/*!--------------------------------------------------------
 * Copyright (C) Microsoft Corporation. All rights reserved.
 *--------------------------------------------------------*//******************************************************************************
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/base/browser/window.js
function $X(targetWindow, fallbackWindowId) {
  const codeWindow = targetWindow;
  if (typeof codeWindow.vscodeWindowId !== "number") {
    Object.defineProperty(codeWindow, "vscodeWindowId", {
      get: () => fallbackWindowId
    });
  }
}
var $Y = window;
function $Z(obj) {
  if (obj === $Y) {
    return false;
  }
  const candidate = obj;
  return typeof candidate?.vscodeWindowId === "number";
}

// 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 key2 = groupFn(element);
    let target = result[key2];
    if (!target) {
      target = result[key2] = [];
    }
    target.push(element);
  }
  return result;
}
function $b(before, after) {
  const removed = [];
  const added = [];
  for (const element of before) {
    if (!after.has(element)) {
      removed.push(element);
    }
  }
  for (const element of after) {
    if (!before.has(element)) {
      added.push(element);
    }
  }
  return { removed, added };
}
function $c(before, after) {
  const removed = [];
  const added = [];
  for (const [index, value] of before) {
    if (!after.has(index)) {
      removed.push(value);
    }
  }
  for (const [index, value] of after) {
    if (!before.has(index)) {
      added.push(value);
    }
  }
  return { removed, added };
}
function $d(setA, setB) {
  const result = /* @__PURE__ */ new Set();
  for (const elem of setB) {
    if (setA.has(elem)) {
      result.add(elem);
    }
  }
  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 key2 = this.b(value);
    this.a.set(key2, 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/errors.js
var $bb = class {
  constructor() {
    this.b = [];
    this.a = function(e) {
      setTimeout(() => {
        if (e.stack) {
          if ($ub.isErrorNoTelemetry(e)) {
            throw new $ub(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 $cb = new $bb();
function setUnexpectedErrorHandler(newUnexpectedErrorHandler) {
  $cb.setUnexpectedErrorHandler(newUnexpectedErrorHandler);
}
function $fb(e) {
  $cb.onUnexpectedError(e);
  return void 0;
}
function $gb(e) {
  if (!$kb(e)) {
    $cb.onUnexpectedError(e);
  }
  return void 0;
}
function $hb(e) {
  if (!$kb(e)) {
    $cb.onUnexpectedExternalError(e);
  }
  return void 0;
}
function $ib(error) {
  if (error instanceof Error) {
    const { name, message } = error;
    const stack = error.stacktrace || error.stack;
    return {
      $isError: true,
      name,
      message,
      stack,
      noTelemetry: $ub.isErrorNoTelemetry(error)
    };
  }
  return error;
}
function $jb(data) {
  let error;
  if (data.noTelemetry) {
    error = new $ub();
  } else {
    error = new Error();
    error.name = data.name;
  }
  error.message = data.message;
  error.stack = data.stack;
  return error;
}
var canceledName = "Canceled";
function $kb(error) {
  if (error instanceof $lb) {
    return true;
  }
  return error instanceof Error && error.name === canceledName && error.message === canceledName;
}
var $lb = class extends Error {
  constructor() {
    super(canceledName);
    this.name = this.message;
  }
};
function $mb() {
  const error = new Error(canceledName);
  error.name = error.message;
  return error;
}
function $nb(name) {
  if (name) {
    return new Error(`Illegal argument: ${name}`);
  } else {
    return new Error("Illegal argument");
  }
}
function $ob(name) {
  if (name) {
    return new Error(`Illegal state: ${name}`);
  } else {
    return new Error("Illegal state");
  }
}
function $qb(err) {
  if (!err) {
    return "Error";
  }
  if (err.message) {
    return err.message;
  }
  if (err.stack) {
    return err.stack.split("\n")[0];
  }
  return String(err);
}
var $sb = class extends Error {
  constructor(message) {
    super("NotSupported");
    if (message) {
      this.message = message;
    }
  }
};
var $ub = class _$ub extends Error {
  constructor(msg) {
    super(msg);
    this.name = "CodeExpectedError";
  }
  static fromError(err) {
    if (err instanceof _$ub) {
      return err;
    }
    const result = new _$ub();
    result.message = err.message;
    result.stack = err.stack;
    return result;
  }
  static isErrorNoTelemetry(err) {
    return err.name === "CodeExpectedError";
  }
};
var $vb = class _$vb extends Error {
  constructor(message) {
    super(message || "An unexpected bug occurred.");
    Object.setPrototypeOf(this, _$vb.prototype);
  }
};

// out-build/vs/base/common/functional.js
function $Qc(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/arraysFind.js
function $1(array2, predicate) {
  const idx = $2(array2, predicate);
  if (idx === -1) {
    return void 0;
  }
  return array2[idx];
}
function $2(array2, predicate, fromIndex = array2.length - 1) {
  for (let i2 = fromIndex; i2 >= 0; i2--) {
    const element = array2[i2];
    if (predicate(element)) {
      return i2;
    }
  }
  return -1;
}
function $3(array2, predicate) {
  const idx = $4(array2, predicate);
  return idx === -1 ? void 0 : array2[idx];
}
function $4(array2, predicate, startIdx = 0, endIdxEx = array2.length) {
  let i2 = startIdx;
  let j = endIdxEx;
  while (i2 < j) {
    const k = Math.floor((i2 + j) / 2);
    if (predicate(array2[k])) {
      i2 = k + 1;
    } else {
      j = k;
    }
  }
  return i2 - 1;
}
function $5(array2, predicate) {
  const idx = $6(array2, predicate);
  return idx === array2.length ? void 0 : array2[idx];
}
function $6(array2, predicate, startIdx = 0, endIdxEx = array2.length) {
  let i2 = startIdx;
  let j = endIdxEx;
  while (i2 < j) {
    const k = Math.floor((i2 + j) / 2);
    if (predicate(array2[k])) {
      j = k;
    } else {
      i2 = k + 1;
    }
  }
  return i2;
}
var $8 = class _$8 {
  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 (_$8.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 = $4(this.e, predicate, this.c);
    this.c = idx + 1;
    return idx === -1 ? void 0 : this.e[idx];
  }
};
function $9(array2, comparator) {
  if (array2.length === 0) {
    return void 0;
  }
  let max = array2[0];
  for (let i2 = 1; i2 < array2.length; i2++) {
    const item = array2[i2];
    if (comparator(item, max) > 0) {
      max = item;
    }
  }
  return max;
}
function $0(array2, comparator) {
  if (array2.length === 0) {
    return void 0;
  }
  let max = array2[0];
  for (let i2 = 1; i2 < array2.length; i2++) {
    const item = array2[i2];
    if (comparator(item, max) >= 0) {
      max = item;
    }
  }
  return max;
}
function $$(array2, comparator) {
  return $9(array2, (a, b) => -comparator(a, b));
}
function $_(array2, comparator) {
  if (array2.length === 0) {
    return -1;
  }
  let maxIdx = 0;
  for (let i2 = 1; i2 < array2.length; i2++) {
    const item = array2[i2];
    if (comparator(item, array2[maxIdx]) > 0) {
      maxIdx = i2;
    }
  }
  return maxIdx;
}
function $ab(items, mapFn) {
  for (const value of items) {
    const mapped = mapFn(value);
    if (mapped !== void 0) {
      return mapped;
    }
  }
  return void 0;
}

// out-build/vs/base/common/arrays.js
function $yb(arr) {
  if (arr.length === 0) {
    throw new Error("Invalid tail call");
  }
  return [arr.slice(0, arr.length - 1), arr[arr.length - 1]];
}
function $zb(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 i2 = 0, len = one.length; i2 < len; i2++) {
    if (!itemEquals(one[i2], other[i2])) {
      return false;
    }
  }
  return true;
}
function $Ab(array2, index) {
  const last = array2.length - 1;
  if (index < last) {
    array2[index] = array2[last];
  }
  array2.pop();
}
function $Bb(array2, key2, comparator) {
  return $Cb(array2.length, (i2) => comparator(array2[i2], key2));
}
function $Cb(length, compareToKey) {
  let low = 0, high = length - 1;
  while (low <= high) {
    const mid = (low + high) / 2 | 0;
    const comp = compareToKey(mid);
    if (comp < 0) {
      low = mid + 1;
    } else if (comp > 0) {
      high = mid - 1;
    } else {
      return mid;
    }
  }
  return -(low + 1);
}
function $Db(nth, data, compare8) {
  nth = nth | 0;
  if (nth >= data.length) {
    throw new TypeError("invalid index");
  }
  const pivotValue = data[Math.floor(data.length * Math.random())];
  const lower = [];
  const higher = [];
  const pivots = [];
  for (const value of data) {
    const val = compare8(value, pivotValue);
    if (val < 0) {
      lower.push(value);
    } else if (val > 0) {
      higher.push(value);
    } else {
      pivots.push(value);
    }
  }
  if (nth < lower.length) {
    return $Db(nth, lower, compare8);
  } else if (nth < lower.length + pivots.length) {
    return pivots[0];
  } else {
    return $Db(nth - (lower.length + pivots.length), higher, compare8);
  }
}
function $Eb(data, compare8) {
  const result = [];
  let currentGroup = void 0;
  for (const element of data.slice(0).sort(compare8)) {
    if (!currentGroup || compare8(currentGroup[0], element) !== 0) {
      currentGroup = [element];
      result.push(currentGroup);
    } else {
      currentGroup.push(element);
    }
  }
  return result;
}
function* $Fb(items, shouldBeGrouped) {
  let currentGroup;
  let last;
  for (const item of items) {
    if (last !== void 0 && shouldBeGrouped(last, item)) {
      currentGroup.push(item);
    } else {
      if (currentGroup) {
        yield currentGroup;
      }
      currentGroup = [item];
    }
    last = item;
  }
  if (currentGroup) {
    yield currentGroup;
  }
}
function $Gb(arr, f) {
  for (let i2 = 0; i2 <= arr.length; i2++) {
    f(i2 === 0 ? void 0 : arr[i2 - 1], i2 === arr.length ? void 0 : arr[i2]);
  }
}
function $Hb(arr, f) {
  for (let i2 = 0; i2 < arr.length; i2++) {
    f(i2 === 0 ? void 0 : arr[i2 - 1], arr[i2], i2 + 1 === arr.length ? void 0 : arr[i2 + 1]);
  }
}
function $Ib(before, after, compare8) {
  const result = [];
  function pushSplice(start, deleteCount, toInsert) {
    if (deleteCount === 0 && toInsert.length === 0) {
      return;
    }
    const latest = result[result.length - 1];
    if (latest && latest.start + latest.deleteCount === start) {
      latest.deleteCount += deleteCount;
      latest.toInsert.push(...toInsert);
    } else {
      result.push({ start, deleteCount, toInsert });
    }
  }
  let beforeIdx = 0;
  let afterIdx = 0;
  while (true) {
    if (beforeIdx === before.length) {
      pushSplice(beforeIdx, 0, after.slice(afterIdx));
      break;
    }
    if (afterIdx === after.length) {
      pushSplice(beforeIdx, before.length - beforeIdx, []);
      break;
    }
    const beforeElement = before[beforeIdx];
    const afterElement = after[afterIdx];
    const n = compare8(beforeElement, afterElement);
    if (n === 0) {
      beforeIdx += 1;
      afterIdx += 1;
    } else if (n < 0) {
      pushSplice(beforeIdx, 1, []);
      beforeIdx += 1;
    } else if (n > 0) {
      pushSplice(beforeIdx, 0, [afterElement]);
      afterIdx += 1;
    }
  }
  return result;
}
function $Jb(before, after, compare8) {
  const splices = $Ib(before, after, compare8);
  const removed = [];
  const added = [];
  for (const splice2 of splices) {
    removed.push(...before.slice(splice2.start, splice2.start + splice2.deleteCount));
    added.push(...splice2.toInsert);
  }
  return { removed, added };
}
function top(array2, compare8, n) {
  if (n === 0) {
    return [];
  }
  const result = array2.slice(0, n).sort(compare8);
  topStep(array2, compare8, result, n, array2.length);
  return result;
}
function topStep(array2, compare8, result, i2, m) {
  for (const n = result.length; i2 < m; i2++) {
    const element = array2[i2];
    if (compare8(element, result[n - 1]) < 0) {
      result.pop();
      const j = $6(result, (e) => compare8(element, e) < 0);
      result.splice(j, 0, element);
    }
  }
}
function $Mb(array2) {
  return array2.filter((e) => !!e);
}
function $Nb(array2) {
  let to = 0;
  for (let i2 = 0; i2 < array2.length; i2++) {
    if (!!array2[i2]) {
      array2[to] = array2[i2];
      to += 1;
    }
  }
  array2.length = to;
}
function $Ob(array2, from, to) {
  array2.splice(to, 0, array2.splice(from, 1)[0]);
}
function $Pb(obj) {
  return !Array.isArray(obj) || obj.length === 0;
}
function $Qb(obj) {
  return Array.isArray(obj) && obj.length > 0;
}
function $Rb(array2, keyFn = (value) => value) {
  const seen = /* @__PURE__ */ new Set();
  return array2.filter((element) => {
    const key2 = keyFn(element);
    if (seen.has(key2)) {
      return false;
    }
    seen.add(key2);
    return true;
  });
}
function $Sb(keyFn) {
  const seen = /* @__PURE__ */ new Set();
  return (element) => {
    const key2 = keyFn(element);
    if (seen.has(key2)) {
      return false;
    }
    seen.add(key2);
    return true;
  };
}
function $Tb(one, other, equals = (a, b) => a === b) {
  let result = 0;
  for (let i2 = 0, len = Math.min(one.length, other.length); i2 < len && equals(one[i2], other[i2]); i2++) {
    result++;
  }
  return result;
}
function $Ub(arg, to) {
  let from = typeof to === "number" ? arg : 0;
  if (typeof to === "number") {
    from = arg;
  } else {
    from = 0;
    to = arg;
  }
  const result = [];
  if (from <= to) {
    for (let i2 = from; i2 < to; i2++) {
      result.push(i2);
    }
  } else {
    for (let i2 = from; i2 > to; i2--) {
      result.push(i2);
    }
  }
  return result;
}
function $Vb(array2, indexer, mapper) {
  return array2.reduce((r2, t) => {
    r2[indexer(t)] = mapper ? mapper(t) : t;
    return r2;
  }, /* @__PURE__ */ Object.create(null));
}
function $Wb(array2, element) {
  array2.push(element);
  return () => $Xb(array2, element);
}
function $Xb(array2, element) {
  const index = array2.indexOf(element);
  if (index > -1) {
    array2.splice(index, 1);
    return element;
  }
  return void 0;
}
function $Yb(target, insertIndex, insertArr) {
  const before = target.slice(0, insertIndex);
  const after = target.slice(insertIndex);
  return before.concat(insertArr, after);
}
function $Zb(array2, _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 i2 = array2.length - 1; i2 > 0; i2 -= 1) {
    const j = Math.floor(rand() * (i2 + 1));
    const temp = array2[i2];
    array2[i2] = array2[j];
    array2[j] = temp;
  }
}
function $1b(arr, value) {
  const index = arr.indexOf(value);
  if (index > -1) {
    arr.splice(index, 1);
    arr.unshift(value);
  }
}
function $2b(arr, value) {
  const index = arr.indexOf(value);
  if (index > -1) {
    arr.splice(index, 1);
    arr.push(value);
  }
}
function $3b(arr, items) {
  for (const item of items) {
    arr.push(item);
  }
}
function $4b(items, fn) {
  return Array.isArray(items) ? items.map(fn) : fn(items);
}
function $5b(x) {
  return Array.isArray(x) ? x : [x];
}
function $7b(array2, start, newItems) {
  const startIdx = getActualStartIndex(array2, start);
  const originalLength = array2.length;
  const newItemsLength = newItems.length;
  array2.length = originalLength + newItemsLength;
  for (let i2 = originalLength - 1; i2 >= startIdx; i2--) {
    array2[i2 + newItemsLength] = array2[i2];
  }
  for (let i2 = 0; i2 < newItemsLength; i2++) {
    array2[i2 + startIdx] = newItems[i2];
  }
}
function $8b(array2, start, deleteCount, newItems) {
  const index = getActualStartIndex(array2, start);
  let result = array2.splice(index, deleteCount);
  if (result === void 0) {
    result = [];
  }
  $7b(array2, index, newItems);
  return result;
}
function getActualStartIndex(array2, start) {
  return start < 0 ? Math.max(start + array2.length, 0) : Math.min(start, array2.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 $9b(selector, comparator) {
  return (a, b) => comparator(selector(a), selector(b));
}
function $0b(...comparators) {
  return (item1, item2) => {
    for (const comparator of comparators) {
      const result = comparator(item1, item2);
      if (!CompareResult.isNeitherLessOrGreaterThan(result)) {
        return result;
      }
    }
    return CompareResult.neitherLessOrGreaterThan;
  };
}
var $$b = (a, b) => a - b;
var $_b = (a, b) => $$b(a ? 1 : 0, b ? 1 : 0);
function $ac(comparator) {
  return (a, b) => -comparator(a, b);
}
var $bc = class {
  /**
   * Constructs a queue that is backed by the given array. Runtime is O(1).
  */
  constructor(g) {
    this.g = g;
    this.c = 0;
    this.d = this.g.length - 1;
  }
  get length() {
    return this.d - this.c + 1;
  }
  /**
   * Consumes elements from the beginning of the queue as long as the predicate returns true.
   * If no elements were consumed, `null` is returned. Has a runtime of O(result.length).
  */
  takeWhile(predicate) {
    let startIdx = this.c;
    while (startIdx < this.g.length && predicate(this.g[startIdx])) {
      startIdx++;
    }
    const result = startIdx === this.c ? null : this.g.slice(this.c, startIdx);
    this.c = startIdx;
    return result;
  }
  /**
   * Consumes elements from the end of the queue as long as the predicate returns true.
   * If no elements were consumed, `null` is returned.
   * The result has the same order as the underlying array!
  */
  takeFromEndWhile(predicate) {
    let endIdx = this.d;
    while (endIdx >= 0 && predicate(this.g[endIdx])) {
      endIdx--;
    }
    const result = endIdx === this.d ? null : this.g.slice(endIdx + 1, this.d + 1);
    this.d = endIdx;
    return result;
  }
  peek() {
    if (this.length === 0) {
      return void 0;
    }
    return this.g[this.c];
  }
  peekLast() {
    if (this.length === 0) {
      return void 0;
    }
    return this.g[this.d];
  }
  dequeue() {
    const result = this.g[this.c];
    this.c++;
    return result;
  }
  removeLast() {
    const result = this.g[this.d];
    this.d--;
    return result;
  }
  takeCount(count) {
    const result = this.g.slice(this.c, this.c + count);
    this.c += count;
    return result;
  }
};
var $cc = class _$cc {
  static {
    this.empty = new _$cc((_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 _$cc((cb) => this.iterate((item) => predicate(item) ? cb(item) : true));
  }
  map(mapFn) {
    return new _$cc((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;
  }
};
var $dc = class _$dc {
  constructor(c) {
    this.c = c;
  }
  /**
   * Returns a permutation that sorts the given array according to the given compare function.
   */
  static createSortPermutation(arr, compareFn) {
    const sortIndices = Array.from(arr.keys()).sort((index1, index2) => compareFn(arr[index1], arr[index2]));
    return new _$dc(sortIndices);
  }
  /**
   * Returns a new array with the elements of the given array re-arranged according to this permutation.
   */
  apply(arr) {
    return arr.map((_, index) => arr[this.c[index]]);
  }
  /**
   * Returns a new permutation that undoes the re-arrangement of this permutation.
  */
  inverse() {
    const inverseIndexMap = this.c.slice();
    for (let i2 = 0; i2 < this.c.length; i2++) {
      inverseIndexMap[this.c[i2]] = i2;
    }
    return new _$dc(inverseIndexMap);
  }
};
async function $ec(array2, predicate) {
  const results = await Promise.all(array2.map(async (element, index) => ({ element, ok: await predicate(element, index) })));
  return results.find((r2) => r2.ok)?.element;
}

// out-build/vs/base/common/map.js
var _a2;
var _b;
var _c;
function $Bc(map, key2, value) {
  let result = map.get(key2);
  if (result === void 0) {
    result = value;
    map.set(key2, result);
  }
  return result;
}
var ResourceMapEntry = class {
  constructor(uri, value) {
    this.uri = uri;
    this.value = value;
  }
};
function isEntries(arg) {
  return Array.isArray(arg);
}
var $Ec = class _$Ec {
  static {
    this.c = (resource) => resource.toString();
  }
  constructor(arg, toKey2) {
    this[_a2] = "ResourceMap";
    if (arg instanceof _$Ec) {
      this.d = new Map(arg.d);
      this.e = toKey2 ?? _$Ec.c;
    } else if (isEntries(arg)) {
      this.d = /* @__PURE__ */ new Map();
      this.e = toKey2 ?? _$Ec.c;
      for (const [resource, value] of arg) {
        this.set(resource, value);
      }
    } else {
      this.d = /* @__PURE__ */ new Map();
      this.e = arg ?? _$Ec.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 $Fc = class {
  constructor(entriesOrKey, toKey2) {
    this[_b] = "ResourceSet";
    if (!entriesOrKey || typeof entriesOrKey === "function") {
      this.c = new $Ec(entriesOrKey);
    } else {
      this.c = new $Ec(toKey2);
      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, key2) => callbackfn.call(thisArg, key2, key2, 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 $Gc = 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(key2) {
    return this.c.has(key2);
  }
  get(key2, touch = 0) {
    const item = this.c.get(key2);
    if (!item) {
      return void 0;
    }
    if (touch !== 0) {
      this.m(item, touch);
    }
    return item.value;
  }
  set(key2, value, touch = 0) {
    let item = this.c.get(key2);
    if (item) {
      item.value = value;
      if (touch !== 0) {
        this.m(item, touch);
      }
    } else {
      item = { key: key2, 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(key2, item);
      this.f++;
    }
    return this;
  }
  delete(key2) {
    return !!this.remove(key2);
  }
  remove(key2) {
    const item = this.c.get(key2);
    if (!item) {
      return void 0;
    }
    this.c.delete(key2);
    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, key2) => {
      data.push([key2, value]);
    });
    return data;
  }
  fromJSON(data) {
    this.clear();
    for (const [key2, value] of data) {
      this.set(key2, value);
    }
  }
};
var Cache = class extends $Gc {
  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(key2, touch = 2) {
    return super.get(key2, touch);
  }
  peek(key2) {
    return super.get(
      key2,
      0
      /* Touch.None */
    );
  }
  set(key2, value) {
    super.set(
      key2,
      value,
      2
      /* Touch.AsNew */
    );
    return this;
  }
  p() {
    if (this.size > this.n) {
      this.q(Math.round(this.n * this.o));
    }
  }
};
var $Hc = class extends Cache {
  constructor(limit, ratio = 1) {
    super(limit, ratio);
  }
  q(newSize) {
    this.h(newSize);
  }
  set(key2, value) {
    super.set(key2, value);
    this.p();
    return this;
  }
};
var $Ic = class extends Cache {
  constructor(limit, ratio = 1) {
    super(limit, ratio);
  }
  q(newSize) {
    this.i(newSize);
  }
  set(key2, value) {
    if (this.n <= this.size && !this.has(key2)) {
      this.q(Math.round(this.n * this.o) - 1);
    }
    super.set(key2, value);
    return this;
  }
};
var $Jc = class {
  constructor() {
    this.c = /* @__PURE__ */ new Map();
  }
  add(value) {
    this.c.set(value, (this.c.get(value) || 0) + 1);
    return this;
  }
  delete(value) {
    let counter = this.c.get(value) || 0;
    if (counter === 0) {
      return false;
    }
    counter--;
    if (counter === 0) {
      this.c.delete(value);
    } else {
      this.c.set(value, counter);
    }
    return true;
  }
  has(value) {
    return this.c.has(value);
  }
};
var $Kc = class {
  constructor(entries2) {
    this.c = /* @__PURE__ */ new Map();
    this.d = /* @__PURE__ */ new Map();
    if (entries2) {
      for (const [key2, value] of entries2) {
        this.set(key2, value);
      }
    }
  }
  clear() {
    this.c.clear();
    this.d.clear();
  }
  set(key2, value) {
    this.c.set(key2, value);
    this.d.set(value, key2);
  }
  get(key2) {
    return this.c.get(key2);
  }
  getKey(value) {
    return this.d.get(value);
  }
  delete(key2) {
    const value = this.c.get(key2);
    if (value === void 0) {
      return false;
    }
    this.c.delete(key2);
    this.d.delete(value);
    return true;
  }
  forEach(callbackfn, thisArg) {
    this.c.forEach((value, key2) => {
      callbackfn.call(thisArg, value, key2, this);
    });
  }
  keys() {
    return this.c.keys();
  }
  values() {
    return this.c.values();
  }
};
var $Lc = class {
  constructor() {
    this.c = /* @__PURE__ */ new Map();
  }
  add(key2, value) {
    let values = this.c.get(key2);
    if (!values) {
      values = /* @__PURE__ */ new Set();
      this.c.set(key2, values);
    }
    values.add(value);
  }
  delete(key2, value) {
    const values = this.c.get(key2);
    if (!values) {
      return;
    }
    values.delete(value);
    if (values.size === 0) {
      this.c.delete(key2);
    }
  }
  forEach(key2, fn) {
    const values = this.c.get(key2);
    if (!values) {
      return;
    }
    values.forEach(fn);
  }
  get(key2) {
    const values = this.c.get(key2);
    if (!values) {
      return /* @__PURE__ */ new Set();
    }
    return values;
  }
};
function $Mc(a, b) {
  if (a === b) {
    return true;
  }
  if (a.size !== b.size) {
    return false;
  }
  for (const [key2, value] of a) {
    if (!b.has(key2) || b.get(key2) !== value) {
      return false;
    }
  }
  for (const [key2] of b) {
    if (!a.has(key2)) {
      return false;
    }
  }
  return true;
}
var $Nc = class {
  constructor() {
    this.c = {};
  }
  set(first, second, value) {
    if (!this.c[first]) {
      this.c[first] = {};
    }
    this.c[first][second] = value;
  }
  get(first, second) {
    return this.c[first]?.[second];
  }
  clear() {
    this.c = {};
  }
  *values() {
    for (const first in this.c) {
      for (const second in this.c[first]) {
        const value = this.c[first][second];
        if (value) {
          yield value;
        }
      }
    }
  }
};
var $Pc = class {
  constructor() {
    this.c = new $Nc();
  }
  set(first, second, third, fourth, value) {
    if (!this.c.get(first, second)) {
      this.c.set(first, second, new $Nc());
    }
    this.c.get(first, second).set(third, fourth, value);
  }
  get(first, second, third, fourth) {
    return this.c.get(first, second)?.get(third, fourth);
  }
  clear() {
    this.c.clear();
  }
};

// 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(array2) {
    for (let i2 = array2.length - 1; i2 >= 0; i2--) {
      yield array2[i2];
    }
  }
  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 i2 = 0;
    for (const element of iterable) {
      if (predicate(element, i2++)) {
        return true;
      }
    }
    return false;
  }
  Iterable2.some = some;
  function find2(iterable, predicate) {
    for (const element of iterable) {
      if (predicate(element)) {
        return element;
      }
    }
    return void 0;
  }
  Iterable2.find = find2;
  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* concat3(...iterables) {
    for (const iterable of iterables) {
      yield* iterable;
    }
  }
  Iterable2.concat = concat3;
  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 < -arr.length) {
      from2 = 0;
    }
    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 i2 = 0; i2 < atMost; i2++) {
      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 $Rc = class _$Rc {
  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: _$Rc.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(array2, linesToRemove) {
        while (array2.length > 0 && linesToRemove.some((regexp) => typeof regexp === "string" ? regexp === array2[0] : array2[0].match(regexp))) {
          array2.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 $Lc();
    for (const leaking of uncoveredLeakingObjs) {
      const stackTracePath = getStackTracePath(leaking);
      for (let i3 = 0; i3 <= stackTracePath.length; i3++) {
        stackTraceStarts.add(stackTracePath.slice(0, i3).join("\n"), leaking);
      }
    }
    uncoveredLeakingObjs.sort($9b((l) => l.idx, $$b));
    let message = "";
    let i2 = 0;
    for (const leaking of uncoveredLeakingObjs.slice(0, maxReported)) {
      i2++;
      const stackTracePath = getStackTracePath(leaking);
      const stackTraceFormattedLines = [];
      for (let i3 = 0; i3 < stackTracePath.length; i3++) {
        let line = stackTracePath[i3];
        const starts = stackTraceStarts.get(stackTracePath.slice(0, i3 + 1).join("\n"));
        line = `(shared with ${starts.size}/${uncoveredLeakingObjs.length} leaks) at ${line}`;
        const prevStarts = stackTraceStarts.get(stackTracePath.slice(0, i3).join("\n"));
        const continuations = $a([...prevStarts].map((d) => getStackTracePath(d)[i3]), (v) => v);
        delete continuations[stackTracePath[i3]];
        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 ${i2}/${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 $Sc(tracker2) {
  disposableTracker = tracker2;
}
if (TRACK_DISPOSABLES) {
  const __is_disposable_tracked__ = "__is_disposable_tracked__";
  $Sc(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 !== $3c.None) {
        try {
          child[__is_disposable_tracked__] = true;
        } catch {
        }
      }
    }
    markAsDisposed(disposable) {
      if (disposable && disposable !== $3c.None) {
        try {
          disposable[__is_disposable_tracked__] = true;
        } catch {
        }
      }
    }
    markAsSingleton(disposable) {
    }
  }());
}
function $Tc(x) {
  disposableTracker?.trackDisposable(x);
  return x;
}
function $Uc(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 $Vc(singleton) {
  disposableTracker?.markAsSingleton(singleton);
  return singleton;
}
function $Wc(thing) {
  return typeof thing === "object" && thing !== null && typeof thing.dispose === "function" && thing.dispose.length === 0;
}
function $Xc(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 $Yc(disposables) {
  for (const d of disposables) {
    if ($Wc(d)) {
      d.dispose();
    }
  }
  return [];
}
function $Zc(...disposables) {
  const parent = $1c(() => $Xc(disposables));
  setParentOfDisposables(disposables, parent);
  return parent;
}
function $1c(fn) {
  const self2 = $Tc({
    dispose: $Qc(() => {
      $Uc(self2);
      fn();
    })
  });
  return self2;
}
var $2c = class _$2c {
  static {
    this.DISABLE_DISPOSED_WARNING = false;
  }
  constructor() {
    this.f = /* @__PURE__ */ new Set();
    this.g = false;
    $Tc(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;
    }
    $Uc(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 {
      $Xc(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 (!_$2c.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 $3c = class {
  static {
    this.None = Object.freeze({ dispose() {
    } });
  }
  constructor() {
    this.q = new $2c();
    $Tc(this);
    setParentOfDisposable(this.q, this);
  }
  dispose() {
    $Uc(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 $4c = class {
  constructor() {
    this.b = false;
    $Tc(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;
    $Uc(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 $5c = class {
  constructor(initialValue) {
    this.a = new $4c();
    this.b = false;
    this.a.value = initialValue;
  }
  get value() {
    return this.a.value;
  }
  set value(value) {
    if (this.b || value === this.a.value) {
      return;
    }
    this.a.value = value;
  }
  dispose() {
    this.b = true;
    this.a.dispose();
  }
};
var $6c = class {
  constructor(b) {
    this.b = b;
    this.a = 1;
  }
  acquire() {
    this.a++;
    return this;
  }
  release() {
    if (--this.a === 0) {
      this.b.dispose();
    }
    return this;
  }
};
var $8c = class {
  constructor() {
    this.a = /* @__PURE__ */ new Map();
  }
  acquire(key2, ...args2) {
    let reference = this.a.get(key2);
    if (!reference) {
      reference = { counter: 0, object: this.b(key2, ...args2) };
      this.a.set(key2, reference);
    }
    const { object } = reference;
    const dispose = $Qc(() => {
      if (--reference.counter === 0) {
        this.c(key2, reference.object);
        this.a.delete(key2);
      }
    });
    reference.counter++;
    return { object, dispose };
  }
};
var $9c = class {
  constructor(a) {
    this.a = a;
  }
  async acquire(key2, ...args2) {
    const ref = this.a.acquire(key2, ...args2);
    try {
      const object = await ref.object;
      return {
        object,
        dispose: () => ref.dispose()
      };
    } catch (error) {
      ref.dispose();
      throw error;
    }
  }
};
var $0c = class {
  constructor(object) {
    this.object = object;
  }
  dispose() {
  }
};
var $_c = class {
  constructor() {
    this.a = /* @__PURE__ */ new Map();
    this.b = false;
    $Tc(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() {
    $Uc(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 {
      $Xc(this.a.values());
    } finally {
      this.a.clear();
    }
  }
  has(key2) {
    return this.a.has(key2);
  }
  get size() {
    return this.a.size;
  }
  get(key2) {
    return this.a.get(key2);
  }
  set(key2, 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(key2)?.dispose();
    }
    this.a.set(key2, value);
  }
  /**
   * Delete the value stored for `key` from this map and also dispose of it.
   */
  deleteAndDispose(key2) {
    this.a.get(key2)?.dispose();
    this.a.delete(key2);
  }
  /**
   * Delete the value stored for `key` from this map but return it. The caller is
   * responsible for disposing of the value.
   */
  deleteAndLeak(key2) {
    const value = this.a.get(key2);
    this.a.delete(key2);
    return value;
  }
  keys() {
    return this.a.keys();
  }
  values() {
    return this.a.values();
  }
  [Symbol.iterator]() {
    return this.a[Symbol.iterator]();
  }
};

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

// out-build/vs/base/common/stopwatch.js
var hasPerformanceNow = globalThis.performance && typeof globalThis.performance.now === "function";
var $te = class _$te {
  static create(highResolution) {
    return new _$te(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 Event2;
(function(Event3) {
  Event3.None = () => $3c.None;
  function _addLeakageTraceLogic(options3) {
    if (_enableSnapshotPotentialLeakWarning) {
      const { onDidAddListener: origListenerDidAdd } = options3;
      const stack = Stacktrace.create();
      let count = 0;
      options3.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);
  }
  Event3.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;
    };
  }
  Event3.once = once;
  function onceIf(event, condition) {
    return Event3.once(Event3.filter(event, condition));
  }
  Event3.onceIf = onceIf;
  function map(event, map2, disposable) {
    return snapshot((listener, thisArgs = null, disposables) => event((i2) => listener.call(thisArgs, map2(i2)), null, disposables), disposable);
  }
  Event3.map = map;
  function forEach(event, each, disposable) {
    return snapshot((listener, thisArgs = null, disposables) => event((i2) => {
      each(i2);
      listener.call(thisArgs, i2);
    }, null, disposables), disposable);
  }
  Event3.forEach = forEach;
  function filter(event, filter2, disposable) {
    return snapshot((listener, thisArgs = null, disposables) => event((e) => filter2(e) && listener.call(thisArgs, e), null, disposables), disposable);
  }
  Event3.filter = filter;
  function signal(event) {
    return event;
  }
  Event3.signal = signal;
  function any(...events) {
    return (listener, thisArgs = null, disposables) => {
      const disposable = $Zc(...events.map((event) => event((e) => listener.call(thisArgs, e))));
      return addAndReturnDisposable(disposable, disposables);
    };
  }
  Event3.any = any;
  function reduce(event, merge2, initial, disposable) {
    let output = initial;
    return map(event, (e) => {
      output = merge2(output, e);
      return output;
    }, disposable);
  }
  Event3.reduce = reduce;
  function snapshot(event, disposable) {
    let listener;
    const options3 = {
      onWillAddFirstListener() {
        listener = event(emitter.fire, emitter);
      },
      onDidRemoveLastListener() {
        listener?.dispose();
      }
    };
    if (!disposable) {
      _addLeakageTraceLogic(options3);
    }
    const emitter = new $ze(options3);
    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 options3 = {
      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(options3);
    }
    const emitter = new $ze(options3);
    disposable?.add(emitter);
    return emitter.event;
  }
  Event3.debounce = debounce;
  function accumulate(event, delay = 0, disposable) {
    return Event3.debounce(event, (last, e) => {
      if (!last) {
        return [e];
      }
      last.push(e);
      return last;
    }, delay, void 0, true, void 0, disposable);
  }
  Event3.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);
  }
  Event3.latch = latch;
  function split(event, isT, disposable) {
    return [
      Event3.filter(event, isT, disposable),
      Event3.filter(event, (e) => !isT(e), disposable)
    ];
  }
  Event3.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 $ze({
      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;
  }
  Event3.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;
  }
  Event3.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 = (...args2) => result.fire(map2(...args2));
    const onFirstListenerAdd = () => emitter.on(eventName, fn);
    const onLastListenerRemove = () => emitter.removeListener(eventName, fn);
    const result = new $ze({ onWillAddFirstListener: onFirstListenerAdd, onDidRemoveLastListener: onLastListenerRemove });
    return result.event;
  }
  Event3.fromNodeEventEmitter = fromNodeEventEmitter;
  function fromDOMEventEmitter(emitter, eventName, map2 = (id2) => id2) {
    const fn = (...args2) => result.fire(map2(...args2));
    const onFirstListenerAdd = () => emitter.addEventListener(eventName, fn);
    const onLastListenerRemove = () => emitter.removeEventListener(eventName, fn);
    const result = new $ze({ onWillAddFirstListener: onFirstListenerAdd, onDidRemoveLastListener: onLastListenerRemove });
    return result.event;
  }
  Event3.fromDOMEventEmitter = fromDOMEventEmitter;
  function toPromise(event) {
    return new Promise((resolve) => once(event)(resolve));
  }
  Event3.toPromise = toPromise;
  function fromPromise(promise) {
    const result = new $ze();
    promise.then((res) => {
      result.fire(res);
    }, () => {
      result.fire(void 0);
    }).finally(() => {
      result.dispose();
    });
    return result.event;
  }
  Event3.fromPromise = fromPromise;
  function forward(from, to) {
    return from((e) => to.fire(e));
  }
  Event3.forward = forward;
  function runAndSubscribe(event, handler, initial) {
    handler(initial);
    return event((e) => handler(e));
  }
  Event3.runAndSubscribe = runAndSubscribe;
  class EmitterObserver {
    constructor(_observable, store) {
      this._observable = _observable;
      this.f = 0;
      this.g = false;
      const options3 = {
        onWillAddFirstListener: () => {
          _observable.addObserver(this);
          this._observable.reportChanges();
        },
        onDidRemoveLastListener: () => {
          _observable.removeObserver(this);
        }
      };
      if (!store) {
        _addLeakageTraceLogic(options3);
      }
      this.emitter = new $ze(options3);
      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;
  }
  Event3.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 $2c) {
        disposables.add(disposable);
      } else if (Array.isArray(disposables)) {
        disposables.push(disposable);
      }
      return disposable;
    };
  }
  Event3.fromObservableLight = fromObservableLight;
})(Event2 || (Event2 = {}));
var $ve = class _$ve {
  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}_${_$ve.f++}`;
    _$ve.all.add(this);
  }
  start(listenerCount) {
    this.g = new $te();
    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;
function $we(n) {
  const oldValue = _globalLeakWarningThreshold;
  _globalLeakWarningThreshold = n;
  return {
    dispose() {
      _globalLeakWarningThreshold = oldValue;
    }
  };
}
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 $xe(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 $xe = class extends Error {
  constructor(message, stack) {
    super(message);
    this.name = "ListenerLeakError";
    this.stack = stack;
  }
};
var $ye = 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 i2 = 0; i2 < listeners.length; i2++) {
      const l = listeners[i2];
      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 $ze = class {
  constructor(options3) {
    this.z = 0;
    this.f = options3;
    this.g = _globalLeakWarningThreshold > 0 || this.f?.leakWarningThreshold ? new LeakageMonitor(options3?.onListenerError ?? $gb, this.f?.leakWarningThreshold ?? _globalLeakWarningThreshold) : void 0;
    this.j = this.f?._profName ? new $ve(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 $ye(`${message}. HINT: Stack shows most frequent listener (${tuple[1]}-times)`, tuple[0]);
        const errorHandler = this.f?.onListenerError || $gb;
        errorHandler(error);
        return $3c.None;
      }
      if (this.m) {
        return $3c.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.f?.onDidAddListener?.(this);
      this.z++;
      const result = $1c(() => {
        _listenerFinalizers?.unregister(result);
        removeMonitor?.();
        this.A(contained);
      });
      if (disposables instanceof $2c) {
        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 i2 = 0; i2 < listeners.length; i2++) {
        if (listeners[i2]) {
          listeners[n++] = listeners[i2];
        } else if (adjustDeliveryQueue && n < this.w.end) {
          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 || $gb;
    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 $Ae = () => new EventDeliveryQueuePrivate();
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 $Be = class extends $ze {
  async fireAsync(data, token, promiseJoin) {
    if (!this.u) {
      return;
    }
    if (!this.h) {
      this.h = new $cd();
    }
    forEachListener(this.u, (listener) => this.h.push([listener.value, data]));
    while (this.h.size > 0 && !token.isCancellationRequested) {
      const [listener, data2] = this.h.shift();
      const thenables = [];
      const event = {
        ...data2,
        token,
        waitUntil: (p) => {
          if (Object.isFrozen(thenables)) {
            throw new Error("waitUntil can NOT be called asynchronous");
          }
          if (promiseJoin) {
            p = promiseJoin(p, listener);
          }
          thenables.push(p);
        }
      };
      try {
        listener(event);
      } catch (e) {
        $gb(e);
        continue;
      }
      Object.freeze(thenables);
      await Promise.allSettled(thenables).then((values) => {
        for (const value of values) {
          if (value.status === "rejected") {
            $gb(value.reason);
          }
        }
      });
    }
  }
};
var $Ce = class extends $ze {
  get isPaused() {
    return this.h !== 0;
  }
  constructor(options3) {
    super(options3);
    this.h = 0;
    this.s = new $cd();
    this.t = options3?.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 $De = class extends $Ce {
  constructor(options3) {
    super(options3);
    this.k = options3.delay ?? 100;
  }
  fire(event) {
    if (!this.o) {
      this.pause();
      this.o = setTimeout(() => {
        this.o = void 0;
        this.resume();
      }, this.k);
    }
    super.fire(event);
  }
};
var $Ee = class extends $ze {
  constructor(options3) {
    super(options3);
    this.h = [];
    this.k = options3?.merge;
  }
  fire(event) {
    if (!this.hasListeners()) {
      return;
    }
    this.h.push(event);
    if (this.h.length === 1) {
      queueMicrotask(() => {
        if (this.k) {
          super.fire(this.k(this.h));
        } else {
          this.h.forEach((e) => super.fire(e));
        }
        this.h = [];
      });
    }
  }
};
var $Fe = class {
  constructor() {
    this.g = false;
    this.h = [];
    this.f = new $ze({
      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 $1c($Qc(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((r2) => this.f.fire(r2));
  }
  o(e) {
    e.listener?.dispose();
    e.listener = null;
  }
  dispose() {
    this.f.dispose();
    for (const e of this.h) {
      e.listener?.dispose();
    }
    this.h = [];
  }
};
var $Ge = class {
  constructor(items, onAddItem, onRemoveItem, getEvent) {
    this.f = new $2c();
    const multiplexer = this.f.add(new $Fe());
    const itemListeners = this.f.add(new $_c());
    function addItem(instance2) {
      itemListeners.set(instance2, multiplexer.add(getEvent(instance2)));
    }
    for (const instance2 of items) {
      addItem(instance2);
    }
    this.f.add(onAddItem((instance2) => {
      addItem(instance2);
    }));
    this.f.add(onRemoveItem((instance2) => {
      itemListeners.deleteAndDispose(instance2);
    }));
    this.event = multiplexer.event;
  }
  dispose() {
    this.f.dispose();
  }
};
var $He = class {
  constructor() {
    this.f = [];
  }
  wrapEvent(event, reduce, initial) {
    return (listener, thisArgs, disposables) => {
      return event((i2) => {
        const data = this.f[this.f.length - 1];
        if (!reduce) {
          if (data) {
            data.buffers.push(() => listener.call(thisArgs, i2));
          } else {
            listener.call(thisArgs, i2);
          }
          return;
        }
        const reduceData = data;
        if (!reduceData) {
          listener.call(thisArgs, reduce(initial, i2));
          return;
        }
        reduceData.items ??= [];
        reduceData.items.push(i2);
        if (reduceData.buffers.length === 0) {
          data.buffers.push(() => {
            reduceData.reducedResult ??= initial ? reduceData.items.reduce(reduce, initial) : reduceData.items.reduce(reduce);
            listener.call(thisArgs, reduceData.reducedResult);
          });
        }
      }, void 0, disposables);
    };
  }
  bufferEvents(fn) {
    const data = { buffers: new Array() };
    this.f.push(data);
    const r2 = fn();
    this.f.pop();
    data.buffers.forEach((flush) => flush());
    return r2;
  }
};
var $Ie = class {
  constructor() {
    this.f = false;
    this.g = Event2.None;
    this.h = $3c.None;
    this.j = new $ze({
      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();
  }
};
var $Je = class {
  static const(value) {
    return new ConstValueWithChangeEvent(value);
  }
  constructor(g) {
    this.g = g;
    this.f = new $ze();
    this.onDidChange = this.f.event;
  }
  get value() {
    return this.g;
  }
  set value(value) {
    if (value !== this.g) {
      this.g = value;
      this.f.fire(void 0);
    }
  }
};
var ConstValueWithChangeEvent = class {
  constructor(value) {
    this.value = value;
    this.onDidChange = Event2.None;
  }
};
function $Ke(getData, onDidChangeData, handleItem) {
  const map = new $_c();
  let oldData = new Set(getData());
  for (const d of oldData) {
    map.set(d, handleItem(d));
  }
  const store = new $2c();
  store.add(onDidChangeData(() => {
    const newData = getData();
    const diff3 = $b(oldData, newData);
    for (const r2 of diff3.removed) {
      map.deleteAndDispose(r2);
    }
    for (const a of diff3.added) {
      map.set(a, handleItem(a));
    }
    oldData = new Set(newData);
  }));
  store.add(map);
  return store;
}

// out-build/vs/base/browser/browser.js
var WindowManager = class _WindowManager {
  constructor() {
    this.a = /* @__PURE__ */ new Map();
    this.b = new $ze();
    this.onDidChangeZoomLevel = this.b.event;
    this.c = /* @__PURE__ */ new Map();
    this.d = new $ze();
    this.onDidChangeFullscreen = this.d.event;
    this.e = /* @__PURE__ */ new Map();
  }
  static {
    this.INSTANCE = new _WindowManager();
  }
  getZoomLevel(targetWindow) {
    return this.a.get(this.f(targetWindow)) ?? 0;
  }
  setZoomLevel(zoomLevel, targetWindow) {
    if (this.getZoomLevel(targetWindow) === zoomLevel) {
      return;
    }
    const targetWindowId = this.f(targetWindow);
    this.a.set(targetWindowId, zoomLevel);
    this.b.fire(targetWindowId);
  }
  getZoomFactor(targetWindow) {
    return this.c.get(this.f(targetWindow)) ?? 1;
  }
  setZoomFactor(zoomFactor, targetWindow) {
    this.c.set(this.f(targetWindow), zoomFactor);
  }
  setFullscreen(fullscreen, targetWindow) {
    if (this.isFullscreen(targetWindow) === fullscreen) {
      return;
    }
    const windowId = this.f(targetWindow);
    this.e.set(windowId, fullscreen);
    this.d.fire(windowId);
  }
  isFullscreen(targetWindow) {
    return !!this.e.get(this.f(targetWindow));
  }
  f(targetWindow) {
    return targetWindow.vscodeWindowId;
  }
};
function $Le(targetWindow, query, callback) {
  if (typeof query === "string") {
    query = targetWindow.matchMedia(query);
  }
  query.addEventListener("change", callback);
}
function $Ne(targetWindow) {
  return WindowManager.INSTANCE.getZoomLevel(targetWindow);
}
var $Oe = WindowManager.INSTANCE.onDidChangeZoomLevel;
function $Pe(targetWindow) {
  return WindowManager.INSTANCE.getZoomFactor(targetWindow);
}
function $Re(fullscreen, targetWindow) {
  WindowManager.INSTANCE.setFullscreen(fullscreen, targetWindow);
}
function $Se(targetWindow) {
  return WindowManager.INSTANCE.isFullscreen(targetWindow);
}
var $Te = WindowManager.INSTANCE.onDidChangeFullscreen;
var userAgent = navigator.userAgent;
var $Ue = userAgent.indexOf("Firefox") >= 0;
var $Ve = userAgent.indexOf("AppleWebKit") >= 0;
var $We = userAgent.indexOf("Chrome") >= 0;
var $Xe = !$We && userAgent.indexOf("Safari") >= 0;
var $Ye = !$We && !$Xe && $Ve;
var $Ze = userAgent.indexOf("Electron/") >= 0;
var $1e = userAgent.indexOf("Android") >= 0;
var standalone = false;
if (typeof $Y.matchMedia === "function") {
  const standaloneMatchMedia = $Y.matchMedia("(display-mode: standalone) or (display-mode: window-controls-overlay)");
  const fullScreenMatchMedia = $Y.matchMedia("(display-mode: fullscreen)");
  standalone = standaloneMatchMedia.matches;
  $Le($Y, standaloneMatchMedia, ({ matches }) => {
    if (standalone && fullScreenMatchMedia.matches) {
      return;
    }
    standalone = matches;
  });
}
function $2e() {
  return standalone;
}
function $3e() {
  return navigator?.windowControlsOverlay?.visible;
}
function $4e(targetWindow) {
  return targetWindow.navigator?.windowControlsOverlay?.getTitlebarAreaRect();
}

// out-build/vs/base/common/lazy.js
var $sf = 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/stream.js
function $oi(obj) {
  const candidate = obj;
  if (!candidate) {
    return false;
  }
  return [candidate.on, candidate.pause, candidate.resume, candidate.destroy].every((fn) => typeof fn === "function");
}
function $pi(obj) {
  const candidate = obj;
  if (!candidate) {
    return false;
  }
  return $oi(candidate.stream) && Array.isArray(candidate.buffer) && typeof candidate.ended === "boolean";
}
function $qi(reducer, options3) {
  return new WriteableStreamImpl(reducer, options3);
}
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) {
      $gb(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 $ri(readable, reducer) {
  const chunks = [];
  let chunk;
  while ((chunk = readable.read()) !== null) {
    chunks.push(chunk);
  }
  return reducer(chunks);
}
function $si(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 $ti(stream, reducer) {
  return new Promise((resolve, reject) => {
    const chunks = [];
    $ui(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 $ui(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 $vi(stream, maxChunks) {
  return new Promise((resolve, reject) => {
    const streamListeners = new $2c();
    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($1c(() => stream.removeListener("error", errorListener)));
    stream.on("error", errorListener);
    streamListeners.add($1c(() => stream.removeListener("end", endListener)));
    stream.on("end", endListener);
    streamListeners.add($1c(() => stream.removeListener("data", dataListener)));
    stream.on("data", dataListener);
  });
}
function $wi(t, reducer) {
  const stream = $qi(reducer);
  stream.end(t);
  return stream;
}
function $xi() {
  const stream = $qi(() => {
    throw new Error("not supported");
  });
  stream.end();
  return stream;
}
function $yi(t) {
  let consumed = false;
  return {
    read: () => {
      if (consumed) {
        return null;
      }
      consumed = true;
      return t;
    }
  };
}
function $zi(stream, transformer, reducer) {
  const target = $qi(reducer);
  $ui(stream, {
    onData: (data) => target.write(transformer.data(data)),
    onError: (error) => target.error(transformer.error ? transformer.error(error) : error),
    onEnd: () => target.end()
  });
  return target;
}
function $Ai(prefix, readable, reducer) {
  let prefixHandled = false;
  return {
    read: () => {
      const chunk = readable.read();
      if (!prefixHandled) {
        prefixHandled = true;
        if (chunk !== null) {
          return reducer([prefix, chunk]);
        }
        return prefix;
      }
      return chunk;
    }
  };
}
function $Bi(prefix, stream, reducer) {
  let prefixHandled = false;
  const target = $qi(reducer);
  $ui(stream, {
    onData: (data) => {
      if (!prefixHandled) {
        prefixHandled = true;
        return target.write(reducer([prefix, data]));
      }
      return target.write(data);
    },
    onError: (error) => target.error(error),
    onEnd: () => {
      if (!prefixHandled) {
        prefixHandled = true;
        target.write(prefix);
      }
      target.end();
    }
  });
  return target;
}

// out-build/vs/base/common/buffer.js
var hasBuffer = typeof Buffer !== "undefined";
var indexOfTable = new $sf(() => new Uint8Array(256));
var textEncoder;
var textDecoder;
var $Ci = class _$Ci {
  /**
   * 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 _$Ci(Buffer.allocUnsafe(byteLength));
    } else {
      return new _$Ci(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 _$Ci(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, options3) {
    const dontUseNodeBuffer = options3?.dontUseNodeBuffer || false;
    if (!dontUseNodeBuffer && hasBuffer) {
      return new _$Ci(Buffer.from(source));
    } else {
      if (!textEncoder) {
        textEncoder = new TextEncoder();
      }
      return new _$Ci(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 = _$Ci.alloc(source.length);
    for (let i2 = 0, len = source.length; i2 < len; i2++) {
      result.buffer[i2] = source[i2];
    }
    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 i2 = 0, len = buffers.length; i2 < len; i2++) {
        totalLength += buffers[i2].byteLength;
      }
    }
    const ret = _$Ci.alloc(totalLength);
    let offset = 0;
    for (let i2 = 0, len = buffers.length; i2 < len; i2++) {
      const element = buffers[i2];
      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 = _$Ci.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 _$Ci(this.buffer.subarray(start, end));
  }
  set(array2, offset) {
    if (array2 instanceof _$Ci) {
      this.buffer.set(array2.buffer, offset);
    } else if (array2 instanceof Uint8Array) {
      this.buffer.set(array2, offset);
    } else if (array2 instanceof ArrayBuffer) {
      this.buffer.set(new Uint8Array(array2), offset);
    } else if (ArrayBuffer.isView(array2)) {
      this.buffer.set(new Uint8Array(array2.buffer, array2.byteOffset, array2.byteLength), offset);
    } else {
      throw new Error(`Unknown argument 'array'`);
    }
  }
  readUInt32BE(offset) {
    return $Gi(this.buffer, offset);
  }
  writeUInt32BE(value, offset) {
    $Hi(this.buffer, value, offset);
  }
  readUInt32LE(offset) {
    return $Ii(this.buffer, offset);
  }
  writeUInt32LE(value, offset) {
    $Ji(this.buffer, value, offset);
  }
  readUInt8(offset) {
    return $Ki(this.buffer, offset);
  }
  writeUInt8(value, offset) {
    $Li(this.buffer, value, offset);
  }
  indexOf(subarray, offset = 0) {
    return $Di(this.buffer, subarray instanceof _$Ci ? subarray.buffer : subarray, offset);
  }
};
function $Di(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 i3 = 0; i3 < needle.length; i3++) {
    table[needle[i3]] = needle.length - i3 - 1;
  }
  let i2 = offset + needle.length - 1;
  let j = i2;
  let result = -1;
  while (i2 < haystackLen) {
    if (haystack[i2] === needle[j]) {
      if (j === 0) {
        result = i2;
        break;
      }
      i2--;
      j--;
    } else {
      i2 += Math.max(needle.length - j, table[haystack[i2]]);
      j = needle.length - 1;
    }
  }
  return result;
}
function $Ei(source, offset) {
  return source[offset + 0] << 0 >>> 0 | source[offset + 1] << 8 >>> 0;
}
function $Fi(destination, value, offset) {
  destination[offset + 0] = value & 255;
  value = value >>> 8;
  destination[offset + 1] = value & 255;
}
function $Gi(source, offset) {
  return source[offset] * 2 ** 24 + source[offset + 1] * 2 ** 16 + source[offset + 2] * 2 ** 8 + source[offset + 3];
}
function $Hi(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 $Ii(source, offset) {
  return source[offset + 0] << 0 >>> 0 | source[offset + 1] << 8 >>> 0 | source[offset + 2] << 16 >>> 0 | source[offset + 3] << 24 >>> 0;
}
function $Ji(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 $Ki(source, offset) {
  return source[offset];
}
function $Li(destination, value, offset) {
  destination[offset] = value;
}
function $Mi(readable) {
  return $ri(readable, (chunks) => $Ci.concat(chunks));
}
function $Ni(buffer) {
  return $yi(buffer);
}
function $Oi(stream) {
  return $ti(stream, (chunks) => $Ci.concat(chunks));
}
async function $Pi(bufferedStream) {
  if (bufferedStream.ended) {
    return $Ci.concat(bufferedStream.buffer);
  }
  return $Ci.concat([
    // Include already read chunks...
    ...bufferedStream.buffer,
    // ...and all additional chunks
    await $Oi(bufferedStream.stream)
  ]);
}
function $Qi(buffer) {
  return $wi(buffer, (chunks) => $Ci.concat(chunks));
}
function $Si(options3) {
  return $qi((chunks) => $Ci.concat(chunks), options3);
}
function $Ti(prefix, readable) {
  return $Ai(prefix, readable, (chunks) => $Ci.concat(chunks));
}
function $Ui(prefix, stream) {
  return $Bi(prefix, stream, (chunks) => $Ci.concat(chunks));
}
function $Vi(encoded) {
  let building = 0;
  let remainder = 0;
  let bufi = 0;
  const buffer = new Uint8Array(Math.floor(encoded.length / 4 * 3));
  const append2 = (value) => {
    switch (remainder) {
      case 3:
        buffer[bufi++] = building | value;
        remainder = 0;
        break;
      case 2:
        buffer[bufi++] = building | value >>> 2;
        building = value << 6;
        remainder = 3;
        break;
      case 1:
        buffer[bufi++] = building | value >>> 4;
        building = value << 4;
        remainder = 2;
        break;
      default:
        building = value << 2;
        remainder = 1;
    }
  };
  for (let i2 = 0; i2 < encoded.length; i2++) {
    const code = encoded.charCodeAt(i2);
    if (code >= 65 && code <= 90) {
      append2(code - 65);
    } else if (code >= 97 && code <= 122) {
      append2(code - 97 + 26);
    } else if (code >= 48 && code <= 57) {
      append2(code - 48 + 52);
    } else if (code === 43 || code === 45) {
      append2(62);
    } else if (code === 47 || code === 95) {
      append2(63);
    } else if (code === 61) {
      break;
    } else {
      throw new SyntaxError(`Unexpected base64 character ${encoded[i2]}`);
    }
  }
  const unpadded = bufi;
  while (remainder > 0) {
    append2(0);
  }
  return $Ci.wrap(buffer).slice(0, unpadded);
}
var base64Alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
var base64UrlSafeAlphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_";
function $Wi({ buffer }, padded = true, urlSafe = false) {
  const dictionary = urlSafe ? base64UrlSafeAlphabet : base64Alphabet;
  let output = "";
  const remainder = buffer.byteLength % 3;
  let i2 = 0;
  for (; i2 < buffer.byteLength - remainder; i2 += 3) {
    const a = buffer[i2 + 0];
    const b = buffer[i2 + 1];
    const c = buffer[i2 + 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[i2 + 0];
    output += dictionary[a >>> 2];
    output += dictionary[a << 4 & 63];
    if (padded) {
      output += "==";
    }
  } else if (remainder === 2) {
    const a = buffer[i2 + 0];
    const b = buffer[i2 + 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/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, args2) {
  let result;
  if (args2.length === 0) {
    result = message;
  } else {
    result = message.replace(/\{(\d+)\}/g, (match, rest) => {
      const index = rest[0];
      const arg = args2[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, ...args2) {
  if (typeof data === "number") {
    return _format(lookupMessage(data, message), args2);
  }
  return _format(message, args2);
}
function lookupMessage(index, fallback2) {
  const message = $f()?.[index];
  if (typeof message !== "string") {
    if (typeof fallback2 === "string") {
      return fallback2;
    }
    throw new Error(`!!! NLS MISSING: ${index} !!!`);
  }
  return message;
}
function localize2(data, originalMessage, ...args2) {
  let message;
  if (typeof data === "number") {
    message = lookupMessage(data, originalMessage);
  } else {
    message = originalMessage;
  }
  const value = _format(message, args2);
  return {
    value,
    original: originalMessage === message ? value : _format(originalMessage, args2)
  };
}

// 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 $q = _isElectron;
var $r = _isWeb;
var $s = _isWeb && typeof $globalThis.importScripts === "function";
var $t = $s ? $globalThis.origin : void 0;
var $u = _isIOS;
var $v = _isMobile;
var $w = _isCI;
var $x = _platform;
var $y = _userAgent;
var $z = _language;
var Language;
(function(Language2) {
  function value() {
    return $z;
  }
  Language2.value = value;
  function isDefaultVariant() {
    if ($z.length === 2) {
      return $z === "en";
    } else if ($z.length >= 3) {
      return $z[0] === "e" && $z[1] === "n" && $z[2] === "-";
    } else {
      return false;
    }
  }
  Language2.isDefaultVariant = isDefaultVariant;
  function isDefault() {
    return $z === "en";
  }
  Language2.isDefault = isDefault;
})(Language || (Language = {}));
var $A = _locale;
var $B = _platformLocale;
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 i2 = 0, len = pending.length; i2 < len; i2++) {
          const candidate = pending[i2];
          if (candidate.id === e.data.vscodeScheduleAsyncWork) {
            pending.splice(i2, 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 _isLittleEndian = true;
var _isLittleEndianComputed = false;
function $G() {
  if (!_isLittleEndianComputed) {
    _isLittleEndianComputed = true;
    const test = new Uint8Array(2);
    test[0] = 1;
    test[1] = 2;
    const view = new Uint16Array(test.buffer);
    _isLittleEndian = view[0] === (2 << 8) + 1;
  }
  return _isLittleEndian;
}
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/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 $hc = safeProcess.platform;
var $ic = 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 type = name.indexOf(".") !== -1 ? "property" : "argument";
    let msg = `The "${name}" ${type} ${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 = $hc === "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(path, allowAboveRoot, separator, isPathSeparator2) {
  let res = "";
  let lastSegmentLength = 0;
  let lastSlash = -1;
  let dots = 0;
  let code = 0;
  for (let i2 = 0; i2 <= path.length; ++i2) {
    if (i2 < path.length) {
      code = path.charCodeAt(i2);
    } else if (isPathSeparator2(code)) {
      break;
    } else {
      code = CHAR_FORWARD_SLASH;
    }
    if (isPathSeparator2(code)) {
      if (lastSlash === i2 - 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 = i2;
            dots = 0;
            continue;
          } else if (res.length !== 0) {
            res = "";
            lastSegmentLength = 0;
            lastSlash = i2;
            dots = 0;
            continue;
          }
        }
        if (allowAboveRoot) {
          res += res.length > 0 ? `${separator}..` : "..";
          lastSegmentLength = 2;
        }
      } else {
        if (res.length > 0) {
          res += `${separator}${path.slice(lastSlash + 1, i2)}`;
        } else {
          res = path.slice(lastSlash + 1, i2);
        }
        lastSegmentLength = i2 - lastSlash - 1;
      }
      lastSlash = i2;
      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 $jc = {
  // path.resolve([from ...], to)
  resolve(...pathSegments) {
    let resolvedDevice = "";
    let resolvedTail = "";
    let resolvedAbsolute = false;
    for (let i2 = pathSegments.length - 1; i2 >= -1; i2--) {
      let path;
      if (i2 >= 0) {
        path = pathSegments[i2];
        validateString(path, `paths[${i2}]`);
        if (path.length === 0) {
          continue;
        }
      } else if (resolvedDevice.length === 0) {
        path = cwd();
      } else {
        path = env[`=${resolvedDevice}`] || cwd();
        if (path === void 0 || path.slice(0, 2).toLowerCase() !== resolvedDevice.toLowerCase() && path.charCodeAt(2) === CHAR_BACKWARD_SLASH) {
          path = `${resolvedDevice}\\`;
        }
      }
      const len = path.length;
      let rootEnd = 0;
      let device = "";
      let isAbsolute = false;
      const code = path.charCodeAt(0);
      if (len === 1) {
        if (isPathSeparator(code)) {
          rootEnd = 1;
          isAbsolute = true;
        }
      } else if (isPathSeparator(code)) {
        isAbsolute = true;
        if (isPathSeparator(path.charCodeAt(1))) {
          let j = 2;
          let last = j;
          while (j < len && !isPathSeparator(path.charCodeAt(j))) {
            j++;
          }
          if (j < len && j !== last) {
            const firstPart = path.slice(last, j);
            last = j;
            while (j < len && isPathSeparator(path.charCodeAt(j))) {
              j++;
            }
            if (j < len && j !== last) {
              last = j;
              while (j < len && !isPathSeparator(path.charCodeAt(j))) {
                j++;
              }
              if (j === len || j !== last) {
                device = `\\\\${firstPart}\\${path.slice(last, j)}`;
                rootEnd = j;
              }
            }
          }
        } else {
          rootEnd = 1;
        }
      } else if (isWindowsDeviceRoot(code) && path.charCodeAt(1) === CHAR_COLON) {
        device = path.slice(0, 2);
        rootEnd = 2;
        if (len > 2 && isPathSeparator(path.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 = `${path.slice(rootEnd)}\\${resolvedTail}`;
        resolvedAbsolute = isAbsolute;
        if (isAbsolute && resolvedDevice.length > 0) {
          break;
        }
      }
    }
    resolvedTail = normalizeString(resolvedTail, !resolvedAbsolute, "\\", isPathSeparator);
    return resolvedAbsolute ? `${resolvedDevice}\\${resolvedTail}` : `${resolvedDevice}${resolvedTail}` || ".";
  },
  normalize(path) {
    validateString(path, "path");
    const len = path.length;
    if (len === 0) {
      return ".";
    }
    let rootEnd = 0;
    let device;
    let isAbsolute = false;
    const code = path.charCodeAt(0);
    if (len === 1) {
      return isPosixPathSeparator(code) ? "\\" : path;
    }
    if (isPathSeparator(code)) {
      isAbsolute = true;
      if (isPathSeparator(path.charCodeAt(1))) {
        let j = 2;
        let last = j;
        while (j < len && !isPathSeparator(path.charCodeAt(j))) {
          j++;
        }
        if (j < len && j !== last) {
          const firstPart = path.slice(last, j);
          last = j;
          while (j < len && isPathSeparator(path.charCodeAt(j))) {
            j++;
          }
          if (j < len && j !== last) {
            last = j;
            while (j < len && !isPathSeparator(path.charCodeAt(j))) {
              j++;
            }
            if (j === len) {
              return `\\\\${firstPart}\\${path.slice(last)}\\`;
            }
            if (j !== last) {
              device = `\\\\${firstPart}\\${path.slice(last, j)}`;
              rootEnd = j;
            }
          }
        }
      } else {
        rootEnd = 1;
      }
    } else if (isWindowsDeviceRoot(code) && path.charCodeAt(1) === CHAR_COLON) {
      device = path.slice(0, 2);
      rootEnd = 2;
      if (len > 2 && isPathSeparator(path.charCodeAt(2))) {
        isAbsolute = true;
        rootEnd = 3;
      }
    }
    let tail = rootEnd < len ? normalizeString(path.slice(rootEnd), !isAbsolute, "\\", isPathSeparator) : "";
    if (tail.length === 0 && !isAbsolute) {
      tail = ".";
    }
    if (tail.length > 0 && isPathSeparator(path.charCodeAt(len - 1))) {
      tail += "\\";
    }
    if (device === void 0) {
      return isAbsolute ? `\\${tail}` : tail;
    }
    return isAbsolute ? `${device}\\${tail}` : `${device}${tail}`;
  },
  isAbsolute(path) {
    validateString(path, "path");
    const len = path.length;
    if (len === 0) {
      return false;
    }
    const code = path.charCodeAt(0);
    return isPathSeparator(code) || // Possible device root
    len > 2 && isWindowsDeviceRoot(code) && path.charCodeAt(1) === CHAR_COLON && isPathSeparator(path.charCodeAt(2));
  },
  join(...paths) {
    if (paths.length === 0) {
      return ".";
    }
    let joined;
    let firstPart;
    for (let i2 = 0; i2 < paths.length; ++i2) {
      const arg = paths[i2];
      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 $jc.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 = $jc.resolve(from);
    const toOrig = $jc.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 i2 = 0;
    for (; i2 < length; i2++) {
      const fromCode = from.charCodeAt(fromStart + i2);
      if (fromCode !== to.charCodeAt(toStart + i2)) {
        break;
      } else if (fromCode === CHAR_BACKWARD_SLASH) {
        lastCommonSep = i2;
      }
    }
    if (i2 !== length) {
      if (lastCommonSep === -1) {
        return toOrig;
      }
    } else {
      if (toLen > length) {
        if (to.charCodeAt(toStart + i2) === CHAR_BACKWARD_SLASH) {
          return toOrig.slice(toStart + i2 + 1);
        }
        if (i2 === 2) {
          return toOrig.slice(toStart + i2);
        }
      }
      if (fromLen > length) {
        if (from.charCodeAt(fromStart + i2) === CHAR_BACKWARD_SLASH) {
          lastCommonSep = i2;
        } else if (i2 === 2) {
          lastCommonSep = 3;
        }
      }
      if (lastCommonSep === -1) {
        lastCommonSep = 0;
      }
    }
    let out = "";
    for (i2 = fromStart + lastCommonSep + 1; i2 <= fromEnd; ++i2) {
      if (i2 === fromEnd || from.charCodeAt(i2) === 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(path) {
    if (typeof path !== "string" || path.length === 0) {
      return path;
    }
    const resolvedPath = $jc.resolve(path);
    if (resolvedPath.length <= 2) {
      return path;
    }
    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 path;
  },
  dirname(path) {
    validateString(path, "path");
    const len = path.length;
    if (len === 0) {
      return ".";
    }
    let rootEnd = -1;
    let offset = 0;
    const code = path.charCodeAt(0);
    if (len === 1) {
      return isPathSeparator(code) ? path : ".";
    }
    if (isPathSeparator(code)) {
      rootEnd = offset = 1;
      if (isPathSeparator(path.charCodeAt(1))) {
        let j = 2;
        let last = j;
        while (j < len && !isPathSeparator(path.charCodeAt(j))) {
          j++;
        }
        if (j < len && j !== last) {
          last = j;
          while (j < len && isPathSeparator(path.charCodeAt(j))) {
            j++;
          }
          if (j < len && j !== last) {
            last = j;
            while (j < len && !isPathSeparator(path.charCodeAt(j))) {
              j++;
            }
            if (j === len) {
              return path;
            }
            if (j !== last) {
              rootEnd = offset = j + 1;
            }
          }
        }
      }
    } else if (isWindowsDeviceRoot(code) && path.charCodeAt(1) === CHAR_COLON) {
      rootEnd = len > 2 && isPathSeparator(path.charCodeAt(2)) ? 3 : 2;
      offset = rootEnd;
    }
    let end = -1;
    let matchedSlash = true;
    for (let i2 = len - 1; i2 >= offset; --i2) {
      if (isPathSeparator(path.charCodeAt(i2))) {
        if (!matchedSlash) {
          end = i2;
          break;
        }
      } else {
        matchedSlash = false;
      }
    }
    if (end === -1) {
      if (rootEnd === -1) {
        return ".";
      }
      end = rootEnd;
    }
    return path.slice(0, end);
  },
  basename(path, suffix) {
    if (suffix !== void 0) {
      validateString(suffix, "suffix");
    }
    validateString(path, "path");
    let start = 0;
    let end = -1;
    let matchedSlash = true;
    let i2;
    if (path.length >= 2 && isWindowsDeviceRoot(path.charCodeAt(0)) && path.charCodeAt(1) === CHAR_COLON) {
      start = 2;
    }
    if (suffix !== void 0 && suffix.length > 0 && suffix.length <= path.length) {
      if (suffix === path) {
        return "";
      }
      let extIdx = suffix.length - 1;
      let firstNonSlashEnd = -1;
      for (i2 = path.length - 1; i2 >= start; --i2) {
        const code = path.charCodeAt(i2);
        if (isPathSeparator(code)) {
          if (!matchedSlash) {
            start = i2 + 1;
            break;
          }
        } else {
          if (firstNonSlashEnd === -1) {
            matchedSlash = false;
            firstNonSlashEnd = i2 + 1;
          }
          if (extIdx >= 0) {
            if (code === suffix.charCodeAt(extIdx)) {
              if (--extIdx === -1) {
                end = i2;
              }
            } else {
              extIdx = -1;
              end = firstNonSlashEnd;
            }
          }
        }
      }
      if (start === end) {
        end = firstNonSlashEnd;
      } else if (end === -1) {
        end = path.length;
      }
      return path.slice(start, end);
    }
    for (i2 = path.length - 1; i2 >= start; --i2) {
      if (isPathSeparator(path.charCodeAt(i2))) {
        if (!matchedSlash) {
          start = i2 + 1;
          break;
        }
      } else if (end === -1) {
        matchedSlash = false;
        end = i2 + 1;
      }
    }
    if (end === -1) {
      return "";
    }
    return path.slice(start, end);
  },
  extname(path) {
    validateString(path, "path");
    let start = 0;
    let startDot = -1;
    let startPart = 0;
    let end = -1;
    let matchedSlash = true;
    let preDotState = 0;
    if (path.length >= 2 && path.charCodeAt(1) === CHAR_COLON && isWindowsDeviceRoot(path.charCodeAt(0))) {
      start = startPart = 2;
    }
    for (let i2 = path.length - 1; i2 >= start; --i2) {
      const code = path.charCodeAt(i2);
      if (isPathSeparator(code)) {
        if (!matchedSlash) {
          startPart = i2 + 1;
          break;
        }
        continue;
      }
      if (end === -1) {
        matchedSlash = false;
        end = i2 + 1;
      }
      if (code === CHAR_DOT) {
        if (startDot === -1) {
          startDot = i2;
        } 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 path.slice(startDot, end);
  },
  format: _format2.bind(null, "\\"),
  parse(path) {
    validateString(path, "path");
    const ret = { root: "", dir: "", base: "", ext: "", name: "" };
    if (path.length === 0) {
      return ret;
    }
    const len = path.length;
    let rootEnd = 0;
    let code = path.charCodeAt(0);
    if (len === 1) {
      if (isPathSeparator(code)) {
        ret.root = ret.dir = path;
        return ret;
      }
      ret.base = ret.name = path;
      return ret;
    }
    if (isPathSeparator(code)) {
      rootEnd = 1;
      if (isPathSeparator(path.charCodeAt(1))) {
        let j = 2;
        let last = j;
        while (j < len && !isPathSeparator(path.charCodeAt(j))) {
          j++;
        }
        if (j < len && j !== last) {
          last = j;
          while (j < len && isPathSeparator(path.charCodeAt(j))) {
            j++;
          }
          if (j < len && j !== last) {
            last = j;
            while (j < len && !isPathSeparator(path.charCodeAt(j))) {
              j++;
            }
            if (j === len) {
              rootEnd = j;
            } else if (j !== last) {
              rootEnd = j + 1;
            }
          }
        }
      }
    } else if (isWindowsDeviceRoot(code) && path.charCodeAt(1) === CHAR_COLON) {
      if (len <= 2) {
        ret.root = ret.dir = path;
        return ret;
      }
      rootEnd = 2;
      if (isPathSeparator(path.charCodeAt(2))) {
        if (len === 3) {
          ret.root = ret.dir = path;
          return ret;
        }
        rootEnd = 3;
      }
    }
    if (rootEnd > 0) {
      ret.root = path.slice(0, rootEnd);
    }
    let startDot = -1;
    let startPart = rootEnd;
    let end = -1;
    let matchedSlash = true;
    let i2 = path.length - 1;
    let preDotState = 0;
    for (; i2 >= rootEnd; --i2) {
      code = path.charCodeAt(i2);
      if (isPathSeparator(code)) {
        if (!matchedSlash) {
          startPart = i2 + 1;
          break;
        }
        continue;
      }
      if (end === -1) {
        matchedSlash = false;
        end = i2 + 1;
      }
      if (code === CHAR_DOT) {
        if (startDot === -1) {
          startDot = i2;
        } 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 = path.slice(startPart, end);
      } else {
        ret.name = path.slice(startPart, startDot);
        ret.base = path.slice(startPart, end);
        ret.ext = path.slice(startDot, end);
      }
    }
    if (startPart > 0 && startPart !== rootEnd) {
      ret.dir = path.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 $kc = {
  // path.resolve([from ...], to)
  resolve(...pathSegments) {
    let resolvedPath = "";
    let resolvedAbsolute = false;
    for (let i2 = pathSegments.length - 1; i2 >= -1 && !resolvedAbsolute; i2--) {
      const path = i2 >= 0 ? pathSegments[i2] : posixCwd();
      validateString(path, `paths[${i2}]`);
      if (path.length === 0) {
        continue;
      }
      resolvedPath = `${path}/${resolvedPath}`;
      resolvedAbsolute = path.charCodeAt(0) === CHAR_FORWARD_SLASH;
    }
    resolvedPath = normalizeString(resolvedPath, !resolvedAbsolute, "/", isPosixPathSeparator);
    if (resolvedAbsolute) {
      return `/${resolvedPath}`;
    }
    return resolvedPath.length > 0 ? resolvedPath : ".";
  },
  normalize(path) {
    validateString(path, "path");
    if (path.length === 0) {
      return ".";
    }
    const isAbsolute = path.charCodeAt(0) === CHAR_FORWARD_SLASH;
    const trailingSeparator = path.charCodeAt(path.length - 1) === CHAR_FORWARD_SLASH;
    path = normalizeString(path, !isAbsolute, "/", isPosixPathSeparator);
    if (path.length === 0) {
      if (isAbsolute) {
        return "/";
      }
      return trailingSeparator ? "./" : ".";
    }
    if (trailingSeparator) {
      path += "/";
    }
    return isAbsolute ? `/${path}` : path;
  },
  isAbsolute(path) {
    validateString(path, "path");
    return path.length > 0 && path.charCodeAt(0) === CHAR_FORWARD_SLASH;
  },
  join(...paths) {
    if (paths.length === 0) {
      return ".";
    }
    let joined;
    for (let i2 = 0; i2 < paths.length; ++i2) {
      const arg = paths[i2];
      validateString(arg, "path");
      if (arg.length > 0) {
        if (joined === void 0) {
          joined = arg;
        } else {
          joined += `/${arg}`;
        }
      }
    }
    if (joined === void 0) {
      return ".";
    }
    return $kc.normalize(joined);
  },
  relative(from, to) {
    validateString(from, "from");
    validateString(to, "to");
    if (from === to) {
      return "";
    }
    from = $kc.resolve(from);
    to = $kc.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 i2 = 0;
    for (; i2 < length; i2++) {
      const fromCode = from.charCodeAt(fromStart + i2);
      if (fromCode !== to.charCodeAt(toStart + i2)) {
        break;
      } else if (fromCode === CHAR_FORWARD_SLASH) {
        lastCommonSep = i2;
      }
    }
    if (i2 === length) {
      if (toLen > length) {
        if (to.charCodeAt(toStart + i2) === CHAR_FORWARD_SLASH) {
          return to.slice(toStart + i2 + 1);
        }
        if (i2 === 0) {
          return to.slice(toStart + i2);
        }
      } else if (fromLen > length) {
        if (from.charCodeAt(fromStart + i2) === CHAR_FORWARD_SLASH) {
          lastCommonSep = i2;
        } else if (i2 === 0) {
          lastCommonSep = 0;
        }
      }
    }
    let out = "";
    for (i2 = fromStart + lastCommonSep + 1; i2 <= fromEnd; ++i2) {
      if (i2 === fromEnd || from.charCodeAt(i2) === CHAR_FORWARD_SLASH) {
        out += out.length === 0 ? ".." : "/..";
      }
    }
    return `${out}${to.slice(toStart + lastCommonSep)}`;
  },
  toNamespacedPath(path) {
    return path;
  },
  dirname(path) {
    validateString(path, "path");
    if (path.length === 0) {
      return ".";
    }
    const hasRoot = path.charCodeAt(0) === CHAR_FORWARD_SLASH;
    let end = -1;
    let matchedSlash = true;
    for (let i2 = path.length - 1; i2 >= 1; --i2) {
      if (path.charCodeAt(i2) === CHAR_FORWARD_SLASH) {
        if (!matchedSlash) {
          end = i2;
          break;
        }
      } else {
        matchedSlash = false;
      }
    }
    if (end === -1) {
      return hasRoot ? "/" : ".";
    }
    if (hasRoot && end === 1) {
      return "//";
    }
    return path.slice(0, end);
  },
  basename(path, suffix) {
    if (suffix !== void 0) {
      validateString(suffix, "ext");
    }
    validateString(path, "path");
    let start = 0;
    let end = -1;
    let matchedSlash = true;
    let i2;
    if (suffix !== void 0 && suffix.length > 0 && suffix.length <= path.length) {
      if (suffix === path) {
        return "";
      }
      let extIdx = suffix.length - 1;
      let firstNonSlashEnd = -1;
      for (i2 = path.length - 1; i2 >= 0; --i2) {
        const code = path.charCodeAt(i2);
        if (code === CHAR_FORWARD_SLASH) {
          if (!matchedSlash) {
            start = i2 + 1;
            break;
          }
        } else {
          if (firstNonSlashEnd === -1) {
            matchedSlash = false;
            firstNonSlashEnd = i2 + 1;
          }
          if (extIdx >= 0) {
            if (code === suffix.charCodeAt(extIdx)) {
              if (--extIdx === -1) {
                end = i2;
              }
            } else {
              extIdx = -1;
              end = firstNonSlashEnd;
            }
          }
        }
      }
      if (start === end) {
        end = firstNonSlashEnd;
      } else if (end === -1) {
        end = path.length;
      }
      return path.slice(start, end);
    }
    for (i2 = path.length - 1; i2 >= 0; --i2) {
      if (path.charCodeAt(i2) === CHAR_FORWARD_SLASH) {
        if (!matchedSlash) {
          start = i2 + 1;
          break;
        }
      } else if (end === -1) {
        matchedSlash = false;
        end = i2 + 1;
      }
    }
    if (end === -1) {
      return "";
    }
    return path.slice(start, end);
  },
  extname(path) {
    validateString(path, "path");
    let startDot = -1;
    let startPart = 0;
    let end = -1;
    let matchedSlash = true;
    let preDotState = 0;
    for (let i2 = path.length - 1; i2 >= 0; --i2) {
      const code = path.charCodeAt(i2);
      if (code === CHAR_FORWARD_SLASH) {
        if (!matchedSlash) {
          startPart = i2 + 1;
          break;
        }
        continue;
      }
      if (end === -1) {
        matchedSlash = false;
        end = i2 + 1;
      }
      if (code === CHAR_DOT) {
        if (startDot === -1) {
          startDot = i2;
        } 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 path.slice(startDot, end);
  },
  format: _format2.bind(null, "/"),
  parse(path) {
    validateString(path, "path");
    const ret = { root: "", dir: "", base: "", ext: "", name: "" };
    if (path.length === 0) {
      return ret;
    }
    const isAbsolute = path.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 i2 = path.length - 1;
    let preDotState = 0;
    for (; i2 >= start; --i2) {
      const code = path.charCodeAt(i2);
      if (code === CHAR_FORWARD_SLASH) {
        if (!matchedSlash) {
          startPart = i2 + 1;
          break;
        }
        continue;
      }
      if (end === -1) {
        matchedSlash = false;
        end = i2 + 1;
      }
      if (code === CHAR_DOT) {
        if (startDot === -1) {
          startDot = i2;
        } 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 = path.slice(start2, end);
      } else {
        ret.name = path.slice(start2, startDot);
        ret.base = path.slice(start2, end);
        ret.ext = path.slice(startDot, end);
      }
    }
    if (startPart > 0) {
      ret.dir = path.slice(0, startPart - 1);
    } else if (isAbsolute) {
      ret.dir = "/";
    }
    return ret;
  },
  sep: "/",
  delimiter: ":",
  win32: null,
  posix: null
};
$kc.win32 = $jc.win32 = $jc;
$kc.posix = $jc.posix = $kc;
var $lc = platformIsWin32 ? $jc.normalize : $kc.normalize;
var $mc = platformIsWin32 ? $jc.isAbsolute : $kc.isAbsolute;
var $nc = platformIsWin32 ? $jc.join : $kc.join;
var $oc = platformIsWin32 ? $jc.resolve : $kc.resolve;
var $pc = platformIsWin32 ? $jc.relative : $kc.relative;
var $qc = platformIsWin32 ? $jc.dirname : $kc.dirname;
var $rc = platformIsWin32 ? $jc.basename : $kc.basename;
var $sc = platformIsWin32 ? $jc.extname : $kc.extname;
var $tc = platformIsWin32 ? $jc.format : $kc.format;
var $uc = platformIsWin32 ? $jc.parse : $kc.parse;
var $vc = platformIsWin32 ? $jc.toNamespacedPath : $kc.toNamespacedPath;
var sep = platformIsWin32 ? $jc.sep : $kc.sep;
var $xc = platformIsWin32 ? $jc.delimiter : $kc.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, path) {
  switch (scheme) {
    case "https":
    case "http":
    case "file":
      if (!path) {
        path = _slash;
      } else if (path[0] !== _slash) {
        path = _slash + path;
      }
      break;
  }
  return path;
}
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, path, 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, path || _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 $Ac(this, false);
  }
  // ---- modify to new -------------------------
  with(change) {
    if (!change) {
      return this;
    }
    let { scheme, authority, path, 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 (path === void 0) {
      path = this.path;
    } else if (path === null) {
      path = _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 && path === this.path && query === this.query && fragment === this.fragment) {
      return this;
    }
    return new Uri(scheme, authority, path, 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(path) {
    let authority = _empty;
    if ($l) {
      path = path.replace(/\\/g, _slash);
    }
    if (path[0] === _slash && path[1] === _slash) {
      const idx = path.indexOf(_slash, 2);
      if (idx === -1) {
        authority = path.substring(2);
        path = _slash;
      } else {
        authority = path.substring(2, idx);
        path = path.substring(idx) || _slash;
      }
    }
    return new Uri("file", authority, path, _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($jc.join($Ac(uri, true), ...pathFragment)).path;
    } else {
      newPath = $kc.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()})`;
  }
};
function $zc(thing) {
  if (!thing || typeof thing !== "object") {
    return false;
  }
  return typeof thing.scheme === "string" && (typeof thing.authority === "string" || typeof thing.authority === "undefined") && (typeof thing.path === "string" || typeof thing.path === "undefined") && (typeof thing.query === "string" || typeof thing.query === "undefined") && (typeof thing.fragment === "string" || typeof thing.fragment === "undefined");
}
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 = $Ac(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(path) {
  let res = void 0;
  for (let pos = 0; pos < path.length; pos++) {
    const code = path.charCodeAt(pos);
    if (code === 35 || code === 63) {
      if (res === void 0) {
        res = path.substr(0, pos);
      }
      res += encodeTable[code];
    } else {
      if (res !== void 0) {
        res += path[pos];
      }
    }
  }
  return res !== void 0 ? res : path;
}
function $Ac(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, 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 (path) {
    if (path.length >= 3 && path.charCodeAt(0) === 47 && path.charCodeAt(2) === 58) {
      const code = path.charCodeAt(1);
      if (code >= 65 && code <= 90) {
        path = `/${String.fromCharCode(code + 32)}:${path.substr(3)}`;
      }
    } else if (path.length >= 2 && path.charCodeAt(1) === 58) {
      const code = path.charCodeAt(0);
      if (code >= 65 && code <= 90) {
        path = `${String.fromCharCode(code + 32)}:${path.substr(2)}`;
      }
    }
    res += encoder(path, 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/marshalling.js
function $au(obj) {
  return JSON.stringify(obj, replacer);
}
function $bu(text2) {
  let data = JSON.parse(text2);
  data = $cu(data);
  return data;
}
function replacer(key2, value) {
  if (value instanceof RegExp) {
    return {
      $mid: 2,
      source: value.source,
      flags: value.flags
    };
  }
  return value;
}
function $cu(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 $Ci || obj instanceof Uint8Array) {
      return obj;
    }
    if (Array.isArray(obj)) {
      for (let i2 = 0; i2 < obj.length; ++i2) {
        obj[i2] = $cu(obj[i2], depth + 1);
      }
    } else {
      for (const key2 in obj) {
        if (Object.hasOwnProperty.call(obj, key2)) {
          obj[key2] = $cu(obj[key2], depth + 1);
        }
      }
    }
  }
  return obj;
}

// 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: Event2.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 $ze();
    }
    return this.b.event;
  }
  dispose() {
    if (this.b) {
      this.b.dispose();
      this.b = null;
    }
  }
};
var $ad = 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();
    }
  }
};
function $bd(store) {
  const source = new $ad();
  store.add({ dispose() {
    source.cancel();
  } });
  return source.token;
}

// out-build/vs/base/common/cache.js
var $of = class {
  constructor(b) {
    this.b = b;
    this.a = null;
  }
  get() {
    if (this.a) {
      return this.a;
    }
    const cts = new $ad();
    const promise = this.b(cts.token);
    this.a = {
      promise,
      dispose: () => {
        this.a = null;
        cts.cancel();
        cts.dispose();
      }
    };
    return this.a;
  }
};
function $pf(t) {
  return t;
}
var $qf = class {
  constructor(arg1, arg2) {
    this.a = void 0;
    this.b = void 0;
    if (typeof arg1 === "function") {
      this.c = arg1;
      this.d = $pf;
    } else {
      this.c = arg2;
      this.d = arg1.getCacheKey;
    }
  }
  get(arg) {
    const key2 = this.d(arg);
    if (this.b !== key2) {
      this.b = key2;
      this.a = this.c(arg);
    }
    return this.a;
  }
};
var $rf = class {
  get cachedValues() {
    return this.a;
  }
  constructor(arg1, arg2) {
    this.a = /* @__PURE__ */ new Map();
    this.b = /* @__PURE__ */ new Map();
    if (typeof arg1 === "function") {
      this.c = arg1;
      this.d = $pf;
    } else {
      this.c = arg2;
      this.d = arg1.getCacheKey;
    }
  }
  get(arg) {
    const key2 = this.d(arg);
    if (this.b.has(key2)) {
      return this.b.get(key2);
    }
    const value = this.c(arg);
    this.a.set(arg, value);
    this.b.set(key2, value);
    return value;
  }
};

// out-build/vs/base/common/strings.js
function $vf(str) {
  if (!str || typeof str !== "string") {
    return true;
  }
  return str.trim().length === 0;
}
var _formatRegexp = /{(\d+)}/g;
function $wf(value, ...args2) {
  if (args2.length === 0) {
    return value;
  }
  return value.replace(_formatRegexp, function(match, group2) {
    const idx = parseInt(group2, 10);
    return isNaN(idx) || idx < 0 || idx >= args2.length ? match : args2[idx];
  });
}
var _format2Regexp = /{([^}]+)}/g;
function $xf(template, values) {
  if (Object.keys(values).length === 0) {
    return template;
  }
  return template.replace(_format2Regexp, (match, group2) => values[group2] ?? match);
}
function $yf(value) {
  return value.replace(/[<>"'&]/g, (ch) => {
    switch (ch) {
      case "<":
        return "&lt;";
      case ">":
        return "&gt;";
      case '"':
        return "&quot;";
      case "'":
        return "&apos;";
      case "&":
        return "&amp;";
    }
    return ch;
  });
}
function $zf(html3) {
  return html3.replace(/[<>&]/g, function(match) {
    switch (match) {
      case "<":
        return "&lt;";
      case ">":
        return "&gt;";
      case "&":
        return "&amp;";
      default:
        return match;
    }
  });
}
function $Af(value) {
  return value.replace(/[\\\{\}\*\+\?\|\^\$\.\[\]\(\)]/g, "\\$&");
}
function $Bf(value, substr) {
  let result = 0;
  let index = value.indexOf(substr);
  while (index !== -1) {
    result++;
    index = value.indexOf(substr, index + substr.length);
  }
  return result;
}
function $Cf(value, maxLength, suffix = "\u2026") {
  if (value.length <= maxLength) {
    return value;
  }
  return `${value.substr(0, maxLength)}${suffix}`;
}
function $Df(value, maxLength, suffix = "\u2026") {
  if (value.length <= maxLength) {
    return value;
  }
  const prefixLength = Math.ceil(maxLength / 2) - suffix.length / 2;
  const suffixLength = Math.floor(maxLength / 2) - suffix.length / 2;
  return `${value.substr(0, prefixLength)}${suffix}${value.substr(value.length - suffixLength)}`;
}
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 $Hf(pattern) {
  return pattern.replace(/[\-\\\{\}\+\?\|\^\$\.\,\[\]\(\)\#\s]/g, "\\$&").replace(/[\*]/g, ".*");
}
function $If(pattern) {
  return pattern.replace(/\*/g, "");
}
function $Jf(searchString, isRegex, options3 = {}) {
  if (!searchString) {
    throw new Error("Cannot create regex from empty string");
  }
  if (!isRegex) {
    searchString = $Af(searchString);
  }
  if (options3.wholeWord) {
    if (!/\B/.test(searchString.charAt(0))) {
      searchString = "\\b" + searchString;
    }
    if (!/\B/.test(searchString.charAt(searchString.length - 1))) {
      searchString = searchString + "\\b";
    }
  }
  let modifiers = "";
  if (options3.global) {
    modifiers += "g";
  }
  if (!options3.matchCase) {
    modifiers += "i";
  }
  if (options3.multiline) {
    modifiers += "m";
  }
  if (options3.unicode) {
    modifiers += "u";
  }
  return new RegExp(searchString, modifiers);
}
function $Kf(regexp) {
  if (regexp.source === "^" || regexp.source === "^$" || regexp.source === "$" || regexp.source === "^\\s*$") {
    return false;
  }
  const match = regexp.exec("");
  return !!(match && regexp.lastIndex === 0);
}
function $Lf(items, separator) {
  return items.filter((item) => item !== void 0 && item !== null && item !== false).join(separator);
}
function $Mf(str) {
  return str.split(/\r\n|\r|\n/);
}
function $Nf(str) {
  const linesWithSeparators = [];
  const splitLinesAndSeparators = str.split(/(\r\n|\r|\n)/);
  for (let i2 = 0; i2 < Math.ceil(splitLinesAndSeparators.length / 2); i2++) {
    linesWithSeparators.push(splitLinesAndSeparators[2 * i2] + (splitLinesAndSeparators[2 * i2 + 1] ?? ""));
  }
  return linesWithSeparators;
}
function $Of(str) {
  for (let i2 = 0, len = str.length; i2 < len; i2++) {
    const chCode = str.charCodeAt(i2);
    if (chCode !== 32 && chCode !== 9) {
      return i2;
    }
  }
  return -1;
}
function $Pf(str, start = 0, end = str.length) {
  for (let i2 = start; i2 < end; i2++) {
    const chCode = str.charCodeAt(i2);
    if (chCode !== 32 && chCode !== 9) {
      return str.substring(start, i2);
    }
  }
  return str.substring(start, end);
}
function $Qf(str, startIndex = str.length - 1) {
  for (let i2 = startIndex; i2 >= 0; i2--) {
    const chCode = str.charCodeAt(i2);
    if (chCode !== 32 && chCode !== 9) {
      return i2;
    }
  }
  return -1;
}
function $Rf(str) {
  const idx = $Of(str);
  if (idx === -1) {
    return str.length;
  }
  return idx;
}
function $Sf(str, search2, replacer2) {
  const parts = [];
  let last = 0;
  for (const match of str.matchAll(search2)) {
    parts.push(str.slice(last, match.index));
    if (match.index === void 0) {
      throw new Error("match.index should be defined");
    }
    last = match.index + match[0].length;
    parts.push(replacer2(match[0], ...match.slice(1), match.index, str, match.groups));
  }
  parts.push(str.slice(last));
  return Promise.all(parts).then((p) => p.join(""));
}
function $Tf(a, b) {
  if (a < b) {
    return -1;
  } else if (a > b) {
    return 1;
  } else {
    return 0;
  }
}
function $Uf(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 $Vf(a, b) {
  return $Wf(a, b, 0, a.length, 0, b.length);
}
function $Wf(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 $Uf(a.toLowerCase(), b.toLowerCase(), aStart, aEnd, bStart, bEnd);
    }
    if ($Yf(codeA)) {
      codeA -= 32;
    }
    if ($Yf(codeB)) {
      codeB -= 32;
    }
    const diff3 = codeA - codeB;
    if (diff3 === 0) {
      continue;
    }
    return diff3;
  }
  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 >= 48 && code <= 57;
}
function $Yf(code) {
  return code >= 97 && code <= 122;
}
function $Zf(code) {
  return code >= 65 && code <= 90;
}
function $1f(a, b) {
  return a.length === b.length && $Wf(a, b) === 0;
}
function $2f(str, candidate) {
  const candidateLength = candidate.length;
  if (candidate.length > str.length) {
    return false;
  }
  return $Wf(str, candidate, 0, candidateLength) === 0;
}
function $3f(a, b) {
  const len = Math.min(a.length, b.length);
  let i2;
  for (i2 = 0; i2 < len; i2++) {
    if (a.charCodeAt(i2) !== b.charCodeAt(i2)) {
      return i2;
    }
  }
  return len;
}
function $4f(a, b) {
  const len = Math.min(a.length, b.length);
  let i2;
  const aLastIndex = a.length - 1;
  const bLastIndex = b.length - 1;
  for (i2 = 0; i2 < len; i2++) {
    if (a.charCodeAt(aLastIndex - i2) !== b.charCodeAt(bLastIndex - i2)) {
      return i2;
    }
  }
  return len;
}
function $5f(charCode) {
  return 55296 <= charCode && charCode <= 56319;
}
function $6f(charCode) {
  return 56320 <= charCode && charCode <= 57343;
}
function $7f(highSurrogate, lowSurrogate) {
  return (highSurrogate - 55296 << 10) + (lowSurrogate - 56320) + 65536;
}
function $8f(str, len, offset) {
  const charCode = str.charCodeAt(offset);
  if ($5f(charCode) && offset + 1 < len) {
    const nextCharCode = str.charCodeAt(offset + 1);
    if ($6f(nextCharCode)) {
      return $7f(charCode, nextCharCode);
    }
  }
  return charCode;
}
function getPrevCodePoint(str, offset) {
  const charCode = str.charCodeAt(offset - 1);
  if ($6f(charCode) && offset > 1) {
    const prevCharCode = str.charCodeAt(offset - 2);
    if ($5f(prevCharCode)) {
      return $7f(prevCharCode, charCode);
    }
  }
  return charCode;
}
var $9f = class {
  get offset() {
    return this.e;
  }
  constructor(str, offset = 0) {
    this.c = str;
    this.d = str.length;
    this.e = offset;
  }
  setOffset(offset) {
    this.e = offset;
  }
  prevCodePoint() {
    const codePoint = getPrevCodePoint(this.c, this.e);
    this.e -= codePoint >= 65536 ? 2 : 1;
    return codePoint;
  }
  nextCodePoint() {
    const codePoint = $8f(this.c, this.d, this.e);
    this.e += codePoint >= 65536 ? 2 : 1;
    return codePoint;
  }
  eol() {
    return this.e >= this.d;
  }
};
var $0f = class {
  get offset() {
    return this.c.offset;
  }
  constructor(str, offset = 0) {
    this.c = new $9f(str, offset);
  }
  nextGraphemeLength() {
    const graphemeBreakTree = GraphemeBreakTree.getInstance();
    const iterator = this.c;
    const initialOffset = iterator.offset;
    let graphemeBreakType = graphemeBreakTree.getGraphemeBreakType(iterator.nextCodePoint());
    while (!iterator.eol()) {
      const offset = iterator.offset;
      const nextGraphemeBreakType = graphemeBreakTree.getGraphemeBreakType(iterator.nextCodePoint());
      if (breakBetweenGraphemeBreakType(graphemeBreakType, nextGraphemeBreakType)) {
        iterator.setOffset(offset);
        break;
      }
      graphemeBreakType = nextGraphemeBreakType;
    }
    return iterator.offset - initialOffset;
  }
  prevGraphemeLength() {
    const graphemeBreakTree = GraphemeBreakTree.getInstance();
    const iterator = this.c;
    const initialOffset = iterator.offset;
    let graphemeBreakType = graphemeBreakTree.getGraphemeBreakType(iterator.prevCodePoint());
    while (iterator.offset > 0) {
      const offset = iterator.offset;
      const prevGraphemeBreakType = graphemeBreakTree.getGraphemeBreakType(iterator.prevCodePoint());
      if (breakBetweenGraphemeBreakType(prevGraphemeBreakType, graphemeBreakType)) {
        iterator.setOffset(offset);
        break;
      }
      graphemeBreakType = prevGraphemeBreakType;
    }
    return initialOffset - iterator.offset;
  }
  eol() {
    return this.c.eol();
  }
};
function $$f(str, initialOffset) {
  const iterator = new $0f(str, initialOffset);
  return iterator.nextGraphemeLength();
}
function $_f(str, initialOffset) {
  const iterator = new $0f(str, initialOffset);
  return iterator.prevGraphemeLength();
}
function $ag(str, offset) {
  if (offset > 0 && $6f(str.charCodeAt(offset))) {
    offset--;
  }
  const endOffset = offset + $$f(str, offset);
  const startOffset = endOffset - $_f(str, endOffset);
  return [startOffset, endOffset];
}
var CONTAINS_RTL = void 0;
function makeContainsRtl() {
  return /(?:[\u05BE\u05C0\u05C3\u05C6\u05D0-\u05F4\u0608\u060B\u060D\u061B-\u064A\u066D-\u066F\u0671-\u06D5\u06E5\u06E6\u06EE\u06EF\u06FA-\u0710\u0712-\u072F\u074D-\u07A5\u07B1-\u07EA\u07F4\u07F5\u07FA\u07FE-\u0815\u081A\u0824\u0828\u0830-\u0858\u085E-\u088E\u08A0-\u08C9\u200F\uFB1D\uFB1F-\uFB28\uFB2A-\uFD3D\uFD50-\uFDC7\uFDF0-\uFDFC\uFE70-\uFEFC]|\uD802[\uDC00-\uDD1B\uDD20-\uDE00\uDE10-\uDE35\uDE40-\uDEE4\uDEEB-\uDF35\uDF40-\uDFFF]|\uD803[\uDC00-\uDD23\uDE80-\uDEA9\uDEAD-\uDF45\uDF51-\uDF81\uDF86-\uDFF6]|\uD83A[\uDC00-\uDCCF\uDD00-\uDD43\uDD4B-\uDFFF]|\uD83B[\uDC00-\uDEBB])/;
}
function $cg(str) {
  if (!CONTAINS_RTL) {
    CONTAINS_RTL = makeContainsRtl();
  }
  return CONTAINS_RTL.test(str);
}
var IS_BASIC_ASCII = /^[\t\n\r\x20-\x7E]*$/;
function $dg(str) {
  return IS_BASIC_ASCII.test(str);
}
var $eg = /[\u2028\u2029]/;
function $fg(str) {
  return $eg.test(str);
}
function $gg(charCode) {
  return charCode >= 11904 && charCode <= 55215 || charCode >= 63744 && charCode <= 64255 || charCode >= 65281 && charCode <= 65374;
}
function $hg(x) {
  return x >= 127462 && x <= 127487 || x === 8986 || x === 8987 || x === 9200 || x === 9203 || x >= 9728 && x <= 10175 || x === 11088 || x === 11093 || x >= 127744 && x <= 128591 || x >= 128640 && x <= 128764 || x >= 128992 && x <= 129008 || x >= 129280 && x <= 129535 || x >= 129648 && x <= 129782;
}
function $ig(text2, n, prefix = "") {
  const trimmed = text2.trimStart();
  if (trimmed.length < n) {
    return trimmed;
  }
  const re = /\b/g;
  let i2 = 0;
  while (re.test(trimmed)) {
    if (trimmed.length - re.lastIndex < n) {
      break;
    }
    i2 = re.lastIndex;
    re.lastIndex += 1;
  }
  if (i2 === 0) {
    return trimmed;
  }
  return prefix + trimmed.substring(i2).trimStart();
}
var CSI_SEQUENCE = /(?:(?:\x1b\[|\x9B)[=?>!]?[\d;:]*["$#'* ]?[a-zA-Z@^`{}|~])|(:?\x1b\].*?\x07)/g;
function* $jg(str) {
  let last = 0;
  for (const match of str.matchAll(CSI_SEQUENCE)) {
    if (last !== match.index) {
      yield { isCode: false, str: str.substring(last, match.index) };
    }
    yield { isCode: true, str: match[0] };
    last = match.index + match[0].length;
  }
  if (last !== str.length) {
    yield { isCode: false, str: str.substring(last) };
  }
}
function $kg(str) {
  if (str) {
    str = str.replace(CSI_SEQUENCE, "");
  }
  return str;
}
var PROMPT_NON_PRINTABLE = /\\\[.*?\\\]/g;
function $lg(str) {
  return $kg(str).replace(PROMPT_NON_PRINTABLE, "");
}
var $mg = String.fromCharCode(
  65279
  /* CharCode.UTF8_BOM */
);
function $ng(str) {
  return !!(str && str.length > 0 && str.charCodeAt(0) === 65279);
}
function $pg(target, query) {
  if (!target || !query) {
    return false;
  }
  if (target.length < query.length) {
    return false;
  }
  const queryLen = query.length;
  const targetLower = target.toLowerCase();
  let index = 0;
  let lastIndexOf = -1;
  while (index < queryLen) {
    const indexOf = targetLower.indexOf(query[index], lastIndexOf + 1);
    if (indexOf < 0) {
      return false;
    }
    lastIndexOf = indexOf;
    index++;
  }
  return true;
}
function $qg(target, ignoreEscapedChars = false) {
  if (!target) {
    return false;
  }
  if (ignoreEscapedChars) {
    target = target.replace(/\\./g, "");
  }
  return target.toLowerCase() !== target;
}
function $rg(str) {
  return str.charAt(0).toUpperCase() + str.slice(1);
}
function $sg(str, n = 1) {
  if (n === 0) {
    return "";
  }
  let idx = -1;
  do {
    idx = str.indexOf("\n", idx + 1);
    n--;
  } while (n > 0 && idx >= 0);
  if (idx === -1) {
    return str;
  }
  if (str[idx - 1] === "\r") {
    idx--;
  }
  return str.substr(0, idx);
}
function $tg(n) {
  const LETTERS_CNT = 90 - 65 + 1;
  n = n % (2 * LETTERS_CNT);
  if (n < LETTERS_CNT) {
    return String.fromCharCode(97 + n);
  }
  return String.fromCharCode(65 + n - LETTERS_CNT);
}
function breakBetweenGraphemeBreakType(breakTypeA, breakTypeB) {
  if (breakTypeA === 0) {
    return breakTypeB !== 5 && breakTypeB !== 7;
  }
  if (breakTypeA === 2) {
    if (breakTypeB === 3) {
      return false;
    }
  }
  if (breakTypeA === 4 || breakTypeA === 2 || breakTypeA === 3) {
    return true;
  }
  if (breakTypeB === 4 || breakTypeB === 2 || breakTypeB === 3) {
    return true;
  }
  if (breakTypeA === 8) {
    if (breakTypeB === 8 || breakTypeB === 9 || breakTypeB === 11 || breakTypeB === 12) {
      return false;
    }
  }
  if (breakTypeA === 11 || breakTypeA === 9) {
    if (breakTypeB === 9 || breakTypeB === 10) {
      return false;
    }
  }
  if (breakTypeA === 12 || breakTypeA === 10) {
    if (breakTypeB === 10) {
      return false;
    }
  }
  if (breakTypeB === 5 || breakTypeB === 13) {
    return false;
  }
  if (breakTypeB === 7) {
    return false;
  }
  if (breakTypeA === 1) {
    return false;
  }
  if (breakTypeA === 13 && breakTypeB === 14) {
    return false;
  }
  if (breakTypeA === 6 && breakTypeB === 6) {
    return false;
  }
  return true;
}
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]");
}
function $vg(offset, str) {
  if (offset === 0) {
    return 0;
  }
  const emojiOffset = getOffsetBeforeLastEmojiComponent(offset, str);
  if (emojiOffset !== void 0) {
    return emojiOffset;
  }
  const iterator = new $9f(str, offset);
  iterator.prevCodePoint();
  return iterator.offset;
}
function getOffsetBeforeLastEmojiComponent(initialOffset, str) {
  const iterator = new $9f(str, initialOffset);
  let codePoint = iterator.prevCodePoint();
  while (isEmojiModifier(codePoint) || codePoint === 65039 || codePoint === 8419) {
    if (iterator.offset === 0) {
      return void 0;
    }
    codePoint = iterator.prevCodePoint();
  }
  if (!$hg(codePoint)) {
    return void 0;
  }
  let resultOffset = iterator.offset;
  if (resultOffset > 0) {
    const optionalZwjCodePoint = iterator.prevCodePoint();
    if (optionalZwjCodePoint === 8205) {
      resultOffset = iterator.offset;
    }
  }
  return resultOffset;
}
function isEmojiModifier(codePoint) {
  return 127995 <= codePoint && codePoint <= 127999;
}
var CodePoint;
(function(CodePoint2) {
  CodePoint2[CodePoint2["zwj"] = 8205] = "zwj";
  CodePoint2[CodePoint2["emojiVariantSelector"] = 65039] = "emojiVariantSelector";
  CodePoint2[CodePoint2["enclosingKeyCap"] = 8419] = "enclosingKeyCap";
})(CodePoint || (CodePoint = {}));
var $wg = "\xA0";
var $xg = class _$xg {
  static {
    this.c = new $sf(() => {
      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 $qf({ getCacheKey: JSON.stringify }, (locales) => {
      function arrayToMap(arr) {
        const result = /* @__PURE__ */ new Map();
        for (let i2 = 0; i2 < arr.length; i2 += 2) {
          result.set(arr[i2], arr[i2 + 1]);
        }
        return result;
      }
      function mergeMaps(map1, map2) {
        const result = new Map(map1);
        for (const [key2, value] of map2) {
          result.set(key2, value);
        }
        return result;
      }
      function intersectMaps(map1, map2) {
        if (!map1) {
          return map2;
        }
        const result = /* @__PURE__ */ new Map();
        for (const [key2, value] of map1) {
          if (map2.has(key2)) {
            result.set(key2, 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 _$xg(map);
    });
  }
  static getInstance(locales) {
    return _$xg.d.get(Array.from(locales));
  }
  static {
    this.e = new $sf(() => Object.keys(_$xg.c.value).filter((k) => !k.startsWith("_")));
  }
  static getLocales() {
    return _$xg.e.value;
  }
  constructor(f) {
    this.f = f;
  }
  isAmbiguous(codePoint) {
    return this.f.has(codePoint);
  }
  containsAmbiguousCharacter(str) {
    for (let i2 = 0; i2 < str.length; i2++) {
      const codePoint = str.codePointAt(i2);
      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 $yg = class _$yg {
  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(_$yg.c());
    }
    return this.d;
  }
  static isInvisibleCharacter(codePoint) {
    return _$yg.e().has(codePoint);
  }
  static containsInvisibleCharacter(str) {
    for (let i2 = 0; i2 < str.length; i2++) {
      const codePoint = str.codePointAt(i2);
      if (typeof codePoint === "number" && _$yg.isInvisibleCharacter(codePoint)) {
        return true;
      }
    }
    return false;
  }
  static get codePoints() {
    return _$yg.e();
  }
};

// out-build/vs/base/common/network.js
var Schemas;
(function(Schemas3) {
  Schemas3.inMemory = "inmemory";
  Schemas3.vscode = "vscode";
  Schemas3.internal = "private";
  Schemas3.walkThrough = "walkThrough";
  Schemas3.walkThroughSnippet = "walkThroughSnippet";
  Schemas3.http = "http";
  Schemas3.https = "https";
  Schemas3.file = "file";
  Schemas3.mailto = "mailto";
  Schemas3.untitled = "untitled";
  Schemas3.data = "data";
  Schemas3.command = "command";
  Schemas3.vscodeRemote = "vscode-remote";
  Schemas3.vscodeRemoteResource = "vscode-remote-resource";
  Schemas3.vscodeManagedRemoteResource = "vscode-managed-remote-resource";
  Schemas3.vscodeUserData = "vscode-userdata";
  Schemas3.vscodeCustomEditor = "vscode-custom-editor";
  Schemas3.vscodeNotebookCell = "vscode-notebook-cell";
  Schemas3.vscodeNotebookCellMetadata = "vscode-notebook-cell-metadata";
  Schemas3.vscodeNotebookCellMetadataDiff = "vscode-notebook-cell-metadata-diff";
  Schemas3.vscodeNotebookCellOutput = "vscode-notebook-cell-output";
  Schemas3.vscodeNotebookCellOutputDiff = "vscode-notebook-cell-output-diff";
  Schemas3.vscodeNotebookMetadata = "vscode-notebook-metadata";
  Schemas3.vscodeInteractiveInput = "vscode-interactive-input";
  Schemas3.vscodeSettings = "vscode-settings";
  Schemas3.vscodeWorkspaceTrust = "vscode-workspace-trust";
  Schemas3.vscodeTerminal = "vscode-terminal";
  Schemas3.vscodeChatCodeBlock = "vscode-chat-code-block";
  Schemas3.vscodeChatCodeCompareBlock = "vscode-chat-code-compare-block";
  Schemas3.vscodeChatSesssion = "vscode-chat-editor";
  Schemas3.webviewPanel = "webview-panel";
  Schemas3.vscodeWebview = "vscode-webview";
  Schemas3.extension = "extension";
  Schemas3.vscodeFileResource = "vscode-file";
  Schemas3.tmp = "tmp";
  Schemas3.vsls = "vsls";
  Schemas3.vscodeSourceControl = "vscode-scm";
  Schemas3.commentsInput = "comment";
  Schemas3.codeSetting = "code-setting";
  Schemas3.outputChannel = "output";
  Schemas3.accessibleView = "accessible-view";
})(Schemas || (Schemas = {}));
function $0g(target, scheme) {
  if (URI.isUri(target)) {
    return $1f(target.scheme, scheme);
  } else {
    return $2f(target, scheme + ":");
  }
}
function $$g(target, ...schemes) {
  return schemes.some((scheme) => $0g(target, scheme));
}
var $_g = "vscode-tkn";
var $ah = "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(schema9) {
    this.d = schema9;
  }
  setDelegate(delegate) {
    this.e = delegate;
  }
  setServerRootPath(product2, serverBasePath) {
    this.f = $ch(product2, serverBasePath);
  }
  getServerRootPath() {
    return this.f;
  }
  get g() {
    return $kc.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) {
        $gb(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 += `&${$ah}=${encodeURIComponent(connectionToken)}`;
    }
    return URI.from({
      scheme: $r ? this.d : Schemas.vscodeRemoteResource,
      authority: `${host}:${port}`,
      path: $r ? (window.location.pathname + "/" + this.g).replace(/\/\/+/g, "/") : this.g,
      query
    });
  }
};
var $bh = new RemoteAuthoritiesImpl();
function $ch(product2, basePath) {
  return $kc.join(basePath ?? "/", `${product2.quality ?? "oss"}-${product2.commit ?? "dev"}`);
}
var $dh = "vs/../../extensions";
var $eh = "vs/../../node_modules";
var $fh = "vs/../../node_modules.asar";
var $gh = "vs/../../node_modules.asar.unpacked";
var $hh = "vscode-app";
var FileAccessImpl = class _FileAccessImpl {
  static {
    this.a = $hh;
  }
  /**
   * 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 $bh.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 = $nc(rootUriOrPath, uriOrModule);
      return URI.file(modulePath);
    }
    return URI.parse(moduleIdToUrl.toUrl(uriOrModule));
  }
};
var $ih = 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/types.js
function $zg(str) {
  return typeof str === "string";
}
function $Ag(value) {
  return Array.isArray(value) && value.every((elem) => $zg(elem));
}
function $Bg(obj) {
  return typeof obj === "object" && obj !== null && !Array.isArray(obj) && !(obj instanceof RegExp) && !(obj instanceof Date);
}
function $Cg(obj) {
  const TypedArray = Object.getPrototypeOf(Uint8Array);
  return typeof obj === "object" && obj instanceof TypedArray;
}
function $Dg(obj) {
  return typeof obj === "number" && !isNaN(obj);
}
function $Eg(obj) {
  return !!obj && typeof obj[Symbol.iterator] === "function";
}
function $Fg(obj) {
  return obj === true || obj === false;
}
function $Gg(obj) {
  return typeof obj === "undefined";
}
function $Hg(arg) {
  return !$Ig(arg);
}
function $Ig(obj) {
  return $Gg(obj) || obj === null;
}
function $Jg(condition, type) {
  if (!condition) {
    throw new Error(type ? `Unexpected type, expected '${type}'` : "Unexpected type");
  }
}
function $Kg(arg) {
  if ($Ig(arg)) {
    throw new Error("Assertion Failed: argument is undefined or null");
  }
  return arg;
}
function $Lg(...args2) {
  const result = [];
  for (let i2 = 0; i2 < args2.length; i2++) {
    const arg = args2[i2];
    if ($Ig(arg)) {
      throw new Error(`Assertion Failed: argument at index ${i2} is undefined or null`);
    }
    result.push(arg);
  }
  return result;
}
var hasOwnProperty = Object.prototype.hasOwnProperty;
function $Mg(obj) {
  if (!$Bg(obj)) {
    return false;
  }
  for (const key2 in obj) {
    if (hasOwnProperty.call(obj, key2)) {
      return false;
    }
  }
  return true;
}
function $Ng(obj) {
  return typeof obj === "function";
}
function $Og(...objects) {
  return objects.length > 0 && objects.every($Ng);
}
function $Pg(args2, constraints) {
  const len = Math.min(args2.length, constraints.length);
  for (let i2 = 0; i2 < len; i2++) {
    $Qg(args2[i2], constraints[i2]);
  }
}
function $Qg(arg, constraint) {
  if ($zg(constraint)) {
    if (typeof arg !== constraint) {
      throw new Error(`argument does not match constraint: typeof ${constraint}`);
    }
  } else if ($Ng(constraint)) {
    try {
      if (arg instanceof constraint) {
        return;
      }
    } catch {
    }
    if (!$Ig(arg) && arg.constructor === constraint) {
      return;
    }
    if (constraint.length === 1 && constraint.call(void 0, arg) === true) {
      return;
    }
    throw new Error(`argument does not match one of these constraints: arg instanceof constraint, arg.constructor === constraint, nor constraint(arg) === true`);
  }
}
function $Rg(x) {
  return x;
}

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

// out-build/vs/base/common/resources.js
function $jh(uri) {
  return $Ac(uri, true);
}
var $kh = class {
  constructor(a) {
    this.a = a;
  }
  compare(uri1, uri2, ignoreFragment = false) {
    if (uri1 === uri2) {
      return 0;
    }
    return $Tf(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 $Zg($jh(base), $jh(parentCandidate), this.a(base)) && base.query === parentCandidate.query && (ignoreFragment || base.fragment === parentCandidate.fragment);
      }
      if ($Ah(base.authority, parentCandidate.authority)) {
        return $Zg(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 $sh(resource) || resource.authority;
  }
  basename(resource) {
    return $kc.basename(resource.path);
  }
  extname(resource) {
    return $kc.extname(resource.path);
  }
  dirname(resource) {
    if (resource.path.length === 0) {
      return resource;
    }
    let dirname;
    if (resource.scheme === Schemas.file) {
      dirname = URI.file($qc($jh(resource))).path;
    } else {
      dirname = $kc.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($lc($jh(resource))).path;
    } else {
      normalizedPath = $kc.normalize(resource.path);
    }
    return resource.with({
      path: normalizedPath
    });
  }
  relativePath(from, to) {
    if (from.scheme !== to.scheme || !$Ah(from.authority, to.authority)) {
      return void 0;
    }
    if (from.scheme === Schemas.file) {
      const relativePath = $pc($jh(from), $jh(to));
      return $l ? $Tg(relativePath) : relativePath;
    }
    let fromPath = from.path || "/";
    const toPath = to.path || "/";
    if (this.a(from)) {
      let i2 = 0;
      for (const len = Math.min(fromPath.length, toPath.length); i2 < len; i2++) {
        if (fromPath.charCodeAt(i2) !== toPath.charCodeAt(i2)) {
          if (fromPath.charAt(i2).toLowerCase() !== toPath.charAt(i2).toLowerCase()) {
            break;
          }
        }
      }
      fromPath = toPath.substr(0, i2) + fromPath.substr(i2);
    }
    return $kc.relative(fromPath, toPath);
  }
  resolvePath(base, path) {
    if (base.scheme === Schemas.file) {
      const newURI = URI.file($oc($jh(base), path));
      return base.with({
        authority: newURI.authority,
        path: newURI.path
      });
    }
    path = $Ug(path);
    return base.with({
      path: $kc.resolve(base.path, path)
    });
  }
  // --- misc
  isAbsolutePath(resource) {
    return !!resource.path && resource.path[0] === "/";
  }
  isEqualAuthority(a1, a2) {
    return a1 === a2 || a1 !== void 0 && a2 !== void 0 && $1f(a1, a2);
  }
  hasTrailingPathSeparator(resource, sep2 = sep) {
    if (resource.scheme === Schemas.file) {
      const fsp = $jh(resource);
      return fsp.length > $Vg(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 ($Bh(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 = $jh(resource);
      isRootSep = fsp !== void 0 && fsp.length === $Vg(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 && !$Bh(resource, sep2)) {
      return resource.with({ path: resource.path + "/" });
    }
    return resource;
  }
};
var $lh = new $kh(() => false);
var $mh = new $kh((uri) => {
  return uri.scheme === Schemas.file ? !$n : true;
});
var $nh = new $kh((_) => true);
var $oh = $lh.isEqual.bind($lh);
var $ph = $lh.isEqualOrParent.bind($lh);
var $qh = $lh.getComparisonKey.bind($lh);
var $rh = $lh.basenameOrAuthority.bind($lh);
var $sh = $lh.basename.bind($lh);
var $th = $lh.extname.bind($lh);
var $uh = $lh.dirname.bind($lh);
var $vh = $lh.joinPath.bind($lh);
var $wh = $lh.normalizePath.bind($lh);
var $xh = $lh.relativePath.bind($lh);
var $yh = $lh.resolvePath.bind($lh);
var $zh = $lh.isAbsolutePath.bind($lh);
var $Ah = $lh.isEqualAuthority.bind($lh);
var $Bh = $lh.hasTrailingPathSeparator.bind($lh);
var $Ch = $lh.removeTrailingPathSeparator.bind($lh);
var $Dh = $lh.addTrailingPathSeparator.bind($lh);
function $Eh(items, resourceAccessor) {
  const distinctParents = [];
  for (let i2 = 0; i2 < items.length; i2++) {
    const candidateResource = resourceAccessor(items[i2]);
    if (items.some((otherItem, index) => {
      if (index === i2) {
        return false;
      }
      return $ph(candidateResource, resourceAccessor(otherItem));
    })) {
      continue;
    }
    distinctParents.push(items[i2]);
  }
  return distinctParents;
}
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 [key2, value] = property.split(":");
      if (key2 && value) {
        metadata.set(key2, 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 = {}));
function $Fh(resource, authority, localScheme) {
  if (authority) {
    let path = resource.path;
    if (path && path[0] !== $kc.sep) {
      path = $kc.sep + path;
    }
    return resource.with({ scheme: localScheme, authority, path });
  }
  return resource.with({ scheme: localScheme });
}

// out-build/vs/platform/product/common/product.js
var product;
var vscodeGlobal2 = globalThis.vscode;
if (typeof vscodeGlobal2 !== "undefined" && typeof vscodeGlobal2.context !== "undefined") {
  const configuration2 = vscodeGlobal2.context.configuration();
  if (configuration2) {
    product = configuration2.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
    });
  }
  if (env["EXTENSIONS_GALLERY"]) {
    Object.assign(product, {
      extensionsGallery: JSON.parse(env["EXTENSIONS_GALLERY"])
    });
  }
} else {
  product = { "nameShort": "Code - OSS with Posit Workbench", "nameLong": "Code - OSS with Posit Workbench", "applicationName": "code-server", "dataFolderName": ".vscode-server", "win32MutexName": "vscodeoss", "licenseName": "MIT", "serverLicenseUrl": "https://posit.co/about/eula/", "licenseUrl": "https://posit.co/about/eula/", "serverGreeting": [], "serverLicense": [], "serverLicensePrompt": "", "serverApplicationName": "vscode-server", "serverDataFolderName": ".vscode-server", "tunnelApplicationName": "vscode-tunnel", "win32DirName": "Microsoft Code OSS", "win32NameVersion": "Microsoft Code OSS", "win32RegValueName": "CodeOSS", "win32AppId": "{{F9502347-C9F5-4EBE-8794-75836AAAD88D}", "win32x64AppId": "{{8DA74215-C267-4C6C-A88D-CD657F897B03}", "win32arm64AppId": "{{3AEBF0C8-F733-4AD4-BADE-FDB816D53D7B}", "win32UserAppId": "{{BA70F482-04D8-4BD6-B6C5-976E94C73E13}", "win32x64UserAppId": "{{D4272F45-0AAB-432E-89DE-DBC7DFA87F7D}", "win32arm64UserAppId": "{{B9BE1090-E373-4510-829E-D98C416CB4D9}", "win32AppUserModelId": "Microsoft.CodeOSS", "win32ShellNameShort": "C&ode - OSS", "win32TunnelServiceMutex": "vscodeoss-tunnelservice", "win32TunnelMutex": "vscodeoss-tunnel", "darwinBundleIdentifier": "com.visualstudio.code.oss", "linuxIconName": "code-oss", "licenseFileName": "LICENSE.txt", "reportIssueUrl": "https://github.com/microsoft/vscode/issues/new", "nodejsRepository": "https://nodejs.org", "urlProtocol": "vscode-server", "webviewContentExternalBaseUrlTemplate": "https://{{uuid}}.vscode-cdn.net/insider/ef65ac1ba57f57f2a3961bfe94aa20481caca4c6/out/vs/workbench/contrib/webview/browser/pre/", "builtInExtensions": [{ "name": "ms-vscode.js-debug-companion", "version": "1.1.3", "sha256": "7380a890787452f14b2db7835dfa94de538caf358ebc263f9d46dd68ac52de93", "repo": "https://github.com/microsoft/vscode-js-debug-companion", "metadata": { "id": "99cb0b7f-7354-4278-b8da-6cc79972169d", "publisherId": { "publisherId": "5f5636e7-69ed-4afe-b5d6-8d231fb3d3ee", "publisherName": "ms-vscode", "displayName": "Microsoft", "flags": "verified" }, "publisherDisplayName": "Microsoft" } }, { "name": "ms-vscode.js-debug", "version": "1.96.0", "sha256": "278cd8b129c133d834a8105d0e0699f2f940c5c159fa5c821c7b9a4f7ffd3581", "repo": "https://github.com/microsoft/vscode-js-debug", "metadata": { "id": "25629058-ddac-4e17-abba-74678e126c5d", "publisherId": { "publisherId": "5f5636e7-69ed-4afe-b5d6-8d231fb3d3ee", "publisherName": "ms-vscode", "displayName": "Microsoft", "flags": "verified" }, "publisherDisplayName": "Microsoft" } }, { "name": "ms-vscode.vscode-js-profile-table", "version": "1.0.10", "sha256": "7361748ddf9fd09d8a2ed1f2a2d7376a2cf9aae708692820b799708385c38e08", "repo": "https://github.com/microsoft/vscode-js-profile-visualizer", "metadata": { "id": "7e52b41b-71ad-457b-ab7e-0620f1fc4feb", "publisherId": { "publisherId": "5f5636e7-69ed-4afe-b5d6-8d231fb3d3ee", "publisherName": "ms-vscode", "displayName": "Microsoft", "flags": "verified" }, "publisherDisplayName": "Microsoft" } }, { "name": "rstudio.rstudio-workbench", "version": "1.5.28", "positUrl": "https://cdn.posit.co/pwb-components/extension", "type": "reh-web", "sha256": "a1052e6cf884977b68883950360d29b394acdbdd2a84f0b17a7cc9887436918f", "metadata": { "publisherDisplayName": "Posit PBC" } }], "extensionsGallery": { "serviceUrl": "https://open-vsx.org/vscode/gallery", "itemUrl": "https://open-vsx.org/vscode/item", "resourceUrlTemplate": "https://open-vsx.org/vscode/asset/{publisher}/{name}/{version}/Microsoft.VisualStudio.Code.WebResources/{path}", "controlUrl": "", "recommendationsUrl": "" }, "linkProtectionTrustedDomains": ["https://open-vsx.org"], "version": "1.96.0", "commit": "b53f4ab975dd2f3b4cf7cd418ed669697450b40a", "date": "2025-02-18T16:54:01.014Z" };
  if (Object.keys(product).length === 0) {
    Object.assign(product, {
      version: "1.95.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/window/common/window.js
var $ws = {
  WIDTH: 400,
  WIDTH_WITH_VERTICAL_PANEL: 600,
  HEIGHT: 270
};
function $ys(uriToOpen) {
  return !!uriToOpen.workspaceUri;
}
function $zs(uriToOpen) {
  return !!uriToOpen.folderUri;
}
function $As(uriToOpen) {
  return !!uriToOpen.fileUri;
}
function $Bs(configurationService) {
  const nativeTitleBarEnabled = $Ds(configurationService);
  const menuBarVisibility = configurationService.getValue("window.menuBarVisibility");
  if (menuBarVisibility === "default" || nativeTitleBarEnabled && menuBarVisibility === "compact" || $m && $p) {
    return "classic";
  } else {
    return menuBarVisibility;
  }
}
var TitleBarSetting;
(function(TitleBarSetting2) {
  TitleBarSetting2["TITLE_BAR_STYLE"] = "window.titleBarStyle";
  TitleBarSetting2["CUSTOM_TITLE_BAR_VISIBILITY"] = "window.customTitleBarVisibility";
})(TitleBarSetting || (TitleBarSetting = {}));
var TitlebarStyle;
(function(TitlebarStyle2) {
  TitlebarStyle2["NATIVE"] = "native";
  TitlebarStyle2["CUSTOM"] = "custom";
})(TitlebarStyle || (TitlebarStyle = {}));
var CustomTitleBarVisibility;
(function(CustomTitleBarVisibility2) {
  CustomTitleBarVisibility2["AUTO"] = "auto";
  CustomTitleBarVisibility2["WINDOWED"] = "windowed";
  CustomTitleBarVisibility2["NEVER"] = "never";
})(CustomTitleBarVisibility || (CustomTitleBarVisibility = {}));
function $Cs(configurationService, titleBarStyle) {
  return true;
}
function $Ds(configurationService, titleBarStyle) {
  if (!titleBarStyle) {
    titleBarStyle = $Es(configurationService);
  }
  return titleBarStyle === "native";
}
function $Es(configurationService) {
  if ($r) {
    return "custom";
  }
  const configuration2 = configurationService.getValue("window");
  if (configuration2) {
    const useNativeTabs = $m && configuration2.nativeTabs === true;
    if (useNativeTabs) {
      return "native";
    }
    const useSimpleFullScreen = $m && configuration2.nativeFullScreen === false;
    if (useSimpleFullScreen) {
      return "native";
    }
    const style = configuration2.titleBarStyle;
    if (style === "native" || style === "custom") {
      return style;
    }
  }
  return $n && product_default.quality === "stable" ? "native" : "custom";
}
var $Fs = 35;
function $Gs(configurationService) {
  if ($m || $r) {
    return false;
  }
  if ($Ds(configurationService)) {
    return false;
  }
  if ($n) {
    const setting = configurationService.getValue("window.experimentalControlOverlay");
    if (typeof setting === "boolean") {
      return setting;
    }
  }
  return true;
}

// out-build/vs/base/browser/canIUse.js
var KeyboardSupport;
(function(KeyboardSupport2) {
  KeyboardSupport2[KeyboardSupport2["Always"] = 0] = "Always";
  KeyboardSupport2[KeyboardSupport2["FullScreen"] = 1] = "FullScreen";
  KeyboardSupport2[KeyboardSupport2["None"] = 2] = "None";
})(KeyboardSupport || (KeyboardSupport = {}));
var $5e = {
  clipboard: {
    writeText: $p || document.queryCommandSupported && document.queryCommandSupported("copy") || !!(navigator && navigator.clipboard && navigator.clipboard.writeText),
    readText: $p || !!(navigator && navigator.clipboard && navigator.clipboard.readText)
  },
  keyboard: (() => {
    if ($p || $2e()) {
      return 0;
    }
    if (navigator.keyboard || $Xe) {
      return 1;
    }
    return 2;
  })(),
  // 'ontouchstart' in window always evaluates to true with typescript's modern typings. This causes `window` to be
  // `never` later in `window.navigator`. That's why we need the explicit `window as Window` cast
  touch: "ontouchstart" in $Y || navigator.maxTouchPoints > 0,
  pointerEvents: $Y.PointerEvent && ("ontouchstart" in $Y || navigator.maxTouchPoints > 0)
};

// out-build/vs/base/common/keyCodes.js
var KeyCode;
(function(KeyCode3) {
  KeyCode3[KeyCode3["DependsOnKbLayout"] = -1] = "DependsOnKbLayout";
  KeyCode3[KeyCode3["Unknown"] = 0] = "Unknown";
  KeyCode3[KeyCode3["Backspace"] = 1] = "Backspace";
  KeyCode3[KeyCode3["Tab"] = 2] = "Tab";
  KeyCode3[KeyCode3["Enter"] = 3] = "Enter";
  KeyCode3[KeyCode3["Shift"] = 4] = "Shift";
  KeyCode3[KeyCode3["Ctrl"] = 5] = "Ctrl";
  KeyCode3[KeyCode3["Alt"] = 6] = "Alt";
  KeyCode3[KeyCode3["PauseBreak"] = 7] = "PauseBreak";
  KeyCode3[KeyCode3["CapsLock"] = 8] = "CapsLock";
  KeyCode3[KeyCode3["Escape"] = 9] = "Escape";
  KeyCode3[KeyCode3["Space"] = 10] = "Space";
  KeyCode3[KeyCode3["PageUp"] = 11] = "PageUp";
  KeyCode3[KeyCode3["PageDown"] = 12] = "PageDown";
  KeyCode3[KeyCode3["End"] = 13] = "End";
  KeyCode3[KeyCode3["Home"] = 14] = "Home";
  KeyCode3[KeyCode3["LeftArrow"] = 15] = "LeftArrow";
  KeyCode3[KeyCode3["UpArrow"] = 16] = "UpArrow";
  KeyCode3[KeyCode3["RightArrow"] = 17] = "RightArrow";
  KeyCode3[KeyCode3["DownArrow"] = 18] = "DownArrow";
  KeyCode3[KeyCode3["Insert"] = 19] = "Insert";
  KeyCode3[KeyCode3["Delete"] = 20] = "Delete";
  KeyCode3[KeyCode3["Digit0"] = 21] = "Digit0";
  KeyCode3[KeyCode3["Digit1"] = 22] = "Digit1";
  KeyCode3[KeyCode3["Digit2"] = 23] = "Digit2";
  KeyCode3[KeyCode3["Digit3"] = 24] = "Digit3";
  KeyCode3[KeyCode3["Digit4"] = 25] = "Digit4";
  KeyCode3[KeyCode3["Digit5"] = 26] = "Digit5";
  KeyCode3[KeyCode3["Digit6"] = 27] = "Digit6";
  KeyCode3[KeyCode3["Digit7"] = 28] = "Digit7";
  KeyCode3[KeyCode3["Digit8"] = 29] = "Digit8";
  KeyCode3[KeyCode3["Digit9"] = 30] = "Digit9";
  KeyCode3[KeyCode3["KeyA"] = 31] = "KeyA";
  KeyCode3[KeyCode3["KeyB"] = 32] = "KeyB";
  KeyCode3[KeyCode3["KeyC"] = 33] = "KeyC";
  KeyCode3[KeyCode3["KeyD"] = 34] = "KeyD";
  KeyCode3[KeyCode3["KeyE"] = 35] = "KeyE";
  KeyCode3[KeyCode3["KeyF"] = 36] = "KeyF";
  KeyCode3[KeyCode3["KeyG"] = 37] = "KeyG";
  KeyCode3[KeyCode3["KeyH"] = 38] = "KeyH";
  KeyCode3[KeyCode3["KeyI"] = 39] = "KeyI";
  KeyCode3[KeyCode3["KeyJ"] = 40] = "KeyJ";
  KeyCode3[KeyCode3["KeyK"] = 41] = "KeyK";
  KeyCode3[KeyCode3["KeyL"] = 42] = "KeyL";
  KeyCode3[KeyCode3["KeyM"] = 43] = "KeyM";
  KeyCode3[KeyCode3["KeyN"] = 44] = "KeyN";
  KeyCode3[KeyCode3["KeyO"] = 45] = "KeyO";
  KeyCode3[KeyCode3["KeyP"] = 46] = "KeyP";
  KeyCode3[KeyCode3["KeyQ"] = 47] = "KeyQ";
  KeyCode3[KeyCode3["KeyR"] = 48] = "KeyR";
  KeyCode3[KeyCode3["KeyS"] = 49] = "KeyS";
  KeyCode3[KeyCode3["KeyT"] = 50] = "KeyT";
  KeyCode3[KeyCode3["KeyU"] = 51] = "KeyU";
  KeyCode3[KeyCode3["KeyV"] = 52] = "KeyV";
  KeyCode3[KeyCode3["KeyW"] = 53] = "KeyW";
  KeyCode3[KeyCode3["KeyX"] = 54] = "KeyX";
  KeyCode3[KeyCode3["KeyY"] = 55] = "KeyY";
  KeyCode3[KeyCode3["KeyZ"] = 56] = "KeyZ";
  KeyCode3[KeyCode3["Meta"] = 57] = "Meta";
  KeyCode3[KeyCode3["ContextMenu"] = 58] = "ContextMenu";
  KeyCode3[KeyCode3["F1"] = 59] = "F1";
  KeyCode3[KeyCode3["F2"] = 60] = "F2";
  KeyCode3[KeyCode3["F3"] = 61] = "F3";
  KeyCode3[KeyCode3["F4"] = 62] = "F4";
  KeyCode3[KeyCode3["F5"] = 63] = "F5";
  KeyCode3[KeyCode3["F6"] = 64] = "F6";
  KeyCode3[KeyCode3["F7"] = 65] = "F7";
  KeyCode3[KeyCode3["F8"] = 66] = "F8";
  KeyCode3[KeyCode3["F9"] = 67] = "F9";
  KeyCode3[KeyCode3["F10"] = 68] = "F10";
  KeyCode3[KeyCode3["F11"] = 69] = "F11";
  KeyCode3[KeyCode3["F12"] = 70] = "F12";
  KeyCode3[KeyCode3["F13"] = 71] = "F13";
  KeyCode3[KeyCode3["F14"] = 72] = "F14";
  KeyCode3[KeyCode3["F15"] = 73] = "F15";
  KeyCode3[KeyCode3["F16"] = 74] = "F16";
  KeyCode3[KeyCode3["F17"] = 75] = "F17";
  KeyCode3[KeyCode3["F18"] = 76] = "F18";
  KeyCode3[KeyCode3["F19"] = 77] = "F19";
  KeyCode3[KeyCode3["F20"] = 78] = "F20";
  KeyCode3[KeyCode3["F21"] = 79] = "F21";
  KeyCode3[KeyCode3["F22"] = 80] = "F22";
  KeyCode3[KeyCode3["F23"] = 81] = "F23";
  KeyCode3[KeyCode3["F24"] = 82] = "F24";
  KeyCode3[KeyCode3["NumLock"] = 83] = "NumLock";
  KeyCode3[KeyCode3["ScrollLock"] = 84] = "ScrollLock";
  KeyCode3[KeyCode3["Semicolon"] = 85] = "Semicolon";
  KeyCode3[KeyCode3["Equal"] = 86] = "Equal";
  KeyCode3[KeyCode3["Comma"] = 87] = "Comma";
  KeyCode3[KeyCode3["Minus"] = 88] = "Minus";
  KeyCode3[KeyCode3["Period"] = 89] = "Period";
  KeyCode3[KeyCode3["Slash"] = 90] = "Slash";
  KeyCode3[KeyCode3["Backquote"] = 91] = "Backquote";
  KeyCode3[KeyCode3["BracketLeft"] = 92] = "BracketLeft";
  KeyCode3[KeyCode3["Backslash"] = 93] = "Backslash";
  KeyCode3[KeyCode3["BracketRight"] = 94] = "BracketRight";
  KeyCode3[KeyCode3["Quote"] = 95] = "Quote";
  KeyCode3[KeyCode3["OEM_8"] = 96] = "OEM_8";
  KeyCode3[KeyCode3["IntlBackslash"] = 97] = "IntlBackslash";
  KeyCode3[KeyCode3["Numpad0"] = 98] = "Numpad0";
  KeyCode3[KeyCode3["Numpad1"] = 99] = "Numpad1";
  KeyCode3[KeyCode3["Numpad2"] = 100] = "Numpad2";
  KeyCode3[KeyCode3["Numpad3"] = 101] = "Numpad3";
  KeyCode3[KeyCode3["Numpad4"] = 102] = "Numpad4";
  KeyCode3[KeyCode3["Numpad5"] = 103] = "Numpad5";
  KeyCode3[KeyCode3["Numpad6"] = 104] = "Numpad6";
  KeyCode3[KeyCode3["Numpad7"] = 105] = "Numpad7";
  KeyCode3[KeyCode3["Numpad8"] = 106] = "Numpad8";
  KeyCode3[KeyCode3["Numpad9"] = 107] = "Numpad9";
  KeyCode3[KeyCode3["NumpadMultiply"] = 108] = "NumpadMultiply";
  KeyCode3[KeyCode3["NumpadAdd"] = 109] = "NumpadAdd";
  KeyCode3[KeyCode3["NUMPAD_SEPARATOR"] = 110] = "NUMPAD_SEPARATOR";
  KeyCode3[KeyCode3["NumpadSubtract"] = 111] = "NumpadSubtract";
  KeyCode3[KeyCode3["NumpadDecimal"] = 112] = "NumpadDecimal";
  KeyCode3[KeyCode3["NumpadDivide"] = 113] = "NumpadDivide";
  KeyCode3[KeyCode3["KEY_IN_COMPOSITION"] = 114] = "KEY_IN_COMPOSITION";
  KeyCode3[KeyCode3["ABNT_C1"] = 115] = "ABNT_C1";
  KeyCode3[KeyCode3["ABNT_C2"] = 116] = "ABNT_C2";
  KeyCode3[KeyCode3["AudioVolumeMute"] = 117] = "AudioVolumeMute";
  KeyCode3[KeyCode3["AudioVolumeUp"] = 118] = "AudioVolumeUp";
  KeyCode3[KeyCode3["AudioVolumeDown"] = 119] = "AudioVolumeDown";
  KeyCode3[KeyCode3["BrowserSearch"] = 120] = "BrowserSearch";
  KeyCode3[KeyCode3["BrowserHome"] = 121] = "BrowserHome";
  KeyCode3[KeyCode3["BrowserBack"] = 122] = "BrowserBack";
  KeyCode3[KeyCode3["BrowserForward"] = 123] = "BrowserForward";
  KeyCode3[KeyCode3["MediaTrackNext"] = 124] = "MediaTrackNext";
  KeyCode3[KeyCode3["MediaTrackPrevious"] = 125] = "MediaTrackPrevious";
  KeyCode3[KeyCode3["MediaStop"] = 126] = "MediaStop";
  KeyCode3[KeyCode3["MediaPlayPause"] = 127] = "MediaPlayPause";
  KeyCode3[KeyCode3["LaunchMediaPlayer"] = 128] = "LaunchMediaPlayer";
  KeyCode3[KeyCode3["LaunchMail"] = 129] = "LaunchMail";
  KeyCode3[KeyCode3["LaunchApp2"] = 130] = "LaunchApp2";
  KeyCode3[KeyCode3["Clear"] = 131] = "Clear";
  KeyCode3[KeyCode3["MAX_VALUE"] = 132] = "MAX_VALUE";
})(KeyCode || (KeyCode = {}));
var ScanCode;
(function(ScanCode2) {
  ScanCode2[ScanCode2["DependsOnKbLayout"] = -1] = "DependsOnKbLayout";
  ScanCode2[ScanCode2["None"] = 0] = "None";
  ScanCode2[ScanCode2["Hyper"] = 1] = "Hyper";
  ScanCode2[ScanCode2["Super"] = 2] = "Super";
  ScanCode2[ScanCode2["Fn"] = 3] = "Fn";
  ScanCode2[ScanCode2["FnLock"] = 4] = "FnLock";
  ScanCode2[ScanCode2["Suspend"] = 5] = "Suspend";
  ScanCode2[ScanCode2["Resume"] = 6] = "Resume";
  ScanCode2[ScanCode2["Turbo"] = 7] = "Turbo";
  ScanCode2[ScanCode2["Sleep"] = 8] = "Sleep";
  ScanCode2[ScanCode2["WakeUp"] = 9] = "WakeUp";
  ScanCode2[ScanCode2["KeyA"] = 10] = "KeyA";
  ScanCode2[ScanCode2["KeyB"] = 11] = "KeyB";
  ScanCode2[ScanCode2["KeyC"] = 12] = "KeyC";
  ScanCode2[ScanCode2["KeyD"] = 13] = "KeyD";
  ScanCode2[ScanCode2["KeyE"] = 14] = "KeyE";
  ScanCode2[ScanCode2["KeyF"] = 15] = "KeyF";
  ScanCode2[ScanCode2["KeyG"] = 16] = "KeyG";
  ScanCode2[ScanCode2["KeyH"] = 17] = "KeyH";
  ScanCode2[ScanCode2["KeyI"] = 18] = "KeyI";
  ScanCode2[ScanCode2["KeyJ"] = 19] = "KeyJ";
  ScanCode2[ScanCode2["KeyK"] = 20] = "KeyK";
  ScanCode2[ScanCode2["KeyL"] = 21] = "KeyL";
  ScanCode2[ScanCode2["KeyM"] = 22] = "KeyM";
  ScanCode2[ScanCode2["KeyN"] = 23] = "KeyN";
  ScanCode2[ScanCode2["KeyO"] = 24] = "KeyO";
  ScanCode2[ScanCode2["KeyP"] = 25] = "KeyP";
  ScanCode2[ScanCode2["KeyQ"] = 26] = "KeyQ";
  ScanCode2[ScanCode2["KeyR"] = 27] = "KeyR";
  ScanCode2[ScanCode2["KeyS"] = 28] = "KeyS";
  ScanCode2[ScanCode2["KeyT"] = 29] = "KeyT";
  ScanCode2[ScanCode2["KeyU"] = 30] = "KeyU";
  ScanCode2[ScanCode2["KeyV"] = 31] = "KeyV";
  ScanCode2[ScanCode2["KeyW"] = 32] = "KeyW";
  ScanCode2[ScanCode2["KeyX"] = 33] = "KeyX";
  ScanCode2[ScanCode2["KeyY"] = 34] = "KeyY";
  ScanCode2[ScanCode2["KeyZ"] = 35] = "KeyZ";
  ScanCode2[ScanCode2["Digit1"] = 36] = "Digit1";
  ScanCode2[ScanCode2["Digit2"] = 37] = "Digit2";
  ScanCode2[ScanCode2["Digit3"] = 38] = "Digit3";
  ScanCode2[ScanCode2["Digit4"] = 39] = "Digit4";
  ScanCode2[ScanCode2["Digit5"] = 40] = "Digit5";
  ScanCode2[ScanCode2["Digit6"] = 41] = "Digit6";
  ScanCode2[ScanCode2["Digit7"] = 42] = "Digit7";
  ScanCode2[ScanCode2["Digit8"] = 43] = "Digit8";
  ScanCode2[ScanCode2["Digit9"] = 44] = "Digit9";
  ScanCode2[ScanCode2["Digit0"] = 45] = "Digit0";
  ScanCode2[ScanCode2["Enter"] = 46] = "Enter";
  ScanCode2[ScanCode2["Escape"] = 47] = "Escape";
  ScanCode2[ScanCode2["Backspace"] = 48] = "Backspace";
  ScanCode2[ScanCode2["Tab"] = 49] = "Tab";
  ScanCode2[ScanCode2["Space"] = 50] = "Space";
  ScanCode2[ScanCode2["Minus"] = 51] = "Minus";
  ScanCode2[ScanCode2["Equal"] = 52] = "Equal";
  ScanCode2[ScanCode2["BracketLeft"] = 53] = "BracketLeft";
  ScanCode2[ScanCode2["BracketRight"] = 54] = "BracketRight";
  ScanCode2[ScanCode2["Backslash"] = 55] = "Backslash";
  ScanCode2[ScanCode2["IntlHash"] = 56] = "IntlHash";
  ScanCode2[ScanCode2["Semicolon"] = 57] = "Semicolon";
  ScanCode2[ScanCode2["Quote"] = 58] = "Quote";
  ScanCode2[ScanCode2["Backquote"] = 59] = "Backquote";
  ScanCode2[ScanCode2["Comma"] = 60] = "Comma";
  ScanCode2[ScanCode2["Period"] = 61] = "Period";
  ScanCode2[ScanCode2["Slash"] = 62] = "Slash";
  ScanCode2[ScanCode2["CapsLock"] = 63] = "CapsLock";
  ScanCode2[ScanCode2["F1"] = 64] = "F1";
  ScanCode2[ScanCode2["F2"] = 65] = "F2";
  ScanCode2[ScanCode2["F3"] = 66] = "F3";
  ScanCode2[ScanCode2["F4"] = 67] = "F4";
  ScanCode2[ScanCode2["F5"] = 68] = "F5";
  ScanCode2[ScanCode2["F6"] = 69] = "F6";
  ScanCode2[ScanCode2["F7"] = 70] = "F7";
  ScanCode2[ScanCode2["F8"] = 71] = "F8";
  ScanCode2[ScanCode2["F9"] = 72] = "F9";
  ScanCode2[ScanCode2["F10"] = 73] = "F10";
  ScanCode2[ScanCode2["F11"] = 74] = "F11";
  ScanCode2[ScanCode2["F12"] = 75] = "F12";
  ScanCode2[ScanCode2["PrintScreen"] = 76] = "PrintScreen";
  ScanCode2[ScanCode2["ScrollLock"] = 77] = "ScrollLock";
  ScanCode2[ScanCode2["Pause"] = 78] = "Pause";
  ScanCode2[ScanCode2["Insert"] = 79] = "Insert";
  ScanCode2[ScanCode2["Home"] = 80] = "Home";
  ScanCode2[ScanCode2["PageUp"] = 81] = "PageUp";
  ScanCode2[ScanCode2["Delete"] = 82] = "Delete";
  ScanCode2[ScanCode2["End"] = 83] = "End";
  ScanCode2[ScanCode2["PageDown"] = 84] = "PageDown";
  ScanCode2[ScanCode2["ArrowRight"] = 85] = "ArrowRight";
  ScanCode2[ScanCode2["ArrowLeft"] = 86] = "ArrowLeft";
  ScanCode2[ScanCode2["ArrowDown"] = 87] = "ArrowDown";
  ScanCode2[ScanCode2["ArrowUp"] = 88] = "ArrowUp";
  ScanCode2[ScanCode2["NumLock"] = 89] = "NumLock";
  ScanCode2[ScanCode2["NumpadDivide"] = 90] = "NumpadDivide";
  ScanCode2[ScanCode2["NumpadMultiply"] = 91] = "NumpadMultiply";
  ScanCode2[ScanCode2["NumpadSubtract"] = 92] = "NumpadSubtract";
  ScanCode2[ScanCode2["NumpadAdd"] = 93] = "NumpadAdd";
  ScanCode2[ScanCode2["NumpadEnter"] = 94] = "NumpadEnter";
  ScanCode2[ScanCode2["Numpad1"] = 95] = "Numpad1";
  ScanCode2[ScanCode2["Numpad2"] = 96] = "Numpad2";
  ScanCode2[ScanCode2["Numpad3"] = 97] = "Numpad3";
  ScanCode2[ScanCode2["Numpad4"] = 98] = "Numpad4";
  ScanCode2[ScanCode2["Numpad5"] = 99] = "Numpad5";
  ScanCode2[ScanCode2["Numpad6"] = 100] = "Numpad6";
  ScanCode2[ScanCode2["Numpad7"] = 101] = "Numpad7";
  ScanCode2[ScanCode2["Numpad8"] = 102] = "Numpad8";
  ScanCode2[ScanCode2["Numpad9"] = 103] = "Numpad9";
  ScanCode2[ScanCode2["Numpad0"] = 104] = "Numpad0";
  ScanCode2[ScanCode2["NumpadDecimal"] = 105] = "NumpadDecimal";
  ScanCode2[ScanCode2["IntlBackslash"] = 106] = "IntlBackslash";
  ScanCode2[ScanCode2["ContextMenu"] = 107] = "ContextMenu";
  ScanCode2[ScanCode2["Power"] = 108] = "Power";
  ScanCode2[ScanCode2["NumpadEqual"] = 109] = "NumpadEqual";
  ScanCode2[ScanCode2["F13"] = 110] = "F13";
  ScanCode2[ScanCode2["F14"] = 111] = "F14";
  ScanCode2[ScanCode2["F15"] = 112] = "F15";
  ScanCode2[ScanCode2["F16"] = 113] = "F16";
  ScanCode2[ScanCode2["F17"] = 114] = "F17";
  ScanCode2[ScanCode2["F18"] = 115] = "F18";
  ScanCode2[ScanCode2["F19"] = 116] = "F19";
  ScanCode2[ScanCode2["F20"] = 117] = "F20";
  ScanCode2[ScanCode2["F21"] = 118] = "F21";
  ScanCode2[ScanCode2["F22"] = 119] = "F22";
  ScanCode2[ScanCode2["F23"] = 120] = "F23";
  ScanCode2[ScanCode2["F24"] = 121] = "F24";
  ScanCode2[ScanCode2["Open"] = 122] = "Open";
  ScanCode2[ScanCode2["Help"] = 123] = "Help";
  ScanCode2[ScanCode2["Select"] = 124] = "Select";
  ScanCode2[ScanCode2["Again"] = 125] = "Again";
  ScanCode2[ScanCode2["Undo"] = 126] = "Undo";
  ScanCode2[ScanCode2["Cut"] = 127] = "Cut";
  ScanCode2[ScanCode2["Copy"] = 128] = "Copy";
  ScanCode2[ScanCode2["Paste"] = 129] = "Paste";
  ScanCode2[ScanCode2["Find"] = 130] = "Find";
  ScanCode2[ScanCode2["AudioVolumeMute"] = 131] = "AudioVolumeMute";
  ScanCode2[ScanCode2["AudioVolumeUp"] = 132] = "AudioVolumeUp";
  ScanCode2[ScanCode2["AudioVolumeDown"] = 133] = "AudioVolumeDown";
  ScanCode2[ScanCode2["NumpadComma"] = 134] = "NumpadComma";
  ScanCode2[ScanCode2["IntlRo"] = 135] = "IntlRo";
  ScanCode2[ScanCode2["KanaMode"] = 136] = "KanaMode";
  ScanCode2[ScanCode2["IntlYen"] = 137] = "IntlYen";
  ScanCode2[ScanCode2["Convert"] = 138] = "Convert";
  ScanCode2[ScanCode2["NonConvert"] = 139] = "NonConvert";
  ScanCode2[ScanCode2["Lang1"] = 140] = "Lang1";
  ScanCode2[ScanCode2["Lang2"] = 141] = "Lang2";
  ScanCode2[ScanCode2["Lang3"] = 142] = "Lang3";
  ScanCode2[ScanCode2["Lang4"] = 143] = "Lang4";
  ScanCode2[ScanCode2["Lang5"] = 144] = "Lang5";
  ScanCode2[ScanCode2["Abort"] = 145] = "Abort";
  ScanCode2[ScanCode2["Props"] = 146] = "Props";
  ScanCode2[ScanCode2["NumpadParenLeft"] = 147] = "NumpadParenLeft";
  ScanCode2[ScanCode2["NumpadParenRight"] = 148] = "NumpadParenRight";
  ScanCode2[ScanCode2["NumpadBackspace"] = 149] = "NumpadBackspace";
  ScanCode2[ScanCode2["NumpadMemoryStore"] = 150] = "NumpadMemoryStore";
  ScanCode2[ScanCode2["NumpadMemoryRecall"] = 151] = "NumpadMemoryRecall";
  ScanCode2[ScanCode2["NumpadMemoryClear"] = 152] = "NumpadMemoryClear";
  ScanCode2[ScanCode2["NumpadMemoryAdd"] = 153] = "NumpadMemoryAdd";
  ScanCode2[ScanCode2["NumpadMemorySubtract"] = 154] = "NumpadMemorySubtract";
  ScanCode2[ScanCode2["NumpadClear"] = 155] = "NumpadClear";
  ScanCode2[ScanCode2["NumpadClearEntry"] = 156] = "NumpadClearEntry";
  ScanCode2[ScanCode2["ControlLeft"] = 157] = "ControlLeft";
  ScanCode2[ScanCode2["ShiftLeft"] = 158] = "ShiftLeft";
  ScanCode2[ScanCode2["AltLeft"] = 159] = "AltLeft";
  ScanCode2[ScanCode2["MetaLeft"] = 160] = "MetaLeft";
  ScanCode2[ScanCode2["ControlRight"] = 161] = "ControlRight";
  ScanCode2[ScanCode2["ShiftRight"] = 162] = "ShiftRight";
  ScanCode2[ScanCode2["AltRight"] = 163] = "AltRight";
  ScanCode2[ScanCode2["MetaRight"] = 164] = "MetaRight";
  ScanCode2[ScanCode2["BrightnessUp"] = 165] = "BrightnessUp";
  ScanCode2[ScanCode2["BrightnessDown"] = 166] = "BrightnessDown";
  ScanCode2[ScanCode2["MediaPlay"] = 167] = "MediaPlay";
  ScanCode2[ScanCode2["MediaRecord"] = 168] = "MediaRecord";
  ScanCode2[ScanCode2["MediaFastForward"] = 169] = "MediaFastForward";
  ScanCode2[ScanCode2["MediaRewind"] = 170] = "MediaRewind";
  ScanCode2[ScanCode2["MediaTrackNext"] = 171] = "MediaTrackNext";
  ScanCode2[ScanCode2["MediaTrackPrevious"] = 172] = "MediaTrackPrevious";
  ScanCode2[ScanCode2["MediaStop"] = 173] = "MediaStop";
  ScanCode2[ScanCode2["Eject"] = 174] = "Eject";
  ScanCode2[ScanCode2["MediaPlayPause"] = 175] = "MediaPlayPause";
  ScanCode2[ScanCode2["MediaSelect"] = 176] = "MediaSelect";
  ScanCode2[ScanCode2["LaunchMail"] = 177] = "LaunchMail";
  ScanCode2[ScanCode2["LaunchApp2"] = 178] = "LaunchApp2";
  ScanCode2[ScanCode2["LaunchApp1"] = 179] = "LaunchApp1";
  ScanCode2[ScanCode2["SelectTask"] = 180] = "SelectTask";
  ScanCode2[ScanCode2["LaunchScreenSaver"] = 181] = "LaunchScreenSaver";
  ScanCode2[ScanCode2["BrowserSearch"] = 182] = "BrowserSearch";
  ScanCode2[ScanCode2["BrowserHome"] = 183] = "BrowserHome";
  ScanCode2[ScanCode2["BrowserBack"] = 184] = "BrowserBack";
  ScanCode2[ScanCode2["BrowserForward"] = 185] = "BrowserForward";
  ScanCode2[ScanCode2["BrowserStop"] = 186] = "BrowserStop";
  ScanCode2[ScanCode2["BrowserRefresh"] = 187] = "BrowserRefresh";
  ScanCode2[ScanCode2["BrowserFavorites"] = 188] = "BrowserFavorites";
  ScanCode2[ScanCode2["ZoomToggle"] = 189] = "ZoomToggle";
  ScanCode2[ScanCode2["MailReply"] = 190] = "MailReply";
  ScanCode2[ScanCode2["MailForward"] = 191] = "MailForward";
  ScanCode2[ScanCode2["MailSend"] = 192] = "MailSend";
  ScanCode2[ScanCode2["MAX_VALUE"] = 193] = "MAX_VALUE";
})(ScanCode || (ScanCode = {}));
var KeyCodeStrMap = class {
  constructor() {
    this._keyCodeToStr = [];
    this._strToKeyCode = /* @__PURE__ */ Object.create(null);
  }
  define(keyCode, str) {
    this._keyCodeToStr[keyCode] = str;
    this._strToKeyCode[str.toLowerCase()] = keyCode;
  }
  keyCodeToStr(keyCode) {
    return this._keyCodeToStr[keyCode];
  }
  strToKeyCode(str) {
    return this._strToKeyCode[str.toLowerCase()] || 0;
  }
};
var uiMap = new KeyCodeStrMap();
var userSettingsUSMap = new KeyCodeStrMap();
var userSettingsGeneralMap = new KeyCodeStrMap();
var $6e = new Array(230);
var $7e = {};
var scanCodeIntToStr = [];
var scanCodeStrToInt = /* @__PURE__ */ Object.create(null);
var scanCodeLowerCaseStrToInt = /* @__PURE__ */ Object.create(null);
var $8e = {
  lowerCaseToEnum: (scanCode) => scanCodeLowerCaseStrToInt[scanCode] || 0,
  toEnum: (scanCode) => scanCodeStrToInt[scanCode] || 0,
  toString: (scanCode) => scanCodeIntToStr[scanCode] || "None"
};
var $9e = [];
var $0e = [];
for (let i2 = 0; i2 <= 193; i2++) {
  $9e[i2] = -1;
}
for (let i2 = 0; i2 <= 132; i2++) {
  $0e[i2] = -1;
}
(function() {
  const empty = "";
  const mappings = [
    // immutable, scanCode, scanCodeStr, keyCode, keyCodeStr, eventKeyCode, vkey, usUserSettingsLabel, generalUserSettingsLabel
    [1, 0, "None", 0, "unknown", 0, "VK_UNKNOWN", empty, empty],
    [1, 1, "Hyper", 0, empty, 0, empty, empty, empty],
    [1, 2, "Super", 0, empty, 0, empty, empty, empty],
    [1, 3, "Fn", 0, empty, 0, empty, empty, empty],
    [1, 4, "FnLock", 0, empty, 0, empty, empty, empty],
    [1, 5, "Suspend", 0, empty, 0, empty, empty, empty],
    [1, 6, "Resume", 0, empty, 0, empty, empty, empty],
    [1, 7, "Turbo", 0, empty, 0, empty, empty, empty],
    [1, 8, "Sleep", 0, empty, 0, "VK_SLEEP", empty, empty],
    [1, 9, "WakeUp", 0, empty, 0, empty, empty, empty],
    [0, 10, "KeyA", 31, "A", 65, "VK_A", empty, empty],
    [0, 11, "KeyB", 32, "B", 66, "VK_B", empty, empty],
    [0, 12, "KeyC", 33, "C", 67, "VK_C", empty, empty],
    [0, 13, "KeyD", 34, "D", 68, "VK_D", empty, empty],
    [0, 14, "KeyE", 35, "E", 69, "VK_E", empty, empty],
    [0, 15, "KeyF", 36, "F", 70, "VK_F", empty, empty],
    [0, 16, "KeyG", 37, "G", 71, "VK_G", empty, empty],
    [0, 17, "KeyH", 38, "H", 72, "VK_H", empty, empty],
    [0, 18, "KeyI", 39, "I", 73, "VK_I", empty, empty],
    [0, 19, "KeyJ", 40, "J", 74, "VK_J", empty, empty],
    [0, 20, "KeyK", 41, "K", 75, "VK_K", empty, empty],
    [0, 21, "KeyL", 42, "L", 76, "VK_L", empty, empty],
    [0, 22, "KeyM", 43, "M", 77, "VK_M", empty, empty],
    [0, 23, "KeyN", 44, "N", 78, "VK_N", empty, empty],
    [0, 24, "KeyO", 45, "O", 79, "VK_O", empty, empty],
    [0, 25, "KeyP", 46, "P", 80, "VK_P", empty, empty],
    [0, 26, "KeyQ", 47, "Q", 81, "VK_Q", empty, empty],
    [0, 27, "KeyR", 48, "R", 82, "VK_R", empty, empty],
    [0, 28, "KeyS", 49, "S", 83, "VK_S", empty, empty],
    [0, 29, "KeyT", 50, "T", 84, "VK_T", empty, empty],
    [0, 30, "KeyU", 51, "U", 85, "VK_U", empty, empty],
    [0, 31, "KeyV", 52, "V", 86, "VK_V", empty, empty],
    [0, 32, "KeyW", 53, "W", 87, "VK_W", empty, empty],
    [0, 33, "KeyX", 54, "X", 88, "VK_X", empty, empty],
    [0, 34, "KeyY", 55, "Y", 89, "VK_Y", empty, empty],
    [0, 35, "KeyZ", 56, "Z", 90, "VK_Z", empty, empty],
    [0, 36, "Digit1", 22, "1", 49, "VK_1", empty, empty],
    [0, 37, "Digit2", 23, "2", 50, "VK_2", empty, empty],
    [0, 38, "Digit3", 24, "3", 51, "VK_3", empty, empty],
    [0, 39, "Digit4", 25, "4", 52, "VK_4", empty, empty],
    [0, 40, "Digit5", 26, "5", 53, "VK_5", empty, empty],
    [0, 41, "Digit6", 27, "6", 54, "VK_6", empty, empty],
    [0, 42, "Digit7", 28, "7", 55, "VK_7", empty, empty],
    [0, 43, "Digit8", 29, "8", 56, "VK_8", empty, empty],
    [0, 44, "Digit9", 30, "9", 57, "VK_9", empty, empty],
    [0, 45, "Digit0", 21, "0", 48, "VK_0", empty, empty],
    [1, 46, "Enter", 3, "Enter", 13, "VK_RETURN", empty, empty],
    [1, 47, "Escape", 9, "Escape", 27, "VK_ESCAPE", empty, empty],
    [1, 48, "Backspace", 1, "Backspace", 8, "VK_BACK", empty, empty],
    [1, 49, "Tab", 2, "Tab", 9, "VK_TAB", empty, empty],
    [1, 50, "Space", 10, "Space", 32, "VK_SPACE", empty, empty],
    [0, 51, "Minus", 88, "-", 189, "VK_OEM_MINUS", "-", "OEM_MINUS"],
    [0, 52, "Equal", 86, "=", 187, "VK_OEM_PLUS", "=", "OEM_PLUS"],
    [0, 53, "BracketLeft", 92, "[", 219, "VK_OEM_4", "[", "OEM_4"],
    [0, 54, "BracketRight", 94, "]", 221, "VK_OEM_6", "]", "OEM_6"],
    [0, 55, "Backslash", 93, "\\", 220, "VK_OEM_5", "\\", "OEM_5"],
    [0, 56, "IntlHash", 0, empty, 0, empty, empty, empty],
    // has been dropped from the w3c spec
    [0, 57, "Semicolon", 85, ";", 186, "VK_OEM_1", ";", "OEM_1"],
    [0, 58, "Quote", 95, "'", 222, "VK_OEM_7", "'", "OEM_7"],
    [0, 59, "Backquote", 91, "`", 192, "VK_OEM_3", "`", "OEM_3"],
    [0, 60, "Comma", 87, ",", 188, "VK_OEM_COMMA", ",", "OEM_COMMA"],
    [0, 61, "Period", 89, ".", 190, "VK_OEM_PERIOD", ".", "OEM_PERIOD"],
    [0, 62, "Slash", 90, "/", 191, "VK_OEM_2", "/", "OEM_2"],
    [1, 63, "CapsLock", 8, "CapsLock", 20, "VK_CAPITAL", empty, empty],
    [1, 64, "F1", 59, "F1", 112, "VK_F1", empty, empty],
    [1, 65, "F2", 60, "F2", 113, "VK_F2", empty, empty],
    [1, 66, "F3", 61, "F3", 114, "VK_F3", empty, empty],
    [1, 67, "F4", 62, "F4", 115, "VK_F4", empty, empty],
    [1, 68, "F5", 63, "F5", 116, "VK_F5", empty, empty],
    [1, 69, "F6", 64, "F6", 117, "VK_F6", empty, empty],
    [1, 70, "F7", 65, "F7", 118, "VK_F7", empty, empty],
    [1, 71, "F8", 66, "F8", 119, "VK_F8", empty, empty],
    [1, 72, "F9", 67, "F9", 120, "VK_F9", empty, empty],
    [1, 73, "F10", 68, "F10", 121, "VK_F10", empty, empty],
    [1, 74, "F11", 69, "F11", 122, "VK_F11", empty, empty],
    [1, 75, "F12", 70, "F12", 123, "VK_F12", empty, empty],
    [1, 76, "PrintScreen", 0, empty, 0, empty, empty, empty],
    [1, 77, "ScrollLock", 84, "ScrollLock", 145, "VK_SCROLL", empty, empty],
    [1, 78, "Pause", 7, "PauseBreak", 19, "VK_PAUSE", empty, empty],
    [1, 79, "Insert", 19, "Insert", 45, "VK_INSERT", empty, empty],
    [1, 80, "Home", 14, "Home", 36, "VK_HOME", empty, empty],
    [1, 81, "PageUp", 11, "PageUp", 33, "VK_PRIOR", empty, empty],
    [1, 82, "Delete", 20, "Delete", 46, "VK_DELETE", empty, empty],
    [1, 83, "End", 13, "End", 35, "VK_END", empty, empty],
    [1, 84, "PageDown", 12, "PageDown", 34, "VK_NEXT", empty, empty],
    [1, 85, "ArrowRight", 17, "RightArrow", 39, "VK_RIGHT", "Right", empty],
    [1, 86, "ArrowLeft", 15, "LeftArrow", 37, "VK_LEFT", "Left", empty],
    [1, 87, "ArrowDown", 18, "DownArrow", 40, "VK_DOWN", "Down", empty],
    [1, 88, "ArrowUp", 16, "UpArrow", 38, "VK_UP", "Up", empty],
    [1, 89, "NumLock", 83, "NumLock", 144, "VK_NUMLOCK", empty, empty],
    [1, 90, "NumpadDivide", 113, "NumPad_Divide", 111, "VK_DIVIDE", empty, empty],
    [1, 91, "NumpadMultiply", 108, "NumPad_Multiply", 106, "VK_MULTIPLY", empty, empty],
    [1, 92, "NumpadSubtract", 111, "NumPad_Subtract", 109, "VK_SUBTRACT", empty, empty],
    [1, 93, "NumpadAdd", 109, "NumPad_Add", 107, "VK_ADD", empty, empty],
    [1, 94, "NumpadEnter", 3, empty, 0, empty, empty, empty],
    [1, 95, "Numpad1", 99, "NumPad1", 97, "VK_NUMPAD1", empty, empty],
    [1, 96, "Numpad2", 100, "NumPad2", 98, "VK_NUMPAD2", empty, empty],
    [1, 97, "Numpad3", 101, "NumPad3", 99, "VK_NUMPAD3", empty, empty],
    [1, 98, "Numpad4", 102, "NumPad4", 100, "VK_NUMPAD4", empty, empty],
    [1, 99, "Numpad5", 103, "NumPad5", 101, "VK_NUMPAD5", empty, empty],
    [1, 100, "Numpad6", 104, "NumPad6", 102, "VK_NUMPAD6", empty, empty],
    [1, 101, "Numpad7", 105, "NumPad7", 103, "VK_NUMPAD7", empty, empty],
    [1, 102, "Numpad8", 106, "NumPad8", 104, "VK_NUMPAD8", empty, empty],
    [1, 103, "Numpad9", 107, "NumPad9", 105, "VK_NUMPAD9", empty, empty],
    [1, 104, "Numpad0", 98, "NumPad0", 96, "VK_NUMPAD0", empty, empty],
    [1, 105, "NumpadDecimal", 112, "NumPad_Decimal", 110, "VK_DECIMAL", empty, empty],
    [0, 106, "IntlBackslash", 97, "OEM_102", 226, "VK_OEM_102", empty, empty],
    [1, 107, "ContextMenu", 58, "ContextMenu", 93, empty, empty, empty],
    [1, 108, "Power", 0, empty, 0, empty, empty, empty],
    [1, 109, "NumpadEqual", 0, empty, 0, empty, empty, empty],
    [1, 110, "F13", 71, "F13", 124, "VK_F13", empty, empty],
    [1, 111, "F14", 72, "F14", 125, "VK_F14", empty, empty],
    [1, 112, "F15", 73, "F15", 126, "VK_F15", empty, empty],
    [1, 113, "F16", 74, "F16", 127, "VK_F16", empty, empty],
    [1, 114, "F17", 75, "F17", 128, "VK_F17", empty, empty],
    [1, 115, "F18", 76, "F18", 129, "VK_F18", empty, empty],
    [1, 116, "F19", 77, "F19", 130, "VK_F19", empty, empty],
    [1, 117, "F20", 78, "F20", 131, "VK_F20", empty, empty],
    [1, 118, "F21", 79, "F21", 132, "VK_F21", empty, empty],
    [1, 119, "F22", 80, "F22", 133, "VK_F22", empty, empty],
    [1, 120, "F23", 81, "F23", 134, "VK_F23", empty, empty],
    [1, 121, "F24", 82, "F24", 135, "VK_F24", empty, empty],
    [1, 122, "Open", 0, empty, 0, empty, empty, empty],
    [1, 123, "Help", 0, empty, 0, empty, empty, empty],
    [1, 124, "Select", 0, empty, 0, empty, empty, empty],
    [1, 125, "Again", 0, empty, 0, empty, empty, empty],
    [1, 126, "Undo", 0, empty, 0, empty, empty, empty],
    [1, 127, "Cut", 0, empty, 0, empty, empty, empty],
    [1, 128, "Copy", 0, empty, 0, empty, empty, empty],
    [1, 129, "Paste", 0, empty, 0, empty, empty, empty],
    [1, 130, "Find", 0, empty, 0, empty, empty, empty],
    [1, 131, "AudioVolumeMute", 117, "AudioVolumeMute", 173, "VK_VOLUME_MUTE", empty, empty],
    [1, 132, "AudioVolumeUp", 118, "AudioVolumeUp", 175, "VK_VOLUME_UP", empty, empty],
    [1, 133, "AudioVolumeDown", 119, "AudioVolumeDown", 174, "VK_VOLUME_DOWN", empty, empty],
    [1, 134, "NumpadComma", 110, "NumPad_Separator", 108, "VK_SEPARATOR", empty, empty],
    [0, 135, "IntlRo", 115, "ABNT_C1", 193, "VK_ABNT_C1", empty, empty],
    [1, 136, "KanaMode", 0, empty, 0, empty, empty, empty],
    [0, 137, "IntlYen", 0, empty, 0, empty, empty, empty],
    [1, 138, "Convert", 0, empty, 0, empty, empty, empty],
    [1, 139, "NonConvert", 0, empty, 0, empty, empty, empty],
    [1, 140, "Lang1", 0, empty, 0, empty, empty, empty],
    [1, 141, "Lang2", 0, empty, 0, empty, empty, empty],
    [1, 142, "Lang3", 0, empty, 0, empty, empty, empty],
    [1, 143, "Lang4", 0, empty, 0, empty, empty, empty],
    [1, 144, "Lang5", 0, empty, 0, empty, empty, empty],
    [1, 145, "Abort", 0, empty, 0, empty, empty, empty],
    [1, 146, "Props", 0, empty, 0, empty, empty, empty],
    [1, 147, "NumpadParenLeft", 0, empty, 0, empty, empty, empty],
    [1, 148, "NumpadParenRight", 0, empty, 0, empty, empty, empty],
    [1, 149, "NumpadBackspace", 0, empty, 0, empty, empty, empty],
    [1, 150, "NumpadMemoryStore", 0, empty, 0, empty, empty, empty],
    [1, 151, "NumpadMemoryRecall", 0, empty, 0, empty, empty, empty],
    [1, 152, "NumpadMemoryClear", 0, empty, 0, empty, empty, empty],
    [1, 153, "NumpadMemoryAdd", 0, empty, 0, empty, empty, empty],
    [1, 154, "NumpadMemorySubtract", 0, empty, 0, empty, empty, empty],
    [1, 155, "NumpadClear", 131, "Clear", 12, "VK_CLEAR", empty, empty],
    [1, 156, "NumpadClearEntry", 0, empty, 0, empty, empty, empty],
    [1, 0, empty, 5, "Ctrl", 17, "VK_CONTROL", empty, empty],
    [1, 0, empty, 4, "Shift", 16, "VK_SHIFT", empty, empty],
    [1, 0, empty, 6, "Alt", 18, "VK_MENU", empty, empty],
    [1, 0, empty, 57, "Meta", 91, "VK_COMMAND", empty, empty],
    [1, 157, "ControlLeft", 5, empty, 0, "VK_LCONTROL", empty, empty],
    [1, 158, "ShiftLeft", 4, empty, 0, "VK_LSHIFT", empty, empty],
    [1, 159, "AltLeft", 6, empty, 0, "VK_LMENU", empty, empty],
    [1, 160, "MetaLeft", 57, empty, 0, "VK_LWIN", empty, empty],
    [1, 161, "ControlRight", 5, empty, 0, "VK_RCONTROL", empty, empty],
    [1, 162, "ShiftRight", 4, empty, 0, "VK_RSHIFT", empty, empty],
    [1, 163, "AltRight", 6, empty, 0, "VK_RMENU", empty, empty],
    [1, 164, "MetaRight", 57, empty, 0, "VK_RWIN", empty, empty],
    [1, 165, "BrightnessUp", 0, empty, 0, empty, empty, empty],
    [1, 166, "BrightnessDown", 0, empty, 0, empty, empty, empty],
    [1, 167, "MediaPlay", 0, empty, 0, empty, empty, empty],
    [1, 168, "MediaRecord", 0, empty, 0, empty, empty, empty],
    [1, 169, "MediaFastForward", 0, empty, 0, empty, empty, empty],
    [1, 170, "MediaRewind", 0, empty, 0, empty, empty, empty],
    [1, 171, "MediaTrackNext", 124, "MediaTrackNext", 176, "VK_MEDIA_NEXT_TRACK", empty, empty],
    [1, 172, "MediaTrackPrevious", 125, "MediaTrackPrevious", 177, "VK_MEDIA_PREV_TRACK", empty, empty],
    [1, 173, "MediaStop", 126, "MediaStop", 178, "VK_MEDIA_STOP", empty, empty],
    [1, 174, "Eject", 0, empty, 0, empty, empty, empty],
    [1, 175, "MediaPlayPause", 127, "MediaPlayPause", 179, "VK_MEDIA_PLAY_PAUSE", empty, empty],
    [1, 176, "MediaSelect", 128, "LaunchMediaPlayer", 181, "VK_MEDIA_LAUNCH_MEDIA_SELECT", empty, empty],
    [1, 177, "LaunchMail", 129, "LaunchMail", 180, "VK_MEDIA_LAUNCH_MAIL", empty, empty],
    [1, 178, "LaunchApp2", 130, "LaunchApp2", 183, "VK_MEDIA_LAUNCH_APP2", empty, empty],
    [1, 179, "LaunchApp1", 0, empty, 0, "VK_MEDIA_LAUNCH_APP1", empty, empty],
    [1, 180, "SelectTask", 0, empty, 0, empty, empty, empty],
    [1, 181, "LaunchScreenSaver", 0, empty, 0, empty, empty, empty],
    [1, 182, "BrowserSearch", 120, "BrowserSearch", 170, "VK_BROWSER_SEARCH", empty, empty],
    [1, 183, "BrowserHome", 121, "BrowserHome", 172, "VK_BROWSER_HOME", empty, empty],
    [1, 184, "BrowserBack", 122, "BrowserBack", 166, "VK_BROWSER_BACK", empty, empty],
    [1, 185, "BrowserForward", 123, "BrowserForward", 167, "VK_BROWSER_FORWARD", empty, empty],
    [1, 186, "BrowserStop", 0, empty, 0, "VK_BROWSER_STOP", empty, empty],
    [1, 187, "BrowserRefresh", 0, empty, 0, "VK_BROWSER_REFRESH", empty, empty],
    [1, 188, "BrowserFavorites", 0, empty, 0, "VK_BROWSER_FAVORITES", empty, empty],
    [1, 189, "ZoomToggle", 0, empty, 0, empty, empty, empty],
    [1, 190, "MailReply", 0, empty, 0, empty, empty, empty],
    [1, 191, "MailForward", 0, empty, 0, empty, empty, empty],
    [1, 192, "MailSend", 0, empty, 0, empty, empty, empty],
    // See https://lists.w3.org/Archives/Public/www-dom/2010JulSep/att-0182/keyCode-spec.html
    // If an Input Method Editor is processing key input and the event is keydown, return 229.
    [1, 0, empty, 114, "KeyInComposition", 229, empty, empty, empty],
    [1, 0, empty, 116, "ABNT_C2", 194, "VK_ABNT_C2", empty, empty],
    [1, 0, empty, 96, "OEM_8", 223, "VK_OEM_8", empty, empty],
    [1, 0, empty, 0, empty, 0, "VK_KANA", empty, empty],
    [1, 0, empty, 0, empty, 0, "VK_HANGUL", empty, empty],
    [1, 0, empty, 0, empty, 0, "VK_JUNJA", empty, empty],
    [1, 0, empty, 0, empty, 0, "VK_FINAL", empty, empty],
    [1, 0, empty, 0, empty, 0, "VK_HANJA", empty, empty],
    [1, 0, empty, 0, empty, 0, "VK_KANJI", empty, empty],
    [1, 0, empty, 0, empty, 0, "VK_CONVERT", empty, empty],
    [1, 0, empty, 0, empty, 0, "VK_NONCONVERT", empty, empty],
    [1, 0, empty, 0, empty, 0, "VK_ACCEPT", empty, empty],
    [1, 0, empty, 0, empty, 0, "VK_MODECHANGE", empty, empty],
    [1, 0, empty, 0, empty, 0, "VK_SELECT", empty, empty],
    [1, 0, empty, 0, empty, 0, "VK_PRINT", empty, empty],
    [1, 0, empty, 0, empty, 0, "VK_EXECUTE", empty, empty],
    [1, 0, empty, 0, empty, 0, "VK_SNAPSHOT", empty, empty],
    [1, 0, empty, 0, empty, 0, "VK_HELP", empty, empty],
    [1, 0, empty, 0, empty, 0, "VK_APPS", empty, empty],
    [1, 0, empty, 0, empty, 0, "VK_PROCESSKEY", empty, empty],
    [1, 0, empty, 0, empty, 0, "VK_PACKET", empty, empty],
    [1, 0, empty, 0, empty, 0, "VK_DBE_SBCSCHAR", empty, empty],
    [1, 0, empty, 0, empty, 0, "VK_DBE_DBCSCHAR", empty, empty],
    [1, 0, empty, 0, empty, 0, "VK_ATTN", empty, empty],
    [1, 0, empty, 0, empty, 0, "VK_CRSEL", empty, empty],
    [1, 0, empty, 0, empty, 0, "VK_EXSEL", empty, empty],
    [1, 0, empty, 0, empty, 0, "VK_EREOF", empty, empty],
    [1, 0, empty, 0, empty, 0, "VK_PLAY", empty, empty],
    [1, 0, empty, 0, empty, 0, "VK_ZOOM", empty, empty],
    [1, 0, empty, 0, empty, 0, "VK_NONAME", empty, empty],
    [1, 0, empty, 0, empty, 0, "VK_PA1", empty, empty],
    [1, 0, empty, 0, empty, 0, "VK_OEM_CLEAR", empty, empty]
  ];
  const seenKeyCode = [];
  const seenScanCode = [];
  for (const mapping2 of mappings) {
    const [immutable, scanCode, scanCodeStr, keyCode, keyCodeStr, eventKeyCode, vkey, usUserSettingsLabel, generalUserSettingsLabel] = mapping2;
    if (!seenScanCode[scanCode]) {
      seenScanCode[scanCode] = true;
      scanCodeIntToStr[scanCode] = scanCodeStr;
      scanCodeStrToInt[scanCodeStr] = scanCode;
      scanCodeLowerCaseStrToInt[scanCodeStr.toLowerCase()] = scanCode;
      if (immutable) {
        $9e[scanCode] = keyCode;
        if (keyCode !== 0 && keyCode !== 3 && keyCode !== 5 && keyCode !== 4 && keyCode !== 6 && keyCode !== 57) {
          $0e[keyCode] = scanCode;
        }
      }
    }
    if (!seenKeyCode[keyCode]) {
      seenKeyCode[keyCode] = true;
      if (!keyCodeStr) {
        throw new Error(`String representation missing for key code ${keyCode} around scan code ${scanCodeStr}`);
      }
      uiMap.define(keyCode, keyCodeStr);
      userSettingsUSMap.define(keyCode, usUserSettingsLabel || keyCodeStr);
      userSettingsGeneralMap.define(keyCode, generalUserSettingsLabel || usUserSettingsLabel || keyCodeStr);
    }
    if (eventKeyCode) {
      $6e[eventKeyCode] = keyCode;
    }
    if (vkey) {
      $7e[vkey] = keyCode;
    }
  }
  $0e[
    3
    /* KeyCode.Enter */
  ] = 46;
})();
var KeyCodeUtils;
(function(KeyCodeUtils2) {
  function toString(keyCode) {
    return uiMap.keyCodeToStr(keyCode);
  }
  KeyCodeUtils2.toString = toString;
  function fromString(key2) {
    return uiMap.strToKeyCode(key2);
  }
  KeyCodeUtils2.fromString = fromString;
  function toUserSettingsUS(keyCode) {
    return userSettingsUSMap.keyCodeToStr(keyCode);
  }
  KeyCodeUtils2.toUserSettingsUS = toUserSettingsUS;
  function toUserSettingsGeneral(keyCode) {
    return userSettingsGeneralMap.keyCodeToStr(keyCode);
  }
  KeyCodeUtils2.toUserSettingsGeneral = toUserSettingsGeneral;
  function fromUserSettings(key2) {
    return userSettingsUSMap.strToKeyCode(key2) || userSettingsGeneralMap.strToKeyCode(key2);
  }
  KeyCodeUtils2.fromUserSettings = fromUserSettings;
  function toElectronAccelerator(keyCode) {
    if (keyCode >= 98 && keyCode <= 113) {
      return null;
    }
    switch (keyCode) {
      case 16:
        return "Up";
      case 18:
        return "Down";
      case 15:
        return "Left";
      case 17:
        return "Right";
    }
    return uiMap.keyCodeToStr(keyCode);
  }
  KeyCodeUtils2.toElectronAccelerator = toElectronAccelerator;
})(KeyCodeUtils || (KeyCodeUtils = {}));
var KeyMod;
(function(KeyMod2) {
  KeyMod2[KeyMod2["CtrlCmd"] = 2048] = "CtrlCmd";
  KeyMod2[KeyMod2["Shift"] = 1024] = "Shift";
  KeyMod2[KeyMod2["Alt"] = 512] = "Alt";
  KeyMod2[KeyMod2["WinCtrl"] = 256] = "WinCtrl";
})(KeyMod || (KeyMod = {}));
function $$e(firstPart, secondPart) {
  const chordPart = (secondPart & 65535) << 16 >>> 0;
  return (firstPart | chordPart) >>> 0;
}

// out-build/vs/base/common/keybindings.js
var BinaryKeybindingsMask;
(function(BinaryKeybindingsMask2) {
  BinaryKeybindingsMask2[BinaryKeybindingsMask2["CtrlCmd"] = 2048] = "CtrlCmd";
  BinaryKeybindingsMask2[BinaryKeybindingsMask2["Shift"] = 1024] = "Shift";
  BinaryKeybindingsMask2[BinaryKeybindingsMask2["Alt"] = 512] = "Alt";
  BinaryKeybindingsMask2[BinaryKeybindingsMask2["WinCtrl"] = 256] = "WinCtrl";
  BinaryKeybindingsMask2[BinaryKeybindingsMask2["KeyCode"] = 255] = "KeyCode";
})(BinaryKeybindingsMask || (BinaryKeybindingsMask = {}));
function $_e(keybinding, OS2) {
  if (typeof keybinding === "number") {
    if (keybinding === 0) {
      return null;
    }
    const firstChord = (keybinding & 65535) >>> 0;
    const secondChord = (keybinding & 4294901760) >>> 16;
    if (secondChord !== 0) {
      return new $df([
        $af(firstChord, OS2),
        $af(secondChord, OS2)
      ]);
    }
    return new $df([$af(firstChord, OS2)]);
  } else {
    const chords = [];
    for (let i2 = 0; i2 < keybinding.length; i2++) {
      chords.push($af(keybinding[i2], OS2));
    }
    return new $df(chords);
  }
}
function $af(keybinding, OS2) {
  const ctrlCmd = keybinding & 2048 ? true : false;
  const winCtrl = keybinding & 256 ? true : false;
  const ctrlKey = OS2 === 2 ? winCtrl : ctrlCmd;
  const shiftKey = keybinding & 1024 ? true : false;
  const altKey = keybinding & 512 ? true : false;
  const metaKey = OS2 === 2 ? ctrlCmd : winCtrl;
  const keyCode = keybinding & 255;
  return new $bf(ctrlKey, shiftKey, altKey, metaKey, keyCode);
}
var $bf = class _$bf {
  constructor(ctrlKey, shiftKey, altKey, metaKey, keyCode) {
    this.ctrlKey = ctrlKey;
    this.shiftKey = shiftKey;
    this.altKey = altKey;
    this.metaKey = metaKey;
    this.keyCode = keyCode;
  }
  equals(other) {
    return other instanceof _$bf && this.ctrlKey === other.ctrlKey && this.shiftKey === other.shiftKey && this.altKey === other.altKey && this.metaKey === other.metaKey && this.keyCode === other.keyCode;
  }
  getHashCode() {
    const ctrl = this.ctrlKey ? "1" : "0";
    const shift = this.shiftKey ? "1" : "0";
    const alt = this.altKey ? "1" : "0";
    const meta = this.metaKey ? "1" : "0";
    return `K${ctrl}${shift}${alt}${meta}${this.keyCode}`;
  }
  isModifierKey() {
    return this.keyCode === 0 || this.keyCode === 5 || this.keyCode === 57 || this.keyCode === 6 || this.keyCode === 4;
  }
  toKeybinding() {
    return new $df([this]);
  }
  /**
   * Does this keybinding refer to the key code of a modifier and it also has the modifier flag?
   */
  isDuplicateModifierCase() {
    return this.ctrlKey && this.keyCode === 5 || this.shiftKey && this.keyCode === 4 || this.altKey && this.keyCode === 6 || this.metaKey && this.keyCode === 57;
  }
};
var $cf = class _$cf {
  constructor(ctrlKey, shiftKey, altKey, metaKey, scanCode) {
    this.ctrlKey = ctrlKey;
    this.shiftKey = shiftKey;
    this.altKey = altKey;
    this.metaKey = metaKey;
    this.scanCode = scanCode;
  }
  equals(other) {
    return other instanceof _$cf && this.ctrlKey === other.ctrlKey && this.shiftKey === other.shiftKey && this.altKey === other.altKey && this.metaKey === other.metaKey && this.scanCode === other.scanCode;
  }
  getHashCode() {
    const ctrl = this.ctrlKey ? "1" : "0";
    const shift = this.shiftKey ? "1" : "0";
    const alt = this.altKey ? "1" : "0";
    const meta = this.metaKey ? "1" : "0";
    return `S${ctrl}${shift}${alt}${meta}${this.scanCode}`;
  }
  /**
   * Does this keybinding refer to the key code of a modifier and it also has the modifier flag?
   */
  isDuplicateModifierCase() {
    return this.ctrlKey && (this.scanCode === 157 || this.scanCode === 161) || this.shiftKey && (this.scanCode === 158 || this.scanCode === 162) || this.altKey && (this.scanCode === 159 || this.scanCode === 163) || this.metaKey && (this.scanCode === 160 || this.scanCode === 164);
  }
};
var $df = class {
  constructor(chords) {
    if (chords.length === 0) {
      throw $nb(`chords`);
    }
    this.chords = chords;
  }
  getHashCode() {
    let result = "";
    for (let i2 = 0, len = this.chords.length; i2 < len; i2++) {
      if (i2 !== 0) {
        result += ";";
      }
      result += this.chords[i2].getHashCode();
    }
    return result;
  }
  equals(other) {
    if (other === null) {
      return false;
    }
    if (this.chords.length !== other.chords.length) {
      return false;
    }
    for (let i2 = 0; i2 < this.chords.length; i2++) {
      if (!this.chords[i2].equals(other.chords[i2])) {
        return false;
      }
    }
    return true;
  }
};
var $ef = class {
  constructor(ctrlKey, shiftKey, altKey, metaKey, keyLabel, keyAriaLabel) {
    this.ctrlKey = ctrlKey;
    this.shiftKey = shiftKey;
    this.altKey = altKey;
    this.metaKey = metaKey;
    this.keyLabel = keyLabel;
    this.keyAriaLabel = keyAriaLabel;
  }
};
var $ff = class {
};

// out-build/vs/base/browser/keyboardEvent.js
function extractKeyCode(e) {
  if (e.charCode) {
    const char = String.fromCharCode(e.charCode).toUpperCase();
    return KeyCodeUtils.fromString(char);
  }
  const keyCode = e.keyCode;
  if (keyCode === 3) {
    return 7;
  } else if ($Ue) {
    switch (keyCode) {
      case 59:
        return 85;
      case 60:
        if ($n) {
          return 97;
        }
        break;
      case 61:
        return 86;
      case 107:
        return 109;
      case 109:
        return 111;
      case 173:
        return 88;
      case 224:
        if ($m) {
          return 57;
        }
        break;
    }
  } else if ($Ve) {
    if ($m && keyCode === 93) {
      return 57;
    } else if (!$m && keyCode === 92) {
      return 57;
    }
  }
  return $6e[keyCode] || 0;
}
var ctrlKeyMod = $m ? 256 : 2048;
var altKeyMod = 512;
var shiftKeyMod = 1024;
var metaKeyMod = $m ? 2048 : 256;
function $gf(e) {
  const modifiers = [];
  if (e.ctrlKey) {
    modifiers.push(`ctrl`);
  }
  if (e.shiftKey) {
    modifiers.push(`shift`);
  }
  if (e.altKey) {
    modifiers.push(`alt`);
  }
  if (e.metaKey) {
    modifiers.push(`meta`);
  }
  return `modifiers: [${modifiers.join(",")}], code: ${e.code}, keyCode: ${e.keyCode}, key: ${e.key}`;
}
function $hf(e) {
  const modifiers = [];
  if (e.ctrlKey) {
    modifiers.push(`ctrl`);
  }
  if (e.shiftKey) {
    modifiers.push(`shift`);
  }
  if (e.altKey) {
    modifiers.push(`alt`);
  }
  if (e.metaKey) {
    modifiers.push(`meta`);
  }
  return `modifiers: [${modifiers.join(",")}], code: ${e.code}, keyCode: ${e.keyCode} ('${KeyCodeUtils.toString(e.keyCode)}')`;
}
var $if = class {
  constructor(source) {
    this._standardKeyboardEventBrand = true;
    const e = source;
    this.browserEvent = e;
    this.target = e.target;
    this.ctrlKey = e.ctrlKey;
    this.shiftKey = e.shiftKey;
    this.altKey = e.altKey;
    this.metaKey = e.metaKey;
    this.altGraphKey = e.getModifierState?.("AltGraph");
    this.keyCode = extractKeyCode(e);
    this.code = e.code;
    this.ctrlKey = this.ctrlKey || this.keyCode === 5;
    this.altKey = this.altKey || this.keyCode === 6;
    this.shiftKey = this.shiftKey || this.keyCode === 4;
    this.metaKey = this.metaKey || this.keyCode === 57;
    this.a = this.c();
    this.b = this.d();
  }
  preventDefault() {
    if (this.browserEvent && this.browserEvent.preventDefault) {
      this.browserEvent.preventDefault();
    }
  }
  stopPropagation() {
    if (this.browserEvent && this.browserEvent.stopPropagation) {
      this.browserEvent.stopPropagation();
    }
  }
  toKeyCodeChord() {
    return this.b;
  }
  equals(other) {
    return this.a === other;
  }
  c() {
    let key2 = 0;
    if (this.keyCode !== 5 && this.keyCode !== 4 && this.keyCode !== 6 && this.keyCode !== 57) {
      key2 = this.keyCode;
    }
    let result = 0;
    if (this.ctrlKey) {
      result |= ctrlKeyMod;
    }
    if (this.altKey) {
      result |= altKeyMod;
    }
    if (this.shiftKey) {
      result |= shiftKeyMod;
    }
    if (this.metaKey) {
      result |= metaKeyMod;
    }
    result |= key2;
    return result;
  }
  d() {
    let key2 = 0;
    if (this.keyCode !== 5 && this.keyCode !== 4 && this.keyCode !== 6 && this.keyCode !== 57) {
      key2 = this.keyCode;
    }
    return new $bf(this.ctrlKey, this.shiftKey, this.altKey, this.metaKey, key2);
  }
};

// out-build/vs/base/browser/iframe.js
var sameOriginWindowChainCache = /* @__PURE__ */ new WeakMap();
function getParentWindowIfSameOrigin(w) {
  if (!w.parent || w.parent === w) {
    return null;
  }
  try {
    const location3 = w.location;
    const parentLocation = w.parent.location;
    if (location3.origin !== "null" && parentLocation.origin !== "null" && location3.origin !== parentLocation.origin) {
      return null;
    }
  } catch (e) {
    return null;
  }
  return w.parent;
}
var $jf = class {
  /**
   * Returns a chain of embedded windows with the same origin (which can be accessed programmatically).
   * Having a chain of length 1 might mean that the current execution environment is running outside of an iframe or inside an iframe embedded in a window with a different origin.
   */
  static a(targetWindow) {
    let windowChainCache = sameOriginWindowChainCache.get(targetWindow);
    if (!windowChainCache) {
      windowChainCache = [];
      sameOriginWindowChainCache.set(targetWindow, windowChainCache);
      let w = targetWindow;
      let parent;
      do {
        parent = getParentWindowIfSameOrigin(w);
        if (parent) {
          windowChainCache.push({
            window: new WeakRef(w),
            iframeElement: w.frameElement || null
          });
        } else {
          windowChainCache.push({
            window: new WeakRef(w),
            iframeElement: null
          });
        }
        w = parent;
      } while (w);
    }
    return windowChainCache.slice(0);
  }
  /**
   * Returns the position of `childWindow` relative to `ancestorWindow`
   */
  static getPositionOfChildWindowRelativeToAncestorWindow(childWindow, ancestorWindow) {
    if (!ancestorWindow || childWindow === ancestorWindow) {
      return {
        top: 0,
        left: 0
      };
    }
    let top2 = 0, left = 0;
    const windowChain = this.a(childWindow);
    for (const windowChainEl of windowChain) {
      const windowInChain = windowChainEl.window.deref();
      top2 += windowInChain?.scrollY ?? 0;
      left += windowInChain?.scrollX ?? 0;
      if (windowInChain === ancestorWindow) {
        break;
      }
      if (!windowChainEl.iframeElement) {
        break;
      }
      const boundingRect = windowChainEl.iframeElement.getBoundingClientRect();
      top2 += boundingRect.top;
      left += boundingRect.left;
    }
    return {
      top: top2,
      left
    };
  }
};
async function $kf(parentOrigin, salt) {
  if (!crypto.subtle) {
    throw new Error(`'crypto.subtle' is not available so webviews will not work. This is likely because the editor is not running in a secure context (https://developer.mozilla.org/en-US/docs/Web/Security/Secure_Contexts).`);
  }
  const strData = JSON.stringify({ parentOrigin, salt });
  const encoder = new TextEncoder();
  const arrData = encoder.encode(strData);
  const hash = await crypto.subtle.digest("sha-256", arrData);
  return sha256AsBase32(hash);
}
function sha256AsBase32(bytes) {
  const array2 = Array.from(new Uint8Array(bytes));
  const hexArray = array2.map((b) => b.toString(16).padStart(2, "0")).join("");
  return BigInt(`0x${hexArray}`).toString(32).padStart(52, "0");
}

// out-build/vs/base/browser/mouseEvent.js
var $lf = class {
  constructor(targetWindow, e) {
    this.timestamp = Date.now();
    this.browserEvent = e;
    this.leftButton = e.button === 0;
    this.middleButton = e.button === 1;
    this.rightButton = e.button === 2;
    this.buttons = e.buttons;
    this.target = e.target;
    this.detail = e.detail || 1;
    if (e.type === "dblclick") {
      this.detail = 2;
    }
    this.ctrlKey = e.ctrlKey;
    this.shiftKey = e.shiftKey;
    this.altKey = e.altKey;
    this.metaKey = e.metaKey;
    if (typeof e.pageX === "number") {
      this.posx = e.pageX;
      this.posy = e.pageY;
    } else {
      this.posx = e.clientX + this.target.ownerDocument.body.scrollLeft + this.target.ownerDocument.documentElement.scrollLeft;
      this.posy = e.clientY + this.target.ownerDocument.body.scrollTop + this.target.ownerDocument.documentElement.scrollTop;
    }
    const iframeOffsets = $jf.getPositionOfChildWindowRelativeToAncestorWindow(targetWindow, e.view);
    this.posx -= iframeOffsets.left;
    this.posy -= iframeOffsets.top;
  }
  preventDefault() {
    this.browserEvent.preventDefault();
  }
  stopPropagation() {
    this.browserEvent.stopPropagation();
  }
};
var $nf = class {
  constructor(e, deltaX = 0, deltaY = 0) {
    this.browserEvent = e || null;
    this.target = e ? e.target || e.targetNode || e.srcElement : null;
    this.deltaY = deltaY;
    this.deltaX = deltaX;
    let shouldFactorDPR = false;
    if ($We) {
      const chromeVersionMatch = navigator.userAgent.match(/Chrome\/(\d+)/);
      const chromeMajorVersion = chromeVersionMatch ? parseInt(chromeVersionMatch[1]) : 123;
      shouldFactorDPR = chromeMajorVersion <= 122;
    }
    if (e) {
      const e1 = e;
      const e2 = e;
      const devicePixelRatio = e.view?.devicePixelRatio || 1;
      if (typeof e1.wheelDeltaY !== "undefined") {
        if (shouldFactorDPR) {
          this.deltaY = e1.wheelDeltaY / (120 * devicePixelRatio);
        } else {
          this.deltaY = e1.wheelDeltaY / 120;
        }
      } else if (typeof e2.VERTICAL_AXIS !== "undefined" && e2.axis === e2.VERTICAL_AXIS) {
        this.deltaY = -e2.detail / 3;
      } else if (e.type === "wheel") {
        const ev = e;
        if (ev.deltaMode === ev.DOM_DELTA_LINE) {
          if ($Ue && !$m) {
            this.deltaY = -e.deltaY / 3;
          } else {
            this.deltaY = -e.deltaY;
          }
        } else {
          this.deltaY = -e.deltaY / 40;
        }
      }
      if (typeof e1.wheelDeltaX !== "undefined") {
        if ($Xe && $l) {
          this.deltaX = -(e1.wheelDeltaX / 120);
        } else if (shouldFactorDPR) {
          this.deltaX = e1.wheelDeltaX / (120 * devicePixelRatio);
        } else {
          this.deltaX = e1.wheelDeltaX / 120;
        }
      } else if (typeof e2.HORIZONTAL_AXIS !== "undefined" && e2.axis === e2.HORIZONTAL_AXIS) {
        this.deltaX = -e.detail / 3;
      } else if (e.type === "wheel") {
        const ev = e;
        if (ev.deltaMode === ev.DOM_DELTA_LINE) {
          if ($Ue && !$m) {
            this.deltaX = -e.deltaX / 3;
          } else {
            this.deltaX = -e.deltaX;
          }
        } else {
          this.deltaX = -e.deltaX / 40;
        }
      }
      if (this.deltaY === 0 && this.deltaX === 0 && e.wheelDelta) {
        if (shouldFactorDPR) {
          this.deltaY = e.wheelDelta / (120 * devicePixelRatio);
        } else {
          this.deltaY = e.wheelDelta / 120;
        }
      }
    }
  }
  preventDefault() {
    this.browserEvent?.preventDefault();
  }
  stopPropagation() {
    this.browserEvent?.stopPropagation();
  }
};

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

// out-build/vs/base/common/async.js
function $Gh(obj) {
  return !!obj && typeof obj.then === "function";
}
function $Hh(callback) {
  const source = new $ad();
  const thenable = callback(source.token);
  const promise = new Promise((resolve, reject) => {
    const subscription = source.token.onCancellationRequested(() => {
      subscription.dispose();
      reject(new $lb());
    });
    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 $Ih(promise, token, defaultValue) {
  return new Promise((resolve, reject) => {
    const ref = token.onCancellationRequested(() => {
      ref.dispose();
      resolve(defaultValue);
    });
    promise.then(resolve, reject).finally(() => ref.dispose());
  });
}
function $Jh(promise, token) {
  return new Promise((resolve, reject) => {
    const ref = token.onCancellationRequested(() => {
      ref.dispose();
      reject(new $lb());
    });
    promise.then(resolve, reject).finally(() => ref.dispose());
  });
}
async function $Kh(cancellablePromises) {
  let resolvedPromiseIndex = -1;
  const promises = cancellablePromises.map((promise, index) => promise.then((result) => {
    resolvedPromiseIndex = index;
    return result;
  }));
  try {
    const result = await Promise.race(promises);
    return result;
  } finally {
    cancellablePromises.forEach((cancellablePromise, index) => {
      if (index !== resolvedPromiseIndex) {
        cancellablePromise.cancel();
      }
    });
  }
}
function $Lh(promise, timeout, onTimeout) {
  let promiseResolve = void 0;
  const timer = setTimeout(() => {
    promiseResolve?.(void 0);
    onTimeout?.();
  }, timeout);
  return Promise.race([
    promise.finally(() => clearTimeout(timer)),
    new Promise((resolve) => promiseResolve = resolve)
  ]);
}
function $Oh() {
  let resolve;
  let reject;
  const promise = new Promise((res, rej) => {
    resolve = res;
    reject = rej;
  });
  return { promise, resolve, reject };
}
var $Ph = 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 $Qh = class {
  constructor() {
    this.a = Promise.resolve(null);
  }
  queue(promiseTask) {
    return this.a = this.a.then(() => promiseTask(), () => promiseTask());
  }
};
var $Rh = class {
  constructor() {
    this.a = /* @__PURE__ */ new Map();
  }
  queue(key2, promiseTask) {
    const runningPromise = this.a.get(key2) ?? Promise.resolve();
    const newPromise = runningPromise.catch(() => {
    }).then(promiseTask).finally(() => {
      if (this.a.get(key2) === newPromise) {
        this.a.delete(key2);
      }
    });
    this.a.set(key2, newPromise);
    return newPromise;
  }
};
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 $Sh = 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 === $ue ? microtaskDeferred(fn) : timeoutDeferred(delay, fn);
    return this.b;
  }
  isTriggered() {
    return !!this.a?.isTriggered();
  }
  cancel() {
    this.h();
    if (this.b) {
      this.f?.(new $lb());
      this.b = null;
    }
  }
  h() {
    this.a?.dispose();
    this.a = null;
  }
  dispose() {
    this.cancel();
  }
};
var $Th = class {
  constructor(defaultDelay) {
    this.a = new $Sh(defaultDelay);
    this.b = new $Ph();
  }
  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 $Uh = 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;
  }
};
var $Vh = class extends $Uh {
  constructor(autoOpenTimeMs) {
    super();
    this.f = setTimeout(() => this.open(), autoOpenTimeMs);
  }
  open() {
    clearTimeout(this.f);
    super.open();
  }
};
function $Wh(millis, token) {
  if (!token) {
    return $Hh((token2) => $Wh(millis, token2));
  }
  return new Promise((resolve, reject) => {
    const handle2 = setTimeout(() => {
      disposable.dispose();
      resolve();
    }, millis);
    const disposable = token.onCancellationRequested(() => {
      clearTimeout(handle2);
      disposable.dispose();
      reject(new $lb());
    });
  });
}
function $Xh(handler, timeout = 0, store) {
  const timer = setTimeout(() => {
    handler();
    if (store) {
      disposable.dispose();
    }
  }, timeout);
  const disposable = $1c(() => {
    clearTimeout(timer);
    store?.deleteAndLeak(disposable);
  });
  store?.add(disposable);
  return disposable;
}
function $Yh(promiseFactories) {
  const results = [];
  let index = 0;
  const len = promiseFactories.length;
  function next() {
    return index < len ? promiseFactories[index++]() : null;
  }
  function thenHandler(result) {
    if (result !== void 0 && result !== null) {
      results.push(result);
    }
    const n = next();
    if (n) {
      return n.then(thenHandler);
    }
    return Promise.resolve(results);
  }
  return Promise.resolve(null).then(thenHandler);
}
function $Zh(promiseFactories, shouldStop = (t) => !!t, defaultValue = null) {
  let index = 0;
  const len = promiseFactories.length;
  const loop = () => {
    if (index >= len) {
      return Promise.resolve(defaultValue);
    }
    const factory = promiseFactories[index++];
    const promise = Promise.resolve(factory());
    return promise.then((result) => {
      if (shouldStop(result)) {
        return Promise.resolve(result);
      }
      return loop();
    });
  };
  return loop();
}
var $2h = class {
  constructor(maxDegreeOfParalellism) {
    this.a = 0;
    this.b = false;
    this.f = maxDegreeOfParalellism;
    this.g = [];
    this.d = 0;
    this.h = new $ze();
  }
  /**
   *
   * @returns A promise that resolved when all work is done (onDrained) or when
   * there is nothing to do
   */
  whenIdle() {
    return this.size > 0 ? Event2.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 $3h = class extends $2h {
  constructor() {
    super(1);
  }
};
var $5h = 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 $gi();
    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 = $lh) {
    const key2 = extUri.getComparisonKey(resource);
    return this.a.get(key2)?.size ?? 0;
  }
  queueFor(resource, factory, extUri = $lh) {
    const key2 = extUri.getComparisonKey(resource);
    let queue = this.a.get(key2);
    if (!queue) {
      queue = new $3h();
      const drainListenerId = this.f++;
      const drainListener = Event2.once(queue.onDrained)(() => {
        queue?.dispose();
        this.a.delete(key2);
        this.h();
        this.d?.deleteAndDispose(drainListenerId);
        if (this.d?.size === 0) {
          this.d.dispose();
          this.d = void 0;
        }
      });
      if (!this.d) {
        this.d = new $_c();
      }
      this.d.set(drainListenerId, drainListener);
      this.a.set(key2, 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 $6h = class {
  constructor(runner, timeout) {
    this.b = false;
    this.a = -1;
    if (typeof runner === "function" && typeof timeout === "number") {
      this.setIfNotSet(runner, timeout);
    }
  }
  dispose() {
    this.cancel();
    this.b = true;
  }
  cancel() {
    if (this.a !== -1) {
      clearTimeout(this.a);
      this.a = -1;
    }
  }
  cancelAndSet(runner, timeout) {
    if (this.b) {
      throw new $vb(`Calling 'cancelAndSet' on a disposed TimeoutTimer`);
    }
    this.cancel();
    this.a = setTimeout(() => {
      this.a = -1;
      runner();
    }, timeout);
  }
  setIfNotSet(runner, timeout) {
    if (this.b) {
      throw new $vb(`Calling 'setIfNotSet' on a disposed TimeoutTimer`);
    }
    if (this.a !== -1) {
      return;
    }
    this.a = setTimeout(() => {
      this.a = -1;
      runner();
    }, timeout);
  }
};
var $7h = class {
  constructor() {
    this.d = void 0;
    this.f = false;
  }
  cancel() {
    this.d?.dispose();
    this.d = void 0;
  }
  cancelAndSet(runner, interval, context = globalThis) {
    if (this.f) {
      throw new $vb(`Calling 'cancelAndSet' on a disposed IntervalTimer`);
    }
    this.cancel();
    const handle2 = context.setInterval(() => {
      runner();
    }, interval);
    this.d = $1c(() => {
      context.clearInterval(handle2);
      this.d = void 0;
    });
  }
  dispose() {
    this.cancel();
    this.f = true;
  }
};
var $8h = 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 $0h = class extends $8h {
  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 $_h;
var $ai;
(function() {
  if (typeof globalThis.requestIdleCallback !== "function" || typeof globalThis.cancelIdleCallback !== "function") {
    $ai = (_targetWindow, runner, timeout) => {
      $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 {
    $ai = (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);
        }
      };
    };
  }
  $_h = (runner, timeout) => $ai(globalThis, runner, timeout);
})();
var $bi = class {
  constructor(targetWindow, executor) {
    this.g = false;
    this.d = () => {
      try {
        this.j = executor();
      } catch (err) {
        this.l = err;
      } finally {
        this.g = true;
      }
    };
    this.f = $ai(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 $ci = class extends $bi {
  constructor(executor) {
    super(globalThis, executor);
  }
};
async function $di(task, delay, retries) {
  let lastError;
  for (let i2 = 0; i2 < retries; i2++) {
    try {
      return await task();
    } catch (error) {
      lastError = error;
      await $Wh(delay);
    }
  }
  throw lastError;
}
var $ei = class {
  isRunning(taskId) {
    if (typeof taskId === "number") {
      return this.a?.taskId === taskId;
    }
    return !!this.a;
  }
  get running() {
    return this.a?.promise;
  }
  cancelRunning() {
    this.a?.cancel();
  }
  run(taskId, promise, onCancel) {
    this.a = { taskId, cancel: () => onCancel?.(), promise };
    promise.then(() => this.d(taskId), () => this.d(taskId));
    return promise;
  }
  d(taskId) {
    if (this.a && taskId === this.a.taskId) {
      this.a = void 0;
      this.f();
    }
  }
  f() {
    if (this.b) {
      const queued = this.b;
      this.b = void 0;
      queued.run().then(queued.promiseResolve, queued.promiseReject);
    }
  }
  /**
   * Note: the promise to schedule as next run MUST itself call `run`.
   *       Otherwise, this sequentializer will report `false` for `isRunning`
   *       even when this task is running. Missing this detail means that
   *       suddenly multiple tasks will run in parallel.
   */
  queue(run) {
    if (!this.b) {
      const { promise, resolve: promiseResolve, reject: promiseReject } = $Oh();
      this.b = {
        run,
        promise,
        promiseResolve,
        promiseReject
      };
    } else {
      this.b.run = run;
    }
    return this.b.promise;
  }
  hasQueued() {
    return !!this.b;
  }
  async join() {
    return this.b?.promise ?? this.a?.promise;
  }
};
var $fi = class {
  constructor(d, f = () => Date.now()) {
    this.d = d;
    this.f = f;
    this.a = 0;
    this.b = 0;
  }
  increment() {
    const now = this.f();
    if (now - this.a > this.d) {
      this.a = now;
      this.b = 0;
    }
    this.b++;
    return this.b;
  }
};
var DeferredOutcome;
(function(DeferredOutcome2) {
  DeferredOutcome2[DeferredOutcome2["Resolved"] = 0] = "Resolved";
  DeferredOutcome2[DeferredOutcome2["Rejected"] = 1] = "Rejected";
})(DeferredOutcome || (DeferredOutcome = {}));
var $gi = 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 $lb());
  }
};
var Promises;
(function(Promises2) {
  async function settled(promises) {
    let firstError = void 0;
    const result = await Promise.all(promises.map((promise) => promise.then((value) => value, (error) => {
      if (!firstError) {
        firstError = error;
      }
      return void 0;
    })));
    if (typeof firstError !== "undefined") {
      throw firstError;
    }
    return result;
  }
  Promises2.settled = settled;
  function withAsyncBody(bodyFn) {
    return new Promise(async (resolve, reject) => {
      try {
        await bodyFn(resolve, reject);
      } catch (error) {
        reject(error);
      }
    });
  }
  Promises2.withAsyncBody = withAsyncBody;
})(Promises || (Promises = {}));
var $hi = class {
  get value() {
    return this.a;
  }
  get error() {
    return this.b;
  }
  get isResolved() {
    return this.d;
  }
  constructor(promise) {
    this.a = void 0;
    this.b = void 0;
    this.d = false;
    this.promise = promise.then((value) => {
      this.a = value;
      this.d = true;
      return value;
    }, (error) => {
      this.b = error;
      this.d = true;
      throw error;
    });
  }
  /**
   * Returns the resolved value.
   * Throws if the promise is not resolved yet.
   */
  requireValue() {
    if (!this.d) {
      throw new $vb("Promise is not resolved yet");
    }
    if (this.b) {
      throw this.b;
    }
    return this.a;
  }
};
var $ii = class {
  constructor(b) {
    this.b = b;
    this.a = new $sf(() => new $hi(this.b()));
  }
  /**
   * Returns the resolved value.
   * Throws if the promise is not resolved yet.
   */
  requireValue() {
    return this.a.value.requireValue();
  }
  /**
   * Returns the promise (and triggers a computation of the promise if not yet done so).
   */
  getPromise() {
    return this.a.value.promise;
  }
  /**
   * Reads the current value without triggering a computation of the promise.
   */
  get currentValue() {
    return this.a.rawValue?.value;
  }
};
var AsyncIterableSourceState;
(function(AsyncIterableSourceState2) {
  AsyncIterableSourceState2[AsyncIterableSourceState2["Initial"] = 0] = "Initial";
  AsyncIterableSourceState2[AsyncIterableSourceState2["DoneOK"] = 1] = "DoneOK";
  AsyncIterableSourceState2[AsyncIterableSourceState2["DoneError"] = 2] = "DoneError";
})(AsyncIterableSourceState || (AsyncIterableSourceState = {}));
var $ji = class _$ji {
  static fromArray(items) {
    return new _$ji((writer) => {
      writer.emitMany(items);
    });
  }
  static fromPromise(promise) {
    return new _$ji(async (emitter) => {
      emitter.emitMany(await promise);
    });
  }
  static fromPromisesResolveOrder(promises) {
    return new _$ji(async (emitter) => {
      await Promise.all(promises.map(async (p) => emitter.emitOne(await p)));
    });
  }
  static merge(iterables) {
    return new _$ji(async (emitter) => {
      await Promise.all(iterables.map(async (iterable) => {
        for await (const item of iterable) {
          emitter.emitOne(item);
        }
      }));
    });
  }
  static {
    this.EMPTY = _$ji.fromArray([]);
  }
  constructor(executor, onReturn) {
    this.a = 0;
    this.b = [];
    this.d = null;
    this.f = onReturn;
    this.g = new $ze();
    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 i2 = 0;
    return {
      next: async () => {
        do {
          if (this.a === 2) {
            throw this.d;
          }
          if (i2 < this.b.length) {
            return { done: false, value: this.b[i2++] };
          }
          if (this.a === 1) {
            return { done: true, value: void 0 };
          }
          await Event2.toPromise(this.g.event);
        } while (true);
      },
      return: async () => {
        this.f?.();
        return { done: true, value: void 0 };
      }
    };
  }
  static map(iterable, mapFn) {
    return new _$ji(async (emitter) => {
      for await (const item of iterable) {
        emitter.emitOne(mapFn(item));
      }
    });
  }
  map(mapFn) {
    return _$ji.map(this, mapFn);
  }
  static filter(iterable, filterFn) {
    return new _$ji(async (emitter) => {
      for await (const item of iterable) {
        if (filterFn(item)) {
          emitter.emitOne(item);
        }
      }
    });
  }
  filter(filterFn) {
    return _$ji.filter(this, filterFn);
  }
  static coalesce(iterable) {
    return _$ji.filter(iterable, (item) => !!item);
  }
  coalesce() {
    return _$ji.coalesce(this);
  }
  static async toPromise(iterable) {
    const result = [];
    for await (const item of iterable) {
      result.push(item);
    }
    return result;
  }
  toPromise() {
    return _$ji.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();
  }
};
var $ki = class extends $ji {
  constructor(m, executor) {
    super(executor);
    this.m = m;
  }
  cancel() {
    this.m.cancel();
  }
};
function $li(callback) {
  const source = new $ad();
  const innerIterable = callback(source.token);
  return new $ki(source, async (emitter) => {
    const subscription = source.token.onCancellationRequested(() => {
      subscription.dispose();
      source.dispose();
      emitter.reject(new $lb());
    });
    try {
      for await (const item of innerIterable) {
        if (source.token.isCancellationRequested) {
          return;
        }
        emitter.emitOne(item);
      }
      subscription.dispose();
      source.dispose();
    } catch (err) {
      subscription.dispose();
      source.dispose();
      emitter.reject(err);
    }
  });
}
var $mi = class {
  /**
   *
   * @param onReturn A function that will be called when consuming the async iterable
   * has finished by the consumer, e.g the for-await-loop has be existed (break, return) early.
   * This is NOT called when resolving this source by its owner.
   */
  constructor(onReturn) {
    this.a = new $gi();
    this.b = new $ji((emitter) => {
      if (earlyError) {
        emitter.reject(earlyError);
        return;
      }
      if (earlyItems) {
        emitter.emitMany(earlyItems);
      }
      this.d = (error) => emitter.reject(error);
      this.f = (item) => emitter.emitOne(item);
      return this.a.p;
    }, onReturn);
    let earlyError;
    let earlyItems;
    this.f = (item) => {
      if (!earlyItems) {
        earlyItems = [];
      }
      earlyItems.push(item);
    };
    this.d = (error) => {
      if (!earlyError) {
        earlyError = error;
      }
    };
  }
  get asyncIterable() {
    return this.b;
  }
  resolve() {
    this.a.complete();
  }
  reject(error) {
    this.d(error);
    this.a.complete();
  }
  emitOne(item) {
    this.f(item);
  }
};

// out-build/vs/base/browser/dompurify/dompurify.js
var {
  entries,
  setPrototypeOf,
  isFrozen,
  getPrototypeOf,
  getOwnPropertyDescriptor
} = Object;
var {
  freeze,
  seal,
  create
} = Object;
var {
  apply,
  construct
} = typeof Reflect !== "undefined" && Reflect;
if (!freeze) {
  freeze = function freeze3(x) {
    return x;
  };
}
if (!seal) {
  seal = function seal2(x) {
    return x;
  };
}
if (!apply) {
  apply = function apply2(fun, thisValue, args2) {
    return fun.apply(thisValue, args2);
  };
}
if (!construct) {
  construct = function construct2(Func, args2) {
    return new Func(...args2);
  };
}
var arrayForEach = unapply(Array.prototype.forEach);
var arrayPop = unapply(Array.prototype.pop);
var arrayPush = unapply(Array.prototype.push);
var stringToLowerCase = unapply(String.prototype.toLowerCase);
var stringToString = unapply(String.prototype.toString);
var stringMatch = unapply(String.prototype.match);
var stringReplace = unapply(String.prototype.replace);
var stringIndexOf = unapply(String.prototype.indexOf);
var stringTrim = unapply(String.prototype.trim);
var objectHasOwnProperty = unapply(Object.prototype.hasOwnProperty);
var regExpTest = unapply(RegExp.prototype.test);
var typeErrorCreate = unconstruct(TypeError);
function unapply(func) {
  return function(thisArg) {
    for (var _len = arguments.length, args2 = new Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) {
      args2[_key - 1] = arguments[_key];
    }
    return apply(func, thisArg, args2);
  };
}
function unconstruct(func) {
  return function() {
    for (var _len2 = arguments.length, args2 = new Array(_len2), _key2 = 0; _key2 < _len2; _key2++) {
      args2[_key2] = arguments[_key2];
    }
    return construct(func, args2);
  };
}
function addToSet(set, array2) {
  let transformCaseFunc = arguments.length > 2 && arguments[2] !== void 0 ? arguments[2] : stringToLowerCase;
  if (setPrototypeOf) {
    setPrototypeOf(set, null);
  }
  let l = array2.length;
  while (l--) {
    let element = array2[l];
    if (typeof element === "string") {
      const lcElement = transformCaseFunc(element);
      if (lcElement !== element) {
        if (!isFrozen(array2)) {
          array2[l] = lcElement;
        }
        element = lcElement;
      }
    }
    set[element] = true;
  }
  return set;
}
function cleanArray(array2) {
  for (let index = 0; index < array2.length; index++) {
    const isPropertyExist = objectHasOwnProperty(array2, index);
    if (!isPropertyExist) {
      array2[index] = null;
    }
  }
  return array2;
}
function clone(object) {
  const newObject = create(null);
  for (const [property, value] of entries(object)) {
    const isPropertyExist = objectHasOwnProperty(object, property);
    if (isPropertyExist) {
      if (Array.isArray(value)) {
        newObject[property] = cleanArray(value);
      } else if (value && typeof value === "object" && value.constructor === Object) {
        newObject[property] = clone(value);
      } else {
        newObject[property] = value;
      }
    }
  }
  return newObject;
}
function lookupGetter(object, prop) {
  while (object !== null) {
    const desc = getOwnPropertyDescriptor(object, prop);
    if (desc) {
      if (desc.get) {
        return unapply(desc.get);
      }
      if (typeof desc.value === "function") {
        return unapply(desc.value);
      }
    }
    object = getPrototypeOf(object);
  }
  function fallbackValue() {
    return null;
  }
  return fallbackValue;
}
var html$1 = freeze(["a", "abbr", "acronym", "address", "area", "article", "aside", "audio", "b", "bdi", "bdo", "big", "blink", "blockquote", "body", "br", "button", "canvas", "caption", "center", "cite", "code", "col", "colgroup", "content", "data", "datalist", "dd", "decorator", "del", "details", "dfn", "dialog", "dir", "div", "dl", "dt", "element", "em", "fieldset", "figcaption", "figure", "font", "footer", "form", "h1", "h2", "h3", "h4", "h5", "h6", "head", "header", "hgroup", "hr", "html", "i", "img", "input", "ins", "kbd", "label", "legend", "li", "main", "map", "mark", "marquee", "menu", "menuitem", "meter", "nav", "nobr", "ol", "optgroup", "option", "output", "p", "picture", "pre", "progress", "q", "rp", "rt", "ruby", "s", "samp", "section", "select", "shadow", "small", "source", "spacer", "span", "strike", "strong", "style", "sub", "summary", "sup", "table", "tbody", "td", "template", "textarea", "tfoot", "th", "thead", "time", "tr", "track", "tt", "u", "ul", "var", "video", "wbr"]);
var svg$1 = freeze(["svg", "a", "altglyph", "altglyphdef", "altglyphitem", "animatecolor", "animatemotion", "animatetransform", "circle", "clippath", "defs", "desc", "ellipse", "filter", "font", "g", "glyph", "glyphref", "hkern", "image", "line", "lineargradient", "marker", "mask", "metadata", "mpath", "path", "pattern", "polygon", "polyline", "radialgradient", "rect", "stop", "style", "switch", "symbol", "text", "textpath", "title", "tref", "tspan", "view", "vkern"]);
var svgFilters = freeze(["feBlend", "feColorMatrix", "feComponentTransfer", "feComposite", "feConvolveMatrix", "feDiffuseLighting", "feDisplacementMap", "feDistantLight", "feDropShadow", "feFlood", "feFuncA", "feFuncB", "feFuncG", "feFuncR", "feGaussianBlur", "feImage", "feMerge", "feMergeNode", "feMorphology", "feOffset", "fePointLight", "feSpecularLighting", "feSpotLight", "feTile", "feTurbulence"]);
var svgDisallowed = freeze(["animate", "color-profile", "cursor", "discard", "font-face", "font-face-format", "font-face-name", "font-face-src", "font-face-uri", "foreignobject", "hatch", "hatchpath", "mesh", "meshgradient", "meshpatch", "meshrow", "missing-glyph", "script", "set", "solidcolor", "unknown", "use"]);
var mathMl$1 = freeze(["math", "menclose", "merror", "mfenced", "mfrac", "mglyph", "mi", "mlabeledtr", "mmultiscripts", "mn", "mo", "mover", "mpadded", "mphantom", "mroot", "mrow", "ms", "mspace", "msqrt", "mstyle", "msub", "msup", "msubsup", "mtable", "mtd", "mtext", "mtr", "munder", "munderover", "mprescripts"]);
var mathMlDisallowed = freeze(["maction", "maligngroup", "malignmark", "mlongdiv", "mscarries", "mscarry", "msgroup", "mstack", "msline", "msrow", "semantics", "annotation", "annotation-xml", "mprescripts", "none"]);
var text = freeze(["#text"]);
var html = freeze(["accept", "action", "align", "alt", "autocapitalize", "autocomplete", "autopictureinpicture", "autoplay", "background", "bgcolor", "border", "capture", "cellpadding", "cellspacing", "checked", "cite", "class", "clear", "color", "cols", "colspan", "controls", "controlslist", "coords", "crossorigin", "datetime", "decoding", "default", "dir", "disabled", "disablepictureinpicture", "disableremoteplayback", "download", "draggable", "enctype", "enterkeyhint", "face", "for", "headers", "height", "hidden", "high", "href", "hreflang", "id", "inputmode", "integrity", "ismap", "kind", "label", "lang", "list", "loading", "loop", "low", "max", "maxlength", "media", "method", "min", "minlength", "multiple", "muted", "name", "nonce", "noshade", "novalidate", "nowrap", "open", "optimum", "pattern", "placeholder", "playsinline", "popover", "popovertarget", "popovertargetaction", "poster", "preload", "pubdate", "radiogroup", "readonly", "rel", "required", "rev", "reversed", "role", "rows", "rowspan", "spellcheck", "scope", "selected", "shape", "size", "sizes", "span", "srclang", "start", "src", "srcset", "step", "style", "summary", "tabindex", "title", "translate", "type", "usemap", "valign", "value", "width", "wrap", "xmlns", "slot"]);
var svg = freeze(["accent-height", "accumulate", "additive", "alignment-baseline", "amplitude", "ascent", "attributename", "attributetype", "azimuth", "basefrequency", "baseline-shift", "begin", "bias", "by", "class", "clip", "clippathunits", "clip-path", "clip-rule", "color", "color-interpolation", "color-interpolation-filters", "color-profile", "color-rendering", "cx", "cy", "d", "dx", "dy", "diffuseconstant", "direction", "display", "divisor", "dur", "edgemode", "elevation", "end", "exponent", "fill", "fill-opacity", "fill-rule", "filter", "filterunits", "flood-color", "flood-opacity", "font-family", "font-size", "font-size-adjust", "font-stretch", "font-style", "font-variant", "font-weight", "fx", "fy", "g1", "g2", "glyph-name", "glyphref", "gradientunits", "gradienttransform", "height", "href", "id", "image-rendering", "in", "in2", "intercept", "k", "k1", "k2", "k3", "k4", "kerning", "keypoints", "keysplines", "keytimes", "lang", "lengthadjust", "letter-spacing", "kernelmatrix", "kernelunitlength", "lighting-color", "local", "marker-end", "marker-mid", "marker-start", "markerheight", "markerunits", "markerwidth", "maskcontentunits", "maskunits", "max", "mask", "media", "method", "mode", "min", "name", "numoctaves", "offset", "operator", "opacity", "order", "orient", "orientation", "origin", "overflow", "paint-order", "path", "pathlength", "patterncontentunits", "patterntransform", "patternunits", "points", "preservealpha", "preserveaspectratio", "primitiveunits", "r", "rx", "ry", "radius", "refx", "refy", "repeatcount", "repeatdur", "restart", "result", "rotate", "scale", "seed", "shape-rendering", "slope", "specularconstant", "specularexponent", "spreadmethod", "startoffset", "stddeviation", "stitchtiles", "stop-color", "stop-opacity", "stroke-dasharray", "stroke-dashoffset", "stroke-linecap", "stroke-linejoin", "stroke-miterlimit", "stroke-opacity", "stroke", "stroke-width", "style", "surfacescale", "systemlanguage", "tabindex", "tablevalues", "targetx", "targety", "transform", "transform-origin", "text-anchor", "text-decoration", "text-rendering", "textlength", "type", "u1", "u2", "unicode", "values", "viewbox", "visibility", "version", "vert-adv-y", "vert-origin-x", "vert-origin-y", "width", "word-spacing", "wrap", "writing-mode", "xchannelselector", "ychannelselector", "x", "x1", "x2", "xmlns", "y", "y1", "y2", "z", "zoomandpan"]);
var mathMl = freeze(["accent", "accentunder", "align", "bevelled", "close", "columnsalign", "columnlines", "columnspan", "denomalign", "depth", "dir", "display", "displaystyle", "encoding", "fence", "frame", "height", "href", "id", "largeop", "length", "linethickness", "lspace", "lquote", "mathbackground", "mathcolor", "mathsize", "mathvariant", "maxsize", "minsize", "movablelimits", "notation", "numalign", "open", "rowalign", "rowlines", "rowspacing", "rowspan", "rspace", "rquote", "scriptlevel", "scriptminsize", "scriptsizemultiplier", "selection", "separator", "separators", "stretchy", "subscriptshift", "supscriptshift", "symmetric", "voffset", "width", "xmlns"]);
var xml = freeze(["xlink:href", "xml:id", "xlink:title", "xml:space", "xmlns:xlink"]);
var MUSTACHE_EXPR = seal(/\{\{[\w\W]*|[\w\W]*\}\}/gm);
var ERB_EXPR = seal(/<%[\w\W]*|[\w\W]*%>/gm);
var TMPLIT_EXPR = seal(/\${[\w\W]*}/gm);
var DATA_ATTR = seal(/^data-[\-\w.\u00B7-\uFFFF]/);
var ARIA_ATTR = seal(/^aria-[\-\w]+$/);
var IS_ALLOWED_URI = seal(
  /^(?:(?:(?:f|ht)tps?|mailto|tel|callto|sms|cid|xmpp):|[^a-z]|[a-z+.\-]+(?:[^a-z+.\-:]|$))/i
  // eslint-disable-line no-useless-escape
);
var IS_SCRIPT_OR_DATA = seal(/^(?:\w+script|data):/i);
var ATTR_WHITESPACE = seal(
  /[\u0000-\u0020\u00A0\u1680\u180E\u2000-\u2029\u205F\u3000]/g
  // eslint-disable-line no-control-regex
);
var DOCTYPE_NAME = seal(/^html$/i);
var CUSTOM_ELEMENT = seal(/^[a-z][.\w]*(-[.\w]+)+$/i);
var EXPRESSIONS = /* @__PURE__ */ Object.freeze({
  __proto__: null,
  MUSTACHE_EXPR,
  ERB_EXPR,
  TMPLIT_EXPR,
  DATA_ATTR,
  ARIA_ATTR,
  IS_ALLOWED_URI,
  IS_SCRIPT_OR_DATA,
  ATTR_WHITESPACE,
  DOCTYPE_NAME,
  CUSTOM_ELEMENT
});
var NODE_TYPE = {
  element: 1,
  attribute: 2,
  text: 3,
  cdataSection: 4,
  entityReference: 5,
  // Deprecated
  entityNode: 6,
  // Deprecated
  progressingInstruction: 7,
  comment: 8,
  document: 9,
  documentType: 10,
  documentFragment: 11,
  notation: 12
  // Deprecated
};
var getGlobal = function getGlobal2() {
  return typeof window === "undefined" ? null : window;
};
var _createTrustedTypesPolicy = function _createTrustedTypesPolicy2(trustedTypes, purifyHostElement) {
  if (typeof trustedTypes !== "object" || typeof trustedTypes.createPolicy !== "function") {
    return null;
  }
  let suffix = null;
  const ATTR_NAME = "data-tt-policy-suffix";
  if (purifyHostElement && purifyHostElement.hasAttribute(ATTR_NAME)) {
    suffix = purifyHostElement.getAttribute(ATTR_NAME);
  }
  const policyName = "dompurify" + (suffix ? "#" + suffix : "");
  try {
    return trustedTypes.createPolicy(policyName, {
      createHTML(html3) {
        return html3;
      },
      createScriptURL(scriptUrl) {
        return scriptUrl;
      }
    });
  } catch (_) {
    console.warn("TrustedTypes policy " + policyName + " could not be created.");
    return null;
  }
};
function createDOMPurify() {
  let window3 = arguments.length > 0 && arguments[0] !== void 0 ? arguments[0] : getGlobal();
  const DOMPurify = (root) => createDOMPurify(root);
  DOMPurify.version = "3.1.7";
  DOMPurify.removed = [];
  if (!window3 || !window3.document || window3.document.nodeType !== NODE_TYPE.document) {
    DOMPurify.isSupported = false;
    return DOMPurify;
  }
  let {
    document: document2
  } = window3;
  const originalDocument = document2;
  const currentScript = originalDocument.currentScript;
  const {
    DocumentFragment,
    HTMLTemplateElement,
    Node: Node6,
    Element: Element2,
    NodeFilter: NodeFilter2,
    NamedNodeMap = window3.NamedNodeMap || window3.MozNamedAttrMap,
    HTMLFormElement,
    DOMParser: DOMParser2,
    trustedTypes
  } = window3;
  const ElementPrototype = Element2.prototype;
  const cloneNode = lookupGetter(ElementPrototype, "cloneNode");
  const remove = lookupGetter(ElementPrototype, "remove");
  const getNextSibling = lookupGetter(ElementPrototype, "nextSibling");
  const getChildNodes = lookupGetter(ElementPrototype, "childNodes");
  const getParentNode = lookupGetter(ElementPrototype, "parentNode");
  if (typeof HTMLTemplateElement === "function") {
    const template = document2.createElement("template");
    if (template.content && template.content.ownerDocument) {
      document2 = template.content.ownerDocument;
    }
  }
  let trustedTypesPolicy;
  let emptyHTML = "";
  const {
    implementation,
    createNodeIterator,
    createDocumentFragment,
    getElementsByTagName
  } = document2;
  const {
    importNode
  } = originalDocument;
  let hooks = {};
  DOMPurify.isSupported = typeof entries === "function" && typeof getParentNode === "function" && implementation && implementation.createHTMLDocument !== void 0;
  const {
    MUSTACHE_EXPR: MUSTACHE_EXPR2,
    ERB_EXPR: ERB_EXPR2,
    TMPLIT_EXPR: TMPLIT_EXPR2,
    DATA_ATTR: DATA_ATTR2,
    ARIA_ATTR: ARIA_ATTR2,
    IS_SCRIPT_OR_DATA: IS_SCRIPT_OR_DATA2,
    ATTR_WHITESPACE: ATTR_WHITESPACE2,
    CUSTOM_ELEMENT: CUSTOM_ELEMENT2
  } = EXPRESSIONS;
  let {
    IS_ALLOWED_URI: IS_ALLOWED_URI$1
  } = EXPRESSIONS;
  let ALLOWED_TAGS = null;
  const DEFAULT_ALLOWED_TAGS = addToSet({}, [...html$1, ...svg$1, ...svgFilters, ...mathMl$1, ...text]);
  let ALLOWED_ATTR = null;
  const DEFAULT_ALLOWED_ATTR = addToSet({}, [...html, ...svg, ...mathMl, ...xml]);
  let CUSTOM_ELEMENT_HANDLING = Object.seal(create(null, {
    tagNameCheck: {
      writable: true,
      configurable: false,
      enumerable: true,
      value: null
    },
    attributeNameCheck: {
      writable: true,
      configurable: false,
      enumerable: true,
      value: null
    },
    allowCustomizedBuiltInElements: {
      writable: true,
      configurable: false,
      enumerable: true,
      value: false
    }
  }));
  let FORBID_TAGS = null;
  let FORBID_ATTR = null;
  let ALLOW_ARIA_ATTR = true;
  let ALLOW_DATA_ATTR = true;
  let ALLOW_UNKNOWN_PROTOCOLS = false;
  let ALLOW_SELF_CLOSE_IN_ATTR = true;
  let SAFE_FOR_TEMPLATES = false;
  let SAFE_FOR_XML = true;
  let WHOLE_DOCUMENT = false;
  let SET_CONFIG = false;
  let FORCE_BODY = false;
  let RETURN_DOM = false;
  let RETURN_DOM_FRAGMENT = false;
  let RETURN_TRUSTED_TYPE = false;
  let SANITIZE_DOM = true;
  let SANITIZE_NAMED_PROPS = false;
  const SANITIZE_NAMED_PROPS_PREFIX = "user-content-";
  let KEEP_CONTENT = true;
  let IN_PLACE = false;
  let USE_PROFILES = {};
  let FORBID_CONTENTS = null;
  const DEFAULT_FORBID_CONTENTS = addToSet({}, ["annotation-xml", "audio", "colgroup", "desc", "foreignobject", "head", "iframe", "math", "mi", "mn", "mo", "ms", "mtext", "noembed", "noframes", "noscript", "plaintext", "script", "style", "svg", "template", "thead", "title", "video", "xmp"]);
  let DATA_URI_TAGS = null;
  const DEFAULT_DATA_URI_TAGS = addToSet({}, ["audio", "video", "img", "source", "image", "track"]);
  let URI_SAFE_ATTRIBUTES = null;
  const DEFAULT_URI_SAFE_ATTRIBUTES = addToSet({}, ["alt", "class", "for", "id", "label", "name", "pattern", "placeholder", "role", "summary", "title", "value", "style", "xmlns"]);
  const MATHML_NAMESPACE = "http://www.w3.org/1998/Math/MathML";
  const SVG_NAMESPACE = "http://www.w3.org/2000/svg";
  const HTML_NAMESPACE = "http://www.w3.org/1999/xhtml";
  let NAMESPACE = HTML_NAMESPACE;
  let IS_EMPTY_INPUT = false;
  let ALLOWED_NAMESPACES = null;
  const DEFAULT_ALLOWED_NAMESPACES = addToSet({}, [MATHML_NAMESPACE, SVG_NAMESPACE, HTML_NAMESPACE], stringToString);
  let PARSER_MEDIA_TYPE = null;
  const SUPPORTED_PARSER_MEDIA_TYPES = ["application/xhtml+xml", "text/html"];
  const DEFAULT_PARSER_MEDIA_TYPE = "text/html";
  let transformCaseFunc = null;
  let CONFIG = null;
  const formElement = document2.createElement("form");
  const isRegexOrFunction = function isRegexOrFunction2(testValue) {
    return testValue instanceof RegExp || testValue instanceof Function;
  };
  const _parseConfig = function _parseConfig2() {
    let cfg = arguments.length > 0 && arguments[0] !== void 0 ? arguments[0] : {};
    if (CONFIG && CONFIG === cfg) {
      return;
    }
    if (!cfg || typeof cfg !== "object") {
      cfg = {};
    }
    cfg = clone(cfg);
    PARSER_MEDIA_TYPE = // eslint-disable-next-line unicorn/prefer-includes
    SUPPORTED_PARSER_MEDIA_TYPES.indexOf(cfg.PARSER_MEDIA_TYPE) === -1 ? DEFAULT_PARSER_MEDIA_TYPE : cfg.PARSER_MEDIA_TYPE;
    transformCaseFunc = PARSER_MEDIA_TYPE === "application/xhtml+xml" ? stringToString : stringToLowerCase;
    ALLOWED_TAGS = objectHasOwnProperty(cfg, "ALLOWED_TAGS") ? addToSet({}, cfg.ALLOWED_TAGS, transformCaseFunc) : DEFAULT_ALLOWED_TAGS;
    ALLOWED_ATTR = objectHasOwnProperty(cfg, "ALLOWED_ATTR") ? addToSet({}, cfg.ALLOWED_ATTR, transformCaseFunc) : DEFAULT_ALLOWED_ATTR;
    ALLOWED_NAMESPACES = objectHasOwnProperty(cfg, "ALLOWED_NAMESPACES") ? addToSet({}, cfg.ALLOWED_NAMESPACES, stringToString) : DEFAULT_ALLOWED_NAMESPACES;
    URI_SAFE_ATTRIBUTES = objectHasOwnProperty(cfg, "ADD_URI_SAFE_ATTR") ? addToSet(
      clone(DEFAULT_URI_SAFE_ATTRIBUTES),
      // eslint-disable-line indent
      cfg.ADD_URI_SAFE_ATTR,
      // eslint-disable-line indent
      transformCaseFunc
      // eslint-disable-line indent
    ) : DEFAULT_URI_SAFE_ATTRIBUTES;
    DATA_URI_TAGS = objectHasOwnProperty(cfg, "ADD_DATA_URI_TAGS") ? addToSet(
      clone(DEFAULT_DATA_URI_TAGS),
      // eslint-disable-line indent
      cfg.ADD_DATA_URI_TAGS,
      // eslint-disable-line indent
      transformCaseFunc
      // eslint-disable-line indent
    ) : DEFAULT_DATA_URI_TAGS;
    FORBID_CONTENTS = objectHasOwnProperty(cfg, "FORBID_CONTENTS") ? addToSet({}, cfg.FORBID_CONTENTS, transformCaseFunc) : DEFAULT_FORBID_CONTENTS;
    FORBID_TAGS = objectHasOwnProperty(cfg, "FORBID_TAGS") ? addToSet({}, cfg.FORBID_TAGS, transformCaseFunc) : {};
    FORBID_ATTR = objectHasOwnProperty(cfg, "FORBID_ATTR") ? addToSet({}, cfg.FORBID_ATTR, transformCaseFunc) : {};
    USE_PROFILES = objectHasOwnProperty(cfg, "USE_PROFILES") ? cfg.USE_PROFILES : false;
    ALLOW_ARIA_ATTR = cfg.ALLOW_ARIA_ATTR !== false;
    ALLOW_DATA_ATTR = cfg.ALLOW_DATA_ATTR !== false;
    ALLOW_UNKNOWN_PROTOCOLS = cfg.ALLOW_UNKNOWN_PROTOCOLS || false;
    ALLOW_SELF_CLOSE_IN_ATTR = cfg.ALLOW_SELF_CLOSE_IN_ATTR !== false;
    SAFE_FOR_TEMPLATES = cfg.SAFE_FOR_TEMPLATES || false;
    SAFE_FOR_XML = cfg.SAFE_FOR_XML !== false;
    WHOLE_DOCUMENT = cfg.WHOLE_DOCUMENT || false;
    RETURN_DOM = cfg.RETURN_DOM || false;
    RETURN_DOM_FRAGMENT = cfg.RETURN_DOM_FRAGMENT || false;
    RETURN_TRUSTED_TYPE = cfg.RETURN_TRUSTED_TYPE || false;
    FORCE_BODY = cfg.FORCE_BODY || false;
    SANITIZE_DOM = cfg.SANITIZE_DOM !== false;
    SANITIZE_NAMED_PROPS = cfg.SANITIZE_NAMED_PROPS || false;
    KEEP_CONTENT = cfg.KEEP_CONTENT !== false;
    IN_PLACE = cfg.IN_PLACE || false;
    IS_ALLOWED_URI$1 = cfg.ALLOWED_URI_REGEXP || IS_ALLOWED_URI;
    NAMESPACE = cfg.NAMESPACE || HTML_NAMESPACE;
    CUSTOM_ELEMENT_HANDLING = cfg.CUSTOM_ELEMENT_HANDLING || {};
    if (cfg.CUSTOM_ELEMENT_HANDLING && isRegexOrFunction(cfg.CUSTOM_ELEMENT_HANDLING.tagNameCheck)) {
      CUSTOM_ELEMENT_HANDLING.tagNameCheck = cfg.CUSTOM_ELEMENT_HANDLING.tagNameCheck;
    }
    if (cfg.CUSTOM_ELEMENT_HANDLING && isRegexOrFunction(cfg.CUSTOM_ELEMENT_HANDLING.attributeNameCheck)) {
      CUSTOM_ELEMENT_HANDLING.attributeNameCheck = cfg.CUSTOM_ELEMENT_HANDLING.attributeNameCheck;
    }
    if (cfg.CUSTOM_ELEMENT_HANDLING && typeof cfg.CUSTOM_ELEMENT_HANDLING.allowCustomizedBuiltInElements === "boolean") {
      CUSTOM_ELEMENT_HANDLING.allowCustomizedBuiltInElements = cfg.CUSTOM_ELEMENT_HANDLING.allowCustomizedBuiltInElements;
    }
    if (SAFE_FOR_TEMPLATES) {
      ALLOW_DATA_ATTR = false;
    }
    if (RETURN_DOM_FRAGMENT) {
      RETURN_DOM = true;
    }
    if (USE_PROFILES) {
      ALLOWED_TAGS = addToSet({}, text);
      ALLOWED_ATTR = [];
      if (USE_PROFILES.html === true) {
        addToSet(ALLOWED_TAGS, html$1);
        addToSet(ALLOWED_ATTR, html);
      }
      if (USE_PROFILES.svg === true) {
        addToSet(ALLOWED_TAGS, svg$1);
        addToSet(ALLOWED_ATTR, svg);
        addToSet(ALLOWED_ATTR, xml);
      }
      if (USE_PROFILES.svgFilters === true) {
        addToSet(ALLOWED_TAGS, svgFilters);
        addToSet(ALLOWED_ATTR, svg);
        addToSet(ALLOWED_ATTR, xml);
      }
      if (USE_PROFILES.mathMl === true) {
        addToSet(ALLOWED_TAGS, mathMl$1);
        addToSet(ALLOWED_ATTR, mathMl);
        addToSet(ALLOWED_ATTR, xml);
      }
    }
    if (cfg.ADD_TAGS) {
      if (ALLOWED_TAGS === DEFAULT_ALLOWED_TAGS) {
        ALLOWED_TAGS = clone(ALLOWED_TAGS);
      }
      addToSet(ALLOWED_TAGS, cfg.ADD_TAGS, transformCaseFunc);
    }
    if (cfg.ADD_ATTR) {
      if (ALLOWED_ATTR === DEFAULT_ALLOWED_ATTR) {
        ALLOWED_ATTR = clone(ALLOWED_ATTR);
      }
      addToSet(ALLOWED_ATTR, cfg.ADD_ATTR, transformCaseFunc);
    }
    if (cfg.ADD_URI_SAFE_ATTR) {
      addToSet(URI_SAFE_ATTRIBUTES, cfg.ADD_URI_SAFE_ATTR, transformCaseFunc);
    }
    if (cfg.FORBID_CONTENTS) {
      if (FORBID_CONTENTS === DEFAULT_FORBID_CONTENTS) {
        FORBID_CONTENTS = clone(FORBID_CONTENTS);
      }
      addToSet(FORBID_CONTENTS, cfg.FORBID_CONTENTS, transformCaseFunc);
    }
    if (KEEP_CONTENT) {
      ALLOWED_TAGS["#text"] = true;
    }
    if (WHOLE_DOCUMENT) {
      addToSet(ALLOWED_TAGS, ["html", "head", "body"]);
    }
    if (ALLOWED_TAGS.table) {
      addToSet(ALLOWED_TAGS, ["tbody"]);
      delete FORBID_TAGS.tbody;
    }
    if (cfg.TRUSTED_TYPES_POLICY) {
      if (typeof cfg.TRUSTED_TYPES_POLICY.createHTML !== "function") {
        throw typeErrorCreate('TRUSTED_TYPES_POLICY configuration option must provide a "createHTML" hook.');
      }
      if (typeof cfg.TRUSTED_TYPES_POLICY.createScriptURL !== "function") {
        throw typeErrorCreate('TRUSTED_TYPES_POLICY configuration option must provide a "createScriptURL" hook.');
      }
      trustedTypesPolicy = cfg.TRUSTED_TYPES_POLICY;
      emptyHTML = trustedTypesPolicy.createHTML("");
    } else {
      if (trustedTypesPolicy === void 0) {
        trustedTypesPolicy = _createTrustedTypesPolicy(trustedTypes, currentScript);
      }
      if (trustedTypesPolicy !== null && typeof emptyHTML === "string") {
        emptyHTML = trustedTypesPolicy.createHTML("");
      }
    }
    if (freeze) {
      freeze(cfg);
    }
    CONFIG = cfg;
  };
  const MATHML_TEXT_INTEGRATION_POINTS = addToSet({}, ["mi", "mo", "mn", "ms", "mtext"]);
  const HTML_INTEGRATION_POINTS = addToSet({}, ["annotation-xml"]);
  const COMMON_SVG_AND_HTML_ELEMENTS = addToSet({}, ["title", "style", "font", "a", "script"]);
  const ALL_SVG_TAGS = addToSet({}, [...svg$1, ...svgFilters, ...svgDisallowed]);
  const ALL_MATHML_TAGS = addToSet({}, [...mathMl$1, ...mathMlDisallowed]);
  const _checkValidNamespace = function _checkValidNamespace2(element) {
    let parent = getParentNode(element);
    if (!parent || !parent.tagName) {
      parent = {
        namespaceURI: NAMESPACE,
        tagName: "template"
      };
    }
    const tagName = stringToLowerCase(element.tagName);
    const parentTagName = stringToLowerCase(parent.tagName);
    if (!ALLOWED_NAMESPACES[element.namespaceURI]) {
      return false;
    }
    if (element.namespaceURI === SVG_NAMESPACE) {
      if (parent.namespaceURI === HTML_NAMESPACE) {
        return tagName === "svg";
      }
      if (parent.namespaceURI === MATHML_NAMESPACE) {
        return tagName === "svg" && (parentTagName === "annotation-xml" || MATHML_TEXT_INTEGRATION_POINTS[parentTagName]);
      }
      return Boolean(ALL_SVG_TAGS[tagName]);
    }
    if (element.namespaceURI === MATHML_NAMESPACE) {
      if (parent.namespaceURI === HTML_NAMESPACE) {
        return tagName === "math";
      }
      if (parent.namespaceURI === SVG_NAMESPACE) {
        return tagName === "math" && HTML_INTEGRATION_POINTS[parentTagName];
      }
      return Boolean(ALL_MATHML_TAGS[tagName]);
    }
    if (element.namespaceURI === HTML_NAMESPACE) {
      if (parent.namespaceURI === SVG_NAMESPACE && !HTML_INTEGRATION_POINTS[parentTagName]) {
        return false;
      }
      if (parent.namespaceURI === MATHML_NAMESPACE && !MATHML_TEXT_INTEGRATION_POINTS[parentTagName]) {
        return false;
      }
      return !ALL_MATHML_TAGS[tagName] && (COMMON_SVG_AND_HTML_ELEMENTS[tagName] || !ALL_SVG_TAGS[tagName]);
    }
    if (PARSER_MEDIA_TYPE === "application/xhtml+xml" && ALLOWED_NAMESPACES[element.namespaceURI]) {
      return true;
    }
    return false;
  };
  const _forceRemove = function _forceRemove2(node) {
    arrayPush(DOMPurify.removed, {
      element: node
    });
    try {
      getParentNode(node).removeChild(node);
    } catch (_) {
      remove(node);
    }
  };
  const _removeAttribute = function _removeAttribute2(name, node) {
    try {
      arrayPush(DOMPurify.removed, {
        attribute: node.getAttributeNode(name),
        from: node
      });
    } catch (_) {
      arrayPush(DOMPurify.removed, {
        attribute: null,
        from: node
      });
    }
    node.removeAttribute(name);
    if (name === "is" && !ALLOWED_ATTR[name]) {
      if (RETURN_DOM || RETURN_DOM_FRAGMENT) {
        try {
          _forceRemove(node);
        } catch (_) {
        }
      } else {
        try {
          node.setAttribute(name, "");
        } catch (_) {
        }
      }
    }
  };
  const _initDocument = function _initDocument2(dirty) {
    let doc = null;
    let leadingWhitespace = null;
    if (FORCE_BODY) {
      dirty = "<remove></remove>" + dirty;
    } else {
      const matches = stringMatch(dirty, /^[\r\n\t ]+/);
      leadingWhitespace = matches && matches[0];
    }
    if (PARSER_MEDIA_TYPE === "application/xhtml+xml" && NAMESPACE === HTML_NAMESPACE) {
      dirty = '<html xmlns="http://www.w3.org/1999/xhtml"><head></head><body>' + dirty + "</body></html>";
    }
    const dirtyPayload = trustedTypesPolicy ? trustedTypesPolicy.createHTML(dirty) : dirty;
    if (NAMESPACE === HTML_NAMESPACE) {
      try {
        doc = new DOMParser2().parseFromString(dirtyPayload, PARSER_MEDIA_TYPE);
      } catch (_) {
      }
    }
    if (!doc || !doc.documentElement) {
      doc = implementation.createDocument(NAMESPACE, "template", null);
      try {
        doc.documentElement.innerHTML = IS_EMPTY_INPUT ? emptyHTML : dirtyPayload;
      } catch (_) {
      }
    }
    const body = doc.body || doc.documentElement;
    if (dirty && leadingWhitespace) {
      body.insertBefore(document2.createTextNode(leadingWhitespace), body.childNodes[0] || null);
    }
    if (NAMESPACE === HTML_NAMESPACE) {
      return getElementsByTagName.call(doc, WHOLE_DOCUMENT ? "html" : "body")[0];
    }
    return WHOLE_DOCUMENT ? doc.documentElement : body;
  };
  const _createNodeIterator = function _createNodeIterator2(root) {
    return createNodeIterator.call(
      root.ownerDocument || root,
      root,
      // eslint-disable-next-line no-bitwise
      NodeFilter2.SHOW_ELEMENT | NodeFilter2.SHOW_COMMENT | NodeFilter2.SHOW_TEXT | NodeFilter2.SHOW_PROCESSING_INSTRUCTION | NodeFilter2.SHOW_CDATA_SECTION,
      null
    );
  };
  const _isClobbered = function _isClobbered2(elm) {
    return elm instanceof HTMLFormElement && (typeof elm.nodeName !== "string" || typeof elm.textContent !== "string" || typeof elm.removeChild !== "function" || !(elm.attributes instanceof NamedNodeMap) || typeof elm.removeAttribute !== "function" || typeof elm.setAttribute !== "function" || typeof elm.namespaceURI !== "string" || typeof elm.insertBefore !== "function" || typeof elm.hasChildNodes !== "function");
  };
  const _isNode = function _isNode2(object) {
    return typeof Node6 === "function" && object instanceof Node6;
  };
  const _executeHook = function _executeHook2(entryPoint, currentNode, data) {
    if (!hooks[entryPoint]) {
      return;
    }
    arrayForEach(hooks[entryPoint], (hook) => {
      hook.call(DOMPurify, currentNode, data, CONFIG);
    });
  };
  const _sanitizeElements = function _sanitizeElements2(currentNode) {
    let content = null;
    _executeHook("beforeSanitizeElements", currentNode, null);
    if (_isClobbered(currentNode)) {
      _forceRemove(currentNode);
      return true;
    }
    const tagName = transformCaseFunc(currentNode.nodeName);
    _executeHook("uponSanitizeElement", currentNode, {
      tagName,
      allowedTags: ALLOWED_TAGS
    });
    if (currentNode.hasChildNodes() && !_isNode(currentNode.firstElementChild) && regExpTest(/<[/\w]/g, currentNode.innerHTML) && regExpTest(/<[/\w]/g, currentNode.textContent)) {
      _forceRemove(currentNode);
      return true;
    }
    if (currentNode.nodeType === NODE_TYPE.progressingInstruction) {
      _forceRemove(currentNode);
      return true;
    }
    if (SAFE_FOR_XML && currentNode.nodeType === NODE_TYPE.comment && regExpTest(/<[/\w]/g, currentNode.data)) {
      _forceRemove(currentNode);
      return true;
    }
    if (!ALLOWED_TAGS[tagName] || FORBID_TAGS[tagName]) {
      if (!FORBID_TAGS[tagName] && _isBasicCustomElement(tagName)) {
        if (CUSTOM_ELEMENT_HANDLING.tagNameCheck instanceof RegExp && regExpTest(CUSTOM_ELEMENT_HANDLING.tagNameCheck, tagName)) {
          return false;
        }
        if (CUSTOM_ELEMENT_HANDLING.tagNameCheck instanceof Function && CUSTOM_ELEMENT_HANDLING.tagNameCheck(tagName)) {
          return false;
        }
      }
      if (KEEP_CONTENT && !FORBID_CONTENTS[tagName]) {
        const parentNode = getParentNode(currentNode) || currentNode.parentNode;
        const childNodes = getChildNodes(currentNode) || currentNode.childNodes;
        if (childNodes && parentNode) {
          const childCount = childNodes.length;
          for (let i2 = childCount - 1; i2 >= 0; --i2) {
            const childClone = cloneNode(childNodes[i2], true);
            childClone.__removalCount = (currentNode.__removalCount || 0) + 1;
            parentNode.insertBefore(childClone, getNextSibling(currentNode));
          }
        }
      }
      _forceRemove(currentNode);
      return true;
    }
    if (currentNode instanceof Element2 && !_checkValidNamespace(currentNode)) {
      _forceRemove(currentNode);
      return true;
    }
    if ((tagName === "noscript" || tagName === "noembed" || tagName === "noframes") && regExpTest(/<\/no(script|embed|frames)/i, currentNode.innerHTML)) {
      _forceRemove(currentNode);
      return true;
    }
    if (SAFE_FOR_TEMPLATES && currentNode.nodeType === NODE_TYPE.text) {
      content = currentNode.textContent;
      arrayForEach([MUSTACHE_EXPR2, ERB_EXPR2, TMPLIT_EXPR2], (expr) => {
        content = stringReplace(content, expr, " ");
      });
      if (currentNode.textContent !== content) {
        arrayPush(DOMPurify.removed, {
          element: currentNode.cloneNode()
        });
        currentNode.textContent = content;
      }
    }
    _executeHook("afterSanitizeElements", currentNode, null);
    return false;
  };
  const _isValidAttribute = function _isValidAttribute2(lcTag, lcName, value) {
    if (SANITIZE_DOM && (lcName === "id" || lcName === "name") && (value in document2 || value in formElement)) {
      return false;
    }
    if (ALLOW_DATA_ATTR && !FORBID_ATTR[lcName] && regExpTest(DATA_ATTR2, lcName)) ;
    else if (ALLOW_ARIA_ATTR && regExpTest(ARIA_ATTR2, lcName)) ;
    else if (!ALLOWED_ATTR[lcName] || FORBID_ATTR[lcName]) {
      if (
        // First condition does a very basic check if a) it's basically a valid custom element tagname AND
        // b) if the tagName passes whatever the user has configured for CUSTOM_ELEMENT_HANDLING.tagNameCheck
        // and c) if the attribute name passes whatever the user has configured for CUSTOM_ELEMENT_HANDLING.attributeNameCheck
        _isBasicCustomElement(lcTag) && (CUSTOM_ELEMENT_HANDLING.tagNameCheck instanceof RegExp && regExpTest(CUSTOM_ELEMENT_HANDLING.tagNameCheck, lcTag) || CUSTOM_ELEMENT_HANDLING.tagNameCheck instanceof Function && CUSTOM_ELEMENT_HANDLING.tagNameCheck(lcTag)) && (CUSTOM_ELEMENT_HANDLING.attributeNameCheck instanceof RegExp && regExpTest(CUSTOM_ELEMENT_HANDLING.attributeNameCheck, lcName) || CUSTOM_ELEMENT_HANDLING.attributeNameCheck instanceof Function && CUSTOM_ELEMENT_HANDLING.attributeNameCheck(lcName)) || // Alternative, second condition checks if it's an `is`-attribute, AND
        // the value passes whatever the user has configured for CUSTOM_ELEMENT_HANDLING.tagNameCheck
        lcName === "is" && CUSTOM_ELEMENT_HANDLING.allowCustomizedBuiltInElements && (CUSTOM_ELEMENT_HANDLING.tagNameCheck instanceof RegExp && regExpTest(CUSTOM_ELEMENT_HANDLING.tagNameCheck, value) || CUSTOM_ELEMENT_HANDLING.tagNameCheck instanceof Function && CUSTOM_ELEMENT_HANDLING.tagNameCheck(value))
      ) ;
      else {
        return false;
      }
    } else if (URI_SAFE_ATTRIBUTES[lcName]) ;
    else if (regExpTest(IS_ALLOWED_URI$1, stringReplace(value, ATTR_WHITESPACE2, ""))) ;
    else if ((lcName === "src" || lcName === "xlink:href" || lcName === "href") && lcTag !== "script" && stringIndexOf(value, "data:") === 0 && DATA_URI_TAGS[lcTag]) ;
    else if (ALLOW_UNKNOWN_PROTOCOLS && !regExpTest(IS_SCRIPT_OR_DATA2, stringReplace(value, ATTR_WHITESPACE2, ""))) ;
    else if (value) {
      return false;
    } else ;
    return true;
  };
  const _isBasicCustomElement = function _isBasicCustomElement2(tagName) {
    return tagName !== "annotation-xml" && stringMatch(tagName, CUSTOM_ELEMENT2);
  };
  const _sanitizeAttributes = function _sanitizeAttributes2(currentNode) {
    _executeHook("beforeSanitizeAttributes", currentNode, null);
    const {
      attributes
    } = currentNode;
    if (!attributes) {
      return;
    }
    const hookEvent = {
      attrName: "",
      attrValue: "",
      keepAttr: true,
      allowedAttributes: ALLOWED_ATTR
    };
    let l = attributes.length;
    while (l--) {
      const attr = attributes[l];
      const {
        name,
        namespaceURI,
        value: attrValue
      } = attr;
      const lcName = transformCaseFunc(name);
      let value = name === "value" ? attrValue : stringTrim(attrValue);
      hookEvent.attrName = lcName;
      hookEvent.attrValue = value;
      hookEvent.keepAttr = true;
      hookEvent.forceKeepAttr = void 0;
      _executeHook("uponSanitizeAttribute", currentNode, hookEvent);
      value = hookEvent.attrValue;
      if (hookEvent.forceKeepAttr) {
        continue;
      }
      _removeAttribute(name, currentNode);
      if (!hookEvent.keepAttr) {
        continue;
      }
      if (!ALLOW_SELF_CLOSE_IN_ATTR && regExpTest(/\/>/i, value)) {
        _removeAttribute(name, currentNode);
        continue;
      }
      if (SAFE_FOR_TEMPLATES) {
        arrayForEach([MUSTACHE_EXPR2, ERB_EXPR2, TMPLIT_EXPR2], (expr) => {
          value = stringReplace(value, expr, " ");
        });
      }
      const lcTag = transformCaseFunc(currentNode.nodeName);
      if (!_isValidAttribute(lcTag, lcName, value)) {
        continue;
      }
      if (SANITIZE_NAMED_PROPS && (lcName === "id" || lcName === "name")) {
        _removeAttribute(name, currentNode);
        value = SANITIZE_NAMED_PROPS_PREFIX + value;
      }
      if (SAFE_FOR_XML && regExpTest(/((--!?|])>)|<\/(style|title)/i, value)) {
        _removeAttribute(name, currentNode);
        continue;
      }
      if (trustedTypesPolicy && typeof trustedTypes === "object" && typeof trustedTypes.getAttributeType === "function") {
        if (namespaceURI) ;
        else {
          switch (trustedTypes.getAttributeType(lcTag, lcName)) {
            case "TrustedHTML": {
              value = trustedTypesPolicy.createHTML(value);
              break;
            }
            case "TrustedScriptURL": {
              value = trustedTypesPolicy.createScriptURL(value);
              break;
            }
          }
        }
      }
      try {
        if (namespaceURI) {
          currentNode.setAttributeNS(namespaceURI, name, value);
        } else {
          currentNode.setAttribute(name, value);
        }
        if (_isClobbered(currentNode)) {
          _forceRemove(currentNode);
        } else {
          arrayPop(DOMPurify.removed);
        }
      } catch (_) {
      }
    }
    _executeHook("afterSanitizeAttributes", currentNode, null);
  };
  const _sanitizeShadowDOM = function _sanitizeShadowDOM2(fragment) {
    let shadowNode = null;
    const shadowIterator = _createNodeIterator(fragment);
    _executeHook("beforeSanitizeShadowDOM", fragment, null);
    while (shadowNode = shadowIterator.nextNode()) {
      _executeHook("uponSanitizeShadowNode", shadowNode, null);
      if (_sanitizeElements(shadowNode)) {
        continue;
      }
      if (shadowNode.content instanceof DocumentFragment) {
        _sanitizeShadowDOM2(shadowNode.content);
      }
      _sanitizeAttributes(shadowNode);
    }
    _executeHook("afterSanitizeShadowDOM", fragment, null);
  };
  DOMPurify.sanitize = function(dirty) {
    let cfg = arguments.length > 1 && arguments[1] !== void 0 ? arguments[1] : {};
    let body = null;
    let importedNode = null;
    let currentNode = null;
    let returnNode = null;
    IS_EMPTY_INPUT = !dirty;
    if (IS_EMPTY_INPUT) {
      dirty = "<!-->";
    }
    if (typeof dirty !== "string" && !_isNode(dirty)) {
      if (typeof dirty.toString === "function") {
        dirty = dirty.toString();
        if (typeof dirty !== "string") {
          throw typeErrorCreate("dirty is not a string, aborting");
        }
      } else {
        throw typeErrorCreate("toString is not a function");
      }
    }
    if (!DOMPurify.isSupported) {
      return dirty;
    }
    if (!SET_CONFIG) {
      _parseConfig(cfg);
    }
    DOMPurify.removed = [];
    if (typeof dirty === "string") {
      IN_PLACE = false;
    }
    if (IN_PLACE) {
      if (dirty.nodeName) {
        const tagName = transformCaseFunc(dirty.nodeName);
        if (!ALLOWED_TAGS[tagName] || FORBID_TAGS[tagName]) {
          throw typeErrorCreate("root node is forbidden and cannot be sanitized in-place");
        }
      }
    } else if (dirty instanceof Node6) {
      body = _initDocument("<!---->");
      importedNode = body.ownerDocument.importNode(dirty, true);
      if (importedNode.nodeType === NODE_TYPE.element && importedNode.nodeName === "BODY") {
        body = importedNode;
      } else if (importedNode.nodeName === "HTML") {
        body = importedNode;
      } else {
        body.appendChild(importedNode);
      }
    } else {
      if (!RETURN_DOM && !SAFE_FOR_TEMPLATES && !WHOLE_DOCUMENT && // eslint-disable-next-line unicorn/prefer-includes
      dirty.indexOf("<") === -1) {
        return trustedTypesPolicy && RETURN_TRUSTED_TYPE ? trustedTypesPolicy.createHTML(dirty) : dirty;
      }
      body = _initDocument(dirty);
      if (!body) {
        return RETURN_DOM ? null : RETURN_TRUSTED_TYPE ? emptyHTML : "";
      }
    }
    if (body && FORCE_BODY) {
      _forceRemove(body.firstChild);
    }
    const nodeIterator = _createNodeIterator(IN_PLACE ? dirty : body);
    while (currentNode = nodeIterator.nextNode()) {
      if (_sanitizeElements(currentNode)) {
        continue;
      }
      if (currentNode.content instanceof DocumentFragment) {
        _sanitizeShadowDOM(currentNode.content);
      }
      _sanitizeAttributes(currentNode);
    }
    if (IN_PLACE) {
      return dirty;
    }
    if (RETURN_DOM) {
      if (RETURN_DOM_FRAGMENT) {
        returnNode = createDocumentFragment.call(body.ownerDocument);
        while (body.firstChild) {
          returnNode.appendChild(body.firstChild);
        }
      } else {
        returnNode = body;
      }
      if (ALLOWED_ATTR.shadowroot || ALLOWED_ATTR.shadowrootmode) {
        returnNode = importNode.call(originalDocument, returnNode, true);
      }
      return returnNode;
    }
    let serializedHTML = WHOLE_DOCUMENT ? body.outerHTML : body.innerHTML;
    if (WHOLE_DOCUMENT && ALLOWED_TAGS["!doctype"] && body.ownerDocument && body.ownerDocument.doctype && body.ownerDocument.doctype.name && regExpTest(DOCTYPE_NAME, body.ownerDocument.doctype.name)) {
      serializedHTML = "<!DOCTYPE " + body.ownerDocument.doctype.name + ">\n" + serializedHTML;
    }
    if (SAFE_FOR_TEMPLATES) {
      arrayForEach([MUSTACHE_EXPR2, ERB_EXPR2, TMPLIT_EXPR2], (expr) => {
        serializedHTML = stringReplace(serializedHTML, expr, " ");
      });
    }
    return trustedTypesPolicy && RETURN_TRUSTED_TYPE ? trustedTypesPolicy.createHTML(serializedHTML) : serializedHTML;
  };
  DOMPurify.setConfig = function() {
    let cfg = arguments.length > 0 && arguments[0] !== void 0 ? arguments[0] : {};
    _parseConfig(cfg);
    SET_CONFIG = true;
  };
  DOMPurify.clearConfig = function() {
    CONFIG = null;
    SET_CONFIG = false;
  };
  DOMPurify.isValidAttribute = function(tag2, attr, value) {
    if (!CONFIG) {
      _parseConfig({});
    }
    const lcTag = transformCaseFunc(tag2);
    const lcName = transformCaseFunc(attr);
    return _isValidAttribute(lcTag, lcName, value);
  };
  DOMPurify.addHook = function(entryPoint, hookFunction) {
    if (typeof hookFunction !== "function") {
      return;
    }
    hooks[entryPoint] = hooks[entryPoint] || [];
    arrayPush(hooks[entryPoint], hookFunction);
  };
  DOMPurify.removeHook = function(entryPoint) {
    if (hooks[entryPoint]) {
      return arrayPop(hooks[entryPoint]);
    }
  };
  DOMPurify.removeHooks = function(entryPoint) {
    if (hooks[entryPoint]) {
      hooks[entryPoint] = [];
    }
  };
  DOMPurify.removeAllHooks = function() {
    hooks = {};
  };
  return DOMPurify;
}
var purify = createDOMPurify();

// out-build/vs/base/common/hash.js
function $Xi(obj) {
  return $Yi(obj, 0);
}
function $Yi(obj, hashVal) {
  switch (typeof obj) {
    case "object":
      if (obj === null) {
        return $Zi(349, hashVal);
      } else if (Array.isArray(obj)) {
        return arrayHash(obj, hashVal);
      }
      return objectHash(obj, hashVal);
    case "string":
      return $1i(obj, hashVal);
    case "boolean":
      return booleanHash(obj, hashVal);
    case "number":
      return $Zi(obj, hashVal);
    case "undefined":
      return $Zi(937, hashVal);
    default:
      return $Zi(617, hashVal);
  }
}
function $Zi(val, initialHashVal) {
  return (initialHashVal << 5) - initialHashVal + val | 0;
}
function booleanHash(b, initialHashVal) {
  return $Zi(b ? 433 : 863, initialHashVal);
}
function $1i(s, hashVal) {
  hashVal = $Zi(149417, hashVal);
  for (let i2 = 0, length = s.length; i2 < length; i2++) {
    hashVal = $Zi(s.charCodeAt(i2), hashVal);
  }
  return hashVal;
}
function arrayHash(arr, initialHashVal) {
  initialHashVal = $Zi(104579, initialHashVal);
  return arr.reduce((hashVal, item) => $Yi(item, hashVal), initialHashVal);
}
function objectHash(obj, initialHashVal) {
  initialHashVal = $Zi(181387, initialHashVal);
  return Object.keys(obj).sort().reduce((hashVal, key2) => {
    hashVal = $1i(key2, hashVal);
    return $Yi(obj[key2], hashVal);
  }, initialHashVal);
}
var $2i = (input) => {
  if (typeof input === "string" && input.length < 250) {
    const sha = new $3i();
    sha.update(input);
    return Promise.resolve(sha.digest());
  }
  let buff;
  if (typeof input === "string") {
    buff = new TextEncoder().encode(input);
  } else if (input instanceof $Ci) {
    buff = input.buffer;
  } else {
    buff = input;
  }
  return crypto.subtle.digest("sha-1", buff).then(toHexString);
};
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 toHexString(bufferOrValue, bitsize = 32) {
  if (bufferOrValue instanceof ArrayBuffer) {
    return Array.from(new Uint8Array(bufferOrValue)).map((b) => b.toString(16).padStart(2, "0")).join("");
  }
  return (bufferOrValue >>> 0).toString(16).padStart(bitsize / 4, "0");
}
var $3i = class _$3i {
  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 ($5f(charCode)) {
        if (offset + 1 < strLen) {
          const nextCharCode = str.charCodeAt(offset + 1);
          if ($6f(nextCharCode)) {
            offset++;
            codePoint = $7f(charCode, nextCharCode);
          } else {
            codePoint = 65533;
          }
        } else {
          leftoverHighSurrogate = charCode;
          break;
        }
      } else if ($6f(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 toHexString(this.h) + toHexString(this.l) + toHexString(this.m) + toHexString(this.n) + toHexString(this.o);
  }
  x() {
    this.p[this.r++] = 128;
    this.p.subarray(this.r).fill(0);
    if (this.r > 56) {
      this.y();
      this.p.fill(0);
    }
    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 = _$3i.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/base/common/numbers.js
function $4i(value, min, max) {
  return Math.min(Math.max(value, min), max);
}
function rot(index, modulo) {
  return (modulo + index % modulo) % modulo;
}
var $7i = class {
  constructor() {
    this.a = 1;
    this.b = 0;
  }
  update(value) {
    this.b = this.b + (value - this.b) / this.a;
    this.a += 1;
    return this.b;
  }
  get value() {
    return this.b;
  }
};
var $8i = class {
  constructor(size) {
    this.a = 0;
    this.b = 0;
    this.c = [];
    this.d = 0;
    this.e = 0;
    this.c = new Array(size);
    this.c.fill(0, 0, size);
  }
  update(value) {
    const oldValue = this.c[this.d];
    this.c[this.d] = value;
    this.d = (this.d + 1) % this.c.length;
    this.e -= oldValue;
    this.e += value;
    if (this.a < this.c.length) {
      this.a += 1;
    }
    this.b = this.e / this.a;
    return this.b;
  }
  get value() {
    return this.b;
  }
};
function $9i(x, y, ax, ay, bx, by, cx, cy) {
  const v0x = cx - ax;
  const v0y = cy - ay;
  const v1x = bx - ax;
  const v1y = by - ay;
  const v2x = x - ax;
  const v2y = y - ay;
  const dot00 = v0x * v0x + v0y * v0y;
  const dot01 = v0x * v1x + v0y * v1y;
  const dot02 = v0x * v2x + v0y * v2y;
  const dot11 = v1x * v1x + v1y * v1y;
  const dot12 = v1x * v2x + v1y * v2y;
  const invDenom = 1 / (dot00 * dot11 - dot01 * dot01);
  const u = (dot11 * dot02 - dot01 * dot12) * invDenom;
  const v = (dot00 * dot12 - dot01 * dot02) * invDenom;
  return u >= 0 && v >= 0 && u + v < 1;
}

// out-build/vs/base/browser/dom.js
var { registerWindow, getWindow, getDocument, getWindows, getWindowsCount, getWindowId, getWindowById, hasWindow, onDidRegisterWindow, onWillUnregisterWindow, onDidUnregisterWindow } = function() {
  const windows = /* @__PURE__ */ new Map();
  $X($Y, 1);
  const mainWindowRegistration = { window: $Y, disposables: new $2c() };
  windows.set($Y.vscodeWindowId, mainWindowRegistration);
  const onDidRegisterWindow2 = new $ze();
  const onDidUnregisterWindow2 = new $ze();
  const onWillUnregisterWindow2 = new $ze();
  function getWindowById2(windowId, fallbackToMain) {
    const window3 = typeof windowId === "number" ? windows.get(windowId) : void 0;
    return window3 ?? (fallbackToMain ? mainWindowRegistration : void 0);
  }
  return {
    onDidRegisterWindow: onDidRegisterWindow2.event,
    onWillUnregisterWindow: onWillUnregisterWindow2.event,
    onDidUnregisterWindow: onDidUnregisterWindow2.event,
    registerWindow(window3) {
      if (windows.has(window3.vscodeWindowId)) {
        return $3c.None;
      }
      const disposables = new $2c();
      const registeredWindow = {
        window: window3,
        disposables: disposables.add(new $2c())
      };
      windows.set(window3.vscodeWindowId, registeredWindow);
      disposables.add($1c(() => {
        windows.delete(window3.vscodeWindowId);
        onDidUnregisterWindow2.fire(window3);
      }));
      disposables.add($_i(window3, $7j.BEFORE_UNLOAD, () => {
        onWillUnregisterWindow2.fire(window3);
      }));
      onDidRegisterWindow2.fire(registeredWindow);
      return disposables;
    },
    getWindows() {
      return windows.values();
    },
    getWindowsCount() {
      return windows.size;
    },
    getWindowId(targetWindow) {
      return targetWindow.vscodeWindowId;
    },
    hasWindow(windowId) {
      return windows.has(windowId);
    },
    getWindowById: getWindowById2,
    getWindow(e) {
      const candidateNode = e;
      if (candidateNode?.ownerDocument?.defaultView) {
        return candidateNode.ownerDocument.defaultView.window;
      }
      const candidateEvent = e;
      if (candidateEvent?.view) {
        return candidateEvent.view.window;
      }
      return $Y;
    },
    getDocument(e) {
      const candidateNode = e;
      return getWindow(candidateNode).document;
    }
  };
}();
function $$i(node) {
  while (node.firstChild) {
    node.firstChild.remove();
  }
}
var DomListener = class {
  constructor(node, type, handler, options3) {
    this.f = node;
    this.g = type;
    this.d = handler;
    this.j = options3 || false;
    this.f.addEventListener(this.g, this.d, this.j);
  }
  dispose() {
    if (!this.d) {
      return;
    }
    this.f.removeEventListener(this.g, this.d, this.j);
    this.f = null;
    this.d = null;
  }
};
function $_i(node, type, handler, useCaptureOrOptions) {
  return new DomListener(node, type, handler, useCaptureOrOptions);
}
function _wrapAsStandardMouseEvent(targetWindow, handler) {
  return function(e) {
    return handler(new $lf(targetWindow, e));
  };
}
function _wrapAsStandardKeyboardEvent(handler) {
  return function(e) {
    return handler(new $if(e));
  };
}
var $aj = function addStandardDisposableListener(node, type, handler, useCapture) {
  let wrapHandler = handler;
  if (type === "click" || type === "mousedown" || type === "contextmenu") {
    wrapHandler = _wrapAsStandardMouseEvent(getWindow(node), handler);
  } else if (type === "keydown" || type === "keypress" || type === "keyup") {
    wrapHandler = _wrapAsStandardKeyboardEvent(handler);
  }
  return $_i(node, type, wrapHandler, useCapture);
};
var $bj = function addStandardDisposableListener2(node, handler, useCapture) {
  const wrapHandler = _wrapAsStandardMouseEvent(getWindow(node), handler);
  return $dj(node, wrapHandler, useCapture);
};
var $cj = function addStandardDisposableListener3(node, handler, useCapture) {
  const wrapHandler = _wrapAsStandardMouseEvent(getWindow(node), handler);
  return $fj(node, wrapHandler, useCapture);
};
function $dj(node, handler, useCapture) {
  return $_i(node, $u && $5e.pointerEvents ? $7j.POINTER_DOWN : $7j.MOUSE_DOWN, handler, useCapture);
}
function $ej(node, handler, useCapture) {
  return $_i(node, $u && $5e.pointerEvents ? $7j.POINTER_MOVE : $7j.MOUSE_MOVE, handler, useCapture);
}
function $fj(node, handler, useCapture) {
  return $_i(node, $u && $5e.pointerEvents ? $7j.POINTER_UP : $7j.MOUSE_UP, handler, useCapture);
}
function $gj(targetWindow, callback, timeout) {
  return $ai(targetWindow, callback, timeout);
}
var $hj = class extends $bi {
  constructor(targetWindow, executor) {
    super(targetWindow, executor);
  }
};
var $ij;
var $jj;
function $kj(targetWindow, handler, interval, iterations) {
  let iteration = 0;
  const timer = targetWindow.setInterval(() => {
    iteration++;
    if (typeof iterations === "number" && iteration >= iterations || handler() === true) {
      disposable.dispose();
    }
  }, interval);
  const disposable = $1c(() => {
    targetWindow.clearInterval(timer);
  });
  return disposable;
}
var $lj = class extends $7h {
  /**
   *
   * @param node The optional node from which the target window is determined
   */
  constructor(node) {
    super();
    this.g = node && getWindow(node);
  }
  cancelAndSet(runner, interval, targetWindow) {
    return super.cancelAndSet(runner, interval, targetWindow ?? this.g);
  }
};
var AnimationFrameQueueItem = class {
  constructor(runner, priority = 0) {
    this.d = runner;
    this.priority = priority;
    this.f = false;
  }
  dispose() {
    this.f = true;
  }
  execute() {
    if (this.f) {
      return;
    }
    try {
      this.d();
    } catch (e) {
      $gb(e);
    }
  }
  // Sort by priority (largest to lowest)
  static sort(a, b) {
    return b.priority - a.priority;
  }
};
(function() {
  const NEXT_QUEUE = /* @__PURE__ */ new Map();
  const CURRENT_QUEUE = /* @__PURE__ */ new Map();
  const animFrameRequested = /* @__PURE__ */ new Map();
  const inAnimationFrameRunner = /* @__PURE__ */ new Map();
  const animationFrameRunner = (targetWindowId) => {
    animFrameRequested.set(targetWindowId, false);
    const currentQueue = NEXT_QUEUE.get(targetWindowId) ?? [];
    CURRENT_QUEUE.set(targetWindowId, currentQueue);
    NEXT_QUEUE.set(targetWindowId, []);
    inAnimationFrameRunner.set(targetWindowId, true);
    while (currentQueue.length > 0) {
      currentQueue.sort(AnimationFrameQueueItem.sort);
      const top2 = currentQueue.shift();
      top2.execute();
    }
    inAnimationFrameRunner.set(targetWindowId, false);
  };
  $jj = (targetWindow, runner, priority = 0) => {
    const targetWindowId = getWindowId(targetWindow);
    const item = new AnimationFrameQueueItem(runner, priority);
    let nextQueue = NEXT_QUEUE.get(targetWindowId);
    if (!nextQueue) {
      nextQueue = [];
      NEXT_QUEUE.set(targetWindowId, nextQueue);
    }
    nextQueue.push(item);
    if (!animFrameRequested.get(targetWindowId)) {
      animFrameRequested.set(targetWindowId, true);
      targetWindow.requestAnimationFrame(() => animationFrameRunner(targetWindowId));
    }
    return item;
  };
  $ij = (targetWindow, runner, priority) => {
    const targetWindowId = getWindowId(targetWindow);
    if (inAnimationFrameRunner.get(targetWindowId)) {
      const item = new AnimationFrameQueueItem(runner, priority);
      let currentQueue = CURRENT_QUEUE.get(targetWindowId);
      if (!currentQueue) {
        currentQueue = [];
        CURRENT_QUEUE.set(targetWindowId, currentQueue);
      }
      currentQueue.push(item);
      return item;
    } else {
      return $jj(targetWindow, runner, priority);
    }
  };
})();
function $mj(targetWindow, callback) {
  return $jj(
    targetWindow,
    callback,
    1e4
    /* must be early */
  );
}
function $nj(targetWindow, callback) {
  return $jj(
    targetWindow,
    callback,
    -1e4
    /* must be late */
  );
}
var MINIMUM_TIME_MS = 8;
var DEFAULT_EVENT_MERGER = function(lastEvent, currentEvent) {
  return currentEvent;
};
var TimeoutThrottledDomListener = class extends $3c {
  constructor(node, type, handler, eventMerger = DEFAULT_EVENT_MERGER, minimumTimeMs = MINIMUM_TIME_MS) {
    super();
    let lastEvent = null;
    let lastHandlerTime = 0;
    const timeout = this.B(new $6h());
    const invokeHandler = () => {
      lastHandlerTime = (/* @__PURE__ */ new Date()).getTime();
      handler(lastEvent);
      lastEvent = null;
    };
    this.B($_i(node, type, (e) => {
      lastEvent = eventMerger(lastEvent, e);
      const elapsedTime = (/* @__PURE__ */ new Date()).getTime() - lastHandlerTime;
      if (elapsedTime >= minimumTimeMs) {
        timeout.cancel();
        invokeHandler();
      } else {
        timeout.setIfNotSet(invokeHandler, minimumTimeMs - elapsedTime);
      }
    }));
  }
};
function $oj(node, type, handler, eventMerger, minimumTimeMs) {
  return new TimeoutThrottledDomListener(node, type, handler, eventMerger, minimumTimeMs);
}
function $pj(el) {
  return getWindow(el).getComputedStyle(el, null);
}
function $qj(element, fallback2) {
  const elWindow = getWindow(element);
  const elDocument = elWindow.document;
  if (element !== elDocument.body) {
    return new $rj(element.clientWidth, element.clientHeight);
  }
  if ($u && elWindow?.visualViewport) {
    return new $rj(elWindow.visualViewport.width, elWindow.visualViewport.height);
  }
  if (elWindow?.innerWidth && elWindow.innerHeight) {
    return new $rj(elWindow.innerWidth, elWindow.innerHeight);
  }
  if (elDocument.body && elDocument.body.clientWidth && elDocument.body.clientHeight) {
    return new $rj(elDocument.body.clientWidth, elDocument.body.clientHeight);
  }
  if (elDocument.documentElement && elDocument.documentElement.clientWidth && elDocument.documentElement.clientHeight) {
    return new $rj(elDocument.documentElement.clientWidth, elDocument.documentElement.clientHeight);
  }
  if (fallback2) {
    return $qj(fallback2);
  }
  throw new Error("Unable to figure out browser width and height");
}
var SizeUtils = class _SizeUtils {
  // Adapted from WinJS
  // Converts a CSS positioning string for the specified element to pixels.
  static d(element, value) {
    return parseFloat(value) || 0;
  }
  static f(element, cssPropertyName, jsPropertyName) {
    const computedStyle = $pj(element);
    const value = computedStyle ? computedStyle.getPropertyValue(cssPropertyName) : "0";
    return _SizeUtils.d(element, value);
  }
  static getBorderLeftWidth(element) {
    return _SizeUtils.f(element, "border-left-width", "borderLeftWidth");
  }
  static getBorderRightWidth(element) {
    return _SizeUtils.f(element, "border-right-width", "borderRightWidth");
  }
  static getBorderTopWidth(element) {
    return _SizeUtils.f(element, "border-top-width", "borderTopWidth");
  }
  static getBorderBottomWidth(element) {
    return _SizeUtils.f(element, "border-bottom-width", "borderBottomWidth");
  }
  static getPaddingLeft(element) {
    return _SizeUtils.f(element, "padding-left", "paddingLeft");
  }
  static getPaddingRight(element) {
    return _SizeUtils.f(element, "padding-right", "paddingRight");
  }
  static getPaddingTop(element) {
    return _SizeUtils.f(element, "padding-top", "paddingTop");
  }
  static getPaddingBottom(element) {
    return _SizeUtils.f(element, "padding-bottom", "paddingBottom");
  }
  static getMarginLeft(element) {
    return _SizeUtils.f(element, "margin-left", "marginLeft");
  }
  static getMarginTop(element) {
    return _SizeUtils.f(element, "margin-top", "marginTop");
  }
  static getMarginRight(element) {
    return _SizeUtils.f(element, "margin-right", "marginRight");
  }
  static getMarginBottom(element) {
    return _SizeUtils.f(element, "margin-bottom", "marginBottom");
  }
};
var $rj = class _$rj {
  static {
    this.None = new _$rj(0, 0);
  }
  constructor(width2, height) {
    this.width = width2;
    this.height = height;
  }
  with(width2 = this.width, height = this.height) {
    if (width2 !== this.width || height !== this.height) {
      return new _$rj(width2, height);
    } else {
      return this;
    }
  }
  static is(obj) {
    return typeof obj === "object" && typeof obj.height === "number" && typeof obj.width === "number";
  }
  static lift(obj) {
    if (obj instanceof _$rj) {
      return obj;
    } else {
      return new _$rj(obj.width, obj.height);
    }
  }
  static equals(a, b) {
    if (a === b) {
      return true;
    }
    if (!a || !b) {
      return false;
    }
    return a.width === b.width && a.height === b.height;
  }
};
function $sj(element) {
  let offsetParent = element.offsetParent;
  let top2 = element.offsetTop;
  let left = element.offsetLeft;
  while ((element = element.parentNode) !== null && element !== element.ownerDocument.body && element !== element.ownerDocument.documentElement) {
    top2 -= element.scrollTop;
    const c = $Ij(element) ? null : $pj(element);
    if (c) {
      left -= c.direction !== "rtl" ? element.scrollLeft : -element.scrollLeft;
    }
    if (element === offsetParent) {
      left += SizeUtils.getBorderLeftWidth(element);
      top2 += SizeUtils.getBorderTopWidth(element);
      top2 += element.offsetTop;
      left += element.offsetLeft;
      offsetParent = element.offsetParent;
    }
  }
  return {
    left,
    top: top2
  };
}
function $tj(element, width2, height) {
  if (typeof width2 === "number") {
    element.style.width = `${width2}px`;
  }
  if (typeof height === "number") {
    element.style.height = `${height}px`;
  }
}
function $uj(element, top2, right, bottom, left, position = "absolute") {
  if (typeof top2 === "number") {
    element.style.top = `${top2}px`;
  }
  if (typeof right === "number") {
    element.style.right = `${right}px`;
  }
  if (typeof bottom === "number") {
    element.style.bottom = `${bottom}px`;
  }
  if (typeof left === "number") {
    element.style.left = `${left}px`;
  }
  element.style.position = position;
}
function $vj(domNode) {
  const bb = domNode.getBoundingClientRect();
  const window3 = getWindow(domNode);
  return {
    left: bb.left + window3.scrollX,
    top: bb.top + window3.scrollY,
    width: bb.width,
    height: bb.height
  };
}
function $wj(domNode) {
  let testElement = domNode;
  let zoom = 1;
  do {
    const elementZoomLevel = $pj(testElement).zoom;
    if (elementZoomLevel !== null && elementZoomLevel !== void 0 && elementZoomLevel !== "1") {
      zoom *= elementZoomLevel;
    }
    testElement = testElement.parentElement;
  } while (testElement !== null && testElement !== testElement.ownerDocument.documentElement);
  return zoom;
}
function $xj(element) {
  const margin = SizeUtils.getMarginLeft(element) + SizeUtils.getMarginRight(element);
  return element.offsetWidth + margin;
}
function $yj(element) {
  const border = SizeUtils.getBorderLeftWidth(element) + SizeUtils.getBorderRightWidth(element);
  const padding = SizeUtils.getPaddingLeft(element) + SizeUtils.getPaddingRight(element);
  return element.offsetWidth - border - padding;
}
function $zj(element) {
  const margin = SizeUtils.getMarginLeft(element) + SizeUtils.getMarginRight(element);
  return element.scrollWidth + margin;
}
function $Aj(element) {
  const border = SizeUtils.getBorderTopWidth(element) + SizeUtils.getBorderBottomWidth(element);
  const padding = SizeUtils.getPaddingTop(element) + SizeUtils.getPaddingBottom(element);
  return element.offsetHeight - border - padding;
}
function $Bj(element) {
  const margin = SizeUtils.getMarginTop(element) + SizeUtils.getMarginBottom(element);
  return element.offsetHeight + margin;
}
function getRelativeLeft(element, parent) {
  if (element === null) {
    return 0;
  }
  const elementPosition = $sj(element);
  const parentPosition = $sj(parent);
  return elementPosition.left - parentPosition.left;
}
function $Cj(parent, children) {
  const childWidths = children.map((child) => {
    return Math.max($zj(child), $xj(child)) + getRelativeLeft(child, parent) || 0;
  });
  const maxWidth = Math.max(...childWidths);
  return maxWidth;
}
function $Dj(testChild, testAncestor) {
  return Boolean(testAncestor?.contains(testChild));
}
var parentFlowToDataKey = "parentFlowToElementId";
function $Ej(fromChildElement, toParentElement) {
  fromChildElement.dataset[parentFlowToDataKey] = toParentElement.id;
}
function getParentFlowToElement(node) {
  const flowToParentId = node.dataset[parentFlowToDataKey];
  if (typeof flowToParentId === "string") {
    return node.ownerDocument.getElementById(flowToParentId);
  }
  return null;
}
function $Fj(testChild, testAncestor) {
  let node = testChild;
  while (node) {
    if (node === testAncestor) {
      return true;
    }
    if ($Uj(node)) {
      const flowToParentElement = getParentFlowToElement(node);
      if (flowToParentElement) {
        node = flowToParentElement;
        continue;
      }
    }
    node = node.parentNode;
  }
  return false;
}
function $Gj(node, clazz, stopAtClazzOrNode) {
  while (node && node.nodeType === node.ELEMENT_NODE) {
    if (node.classList.contains(clazz)) {
      return node;
    }
    if (stopAtClazzOrNode) {
      if (typeof stopAtClazzOrNode === "string") {
        if (node.classList.contains(stopAtClazzOrNode)) {
          return null;
        }
      } else {
        if (node === stopAtClazzOrNode) {
          return null;
        }
      }
    }
    node = node.parentNode;
  }
  return null;
}
function $Hj(node, clazz, stopAtClazzOrNode) {
  return !!$Gj(node, clazz, stopAtClazzOrNode);
}
function $Ij(node) {
  return node && !!node.host && !!node.mode;
}
function $Jj(domNode) {
  return !!$Kj(domNode);
}
function $Kj(domNode) {
  while (domNode.parentNode) {
    if (domNode === domNode.ownerDocument?.body) {
      return null;
    }
    domNode = domNode.parentNode;
  }
  return $Ij(domNode) ? domNode : null;
}
function $Lj() {
  let result = $Pj().activeElement;
  while (result?.shadowRoot) {
    result = result.shadowRoot.activeElement;
  }
  return result;
}
function $Mj(element) {
  return $Lj() === element;
}
function $Nj(ancestor) {
  return $Dj($Lj(), ancestor);
}
function $Oj(element) {
  return element.ownerDocument === $Pj();
}
function $Pj() {
  if (getWindowsCount() <= 1) {
    return $Y.document;
  }
  const documents = Array.from(getWindows()).map(({ window: window3 }) => window3.document);
  return documents.find((doc) => doc.hasFocus()) ?? $Y.document;
}
function $Qj() {
  const document2 = $Pj();
  return document2.defaultView?.window ?? $Y;
}
var $Rj = new class {
  constructor() {
    this.mutationObservers = /* @__PURE__ */ new Map();
  }
  observe(target, disposables, options3) {
    let mutationObserversPerTarget = this.mutationObservers.get(target);
    if (!mutationObserversPerTarget) {
      mutationObserversPerTarget = /* @__PURE__ */ new Map();
      this.mutationObservers.set(target, mutationObserversPerTarget);
    }
    const optionsHash = $Xi(options3);
    let mutationObserverPerOptions = mutationObserversPerTarget.get(optionsHash);
    if (!mutationObserverPerOptions) {
      const onDidMutate = new $ze();
      const observer = new MutationObserver((mutations) => onDidMutate.fire(mutations));
      observer.observe(target, options3);
      const resolvedMutationObserverPerOptions = mutationObserverPerOptions = {
        users: 1,
        observer,
        onDidMutate: onDidMutate.event
      };
      disposables.add($1c(() => {
        resolvedMutationObserverPerOptions.users -= 1;
        if (resolvedMutationObserverPerOptions.users === 0) {
          onDidMutate.dispose();
          observer.disconnect();
          mutationObserversPerTarget?.delete(optionsHash);
          if (mutationObserversPerTarget?.size === 0) {
            this.mutationObservers.delete(target);
          }
        }
      }));
      mutationObserversPerTarget.set(optionsHash, mutationObserverPerOptions);
    } else {
      mutationObserverPerOptions.users += 1;
    }
    return mutationObserverPerOptions.onDidMutate;
  }
}();
function $Sj(container2 = $Y.document.head) {
  return createHeadElement("meta", container2);
}
function $Tj(container2 = $Y.document.head) {
  return createHeadElement("link", container2);
}
function createHeadElement(tagName, container2 = $Y.document.head) {
  const element = document.createElement(tagName);
  container2.appendChild(element);
  return element;
}
function $Uj(e) {
  return e instanceof HTMLElement || e instanceof getWindow(e).HTMLElement;
}
function $Vj(e) {
  return e instanceof HTMLAnchorElement || e instanceof getWindow(e).HTMLAnchorElement;
}
function $Xj(e) {
  return e instanceof HTMLTextAreaElement || e instanceof getWindow(e).HTMLTextAreaElement;
}
function $Yj(e) {
  return e instanceof HTMLInputElement || e instanceof getWindow(e).HTMLInputElement;
}
function $Zj(e) {
  return e instanceof HTMLButtonElement || e instanceof getWindow(e).HTMLButtonElement;
}
function $2j(e) {
  return e instanceof SVGElement || e instanceof getWindow(e).SVGElement;
}
function $3j(e) {
  return e instanceof MouseEvent || e instanceof getWindow(e).MouseEvent;
}
function $4j(e) {
  return e instanceof KeyboardEvent || e instanceof getWindow(e).KeyboardEvent;
}
function $5j(e) {
  return e instanceof PointerEvent || e instanceof getWindow(e).PointerEvent;
}
function $6j(e) {
  return e instanceof DragEvent || e instanceof getWindow(e).DragEvent;
}
var $7j = {
  // Mouse
  CLICK: "click",
  AUXCLICK: "auxclick",
  DBLCLICK: "dblclick",
  MOUSE_UP: "mouseup",
  MOUSE_DOWN: "mousedown",
  MOUSE_OVER: "mouseover",
  MOUSE_MOVE: "mousemove",
  MOUSE_OUT: "mouseout",
  MOUSE_ENTER: "mouseenter",
  MOUSE_LEAVE: "mouseleave",
  MOUSE_WHEEL: "wheel",
  POINTER_UP: "pointerup",
  POINTER_DOWN: "pointerdown",
  POINTER_MOVE: "pointermove",
  POINTER_LEAVE: "pointerleave",
  CONTEXT_MENU: "contextmenu",
  WHEEL: "wheel",
  // Keyboard
  KEY_DOWN: "keydown",
  KEY_PRESS: "keypress",
  KEY_UP: "keyup",
  // HTML Document
  LOAD: "load",
  BEFORE_UNLOAD: "beforeunload",
  UNLOAD: "unload",
  PAGE_SHOW: "pageshow",
  PAGE_HIDE: "pagehide",
  PASTE: "paste",
  ABORT: "abort",
  ERROR: "error",
  RESIZE: "resize",
  SCROLL: "scroll",
  FULLSCREEN_CHANGE: "fullscreenchange",
  WK_FULLSCREEN_CHANGE: "webkitfullscreenchange",
  // Form
  SELECT: "select",
  CHANGE: "change",
  SUBMIT: "submit",
  RESET: "reset",
  FOCUS: "focus",
  FOCUS_IN: "focusin",
  FOCUS_OUT: "focusout",
  BLUR: "blur",
  INPUT: "input",
  // Local Storage
  STORAGE: "storage",
  // Drag
  DRAG_START: "dragstart",
  DRAG: "drag",
  DRAG_ENTER: "dragenter",
  DRAG_LEAVE: "dragleave",
  DRAG_OVER: "dragover",
  DROP: "drop",
  DRAG_END: "dragend",
  // Animation
  ANIMATION_START: $Ve ? "webkitAnimationStart" : "animationstart",
  ANIMATION_END: $Ve ? "webkitAnimationEnd" : "animationend",
  ANIMATION_ITERATION: $Ve ? "webkitAnimationIteration" : "animationiteration"
};
function $8j(obj) {
  const candidate = obj;
  return !!(candidate && typeof candidate.preventDefault === "function" && typeof candidate.stopPropagation === "function");
}
var $9j = {
  stop: (e, cancelBubble) => {
    e.preventDefault();
    if (cancelBubble) {
      e.stopPropagation();
    }
    return e;
  }
};
function $0j(node) {
  const r2 = [];
  for (let i2 = 0; node && node.nodeType === node.ELEMENT_NODE; i2++) {
    r2[i2] = node.scrollTop;
    node = node.parentNode;
  }
  return r2;
}
function $$j(node, state) {
  for (let i2 = 0; node && node.nodeType === node.ELEMENT_NODE; i2++) {
    if (node.scrollTop !== state[i2]) {
      node.scrollTop = state[i2];
    }
    node = node.parentNode;
  }
}
var FocusTracker = class _FocusTracker extends $3c {
  static m(element) {
    if ($Uj(element)) {
      const shadowRoot = $Kj(element);
      const activeElement = shadowRoot ? shadowRoot.activeElement : element.ownerDocument.activeElement;
      return $Dj(activeElement, element);
    } else {
      const window3 = element;
      return $Dj(window3.document.activeElement, window3.document);
    }
  }
  constructor(element) {
    super();
    this.f = this.B(new $ze());
    this.onDidFocus = this.f.event;
    this.g = this.B(new $ze());
    this.onDidBlur = this.g.event;
    let hasFocus = _FocusTracker.m(element);
    let loosingFocus = false;
    const onFocus = () => {
      loosingFocus = false;
      if (!hasFocus) {
        hasFocus = true;
        this.f.fire();
      }
    };
    const onBlur = () => {
      if (hasFocus) {
        loosingFocus = true;
        ($Uj(element) ? getWindow(element) : element).setTimeout(() => {
          if (loosingFocus) {
            loosingFocus = false;
            hasFocus = false;
            this.g.fire();
          }
        }, 0);
      }
    };
    this.j = () => {
      const currentNodeHasFocus = _FocusTracker.m(element);
      if (currentNodeHasFocus !== hasFocus) {
        if (hasFocus) {
          onBlur();
        } else {
          onFocus();
        }
      }
    };
    this.B($_i(element, $7j.FOCUS, onFocus, true));
    this.B($_i(element, $7j.BLUR, onBlur, true));
    if ($Uj(element)) {
      this.B($_i(element, $7j.FOCUS_IN, () => this.j()));
      this.B($_i(element, $7j.FOCUS_OUT, () => this.j()));
    }
  }
  refreshState() {
    this.j();
  }
};
function $_j(element) {
  return new FocusTracker(element);
}
function $ak(sibling, child) {
  sibling.after(child);
  return child;
}
function $bk(parent, ...children) {
  parent.append(...children);
  if (children.length === 1 && typeof children[0] !== "string") {
    return children[0];
  }
}
function $ck(parent, child) {
  parent.insertBefore(child, parent.firstChild);
  return child;
}
function $dk(parent, ...children) {
  parent.innerText = "";
  $bk(parent, ...children);
}
var SELECTOR_REGEX = /([\w\-]+)?(#([\w\-]+))?((\.([\w\-]+))*)/;
var Namespace;
(function(Namespace2) {
  Namespace2["HTML"] = "http://www.w3.org/1999/xhtml";
  Namespace2["SVG"] = "http://www.w3.org/2000/svg";
})(Namespace || (Namespace = {}));
function _$(namespace, description, attrs, ...children) {
  const match = SELECTOR_REGEX.exec(description);
  if (!match) {
    throw new Error("Bad use of emmet");
  }
  const tagName = match[1] || "div";
  let result;
  if (namespace !== Namespace.HTML) {
    result = document.createElementNS(namespace, tagName);
  } else {
    result = document.createElement(tagName);
  }
  if (match[3]) {
    result.id = match[3];
  }
  if (match[4]) {
    result.className = match[4].replace(/\./g, " ").trim();
  }
  if (attrs) {
    Object.entries(attrs).forEach(([name, value]) => {
      if (typeof value === "undefined") {
        return;
      }
      if (/^on\w+$/.test(name)) {
        result[name] = value;
      } else if (name === "selected") {
        if (value) {
          result.setAttribute(name, "true");
        }
      } else {
        result.setAttribute(name, value);
      }
    });
  }
  result.append(...children);
  return result;
}
function $(description, attrs, ...children) {
  return _$(Namespace.HTML, description, attrs, ...children);
}
$.SVG = function(description, attrs, ...children) {
  return _$(Namespace.SVG, description, attrs, ...children);
};
function $gk(visible, ...elements) {
  if (visible) {
    $hk(...elements);
  } else {
    $ik(...elements);
  }
}
function $hk(...elements) {
  for (const element of elements) {
    element.style.display = "";
    element.removeAttribute("aria-hidden");
  }
}
function $ik(...elements) {
  for (const element of elements) {
    element.style.display = "none";
    element.setAttribute("aria-hidden", "true");
  }
}
function $kk(fn) {
  return (e) => {
    e.preventDefault();
    e.stopPropagation();
    fn(e);
  };
}
function $lk(targetWindow) {
  return new Promise((resolve) => {
    const readyState = targetWindow.document.readyState;
    if (readyState === "complete" || targetWindow.document && targetWindow.document.body !== null) {
      resolve(void 0);
    } else {
      const listener = () => {
        targetWindow.window.removeEventListener("DOMContentLoaded", listener, false);
        resolve();
      };
      targetWindow.window.addEventListener("DOMContentLoaded", listener, false);
    }
  });
}
function $mk(window3, cssPx) {
  const screenPx = window3.devicePixelRatio * cssPx;
  return Math.max(1, Math.floor(screenPx)) / window3.devicePixelRatio;
}
function $nk(url) {
  $Y.open(url, "_blank", "noopener");
}
var popupWidth = 780;
var popupHeight = 640;
function $ok(url) {
  const left = Math.floor($Y.screenLeft + $Y.innerWidth / 2 - popupWidth / 2);
  const top2 = Math.floor($Y.screenTop + $Y.innerHeight / 2 - popupHeight / 2);
  $Y.open(url, "_blank", `width=${popupWidth},height=${popupHeight},top=${top2},left=${left}`);
}
function $pk(url, noOpener = true) {
  const newTab = $Y.open();
  if (newTab) {
    if (noOpener) {
      newTab.opener = null;
    }
    newTab.location.href = url;
    return true;
  }
  return false;
}
function $qk(targetWindow, fn) {
  const step = () => {
    fn();
    stepDisposable = $jj(targetWindow, step);
  };
  let stepDisposable = $jj(targetWindow, step);
  return $1c(() => stepDisposable.dispose());
}
$bh.setPreferredWebSchema(/^https:/.test($Y.location.href) ? "https" : "http");
function $rk(dataOrUri, name) {
  let url;
  if (URI.isUri(dataOrUri)) {
    url = dataOrUri.toString(true);
  } else {
    const blob = new Blob([dataOrUri]);
    url = URL.createObjectURL(blob);
    setTimeout(() => URL.revokeObjectURL(url));
  }
  const activeWindow = $Qj();
  const anchor = document.createElement("a");
  activeWindow.document.body.appendChild(anchor);
  anchor.download = name;
  anchor.href = url;
  anchor.click();
  setTimeout(() => anchor.remove());
}
function $sk() {
  return new Promise((resolve) => {
    const activeWindow = $Qj();
    const input = document.createElement("input");
    activeWindow.document.body.appendChild(input);
    input.type = "file";
    input.multiple = true;
    Event2.once(Event2.fromDOMEventEmitter(input, "input"))(() => {
      resolve(input.files ?? void 0);
    });
    input.click();
    setTimeout(() => input.remove());
  });
}
var DetectedFullscreenMode;
(function(DetectedFullscreenMode2) {
  DetectedFullscreenMode2[DetectedFullscreenMode2["DOCUMENT"] = 1] = "DOCUMENT";
  DetectedFullscreenMode2[DetectedFullscreenMode2["BROWSER"] = 2] = "BROWSER";
})(DetectedFullscreenMode || (DetectedFullscreenMode = {}));
function $tk(targetWindow) {
  if (targetWindow.document.fullscreenElement || targetWindow.document.webkitFullscreenElement || targetWindow.document.webkitIsFullScreen) {
    return { mode: DetectedFullscreenMode.DOCUMENT, guess: false };
  }
  if (targetWindow.innerHeight === targetWindow.screen.height) {
    return { mode: DetectedFullscreenMode.BROWSER, guess: false };
  }
  if ($m || $n) {
    if (targetWindow.outerHeight === targetWindow.screen.height && targetWindow.outerWidth === targetWindow.screen.width) {
      return { mode: DetectedFullscreenMode.BROWSER, guess: true };
    }
  }
  return null;
}
function $uk(allowedProtocols2, allowDataImages = false) {
  const anchor = document.createElement("a");
  purify.addHook("afterSanitizeAttributes", (node) => {
    for (const attr of ["href", "src"]) {
      if (node.hasAttribute(attr)) {
        const attrValue = node.getAttribute(attr);
        if (attr === "href" && attrValue.startsWith("#")) {
          continue;
        }
        anchor.href = attrValue;
        if (!allowedProtocols2.includes(anchor.protocol.replace(/:$/, ""))) {
          if (allowDataImages && attr === "src" && anchor.href.startsWith("data:")) {
            continue;
          }
          node.removeAttribute(attr);
        }
      }
    }
  });
  return $1c(() => {
    purify.removeHook("afterSanitizeAttributes");
  });
}
var defaultSafeProtocols = [
  Schemas.http,
  Schemas.https,
  Schemas.command
];
var $vk = Object.freeze([
  "a",
  "abbr",
  "b",
  "bdo",
  "blockquote",
  "br",
  "caption",
  "cite",
  "code",
  "col",
  "colgroup",
  "dd",
  "del",
  "details",
  "dfn",
  "div",
  "dl",
  "dt",
  "em",
  "figcaption",
  "figure",
  "h1",
  "h2",
  "h3",
  "h4",
  "h5",
  "h6",
  "hr",
  "i",
  "img",
  "input",
  "ins",
  "kbd",
  "label",
  "li",
  "mark",
  "ol",
  "p",
  "pre",
  "q",
  "rp",
  "rt",
  "ruby",
  "samp",
  "small",
  "small",
  "source",
  "span",
  "strike",
  "strong",
  "sub",
  "summary",
  "sup",
  "table",
  "tbody",
  "td",
  "tfoot",
  "th",
  "thead",
  "time",
  "tr",
  "tt",
  "u",
  "ul",
  "var",
  "video",
  "wbr"
]);
var defaultDomPurifyConfig = Object.freeze({
  ALLOWED_TAGS: ["a", "button", "blockquote", "code", "div", "h1", "h2", "h3", "h4", "h5", "h6", "hr", "input", "label", "li", "p", "pre", "select", "small", "span", "strong", "textarea", "ul", "ol"],
  ALLOWED_ATTR: ["href", "data-href", "data-command", "target", "title", "name", "src", "alt", "class", "id", "role", "tabindex", "style", "data-code", "width", "height", "align", "x-dispatch", "required", "checked", "placeholder", "type", "start"],
  RETURN_DOM: false,
  RETURN_DOM_FRAGMENT: false,
  RETURN_TRUSTED_TYPE: true
});
function $wk(node, value, extraDomPurifyConfig) {
  const hook = $uk(defaultSafeProtocols);
  try {
    const html3 = purify.sanitize(value, { ...defaultDomPurifyConfig, ...extraDomPurifyConfig });
    node.innerHTML = html3;
  } finally {
    hook.dispose();
  }
}
function toBinary(str) {
  const codeUnits = new Uint16Array(str.length);
  for (let i2 = 0; i2 < codeUnits.length; i2++) {
    codeUnits[i2] = str.charCodeAt(i2);
  }
  let binary = "";
  const uint8array = new Uint8Array(codeUnits.buffer);
  for (let i2 = 0; i2 < uint8array.length; i2++) {
    binary += String.fromCharCode(uint8array[i2]);
  }
  return binary;
}
function $xk(str) {
  return btoa(toBinary(str));
}
var $yk = class _$yk extends $ze {
  constructor() {
    super();
    this.o = new $2c();
    this.s = {
      altKey: false,
      shiftKey: false,
      ctrlKey: false,
      metaKey: false
    };
    this.o.add(Event2.runAndSubscribe(onDidRegisterWindow, ({ window: window3, disposables }) => this.F(window3, disposables), { window: $Y, disposables: this.o }));
  }
  F(window3, disposables) {
    disposables.add($_i(window3, "keydown", (e) => {
      if (e.defaultPrevented) {
        return;
      }
      const event = new $if(e);
      if (event.keyCode === 6 && e.repeat) {
        return;
      }
      if (e.altKey && !this.s.altKey) {
        this.s.lastKeyPressed = "alt";
      } else if (e.ctrlKey && !this.s.ctrlKey) {
        this.s.lastKeyPressed = "ctrl";
      } else if (e.metaKey && !this.s.metaKey) {
        this.s.lastKeyPressed = "meta";
      } else if (e.shiftKey && !this.s.shiftKey) {
        this.s.lastKeyPressed = "shift";
      } else if (event.keyCode !== 6) {
        this.s.lastKeyPressed = void 0;
      } else {
        return;
      }
      this.s.altKey = e.altKey;
      this.s.ctrlKey = e.ctrlKey;
      this.s.metaKey = e.metaKey;
      this.s.shiftKey = e.shiftKey;
      if (this.s.lastKeyPressed) {
        this.s.event = e;
        this.fire(this.s);
      }
    }, true));
    disposables.add($_i(window3, "keyup", (e) => {
      if (e.defaultPrevented) {
        return;
      }
      if (!e.altKey && this.s.altKey) {
        this.s.lastKeyReleased = "alt";
      } else if (!e.ctrlKey && this.s.ctrlKey) {
        this.s.lastKeyReleased = "ctrl";
      } else if (!e.metaKey && this.s.metaKey) {
        this.s.lastKeyReleased = "meta";
      } else if (!e.shiftKey && this.s.shiftKey) {
        this.s.lastKeyReleased = "shift";
      } else {
        this.s.lastKeyReleased = void 0;
      }
      if (this.s.lastKeyPressed !== this.s.lastKeyReleased) {
        this.s.lastKeyPressed = void 0;
      }
      this.s.altKey = e.altKey;
      this.s.ctrlKey = e.ctrlKey;
      this.s.metaKey = e.metaKey;
      this.s.shiftKey = e.shiftKey;
      if (this.s.lastKeyReleased) {
        this.s.event = e;
        this.fire(this.s);
      }
    }, true));
    disposables.add($_i(window3.document.body, "mousedown", () => {
      this.s.lastKeyPressed = void 0;
    }, true));
    disposables.add($_i(window3.document.body, "mouseup", () => {
      this.s.lastKeyPressed = void 0;
    }, true));
    disposables.add($_i(window3.document.body, "mousemove", (e) => {
      if (e.buttons) {
        this.s.lastKeyPressed = void 0;
      }
    }, true));
    disposables.add($_i(window3, "blur", () => {
      this.resetKeyStatus();
    }));
  }
  get keyStatus() {
    return this.s;
  }
  get isModifierPressed() {
    return this.s.altKey || this.s.ctrlKey || this.s.metaKey || this.s.shiftKey;
  }
  /**
   * Allows to explicitly reset the key status based on more knowledge (#109062)
   */
  resetKeyStatus() {
    this.G();
    this.fire(this.s);
  }
  G() {
    this.s = {
      altKey: false,
      shiftKey: false,
      ctrlKey: false,
      metaKey: false
    };
  }
  static getInstance() {
    if (!_$yk.D) {
      _$yk.D = new _$yk();
    }
    return _$yk.D;
  }
  dispose() {
    super.dispose();
    this.o.dispose();
  }
};
function $zk(name) {
  const match = document.cookie.match("(^|[^;]+)\\s*" + name + "\\s*=\\s*([^;]+)");
  return match ? match.pop() : void 0;
}
var $Ak = class extends $3c {
  constructor(j, m) {
    super();
    this.j = j;
    this.m = m;
    this.f = 0;
    this.g = 0;
    this.n();
  }
  n() {
    if (this.m.onDragStart) {
      this.B($_i(this.j, $7j.DRAG_START, (e) => {
        this.m.onDragStart?.(e);
      }));
    }
    if (this.m.onDrag) {
      this.B($_i(this.j, $7j.DRAG, (e) => {
        this.m.onDrag?.(e);
      }));
    }
    this.B($_i(this.j, $7j.DRAG_ENTER, (e) => {
      this.f++;
      this.g = e.timeStamp;
      this.m.onDragEnter?.(e);
    }));
    this.B($_i(this.j, $7j.DRAG_OVER, (e) => {
      e.preventDefault();
      this.m.onDragOver?.(e, e.timeStamp - this.g);
    }));
    this.B($_i(this.j, $7j.DRAG_LEAVE, (e) => {
      this.f--;
      if (this.f === 0) {
        this.g = 0;
        this.m.onDragLeave?.(e);
      }
    }));
    this.B($_i(this.j, $7j.DRAG_END, (e) => {
      this.f = 0;
      this.g = 0;
      this.m.onDragEnd?.(e);
    }));
    this.B($_i(this.j, $7j.DROP, (e) => {
      this.f = 0;
      this.g = 0;
      this.m.onDrop?.(e);
    }));
  }
};
var H_REGEX = /(?<tag>[\w\-]+)?(?:#(?<id>[\w\-]+))?(?<class>(?:\.(?:[\w\-]+))*)(?:@(?<name>(?:[\w\_])+))?/;
function h(tag2, ...args2) {
  let attributes;
  let children;
  if (Array.isArray(args2[0])) {
    attributes = {};
    children = args2[0];
  } else {
    attributes = args2[0] || {};
    children = args2[1];
  }
  const match = H_REGEX.exec(tag2);
  if (!match || !match.groups) {
    throw new Error("Bad use of h");
  }
  const tagName = match.groups["tag"] || "div";
  const el = document.createElement(tagName);
  if (match.groups["id"]) {
    el.id = match.groups["id"];
  }
  const classNames = [];
  if (match.groups["class"]) {
    for (const className of match.groups["class"].split(".")) {
      if (className !== "") {
        classNames.push(className);
      }
    }
  }
  if (attributes.className !== void 0) {
    for (const className of attributes.className.split(".")) {
      if (className !== "") {
        classNames.push(className);
      }
    }
  }
  if (classNames.length > 0) {
    el.className = classNames.join(" ");
  }
  const result = {};
  if (match.groups["name"]) {
    result[match.groups["name"]] = el;
  }
  if (children) {
    for (const c of children) {
      if ($Uj(c)) {
        el.appendChild(c);
      } else if (typeof c === "string") {
        el.append(c);
      } else if ("root" in c) {
        Object.assign(result, c);
        el.appendChild(c.root);
      }
    }
  }
  for (const [key2, value] of Object.entries(attributes)) {
    if (key2 === "className") {
      continue;
    } else if (key2 === "style") {
      for (const [cssKey, cssValue] of Object.entries(value)) {
        el.style.setProperty(camelCaseToHyphenCase(cssKey), typeof cssValue === "number" ? cssValue + "px" : "" + cssValue);
      }
    } else if (key2 === "tabIndex") {
      el.tabIndex = value;
    } else {
      el.setAttribute(camelCaseToHyphenCase(key2), value.toString());
    }
  }
  result["root"] = el;
  return result;
}
function $Ck(tag2, ...args2) {
  let attributes;
  let children;
  if (Array.isArray(args2[0])) {
    attributes = {};
    children = args2[0];
  } else {
    attributes = args2[0] || {};
    children = args2[1];
  }
  const match = H_REGEX.exec(tag2);
  if (!match || !match.groups) {
    throw new Error("Bad use of h");
  }
  const tagName = match.groups["tag"] || "div";
  const el = document.createElementNS("http://www.w3.org/2000/svg", tagName);
  if (match.groups["id"]) {
    el.id = match.groups["id"];
  }
  const classNames = [];
  if (match.groups["class"]) {
    for (const className of match.groups["class"].split(".")) {
      if (className !== "") {
        classNames.push(className);
      }
    }
  }
  if (attributes.className !== void 0) {
    for (const className of attributes.className.split(".")) {
      if (className !== "") {
        classNames.push(className);
      }
    }
  }
  if (classNames.length > 0) {
    el.className = classNames.join(" ");
  }
  const result = {};
  if (match.groups["name"]) {
    result[match.groups["name"]] = el;
  }
  if (children) {
    for (const c of children) {
      if ($Uj(c)) {
        el.appendChild(c);
      } else if (typeof c === "string") {
        el.append(c);
      } else if ("root" in c) {
        Object.assign(result, c);
        el.appendChild(c.root);
      }
    }
  }
  for (const [key2, value] of Object.entries(attributes)) {
    if (key2 === "className") {
      continue;
    } else if (key2 === "style") {
      for (const [cssKey, cssValue] of Object.entries(value)) {
        el.style.setProperty(camelCaseToHyphenCase(cssKey), typeof cssValue === "number" ? cssValue + "px" : "" + cssValue);
      }
    } else if (key2 === "tabIndex") {
      el.tabIndex = value;
    } else {
      el.setAttribute(camelCaseToHyphenCase(key2), value.toString());
    }
  }
  result["root"] = el;
  return result;
}
function camelCaseToHyphenCase(str) {
  return str.replace(/([a-z])([A-Z])/g, "$1-$2").toLowerCase();
}
function $Dk(from, to, filter) {
  for (const { name, value } of from.attributes) {
    if (!filter || filter.includes(name)) {
      to.setAttribute(name, value);
    }
  }
}
function copyAttribute(from, to, name) {
  const value = from.getAttribute(name);
  if (value) {
    to.setAttribute(name, value);
  } else {
    to.removeAttribute(name);
  }
}
function $Ek(from, to, filter) {
  $Dk(from, to, filter);
  const disposables = new $2c();
  disposables.add($Rj.observe(from, disposables, { attributes: true, attributeFilter: filter })((mutations) => {
    for (const mutation of mutations) {
      if (mutation.type === "attributes" && mutation.attributeName) {
        copyAttribute(from, to, mutation.attributeName);
      }
    }
  }));
  return disposables;
}
function $Fk(element) {
  return element.tagName.toLowerCase() === "input" || element.tagName.toLowerCase() === "textarea" || $Uj(element) && !!element.editContext;
}
var $Gk = class {
  constructor(f, g, target) {
    this.f = f;
    this.g = g;
    this.d = new Int16Array(8);
    const { top: top2, left, right, bottom } = target.getBoundingClientRect();
    const t = this.d;
    let i2 = 0;
    t[i2++] = left;
    t[i2++] = top2;
    t[i2++] = right;
    t[i2++] = top2;
    t[i2++] = left;
    t[i2++] = bottom;
    t[i2++] = right;
    t[i2++] = bottom;
  }
  contains(x, y) {
    const { d: points, f: originX, g: originY } = this;
    for (let i2 = 0; i2 < 4; i2++) {
      const p1 = 2 * i2;
      const p2 = 2 * ((i2 + 1) % 4);
      if ($9i(x, y, originX, originY, points[p1], points[p1 + 1], points[p2], points[p2 + 1])) {
        return true;
      }
    }
    return false;
  }
};

// out-build/vs/base/browser/ui/aria/aria.js
var MAX_MESSAGE_LENGTH = 2e4;
var ariaContainer;
var alertContainer;
var alertContainer2;
var statusContainer;
var statusContainer2;
function $0Z(parent) {
  ariaContainer = document.createElement("div");
  ariaContainer.className = "monaco-aria-container";
  const createAlertContainer = () => {
    const element = document.createElement("div");
    element.className = "monaco-alert";
    element.setAttribute("role", "alert");
    element.setAttribute("aria-atomic", "true");
    ariaContainer.appendChild(element);
    return element;
  };
  alertContainer = createAlertContainer();
  alertContainer2 = createAlertContainer();
  const createStatusContainer = () => {
    const element = document.createElement("div");
    element.className = "monaco-status";
    element.setAttribute("aria-live", "polite");
    element.setAttribute("aria-atomic", "true");
    ariaContainer.appendChild(element);
    return element;
  };
  statusContainer = createStatusContainer();
  statusContainer2 = createStatusContainer();
  parent.appendChild(ariaContainer);
}
function $$Z(msg) {
  if (!ariaContainer) {
    return;
  }
  if (alertContainer.textContent !== msg) {
    $$i(alertContainer2);
    insertMessage(alertContainer, msg);
  } else {
    $$i(alertContainer);
    insertMessage(alertContainer2, msg);
  }
}
function $_Z(msg) {
  if (!ariaContainer) {
    return;
  }
  if (statusContainer.textContent !== msg) {
    $$i(statusContainer2);
    insertMessage(statusContainer, msg);
  } else {
    $$i(statusContainer);
    insertMessage(statusContainer2, msg);
  }
}
function insertMessage(target, msg) {
  $$i(target);
  if (msg.length > MAX_MESSAGE_LENGTH) {
    msg = msg.substr(0, MAX_MESSAGE_LENGTH);
  }
  target.textContent = msg;
  target.style.visibility = "hidden";
  target.style.visibility = "visible";
}

// 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 $Pk = $Qk("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 $Qk(serviceId) {
  if (_util.serviceIds.has(serviceId)) {
    return _util.serviceIds.get(serviceId);
  }
  const id2 = function(target, key2, 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 $Rk(serviceIdentifier) {
  return serviceIdentifier;
}

// out-build/vs/editor/browser/services/codeEditorService.js
var $U5 = $Qk("codeEditorService");

// out-build/vs/editor/common/core/position.js
var $8C = class _$8C {
  constructor(lineNumber, column) {
    this.lineNumber = lineNumber;
    this.column = column;
  }
  /**
   * Create a new position from this position.
   *
   * @param newLineNumber new line number
   * @param newColumn new column
   */
  with(newLineNumber = this.lineNumber, newColumn = this.column) {
    if (newLineNumber === this.lineNumber && newColumn === this.column) {
      return this;
    } else {
      return new _$8C(newLineNumber, newColumn);
    }
  }
  /**
   * Derive a new position from this position.
   *
   * @param deltaLineNumber line number delta
   * @param deltaColumn column delta
   */
  delta(deltaLineNumber = 0, deltaColumn = 0) {
    return this.with(this.lineNumber + deltaLineNumber, this.column + deltaColumn);
  }
  /**
   * Test if this position equals other position
   */
  equals(other) {
    return _$8C.equals(this, other);
  }
  /**
   * Test if position `a` equals position `b`
   */
  static equals(a, b) {
    if (!a && !b) {
      return true;
    }
    return !!a && !!b && a.lineNumber === b.lineNumber && a.column === b.column;
  }
  /**
   * Test if this position is before other position.
   * If the two positions are equal, the result will be false.
   */
  isBefore(other) {
    return _$8C.isBefore(this, other);
  }
  /**
   * Test if position `a` is before position `b`.
   * If the two positions are equal, the result will be false.
   */
  static isBefore(a, b) {
    if (a.lineNumber < b.lineNumber) {
      return true;
    }
    if (b.lineNumber < a.lineNumber) {
      return false;
    }
    return a.column < b.column;
  }
  /**
   * Test if this position is before other position.
   * If the two positions are equal, the result will be true.
   */
  isBeforeOrEqual(other) {
    return _$8C.isBeforeOrEqual(this, other);
  }
  /**
   * Test if position `a` is before position `b`.
   * If the two positions are equal, the result will be true.
   */
  static isBeforeOrEqual(a, b) {
    if (a.lineNumber < b.lineNumber) {
      return true;
    }
    if (b.lineNumber < a.lineNumber) {
      return false;
    }
    return a.column <= b.column;
  }
  /**
   * A function that compares positions, useful for sorting
   */
  static compare(a, b) {
    const aLineNumber = a.lineNumber | 0;
    const bLineNumber = b.lineNumber | 0;
    if (aLineNumber === bLineNumber) {
      const aColumn = a.column | 0;
      const bColumn = b.column | 0;
      return aColumn - bColumn;
    }
    return aLineNumber - bLineNumber;
  }
  /**
   * Clone this position.
   */
  clone() {
    return new _$8C(this.lineNumber, this.column);
  }
  /**
   * Convert to a human-readable representation.
   */
  toString() {
    return "(" + this.lineNumber + "," + this.column + ")";
  }
  // ---
  /**
   * Create a `Position` from an `IPosition`.
   */
  static lift(pos) {
    return new _$8C(pos.lineNumber, pos.column);
  }
  /**
   * Test if `obj` is an `IPosition`.
   */
  static isIPosition(obj) {
    return obj && typeof obj.lineNumber === "number" && typeof obj.column === "number";
  }
  toJSON() {
    return {
      lineNumber: this.lineNumber,
      column: this.column
    };
  }
};

// out-build/vs/editor/common/services/model.js
var $sG = $Qk("modelService");

// out-build/vs/editor/common/services/resolverService.js
var $oG = $Qk("textModelService");
function $pG(model) {
  const candidate = model;
  return !!candidate.textEditorModel;
}

// out-build/vs/base/common/actions.js
var $Um = class extends $3c {
  constructor(id2, label3 = "", cssClass = "", enabled = true, actionCallback) {
    super();
    this.j = this.B(new $ze());
    this.onDidChange = this.j.event;
    this.z = true;
    this.m = id2;
    this.n = label3;
    this.w = cssClass;
    this.z = enabled;
    this.D = actionCallback;
  }
  get id() {
    return this.m;
  }
  get label() {
    return this.n;
  }
  set label(value) {
    this.F(value);
  }
  F(value) {
    if (this.n !== value) {
      this.n = value;
      this.j.fire({ label: value });
    }
  }
  get tooltip() {
    return this.u || "";
  }
  set tooltip(value) {
    this.G(value);
  }
  G(value) {
    if (this.u !== value) {
      this.u = value;
      this.j.fire({ tooltip: value });
    }
  }
  get class() {
    return this.w;
  }
  set class(value) {
    this.H(value);
  }
  H(value) {
    if (this.w !== value) {
      this.w = value;
      this.j.fire({ class: value });
    }
  }
  get enabled() {
    return this.z;
  }
  set enabled(value) {
    this.I(value);
  }
  I(value) {
    if (this.z !== value) {
      this.z = value;
      this.j.fire({ enabled: value });
    }
  }
  get checked() {
    return this.C;
  }
  set checked(value) {
    this.J(value);
  }
  J(value) {
    if (this.C !== value) {
      this.C = value;
      this.j.fire({ checked: value });
    }
  }
  async run(event, data) {
    if (this.D) {
      await this.D(event);
    }
  }
};
var $Vm = class extends $3c {
  constructor() {
    super(...arguments);
    this.f = this.B(new $ze());
    this.onWillRun = this.f.event;
    this.m = this.B(new $ze());
    this.onDidRun = this.m.event;
  }
  async run(action, context) {
    if (!action.enabled) {
      return;
    }
    this.f.fire({ action });
    let error = void 0;
    try {
      await this.u(action, context);
    } catch (e) {
      error = e;
    }
    this.m.fire({ action, error });
  }
  async u(action, context) {
    await action.run(context);
  }
};
var $Wm = class _$Wm {
  constructor() {
    this.id = _$Wm.ID;
    this.label = "";
    this.tooltip = "";
    this.class = "separator";
    this.enabled = false;
    this.checked = false;
  }
  /**
   * Joins all non-empty lists of actions with separators.
   */
  static join(...actionLists) {
    let out = [];
    for (const list2 of actionLists) {
      if (!list2.length) {
      } else if (out.length) {
        out = [...out, new _$Wm(), ...list2];
      } else {
        out = list2;
      }
    }
    return out;
  }
  static {
    this.ID = "vs.actions.separator";
  }
  async run() {
  }
};
var $Xm = class {
  get actions() {
    return this.a;
  }
  constructor(id2, label3, actions, cssClass) {
    this.tooltip = "";
    this.enabled = true;
    this.checked = void 0;
    this.id = id2;
    this.label = label3;
    this.class = cssClass;
    this.a = actions;
  }
  async run() {
  }
};
var $Ym = class _$Ym extends $Um {
  static {
    this.ID = "vs.actions.empty";
  }
  constructor() {
    super(_$Ym.ID, localize(44, null), void 0, false);
  }
};
function $Zm(props) {
  return {
    id: props.id,
    label: props.label,
    tooltip: props.tooltip ?? props.label,
    class: props.class,
    enabled: props.enabled ?? true,
    checked: props.checked,
    run: async (...args2) => props.run(...args2)
  };
}

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

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

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

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

// out-build/vs/platform/commands/common/commands.js
var $sn = $Qk("commandService");
var $tn = new class {
  constructor() {
    this.a = /* @__PURE__ */ new Map();
    this.b = new $ze();
    this.onDidRegisterCommand = this.b.event;
  }
  registerCommand(idOrCommand, handler) {
    if (!idOrCommand) {
      throw new Error(`invalid command`);
    }
    if (typeof idOrCommand === "string") {
      if (!handler) {
        throw new Error(`invalid command`);
      }
      return this.registerCommand({ id: idOrCommand, handler });
    }
    if (idOrCommand.metadata && Array.isArray(idOrCommand.metadata.args)) {
      const constraints = [];
      for (const arg of idOrCommand.metadata.args) {
        constraints.push(arg.constraint);
      }
      const actualHandler = idOrCommand.handler;
      idOrCommand.handler = function(accessor, ...args2) {
        $Pg(args2, constraints);
        return actualHandler(accessor, ...args2);
      };
    }
    const { id: id2 } = idOrCommand;
    let commands2 = this.a.get(id2);
    if (!commands2) {
      commands2 = new $cd();
      this.a.set(id2, commands2);
    }
    const removeFn = commands2.unshift(idOrCommand);
    const ret = $1c(() => {
      removeFn();
      const command4 = this.a.get(id2);
      if (command4?.isEmpty()) {
        this.a.delete(id2);
      }
    });
    this.b.fire(id2);
    return ret;
  }
  registerCommandAlias(oldId, newId) {
    return $tn.registerCommand(oldId, (accessor, ...args2) => accessor.get($sn).executeCommand(newId, ...args2));
  }
  getCommand(id2) {
    const list2 = this.a.get(id2);
    if (!list2 || list2.isEmpty()) {
      return void 0;
    }
    return Iterable.first(list2);
  }
  getCommands() {
    const result = /* @__PURE__ */ new Map();
    for (const key2 of this.a.keys()) {
      const command4 = this.getCommand(key2);
      if (command4) {
        result.set(key2, command4);
      }
    }
    return result;
  }
}();
$tn.registerCommand("noop", () => {
});

// out-build/vs/platform/contextkey/common/scanner.js
var TokenType;
(function(TokenType4) {
  TokenType4[TokenType4["LParen"] = 0] = "LParen";
  TokenType4[TokenType4["RParen"] = 1] = "RParen";
  TokenType4[TokenType4["Neg"] = 2] = "Neg";
  TokenType4[TokenType4["Eq"] = 3] = "Eq";
  TokenType4[TokenType4["NotEq"] = 4] = "NotEq";
  TokenType4[TokenType4["Lt"] = 5] = "Lt";
  TokenType4[TokenType4["LtEq"] = 6] = "LtEq";
  TokenType4[TokenType4["Gt"] = 7] = "Gt";
  TokenType4[TokenType4["GtEq"] = 8] = "GtEq";
  TokenType4[TokenType4["RegexOp"] = 9] = "RegexOp";
  TokenType4[TokenType4["RegexStr"] = 10] = "RegexStr";
  TokenType4[TokenType4["True"] = 11] = "True";
  TokenType4[TokenType4["False"] = 12] = "False";
  TokenType4[TokenType4["In"] = 13] = "In";
  TokenType4[TokenType4["Not"] = 14] = "Not";
  TokenType4[TokenType4["And"] = 15] = "And";
  TokenType4[TokenType4["Or"] = 16] = "Or";
  TokenType4[TokenType4["Str"] = 17] = "Str";
  TokenType4[TokenType4["QuotedStr"] = 18] = "QuotedStr";
  TokenType4[TokenType4["Error"] = 19] = "Error";
  TokenType4[TokenType4["EOF"] = 20] = "EOF";
})(TokenType || (TokenType = {}));
function hintDidYouMean(...meant) {
  switch (meant.length) {
    case 1:
      return localize(1724, null, meant[0]);
    case 2:
      return localize(1725, null, meant[0], meant[1]);
    case 3:
      return localize(1726, null, meant[0], meant[1], meant[2]);
    default:
      return void 0;
  }
}
var hintDidYouForgetToOpenOrCloseQuote = localize(1727, null);
var hintDidYouForgetToEscapeSlash = localize(1728, null);
var $4m = class _$4m {
  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 $ob(`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(type) {
    this.f.push({ type, 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 = _$4m.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 && _$4m.a.has(this.c.charCodeAt(p))) {
      p++;
    }
    this.e = p;
    const lexeme = this.c.substring(this.d, this.e);
    this.f.push({ type: 10, lexeme, offset: this.d });
  }
  r() {
    return this.e >= this.c.length;
  }
};

// out-build/vs/platform/contextkey/common/contextkey.js
var CONSTANT_VALUES = /* @__PURE__ */ new Map();
CONSTANT_VALUES.set("false", false);
CONSTANT_VALUES.set("true", true);
CONSTANT_VALUES.set("isMac", $m);
CONSTANT_VALUES.set("isLinux", $n);
CONSTANT_VALUES.set("isWindows", $l);
CONSTANT_VALUES.set("isWeb", $r);
CONSTANT_VALUES.set("isMacNative", $m && !$r);
CONSTANT_VALUES.set("isEdge", $K);
CONSTANT_VALUES.set("isFirefox", $I);
CONSTANT_VALUES.set("isChrome", $H);
CONSTANT_VALUES.set("isSafari", $J);
function $5m(key2, value) {
  if (CONSTANT_VALUES.get(key2) !== void 0) {
    throw $nb("contextkey.setConstant(k, v) invoked with already set constant `k`");
  }
  CONSTANT_VALUES.set(key2, value);
}
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(1704, null);
var hintEmptyString = localize(1705, null);
var errorNoInAfterNot = localize(1706, null);
var errorClosingParenthesis = localize(1707, null);
var errorUnexpectedToken = localize(1708, null);
var hintUnexpectedToken = localize(1709, null);
var errorUnexpectedEOF = localize(1710, null);
var hintUnexpectedEOF = localize(1711, null);
var $6m = class _$6m {
  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 $4m();
    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: $4m.getLexeme(peek), additionalInfo });
        throw _$6m.c;
      }
      return expr;
    } catch (e) {
      if (!(e === _$6m.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] : $7m.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] : $7m.and(...expr);
  }
  s() {
    if (this.y(
      2
      /* TokenType.Neg */
    )) {
      const peek = this.D();
      switch (peek.type) {
        case 11:
          this.z();
          return $0m.INSTANCE;
        case 12:
          this.z();
          return $$m.INSTANCE;
        case 0: {
          this.z();
          const expr = this.l();
          this.A(1, errorClosingParenthesis);
          return expr?.negate();
        }
        case 17:
          this.z();
          return $en.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 $7m.true();
      case 12:
        this.z();
        return $7m.false();
      case 0: {
        this.z();
        const expr = this.l();
        this.A(1, errorClosingParenthesis);
        return expr;
      }
      case 17: {
        const key2 = 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 $jn.create(key2, regexp);
          }
          switch (expr.type) {
            case 10:
            case 19: {
              const lexemeReconstruction = [expr.lexeme];
              this.z();
              let followingToken = this.D();
              let parenBalance = 0;
              for (let i2 = 0; i2 < expr.lexeme.length; i2++) {
                if (expr.lexeme.charCodeAt(i2) === 40) {
                  parenBalance++;
                } else if (expr.lexeme.charCodeAt(i2) === 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 i2 = 0; i2 < followingToken.lexeme.length; i2++) {
                      if (followingToken.lexeme.charCodeAt(i2) === 40) {
                        parenBalance++;
                      } else if (expr.lexeme.charCodeAt(i2) === 41) {
                        parenBalance--;
                      }
                    }
                }
                if (parenBalance < 0) {
                  break;
                }
                lexemeReconstruction.push($4m.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 $7m.regex(key2, 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 $jn.create(key2, regex);
            }
            default:
              throw this.B("REGEX", this.D());
          }
        }
        if (this.y(
          14
          /* TokenType.Not */
        )) {
          this.A(13, errorNoInAfterNot);
          const right = this.u();
          return $7m.notIn(key2, right);
        }
        const maybeOp = this.D().type;
        switch (maybeOp) {
          case 3: {
            this.z();
            const right = this.u();
            if (this.x().type === 18) {
              return $7m.equals(key2, right);
            }
            switch (right) {
              case "true":
                return $7m.has(key2);
              case "false":
                return $7m.not(key2);
              default:
                return $7m.equals(key2, right);
            }
          }
          case 4: {
            this.z();
            const right = this.u();
            if (this.x().type === 18) {
              return $7m.notEquals(key2, right);
            }
            switch (right) {
              case "true":
                return $7m.not(key2);
              case "false":
                return $7m.has(key2);
              default:
                return $7m.notEquals(key2, right);
            }
          }
          case 5:
            this.z();
            return $hn.create(key2, this.u());
          case 6:
            this.z();
            return $in.create(key2, this.u());
          case 7:
            this.z();
            return $fn.create(key2, this.u());
          case 8:
            this.z();
            return $gn.create(key2, this.u());
          case 13:
            this.z();
            return $7m.in(key2, this.u());
          default:
            return $7m.has(key2);
        }
      }
      case 20:
        this.h.push({ message: errorUnexpectedEOF, offset: peek.offset, lexeme: "", additionalInfo: hintUnexpectedEOF });
        throw _$6m.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(type, message) {
    if (this.C(type)) {
      return this.z();
    }
    throw this.B(message, this.D());
  }
  B(expected, got, additionalInfo) {
    const message = localize(1712, null, expected, $4m.getLexeme(got));
    const offset = got.offset;
    const lexeme = $4m.getLexeme(got);
    this.h.push({ message, offset, lexeme, additionalInfo });
    return _$6m.c;
  }
  C(type) {
    return this.D().type === type;
  }
  D() {
    return this.f[this.g];
  }
  E() {
    return this.D().type === 20;
  }
};
var $7m = class {
  static false() {
    return $0m.INSTANCE;
  }
  static true() {
    return $$m.INSTANCE;
  }
  static has(key2) {
    return $_m.create(key2);
  }
  static equals(key2, value) {
    return $an.create(key2, value);
  }
  static notEquals(key2, value) {
    return $dn.create(key2, value);
  }
  static regex(key2, value) {
    return $jn.create(key2, value);
  }
  static in(key2, value) {
    return $bn.create(key2, value);
  }
  static notIn(key2, value) {
    return $cn.create(key2, value);
  }
  static not(key2) {
    return $en.create(key2);
  }
  static and(...expr) {
    return $ln.create(expr, null, true);
  }
  static or(...expr) {
    return $mn.create(expr, null, true);
  }
  static greater(key2, value) {
    return $fn.create(key2, value);
  }
  static greaterEquals(key2, value) {
    return $gn.create(key2, value);
  }
  static smaller(key2, value) {
    return $hn.create(key2, value);
  }
  static smallerEquals(key2, value) {
    return $in.create(key2, value);
  }
  static {
    this.c = new $6m({ regexParsingWithErrorRecovery: false });
  }
  static deserialize(serialized) {
    if (serialized === void 0 || serialized === null) {
      return void 0;
    }
    const expr = this.c.parse(serialized);
    return expr;
  }
};
function $9m(a, b) {
  const aExpr = a ? a.substituteConstants() : void 0;
  const bExpr = b ? b.substituteConstants() : void 0;
  if (!aExpr && !bExpr) {
    return true;
  }
  if (!aExpr || !bExpr) {
    return false;
  }
  return aExpr.equals(bExpr);
}
function cmp(a, b) {
  return a.cmp(b);
}
var $0m = class _$0m {
  static {
    this.INSTANCE = new _$0m();
  }
  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 $$m.INSTANCE;
  }
};
var $$m = class _$$m {
  static {
    this.INSTANCE = new _$$m();
  }
  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 $0m.INSTANCE;
  }
};
var $_m = class _$_m {
  static create(key2, negated = null) {
    const constantValue = CONSTANT_VALUES.get(key2);
    if (typeof constantValue === "boolean") {
      return constantValue ? $$m.INSTANCE : $0m.INSTANCE;
    }
    return new _$_m(key2, negated);
  }
  constructor(key2, c) {
    this.key = key2;
    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 ? $$m.INSTANCE : $0m.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 = $en.create(this.key, this);
    }
    return this.c;
  }
};
var $an = class _$an {
  static create(key2, value, negated = null) {
    if (typeof value === "boolean") {
      return value ? $_m.create(key2, negated) : $en.create(key2, negated);
    }
    const constantValue = CONSTANT_VALUES.get(key2);
    if (typeof constantValue === "boolean") {
      const trueValue = constantValue ? "true" : "false";
      return value === trueValue ? $$m.INSTANCE : $0m.INSTANCE;
    }
    return new _$an(key2, 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 ? $$m.INSTANCE : $0m.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 = $dn.create(this.c, this.d, this);
    }
    return this.f;
  }
};
var $bn = class _$bn {
  static create(key2, valueKey) {
    return new _$bn(key2, 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 = $cn.create(this.d, this.f);
    }
    return this.c;
  }
};
var $cn = class _$cn {
  static create(key2, valueKey) {
    return new _$cn(key2, valueKey);
  }
  constructor(d, f) {
    this.d = d;
    this.f = f;
    this.type = 11;
    this.c = $bn.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 $dn = class _$dn {
  static create(key2, value, negated = null) {
    if (typeof value === "boolean") {
      if (value) {
        return $en.create(key2, negated);
      }
      return $_m.create(key2, negated);
    }
    const constantValue = CONSTANT_VALUES.get(key2);
    if (typeof constantValue === "boolean") {
      const falseValue = constantValue ? "true" : "false";
      return value === falseValue ? $0m.INSTANCE : $$m.INSTANCE;
    }
    return new _$dn(key2, 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 ? $0m.INSTANCE : $$m.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 = $an.create(this.c, this.d, this);
    }
    return this.f;
  }
};
var $en = class _$en {
  static create(key2, negated = null) {
    const constantValue = CONSTANT_VALUES.get(key2);
    if (typeof constantValue === "boolean") {
      return constantValue ? $0m.INSTANCE : $$m.INSTANCE;
    }
    return new _$en(key2, 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 ? $0m.INSTANCE : $$m.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 = $_m.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 $0m.INSTANCE;
}
var $fn = class _$fn {
  static create(key2, _value, negated = null) {
    return withFloatOrStr(_value, (value) => new _$fn(key2, 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 = $in.create(this.c, this.d, this);
    }
    return this.f;
  }
};
var $gn = class _$gn {
  static create(key2, _value, negated = null) {
    return withFloatOrStr(_value, (value) => new _$gn(key2, 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 = $hn.create(this.c, this.d, this);
    }
    return this.f;
  }
};
var $hn = class _$hn {
  static create(key2, _value, negated = null) {
    return withFloatOrStr(_value, (value) => new _$hn(key2, 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 = $gn.create(this.c, this.d, this);
    }
    return this.f;
  }
};
var $in = class _$in {
  static create(key2, _value, negated = null) {
    return withFloatOrStr(_value, (value) => new _$in(key2, 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 = $fn.create(this.c, this.d, this);
    }
    return this.f;
  }
};
var $jn = class _$jn {
  static create(key2, regexp) {
    return new _$jn(key2, 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 = $kn.create(this);
    }
    return this.c;
  }
};
var $kn = class _$kn {
  static create(actual) {
    return new _$kn(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 _$kn(this.c.map(mapFnc));
  }
  negate() {
    return this.c;
  }
};
function eliminateConstantsInArray(arr) {
  let newArr = null;
  for (let i2 = 0, len = arr.length; i2 < len; i2++) {
    const newExpr = arr[i2].substituteConstants();
    if (arr[i2] !== newExpr) {
      if (newArr === null) {
        newArr = [];
        for (let j = 0; j < i2; j++) {
          newArr[j] = arr[j];
        }
      }
    }
    if (newArr !== null) {
      newArr[i2] = newExpr;
    }
  }
  if (newArr === null) {
    return arr;
  }
  return newArr;
}
var $ln = class _$ln {
  static create(_expr, negated, extraRedundantCheck) {
    return _$ln.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 i2 = 0, len = this.expr.length; i2 < len; i2++) {
      const r2 = cmp(this.expr[i2], other.expr[i2]);
      if (r2 !== 0) {
        return r2;
      }
    }
    return 0;
  }
  equals(other) {
    if (other.type === this.type) {
      if (this.expr.length !== other.expr.length) {
        return false;
      }
      for (let i2 = 0, len = this.expr.length; i2 < len; i2++) {
        if (!this.expr[i2].equals(other.expr[i2])) {
          return false;
        }
      }
      return true;
    }
    return false;
  }
  substituteConstants() {
    const exprArr = eliminateConstantsInArray(this.expr);
    if (exprArr === this.expr) {
      return this;
    }
    return _$ln.create(exprArr, this.c, false);
  }
  evaluate(context) {
    for (let i2 = 0, len = this.expr.length; i2 < len; i2++) {
      if (!this.expr[i2].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 $0m.INSTANCE;
      }
      if (e.type === 6) {
        expr.push(...e.expr);
        continue;
      }
      expr.push(e);
    }
    if (expr.length === 0 && hasTrue) {
      return $$m.INSTANCE;
    }
    if (expr.length === 0) {
      return void 0;
    }
    if (expr.length === 1) {
      return expr[0];
    }
    expr.sort(cmp);
    for (let i2 = 1; i2 < expr.length; i2++) {
      if (expr[i2 - 1].equals(expr[i2])) {
        expr.splice(i2, 1);
        i2--;
      }
    }
    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 = $mn.create(lastElement.expr.map((el) => _$ln.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 i2 = 0; i2 < expr.length; i2++) {
        for (let j = i2 + 1; j < expr.length; j++) {
          if (expr[i2].negate().equals(expr[j])) {
            return $0m.INSTANCE;
          }
        }
      }
      if (expr.length === 1) {
        return expr[0];
      }
    }
    return new _$ln(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 _$ln(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 = $mn.create(result, this, true);
    }
    return this.c;
  }
};
var $mn = class _$mn {
  static create(_expr, negated, extraRedundantCheck) {
    return _$mn.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 i2 = 0, len = this.expr.length; i2 < len; i2++) {
      const r2 = cmp(this.expr[i2], other.expr[i2]);
      if (r2 !== 0) {
        return r2;
      }
    }
    return 0;
  }
  equals(other) {
    if (other.type === this.type) {
      if (this.expr.length !== other.expr.length) {
        return false;
      }
      for (let i2 = 0, len = this.expr.length; i2 < len; i2++) {
        if (!this.expr[i2].equals(other.expr[i2])) {
          return false;
        }
      }
      return true;
    }
    return false;
  }
  substituteConstants() {
    const exprArr = eliminateConstantsInArray(this.expr);
    if (exprArr === this.expr) {
      return this;
    }
    return _$mn.create(exprArr, this.c, false);
  }
  evaluate(context) {
    for (let i2 = 0, len = this.expr.length; i2 < len; i2++) {
      if (this.expr[i2].evaluate(context)) {
        return true;
      }
    }
    return false;
  }
  static d(arr, negated, extraRedundantCheck) {
    let expr = [];
    let hasFalse = false;
    if (arr) {
      for (let i2 = 0, len = arr.length; i2 < len; i2++) {
        const e = arr[i2];
        if (!e) {
          continue;
        }
        if (e.type === 0) {
          hasFalse = true;
          continue;
        }
        if (e.type === 1) {
          return $$m.INSTANCE;
        }
        if (e.type === 9) {
          expr = expr.concat(e.expr);
          continue;
        }
        expr.push(e);
      }
      if (expr.length === 0 && hasFalse) {
        return $0m.INSTANCE;
      }
      expr.sort(cmp);
    }
    if (expr.length === 0) {
      return void 0;
    }
    if (expr.length === 1) {
      return expr[0];
    }
    for (let i2 = 1; i2 < expr.length; i2++) {
      if (expr[i2 - 1].equals(expr[i2])) {
        expr.splice(i2, 1);
        i2--;
      }
    }
    if (expr.length === 1) {
      return expr[0];
    }
    if (extraRedundantCheck) {
      for (let i2 = 0; i2 < expr.length; i2++) {
        for (let j = i2 + 1; j < expr.length; j++) {
          if (expr[i2].negate().equals(expr[j])) {
            return $$m.INSTANCE;
          }
        }
      }
      if (expr.length === 1) {
        return expr[0];
      }
    }
    return new _$mn(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 _$mn(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($ln.create([left, right], null, false));
          }
        }
        result.unshift(_$mn.create(all, null, false));
      }
      this.c = _$mn.create(result, this, true);
    }
    return this.c;
  }
};
var $nn = class _$nn extends $_m {
  static {
    this.d = [];
  }
  static all() {
    return _$nn.d.values();
  }
  constructor(key2, defaultValue, metaOrHide) {
    super(key2, null);
    this.f = defaultValue;
    if (typeof metaOrHide === "object") {
      _$nn.d.push({ ...metaOrHide, key: key2 });
    } else if (metaOrHide !== true) {
      _$nn.d.push({ key: key2, 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 $an.create(this.key, value);
  }
  notEqualsTo(value) {
    return $dn.create(this.key, value);
  }
};
var $on = $Qk("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 $pn(p, q) {
  if (p.type === 0 || q.type === 1) {
    return true;
  }
  if (p.type === 9) {
    if (q.type === 9) {
      return allElementsIncluded(p.expr, q.expr);
    }
    return false;
  }
  if (q.type === 9) {
    for (const element of q.expr) {
      if ($pn(p, element)) {
        return true;
      }
    }
    return false;
  }
  if (p.type === 6) {
    if (q.type === 6) {
      return allElementsIncluded(q.expr, p.expr);
    }
    for (const element of p.expr) {
      if ($pn(element, q)) {
        return true;
      }
    }
    return false;
  }
  return p.equals(q);
}
function allElementsIncluded(p, q) {
  let pIndex = 0;
  let qIndex = 0;
  while (pIndex < p.length && qIndex < q.length) {
    const cmp4 = p[pIndex].cmp(q[qIndex]);
    if (cmp4 < 0) {
      return false;
    } else if (cmp4 === 0) {
      pIndex++;
      qIndex++;
    } else {
      qIndex++;
    }
  }
  return pIndex === p.length;
}
function getTerminals(node) {
  if (node.type === 9) {
    return node.expr;
  }
  return [node];
}

// out-build/vs/base/common/assert.js
function ok(value, message) {
  if (!value) {
    throw new Error(message ? `Assertion failed (${message})` : "Assertion Failed");
  }
}
function $hd(value, message = "Unreachable") {
  throw new Error(message);
}
function $id(condition, message = "unexpected state") {
  if (!condition) {
    throw new $vb(`Assertion Failed: ${message}`);
  }
}
function $jd(condition) {
  if (!condition) {
    $gb(new $vb("Soft Assertion Failed"));
  }
}
function $kd(condition) {
  if (!condition()) {
    debugger;
    condition();
    $gb(new $vb("Assertion Failed"));
  }
}
function $ld(items, predicate) {
  let i2 = 0;
  while (i2 < items.length - 1) {
    const a = items[i2];
    const b = items[i2 + 1];
    if (!predicate(a, b)) {
      return false;
    }
    i2++;
  }
  return true;
}

// out-build/vs/platform/registry/common/platform.js
var RegistryImpl = class {
  constructor() {
    this.a = /* @__PURE__ */ new Map();
  }
  add(id2, data) {
    ok($zg(id2));
    ok($Bg(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 $Wn = new RegistryImpl();

// out-build/vs/platform/keybinding/common/keybindingsRegistry.js
var KeybindingWeight;
(function(KeybindingWeight2) {
  KeybindingWeight2[KeybindingWeight2["EditorCore"] = 0] = "EditorCore";
  KeybindingWeight2[KeybindingWeight2["EditorContrib"] = 100] = "EditorContrib";
  KeybindingWeight2[KeybindingWeight2["WorkbenchContrib"] = 200] = "WorkbenchContrib";
  KeybindingWeight2[KeybindingWeight2["BuiltinExtension"] = 300] = "BuiltinExtension";
  KeybindingWeight2[KeybindingWeight2["ExternalExtension"] = 400] = "ExternalExtension";
})(KeybindingWeight || (KeybindingWeight = {}));
var KeybindingsRegistryImpl = class _KeybindingsRegistryImpl {
  constructor() {
    this.c = new $cd();
    this.d = [];
    this.e = null;
  }
  /**
   * Take current platform into account and reduce to primary & secondary.
   */
  static f(kb) {
    if (OS === 1) {
      if (kb && kb.win) {
        return kb.win;
      }
    } else if (OS === 2) {
      if (kb && kb.mac) {
        return kb.mac;
      }
    } else {
      if (kb && kb.linux) {
        return kb.linux;
      }
    }
    return kb;
  }
  registerKeybindingRule(rule) {
    const actualKb = _KeybindingsRegistryImpl.f(rule);
    const result = new $2c();
    if (actualKb && actualKb.primary) {
      const kk = $_e(actualKb.primary, OS);
      if (kk) {
        result.add(this.g(kk, rule.id, rule.args, rule.weight, 0, rule.when));
      }
    }
    if (actualKb && Array.isArray(actualKb.secondary)) {
      for (let i2 = 0, len = actualKb.secondary.length; i2 < len; i2++) {
        const k = actualKb.secondary[i2];
        const kk = $_e(k, OS);
        if (kk) {
          result.add(this.g(kk, rule.id, rule.args, rule.weight, -i2 - 1, rule.when));
        }
      }
    }
    return result;
  }
  setExtensionKeybindings(rules) {
    const result = [];
    let keybindingsLen = 0;
    for (const rule of rules) {
      if (rule.keybinding) {
        result[keybindingsLen++] = {
          keybinding: rule.keybinding,
          command: rule.id,
          commandArgs: rule.args,
          when: rule.when,
          weight1: rule.weight,
          weight2: 0,
          extensionId: rule.extensionId || null,
          isBuiltinExtension: rule.isBuiltinExtension || false
        };
      }
    }
    this.d = result;
    this.e = null;
  }
  registerCommandAndKeybindingRule(desc) {
    return $Zc(this.registerKeybindingRule(desc), $tn.registerCommand(desc));
  }
  g(keybinding, commandId, commandArgs, weight1, weight22, when) {
    const remove = this.c.push({
      keybinding,
      command: commandId,
      commandArgs,
      when,
      weight1,
      weight2: weight22,
      extensionId: null,
      isBuiltinExtension: false
    });
    this.e = null;
    return $1c(() => {
      remove();
      this.e = null;
    });
  }
  getDefaultKeybindings() {
    if (!this.e) {
      this.e = Array.from(this.c).concat(this.d);
      this.e.sort(sorter);
    }
    return this.e.slice(0);
  }
};
var $0I = new KeybindingsRegistryImpl();
var $$I = {
  EditorModes: "platform.keybindingsRegistry"
};
$Wn.add($$I.EditorModes, $0I);
function sorter(a, b) {
  if (a.weight1 !== b.weight1) {
    return a.weight1 - b.weight1;
  }
  if (a.command && b.command) {
    if (a.command < b.command) {
      return -1;
    }
    if (a.command > b.command) {
      return 1;
    }
  }
  return a.weight2 - b.weight2;
}

// out-build/vs/platform/actions/common/actions.js
var $fJ_1;
function $_I(item) {
  return item.command !== void 0;
}
function $aJ(item) {
  return item.submenu !== void 0;
}
var $bJ = class _$bJ {
  static {
    this.a = /* @__PURE__ */ new Map();
  }
  static {
    this.CommandPalette = new _$bJ("CommandPalette");
  }
  static {
    this.DebugBreakpointsContext = new _$bJ("DebugBreakpointsContext");
  }
  static {
    this.DebugCallStackContext = new _$bJ("DebugCallStackContext");
  }
  static {
    this.DebugConsoleContext = new _$bJ("DebugConsoleContext");
  }
  static {
    this.DebugVariablesContext = new _$bJ("DebugVariablesContext");
  }
  static {
    this.NotebookVariablesContext = new _$bJ("NotebookVariablesContext");
  }
  static {
    this.DebugHoverContext = new _$bJ("DebugHoverContext");
  }
  static {
    this.DebugWatchContext = new _$bJ("DebugWatchContext");
  }
  static {
    this.DebugToolBar = new _$bJ("DebugToolBar");
  }
  static {
    this.DebugToolBarStop = new _$bJ("DebugToolBarStop");
  }
  static {
    this.DebugCallStackToolbar = new _$bJ("DebugCallStackToolbar");
  }
  static {
    this.DebugCreateConfiguration = new _$bJ("DebugCreateConfiguration");
  }
  static {
    this.EditorContext = new _$bJ("EditorContext");
  }
  static {
    this.SimpleEditorContext = new _$bJ("SimpleEditorContext");
  }
  static {
    this.EditorContent = new _$bJ("EditorContent");
  }
  static {
    this.EditorLineNumberContext = new _$bJ("EditorLineNumberContext");
  }
  static {
    this.EditorContextCopy = new _$bJ("EditorContextCopy");
  }
  static {
    this.EditorContextPeek = new _$bJ("EditorContextPeek");
  }
  static {
    this.EditorContextShare = new _$bJ("EditorContextShare");
  }
  static {
    this.EditorTitle = new _$bJ("EditorTitle");
  }
  static {
    this.EditorTitleRun = new _$bJ("EditorTitleRun");
  }
  static {
    this.EditorTitleContext = new _$bJ("EditorTitleContext");
  }
  static {
    this.EditorTitleContextShare = new _$bJ("EditorTitleContextShare");
  }
  static {
    this.EmptyEditorGroup = new _$bJ("EmptyEditorGroup");
  }
  static {
    this.EmptyEditorGroupContext = new _$bJ("EmptyEditorGroupContext");
  }
  static {
    this.EditorTabsBarContext = new _$bJ("EditorTabsBarContext");
  }
  static {
    this.EditorTabsBarShowTabsSubmenu = new _$bJ("EditorTabsBarShowTabsSubmenu");
  }
  static {
    this.EditorTabsBarShowTabsZenModeSubmenu = new _$bJ("EditorTabsBarShowTabsZenModeSubmenu");
  }
  static {
    this.EditorActionsPositionSubmenu = new _$bJ("EditorActionsPositionSubmenu");
  }
  static {
    this.ExplorerContext = new _$bJ("ExplorerContext");
  }
  static {
    this.ExplorerContextShare = new _$bJ("ExplorerContextShare");
  }
  static {
    this.ExtensionContext = new _$bJ("ExtensionContext");
  }
  static {
    this.ExtensionEditorContextMenu = new _$bJ("ExtensionEditorContextMenu");
  }
  static {
    this.GlobalActivity = new _$bJ("GlobalActivity");
  }
  static {
    this.CommandCenter = new _$bJ("CommandCenter");
  }
  static {
    this.CommandCenterCenter = new _$bJ("CommandCenterCenter");
  }
  static {
    this.LayoutControlMenuSubmenu = new _$bJ("LayoutControlMenuSubmenu");
  }
  static {
    this.LayoutControlMenu = new _$bJ("LayoutControlMenu");
  }
  static {
    this.MenubarMainMenu = new _$bJ("MenubarMainMenu");
  }
  static {
    this.MenubarAppearanceMenu = new _$bJ("MenubarAppearanceMenu");
  }
  static {
    this.MenubarDebugMenu = new _$bJ("MenubarDebugMenu");
  }
  static {
    this.MenubarEditMenu = new _$bJ("MenubarEditMenu");
  }
  static {
    this.MenubarCopy = new _$bJ("MenubarCopy");
  }
  static {
    this.MenubarFileMenu = new _$bJ("MenubarFileMenu");
  }
  static {
    this.MenubarGoMenu = new _$bJ("MenubarGoMenu");
  }
  static {
    this.MenubarHelpMenu = new _$bJ("MenubarHelpMenu");
  }
  static {
    this.MenubarLayoutMenu = new _$bJ("MenubarLayoutMenu");
  }
  static {
    this.MenubarNewBreakpointMenu = new _$bJ("MenubarNewBreakpointMenu");
  }
  static {
    this.PanelAlignmentMenu = new _$bJ("PanelAlignmentMenu");
  }
  static {
    this.PanelPositionMenu = new _$bJ("PanelPositionMenu");
  }
  static {
    this.ActivityBarPositionMenu = new _$bJ("ActivityBarPositionMenu");
  }
  static {
    this.MenubarPreferencesMenu = new _$bJ("MenubarPreferencesMenu");
  }
  static {
    this.MenubarRecentMenu = new _$bJ("MenubarRecentMenu");
  }
  static {
    this.MenubarSelectionMenu = new _$bJ("MenubarSelectionMenu");
  }
  static {
    this.MenubarShare = new _$bJ("MenubarShare");
  }
  static {
    this.MenubarSwitchEditorMenu = new _$bJ("MenubarSwitchEditorMenu");
  }
  static {
    this.MenubarSwitchGroupMenu = new _$bJ("MenubarSwitchGroupMenu");
  }
  static {
    this.MenubarTerminalMenu = new _$bJ("MenubarTerminalMenu");
  }
  static {
    this.MenubarViewMenu = new _$bJ("MenubarViewMenu");
  }
  static {
    this.MenubarHomeMenu = new _$bJ("MenubarHomeMenu");
  }
  static {
    this.OpenEditorsContext = new _$bJ("OpenEditorsContext");
  }
  static {
    this.OpenEditorsContextShare = new _$bJ("OpenEditorsContextShare");
  }
  static {
    this.ProblemsPanelContext = new _$bJ("ProblemsPanelContext");
  }
  static {
    this.SCMInputBox = new _$bJ("SCMInputBox");
  }
  static {
    this.SCMChangesContext = new _$bJ("SCMChangesContext");
  }
  static {
    this.SCMChangeContext = new _$bJ("SCMChangeContext");
  }
  static {
    this.SCMResourceContext = new _$bJ("SCMResourceContext");
  }
  static {
    this.SCMResourceContextShare = new _$bJ("SCMResourceContextShare");
  }
  static {
    this.SCMResourceFolderContext = new _$bJ("SCMResourceFolderContext");
  }
  static {
    this.SCMResourceGroupContext = new _$bJ("SCMResourceGroupContext");
  }
  static {
    this.SCMSourceControl = new _$bJ("SCMSourceControl");
  }
  static {
    this.SCMSourceControlInline = new _$bJ("SCMSourceControlInline");
  }
  static {
    this.SCMSourceControlTitle = new _$bJ("SCMSourceControlTitle");
  }
  static {
    this.SCMHistoryTitle = new _$bJ("SCMHistoryTitle");
  }
  static {
    this.SCMHistoryItemRefContext = new _$bJ("SCMHistoryItemRefContext");
  }
  static {
    this.SCMTitle = new _$bJ("SCMTitle");
  }
  static {
    this.SearchContext = new _$bJ("SearchContext");
  }
  static {
    this.SearchActionMenu = new _$bJ("SearchActionContext");
  }
  static {
    this.StatusBarWindowIndicatorMenu = new _$bJ("StatusBarWindowIndicatorMenu");
  }
  static {
    this.StatusBarRemoteIndicatorMenu = new _$bJ("StatusBarRemoteIndicatorMenu");
  }
  static {
    this.StickyScrollContext = new _$bJ("StickyScrollContext");
  }
  static {
    this.TestItem = new _$bJ("TestItem");
  }
  static {
    this.TestItemGutter = new _$bJ("TestItemGutter");
  }
  static {
    this.TestProfilesContext = new _$bJ("TestProfilesContext");
  }
  static {
    this.TestMessageContext = new _$bJ("TestMessageContext");
  }
  static {
    this.TestMessageContent = new _$bJ("TestMessageContent");
  }
  static {
    this.TestPeekElement = new _$bJ("TestPeekElement");
  }
  static {
    this.TestPeekTitle = new _$bJ("TestPeekTitle");
  }
  static {
    this.TestCallStack = new _$bJ("TestCallStack");
  }
  static {
    this.TouchBarContext = new _$bJ("TouchBarContext");
  }
  static {
    this.TitleBarContext = new _$bJ("TitleBarContext");
  }
  static {
    this.TitleBarTitleContext = new _$bJ("TitleBarTitleContext");
  }
  static {
    this.TunnelContext = new _$bJ("TunnelContext");
  }
  static {
    this.TunnelPrivacy = new _$bJ("TunnelPrivacy");
  }
  static {
    this.TunnelProtocol = new _$bJ("TunnelProtocol");
  }
  static {
    this.TunnelPortInline = new _$bJ("TunnelInline");
  }
  static {
    this.TunnelTitle = new _$bJ("TunnelTitle");
  }
  static {
    this.TunnelLocalAddressInline = new _$bJ("TunnelLocalAddressInline");
  }
  static {
    this.TunnelOriginInline = new _$bJ("TunnelOriginInline");
  }
  static {
    this.ViewItemContext = new _$bJ("ViewItemContext");
  }
  static {
    this.ViewContainerTitle = new _$bJ("ViewContainerTitle");
  }
  static {
    this.ViewContainerTitleContext = new _$bJ("ViewContainerTitleContext");
  }
  static {
    this.ViewTitle = new _$bJ("ViewTitle");
  }
  static {
    this.ViewTitleContext = new _$bJ("ViewTitleContext");
  }
  static {
    this.CommentEditorActions = new _$bJ("CommentEditorActions");
  }
  static {
    this.CommentThreadTitle = new _$bJ("CommentThreadTitle");
  }
  static {
    this.CommentThreadActions = new _$bJ("CommentThreadActions");
  }
  static {
    this.CommentThreadAdditionalActions = new _$bJ("CommentThreadAdditionalActions");
  }
  static {
    this.CommentThreadTitleContext = new _$bJ("CommentThreadTitleContext");
  }
  static {
    this.CommentThreadCommentContext = new _$bJ("CommentThreadCommentContext");
  }
  static {
    this.CommentTitle = new _$bJ("CommentTitle");
  }
  static {
    this.CommentActions = new _$bJ("CommentActions");
  }
  static {
    this.CommentsViewThreadActions = new _$bJ("CommentsViewThreadActions");
  }
  static {
    this.InteractiveToolbar = new _$bJ("InteractiveToolbar");
  }
  static {
    this.InteractiveCellTitle = new _$bJ("InteractiveCellTitle");
  }
  static {
    this.InteractiveCellDelete = new _$bJ("InteractiveCellDelete");
  }
  static {
    this.InteractiveCellExecute = new _$bJ("InteractiveCellExecute");
  }
  static {
    this.InteractiveInputExecute = new _$bJ("InteractiveInputExecute");
  }
  static {
    this.InteractiveInputConfig = new _$bJ("InteractiveInputConfig");
  }
  static {
    this.ReplInputExecute = new _$bJ("ReplInputExecute");
  }
  static {
    this.IssueReporter = new _$bJ("IssueReporter");
  }
  static {
    this.NotebookToolbar = new _$bJ("NotebookToolbar");
  }
  static {
    this.NotebookStickyScrollContext = new _$bJ("NotebookStickyScrollContext");
  }
  static {
    this.NotebookCellTitle = new _$bJ("NotebookCellTitle");
  }
  static {
    this.NotebookCellDelete = new _$bJ("NotebookCellDelete");
  }
  static {
    this.NotebookCellInsert = new _$bJ("NotebookCellInsert");
  }
  static {
    this.NotebookCellBetween = new _$bJ("NotebookCellBetween");
  }
  static {
    this.NotebookCellListTop = new _$bJ("NotebookCellTop");
  }
  static {
    this.NotebookCellExecute = new _$bJ("NotebookCellExecute");
  }
  static {
    this.NotebookCellExecuteGoTo = new _$bJ("NotebookCellExecuteGoTo");
  }
  static {
    this.NotebookCellExecutePrimary = new _$bJ("NotebookCellExecutePrimary");
  }
  static {
    this.NotebookDiffCellInputTitle = new _$bJ("NotebookDiffCellInputTitle");
  }
  static {
    this.NotebookDiffDocumentMetadata = new _$bJ("NotebookDiffDocumentMetadata");
  }
  static {
    this.NotebookDiffCellMetadataTitle = new _$bJ("NotebookDiffCellMetadataTitle");
  }
  static {
    this.NotebookDiffCellOutputsTitle = new _$bJ("NotebookDiffCellOutputsTitle");
  }
  static {
    this.NotebookOutputToolbar = new _$bJ("NotebookOutputToolbar");
  }
  static {
    this.NotebookOutlineFilter = new _$bJ("NotebookOutlineFilter");
  }
  static {
    this.NotebookOutlineActionMenu = new _$bJ("NotebookOutlineActionMenu");
  }
  static {
    this.NotebookEditorLayoutConfigure = new _$bJ("NotebookEditorLayoutConfigure");
  }
  static {
    this.NotebookKernelSource = new _$bJ("NotebookKernelSource");
  }
  static {
    this.BulkEditTitle = new _$bJ("BulkEditTitle");
  }
  static {
    this.BulkEditContext = new _$bJ("BulkEditContext");
  }
  static {
    this.TimelineItemContext = new _$bJ("TimelineItemContext");
  }
  static {
    this.TimelineTitle = new _$bJ("TimelineTitle");
  }
  static {
    this.TimelineTitleContext = new _$bJ("TimelineTitleContext");
  }
  static {
    this.TimelineFilterSubMenu = new _$bJ("TimelineFilterSubMenu");
  }
  static {
    this.AccountsContext = new _$bJ("AccountsContext");
  }
  static {
    this.SidebarTitle = new _$bJ("SidebarTitle");
  }
  static {
    this.PanelTitle = new _$bJ("PanelTitle");
  }
  static {
    this.AuxiliaryBarTitle = new _$bJ("AuxiliaryBarTitle");
  }
  static {
    this.AuxiliaryBarHeader = new _$bJ("AuxiliaryBarHeader");
  }
  static {
    this.TerminalInstanceContext = new _$bJ("TerminalInstanceContext");
  }
  static {
    this.TerminalEditorInstanceContext = new _$bJ("TerminalEditorInstanceContext");
  }
  static {
    this.TerminalNewDropdownContext = new _$bJ("TerminalNewDropdownContext");
  }
  static {
    this.TerminalTabContext = new _$bJ("TerminalTabContext");
  }
  static {
    this.TerminalTabEmptyAreaContext = new _$bJ("TerminalTabEmptyAreaContext");
  }
  static {
    this.TerminalStickyScrollContext = new _$bJ("TerminalStickyScrollContext");
  }
  static {
    this.WebviewContext = new _$bJ("WebviewContext");
  }
  static {
    this.InlineCompletionsActions = new _$bJ("InlineCompletionsActions");
  }
  static {
    this.InlineEditsActions = new _$bJ("InlineEditsActions");
  }
  static {
    this.NewFile = new _$bJ("NewFile");
  }
  static {
    this.MergeInput1Toolbar = new _$bJ("MergeToolbar1Toolbar");
  }
  static {
    this.MergeInput2Toolbar = new _$bJ("MergeToolbar2Toolbar");
  }
  static {
    this.MergeBaseToolbar = new _$bJ("MergeBaseToolbar");
  }
  static {
    this.MergeInputResultToolbar = new _$bJ("MergeToolbarResultToolbar");
  }
  static {
    this.InlineSuggestionToolbar = new _$bJ("InlineSuggestionToolbar");
  }
  static {
    this.InlineEditToolbar = new _$bJ("InlineEditToolbar");
  }
  static {
    this.ChatContext = new _$bJ("ChatContext");
  }
  static {
    this.ChatCodeBlock = new _$bJ("ChatCodeblock");
  }
  static {
    this.ChatCompareBlock = new _$bJ("ChatCompareBlock");
  }
  static {
    this.ChatMessageTitle = new _$bJ("ChatMessageTitle");
  }
  static {
    this.ChatMessageFooter = new _$bJ("ChatMessageFooter");
  }
  static {
    this.ChatExecute = new _$bJ("ChatExecute");
  }
  static {
    this.ChatExecuteSecondary = new _$bJ("ChatExecuteSecondary");
  }
  static {
    this.ChatInput = new _$bJ("ChatInput");
  }
  static {
    this.ChatInputSide = new _$bJ("ChatInputSide");
  }
  static {
    this.ChatEditingWidgetToolbar = new _$bJ("ChatEditingWidgetToolbar");
  }
  static {
    this.ChatEditingEditorContent = new _$bJ("ChatEditingEditorContent");
  }
  static {
    this.ChatEditingEditorHunk = new _$bJ("ChatEditingEditorHunk");
  }
  static {
    this.ChatEditingWidgetModifiedFilesToolbar = new _$bJ("ChatEditingWidgetModifiedFilesToolbar");
  }
  static {
    this.ChatInputResourceAttachmentContext = new _$bJ("ChatInputResourceAttachmentContext");
  }
  static {
    this.ChatInputSymbolAttachmentContext = new _$bJ("ChatInputSymbolAttachmentContext");
  }
  static {
    this.ChatInlineResourceAnchorContext = new _$bJ("ChatInlineResourceAnchorContext");
  }
  static {
    this.ChatInlineSymbolAnchorContext = new _$bJ("ChatInlineSymbolAnchorContext");
  }
  static {
    this.ChatEditingCodeBlockContext = new _$bJ("ChatEditingCodeBlockContext");
  }
  static {
    this.ChatCommandCenter = new _$bJ("ChatCommandCenter");
  }
  static {
    this.ChatAttachmentsContext = new _$bJ("ChatAttachmentsContext");
  }
  static {
    this.AccessibleView = new _$bJ("AccessibleView");
  }
  static {
    this.MultiDiffEditorFileToolbar = new _$bJ("MultiDiffEditorFileToolbar");
  }
  static {
    this.DiffEditorHunkToolbar = new _$bJ("DiffEditorHunkToolbar");
  }
  static {
    this.DiffEditorSelectionToolbar = new _$bJ("DiffEditorSelectionToolbar");
  }
  /**
   * Create or reuse a `MenuId` with the given identifier
   */
  static for(identifier2) {
    return _$bJ.a.get(identifier2) ?? new _$bJ(identifier2);
  }
  /**
   * Create a new `MenuId` with the unique identifier. Will throw if a menu
   * with the identifier already exists, use `MenuId.for(ident)` or a unique
   * identifier
   */
  constructor(identifier2) {
    if (_$bJ.a.has(identifier2)) {
      throw new TypeError(`MenuId with identifier '${identifier2}' already exists. Use MenuId.for(ident) or a unique identifier`);
    }
    _$bJ.a.set(identifier2, this);
    this.id = identifier2;
  }
};
var $cJ = $Qk("menuService");
var MenuRegistryChangeEvent = class _MenuRegistryChangeEvent {
  static {
    this.a = /* @__PURE__ */ new Map();
  }
  static for(id2) {
    let value = this.a.get(id2);
    if (!value) {
      value = new _MenuRegistryChangeEvent(id2);
      this.a.set(id2, value);
    }
    return value;
  }
  static merge(events) {
    const ids = /* @__PURE__ */ new Set();
    for (const item of events) {
      if (item instanceof _MenuRegistryChangeEvent) {
        ids.add(item.b);
      }
    }
    return ids;
  }
  constructor(b) {
    this.b = b;
    this.has = (candidate) => candidate === b;
  }
};
var $dJ = new class {
  constructor() {
    this.a = /* @__PURE__ */ new Map();
    this.b = /* @__PURE__ */ new Map();
    this.c = new $Ee({
      merge: MenuRegistryChangeEvent.merge
    });
    this.onDidChangeMenu = this.c.event;
  }
  addCommand(command4) {
    this.a.set(command4.id, command4);
    this.c.fire(MenuRegistryChangeEvent.for($bJ.CommandPalette));
    return $1c(() => {
      if (this.a.delete(command4.id)) {
        this.c.fire(MenuRegistryChangeEvent.for($bJ.CommandPalette));
      }
    });
  }
  getCommand(id2) {
    return this.a.get(id2);
  }
  getCommands() {
    const map = /* @__PURE__ */ new Map();
    this.a.forEach((value, key2) => map.set(key2, value));
    return map;
  }
  appendMenuItem(id2, item) {
    let list2 = this.b.get(id2);
    if (!list2) {
      list2 = new $cd();
      this.b.set(id2, list2);
    }
    const rm = list2.push(item);
    this.c.fire(MenuRegistryChangeEvent.for(id2));
    return $1c(() => {
      rm();
      this.c.fire(MenuRegistryChangeEvent.for(id2));
    });
  }
  appendMenuItems(items) {
    const result = new $2c();
    for (const { id: id2, item } of items) {
      result.add(this.appendMenuItem(id2, item));
    }
    return result;
  }
  getMenuItems(id2) {
    let result;
    if (this.b.has(id2)) {
      result = [...this.b.get(id2)];
    } else {
      result = [];
    }
    if (id2 === $bJ.CommandPalette) {
      this.d(result);
    }
    return result;
  }
  d(result) {
    const set = /* @__PURE__ */ new Set();
    for (const item of result) {
      if ($_I(item)) {
        set.add(item.command.id);
        if (item.alt) {
          set.add(item.alt.id);
        }
      }
    }
    this.a.forEach((command4, id2) => {
      if (!set.has(id2)) {
        result.push({ command: command4 });
      }
    });
  }
}();
var $eJ = class extends $Xm {
  constructor(item, hideActions, actions) {
    super(`submenuitem.${item.submenu.id}`, typeof item.title === "string" ? item.title : item.title.value, actions, "submenu");
    this.item = item;
    this.hideActions = hideActions;
  }
};
var $fJ = $fJ_1 = class $fJ2 {
  static label(action, options3) {
    return options3?.renderShortTitle && action.shortTitle ? typeof action.shortTitle === "string" ? action.shortTitle : action.shortTitle.value : typeof action.title === "string" ? action.title : action.title.value;
  }
  constructor(item, alt, options3, hideActions, menuKeybinding, contextKeyService, d) {
    this.hideActions = hideActions;
    this.menuKeybinding = menuKeybinding;
    this.d = d;
    this.id = item.id;
    this.label = $fJ_1.label(item, options3);
    this.tooltip = (typeof item.tooltip === "string" ? item.tooltip : item.tooltip?.value) ?? "";
    this.enabled = !item.precondition || contextKeyService.contextMatchesRules(item.precondition);
    this.checked = void 0;
    let icon2;
    if (item.toggled) {
      const toggled = item.toggled.condition ? item.toggled : { condition: item.toggled };
      this.checked = contextKeyService.contextMatchesRules(toggled.condition);
      if (this.checked && toggled.tooltip) {
        this.tooltip = typeof toggled.tooltip === "string" ? toggled.tooltip : toggled.tooltip.value;
      }
      if (this.checked && ThemeIcon.isThemeIcon(toggled.icon)) {
        icon2 = toggled.icon;
      }
      if (this.checked && toggled.title) {
        this.label = typeof toggled.title === "string" ? toggled.title : toggled.title.value;
      }
    }
    if (!icon2) {
      icon2 = ThemeIcon.isThemeIcon(item.icon) ? item.icon : void 0;
    }
    this.item = item;
    this.alt = alt ? new $fJ_1(alt, void 0, options3, hideActions, void 0, contextKeyService, d) : void 0;
    this.c = options3;
    this.class = icon2 && ThemeIcon.asClassName(icon2);
  }
  run(...args2) {
    let runArgs = [];
    if (this.c?.arg) {
      runArgs = [...runArgs, this.c.arg];
    }
    if (this.c?.shouldForwardArgs) {
      runArgs = [...runArgs, ...args2];
    }
    return this.d.executeCommand(this.id, ...runArgs);
  }
};
$fJ = $fJ_1 = __decorate([
  __param(5, $on),
  __param(6, $sn)
], $fJ);
var $gJ = class {
  constructor(desc) {
    this.desc = desc;
  }
};
function $hJ(ctor) {
  const disposables = [];
  const action = new ctor();
  const { f1, menu, keybinding, ...command4 } = action.desc;
  if ($tn.getCommand(command4.id)) {
    throw new Error(`Cannot register two commands with the same id: ${command4.id}`);
  }
  disposables.push($tn.registerCommand({
    id: command4.id,
    handler: (accessor, ...args2) => action.run(accessor, ...args2),
    metadata: command4.metadata ?? { description: action.desc.title }
  }));
  if (Array.isArray(menu)) {
    for (const item of menu) {
      disposables.push($dJ.appendMenuItem(item.id, { command: { ...command4, precondition: item.precondition === null ? void 0 : command4.precondition }, ...item }));
    }
  } else if (menu) {
    disposables.push($dJ.appendMenuItem(menu.id, { command: { ...command4, precondition: menu.precondition === null ? void 0 : command4.precondition }, ...menu }));
  }
  if (f1) {
    disposables.push($dJ.appendMenuItem($bJ.CommandPalette, { command: command4, when: command4.precondition }));
    disposables.push($dJ.addCommand(command4));
  }
  if (Array.isArray(keybinding)) {
    for (const item of keybinding) {
      disposables.push($0I.registerKeybindingRule({
        ...item,
        id: command4.id,
        when: command4.precondition ? $7m.and(command4.precondition, item.when) : item.when
      }));
    }
  } else if (keybinding) {
    disposables.push($0I.registerKeybindingRule({
      ...keybinding,
      id: command4.id,
      when: command4.precondition ? $7m.and(command4.precondition, keybinding.when) : keybinding.when
    }));
  }
  return {
    dispose() {
      $Xc(disposables);
    }
  };
}

// out-build/vs/platform/telemetry/common/telemetry.js
var $zv = $Qk("telemetryService");
var $Av = $Qk("customEndpointTelemetryService");
var $Cv = "telemetry.firstSessionDate";
var $Dv = "telemetry.lastSessionDate";
var $Ev = "telemetry.machineId";
var $Hv = "telemetry";
var $Iv = "telemetry.telemetryLevel";
var $Jv = "telemetry.enableCrashReporter";
var $Kv = "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/base/common/errorMessage.js
function exceptionToErrorMessage(exception, verbose) {
  if (verbose && (exception.stack || exception.stacktrace)) {
    return localize(110, 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(111, null, exception.message);
  }
  return exception.message || localize(112, null);
}
function $1m(error = null, verbose = false) {
  if (!error) {
    return localize(113, null);
  }
  if (Array.isArray(error)) {
    const errors = $Mb(error);
    const msg = $1m(errors[0], verbose);
    if (errors.length > 1) {
      return localize(114, null, msg, errors.length);
    }
    return msg;
  }
  if ($zg(error)) {
    return error;
  }
  if (error.detail) {
    const detail2 = error.detail;
    if (detail2.error) {
      return exceptionToErrorMessage(detail2.error, verbose);
    }
    if (detail2.exception) {
      return exceptionToErrorMessage(detail2.exception, verbose);
    }
  }
  if (error.stack) {
    return exceptionToErrorMessage(error, verbose);
  }
  if (error.message) {
    return error.message;
  }
  return localize(115, null);
}
function $2m(obj) {
  const candidate = obj;
  return candidate instanceof Error && Array.isArray(candidate.actions);
}
function $3m(messageOrError, actions) {
  let error;
  if (typeof messageOrError === "string") {
    error = new Error(messageOrError);
  } else {
    error = messageOrError;
  }
  error.actions = actions;
  return error;
}

// out-build/vs/platform/log/common/log.js
var $wn = $Qk("logService");
var $xn = $Qk("loggerService");
function $yn(thing) {
  return $Dg(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 $zn = LogLevel.Info;
function log(logger2, level, message) {
  switch (level) {
    case LogLevel.Trace:
      logger2.trace(message);
      break;
    case LogLevel.Debug:
      logger2.debug(message);
      break;
    case LogLevel.Info:
      logger2.info(message);
      break;
    case LogLevel.Warning:
      logger2.warn(message);
      break;
    case LogLevel.Error:
      logger2.error(message);
      break;
    case LogLevel.Off:
      break;
    default:
      throw new Error(`Invalid log level ${level}`);
  }
}
function format(args2, verbose = false) {
  let result = "";
  for (let i2 = 0; i2 < args2.length; i2++) {
    let a = args2[i2];
    if (a instanceof Error) {
      a = $1m(a, verbose);
    }
    if (typeof a === "object") {
      try {
        a = JSON.stringify(a);
      } catch (e) {
      }
    }
    result += (i2 > 0 ? " " : "") + a;
  }
  return result;
}
var $Bn = class extends $3c {
  constructor() {
    super(...arguments);
    this.b = $zn;
    this.c = this.B(new $ze());
    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;
  }
  g(level) {
    if (this.q.isDisposed) {
      return false;
    }
    return this.f(level);
  }
};
var $Cn = class extends $Bn {
  constructor(h3) {
    super();
    this.h = h3;
  }
  f(level) {
    return this.h || super.f(level);
  }
  trace(message, ...args2) {
    if (this.g(LogLevel.Trace)) {
      this.m(LogLevel.Trace, format([message, ...args2], true));
    }
  }
  debug(message, ...args2) {
    if (this.g(LogLevel.Debug)) {
      this.m(LogLevel.Debug, format([message, ...args2]));
    }
  }
  info(message, ...args2) {
    if (this.g(LogLevel.Info)) {
      this.m(LogLevel.Info, format([message, ...args2]));
    }
  }
  warn(message, ...args2) {
    if (this.g(LogLevel.Warning)) {
      this.m(LogLevel.Warning, format([message, ...args2]));
    }
  }
  error(message, ...args2) {
    if (this.g(LogLevel.Error)) {
      if (message instanceof Error) {
        const array2 = Array.prototype.slice.call(arguments);
        array2[0] = message.stack;
        this.m(LogLevel.Error, format(array2));
      } else {
        this.m(LogLevel.Error, format([message, ...args2]));
      }
    }
  }
  flush() {
  }
};
var $En = class extends $Bn {
  constructor(logLevel = $zn, h3 = true) {
    super();
    this.h = h3;
    this.setLevel(logLevel);
  }
  trace(message, ...args2) {
    if (this.g(LogLevel.Trace)) {
      if (this.h) {
        console.log("%cTRACE", "color: #888", message, ...args2);
      } else {
        console.log(message, ...args2);
      }
    }
  }
  debug(message, ...args2) {
    if (this.g(LogLevel.Debug)) {
      if (this.h) {
        console.log("%cDEBUG", "background: #eee; color: #888", message, ...args2);
      } else {
        console.log(message, ...args2);
      }
    }
  }
  info(message, ...args2) {
    if (this.g(LogLevel.Info)) {
      if (this.h) {
        console.log("%c INFO", "color: #33f", message, ...args2);
      } else {
        console.log(message, ...args2);
      }
    }
  }
  warn(message, ...args2) {
    if (this.g(LogLevel.Warning)) {
      if (this.h) {
        console.log("%c WARN", "color: #993", message, ...args2);
      } else {
        console.log(message, ...args2);
      }
    }
  }
  error(message, ...args2) {
    if (this.g(LogLevel.Error)) {
      if (this.h) {
        console.log("%c  ERR", "color: #f33", message, ...args2);
      } else {
        console.error(message, ...args2);
      }
    }
  }
  flush() {
  }
};
var $Fn = class extends $Bn {
  constructor(h3, logLevel = $zn) {
    super();
    this.h = h3;
    this.setLevel(logLevel);
  }
  trace(message, ...args2) {
    if (this.g(LogLevel.Trace)) {
      this.h.log(LogLevel.Trace, [this.j(message), ...args2]);
    }
  }
  debug(message, ...args2) {
    if (this.g(LogLevel.Debug)) {
      this.h.log(LogLevel.Debug, [this.j(message), ...args2]);
    }
  }
  info(message, ...args2) {
    if (this.g(LogLevel.Info)) {
      this.h.log(LogLevel.Info, [this.j(message), ...args2]);
    }
  }
  warn(message, ...args2) {
    if (this.g(LogLevel.Warning)) {
      this.h.log(LogLevel.Warning, [this.j(message), ...args2]);
    }
  }
  error(message, ...args2) {
    if (this.g(LogLevel.Error)) {
      this.h.log(LogLevel.Error, [this.j(message), ...args2]);
    }
  }
  j(msg) {
    if (typeof msg === "string") {
      return msg;
    }
    return $1m(msg, this.g(LogLevel.Trace));
  }
  flush() {
  }
};
var $Gn = class extends $Bn {
  constructor(h3) {
    super();
    this.h = h3;
    if (h3.length) {
      this.setLevel(h3[0].getLevel());
    }
  }
  setLevel(level) {
    for (const logger2 of this.h) {
      logger2.setLevel(level);
    }
    super.setLevel(level);
  }
  trace(message, ...args2) {
    for (const logger2 of this.h) {
      logger2.trace(message, ...args2);
    }
  }
  debug(message, ...args2) {
    for (const logger2 of this.h) {
      logger2.debug(message, ...args2);
    }
  }
  info(message, ...args2) {
    for (const logger2 of this.h) {
      logger2.info(message, ...args2);
    }
  }
  warn(message, ...args2) {
    for (const logger2 of this.h) {
      logger2.warn(message, ...args2);
    }
  }
  error(message, ...args2) {
    for (const logger2 of this.h) {
      logger2.error(message, ...args2);
    }
  }
  flush() {
    for (const logger2 of this.h) {
      logger2.flush();
    }
  }
  dispose() {
    for (const logger2 of this.h) {
      logger2.dispose();
    }
    super.dispose();
  }
};
var $Hn = class extends $3c {
  constructor(h3, j, loggerResources) {
    super();
    this.h = h3;
    this.j = j;
    this.b = new $Ec();
    this.c = this.B(new $ze());
    this.onDidChangeLoggers = this.c.event;
    this.f = this.B(new $ze());
    this.onDidChangeLogLevel = this.f.event;
    this.g = this.B(new $ze());
    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 ($zg(resourceOrId)) {
      return [...this.b.values()].find((logger2) => logger2.info.id === resourceOrId);
    }
    return this.b.get(resourceOrId);
  }
  getLogger(resourceOrId) {
    return this.m(resourceOrId)?.logger;
  }
  createLogger(idOrResource, options3) {
    const resource = this.n(idOrResource);
    const id2 = $zg(idOrResource) ? idOrResource : options3?.id ?? $Xi(resource.toString()).toString(16);
    let logger2 = this.b.get(resource)?.logger;
    const logLevel = options3?.logLevel === "always" ? LogLevel.Trace : options3?.logLevel;
    if (!logger2) {
      logger2 = this.s(resource, logLevel ?? this.getLogLevel(resource) ?? this.h, { ...options3, id: id2 });
    }
    const loggerEntry = {
      logger: logger2,
      info: { resource, id: id2, logLevel, name: options3?.name, hidden: options3?.hidden, extensionId: options3?.extensionId, when: options3?.when }
    };
    this.registerLogger(loggerEntry.info);
    this.b.set(resource, loggerEntry);
    return logger2;
  }
  n(idOrResource) {
    return $zg(idOrResource) ? $vh(this.j, `${idOrResource}.log`) : idOrResource;
  }
  setLogLevel(arg1, arg2) {
    if (URI.isUri(arg1)) {
      const resource = arg1;
      const logLevel = arg2;
      const logger2 = this.b.get(resource);
      if (logger2 && logLevel !== logger2.info.logLevel) {
        logger2.info.logLevel = logLevel === this.h ? void 0 : logLevel;
        logger2.logger?.setLevel(logLevel);
        this.b.set(logger2.info.resource, logger2);
        this.f.fire([resource, logLevel]);
      }
    } else {
      this.h = arg1;
      for (const [resource, logger2] of this.b.entries()) {
        if (this.b.get(resource)?.info.logLevel === void 0) {
          logger2.logger?.setLevel(this.h);
        }
      }
      this.f.fire(this.h);
    }
  }
  setVisibility(resourceOrId, visibility) {
    const logger2 = this.m(resourceOrId);
    if (logger2 && visibility !== !logger2.info.hidden) {
      logger2.info.hidden = !visibility;
      this.b.set(logger2.info.resource, logger2);
      this.g.fire([logger2.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((logger2) => logger2.logger?.dispose());
    this.b.clear();
    super.dispose();
  }
};
var $In = class {
  constructor() {
    this.onDidChangeLogLevel = new $ze().event;
  }
  setLevel(level) {
  }
  getLevel() {
    return LogLevel.Info;
  }
  trace(message, ...args2) {
  }
  debug(message, ...args2) {
  }
  info(message, ...args2) {
  }
  warn(message, ...args2) {
  }
  error(message, ...args2) {
  }
  critical(message, ...args2) {
  }
  dispose() {
  }
  flush() {
  }
};
var $Jn = class extends $In {
};
function $Kn(environmentService) {
  if (environmentService.verbose) {
    return LogLevel.Trace;
  }
  if (typeof environmentService.logLevel === "string") {
    const logLevel = $Nn(environmentService.logLevel.toLowerCase());
    if (logLevel !== void 0) {
      return logLevel;
    }
  }
  return $zn;
}
function $Ln(logLevel) {
  switch (logLevel) {
    case LogLevel.Trace:
      return "trace";
    case LogLevel.Debug:
      return "debug";
    case LogLevel.Info:
      return "info";
    case LogLevel.Warning:
      return "warn";
    case LogLevel.Error:
      return "error";
    case LogLevel.Off:
      return "off";
  }
}
function $Mn(logLevel) {
  switch (logLevel) {
    case LogLevel.Trace:
      return { original: "Trace", value: localize(1992, null) };
    case LogLevel.Debug:
      return { original: "Debug", value: localize(1993, null) };
    case LogLevel.Info:
      return { original: "Info", value: localize(1994, null) };
    case LogLevel.Warning:
      return { original: "Warning", value: localize(1995, null) };
    case LogLevel.Error:
      return { original: "Error", value: localize(1996, null) };
    case LogLevel.Off:
      return { original: "Off", value: localize(1997, null) };
  }
}
function $Nn(logLevel) {
  switch (logLevel) {
    case "trace":
      return LogLevel.Trace;
    case "debug":
      return LogLevel.Debug;
    case "info":
      return LogLevel.Info;
    case "warn":
      return LogLevel.Warning;
    case "error":
      return LogLevel.Error;
    case "critical":
      return LogLevel.Error;
    case "off":
      return LogLevel.Off;
  }
  return void 0;
}
var $On = new $nn("logLevel", $Ln(LogLevel.Info));

// out-build/vs/editor/browser/editorExtensions.js
var EditorContributionInstantiation;
(function(EditorContributionInstantiation2) {
  EditorContributionInstantiation2[EditorContributionInstantiation2["Eager"] = 0] = "Eager";
  EditorContributionInstantiation2[EditorContributionInstantiation2["AfterFirstRender"] = 1] = "AfterFirstRender";
  EditorContributionInstantiation2[EditorContributionInstantiation2["BeforeFirstInteraction"] = 2] = "BeforeFirstInteraction";
  EditorContributionInstantiation2[EditorContributionInstantiation2["Eventually"] = 3] = "Eventually";
  EditorContributionInstantiation2[EditorContributionInstantiation2["Lazy"] = 4] = "Lazy";
})(EditorContributionInstantiation || (EditorContributionInstantiation = {}));
var $V5 = class {
  constructor(opts) {
    this.id = opts.id;
    this.precondition = opts.precondition;
    this.f = opts.kbOpts;
    this.g = opts.menuOpts;
    this.metadata = opts.metadata;
  }
  register() {
    if (Array.isArray(this.g)) {
      this.g.forEach(this.o, this);
    } else if (this.g) {
      this.o(this.g);
    }
    if (this.f) {
      const kbOptsArr = Array.isArray(this.f) ? this.f : [this.f];
      for (const kbOpts of kbOptsArr) {
        let kbWhen = kbOpts.kbExpr;
        if (this.precondition) {
          if (kbWhen) {
            kbWhen = $7m.and(kbWhen, this.precondition);
          } else {
            kbWhen = this.precondition;
          }
        }
        const desc = {
          id: this.id,
          weight: kbOpts.weight,
          args: kbOpts.args,
          when: kbWhen,
          primary: kbOpts.primary,
          secondary: kbOpts.secondary,
          win: kbOpts.win,
          linux: kbOpts.linux,
          mac: kbOpts.mac
        };
        $0I.registerKeybindingRule(desc);
      }
    }
    $tn.registerCommand({
      id: this.id,
      handler: (accessor, args2) => this.runCommand(accessor, args2),
      metadata: this.metadata
    });
  }
  o(item) {
    $dJ.appendMenuItem(item.menuId, {
      group: item.group,
      command: {
        id: this.id,
        title: item.title,
        icon: item.icon,
        precondition: this.precondition
      },
      when: item.when,
      order: item.order
    });
  }
};
var $W5 = class extends $V5 {
  constructor() {
    super(...arguments);
    this.d = [];
  }
  /**
   * A higher priority gets to be looked at first
   */
  addImplementation(priority, name, implementation, when) {
    this.d.push({ priority, name, implementation, when });
    this.d.sort((a, b) => b.priority - a.priority);
    return {
      dispose: () => {
        for (let i2 = 0; i2 < this.d.length; i2++) {
          if (this.d[i2].implementation === implementation) {
            this.d.splice(i2, 1);
            return;
          }
        }
      }
    };
  }
  runCommand(accessor, args2) {
    const logService = accessor.get($wn);
    const contextKeyService = accessor.get($on);
    logService.trace(`Executing Command '${this.id}' which has ${this.d.length} bound.`);
    for (const impl of this.d) {
      if (impl.when) {
        const context = contextKeyService.getContext($Lj());
        const value = impl.when.evaluate(context);
        if (!value) {
          continue;
        }
      }
      const result = impl.implementation(accessor, args2);
      if (result) {
        logService.trace(`Command '${this.id}' was handled by '${impl.name}'.`);
        if (typeof result === "boolean") {
          return;
        }
        return result;
      }
    }
    logService.trace(`The Command '${this.id}' was not handled by any implementation.`);
  }
};
var $X5 = class extends $V5 {
  constructor(d, opts) {
    super(opts);
    this.d = d;
  }
  runCommand(accessor, args2) {
    return this.d.runCommand(accessor, args2);
  }
};
var $Y5 = class _$Y5 extends $V5 {
  /**
   * Create a command class that is bound to a certain editor contribution.
   */
  static bindToContribution(controllerGetter) {
    return class EditorControllerCommandImpl extends _$Y5 {
      constructor(opts) {
        super(opts);
        this.d = opts.handler;
      }
      runEditorCommand(accessor, editor, args2) {
        const controller = controllerGetter(editor);
        if (controller) {
          this.d(controller, args2);
        }
      }
    };
  }
  static runEditorCommand(accessor, args2, precondition2, runner) {
    const codeEditorService = accessor.get($U5);
    const editor = codeEditorService.getFocusedCodeEditor() || codeEditorService.getActiveCodeEditor();
    if (!editor) {
      return;
    }
    return editor.invokeWithinContext((editorAccessor) => {
      const kbService = editorAccessor.get($on);
      if (!kbService.contextMatchesRules(precondition2 ?? void 0)) {
        return;
      }
      return runner(editorAccessor, editor, args2);
    });
  }
  runCommand(accessor, args2) {
    return _$Y5.runEditorCommand(accessor, args2, this.precondition, (accessor2, editor, args3) => this.runEditorCommand(accessor2, editor, args3));
  }
};
var $Z5 = class _$Z5 extends $Y5 {
  static q(opts) {
    let menuOpts;
    if (Array.isArray(opts.menuOpts)) {
      menuOpts = opts.menuOpts;
    } else if (opts.menuOpts) {
      menuOpts = [opts.menuOpts];
    } else {
      menuOpts = [];
    }
    function withDefaults(item) {
      if (!item.menuId) {
        item.menuId = $bJ.EditorContext;
      }
      if (!item.title) {
        item.title = typeof opts.label === "string" ? opts.label : opts.label.value;
      }
      item.when = $7m.and(opts.precondition, item.when);
      return item;
    }
    if (Array.isArray(opts.contextMenuOpts)) {
      menuOpts.push(...opts.contextMenuOpts.map(withDefaults));
    } else if (opts.contextMenuOpts) {
      menuOpts.push(withDefaults(opts.contextMenuOpts));
    }
    opts.menuOpts = menuOpts;
    return opts;
  }
  constructor(opts) {
    super(_$Z5.q(opts));
    if (typeof opts.label === "string") {
      this.label = opts.label;
      this.alias = opts.alias ?? opts.label;
    } else {
      this.label = opts.label.value;
      this.alias = opts.alias ?? opts.label.original;
    }
  }
  runEditorCommand(accessor, editor, args2) {
    this.u(accessor, editor);
    return this.run(accessor, editor, args2 || {});
  }
  u(accessor, editor) {
    accessor.get($zv).publicLog2("editorActionInvoked", { name: this.label, id: this.id });
  }
};
var $15 = class extends $Z5 {
  constructor() {
    super(...arguments);
    this.d = [];
  }
  /**
   * A higher priority gets to be looked at first
   */
  addImplementation(priority, implementation) {
    this.d.push([priority, implementation]);
    this.d.sort((a, b) => b[0] - a[0]);
    return {
      dispose: () => {
        for (let i2 = 0; i2 < this.d.length; i2++) {
          if (this.d[i2][1] === implementation) {
            this.d.splice(i2, 1);
            return;
          }
        }
      }
    };
  }
  run(accessor, editor, args2) {
    for (const impl of this.d) {
      const result = impl[1](accessor, editor, args2);
      if (result) {
        if (typeof result === "boolean") {
          return;
        }
        return result;
      }
    }
  }
};
var $25 = class extends $gJ {
  run(accessor, ...args2) {
    const codeEditorService = accessor.get($U5);
    const editor = codeEditorService.getFocusedCodeEditor() || codeEditorService.getActiveCodeEditor();
    if (!editor) {
      return;
    }
    return editor.invokeWithinContext((editorAccessor) => {
      const kbService = editorAccessor.get($on);
      const logService = editorAccessor.get($wn);
      const enabled = kbService.contextMatchesRules(this.desc.precondition ?? void 0);
      if (!enabled) {
        logService.debug(`[EditorAction2] NOT running command because its precondition is FALSE`, this.desc.id, this.desc.precondition?.serialize());
        return;
      }
      return this.runEditorCommand(editorAccessor, editor, ...args2);
    });
  }
};
function $35(id2, handler) {
  $tn.registerCommand(id2, function(accessor, ...args2) {
    const instaService = accessor.get($Pk);
    const [resource, position] = args2;
    $Jg(URI.isUri(resource));
    $Jg($8C.isIPosition(position));
    const model = accessor.get($sG).getModel(resource);
    if (model) {
      const editorPosition = $8C.lift(position);
      return instaService.invokeFunction(handler, model, editorPosition, ...args2.slice(2));
    }
    return accessor.get($oG).createModelReference(resource).then((reference) => {
      return new Promise((resolve, reject) => {
        try {
          const result = instaService.invokeFunction(handler, reference.object.textEditorModel, $8C.lift(position), args2.slice(2));
          resolve(result);
        } catch (err) {
          reject(err);
        }
      }).finally(() => {
        reference.dispose();
      });
    });
  });
}
function $45(editorCommand) {
  EditorContributionRegistry.INSTANCE.registerEditorCommand(editorCommand);
  return editorCommand;
}
function $55(ctor) {
  const action = new ctor();
  EditorContributionRegistry.INSTANCE.registerEditorAction(action);
  return action;
}
function $65(action) {
  EditorContributionRegistry.INSTANCE.registerEditorAction(action);
  return action;
}
function $75(editorAction) {
  EditorContributionRegistry.INSTANCE.registerEditorAction(editorAction);
}
function $85(id2, ctor, instantiation) {
  EditorContributionRegistry.INSTANCE.registerEditorContribution(id2, ctor, instantiation);
}
function $95(id2, ctor) {
  EditorContributionRegistry.INSTANCE.registerDiffEditorContribution(id2, ctor);
}
var EditorExtensionsRegistry;
(function(EditorExtensionsRegistry2) {
  function getEditorCommand(commandId) {
    return EditorContributionRegistry.INSTANCE.getEditorCommand(commandId);
  }
  EditorExtensionsRegistry2.getEditorCommand = getEditorCommand;
  function getEditorActions() {
    return EditorContributionRegistry.INSTANCE.getEditorActions();
  }
  EditorExtensionsRegistry2.getEditorActions = getEditorActions;
  function getEditorContributions() {
    return EditorContributionRegistry.INSTANCE.getEditorContributions();
  }
  EditorExtensionsRegistry2.getEditorContributions = getEditorContributions;
  function getSomeEditorContributions(ids) {
    return EditorContributionRegistry.INSTANCE.getEditorContributions().filter((c) => ids.indexOf(c.id) >= 0);
  }
  EditorExtensionsRegistry2.getSomeEditorContributions = getSomeEditorContributions;
  function getDiffEditorContributions() {
    return EditorContributionRegistry.INSTANCE.getDiffEditorContributions();
  }
  EditorExtensionsRegistry2.getDiffEditorContributions = getDiffEditorContributions;
})(EditorExtensionsRegistry || (EditorExtensionsRegistry = {}));
var Extensions = {
  EditorCommonContributions: "editor.contributions"
};
var EditorContributionRegistry = class _EditorContributionRegistry {
  static {
    this.INSTANCE = new _EditorContributionRegistry();
  }
  constructor() {
    this.d = [];
    this.e = [];
    this.f = [];
    this.g = /* @__PURE__ */ Object.create(null);
  }
  registerEditorContribution(id2, ctor, instantiation) {
    this.d.push({ id: id2, ctor, instantiation });
  }
  getEditorContributions() {
    return this.d.slice(0);
  }
  registerDiffEditorContribution(id2, ctor) {
    this.e.push({ id: id2, ctor });
  }
  getDiffEditorContributions() {
    return this.e.slice(0);
  }
  registerEditorAction(action) {
    action.register();
    this.f.push(action);
  }
  getEditorActions() {
    return this.f;
  }
  registerEditorCommand(editorCommand) {
    editorCommand.register();
    this.g[editorCommand.id] = editorCommand;
  }
  getEditorCommand(commandId) {
    return this.g[commandId] || null;
  }
};
$Wn.add(Extensions.EditorCommonContributions, EditorContributionRegistry.INSTANCE);
function registerCommand(command4) {
  command4.register();
  return command4;
}
var $05 = registerCommand(new $W5({
  id: "undo",
  precondition: void 0,
  kbOpts: {
    weight: 0,
    primary: 2048 | 56
    /* KeyCode.KeyZ */
  },
  menuOpts: [{
    menuId: $bJ.MenubarEditMenu,
    group: "1_do",
    title: localize(185, null),
    order: 1
  }, {
    menuId: $bJ.CommandPalette,
    group: "",
    title: localize(186, null),
    order: 1
  }]
}));
registerCommand(new $X5($05, { id: "default:undo", precondition: void 0 }));
var $$5 = registerCommand(new $W5({
  id: "redo",
  precondition: void 0,
  kbOpts: {
    weight: 0,
    primary: 2048 | 55,
    secondary: [
      2048 | 1024 | 56
      /* KeyCode.KeyZ */
    ],
    mac: {
      primary: 2048 | 1024 | 56
      /* KeyCode.KeyZ */
    }
  },
  menuOpts: [{
    menuId: $bJ.MenubarEditMenu,
    group: "1_do",
    title: localize(187, null),
    order: 2
  }, {
    menuId: $bJ.CommandPalette,
    group: "",
    title: localize(188, null),
    order: 1
  }]
}));
registerCommand(new $X5($$5, { id: "default:redo", precondition: void 0 }));
var $_5 = registerCommand(new $W5({
  id: "editor.action.selectAll",
  precondition: void 0,
  kbOpts: {
    weight: 0,
    kbExpr: null,
    primary: 2048 | 31
    /* KeyCode.KeyA */
  },
  menuOpts: [{
    menuId: $bJ.MenubarSelectionMenu,
    group: "1_basic",
    title: localize(189, null),
    order: 1
  }, {
    menuId: $bJ.CommandPalette,
    group: "",
    title: localize(190, null),
    order: 1
  }]
}));

// out-build/vs/editor/common/core/range.js
var $9C = class _$9C {
  constructor(startLineNumber, startColumn, endLineNumber, endColumn) {
    if (startLineNumber > endLineNumber || startLineNumber === endLineNumber && startColumn > endColumn) {
      this.startLineNumber = endLineNumber;
      this.startColumn = endColumn;
      this.endLineNumber = startLineNumber;
      this.endColumn = startColumn;
    } else {
      this.startLineNumber = startLineNumber;
      this.startColumn = startColumn;
      this.endLineNumber = endLineNumber;
      this.endColumn = endColumn;
    }
  }
  /**
   * Test if this range is empty.
   */
  isEmpty() {
    return _$9C.isEmpty(this);
  }
  /**
   * Test if `range` is empty.
   */
  static isEmpty(range) {
    return range.startLineNumber === range.endLineNumber && range.startColumn === range.endColumn;
  }
  /**
   * Test if position is in this range. If the position is at the edges, will return true.
   */
  containsPosition(position) {
    return _$9C.containsPosition(this, position);
  }
  /**
   * Test if `position` is in `range`. If the position is at the edges, will return true.
   */
  static containsPosition(range, position) {
    if (position.lineNumber < range.startLineNumber || position.lineNumber > range.endLineNumber) {
      return false;
    }
    if (position.lineNumber === range.startLineNumber && position.column < range.startColumn) {
      return false;
    }
    if (position.lineNumber === range.endLineNumber && position.column > range.endColumn) {
      return false;
    }
    return true;
  }
  /**
   * Test if `position` is in `range`. If the position is at the edges, will return false.
   * @internal
   */
  static strictContainsPosition(range, position) {
    if (position.lineNumber < range.startLineNumber || position.lineNumber > range.endLineNumber) {
      return false;
    }
    if (position.lineNumber === range.startLineNumber && position.column <= range.startColumn) {
      return false;
    }
    if (position.lineNumber === range.endLineNumber && position.column >= range.endColumn) {
      return false;
    }
    return true;
  }
  /**
   * Test if range is in this range. If the range is equal to this range, will return true.
   */
  containsRange(range) {
    return _$9C.containsRange(this, range);
  }
  /**
   * Test if `otherRange` is in `range`. If the ranges are equal, will return true.
   */
  static containsRange(range, otherRange) {
    if (otherRange.startLineNumber < range.startLineNumber || otherRange.endLineNumber < range.startLineNumber) {
      return false;
    }
    if (otherRange.startLineNumber > range.endLineNumber || otherRange.endLineNumber > range.endLineNumber) {
      return false;
    }
    if (otherRange.startLineNumber === range.startLineNumber && otherRange.startColumn < range.startColumn) {
      return false;
    }
    if (otherRange.endLineNumber === range.endLineNumber && otherRange.endColumn > range.endColumn) {
      return false;
    }
    return true;
  }
  /**
   * Test if `range` is strictly in this range. `range` must start after and end before this range for the result to be true.
   */
  strictContainsRange(range) {
    return _$9C.strictContainsRange(this, range);
  }
  /**
   * Test if `otherRange` is strictly in `range` (must start after, and end before). If the ranges are equal, will return false.
   */
  static strictContainsRange(range, otherRange) {
    if (otherRange.startLineNumber < range.startLineNumber || otherRange.endLineNumber < range.startLineNumber) {
      return false;
    }
    if (otherRange.startLineNumber > range.endLineNumber || otherRange.endLineNumber > range.endLineNumber) {
      return false;
    }
    if (otherRange.startLineNumber === range.startLineNumber && otherRange.startColumn <= range.startColumn) {
      return false;
    }
    if (otherRange.endLineNumber === range.endLineNumber && otherRange.endColumn >= range.endColumn) {
      return false;
    }
    return true;
  }
  /**
   * A reunion of the two ranges.
   * The smallest position will be used as the start point, and the largest one as the end point.
   */
  plusRange(range) {
    return _$9C.plusRange(this, range);
  }
  /**
   * A reunion of the two ranges.
   * The smallest position will be used as the start point, and the largest one as the end point.
   */
  static plusRange(a, b) {
    let startLineNumber;
    let startColumn;
    let endLineNumber;
    let endColumn;
    if (b.startLineNumber < a.startLineNumber) {
      startLineNumber = b.startLineNumber;
      startColumn = b.startColumn;
    } else if (b.startLineNumber === a.startLineNumber) {
      startLineNumber = b.startLineNumber;
      startColumn = Math.min(b.startColumn, a.startColumn);
    } else {
      startLineNumber = a.startLineNumber;
      startColumn = a.startColumn;
    }
    if (b.endLineNumber > a.endLineNumber) {
      endLineNumber = b.endLineNumber;
      endColumn = b.endColumn;
    } else if (b.endLineNumber === a.endLineNumber) {
      endLineNumber = b.endLineNumber;
      endColumn = Math.max(b.endColumn, a.endColumn);
    } else {
      endLineNumber = a.endLineNumber;
      endColumn = a.endColumn;
    }
    return new _$9C(startLineNumber, startColumn, endLineNumber, endColumn);
  }
  /**
   * A intersection of the two ranges.
   */
  intersectRanges(range) {
    return _$9C.intersectRanges(this, range);
  }
  /**
   * A intersection of the two ranges.
   */
  static intersectRanges(a, b) {
    let resultStartLineNumber = a.startLineNumber;
    let resultStartColumn = a.startColumn;
    let resultEndLineNumber = a.endLineNumber;
    let resultEndColumn = a.endColumn;
    const otherStartLineNumber = b.startLineNumber;
    const otherStartColumn = b.startColumn;
    const otherEndLineNumber = b.endLineNumber;
    const otherEndColumn = b.endColumn;
    if (resultStartLineNumber < otherStartLineNumber) {
      resultStartLineNumber = otherStartLineNumber;
      resultStartColumn = otherStartColumn;
    } else if (resultStartLineNumber === otherStartLineNumber) {
      resultStartColumn = Math.max(resultStartColumn, otherStartColumn);
    }
    if (resultEndLineNumber > otherEndLineNumber) {
      resultEndLineNumber = otherEndLineNumber;
      resultEndColumn = otherEndColumn;
    } else if (resultEndLineNumber === otherEndLineNumber) {
      resultEndColumn = Math.min(resultEndColumn, otherEndColumn);
    }
    if (resultStartLineNumber > resultEndLineNumber) {
      return null;
    }
    if (resultStartLineNumber === resultEndLineNumber && resultStartColumn > resultEndColumn) {
      return null;
    }
    return new _$9C(resultStartLineNumber, resultStartColumn, resultEndLineNumber, resultEndColumn);
  }
  /**
   * Test if this range equals other.
   */
  equalsRange(other) {
    return _$9C.equalsRange(this, other);
  }
  /**
   * Test if range `a` equals `b`.
   */
  static equalsRange(a, b) {
    if (!a && !b) {
      return true;
    }
    return !!a && !!b && a.startLineNumber === b.startLineNumber && a.startColumn === b.startColumn && a.endLineNumber === b.endLineNumber && a.endColumn === b.endColumn;
  }
  /**
   * Return the end position (which will be after or equal to the start position)
   */
  getEndPosition() {
    return _$9C.getEndPosition(this);
  }
  /**
   * Return the end position (which will be after or equal to the start position)
   */
  static getEndPosition(range) {
    return new $8C(range.endLineNumber, range.endColumn);
  }
  /**
   * Return the start position (which will be before or equal to the end position)
   */
  getStartPosition() {
    return _$9C.getStartPosition(this);
  }
  /**
   * Return the start position (which will be before or equal to the end position)
   */
  static getStartPosition(range) {
    return new $8C(range.startLineNumber, range.startColumn);
  }
  /**
   * Transform to a user presentable string representation.
   */
  toString() {
    return "[" + this.startLineNumber + "," + this.startColumn + " -> " + this.endLineNumber + "," + this.endColumn + "]";
  }
  /**
   * Create a new range using this range's start position, and using endLineNumber and endColumn as the end position.
   */
  setEndPosition(endLineNumber, endColumn) {
    return new _$9C(this.startLineNumber, this.startColumn, endLineNumber, endColumn);
  }
  /**
   * Create a new range using this range's end position, and using startLineNumber and startColumn as the start position.
   */
  setStartPosition(startLineNumber, startColumn) {
    return new _$9C(startLineNumber, startColumn, this.endLineNumber, this.endColumn);
  }
  /**
   * Create a new empty range using this range's start position.
   */
  collapseToStart() {
    return _$9C.collapseToStart(this);
  }
  /**
   * Create a new empty range using this range's start position.
   */
  static collapseToStart(range) {
    return new _$9C(range.startLineNumber, range.startColumn, range.startLineNumber, range.startColumn);
  }
  /**
   * Create a new empty range using this range's end position.
   */
  collapseToEnd() {
    return _$9C.collapseToEnd(this);
  }
  /**
   * Create a new empty range using this range's end position.
   */
  static collapseToEnd(range) {
    return new _$9C(range.endLineNumber, range.endColumn, range.endLineNumber, range.endColumn);
  }
  /**
   * Moves the range by the given amount of lines.
   */
  delta(lineCount) {
    return new _$9C(this.startLineNumber + lineCount, this.startColumn, this.endLineNumber + lineCount, this.endColumn);
  }
  // ---
  static fromPositions(start, end = start) {
    return new _$9C(start.lineNumber, start.column, end.lineNumber, end.column);
  }
  static lift(range) {
    if (!range) {
      return null;
    }
    return new _$9C(range.startLineNumber, range.startColumn, range.endLineNumber, range.endColumn);
  }
  /**
   * Test if `obj` is an `IRange`.
   */
  static isIRange(obj) {
    return obj && typeof obj.startLineNumber === "number" && typeof obj.startColumn === "number" && typeof obj.endLineNumber === "number" && typeof obj.endColumn === "number";
  }
  /**
   * Test if the two ranges are touching in any way.
   */
  static areIntersectingOrTouching(a, b) {
    if (a.endLineNumber < b.startLineNumber || a.endLineNumber === b.startLineNumber && a.endColumn < b.startColumn) {
      return false;
    }
    if (b.endLineNumber < a.startLineNumber || b.endLineNumber === a.startLineNumber && b.endColumn < a.startColumn) {
      return false;
    }
    return true;
  }
  /**
   * Test if the two ranges are intersecting. If the ranges are touching it returns true.
   */
  static areIntersecting(a, b) {
    if (a.endLineNumber < b.startLineNumber || a.endLineNumber === b.startLineNumber && a.endColumn <= b.startColumn) {
      return false;
    }
    if (b.endLineNumber < a.startLineNumber || b.endLineNumber === a.startLineNumber && b.endColumn <= a.startColumn) {
      return false;
    }
    return true;
  }
  /**
   * A function that compares ranges, useful for sorting ranges
   * It will first compare ranges on the startPosition and then on the endPosition
   */
  static compareRangesUsingStarts(a, b) {
    if (a && b) {
      const aStartLineNumber = a.startLineNumber | 0;
      const bStartLineNumber = b.startLineNumber | 0;
      if (aStartLineNumber === bStartLineNumber) {
        const aStartColumn = a.startColumn | 0;
        const bStartColumn = b.startColumn | 0;
        if (aStartColumn === bStartColumn) {
          const aEndLineNumber = a.endLineNumber | 0;
          const bEndLineNumber = b.endLineNumber | 0;
          if (aEndLineNumber === bEndLineNumber) {
            const aEndColumn = a.endColumn | 0;
            const bEndColumn = b.endColumn | 0;
            return aEndColumn - bEndColumn;
          }
          return aEndLineNumber - bEndLineNumber;
        }
        return aStartColumn - bStartColumn;
      }
      return aStartLineNumber - bStartLineNumber;
    }
    const aExists = a ? 1 : 0;
    const bExists = b ? 1 : 0;
    return aExists - bExists;
  }
  /**
   * A function that compares ranges, useful for sorting ranges
   * It will first compare ranges on the endPosition and then on the startPosition
   */
  static compareRangesUsingEnds(a, b) {
    if (a.endLineNumber === b.endLineNumber) {
      if (a.endColumn === b.endColumn) {
        if (a.startLineNumber === b.startLineNumber) {
          return a.startColumn - b.startColumn;
        }
        return a.startLineNumber - b.startLineNumber;
      }
      return a.endColumn - b.endColumn;
    }
    return a.endLineNumber - b.endLineNumber;
  }
  /**
   * Test if the range spans multiple lines.
   */
  static spansMultipleLines(range) {
    return range.endLineNumber > range.startLineNumber;
  }
  toJSON() {
    return this;
  }
};

// out-build/vs/editor/common/core/selection.js
var SelectionDirection;
(function(SelectionDirection3) {
  SelectionDirection3[SelectionDirection3["LTR"] = 0] = "LTR";
  SelectionDirection3[SelectionDirection3["RTL"] = 1] = "RTL";
})(SelectionDirection || (SelectionDirection = {}));
var $_D = class _$_D extends $9C {
  constructor(selectionStartLineNumber, selectionStartColumn, positionLineNumber, positionColumn) {
    super(selectionStartLineNumber, selectionStartColumn, positionLineNumber, positionColumn);
    this.selectionStartLineNumber = selectionStartLineNumber;
    this.selectionStartColumn = selectionStartColumn;
    this.positionLineNumber = positionLineNumber;
    this.positionColumn = positionColumn;
  }
  /**
   * Transform to a human-readable representation.
   */
  toString() {
    return "[" + this.selectionStartLineNumber + "," + this.selectionStartColumn + " -> " + this.positionLineNumber + "," + this.positionColumn + "]";
  }
  /**
   * Test if equals other selection.
   */
  equalsSelection(other) {
    return _$_D.selectionsEqual(this, other);
  }
  /**
   * Test if the two selections are equal.
   */
  static selectionsEqual(a, b) {
    return a.selectionStartLineNumber === b.selectionStartLineNumber && a.selectionStartColumn === b.selectionStartColumn && a.positionLineNumber === b.positionLineNumber && a.positionColumn === b.positionColumn;
  }
  /**
   * Get directions (LTR or RTL).
   */
  getDirection() {
    if (this.selectionStartLineNumber === this.startLineNumber && this.selectionStartColumn === this.startColumn) {
      return 0;
    }
    return 1;
  }
  /**
   * Create a new selection with a different `positionLineNumber` and `positionColumn`.
   */
  setEndPosition(endLineNumber, endColumn) {
    if (this.getDirection() === 0) {
      return new _$_D(this.startLineNumber, this.startColumn, endLineNumber, endColumn);
    }
    return new _$_D(endLineNumber, endColumn, this.startLineNumber, this.startColumn);
  }
  /**
   * Get the position at `positionLineNumber` and `positionColumn`.
   */
  getPosition() {
    return new $8C(this.positionLineNumber, this.positionColumn);
  }
  /**
   * Get the position at the start of the selection.
  */
  getSelectionStart() {
    return new $8C(this.selectionStartLineNumber, this.selectionStartColumn);
  }
  /**
   * Create a new selection with a different `selectionStartLineNumber` and `selectionStartColumn`.
   */
  setStartPosition(startLineNumber, startColumn) {
    if (this.getDirection() === 0) {
      return new _$_D(startLineNumber, startColumn, this.endLineNumber, this.endColumn);
    }
    return new _$_D(this.endLineNumber, this.endColumn, startLineNumber, startColumn);
  }
  // ----
  /**
   * Create a `Selection` from one or two positions
   */
  static fromPositions(start, end = start) {
    return new _$_D(start.lineNumber, start.column, end.lineNumber, end.column);
  }
  /**
   * Creates a `Selection` from a range, given a direction.
   */
  static fromRange(range, direction) {
    if (direction === 0) {
      return new _$_D(range.startLineNumber, range.startColumn, range.endLineNumber, range.endColumn);
    } else {
      return new _$_D(range.endLineNumber, range.endColumn, range.startLineNumber, range.startColumn);
    }
  }
  /**
   * Create a `Selection` from an `ISelection`.
   */
  static liftSelection(sel) {
    return new _$_D(sel.selectionStartLineNumber, sel.selectionStartColumn, sel.positionLineNumber, sel.positionColumn);
  }
  /**
   * `a` equals `b`.
   */
  static selectionsArrEqual(a, b) {
    if (a && !b || !a && b) {
      return false;
    }
    if (!a && !b) {
      return true;
    }
    if (a.length !== b.length) {
      return false;
    }
    for (let i2 = 0, len = a.length; i2 < len; i2++) {
      if (!this.selectionsEqual(a[i2], b[i2])) {
        return false;
      }
    }
    return true;
  }
  /**
   * Test if `obj` is an `ISelection`.
   */
  static isISelection(obj) {
    return obj && typeof obj.selectionStartLineNumber === "number" && typeof obj.selectionStartColumn === "number" && typeof obj.positionLineNumber === "number" && typeof obj.positionColumn === "number";
  }
  /**
   * Create with a direction.
   */
  static createWithDirection(startLineNumber, startColumn, endLineNumber, endColumn, direction) {
    if (direction === 0) {
      return new _$_D(startLineNumber, startColumn, endLineNumber, endColumn);
    }
    return new _$_D(endLineNumber, endColumn, startLineNumber, startColumn);
  }
};

// out-build/vs/editor/common/languages/supports.js
function $2E(context, offset) {
  const tokenCount = context.getCount();
  const tokenIndex = context.findTokenIndexAtOffset(offset);
  const desiredLanguageId = context.getLanguageId(tokenIndex);
  let lastTokenIndex = tokenIndex;
  while (lastTokenIndex + 1 < tokenCount && context.getLanguageId(lastTokenIndex + 1) === desiredLanguageId) {
    lastTokenIndex++;
  }
  let firstTokenIndex = tokenIndex;
  while (firstTokenIndex > 0 && context.getLanguageId(firstTokenIndex - 1) === desiredLanguageId) {
    firstTokenIndex--;
  }
  return new $3E(context, desiredLanguageId, firstTokenIndex, lastTokenIndex + 1, context.getStartOffset(firstTokenIndex), context.getEndOffset(lastTokenIndex));
}
var $3E = class {
  constructor(actual, languageId, firstTokenIndex, lastTokenIndex, firstCharOffset, lastCharOffset) {
    this._scopedLineTokensBrand = void 0;
    this.a = actual;
    this.languageId = languageId;
    this.b = firstTokenIndex;
    this.c = lastTokenIndex;
    this.firstCharOffset = firstCharOffset;
    this.d = lastCharOffset;
    this.languageIdCodec = actual.languageIdCodec;
  }
  getLineContent() {
    const actualLineContent = this.a.getLineContent();
    return actualLineContent.substring(this.firstCharOffset, this.d);
  }
  getLineLength() {
    return this.d - this.firstCharOffset;
  }
  getActualLineContentBefore(offset) {
    const actualLineContent = this.a.getLineContent();
    return actualLineContent.substring(0, this.firstCharOffset + offset);
  }
  getTokenCount() {
    return this.c - this.b;
  }
  findTokenIndexAtOffset(offset) {
    return this.a.findTokenIndexAtOffset(offset + this.firstCharOffset) - this.b;
  }
  getStandardTokenType(tokenIndex) {
    return this.a.getStandardTokenType(tokenIndex + this.b);
  }
  toIViewLineTokens() {
    return this.a.sliceAndInflate(this.firstCharOffset, this.d, 0);
  }
};
var IgnoreBracketsInTokens;
(function(IgnoreBracketsInTokens2) {
  IgnoreBracketsInTokens2[IgnoreBracketsInTokens2["value"] = 3] = "value";
})(IgnoreBracketsInTokens || (IgnoreBracketsInTokens = {}));
function $4E(standardTokenType) {
  return (standardTokenType & 3) !== 0;
}

// out-build/vs/editor/common/core/cursorColumns.js
var $cF = class _$cF {
  static a(codePoint, visibleColumn, tabSize) {
    if (codePoint === 9) {
      return _$cF.nextRenderTabStop(visibleColumn, tabSize);
    }
    if ($gg(codePoint) || $hg(codePoint)) {
      return visibleColumn + 2;
    }
    return visibleColumn + 1;
  }
  /**
   * Returns a visible column from a column.
   * @see {@link $cF}
   */
  static visibleColumnFromColumn(lineContent, column, tabSize) {
    const textLen = Math.min(column - 1, lineContent.length);
    const text2 = lineContent.substring(0, textLen);
    const iterator = new $0f(text2);
    let result = 0;
    while (!iterator.eol()) {
      const codePoint = $8f(text2, textLen, iterator.offset);
      iterator.nextGraphemeLength();
      result = this.a(codePoint, result, tabSize);
    }
    return result;
  }
  /**
   * Returns the value to display as "Col" in the status bar.
   * @see {@link $cF}
   */
  static toStatusbarColumn(lineContent, column, tabSize) {
    const text2 = lineContent.substring(0, Math.min(column - 1, lineContent.length));
    const iterator = new $9f(text2);
    let result = 0;
    while (!iterator.eol()) {
      const codePoint = iterator.nextCodePoint();
      if (codePoint === 9) {
        result = _$cF.nextRenderTabStop(result, tabSize);
      } else {
        result = result + 1;
      }
    }
    return result + 1;
  }
  /**
   * Returns a column from a visible column.
   * @see {@link $cF}
   */
  static columnFromVisibleColumn(lineContent, visibleColumn, tabSize) {
    if (visibleColumn <= 0) {
      return 1;
    }
    const lineContentLength = lineContent.length;
    const iterator = new $0f(lineContent);
    let beforeVisibleColumn = 0;
    let beforeColumn = 1;
    while (!iterator.eol()) {
      const codePoint = $8f(lineContent, lineContentLength, iterator.offset);
      iterator.nextGraphemeLength();
      const afterVisibleColumn = this.a(codePoint, beforeVisibleColumn, tabSize);
      const afterColumn = iterator.offset + 1;
      if (afterVisibleColumn >= visibleColumn) {
        const beforeDelta = visibleColumn - beforeVisibleColumn;
        const afterDelta = afterVisibleColumn - visibleColumn;
        if (afterDelta < beforeDelta) {
          return afterColumn;
        } else {
          return beforeColumn;
        }
      }
      beforeVisibleColumn = afterVisibleColumn;
      beforeColumn = afterColumn;
    }
    return lineContentLength + 1;
  }
  /**
   * ATTENTION: This works with 0-based columns (as opposed to the regular 1-based columns)
   * @see {@link $cF}
   */
  static nextRenderTabStop(visibleColumn, tabSize) {
    return visibleColumn + tabSize - visibleColumn % tabSize;
  }
  /**
   * ATTENTION: This works with 0-based columns (as opposed to the regular 1-based columns)
   * @see {@link $cF}
   */
  static nextIndentTabStop(visibleColumn, indentSize) {
    return _$cF.nextRenderTabStop(visibleColumn, indentSize);
  }
  /**
   * ATTENTION: This works with 0-based columns (as opposed to the regular 1-based columns)
   * @see {@link $cF}
   */
  static prevRenderTabStop(column, tabSize) {
    return Math.max(0, column - 1 - (column - 1) % tabSize);
  }
  /**
   * ATTENTION: This works with 0-based columns (as opposed to the regular 1-based columns)
   * @see {@link $cF}
   */
  static prevIndentTabStop(column, indentSize) {
    return _$cF.prevRenderTabStop(column, indentSize);
  }
};

// out-build/vs/editor/common/core/indentation.js
function _normalizeIndentationFromWhitespace(str, indentSize, insertSpaces) {
  let spacesCnt = 0;
  for (let i2 = 0; i2 < str.length; i2++) {
    if (str.charAt(i2) === "	") {
      spacesCnt = $cF.nextIndentTabStop(spacesCnt, indentSize);
    } else {
      spacesCnt++;
    }
  }
  let result = "";
  if (!insertSpaces) {
    const tabsCnt = Math.floor(spacesCnt / indentSize);
    spacesCnt = spacesCnt % indentSize;
    for (let i2 = 0; i2 < tabsCnt; i2++) {
      result += "	";
    }
  }
  for (let i2 = 0; i2 < spacesCnt; i2++) {
    result += " ";
  }
  return result;
}
function $BG(str, indentSize, insertSpaces) {
  let firstNonWhitespaceIndex = $Of(str);
  if (firstNonWhitespaceIndex === -1) {
    firstNonWhitespaceIndex = str.length;
  }
  return _normalizeIndentationFromWhitespace(str.substring(0, firstNonWhitespaceIndex), indentSize, insertSpaces) + str.substring(firstNonWhitespaceIndex);
}

// out-build/vs/editor/common/inputMode.js
var InputModeImpl = class {
  constructor() {
    this.a = "insert";
    this.b = new $ze();
    this.onDidChangeInputMode = this.b.event;
  }
  getInputMode() {
    return this.a;
  }
  setInputMode(inputMode) {
    this.a = inputMode;
    this.b.fire(this.a);
  }
};
var $04 = new InputModeImpl();

// out-build/vs/editor/common/cursorCommon.js
var EditOperationType;
(function(EditOperationType2) {
  EditOperationType2[EditOperationType2["Other"] = 0] = "Other";
  EditOperationType2[EditOperationType2["DeletingLeft"] = 2] = "DeletingLeft";
  EditOperationType2[EditOperationType2["DeletingRight"] = 3] = "DeletingRight";
  EditOperationType2[EditOperationType2["TypingOther"] = 4] = "TypingOther";
  EditOperationType2[EditOperationType2["TypingFirstSpace"] = 5] = "TypingFirstSpace";
  EditOperationType2[EditOperationType2["TypingConsecutiveSpace"] = 6] = "TypingConsecutiveSpace";
})(EditOperationType || (EditOperationType = {}));
var autoCloseAlways = () => true;
var autoCloseNever = () => false;
var autoCloseBeforeWhitespace = (chr) => chr === " " || chr === "	";
var $d5 = class {
  static shouldRecreate(e) {
    return e.hasChanged(
      151
      /* EditorOption.layoutInfo */
    ) || e.hasChanged(
      136
      /* EditorOption.wordSeparators */
    ) || e.hasChanged(
      38
      /* EditorOption.emptySelectionClipboard */
    ) || e.hasChanged(
      78
      /* EditorOption.multiCursorMergeOverlapping */
    ) || e.hasChanged(
      80
      /* EditorOption.multiCursorPaste */
    ) || e.hasChanged(
      81
      /* EditorOption.multiCursorLimit */
    ) || e.hasChanged(
      6
      /* EditorOption.autoClosingBrackets */
    ) || e.hasChanged(
      7
      /* EditorOption.autoClosingComments */
    ) || e.hasChanged(
      11
      /* EditorOption.autoClosingQuotes */
    ) || e.hasChanged(
      9
      /* EditorOption.autoClosingDelete */
    ) || e.hasChanged(
      10
      /* EditorOption.autoClosingOvertype */
    ) || e.hasChanged(
      14
      /* EditorOption.autoSurround */
    ) || e.hasChanged(
      133
      /* EditorOption.useTabStops */
    ) || e.hasChanged(
      52
      /* EditorOption.fontInfo */
    ) || e.hasChanged(
      96
      /* EditorOption.readOnly */
    ) || e.hasChanged(
      135
      /* EditorOption.wordSegmenterLocales */
    ) || e.hasChanged(
      85
      /* EditorOption.overtypeOnPaste */
    );
  }
  constructor(languageId, modelOptions, configuration2, languageConfigurationService) {
    this.languageConfigurationService = languageConfigurationService;
    this._cursorMoveConfigurationBrand = void 0;
    this.a = languageId;
    const options3 = configuration2.options;
    const layoutInfo = options3.get(
      151
      /* EditorOption.layoutInfo */
    );
    const fontInfo = options3.get(
      52
      /* EditorOption.fontInfo */
    );
    this.readOnly = options3.get(
      96
      /* EditorOption.readOnly */
    );
    this.tabSize = modelOptions.tabSize;
    this.indentSize = modelOptions.indentSize;
    this.insertSpaces = modelOptions.insertSpaces;
    this.stickyTabStops = options3.get(
      121
      /* EditorOption.stickyTabStops */
    );
    this.lineHeight = fontInfo.lineHeight;
    this.typicalHalfwidthCharacterWidth = fontInfo.typicalHalfwidthCharacterWidth;
    this.pageSize = Math.max(1, Math.floor(layoutInfo.height / this.lineHeight) - 2);
    this.useTabStops = options3.get(
      133
      /* EditorOption.useTabStops */
    );
    this.wordSeparators = options3.get(
      136
      /* EditorOption.wordSeparators */
    );
    this.emptySelectionClipboard = options3.get(
      38
      /* EditorOption.emptySelectionClipboard */
    );
    this.copyWithSyntaxHighlighting = options3.get(
      25
      /* EditorOption.copyWithSyntaxHighlighting */
    );
    this.multiCursorMergeOverlapping = options3.get(
      78
      /* EditorOption.multiCursorMergeOverlapping */
    );
    this.multiCursorPaste = options3.get(
      80
      /* EditorOption.multiCursorPaste */
    );
    this.multiCursorLimit = options3.get(
      81
      /* EditorOption.multiCursorLimit */
    );
    this.autoClosingBrackets = options3.get(
      6
      /* EditorOption.autoClosingBrackets */
    );
    this.autoClosingComments = options3.get(
      7
      /* EditorOption.autoClosingComments */
    );
    this.autoClosingQuotes = options3.get(
      11
      /* EditorOption.autoClosingQuotes */
    );
    this.autoClosingDelete = options3.get(
      9
      /* EditorOption.autoClosingDelete */
    );
    this.autoClosingOvertype = options3.get(
      10
      /* EditorOption.autoClosingOvertype */
    );
    this.autoSurround = options3.get(
      14
      /* EditorOption.autoSurround */
    );
    this.autoIndent = options3.get(
      12
      /* EditorOption.autoIndent */
    );
    this.wordSegmenterLocales = options3.get(
      135
      /* EditorOption.wordSegmenterLocales */
    );
    this.overtypeOnPaste = options3.get(
      85
      /* EditorOption.overtypeOnPaste */
    );
    this.surroundingPairs = {};
    this.b = null;
    this.shouldAutoCloseBefore = {
      quote: this.d(languageId, this.autoClosingQuotes, true),
      comment: this.d(languageId, this.autoClosingComments, false),
      bracket: this.d(languageId, this.autoClosingBrackets, false)
    };
    this.autoClosingPairs = this.languageConfigurationService.getLanguageConfiguration(languageId).getAutoClosingPairs();
    const surroundingPairs = this.languageConfigurationService.getLanguageConfiguration(languageId).getSurroundingPairs();
    if (surroundingPairs) {
      for (const pair of surroundingPairs) {
        this.surroundingPairs[pair.open] = pair.close;
      }
    }
    const commentsConfiguration = this.languageConfigurationService.getLanguageConfiguration(languageId).comments;
    this.blockCommentStartToken = commentsConfiguration?.blockCommentStartToken ?? null;
  }
  get electricChars() {
    if (!this.b) {
      this.b = {};
      const electricChars = this.languageConfigurationService.getLanguageConfiguration(this.a).electricCharacter?.getElectricCharacters();
      if (electricChars) {
        for (const char of electricChars) {
          this.b[char] = true;
        }
      }
    }
    return this.b;
  }
  get inputMode() {
    return $04.getInputMode();
  }
  /**
   * Should return opening bracket type to match indentation with
   */
  onElectricCharacter(character, context, column) {
    const scopedLineTokens = $2E(context, column - 1);
    const electricCharacterSupport = this.languageConfigurationService.getLanguageConfiguration(scopedLineTokens.languageId).electricCharacter;
    if (!electricCharacterSupport) {
      return null;
    }
    return electricCharacterSupport.onElectricCharacter(character, scopedLineTokens, column - scopedLineTokens.firstCharOffset);
  }
  normalizeIndentation(str) {
    return $BG(str, this.indentSize, this.insertSpaces);
  }
  d(languageId, autoCloseConfig, forQuotes) {
    switch (autoCloseConfig) {
      case "beforeWhitespace":
        return autoCloseBeforeWhitespace;
      case "languageDefined":
        return this.f(languageId, forQuotes);
      case "always":
        return autoCloseAlways;
      case "never":
        return autoCloseNever;
    }
  }
  f(languageId, forQuotes) {
    const autoCloseBeforeSet = this.languageConfigurationService.getLanguageConfiguration(languageId).getAutoCloseBeforeSet(forQuotes);
    return (c) => autoCloseBeforeSet.indexOf(c) !== -1;
  }
  /**
   * Returns a visible column from a column.
   * @see {@link $cF}
   */
  visibleColumnFromColumn(model, position) {
    return $cF.visibleColumnFromColumn(model.getLineContent(position.lineNumber), position.column, this.tabSize);
  }
  /**
   * Returns a visible column from a column.
   * @see {@link $cF}
   */
  columnFromVisibleColumn(model, lineNumber, visibleColumn) {
    const result = $cF.columnFromVisibleColumn(model.getLineContent(lineNumber), visibleColumn, this.tabSize);
    const minColumn = model.getLineMinColumn(lineNumber);
    if (result < minColumn) {
      return minColumn;
    }
    const maxColumn = model.getLineMaxColumn(lineNumber);
    if (result > maxColumn) {
      return maxColumn;
    }
    return result;
  }
};
var $e5 = class _$e5 {
  static fromModelState(modelState) {
    return new $f5(modelState);
  }
  static fromViewState(viewState) {
    return new $g5(viewState);
  }
  static fromModelSelection(modelSelection) {
    const selection = $_D.liftSelection(modelSelection);
    const modelState = new $h5($9C.fromPositions(selection.getSelectionStart()), 0, 0, selection.getPosition(), 0);
    return _$e5.fromModelState(modelState);
  }
  static fromModelSelections(modelSelections) {
    const states = [];
    for (let i2 = 0, len = modelSelections.length; i2 < len; i2++) {
      states[i2] = this.fromModelSelection(modelSelections[i2]);
    }
    return states;
  }
  constructor(modelState, viewState) {
    this._cursorStateBrand = void 0;
    this.modelState = modelState;
    this.viewState = viewState;
  }
  equals(other) {
    return this.viewState.equals(other.viewState) && this.modelState.equals(other.modelState);
  }
};
var $f5 = class {
  constructor(modelState) {
    this.modelState = modelState;
    this.viewState = null;
  }
};
var $g5 = class {
  constructor(viewState) {
    this.modelState = null;
    this.viewState = viewState;
  }
};
var SelectionStartKind;
(function(SelectionStartKind2) {
  SelectionStartKind2[SelectionStartKind2["Simple"] = 0] = "Simple";
  SelectionStartKind2[SelectionStartKind2["Word"] = 1] = "Word";
  SelectionStartKind2[SelectionStartKind2["Line"] = 2] = "Line";
})(SelectionStartKind || (SelectionStartKind = {}));
var $h5 = class _$h5 {
  constructor(selectionStart, selectionStartKind, selectionStartLeftoverVisibleColumns, position, leftoverVisibleColumns) {
    this.selectionStart = selectionStart;
    this.selectionStartKind = selectionStartKind;
    this.selectionStartLeftoverVisibleColumns = selectionStartLeftoverVisibleColumns;
    this.position = position;
    this.leftoverVisibleColumns = leftoverVisibleColumns;
    this._singleCursorStateBrand = void 0;
    this.selection = _$h5.a(this.selectionStart, this.position);
  }
  equals(other) {
    return this.selectionStartLeftoverVisibleColumns === other.selectionStartLeftoverVisibleColumns && this.leftoverVisibleColumns === other.leftoverVisibleColumns && this.selectionStartKind === other.selectionStartKind && this.position.equals(other.position) && this.selectionStart.equalsRange(other.selectionStart);
  }
  hasSelection() {
    return !this.selection.isEmpty() || !this.selectionStart.isEmpty();
  }
  move(inSelectionMode, lineNumber, column, leftoverVisibleColumns) {
    if (inSelectionMode) {
      return new _$h5(this.selectionStart, this.selectionStartKind, this.selectionStartLeftoverVisibleColumns, new $8C(lineNumber, column), leftoverVisibleColumns);
    } else {
      return new _$h5(new $9C(lineNumber, column, lineNumber, column), 0, leftoverVisibleColumns, new $8C(lineNumber, column), leftoverVisibleColumns);
    }
  }
  static a(selectionStart, position) {
    if (selectionStart.isEmpty() || !position.isBeforeOrEqual(selectionStart.getStartPosition())) {
      return $_D.fromPositions(selectionStart.getStartPosition(), position);
    } else {
      return $_D.fromPositions(selectionStart.getEndPosition(), position);
    }
  }
};
var $i5 = class {
  constructor(type, commands2, opts) {
    this._editOperationResultBrand = void 0;
    this.type = type;
    this.commands = commands2;
    this.shouldPushStackElementBefore = opts.shouldPushStackElementBefore;
    this.shouldPushStackElementAfter = opts.shouldPushStackElementAfter;
  }
};
function $j5(ch) {
  return ch === "'" || ch === '"' || ch === "`";
}

// out-build/vs/editor/common/cursor/cursorColumnSelection.js
var $a6 = class _$a6 {
  static columnSelect(config, model, fromLineNumber, fromVisibleColumn, toLineNumber, toVisibleColumn) {
    const lineCount = Math.abs(toLineNumber - fromLineNumber) + 1;
    const reversed = fromLineNumber > toLineNumber;
    const isRTL = fromVisibleColumn > toVisibleColumn;
    const isLTR = fromVisibleColumn < toVisibleColumn;
    const result = [];
    for (let i2 = 0; i2 < lineCount; i2++) {
      const lineNumber = fromLineNumber + (reversed ? -i2 : i2);
      const startColumn = config.columnFromVisibleColumn(model, lineNumber, fromVisibleColumn);
      const endColumn = config.columnFromVisibleColumn(model, lineNumber, toVisibleColumn);
      const visibleStartColumn = config.visibleColumnFromColumn(model, new $8C(lineNumber, startColumn));
      const visibleEndColumn = config.visibleColumnFromColumn(model, new $8C(lineNumber, endColumn));
      if (isLTR) {
        if (visibleStartColumn > toVisibleColumn) {
          continue;
        }
        if (visibleEndColumn < fromVisibleColumn) {
          continue;
        }
      }
      if (isRTL) {
        if (visibleEndColumn > fromVisibleColumn) {
          continue;
        }
        if (visibleStartColumn < toVisibleColumn) {
          continue;
        }
      }
      result.push(new $h5(new $9C(lineNumber, startColumn, lineNumber, startColumn), 0, 0, new $8C(lineNumber, endColumn), 0));
    }
    if (result.length === 0) {
      for (let i2 = 0; i2 < lineCount; i2++) {
        const lineNumber = fromLineNumber + (reversed ? -i2 : i2);
        const maxColumn = model.getLineMaxColumn(lineNumber);
        result.push(new $h5(new $9C(lineNumber, maxColumn, lineNumber, maxColumn), 0, 0, new $8C(lineNumber, maxColumn), 0));
      }
    }
    return {
      viewStates: result,
      reversed,
      fromLineNumber,
      fromVisualColumn: fromVisibleColumn,
      toLineNumber,
      toVisualColumn: toVisibleColumn
    };
  }
  static columnSelectLeft(config, model, prevColumnSelectData) {
    let toViewVisualColumn = prevColumnSelectData.toViewVisualColumn;
    if (toViewVisualColumn > 0) {
      toViewVisualColumn--;
    }
    return _$a6.columnSelect(config, model, prevColumnSelectData.fromViewLineNumber, prevColumnSelectData.fromViewVisualColumn, prevColumnSelectData.toViewLineNumber, toViewVisualColumn);
  }
  static columnSelectRight(config, model, prevColumnSelectData) {
    let maxVisualViewColumn = 0;
    const minViewLineNumber = Math.min(prevColumnSelectData.fromViewLineNumber, prevColumnSelectData.toViewLineNumber);
    const maxViewLineNumber = Math.max(prevColumnSelectData.fromViewLineNumber, prevColumnSelectData.toViewLineNumber);
    for (let lineNumber = minViewLineNumber; lineNumber <= maxViewLineNumber; lineNumber++) {
      const lineMaxViewColumn = model.getLineMaxColumn(lineNumber);
      const lineMaxVisualViewColumn = config.visibleColumnFromColumn(model, new $8C(lineNumber, lineMaxViewColumn));
      maxVisualViewColumn = Math.max(maxVisualViewColumn, lineMaxVisualViewColumn);
    }
    let toViewVisualColumn = prevColumnSelectData.toViewVisualColumn;
    if (toViewVisualColumn < maxVisualViewColumn) {
      toViewVisualColumn++;
    }
    return this.columnSelect(config, model, prevColumnSelectData.fromViewLineNumber, prevColumnSelectData.fromViewVisualColumn, prevColumnSelectData.toViewLineNumber, toViewVisualColumn);
  }
  static columnSelectUp(config, model, prevColumnSelectData, isPaged) {
    const linesCount = isPaged ? config.pageSize : 1;
    const toViewLineNumber = Math.max(1, prevColumnSelectData.toViewLineNumber - linesCount);
    return this.columnSelect(config, model, prevColumnSelectData.fromViewLineNumber, prevColumnSelectData.fromViewVisualColumn, toViewLineNumber, prevColumnSelectData.toViewVisualColumn);
  }
  static columnSelectDown(config, model, prevColumnSelectData, isPaged) {
    const linesCount = isPaged ? config.pageSize : 1;
    const toViewLineNumber = Math.min(model.getLineCount(), prevColumnSelectData.toViewLineNumber + linesCount);
    return this.columnSelect(config, model, prevColumnSelectData.fromViewLineNumber, prevColumnSelectData.fromViewVisualColumn, toViewLineNumber, prevColumnSelectData.toViewVisualColumn);
  }
};

// out-build/vs/editor/common/commands/replaceCommand.js
var $b6 = class {
  constructor(range, text2, insertsAutoWhitespace = false) {
    this.a = range;
    this.b = text2;
    this.insertsAutoWhitespace = insertsAutoWhitespace;
  }
  getEditOperations(model, builder) {
    builder.addTrackedEditOperation(this.a, this.b);
  }
  computeCursorState(model, helper) {
    const inverseEditOperations = helper.getInverseEditOperations();
    const srcRange = inverseEditOperations[0].range;
    return $_D.fromPositions(srcRange.getEndPosition());
  }
};
var $c6 = class {
  constructor(range, text2, insertsAutoWhitespace = false) {
    this.a = range;
    this.b = text2;
    this.insertsAutoWhitespace = insertsAutoWhitespace;
  }
  getEditOperations(model, builder) {
    const intialStartPosition = this.a.getStartPosition();
    const initialEndPosition = this.a.getEndPosition();
    const initialEndLineNumber = initialEndPosition.lineNumber;
    const offsetDelta = this.b.length + (this.a.isEmpty() ? 0 : -1);
    let endPosition = addPositiveOffsetToModelPosition(model, initialEndPosition, offsetDelta);
    if (endPosition.lineNumber > initialEndLineNumber) {
      endPosition = new $8C(initialEndLineNumber, model.getLineMaxColumn(initialEndLineNumber));
    }
    const replaceRange = $9C.fromPositions(intialStartPosition, endPosition);
    builder.addTrackedEditOperation(replaceRange, this.b);
  }
  computeCursorState(model, helper) {
    const inverseEditOperations = helper.getInverseEditOperations();
    const srcRange = inverseEditOperations[0].range;
    return $_D.fromPositions(srcRange.getEndPosition());
  }
};
var $d6 = class {
  constructor(range, text2) {
    this.a = range;
    this.b = text2;
  }
  getEditOperations(model, builder) {
    builder.addTrackedEditOperation(this.a, this.b);
  }
  computeCursorState(model, helper) {
    const inverseEditOperations = helper.getInverseEditOperations();
    const srcRange = inverseEditOperations[0].range;
    return $_D.fromRange(
      srcRange,
      0
      /* SelectionDirection.LTR */
    );
  }
};
var $e6 = class {
  constructor(range, text2, insertsAutoWhitespace = false) {
    this.a = range;
    this.b = text2;
    this.insertsAutoWhitespace = insertsAutoWhitespace;
  }
  getEditOperations(model, builder) {
    builder.addTrackedEditOperation(this.a, this.b);
  }
  computeCursorState(model, helper) {
    const inverseEditOperations = helper.getInverseEditOperations();
    const srcRange = inverseEditOperations[0].range;
    return $_D.fromPositions(srcRange.getStartPosition());
  }
};
var $f6 = class {
  constructor(range, text2, lineNumberDeltaOffset, columnDeltaOffset, insertsAutoWhitespace = false) {
    this.a = range;
    this.b = text2;
    this.c = columnDeltaOffset;
    this.d = lineNumberDeltaOffset;
    this.insertsAutoWhitespace = insertsAutoWhitespace;
  }
  getEditOperations(model, builder) {
    builder.addTrackedEditOperation(this.a, this.b);
  }
  computeCursorState(model, helper) {
    const inverseEditOperations = helper.getInverseEditOperations();
    const srcRange = inverseEditOperations[0].range;
    return $_D.fromPositions(srcRange.getEndPosition().delta(this.d, this.c));
  }
};
var $g6 = class {
  constructor(range) {
    this.a = range;
  }
  getEditOperations(model, builder) {
    const text2 = model.getValueInRange(this.a);
    const initialEndPosition = this.a.getEndPosition();
    const initialEndLineNumber = initialEndPosition.lineNumber;
    let endPosition = addPositiveOffsetToModelPosition(model, initialEndPosition, text2.length);
    if (endPosition.lineNumber > initialEndLineNumber) {
      endPosition = new $8C(initialEndLineNumber, model.getLineMaxColumn(initialEndLineNumber));
    }
    const replaceRange = $9C.fromPositions(initialEndPosition, endPosition);
    builder.addTrackedEditOperation(replaceRange, "");
  }
  computeCursorState(model, helper) {
    const inverseEditOperations = helper.getInverseEditOperations();
    const srcRange = inverseEditOperations[0].range;
    return $_D.fromPositions(srcRange.getEndPosition());
  }
};
var $h6 = class {
  constructor(editRange, text2, initialSelection, forceMoveMarkers = false) {
    this.a = editRange;
    this.b = text2;
    this.c = initialSelection;
    this.d = forceMoveMarkers;
    this.e = null;
  }
  getEditOperations(model, builder) {
    builder.addTrackedEditOperation(this.a, this.b, this.d);
    this.e = builder.trackSelection(this.c);
  }
  computeCursorState(model, helper) {
    return helper.getTrackedSelection(this.e);
  }
};
function addPositiveOffsetToModelPosition(model, position, offset) {
  if (offset < 0) {
    throw new Error("Unexpected negative delta");
  }
  const lineCount = model.getLineCount();
  let endPosition = new $8C(lineCount, model.getLineMaxColumn(lineCount));
  for (let lineNumber = position.lineNumber; lineNumber <= lineCount; lineNumber++) {
    if (lineNumber === position.lineNumber) {
      const futureOffset = offset - model.getLineMaxColumn(position.lineNumber) + position.column;
      if (futureOffset <= 0) {
        endPosition = new $8C(position.lineNumber, position.column + offset);
        break;
      }
      offset = futureOffset;
    } else {
      const futureOffset = offset - model.getLineMaxColumn(lineNumber);
      if (futureOffset <= 0) {
        endPosition = new $8C(lineNumber, offset);
        break;
      }
      offset = futureOffset;
    }
  }
  return endPosition;
}

// out-build/vs/editor/common/cursor/cursorAtomicMoveOperations.js
var Direction;
(function(Direction4) {
  Direction4[Direction4["Left"] = 0] = "Left";
  Direction4[Direction4["Right"] = 1] = "Right";
  Direction4[Direction4["Nearest"] = 2] = "Nearest";
})(Direction || (Direction = {}));
var $i6 = class _$i6 {
  /**
   * Get the visible column at the position. If we get to a non-whitespace character first
   * or past the end of string then return -1.
   *
   * **Note** `position` and the return value are 0-based.
   */
  static whitespaceVisibleColumn(lineContent, position, tabSize) {
    const lineLength = lineContent.length;
    let visibleColumn = 0;
    let prevTabStopPosition = -1;
    let prevTabStopVisibleColumn = -1;
    for (let i2 = 0; i2 < lineLength; i2++) {
      if (i2 === position) {
        return [prevTabStopPosition, prevTabStopVisibleColumn, visibleColumn];
      }
      if (visibleColumn % tabSize === 0) {
        prevTabStopPosition = i2;
        prevTabStopVisibleColumn = visibleColumn;
      }
      const chCode = lineContent.charCodeAt(i2);
      switch (chCode) {
        case 32:
          visibleColumn += 1;
          break;
        case 9:
          visibleColumn = $cF.nextRenderTabStop(visibleColumn, tabSize);
          break;
        default:
          return [-1, -1, -1];
      }
    }
    if (position === lineLength) {
      return [prevTabStopPosition, prevTabStopVisibleColumn, visibleColumn];
    }
    return [-1, -1, -1];
  }
  /**
   * Return the position that should result from a move left, right or to the
   * nearest tab, if atomic tabs are enabled. Left and right are used for the
   * arrow key movements, nearest is used for mouse selection. It returns
   * -1 if atomic tabs are not relevant and you should fall back to normal
   * behaviour.
   *
   * **Note**: `position` and the return value are 0-based.
   */
  static atomicPosition(lineContent, position, tabSize, direction) {
    const lineLength = lineContent.length;
    const [prevTabStopPosition, prevTabStopVisibleColumn, visibleColumn] = _$i6.whitespaceVisibleColumn(lineContent, position, tabSize);
    if (visibleColumn === -1) {
      return -1;
    }
    let left;
    switch (direction) {
      case 0:
        left = true;
        break;
      case 1:
        left = false;
        break;
      case 2:
        if (visibleColumn % tabSize === 0) {
          return position;
        }
        left = visibleColumn % tabSize <= tabSize / 2;
        break;
    }
    if (left) {
      if (prevTabStopPosition === -1) {
        return -1;
      }
      let currentVisibleColumn2 = prevTabStopVisibleColumn;
      for (let i2 = prevTabStopPosition; i2 < lineLength; ++i2) {
        if (currentVisibleColumn2 === prevTabStopVisibleColumn + tabSize) {
          return prevTabStopPosition;
        }
        const chCode = lineContent.charCodeAt(i2);
        switch (chCode) {
          case 32:
            currentVisibleColumn2 += 1;
            break;
          case 9:
            currentVisibleColumn2 = $cF.nextRenderTabStop(currentVisibleColumn2, tabSize);
            break;
          default:
            return -1;
        }
      }
      if (currentVisibleColumn2 === prevTabStopVisibleColumn + tabSize) {
        return prevTabStopPosition;
      }
      return -1;
    }
    const targetVisibleColumn = $cF.nextRenderTabStop(visibleColumn, tabSize);
    let currentVisibleColumn = visibleColumn;
    for (let i2 = position; i2 < lineLength; i2++) {
      if (currentVisibleColumn === targetVisibleColumn) {
        return i2;
      }
      const chCode = lineContent.charCodeAt(i2);
      switch (chCode) {
        case 32:
          currentVisibleColumn += 1;
          break;
        case 9:
          currentVisibleColumn = $cF.nextRenderTabStop(currentVisibleColumn, tabSize);
          break;
        default:
          return -1;
      }
    }
    if (currentVisibleColumn === targetVisibleColumn) {
      return lineLength;
    }
    return -1;
  }
};

// out-build/vs/editor/common/cursor/cursorMoveOperations.js
var $j6 = class {
  constructor(lineNumber, column, leftoverVisibleColumns) {
    this._cursorPositionBrand = void 0;
    this.lineNumber = lineNumber;
    this.column = column;
    this.leftoverVisibleColumns = leftoverVisibleColumns;
  }
};
var $k6 = class _$k6 {
  static leftPosition(model, position) {
    if (position.column > model.getLineMinColumn(position.lineNumber)) {
      return position.delta(void 0, -$_f(model.getLineContent(position.lineNumber), position.column - 1));
    } else if (position.lineNumber > 1) {
      const newLineNumber = position.lineNumber - 1;
      return new $8C(newLineNumber, model.getLineMaxColumn(newLineNumber));
    } else {
      return position;
    }
  }
  static a(model, position, tabSize) {
    if (position.column <= model.getLineIndentColumn(position.lineNumber)) {
      const minColumn = model.getLineMinColumn(position.lineNumber);
      const lineContent = model.getLineContent(position.lineNumber);
      const newPosition = $i6.atomicPosition(
        lineContent,
        position.column - 1,
        tabSize,
        0
        /* Direction.Left */
      );
      if (newPosition !== -1 && newPosition + 1 >= minColumn) {
        return new $8C(position.lineNumber, newPosition + 1);
      }
    }
    return this.leftPosition(model, position);
  }
  static b(config, model, position) {
    const pos = config.stickyTabStops ? _$k6.a(model, position, config.tabSize) : _$k6.leftPosition(model, position);
    return new $j6(pos.lineNumber, pos.column, 0);
  }
  /**
   * @param noOfColumns Must be either `1`
   * or `Math.round(viewModel.getLineContent(viewLineNumber).length / 2)` (for half lines).
  */
  static moveLeft(config, model, cursor, inSelectionMode, noOfColumns) {
    let lineNumber, column;
    if (cursor.hasSelection() && !inSelectionMode) {
      lineNumber = cursor.selection.startLineNumber;
      column = cursor.selection.startColumn;
    } else {
      const pos = cursor.position.delta(void 0, -(noOfColumns - 1));
      const normalizedPos = model.normalizePosition(
        _$k6.c(pos, model),
        0
        /* PositionAffinity.Left */
      );
      const p = _$k6.b(config, model, normalizedPos);
      lineNumber = p.lineNumber;
      column = p.column;
    }
    return cursor.move(inSelectionMode, lineNumber, column, 0);
  }
  /**
   * Adjusts the column so that it is within min/max of the line.
  */
  static c(position, model) {
    return new $8C(position.lineNumber, _$k6.d(position.column, model.getLineMinColumn(position.lineNumber), model.getLineMaxColumn(position.lineNumber)));
  }
  static d(value, min, max) {
    if (value < min) {
      return min;
    }
    if (value > max) {
      return max;
    }
    return value;
  }
  static rightPosition(model, lineNumber, column) {
    if (column < model.getLineMaxColumn(lineNumber)) {
      column = column + $$f(model.getLineContent(lineNumber), column - 1);
    } else if (lineNumber < model.getLineCount()) {
      lineNumber = lineNumber + 1;
      column = model.getLineMinColumn(lineNumber);
    }
    return new $8C(lineNumber, column);
  }
  static rightPositionAtomicSoftTabs(model, lineNumber, column, tabSize, indentSize) {
    if (column < model.getLineIndentColumn(lineNumber)) {
      const lineContent = model.getLineContent(lineNumber);
      const newPosition = $i6.atomicPosition(
        lineContent,
        column - 1,
        tabSize,
        1
        /* Direction.Right */
      );
      if (newPosition !== -1) {
        return new $8C(lineNumber, newPosition + 1);
      }
    }
    return this.rightPosition(model, lineNumber, column);
  }
  static right(config, model, position) {
    const pos = config.stickyTabStops ? _$k6.rightPositionAtomicSoftTabs(model, position.lineNumber, position.column, config.tabSize, config.indentSize) : _$k6.rightPosition(model, position.lineNumber, position.column);
    return new $j6(pos.lineNumber, pos.column, 0);
  }
  static moveRight(config, model, cursor, inSelectionMode, noOfColumns) {
    let lineNumber, column;
    if (cursor.hasSelection() && !inSelectionMode) {
      lineNumber = cursor.selection.endLineNumber;
      column = cursor.selection.endColumn;
    } else {
      const pos = cursor.position.delta(void 0, noOfColumns - 1);
      const normalizedPos = model.normalizePosition(
        _$k6.c(pos, model),
        1
        /* PositionAffinity.Right */
      );
      const r2 = _$k6.right(config, model, normalizedPos);
      lineNumber = r2.lineNumber;
      column = r2.column;
    }
    return cursor.move(inSelectionMode, lineNumber, column, 0);
  }
  static vertical(config, model, lineNumber, column, leftoverVisibleColumns, newLineNumber, allowMoveOnEdgeLine, normalizationAffinity) {
    const currentVisibleColumn = $cF.visibleColumnFromColumn(model.getLineContent(lineNumber), column, config.tabSize) + leftoverVisibleColumns;
    const lineCount = model.getLineCount();
    const wasOnFirstPosition = lineNumber === 1 && column === 1;
    const wasOnLastPosition = lineNumber === lineCount && column === model.getLineMaxColumn(lineNumber);
    const wasAtEdgePosition = newLineNumber < lineNumber ? wasOnFirstPosition : wasOnLastPosition;
    lineNumber = newLineNumber;
    if (lineNumber < 1) {
      lineNumber = 1;
      if (allowMoveOnEdgeLine) {
        column = model.getLineMinColumn(lineNumber);
      } else {
        column = Math.min(model.getLineMaxColumn(lineNumber), column);
      }
    } else if (lineNumber > lineCount) {
      lineNumber = lineCount;
      if (allowMoveOnEdgeLine) {
        column = model.getLineMaxColumn(lineNumber);
      } else {
        column = Math.min(model.getLineMaxColumn(lineNumber), column);
      }
    } else {
      column = config.columnFromVisibleColumn(model, lineNumber, currentVisibleColumn);
    }
    if (wasAtEdgePosition) {
      leftoverVisibleColumns = 0;
    } else {
      leftoverVisibleColumns = currentVisibleColumn - $cF.visibleColumnFromColumn(model.getLineContent(lineNumber), column, config.tabSize);
    }
    if (normalizationAffinity !== void 0) {
      const position = new $8C(lineNumber, column);
      const newPosition = model.normalizePosition(position, normalizationAffinity);
      leftoverVisibleColumns = leftoverVisibleColumns + (column - newPosition.column);
      lineNumber = newPosition.lineNumber;
      column = newPosition.column;
    }
    return new $j6(lineNumber, column, leftoverVisibleColumns);
  }
  static down(config, model, lineNumber, column, leftoverVisibleColumns, count, allowMoveOnLastLine) {
    return this.vertical(
      config,
      model,
      lineNumber,
      column,
      leftoverVisibleColumns,
      lineNumber + count,
      allowMoveOnLastLine,
      4
      /* PositionAffinity.RightOfInjectedText */
    );
  }
  static moveDown(config, model, cursor, inSelectionMode, linesCount) {
    let lineNumber, column;
    if (cursor.hasSelection() && !inSelectionMode) {
      lineNumber = cursor.selection.endLineNumber;
      column = cursor.selection.endColumn;
    } else {
      lineNumber = cursor.position.lineNumber;
      column = cursor.position.column;
    }
    let i2 = 0;
    let r2;
    do {
      r2 = _$k6.down(config, model, lineNumber + i2, column, cursor.leftoverVisibleColumns, linesCount, true);
      const np = model.normalizePosition(
        new $8C(r2.lineNumber, r2.column),
        2
        /* PositionAffinity.None */
      );
      if (np.lineNumber > lineNumber) {
        break;
      }
    } while (i2++ < 10 && lineNumber + i2 < model.getLineCount());
    return cursor.move(inSelectionMode, r2.lineNumber, r2.column, r2.leftoverVisibleColumns);
  }
  static translateDown(config, model, cursor) {
    const selection = cursor.selection;
    const selectionStart = _$k6.down(config, model, selection.selectionStartLineNumber, selection.selectionStartColumn, cursor.selectionStartLeftoverVisibleColumns, 1, false);
    const position = _$k6.down(config, model, selection.positionLineNumber, selection.positionColumn, cursor.leftoverVisibleColumns, 1, false);
    return new $h5(new $9C(selectionStart.lineNumber, selectionStart.column, selectionStart.lineNumber, selectionStart.column), 0, selectionStart.leftoverVisibleColumns, new $8C(position.lineNumber, position.column), position.leftoverVisibleColumns);
  }
  static up(config, model, lineNumber, column, leftoverVisibleColumns, count, allowMoveOnFirstLine) {
    return this.vertical(
      config,
      model,
      lineNumber,
      column,
      leftoverVisibleColumns,
      lineNumber - count,
      allowMoveOnFirstLine,
      3
      /* PositionAffinity.LeftOfInjectedText */
    );
  }
  static moveUp(config, model, cursor, inSelectionMode, linesCount) {
    let lineNumber, column;
    if (cursor.hasSelection() && !inSelectionMode) {
      lineNumber = cursor.selection.startLineNumber;
      column = cursor.selection.startColumn;
    } else {
      lineNumber = cursor.position.lineNumber;
      column = cursor.position.column;
    }
    const r2 = _$k6.up(config, model, lineNumber, column, cursor.leftoverVisibleColumns, linesCount, true);
    return cursor.move(inSelectionMode, r2.lineNumber, r2.column, r2.leftoverVisibleColumns);
  }
  static translateUp(config, model, cursor) {
    const selection = cursor.selection;
    const selectionStart = _$k6.up(config, model, selection.selectionStartLineNumber, selection.selectionStartColumn, cursor.selectionStartLeftoverVisibleColumns, 1, false);
    const position = _$k6.up(config, model, selection.positionLineNumber, selection.positionColumn, cursor.leftoverVisibleColumns, 1, false);
    return new $h5(new $9C(selectionStart.lineNumber, selectionStart.column, selectionStart.lineNumber, selectionStart.column), 0, selectionStart.leftoverVisibleColumns, new $8C(position.lineNumber, position.column), position.leftoverVisibleColumns);
  }
  static e(model, lineNumber) {
    if (model.getLineFirstNonWhitespaceColumn(lineNumber) === 0) {
      return true;
    }
    return false;
  }
  static moveToPrevBlankLine(config, model, cursor, inSelectionMode) {
    let lineNumber = cursor.position.lineNumber;
    while (lineNumber > 1 && this.e(model, lineNumber)) {
      lineNumber--;
    }
    while (lineNumber > 1 && !this.e(model, lineNumber)) {
      lineNumber--;
    }
    return cursor.move(inSelectionMode, lineNumber, model.getLineMinColumn(lineNumber), 0);
  }
  static moveToNextBlankLine(config, model, cursor, inSelectionMode) {
    const lineCount = model.getLineCount();
    let lineNumber = cursor.position.lineNumber;
    while (lineNumber < lineCount && this.e(model, lineNumber)) {
      lineNumber++;
    }
    while (lineNumber < lineCount && !this.e(model, lineNumber)) {
      lineNumber++;
    }
    return cursor.move(inSelectionMode, lineNumber, model.getLineMinColumn(lineNumber), 0);
  }
  static moveToBeginningOfLine(config, model, cursor, inSelectionMode) {
    const lineNumber = cursor.position.lineNumber;
    const minColumn = model.getLineMinColumn(lineNumber);
    const firstNonBlankColumn = model.getLineFirstNonWhitespaceColumn(lineNumber) || minColumn;
    let column;
    const relevantColumnNumber = cursor.position.column;
    if (relevantColumnNumber === firstNonBlankColumn) {
      column = minColumn;
    } else {
      column = firstNonBlankColumn;
    }
    return cursor.move(inSelectionMode, lineNumber, column, 0);
  }
  static moveToEndOfLine(config, model, cursor, inSelectionMode, sticky) {
    const lineNumber = cursor.position.lineNumber;
    const maxColumn = model.getLineMaxColumn(lineNumber);
    return cursor.move(inSelectionMode, lineNumber, maxColumn, sticky ? 1073741824 - maxColumn : 0);
  }
  static moveToBeginningOfBuffer(config, model, cursor, inSelectionMode) {
    return cursor.move(inSelectionMode, 1, 1, 0);
  }
  static moveToEndOfBuffer(config, model, cursor, inSelectionMode) {
    const lastLineNumber = model.getLineCount();
    const lastColumn = model.getLineMaxColumn(lastLineNumber);
    return cursor.move(inSelectionMode, lastLineNumber, lastColumn, 0);
  }
};

// out-build/vs/editor/common/cursor/cursorDeleteOperations.js
var $l6 = class _$l6 {
  static deleteRight(prevEditOperationType, config, model, selections) {
    const commands2 = [];
    let shouldPushStackElementBefore = prevEditOperationType !== 3;
    for (let i2 = 0, len = selections.length; i2 < len; i2++) {
      const selection = selections[i2];
      let deleteSelection = selection;
      if (deleteSelection.isEmpty()) {
        const position = selection.getPosition();
        const rightOfPosition = $k6.right(config, model, position);
        deleteSelection = new $9C(rightOfPosition.lineNumber, rightOfPosition.column, position.lineNumber, position.column);
      }
      if (deleteSelection.isEmpty()) {
        commands2[i2] = null;
        continue;
      }
      if (deleteSelection.startLineNumber !== deleteSelection.endLineNumber) {
        shouldPushStackElementBefore = true;
      }
      commands2[i2] = new $b6(deleteSelection, "");
    }
    return [shouldPushStackElementBefore, commands2];
  }
  static isAutoClosingPairDelete(autoClosingDelete, autoClosingBrackets, autoClosingQuotes, autoClosingPairsOpen, model, selections, autoClosedCharacters) {
    if (autoClosingBrackets === "never" && autoClosingQuotes === "never") {
      return false;
    }
    if (autoClosingDelete === "never") {
      return false;
    }
    for (let i2 = 0, len = selections.length; i2 < len; i2++) {
      const selection = selections[i2];
      const position = selection.getPosition();
      if (!selection.isEmpty()) {
        return false;
      }
      const lineText = model.getLineContent(position.lineNumber);
      if (position.column < 2 || position.column >= lineText.length + 1) {
        return false;
      }
      const character = lineText.charAt(position.column - 2);
      const autoClosingPairCandidates = autoClosingPairsOpen.get(character);
      if (!autoClosingPairCandidates) {
        return false;
      }
      if ($j5(character)) {
        if (autoClosingQuotes === "never") {
          return false;
        }
      } else {
        if (autoClosingBrackets === "never") {
          return false;
        }
      }
      const afterCharacter = lineText.charAt(position.column - 1);
      let foundAutoClosingPair = false;
      for (const autoClosingPairCandidate of autoClosingPairCandidates) {
        if (autoClosingPairCandidate.open === character && autoClosingPairCandidate.close === afterCharacter) {
          foundAutoClosingPair = true;
        }
      }
      if (!foundAutoClosingPair) {
        return false;
      }
      if (autoClosingDelete === "auto") {
        let found = false;
        for (let j = 0, lenJ = autoClosedCharacters.length; j < lenJ; j++) {
          const autoClosedCharacter = autoClosedCharacters[j];
          if (position.lineNumber === autoClosedCharacter.startLineNumber && position.column === autoClosedCharacter.startColumn) {
            found = true;
            break;
          }
        }
        if (!found) {
          return false;
        }
      }
    }
    return true;
  }
  static c(config, model, selections) {
    const commands2 = [];
    for (let i2 = 0, len = selections.length; i2 < len; i2++) {
      const position = selections[i2].getPosition();
      const deleteSelection = new $9C(position.lineNumber, position.column - 1, position.lineNumber, position.column + 1);
      commands2[i2] = new $b6(deleteSelection, "");
    }
    return [true, commands2];
  }
  static deleteLeft(prevEditOperationType, config, model, selections, autoClosedCharacters) {
    if (this.isAutoClosingPairDelete(config.autoClosingDelete, config.autoClosingBrackets, config.autoClosingQuotes, config.autoClosingPairs.autoClosingPairsOpenByEnd, model, selections, autoClosedCharacters)) {
      return this.c(config, model, selections);
    }
    const commands2 = [];
    let shouldPushStackElementBefore = prevEditOperationType !== 2;
    for (let i2 = 0, len = selections.length; i2 < len; i2++) {
      const deleteRange = _$l6.d(selections[i2], model, config);
      if (deleteRange.isEmpty()) {
        commands2[i2] = null;
        continue;
      }
      if (deleteRange.startLineNumber !== deleteRange.endLineNumber) {
        shouldPushStackElementBefore = true;
      }
      commands2[i2] = new $b6(deleteRange, "");
    }
    return [shouldPushStackElementBefore, commands2];
  }
  static d(selection, model, config) {
    if (!selection.isEmpty()) {
      return selection;
    }
    const position = selection.getPosition();
    if (config.useTabStops && position.column > 1) {
      const lineContent = model.getLineContent(position.lineNumber);
      const firstNonWhitespaceIndex = $Of(lineContent);
      const lastIndentationColumn = firstNonWhitespaceIndex === -1 ? (
        /* entire string is whitespace */
        lineContent.length + 1
      ) : firstNonWhitespaceIndex + 1;
      if (position.column <= lastIndentationColumn) {
        const fromVisibleColumn = config.visibleColumnFromColumn(model, position);
        const toVisibleColumn = $cF.prevIndentTabStop(fromVisibleColumn, config.indentSize);
        const toColumn = config.columnFromVisibleColumn(model, position.lineNumber, toVisibleColumn);
        return new $9C(position.lineNumber, toColumn, position.lineNumber, position.column);
      }
    }
    return $9C.fromPositions(_$l6.e(position, model), position);
  }
  static e(position, model) {
    if (position.column > 1) {
      const idx = $vg(position.column - 1, model.getLineContent(position.lineNumber));
      return position.with(void 0, idx + 1);
    } else if (position.lineNumber > 1) {
      const newLine = position.lineNumber - 1;
      return new $8C(newLine, model.getLineMaxColumn(newLine));
    } else {
      return position;
    }
  }
  static cut(config, model, selections) {
    const commands2 = [];
    let lastCutRange = null;
    selections.sort((a, b) => $8C.compare(a.getStartPosition(), b.getEndPosition()));
    for (let i2 = 0, len = selections.length; i2 < len; i2++) {
      const selection = selections[i2];
      if (selection.isEmpty()) {
        if (config.emptySelectionClipboard) {
          const position = selection.getPosition();
          let startLineNumber, startColumn, endLineNumber, endColumn;
          if (position.lineNumber < model.getLineCount()) {
            startLineNumber = position.lineNumber;
            startColumn = 1;
            endLineNumber = position.lineNumber + 1;
            endColumn = 1;
          } else if (position.lineNumber > 1 && lastCutRange?.endLineNumber !== position.lineNumber) {
            startLineNumber = position.lineNumber - 1;
            startColumn = model.getLineMaxColumn(position.lineNumber - 1);
            endLineNumber = position.lineNumber;
            endColumn = model.getLineMaxColumn(position.lineNumber);
          } else {
            startLineNumber = position.lineNumber;
            startColumn = 1;
            endLineNumber = position.lineNumber;
            endColumn = model.getLineMaxColumn(position.lineNumber);
          }
          const deleteSelection = new $9C(startLineNumber, startColumn, endLineNumber, endColumn);
          lastCutRange = deleteSelection;
          if (!deleteSelection.isEmpty()) {
            commands2[i2] = new $b6(deleteSelection, "");
          } else {
            commands2[i2] = null;
          }
        } else {
          commands2[i2] = null;
        }
      } else {
        commands2[i2] = new $b6(selection, "");
      }
    }
    return new $i5(0, commands2, {
      shouldPushStackElementBefore: true,
      shouldPushStackElementAfter: true
    });
  }
};

// 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 $Qu(date, appendAgoLabel, useFullTimeWords, disallowNow) {
  if (typeof date !== "number") {
    date = date.getTime();
  }
  const seconds = Math.round(((/* @__PURE__ */ new Date()).getTime() - date) / 1e3);
  if (seconds < -30) {
    return localize(45, null, $Qu((/* @__PURE__ */ new Date()).getTime() + seconds * 1e3, false));
  }
  if (!disallowNow && seconds < 30) {
    return localize(46, null);
  }
  let value;
  if (seconds < minute) {
    value = seconds;
    if (appendAgoLabel) {
      if (value === 1) {
        return useFullTimeWords ? localize(47, null, value) : localize(48, null, value);
      } else {
        return useFullTimeWords ? localize(49, null, value) : localize(50, null, value);
      }
    } else {
      if (value === 1) {
        return useFullTimeWords ? localize(51, null, value) : localize(52, null, value);
      } else {
        return useFullTimeWords ? localize(53, null, value) : localize(54, null, value);
      }
    }
  }
  if (seconds < hour) {
    value = Math.floor(seconds / minute);
    if (appendAgoLabel) {
      if (value === 1) {
        return useFullTimeWords ? localize(55, null, value) : localize(56, null, value);
      } else {
        return useFullTimeWords ? localize(57, null, value) : localize(58, null, value);
      }
    } else {
      if (value === 1) {
        return useFullTimeWords ? localize(59, null, value) : localize(60, null, value);
      } else {
        return useFullTimeWords ? localize(61, null, value) : localize(62, null, value);
      }
    }
  }
  if (seconds < day) {
    value = Math.floor(seconds / hour);
    if (appendAgoLabel) {
      if (value === 1) {
        return useFullTimeWords ? localize(63, null, value) : localize(64, null, value);
      } else {
        return useFullTimeWords ? localize(65, null, value) : localize(66, null, value);
      }
    } else {
      if (value === 1) {
        return useFullTimeWords ? localize(67, null, value) : localize(68, null, value);
      } else {
        return useFullTimeWords ? localize(69, null, value) : localize(70, null, value);
      }
    }
  }
  if (seconds < week) {
    value = Math.floor(seconds / day);
    if (appendAgoLabel) {
      return value === 1 ? localize(71, null, value) : localize(72, null, value);
    } else {
      return value === 1 ? localize(73, null, value) : localize(74, null, value);
    }
  }
  if (seconds < month) {
    value = Math.floor(seconds / week);
    if (appendAgoLabel) {
      if (value === 1) {
        return useFullTimeWords ? localize(75, null, value) : localize(76, null, value);
      } else {
        return useFullTimeWords ? localize(77, null, value) : localize(78, null, value);
      }
    } else {
      if (value === 1) {
        return useFullTimeWords ? localize(79, null, value) : localize(80, null, value);
      } else {
        return useFullTimeWords ? localize(81, null, value) : localize(82, null, value);
      }
    }
  }
  if (seconds < year) {
    value = Math.floor(seconds / month);
    if (appendAgoLabel) {
      if (value === 1) {
        return useFullTimeWords ? localize(83, null, value) : localize(84, null, value);
      } else {
        return useFullTimeWords ? localize(85, null, value) : localize(86, null, value);
      }
    } else {
      if (value === 1) {
        return useFullTimeWords ? localize(87, null, value) : localize(88, null, value);
      } else {
        return useFullTimeWords ? localize(89, null, value) : localize(90, null, value);
      }
    }
  }
  value = Math.floor(seconds / year);
  if (appendAgoLabel) {
    if (value === 1) {
      return useFullTimeWords ? localize(91, null, value) : localize(92, null, value);
    } else {
      return useFullTimeWords ? localize(93, null, value) : localize(94, null, value);
    }
  } else {
    if (value === 1) {
      return useFullTimeWords ? localize(95, null, value) : localize(96, null, value);
    } else {
      return useFullTimeWords ? localize(97, null, value) : localize(98, null, value);
    }
  }
}
function $Ru(date, appendAgoLabel, useFullTimeWords) {
  if (typeof date !== "number") {
    date = date.getTime();
  }
  const todayMidnightTime = /* @__PURE__ */ new Date();
  todayMidnightTime.setHours(0, 0, 0, 0);
  const yesterdayMidnightTime = new Date(todayMidnightTime.getTime());
  yesterdayMidnightTime.setDate(yesterdayMidnightTime.getDate() - 1);
  if (date > todayMidnightTime.getTime()) {
    return localize(99, null);
  }
  if (date > yesterdayMidnightTime.getTime()) {
    return localize(100, null);
  }
  return $Qu(date, appendAgoLabel, useFullTimeWords);
}
function $Su(ms, useFullTimeWords) {
  const seconds = Math.abs(ms / 1e3);
  if (seconds < 1) {
    return useFullTimeWords ? localize(101, null, ms) : localize(102, null, ms);
  }
  if (seconds < minute) {
    return useFullTimeWords ? localize(103, null, Math.round(ms) / 1e3) : localize(104, null, Math.round(ms) / 1e3);
  }
  if (seconds < hour) {
    return useFullTimeWords ? localize(105, null, Math.round(ms / (1e3 * minute))) : localize(106, null, Math.round(ms / (1e3 * minute)));
  }
  if (seconds < day) {
    return useFullTimeWords ? localize(107, null, Math.round(ms / (1e3 * hour))) : localize(108, null, Math.round(ms / (1e3 * hour)));
  }
  return localize(109, null, Math.round(ms / (1e3 * day)));
}
function $Tu(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";
}
var $Uu = {
  DateTimeFormat(locales, options3) {
    try {
      return new Intl.DateTimeFormat(locales, options3);
    } catch {
      return new Intl.DateTimeFormat(void 0, options3);
    }
  },
  Collator(locales, options3) {
    try {
      return new Intl.Collator(locales, options3);
    } catch {
      return new Intl.Collator(void 0, options3);
    }
  },
  Segmenter(locales, options3) {
    try {
      return new Intl.Segmenter(locales, options3);
    } catch {
      return new Intl.Segmenter(void 0, options3);
    }
  },
  Locale(tag2, options3) {
    try {
      return new Intl.Locale(tag2, options3);
    } catch {
      return new Intl.Locale($j, options3);
    }
  }
};

// out-build/vs/base/common/uint.js
var Constants;
(function(Constants27) {
  Constants27[Constants27["MAX_SAFE_SMALL_INTEGER"] = 1073741824] = "MAX_SAFE_SMALL_INTEGER";
  Constants27[Constants27["MIN_SAFE_SMALL_INTEGER"] = -1073741824] = "MIN_SAFE_SMALL_INTEGER";
  Constants27[Constants27["MAX_UINT_8"] = 255] = "MAX_UINT_8";
  Constants27[Constants27["MAX_UINT_16"] = 65535] = "MAX_UINT_16";
  Constants27[Constants27["MAX_UINT_32"] = 4294967295] = "MAX_UINT_32";
  Constants27[Constants27["UNICODE_SUPPLEMENTARY_PLANE_BEGIN"] = 65536] = "UNICODE_SUPPLEMENTARY_PLANE_BEGIN";
})(Constants || (Constants = {}));
function $tf(v) {
  if (v < 0) {
    return 0;
  }
  if (v > 255) {
    return 255;
  }
  return v | 0;
}
function $uf(v) {
  if (v < 0) {
    return 0;
  }
  if (v > 4294967295) {
    return 4294967295;
  }
  return v | 0;
}

// out-build/vs/editor/common/core/characterClassifier.js
var $fE = class _$fE {
  constructor(_defaultValue) {
    const defaultValue = $tf(_defaultValue);
    this.c = defaultValue;
    this.a = _$fE.d(defaultValue);
    this.b = /* @__PURE__ */ new Map();
  }
  static d(defaultValue) {
    const asciiMap = new Uint8Array(256);
    asciiMap.fill(defaultValue);
    return asciiMap;
  }
  set(charCode, _value) {
    const value = $tf(_value);
    if (charCode >= 0 && charCode < 256) {
      this.a[charCode] = value;
    } else {
      this.b.set(charCode, value);
    }
  }
  get(charCode) {
    if (charCode >= 0 && charCode < 256) {
      return this.a[charCode];
    } else {
      return this.b.get(charCode) || this.c;
    }
  }
  clear() {
    this.a.fill(this.c);
    this.b.clear();
  }
};
var Boolean2;
(function(Boolean3) {
  Boolean3[Boolean3["False"] = 0] = "False";
  Boolean3[Boolean3["True"] = 1] = "True";
})(Boolean2 || (Boolean2 = {}));
var $gE = class {
  constructor() {
    this.a = new $fE(
      0
      /* Boolean.False */
    );
  }
  add(charCode) {
    this.a.set(
      charCode,
      1
      /* Boolean.True */
    );
  }
  has(charCode) {
    return this.a.get(charCode) === 1;
  }
  clear() {
    return this.a.clear();
  }
};

// out-build/vs/editor/common/core/wordCharacterClassifier.js
var WordCharacterClass;
(function(WordCharacterClass2) {
  WordCharacterClass2[WordCharacterClass2["Regular"] = 0] = "Regular";
  WordCharacterClass2[WordCharacterClass2["Whitespace"] = 1] = "Whitespace";
  WordCharacterClass2[WordCharacterClass2["WordSeparator"] = 2] = "WordSeparator";
})(WordCharacterClass || (WordCharacterClass = {}));
var $hE = class extends $fE {
  constructor(wordSeparators2, intlSegmenterLocales) {
    super(
      0
      /* WordCharacterClass.Regular */
    );
    this.e = null;
    this.f = null;
    this.g = [];
    this.intlSegmenterLocales = intlSegmenterLocales;
    if (this.intlSegmenterLocales.length > 0) {
      this.e = $Uu.Segmenter(this.intlSegmenterLocales, { granularity: "word" });
    } else {
      this.e = null;
    }
    for (let i2 = 0, len = wordSeparators2.length; i2 < len; i2++) {
      this.set(
        wordSeparators2.charCodeAt(i2),
        2
        /* WordCharacterClass.WordSeparator */
      );
    }
    this.set(
      32,
      1
      /* WordCharacterClass.Whitespace */
    );
    this.set(
      9,
      1
      /* WordCharacterClass.Whitespace */
    );
  }
  findPrevIntlWordBeforeOrAtOffset(line, offset) {
    let candidate = null;
    for (const segment of this.h(line)) {
      if (segment.index > offset) {
        break;
      }
      candidate = segment;
    }
    return candidate;
  }
  findNextIntlWordAtOrAfterOffset(lineContent, offset) {
    for (const segment of this.h(lineContent)) {
      if (segment.index < offset) {
        continue;
      }
      return segment;
    }
    return null;
  }
  h(line) {
    if (!this.e) {
      return [];
    }
    if (this.f === line) {
      return this.g;
    }
    this.f = line;
    this.g = this.j(this.e.segment(line));
    return this.g;
  }
  j(segments) {
    const result = [];
    for (const segment of segments) {
      if (this.k(segment)) {
        result.push(segment);
      }
    }
    return result;
  }
  k(segment) {
    if (segment.isWordLike) {
      return true;
    }
    return false;
  }
};
var wordClassifierCache = new $Hc(10);
function $iE(wordSeparators2, intlSegmenterLocales) {
  const key2 = `${wordSeparators2}/${intlSegmenterLocales.join(",")}`;
  let result = wordClassifierCache.get(key2);
  if (!result) {
    result = new $hE(wordSeparators2, intlSegmenterLocales);
    wordClassifierCache.set(key2, result);
  }
  return result;
}

// out-build/vs/editor/common/cursor/cursorWordOperations.js
var WordType;
(function(WordType2) {
  WordType2[WordType2["None"] = 0] = "None";
  WordType2[WordType2["Regular"] = 1] = "Regular";
  WordType2[WordType2["Separator"] = 2] = "Separator";
})(WordType || (WordType = {}));
var WordNavigationType;
(function(WordNavigationType2) {
  WordNavigationType2[WordNavigationType2["WordStart"] = 0] = "WordStart";
  WordNavigationType2[WordNavigationType2["WordStartFast"] = 1] = "WordStartFast";
  WordNavigationType2[WordNavigationType2["WordEnd"] = 2] = "WordEnd";
  WordNavigationType2[WordNavigationType2["WordAccessibility"] = 3] = "WordAccessibility";
})(WordNavigationType || (WordNavigationType = {}));
var $m6 = class _$m6 {
  static a(lineContent, wordType, nextCharClass, start, end) {
    return { start, end, wordType, nextCharClass };
  }
  static b(intlWord, nextCharClass) {
    return { start: intlWord.index, end: intlWord.index + intlWord.segment.length, wordType: 1, nextCharClass };
  }
  static c(wordSeparators2, model, position) {
    const lineContent = model.getLineContent(position.lineNumber);
    return this.d(lineContent, wordSeparators2, position);
  }
  static d(lineContent, wordSeparators2, position) {
    let wordType = 0;
    const previousIntlWord = wordSeparators2.findPrevIntlWordBeforeOrAtOffset(lineContent, position.column - 2);
    for (let chIndex = position.column - 2; chIndex >= 0; chIndex--) {
      const chCode = lineContent.charCodeAt(chIndex);
      const chClass = wordSeparators2.get(chCode);
      if (previousIntlWord && chIndex === previousIntlWord.index) {
        return this.b(previousIntlWord, chClass);
      }
      if (chClass === 0) {
        if (wordType === 2) {
          return this.a(lineContent, wordType, chClass, chIndex + 1, this.e(lineContent, wordSeparators2, wordType, chIndex + 1));
        }
        wordType = 1;
      } else if (chClass === 2) {
        if (wordType === 1) {
          return this.a(lineContent, wordType, chClass, chIndex + 1, this.e(lineContent, wordSeparators2, wordType, chIndex + 1));
        }
        wordType = 2;
      } else if (chClass === 1) {
        if (wordType !== 0) {
          return this.a(lineContent, wordType, chClass, chIndex + 1, this.e(lineContent, wordSeparators2, wordType, chIndex + 1));
        }
      }
    }
    if (wordType !== 0) {
      return this.a(lineContent, wordType, 1, 0, this.e(lineContent, wordSeparators2, wordType, 0));
    }
    return null;
  }
  static e(lineContent, wordSeparators2, wordType, startIndex) {
    const nextIntlWord = wordSeparators2.findNextIntlWordAtOrAfterOffset(lineContent, startIndex);
    const len = lineContent.length;
    for (let chIndex = startIndex; chIndex < len; chIndex++) {
      const chCode = lineContent.charCodeAt(chIndex);
      const chClass = wordSeparators2.get(chCode);
      if (nextIntlWord && chIndex === nextIntlWord.index + nextIntlWord.segment.length) {
        return chIndex;
      }
      if (chClass === 1) {
        return chIndex;
      }
      if (wordType === 1 && chClass === 2) {
        return chIndex;
      }
      if (wordType === 2 && chClass === 0) {
        return chIndex;
      }
    }
    return len;
  }
  static f(wordSeparators2, model, position) {
    const lineContent = model.getLineContent(position.lineNumber);
    return this.g(lineContent, wordSeparators2, position);
  }
  static g(lineContent, wordSeparators2, position) {
    let wordType = 0;
    const len = lineContent.length;
    const nextIntlWord = wordSeparators2.findNextIntlWordAtOrAfterOffset(lineContent, position.column - 1);
    for (let chIndex = position.column - 1; chIndex < len; chIndex++) {
      const chCode = lineContent.charCodeAt(chIndex);
      const chClass = wordSeparators2.get(chCode);
      if (nextIntlWord && chIndex === nextIntlWord.index) {
        return this.b(nextIntlWord, chClass);
      }
      if (chClass === 0) {
        if (wordType === 2) {
          return this.a(lineContent, wordType, chClass, this.h(lineContent, wordSeparators2, wordType, chIndex - 1), chIndex);
        }
        wordType = 1;
      } else if (chClass === 2) {
        if (wordType === 1) {
          return this.a(lineContent, wordType, chClass, this.h(lineContent, wordSeparators2, wordType, chIndex - 1), chIndex);
        }
        wordType = 2;
      } else if (chClass === 1) {
        if (wordType !== 0) {
          return this.a(lineContent, wordType, chClass, this.h(lineContent, wordSeparators2, wordType, chIndex - 1), chIndex);
        }
      }
    }
    if (wordType !== 0) {
      return this.a(lineContent, wordType, 1, this.h(lineContent, wordSeparators2, wordType, len - 1), len);
    }
    return null;
  }
  static h(lineContent, wordSeparators2, wordType, startIndex) {
    const previousIntlWord = wordSeparators2.findPrevIntlWordBeforeOrAtOffset(lineContent, startIndex);
    for (let chIndex = startIndex; chIndex >= 0; chIndex--) {
      const chCode = lineContent.charCodeAt(chIndex);
      const chClass = wordSeparators2.get(chCode);
      if (previousIntlWord && chIndex === previousIntlWord.index) {
        return chIndex;
      }
      if (chClass === 1) {
        return chIndex + 1;
      }
      if (wordType === 1 && chClass === 2) {
        return chIndex + 1;
      }
      if (wordType === 2 && chClass === 0) {
        return chIndex + 1;
      }
    }
    return 0;
  }
  static moveWordLeft(wordSeparators2, model, position, wordNavigationType, hasMulticursor) {
    let lineNumber = position.lineNumber;
    let column = position.column;
    if (column === 1) {
      if (lineNumber > 1) {
        lineNumber = lineNumber - 1;
        column = model.getLineMaxColumn(lineNumber);
      }
    }
    let prevWordOnLine = _$m6.c(wordSeparators2, model, new $8C(lineNumber, column));
    if (wordNavigationType === 0) {
      return new $8C(lineNumber, prevWordOnLine ? prevWordOnLine.start + 1 : 1);
    }
    if (wordNavigationType === 1) {
      if (!hasMulticursor && prevWordOnLine && prevWordOnLine.wordType === 2 && prevWordOnLine.end - prevWordOnLine.start === 1 && prevWordOnLine.nextCharClass === 0) {
        prevWordOnLine = _$m6.c(wordSeparators2, model, new $8C(lineNumber, prevWordOnLine.start + 1));
      }
      return new $8C(lineNumber, prevWordOnLine ? prevWordOnLine.start + 1 : 1);
    }
    if (wordNavigationType === 3) {
      while (prevWordOnLine && prevWordOnLine.wordType === 2) {
        prevWordOnLine = _$m6.c(wordSeparators2, model, new $8C(lineNumber, prevWordOnLine.start + 1));
      }
      return new $8C(lineNumber, prevWordOnLine ? prevWordOnLine.start + 1 : 1);
    }
    if (prevWordOnLine && column <= prevWordOnLine.end + 1) {
      prevWordOnLine = _$m6.c(wordSeparators2, model, new $8C(lineNumber, prevWordOnLine.start + 1));
    }
    return new $8C(lineNumber, prevWordOnLine ? prevWordOnLine.end + 1 : 1);
  }
  static _moveWordPartLeft(model, position) {
    const lineNumber = position.lineNumber;
    const maxColumn = model.getLineMaxColumn(lineNumber);
    if (position.column === 1) {
      return lineNumber > 1 ? new $8C(lineNumber - 1, model.getLineMaxColumn(lineNumber - 1)) : position;
    }
    const lineContent = model.getLineContent(lineNumber);
    for (let column = position.column - 1; column > 1; column--) {
      const left = lineContent.charCodeAt(column - 2);
      const right = lineContent.charCodeAt(column - 1);
      if (left === 95 && right !== 95) {
        return new $8C(lineNumber, column);
      }
      if (left === 45 && right !== 45) {
        return new $8C(lineNumber, column);
      }
      if (($Yf(left) || $Xf(left)) && $Zf(right)) {
        return new $8C(lineNumber, column);
      }
      if ($Zf(left) && $Zf(right)) {
        if (column + 1 < maxColumn) {
          const rightRight = lineContent.charCodeAt(column);
          if ($Yf(rightRight) || $Xf(rightRight)) {
            return new $8C(lineNumber, column);
          }
        }
      }
    }
    return new $8C(lineNumber, 1);
  }
  static moveWordRight(wordSeparators2, model, position, wordNavigationType) {
    let lineNumber = position.lineNumber;
    let column = position.column;
    let movedDown = false;
    if (column === model.getLineMaxColumn(lineNumber)) {
      if (lineNumber < model.getLineCount()) {
        movedDown = true;
        lineNumber = lineNumber + 1;
        column = 1;
      }
    }
    let nextWordOnLine = _$m6.f(wordSeparators2, model, new $8C(lineNumber, column));
    if (wordNavigationType === 2) {
      if (nextWordOnLine && nextWordOnLine.wordType === 2) {
        if (nextWordOnLine.end - nextWordOnLine.start === 1 && nextWordOnLine.nextCharClass === 0) {
          nextWordOnLine = _$m6.f(wordSeparators2, model, new $8C(lineNumber, nextWordOnLine.end + 1));
        }
      }
      if (nextWordOnLine) {
        column = nextWordOnLine.end + 1;
      } else {
        column = model.getLineMaxColumn(lineNumber);
      }
    } else if (wordNavigationType === 3) {
      if (movedDown) {
        column = 0;
      }
      while (nextWordOnLine && (nextWordOnLine.wordType === 2 || nextWordOnLine.start + 1 <= column)) {
        nextWordOnLine = _$m6.f(wordSeparators2, model, new $8C(lineNumber, nextWordOnLine.end + 1));
      }
      if (nextWordOnLine) {
        column = nextWordOnLine.start + 1;
      } else {
        column = model.getLineMaxColumn(lineNumber);
      }
    } else {
      if (nextWordOnLine && !movedDown && column >= nextWordOnLine.start + 1) {
        nextWordOnLine = _$m6.f(wordSeparators2, model, new $8C(lineNumber, nextWordOnLine.end + 1));
      }
      if (nextWordOnLine) {
        column = nextWordOnLine.start + 1;
      } else {
        column = model.getLineMaxColumn(lineNumber);
      }
    }
    return new $8C(lineNumber, column);
  }
  static _moveWordPartRight(model, position) {
    const lineNumber = position.lineNumber;
    const maxColumn = model.getLineMaxColumn(lineNumber);
    if (position.column === maxColumn) {
      return lineNumber < model.getLineCount() ? new $8C(lineNumber + 1, 1) : position;
    }
    const lineContent = model.getLineContent(lineNumber);
    for (let column = position.column + 1; column < maxColumn; column++) {
      const left = lineContent.charCodeAt(column - 2);
      const right = lineContent.charCodeAt(column - 1);
      if (left !== 95 && right === 95) {
        return new $8C(lineNumber, column);
      }
      if (left !== 45 && right === 45) {
        return new $8C(lineNumber, column);
      }
      if (($Yf(left) || $Xf(left)) && $Zf(right)) {
        return new $8C(lineNumber, column);
      }
      if ($Zf(left) && $Zf(right)) {
        if (column + 1 < maxColumn) {
          const rightRight = lineContent.charCodeAt(column);
          if ($Yf(rightRight) || $Xf(rightRight)) {
            return new $8C(lineNumber, column);
          }
        }
      }
    }
    return new $8C(lineNumber, maxColumn);
  }
  static i(model, position) {
    const lineContent = model.getLineContent(position.lineNumber);
    const startIndex = position.column - 2;
    const lastNonWhitespace = $Qf(lineContent, startIndex);
    if (lastNonWhitespace + 1 < startIndex) {
      return new $9C(position.lineNumber, lastNonWhitespace + 2, position.lineNumber, position.column);
    }
    return null;
  }
  static deleteWordLeft(ctx, wordNavigationType) {
    const wordSeparators2 = ctx.wordSeparators;
    const model = ctx.model;
    const selection = ctx.selection;
    const whitespaceHeuristics = ctx.whitespaceHeuristics;
    if (!selection.isEmpty()) {
      return selection;
    }
    if ($l6.isAutoClosingPairDelete(ctx.autoClosingDelete, ctx.autoClosingBrackets, ctx.autoClosingQuotes, ctx.autoClosingPairs.autoClosingPairsOpenByEnd, ctx.model, [ctx.selection], ctx.autoClosedCharacters)) {
      const position2 = ctx.selection.getPosition();
      return new $9C(position2.lineNumber, position2.column - 1, position2.lineNumber, position2.column + 1);
    }
    const position = new $8C(selection.positionLineNumber, selection.positionColumn);
    let lineNumber = position.lineNumber;
    let column = position.column;
    if (lineNumber === 1 && column === 1) {
      return null;
    }
    if (whitespaceHeuristics) {
      const r2 = this.i(model, position);
      if (r2) {
        return r2;
      }
    }
    let prevWordOnLine = _$m6.c(wordSeparators2, model, position);
    if (wordNavigationType === 0) {
      if (prevWordOnLine) {
        column = prevWordOnLine.start + 1;
      } else {
        if (column > 1) {
          column = 1;
        } else {
          lineNumber--;
          column = model.getLineMaxColumn(lineNumber);
        }
      }
    } else {
      if (prevWordOnLine && column <= prevWordOnLine.end + 1) {
        prevWordOnLine = _$m6.c(wordSeparators2, model, new $8C(lineNumber, prevWordOnLine.start + 1));
      }
      if (prevWordOnLine) {
        column = prevWordOnLine.end + 1;
      } else {
        if (column > 1) {
          column = 1;
        } else {
          lineNumber--;
          column = model.getLineMaxColumn(lineNumber);
        }
      }
    }
    return new $9C(lineNumber, column, position.lineNumber, position.column);
  }
  static deleteInsideWord(wordSeparators2, model, selection) {
    if (!selection.isEmpty()) {
      return selection;
    }
    const position = new $8C(selection.positionLineNumber, selection.positionColumn);
    const r2 = this.k(model, position);
    if (r2) {
      return r2;
    }
    return this.l(wordSeparators2, model, position);
  }
  static j(str, index) {
    const charCode = str.charCodeAt(index);
    return charCode === 32 || charCode === 9;
  }
  static k(model, position) {
    const lineContent = model.getLineContent(position.lineNumber);
    const lineContentLength = lineContent.length;
    if (lineContentLength === 0) {
      return null;
    }
    let leftIndex = Math.max(position.column - 2, 0);
    if (!this.j(lineContent, leftIndex)) {
      return null;
    }
    let rightIndex = Math.min(position.column - 1, lineContentLength - 1);
    if (!this.j(lineContent, rightIndex)) {
      return null;
    }
    while (leftIndex > 0 && this.j(lineContent, leftIndex - 1)) {
      leftIndex--;
    }
    while (rightIndex + 1 < lineContentLength && this.j(lineContent, rightIndex + 1)) {
      rightIndex++;
    }
    return new $9C(position.lineNumber, leftIndex + 1, position.lineNumber, rightIndex + 2);
  }
  static l(wordSeparators2, model, position) {
    const lineContent = model.getLineContent(position.lineNumber);
    const lineLength = lineContent.length;
    if (lineLength === 0) {
      if (position.lineNumber > 1) {
        return new $9C(position.lineNumber - 1, model.getLineMaxColumn(position.lineNumber - 1), position.lineNumber, 1);
      } else {
        if (position.lineNumber < model.getLineCount()) {
          return new $9C(position.lineNumber, 1, position.lineNumber + 1, 1);
        } else {
          return new $9C(position.lineNumber, 1, position.lineNumber, 1);
        }
      }
    }
    const touchesWord = (word) => {
      return word.start + 1 <= position.column && position.column <= word.end + 1;
    };
    const createRangeWithPosition = (startColumn, endColumn) => {
      startColumn = Math.min(startColumn, position.column);
      endColumn = Math.max(endColumn, position.column);
      return new $9C(position.lineNumber, startColumn, position.lineNumber, endColumn);
    };
    const deleteWordAndAdjacentWhitespace = (word) => {
      let startColumn = word.start + 1;
      let endColumn = word.end + 1;
      let expandedToTheRight = false;
      while (endColumn - 1 < lineLength && this.j(lineContent, endColumn - 1)) {
        expandedToTheRight = true;
        endColumn++;
      }
      if (!expandedToTheRight) {
        while (startColumn > 1 && this.j(lineContent, startColumn - 2)) {
          startColumn--;
        }
      }
      return createRangeWithPosition(startColumn, endColumn);
    };
    const prevWordOnLine = _$m6.c(wordSeparators2, model, position);
    if (prevWordOnLine && touchesWord(prevWordOnLine)) {
      return deleteWordAndAdjacentWhitespace(prevWordOnLine);
    }
    const nextWordOnLine = _$m6.f(wordSeparators2, model, position);
    if (nextWordOnLine && touchesWord(nextWordOnLine)) {
      return deleteWordAndAdjacentWhitespace(nextWordOnLine);
    }
    if (prevWordOnLine && nextWordOnLine) {
      return createRangeWithPosition(prevWordOnLine.end + 1, nextWordOnLine.start + 1);
    }
    if (prevWordOnLine) {
      return createRangeWithPosition(prevWordOnLine.start + 1, prevWordOnLine.end + 1);
    }
    if (nextWordOnLine) {
      return createRangeWithPosition(nextWordOnLine.start + 1, nextWordOnLine.end + 1);
    }
    return createRangeWithPosition(1, lineLength + 1);
  }
  static _deleteWordPartLeft(model, selection) {
    if (!selection.isEmpty()) {
      return selection;
    }
    const pos = selection.getPosition();
    const toPosition = _$m6._moveWordPartLeft(model, pos);
    return new $9C(pos.lineNumber, pos.column, toPosition.lineNumber, toPosition.column);
  }
  static m(str, startIndex) {
    const len = str.length;
    for (let chIndex = startIndex; chIndex < len; chIndex++) {
      const ch = str.charAt(chIndex);
      if (ch !== " " && ch !== "	") {
        return chIndex;
      }
    }
    return len;
  }
  static n(model, position) {
    const lineContent = model.getLineContent(position.lineNumber);
    const startIndex = position.column - 1;
    const firstNonWhitespace = this.m(lineContent, startIndex);
    if (startIndex + 1 < firstNonWhitespace) {
      return new $9C(position.lineNumber, position.column, position.lineNumber, firstNonWhitespace + 1);
    }
    return null;
  }
  static deleteWordRight(ctx, wordNavigationType) {
    const wordSeparators2 = ctx.wordSeparators;
    const model = ctx.model;
    const selection = ctx.selection;
    const whitespaceHeuristics = ctx.whitespaceHeuristics;
    if (!selection.isEmpty()) {
      return selection;
    }
    const position = new $8C(selection.positionLineNumber, selection.positionColumn);
    let lineNumber = position.lineNumber;
    let column = position.column;
    const lineCount = model.getLineCount();
    const maxColumn = model.getLineMaxColumn(lineNumber);
    if (lineNumber === lineCount && column === maxColumn) {
      return null;
    }
    if (whitespaceHeuristics) {
      const r2 = this.n(model, position);
      if (r2) {
        return r2;
      }
    }
    let nextWordOnLine = _$m6.f(wordSeparators2, model, position);
    if (wordNavigationType === 2) {
      if (nextWordOnLine) {
        column = nextWordOnLine.end + 1;
      } else {
        if (column < maxColumn || lineNumber === lineCount) {
          column = maxColumn;
        } else {
          lineNumber++;
          nextWordOnLine = _$m6.f(wordSeparators2, model, new $8C(lineNumber, 1));
          if (nextWordOnLine) {
            column = nextWordOnLine.start + 1;
          } else {
            column = model.getLineMaxColumn(lineNumber);
          }
        }
      }
    } else {
      if (nextWordOnLine && column >= nextWordOnLine.start + 1) {
        nextWordOnLine = _$m6.f(wordSeparators2, model, new $8C(lineNumber, nextWordOnLine.end + 1));
      }
      if (nextWordOnLine) {
        column = nextWordOnLine.start + 1;
      } else {
        if (column < maxColumn || lineNumber === lineCount) {
          column = maxColumn;
        } else {
          lineNumber++;
          nextWordOnLine = _$m6.f(wordSeparators2, model, new $8C(lineNumber, 1));
          if (nextWordOnLine) {
            column = nextWordOnLine.start + 1;
          } else {
            column = model.getLineMaxColumn(lineNumber);
          }
        }
      }
    }
    return new $9C(lineNumber, column, position.lineNumber, position.column);
  }
  static _deleteWordPartRight(model, selection) {
    if (!selection.isEmpty()) {
      return selection;
    }
    const pos = selection.getPosition();
    const toPosition = _$m6._moveWordPartRight(model, pos);
    return new $9C(pos.lineNumber, pos.column, toPosition.lineNumber, toPosition.column);
  }
  static o(model, lineNumber, word) {
    const range = new $9C(lineNumber, word.start + 1, lineNumber, word.end + 1);
    return {
      word: model.getValueInRange(range),
      startColumn: range.startColumn,
      endColumn: range.endColumn
    };
  }
  static getWordAtPosition(model, _wordSeparators, _intlSegmenterLocales, position) {
    const wordSeparators2 = $iE(_wordSeparators, _intlSegmenterLocales);
    const prevWord = _$m6.c(wordSeparators2, model, position);
    if (prevWord && prevWord.wordType === 1 && prevWord.start <= position.column - 1 && position.column - 1 <= prevWord.end) {
      return _$m6.o(model, position.lineNumber, prevWord);
    }
    const nextWord2 = _$m6.f(wordSeparators2, model, position);
    if (nextWord2 && nextWord2.wordType === 1 && nextWord2.start <= position.column - 1 && position.column - 1 <= nextWord2.end) {
      return _$m6.o(model, position.lineNumber, nextWord2);
    }
    return null;
  }
  static word(config, model, cursor, inSelectionMode, position) {
    const wordSeparators2 = $iE(config.wordSeparators, config.wordSegmenterLocales);
    const prevWord = _$m6.c(wordSeparators2, model, position);
    const nextWord2 = _$m6.f(wordSeparators2, model, position);
    if (!inSelectionMode) {
      let startColumn2;
      let endColumn2;
      if (prevWord && prevWord.wordType === 1 && prevWord.start <= position.column - 1 && position.column - 1 <= prevWord.end) {
        startColumn2 = prevWord.start + 1;
        endColumn2 = prevWord.end + 1;
      } else if (nextWord2 && nextWord2.wordType === 1 && nextWord2.start <= position.column - 1 && position.column - 1 <= nextWord2.end) {
        startColumn2 = nextWord2.start + 1;
        endColumn2 = nextWord2.end + 1;
      } else {
        if (prevWord) {
          startColumn2 = prevWord.end + 1;
        } else {
          startColumn2 = 1;
        }
        if (nextWord2) {
          endColumn2 = nextWord2.start + 1;
        } else {
          endColumn2 = model.getLineMaxColumn(position.lineNumber);
        }
      }
      return new $h5(new $9C(position.lineNumber, startColumn2, position.lineNumber, endColumn2), 1, 0, new $8C(position.lineNumber, endColumn2), 0);
    }
    let startColumn;
    let endColumn;
    if (prevWord && prevWord.wordType === 1 && prevWord.start < position.column - 1 && position.column - 1 < prevWord.end) {
      startColumn = prevWord.start + 1;
      endColumn = prevWord.end + 1;
    } else if (nextWord2 && nextWord2.wordType === 1 && nextWord2.start < position.column - 1 && position.column - 1 < nextWord2.end) {
      startColumn = nextWord2.start + 1;
      endColumn = nextWord2.end + 1;
    } else {
      startColumn = position.column;
      endColumn = position.column;
    }
    const lineNumber = position.lineNumber;
    let column;
    if (cursor.selectionStart.containsPosition(position)) {
      column = cursor.selectionStart.endColumn;
    } else if (position.isBeforeOrEqual(cursor.selectionStart.getStartPosition())) {
      column = startColumn;
      const possiblePosition = new $8C(lineNumber, column);
      if (cursor.selectionStart.containsPosition(possiblePosition)) {
        column = cursor.selectionStart.endColumn;
      }
    } else {
      column = endColumn;
      const possiblePosition = new $8C(lineNumber, column);
      if (cursor.selectionStart.containsPosition(possiblePosition)) {
        column = cursor.selectionStart.startColumn;
      }
    }
    return cursor.move(true, lineNumber, column, 0);
  }
};
var $n6 = class extends $m6 {
  static deleteWordPartLeft(ctx) {
    const candidates = enforceDefined([
      $m6.deleteWordLeft(
        ctx,
        0
        /* WordNavigationType.WordStart */
      ),
      $m6.deleteWordLeft(
        ctx,
        2
        /* WordNavigationType.WordEnd */
      ),
      $m6._deleteWordPartLeft(ctx.model, ctx.selection)
    ]);
    candidates.sort($9C.compareRangesUsingEnds);
    return candidates[2];
  }
  static deleteWordPartRight(ctx) {
    const candidates = enforceDefined([
      $m6.deleteWordRight(
        ctx,
        0
        /* WordNavigationType.WordStart */
      ),
      $m6.deleteWordRight(
        ctx,
        2
        /* WordNavigationType.WordEnd */
      ),
      $m6._deleteWordPartRight(ctx.model, ctx.selection)
    ]);
    candidates.sort($9C.compareRangesUsingStarts);
    return candidates[0];
  }
  static moveWordPartLeft(wordSeparators2, model, position, hasMulticursor) {
    const candidates = enforceDefined([
      $m6.moveWordLeft(wordSeparators2, model, position, 0, hasMulticursor),
      $m6.moveWordLeft(wordSeparators2, model, position, 2, hasMulticursor),
      $m6._moveWordPartLeft(model, position)
    ]);
    candidates.sort($8C.compare);
    return candidates[2];
  }
  static moveWordPartRight(wordSeparators2, model, position) {
    const candidates = enforceDefined([
      $m6.moveWordRight(
        wordSeparators2,
        model,
        position,
        0
        /* WordNavigationType.WordStart */
      ),
      $m6.moveWordRight(
        wordSeparators2,
        model,
        position,
        2
        /* WordNavigationType.WordEnd */
      ),
      $m6._moveWordPartRight(model, position)
    ]);
    candidates.sort($8C.compare);
    return candidates[0];
  }
};
function enforceDefined(arr) {
  return arr.filter((el) => Boolean(el));
}

// out-build/vs/editor/common/cursor/cursorMoveCommands.js
var $o6 = class {
  static addCursorDown(viewModel, cursors, useLogicalLine) {
    const result = [];
    let resultLen = 0;
    for (let i2 = 0, len = cursors.length; i2 < len; i2++) {
      const cursor = cursors[i2];
      result[resultLen++] = new $e5(cursor.modelState, cursor.viewState);
      if (useLogicalLine) {
        result[resultLen++] = $e5.fromModelState($k6.translateDown(viewModel.cursorConfig, viewModel.model, cursor.modelState));
      } else {
        result[resultLen++] = $e5.fromViewState($k6.translateDown(viewModel.cursorConfig, viewModel, cursor.viewState));
      }
    }
    return result;
  }
  static addCursorUp(viewModel, cursors, useLogicalLine) {
    const result = [];
    let resultLen = 0;
    for (let i2 = 0, len = cursors.length; i2 < len; i2++) {
      const cursor = cursors[i2];
      result[resultLen++] = new $e5(cursor.modelState, cursor.viewState);
      if (useLogicalLine) {
        result[resultLen++] = $e5.fromModelState($k6.translateUp(viewModel.cursorConfig, viewModel.model, cursor.modelState));
      } else {
        result[resultLen++] = $e5.fromViewState($k6.translateUp(viewModel.cursorConfig, viewModel, cursor.viewState));
      }
    }
    return result;
  }
  static moveToBeginningOfLine(viewModel, cursors, inSelectionMode) {
    const result = [];
    for (let i2 = 0, len = cursors.length; i2 < len; i2++) {
      const cursor = cursors[i2];
      result[i2] = this.a(viewModel, cursor, inSelectionMode);
    }
    return result;
  }
  static a(viewModel, cursor, inSelectionMode) {
    const currentViewStateColumn = cursor.viewState.position.column;
    const currentModelStateColumn = cursor.modelState.position.column;
    const isFirstLineOfWrappedLine = currentViewStateColumn === currentModelStateColumn;
    const currentViewStatelineNumber = cursor.viewState.position.lineNumber;
    const firstNonBlankColumn = viewModel.getLineFirstNonWhitespaceColumn(currentViewStatelineNumber);
    const isBeginningOfViewLine = currentViewStateColumn === firstNonBlankColumn;
    if (!isFirstLineOfWrappedLine && !isBeginningOfViewLine) {
      return this.b(viewModel, cursor, inSelectionMode);
    } else {
      return this.c(viewModel, cursor, inSelectionMode);
    }
  }
  static b(viewModel, cursor, inSelectionMode) {
    return $e5.fromViewState($k6.moveToBeginningOfLine(viewModel.cursorConfig, viewModel, cursor.viewState, inSelectionMode));
  }
  static c(viewModel, cursor, inSelectionMode) {
    return $e5.fromModelState($k6.moveToBeginningOfLine(viewModel.cursorConfig, viewModel.model, cursor.modelState, inSelectionMode));
  }
  static moveToEndOfLine(viewModel, cursors, inSelectionMode, sticky) {
    const result = [];
    for (let i2 = 0, len = cursors.length; i2 < len; i2++) {
      const cursor = cursors[i2];
      result[i2] = this.d(viewModel, cursor, inSelectionMode, sticky);
    }
    return result;
  }
  static d(viewModel, cursor, inSelectionMode, sticky) {
    const viewStatePosition = cursor.viewState.position;
    const viewModelMaxColumn = viewModel.getLineMaxColumn(viewStatePosition.lineNumber);
    const isEndOfViewLine = viewStatePosition.column === viewModelMaxColumn;
    const modelStatePosition = cursor.modelState.position;
    const modelMaxColumn = viewModel.model.getLineMaxColumn(modelStatePosition.lineNumber);
    const isEndLineOfWrappedLine = viewModelMaxColumn - viewStatePosition.column === modelMaxColumn - modelStatePosition.column;
    if (isEndOfViewLine || isEndLineOfWrappedLine) {
      return this.f(viewModel, cursor, inSelectionMode, sticky);
    } else {
      return this.e(viewModel, cursor, inSelectionMode, sticky);
    }
  }
  static e(viewModel, cursor, inSelectionMode, sticky) {
    return $e5.fromViewState($k6.moveToEndOfLine(viewModel.cursorConfig, viewModel, cursor.viewState, inSelectionMode, sticky));
  }
  static f(viewModel, cursor, inSelectionMode, sticky) {
    return $e5.fromModelState($k6.moveToEndOfLine(viewModel.cursorConfig, viewModel.model, cursor.modelState, inSelectionMode, sticky));
  }
  static expandLineSelection(viewModel, cursors) {
    const result = [];
    for (let i2 = 0, len = cursors.length; i2 < len; i2++) {
      const cursor = cursors[i2];
      const startLineNumber = cursor.modelState.selection.startLineNumber;
      const lineCount = viewModel.model.getLineCount();
      let endLineNumber = cursor.modelState.selection.endLineNumber;
      let endColumn;
      if (endLineNumber === lineCount) {
        endColumn = viewModel.model.getLineMaxColumn(lineCount);
      } else {
        endLineNumber++;
        endColumn = 1;
      }
      result[i2] = $e5.fromModelState(new $h5(new $9C(startLineNumber, 1, startLineNumber, 1), 0, 0, new $8C(endLineNumber, endColumn), 0));
    }
    return result;
  }
  static moveToBeginningOfBuffer(viewModel, cursors, inSelectionMode) {
    const result = [];
    for (let i2 = 0, len = cursors.length; i2 < len; i2++) {
      const cursor = cursors[i2];
      result[i2] = $e5.fromModelState($k6.moveToBeginningOfBuffer(viewModel.cursorConfig, viewModel.model, cursor.modelState, inSelectionMode));
    }
    return result;
  }
  static moveToEndOfBuffer(viewModel, cursors, inSelectionMode) {
    const result = [];
    for (let i2 = 0, len = cursors.length; i2 < len; i2++) {
      const cursor = cursors[i2];
      result[i2] = $e5.fromModelState($k6.moveToEndOfBuffer(viewModel.cursorConfig, viewModel.model, cursor.modelState, inSelectionMode));
    }
    return result;
  }
  static selectAll(viewModel, cursor) {
    const lineCount = viewModel.model.getLineCount();
    const maxColumn = viewModel.model.getLineMaxColumn(lineCount);
    return $e5.fromModelState(new $h5(new $9C(1, 1, 1, 1), 0, 0, new $8C(lineCount, maxColumn), 0));
  }
  static line(viewModel, cursor, inSelectionMode, _position, _viewPosition) {
    const position = viewModel.model.validatePosition(_position);
    const viewPosition = _viewPosition ? viewModel.coordinatesConverter.validateViewPosition(new $8C(_viewPosition.lineNumber, _viewPosition.column), position) : viewModel.coordinatesConverter.convertModelPositionToViewPosition(position);
    if (!inSelectionMode) {
      const lineCount = viewModel.model.getLineCount();
      let selectToLineNumber = position.lineNumber + 1;
      let selectToColumn = 1;
      if (selectToLineNumber > lineCount) {
        selectToLineNumber = lineCount;
        selectToColumn = viewModel.model.getLineMaxColumn(selectToLineNumber);
      }
      return $e5.fromModelState(new $h5(new $9C(position.lineNumber, 1, selectToLineNumber, selectToColumn), 2, 0, new $8C(selectToLineNumber, selectToColumn), 0));
    }
    const enteringLineNumber = cursor.modelState.selectionStart.getStartPosition().lineNumber;
    if (position.lineNumber < enteringLineNumber) {
      return $e5.fromViewState(cursor.viewState.move(true, viewPosition.lineNumber, 1, 0));
    } else if (position.lineNumber > enteringLineNumber) {
      const lineCount = viewModel.getLineCount();
      let selectToViewLineNumber = viewPosition.lineNumber + 1;
      let selectToViewColumn = 1;
      if (selectToViewLineNumber > lineCount) {
        selectToViewLineNumber = lineCount;
        selectToViewColumn = viewModel.getLineMaxColumn(selectToViewLineNumber);
      }
      return $e5.fromViewState(cursor.viewState.move(true, selectToViewLineNumber, selectToViewColumn, 0));
    } else {
      const endPositionOfSelectionStart = cursor.modelState.selectionStart.getEndPosition();
      return $e5.fromModelState(cursor.modelState.move(true, endPositionOfSelectionStart.lineNumber, endPositionOfSelectionStart.column, 0));
    }
  }
  static word(viewModel, cursor, inSelectionMode, _position) {
    const position = viewModel.model.validatePosition(_position);
    return $e5.fromModelState($m6.word(viewModel.cursorConfig, viewModel.model, cursor.modelState, inSelectionMode, position));
  }
  static cancelSelection(viewModel, cursor) {
    if (!cursor.modelState.hasSelection()) {
      return new $e5(cursor.modelState, cursor.viewState);
    }
    const lineNumber = cursor.viewState.position.lineNumber;
    const column = cursor.viewState.position.column;
    return $e5.fromViewState(new $h5(new $9C(lineNumber, column, lineNumber, column), 0, 0, new $8C(lineNumber, column), 0));
  }
  static moveTo(viewModel, cursor, inSelectionMode, _position, _viewPosition) {
    if (inSelectionMode) {
      if (cursor.modelState.selectionStartKind === 1) {
        return this.word(viewModel, cursor, inSelectionMode, _position);
      }
      if (cursor.modelState.selectionStartKind === 2) {
        return this.line(viewModel, cursor, inSelectionMode, _position, _viewPosition);
      }
    }
    const position = viewModel.model.validatePosition(_position);
    const viewPosition = _viewPosition ? viewModel.coordinatesConverter.validateViewPosition(new $8C(_viewPosition.lineNumber, _viewPosition.column), position) : viewModel.coordinatesConverter.convertModelPositionToViewPosition(position);
    return $e5.fromViewState(cursor.viewState.move(inSelectionMode, viewPosition.lineNumber, viewPosition.column, 0));
  }
  static simpleMove(viewModel, cursors, direction, inSelectionMode, value, unit) {
    switch (direction) {
      case 0: {
        if (unit === 4) {
          return this.k(viewModel, cursors, inSelectionMode);
        } else {
          return this.j(viewModel, cursors, inSelectionMode, value);
        }
      }
      case 1: {
        if (unit === 4) {
          return this.m(viewModel, cursors, inSelectionMode);
        } else {
          return this.l(viewModel, cursors, inSelectionMode, value);
        }
      }
      case 2: {
        if (unit === 2) {
          return this.p(viewModel, cursors, inSelectionMode, value);
        } else {
          return this.q(viewModel, cursors, inSelectionMode, value);
        }
      }
      case 3: {
        if (unit === 2) {
          return this.n(viewModel, cursors, inSelectionMode, value);
        } else {
          return this.o(viewModel, cursors, inSelectionMode, value);
        }
      }
      case 4: {
        if (unit === 2) {
          return cursors.map((cursor) => $e5.fromViewState($k6.moveToPrevBlankLine(viewModel.cursorConfig, viewModel, cursor.viewState, inSelectionMode)));
        } else {
          return cursors.map((cursor) => $e5.fromModelState($k6.moveToPrevBlankLine(viewModel.cursorConfig, viewModel.model, cursor.modelState, inSelectionMode)));
        }
      }
      case 5: {
        if (unit === 2) {
          return cursors.map((cursor) => $e5.fromViewState($k6.moveToNextBlankLine(viewModel.cursorConfig, viewModel, cursor.viewState, inSelectionMode)));
        } else {
          return cursors.map((cursor) => $e5.fromModelState($k6.moveToNextBlankLine(viewModel.cursorConfig, viewModel.model, cursor.modelState, inSelectionMode)));
        }
      }
      case 6: {
        return this.t(viewModel, cursors, inSelectionMode);
      }
      case 7: {
        return this.u(viewModel, cursors, inSelectionMode);
      }
      case 8: {
        return this.v(viewModel, cursors, inSelectionMode);
      }
      case 9: {
        return this.w(viewModel, cursors, inSelectionMode);
      }
      case 10: {
        return this.x(viewModel, cursors, inSelectionMode);
      }
      default:
        return null;
    }
  }
  static viewportMove(viewModel, cursors, direction, inSelectionMode, value) {
    const visibleViewRange = viewModel.getCompletelyVisibleViewRange();
    const visibleModelRange = viewModel.coordinatesConverter.convertViewRangeToModelRange(visibleViewRange);
    switch (direction) {
      case 11: {
        const modelLineNumber = this.g(viewModel.model, visibleModelRange, value);
        const modelColumn = viewModel.model.getLineFirstNonWhitespaceColumn(modelLineNumber);
        return [this.s(viewModel, cursors[0], inSelectionMode, modelLineNumber, modelColumn)];
      }
      case 13: {
        const modelLineNumber = this.h(viewModel.model, visibleModelRange, value);
        const modelColumn = viewModel.model.getLineFirstNonWhitespaceColumn(modelLineNumber);
        return [this.s(viewModel, cursors[0], inSelectionMode, modelLineNumber, modelColumn)];
      }
      case 12: {
        const modelLineNumber = Math.round((visibleModelRange.startLineNumber + visibleModelRange.endLineNumber) / 2);
        const modelColumn = viewModel.model.getLineFirstNonWhitespaceColumn(modelLineNumber);
        return [this.s(viewModel, cursors[0], inSelectionMode, modelLineNumber, modelColumn)];
      }
      case 14: {
        const result = [];
        for (let i2 = 0, len = cursors.length; i2 < len; i2++) {
          const cursor = cursors[i2];
          result[i2] = this.findPositionInViewportIfOutside(viewModel, cursor, visibleViewRange, inSelectionMode);
        }
        return result;
      }
      default:
        return null;
    }
  }
  static findPositionInViewportIfOutside(viewModel, cursor, visibleViewRange, inSelectionMode) {
    const viewLineNumber = cursor.viewState.position.lineNumber;
    if (visibleViewRange.startLineNumber <= viewLineNumber && viewLineNumber <= visibleViewRange.endLineNumber - 1) {
      return new $e5(cursor.modelState, cursor.viewState);
    } else {
      let newViewLineNumber;
      if (viewLineNumber > visibleViewRange.endLineNumber - 1) {
        newViewLineNumber = visibleViewRange.endLineNumber - 1;
      } else if (viewLineNumber < visibleViewRange.startLineNumber) {
        newViewLineNumber = visibleViewRange.startLineNumber;
      } else {
        newViewLineNumber = viewLineNumber;
      }
      const position = $k6.vertical(viewModel.cursorConfig, viewModel, viewLineNumber, cursor.viewState.position.column, cursor.viewState.leftoverVisibleColumns, newViewLineNumber, false);
      return $e5.fromViewState(cursor.viewState.move(inSelectionMode, position.lineNumber, position.column, position.leftoverVisibleColumns));
    }
  }
  /**
   * Find the nth line start included in the range (from the start).
   */
  static g(model, range, count) {
    let startLineNumber = range.startLineNumber;
    if (range.startColumn !== model.getLineMinColumn(startLineNumber)) {
      startLineNumber++;
    }
    return Math.min(range.endLineNumber, startLineNumber + count - 1);
  }
  /**
   * Find the nth line start included in the range (from the end).
   */
  static h(model, range, count) {
    let startLineNumber = range.startLineNumber;
    if (range.startColumn !== model.getLineMinColumn(startLineNumber)) {
      startLineNumber++;
    }
    return Math.max(startLineNumber, range.endLineNumber - count + 1);
  }
  static j(viewModel, cursors, inSelectionMode, noOfColumns) {
    return cursors.map((cursor) => $e5.fromViewState($k6.moveLeft(viewModel.cursorConfig, viewModel, cursor.viewState, inSelectionMode, noOfColumns)));
  }
  static k(viewModel, cursors, inSelectionMode) {
    const result = [];
    for (let i2 = 0, len = cursors.length; i2 < len; i2++) {
      const cursor = cursors[i2];
      const viewLineNumber = cursor.viewState.position.lineNumber;
      const halfLine = Math.round(viewModel.getLineLength(viewLineNumber) / 2);
      result[i2] = $e5.fromViewState($k6.moveLeft(viewModel.cursorConfig, viewModel, cursor.viewState, inSelectionMode, halfLine));
    }
    return result;
  }
  static l(viewModel, cursors, inSelectionMode, noOfColumns) {
    return cursors.map((cursor) => $e5.fromViewState($k6.moveRight(viewModel.cursorConfig, viewModel, cursor.viewState, inSelectionMode, noOfColumns)));
  }
  static m(viewModel, cursors, inSelectionMode) {
    const result = [];
    for (let i2 = 0, len = cursors.length; i2 < len; i2++) {
      const cursor = cursors[i2];
      const viewLineNumber = cursor.viewState.position.lineNumber;
      const halfLine = Math.round(viewModel.getLineLength(viewLineNumber) / 2);
      result[i2] = $e5.fromViewState($k6.moveRight(viewModel.cursorConfig, viewModel, cursor.viewState, inSelectionMode, halfLine));
    }
    return result;
  }
  static n(viewModel, cursors, inSelectionMode, linesCount) {
    const result = [];
    for (let i2 = 0, len = cursors.length; i2 < len; i2++) {
      const cursor = cursors[i2];
      result[i2] = $e5.fromViewState($k6.moveDown(viewModel.cursorConfig, viewModel, cursor.viewState, inSelectionMode, linesCount));
    }
    return result;
  }
  static o(viewModel, cursors, inSelectionMode, linesCount) {
    const result = [];
    for (let i2 = 0, len = cursors.length; i2 < len; i2++) {
      const cursor = cursors[i2];
      result[i2] = $e5.fromModelState($k6.moveDown(viewModel.cursorConfig, viewModel.model, cursor.modelState, inSelectionMode, linesCount));
    }
    return result;
  }
  static p(viewModel, cursors, inSelectionMode, linesCount) {
    const result = [];
    for (let i2 = 0, len = cursors.length; i2 < len; i2++) {
      const cursor = cursors[i2];
      result[i2] = $e5.fromViewState($k6.moveUp(viewModel.cursorConfig, viewModel, cursor.viewState, inSelectionMode, linesCount));
    }
    return result;
  }
  static q(viewModel, cursors, inSelectionMode, linesCount) {
    const result = [];
    for (let i2 = 0, len = cursors.length; i2 < len; i2++) {
      const cursor = cursors[i2];
      result[i2] = $e5.fromModelState($k6.moveUp(viewModel.cursorConfig, viewModel.model, cursor.modelState, inSelectionMode, linesCount));
    }
    return result;
  }
  static r(viewModel, cursor, inSelectionMode, toViewLineNumber, toViewColumn) {
    return $e5.fromViewState(cursor.viewState.move(inSelectionMode, toViewLineNumber, toViewColumn, 0));
  }
  static s(viewModel, cursor, inSelectionMode, toModelLineNumber, toModelColumn) {
    return $e5.fromModelState(cursor.modelState.move(inSelectionMode, toModelLineNumber, toModelColumn, 0));
  }
  static t(viewModel, cursors, inSelectionMode) {
    const result = [];
    for (let i2 = 0, len = cursors.length; i2 < len; i2++) {
      const cursor = cursors[i2];
      const viewLineNumber = cursor.viewState.position.lineNumber;
      const viewColumn = viewModel.getLineMinColumn(viewLineNumber);
      result[i2] = this.r(viewModel, cursor, inSelectionMode, viewLineNumber, viewColumn);
    }
    return result;
  }
  static u(viewModel, cursors, inSelectionMode) {
    const result = [];
    for (let i2 = 0, len = cursors.length; i2 < len; i2++) {
      const cursor = cursors[i2];
      const viewLineNumber = cursor.viewState.position.lineNumber;
      const viewColumn = viewModel.getLineFirstNonWhitespaceColumn(viewLineNumber);
      result[i2] = this.r(viewModel, cursor, inSelectionMode, viewLineNumber, viewColumn);
    }
    return result;
  }
  static v(viewModel, cursors, inSelectionMode) {
    const result = [];
    for (let i2 = 0, len = cursors.length; i2 < len; i2++) {
      const cursor = cursors[i2];
      const viewLineNumber = cursor.viewState.position.lineNumber;
      const viewColumn = Math.round((viewModel.getLineMaxColumn(viewLineNumber) + viewModel.getLineMinColumn(viewLineNumber)) / 2);
      result[i2] = this.r(viewModel, cursor, inSelectionMode, viewLineNumber, viewColumn);
    }
    return result;
  }
  static w(viewModel, cursors, inSelectionMode) {
    const result = [];
    for (let i2 = 0, len = cursors.length; i2 < len; i2++) {
      const cursor = cursors[i2];
      const viewLineNumber = cursor.viewState.position.lineNumber;
      const viewColumn = viewModel.getLineMaxColumn(viewLineNumber);
      result[i2] = this.r(viewModel, cursor, inSelectionMode, viewLineNumber, viewColumn);
    }
    return result;
  }
  static x(viewModel, cursors, inSelectionMode) {
    const result = [];
    for (let i2 = 0, len = cursors.length; i2 < len; i2++) {
      const cursor = cursors[i2];
      const viewLineNumber = cursor.viewState.position.lineNumber;
      const viewColumn = viewModel.getLineLastNonWhitespaceColumn(viewLineNumber);
      result[i2] = this.r(viewModel, cursor, inSelectionMode, viewLineNumber, viewColumn);
    }
    return result;
  }
};
var CursorMove;
(function(CursorMove2) {
  const isCursorMoveArgs = function(arg) {
    if (!$Bg(arg)) {
      return false;
    }
    const cursorMoveArg = arg;
    if (!$zg(cursorMoveArg.to)) {
      return false;
    }
    if (!$Gg(cursorMoveArg.select) && !$Fg(cursorMoveArg.select)) {
      return false;
    }
    if (!$Gg(cursorMoveArg.by) && !$zg(cursorMoveArg.by)) {
      return false;
    }
    if (!$Gg(cursorMoveArg.value) && !$Dg(cursorMoveArg.value)) {
      return false;
    }
    return true;
  };
  CursorMove2.metadata = {
    description: "Move cursor to a logical position in the view",
    args: [
      {
        name: "Cursor move argument object",
        description: `Property-value pairs that can be passed through this argument:
					* 'to': A mandatory logical position value providing where to move the cursor.
						\`\`\`
						'left', 'right', 'up', 'down', 'prevBlankLine', 'nextBlankLine',
						'wrappedLineStart', 'wrappedLineEnd', 'wrappedLineColumnCenter'
						'wrappedLineFirstNonWhitespaceCharacter', 'wrappedLineLastNonWhitespaceCharacter'
						'viewPortTop', 'viewPortCenter', 'viewPortBottom', 'viewPortIfOutside'
						\`\`\`
					* 'by': Unit to move. Default is computed based on 'to' value.
						\`\`\`
						'line', 'wrappedLine', 'character', 'halfLine'
						\`\`\`
					* 'value': Number of units to move. Default is '1'.
					* 'select': If 'true' makes the selection. Default is 'false'.
				`,
        constraint: isCursorMoveArgs,
        schema: {
          "type": "object",
          "required": ["to"],
          "properties": {
            "to": {
              "type": "string",
              "enum": ["left", "right", "up", "down", "prevBlankLine", "nextBlankLine", "wrappedLineStart", "wrappedLineEnd", "wrappedLineColumnCenter", "wrappedLineFirstNonWhitespaceCharacter", "wrappedLineLastNonWhitespaceCharacter", "viewPortTop", "viewPortCenter", "viewPortBottom", "viewPortIfOutside"]
            },
            "by": {
              "type": "string",
              "enum": ["line", "wrappedLine", "character", "halfLine"]
            },
            "value": {
              "type": "number",
              "default": 1
            },
            "select": {
              "type": "boolean",
              "default": false
            }
          }
        }
      }
    ]
  };
  CursorMove2.RawDirection = {
    Left: "left",
    Right: "right",
    Up: "up",
    Down: "down",
    PrevBlankLine: "prevBlankLine",
    NextBlankLine: "nextBlankLine",
    WrappedLineStart: "wrappedLineStart",
    WrappedLineFirstNonWhitespaceCharacter: "wrappedLineFirstNonWhitespaceCharacter",
    WrappedLineColumnCenter: "wrappedLineColumnCenter",
    WrappedLineEnd: "wrappedLineEnd",
    WrappedLineLastNonWhitespaceCharacter: "wrappedLineLastNonWhitespaceCharacter",
    ViewPortTop: "viewPortTop",
    ViewPortCenter: "viewPortCenter",
    ViewPortBottom: "viewPortBottom",
    ViewPortIfOutside: "viewPortIfOutside"
  };
  CursorMove2.RawUnit = {
    Line: "line",
    WrappedLine: "wrappedLine",
    Character: "character",
    HalfLine: "halfLine"
  };
  function parse4(args2) {
    if (!args2.to) {
      return null;
    }
    let direction;
    switch (args2.to) {
      case CursorMove2.RawDirection.Left:
        direction = 0;
        break;
      case CursorMove2.RawDirection.Right:
        direction = 1;
        break;
      case CursorMove2.RawDirection.Up:
        direction = 2;
        break;
      case CursorMove2.RawDirection.Down:
        direction = 3;
        break;
      case CursorMove2.RawDirection.PrevBlankLine:
        direction = 4;
        break;
      case CursorMove2.RawDirection.NextBlankLine:
        direction = 5;
        break;
      case CursorMove2.RawDirection.WrappedLineStart:
        direction = 6;
        break;
      case CursorMove2.RawDirection.WrappedLineFirstNonWhitespaceCharacter:
        direction = 7;
        break;
      case CursorMove2.RawDirection.WrappedLineColumnCenter:
        direction = 8;
        break;
      case CursorMove2.RawDirection.WrappedLineEnd:
        direction = 9;
        break;
      case CursorMove2.RawDirection.WrappedLineLastNonWhitespaceCharacter:
        direction = 10;
        break;
      case CursorMove2.RawDirection.ViewPortTop:
        direction = 11;
        break;
      case CursorMove2.RawDirection.ViewPortBottom:
        direction = 13;
        break;
      case CursorMove2.RawDirection.ViewPortCenter:
        direction = 12;
        break;
      case CursorMove2.RawDirection.ViewPortIfOutside:
        direction = 14;
        break;
      default:
        return null;
    }
    let unit = 0;
    switch (args2.by) {
      case CursorMove2.RawUnit.Line:
        unit = 1;
        break;
      case CursorMove2.RawUnit.WrappedLine:
        unit = 2;
        break;
      case CursorMove2.RawUnit.Character:
        unit = 3;
        break;
      case CursorMove2.RawUnit.HalfLine:
        unit = 4;
        break;
    }
    return {
      direction,
      unit,
      select: !!args2.select,
      value: args2.value || 1
    };
  }
  CursorMove2.parse = parse4;
  let Direction4;
  (function(Direction5) {
    Direction5[Direction5["Left"] = 0] = "Left";
    Direction5[Direction5["Right"] = 1] = "Right";
    Direction5[Direction5["Up"] = 2] = "Up";
    Direction5[Direction5["Down"] = 3] = "Down";
    Direction5[Direction5["PrevBlankLine"] = 4] = "PrevBlankLine";
    Direction5[Direction5["NextBlankLine"] = 5] = "NextBlankLine";
    Direction5[Direction5["WrappedLineStart"] = 6] = "WrappedLineStart";
    Direction5[Direction5["WrappedLineFirstNonWhitespaceCharacter"] = 7] = "WrappedLineFirstNonWhitespaceCharacter";
    Direction5[Direction5["WrappedLineColumnCenter"] = 8] = "WrappedLineColumnCenter";
    Direction5[Direction5["WrappedLineEnd"] = 9] = "WrappedLineEnd";
    Direction5[Direction5["WrappedLineLastNonWhitespaceCharacter"] = 10] = "WrappedLineLastNonWhitespaceCharacter";
    Direction5[Direction5["ViewPortTop"] = 11] = "ViewPortTop";
    Direction5[Direction5["ViewPortCenter"] = 12] = "ViewPortCenter";
    Direction5[Direction5["ViewPortBottom"] = 13] = "ViewPortBottom";
    Direction5[Direction5["ViewPortIfOutside"] = 14] = "ViewPortIfOutside";
  })(Direction4 = CursorMove2.Direction || (CursorMove2.Direction = {}));
  let Unit;
  (function(Unit2) {
    Unit2[Unit2["None"] = 0] = "None";
    Unit2[Unit2["Line"] = 1] = "Line";
    Unit2[Unit2["WrappedLine"] = 2] = "WrappedLine";
    Unit2[Unit2["Character"] = 3] = "Character";
    Unit2[Unit2["HalfLine"] = 4] = "HalfLine";
  })(Unit = CursorMove2.Unit || (CursorMove2.Unit = {}));
})(CursorMove || (CursorMove = {}));

// out-build/vs/editor/common/languages/languageConfiguration.js
var IndentAction;
(function(IndentAction3) {
  IndentAction3[IndentAction3["None"] = 0] = "None";
  IndentAction3[IndentAction3["Indent"] = 1] = "Indent";
  IndentAction3[IndentAction3["IndentOutdent"] = 2] = "IndentOutdent";
  IndentAction3[IndentAction3["Outdent"] = 3] = "Outdent";
})(IndentAction || (IndentAction = {}));
var $5E = class {
  constructor(source) {
    this.e = null;
    this.f = false;
    this.open = source.open;
    this.close = source.close;
    this.b = true;
    this.c = true;
    this.d = true;
    if (Array.isArray(source.notIn)) {
      for (let i2 = 0, len = source.notIn.length; i2 < len; i2++) {
        const notIn = source.notIn[i2];
        switch (notIn) {
          case "string":
            this.b = false;
            break;
          case "comment":
            this.c = false;
            break;
          case "regex":
            this.d = false;
            break;
        }
      }
    }
  }
  isOK(standardToken) {
    switch (standardToken) {
      case 0:
        return true;
      case 1:
        return this.c;
      case 2:
        return this.b;
      case 3:
        return this.d;
    }
  }
  shouldAutoClose(context, column) {
    if (context.getTokenCount() === 0) {
      return true;
    }
    const tokenIndex = context.findTokenIndexAtOffset(column - 2);
    const standardTokenType = context.getStandardTokenType(tokenIndex);
    return this.isOK(standardTokenType);
  }
  g(fromCharCode, toCharCode) {
    for (let charCode = fromCharCode; charCode <= toCharCode; charCode++) {
      const character = String.fromCharCode(charCode);
      if (!this.open.includes(character) && !this.close.includes(character)) {
        return character;
      }
    }
    return null;
  }
  /**
   * Find a character in the range [0-9a-zA-Z] that does not appear in the open or close
   */
  findNeutralCharacter() {
    if (!this.f) {
      this.f = true;
      if (!this.e) {
        this.e = this.g(
          48,
          57
          /* CharCode.Digit9 */
        );
      }
      if (!this.e) {
        this.e = this.g(
          97,
          122
          /* CharCode.z */
        );
      }
      if (!this.e) {
        this.e = this.g(
          65,
          90
          /* CharCode.Z */
        );
      }
    }
    return this.e;
  }
};
var $6E = class {
  constructor(autoClosingPairs) {
    this.autoClosingPairsOpenByStart = /* @__PURE__ */ new Map();
    this.autoClosingPairsOpenByEnd = /* @__PURE__ */ new Map();
    this.autoClosingPairsCloseByStart = /* @__PURE__ */ new Map();
    this.autoClosingPairsCloseByEnd = /* @__PURE__ */ new Map();
    this.autoClosingPairsCloseSingleChar = /* @__PURE__ */ new Map();
    for (const pair of autoClosingPairs) {
      appendEntry(this.autoClosingPairsOpenByStart, pair.open.charAt(0), pair);
      appendEntry(this.autoClosingPairsOpenByEnd, pair.open.charAt(pair.open.length - 1), pair);
      appendEntry(this.autoClosingPairsCloseByStart, pair.close.charAt(0), pair);
      appendEntry(this.autoClosingPairsCloseByEnd, pair.close.charAt(pair.close.length - 1), pair);
      if (pair.close.length === 1 && pair.open.length === 1) {
        appendEntry(this.autoClosingPairsCloseSingleChar, pair.close, pair);
      }
    }
  }
};
function appendEntry(target, key2, value) {
  if (target.has(key2)) {
    target.get(key2).push(value);
  } else {
    target.set(key2, [value]);
  }
}

// out-build/vs/editor/common/core/wordHelper.js
var $ID = "`~!@#$%^&*()-=+[{]}\\|;:'\",.<>/?";
function createWordRegExp(allowInWords = "") {
  let source = "(-?\\d*\\.\\d\\w*)|([^";
  for (const sep2 of $ID) {
    if (allowInWords.indexOf(sep2) >= 0) {
      continue;
    }
    source += "\\" + sep2;
  }
  source += "\\s]+)";
  return new RegExp(source, "g");
}
var $JD = createWordRegExp();
function $KD(wordDefinition) {
  let result = $JD;
  if (wordDefinition && wordDefinition instanceof RegExp) {
    if (!wordDefinition.global) {
      let flags = "g";
      if (wordDefinition.ignoreCase) {
        flags += "i";
      }
      if (wordDefinition.multiline) {
        flags += "m";
      }
      if (wordDefinition.unicode) {
        flags += "u";
      }
      result = new RegExp(wordDefinition.source, flags);
    } else {
      result = wordDefinition;
    }
  }
  result.lastIndex = 0;
  return result;
}
var _defaultConfig = new $cd();
_defaultConfig.unshift({
  maxLen: 1e3,
  windowSize: 15,
  timeBudget: 150
});
function $MD(column, wordDefinition, text2, textOffset, config) {
  wordDefinition = $KD(wordDefinition);
  if (!config) {
    config = Iterable.first(_defaultConfig);
  }
  if (text2.length > config.maxLen) {
    let start = column - config.maxLen / 2;
    if (start < 0) {
      start = 0;
    } else {
      textOffset += start;
    }
    text2 = text2.substring(start, column + config.maxLen / 2);
    return $MD(column, wordDefinition, text2, textOffset, config);
  }
  const t1 = Date.now();
  const pos = column - 1 - textOffset;
  let prevRegexIndex = -1;
  let match = null;
  for (let i2 = 1; ; i2++) {
    if (Date.now() - t1 >= config.timeBudget) {
      break;
    }
    const regexIndex = pos - config.windowSize * i2;
    wordDefinition.lastIndex = Math.max(0, regexIndex);
    const thisMatch = _findRegexMatchEnclosingPosition(wordDefinition, text2, pos, prevRegexIndex);
    if (!thisMatch && match) {
      break;
    }
    match = thisMatch;
    if (regexIndex <= 0) {
      break;
    }
    prevRegexIndex = regexIndex;
  }
  if (match) {
    const result = {
      word: match[0],
      startColumn: textOffset + 1 + match.index,
      endColumn: textOffset + 1 + match.index + match[0].length
    };
    wordDefinition.lastIndex = 0;
    return result;
  }
  return null;
}
function _findRegexMatchEnclosingPosition(wordDefinition, text2, pos, stopPos) {
  let match;
  while (match = wordDefinition.exec(text2)) {
    const matchIndex = match.index || 0;
    if (matchIndex <= pos && wordDefinition.lastIndex >= pos) {
      return match;
    } else if (stopPos > 0 && matchIndex > stopPos) {
      return null;
    }
  }
  return null;
}

// out-build/vs/editor/common/languages/supports/characterPair.js
var $DF = class _$DF {
  static {
    this.DEFAULT_AUTOCLOSE_BEFORE_LANGUAGE_DEFINED_QUOTES = ";:.,=}])> \n	";
  }
  static {
    this.DEFAULT_AUTOCLOSE_BEFORE_LANGUAGE_DEFINED_BRACKETS = "'\"`;:.,=}])> \n	";
  }
  static {
    this.DEFAULT_AUTOCLOSE_BEFORE_WHITESPACE = " \n	";
  }
  constructor(config) {
    if (config.autoClosingPairs) {
      this.a = config.autoClosingPairs.map((el) => new $5E(el));
    } else if (config.brackets) {
      this.a = config.brackets.map((b) => new $5E({ open: b[0], close: b[1] }));
    } else {
      this.a = [];
    }
    if (config.__electricCharacterSupport && config.__electricCharacterSupport.docComment) {
      const docComment = config.__electricCharacterSupport.docComment;
      this.a.push(new $5E({ open: docComment.open, close: docComment.close || "" }));
    }
    this.d = typeof config.autoCloseBefore === "string" ? config.autoCloseBefore : _$DF.DEFAULT_AUTOCLOSE_BEFORE_LANGUAGE_DEFINED_QUOTES;
    this.e = typeof config.autoCloseBefore === "string" ? config.autoCloseBefore : _$DF.DEFAULT_AUTOCLOSE_BEFORE_LANGUAGE_DEFINED_BRACKETS;
    this.c = config.surroundingPairs || this.a;
  }
  getAutoClosingPairs() {
    return this.a;
  }
  getAutoCloseBeforeSet(forQuotes) {
    return forQuotes ? this.d : this.e;
  }
  getSurroundingPairs() {
    return this.c;
  }
};

// out-build/vs/editor/common/core/stringBuilder.js
var _utf16LE_TextDecoder;
function getUTF16LE_TextDecoder() {
  if (!_utf16LE_TextDecoder) {
    _utf16LE_TextDecoder = new TextDecoder("UTF-16LE");
  }
  return _utf16LE_TextDecoder;
}
var _utf16BE_TextDecoder;
function getUTF16BE_TextDecoder() {
  if (!_utf16BE_TextDecoder) {
    _utf16BE_TextDecoder = new TextDecoder("UTF-16BE");
  }
  return _utf16BE_TextDecoder;
}
var _platformTextDecoder;
function $aE() {
  if (!_platformTextDecoder) {
    _platformTextDecoder = $G() ? getUTF16LE_TextDecoder() : getUTF16BE_TextDecoder();
  }
  return _platformTextDecoder;
}
function $bE(source, offset, len) {
  const view = new Uint16Array(source.buffer, offset, len);
  if (len > 0 && (view[0] === 65279 || view[0] === 65534)) {
    return compatDecodeUTF16LE(source, offset, len);
  }
  return getUTF16LE_TextDecoder().decode(view);
}
function compatDecodeUTF16LE(source, offset, len) {
  const result = [];
  let resultLen = 0;
  for (let i2 = 0; i2 < len; i2++) {
    const charCode = $Ei(source, offset);
    offset += 2;
    result[resultLen++] = String.fromCharCode(charCode);
  }
  return result.join("");
}
var $cE = class {
  constructor(capacity) {
    this.a = capacity | 0;
    this.b = new Uint16Array(this.a);
    this.c = null;
    this.d = 0;
  }
  reset() {
    this.c = null;
    this.d = 0;
  }
  build() {
    if (this.c !== null) {
      this.f();
      return this.c.join("");
    }
    return this.e();
  }
  e() {
    if (this.d === 0) {
      return "";
    }
    const view = new Uint16Array(this.b.buffer, 0, this.d);
    return $aE().decode(view);
  }
  f() {
    const bufferString = this.e();
    this.d = 0;
    if (this.c === null) {
      this.c = [bufferString];
    } else {
      this.c[this.c.length] = bufferString;
    }
  }
  /**
   * Append a char code (<2^16)
   */
  appendCharCode(charCode) {
    const remainingSpace = this.a - this.d;
    if (remainingSpace <= 1) {
      if (remainingSpace === 0 || $5f(charCode)) {
        this.f();
      }
    }
    this.b[this.d++] = charCode;
  }
  /**
   * Append an ASCII char code (<2^8)
   */
  appendASCIICharCode(charCode) {
    if (this.d === this.a) {
      this.f();
    }
    this.b[this.d++] = charCode;
  }
  appendString(str) {
    const strLen = str.length;
    if (this.d + strLen >= this.a) {
      this.f();
      this.c[this.c.length] = str;
      return;
    }
    for (let i2 = 0; i2 < strLen; i2++) {
      this.b[this.d++] = str.charCodeAt(i2);
    }
  }
};

// out-build/vs/editor/common/languages/supports/richEditBrackets.js
var $7E = class _$7E {
  constructor(languageId, index, open2, close2, forwardRegex, reversedRegex) {
    this._richEditBracketBrand = void 0;
    this.languageId = languageId;
    this.index = index;
    this.open = open2;
    this.close = close2;
    this.forwardRegex = forwardRegex;
    this.reversedRegex = reversedRegex;
    this.c = _$7E.e(this.open);
    this.d = _$7E.e(this.close);
  }
  /**
   * Check if the provided `text` is an open bracket in this group.
   */
  isOpen(text2) {
    return this.c.has(text2);
  }
  /**
   * Check if the provided `text` is a close bracket in this group.
   */
  isClose(text2) {
    return this.d.has(text2);
  }
  static e(arr) {
    const result = /* @__PURE__ */ new Set();
    for (const element of arr) {
      result.add(element);
    }
    return result;
  }
};
function groupFuzzyBrackets(brackets) {
  const N = brackets.length;
  brackets = brackets.map((b) => [b[0].toLowerCase(), b[1].toLowerCase()]);
  const group2 = [];
  for (let i2 = 0; i2 < N; i2++) {
    group2[i2] = i2;
  }
  const areOverlapping = (a, b) => {
    const [aOpen, aClose] = a;
    const [bOpen, bClose] = b;
    return aOpen === bOpen || aOpen === bClose || aClose === bOpen || aClose === bClose;
  };
  const mergeGroups = (g1, g2) => {
    const newG = Math.min(g1, g2);
    const oldG = Math.max(g1, g2);
    for (let i2 = 0; i2 < N; i2++) {
      if (group2[i2] === oldG) {
        group2[i2] = newG;
      }
    }
  };
  for (let i2 = 0; i2 < N; i2++) {
    const a = brackets[i2];
    for (let j = i2 + 1; j < N; j++) {
      const b = brackets[j];
      if (areOverlapping(a, b)) {
        mergeGroups(group2[i2], group2[j]);
      }
    }
  }
  const result = [];
  for (let g = 0; g < N; g++) {
    const currentOpen = [];
    const currentClose = [];
    for (let i2 = 0; i2 < N; i2++) {
      if (group2[i2] === g) {
        const [open2, close2] = brackets[i2];
        currentOpen.push(open2);
        currentClose.push(close2);
      }
    }
    if (currentOpen.length > 0) {
      result.push({
        open: currentOpen,
        close: currentClose
      });
    }
  }
  return result;
}
var $8E = class {
  constructor(languageId, _brackets) {
    this._richEditBracketsBrand = void 0;
    const brackets = groupFuzzyBrackets(_brackets);
    this.brackets = brackets.map((b, index) => {
      return new $7E(languageId, index, b.open, b.close, getRegexForBracketPair(b.open, b.close, brackets, index), getReversedRegexForBracketPair(b.open, b.close, brackets, index));
    });
    this.forwardRegex = getRegexForBrackets(this.brackets);
    this.reversedRegex = getReversedRegexForBrackets(this.brackets);
    this.textIsBracket = {};
    this.textIsOpenBracket = {};
    this.maxBracketLength = 0;
    for (const bracket of this.brackets) {
      for (const open2 of bracket.open) {
        this.textIsBracket[open2] = bracket;
        this.textIsOpenBracket[open2] = true;
        this.maxBracketLength = Math.max(this.maxBracketLength, open2.length);
      }
      for (const close2 of bracket.close) {
        this.textIsBracket[close2] = bracket;
        this.textIsOpenBracket[close2] = false;
        this.maxBracketLength = Math.max(this.maxBracketLength, close2.length);
      }
    }
  }
};
function collectSuperstrings(str, brackets, currentIndex, dest) {
  for (let i2 = 0, len = brackets.length; i2 < len; i2++) {
    if (i2 === currentIndex) {
      continue;
    }
    const bracket = brackets[i2];
    for (const open2 of bracket.open) {
      if (open2.indexOf(str) >= 0) {
        dest.push(open2);
      }
    }
    for (const close2 of bracket.close) {
      if (close2.indexOf(str) >= 0) {
        dest.push(close2);
      }
    }
  }
}
function lengthcmp(a, b) {
  return a.length - b.length;
}
function unique(arr) {
  if (arr.length <= 1) {
    return arr;
  }
  const result = [];
  const seen = /* @__PURE__ */ new Set();
  for (const element of arr) {
    if (seen.has(element)) {
      continue;
    }
    result.push(element);
    seen.add(element);
  }
  return result;
}
function getRegexForBracketPair(open2, close2, brackets, currentIndex) {
  let pieces = [];
  pieces = pieces.concat(open2);
  pieces = pieces.concat(close2);
  for (let i2 = 0, len = pieces.length; i2 < len; i2++) {
    collectSuperstrings(pieces[i2], brackets, currentIndex, pieces);
  }
  pieces = unique(pieces);
  pieces.sort(lengthcmp);
  pieces.reverse();
  return $9E(pieces);
}
function getReversedRegexForBracketPair(open2, close2, brackets, currentIndex) {
  let pieces = [];
  pieces = pieces.concat(open2);
  pieces = pieces.concat(close2);
  for (let i2 = 0, len = pieces.length; i2 < len; i2++) {
    collectSuperstrings(pieces[i2], brackets, currentIndex, pieces);
  }
  pieces = unique(pieces);
  pieces.sort(lengthcmp);
  pieces.reverse();
  return $9E(pieces.map(toReversedString));
}
function getRegexForBrackets(brackets) {
  let pieces = [];
  for (const bracket of brackets) {
    for (const open2 of bracket.open) {
      pieces.push(open2);
    }
    for (const close2 of bracket.close) {
      pieces.push(close2);
    }
  }
  pieces = unique(pieces);
  return $9E(pieces);
}
function getReversedRegexForBrackets(brackets) {
  let pieces = [];
  for (const bracket of brackets) {
    for (const open2 of bracket.open) {
      pieces.push(open2);
    }
    for (const close2 of bracket.close) {
      pieces.push(close2);
    }
  }
  pieces = unique(pieces);
  return $9E(pieces.map(toReversedString));
}
function prepareBracketForRegExp(str) {
  const insertWordBoundaries = /^[\w ]+$/.test(str);
  str = $Af(str);
  return insertWordBoundaries ? `\\b${str}\\b` : str;
}
function $9E(pieces, options3) {
  const regexStr = `(${pieces.map(prepareBracketForRegExp).join(")|(")})`;
  return $Jf(regexStr, true, options3);
}
var toReversedString = /* @__PURE__ */ function() {
  function reverse(str) {
    const arr = new Uint16Array(str.length);
    let offset = 0;
    for (let i2 = str.length - 1; i2 >= 0; i2--) {
      arr[offset++] = str.charCodeAt(i2);
    }
    return $aE().decode(arr);
  }
  let lastInput = null;
  let lastOutput = null;
  return function toReversedString2(str) {
    if (lastInput !== str) {
      lastInput = str;
      lastOutput = reverse(lastInput);
    }
    return lastOutput;
  };
}();
var $0E = class {
  static c(reversedBracketRegex, lineNumber, reversedText, offset) {
    const m = reversedText.match(reversedBracketRegex);
    if (!m) {
      return null;
    }
    const matchOffset = reversedText.length - (m.index || 0);
    const matchLength = m[0].length;
    const absoluteMatchOffset = offset + matchOffset;
    return new $9C(lineNumber, absoluteMatchOffset - matchLength + 1, lineNumber, absoluteMatchOffset + 1);
  }
  static findPrevBracketInRange(reversedBracketRegex, lineNumber, lineText, startOffset, endOffset) {
    const reversedLineText = toReversedString(lineText);
    const reversedSubstr = reversedLineText.substring(lineText.length - endOffset, lineText.length - startOffset);
    return this.c(reversedBracketRegex, lineNumber, reversedSubstr, startOffset);
  }
  static findNextBracketInText(bracketRegex, lineNumber, text2, offset) {
    const m = text2.match(bracketRegex);
    if (!m) {
      return null;
    }
    const matchOffset = m.index || 0;
    const matchLength = m[0].length;
    if (matchLength === 0) {
      return null;
    }
    const absoluteMatchOffset = offset + matchOffset;
    return new $9C(lineNumber, absoluteMatchOffset + 1, lineNumber, absoluteMatchOffset + 1 + matchLength);
  }
  static findNextBracketInRange(bracketRegex, lineNumber, lineText, startOffset, endOffset) {
    const substr = lineText.substring(startOffset, endOffset);
    return this.findNextBracketInText(bracketRegex, lineNumber, substr, startOffset);
  }
};

// out-build/vs/editor/common/languages/supports/electricCharacter.js
var $EF = class {
  constructor(richEditBrackets) {
    this.a = richEditBrackets;
  }
  getElectricCharacters() {
    const result = [];
    if (this.a) {
      for (const bracket of this.a.brackets) {
        for (const close2 of bracket.close) {
          const lastChar = close2.charAt(close2.length - 1);
          result.push(lastChar);
        }
      }
    }
    return $Rb(result);
  }
  onElectricCharacter(character, context, column) {
    if (!this.a || this.a.brackets.length === 0) {
      return null;
    }
    const tokenIndex = context.findTokenIndexAtOffset(column - 1);
    if ($4E(context.getStandardTokenType(tokenIndex))) {
      return null;
    }
    const reversedBracketRegex = this.a.reversedRegex;
    const text2 = context.getLineContent().substring(0, column - 1) + character;
    const r2 = $0E.findPrevBracketInRange(reversedBracketRegex, 1, text2, 0, text2.length);
    if (!r2) {
      return null;
    }
    const bracketText = text2.substring(r2.startColumn - 1, r2.endColumn - 1).toLowerCase();
    const isOpen = this.a.textIsOpenBracket[bracketText];
    if (isOpen) {
      return null;
    }
    const textBeforeBracket = context.getActualLineContentBefore(r2.startColumn - 1);
    if (!/^\s*$/.test(textBeforeBracket)) {
      return null;
    }
    return {
      matchOpenBracket: bracketText
    };
  }
};

// out-build/vs/editor/common/languages/supports/indentRules.js
var IndentConsts;
(function(IndentConsts2) {
  IndentConsts2[IndentConsts2["INCREASE_MASK"] = 1] = "INCREASE_MASK";
  IndentConsts2[IndentConsts2["DECREASE_MASK"] = 2] = "DECREASE_MASK";
  IndentConsts2[IndentConsts2["INDENT_NEXTLINE_MASK"] = 4] = "INDENT_NEXTLINE_MASK";
  IndentConsts2[IndentConsts2["UNINDENT_MASK"] = 8] = "UNINDENT_MASK";
})(IndentConsts || (IndentConsts = {}));
function resetGlobalRegex(reg2) {
  if (reg2.global) {
    reg2.lastIndex = 0;
  }
  return true;
}
var $FF = class {
  constructor(indentationRules) {
    this.a = indentationRules;
  }
  shouldIncrease(text2) {
    if (this.a) {
      if (this.a.increaseIndentPattern && resetGlobalRegex(this.a.increaseIndentPattern) && this.a.increaseIndentPattern.test(text2)) {
        return true;
      }
    }
    return false;
  }
  shouldDecrease(text2) {
    if (this.a && this.a.decreaseIndentPattern && resetGlobalRegex(this.a.decreaseIndentPattern) && this.a.decreaseIndentPattern.test(text2)) {
      return true;
    }
    return false;
  }
  shouldIndentNextLine(text2) {
    if (this.a && this.a.indentNextLinePattern && resetGlobalRegex(this.a.indentNextLinePattern) && this.a.indentNextLinePattern.test(text2)) {
      return true;
    }
    return false;
  }
  shouldIgnore(text2) {
    if (this.a && this.a.unIndentedLinePattern && resetGlobalRegex(this.a.unIndentedLinePattern) && this.a.unIndentedLinePattern.test(text2)) {
      return true;
    }
    return false;
  }
  getIndentMetadata(text2) {
    let ret = 0;
    if (this.shouldIncrease(text2)) {
      ret += 1;
    }
    if (this.shouldDecrease(text2)) {
      ret += 2;
    }
    if (this.shouldIndentNextLine(text2)) {
      ret += 4;
    }
    if (this.shouldIgnore(text2)) {
      ret += 8;
    }
    return ret;
  }
};

// out-build/vs/editor/common/languages/supports/onEnter.js
var $GF = class _$GF {
  constructor(opts) {
    opts = opts || {};
    opts.brackets = opts.brackets || [
      ["(", ")"],
      ["{", "}"],
      ["[", "]"]
    ];
    this.a = [];
    opts.brackets.forEach((bracket) => {
      const openRegExp = _$GF.c(bracket[0]);
      const closeRegExp = _$GF.d(bracket[1]);
      if (openRegExp && closeRegExp) {
        this.a.push({
          open: bracket[0],
          openRegExp,
          close: bracket[1],
          closeRegExp
        });
      }
    });
    this.b = opts.onEnterRules || [];
  }
  onEnter(autoIndent, previousLineText, beforeEnterText, afterEnterText) {
    if (autoIndent >= 3) {
      for (let i2 = 0, len = this.b.length; i2 < len; i2++) {
        const rule = this.b[i2];
        const regResult = [{
          reg: rule.beforeText,
          text: beforeEnterText
        }, {
          reg: rule.afterText,
          text: afterEnterText
        }, {
          reg: rule.previousLineText,
          text: previousLineText
        }].every((obj) => {
          if (!obj.reg) {
            return true;
          }
          obj.reg.lastIndex = 0;
          return obj.reg.test(obj.text);
        });
        if (regResult) {
          return rule.action;
        }
      }
    }
    if (autoIndent >= 2) {
      if (beforeEnterText.length > 0 && afterEnterText.length > 0) {
        for (let i2 = 0, len = this.a.length; i2 < len; i2++) {
          const bracket = this.a[i2];
          if (bracket.openRegExp.test(beforeEnterText) && bracket.closeRegExp.test(afterEnterText)) {
            return { indentAction: IndentAction.IndentOutdent };
          }
        }
      }
    }
    if (autoIndent >= 2) {
      if (beforeEnterText.length > 0) {
        for (let i2 = 0, len = this.a.length; i2 < len; i2++) {
          const bracket = this.a[i2];
          if (bracket.openRegExp.test(beforeEnterText)) {
            return { indentAction: IndentAction.Indent };
          }
        }
      }
    }
    return null;
  }
  static c(bracket) {
    let str = $Af(bracket);
    if (!/\B/.test(str.charAt(0))) {
      str = "\\b" + str;
    }
    str += "\\s*$";
    return _$GF.e(str);
  }
  static d(bracket) {
    let str = $Af(bracket);
    if (!/\B/.test(str.charAt(str.length - 1))) {
      str = str + "\\b";
    }
    str = "^\\s*" + str;
    return _$GF.e(str);
  }
  static e(def2) {
    try {
      return new RegExp(def2);
    } catch (err) {
      $gb(err);
      return null;
    }
  }
};

// out-build/vs/platform/configuration/common/configuration.js
var $kl = $Qk("configurationService");
function $ll(thing) {
  return thing && typeof thing === "object" && (!thing.overrideIdentifier || typeof thing.overrideIdentifier === "string") && (!thing.resource || thing.resource instanceof URI);
}
function $ml(thing) {
  return thing && typeof thing === "object" && (!thing.overrideIdentifiers || Array.isArray(thing.overrideIdentifiers)) && !thing.overrideIdentifier && (!thing.resource || thing.resource instanceof URI);
}
var ConfigurationTarget;
(function(ConfigurationTarget3) {
  ConfigurationTarget3[ConfigurationTarget3["APPLICATION"] = 1] = "APPLICATION";
  ConfigurationTarget3[ConfigurationTarget3["USER"] = 2] = "USER";
  ConfigurationTarget3[ConfigurationTarget3["USER_LOCAL"] = 3] = "USER_LOCAL";
  ConfigurationTarget3[ConfigurationTarget3["USER_REMOTE"] = 4] = "USER_REMOTE";
  ConfigurationTarget3[ConfigurationTarget3["WORKSPACE"] = 5] = "WORKSPACE";
  ConfigurationTarget3[ConfigurationTarget3["WORKSPACE_FOLDER"] = 6] = "WORKSPACE_FOLDER";
  ConfigurationTarget3[ConfigurationTarget3["DEFAULT"] = 7] = "DEFAULT";
  ConfigurationTarget3[ConfigurationTarget3["MEMORY"] = 8] = "MEMORY";
})(ConfigurationTarget || (ConfigurationTarget = {}));
function $nl(configurationTarget) {
  switch (configurationTarget) {
    case 1:
      return "APPLICATION";
    case 2:
      return "USER";
    case 3:
      return "USER_LOCAL";
    case 4:
      return "USER_REMOTE";
    case 5:
      return "WORKSPACE";
    case 6:
      return "WORKSPACE_FOLDER";
    case 7:
      return "DEFAULT";
    case 8:
      return "MEMORY";
  }
}
function $ol(configValue) {
  return configValue.applicationValue !== void 0 || configValue.userValue !== void 0 || configValue.userLocalValue !== void 0 || configValue.userRemoteValue !== void 0 || configValue.workspaceValue !== void 0 || configValue.workspaceFolderValue !== void 0;
}
function $pl(properties, conflictReporter) {
  const root = /* @__PURE__ */ Object.create(null);
  for (const key2 in properties) {
    $ql(root, key2, properties[key2], conflictReporter);
  }
  return root;
}
function $ql(settingsTreeRoot, key2, value, conflictReporter) {
  const segments = key2.split(".");
  const last = segments.pop();
  let curr = settingsTreeRoot;
  for (let i2 = 0; i2 < segments.length; i2++) {
    const s = segments[i2];
    let obj = curr[s];
    switch (typeof obj) {
      case "undefined":
        obj = curr[s] = /* @__PURE__ */ Object.create(null);
        break;
      case "object":
        if (obj === null) {
          conflictReporter(`Ignoring ${key2} as ${segments.slice(0, i2 + 1).join(".")} is null`);
          return;
        }
        break;
      default:
        conflictReporter(`Ignoring ${key2} as ${segments.slice(0, i2 + 1).join(".")} is ${JSON.stringify(obj)}`);
        return;
    }
    curr = obj;
  }
  if (typeof curr === "object" && curr !== null) {
    try {
      curr[last] = value;
    } catch (e) {
      conflictReporter(`Ignoring ${key2} as ${segments.join(".")} is ${JSON.stringify(curr)}`);
    }
  } else {
    conflictReporter(`Ignoring ${key2} as ${segments.join(".")} is ${JSON.stringify(curr)}`);
  }
}
function $rl(valueTree, key2) {
  const segments = key2.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 $sl(config, settingPath, defaultValue) {
  function accessSetting(config2, path2) {
    let current = config2;
    for (const component of path2) {
      if (typeof current !== "object" || current === null) {
        return void 0;
      }
      current = current[component];
    }
    return current;
  }
  const path = settingPath.split(".");
  const result = accessSetting(config, path);
  return typeof result === "undefined" ? defaultValue : result;
}
function $ul(settingKey) {
  return settingKey.replace(/[\[\]]/g, "");
}

// out-build/vs/editor/common/languages/language.js
var $1E = $Qk("languageService");

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

// 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 $SC(id2, ctorOrDescriptor, supportsDelayedInstantiation) {
  if (!(ctorOrDescriptor instanceof $Nk)) {
    ctorOrDescriptor = new $Nk(ctorOrDescriptor, [], Boolean(supportsDelayedInstantiation));
  }
  _registry.push([id2, ctorOrDescriptor]);
}
function $TC() {
  return _registry;
}

// out-build/vs/base/common/mime.js
var $YC = Object.freeze({
  text: "text/plain",
  binary: "application/octet-stream",
  unknown: "application/unknown",
  markdown: "text/markdown",
  latex: "text/latex",
  uriList: "text/uri-list"
});
var mapExtToTextMimes = {
  ".css": "text/css",
  ".csv": "text/csv",
  ".htm": "text/html",
  ".html": "text/html",
  ".ics": "text/calendar",
  ".js": "text/javascript",
  ".mjs": "text/javascript",
  ".txt": "text/plain",
  ".xml": "text/xml"
};
var mapExtToMediaMimes = {
  ".aac": "audio/x-aac",
  ".avi": "video/x-msvideo",
  ".bmp": "image/bmp",
  ".flv": "video/x-flv",
  ".gif": "image/gif",
  ".ico": "image/x-icon",
  ".jpe": "image/jpg",
  ".jpeg": "image/jpg",
  ".jpg": "image/jpg",
  ".m1v": "video/mpeg",
  ".m2a": "audio/mpeg",
  ".m2v": "video/mpeg",
  ".m3a": "audio/mpeg",
  ".mid": "audio/midi",
  ".midi": "audio/midi",
  ".mk3d": "video/x-matroska",
  ".mks": "video/x-matroska",
  ".mkv": "video/x-matroska",
  ".mov": "video/quicktime",
  ".movie": "video/x-sgi-movie",
  ".mp2": "audio/mpeg",
  ".mp2a": "audio/mpeg",
  ".mp3": "audio/mpeg",
  ".mp4": "video/mp4",
  ".mp4a": "audio/mp4",
  ".mp4v": "video/mp4",
  ".mpe": "video/mpeg",
  ".mpeg": "video/mpeg",
  ".mpg": "video/mpeg",
  ".mpg4": "video/mp4",
  ".mpga": "audio/mpeg",
  ".oga": "audio/ogg",
  ".ogg": "audio/ogg",
  ".opus": "audio/opus",
  ".ogv": "video/ogg",
  ".png": "image/png",
  ".psd": "image/vnd.adobe.photoshop",
  ".qt": "video/quicktime",
  ".spx": "audio/ogg",
  ".svg": "image/svg+xml",
  ".tga": "image/x-tga",
  ".tif": "image/tiff",
  ".tiff": "image/tiff",
  ".wav": "audio/x-wav",
  ".webm": "video/webm",
  ".webp": "image/webp",
  ".wma": "audio/x-ms-wma",
  ".wmv": "video/x-ms-wmv",
  ".woff": "application/font-woff"
};
function $ZC(path) {
  const ext = $sc(path);
  const textMime = mapExtToTextMimes[ext.toLowerCase()];
  if (textMime !== void 0) {
    return textMime;
  } else {
    return $1C(path);
  }
}
function $1C(path) {
  const ext = $sc(path);
  return mapExtToMediaMimes[ext.toLowerCase()];
}
function $2C(mimeType) {
  for (const extension in mapExtToMediaMimes) {
    if (mapExtToMediaMimes[extension] === mimeType) {
      return extension;
    }
  }
  return void 0;
}
var _simplePattern = /^(.+)\/(.+?)(;.+)?$/;
function $3C(mimeType, strict) {
  const match = _simplePattern.exec(mimeType);
  if (!match) {
    return strict ? void 0 : mimeType;
  }
  return `${match[1].toLowerCase()}/${match[2].toLowerCase()}${match[3] ?? ""}`;
}

// out-build/vs/base/common/jsonSchema.js
function $rn(schema9) {
  let hasDups = false;
  const equalsByString = /* @__PURE__ */ new Map();
  const nodeToEquals = /* @__PURE__ */ new Map();
  const visitSchemas = (next) => {
    if (schema9 === 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(schema9, visitSchemas);
  equalsByString.clear();
  if (!hasDups) {
    return JSON.stringify(schema9);
  }
  let defNodeName = "$defs";
  while (schema9.hasOwnProperty(defNodeName)) {
    defNodeName += "_";
  }
  const definitions3 = [];
  function stringify2(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 = `_${definitions3.length}`;
            definitions3.push(eq2.schemas[0]);
          }
          return { $ref: `#/${defNodeName}/${eq2.id}` };
        }
      }
      return value;
    });
  }
  const str = stringify2(schema9);
  const defStrings = [];
  for (let i2 = 0; i2 < definitions3.length; i2++) {
    defStrings.push(`"_${i2}":${stringify2(definitions3[i2])}`);
  }
  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 = (...entries2) => {
    for (const entry of entries2) {
      if (isObject(entry)) {
        toWalk.push(entry);
      }
    }
  };
  const collectMapEntries = (...maps) => {
    for (const map of maps) {
      if (isObject(map)) {
        for (const key2 in map) {
          const entry = map[key2];
          if (isObject(entry)) {
            toWalk.push(entry);
          }
        }
      }
    }
  };
  const collectArrayEntries = (...arrays) => {
    for (const array2 of arrays) {
      if (Array.isArray(array2)) {
        for (const entry of array2) {
          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/platform/jsonschemas/common/jsonContributionRegistry.js
var $Xn = {
  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 $ze();
    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 schema9 = this.a[uri];
    return schema9 ? $rn(schema9) : void 0;
  }
  hasSchemaContent(uri) {
    return !!this.a[uri];
  }
};
var jsonContributionRegistry = new JSONContributionRegistry();
$Wn.add($Xn.JSONContribution, jsonContributionRegistry);

// out-build/vs/platform/configuration/common/configurationRegistry.js
var EditPresentationTypes;
(function(EditPresentationTypes2) {
  EditPresentationTypes2["Multiline"] = "multilineText";
  EditPresentationTypes2["Singleline"] = "singlelineText";
})(EditPresentationTypes || (EditPresentationTypes = {}));
var $Ht = {
  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 $It = { properties: {}, patternProperties: {} };
var $Jt = { properties: {}, patternProperties: {} };
var $Kt = { properties: {}, patternProperties: {} };
var $Lt = { properties: {}, patternProperties: {} };
var $Mt = { properties: {}, patternProperties: {} };
var $Nt = { properties: {}, patternProperties: {} };
var $Ot = "vscode://schemas/settings/resourceLanguage";
var $Pt = "vscode://schemas/settings/configurationDefaults";
var contributionRegistry = $Wn.as($Xn.JSONContribution);
var ConfigurationRegistry = class {
  constructor() {
    this.a = [];
    this.i = /* @__PURE__ */ new Set();
    this.j = new $ze();
    this.onDidSchemaChange = this.j.event;
    this.k = new $ze();
    this.onDidUpdateConfiguration = this.k.event;
    this.b = /* @__PURE__ */ new Map();
    this.c = {
      id: "defaultOverrides",
      title: localize(1693, 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($Ot, this.h);
    this.z();
  }
  registerConfiguration(configuration2, validate = true) {
    this.registerConfigurations([configuration2], validate);
  }
  registerConfigurations(configurations, validate = true) {
    const properties = /* @__PURE__ */ new Set();
    this.r(configurations, validate, properties);
    contributionRegistry.registerSchema($Ot, this.h);
    this.j.fire();
    this.k.fire({ properties });
  }
  deregisterConfigurations(configurations) {
    const properties = /* @__PURE__ */ new Set();
    this.s(configurations, properties);
    contributionRegistry.registerSchema($Ot, 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($Ot, 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 key2 in overrides) {
        bucket.add(key2);
        const configurationDefaultOverridesForKey = this.b.get(key2) ?? this.b.set(key2, { configurationDefaultOverrides: [] }).get(key2);
        const value = overrides[key2];
        configurationDefaultOverridesForKey.configurationDefaultOverrides.push({ value, source });
        if ($Rt.test(key2)) {
          const newDefaultOverride = this.o(key2, value, source, configurationDefaultOverridesForKey.configurationDefaultOverrideValue);
          if (!newDefaultOverride) {
            continue;
          }
          configurationDefaultOverridesForKey.configurationDefaultOverrideValue = newDefaultOverride;
          this.n(key2, newDefaultOverride, source);
          overrideIdentifiers.push(...$St(key2));
        } else {
          const newDefaultOverride = this.p(key2, value, source, configurationDefaultOverridesForKey.configurationDefaultOverrideValue);
          if (!newDefaultOverride) {
            continue;
          }
          configurationDefaultOverridesForKey.configurationDefaultOverrideValue = newDefaultOverride;
          const property = this.e[key2];
          if (property) {
            this.A(key2, property);
            this.w(key2, 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 key2 in overrides) {
        const configurationDefaultOverridesForKey = this.b.get(key2);
        if (!configurationDefaultOverridesForKey) {
          continue;
        }
        const index = configurationDefaultOverridesForKey.configurationDefaultOverrides.findIndex((configurationDefaultOverride) => source ? configurationDefaultOverride.source?.id === source.id : configurationDefaultOverride.value === overrides[key2]);
        if (index === -1) {
          continue;
        }
        configurationDefaultOverridesForKey.configurationDefaultOverrides.splice(index, 1);
        if (configurationDefaultOverridesForKey.configurationDefaultOverrides.length === 0) {
          this.b.delete(key2);
        }
        if ($Rt.test(key2)) {
          let configurationDefaultOverrideValue;
          for (const configurationDefaultOverride of configurationDefaultOverridesForKey.configurationDefaultOverrides) {
            configurationDefaultOverrideValue = this.o(key2, configurationDefaultOverride.value, configurationDefaultOverride.source, configurationDefaultOverrideValue);
          }
          if (configurationDefaultOverrideValue && !$Mg(configurationDefaultOverrideValue.value)) {
            configurationDefaultOverridesForKey.configurationDefaultOverrideValue = configurationDefaultOverrideValue;
            this.n(key2, configurationDefaultOverrideValue, source);
          } else {
            this.b.delete(key2);
            delete this.e[key2];
            delete this.c.properties[key2];
          }
        } else {
          let configurationDefaultOverrideValue;
          for (const configurationDefaultOverride of configurationDefaultOverridesForKey.configurationDefaultOverrides) {
            configurationDefaultOverrideValue = this.p(key2, configurationDefaultOverride.value, configurationDefaultOverride.source, configurationDefaultOverrideValue);
          }
          configurationDefaultOverridesForKey.configurationDefaultOverrideValue = configurationDefaultOverrideValue;
          const property = this.e[key2];
          if (property) {
            this.A(key2, property);
            this.w(key2, property);
          }
        }
        bucket.add(key2);
      }
    }
    this.y();
  }
  n(key2, newDefaultOverride, source) {
    const property = {
      type: "object",
      default: newDefaultOverride.value,
      description: localize(1694, null, $ul(key2)),
      $ref: $Ot,
      defaultDefaultValue: newDefaultOverride.value,
      source,
      defaultValueSource: source
    };
    this.e[key2] = property;
    this.c.properties[key2] = 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 = $Bg(propertyDefaultValue) && ($Gg(defaultValue[propertyKey]) || $Bg(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 = $Bg(value) && (property !== void 0 && property.type === "object" || property === void 0 && ($Gg(existingDefaultValue) || $Bg(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 = { ...$Bg(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((configuration2) => {
      this.u(configuration2, validate, configuration2.extensionInfo, configuration2.restrictedProperties, void 0, bucket);
      this.d.push(configuration2);
      this.v(configuration2);
    });
  }
  s(configurations, bucket) {
    const deregisterConfiguration = (configuration2) => {
      if (configuration2.properties) {
        for (const key2 in configuration2.properties) {
          bucket.add(key2);
          const property = this.e[key2];
          if (property?.policy?.name) {
            this.f.delete(property.policy.name);
          }
          delete this.e[key2];
          this.x(key2, configuration2.properties[key2]);
        }
      }
      configuration2.allOf?.forEach((node) => deregisterConfiguration(node));
    };
    for (const configuration2 of configurations) {
      deregisterConfiguration(configuration2);
      const index = this.d.indexOf(configuration2);
      if (index !== -1) {
        this.d.splice(index, 1);
      }
    }
  }
  u(configuration2, validate = true, extensionInfo, restrictedProperties, scope = 3, bucket) {
    scope = $Ig(configuration2.scope) ? scope : configuration2.scope;
    const properties = configuration2.properties;
    if (properties) {
      for (const key2 in properties) {
        const property = properties[key2];
        if (validate && $Vt(key2, property)) {
          delete properties[key2];
          continue;
        }
        property.source = extensionInfo;
        property.defaultDefaultValue = properties[key2].default;
        this.A(key2, property);
        if ($Rt.test(key2)) {
          property.scope = void 0;
        } else {
          property.scope = $Ig(property.scope) ? scope : property.scope;
          property.restricted = $Ig(property.restricted) ? !!restrictedProperties?.includes(key2) : property.restricted;
        }
        if (properties[key2].hasOwnProperty("included") && !properties[key2].included) {
          this.g[key2] = properties[key2];
          delete properties[key2];
          continue;
        } else {
          this.e[key2] = properties[key2];
          if (properties[key2].policy?.name) {
            this.f.set(properties[key2].policy.name, key2);
          }
        }
        if (!properties[key2].deprecationMessage && properties[key2].markdownDeprecationMessage) {
          properties[key2].deprecationMessage = properties[key2].markdownDeprecationMessage;
        }
        bucket.add(key2);
      }
    }
    const subNodes = configuration2.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 [key2, value] of this.b) {
      if (value.configurationDefaultOverrideValue) {
        configurationDefaultsOverrides.set(key2, value.configurationDefaultOverrideValue);
      }
    }
    return configurationDefaultsOverrides;
  }
  v(configuration2) {
    const register2 = (configuration3) => {
      const properties = configuration3.properties;
      if (properties) {
        for (const key2 in properties) {
          this.w(key2, properties[key2]);
        }
      }
      const subNodes = configuration3.allOf;
      subNodes?.forEach(register2);
    };
    register2(configuration2);
  }
  w(key2, property) {
    $It.properties[key2] = property;
    switch (property.scope) {
      case 1:
        $Jt.properties[key2] = property;
        break;
      case 2:
        $Kt.properties[key2] = property;
        break;
      case 6:
        $Lt.properties[key2] = property;
        break;
      case 3:
        $Mt.properties[key2] = property;
        break;
      case 4:
        $Nt.properties[key2] = property;
        break;
      case 5:
        $Nt.properties[key2] = property;
        this.h.properties[key2] = property;
        break;
    }
  }
  x(key2, property) {
    delete $It.properties[key2];
    switch (property.scope) {
      case 1:
        delete $Jt.properties[key2];
        break;
      case 2:
        delete $Kt.properties[key2];
        break;
      case 6:
        delete $Lt.properties[key2];
        break;
      case 3:
        delete $Mt.properties[key2];
        break;
      case 4:
      case 5:
        delete $Nt.properties[key2];
        delete this.h.properties[key2];
        break;
    }
  }
  y() {
    for (const overrideIdentifier of this.i.values()) {
      const overrideIdentifierProperty = `[${overrideIdentifier}]`;
      const resourceLanguagePropertiesSchema = {
        type: "object",
        description: localize(1695, null),
        errorMessage: localize(1696, null),
        $ref: $Ot
      };
      this.A(overrideIdentifierProperty, resourceLanguagePropertiesSchema);
      $It.properties[overrideIdentifierProperty] = resourceLanguagePropertiesSchema;
      $Jt.properties[overrideIdentifierProperty] = resourceLanguagePropertiesSchema;
      $Kt.properties[overrideIdentifierProperty] = resourceLanguagePropertiesSchema;
      $Lt.properties[overrideIdentifierProperty] = resourceLanguagePropertiesSchema;
      $Mt.properties[overrideIdentifierProperty] = resourceLanguagePropertiesSchema;
      $Nt.properties[overrideIdentifierProperty] = resourceLanguagePropertiesSchema;
    }
  }
  z() {
    const resourceLanguagePropertiesSchema = {
      type: "object",
      description: localize(1697, null),
      errorMessage: localize(1698, null),
      $ref: $Ot
    };
    $It.patternProperties[$Qt] = resourceLanguagePropertiesSchema;
    $Jt.patternProperties[$Qt] = resourceLanguagePropertiesSchema;
    $Kt.patternProperties[$Qt] = resourceLanguagePropertiesSchema;
    $Lt.patternProperties[$Qt] = resourceLanguagePropertiesSchema;
    $Mt.patternProperties[$Qt] = resourceLanguagePropertiesSchema;
    $Nt.patternProperties[$Qt] = resourceLanguagePropertiesSchema;
    this.j.fire();
  }
  A(key2, property) {
    const configurationdefaultOverride = this.b.get(key2)?.configurationDefaultOverrideValue;
    let defaultValue = void 0;
    let defaultSource = void 0;
    if (configurationdefaultOverride && (!property.disallowConfigurationDefault || !configurationdefaultOverride.source)) {
      defaultValue = configurationdefaultOverride.value;
      defaultSource = configurationdefaultOverride.source;
    }
    if ($Gg(defaultValue)) {
      defaultValue = property.defaultDefaultValue;
      defaultSource = void 0;
    }
    if ($Gg(defaultValue)) {
      defaultValue = $Ut(property.type);
    }
    property.default = defaultValue;
    property.defaultValueSource = defaultSource;
  }
};
var OVERRIDE_IDENTIFIER_PATTERN = `\\[([^\\]]+)\\]`;
var OVERRIDE_IDENTIFIER_REGEX = new RegExp(OVERRIDE_IDENTIFIER_PATTERN, "g");
var $Qt = `^(${OVERRIDE_IDENTIFIER_PATTERN})+$`;
var $Rt = new RegExp($Qt);
function $St(key2) {
  const identifiers2 = [];
  if ($Rt.test(key2)) {
    let matches = OVERRIDE_IDENTIFIER_REGEX.exec(key2);
    while (matches?.length) {
      const identifier2 = matches[1].trim();
      if (identifier2) {
        identifiers2.push(identifier2);
      }
      matches = OVERRIDE_IDENTIFIER_REGEX.exec(key2);
    }
  }
  return $Rb(identifiers2);
}
function $Tt(overrideIdentifiers) {
  return overrideIdentifiers.reduce((result, overrideIdentifier) => `${result}[${overrideIdentifier}]`, "");
}
function $Ut(type) {
  const t = Array.isArray(type) ? type[0] : type;
  switch (t) {
    case "boolean":
      return false;
    case "integer":
    case "number":
      return 0;
    case "string":
      return "";
    case "array":
      return [];
    case "object":
      return {};
    default:
      return null;
  }
}
var configurationRegistry = new ConfigurationRegistry();
$Wn.add($Ht.Configuration, configurationRegistry);
function $Vt(property, schema9) {
  if (!property.trim()) {
    return localize(1699, null);
  }
  if ($Rt.test(property)) {
    return localize(1700, null, property);
  }
  if (configurationRegistry.getConfigurationProperties()[property] !== void 0) {
    return localize(1701, null, property);
  }
  if (schema9.policy?.name && configurationRegistry.getPolicyConfigurations().get(schema9.policy?.name) !== void 0) {
    return localize(1702, null, property, schema9.policy?.name, configurationRegistry.getPolicyConfigurations().get(schema9.policy?.name));
  }
  return null;
}
function $Wt() {
  const scopes = [];
  const configurationProperties = configurationRegistry.getConfigurationProperties();
  for (const key2 of Object.keys(configurationProperties)) {
    scopes.push([key2, configurationProperties[key2].scope]);
  }
  scopes.push([
    "launch",
    4
    /* ConfigurationScope.RESOURCE */
  ]);
  scopes.push([
    "task",
    4
    /* ConfigurationScope.RESOURCE */
  ]);
  return scopes;
}
function $Xt(configurationNode) {
  const result = {};
  for (const configuration2 of configurationNode) {
    const properties = configuration2.properties;
    if ($Bg(properties)) {
      for (const key2 in properties) {
        result[key2] = properties[key2];
      }
    }
    if (configuration2.allOf) {
      Object.assign(result, $Xt(configuration2.allOf));
    }
  }
  return result;
}
function $Yt(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/editor/common/languages/modesRegistry.js
var $HF = {
  ModesRegistry: "editor.modesRegistry"
};
var $IF = class {
  constructor() {
    this.b = new $ze();
    this.onDidChangeLanguages = this.b.event;
    this.a = [];
  }
  registerLanguage(def2) {
    this.a.push(def2);
    this.b.fire(void 0);
    return {
      dispose: () => {
        for (let i2 = 0, len = this.a.length; i2 < len; i2++) {
          if (this.a[i2] === def2) {
            this.a.splice(i2, 1);
            return;
          }
        }
      }
    };
  }
  getLanguages() {
    return this.a;
  }
};
var $JF = new $IF();
$Wn.add($HF.ModesRegistry, $JF);
var $KF = "plaintext";
var $LF = ".txt";
$JF.registerLanguage({
  id: $KF,
  extensions: [$LF],
  aliases: [localize(831, null), "text"],
  mimetypes: [$YC.text]
});
$Wn.as($Ht.Configuration).registerDefaultConfigurations([{
  overrides: {
    "[plaintext]": {
      "editor.unicodeHighlight.ambiguousCharacters": false,
      "editor.unicodeHighlight.invisibleCharacters": false
    }
  }
}]);

// out-build/vs/editor/common/languages/supports/languageBracketsConfiguration.js
var $$E = class {
  constructor(languageId, config) {
    this.languageId = languageId;
    const bracketPairs = config.brackets ? filterValidBrackets(config.brackets) : [];
    const openingBracketInfos = new $rf((bracket) => {
      const closing = /* @__PURE__ */ new Set();
      return {
        info: new $aF(this, bracket, closing),
        closing
      };
    });
    const closingBracketInfos = new $rf((bracket) => {
      const opening = /* @__PURE__ */ new Set();
      const openingColorized = /* @__PURE__ */ new Set();
      return {
        info: new $bF(this, bracket, opening, openingColorized),
        opening,
        openingColorized
      };
    });
    for (const [open2, close2] of bracketPairs) {
      const opening = openingBracketInfos.get(open2);
      const closing = closingBracketInfos.get(close2);
      opening.closing.add(closing.info);
      closing.opening.add(opening.info);
    }
    const colorizedBracketPairs = config.colorizedBracketPairs ? filterValidBrackets(config.colorizedBracketPairs) : bracketPairs.filter((p) => !(p[0] === "<" && p[1] === ">"));
    for (const [open2, close2] of colorizedBracketPairs) {
      const opening = openingBracketInfos.get(open2);
      const closing = closingBracketInfos.get(close2);
      opening.closing.add(closing.info);
      closing.openingColorized.add(opening.info);
      closing.opening.add(opening.info);
    }
    this.a = new Map([...openingBracketInfos.cachedValues].map(([k, v]) => [k, v.info]));
    this.b = new Map([...closingBracketInfos.cachedValues].map(([k, v]) => [k, v.info]));
  }
  /**
   * No two brackets have the same bracket text.
  */
  get openingBrackets() {
    return [...this.a.values()];
  }
  /**
   * No two brackets have the same bracket text.
  */
  get closingBrackets() {
    return [...this.b.values()];
  }
  getOpeningBracketInfo(bracketText) {
    return this.a.get(bracketText);
  }
  getClosingBracketInfo(bracketText) {
    return this.b.get(bracketText);
  }
  getBracketInfo(bracketText) {
    return this.getOpeningBracketInfo(bracketText) || this.getClosingBracketInfo(bracketText);
  }
  getBracketRegExp(options3) {
    const brackets = Array.from([...this.a.keys(), ...this.b.keys()]);
    return $9E(brackets, options3);
  }
};
function filterValidBrackets(bracketPairs) {
  return bracketPairs.filter(([open2, close2]) => open2 !== "" && close2 !== "");
}
var $_E = class {
  constructor(a, bracketText) {
    this.a = a;
    this.bracketText = bracketText;
  }
  get languageId() {
    return this.a.languageId;
  }
};
var $aF = class extends $_E {
  constructor(config, bracketText, openedBrackets) {
    super(config, bracketText);
    this.openedBrackets = openedBrackets;
    this.isOpeningBracket = true;
  }
};
var $bF = class extends $_E {
  constructor(config, bracketText, openingBrackets, b) {
    super(config, bracketText);
    this.openingBrackets = openingBrackets;
    this.b = b;
    this.isOpeningBracket = false;
  }
  /**
   * Checks if this bracket closes the given other bracket.
   * If the bracket infos come from different configurations, this method will return false.
  */
  closes(other) {
    if (other["a"] !== this.a) {
      return false;
    }
    return this.openingBrackets.has(other);
  }
  closesColorized(other) {
    if (other["a"] !== this.a) {
      return false;
    }
    return this.b.has(other);
  }
  getOpeningBrackets() {
    return [...this.openingBrackets];
  }
};

// out-build/vs/editor/common/languages/languageConfigurationRegistry.js
var $MF = class {
  constructor(languageId) {
    this.languageId = languageId;
  }
  affects(languageId) {
    return !this.languageId ? true : this.languageId === languageId;
  }
};
var $NF = $Qk("languageConfigurationService");
var $OF = class $OF2 extends $3c {
  constructor(h3, j) {
    super();
    this.h = h3;
    this.j = j;
    this.c = this.B(new $RF());
    this.f = this.B(new $ze());
    this.onDidChange = this.f.event;
    this.g = /* @__PURE__ */ new Map();
    const languageConfigKeys = new Set(Object.values(customizedLanguageConfigKeys));
    this.B(this.h.onDidChangeConfiguration((e) => {
      const globalConfigChanged = e.change.keys.some((k) => languageConfigKeys.has(k));
      const localConfigChanged = e.change.overrides.filter(([overrideLangName, keys]) => keys.some((k) => languageConfigKeys.has(k))).map(([overrideLangName]) => overrideLangName);
      if (globalConfigChanged) {
        this.g.clear();
        this.f.fire(new $MF(void 0));
      } else {
        for (const languageId of localConfigChanged) {
          if (this.j.isRegisteredLanguageId(languageId)) {
            this.g.delete(languageId);
            this.f.fire(new $MF(languageId));
          }
        }
      }
    }));
    this.B(this.c.onDidChange((e) => {
      this.g.delete(e.languageId);
      this.f.fire(new $MF(e.languageId));
    }));
  }
  register(languageId, configuration2, priority) {
    return this.c.register(languageId, configuration2, priority);
  }
  getLanguageConfiguration(languageId) {
    let result = this.g.get(languageId);
    if (!result) {
      result = computeConfig(languageId, this.c, this.h, this.j);
      this.g.set(languageId, result);
    }
    return result;
  }
};
$OF = __decorate([
  __param(0, $kl),
  __param(1, $1E)
], $OF);
function computeConfig(languageId, registry4, configurationService, languageService) {
  let languageConfig = registry4.getLanguageConfiguration(languageId);
  if (!languageConfig) {
    if (!languageService.isRegisteredLanguageId(languageId)) {
      return new $SF(languageId, {});
    }
    languageConfig = new $SF(languageId, {});
  }
  const customizedConfig = getCustomizedLanguageConfig(languageConfig.languageId, configurationService);
  const data = combineLanguageConfigurations([languageConfig.underlyingConfig, customizedConfig]);
  const config = new $SF(languageConfig.languageId, data);
  return config;
}
var customizedLanguageConfigKeys = {
  brackets: "editor.language.brackets",
  colorizedBracketPairs: "editor.language.colorizedBracketPairs"
};
function getCustomizedLanguageConfig(languageId, configurationService) {
  const brackets = configurationService.getValue(customizedLanguageConfigKeys.brackets, {
    overrideIdentifier: languageId
  });
  const colorizedBracketPairs = configurationService.getValue(customizedLanguageConfigKeys.colorizedBracketPairs, {
    overrideIdentifier: languageId
  });
  return {
    brackets: validateBracketPairs(brackets),
    colorizedBracketPairs: validateBracketPairs(colorizedBracketPairs)
  };
}
function validateBracketPairs(data) {
  if (!Array.isArray(data)) {
    return void 0;
  }
  return data.map((pair) => {
    if (!Array.isArray(pair) || pair.length !== 2) {
      return void 0;
    }
    return [pair[0], pair[1]];
  }).filter((p) => !!p);
}
function $PF(model, lineNumber, column) {
  const lineText = model.getLineContent(lineNumber);
  let indentation = $Pf(lineText);
  if (indentation.length > column - 1) {
    indentation = indentation.substring(0, column - 1);
  }
  return indentation;
}
var ComposedLanguageConfiguration = class {
  constructor(languageId) {
    this.languageId = languageId;
    this.f = null;
    this.c = [];
    this.d = 0;
    this.f = null;
  }
  register(configuration2, priority) {
    const entry = new LanguageConfigurationContribution(configuration2, priority, ++this.d);
    this.c.push(entry);
    this.f = null;
    return $1c(() => {
      for (let i2 = 0; i2 < this.c.length; i2++) {
        if (this.c[i2] === entry) {
          this.c.splice(i2, 1);
          this.f = null;
          break;
        }
      }
    });
  }
  getResolvedConfiguration() {
    if (!this.f) {
      const config = this.g();
      if (config) {
        this.f = new $SF(this.languageId, config);
      }
    }
    return this.f;
  }
  g() {
    if (this.c.length === 0) {
      return null;
    }
    this.c.sort(LanguageConfigurationContribution.cmp);
    return combineLanguageConfigurations(this.c.map((e) => e.configuration));
  }
};
function combineLanguageConfigurations(configs) {
  let result = {
    comments: void 0,
    brackets: void 0,
    wordPattern: void 0,
    indentationRules: void 0,
    onEnterRules: void 0,
    autoClosingPairs: void 0,
    surroundingPairs: void 0,
    autoCloseBefore: void 0,
    folding: void 0,
    colorizedBracketPairs: void 0,
    __electricCharacterSupport: void 0
  };
  for (const entry of configs) {
    result = {
      comments: entry.comments || result.comments,
      brackets: entry.brackets || result.brackets,
      wordPattern: entry.wordPattern || result.wordPattern,
      indentationRules: entry.indentationRules || result.indentationRules,
      onEnterRules: entry.onEnterRules || result.onEnterRules,
      autoClosingPairs: entry.autoClosingPairs || result.autoClosingPairs,
      surroundingPairs: entry.surroundingPairs || result.surroundingPairs,
      autoCloseBefore: entry.autoCloseBefore || result.autoCloseBefore,
      folding: entry.folding || result.folding,
      colorizedBracketPairs: entry.colorizedBracketPairs || result.colorizedBracketPairs,
      __electricCharacterSupport: entry.__electricCharacterSupport || result.__electricCharacterSupport
    };
  }
  return result;
}
var LanguageConfigurationContribution = class {
  constructor(configuration2, priority, order) {
    this.configuration = configuration2;
    this.priority = priority;
    this.order = order;
  }
  static cmp(a, b) {
    if (a.priority === b.priority) {
      return a.order - b.order;
    }
    return a.priority - b.priority;
  }
};
var $QF = class {
  constructor(languageId) {
    this.languageId = languageId;
  }
};
var $RF = class extends $3c {
  constructor() {
    super();
    this.c = /* @__PURE__ */ new Map();
    this.f = this.B(new $ze());
    this.onDidChange = this.f.event;
    this.B(this.register($KF, {
      brackets: [
        ["(", ")"],
        ["[", "]"],
        ["{", "}"]
      ],
      surroundingPairs: [
        { open: "{", close: "}" },
        { open: "[", close: "]" },
        { open: "(", close: ")" },
        { open: "<", close: ">" },
        { open: '"', close: '"' },
        { open: "'", close: "'" },
        { open: "`", close: "`" }
      ],
      colorizedBracketPairs: [],
      folding: {
        offSide: true
      }
    }, 0));
  }
  /**
   * @param priority Use a higher number for higher priority
   */
  register(languageId, configuration2, priority = 0) {
    let entries2 = this.c.get(languageId);
    if (!entries2) {
      entries2 = new ComposedLanguageConfiguration(languageId);
      this.c.set(languageId, entries2);
    }
    const disposable = entries2.register(configuration2, priority);
    this.f.fire(new $QF(languageId));
    return $1c(() => {
      disposable.dispose();
      this.f.fire(new $QF(languageId));
    });
  }
  getLanguageConfiguration(languageId) {
    const entries2 = this.c.get(languageId);
    return entries2?.getResolvedConfiguration() || null;
  }
};
var $SF = class _$SF {
  constructor(languageId, underlyingConfig) {
    this.languageId = languageId;
    this.underlyingConfig = underlyingConfig;
    this.c = null;
    this.d = null;
    this.f = this.underlyingConfig.brackets || this.underlyingConfig.indentationRules || this.underlyingConfig.onEnterRules ? new $GF(this.underlyingConfig) : null;
    this.comments = _$SF.g(this.underlyingConfig);
    this.characterPair = new $DF(this.underlyingConfig);
    this.wordDefinition = this.underlyingConfig.wordPattern || $JD;
    this.indentationRules = this.underlyingConfig.indentationRules;
    if (this.underlyingConfig.indentationRules) {
      this.indentRulesSupport = new $FF(this.underlyingConfig.indentationRules);
    } else {
      this.indentRulesSupport = null;
    }
    this.foldingRules = this.underlyingConfig.folding || {};
    this.bracketsNew = new $$E(languageId, this.underlyingConfig);
  }
  getWordDefinition() {
    return $KD(this.wordDefinition);
  }
  get brackets() {
    if (!this.c && this.underlyingConfig.brackets) {
      this.c = new $8E(this.languageId, this.underlyingConfig.brackets);
    }
    return this.c;
  }
  get electricCharacter() {
    if (!this.d) {
      this.d = new $EF(this.brackets);
    }
    return this.d;
  }
  onEnter(autoIndent, previousLineText, beforeEnterText, afterEnterText) {
    if (!this.f) {
      return null;
    }
    return this.f.onEnter(autoIndent, previousLineText, beforeEnterText, afterEnterText);
  }
  getAutoClosingPairs() {
    return new $6E(this.characterPair.getAutoClosingPairs());
  }
  getAutoCloseBeforeSet(forQuotes) {
    return this.characterPair.getAutoCloseBeforeSet(forQuotes);
  }
  getSurroundingPairs() {
    return this.characterPair.getSurroundingPairs();
  }
  static g(conf) {
    const commentRule = conf.comments;
    if (!commentRule) {
      return null;
    }
    const comments = {};
    if (commentRule.lineComment) {
      comments.lineCommentToken = commentRule.lineComment;
    }
    if (commentRule.blockComment) {
      const [blockStart, blockEnd] = commentRule.blockComment;
      comments.blockCommentStartToken = blockStart;
      comments.blockCommentEndToken = blockEnd;
    }
    return comments;
  }
};
$SC(
  $NF,
  $OF,
  1
  /* InstantiationType.Delayed */
);

// out-build/vs/editor/common/encodedTokenAttributes.js
var LanguageId;
(function(LanguageId2) {
  LanguageId2[LanguageId2["Null"] = 0] = "Null";
  LanguageId2[LanguageId2["PlainText"] = 1] = "PlainText";
})(LanguageId || (LanguageId = {}));
var FontStyle;
(function(FontStyle2) {
  FontStyle2[FontStyle2["NotSet"] = -1] = "NotSet";
  FontStyle2[FontStyle2["None"] = 0] = "None";
  FontStyle2[FontStyle2["Italic"] = 1] = "Italic";
  FontStyle2[FontStyle2["Bold"] = 2] = "Bold";
  FontStyle2[FontStyle2["Underline"] = 4] = "Underline";
  FontStyle2[FontStyle2["Strikethrough"] = 8] = "Strikethrough";
})(FontStyle || (FontStyle = {}));
var ColorId;
(function(ColorId2) {
  ColorId2[ColorId2["None"] = 0] = "None";
  ColorId2[ColorId2["DefaultForeground"] = 1] = "DefaultForeground";
  ColorId2[ColorId2["DefaultBackground"] = 2] = "DefaultBackground";
})(ColorId || (ColorId = {}));
var StandardTokenType;
(function(StandardTokenType3) {
  StandardTokenType3[StandardTokenType3["Other"] = 0] = "Other";
  StandardTokenType3[StandardTokenType3["Comment"] = 1] = "Comment";
  StandardTokenType3[StandardTokenType3["String"] = 2] = "String";
  StandardTokenType3[StandardTokenType3["RegEx"] = 3] = "RegEx";
})(StandardTokenType || (StandardTokenType = {}));
var MetadataConsts;
(function(MetadataConsts2) {
  MetadataConsts2[MetadataConsts2["LANGUAGEID_MASK"] = 255] = "LANGUAGEID_MASK";
  MetadataConsts2[MetadataConsts2["TOKEN_TYPE_MASK"] = 768] = "TOKEN_TYPE_MASK";
  MetadataConsts2[MetadataConsts2["BALANCED_BRACKETS_MASK"] = 1024] = "BALANCED_BRACKETS_MASK";
  MetadataConsts2[MetadataConsts2["FONT_STYLE_MASK"] = 30720] = "FONT_STYLE_MASK";
  MetadataConsts2[MetadataConsts2["FOREGROUND_MASK"] = 16744448] = "FOREGROUND_MASK";
  MetadataConsts2[MetadataConsts2["BACKGROUND_MASK"] = 4278190080] = "BACKGROUND_MASK";
  MetadataConsts2[MetadataConsts2["ITALIC_MASK"] = 2048] = "ITALIC_MASK";
  MetadataConsts2[MetadataConsts2["BOLD_MASK"] = 4096] = "BOLD_MASK";
  MetadataConsts2[MetadataConsts2["UNDERLINE_MASK"] = 8192] = "UNDERLINE_MASK";
  MetadataConsts2[MetadataConsts2["STRIKETHROUGH_MASK"] = 16384] = "STRIKETHROUGH_MASK";
  MetadataConsts2[MetadataConsts2["SEMANTIC_USE_ITALIC"] = 1] = "SEMANTIC_USE_ITALIC";
  MetadataConsts2[MetadataConsts2["SEMANTIC_USE_BOLD"] = 2] = "SEMANTIC_USE_BOLD";
  MetadataConsts2[MetadataConsts2["SEMANTIC_USE_UNDERLINE"] = 4] = "SEMANTIC_USE_UNDERLINE";
  MetadataConsts2[MetadataConsts2["SEMANTIC_USE_STRIKETHROUGH"] = 8] = "SEMANTIC_USE_STRIKETHROUGH";
  MetadataConsts2[MetadataConsts2["SEMANTIC_USE_FOREGROUND"] = 16] = "SEMANTIC_USE_FOREGROUND";
  MetadataConsts2[MetadataConsts2["SEMANTIC_USE_BACKGROUND"] = 32] = "SEMANTIC_USE_BACKGROUND";
  MetadataConsts2[MetadataConsts2["LANGUAGEID_OFFSET"] = 0] = "LANGUAGEID_OFFSET";
  MetadataConsts2[MetadataConsts2["TOKEN_TYPE_OFFSET"] = 8] = "TOKEN_TYPE_OFFSET";
  MetadataConsts2[MetadataConsts2["BALANCED_BRACKETS_OFFSET"] = 10] = "BALANCED_BRACKETS_OFFSET";
  MetadataConsts2[MetadataConsts2["FONT_STYLE_OFFSET"] = 11] = "FONT_STYLE_OFFSET";
  MetadataConsts2[MetadataConsts2["FOREGROUND_OFFSET"] = 15] = "FOREGROUND_OFFSET";
  MetadataConsts2[MetadataConsts2["BACKGROUND_OFFSET"] = 24] = "BACKGROUND_OFFSET";
})(MetadataConsts || (MetadataConsts = {}));
var $pE = class {
  static getLanguageId(metadata) {
    return (metadata & 255) >>> 0;
  }
  static getTokenType(metadata) {
    return (metadata & 768) >>> 8;
  }
  static containsBalancedBrackets(metadata) {
    return (metadata & 1024) !== 0;
  }
  static getFontStyle(metadata) {
    return (metadata & 30720) >>> 11;
  }
  static getForeground(metadata) {
    return (metadata & 16744448) >>> 15;
  }
  static getBackground(metadata) {
    return (metadata & 4278190080) >>> 24;
  }
  static getClassNameFromMetadata(metadata) {
    const foreground = this.getForeground(metadata);
    let className = "mtk" + foreground;
    const fontStyle = this.getFontStyle(metadata);
    if (fontStyle & 1) {
      className += " mtki";
    }
    if (fontStyle & 2) {
      className += " mtkb";
    }
    if (fontStyle & 4) {
      className += " mtku";
    }
    if (fontStyle & 8) {
      className += " mtks";
    }
    return className;
  }
  static getInlineStyleFromMetadata(metadata, colorMap) {
    const foreground = this.getForeground(metadata);
    const fontStyle = this.getFontStyle(metadata);
    let result = `color: ${colorMap[foreground]};`;
    if (fontStyle & 1) {
      result += "font-style: italic;";
    }
    if (fontStyle & 2) {
      result += "font-weight: bold;";
    }
    let textDecoration = "";
    if (fontStyle & 4) {
      textDecoration += " underline";
    }
    if (fontStyle & 8) {
      textDecoration += " line-through";
    }
    if (textDecoration) {
      result += `text-decoration:${textDecoration};`;
    }
    return result;
  }
  static getPresentationFromMetadata(metadata) {
    const foreground = this.getForeground(metadata);
    const fontStyle = this.getFontStyle(metadata);
    return {
      foreground,
      italic: Boolean(
        fontStyle & 1
        /* FontStyle.Italic */
      ),
      bold: Boolean(
        fontStyle & 2
        /* FontStyle.Bold */
      ),
      underline: Boolean(
        fontStyle & 4
        /* FontStyle.Underline */
      ),
      strikethrough: Boolean(
        fontStyle & 8
        /* FontStyle.Strikethrough */
      )
    };
  }
};

// out-build/vs/editor/common/core/offsetRange.js
var $0C = class _$0C {
  static addRange(range, sortedRanges) {
    let i2 = 0;
    while (i2 < sortedRanges.length && sortedRanges[i2].endExclusive < range.start) {
      i2++;
    }
    let j = i2;
    while (j < sortedRanges.length && sortedRanges[j].start <= range.endExclusive) {
      j++;
    }
    if (i2 === j) {
      sortedRanges.splice(i2, 0, range);
    } else {
      const start = Math.min(range.start, sortedRanges[i2].start);
      const end = Math.max(range.endExclusive, sortedRanges[j - 1].endExclusive);
      sortedRanges.splice(i2, j - i2, new _$0C(start, end));
    }
  }
  static tryCreate(start, endExclusive) {
    if (start > endExclusive) {
      return void 0;
    }
    return new _$0C(start, endExclusive);
  }
  static ofLength(length) {
    return new _$0C(0, length);
  }
  static ofStartAndLength(start, length) {
    return new _$0C(start, start + length);
  }
  static emptyAt(offset) {
    return new _$0C(offset, offset);
  }
  constructor(start, endExclusive) {
    this.start = start;
    this.endExclusive = endExclusive;
    if (start > endExclusive) {
      throw new $vb(`Invalid range: ${this.toString()}`);
    }
  }
  get isEmpty() {
    return this.start === this.endExclusive;
  }
  delta(offset) {
    return new _$0C(this.start + offset, this.endExclusive + offset);
  }
  deltaStart(offset) {
    return new _$0C(this.start + offset, this.endExclusive);
  }
  deltaEnd(offset) {
    return new _$0C(this.start, this.endExclusive + offset);
  }
  get length() {
    return this.endExclusive - this.start;
  }
  toString() {
    return `[${this.start}, ${this.endExclusive})`;
  }
  equals(other) {
    return this.start === other.start && this.endExclusive === other.endExclusive;
  }
  containsRange(other) {
    return this.start <= other.start && other.endExclusive <= this.endExclusive;
  }
  contains(offset) {
    return this.start <= offset && offset < this.endExclusive;
  }
  /**
   * for all numbers n: range1.contains(n) or range2.contains(n) => range1.join(range2).contains(n)
   * The joined range is the smallest range that contains both ranges.
   */
  join(other) {
    return new _$0C(Math.min(this.start, other.start), Math.max(this.endExclusive, other.endExclusive));
  }
  /**
   * for all numbers n: range1.contains(n) and range2.contains(n) <=> range1.intersect(range2).contains(n)
   *
   * The resulting range is empty if the ranges do not intersect, but touch.
   * If the ranges don't even touch, the result is undefined.
   */
  intersect(other) {
    const start = Math.max(this.start, other.start);
    const end = Math.min(this.endExclusive, other.endExclusive);
    if (start <= end) {
      return new _$0C(start, end);
    }
    return void 0;
  }
  intersectionLength(range) {
    const start = Math.max(this.start, range.start);
    const end = Math.min(this.endExclusive, range.endExclusive);
    return Math.max(0, end - start);
  }
  intersects(other) {
    const start = Math.max(this.start, other.start);
    const end = Math.min(this.endExclusive, other.endExclusive);
    return start < end;
  }
  intersectsOrTouches(other) {
    const start = Math.max(this.start, other.start);
    const end = Math.min(this.endExclusive, other.endExclusive);
    return start <= end;
  }
  isBefore(other) {
    return this.endExclusive <= other.start;
  }
  isAfter(other) {
    return this.start >= other.endExclusive;
  }
  slice(arr) {
    return arr.slice(this.start, this.endExclusive);
  }
  substring(str) {
    return str.substring(this.start, this.endExclusive);
  }
  /**
   * Returns the given value if it is contained in this instance, otherwise the closest value that is contained.
   * The range must not be empty.
   */
  clip(value) {
    if (this.isEmpty) {
      throw new $vb(`Invalid clipping range: ${this.toString()}`);
    }
    return Math.max(this.start, Math.min(this.endExclusive - 1, value));
  }
  /**
   * Returns `r := value + k * length` such that `r` is contained in this range.
   * The range must not be empty.
   *
   * E.g. `[5, 10).clipCyclic(10) === 5`, `[5, 10).clipCyclic(11) === 6` and `[5, 10).clipCyclic(4) === 9`.
   */
  clipCyclic(value) {
    if (this.isEmpty) {
      throw new $vb(`Invalid clipping range: ${this.toString()}`);
    }
    if (value < this.start) {
      return this.endExclusive - (this.start - value) % this.length;
    }
    if (value >= this.endExclusive) {
      return this.start + (value - this.start) % this.length;
    }
    return value;
  }
  map(f) {
    const result = [];
    for (let i2 = this.start; i2 < this.endExclusive; i2++) {
      result.push(f(i2));
    }
    return result;
  }
  forEach(f) {
    for (let i2 = this.start; i2 < this.endExclusive; i2++) {
      f(i2);
    }
  }
};
var $$C = class _$$C {
  constructor() {
    this.a = [];
  }
  addRange(range) {
    let i2 = 0;
    while (i2 < this.a.length && this.a[i2].endExclusive < range.start) {
      i2++;
    }
    let j = i2;
    while (j < this.a.length && this.a[j].start <= range.endExclusive) {
      j++;
    }
    if (i2 === j) {
      this.a.splice(i2, 0, range);
    } else {
      const start = Math.min(range.start, this.a[i2].start);
      const end = Math.max(range.endExclusive, this.a[j - 1].endExclusive);
      this.a.splice(i2, j - i2, new $0C(start, end));
    }
  }
  toString() {
    return this.a.map((r2) => r2.toString()).join(", ");
  }
  /**
   * Returns of there is a value that is contained in this instance and the given range.
   */
  intersectsStrict(other) {
    let i2 = 0;
    while (i2 < this.a.length && this.a[i2].endExclusive <= other.start) {
      i2++;
    }
    return i2 < this.a.length && this.a[i2].start < other.endExclusive;
  }
  intersectWithRange(other) {
    const result = new _$$C();
    for (const range of this.a) {
      const intersection = range.intersect(other);
      if (intersection) {
        result.addRange(intersection);
      }
    }
    return result;
  }
  intersectWithRangeLength(other) {
    return this.intersectWithRange(other).length;
  }
  get length() {
    return this.a.reduce((prev, cur) => prev + cur.length, 0);
  }
};

// out-build/vs/editor/common/tokens/tokenArray.js
var $uE = class _$uE {
  static create(tokenInfo) {
    return new _$uE(tokenInfo);
  }
  constructor(a) {
    this.a = a;
  }
  forEach(cb) {
    let lengthSum = 0;
    for (const tokenInfo of this.a) {
      const range = new $0C(lengthSum, lengthSum + tokenInfo.length);
      cb(range, tokenInfo);
      lengthSum += tokenInfo.length;
    }
  }
  slice(range) {
    const result = [];
    let lengthSum = 0;
    for (const tokenInfo of this.a) {
      const tokenStart = lengthSum;
      const tokenEndEx = tokenStart + tokenInfo.length;
      if (tokenEndEx > range.start) {
        if (tokenStart >= range.endExclusive) {
          break;
        }
        const deltaBefore = Math.max(0, range.start - tokenStart);
        const deltaAfter = Math.max(0, tokenEndEx - range.endExclusive);
        result.push(new $vE(tokenInfo.length - deltaBefore - deltaAfter, tokenInfo.metadata));
      }
      lengthSum += tokenInfo.length;
    }
    return _$uE.create(result);
  }
};
var $vE = class {
  constructor(length, metadata) {
    this.length = length;
    this.metadata = metadata;
  }
};
var $wE = class {
  constructor() {
    this.a = [];
  }
  add(length, metadata) {
    this.a.push(new $vE(length, metadata));
  }
  build() {
    return $uE.create(this.a);
  }
};

// out-build/vs/editor/common/tokens/lineTokens.js
var $xE = class _$xE {
  static createEmpty(lineContent, decoder2) {
    const defaultMetadata = _$xE.defaultTokenMetadata;
    const tokens = new Uint32Array(2);
    tokens[0] = lineContent.length;
    tokens[1] = defaultMetadata;
    return new _$xE(tokens, lineContent, decoder2);
  }
  static createFromTextAndMetadata(data, decoder2) {
    let offset = 0;
    let fullText = "";
    const tokens = new Array();
    for (const { text: text2, metadata } of data) {
      tokens.push(offset + text2.length, metadata);
      offset += text2.length;
      fullText += text2;
    }
    return new _$xE(new Uint32Array(tokens), fullText, decoder2);
  }
  static convertToEndOffset(tokens, lineTextLength) {
    const tokenCount = tokens.length >>> 1;
    const lastTokenIndex = tokenCount - 1;
    for (let tokenIndex = 0; tokenIndex < lastTokenIndex; tokenIndex++) {
      tokens[tokenIndex << 1] = tokens[tokenIndex + 1 << 1];
    }
    tokens[lastTokenIndex << 1] = lineTextLength;
  }
  static findIndexInTokensArray(tokens, desiredIndex) {
    if (tokens.length <= 2) {
      return 0;
    }
    let low = 0;
    let high = (tokens.length >>> 1) - 1;
    while (low < high) {
      const mid = low + Math.floor((high - low) / 2);
      const endOffset = tokens[mid << 1];
      if (endOffset === desiredIndex) {
        return mid + 1;
      } else if (endOffset < desiredIndex) {
        low = mid + 1;
      } else if (endOffset > desiredIndex) {
        high = mid;
      }
    }
    return low;
  }
  static {
    this.defaultTokenMetadata = (0 << 11 | 1 << 15 | 2 << 24) >>> 0;
  }
  constructor(tokens, text2, decoder2) {
    this._lineTokensBrand = void 0;
    this.a = tokens;
    this.b = this.a.length >>> 1;
    this.c = text2;
    this.languageIdCodec = decoder2;
  }
  equals(other) {
    if (other instanceof _$xE) {
      return this.slicedEquals(other, 0, this.b);
    }
    return false;
  }
  slicedEquals(other, sliceFromTokenIndex, sliceTokenCount) {
    if (this.c !== other.c) {
      return false;
    }
    if (this.b !== other.b) {
      return false;
    }
    const from = sliceFromTokenIndex << 1;
    const to = from + (sliceTokenCount << 1);
    for (let i2 = from; i2 < to; i2++) {
      if (this.a[i2] !== other.a[i2]) {
        return false;
      }
    }
    return true;
  }
  getLineContent() {
    return this.c;
  }
  getCount() {
    return this.b;
  }
  getStartOffset(tokenIndex) {
    if (tokenIndex > 0) {
      return this.a[tokenIndex - 1 << 1];
    }
    return 0;
  }
  getMetadata(tokenIndex) {
    const metadata = this.a[(tokenIndex << 1) + 1];
    return metadata;
  }
  getLanguageId(tokenIndex) {
    const metadata = this.a[(tokenIndex << 1) + 1];
    const languageId = $pE.getLanguageId(metadata);
    return this.languageIdCodec.decodeLanguageId(languageId);
  }
  getStandardTokenType(tokenIndex) {
    const metadata = this.a[(tokenIndex << 1) + 1];
    return $pE.getTokenType(metadata);
  }
  getForeground(tokenIndex) {
    const metadata = this.a[(tokenIndex << 1) + 1];
    return $pE.getForeground(metadata);
  }
  getClassName(tokenIndex) {
    const metadata = this.a[(tokenIndex << 1) + 1];
    return $pE.getClassNameFromMetadata(metadata);
  }
  getInlineStyle(tokenIndex, colorMap) {
    const metadata = this.a[(tokenIndex << 1) + 1];
    return $pE.getInlineStyleFromMetadata(metadata, colorMap);
  }
  getPresentation(tokenIndex) {
    const metadata = this.a[(tokenIndex << 1) + 1];
    return $pE.getPresentationFromMetadata(metadata);
  }
  getEndOffset(tokenIndex) {
    return this.a[tokenIndex << 1];
  }
  /**
   * Find the token containing offset `offset`.
   * @param offset The search offset
   * @return The index of the token containing the offset.
   */
  findTokenIndexAtOffset(offset) {
    return _$xE.findIndexInTokensArray(this.a, offset);
  }
  inflate() {
    return this;
  }
  sliceAndInflate(startOffset, endOffset, deltaOffset) {
    return new SliceLineTokens(this, startOffset, endOffset, deltaOffset);
  }
  /**
   * @pure
   * @param insertTokens Must be sorted by offset.
  */
  withInserted(insertTokens) {
    if (insertTokens.length === 0) {
      return this;
    }
    let nextOriginalTokenIdx = 0;
    let nextInsertTokenIdx = 0;
    let text2 = "";
    const newTokens = new Array();
    let originalEndOffset = 0;
    while (true) {
      const nextOriginalTokenEndOffset = nextOriginalTokenIdx < this.b ? this.a[nextOriginalTokenIdx << 1] : -1;
      const nextInsertToken = nextInsertTokenIdx < insertTokens.length ? insertTokens[nextInsertTokenIdx] : null;
      if (nextOriginalTokenEndOffset !== -1 && (nextInsertToken === null || nextOriginalTokenEndOffset <= nextInsertToken.offset)) {
        text2 += this.c.substring(originalEndOffset, nextOriginalTokenEndOffset);
        const metadata = this.a[(nextOriginalTokenIdx << 1) + 1];
        newTokens.push(text2.length, metadata);
        nextOriginalTokenIdx++;
        originalEndOffset = nextOriginalTokenEndOffset;
      } else if (nextInsertToken) {
        if (nextInsertToken.offset > originalEndOffset) {
          text2 += this.c.substring(originalEndOffset, nextInsertToken.offset);
          const metadata = this.a[(nextOriginalTokenIdx << 1) + 1];
          newTokens.push(text2.length, metadata);
          originalEndOffset = nextInsertToken.offset;
        }
        text2 += nextInsertToken.text;
        newTokens.push(text2.length, nextInsertToken.tokenMetadata);
        nextInsertTokenIdx++;
      } else {
        break;
      }
    }
    return new _$xE(new Uint32Array(newTokens), text2, this.languageIdCodec);
  }
  getTokensInRange(range) {
    const builder = new $wE();
    const startTokenIndex = this.findTokenIndexAtOffset(range.start);
    const endTokenIndex = this.findTokenIndexAtOffset(range.endExclusive);
    for (let tokenIndex = startTokenIndex; tokenIndex <= endTokenIndex; tokenIndex++) {
      const tokenRange = new $0C(this.getStartOffset(tokenIndex), this.getEndOffset(tokenIndex));
      const length = tokenRange.intersectionLength(range);
      if (length > 0) {
        builder.add(length, this.getMetadata(tokenIndex));
      }
    }
    return builder.build();
  }
  getTokenText(tokenIndex) {
    const startOffset = this.getStartOffset(tokenIndex);
    const endOffset = this.getEndOffset(tokenIndex);
    const text2 = this.c.substring(startOffset, endOffset);
    return text2;
  }
  forEach(callback) {
    const tokenCount = this.getCount();
    for (let tokenIndex = 0; tokenIndex < tokenCount; tokenIndex++) {
      callback(tokenIndex);
    }
  }
  toString() {
    let result = "";
    this.forEach((i2) => {
      result += `[${this.getTokenText(i2)}]{${this.getClassName(i2)}}`;
    });
    return result;
  }
};
var SliceLineTokens = class _SliceLineTokens {
  constructor(source, startOffset, endOffset, deltaOffset) {
    this.a = source;
    this.b = startOffset;
    this.c = endOffset;
    this.d = deltaOffset;
    this.e = source.findTokenIndexAtOffset(startOffset);
    this.languageIdCodec = source.languageIdCodec;
    this.f = 0;
    for (let i2 = this.e, len = source.getCount(); i2 < len; i2++) {
      const tokenStartOffset = source.getStartOffset(i2);
      if (tokenStartOffset >= endOffset) {
        break;
      }
      this.f++;
    }
  }
  getMetadata(tokenIndex) {
    return this.a.getMetadata(this.e + tokenIndex);
  }
  getLanguageId(tokenIndex) {
    return this.a.getLanguageId(this.e + tokenIndex);
  }
  getLineContent() {
    return this.a.getLineContent().substring(this.b, this.c);
  }
  equals(other) {
    if (other instanceof _SliceLineTokens) {
      return this.b === other.b && this.c === other.c && this.d === other.d && this.a.slicedEquals(other.a, this.e, this.f);
    }
    return false;
  }
  getCount() {
    return this.f;
  }
  getStandardTokenType(tokenIndex) {
    return this.a.getStandardTokenType(this.e + tokenIndex);
  }
  getForeground(tokenIndex) {
    return this.a.getForeground(this.e + tokenIndex);
  }
  getEndOffset(tokenIndex) {
    const tokenEndOffset = this.a.getEndOffset(this.e + tokenIndex);
    return Math.min(this.c, tokenEndOffset) - this.b + this.d;
  }
  getClassName(tokenIndex) {
    return this.a.getClassName(this.e + tokenIndex);
  }
  getInlineStyle(tokenIndex, colorMap) {
    return this.a.getInlineStyle(this.e + tokenIndex, colorMap);
  }
  getPresentation(tokenIndex) {
    return this.a.getPresentation(this.e + tokenIndex);
  }
  findTokenIndexAtOffset(offset) {
    return this.a.findTokenIndexAtOffset(offset + this.b - this.d) - this.e;
  }
  getTokenText(tokenIndex) {
    const adjustedTokenIndex = this.e + tokenIndex;
    const tokenStartOffset = this.a.getStartOffset(adjustedTokenIndex);
    const tokenEndOffset = this.a.getEndOffset(adjustedTokenIndex);
    let text2 = this.a.getTokenText(adjustedTokenIndex);
    if (tokenStartOffset < this.b) {
      text2 = text2.substring(this.b - tokenStartOffset);
    }
    if (tokenEndOffset > this.c) {
      text2 = text2.substring(0, text2.length - (tokenEndOffset - this.c));
    }
    return text2;
  }
  forEach(callback) {
    for (let tokenIndex = 0; tokenIndex < this.getCount(); tokenIndex++) {
      callback(tokenIndex);
    }
  }
};
function $yE(model, position) {
  const lineNumber = position.lineNumber;
  if (!model.tokenization.isCheapToTokenize(lineNumber)) {
    return void 0;
  }
  model.tokenization.forceTokenization(lineNumber);
  const lineTokens = model.tokenization.getLineTokens(lineNumber);
  const tokenIndex = lineTokens.findTokenIndexAtOffset(position.column - 1);
  const tokenType = lineTokens.getStandardTokenType(tokenIndex);
  return tokenType;
}

// out-build/vs/editor/common/languages/supports/indentationLineProcessor.js
var $u6 = class {
  constructor(model, indentRulesSupport, languageConfigurationService) {
    this.a = indentRulesSupport;
    this.b = new IndentationLineProcessor(model, languageConfigurationService);
  }
  /**
   * Apply the new indentation and return whether the indentation level should be increased after the given line number
   */
  shouldIncrease(lineNumber, newIndentation) {
    const processedLine = this.b.getProcessedLine(lineNumber, newIndentation);
    return this.a.shouldIncrease(processedLine);
  }
  /**
   * Apply the new indentation and return whether the indentation level should be decreased after the given line number
   */
  shouldDecrease(lineNumber, newIndentation) {
    const processedLine = this.b.getProcessedLine(lineNumber, newIndentation);
    return this.a.shouldDecrease(processedLine);
  }
  /**
   * Apply the new indentation and return whether the indentation level should remain unchanged at the given line number
   */
  shouldIgnore(lineNumber, newIndentation) {
    const processedLine = this.b.getProcessedLine(lineNumber, newIndentation);
    return this.a.shouldIgnore(processedLine);
  }
  /**
   * Apply the new indentation and return whether the indentation level should increase on the line after the given line number
   */
  shouldIndentNextLine(lineNumber, newIndentation) {
    const processedLine = this.b.getProcessedLine(lineNumber, newIndentation);
    return this.a.shouldIndentNextLine(processedLine);
  }
};
var $v6 = class {
  constructor(model, languageConfigurationService) {
    this.a = model;
    this.b = new IndentationLineProcessor(model, languageConfigurationService);
  }
  /**
   * Returns the processed text, stripped from the language configuration brackets within the string, comment and regex tokens, around the given range
   */
  getProcessedTokenContextAroundRange(range) {
    const beforeRangeProcessedTokens = this.c(range);
    const afterRangeProcessedTokens = this.d(range);
    const previousLineProcessedTokens = this.e(range);
    return { beforeRangeProcessedTokens, afterRangeProcessedTokens, previousLineProcessedTokens };
  }
  c(range) {
    this.a.tokenization.forceTokenization(range.startLineNumber);
    const lineTokens = this.a.tokenization.getLineTokens(range.startLineNumber);
    const scopedLineTokens = $2E(lineTokens, range.startColumn - 1);
    let slicedTokens;
    if ($w6(this.a, range.getStartPosition())) {
      const columnIndexWithinScope = range.startColumn - 1 - scopedLineTokens.firstCharOffset;
      const firstCharacterOffset = scopedLineTokens.firstCharOffset;
      const lastCharacterOffset = firstCharacterOffset + columnIndexWithinScope;
      slicedTokens = lineTokens.sliceAndInflate(firstCharacterOffset, lastCharacterOffset, 0);
    } else {
      const columnWithinLine = range.startColumn - 1;
      slicedTokens = lineTokens.sliceAndInflate(0, columnWithinLine, 0);
    }
    const processedTokens = this.b.getProcessedTokens(slicedTokens);
    return processedTokens;
  }
  d(range) {
    const position = range.isEmpty() ? range.getStartPosition() : range.getEndPosition();
    this.a.tokenization.forceTokenization(position.lineNumber);
    const lineTokens = this.a.tokenization.getLineTokens(position.lineNumber);
    const scopedLineTokens = $2E(lineTokens, position.column - 1);
    const columnIndexWithinScope = position.column - 1 - scopedLineTokens.firstCharOffset;
    const firstCharacterOffset = scopedLineTokens.firstCharOffset + columnIndexWithinScope;
    const lastCharacterOffset = scopedLineTokens.firstCharOffset + scopedLineTokens.getLineLength();
    const slicedTokens = lineTokens.sliceAndInflate(firstCharacterOffset, lastCharacterOffset, 0);
    const processedTokens = this.b.getProcessedTokens(slicedTokens);
    return processedTokens;
  }
  e(range) {
    const getScopedLineTokensAtEndColumnOfLine = (lineNumber) => {
      this.a.tokenization.forceTokenization(lineNumber);
      const lineTokens2 = this.a.tokenization.getLineTokens(lineNumber);
      const endColumnOfLine = this.a.getLineMaxColumn(lineNumber) - 1;
      const scopedLineTokensAtEndColumn = $2E(lineTokens2, endColumnOfLine);
      return scopedLineTokensAtEndColumn;
    };
    this.a.tokenization.forceTokenization(range.startLineNumber);
    const lineTokens = this.a.tokenization.getLineTokens(range.startLineNumber);
    const scopedLineTokens = $2E(lineTokens, range.startColumn - 1);
    const emptyTokens = $xE.createEmpty("", scopedLineTokens.languageIdCodec);
    const previousLineNumber = range.startLineNumber - 1;
    const isFirstLine = previousLineNumber === 0;
    if (isFirstLine) {
      return emptyTokens;
    }
    const canScopeExtendOnPreviousLine = scopedLineTokens.firstCharOffset === 0;
    if (!canScopeExtendOnPreviousLine) {
      return emptyTokens;
    }
    const scopedLineTokensAtEndColumnOfPreviousLine = getScopedLineTokensAtEndColumnOfLine(previousLineNumber);
    const doesLanguageContinueOnPreviousLine = scopedLineTokens.languageId === scopedLineTokensAtEndColumnOfPreviousLine.languageId;
    if (!doesLanguageContinueOnPreviousLine) {
      return emptyTokens;
    }
    const previousSlicedLineTokens = scopedLineTokensAtEndColumnOfPreviousLine.toIViewLineTokens();
    const processedTokens = this.b.getProcessedTokens(previousSlicedLineTokens);
    return processedTokens;
  }
};
var IndentationLineProcessor = class {
  constructor(a, b) {
    this.a = a;
    this.b = b;
  }
  /**
   * Get the processed line for the given line number and potentially adjust the indentation level.
   * Remove the language configuration brackets from the regex, string and comment tokens.
   */
  getProcessedLine(lineNumber, newIndentation) {
    const replaceIndentation = (line, newIndentation2) => {
      const currentIndentation = $Pf(line);
      const adjustedLine = newIndentation2 + line.substring(currentIndentation.length);
      return adjustedLine;
    };
    this.a.tokenization.forceTokenization?.(lineNumber);
    const tokens = this.a.tokenization.getLineTokens(lineNumber);
    let processedLine = this.getProcessedTokens(tokens).getLineContent();
    if (newIndentation !== void 0) {
      processedLine = replaceIndentation(processedLine, newIndentation);
    }
    return processedLine;
  }
  /**
   * Process the line with the given tokens, remove the language configuration brackets from the regex, string and comment tokens.
   */
  getProcessedTokens(tokens) {
    const shouldRemoveBracketsFromTokenType = (tokenType) => {
      return tokenType === 2 || tokenType === 3 || tokenType === 1;
    };
    const languageId = tokens.getLanguageId(0);
    const bracketsConfiguration = this.b.getLanguageConfiguration(languageId).bracketsNew;
    const bracketsRegExp = bracketsConfiguration.getBracketRegExp({ global: true });
    const textAndMetadata = [];
    tokens.forEach((tokenIndex) => {
      const tokenType = tokens.getStandardTokenType(tokenIndex);
      let text2 = tokens.getTokenText(tokenIndex);
      if (shouldRemoveBracketsFromTokenType(tokenType)) {
        text2 = text2.replace(bracketsRegExp, "");
      }
      const metadata = tokens.getMetadata(tokenIndex);
      textAndMetadata.push({ text: text2, metadata });
    });
    const processedLineTokens = $xE.createFromTextAndMetadata(textAndMetadata, tokens.languageIdCodec);
    return processedLineTokens;
  }
};
function $w6(model, position) {
  model.tokenization.forceTokenization(position.lineNumber);
  const lineTokens = model.tokenization.getLineTokens(position.lineNumber);
  const scopedLineTokens = $2E(lineTokens, position.column - 1);
  const doesScopeStartAtOffsetZero = scopedLineTokens.firstCharOffset === 0;
  const isScopedLanguageEqualToFirstLanguageOnLine = lineTokens.getLanguageId(0) === scopedLineTokens.languageId;
  const languageIsDifferentFromLineStart = !doesScopeStartAtOffsetZero && !isScopedLanguageEqualToFirstLanguageOnLine;
  return languageIsDifferentFromLineStart;
}

// out-build/vs/editor/common/languages/enterAction.js
function $x6(autoIndent, model, range, languageConfigurationService) {
  model.tokenization.forceTokenization(range.startLineNumber);
  const languageId = model.getLanguageIdAtPosition(range.startLineNumber, range.startColumn);
  const richEditSupport = languageConfigurationService.getLanguageConfiguration(languageId);
  if (!richEditSupport) {
    return null;
  }
  const indentationContextProcessor = new $v6(model, languageConfigurationService);
  const processedContextTokens = indentationContextProcessor.getProcessedTokenContextAroundRange(range);
  const previousLineText = processedContextTokens.previousLineProcessedTokens.getLineContent();
  const beforeEnterText = processedContextTokens.beforeRangeProcessedTokens.getLineContent();
  const afterEnterText = processedContextTokens.afterRangeProcessedTokens.getLineContent();
  const enterResult = richEditSupport.onEnter(autoIndent, previousLineText, beforeEnterText, afterEnterText);
  if (!enterResult) {
    return null;
  }
  const indentAction = enterResult.indentAction;
  let appendText = enterResult.appendText;
  const removeText = enterResult.removeText || 0;
  if (!appendText) {
    if (indentAction === IndentAction.Indent || indentAction === IndentAction.IndentOutdent) {
      appendText = "	";
    } else {
      appendText = "";
    }
  } else if (indentAction === IndentAction.Indent) {
    appendText = "	" + appendText;
  }
  let indentation = $PF(model, range.startLineNumber, range.startColumn);
  if (removeText) {
    indentation = indentation.substring(0, indentation.length - removeText);
  }
  return {
    indentAction,
    appendText,
    removeText,
    indentation
  };
}

// out-build/vs/editor/common/commands/shiftCommand.js
var $y6_1;
var repeatCache = /* @__PURE__ */ Object.create(null);
function cachedStringRepeat(str, count) {
  if (count <= 0) {
    return "";
  }
  if (!repeatCache[str]) {
    repeatCache[str] = ["", str];
  }
  const cache2 = repeatCache[str];
  for (let i2 = cache2.length; i2 <= count; i2++) {
    cache2[i2] = cache2[i2 - 1] + str;
  }
  return cache2[count];
}
var $y6 = $y6_1 = class $y62 {
  static unshiftIndent(line, column, tabSize, indentSize, insertSpaces) {
    const contentStartVisibleColumn = $cF.visibleColumnFromColumn(line, column, tabSize);
    if (insertSpaces) {
      const indent = cachedStringRepeat(" ", indentSize);
      const desiredTabStop = $cF.prevIndentTabStop(contentStartVisibleColumn, indentSize);
      const indentCount = desiredTabStop / indentSize;
      return cachedStringRepeat(indent, indentCount);
    } else {
      const indent = "	";
      const desiredTabStop = $cF.prevRenderTabStop(contentStartVisibleColumn, tabSize);
      const indentCount = desiredTabStop / tabSize;
      return cachedStringRepeat(indent, indentCount);
    }
  }
  static shiftIndent(line, column, tabSize, indentSize, insertSpaces) {
    const contentStartVisibleColumn = $cF.visibleColumnFromColumn(line, column, tabSize);
    if (insertSpaces) {
      const indent = cachedStringRepeat(" ", indentSize);
      const desiredTabStop = $cF.nextIndentTabStop(contentStartVisibleColumn, indentSize);
      const indentCount = desiredTabStop / indentSize;
      return cachedStringRepeat(indent, indentCount);
    } else {
      const indent = "	";
      const desiredTabStop = $cF.nextRenderTabStop(contentStartVisibleColumn, tabSize);
      const indentCount = desiredTabStop / tabSize;
      return cachedStringRepeat(indent, indentCount);
    }
  }
  constructor(range, opts, f) {
    this.f = f;
    this.a = opts;
    this.b = range;
    this.c = null;
    this.d = false;
    this.e = false;
  }
  g(builder, range, text2) {
    if (this.d) {
      builder.addTrackedEditOperation(range, text2);
    } else {
      builder.addEditOperation(range, text2);
    }
  }
  getEditOperations(model, builder) {
    const startLine = this.b.startLineNumber;
    let endLine = this.b.endLineNumber;
    if (this.b.endColumn === 1 && startLine !== endLine) {
      endLine = endLine - 1;
    }
    const { tabSize, indentSize, insertSpaces } = this.a;
    const shouldIndentEmptyLines = startLine === endLine;
    if (this.a.useTabStops) {
      if (this.b.isEmpty()) {
        if (/^\s*$/.test(model.getLineContent(startLine))) {
          this.d = true;
        }
      }
      let previousLineExtraSpaces = 0, extraSpaces = 0;
      for (let lineNumber = startLine; lineNumber <= endLine; lineNumber++, previousLineExtraSpaces = extraSpaces) {
        extraSpaces = 0;
        const lineText = model.getLineContent(lineNumber);
        let indentationEndIndex = $Of(lineText);
        if (this.a.isUnshift && (lineText.length === 0 || indentationEndIndex === 0)) {
          continue;
        }
        if (!shouldIndentEmptyLines && !this.a.isUnshift && lineText.length === 0) {
          continue;
        }
        if (indentationEndIndex === -1) {
          indentationEndIndex = lineText.length;
        }
        if (lineNumber > 1) {
          const contentStartVisibleColumn = $cF.visibleColumnFromColumn(lineText, indentationEndIndex + 1, tabSize);
          if (contentStartVisibleColumn % indentSize !== 0) {
            if (model.tokenization.isCheapToTokenize(lineNumber - 1)) {
              const enterAction = $x6(this.a.autoIndent, model, new $9C(lineNumber - 1, model.getLineMaxColumn(lineNumber - 1), lineNumber - 1, model.getLineMaxColumn(lineNumber - 1)), this.f);
              if (enterAction) {
                extraSpaces = previousLineExtraSpaces;
                if (enterAction.appendText) {
                  for (let j = 0, lenJ = enterAction.appendText.length; j < lenJ && extraSpaces < indentSize; j++) {
                    if (enterAction.appendText.charCodeAt(j) === 32) {
                      extraSpaces++;
                    } else {
                      break;
                    }
                  }
                }
                if (enterAction.removeText) {
                  extraSpaces = Math.max(0, extraSpaces - enterAction.removeText);
                }
                for (let j = 0; j < extraSpaces; j++) {
                  if (indentationEndIndex === 0 || lineText.charCodeAt(indentationEndIndex - 1) !== 32) {
                    break;
                  }
                  indentationEndIndex--;
                }
              }
            }
          }
        }
        if (this.a.isUnshift && indentationEndIndex === 0) {
          continue;
        }
        let desiredIndent;
        if (this.a.isUnshift) {
          desiredIndent = $y6_1.unshiftIndent(lineText, indentationEndIndex + 1, tabSize, indentSize, insertSpaces);
        } else {
          desiredIndent = $y6_1.shiftIndent(lineText, indentationEndIndex + 1, tabSize, indentSize, insertSpaces);
        }
        this.g(builder, new $9C(lineNumber, 1, lineNumber, indentationEndIndex + 1), desiredIndent);
        if (lineNumber === startLine && !this.b.isEmpty()) {
          this.e = this.b.startColumn <= indentationEndIndex + 1;
        }
      }
    } else {
      if (!this.a.isUnshift && this.b.isEmpty() && model.getLineLength(startLine) === 0) {
        this.d = true;
      }
      const oneIndent = insertSpaces ? cachedStringRepeat(" ", indentSize) : "	";
      for (let lineNumber = startLine; lineNumber <= endLine; lineNumber++) {
        const lineText = model.getLineContent(lineNumber);
        let indentationEndIndex = $Of(lineText);
        if (this.a.isUnshift && (lineText.length === 0 || indentationEndIndex === 0)) {
          continue;
        }
        if (!shouldIndentEmptyLines && !this.a.isUnshift && lineText.length === 0) {
          continue;
        }
        if (indentationEndIndex === -1) {
          indentationEndIndex = lineText.length;
        }
        if (this.a.isUnshift && indentationEndIndex === 0) {
          continue;
        }
        if (this.a.isUnshift) {
          indentationEndIndex = Math.min(indentationEndIndex, indentSize);
          for (let i2 = 0; i2 < indentationEndIndex; i2++) {
            const chr = lineText.charCodeAt(i2);
            if (chr === 9) {
              indentationEndIndex = i2 + 1;
              break;
            }
          }
          this.g(builder, new $9C(lineNumber, 1, lineNumber, indentationEndIndex + 1), "");
        } else {
          this.g(builder, new $9C(lineNumber, 1, lineNumber, 1), oneIndent);
          if (lineNumber === startLine && !this.b.isEmpty()) {
            this.e = this.b.startColumn === 1;
          }
        }
      }
    }
    this.c = builder.trackSelection(this.b);
  }
  computeCursorState(model, helper) {
    if (this.d) {
      const lastOp = helper.getInverseEditOperations()[0];
      return new $_D(lastOp.range.endLineNumber, lastOp.range.endColumn, lastOp.range.endLineNumber, lastOp.range.endColumn);
    }
    const result = helper.getTrackedSelection(this.c);
    if (this.e) {
      const initialStartColumn = this.b.startColumn;
      const resultStartColumn = result.startColumn;
      if (resultStartColumn <= initialStartColumn) {
        return result;
      }
      if (result.getDirection() === 0) {
        return new $_D(result.startLineNumber, initialStartColumn, result.endLineNumber, result.endColumn);
      }
      return new $_D(result.endLineNumber, result.endColumn, result.startLineNumber, initialStartColumn);
    }
    return result;
  }
};
$y6 = $y6_1 = __decorate([
  __param(2, $NF)
], $y6);

// out-build/vs/editor/common/commands/surroundSelectionCommand.js
var $z6 = class {
  constructor(range, charBeforeSelection, charAfterSelection) {
    this.a = range;
    this.b = charBeforeSelection;
    this.c = charAfterSelection;
  }
  getEditOperations(model, builder) {
    builder.addTrackedEditOperation(new $9C(this.a.startLineNumber, this.a.startColumn, this.a.startLineNumber, this.a.startColumn), this.b);
    builder.addTrackedEditOperation(new $9C(this.a.endLineNumber, this.a.endColumn, this.a.endLineNumber, this.a.endColumn), this.c);
  }
  computeCursorState(model, helper) {
    const inverseEditOperations = helper.getInverseEditOperations();
    const firstOperationRange = inverseEditOperations[0].range;
    const secondOperationRange = inverseEditOperations[1].range;
    return new $_D(firstOperationRange.endLineNumber, firstOperationRange.endColumn, secondOperationRange.endLineNumber, secondOperationRange.endColumn - this.c.length);
  }
};
var $A6 = class {
  constructor(a, b, c) {
    this.a = a;
    this.b = b;
    this.c = c;
  }
  getEditOperations(model, builder) {
    builder.addTrackedEditOperation(new $9C(this.a.lineNumber, this.a.column, this.a.lineNumber, this.a.column), this.b + this.c);
  }
  computeCursorState(model, helper) {
    const inverseEditOperations = helper.getInverseEditOperations();
    const opRange = inverseEditOperations[0].range;
    return new $_D(opRange.endLineNumber, opRange.startColumn, opRange.endLineNumber, opRange.endColumn - this.c.length);
  }
};

// out-build/vs/editor/common/languages/autoIndent.js
function getPrecedingValidLine(model, lineNumber, processedIndentRulesSupport) {
  const languageId = model.tokenization.getLanguageIdAtPosition(lineNumber, 0);
  if (lineNumber > 1) {
    let lastLineNumber;
    let resultLineNumber = -1;
    for (lastLineNumber = lineNumber - 1; lastLineNumber >= 1; lastLineNumber--) {
      if (model.tokenization.getLanguageIdAtPosition(lastLineNumber, 0) !== languageId) {
        return resultLineNumber;
      }
      const text2 = model.getLineContent(lastLineNumber);
      if (processedIndentRulesSupport.shouldIgnore(lastLineNumber) || /^\s+$/.test(text2) || text2 === "") {
        resultLineNumber = lastLineNumber;
        continue;
      }
      return lastLineNumber;
    }
  }
  return -1;
}
function $p6(autoIndent, model, lineNumber, honorIntentialIndent = true, languageConfigurationService) {
  if (autoIndent < 4) {
    return null;
  }
  const indentRulesSupport = languageConfigurationService.getLanguageConfiguration(model.tokenization.getLanguageId()).indentRulesSupport;
  if (!indentRulesSupport) {
    return null;
  }
  const processedIndentRulesSupport = new $u6(model, indentRulesSupport, languageConfigurationService);
  if (lineNumber <= 1) {
    return {
      indentation: "",
      action: null
    };
  }
  for (let priorLineNumber = lineNumber - 1; priorLineNumber > 0; priorLineNumber--) {
    if (model.getLineContent(priorLineNumber) !== "") {
      break;
    }
    if (priorLineNumber === 1) {
      return {
        indentation: "",
        action: null
      };
    }
  }
  const precedingUnIgnoredLine = getPrecedingValidLine(model, lineNumber, processedIndentRulesSupport);
  if (precedingUnIgnoredLine < 0) {
    return null;
  } else if (precedingUnIgnoredLine < 1) {
    return {
      indentation: "",
      action: null
    };
  }
  if (processedIndentRulesSupport.shouldIncrease(precedingUnIgnoredLine) || processedIndentRulesSupport.shouldIndentNextLine(precedingUnIgnoredLine)) {
    const precedingUnIgnoredLineContent = model.getLineContent(precedingUnIgnoredLine);
    return {
      indentation: $Pf(precedingUnIgnoredLineContent),
      action: IndentAction.Indent,
      line: precedingUnIgnoredLine
    };
  } else if (processedIndentRulesSupport.shouldDecrease(precedingUnIgnoredLine)) {
    const precedingUnIgnoredLineContent = model.getLineContent(precedingUnIgnoredLine);
    return {
      indentation: $Pf(precedingUnIgnoredLineContent),
      action: null,
      line: precedingUnIgnoredLine
    };
  } else {
    if (precedingUnIgnoredLine === 1) {
      return {
        indentation: $Pf(model.getLineContent(precedingUnIgnoredLine)),
        action: null,
        line: precedingUnIgnoredLine
      };
    }
    const previousLine = precedingUnIgnoredLine - 1;
    const previousLineIndentMetadata = indentRulesSupport.getIndentMetadata(model.getLineContent(previousLine));
    if (!(previousLineIndentMetadata & (1 | 2)) && previousLineIndentMetadata & 4) {
      let stopLine = 0;
      for (let i2 = previousLine - 1; i2 > 0; i2--) {
        if (processedIndentRulesSupport.shouldIndentNextLine(i2)) {
          continue;
        }
        stopLine = i2;
        break;
      }
      return {
        indentation: $Pf(model.getLineContent(stopLine + 1)),
        action: null,
        line: stopLine + 1
      };
    }
    if (honorIntentialIndent) {
      return {
        indentation: $Pf(model.getLineContent(precedingUnIgnoredLine)),
        action: null,
        line: precedingUnIgnoredLine
      };
    } else {
      for (let i2 = precedingUnIgnoredLine; i2 > 0; i2--) {
        if (processedIndentRulesSupport.shouldIncrease(i2)) {
          return {
            indentation: $Pf(model.getLineContent(i2)),
            action: IndentAction.Indent,
            line: i2
          };
        } else if (processedIndentRulesSupport.shouldIndentNextLine(i2)) {
          let stopLine = 0;
          for (let j = i2 - 1; j > 0; j--) {
            if (processedIndentRulesSupport.shouldIndentNextLine(i2)) {
              continue;
            }
            stopLine = j;
            break;
          }
          return {
            indentation: $Pf(model.getLineContent(stopLine + 1)),
            action: null,
            line: stopLine + 1
          };
        } else if (processedIndentRulesSupport.shouldDecrease(i2)) {
          return {
            indentation: $Pf(model.getLineContent(i2)),
            action: null,
            line: i2
          };
        }
      }
      return {
        indentation: $Pf(model.getLineContent(1)),
        action: null,
        line: 1
      };
    }
  }
}
function $q6(autoIndent, virtualModel, languageId, lineNumber, indentConverter, languageConfigurationService) {
  if (autoIndent < 4) {
    return null;
  }
  const richEditSupport = languageConfigurationService.getLanguageConfiguration(languageId);
  if (!richEditSupport) {
    return null;
  }
  const indentRulesSupport = languageConfigurationService.getLanguageConfiguration(languageId).indentRulesSupport;
  if (!indentRulesSupport) {
    return null;
  }
  const processedIndentRulesSupport = new $u6(virtualModel, indentRulesSupport, languageConfigurationService);
  const indent = $p6(autoIndent, virtualModel, lineNumber, void 0, languageConfigurationService);
  if (indent) {
    const inheritLine = indent.line;
    if (inheritLine !== void 0) {
      let shouldApplyEnterRules = true;
      for (let inBetweenLine = inheritLine; inBetweenLine < lineNumber - 1; inBetweenLine++) {
        if (!/^\s*$/.test(virtualModel.getLineContent(inBetweenLine))) {
          shouldApplyEnterRules = false;
          break;
        }
      }
      if (shouldApplyEnterRules) {
        const enterResult = richEditSupport.onEnter(autoIndent, "", virtualModel.getLineContent(inheritLine), "");
        if (enterResult) {
          let indentation = $Pf(virtualModel.getLineContent(inheritLine));
          if (enterResult.removeText) {
            indentation = indentation.substring(0, indentation.length - enterResult.removeText);
          }
          if (enterResult.indentAction === IndentAction.Indent || enterResult.indentAction === IndentAction.IndentOutdent) {
            indentation = indentConverter.shiftIndent(indentation);
          } else if (enterResult.indentAction === IndentAction.Outdent) {
            indentation = indentConverter.unshiftIndent(indentation);
          }
          if (processedIndentRulesSupport.shouldDecrease(lineNumber)) {
            indentation = indentConverter.unshiftIndent(indentation);
          }
          if (enterResult.appendText) {
            indentation += enterResult.appendText;
          }
          return $Pf(indentation);
        }
      }
    }
    if (processedIndentRulesSupport.shouldDecrease(lineNumber)) {
      if (indent.action === IndentAction.Indent) {
        return indent.indentation;
      } else {
        return indentConverter.unshiftIndent(indent.indentation);
      }
    } else {
      if (indent.action === IndentAction.Indent) {
        return indentConverter.shiftIndent(indent.indentation);
      } else {
        return indent.indentation;
      }
    }
  }
  return null;
}
function $r6(autoIndent, model, range, indentConverter, languageConfigurationService) {
  if (autoIndent < 4) {
    return null;
  }
  const languageId = model.getLanguageIdAtPosition(range.startLineNumber, range.startColumn);
  const indentRulesSupport = languageConfigurationService.getLanguageConfiguration(languageId).indentRulesSupport;
  if (!indentRulesSupport) {
    return null;
  }
  model.tokenization.forceTokenization(range.startLineNumber);
  const indentationContextProcessor = new $v6(model, languageConfigurationService);
  const processedContextTokens = indentationContextProcessor.getProcessedTokenContextAroundRange(range);
  const afterEnterProcessedTokens = processedContextTokens.afterRangeProcessedTokens;
  const beforeEnterProcessedTokens = processedContextTokens.beforeRangeProcessedTokens;
  const beforeEnterIndent = $Pf(beforeEnterProcessedTokens.getLineContent());
  const virtualModel = createVirtualModelWithModifiedTokensAtLine(model, range.startLineNumber, beforeEnterProcessedTokens);
  const languageIsDifferentFromLineStart = $w6(model, range.getStartPosition());
  const currentLine = model.getLineContent(range.startLineNumber);
  const currentLineIndent = $Pf(currentLine);
  const afterEnterAction = $p6(autoIndent, virtualModel, range.startLineNumber + 1, void 0, languageConfigurationService);
  if (!afterEnterAction) {
    const beforeEnter = languageIsDifferentFromLineStart ? currentLineIndent : beforeEnterIndent;
    return {
      beforeEnter,
      afterEnter: beforeEnter
    };
  }
  let afterEnterIndent = languageIsDifferentFromLineStart ? currentLineIndent : afterEnterAction.indentation;
  if (afterEnterAction.action === IndentAction.Indent) {
    afterEnterIndent = indentConverter.shiftIndent(afterEnterIndent);
  }
  if (indentRulesSupport.shouldDecrease(afterEnterProcessedTokens.getLineContent())) {
    afterEnterIndent = indentConverter.unshiftIndent(afterEnterIndent);
  }
  return {
    beforeEnter: languageIsDifferentFromLineStart ? currentLineIndent : beforeEnterIndent,
    afterEnter: afterEnterIndent
  };
}
function $s6(cursorConfig, model, range, ch, indentConverter, languageConfigurationService) {
  const autoIndent = cursorConfig.autoIndent;
  if (autoIndent < 4) {
    return null;
  }
  const languageIsDifferentFromLineStart = $w6(model, range.getStartPosition());
  if (languageIsDifferentFromLineStart) {
    return null;
  }
  const languageId = model.getLanguageIdAtPosition(range.startLineNumber, range.startColumn);
  const indentRulesSupport = languageConfigurationService.getLanguageConfiguration(languageId).indentRulesSupport;
  if (!indentRulesSupport) {
    return null;
  }
  const indentationContextProcessor = new $v6(model, languageConfigurationService);
  const processedContextTokens = indentationContextProcessor.getProcessedTokenContextAroundRange(range);
  const beforeRangeText = processedContextTokens.beforeRangeProcessedTokens.getLineContent();
  const afterRangeText = processedContextTokens.afterRangeProcessedTokens.getLineContent();
  const textAroundRange = beforeRangeText + afterRangeText;
  const textAroundRangeWithCharacter = beforeRangeText + ch + afterRangeText;
  if (!indentRulesSupport.shouldDecrease(textAroundRange) && indentRulesSupport.shouldDecrease(textAroundRangeWithCharacter)) {
    const r2 = $p6(autoIndent, model, range.startLineNumber, false, languageConfigurationService);
    if (!r2) {
      return null;
    }
    let indentation = r2.indentation;
    if (r2.action !== IndentAction.Indent) {
      indentation = indentConverter.unshiftIndent(indentation);
    }
    return indentation;
  }
  const previousLineNumber = range.startLineNumber - 1;
  if (previousLineNumber > 0) {
    const previousLine = model.getLineContent(previousLineNumber);
    if (indentRulesSupport.shouldIndentNextLine(previousLine) && indentRulesSupport.shouldIncrease(textAroundRangeWithCharacter)) {
      const inheritedIndentationData = $p6(autoIndent, model, range.startLineNumber, false, languageConfigurationService);
      const inheritedIndentation = inheritedIndentationData?.indentation;
      if (inheritedIndentation !== void 0) {
        const currentLine = model.getLineContent(range.startLineNumber);
        const actualCurrentIndentation = $Pf(currentLine);
        const inferredCurrentIndentation = indentConverter.shiftIndent(inheritedIndentation);
        const inferredIndentationEqualsActual = inferredCurrentIndentation === actualCurrentIndentation;
        const textAroundRangeContainsOnlyWhitespace = /^\s*$/.test(textAroundRange);
        const autoClosingPairs = cursorConfig.autoClosingPairs.autoClosingPairsOpenByEnd.get(ch);
        const autoClosingPairExists = autoClosingPairs && autoClosingPairs.length > 0;
        const isChFirstNonWhitespaceCharacterAndInAutoClosingPair = autoClosingPairExists && textAroundRangeContainsOnlyWhitespace;
        if (inferredIndentationEqualsActual && isChFirstNonWhitespaceCharacterAndInAutoClosingPair) {
          return inheritedIndentation;
        }
      }
    }
  }
  return null;
}
function $t6(model, lineNumber, languageConfigurationService) {
  const indentRulesSupport = languageConfigurationService.getLanguageConfiguration(model.getLanguageId()).indentRulesSupport;
  if (!indentRulesSupport) {
    return null;
  }
  if (lineNumber < 1 || lineNumber > model.getLineCount()) {
    return null;
  }
  return indentRulesSupport.getIndentMetadata(model.getLineContent(lineNumber));
}
function createVirtualModelWithModifiedTokensAtLine(model, modifiedLineNumber, modifiedTokens) {
  const virtualModel = {
    tokenization: {
      getLineTokens: (lineNumber) => {
        if (lineNumber === modifiedLineNumber) {
          return modifiedTokens;
        } else {
          return model.tokenization.getLineTokens(lineNumber);
        }
      },
      getLanguageId: () => {
        return model.getLanguageId();
      },
      getLanguageIdAtPosition: (lineNumber, column) => {
        return model.getLanguageIdAtPosition(lineNumber, column);
      }
    },
    getLineContent: (lineNumber) => {
      if (lineNumber === modifiedLineNumber) {
        return modifiedTokens.getLineContent();
      } else {
        return model.getLineContent(lineNumber);
      }
    }
  };
  return virtualModel;
}

// out-build/vs/editor/common/cursor/cursorTypeEditOperations.js
var $B6 = class {
  static getEdits(config, model, selections, ch, isDoingComposition) {
    if (!isDoingComposition && this.a(config, model, selections)) {
      const indentationForSelections = [];
      for (const selection of selections) {
        const indentation = this.b(config, model, selection, ch);
        if (indentation === null) {
          return;
        }
        indentationForSelections.push({ selection, indentation });
      }
      const autoClosingPairClose = $E6.getAutoClosingPairClose(config, model, selections, ch, false);
      return this.c(config, model, indentationForSelections, ch, autoClosingPairClose);
    }
    return;
  }
  static a(config, model, selections) {
    if (config.autoIndent < 4) {
      return false;
    }
    for (let i2 = 0, len = selections.length; i2 < len; i2++) {
      if (!model.tokenization.isCheapToTokenize(selections[i2].getEndPosition().lineNumber)) {
        return false;
      }
    }
    return true;
  }
  static b(config, model, selection, ch) {
    const actualIndentation = $s6(config, model, selection, ch, {
      shiftIndent: (indentation) => {
        return $P6(config, indentation);
      },
      unshiftIndent: (indentation) => {
        return $Q6(config, indentation);
      }
    }, config.languageConfigurationService);
    if (actualIndentation === null) {
      return null;
    }
    const currentIndentation = $PF(model, selection.startLineNumber, selection.startColumn);
    if (actualIndentation === config.normalizeIndentation(currentIndentation)) {
      return null;
    }
    return actualIndentation;
  }
  static c(config, model, indentationForSelections, ch, autoClosingPairClose) {
    const commands2 = indentationForSelections.map(({ selection, indentation }) => {
      if (autoClosingPairClose !== null) {
        const indentationEdit = this.d(config, model, indentation, selection, ch, false);
        return new TypeWithIndentationAndAutoClosingCommand(indentationEdit, selection, ch, autoClosingPairClose);
      } else {
        const indentationEdit = this.d(config, model, indentation, selection, ch, true);
        return typeCommand(indentationEdit.range, indentationEdit.text, false);
      }
    });
    const editOptions = { shouldPushStackElementBefore: true, shouldPushStackElementAfter: false };
    return new $i5(4, commands2, editOptions);
  }
  static d(config, model, indentation, selection, ch, includeChInEdit = true) {
    const startLineNumber = selection.startLineNumber;
    const firstNonWhitespaceColumn = model.getLineFirstNonWhitespaceColumn(startLineNumber);
    let text2 = config.normalizeIndentation(indentation);
    if (firstNonWhitespaceColumn !== 0) {
      const startLine = model.getLineContent(startLineNumber);
      text2 += startLine.substring(firstNonWhitespaceColumn - 1, selection.startColumn - 1);
    }
    text2 += includeChInEdit ? ch : "";
    const range = new $9C(startLineNumber, 1, selection.endLineNumber, selection.endColumn);
    return { range, text: text2 };
  }
};
var $C6 = class {
  static getEdits(prevEditOperationType, config, model, selections, autoClosedCharacters, ch) {
    if (isAutoClosingOvertype(config, model, selections, autoClosedCharacters, ch)) {
      return this.a(prevEditOperationType, selections, ch);
    }
    return;
  }
  static a(prevEditOperationType, selections, ch) {
    const commands2 = [];
    for (let i2 = 0, len = selections.length; i2 < len; i2++) {
      const selection = selections[i2];
      const position = selection.getPosition();
      const typeSelection = new $9C(position.lineNumber, position.column, position.lineNumber, position.column + 1);
      commands2[i2] = new $b6(typeSelection, ch);
    }
    return new $i5(4, commands2, {
      shouldPushStackElementBefore: shouldPushStackElementBetween(
        prevEditOperationType,
        4
        /* EditOperationType.TypingOther */
      ),
      shouldPushStackElementAfter: false
    });
  }
};
var $D6 = class {
  static getEdits(config, model, selections, autoClosedCharacters, ch) {
    if (isAutoClosingOvertype(config, model, selections, autoClosedCharacters, ch)) {
      const commands2 = selections.map((s) => new $b6(new $9C(s.positionLineNumber, s.positionColumn, s.positionLineNumber, s.positionColumn + 1), "", false));
      return new $i5(4, commands2, {
        shouldPushStackElementBefore: true,
        shouldPushStackElementAfter: false
      });
    }
    return;
  }
};
var $E6 = class {
  static getEdits(config, model, selections, ch, chIsAlreadyTyped, isDoingComposition) {
    if (!isDoingComposition) {
      const autoClosingPairClose = this.getAutoClosingPairClose(config, model, selections, ch, chIsAlreadyTyped);
      if (autoClosingPairClose !== null) {
        return this.a(selections, ch, chIsAlreadyTyped, autoClosingPairClose);
      }
    }
    return;
  }
  static a(selections, ch, chIsAlreadyTyped, autoClosingPairClose) {
    const commands2 = [];
    for (let i2 = 0, len = selections.length; i2 < len; i2++) {
      const selection = selections[i2];
      commands2[i2] = new TypeWithAutoClosingCommand(selection, ch, !chIsAlreadyTyped, autoClosingPairClose);
    }
    return new $i5(4, commands2, {
      shouldPushStackElementBefore: true,
      shouldPushStackElementAfter: false
    });
  }
  static getAutoClosingPairClose(config, model, selections, ch, chIsAlreadyTyped) {
    for (const selection of selections) {
      if (!selection.isEmpty()) {
        return null;
      }
    }
    const positions = selections.map((s) => {
      const position = s.getPosition();
      if (chIsAlreadyTyped) {
        return { lineNumber: position.lineNumber, beforeColumn: position.column - ch.length, afterColumn: position.column };
      } else {
        return { lineNumber: position.lineNumber, beforeColumn: position.column, afterColumn: position.column };
      }
    });
    const pair = this.c(config, model, positions.map((p) => new $8C(p.lineNumber, p.beforeColumn)), ch);
    if (!pair) {
      return null;
    }
    let autoCloseConfig;
    let shouldAutoCloseBefore;
    const chIsQuote = $j5(ch);
    if (chIsQuote) {
      autoCloseConfig = config.autoClosingQuotes;
      shouldAutoCloseBefore = config.shouldAutoCloseBefore.quote;
    } else {
      const pairIsForComments = config.blockCommentStartToken ? pair.open.includes(config.blockCommentStartToken) : false;
      if (pairIsForComments) {
        autoCloseConfig = config.autoClosingComments;
        shouldAutoCloseBefore = config.shouldAutoCloseBefore.comment;
      } else {
        autoCloseConfig = config.autoClosingBrackets;
        shouldAutoCloseBefore = config.shouldAutoCloseBefore.bracket;
      }
    }
    if (autoCloseConfig === "never") {
      return null;
    }
    const containedPair = this.b(config, pair);
    const containedPairClose = containedPair ? containedPair.close : "";
    let isContainedPairPresent = true;
    for (const position of positions) {
      const { lineNumber, beforeColumn, afterColumn } = position;
      const lineText = model.getLineContent(lineNumber);
      const lineBefore = lineText.substring(0, beforeColumn - 1);
      const lineAfter = lineText.substring(afterColumn - 1);
      if (!lineAfter.startsWith(containedPairClose)) {
        isContainedPairPresent = false;
      }
      if (lineAfter.length > 0) {
        const characterAfter = lineAfter.charAt(0);
        const isBeforeCloseBrace = this.d(config, lineAfter);
        if (!isBeforeCloseBrace && !shouldAutoCloseBefore(characterAfter)) {
          return null;
        }
      }
      if (pair.open.length === 1 && (ch === "'" || ch === '"') && autoCloseConfig !== "always") {
        const wordSeparators2 = $iE(config.wordSeparators, []);
        if (lineBefore.length > 0) {
          const characterBefore = lineBefore.charCodeAt(lineBefore.length - 1);
          if (wordSeparators2.get(characterBefore) === 0) {
            return null;
          }
        }
      }
      if (!model.tokenization.isCheapToTokenize(lineNumber)) {
        return null;
      }
      model.tokenization.forceTokenization(lineNumber);
      const lineTokens = model.tokenization.getLineTokens(lineNumber);
      const scopedLineTokens = $2E(lineTokens, beforeColumn - 1);
      if (!pair.shouldAutoClose(scopedLineTokens, beforeColumn - scopedLineTokens.firstCharOffset)) {
        return null;
      }
      const neutralCharacter = pair.findNeutralCharacter();
      if (neutralCharacter) {
        const tokenType = model.tokenization.getTokenTypeIfInsertingCharacter(lineNumber, beforeColumn, neutralCharacter);
        if (!pair.isOK(tokenType)) {
          return null;
        }
      }
    }
    if (isContainedPairPresent) {
      return pair.close.substring(0, pair.close.length - containedPairClose.length);
    } else {
      return pair.close;
    }
  }
  /**
   * Find another auto-closing pair that is contained by the one passed in.
   *
   * e.g. when having [(,)] and [(*,*)] as auto-closing pairs
   * this method will find [(,)] as a containment pair for [(*,*)]
   */
  static b(config, pair) {
    if (pair.open.length <= 1) {
      return null;
    }
    const lastChar = pair.close.charAt(pair.close.length - 1);
    const candidates = config.autoClosingPairs.autoClosingPairsCloseByEnd.get(lastChar) || [];
    let result = null;
    for (const candidate of candidates) {
      if (candidate.open !== pair.open && pair.open.includes(candidate.open) && pair.close.endsWith(candidate.close)) {
        if (!result || candidate.open.length > result.open.length) {
          result = candidate;
        }
      }
    }
    return result;
  }
  /**
   * Determine if typing `ch` at all `positions` in the `model` results in an
   * auto closing open sequence being typed.
   *
   * Auto closing open sequences can consist of multiple characters, which
   * can lead to ambiguities. In such a case, the longest auto-closing open
   * sequence is returned.
   */
  static c(config, model, positions, ch) {
    const candidates = config.autoClosingPairs.autoClosingPairsOpenByEnd.get(ch);
    if (!candidates) {
      return null;
    }
    let result = null;
    for (const candidate of candidates) {
      if (result === null || candidate.open.length > result.open.length) {
        let candidateIsMatch = true;
        for (const position of positions) {
          const relevantText = model.getValueInRange(new $9C(position.lineNumber, position.column - candidate.open.length + 1, position.lineNumber, position.column));
          if (relevantText + ch !== candidate.open) {
            candidateIsMatch = false;
            break;
          }
        }
        if (candidateIsMatch) {
          result = candidate;
        }
      }
    }
    return result;
  }
  static d(config, lineAfter) {
    const nextChar = lineAfter.charAt(0);
    const potentialStartingBraces = config.autoClosingPairs.autoClosingPairsOpenByStart.get(nextChar) || [];
    const potentialClosingBraces = config.autoClosingPairs.autoClosingPairsCloseByStart.get(nextChar) || [];
    const isBeforeStartingBrace = potentialStartingBraces.some((x) => lineAfter.startsWith(x.open));
    const isBeforeClosingBrace = potentialClosingBraces.some((x) => lineAfter.startsWith(x.close));
    return !isBeforeStartingBrace && isBeforeClosingBrace;
  }
};
var $F6 = class {
  static getEdits(config, compositions) {
    const isOvertypeMode = config.inputMode === "overtype";
    if (!isOvertypeMode) {
      return null;
    }
    const commands2 = compositions.map((composition) => new $g6(composition.insertedTextRange));
    return new $i5(4, commands2, {
      shouldPushStackElementBefore: true,
      shouldPushStackElementAfter: false
    });
  }
};
var $G6 = class {
  static getEdits(config, model, selections, ch, isDoingComposition) {
    if (!isDoingComposition && this.b(config, model, selections, ch)) {
      return this.a(config, selections, ch);
    }
    return;
  }
  static a(config, selections, ch) {
    const commands2 = [];
    for (let i2 = 0, len = selections.length; i2 < len; i2++) {
      const selection = selections[i2];
      const closeCharacter = config.surroundingPairs[ch];
      commands2[i2] = new $z6(selection, ch, closeCharacter);
    }
    return new $i5(0, commands2, {
      shouldPushStackElementBefore: true,
      shouldPushStackElementAfter: true
    });
  }
  static b(config, model, selections, ch) {
    if (!$R6(config, ch) || !config.surroundingPairs.hasOwnProperty(ch)) {
      return false;
    }
    const isTypingAQuoteCharacter = $j5(ch);
    for (const selection of selections) {
      if (selection.isEmpty()) {
        return false;
      }
      let selectionContainsOnlyWhitespace = true;
      for (let lineNumber = selection.startLineNumber; lineNumber <= selection.endLineNumber; lineNumber++) {
        const lineText = model.getLineContent(lineNumber);
        const startIndex = lineNumber === selection.startLineNumber ? selection.startColumn - 1 : 0;
        const endIndex = lineNumber === selection.endLineNumber ? selection.endColumn - 1 : lineText.length;
        const selectedText = lineText.substring(startIndex, endIndex);
        if (/[^ \t]/.test(selectedText)) {
          selectionContainsOnlyWhitespace = false;
          break;
        }
      }
      if (selectionContainsOnlyWhitespace) {
        return false;
      }
      if (isTypingAQuoteCharacter && selection.startLineNumber === selection.endLineNumber && selection.startColumn + 1 === selection.endColumn) {
        const selectionText = model.getValueInRange(selection);
        if ($j5(selectionText)) {
          return false;
        }
      }
    }
    return true;
  }
};
var $H6 = class {
  static getEdits(prevEditOperationType, config, model, selections, ch, isDoingComposition) {
    if (!isDoingComposition && this.a(config, model, selections)) {
      const r2 = this.b(prevEditOperationType, config, model, selections[0], ch);
      if (r2) {
        return r2;
      }
    }
    return;
  }
  static a(config, model, selections) {
    if (selections.length === 1 && model.tokenization.isCheapToTokenize(selections[0].getEndPosition().lineNumber)) {
      return true;
    }
    return false;
  }
  static b(prevEditOperationType, config, model, selection, ch) {
    if (!config.electricChars.hasOwnProperty(ch) || !selection.isEmpty()) {
      return null;
    }
    const position = selection.getPosition();
    model.tokenization.forceTokenization(position.lineNumber);
    const lineTokens = model.tokenization.getLineTokens(position.lineNumber);
    let electricAction;
    try {
      electricAction = config.onElectricCharacter(ch, lineTokens, position.column);
    } catch (e) {
      $gb(e);
      return null;
    }
    if (!electricAction) {
      return null;
    }
    if (electricAction.matchOpenBracket) {
      const endColumn = (lineTokens.getLineContent() + ch).lastIndexOf(electricAction.matchOpenBracket) + 1;
      const match = model.bracketPairs.findMatchingBracketUp(
        electricAction.matchOpenBracket,
        {
          lineNumber: position.lineNumber,
          column: endColumn
        },
        500
        /* give at most 500ms to compute */
      );
      if (match) {
        if (match.startLineNumber === position.lineNumber) {
          return null;
        }
        const matchLine = model.getLineContent(match.startLineNumber);
        const matchLineIndentation = $Pf(matchLine);
        const newIndentation = config.normalizeIndentation(matchLineIndentation);
        const lineText = model.getLineContent(position.lineNumber);
        const lineFirstNonBlankColumn = model.getLineFirstNonWhitespaceColumn(position.lineNumber) || position.column;
        const prefix = lineText.substring(lineFirstNonBlankColumn - 1, position.column - 1);
        const typeText = newIndentation + prefix + ch;
        const typeSelection = new $9C(position.lineNumber, 1, position.lineNumber, position.column);
        const command4 = new $b6(typeSelection, typeText);
        return new $i5(getTypingOperation(typeText, prevEditOperationType), [command4], {
          shouldPushStackElementBefore: false,
          shouldPushStackElementAfter: true
        });
      }
    }
    return null;
  }
};
var $I6 = class {
  static getEdits(config, prevEditOperationType, selections, ch, isDoingComposition) {
    const commands2 = [];
    for (let i2 = 0, len = selections.length; i2 < len; i2++) {
      const ChosenReplaceCommand = config.inputMode === "overtype" && !isDoingComposition ? $c6 : $b6;
      commands2[i2] = new ChosenReplaceCommand(selections[i2], ch);
    }
    const opType = getTypingOperation(ch, prevEditOperationType);
    return new $i5(opType, commands2, {
      shouldPushStackElementBefore: shouldPushStackElementBetween(prevEditOperationType, opType),
      shouldPushStackElementAfter: false
    });
  }
};
var $J6 = class {
  static getEdits(config, model, selections, ch, isDoingComposition) {
    if (!isDoingComposition && ch === "\n") {
      const commands2 = [];
      for (let i2 = 0, len = selections.length; i2 < len; i2++) {
        commands2[i2] = this.a(config, model, false, selections[i2]);
      }
      return new $i5(4, commands2, {
        shouldPushStackElementBefore: true,
        shouldPushStackElementAfter: false
      });
    }
    return;
  }
  static a(config, model, keepPosition, range) {
    if (config.autoIndent === 0) {
      return typeCommand(range, "\n", keepPosition);
    }
    if (!model.tokenization.isCheapToTokenize(range.getStartPosition().lineNumber) || config.autoIndent === 1) {
      const lineText2 = model.getLineContent(range.startLineNumber);
      const indentation2 = $Pf(lineText2).substring(0, range.startColumn - 1);
      return typeCommand(range, "\n" + config.normalizeIndentation(indentation2), keepPosition);
    }
    const r2 = $x6(config.autoIndent, model, range, config.languageConfigurationService);
    if (r2) {
      if (r2.indentAction === IndentAction.None) {
        return typeCommand(range, "\n" + config.normalizeIndentation(r2.indentation + r2.appendText), keepPosition);
      } else if (r2.indentAction === IndentAction.Indent) {
        return typeCommand(range, "\n" + config.normalizeIndentation(r2.indentation + r2.appendText), keepPosition);
      } else if (r2.indentAction === IndentAction.IndentOutdent) {
        const normalIndent = config.normalizeIndentation(r2.indentation);
        const increasedIndent = config.normalizeIndentation(r2.indentation + r2.appendText);
        const typeText = "\n" + increasedIndent + "\n" + normalIndent;
        if (keepPosition) {
          return new $e6(range, typeText, true);
        } else {
          return new $f6(range, typeText, -1, increasedIndent.length - normalIndent.length, true);
        }
      } else if (r2.indentAction === IndentAction.Outdent) {
        const actualIndentation = $Q6(config, r2.indentation);
        return typeCommand(range, "\n" + config.normalizeIndentation(actualIndentation + r2.appendText), keepPosition);
      }
    }
    const lineText = model.getLineContent(range.startLineNumber);
    const indentation = $Pf(lineText).substring(0, range.startColumn - 1);
    if (config.autoIndent >= 4) {
      const ir = $r6(config.autoIndent, model, range, {
        unshiftIndent: (indent) => {
          return $Q6(config, indent);
        },
        shiftIndent: (indent) => {
          return $P6(config, indent);
        },
        normalizeIndentation: (indent) => {
          return config.normalizeIndentation(indent);
        }
      }, config.languageConfigurationService);
      if (ir) {
        let oldEndViewColumn = config.visibleColumnFromColumn(model, range.getEndPosition());
        const oldEndColumn = range.endColumn;
        const newLineContent = model.getLineContent(range.endLineNumber);
        const firstNonWhitespace = $Of(newLineContent);
        if (firstNonWhitespace >= 0) {
          range = range.setEndPosition(range.endLineNumber, Math.max(range.endColumn, firstNonWhitespace + 1));
        } else {
          range = range.setEndPosition(range.endLineNumber, model.getLineMaxColumn(range.endLineNumber));
        }
        if (keepPosition) {
          return new $e6(range, "\n" + config.normalizeIndentation(ir.afterEnter), true);
        } else {
          let offset = 0;
          if (oldEndColumn <= firstNonWhitespace + 1) {
            if (!config.insertSpaces) {
              oldEndViewColumn = Math.ceil(oldEndViewColumn / config.indentSize);
            }
            offset = Math.min(oldEndViewColumn + 1 - config.normalizeIndentation(ir.afterEnter).length - 1, 0);
          }
          return new $f6(range, "\n" + config.normalizeIndentation(ir.afterEnter), 0, offset, true);
        }
      }
    }
    return typeCommand(range, "\n" + config.normalizeIndentation(indentation), keepPosition);
  }
  static lineInsertBefore(config, model, selections) {
    if (model === null || selections === null) {
      return [];
    }
    const commands2 = [];
    for (let i2 = 0, len = selections.length; i2 < len; i2++) {
      let lineNumber = selections[i2].positionLineNumber;
      if (lineNumber === 1) {
        commands2[i2] = new $e6(new $9C(1, 1, 1, 1), "\n");
      } else {
        lineNumber--;
        const column = model.getLineMaxColumn(lineNumber);
        commands2[i2] = this.a(config, model, false, new $9C(lineNumber, column, lineNumber, column));
      }
    }
    return commands2;
  }
  static lineInsertAfter(config, model, selections) {
    if (model === null || selections === null) {
      return [];
    }
    const commands2 = [];
    for (let i2 = 0, len = selections.length; i2 < len; i2++) {
      const lineNumber = selections[i2].positionLineNumber;
      const column = model.getLineMaxColumn(lineNumber);
      commands2[i2] = this.a(config, model, false, new $9C(lineNumber, column, lineNumber, column));
    }
    return commands2;
  }
  static lineBreakInsert(config, model, selections) {
    const commands2 = [];
    for (let i2 = 0, len = selections.length; i2 < len; i2++) {
      commands2[i2] = this.a(config, model, true, selections[i2]);
    }
    return commands2;
  }
};
var $K6 = class {
  static getEdits(config, model, selections, text2, pasteOnNewLine, multicursorText) {
    const distributedPaste = this.a(config, selections, text2, pasteOnNewLine, multicursorText);
    if (distributedPaste) {
      selections = selections.sort($9C.compareRangesUsingStarts);
      return this.b(config, model, selections, distributedPaste);
    } else {
      return this.c(config, model, selections, text2, pasteOnNewLine);
    }
  }
  static a(config, selections, text2, pasteOnNewLine, multicursorText) {
    if (pasteOnNewLine) {
      return null;
    }
    if (selections.length === 1) {
      return null;
    }
    if (multicursorText && multicursorText.length === selections.length) {
      return multicursorText;
    }
    if (config.multiCursorPaste === "spread") {
      if (text2.charCodeAt(text2.length - 1) === 10) {
        text2 = text2.substring(0, text2.length - 1);
      }
      if (text2.charCodeAt(text2.length - 1) === 13) {
        text2 = text2.substring(0, text2.length - 1);
      }
      const lines = $Mf(text2);
      if (lines.length === selections.length) {
        return lines;
      }
    }
    return null;
  }
  static b(config, model, selections, text2) {
    const commands2 = [];
    for (let i2 = 0, len = selections.length; i2 < len; i2++) {
      const shouldOvertypeOnPaste = config.overtypeOnPaste && config.inputMode === "overtype";
      const ChosenReplaceCommand = shouldOvertypeOnPaste ? $c6 : $b6;
      commands2[i2] = new ChosenReplaceCommand(selections[i2], text2[i2]);
    }
    return new $i5(0, commands2, {
      shouldPushStackElementBefore: true,
      shouldPushStackElementAfter: true
    });
  }
  static c(config, model, selections, text2, pasteOnNewLine) {
    const commands2 = [];
    for (let i2 = 0, len = selections.length; i2 < len; i2++) {
      const selection = selections[i2];
      const position = selection.getPosition();
      if (pasteOnNewLine && !selection.isEmpty()) {
        pasteOnNewLine = false;
      }
      if (pasteOnNewLine && text2.indexOf("\n") !== text2.length - 1) {
        pasteOnNewLine = false;
      }
      if (pasteOnNewLine) {
        const typeSelection = new $9C(position.lineNumber, 1, position.lineNumber, 1);
        commands2[i2] = new $h6(typeSelection, text2, selection, true);
      } else {
        const shouldOvertypeOnPaste = config.overtypeOnPaste && config.inputMode === "overtype";
        const ChosenReplaceCommand = shouldOvertypeOnPaste ? $c6 : $b6;
        commands2[i2] = new ChosenReplaceCommand(selection, text2);
      }
    }
    return new $i5(0, commands2, {
      shouldPushStackElementBefore: true,
      shouldPushStackElementAfter: true
    });
  }
};
var $L6 = class {
  static getEdits(prevEditOperationType, config, model, selections, text2, replacePrevCharCnt, replaceNextCharCnt, positionDelta) {
    const commands2 = selections.map((selection) => this.a(model, selection, text2, replacePrevCharCnt, replaceNextCharCnt, positionDelta));
    return new $i5(4, commands2, {
      shouldPushStackElementBefore: shouldPushStackElementBetween(
        prevEditOperationType,
        4
        /* EditOperationType.TypingOther */
      ),
      shouldPushStackElementAfter: false
    });
  }
  static a(model, selection, text2, replacePrevCharCnt, replaceNextCharCnt, positionDelta) {
    if (!selection.isEmpty()) {
      return null;
    }
    const pos = selection.getPosition();
    const startColumn = Math.max(1, pos.column - replacePrevCharCnt);
    const endColumn = Math.min(model.getLineMaxColumn(pos.lineNumber), pos.column + replaceNextCharCnt);
    const range = new $9C(pos.lineNumber, startColumn, pos.lineNumber, endColumn);
    return new $f6(range, text2, 0, positionDelta);
  }
};
var $M6 = class {
  static getEdits(prevEditOperationType, selections, str) {
    const commands2 = [];
    for (let i2 = 0, len = selections.length; i2 < len; i2++) {
      commands2[i2] = new $b6(selections[i2], str);
    }
    const opType = getTypingOperation(str, prevEditOperationType);
    return new $i5(opType, commands2, {
      shouldPushStackElementBefore: shouldPushStackElementBetween(prevEditOperationType, opType),
      shouldPushStackElementAfter: false
    });
  }
};
var $N6 = class {
  static getCommands(config, model, selections) {
    const commands2 = [];
    for (let i2 = 0, len = selections.length; i2 < len; i2++) {
      const selection = selections[i2];
      if (selection.isEmpty()) {
        const lineText = model.getLineContent(selection.startLineNumber);
        if (/^\s*$/.test(lineText) && model.tokenization.isCheapToTokenize(selection.startLineNumber)) {
          let goodIndent = this.a(config, model, selection.startLineNumber);
          goodIndent = goodIndent || "	";
          const possibleTypeText = config.normalizeIndentation(goodIndent);
          if (!lineText.startsWith(possibleTypeText)) {
            commands2[i2] = new $b6(new $9C(selection.startLineNumber, 1, selection.startLineNumber, lineText.length + 1), possibleTypeText, true);
            continue;
          }
        }
        commands2[i2] = this.b(config, model, selection, true);
      } else {
        if (selection.startLineNumber === selection.endLineNumber) {
          const lineMaxColumn = model.getLineMaxColumn(selection.startLineNumber);
          if (selection.startColumn !== 1 || selection.endColumn !== lineMaxColumn) {
            commands2[i2] = this.b(config, model, selection, false);
            continue;
          }
        }
        commands2[i2] = new $y6(selection, {
          isUnshift: false,
          tabSize: config.tabSize,
          indentSize: config.indentSize,
          insertSpaces: config.insertSpaces,
          useTabStops: config.useTabStops,
          autoIndent: config.autoIndent
        }, config.languageConfigurationService);
      }
    }
    return commands2;
  }
  static a(config, model, lineNumber) {
    let action = null;
    let indentation = "";
    const expectedIndentAction = $p6(config.autoIndent, model, lineNumber, false, config.languageConfigurationService);
    if (expectedIndentAction) {
      action = expectedIndentAction.action;
      indentation = expectedIndentAction.indentation;
    } else if (lineNumber > 1) {
      let lastLineNumber;
      for (lastLineNumber = lineNumber - 1; lastLineNumber >= 1; lastLineNumber--) {
        const lineText = model.getLineContent(lastLineNumber);
        const nonWhitespaceIdx = $Qf(lineText);
        if (nonWhitespaceIdx >= 0) {
          break;
        }
      }
      if (lastLineNumber < 1) {
        return null;
      }
      const maxColumn = model.getLineMaxColumn(lastLineNumber);
      const expectedEnterAction = $x6(config.autoIndent, model, new $9C(lastLineNumber, maxColumn, lastLineNumber, maxColumn), config.languageConfigurationService);
      if (expectedEnterAction) {
        indentation = expectedEnterAction.indentation + expectedEnterAction.appendText;
      }
    }
    if (action) {
      if (action === IndentAction.Indent) {
        indentation = $P6(config, indentation);
      }
      if (action === IndentAction.Outdent) {
        indentation = $Q6(config, indentation);
      }
      indentation = config.normalizeIndentation(indentation);
    }
    if (!indentation) {
      return null;
    }
    return indentation;
  }
  static b(config, model, selection, insertsAutoWhitespace) {
    let typeText = "";
    const position = selection.getStartPosition();
    if (config.insertSpaces) {
      const visibleColumnFromColumn = config.visibleColumnFromColumn(model, position);
      const indentSize = config.indentSize;
      const spacesCnt = indentSize - visibleColumnFromColumn % indentSize;
      for (let i2 = 0; i2 < spacesCnt; i2++) {
        typeText += " ";
      }
    } else {
      typeText = "	";
    }
    return new $b6(selection, typeText, insertsAutoWhitespace);
  }
};
var $O6 = class extends $f6 {
  constructor(selection, text2, lineNumberDeltaOffset, columnDeltaOffset, openCharacter, closeCharacter) {
    super(selection, text2, lineNumberDeltaOffset, columnDeltaOffset);
    this.f = openCharacter;
    this.g = closeCharacter;
    this.closeCharacterRange = null;
    this.enclosingRange = null;
  }
  h(model, range, helper) {
    this.closeCharacterRange = new $9C(range.startLineNumber, range.endColumn - this.g.length, range.endLineNumber, range.endColumn);
    this.enclosingRange = new $9C(range.startLineNumber, range.endColumn - this.f.length - this.g.length, range.endLineNumber, range.endColumn);
    return super.computeCursorState(model, helper);
  }
};
var TypeWithAutoClosingCommand = class extends $O6 {
  constructor(selection, openCharacter, insertOpenCharacter, closeCharacter) {
    const text2 = (insertOpenCharacter ? openCharacter : "") + closeCharacter;
    const lineNumberDeltaOffset = 0;
    const columnDeltaOffset = -closeCharacter.length;
    super(selection, text2, lineNumberDeltaOffset, columnDeltaOffset, openCharacter, closeCharacter);
  }
  computeCursorState(model, helper) {
    const inverseEditOperations = helper.getInverseEditOperations();
    const range = inverseEditOperations[0].range;
    return this.h(model, range, helper);
  }
};
var TypeWithIndentationAndAutoClosingCommand = class extends $O6 {
  constructor(autoIndentationEdit, selection, openCharacter, closeCharacter) {
    const text2 = openCharacter + closeCharacter;
    const lineNumberDeltaOffset = 0;
    const columnDeltaOffset = openCharacter.length;
    super(selection, text2, lineNumberDeltaOffset, columnDeltaOffset, openCharacter, closeCharacter);
    this.k = autoIndentationEdit;
    this.l = { range: selection, text: text2 };
  }
  getEditOperations(model, builder) {
    builder.addTrackedEditOperation(this.k.range, this.k.text);
    builder.addTrackedEditOperation(this.l.range, this.l.text);
  }
  computeCursorState(model, helper) {
    const inverseEditOperations = helper.getInverseEditOperations();
    if (inverseEditOperations.length !== 2) {
      throw new Error("There should be two inverse edit operations!");
    }
    const range1 = inverseEditOperations[0].range;
    const range2 = inverseEditOperations[1].range;
    const range = range1.plusRange(range2);
    return this.h(model, range, helper);
  }
};
function getTypingOperation(typedText, previousTypingOperation) {
  if (typedText === " ") {
    return previousTypingOperation === 5 || previousTypingOperation === 6 ? 6 : 5;
  }
  return 4;
}
function shouldPushStackElementBetween(previousTypingOperation, typingOperation) {
  if (isTypingOperation(previousTypingOperation) && !isTypingOperation(typingOperation)) {
    return true;
  }
  if (previousTypingOperation === 5) {
    return false;
  }
  return normalizeOperationType(previousTypingOperation) !== normalizeOperationType(typingOperation);
}
function normalizeOperationType(type) {
  return type === 6 || type === 5 ? "space" : type;
}
function isTypingOperation(type) {
  return type === 4 || type === 5 || type === 6;
}
function isAutoClosingOvertype(config, model, selections, autoClosedCharacters, ch) {
  if (config.autoClosingOvertype === "never") {
    return false;
  }
  if (!config.autoClosingPairs.autoClosingPairsCloseSingleChar.has(ch)) {
    return false;
  }
  for (let i2 = 0, len = selections.length; i2 < len; i2++) {
    const selection = selections[i2];
    if (!selection.isEmpty()) {
      return false;
    }
    const position = selection.getPosition();
    const lineText = model.getLineContent(position.lineNumber);
    const afterCharacter = lineText.charAt(position.column - 1);
    if (afterCharacter !== ch) {
      return false;
    }
    const chIsQuote = $j5(ch);
    const beforeCharacter = position.column > 2 ? lineText.charCodeAt(position.column - 2) : 0;
    if (beforeCharacter === 92 && chIsQuote) {
      return false;
    }
    if (config.autoClosingOvertype === "auto") {
      let found = false;
      for (let j = 0, lenJ = autoClosedCharacters.length; j < lenJ; j++) {
        const autoClosedCharacter = autoClosedCharacters[j];
        if (position.lineNumber === autoClosedCharacter.startLineNumber && position.column === autoClosedCharacter.startColumn) {
          found = true;
          break;
        }
      }
      if (!found) {
        return false;
      }
    }
  }
  return true;
}
function typeCommand(range, text2, keepPosition) {
  if (keepPosition) {
    return new $e6(range, text2, true);
  } else {
    return new $b6(range, text2, true);
  }
}
function $P6(config, indentation, count) {
  count = count || 1;
  return $y6.shiftIndent(indentation, indentation.length + count, config.tabSize, config.indentSize, config.insertSpaces);
}
function $Q6(config, indentation, count) {
  count = count || 1;
  return $y6.unshiftIndent(indentation, indentation.length + count, config.tabSize, config.indentSize, config.insertSpaces);
}
function $R6(config, ch) {
  if ($j5(ch)) {
    return config.autoSurround === "quotes" || config.autoSurround === "languageDefined";
  } else {
    return config.autoSurround === "brackets" || config.autoSurround === "languageDefined";
  }
}

// out-build/vs/editor/common/cursor/cursorTypeOperations.js
var $S6 = class {
  static indent(config, model, selections) {
    if (model === null || selections === null) {
      return [];
    }
    const commands2 = [];
    for (let i2 = 0, len = selections.length; i2 < len; i2++) {
      commands2[i2] = new $y6(selections[i2], {
        isUnshift: false,
        tabSize: config.tabSize,
        indentSize: config.indentSize,
        insertSpaces: config.insertSpaces,
        useTabStops: config.useTabStops,
        autoIndent: config.autoIndent
      }, config.languageConfigurationService);
    }
    return commands2;
  }
  static outdent(config, model, selections) {
    const commands2 = [];
    for (let i2 = 0, len = selections.length; i2 < len; i2++) {
      commands2[i2] = new $y6(selections[i2], {
        isUnshift: true,
        tabSize: config.tabSize,
        indentSize: config.indentSize,
        insertSpaces: config.insertSpaces,
        useTabStops: config.useTabStops,
        autoIndent: config.autoIndent
      }, config.languageConfigurationService);
    }
    return commands2;
  }
  static shiftIndent(config, indentation, count) {
    return $P6(config, indentation, count);
  }
  static unshiftIndent(config, indentation, count) {
    return $Q6(config, indentation, count);
  }
  static paste(config, model, selections, text2, pasteOnNewLine, multicursorText) {
    return $K6.getEdits(config, model, selections, text2, pasteOnNewLine, multicursorText);
  }
  static tab(config, model, selections) {
    return $N6.getCommands(config, model, selections);
  }
  static compositionType(prevEditOperationType, config, model, selections, text2, replacePrevCharCnt, replaceNextCharCnt, positionDelta) {
    return $L6.getEdits(prevEditOperationType, config, model, selections, text2, replacePrevCharCnt, replaceNextCharCnt, positionDelta);
  }
  /**
   * This is very similar with typing, but the character is already in the text buffer!
   */
  static compositionEndWithInterceptors(prevEditOperationType, config, model, compositions, selections, autoClosedCharacters) {
    if (!compositions) {
      return null;
    }
    let insertedText = null;
    for (const composition of compositions) {
      if (insertedText === null) {
        insertedText = composition.insertedText;
      } else if (insertedText !== composition.insertedText) {
        return null;
      }
    }
    if (!insertedText || insertedText.length !== 1) {
      return $F6.getEdits(config, compositions);
    }
    const ch = insertedText;
    let hasDeletion = false;
    for (const composition of compositions) {
      if (composition.deletedText.length !== 0) {
        hasDeletion = true;
        break;
      }
    }
    if (hasDeletion) {
      if (!$R6(config, ch) || !config.surroundingPairs.hasOwnProperty(ch)) {
        return null;
      }
      const isTypingAQuoteCharacter = $j5(ch);
      for (const composition of compositions) {
        if (composition.deletedSelectionStart !== 0 || composition.deletedSelectionEnd !== composition.deletedText.length) {
          return null;
        }
        if (/^[ \t]+$/.test(composition.deletedText)) {
          return null;
        }
        if (isTypingAQuoteCharacter && $j5(composition.deletedText)) {
          return null;
        }
      }
      const positions = [];
      for (const selection of selections) {
        if (!selection.isEmpty()) {
          return null;
        }
        positions.push(selection.getPosition());
      }
      if (positions.length !== compositions.length) {
        return null;
      }
      const commands2 = [];
      for (let i2 = 0, len = positions.length; i2 < len; i2++) {
        commands2.push(new $A6(positions[i2], compositions[i2].deletedText, config.surroundingPairs[ch]));
      }
      return new $i5(4, commands2, {
        shouldPushStackElementBefore: true,
        shouldPushStackElementAfter: false
      });
    }
    const autoClosingOvertypeEdits = $D6.getEdits(config, model, selections, autoClosedCharacters, ch);
    if (autoClosingOvertypeEdits !== void 0) {
      return autoClosingOvertypeEdits;
    }
    const autoClosingOpenCharEdits = $E6.getEdits(config, model, selections, ch, true, false);
    if (autoClosingOpenCharEdits !== void 0) {
      return autoClosingOpenCharEdits;
    }
    return $F6.getEdits(config, compositions);
  }
  static typeWithInterceptors(isDoingComposition, prevEditOperationType, config, model, selections, autoClosedCharacters, ch) {
    const enterEdits = $J6.getEdits(config, model, selections, ch, isDoingComposition);
    if (enterEdits !== void 0) {
      return enterEdits;
    }
    const autoIndentEdits = $B6.getEdits(config, model, selections, ch, isDoingComposition);
    if (autoIndentEdits !== void 0) {
      return autoIndentEdits;
    }
    const autoClosingOverTypeEdits = $C6.getEdits(prevEditOperationType, config, model, selections, autoClosedCharacters, ch);
    if (autoClosingOverTypeEdits !== void 0) {
      return autoClosingOverTypeEdits;
    }
    const autoClosingOpenCharEdits = $E6.getEdits(config, model, selections, ch, false, isDoingComposition);
    if (autoClosingOpenCharEdits !== void 0) {
      return autoClosingOpenCharEdits;
    }
    const surroundSelectionEdits = $G6.getEdits(config, model, selections, ch, isDoingComposition);
    if (surroundSelectionEdits !== void 0) {
      return surroundSelectionEdits;
    }
    const interceptorElectricCharOperation = $H6.getEdits(prevEditOperationType, config, model, selections, ch, isDoingComposition);
    if (interceptorElectricCharOperation !== void 0) {
      return interceptorElectricCharOperation;
    }
    return $I6.getEdits(config, prevEditOperationType, selections, ch, isDoingComposition);
  }
  static typeWithoutInterceptors(prevEditOperationType, config, model, selections, str) {
    return $M6.getEdits(prevEditOperationType, selections, str);
  }
};
var $T6 = class {
  constructor(deletedText, deletedSelectionStart, deletedSelectionEnd, insertedText, insertedSelectionStart, insertedSelectionEnd, insertedTextRange) {
    this.deletedText = deletedText;
    this.deletedSelectionStart = deletedSelectionStart;
    this.deletedSelectionEnd = deletedSelectionEnd;
    this.insertedText = insertedText;
    this.insertedSelectionStart = insertedSelectionStart;
    this.insertedSelectionEnd = insertedSelectionEnd;
    this.insertedTextRange = insertedTextRange;
  }
};

// out-build/vs/editor/common/editorContextKeys.js
var EditorContextKeys;
(function(EditorContextKeys2) {
  EditorContextKeys2.editorSimpleInput = new $nn("editorSimpleInput", false, true);
  EditorContextKeys2.editorTextFocus = new $nn("editorTextFocus", false, localize(758, null));
  EditorContextKeys2.focus = new $nn("editorFocus", false, localize(759, null));
  EditorContextKeys2.textInputFocus = new $nn("textInputFocus", false, localize(760, null));
  EditorContextKeys2.readOnly = new $nn("editorReadonly", false, localize(761, null));
  EditorContextKeys2.inDiffEditor = new $nn("inDiffEditor", false, localize(762, null));
  EditorContextKeys2.isEmbeddedDiffEditor = new $nn("isEmbeddedDiffEditor", false, localize(763, null));
  EditorContextKeys2.multiDiffEditorAllCollapsed = new $nn("multiDiffEditorAllCollapsed", void 0, localize(764, null));
  EditorContextKeys2.hasChanges = new $nn("diffEditorHasChanges", false, localize(765, null));
  EditorContextKeys2.comparingMovedCode = new $nn("comparingMovedCode", false, localize(766, null));
  EditorContextKeys2.accessibleDiffViewerVisible = new $nn("accessibleDiffViewerVisible", false, localize(767, null));
  EditorContextKeys2.diffEditorRenderSideBySideInlineBreakpointReached = new $nn("diffEditorRenderSideBySideInlineBreakpointReached", false, localize(768, null));
  EditorContextKeys2.diffEditorInlineMode = new $nn("diffEditorInlineMode", false, localize(769, null));
  EditorContextKeys2.diffEditorOriginalWritable = new $nn("diffEditorOriginalWritable", false, localize(770, null));
  EditorContextKeys2.diffEditorModifiedWritable = new $nn("diffEditorModifiedWritable", false, localize(771, null));
  EditorContextKeys2.diffEditorOriginalUri = new $nn("diffEditorOriginalUri", "", localize(772, null));
  EditorContextKeys2.diffEditorModifiedUri = new $nn("diffEditorModifiedUri", "", localize(773, null));
  EditorContextKeys2.columnSelection = new $nn("editorColumnSelection", false, localize(774, null));
  EditorContextKeys2.writable = EditorContextKeys2.readOnly.toNegated();
  EditorContextKeys2.hasNonEmptySelection = new $nn("editorHasSelection", false, localize(775, null));
  EditorContextKeys2.hasOnlyEmptySelection = EditorContextKeys2.hasNonEmptySelection.toNegated();
  EditorContextKeys2.hasMultipleSelections = new $nn("editorHasMultipleSelections", false, localize(776, null));
  EditorContextKeys2.hasSingleSelection = EditorContextKeys2.hasMultipleSelections.toNegated();
  EditorContextKeys2.tabMovesFocus = new $nn("editorTabMovesFocus", false, localize(777, null));
  EditorContextKeys2.tabDoesNotMoveFocus = EditorContextKeys2.tabMovesFocus.toNegated();
  EditorContextKeys2.isInEmbeddedEditor = new $nn("isInEmbeddedEditor", false, true);
  EditorContextKeys2.canUndo = new $nn("canUndo", false, true);
  EditorContextKeys2.canRedo = new $nn("canRedo", false, true);
  EditorContextKeys2.hoverVisible = new $nn("editorHoverVisible", false, localize(778, null));
  EditorContextKeys2.hoverFocused = new $nn("editorHoverFocused", false, localize(779, null));
  EditorContextKeys2.stickyScrollFocused = new $nn("stickyScrollFocused", false, localize(780, null));
  EditorContextKeys2.stickyScrollVisible = new $nn("stickyScrollVisible", false, localize(781, null));
  EditorContextKeys2.standaloneColorPickerVisible = new $nn("standaloneColorPickerVisible", false, localize(782, null));
  EditorContextKeys2.standaloneColorPickerFocused = new $nn("standaloneColorPickerFocused", false, localize(783, null));
  EditorContextKeys2.inCompositeEditor = new $nn("inCompositeEditor", void 0, localize(784, null));
  EditorContextKeys2.notInCompositeEditor = EditorContextKeys2.inCompositeEditor.toNegated();
  EditorContextKeys2.languageId = new $nn("editorLangId", "", localize(785, null));
  EditorContextKeys2.hasCompletionItemProvider = new $nn("editorHasCompletionItemProvider", false, localize(786, null));
  EditorContextKeys2.hasCodeActionsProvider = new $nn("editorHasCodeActionsProvider", false, localize(787, null));
  EditorContextKeys2.hasCodeLensProvider = new $nn("editorHasCodeLensProvider", false, localize(788, null));
  EditorContextKeys2.hasDefinitionProvider = new $nn("editorHasDefinitionProvider", false, localize(789, null));
  EditorContextKeys2.hasDeclarationProvider = new $nn("editorHasDeclarationProvider", false, localize(790, null));
  EditorContextKeys2.hasImplementationProvider = new $nn("editorHasImplementationProvider", false, localize(791, null));
  EditorContextKeys2.hasTypeDefinitionProvider = new $nn("editorHasTypeDefinitionProvider", false, localize(792, null));
  EditorContextKeys2.hasHoverProvider = new $nn("editorHasHoverProvider", false, localize(793, null));
  EditorContextKeys2.hasDocumentHighlightProvider = new $nn("editorHasDocumentHighlightProvider", false, localize(794, null));
  EditorContextKeys2.hasDocumentSymbolProvider = new $nn("editorHasDocumentSymbolProvider", false, localize(795, null));
  EditorContextKeys2.hasReferenceProvider = new $nn("editorHasReferenceProvider", false, localize(796, null));
  EditorContextKeys2.hasRenameProvider = new $nn("editorHasRenameProvider", false, localize(797, null));
  EditorContextKeys2.hasSignatureHelpProvider = new $nn("editorHasSignatureHelpProvider", false, localize(798, null));
  EditorContextKeys2.hasInlayHintsProvider = new $nn("editorHasInlayHintsProvider", false, localize(799, null));
  EditorContextKeys2.hasDocumentFormattingProvider = new $nn("editorHasDocumentFormattingProvider", false, localize(800, null));
  EditorContextKeys2.hasDocumentSelectionFormattingProvider = new $nn("editorHasDocumentSelectionFormattingProvider", false, localize(801, null));
  EditorContextKeys2.hasMultipleDocumentFormattingProvider = new $nn("editorHasMultipleDocumentFormattingProvider", false, localize(802, null));
  EditorContextKeys2.hasMultipleDocumentSelectionFormattingProvider = new $nn("editorHasMultipleDocumentSelectionFormattingProvider", false, localize(803, null));
})(EditorContextKeys || (EditorContextKeys = {}));

// out-build/vs/editor/browser/coreCommands.js
var CORE_WEIGHT = 0;
var $U6 = class extends $Y5 {
  runEditorCommand(accessor, editor, args2) {
    const viewModel = editor._getViewModel();
    if (!viewModel) {
      return;
    }
    this.runCoreEditorCommand(viewModel, args2 || {});
  }
};
var EditorScroll_;
(function(EditorScroll_2) {
  const isEditorScrollArgs = function(arg) {
    if (!$Bg(arg)) {
      return false;
    }
    const scrollArg = arg;
    if (!$zg(scrollArg.to)) {
      return false;
    }
    if (!$Gg(scrollArg.by) && !$zg(scrollArg.by)) {
      return false;
    }
    if (!$Gg(scrollArg.value) && !$Dg(scrollArg.value)) {
      return false;
    }
    if (!$Gg(scrollArg.revealCursor) && !$Fg(scrollArg.revealCursor)) {
      return false;
    }
    return true;
  };
  EditorScroll_2.metadata = {
    description: "Scroll editor in the given direction",
    args: [
      {
        name: "Editor scroll argument object",
        description: `Property-value pairs that can be passed through this argument:
					* 'to': A mandatory direction value.
						\`\`\`
						'up', 'down'
						\`\`\`
					* 'by': Unit to move. Default is computed based on 'to' value.
						\`\`\`
						'line', 'wrappedLine', 'page', 'halfPage', 'editor'
						\`\`\`
					* 'value': Number of units to move. Default is '1'.
					* 'revealCursor': If 'true' reveals the cursor if it is outside view port.
				`,
        constraint: isEditorScrollArgs,
        schema: {
          "type": "object",
          "required": ["to"],
          "properties": {
            "to": {
              "type": "string",
              "enum": ["up", "down"]
            },
            "by": {
              "type": "string",
              "enum": ["line", "wrappedLine", "page", "halfPage", "editor"]
            },
            "value": {
              "type": "number",
              "default": 1
            },
            "revealCursor": {
              "type": "boolean"
            }
          }
        }
      }
    ]
  };
  EditorScroll_2.RawDirection = {
    Up: "up",
    Right: "right",
    Down: "down",
    Left: "left"
  };
  EditorScroll_2.RawUnit = {
    Line: "line",
    WrappedLine: "wrappedLine",
    Page: "page",
    HalfPage: "halfPage",
    Editor: "editor",
    Column: "column"
  };
  function parse4(args2) {
    let direction;
    switch (args2.to) {
      case EditorScroll_2.RawDirection.Up:
        direction = 1;
        break;
      case EditorScroll_2.RawDirection.Right:
        direction = 2;
        break;
      case EditorScroll_2.RawDirection.Down:
        direction = 3;
        break;
      case EditorScroll_2.RawDirection.Left:
        direction = 4;
        break;
      default:
        return null;
    }
    let unit;
    switch (args2.by) {
      case EditorScroll_2.RawUnit.Line:
        unit = 1;
        break;
      case EditorScroll_2.RawUnit.WrappedLine:
        unit = 2;
        break;
      case EditorScroll_2.RawUnit.Page:
        unit = 3;
        break;
      case EditorScroll_2.RawUnit.HalfPage:
        unit = 4;
        break;
      case EditorScroll_2.RawUnit.Editor:
        unit = 5;
        break;
      case EditorScroll_2.RawUnit.Column:
        unit = 6;
        break;
      default:
        unit = 2;
    }
    const value = Math.floor(args2.value || 1);
    const revealCursor = !!args2.revealCursor;
    return {
      direction,
      unit,
      value,
      revealCursor,
      select: !!args2.select
    };
  }
  EditorScroll_2.parse = parse4;
  let Direction4;
  (function(Direction5) {
    Direction5[Direction5["Up"] = 1] = "Up";
    Direction5[Direction5["Right"] = 2] = "Right";
    Direction5[Direction5["Down"] = 3] = "Down";
    Direction5[Direction5["Left"] = 4] = "Left";
  })(Direction4 = EditorScroll_2.Direction || (EditorScroll_2.Direction = {}));
  let Unit;
  (function(Unit2) {
    Unit2[Unit2["Line"] = 1] = "Line";
    Unit2[Unit2["WrappedLine"] = 2] = "WrappedLine";
    Unit2[Unit2["Page"] = 3] = "Page";
    Unit2[Unit2["HalfPage"] = 4] = "HalfPage";
    Unit2[Unit2["Editor"] = 5] = "Editor";
    Unit2[Unit2["Column"] = 6] = "Column";
  })(Unit = EditorScroll_2.Unit || (EditorScroll_2.Unit = {}));
})(EditorScroll_ || (EditorScroll_ = {}));
var RevealLine_;
(function(RevealLine_2) {
  const isRevealLineArgs = function(arg) {
    if (!$Bg(arg)) {
      return false;
    }
    const reveaLineArg = arg;
    if (!$Dg(reveaLineArg.lineNumber) && !$zg(reveaLineArg.lineNumber)) {
      return false;
    }
    if (!$Gg(reveaLineArg.at) && !$zg(reveaLineArg.at)) {
      return false;
    }
    return true;
  };
  RevealLine_2.metadata = {
    description: "Reveal the given line at the given logical position",
    args: [
      {
        name: "Reveal line argument object",
        description: `Property-value pairs that can be passed through this argument:
					* 'lineNumber': A mandatory line number value.
					* 'at': Logical position at which line has to be revealed.
						\`\`\`
						'top', 'center', 'bottom'
						\`\`\`
				`,
        constraint: isRevealLineArgs,
        schema: {
          "type": "object",
          "required": ["lineNumber"],
          "properties": {
            "lineNumber": {
              "type": ["number", "string"]
            },
            "at": {
              "type": "string",
              "enum": ["top", "center", "bottom"]
            }
          }
        }
      }
    ]
  };
  RevealLine_2.RawAtArgument = {
    Top: "top",
    Center: "center",
    Bottom: "bottom"
  };
})(RevealLine_ || (RevealLine_ = {}));
var EditorOrNativeTextInputCommand = class {
  constructor(target) {
    target.addImplementation(1e4, "code-editor", (accessor, args2) => {
      const focusedEditor = accessor.get($U5).getFocusedCodeEditor();
      if (focusedEditor && focusedEditor.hasTextFocus()) {
        return this._runEditorCommand(accessor, focusedEditor, args2);
      }
      return false;
    });
    target.addImplementation(1e3, "generic-dom-input-textarea", (accessor, args2) => {
      const activeElement = $Lj();
      if (activeElement && $Fk(activeElement)) {
        this.runDOMCommand(activeElement);
        return true;
      }
      return false;
    });
    target.addImplementation(0, "generic-dom", (accessor, args2) => {
      const activeEditor = accessor.get($U5).getActiveCodeEditor();
      if (activeEditor) {
        activeEditor.focus();
        return this._runEditorCommand(accessor, activeEditor, args2);
      }
      return false;
    });
  }
  _runEditorCommand(accessor, editor, args2) {
    const result = this.runEditorCommand(accessor, editor, args2);
    if (result) {
      return result;
    }
    return true;
  }
};
var NavigationCommandRevealType;
(function(NavigationCommandRevealType2) {
  NavigationCommandRevealType2[NavigationCommandRevealType2["Regular"] = 0] = "Regular";
  NavigationCommandRevealType2[NavigationCommandRevealType2["Minimal"] = 1] = "Minimal";
  NavigationCommandRevealType2[NavigationCommandRevealType2["None"] = 2] = "None";
})(NavigationCommandRevealType || (NavigationCommandRevealType = {}));
var CoreNavigationCommands;
(function(CoreNavigationCommands2) {
  class BaseMoveToCommand extends $U6 {
    constructor(opts) {
      super(opts);
      this.d = opts.inSelectionMode;
    }
    runCoreEditorCommand(viewModel, args2) {
      if (!args2.position) {
        return;
      }
      viewModel.model.pushStackElement();
      const cursorStateChanged = viewModel.setCursorStates(args2.source, 3, [
        $o6.moveTo(viewModel, viewModel.getPrimaryCursorState(), this.d, args2.position, args2.viewPosition)
      ]);
      if (cursorStateChanged && args2.revealType !== 2) {
        viewModel.revealAllCursors(args2.source, true, true);
      }
    }
  }
  CoreNavigationCommands2.MoveTo = $45(new BaseMoveToCommand({
    id: "_moveTo",
    inSelectionMode: false,
    precondition: void 0
  }));
  CoreNavigationCommands2.MoveToSelect = $45(new BaseMoveToCommand({
    id: "_moveToSelect",
    inSelectionMode: true,
    precondition: void 0
  }));
  class ColumnSelectCommand extends $U6 {
    runCoreEditorCommand(viewModel, args2) {
      viewModel.model.pushStackElement();
      const result = this.d(viewModel, viewModel.getPrimaryCursorState(), viewModel.getCursorColumnSelectData(), args2);
      if (result === null) {
        return;
      }
      viewModel.setCursorStates(args2.source, 3, result.viewStates.map((viewState) => $e5.fromViewState(viewState)));
      viewModel.setCursorColumnSelectData({
        isReal: true,
        fromViewLineNumber: result.fromLineNumber,
        fromViewVisualColumn: result.fromVisualColumn,
        toViewLineNumber: result.toLineNumber,
        toViewVisualColumn: result.toVisualColumn
      });
      if (result.reversed) {
        viewModel.revealTopMostCursor(args2.source);
      } else {
        viewModel.revealBottomMostCursor(args2.source);
      }
    }
  }
  CoreNavigationCommands2.ColumnSelect = $45(new class extends ColumnSelectCommand {
    constructor() {
      super({
        id: "columnSelect",
        precondition: void 0
      });
    }
    d(viewModel, primary, prevColumnSelectData, args2) {
      if (typeof args2.position === "undefined" || typeof args2.viewPosition === "undefined" || typeof args2.mouseColumn === "undefined") {
        return null;
      }
      const validatedPosition = viewModel.model.validatePosition(args2.position);
      const validatedViewPosition = viewModel.coordinatesConverter.validateViewPosition(new $8C(args2.viewPosition.lineNumber, args2.viewPosition.column), validatedPosition);
      const fromViewLineNumber = args2.doColumnSelect ? prevColumnSelectData.fromViewLineNumber : validatedViewPosition.lineNumber;
      const fromViewVisualColumn = args2.doColumnSelect ? prevColumnSelectData.fromViewVisualColumn : args2.mouseColumn - 1;
      return $a6.columnSelect(viewModel.cursorConfig, viewModel, fromViewLineNumber, fromViewVisualColumn, validatedViewPosition.lineNumber, args2.mouseColumn - 1);
    }
  }());
  CoreNavigationCommands2.CursorColumnSelectLeft = $45(new class extends ColumnSelectCommand {
    constructor() {
      super({
        id: "cursorColumnSelectLeft",
        precondition: void 0,
        kbOpts: {
          weight: CORE_WEIGHT,
          kbExpr: EditorContextKeys.textInputFocus,
          primary: 2048 | 1024 | 512 | 15,
          linux: { primary: 0 }
        }
      });
    }
    d(viewModel, primary, prevColumnSelectData, args2) {
      return $a6.columnSelectLeft(viewModel.cursorConfig, viewModel, prevColumnSelectData);
    }
  }());
  CoreNavigationCommands2.CursorColumnSelectRight = $45(new class extends ColumnSelectCommand {
    constructor() {
      super({
        id: "cursorColumnSelectRight",
        precondition: void 0,
        kbOpts: {
          weight: CORE_WEIGHT,
          kbExpr: EditorContextKeys.textInputFocus,
          primary: 2048 | 1024 | 512 | 17,
          linux: { primary: 0 }
        }
      });
    }
    d(viewModel, primary, prevColumnSelectData, args2) {
      return $a6.columnSelectRight(viewModel.cursorConfig, viewModel, prevColumnSelectData);
    }
  }());
  class ColumnSelectUpCommand extends ColumnSelectCommand {
    constructor(opts) {
      super(opts);
      this.e = opts.isPaged;
    }
    d(viewModel, primary, prevColumnSelectData, args2) {
      return $a6.columnSelectUp(viewModel.cursorConfig, viewModel, prevColumnSelectData, this.e);
    }
  }
  CoreNavigationCommands2.CursorColumnSelectUp = $45(new ColumnSelectUpCommand({
    isPaged: false,
    id: "cursorColumnSelectUp",
    precondition: void 0,
    kbOpts: {
      weight: CORE_WEIGHT,
      kbExpr: EditorContextKeys.textInputFocus,
      primary: 2048 | 1024 | 512 | 16,
      linux: { primary: 0 }
    }
  }));
  CoreNavigationCommands2.CursorColumnSelectPageUp = $45(new ColumnSelectUpCommand({
    isPaged: true,
    id: "cursorColumnSelectPageUp",
    precondition: void 0,
    kbOpts: {
      weight: CORE_WEIGHT,
      kbExpr: EditorContextKeys.textInputFocus,
      primary: 2048 | 1024 | 512 | 11,
      linux: { primary: 0 }
    }
  }));
  class ColumnSelectDownCommand extends ColumnSelectCommand {
    constructor(opts) {
      super(opts);
      this.e = opts.isPaged;
    }
    d(viewModel, primary, prevColumnSelectData, args2) {
      return $a6.columnSelectDown(viewModel.cursorConfig, viewModel, prevColumnSelectData, this.e);
    }
  }
  CoreNavigationCommands2.CursorColumnSelectDown = $45(new ColumnSelectDownCommand({
    isPaged: false,
    id: "cursorColumnSelectDown",
    precondition: void 0,
    kbOpts: {
      weight: CORE_WEIGHT,
      kbExpr: EditorContextKeys.textInputFocus,
      primary: 2048 | 1024 | 512 | 18,
      linux: { primary: 0 }
    }
  }));
  CoreNavigationCommands2.CursorColumnSelectPageDown = $45(new ColumnSelectDownCommand({
    isPaged: true,
    id: "cursorColumnSelectPageDown",
    precondition: void 0,
    kbOpts: {
      weight: CORE_WEIGHT,
      kbExpr: EditorContextKeys.textInputFocus,
      primary: 2048 | 1024 | 512 | 12,
      linux: { primary: 0 }
    }
  }));
  class CursorMoveImpl extends $U6 {
    constructor() {
      super({
        id: "cursorMove",
        precondition: void 0,
        metadata: CursorMove.metadata
      });
    }
    runCoreEditorCommand(viewModel, args2) {
      const parsed = CursorMove.parse(args2);
      if (!parsed) {
        return;
      }
      this.d(viewModel, args2.source, parsed);
    }
    d(viewModel, source, args2) {
      viewModel.model.pushStackElement();
      viewModel.setCursorStates(source, 3, CursorMoveImpl.e(viewModel, viewModel.getCursorStates(), args2));
      viewModel.revealAllCursors(source, true);
    }
    static e(viewModel, cursors, args2) {
      const inSelectionMode = args2.select;
      const value = args2.value;
      switch (args2.direction) {
        case 0:
        case 1:
        case 2:
        case 3:
        case 4:
        case 5:
        case 6:
        case 7:
        case 8:
        case 9:
        case 10:
          return $o6.simpleMove(viewModel, cursors, args2.direction, inSelectionMode, value, args2.unit);
        case 11:
        case 13:
        case 12:
        case 14:
          return $o6.viewportMove(viewModel, cursors, args2.direction, inSelectionMode, value);
        default:
          return null;
      }
    }
  }
  CoreNavigationCommands2.CursorMoveImpl = CursorMoveImpl;
  CoreNavigationCommands2.CursorMove = $45(new CursorMoveImpl());
  let Constants27;
  (function(Constants28) {
    Constants28[Constants28["PAGE_SIZE_MARKER"] = -1] = "PAGE_SIZE_MARKER";
  })(Constants27 || (Constants27 = {}));
  class CursorMoveBasedCommand extends $U6 {
    constructor(opts) {
      super(opts);
      this.d = opts.args;
    }
    runCoreEditorCommand(viewModel, dynamicArgs) {
      let args2 = this.d;
      if (this.d.value === -1) {
        args2 = {
          direction: this.d.direction,
          unit: this.d.unit,
          select: this.d.select,
          value: dynamicArgs.pageSize || viewModel.cursorConfig.pageSize
        };
      }
      viewModel.model.pushStackElement();
      viewModel.setCursorStates(dynamicArgs.source, 3, $o6.simpleMove(viewModel, viewModel.getCursorStates(), args2.direction, args2.select, args2.value, args2.unit));
      viewModel.revealAllCursors(dynamicArgs.source, true);
    }
  }
  CoreNavigationCommands2.CursorLeft = $45(new CursorMoveBasedCommand({
    args: {
      direction: 0,
      unit: 0,
      select: false,
      value: 1
    },
    id: "cursorLeft",
    precondition: void 0,
    kbOpts: {
      weight: CORE_WEIGHT,
      kbExpr: EditorContextKeys.textInputFocus,
      primary: 15,
      mac: { primary: 15, secondary: [
        256 | 32
        /* KeyCode.KeyB */
      ] }
    }
  }));
  CoreNavigationCommands2.CursorLeftSelect = $45(new CursorMoveBasedCommand({
    args: {
      direction: 0,
      unit: 0,
      select: true,
      value: 1
    },
    id: "cursorLeftSelect",
    precondition: void 0,
    kbOpts: {
      weight: CORE_WEIGHT,
      kbExpr: EditorContextKeys.textInputFocus,
      primary: 1024 | 15
      /* KeyCode.LeftArrow */
    }
  }));
  CoreNavigationCommands2.CursorRight = $45(new CursorMoveBasedCommand({
    args: {
      direction: 1,
      unit: 0,
      select: false,
      value: 1
    },
    id: "cursorRight",
    precondition: void 0,
    kbOpts: {
      weight: CORE_WEIGHT,
      kbExpr: EditorContextKeys.textInputFocus,
      primary: 17,
      mac: { primary: 17, secondary: [
        256 | 36
        /* KeyCode.KeyF */
      ] }
    }
  }));
  CoreNavigationCommands2.CursorRightSelect = $45(new CursorMoveBasedCommand({
    args: {
      direction: 1,
      unit: 0,
      select: true,
      value: 1
    },
    id: "cursorRightSelect",
    precondition: void 0,
    kbOpts: {
      weight: CORE_WEIGHT,
      kbExpr: EditorContextKeys.textInputFocus,
      primary: 1024 | 17
      /* KeyCode.RightArrow */
    }
  }));
  CoreNavigationCommands2.CursorUp = $45(new CursorMoveBasedCommand({
    args: {
      direction: 2,
      unit: 2,
      select: false,
      value: 1
    },
    id: "cursorUp",
    precondition: void 0,
    kbOpts: {
      weight: CORE_WEIGHT,
      kbExpr: EditorContextKeys.textInputFocus,
      primary: 16,
      mac: { primary: 16, secondary: [
        256 | 46
        /* KeyCode.KeyP */
      ] }
    }
  }));
  CoreNavigationCommands2.CursorUpSelect = $45(new CursorMoveBasedCommand({
    args: {
      direction: 2,
      unit: 2,
      select: true,
      value: 1
    },
    id: "cursorUpSelect",
    precondition: void 0,
    kbOpts: {
      weight: CORE_WEIGHT,
      kbExpr: EditorContextKeys.textInputFocus,
      primary: 1024 | 16,
      secondary: [
        2048 | 1024 | 16
        /* KeyCode.UpArrow */
      ],
      mac: {
        primary: 1024 | 16
        /* KeyCode.UpArrow */
      },
      linux: {
        primary: 1024 | 16
        /* KeyCode.UpArrow */
      }
    }
  }));
  CoreNavigationCommands2.CursorPageUp = $45(new CursorMoveBasedCommand({
    args: {
      direction: 2,
      unit: 2,
      select: false,
      value: -1
      /* Constants.PAGE_SIZE_MARKER */
    },
    id: "cursorPageUp",
    precondition: void 0,
    kbOpts: {
      weight: CORE_WEIGHT,
      kbExpr: EditorContextKeys.textInputFocus,
      primary: 11
      /* KeyCode.PageUp */
    }
  }));
  CoreNavigationCommands2.CursorPageUpSelect = $45(new CursorMoveBasedCommand({
    args: {
      direction: 2,
      unit: 2,
      select: true,
      value: -1
      /* Constants.PAGE_SIZE_MARKER */
    },
    id: "cursorPageUpSelect",
    precondition: void 0,
    kbOpts: {
      weight: CORE_WEIGHT,
      kbExpr: EditorContextKeys.textInputFocus,
      primary: 1024 | 11
      /* KeyCode.PageUp */
    }
  }));
  CoreNavigationCommands2.CursorDown = $45(new CursorMoveBasedCommand({
    args: {
      direction: 3,
      unit: 2,
      select: false,
      value: 1
    },
    id: "cursorDown",
    precondition: void 0,
    kbOpts: {
      weight: CORE_WEIGHT,
      kbExpr: EditorContextKeys.textInputFocus,
      primary: 18,
      mac: { primary: 18, secondary: [
        256 | 44
        /* KeyCode.KeyN */
      ] }
    }
  }));
  CoreNavigationCommands2.CursorDownSelect = $45(new CursorMoveBasedCommand({
    args: {
      direction: 3,
      unit: 2,
      select: true,
      value: 1
    },
    id: "cursorDownSelect",
    precondition: void 0,
    kbOpts: {
      weight: CORE_WEIGHT,
      kbExpr: EditorContextKeys.textInputFocus,
      primary: 1024 | 18,
      secondary: [
        2048 | 1024 | 18
        /* KeyCode.DownArrow */
      ],
      mac: {
        primary: 1024 | 18
        /* KeyCode.DownArrow */
      },
      linux: {
        primary: 1024 | 18
        /* KeyCode.DownArrow */
      }
    }
  }));
  CoreNavigationCommands2.CursorPageDown = $45(new CursorMoveBasedCommand({
    args: {
      direction: 3,
      unit: 2,
      select: false,
      value: -1
      /* Constants.PAGE_SIZE_MARKER */
    },
    id: "cursorPageDown",
    precondition: void 0,
    kbOpts: {
      weight: CORE_WEIGHT,
      kbExpr: EditorContextKeys.textInputFocus,
      primary: 12
      /* KeyCode.PageDown */
    }
  }));
  CoreNavigationCommands2.CursorPageDownSelect = $45(new CursorMoveBasedCommand({
    args: {
      direction: 3,
      unit: 2,
      select: true,
      value: -1
      /* Constants.PAGE_SIZE_MARKER */
    },
    id: "cursorPageDownSelect",
    precondition: void 0,
    kbOpts: {
      weight: CORE_WEIGHT,
      kbExpr: EditorContextKeys.textInputFocus,
      primary: 1024 | 12
      /* KeyCode.PageDown */
    }
  }));
  CoreNavigationCommands2.CreateCursor = $45(new class extends $U6 {
    constructor() {
      super({
        id: "createCursor",
        precondition: void 0
      });
    }
    runCoreEditorCommand(viewModel, args2) {
      if (!args2.position) {
        return;
      }
      let newState;
      if (args2.wholeLine) {
        newState = $o6.line(viewModel, viewModel.getPrimaryCursorState(), false, args2.position, args2.viewPosition);
      } else {
        newState = $o6.moveTo(viewModel, viewModel.getPrimaryCursorState(), false, args2.position, args2.viewPosition);
      }
      const states = viewModel.getCursorStates();
      if (states.length > 1) {
        const newModelPosition = newState.modelState ? newState.modelState.position : null;
        const newViewPosition = newState.viewState ? newState.viewState.position : null;
        for (let i2 = 0, len = states.length; i2 < len; i2++) {
          const state = states[i2];
          if (newModelPosition && !state.modelState.selection.containsPosition(newModelPosition)) {
            continue;
          }
          if (newViewPosition && !state.viewState.selection.containsPosition(newViewPosition)) {
            continue;
          }
          states.splice(i2, 1);
          viewModel.model.pushStackElement();
          viewModel.setCursorStates(args2.source, 3, states);
          return;
        }
      }
      states.push(newState);
      viewModel.model.pushStackElement();
      viewModel.setCursorStates(args2.source, 3, states);
    }
  }());
  CoreNavigationCommands2.LastCursorMoveToSelect = $45(new class extends $U6 {
    constructor() {
      super({
        id: "_lastCursorMoveToSelect",
        precondition: void 0
      });
    }
    runCoreEditorCommand(viewModel, args2) {
      if (!args2.position) {
        return;
      }
      const lastAddedCursorIndex = viewModel.getLastAddedCursorIndex();
      const states = viewModel.getCursorStates();
      const newStates = states.slice(0);
      newStates[lastAddedCursorIndex] = $o6.moveTo(viewModel, states[lastAddedCursorIndex], true, args2.position, args2.viewPosition);
      viewModel.model.pushStackElement();
      viewModel.setCursorStates(args2.source, 3, newStates);
    }
  }());
  class HomeCommand extends $U6 {
    constructor(opts) {
      super(opts);
      this.d = opts.inSelectionMode;
    }
    runCoreEditorCommand(viewModel, args2) {
      viewModel.model.pushStackElement();
      viewModel.setCursorStates(args2.source, 3, $o6.moveToBeginningOfLine(viewModel, viewModel.getCursorStates(), this.d));
      viewModel.revealAllCursors(args2.source, true);
    }
  }
  CoreNavigationCommands2.CursorHome = $45(new HomeCommand({
    inSelectionMode: false,
    id: "cursorHome",
    precondition: void 0,
    kbOpts: {
      weight: CORE_WEIGHT,
      kbExpr: EditorContextKeys.textInputFocus,
      primary: 14,
      mac: { primary: 14, secondary: [
        2048 | 15
        /* KeyCode.LeftArrow */
      ] }
    }
  }));
  CoreNavigationCommands2.CursorHomeSelect = $45(new HomeCommand({
    inSelectionMode: true,
    id: "cursorHomeSelect",
    precondition: void 0,
    kbOpts: {
      weight: CORE_WEIGHT,
      kbExpr: EditorContextKeys.textInputFocus,
      primary: 1024 | 14,
      mac: { primary: 1024 | 14, secondary: [
        2048 | 1024 | 15
        /* KeyCode.LeftArrow */
      ] }
    }
  }));
  class LineStartCommand extends $U6 {
    constructor(opts) {
      super(opts);
      this.d = opts.inSelectionMode;
    }
    runCoreEditorCommand(viewModel, args2) {
      viewModel.model.pushStackElement();
      viewModel.setCursorStates(args2.source, 3, this.e(viewModel.getCursorStates()));
      viewModel.revealAllCursors(args2.source, true);
    }
    e(cursors) {
      const result = [];
      for (let i2 = 0, len = cursors.length; i2 < len; i2++) {
        const cursor = cursors[i2];
        const lineNumber = cursor.modelState.position.lineNumber;
        result[i2] = $e5.fromModelState(cursor.modelState.move(this.d, lineNumber, 1, 0));
      }
      return result;
    }
  }
  CoreNavigationCommands2.CursorLineStart = $45(new LineStartCommand({
    inSelectionMode: false,
    id: "cursorLineStart",
    precondition: void 0,
    kbOpts: {
      weight: CORE_WEIGHT,
      kbExpr: EditorContextKeys.textInputFocus,
      primary: 0,
      mac: {
        primary: 256 | 31
        /* KeyCode.KeyA */
      }
    }
  }));
  CoreNavigationCommands2.CursorLineStartSelect = $45(new LineStartCommand({
    inSelectionMode: true,
    id: "cursorLineStartSelect",
    precondition: void 0,
    kbOpts: {
      weight: CORE_WEIGHT,
      kbExpr: EditorContextKeys.textInputFocus,
      primary: 0,
      mac: {
        primary: 256 | 1024 | 31
        /* KeyCode.KeyA */
      }
    }
  }));
  class EndCommand extends $U6 {
    constructor(opts) {
      super(opts);
      this.d = opts.inSelectionMode;
    }
    runCoreEditorCommand(viewModel, args2) {
      viewModel.model.pushStackElement();
      viewModel.setCursorStates(args2.source, 3, $o6.moveToEndOfLine(viewModel, viewModel.getCursorStates(), this.d, args2.sticky || false));
      viewModel.revealAllCursors(args2.source, true);
    }
  }
  CoreNavigationCommands2.CursorEnd = $45(new EndCommand({
    inSelectionMode: false,
    id: "cursorEnd",
    precondition: void 0,
    kbOpts: {
      args: { sticky: false },
      weight: CORE_WEIGHT,
      kbExpr: EditorContextKeys.textInputFocus,
      primary: 13,
      mac: { primary: 13, secondary: [
        2048 | 17
        /* KeyCode.RightArrow */
      ] }
    },
    metadata: {
      description: `Go to End`,
      args: [{
        name: "args",
        schema: {
          type: "object",
          properties: {
            "sticky": {
              description: localize(182, null),
              type: "boolean",
              default: false
            }
          }
        }
      }]
    }
  }));
  CoreNavigationCommands2.CursorEndSelect = $45(new EndCommand({
    inSelectionMode: true,
    id: "cursorEndSelect",
    precondition: void 0,
    kbOpts: {
      args: { sticky: false },
      weight: CORE_WEIGHT,
      kbExpr: EditorContextKeys.textInputFocus,
      primary: 1024 | 13,
      mac: { primary: 1024 | 13, secondary: [
        2048 | 1024 | 17
        /* KeyCode.RightArrow */
      ] }
    },
    metadata: {
      description: `Select to End`,
      args: [{
        name: "args",
        schema: {
          type: "object",
          properties: {
            "sticky": {
              description: localize(183, null),
              type: "boolean",
              default: false
            }
          }
        }
      }]
    }
  }));
  class LineEndCommand extends $U6 {
    constructor(opts) {
      super(opts);
      this.d = opts.inSelectionMode;
    }
    runCoreEditorCommand(viewModel, args2) {
      viewModel.model.pushStackElement();
      viewModel.setCursorStates(args2.source, 3, this.e(viewModel, viewModel.getCursorStates()));
      viewModel.revealAllCursors(args2.source, true);
    }
    e(viewModel, cursors) {
      const result = [];
      for (let i2 = 0, len = cursors.length; i2 < len; i2++) {
        const cursor = cursors[i2];
        const lineNumber = cursor.modelState.position.lineNumber;
        const maxColumn = viewModel.model.getLineMaxColumn(lineNumber);
        result[i2] = $e5.fromModelState(cursor.modelState.move(this.d, lineNumber, maxColumn, 0));
      }
      return result;
    }
  }
  CoreNavigationCommands2.CursorLineEnd = $45(new LineEndCommand({
    inSelectionMode: false,
    id: "cursorLineEnd",
    precondition: void 0,
    kbOpts: {
      weight: CORE_WEIGHT,
      kbExpr: EditorContextKeys.textInputFocus,
      primary: 0,
      mac: {
        primary: 256 | 35
        /* KeyCode.KeyE */
      }
    }
  }));
  CoreNavigationCommands2.CursorLineEndSelect = $45(new LineEndCommand({
    inSelectionMode: true,
    id: "cursorLineEndSelect",
    precondition: void 0,
    kbOpts: {
      weight: CORE_WEIGHT,
      kbExpr: EditorContextKeys.textInputFocus,
      primary: 0,
      mac: {
        primary: 256 | 1024 | 35
        /* KeyCode.KeyE */
      }
    }
  }));
  class TopCommand extends $U6 {
    constructor(opts) {
      super(opts);
      this.d = opts.inSelectionMode;
    }
    runCoreEditorCommand(viewModel, args2) {
      viewModel.model.pushStackElement();
      viewModel.setCursorStates(args2.source, 3, $o6.moveToBeginningOfBuffer(viewModel, viewModel.getCursorStates(), this.d));
      viewModel.revealAllCursors(args2.source, true);
    }
  }
  CoreNavigationCommands2.CursorTop = $45(new TopCommand({
    inSelectionMode: false,
    id: "cursorTop",
    precondition: void 0,
    kbOpts: {
      weight: CORE_WEIGHT,
      kbExpr: EditorContextKeys.textInputFocus,
      primary: 2048 | 14,
      mac: {
        primary: 2048 | 16
        /* KeyCode.UpArrow */
      }
    }
  }));
  CoreNavigationCommands2.CursorTopSelect = $45(new TopCommand({
    inSelectionMode: true,
    id: "cursorTopSelect",
    precondition: void 0,
    kbOpts: {
      weight: CORE_WEIGHT,
      kbExpr: EditorContextKeys.textInputFocus,
      primary: 2048 | 1024 | 14,
      mac: {
        primary: 2048 | 1024 | 16
        /* KeyCode.UpArrow */
      }
    }
  }));
  class BottomCommand extends $U6 {
    constructor(opts) {
      super(opts);
      this.d = opts.inSelectionMode;
    }
    runCoreEditorCommand(viewModel, args2) {
      viewModel.model.pushStackElement();
      viewModel.setCursorStates(args2.source, 3, $o6.moveToEndOfBuffer(viewModel, viewModel.getCursorStates(), this.d));
      viewModel.revealAllCursors(args2.source, true);
    }
  }
  CoreNavigationCommands2.CursorBottom = $45(new BottomCommand({
    inSelectionMode: false,
    id: "cursorBottom",
    precondition: void 0,
    kbOpts: {
      weight: CORE_WEIGHT,
      kbExpr: EditorContextKeys.textInputFocus,
      primary: 2048 | 13,
      mac: {
        primary: 2048 | 18
        /* KeyCode.DownArrow */
      }
    }
  }));
  CoreNavigationCommands2.CursorBottomSelect = $45(new BottomCommand({
    inSelectionMode: true,
    id: "cursorBottomSelect",
    precondition: void 0,
    kbOpts: {
      weight: CORE_WEIGHT,
      kbExpr: EditorContextKeys.textInputFocus,
      primary: 2048 | 1024 | 13,
      mac: {
        primary: 2048 | 1024 | 18
        /* KeyCode.DownArrow */
      }
    }
  }));
  class EditorScrollImpl extends $U6 {
    constructor() {
      super({
        id: "editorScroll",
        precondition: void 0,
        metadata: EditorScroll_.metadata
      });
    }
    determineScrollMethod(args2) {
      const horizontalUnits = [
        6
        /* EditorScroll_.Unit.Column */
      ];
      const verticalUnits = [
        1,
        2,
        3,
        4,
        5,
        6
        /* EditorScroll_.Unit.Column */
      ];
      const horizontalDirections = [
        4,
        2
        /* EditorScroll_.Direction.Right */
      ];
      const verticalDirections = [
        1,
        3
        /* EditorScroll_.Direction.Down */
      ];
      if (horizontalUnits.includes(args2.unit) && horizontalDirections.includes(args2.direction)) {
        return this._runHorizontalEditorScroll.bind(this);
      }
      if (verticalUnits.includes(args2.unit) && verticalDirections.includes(args2.direction)) {
        return this._runVerticalEditorScroll.bind(this);
      }
      return null;
    }
    runCoreEditorCommand(viewModel, args2) {
      const parsed = EditorScroll_.parse(args2);
      if (!parsed) {
        return;
      }
      const runEditorScroll = this.determineScrollMethod(parsed);
      if (!runEditorScroll) {
        return;
      }
      runEditorScroll(viewModel, args2.source, parsed);
    }
    _runVerticalEditorScroll(viewModel, source, args2) {
      const desiredScrollTop = this.d(viewModel, args2);
      if (args2.revealCursor) {
        const desiredVisibleViewRange = viewModel.getCompletelyVisibleViewRangeAtScrollTop(desiredScrollTop);
        viewModel.setCursorStates(source, 3, [
          $o6.findPositionInViewportIfOutside(viewModel, viewModel.getPrimaryCursorState(), desiredVisibleViewRange, args2.select)
        ]);
      }
      viewModel.viewLayout.setScrollPosition(
        { scrollTop: desiredScrollTop },
        0
        /* ScrollType.Smooth */
      );
    }
    d(viewModel, args2) {
      if (args2.unit === 1) {
        const futureViewport = viewModel.viewLayout.getFutureViewport();
        const visibleViewRange = viewModel.getCompletelyVisibleViewRangeAtScrollTop(futureViewport.top);
        const visibleModelRange = viewModel.coordinatesConverter.convertViewRangeToModelRange(visibleViewRange);
        let desiredTopModelLineNumber;
        if (args2.direction === 1) {
          desiredTopModelLineNumber = Math.max(1, visibleModelRange.startLineNumber - args2.value);
        } else {
          desiredTopModelLineNumber = Math.min(viewModel.model.getLineCount(), visibleModelRange.startLineNumber + args2.value);
        }
        const viewPosition = viewModel.coordinatesConverter.convertModelPositionToViewPosition(new $8C(desiredTopModelLineNumber, 1));
        return viewModel.viewLayout.getVerticalOffsetForLineNumber(viewPosition.lineNumber);
      }
      if (args2.unit === 5) {
        let desiredTopModelLineNumber = 0;
        if (args2.direction === 3) {
          desiredTopModelLineNumber = viewModel.model.getLineCount() - viewModel.cursorConfig.pageSize;
        }
        return viewModel.viewLayout.getVerticalOffsetForLineNumber(desiredTopModelLineNumber);
      }
      let noOfLines;
      if (args2.unit === 3) {
        noOfLines = viewModel.cursorConfig.pageSize * args2.value;
      } else if (args2.unit === 4) {
        noOfLines = Math.round(viewModel.cursorConfig.pageSize / 2) * args2.value;
      } else {
        noOfLines = args2.value;
      }
      const deltaLines = (args2.direction === 1 ? -1 : 1) * noOfLines;
      return viewModel.viewLayout.getCurrentScrollTop() + deltaLines * viewModel.cursorConfig.lineHeight;
    }
    _runHorizontalEditorScroll(viewModel, source, args2) {
      const desiredScrollLeft = this._computeDesiredScrollLeft(viewModel, args2);
      viewModel.viewLayout.setScrollPosition(
        { scrollLeft: desiredScrollLeft },
        0
        /* ScrollType.Smooth */
      );
    }
    _computeDesiredScrollLeft(viewModel, args2) {
      const deltaColumns = (args2.direction === 4 ? -1 : 1) * args2.value;
      return viewModel.viewLayout.getCurrentScrollLeft() + deltaColumns * viewModel.cursorConfig.typicalHalfwidthCharacterWidth;
    }
  }
  CoreNavigationCommands2.EditorScrollImpl = EditorScrollImpl;
  CoreNavigationCommands2.EditorScroll = $45(new EditorScrollImpl());
  CoreNavigationCommands2.ScrollLineUp = $45(new class extends $U6 {
    constructor() {
      super({
        id: "scrollLineUp",
        precondition: void 0,
        kbOpts: {
          weight: CORE_WEIGHT,
          kbExpr: EditorContextKeys.textInputFocus,
          primary: 2048 | 16,
          mac: {
            primary: 256 | 11
            /* KeyCode.PageUp */
          }
        }
      });
    }
    runCoreEditorCommand(viewModel, args2) {
      CoreNavigationCommands2.EditorScroll.runCoreEditorCommand(viewModel, {
        to: EditorScroll_.RawDirection.Up,
        by: EditorScroll_.RawUnit.WrappedLine,
        value: 1,
        revealCursor: false,
        select: false,
        source: args2.source
      });
    }
  }());
  CoreNavigationCommands2.ScrollPageUp = $45(new class extends $U6 {
    constructor() {
      super({
        id: "scrollPageUp",
        precondition: void 0,
        kbOpts: {
          weight: CORE_WEIGHT,
          kbExpr: EditorContextKeys.textInputFocus,
          primary: 2048 | 11,
          win: {
            primary: 512 | 11
            /* KeyCode.PageUp */
          },
          linux: {
            primary: 512 | 11
            /* KeyCode.PageUp */
          }
        }
      });
    }
    runCoreEditorCommand(viewModel, args2) {
      CoreNavigationCommands2.EditorScroll.runCoreEditorCommand(viewModel, {
        to: EditorScroll_.RawDirection.Up,
        by: EditorScroll_.RawUnit.Page,
        value: 1,
        revealCursor: false,
        select: false,
        source: args2.source
      });
    }
  }());
  CoreNavigationCommands2.ScrollEditorTop = $45(new class extends $U6 {
    constructor() {
      super({
        id: "scrollEditorTop",
        precondition: void 0,
        kbOpts: {
          weight: CORE_WEIGHT,
          kbExpr: EditorContextKeys.textInputFocus
        }
      });
    }
    runCoreEditorCommand(viewModel, args2) {
      CoreNavigationCommands2.EditorScroll.runCoreEditorCommand(viewModel, {
        to: EditorScroll_.RawDirection.Up,
        by: EditorScroll_.RawUnit.Editor,
        value: 1,
        revealCursor: false,
        select: false,
        source: args2.source
      });
    }
  }());
  CoreNavigationCommands2.ScrollLineDown = $45(new class extends $U6 {
    constructor() {
      super({
        id: "scrollLineDown",
        precondition: void 0,
        kbOpts: {
          weight: CORE_WEIGHT,
          kbExpr: EditorContextKeys.textInputFocus,
          primary: 2048 | 18,
          mac: {
            primary: 256 | 12
            /* KeyCode.PageDown */
          }
        }
      });
    }
    runCoreEditorCommand(viewModel, args2) {
      CoreNavigationCommands2.EditorScroll.runCoreEditorCommand(viewModel, {
        to: EditorScroll_.RawDirection.Down,
        by: EditorScroll_.RawUnit.WrappedLine,
        value: 1,
        revealCursor: false,
        select: false,
        source: args2.source
      });
    }
  }());
  CoreNavigationCommands2.ScrollPageDown = $45(new class extends $U6 {
    constructor() {
      super({
        id: "scrollPageDown",
        precondition: void 0,
        kbOpts: {
          weight: CORE_WEIGHT,
          kbExpr: EditorContextKeys.textInputFocus,
          primary: 2048 | 12,
          win: {
            primary: 512 | 12
            /* KeyCode.PageDown */
          },
          linux: {
            primary: 512 | 12
            /* KeyCode.PageDown */
          }
        }
      });
    }
    runCoreEditorCommand(viewModel, args2) {
      CoreNavigationCommands2.EditorScroll.runCoreEditorCommand(viewModel, {
        to: EditorScroll_.RawDirection.Down,
        by: EditorScroll_.RawUnit.Page,
        value: 1,
        revealCursor: false,
        select: false,
        source: args2.source
      });
    }
  }());
  CoreNavigationCommands2.ScrollEditorBottom = $45(new class extends $U6 {
    constructor() {
      super({
        id: "scrollEditorBottom",
        precondition: void 0,
        kbOpts: {
          weight: CORE_WEIGHT,
          kbExpr: EditorContextKeys.textInputFocus
        }
      });
    }
    runCoreEditorCommand(viewModel, args2) {
      CoreNavigationCommands2.EditorScroll.runCoreEditorCommand(viewModel, {
        to: EditorScroll_.RawDirection.Down,
        by: EditorScroll_.RawUnit.Editor,
        value: 1,
        revealCursor: false,
        select: false,
        source: args2.source
      });
    }
  }());
  CoreNavigationCommands2.ScrollLeft = $45(new class extends $U6 {
    constructor() {
      super({
        id: "scrollLeft",
        precondition: void 0,
        kbOpts: {
          weight: CORE_WEIGHT,
          kbExpr: EditorContextKeys.textInputFocus
        }
      });
    }
    runCoreEditorCommand(viewModel, args2) {
      CoreNavigationCommands2.EditorScroll.runCoreEditorCommand(viewModel, {
        to: EditorScroll_.RawDirection.Left,
        by: EditorScroll_.RawUnit.Column,
        value: 2,
        revealCursor: false,
        select: false,
        source: args2.source
      });
    }
  }());
  CoreNavigationCommands2.ScrollRight = $45(new class extends $U6 {
    constructor() {
      super({
        id: "scrollRight",
        precondition: void 0,
        kbOpts: {
          weight: CORE_WEIGHT,
          kbExpr: EditorContextKeys.textInputFocus
        }
      });
    }
    runCoreEditorCommand(viewModel, args2) {
      CoreNavigationCommands2.EditorScroll.runCoreEditorCommand(viewModel, {
        to: EditorScroll_.RawDirection.Right,
        by: EditorScroll_.RawUnit.Column,
        value: 2,
        revealCursor: false,
        select: false,
        source: args2.source
      });
    }
  }());
  class WordCommand extends $U6 {
    constructor(opts) {
      super(opts);
      this.d = opts.inSelectionMode;
    }
    runCoreEditorCommand(viewModel, args2) {
      if (!args2.position) {
        return;
      }
      viewModel.model.pushStackElement();
      viewModel.setCursorStates(args2.source, 3, [
        $o6.word(viewModel, viewModel.getPrimaryCursorState(), this.d, args2.position)
      ]);
      if (args2.revealType !== 2) {
        viewModel.revealAllCursors(args2.source, true, true);
      }
    }
  }
  CoreNavigationCommands2.WordSelect = $45(new WordCommand({
    inSelectionMode: false,
    id: "_wordSelect",
    precondition: void 0
  }));
  CoreNavigationCommands2.WordSelectDrag = $45(new WordCommand({
    inSelectionMode: true,
    id: "_wordSelectDrag",
    precondition: void 0
  }));
  CoreNavigationCommands2.LastCursorWordSelect = $45(new class extends $U6 {
    constructor() {
      super({
        id: "lastCursorWordSelect",
        precondition: void 0
      });
    }
    runCoreEditorCommand(viewModel, args2) {
      if (!args2.position) {
        return;
      }
      const lastAddedCursorIndex = viewModel.getLastAddedCursorIndex();
      const states = viewModel.getCursorStates();
      const newStates = states.slice(0);
      const lastAddedState = states[lastAddedCursorIndex];
      newStates[lastAddedCursorIndex] = $o6.word(viewModel, lastAddedState, lastAddedState.modelState.hasSelection(), args2.position);
      viewModel.model.pushStackElement();
      viewModel.setCursorStates(args2.source, 3, newStates);
    }
  }());
  class LineCommand extends $U6 {
    constructor(opts) {
      super(opts);
      this.d = opts.inSelectionMode;
    }
    runCoreEditorCommand(viewModel, args2) {
      if (!args2.position) {
        return;
      }
      viewModel.model.pushStackElement();
      viewModel.setCursorStates(args2.source, 3, [
        $o6.line(viewModel, viewModel.getPrimaryCursorState(), this.d, args2.position, args2.viewPosition)
      ]);
      if (args2.revealType !== 2) {
        viewModel.revealAllCursors(args2.source, false, true);
      }
    }
  }
  CoreNavigationCommands2.LineSelect = $45(new LineCommand({
    inSelectionMode: false,
    id: "_lineSelect",
    precondition: void 0
  }));
  CoreNavigationCommands2.LineSelectDrag = $45(new LineCommand({
    inSelectionMode: true,
    id: "_lineSelectDrag",
    precondition: void 0
  }));
  class LastCursorLineCommand extends $U6 {
    constructor(opts) {
      super(opts);
      this.d = opts.inSelectionMode;
    }
    runCoreEditorCommand(viewModel, args2) {
      if (!args2.position) {
        return;
      }
      const lastAddedCursorIndex = viewModel.getLastAddedCursorIndex();
      const states = viewModel.getCursorStates();
      const newStates = states.slice(0);
      newStates[lastAddedCursorIndex] = $o6.line(viewModel, states[lastAddedCursorIndex], this.d, args2.position, args2.viewPosition);
      viewModel.model.pushStackElement();
      viewModel.setCursorStates(args2.source, 3, newStates);
    }
  }
  CoreNavigationCommands2.LastCursorLineSelect = $45(new LastCursorLineCommand({
    inSelectionMode: false,
    id: "lastCursorLineSelect",
    precondition: void 0
  }));
  CoreNavigationCommands2.LastCursorLineSelectDrag = $45(new LastCursorLineCommand({
    inSelectionMode: true,
    id: "lastCursorLineSelectDrag",
    precondition: void 0
  }));
  CoreNavigationCommands2.CancelSelection = $45(new class extends $U6 {
    constructor() {
      super({
        id: "cancelSelection",
        precondition: EditorContextKeys.hasNonEmptySelection,
        kbOpts: {
          weight: CORE_WEIGHT,
          kbExpr: EditorContextKeys.textInputFocus,
          primary: 9,
          secondary: [
            1024 | 9
            /* KeyCode.Escape */
          ]
        }
      });
    }
    runCoreEditorCommand(viewModel, args2) {
      viewModel.model.pushStackElement();
      viewModel.setCursorStates(args2.source, 3, [
        $o6.cancelSelection(viewModel, viewModel.getPrimaryCursorState())
      ]);
      viewModel.revealAllCursors(args2.source, true);
    }
  }());
  CoreNavigationCommands2.RemoveSecondaryCursors = $45(new class extends $U6 {
    constructor() {
      super({
        id: "removeSecondaryCursors",
        precondition: EditorContextKeys.hasMultipleSelections,
        kbOpts: {
          weight: CORE_WEIGHT + 1,
          kbExpr: EditorContextKeys.textInputFocus,
          primary: 9,
          secondary: [
            1024 | 9
            /* KeyCode.Escape */
          ]
        }
      });
    }
    runCoreEditorCommand(viewModel, args2) {
      viewModel.model.pushStackElement();
      viewModel.setCursorStates(args2.source, 3, [
        viewModel.getPrimaryCursorState()
      ]);
      viewModel.revealAllCursors(args2.source, true);
      $_Z(localize(184, null));
    }
  }());
  CoreNavigationCommands2.RevealLine = $45(new class extends $U6 {
    constructor() {
      super({
        id: "revealLine",
        precondition: void 0,
        metadata: RevealLine_.metadata
      });
    }
    runCoreEditorCommand(viewModel, args2) {
      const revealLineArg = args2;
      const lineNumberArg = revealLineArg.lineNumber || 0;
      let lineNumber = typeof lineNumberArg === "number" ? lineNumberArg + 1 : parseInt(lineNumberArg) + 1;
      if (lineNumber < 1) {
        lineNumber = 1;
      }
      const lineCount = viewModel.model.getLineCount();
      if (lineNumber > lineCount) {
        lineNumber = lineCount;
      }
      const range = new $9C(lineNumber, 1, lineNumber, viewModel.model.getLineMaxColumn(lineNumber));
      let revealAt = 0;
      if (revealLineArg.at) {
        switch (revealLineArg.at) {
          case RevealLine_.RawAtArgument.Top:
            revealAt = 3;
            break;
          case RevealLine_.RawAtArgument.Center:
            revealAt = 1;
            break;
          case RevealLine_.RawAtArgument.Bottom:
            revealAt = 4;
            break;
          default:
            break;
        }
      }
      const viewRange = viewModel.coordinatesConverter.convertModelRangeToViewRange(range);
      viewModel.revealRange(
        args2.source,
        false,
        viewRange,
        revealAt,
        0
        /* ScrollType.Smooth */
      );
    }
  }());
  CoreNavigationCommands2.SelectAll = new class extends EditorOrNativeTextInputCommand {
    constructor() {
      super($_5);
    }
    runDOMCommand(activeElement) {
      if ($Ue) {
        activeElement.focus();
        activeElement.select();
      }
      activeElement.ownerDocument.execCommand("selectAll");
    }
    runEditorCommand(accessor, editor, args2) {
      const viewModel = editor._getViewModel();
      if (!viewModel) {
        return;
      }
      this.runCoreEditorCommand(viewModel, args2);
    }
    runCoreEditorCommand(viewModel, args2) {
      viewModel.model.pushStackElement();
      viewModel.setCursorStates("keyboard", 3, [
        $o6.selectAll(viewModel, viewModel.getPrimaryCursorState())
      ]);
    }
  }();
  CoreNavigationCommands2.SetSelection = $45(new class extends $U6 {
    constructor() {
      super({
        id: "setSelection",
        precondition: void 0
      });
    }
    runCoreEditorCommand(viewModel, args2) {
      if (!args2.selection) {
        return;
      }
      viewModel.model.pushStackElement();
      viewModel.setCursorStates(args2.source, 3, [
        $e5.fromModelSelection(args2.selection)
      ]);
    }
  }());
})(CoreNavigationCommands || (CoreNavigationCommands = {}));
var columnSelectionCondition = $7m.and(EditorContextKeys.textInputFocus, EditorContextKeys.columnSelection);
function registerColumnSelection(id2, keybinding) {
  $0I.registerKeybindingRule({
    id: id2,
    primary: keybinding,
    when: columnSelectionCondition,
    weight: CORE_WEIGHT + 1
  });
}
registerColumnSelection(
  CoreNavigationCommands.CursorColumnSelectLeft.id,
  1024 | 15
  /* KeyCode.LeftArrow */
);
registerColumnSelection(
  CoreNavigationCommands.CursorColumnSelectRight.id,
  1024 | 17
  /* KeyCode.RightArrow */
);
registerColumnSelection(
  CoreNavigationCommands.CursorColumnSelectUp.id,
  1024 | 16
  /* KeyCode.UpArrow */
);
registerColumnSelection(
  CoreNavigationCommands.CursorColumnSelectPageUp.id,
  1024 | 11
  /* KeyCode.PageUp */
);
registerColumnSelection(
  CoreNavigationCommands.CursorColumnSelectDown.id,
  1024 | 18
  /* KeyCode.DownArrow */
);
registerColumnSelection(
  CoreNavigationCommands.CursorColumnSelectPageDown.id,
  1024 | 12
  /* KeyCode.PageDown */
);
function registerCommand2(command4) {
  command4.register();
  return command4;
}
var CoreEditingCommands;
(function(CoreEditingCommands2) {
  class CoreEditingCommand extends $Y5 {
    runEditorCommand(accessor, editor, args2) {
      const viewModel = editor._getViewModel();
      if (!viewModel) {
        return;
      }
      this.runCoreEditingCommand(editor, viewModel, args2 || {});
    }
  }
  CoreEditingCommands2.CoreEditingCommand = CoreEditingCommand;
  CoreEditingCommands2.LineBreakInsert = $45(new class extends CoreEditingCommand {
    constructor() {
      super({
        id: "lineBreakInsert",
        precondition: EditorContextKeys.writable,
        kbOpts: {
          weight: CORE_WEIGHT,
          kbExpr: EditorContextKeys.textInputFocus,
          primary: 0,
          mac: {
            primary: 256 | 45
            /* KeyCode.KeyO */
          }
        }
      });
    }
    runCoreEditingCommand(editor, viewModel, args2) {
      editor.pushUndoStop();
      editor.executeCommands(this.id, $J6.lineBreakInsert(viewModel.cursorConfig, viewModel.model, viewModel.getCursorStates().map((s) => s.modelState.selection)));
    }
  }());
  CoreEditingCommands2.Outdent = $45(new class extends CoreEditingCommand {
    constructor() {
      super({
        id: "outdent",
        precondition: EditorContextKeys.writable,
        kbOpts: {
          weight: CORE_WEIGHT,
          kbExpr: $7m.and(EditorContextKeys.editorTextFocus, EditorContextKeys.tabDoesNotMoveFocus),
          primary: 1024 | 2
          /* KeyCode.Tab */
        }
      });
    }
    runCoreEditingCommand(editor, viewModel, args2) {
      editor.pushUndoStop();
      editor.executeCommands(this.id, $S6.outdent(viewModel.cursorConfig, viewModel.model, viewModel.getCursorStates().map((s) => s.modelState.selection)));
      editor.pushUndoStop();
    }
  }());
  CoreEditingCommands2.Tab = $45(new class extends CoreEditingCommand {
    constructor() {
      super({
        id: "tab",
        precondition: EditorContextKeys.writable,
        kbOpts: {
          weight: CORE_WEIGHT,
          kbExpr: $7m.and(EditorContextKeys.editorTextFocus, EditorContextKeys.tabDoesNotMoveFocus),
          primary: 2
          /* KeyCode.Tab */
        }
      });
    }
    runCoreEditingCommand(editor, viewModel, args2) {
      editor.pushUndoStop();
      editor.executeCommands(this.id, $S6.tab(viewModel.cursorConfig, viewModel.model, viewModel.getCursorStates().map((s) => s.modelState.selection)));
      editor.pushUndoStop();
    }
  }());
  CoreEditingCommands2.DeleteLeft = $45(new class extends CoreEditingCommand {
    constructor() {
      super({
        id: "deleteLeft",
        precondition: void 0,
        kbOpts: {
          weight: CORE_WEIGHT,
          kbExpr: EditorContextKeys.textInputFocus,
          primary: 1,
          secondary: [
            1024 | 1
            /* KeyCode.Backspace */
          ],
          mac: { primary: 1, secondary: [
            1024 | 1,
            256 | 38,
            256 | 1
            /* KeyCode.Backspace */
          ] }
        }
      });
    }
    runCoreEditingCommand(editor, viewModel, args2) {
      const [shouldPushStackElementBefore, commands2] = $l6.deleteLeft(viewModel.getPrevEditOperationType(), viewModel.cursorConfig, viewModel.model, viewModel.getCursorStates().map((s) => s.modelState.selection), viewModel.getCursorAutoClosedCharacters());
      if (shouldPushStackElementBefore) {
        editor.pushUndoStop();
      }
      editor.executeCommands(this.id, commands2);
      viewModel.setPrevEditOperationType(
        2
        /* EditOperationType.DeletingLeft */
      );
    }
  }());
  CoreEditingCommands2.DeleteRight = $45(new class extends CoreEditingCommand {
    constructor() {
      super({
        id: "deleteRight",
        precondition: void 0,
        kbOpts: {
          weight: CORE_WEIGHT,
          kbExpr: EditorContextKeys.textInputFocus,
          primary: 20,
          mac: { primary: 20, secondary: [
            256 | 34,
            256 | 20
            /* KeyCode.Delete */
          ] }
        }
      });
    }
    runCoreEditingCommand(editor, viewModel, args2) {
      const [shouldPushStackElementBefore, commands2] = $l6.deleteRight(viewModel.getPrevEditOperationType(), viewModel.cursorConfig, viewModel.model, viewModel.getCursorStates().map((s) => s.modelState.selection));
      if (shouldPushStackElementBefore) {
        editor.pushUndoStop();
      }
      editor.executeCommands(this.id, commands2);
      viewModel.setPrevEditOperationType(
        3
        /* EditOperationType.DeletingRight */
      );
    }
  }());
  CoreEditingCommands2.Undo = new class extends EditorOrNativeTextInputCommand {
    constructor() {
      super($05);
    }
    runDOMCommand(activeElement) {
      activeElement.ownerDocument.execCommand("undo");
    }
    runEditorCommand(accessor, editor, args2) {
      if (!editor.hasModel() || editor.getOption(
        96
        /* EditorOption.readOnly */
      ) === true) {
        return;
      }
      return editor.getModel().undo();
    }
  }();
  CoreEditingCommands2.Redo = new class extends EditorOrNativeTextInputCommand {
    constructor() {
      super($$5);
    }
    runDOMCommand(activeElement) {
      activeElement.ownerDocument.execCommand("redo");
    }
    runEditorCommand(accessor, editor, args2) {
      if (!editor.hasModel() || editor.getOption(
        96
        /* EditorOption.readOnly */
      ) === true) {
        return;
      }
      return editor.getModel().redo();
    }
  }();
})(CoreEditingCommands || (CoreEditingCommands = {}));
var EditorHandlerCommand = class extends $V5 {
  constructor(id2, handlerId, metadata) {
    super({
      id: id2,
      precondition: void 0,
      metadata
    });
    this.d = handlerId;
  }
  runCommand(accessor, args2) {
    const editor = accessor.get($U5).getFocusedCodeEditor();
    if (!editor) {
      return;
    }
    editor.trigger("keyboard", this.d, args2);
  }
};
function registerOverwritableCommand(handlerId, metadata) {
  registerCommand2(new EditorHandlerCommand("default:" + handlerId, handlerId));
  registerCommand2(new EditorHandlerCommand(handlerId, handlerId, metadata));
}
registerOverwritableCommand("type", {
  description: `Type`,
  args: [{
    name: "args",
    schema: {
      "type": "object",
      "required": ["text"],
      "properties": {
        "text": {
          "type": "string"
        }
      }
    }
  }]
});
registerOverwritableCommand(
  "replacePreviousChar"
  /* Handler.ReplacePreviousChar */
);
registerOverwritableCommand(
  "compositionType"
  /* Handler.CompositionType */
);
registerOverwritableCommand(
  "compositionStart"
  /* Handler.CompositionStart */
);
registerOverwritableCommand(
  "compositionEnd"
  /* Handler.CompositionEnd */
);
registerOverwritableCommand(
  "paste"
  /* Handler.Paste */
);
registerOverwritableCommand(
  "cut"
  /* Handler.Cut */
);

// out-build/vs/editor/common/services/markerDecorations.js
var $V6 = $Qk("markerDecorationsService");

// out-build/vs/editor/browser/services/markerDecorations.js
var $W6 = class $W62 {
  static {
    this.ID = "editor.contrib.markerDecorations";
  }
  constructor(_editor, _markerDecorationsService) {
  }
  dispose() {
  }
};
$W6 = __decorate([
  __param(1, $V6)
], $W6);
$85(
  $W6.ID,
  $W6,
  0
  /* EditorContributionInstantiation.Eager */
);

// out-build/vs/base/browser/fastDomNode.js
var $nZ = class {
  constructor(domNode) {
    this.domNode = domNode;
    this.a = "";
    this.b = "";
    this.c = "";
    this.d = "";
    this.e = "";
    this.f = "";
    this.g = "";
    this.h = "";
    this.i = "";
    this.j = "";
    this.k = "";
    this.l = "";
    this.m = "";
    this.n = "";
    this.o = "";
    this.p = "";
    this.q = "";
    this.r = "";
    this.s = "";
    this.t = "";
    this.u = "";
    this.v = "";
    this.w = "";
    this.x = "";
    this.y = "";
    this.z = "";
    this.A = false;
    this.B = "none";
    this.C = "";
  }
  focus() {
    this.domNode.focus();
  }
  setMaxWidth(_maxWidth) {
    const maxWidth = numberAsPixels(_maxWidth);
    if (this.a === maxWidth) {
      return;
    }
    this.a = maxWidth;
    this.domNode.style.maxWidth = this.a;
  }
  setWidth(_width) {
    const width2 = numberAsPixels(_width);
    if (this.b === width2) {
      return;
    }
    this.b = width2;
    this.domNode.style.width = this.b;
  }
  setHeight(_height) {
    const height = numberAsPixels(_height);
    if (this.c === height) {
      return;
    }
    this.c = height;
    this.domNode.style.height = this.c;
  }
  setTop(_top) {
    const top2 = numberAsPixels(_top);
    if (this.d === top2) {
      return;
    }
    this.d = top2;
    this.domNode.style.top = this.d;
  }
  setLeft(_left) {
    const left = numberAsPixels(_left);
    if (this.e === left) {
      return;
    }
    this.e = left;
    this.domNode.style.left = this.e;
  }
  setBottom(_bottom) {
    const bottom = numberAsPixels(_bottom);
    if (this.f === bottom) {
      return;
    }
    this.f = bottom;
    this.domNode.style.bottom = this.f;
  }
  setRight(_right) {
    const right = numberAsPixels(_right);
    if (this.g === right) {
      return;
    }
    this.g = right;
    this.domNode.style.right = this.g;
  }
  setPaddingTop(_paddingTop) {
    const paddingTop = numberAsPixels(_paddingTop);
    if (this.h === paddingTop) {
      return;
    }
    this.h = paddingTop;
    this.domNode.style.paddingTop = this.h;
  }
  setPaddingLeft(_paddingLeft) {
    const paddingLeft = numberAsPixels(_paddingLeft);
    if (this.i === paddingLeft) {
      return;
    }
    this.i = paddingLeft;
    this.domNode.style.paddingLeft = this.i;
  }
  setPaddingBottom(_paddingBottom) {
    const paddingBottom = numberAsPixels(_paddingBottom);
    if (this.j === paddingBottom) {
      return;
    }
    this.j = paddingBottom;
    this.domNode.style.paddingBottom = this.j;
  }
  setPaddingRight(_paddingRight) {
    const paddingRight = numberAsPixels(_paddingRight);
    if (this.k === paddingRight) {
      return;
    }
    this.k = paddingRight;
    this.domNode.style.paddingRight = this.k;
  }
  setFontFamily(fontFamily) {
    if (this.l === fontFamily) {
      return;
    }
    this.l = fontFamily;
    this.domNode.style.fontFamily = this.l;
  }
  setFontWeight(fontWeight) {
    if (this.m === fontWeight) {
      return;
    }
    this.m = fontWeight;
    this.domNode.style.fontWeight = this.m;
  }
  setFontSize(_fontSize) {
    const fontSize = numberAsPixels(_fontSize);
    if (this.n === fontSize) {
      return;
    }
    this.n = fontSize;
    this.domNode.style.fontSize = this.n;
  }
  setFontStyle(fontStyle) {
    if (this.o === fontStyle) {
      return;
    }
    this.o = fontStyle;
    this.domNode.style.fontStyle = this.o;
  }
  setFontFeatureSettings(fontFeatureSettings) {
    if (this.p === fontFeatureSettings) {
      return;
    }
    this.p = fontFeatureSettings;
    this.domNode.style.fontFeatureSettings = this.p;
  }
  setFontVariationSettings(fontVariationSettings) {
    if (this.q === fontVariationSettings) {
      return;
    }
    this.q = fontVariationSettings;
    this.domNode.style.fontVariationSettings = this.q;
  }
  setTextDecoration(textDecoration) {
    if (this.r === textDecoration) {
      return;
    }
    this.r = textDecoration;
    this.domNode.style.textDecoration = this.r;
  }
  setLineHeight(_lineHeight) {
    const lineHeight = numberAsPixels(_lineHeight);
    if (this.s === lineHeight) {
      return;
    }
    this.s = lineHeight;
    this.domNode.style.lineHeight = this.s;
  }
  setLetterSpacing(_letterSpacing) {
    const letterSpacing = numberAsPixels(_letterSpacing);
    if (this.t === letterSpacing) {
      return;
    }
    this.t = letterSpacing;
    this.domNode.style.letterSpacing = this.t;
  }
  setClassName(className) {
    if (this.u === className) {
      return;
    }
    this.u = className;
    this.domNode.className = this.u;
  }
  toggleClassName(className, shouldHaveIt) {
    this.domNode.classList.toggle(className, shouldHaveIt);
    this.u = this.domNode.className;
  }
  setDisplay(display) {
    if (this.v === display) {
      return;
    }
    this.v = display;
    this.domNode.style.display = this.v;
  }
  setPosition(position) {
    if (this.w === position) {
      return;
    }
    this.w = position;
    this.domNode.style.position = this.w;
  }
  setVisibility(visibility) {
    if (this.x === visibility) {
      return;
    }
    this.x = visibility;
    this.domNode.style.visibility = this.x;
  }
  setColor(color2) {
    if (this.y === color2) {
      return;
    }
    this.y = color2;
    this.domNode.style.color = this.y;
  }
  setBackgroundColor(backgroundColor) {
    if (this.z === backgroundColor) {
      return;
    }
    this.z = backgroundColor;
    this.domNode.style.backgroundColor = this.z;
  }
  setLayerHinting(layerHint) {
    if (this.A === layerHint) {
      return;
    }
    this.A = layerHint;
    this.domNode.style.transform = this.A ? "translate3d(0px, 0px, 0px)" : "";
  }
  setBoxShadow(boxShadow) {
    if (this.C === boxShadow) {
      return;
    }
    this.C = boxShadow;
    this.domNode.style.boxShadow = boxShadow;
  }
  setContain(contain) {
    if (this.B === contain) {
      return;
    }
    this.B = contain;
    this.domNode.style.contain = this.B;
  }
  setAttribute(name, value) {
    this.domNode.setAttribute(name, value);
  }
  removeAttribute(name) {
    this.domNode.removeAttribute(name);
  }
  appendChild(child) {
    this.domNode.appendChild(child.domNode);
  }
  removeChild(child) {
    this.domNode.removeChild(child.domNode);
  }
};
function numberAsPixels(value) {
  return typeof value === "number" ? `${value}px` : value;
}
function $oZ(domNode) {
  return new $nZ(domNode);
}

// out-build/vs/editor/browser/config/domFontInfo.js
function $24(domNode, fontInfo) {
  if (domNode instanceof $nZ) {
    domNode.setFontFamily(fontInfo.getMassagedFontFamily());
    domNode.setFontWeight(fontInfo.fontWeight);
    domNode.setFontSize(fontInfo.fontSize);
    domNode.setFontFeatureSettings(fontInfo.fontFeatureSettings);
    domNode.setFontVariationSettings(fontInfo.fontVariationSettings);
    domNode.setLineHeight(fontInfo.lineHeight);
    domNode.setLetterSpacing(fontInfo.letterSpacing);
  } else {
    domNode.style.fontFamily = fontInfo.getMassagedFontFamily();
    domNode.style.fontWeight = fontInfo.fontWeight;
    domNode.style.fontSize = fontInfo.fontSize + "px";
    domNode.style.fontFeatureSettings = fontInfo.fontFeatureSettings;
    domNode.style.fontVariationSettings = fontInfo.fontVariationSettings;
    domNode.style.lineHeight = fontInfo.lineHeight + "px";
    domNode.style.letterSpacing = fontInfo.letterSpacing + "px";
  }
}

// out-build/vs/base/common/objects.js
function $Lv(obj) {
  if (!obj || typeof obj !== "object") {
    return obj;
  }
  if (obj instanceof RegExp) {
    return obj;
  }
  const result = Array.isArray(obj) ? [] : {};
  Object.entries(obj).forEach(([key2, value]) => {
    result[key2] = value && typeof value === "object" ? $Lv(value) : value;
  });
  return result;
}
function $Mv(obj) {
  if (!obj || typeof obj !== "object") {
    return obj;
  }
  const stack = [obj];
  while (stack.length > 0) {
    const obj2 = stack.shift();
    Object.freeze(obj2);
    for (const key2 in obj2) {
      if (_hasOwnProperty.call(obj2, key2)) {
        const prop = obj2[key2];
        if (typeof prop === "object" && !Object.isFrozen(prop) && !$Cg(prop)) {
          stack.push(prop);
        }
      }
    }
  }
  return obj;
}
var _hasOwnProperty = Object.prototype.hasOwnProperty;
function $Nv(obj, changer) {
  return _cloneAndChange(obj, changer, /* @__PURE__ */ new Set());
}
function _cloneAndChange(obj, changer, seen) {
  if ($Ig(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 ($Bg(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 $Ov(destination, source, overwrite = true) {
  if (!$Bg(destination)) {
    return source;
  }
  if ($Bg(source)) {
    Object.keys(source).forEach((key2) => {
      if (key2 in destination) {
        if (overwrite) {
          if ($Bg(destination[key2]) && $Bg(source[key2])) {
            $Ov(destination[key2], source[key2], overwrite);
          } else {
            destination[key2] = source[key2];
          }
        }
      } else {
        destination[key2] = source[key2];
      }
    });
  }
  return destination;
}
function $Pv(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 i2;
  let key2;
  if (Array.isArray(one)) {
    if (one.length !== other.length) {
      return false;
    }
    for (i2 = 0; i2 < one.length; i2++) {
      if (!$Pv(one[i2], other[i2])) {
        return false;
      }
    }
  } else {
    const oneKeys = [];
    for (key2 in one) {
      oneKeys.push(key2);
    }
    oneKeys.sort();
    const otherKeys = [];
    for (key2 in other) {
      otherKeys.push(key2);
    }
    otherKeys.sort();
    if (!$Pv(oneKeys, otherKeys)) {
      return false;
    }
    for (i2 = 0; i2 < oneKeys.length; i2++) {
      if (!$Pv(one[oneKeys[i2]], other[oneKeys[i2]])) {
        return false;
      }
    }
  }
  return true;
}
function $Qv(obj) {
  const seen = /* @__PURE__ */ new Set();
  return JSON.stringify(obj, (key2, value) => {
    if ($Bg(value) || Array.isArray(value)) {
      if (seen.has(value)) {
        return "[Circular]";
      } else {
        seen.add(value);
      }
    }
    if (typeof value === "bigint") {
      return `[BigInt ${value.toString()}]`;
    }
    return value;
  });
}
function $Rv(base, target) {
  const result = /* @__PURE__ */ Object.create(null);
  if (!base || !target) {
    return result;
  }
  const targetKeys = Object.keys(target);
  targetKeys.forEach((k) => {
    const baseValue = base[k];
    const targetValue = target[k];
    if (!$Pv(baseValue, targetValue)) {
      result[k] = targetValue;
    }
  });
  return result;
}
function $Tv(obj, predicate) {
  const result = /* @__PURE__ */ Object.create(null);
  for (const [key2, value] of Object.entries(obj)) {
    if (predicate(key2, value)) {
      result[key2] = value;
    }
  }
  return result;
}
function $Uv(obj) {
  let res = [];
  while (Object.prototype !== obj) {
    res = res.concat(Object.getOwnPropertyNames(obj));
    obj = Object.getPrototypeOf(obj);
  }
  return res;
}
function $Vv(obj) {
  const methods = [];
  for (const prop of $Uv(obj)) {
    if (typeof obj[prop] === "function") {
      methods.push(prop);
    }
  }
  return methods;
}
function $Wv(methodNames, invoke) {
  const createProxyMethod = (method) => {
    return function() {
      const args2 = Array.prototype.slice.call(arguments, 0);
      return invoke(method, args2);
    };
  };
  const result = {};
  for (const methodName of methodNames) {
    result[methodName] = createProxyMethod(methodName);
  }
  return result;
}
function $Xv(obj, fn) {
  const result = {};
  for (const [key2, value] of Object.entries(obj)) {
    result[key2] = fn(value, key2);
  }
  return result;
}

// out-build/vs/editor/browser/config/elementSizeObserver.js
var $14 = class extends $3c {
  constructor(referenceDomElement, dimension) {
    super();
    this.a = this.B(new $ze());
    this.onDidChange = this.a.event;
    this.b = referenceDomElement;
    this.c = -1;
    this.f = -1;
    this.g = null;
    this.h(false, dimension);
  }
  dispose() {
    this.stopObserving();
    super.dispose();
  }
  getWidth() {
    return this.c;
  }
  getHeight() {
    return this.f;
  }
  startObserving() {
    if (!this.g && this.b) {
      let observedDimenstion = null;
      const observeNow = () => {
        if (observedDimenstion) {
          this.observe({ width: observedDimenstion.width, height: observedDimenstion.height });
        } else {
          this.observe();
        }
      };
      let shouldObserve = false;
      let alreadyObservedThisAnimationFrame = false;
      const update = () => {
        if (shouldObserve && !alreadyObservedThisAnimationFrame) {
          try {
            shouldObserve = false;
            alreadyObservedThisAnimationFrame = true;
            observeNow();
          } finally {
            $jj(getWindow(this.b), () => {
              alreadyObservedThisAnimationFrame = false;
              update();
            });
          }
        }
      };
      this.g = new ResizeObserver((entries2) => {
        if (entries2 && entries2[0] && entries2[0].contentRect) {
          observedDimenstion = { width: entries2[0].contentRect.width, height: entries2[0].contentRect.height };
        } else {
          observedDimenstion = null;
        }
        shouldObserve = true;
        update();
      });
      this.g.observe(this.b);
    }
  }
  stopObserving() {
    if (this.g) {
      this.g.disconnect();
      this.g = null;
    }
  }
  observe(dimension) {
    this.h(true, dimension);
  }
  h(emitEvent, dimension) {
    let observedWidth = 0;
    let observedHeight = 0;
    if (dimension) {
      observedWidth = dimension.width;
      observedHeight = dimension.height;
    } else if (this.b) {
      observedWidth = this.b.clientWidth;
      observedHeight = this.b.clientHeight;
    }
    observedWidth = Math.max(5, observedWidth);
    observedHeight = Math.max(5, observedHeight);
    if (this.c !== observedWidth || this.f !== observedHeight) {
      this.c = observedWidth;
      this.f = observedHeight;
      if (emitEvent) {
        this.a.fire();
      }
    }
  }
};

// out-build/vs/base/browser/pixelRatio.js
var DevicePixelRatioMonitor = class extends $3c {
  constructor(targetWindow) {
    super();
    this.a = this.B(new $ze());
    this.onDidChange = this.a.event;
    this.b = () => this.f(targetWindow, true);
    this.c = null;
    this.f(targetWindow, false);
  }
  f(targetWindow, fireEvent) {
    this.c?.removeEventListener("change", this.b);
    this.c = targetWindow.matchMedia(`(resolution: ${targetWindow.devicePixelRatio}dppx)`);
    this.c.addEventListener("change", this.b);
    if (fireEvent) {
      this.a.fire();
    }
  }
};
var PixelRatioMonitorImpl = class extends $3c {
  get value() {
    return this.b;
  }
  constructor(targetWindow) {
    super();
    this.a = this.B(new $ze());
    this.onDidChange = this.a.event;
    this.b = this.c(targetWindow);
    const dprMonitor = this.B(new DevicePixelRatioMonitor(targetWindow));
    this.B(dprMonitor.onDidChange(() => {
      this.b = this.c(targetWindow);
      this.a.fire(this.b);
    }));
  }
  c(targetWindow) {
    const ctx = document.createElement("canvas").getContext("2d");
    const dpr = targetWindow.devicePixelRatio || 1;
    const bsr = ctx.webkitBackingStorePixelRatio || ctx.mozBackingStorePixelRatio || ctx.msBackingStorePixelRatio || ctx.oBackingStorePixelRatio || ctx.backingStorePixelRatio || 1;
    return dpr / bsr;
  }
};
var PixelRatioMonitorFacade = class {
  constructor() {
    this.a = /* @__PURE__ */ new Map();
  }
  b(targetWindow) {
    const targetWindowId = getWindowId(targetWindow);
    let pixelRatioMonitor = this.a.get(targetWindowId);
    if (!pixelRatioMonitor) {
      pixelRatioMonitor = $Vc(new PixelRatioMonitorImpl(targetWindow));
      this.a.set(targetWindowId, pixelRatioMonitor);
      $Vc(Event2.once(onDidUnregisterWindow)(({ vscodeWindowId }) => {
        if (vscodeWindowId === targetWindowId) {
          pixelRatioMonitor?.dispose();
          this.a.delete(targetWindowId);
        }
      }));
    }
    return pixelRatioMonitor;
  }
  getInstance(targetWindow) {
    return this.b(targetWindow);
  }
};
var $_1 = new PixelRatioMonitorFacade();

// out-build/vs/editor/browser/config/charWidthReader.js
var CharWidthRequestType;
(function(CharWidthRequestType2) {
  CharWidthRequestType2[CharWidthRequestType2["Regular"] = 0] = "Regular";
  CharWidthRequestType2[CharWidthRequestType2["Italic"] = 1] = "Italic";
  CharWidthRequestType2[CharWidthRequestType2["Bold"] = 2] = "Bold";
})(CharWidthRequestType || (CharWidthRequestType = {}));
var $34 = class {
  constructor(chr, type) {
    this.chr = chr;
    this.type = type;
    this.width = 0;
  }
  fulfill(width2) {
    this.width = width2;
  }
};
var DomCharWidthReader = class _DomCharWidthReader {
  constructor(bareFontInfo, requests) {
    this.a = bareFontInfo;
    this.b = requests;
    this.c = null;
    this.d = null;
  }
  read(targetWindow) {
    this.e();
    targetWindow.document.body.appendChild(this.c);
    this.g();
    this.c?.remove();
    this.c = null;
    this.d = null;
  }
  e() {
    const container2 = document.createElement("div");
    container2.style.position = "absolute";
    container2.style.top = "-50000px";
    container2.style.width = "50000px";
    const regularDomNode = document.createElement("div");
    $24(regularDomNode, this.a);
    container2.appendChild(regularDomNode);
    const boldDomNode = document.createElement("div");
    $24(boldDomNode, this.a);
    boldDomNode.style.fontWeight = "bold";
    container2.appendChild(boldDomNode);
    const italicDomNode = document.createElement("div");
    $24(italicDomNode, this.a);
    italicDomNode.style.fontStyle = "italic";
    container2.appendChild(italicDomNode);
    const testElements = [];
    for (const request of this.b) {
      let parent;
      if (request.type === 0) {
        parent = regularDomNode;
      }
      if (request.type === 2) {
        parent = boldDomNode;
      }
      if (request.type === 1) {
        parent = italicDomNode;
      }
      parent.appendChild(document.createElement("br"));
      const testElement = document.createElement("span");
      _DomCharWidthReader.f(testElement, request);
      parent.appendChild(testElement);
      testElements.push(testElement);
    }
    this.c = container2;
    this.d = testElements;
  }
  static f(testElement, request) {
    if (request.chr === " ") {
      let htmlString = "\xA0";
      for (let i2 = 0; i2 < 8; i2++) {
        htmlString += htmlString;
      }
      testElement.innerText = htmlString;
    } else {
      let testString = request.chr;
      for (let i2 = 0; i2 < 8; i2++) {
        testString += testString;
      }
      testElement.textContent = testString;
    }
  }
  g() {
    for (let i2 = 0, len = this.b.length; i2 < len; i2++) {
      const request = this.b[i2];
      const testElement = this.d[i2];
      request.fulfill(testElement.offsetWidth / 256);
    }
  }
};
function $44(targetWindow, bareFontInfo, requests) {
  const reader = new DomCharWidthReader(bareFontInfo, requests);
  reader.read(targetWindow);
}

// out-build/vs/editor/common/core/textModelDefaults.js
var $HD = {
  tabSize: 4,
  indentSize: 4,
  insertSpaces: true,
  detectIndentation: true,
  trimAutoWhitespace: true,
  largeFileOptimizations: true,
  bracketPairColorizationOptions: {
    enabled: true,
    independentColorPoolPerBracketType: false
  }
};

// out-build/vs/editor/common/config/editorOptions.js
var EditorAutoIndentStrategy;
(function(EditorAutoIndentStrategy3) {
  EditorAutoIndentStrategy3[EditorAutoIndentStrategy3["None"] = 0] = "None";
  EditorAutoIndentStrategy3[EditorAutoIndentStrategy3["Keep"] = 1] = "Keep";
  EditorAutoIndentStrategy3[EditorAutoIndentStrategy3["Brackets"] = 2] = "Brackets";
  EditorAutoIndentStrategy3[EditorAutoIndentStrategy3["Advanced"] = 3] = "Advanced";
  EditorAutoIndentStrategy3[EditorAutoIndentStrategy3["Full"] = 4] = "Full";
})(EditorAutoIndentStrategy || (EditorAutoIndentStrategy = {}));
var MINIMAP_GUTTER_WIDTH = 8;
var ConfigurationChangedEvent = class {
  /**
   * @internal
   */
  constructor(values) {
    this.c = values;
  }
  hasChanged(id2) {
    return this.c[id2];
  }
};
var ComputeOptionsMemory = class {
  constructor() {
    this.stableMinimapLayoutInput = null;
    this.stableFitMaxMinimapScale = 0;
    this.stableFitRemainingWidth = 0;
  }
};
var BaseEditorOption = class {
  constructor(id2, name, defaultValue, schema9) {
    this.id = id2;
    this.name = name;
    this.defaultValue = defaultValue;
    this.schema = schema9;
  }
  applyUpdate(value, update) {
    return applyUpdate(value, update);
  }
  compute(env3, options3, value) {
    return value;
  }
};
var ApplyUpdateResult = class {
  constructor(newValue, didChange) {
    this.newValue = newValue;
    this.didChange = didChange;
  }
};
function applyUpdate(value, update) {
  if (typeof value !== "object" || typeof update !== "object" || !value || !update) {
    return new ApplyUpdateResult(update, value !== update);
  }
  if (Array.isArray(value) || Array.isArray(update)) {
    const arrayEquals = Array.isArray(value) && Array.isArray(update) && $zb(value, update);
    return new ApplyUpdateResult(update, !arrayEquals);
  }
  let didChange = false;
  for (const key2 in update) {
    if (update.hasOwnProperty(key2)) {
      const result = applyUpdate(value[key2], update[key2]);
      if (result.didChange) {
        value[key2] = result.newValue;
        didChange = true;
      }
    }
  }
  return new ApplyUpdateResult(value, didChange);
}
var ComputedEditorOption = class {
  constructor(id2) {
    this.schema = void 0;
    this.id = id2;
    this.name = "_never_";
    this.defaultValue = void 0;
  }
  applyUpdate(value, update) {
    return applyUpdate(value, update);
  }
  validate(input) {
    return this.defaultValue;
  }
};
var SimpleEditorOption = class {
  constructor(id2, name, defaultValue, schema9) {
    this.id = id2;
    this.name = name;
    this.defaultValue = defaultValue;
    this.schema = schema9;
  }
  applyUpdate(value, update) {
    return applyUpdate(value, update);
  }
  validate(input) {
    if (typeof input === "undefined") {
      return this.defaultValue;
    }
    return input;
  }
  compute(env3, options3, value) {
    return value;
  }
};
function boolean(value, defaultValue) {
  if (typeof value === "undefined") {
    return defaultValue;
  }
  if (value === "false") {
    return false;
  }
  return Boolean(value);
}
var EditorBooleanOption = class extends SimpleEditorOption {
  constructor(id2, name, defaultValue, schema9 = void 0) {
    if (typeof schema9 !== "undefined") {
      schema9.type = "boolean";
      schema9.default = defaultValue;
    }
    super(id2, name, defaultValue, schema9);
  }
  validate(input) {
    return boolean(input, this.defaultValue);
  }
};
function clampedInt(value, defaultValue, minimum, maximum) {
  if (typeof value === "undefined") {
    return defaultValue;
  }
  let r2 = parseInt(value, 10);
  if (isNaN(r2)) {
    return defaultValue;
  }
  r2 = Math.max(minimum, r2);
  r2 = Math.min(maximum, r2);
  return r2 | 0;
}
var EditorIntOption = class _EditorIntOption extends SimpleEditorOption {
  static clampedInt(value, defaultValue, minimum, maximum) {
    return clampedInt(value, defaultValue, minimum, maximum);
  }
  constructor(id2, name, defaultValue, minimum, maximum, schema9 = void 0) {
    if (typeof schema9 !== "undefined") {
      schema9.type = "integer";
      schema9.default = defaultValue;
      schema9.minimum = minimum;
      schema9.maximum = maximum;
    }
    super(id2, name, defaultValue, schema9);
    this.minimum = minimum;
    this.maximum = maximum;
  }
  validate(input) {
    return _EditorIntOption.clampedInt(input, this.defaultValue, this.minimum, this.maximum);
  }
};
function clampedFloat(value, defaultValue, minimum, maximum) {
  if (typeof value === "undefined") {
    return defaultValue;
  }
  const r2 = EditorFloatOption.float(value, defaultValue);
  return EditorFloatOption.clamp(r2, minimum, maximum);
}
var EditorFloatOption = class _EditorFloatOption extends SimpleEditorOption {
  static clamp(n, min, max) {
    if (n < min) {
      return min;
    }
    if (n > max) {
      return max;
    }
    return n;
  }
  static float(value, defaultValue) {
    if (typeof value === "number") {
      return value;
    }
    if (typeof value === "undefined") {
      return defaultValue;
    }
    const r2 = parseFloat(value);
    return isNaN(r2) ? defaultValue : r2;
  }
  constructor(id2, name, defaultValue, validationFn, schema9) {
    if (typeof schema9 !== "undefined") {
      schema9.type = "number";
      schema9.default = defaultValue;
    }
    super(id2, name, defaultValue, schema9);
    this.validationFn = validationFn;
  }
  validate(input) {
    return this.validationFn(_EditorFloatOption.float(input, this.defaultValue));
  }
};
var EditorStringOption = class _EditorStringOption extends SimpleEditorOption {
  static string(value, defaultValue) {
    if (typeof value !== "string") {
      return defaultValue;
    }
    return value;
  }
  constructor(id2, name, defaultValue, schema9 = void 0) {
    if (typeof schema9 !== "undefined") {
      schema9.type = "string";
      schema9.default = defaultValue;
    }
    super(id2, name, defaultValue, schema9);
  }
  validate(input) {
    return _EditorStringOption.string(input, this.defaultValue);
  }
};
function stringSet(value, defaultValue, allowedValues, renamedValues) {
  if (typeof value !== "string") {
    return defaultValue;
  }
  if (renamedValues && value in renamedValues) {
    return renamedValues[value];
  }
  if (allowedValues.indexOf(value) === -1) {
    return defaultValue;
  }
  return value;
}
var EditorStringEnumOption = class extends SimpleEditorOption {
  constructor(id2, name, defaultValue, allowedValues, schema9 = void 0) {
    if (typeof schema9 !== "undefined") {
      schema9.type = "string";
      schema9.enum = allowedValues;
      schema9.default = defaultValue;
    }
    super(id2, name, defaultValue, schema9);
    this.c = allowedValues;
  }
  validate(input) {
    return stringSet(input, this.defaultValue, this.c);
  }
};
var EditorEnumOption = class extends BaseEditorOption {
  constructor(id2, name, defaultValue, defaultStringValue, allowedValues, convert, schema9 = void 0) {
    if (typeof schema9 !== "undefined") {
      schema9.type = "string";
      schema9.enum = allowedValues;
      schema9.default = defaultStringValue;
    }
    super(id2, name, defaultValue, schema9);
    this.c = allowedValues;
    this.d = convert;
  }
  validate(input) {
    if (typeof input !== "string") {
      return this.defaultValue;
    }
    if (this.c.indexOf(input) === -1) {
      return this.defaultValue;
    }
    return this.d(input);
  }
};
function _autoIndentFromString(autoIndent) {
  switch (autoIndent) {
    case "none":
      return 0;
    case "keep":
      return 1;
    case "brackets":
      return 2;
    case "advanced":
      return 3;
    case "full":
      return 4;
  }
}
var EditorAccessibilitySupport = class extends BaseEditorOption {
  constructor() {
    super(2, "accessibilitySupport", 0, {
      type: "string",
      enum: ["auto", "on", "off"],
      enumDescriptions: [
        localize(309, null),
        localize(310, null),
        localize(311, null)
      ],
      default: "auto",
      tags: ["accessibility"],
      description: localize(312, null)
    });
  }
  validate(input) {
    switch (input) {
      case "auto":
        return 0;
      case "off":
        return 1;
      case "on":
        return 2;
    }
    return this.defaultValue;
  }
  compute(env3, options3, value) {
    if (value === 0) {
      return env3.accessibilitySupport;
    }
    return value;
  }
};
var EditorComments = class extends BaseEditorOption {
  constructor() {
    const defaults = {
      insertSpace: true,
      ignoreEmptyLines: true
    };
    super(23, "comments", defaults, {
      "editor.comments.insertSpace": {
        type: "boolean",
        default: defaults.insertSpace,
        description: localize(313, null)
      },
      "editor.comments.ignoreEmptyLines": {
        type: "boolean",
        default: defaults.ignoreEmptyLines,
        description: localize(314, null)
      }
    });
  }
  validate(_input) {
    if (!_input || typeof _input !== "object") {
      return this.defaultValue;
    }
    const input = _input;
    return {
      insertSpace: boolean(input.insertSpace, this.defaultValue.insertSpace),
      ignoreEmptyLines: boolean(input.ignoreEmptyLines, this.defaultValue.ignoreEmptyLines)
    };
  }
};
var TextEditorCursorBlinkingStyle;
(function(TextEditorCursorBlinkingStyle3) {
  TextEditorCursorBlinkingStyle3[TextEditorCursorBlinkingStyle3["Hidden"] = 0] = "Hidden";
  TextEditorCursorBlinkingStyle3[TextEditorCursorBlinkingStyle3["Blink"] = 1] = "Blink";
  TextEditorCursorBlinkingStyle3[TextEditorCursorBlinkingStyle3["Smooth"] = 2] = "Smooth";
  TextEditorCursorBlinkingStyle3[TextEditorCursorBlinkingStyle3["Phase"] = 3] = "Phase";
  TextEditorCursorBlinkingStyle3[TextEditorCursorBlinkingStyle3["Expand"] = 4] = "Expand";
  TextEditorCursorBlinkingStyle3[TextEditorCursorBlinkingStyle3["Solid"] = 5] = "Solid";
})(TextEditorCursorBlinkingStyle || (TextEditorCursorBlinkingStyle = {}));
function cursorBlinkingStyleFromString(cursorBlinkingStyle) {
  switch (cursorBlinkingStyle) {
    case "blink":
      return 1;
    case "smooth":
      return 2;
    case "phase":
      return 3;
    case "expand":
      return 4;
    case "solid":
      return 5;
  }
}
var TextEditorCursorStyle;
(function(TextEditorCursorStyle3) {
  TextEditorCursorStyle3[TextEditorCursorStyle3["Line"] = 1] = "Line";
  TextEditorCursorStyle3[TextEditorCursorStyle3["Block"] = 2] = "Block";
  TextEditorCursorStyle3[TextEditorCursorStyle3["Underline"] = 3] = "Underline";
  TextEditorCursorStyle3[TextEditorCursorStyle3["LineThin"] = 4] = "LineThin";
  TextEditorCursorStyle3[TextEditorCursorStyle3["BlockOutline"] = 5] = "BlockOutline";
  TextEditorCursorStyle3[TextEditorCursorStyle3["UnderlineThin"] = 6] = "UnderlineThin";
})(TextEditorCursorStyle || (TextEditorCursorStyle = {}));
function cursorStyleToString(cursorStyle) {
  switch (cursorStyle) {
    case TextEditorCursorStyle.Line:
      return "line";
    case TextEditorCursorStyle.Block:
      return "block";
    case TextEditorCursorStyle.Underline:
      return "underline";
    case TextEditorCursorStyle.LineThin:
      return "line-thin";
    case TextEditorCursorStyle.BlockOutline:
      return "block-outline";
    case TextEditorCursorStyle.UnderlineThin:
      return "underline-thin";
  }
}
function cursorStyleFromString(cursorStyle) {
  switch (cursorStyle) {
    case "line":
      return TextEditorCursorStyle.Line;
    case "block":
      return TextEditorCursorStyle.Block;
    case "underline":
      return TextEditorCursorStyle.Underline;
    case "line-thin":
      return TextEditorCursorStyle.LineThin;
    case "block-outline":
      return TextEditorCursorStyle.BlockOutline;
    case "underline-thin":
      return TextEditorCursorStyle.UnderlineThin;
  }
}
var EditorClassName = class extends ComputedEditorOption {
  constructor() {
    super(
      148
      /* EditorOption.editorClassName */
    );
  }
  compute(env3, options3, _) {
    const classNames = ["monaco-editor"];
    if (options3.get(
      41
      /* EditorOption.extraEditorClassName */
    )) {
      classNames.push(options3.get(
        41
        /* EditorOption.extraEditorClassName */
      ));
    }
    if (env3.extraEditorClassName) {
      classNames.push(env3.extraEditorClassName);
    }
    if (options3.get(
      75
      /* EditorOption.mouseStyle */
    ) === "default") {
      classNames.push("mouse-default");
    } else if (options3.get(
      75
      /* EditorOption.mouseStyle */
    ) === "copy") {
      classNames.push("mouse-copy");
    }
    if (options3.get(
      116
      /* EditorOption.showUnused */
    )) {
      classNames.push("showUnused");
    }
    if (options3.get(
      145
      /* EditorOption.showDeprecated */
    )) {
      classNames.push("showDeprecated");
    }
    return classNames.join(" ");
  }
};
var EditorEmptySelectionClipboard = class extends EditorBooleanOption {
  constructor() {
    super(38, "emptySelectionClipboard", true, { description: localize(315, null) });
  }
  compute(env3, options3, value) {
    return value && env3.emptySelectionClipboard;
  }
};
var EditorFind = class extends BaseEditorOption {
  constructor() {
    const defaults = {
      cursorMoveOnType: true,
      seedSearchStringFromSelection: "always",
      autoFindInSelection: "never",
      globalFindClipboard: false,
      addExtraSpaceOnTop: true,
      loop: true,
      history: "workspace"
    };
    super(43, "find", defaults, {
      "editor.find.cursorMoveOnType": {
        type: "boolean",
        default: defaults.cursorMoveOnType,
        description: localize(316, null)
      },
      "editor.find.seedSearchStringFromSelection": {
        type: "string",
        enum: ["never", "always", "selection"],
        default: defaults.seedSearchStringFromSelection,
        enumDescriptions: [
          localize(317, null),
          localize(318, null),
          localize(319, null)
        ],
        description: localize(320, null)
      },
      "editor.find.autoFindInSelection": {
        type: "string",
        enum: ["never", "always", "multiline"],
        default: defaults.autoFindInSelection,
        enumDescriptions: [
          localize(321, null),
          localize(322, null),
          localize(323, null)
        ],
        description: localize(324, null)
      },
      "editor.find.globalFindClipboard": {
        type: "boolean",
        default: defaults.globalFindClipboard,
        description: localize(325, null),
        included: $m
      },
      "editor.find.addExtraSpaceOnTop": {
        type: "boolean",
        default: defaults.addExtraSpaceOnTop,
        description: localize(326, null)
      },
      "editor.find.loop": {
        type: "boolean",
        default: defaults.loop,
        description: localize(327, null)
      },
      "editor.find.history": {
        type: "string",
        enum: ["never", "workspace"],
        default: "workspace",
        enumDescriptions: [
          localize(328, null),
          localize(329, null)
        ],
        description: localize(330, null)
      }
    });
  }
  validate(_input) {
    if (!_input || typeof _input !== "object") {
      return this.defaultValue;
    }
    const input = _input;
    return {
      cursorMoveOnType: boolean(input.cursorMoveOnType, this.defaultValue.cursorMoveOnType),
      seedSearchStringFromSelection: typeof _input.seedSearchStringFromSelection === "boolean" ? _input.seedSearchStringFromSelection ? "always" : "never" : stringSet(input.seedSearchStringFromSelection, this.defaultValue.seedSearchStringFromSelection, ["never", "always", "selection"]),
      autoFindInSelection: typeof _input.autoFindInSelection === "boolean" ? _input.autoFindInSelection ? "always" : "never" : stringSet(input.autoFindInSelection, this.defaultValue.autoFindInSelection, ["never", "always", "multiline"]),
      globalFindClipboard: boolean(input.globalFindClipboard, this.defaultValue.globalFindClipboard),
      addExtraSpaceOnTop: boolean(input.addExtraSpaceOnTop, this.defaultValue.addExtraSpaceOnTop),
      loop: boolean(input.loop, this.defaultValue.loop),
      history: stringSet(input.history, this.defaultValue.history, ["never", "workspace"])
    };
  }
};
var EditorFontLigatures = class _EditorFontLigatures extends BaseEditorOption {
  static {
    this.OFF = '"liga" off, "calt" off';
  }
  static {
    this.ON = '"liga" on, "calt" on';
  }
  constructor() {
    super(53, "fontLigatures", _EditorFontLigatures.OFF, {
      anyOf: [
        {
          type: "boolean",
          description: localize(331, null)
        },
        {
          type: "string",
          description: localize(332, null)
        }
      ],
      description: localize(333, null),
      default: false
    });
  }
  validate(input) {
    if (typeof input === "undefined") {
      return this.defaultValue;
    }
    if (typeof input === "string") {
      if (input === "false" || input.length === 0) {
        return _EditorFontLigatures.OFF;
      }
      if (input === "true") {
        return _EditorFontLigatures.ON;
      }
      return input;
    }
    if (Boolean(input)) {
      return _EditorFontLigatures.ON;
    }
    return _EditorFontLigatures.OFF;
  }
};
var EditorFontVariations = class _EditorFontVariations extends BaseEditorOption {
  static {
    this.OFF = "normal";
  }
  static {
    this.TRANSLATE = "translate";
  }
  constructor() {
    super(56, "fontVariations", _EditorFontVariations.OFF, {
      anyOf: [
        {
          type: "boolean",
          description: localize(334, null)
        },
        {
          type: "string",
          description: localize(335, null)
        }
      ],
      description: localize(336, null),
      default: false
    });
  }
  validate(input) {
    if (typeof input === "undefined") {
      return this.defaultValue;
    }
    if (typeof input === "string") {
      if (input === "false") {
        return _EditorFontVariations.OFF;
      }
      if (input === "true") {
        return _EditorFontVariations.TRANSLATE;
      }
      return input;
    }
    if (Boolean(input)) {
      return _EditorFontVariations.TRANSLATE;
    }
    return _EditorFontVariations.OFF;
  }
  compute(env3, options3, value) {
    return env3.fontInfo.fontVariationSettings;
  }
};
var EditorFontInfo = class extends ComputedEditorOption {
  constructor() {
    super(
      52
      /* EditorOption.fontInfo */
    );
  }
  compute(env3, options3, _) {
    return env3.fontInfo;
  }
};
var EffectiveCursorStyle = class extends ComputedEditorOption {
  constructor() {
    super(
      147
      /* EditorOption.effectiveCursorStyle */
    );
  }
  compute(env3, options3, _) {
    return env3.inputMode === "overtype" ? options3.get(
      84
      /* EditorOption.overtypeCursorStyle */
    ) : options3.get(
      28
      /* EditorOption.cursorStyle */
    );
  }
};
var EditorFontSize = class extends SimpleEditorOption {
  constructor() {
    super(54, "fontSize", EDITOR_FONT_DEFAULTS.fontSize, {
      type: "number",
      minimum: 6,
      maximum: 100,
      default: EDITOR_FONT_DEFAULTS.fontSize,
      description: localize(337, null)
    });
  }
  validate(input) {
    const r2 = EditorFloatOption.float(input, this.defaultValue);
    if (r2 === 0) {
      return EDITOR_FONT_DEFAULTS.fontSize;
    }
    return EditorFloatOption.clamp(r2, 6, 100);
  }
  compute(env3, options3, value) {
    return env3.fontInfo.fontSize;
  }
};
var EditorFontWeight = class _EditorFontWeight extends BaseEditorOption {
  static {
    this.c = ["normal", "bold", "100", "200", "300", "400", "500", "600", "700", "800", "900"];
  }
  static {
    this.d = 1;
  }
  static {
    this.e = 1e3;
  }
  constructor() {
    super(55, "fontWeight", EDITOR_FONT_DEFAULTS.fontWeight, {
      anyOf: [
        {
          type: "number",
          minimum: _EditorFontWeight.d,
          maximum: _EditorFontWeight.e,
          errorMessage: localize(338, null)
        },
        {
          type: "string",
          pattern: "^(normal|bold|1000|[1-9][0-9]{0,2})$"
        },
        {
          enum: _EditorFontWeight.c
        }
      ],
      default: EDITOR_FONT_DEFAULTS.fontWeight,
      description: localize(339, null)
    });
  }
  validate(input) {
    if (input === "normal" || input === "bold") {
      return input;
    }
    return String(EditorIntOption.clampedInt(input, EDITOR_FONT_DEFAULTS.fontWeight, _EditorFontWeight.d, _EditorFontWeight.e));
  }
};
var EditorGoToLocation = class extends BaseEditorOption {
  constructor() {
    const defaults = {
      multiple: "peek",
      multipleDefinitions: "peek",
      multipleTypeDefinitions: "peek",
      multipleDeclarations: "peek",
      multipleImplementations: "peek",
      multipleReferences: "peek",
      multipleTests: "peek",
      alternativeDefinitionCommand: "editor.action.goToReferences",
      alternativeTypeDefinitionCommand: "editor.action.goToReferences",
      alternativeDeclarationCommand: "editor.action.goToReferences",
      alternativeImplementationCommand: "",
      alternativeReferenceCommand: "",
      alternativeTestsCommand: ""
    };
    const jsonSubset = {
      type: "string",
      enum: ["peek", "gotoAndPeek", "goto"],
      default: defaults.multiple,
      enumDescriptions: [
        localize(340, null),
        localize(341, null),
        localize(342, null)
      ]
    };
    const alternativeCommandOptions = ["", "editor.action.referenceSearch.trigger", "editor.action.goToReferences", "editor.action.peekImplementation", "editor.action.goToImplementation", "editor.action.peekTypeDefinition", "editor.action.goToTypeDefinition", "editor.action.peekDeclaration", "editor.action.revealDeclaration", "editor.action.peekDefinition", "editor.action.revealDefinitionAside", "editor.action.revealDefinition"];
    super(60, "gotoLocation", defaults, {
      "editor.gotoLocation.multiple": {
        deprecationMessage: localize(343, null)
      },
      "editor.gotoLocation.multipleDefinitions": {
        description: localize(344, null),
        ...jsonSubset
      },
      "editor.gotoLocation.multipleTypeDefinitions": {
        description: localize(345, null),
        ...jsonSubset
      },
      "editor.gotoLocation.multipleDeclarations": {
        description: localize(346, null),
        ...jsonSubset
      },
      "editor.gotoLocation.multipleImplementations": {
        description: localize(347, null),
        ...jsonSubset
      },
      "editor.gotoLocation.multipleReferences": {
        description: localize(348, null),
        ...jsonSubset
      },
      "editor.gotoLocation.alternativeDefinitionCommand": {
        type: "string",
        default: defaults.alternativeDefinitionCommand,
        enum: alternativeCommandOptions,
        description: localize(349, null)
      },
      "editor.gotoLocation.alternativeTypeDefinitionCommand": {
        type: "string",
        default: defaults.alternativeTypeDefinitionCommand,
        enum: alternativeCommandOptions,
        description: localize(350, null)
      },
      "editor.gotoLocation.alternativeDeclarationCommand": {
        type: "string",
        default: defaults.alternativeDeclarationCommand,
        enum: alternativeCommandOptions,
        description: localize(351, null)
      },
      "editor.gotoLocation.alternativeImplementationCommand": {
        type: "string",
        default: defaults.alternativeImplementationCommand,
        enum: alternativeCommandOptions,
        description: localize(352, null)
      },
      "editor.gotoLocation.alternativeReferenceCommand": {
        type: "string",
        default: defaults.alternativeReferenceCommand,
        enum: alternativeCommandOptions,
        description: localize(353, null)
      }
    });
  }
  validate(_input) {
    if (!_input || typeof _input !== "object") {
      return this.defaultValue;
    }
    const input = _input;
    return {
      multiple: stringSet(input.multiple, this.defaultValue.multiple, ["peek", "gotoAndPeek", "goto"]),
      multipleDefinitions: input.multipleDefinitions ?? stringSet(input.multipleDefinitions, "peek", ["peek", "gotoAndPeek", "goto"]),
      multipleTypeDefinitions: input.multipleTypeDefinitions ?? stringSet(input.multipleTypeDefinitions, "peek", ["peek", "gotoAndPeek", "goto"]),
      multipleDeclarations: input.multipleDeclarations ?? stringSet(input.multipleDeclarations, "peek", ["peek", "gotoAndPeek", "goto"]),
      multipleImplementations: input.multipleImplementations ?? stringSet(input.multipleImplementations, "peek", ["peek", "gotoAndPeek", "goto"]),
      multipleReferences: input.multipleReferences ?? stringSet(input.multipleReferences, "peek", ["peek", "gotoAndPeek", "goto"]),
      multipleTests: input.multipleTests ?? stringSet(input.multipleTests, "peek", ["peek", "gotoAndPeek", "goto"]),
      alternativeDefinitionCommand: EditorStringOption.string(input.alternativeDefinitionCommand, this.defaultValue.alternativeDefinitionCommand),
      alternativeTypeDefinitionCommand: EditorStringOption.string(input.alternativeTypeDefinitionCommand, this.defaultValue.alternativeTypeDefinitionCommand),
      alternativeDeclarationCommand: EditorStringOption.string(input.alternativeDeclarationCommand, this.defaultValue.alternativeDeclarationCommand),
      alternativeImplementationCommand: EditorStringOption.string(input.alternativeImplementationCommand, this.defaultValue.alternativeImplementationCommand),
      alternativeReferenceCommand: EditorStringOption.string(input.alternativeReferenceCommand, this.defaultValue.alternativeReferenceCommand),
      alternativeTestsCommand: EditorStringOption.string(input.alternativeTestsCommand, this.defaultValue.alternativeTestsCommand)
    };
  }
};
var EditorHover = class extends BaseEditorOption {
  constructor() {
    const defaults = {
      enabled: true,
      delay: 300,
      hidingDelay: 300,
      sticky: true,
      above: true
    };
    super(62, "hover", defaults, {
      "editor.hover.enabled": {
        type: "boolean",
        default: defaults.enabled,
        description: localize(354, null)
      },
      "editor.hover.delay": {
        type: "number",
        default: defaults.delay,
        minimum: 0,
        maximum: 1e4,
        description: localize(355, null)
      },
      "editor.hover.sticky": {
        type: "boolean",
        default: defaults.sticky,
        description: localize(356, null)
      },
      "editor.hover.hidingDelay": {
        type: "integer",
        minimum: 0,
        default: defaults.hidingDelay,
        description: localize(357, null)
      },
      "editor.hover.above": {
        type: "boolean",
        default: defaults.above,
        description: localize(358, null)
      }
    });
  }
  validate(_input) {
    if (!_input || typeof _input !== "object") {
      return this.defaultValue;
    }
    const input = _input;
    return {
      enabled: boolean(input.enabled, this.defaultValue.enabled),
      delay: EditorIntOption.clampedInt(input.delay, this.defaultValue.delay, 0, 1e4),
      sticky: boolean(input.sticky, this.defaultValue.sticky),
      hidingDelay: EditorIntOption.clampedInt(input.hidingDelay, this.defaultValue.hidingDelay, 0, 6e5),
      above: boolean(input.above, this.defaultValue.above)
    };
  }
};
var RenderMinimap;
(function(RenderMinimap3) {
  RenderMinimap3[RenderMinimap3["None"] = 0] = "None";
  RenderMinimap3[RenderMinimap3["Text"] = 1] = "Text";
  RenderMinimap3[RenderMinimap3["Blocks"] = 2] = "Blocks";
})(RenderMinimap || (RenderMinimap = {}));
var EditorLayoutInfoComputer = class _EditorLayoutInfoComputer extends ComputedEditorOption {
  constructor() {
    super(
      151
      /* EditorOption.layoutInfo */
    );
  }
  compute(env3, options3, _) {
    return _EditorLayoutInfoComputer.computeLayout(options3, {
      memory: env3.memory,
      outerWidth: env3.outerWidth,
      outerHeight: env3.outerHeight,
      isDominatedByLongLines: env3.isDominatedByLongLines,
      lineHeight: env3.fontInfo.lineHeight,
      viewLineCount: env3.viewLineCount,
      lineNumbersDigitCount: env3.lineNumbersDigitCount,
      typicalHalfwidthCharacterWidth: env3.fontInfo.typicalHalfwidthCharacterWidth,
      maxDigitWidth: env3.fontInfo.maxDigitWidth,
      pixelRatio: env3.pixelRatio,
      glyphMarginDecorationLaneCount: env3.glyphMarginDecorationLaneCount
    });
  }
  static computeContainedMinimapLineCount(input) {
    const typicalViewportLineCount = input.height / input.lineHeight;
    const extraLinesBeforeFirstLine = Math.floor(input.paddingTop / input.lineHeight);
    let extraLinesBeyondLastLine = Math.floor(input.paddingBottom / input.lineHeight);
    if (input.scrollBeyondLastLine) {
      extraLinesBeyondLastLine = Math.max(extraLinesBeyondLastLine, typicalViewportLineCount - 1);
    }
    const desiredRatio = (extraLinesBeforeFirstLine + input.viewLineCount + extraLinesBeyondLastLine) / (input.pixelRatio * input.height);
    const minimapLineCount = Math.floor(input.viewLineCount / desiredRatio);
    return { typicalViewportLineCount, extraLinesBeforeFirstLine, extraLinesBeyondLastLine, desiredRatio, minimapLineCount };
  }
  static c(input, memory) {
    const outerWidth = input.outerWidth;
    const outerHeight = input.outerHeight;
    const pixelRatio = input.pixelRatio;
    if (!input.minimap.enabled) {
      return {
        renderMinimap: 0,
        minimapLeft: 0,
        minimapWidth: 0,
        minimapHeightIsEditorHeight: false,
        minimapIsSampling: false,
        minimapScale: 1,
        minimapLineHeight: 1,
        minimapCanvasInnerWidth: 0,
        minimapCanvasInnerHeight: Math.floor(pixelRatio * outerHeight),
        minimapCanvasOuterWidth: 0,
        minimapCanvasOuterHeight: outerHeight
      };
    }
    const stableMinimapLayoutInput = memory.stableMinimapLayoutInput;
    const couldUseMemory = stableMinimapLayoutInput && input.outerHeight === stableMinimapLayoutInput.outerHeight && input.lineHeight === stableMinimapLayoutInput.lineHeight && input.typicalHalfwidthCharacterWidth === stableMinimapLayoutInput.typicalHalfwidthCharacterWidth && input.pixelRatio === stableMinimapLayoutInput.pixelRatio && input.scrollBeyondLastLine === stableMinimapLayoutInput.scrollBeyondLastLine && input.paddingTop === stableMinimapLayoutInput.paddingTop && input.paddingBottom === stableMinimapLayoutInput.paddingBottom && input.minimap.enabled === stableMinimapLayoutInput.minimap.enabled && input.minimap.side === stableMinimapLayoutInput.minimap.side && input.minimap.size === stableMinimapLayoutInput.minimap.size && input.minimap.showSlider === stableMinimapLayoutInput.minimap.showSlider && input.minimap.renderCharacters === stableMinimapLayoutInput.minimap.renderCharacters && input.minimap.maxColumn === stableMinimapLayoutInput.minimap.maxColumn && input.minimap.scale === stableMinimapLayoutInput.minimap.scale && input.verticalScrollbarWidth === stableMinimapLayoutInput.verticalScrollbarWidth && input.isViewportWrapping === stableMinimapLayoutInput.isViewportWrapping;
    const lineHeight = input.lineHeight;
    const typicalHalfwidthCharacterWidth = input.typicalHalfwidthCharacterWidth;
    const scrollBeyondLastLine = input.scrollBeyondLastLine;
    const minimapRenderCharacters = input.minimap.renderCharacters;
    let minimapScale = pixelRatio >= 2 ? Math.round(input.minimap.scale * 2) : input.minimap.scale;
    const minimapMaxColumn = input.minimap.maxColumn;
    const minimapSize = input.minimap.size;
    const minimapSide = input.minimap.side;
    const verticalScrollbarWidth = input.verticalScrollbarWidth;
    const viewLineCount = input.viewLineCount;
    const remainingWidth = input.remainingWidth;
    const isViewportWrapping = input.isViewportWrapping;
    const baseCharHeight = minimapRenderCharacters ? 2 : 3;
    let minimapCanvasInnerHeight = Math.floor(pixelRatio * outerHeight);
    const minimapCanvasOuterHeight = minimapCanvasInnerHeight / pixelRatio;
    let minimapHeightIsEditorHeight = false;
    let minimapIsSampling = false;
    let minimapLineHeight = baseCharHeight * minimapScale;
    let minimapCharWidth = minimapScale / pixelRatio;
    let minimapWidthMultiplier = 1;
    if (minimapSize === "fill" || minimapSize === "fit") {
      const { typicalViewportLineCount, extraLinesBeforeFirstLine, extraLinesBeyondLastLine, desiredRatio, minimapLineCount } = _EditorLayoutInfoComputer.computeContainedMinimapLineCount({
        viewLineCount,
        scrollBeyondLastLine,
        paddingTop: input.paddingTop,
        paddingBottom: input.paddingBottom,
        height: outerHeight,
        lineHeight,
        pixelRatio
      });
      const ratio = viewLineCount / minimapLineCount;
      if (ratio > 1) {
        minimapHeightIsEditorHeight = true;
        minimapIsSampling = true;
        minimapScale = 1;
        minimapLineHeight = 1;
        minimapCharWidth = minimapScale / pixelRatio;
      } else {
        let fitBecomesFill = false;
        let maxMinimapScale = minimapScale + 1;
        if (minimapSize === "fit") {
          const effectiveMinimapHeight = Math.ceil((extraLinesBeforeFirstLine + viewLineCount + extraLinesBeyondLastLine) * minimapLineHeight);
          if (isViewportWrapping && couldUseMemory && remainingWidth <= memory.stableFitRemainingWidth) {
            fitBecomesFill = true;
            maxMinimapScale = memory.stableFitMaxMinimapScale;
          } else {
            fitBecomesFill = effectiveMinimapHeight > minimapCanvasInnerHeight;
          }
        }
        if (minimapSize === "fill" || fitBecomesFill) {
          minimapHeightIsEditorHeight = true;
          const configuredMinimapScale = minimapScale;
          minimapLineHeight = Math.min(lineHeight * pixelRatio, Math.max(1, Math.floor(1 / desiredRatio)));
          if (isViewportWrapping && couldUseMemory && remainingWidth <= memory.stableFitRemainingWidth) {
            maxMinimapScale = memory.stableFitMaxMinimapScale;
          }
          minimapScale = Math.min(maxMinimapScale, Math.max(1, Math.floor(minimapLineHeight / baseCharHeight)));
          if (minimapScale > configuredMinimapScale) {
            minimapWidthMultiplier = Math.min(2, minimapScale / configuredMinimapScale);
          }
          minimapCharWidth = minimapScale / pixelRatio / minimapWidthMultiplier;
          minimapCanvasInnerHeight = Math.ceil(Math.max(typicalViewportLineCount, extraLinesBeforeFirstLine + viewLineCount + extraLinesBeyondLastLine) * minimapLineHeight);
          if (isViewportWrapping) {
            memory.stableMinimapLayoutInput = input;
            memory.stableFitRemainingWidth = remainingWidth;
            memory.stableFitMaxMinimapScale = minimapScale;
          } else {
            memory.stableMinimapLayoutInput = null;
            memory.stableFitRemainingWidth = 0;
          }
        }
      }
    }
    const minimapMaxWidth = Math.floor(minimapMaxColumn * minimapCharWidth);
    const minimapWidth = Math.min(minimapMaxWidth, Math.max(0, Math.floor((remainingWidth - verticalScrollbarWidth - 2) * minimapCharWidth / (typicalHalfwidthCharacterWidth + minimapCharWidth))) + MINIMAP_GUTTER_WIDTH);
    let minimapCanvasInnerWidth = Math.floor(pixelRatio * minimapWidth);
    const minimapCanvasOuterWidth = minimapCanvasInnerWidth / pixelRatio;
    minimapCanvasInnerWidth = Math.floor(minimapCanvasInnerWidth * minimapWidthMultiplier);
    const renderMinimap = minimapRenderCharacters ? 1 : 2;
    const minimapLeft = minimapSide === "left" ? 0 : outerWidth - minimapWidth - verticalScrollbarWidth;
    return {
      renderMinimap,
      minimapLeft,
      minimapWidth,
      minimapHeightIsEditorHeight,
      minimapIsSampling,
      minimapScale,
      minimapLineHeight,
      minimapCanvasInnerWidth,
      minimapCanvasInnerHeight,
      minimapCanvasOuterWidth,
      minimapCanvasOuterHeight
    };
  }
  static computeLayout(options3, env3) {
    const outerWidth = env3.outerWidth | 0;
    const outerHeight = env3.outerHeight | 0;
    const lineHeight = env3.lineHeight | 0;
    const lineNumbersDigitCount = env3.lineNumbersDigitCount | 0;
    const typicalHalfwidthCharacterWidth = env3.typicalHalfwidthCharacterWidth;
    const maxDigitWidth = env3.maxDigitWidth;
    const pixelRatio = env3.pixelRatio;
    const viewLineCount = env3.viewLineCount;
    const wordWrapOverride2 = options3.get(
      142
      /* EditorOption.wordWrapOverride2 */
    );
    const wordWrapOverride1 = wordWrapOverride2 === "inherit" ? options3.get(
      141
      /* EditorOption.wordWrapOverride1 */
    ) : wordWrapOverride2;
    const wordWrap = wordWrapOverride1 === "inherit" ? options3.get(
      137
      /* EditorOption.wordWrap */
    ) : wordWrapOverride1;
    const wordWrapColumn = options3.get(
      140
      /* EditorOption.wordWrapColumn */
    );
    const isDominatedByLongLines = env3.isDominatedByLongLines;
    const showGlyphMargin = options3.get(
      59
      /* EditorOption.glyphMargin */
    );
    const showLineNumbers = options3.get(
      69
      /* EditorOption.lineNumbers */
    ).renderType !== 0;
    const lineNumbersMinChars = options3.get(
      70
      /* EditorOption.lineNumbersMinChars */
    );
    const scrollBeyondLastLine = options3.get(
      110
      /* EditorOption.scrollBeyondLastLine */
    );
    const padding = options3.get(
      88
      /* EditorOption.padding */
    );
    const minimap = options3.get(
      74
      /* EditorOption.minimap */
    );
    const scrollbar = options3.get(
      108
      /* EditorOption.scrollbar */
    );
    const verticalScrollbarWidth = scrollbar.verticalScrollbarSize;
    const verticalScrollbarHasArrows = scrollbar.verticalHasArrows;
    const scrollbarArrowSize = scrollbar.arrowSize;
    const horizontalScrollbarHeight = scrollbar.horizontalScrollbarSize;
    const folding = options3.get(
      45
      /* EditorOption.folding */
    );
    const showFoldingDecoration = options3.get(
      115
      /* EditorOption.showFoldingControls */
    ) !== "never";
    let lineDecorationsWidth = options3.get(
      67
      /* EditorOption.lineDecorationsWidth */
    );
    if (folding && showFoldingDecoration) {
      lineDecorationsWidth += 16;
    }
    let lineNumbersWidth = 0;
    if (showLineNumbers) {
      const digitCount2 = Math.max(lineNumbersDigitCount, lineNumbersMinChars);
      lineNumbersWidth = Math.round(digitCount2 * maxDigitWidth);
    }
    let glyphMarginWidth = 0;
    if (showGlyphMargin) {
      glyphMarginWidth = lineHeight * env3.glyphMarginDecorationLaneCount;
    }
    let glyphMarginLeft = 0;
    let lineNumbersLeft = glyphMarginLeft + glyphMarginWidth;
    let decorationsLeft = lineNumbersLeft + lineNumbersWidth;
    let contentLeft = decorationsLeft + lineDecorationsWidth;
    const remainingWidth = outerWidth - glyphMarginWidth - lineNumbersWidth - lineDecorationsWidth;
    let isWordWrapMinified = false;
    let isViewportWrapping = false;
    let wrappingColumn = -1;
    if (wordWrapOverride1 === "inherit" && isDominatedByLongLines) {
      isWordWrapMinified = true;
      isViewportWrapping = true;
    } else if (wordWrap === "on" || wordWrap === "bounded") {
      isViewportWrapping = true;
    } else if (wordWrap === "wordWrapColumn") {
      wrappingColumn = wordWrapColumn;
    }
    const minimapLayout = _EditorLayoutInfoComputer.c({
      outerWidth,
      outerHeight,
      lineHeight,
      typicalHalfwidthCharacterWidth,
      pixelRatio,
      scrollBeyondLastLine,
      paddingTop: padding.top,
      paddingBottom: padding.bottom,
      minimap,
      verticalScrollbarWidth,
      viewLineCount,
      remainingWidth,
      isViewportWrapping
    }, env3.memory || new ComputeOptionsMemory());
    if (minimapLayout.renderMinimap !== 0 && minimapLayout.minimapLeft === 0) {
      glyphMarginLeft += minimapLayout.minimapWidth;
      lineNumbersLeft += minimapLayout.minimapWidth;
      decorationsLeft += minimapLayout.minimapWidth;
      contentLeft += minimapLayout.minimapWidth;
    }
    const contentWidth = remainingWidth - minimapLayout.minimapWidth;
    const viewportColumn = Math.max(1, Math.floor((contentWidth - verticalScrollbarWidth - 2) / typicalHalfwidthCharacterWidth));
    const verticalArrowSize = verticalScrollbarHasArrows ? scrollbarArrowSize : 0;
    if (isViewportWrapping) {
      wrappingColumn = Math.max(1, viewportColumn);
      if (wordWrap === "bounded") {
        wrappingColumn = Math.min(wrappingColumn, wordWrapColumn);
      }
    }
    return {
      width: outerWidth,
      height: outerHeight,
      glyphMarginLeft,
      glyphMarginWidth,
      glyphMarginDecorationLaneCount: env3.glyphMarginDecorationLaneCount,
      lineNumbersLeft,
      lineNumbersWidth,
      decorationsLeft,
      decorationsWidth: lineDecorationsWidth,
      contentLeft,
      contentWidth,
      minimap: minimapLayout,
      viewportColumn,
      isWordWrapMinified,
      isViewportWrapping,
      wrappingColumn,
      verticalScrollbarWidth,
      horizontalScrollbarHeight,
      overviewRuler: {
        top: verticalArrowSize,
        width: verticalScrollbarWidth,
        height: outerHeight - 2 * verticalArrowSize,
        right: 0
      }
    };
  }
};
var WrappingStrategy = class extends BaseEditorOption {
  constructor() {
    super(144, "wrappingStrategy", "simple", {
      "editor.wrappingStrategy": {
        enumDescriptions: [
          localize(359, null),
          localize(360, null)
        ],
        type: "string",
        enum: ["simple", "advanced"],
        default: "simple",
        description: localize(361, null)
      }
    });
  }
  validate(input) {
    return stringSet(input, "simple", ["simple", "advanced"]);
  }
  compute(env3, options3, value) {
    const accessibilitySupport = options3.get(
      2
      /* EditorOption.accessibilitySupport */
    );
    if (accessibilitySupport === 2) {
      return "advanced";
    }
    return value;
  }
};
var ShowLightbulbIconMode;
(function(ShowLightbulbIconMode3) {
  ShowLightbulbIconMode3["Off"] = "off";
  ShowLightbulbIconMode3["OnCode"] = "onCode";
  ShowLightbulbIconMode3["On"] = "on";
})(ShowLightbulbIconMode || (ShowLightbulbIconMode = {}));
var EditorLightbulb = class extends BaseEditorOption {
  constructor() {
    const defaults = { enabled: ShowLightbulbIconMode.OnCode };
    super(66, "lightbulb", defaults, {
      "editor.lightbulb.enabled": {
        type: "string",
        enum: [ShowLightbulbIconMode.Off, ShowLightbulbIconMode.OnCode, ShowLightbulbIconMode.On],
        default: defaults.enabled,
        enumDescriptions: [
          localize(362, null),
          localize(363, null),
          localize(364, null)
        ],
        description: localize(365, null)
      }
    });
  }
  validate(_input) {
    if (!_input || typeof _input !== "object") {
      return this.defaultValue;
    }
    const input = _input;
    return {
      enabled: stringSet(input.enabled, this.defaultValue.enabled, [ShowLightbulbIconMode.Off, ShowLightbulbIconMode.OnCode, ShowLightbulbIconMode.On])
    };
  }
};
var EditorStickyScroll = class extends BaseEditorOption {
  constructor() {
    const defaults = { enabled: true, maxLineCount: 5, defaultModel: "outlineModel", scrollWithEditor: true };
    super(120, "stickyScroll", defaults, {
      "editor.stickyScroll.enabled": {
        type: "boolean",
        default: defaults.enabled,
        description: localize(366, null)
      },
      "editor.stickyScroll.maxLineCount": {
        type: "number",
        default: defaults.maxLineCount,
        minimum: 1,
        maximum: 20,
        description: localize(367, null)
      },
      "editor.stickyScroll.defaultModel": {
        type: "string",
        enum: ["outlineModel", "foldingProviderModel", "indentationModel"],
        default: defaults.defaultModel,
        description: localize(368, null)
      },
      "editor.stickyScroll.scrollWithEditor": {
        type: "boolean",
        default: defaults.scrollWithEditor,
        description: localize(369, null)
      }
    });
  }
  validate(_input) {
    if (!_input || typeof _input !== "object") {
      return this.defaultValue;
    }
    const input = _input;
    return {
      enabled: boolean(input.enabled, this.defaultValue.enabled),
      maxLineCount: EditorIntOption.clampedInt(input.maxLineCount, this.defaultValue.maxLineCount, 1, 20),
      defaultModel: stringSet(input.defaultModel, this.defaultValue.defaultModel, ["outlineModel", "foldingProviderModel", "indentationModel"]),
      scrollWithEditor: boolean(input.scrollWithEditor, this.defaultValue.scrollWithEditor)
    };
  }
};
var EditorInlayHints = class extends BaseEditorOption {
  constructor() {
    const defaults = { enabled: "on", fontSize: 0, fontFamily: "", padding: false, maximumLength: 43 };
    super(146, "inlayHints", defaults, {
      "editor.inlayHints.enabled": {
        type: "string",
        default: defaults.enabled,
        description: localize(370, null),
        enum: ["on", "onUnlessPressed", "offUnlessPressed", "off"],
        markdownEnumDescriptions: [
          localize(371, null),
          localize(372, null, $m ? `Ctrl+Option` : `Ctrl+Alt`),
          localize(373, null, $m ? `Ctrl+Option` : `Ctrl+Alt`),
          localize(374, null)
        ]
      },
      "editor.inlayHints.fontSize": {
        type: "number",
        default: defaults.fontSize,
        markdownDescription: localize(375, null, "`#editor.fontSize#`", "`5`")
      },
      "editor.inlayHints.fontFamily": {
        type: "string",
        default: defaults.fontFamily,
        markdownDescription: localize(376, null, "`#editor.fontFamily#`")
      },
      "editor.inlayHints.padding": {
        type: "boolean",
        default: defaults.padding,
        description: localize(377, null)
      },
      "editor.inlayHints.maximumLength": {
        type: "number",
        default: defaults.maximumLength,
        markdownDescription: localize(378, null)
      }
    });
  }
  validate(_input) {
    if (!_input || typeof _input !== "object") {
      return this.defaultValue;
    }
    const input = _input;
    if (typeof input.enabled === "boolean") {
      input.enabled = input.enabled ? "on" : "off";
    }
    return {
      enabled: stringSet(input.enabled, this.defaultValue.enabled, ["on", "off", "offUnlessPressed", "onUnlessPressed"]),
      fontSize: EditorIntOption.clampedInt(input.fontSize, this.defaultValue.fontSize, 0, 100),
      fontFamily: EditorStringOption.string(input.fontFamily, this.defaultValue.fontFamily),
      padding: boolean(input.padding, this.defaultValue.padding),
      maximumLength: EditorIntOption.clampedInt(input.maximumLength, this.defaultValue.maximumLength, 0, Number.MAX_SAFE_INTEGER)
    };
  }
};
var EditorLineDecorationsWidth = class extends BaseEditorOption {
  constructor() {
    super(67, "lineDecorationsWidth", 10);
  }
  validate(input) {
    if (typeof input === "string" && /^\d+(\.\d+)?ch$/.test(input)) {
      const multiple = parseFloat(input.substring(0, input.length - 2));
      return -multiple;
    } else {
      return EditorIntOption.clampedInt(input, this.defaultValue, 0, 1e3);
    }
  }
  compute(env3, options3, value) {
    if (value < 0) {
      return EditorIntOption.clampedInt(-value * env3.fontInfo.typicalHalfwidthCharacterWidth, this.defaultValue, 0, 1e3);
    } else {
      return value;
    }
  }
};
var EditorLineHeight = class extends EditorFloatOption {
  constructor() {
    super(68, "lineHeight", EDITOR_FONT_DEFAULTS.lineHeight, (x) => EditorFloatOption.clamp(x, 0, 150), { markdownDescription: localize(379, null) });
  }
  compute(env3, options3, value) {
    return env3.fontInfo.lineHeight;
  }
};
var EditorMinimap = class extends BaseEditorOption {
  constructor() {
    const defaults = {
      enabled: true,
      size: "proportional",
      side: "right",
      showSlider: "mouseover",
      autohide: false,
      renderCharacters: true,
      maxColumn: 120,
      scale: 1,
      showRegionSectionHeaders: true,
      showMarkSectionHeaders: true,
      sectionHeaderFontSize: 9,
      sectionHeaderLetterSpacing: 1
    };
    super(74, "minimap", defaults, {
      "editor.minimap.enabled": {
        type: "boolean",
        default: defaults.enabled,
        description: localize(380, null)
      },
      "editor.minimap.autohide": {
        type: "boolean",
        default: defaults.autohide,
        description: localize(381, null)
      },
      "editor.minimap.size": {
        type: "string",
        enum: ["proportional", "fill", "fit"],
        enumDescriptions: [
          localize(382, null),
          localize(383, null),
          localize(384, null)
        ],
        default: defaults.size,
        description: localize(385, null)
      },
      "editor.minimap.side": {
        type: "string",
        enum: ["left", "right"],
        default: defaults.side,
        description: localize(386, null)
      },
      "editor.minimap.showSlider": {
        type: "string",
        enum: ["always", "mouseover"],
        default: defaults.showSlider,
        description: localize(387, null)
      },
      "editor.minimap.scale": {
        type: "number",
        default: defaults.scale,
        minimum: 1,
        maximum: 3,
        enum: [1, 2, 3],
        description: localize(388, null)
      },
      "editor.minimap.renderCharacters": {
        type: "boolean",
        default: defaults.renderCharacters,
        description: localize(389, null)
      },
      "editor.minimap.maxColumn": {
        type: "number",
        default: defaults.maxColumn,
        description: localize(390, null)
      },
      "editor.minimap.showRegionSectionHeaders": {
        type: "boolean",
        default: defaults.showRegionSectionHeaders,
        description: localize(391, null)
      },
      "editor.minimap.showMarkSectionHeaders": {
        type: "boolean",
        default: defaults.showMarkSectionHeaders,
        description: localize(392, null)
      },
      "editor.minimap.sectionHeaderFontSize": {
        type: "number",
        default: defaults.sectionHeaderFontSize,
        description: localize(393, null)
      },
      "editor.minimap.sectionHeaderLetterSpacing": {
        type: "number",
        default: defaults.sectionHeaderLetterSpacing,
        description: localize(394, null)
      }
    });
  }
  validate(_input) {
    if (!_input || typeof _input !== "object") {
      return this.defaultValue;
    }
    const input = _input;
    return {
      enabled: boolean(input.enabled, this.defaultValue.enabled),
      autohide: boolean(input.autohide, this.defaultValue.autohide),
      size: stringSet(input.size, this.defaultValue.size, ["proportional", "fill", "fit"]),
      side: stringSet(input.side, this.defaultValue.side, ["right", "left"]),
      showSlider: stringSet(input.showSlider, this.defaultValue.showSlider, ["always", "mouseover"]),
      renderCharacters: boolean(input.renderCharacters, this.defaultValue.renderCharacters),
      scale: EditorIntOption.clampedInt(input.scale, 1, 1, 3),
      maxColumn: EditorIntOption.clampedInt(input.maxColumn, this.defaultValue.maxColumn, 1, 1e4),
      showRegionSectionHeaders: boolean(input.showRegionSectionHeaders, this.defaultValue.showRegionSectionHeaders),
      showMarkSectionHeaders: boolean(input.showMarkSectionHeaders, this.defaultValue.showMarkSectionHeaders),
      sectionHeaderFontSize: EditorFloatOption.clamp(input.sectionHeaderFontSize ?? this.defaultValue.sectionHeaderFontSize, 4, 32),
      sectionHeaderLetterSpacing: EditorFloatOption.clamp(input.sectionHeaderLetterSpacing ?? this.defaultValue.sectionHeaderLetterSpacing, 0, 5)
    };
  }
};
function _multiCursorModifierFromString(multiCursorModifier2) {
  if (multiCursorModifier2 === "ctrlCmd") {
    return $m ? "metaKey" : "ctrlKey";
  }
  return "altKey";
}
var EditorPadding = class extends BaseEditorOption {
  constructor() {
    super(88, "padding", { top: 0, bottom: 0 }, {
      "editor.padding.top": {
        type: "number",
        default: 0,
        minimum: 0,
        maximum: 1e3,
        description: localize(395, null)
      },
      "editor.padding.bottom": {
        type: "number",
        default: 0,
        minimum: 0,
        maximum: 1e3,
        description: localize(396, null)
      }
    });
  }
  validate(_input) {
    if (!_input || typeof _input !== "object") {
      return this.defaultValue;
    }
    const input = _input;
    return {
      top: EditorIntOption.clampedInt(input.top, 0, 0, 1e3),
      bottom: EditorIntOption.clampedInt(input.bottom, 0, 0, 1e3)
    };
  }
};
var EditorParameterHints = class extends BaseEditorOption {
  constructor() {
    const defaults = {
      enabled: true,
      cycle: true
    };
    super(90, "parameterHints", defaults, {
      "editor.parameterHints.enabled": {
        type: "boolean",
        default: defaults.enabled,
        description: localize(397, null)
      },
      "editor.parameterHints.cycle": {
        type: "boolean",
        default: defaults.cycle,
        description: localize(398, null)
      }
    });
  }
  validate(_input) {
    if (!_input || typeof _input !== "object") {
      return this.defaultValue;
    }
    const input = _input;
    return {
      enabled: boolean(input.enabled, this.defaultValue.enabled),
      cycle: boolean(input.cycle, this.defaultValue.cycle)
    };
  }
};
var EditorPixelRatio = class extends ComputedEditorOption {
  constructor() {
    super(
      149
      /* EditorOption.pixelRatio */
    );
  }
  compute(env3, options3, _) {
    return env3.pixelRatio;
  }
};
var PlaceholderOption = class extends BaseEditorOption {
  constructor() {
    super(92, "placeholder", void 0);
  }
  validate(input) {
    if (typeof input === "undefined") {
      return this.defaultValue;
    }
    if (typeof input === "string") {
      return input;
    }
    return this.defaultValue;
  }
};
var EditorQuickSuggestions = class extends BaseEditorOption {
  constructor() {
    const defaults = {
      other: "on",
      comments: "off",
      strings: "off"
    };
    const types = [
      { type: "boolean" },
      {
        type: "string",
        enum: ["on", "inline", "off"],
        enumDescriptions: [localize(399, null), localize(400, null), localize(401, null)]
      }
    ];
    super(94, "quickSuggestions", defaults, {
      type: "object",
      additionalProperties: false,
      properties: {
        strings: {
          anyOf: types,
          default: defaults.strings,
          description: localize(402, null)
        },
        comments: {
          anyOf: types,
          default: defaults.comments,
          description: localize(403, null)
        },
        other: {
          anyOf: types,
          default: defaults.other,
          description: localize(404, null)
        }
      },
      default: defaults,
      markdownDescription: localize(405, null, "`#editor.suggestOnTriggerCharacters#`")
    });
    this.defaultValue = defaults;
  }
  validate(input) {
    if (typeof input === "boolean") {
      const value = input ? "on" : "off";
      return { comments: value, strings: value, other: value };
    }
    if (!input || typeof input !== "object") {
      return this.defaultValue;
    }
    const { other, comments, strings } = input;
    const allowedValues = ["on", "inline", "off"];
    let validatedOther;
    let validatedComments;
    let validatedStrings;
    if (typeof other === "boolean") {
      validatedOther = other ? "on" : "off";
    } else {
      validatedOther = stringSet(other, this.defaultValue.other, allowedValues);
    }
    if (typeof comments === "boolean") {
      validatedComments = comments ? "on" : "off";
    } else {
      validatedComments = stringSet(comments, this.defaultValue.comments, allowedValues);
    }
    if (typeof strings === "boolean") {
      validatedStrings = strings ? "on" : "off";
    } else {
      validatedStrings = stringSet(strings, this.defaultValue.strings, allowedValues);
    }
    return {
      other: validatedOther,
      comments: validatedComments,
      strings: validatedStrings
    };
  }
};
var RenderLineNumbersType;
(function(RenderLineNumbersType3) {
  RenderLineNumbersType3[RenderLineNumbersType3["Off"] = 0] = "Off";
  RenderLineNumbersType3[RenderLineNumbersType3["On"] = 1] = "On";
  RenderLineNumbersType3[RenderLineNumbersType3["Relative"] = 2] = "Relative";
  RenderLineNumbersType3[RenderLineNumbersType3["Interval"] = 3] = "Interval";
  RenderLineNumbersType3[RenderLineNumbersType3["Custom"] = 4] = "Custom";
})(RenderLineNumbersType || (RenderLineNumbersType = {}));
var EditorRenderLineNumbersOption = class extends BaseEditorOption {
  constructor() {
    super(69, "lineNumbers", { renderType: 1, renderFn: null }, {
      type: "string",
      enum: ["off", "on", "relative", "interval"],
      enumDescriptions: [
        localize(406, null),
        localize(407, null),
        localize(408, null),
        localize(409, null)
      ],
      default: "on",
      description: localize(410, null)
    });
  }
  validate(lineNumbers) {
    let renderType = this.defaultValue.renderType;
    let renderFn = this.defaultValue.renderFn;
    if (typeof lineNumbers !== "undefined") {
      if (typeof lineNumbers === "function") {
        renderType = 4;
        renderFn = lineNumbers;
      } else if (lineNumbers === "interval") {
        renderType = 3;
      } else if (lineNumbers === "relative") {
        renderType = 2;
      } else if (lineNumbers === "on") {
        renderType = 1;
      } else {
        renderType = 0;
      }
    }
    return {
      renderType,
      renderFn
    };
  }
};
function filterValidationDecorations(options3) {
  const renderValidationDecorations = options3.get(
    103
    /* EditorOption.renderValidationDecorations */
  );
  if (renderValidationDecorations === "editable") {
    return options3.get(
      96
      /* EditorOption.readOnly */
    );
  }
  return renderValidationDecorations === "on" ? false : true;
}
var EditorRulers = class extends BaseEditorOption {
  constructor() {
    const defaults = [];
    const columnSchema = { type: "number", description: localize(411, null) };
    super(107, "rulers", defaults, {
      type: "array",
      items: {
        anyOf: [
          columnSchema,
          {
            type: [
              "object"
            ],
            properties: {
              column: columnSchema,
              color: {
                type: "string",
                description: localize(412, null),
                format: "color-hex"
              }
            }
          }
        ]
      },
      default: defaults,
      description: localize(413, null)
    });
  }
  validate(input) {
    if (Array.isArray(input)) {
      const rulers = [];
      for (const _element of input) {
        if (typeof _element === "number") {
          rulers.push({
            column: EditorIntOption.clampedInt(_element, 0, 0, 1e4),
            color: null
          });
        } else if (_element && typeof _element === "object") {
          const element = _element;
          rulers.push({
            column: EditorIntOption.clampedInt(element.column, 0, 0, 1e4),
            color: element.color
          });
        }
      }
      rulers.sort((a, b) => a.column - b.column);
      return rulers;
    }
    return this.defaultValue;
  }
};
var ReadonlyMessage = class extends BaseEditorOption {
  constructor() {
    const defaults = void 0;
    super(97, "readOnlyMessage", defaults);
  }
  validate(_input) {
    if (!_input || typeof _input !== "object") {
      return this.defaultValue;
    }
    return _input;
  }
};
function _scrollbarVisibilityFromString(visibility, defaultValue) {
  if (typeof visibility !== "string") {
    return defaultValue;
  }
  switch (visibility) {
    case "hidden":
      return 2;
    case "visible":
      return 3;
    default:
      return 1;
  }
}
var EditorScrollbar = class extends BaseEditorOption {
  constructor() {
    const defaults = {
      vertical: 1,
      horizontal: 1,
      arrowSize: 11,
      useShadows: true,
      verticalHasArrows: false,
      horizontalHasArrows: false,
      horizontalScrollbarSize: 12,
      horizontalSliderSize: 12,
      verticalScrollbarSize: 14,
      verticalSliderSize: 14,
      handleMouseWheel: true,
      alwaysConsumeMouseWheel: true,
      scrollByPage: false,
      ignoreHorizontalScrollbarInContentHeight: false
    };
    super(108, "scrollbar", defaults, {
      "editor.scrollbar.vertical": {
        type: "string",
        enum: ["auto", "visible", "hidden"],
        enumDescriptions: [
          localize(414, null),
          localize(415, null),
          localize(416, null)
        ],
        default: "auto",
        description: localize(417, null)
      },
      "editor.scrollbar.horizontal": {
        type: "string",
        enum: ["auto", "visible", "hidden"],
        enumDescriptions: [
          localize(418, null),
          localize(419, null),
          localize(420, null)
        ],
        default: "auto",
        description: localize(421, null)
      },
      "editor.scrollbar.verticalScrollbarSize": {
        type: "number",
        default: defaults.verticalScrollbarSize,
        description: localize(422, null)
      },
      "editor.scrollbar.horizontalScrollbarSize": {
        type: "number",
        default: defaults.horizontalScrollbarSize,
        description: localize(423, null)
      },
      "editor.scrollbar.scrollByPage": {
        type: "boolean",
        default: defaults.scrollByPage,
        description: localize(424, null)
      },
      "editor.scrollbar.ignoreHorizontalScrollbarInContentHeight": {
        type: "boolean",
        default: defaults.ignoreHorizontalScrollbarInContentHeight,
        description: localize(425, null)
      }
    });
  }
  validate(_input) {
    if (!_input || typeof _input !== "object") {
      return this.defaultValue;
    }
    const input = _input;
    const horizontalScrollbarSize = EditorIntOption.clampedInt(input.horizontalScrollbarSize, this.defaultValue.horizontalScrollbarSize, 0, 1e3);
    const verticalScrollbarSize = EditorIntOption.clampedInt(input.verticalScrollbarSize, this.defaultValue.verticalScrollbarSize, 0, 1e3);
    return {
      arrowSize: EditorIntOption.clampedInt(input.arrowSize, this.defaultValue.arrowSize, 0, 1e3),
      vertical: _scrollbarVisibilityFromString(input.vertical, this.defaultValue.vertical),
      horizontal: _scrollbarVisibilityFromString(input.horizontal, this.defaultValue.horizontal),
      useShadows: boolean(input.useShadows, this.defaultValue.useShadows),
      verticalHasArrows: boolean(input.verticalHasArrows, this.defaultValue.verticalHasArrows),
      horizontalHasArrows: boolean(input.horizontalHasArrows, this.defaultValue.horizontalHasArrows),
      handleMouseWheel: boolean(input.handleMouseWheel, this.defaultValue.handleMouseWheel),
      alwaysConsumeMouseWheel: boolean(input.alwaysConsumeMouseWheel, this.defaultValue.alwaysConsumeMouseWheel),
      horizontalScrollbarSize,
      horizontalSliderSize: EditorIntOption.clampedInt(input.horizontalSliderSize, horizontalScrollbarSize, 0, 1e3),
      verticalScrollbarSize,
      verticalSliderSize: EditorIntOption.clampedInt(input.verticalSliderSize, verticalScrollbarSize, 0, 1e3),
      scrollByPage: boolean(input.scrollByPage, this.defaultValue.scrollByPage),
      ignoreHorizontalScrollbarInContentHeight: boolean(input.ignoreHorizontalScrollbarInContentHeight, this.defaultValue.ignoreHorizontalScrollbarInContentHeight)
    };
  }
};
var inUntrustedWorkspace = "inUntrustedWorkspace";
var unicodeHighlightConfigKeys = {
  allowedCharacters: "editor.unicodeHighlight.allowedCharacters",
  invisibleCharacters: "editor.unicodeHighlight.invisibleCharacters",
  nonBasicASCII: "editor.unicodeHighlight.nonBasicASCII",
  ambiguousCharacters: "editor.unicodeHighlight.ambiguousCharacters",
  includeComments: "editor.unicodeHighlight.includeComments",
  includeStrings: "editor.unicodeHighlight.includeStrings",
  allowedLocales: "editor.unicodeHighlight.allowedLocales"
};
var UnicodeHighlight = class extends BaseEditorOption {
  constructor() {
    const defaults = {
      nonBasicASCII: inUntrustedWorkspace,
      invisibleCharacters: true,
      ambiguousCharacters: true,
      includeComments: inUntrustedWorkspace,
      includeStrings: true,
      allowedCharacters: {},
      allowedLocales: { _os: true, _vscode: true }
    };
    super(130, "unicodeHighlight", defaults, {
      [unicodeHighlightConfigKeys.nonBasicASCII]: {
        restricted: true,
        type: ["boolean", "string"],
        enum: [true, false, inUntrustedWorkspace],
        default: defaults.nonBasicASCII,
        description: localize(426, null)
      },
      [unicodeHighlightConfigKeys.invisibleCharacters]: {
        restricted: true,
        type: "boolean",
        default: defaults.invisibleCharacters,
        description: localize(427, null)
      },
      [unicodeHighlightConfigKeys.ambiguousCharacters]: {
        restricted: true,
        type: "boolean",
        default: defaults.ambiguousCharacters,
        description: localize(428, null)
      },
      [unicodeHighlightConfigKeys.includeComments]: {
        restricted: true,
        type: ["boolean", "string"],
        enum: [true, false, inUntrustedWorkspace],
        default: defaults.includeComments,
        description: localize(429, null)
      },
      [unicodeHighlightConfigKeys.includeStrings]: {
        restricted: true,
        type: ["boolean", "string"],
        enum: [true, false, inUntrustedWorkspace],
        default: defaults.includeStrings,
        description: localize(430, null)
      },
      [unicodeHighlightConfigKeys.allowedCharacters]: {
        restricted: true,
        type: "object",
        default: defaults.allowedCharacters,
        description: localize(431, null),
        additionalProperties: {
          type: "boolean"
        }
      },
      [unicodeHighlightConfigKeys.allowedLocales]: {
        restricted: true,
        type: "object",
        additionalProperties: {
          type: "boolean"
        },
        default: defaults.allowedLocales,
        description: localize(432, null)
      }
    });
  }
  applyUpdate(value, update) {
    let didChange = false;
    if (update.allowedCharacters && value) {
      if (!$Pv(value.allowedCharacters, update.allowedCharacters)) {
        value = { ...value, allowedCharacters: update.allowedCharacters };
        didChange = true;
      }
    }
    if (update.allowedLocales && value) {
      if (!$Pv(value.allowedLocales, update.allowedLocales)) {
        value = { ...value, allowedLocales: update.allowedLocales };
        didChange = true;
      }
    }
    const result = super.applyUpdate(value, update);
    if (didChange) {
      return new ApplyUpdateResult(result.newValue, true);
    }
    return result;
  }
  validate(_input) {
    if (!_input || typeof _input !== "object") {
      return this.defaultValue;
    }
    const input = _input;
    return {
      nonBasicASCII: primitiveSet(input.nonBasicASCII, inUntrustedWorkspace, [true, false, inUntrustedWorkspace]),
      invisibleCharacters: boolean(input.invisibleCharacters, this.defaultValue.invisibleCharacters),
      ambiguousCharacters: boolean(input.ambiguousCharacters, this.defaultValue.ambiguousCharacters),
      includeComments: primitiveSet(input.includeComments, inUntrustedWorkspace, [true, false, inUntrustedWorkspace]),
      includeStrings: primitiveSet(input.includeStrings, inUntrustedWorkspace, [true, false, inUntrustedWorkspace]),
      allowedCharacters: this.c(_input.allowedCharacters, this.defaultValue.allowedCharacters),
      allowedLocales: this.c(_input.allowedLocales, this.defaultValue.allowedLocales)
    };
  }
  c(map, defaultValue) {
    if (typeof map !== "object" || !map) {
      return defaultValue;
    }
    const result = {};
    for (const [key2, value] of Object.entries(map)) {
      if (value === true) {
        result[key2] = true;
      }
    }
    return result;
  }
};
var InlineEditorSuggest = class extends BaseEditorOption {
  constructor() {
    const defaults = {
      enabled: true,
      mode: "subwordSmart",
      showToolbar: "onHover",
      suppressSuggestions: false,
      keepOnBlur: false,
      fontFamily: "default",
      syntaxHighlightingEnabled: false,
      edits: {
        experimental: {
          enabled: true,
          useMixedLinesDiff: "never",
          useInterleavedLinesDiff: "never",
          onlyShowWhenCloseToCursor: true
        }
      }
    };
    super(64, "inlineSuggest", defaults, {
      "editor.inlineSuggest.enabled": {
        type: "boolean",
        default: defaults.enabled,
        description: localize(433, null)
      },
      "editor.inlineSuggest.showToolbar": {
        type: "string",
        default: defaults.showToolbar,
        enum: ["always", "onHover", "never"],
        enumDescriptions: [
          localize(434, null),
          localize(435, null),
          localize(436, null)
        ],
        description: localize(437, null)
      },
      "editor.inlineSuggest.syntaxHighlightingEnabled": {
        type: "boolean",
        default: defaults.syntaxHighlightingEnabled,
        description: localize(438, null)
      },
      "editor.inlineSuggest.suppressSuggestions": {
        type: "boolean",
        default: defaults.suppressSuggestions,
        description: localize(439, null)
      },
      "editor.inlineSuggest.fontFamily": {
        type: "string",
        default: defaults.fontFamily,
        description: localize(440, null)
      },
      "editor.inlineSuggest.edits.experimental.enabled": {
        type: "boolean",
        default: defaults.edits.experimental.enabled,
        description: localize(441, null)
      },
      "editor.inlineSuggest.edits.experimental.useMixedLinesDiff": {
        type: "string",
        default: defaults.edits.experimental.useMixedLinesDiff,
        description: localize(442, null),
        enum: ["never", "whenPossible"]
      },
      "editor.inlineSuggest.edits.experimental.useInterleavedLinesDiff": {
        type: "string",
        default: defaults.edits.experimental.useInterleavedLinesDiff,
        description: localize(443, null),
        enum: ["never", "always", "afterJump"]
      },
      "editor.inlineSuggest.edits.experimental.onlyShowWhenCloseToCursor": {
        type: "boolean",
        default: defaults.edits.experimental.onlyShowWhenCloseToCursor,
        description: localize(444, null)
      }
    });
  }
  validate(_input) {
    if (!_input || typeof _input !== "object") {
      return this.defaultValue;
    }
    const input = _input;
    return {
      enabled: boolean(input.enabled, this.defaultValue.enabled),
      mode: stringSet(input.mode, this.defaultValue.mode, ["prefix", "subword", "subwordSmart"]),
      showToolbar: stringSet(input.showToolbar, this.defaultValue.showToolbar, ["always", "onHover", "never"]),
      suppressSuggestions: boolean(input.suppressSuggestions, this.defaultValue.suppressSuggestions),
      keepOnBlur: boolean(input.keepOnBlur, this.defaultValue.keepOnBlur),
      fontFamily: EditorStringOption.string(input.fontFamily, this.defaultValue.fontFamily),
      syntaxHighlightingEnabled: boolean(input.syntaxHighlightingEnabled, this.defaultValue.syntaxHighlightingEnabled),
      edits: {
        experimental: {
          enabled: boolean(input.edits?.experimental?.enabled, this.defaultValue.edits.experimental.enabled),
          useMixedLinesDiff: stringSet(input.edits?.experimental?.useMixedLinesDiff, this.defaultValue.edits.experimental.useMixedLinesDiff, ["never", "whenPossible", "afterJumpWhenPossible"]),
          useInterleavedLinesDiff: stringSet(input.edits?.experimental?.useInterleavedLinesDiff, this.defaultValue.edits.experimental.useInterleavedLinesDiff, ["never", "always", "afterJump"]),
          onlyShowWhenCloseToCursor: boolean(input.edits?.experimental?.onlyShowWhenCloseToCursor, this.defaultValue.edits.experimental.onlyShowWhenCloseToCursor)
        }
      }
    };
  }
};
var BracketPairColorization = class extends BaseEditorOption {
  constructor() {
    const defaults = {
      enabled: $HD.bracketPairColorizationOptions.enabled,
      independentColorPoolPerBracketType: $HD.bracketPairColorizationOptions.independentColorPoolPerBracketType
    };
    super(15, "bracketPairColorization", defaults, {
      "editor.bracketPairColorization.enabled": {
        type: "boolean",
        default: defaults.enabled,
        markdownDescription: localize(445, null, "`#workbench.colorCustomizations#`")
      },
      "editor.bracketPairColorization.independentColorPoolPerBracketType": {
        type: "boolean",
        default: defaults.independentColorPoolPerBracketType,
        description: localize(446, null)
      }
    });
  }
  validate(_input) {
    if (!_input || typeof _input !== "object") {
      return this.defaultValue;
    }
    const input = _input;
    return {
      enabled: boolean(input.enabled, this.defaultValue.enabled),
      independentColorPoolPerBracketType: boolean(input.independentColorPoolPerBracketType, this.defaultValue.independentColorPoolPerBracketType)
    };
  }
};
var GuideOptions = class extends BaseEditorOption {
  constructor() {
    const defaults = {
      bracketPairs: false,
      bracketPairsHorizontal: "active",
      highlightActiveBracketPair: true,
      indentation: true,
      highlightActiveIndentation: true
    };
    super(16, "guides", defaults, {
      "editor.guides.bracketPairs": {
        type: ["boolean", "string"],
        enum: [true, "active", false],
        enumDescriptions: [
          localize(447, null),
          localize(448, null),
          localize(449, null)
        ],
        default: defaults.bracketPairs,
        description: localize(450, null)
      },
      "editor.guides.bracketPairsHorizontal": {
        type: ["boolean", "string"],
        enum: [true, "active", false],
        enumDescriptions: [
          localize(451, null),
          localize(452, null),
          localize(453, null)
        ],
        default: defaults.bracketPairsHorizontal,
        description: localize(454, null)
      },
      "editor.guides.highlightActiveBracketPair": {
        type: "boolean",
        default: defaults.highlightActiveBracketPair,
        description: localize(455, null)
      },
      "editor.guides.indentation": {
        type: "boolean",
        default: defaults.indentation,
        description: localize(456, null)
      },
      "editor.guides.highlightActiveIndentation": {
        type: ["boolean", "string"],
        enum: [true, "always", false],
        enumDescriptions: [
          localize(457, null),
          localize(458, null),
          localize(459, null)
        ],
        default: defaults.highlightActiveIndentation,
        description: localize(460, null)
      }
    });
  }
  validate(_input) {
    if (!_input || typeof _input !== "object") {
      return this.defaultValue;
    }
    const input = _input;
    return {
      bracketPairs: primitiveSet(input.bracketPairs, this.defaultValue.bracketPairs, [true, false, "active"]),
      bracketPairsHorizontal: primitiveSet(input.bracketPairsHorizontal, this.defaultValue.bracketPairsHorizontal, [true, false, "active"]),
      highlightActiveBracketPair: boolean(input.highlightActiveBracketPair, this.defaultValue.highlightActiveBracketPair),
      indentation: boolean(input.indentation, this.defaultValue.indentation),
      highlightActiveIndentation: primitiveSet(input.highlightActiveIndentation, this.defaultValue.highlightActiveIndentation, [true, false, "always"])
    };
  }
};
function primitiveSet(value, defaultValue, allowedValues) {
  const idx = allowedValues.indexOf(value);
  if (idx === -1) {
    return defaultValue;
  }
  return allowedValues[idx];
}
var EditorSuggest = class extends BaseEditorOption {
  constructor() {
    const defaults = {
      insertMode: "insert",
      filterGraceful: true,
      snippetsPreventQuickSuggestions: false,
      localityBonus: false,
      shareSuggestSelections: false,
      selectionMode: "always",
      showIcons: true,
      showStatusBar: false,
      preview: false,
      previewMode: "subwordSmart",
      showInlineDetails: true,
      showMethods: true,
      showFunctions: true,
      showConstructors: true,
      showDeprecated: true,
      matchOnWordStartOnly: true,
      showFields: true,
      showVariables: true,
      showClasses: true,
      showStructs: true,
      showInterfaces: true,
      showModules: true,
      showProperties: true,
      showEvents: true,
      showOperators: true,
      showUnits: true,
      showValues: true,
      showConstants: true,
      showEnums: true,
      showEnumMembers: true,
      showKeywords: true,
      showWords: true,
      showColors: true,
      showFiles: true,
      showReferences: true,
      showFolders: true,
      showTypeParameters: true,
      showSnippets: true,
      showUsers: true,
      showIssues: true
    };
    super(123, "suggest", defaults, {
      "editor.suggest.insertMode": {
        type: "string",
        enum: ["insert", "replace"],
        enumDescriptions: [
          localize(461, null),
          localize(462, null)
        ],
        default: defaults.insertMode,
        description: localize(463, null)
      },
      "editor.suggest.filterGraceful": {
        type: "boolean",
        default: defaults.filterGraceful,
        description: localize(464, null)
      },
      "editor.suggest.localityBonus": {
        type: "boolean",
        default: defaults.localityBonus,
        description: localize(465, null)
      },
      "editor.suggest.shareSuggestSelections": {
        type: "boolean",
        default: defaults.shareSuggestSelections,
        markdownDescription: localize(466, null)
      },
      "editor.suggest.selectionMode": {
        type: "string",
        enum: ["always", "never", "whenTriggerCharacter", "whenQuickSuggestion"],
        enumDescriptions: [
          localize(467, null),
          localize(468, null),
          localize(469, null),
          localize(470, null)
        ],
        default: defaults.selectionMode,
        markdownDescription: localize(471, null, "`#editor.quickSuggestions#`", "`#editor.suggestOnTriggerCharacters#`")
      },
      "editor.suggest.snippetsPreventQuickSuggestions": {
        type: "boolean",
        default: defaults.snippetsPreventQuickSuggestions,
        description: localize(472, null)
      },
      "editor.suggest.showIcons": {
        type: "boolean",
        default: defaults.showIcons,
        description: localize(473, null)
      },
      "editor.suggest.showStatusBar": {
        type: "boolean",
        default: defaults.showStatusBar,
        description: localize(474, null)
      },
      "editor.suggest.preview": {
        type: "boolean",
        default: defaults.preview,
        description: localize(475, null)
      },
      "editor.suggest.showInlineDetails": {
        type: "boolean",
        default: defaults.showInlineDetails,
        description: localize(476, null)
      },
      "editor.suggest.maxVisibleSuggestions": {
        type: "number",
        deprecationMessage: localize(477, null)
      },
      "editor.suggest.filteredTypes": {
        type: "object",
        deprecationMessage: localize(478, null)
      },
      "editor.suggest.showMethods": {
        type: "boolean",
        default: true,
        markdownDescription: localize(479, null)
      },
      "editor.suggest.showFunctions": {
        type: "boolean",
        default: true,
        markdownDescription: localize(480, null)
      },
      "editor.suggest.showConstructors": {
        type: "boolean",
        default: true,
        markdownDescription: localize(481, null)
      },
      "editor.suggest.showDeprecated": {
        type: "boolean",
        default: true,
        markdownDescription: localize(482, null)
      },
      "editor.suggest.matchOnWordStartOnly": {
        type: "boolean",
        default: true,
        markdownDescription: localize(483, null)
      },
      "editor.suggest.showFields": {
        type: "boolean",
        default: true,
        markdownDescription: localize(484, null)
      },
      "editor.suggest.showVariables": {
        type: "boolean",
        default: true,
        markdownDescription: localize(485, null)
      },
      "editor.suggest.showClasses": {
        type: "boolean",
        default: true,
        markdownDescription: localize(486, null)
      },
      "editor.suggest.showStructs": {
        type: "boolean",
        default: true,
        markdownDescription: localize(487, null)
      },
      "editor.suggest.showInterfaces": {
        type: "boolean",
        default: true,
        markdownDescription: localize(488, null)
      },
      "editor.suggest.showModules": {
        type: "boolean",
        default: true,
        markdownDescription: localize(489, null)
      },
      "editor.suggest.showProperties": {
        type: "boolean",
        default: true,
        markdownDescription: localize(490, null)
      },
      "editor.suggest.showEvents": {
        type: "boolean",
        default: true,
        markdownDescription: localize(491, null)
      },
      "editor.suggest.showOperators": {
        type: "boolean",
        default: true,
        markdownDescription: localize(492, null)
      },
      "editor.suggest.showUnits": {
        type: "boolean",
        default: true,
        markdownDescription: localize(493, null)
      },
      "editor.suggest.showValues": {
        type: "boolean",
        default: true,
        markdownDescription: localize(494, null)
      },
      "editor.suggest.showConstants": {
        type: "boolean",
        default: true,
        markdownDescription: localize(495, null)
      },
      "editor.suggest.showEnums": {
        type: "boolean",
        default: true,
        markdownDescription: localize(496, null)
      },
      "editor.suggest.showEnumMembers": {
        type: "boolean",
        default: true,
        markdownDescription: localize(497, null)
      },
      "editor.suggest.showKeywords": {
        type: "boolean",
        default: true,
        markdownDescription: localize(498, null)
      },
      "editor.suggest.showWords": {
        type: "boolean",
        default: true,
        markdownDescription: localize(499, null)
      },
      "editor.suggest.showColors": {
        type: "boolean",
        default: true,
        markdownDescription: localize(500, null)
      },
      "editor.suggest.showFiles": {
        type: "boolean",
        default: true,
        markdownDescription: localize(501, null)
      },
      "editor.suggest.showReferences": {
        type: "boolean",
        default: true,
        markdownDescription: localize(502, null)
      },
      "editor.suggest.showCustomcolors": {
        type: "boolean",
        default: true,
        markdownDescription: localize(503, null)
      },
      "editor.suggest.showFolders": {
        type: "boolean",
        default: true,
        markdownDescription: localize(504, null)
      },
      "editor.suggest.showTypeParameters": {
        type: "boolean",
        default: true,
        markdownDescription: localize(505, null)
      },
      "editor.suggest.showSnippets": {
        type: "boolean",
        default: true,
        markdownDescription: localize(506, null)
      },
      "editor.suggest.showUsers": {
        type: "boolean",
        default: true,
        markdownDescription: localize(507, null)
      },
      "editor.suggest.showIssues": {
        type: "boolean",
        default: true,
        markdownDescription: localize(508, null)
      }
    });
  }
  validate(_input) {
    if (!_input || typeof _input !== "object") {
      return this.defaultValue;
    }
    const input = _input;
    return {
      insertMode: stringSet(input.insertMode, this.defaultValue.insertMode, ["insert", "replace"]),
      filterGraceful: boolean(input.filterGraceful, this.defaultValue.filterGraceful),
      snippetsPreventQuickSuggestions: boolean(input.snippetsPreventQuickSuggestions, this.defaultValue.filterGraceful),
      localityBonus: boolean(input.localityBonus, this.defaultValue.localityBonus),
      shareSuggestSelections: boolean(input.shareSuggestSelections, this.defaultValue.shareSuggestSelections),
      selectionMode: stringSet(input.selectionMode, this.defaultValue.selectionMode, ["always", "never", "whenQuickSuggestion", "whenTriggerCharacter"]),
      showIcons: boolean(input.showIcons, this.defaultValue.showIcons),
      showStatusBar: boolean(input.showStatusBar, this.defaultValue.showStatusBar),
      preview: boolean(input.preview, this.defaultValue.preview),
      previewMode: stringSet(input.previewMode, this.defaultValue.previewMode, ["prefix", "subword", "subwordSmart"]),
      showInlineDetails: boolean(input.showInlineDetails, this.defaultValue.showInlineDetails),
      showMethods: boolean(input.showMethods, this.defaultValue.showMethods),
      showFunctions: boolean(input.showFunctions, this.defaultValue.showFunctions),
      showConstructors: boolean(input.showConstructors, this.defaultValue.showConstructors),
      showDeprecated: boolean(input.showDeprecated, this.defaultValue.showDeprecated),
      matchOnWordStartOnly: boolean(input.matchOnWordStartOnly, this.defaultValue.matchOnWordStartOnly),
      showFields: boolean(input.showFields, this.defaultValue.showFields),
      showVariables: boolean(input.showVariables, this.defaultValue.showVariables),
      showClasses: boolean(input.showClasses, this.defaultValue.showClasses),
      showStructs: boolean(input.showStructs, this.defaultValue.showStructs),
      showInterfaces: boolean(input.showInterfaces, this.defaultValue.showInterfaces),
      showModules: boolean(input.showModules, this.defaultValue.showModules),
      showProperties: boolean(input.showProperties, this.defaultValue.showProperties),
      showEvents: boolean(input.showEvents, this.defaultValue.showEvents),
      showOperators: boolean(input.showOperators, this.defaultValue.showOperators),
      showUnits: boolean(input.showUnits, this.defaultValue.showUnits),
      showValues: boolean(input.showValues, this.defaultValue.showValues),
      showConstants: boolean(input.showConstants, this.defaultValue.showConstants),
      showEnums: boolean(input.showEnums, this.defaultValue.showEnums),
      showEnumMembers: boolean(input.showEnumMembers, this.defaultValue.showEnumMembers),
      showKeywords: boolean(input.showKeywords, this.defaultValue.showKeywords),
      showWords: boolean(input.showWords, this.defaultValue.showWords),
      showColors: boolean(input.showColors, this.defaultValue.showColors),
      showFiles: boolean(input.showFiles, this.defaultValue.showFiles),
      showReferences: boolean(input.showReferences, this.defaultValue.showReferences),
      showFolders: boolean(input.showFolders, this.defaultValue.showFolders),
      showTypeParameters: boolean(input.showTypeParameters, this.defaultValue.showTypeParameters),
      showSnippets: boolean(input.showSnippets, this.defaultValue.showSnippets),
      showUsers: boolean(input.showUsers, this.defaultValue.showUsers),
      showIssues: boolean(input.showIssues, this.defaultValue.showIssues)
    };
  }
};
var SmartSelect = class extends BaseEditorOption {
  constructor() {
    super(118, "smartSelect", {
      selectLeadingAndTrailingWhitespace: true,
      selectSubwords: true
    }, {
      "editor.smartSelect.selectLeadingAndTrailingWhitespace": {
        description: localize(509, null),
        default: true,
        type: "boolean"
      },
      "editor.smartSelect.selectSubwords": {
        description: localize(510, null),
        default: true,
        type: "boolean"
      }
    });
  }
  validate(input) {
    if (!input || typeof input !== "object") {
      return this.defaultValue;
    }
    return {
      selectLeadingAndTrailingWhitespace: boolean(input.selectLeadingAndTrailingWhitespace, this.defaultValue.selectLeadingAndTrailingWhitespace),
      selectSubwords: boolean(input.selectSubwords, this.defaultValue.selectSubwords)
    };
  }
};
var WordSegmenterLocales = class extends BaseEditorOption {
  constructor() {
    const defaults = [];
    super(135, "wordSegmenterLocales", defaults, {
      anyOf: [
        {
          description: localize(511, null),
          type: "string"
        },
        {
          description: localize(512, null),
          type: "array",
          items: {
            type: "string"
          }
        }
      ]
    });
  }
  validate(input) {
    if (typeof input === "string") {
      input = [input];
    }
    if (Array.isArray(input)) {
      const validLocales = [];
      for (const locale of input) {
        if (typeof locale === "string") {
          try {
            if (Intl.Segmenter.supportedLocalesOf(locale).length > 0) {
              validLocales.push(locale);
            }
          } catch {
          }
        }
      }
      return validLocales;
    }
    return this.defaultValue;
  }
};
var WrappingIndent;
(function(WrappingIndent3) {
  WrappingIndent3[WrappingIndent3["None"] = 0] = "None";
  WrappingIndent3[WrappingIndent3["Same"] = 1] = "Same";
  WrappingIndent3[WrappingIndent3["Indent"] = 2] = "Indent";
  WrappingIndent3[WrappingIndent3["DeepIndent"] = 3] = "DeepIndent";
})(WrappingIndent || (WrappingIndent = {}));
var WrappingIndentOption = class extends BaseEditorOption {
  constructor() {
    super(143, "wrappingIndent", 1, {
      "editor.wrappingIndent": {
        type: "string",
        enum: ["none", "same", "indent", "deepIndent"],
        enumDescriptions: [
          localize(513, null),
          localize(514, null),
          localize(515, null),
          localize(516, null)
        ],
        description: localize(517, null),
        default: "same"
      }
    });
  }
  validate(input) {
    switch (input) {
      case "none":
        return 0;
      case "same":
        return 1;
      case "indent":
        return 2;
      case "deepIndent":
        return 3;
    }
    return 1;
  }
  compute(env3, options3, value) {
    const accessibilitySupport = options3.get(
      2
      /* EditorOption.accessibilitySupport */
    );
    if (accessibilitySupport === 2) {
      return 0;
    }
    return value;
  }
};
var EditorWrappingInfoComputer = class extends ComputedEditorOption {
  constructor() {
    super(
      152
      /* EditorOption.wrappingInfo */
    );
  }
  compute(env3, options3, _) {
    const layoutInfo = options3.get(
      151
      /* EditorOption.layoutInfo */
    );
    return {
      isDominatedByLongLines: env3.isDominatedByLongLines,
      isWordWrapMinified: layoutInfo.isWordWrapMinified,
      isViewportWrapping: layoutInfo.isViewportWrapping,
      wrappingColumn: layoutInfo.wrappingColumn
    };
  }
};
var EditorDropIntoEditor = class extends BaseEditorOption {
  constructor() {
    const defaults = { enabled: true, showDropSelector: "afterDrop" };
    super(36, "dropIntoEditor", defaults, {
      "editor.dropIntoEditor.enabled": {
        type: "boolean",
        default: defaults.enabled,
        markdownDescription: localize(518, null)
      },
      "editor.dropIntoEditor.showDropSelector": {
        type: "string",
        markdownDescription: localize(519, null),
        enum: [
          "afterDrop",
          "never"
        ],
        enumDescriptions: [
          localize(520, null),
          localize(521, null)
        ],
        default: "afterDrop"
      }
    });
  }
  validate(_input) {
    if (!_input || typeof _input !== "object") {
      return this.defaultValue;
    }
    const input = _input;
    return {
      enabled: boolean(input.enabled, this.defaultValue.enabled),
      showDropSelector: stringSet(input.showDropSelector, this.defaultValue.showDropSelector, ["afterDrop", "never"])
    };
  }
};
var EditorPasteAs = class extends BaseEditorOption {
  constructor() {
    const defaults = { enabled: true, showPasteSelector: "afterPaste" };
    super(89, "pasteAs", defaults, {
      "editor.pasteAs.enabled": {
        type: "boolean",
        default: defaults.enabled,
        markdownDescription: localize(522, null)
      },
      "editor.pasteAs.showPasteSelector": {
        type: "string",
        markdownDescription: localize(523, null),
        enum: [
          "afterPaste",
          "never"
        ],
        enumDescriptions: [
          localize(524, null),
          localize(525, null)
        ],
        default: "afterPaste"
      }
    });
  }
  validate(_input) {
    if (!_input || typeof _input !== "object") {
      return this.defaultValue;
    }
    const input = _input;
    return {
      enabled: boolean(input.enabled, this.defaultValue.enabled),
      showPasteSelector: stringSet(input.showPasteSelector, this.defaultValue.showPasteSelector, ["afterPaste", "never"])
    };
  }
};
var DEFAULT_WINDOWS_FONT_FAMILY = "Consolas, 'Courier New', monospace";
var DEFAULT_MAC_FONT_FAMILY = "Menlo, Monaco, 'Courier New', monospace";
var DEFAULT_LINUX_FONT_FAMILY = "'Droid Sans Mono', 'monospace', monospace";
var EDITOR_FONT_DEFAULTS = {
  fontFamily: $m ? DEFAULT_MAC_FONT_FAMILY : $n ? DEFAULT_LINUX_FONT_FAMILY : DEFAULT_WINDOWS_FONT_FAMILY,
  fontWeight: "normal",
  fontSize: $m ? 12 : 14,
  lineHeight: 0,
  letterSpacing: 0
};
var editorOptionsRegistry = [];
function register(option) {
  editorOptionsRegistry[option.id] = option;
  return option;
}
var EditorOption;
(function(EditorOption3) {
  EditorOption3[EditorOption3["acceptSuggestionOnCommitCharacter"] = 0] = "acceptSuggestionOnCommitCharacter";
  EditorOption3[EditorOption3["acceptSuggestionOnEnter"] = 1] = "acceptSuggestionOnEnter";
  EditorOption3[EditorOption3["accessibilitySupport"] = 2] = "accessibilitySupport";
  EditorOption3[EditorOption3["accessibilityPageSize"] = 3] = "accessibilityPageSize";
  EditorOption3[EditorOption3["ariaLabel"] = 4] = "ariaLabel";
  EditorOption3[EditorOption3["ariaRequired"] = 5] = "ariaRequired";
  EditorOption3[EditorOption3["autoClosingBrackets"] = 6] = "autoClosingBrackets";
  EditorOption3[EditorOption3["autoClosingComments"] = 7] = "autoClosingComments";
  EditorOption3[EditorOption3["screenReaderAnnounceInlineSuggestion"] = 8] = "screenReaderAnnounceInlineSuggestion";
  EditorOption3[EditorOption3["autoClosingDelete"] = 9] = "autoClosingDelete";
  EditorOption3[EditorOption3["autoClosingOvertype"] = 10] = "autoClosingOvertype";
  EditorOption3[EditorOption3["autoClosingQuotes"] = 11] = "autoClosingQuotes";
  EditorOption3[EditorOption3["autoIndent"] = 12] = "autoIndent";
  EditorOption3[EditorOption3["automaticLayout"] = 13] = "automaticLayout";
  EditorOption3[EditorOption3["autoSurround"] = 14] = "autoSurround";
  EditorOption3[EditorOption3["bracketPairColorization"] = 15] = "bracketPairColorization";
  EditorOption3[EditorOption3["guides"] = 16] = "guides";
  EditorOption3[EditorOption3["codeLens"] = 17] = "codeLens";
  EditorOption3[EditorOption3["codeLensFontFamily"] = 18] = "codeLensFontFamily";
  EditorOption3[EditorOption3["codeLensFontSize"] = 19] = "codeLensFontSize";
  EditorOption3[EditorOption3["colorDecorators"] = 20] = "colorDecorators";
  EditorOption3[EditorOption3["colorDecoratorsLimit"] = 21] = "colorDecoratorsLimit";
  EditorOption3[EditorOption3["columnSelection"] = 22] = "columnSelection";
  EditorOption3[EditorOption3["comments"] = 23] = "comments";
  EditorOption3[EditorOption3["contextmenu"] = 24] = "contextmenu";
  EditorOption3[EditorOption3["copyWithSyntaxHighlighting"] = 25] = "copyWithSyntaxHighlighting";
  EditorOption3[EditorOption3["cursorBlinking"] = 26] = "cursorBlinking";
  EditorOption3[EditorOption3["cursorSmoothCaretAnimation"] = 27] = "cursorSmoothCaretAnimation";
  EditorOption3[EditorOption3["cursorStyle"] = 28] = "cursorStyle";
  EditorOption3[EditorOption3["cursorSurroundingLines"] = 29] = "cursorSurroundingLines";
  EditorOption3[EditorOption3["cursorSurroundingLinesStyle"] = 30] = "cursorSurroundingLinesStyle";
  EditorOption3[EditorOption3["cursorWidth"] = 31] = "cursorWidth";
  EditorOption3[EditorOption3["disableLayerHinting"] = 32] = "disableLayerHinting";
  EditorOption3[EditorOption3["disableMonospaceOptimizations"] = 33] = "disableMonospaceOptimizations";
  EditorOption3[EditorOption3["domReadOnly"] = 34] = "domReadOnly";
  EditorOption3[EditorOption3["dragAndDrop"] = 35] = "dragAndDrop";
  EditorOption3[EditorOption3["dropIntoEditor"] = 36] = "dropIntoEditor";
  EditorOption3[EditorOption3["experimentalEditContextEnabled"] = 37] = "experimentalEditContextEnabled";
  EditorOption3[EditorOption3["emptySelectionClipboard"] = 38] = "emptySelectionClipboard";
  EditorOption3[EditorOption3["experimentalGpuAcceleration"] = 39] = "experimentalGpuAcceleration";
  EditorOption3[EditorOption3["experimentalWhitespaceRendering"] = 40] = "experimentalWhitespaceRendering";
  EditorOption3[EditorOption3["extraEditorClassName"] = 41] = "extraEditorClassName";
  EditorOption3[EditorOption3["fastScrollSensitivity"] = 42] = "fastScrollSensitivity";
  EditorOption3[EditorOption3["find"] = 43] = "find";
  EditorOption3[EditorOption3["fixedOverflowWidgets"] = 44] = "fixedOverflowWidgets";
  EditorOption3[EditorOption3["folding"] = 45] = "folding";
  EditorOption3[EditorOption3["foldingStrategy"] = 46] = "foldingStrategy";
  EditorOption3[EditorOption3["foldingHighlight"] = 47] = "foldingHighlight";
  EditorOption3[EditorOption3["foldingImportsByDefault"] = 48] = "foldingImportsByDefault";
  EditorOption3[EditorOption3["foldingMaximumRegions"] = 49] = "foldingMaximumRegions";
  EditorOption3[EditorOption3["unfoldOnClickAfterEndOfLine"] = 50] = "unfoldOnClickAfterEndOfLine";
  EditorOption3[EditorOption3["fontFamily"] = 51] = "fontFamily";
  EditorOption3[EditorOption3["fontInfo"] = 52] = "fontInfo";
  EditorOption3[EditorOption3["fontLigatures"] = 53] = "fontLigatures";
  EditorOption3[EditorOption3["fontSize"] = 54] = "fontSize";
  EditorOption3[EditorOption3["fontWeight"] = 55] = "fontWeight";
  EditorOption3[EditorOption3["fontVariations"] = 56] = "fontVariations";
  EditorOption3[EditorOption3["formatOnPaste"] = 57] = "formatOnPaste";
  EditorOption3[EditorOption3["formatOnType"] = 58] = "formatOnType";
  EditorOption3[EditorOption3["glyphMargin"] = 59] = "glyphMargin";
  EditorOption3[EditorOption3["gotoLocation"] = 60] = "gotoLocation";
  EditorOption3[EditorOption3["hideCursorInOverviewRuler"] = 61] = "hideCursorInOverviewRuler";
  EditorOption3[EditorOption3["hover"] = 62] = "hover";
  EditorOption3[EditorOption3["inDiffEditor"] = 63] = "inDiffEditor";
  EditorOption3[EditorOption3["inlineSuggest"] = 64] = "inlineSuggest";
  EditorOption3[EditorOption3["letterSpacing"] = 65] = "letterSpacing";
  EditorOption3[EditorOption3["lightbulb"] = 66] = "lightbulb";
  EditorOption3[EditorOption3["lineDecorationsWidth"] = 67] = "lineDecorationsWidth";
  EditorOption3[EditorOption3["lineHeight"] = 68] = "lineHeight";
  EditorOption3[EditorOption3["lineNumbers"] = 69] = "lineNumbers";
  EditorOption3[EditorOption3["lineNumbersMinChars"] = 70] = "lineNumbersMinChars";
  EditorOption3[EditorOption3["linkedEditing"] = 71] = "linkedEditing";
  EditorOption3[EditorOption3["links"] = 72] = "links";
  EditorOption3[EditorOption3["matchBrackets"] = 73] = "matchBrackets";
  EditorOption3[EditorOption3["minimap"] = 74] = "minimap";
  EditorOption3[EditorOption3["mouseStyle"] = 75] = "mouseStyle";
  EditorOption3[EditorOption3["mouseWheelScrollSensitivity"] = 76] = "mouseWheelScrollSensitivity";
  EditorOption3[EditorOption3["mouseWheelZoom"] = 77] = "mouseWheelZoom";
  EditorOption3[EditorOption3["multiCursorMergeOverlapping"] = 78] = "multiCursorMergeOverlapping";
  EditorOption3[EditorOption3["multiCursorModifier"] = 79] = "multiCursorModifier";
  EditorOption3[EditorOption3["multiCursorPaste"] = 80] = "multiCursorPaste";
  EditorOption3[EditorOption3["multiCursorLimit"] = 81] = "multiCursorLimit";
  EditorOption3[EditorOption3["occurrencesHighlight"] = 82] = "occurrencesHighlight";
  EditorOption3[EditorOption3["occurrencesHighlightDelay"] = 83] = "occurrencesHighlightDelay";
  EditorOption3[EditorOption3["overtypeCursorStyle"] = 84] = "overtypeCursorStyle";
  EditorOption3[EditorOption3["overtypeOnPaste"] = 85] = "overtypeOnPaste";
  EditorOption3[EditorOption3["overviewRulerBorder"] = 86] = "overviewRulerBorder";
  EditorOption3[EditorOption3["overviewRulerLanes"] = 87] = "overviewRulerLanes";
  EditorOption3[EditorOption3["padding"] = 88] = "padding";
  EditorOption3[EditorOption3["pasteAs"] = 89] = "pasteAs";
  EditorOption3[EditorOption3["parameterHints"] = 90] = "parameterHints";
  EditorOption3[EditorOption3["peekWidgetDefaultFocus"] = 91] = "peekWidgetDefaultFocus";
  EditorOption3[EditorOption3["placeholder"] = 92] = "placeholder";
  EditorOption3[EditorOption3["definitionLinkOpensInPeek"] = 93] = "definitionLinkOpensInPeek";
  EditorOption3[EditorOption3["quickSuggestions"] = 94] = "quickSuggestions";
  EditorOption3[EditorOption3["quickSuggestionsDelay"] = 95] = "quickSuggestionsDelay";
  EditorOption3[EditorOption3["readOnly"] = 96] = "readOnly";
  EditorOption3[EditorOption3["readOnlyMessage"] = 97] = "readOnlyMessage";
  EditorOption3[EditorOption3["renameOnType"] = 98] = "renameOnType";
  EditorOption3[EditorOption3["renderControlCharacters"] = 99] = "renderControlCharacters";
  EditorOption3[EditorOption3["renderFinalNewline"] = 100] = "renderFinalNewline";
  EditorOption3[EditorOption3["renderLineHighlight"] = 101] = "renderLineHighlight";
  EditorOption3[EditorOption3["renderLineHighlightOnlyWhenFocus"] = 102] = "renderLineHighlightOnlyWhenFocus";
  EditorOption3[EditorOption3["renderValidationDecorations"] = 103] = "renderValidationDecorations";
  EditorOption3[EditorOption3["renderWhitespace"] = 104] = "renderWhitespace";
  EditorOption3[EditorOption3["revealHorizontalRightPadding"] = 105] = "revealHorizontalRightPadding";
  EditorOption3[EditorOption3["roundedSelection"] = 106] = "roundedSelection";
  EditorOption3[EditorOption3["rulers"] = 107] = "rulers";
  EditorOption3[EditorOption3["scrollbar"] = 108] = "scrollbar";
  EditorOption3[EditorOption3["scrollBeyondLastColumn"] = 109] = "scrollBeyondLastColumn";
  EditorOption3[EditorOption3["scrollBeyondLastLine"] = 110] = "scrollBeyondLastLine";
  EditorOption3[EditorOption3["scrollPredominantAxis"] = 111] = "scrollPredominantAxis";
  EditorOption3[EditorOption3["selectionClipboard"] = 112] = "selectionClipboard";
  EditorOption3[EditorOption3["selectionHighlight"] = 113] = "selectionHighlight";
  EditorOption3[EditorOption3["selectOnLineNumbers"] = 114] = "selectOnLineNumbers";
  EditorOption3[EditorOption3["showFoldingControls"] = 115] = "showFoldingControls";
  EditorOption3[EditorOption3["showUnused"] = 116] = "showUnused";
  EditorOption3[EditorOption3["snippetSuggestions"] = 117] = "snippetSuggestions";
  EditorOption3[EditorOption3["smartSelect"] = 118] = "smartSelect";
  EditorOption3[EditorOption3["smoothScrolling"] = 119] = "smoothScrolling";
  EditorOption3[EditorOption3["stickyScroll"] = 120] = "stickyScroll";
  EditorOption3[EditorOption3["stickyTabStops"] = 121] = "stickyTabStops";
  EditorOption3[EditorOption3["stopRenderingLineAfter"] = 122] = "stopRenderingLineAfter";
  EditorOption3[EditorOption3["suggest"] = 123] = "suggest";
  EditorOption3[EditorOption3["suggestFontSize"] = 124] = "suggestFontSize";
  EditorOption3[EditorOption3["suggestLineHeight"] = 125] = "suggestLineHeight";
  EditorOption3[EditorOption3["suggestOnTriggerCharacters"] = 126] = "suggestOnTriggerCharacters";
  EditorOption3[EditorOption3["suggestSelection"] = 127] = "suggestSelection";
  EditorOption3[EditorOption3["tabCompletion"] = 128] = "tabCompletion";
  EditorOption3[EditorOption3["tabIndex"] = 129] = "tabIndex";
  EditorOption3[EditorOption3["unicodeHighlighting"] = 130] = "unicodeHighlighting";
  EditorOption3[EditorOption3["unusualLineTerminators"] = 131] = "unusualLineTerminators";
  EditorOption3[EditorOption3["useShadowDOM"] = 132] = "useShadowDOM";
  EditorOption3[EditorOption3["useTabStops"] = 133] = "useTabStops";
  EditorOption3[EditorOption3["wordBreak"] = 134] = "wordBreak";
  EditorOption3[EditorOption3["wordSegmenterLocales"] = 135] = "wordSegmenterLocales";
  EditorOption3[EditorOption3["wordSeparators"] = 136] = "wordSeparators";
  EditorOption3[EditorOption3["wordWrap"] = 137] = "wordWrap";
  EditorOption3[EditorOption3["wordWrapBreakAfterCharacters"] = 138] = "wordWrapBreakAfterCharacters";
  EditorOption3[EditorOption3["wordWrapBreakBeforeCharacters"] = 139] = "wordWrapBreakBeforeCharacters";
  EditorOption3[EditorOption3["wordWrapColumn"] = 140] = "wordWrapColumn";
  EditorOption3[EditorOption3["wordWrapOverride1"] = 141] = "wordWrapOverride1";
  EditorOption3[EditorOption3["wordWrapOverride2"] = 142] = "wordWrapOverride2";
  EditorOption3[EditorOption3["wrappingIndent"] = 143] = "wrappingIndent";
  EditorOption3[EditorOption3["wrappingStrategy"] = 144] = "wrappingStrategy";
  EditorOption3[EditorOption3["showDeprecated"] = 145] = "showDeprecated";
  EditorOption3[EditorOption3["inlayHints"] = 146] = "inlayHints";
  EditorOption3[EditorOption3["effectiveCursorStyle"] = 147] = "effectiveCursorStyle";
  EditorOption3[EditorOption3["editorClassName"] = 148] = "editorClassName";
  EditorOption3[EditorOption3["pixelRatio"] = 149] = "pixelRatio";
  EditorOption3[EditorOption3["tabFocusMode"] = 150] = "tabFocusMode";
  EditorOption3[EditorOption3["layoutInfo"] = 151] = "layoutInfo";
  EditorOption3[EditorOption3["wrappingInfo"] = 152] = "wrappingInfo";
  EditorOption3[EditorOption3["defaultColorDecorators"] = 153] = "defaultColorDecorators";
  EditorOption3[EditorOption3["colorDecoratorsActivatedOn"] = 154] = "colorDecoratorsActivatedOn";
  EditorOption3[EditorOption3["inlineCompletionsAccessibilityVerbose"] = 155] = "inlineCompletionsAccessibilityVerbose";
})(EditorOption || (EditorOption = {}));
var EditorOptions = {
  acceptSuggestionOnCommitCharacter: register(new EditorBooleanOption(0, "acceptSuggestionOnCommitCharacter", true, { markdownDescription: localize(526, null) })),
  acceptSuggestionOnEnter: register(new EditorStringEnumOption(1, "acceptSuggestionOnEnter", "on", ["on", "smart", "off"], {
    markdownEnumDescriptions: [
      "",
      localize(527, null),
      ""
    ],
    markdownDescription: localize(528, null)
  })),
  accessibilitySupport: register(new EditorAccessibilitySupport()),
  accessibilityPageSize: register(new EditorIntOption(3, "accessibilityPageSize", 10, 1, 1073741824, {
    description: localize(529, null),
    tags: ["accessibility"]
  })),
  ariaLabel: register(new EditorStringOption(4, "ariaLabel", localize(530, null))),
  ariaRequired: register(new EditorBooleanOption(5, "ariaRequired", false, void 0)),
  screenReaderAnnounceInlineSuggestion: register(new EditorBooleanOption(8, "screenReaderAnnounceInlineSuggestion", true, {
    description: localize(531, null),
    tags: ["accessibility"]
  })),
  autoClosingBrackets: register(new EditorStringEnumOption(6, "autoClosingBrackets", "languageDefined", ["always", "languageDefined", "beforeWhitespace", "never"], {
    enumDescriptions: [
      "",
      localize(532, null),
      localize(533, null),
      ""
    ],
    description: localize(534, null)
  })),
  autoClosingComments: register(new EditorStringEnumOption(7, "autoClosingComments", "languageDefined", ["always", "languageDefined", "beforeWhitespace", "never"], {
    enumDescriptions: [
      "",
      localize(535, null),
      localize(536, null),
      ""
    ],
    description: localize(537, null)
  })),
  autoClosingDelete: register(new EditorStringEnumOption(9, "autoClosingDelete", "auto", ["always", "auto", "never"], {
    enumDescriptions: [
      "",
      localize(538, null),
      ""
    ],
    description: localize(539, null)
  })),
  autoClosingOvertype: register(new EditorStringEnumOption(10, "autoClosingOvertype", "auto", ["always", "auto", "never"], {
    enumDescriptions: [
      "",
      localize(540, null),
      ""
    ],
    description: localize(541, null)
  })),
  autoClosingQuotes: register(new EditorStringEnumOption(11, "autoClosingQuotes", "languageDefined", ["always", "languageDefined", "beforeWhitespace", "never"], {
    enumDescriptions: [
      "",
      localize(542, null),
      localize(543, null),
      ""
    ],
    description: localize(544, null)
  })),
  autoIndent: register(new EditorEnumOption(12, "autoIndent", 4, "full", ["none", "keep", "brackets", "advanced", "full"], _autoIndentFromString, {
    enumDescriptions: [
      localize(545, null),
      localize(546, null),
      localize(547, null),
      localize(548, null),
      localize(549, null)
    ],
    description: localize(550, null)
  })),
  automaticLayout: register(new EditorBooleanOption(13, "automaticLayout", false)),
  autoSurround: register(new EditorStringEnumOption(14, "autoSurround", "languageDefined", ["languageDefined", "quotes", "brackets", "never"], {
    enumDescriptions: [
      localize(551, null),
      localize(552, null),
      localize(553, null),
      ""
    ],
    description: localize(554, null)
  })),
  bracketPairColorization: register(new BracketPairColorization()),
  bracketPairGuides: register(new GuideOptions()),
  stickyTabStops: register(new EditorBooleanOption(121, "stickyTabStops", false, { description: localize(555, null) })),
  codeLens: register(new EditorBooleanOption(17, "codeLens", true, { description: localize(556, null) })),
  codeLensFontFamily: register(new EditorStringOption(18, "codeLensFontFamily", "", { description: localize(557, null) })),
  codeLensFontSize: register(new EditorIntOption(19, "codeLensFontSize", 0, 0, 100, {
    type: "number",
    default: 0,
    minimum: 0,
    maximum: 100,
    markdownDescription: localize(558, null)
  })),
  colorDecorators: register(new EditorBooleanOption(20, "colorDecorators", true, { description: localize(559, null) })),
  colorDecoratorActivatedOn: register(new EditorStringEnumOption(154, "colorDecoratorsActivatedOn", "clickAndHover", ["clickAndHover", "hover", "click"], {
    enumDescriptions: [
      localize(560, null),
      localize(561, null),
      localize(562, null)
    ],
    description: localize(563, null)
  })),
  colorDecoratorsLimit: register(new EditorIntOption(21, "colorDecoratorsLimit", 500, 1, 1e6, {
    markdownDescription: localize(564, null)
  })),
  columnSelection: register(new EditorBooleanOption(22, "columnSelection", false, { description: localize(565, null) })),
  comments: register(new EditorComments()),
  contextmenu: register(new EditorBooleanOption(24, "contextmenu", true)),
  copyWithSyntaxHighlighting: register(new EditorBooleanOption(25, "copyWithSyntaxHighlighting", true, { description: localize(566, null) })),
  cursorBlinking: register(new EditorEnumOption(26, "cursorBlinking", 1, "blink", ["blink", "smooth", "phase", "expand", "solid"], cursorBlinkingStyleFromString, { description: localize(567, null) })),
  cursorSmoothCaretAnimation: register(new EditorStringEnumOption(27, "cursorSmoothCaretAnimation", "off", ["off", "explicit", "on"], {
    enumDescriptions: [
      localize(568, null),
      localize(569, null),
      localize(570, null)
    ],
    description: localize(571, null)
  })),
  cursorStyle: register(new EditorEnumOption(28, "cursorStyle", TextEditorCursorStyle.Line, "line", ["line", "block", "underline", "line-thin", "block-outline", "underline-thin"], cursorStyleFromString, { description: localize(572, null) })),
  overtypeCursorStyle: register(new EditorEnumOption(84, "overtypeCursorStyle", TextEditorCursorStyle.Block, "block", ["line", "block", "underline", "line-thin", "block-outline", "underline-thin"], cursorStyleFromString, { description: localize(573, null) })),
  cursorSurroundingLines: register(new EditorIntOption(29, "cursorSurroundingLines", 0, 0, 1073741824, { description: localize(574, null) })),
  cursorSurroundingLinesStyle: register(new EditorStringEnumOption(30, "cursorSurroundingLinesStyle", "default", ["default", "all"], {
    enumDescriptions: [
      localize(575, null),
      localize(576, null)
    ],
    markdownDescription: localize(577, null)
  })),
  cursorWidth: register(new EditorIntOption(31, "cursorWidth", 0, 0, 1073741824, { markdownDescription: localize(578, null) })),
  disableLayerHinting: register(new EditorBooleanOption(32, "disableLayerHinting", false)),
  disableMonospaceOptimizations: register(new EditorBooleanOption(33, "disableMonospaceOptimizations", false)),
  domReadOnly: register(new EditorBooleanOption(34, "domReadOnly", false)),
  dragAndDrop: register(new EditorBooleanOption(35, "dragAndDrop", true, { description: localize(579, null) })),
  emptySelectionClipboard: register(new EditorEmptySelectionClipboard()),
  dropIntoEditor: register(new EditorDropIntoEditor()),
  experimentalEditContextEnabled: register(new EditorBooleanOption(37, "experimentalEditContextEnabled", false, {
    description: localize(580, null),
    included: $H || $K || $p
  })),
  stickyScroll: register(new EditorStickyScroll()),
  experimentalGpuAcceleration: register(new EditorStringEnumOption(
    39,
    "experimentalGpuAcceleration",
    "off",
    ["off", "on"],
    void 0
    // TODO: Uncomment when we want to expose the setting to VS Code users
    // {
    // 	enumDescriptions: [
    // 		nls.localize('experimentalGpuAcceleration.off', "Use regular DOM-based rendering."),
    // 		nls.localize('experimentalGpuAcceleration.on', "Use GPU acceleration."),
    // 	],
    // 	description: nls.localize('experimentalGpuAcceleration', "Controls whether to use the (very) experimental GPU acceleration to render the editor.")
    // }
  )),
  experimentalWhitespaceRendering: register(new EditorStringEnumOption(40, "experimentalWhitespaceRendering", "svg", ["svg", "font", "off"], {
    enumDescriptions: [
      localize(581, null),
      localize(582, null),
      localize(583, null)
    ],
    description: localize(584, null)
  })),
  extraEditorClassName: register(new EditorStringOption(41, "extraEditorClassName", "")),
  fastScrollSensitivity: register(new EditorFloatOption(42, "fastScrollSensitivity", 5, (x) => x <= 0 ? 5 : x, { markdownDescription: localize(585, null) })),
  find: register(new EditorFind()),
  fixedOverflowWidgets: register(new EditorBooleanOption(44, "fixedOverflowWidgets", false)),
  folding: register(new EditorBooleanOption(45, "folding", true, { description: localize(586, null) })),
  foldingStrategy: register(new EditorStringEnumOption(46, "foldingStrategy", "auto", ["auto", "indentation"], {
    enumDescriptions: [
      localize(587, null),
      localize(588, null)
    ],
    description: localize(589, null)
  })),
  foldingHighlight: register(new EditorBooleanOption(47, "foldingHighlight", true, { description: localize(590, null) })),
  foldingImportsByDefault: register(new EditorBooleanOption(48, "foldingImportsByDefault", false, { description: localize(591, null) })),
  foldingMaximumRegions: register(new EditorIntOption(
    49,
    "foldingMaximumRegions",
    5e3,
    10,
    65e3,
    // limit must be less than foldingRanges MAX_FOLDING_REGIONS
    { description: localize(592, null) }
  )),
  unfoldOnClickAfterEndOfLine: register(new EditorBooleanOption(50, "unfoldOnClickAfterEndOfLine", false, { description: localize(593, null) })),
  fontFamily: register(new EditorStringOption(51, "fontFamily", EDITOR_FONT_DEFAULTS.fontFamily, { description: localize(594, null) })),
  fontInfo: register(new EditorFontInfo()),
  fontLigatures2: register(new EditorFontLigatures()),
  fontSize: register(new EditorFontSize()),
  fontWeight: register(new EditorFontWeight()),
  fontVariations: register(new EditorFontVariations()),
  formatOnPaste: register(new EditorBooleanOption(57, "formatOnPaste", false, { description: localize(595, null) })),
  formatOnType: register(new EditorBooleanOption(58, "formatOnType", false, { description: localize(596, null) })),
  glyphMargin: register(new EditorBooleanOption(59, "glyphMargin", true, { description: localize(597, null) })),
  gotoLocation: register(new EditorGoToLocation()),
  hideCursorInOverviewRuler: register(new EditorBooleanOption(61, "hideCursorInOverviewRuler", false, { description: localize(598, null) })),
  hover: register(new EditorHover()),
  inDiffEditor: register(new EditorBooleanOption(63, "inDiffEditor", false)),
  letterSpacing: register(new EditorFloatOption(65, "letterSpacing", EDITOR_FONT_DEFAULTS.letterSpacing, (x) => EditorFloatOption.clamp(x, -5, 20), { description: localize(599, null) })),
  lightbulb: register(new EditorLightbulb()),
  lineDecorationsWidth: register(new EditorLineDecorationsWidth()),
  lineHeight: register(new EditorLineHeight()),
  lineNumbers: register(new EditorRenderLineNumbersOption()),
  lineNumbersMinChars: register(new EditorIntOption(70, "lineNumbersMinChars", 5, 1, 300)),
  linkedEditing: register(new EditorBooleanOption(71, "linkedEditing", false, { description: localize(600, null) })),
  links: register(new EditorBooleanOption(72, "links", true, { description: localize(601, null) })),
  matchBrackets: register(new EditorStringEnumOption(73, "matchBrackets", "always", ["always", "near", "never"], { description: localize(602, null) })),
  minimap: register(new EditorMinimap()),
  mouseStyle: register(new EditorStringEnumOption(75, "mouseStyle", "text", ["text", "default", "copy"])),
  mouseWheelScrollSensitivity: register(new EditorFloatOption(76, "mouseWheelScrollSensitivity", 1, (x) => x === 0 ? 1 : x, { markdownDescription: localize(603, null) })),
  mouseWheelZoom: register(new EditorBooleanOption(77, "mouseWheelZoom", false, {
    markdownDescription: $m ? localize(604, null) : localize(605, null)
  })),
  multiCursorMergeOverlapping: register(new EditorBooleanOption(78, "multiCursorMergeOverlapping", true, { description: localize(606, null) })),
  multiCursorModifier: register(new EditorEnumOption(79, "multiCursorModifier", "altKey", "alt", ["ctrlCmd", "alt"], _multiCursorModifierFromString, {
    markdownEnumDescriptions: [
      localize(607, null),
      localize(608, null)
    ],
    markdownDescription: localize(609, null)
  })),
  multiCursorPaste: register(new EditorStringEnumOption(80, "multiCursorPaste", "spread", ["spread", "full"], {
    markdownEnumDescriptions: [
      localize(610, null),
      localize(611, null)
    ],
    markdownDescription: localize(612, null)
  })),
  multiCursorLimit: register(new EditorIntOption(81, "multiCursorLimit", 1e4, 1, 1e5, {
    markdownDescription: localize(613, null)
  })),
  occurrencesHighlight: register(new EditorStringEnumOption(82, "occurrencesHighlight", "singleFile", ["off", "singleFile", "multiFile"], {
    markdownEnumDescriptions: [
      localize(614, null),
      localize(615, null),
      localize(616, null)
    ],
    markdownDescription: localize(617, null)
  })),
  occurrencesHighlightDelay: register(new EditorIntOption(83, "occurrencesHighlightDelay", 250, 0, 2e3, {
    description: localize(618, null),
    tags: ["preview"]
  })),
  overtypeOnPaste: register(new EditorBooleanOption(85, "overtypeOnPaste", true, { description: localize(619, null) })),
  overviewRulerBorder: register(new EditorBooleanOption(86, "overviewRulerBorder", true, { description: localize(620, null) })),
  overviewRulerLanes: register(new EditorIntOption(87, "overviewRulerLanes", 3, 0, 3)),
  padding: register(new EditorPadding()),
  pasteAs: register(new EditorPasteAs()),
  parameterHints: register(new EditorParameterHints()),
  peekWidgetDefaultFocus: register(new EditorStringEnumOption(91, "peekWidgetDefaultFocus", "tree", ["tree", "editor"], {
    enumDescriptions: [
      localize(621, null),
      localize(622, null)
    ],
    description: localize(623, null)
  })),
  placeholder: register(new PlaceholderOption()),
  definitionLinkOpensInPeek: register(new EditorBooleanOption(93, "definitionLinkOpensInPeek", false, { description: localize(624, null) })),
  quickSuggestions: register(new EditorQuickSuggestions()),
  quickSuggestionsDelay: register(new EditorIntOption(95, "quickSuggestionsDelay", 10, 0, 1073741824, { description: localize(625, null) })),
  readOnly: register(new EditorBooleanOption(96, "readOnly", false)),
  readOnlyMessage: register(new ReadonlyMessage()),
  renameOnType: register(new EditorBooleanOption(98, "renameOnType", false, { description: localize(626, null), markdownDeprecationMessage: localize(627, null) })),
  renderControlCharacters: register(new EditorBooleanOption(99, "renderControlCharacters", true, { description: localize(628, null), restricted: true })),
  renderFinalNewline: register(new EditorStringEnumOption(100, "renderFinalNewline", $n ? "dimmed" : "on", ["off", "on", "dimmed"], { description: localize(629, null) })),
  renderLineHighlight: register(new EditorStringEnumOption(101, "renderLineHighlight", "line", ["none", "gutter", "line", "all"], {
    enumDescriptions: [
      "",
      "",
      "",
      localize(630, null)
    ],
    description: localize(631, null)
  })),
  renderLineHighlightOnlyWhenFocus: register(new EditorBooleanOption(102, "renderLineHighlightOnlyWhenFocus", false, { description: localize(632, null) })),
  renderValidationDecorations: register(new EditorStringEnumOption(103, "renderValidationDecorations", "editable", ["editable", "on", "off"])),
  renderWhitespace: register(new EditorStringEnumOption(104, "renderWhitespace", "selection", ["none", "boundary", "selection", "trailing", "all"], {
    enumDescriptions: [
      "",
      localize(633, null),
      localize(634, null),
      localize(635, null),
      ""
    ],
    description: localize(636, null)
  })),
  revealHorizontalRightPadding: register(new EditorIntOption(105, "revealHorizontalRightPadding", 15, 0, 1e3)),
  roundedSelection: register(new EditorBooleanOption(106, "roundedSelection", true, { description: localize(637, null) })),
  rulers: register(new EditorRulers()),
  scrollbar: register(new EditorScrollbar()),
  scrollBeyondLastColumn: register(new EditorIntOption(109, "scrollBeyondLastColumn", 4, 0, 1073741824, { description: localize(638, null) })),
  scrollBeyondLastLine: register(new EditorBooleanOption(110, "scrollBeyondLastLine", true, { description: localize(639, null) })),
  scrollPredominantAxis: register(new EditorBooleanOption(111, "scrollPredominantAxis", true, { description: localize(640, null) })),
  selectionClipboard: register(new EditorBooleanOption(112, "selectionClipboard", true, {
    description: localize(641, null),
    included: $n
  })),
  selectionHighlight: register(new EditorBooleanOption(113, "selectionHighlight", true, { description: localize(642, null) })),
  selectOnLineNumbers: register(new EditorBooleanOption(114, "selectOnLineNumbers", true)),
  showFoldingControls: register(new EditorStringEnumOption(115, "showFoldingControls", "mouseover", ["always", "never", "mouseover"], {
    enumDescriptions: [
      localize(643, null),
      localize(644, null),
      localize(645, null)
    ],
    description: localize(646, null)
  })),
  showUnused: register(new EditorBooleanOption(116, "showUnused", true, { description: localize(647, null) })),
  showDeprecated: register(new EditorBooleanOption(145, "showDeprecated", true, { description: localize(648, null) })),
  inlayHints: register(new EditorInlayHints()),
  snippetSuggestions: register(new EditorStringEnumOption(117, "snippetSuggestions", "inline", ["top", "bottom", "inline", "none"], {
    enumDescriptions: [
      localize(649, null),
      localize(650, null),
      localize(651, null),
      localize(652, null)
    ],
    description: localize(653, null)
  })),
  smartSelect: register(new SmartSelect()),
  smoothScrolling: register(new EditorBooleanOption(119, "smoothScrolling", false, { description: localize(654, null) })),
  stopRenderingLineAfter: register(new EditorIntOption(
    122,
    "stopRenderingLineAfter",
    1e4,
    -1,
    1073741824
    /* Constants.MAX_SAFE_SMALL_INTEGER */
  )),
  suggest: register(new EditorSuggest()),
  inlineSuggest: register(new InlineEditorSuggest()),
  inlineCompletionsAccessibilityVerbose: register(new EditorBooleanOption(155, "inlineCompletionsAccessibilityVerbose", false, { description: localize(655, null) })),
  suggestFontSize: register(new EditorIntOption(124, "suggestFontSize", 0, 0, 1e3, { markdownDescription: localize(656, null, "`0`", "`#editor.fontSize#`") })),
  suggestLineHeight: register(new EditorIntOption(125, "suggestLineHeight", 0, 0, 1e3, { markdownDescription: localize(657, null, "`0`", "`#editor.lineHeight#`") })),
  suggestOnTriggerCharacters: register(new EditorBooleanOption(126, "suggestOnTriggerCharacters", true, { description: localize(658, null) })),
  suggestSelection: register(new EditorStringEnumOption(127, "suggestSelection", "first", ["first", "recentlyUsed", "recentlyUsedByPrefix"], {
    markdownEnumDescriptions: [
      localize(659, null),
      localize(660, null),
      localize(661, null)
    ],
    description: localize(662, null)
  })),
  tabCompletion: register(new EditorStringEnumOption(128, "tabCompletion", "off", ["on", "off", "onlySnippets"], {
    enumDescriptions: [
      localize(663, null),
      localize(664, null),
      localize(665, null)
    ],
    description: localize(666, null)
  })),
  tabIndex: register(new EditorIntOption(
    129,
    "tabIndex",
    0,
    -1,
    1073741824
    /* Constants.MAX_SAFE_SMALL_INTEGER */
  )),
  unicodeHighlight: register(new UnicodeHighlight()),
  unusualLineTerminators: register(new EditorStringEnumOption(131, "unusualLineTerminators", "prompt", ["auto", "off", "prompt"], {
    enumDescriptions: [
      localize(667, null),
      localize(668, null),
      localize(669, null)
    ],
    description: localize(670, null)
  })),
  useShadowDOM: register(new EditorBooleanOption(132, "useShadowDOM", true)),
  useTabStops: register(new EditorBooleanOption(133, "useTabStops", true, { description: localize(671, null) })),
  wordBreak: register(new EditorStringEnumOption(134, "wordBreak", "normal", ["normal", "keepAll"], {
    markdownEnumDescriptions: [
      localize(672, null),
      localize(673, null)
    ],
    description: localize(674, null)
  })),
  wordSegmenterLocales: register(new WordSegmenterLocales()),
  wordSeparators: register(new EditorStringOption(136, "wordSeparators", $ID, { description: localize(675, null) })),
  wordWrap: register(new EditorStringEnumOption(137, "wordWrap", "off", ["off", "on", "wordWrapColumn", "bounded"], {
    markdownEnumDescriptions: [
      localize(676, null),
      localize(677, null),
      localize(678, null),
      localize(679, null)
    ],
    description: localize(680, null)
  })),
  wordWrapBreakAfterCharacters: register(new EditorStringOption(
    138,
    "wordWrapBreakAfterCharacters",
    // allow-any-unicode-next-line
    " 	})]?|/&.,;\xA2\xB0\u2032\u2033\u2030\u2103\u3001\u3002\uFF61\uFF64\uFFE0\uFF0C\uFF0E\uFF1A\uFF1B\uFF1F\uFF01\uFF05\u30FB\uFF65\u309D\u309E\u30FD\u30FE\u30FC\u30A1\u30A3\u30A5\u30A7\u30A9\u30C3\u30E3\u30E5\u30E7\u30EE\u30F5\u30F6\u3041\u3043\u3045\u3047\u3049\u3063\u3083\u3085\u3087\u308E\u3095\u3096\u31F0\u31F1\u31F2\u31F3\u31F4\u31F5\u31F6\u31F7\u31F8\u31F9\u31FA\u31FB\u31FC\u31FD\u31FE\u31FF\u3005\u303B\uFF67\uFF68\uFF69\uFF6A\uFF6B\uFF6C\uFF6D\uFF6E\uFF6F\uFF70\u201D\u3009\u300B\u300D\u300F\u3011\u3015\uFF09\uFF3D\uFF5D\uFF63"
  )),
  wordWrapBreakBeforeCharacters: register(new EditorStringOption(
    139,
    "wordWrapBreakBeforeCharacters",
    // allow-any-unicode-next-line
    "([{\u2018\u201C\u3008\u300A\u300C\u300E\u3010\u3014\uFF08\uFF3B\uFF5B\uFF62\xA3\xA5\uFF04\uFFE1\uFFE5+\uFF0B"
  )),
  wordWrapColumn: register(new EditorIntOption(140, "wordWrapColumn", 80, 1, 1073741824, {
    markdownDescription: localize(681, null)
  })),
  wordWrapOverride1: register(new EditorStringEnumOption(141, "wordWrapOverride1", "inherit", ["off", "on", "inherit"])),
  wordWrapOverride2: register(new EditorStringEnumOption(142, "wordWrapOverride2", "inherit", ["off", "on", "inherit"])),
  // Leave these at the end (because they have dependencies!)
  effectiveCursorStyle: register(new EffectiveCursorStyle()),
  editorClassName: register(new EditorClassName()),
  defaultColorDecorators: register(new EditorStringEnumOption(153, "defaultColorDecorators", "auto", ["auto", "always", "never"], {
    enumDescriptions: [
      localize(682, null),
      localize(683, null),
      localize(684, null)
    ],
    description: localize(685, null)
  })),
  pixelRatio: register(new EditorPixelRatio()),
  tabFocusMode: register(new EditorBooleanOption(150, "tabFocusMode", false, { markdownDescription: localize(686, null) })),
  layoutInfo: register(new EditorLayoutInfoComputer()),
  wrappingInfo: register(new EditorWrappingInfoComputer()),
  wrappingIndent: register(new WrappingIndentOption()),
  wrappingStrategy: register(new WrappingStrategy())
};

// out-build/vs/editor/common/config/editorZoom.js
var EditorZoom = new class {
  constructor() {
    this.a = 0;
    this.b = new $ze();
    this.onDidChangeZoomLevel = this.b.event;
  }
  getZoomLevel() {
    return this.a;
  }
  setZoomLevel(zoomLevel) {
    zoomLevel = Math.min(Math.max(-5, zoomLevel), 20);
    if (this.a === zoomLevel) {
      return;
    }
    this.a = zoomLevel;
    this.b.fire(this.a);
  }
}();

// out-build/vs/editor/common/config/fontInfo.js
var GOLDEN_LINE_HEIGHT_RATIO = $m ? 1.5 : 1.35;
var MINIMUM_LINE_HEIGHT = 8;
var $ED = class _$ED {
  /**
   * @internal
   */
  static createFromValidatedSettings(options3, pixelRatio, ignoreEditorZoom) {
    const fontFamily = options3.get(
      51
      /* EditorOption.fontFamily */
    );
    const fontWeight = options3.get(
      55
      /* EditorOption.fontWeight */
    );
    const fontSize = options3.get(
      54
      /* EditorOption.fontSize */
    );
    const fontFeatureSettings = options3.get(
      53
      /* EditorOption.fontLigatures */
    );
    const fontVariationSettings = options3.get(
      56
      /* EditorOption.fontVariations */
    );
    const lineHeight = options3.get(
      68
      /* EditorOption.lineHeight */
    );
    const letterSpacing = options3.get(
      65
      /* EditorOption.letterSpacing */
    );
    return _$ED.a(fontFamily, fontWeight, fontSize, fontFeatureSettings, fontVariationSettings, lineHeight, letterSpacing, pixelRatio, ignoreEditorZoom);
  }
  /**
   * @internal
   */
  static createFromRawSettings(opts, pixelRatio, ignoreEditorZoom = false) {
    const fontFamily = EditorOptions.fontFamily.validate(opts.fontFamily);
    const fontWeight = EditorOptions.fontWeight.validate(opts.fontWeight);
    const fontSize = EditorOptions.fontSize.validate(opts.fontSize);
    const fontFeatureSettings = EditorOptions.fontLigatures2.validate(opts.fontLigatures);
    const fontVariationSettings = EditorOptions.fontVariations.validate(opts.fontVariations);
    const lineHeight = EditorOptions.lineHeight.validate(opts.lineHeight);
    const letterSpacing = EditorOptions.letterSpacing.validate(opts.letterSpacing);
    return _$ED.a(fontFamily, fontWeight, fontSize, fontFeatureSettings, fontVariationSettings, lineHeight, letterSpacing, pixelRatio, ignoreEditorZoom);
  }
  /**
   * @internal
   */
  static a(fontFamily, fontWeight, fontSize, fontFeatureSettings, fontVariationSettings, lineHeight, letterSpacing, pixelRatio, ignoreEditorZoom) {
    if (lineHeight === 0) {
      lineHeight = GOLDEN_LINE_HEIGHT_RATIO * fontSize;
    } else if (lineHeight < MINIMUM_LINE_HEIGHT) {
      lineHeight = lineHeight * fontSize;
    }
    lineHeight = Math.round(lineHeight);
    if (lineHeight < MINIMUM_LINE_HEIGHT) {
      lineHeight = MINIMUM_LINE_HEIGHT;
    }
    const editorZoomLevelMultiplier = 1 + (ignoreEditorZoom ? 0 : EditorZoom.getZoomLevel() * 0.1);
    fontSize *= editorZoomLevelMultiplier;
    lineHeight *= editorZoomLevelMultiplier;
    if (fontVariationSettings === EditorFontVariations.TRANSLATE) {
      if (fontWeight === "normal" || fontWeight === "bold") {
        fontVariationSettings = EditorFontVariations.OFF;
      } else {
        const fontWeightAsNumber = parseInt(fontWeight, 10);
        fontVariationSettings = `'wght' ${fontWeightAsNumber}`;
        fontWeight = "normal";
      }
    }
    return new _$ED({
      pixelRatio,
      fontFamily,
      fontWeight,
      fontSize,
      fontFeatureSettings,
      fontVariationSettings,
      lineHeight,
      letterSpacing
    });
  }
  /**
   * @internal
   */
  constructor(opts) {
    this._bareFontInfoBrand = void 0;
    this.pixelRatio = opts.pixelRatio;
    this.fontFamily = String(opts.fontFamily);
    this.fontWeight = String(opts.fontWeight);
    this.fontSize = opts.fontSize;
    this.fontFeatureSettings = opts.fontFeatureSettings;
    this.fontVariationSettings = opts.fontVariationSettings;
    this.lineHeight = opts.lineHeight | 0;
    this.letterSpacing = opts.letterSpacing;
  }
  /**
   * @internal
   */
  getId() {
    return `${this.pixelRatio}-${this.fontFamily}-${this.fontWeight}-${this.fontSize}-${this.fontFeatureSettings}-${this.fontVariationSettings}-${this.lineHeight}-${this.letterSpacing}`;
  }
  /**
   * @internal
   */
  getMassagedFontFamily() {
    const fallbackFontFamily = EDITOR_FONT_DEFAULTS.fontFamily;
    const fontFamily = _$ED.b(this.fontFamily);
    if (fallbackFontFamily && this.fontFamily !== fallbackFontFamily) {
      return `${fontFamily}, ${fallbackFontFamily}`;
    }
    return fontFamily;
  }
  static b(fontFamily) {
    if (/[,"']/.test(fontFamily)) {
      return fontFamily;
    }
    if (/[+ ]/.test(fontFamily)) {
      return `"${fontFamily}"`;
    }
    return fontFamily;
  }
};
var $FD = 2;
var $GD = class extends $ED {
  /**
   * @internal
   */
  constructor(opts, isTrusted) {
    super(opts);
    this._editorStylingBrand = void 0;
    this.version = $FD;
    this.isTrusted = isTrusted;
    this.isMonospace = opts.isMonospace;
    this.typicalHalfwidthCharacterWidth = opts.typicalHalfwidthCharacterWidth;
    this.typicalFullwidthCharacterWidth = opts.typicalFullwidthCharacterWidth;
    this.canUseHalfwidthRightwardsArrow = opts.canUseHalfwidthRightwardsArrow;
    this.spaceWidth = opts.spaceWidth;
    this.middotWidth = opts.middotWidth;
    this.wsmiddotWidth = opts.wsmiddotWidth;
    this.maxDigitWidth = opts.maxDigitWidth;
  }
  /**
   * @internal
   */
  equals(other) {
    return this.fontFamily === other.fontFamily && this.fontWeight === other.fontWeight && this.fontSize === other.fontSize && this.fontFeatureSettings === other.fontFeatureSettings && this.fontVariationSettings === other.fontVariationSettings && this.lineHeight === other.lineHeight && this.letterSpacing === other.letterSpacing && this.typicalHalfwidthCharacterWidth === other.typicalHalfwidthCharacterWidth && this.typicalFullwidthCharacterWidth === other.typicalFullwidthCharacterWidth && this.canUseHalfwidthRightwardsArrow === other.canUseHalfwidthRightwardsArrow && this.spaceWidth === other.spaceWidth && this.middotWidth === other.middotWidth && this.wsmiddotWidth === other.wsmiddotWidth && this.maxDigitWidth === other.maxDigitWidth;
  }
};

// out-build/vs/editor/browser/config/fontMeasurements.js
var $54 = class extends $3c {
  constructor() {
    super(...arguments);
    this.a = /* @__PURE__ */ new Map();
    this.b = -1;
    this.c = this.B(new $ze());
    this.onDidChange = this.c.event;
  }
  dispose() {
    if (this.b !== -1) {
      clearTimeout(this.b);
      this.b = -1;
    }
    super.dispose();
  }
  /**
   * Clear all cached font information and trigger a change event.
   */
  clearAllFontInfos() {
    this.a.clear();
    this.c.fire();
  }
  f(targetWindow) {
    const windowId = getWindowId(targetWindow);
    let cache2 = this.a.get(windowId);
    if (!cache2) {
      cache2 = new FontMeasurementsCache();
      this.a.set(windowId, cache2);
    }
    return cache2;
  }
  g(targetWindow, item, value) {
    const cache2 = this.f(targetWindow);
    cache2.put(item, value);
    if (!value.isTrusted && this.b === -1) {
      this.b = targetWindow.setTimeout(() => {
        this.b = -1;
        this.h(targetWindow);
      }, 5e3);
    }
  }
  h(targetWindow) {
    const cache2 = this.f(targetWindow);
    const values = cache2.getValues();
    let somethingRemoved = false;
    for (const item of values) {
      if (!item.isTrusted) {
        somethingRemoved = true;
        cache2.remove(item);
      }
    }
    if (somethingRemoved) {
      this.c.fire();
    }
  }
  /**
   * Serialized currently cached font information.
   */
  serializeFontInfo(targetWindow) {
    const cache2 = this.f(targetWindow);
    return cache2.getValues().filter((item) => item.isTrusted);
  }
  /**
   * Restore previously serialized font informations.
   */
  restoreFontInfo(targetWindow, savedFontInfos) {
    for (const savedFontInfo of savedFontInfos) {
      if (savedFontInfo.version !== $FD) {
        continue;
      }
      const fontInfo = new $GD(savedFontInfo, false);
      this.g(targetWindow, fontInfo, fontInfo);
    }
  }
  /**
   * Read font information.
   */
  readFontInfo(targetWindow, bareFontInfo) {
    const cache2 = this.f(targetWindow);
    if (!cache2.has(bareFontInfo)) {
      let readConfig = this.m(targetWindow, bareFontInfo);
      if (readConfig.typicalHalfwidthCharacterWidth <= 2 || readConfig.typicalFullwidthCharacterWidth <= 2 || readConfig.spaceWidth <= 2 || readConfig.maxDigitWidth <= 2) {
        readConfig = new $GD({
          pixelRatio: $_1.getInstance(targetWindow).value,
          fontFamily: readConfig.fontFamily,
          fontWeight: readConfig.fontWeight,
          fontSize: readConfig.fontSize,
          fontFeatureSettings: readConfig.fontFeatureSettings,
          fontVariationSettings: readConfig.fontVariationSettings,
          lineHeight: readConfig.lineHeight,
          letterSpacing: readConfig.letterSpacing,
          isMonospace: readConfig.isMonospace,
          typicalHalfwidthCharacterWidth: Math.max(readConfig.typicalHalfwidthCharacterWidth, 5),
          typicalFullwidthCharacterWidth: Math.max(readConfig.typicalFullwidthCharacterWidth, 5),
          canUseHalfwidthRightwardsArrow: readConfig.canUseHalfwidthRightwardsArrow,
          spaceWidth: Math.max(readConfig.spaceWidth, 5),
          middotWidth: Math.max(readConfig.middotWidth, 5),
          wsmiddotWidth: Math.max(readConfig.wsmiddotWidth, 5),
          maxDigitWidth: Math.max(readConfig.maxDigitWidth, 5)
        }, false);
      }
      this.g(targetWindow, bareFontInfo, readConfig);
    }
    return cache2.get(bareFontInfo);
  }
  j(chr, type, all, monospace) {
    const result = new $34(chr, type);
    all.push(result);
    monospace?.push(result);
    return result;
  }
  m(targetWindow, bareFontInfo) {
    const all = [];
    const monospace = [];
    const typicalHalfwidthCharacter = this.j("n", 0, all, monospace);
    const typicalFullwidthCharacter = this.j("\uFF4D", 0, all, null);
    const space = this.j(" ", 0, all, monospace);
    const digit0 = this.j("0", 0, all, monospace);
    const digit1 = this.j("1", 0, all, monospace);
    const digit2 = this.j("2", 0, all, monospace);
    const digit3 = this.j("3", 0, all, monospace);
    const digit4 = this.j("4", 0, all, monospace);
    const digit5 = this.j("5", 0, all, monospace);
    const digit6 = this.j("6", 0, all, monospace);
    const digit7 = this.j("7", 0, all, monospace);
    const digit8 = this.j("8", 0, all, monospace);
    const digit9 = this.j("9", 0, all, monospace);
    const rightwardsArrow = this.j("\u2192", 0, all, monospace);
    const halfwidthRightwardsArrow = this.j("\uFFEB", 0, all, null);
    const middot = this.j("\xB7", 0, all, monospace);
    const wsmiddotWidth = this.j(String.fromCharCode(11825), 0, all, null);
    const monospaceTestChars = "|/-_ilm%";
    for (let i2 = 0, len = monospaceTestChars.length; i2 < len; i2++) {
      this.j(monospaceTestChars.charAt(i2), 0, all, monospace);
      this.j(monospaceTestChars.charAt(i2), 1, all, monospace);
      this.j(monospaceTestChars.charAt(i2), 2, all, monospace);
    }
    $44(targetWindow, bareFontInfo, all);
    const maxDigitWidth = Math.max(digit0.width, digit1.width, digit2.width, digit3.width, digit4.width, digit5.width, digit6.width, digit7.width, digit8.width, digit9.width);
    let isMonospace = bareFontInfo.fontFeatureSettings === EditorFontLigatures.OFF;
    const referenceWidth = monospace[0].width;
    for (let i2 = 1, len = monospace.length; isMonospace && i2 < len; i2++) {
      const diff3 = referenceWidth - monospace[i2].width;
      if (diff3 < -1e-3 || diff3 > 1e-3) {
        isMonospace = false;
        break;
      }
    }
    let canUseHalfwidthRightwardsArrow = true;
    if (isMonospace && halfwidthRightwardsArrow.width !== referenceWidth) {
      canUseHalfwidthRightwardsArrow = false;
    }
    if (halfwidthRightwardsArrow.width > rightwardsArrow.width) {
      canUseHalfwidthRightwardsArrow = false;
    }
    return new $GD({
      pixelRatio: $_1.getInstance(targetWindow).value,
      fontFamily: bareFontInfo.fontFamily,
      fontWeight: bareFontInfo.fontWeight,
      fontSize: bareFontInfo.fontSize,
      fontFeatureSettings: bareFontInfo.fontFeatureSettings,
      fontVariationSettings: bareFontInfo.fontVariationSettings,
      lineHeight: bareFontInfo.lineHeight,
      letterSpacing: bareFontInfo.letterSpacing,
      isMonospace,
      typicalHalfwidthCharacterWidth: typicalHalfwidthCharacter.width,
      typicalFullwidthCharacterWidth: typicalFullwidthCharacter.width,
      canUseHalfwidthRightwardsArrow,
      spaceWidth: space.width,
      middotWidth: middot.width,
      wsmiddotWidth: wsmiddotWidth.width,
      maxDigitWidth
    }, true);
  }
};
var FontMeasurementsCache = class {
  constructor() {
    this.a = /* @__PURE__ */ Object.create(null);
    this.b = /* @__PURE__ */ Object.create(null);
  }
  has(item) {
    const itemId = item.getId();
    return !!this.b[itemId];
  }
  get(item) {
    const itemId = item.getId();
    return this.b[itemId];
  }
  put(item, value) {
    const itemId = item.getId();
    this.a[itemId] = item;
    this.b[itemId] = value;
  }
  remove(item) {
    const itemId = item.getId();
    delete this.a[itemId];
    delete this.b[itemId];
  }
  getValues() {
    return Object.keys(this.a).map((id2) => this.b[id2]);
  }
};
var $64 = new $54();

// out-build/vs/editor/browser/config/migrateOptions.js
var $74 = class _$74 {
  static {
    this.items = [];
  }
  constructor(key2, migrate) {
    this.key = key2;
    this.migrate = migrate;
  }
  apply(options3) {
    const value = _$74.a(options3, this.key);
    const read = (key2) => _$74.a(options3, key2);
    const write = (key2, value2) => _$74.b(options3, key2, value2);
    this.migrate(value, read, write);
  }
  static a(source, key2) {
    if (typeof source === "undefined") {
      return void 0;
    }
    const firstDotIndex = key2.indexOf(".");
    if (firstDotIndex >= 0) {
      const firstSegment = key2.substring(0, firstDotIndex);
      return this.a(source[firstSegment], key2.substring(firstDotIndex + 1));
    }
    return source[key2];
  }
  static b(target, key2, value) {
    const firstDotIndex = key2.indexOf(".");
    if (firstDotIndex >= 0) {
      const firstSegment = key2.substring(0, firstDotIndex);
      target[firstSegment] = target[firstSegment] || {};
      this.b(target[firstSegment], key2.substring(firstDotIndex + 1), value);
      return;
    }
    target[key2] = value;
  }
};
function registerEditorSettingMigration(key2, migrate) {
  $74.items.push(new $74(key2, migrate));
}
function registerSimpleEditorSettingMigration(key2, values) {
  registerEditorSettingMigration(key2, (value, read, write) => {
    if (typeof value !== "undefined") {
      for (const [oldValue, newValue] of values) {
        if (value === oldValue) {
          write(key2, newValue);
          return;
        }
      }
    }
  });
}
function $84(options3) {
  $74.items.forEach((migration) => migration.apply(options3));
}
registerSimpleEditorSettingMigration("wordWrap", [[true, "on"], [false, "off"]]);
registerSimpleEditorSettingMigration("lineNumbers", [[true, "on"], [false, "off"]]);
registerSimpleEditorSettingMigration("cursorBlinking", [["visible", "solid"]]);
registerSimpleEditorSettingMigration("renderWhitespace", [[true, "boundary"], [false, "none"]]);
registerSimpleEditorSettingMigration("renderLineHighlight", [[true, "line"], [false, "none"]]);
registerSimpleEditorSettingMigration("acceptSuggestionOnEnter", [[true, "on"], [false, "off"]]);
registerSimpleEditorSettingMigration("tabCompletion", [[false, "off"], [true, "onlySnippets"]]);
registerSimpleEditorSettingMigration("hover", [[true, { enabled: true }], [false, { enabled: false }]]);
registerSimpleEditorSettingMigration("parameterHints", [[true, { enabled: true }], [false, { enabled: false }]]);
registerSimpleEditorSettingMigration("autoIndent", [[false, "advanced"], [true, "full"]]);
registerSimpleEditorSettingMigration("matchBrackets", [[true, "always"], [false, "never"]]);
registerSimpleEditorSettingMigration("renderFinalNewline", [[true, "on"], [false, "off"]]);
registerSimpleEditorSettingMigration("cursorSmoothCaretAnimation", [[true, "on"], [false, "off"]]);
registerSimpleEditorSettingMigration("occurrencesHighlight", [[true, "singleFile"], [false, "off"]]);
registerSimpleEditorSettingMigration("wordBasedSuggestions", [[true, "matchingDocuments"], [false, "off"]]);
registerSimpleEditorSettingMigration("defaultColorDecorators", [[true, "auto"], [false, "never"]]);
registerEditorSettingMigration("autoClosingBrackets", (value, read, write) => {
  if (value === false) {
    write("autoClosingBrackets", "never");
    if (typeof read("autoClosingQuotes") === "undefined") {
      write("autoClosingQuotes", "never");
    }
    if (typeof read("autoSurround") === "undefined") {
      write("autoSurround", "never");
    }
  }
});
registerEditorSettingMigration("renderIndentGuides", (value, read, write) => {
  if (typeof value !== "undefined") {
    write("renderIndentGuides", void 0);
    if (typeof read("guides.indentation") === "undefined") {
      write("guides.indentation", !!value);
    }
  }
});
registerEditorSettingMigration("highlightActiveIndentGuide", (value, read, write) => {
  if (typeof value !== "undefined") {
    write("highlightActiveIndentGuide", void 0);
    if (typeof read("guides.highlightActiveIndentation") === "undefined") {
      write("guides.highlightActiveIndentation", !!value);
    }
  }
});
var suggestFilteredTypesMapping = {
  method: "showMethods",
  function: "showFunctions",
  constructor: "showConstructors",
  deprecated: "showDeprecated",
  field: "showFields",
  variable: "showVariables",
  class: "showClasses",
  struct: "showStructs",
  interface: "showInterfaces",
  module: "showModules",
  property: "showProperties",
  event: "showEvents",
  operator: "showOperators",
  unit: "showUnits",
  value: "showValues",
  constant: "showConstants",
  enum: "showEnums",
  enumMember: "showEnumMembers",
  keyword: "showKeywords",
  text: "showWords",
  color: "showColors",
  file: "showFiles",
  reference: "showReferences",
  folder: "showFolders",
  typeParameter: "showTypeParameters",
  snippet: "showSnippets"
};
registerEditorSettingMigration("suggest.filteredTypes", (value, read, write) => {
  if (value && typeof value === "object") {
    for (const entry of Object.entries(suggestFilteredTypesMapping)) {
      const v = value[entry[0]];
      if (v === false) {
        if (typeof read(`suggest.${entry[1]}`) === "undefined") {
          write(`suggest.${entry[1]}`, false);
        }
      }
    }
    write("suggest.filteredTypes", void 0);
  }
});
registerEditorSettingMigration("quickSuggestions", (input, read, write) => {
  if (typeof input === "boolean") {
    const value = input ? "on" : "off";
    const newValue = { comments: value, strings: value, other: value };
    write("quickSuggestions", newValue);
  }
});
registerEditorSettingMigration("experimental.stickyScroll.enabled", (value, read, write) => {
  if (typeof value === "boolean") {
    write("experimental.stickyScroll.enabled", void 0);
    if (typeof read("stickyScroll.enabled") === "undefined") {
      write("stickyScroll.enabled", value);
    }
  }
});
registerEditorSettingMigration("experimental.stickyScroll.maxLineCount", (value, read, write) => {
  if (typeof value === "number") {
    write("experimental.stickyScroll.maxLineCount", void 0);
    if (typeof read("stickyScroll.maxLineCount") === "undefined") {
      write("stickyScroll.maxLineCount", value);
    }
  }
});
registerEditorSettingMigration("codeActionsOnSave", (value, read, write) => {
  if (value && typeof value === "object") {
    let toBeModified = false;
    const newValue = {};
    for (const entry of Object.entries(value)) {
      if (typeof entry[1] === "boolean") {
        toBeModified = true;
        newValue[entry[0]] = entry[1] ? "explicit" : "never";
      } else {
        newValue[entry[0]] = entry[1];
      }
    }
    if (toBeModified) {
      write(`codeActionsOnSave`, newValue);
    }
  }
});
registerEditorSettingMigration("codeActionWidget.includeNearbyQuickfixes", (value, read, write) => {
  if (typeof value === "boolean") {
    write("codeActionWidget.includeNearbyQuickfixes", void 0);
    if (typeof read("codeActionWidget.includeNearbyQuickFixes") === "undefined") {
      write("codeActionWidget.includeNearbyQuickFixes", value);
    }
  }
});
registerEditorSettingMigration("lightbulb.enabled", (value, read, write) => {
  if (typeof value === "boolean") {
    write("lightbulb.enabled", value ? void 0 : "off");
  }
});

// out-build/vs/editor/browser/config/tabFocus.js
var TabFocusImpl = class {
  constructor() {
    this.a = false;
    this.b = new $ze();
    this.onDidChangeTabFocus = this.b.event;
  }
  getTabFocusMode() {
    return this.a;
  }
  setTabFocusMode(tabFocusMode) {
    this.a = tabFocusMode;
    this.b.fire(this.a);
  }
};
var $94 = new TabFocusImpl();

// out-build/vs/platform/accessibility/common/accessibility.js
var $ND = $Qk("accessibilityService");
var AccessibilitySupport;
(function(AccessibilitySupport3) {
  AccessibilitySupport3[AccessibilitySupport3["Unknown"] = 0] = "Unknown";
  AccessibilitySupport3[AccessibilitySupport3["Disabled"] = 1] = "Disabled";
  AccessibilitySupport3[AccessibilitySupport3["Enabled"] = 2] = "Enabled";
})(AccessibilitySupport || (AccessibilitySupport = {}));
var $OD = new $nn("accessibilityModeEnabled", false);
function $PD(obj) {
  return obj && typeof obj === "object" && typeof obj.label === "string" && (typeof obj.role === "undefined" || typeof obj.role === "string");
}
var $QD = "ACCESSIBLE_VIEW_SHOWN_";

// out-build/vs/editor/browser/config/editorConfiguration.js
var $$4 = class $$42 extends $3c {
  constructor(isSimpleWidget, contextMenuId, options3, container2, C) {
    super();
    this.C = C;
    this.c = this.B(new $ze());
    this.onDidChange = this.c.event;
    this.f = this.B(new $ze());
    this.onDidChangeFast = this.f.event;
    this.h = false;
    this.j = 1;
    this.m = 1;
    this.s = 0;
    this.t = 1;
    this.w = new ComputeOptionsMemory();
    this.isSimpleWidget = isSimpleWidget;
    this.contextMenuId = contextMenuId;
    this.g = this.B(new $14(container2, options3.dimension));
    this.u = getWindow(container2).vscodeWindowId;
    this.y = deepCloneAndMigrateOptions(options3);
    this.z = EditorOptionsUtil.validateOptions(this.y);
    this.options = this.F();
    if (this.options.get(
      13
      /* EditorOption.automaticLayout */
    )) {
      this.g.startObserving();
    }
    this.B(EditorZoom.onDidChangeZoomLevel(() => this.D()));
    this.B($94.onDidChangeTabFocus(() => this.D()));
    this.B(this.g.onDidChange(() => this.D()));
    this.B($64.onDidChange(() => this.D()));
    this.B($_1.getInstance(getWindow(container2)).onDidChange(() => this.D()));
    this.B(this.C.onDidChangeScreenReaderOptimized(() => this.D()));
    this.B($04.onDidChangeInputMode(() => this.D()));
  }
  D() {
    const newOptions = this.F();
    const changeEvent = EditorOptionsUtil.checkEquals(this.options, newOptions);
    if (changeEvent === null) {
      return;
    }
    this.options = newOptions;
    this.f.fire(changeEvent);
    this.c.fire(changeEvent);
  }
  F() {
    const partialEnv = this.G();
    const bareFontInfo = $ED.createFromValidatedSettings(this.z, partialEnv.pixelRatio, this.isSimpleWidget);
    const fontInfo = this.H(bareFontInfo);
    const env3 = {
      memory: this.w,
      outerWidth: partialEnv.outerWidth,
      outerHeight: partialEnv.outerHeight - this.s,
      fontInfo,
      extraEditorClassName: partialEnv.extraEditorClassName,
      isDominatedByLongLines: this.h,
      viewLineCount: this.j,
      lineNumbersDigitCount: this.m,
      emptySelectionClipboard: partialEnv.emptySelectionClipboard,
      pixelRatio: partialEnv.pixelRatio,
      tabFocusMode: $94.getTabFocusMode(),
      inputMode: $04.getInputMode(),
      accessibilitySupport: partialEnv.accessibilitySupport,
      glyphMarginDecorationLaneCount: this.t
    };
    return EditorOptionsUtil.computeOptions(this.z, env3);
  }
  G() {
    return {
      extraEditorClassName: getExtraEditorClassName(),
      outerWidth: this.g.getWidth(),
      outerHeight: this.g.getHeight(),
      emptySelectionClipboard: $Ve || $Ue,
      pixelRatio: $_1.getInstance(getWindowById(this.u, true).window).value,
      accessibilitySupport: this.C.isScreenReaderOptimized() ? 2 : this.C.getAccessibilitySupport()
    };
  }
  H(bareFontInfo) {
    return $64.readFontInfo(getWindowById(this.u, true).window, bareFontInfo);
  }
  getRawOptions() {
    return this.y;
  }
  updateOptions(_newOptions) {
    const newOptions = deepCloneAndMigrateOptions(_newOptions);
    const didChange = EditorOptionsUtil.applyUpdate(this.y, newOptions);
    if (!didChange) {
      return;
    }
    this.z = EditorOptionsUtil.validateOptions(this.y);
    this.D();
  }
  observeContainer(dimension) {
    this.g.observe(dimension);
  }
  setIsDominatedByLongLines(isDominatedByLongLines) {
    if (this.h === isDominatedByLongLines) {
      return;
    }
    this.h = isDominatedByLongLines;
    this.D();
  }
  setModelLineCount(modelLineCount) {
    const lineNumbersDigitCount = digitCount(modelLineCount);
    if (this.m === lineNumbersDigitCount) {
      return;
    }
    this.m = lineNumbersDigitCount;
    this.D();
  }
  setViewLineCount(viewLineCount) {
    if (this.j === viewLineCount) {
      return;
    }
    this.j = viewLineCount;
    this.D();
  }
  setReservedHeight(reservedHeight) {
    if (this.s === reservedHeight) {
      return;
    }
    this.s = reservedHeight;
    this.D();
  }
  setGlyphMarginDecorationLaneCount(decorationLaneCount) {
    if (this.t === decorationLaneCount) {
      return;
    }
    this.t = decorationLaneCount;
    this.D();
  }
};
$$4 = __decorate([
  __param(4, $ND)
], $$4);
function digitCount(n) {
  let r2 = 0;
  while (n) {
    n = Math.floor(n / 10);
    r2++;
  }
  return r2 ? r2 : 1;
}
function getExtraEditorClassName() {
  let extra = "";
  if (!$Xe && !$Ye) {
    extra += "no-user-select ";
  }
  if ($Xe) {
    extra += "no-minimap-shadow ";
    extra += "enable-user-select ";
  }
  if ($m) {
    extra += "mac ";
  }
  return extra;
}
var ValidatedEditorOptions = class {
  constructor() {
    this.c = [];
  }
  _read(option) {
    return this.c[option];
  }
  get(id2) {
    return this.c[id2];
  }
  _write(option, value) {
    this.c[option] = value;
  }
};
var $_4 = class {
  constructor() {
    this.c = [];
  }
  _read(id2) {
    if (id2 >= this.c.length) {
      throw new Error("Cannot read uninitialized value");
    }
    return this.c[id2];
  }
  get(id2) {
    return this._read(id2);
  }
  _write(id2, value) {
    this.c[id2] = value;
  }
};
var EditorOptionsUtil = class _EditorOptionsUtil {
  static validateOptions(options3) {
    const result = new ValidatedEditorOptions();
    for (const editorOption of editorOptionsRegistry) {
      const value = editorOption.name === "_never_" ? void 0 : options3[editorOption.name];
      result._write(editorOption.id, editorOption.validate(value));
    }
    return result;
  }
  static computeOptions(options3, env3) {
    const result = new $_4();
    for (const editorOption of editorOptionsRegistry) {
      result._write(editorOption.id, editorOption.compute(env3, result, options3._read(editorOption.id)));
    }
    return result;
  }
  static c(a, b) {
    if (typeof a !== "object" || typeof b !== "object" || !a || !b) {
      return a === b;
    }
    if (Array.isArray(a) || Array.isArray(b)) {
      return Array.isArray(a) && Array.isArray(b) ? $zb(a, b) : false;
    }
    if (Object.keys(a).length !== Object.keys(b).length) {
      return false;
    }
    for (const key2 in a) {
      if (!_EditorOptionsUtil.c(a[key2], b[key2])) {
        return false;
      }
    }
    return true;
  }
  static checkEquals(a, b) {
    const result = [];
    let somethingChanged = false;
    for (const editorOption of editorOptionsRegistry) {
      const changed = !_EditorOptionsUtil.c(a._read(editorOption.id), b._read(editorOption.id));
      result[editorOption.id] = changed;
      if (changed) {
        somethingChanged = true;
      }
    }
    return somethingChanged ? new ConfigurationChangedEvent(result) : null;
  }
  /**
   * Returns true if something changed.
   * Modifies `options`.
  */
  static applyUpdate(options3, update) {
    let changed = false;
    for (const editorOption of editorOptionsRegistry) {
      if (update.hasOwnProperty(editorOption.name)) {
        const result = editorOption.applyUpdate(options3[editorOption.name], update[editorOption.name]);
        options3[editorOption.name] = result.newValue;
        changed = changed || result.didChange;
      }
    }
    return changed;
  }
};
function deepCloneAndMigrateOptions(_options) {
  const options3 = $Lv(_options);
  $84(options3);
  return options3;
}

// out-build/vs/base/browser/performance.js
var inputLatency;
(function(inputLatency2) {
  const totalKeydownTime = { total: 0, min: Number.MAX_VALUE, max: 0 };
  const totalInputTime = { ...totalKeydownTime };
  const totalRenderTime = { ...totalKeydownTime };
  const totalInputLatencyTime = { ...totalKeydownTime };
  let measurementsCount = 0;
  let EventPhase;
  (function(EventPhase2) {
    EventPhase2[EventPhase2["Before"] = 0] = "Before";
    EventPhase2[EventPhase2["InProgress"] = 1] = "InProgress";
    EventPhase2[EventPhase2["Finished"] = 2] = "Finished";
  })(EventPhase || (EventPhase = {}));
  const state = {
    keydown: 0,
    input: 0,
    render: 0
  };
  function onKeyDown() {
    recordIfFinished();
    performance.mark("inputlatency/start");
    performance.mark("keydown/start");
    state.keydown = 1;
    queueMicrotask(markKeyDownEnd);
  }
  inputLatency2.onKeyDown = onKeyDown;
  function markKeyDownEnd() {
    if (state.keydown === 1) {
      performance.mark("keydown/end");
      state.keydown = 2;
    }
  }
  function onBeforeInput() {
    performance.mark("input/start");
    state.input = 1;
    scheduleRecordIfFinishedTask();
  }
  inputLatency2.onBeforeInput = onBeforeInput;
  function onInput() {
    if (state.input === 0) {
      onBeforeInput();
    }
    queueMicrotask(markInputEnd);
  }
  inputLatency2.onInput = onInput;
  function markInputEnd() {
    if (state.input === 1) {
      performance.mark("input/end");
      state.input = 2;
    }
  }
  function onKeyUp() {
    recordIfFinished();
  }
  inputLatency2.onKeyUp = onKeyUp;
  function onSelectionChange() {
    recordIfFinished();
  }
  inputLatency2.onSelectionChange = onSelectionChange;
  function onRenderStart() {
    if (state.keydown === 2 && state.input === 2 && state.render === 0) {
      performance.mark("render/start");
      state.render = 1;
      queueMicrotask(markRenderEnd);
      scheduleRecordIfFinishedTask();
    }
  }
  inputLatency2.onRenderStart = onRenderStart;
  function markRenderEnd() {
    if (state.render === 1) {
      performance.mark("render/end");
      state.render = 2;
    }
  }
  function scheduleRecordIfFinishedTask() {
    setTimeout(recordIfFinished);
  }
  function recordIfFinished() {
    if (state.keydown === 2 && state.input === 2 && state.render === 2) {
      performance.mark("inputlatency/end");
      performance.measure("keydown", "keydown/start", "keydown/end");
      performance.measure("input", "input/start", "input/end");
      performance.measure("render", "render/start", "render/end");
      performance.measure("inputlatency", "inputlatency/start", "inputlatency/end");
      addMeasure("keydown", totalKeydownTime);
      addMeasure("input", totalInputTime);
      addMeasure("render", totalRenderTime);
      addMeasure("inputlatency", totalInputLatencyTime);
      measurementsCount++;
      reset();
    }
  }
  function addMeasure(entryName, cumulativeMeasurement) {
    const duration = performance.getEntriesByName(entryName)[0].duration;
    cumulativeMeasurement.total += duration;
    cumulativeMeasurement.min = Math.min(cumulativeMeasurement.min, duration);
    cumulativeMeasurement.max = Math.max(cumulativeMeasurement.max, duration);
  }
  function reset() {
    performance.clearMarks("keydown/start");
    performance.clearMarks("keydown/end");
    performance.clearMarks("input/start");
    performance.clearMarks("input/end");
    performance.clearMarks("render/start");
    performance.clearMarks("render/end");
    performance.clearMarks("inputlatency/start");
    performance.clearMarks("inputlatency/end");
    performance.clearMeasures("keydown");
    performance.clearMeasures("input");
    performance.clearMeasures("render");
    performance.clearMeasures("inputlatency");
    state.keydown = 0;
    state.input = 0;
    state.render = 0;
  }
  function getAndClearMeasurements() {
    if (measurementsCount === 0) {
      return void 0;
    }
    const result = {
      keydown: cumulativeToFinalMeasurement(totalKeydownTime),
      input: cumulativeToFinalMeasurement(totalInputTime),
      render: cumulativeToFinalMeasurement(totalRenderTime),
      total: cumulativeToFinalMeasurement(totalInputLatencyTime),
      sampleCount: measurementsCount
    };
    clearCumulativeMeasurement(totalKeydownTime);
    clearCumulativeMeasurement(totalInputTime);
    clearCumulativeMeasurement(totalRenderTime);
    clearCumulativeMeasurement(totalInputLatencyTime);
    measurementsCount = 0;
    return result;
  }
  inputLatency2.getAndClearMeasurements = getAndClearMeasurements;
  function cumulativeToFinalMeasurement(cumulative) {
    return {
      average: cumulative.total / measurementsCount,
      max: cumulative.max,
      min: cumulative.min
    };
  }
  function clearCumulativeMeasurement(cumulative) {
    cumulative.total = 0;
    cumulative.min = Number.MAX_VALUE;
    cumulative.max = 0;
  }
})(inputLatency || (inputLatency = {}));

// out-build/vs/base/browser/domStylesheets.js
var globalStylesheets = /* @__PURE__ */ new Map();
function $TZ(node) {
  return globalStylesheets.has(node);
}
function $UZ() {
  return new WrappedStyleElement();
}
var WrappedStyleElement = class {
  constructor() {
    this.a = "";
    this.b = void 0;
  }
  setStyle(cssStyle) {
    if (cssStyle === this.a) {
      return;
    }
    this.a = cssStyle;
    if (!this.b) {
      this.b = $VZ($Y.document.head, (s) => s.innerText = cssStyle);
    } else {
      this.b.innerText = cssStyle;
    }
  }
  dispose() {
    if (this.b) {
      this.b.remove();
      this.b = void 0;
    }
  }
};
function $VZ(container2 = $Y.document.head, beforeAppend, disposableStore) {
  const style = document.createElement("style");
  style.type = "text/css";
  style.media = "screen";
  beforeAppend?.(style);
  container2.appendChild(style);
  if (disposableStore) {
    disposableStore.add($1c(() => style.remove()));
  }
  if (container2 === $Y.document.head) {
    const globalStylesheetClones = /* @__PURE__ */ new Set();
    globalStylesheets.set(style, globalStylesheetClones);
    for (const { window: targetWindow, disposables } of getWindows()) {
      if (targetWindow === $Y) {
        continue;
      }
      const cloneDisposable = disposables.add(cloneGlobalStyleSheet(style, globalStylesheetClones, targetWindow));
      disposableStore?.add(cloneDisposable);
    }
  }
  return style;
}
function $WZ(targetWindow) {
  const disposables = new $2c();
  for (const [globalStylesheet, clonedGlobalStylesheets] of globalStylesheets) {
    disposables.add(cloneGlobalStyleSheet(globalStylesheet, clonedGlobalStylesheets, targetWindow));
  }
  return disposables;
}
function cloneGlobalStyleSheet(globalStylesheet, globalStylesheetClones, targetWindow) {
  const disposables = new $2c();
  const clone2 = globalStylesheet.cloneNode(true);
  targetWindow.document.head.appendChild(clone2);
  disposables.add($1c(() => clone2.remove()));
  for (const rule of getDynamicStyleSheetRules(globalStylesheet)) {
    clone2.sheet?.insertRule(rule.cssText, clone2.sheet?.cssRules.length);
  }
  disposables.add($Rj.observe(globalStylesheet, disposables, { childList: true })(() => {
    clone2.textContent = globalStylesheet.textContent;
  }));
  globalStylesheetClones.add(clone2);
  disposables.add($1c(() => globalStylesheetClones.delete(clone2)));
  return disposables;
}
var _sharedStyleSheet = null;
function getSharedStyleSheet() {
  if (!_sharedStyleSheet) {
    _sharedStyleSheet = $VZ();
  }
  return _sharedStyleSheet;
}
function getDynamicStyleSheetRules(style) {
  if (style?.sheet?.rules) {
    return style.sheet.rules;
  }
  if (style?.sheet?.cssRules) {
    return style.sheet.cssRules;
  }
  return [];
}
function $XZ(selector, cssText, style = getSharedStyleSheet()) {
  if (!style || !cssText) {
    return;
  }
  style.sheet?.insertRule(`${selector} {${cssText}}`, 0);
  for (const clonedGlobalStylesheet of globalStylesheets.get(style) ?? []) {
    $XZ(selector, cssText, clonedGlobalStylesheet);
  }
}
function $YZ(ruleName, style = getSharedStyleSheet()) {
  if (!style) {
    return;
  }
  const rules = getDynamicStyleSheetRules(style);
  const toDelete = [];
  for (let i2 = 0; i2 < rules.length; i2++) {
    const rule = rules[i2];
    if (isCSSStyleRule(rule) && rule.selectorText.indexOf(ruleName) !== -1) {
      toDelete.push(i2);
    }
  }
  for (let i2 = toDelete.length - 1; i2 >= 0; i2--) {
    style.sheet?.deleteRule(toDelete[i2]);
  }
  for (const clonedGlobalStylesheet of globalStylesheets.get(style) ?? []) {
    $YZ(ruleName, clonedGlobalStylesheet);
  }
}
function isCSSStyleRule(rule) {
  return typeof rule.selectorText === "string";
}

// out-build/vs/base/browser/globalPointerMoveMonitor.js
var $pZ = class {
  constructor() {
    this.a = new $2c();
    this.b = null;
    this.c = null;
  }
  dispose() {
    this.stopMonitoring(false);
    this.a.dispose();
  }
  stopMonitoring(invokeStopCallback, browserEvent) {
    if (!this.isMonitoring()) {
      return;
    }
    this.a.clear();
    this.b = null;
    const onStopCallback = this.c;
    this.c = null;
    if (invokeStopCallback && onStopCallback) {
      onStopCallback(browserEvent);
    }
  }
  isMonitoring() {
    return !!this.b;
  }
  startMonitoring(initialElement, pointerId, initialButtons, pointerMoveCallback, onStopCallback) {
    if (this.isMonitoring()) {
      this.stopMonitoring(false);
    }
    this.b = pointerMoveCallback;
    this.c = onStopCallback;
    let eventSource = initialElement;
    try {
      initialElement.setPointerCapture(pointerId);
      this.a.add($1c(() => {
        try {
          initialElement.releasePointerCapture(pointerId);
        } catch (err) {
        }
      }));
    } catch (err) {
      eventSource = getWindow(initialElement);
    }
    this.a.add($_i(eventSource, $7j.POINTER_MOVE, (e) => {
      if (e.buttons !== initialButtons) {
        this.stopMonitoring(true);
        return;
      }
      e.preventDefault();
      this.b(e);
    }));
    this.a.add($_i(eventSource, $7j.POINTER_UP, (e) => this.stopMonitoring(true)));
  }
};

// out-build/vs/base/common/color.js
function roundFloat(number, decimalPoints) {
  const decimal = Math.pow(10, decimalPoints);
  return Math.round(number * decimal) / decimal;
}
var $Sn = class {
  constructor(r2, g, b, a = 1) {
    this._rgbaBrand = void 0;
    this.r = Math.min(255, Math.max(0, r2)) | 0;
    this.g = Math.min(255, Math.max(0, g)) | 0;
    this.b = Math.min(255, Math.max(0, b)) | 0;
    this.a = roundFloat(Math.max(Math.min(1, a), 0), 3);
  }
  static equals(a, b) {
    return a.r === b.r && a.g === b.g && a.b === b.b && a.a === b.a;
  }
};
var $Tn = class _$Tn {
  constructor(h3, s, l, a) {
    this._hslaBrand = void 0;
    this.h = Math.max(Math.min(360, h3), 0) | 0;
    this.s = roundFloat(Math.max(Math.min(1, s), 0), 3);
    this.l = roundFloat(Math.max(Math.min(1, l), 0), 3);
    this.a = roundFloat(Math.max(Math.min(1, a), 0), 3);
  }
  static equals(a, b) {
    return a.h === b.h && a.s === b.s && a.l === b.l && a.a === b.a;
  }
  /**
   * Converts an RGB color value to HSL. Conversion formula
   * adapted from http://en.wikipedia.org/wiki/HSL_color_space.
   * Assumes r, g, and b are contained in the set [0, 255] and
   * returns h in the set [0, 360], s, and l in the set [0, 1].
   */
  static fromRGBA(rgba) {
    const r2 = rgba.r / 255;
    const g = rgba.g / 255;
    const b = rgba.b / 255;
    const a = rgba.a;
    const max = Math.max(r2, g, b);
    const min = Math.min(r2, g, b);
    let h3 = 0;
    let s = 0;
    const l = (min + max) / 2;
    const chroma = max - min;
    if (chroma > 0) {
      s = Math.min(l <= 0.5 ? chroma / (2 * l) : chroma / (2 - 2 * l), 1);
      switch (max) {
        case r2:
          h3 = (g - b) / chroma + (g < b ? 6 : 0);
          break;
        case g:
          h3 = (b - r2) / chroma + 2;
          break;
        case b:
          h3 = (r2 - g) / chroma + 4;
          break;
      }
      h3 *= 60;
      h3 = Math.round(h3);
    }
    return new _$Tn(h3, s, l, a);
  }
  static i(p, q, t) {
    if (t < 0) {
      t += 1;
    }
    if (t > 1) {
      t -= 1;
    }
    if (t < 1 / 6) {
      return p + (q - p) * 6 * t;
    }
    if (t < 1 / 2) {
      return q;
    }
    if (t < 2 / 3) {
      return p + (q - p) * (2 / 3 - t) * 6;
    }
    return p;
  }
  /**
   * Converts an HSL color value to RGB. Conversion formula
   * adapted from http://en.wikipedia.org/wiki/HSL_color_space.
   * Assumes h in the set [0, 360] s, and l are contained in the set [0, 1] and
   * returns r, g, and b in the set [0, 255].
   */
  static toRGBA(hsla) {
    const h3 = hsla.h / 360;
    const { s, l, a } = hsla;
    let r2, g, b;
    if (s === 0) {
      r2 = g = b = l;
    } else {
      const q = l < 0.5 ? l * (1 + s) : l + s - l * s;
      const p = 2 * l - q;
      r2 = _$Tn.i(p, q, h3 + 1 / 3);
      g = _$Tn.i(p, q, h3);
      b = _$Tn.i(p, q, h3 - 1 / 3);
    }
    return new $Sn(Math.round(r2 * 255), Math.round(g * 255), Math.round(b * 255), a);
  }
};
var $Un = class _$Un {
  constructor(h3, s, v, a) {
    this._hsvaBrand = void 0;
    this.h = Math.max(Math.min(360, h3), 0) | 0;
    this.s = roundFloat(Math.max(Math.min(1, s), 0), 3);
    this.v = roundFloat(Math.max(Math.min(1, v), 0), 3);
    this.a = roundFloat(Math.max(Math.min(1, a), 0), 3);
  }
  static equals(a, b) {
    return a.h === b.h && a.s === b.s && a.v === b.v && a.a === b.a;
  }
  // from http://www.rapidtables.com/convert/color/rgb-to-hsv.htm
  static fromRGBA(rgba) {
    const r2 = rgba.r / 255;
    const g = rgba.g / 255;
    const b = rgba.b / 255;
    const cmax = Math.max(r2, g, b);
    const cmin = Math.min(r2, g, b);
    const delta = cmax - cmin;
    const s = cmax === 0 ? 0 : delta / cmax;
    let m;
    if (delta === 0) {
      m = 0;
    } else if (cmax === r2) {
      m = ((g - b) / delta % 6 + 6) % 6;
    } else if (cmax === g) {
      m = (b - r2) / delta + 2;
    } else {
      m = (r2 - g) / delta + 4;
    }
    return new _$Un(Math.round(m * 60), s, cmax, rgba.a);
  }
  // from http://www.rapidtables.com/convert/color/hsv-to-rgb.htm
  static toRGBA(hsva) {
    const { h: h3, s, v, a } = hsva;
    const c = v * s;
    const x = c * (1 - Math.abs(h3 / 60 % 2 - 1));
    const m = v - c;
    let [r2, g, b] = [0, 0, 0];
    if (h3 < 60) {
      r2 = c;
      g = x;
    } else if (h3 < 120) {
      r2 = x;
      g = c;
    } else if (h3 < 180) {
      g = c;
      b = x;
    } else if (h3 < 240) {
      g = x;
      b = c;
    } else if (h3 < 300) {
      r2 = x;
      b = c;
    } else if (h3 <= 360) {
      r2 = c;
      b = x;
    }
    r2 = Math.round((r2 + m) * 255);
    g = Math.round((g + m) * 255);
    b = Math.round((b + m) * 255);
    return new $Sn(r2, g, b, a);
  }
};
var $Vn = class _$Vn {
  static fromHex(hex) {
    return _$Vn.Format.CSS.parseHex(hex) || _$Vn.red;
  }
  static equals(a, b) {
    if (!a && !b) {
      return true;
    }
    if (!a || !b) {
      return false;
    }
    return a.equals(b);
  }
  get hsla() {
    if (this.i) {
      return this.i;
    } else {
      return $Tn.fromRGBA(this.rgba);
    }
  }
  get hsva() {
    if (this.j) {
      return this.j;
    }
    return $Un.fromRGBA(this.rgba);
  }
  constructor(arg) {
    if (!arg) {
      throw new Error("Color needs a value");
    } else if (arg instanceof $Sn) {
      this.rgba = arg;
    } else if (arg instanceof $Tn) {
      this.i = arg;
      this.rgba = $Tn.toRGBA(arg);
    } else if (arg instanceof $Un) {
      this.j = arg;
      this.rgba = $Un.toRGBA(arg);
    } else {
      throw new Error("Invalid color ctor argument");
    }
  }
  equals(other) {
    return !!other && $Sn.equals(this.rgba, other.rgba) && $Tn.equals(this.hsla, other.hsla) && $Un.equals(this.hsva, other.hsva);
  }
  /**
   * http://www.w3.org/TR/WCAG20/#relativeluminancedef
   * Returns the number in the set [0, 1]. O => Darkest Black. 1 => Lightest white.
   */
  getRelativeLuminance() {
    const R = _$Vn.k(this.rgba.r);
    const G = _$Vn.k(this.rgba.g);
    const B = _$Vn.k(this.rgba.b);
    const luminance = 0.2126 * R + 0.7152 * G + 0.0722 * B;
    return roundFloat(luminance, 4);
  }
  /**
   * Reduces the "foreground" color on this "background" color unti it is
   * below the relative luminace ratio.
   * @returns the new foreground color
   * @see https://github.com/xtermjs/xterm.js/blob/44f9fa39ae03e2ca6d28354d88a399608686770e/src/common/Color.ts#L315
   */
  reduceRelativeLuminace(foreground, ratio) {
    let { r: fgR, g: fgG, b: fgB } = foreground.rgba;
    let cr = this.getContrastRatio(foreground);
    while (cr < ratio && (fgR > 0 || fgG > 0 || fgB > 0)) {
      fgR -= Math.max(0, Math.ceil(fgR * 0.1));
      fgG -= Math.max(0, Math.ceil(fgG * 0.1));
      fgB -= Math.max(0, Math.ceil(fgB * 0.1));
      cr = this.getContrastRatio(new _$Vn(new $Sn(fgR, fgG, fgB)));
    }
    return new _$Vn(new $Sn(fgR, fgG, fgB));
  }
  /**
   * Increases the "foreground" color on this "background" color unti it is
   * below the relative luminace ratio.
   * @returns the new foreground color
   * @see https://github.com/xtermjs/xterm.js/blob/44f9fa39ae03e2ca6d28354d88a399608686770e/src/common/Color.ts#L335
   */
  increaseRelativeLuminace(foreground, ratio) {
    let { r: fgR, g: fgG, b: fgB } = foreground.rgba;
    let cr = this.getContrastRatio(foreground);
    while (cr < ratio && (fgR < 255 || fgG < 255 || fgB < 255)) {
      fgR = Math.min(255, fgR + Math.ceil((255 - fgR) * 0.1));
      fgG = Math.min(255, fgG + Math.ceil((255 - fgG) * 0.1));
      fgB = Math.min(255, fgB + Math.ceil((255 - fgB) * 0.1));
      cr = this.getContrastRatio(new _$Vn(new $Sn(fgR, fgG, fgB)));
    }
    return new _$Vn(new $Sn(fgR, fgG, fgB));
  }
  static k(color2) {
    const c = color2 / 255;
    return c <= 0.03928 ? c / 12.92 : Math.pow((c + 0.055) / 1.055, 2.4);
  }
  /**
   * http://www.w3.org/TR/WCAG20/#contrast-ratiodef
   * Returns the contrast ration number in the set [1, 21].
   */
  getContrastRatio(another) {
    const lum1 = this.getRelativeLuminance();
    const lum2 = another.getRelativeLuminance();
    return lum1 > lum2 ? (lum1 + 0.05) / (lum2 + 0.05) : (lum2 + 0.05) / (lum1 + 0.05);
  }
  /**
   *	http://24ways.org/2010/calculating-color-contrast
   *  Return 'true' if darker color otherwise 'false'
   */
  isDarker() {
    const yiq = (this.rgba.r * 299 + this.rgba.g * 587 + this.rgba.b * 114) / 1e3;
    return yiq < 128;
  }
  /**
   *	http://24ways.org/2010/calculating-color-contrast
   *  Return 'true' if lighter color otherwise 'false'
   */
  isLighter() {
    const yiq = (this.rgba.r * 299 + this.rgba.g * 587 + this.rgba.b * 114) / 1e3;
    return yiq >= 128;
  }
  isLighterThan(another) {
    const lum1 = this.getRelativeLuminance();
    const lum2 = another.getRelativeLuminance();
    return lum1 > lum2;
  }
  isDarkerThan(another) {
    const lum1 = this.getRelativeLuminance();
    const lum2 = another.getRelativeLuminance();
    return lum1 < lum2;
  }
  /**
   * Based on xterm.js: https://github.com/xtermjs/xterm.js/blob/44f9fa39ae03e2ca6d28354d88a399608686770e/src/common/Color.ts#L288
   *
   * Given a foreground color and a background color, either increase or reduce the luminance of the
   * foreground color until the specified contrast ratio is met. If pure white or black is hit
   * without the contrast ratio being met, go the other direction using the background color as the
   * foreground color and take either the first or second result depending on which has the higher
   * contrast ratio.
   *
   * @param foreground The foreground color.
   * @param ratio The contrast ratio to achieve.
   * @returns The adjusted foreground color.
   */
  ensureConstrast(foreground, ratio) {
    const bgL = this.getRelativeLuminance();
    const fgL = foreground.getRelativeLuminance();
    const cr = this.getContrastRatio(foreground);
    if (cr < ratio) {
      if (fgL < bgL) {
        const resultA2 = this.reduceRelativeLuminace(foreground, ratio);
        const resultARatio2 = this.getContrastRatio(resultA2);
        if (resultARatio2 < ratio) {
          const resultB = this.increaseRelativeLuminace(foreground, ratio);
          const resultBRatio = this.getContrastRatio(resultB);
          return resultARatio2 > resultBRatio ? resultA2 : resultB;
        }
        return resultA2;
      }
      const resultA = this.increaseRelativeLuminace(foreground, ratio);
      const resultARatio = this.getContrastRatio(resultA);
      if (resultARatio < ratio) {
        const resultB = this.reduceRelativeLuminace(foreground, ratio);
        const resultBRatio = this.getContrastRatio(resultB);
        return resultARatio > resultBRatio ? resultA : resultB;
      }
      return resultA;
    }
    return foreground;
  }
  lighten(factor2) {
    return new _$Vn(new $Tn(this.hsla.h, this.hsla.s, this.hsla.l + this.hsla.l * factor2, this.hsla.a));
  }
  darken(factor2) {
    return new _$Vn(new $Tn(this.hsla.h, this.hsla.s, this.hsla.l - this.hsla.l * factor2, this.hsla.a));
  }
  transparent(factor2) {
    const { r: r2, g, b, a } = this.rgba;
    return new _$Vn(new $Sn(r2, g, b, a * factor2));
  }
  isTransparent() {
    return this.rgba.a === 0;
  }
  isOpaque() {
    return this.rgba.a === 1;
  }
  opposite() {
    return new _$Vn(new $Sn(255 - this.rgba.r, 255 - this.rgba.g, 255 - this.rgba.b, this.rgba.a));
  }
  blend(c) {
    const rgba = c.rgba;
    const thisA = this.rgba.a;
    const colorA = rgba.a;
    const a = thisA + colorA * (1 - thisA);
    if (a < 1e-6) {
      return _$Vn.transparent;
    }
    const r2 = this.rgba.r * thisA / a + rgba.r * colorA * (1 - thisA) / a;
    const g = this.rgba.g * thisA / a + rgba.g * colorA * (1 - thisA) / a;
    const b = this.rgba.b * thisA / a + rgba.b * colorA * (1 - thisA) / a;
    return new _$Vn(new $Sn(r2, g, b, a));
  }
  makeOpaque(opaqueBackground) {
    if (this.isOpaque() || opaqueBackground.rgba.a !== 1) {
      return this;
    }
    const { r: r2, g, b, a } = this.rgba;
    return new _$Vn(new $Sn(opaqueBackground.rgba.r - a * (opaqueBackground.rgba.r - r2), opaqueBackground.rgba.g - a * (opaqueBackground.rgba.g - g), opaqueBackground.rgba.b - a * (opaqueBackground.rgba.b - b), 1));
  }
  flatten(...backgrounds) {
    const background = backgrounds.reduceRight((accumulator, color2) => {
      return _$Vn.o(color2, accumulator);
    });
    return _$Vn.o(this, background);
  }
  static o(foreground, background) {
    const backgroundAlpha = 1 - foreground.rgba.a;
    return new _$Vn(new $Sn(backgroundAlpha * background.rgba.r + foreground.rgba.a * foreground.rgba.r, backgroundAlpha * background.rgba.g + foreground.rgba.a * foreground.rgba.g, backgroundAlpha * background.rgba.b + foreground.rgba.a * foreground.rgba.b));
  }
  toString() {
    if (!this.u) {
      this.u = _$Vn.Format.CSS.format(this);
    }
    return this.u;
  }
  toNumber24Bit() {
    if (!this.w) {
      this.w = (this.rgba.r << 24 | this.rgba.g << 16 | this.rgba.b << 8 | this.rgba.a * 255 << 0) >>> 0;
    }
    return this.w;
  }
  static getLighterColor(of, relative, factor2) {
    if (of.isLighterThan(relative)) {
      return of;
    }
    factor2 = factor2 ? factor2 : 0.5;
    const lum1 = of.getRelativeLuminance();
    const lum2 = relative.getRelativeLuminance();
    factor2 = factor2 * (lum2 - lum1) / lum2;
    return of.lighten(factor2);
  }
  static getDarkerColor(of, relative, factor2) {
    if (of.isDarkerThan(relative)) {
      return of;
    }
    factor2 = factor2 ? factor2 : 0.5;
    const lum1 = of.getRelativeLuminance();
    const lum2 = relative.getRelativeLuminance();
    factor2 = factor2 * (lum1 - lum2) / lum1;
    return of.darken(factor2);
  }
  static {
    this.white = new _$Vn(new $Sn(255, 255, 255, 1));
  }
  static {
    this.black = new _$Vn(new $Sn(0, 0, 0, 1));
  }
  static {
    this.red = new _$Vn(new $Sn(255, 0, 0, 1));
  }
  static {
    this.blue = new _$Vn(new $Sn(0, 0, 255, 1));
  }
  static {
    this.green = new _$Vn(new $Sn(0, 255, 0, 1));
  }
  static {
    this.cyan = new _$Vn(new $Sn(0, 255, 255, 1));
  }
  static {
    this.lightgrey = new _$Vn(new $Sn(211, 211, 211, 1));
  }
  static {
    this.transparent = new _$Vn(new $Sn(0, 0, 0, 0));
  }
};
(function($Vn2) {
  let Format;
  (function(Format2) {
    let CSS2;
    (function(CSS3) {
      function formatRGB(color2) {
        if (color2.rgba.a === 1) {
          return `rgb(${color2.rgba.r}, ${color2.rgba.g}, ${color2.rgba.b})`;
        }
        return $Vn2.Format.CSS.formatRGBA(color2);
      }
      CSS3.formatRGB = formatRGB;
      function formatRGBA(color2) {
        return `rgba(${color2.rgba.r}, ${color2.rgba.g}, ${color2.rgba.b}, ${+color2.rgba.a.toFixed(2)})`;
      }
      CSS3.formatRGBA = formatRGBA;
      function formatHSL(color2) {
        if (color2.hsla.a === 1) {
          return `hsl(${color2.hsla.h}, ${(color2.hsla.s * 100).toFixed(2)}%, ${(color2.hsla.l * 100).toFixed(2)}%)`;
        }
        return $Vn2.Format.CSS.formatHSLA(color2);
      }
      CSS3.formatHSL = formatHSL;
      function formatHSLA(color2) {
        return `hsla(${color2.hsla.h}, ${(color2.hsla.s * 100).toFixed(2)}%, ${(color2.hsla.l * 100).toFixed(2)}%, ${color2.hsla.a.toFixed(2)})`;
      }
      CSS3.formatHSLA = formatHSLA;
      function _toTwoDigitHex(n) {
        const r2 = n.toString(16);
        return r2.length !== 2 ? "0" + r2 : r2;
      }
      function formatHex(color2) {
        return `#${_toTwoDigitHex(color2.rgba.r)}${_toTwoDigitHex(color2.rgba.g)}${_toTwoDigitHex(color2.rgba.b)}`;
      }
      CSS3.formatHex = formatHex;
      function formatHexA(color2, compact = false) {
        if (compact && color2.rgba.a === 1) {
          return $Vn2.Format.CSS.formatHex(color2);
        }
        return `#${_toTwoDigitHex(color2.rgba.r)}${_toTwoDigitHex(color2.rgba.g)}${_toTwoDigitHex(color2.rgba.b)}${_toTwoDigitHex(Math.round(color2.rgba.a * 255))}`;
      }
      CSS3.formatHexA = formatHexA;
      function format2(color2) {
        if (color2.isOpaque()) {
          return $Vn2.Format.CSS.formatHex(color2);
        }
        return $Vn2.Format.CSS.formatRGBA(color2);
      }
      CSS3.format = format2;
      function parse4(css) {
        if (css === "transparent") {
          return $Vn2.transparent;
        }
        if (css.startsWith("#")) {
          return parseHex(css);
        }
        if (css.startsWith("rgba(")) {
          const color2 = css.match(/rgba\((?<r>(?:\+|-)?\d+), *(?<g>(?:\+|-)?\d+), *(?<b>(?:\+|-)?\d+), *(?<a>(?:\+|-)?\d+(\.\d+)?)\)/);
          if (!color2) {
            throw new Error("Invalid color format " + css);
          }
          const r2 = parseInt(color2.groups?.r ?? "0");
          const g = parseInt(color2.groups?.g ?? "0");
          const b = parseInt(color2.groups?.b ?? "0");
          const a = parseFloat(color2.groups?.a ?? "0");
          return new $Vn2(new $Sn(r2, g, b, a));
        }
        if (css.startsWith("rgb(")) {
          const color2 = css.match(/rgb\((?<r>(?:\+|-)?\d+), *(?<g>(?:\+|-)?\d+), *(?<b>(?:\+|-)?\d+)\)/);
          if (!color2) {
            throw new Error("Invalid color format " + css);
          }
          const r2 = parseInt(color2.groups?.r ?? "0");
          const g = parseInt(color2.groups?.g ?? "0");
          const b = parseInt(color2.groups?.b ?? "0");
          return new $Vn2(new $Sn(r2, g, b));
        }
        return parseNamedKeyword(css);
      }
      CSS3.parse = parse4;
      function parseNamedKeyword(css) {
        switch (css) {
          case "aliceblue":
            return new $Vn2(new $Sn(240, 248, 255, 1));
          case "antiquewhite":
            return new $Vn2(new $Sn(250, 235, 215, 1));
          case "aqua":
            return new $Vn2(new $Sn(0, 255, 255, 1));
          case "aquamarine":
            return new $Vn2(new $Sn(127, 255, 212, 1));
          case "azure":
            return new $Vn2(new $Sn(240, 255, 255, 1));
          case "beige":
            return new $Vn2(new $Sn(245, 245, 220, 1));
          case "bisque":
            return new $Vn2(new $Sn(255, 228, 196, 1));
          case "black":
            return new $Vn2(new $Sn(0, 0, 0, 1));
          case "blanchedalmond":
            return new $Vn2(new $Sn(255, 235, 205, 1));
          case "blue":
            return new $Vn2(new $Sn(0, 0, 255, 1));
          case "blueviolet":
            return new $Vn2(new $Sn(138, 43, 226, 1));
          case "brown":
            return new $Vn2(new $Sn(165, 42, 42, 1));
          case "burlywood":
            return new $Vn2(new $Sn(222, 184, 135, 1));
          case "cadetblue":
            return new $Vn2(new $Sn(95, 158, 160, 1));
          case "chartreuse":
            return new $Vn2(new $Sn(127, 255, 0, 1));
          case "chocolate":
            return new $Vn2(new $Sn(210, 105, 30, 1));
          case "coral":
            return new $Vn2(new $Sn(255, 127, 80, 1));
          case "cornflowerblue":
            return new $Vn2(new $Sn(100, 149, 237, 1));
          case "cornsilk":
            return new $Vn2(new $Sn(255, 248, 220, 1));
          case "crimson":
            return new $Vn2(new $Sn(220, 20, 60, 1));
          case "cyan":
            return new $Vn2(new $Sn(0, 255, 255, 1));
          case "darkblue":
            return new $Vn2(new $Sn(0, 0, 139, 1));
          case "darkcyan":
            return new $Vn2(new $Sn(0, 139, 139, 1));
          case "darkgoldenrod":
            return new $Vn2(new $Sn(184, 134, 11, 1));
          case "darkgray":
            return new $Vn2(new $Sn(169, 169, 169, 1));
          case "darkgreen":
            return new $Vn2(new $Sn(0, 100, 0, 1));
          case "darkgrey":
            return new $Vn2(new $Sn(169, 169, 169, 1));
          case "darkkhaki":
            return new $Vn2(new $Sn(189, 183, 107, 1));
          case "darkmagenta":
            return new $Vn2(new $Sn(139, 0, 139, 1));
          case "darkolivegreen":
            return new $Vn2(new $Sn(85, 107, 47, 1));
          case "darkorange":
            return new $Vn2(new $Sn(255, 140, 0, 1));
          case "darkorchid":
            return new $Vn2(new $Sn(153, 50, 204, 1));
          case "darkred":
            return new $Vn2(new $Sn(139, 0, 0, 1));
          case "darksalmon":
            return new $Vn2(new $Sn(233, 150, 122, 1));
          case "darkseagreen":
            return new $Vn2(new $Sn(143, 188, 143, 1));
          case "darkslateblue":
            return new $Vn2(new $Sn(72, 61, 139, 1));
          case "darkslategray":
            return new $Vn2(new $Sn(47, 79, 79, 1));
          case "darkslategrey":
            return new $Vn2(new $Sn(47, 79, 79, 1));
          case "darkturquoise":
            return new $Vn2(new $Sn(0, 206, 209, 1));
          case "darkviolet":
            return new $Vn2(new $Sn(148, 0, 211, 1));
          case "deeppink":
            return new $Vn2(new $Sn(255, 20, 147, 1));
          case "deepskyblue":
            return new $Vn2(new $Sn(0, 191, 255, 1));
          case "dimgray":
            return new $Vn2(new $Sn(105, 105, 105, 1));
          case "dimgrey":
            return new $Vn2(new $Sn(105, 105, 105, 1));
          case "dodgerblue":
            return new $Vn2(new $Sn(30, 144, 255, 1));
          case "firebrick":
            return new $Vn2(new $Sn(178, 34, 34, 1));
          case "floralwhite":
            return new $Vn2(new $Sn(255, 250, 240, 1));
          case "forestgreen":
            return new $Vn2(new $Sn(34, 139, 34, 1));
          case "fuchsia":
            return new $Vn2(new $Sn(255, 0, 255, 1));
          case "gainsboro":
            return new $Vn2(new $Sn(220, 220, 220, 1));
          case "ghostwhite":
            return new $Vn2(new $Sn(248, 248, 255, 1));
          case "gold":
            return new $Vn2(new $Sn(255, 215, 0, 1));
          case "goldenrod":
            return new $Vn2(new $Sn(218, 165, 32, 1));
          case "gray":
            return new $Vn2(new $Sn(128, 128, 128, 1));
          case "green":
            return new $Vn2(new $Sn(0, 128, 0, 1));
          case "greenyellow":
            return new $Vn2(new $Sn(173, 255, 47, 1));
          case "grey":
            return new $Vn2(new $Sn(128, 128, 128, 1));
          case "honeydew":
            return new $Vn2(new $Sn(240, 255, 240, 1));
          case "hotpink":
            return new $Vn2(new $Sn(255, 105, 180, 1));
          case "indianred":
            return new $Vn2(new $Sn(205, 92, 92, 1));
          case "indigo":
            return new $Vn2(new $Sn(75, 0, 130, 1));
          case "ivory":
            return new $Vn2(new $Sn(255, 255, 240, 1));
          case "khaki":
            return new $Vn2(new $Sn(240, 230, 140, 1));
          case "lavender":
            return new $Vn2(new $Sn(230, 230, 250, 1));
          case "lavenderblush":
            return new $Vn2(new $Sn(255, 240, 245, 1));
          case "lawngreen":
            return new $Vn2(new $Sn(124, 252, 0, 1));
          case "lemonchiffon":
            return new $Vn2(new $Sn(255, 250, 205, 1));
          case "lightblue":
            return new $Vn2(new $Sn(173, 216, 230, 1));
          case "lightcoral":
            return new $Vn2(new $Sn(240, 128, 128, 1));
          case "lightcyan":
            return new $Vn2(new $Sn(224, 255, 255, 1));
          case "lightgoldenrodyellow":
            return new $Vn2(new $Sn(250, 250, 210, 1));
          case "lightgray":
            return new $Vn2(new $Sn(211, 211, 211, 1));
          case "lightgreen":
            return new $Vn2(new $Sn(144, 238, 144, 1));
          case "lightgrey":
            return new $Vn2(new $Sn(211, 211, 211, 1));
          case "lightpink":
            return new $Vn2(new $Sn(255, 182, 193, 1));
          case "lightsalmon":
            return new $Vn2(new $Sn(255, 160, 122, 1));
          case "lightseagreen":
            return new $Vn2(new $Sn(32, 178, 170, 1));
          case "lightskyblue":
            return new $Vn2(new $Sn(135, 206, 250, 1));
          case "lightslategray":
            return new $Vn2(new $Sn(119, 136, 153, 1));
          case "lightslategrey":
            return new $Vn2(new $Sn(119, 136, 153, 1));
          case "lightsteelblue":
            return new $Vn2(new $Sn(176, 196, 222, 1));
          case "lightyellow":
            return new $Vn2(new $Sn(255, 255, 224, 1));
          case "lime":
            return new $Vn2(new $Sn(0, 255, 0, 1));
          case "limegreen":
            return new $Vn2(new $Sn(50, 205, 50, 1));
          case "linen":
            return new $Vn2(new $Sn(250, 240, 230, 1));
          case "magenta":
            return new $Vn2(new $Sn(255, 0, 255, 1));
          case "maroon":
            return new $Vn2(new $Sn(128, 0, 0, 1));
          case "mediumaquamarine":
            return new $Vn2(new $Sn(102, 205, 170, 1));
          case "mediumblue":
            return new $Vn2(new $Sn(0, 0, 205, 1));
          case "mediumorchid":
            return new $Vn2(new $Sn(186, 85, 211, 1));
          case "mediumpurple":
            return new $Vn2(new $Sn(147, 112, 219, 1));
          case "mediumseagreen":
            return new $Vn2(new $Sn(60, 179, 113, 1));
          case "mediumslateblue":
            return new $Vn2(new $Sn(123, 104, 238, 1));
          case "mediumspringgreen":
            return new $Vn2(new $Sn(0, 250, 154, 1));
          case "mediumturquoise":
            return new $Vn2(new $Sn(72, 209, 204, 1));
          case "mediumvioletred":
            return new $Vn2(new $Sn(199, 21, 133, 1));
          case "midnightblue":
            return new $Vn2(new $Sn(25, 25, 112, 1));
          case "mintcream":
            return new $Vn2(new $Sn(245, 255, 250, 1));
          case "mistyrose":
            return new $Vn2(new $Sn(255, 228, 225, 1));
          case "moccasin":
            return new $Vn2(new $Sn(255, 228, 181, 1));
          case "navajowhite":
            return new $Vn2(new $Sn(255, 222, 173, 1));
          case "navy":
            return new $Vn2(new $Sn(0, 0, 128, 1));
          case "oldlace":
            return new $Vn2(new $Sn(253, 245, 230, 1));
          case "olive":
            return new $Vn2(new $Sn(128, 128, 0, 1));
          case "olivedrab":
            return new $Vn2(new $Sn(107, 142, 35, 1));
          case "orange":
            return new $Vn2(new $Sn(255, 165, 0, 1));
          case "orangered":
            return new $Vn2(new $Sn(255, 69, 0, 1));
          case "orchid":
            return new $Vn2(new $Sn(218, 112, 214, 1));
          case "palegoldenrod":
            return new $Vn2(new $Sn(238, 232, 170, 1));
          case "palegreen":
            return new $Vn2(new $Sn(152, 251, 152, 1));
          case "paleturquoise":
            return new $Vn2(new $Sn(175, 238, 238, 1));
          case "palevioletred":
            return new $Vn2(new $Sn(219, 112, 147, 1));
          case "papayawhip":
            return new $Vn2(new $Sn(255, 239, 213, 1));
          case "peachpuff":
            return new $Vn2(new $Sn(255, 218, 185, 1));
          case "peru":
            return new $Vn2(new $Sn(205, 133, 63, 1));
          case "pink":
            return new $Vn2(new $Sn(255, 192, 203, 1));
          case "plum":
            return new $Vn2(new $Sn(221, 160, 221, 1));
          case "powderblue":
            return new $Vn2(new $Sn(176, 224, 230, 1));
          case "purple":
            return new $Vn2(new $Sn(128, 0, 128, 1));
          case "rebeccapurple":
            return new $Vn2(new $Sn(102, 51, 153, 1));
          case "red":
            return new $Vn2(new $Sn(255, 0, 0, 1));
          case "rosybrown":
            return new $Vn2(new $Sn(188, 143, 143, 1));
          case "royalblue":
            return new $Vn2(new $Sn(65, 105, 225, 1));
          case "saddlebrown":
            return new $Vn2(new $Sn(139, 69, 19, 1));
          case "salmon":
            return new $Vn2(new $Sn(250, 128, 114, 1));
          case "sandybrown":
            return new $Vn2(new $Sn(244, 164, 96, 1));
          case "seagreen":
            return new $Vn2(new $Sn(46, 139, 87, 1));
          case "seashell":
            return new $Vn2(new $Sn(255, 245, 238, 1));
          case "sienna":
            return new $Vn2(new $Sn(160, 82, 45, 1));
          case "silver":
            return new $Vn2(new $Sn(192, 192, 192, 1));
          case "skyblue":
            return new $Vn2(new $Sn(135, 206, 235, 1));
          case "slateblue":
            return new $Vn2(new $Sn(106, 90, 205, 1));
          case "slategray":
            return new $Vn2(new $Sn(112, 128, 144, 1));
          case "slategrey":
            return new $Vn2(new $Sn(112, 128, 144, 1));
          case "snow":
            return new $Vn2(new $Sn(255, 250, 250, 1));
          case "springgreen":
            return new $Vn2(new $Sn(0, 255, 127, 1));
          case "steelblue":
            return new $Vn2(new $Sn(70, 130, 180, 1));
          case "tan":
            return new $Vn2(new $Sn(210, 180, 140, 1));
          case "teal":
            return new $Vn2(new $Sn(0, 128, 128, 1));
          case "thistle":
            return new $Vn2(new $Sn(216, 191, 216, 1));
          case "tomato":
            return new $Vn2(new $Sn(255, 99, 71, 1));
          case "turquoise":
            return new $Vn2(new $Sn(64, 224, 208, 1));
          case "violet":
            return new $Vn2(new $Sn(238, 130, 238, 1));
          case "wheat":
            return new $Vn2(new $Sn(245, 222, 179, 1));
          case "white":
            return new $Vn2(new $Sn(255, 255, 255, 1));
          case "whitesmoke":
            return new $Vn2(new $Sn(245, 245, 245, 1));
          case "yellow":
            return new $Vn2(new $Sn(255, 255, 0, 1));
          case "yellowgreen":
            return new $Vn2(new $Sn(154, 205, 50, 1));
          default:
            return null;
        }
      }
      function parseHex(hex) {
        const length = hex.length;
        if (length === 0) {
          return null;
        }
        if (hex.charCodeAt(0) !== 35) {
          return null;
        }
        if (length === 7) {
          const r2 = 16 * _parseHexDigit(hex.charCodeAt(1)) + _parseHexDigit(hex.charCodeAt(2));
          const g = 16 * _parseHexDigit(hex.charCodeAt(3)) + _parseHexDigit(hex.charCodeAt(4));
          const b = 16 * _parseHexDigit(hex.charCodeAt(5)) + _parseHexDigit(hex.charCodeAt(6));
          return new $Vn2(new $Sn(r2, g, b, 1));
        }
        if (length === 9) {
          const r2 = 16 * _parseHexDigit(hex.charCodeAt(1)) + _parseHexDigit(hex.charCodeAt(2));
          const g = 16 * _parseHexDigit(hex.charCodeAt(3)) + _parseHexDigit(hex.charCodeAt(4));
          const b = 16 * _parseHexDigit(hex.charCodeAt(5)) + _parseHexDigit(hex.charCodeAt(6));
          const a = 16 * _parseHexDigit(hex.charCodeAt(7)) + _parseHexDigit(hex.charCodeAt(8));
          return new $Vn2(new $Sn(r2, g, b, a / 255));
        }
        if (length === 4) {
          const r2 = _parseHexDigit(hex.charCodeAt(1));
          const g = _parseHexDigit(hex.charCodeAt(2));
          const b = _parseHexDigit(hex.charCodeAt(3));
          return new $Vn2(new $Sn(16 * r2 + r2, 16 * g + g, 16 * b + b));
        }
        if (length === 5) {
          const r2 = _parseHexDigit(hex.charCodeAt(1));
          const g = _parseHexDigit(hex.charCodeAt(2));
          const b = _parseHexDigit(hex.charCodeAt(3));
          const a = _parseHexDigit(hex.charCodeAt(4));
          return new $Vn2(new $Sn(16 * r2 + r2, 16 * g + g, 16 * b + b, (16 * a + a) / 255));
        }
        return null;
      }
      CSS3.parseHex = parseHex;
      function _parseHexDigit(charCode) {
        switch (charCode) {
          case 48:
            return 0;
          case 49:
            return 1;
          case 50:
            return 2;
          case 51:
            return 3;
          case 52:
            return 4;
          case 53:
            return 5;
          case 54:
            return 6;
          case 55:
            return 7;
          case 56:
            return 8;
          case 57:
            return 9;
          case 97:
            return 10;
          case 65:
            return 10;
          case 98:
            return 11;
          case 66:
            return 11;
          case 99:
            return 12;
          case 67:
            return 12;
          case 100:
            return 13;
          case 68:
            return 13;
          case 101:
            return 14;
          case 69:
            return 14;
          case 102:
            return 15;
          case 70:
            return 15;
        }
        return 0;
      }
    })(CSS2 = Format2.CSS || (Format2.CSS = {}));
  })(Format = $Vn2.Format || ($Vn2.Format = {}));
})($Vn || ($Vn = {}));

// out-build/vs/platform/theme/common/colorUtils.js
function $Yn(colorIdent) {
  return `--vscode-${colorIdent.replace(/\./g, "-")}`;
}
function $Zn(color2) {
  return `var(${$Yn(color2)})`;
}
function $1n(color2, defaultCssValue) {
  return `var(${$Yn(color2)}, ${defaultCssValue})`;
}
var ColorTransformType;
(function(ColorTransformType2) {
  ColorTransformType2[ColorTransformType2["Darken"] = 0] = "Darken";
  ColorTransformType2[ColorTransformType2["Lighten"] = 1] = "Lighten";
  ColorTransformType2[ColorTransformType2["Transparent"] = 2] = "Transparent";
  ColorTransformType2[ColorTransformType2["Opaque"] = 3] = "Opaque";
  ColorTransformType2[ColorTransformType2["OneOf"] = 4] = "OneOf";
  ColorTransformType2[ColorTransformType2["LessProminent"] = 5] = "LessProminent";
  ColorTransformType2[ColorTransformType2["IfDefinedThenElse"] = 6] = "IfDefinedThenElse";
})(ColorTransformType || (ColorTransformType = {}));
function $2n(value) {
  return value !== null && typeof value === "object" && "light" in value && "dark" in value;
}
var $3n = {
  ColorContribution: "base.contributions.colors"
};
var $4n = "default";
var ColorRegistry = class {
  constructor() {
    this.c = new $ze();
    this.onDidChangeSchema = this.c.event;
    this.e = { type: "object", properties: {} };
    this.f = { type: "string", enum: [], enumDescriptions: [] };
    this.d = {};
  }
  notifyThemeUpdate(colorThemeData) {
    for (const key2 of Object.keys(this.d)) {
      const color2 = colorThemeData.getColor(key2);
      if (color2) {
        this.e.properties[key2].oneOf[0].defaultSnippets[0].body = `\${1:${color2.toString()}}`;
      }
    }
    this.c.fire();
  }
  registerColor(id2, defaults, description, needsTransparency = false, deprecationMessage) {
    const colorContribution = { id: id2, description, defaults, needsTransparency, deprecationMessage };
    this.d[id2] = colorContribution;
    const propertySchema = { type: "string", format: "color-hex", defaultSnippets: [{ body: "${1:#ff0000}" }] };
    if (deprecationMessage) {
      propertySchema.deprecationMessage = deprecationMessage;
    }
    if (needsTransparency) {
      propertySchema.pattern = "^#(?:(?<rgba>[0-9a-fA-f]{3}[0-9a-eA-E])|(?:[0-9a-fA-F]{6}(?:(?![fF]{2})(?:[0-9a-fA-F]{2}))))?$";
      propertySchema.patternErrorMessage = localize(2409, null);
    }
    this.e.properties[id2] = {
      description,
      oneOf: [
        propertySchema,
        { type: "string", const: $4n, description: localize(2410, null) }
      ]
    };
    this.f.enum.push(id2);
    this.f.enumDescriptions.push(description);
    this.c.fire();
    return id2;
  }
  deregisterColor(id2) {
    delete this.d[id2];
    delete this.e.properties[id2];
    const index = this.f.enum.indexOf(id2);
    if (index !== -1) {
      this.f.enum.splice(index, 1);
      this.f.enumDescriptions.splice(index, 1);
    }
    this.c.fire();
  }
  getColors() {
    return Object.keys(this.d).map((id2) => this.d[id2]);
  }
  resolveDefaultColor(id2, theme) {
    const colorDesc = this.d[id2];
    if (colorDesc?.defaults) {
      const colorValue = $2n(colorDesc.defaults) ? colorDesc.defaults[theme.type] : colorDesc.defaults;
      return $co(colorValue, theme);
    }
    return void 0;
  }
  getColorSchema() {
    return this.e;
  }
  getColorReferenceSchema() {
    return this.f;
  }
  toString() {
    const sorter3 = (a, b) => {
      const cat1 = a.indexOf(".") === -1 ? 0 : 1;
      const cat2 = b.indexOf(".") === -1 ? 0 : 1;
      if (cat1 !== cat2) {
        return cat1 - cat2;
      }
      return a.localeCompare(b);
    };
    return Object.keys(this.d).sort(sorter3).map((k) => `- \`${k}\`: ${this.d[k].description}`).join("\n");
  }
};
var colorRegistry = new ColorRegistry();
$Wn.add($3n.ColorContribution, colorRegistry);
function $5n(id2, defaults, description, needsTransparency, deprecationMessage) {
  return colorRegistry.registerColor(id2, defaults, description, needsTransparency, deprecationMessage);
}
function $6n() {
  return colorRegistry;
}
function $7n(transform, theme) {
  switch (transform.op) {
    case 0:
      return $co(transform.value, theme)?.darken(transform.factor);
    case 1:
      return $co(transform.value, theme)?.lighten(transform.factor);
    case 2:
      return $co(transform.value, theme)?.transparent(transform.factor);
    case 3: {
      const backgroundColor = $co(transform.background, theme);
      if (!backgroundColor) {
        return $co(transform.value, theme);
      }
      return $co(transform.value, theme)?.makeOpaque(backgroundColor);
    }
    case 4:
      for (const candidate of transform.values) {
        const color2 = $co(candidate, theme);
        if (color2) {
          return color2;
        }
      }
      return void 0;
    case 6:
      return $co(theme.defines(transform.if) ? transform.then : transform.else, theme);
    case 5: {
      const from = $co(transform.value, theme);
      if (!from) {
        return void 0;
      }
      const backgroundColor = $co(transform.background, theme);
      if (!backgroundColor) {
        return from.transparent(transform.factor * transform.transparency);
      }
      return from.isDarkerThan(backgroundColor) ? $Vn.getLighterColor(from, backgroundColor, transform.factor).transparent(transform.transparency) : $Vn.getDarkerColor(from, backgroundColor, transform.factor).transparent(transform.transparency);
    }
    default:
      throw $hd(transform);
  }
}
function $8n(colorValue, factor2) {
  return { op: 0, value: colorValue, factor: factor2 };
}
function $9n(colorValue, factor2) {
  return { op: 1, value: colorValue, factor: factor2 };
}
function $0n(colorValue, factor2) {
  return { op: 2, value: colorValue, factor: factor2 };
}
function $$n(colorValue, background) {
  return { op: 3, value: colorValue, background };
}
function $_n(...colorValues) {
  return { op: 4, values: colorValues };
}
function $ao(ifArg, thenArg, elseArg) {
  return { op: 6, if: ifArg, then: thenArg, else: elseArg };
}
function $bo(colorValue, backgroundColorValue, factor2, transparency) {
  return { op: 5, value: colorValue, background: backgroundColorValue, factor: factor2, transparency };
}
function $co(colorValue, theme) {
  if (colorValue === null) {
    return void 0;
  } else if (typeof colorValue === "string") {
    if (colorValue[0] === "#") {
      return $Vn.fromHex(colorValue);
    }
    return theme.getColor(colorValue);
  } else if (colorValue instanceof $Vn) {
    return colorValue;
  } else if (typeof colorValue === "object") {
    return $7n(colorValue, theme);
  }
  return void 0;
}
var $do = "vscode://schemas/workbench-colors";
var schemaRegistry = $Wn.as($Xn.JSONContribution);
schemaRegistry.registerSchema($do, colorRegistry.getColorSchema());
var delayer = new $8h(() => schemaRegistry.notifySchemaChanged($do), 200);
colorRegistry.onDidChangeSchema(() => {
  if (!delayer.isScheduled()) {
    delayer.schedule();
  }
});

// out-build/vs/platform/theme/common/colors/baseColors.js
var $eo = $5n("foreground", { dark: "#CCCCCC", light: "#616161", hcDark: "#FFFFFF", hcLight: "#292929" }, localize(2164, null));
var $fo = $5n("disabledForeground", { dark: "#CCCCCC80", light: "#61616180", hcDark: "#A5A5A5", hcLight: "#7F7F7F" }, localize(2165, null));
var $go = $5n("errorForeground", { dark: "#F48771", light: "#A1260D", hcDark: "#F48771", hcLight: "#B5200D" }, localize(2166, null));
var $ho = $5n("descriptionForeground", { light: "#717171", dark: $0n($eo, 0.7), hcDark: $0n($eo, 0.7), hcLight: $0n($eo, 0.7) }, localize(2167, null));
var $io = $5n("icon.foreground", { dark: "#C5C5C5", light: "#424242", hcDark: "#FFFFFF", hcLight: "#292929" }, localize(2168, null));
var $jo = $5n("focusBorder", { dark: "#007FD4", light: "#0090F1", hcDark: "#F38518", hcLight: "#006BBD" }, localize(2169, null));
var $ko = $5n("contrastBorder", { light: null, dark: null, hcDark: "#6FC3DF", hcLight: "#0F4A85" }, localize(2170, null));
var $lo = $5n("contrastActiveBorder", { light: null, dark: null, hcDark: $jo, hcLight: $jo }, localize(2171, null));
var $mo = $5n("selection.background", null, localize(2172, null));
var $no = $5n("textLink.foreground", { light: "#006AB1", dark: "#3794FF", hcDark: "#21A6FF", hcLight: "#0F4A85" }, localize(2173, null));
var $oo = $5n("textLink.activeForeground", { light: "#006AB1", dark: "#3794FF", hcDark: "#21A6FF", hcLight: "#0F4A85" }, localize(2174, null));
var $po = $5n("textSeparator.foreground", { light: "#0000002e", dark: "#ffffff2e", hcDark: $Vn.black, hcLight: "#292929" }, localize(2175, null));
var $qo = $5n("textPreformat.foreground", { light: "#A31515", dark: "#D7BA7D", hcDark: "#000000", hcLight: "#FFFFFF" }, localize(2176, null));
var $ro = $5n("textPreformat.background", { light: "#0000001A", dark: "#FFFFFF1A", hcDark: "#FFFFFF", hcLight: "#09345f" }, localize(2177, null));
var $so = $5n("textBlockQuote.background", { light: "#f2f2f2", dark: "#222222", hcDark: null, hcLight: "#F2F2F2" }, localize(2178, null));
var $to = $5n("textBlockQuote.border", { light: "#007acc80", dark: "#007acc80", hcDark: $Vn.white, hcLight: "#292929" }, localize(2179, null));
var $uo = $5n("textCodeBlock.background", { light: "#dcdcdc66", dark: "#0a0a0a66", hcDark: $Vn.black, hcLight: "#F2F2F2" }, localize(2180, null));

// out-build/vs/platform/theme/common/colors/miscColors.js
var $vo = $5n("sash.hoverBorder", $jo, localize(2382, null));
var $wo = $5n("badge.background", { dark: "#4D4D4D", light: "#C4C4C4", hcDark: $Vn.black, hcLight: "#0F4A85" }, localize(2383, null));
var $xo = $5n("badge.foreground", { dark: $Vn.white, light: "#333", hcDark: $Vn.white, hcLight: $Vn.white }, localize(2384, null));
var $yo = $5n("activityWarningBadge.foreground", { dark: $Vn.black.lighten(0.2), light: $Vn.white, hcDark: null, hcLight: $Vn.black.lighten(0.2) }, localize(2385, null));
var $zo = $5n("activityWarningBadge.background", { dark: "#CCA700", light: "#BF8803", hcDark: null, hcLight: "#CCA700" }, localize(2386, null));
var $Ao = $5n("activityErrorBadge.foreground", { dark: $Vn.black.lighten(0.2), light: $Vn.white, hcDark: null, hcLight: $Vn.black.lighten(0.2) }, localize(2387, null));
var $Bo = $5n("activityErrorBadge.background", { dark: "#F14C4C", light: "#E51400", hcDark: null, hcLight: "#F14C4C" }, localize(2388, null));
var $Co = $5n("scrollbar.shadow", { dark: "#000000", light: "#DDDDDD", hcDark: null, hcLight: null }, localize(2389, null));
var $Do = $5n("scrollbarSlider.background", { dark: $Vn.fromHex("#797979").transparent(0.4), light: $Vn.fromHex("#646464").transparent(0.4), hcDark: $0n($ko, 0.6), hcLight: $0n($ko, 0.4) }, localize(2390, null));
var $Eo = $5n("scrollbarSlider.hoverBackground", { dark: $Vn.fromHex("#646464").transparent(0.7), light: $Vn.fromHex("#646464").transparent(0.7), hcDark: $0n($ko, 0.8), hcLight: $0n($ko, 0.8) }, localize(2391, null));
var $Fo = $5n("scrollbarSlider.activeBackground", { dark: $Vn.fromHex("#BFBFBF").transparent(0.4), light: $Vn.fromHex("#000000").transparent(0.6), hcDark: $ko, hcLight: $ko }, localize(2392, null));
var $Go = $5n("progressBar.background", { dark: $Vn.fromHex("#0E70C0"), light: $Vn.fromHex("#0E70C0"), hcDark: $ko, hcLight: $ko }, localize(2393, null));
var $Ho = $5n("chart.line", { dark: "#236B8E", light: "#236B8E", hcDark: "#236B8E", hcLight: "#236B8E" }, localize(2394, null));
var $Io = $5n("chart.axis", { dark: $Vn.fromHex("#BFBFBF").transparent(0.4), light: $Vn.fromHex("#000000").transparent(0.6), hcDark: $ko, hcLight: $ko }, localize(2395, null));
var $Jo = $5n("chart.guide", { dark: $Vn.fromHex("#BFBFBF").transparent(0.2), light: $Vn.fromHex("#000000").transparent(0.2), hcDark: $ko, hcLight: $ko }, localize(2396, null));

// out-build/vs/platform/theme/common/colors/editorColors.js
var $Ko = $5n("editor.background", { light: "#ffffff", dark: "#1E1E1E", hcDark: $Vn.black, hcLight: $Vn.white }, localize(2189, null));
var $Lo = $5n("editor.foreground", { light: "#333333", dark: "#BBBBBB", hcDark: $Vn.white, hcLight: $eo }, localize(2190, null));
var $Mo = $5n("editorStickyScroll.background", $Ko, localize(2191, null));
var $No = $5n("editorStickyScrollHover.background", { dark: "#2A2D2E", light: "#F0F0F0", hcDark: null, hcLight: $Vn.fromHex("#0F4A85").transparent(0.1) }, localize(2192, null));
var $Oo = $5n("editorStickyScroll.border", { dark: null, light: null, hcDark: $ko, hcLight: $ko }, localize(2193, null));
var $Po = $5n("editorStickyScroll.shadow", $Co, localize(2194, null));
var $Qo = $5n("editorWidget.background", { dark: "#252526", light: "#F3F3F3", hcDark: "#0C141F", hcLight: $Vn.white }, localize(2195, null));
var $Ro = $5n("editorWidget.foreground", $eo, localize(2196, null));
var $So = $5n("editorWidget.border", { dark: "#454545", light: "#C8C8C8", hcDark: $ko, hcLight: $ko }, localize(2197, null));
var $To = $5n("editorWidget.resizeBorder", null, localize(2198, null));
var $Uo = $5n("editorError.background", null, localize(2199, null), true);
var $Vo = $5n("editorError.foreground", { dark: "#F14C4C", light: "#E51400", hcDark: "#F48771", hcLight: "#B5200D" }, localize(2200, null));
var $Wo = $5n("editorError.border", { dark: null, light: null, hcDark: $Vn.fromHex("#E47777").transparent(0.8), hcLight: "#B5200D" }, localize(2201, null));
var $Xo = $5n("editorWarning.background", null, localize(2202, null), true);
var $Yo = $5n("editorWarning.foreground", { dark: "#CCA700", light: "#BF8803", hcDark: "#FFD370", hcLight: "#895503" }, localize(2203, null));
var $Zo = $5n("editorWarning.border", { dark: null, light: null, hcDark: $Vn.fromHex("#FFCC00").transparent(0.8), hcLight: $Vn.fromHex("#FFCC00").transparent(0.8) }, localize(2204, null));
var $1o = $5n("editorInfo.background", null, localize(2205, null), true);
var $2o = $5n("editorInfo.foreground", { dark: "#3794FF", light: "#1a85ff", hcDark: "#3794FF", hcLight: "#1a85ff" }, localize(2206, null));
var $3o = $5n("editorInfo.border", { dark: null, light: null, hcDark: $Vn.fromHex("#3794FF").transparent(0.8), hcLight: "#292929" }, localize(2207, null));
var $4o = $5n("editorHint.foreground", { dark: $Vn.fromHex("#eeeeee").transparent(0.7), light: "#6c6c6c", hcDark: null, hcLight: null }, localize(2208, null));
var $5o = $5n("editorHint.border", { dark: null, light: null, hcDark: $Vn.fromHex("#eeeeee").transparent(0.8), hcLight: "#292929" }, localize(2209, null));
var $6o = $5n("editorLink.activeForeground", { dark: "#4E94CE", light: $Vn.blue, hcDark: $Vn.cyan, hcLight: "#292929" }, localize(2210, null));
var $7o = $5n("editor.selectionBackground", { light: "#ADD6FF", dark: "#264F78", hcDark: "#f3f518", hcLight: "#0F4A85" }, localize(2211, null));
var $8o = $5n("editor.selectionForeground", { light: null, dark: null, hcDark: "#000000", hcLight: $Vn.white }, localize(2212, null));
var $9o = $5n("editor.inactiveSelectionBackground", { light: $0n($7o, 0.5), dark: $0n($7o, 0.5), hcDark: $0n($7o, 0.7), hcLight: $0n($7o, 0.5) }, localize(2213, null), true);
var $0o = $5n("editor.selectionHighlightBackground", { light: $bo($7o, $Ko, 0.3, 0.6), dark: $bo($7o, $Ko, 0.3, 0.6), hcDark: null, hcLight: null }, localize(2214, null), true);
var $$o = $5n("editor.selectionHighlightBorder", { light: null, dark: null, hcDark: $lo, hcLight: $lo }, localize(2215, null));
var $_o = $5n("editor.compositionBorder", { light: "#000000", dark: "#ffffff", hcLight: "#000000", hcDark: "#ffffff" }, localize(2216, null));
var $ap = $5n("editor.findMatchBackground", { light: "#A8AC94", dark: "#515C6A", hcDark: null, hcLight: null }, localize(2217, null));
var $bp = $5n("editor.findMatchForeground", null, localize(2218, null));
var $cp = $5n("editor.findMatchHighlightBackground", { light: "#EA5C0055", dark: "#EA5C0055", hcDark: null, hcLight: null }, localize(2219, null), true);
var $dp = $5n("editor.findMatchHighlightForeground", null, localize(2220, null), true);
var $ep = $5n("editor.findRangeHighlightBackground", { dark: "#3a3d4166", light: "#b4b4b44d", hcDark: null, hcLight: null }, localize(2221, null), true);
var $fp = $5n("editor.findMatchBorder", { light: null, dark: null, hcDark: $lo, hcLight: $lo }, localize(2222, null));
var $gp = $5n("editor.findMatchHighlightBorder", { light: null, dark: null, hcDark: $lo, hcLight: $lo }, localize(2223, null));
var $hp = $5n("editor.findRangeHighlightBorder", { dark: null, light: null, hcDark: $0n($lo, 0.4), hcLight: $0n($lo, 0.4) }, localize(2224, null), true);
var $ip = $5n("editor.hoverHighlightBackground", { light: "#ADD6FF26", dark: "#264f7840", hcDark: "#ADD6FF26", hcLight: null }, localize(2225, null), true);
var $jp = $5n("editorHoverWidget.background", $Qo, localize(2226, null));
var $kp = $5n("editorHoverWidget.foreground", $Ro, localize(2227, null));
var $lp = $5n("editorHoverWidget.border", $So, localize(2228, null));
var $mp = $5n("editorHoverWidget.statusBarBackground", { dark: $9n($jp, 0.2), light: $8n($jp, 0.05), hcDark: $Qo, hcLight: $Qo }, localize(2229, null));
var $np = $5n("editorInlayHint.foreground", { dark: "#969696", light: "#969696", hcDark: $Vn.white, hcLight: $Vn.black }, localize(2230, null));
var $op = $5n("editorInlayHint.background", { dark: $0n($wo, 0.1), light: $0n($wo, 0.1), hcDark: $0n($Vn.white, 0.1), hcLight: $0n($wo, 0.1) }, localize(2231, null));
var $pp = $5n("editorInlayHint.typeForeground", $np, localize(2232, null));
var $qp = $5n("editorInlayHint.typeBackground", $op, localize(2233, null));
var $rp = $5n("editorInlayHint.parameterForeground", $np, localize(2234, null));
var $sp = $5n("editorInlayHint.parameterBackground", $op, localize(2235, null));
var $tp = $5n("editorLightBulb.foreground", { dark: "#FFCC00", light: "#DDB100", hcDark: "#FFCC00", hcLight: "#007ACC" }, localize(2236, null));
var $up = $5n("editorLightBulbAutoFix.foreground", { dark: "#75BEFF", light: "#007ACC", hcDark: "#75BEFF", hcLight: "#007ACC" }, localize(2237, null));
var $vp = $5n("editorLightBulbAi.foreground", $tp, localize(2238, null));
var $wp = $5n("editor.snippetTabstopHighlightBackground", { dark: new $Vn(new $Sn(124, 124, 124, 0.3)), light: new $Vn(new $Sn(10, 50, 100, 0.2)), hcDark: new $Vn(new $Sn(124, 124, 124, 0.3)), hcLight: new $Vn(new $Sn(10, 50, 100, 0.2)) }, localize(2239, null));
var $xp = $5n("editor.snippetTabstopHighlightBorder", null, localize(2240, null));
var $yp = $5n("editor.snippetFinalTabstopHighlightBackground", null, localize(2241, null));
var $zp = $5n("editor.snippetFinalTabstopHighlightBorder", { dark: "#525252", light: new $Vn(new $Sn(10, 50, 100, 0.5)), hcDark: "#525252", hcLight: "#292929" }, localize(2242, null));
var $Ap = new $Vn(new $Sn(155, 185, 85, 0.2));
var $Bp = new $Vn(new $Sn(255, 0, 0, 0.2));
var $Cp = $5n("diffEditor.insertedTextBackground", { dark: "#9ccc2c33", light: "#9ccc2c40", hcDark: null, hcLight: null }, localize(2243, null), true);
var $Dp = $5n("diffEditor.removedTextBackground", { dark: "#ff000033", light: "#ff000033", hcDark: null, hcLight: null }, localize(2244, null), true);
var $Ep = $5n("diffEditor.insertedLineBackground", { dark: $Ap, light: $Ap, hcDark: null, hcLight: null }, localize(2245, null), true);
var $Fp = $5n("diffEditor.removedLineBackground", { dark: $Bp, light: $Bp, hcDark: null, hcLight: null }, localize(2246, null), true);
var $Gp = $5n("diffEditorGutter.insertedLineBackground", null, localize(2247, null));
var $Hp = $5n("diffEditorGutter.removedLineBackground", null, localize(2248, null));
var $Ip = $5n("diffEditorOverview.insertedForeground", null, localize(2249, null));
var $Jp = $5n("diffEditorOverview.removedForeground", null, localize(2250, null));
var $Kp = $5n("diffEditor.insertedTextBorder", { dark: null, light: null, hcDark: "#33ff2eff", hcLight: "#374E06" }, localize(2251, null));
var $Lp = $5n("diffEditor.removedTextBorder", { dark: null, light: null, hcDark: "#FF008F", hcLight: "#AD0707" }, localize(2252, null));
var $Mp = $5n("diffEditor.border", { dark: null, light: null, hcDark: $ko, hcLight: $ko }, localize(2253, null));
var $Np = $5n("diffEditor.diagonalFill", { dark: "#cccccc33", light: "#22222233", hcDark: null, hcLight: null }, localize(2254, null));
var $Op = $5n("diffEditor.unchangedRegionBackground", "sideBar.background", localize(2255, null));
var $Pp = $5n("diffEditor.unchangedRegionForeground", "foreground", localize(2256, null));
var $Qp = $5n("diffEditor.unchangedCodeBackground", { dark: "#74747429", light: "#b8b8b829", hcDark: null, hcLight: null }, localize(2257, null));
var $Rp = $5n("widget.shadow", { dark: $0n($Vn.black, 0.36), light: $0n($Vn.black, 0.16), hcDark: null, hcLight: null }, localize(2258, null));
var $Sp = $5n("widget.border", { dark: null, light: null, hcDark: $ko, hcLight: $ko }, localize(2259, null));
var $Tp = $5n("toolbar.hoverBackground", { dark: "#5a5d5e50", light: "#b8b8b850", hcDark: null, hcLight: null }, localize(2260, null));
var $Up = $5n("toolbar.hoverOutline", { dark: null, light: null, hcDark: $lo, hcLight: $lo }, localize(2261, null));
var $Vp = $5n("toolbar.activeBackground", { dark: $9n($Tp, 0.1), light: $8n($Tp, 0.1), hcDark: null, hcLight: null }, localize(2262, null));
var $Wp = $5n("breadcrumb.foreground", $0n($eo, 0.8), localize(2263, null));
var $Xp = $5n("breadcrumb.background", $Ko, localize(2264, null));
var $Yp = $5n("breadcrumb.focusForeground", { light: $8n($eo, 0.2), dark: $9n($eo, 0.1), hcDark: $9n($eo, 0.1), hcLight: $9n($eo, 0.1) }, localize(2265, null));
var $Zp = $5n("breadcrumb.activeSelectionForeground", { light: $8n($eo, 0.2), dark: $9n($eo, 0.1), hcDark: $9n($eo, 0.1), hcLight: $9n($eo, 0.1) }, localize(2266, null));
var $1p = $5n("breadcrumbPicker.background", $Qo, localize(2267, null));
var headerTransparency = 0.5;
var currentBaseColor = $Vn.fromHex("#40C8AE").transparent(headerTransparency);
var incomingBaseColor = $Vn.fromHex("#40A6FF").transparent(headerTransparency);
var commonBaseColor = $Vn.fromHex("#606060").transparent(0.4);
var contentTransparency = 0.4;
var rulerTransparency = 1;
var $2p = $5n("merge.currentHeaderBackground", { dark: currentBaseColor, light: currentBaseColor, hcDark: null, hcLight: null }, localize(2268, null), true);
var $3p = $5n("merge.currentContentBackground", $0n($2p, contentTransparency), localize(2269, null), true);
var $4p = $5n("merge.incomingHeaderBackground", { dark: incomingBaseColor, light: incomingBaseColor, hcDark: null, hcLight: null }, localize(2270, null), true);
var $5p = $5n("merge.incomingContentBackground", $0n($4p, contentTransparency), localize(2271, null), true);
var $6p = $5n("merge.commonHeaderBackground", { dark: commonBaseColor, light: commonBaseColor, hcDark: null, hcLight: null }, localize(2272, null), true);
var $7p = $5n("merge.commonContentBackground", $0n($6p, contentTransparency), localize(2273, null), true);
var $8p = $5n("merge.border", { dark: null, light: null, hcDark: "#C3DF6F", hcLight: "#007ACC" }, localize(2274, null));
var $9p = $5n("editorOverviewRuler.currentContentForeground", { dark: $0n($2p, rulerTransparency), light: $0n($2p, rulerTransparency), hcDark: $8p, hcLight: $8p }, localize(2275, null));
var $0p = $5n("editorOverviewRuler.incomingContentForeground", { dark: $0n($4p, rulerTransparency), light: $0n($4p, rulerTransparency), hcDark: $8p, hcLight: $8p }, localize(2276, null));
var $$p = $5n("editorOverviewRuler.commonContentForeground", { dark: $0n($6p, rulerTransparency), light: $0n($6p, rulerTransparency), hcDark: $8p, hcLight: $8p }, localize(2277, null));
var $_p = $5n("editorOverviewRuler.findMatchForeground", { dark: "#d186167e", light: "#d186167e", hcDark: "#AB5A00", hcLight: "#AB5A00" }, localize(2278, null), true);
var $aq = $5n("editorOverviewRuler.selectionHighlightForeground", "#A0A0A0CC", localize(2279, null), true);
var $bq = $5n("problemsErrorIcon.foreground", $Vo, localize(2280, null));
var $cq = $5n("problemsWarningIcon.foreground", $Yo, localize(2281, null));
var $dq = $5n("problemsInfoIcon.foreground", $2o, localize(2282, null));

// out-build/vs/platform/theme/common/colors/minimapColors.js
var $eq = $5n("minimap.findMatchHighlight", { light: "#d18616", dark: "#d18616", hcDark: "#AB5A00", hcLight: "#0F4A85" }, localize(2371, null), true);
var $fq = $5n("minimap.selectionOccurrenceHighlight", { light: "#c9c9c9", dark: "#676767", hcDark: "#ffffff", hcLight: "#0F4A85" }, localize(2372, null), true);
var $gq = $5n("minimap.selectionHighlight", { light: "#ADD6FF", dark: "#264F78", hcDark: "#ffffff", hcLight: "#0F4A85" }, localize(2373, null), true);
var $hq = $5n("minimap.infoHighlight", { dark: $2o, light: $2o, hcDark: $3o, hcLight: $3o }, localize(2374, null));
var $iq = $5n("minimap.warningHighlight", { dark: $Yo, light: $Yo, hcDark: $Zo, hcLight: $Zo }, localize(2375, null));
var $jq = $5n("minimap.errorHighlight", { dark: new $Vn(new $Sn(255, 18, 18, 0.7)), light: new $Vn(new $Sn(255, 18, 18, 0.7)), hcDark: new $Vn(new $Sn(255, 50, 50, 1)), hcLight: "#B5200D" }, localize(2376, null));
var $kq = $5n("minimap.background", null, localize(2377, null));
var $lq = $5n("minimap.foregroundOpacity", $Vn.fromHex("#000f"), localize(2378, null));
var $mq = $5n("minimapSlider.background", $0n($Do, 0.5), localize(2379, null));
var $nq = $5n("minimapSlider.hoverBackground", $0n($Eo, 0.5), localize(2380, null));
var $oq = $5n("minimapSlider.activeBackground", $0n($Fo, 0.5), localize(2381, null));

// out-build/vs/platform/theme/common/colors/chartsColors.js
var $pq = $5n("charts.foreground", $eo, localize(2181, null));
var $qq = $5n("charts.lines", $0n($eo, 0.5), localize(2182, null));
var $rq = $5n("charts.red", $Vo, localize(2183, null));
var $sq = $5n("charts.blue", $2o, localize(2184, null));
var $tq = $5n("charts.yellow", $Yo, localize(2185, null));
var $uq = $5n("charts.orange", $eq, localize(2186, null));
var $vq = $5n("charts.green", { dark: "#89D185", light: "#388A34", hcDark: "#89D185", hcLight: "#374e06" }, localize(2187, null));
var $wq = $5n("charts.purple", { dark: "#B180D7", light: "#652D90", hcDark: "#B180D7", hcLight: "#652D90" }, localize(2188, null));

// out-build/vs/platform/theme/common/colors/inputColors.js
var $xq = $5n("input.background", { dark: "#3C3C3C", light: $Vn.white, hcDark: $Vn.black, hcLight: $Vn.white }, localize(2283, null));
var $yq = $5n("input.foreground", $eo, localize(2284, null));
var $zq = $5n("input.border", { dark: null, light: null, hcDark: $ko, hcLight: $ko }, localize(2285, null));
var $Aq = $5n("inputOption.activeBorder", { dark: "#007ACC", light: "#007ACC", hcDark: $ko, hcLight: $ko }, localize(2286, null));
var $Bq = $5n("inputOption.hoverBackground", { dark: "#5a5d5e80", light: "#b8b8b850", hcDark: null, hcLight: null }, localize(2287, null));
var $Cq = $5n("inputOption.activeBackground", { dark: $0n($jo, 0.4), light: $0n($jo, 0.2), hcDark: $Vn.transparent, hcLight: $Vn.transparent }, localize(2288, null));
var $Dq = $5n("inputOption.activeForeground", { dark: $Vn.white, light: $Vn.black, hcDark: $eo, hcLight: $eo }, localize(2289, null));
var $Eq = $5n("input.placeholderForeground", { light: $0n($eo, 0.5), dark: $0n($eo, 0.5), hcDark: $0n($eo, 0.7), hcLight: $0n($eo, 0.7) }, localize(2290, null));
var $Fq = $5n("inputValidation.infoBackground", { dark: "#063B49", light: "#D6ECF2", hcDark: $Vn.black, hcLight: $Vn.white }, localize(2291, null));
var $Gq = $5n("inputValidation.infoForeground", { dark: null, light: null, hcDark: null, hcLight: $eo }, localize(2292, null));
var $Hq = $5n("inputValidation.infoBorder", { dark: "#007acc", light: "#007acc", hcDark: $ko, hcLight: $ko }, localize(2293, null));
var $Iq = $5n("inputValidation.warningBackground", { dark: "#352A05", light: "#F6F5D2", hcDark: $Vn.black, hcLight: $Vn.white }, localize(2294, null));
var $Jq = $5n("inputValidation.warningForeground", { dark: null, light: null, hcDark: null, hcLight: $eo }, localize(2295, null));
var $Kq = $5n("inputValidation.warningBorder", { dark: "#B89500", light: "#B89500", hcDark: $ko, hcLight: $ko }, localize(2296, null));
var $Lq = $5n("inputValidation.errorBackground", { dark: "#5A1D1D", light: "#F2DEDE", hcDark: $Vn.black, hcLight: $Vn.white }, localize(2297, null));
var $Mq = $5n("inputValidation.errorForeground", { dark: null, light: null, hcDark: null, hcLight: $eo }, localize(2298, null));
var $Nq = $5n("inputValidation.errorBorder", { dark: "#BE1100", light: "#BE1100", hcDark: $ko, hcLight: $ko }, localize(2299, null));
var $Oq = $5n("dropdown.background", { dark: "#3C3C3C", light: $Vn.white, hcDark: $Vn.black, hcLight: $Vn.white }, localize(2300, null));
var $Pq = $5n("dropdown.listBackground", { dark: null, light: null, hcDark: $Vn.black, hcLight: $Vn.white }, localize(2301, null));
var $Qq = $5n("dropdown.foreground", { dark: "#F0F0F0", light: $eo, hcDark: $Vn.white, hcLight: $eo }, localize(2302, null));
var $Rq = $5n("dropdown.border", { dark: $Oq, light: "#CECECE", hcDark: $ko, hcLight: $ko }, localize(2303, null));
var $Sq = $5n("button.foreground", $Vn.white, localize(2304, null));
var $Tq = $5n("button.separator", $0n($Sq, 0.4), localize(2305, null));
var $Uq = $5n("button.background", { dark: "#0E639C", light: "#007ACC", hcDark: null, hcLight: "#0F4A85" }, localize(2306, null));
var $Vq = $5n("button.hoverBackground", { dark: $9n($Uq, 0.2), light: $8n($Uq, 0.2), hcDark: $Uq, hcLight: $Uq }, localize(2307, null));
var $Wq = $5n("button.border", $ko, localize(2308, null));
var $Xq = $5n("button.secondaryForeground", { dark: $Vn.white, light: $Vn.white, hcDark: $Vn.white, hcLight: $eo }, localize(2309, null));
var $Yq = $5n("button.secondaryBackground", { dark: "#3A3D41", light: "#5F6A79", hcDark: null, hcLight: $Vn.white }, localize(2310, null));
var $Zq = $5n("button.secondaryHoverBackground", { dark: $9n($Yq, 0.2), light: $8n($Yq, 0.2), hcDark: null, hcLight: null }, localize(2311, null));
var $1q = $5n("radio.activeForeground", $Dq, localize(2312, null));
var $2q = $5n("radio.activeBackground", $Cq, localize(2313, null));
var $3q = $5n("radio.activeBorder", $Aq, localize(2314, null));
var $4q = $5n("radio.inactiveForeground", null, localize(2315, null));
var $5q = $5n("radio.inactiveBackground", null, localize(2316, null));
var $6q = $5n("radio.inactiveBorder", { light: $0n($1q, 0.2), dark: $0n($1q, 0.2), hcDark: $0n($1q, 0.4), hcLight: $0n($1q, 0.2) }, localize(2317, null));
var $7q = $5n("radio.inactiveHoverBackground", $Bq, localize(2318, null));
var $8q = $5n("checkbox.background", $Oq, localize(2319, null));
var $9q = $5n("checkbox.selectBackground", $Qo, localize(2320, null));
var $0q = $5n("checkbox.foreground", $Qq, localize(2321, null));
var $$q = $5n("checkbox.border", $Rq, localize(2322, null));
var $_q = $5n("checkbox.selectBorder", $io, localize(2323, null));
var $ar = $5n("keybindingLabel.background", { dark: new $Vn(new $Sn(128, 128, 128, 0.17)), light: new $Vn(new $Sn(221, 221, 221, 0.4)), hcDark: $Vn.transparent, hcLight: $Vn.transparent }, localize(2324, null));
var $br = $5n("keybindingLabel.foreground", { dark: $Vn.fromHex("#CCCCCC"), light: $Vn.fromHex("#555555"), hcDark: $Vn.white, hcLight: $eo }, localize(2325, null));
var $cr = $5n("keybindingLabel.border", { dark: new $Vn(new $Sn(51, 51, 51, 0.6)), light: new $Vn(new $Sn(204, 204, 204, 0.4)), hcDark: new $Vn(new $Sn(111, 195, 223)), hcLight: $ko }, localize(2326, null));
var $dr = $5n("keybindingLabel.bottomBorder", { dark: new $Vn(new $Sn(68, 68, 68, 0.6)), light: new $Vn(new $Sn(187, 187, 187, 0.4)), hcDark: new $Vn(new $Sn(111, 195, 223)), hcLight: $eo }, localize(2327, null));

// out-build/vs/platform/theme/common/colors/listColors.js
var $er = $5n("list.focusBackground", null, localize(2328, null));
var $fr = $5n("list.focusForeground", null, localize(2329, null));
var $gr = $5n("list.focusOutline", { dark: $jo, light: $jo, hcDark: $lo, hcLight: $lo }, localize(2330, null));
var $hr = $5n("list.focusAndSelectionOutline", null, localize(2331, null));
var $ir = $5n("list.activeSelectionBackground", { dark: "#04395E", light: "#0060C0", hcDark: null, hcLight: $Vn.fromHex("#0F4A85").transparent(0.1) }, localize(2332, null));
var $jr = $5n("list.activeSelectionForeground", { dark: $Vn.white, light: $Vn.white, hcDark: null, hcLight: null }, localize(2333, null));
var $kr = $5n("list.activeSelectionIconForeground", null, localize(2334, null));
var $lr = $5n("list.inactiveSelectionBackground", { dark: "#37373D", light: "#E4E6F1", hcDark: null, hcLight: $Vn.fromHex("#0F4A85").transparent(0.1) }, localize(2335, null));
var $mr = $5n("list.inactiveSelectionForeground", null, localize(2336, null));
var $nr = $5n("list.inactiveSelectionIconForeground", null, localize(2337, null));
var $or = $5n("list.inactiveFocusBackground", null, localize(2338, null));
var $pr = $5n("list.inactiveFocusOutline", null, localize(2339, null));
var $qr = $5n("list.hoverBackground", { dark: "#2A2D2E", light: "#F0F0F0", hcDark: $Vn.white.transparent(0.1), hcLight: $Vn.fromHex("#0F4A85").transparent(0.1) }, localize(2340, null));
var $rr = $5n("list.hoverForeground", null, localize(2341, null));
var $sr = $5n("list.dropBackground", { dark: "#062F4A", light: "#D6EBFF", hcDark: null, hcLight: null }, localize(2342, null));
var $tr = $5n("list.dropBetweenBackground", { dark: $io, light: $io, hcDark: null, hcLight: null }, localize(2343, null));
var $ur = $5n("list.highlightForeground", { dark: "#2AAAFF", light: "#0066BF", hcDark: $jo, hcLight: $jo }, localize(2344, null));
var $vr = $5n("list.focusHighlightForeground", { dark: $ur, light: $ao($ir, $ur, "#BBE7FF"), hcDark: $ur, hcLight: $ur }, localize(2345, null));
var $wr = $5n("list.invalidItemForeground", { dark: "#B89500", light: "#B89500", hcDark: "#B89500", hcLight: "#B5200D" }, localize(2346, null));
var $xr = $5n("list.errorForeground", { dark: "#F88070", light: "#B01011", hcDark: null, hcLight: null }, localize(2347, null));
var $yr = $5n("list.warningForeground", { dark: "#CCA700", light: "#855F00", hcDark: null, hcLight: null }, localize(2348, null));
var $zr = $5n("listFilterWidget.background", { light: $8n($Qo, 0), dark: $9n($Qo, 0), hcDark: $Qo, hcLight: $Qo }, localize(2349, null));
var $Ar = $5n("listFilterWidget.outline", { dark: $Vn.transparent, light: $Vn.transparent, hcDark: "#f38518", hcLight: "#007ACC" }, localize(2350, null));
var $Br = $5n("listFilterWidget.noMatchesOutline", { dark: "#BE1100", light: "#BE1100", hcDark: $ko, hcLight: $ko }, localize(2351, null));
var $Cr = $5n("listFilterWidget.shadow", $Rp, localize(2352, null));
var $Dr = $5n("list.filterMatchBackground", { dark: $cp, light: $cp, hcDark: null, hcLight: null }, localize(2353, null));
var $Er = $5n("list.filterMatchBorder", { dark: $gp, light: $gp, hcDark: $ko, hcLight: $lo }, localize(2354, null));
var $Fr = $5n("list.deemphasizedForeground", { dark: "#8C8C8C", light: "#8E8E90", hcDark: "#A7A8A9", hcLight: "#666666" }, localize(2355, null));
var $Gr = $5n("tree.indentGuidesStroke", { dark: "#585858", light: "#a9a9a9", hcDark: "#a9a9a9", hcLight: "#a5a5a5" }, localize(2356, null));
var $Hr = $5n("tree.inactiveIndentGuidesStroke", $0n($Gr, 0.4), localize(2357, null));
var $Ir = $5n("tree.tableColumnsBorder", { dark: "#CCCCCC20", light: "#61616120", hcDark: null, hcLight: null }, localize(2358, null));
var $Jr = $5n("tree.tableOddRowsBackground", { dark: $0n($eo, 0.04), light: $0n($eo, 0.04), hcDark: null, hcLight: null }, localize(2359, null));
var $Kr = $5n("editorActionList.background", $Qo, localize(2360, null));
var $Lr = $5n("editorActionList.foreground", $Ro, localize(2361, null));
var $Mr = $5n("editorActionList.focusForeground", $jr, localize(2362, null));
var $Nr = $5n("editorActionList.focusBackground", $ir, localize(2363, null));

// out-build/vs/platform/theme/common/colors/menuColors.js
var $Or = $5n("menu.border", { dark: null, light: null, hcDark: $ko, hcLight: $ko }, localize(2364, null));
var $Pr = $5n("menu.foreground", $Qq, localize(2365, null));
var $Qr = $5n("menu.background", $Oq, localize(2366, null));
var $Rr = $5n("menu.selectionForeground", $jr, localize(2367, null));
var $Sr = $5n("menu.selectionBackground", $ir, localize(2368, null));
var $Tr = $5n("menu.selectionBorder", { dark: null, light: null, hcDark: $lo, hcLight: $lo }, localize(2369, null));
var $Ur = $5n("menu.separatorBackground", { dark: "#606060", light: "#D4D4D4", hcDark: $ko, hcLight: $ko }, localize(2370, null));

// out-build/vs/platform/theme/common/colors/quickpickColors.js
var $Vr = $5n("quickInput.background", $Qo, localize(2397, null));
var $Wr = $5n("quickInput.foreground", $Ro, localize(2398, null));
var $Xr = $5n("quickInputTitle.background", { dark: new $Vn(new $Sn(255, 255, 255, 0.105)), light: new $Vn(new $Sn(0, 0, 0, 0.06)), hcDark: "#000000", hcLight: $Vn.white }, localize(2399, null));
var $Yr = $5n("pickerGroup.foreground", { dark: "#3794FF", light: "#0066BF", hcDark: $Vn.white, hcLight: "#0F4A85" }, localize(2400, null));
var $Zr = $5n("pickerGroup.border", { dark: "#3F3F46", light: "#CCCEDB", hcDark: $Vn.white, hcLight: "#0F4A85" }, localize(2401, null));
var $1r = $5n("quickInput.list.focusBackground", null, "", void 0, localize(2402, null));
var $2r = $5n("quickInputList.focusForeground", $jr, localize(2403, null));
var $3r = $5n("quickInputList.focusIconForeground", $kr, localize(2404, null));
var $4r = $5n("quickInputList.focusBackground", { dark: $_n($1r, $ir), light: $_n($1r, $ir), hcDark: null, hcLight: null }, localize(2405, null));

// out-build/vs/platform/theme/common/colors/searchColors.js
var $5r = $5n("search.resultsInfoForeground", { light: $eo, dark: $0n($eo, 0.65), hcDark: $eo, hcLight: $eo }, localize(2406, null));
var $6r = $5n("searchEditor.findMatchBackground", { light: $0n($cp, 0.66), dark: $0n($cp, 0.66), hcDark: $cp, hcLight: $cp }, localize(2407, null));
var $7r = $5n("searchEditor.findMatchBorder", { light: $0n($gp, 0.66), dark: $0n($gp, 0.66), hcDark: $gp, hcLight: $gp }, localize(2408, null));

// out-build/vs/editor/browser/editorDom.js
var $X6 = class {
  constructor(x, y) {
    this.x = x;
    this.y = y;
    this._pageCoordinatesBrand = void 0;
  }
  toClientCoordinates(targetWindow) {
    return new $Y6(this.x - targetWindow.scrollX, this.y - targetWindow.scrollY);
  }
};
var $Y6 = class {
  constructor(clientX, clientY) {
    this.clientX = clientX;
    this.clientY = clientY;
    this._clientCoordinatesBrand = void 0;
  }
  toPageCoordinates(targetWindow) {
    return new $X6(this.clientX + targetWindow.scrollX, this.clientY + targetWindow.scrollY);
  }
};
var $Z6 = class {
  constructor(x, y, width2, height) {
    this.x = x;
    this.y = y;
    this.width = width2;
    this.height = height;
    this._editorPagePositionBrand = void 0;
  }
};
var $16 = class {
  constructor(x, y) {
    this.x = x;
    this.y = y;
    this._positionRelativeToEditorBrand = void 0;
  }
};
function $26(editorViewDomNode) {
  const editorPos = $vj(editorViewDomNode);
  return new $Z6(editorPos.left, editorPos.top, editorPos.width, editorPos.height);
}
function $36(editorViewDomNode, editorPagePosition, pos) {
  const scaleX = editorPagePosition.width / editorViewDomNode.offsetWidth;
  const scaleY = editorPagePosition.height / editorViewDomNode.offsetHeight;
  const relativeX = (pos.x - editorPagePosition.x) / scaleX;
  const relativeY = (pos.y - editorPagePosition.y) / scaleY;
  return new $16(relativeX, relativeY);
}
var $46 = class extends $lf {
  constructor(e, isFromPointerCapture, editorViewDomNode) {
    super(getWindow(editorViewDomNode), e);
    this._editorMouseEventBrand = void 0;
    this.isFromPointerCapture = isFromPointerCapture;
    this.pos = new $X6(this.posx, this.posy);
    this.editorPos = $26(editorViewDomNode);
    this.relativePos = $36(editorViewDomNode, this.editorPos, this.pos);
  }
};
var $56 = class {
  constructor(editorViewDomNode) {
    this.a = editorViewDomNode;
  }
  b(e) {
    return new $46(e, false, this.a);
  }
  onContextMenu(target, callback) {
    return $_i(target, "contextmenu", (e) => {
      callback(this.b(e));
    });
  }
  onMouseUp(target, callback) {
    return $_i(target, "mouseup", (e) => {
      callback(this.b(e));
    });
  }
  onMouseDown(target, callback) {
    return $_i(target, $7j.MOUSE_DOWN, (e) => {
      callback(this.b(e));
    });
  }
  onPointerDown(target, callback) {
    return $_i(target, $7j.POINTER_DOWN, (e) => {
      callback(this.b(e), e.pointerId);
    });
  }
  onMouseLeave(target, callback) {
    return $_i(target, $7j.MOUSE_LEAVE, (e) => {
      callback(this.b(e));
    });
  }
  onMouseMove(target, callback) {
    return $_i(target, "mousemove", (e) => callback(this.b(e)));
  }
};
var $66 = class {
  constructor(editorViewDomNode) {
    this.a = editorViewDomNode;
  }
  b(e) {
    return new $46(e, false, this.a);
  }
  onPointerUp(target, callback) {
    return $_i(target, "pointerup", (e) => {
      callback(this.b(e));
    });
  }
  onPointerDown(target, callback) {
    return $_i(target, $7j.POINTER_DOWN, (e) => {
      callback(this.b(e), e.pointerId);
    });
  }
  onPointerLeave(target, callback) {
    return $_i(target, $7j.POINTER_LEAVE, (e) => {
      callback(this.b(e));
    });
  }
  onPointerMove(target, callback) {
    return $_i(target, "pointermove", (e) => callback(this.b(e)));
  }
};
var $76 = class extends $3c {
  constructor(editorViewDomNode) {
    super();
    this.a = editorViewDomNode;
    this.b = this.B(new $pZ());
    this.c = null;
  }
  startMonitoring(initialElement, pointerId, initialButtons, pointerMoveCallback, onStopCallback) {
    this.c = $aj(initialElement.ownerDocument, "keydown", (e) => {
      const chord = e.toKeyCodeChord();
      if (chord.isModifierKey()) {
        return;
      }
      this.b.stopMonitoring(true, e.browserEvent);
    }, true);
    this.b.startMonitoring(initialElement, pointerId, initialButtons, (e) => {
      pointerMoveCallback(new $46(e, true, this.a));
    }, (e) => {
      this.c.dispose();
      onStopCallback(e);
    });
  }
  stopMonitoring() {
    this.b.stopMonitoring(true);
  }
};
var $86 = class _$86 {
  static {
    this.a = 0;
  }
  constructor(g) {
    this.g = g;
    this.b = ++_$86.a;
    this.c = 0;
    this.d = /* @__PURE__ */ new Map();
    this.f = new $8h(() => this.j(), 1e3);
  }
  createClassNameRef(options3) {
    const rule = this.h(options3);
    rule.increaseRefCount();
    return {
      className: rule.className,
      dispose: () => {
        rule.decreaseRefCount();
        this.f.schedule();
      }
    };
  }
  h(properties) {
    const key2 = this.i(properties);
    let existingRule = this.d.get(key2);
    if (!existingRule) {
      const counter = this.c++;
      existingRule = new RefCountedCssRule(key2, `dyn-rule-${this.b}-${counter}`, $Jj(this.g.getContainerDomNode()) ? this.g.getContainerDomNode() : void 0, properties);
      this.d.set(key2, existingRule);
    }
    return existingRule;
  }
  i(properties) {
    return JSON.stringify(properties);
  }
  j() {
    for (const rule of this.d.values()) {
      if (!rule.hasReferences()) {
        this.d.delete(rule.key);
        rule.dispose();
      }
    }
  }
};
var RefCountedCssRule = class {
  constructor(key2, className, _containerElement, properties) {
    this.key = key2;
    this.className = className;
    this.properties = properties;
    this.a = 0;
    this.c = new $2c();
    this.b = $VZ(_containerElement, void 0, this.c);
    this.b.textContent = this.d(this.className, this.properties);
  }
  d(className, properties) {
    let str = `.${className} {`;
    for (const prop in properties) {
      const value = properties[prop];
      let cssValue;
      if (typeof value === "object") {
        cssValue = $Zn(value.id);
      } else {
        cssValue = value;
      }
      const cssPropName = camelToDashes(prop);
      str += `
	${cssPropName}: ${cssValue};`;
    }
    str += `
}`;
    return str;
  }
  dispose() {
    this.c.dispose();
    this.b = void 0;
  }
  increaseRefCount() {
    this.a++;
  }
  decreaseRefCount() {
    this.a--;
  }
  hasReferences() {
    return this.a > 0;
  }
};
function camelToDashes(str) {
  return str.replace(/(^[A-Z])/, ([first]) => first.toLowerCase()).replace(/([A-Z])/g, ([letter]) => `-${letter.toLowerCase()}`);
}

// out-build/vs/editor/common/viewEventHandler.js
var $D5 = class extends $3c {
  constructor() {
    super();
    this.m = true;
  }
  shouldRender() {
    return this.m;
  }
  forceShouldRender() {
    this.m = true;
  }
  u() {
    this.m = true;
  }
  onDidRender() {
    this.m = false;
  }
  // --- begin event handlers
  onCompositionStart(e) {
    return false;
  }
  onCompositionEnd(e) {
    return false;
  }
  onConfigurationChanged(e) {
    return false;
  }
  onCursorStateChanged(e) {
    return false;
  }
  onDecorationsChanged(e) {
    return false;
  }
  onFlushed(e) {
    return false;
  }
  onFocusChanged(e) {
    return false;
  }
  onLanguageConfigurationChanged(e) {
    return false;
  }
  onLineMappingChanged(e) {
    return false;
  }
  onLinesChanged(e) {
    return false;
  }
  onLinesDeleted(e) {
    return false;
  }
  onLinesInserted(e) {
    return false;
  }
  onRevealRangeRequest(e) {
    return false;
  }
  onScrollChanged(e) {
    return false;
  }
  onThemeChanged(e) {
    return false;
  }
  onTokensChanged(e) {
    return false;
  }
  onTokensColorsChanged(e) {
    return false;
  }
  onZonesChanged(e) {
    return false;
  }
  // --- end event handlers
  handleEvents(events) {
    let shouldRender = false;
    for (let i2 = 0, len = events.length; i2 < len; i2++) {
      const e = events[i2];
      switch (e.type) {
        case 0:
          if (this.onCompositionStart(e)) {
            shouldRender = true;
          }
          break;
        case 1:
          if (this.onCompositionEnd(e)) {
            shouldRender = true;
          }
          break;
        case 2:
          if (this.onConfigurationChanged(e)) {
            shouldRender = true;
          }
          break;
        case 3:
          if (this.onCursorStateChanged(e)) {
            shouldRender = true;
          }
          break;
        case 4:
          if (this.onDecorationsChanged(e)) {
            shouldRender = true;
          }
          break;
        case 5:
          if (this.onFlushed(e)) {
            shouldRender = true;
          }
          break;
        case 6:
          if (this.onFocusChanged(e)) {
            shouldRender = true;
          }
          break;
        case 7:
          if (this.onLanguageConfigurationChanged(e)) {
            shouldRender = true;
          }
          break;
        case 8:
          if (this.onLineMappingChanged(e)) {
            shouldRender = true;
          }
          break;
        case 9:
          if (this.onLinesChanged(e)) {
            shouldRender = true;
          }
          break;
        case 10:
          if (this.onLinesDeleted(e)) {
            shouldRender = true;
          }
          break;
        case 11:
          if (this.onLinesInserted(e)) {
            shouldRender = true;
          }
          break;
        case 12:
          if (this.onRevealRangeRequest(e)) {
            shouldRender = true;
          }
          break;
        case 13:
          if (this.onScrollChanged(e)) {
            shouldRender = true;
          }
          break;
        case 15:
          if (this.onTokensChanged(e)) {
            shouldRender = true;
          }
          break;
        case 14:
          if (this.onThemeChanged(e)) {
            shouldRender = true;
          }
          break;
        case 16:
          if (this.onTokensColorsChanged(e)) {
            shouldRender = true;
          }
          break;
        case 17:
          if (this.onZonesChanged(e)) {
            shouldRender = true;
          }
          break;
        default:
          console.info("View received unknown event: ");
          console.info(e);
      }
    }
    if (shouldRender) {
      this.m = true;
    }
  }
};

// out-build/vs/editor/browser/view/viewPart.js
var $f7 = class extends $D5 {
  constructor(context) {
    super();
    this._context = context;
    this._context.addEventHandler(this);
  }
  dispose() {
    this._context.removeEventHandler(this);
    super.dispose();
  }
};
var PartFingerprint;
(function(PartFingerprint2) {
  PartFingerprint2[PartFingerprint2["None"] = 0] = "None";
  PartFingerprint2[PartFingerprint2["ContentWidgets"] = 1] = "ContentWidgets";
  PartFingerprint2[PartFingerprint2["OverflowingContentWidgets"] = 2] = "OverflowingContentWidgets";
  PartFingerprint2[PartFingerprint2["OverflowGuard"] = 3] = "OverflowGuard";
  PartFingerprint2[PartFingerprint2["OverlayWidgets"] = 4] = "OverlayWidgets";
  PartFingerprint2[PartFingerprint2["OverflowingOverlayWidgets"] = 5] = "OverflowingOverlayWidgets";
  PartFingerprint2[PartFingerprint2["ScrollableElement"] = 6] = "ScrollableElement";
  PartFingerprint2[PartFingerprint2["TextArea"] = 7] = "TextArea";
  PartFingerprint2[PartFingerprint2["ViewLines"] = 8] = "ViewLines";
  PartFingerprint2[PartFingerprint2["Minimap"] = 9] = "Minimap";
  PartFingerprint2[PartFingerprint2["ViewLinesGpu"] = 10] = "ViewLinesGpu";
})(PartFingerprint || (PartFingerprint = {}));
var $g7 = class {
  static write(target, partId) {
    target.setAttribute("data-mprt", String(partId));
  }
  static read(target) {
    const r2 = target.getAttribute("data-mprt");
    if (r2 === null) {
      return 0;
    }
    return parseInt(r2, 10);
  }
  static collect(child, stopAt) {
    const result = [];
    let resultLen = 0;
    while (child && child !== child.ownerDocument.body) {
      if (child === stopAt) {
        break;
      }
      if (child.nodeType === child.ELEMENT_NODE) {
        result[resultLen++] = this.read(child);
      }
      child = child.parentElement;
    }
    const r2 = new Uint8Array(resultLen);
    for (let i2 = 0; i2 < resultLen; i2++) {
      r2[i2] = result[resultLen - i2 - 1];
    }
    return r2;
  }
};

// out-build/vs/editor/browser/view/renderingContext.js
var $06 = class {
  constructor(viewLayout, viewportData) {
    this._restrictedRenderingContextBrand = void 0;
    this.c = viewLayout;
    this.viewportData = viewportData;
    this.scrollWidth = this.c.getScrollWidth();
    this.scrollHeight = this.c.getScrollHeight();
    this.visibleRange = this.viewportData.visibleRange;
    this.bigNumbersDelta = this.viewportData.bigNumbersDelta;
    const vInfo = this.c.getCurrentViewport();
    this.scrollTop = vInfo.top;
    this.scrollLeft = vInfo.left;
    this.viewportWidth = vInfo.width;
    this.viewportHeight = vInfo.height;
  }
  getScrolledTopFromAbsoluteTop(absoluteTop) {
    return absoluteTop - this.scrollTop;
  }
  getVerticalOffsetForLineNumber(lineNumber, includeViewZones) {
    return this.c.getVerticalOffsetForLineNumber(lineNumber, includeViewZones);
  }
  getVerticalOffsetAfterLineNumber(lineNumber, includeViewZones) {
    return this.c.getVerticalOffsetAfterLineNumber(lineNumber, includeViewZones);
  }
  getDecorationsInViewport() {
    return this.viewportData.getDecorationsInViewport();
  }
};
var $$6 = class extends $06 {
  constructor(viewLayout, viewportData, viewLines, viewLinesGpu) {
    super(viewLayout, viewportData);
    this._renderingContextBrand = void 0;
    this.d = viewLines;
    this.e = viewLinesGpu;
  }
  linesVisibleRangesForRange(range, includeNewLines) {
    const domRanges = this.d.linesVisibleRangesForRange(range, includeNewLines);
    if (!this.e) {
      return domRanges ?? null;
    }
    const gpuRanges = this.e.linesVisibleRangesForRange(range, includeNewLines);
    if (!domRanges) {
      return gpuRanges;
    }
    if (!gpuRanges) {
      return domRanges;
    }
    return domRanges.concat(gpuRanges).sort((a, b) => a.lineNumber - b.lineNumber);
  }
  visibleRangeForPosition(position) {
    return this.d.visibleRangeForPosition(position) ?? this.e?.visibleRangeForPosition(position) ?? null;
  }
};
var $_6 = class {
  /**
   * Returns the element with the smallest `lineNumber`.
   */
  static firstLine(ranges) {
    if (!ranges) {
      return null;
    }
    let result = null;
    for (const range of ranges) {
      if (!result || range.lineNumber < result.lineNumber) {
        result = range;
      }
    }
    return result;
  }
  /**
   * Returns the element with the largest `lineNumber`.
   */
  static lastLine(ranges) {
    if (!ranges) {
      return null;
    }
    let result = null;
    for (const range of ranges) {
      if (!result || range.lineNumber > result.lineNumber) {
        result = range;
      }
    }
    return result;
  }
  constructor(outsideRenderedLine, lineNumber, ranges, continuesOnNextLine) {
    this.outsideRenderedLine = outsideRenderedLine;
    this.lineNumber = lineNumber;
    this.ranges = ranges;
    this.continuesOnNextLine = continuesOnNextLine;
  }
};
var $a7 = class _$a7 {
  static from(ranges) {
    const result = new Array(ranges.length);
    for (let i2 = 0, len = ranges.length; i2 < len; i2++) {
      const range = ranges[i2];
      result[i2] = new _$a7(range.left, range.width);
    }
    return result;
  }
  constructor(left, width2) {
    this._horizontalRangeBrand = void 0;
    this.left = Math.round(left);
    this.width = Math.round(width2);
  }
  toString() {
    return `[${this.left},${this.width}]`;
  }
};
var $b7 = class {
  constructor(left, width2) {
    this._floatHorizontalRangeBrand = void 0;
    this.left = left;
    this.width = width2;
  }
  toString() {
    return `[${this.left},${this.width}]`;
  }
  static compare(a, b) {
    return a.left - b.left;
  }
};
var $c7 = class {
  constructor(outsideRenderedLine, left) {
    this.outsideRenderedLine = outsideRenderedLine;
    this.originalLeft = left;
    this.left = Math.round(this.originalLeft);
  }
};
var $d7 = class {
  constructor(outsideRenderedLine, ranges) {
    this.outsideRenderedLine = outsideRenderedLine;
    this.ranges = ranges;
  }
};

// out-build/vs/editor/browser/viewParts/viewLines/rangeUtil.js
var $k7 = class {
  static b() {
    if (!this.a) {
      this.a = document.createRange();
    }
    return this.a;
  }
  static c(range, endNode) {
    range.selectNodeContents(endNode);
  }
  static d(startElement, startOffset, endElement, endOffset, endNode) {
    const range = this.b();
    try {
      range.setStart(startElement, startOffset);
      range.setEnd(endElement, endOffset);
      return range.getClientRects();
    } catch (e) {
      return null;
    } finally {
      this.c(range, endNode);
    }
  }
  static f(ranges) {
    if (ranges.length === 1) {
      return ranges;
    }
    ranges.sort($b7.compare);
    const result = [];
    let resultLen = 0;
    let prev = ranges[0];
    for (let i2 = 1, len = ranges.length; i2 < len; i2++) {
      const range = ranges[i2];
      if (prev.left + prev.width + 0.9 >= range.left) {
        prev.width = Math.max(prev.width, range.left + range.width - prev.left);
      } else {
        result[resultLen++] = prev;
        prev = range;
      }
    }
    result[resultLen++] = prev;
    return result;
  }
  static g(clientRects, clientRectDeltaLeft, clientRectScale) {
    if (!clientRects || clientRects.length === 0) {
      return null;
    }
    const result = [];
    for (let i2 = 0, len = clientRects.length; i2 < len; i2++) {
      const clientRect = clientRects[i2];
      result[i2] = new $b7(Math.max(0, (clientRect.left - clientRectDeltaLeft) / clientRectScale), clientRect.width / clientRectScale);
    }
    return this.f(result);
  }
  static readHorizontalRanges(domNode, startChildIndex, startOffset, endChildIndex, endOffset, context) {
    const min = 0;
    const max = domNode.children.length - 1;
    if (min > max) {
      return null;
    }
    startChildIndex = Math.min(max, Math.max(min, startChildIndex));
    endChildIndex = Math.min(max, Math.max(min, endChildIndex));
    if (startChildIndex === endChildIndex && startOffset === endOffset && startOffset === 0 && !domNode.children[startChildIndex].firstChild) {
      const clientRects2 = domNode.children[startChildIndex].getClientRects();
      context.markDidDomLayout();
      return this.g(clientRects2, context.clientRectDeltaLeft, context.clientRectScale);
    }
    if (startChildIndex !== endChildIndex) {
      if (endChildIndex > 0 && endOffset === 0) {
        endChildIndex--;
        endOffset = 1073741824;
      }
    }
    let startElement = domNode.children[startChildIndex].firstChild;
    let endElement = domNode.children[endChildIndex].firstChild;
    if (!startElement || !endElement) {
      if (!startElement && startOffset === 0 && startChildIndex > 0) {
        startElement = domNode.children[startChildIndex - 1].firstChild;
        startOffset = 1073741824;
      }
      if (!endElement && endOffset === 0 && endChildIndex > 0) {
        endElement = domNode.children[endChildIndex - 1].firstChild;
        endOffset = 1073741824;
      }
    }
    if (!startElement || !endElement) {
      return null;
    }
    startOffset = Math.min(startElement.textContent.length, Math.max(0, startOffset));
    endOffset = Math.min(endElement.textContent.length, Math.max(0, endOffset));
    const clientRects = this.d(startElement, startOffset, endElement, endOffset, context.endNode);
    context.markDidDomLayout();
    return this.g(clientRects, context.clientRectDeltaLeft, context.clientRectScale);
  }
};

// out-build/vs/editor/common/viewLayout/lineDecorations.js
var $m7 = class _$m7 {
  constructor(startColumn, endColumn, className, type) {
    this.startColumn = startColumn;
    this.endColumn = endColumn;
    this.className = className;
    this.type = type;
    this._lineDecorationBrand = void 0;
  }
  static c(a, b) {
    return a.startColumn === b.startColumn && a.endColumn === b.endColumn && a.className === b.className && a.type === b.type;
  }
  static equalsArr(a, b) {
    const aLen = a.length;
    const bLen = b.length;
    if (aLen !== bLen) {
      return false;
    }
    for (let i2 = 0; i2 < aLen; i2++) {
      if (!_$m7.c(a[i2], b[i2])) {
        return false;
      }
    }
    return true;
  }
  static extractWrapped(arr, startOffset, endOffset) {
    if (arr.length === 0) {
      return arr;
    }
    const startColumn = startOffset + 1;
    const endColumn = endOffset + 1;
    const lineLength = endOffset - startOffset;
    const r2 = [];
    let rLength = 0;
    for (const dec of arr) {
      if (dec.endColumn <= startColumn || dec.startColumn >= endColumn) {
        continue;
      }
      r2[rLength++] = new _$m7(Math.max(1, dec.startColumn - startColumn + 1), Math.min(lineLength + 1, dec.endColumn - startColumn + 1), dec.className, dec.type);
    }
    return r2;
  }
  static filter(lineDecorations, lineNumber, minLineColumn, maxLineColumn) {
    if (lineDecorations.length === 0) {
      return [];
    }
    const result = [];
    let resultLen = 0;
    for (let i2 = 0, len = lineDecorations.length; i2 < len; i2++) {
      const d = lineDecorations[i2];
      const range = d.range;
      if (range.endLineNumber < lineNumber || range.startLineNumber > lineNumber) {
        continue;
      }
      if (range.isEmpty() && (d.type === 0 || d.type === 3)) {
        continue;
      }
      const startColumn = range.startLineNumber === lineNumber ? range.startColumn : minLineColumn;
      const endColumn = range.endLineNumber === lineNumber ? range.endColumn : maxLineColumn;
      result[resultLen++] = new _$m7(startColumn, endColumn, d.inlineClassName, d.type);
    }
    return result;
  }
  static e(a, b) {
    const ORDER = [2, 0, 1, 3];
    return ORDER[a] - ORDER[b];
  }
  static compare(a, b) {
    if (a.startColumn !== b.startColumn) {
      return a.startColumn - b.startColumn;
    }
    if (a.endColumn !== b.endColumn) {
      return a.endColumn - b.endColumn;
    }
    const typeCmp = _$m7.e(a.type, b.type);
    if (typeCmp !== 0) {
      return typeCmp;
    }
    if (a.className !== b.className) {
      return a.className < b.className ? -1 : 1;
    }
    return 0;
  }
};
var $n7 = class {
  constructor(startOffset, endOffset, className, metadata) {
    this.startOffset = startOffset;
    this.endOffset = endOffset;
    this.className = className;
    this.metadata = metadata;
  }
};
var Stack = class _Stack {
  constructor() {
    this.c = [];
    this.e = [];
    this.f = [];
    this.count = 0;
  }
  static g(metadata) {
    let result = 0;
    for (let i2 = 0, len = metadata.length; i2 < len; i2++) {
      result |= metadata[i2];
    }
    return result;
  }
  consumeLowerThan(maxStopOffset, nextStartOffset, result) {
    while (this.count > 0 && this.c[0] < maxStopOffset) {
      let i2 = 0;
      while (i2 + 1 < this.count && this.c[i2] === this.c[i2 + 1]) {
        i2++;
      }
      result.push(new $n7(nextStartOffset, this.c[i2], this.e.join(" "), _Stack.g(this.f)));
      nextStartOffset = this.c[i2] + 1;
      this.c.splice(0, i2 + 1);
      this.e.splice(0, i2 + 1);
      this.f.splice(0, i2 + 1);
      this.count -= i2 + 1;
    }
    if (this.count > 0 && nextStartOffset < maxStopOffset) {
      result.push(new $n7(nextStartOffset, maxStopOffset - 1, this.e.join(" "), _Stack.g(this.f)));
      nextStartOffset = maxStopOffset;
    }
    return nextStartOffset;
  }
  insert(stopOffset, className, metadata) {
    if (this.count === 0 || this.c[this.count - 1] <= stopOffset) {
      this.c.push(stopOffset);
      this.e.push(className);
      this.f.push(metadata);
    } else {
      for (let i2 = 0; i2 < this.count; i2++) {
        if (this.c[i2] >= stopOffset) {
          this.c.splice(i2, 0, stopOffset);
          this.e.splice(i2, 0, className);
          this.f.splice(i2, 0, metadata);
          break;
        }
      }
    }
    this.count++;
    return;
  }
};
var $o7 = class {
  /**
   * Normalize line decorations. Overlapping decorations will generate multiple segments
   */
  static normalize(lineContent, lineDecorations) {
    if (lineDecorations.length === 0) {
      return [];
    }
    const result = [];
    const stack = new Stack();
    let nextStartOffset = 0;
    for (let i2 = 0, len = lineDecorations.length; i2 < len; i2++) {
      const d = lineDecorations[i2];
      let startColumn = d.startColumn;
      let endColumn = d.endColumn;
      const className = d.className;
      const metadata = d.type === 1 ? 2 : d.type === 2 ? 4 : 0;
      if (startColumn > 1) {
        const charCodeBefore = lineContent.charCodeAt(startColumn - 2);
        if ($5f(charCodeBefore)) {
          startColumn--;
        }
      }
      if (endColumn > 1) {
        const charCodeBefore = lineContent.charCodeAt(endColumn - 2);
        if ($5f(charCodeBefore)) {
          endColumn--;
        }
      }
      const currentStartOffset = startColumn - 1;
      const currentEndOffset = endColumn - 2;
      nextStartOffset = stack.consumeLowerThan(currentStartOffset, nextStartOffset, result);
      if (stack.count === 0) {
        nextStartOffset = currentStartOffset;
      }
      stack.insert(currentEndOffset, className, metadata);
    }
    stack.consumeLowerThan(1073741824, nextStartOffset, result);
    return result;
  }
};

// out-build/vs/editor/common/viewLayout/linePart.js
var LinePartMetadata;
(function(LinePartMetadata2) {
  LinePartMetadata2[LinePartMetadata2["IS_WHITESPACE"] = 1] = "IS_WHITESPACE";
  LinePartMetadata2[LinePartMetadata2["PSEUDO_BEFORE"] = 2] = "PSEUDO_BEFORE";
  LinePartMetadata2[LinePartMetadata2["PSEUDO_AFTER"] = 4] = "PSEUDO_AFTER";
  LinePartMetadata2[LinePartMetadata2["IS_WHITESPACE_MASK"] = 1] = "IS_WHITESPACE_MASK";
  LinePartMetadata2[LinePartMetadata2["PSEUDO_BEFORE_MASK"] = 2] = "PSEUDO_BEFORE_MASK";
  LinePartMetadata2[LinePartMetadata2["PSEUDO_AFTER_MASK"] = 4] = "PSEUDO_AFTER_MASK";
})(LinePartMetadata || (LinePartMetadata = {}));
var $l7 = class {
  constructor(endIndex, type, metadata, containsRTL) {
    this.endIndex = endIndex;
    this.type = type;
    this.metadata = metadata;
    this.containsRTL = containsRTL;
    this._linePartBrand = void 0;
  }
  isWhitespace() {
    return this.metadata & 1 ? true : false;
  }
  isPseudoAfter() {
    return this.metadata & 4 ? true : false;
  }
};

// out-build/vs/editor/common/viewLayout/viewLineRenderer.js
var RenderWhitespace;
(function(RenderWhitespace2) {
  RenderWhitespace2[RenderWhitespace2["None"] = 0] = "None";
  RenderWhitespace2[RenderWhitespace2["Boundary"] = 1] = "Boundary";
  RenderWhitespace2[RenderWhitespace2["Selection"] = 2] = "Selection";
  RenderWhitespace2[RenderWhitespace2["Trailing"] = 3] = "Trailing";
  RenderWhitespace2[RenderWhitespace2["All"] = 4] = "All";
})(RenderWhitespace || (RenderWhitespace = {}));
var $p7 = class {
  constructor(startIndex, endIndex) {
    this.startOffset = startIndex;
    this.endOffset = endIndex;
  }
  equals(otherLineRange) {
    return this.startOffset === otherLineRange.startOffset && this.endOffset === otherLineRange.endOffset;
  }
};
var $q7 = class {
  constructor(useMonospaceOptimizations, canUseHalfwidthRightwardsArrow, lineContent, continuesWithWrappedLine, isBasicASCII, containsRTL, fauxIndentLength, lineTokens, lineDecorations, tabSize, startVisibleColumn, spaceWidth, middotWidth, wsmiddotWidth, stopRenderingLineAfter, renderWhitespace, renderControlCharacters, fontLigatures, selectionsOnLine) {
    this.useMonospaceOptimizations = useMonospaceOptimizations;
    this.canUseHalfwidthRightwardsArrow = canUseHalfwidthRightwardsArrow;
    this.lineContent = lineContent;
    this.continuesWithWrappedLine = continuesWithWrappedLine;
    this.isBasicASCII = isBasicASCII;
    this.containsRTL = containsRTL;
    this.fauxIndentLength = fauxIndentLength;
    this.lineTokens = lineTokens;
    this.lineDecorations = lineDecorations.sort($m7.compare);
    this.tabSize = tabSize;
    this.startVisibleColumn = startVisibleColumn;
    this.spaceWidth = spaceWidth;
    this.stopRenderingLineAfter = stopRenderingLineAfter;
    this.renderWhitespace = renderWhitespace === "all" ? 4 : renderWhitespace === "boundary" ? 1 : renderWhitespace === "selection" ? 2 : renderWhitespace === "trailing" ? 3 : 0;
    this.renderControlCharacters = renderControlCharacters;
    this.fontLigatures = fontLigatures;
    this.selectionsOnLine = selectionsOnLine && selectionsOnLine.sort((a, b) => a.startOffset < b.startOffset ? -1 : 1);
    const wsmiddotDiff = Math.abs(wsmiddotWidth - spaceWidth);
    const middotDiff = Math.abs(middotWidth - spaceWidth);
    if (wsmiddotDiff < middotDiff) {
      this.renderSpaceWidth = wsmiddotWidth;
      this.renderSpaceCharCode = 11825;
    } else {
      this.renderSpaceWidth = middotWidth;
      this.renderSpaceCharCode = 183;
    }
  }
  c(otherSelections) {
    if (this.selectionsOnLine === null) {
      return otherSelections === null;
    }
    if (otherSelections === null) {
      return false;
    }
    if (otherSelections.length !== this.selectionsOnLine.length) {
      return false;
    }
    for (let i2 = 0; i2 < this.selectionsOnLine.length; i2++) {
      if (!this.selectionsOnLine[i2].equals(otherSelections[i2])) {
        return false;
      }
    }
    return true;
  }
  equals(other) {
    return this.useMonospaceOptimizations === other.useMonospaceOptimizations && this.canUseHalfwidthRightwardsArrow === other.canUseHalfwidthRightwardsArrow && this.lineContent === other.lineContent && this.continuesWithWrappedLine === other.continuesWithWrappedLine && this.isBasicASCII === other.isBasicASCII && this.containsRTL === other.containsRTL && this.fauxIndentLength === other.fauxIndentLength && this.tabSize === other.tabSize && this.startVisibleColumn === other.startVisibleColumn && this.spaceWidth === other.spaceWidth && this.renderSpaceWidth === other.renderSpaceWidth && this.renderSpaceCharCode === other.renderSpaceCharCode && this.stopRenderingLineAfter === other.stopRenderingLineAfter && this.renderWhitespace === other.renderWhitespace && this.renderControlCharacters === other.renderControlCharacters && this.fontLigatures === other.fontLigatures && $m7.equalsArr(this.lineDecorations, other.lineDecorations) && this.lineTokens.equals(other.lineTokens) && this.c(other.selectionsOnLine);
  }
};
var CharacterMappingConstants;
(function(CharacterMappingConstants2) {
  CharacterMappingConstants2[CharacterMappingConstants2["PART_INDEX_MASK"] = 4294901760] = "PART_INDEX_MASK";
  CharacterMappingConstants2[CharacterMappingConstants2["CHAR_INDEX_MASK"] = 65535] = "CHAR_INDEX_MASK";
  CharacterMappingConstants2[CharacterMappingConstants2["CHAR_INDEX_OFFSET"] = 0] = "CHAR_INDEX_OFFSET";
  CharacterMappingConstants2[CharacterMappingConstants2["PART_INDEX_OFFSET"] = 16] = "PART_INDEX_OFFSET";
})(CharacterMappingConstants || (CharacterMappingConstants = {}));
var $r7 = class {
  constructor(partIndex, charIndex) {
    this.partIndex = partIndex;
    this.charIndex = charIndex;
  }
};
var $s7 = class _$s7 {
  static c(partData) {
    return (partData & 4294901760) >>> 16;
  }
  static d(partData) {
    return (partData & 65535) >>> 0;
  }
  constructor(length, partCount) {
    this.length = length;
    this.e = new Uint32Array(this.length);
    this.f = new Uint32Array(this.length);
  }
  setColumnInfo(column, partIndex, charIndex, horizontalOffset) {
    const partData = (partIndex << 16 | charIndex << 0) >>> 0;
    this.e[column - 1] = partData;
    this.f[column - 1] = horizontalOffset;
  }
  getHorizontalOffset(column) {
    if (this.f.length === 0) {
      return 0;
    }
    return this.f[column - 1];
  }
  g(charOffset) {
    if (this.length === 0) {
      return 0;
    }
    if (charOffset < 0) {
      return this.e[0];
    }
    if (charOffset >= this.length) {
      return this.e[this.length - 1];
    }
    return this.e[charOffset];
  }
  getDomPosition(column) {
    const partData = this.g(column - 1);
    const partIndex = _$s7.c(partData);
    const charIndex = _$s7.d(partData);
    return new $r7(partIndex, charIndex);
  }
  getColumn(domPosition, partLength) {
    const charOffset = this.h(domPosition.partIndex, partLength, domPosition.charIndex);
    return charOffset + 1;
  }
  h(partIndex, partLength, charIndex) {
    if (this.length === 0) {
      return 0;
    }
    const searchEntry = (partIndex << 16 | charIndex << 0) >>> 0;
    let min = 0;
    let max = this.length - 1;
    while (min + 1 < max) {
      const mid = min + max >>> 1;
      const midEntry = this.e[mid];
      if (midEntry === searchEntry) {
        return mid;
      } else if (midEntry > searchEntry) {
        max = mid;
      } else {
        min = mid;
      }
    }
    if (min === max) {
      return min;
    }
    const minEntry = this.e[min];
    const maxEntry = this.e[max];
    if (minEntry === searchEntry) {
      return min;
    }
    if (maxEntry === searchEntry) {
      return max;
    }
    const minPartIndex = _$s7.c(minEntry);
    const minCharIndex = _$s7.d(minEntry);
    const maxPartIndex = _$s7.c(maxEntry);
    let maxCharIndex;
    if (minPartIndex !== maxPartIndex) {
      maxCharIndex = partLength;
    } else {
      maxCharIndex = _$s7.d(maxEntry);
    }
    const minEntryDistance = charIndex - minCharIndex;
    const maxEntryDistance = maxCharIndex - charIndex;
    if (minEntryDistance <= maxEntryDistance) {
      return min;
    }
    return max;
  }
  inflate() {
    const result = [];
    for (let i2 = 0; i2 < this.length; i2++) {
      const partData = this.e[i2];
      const partIndex = _$s7.c(partData);
      const charIndex = _$s7.d(partData);
      const visibleColumn = this.f[i2];
      result.push([partIndex, charIndex, visibleColumn]);
    }
    return result;
  }
};
var ForeignElementType;
(function(ForeignElementType2) {
  ForeignElementType2[ForeignElementType2["None"] = 0] = "None";
  ForeignElementType2[ForeignElementType2["Before"] = 1] = "Before";
  ForeignElementType2[ForeignElementType2["After"] = 2] = "After";
})(ForeignElementType || (ForeignElementType = {}));
var $t7 = class {
  constructor(characterMapping, containsRTL, containsForeignElements) {
    this._renderLineOutputBrand = void 0;
    this.characterMapping = characterMapping;
    this.containsRTL = containsRTL;
    this.containsForeignElements = containsForeignElements;
  }
};
function $u7(input, sb) {
  if (input.lineContent.length === 0) {
    if (input.lineDecorations.length > 0) {
      sb.appendString(`<span>`);
      let beforeCount = 0;
      let afterCount = 0;
      let containsForeignElements = 0;
      for (const lineDecoration of input.lineDecorations) {
        if (lineDecoration.type === 1 || lineDecoration.type === 2) {
          sb.appendString(`<span class="`);
          sb.appendString(lineDecoration.className);
          sb.appendString(`"></span>`);
          if (lineDecoration.type === 1) {
            containsForeignElements |= 1;
            beforeCount++;
          }
          if (lineDecoration.type === 2) {
            containsForeignElements |= 2;
            afterCount++;
          }
        }
      }
      sb.appendString(`</span>`);
      const characterMapping = new $s7(1, beforeCount + afterCount);
      characterMapping.setColumnInfo(1, beforeCount, 0, 0);
      return new $t7(characterMapping, false, containsForeignElements);
    }
    sb.appendString("<span><span></span></span>");
    return new $t7(
      new $s7(0, 0),
      false,
      0
      /* ForeignElementType.None */
    );
  }
  return _renderLine(resolveRenderLineInput(input), sb);
}
var $v7 = class {
  constructor(characterMapping, html3, containsRTL, containsForeignElements) {
    this.characterMapping = characterMapping;
    this.html = html3;
    this.containsRTL = containsRTL;
    this.containsForeignElements = containsForeignElements;
  }
};
function $w7(input) {
  const sb = new $cE(1e4);
  const out = $u7(input, sb);
  return new $v7(out.characterMapping, sb.build(), out.containsRTL, out.containsForeignElements);
}
var ResolvedRenderLineInput = class {
  constructor(fontIsMonospace, canUseHalfwidthRightwardsArrow, lineContent, len, isOverflowing, overflowingCharCount, parts, containsForeignElements, fauxIndentLength, tabSize, startVisibleColumn, containsRTL, spaceWidth, renderSpaceCharCode, renderWhitespace, renderControlCharacters) {
    this.fontIsMonospace = fontIsMonospace;
    this.canUseHalfwidthRightwardsArrow = canUseHalfwidthRightwardsArrow;
    this.lineContent = lineContent;
    this.len = len;
    this.isOverflowing = isOverflowing;
    this.overflowingCharCount = overflowingCharCount;
    this.parts = parts;
    this.containsForeignElements = containsForeignElements;
    this.fauxIndentLength = fauxIndentLength;
    this.tabSize = tabSize;
    this.startVisibleColumn = startVisibleColumn;
    this.containsRTL = containsRTL;
    this.spaceWidth = spaceWidth;
    this.renderSpaceCharCode = renderSpaceCharCode;
    this.renderWhitespace = renderWhitespace;
    this.renderControlCharacters = renderControlCharacters;
  }
};
function resolveRenderLineInput(input) {
  const lineContent = input.lineContent;
  let isOverflowing;
  let overflowingCharCount;
  let len;
  if (input.stopRenderingLineAfter !== -1 && input.stopRenderingLineAfter < lineContent.length) {
    isOverflowing = true;
    overflowingCharCount = lineContent.length - input.stopRenderingLineAfter;
    len = input.stopRenderingLineAfter;
  } else {
    isOverflowing = false;
    overflowingCharCount = 0;
    len = lineContent.length;
  }
  let tokens = transformAndRemoveOverflowing(lineContent, input.containsRTL, input.lineTokens, input.fauxIndentLength, len);
  if (input.renderControlCharacters && !input.isBasicASCII) {
    tokens = extractControlCharacters(lineContent, tokens);
  }
  if (input.renderWhitespace === 4 || input.renderWhitespace === 1 || input.renderWhitespace === 2 && !!input.selectionsOnLine || input.renderWhitespace === 3 && !input.continuesWithWrappedLine) {
    tokens = _applyRenderWhitespace(input, lineContent, len, tokens);
  }
  let containsForeignElements = 0;
  if (input.lineDecorations.length > 0) {
    for (let i2 = 0, len2 = input.lineDecorations.length; i2 < len2; i2++) {
      const lineDecoration = input.lineDecorations[i2];
      if (lineDecoration.type === 3) {
        containsForeignElements |= 1;
      } else if (lineDecoration.type === 1) {
        containsForeignElements |= 1;
      } else if (lineDecoration.type === 2) {
        containsForeignElements |= 2;
      }
    }
    tokens = _applyInlineDecorations(lineContent, len, tokens, input.lineDecorations);
  }
  if (!input.containsRTL) {
    tokens = splitLargeTokens(lineContent, tokens, !input.isBasicASCII || input.fontLigatures);
  }
  return new ResolvedRenderLineInput(input.useMonospaceOptimizations, input.canUseHalfwidthRightwardsArrow, lineContent, len, isOverflowing, overflowingCharCount, tokens, containsForeignElements, input.fauxIndentLength, input.tabSize, input.startVisibleColumn, input.containsRTL, input.spaceWidth, input.renderSpaceCharCode, input.renderWhitespace, input.renderControlCharacters);
}
function transformAndRemoveOverflowing(lineContent, lineContainsRTL, tokens, fauxIndentLength, len) {
  const result = [];
  let resultLen = 0;
  if (fauxIndentLength > 0) {
    result[resultLen++] = new $l7(fauxIndentLength, "", 0, false);
  }
  let startOffset = fauxIndentLength;
  for (let tokenIndex = 0, tokensLen = tokens.getCount(); tokenIndex < tokensLen; tokenIndex++) {
    const endIndex = tokens.getEndOffset(tokenIndex);
    if (endIndex <= fauxIndentLength) {
      continue;
    }
    const type = tokens.getClassName(tokenIndex);
    if (endIndex >= len) {
      const tokenContainsRTL2 = lineContainsRTL ? $cg(lineContent.substring(startOffset, len)) : false;
      result[resultLen++] = new $l7(len, type, 0, tokenContainsRTL2);
      break;
    }
    const tokenContainsRTL = lineContainsRTL ? $cg(lineContent.substring(startOffset, endIndex)) : false;
    result[resultLen++] = new $l7(endIndex, type, 0, tokenContainsRTL);
    startOffset = endIndex;
  }
  return result;
}
var Constants2;
(function(Constants27) {
  Constants27[Constants27["LongToken"] = 50] = "LongToken";
})(Constants2 || (Constants2 = {}));
function splitLargeTokens(lineContent, tokens, onlyAtSpaces) {
  let lastTokenEndIndex = 0;
  const result = [];
  let resultLen = 0;
  if (onlyAtSpaces) {
    for (let i2 = 0, len = tokens.length; i2 < len; i2++) {
      const token = tokens[i2];
      const tokenEndIndex = token.endIndex;
      if (lastTokenEndIndex + 50 < tokenEndIndex) {
        const tokenType = token.type;
        const tokenMetadata = token.metadata;
        const tokenContainsRTL = token.containsRTL;
        let lastSpaceOffset = -1;
        let currTokenStart = lastTokenEndIndex;
        for (let j = lastTokenEndIndex; j < tokenEndIndex; j++) {
          if (lineContent.charCodeAt(j) === 32) {
            lastSpaceOffset = j;
          }
          if (lastSpaceOffset !== -1 && j - currTokenStart >= 50) {
            result[resultLen++] = new $l7(lastSpaceOffset + 1, tokenType, tokenMetadata, tokenContainsRTL);
            currTokenStart = lastSpaceOffset + 1;
            lastSpaceOffset = -1;
          }
        }
        if (currTokenStart !== tokenEndIndex) {
          result[resultLen++] = new $l7(tokenEndIndex, tokenType, tokenMetadata, tokenContainsRTL);
        }
      } else {
        result[resultLen++] = token;
      }
      lastTokenEndIndex = tokenEndIndex;
    }
  } else {
    for (let i2 = 0, len = tokens.length; i2 < len; i2++) {
      const token = tokens[i2];
      const tokenEndIndex = token.endIndex;
      const diff3 = tokenEndIndex - lastTokenEndIndex;
      if (diff3 > 50) {
        const tokenType = token.type;
        const tokenMetadata = token.metadata;
        const tokenContainsRTL = token.containsRTL;
        const piecesCount = Math.ceil(
          diff3 / 50
          /* Constants.LongToken */
        );
        for (let j = 1; j < piecesCount; j++) {
          const pieceEndIndex = lastTokenEndIndex + j * 50;
          result[resultLen++] = new $l7(pieceEndIndex, tokenType, tokenMetadata, tokenContainsRTL);
        }
        result[resultLen++] = new $l7(tokenEndIndex, tokenType, tokenMetadata, tokenContainsRTL);
      } else {
        result[resultLen++] = token;
      }
      lastTokenEndIndex = tokenEndIndex;
    }
  }
  return result;
}
function isControlCharacter(charCode) {
  if (charCode < 32) {
    return charCode !== 9;
  }
  if (charCode === 127) {
    return true;
  }
  if (charCode >= 8234 && charCode <= 8238 || charCode >= 8294 && charCode <= 8297 || charCode >= 8206 && charCode <= 8207 || charCode === 1564) {
    return true;
  }
  return false;
}
function extractControlCharacters(lineContent, tokens) {
  const result = [];
  let lastLinePart = new $l7(0, "", 0, false);
  let charOffset = 0;
  for (const token of tokens) {
    const tokenEndIndex = token.endIndex;
    for (; charOffset < tokenEndIndex; charOffset++) {
      const charCode = lineContent.charCodeAt(charOffset);
      if (isControlCharacter(charCode)) {
        if (charOffset > lastLinePart.endIndex) {
          lastLinePart = new $l7(charOffset, token.type, token.metadata, token.containsRTL);
          result.push(lastLinePart);
        }
        lastLinePart = new $l7(charOffset + 1, "mtkcontrol", token.metadata, false);
        result.push(lastLinePart);
      }
    }
    if (charOffset > lastLinePart.endIndex) {
      lastLinePart = new $l7(tokenEndIndex, token.type, token.metadata, token.containsRTL);
      result.push(lastLinePart);
    }
  }
  return result;
}
function _applyRenderWhitespace(input, lineContent, len, tokens) {
  const continuesWithWrappedLine = input.continuesWithWrappedLine;
  const fauxIndentLength = input.fauxIndentLength;
  const tabSize = input.tabSize;
  const startVisibleColumn = input.startVisibleColumn;
  const useMonospaceOptimizations = input.useMonospaceOptimizations;
  const selections = input.selectionsOnLine;
  const onlyBoundary = input.renderWhitespace === 1;
  const onlyTrailing = input.renderWhitespace === 3;
  const generateLinePartForEachWhitespace = input.renderSpaceWidth !== input.spaceWidth;
  const result = [];
  let resultLen = 0;
  let tokenIndex = 0;
  let tokenType = tokens[tokenIndex].type;
  let tokenContainsRTL = tokens[tokenIndex].containsRTL;
  let tokenEndIndex = tokens[tokenIndex].endIndex;
  const tokensLength = tokens.length;
  let lineIsEmptyOrWhitespace = false;
  let firstNonWhitespaceIndex = $Of(lineContent);
  let lastNonWhitespaceIndex;
  if (firstNonWhitespaceIndex === -1) {
    lineIsEmptyOrWhitespace = true;
    firstNonWhitespaceIndex = len;
    lastNonWhitespaceIndex = len;
  } else {
    lastNonWhitespaceIndex = $Qf(lineContent);
  }
  let wasInWhitespace = false;
  let currentSelectionIndex = 0;
  let currentSelection = selections && selections[currentSelectionIndex];
  let tmpIndent = startVisibleColumn % tabSize;
  for (let charIndex = fauxIndentLength; charIndex < len; charIndex++) {
    const chCode = lineContent.charCodeAt(charIndex);
    if (currentSelection && charIndex >= currentSelection.endOffset) {
      currentSelectionIndex++;
      currentSelection = selections && selections[currentSelectionIndex];
    }
    let isInWhitespace;
    if (charIndex < firstNonWhitespaceIndex || charIndex > lastNonWhitespaceIndex) {
      isInWhitespace = true;
    } else if (chCode === 9) {
      isInWhitespace = true;
    } else if (chCode === 32) {
      if (onlyBoundary) {
        if (wasInWhitespace) {
          isInWhitespace = true;
        } else {
          const nextChCode = charIndex + 1 < len ? lineContent.charCodeAt(charIndex + 1) : 0;
          isInWhitespace = nextChCode === 32 || nextChCode === 9;
        }
      } else {
        isInWhitespace = true;
      }
    } else {
      isInWhitespace = false;
    }
    if (isInWhitespace && selections) {
      isInWhitespace = !!currentSelection && currentSelection.startOffset <= charIndex && currentSelection.endOffset > charIndex;
    }
    if (isInWhitespace && onlyTrailing) {
      isInWhitespace = lineIsEmptyOrWhitespace || charIndex > lastNonWhitespaceIndex;
    }
    if (isInWhitespace && tokenContainsRTL) {
      if (charIndex >= firstNonWhitespaceIndex && charIndex <= lastNonWhitespaceIndex) {
        isInWhitespace = false;
      }
    }
    if (wasInWhitespace) {
      if (!isInWhitespace || !useMonospaceOptimizations && tmpIndent >= tabSize) {
        if (generateLinePartForEachWhitespace) {
          const lastEndIndex = resultLen > 0 ? result[resultLen - 1].endIndex : fauxIndentLength;
          for (let i2 = lastEndIndex + 1; i2 <= charIndex; i2++) {
            result[resultLen++] = new $l7(i2, "mtkw", 1, false);
          }
        } else {
          result[resultLen++] = new $l7(charIndex, "mtkw", 1, false);
        }
        tmpIndent = tmpIndent % tabSize;
      }
    } else {
      if (charIndex === tokenEndIndex || isInWhitespace && charIndex > fauxIndentLength) {
        result[resultLen++] = new $l7(charIndex, tokenType, 0, tokenContainsRTL);
        tmpIndent = tmpIndent % tabSize;
      }
    }
    if (chCode === 9) {
      tmpIndent = tabSize;
    } else if ($gg(chCode)) {
      tmpIndent += 2;
    } else {
      tmpIndent++;
    }
    wasInWhitespace = isInWhitespace;
    while (charIndex === tokenEndIndex) {
      tokenIndex++;
      if (tokenIndex < tokensLength) {
        tokenType = tokens[tokenIndex].type;
        tokenContainsRTL = tokens[tokenIndex].containsRTL;
        tokenEndIndex = tokens[tokenIndex].endIndex;
      } else {
        break;
      }
    }
  }
  let generateWhitespace = false;
  if (wasInWhitespace) {
    if (continuesWithWrappedLine && onlyBoundary) {
      const lastCharCode = len > 0 ? lineContent.charCodeAt(len - 1) : 0;
      const prevCharCode = len > 1 ? lineContent.charCodeAt(len - 2) : 0;
      const isSingleTrailingSpace = lastCharCode === 32 && (prevCharCode !== 32 && prevCharCode !== 9);
      if (!isSingleTrailingSpace) {
        generateWhitespace = true;
      }
    } else {
      generateWhitespace = true;
    }
  }
  if (generateWhitespace) {
    if (generateLinePartForEachWhitespace) {
      const lastEndIndex = resultLen > 0 ? result[resultLen - 1].endIndex : fauxIndentLength;
      for (let i2 = lastEndIndex + 1; i2 <= len; i2++) {
        result[resultLen++] = new $l7(i2, "mtkw", 1, false);
      }
    } else {
      result[resultLen++] = new $l7(len, "mtkw", 1, false);
    }
  } else {
    result[resultLen++] = new $l7(len, tokenType, 0, tokenContainsRTL);
  }
  return result;
}
function _applyInlineDecorations(lineContent, len, tokens, _lineDecorations) {
  _lineDecorations.sort($m7.compare);
  const lineDecorations = $o7.normalize(lineContent, _lineDecorations);
  const lineDecorationsLen = lineDecorations.length;
  let lineDecorationIndex = 0;
  const result = [];
  let resultLen = 0;
  let lastResultEndIndex = 0;
  for (let tokenIndex = 0, len2 = tokens.length; tokenIndex < len2; tokenIndex++) {
    const token = tokens[tokenIndex];
    const tokenEndIndex = token.endIndex;
    const tokenType = token.type;
    const tokenMetadata = token.metadata;
    const tokenContainsRTL = token.containsRTL;
    while (lineDecorationIndex < lineDecorationsLen && lineDecorations[lineDecorationIndex].startOffset < tokenEndIndex) {
      const lineDecoration = lineDecorations[lineDecorationIndex];
      if (lineDecoration.startOffset > lastResultEndIndex) {
        lastResultEndIndex = lineDecoration.startOffset;
        result[resultLen++] = new $l7(lastResultEndIndex, tokenType, tokenMetadata, tokenContainsRTL);
      }
      if (lineDecoration.endOffset + 1 <= tokenEndIndex) {
        lastResultEndIndex = lineDecoration.endOffset + 1;
        result[resultLen++] = new $l7(lastResultEndIndex, tokenType + " " + lineDecoration.className, tokenMetadata | lineDecoration.metadata, tokenContainsRTL);
        lineDecorationIndex++;
      } else {
        lastResultEndIndex = tokenEndIndex;
        result[resultLen++] = new $l7(lastResultEndIndex, tokenType + " " + lineDecoration.className, tokenMetadata | lineDecoration.metadata, tokenContainsRTL);
        break;
      }
    }
    if (tokenEndIndex > lastResultEndIndex) {
      lastResultEndIndex = tokenEndIndex;
      result[resultLen++] = new $l7(lastResultEndIndex, tokenType, tokenMetadata, tokenContainsRTL);
    }
  }
  const lastTokenEndIndex = tokens[tokens.length - 1].endIndex;
  if (lineDecorationIndex < lineDecorationsLen && lineDecorations[lineDecorationIndex].startOffset === lastTokenEndIndex) {
    while (lineDecorationIndex < lineDecorationsLen && lineDecorations[lineDecorationIndex].startOffset === lastTokenEndIndex) {
      const lineDecoration = lineDecorations[lineDecorationIndex];
      result[resultLen++] = new $l7(lastResultEndIndex, lineDecoration.className, lineDecoration.metadata, false);
      lineDecorationIndex++;
    }
  }
  return result;
}
function _renderLine(input, sb) {
  const fontIsMonospace = input.fontIsMonospace;
  const canUseHalfwidthRightwardsArrow = input.canUseHalfwidthRightwardsArrow;
  const containsForeignElements = input.containsForeignElements;
  const lineContent = input.lineContent;
  const len = input.len;
  const isOverflowing = input.isOverflowing;
  const overflowingCharCount = input.overflowingCharCount;
  const parts = input.parts;
  const fauxIndentLength = input.fauxIndentLength;
  const tabSize = input.tabSize;
  const startVisibleColumn = input.startVisibleColumn;
  const containsRTL = input.containsRTL;
  const spaceWidth = input.spaceWidth;
  const renderSpaceCharCode = input.renderSpaceCharCode;
  const renderWhitespace = input.renderWhitespace;
  const renderControlCharacters = input.renderControlCharacters;
  const characterMapping = new $s7(len + 1, parts.length);
  let lastCharacterMappingDefined = false;
  let charIndex = 0;
  let visibleColumn = startVisibleColumn;
  let charOffsetInPart = 0;
  let charHorizontalOffset = 0;
  let partDisplacement = 0;
  if (containsRTL) {
    sb.appendString('<span dir="ltr">');
  } else {
    sb.appendString("<span>");
  }
  for (let partIndex = 0, tokensLen = parts.length; partIndex < tokensLen; partIndex++) {
    const part = parts[partIndex];
    const partEndIndex = part.endIndex;
    const partType = part.type;
    const partContainsRTL = part.containsRTL;
    const partRendersWhitespace = renderWhitespace !== 0 && part.isWhitespace();
    const partRendersWhitespaceWithWidth = partRendersWhitespace && !fontIsMonospace && (partType === "mtkw" || !containsForeignElements);
    const partIsEmptyAndHasPseudoAfter = charIndex === partEndIndex && part.isPseudoAfter();
    charOffsetInPart = 0;
    sb.appendString("<span ");
    if (partContainsRTL) {
      sb.appendString('style="unicode-bidi:isolate" ');
    }
    sb.appendString('class="');
    sb.appendString(partRendersWhitespaceWithWidth ? "mtkz" : partType);
    sb.appendASCIICharCode(
      34
      /* CharCode.DoubleQuote */
    );
    if (partRendersWhitespace) {
      let partWidth = 0;
      {
        let _charIndex = charIndex;
        let _visibleColumn = visibleColumn;
        for (; _charIndex < partEndIndex; _charIndex++) {
          const charCode = lineContent.charCodeAt(_charIndex);
          const charWidth = (charCode === 9 ? tabSize - _visibleColumn % tabSize : 1) | 0;
          partWidth += charWidth;
          if (_charIndex >= fauxIndentLength) {
            _visibleColumn += charWidth;
          }
        }
      }
      if (partRendersWhitespaceWithWidth) {
        sb.appendString(' style="width:');
        sb.appendString(String(spaceWidth * partWidth));
        sb.appendString('px"');
      }
      sb.appendASCIICharCode(
        62
        /* CharCode.GreaterThan */
      );
      for (; charIndex < partEndIndex; charIndex++) {
        characterMapping.setColumnInfo(charIndex + 1, partIndex - partDisplacement, charOffsetInPart, charHorizontalOffset);
        partDisplacement = 0;
        const charCode = lineContent.charCodeAt(charIndex);
        let producedCharacters;
        let charWidth;
        if (charCode === 9) {
          producedCharacters = tabSize - visibleColumn % tabSize | 0;
          charWidth = producedCharacters;
          if (!canUseHalfwidthRightwardsArrow || charWidth > 1) {
            sb.appendCharCode(8594);
          } else {
            sb.appendCharCode(65515);
          }
          for (let space = 2; space <= charWidth; space++) {
            sb.appendCharCode(160);
          }
        } else {
          producedCharacters = 2;
          charWidth = 1;
          sb.appendCharCode(renderSpaceCharCode);
          sb.appendCharCode(8204);
        }
        charOffsetInPart += producedCharacters;
        charHorizontalOffset += charWidth;
        if (charIndex >= fauxIndentLength) {
          visibleColumn += charWidth;
        }
      }
    } else {
      sb.appendASCIICharCode(
        62
        /* CharCode.GreaterThan */
      );
      for (; charIndex < partEndIndex; charIndex++) {
        characterMapping.setColumnInfo(charIndex + 1, partIndex - partDisplacement, charOffsetInPart, charHorizontalOffset);
        partDisplacement = 0;
        const charCode = lineContent.charCodeAt(charIndex);
        let producedCharacters = 1;
        let charWidth = 1;
        switch (charCode) {
          case 9:
            producedCharacters = tabSize - visibleColumn % tabSize;
            charWidth = producedCharacters;
            for (let space = 1; space <= producedCharacters; space++) {
              sb.appendCharCode(160);
            }
            break;
          case 32:
            sb.appendCharCode(160);
            break;
          case 60:
            sb.appendString("&lt;");
            break;
          case 62:
            sb.appendString("&gt;");
            break;
          case 38:
            sb.appendString("&amp;");
            break;
          case 0:
            if (renderControlCharacters) {
              sb.appendCharCode(9216);
            } else {
              sb.appendString("&#00;");
            }
            break;
          case 65279:
          case 8232:
          case 8233:
          case 133:
            sb.appendCharCode(65533);
            break;
          default:
            if ($gg(charCode)) {
              charWidth++;
            }
            if (renderControlCharacters && charCode < 32) {
              sb.appendCharCode(9216 + charCode);
            } else if (renderControlCharacters && charCode === 127) {
              sb.appendCharCode(9249);
            } else if (renderControlCharacters && isControlCharacter(charCode)) {
              sb.appendString("[U+");
              sb.appendString(to4CharHex(charCode));
              sb.appendString("]");
              producedCharacters = 8;
              charWidth = producedCharacters;
            } else {
              sb.appendCharCode(charCode);
            }
        }
        charOffsetInPart += producedCharacters;
        charHorizontalOffset += charWidth;
        if (charIndex >= fauxIndentLength) {
          visibleColumn += charWidth;
        }
      }
    }
    if (partIsEmptyAndHasPseudoAfter) {
      partDisplacement++;
    } else {
      partDisplacement = 0;
    }
    if (charIndex >= len && !lastCharacterMappingDefined && part.isPseudoAfter()) {
      lastCharacterMappingDefined = true;
      characterMapping.setColumnInfo(charIndex + 1, partIndex, charOffsetInPart, charHorizontalOffset);
    }
    sb.appendString("</span>");
  }
  if (!lastCharacterMappingDefined) {
    characterMapping.setColumnInfo(len + 1, parts.length - 1, charOffsetInPart, charHorizontalOffset);
  }
  if (isOverflowing) {
    sb.appendString('<span class="mtkoverflow">');
    sb.appendString(localize(871, null, renderOverflowingCharCount(overflowingCharCount)));
    sb.appendString("</span>");
  }
  sb.appendString("</span>");
  return new $t7(characterMapping, containsRTL, containsForeignElements);
}
function to4CharHex(n) {
  return n.toString(16).toUpperCase().padStart(4, "0");
}
function renderOverflowingCharCount(n) {
  if (n < 1024) {
    return localize(872, null, n);
  }
  if (n < 1024 * 1024) {
    return `${(n / 1024).toFixed(1)} KB`;
  }
  return `${(n / 1024 / 1024).toFixed(1)} MB`;
}

// out-build/vs/platform/theme/common/theme.js
var ColorScheme;
(function(ColorScheme3) {
  ColorScheme3["DARK"] = "dark";
  ColorScheme3["LIGHT"] = "light";
  ColorScheme3["HIGH_CONTRAST_DARK"] = "hcDark";
  ColorScheme3["HIGH_CONTRAST_LIGHT"] = "hcLight";
})(ColorScheme || (ColorScheme = {}));
function $es(scheme) {
  return scheme === ColorScheme.HIGH_CONTRAST_DARK || scheme === ColorScheme.HIGH_CONTRAST_LIGHT;
}
function $fs(scheme) {
  return scheme === ColorScheme.DARK || scheme === ColorScheme.HIGH_CONTRAST_DARK;
}

// out-build/vs/editor/browser/viewParts/viewLines/viewLine.js
var canUseFastRenderedViewLine = function() {
  if ($p) {
    return true;
  }
  if ($n || $Ue || $Xe) {
    return false;
  }
  return true;
}();
var monospaceAssumptionsAreValid = true;
var $P7 = class _$P7 {
  static {
    this.CLASS_NAME = "view-line";
  }
  constructor(d, options3) {
    this.d = d;
    this.a = options3;
    this.b = true;
    this.c = null;
  }
  // --- begin IVisibleLineData
  getDomNode() {
    if (this.c && this.c.domNode) {
      return this.c.domNode.domNode;
    }
    return null;
  }
  setDomNode(domNode) {
    if (this.c) {
      this.c.domNode = $oZ(domNode);
    } else {
      throw new Error("I have no rendered view line to set the dom node to...");
    }
  }
  onContentChanged() {
    this.b = true;
  }
  onTokensChanged() {
    this.b = true;
  }
  onDecorationsChanged() {
    this.b = true;
  }
  onOptionsChanged(newOptions) {
    this.b = true;
    this.a = newOptions;
  }
  onSelectionChanged() {
    if ($es(this.a.themeType) || this.a.renderWhitespace === "selection") {
      this.b = true;
      return true;
    }
    return false;
  }
  renderLine(lineNumber, deltaTop, lineHeight, viewportData, sb) {
    if (this.a.useGpu && this.d?.canRender(this.a, viewportData, lineNumber)) {
      this.c?.domNode?.domNode.remove();
      this.c = null;
      return false;
    }
    if (this.b === false) {
      return false;
    }
    this.b = false;
    const lineData = viewportData.getViewLineRenderingData(lineNumber);
    const options3 = this.a;
    const actualInlineDecorations = $m7.filter(lineData.inlineDecorations, lineNumber, lineData.minColumn, lineData.maxColumn);
    let selectionsOnLine = null;
    if ($es(options3.themeType) || this.a.renderWhitespace === "selection") {
      const selections = viewportData.selections;
      for (const selection of selections) {
        if (selection.endLineNumber < lineNumber || selection.startLineNumber > lineNumber) {
          continue;
        }
        const startColumn = selection.startLineNumber === lineNumber ? selection.startColumn : lineData.minColumn;
        const endColumn = selection.endLineNumber === lineNumber ? selection.endColumn : lineData.maxColumn;
        if (startColumn < endColumn) {
          if ($es(options3.themeType)) {
            actualInlineDecorations.push(new $m7(
              startColumn,
              endColumn,
              "inline-selected-text",
              0
              /* InlineDecorationType.Regular */
            ));
          }
          if (this.a.renderWhitespace === "selection") {
            if (!selectionsOnLine) {
              selectionsOnLine = [];
            }
            selectionsOnLine.push(new $p7(startColumn - 1, endColumn - 1));
          }
        }
      }
    }
    const renderLineInput = new $q7(options3.useMonospaceOptimizations, options3.canUseHalfwidthRightwardsArrow, lineData.content, lineData.continuesWithWrappedLine, lineData.isBasicASCII, lineData.containsRTL, lineData.minColumn - 1, lineData.tokens, actualInlineDecorations, lineData.tabSize, lineData.startVisibleColumn, options3.spaceWidth, options3.middotWidth, options3.wsmiddotWidth, options3.stopRenderingLineAfter, options3.renderWhitespace, options3.renderControlCharacters, options3.fontLigatures !== EditorFontLigatures.OFF, selectionsOnLine);
    if (this.c && this.c.input.equals(renderLineInput)) {
      return false;
    }
    sb.appendString('<div style="top:');
    sb.appendString(String(deltaTop));
    sb.appendString("px;height:");
    sb.appendString(String(lineHeight));
    sb.appendString('px;" class="');
    sb.appendString(_$P7.CLASS_NAME);
    sb.appendString('">');
    const output = $u7(renderLineInput, sb);
    sb.appendString("</div>");
    let renderedViewLine = null;
    if (monospaceAssumptionsAreValid && canUseFastRenderedViewLine && lineData.isBasicASCII && options3.useMonospaceOptimizations && output.containsForeignElements === 0) {
      renderedViewLine = new FastRenderedViewLine(this.c ? this.c.domNode : null, renderLineInput, output.characterMapping);
    }
    if (!renderedViewLine) {
      renderedViewLine = createRenderedLine(this.c ? this.c.domNode : null, renderLineInput, output.characterMapping, output.containsRTL, output.containsForeignElements);
    }
    this.c = renderedViewLine;
    return true;
  }
  layoutLine(lineNumber, deltaTop, lineHeight) {
    if (this.c && this.c.domNode) {
      this.c.domNode.setTop(deltaTop);
      this.c.domNode.setHeight(lineHeight);
    }
  }
  // --- end IVisibleLineData
  getWidth(context) {
    if (!this.c) {
      return 0;
    }
    return this.c.getWidth(context);
  }
  getWidthIsFast() {
    if (!this.c) {
      return true;
    }
    return this.c.getWidthIsFast();
  }
  needsMonospaceFontCheck() {
    if (!this.c) {
      return false;
    }
    return this.c instanceof FastRenderedViewLine;
  }
  monospaceAssumptionsAreValid() {
    if (!this.c) {
      return monospaceAssumptionsAreValid;
    }
    if (this.c instanceof FastRenderedViewLine) {
      return this.c.monospaceAssumptionsAreValid();
    }
    return monospaceAssumptionsAreValid;
  }
  onMonospaceAssumptionsInvalidated() {
    if (this.c && this.c instanceof FastRenderedViewLine) {
      this.c = this.c.toSlowRenderedLine();
    }
  }
  getVisibleRangesForRange(lineNumber, startColumn, endColumn, context) {
    if (!this.c) {
      return null;
    }
    startColumn = Math.min(this.c.input.lineContent.length + 1, Math.max(1, startColumn));
    endColumn = Math.min(this.c.input.lineContent.length + 1, Math.max(1, endColumn));
    const stopRenderingLineAfter = this.c.input.stopRenderingLineAfter;
    if (stopRenderingLineAfter !== -1 && startColumn > stopRenderingLineAfter + 1 && endColumn > stopRenderingLineAfter + 1) {
      return new $d7(true, [new $b7(this.getWidth(context), 0)]);
    }
    if (stopRenderingLineAfter !== -1 && startColumn > stopRenderingLineAfter + 1) {
      startColumn = stopRenderingLineAfter + 1;
    }
    if (stopRenderingLineAfter !== -1 && endColumn > stopRenderingLineAfter + 1) {
      endColumn = stopRenderingLineAfter + 1;
    }
    const horizontalRanges = this.c.getVisibleRangesForRange(lineNumber, startColumn, endColumn, context);
    if (horizontalRanges && horizontalRanges.length > 0) {
      return new $d7(false, horizontalRanges);
    }
    return null;
  }
  getColumnOfNodeOffset(spanNode, offset) {
    if (!this.c) {
      return 1;
    }
    return this.c.getColumnOfNodeOffset(spanNode, offset);
  }
};
var Constants3;
(function(Constants27) {
  Constants27[Constants27["MaxMonospaceDistance"] = 300] = "MaxMonospaceDistance";
})(Constants3 || (Constants3 = {}));
var FastRenderedViewLine = class {
  constructor(domNode, renderLineInput, characterMapping) {
    this.d = -1;
    this.domNode = domNode;
    this.input = renderLineInput;
    const keyColumnCount = Math.floor(
      renderLineInput.lineContent.length / 300
      /* Constants.MaxMonospaceDistance */
    );
    if (keyColumnCount > 0) {
      this.c = new Float32Array(keyColumnCount);
      for (let i2 = 0; i2 < keyColumnCount; i2++) {
        this.c[i2] = -1;
      }
    } else {
      this.c = null;
    }
    this.a = characterMapping;
    this.b = renderLineInput.spaceWidth;
  }
  getWidth(context) {
    if (!this.domNode || this.input.lineContent.length < 300) {
      const horizontalOffset = this.a.getHorizontalOffset(this.a.length);
      return Math.round(this.b * horizontalOffset);
    }
    if (this.d === -1) {
      this.d = this.f(this.domNode).offsetWidth;
      context?.markDidDomLayout();
    }
    return this.d;
  }
  getWidthIsFast() {
    return this.input.lineContent.length < 300 || this.d !== -1;
  }
  monospaceAssumptionsAreValid() {
    if (!this.domNode) {
      return monospaceAssumptionsAreValid;
    }
    if (this.input.lineContent.length < 300) {
      const expectedWidth = this.getWidth(null);
      const actualWidth = this.domNode.domNode.firstChild.offsetWidth;
      if (Math.abs(expectedWidth - actualWidth) >= 2) {
        console.warn(`monospace assumptions have been violated, therefore disabling monospace optimizations!`);
        monospaceAssumptionsAreValid = false;
      }
    }
    return monospaceAssumptionsAreValid;
  }
  toSlowRenderedLine() {
    return createRenderedLine(
      this.domNode,
      this.input,
      this.a,
      false,
      0
      /* ForeignElementType.None */
    );
  }
  getVisibleRangesForRange(lineNumber, startColumn, endColumn, context) {
    const startPosition = this.e(lineNumber, startColumn, context);
    const endPosition = this.e(lineNumber, endColumn, context);
    return [new $b7(startPosition, endPosition - startPosition)];
  }
  e(lineNumber, column, context) {
    if (column <= 300) {
      const horizontalOffset2 = this.a.getHorizontalOffset(column);
      return this.b * horizontalOffset2;
    }
    const keyColumnOrdinal = Math.floor(
      (column - 1) / 300
      /* Constants.MaxMonospaceDistance */
    ) - 1;
    const keyColumn = (keyColumnOrdinal + 1) * 300 + 1;
    let keyColumnPixelOffset = -1;
    if (this.c) {
      keyColumnPixelOffset = this.c[keyColumnOrdinal];
      if (keyColumnPixelOffset === -1) {
        keyColumnPixelOffset = this.g(lineNumber, keyColumn, context);
        this.c[keyColumnOrdinal] = keyColumnPixelOffset;
      }
    }
    if (keyColumnPixelOffset === -1) {
      const horizontalOffset2 = this.a.getHorizontalOffset(column);
      return this.b * horizontalOffset2;
    }
    const keyColumnHorizontalOffset = this.a.getHorizontalOffset(keyColumn);
    const horizontalOffset = this.a.getHorizontalOffset(column);
    return keyColumnPixelOffset + this.b * (horizontalOffset - keyColumnHorizontalOffset);
  }
  f(myDomNode) {
    return myDomNode.domNode.firstChild;
  }
  g(lineNumber, column, context) {
    if (!this.domNode) {
      return -1;
    }
    const domPosition = this.a.getDomPosition(column);
    const r2 = $k7.readHorizontalRanges(this.f(this.domNode), domPosition.partIndex, domPosition.charIndex, domPosition.partIndex, domPosition.charIndex, context);
    if (!r2 || r2.length === 0) {
      return -1;
    }
    return r2[0].left;
  }
  getColumnOfNodeOffset(spanNode, offset) {
    return $Q7(this.a, spanNode, offset);
  }
};
var RenderedViewLine = class {
  constructor(domNode, renderLineInput, characterMapping, containsRTL, containsForeignElements) {
    this.domNode = domNode;
    this.input = renderLineInput;
    this.a = characterMapping;
    this.b = /^\s*$/.test(renderLineInput.lineContent);
    this.c = containsForeignElements;
    this.d = -1;
    this.e = null;
    if (!containsRTL || this.a.length === 0) {
      this.e = new Float32Array(Math.max(2, this.a.length + 1));
      for (let column = 0, len = this.a.length; column <= len; column++) {
        this.e[column] = -1;
      }
    }
  }
  // --- Reading from the DOM methods
  f(myDomNode) {
    return myDomNode.domNode.firstChild;
  }
  /**
   * Width of the line in pixels
   */
  getWidth(context) {
    if (!this.domNode) {
      return 0;
    }
    if (this.d === -1) {
      this.d = this.f(this.domNode).offsetWidth;
      context?.markDidDomLayout();
    }
    return this.d;
  }
  getWidthIsFast() {
    if (this.d === -1) {
      return false;
    }
    return true;
  }
  /**
   * Visible ranges for a model range
   */
  getVisibleRangesForRange(lineNumber, startColumn, endColumn, context) {
    if (!this.domNode) {
      return null;
    }
    if (this.e !== null) {
      const startOffset = this.h(this.domNode, lineNumber, startColumn, context);
      if (startOffset === -1) {
        return null;
      }
      const endOffset = this.h(this.domNode, lineNumber, endColumn, context);
      if (endOffset === -1) {
        return null;
      }
      return [new $b7(startOffset, endOffset - startOffset)];
    }
    return this.g(this.domNode, lineNumber, startColumn, endColumn, context);
  }
  g(domNode, lineNumber, startColumn, endColumn, context) {
    if (startColumn === endColumn) {
      const pixelOffset = this.h(domNode, lineNumber, startColumn, context);
      if (pixelOffset === -1) {
        return null;
      } else {
        return [new $b7(pixelOffset, 0)];
      }
    } else {
      return this.k(domNode, startColumn, endColumn, context);
    }
  }
  h(domNode, lineNumber, column, context) {
    if (this.a.length === 0) {
      if (this.c === 0) {
        return 0;
      }
      if (this.c === 2) {
        return 0;
      }
      if (this.c === 1) {
        return this.getWidth(context);
      }
      const readingTarget = this.f(domNode);
      if (readingTarget.firstChild) {
        context.markDidDomLayout();
        return readingTarget.firstChild.offsetWidth;
      } else {
        return 0;
      }
    }
    if (this.e !== null) {
      const cachedPixelOffset = this.e[column];
      if (cachedPixelOffset !== -1) {
        return cachedPixelOffset;
      }
      const result = this.j(domNode, lineNumber, column, context);
      this.e[column] = result;
      return result;
    }
    return this.j(domNode, lineNumber, column, context);
  }
  j(domNode, lineNumber, column, context) {
    if (this.a.length === 0) {
      const r3 = $k7.readHorizontalRanges(this.f(domNode), 0, 0, 0, 0, context);
      if (!r3 || r3.length === 0) {
        return -1;
      }
      return r3[0].left;
    }
    if (column === this.a.length && this.b && this.c === 0) {
      return this.getWidth(context);
    }
    const domPosition = this.a.getDomPosition(column);
    const r2 = $k7.readHorizontalRanges(this.f(domNode), domPosition.partIndex, domPosition.charIndex, domPosition.partIndex, domPosition.charIndex, context);
    if (!r2 || r2.length === 0) {
      return -1;
    }
    const result = r2[0].left;
    if (this.input.isBasicASCII) {
      const horizontalOffset = this.a.getHorizontalOffset(column);
      const expectedResult = Math.round(this.input.spaceWidth * horizontalOffset);
      if (Math.abs(expectedResult - result) <= 1) {
        return expectedResult;
      }
    }
    return result;
  }
  k(domNode, startColumn, endColumn, context) {
    if (startColumn === 1 && endColumn === this.a.length) {
      return [new $b7(0, this.getWidth(context))];
    }
    const startDomPosition = this.a.getDomPosition(startColumn);
    const endDomPosition = this.a.getDomPosition(endColumn);
    return $k7.readHorizontalRanges(this.f(domNode), startDomPosition.partIndex, startDomPosition.charIndex, endDomPosition.partIndex, endDomPosition.charIndex, context);
  }
  /**
   * Returns the column for the text found at a specific offset inside a rendered dom node
   */
  getColumnOfNodeOffset(spanNode, offset) {
    return $Q7(this.a, spanNode, offset);
  }
};
var WebKitRenderedViewLine = class extends RenderedViewLine {
  g(domNode, lineNumber, startColumn, endColumn, context) {
    const output = super.g(domNode, lineNumber, startColumn, endColumn, context);
    if (!output || output.length === 0 || startColumn === endColumn || startColumn === 1 && endColumn === this.a.length) {
      return output;
    }
    if (!this.input.containsRTL) {
      const endPixelOffset = this.h(domNode, lineNumber, endColumn, context);
      if (endPixelOffset !== -1) {
        const lastRange = output[output.length - 1];
        if (lastRange.left < endPixelOffset) {
          lastRange.width = endPixelOffset - lastRange.left;
        }
      }
    }
    return output;
  }
};
var createRenderedLine = function() {
  if ($Ve) {
    return createWebKitRenderedLine;
  }
  return createNormalRenderedLine;
}();
function createWebKitRenderedLine(domNode, renderLineInput, characterMapping, containsRTL, containsForeignElements) {
  return new WebKitRenderedViewLine(domNode, renderLineInput, characterMapping, containsRTL, containsForeignElements);
}
function createNormalRenderedLine(domNode, renderLineInput, characterMapping, containsRTL, containsForeignElements) {
  return new RenderedViewLine(domNode, renderLineInput, characterMapping, containsRTL, containsForeignElements);
}
function $Q7(characterMapping, spanNode, offset) {
  const spanNodeTextContentLength = spanNode.textContent.length;
  let spanIndex = -1;
  while (spanNode) {
    spanNode = spanNode.previousSibling;
    spanIndex++;
  }
  return characterMapping.getColumn(new $r7(spanIndex, offset), spanNodeTextContentLength);
}

// out-build/vs/editor/browser/controller/mouseTarget.js
var HitTestResultType;
(function(HitTestResultType2) {
  HitTestResultType2[HitTestResultType2["Unknown"] = 0] = "Unknown";
  HitTestResultType2[HitTestResultType2["Content"] = 1] = "Content";
})(HitTestResultType || (HitTestResultType = {}));
var UnknownHitTestResult = class {
  constructor(hitTarget = null) {
    this.hitTarget = hitTarget;
    this.type = 0;
  }
};
var ContentHitTestResult = class {
  get hitTarget() {
    return this.spanNode;
  }
  constructor(position, spanNode, injectedText) {
    this.position = position;
    this.spanNode = spanNode;
    this.injectedText = injectedText;
    this.type = 1;
  }
};
var HitTestResult;
(function(HitTestResult2) {
  function createFromDOMInfo(ctx, spanNode, offset) {
    const position = ctx.getPositionFromDOMInfo(spanNode, offset);
    if (position) {
      return new ContentHitTestResult(position, spanNode, null);
    }
    return new UnknownHitTestResult(spanNode);
  }
  HitTestResult2.createFromDOMInfo = createFromDOMInfo;
})(HitTestResult || (HitTestResult = {}));
var $V7 = class {
  constructor(lastViewCursorsRenderData, lastTextareaPosition) {
    this.lastViewCursorsRenderData = lastViewCursorsRenderData;
    this.lastTextareaPosition = lastTextareaPosition;
  }
};
var $W7 = class {
  static c(position, range = null) {
    if (!range && position) {
      return new $9C(position.lineNumber, position.column, position.lineNumber, position.column);
    }
    return range ?? null;
  }
  static createUnknown(element, mouseColumn, position) {
    return { type: 0, element, mouseColumn, position, range: this.c(position) };
  }
  static createTextarea(element, mouseColumn) {
    return { type: 1, element, mouseColumn, position: null, range: null };
  }
  static createMargin(type, element, mouseColumn, position, range, detail2) {
    return { type, element, mouseColumn, position, range, detail: detail2 };
  }
  static createViewZone(type, element, mouseColumn, position, detail2) {
    return { type, element, mouseColumn, position, range: this.c(position), detail: detail2 };
  }
  static createContentText(element, mouseColumn, position, range, detail2) {
    return { type: 6, element, mouseColumn, position, range: this.c(position, range), detail: detail2 };
  }
  static createContentEmpty(element, mouseColumn, position, detail2) {
    return { type: 7, element, mouseColumn, position, range: this.c(position), detail: detail2 };
  }
  static createContentWidget(element, mouseColumn, detail2) {
    return { type: 9, element, mouseColumn, position: null, range: null, detail: detail2 };
  }
  static createScrollbar(element, mouseColumn, position) {
    return { type: 11, element, mouseColumn, position, range: this.c(position) };
  }
  static createOverlayWidget(element, mouseColumn, detail2) {
    return { type: 12, element, mouseColumn, position: null, range: null, detail: detail2 };
  }
  static createOutsideEditor(mouseColumn, position, outsidePosition, outsideDistance) {
    return { type: 13, element: null, mouseColumn, position, range: this.c(position), outsidePosition, outsideDistance };
  }
  static f(type) {
    if (type === 1) {
      return "TEXTAREA";
    }
    if (type === 2) {
      return "GUTTER_GLYPH_MARGIN";
    }
    if (type === 3) {
      return "GUTTER_LINE_NUMBERS";
    }
    if (type === 4) {
      return "GUTTER_LINE_DECORATIONS";
    }
    if (type === 5) {
      return "GUTTER_VIEW_ZONE";
    }
    if (type === 6) {
      return "CONTENT_TEXT";
    }
    if (type === 7) {
      return "CONTENT_EMPTY";
    }
    if (type === 8) {
      return "CONTENT_VIEW_ZONE";
    }
    if (type === 9) {
      return "CONTENT_WIDGET";
    }
    if (type === 10) {
      return "OVERVIEW_RULER";
    }
    if (type === 11) {
      return "SCROLLBAR";
    }
    if (type === 12) {
      return "OVERLAY_WIDGET";
    }
    return "UNKNOWN";
  }
  static toString(target) {
    return this.f(target.type) + ": " + target.position + " - " + target.range + " - " + JSON.stringify(target.detail);
  }
};
var ElementPath = class {
  static isTextArea(path) {
    return path.length === 2 && path[0] === 3 && path[1] === 7;
  }
  static isChildOfViewLines(path) {
    return path.length >= 4 && path[0] === 3 && path[3] === 8;
  }
  static isStrictChildOfViewLines(path) {
    return path.length > 4 && path[0] === 3 && path[3] === 8;
  }
  static isChildOfScrollableElement(path) {
    return path.length >= 2 && path[0] === 3 && path[1] === 6;
  }
  static isChildOfMinimap(path) {
    return path.length >= 2 && path[0] === 3 && path[1] === 9;
  }
  static isChildOfContentWidgets(path) {
    return path.length >= 4 && path[0] === 3 && path[3] === 1;
  }
  static isChildOfOverflowGuard(path) {
    return path.length >= 1 && path[0] === 3;
  }
  static isChildOfOverflowingContentWidgets(path) {
    return path.length >= 1 && path[0] === 2;
  }
  static isChildOfOverlayWidgets(path) {
    return path.length >= 2 && path[0] === 3 && path[1] === 4;
  }
  static isChildOfOverflowingOverlayWidgets(path) {
    return path.length >= 1 && path[0] === 5;
  }
};
var $X7 = class _$X7 {
  constructor(context, viewHelper, lastRenderData) {
    this.viewModel = context.viewModel;
    const options3 = context.configuration.options;
    this.layoutInfo = options3.get(
      151
      /* EditorOption.layoutInfo */
    );
    this.viewDomNode = viewHelper.viewDomNode;
    this.viewLinesGpu = viewHelper.viewLinesGpu;
    this.lineHeight = options3.get(
      68
      /* EditorOption.lineHeight */
    );
    this.stickyTabStops = options3.get(
      121
      /* EditorOption.stickyTabStops */
    );
    this.typicalHalfwidthCharacterWidth = options3.get(
      52
      /* EditorOption.fontInfo */
    ).typicalHalfwidthCharacterWidth;
    this.lastRenderData = lastRenderData;
    this.c = context;
    this.f = viewHelper;
  }
  getZoneAtCoord(mouseVerticalOffset) {
    return _$X7.getZoneAtCoord(this.c, mouseVerticalOffset);
  }
  static getZoneAtCoord(context, mouseVerticalOffset) {
    const viewZoneWhitespace = context.viewLayout.getWhitespaceAtVerticalOffset(mouseVerticalOffset);
    if (viewZoneWhitespace) {
      const viewZoneMiddle = viewZoneWhitespace.verticalOffset + viewZoneWhitespace.height / 2;
      const lineCount = context.viewModel.getLineCount();
      let positionBefore = null;
      let position;
      let positionAfter = null;
      if (viewZoneWhitespace.afterLineNumber !== lineCount) {
        positionAfter = new $8C(viewZoneWhitespace.afterLineNumber + 1, 1);
      }
      if (viewZoneWhitespace.afterLineNumber > 0) {
        positionBefore = new $8C(viewZoneWhitespace.afterLineNumber, context.viewModel.getLineMaxColumn(viewZoneWhitespace.afterLineNumber));
      }
      if (positionAfter === null) {
        position = positionBefore;
      } else if (positionBefore === null) {
        position = positionAfter;
      } else if (mouseVerticalOffset < viewZoneMiddle) {
        position = positionBefore;
      } else {
        position = positionAfter;
      }
      return {
        viewZoneId: viewZoneWhitespace.id,
        afterLineNumber: viewZoneWhitespace.afterLineNumber,
        positionBefore,
        positionAfter,
        position
      };
    }
    return null;
  }
  getFullLineRangeAtCoord(mouseVerticalOffset) {
    if (this.c.viewLayout.isAfterLines(mouseVerticalOffset)) {
      const lineNumber2 = this.c.viewModel.getLineCount();
      const maxLineColumn2 = this.c.viewModel.getLineMaxColumn(lineNumber2);
      return {
        range: new $9C(lineNumber2, maxLineColumn2, lineNumber2, maxLineColumn2),
        isAfterLines: true
      };
    }
    const lineNumber = this.c.viewLayout.getLineNumberAtVerticalOffset(mouseVerticalOffset);
    const maxLineColumn = this.c.viewModel.getLineMaxColumn(lineNumber);
    return {
      range: new $9C(lineNumber, 1, lineNumber, maxLineColumn),
      isAfterLines: false
    };
  }
  getLineNumberAtVerticalOffset(mouseVerticalOffset) {
    return this.c.viewLayout.getLineNumberAtVerticalOffset(mouseVerticalOffset);
  }
  isAfterLines(mouseVerticalOffset) {
    return this.c.viewLayout.isAfterLines(mouseVerticalOffset);
  }
  isInTopPadding(mouseVerticalOffset) {
    return this.c.viewLayout.isInTopPadding(mouseVerticalOffset);
  }
  isInBottomPadding(mouseVerticalOffset) {
    return this.c.viewLayout.isInBottomPadding(mouseVerticalOffset);
  }
  getVerticalOffsetForLineNumber(lineNumber) {
    return this.c.viewLayout.getVerticalOffsetForLineNumber(lineNumber);
  }
  findAttribute(element, attr) {
    return _$X7.g(element, attr, this.f.viewDomNode);
  }
  static g(element, attr, stopAt) {
    while (element && element !== element.ownerDocument.body) {
      if (element.hasAttribute && element.hasAttribute(attr)) {
        return element.getAttribute(attr);
      }
      if (element === stopAt) {
        return null;
      }
      element = element.parentNode;
    }
    return null;
  }
  getLineWidth(lineNumber) {
    return this.f.getLineWidth(lineNumber);
  }
  visibleRangeForPosition(lineNumber, column) {
    return this.f.visibleRangeForPosition(lineNumber, column);
  }
  getPositionFromDOMInfo(spanNode, offset) {
    return this.f.getPositionFromDOMInfo(spanNode, offset);
  }
  getCurrentScrollTop() {
    return this.c.viewLayout.getCurrentScrollTop();
  }
  getCurrentScrollLeft() {
    return this.c.viewLayout.getCurrentScrollLeft();
  }
};
var BareHitTestRequest = class {
  constructor(ctx, editorPos, pos, relativePos) {
    this.editorPos = editorPos;
    this.pos = pos;
    this.relativePos = relativePos;
    this.mouseVerticalOffset = Math.max(0, ctx.getCurrentScrollTop() + this.relativePos.y);
    this.mouseContentHorizontalOffset = ctx.getCurrentScrollLeft() + this.relativePos.x - ctx.layoutInfo.contentLeft;
    this.isInMarginArea = this.relativePos.x < ctx.layoutInfo.contentLeft && this.relativePos.x >= ctx.layoutInfo.glyphMarginLeft;
    this.isInContentArea = !this.isInMarginArea;
    this.c = Math.max(0, $Y7._getMouseColumn(this.mouseContentHorizontalOffset, ctx.typicalHalfwidthCharacterWidth));
  }
};
var HitTestRequest = class extends BareHitTestRequest {
  get target() {
    if (this.h) {
      return this.hitTestResult.value.hitTarget;
    }
    return this.g;
  }
  get targetPath() {
    if (this.j !== this.target) {
      this.j = this.target;
      this.k = $g7.collect(this.target, this.f.viewDomNode);
    }
    return this.k;
  }
  constructor(ctx, editorPos, pos, relativePos, eventTarget) {
    super(ctx, editorPos, pos, relativePos);
    this.hitTestResult = new $sf(() => $Y7.doHitTest(this.f, this));
    this.j = null;
    this.k = new Uint8Array(0);
    this.f = ctx;
    this.g = eventTarget;
    const hasEventTarget = Boolean(this.g);
    this.h = !hasEventTarget;
  }
  toString() {
    return `pos(${this.pos.x},${this.pos.y}), editorPos(${this.editorPos.x},${this.editorPos.y}), relativePos(${this.relativePos.x},${this.relativePos.y}), mouseVerticalOffset: ${this.mouseVerticalOffset}, mouseContentHorizontalOffset: ${this.mouseContentHorizontalOffset}
	target: ${this.target ? this.target.outerHTML : null}`;
  }
  get wouldBenefitFromHitTestTargetSwitch() {
    return !this.h && this.hitTestResult.value.hitTarget !== null && this.target !== this.hitTestResult.value.hitTarget;
  }
  switchToHitTestTarget() {
    this.h = true;
  }
  l(position = null) {
    if (position && position.column < this.f.viewModel.getLineMaxColumn(position.lineNumber)) {
      return $cF.visibleColumnFromColumn(this.f.viewModel.getLineContent(position.lineNumber), position.column, this.f.viewModel.model.getOptions().tabSize) + 1;
    }
    return this.c;
  }
  fulfillUnknown(position = null) {
    return $W7.createUnknown(this.target, this.l(position), position);
  }
  fulfillTextarea() {
    return $W7.createTextarea(this.target, this.l());
  }
  fulfillMargin(type, position, range, detail2) {
    return $W7.createMargin(type, this.target, this.l(position), position, range, detail2);
  }
  fulfillViewZone(type, position, detail2) {
    return $W7.createViewZone(type, this.target, this.l(position), position, detail2);
  }
  fulfillContentText(position, range, detail2) {
    return $W7.createContentText(this.target, this.l(position), position, range, detail2);
  }
  fulfillContentEmpty(position, detail2) {
    return $W7.createContentEmpty(this.target, this.l(position), position, detail2);
  }
  fulfillContentWidget(detail2) {
    return $W7.createContentWidget(this.target, this.l(), detail2);
  }
  fulfillScrollbar(position) {
    return $W7.createScrollbar(this.target, this.l(position), position);
  }
  fulfillOverlayWidget(detail2) {
    return $W7.createOverlayWidget(this.target, this.l(), detail2);
  }
};
var EMPTY_CONTENT_AFTER_LINES = { isAfterLines: true };
function createEmptyContentDataInLines(horizontalDistanceToText) {
  return {
    isAfterLines: false,
    horizontalDistanceToText
  };
}
var $Y7 = class _$Y7 {
  constructor(context, viewHelper) {
    this.c = context;
    this.f = viewHelper;
  }
  mouseTargetIsWidget(e) {
    const t = e.target;
    const path = $g7.collect(t, this.f.viewDomNode);
    if (ElementPath.isChildOfContentWidgets(path) || ElementPath.isChildOfOverflowingContentWidgets(path)) {
      return true;
    }
    if (ElementPath.isChildOfOverlayWidgets(path) || ElementPath.isChildOfOverflowingOverlayWidgets(path)) {
      return true;
    }
    return false;
  }
  createMouseTarget(lastRenderData, editorPos, pos, relativePos, target) {
    const ctx = new $X7(this.c, this.f, lastRenderData);
    const request = new HitTestRequest(ctx, editorPos, pos, relativePos, target);
    try {
      const r2 = _$Y7.g(ctx, request);
      if (r2.type === 6) {
        if (ctx.stickyTabStops && r2.position !== null) {
          const position = _$Y7.A(r2.position, ctx.viewModel);
          const range = $9C.fromPositions(position, position).plusRange(r2.range);
          return request.fulfillContentText(position, range, r2.detail);
        }
      }
      return r2;
    } catch (err) {
      return request.fulfillUnknown();
    }
  }
  static g(ctx, request) {
    if (request.target === null) {
      return request.fulfillUnknown();
    }
    const resolvedRequest = request;
    let result = null;
    if (!ElementPath.isChildOfOverflowGuard(request.targetPath) && !ElementPath.isChildOfOverflowingContentWidgets(request.targetPath) && !ElementPath.isChildOfOverflowingOverlayWidgets(request.targetPath)) {
      result = result || request.fulfillUnknown();
    }
    result = result || _$Y7.h(ctx, resolvedRequest);
    result = result || _$Y7.j(ctx, resolvedRequest);
    result = result || _$Y7.p(ctx, resolvedRequest);
    result = result || _$Y7.q(ctx, resolvedRequest);
    result = result || _$Y7.l(ctx, resolvedRequest);
    result = result || _$Y7.n(ctx, resolvedRequest);
    result = result || _$Y7.k(ctx, resolvedRequest);
    result = result || _$Y7.m(ctx, resolvedRequest);
    result = result || _$Y7.o(ctx, resolvedRequest);
    result = result || _$Y7.s(ctx, resolvedRequest);
    return result || request.fulfillUnknown();
  }
  static h(ctx, request) {
    if (ElementPath.isChildOfContentWidgets(request.targetPath) || ElementPath.isChildOfOverflowingContentWidgets(request.targetPath)) {
      const widgetId = ctx.findAttribute(request.target, "widgetId");
      if (widgetId) {
        return request.fulfillContentWidget(widgetId);
      } else {
        return request.fulfillUnknown();
      }
    }
    return null;
  }
  static j(ctx, request) {
    if (ElementPath.isChildOfOverlayWidgets(request.targetPath) || ElementPath.isChildOfOverflowingOverlayWidgets(request.targetPath)) {
      const widgetId = ctx.findAttribute(request.target, "widgetId");
      if (widgetId) {
        return request.fulfillOverlayWidget(widgetId);
      } else {
        return request.fulfillUnknown();
      }
    }
    return null;
  }
  static k(ctx, request) {
    if (request.target) {
      const lastViewCursorsRenderData = ctx.lastRenderData.lastViewCursorsRenderData;
      for (const d of lastViewCursorsRenderData) {
        if (request.target === d.domNode) {
          return request.fulfillContentText(d.position, null, { mightBeForeignElement: false, injectedText: null });
        }
      }
    }
    if (request.isInContentArea) {
      const lastViewCursorsRenderData = ctx.lastRenderData.lastViewCursorsRenderData;
      const mouseContentHorizontalOffset = request.mouseContentHorizontalOffset;
      const mouseVerticalOffset = request.mouseVerticalOffset;
      for (const d of lastViewCursorsRenderData) {
        if (mouseContentHorizontalOffset < d.contentLeft) {
          continue;
        }
        if (mouseContentHorizontalOffset > d.contentLeft + d.width) {
          continue;
        }
        const cursorVerticalOffset = ctx.getVerticalOffsetForLineNumber(d.position.lineNumber);
        if (cursorVerticalOffset <= mouseVerticalOffset && mouseVerticalOffset <= cursorVerticalOffset + d.height) {
          return request.fulfillContentText(d.position, null, { mightBeForeignElement: false, injectedText: null });
        }
      }
    }
    return null;
  }
  static l(ctx, request) {
    const viewZoneData = ctx.getZoneAtCoord(request.mouseVerticalOffset);
    if (viewZoneData) {
      const mouseTargetType = request.isInContentArea ? 8 : 5;
      return request.fulfillViewZone(mouseTargetType, viewZoneData.position, viewZoneData);
    }
    return null;
  }
  static m(ctx, request) {
    if (ElementPath.isTextArea(request.targetPath)) {
      if (ctx.lastRenderData.lastTextareaPosition) {
        return request.fulfillContentText(ctx.lastRenderData.lastTextareaPosition, null, { mightBeForeignElement: false, injectedText: null });
      }
      return request.fulfillTextarea();
    }
    return null;
  }
  static n(ctx, request) {
    if (request.isInMarginArea) {
      const res = ctx.getFullLineRangeAtCoord(request.mouseVerticalOffset);
      const pos = res.range.getStartPosition();
      let offset = Math.abs(request.relativePos.x);
      const detail2 = {
        isAfterLines: res.isAfterLines,
        glyphMarginLeft: ctx.layoutInfo.glyphMarginLeft,
        glyphMarginWidth: ctx.layoutInfo.glyphMarginWidth,
        lineNumbersWidth: ctx.layoutInfo.lineNumbersWidth,
        offsetX: offset
      };
      offset -= ctx.layoutInfo.glyphMarginLeft;
      if (offset <= ctx.layoutInfo.glyphMarginWidth) {
        const modelCoordinate = ctx.viewModel.coordinatesConverter.convertViewPositionToModelPosition(res.range.getStartPosition());
        const lanes = ctx.viewModel.glyphLanes.getLanesAtLine(modelCoordinate.lineNumber);
        detail2.glyphMarginLane = lanes[Math.floor(offset / ctx.lineHeight)];
        return request.fulfillMargin(2, pos, res.range, detail2);
      }
      offset -= ctx.layoutInfo.glyphMarginWidth;
      if (offset <= ctx.layoutInfo.lineNumbersWidth) {
        return request.fulfillMargin(3, pos, res.range, detail2);
      }
      offset -= ctx.layoutInfo.lineNumbersWidth;
      return request.fulfillMargin(4, pos, res.range, detail2);
    }
    return null;
  }
  static o(ctx, request) {
    if (!ElementPath.isChildOfViewLines(request.targetPath)) {
      return null;
    }
    if (ctx.isInTopPadding(request.mouseVerticalOffset)) {
      return request.fulfillContentEmpty(new $8C(1, 1), EMPTY_CONTENT_AFTER_LINES);
    }
    if (ctx.isAfterLines(request.mouseVerticalOffset) || ctx.isInBottomPadding(request.mouseVerticalOffset)) {
      const lineCount = ctx.viewModel.getLineCount();
      const maxLineColumn = ctx.viewModel.getLineMaxColumn(lineCount);
      return request.fulfillContentEmpty(new $8C(lineCount, maxLineColumn), EMPTY_CONTENT_AFTER_LINES);
    }
    if (ElementPath.isStrictChildOfViewLines(request.targetPath)) {
      const lineNumber = ctx.getLineNumberAtVerticalOffset(request.mouseVerticalOffset);
      if (ctx.viewModel.getLineLength(lineNumber) === 0) {
        const lineWidth2 = ctx.getLineWidth(lineNumber);
        const detail2 = createEmptyContentDataInLines(request.mouseContentHorizontalOffset - lineWidth2);
        return request.fulfillContentEmpty(new $8C(lineNumber, 1), detail2);
      }
      const lineWidth = ctx.getLineWidth(lineNumber);
      if (request.mouseContentHorizontalOffset >= lineWidth) {
        const detail2 = createEmptyContentDataInLines(request.mouseContentHorizontalOffset - lineWidth);
        const pos = new $8C(lineNumber, ctx.viewModel.getLineMaxColumn(lineNumber));
        return request.fulfillContentEmpty(pos, detail2);
      }
    } else {
      if (ctx.viewLinesGpu) {
        const lineNumber = ctx.getLineNumberAtVerticalOffset(request.mouseVerticalOffset);
        if (ctx.viewModel.getLineLength(lineNumber) === 0) {
          const lineWidth2 = ctx.getLineWidth(lineNumber);
          const detail2 = createEmptyContentDataInLines(request.mouseContentHorizontalOffset - lineWidth2);
          return request.fulfillContentEmpty(new $8C(lineNumber, 1), detail2);
        }
        const lineWidth = ctx.getLineWidth(lineNumber);
        if (request.mouseContentHorizontalOffset >= lineWidth) {
          const detail2 = createEmptyContentDataInLines(request.mouseContentHorizontalOffset - lineWidth);
          const pos = new $8C(lineNumber, ctx.viewModel.getLineMaxColumn(lineNumber));
          return request.fulfillContentEmpty(pos, detail2);
        }
        const position = ctx.viewLinesGpu.getPositionAtCoordinate(lineNumber, request.mouseContentHorizontalOffset);
        if (position) {
          const detail2 = {
            injectedText: null,
            mightBeForeignElement: false
          };
          return request.fulfillContentText(position, $9C.fromPositions(position, position), detail2);
        }
      }
    }
    const hitTestResult = request.hitTestResult.value;
    if (hitTestResult.type === 1) {
      return _$Y7.u(ctx, request, hitTestResult.spanNode, hitTestResult.position, hitTestResult.injectedText);
    }
    if (request.wouldBenefitFromHitTestTargetSwitch) {
      request.switchToHitTestTarget();
      return this.g(ctx, request);
    }
    return request.fulfillUnknown();
  }
  static p(ctx, request) {
    if (ElementPath.isChildOfMinimap(request.targetPath)) {
      const possibleLineNumber = ctx.getLineNumberAtVerticalOffset(request.mouseVerticalOffset);
      const maxColumn = ctx.viewModel.getLineMaxColumn(possibleLineNumber);
      return request.fulfillScrollbar(new $8C(possibleLineNumber, maxColumn));
    }
    return null;
  }
  static q(ctx, request) {
    if (ElementPath.isChildOfScrollableElement(request.targetPath)) {
      if (request.target && request.target.nodeType === 1) {
        const className = request.target.className;
        if (className && /\b(slider|scrollbar)\b/.test(className)) {
          const possibleLineNumber = ctx.getLineNumberAtVerticalOffset(request.mouseVerticalOffset);
          const maxColumn = ctx.viewModel.getLineMaxColumn(possibleLineNumber);
          return request.fulfillScrollbar(new $8C(possibleLineNumber, maxColumn));
        }
      }
    }
    return null;
  }
  static s(ctx, request) {
    if (ElementPath.isChildOfScrollableElement(request.targetPath)) {
      const possibleLineNumber = ctx.getLineNumberAtVerticalOffset(request.mouseVerticalOffset);
      const maxColumn = ctx.viewModel.getLineMaxColumn(possibleLineNumber);
      return request.fulfillScrollbar(new $8C(possibleLineNumber, maxColumn));
    }
    return null;
  }
  getMouseColumn(relativePos) {
    const options3 = this.c.configuration.options;
    const layoutInfo = options3.get(
      151
      /* EditorOption.layoutInfo */
    );
    const mouseContentHorizontalOffset = this.c.viewLayout.getCurrentScrollLeft() + relativePos.x - layoutInfo.contentLeft;
    return _$Y7._getMouseColumn(mouseContentHorizontalOffset, options3.get(
      52
      /* EditorOption.fontInfo */
    ).typicalHalfwidthCharacterWidth);
  }
  static _getMouseColumn(mouseContentHorizontalOffset, typicalHalfwidthCharacterWidth) {
    if (mouseContentHorizontalOffset < 0) {
      return 1;
    }
    const chars = Math.round(mouseContentHorizontalOffset / typicalHalfwidthCharacterWidth);
    return chars + 1;
  }
  static u(ctx, request, spanNode, pos, injectedText) {
    const lineNumber = pos.lineNumber;
    const column = pos.column;
    const lineWidth = ctx.getLineWidth(lineNumber);
    if (request.mouseContentHorizontalOffset > lineWidth) {
      const detail2 = createEmptyContentDataInLines(request.mouseContentHorizontalOffset - lineWidth);
      return request.fulfillContentEmpty(pos, detail2);
    }
    const visibleRange = ctx.visibleRangeForPosition(lineNumber, column);
    if (!visibleRange) {
      return request.fulfillUnknown(pos);
    }
    const columnHorizontalOffset = visibleRange.left;
    if (Math.abs(request.mouseContentHorizontalOffset - columnHorizontalOffset) < 1) {
      return request.fulfillContentText(pos, null, { mightBeForeignElement: !!injectedText, injectedText });
    }
    const points = [];
    points.push({ offset: visibleRange.left, column });
    if (column > 1) {
      const visibleRange2 = ctx.visibleRangeForPosition(lineNumber, column - 1);
      if (visibleRange2) {
        points.push({ offset: visibleRange2.left, column: column - 1 });
      }
    }
    const lineMaxColumn = ctx.viewModel.getLineMaxColumn(lineNumber);
    if (column < lineMaxColumn) {
      const visibleRange2 = ctx.visibleRangeForPosition(lineNumber, column + 1);
      if (visibleRange2) {
        points.push({ offset: visibleRange2.left, column: column + 1 });
      }
    }
    points.sort((a, b) => a.offset - b.offset);
    const mouseCoordinates = request.pos.toClientCoordinates(getWindow(ctx.viewDomNode));
    const spanNodeClientRect = spanNode.getBoundingClientRect();
    const mouseIsOverSpanNode = spanNodeClientRect.left <= mouseCoordinates.clientX && mouseCoordinates.clientX <= spanNodeClientRect.right;
    let rng = null;
    for (let i2 = 1; i2 < points.length; i2++) {
      const prev = points[i2 - 1];
      const curr = points[i2];
      if (prev.offset <= request.mouseContentHorizontalOffset && request.mouseContentHorizontalOffset <= curr.offset) {
        rng = new $9C(lineNumber, prev.column, lineNumber, curr.column);
        const prevDelta = Math.abs(prev.offset - request.mouseContentHorizontalOffset);
        const nextDelta = Math.abs(curr.offset - request.mouseContentHorizontalOffset);
        pos = prevDelta < nextDelta ? new $8C(lineNumber, prev.column) : new $8C(lineNumber, curr.column);
        break;
      }
    }
    return request.fulfillContentText(pos, rng, { mightBeForeignElement: !mouseIsOverSpanNode || !!injectedText, injectedText });
  }
  /**
   * Most probably WebKit browsers and Edge
   */
  static v(ctx, request) {
    const lineNumber = ctx.getLineNumberAtVerticalOffset(request.mouseVerticalOffset);
    const lineStartVerticalOffset = ctx.getVerticalOffsetForLineNumber(lineNumber);
    const lineEndVerticalOffset = lineStartVerticalOffset + ctx.lineHeight;
    const isBelowLastLine = lineNumber === ctx.viewModel.getLineCount() && request.mouseVerticalOffset > lineEndVerticalOffset;
    if (!isBelowLastLine) {
      const lineCenteredVerticalOffset = Math.floor((lineStartVerticalOffset + lineEndVerticalOffset) / 2);
      let adjustedPageY = request.pos.y + (lineCenteredVerticalOffset - request.mouseVerticalOffset);
      if (adjustedPageY <= request.editorPos.y) {
        adjustedPageY = request.editorPos.y + 1;
      }
      if (adjustedPageY >= request.editorPos.y + request.editorPos.height) {
        adjustedPageY = request.editorPos.y + request.editorPos.height - 1;
      }
      const adjustedPage = new $X6(request.pos.x, adjustedPageY);
      const r2 = this.w(ctx, adjustedPage.toClientCoordinates(getWindow(ctx.viewDomNode)));
      if (r2.type === 1) {
        return r2;
      }
    }
    return this.w(ctx, request.pos.toClientCoordinates(getWindow(ctx.viewDomNode)));
  }
  static w(ctx, coords) {
    const shadowRoot = $Kj(ctx.viewDomNode);
    let range;
    if (shadowRoot) {
      if (typeof shadowRoot.caretRangeFromPoint === "undefined") {
        range = shadowCaretRangeFromPoint(shadowRoot, coords.clientX, coords.clientY);
      } else {
        range = shadowRoot.caretRangeFromPoint(coords.clientX, coords.clientY);
      }
    } else {
      range = ctx.viewDomNode.ownerDocument.caretRangeFromPoint(coords.clientX, coords.clientY);
    }
    if (!range || !range.startContainer) {
      return new UnknownHitTestResult();
    }
    const startContainer = range.startContainer;
    if (startContainer.nodeType === startContainer.TEXT_NODE) {
      const parent1 = startContainer.parentNode;
      const parent2 = parent1 ? parent1.parentNode : null;
      const parent3 = parent2 ? parent2.parentNode : null;
      const parent3ClassName = parent3 && parent3.nodeType === parent3.ELEMENT_NODE ? parent3.className : null;
      if (parent3ClassName === $P7.CLASS_NAME) {
        return HitTestResult.createFromDOMInfo(ctx, parent1, range.startOffset);
      } else {
        return new UnknownHitTestResult(startContainer.parentNode);
      }
    } else if (startContainer.nodeType === startContainer.ELEMENT_NODE) {
      const parent1 = startContainer.parentNode;
      const parent2 = parent1 ? parent1.parentNode : null;
      const parent2ClassName = parent2 && parent2.nodeType === parent2.ELEMENT_NODE ? parent2.className : null;
      if (parent2ClassName === $P7.CLASS_NAME) {
        return HitTestResult.createFromDOMInfo(ctx, startContainer, startContainer.textContent.length);
      } else {
        return new UnknownHitTestResult(startContainer);
      }
    }
    return new UnknownHitTestResult();
  }
  /**
   * Most probably Gecko
   */
  static z(ctx, coords) {
    const hitResult = ctx.viewDomNode.ownerDocument.caretPositionFromPoint(coords.clientX, coords.clientY);
    if (hitResult.offsetNode.nodeType === hitResult.offsetNode.TEXT_NODE) {
      const parent1 = hitResult.offsetNode.parentNode;
      const parent2 = parent1 ? parent1.parentNode : null;
      const parent3 = parent2 ? parent2.parentNode : null;
      const parent3ClassName = parent3 && parent3.nodeType === parent3.ELEMENT_NODE ? parent3.className : null;
      if (parent3ClassName === $P7.CLASS_NAME) {
        return HitTestResult.createFromDOMInfo(ctx, hitResult.offsetNode.parentNode, hitResult.offset);
      } else {
        return new UnknownHitTestResult(hitResult.offsetNode.parentNode);
      }
    }
    if (hitResult.offsetNode.nodeType === hitResult.offsetNode.ELEMENT_NODE) {
      const parent1 = hitResult.offsetNode.parentNode;
      const parent1ClassName = parent1 && parent1.nodeType === parent1.ELEMENT_NODE ? parent1.className : null;
      const parent2 = parent1 ? parent1.parentNode : null;
      const parent2ClassName = parent2 && parent2.nodeType === parent2.ELEMENT_NODE ? parent2.className : null;
      if (parent1ClassName === $P7.CLASS_NAME) {
        const tokenSpan = hitResult.offsetNode.childNodes[Math.min(hitResult.offset, hitResult.offsetNode.childNodes.length - 1)];
        if (tokenSpan) {
          return HitTestResult.createFromDOMInfo(ctx, tokenSpan, 0);
        }
      } else if (parent2ClassName === $P7.CLASS_NAME) {
        return HitTestResult.createFromDOMInfo(ctx, hitResult.offsetNode, 0);
      }
    }
    return new UnknownHitTestResult(hitResult.offsetNode);
  }
  static A(position, viewModel) {
    const lineContent = viewModel.getLineContent(position.lineNumber);
    const { tabSize } = viewModel.model.getOptions();
    const newPosition = $i6.atomicPosition(
      lineContent,
      position.column - 1,
      tabSize,
      2
      /* Direction.Nearest */
    );
    if (newPosition !== -1) {
      return new $8C(position.lineNumber, newPosition + 1);
    }
    return position;
  }
  static doHitTest(ctx, request) {
    let result = new UnknownHitTestResult();
    if (typeof ctx.viewDomNode.ownerDocument.caretRangeFromPoint === "function") {
      result = this.v(ctx, request);
    } else if (ctx.viewDomNode.ownerDocument.caretPositionFromPoint) {
      result = this.z(ctx, request.pos.toClientCoordinates(getWindow(ctx.viewDomNode)));
    }
    if (result.type === 1) {
      const injectedText = ctx.viewModel.getInjectedTextAt(result.position);
      const normalizedPosition = ctx.viewModel.normalizePosition(
        result.position,
        2
        /* PositionAffinity.None */
      );
      if (injectedText || !normalizedPosition.equals(result.position)) {
        result = new ContentHitTestResult(normalizedPosition, result.spanNode, injectedText);
      }
    }
    return result;
  }
};
function shadowCaretRangeFromPoint(shadowRoot, x, y) {
  const range = document.createRange();
  let el = shadowRoot.elementFromPoint(x, y);
  if (el !== null) {
    while (el && el.firstChild && el.firstChild.nodeType !== el.firstChild.TEXT_NODE && el.lastChild && el.lastChild.firstChild) {
      el = el.lastChild;
    }
    const rect = el.getBoundingClientRect();
    const elWindow = getWindow(el);
    const fontStyle = elWindow.getComputedStyle(el, null).getPropertyValue("font-style");
    const fontVariant = elWindow.getComputedStyle(el, null).getPropertyValue("font-variant");
    const fontWeight = elWindow.getComputedStyle(el, null).getPropertyValue("font-weight");
    const fontSize = elWindow.getComputedStyle(el, null).getPropertyValue("font-size");
    const lineHeight = elWindow.getComputedStyle(el, null).getPropertyValue("line-height");
    const fontFamily = elWindow.getComputedStyle(el, null).getPropertyValue("font-family");
    const font = `${fontStyle} ${fontVariant} ${fontWeight} ${fontSize}/${lineHeight} ${fontFamily}`;
    const text2 = el.innerText;
    let pixelCursor = rect.left;
    let offset = 0;
    let step;
    if (x > rect.left + rect.width) {
      offset = text2.length;
    } else {
      const charWidthReader = CharWidthReader.getInstance();
      for (let i2 = 0; i2 < text2.length + 1; i2++) {
        step = charWidthReader.getCharWidth(text2.charAt(i2), font) / 2;
        pixelCursor += step;
        if (x < pixelCursor) {
          offset = i2;
          break;
        }
        pixelCursor += step;
      }
    }
    range.setStart(el.firstChild, offset);
    range.setEnd(el.firstChild, offset);
  }
  return range;
}
var CharWidthReader = class _CharWidthReader {
  static {
    this.c = null;
  }
  static getInstance() {
    if (!_CharWidthReader.c) {
      _CharWidthReader.c = new _CharWidthReader();
    }
    return _CharWidthReader.c;
  }
  constructor() {
    this.f = {};
    this.g = document.createElement("canvas");
  }
  getCharWidth(char, font) {
    const cacheKey = char + font;
    if (this.f[cacheKey]) {
      return this.f[cacheKey];
    }
    const context = this.g.getContext("2d");
    context.font = font;
    const metrics = context.measureText(char);
    const width2 = metrics.width;
    this.f[cacheKey] = width2;
    return width2;
  }
};

// out-build/vs/base/common/decorators.js
function createDecorator(mapFn) {
  return (_target, key2, descriptor) => {
    let fnKey = null;
    let fn = null;
    if (typeof descriptor.value === "function") {
      fnKey = "value";
      fn = descriptor.value;
    } else if (typeof descriptor.get === "function") {
      fnKey = "get";
      fn = descriptor.get;
    }
    if (!fn || typeof key2 === "symbol") {
      throw new Error("not supported");
    }
    descriptor[fnKey] = mapFn(fn, key2);
  };
}
function $0t(_target, key2, 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$${key2}`;
  descriptor[fnKey] = function(...args2) {
    if (!this.hasOwnProperty(memoizeKey)) {
      Object.defineProperty(this, memoizeKey, {
        configurable: false,
        enumerable: false,
        writable: false,
        value: fn.apply(this, args2)
      });
    }
    return this[memoizeKey];
  };
}
function $$t(delay, reducer, initialValueProvider) {
  return createDecorator((fn, key2) => {
    const timerKey = `$debounce$${key2}`;
    const resultKey = `$debounce$result$${key2}`;
    return function(...args2) {
      if (!this[resultKey]) {
        this[resultKey] = initialValueProvider ? initialValueProvider() : void 0;
      }
      clearTimeout(this[timerKey]);
      if (reducer) {
        this[resultKey] = reducer(this[resultKey], ...args2);
        args2 = [this[resultKey]];
      }
      this[timerKey] = setTimeout(() => {
        fn.apply(this, args2);
        this[resultKey] = initialValueProvider ? initialValueProvider() : void 0;
      }, delay);
    };
  });
}
function $_t(delay, reducer, initialValueProvider) {
  return createDecorator((fn, key2) => {
    const timerKey = `$throttle$timer$${key2}`;
    const resultKey = `$throttle$result$${key2}`;
    const lastRunKey = `$throttle$lastRun$${key2}`;
    const pendingKey = `$throttle$pending$${key2}`;
    return function(...args2) {
      if (!this[resultKey]) {
        this[resultKey] = initialValueProvider ? initialValueProvider() : void 0;
      }
      if (this[lastRunKey] === null || this[lastRunKey] === void 0) {
        this[lastRunKey] = -Number.MAX_VALUE;
      }
      if (reducer) {
        this[resultKey] = reducer(this[resultKey], ...args2);
      }
      if (this[pendingKey]) {
        return;
      }
      const nextTime = this[lastRunKey] + delay;
      if (nextTime <= Date.now()) {
        this[lastRunKey] = Date.now();
        fn.apply(this, [this[resultKey]]);
        this[resultKey] = initialValueProvider ? initialValueProvider() : void 0;
      } else {
        this[pendingKey] = true;
        this[timerKey] = setTimeout(() => {
          this[pendingKey] = false;
          this[lastRunKey] = Date.now();
          fn.apply(this, [this[resultKey]]);
          this[resultKey] = initialValueProvider ? initialValueProvider() : void 0;
        }, nextTime - Date.now());
      }
    };
  });
}

// out-build/vs/base/browser/touch.js
var EventType;
(function(EventType2) {
  EventType2.Tap = "-monaco-gesturetap";
  EventType2.Change = "-monaco-gesturechange";
  EventType2.Start = "-monaco-gesturestart";
  EventType2.End = "-monaco-gesturesend";
  EventType2.Contextmenu = "-monaco-gesturecontextmenu";
})(EventType || (EventType = {}));
var $mZ = class _$mZ extends $3c {
  static {
    this.c = -5e-3;
  }
  static {
    this.g = 700;
  }
  static {
    this.u = 400;
  }
  // ms
  constructor() {
    super();
    this.h = false;
    this.j = new $cd();
    this.m = new $cd();
    this.r = {};
    this.n = null;
    this.s = 0;
    this.B(Event2.runAndSubscribe(onDidRegisterWindow, ({ window: window3, disposables }) => {
      disposables.add($_i(window3.document, "touchstart", (e) => this.w(e), { passive: false }));
      disposables.add($_i(window3.document, "touchend", (e) => this.z(window3, e)));
      disposables.add($_i(window3.document, "touchmove", (e) => this.G(e), { passive: false }));
    }, { window: $Y, disposables: this.q }));
  }
  static addTarget(element) {
    if (!_$mZ.isTouchDevice()) {
      return $3c.None;
    }
    if (!_$mZ.f) {
      _$mZ.f = $Vc(new _$mZ());
    }
    const remove = _$mZ.f.j.push(element);
    return $1c(remove);
  }
  static ignoreTarget(element) {
    if (!_$mZ.isTouchDevice()) {
      return $3c.None;
    }
    if (!_$mZ.f) {
      _$mZ.f = $Vc(new _$mZ());
    }
    const remove = _$mZ.f.m.push(element);
    return $1c(remove);
  }
  static isTouchDevice() {
    return "ontouchstart" in $Y || navigator.maxTouchPoints > 0;
  }
  dispose() {
    if (this.n) {
      this.n.dispose();
      this.n = null;
    }
    super.dispose();
  }
  w(e) {
    const timestamp = Date.now();
    if (this.n) {
      this.n.dispose();
      this.n = null;
    }
    for (let i2 = 0, len = e.targetTouches.length; i2 < len; i2++) {
      const touch = e.targetTouches.item(i2);
      this.r[touch.identifier] = {
        id: touch.identifier,
        initialTarget: touch.target,
        initialTimeStamp: timestamp,
        initialPageX: touch.pageX,
        initialPageY: touch.pageY,
        rollingTimestamps: [timestamp],
        rollingPageX: [touch.pageX],
        rollingPageY: [touch.pageY]
      };
      const evt = this.C(EventType.Start, touch.target);
      evt.pageX = touch.pageX;
      evt.pageY = touch.pageY;
      this.D(evt);
    }
    if (this.h) {
      e.preventDefault();
      e.stopPropagation();
      this.h = false;
    }
  }
  z(targetWindow, e) {
    const timestamp = Date.now();
    const activeTouchCount = Object.keys(this.r).length;
    for (let i2 = 0, len = e.changedTouches.length; i2 < len; i2++) {
      const touch = e.changedTouches.item(i2);
      if (!this.r.hasOwnProperty(String(touch.identifier))) {
        console.warn("move of an UNKNOWN touch", touch);
        continue;
      }
      const data = this.r[touch.identifier], holdTime = Date.now() - data.initialTimeStamp;
      if (holdTime < _$mZ.g && Math.abs(data.initialPageX - data.rollingPageX.at(-1)) < 30 && Math.abs(data.initialPageY - data.rollingPageY.at(-1)) < 30) {
        const evt = this.C(EventType.Tap, data.initialTarget);
        evt.pageX = data.rollingPageX.at(-1);
        evt.pageY = data.rollingPageY.at(-1);
        this.D(evt);
      } else if (holdTime >= _$mZ.g && Math.abs(data.initialPageX - data.rollingPageX.at(-1)) < 30 && Math.abs(data.initialPageY - data.rollingPageY.at(-1)) < 30) {
        const evt = this.C(EventType.Contextmenu, data.initialTarget);
        evt.pageX = data.rollingPageX.at(-1);
        evt.pageY = data.rollingPageY.at(-1);
        this.D(evt);
      } else if (activeTouchCount === 1) {
        const finalX = data.rollingPageX.at(-1);
        const finalY = data.rollingPageY.at(-1);
        const deltaT = data.rollingTimestamps.at(-1) - data.rollingTimestamps[0];
        const deltaX = finalX - data.rollingPageX[0];
        const deltaY = finalY - data.rollingPageY[0];
        const dispatchTo = [...this.j].filter((t) => data.initialTarget instanceof Node && t.contains(data.initialTarget));
        this.F(
          targetWindow,
          dispatchTo,
          timestamp,
          // time now
          Math.abs(deltaX) / deltaT,
          // speed
          deltaX > 0 ? 1 : -1,
          // x direction
          finalX,
          // x now
          Math.abs(deltaY) / deltaT,
          // y speed
          deltaY > 0 ? 1 : -1,
          // y direction
          finalY
          // y now
        );
      }
      this.D(this.C(EventType.End, data.initialTarget));
      delete this.r[touch.identifier];
    }
    if (this.h) {
      e.preventDefault();
      e.stopPropagation();
      this.h = false;
    }
  }
  C(type, initialTarget) {
    const event = document.createEvent("CustomEvent");
    event.initEvent(type, false, true);
    event.initialTarget = initialTarget;
    event.tapCount = 0;
    return event;
  }
  D(event) {
    if (event.type === EventType.Tap) {
      const currentTime = (/* @__PURE__ */ new Date()).getTime();
      let setTapCount = 0;
      if (currentTime - this.s > _$mZ.u) {
        setTapCount = 1;
      } else {
        setTapCount = 2;
      }
      this.s = currentTime;
      event.tapCount = setTapCount;
    } else if (event.type === EventType.Change || event.type === EventType.Contextmenu) {
      this.s = 0;
    }
    if (event.initialTarget instanceof Node) {
      for (const ignoreTarget of this.m) {
        if (ignoreTarget.contains(event.initialTarget)) {
          return;
        }
      }
      const targets = [];
      for (const target of this.j) {
        if (target.contains(event.initialTarget)) {
          let depth = 0;
          let now = event.initialTarget;
          while (now && now !== target) {
            depth++;
            now = now.parentElement;
          }
          targets.push([depth, target]);
        }
      }
      targets.sort((a, b) => a[0] - b[0]);
      for (const [_, target] of targets) {
        target.dispatchEvent(event);
        this.h = true;
      }
    }
  }
  F(targetWindow, dispatchTo, t1, vX, dirX, x, vY, dirY, y) {
    this.n = $jj(targetWindow, () => {
      const now = Date.now();
      const deltaT = now - t1;
      let delta_pos_x = 0, delta_pos_y = 0;
      let stopped = true;
      vX += _$mZ.c * deltaT;
      vY += _$mZ.c * deltaT;
      if (vX > 0) {
        stopped = false;
        delta_pos_x = dirX * vX * deltaT;
      }
      if (vY > 0) {
        stopped = false;
        delta_pos_y = dirY * vY * deltaT;
      }
      const evt = this.C(EventType.Change);
      evt.translationX = delta_pos_x;
      evt.translationY = delta_pos_y;
      dispatchTo.forEach((d) => d.dispatchEvent(evt));
      if (!stopped) {
        this.F(targetWindow, dispatchTo, now, vX, dirX, x + delta_pos_x, vY, dirY, y + delta_pos_y);
      }
    });
  }
  G(e) {
    const timestamp = Date.now();
    for (let i2 = 0, len = e.changedTouches.length; i2 < len; i2++) {
      const touch = e.changedTouches.item(i2);
      if (!this.r.hasOwnProperty(String(touch.identifier))) {
        console.warn("end of an UNKNOWN touch", touch);
        continue;
      }
      const data = this.r[touch.identifier];
      const evt = this.C(EventType.Change, data.initialTarget);
      evt.translationX = touch.pageX - data.rollingPageX.at(-1);
      evt.translationY = touch.pageY - data.rollingPageY.at(-1);
      evt.pageX = touch.pageX;
      evt.pageY = touch.pageY;
      this.D(evt);
      if (data.rollingPageX.length > 3) {
        data.rollingPageX.shift();
        data.rollingPageY.shift();
        data.rollingTimestamps.shift();
      }
      data.rollingPageX.push(touch.pageX);
      data.rollingPageY.push(touch.pageY);
      data.rollingTimestamps.push(timestamp);
    }
    if (this.h) {
      e.preventDefault();
      e.stopPropagation();
      this.h = false;
    }
  }
};
__decorate([
  $0t
], $mZ, "isTouchDevice", null);

// out-build/vs/base/browser/ui/widget.js
var $qZ = class extends $3c {
  b(domNode, listener) {
    this.B($_i(domNode, $7j.CLICK, (e) => listener(new $lf(getWindow(domNode), e))));
  }
  f(domNode, listener) {
    this.B($_i(domNode, $7j.MOUSE_DOWN, (e) => listener(new $lf(getWindow(domNode), e))));
  }
  j(domNode, listener) {
    this.B($_i(domNode, $7j.MOUSE_OVER, (e) => listener(new $lf(getWindow(domNode), e))));
  }
  m(domNode, listener) {
    this.B($_i(domNode, $7j.MOUSE_LEAVE, (e) => listener(new $lf(getWindow(domNode), e))));
  }
  s(domNode, listener) {
    this.B($_i(domNode, $7j.KEY_DOWN, (e) => listener(new $if(e))));
  }
  u(domNode, listener) {
    this.B($_i(domNode, $7j.KEY_UP, (e) => listener(new $if(e))));
  }
  z(domNode, listener) {
    this.B($_i(domNode, $7j.INPUT, listener));
  }
  C(domNode, listener) {
    this.B($_i(domNode, $7j.BLUR, listener));
  }
  D(domNode, listener) {
    this.B($_i(domNode, $7j.FOCUS, listener));
  }
  F(domNode, listener) {
    this.B($_i(domNode, $7j.CHANGE, listener));
  }
  G(domNode) {
    return $mZ.ignoreTarget(domNode);
  }
};

// out-build/vs/base/browser/ui/scrollbar/scrollbarArrow.js
var $rZ = 11;
var $sZ = class extends $qZ {
  constructor(opts) {
    super();
    this.a = opts.onActivate;
    this.bgDomNode = document.createElement("div");
    this.bgDomNode.className = "arrow-background";
    this.bgDomNode.style.position = "absolute";
    this.bgDomNode.style.width = opts.bgWidth + "px";
    this.bgDomNode.style.height = opts.bgHeight + "px";
    if (typeof opts.top !== "undefined") {
      this.bgDomNode.style.top = "0px";
    }
    if (typeof opts.left !== "undefined") {
      this.bgDomNode.style.left = "0px";
    }
    if (typeof opts.bottom !== "undefined") {
      this.bgDomNode.style.bottom = "0px";
    }
    if (typeof opts.right !== "undefined") {
      this.bgDomNode.style.right = "0px";
    }
    this.domNode = document.createElement("div");
    this.domNode.className = opts.className;
    this.domNode.classList.add(...ThemeIcon.asClassNameArray(opts.icon));
    this.domNode.style.position = "absolute";
    this.domNode.style.width = $rZ + "px";
    this.domNode.style.height = $rZ + "px";
    if (typeof opts.top !== "undefined") {
      this.domNode.style.top = opts.top + "px";
    }
    if (typeof opts.left !== "undefined") {
      this.domNode.style.left = opts.left + "px";
    }
    if (typeof opts.bottom !== "undefined") {
      this.domNode.style.bottom = opts.bottom + "px";
    }
    if (typeof opts.right !== "undefined") {
      this.domNode.style.right = opts.right + "px";
    }
    this.h = this.B(new $pZ());
    this.B($aj(this.bgDomNode, $7j.POINTER_DOWN, (e) => this.n(e)));
    this.B($aj(this.domNode, $7j.POINTER_DOWN, (e) => this.n(e)));
    this.c = this.B(new $lj());
    this.g = this.B(new $6h());
  }
  n(e) {
    if (!e.target || !(e.target instanceof Element)) {
      return;
    }
    const scheduleRepeater = () => {
      this.c.cancelAndSet(() => this.a(), 1e3 / 24, getWindow(e));
    };
    this.a();
    this.c.cancel();
    this.g.cancelAndSet(scheduleRepeater, 200);
    this.h.startMonitoring(e.target, e.pointerId, e.buttons, (pointerMoveData) => {
    }, () => {
      this.c.cancel();
      this.g.cancel();
    });
    e.preventDefault();
  }
};

// out-build/vs/base/browser/ui/scrollbar/scrollbarVisibilityController.js
var $uZ = class extends $3c {
  constructor(visibility, visibleClassName, invisibleClassName) {
    super();
    this.a = visibility;
    this.b = visibleClassName;
    this.c = invisibleClassName;
    this.f = null;
    this.m = false;
    this.j = false;
    this.g = false;
    this.h = false;
    this.n = this.B(new $6h());
  }
  setVisibility(visibility) {
    if (this.a !== visibility) {
      this.a = visibility;
      this.s();
    }
  }
  // ----------------- Hide / Reveal
  setShouldBeVisible(rawShouldBeVisible) {
    this.g = rawShouldBeVisible;
    this.s();
  }
  r() {
    if (this.a === 2) {
      return false;
    }
    if (this.a === 3) {
      return true;
    }
    return this.g;
  }
  s() {
    const shouldBeVisible = this.r();
    if (this.h !== shouldBeVisible) {
      this.h = shouldBeVisible;
      this.ensureVisibility();
    }
  }
  setIsNeeded(isNeeded) {
    if (this.j !== isNeeded) {
      this.j = isNeeded;
      this.ensureVisibility();
    }
  }
  setDomNode(domNode) {
    this.f = domNode;
    this.f.setClassName(this.c);
    this.setShouldBeVisible(false);
  }
  ensureVisibility() {
    if (!this.j) {
      this.u(false);
      return;
    }
    if (this.h) {
      this.t();
    } else {
      this.u(true);
    }
  }
  t() {
    if (this.m) {
      return;
    }
    this.m = true;
    this.n.setIfNotSet(() => {
      this.f?.setClassName(this.b);
    }, 0);
  }
  u(withFadeAway) {
    this.n.cancel();
    if (!this.m) {
      return;
    }
    this.m = false;
    this.f?.setClassName(this.c + (withFadeAway ? " fade" : ""));
  }
};

// out-build/vs/base/browser/ui/scrollbar/abstractScrollbar.js
var POINTER_DRAG_RESET_DISTANCE = 140;
var $vZ = class extends $qZ {
  constructor(opts) {
    super();
    this.h = opts.lazyRender;
    this.a = opts.host;
    this.c = opts.scrollable;
    this.g = opts.scrollByPage;
    this.n = opts.scrollbarState;
    this.r = this.B(new $uZ(opts.visibility, "visible scrollbar " + opts.extraScrollbarClassName, "invisible scrollbar " + opts.extraScrollbarClassName));
    this.r.setIsNeeded(this.n.isNeeded());
    this.t = this.B(new $pZ());
    this.w = true;
    this.domNode = $oZ(document.createElement("div"));
    this.domNode.setAttribute("role", "presentation");
    this.domNode.setAttribute("aria-hidden", "true");
    this.r.setDomNode(this.domNode);
    this.domNode.setPosition("absolute");
    this.B($_i(this.domNode.domNode, $7j.POINTER_DOWN, (e) => this.M(e)));
  }
  // ----------------- creation
  /**
   * Creates the dom node for an arrow & adds it to the container
   */
  y(opts) {
    const arrow = this.B(new $sZ(opts));
    this.domNode.domNode.appendChild(arrow.bgDomNode);
    this.domNode.domNode.appendChild(arrow.domNode);
  }
  /**
   * Creates the slider dom node, adds it to the container & hooks up the events
   */
  H(top2, left, width2, height) {
    this.slider = $oZ(document.createElement("div"));
    this.slider.setClassName("slider");
    this.slider.setPosition("absolute");
    this.slider.setTop(top2);
    this.slider.setLeft(left);
    if (typeof width2 === "number") {
      this.slider.setWidth(width2);
    }
    if (typeof height === "number") {
      this.slider.setHeight(height);
    }
    this.slider.setLayerHinting(true);
    this.slider.setContain("strict");
    this.domNode.domNode.appendChild(this.slider.domNode);
    this.B($_i(this.slider.domNode, $7j.POINTER_DOWN, (e) => {
      if (e.button === 0) {
        e.preventDefault();
        this.O(e);
      }
    }));
    this.b(this.slider.domNode, (e) => {
      if (e.leftButton) {
        e.stopPropagation();
      }
    });
  }
  // ----------------- Update state
  I(visibleSize) {
    if (this.n.setVisibleSize(visibleSize)) {
      this.r.setIsNeeded(this.n.isNeeded());
      this.w = true;
      if (!this.h) {
        this.render();
      }
    }
    return this.w;
  }
  J(elementScrollSize) {
    if (this.n.setScrollSize(elementScrollSize)) {
      this.r.setIsNeeded(this.n.isNeeded());
      this.w = true;
      if (!this.h) {
        this.render();
      }
    }
    return this.w;
  }
  L(elementScrollPosition) {
    if (this.n.setScrollPosition(elementScrollPosition)) {
      this.r.setIsNeeded(this.n.isNeeded());
      this.w = true;
      if (!this.h) {
        this.render();
      }
    }
    return this.w;
  }
  // ----------------- rendering
  beginReveal() {
    this.r.setShouldBeVisible(true);
  }
  beginHide() {
    this.r.setShouldBeVisible(false);
  }
  render() {
    if (!this.w) {
      return;
    }
    this.w = false;
    this.Q(this.n.getRectangleLargeSize(), this.n.getRectangleSmallSize());
    this.R(this.n.getSliderSize(), this.n.getArrowSize() + this.n.getSliderPosition());
  }
  // ----------------- DOM events
  M(e) {
    if (e.target !== this.domNode.domNode) {
      return;
    }
    this.N(e);
  }
  delegatePointerDown(e) {
    const domTop = this.domNode.domNode.getClientRects()[0].top;
    const sliderStart = domTop + this.n.getSliderPosition();
    const sliderStop = domTop + this.n.getSliderPosition() + this.n.getSliderSize();
    const pointerPos = this.U(e);
    if (sliderStart <= pointerPos && pointerPos <= sliderStop) {
      if (e.button === 0) {
        e.preventDefault();
        this.O(e);
      }
    } else {
      this.N(e);
    }
  }
  N(e) {
    let offsetX;
    let offsetY;
    if (e.target === this.domNode.domNode && typeof e.offsetX === "number" && typeof e.offsetY === "number") {
      offsetX = e.offsetX;
      offsetY = e.offsetY;
    } else {
      const domNodePosition = $vj(this.domNode.domNode);
      offsetX = e.pageX - domNodePosition.left;
      offsetY = e.pageY - domNodePosition.top;
    }
    const offset = this.S(offsetX, offsetY);
    this.P(this.g ? this.n.getDesiredScrollPositionFromOffsetPaged(offset) : this.n.getDesiredScrollPositionFromOffset(offset));
    if (e.button === 0) {
      e.preventDefault();
      this.O(e);
    }
  }
  O(e) {
    if (!e.target || !(e.target instanceof Element)) {
      return;
    }
    const initialPointerPosition = this.U(e);
    const initialPointerOrthogonalPosition = this.W(e);
    const initialScrollbarState = this.n.clone();
    this.slider.toggleClassName("active", true);
    this.t.startMonitoring(e.target, e.pointerId, e.buttons, (pointerMoveData) => {
      const pointerOrthogonalPosition = this.W(pointerMoveData);
      const pointerOrthogonalDelta = Math.abs(pointerOrthogonalPosition - initialPointerOrthogonalPosition);
      if ($l && pointerOrthogonalDelta > POINTER_DRAG_RESET_DISTANCE) {
        this.P(initialScrollbarState.getScrollPosition());
        return;
      }
      const pointerPosition = this.U(pointerMoveData);
      const pointerDelta = pointerPosition - initialPointerPosition;
      this.P(initialScrollbarState.getDesiredScrollPositionFromDelta(pointerDelta));
    }, () => {
      this.slider.toggleClassName("active", false);
      this.a.onDragEnd();
    });
    this.a.onDragStart();
  }
  P(_desiredScrollPosition) {
    const desiredScrollPosition = {};
    this.writeScrollPosition(desiredScrollPosition, _desiredScrollPosition);
    this.c.setScrollPositionNow(desiredScrollPosition);
  }
  updateScrollbarSize(scrollbarSize) {
    this.X(scrollbarSize);
    this.n.setScrollbarSize(scrollbarSize);
    this.w = true;
    if (!this.h) {
      this.render();
    }
  }
  isNeeded() {
    return this.n.isNeeded();
  }
};

// out-build/vs/base/browser/ui/scrollbar/scrollbarState.js
var MINIMUM_SLIDER_SIZE = 20;
var $tZ = class _$tZ {
  constructor(arrowSize, scrollbarSize, oppositeScrollbarSize, visibleSize, scrollSize, scrollPosition) {
    this.a = Math.round(scrollbarSize);
    this.b = Math.round(oppositeScrollbarSize);
    this.c = Math.round(arrowSize);
    this.d = visibleSize;
    this.e = scrollSize;
    this.f = scrollPosition;
    this.g = 0;
    this.h = false;
    this.i = 0;
    this.j = 0;
    this.k = 0;
    this.m();
  }
  clone() {
    return new _$tZ(this.c, this.a, this.b, this.d, this.e, this.f);
  }
  setVisibleSize(visibleSize) {
    const iVisibleSize = Math.round(visibleSize);
    if (this.d !== iVisibleSize) {
      this.d = iVisibleSize;
      this.m();
      return true;
    }
    return false;
  }
  setScrollSize(scrollSize) {
    const iScrollSize = Math.round(scrollSize);
    if (this.e !== iScrollSize) {
      this.e = iScrollSize;
      this.m();
      return true;
    }
    return false;
  }
  setScrollPosition(scrollPosition) {
    const iScrollPosition = Math.round(scrollPosition);
    if (this.f !== iScrollPosition) {
      this.f = iScrollPosition;
      this.m();
      return true;
    }
    return false;
  }
  setScrollbarSize(scrollbarSize) {
    this.a = Math.round(scrollbarSize);
  }
  setOppositeScrollbarSize(oppositeScrollbarSize) {
    this.b = Math.round(oppositeScrollbarSize);
  }
  static l(oppositeScrollbarSize, arrowSize, visibleSize, scrollSize, scrollPosition) {
    const computedAvailableSize = Math.max(0, visibleSize - oppositeScrollbarSize);
    const computedRepresentableSize = Math.max(0, computedAvailableSize - 2 * arrowSize);
    const computedIsNeeded = scrollSize > 0 && scrollSize > visibleSize;
    if (!computedIsNeeded) {
      return {
        computedAvailableSize: Math.round(computedAvailableSize),
        computedIsNeeded,
        computedSliderSize: Math.round(computedRepresentableSize),
        computedSliderRatio: 0,
        computedSliderPosition: 0
      };
    }
    const computedSliderSize = Math.round(Math.max(MINIMUM_SLIDER_SIZE, Math.floor(visibleSize * computedRepresentableSize / scrollSize)));
    const computedSliderRatio = (computedRepresentableSize - computedSliderSize) / (scrollSize - visibleSize);
    const computedSliderPosition = scrollPosition * computedSliderRatio;
    return {
      computedAvailableSize: Math.round(computedAvailableSize),
      computedIsNeeded,
      computedSliderSize: Math.round(computedSliderSize),
      computedSliderRatio,
      computedSliderPosition: Math.round(computedSliderPosition)
    };
  }
  m() {
    const r2 = _$tZ.l(this.b, this.c, this.d, this.e, this.f);
    this.g = r2.computedAvailableSize;
    this.h = r2.computedIsNeeded;
    this.i = r2.computedSliderSize;
    this.j = r2.computedSliderRatio;
    this.k = r2.computedSliderPosition;
  }
  getArrowSize() {
    return this.c;
  }
  getScrollPosition() {
    return this.f;
  }
  getRectangleLargeSize() {
    return this.g;
  }
  getRectangleSmallSize() {
    return this.a;
  }
  isNeeded() {
    return this.h;
  }
  getSliderSize() {
    return this.i;
  }
  getSliderPosition() {
    return this.k;
  }
  /**
   * Compute a desired `scrollPosition` such that `offset` ends up in the center of the slider.
   * `offset` is based on the same coordinate system as the `sliderPosition`.
   */
  getDesiredScrollPositionFromOffset(offset) {
    if (!this.h) {
      return 0;
    }
    const desiredSliderPosition = offset - this.c - this.i / 2;
    return Math.round(desiredSliderPosition / this.j);
  }
  /**
   * Compute a desired `scrollPosition` from if offset is before or after the slider position.
   * If offset is before slider, treat as a page up (or left).  If after, page down (or right).
   * `offset` and `_computedSliderPosition` are based on the same coordinate system.
   * `_visibleSize` corresponds to a "page" of lines in the returned coordinate system.
   */
  getDesiredScrollPositionFromOffsetPaged(offset) {
    if (!this.h) {
      return 0;
    }
    const correctedOffset = offset - this.c;
    let desiredScrollPosition = this.f;
    if (correctedOffset < this.k) {
      desiredScrollPosition -= this.d;
    } else {
      desiredScrollPosition += this.d;
    }
    return desiredScrollPosition;
  }
  /**
   * Compute a desired `scrollPosition` such that the slider moves by `delta`.
   */
  getDesiredScrollPositionFromDelta(delta) {
    if (!this.h) {
      return 0;
    }
    const desiredSliderPosition = this.k + delta;
    return Math.round(desiredSliderPosition / this.j);
  }
};

// out-build/vs/base/browser/ui/scrollbar/horizontalScrollbar.js
var $wZ = class extends $vZ {
  constructor(scrollable, options3, host) {
    const scrollDimensions = scrollable.getScrollDimensions();
    const scrollPosition = scrollable.getCurrentScrollPosition();
    super({
      lazyRender: options3.lazyRender,
      host,
      scrollbarState: new $tZ(options3.horizontalHasArrows ? options3.arrowSize : 0, options3.horizontal === 2 ? 0 : options3.horizontalScrollbarSize, options3.vertical === 2 ? 0 : options3.verticalScrollbarSize, scrollDimensions.width, scrollDimensions.scrollWidth, scrollPosition.scrollLeft),
      visibility: options3.horizontal,
      extraScrollbarClassName: "horizontal",
      scrollable,
      scrollByPage: options3.scrollByPage
    });
    if (options3.horizontalHasArrows) {
      const arrowDelta = (options3.arrowSize - $rZ) / 2;
      const scrollbarDelta = (options3.horizontalScrollbarSize - $rZ) / 2;
      this.y({
        className: "scra",
        icon: $6l.scrollbarButtonLeft,
        top: scrollbarDelta,
        left: arrowDelta,
        bottom: void 0,
        right: void 0,
        bgWidth: options3.arrowSize,
        bgHeight: options3.horizontalScrollbarSize,
        onActivate: () => this.a.onMouseWheel(new $nf(null, 1, 0))
      });
      this.y({
        className: "scra",
        icon: $6l.scrollbarButtonRight,
        top: scrollbarDelta,
        left: void 0,
        bottom: void 0,
        right: arrowDelta,
        bgWidth: options3.arrowSize,
        bgHeight: options3.horizontalScrollbarSize,
        onActivate: () => this.a.onMouseWheel(new $nf(null, -1, 0))
      });
    }
    this.H(Math.floor((options3.horizontalScrollbarSize - options3.horizontalSliderSize) / 2), 0, void 0, options3.horizontalSliderSize);
  }
  R(sliderSize, sliderPosition) {
    this.slider.setWidth(sliderSize);
    this.slider.setLeft(sliderPosition);
  }
  Q(largeSize, smallSize) {
    this.domNode.setWidth(largeSize);
    this.domNode.setHeight(smallSize);
    this.domNode.setLeft(0);
    this.domNode.setBottom(0);
  }
  onDidScroll(e) {
    this.w = this.J(e.scrollWidth) || this.w;
    this.w = this.L(e.scrollLeft) || this.w;
    this.w = this.I(e.width) || this.w;
    return this.w;
  }
  S(offsetX, offsetY) {
    return offsetX;
  }
  U(e) {
    return e.pageX;
  }
  W(e) {
    return e.pageY;
  }
  X(size) {
    this.slider.setHeight(size);
  }
  writeScrollPosition(target, scrollPosition) {
    target.scrollLeft = scrollPosition;
  }
  updateOptions(options3) {
    this.updateScrollbarSize(options3.horizontal === 2 ? 0 : options3.horizontalScrollbarSize);
    this.n.setOppositeScrollbarSize(options3.vertical === 2 ? 0 : options3.verticalScrollbarSize);
    this.r.setVisibility(options3.horizontal);
    this.g = options3.scrollByPage;
  }
};

// out-build/vs/base/browser/ui/scrollbar/verticalScrollbar.js
var $xZ = class extends $vZ {
  constructor(scrollable, options3, host) {
    const scrollDimensions = scrollable.getScrollDimensions();
    const scrollPosition = scrollable.getCurrentScrollPosition();
    super({
      lazyRender: options3.lazyRender,
      host,
      scrollbarState: new $tZ(
        options3.verticalHasArrows ? options3.arrowSize : 0,
        options3.vertical === 2 ? 0 : options3.verticalScrollbarSize,
        // give priority to vertical scroll bar over horizontal and let it scroll all the way to the bottom
        0,
        scrollDimensions.height,
        scrollDimensions.scrollHeight,
        scrollPosition.scrollTop
      ),
      visibility: options3.vertical,
      extraScrollbarClassName: "vertical",
      scrollable,
      scrollByPage: options3.scrollByPage
    });
    if (options3.verticalHasArrows) {
      const arrowDelta = (options3.arrowSize - $rZ) / 2;
      const scrollbarDelta = (options3.verticalScrollbarSize - $rZ) / 2;
      this.y({
        className: "scra",
        icon: $6l.scrollbarButtonUp,
        top: arrowDelta,
        left: scrollbarDelta,
        bottom: void 0,
        right: void 0,
        bgWidth: options3.verticalScrollbarSize,
        bgHeight: options3.arrowSize,
        onActivate: () => this.a.onMouseWheel(new $nf(null, 0, 1))
      });
      this.y({
        className: "scra",
        icon: $6l.scrollbarButtonDown,
        top: void 0,
        left: scrollbarDelta,
        bottom: arrowDelta,
        right: void 0,
        bgWidth: options3.verticalScrollbarSize,
        bgHeight: options3.arrowSize,
        onActivate: () => this.a.onMouseWheel(new $nf(null, 0, -1))
      });
    }
    this.H(0, Math.floor((options3.verticalScrollbarSize - options3.verticalSliderSize) / 2), options3.verticalSliderSize, void 0);
  }
  R(sliderSize, sliderPosition) {
    this.slider.setHeight(sliderSize);
    this.slider.setTop(sliderPosition);
  }
  Q(largeSize, smallSize) {
    this.domNode.setWidth(smallSize);
    this.domNode.setHeight(largeSize);
    this.domNode.setRight(0);
    this.domNode.setTop(0);
  }
  onDidScroll(e) {
    this.w = this.J(e.scrollHeight) || this.w;
    this.w = this.L(e.scrollTop) || this.w;
    this.w = this.I(e.height) || this.w;
    return this.w;
  }
  S(offsetX, offsetY) {
    return offsetY;
  }
  U(e) {
    return e.pageY;
  }
  W(e) {
    return e.pageX;
  }
  X(size) {
    this.slider.setWidth(size);
  }
  writeScrollPosition(target, scrollPosition) {
    target.scrollTop = scrollPosition;
  }
  updateOptions(options3) {
    this.updateScrollbarSize(options3.vertical === 2 ? 0 : options3.verticalScrollbarSize);
    this.n.setOppositeScrollbarSize(0);
    this.r.setVisibility(options3.vertical);
    this.g = options3.scrollByPage;
  }
};

// out-build/vs/base/common/scrollable.js
var ScrollbarVisibility;
(function(ScrollbarVisibility3) {
  ScrollbarVisibility3[ScrollbarVisibility3["Auto"] = 1] = "Auto";
  ScrollbarVisibility3[ScrollbarVisibility3["Hidden"] = 2] = "Hidden";
  ScrollbarVisibility3[ScrollbarVisibility3["Visible"] = 3] = "Visible";
})(ScrollbarVisibility || (ScrollbarVisibility = {}));
var $zD = class _$zD {
  constructor(c, width2, scrollWidth, scrollLeft, height, scrollHeight, scrollTop) {
    this.c = c;
    this._scrollStateBrand = void 0;
    if (this.c) {
      width2 = width2 | 0;
      scrollWidth = scrollWidth | 0;
      scrollLeft = scrollLeft | 0;
      height = height | 0;
      scrollHeight = scrollHeight | 0;
      scrollTop = scrollTop | 0;
    }
    this.rawScrollLeft = scrollLeft;
    this.rawScrollTop = scrollTop;
    if (width2 < 0) {
      width2 = 0;
    }
    if (scrollLeft + width2 > scrollWidth) {
      scrollLeft = scrollWidth - width2;
    }
    if (scrollLeft < 0) {
      scrollLeft = 0;
    }
    if (height < 0) {
      height = 0;
    }
    if (scrollTop + height > scrollHeight) {
      scrollTop = scrollHeight - height;
    }
    if (scrollTop < 0) {
      scrollTop = 0;
    }
    this.width = width2;
    this.scrollWidth = scrollWidth;
    this.scrollLeft = scrollLeft;
    this.height = height;
    this.scrollHeight = scrollHeight;
    this.scrollTop = scrollTop;
  }
  equals(other) {
    return this.rawScrollLeft === other.rawScrollLeft && this.rawScrollTop === other.rawScrollTop && this.width === other.width && this.scrollWidth === other.scrollWidth && this.scrollLeft === other.scrollLeft && this.height === other.height && this.scrollHeight === other.scrollHeight && this.scrollTop === other.scrollTop;
  }
  withScrollDimensions(update, useRawScrollPositions) {
    return new _$zD(this.c, typeof update.width !== "undefined" ? update.width : this.width, typeof update.scrollWidth !== "undefined" ? update.scrollWidth : this.scrollWidth, useRawScrollPositions ? this.rawScrollLeft : this.scrollLeft, typeof update.height !== "undefined" ? update.height : this.height, typeof update.scrollHeight !== "undefined" ? update.scrollHeight : this.scrollHeight, useRawScrollPositions ? this.rawScrollTop : this.scrollTop);
  }
  withScrollPosition(update) {
    return new _$zD(this.c, this.width, this.scrollWidth, typeof update.scrollLeft !== "undefined" ? update.scrollLeft : this.rawScrollLeft, this.height, this.scrollHeight, typeof update.scrollTop !== "undefined" ? update.scrollTop : this.rawScrollTop);
  }
  createScrollEvent(previous, inSmoothScrolling) {
    const widthChanged = this.width !== previous.width;
    const scrollWidthChanged = this.scrollWidth !== previous.scrollWidth;
    const scrollLeftChanged = this.scrollLeft !== previous.scrollLeft;
    const heightChanged = this.height !== previous.height;
    const scrollHeightChanged = this.scrollHeight !== previous.scrollHeight;
    const scrollTopChanged = this.scrollTop !== previous.scrollTop;
    return {
      inSmoothScrolling,
      oldWidth: previous.width,
      oldScrollWidth: previous.scrollWidth,
      oldScrollLeft: previous.scrollLeft,
      width: this.width,
      scrollWidth: this.scrollWidth,
      scrollLeft: this.scrollLeft,
      oldHeight: previous.height,
      oldScrollHeight: previous.scrollHeight,
      oldScrollTop: previous.scrollTop,
      height: this.height,
      scrollHeight: this.scrollHeight,
      scrollTop: this.scrollTop,
      widthChanged,
      scrollWidthChanged,
      scrollLeftChanged,
      heightChanged,
      scrollHeightChanged,
      scrollTopChanged
    };
  }
};
var $AD = class extends $3c {
  constructor(options3) {
    super();
    this._scrollableBrand = void 0;
    this.j = this.B(new $ze());
    this.onScroll = this.j.event;
    this.c = options3.smoothScrollDuration;
    this.f = options3.scheduleAtNextAnimationFrame;
    this.g = new $zD(options3.forceIntegerValues, 0, 0, 0, 0, 0, 0);
    this.h = null;
  }
  dispose() {
    if (this.h) {
      this.h.dispose();
      this.h = null;
    }
    super.dispose();
  }
  setSmoothScrollDuration(smoothScrollDuration) {
    this.c = smoothScrollDuration;
  }
  validateScrollPosition(scrollPosition) {
    return this.g.withScrollPosition(scrollPosition);
  }
  getScrollDimensions() {
    return this.g;
  }
  setScrollDimensions(dimensions, useRawScrollPositions) {
    const newState = this.g.withScrollDimensions(dimensions, useRawScrollPositions);
    this.n(newState, Boolean(this.h));
    this.h?.acceptScrollDimensions(this.g);
  }
  /**
   * Returns the final scroll position that the instance will have once the smooth scroll animation concludes.
   * If no scroll animation is occurring, it will return the current scroll position instead.
   */
  getFutureScrollPosition() {
    if (this.h) {
      return this.h.to;
    }
    return this.g;
  }
  /**
   * Returns the current scroll position.
   * Note: This result might be an intermediate scroll position, as there might be an ongoing smooth scroll animation.
   */
  getCurrentScrollPosition() {
    return this.g;
  }
  setScrollPositionNow(update) {
    const newState = this.g.withScrollPosition(update);
    if (this.h) {
      this.h.dispose();
      this.h = null;
    }
    this.n(newState, false);
  }
  setScrollPositionSmooth(update, reuseAnimation) {
    if (this.c === 0) {
      return this.setScrollPositionNow(update);
    }
    if (this.h) {
      update = {
        scrollLeft: typeof update.scrollLeft === "undefined" ? this.h.to.scrollLeft : update.scrollLeft,
        scrollTop: typeof update.scrollTop === "undefined" ? this.h.to.scrollTop : update.scrollTop
      };
      const validTarget = this.g.withScrollPosition(update);
      if (this.h.to.scrollLeft === validTarget.scrollLeft && this.h.to.scrollTop === validTarget.scrollTop) {
        return;
      }
      let newSmoothScrolling;
      if (reuseAnimation) {
        newSmoothScrolling = new $CD(this.h.from, validTarget, this.h.startTime, this.h.duration);
      } else {
        newSmoothScrolling = this.h.combine(this.g, validTarget, this.c);
      }
      this.h.dispose();
      this.h = newSmoothScrolling;
    } else {
      const validTarget = this.g.withScrollPosition(update);
      this.h = $CD.start(this.g, validTarget, this.c);
    }
    this.h.animationFrameDisposable = this.f(() => {
      if (!this.h) {
        return;
      }
      this.h.animationFrameDisposable = null;
      this.m();
    });
  }
  hasPendingScrollAnimation() {
    return Boolean(this.h);
  }
  m() {
    if (!this.h) {
      return;
    }
    const update = this.h.tick();
    const newState = this.g.withScrollPosition(update);
    this.n(newState, true);
    if (!this.h) {
      return;
    }
    if (update.isDone) {
      this.h.dispose();
      this.h = null;
      return;
    }
    this.h.animationFrameDisposable = this.f(() => {
      if (!this.h) {
        return;
      }
      this.h.animationFrameDisposable = null;
      this.m();
    });
  }
  n(newState, inSmoothScrolling) {
    const oldState = this.g;
    if (oldState.equals(newState)) {
      return;
    }
    this.g = newState;
    this.j.fire(this.g.createScrollEvent(oldState, inSmoothScrolling));
  }
};
var $BD = class {
  constructor(scrollLeft, scrollTop, isDone) {
    this.scrollLeft = scrollLeft;
    this.scrollTop = scrollTop;
    this.isDone = isDone;
  }
};
function createEaseOutCubic(from, to) {
  const delta = to - from;
  return function(completion) {
    return from + delta * easeOutCubic(completion);
  };
}
function createComposed(a, b, cut) {
  return function(completion) {
    if (completion < cut) {
      return a(completion / cut);
    }
    return b((completion - cut) / (1 - cut));
  };
}
var $CD = class _$CD {
  constructor(from, to, startTime, duration) {
    this.from = from;
    this.to = to;
    this.duration = duration;
    this.startTime = startTime;
    this.animationFrameDisposable = null;
    this.e();
  }
  e() {
    this.c = this.f(this.from.scrollLeft, this.to.scrollLeft, this.to.width);
    this.d = this.f(this.from.scrollTop, this.to.scrollTop, this.to.height);
  }
  f(from, to, viewportSize) {
    const delta = Math.abs(from - to);
    if (delta > 2.5 * viewportSize) {
      let stop1, stop2;
      if (from < to) {
        stop1 = from + 0.75 * viewportSize;
        stop2 = to - 0.75 * viewportSize;
      } else {
        stop1 = from - 0.75 * viewportSize;
        stop2 = to + 0.75 * viewportSize;
      }
      return createComposed(createEaseOutCubic(from, stop1), createEaseOutCubic(stop2, to), 0.33);
    }
    return createEaseOutCubic(from, to);
  }
  dispose() {
    if (this.animationFrameDisposable !== null) {
      this.animationFrameDisposable.dispose();
      this.animationFrameDisposable = null;
    }
  }
  acceptScrollDimensions(state) {
    this.to = state.withScrollPosition(this.to);
    this.e();
  }
  tick() {
    return this.g(Date.now());
  }
  g(now) {
    const completion = (now - this.startTime) / this.duration;
    if (completion < 1) {
      const newScrollLeft = this.c(completion);
      const newScrollTop = this.d(completion);
      return new $BD(newScrollLeft, newScrollTop, false);
    }
    return new $BD(this.to.scrollLeft, this.to.scrollTop, true);
  }
  combine(from, to, duration) {
    return _$CD.start(from, to, duration);
  }
  static start(from, to, duration) {
    duration = duration + 10;
    const startTime = Date.now() - 10;
    return new _$CD(from, to, startTime, duration);
  }
};
function easeInCubic(t) {
  return Math.pow(t, 3);
}
function easeOutCubic(t) {
  return 1 - easeInCubic(1 - t);
}

// out-build/vs/base/browser/ui/scrollbar/scrollableElement.js
var HIDE_TIMEOUT = 500;
var SCROLL_WHEEL_SENSITIVITY = 50;
var SCROLL_WHEEL_SMOOTH_SCROLL_ENABLED = true;
var MouseWheelClassifierItem = class {
  constructor(timestamp, deltaX, deltaY) {
    this.timestamp = timestamp;
    this.deltaX = deltaX;
    this.deltaY = deltaY;
    this.score = 0;
  }
};
var $yZ = class _$yZ {
  static {
    this.INSTANCE = new _$yZ();
  }
  constructor() {
    this.a = 5;
    this.b = [];
    this.c = -1;
    this.d = -1;
  }
  isPhysicalMouseWheel() {
    if (this.c === -1 && this.d === -1) {
      return false;
    }
    let remainingInfluence = 1;
    let score2 = 0;
    let iteration = 1;
    let index = this.d;
    do {
      const influence = index === this.c ? remainingInfluence : Math.pow(2, -iteration);
      remainingInfluence -= influence;
      score2 += this.b[index].score * influence;
      if (index === this.c) {
        break;
      }
      index = (this.a + index - 1) % this.a;
      iteration++;
    } while (true);
    return score2 <= 0.5;
  }
  acceptStandardWheelEvent(e) {
    if ($We) {
      const targetWindow = getWindow(e.browserEvent);
      const pageZoomFactor = $Pe(targetWindow);
      this.accept(Date.now(), e.deltaX * pageZoomFactor, e.deltaY * pageZoomFactor);
    } else {
      this.accept(Date.now(), e.deltaX, e.deltaY);
    }
  }
  accept(timestamp, deltaX, deltaY) {
    let previousItem = null;
    const item = new MouseWheelClassifierItem(timestamp, deltaX, deltaY);
    if (this.c === -1 && this.d === -1) {
      this.b[0] = item;
      this.c = 0;
      this.d = 0;
    } else {
      previousItem = this.b[this.d];
      this.d = (this.d + 1) % this.a;
      if (this.d === this.c) {
        this.c = (this.c + 1) % this.a;
      }
      this.b[this.d] = item;
    }
    item.score = this.f(item, previousItem);
  }
  /**
   * A score between 0 and 1 for `item`.
   *  - a score towards 0 indicates that the source appears to be a physical mouse wheel
   *  - a score towards 1 indicates that the source appears to be a touchpad or magic mouse, etc.
   */
  f(item, previousItem) {
    if (Math.abs(item.deltaX) > 0 && Math.abs(item.deltaY) > 0) {
      return 1;
    }
    let score2 = 0.5;
    if (!this.g(item.deltaX) || !this.g(item.deltaY)) {
      score2 += 0.25;
    }
    if (previousItem) {
      const absDeltaX = Math.abs(item.deltaX);
      const absDeltaY = Math.abs(item.deltaY);
      const absPreviousDeltaX = Math.abs(previousItem.deltaX);
      const absPreviousDeltaY = Math.abs(previousItem.deltaY);
      const minDeltaX = Math.max(Math.min(absDeltaX, absPreviousDeltaX), 1);
      const minDeltaY = Math.max(Math.min(absDeltaY, absPreviousDeltaY), 1);
      const maxDeltaX = Math.max(absDeltaX, absPreviousDeltaX);
      const maxDeltaY = Math.max(absDeltaY, absPreviousDeltaY);
      const isSameModulo = maxDeltaX % minDeltaX === 0 && maxDeltaY % minDeltaY === 0;
      if (isSameModulo) {
        score2 -= 0.5;
      }
    }
    return Math.min(Math.max(score2, 0), 1);
  }
  g(value) {
    const delta = Math.abs(Math.round(value) - value);
    return delta < 0.01;
  }
};
var $zZ = class extends $qZ {
  get options() {
    return this.a;
  }
  constructor(element, options3, scrollable) {
    super();
    this.O = this.B(new $ze());
    this.onScroll = this.O.event;
    this.P = this.B(new $ze());
    this.onWillScroll = this.P.event;
    element.style.overflow = "hidden";
    this.a = resolveOptions(options3);
    this.c = scrollable;
    this.B(this.c.onScroll((e) => {
      this.P.fire(e);
      this.S(e);
      this.O.fire(e);
    }));
    const scrollbarHost = {
      onMouseWheel: (mouseWheelEvent) => this.R(mouseWheelEvent),
      onDragStart: () => this.W(),
      onDragEnd: () => this.X()
    };
    this.g = this.B(new $xZ(this.c, this.a, scrollbarHost));
    this.h = this.B(new $wZ(this.c, this.a, scrollbarHost));
    this.n = document.createElement("div");
    this.n.className = "monaco-scrollable-element " + this.a.className;
    this.n.setAttribute("role", "presentation");
    this.n.style.position = "relative";
    this.n.style.overflow = "hidden";
    this.n.appendChild(element);
    this.n.appendChild(this.h.domNode.domNode);
    this.n.appendChild(this.g.domNode.domNode);
    if (this.a.useShadows) {
      this.r = $oZ(document.createElement("div"));
      this.r.setClassName("shadow");
      this.n.appendChild(this.r.domNode);
      this.t = $oZ(document.createElement("div"));
      this.t.setClassName("shadow");
      this.n.appendChild(this.t.domNode);
      this.w = $oZ(document.createElement("div"));
      this.w.setClassName("shadow");
      this.n.appendChild(this.w.domNode);
    } else {
      this.r = null;
      this.t = null;
      this.w = null;
    }
    this.y = this.a.listenOnDomNode || this.n;
    this.H = [];
    this.Q(this.a.handleMouseWheel);
    this.j(this.y, (e) => this.Z(e));
    this.m(this.y, (e) => this.Y(e));
    this.L = this.B(new $6h());
    this.I = false;
    this.J = false;
    this.M = true;
    this.N = true;
  }
  dispose() {
    this.H = $Xc(this.H);
    super.dispose();
  }
  /**
   * Get the generated 'scrollable' dom node
   */
  getDomNode() {
    return this.n;
  }
  getOverviewRulerLayoutInfo() {
    return {
      parent: this.n,
      insertBefore: this.g.domNode.domNode
    };
  }
  /**
   * Delegate a pointer down event to the vertical scrollbar.
   * This is to help with clicking somewhere else and having the scrollbar react.
   */
  delegateVerticalScrollbarPointerDown(browserEvent) {
    this.g.delegatePointerDown(browserEvent);
  }
  getScrollDimensions() {
    return this.c.getScrollDimensions();
  }
  setScrollDimensions(dimensions) {
    this.c.setScrollDimensions(dimensions, false);
  }
  /**
   * Update the class name of the scrollable element.
   */
  updateClassName(newClassName) {
    this.a.className = newClassName;
    if ($m) {
      this.a.className += " mac";
    }
    this.n.className = "monaco-scrollable-element " + this.a.className;
  }
  /**
   * Update configuration options for the scrollbar.
   */
  updateOptions(newOptions) {
    if (typeof newOptions.handleMouseWheel !== "undefined") {
      this.a.handleMouseWheel = newOptions.handleMouseWheel;
      this.Q(this.a.handleMouseWheel);
    }
    if (typeof newOptions.mouseWheelScrollSensitivity !== "undefined") {
      this.a.mouseWheelScrollSensitivity = newOptions.mouseWheelScrollSensitivity;
    }
    if (typeof newOptions.fastScrollSensitivity !== "undefined") {
      this.a.fastScrollSensitivity = newOptions.fastScrollSensitivity;
    }
    if (typeof newOptions.scrollPredominantAxis !== "undefined") {
      this.a.scrollPredominantAxis = newOptions.scrollPredominantAxis;
    }
    if (typeof newOptions.horizontal !== "undefined") {
      this.a.horizontal = newOptions.horizontal;
    }
    if (typeof newOptions.vertical !== "undefined") {
      this.a.vertical = newOptions.vertical;
    }
    if (typeof newOptions.horizontalScrollbarSize !== "undefined") {
      this.a.horizontalScrollbarSize = newOptions.horizontalScrollbarSize;
    }
    if (typeof newOptions.verticalScrollbarSize !== "undefined") {
      this.a.verticalScrollbarSize = newOptions.verticalScrollbarSize;
    }
    if (typeof newOptions.scrollByPage !== "undefined") {
      this.a.scrollByPage = newOptions.scrollByPage;
    }
    this.h.updateOptions(this.a);
    this.g.updateOptions(this.a);
    if (!this.a.lazyRender) {
      this.U();
    }
  }
  setRevealOnScroll(value) {
    this.N = value;
  }
  delegateScrollFromMouseWheelEvent(browserEvent) {
    this.R(new $nf(browserEvent));
  }
  // -------------------- mouse wheel scrolling --------------------
  Q(shouldListen) {
    const isListening = this.H.length > 0;
    if (isListening === shouldListen) {
      return;
    }
    this.H = $Xc(this.H);
    if (shouldListen) {
      const onMouseWheel = (browserEvent) => {
        this.R(new $nf(browserEvent));
      };
      this.H.push($_i(this.y, $7j.MOUSE_WHEEL, onMouseWheel, { passive: false }));
    }
  }
  R(e) {
    if (e.browserEvent?.defaultPrevented) {
      return;
    }
    const classifier = $yZ.INSTANCE;
    if (SCROLL_WHEEL_SMOOTH_SCROLL_ENABLED) {
      classifier.acceptStandardWheelEvent(e);
    }
    let didScroll = false;
    if (e.deltaY || e.deltaX) {
      let deltaY = e.deltaY * this.a.mouseWheelScrollSensitivity;
      let deltaX = e.deltaX * this.a.mouseWheelScrollSensitivity;
      if (this.a.scrollPredominantAxis) {
        if (this.a.scrollYToX && deltaX + deltaY === 0) {
          deltaX = deltaY = 0;
        } else if (Math.abs(deltaY) >= Math.abs(deltaX)) {
          deltaX = 0;
        } else {
          deltaY = 0;
        }
      }
      if (this.a.flipAxes) {
        [deltaY, deltaX] = [deltaX, deltaY];
      }
      const shiftConvert = !$m && e.browserEvent && e.browserEvent.shiftKey;
      if ((this.a.scrollYToX || shiftConvert) && !deltaX) {
        deltaX = deltaY;
        deltaY = 0;
      }
      if (e.browserEvent && e.browserEvent.altKey) {
        deltaX = deltaX * this.a.fastScrollSensitivity;
        deltaY = deltaY * this.a.fastScrollSensitivity;
      }
      const futureScrollPosition = this.c.getFutureScrollPosition();
      let desiredScrollPosition = {};
      if (deltaY) {
        const deltaScrollTop = SCROLL_WHEEL_SENSITIVITY * deltaY;
        const desiredScrollTop = futureScrollPosition.scrollTop - (deltaScrollTop < 0 ? Math.floor(deltaScrollTop) : Math.ceil(deltaScrollTop));
        this.g.writeScrollPosition(desiredScrollPosition, desiredScrollTop);
      }
      if (deltaX) {
        const deltaScrollLeft = SCROLL_WHEEL_SENSITIVITY * deltaX;
        const desiredScrollLeft = futureScrollPosition.scrollLeft - (deltaScrollLeft < 0 ? Math.floor(deltaScrollLeft) : Math.ceil(deltaScrollLeft));
        this.h.writeScrollPosition(desiredScrollPosition, desiredScrollLeft);
      }
      desiredScrollPosition = this.c.validateScrollPosition(desiredScrollPosition);
      if (futureScrollPosition.scrollLeft !== desiredScrollPosition.scrollLeft || futureScrollPosition.scrollTop !== desiredScrollPosition.scrollTop) {
        const canPerformSmoothScroll = SCROLL_WHEEL_SMOOTH_SCROLL_ENABLED && this.a.mouseWheelSmoothScroll && classifier.isPhysicalMouseWheel();
        if (canPerformSmoothScroll) {
          this.c.setScrollPositionSmooth(desiredScrollPosition);
        } else {
          this.c.setScrollPositionNow(desiredScrollPosition);
        }
        didScroll = true;
      }
    }
    let consumeMouseWheel = didScroll;
    if (!consumeMouseWheel && this.a.alwaysConsumeMouseWheel) {
      consumeMouseWheel = true;
    }
    if (!consumeMouseWheel && this.a.consumeMouseWheelIfScrollbarIsNeeded && (this.g.isNeeded() || this.h.isNeeded())) {
      consumeMouseWheel = true;
    }
    if (consumeMouseWheel) {
      e.preventDefault();
      e.stopPropagation();
    }
  }
  S(e) {
    this.M = this.h.onDidScroll(e) || this.M;
    this.M = this.g.onDidScroll(e) || this.M;
    if (this.a.useShadows) {
      this.M = true;
    }
    if (this.N) {
      this.$();
    }
    if (!this.a.lazyRender) {
      this.U();
    }
  }
  /**
   * Render / mutate the DOM now.
   * Should be used together with the ctor option `lazyRender`.
   */
  renderNow() {
    if (!this.a.lazyRender) {
      throw new Error("Please use `lazyRender` together with `renderNow`!");
    }
    this.U();
  }
  U() {
    if (!this.M) {
      return;
    }
    this.M = false;
    this.h.render();
    this.g.render();
    if (this.a.useShadows) {
      const scrollState = this.c.getCurrentScrollPosition();
      const enableTop = scrollState.scrollTop > 0;
      const enableLeft = scrollState.scrollLeft > 0;
      const leftClassName = enableLeft ? " left" : "";
      const topClassName = enableTop ? " top" : "";
      const topLeftClassName = enableLeft || enableTop ? " top-left-corner" : "";
      this.r.setClassName(`shadow${leftClassName}`);
      this.t.setClassName(`shadow${topClassName}`);
      this.w.setClassName(`shadow${topLeftClassName}${topClassName}${leftClassName}`);
    }
  }
  // -------------------- fade in / fade out --------------------
  W() {
    this.I = true;
    this.$();
  }
  X() {
    this.I = false;
    this.ab();
  }
  Y(e) {
    this.J = false;
    this.ab();
  }
  Z(e) {
    this.J = true;
    this.$();
  }
  $() {
    this.g.beginReveal();
    this.h.beginReveal();
    this.bb();
  }
  ab() {
    if (!this.J && !this.I) {
      this.g.beginHide();
      this.h.beginHide();
    }
  }
  bb() {
    if (!this.J && !this.I) {
      this.L.cancelAndSet(() => this.ab(), HIDE_TIMEOUT);
    }
  }
};
var $AZ = class extends $zZ {
  constructor(element, options3) {
    options3 = options3 || {};
    options3.mouseWheelSmoothScroll = false;
    const scrollable = new $AD({
      forceIntegerValues: true,
      smoothScrollDuration: 0,
      scheduleAtNextAnimationFrame: (callback) => $jj(getWindow(element), callback)
    });
    super(element, options3, scrollable);
    this.B(scrollable);
  }
  setScrollPosition(update) {
    this.c.setScrollPositionNow(update);
  }
  getScrollPosition() {
    return this.c.getCurrentScrollPosition();
  }
};
var $BZ = class extends $zZ {
  constructor(element, options3, scrollable) {
    super(element, options3, scrollable);
  }
  setScrollPosition(update) {
    if (update.reuseAnimation) {
      this.c.setScrollPositionSmooth(update, update.reuseAnimation);
    } else {
      this.c.setScrollPositionNow(update);
    }
  }
  getScrollPosition() {
    return this.c.getCurrentScrollPosition();
  }
};
var $CZ = class extends $zZ {
  constructor(element, options3) {
    options3 = options3 || {};
    options3.mouseWheelSmoothScroll = false;
    const scrollable = new $AD({
      forceIntegerValues: false,
      // See https://github.com/microsoft/vscode/issues/139877
      smoothScrollDuration: 0,
      scheduleAtNextAnimationFrame: (callback) => $jj(getWindow(element), callback)
    });
    super(element, options3, scrollable);
    this.B(scrollable);
    this.cb = element;
    this.B(this.onScroll((e) => {
      if (e.scrollTopChanged) {
        this.cb.scrollTop = e.scrollTop;
      }
      if (e.scrollLeftChanged) {
        this.cb.scrollLeft = e.scrollLeft;
      }
    }));
    this.scanDomNode();
  }
  setScrollPosition(update) {
    this.c.setScrollPositionNow(update);
  }
  getScrollPosition() {
    return this.c.getCurrentScrollPosition();
  }
  scanDomNode() {
    this.setScrollDimensions({
      width: this.cb.clientWidth,
      scrollWidth: this.cb.scrollWidth,
      height: this.cb.clientHeight,
      scrollHeight: this.cb.scrollHeight
    });
    this.setScrollPosition({
      scrollLeft: this.cb.scrollLeft,
      scrollTop: this.cb.scrollTop
    });
  }
};
function resolveOptions(opts) {
  const result = {
    lazyRender: typeof opts.lazyRender !== "undefined" ? opts.lazyRender : false,
    className: typeof opts.className !== "undefined" ? opts.className : "",
    useShadows: typeof opts.useShadows !== "undefined" ? opts.useShadows : true,
    handleMouseWheel: typeof opts.handleMouseWheel !== "undefined" ? opts.handleMouseWheel : true,
    flipAxes: typeof opts.flipAxes !== "undefined" ? opts.flipAxes : false,
    consumeMouseWheelIfScrollbarIsNeeded: typeof opts.consumeMouseWheelIfScrollbarIsNeeded !== "undefined" ? opts.consumeMouseWheelIfScrollbarIsNeeded : false,
    alwaysConsumeMouseWheel: typeof opts.alwaysConsumeMouseWheel !== "undefined" ? opts.alwaysConsumeMouseWheel : false,
    scrollYToX: typeof opts.scrollYToX !== "undefined" ? opts.scrollYToX : false,
    mouseWheelScrollSensitivity: typeof opts.mouseWheelScrollSensitivity !== "undefined" ? opts.mouseWheelScrollSensitivity : 1,
    fastScrollSensitivity: typeof opts.fastScrollSensitivity !== "undefined" ? opts.fastScrollSensitivity : 5,
    scrollPredominantAxis: typeof opts.scrollPredominantAxis !== "undefined" ? opts.scrollPredominantAxis : true,
    mouseWheelSmoothScroll: typeof opts.mouseWheelSmoothScroll !== "undefined" ? opts.mouseWheelSmoothScroll : true,
    arrowSize: typeof opts.arrowSize !== "undefined" ? opts.arrowSize : 11,
    listenOnDomNode: typeof opts.listenOnDomNode !== "undefined" ? opts.listenOnDomNode : null,
    horizontal: typeof opts.horizontal !== "undefined" ? opts.horizontal : 1,
    horizontalScrollbarSize: typeof opts.horizontalScrollbarSize !== "undefined" ? opts.horizontalScrollbarSize : 10,
    horizontalSliderSize: typeof opts.horizontalSliderSize !== "undefined" ? opts.horizontalSliderSize : 0,
    horizontalHasArrows: typeof opts.horizontalHasArrows !== "undefined" ? opts.horizontalHasArrows : false,
    vertical: typeof opts.vertical !== "undefined" ? opts.vertical : 1,
    verticalScrollbarSize: typeof opts.verticalScrollbarSize !== "undefined" ? opts.verticalScrollbarSize : 10,
    verticalHasArrows: typeof opts.verticalHasArrows !== "undefined" ? opts.verticalHasArrows : false,
    verticalSliderSize: typeof opts.verticalSliderSize !== "undefined" ? opts.verticalSliderSize : 0,
    scrollByPage: typeof opts.scrollByPage !== "undefined" ? opts.scrollByPage : false
  };
  result.horizontalSliderSize = typeof opts.horizontalSliderSize !== "undefined" ? opts.horizontalSliderSize : result.horizontalScrollbarSize;
  result.verticalSliderSize = typeof opts.verticalSliderSize !== "undefined" ? opts.verticalSliderSize : result.verticalScrollbarSize;
  if ($m) {
    result.className += " mac";
  }
  return result;
}

// out-build/vs/editor/browser/controller/mouseHandler.js
var $27 = class extends $D5 {
  constructor(context, viewController, viewHelper) {
    super();
    this.n = null;
    this.a = context;
    this.b = viewController;
    this.c = viewHelper;
    this.f = new $Y7(this.a, viewHelper);
    this.g = this.B(new MouseDownOperation(this.a, this.b, this.c, this.f, (e, testEventTarget) => this.s(e, testEventTarget), (e) => this.w(e)));
    this.h = -1;
    this.j = this.a.configuration.options.get(
      151
      /* EditorOption.layoutInfo */
    ).height;
    const mouseEvents = new $56(this.c.viewDomNode);
    this.B(mouseEvents.onContextMenu(this.c.viewDomNode, (e) => this.z(e, true)));
    this.B(mouseEvents.onMouseMove(this.c.viewDomNode, (e) => {
      this.C(e);
      if (!this.n) {
        this.n = $_i(this.c.viewDomNode.ownerDocument, "mousemove", (e2) => {
          if (!this.c.viewDomNode.contains(e2.target)) {
            this.D(new $46(e2, false, this.c.viewDomNode));
          }
        });
      }
    }));
    this.B(mouseEvents.onMouseUp(this.c.viewDomNode, (e) => this.F(e)));
    this.B(mouseEvents.onMouseLeave(this.c.viewDomNode, (e) => this.D(e)));
    let capturePointerId = 0;
    this.B(mouseEvents.onPointerDown(this.c.viewDomNode, (e, pointerId) => {
      capturePointerId = pointerId;
    }));
    this.B($_i(this.c.viewDomNode, $7j.POINTER_UP, (e) => {
      this.g.onPointerUp();
    }));
    this.B(mouseEvents.onMouseDown(this.c.viewDomNode, (e) => this.G(e, capturePointerId)));
    this.r();
    this.a.addEventHandler(this);
  }
  r() {
    const classifier = $yZ.INSTANCE;
    let prevMouseWheelTime = 0;
    let gestureStartZoomLevel = EditorZoom.getZoomLevel();
    let gestureHasZoomModifiers = false;
    let gestureAccumulatedDelta = 0;
    const onMouseWheel = (browserEvent) => {
      this.b.emitMouseWheel(browserEvent);
      if (!this.a.configuration.options.get(
        77
        /* EditorOption.mouseWheelZoom */
      )) {
        return;
      }
      const e = new $nf(browserEvent);
      classifier.acceptStandardWheelEvent(e);
      if (classifier.isPhysicalMouseWheel()) {
        if (hasMouseWheelZoomModifiers(browserEvent)) {
          const zoomLevel = EditorZoom.getZoomLevel();
          const delta = e.deltaY > 0 ? 1 : -1;
          EditorZoom.setZoomLevel(zoomLevel + delta);
          e.preventDefault();
          e.stopPropagation();
        }
      } else {
        if (Date.now() - prevMouseWheelTime > 50) {
          gestureStartZoomLevel = EditorZoom.getZoomLevel();
          gestureHasZoomModifiers = hasMouseWheelZoomModifiers(browserEvent);
          gestureAccumulatedDelta = 0;
        }
        prevMouseWheelTime = Date.now();
        gestureAccumulatedDelta += e.deltaY;
        if (gestureHasZoomModifiers) {
          EditorZoom.setZoomLevel(gestureStartZoomLevel + gestureAccumulatedDelta / 5);
          e.preventDefault();
          e.stopPropagation();
        }
      }
    };
    this.B($_i(this.c.viewDomNode, $7j.MOUSE_WHEEL, onMouseWheel, { capture: true, passive: false }));
    function hasMouseWheelZoomModifiers(browserEvent) {
      return $m ? (browserEvent.metaKey || browserEvent.ctrlKey) && !browserEvent.shiftKey && !browserEvent.altKey : browserEvent.ctrlKey && !browserEvent.metaKey && !browserEvent.shiftKey && !browserEvent.altKey;
    }
  }
  dispose() {
    this.a.removeEventHandler(this);
    if (this.n) {
      this.n.dispose();
      this.n = null;
    }
    super.dispose();
  }
  // --- begin event handlers
  onConfigurationChanged(e) {
    if (e.hasChanged(
      151
      /* EditorOption.layoutInfo */
    )) {
      const height = this.a.configuration.options.get(
        151
        /* EditorOption.layoutInfo */
      ).height;
      if (this.j !== height) {
        this.j = height;
        this.g.onHeightChanged();
      }
    }
    return false;
  }
  onCursorStateChanged(e) {
    this.g.onCursorStateChanged(e);
    return false;
  }
  onFocusChanged(e) {
    return false;
  }
  // --- end event handlers
  getTargetAtClientPoint(clientX, clientY) {
    const clientPos = new $Y6(clientX, clientY);
    const pos = clientPos.toPageCoordinates(getWindow(this.c.viewDomNode));
    const editorPos = $26(this.c.viewDomNode);
    if (pos.y < editorPos.y || pos.y > editorPos.y + editorPos.height || pos.x < editorPos.x || pos.x > editorPos.x + editorPos.width) {
      return null;
    }
    const relativePos = $36(this.c.viewDomNode, editorPos, pos);
    return this.f.createMouseTarget(this.c.getLastRenderData(), editorPos, pos, relativePos, null);
  }
  s(e, testEventTarget) {
    let target = e.target;
    if (!this.c.viewDomNode.contains(target)) {
      const shadowRoot = $Kj(this.c.viewDomNode);
      if (shadowRoot) {
        target = shadowRoot.elementsFromPoint(e.posx, e.posy).find((el) => this.c.viewDomNode.contains(el));
      }
    }
    return this.f.createMouseTarget(this.c.getLastRenderData(), e.editorPos, e.pos, e.relativePos, testEventTarget ? target : null);
  }
  w(e) {
    return this.f.getMouseColumn(e.relativePos);
  }
  z(e, testEventTarget) {
    this.b.emitContextMenu({
      event: e,
      target: this.s(e, testEventTarget)
    });
  }
  C(e) {
    const targetIsWidget = this.f.mouseTargetIsWidget(e);
    if (!targetIsWidget) {
      e.preventDefault();
    }
    if (this.g.isActive()) {
      return;
    }
    const actualMouseMoveTime = e.timestamp;
    if (actualMouseMoveTime < this.h) {
      return;
    }
    this.b.emitMouseMove({
      event: e,
      target: this.s(e, true)
    });
  }
  D(e) {
    if (this.n) {
      this.n.dispose();
      this.n = null;
    }
    this.h = (/* @__PURE__ */ new Date()).getTime();
    this.b.emitMouseLeave({
      event: e,
      target: null
    });
  }
  F(e) {
    this.b.emitMouseUp({
      event: e,
      target: this.s(e, true)
    });
  }
  G(e, pointerId) {
    const t = this.s(e, true);
    const targetIsContent = t.type === 6 || t.type === 7;
    const targetIsGutter = t.type === 2 || t.type === 3 || t.type === 4;
    const targetIsLineNumbers = t.type === 3;
    const selectOnLineNumbers = this.a.configuration.options.get(
      114
      /* EditorOption.selectOnLineNumbers */
    );
    const targetIsViewZone = t.type === 8 || t.type === 5;
    const targetIsWidget = t.type === 9;
    let shouldHandle = e.leftButton || e.middleButton;
    if ($m && e.leftButton && e.ctrlKey) {
      shouldHandle = false;
    }
    const focus = () => {
      e.preventDefault();
      this.c.focusTextArea();
    };
    if (shouldHandle && (targetIsContent || targetIsLineNumbers && selectOnLineNumbers)) {
      focus();
      this.g.start(t.type, e, pointerId);
    } else if (targetIsGutter) {
      e.preventDefault();
    } else if (targetIsViewZone) {
      const viewZoneData = t.detail;
      if (shouldHandle && this.c.shouldSuppressMouseDownOnViewZone(viewZoneData.viewZoneId)) {
        focus();
        this.g.start(t.type, e, pointerId);
        e.preventDefault();
      }
    } else if (targetIsWidget && this.c.shouldSuppressMouseDownOnWidget(t.detail)) {
      focus();
      e.preventDefault();
    }
    this.b.emitMouseDown({
      event: e,
      target: t
    });
  }
  H(e) {
    this.b.emitMouseWheel(e);
  }
};
var MouseDownOperation = class extends $3c {
  constructor(n, r2, s, u, createMouseTarget, getMouseColumn) {
    super();
    this.n = n;
    this.r = r2;
    this.s = s;
    this.u = u;
    this.a = createMouseTarget;
    this.b = getMouseColumn;
    this.c = this.B(new $76(this.s.viewDomNode));
    this.f = this.B(new TopBottomDragScrolling(this.n, this.s, this.u, (position, inSelectionMode, revealType) => this.G(position, inSelectionMode, revealType)));
    this.g = new MouseDownState();
    this.h = new $_D(1, 1, 1, 1);
    this.j = false;
    this.m = null;
  }
  dispose() {
    super.dispose();
  }
  isActive() {
    return this.j;
  }
  w(e) {
    this.m = e;
    this.g.setModifiers(e);
    const position = this.D(e, false);
    if (!position) {
      return;
    }
    if (this.g.isDragAndDrop) {
      this.r.emitMouseDrag({
        event: e,
        target: position
      });
    } else {
      if (position.type === 13 && (position.outsidePosition === "above" || position.outsidePosition === "below")) {
        this.f.start(position, e);
      } else {
        this.f.stop();
        this.G(
          position,
          true,
          1
          /* NavigationCommandRevealType.Minimal */
        );
      }
    }
  }
  start(targetType, e, pointerId) {
    this.m = e;
    this.g.setStartedOnLineNumbers(
      targetType === 3
      /* MouseTargetType.GUTTER_LINE_NUMBERS */
    );
    this.g.setStartButtons(e);
    this.g.setModifiers(e);
    const position = this.D(e, true);
    if (!position || !position.position) {
      return;
    }
    this.g.trySetCount(e.detail, position.position);
    e.detail = this.g.count;
    const options3 = this.n.configuration.options;
    if (!options3.get(
      96
      /* EditorOption.readOnly */
    ) && options3.get(
      35
      /* EditorOption.dragAndDrop */
    ) && !options3.get(
      22
      /* EditorOption.columnSelection */
    ) && !this.g.altKey && e.detail < 2 && !this.j && !this.h.isEmpty() && position.type === 6 && position.position && this.h.containsPosition(position.position)) {
      this.g.isDragAndDrop = true;
      this.j = true;
      this.c.startMonitoring(this.s.viewLinesDomNode, pointerId, e.buttons, (e2) => this.w(e2), (browserEvent) => {
        const position2 = this.D(this.m, false);
        if ($4j(browserEvent)) {
          this.r.emitMouseDropCanceled();
        } else {
          this.r.emitMouseDrop({
            event: this.m,
            target: position2 ? this.a(this.m, true) : null
            // Ignoring because position is unknown, e.g., Content View Zone
          });
        }
        this.z();
      });
      return;
    }
    this.g.isDragAndDrop = false;
    this.G(
      position,
      e.shiftKey,
      1
      /* NavigationCommandRevealType.Minimal */
    );
    if (!this.j) {
      this.j = true;
      this.c.startMonitoring(this.s.viewLinesDomNode, pointerId, e.buttons, (e2) => this.w(e2), () => this.z());
    }
  }
  z() {
    this.j = false;
    this.f.stop();
  }
  onHeightChanged() {
    this.c.stopMonitoring();
  }
  onPointerUp() {
    this.c.stopMonitoring();
  }
  onCursorStateChanged(e) {
    this.h = e.selections[0];
  }
  C(e) {
    const editorContent = e.editorPos;
    const model = this.n.viewModel;
    const viewLayout = this.n.viewLayout;
    const mouseColumn = this.b(e);
    if (e.posy < editorContent.y) {
      const outsideDistance = editorContent.y - e.posy;
      const verticalOffset = Math.max(viewLayout.getCurrentScrollTop() - outsideDistance, 0);
      const viewZoneData = $X7.getZoneAtCoord(this.n, verticalOffset);
      if (viewZoneData) {
        const newPosition = this.F(viewZoneData);
        if (newPosition) {
          return $W7.createOutsideEditor(mouseColumn, newPosition, "above", outsideDistance);
        }
      }
      const aboveLineNumber = viewLayout.getLineNumberAtVerticalOffset(verticalOffset);
      return $W7.createOutsideEditor(mouseColumn, new $8C(aboveLineNumber, 1), "above", outsideDistance);
    }
    if (e.posy > editorContent.y + editorContent.height) {
      const outsideDistance = e.posy - editorContent.y - editorContent.height;
      const verticalOffset = viewLayout.getCurrentScrollTop() + e.relativePos.y;
      const viewZoneData = $X7.getZoneAtCoord(this.n, verticalOffset);
      if (viewZoneData) {
        const newPosition = this.F(viewZoneData);
        if (newPosition) {
          return $W7.createOutsideEditor(mouseColumn, newPosition, "below", outsideDistance);
        }
      }
      const belowLineNumber = viewLayout.getLineNumberAtVerticalOffset(verticalOffset);
      return $W7.createOutsideEditor(mouseColumn, new $8C(belowLineNumber, model.getLineMaxColumn(belowLineNumber)), "below", outsideDistance);
    }
    const possibleLineNumber = viewLayout.getLineNumberAtVerticalOffset(viewLayout.getCurrentScrollTop() + e.relativePos.y);
    if (e.posx < editorContent.x) {
      const outsideDistance = editorContent.x - e.posx;
      return $W7.createOutsideEditor(mouseColumn, new $8C(possibleLineNumber, 1), "left", outsideDistance);
    }
    if (e.posx > editorContent.x + editorContent.width) {
      const outsideDistance = e.posx - editorContent.x - editorContent.width;
      return $W7.createOutsideEditor(mouseColumn, new $8C(possibleLineNumber, model.getLineMaxColumn(possibleLineNumber)), "right", outsideDistance);
    }
    return null;
  }
  D(e, testEventTarget) {
    const positionOutsideEditor = this.C(e);
    if (positionOutsideEditor) {
      return positionOutsideEditor;
    }
    const t = this.a(e, testEventTarget);
    const hintedPosition = t.position;
    if (!hintedPosition) {
      return null;
    }
    if (t.type === 8 || t.type === 5) {
      const newPosition = this.F(t.detail);
      if (newPosition) {
        return $W7.createViewZone(t.type, t.element, t.mouseColumn, newPosition, t.detail);
      }
    }
    return t;
  }
  F(viewZoneData) {
    const selectionStart = new $8C(this.h.selectionStartLineNumber, this.h.selectionStartColumn);
    const positionBefore = viewZoneData.positionBefore;
    const positionAfter = viewZoneData.positionAfter;
    if (positionBefore && positionAfter) {
      if (positionBefore.isBefore(selectionStart)) {
        return positionBefore;
      } else {
        return positionAfter;
      }
    }
    return null;
  }
  G(position, inSelectionMode, revealType) {
    if (!position.position) {
      return;
    }
    this.r.dispatchMouse({
      position: position.position,
      mouseColumn: position.mouseColumn,
      startedOnLineNumbers: this.g.startedOnLineNumbers,
      revealType,
      inSelectionMode,
      mouseDownCount: this.g.count,
      altKey: this.g.altKey,
      ctrlKey: this.g.ctrlKey,
      metaKey: this.g.metaKey,
      shiftKey: this.g.shiftKey,
      leftButton: this.g.leftButton,
      middleButton: this.g.middleButton,
      onInjectedText: position.type === 6 && position.detail.injectedText !== null
    });
  }
};
var TopBottomDragScrolling = class extends $3c {
  constructor(b, c, f, g) {
    super();
    this.b = b;
    this.c = c;
    this.f = f;
    this.g = g;
    this.a = null;
  }
  dispose() {
    super.dispose();
    this.stop();
  }
  start(position, mouseEvent) {
    if (this.a) {
      this.a.setPosition(position, mouseEvent);
    } else {
      this.a = new TopBottomDragScrollingOperation(this.b, this.c, this.f, this.g, position, mouseEvent);
    }
  }
  stop() {
    if (this.a) {
      this.a.dispose();
      this.a = null;
    }
  }
};
var TopBottomDragScrollingOperation = class extends $3c {
  constructor(g, h3, j, m, position, mouseEvent) {
    super();
    this.g = g;
    this.h = h3;
    this.j = j;
    this.m = m;
    this.a = position;
    this.b = mouseEvent;
    this.c = Date.now();
    this.f = $jj(getWindow(mouseEvent.browserEvent), () => this.s());
  }
  dispose() {
    this.f.dispose();
    super.dispose();
  }
  setPosition(position, mouseEvent) {
    this.a = position;
    this.b = mouseEvent;
  }
  /**
   * update internal state and return elapsed ms since last time
   */
  n() {
    const now = Date.now();
    const elapsed = now - this.c;
    this.c = now;
    return elapsed;
  }
  /**
   * get the number of lines per second to auto-scroll
   */
  r() {
    const lineHeight = this.g.configuration.options.get(
      68
      /* EditorOption.lineHeight */
    );
    const viewportInLines = this.g.configuration.options.get(
      151
      /* EditorOption.layoutInfo */
    ).height / lineHeight;
    const outsideDistanceInLines = this.a.outsideDistance / lineHeight;
    if (outsideDistanceInLines <= 1.5) {
      return Math.max(30, viewportInLines * (1 + outsideDistanceInLines));
    }
    if (outsideDistanceInLines <= 3) {
      return Math.max(60, viewportInLines * (2 + outsideDistanceInLines));
    }
    return Math.max(200, viewportInLines * (7 + outsideDistanceInLines));
  }
  s() {
    const lineHeight = this.g.configuration.options.get(
      68
      /* EditorOption.lineHeight */
    );
    const scrollSpeedInLines = this.r();
    const elapsed = this.n();
    const scrollInPixels = scrollSpeedInLines * (elapsed / 1e3) * lineHeight;
    const scrollValue = this.a.outsidePosition === "above" ? -scrollInPixels : scrollInPixels;
    this.g.viewModel.viewLayout.deltaScrollNow(0, scrollValue);
    this.h.renderNow();
    const viewportData = this.g.viewLayout.getLinesViewportData();
    const edgeLineNumber = this.a.outsidePosition === "above" ? viewportData.startLineNumber : viewportData.endLineNumber;
    let mouseTarget;
    {
      const editorPos = $26(this.h.viewDomNode);
      const horizontalScrollbarHeight = this.g.configuration.options.get(
        151
        /* EditorOption.layoutInfo */
      ).horizontalScrollbarHeight;
      const pos = new $X6(this.b.pos.x, editorPos.y + editorPos.height - horizontalScrollbarHeight - 0.1);
      const relativePos = $36(this.h.viewDomNode, editorPos, pos);
      mouseTarget = this.j.createMouseTarget(this.h.getLastRenderData(), editorPos, pos, relativePos, null);
    }
    if (!mouseTarget.position || mouseTarget.position.lineNumber !== edgeLineNumber) {
      if (this.a.outsidePosition === "above") {
        mouseTarget = $W7.createOutsideEditor(this.a.mouseColumn, new $8C(edgeLineNumber, 1), "above", this.a.outsideDistance);
      } else {
        mouseTarget = $W7.createOutsideEditor(this.a.mouseColumn, new $8C(edgeLineNumber, this.g.viewModel.getLineMaxColumn(edgeLineNumber)), "below", this.a.outsideDistance);
      }
    }
    this.m(
      mouseTarget,
      true,
      2
      /* NavigationCommandRevealType.None */
    );
    this.f = $jj(getWindow(mouseTarget.element), () => this.s());
  }
};
var MouseDownState = class _MouseDownState {
  static {
    this.a = 400;
  }
  // ms
  get altKey() {
    return this.b;
  }
  get ctrlKey() {
    return this.c;
  }
  get metaKey() {
    return this.d;
  }
  get shiftKey() {
    return this.f;
  }
  get leftButton() {
    return this.g;
  }
  get middleButton() {
    return this.h;
  }
  get startedOnLineNumbers() {
    return this.i;
  }
  constructor() {
    this.b = false;
    this.c = false;
    this.d = false;
    this.f = false;
    this.g = false;
    this.h = false;
    this.i = false;
    this.j = null;
    this.k = 0;
    this.l = 0;
    this.m = 0;
    this.isDragAndDrop = false;
  }
  get count() {
    return this.l;
  }
  setModifiers(source) {
    this.b = source.altKey;
    this.c = source.ctrlKey;
    this.d = source.metaKey;
    this.f = source.shiftKey;
  }
  setStartButtons(source) {
    this.g = source.leftButton;
    this.h = source.middleButton;
  }
  setStartedOnLineNumbers(startedOnLineNumbers) {
    this.i = startedOnLineNumbers;
  }
  trySetCount(setMouseDownCount, newMouseDownPosition) {
    const currentTime = (/* @__PURE__ */ new Date()).getTime();
    if (currentTime - this.m > _MouseDownState.a) {
      setMouseDownCount = 1;
    }
    this.m = currentTime;
    if (setMouseDownCount > this.l + 1) {
      setMouseDownCount = this.l + 1;
    }
    if (this.j && this.j.equals(newMouseDownPosition)) {
      this.k++;
    } else {
      this.k = 1;
    }
    this.j = newMouseDownPosition;
    this.l = Math.min(setMouseDownCount, this.k);
  }
};

// out-build/vs/base/browser/event.js
var $9Z = class {
  get event() {
    return this.a.event;
  }
  constructor(element, type, useCapture) {
    const fn = (e) => this.a.fire(e);
    this.a = new $ze({
      onWillAddFirstListener: () => element.addEventListener(type, fn, useCapture),
      onDidRemoveLastListener: () => element.removeEventListener(type, fn, useCapture)
    });
  }
  dispose() {
    this.a.dispose();
  }
};

// out-build/vs/editor/browser/controller/editContext/clipboardUtils.js
function $37(viewModel, modelSelections, emptySelectionClipboard, copyWithSyntaxHighlighting) {
  const rawTextToCopy = viewModel.getPlainTextToCopy(modelSelections, emptySelectionClipboard, $l);
  const newLineCharacter = viewModel.model.getEOL();
  const isFromEmptySelection = emptySelectionClipboard && modelSelections.length === 1 && modelSelections[0].isEmpty();
  const multicursorText = Array.isArray(rawTextToCopy) ? rawTextToCopy : null;
  const text2 = Array.isArray(rawTextToCopy) ? rawTextToCopy.join(newLineCharacter) : rawTextToCopy;
  let html3 = void 0;
  let mode = null;
  if ($57.forceCopyWithSyntaxHighlighting || copyWithSyntaxHighlighting && text2.length < 65536) {
    const richText = viewModel.getRichTextToCopy(modelSelections, emptySelectionClipboard);
    if (richText) {
      html3 = richText.html;
      mode = richText.mode;
    }
  }
  const dataToCopy = {
    isFromEmptySelection,
    multicursorText,
    text: text2,
    html: html3,
    mode
  };
  return dataToCopy;
}
var $47 = class _$47 {
  static {
    this.INSTANCE = new _$47();
  }
  constructor() {
    this.a = null;
  }
  set(lastCopiedValue, data) {
    this.a = { lastCopiedValue, data };
  }
  get(pastedText) {
    if (this.a && this.a.lastCopiedValue === pastedText) {
      return this.a.data;
    }
    this.a = null;
    return null;
  }
};
var $57 = {
  forceCopyWithSyntaxHighlighting: false
};
var $67 = {
  getTextData(clipboardData) {
    const text2 = clipboardData.getData($YC.text);
    let metadata = null;
    const rawmetadata = clipboardData.getData("vscode-editor-data");
    if (typeof rawmetadata === "string") {
      try {
        metadata = JSON.parse(rawmetadata);
        if (metadata.version !== 1) {
          metadata = null;
        }
      } catch (err) {
      }
    }
    if (text2.length === 0 && metadata === null && clipboardData.files.length > 0) {
      const files = Array.prototype.slice.call(clipboardData.files, 0);
      return [files.map((file) => file.name).join("\n"), null];
    }
    return [text2, metadata];
  },
  setTextData(clipboardData, text2, html3, metadata) {
    clipboardData.setData($YC.text, text2);
    if (typeof html3 === "string") {
      clipboardData.setData("text/html", html3);
    }
    clipboardData.setData("vscode-editor-data", JSON.stringify(metadata));
  }
};

// out-build/vs/editor/browser/controller/editContext/textArea/textAreaEditContextState.js
var $07 = false;
var $$7 = class _$$7 {
  static {
    this.EMPTY = new _$$7("", 0, 0, null, void 0);
  }
  constructor(value, selectionStart, selectionEnd, selection, newlineCountBeforeSelection) {
    this.value = value;
    this.selectionStart = selectionStart;
    this.selectionEnd = selectionEnd;
    this.selection = selection;
    this.newlineCountBeforeSelection = newlineCountBeforeSelection;
  }
  toString() {
    return `[ <${this.value}>, selectionStart: ${this.selectionStart}, selectionEnd: ${this.selectionEnd}]`;
  }
  static readFromTextArea(textArea, previousState) {
    const value = textArea.getValue();
    const selectionStart = textArea.getSelectionStart();
    const selectionEnd = textArea.getSelectionEnd();
    let newlineCountBeforeSelection = void 0;
    if (previousState) {
      const valueBeforeSelectionStart = value.substring(0, selectionStart);
      const previousValueBeforeSelectionStart = previousState.value.substring(0, previousState.selectionStart);
      if (valueBeforeSelectionStart === previousValueBeforeSelectionStart) {
        newlineCountBeforeSelection = previousState.newlineCountBeforeSelection;
      }
    }
    return new _$$7(value, selectionStart, selectionEnd, null, newlineCountBeforeSelection);
  }
  collapseSelection() {
    if (this.selectionStart === this.value.length) {
      return this;
    }
    return new _$$7(this.value, this.value.length, this.value.length, null, void 0);
  }
  isWrittenToTextArea(textArea, select) {
    const valuesEqual = this.value === textArea.getValue();
    if (!select) {
      return valuesEqual;
    }
    const selectionsEqual = this.selectionStart === textArea.getSelectionStart() && this.selectionEnd === textArea.getSelectionEnd();
    return selectionsEqual && valuesEqual;
  }
  writeToTextArea(reason, textArea, select) {
    if ($07) {
      console.log(`writeToTextArea ${reason}: ${this.toString()}`);
    }
    textArea.setValue(reason, this.value);
    if (select) {
      textArea.setSelectionRange(reason, this.selectionStart, this.selectionEnd);
    }
  }
  deduceEditorPosition(offset) {
    if (offset <= this.selectionStart) {
      const str = this.value.substring(offset, this.selectionStart);
      return this.a(this.selection?.getStartPosition() ?? null, str, -1);
    }
    if (offset >= this.selectionEnd) {
      const str = this.value.substring(this.selectionEnd, offset);
      return this.a(this.selection?.getEndPosition() ?? null, str, 1);
    }
    const str1 = this.value.substring(this.selectionStart, offset);
    if (str1.indexOf(String.fromCharCode(8230)) === -1) {
      return this.a(this.selection?.getStartPosition() ?? null, str1, 1);
    }
    const str2 = this.value.substring(offset, this.selectionEnd);
    return this.a(this.selection?.getEndPosition() ?? null, str2, -1);
  }
  a(anchor, deltaText, signum) {
    let lineFeedCnt = 0;
    let lastLineFeedIndex = -1;
    while ((lastLineFeedIndex = deltaText.indexOf("\n", lastLineFeedIndex + 1)) !== -1) {
      lineFeedCnt++;
    }
    return [anchor, signum * deltaText.length, lineFeedCnt];
  }
  static deduceInput(previousState, currentState, couldBeEmojiInput) {
    if (!previousState) {
      return {
        text: "",
        replacePrevCharCnt: 0,
        replaceNextCharCnt: 0,
        positionDelta: 0
      };
    }
    if ($07) {
      console.log("------------------------deduceInput");
      console.log(`PREVIOUS STATE: ${previousState.toString()}`);
      console.log(`CURRENT STATE: ${currentState.toString()}`);
    }
    const prefixLength = Math.min($3f(previousState.value, currentState.value), previousState.selectionStart, currentState.selectionStart);
    const suffixLength = Math.min($4f(previousState.value, currentState.value), previousState.value.length - previousState.selectionEnd, currentState.value.length - currentState.selectionEnd);
    const previousValue = previousState.value.substring(prefixLength, previousState.value.length - suffixLength);
    const currentValue = currentState.value.substring(prefixLength, currentState.value.length - suffixLength);
    const previousSelectionStart = previousState.selectionStart - prefixLength;
    const previousSelectionEnd = previousState.selectionEnd - prefixLength;
    const currentSelectionStart = currentState.selectionStart - prefixLength;
    const currentSelectionEnd = currentState.selectionEnd - prefixLength;
    if ($07) {
      console.log(`AFTER DIFFING PREVIOUS STATE: <${previousValue}>, selectionStart: ${previousSelectionStart}, selectionEnd: ${previousSelectionEnd}`);
      console.log(`AFTER DIFFING CURRENT STATE: <${currentValue}>, selectionStart: ${currentSelectionStart}, selectionEnd: ${currentSelectionEnd}`);
    }
    if (currentSelectionStart === currentSelectionEnd) {
      const replacePreviousCharacters2 = previousState.selectionStart - prefixLength;
      if ($07) {
        console.log(`REMOVE PREVIOUS: ${replacePreviousCharacters2} chars`);
      }
      return {
        text: currentValue,
        replacePrevCharCnt: replacePreviousCharacters2,
        replaceNextCharCnt: 0,
        positionDelta: 0
      };
    }
    const replacePreviousCharacters = previousSelectionEnd - previousSelectionStart;
    return {
      text: currentValue,
      replacePrevCharCnt: replacePreviousCharacters,
      replaceNextCharCnt: 0,
      positionDelta: 0
    };
  }
  static deduceAndroidCompositionInput(previousState, currentState) {
    if (!previousState) {
      return {
        text: "",
        replacePrevCharCnt: 0,
        replaceNextCharCnt: 0,
        positionDelta: 0
      };
    }
    if ($07) {
      console.log("------------------------deduceAndroidCompositionInput");
      console.log(`PREVIOUS STATE: ${previousState.toString()}`);
      console.log(`CURRENT STATE: ${currentState.toString()}`);
    }
    if (previousState.value === currentState.value) {
      return {
        text: "",
        replacePrevCharCnt: 0,
        replaceNextCharCnt: 0,
        positionDelta: currentState.selectionEnd - previousState.selectionEnd
      };
    }
    const prefixLength = Math.min($3f(previousState.value, currentState.value), previousState.selectionEnd);
    const suffixLength = Math.min($4f(previousState.value, currentState.value), previousState.value.length - previousState.selectionEnd);
    const previousValue = previousState.value.substring(prefixLength, previousState.value.length - suffixLength);
    const currentValue = currentState.value.substring(prefixLength, currentState.value.length - suffixLength);
    const previousSelectionStart = previousState.selectionStart - prefixLength;
    const previousSelectionEnd = previousState.selectionEnd - prefixLength;
    const currentSelectionStart = currentState.selectionStart - prefixLength;
    const currentSelectionEnd = currentState.selectionEnd - prefixLength;
    if ($07) {
      console.log(`AFTER DIFFING PREVIOUS STATE: <${previousValue}>, selectionStart: ${previousSelectionStart}, selectionEnd: ${previousSelectionEnd}`);
      console.log(`AFTER DIFFING CURRENT STATE: <${currentValue}>, selectionStart: ${currentSelectionStart}, selectionEnd: ${currentSelectionEnd}`);
    }
    return {
      text: currentValue,
      replacePrevCharCnt: previousSelectionEnd,
      replaceNextCharCnt: previousValue.length - previousSelectionEnd,
      positionDelta: currentSelectionEnd - currentValue.length
    };
  }
  static fromScreenReaderContentState(screenReaderContentState) {
    return new _$$7(screenReaderContentState.value, screenReaderContentState.selectionStart, screenReaderContentState.selectionEnd, screenReaderContentState.selection, screenReaderContentState.newlineCountBeforeSelection);
  }
};

// out-build/vs/editor/browser/controller/editContext/textArea/textAreaEditContextInput.js
var TextAreaSyntethicEvents;
(function(TextAreaSyntethicEvents2) {
  TextAreaSyntethicEvents2.Tap = "-monaco-textarea-synthetic-tap";
})(TextAreaSyntethicEvents || (TextAreaSyntethicEvents = {}));
var CompositionContext = class {
  constructor() {
    this.a = 0;
  }
  handleCompositionUpdate(text2) {
    text2 = text2 || "";
    const typeInput = {
      text: text2,
      replacePrevCharCnt: this.a,
      replaceNextCharCnt: 0,
      positionDelta: 0
    };
    this.a = text2.length;
    return typeInput;
  }
};
var $_7 = class $_72 extends $3c {
  get textAreaState() {
    return this.w;
  }
  constructor(D, F, G, H, I, J) {
    super();
    this.D = D;
    this.F = F;
    this.G = G;
    this.H = H;
    this.I = I;
    this.J = J;
    this.a = this.B(new $ze());
    this.onFocus = this.a.event;
    this.b = this.B(new $ze());
    this.onBlur = this.b.event;
    this.c = this.B(new $ze());
    this.onKeyDown = this.c.event;
    this.f = this.B(new $ze());
    this.onKeyUp = this.f.event;
    this.g = this.B(new $ze());
    this.onCut = this.g.event;
    this.h = this.B(new $ze());
    this.onPaste = this.h.event;
    this.j = this.B(new $ze());
    this.onType = this.j.event;
    this.m = this.B(new $ze());
    this.onCompositionStart = this.m.event;
    this.n = this.B(new $ze());
    this.onCompositionUpdate = this.n.event;
    this.r = this.B(new $ze());
    this.onCompositionEnd = this.r.event;
    this.s = this.B(new $ze());
    this.onSelectionChangeRequest = this.s.event;
    this.u = this.B(new $4c());
    this.t = this.B(new $8h(() => this.g.fire(), 0));
    this.w = $$7.EMPTY;
    this.y = null;
    if (this.I.isScreenReaderOptimized()) {
      this.writeNativeTextAreaContent("ctor");
    }
    this.B(Event2.runAndSubscribe(this.I.onDidChangeScreenReaderOptimized, () => {
      if (this.I.isScreenReaderOptimized() && !this.u.value) {
        this.u.value = this.B(new $8h(() => this.writeNativeTextAreaContent("asyncFocusGain"), 0));
      } else {
        this.u.clear();
      }
    }));
    this.z = false;
    this.C = null;
    let lastKeyDown = null;
    this.B(this.F.onKeyDown((_e) => {
      const e = new $if(_e);
      if (e.keyCode === 114 || this.C && e.keyCode === 1) {
        e.stopPropagation();
      }
      if (e.equals(
        9
        /* KeyCode.Escape */
      )) {
        e.preventDefault();
      }
      lastKeyDown = e;
      this.c.fire(e);
    }));
    this.B(this.F.onKeyUp((_e) => {
      const e = new $if(_e);
      this.f.fire(e);
    }));
    this.B(this.F.onCompositionStart((e) => {
      if ($07) {
        console.log(`[compositionstart]`, e);
      }
      const currentComposition = new CompositionContext();
      if (this.C) {
        this.C = currentComposition;
        return;
      }
      this.C = currentComposition;
      if (this.G === 2 && lastKeyDown && lastKeyDown.equals(
        114
        /* KeyCode.KEY_IN_COMPOSITION */
      ) && this.w.selectionStart === this.w.selectionEnd && this.w.selectionStart > 0 && this.w.value.substr(this.w.selectionStart - 1, 1) === e.data && (lastKeyDown.code === "ArrowRight" || lastKeyDown.code === "ArrowLeft")) {
        if ($07) {
          console.log(`[compositionstart] Handling long press case on macOS + arrow key`, e);
        }
        currentComposition.handleCompositionUpdate("x");
        this.m.fire({ data: e.data });
        return;
      }
      if (this.H.isAndroid) {
        this.m.fire({ data: e.data });
        return;
      }
      this.m.fire({ data: e.data });
    }));
    this.B(this.F.onCompositionUpdate((e) => {
      if ($07) {
        console.log(`[compositionupdate]`, e);
      }
      const currentComposition = this.C;
      if (!currentComposition) {
        return;
      }
      if (this.H.isAndroid) {
        const newState = $$7.readFromTextArea(this.F, this.w);
        const typeInput2 = $$7.deduceAndroidCompositionInput(this.w, newState);
        this.w = newState;
        this.j.fire(typeInput2);
        this.n.fire(e);
        return;
      }
      const typeInput = currentComposition.handleCompositionUpdate(e.data);
      this.w = $$7.readFromTextArea(this.F, this.w);
      this.j.fire(typeInput);
      this.n.fire(e);
    }));
    this.B(this.F.onCompositionEnd((e) => {
      if ($07) {
        console.log(`[compositionend]`, e);
      }
      const currentComposition = this.C;
      if (!currentComposition) {
        return;
      }
      this.C = null;
      if (this.H.isAndroid) {
        const newState = $$7.readFromTextArea(this.F, this.w);
        const typeInput2 = $$7.deduceAndroidCompositionInput(this.w, newState);
        this.w = newState;
        this.j.fire(typeInput2);
        this.r.fire();
        return;
      }
      const typeInput = currentComposition.handleCompositionUpdate(e.data);
      this.w = $$7.readFromTextArea(this.F, this.w);
      this.j.fire(typeInput);
      this.r.fire();
    }));
    this.B(this.F.onInput((e) => {
      if ($07) {
        console.log(`[input]`, e);
      }
      this.F.setIgnoreSelectionChangeTime("received input event");
      if (this.C) {
        return;
      }
      const newState = $$7.readFromTextArea(this.F, this.w);
      const typeInput = $$7.deduceInput(
        this.w,
        newState,
        /*couldBeEmojiInput*/
        this.G === 2
        /* OperatingSystem.Macintosh */
      );
      if (typeInput.replacePrevCharCnt === 0 && typeInput.text.length === 1) {
        if ($5f(typeInput.text.charCodeAt(0)) || typeInput.text.charCodeAt(0) === 127) {
          return;
        }
      }
      this.w = newState;
      if (typeInput.text !== "" || typeInput.replacePrevCharCnt !== 0 || typeInput.replaceNextCharCnt !== 0 || typeInput.positionDelta !== 0) {
        this.j.fire(typeInput);
      }
    }));
    this.B(this.F.onCut((e) => {
      this.F.setIgnoreSelectionChangeTime("received cut event");
      this.O(e);
      this.t.schedule();
    }));
    this.B(this.F.onCopy((e) => {
      this.O(e);
    }));
    this.B(this.F.onPaste((e) => {
      this.F.setIgnoreSelectionChangeTime("received paste event");
      e.preventDefault();
      if (!e.clipboardData) {
        return;
      }
      let [text2, metadata] = $67.getTextData(e.clipboardData);
      if (!text2) {
        return;
      }
      metadata = metadata || $47.INSTANCE.get(text2);
      this.h.fire({
        text: text2,
        metadata
      });
    }));
    this.B(this.F.onFocus(() => {
      const hadFocus = this.z;
      this.M(true);
      if (this.I.isScreenReaderOptimized() && this.H.isSafari && !hadFocus && this.z) {
        if (!this.u.value) {
          this.u.value = new $8h(() => this.writeNativeTextAreaContent("asyncFocusGain"), 0);
        }
        this.u.value.schedule();
      }
    }));
    this.B(this.F.onBlur(() => {
      if (this.C) {
        this.C = null;
        this.writeNativeTextAreaContent("blurWithoutCompositionEnd");
        this.r.fire();
      }
      this.M(false);
    }));
    this.B(this.F.onSyntheticTap(() => {
      if (this.H.isAndroid && this.C) {
        this.C = null;
        this.writeNativeTextAreaContent("tapWithoutCompositionEnd");
        this.r.fire();
      }
    }));
  }
  _initializeFromTest() {
    this.z = true;
    this.w = $$7.readFromTextArea(this.F, null);
  }
  L() {
    let previousSelectionChangeEventTime = 0;
    return $_i(this.F.ownerDocument, "selectionchange", (e) => {
      inputLatency.onSelectionChange();
      if (!this.z) {
        return;
      }
      if (this.C) {
        return;
      }
      if (!this.H.isChrome) {
        return;
      }
      const now = Date.now();
      const delta1 = now - previousSelectionChangeEventTime;
      previousSelectionChangeEventTime = now;
      if (delta1 < 5) {
        return;
      }
      const delta2 = now - this.F.getIgnoreSelectionChangeTime();
      this.F.resetSelectionChangeTime();
      if (delta2 < 100) {
        return;
      }
      if (!this.w.selection) {
        return;
      }
      const newValue = this.F.getValue();
      if (this.w.value !== newValue) {
        return;
      }
      const newSelectionStart = this.F.getSelectionStart();
      const newSelectionEnd = this.F.getSelectionEnd();
      if (this.w.selectionStart === newSelectionStart && this.w.selectionEnd === newSelectionEnd) {
        return;
      }
      const _newSelectionStartPosition = this.w.deduceEditorPosition(newSelectionStart);
      const newSelectionStartPosition = this.D.deduceModelPosition(_newSelectionStartPosition[0], _newSelectionStartPosition[1], _newSelectionStartPosition[2]);
      const _newSelectionEndPosition = this.w.deduceEditorPosition(newSelectionEnd);
      const newSelectionEndPosition = this.D.deduceModelPosition(_newSelectionEndPosition[0], _newSelectionEndPosition[1], _newSelectionEndPosition[2]);
      const newSelection = new $_D(newSelectionStartPosition.lineNumber, newSelectionStartPosition.column, newSelectionEndPosition.lineNumber, newSelectionEndPosition.column);
      this.s.fire(newSelection);
    });
  }
  dispose() {
    super.dispose();
    if (this.y) {
      this.y.dispose();
      this.y = null;
    }
  }
  focusTextArea() {
    this.M(true);
    this.refreshFocusState();
  }
  isFocused() {
    return this.z;
  }
  refreshFocusState() {
    this.M(this.F.hasFocus());
  }
  M(newHasFocus) {
    if (this.z === newHasFocus) {
      return;
    }
    this.z = newHasFocus;
    if (this.y) {
      this.y.dispose();
      this.y = null;
    }
    if (this.z) {
      this.y = this.L();
    }
    if (this.z) {
      this.writeNativeTextAreaContent("focusgain");
    }
    if (this.z) {
      this.a.fire();
    } else {
      this.b.fire();
    }
  }
  N(reason, textAreaState) {
    if (!this.z) {
      textAreaState = textAreaState.collapseSelection();
    }
    if (!textAreaState.isWrittenToTextArea(this.F, this.z)) {
      this.J.trace(`writeTextAreaState(reason: ${reason})`);
    }
    textAreaState.writeToTextArea(reason, this.F, this.z);
    this.w = textAreaState;
  }
  writeNativeTextAreaContent(reason) {
    if (!this.I.isScreenReaderOptimized() && reason === "render" || this.C) {
      return;
    }
    this.N(reason, this.D.getScreenReaderContent());
  }
  O(e) {
    const dataToCopy = this.D.getDataToCopy();
    const storedMetadata = {
      version: 1,
      isFromEmptySelection: dataToCopy.isFromEmptySelection,
      multicursorText: dataToCopy.multicursorText,
      mode: dataToCopy.mode
    };
    $47.INSTANCE.set(
      // When writing "LINE\r\n" to the clipboard and then pasting,
      // Firefox pastes "LINE\n", so let's work around this quirk
      this.H.isFirefox ? dataToCopy.text.replace(/\r\n/g, "\n") : dataToCopy.text,
      storedMetadata
    );
    e.preventDefault();
    if (e.clipboardData) {
      $67.setTextData(e.clipboardData, dataToCopy.text, dataToCopy.html, storedMetadata);
    }
  }
};
$_7 = __decorate([
  __param(4, $ND),
  __param(5, $wn)
], $_7);
var $a8 = class extends $3c {
  get ownerDocument() {
    return this.c.ownerDocument;
  }
  constructor(c) {
    super();
    this.c = c;
    this.onKeyDown = this.B(new $9Z(this.c, "keydown")).event;
    this.onKeyPress = this.B(new $9Z(this.c, "keypress")).event;
    this.onKeyUp = this.B(new $9Z(this.c, "keyup")).event;
    this.onCompositionStart = this.B(new $9Z(this.c, "compositionstart")).event;
    this.onCompositionUpdate = this.B(new $9Z(this.c, "compositionupdate")).event;
    this.onCompositionEnd = this.B(new $9Z(this.c, "compositionend")).event;
    this.onBeforeInput = this.B(new $9Z(this.c, "beforeinput")).event;
    this.onInput = this.B(new $9Z(this.c, "input")).event;
    this.onCut = this.B(new $9Z(this.c, "cut")).event;
    this.onCopy = this.B(new $9Z(this.c, "copy")).event;
    this.onPaste = this.B(new $9Z(this.c, "paste")).event;
    this.onFocus = this.B(new $9Z(this.c, "focus")).event;
    this.onBlur = this.B(new $9Z(this.c, "blur")).event;
    this.a = this.B(new $ze());
    this.onSyntheticTap = this.a.event;
    this.b = 0;
    this.B(this.onKeyDown(() => inputLatency.onKeyDown()));
    this.B(this.onBeforeInput(() => inputLatency.onBeforeInput()));
    this.B(this.onInput(() => inputLatency.onInput()));
    this.B(this.onKeyUp(() => inputLatency.onKeyUp()));
    this.B($_i(this.c, TextAreaSyntethicEvents.Tap, () => this.a.fire()));
  }
  hasFocus() {
    const shadowRoot = $Kj(this.c);
    if (shadowRoot) {
      return shadowRoot.activeElement === this.c;
    } else if (this.c.isConnected) {
      return $Lj() === this.c;
    } else {
      return false;
    }
  }
  setIgnoreSelectionChangeTime(reason) {
    this.b = Date.now();
  }
  getIgnoreSelectionChangeTime() {
    return this.b;
  }
  resetSelectionChangeTime() {
    this.b = 0;
  }
  getValue() {
    return this.c.value;
  }
  setValue(reason, value) {
    const textArea = this.c;
    if (textArea.value === value) {
      return;
    }
    this.setIgnoreSelectionChangeTime("setValue");
    textArea.value = value;
  }
  getSelectionStart() {
    return this.c.selectionDirection === "backward" ? this.c.selectionEnd : this.c.selectionStart;
  }
  getSelectionEnd() {
    return this.c.selectionDirection === "backward" ? this.c.selectionStart : this.c.selectionEnd;
  }
  setSelectionRange(reason, selectionStart, selectionEnd) {
    const textArea = this.c;
    let activeElement = null;
    const shadowRoot = $Kj(textArea);
    if (shadowRoot) {
      activeElement = shadowRoot.activeElement;
    } else {
      activeElement = $Lj();
    }
    const activeWindow = getWindow(activeElement);
    const currentIsFocused = activeElement === textArea;
    const currentSelectionStart = textArea.selectionStart;
    const currentSelectionEnd = textArea.selectionEnd;
    if (currentIsFocused && currentSelectionStart === selectionStart && currentSelectionEnd === selectionEnd) {
      if ($Ue && activeWindow.parent !== activeWindow) {
        textArea.focus();
      }
      return;
    }
    if (currentIsFocused) {
      this.setIgnoreSelectionChangeTime("setSelectionRange");
      textArea.setSelectionRange(selectionStart, selectionEnd);
      if ($Ue && activeWindow.parent !== activeWindow) {
        textArea.focus();
      }
      return;
    }
    try {
      const scrollState = $0j(textArea);
      this.setIgnoreSelectionChangeTime("setSelectionRange");
      textArea.focus();
      textArea.setSelectionRange(selectionStart, selectionEnd);
      $$j(textArea, scrollState);
    } catch (e) {
    }
  }
};

// out-build/vs/editor/browser/controller/pointerHandler.js
var $b8 = class extends $27 {
  constructor(context, viewController, viewHelper) {
    super(context, viewController, viewHelper);
    this.B($mZ.addTarget(this.c.linesContentDomNode));
    this.B($_i(this.c.linesContentDomNode, EventType.Tap, (e) => this.J(e)));
    this.B($_i(this.c.linesContentDomNode, EventType.Change, (e) => this.L(e)));
    this.B($_i(this.c.linesContentDomNode, EventType.Contextmenu, (e) => this.z(new $46(e, false, this.c.viewDomNode), false)));
    this.I = "mouse";
    this.B($_i(this.c.linesContentDomNode, "pointerdown", (e) => {
      const pointerType = e.pointerType;
      if (pointerType === "mouse") {
        this.I = "mouse";
        return;
      } else if (pointerType === "touch") {
        this.I = "touch";
      } else {
        this.I = "pen";
      }
    }));
    const pointerEvents = new $66(this.c.viewDomNode);
    this.B(pointerEvents.onPointerMove(this.c.viewDomNode, (e) => this.C(e)));
    this.B(pointerEvents.onPointerUp(this.c.viewDomNode, (e) => this.F(e)));
    this.B(pointerEvents.onPointerLeave(this.c.viewDomNode, (e) => this.D(e)));
    this.B(pointerEvents.onPointerDown(this.c.viewDomNode, (e, pointerId) => this.G(e, pointerId)));
  }
  J(event) {
    if (!event.initialTarget || !this.c.linesContentDomNode.contains(event.initialTarget)) {
      return;
    }
    event.preventDefault();
    this.c.focusTextArea();
    this.M(
      event,
      /*inSelectionMode*/
      false
    );
  }
  L(event) {
    if (this.I === "touch") {
      this.a.viewModel.viewLayout.deltaScrollNow(-event.translationX, -event.translationY);
    }
    if (this.I === "pen") {
      this.M(
        event,
        /*inSelectionMode*/
        true
      );
    }
  }
  M(event, inSelectionMode) {
    const target = this.s(new $46(event, false, this.c.viewDomNode), false);
    if (target.position) {
      this.b.dispatchMouse({
        position: target.position,
        mouseColumn: target.position.column,
        startedOnLineNumbers: false,
        revealType: 1,
        mouseDownCount: event.tapCount,
        inSelectionMode,
        altKey: false,
        ctrlKey: false,
        metaKey: false,
        shiftKey: false,
        leftButton: false,
        middleButton: false,
        onInjectedText: target.type === 6 && target.detail.injectedText !== null
      });
    }
  }
  G(e, pointerId) {
    if (e.browserEvent.pointerType === "touch") {
      return;
    }
    super.G(e, pointerId);
  }
};
var TouchHandler = class extends $27 {
  constructor(context, viewController, viewHelper) {
    super(context, viewController, viewHelper);
    this.B($mZ.addTarget(this.c.linesContentDomNode));
    this.B($_i(this.c.linesContentDomNode, EventType.Tap, (e) => this.I(e)));
    this.B($_i(this.c.linesContentDomNode, EventType.Change, (e) => this.J(e)));
    this.B($_i(this.c.linesContentDomNode, EventType.Contextmenu, (e) => this.z(new $46(e, false, this.c.viewDomNode), false)));
  }
  I(event) {
    event.preventDefault();
    this.c.focusTextArea();
    const target = this.s(new $46(event, false, this.c.viewDomNode), false);
    if (target.position) {
      const event2 = document.createEvent("CustomEvent");
      event2.initEvent(TextAreaSyntethicEvents.Tap, false, true);
      this.c.dispatchTextAreaEvent(event2);
      this.b.moveTo(
        target.position,
        1
        /* NavigationCommandRevealType.Minimal */
      );
    }
  }
  J(e) {
    this.a.viewModel.viewLayout.deltaScrollNow(-e.translationX, -e.translationY);
  }
};
var $c8 = class extends $3c {
  constructor(context, viewController, viewHelper) {
    super();
    const isPhone = $u || $L && $v;
    if (isPhone && $5e.pointerEvents) {
      this.a = this.B(new $b8(context, viewController, viewHelper));
    } else if ($Y.TouchEvent) {
      this.a = this.B(new TouchHandler(context, viewController, viewHelper));
    } else {
      this.a = this.B(new $27(context, viewController, viewHelper));
    }
  }
  getTargetAtClientPoint(clientX, clientY) {
    return this.a.getTargetAtClientPoint(clientX, clientY);
  }
};

// out-build/vs/editor/browser/view/viewController.js
var $17 = class {
  constructor(configuration2, viewModel, userInputEvents, commandDelegate) {
    this.a = configuration2;
    this.b = viewModel;
    this.c = userInputEvents;
    this.d = commandDelegate;
  }
  paste(text2, pasteOnNewLine, multicursorText, mode) {
    this.d.paste(text2, pasteOnNewLine, multicursorText, mode);
  }
  type(text2) {
    this.d.type(text2);
  }
  compositionType(text2, replacePrevCharCnt, replaceNextCharCnt, positionDelta) {
    this.d.compositionType(text2, replacePrevCharCnt, replaceNextCharCnt, positionDelta);
  }
  compositionStart() {
    this.d.startComposition();
  }
  compositionEnd() {
    this.d.endComposition();
  }
  cut() {
    this.d.cut();
  }
  setSelection(modelSelection) {
    CoreNavigationCommands.SetSelection.runCoreEditorCommand(this.b, {
      source: "keyboard",
      selection: modelSelection
    });
  }
  f(viewPosition) {
    const minColumn = this.b.getLineMinColumn(viewPosition.lineNumber);
    if (viewPosition.column < minColumn) {
      return new $8C(viewPosition.lineNumber, minColumn);
    }
    return viewPosition;
  }
  g(data) {
    switch (this.a.options.get(
      79
      /* EditorOption.multiCursorModifier */
    )) {
      case "altKey":
        return data.altKey;
      case "ctrlKey":
        return data.ctrlKey;
      case "metaKey":
        return data.metaKey;
      default:
        return false;
    }
  }
  h(data) {
    switch (this.a.options.get(
      79
      /* EditorOption.multiCursorModifier */
    )) {
      case "altKey":
        return data.ctrlKey || data.metaKey;
      case "ctrlKey":
        return data.altKey || data.metaKey;
      case "metaKey":
        return data.ctrlKey || data.altKey;
      default:
        return false;
    }
  }
  dispatchMouse(data) {
    const options3 = this.a.options;
    const selectionClipboardIsOn = $n && options3.get(
      112
      /* EditorOption.selectionClipboard */
    );
    const columnSelection = options3.get(
      22
      /* EditorOption.columnSelection */
    );
    if (data.middleButton && !selectionClipboardIsOn) {
      this.k(data.position, data.mouseColumn, data.inSelectionMode);
    } else if (data.startedOnLineNumbers) {
      if (this.g(data)) {
        if (data.inSelectionMode) {
          this.s(data.position, data.revealType);
        } else {
          this.l(data.position, true);
        }
      } else {
        if (data.inSelectionMode) {
          this.r(data.position, data.revealType);
        } else {
          this.q(data.position, data.revealType);
        }
      }
    } else if (data.mouseDownCount >= 4) {
      this.u();
    } else if (data.mouseDownCount === 3) {
      if (this.g(data)) {
        if (data.inSelectionMode) {
          this.t(data.position, data.revealType);
        } else {
          this.s(data.position, data.revealType);
        }
      } else {
        if (data.inSelectionMode) {
          this.r(data.position, data.revealType);
        } else {
          this.q(data.position, data.revealType);
        }
      }
    } else if (data.mouseDownCount === 2) {
      if (!data.onInjectedText) {
        if (this.g(data)) {
          this.p(data.position, data.revealType);
        } else {
          if (data.inSelectionMode) {
            this.o(data.position, data.revealType);
          } else {
            this.n(data.position, data.revealType);
          }
        }
      }
    } else {
      if (this.g(data)) {
        if (!this.h(data)) {
          if (data.shiftKey) {
            this.k(data.position, data.mouseColumn, true);
          } else {
            if (data.inSelectionMode) {
              this.m(data.position, data.revealType);
            } else {
              this.l(data.position, false);
            }
          }
        }
      } else {
        if (data.inSelectionMode) {
          if (data.altKey) {
            this.k(data.position, data.mouseColumn, true);
          } else {
            if (columnSelection) {
              this.k(data.position, data.mouseColumn, true);
            } else {
              this.j(data.position, data.revealType);
            }
          }
        } else {
          this.moveTo(data.position, data.revealType);
        }
      }
    }
  }
  i(viewPosition, revealType) {
    viewPosition = this.f(viewPosition);
    return {
      source: "mouse",
      position: this.v(viewPosition),
      viewPosition,
      revealType
    };
  }
  moveTo(viewPosition, revealType) {
    CoreNavigationCommands.MoveTo.runCoreEditorCommand(this.b, this.i(viewPosition, revealType));
  }
  j(viewPosition, revealType) {
    CoreNavigationCommands.MoveToSelect.runCoreEditorCommand(this.b, this.i(viewPosition, revealType));
  }
  k(viewPosition, mouseColumn, doColumnSelect) {
    viewPosition = this.f(viewPosition);
    CoreNavigationCommands.ColumnSelect.runCoreEditorCommand(this.b, {
      source: "mouse",
      position: this.v(viewPosition),
      viewPosition,
      mouseColumn,
      doColumnSelect
    });
  }
  l(viewPosition, wholeLine) {
    viewPosition = this.f(viewPosition);
    CoreNavigationCommands.CreateCursor.runCoreEditorCommand(this.b, {
      source: "mouse",
      position: this.v(viewPosition),
      viewPosition,
      wholeLine
    });
  }
  m(viewPosition, revealType) {
    CoreNavigationCommands.LastCursorMoveToSelect.runCoreEditorCommand(this.b, this.i(viewPosition, revealType));
  }
  n(viewPosition, revealType) {
    CoreNavigationCommands.WordSelect.runCoreEditorCommand(this.b, this.i(viewPosition, revealType));
  }
  o(viewPosition, revealType) {
    CoreNavigationCommands.WordSelectDrag.runCoreEditorCommand(this.b, this.i(viewPosition, revealType));
  }
  p(viewPosition, revealType) {
    CoreNavigationCommands.LastCursorWordSelect.runCoreEditorCommand(this.b, this.i(viewPosition, revealType));
  }
  q(viewPosition, revealType) {
    CoreNavigationCommands.LineSelect.runCoreEditorCommand(this.b, this.i(viewPosition, revealType));
  }
  r(viewPosition, revealType) {
    CoreNavigationCommands.LineSelectDrag.runCoreEditorCommand(this.b, this.i(viewPosition, revealType));
  }
  s(viewPosition, revealType) {
    CoreNavigationCommands.LastCursorLineSelect.runCoreEditorCommand(this.b, this.i(viewPosition, revealType));
  }
  t(viewPosition, revealType) {
    CoreNavigationCommands.LastCursorLineSelectDrag.runCoreEditorCommand(this.b, this.i(viewPosition, revealType));
  }
  u() {
    CoreNavigationCommands.SelectAll.runCoreEditorCommand(this.b, { source: "mouse" });
  }
  // ----------------------
  v(viewPosition) {
    return this.b.coordinatesConverter.convertViewPositionToModelPosition(viewPosition);
  }
  emitKeyDown(e) {
    this.c.emitKeyDown(e);
  }
  emitKeyUp(e) {
    this.c.emitKeyUp(e);
  }
  emitContextMenu(e) {
    this.c.emitContextMenu(e);
  }
  emitMouseMove(e) {
    this.c.emitMouseMove(e);
  }
  emitMouseLeave(e) {
    this.c.emitMouseLeave(e);
  }
  emitMouseUp(e) {
    this.c.emitMouseUp(e);
  }
  emitMouseDown(e) {
    this.c.emitMouseDown(e);
  }
  emitMouseDrag(e) {
    this.c.emitMouseDrag(e);
  }
  emitMouseDrop(e) {
    this.c.emitMouseDrop(e);
  }
  emitMouseDropCanceled() {
    this.c.emitMouseDropCanceled();
  }
  emitMouseWheel(e) {
    this.c.emitMouseWheel(e);
  }
};

// out-build/vs/base/browser/trustedTypes.js
function $W1(policyName, policyOptions) {
  const monacoEnvironment = globalThis.MonacoEnvironment;
  if (monacoEnvironment?.createTrustedTypesPolicy) {
    try {
      return monacoEnvironment.createTrustedTypesPolicy(policyName, policyOptions);
    } catch (err) {
      $gb(err);
      return void 0;
    }
  }
  try {
    return globalThis.trustedTypes?.createPolicy(policyName, policyOptions);
  } catch (err) {
    $gb(err);
    return void 0;
  }
}

// out-build/vs/editor/browser/view/viewLayer.js
var $h7 = class {
  constructor(c) {
    this.c = c;
    this._set(1, []);
  }
  flush() {
    this._set(1, []);
  }
  _set(rendLineNumberStart, lines) {
    this.a = lines;
    this.b = rendLineNumberStart;
  }
  _get() {
    return {
      rendLineNumberStart: this.b,
      lines: this.a
    };
  }
  /**
   * @returns Inclusive line number that is inside this collection
   */
  getStartLineNumber() {
    return this.b;
  }
  /**
   * @returns Inclusive line number that is inside this collection
   */
  getEndLineNumber() {
    return this.b + this.a.length - 1;
  }
  getCount() {
    return this.a.length;
  }
  getLine(lineNumber) {
    const lineIndex = lineNumber - this.b;
    if (lineIndex < 0 || lineIndex >= this.a.length) {
      throw new $vb("Illegal value for lineNumber");
    }
    return this.a[lineIndex];
  }
  /**
   * @returns Lines that were removed from this collection
   */
  onLinesDeleted(deleteFromLineNumber, deleteToLineNumber) {
    if (this.getCount() === 0) {
      return null;
    }
    const startLineNumber = this.getStartLineNumber();
    const endLineNumber = this.getEndLineNumber();
    if (deleteToLineNumber < startLineNumber) {
      const deleteCnt = deleteToLineNumber - deleteFromLineNumber + 1;
      this.b -= deleteCnt;
      return null;
    }
    if (deleteFromLineNumber > endLineNumber) {
      return null;
    }
    let deleteStartIndex = 0;
    let deleteCount = 0;
    for (let lineNumber = startLineNumber; lineNumber <= endLineNumber; lineNumber++) {
      const lineIndex = lineNumber - this.b;
      if (deleteFromLineNumber <= lineNumber && lineNumber <= deleteToLineNumber) {
        if (deleteCount === 0) {
          deleteStartIndex = lineIndex;
          deleteCount = 1;
        } else {
          deleteCount++;
        }
      }
    }
    if (deleteFromLineNumber < startLineNumber) {
      let deleteAboveCount = 0;
      if (deleteToLineNumber < startLineNumber) {
        deleteAboveCount = deleteToLineNumber - deleteFromLineNumber + 1;
      } else {
        deleteAboveCount = startLineNumber - deleteFromLineNumber;
      }
      this.b -= deleteAboveCount;
    }
    const deleted = this.a.splice(deleteStartIndex, deleteCount);
    return deleted;
  }
  onLinesChanged(changeFromLineNumber, changeCount) {
    const changeToLineNumber = changeFromLineNumber + changeCount - 1;
    if (this.getCount() === 0) {
      return false;
    }
    const startLineNumber = this.getStartLineNumber();
    const endLineNumber = this.getEndLineNumber();
    let someoneNotified = false;
    for (let changedLineNumber = changeFromLineNumber; changedLineNumber <= changeToLineNumber; changedLineNumber++) {
      if (changedLineNumber >= startLineNumber && changedLineNumber <= endLineNumber) {
        this.a[changedLineNumber - this.b].onContentChanged();
        someoneNotified = true;
      }
    }
    return someoneNotified;
  }
  onLinesInserted(insertFromLineNumber, insertToLineNumber) {
    if (this.getCount() === 0) {
      return null;
    }
    const insertCnt = insertToLineNumber - insertFromLineNumber + 1;
    const startLineNumber = this.getStartLineNumber();
    const endLineNumber = this.getEndLineNumber();
    if (insertFromLineNumber <= startLineNumber) {
      this.b += insertCnt;
      return null;
    }
    if (insertFromLineNumber > endLineNumber) {
      return null;
    }
    if (insertCnt + insertFromLineNumber > endLineNumber) {
      const deleted = this.a.splice(insertFromLineNumber - this.b, endLineNumber - insertFromLineNumber + 1);
      return deleted;
    }
    const newLines = [];
    for (let i2 = 0; i2 < insertCnt; i2++) {
      newLines[i2] = this.c.createLine();
    }
    const insertIndex = insertFromLineNumber - this.b;
    const beforeLines = this.a.slice(0, insertIndex);
    const afterLines = this.a.slice(insertIndex, this.a.length - insertCnt);
    const deletedLines = this.a.slice(this.a.length - insertCnt, this.a.length);
    this.a = beforeLines.concat(newLines).concat(afterLines);
    return deletedLines;
  }
  onTokensChanged(ranges) {
    if (this.getCount() === 0) {
      return false;
    }
    const startLineNumber = this.getStartLineNumber();
    const endLineNumber = this.getEndLineNumber();
    let notifiedSomeone = false;
    for (let i2 = 0, len = ranges.length; i2 < len; i2++) {
      const rng = ranges[i2];
      if (rng.toLineNumber < startLineNumber || rng.fromLineNumber > endLineNumber) {
        continue;
      }
      const from = Math.max(startLineNumber, rng.fromLineNumber);
      const to = Math.min(endLineNumber, rng.toLineNumber);
      for (let lineNumber = from; lineNumber <= to; lineNumber++) {
        const lineIndex = lineNumber - this.b;
        this.a[lineIndex].onTokensChanged();
        notifiedSomeone = true;
      }
    }
    return notifiedSomeone;
  }
};
var $i7 = class {
  constructor(b) {
    this.b = b;
    this.domNode = this.c();
    this.a = new $h7(this.b);
  }
  c() {
    const domNode = $oZ(document.createElement("div"));
    domNode.setClassName("view-layer");
    domNode.setPosition("absolute");
    domNode.domNode.setAttribute("role", "presentation");
    domNode.domNode.setAttribute("aria-hidden", "true");
    return domNode;
  }
  // ---- begin view event handlers
  onConfigurationChanged(e) {
    if (e.hasChanged(
      151
      /* EditorOption.layoutInfo */
    )) {
      return true;
    }
    return false;
  }
  onFlushed(e) {
    this.a.flush();
    return true;
  }
  onLinesChanged(e) {
    return this.a.onLinesChanged(e.fromLineNumber, e.count);
  }
  onLinesDeleted(e) {
    const deleted = this.a.onLinesDeleted(e.fromLineNumber, e.toLineNumber);
    if (deleted) {
      for (let i2 = 0, len = deleted.length; i2 < len; i2++) {
        const lineDomNode = deleted[i2].getDomNode();
        lineDomNode?.remove();
      }
    }
    return true;
  }
  onLinesInserted(e) {
    const deleted = this.a.onLinesInserted(e.fromLineNumber, e.toLineNumber);
    if (deleted) {
      for (let i2 = 0, len = deleted.length; i2 < len; i2++) {
        const lineDomNode = deleted[i2].getDomNode();
        lineDomNode?.remove();
      }
    }
    return true;
  }
  onScrollChanged(e) {
    return e.scrollTopChanged;
  }
  onTokensChanged(e) {
    return this.a.onTokensChanged(e.ranges);
  }
  onZonesChanged(e) {
    return true;
  }
  // ---- end view event handlers
  getStartLineNumber() {
    return this.a.getStartLineNumber();
  }
  getEndLineNumber() {
    return this.a.getEndLineNumber();
  }
  getVisibleLine(lineNumber) {
    return this.a.getLine(lineNumber);
  }
  renderLines(viewportData) {
    const inp = this.a._get();
    const renderer = new ViewLayerRenderer(this.domNode.domNode, this.b, viewportData);
    const ctx = {
      rendLineNumberStart: inp.rendLineNumberStart,
      lines: inp.lines,
      linesLength: inp.lines.length
    };
    const resCtx = renderer.render(ctx, viewportData.startLineNumber, viewportData.endLineNumber, viewportData.relativeVerticalOffset);
    this.a._set(resCtx.rendLineNumberStart, resCtx.lines);
  }
};
var ViewLayerRenderer = class _ViewLayerRenderer {
  static {
    this.a = $W1("editorViewLayer", { createHTML: (value) => value });
  }
  constructor(b, c, d) {
    this.b = b;
    this.c = c;
    this.d = d;
  }
  render(inContext, startLineNumber, stopLineNumber, deltaTop) {
    const ctx = {
      rendLineNumberStart: inContext.rendLineNumberStart,
      lines: inContext.lines.slice(0),
      linesLength: inContext.linesLength
    };
    if (ctx.rendLineNumberStart + ctx.linesLength - 1 < startLineNumber || stopLineNumber < ctx.rendLineNumberStart) {
      ctx.rendLineNumberStart = startLineNumber;
      ctx.linesLength = stopLineNumber - startLineNumber + 1;
      ctx.lines = [];
      for (let x = startLineNumber; x <= stopLineNumber; x++) {
        ctx.lines[x - startLineNumber] = this.c.createLine();
      }
      this.o(ctx, true, deltaTop);
      return ctx;
    }
    this.f(ctx, Math.max(startLineNumber - ctx.rendLineNumberStart, 0), Math.min(stopLineNumber - ctx.rendLineNumberStart, ctx.linesLength - 1), deltaTop, startLineNumber);
    if (ctx.rendLineNumberStart > startLineNumber) {
      const fromLineNumber = startLineNumber;
      const toLineNumber = Math.min(stopLineNumber, ctx.rendLineNumberStart - 1);
      if (fromLineNumber <= toLineNumber) {
        this.g(ctx, fromLineNumber, toLineNumber, deltaTop, startLineNumber);
        ctx.linesLength += toLineNumber - fromLineNumber + 1;
      }
    } else if (ctx.rendLineNumberStart < startLineNumber) {
      const removeCnt = Math.min(ctx.linesLength, startLineNumber - ctx.rendLineNumberStart);
      if (removeCnt > 0) {
        this.h(ctx, removeCnt);
        ctx.linesLength -= removeCnt;
      }
    }
    ctx.rendLineNumberStart = startLineNumber;
    if (ctx.rendLineNumberStart + ctx.linesLength - 1 < stopLineNumber) {
      const fromLineNumber = ctx.rendLineNumberStart + ctx.linesLength;
      const toLineNumber = stopLineNumber;
      if (fromLineNumber <= toLineNumber) {
        this.j(ctx, fromLineNumber, toLineNumber, deltaTop, startLineNumber);
        ctx.linesLength += toLineNumber - fromLineNumber + 1;
      }
    } else if (ctx.rendLineNumberStart + ctx.linesLength - 1 > stopLineNumber) {
      const fromLineNumber = Math.max(0, stopLineNumber - ctx.rendLineNumberStart + 1);
      const toLineNumber = ctx.linesLength - 1;
      const removeCnt = toLineNumber - fromLineNumber + 1;
      if (removeCnt > 0) {
        this.k(ctx, removeCnt);
        ctx.linesLength -= removeCnt;
      }
    }
    this.o(ctx, false, deltaTop);
    return ctx;
  }
  f(ctx, startIndex, endIndex, deltaTop, deltaLN) {
    const rendLineNumberStart = ctx.rendLineNumberStart;
    const lines = ctx.lines;
    for (let i2 = startIndex; i2 <= endIndex; i2++) {
      const lineNumber = rendLineNumberStart + i2;
      lines[i2].layoutLine(lineNumber, deltaTop[lineNumber - deltaLN], this.d.lineHeight);
    }
  }
  g(ctx, fromLineNumber, toLineNumber, deltaTop, deltaLN) {
    const newLines = [];
    let newLinesLen = 0;
    for (let lineNumber = fromLineNumber; lineNumber <= toLineNumber; lineNumber++) {
      newLines[newLinesLen++] = this.c.createLine();
    }
    ctx.lines = newLines.concat(ctx.lines);
  }
  h(ctx, removeCount) {
    for (let i2 = 0; i2 < removeCount; i2++) {
      const lineDomNode = ctx.lines[i2].getDomNode();
      lineDomNode?.remove();
    }
    ctx.lines.splice(0, removeCount);
  }
  j(ctx, fromLineNumber, toLineNumber, deltaTop, deltaLN) {
    const newLines = [];
    let newLinesLen = 0;
    for (let lineNumber = fromLineNumber; lineNumber <= toLineNumber; lineNumber++) {
      newLines[newLinesLen++] = this.c.createLine();
    }
    ctx.lines = ctx.lines.concat(newLines);
  }
  k(ctx, removeCount) {
    const removeIndex = ctx.linesLength - removeCount;
    for (let i2 = 0; i2 < removeCount; i2++) {
      const lineDomNode = ctx.lines[removeIndex + i2].getDomNode();
      lineDomNode?.remove();
    }
    ctx.lines.splice(removeIndex, removeCount);
  }
  l(ctx, domNodeIsEmpty, newLinesHTML, wasNew) {
    if (_ViewLayerRenderer.a) {
      newLinesHTML = _ViewLayerRenderer.a.createHTML(newLinesHTML);
    }
    const lastChild = this.b.lastChild;
    if (domNodeIsEmpty || !lastChild) {
      this.b.innerHTML = newLinesHTML;
    } else {
      lastChild.insertAdjacentHTML("afterend", newLinesHTML);
    }
    let currChild = this.b.lastChild;
    for (let i2 = ctx.linesLength - 1; i2 >= 0; i2--) {
      const line = ctx.lines[i2];
      if (wasNew[i2]) {
        line.setDomNode(currChild);
        currChild = currChild.previousSibling;
      }
    }
  }
  m(ctx, invalidLinesHTML, wasInvalid) {
    const hugeDomNode = document.createElement("div");
    if (_ViewLayerRenderer.a) {
      invalidLinesHTML = _ViewLayerRenderer.a.createHTML(invalidLinesHTML);
    }
    hugeDomNode.innerHTML = invalidLinesHTML;
    for (let i2 = 0; i2 < ctx.linesLength; i2++) {
      const line = ctx.lines[i2];
      if (wasInvalid[i2]) {
        const source = hugeDomNode.firstChild;
        const lineDomNode = line.getDomNode();
        lineDomNode.parentNode.replaceChild(source, lineDomNode);
        line.setDomNode(source);
      }
    }
  }
  static {
    this.n = new $cE(1e5);
  }
  o(ctx, domNodeIsEmpty, deltaTop) {
    const sb = _ViewLayerRenderer.n;
    const linesLength = ctx.linesLength;
    const lines = ctx.lines;
    const rendLineNumberStart = ctx.rendLineNumberStart;
    const wasNew = [];
    {
      sb.reset();
      let hadNewLine = false;
      for (let i2 = 0; i2 < linesLength; i2++) {
        const line = lines[i2];
        wasNew[i2] = false;
        const lineDomNode = line.getDomNode();
        if (lineDomNode) {
          continue;
        }
        const renderResult = line.renderLine(i2 + rendLineNumberStart, deltaTop[i2], this.d.lineHeight, this.d, sb);
        if (!renderResult) {
          continue;
        }
        wasNew[i2] = true;
        hadNewLine = true;
      }
      if (hadNewLine) {
        this.l(ctx, domNodeIsEmpty, sb.build(), wasNew);
      }
    }
    {
      sb.reset();
      let hadInvalidLine = false;
      const wasInvalid = [];
      for (let i2 = 0; i2 < linesLength; i2++) {
        const line = lines[i2];
        wasInvalid[i2] = false;
        if (wasNew[i2]) {
          continue;
        }
        const renderResult = line.renderLine(i2 + rendLineNumberStart, deltaTop[i2], this.d.lineHeight, this.d, sb);
        if (!renderResult) {
          continue;
        }
        wasInvalid[i2] = true;
        hadInvalidLine = true;
      }
      if (hadInvalidLine) {
        this.m(ctx, sb.build(), wasInvalid);
      }
    }
  }
};

// out-build/vs/editor/browser/view/viewOverlays.js
var $e8 = class extends $f7 {
  constructor(context) {
    super(context);
    this.c = [];
    this.f = false;
    this.a = new $i7({
      createLine: () => new $f8(this.c)
    });
    this.b = this.a.domNode;
    const options3 = this._context.configuration.options;
    const fontInfo = options3.get(
      52
      /* EditorOption.fontInfo */
    );
    $24(this.b, fontInfo);
    this.b.setClassName("view-overlays");
  }
  shouldRender() {
    if (super.shouldRender()) {
      return true;
    }
    for (let i2 = 0, len = this.c.length; i2 < len; i2++) {
      const dynamicOverlay = this.c[i2];
      if (dynamicOverlay.shouldRender()) {
        return true;
      }
    }
    return false;
  }
  dispose() {
    super.dispose();
    for (let i2 = 0, len = this.c.length; i2 < len; i2++) {
      const dynamicOverlay = this.c[i2];
      dynamicOverlay.dispose();
    }
    this.c = [];
  }
  getDomNode() {
    return this.b;
  }
  addDynamicOverlay(overlay) {
    this.c.push(overlay);
  }
  // ----- event handlers
  onConfigurationChanged(e) {
    this.a.onConfigurationChanged(e);
    const options3 = this._context.configuration.options;
    const fontInfo = options3.get(
      52
      /* EditorOption.fontInfo */
    );
    $24(this.b, fontInfo);
    return true;
  }
  onFlushed(e) {
    return this.a.onFlushed(e);
  }
  onFocusChanged(e) {
    this.f = e.isFocused;
    return true;
  }
  onLinesChanged(e) {
    return this.a.onLinesChanged(e);
  }
  onLinesDeleted(e) {
    return this.a.onLinesDeleted(e);
  }
  onLinesInserted(e) {
    return this.a.onLinesInserted(e);
  }
  onScrollChanged(e) {
    return this.a.onScrollChanged(e) || true;
  }
  onTokensChanged(e) {
    return this.a.onTokensChanged(e);
  }
  onZonesChanged(e) {
    return this.a.onZonesChanged(e);
  }
  // ----- end event handlers
  prepareRender(ctx) {
    const toRender = this.c.filter((overlay) => overlay.shouldRender());
    for (let i2 = 0, len = toRender.length; i2 < len; i2++) {
      const dynamicOverlay = toRender[i2];
      dynamicOverlay.prepareRender(ctx);
      dynamicOverlay.onDidRender();
    }
  }
  render(ctx) {
    this._viewOverlaysRender(ctx);
    this.b.toggleClassName("focused", this.f);
  }
  _viewOverlaysRender(ctx) {
    this.a.renderLines(ctx.viewportData);
  }
};
var $f8 = class {
  constructor(dynamicOverlays) {
    this.a = dynamicOverlays;
    this.b = null;
    this.c = null;
  }
  getDomNode() {
    if (!this.b) {
      return null;
    }
    return this.b.domNode;
  }
  setDomNode(domNode) {
    this.b = $oZ(domNode);
  }
  onContentChanged() {
  }
  onTokensChanged() {
  }
  renderLine(lineNumber, deltaTop, lineHeight, viewportData, sb) {
    let result = "";
    for (let i2 = 0, len = this.a.length; i2 < len; i2++) {
      const dynamicOverlay = this.a[i2];
      result += dynamicOverlay.render(viewportData.startLineNumber, lineNumber);
    }
    if (this.c === result) {
      return false;
    }
    this.c = result;
    sb.appendString('<div style="top:');
    sb.appendString(String(deltaTop));
    sb.appendString("px;height:");
    sb.appendString(String(lineHeight));
    sb.appendString('px;">');
    sb.appendString(result);
    sb.appendString("</div>");
    return true;
  }
  layoutLine(lineNumber, deltaTop, lineHeight) {
    if (this.b) {
      this.b.setTop(deltaTop);
      this.b.setHeight(lineHeight);
    }
  }
};
var $g8 = class extends $e8 {
  constructor(context) {
    super(context);
    const options3 = this._context.configuration.options;
    const layoutInfo = options3.get(
      151
      /* EditorOption.layoutInfo */
    );
    this.g = layoutInfo.contentWidth;
    this.b.setHeight(0);
  }
  // --- begin event handlers
  onConfigurationChanged(e) {
    const options3 = this._context.configuration.options;
    const layoutInfo = options3.get(
      151
      /* EditorOption.layoutInfo */
    );
    this.g = layoutInfo.contentWidth;
    return super.onConfigurationChanged(e) || true;
  }
  onScrollChanged(e) {
    return super.onScrollChanged(e) || e.scrollWidthChanged;
  }
  // --- end event handlers
  _viewOverlaysRender(ctx) {
    super._viewOverlaysRender(ctx);
    this.b.setWidth(Math.max(ctx.scrollWidth, this.g));
  }
};
var $h8 = class extends $e8 {
  constructor(context) {
    super(context);
    const options3 = this._context.configuration.options;
    const layoutInfo = options3.get(
      151
      /* EditorOption.layoutInfo */
    );
    this.g = layoutInfo.contentLeft;
    this.b.setClassName("margin-view-overlays");
    this.b.setWidth(1);
    $24(this.b, options3.get(
      52
      /* EditorOption.fontInfo */
    ));
  }
  onConfigurationChanged(e) {
    const options3 = this._context.configuration.options;
    $24(this.b, options3.get(
      52
      /* EditorOption.fontInfo */
    ));
    const layoutInfo = options3.get(
      151
      /* EditorOption.layoutInfo */
    );
    this.g = layoutInfo.contentLeft;
    return super.onConfigurationChanged(e) || true;
  }
  onScrollChanged(e) {
    return super.onScrollChanged(e) || e.scrollHeightChanged;
  }
  _viewOverlaysRender(ctx) {
    super._viewOverlaysRender(ctx);
    const height = Math.min(ctx.scrollHeight, 1e6);
    this.b.setHeight(height);
    this.b.setWidth(this.g);
  }
};

// out-build/vs/editor/browser/view/viewUserInputEvents.js
var $Z7 = class _$Z7 {
  constructor(coordinatesConverter) {
    this.onKeyDown = null;
    this.onKeyUp = null;
    this.onContextMenu = null;
    this.onMouseMove = null;
    this.onMouseLeave = null;
    this.onMouseDown = null;
    this.onMouseUp = null;
    this.onMouseDrag = null;
    this.onMouseDrop = null;
    this.onMouseDropCanceled = null;
    this.onMouseWheel = null;
    this.a = coordinatesConverter;
  }
  emitKeyDown(e) {
    this.onKeyDown?.(e);
  }
  emitKeyUp(e) {
    this.onKeyUp?.(e);
  }
  emitContextMenu(e) {
    this.onContextMenu?.(this.b(e));
  }
  emitMouseMove(e) {
    this.onMouseMove?.(this.b(e));
  }
  emitMouseLeave(e) {
    this.onMouseLeave?.(this.b(e));
  }
  emitMouseDown(e) {
    this.onMouseDown?.(this.b(e));
  }
  emitMouseUp(e) {
    this.onMouseUp?.(this.b(e));
  }
  emitMouseDrag(e) {
    this.onMouseDrag?.(this.b(e));
  }
  emitMouseDrop(e) {
    this.onMouseDrop?.(this.b(e));
  }
  emitMouseDropCanceled() {
    this.onMouseDropCanceled?.();
  }
  emitMouseWheel(e) {
    this.onMouseWheel?.(e);
  }
  b(e) {
    if (e.target) {
      return {
        event: e.event,
        target: this.c(e.target)
      };
    }
    return e;
  }
  c(target) {
    return _$Z7.convertViewToModelMouseTarget(target, this.a);
  }
  static convertViewToModelMouseTarget(target, coordinatesConverter) {
    const result = { ...target };
    if (result.position) {
      result.position = coordinatesConverter.convertViewPositionToModelPosition(result.position);
    }
    if (result.range) {
      result.range = coordinatesConverter.convertViewRangeToModelRange(result.range);
    }
    if (result.type === 5 || result.type === 8) {
      result.detail = this.d(result.detail, coordinatesConverter);
    }
    return result;
  }
  static d(data, coordinatesConverter) {
    return {
      viewZoneId: data.viewZoneId,
      positionBefore: data.positionBefore ? coordinatesConverter.convertViewPositionToModelPosition(data.positionBefore) : data.positionBefore,
      positionAfter: data.positionAfter ? coordinatesConverter.convertViewPositionToModelPosition(data.positionAfter) : data.positionAfter,
      position: coordinatesConverter.convertViewPositionToModelPosition(data.position),
      afterLineNumber: coordinatesConverter.convertViewPositionToModelPosition(new $8C(data.afterLineNumber, 1)).lineNumber
    };
  }
};

// out-build/vs/editor/browser/viewParts/blockDecorations/blockDecorations.js
var $i8 = class extends $f7 {
  constructor(context) {
    super(context);
    this.a = [];
    this.b = -1;
    this.c = 0;
    this.domNode = $oZ(document.createElement("div"));
    this.domNode.setAttribute("role", "presentation");
    this.domNode.setAttribute("aria-hidden", "true");
    this.domNode.setClassName("blockDecorations-container");
    this.f();
  }
  f() {
    let didChange = false;
    const options3 = this._context.configuration.options;
    const layoutInfo = options3.get(
      151
      /* EditorOption.layoutInfo */
    );
    const newContentWidth = layoutInfo.contentWidth - layoutInfo.verticalScrollbarWidth;
    if (this.b !== newContentWidth) {
      this.b = newContentWidth;
      didChange = true;
    }
    const newContentLeft = layoutInfo.contentLeft;
    if (this.c !== newContentLeft) {
      this.c = newContentLeft;
      didChange = true;
    }
    return didChange;
  }
  dispose() {
    super.dispose();
  }
  // --- begin event handlers
  onConfigurationChanged(e) {
    return this.f();
  }
  onScrollChanged(e) {
    return e.scrollTopChanged || e.scrollLeftChanged;
  }
  onDecorationsChanged(e) {
    return true;
  }
  onZonesChanged(e) {
    return true;
  }
  // --- end event handlers
  prepareRender(ctx) {
  }
  render(ctx) {
    let count = 0;
    const decorations = ctx.getDecorationsInViewport();
    for (const decoration3 of decorations) {
      if (!decoration3.options.blockClassName) {
        continue;
      }
      let block2 = this.a[count];
      if (!block2) {
        block2 = this.a[count] = $oZ(document.createElement("div"));
        this.domNode.appendChild(block2);
      }
      let top2;
      let bottom;
      if (decoration3.options.blockIsAfterEnd) {
        top2 = ctx.getVerticalOffsetAfterLineNumber(decoration3.range.endLineNumber, false);
        bottom = ctx.getVerticalOffsetAfterLineNumber(decoration3.range.endLineNumber, true);
      } else {
        top2 = ctx.getVerticalOffsetForLineNumber(decoration3.range.startLineNumber, true);
        bottom = decoration3.range.isEmpty() && !decoration3.options.blockDoesNotCollapse ? ctx.getVerticalOffsetForLineNumber(decoration3.range.startLineNumber, false) : ctx.getVerticalOffsetAfterLineNumber(decoration3.range.endLineNumber, true);
      }
      const [paddingTop, paddingRight, paddingBottom, paddingLeft] = decoration3.options.blockPadding ?? [0, 0, 0, 0];
      block2.setClassName("blockDecorations-block " + decoration3.options.blockClassName);
      block2.setLeft(this.c - paddingLeft);
      block2.setWidth(this.b + paddingLeft + paddingRight);
      block2.setTop(top2 - ctx.scrollTop - paddingTop);
      block2.setHeight(bottom - top2 + paddingTop + paddingBottom);
      count++;
    }
    for (let i2 = count; i2 < this.a.length; i2++) {
      this.a[i2].domNode.remove();
    }
    this.a.length = count;
  }
};

// out-build/vs/editor/browser/viewParts/contentWidgets/contentWidgets.js
var $j8 = class extends $f7 {
  constructor(context, viewDomNode) {
    super(context);
    this.a = viewDomNode;
    this.b = {};
    this.domNode = $oZ(document.createElement("div"));
    $g7.write(
      this.domNode,
      1
      /* PartFingerprint.ContentWidgets */
    );
    this.domNode.setClassName("contentWidgets");
    this.domNode.setPosition("absolute");
    this.domNode.setTop(0);
    this.overflowingContentWidgetsDomNode = $oZ(document.createElement("div"));
    $g7.write(
      this.overflowingContentWidgetsDomNode,
      2
      /* PartFingerprint.OverflowingContentWidgets */
    );
    this.overflowingContentWidgetsDomNode.setClassName("overflowingContentWidgets");
  }
  dispose() {
    super.dispose();
    this.b = {};
  }
  // --- begin event handlers
  onConfigurationChanged(e) {
    const keys = Object.keys(this.b);
    for (const widgetId of keys) {
      this.b[widgetId].onConfigurationChanged(e);
    }
    return true;
  }
  onDecorationsChanged(e) {
    return true;
  }
  onFlushed(e) {
    return true;
  }
  onLineMappingChanged(e) {
    this.c();
    return true;
  }
  onLinesChanged(e) {
    this.c();
    return true;
  }
  onLinesDeleted(e) {
    this.c();
    return true;
  }
  onLinesInserted(e) {
    this.c();
    return true;
  }
  onScrollChanged(e) {
    return true;
  }
  onZonesChanged(e) {
    return true;
  }
  // ---- end view event handlers
  c() {
    const keys = Object.keys(this.b);
    for (const widgetId of keys) {
      this.b[widgetId].updateAnchorViewPosition();
    }
  }
  addWidget(_widget) {
    const myWidget = new Widget(this._context, this.a, _widget);
    this.b[myWidget.id] = myWidget;
    if (myWidget.allowEditorOverflow) {
      this.overflowingContentWidgetsDomNode.appendChild(myWidget.domNode);
    } else {
      this.domNode.appendChild(myWidget.domNode);
    }
    this.u();
  }
  setWidgetPosition(widget, primaryAnchor, secondaryAnchor, preference, affinity) {
    const myWidget = this.b[widget.getId()];
    myWidget.setPosition(primaryAnchor, secondaryAnchor, preference, affinity);
    this.u();
  }
  removeWidget(widget) {
    const widgetId = widget.getId();
    if (this.b.hasOwnProperty(widgetId)) {
      const myWidget = this.b[widgetId];
      delete this.b[widgetId];
      const domNode = myWidget.domNode.domNode;
      domNode.remove();
      domNode.removeAttribute("monaco-visible-content-widget");
      this.u();
    }
  }
  shouldSuppressMouseDownOnWidget(widgetId) {
    if (this.b.hasOwnProperty(widgetId)) {
      return this.b[widgetId].suppressMouseDown;
    }
    return false;
  }
  onBeforeRender(viewportData) {
    const keys = Object.keys(this.b);
    for (const widgetId of keys) {
      this.b[widgetId].onBeforeRender(viewportData);
    }
  }
  prepareRender(ctx) {
    const keys = Object.keys(this.b);
    for (const widgetId of keys) {
      this.b[widgetId].prepareRender(ctx);
    }
  }
  render(ctx) {
    const keys = Object.keys(this.b);
    for (const widgetId of keys) {
      this.b[widgetId].render(ctx);
    }
  }
};
var Widget = class {
  constructor(context, viewDomNode, actual) {
    this.i = new PositionPair(null, null);
    this.j = new PositionPair(null, null);
    this.a = context;
    this.b = viewDomNode;
    this.c = actual;
    this.domNode = $oZ(this.c.getDomNode());
    this.id = this.c.getId();
    this.allowEditorOverflow = this.c.allowEditorOverflow || false;
    this.suppressMouseDown = this.c.suppressMouseDown || false;
    const options3 = this.a.configuration.options;
    const layoutInfo = options3.get(
      151
      /* EditorOption.layoutInfo */
    );
    this.d = options3.get(
      44
      /* EditorOption.fixedOverflowWidgets */
    );
    this.f = layoutInfo.contentWidth;
    this.g = layoutInfo.contentLeft;
    this.h = options3.get(
      68
      /* EditorOption.lineHeight */
    );
    this.k = null;
    this.l = [];
    this.m = -1;
    this.n = -1;
    this.o = this.s();
    this.p = false;
    this.q = null;
    this.domNode.setPosition(this.d && this.allowEditorOverflow ? "fixed" : "absolute");
    this.domNode.setDisplay("none");
    this.domNode.setVisibility("hidden");
    this.domNode.setAttribute("widgetId", this.id);
    this.domNode.setMaxWidth(this.o);
  }
  onConfigurationChanged(e) {
    const options3 = this.a.configuration.options;
    this.h = options3.get(
      68
      /* EditorOption.lineHeight */
    );
    if (e.hasChanged(
      151
      /* EditorOption.layoutInfo */
    )) {
      const layoutInfo = options3.get(
        151
        /* EditorOption.layoutInfo */
      );
      this.g = layoutInfo.contentLeft;
      this.f = layoutInfo.contentWidth;
      this.o = this.s();
    }
  }
  updateAnchorViewPosition() {
    this.r(this.k, this.i.modelPosition, this.j.modelPosition);
  }
  r(affinity, primaryAnchor, secondaryAnchor) {
    this.k = affinity;
    this.i = getValidPositionPair(primaryAnchor, this.a.viewModel, this.k);
    this.j = getValidPositionPair(secondaryAnchor, this.a.viewModel, this.k);
    function getValidPositionPair(position, viewModel, affinity2) {
      if (!position) {
        return new PositionPair(null, null);
      }
      const validModelPosition = viewModel.model.validatePosition(position);
      if (viewModel.coordinatesConverter.modelPositionIsVisible(validModelPosition)) {
        const viewPosition = viewModel.coordinatesConverter.convertModelPositionToViewPosition(validModelPosition, affinity2 ?? void 0);
        return new PositionPair(position, viewPosition);
      }
      return new PositionPair(position, null);
    }
  }
  s() {
    const elDocument = this.domNode.domNode.ownerDocument;
    const elWindow = elDocument.defaultView;
    return this.allowEditorOverflow ? elWindow?.innerWidth || elDocument.documentElement.offsetWidth || elDocument.body.offsetWidth : this.f;
  }
  setPosition(primaryAnchor, secondaryAnchor, preference, affinity) {
    this.r(affinity, primaryAnchor, secondaryAnchor);
    this.l = preference;
    if (this.i.viewPosition && this.l && this.l.length > 0) {
      this.domNode.setDisplay("block");
    } else {
      this.domNode.setDisplay("none");
    }
    this.m = -1;
    this.n = -1;
  }
  t(anchor, width2, height, ctx) {
    const aboveLineTop = anchor.top;
    const heightAvailableAboveLine = aboveLineTop;
    const underLineTop = anchor.top + anchor.height;
    const heightAvailableUnderLine = ctx.viewportHeight - underLineTop;
    const aboveTop = aboveLineTop - height;
    const fitsAbove = heightAvailableAboveLine >= height;
    const belowTop = underLineTop;
    const fitsBelow = heightAvailableUnderLine >= height;
    let left = anchor.left;
    if (left + width2 > ctx.scrollLeft + ctx.viewportWidth) {
      left = ctx.scrollLeft + ctx.viewportWidth - width2;
    }
    if (left < ctx.scrollLeft) {
      left = ctx.scrollLeft;
    }
    return { fitsAbove, aboveTop, fitsBelow, belowTop, left };
  }
  u(windowSize, domNodePosition, left, width2) {
    const LEFT_PADDING = 15;
    const RIGHT_PADDING = 15;
    const MIN_LIMIT = Math.max(LEFT_PADDING, domNodePosition.left - width2);
    const MAX_LIMIT = Math.min(domNodePosition.left + domNodePosition.width + width2, windowSize.width - RIGHT_PADDING);
    const elDocument = this.b.domNode.ownerDocument;
    const elWindow = elDocument.defaultView;
    let absoluteLeft = domNodePosition.left + left - (elWindow?.scrollX ?? 0);
    if (absoluteLeft + width2 > MAX_LIMIT) {
      const delta = absoluteLeft - (MAX_LIMIT - width2);
      absoluteLeft -= delta;
      left -= delta;
    }
    if (absoluteLeft < MIN_LIMIT) {
      const delta = absoluteLeft - MIN_LIMIT;
      absoluteLeft -= delta;
      left -= delta;
    }
    return [left, absoluteLeft];
  }
  v(anchor, width2, height, ctx) {
    const aboveTop = anchor.top - height;
    const belowTop = anchor.top + anchor.height;
    const domNodePosition = $vj(this.b.domNode);
    const elDocument = this.b.domNode.ownerDocument;
    const elWindow = elDocument.defaultView;
    const absoluteAboveTop = domNodePosition.top + aboveTop - (elWindow?.scrollY ?? 0);
    const absoluteBelowTop = domNodePosition.top + belowTop - (elWindow?.scrollY ?? 0);
    const windowSize = $qj(elDocument.body);
    const [left, absoluteAboveLeft] = this.u(windowSize, domNodePosition, anchor.left - ctx.scrollLeft + this.g, width2);
    const TOP_PADDING = 22;
    const BOTTOM_PADDING = 22;
    const fitsAbove = absoluteAboveTop >= TOP_PADDING;
    const fitsBelow = absoluteBelowTop + height <= windowSize.height - BOTTOM_PADDING;
    if (this.d) {
      return {
        fitsAbove,
        aboveTop: Math.max(absoluteAboveTop, TOP_PADDING),
        fitsBelow,
        belowTop: absoluteBelowTop,
        left: absoluteAboveLeft
      };
    }
    return { fitsAbove, aboveTop, fitsBelow, belowTop, left };
  }
  w(topLeft) {
    return new Coordinate(topLeft.top, topLeft.left + this.g);
  }
  /**
   * Compute the coordinates above and below the primary and secondary anchors.
   * The content widget *must* touch the primary anchor.
   * The content widget should touch if possible the secondary anchor.
   */
  x(ctx) {
    const primary = getCoordinates(this.i.viewPosition, this.k, this.h);
    const secondaryViewPosition = this.j.viewPosition?.lineNumber === this.i.viewPosition?.lineNumber ? this.j.viewPosition : null;
    const secondary = getCoordinates(secondaryViewPosition, this.k, this.h);
    return { primary, secondary };
    function getCoordinates(position, affinity, lineHeight) {
      if (!position) {
        return null;
      }
      const horizontalPosition = ctx.visibleRangeForPosition(position);
      if (!horizontalPosition) {
        return null;
      }
      const left = position.column === 1 && affinity === 3 ? 0 : horizontalPosition.left;
      const top2 = ctx.getVerticalOffsetForLineNumber(position.lineNumber) - ctx.scrollTop;
      return new AnchorCoordinate(top2, left, lineHeight);
    }
  }
  y(primary, secondary, width2) {
    if (!secondary) {
      return primary;
    }
    const fontInfo = this.a.configuration.options.get(
      52
      /* EditorOption.fontInfo */
    );
    let left = secondary.left;
    if (left < primary.left) {
      left = Math.max(left, primary.left - width2 + fontInfo.typicalFullwidthCharacterWidth);
    } else {
      left = Math.min(left, primary.left + width2 - fontInfo.typicalFullwidthCharacterWidth);
    }
    return new AnchorCoordinate(primary.top, left, primary.height);
  }
  z(ctx) {
    if (!this.l || this.l.length === 0) {
      return null;
    }
    const { primary, secondary } = this.x(ctx);
    if (!primary) {
      return {
        kind: "offViewport",
        preserveFocus: this.domNode.domNode.contains(this.domNode.domNode.ownerDocument.activeElement)
      };
    }
    if (this.m === -1 || this.n === -1) {
      let preferredDimensions = null;
      if (typeof this.c.beforeRender === "function") {
        preferredDimensions = safeInvoke(this.c.beforeRender, this.c);
      }
      if (preferredDimensions) {
        this.m = preferredDimensions.width;
        this.n = preferredDimensions.height;
      } else {
        const domNode = this.domNode.domNode;
        const clientRect = domNode.getBoundingClientRect();
        this.m = Math.round(clientRect.width);
        this.n = Math.round(clientRect.height);
      }
    }
    const anchor = this.y(primary, secondary, this.m);
    let placement;
    if (this.allowEditorOverflow) {
      placement = this.v(anchor, this.m, this.n, ctx);
    } else {
      placement = this.t(anchor, this.m, this.n, ctx);
    }
    for (let pass = 1; pass <= 2; pass++) {
      for (const pref of this.l) {
        if (pref === 1) {
          if (!placement) {
            return null;
          }
          if (pass === 2 || placement.fitsAbove) {
            return {
              kind: "inViewport",
              coordinate: new Coordinate(placement.aboveTop, placement.left),
              position: 1
              /* ContentWidgetPositionPreference.ABOVE */
            };
          }
        } else if (pref === 2) {
          if (!placement) {
            return null;
          }
          if (pass === 2 || placement.fitsBelow) {
            return {
              kind: "inViewport",
              coordinate: new Coordinate(placement.belowTop, placement.left),
              position: 2
              /* ContentWidgetPositionPreference.BELOW */
            };
          }
        } else {
          if (this.allowEditorOverflow) {
            return {
              kind: "inViewport",
              coordinate: this.w(new Coordinate(anchor.top, anchor.left)),
              position: 0
              /* ContentWidgetPositionPreference.EXACT */
            };
          } else {
            return {
              kind: "inViewport",
              coordinate: new Coordinate(anchor.top, anchor.left),
              position: 0
              /* ContentWidgetPositionPreference.EXACT */
            };
          }
        }
      }
    }
    return null;
  }
  /**
   * On this first pass, we ensure that the content widget (if it is in the viewport) has the max width set correctly.
   */
  onBeforeRender(viewportData) {
    if (!this.i.viewPosition || !this.l) {
      return;
    }
    if (this.i.viewPosition.lineNumber < viewportData.startLineNumber || this.i.viewPosition.lineNumber > viewportData.endLineNumber) {
      return;
    }
    this.domNode.setMaxWidth(this.o);
  }
  prepareRender(ctx) {
    this.q = this.z(ctx);
  }
  render(ctx) {
    if (!this.q || this.q.kind === "offViewport") {
      if (this.p) {
        this.domNode.removeAttribute("monaco-visible-content-widget");
        this.p = false;
        if (this.q?.kind === "offViewport" && this.q.preserveFocus) {
          this.domNode.setTop(-1e3);
        } else {
          this.domNode.setVisibility("hidden");
        }
      }
      if (typeof this.c.afterRender === "function") {
        safeInvoke(this.c.afterRender, this.c, null, null);
      }
      return;
    }
    if (this.allowEditorOverflow) {
      this.domNode.setTop(this.q.coordinate.top);
      this.domNode.setLeft(this.q.coordinate.left);
    } else {
      this.domNode.setTop(this.q.coordinate.top + ctx.scrollTop - ctx.bigNumbersDelta);
      this.domNode.setLeft(this.q.coordinate.left);
    }
    if (!this.p) {
      this.domNode.setVisibility("inherit");
      this.domNode.setAttribute("monaco-visible-content-widget", "true");
      this.p = true;
    }
    if (typeof this.c.afterRender === "function") {
      safeInvoke(this.c.afterRender, this.c, this.q.position, this.q.coordinate);
    }
  }
};
var PositionPair = class {
  constructor(modelPosition, viewPosition) {
    this.modelPosition = modelPosition;
    this.viewPosition = viewPosition;
  }
};
var Coordinate = class {
  constructor(top2, left) {
    this.top = top2;
    this.left = left;
    this._coordinateBrand = void 0;
  }
};
var AnchorCoordinate = class {
  constructor(top2, left, height) {
    this.top = top2;
    this.left = left;
    this.height = height;
    this._anchorCoordinateBrand = void 0;
  }
};
function safeInvoke(fn, thisArg, ...args2) {
  try {
    return fn.call(thisArg, ...args2);
  } catch {
    return null;
  }
}

// out-build/vs/editor/browser/view/dynamicViewOverlay.js
var $d8 = class extends $D5 {
};

// out-build/vs/platform/theme/common/themeService.js
var $gs = $Qk("themeService");
function $hs(id2) {
  return { id: id2 };
}
var $is = $6l.file;
var $js = $6l.folder;
function $ks(type) {
  switch (type) {
    case ColorScheme.DARK:
      return "vs-dark";
    case ColorScheme.HIGH_CONTRAST_DARK:
      return "hc-black";
    case ColorScheme.HIGH_CONTRAST_LIGHT:
      return "hc-light";
    default:
      return "vs";
  }
}
var $ls = {
  ThemingContribution: "base.contributions.theming"
};
var ThemingRegistry = class {
  constructor() {
    this.a = [];
    this.a = [];
    this.b = new $ze();
  }
  onColorThemeChange(participant) {
    this.a.push(participant);
    this.b.fire(participant);
    return $1c(() => {
      const idx = this.a.indexOf(participant);
      this.a.splice(idx, 1);
    });
  }
  get onThemingParticipantAdded() {
    return this.b.event;
  }
  getThemingParticipants() {
    return this.a;
  }
};
var themingRegistry = new ThemingRegistry();
$Wn.add($ls.ThemingContribution, themingRegistry);
function $ms(participant) {
  return themingRegistry.onColorThemeChange(participant);
}
var $ns = class extends $3c {
  constructor(n) {
    super();
    this.n = n;
    this.h = n.getColorTheme();
    this.B(this.n.onDidColorThemeChange((theme) => this.w(theme)));
  }
  w(theme) {
    this.h = theme;
    this.updateStyles();
  }
  updateStyles() {
  }
  z(id2, modify) {
    let color2 = this.h.getColor(id2);
    if (color2 && modify) {
      color2 = modify(color2, this.h);
    }
    return color2 ? color2.toString() : null;
  }
};

// out-build/vs/editor/common/core/editorColorRegistry.js
var $LG = $5n("editor.lineHighlightBackground", null, localize(687, null));
var $MG = $5n("editor.lineHighlightBorder", { dark: "#282828", light: "#eeeeee", hcDark: "#f38518", hcLight: $ko }, localize(688, null));
var $NG = $5n("editor.rangeHighlightBackground", { dark: "#ffffff0b", light: "#fdff0033", hcDark: null, hcLight: null }, localize(689, null), true);
var $OG = $5n("editor.rangeHighlightBorder", { dark: null, light: null, hcDark: $lo, hcLight: $lo }, localize(690, null));
var $PG = $5n("editor.symbolHighlightBackground", { dark: $cp, light: $cp, hcDark: null, hcLight: null }, localize(691, null), true);
var $QG = $5n("editor.symbolHighlightBorder", { dark: null, light: null, hcDark: $lo, hcLight: $lo }, localize(692, null));
var $RG = $5n("editorCursor.foreground", { dark: "#AEAFAD", light: $Vn.black, hcDark: $Vn.white, hcLight: "#0F4A85" }, localize(693, null));
var $SG = $5n("editorCursor.background", null, localize(694, null));
var $TG = $5n("editorMultiCursor.primary.foreground", $RG, localize(695, null));
var $UG = $5n("editorMultiCursor.primary.background", $SG, localize(696, null));
var $VG = $5n("editorMultiCursor.secondary.foreground", $RG, localize(697, null));
var $WG = $5n("editorMultiCursor.secondary.background", $SG, localize(698, null));
var $XG = $5n("editorWhitespace.foreground", { dark: "#e3e4e229", light: "#33333333", hcDark: "#e3e4e229", hcLight: "#CCCCCC" }, localize(699, null));
var $YG = $5n("editorLineNumber.foreground", { dark: "#858585", light: "#237893", hcDark: $Vn.white, hcLight: "#292929" }, localize(700, null));
var $ZG = $5n("editorIndentGuide.background", $XG, localize(701, null), false, localize(702, null));
var $1G = $5n("editorIndentGuide.activeBackground", $XG, localize(703, null), false, localize(704, null));
var $2G = $5n("editorIndentGuide.background1", $ZG, localize(705, null));
var $3G = $5n("editorIndentGuide.background2", "#00000000", localize(706, null));
var $4G = $5n("editorIndentGuide.background3", "#00000000", localize(707, null));
var $5G = $5n("editorIndentGuide.background4", "#00000000", localize(708, null));
var $6G = $5n("editorIndentGuide.background5", "#00000000", localize(709, null));
var $7G = $5n("editorIndentGuide.background6", "#00000000", localize(710, null));
var $8G = $5n("editorIndentGuide.activeBackground1", $1G, localize(711, null));
var $9G = $5n("editorIndentGuide.activeBackground2", "#00000000", localize(712, null));
var $0G = $5n("editorIndentGuide.activeBackground3", "#00000000", localize(713, null));
var $$G = $5n("editorIndentGuide.activeBackground4", "#00000000", localize(714, null));
var $_G = $5n("editorIndentGuide.activeBackground5", "#00000000", localize(715, null));
var $aH = $5n("editorIndentGuide.activeBackground6", "#00000000", localize(716, null));
var deprecatedEditorActiveLineNumber = $5n("editorActiveLineNumber.foreground", { dark: "#c6c6c6", light: "#0B216F", hcDark: $lo, hcLight: $lo }, localize(717, null), false, localize(718, null));
var $bH = $5n("editorLineNumber.activeForeground", deprecatedEditorActiveLineNumber, localize(719, null));
var $cH = $5n("editorLineNumber.dimmedForeground", null, localize(720, null));
var $dH = $5n("editorRuler.foreground", { dark: "#5A5A5A", light: $Vn.lightgrey, hcDark: $Vn.white, hcLight: "#292929" }, localize(721, null));
var $eH = $5n("editorCodeLens.foreground", { dark: "#999999", light: "#919191", hcDark: "#999999", hcLight: "#292929" }, localize(722, null));
var $fH = $5n("editorBracketMatch.background", { dark: "#0064001a", light: "#0064001a", hcDark: "#0064001a", hcLight: "#0000" }, localize(723, null));
var $gH = $5n("editorBracketMatch.border", { dark: "#888", light: "#B9B9B9", hcDark: $ko, hcLight: $ko }, localize(724, null));
var $hH = $5n("editorOverviewRuler.border", { dark: "#7f7f7f4d", light: "#7f7f7f4d", hcDark: "#7f7f7f4d", hcLight: "#666666" }, localize(725, null));
var $iH = $5n("editorOverviewRuler.background", null, localize(726, null));
var $jH = $5n("editorGutter.background", $Ko, localize(727, null));
var $kH = $5n("editorUnnecessaryCode.border", { dark: null, light: null, hcDark: $Vn.fromHex("#fff").transparent(0.8), hcLight: $ko }, localize(728, null));
var $lH = $5n("editorUnnecessaryCode.opacity", { dark: $Vn.fromHex("#000a"), light: $Vn.fromHex("#0007"), hcDark: null, hcLight: null }, localize(729, null));
var $mH = $5n("editorGhostText.border", { dark: null, light: null, hcDark: $Vn.fromHex("#fff").transparent(0.8), hcLight: $Vn.fromHex("#292929").transparent(0.8) }, localize(730, null));
var $nH = $5n("editorGhostText.foreground", { dark: $Vn.fromHex("#ffffff56"), light: $Vn.fromHex("#0007"), hcDark: null, hcLight: null }, localize(731, null));
var $oH = $5n("editorGhostText.background", null, localize(732, null));
var rulerRangeDefault = new $Vn(new $Sn(0, 122, 204, 0.6));
var $pH = $5n("editorOverviewRuler.rangeHighlightForeground", rulerRangeDefault, localize(733, null), true);
var $qH = $5n("editorOverviewRuler.errorForeground", { dark: new $Vn(new $Sn(255, 18, 18, 0.7)), light: new $Vn(new $Sn(255, 18, 18, 0.7)), hcDark: new $Vn(new $Sn(255, 50, 50, 1)), hcLight: "#B5200D" }, localize(734, null));
var $rH = $5n("editorOverviewRuler.warningForeground", { dark: $Yo, light: $Yo, hcDark: $Zo, hcLight: $Zo }, localize(735, null));
var $sH = $5n("editorOverviewRuler.infoForeground", { dark: $2o, light: $2o, hcDark: $3o, hcLight: $3o }, localize(736, null));
var $tH = $5n("editorBracketHighlight.foreground1", { dark: "#FFD700", light: "#0431FAFF", hcDark: "#FFD700", hcLight: "#0431FAFF" }, localize(737, null));
var $uH = $5n("editorBracketHighlight.foreground2", { dark: "#DA70D6", light: "#319331FF", hcDark: "#DA70D6", hcLight: "#319331FF" }, localize(738, null));
var $vH = $5n("editorBracketHighlight.foreground3", { dark: "#179FFF", light: "#7B3814FF", hcDark: "#87CEFA", hcLight: "#7B3814FF" }, localize(739, null));
var $wH = $5n("editorBracketHighlight.foreground4", "#00000000", localize(740, null));
var $xH = $5n("editorBracketHighlight.foreground5", "#00000000", localize(741, null));
var $yH = $5n("editorBracketHighlight.foreground6", "#00000000", localize(742, null));
var $zH = $5n("editorBracketHighlight.unexpectedBracket.foreground", { dark: new $Vn(new $Sn(255, 18, 18, 0.8)), light: new $Vn(new $Sn(255, 18, 18, 0.8)), hcDark: "new Color(new RGBA(255, 50, 50, 1))", hcLight: "#B5200D" }, localize(743, null));
var $AH = $5n("editorBracketPairGuide.background1", "#00000000", localize(744, null));
var $BH = $5n("editorBracketPairGuide.background2", "#00000000", localize(745, null));
var $CH = $5n("editorBracketPairGuide.background3", "#00000000", localize(746, null));
var $DH = $5n("editorBracketPairGuide.background4", "#00000000", localize(747, null));
var $EH = $5n("editorBracketPairGuide.background5", "#00000000", localize(748, null));
var $FH = $5n("editorBracketPairGuide.background6", "#00000000", localize(749, null));
var $GH = $5n("editorBracketPairGuide.activeBackground1", "#00000000", localize(750, null));
var $HH = $5n("editorBracketPairGuide.activeBackground2", "#00000000", localize(751, null));
var $IH = $5n("editorBracketPairGuide.activeBackground3", "#00000000", localize(752, null));
var $JH = $5n("editorBracketPairGuide.activeBackground4", "#00000000", localize(753, null));
var $KH = $5n("editorBracketPairGuide.activeBackground5", "#00000000", localize(754, null));
var $LH = $5n("editorBracketPairGuide.activeBackground6", "#00000000", localize(755, null));
var $MH = $5n("editorUnicodeHighlight.border", $Yo, localize(756, null));
var $NH = $5n("editorUnicodeHighlight.background", $Xo, localize(757, null));
$ms((theme, collector) => {
  const background = theme.getColor($Ko);
  const lineHighlight = theme.getColor($LG);
  const imeBackground = lineHighlight && !lineHighlight.isTransparent() ? lineHighlight : background;
  if (imeBackground) {
    collector.addRule(`.monaco-editor .inputarea.ime-input { background-color: ${imeBackground}; }`);
  }
});

// out-build/vs/editor/browser/viewParts/currentLineHighlight/currentLineHighlight.js
var $k8 = class extends $d8 {
  constructor(context) {
    super();
    this.c = context;
    const options3 = this.c.configuration.options;
    const layoutInfo = options3.get(
      151
      /* EditorOption.layoutInfo */
    );
    this.f = options3.get(
      101
      /* EditorOption.renderLineHighlight */
    );
    this.r = options3.get(
      102
      /* EditorOption.renderLineHighlightOnlyWhenFocus */
    );
    this.g = layoutInfo.isViewportWrapping;
    this.h = layoutInfo.contentLeft;
    this.j = layoutInfo.contentWidth;
    this.n = true;
    this.t = false;
    this.w = [1];
    this.y = [new $_D(1, 1, 1, 1)];
    this.z = null;
    this.c.addEventHandler(this);
  }
  dispose() {
    this.c.removeEventHandler(this);
    super.dispose();
  }
  C() {
    let hasChanged = false;
    const lineNumbers = /* @__PURE__ */ new Set();
    for (const selection of this.y) {
      lineNumbers.add(selection.positionLineNumber);
    }
    const cursorsLineNumbers = Array.from(lineNumbers);
    cursorsLineNumbers.sort((a, b) => a - b);
    if (!$zb(this.w, cursorsLineNumbers)) {
      this.w = cursorsLineNumbers;
      hasChanged = true;
    }
    const selectionIsEmpty = this.y.every((s) => s.isEmpty());
    if (this.n !== selectionIsEmpty) {
      this.n = selectionIsEmpty;
      hasChanged = true;
    }
    return hasChanged;
  }
  // --- begin event handlers
  onThemeChanged(e) {
    return this.C();
  }
  onConfigurationChanged(e) {
    const options3 = this.c.configuration.options;
    const layoutInfo = options3.get(
      151
      /* EditorOption.layoutInfo */
    );
    this.f = options3.get(
      101
      /* EditorOption.renderLineHighlight */
    );
    this.r = options3.get(
      102
      /* EditorOption.renderLineHighlightOnlyWhenFocus */
    );
    this.g = layoutInfo.isViewportWrapping;
    this.h = layoutInfo.contentLeft;
    this.j = layoutInfo.contentWidth;
    return true;
  }
  onCursorStateChanged(e) {
    this.y = e.selections;
    return this.C();
  }
  onFlushed(e) {
    return true;
  }
  onLinesDeleted(e) {
    return true;
  }
  onLinesInserted(e) {
    return true;
  }
  onScrollChanged(e) {
    return e.scrollWidthChanged || e.scrollTopChanged;
  }
  onZonesChanged(e) {
    return true;
  }
  onFocusChanged(e) {
    if (!this.r) {
      return false;
    }
    this.t = e.isFocused;
    return true;
  }
  // --- end event handlers
  prepareRender(ctx) {
    if (!this.G()) {
      this.z = null;
      return;
    }
    const visibleStartLineNumber = ctx.visibleRange.startLineNumber;
    const visibleEndLineNumber = ctx.visibleRange.endLineNumber;
    const renderData = [];
    for (let lineNumber = visibleStartLineNumber; lineNumber <= visibleEndLineNumber; lineNumber++) {
      const lineIndex = lineNumber - visibleStartLineNumber;
      renderData[lineIndex] = "";
    }
    if (this.g) {
      const renderedLineWrapped = this.I(ctx, false);
      for (const cursorLineNumber of this.w) {
        const coordinatesConverter = this.c.viewModel.coordinatesConverter;
        const modelLineNumber = coordinatesConverter.convertViewPositionToModelPosition(new $8C(cursorLineNumber, 1)).lineNumber;
        const firstViewLineNumber = coordinatesConverter.convertModelPositionToViewPosition(new $8C(modelLineNumber, 1)).lineNumber;
        const lastViewLineNumber = coordinatesConverter.convertModelPositionToViewPosition(new $8C(modelLineNumber, this.c.viewModel.model.getLineMaxColumn(modelLineNumber))).lineNumber;
        const firstLine3 = Math.max(firstViewLineNumber, visibleStartLineNumber);
        const lastLine = Math.min(lastViewLineNumber, visibleEndLineNumber);
        for (let lineNumber = firstLine3; lineNumber <= lastLine; lineNumber++) {
          const lineIndex = lineNumber - visibleStartLineNumber;
          renderData[lineIndex] = renderedLineWrapped;
        }
      }
    }
    const renderedLineExact = this.I(ctx, true);
    for (const cursorLineNumber of this.w) {
      if (cursorLineNumber < visibleStartLineNumber || cursorLineNumber > visibleEndLineNumber) {
        continue;
      }
      const lineIndex = cursorLineNumber - visibleStartLineNumber;
      renderData[lineIndex] = renderedLineExact;
    }
    this.z = renderData;
  }
  render(startLineNumber, lineNumber) {
    if (!this.z) {
      return "";
    }
    const lineIndex = lineNumber - startLineNumber;
    if (lineIndex >= this.z.length) {
      return "";
    }
    return this.z[lineIndex];
  }
  D() {
    return (this.f === "gutter" || this.f === "all") && (!this.r || this.t);
  }
  F() {
    return (this.f === "line" || this.f === "all") && this.n && (!this.r || this.t);
  }
};
var $l8 = class extends $k8 {
  I(ctx, exact) {
    const className = "current-line" + (this.D() ? " current-line-both" : "") + (exact ? " current-line-exact" : "");
    return `<div class="${className}" style="width:${Math.max(ctx.scrollWidth, this.j)}px;"></div>`;
  }
  G() {
    return this.F();
  }
  H() {
    return this.D();
  }
};
var $m8 = class extends $k8 {
  I(ctx, exact) {
    const className = "current-line" + (this.D() ? " current-line-margin" : "") + (this.H() ? " current-line-margin-both" : "") + (this.D() && exact ? " current-line-exact-margin" : "");
    return `<div class="${className}" style="width:${this.h}px"></div>`;
  }
  G() {
    return true;
  }
  H() {
    return this.F();
  }
};
$ms((theme, collector) => {
  const lineHighlight = theme.getColor($LG);
  if (lineHighlight) {
    collector.addRule(`.monaco-editor .view-overlays .current-line { background-color: ${lineHighlight}; }`);
    collector.addRule(`.monaco-editor .margin-view-overlays .current-line-margin { background-color: ${lineHighlight}; border: none; }`);
  }
  if (!lineHighlight || lineHighlight.isTransparent() || theme.defines($MG)) {
    const lineHighlightBorder = theme.getColor($MG);
    if (lineHighlightBorder) {
      collector.addRule(`.monaco-editor .view-overlays .current-line-exact { border: 2px solid ${lineHighlightBorder}; }`);
      collector.addRule(`.monaco-editor .margin-view-overlays .current-line-exact-margin { border: 2px solid ${lineHighlightBorder}; }`);
      if ($es(theme.type)) {
        collector.addRule(`.monaco-editor .view-overlays .current-line-exact { border-width: 1px; }`);
        collector.addRule(`.monaco-editor .margin-view-overlays .current-line-exact-margin { border-width: 1px; }`);
      }
    }
  }
});

// out-build/vs/editor/browser/viewParts/decorations/decorations.js
var $n8 = class extends $d8 {
  constructor(context) {
    super();
    this.c = context;
    const options3 = this.c.configuration.options;
    this.f = options3.get(
      52
      /* EditorOption.fontInfo */
    ).typicalHalfwidthCharacterWidth;
    this.g = null;
    this.c.addEventHandler(this);
  }
  dispose() {
    this.c.removeEventHandler(this);
    this.g = null;
    super.dispose();
  }
  // --- begin event handlers
  onConfigurationChanged(e) {
    const options3 = this.c.configuration.options;
    this.f = options3.get(
      52
      /* EditorOption.fontInfo */
    ).typicalHalfwidthCharacterWidth;
    return true;
  }
  onDecorationsChanged(e) {
    return true;
  }
  onFlushed(e) {
    return true;
  }
  onLinesChanged(e) {
    return true;
  }
  onLinesDeleted(e) {
    return true;
  }
  onLinesInserted(e) {
    return true;
  }
  onScrollChanged(e) {
    return e.scrollTopChanged || e.scrollWidthChanged;
  }
  onZonesChanged(e) {
    return true;
  }
  // --- end event handlers
  prepareRender(ctx) {
    const _decorations = ctx.getDecorationsInViewport();
    let decorations = [];
    let decorationsLen = 0;
    for (let i2 = 0, len = _decorations.length; i2 < len; i2++) {
      const d = _decorations[i2];
      if (d.options.className) {
        decorations[decorationsLen++] = d;
      }
    }
    decorations = decorations.sort((a, b) => {
      if (a.options.zIndex < b.options.zIndex) {
        return -1;
      }
      if (a.options.zIndex > b.options.zIndex) {
        return 1;
      }
      const aClassName = a.options.className;
      const bClassName = b.options.className;
      if (aClassName < bClassName) {
        return -1;
      }
      if (aClassName > bClassName) {
        return 1;
      }
      return $9C.compareRangesUsingStarts(a.range, b.range);
    });
    const visibleStartLineNumber = ctx.visibleRange.startLineNumber;
    const visibleEndLineNumber = ctx.visibleRange.endLineNumber;
    const output = [];
    for (let lineNumber = visibleStartLineNumber; lineNumber <= visibleEndLineNumber; lineNumber++) {
      const lineIndex = lineNumber - visibleStartLineNumber;
      output[lineIndex] = "";
    }
    this.h(ctx, decorations, output);
    this.n(ctx, decorations, output);
    this.g = output;
  }
  h(ctx, decorations, output) {
    const visibleStartLineNumber = ctx.visibleRange.startLineNumber;
    const visibleEndLineNumber = ctx.visibleRange.endLineNumber;
    for (let i2 = 0, lenI = decorations.length; i2 < lenI; i2++) {
      const d = decorations[i2];
      if (!d.options.isWholeLine) {
        continue;
      }
      const decorationOutput = '<div class="cdr ' + d.options.className + '" style="left:0;width:100%;"></div>';
      const startLineNumber = Math.max(d.range.startLineNumber, visibleStartLineNumber);
      const endLineNumber = Math.min(d.range.endLineNumber, visibleEndLineNumber);
      for (let j = startLineNumber; j <= endLineNumber; j++) {
        const lineIndex = j - visibleStartLineNumber;
        output[lineIndex] += decorationOutput;
      }
    }
  }
  n(ctx, decorations, output) {
    const visibleStartLineNumber = ctx.visibleRange.startLineNumber;
    let prevClassName = null;
    let prevShowIfCollapsed = false;
    let prevRange = null;
    let prevShouldFillLineOnLineBreak = false;
    for (let i2 = 0, lenI = decorations.length; i2 < lenI; i2++) {
      const d = decorations[i2];
      if (d.options.isWholeLine) {
        continue;
      }
      const className = d.options.className;
      const showIfCollapsed = Boolean(d.options.showIfCollapsed);
      let range = d.range;
      if (showIfCollapsed && range.endColumn === 1 && range.endLineNumber !== range.startLineNumber) {
        range = new $9C(range.startLineNumber, range.startColumn, range.endLineNumber - 1, this.c.viewModel.getLineMaxColumn(range.endLineNumber - 1));
      }
      if (prevClassName === className && prevShowIfCollapsed === showIfCollapsed && $9C.areIntersectingOrTouching(prevRange, range)) {
        prevRange = $9C.plusRange(prevRange, range);
        continue;
      }
      if (prevClassName !== null) {
        this.r(ctx, prevRange, prevClassName, prevShouldFillLineOnLineBreak, prevShowIfCollapsed, visibleStartLineNumber, output);
      }
      prevClassName = className;
      prevShowIfCollapsed = showIfCollapsed;
      prevRange = range;
      prevShouldFillLineOnLineBreak = d.options.shouldFillLineOnLineBreak ?? false;
    }
    if (prevClassName !== null) {
      this.r(ctx, prevRange, prevClassName, prevShouldFillLineOnLineBreak, prevShowIfCollapsed, visibleStartLineNumber, output);
    }
  }
  r(ctx, range, className, shouldFillLineOnLineBreak, showIfCollapsed, visibleStartLineNumber, output) {
    const linesVisibleRanges = ctx.linesVisibleRangesForRange(
      range,
      /*TODO@Alex*/
      className === "findMatch"
    );
    if (!linesVisibleRanges) {
      return;
    }
    for (let j = 0, lenJ = linesVisibleRanges.length; j < lenJ; j++) {
      const lineVisibleRanges = linesVisibleRanges[j];
      if (lineVisibleRanges.outsideRenderedLine) {
        continue;
      }
      const lineIndex = lineVisibleRanges.lineNumber - visibleStartLineNumber;
      if (showIfCollapsed && lineVisibleRanges.ranges.length === 1) {
        const singleVisibleRange = lineVisibleRanges.ranges[0];
        if (singleVisibleRange.width < this.f) {
          const center = Math.round(singleVisibleRange.left + singleVisibleRange.width / 2);
          const left = Math.max(0, Math.round(center - this.f / 2));
          lineVisibleRanges.ranges[0] = new $a7(left, this.f);
        }
      }
      for (let k = 0, lenK = lineVisibleRanges.ranges.length; k < lenK; k++) {
        const expandToLeft = shouldFillLineOnLineBreak && lineVisibleRanges.continuesOnNextLine && lenK === 1;
        const visibleRange = lineVisibleRanges.ranges[k];
        const decorationOutput = '<div class="cdr ' + className + '" style="left:' + String(visibleRange.left) + "px;width:" + (expandToLeft ? "100%;" : String(visibleRange.width) + "px;") + '"></div>';
        output[lineIndex] += decorationOutput;
      }
    }
  }
  render(startLineNumber, lineNumber) {
    if (!this.g) {
      return "";
    }
    const lineIndex = lineNumber - startLineNumber;
    if (lineIndex < 0 || lineIndex >= this.g.length) {
      return "";
    }
    return this.g[lineIndex];
  }
};

// out-build/vs/editor/browser/viewParts/editorScrollbar/editorScrollbar.js
var $o8 = class extends $f7 {
  constructor(context, linesContent, viewDomNode, overflowGuardDomNode) {
    super(context);
    const options3 = this._context.configuration.options;
    const scrollbar = options3.get(
      108
      /* EditorOption.scrollbar */
    );
    const mouseWheelScrollSensitivity = options3.get(
      76
      /* EditorOption.mouseWheelScrollSensitivity */
    );
    const fastScrollSensitivity = options3.get(
      42
      /* EditorOption.fastScrollSensitivity */
    );
    const scrollPredominantAxis = options3.get(
      111
      /* EditorOption.scrollPredominantAxis */
    );
    const scrollbarOptions = {
      listenOnDomNode: viewDomNode.domNode,
      className: "editor-scrollable " + $ks(context.theme.type),
      useShadows: false,
      lazyRender: true,
      vertical: scrollbar.vertical,
      horizontal: scrollbar.horizontal,
      verticalHasArrows: scrollbar.verticalHasArrows,
      horizontalHasArrows: scrollbar.horizontalHasArrows,
      verticalScrollbarSize: scrollbar.verticalScrollbarSize,
      verticalSliderSize: scrollbar.verticalSliderSize,
      horizontalScrollbarSize: scrollbar.horizontalScrollbarSize,
      horizontalSliderSize: scrollbar.horizontalSliderSize,
      handleMouseWheel: scrollbar.handleMouseWheel,
      alwaysConsumeMouseWheel: scrollbar.alwaysConsumeMouseWheel,
      arrowSize: scrollbar.arrowSize,
      mouseWheelScrollSensitivity,
      fastScrollSensitivity,
      scrollPredominantAxis,
      scrollByPage: scrollbar.scrollByPage
    };
    this.a = this.B(new $BZ(linesContent.domNode, scrollbarOptions, this._context.viewLayout.getScrollable()));
    $g7.write(
      this.a.getDomNode(),
      6
      /* PartFingerprint.ScrollableElement */
    );
    this.b = $oZ(this.a.getDomNode());
    this.b.setPosition("absolute");
    this.c();
    const onBrowserDesperateReveal = (domNode, lookAtScrollTop, lookAtScrollLeft) => {
      const newScrollPosition = {};
      if (lookAtScrollTop) {
        const deltaTop = domNode.scrollTop;
        if (deltaTop) {
          newScrollPosition.scrollTop = this._context.viewLayout.getCurrentScrollTop() + deltaTop;
          domNode.scrollTop = 0;
        }
      }
      if (lookAtScrollLeft) {
        const deltaLeft = domNode.scrollLeft;
        if (deltaLeft) {
          newScrollPosition.scrollLeft = this._context.viewLayout.getCurrentScrollLeft() + deltaLeft;
          domNode.scrollLeft = 0;
        }
      }
      this._context.viewModel.viewLayout.setScrollPosition(
        newScrollPosition,
        1
        /* ScrollType.Immediate */
      );
    };
    this.B($_i(viewDomNode.domNode, "scroll", (e) => onBrowserDesperateReveal(viewDomNode.domNode, true, true)));
    this.B($_i(linesContent.domNode, "scroll", (e) => onBrowserDesperateReveal(linesContent.domNode, true, false)));
    this.B($_i(overflowGuardDomNode.domNode, "scroll", (e) => onBrowserDesperateReveal(overflowGuardDomNode.domNode, true, false)));
    this.B($_i(this.b.domNode, "scroll", (e) => onBrowserDesperateReveal(this.b.domNode, true, false)));
  }
  dispose() {
    super.dispose();
  }
  c() {
    const options3 = this._context.configuration.options;
    const layoutInfo = options3.get(
      151
      /* EditorOption.layoutInfo */
    );
    this.b.setLeft(layoutInfo.contentLeft);
    const minimap = options3.get(
      74
      /* EditorOption.minimap */
    );
    const side = minimap.side;
    if (side === "right") {
      this.b.setWidth(layoutInfo.contentWidth + layoutInfo.minimap.minimapWidth);
    } else {
      this.b.setWidth(layoutInfo.contentWidth);
    }
    this.b.setHeight(layoutInfo.height);
  }
  getOverviewRulerLayoutInfo() {
    return this.a.getOverviewRulerLayoutInfo();
  }
  getDomNode() {
    return this.b;
  }
  delegateVerticalScrollbarPointerDown(browserEvent) {
    this.a.delegateVerticalScrollbarPointerDown(browserEvent);
  }
  delegateScrollFromMouseWheelEvent(browserEvent) {
    this.a.delegateScrollFromMouseWheelEvent(browserEvent);
  }
  // --- begin event handlers
  onConfigurationChanged(e) {
    if (e.hasChanged(
      108
      /* EditorOption.scrollbar */
    ) || e.hasChanged(
      76
      /* EditorOption.mouseWheelScrollSensitivity */
    ) || e.hasChanged(
      42
      /* EditorOption.fastScrollSensitivity */
    )) {
      const options3 = this._context.configuration.options;
      const scrollbar = options3.get(
        108
        /* EditorOption.scrollbar */
      );
      const mouseWheelScrollSensitivity = options3.get(
        76
        /* EditorOption.mouseWheelScrollSensitivity */
      );
      const fastScrollSensitivity = options3.get(
        42
        /* EditorOption.fastScrollSensitivity */
      );
      const scrollPredominantAxis = options3.get(
        111
        /* EditorOption.scrollPredominantAxis */
      );
      const newOpts = {
        vertical: scrollbar.vertical,
        horizontal: scrollbar.horizontal,
        verticalScrollbarSize: scrollbar.verticalScrollbarSize,
        horizontalScrollbarSize: scrollbar.horizontalScrollbarSize,
        scrollByPage: scrollbar.scrollByPage,
        handleMouseWheel: scrollbar.handleMouseWheel,
        mouseWheelScrollSensitivity,
        fastScrollSensitivity,
        scrollPredominantAxis
      };
      this.a.updateOptions(newOpts);
    }
    if (e.hasChanged(
      151
      /* EditorOption.layoutInfo */
    )) {
      this.c();
    }
    return true;
  }
  onScrollChanged(e) {
    return true;
  }
  onThemeChanged(e) {
    this.a.updateClassName("editor-scrollable " + $ks(this._context.theme.type));
    return true;
  }
  // --- end event handlers
  prepareRender(ctx) {
  }
  render(ctx) {
    this.a.renderNow();
  }
};

// out-build/vs/editor/common/model.js
var OverviewRulerLane;
(function(OverviewRulerLane4) {
  OverviewRulerLane4[OverviewRulerLane4["Left"] = 1] = "Left";
  OverviewRulerLane4[OverviewRulerLane4["Center"] = 2] = "Center";
  OverviewRulerLane4[OverviewRulerLane4["Right"] = 4] = "Right";
  OverviewRulerLane4[OverviewRulerLane4["Full"] = 7] = "Full";
})(OverviewRulerLane || (OverviewRulerLane = {}));
var GlyphMarginLane;
(function(GlyphMarginLane3) {
  GlyphMarginLane3[GlyphMarginLane3["Left"] = 1] = "Left";
  GlyphMarginLane3[GlyphMarginLane3["Center"] = 2] = "Center";
  GlyphMarginLane3[GlyphMarginLane3["Right"] = 3] = "Right";
})(GlyphMarginLane || (GlyphMarginLane = {}));
var MinimapPosition;
(function(MinimapPosition3) {
  MinimapPosition3[MinimapPosition3["Inline"] = 1] = "Inline";
  MinimapPosition3[MinimapPosition3["Gutter"] = 2] = "Gutter";
})(MinimapPosition || (MinimapPosition = {}));
var MinimapSectionHeaderStyle;
(function(MinimapSectionHeaderStyle3) {
  MinimapSectionHeaderStyle3[MinimapSectionHeaderStyle3["Normal"] = 1] = "Normal";
  MinimapSectionHeaderStyle3[MinimapSectionHeaderStyle3["Underlined"] = 2] = "Underlined";
})(MinimapSectionHeaderStyle || (MinimapSectionHeaderStyle = {}));
var InjectedTextCursorStops;
(function(InjectedTextCursorStops3) {
  InjectedTextCursorStops3[InjectedTextCursorStops3["Both"] = 0] = "Both";
  InjectedTextCursorStops3[InjectedTextCursorStops3["Right"] = 1] = "Right";
  InjectedTextCursorStops3[InjectedTextCursorStops3["Left"] = 2] = "Left";
  InjectedTextCursorStops3[InjectedTextCursorStops3["None"] = 3] = "None";
})(InjectedTextCursorStops || (InjectedTextCursorStops = {}));
var EndOfLinePreference;
(function(EndOfLinePreference3) {
  EndOfLinePreference3[EndOfLinePreference3["TextDefined"] = 0] = "TextDefined";
  EndOfLinePreference3[EndOfLinePreference3["LF"] = 1] = "LF";
  EndOfLinePreference3[EndOfLinePreference3["CRLF"] = 2] = "CRLF";
})(EndOfLinePreference || (EndOfLinePreference = {}));
var DefaultEndOfLine;
(function(DefaultEndOfLine3) {
  DefaultEndOfLine3[DefaultEndOfLine3["LF"] = 1] = "LF";
  DefaultEndOfLine3[DefaultEndOfLine3["CRLF"] = 2] = "CRLF";
})(DefaultEndOfLine || (DefaultEndOfLine = {}));
var EndOfLineSequence;
(function(EndOfLineSequence3) {
  EndOfLineSequence3[EndOfLineSequence3["LF"] = 0] = "LF";
  EndOfLineSequence3[EndOfLineSequence3["CRLF"] = 1] = "CRLF";
})(EndOfLineSequence || (EndOfLineSequence = {}));
var $dG = class {
  get originalIndentSize() {
    return this.a ? "tabSize" : this.indentSize;
  }
  /**
   * @internal
   */
  constructor(src) {
    this._textModelResolvedOptionsBrand = void 0;
    this.tabSize = Math.max(1, src.tabSize | 0);
    if (src.indentSize === "tabSize") {
      this.indentSize = this.tabSize;
      this.a = true;
    } else {
      this.indentSize = Math.max(1, src.indentSize | 0);
      this.a = false;
    }
    this.insertSpaces = Boolean(src.insertSpaces);
    this.defaultEOL = src.defaultEOL | 0;
    this.trimAutoWhitespace = Boolean(src.trimAutoWhitespace);
    this.bracketPairColorizationOptions = src.bracketPairColorizationOptions;
  }
  /**
   * @internal
   */
  equals(other) {
    return this.tabSize === other.tabSize && this.a === other.a && this.indentSize === other.indentSize && this.insertSpaces === other.insertSpaces && this.defaultEOL === other.defaultEOL && this.trimAutoWhitespace === other.trimAutoWhitespace && $Pv(this.bracketPairColorizationOptions, other.bracketPairColorizationOptions);
  }
  /**
   * @internal
   */
  createChangeEvent(newOpts) {
    return {
      tabSize: this.tabSize !== newOpts.tabSize,
      indentSize: this.indentSize !== newOpts.indentSize,
      insertSpaces: this.insertSpaces !== newOpts.insertSpaces,
      trimAutoWhitespace: this.trimAutoWhitespace !== newOpts.trimAutoWhitespace
    };
  }
};
var $eG = class {
  /**
   * @internal
   */
  constructor(range, matches) {
    this._findMatchBrand = void 0;
    this.range = range;
    this.matches = matches;
  }
};
var TrackedRangeStickiness;
(function(TrackedRangeStickiness3) {
  TrackedRangeStickiness3[TrackedRangeStickiness3["AlwaysGrowsWhenTypingAtEdges"] = 0] = "AlwaysGrowsWhenTypingAtEdges";
  TrackedRangeStickiness3[TrackedRangeStickiness3["NeverGrowsWhenTypingAtEdges"] = 1] = "NeverGrowsWhenTypingAtEdges";
  TrackedRangeStickiness3[TrackedRangeStickiness3["GrowsOnlyWhenTypingBefore"] = 2] = "GrowsOnlyWhenTypingBefore";
  TrackedRangeStickiness3[TrackedRangeStickiness3["GrowsOnlyWhenTypingAfter"] = 3] = "GrowsOnlyWhenTypingAfter";
})(TrackedRangeStickiness || (TrackedRangeStickiness = {}));
function $fG(obj) {
  return obj && typeof obj.read === "function";
}
function $gG(obj) {
  return Boolean(obj && obj.uri);
}
var PositionAffinity;
(function(PositionAffinity3) {
  PositionAffinity3[PositionAffinity3["Left"] = 0] = "Left";
  PositionAffinity3[PositionAffinity3["Right"] = 1] = "Right";
  PositionAffinity3[PositionAffinity3["None"] = 2] = "None";
  PositionAffinity3[PositionAffinity3["LeftOfInjectedText"] = 3] = "LeftOfInjectedText";
  PositionAffinity3[PositionAffinity3["RightOfInjectedText"] = 4] = "RightOfInjectedText";
})(PositionAffinity || (PositionAffinity = {}));
var ModelConstants;
(function(ModelConstants2) {
  ModelConstants2[ModelConstants2["FIRST_LINE_DETECTION_LENGTH_LIMIT"] = 1e3] = "FIRST_LINE_DETECTION_LENGTH_LIMIT";
})(ModelConstants || (ModelConstants = {}));
var $hG = class {
  constructor(identifier2, range, text2, forceMoveMarkers, isAutoWhitespaceEdit, _isTracked) {
    this.identifier = identifier2;
    this.range = range;
    this.text = text2;
    this.forceMoveMarkers = forceMoveMarkers;
    this.isAutoWhitespaceEdit = isAutoWhitespaceEdit;
    this._isTracked = _isTracked;
  }
};
var $iG = class {
  constructor(regex, wordSeparators2, simpleSearch) {
    this.regex = regex;
    this.wordSeparators = wordSeparators2;
    this.simpleSearch = simpleSearch;
  }
};
var $jG = class {
  constructor(reverseEdits, changes, trimAutoWhitespaceLineNumbers) {
    this.reverseEdits = reverseEdits;
    this.changes = changes;
    this.trimAutoWhitespaceLineNumbers = trimAutoWhitespaceLineNumbers;
  }
};
function $kG(model) {
  return !model.isTooLargeForSyncing() && !model.isForSimpleWidget;
}

// out-build/vs/editor/browser/viewParts/glyphMargin/glyphMargin.js
var $p8 = class {
  constructor(startLineNumber, endLineNumber, className, tooltip, zIndex) {
    this.startLineNumber = startLineNumber;
    this.endLineNumber = endLineNumber;
    this.className = className;
    this.tooltip = tooltip;
    this._decorationToRenderBrand = void 0;
    this.zIndex = zIndex ?? 0;
  }
};
var $q8 = class {
  constructor(className, zIndex, tooltip) {
    this.className = className;
    this.zIndex = zIndex;
    this.tooltip = tooltip;
  }
};
var $r8 = class {
  constructor() {
    this.c = [];
  }
  add(decoration3) {
    this.c.push(decoration3);
  }
  getDecorations() {
    return this.c;
  }
};
var $s8 = class extends $d8 {
  /**
   * Returns an array with an element for each visible line number.
   */
  c(visibleStartLineNumber, visibleEndLineNumber, decorations) {
    const output = [];
    for (let lineNumber = visibleStartLineNumber; lineNumber <= visibleEndLineNumber; lineNumber++) {
      const lineIndex = lineNumber - visibleStartLineNumber;
      output[lineIndex] = new $r8();
    }
    if (decorations.length === 0) {
      return output;
    }
    decorations.sort((a, b) => {
      if (a.className === b.className) {
        if (a.startLineNumber === b.startLineNumber) {
          return a.endLineNumber - b.endLineNumber;
        }
        return a.startLineNumber - b.startLineNumber;
      }
      return a.className < b.className ? -1 : 1;
    });
    let prevClassName = null;
    let prevEndLineIndex = 0;
    for (let i2 = 0, len = decorations.length; i2 < len; i2++) {
      const d = decorations[i2];
      const className = d.className;
      const zIndex = d.zIndex;
      let startLineIndex = Math.max(d.startLineNumber, visibleStartLineNumber) - visibleStartLineNumber;
      const endLineIndex = Math.min(d.endLineNumber, visibleEndLineNumber) - visibleStartLineNumber;
      if (prevClassName === className) {
        startLineIndex = Math.max(prevEndLineIndex + 1, startLineIndex);
        prevEndLineIndex = Math.max(prevEndLineIndex, endLineIndex);
      } else {
        prevClassName = className;
        prevEndLineIndex = endLineIndex;
      }
      for (let i3 = startLineIndex; i3 <= prevEndLineIndex; i3++) {
        output[i3].add(new $q8(className, zIndex, d.tooltip));
      }
    }
    return output;
  }
};
var $t8 = class extends $f7 {
  constructor(context) {
    super(context);
    this.t = {};
    this._context = context;
    const options3 = this._context.configuration.options;
    const layoutInfo = options3.get(
      151
      /* EditorOption.layoutInfo */
    );
    this.domNode = $oZ(document.createElement("div"));
    this.domNode.setClassName("glyph-margin-widgets");
    this.domNode.setPosition("absolute");
    this.domNode.setTop(0);
    this.c = options3.get(
      68
      /* EditorOption.lineHeight */
    );
    this.f = options3.get(
      59
      /* EditorOption.glyphMargin */
    );
    this.g = layoutInfo.glyphMarginLeft;
    this.h = layoutInfo.glyphMarginWidth;
    this.j = layoutInfo.glyphMarginDecorationLaneCount;
    this.n = [];
    this.s = [];
  }
  dispose() {
    this.n = [];
    this.s = [];
    this.t = {};
    super.dispose();
  }
  getWidgets() {
    return Object.values(this.t);
  }
  // --- begin event handlers
  onConfigurationChanged(e) {
    const options3 = this._context.configuration.options;
    const layoutInfo = options3.get(
      151
      /* EditorOption.layoutInfo */
    );
    this.c = options3.get(
      68
      /* EditorOption.lineHeight */
    );
    this.f = options3.get(
      59
      /* EditorOption.glyphMargin */
    );
    this.g = layoutInfo.glyphMarginLeft;
    this.h = layoutInfo.glyphMarginWidth;
    this.j = layoutInfo.glyphMarginDecorationLaneCount;
    return true;
  }
  onDecorationsChanged(e) {
    return true;
  }
  onFlushed(e) {
    return true;
  }
  onLinesChanged(e) {
    return true;
  }
  onLinesDeleted(e) {
    return true;
  }
  onLinesInserted(e) {
    return true;
  }
  onScrollChanged(e) {
    return e.scrollTopChanged;
  }
  onZonesChanged(e) {
    return true;
  }
  // --- end event handlers
  // --- begin widget management
  addWidget(widget) {
    const domNode = $oZ(widget.getDomNode());
    this.t[widget.getId()] = {
      widget,
      preference: widget.getPosition(),
      domNode,
      renderInfo: null
    };
    domNode.setPosition("absolute");
    domNode.setDisplay("none");
    domNode.setAttribute("widgetId", widget.getId());
    this.domNode.appendChild(domNode);
    this.u();
  }
  setWidgetPosition(widget, preference) {
    const myWidget = this.t[widget.getId()];
    if (myWidget.preference.lane === preference.lane && myWidget.preference.zIndex === preference.zIndex && $9C.equalsRange(myWidget.preference.range, preference.range)) {
      return false;
    }
    myWidget.preference = preference;
    this.u();
    return true;
  }
  removeWidget(widget) {
    const widgetId = widget.getId();
    if (this.t[widgetId]) {
      const widgetData = this.t[widgetId];
      const domNode = widgetData.domNode.domNode;
      delete this.t[widgetId];
      domNode.remove();
      this.u();
    }
  }
  // --- end widget management
  w(ctx, requests) {
    const visibleStartLineNumber = ctx.visibleRange.startLineNumber;
    const visibleEndLineNumber = ctx.visibleRange.endLineNumber;
    const decorations = ctx.getDecorationsInViewport();
    for (const d of decorations) {
      const glyphMarginClassName = d.options.glyphMarginClassName;
      if (!glyphMarginClassName) {
        continue;
      }
      const startLineNumber = Math.max(d.range.startLineNumber, visibleStartLineNumber);
      const endLineNumber = Math.min(d.range.endLineNumber, visibleEndLineNumber);
      const lane = d.options.glyphMargin?.position ?? GlyphMarginLane.Center;
      const zIndex = d.options.zIndex ?? 0;
      for (let lineNumber = startLineNumber; lineNumber <= endLineNumber; lineNumber++) {
        const modelPosition = this._context.viewModel.coordinatesConverter.convertViewPositionToModelPosition(new $8C(lineNumber, 0));
        const laneIndex = this._context.viewModel.glyphLanes.getLanesAtLine(modelPosition.lineNumber).indexOf(lane);
        requests.push(new DecorationBasedGlyphRenderRequest(lineNumber, laneIndex, zIndex, glyphMarginClassName));
      }
    }
  }
  y(ctx, requests) {
    const visibleStartLineNumber = ctx.visibleRange.startLineNumber;
    const visibleEndLineNumber = ctx.visibleRange.endLineNumber;
    for (const widget of Object.values(this.t)) {
      const range = widget.preference.range;
      const { startLineNumber, endLineNumber } = this._context.viewModel.coordinatesConverter.convertModelRangeToViewRange($9C.lift(range));
      if (!startLineNumber || !endLineNumber || endLineNumber < visibleStartLineNumber || startLineNumber > visibleEndLineNumber) {
        continue;
      }
      const widgetLineNumber = Math.max(startLineNumber, visibleStartLineNumber);
      const modelPosition = this._context.viewModel.coordinatesConverter.convertViewPositionToModelPosition(new $8C(widgetLineNumber, 0));
      const laneIndex = this._context.viewModel.glyphLanes.getLanesAtLine(modelPosition.lineNumber).indexOf(widget.preference.lane);
      requests.push(new WidgetBasedGlyphRenderRequest(widgetLineNumber, laneIndex, widget.preference.zIndex, widget));
    }
  }
  z(ctx) {
    const requests = [];
    this.w(ctx, requests);
    this.y(ctx, requests);
    requests.sort((a, b) => {
      if (a.lineNumber === b.lineNumber) {
        if (a.laneIndex === b.laneIndex) {
          if (a.zIndex === b.zIndex) {
            if (b.type === a.type) {
              if (a.type === 0 && b.type === 0) {
                return a.className < b.className ? -1 : 1;
              }
              return 0;
            }
            return b.type - a.type;
          }
          return b.zIndex - a.zIndex;
        }
        return a.laneIndex - b.laneIndex;
      }
      return a.lineNumber - b.lineNumber;
    });
    return requests;
  }
  /**
   * Will store render information in each widget's renderInfo and in `_decorationGlyphsToRender`.
   */
  prepareRender(ctx) {
    if (!this.f) {
      this.s = [];
      return;
    }
    for (const widget of Object.values(this.t)) {
      widget.renderInfo = null;
    }
    const requests = new $bc(this.z(ctx));
    const decorationGlyphsToRender = [];
    while (requests.length > 0) {
      const first = requests.peek();
      if (!first) {
        break;
      }
      const requestsAtLocation = requests.takeWhile((el) => el.lineNumber === first.lineNumber && el.laneIndex === first.laneIndex);
      if (!requestsAtLocation || requestsAtLocation.length === 0) {
        break;
      }
      const winner = requestsAtLocation[0];
      if (winner.type === 0) {
        const classNames = [];
        for (const request of requestsAtLocation) {
          if (request.zIndex !== winner.zIndex || request.type !== winner.type) {
            break;
          }
          if (classNames.length === 0 || classNames[classNames.length - 1] !== request.className) {
            classNames.push(request.className);
          }
        }
        decorationGlyphsToRender.push(winner.accept(classNames.join(" ")));
      } else {
        winner.widget.renderInfo = {
          lineNumber: winner.lineNumber,
          laneIndex: winner.laneIndex
        };
      }
    }
    this.s = decorationGlyphsToRender;
  }
  render(ctx) {
    if (!this.f) {
      for (const widget of Object.values(this.t)) {
        widget.domNode.setDisplay("none");
      }
      while (this.n.length > 0) {
        const domNode = this.n.pop();
        domNode?.domNode.remove();
      }
      return;
    }
    const width2 = Math.round(this.h / this.j);
    for (const widget of Object.values(this.t)) {
      if (!widget.renderInfo) {
        widget.domNode.setDisplay("none");
      } else {
        const top2 = ctx.viewportData.relativeVerticalOffset[widget.renderInfo.lineNumber - ctx.viewportData.startLineNumber];
        const left = this.g + widget.renderInfo.laneIndex * this.c;
        widget.domNode.setDisplay("block");
        widget.domNode.setTop(top2);
        widget.domNode.setLeft(left);
        widget.domNode.setWidth(width2);
        widget.domNode.setHeight(this.c);
      }
    }
    for (let i2 = 0; i2 < this.s.length; i2++) {
      const dec = this.s[i2];
      const top2 = ctx.viewportData.relativeVerticalOffset[dec.lineNumber - ctx.viewportData.startLineNumber];
      const left = this.g + dec.laneIndex * this.c;
      let domNode;
      if (i2 < this.n.length) {
        domNode = this.n[i2];
      } else {
        domNode = $oZ(document.createElement("div"));
        this.n.push(domNode);
        this.domNode.appendChild(domNode);
      }
      domNode.setClassName(`cgmr codicon ` + dec.combinedClassName);
      domNode.setPosition(`absolute`);
      domNode.setTop(top2);
      domNode.setLeft(left);
      domNode.setWidth(width2);
      domNode.setHeight(this.c);
    }
    while (this.n.length > this.s.length) {
      const domNode = this.n.pop();
      domNode?.domNode.remove();
    }
  }
};
var GlyphRenderRequestType;
(function(GlyphRenderRequestType2) {
  GlyphRenderRequestType2[GlyphRenderRequestType2["Decoration"] = 0] = "Decoration";
  GlyphRenderRequestType2[GlyphRenderRequestType2["Widget"] = 1] = "Widget";
})(GlyphRenderRequestType || (GlyphRenderRequestType = {}));
var DecorationBasedGlyphRenderRequest = class {
  constructor(lineNumber, laneIndex, zIndex, className) {
    this.lineNumber = lineNumber;
    this.laneIndex = laneIndex;
    this.zIndex = zIndex;
    this.className = className;
    this.type = 0;
  }
  accept(combinedClassName) {
    return new DecorationBasedGlyph(this.lineNumber, this.laneIndex, combinedClassName);
  }
};
var WidgetBasedGlyphRenderRequest = class {
  constructor(lineNumber, laneIndex, zIndex, widget) {
    this.lineNumber = lineNumber;
    this.laneIndex = laneIndex;
    this.zIndex = zIndex;
    this.widget = widget;
    this.type = 1;
  }
};
var DecorationBasedGlyph = class {
  constructor(lineNumber, laneIndex, combinedClassName) {
    this.lineNumber = lineNumber;
    this.laneIndex = laneIndex;
    this.combinedClassName = combinedClassName;
  }
};

// out-build/vs/editor/common/model/textModelPart.js
var $UH = class extends $3c {
  constructor() {
    super(...arguments);
    this.f = false;
  }
  dispose() {
    super.dispose();
    this.f = true;
  }
  g() {
    if (this.f) {
      throw new Error("TextModelPart is disposed!");
    }
  }
};

// out-build/vs/editor/common/model/utils.js
function $VH(line, tabSize) {
  let indent = 0;
  let i2 = 0;
  const len = line.length;
  while (i2 < len) {
    const chCode = line.charCodeAt(i2);
    if (chCode === 32) {
      indent++;
    } else if (chCode === 9) {
      indent = indent - indent % tabSize + tabSize;
    } else {
      break;
    }
    i2++;
  }
  if (i2 === len) {
    return -1;
  }
  return indent;
}

// out-build/vs/editor/common/textModelGuides.js
var HorizontalGuidesState;
(function(HorizontalGuidesState2) {
  HorizontalGuidesState2[HorizontalGuidesState2["Disabled"] = 0] = "Disabled";
  HorizontalGuidesState2[HorizontalGuidesState2["EnabledForActive"] = 1] = "EnabledForActive";
  HorizontalGuidesState2[HorizontalGuidesState2["Enabled"] = 2] = "Enabled";
})(HorizontalGuidesState || (HorizontalGuidesState = {}));
var $7F = class {
  constructor(visibleColumn, column, className, horizontalLine, forWrappedLinesAfterColumn, forWrappedLinesBeforeOrAtColumn) {
    this.visibleColumn = visibleColumn;
    this.column = column;
    this.className = className;
    this.horizontalLine = horizontalLine;
    this.forWrappedLinesAfterColumn = forWrappedLinesAfterColumn;
    this.forWrappedLinesBeforeOrAtColumn = forWrappedLinesBeforeOrAtColumn;
    if (visibleColumn !== -1 === (column !== -1)) {
      throw new Error();
    }
  }
};
var $8F = class {
  constructor(top2, endColumn) {
    this.top = top2;
    this.endColumn = endColumn;
  }
};

// out-build/vs/editor/common/model/guidesTextModelPart.js
var $WH = class extends $UH {
  constructor(c, h3) {
    super();
    this.c = c;
    this.h = h3;
  }
  j(languageId) {
    return this.h.getLanguageConfiguration(languageId);
  }
  m(lineIndex) {
    return $VH(this.c.getLineContent(lineIndex + 1), this.c.getOptions().tabSize);
  }
  getActiveIndentGuide(lineNumber, minLineNumber, maxLineNumber) {
    this.g();
    const lineCount = this.c.getLineCount();
    if (lineNumber < 1 || lineNumber > lineCount) {
      throw new $vb("Illegal value for lineNumber");
    }
    const foldingRules = this.j(this.c.getLanguageId()).foldingRules;
    const offSide = Boolean(foldingRules && foldingRules.offSide);
    let up_aboveContentLineIndex = -2;
    let up_aboveContentLineIndent = -1;
    let up_belowContentLineIndex = -2;
    let up_belowContentLineIndent = -1;
    const up_resolveIndents = (lineNumber2) => {
      if (up_aboveContentLineIndex !== -1 && (up_aboveContentLineIndex === -2 || up_aboveContentLineIndex > lineNumber2 - 1)) {
        up_aboveContentLineIndex = -1;
        up_aboveContentLineIndent = -1;
        for (let lineIndex = lineNumber2 - 2; lineIndex >= 0; lineIndex--) {
          const indent2 = this.m(lineIndex);
          if (indent2 >= 0) {
            up_aboveContentLineIndex = lineIndex;
            up_aboveContentLineIndent = indent2;
            break;
          }
        }
      }
      if (up_belowContentLineIndex === -2) {
        up_belowContentLineIndex = -1;
        up_belowContentLineIndent = -1;
        for (let lineIndex = lineNumber2; lineIndex < lineCount; lineIndex++) {
          const indent2 = this.m(lineIndex);
          if (indent2 >= 0) {
            up_belowContentLineIndex = lineIndex;
            up_belowContentLineIndent = indent2;
            break;
          }
        }
      }
    };
    let down_aboveContentLineIndex = -2;
    let down_aboveContentLineIndent = -1;
    let down_belowContentLineIndex = -2;
    let down_belowContentLineIndent = -1;
    const down_resolveIndents = (lineNumber2) => {
      if (down_aboveContentLineIndex === -2) {
        down_aboveContentLineIndex = -1;
        down_aboveContentLineIndent = -1;
        for (let lineIndex = lineNumber2 - 2; lineIndex >= 0; lineIndex--) {
          const indent2 = this.m(lineIndex);
          if (indent2 >= 0) {
            down_aboveContentLineIndex = lineIndex;
            down_aboveContentLineIndent = indent2;
            break;
          }
        }
      }
      if (down_belowContentLineIndex !== -1 && (down_belowContentLineIndex === -2 || down_belowContentLineIndex < lineNumber2 - 1)) {
        down_belowContentLineIndex = -1;
        down_belowContentLineIndent = -1;
        for (let lineIndex = lineNumber2; lineIndex < lineCount; lineIndex++) {
          const indent2 = this.m(lineIndex);
          if (indent2 >= 0) {
            down_belowContentLineIndex = lineIndex;
            down_belowContentLineIndent = indent2;
            break;
          }
        }
      }
    };
    let startLineNumber = 0;
    let goUp = true;
    let endLineNumber = 0;
    let goDown = true;
    let indent = 0;
    let initialIndent = 0;
    for (let distance = 0; goUp || goDown; distance++) {
      const upLineNumber = lineNumber - distance;
      const downLineNumber = lineNumber + distance;
      if (distance > 1 && (upLineNumber < 1 || upLineNumber < minLineNumber)) {
        goUp = false;
      }
      if (distance > 1 && (downLineNumber > lineCount || downLineNumber > maxLineNumber)) {
        goDown = false;
      }
      if (distance > 5e4) {
        goUp = false;
        goDown = false;
      }
      let upLineIndentLevel = -1;
      if (goUp && upLineNumber >= 1) {
        const currentIndent = this.m(upLineNumber - 1);
        if (currentIndent >= 0) {
          up_belowContentLineIndex = upLineNumber - 1;
          up_belowContentLineIndent = currentIndent;
          upLineIndentLevel = Math.ceil(currentIndent / this.c.getOptions().indentSize);
        } else {
          up_resolveIndents(upLineNumber);
          upLineIndentLevel = this.r(offSide, up_aboveContentLineIndent, up_belowContentLineIndent);
        }
      }
      let downLineIndentLevel = -1;
      if (goDown && downLineNumber <= lineCount) {
        const currentIndent = this.m(downLineNumber - 1);
        if (currentIndent >= 0) {
          down_aboveContentLineIndex = downLineNumber - 1;
          down_aboveContentLineIndent = currentIndent;
          downLineIndentLevel = Math.ceil(currentIndent / this.c.getOptions().indentSize);
        } else {
          down_resolveIndents(downLineNumber);
          downLineIndentLevel = this.r(offSide, down_aboveContentLineIndent, down_belowContentLineIndent);
        }
      }
      if (distance === 0) {
        initialIndent = upLineIndentLevel;
        continue;
      }
      if (distance === 1) {
        if (downLineNumber <= lineCount && downLineIndentLevel >= 0 && initialIndent + 1 === downLineIndentLevel) {
          goUp = false;
          startLineNumber = downLineNumber;
          endLineNumber = downLineNumber;
          indent = downLineIndentLevel;
          continue;
        }
        if (upLineNumber >= 1 && upLineIndentLevel >= 0 && upLineIndentLevel - 1 === initialIndent) {
          goDown = false;
          startLineNumber = upLineNumber;
          endLineNumber = upLineNumber;
          indent = upLineIndentLevel;
          continue;
        }
        startLineNumber = lineNumber;
        endLineNumber = lineNumber;
        indent = initialIndent;
        if (indent === 0) {
          return { startLineNumber, endLineNumber, indent };
        }
      }
      if (goUp) {
        if (upLineIndentLevel >= indent) {
          startLineNumber = upLineNumber;
        } else {
          goUp = false;
        }
      }
      if (goDown) {
        if (downLineIndentLevel >= indent) {
          endLineNumber = downLineNumber;
        } else {
          goDown = false;
        }
      }
    }
    return { startLineNumber, endLineNumber, indent };
  }
  getLinesBracketGuides(startLineNumber, endLineNumber, activePosition, options3) {
    const result = [];
    for (let lineNumber = startLineNumber; lineNumber <= endLineNumber; lineNumber++) {
      result.push([]);
    }
    const includeSingleLinePairs = true;
    const bracketPairs = this.c.bracketPairs.getBracketPairsInRangeWithMinIndentation(new $9C(startLineNumber, 1, endLineNumber, this.c.getLineMaxColumn(endLineNumber))).toArray();
    let activeBracketPairRange = void 0;
    if (activePosition && bracketPairs.length > 0) {
      const bracketsContainingActivePosition = (startLineNumber <= activePosition.lineNumber && activePosition.lineNumber <= endLineNumber ? bracketPairs : this.c.bracketPairs.getBracketPairsInRange($9C.fromPositions(activePosition)).toArray()).filter((bp) => $9C.strictContainsPosition(bp.range, activePosition));
      activeBracketPairRange = $1(bracketsContainingActivePosition, (i2) => includeSingleLinePairs || i2.range.startLineNumber !== i2.range.endLineNumber)?.range;
    }
    const independentColorPoolPerBracketType = this.c.getOptions().bracketPairColorizationOptions.independentColorPoolPerBracketType;
    const colorProvider = new $XH();
    for (const pair of bracketPairs) {
      if (!pair.closingBracketRange) {
        continue;
      }
      const isActive2 = activeBracketPairRange && pair.range.equalsRange(activeBracketPairRange);
      if (!isActive2 && !options3.includeInactive) {
        continue;
      }
      const className = colorProvider.getInlineClassName(pair.nestingLevel, pair.nestingLevelOfEqualBracketType, independentColorPoolPerBracketType) + (options3.highlightActive && isActive2 ? " " + colorProvider.activeClassName : "");
      const start = pair.openingBracketRange.getStartPosition();
      const end = pair.closingBracketRange.getStartPosition();
      const horizontalGuides = options3.horizontalGuides === HorizontalGuidesState.Enabled || options3.horizontalGuides === HorizontalGuidesState.EnabledForActive && isActive2;
      if (pair.range.startLineNumber === pair.range.endLineNumber) {
        if (includeSingleLinePairs && horizontalGuides) {
          result[pair.range.startLineNumber - startLineNumber].push(new $7F(-1, pair.openingBracketRange.getEndPosition().column, className, new $8F(false, end.column), -1, -1));
        }
        continue;
      }
      const endVisibleColumn = this.n(end);
      const startVisibleColumn = this.n(pair.openingBracketRange.getStartPosition());
      const guideVisibleColumn = Math.min(startVisibleColumn, endVisibleColumn, pair.minVisibleColumnIndentation + 1);
      let renderHorizontalEndLineAtTheBottom = false;
      const firstNonWsIndex = $Of(this.c.getLineContent(pair.closingBracketRange.startLineNumber));
      const hasTextBeforeClosingBracket = firstNonWsIndex < pair.closingBracketRange.startColumn - 1;
      if (hasTextBeforeClosingBracket) {
        renderHorizontalEndLineAtTheBottom = true;
      }
      const visibleGuideStartLineNumber = Math.max(start.lineNumber, startLineNumber);
      const visibleGuideEndLineNumber = Math.min(end.lineNumber, endLineNumber);
      const offset = renderHorizontalEndLineAtTheBottom ? 1 : 0;
      for (let l = visibleGuideStartLineNumber; l < visibleGuideEndLineNumber + offset; l++) {
        result[l - startLineNumber].push(new $7F(guideVisibleColumn, -1, className, null, l === start.lineNumber ? start.column : -1, l === end.lineNumber ? end.column : -1));
      }
      if (horizontalGuides) {
        if (start.lineNumber >= startLineNumber && startVisibleColumn > guideVisibleColumn) {
          result[start.lineNumber - startLineNumber].push(new $7F(guideVisibleColumn, -1, className, new $8F(false, start.column), -1, -1));
        }
        if (end.lineNumber <= endLineNumber && endVisibleColumn > guideVisibleColumn) {
          result[end.lineNumber - startLineNumber].push(new $7F(guideVisibleColumn, -1, className, new $8F(!renderHorizontalEndLineAtTheBottom, end.column), -1, -1));
        }
      }
    }
    for (const guides of result) {
      guides.sort((a, b) => a.visibleColumn - b.visibleColumn);
    }
    return result;
  }
  n(position) {
    return $cF.visibleColumnFromColumn(this.c.getLineContent(position.lineNumber), position.column, this.c.getOptions().tabSize) + 1;
  }
  getLinesIndentGuides(startLineNumber, endLineNumber) {
    this.g();
    const lineCount = this.c.getLineCount();
    if (startLineNumber < 1 || startLineNumber > lineCount) {
      throw new Error("Illegal value for startLineNumber");
    }
    if (endLineNumber < 1 || endLineNumber > lineCount) {
      throw new Error("Illegal value for endLineNumber");
    }
    const options3 = this.c.getOptions();
    const foldingRules = this.j(this.c.getLanguageId()).foldingRules;
    const offSide = Boolean(foldingRules && foldingRules.offSide);
    const result = new Array(endLineNumber - startLineNumber + 1);
    let aboveContentLineIndex = -2;
    let aboveContentLineIndent = -1;
    let belowContentLineIndex = -2;
    let belowContentLineIndent = -1;
    for (let lineNumber = startLineNumber; lineNumber <= endLineNumber; lineNumber++) {
      const resultIndex = lineNumber - startLineNumber;
      const currentIndent = this.m(lineNumber - 1);
      if (currentIndent >= 0) {
        aboveContentLineIndex = lineNumber - 1;
        aboveContentLineIndent = currentIndent;
        result[resultIndex] = Math.ceil(currentIndent / options3.indentSize);
        continue;
      }
      if (aboveContentLineIndex === -2) {
        aboveContentLineIndex = -1;
        aboveContentLineIndent = -1;
        for (let lineIndex = lineNumber - 2; lineIndex >= 0; lineIndex--) {
          const indent = this.m(lineIndex);
          if (indent >= 0) {
            aboveContentLineIndex = lineIndex;
            aboveContentLineIndent = indent;
            break;
          }
        }
      }
      if (belowContentLineIndex !== -1 && (belowContentLineIndex === -2 || belowContentLineIndex < lineNumber - 1)) {
        belowContentLineIndex = -1;
        belowContentLineIndent = -1;
        for (let lineIndex = lineNumber; lineIndex < lineCount; lineIndex++) {
          const indent = this.m(lineIndex);
          if (indent >= 0) {
            belowContentLineIndex = lineIndex;
            belowContentLineIndent = indent;
            break;
          }
        }
      }
      result[resultIndex] = this.r(offSide, aboveContentLineIndent, belowContentLineIndent);
    }
    return result;
  }
  r(offSide, aboveContentLineIndent, belowContentLineIndent) {
    const options3 = this.c.getOptions();
    if (aboveContentLineIndent === -1 || belowContentLineIndent === -1) {
      return 0;
    } else if (aboveContentLineIndent < belowContentLineIndent) {
      return 1 + Math.floor(aboveContentLineIndent / options3.indentSize);
    } else if (aboveContentLineIndent === belowContentLineIndent) {
      return Math.ceil(belowContentLineIndent / options3.indentSize);
    } else {
      if (offSide) {
        return Math.ceil(belowContentLineIndent / options3.indentSize);
      } else {
        return 1 + Math.floor(belowContentLineIndent / options3.indentSize);
      }
    }
  }
};
var $XH = class {
  constructor() {
    this.activeClassName = "indent-active";
  }
  getInlineClassName(nestingLevel, nestingLevelOfEqualBracketType, independentColorPoolPerBracketType) {
    return this.getInlineClassNameOfLevel(independentColorPoolPerBracketType ? nestingLevelOfEqualBracketType : nestingLevel);
  }
  getInlineClassNameOfLevel(level) {
    return `bracket-indent-guide lvl-${level % 30}`;
  }
};

// out-build/vs/editor/browser/viewParts/indentGuides/indentGuides.js
var $u8 = class extends $d8 {
  constructor(context) {
    super();
    this.a = context;
    this.b = null;
    const options3 = this.a.configuration.options;
    const wrappingInfo = options3.get(
      152
      /* EditorOption.wrappingInfo */
    );
    const fontInfo = options3.get(
      52
      /* EditorOption.fontInfo */
    );
    this.f = fontInfo.spaceWidth;
    this.j = wrappingInfo.wrappingColumn === -1 ? -1 : wrappingInfo.wrappingColumn * fontInfo.typicalHalfwidthCharacterWidth;
    this.n = options3.get(
      16
      /* EditorOption.guides */
    );
    this.h = null;
    this.a.addEventHandler(this);
  }
  dispose() {
    this.a.removeEventHandler(this);
    this.h = null;
    super.dispose();
  }
  // --- begin event handlers
  onConfigurationChanged(e) {
    const options3 = this.a.configuration.options;
    const wrappingInfo = options3.get(
      152
      /* EditorOption.wrappingInfo */
    );
    const fontInfo = options3.get(
      52
      /* EditorOption.fontInfo */
    );
    this.f = fontInfo.spaceWidth;
    this.j = wrappingInfo.wrappingColumn === -1 ? -1 : wrappingInfo.wrappingColumn * fontInfo.typicalHalfwidthCharacterWidth;
    this.n = options3.get(
      16
      /* EditorOption.guides */
    );
    return true;
  }
  onCursorStateChanged(e) {
    const selection = e.selections[0];
    const newPosition = selection.getPosition();
    if (!this.b?.equals(newPosition)) {
      this.b = newPosition;
      return true;
    }
    return false;
  }
  onDecorationsChanged(e) {
    return true;
  }
  onFlushed(e) {
    return true;
  }
  onLinesChanged(e) {
    return true;
  }
  onLinesDeleted(e) {
    return true;
  }
  onLinesInserted(e) {
    return true;
  }
  onScrollChanged(e) {
    return e.scrollTopChanged;
  }
  onZonesChanged(e) {
    return true;
  }
  onLanguageConfigurationChanged(e) {
    return true;
  }
  // --- end event handlers
  prepareRender(ctx) {
    if (!this.n.indentation && this.n.bracketPairs === false) {
      this.h = null;
      return;
    }
    const visibleStartLineNumber = ctx.visibleRange.startLineNumber;
    const visibleEndLineNumber = ctx.visibleRange.endLineNumber;
    const scrollWidth = ctx.scrollWidth;
    const activeCursorPosition = this.b;
    const indents = this.r(visibleStartLineNumber, Math.min(visibleEndLineNumber + 1, this.a.viewModel.getLineCount()), activeCursorPosition);
    const output = [];
    for (let lineNumber = visibleStartLineNumber; lineNumber <= visibleEndLineNumber; lineNumber++) {
      const lineIndex = lineNumber - visibleStartLineNumber;
      const indent = indents[lineIndex];
      let result = "";
      const leftOffset = ctx.visibleRangeForPosition(new $8C(lineNumber, 1))?.left ?? 0;
      for (const guide of indent) {
        const left = guide.column === -1 ? leftOffset + (guide.visibleColumn - 1) * this.f : ctx.visibleRangeForPosition(new $8C(lineNumber, guide.column)).left;
        if (left > scrollWidth || this.j > 0 && left > this.j) {
          break;
        }
        const className = guide.horizontalLine ? guide.horizontalLine.top ? "horizontal-top" : "horizontal-bottom" : "vertical";
        const width2 = guide.horizontalLine ? (ctx.visibleRangeForPosition(new $8C(lineNumber, guide.horizontalLine.endColumn))?.left ?? left + this.f) - left : this.f;
        result += `<div class="core-guide ${guide.className} ${className}" style="left:${left}px;width:${width2}px"></div>`;
      }
      output[lineIndex] = result;
    }
    this.h = output;
  }
  r(visibleStartLineNumber, visibleEndLineNumber, activeCursorPosition) {
    const bracketGuides = this.n.bracketPairs !== false ? this.a.viewModel.getBracketGuidesInRangeByLine(visibleStartLineNumber, visibleEndLineNumber, activeCursorPosition, {
      highlightActive: this.n.highlightActiveBracketPair,
      horizontalGuides: this.n.bracketPairsHorizontal === true ? HorizontalGuidesState.Enabled : this.n.bracketPairsHorizontal === "active" ? HorizontalGuidesState.EnabledForActive : HorizontalGuidesState.Disabled,
      includeInactive: this.n.bracketPairs === true
    }) : null;
    const indentGuides = this.n.indentation ? this.a.viewModel.getLinesIndentGuides(visibleStartLineNumber, visibleEndLineNumber) : null;
    let activeIndentStartLineNumber = 0;
    let activeIndentEndLineNumber = 0;
    let activeIndentLevel = 0;
    if (this.n.highlightActiveIndentation !== false && activeCursorPosition) {
      const activeIndentInfo = this.a.viewModel.getActiveIndentGuide(activeCursorPosition.lineNumber, visibleStartLineNumber, visibleEndLineNumber);
      activeIndentStartLineNumber = activeIndentInfo.startLineNumber;
      activeIndentEndLineNumber = activeIndentInfo.endLineNumber;
      activeIndentLevel = activeIndentInfo.indent;
    }
    const { indentSize } = this.a.viewModel.model.getOptions();
    const result = [];
    for (let lineNumber = visibleStartLineNumber; lineNumber <= visibleEndLineNumber; lineNumber++) {
      const lineGuides = new Array();
      result.push(lineGuides);
      const bracketGuidesInLine = bracketGuides ? bracketGuides[lineNumber - visibleStartLineNumber] : [];
      const bracketGuidesInLineQueue = new $bc(bracketGuidesInLine);
      const indentGuidesInLine = indentGuides ? indentGuides[lineNumber - visibleStartLineNumber] : 0;
      for (let indentLvl = 1; indentLvl <= indentGuidesInLine; indentLvl++) {
        const indentGuide = (indentLvl - 1) * indentSize + 1;
        const isActive2 = (
          // Disable active indent guide if there are bracket guides.
          (this.n.highlightActiveIndentation === "always" || bracketGuidesInLine.length === 0) && activeIndentStartLineNumber <= lineNumber && lineNumber <= activeIndentEndLineNumber && indentLvl === activeIndentLevel
        );
        lineGuides.push(...bracketGuidesInLineQueue.takeWhile((g) => g.visibleColumn < indentGuide) || []);
        const peeked = bracketGuidesInLineQueue.peek();
        if (!peeked || peeked.visibleColumn !== indentGuide || peeked.horizontalLine) {
          lineGuides.push(new $7F(indentGuide, -1, `core-guide-indent lvl-${(indentLvl - 1) % 30}` + (isActive2 ? " indent-active" : ""), null, -1, -1));
        }
      }
      lineGuides.push(...bracketGuidesInLineQueue.takeWhile((g) => true) || []);
    }
    return result;
  }
  render(startLineNumber, lineNumber) {
    if (!this.h) {
      return "";
    }
    const lineIndex = lineNumber - startLineNumber;
    if (lineIndex < 0 || lineIndex >= this.h.length) {
      return "";
    }
    return this.h[lineIndex];
  }
};
function transparentToUndefined(color2) {
  if (color2 && color2.isTransparent()) {
    return void 0;
  }
  return color2;
}
$ms((theme, collector) => {
  const colors = [
    { bracketColor: $tH, guideColor: $AH, guideColorActive: $GH },
    { bracketColor: $uH, guideColor: $BH, guideColorActive: $HH },
    { bracketColor: $vH, guideColor: $CH, guideColorActive: $IH },
    { bracketColor: $wH, guideColor: $DH, guideColorActive: $JH },
    { bracketColor: $xH, guideColor: $EH, guideColorActive: $KH },
    { bracketColor: $yH, guideColor: $FH, guideColorActive: $LH }
  ];
  const colorProvider = new $XH();
  const indentColors = [
    { indentColor: $2G, indentColorActive: $8G },
    { indentColor: $3G, indentColorActive: $9G },
    { indentColor: $4G, indentColorActive: $0G },
    { indentColor: $5G, indentColorActive: $$G },
    { indentColor: $6G, indentColorActive: $_G },
    { indentColor: $7G, indentColorActive: $aH }
  ];
  const colorValues = colors.map((c) => {
    const bracketColor = theme.getColor(c.bracketColor);
    const guideColor = theme.getColor(c.guideColor);
    const guideColorActive = theme.getColor(c.guideColorActive);
    const effectiveGuideColor = transparentToUndefined(transparentToUndefined(guideColor) ?? bracketColor?.transparent(0.3));
    const effectiveGuideColorActive = transparentToUndefined(transparentToUndefined(guideColorActive) ?? bracketColor);
    if (!effectiveGuideColor || !effectiveGuideColorActive) {
      return void 0;
    }
    return {
      guideColor: effectiveGuideColor,
      guideColorActive: effectiveGuideColorActive
    };
  }).filter($Hg);
  const indentColorValues = indentColors.map((c) => {
    const indentColor = theme.getColor(c.indentColor);
    const indentColorActive = theme.getColor(c.indentColorActive);
    const effectiveIndentColor = transparentToUndefined(indentColor);
    const effectiveIndentColorActive = transparentToUndefined(indentColorActive);
    if (!effectiveIndentColor || !effectiveIndentColorActive) {
      return void 0;
    }
    return {
      indentColor: effectiveIndentColor,
      indentColorActive: effectiveIndentColorActive
    };
  }).filter($Hg);
  if (colorValues.length > 0) {
    for (let level = 0; level < 30; level++) {
      const colors2 = colorValues[level % colorValues.length];
      collector.addRule(`.monaco-editor .${colorProvider.getInlineClassNameOfLevel(level).replace(/ /g, ".")} { --guide-color: ${colors2.guideColor}; --guide-color-active: ${colors2.guideColorActive}; }`);
    }
    collector.addRule(`.monaco-editor .vertical { box-shadow: 1px 0 0 0 var(--guide-color) inset; }`);
    collector.addRule(`.monaco-editor .horizontal-top { border-top: 1px solid var(--guide-color); }`);
    collector.addRule(`.monaco-editor .horizontal-bottom { border-bottom: 1px solid var(--guide-color); }`);
    collector.addRule(`.monaco-editor .vertical.${colorProvider.activeClassName} { box-shadow: 1px 0 0 0 var(--guide-color-active) inset; }`);
    collector.addRule(`.monaco-editor .horizontal-top.${colorProvider.activeClassName} { border-top: 1px solid var(--guide-color-active); }`);
    collector.addRule(`.monaco-editor .horizontal-bottom.${colorProvider.activeClassName} { border-bottom: 1px solid var(--guide-color-active); }`);
  }
  if (indentColorValues.length > 0) {
    for (let level = 0; level < 30; level++) {
      const colors2 = indentColorValues[level % indentColorValues.length];
      collector.addRule(`.monaco-editor .lines-content .core-guide-indent.lvl-${level} { --indent-color: ${colors2.indentColor}; --indent-color-active: ${colors2.indentColorActive}; }`);
    }
    collector.addRule(`.monaco-editor .lines-content .core-guide-indent { box-shadow: 1px 0 0 0 var(--indent-color) inset; }`);
    collector.addRule(`.monaco-editor .lines-content .core-guide-indent.indent-active { box-shadow: 1px 0 0 0 var(--indent-color-active) inset; }`);
  }
});

// out-build/vs/editor/browser/viewParts/lineNumbers/lineNumbers.js
var $v8 = class _$v8 extends $d8 {
  static {
    this.CLASS_NAME = "line-numbers";
  }
  constructor(context) {
    super();
    this.c = context;
    this.y();
    this.s = new $8C(1, 1);
    this.t = null;
    this.w = 1;
    this.c.addEventHandler(this);
  }
  y() {
    const options3 = this.c.configuration.options;
    this.f = options3.get(
      68
      /* EditorOption.lineHeight */
    );
    const lineNumbers = options3.get(
      69
      /* EditorOption.lineNumbers */
    );
    this.g = lineNumbers.renderType;
    this.h = lineNumbers.renderFn;
    this.j = options3.get(
      100
      /* EditorOption.renderFinalNewline */
    );
    const layoutInfo = options3.get(
      151
      /* EditorOption.layoutInfo */
    );
    this.n = layoutInfo.lineNumbersLeft;
    this.r = layoutInfo.lineNumbersWidth;
  }
  dispose() {
    this.c.removeEventHandler(this);
    this.t = null;
    super.dispose();
  }
  // --- begin event handlers
  onConfigurationChanged(e) {
    this.y();
    return true;
  }
  onCursorStateChanged(e) {
    const primaryViewPosition = e.selections[0].getPosition();
    this.s = this.c.viewModel.coordinatesConverter.convertViewPositionToModelPosition(primaryViewPosition);
    let shouldRender = false;
    if (this.w !== primaryViewPosition.lineNumber) {
      this.w = primaryViewPosition.lineNumber;
      shouldRender = true;
    }
    if (this.g === 2 || this.g === 3) {
      shouldRender = true;
    }
    return shouldRender;
  }
  onFlushed(e) {
    return true;
  }
  onLinesChanged(e) {
    return true;
  }
  onLinesDeleted(e) {
    return true;
  }
  onLinesInserted(e) {
    return true;
  }
  onScrollChanged(e) {
    return e.scrollTopChanged;
  }
  onZonesChanged(e) {
    return true;
  }
  onDecorationsChanged(e) {
    return e.affectsLineNumber;
  }
  // --- end event handlers
  z(viewLineNumber) {
    const modelPosition = this.c.viewModel.coordinatesConverter.convertViewPositionToModelPosition(new $8C(viewLineNumber, 1));
    if (modelPosition.column !== 1) {
      return "";
    }
    const modelLineNumber = modelPosition.lineNumber;
    if (this.h) {
      return this.h(modelLineNumber);
    }
    if (this.g === 2) {
      const diff3 = Math.abs(this.s.lineNumber - modelLineNumber);
      if (diff3 === 0) {
        return '<span class="relative-current-line-number">' + modelLineNumber + "</span>";
      }
      return String(diff3);
    }
    if (this.g === 3) {
      if (this.s.lineNumber === modelLineNumber) {
        return String(modelLineNumber);
      }
      if (modelLineNumber % 10 === 0) {
        return String(modelLineNumber);
      }
      const finalLineNumber = this.c.viewModel.getLineCount();
      if (modelLineNumber === finalLineNumber) {
        return String(modelLineNumber);
      }
      return "";
    }
    return String(modelLineNumber);
  }
  prepareRender(ctx) {
    if (this.g === 0) {
      this.t = null;
      return;
    }
    const lineHeightClassName = $n ? this.f % 2 === 0 ? " lh-even" : " lh-odd" : "";
    const visibleStartLineNumber = ctx.visibleRange.startLineNumber;
    const visibleEndLineNumber = ctx.visibleRange.endLineNumber;
    const lineNoDecorations = this.c.viewModel.getDecorationsInViewport(ctx.visibleRange).filter((d) => !!d.options.lineNumberClassName);
    lineNoDecorations.sort((a, b) => $9C.compareRangesUsingEnds(a.range, b.range));
    let decorationStartIndex = 0;
    const lineCount = this.c.viewModel.getLineCount();
    const output = [];
    for (let lineNumber = visibleStartLineNumber; lineNumber <= visibleEndLineNumber; lineNumber++) {
      const lineIndex = lineNumber - visibleStartLineNumber;
      let renderLineNumber = this.z(lineNumber);
      let extraClassNames = "";
      while (decorationStartIndex < lineNoDecorations.length && lineNoDecorations[decorationStartIndex].range.endLineNumber < lineNumber) {
        decorationStartIndex++;
      }
      for (let i2 = decorationStartIndex; i2 < lineNoDecorations.length; i2++) {
        const { range, options: options3 } = lineNoDecorations[i2];
        if (range.startLineNumber <= lineNumber) {
          extraClassNames += " " + options3.lineNumberClassName;
        }
      }
      if (!renderLineNumber && !extraClassNames) {
        output[lineIndex] = "";
        continue;
      }
      if (lineNumber === lineCount && this.c.viewModel.getLineLength(lineNumber) === 0) {
        if (this.j === "off") {
          renderLineNumber = "";
        }
        if (this.j === "dimmed") {
          extraClassNames += " dimmed-line-number";
        }
      }
      if (lineNumber === this.w) {
        extraClassNames += " active-line-number";
      }
      output[lineIndex] = `<div class="${_$v8.CLASS_NAME}${lineHeightClassName}${extraClassNames}" style="left:${this.n}px;width:${this.r}px;">${renderLineNumber}</div>`;
    }
    this.t = output;
  }
  render(startLineNumber, lineNumber) {
    if (!this.t) {
      return "";
    }
    const lineIndex = lineNumber - startLineNumber;
    if (lineIndex < 0 || lineIndex >= this.t.length) {
      return "";
    }
    return this.t[lineIndex];
  }
};
$ms((theme, collector) => {
  const editorLineNumbersColor = theme.getColor($YG);
  const editorDimmedLineNumberColor = theme.getColor($cH);
  if (editorDimmedLineNumberColor) {
    collector.addRule(`.monaco-editor .line-numbers.dimmed-line-number { color: ${editorDimmedLineNumberColor}; }`);
  } else if (editorLineNumbersColor) {
    collector.addRule(`.monaco-editor .line-numbers.dimmed-line-number { color: ${editorLineNumbersColor.transparent(0.4)}; }`);
  }
});

// out-build/vs/base/browser/ui/mouseCursor/mouseCursor.js
var $62 = `monaco-mouse-cursor-text`;

// out-build/vs/editor/browser/viewParts/viewLines/domReadingContext.js
var $j7 = class {
  get didDomLayout() {
    return this.a;
  }
  e() {
    if (!this.d) {
      this.d = true;
      const rect = this.f.getBoundingClientRect();
      this.markDidDomLayout();
      this.b = rect.left;
      this.c = rect.width / this.f.offsetWidth;
    }
  }
  get clientRectDeltaLeft() {
    if (!this.d) {
      this.e();
    }
    return this.b;
  }
  get clientRectScale() {
    if (!this.d) {
      this.e();
    }
    return this.c;
  }
  constructor(f, endNode) {
    this.f = f;
    this.endNode = endNode;
    this.a = false;
    this.b = 0;
    this.c = 1;
    this.d = false;
  }
  markDidDomLayout() {
    this.a = true;
  }
};

// out-build/vs/editor/browser/viewParts/viewLines/viewLineOptions.js
var $x7 = class {
  constructor(config, themeType) {
    this.themeType = themeType;
    const options3 = config.options;
    const fontInfo = options3.get(
      52
      /* EditorOption.fontInfo */
    );
    const experimentalWhitespaceRendering = options3.get(
      40
      /* EditorOption.experimentalWhitespaceRendering */
    );
    if (experimentalWhitespaceRendering === "off") {
      this.renderWhitespace = options3.get(
        104
        /* EditorOption.renderWhitespace */
      );
    } else {
      this.renderWhitespace = "none";
    }
    this.renderControlCharacters = options3.get(
      99
      /* EditorOption.renderControlCharacters */
    );
    this.spaceWidth = fontInfo.spaceWidth;
    this.middotWidth = fontInfo.middotWidth;
    this.wsmiddotWidth = fontInfo.wsmiddotWidth;
    this.useMonospaceOptimizations = fontInfo.isMonospace && !options3.get(
      33
      /* EditorOption.disableMonospaceOptimizations */
    );
    this.canUseHalfwidthRightwardsArrow = fontInfo.canUseHalfwidthRightwardsArrow;
    this.lineHeight = options3.get(
      68
      /* EditorOption.lineHeight */
    );
    this.stopRenderingLineAfter = options3.get(
      122
      /* EditorOption.stopRenderingLineAfter */
    );
    this.fontLigatures = options3.get(
      53
      /* EditorOption.fontLigatures */
    );
    this.useGpu = options3.get(
      39
      /* EditorOption.experimentalGpuAcceleration */
    ) === "on";
  }
  equals(other) {
    return this.themeType === other.themeType && this.renderWhitespace === other.renderWhitespace && this.renderControlCharacters === other.renderControlCharacters && this.spaceWidth === other.spaceWidth && this.middotWidth === other.middotWidth && this.wsmiddotWidth === other.wsmiddotWidth && this.useMonospaceOptimizations === other.useMonospaceOptimizations && this.canUseHalfwidthRightwardsArrow === other.canUseHalfwidthRightwardsArrow && this.lineHeight === other.lineHeight && this.stopRenderingLineAfter === other.stopRenderingLineAfter && this.fontLigatures === other.fontLigatures && this.useGpu === other.useGpu;
  }
};

// out-build/vs/editor/browser/viewParts/viewLines/viewLines.js
var LastRenderedData = class {
  constructor() {
    this.a = new $9C(1, 1, 1, 1);
  }
  getCurrentVisibleRange() {
    return this.a;
  }
  setCurrentVisibleRange(currentVisibleRange) {
    this.a = currentVisibleRange;
  }
};
var HorizontalRevealRangeRequest = class {
  constructor(minimalReveal, lineNumber, startColumn, endColumn, startScrollTop, stopScrollTop, scrollType) {
    this.minimalReveal = minimalReveal;
    this.lineNumber = lineNumber;
    this.startColumn = startColumn;
    this.endColumn = endColumn;
    this.startScrollTop = startScrollTop;
    this.stopScrollTop = stopScrollTop;
    this.scrollType = scrollType;
    this.type = "range";
    this.minLineNumber = lineNumber;
    this.maxLineNumber = lineNumber;
  }
};
var HorizontalRevealSelectionsRequest = class {
  constructor(minimalReveal, selections, startScrollTop, stopScrollTop, scrollType) {
    this.minimalReveal = minimalReveal;
    this.selections = selections;
    this.startScrollTop = startScrollTop;
    this.stopScrollTop = stopScrollTop;
    this.scrollType = scrollType;
    this.type = "selections";
    let minLineNumber = selections[0].startLineNumber;
    let maxLineNumber = selections[0].endLineNumber;
    for (let i2 = 1, len = selections.length; i2 < len; i2++) {
      const selection = selections[i2];
      minLineNumber = Math.min(minLineNumber, selection.startLineNumber);
      maxLineNumber = Math.max(maxLineNumber, selection.endLineNumber);
    }
    this.minLineNumber = minLineNumber;
    this.maxLineNumber = maxLineNumber;
  }
};
var $w8 = class _$w8 extends $f7 {
  static {
    this.a = 30;
  }
  constructor(context, viewGpuContext, linesContent) {
    super(context);
    const conf = this._context.configuration;
    const options3 = this._context.configuration.options;
    const fontInfo = options3.get(
      52
      /* EditorOption.fontInfo */
    );
    const wrappingInfo = options3.get(
      152
      /* EditorOption.wrappingInfo */
    );
    this.h = options3.get(
      68
      /* EditorOption.lineHeight */
    );
    this.j = fontInfo.typicalHalfwidthCharacterWidth;
    this.n = wrappingInfo.isViewportWrapping;
    this.s = options3.get(
      105
      /* EditorOption.revealHorizontalRightPadding */
    );
    this.t = options3.get(
      29
      /* EditorOption.cursorSurroundingLines */
    );
    this.w = options3.get(
      30
      /* EditorOption.cursorSurroundingLinesStyle */
    );
    this.y = !options3.get(
      32
      /* EditorOption.disableLayerHinting */
    );
    this.z = new $x7(conf, this._context.theme.type);
    this.b = linesContent;
    this.c = document.createElement("div");
    this.f = new $i7({
      createLine: () => new $P7(viewGpuContext, this.z)
    });
    this.g = this.f.domNode;
    $g7.write(
      this.g,
      8
      /* PartFingerprint.ViewLines */
    );
    this.g.setClassName(`view-lines ${$62}`);
    $24(this.g, fontInfo);
    this.C = 0;
    this.D = new $8h(() => {
      this.Q();
    }, 200);
    this.F = new $8h(() => {
      this.U();
    }, 2e3);
    this.H = new LastRenderedData();
    this.G = null;
    this.I = options3.get(
      120
      /* EditorOption.stickyScroll */
    ).enabled;
    this.J = options3.get(
      120
      /* EditorOption.stickyScroll */
    ).maxLineCount;
  }
  dispose() {
    this.D.dispose();
    this.F.dispose();
    super.dispose();
  }
  getDomNode() {
    return this.g;
  }
  // ---- begin view event handlers
  onConfigurationChanged(e) {
    this.f.onConfigurationChanged(e);
    if (e.hasChanged(
      152
      /* EditorOption.wrappingInfo */
    )) {
      this.C = 0;
    }
    const options3 = this._context.configuration.options;
    const fontInfo = options3.get(
      52
      /* EditorOption.fontInfo */
    );
    const wrappingInfo = options3.get(
      152
      /* EditorOption.wrappingInfo */
    );
    this.h = options3.get(
      68
      /* EditorOption.lineHeight */
    );
    this.j = fontInfo.typicalHalfwidthCharacterWidth;
    this.n = wrappingInfo.isViewportWrapping;
    this.s = options3.get(
      105
      /* EditorOption.revealHorizontalRightPadding */
    );
    this.t = options3.get(
      29
      /* EditorOption.cursorSurroundingLines */
    );
    this.w = options3.get(
      30
      /* EditorOption.cursorSurroundingLinesStyle */
    );
    this.y = !options3.get(
      32
      /* EditorOption.disableLayerHinting */
    );
    this.I = options3.get(
      120
      /* EditorOption.stickyScroll */
    ).enabled;
    this.J = options3.get(
      120
      /* EditorOption.stickyScroll */
    ).maxLineCount;
    $24(this.g, fontInfo);
    this.L();
    if (e.hasChanged(
      151
      /* EditorOption.layoutInfo */
    )) {
      this.C = 0;
    }
    return true;
  }
  L() {
    const conf = this._context.configuration;
    const newViewLineOptions = new $x7(conf, this._context.theme.type);
    if (!this.z.equals(newViewLineOptions)) {
      this.z = newViewLineOptions;
      const startLineNumber = this.f.getStartLineNumber();
      const endLineNumber = this.f.getEndLineNumber();
      for (let lineNumber = startLineNumber; lineNumber <= endLineNumber; lineNumber++) {
        const line = this.f.getVisibleLine(lineNumber);
        line.onOptionsChanged(this.z);
      }
      return true;
    }
    return false;
  }
  onCursorStateChanged(e) {
    const rendStartLineNumber = this.f.getStartLineNumber();
    const rendEndLineNumber = this.f.getEndLineNumber();
    let r2 = false;
    for (let lineNumber = rendStartLineNumber; lineNumber <= rendEndLineNumber; lineNumber++) {
      r2 = this.f.getVisibleLine(lineNumber).onSelectionChanged() || r2;
    }
    return r2;
  }
  onDecorationsChanged(e) {
    if (true) {
      const rendStartLineNumber = this.f.getStartLineNumber();
      const rendEndLineNumber = this.f.getEndLineNumber();
      for (let lineNumber = rendStartLineNumber; lineNumber <= rendEndLineNumber; lineNumber++) {
        this.f.getVisibleLine(lineNumber).onDecorationsChanged();
      }
    }
    return true;
  }
  onFlushed(e) {
    const shouldRender = this.f.onFlushed(e);
    this.C = 0;
    return shouldRender;
  }
  onLinesChanged(e) {
    return this.f.onLinesChanged(e);
  }
  onLinesDeleted(e) {
    return this.f.onLinesDeleted(e);
  }
  onLinesInserted(e) {
    return this.f.onLinesInserted(e);
  }
  onRevealRangeRequest(e) {
    const desiredScrollTop = this.X(this._context.viewLayout.getFutureViewport(), e.source, e.minimalReveal, e.range, e.selections, e.verticalType);
    if (desiredScrollTop === -1) {
      return false;
    }
    let newScrollPosition = this._context.viewLayout.validateScrollPosition({ scrollTop: desiredScrollTop });
    if (e.revealHorizontal) {
      if (e.range && e.range.startLineNumber !== e.range.endLineNumber) {
        newScrollPosition = {
          scrollTop: newScrollPosition.scrollTop,
          scrollLeft: 0
        };
      } else if (e.range) {
        this.G = new HorizontalRevealRangeRequest(e.minimalReveal, e.range.startLineNumber, e.range.startColumn, e.range.endColumn, this._context.viewLayout.getCurrentScrollTop(), newScrollPosition.scrollTop, e.scrollType);
      } else if (e.selections && e.selections.length > 0) {
        this.G = new HorizontalRevealSelectionsRequest(e.minimalReveal, e.selections, this._context.viewLayout.getCurrentScrollTop(), newScrollPosition.scrollTop, e.scrollType);
      }
    } else {
      this.G = null;
    }
    const scrollTopDelta = Math.abs(this._context.viewLayout.getCurrentScrollTop() - newScrollPosition.scrollTop);
    const scrollType = scrollTopDelta <= this.h ? 1 : e.scrollType;
    this._context.viewModel.viewLayout.setScrollPosition(newScrollPosition, scrollType);
    return true;
  }
  onScrollChanged(e) {
    if (this.G && e.scrollLeftChanged) {
      this.G = null;
    }
    if (this.G && e.scrollTopChanged) {
      const min = Math.min(this.G.startScrollTop, this.G.stopScrollTop);
      const max = Math.max(this.G.startScrollTop, this.G.stopScrollTop);
      if (e.scrollTop < min || e.scrollTop > max) {
        this.G = null;
      }
    }
    this.g.setWidth(e.scrollWidth);
    return this.f.onScrollChanged(e) || true;
  }
  onTokensChanged(e) {
    return this.f.onTokensChanged(e);
  }
  onZonesChanged(e) {
    this._context.viewModel.viewLayout.setMaxLineWidth(this.C);
    return this.f.onZonesChanged(e);
  }
  onThemeChanged(e) {
    return this.L();
  }
  // ---- end view event handlers
  // ----------- HELPERS FOR OTHERS
  getPositionFromDOMInfo(spanNode, offset) {
    const viewLineDomNode = this.M(spanNode);
    if (viewLineDomNode === null) {
      return null;
    }
    const lineNumber = this.N(viewLineDomNode);
    if (lineNumber === -1) {
      return null;
    }
    if (lineNumber < 1 || lineNumber > this._context.viewModel.getLineCount()) {
      return null;
    }
    if (this._context.viewModel.getLineMaxColumn(lineNumber) === 1) {
      return new $8C(lineNumber, 1);
    }
    const rendStartLineNumber = this.f.getStartLineNumber();
    const rendEndLineNumber = this.f.getEndLineNumber();
    if (lineNumber < rendStartLineNumber || lineNumber > rendEndLineNumber) {
      return null;
    }
    let column = this.f.getVisibleLine(lineNumber).getColumnOfNodeOffset(spanNode, offset);
    const minColumn = this._context.viewModel.getLineMinColumn(lineNumber);
    if (column < minColumn) {
      column = minColumn;
    }
    return new $8C(lineNumber, column);
  }
  M(node) {
    while (node && node.nodeType === 1) {
      if (node.className === $P7.CLASS_NAME) {
        return node;
      }
      node = node.parentElement;
    }
    return null;
  }
  /**
   * @returns the line number of this view line dom node.
   */
  N(domNode) {
    const startLineNumber = this.f.getStartLineNumber();
    const endLineNumber = this.f.getEndLineNumber();
    for (let lineNumber = startLineNumber; lineNumber <= endLineNumber; lineNumber++) {
      const line = this.f.getVisibleLine(lineNumber);
      if (domNode === line.getDomNode()) {
        return lineNumber;
      }
    }
    return -1;
  }
  getLineWidth(lineNumber) {
    const rendStartLineNumber = this.f.getStartLineNumber();
    const rendEndLineNumber = this.f.getEndLineNumber();
    if (lineNumber < rendStartLineNumber || lineNumber > rendEndLineNumber) {
      return -1;
    }
    const context = new $j7(this.g.domNode, this.c);
    const result = this.f.getVisibleLine(lineNumber).getWidth(context);
    this.R(context);
    return result;
  }
  linesVisibleRangesForRange(_range, includeNewLines) {
    if (this.shouldRender()) {
      return null;
    }
    const originalEndLineNumber = _range.endLineNumber;
    const range = $9C.intersectRanges(_range, this.H.getCurrentVisibleRange());
    if (!range) {
      return null;
    }
    const visibleRanges = [];
    let visibleRangesLen = 0;
    const domReadingContext = new $j7(this.g.domNode, this.c);
    let nextLineModelLineNumber = 0;
    if (includeNewLines) {
      nextLineModelLineNumber = this._context.viewModel.coordinatesConverter.convertViewPositionToModelPosition(new $8C(range.startLineNumber, 1)).lineNumber;
    }
    const rendStartLineNumber = this.f.getStartLineNumber();
    const rendEndLineNumber = this.f.getEndLineNumber();
    for (let lineNumber = range.startLineNumber; lineNumber <= range.endLineNumber; lineNumber++) {
      if (lineNumber < rendStartLineNumber || lineNumber > rendEndLineNumber) {
        continue;
      }
      const startColumn = lineNumber === range.startLineNumber ? range.startColumn : 1;
      const continuesInNextLine = lineNumber !== range.endLineNumber;
      const endColumn = continuesInNextLine ? this._context.viewModel.getLineMaxColumn(lineNumber) : range.endColumn;
      const visibleRangesForLine = this.f.getVisibleLine(lineNumber).getVisibleRangesForRange(lineNumber, startColumn, endColumn, domReadingContext);
      if (!visibleRangesForLine) {
        continue;
      }
      if (includeNewLines && lineNumber < originalEndLineNumber) {
        const currentLineModelLineNumber = nextLineModelLineNumber;
        nextLineModelLineNumber = this._context.viewModel.coordinatesConverter.convertViewPositionToModelPosition(new $8C(lineNumber + 1, 1)).lineNumber;
        if (currentLineModelLineNumber !== nextLineModelLineNumber) {
          visibleRangesForLine.ranges[visibleRangesForLine.ranges.length - 1].width += this.j;
        }
      }
      visibleRanges[visibleRangesLen++] = new $_6(visibleRangesForLine.outsideRenderedLine, lineNumber, $a7.from(visibleRangesForLine.ranges), continuesInNextLine);
    }
    this.R(domReadingContext);
    if (visibleRangesLen === 0) {
      return null;
    }
    return visibleRanges;
  }
  O(lineNumber, startColumn, endColumn) {
    if (this.shouldRender()) {
      return null;
    }
    if (lineNumber < this.f.getStartLineNumber() || lineNumber > this.f.getEndLineNumber()) {
      return null;
    }
    const domReadingContext = new $j7(this.g.domNode, this.c);
    const result = this.f.getVisibleLine(lineNumber).getVisibleRangesForRange(lineNumber, startColumn, endColumn, domReadingContext);
    this.R(domReadingContext);
    return result;
  }
  visibleRangeForPosition(position) {
    const visibleRanges = this.O(position.lineNumber, position.column, position.column);
    if (!visibleRanges) {
      return null;
    }
    return new $c7(visibleRanges.outsideRenderedLine, visibleRanges.ranges[0].left);
  }
  // --- implementation
  updateLineWidths() {
    this.S(false);
  }
  /**
   * Updates the max line width if it is fast to compute.
   * Returns true if all lines were taken into account.
   * Returns false if some lines need to be reevaluated (in a slow fashion).
   */
  P() {
    return this.S(true);
  }
  Q() {
    this.S(false);
  }
  /**
   * Update the line widths using DOM layout information after someone else
   * has caused a synchronous layout.
   */
  R(domReadingContext) {
    if (!domReadingContext.didDomLayout) {
      return;
    }
    if (this.D.isScheduled()) {
      return;
    }
    this.D.cancel();
    this.Q();
  }
  S(fast) {
    const rendStartLineNumber = this.f.getStartLineNumber();
    const rendEndLineNumber = this.f.getEndLineNumber();
    let localMaxLineWidth = 1;
    let allWidthsComputed = true;
    for (let lineNumber = rendStartLineNumber; lineNumber <= rendEndLineNumber; lineNumber++) {
      const visibleLine = this.f.getVisibleLine(lineNumber);
      if (fast && !visibleLine.getWidthIsFast()) {
        allWidthsComputed = false;
        continue;
      }
      localMaxLineWidth = Math.max(localMaxLineWidth, visibleLine.getWidth(null));
    }
    if (allWidthsComputed && rendStartLineNumber === 1 && rendEndLineNumber === this._context.viewModel.getLineCount()) {
      this.C = 0;
    }
    this.W(localMaxLineWidth);
    return allWidthsComputed;
  }
  U() {
    let longestLineNumber = -1;
    let longestWidth = -1;
    const rendStartLineNumber = this.f.getStartLineNumber();
    const rendEndLineNumber = this.f.getEndLineNumber();
    for (let lineNumber = rendStartLineNumber; lineNumber <= rendEndLineNumber; lineNumber++) {
      const visibleLine = this.f.getVisibleLine(lineNumber);
      if (visibleLine.needsMonospaceFontCheck()) {
        const lineWidth = visibleLine.getWidth(null);
        if (lineWidth > longestWidth) {
          longestWidth = lineWidth;
          longestLineNumber = lineNumber;
        }
      }
    }
    if (longestLineNumber === -1) {
      return;
    }
    if (!this.f.getVisibleLine(longestLineNumber).monospaceAssumptionsAreValid()) {
      for (let lineNumber = rendStartLineNumber; lineNumber <= rendEndLineNumber; lineNumber++) {
        const visibleLine = this.f.getVisibleLine(lineNumber);
        visibleLine.onMonospaceAssumptionsInvalidated();
      }
    }
  }
  prepareRender() {
    throw new Error("Not supported");
  }
  render() {
    throw new Error("Not supported");
  }
  renderText(viewportData) {
    this.f.renderLines(viewportData);
    this.H.setCurrentVisibleRange(viewportData.visibleRange);
    this.g.setWidth(this._context.viewLayout.getScrollWidth());
    this.g.setHeight(Math.min(this._context.viewLayout.getScrollHeight(), 1e6));
    if (this.G) {
      const horizontalRevealRequest = this.G;
      if (viewportData.startLineNumber <= horizontalRevealRequest.minLineNumber && horizontalRevealRequest.maxLineNumber <= viewportData.endLineNumber) {
        this.G = null;
        this.onDidRender();
        const newScrollLeft = this.Y(horizontalRevealRequest);
        if (newScrollLeft) {
          if (!this.n) {
            this.W(newScrollLeft.maxHorizontalOffset);
          }
          this._context.viewModel.viewLayout.setScrollPosition({
            scrollLeft: newScrollLeft.scrollLeft
          }, horizontalRevealRequest.scrollType);
        }
      }
    }
    if (!this.P()) {
      this.D.schedule();
    } else {
      this.D.cancel();
    }
    if ($n && !this.F.isScheduled()) {
      const rendStartLineNumber = this.f.getStartLineNumber();
      const rendEndLineNumber = this.f.getEndLineNumber();
      for (let lineNumber = rendStartLineNumber; lineNumber <= rendEndLineNumber; lineNumber++) {
        const visibleLine = this.f.getVisibleLine(lineNumber);
        if (visibleLine.needsMonospaceFontCheck()) {
          this.F.schedule();
          break;
        }
      }
    }
    this.b.setLayerHinting(this.y);
    this.b.setContain("strict");
    const adjustedScrollTop = this._context.viewLayout.getCurrentScrollTop() - viewportData.bigNumbersDelta;
    this.b.setTop(-adjustedScrollTop);
    this.b.setLeft(-this._context.viewLayout.getCurrentScrollLeft());
  }
  // --- width
  W(lineWidth) {
    const iLineWidth = Math.ceil(lineWidth);
    if (this.C < iLineWidth) {
      this.C = iLineWidth;
      this._context.viewModel.viewLayout.setMaxLineWidth(this.C);
    }
  }
  X(viewport, source, minimalReveal, range, selections, verticalType) {
    const viewportStartY = viewport.top;
    const viewportHeight = viewport.height;
    const viewportEndY = viewportStartY + viewportHeight;
    let boxIsSingleRange;
    let boxStartY;
    let boxEndY;
    if (selections && selections.length > 0) {
      let minLineNumber = selections[0].startLineNumber;
      let maxLineNumber = selections[0].endLineNumber;
      for (let i2 = 1, len = selections.length; i2 < len; i2++) {
        const selection = selections[i2];
        minLineNumber = Math.min(minLineNumber, selection.startLineNumber);
        maxLineNumber = Math.max(maxLineNumber, selection.endLineNumber);
      }
      boxIsSingleRange = false;
      boxStartY = this._context.viewLayout.getVerticalOffsetForLineNumber(minLineNumber);
      boxEndY = this._context.viewLayout.getVerticalOffsetForLineNumber(maxLineNumber) + this.h;
    } else if (range) {
      boxIsSingleRange = true;
      boxStartY = this._context.viewLayout.getVerticalOffsetForLineNumber(range.startLineNumber);
      boxEndY = this._context.viewLayout.getVerticalOffsetForLineNumber(range.endLineNumber) + this.h;
    } else {
      return -1;
    }
    const shouldIgnoreScrollOff = (source === "mouse" || minimalReveal) && this.w === "default";
    let paddingTop = 0;
    let paddingBottom = 0;
    if (!shouldIgnoreScrollOff) {
      const maxLinesInViewport = viewportHeight / this.h;
      const surroundingLines = Math.max(this.t, this.I ? this.J : 0);
      const context = Math.min(maxLinesInViewport / 2, surroundingLines);
      paddingTop = context * this.h;
      paddingBottom = Math.max(0, context - 1) * this.h;
    } else {
      if (!minimalReveal) {
        paddingTop = this.h;
      }
    }
    if (!minimalReveal) {
      if (verticalType === 0 || verticalType === 4) {
        paddingBottom += this.h;
      }
    }
    boxStartY -= paddingTop;
    boxEndY += paddingBottom;
    let newScrollTop;
    if (boxEndY - boxStartY > viewportHeight) {
      if (!boxIsSingleRange) {
        return -1;
      }
      newScrollTop = boxStartY;
    } else if (verticalType === 5 || verticalType === 6) {
      if (verticalType === 6 && viewportStartY <= boxStartY && boxEndY <= viewportEndY) {
        newScrollTop = viewportStartY;
      } else {
        const desiredGapAbove = Math.max(5 * this.h, viewportHeight * 0.2);
        const desiredScrollTop = boxStartY - desiredGapAbove;
        const minScrollTop = boxEndY - viewportHeight;
        newScrollTop = Math.max(minScrollTop, desiredScrollTop);
      }
    } else if (verticalType === 1 || verticalType === 2) {
      if (verticalType === 2 && viewportStartY <= boxStartY && boxEndY <= viewportEndY) {
        newScrollTop = viewportStartY;
      } else {
        const boxMiddleY = (boxStartY + boxEndY) / 2;
        newScrollTop = Math.max(0, boxMiddleY - viewportHeight / 2);
      }
    } else {
      newScrollTop = this.Z(
        viewportStartY,
        viewportEndY,
        boxStartY,
        boxEndY,
        verticalType === 3,
        verticalType === 4
        /* viewEvents.VerticalRevealType.Bottom */
      );
    }
    return newScrollTop;
  }
  Y(horizontalRevealRequest) {
    const viewport = this._context.viewLayout.getCurrentViewport();
    const layoutInfo = this._context.configuration.options.get(
      151
      /* EditorOption.layoutInfo */
    );
    const viewportStartX = viewport.left;
    const viewportEndX = viewportStartX + viewport.width - layoutInfo.verticalScrollbarWidth;
    let boxStartX = 1073741824;
    let boxEndX = 0;
    if (horizontalRevealRequest.type === "range") {
      const visibleRanges = this.O(horizontalRevealRequest.lineNumber, horizontalRevealRequest.startColumn, horizontalRevealRequest.endColumn);
      if (!visibleRanges) {
        return null;
      }
      for (const visibleRange of visibleRanges.ranges) {
        boxStartX = Math.min(boxStartX, Math.round(visibleRange.left));
        boxEndX = Math.max(boxEndX, Math.round(visibleRange.left + visibleRange.width));
      }
    } else {
      for (const selection of horizontalRevealRequest.selections) {
        if (selection.startLineNumber !== selection.endLineNumber) {
          return null;
        }
        const visibleRanges = this.O(selection.startLineNumber, selection.startColumn, selection.endColumn);
        if (!visibleRanges) {
          return null;
        }
        for (const visibleRange of visibleRanges.ranges) {
          boxStartX = Math.min(boxStartX, Math.round(visibleRange.left));
          boxEndX = Math.max(boxEndX, Math.round(visibleRange.left + visibleRange.width));
        }
      }
    }
    if (!horizontalRevealRequest.minimalReveal) {
      boxStartX = Math.max(0, boxStartX - _$w8.a);
      boxEndX += this.s;
    }
    if (horizontalRevealRequest.type === "selections" && boxEndX - boxStartX > viewport.width) {
      return null;
    }
    const newScrollLeft = this.Z(viewportStartX, viewportEndX, boxStartX, boxEndX);
    return {
      scrollLeft: newScrollLeft,
      maxHorizontalOffset: boxEndX
    };
  }
  Z(viewportStart, viewportEnd, boxStart, boxEnd, revealAtStart, revealAtEnd) {
    viewportStart = viewportStart | 0;
    viewportEnd = viewportEnd | 0;
    boxStart = boxStart | 0;
    boxEnd = boxEnd | 0;
    revealAtStart = !!revealAtStart;
    revealAtEnd = !!revealAtEnd;
    const viewportLength = viewportEnd - viewportStart;
    const boxLength = boxEnd - boxStart;
    if (boxLength < viewportLength) {
      if (revealAtStart) {
        return boxStart;
      }
      if (revealAtEnd) {
        return Math.max(0, boxEnd - viewportLength);
      }
      if (boxStart < viewportStart) {
        return boxStart;
      } else if (boxEnd > viewportEnd) {
        return Math.max(0, boxEnd - viewportLength);
      }
    } else {
      return boxStart;
    }
    return viewportStart;
  }
};

// out-build/vs/editor/browser/viewParts/linesDecorations/linesDecorations.js
var $x8 = class extends $s8 {
  constructor(context) {
    super();
    this.f = context;
    const options3 = this.f.configuration.options;
    const layoutInfo = options3.get(
      151
      /* EditorOption.layoutInfo */
    );
    this.g = layoutInfo.decorationsLeft;
    this.h = layoutInfo.decorationsWidth;
    this.j = null;
    this.f.addEventHandler(this);
  }
  dispose() {
    this.f.removeEventHandler(this);
    this.j = null;
    super.dispose();
  }
  // --- begin event handlers
  onConfigurationChanged(e) {
    const options3 = this.f.configuration.options;
    const layoutInfo = options3.get(
      151
      /* EditorOption.layoutInfo */
    );
    this.g = layoutInfo.decorationsLeft;
    this.h = layoutInfo.decorationsWidth;
    return true;
  }
  onDecorationsChanged(e) {
    return true;
  }
  onFlushed(e) {
    return true;
  }
  onLinesChanged(e) {
    return true;
  }
  onLinesDeleted(e) {
    return true;
  }
  onLinesInserted(e) {
    return true;
  }
  onScrollChanged(e) {
    return e.scrollTopChanged;
  }
  onZonesChanged(e) {
    return true;
  }
  // --- end event handlers
  n(ctx) {
    const decorations = ctx.getDecorationsInViewport();
    const r2 = [];
    let rLen = 0;
    for (let i2 = 0, len = decorations.length; i2 < len; i2++) {
      const d = decorations[i2];
      const linesDecorationsClassName = d.options.linesDecorationsClassName;
      const zIndex = d.options.zIndex;
      if (linesDecorationsClassName) {
        r2[rLen++] = new $p8(d.range.startLineNumber, d.range.endLineNumber, linesDecorationsClassName, d.options.linesDecorationsTooltip ?? null, zIndex);
      }
      const firstLineDecorationClassName = d.options.firstLineDecorationClassName;
      if (firstLineDecorationClassName) {
        r2[rLen++] = new $p8(d.range.startLineNumber, d.range.startLineNumber, firstLineDecorationClassName, d.options.linesDecorationsTooltip ?? null, zIndex);
      }
    }
    return r2;
  }
  prepareRender(ctx) {
    const visibleStartLineNumber = ctx.visibleRange.startLineNumber;
    const visibleEndLineNumber = ctx.visibleRange.endLineNumber;
    const toRender = this.c(visibleStartLineNumber, visibleEndLineNumber, this.n(ctx));
    const left = this.g.toString();
    const width2 = this.h.toString();
    const common = '" style="left:' + left + "px;width:" + width2 + 'px;"></div>';
    const output = [];
    for (let lineNumber = visibleStartLineNumber; lineNumber <= visibleEndLineNumber; lineNumber++) {
      const lineIndex = lineNumber - visibleStartLineNumber;
      const decorations = toRender[lineIndex].getDecorations();
      let lineOutput = "";
      for (const decoration3 of decorations) {
        let addition = '<div class="cldr ' + decoration3.className;
        if (decoration3.tooltip !== null) {
          addition += '" title="' + decoration3.tooltip;
        }
        addition += common;
        lineOutput += addition;
      }
      output[lineIndex] = lineOutput;
    }
    this.j = output;
  }
  render(startLineNumber, lineNumber) {
    if (!this.j) {
      return "";
    }
    return this.j[lineNumber - startLineNumber];
  }
};

// out-build/vs/editor/browser/viewParts/margin/margin.js
var $y8 = class _$y8 extends $f7 {
  static {
    this.CLASS_NAME = "glyph-margin";
  }
  static {
    this.OUTER_CLASS_NAME = "margin";
  }
  constructor(context) {
    super(context);
    const options3 = this._context.configuration.options;
    const layoutInfo = options3.get(
      151
      /* EditorOption.layoutInfo */
    );
    this.b = !options3.get(
      32
      /* EditorOption.disableLayerHinting */
    );
    this.c = layoutInfo.contentLeft;
    this.f = layoutInfo.glyphMarginLeft;
    this.g = layoutInfo.glyphMarginWidth;
    this.a = $oZ(document.createElement("div"));
    this.a.setClassName(_$y8.OUTER_CLASS_NAME);
    this.a.setPosition("absolute");
    this.a.setAttribute("role", "presentation");
    this.a.setAttribute("aria-hidden", "true");
    this.h = $oZ(document.createElement("div"));
    this.h.setClassName(_$y8.CLASS_NAME);
    this.a.appendChild(this.h);
  }
  dispose() {
    super.dispose();
  }
  getDomNode() {
    return this.a;
  }
  // --- begin event handlers
  onConfigurationChanged(e) {
    const options3 = this._context.configuration.options;
    const layoutInfo = options3.get(
      151
      /* EditorOption.layoutInfo */
    );
    this.b = !options3.get(
      32
      /* EditorOption.disableLayerHinting */
    );
    this.c = layoutInfo.contentLeft;
    this.f = layoutInfo.glyphMarginLeft;
    this.g = layoutInfo.glyphMarginWidth;
    return true;
  }
  onScrollChanged(e) {
    return super.onScrollChanged(e) || e.scrollTopChanged;
  }
  // --- end event handlers
  prepareRender(ctx) {
  }
  render(ctx) {
    this.a.setLayerHinting(this.b);
    this.a.setContain("strict");
    const adjustedScrollTop = ctx.scrollTop - ctx.bigNumbersDelta;
    this.a.setTop(-adjustedScrollTop);
    const height = Math.min(ctx.scrollHeight, 1e6);
    this.a.setHeight(height);
    this.a.setWidth(this.c);
    this.h.setLeft(this.f);
    this.h.setWidth(this.g);
    this.h.setHeight(height);
  }
};

// out-build/vs/editor/browser/viewParts/marginDecorations/marginDecorations.js
var $z8 = class extends $s8 {
  constructor(context) {
    super();
    this.f = context;
    this.g = null;
    this.f.addEventHandler(this);
  }
  dispose() {
    this.f.removeEventHandler(this);
    this.g = null;
    super.dispose();
  }
  // --- begin event handlers
  onConfigurationChanged(e) {
    return true;
  }
  onDecorationsChanged(e) {
    return true;
  }
  onFlushed(e) {
    return true;
  }
  onLinesChanged(e) {
    return true;
  }
  onLinesDeleted(e) {
    return true;
  }
  onLinesInserted(e) {
    return true;
  }
  onScrollChanged(e) {
    return e.scrollTopChanged;
  }
  onZonesChanged(e) {
    return true;
  }
  // --- end event handlers
  h(ctx) {
    const decorations = ctx.getDecorationsInViewport();
    const r2 = [];
    let rLen = 0;
    for (let i2 = 0, len = decorations.length; i2 < len; i2++) {
      const d = decorations[i2];
      const marginClassName = d.options.marginClassName;
      const zIndex = d.options.zIndex;
      if (marginClassName) {
        r2[rLen++] = new $p8(d.range.startLineNumber, d.range.endLineNumber, marginClassName, null, zIndex);
      }
    }
    return r2;
  }
  prepareRender(ctx) {
    const visibleStartLineNumber = ctx.visibleRange.startLineNumber;
    const visibleEndLineNumber = ctx.visibleRange.endLineNumber;
    const toRender = this.c(visibleStartLineNumber, visibleEndLineNumber, this.h(ctx));
    const output = [];
    for (let lineNumber = visibleStartLineNumber; lineNumber <= visibleEndLineNumber; lineNumber++) {
      const lineIndex = lineNumber - visibleStartLineNumber;
      const decorations = toRender[lineIndex].getDecorations();
      let lineOutput = "";
      for (const decoration3 of decorations) {
        lineOutput += '<div class="cmdr ' + decoration3.className + '" style=""></div>';
      }
      output[lineIndex] = lineOutput;
    }
    this.g = output;
  }
  render(startLineNumber, lineNumber) {
    if (!this.g) {
      return "";
    }
    return this.g[lineNumber - startLineNumber];
  }
};

// out-build/vs/editor/common/core/rgba.js
var $A8 = class _$A8 {
  static {
    this.Empty = new _$A8(0, 0, 0, 0);
  }
  constructor(r2, g, b, a) {
    this._rgba8Brand = void 0;
    this.r = _$A8._clamp(r2);
    this.g = _$A8._clamp(g);
    this.b = _$A8._clamp(b);
    this.a = _$A8._clamp(a);
  }
  equals(other) {
    return this.r === other.r && this.g === other.g && this.b === other.b && this.a === other.a;
  }
  static _clamp(c) {
    if (c < 0) {
      return 0;
    }
    if (c > 255) {
      return 255;
    }
    return c | 0;
  }
};

// out-build/vs/editor/common/core/editOperation.js
var $bD = class {
  static insert(position, text2) {
    return {
      range: new $9C(position.lineNumber, position.column, position.lineNumber, position.column),
      text: text2,
      forceMoveMarkers: true
    };
  }
  static delete(range) {
    return {
      range,
      text: null
    };
  }
  static replace(range, text2) {
    return {
      range,
      text: text2
    };
  }
  static replaceMove(range, text2) {
    return {
      range,
      text: text2,
      forceMoveMarkers: true
    };
  }
};

// out-build/vs/editor/common/tokenizationRegistry.js
var $sE = class {
  constructor() {
    this.a = /* @__PURE__ */ new Map();
    this.b = /* @__PURE__ */ new Map();
    this.c = new $ze();
    this.onDidChange = this.c.event;
    this.d = null;
  }
  handleChange(languageIds) {
    this.c.fire({
      changedLanguages: languageIds,
      changedColorMap: false
    });
  }
  register(languageId, support) {
    this.a.set(languageId, support);
    this.handleChange([languageId]);
    return $1c(() => {
      if (this.a.get(languageId) !== support) {
        return;
      }
      this.a.delete(languageId);
      this.handleChange([languageId]);
    });
  }
  get(languageId) {
    return this.a.get(languageId) || null;
  }
  registerFactory(languageId, factory) {
    this.b.get(languageId)?.dispose();
    const myData = new TokenizationSupportFactoryData(this, languageId, factory);
    this.b.set(languageId, myData);
    return $1c(() => {
      const v = this.b.get(languageId);
      if (!v || v !== myData) {
        return;
      }
      this.b.delete(languageId);
      v.dispose();
    });
  }
  async getOrCreate(languageId) {
    const tokenizationSupport = this.get(languageId);
    if (tokenizationSupport) {
      return tokenizationSupport;
    }
    const factory = this.b.get(languageId);
    if (!factory || factory.isResolved) {
      return null;
    }
    await factory.resolve();
    return this.get(languageId);
  }
  isResolved(languageId) {
    const tokenizationSupport = this.get(languageId);
    if (tokenizationSupport) {
      return true;
    }
    const factory = this.b.get(languageId);
    if (!factory || factory.isResolved) {
      return true;
    }
    return false;
  }
  setColorMap(colorMap) {
    this.d = colorMap;
    this.c.fire({
      changedLanguages: Array.from(this.a.keys()),
      changedColorMap: true
    });
  }
  getColorMap() {
    return this.d;
  }
  getDefaultBackground() {
    if (this.d && this.d.length > 2) {
      return this.d[
        2
        /* ColorId.DefaultBackground */
      ];
    }
    return null;
  }
};
var TokenizationSupportFactoryData = class extends $3c {
  get isResolved() {
    return this.c;
  }
  constructor(f, g, h3) {
    super();
    this.f = f;
    this.g = g;
    this.h = h3;
    this.a = false;
    this.b = null;
    this.c = false;
  }
  dispose() {
    this.a = true;
    super.dispose();
  }
  async resolve() {
    if (!this.b) {
      this.b = this.j();
    }
    return this.b;
  }
  async j() {
    const value = await this.h.tokenizationSupport;
    this.c = true;
    if (value && !this.a) {
      this.B(this.f.register(this.g, value));
    }
  }
};

// out-build/vs/editor/common/languages.js
var $NE = class {
  constructor(offset, type, language) {
    this.offset = offset;
    this.type = type;
    this.language = language;
    this._tokenBrand = void 0;
  }
  toString() {
    return "(" + this.offset + ", " + this.type + ")";
  }
};
var $PE = class {
  constructor(tokens, endState) {
    this.tokens = tokens;
    this.endState = endState;
    this._encodedTokenizationResultBrand = void 0;
  }
};
var HoverVerbosityAction;
(function(HoverVerbosityAction4) {
  HoverVerbosityAction4[HoverVerbosityAction4["Increase"] = 0] = "Increase";
  HoverVerbosityAction4[HoverVerbosityAction4["Decrease"] = 1] = "Decrease";
})(HoverVerbosityAction || (HoverVerbosityAction = {}));
var CompletionItemKind;
(function(CompletionItemKind5) {
  CompletionItemKind5[CompletionItemKind5["Method"] = 0] = "Method";
  CompletionItemKind5[CompletionItemKind5["Function"] = 1] = "Function";
  CompletionItemKind5[CompletionItemKind5["Constructor"] = 2] = "Constructor";
  CompletionItemKind5[CompletionItemKind5["Field"] = 3] = "Field";
  CompletionItemKind5[CompletionItemKind5["Variable"] = 4] = "Variable";
  CompletionItemKind5[CompletionItemKind5["Class"] = 5] = "Class";
  CompletionItemKind5[CompletionItemKind5["Struct"] = 6] = "Struct";
  CompletionItemKind5[CompletionItemKind5["Interface"] = 7] = "Interface";
  CompletionItemKind5[CompletionItemKind5["Module"] = 8] = "Module";
  CompletionItemKind5[CompletionItemKind5["Property"] = 9] = "Property";
  CompletionItemKind5[CompletionItemKind5["Event"] = 10] = "Event";
  CompletionItemKind5[CompletionItemKind5["Operator"] = 11] = "Operator";
  CompletionItemKind5[CompletionItemKind5["Unit"] = 12] = "Unit";
  CompletionItemKind5[CompletionItemKind5["Value"] = 13] = "Value";
  CompletionItemKind5[CompletionItemKind5["Constant"] = 14] = "Constant";
  CompletionItemKind5[CompletionItemKind5["Enum"] = 15] = "Enum";
  CompletionItemKind5[CompletionItemKind5["EnumMember"] = 16] = "EnumMember";
  CompletionItemKind5[CompletionItemKind5["Keyword"] = 17] = "Keyword";
  CompletionItemKind5[CompletionItemKind5["Text"] = 18] = "Text";
  CompletionItemKind5[CompletionItemKind5["Color"] = 19] = "Color";
  CompletionItemKind5[CompletionItemKind5["File"] = 20] = "File";
  CompletionItemKind5[CompletionItemKind5["Reference"] = 21] = "Reference";
  CompletionItemKind5[CompletionItemKind5["Customcolor"] = 22] = "Customcolor";
  CompletionItemKind5[CompletionItemKind5["Folder"] = 23] = "Folder";
  CompletionItemKind5[CompletionItemKind5["TypeParameter"] = 24] = "TypeParameter";
  CompletionItemKind5[CompletionItemKind5["User"] = 25] = "User";
  CompletionItemKind5[CompletionItemKind5["Issue"] = 26] = "Issue";
  CompletionItemKind5[CompletionItemKind5["Snippet"] = 27] = "Snippet";
})(CompletionItemKind || (CompletionItemKind = {}));
var CompletionItemKinds;
(function(CompletionItemKinds2) {
  const byKind = /* @__PURE__ */ new Map();
  byKind.set(0, $6l.symbolMethod);
  byKind.set(1, $6l.symbolFunction);
  byKind.set(2, $6l.symbolConstructor);
  byKind.set(3, $6l.symbolField);
  byKind.set(4, $6l.symbolVariable);
  byKind.set(5, $6l.symbolClass);
  byKind.set(6, $6l.symbolStruct);
  byKind.set(7, $6l.symbolInterface);
  byKind.set(8, $6l.symbolModule);
  byKind.set(9, $6l.symbolProperty);
  byKind.set(10, $6l.symbolEvent);
  byKind.set(11, $6l.symbolOperator);
  byKind.set(12, $6l.symbolUnit);
  byKind.set(13, $6l.symbolValue);
  byKind.set(15, $6l.symbolEnum);
  byKind.set(14, $6l.symbolConstant);
  byKind.set(15, $6l.symbolEnum);
  byKind.set(16, $6l.symbolEnumMember);
  byKind.set(17, $6l.symbolKeyword);
  byKind.set(27, $6l.symbolSnippet);
  byKind.set(18, $6l.symbolText);
  byKind.set(19, $6l.symbolColor);
  byKind.set(20, $6l.symbolFile);
  byKind.set(21, $6l.symbolReference);
  byKind.set(22, $6l.symbolCustomColor);
  byKind.set(23, $6l.symbolFolder);
  byKind.set(24, $6l.symbolTypeParameter);
  byKind.set(25, $6l.account);
  byKind.set(26, $6l.issues);
  function toIcon(kind) {
    let codicon = byKind.get(kind);
    if (!codicon) {
      console.info("No codicon found for CompletionItemKind " + kind);
      codicon = $6l.symbolProperty;
    }
    return codicon;
  }
  CompletionItemKinds2.toIcon = toIcon;
  const data = /* @__PURE__ */ new Map();
  data.set(
    "method",
    0
    /* CompletionItemKind.Method */
  );
  data.set(
    "function",
    1
    /* CompletionItemKind.Function */
  );
  data.set(
    "constructor",
    2
    /* CompletionItemKind.Constructor */
  );
  data.set(
    "field",
    3
    /* CompletionItemKind.Field */
  );
  data.set(
    "variable",
    4
    /* CompletionItemKind.Variable */
  );
  data.set(
    "class",
    5
    /* CompletionItemKind.Class */
  );
  data.set(
    "struct",
    6
    /* CompletionItemKind.Struct */
  );
  data.set(
    "interface",
    7
    /* CompletionItemKind.Interface */
  );
  data.set(
    "module",
    8
    /* CompletionItemKind.Module */
  );
  data.set(
    "property",
    9
    /* CompletionItemKind.Property */
  );
  data.set(
    "event",
    10
    /* CompletionItemKind.Event */
  );
  data.set(
    "operator",
    11
    /* CompletionItemKind.Operator */
  );
  data.set(
    "unit",
    12
    /* CompletionItemKind.Unit */
  );
  data.set(
    "value",
    13
    /* CompletionItemKind.Value */
  );
  data.set(
    "constant",
    14
    /* CompletionItemKind.Constant */
  );
  data.set(
    "enum",
    15
    /* CompletionItemKind.Enum */
  );
  data.set(
    "enum-member",
    16
    /* CompletionItemKind.EnumMember */
  );
  data.set(
    "enumMember",
    16
    /* CompletionItemKind.EnumMember */
  );
  data.set(
    "keyword",
    17
    /* CompletionItemKind.Keyword */
  );
  data.set(
    "snippet",
    27
    /* CompletionItemKind.Snippet */
  );
  data.set(
    "text",
    18
    /* CompletionItemKind.Text */
  );
  data.set(
    "color",
    19
    /* CompletionItemKind.Color */
  );
  data.set(
    "file",
    20
    /* CompletionItemKind.File */
  );
  data.set(
    "reference",
    21
    /* CompletionItemKind.Reference */
  );
  data.set(
    "customcolor",
    22
    /* CompletionItemKind.Customcolor */
  );
  data.set(
    "folder",
    23
    /* CompletionItemKind.Folder */
  );
  data.set(
    "type-parameter",
    24
    /* CompletionItemKind.TypeParameter */
  );
  data.set(
    "typeParameter",
    24
    /* CompletionItemKind.TypeParameter */
  );
  data.set(
    "account",
    25
    /* CompletionItemKind.User */
  );
  data.set(
    "issue",
    26
    /* CompletionItemKind.Issue */
  );
  function fromString(value, strict) {
    let res = data.get(value);
    if (typeof res === "undefined" && !strict) {
      res = 9;
    }
    return res;
  }
  CompletionItemKinds2.fromString = fromString;
})(CompletionItemKinds || (CompletionItemKinds = {}));
var CompletionItemTag;
(function(CompletionItemTag5) {
  CompletionItemTag5[CompletionItemTag5["Deprecated"] = 1] = "Deprecated";
})(CompletionItemTag || (CompletionItemTag = {}));
var CompletionItemInsertTextRule;
(function(CompletionItemInsertTextRule3) {
  CompletionItemInsertTextRule3[CompletionItemInsertTextRule3["None"] = 0] = "None";
  CompletionItemInsertTextRule3[CompletionItemInsertTextRule3["KeepWhitespace"] = 1] = "KeepWhitespace";
  CompletionItemInsertTextRule3[CompletionItemInsertTextRule3["InsertAsSnippet"] = 4] = "InsertAsSnippet";
})(CompletionItemInsertTextRule || (CompletionItemInsertTextRule = {}));
var PartialAcceptTriggerKind;
(function(PartialAcceptTriggerKind5) {
  PartialAcceptTriggerKind5[PartialAcceptTriggerKind5["Word"] = 0] = "Word";
  PartialAcceptTriggerKind5[PartialAcceptTriggerKind5["Line"] = 1] = "Line";
  PartialAcceptTriggerKind5[PartialAcceptTriggerKind5["Suggest"] = 2] = "Suggest";
})(PartialAcceptTriggerKind || (PartialAcceptTriggerKind = {}));
var CompletionTriggerKind;
(function(CompletionTriggerKind5) {
  CompletionTriggerKind5[CompletionTriggerKind5["Invoke"] = 0] = "Invoke";
  CompletionTriggerKind5[CompletionTriggerKind5["TriggerCharacter"] = 1] = "TriggerCharacter";
  CompletionTriggerKind5[CompletionTriggerKind5["TriggerForIncompleteCompletions"] = 2] = "TriggerForIncompleteCompletions";
})(CompletionTriggerKind || (CompletionTriggerKind = {}));
var InlineCompletionTriggerKind;
(function(InlineCompletionTriggerKind4) {
  InlineCompletionTriggerKind4[InlineCompletionTriggerKind4["Automatic"] = 0] = "Automatic";
  InlineCompletionTriggerKind4[InlineCompletionTriggerKind4["Explicit"] = 1] = "Explicit";
})(InlineCompletionTriggerKind || (InlineCompletionTriggerKind = {}));
var $QE = class {
  constructor(range, text2, completionKind, isSnippetText) {
    this.range = range;
    this.text = text2;
    this.completionKind = completionKind;
    this.isSnippetText = isSnippetText;
  }
  equals(other) {
    return $9C.lift(this.range).equalsRange(other.range) && this.text === other.text && this.completionKind === other.completionKind && this.isSnippetText === other.isSnippetText;
  }
};
var CodeActionTriggerType;
(function(CodeActionTriggerType3) {
  CodeActionTriggerType3[CodeActionTriggerType3["Invoke"] = 1] = "Invoke";
  CodeActionTriggerType3[CodeActionTriggerType3["Auto"] = 2] = "Auto";
})(CodeActionTriggerType || (CodeActionTriggerType = {}));
var DocumentPasteTriggerKind;
(function(DocumentPasteTriggerKind3) {
  DocumentPasteTriggerKind3[DocumentPasteTriggerKind3["Automatic"] = 0] = "Automatic";
  DocumentPasteTriggerKind3[DocumentPasteTriggerKind3["PasteAs"] = 1] = "PasteAs";
})(DocumentPasteTriggerKind || (DocumentPasteTriggerKind = {}));
var SignatureHelpTriggerKind;
(function(SignatureHelpTriggerKind4) {
  SignatureHelpTriggerKind4[SignatureHelpTriggerKind4["Invoke"] = 1] = "Invoke";
  SignatureHelpTriggerKind4[SignatureHelpTriggerKind4["TriggerCharacter"] = 2] = "TriggerCharacter";
  SignatureHelpTriggerKind4[SignatureHelpTriggerKind4["ContentChange"] = 3] = "ContentChange";
})(SignatureHelpTriggerKind || (SignatureHelpTriggerKind = {}));
var DocumentHighlightKind;
(function(DocumentHighlightKind4) {
  DocumentHighlightKind4[DocumentHighlightKind4["Text"] = 0] = "Text";
  DocumentHighlightKind4[DocumentHighlightKind4["Read"] = 1] = "Read";
  DocumentHighlightKind4[DocumentHighlightKind4["Write"] = 2] = "Write";
})(DocumentHighlightKind || (DocumentHighlightKind = {}));
function $RE(thing) {
  return thing && URI.isUri(thing.uri) && $9C.isIRange(thing.range) && ($9C.isIRange(thing.originSelectionRange) || $9C.isIRange(thing.targetSelectionRange));
}
function $SE(thing) {
  return thing && URI.isUri(thing.uri) && $9C.isIRange(thing.range);
}
var SymbolKind;
(function(SymbolKind5) {
  SymbolKind5[SymbolKind5["File"] = 0] = "File";
  SymbolKind5[SymbolKind5["Module"] = 1] = "Module";
  SymbolKind5[SymbolKind5["Namespace"] = 2] = "Namespace";
  SymbolKind5[SymbolKind5["Package"] = 3] = "Package";
  SymbolKind5[SymbolKind5["Class"] = 4] = "Class";
  SymbolKind5[SymbolKind5["Method"] = 5] = "Method";
  SymbolKind5[SymbolKind5["Property"] = 6] = "Property";
  SymbolKind5[SymbolKind5["Field"] = 7] = "Field";
  SymbolKind5[SymbolKind5["Constructor"] = 8] = "Constructor";
  SymbolKind5[SymbolKind5["Enum"] = 9] = "Enum";
  SymbolKind5[SymbolKind5["Interface"] = 10] = "Interface";
  SymbolKind5[SymbolKind5["Function"] = 11] = "Function";
  SymbolKind5[SymbolKind5["Variable"] = 12] = "Variable";
  SymbolKind5[SymbolKind5["Constant"] = 13] = "Constant";
  SymbolKind5[SymbolKind5["String"] = 14] = "String";
  SymbolKind5[SymbolKind5["Number"] = 15] = "Number";
  SymbolKind5[SymbolKind5["Boolean"] = 16] = "Boolean";
  SymbolKind5[SymbolKind5["Array"] = 17] = "Array";
  SymbolKind5[SymbolKind5["Object"] = 18] = "Object";
  SymbolKind5[SymbolKind5["Key"] = 19] = "Key";
  SymbolKind5[SymbolKind5["Null"] = 20] = "Null";
  SymbolKind5[SymbolKind5["EnumMember"] = 21] = "EnumMember";
  SymbolKind5[SymbolKind5["Struct"] = 22] = "Struct";
  SymbolKind5[SymbolKind5["Event"] = 23] = "Event";
  SymbolKind5[SymbolKind5["Operator"] = 24] = "Operator";
  SymbolKind5[SymbolKind5["TypeParameter"] = 25] = "TypeParameter";
})(SymbolKind || (SymbolKind = {}));
var $TE = {
  [
    17
    /* SymbolKind.Array */
  ]: localize(804, null),
  [
    16
    /* SymbolKind.Boolean */
  ]: localize(805, null),
  [
    4
    /* SymbolKind.Class */
  ]: localize(806, null),
  [
    13
    /* SymbolKind.Constant */
  ]: localize(807, null),
  [
    8
    /* SymbolKind.Constructor */
  ]: localize(808, null),
  [
    9
    /* SymbolKind.Enum */
  ]: localize(809, null),
  [
    21
    /* SymbolKind.EnumMember */
  ]: localize(810, null),
  [
    23
    /* SymbolKind.Event */
  ]: localize(811, null),
  [
    7
    /* SymbolKind.Field */
  ]: localize(812, null),
  [
    0
    /* SymbolKind.File */
  ]: localize(813, null),
  [
    11
    /* SymbolKind.Function */
  ]: localize(814, null),
  [
    10
    /* SymbolKind.Interface */
  ]: localize(815, null),
  [
    19
    /* SymbolKind.Key */
  ]: localize(816, null),
  [
    5
    /* SymbolKind.Method */
  ]: localize(817, null),
  [
    1
    /* SymbolKind.Module */
  ]: localize(818, null),
  [
    2
    /* SymbolKind.Namespace */
  ]: localize(819, null),
  [
    20
    /* SymbolKind.Null */
  ]: localize(820, null),
  [
    15
    /* SymbolKind.Number */
  ]: localize(821, null),
  [
    18
    /* SymbolKind.Object */
  ]: localize(822, null),
  [
    24
    /* SymbolKind.Operator */
  ]: localize(823, null),
  [
    3
    /* SymbolKind.Package */
  ]: localize(824, null),
  [
    6
    /* SymbolKind.Property */
  ]: localize(825, null),
  [
    14
    /* SymbolKind.String */
  ]: localize(826, null),
  [
    22
    /* SymbolKind.Struct */
  ]: localize(827, null),
  [
    25
    /* SymbolKind.TypeParameter */
  ]: localize(828, null),
  [
    12
    /* SymbolKind.Variable */
  ]: localize(829, null)
};
function $UE(symbolName, kind) {
  return localize(830, null, symbolName, $TE[kind]);
}
var SymbolTag;
(function(SymbolTag5) {
  SymbolTag5[SymbolTag5["Deprecated"] = 1] = "Deprecated";
})(SymbolTag || (SymbolTag = {}));
var SymbolKinds;
(function(SymbolKinds2) {
  const byKind = /* @__PURE__ */ new Map();
  byKind.set(0, $6l.symbolFile);
  byKind.set(1, $6l.symbolModule);
  byKind.set(2, $6l.symbolNamespace);
  byKind.set(3, $6l.symbolPackage);
  byKind.set(4, $6l.symbolClass);
  byKind.set(5, $6l.symbolMethod);
  byKind.set(6, $6l.symbolProperty);
  byKind.set(7, $6l.symbolField);
  byKind.set(8, $6l.symbolConstructor);
  byKind.set(9, $6l.symbolEnum);
  byKind.set(10, $6l.symbolInterface);
  byKind.set(11, $6l.symbolFunction);
  byKind.set(12, $6l.symbolVariable);
  byKind.set(13, $6l.symbolConstant);
  byKind.set(14, $6l.symbolString);
  byKind.set(15, $6l.symbolNumber);
  byKind.set(16, $6l.symbolBoolean);
  byKind.set(17, $6l.symbolArray);
  byKind.set(18, $6l.symbolObject);
  byKind.set(19, $6l.symbolKey);
  byKind.set(20, $6l.symbolNull);
  byKind.set(21, $6l.symbolEnumMember);
  byKind.set(22, $6l.symbolStruct);
  byKind.set(23, $6l.symbolEvent);
  byKind.set(24, $6l.symbolOperator);
  byKind.set(25, $6l.symbolTypeParameter);
  function toIcon(kind) {
    let icon2 = byKind.get(kind);
    if (!icon2) {
      console.info("No codicon found for SymbolKind " + kind);
      icon2 = $6l.symbolProperty;
    }
    return icon2;
  }
  SymbolKinds2.toIcon = toIcon;
  const byCompletionKind = /* @__PURE__ */ new Map();
  byCompletionKind.set(
    0,
    20
    /* CompletionItemKind.File */
  );
  byCompletionKind.set(
    1,
    8
    /* CompletionItemKind.Module */
  );
  byCompletionKind.set(
    2,
    8
    /* CompletionItemKind.Module */
  );
  byCompletionKind.set(
    3,
    8
    /* CompletionItemKind.Module */
  );
  byCompletionKind.set(
    4,
    5
    /* CompletionItemKind.Class */
  );
  byCompletionKind.set(
    5,
    0
    /* CompletionItemKind.Method */
  );
  byCompletionKind.set(
    6,
    9
    /* CompletionItemKind.Property */
  );
  byCompletionKind.set(
    7,
    3
    /* CompletionItemKind.Field */
  );
  byCompletionKind.set(
    8,
    2
    /* CompletionItemKind.Constructor */
  );
  byCompletionKind.set(
    9,
    15
    /* CompletionItemKind.Enum */
  );
  byCompletionKind.set(
    10,
    7
    /* CompletionItemKind.Interface */
  );
  byCompletionKind.set(
    11,
    1
    /* CompletionItemKind.Function */
  );
  byCompletionKind.set(
    12,
    4
    /* CompletionItemKind.Variable */
  );
  byCompletionKind.set(
    13,
    14
    /* CompletionItemKind.Constant */
  );
  byCompletionKind.set(
    14,
    18
    /* CompletionItemKind.Text */
  );
  byCompletionKind.set(
    15,
    13
    /* CompletionItemKind.Value */
  );
  byCompletionKind.set(
    16,
    13
    /* CompletionItemKind.Value */
  );
  byCompletionKind.set(
    17,
    13
    /* CompletionItemKind.Value */
  );
  byCompletionKind.set(
    18,
    13
    /* CompletionItemKind.Value */
  );
  byCompletionKind.set(
    19,
    17
    /* CompletionItemKind.Keyword */
  );
  byCompletionKind.set(
    20,
    13
    /* CompletionItemKind.Value */
  );
  byCompletionKind.set(
    21,
    16
    /* CompletionItemKind.EnumMember */
  );
  byCompletionKind.set(
    22,
    6
    /* CompletionItemKind.Struct */
  );
  byCompletionKind.set(
    23,
    10
    /* CompletionItemKind.Event */
  );
  byCompletionKind.set(
    24,
    11
    /* CompletionItemKind.Operator */
  );
  byCompletionKind.set(
    25,
    24
    /* CompletionItemKind.TypeParameter */
  );
  function toCompletionKind(kind) {
    let completionKind = byCompletionKind.get(kind);
    if (completionKind === void 0) {
      console.info("No completion kind found for SymbolKind " + kind);
      completionKind = 20;
    }
    return completionKind;
  }
  SymbolKinds2.toCompletionKind = toCompletionKind;
})(SymbolKinds || (SymbolKinds = {}));
var $VE = class {
  static asEditOperation(edit3) {
    return $bD.replace($9C.lift(edit3.range), edit3.text);
  }
};
var $WE = class _$WE {
  static {
    this.Comment = new _$WE("comment");
  }
  static {
    this.Imports = new _$WE("imports");
  }
  static {
    this.Region = new _$WE("region");
  }
  /**
   * Returns a {@link $WE} for the given value.
   *
   * @param value of the kind.
   */
  static fromValue(value) {
    switch (value) {
      case "comment":
        return _$WE.Comment;
      case "imports":
        return _$WE.Imports;
      case "region":
        return _$WE.Region;
    }
    return new _$WE(value);
  }
  /**
   * Creates a new {@link $WE}.
   *
   * @param value of the kind.
   */
  constructor(value) {
    this.value = value;
  }
};
var NewSymbolNameTag;
(function(NewSymbolNameTag4) {
  NewSymbolNameTag4[NewSymbolNameTag4["AIGenerated"] = 1] = "AIGenerated";
})(NewSymbolNameTag || (NewSymbolNameTag = {}));
var NewSymbolNameTriggerKind;
(function(NewSymbolNameTriggerKind4) {
  NewSymbolNameTriggerKind4[NewSymbolNameTriggerKind4["Invoke"] = 0] = "Invoke";
  NewSymbolNameTriggerKind4[NewSymbolNameTriggerKind4["Automatic"] = 1] = "Automatic";
})(NewSymbolNameTriggerKind || (NewSymbolNameTriggerKind = {}));
var Command;
(function(Command2) {
  function is(obj) {
    if (!obj || typeof obj !== "object") {
      return false;
    }
    return typeof obj.id === "string" && typeof obj.title === "string";
  }
  Command2.is = is;
})(Command || (Command = {}));
var CommentThreadCollapsibleState;
(function(CommentThreadCollapsibleState3) {
  CommentThreadCollapsibleState3[CommentThreadCollapsibleState3["Collapsed"] = 0] = "Collapsed";
  CommentThreadCollapsibleState3[CommentThreadCollapsibleState3["Expanded"] = 1] = "Expanded";
})(CommentThreadCollapsibleState || (CommentThreadCollapsibleState = {}));
var CommentThreadState;
(function(CommentThreadState3) {
  CommentThreadState3[CommentThreadState3["Unresolved"] = 0] = "Unresolved";
  CommentThreadState3[CommentThreadState3["Resolved"] = 1] = "Resolved";
})(CommentThreadState || (CommentThreadState = {}));
var CommentThreadApplicability;
(function(CommentThreadApplicability3) {
  CommentThreadApplicability3[CommentThreadApplicability3["Current"] = 0] = "Current";
  CommentThreadApplicability3[CommentThreadApplicability3["Outdated"] = 1] = "Outdated";
})(CommentThreadApplicability || (CommentThreadApplicability = {}));
var CommentMode;
(function(CommentMode3) {
  CommentMode3[CommentMode3["Editing"] = 0] = "Editing";
  CommentMode3[CommentMode3["Preview"] = 1] = "Preview";
})(CommentMode || (CommentMode = {}));
var CommentState;
(function(CommentState3) {
  CommentState3[CommentState3["Published"] = 0] = "Published";
  CommentState3[CommentState3["Draft"] = 1] = "Draft";
})(CommentState || (CommentState = {}));
var InlayHintKind;
(function(InlayHintKind5) {
  InlayHintKind5[InlayHintKind5["Type"] = 1] = "Type";
  InlayHintKind5[InlayHintKind5["Parameter"] = 2] = "Parameter";
})(InlayHintKind || (InlayHintKind = {}));
var $XE = class {
  constructor(b) {
    this.b = b;
    this.a = null;
  }
  dispose() {
    if (this.a) {
      this.a.then((support) => {
        if (support) {
          support.dispose();
        }
      });
    }
  }
  get tokenizationSupport() {
    if (!this.a) {
      this.a = this.b();
    }
    return this.a;
  }
};
var $YE = new $sE();
var $ZE = new $sE();
var ExternalUriOpenerPriority;
(function(ExternalUriOpenerPriority3) {
  ExternalUriOpenerPriority3[ExternalUriOpenerPriority3["None"] = 0] = "None";
  ExternalUriOpenerPriority3[ExternalUriOpenerPriority3["Option"] = 1] = "Option";
  ExternalUriOpenerPriority3[ExternalUriOpenerPriority3["Default"] = 2] = "Default";
  ExternalUriOpenerPriority3[ExternalUriOpenerPriority3["Preferred"] = 3] = "Preferred";
})(ExternalUriOpenerPriority || (ExternalUriOpenerPriority = {}));
var InlineEditTriggerKind;
(function(InlineEditTriggerKind4) {
  InlineEditTriggerKind4[InlineEditTriggerKind4["Invoke"] = 0] = "Invoke";
  InlineEditTriggerKind4[InlineEditTriggerKind4["Automatic"] = 1] = "Automatic";
})(InlineEditTriggerKind || (InlineEditTriggerKind = {}));

// out-build/vs/editor/common/viewModel/minimapTokensColorTracker.js
var $E8 = class _$E8 extends $3c {
  static {
    this.c = null;
  }
  static getInstance() {
    if (!this.c) {
      this.c = $Vc(new _$E8());
    }
    return this.c;
  }
  constructor() {
    super();
    this.j = new $ze();
    this.onDidChange = this.j.event;
    this.m();
    this.B($YE.onDidChange((e) => {
      if (e.changedColorMap) {
        this.m();
      }
    }));
  }
  m() {
    const colorMap = $YE.getColorMap();
    if (!colorMap) {
      this.f = [$A8.Empty];
      this.h = true;
      return;
    }
    this.f = [$A8.Empty];
    for (let colorId = 1; colorId < colorMap.length; colorId++) {
      const source = colorMap[colorId].rgba;
      this.f[colorId] = new $A8(source.r, source.g, source.b, Math.round(source.a * 255));
    }
    const backgroundLuminosity = colorMap[
      2
      /* ColorId.DefaultBackground */
    ].getRelativeLuminance();
    this.h = backgroundLuminosity >= 0.5;
    this.j.fire(void 0);
  }
  getColor(colorId) {
    if (colorId < 1 || colorId >= this.f.length) {
      colorId = 2;
    }
    return this.f[colorId];
  }
  backgroundIsLight() {
    return this.h;
  }
};

// out-build/vs/editor/common/viewModel.js
var $E5 = class {
  constructor(top2, left, width2, height) {
    this._viewportBrand = void 0;
    this.top = top2 | 0;
    this.left = left | 0;
    this.width = width2 | 0;
    this.height = height | 0;
  }
};
var $F5 = class {
  constructor(tabSize, data) {
    this.tabSize = tabSize;
    this.data = data;
  }
};
var $G5 = class {
  constructor(content, continuesWithWrappedLine, minColumn, maxColumn, startVisibleColumn, tokens, inlineDecorations) {
    this._viewLineDataBrand = void 0;
    this.content = content;
    this.continuesWithWrappedLine = continuesWithWrappedLine;
    this.minColumn = minColumn;
    this.maxColumn = maxColumn;
    this.startVisibleColumn = startVisibleColumn;
    this.tokens = tokens;
    this.inlineDecorations = inlineDecorations;
  }
};
var $H5 = class _$H5 {
  constructor(minColumn, maxColumn, content, continuesWithWrappedLine, mightContainRTL, mightContainNonBasicASCII, tokens, inlineDecorations, tabSize, startVisibleColumn) {
    this.minColumn = minColumn;
    this.maxColumn = maxColumn;
    this.content = content;
    this.continuesWithWrappedLine = continuesWithWrappedLine;
    this.isBasicASCII = _$H5.isBasicASCII(content, mightContainNonBasicASCII);
    this.containsRTL = _$H5.containsRTL(content, this.isBasicASCII, mightContainRTL);
    this.tokens = tokens;
    this.inlineDecorations = inlineDecorations;
    this.tabSize = tabSize;
    this.startVisibleColumn = startVisibleColumn;
  }
  static isBasicASCII(lineContent, mightContainNonBasicASCII) {
    if (mightContainNonBasicASCII) {
      return $dg(lineContent);
    }
    return true;
  }
  static containsRTL(lineContent, isBasicASCII, mightContainRTL) {
    if (!isBasicASCII && mightContainRTL) {
      return $cg(lineContent);
    }
    return false;
  }
};
var InlineDecorationType;
(function(InlineDecorationType2) {
  InlineDecorationType2[InlineDecorationType2["Regular"] = 0] = "Regular";
  InlineDecorationType2[InlineDecorationType2["Before"] = 1] = "Before";
  InlineDecorationType2[InlineDecorationType2["After"] = 2] = "After";
  InlineDecorationType2[InlineDecorationType2["RegularAffectingLetterSpacing"] = 3] = "RegularAffectingLetterSpacing";
})(InlineDecorationType || (InlineDecorationType = {}));
var $I5 = class {
  constructor(range, inlineClassName, type) {
    this.range = range;
    this.inlineClassName = inlineClassName;
    this.type = type;
  }
};
var $J5 = class {
  constructor(startOffset, endOffset, inlineClassName, inlineClassNameAffectsLetterSpacing) {
    this.startOffset = startOffset;
    this.endOffset = endOffset;
    this.inlineClassName = inlineClassName;
    this.inlineClassNameAffectsLetterSpacing = inlineClassNameAffectsLetterSpacing;
  }
  toInlineDecoration(lineNumber) {
    return new $I5(
      new $9C(lineNumber, this.startOffset + 1, lineNumber, this.endOffset + 1),
      this.inlineClassName,
      this.inlineClassNameAffectsLetterSpacing ? 3 : 0
      /* InlineDecorationType.Regular */
    );
  }
};
var $K5 = class {
  constructor(range, options3) {
    this._viewModelDecorationBrand = void 0;
    this.range = range;
    this.options = options3;
  }
};
var $L5 = class _$L5 {
  constructor(color2, zIndex, data) {
    this.color = color2;
    this.zIndex = zIndex;
    this.data = data;
  }
  static compareByRenderingProps(a, b) {
    if (a.zIndex === b.zIndex) {
      if (a.color < b.color) {
        return -1;
      }
      if (a.color > b.color) {
        return 1;
      }
      return 0;
    }
    return a.zIndex - b.zIndex;
  }
  static equals(a, b) {
    return a.color === b.color && a.zIndex === b.zIndex && $zb(a.data, b.data);
  }
  static equalsArr(a, b) {
    return $zb(a, b, _$L5.equals);
  }
};

// out-build/vs/editor/browser/viewParts/minimap/minimapCharSheet.js
var Constants4;
(function(Constants27) {
  Constants27[Constants27["START_CH_CODE"] = 32] = "START_CH_CODE";
  Constants27[Constants27["END_CH_CODE"] = 126] = "END_CH_CODE";
  Constants27[Constants27["UNKNOWN_CODE"] = 65533] = "UNKNOWN_CODE";
  Constants27[Constants27["CHAR_COUNT"] = 96] = "CHAR_COUNT";
  Constants27[Constants27["SAMPLED_CHAR_HEIGHT"] = 16] = "SAMPLED_CHAR_HEIGHT";
  Constants27[Constants27["SAMPLED_CHAR_WIDTH"] = 10] = "SAMPLED_CHAR_WIDTH";
  Constants27[Constants27["BASE_CHAR_HEIGHT"] = 2] = "BASE_CHAR_HEIGHT";
  Constants27[Constants27["BASE_CHAR_WIDTH"] = 1] = "BASE_CHAR_WIDTH";
  Constants27[Constants27["RGBA_CHANNELS_CNT"] = 4] = "RGBA_CHANNELS_CNT";
  Constants27[Constants27["RGBA_SAMPLED_ROW_WIDTH"] = 3840] = "RGBA_SAMPLED_ROW_WIDTH";
})(Constants4 || (Constants4 = {}));
var $B8 = (() => {
  const v = [];
  for (let i2 = 32; i2 <= 126; i2++) {
    v.push(i2);
  }
  v.push(
    65533
    /* Constants.UNKNOWN_CODE */
  );
  return v;
})();
var $C8 = (chCode, fontScale) => {
  chCode -= 32;
  if (chCode < 0 || chCode > 96) {
    if (fontScale <= 2) {
      return (chCode + 96) % 96;
    }
    return 96 - 1;
  }
  return chCode;
};

// out-build/vs/editor/browser/viewParts/minimap/minimapCharRenderer.js
var $D8 = class _$D8 {
  constructor(charData, scale) {
    this.scale = scale;
    this._minimapCharRendererBrand = void 0;
    this.a = _$D8.e(charData, 12 / 15);
    this.d = _$D8.e(charData, 50 / 60);
  }
  static e(input, ratio) {
    const result = new Uint8ClampedArray(input.length);
    for (let i2 = 0, len = input.length; i2 < len; i2++) {
      result[i2] = $tf(input[i2] * ratio);
    }
    return result;
  }
  renderChar(target, dx, dy, chCode, color2, foregroundAlpha, backgroundColor, backgroundAlpha, fontScale, useLighterFont, force1pxHeight) {
    const charWidth = 1 * this.scale;
    const charHeight = 2 * this.scale;
    const renderHeight = force1pxHeight ? 1 : charHeight;
    if (dx + charWidth > target.width || dy + renderHeight > target.height) {
      console.warn("bad render request outside image data");
      return;
    }
    const charData = useLighterFont ? this.d : this.a;
    const charIndex = $C8(chCode, fontScale);
    const destWidth = target.width * 4;
    const backgroundR = backgroundColor.r;
    const backgroundG = backgroundColor.g;
    const backgroundB = backgroundColor.b;
    const deltaR = color2.r - backgroundR;
    const deltaG = color2.g - backgroundG;
    const deltaB = color2.b - backgroundB;
    const destAlpha = Math.max(foregroundAlpha, backgroundAlpha);
    const dest = target.data;
    let sourceOffset = charIndex * charWidth * charHeight;
    let row = dy * destWidth + dx * 4;
    for (let y = 0; y < renderHeight; y++) {
      let column = row;
      for (let x = 0; x < charWidth; x++) {
        const c = charData[sourceOffset++] / 255 * (foregroundAlpha / 255);
        dest[column++] = backgroundR + deltaR * c;
        dest[column++] = backgroundG + deltaG * c;
        dest[column++] = backgroundB + deltaB * c;
        dest[column++] = destAlpha;
      }
      row += destWidth;
    }
  }
  blockRenderChar(target, dx, dy, color2, foregroundAlpha, backgroundColor, backgroundAlpha, force1pxHeight) {
    const charWidth = 1 * this.scale;
    const charHeight = 2 * this.scale;
    const renderHeight = force1pxHeight ? 1 : charHeight;
    if (dx + charWidth > target.width || dy + renderHeight > target.height) {
      console.warn("bad render request outside image data");
      return;
    }
    const destWidth = target.width * 4;
    const c = 0.5 * (foregroundAlpha / 255);
    const backgroundR = backgroundColor.r;
    const backgroundG = backgroundColor.g;
    const backgroundB = backgroundColor.b;
    const deltaR = color2.r - backgroundR;
    const deltaG = color2.g - backgroundG;
    const deltaB = color2.b - backgroundB;
    const colorR = backgroundR + deltaR * c;
    const colorG = backgroundG + deltaG * c;
    const colorB = backgroundB + deltaB * c;
    const destAlpha = Math.max(foregroundAlpha, backgroundAlpha);
    const dest = target.data;
    let row = dy * destWidth + dx * 4;
    for (let y = 0; y < renderHeight; y++) {
      let column = row;
      for (let x = 0; x < charWidth; x++) {
        dest[column++] = colorR;
        dest[column++] = colorG;
        dest[column++] = colorB;
        dest[column++] = destAlpha;
      }
      row += destWidth;
    }
  }
};

// out-build/vs/editor/browser/viewParts/minimap/minimapPreBaked.js
var charTable = {
  "0": 0,
  "1": 1,
  "2": 2,
  "3": 3,
  "4": 4,
  "5": 5,
  "6": 6,
  "7": 7,
  "8": 8,
  "9": 9,
  A: 10,
  B: 11,
  C: 12,
  D: 13,
  E: 14,
  F: 15
};
var decodeData = (str) => {
  const output = new Uint8ClampedArray(str.length / 2);
  for (let i2 = 0; i2 < str.length; i2 += 2) {
    output[i2 >> 1] = charTable[str[i2]] << 4 | charTable[str[i2 + 1]] & 15;
  }
  return output;
};
var $F8 = {
  1: $Qc(() => decodeData("0000511D6300CF609C709645A78432005642574171487021003C451900274D35D762755E8B629C5BA856AF57BA649530C167D1512A272A3F6038604460398526BCA2A968DB6F8957C768BE5FBE2FB467CF5D8D5B795DC7625B5DFF50DE64C466DB2FC47CD860A65E9A2EB96CB54CE06DA763AB2EA26860524D3763536601005116008177A8705E53AB738E6A982F88BAA35B5F5B626D9C636B449B737E5B7B678598869A662F6B5B8542706C704C80736A607578685B70594A49715A4522E792")),
  2: $Qc(() => decodeData("000000000000000055394F383D2800008B8B1F210002000081B1CBCBCC820000847AAF6B9AAF2119BE08B8881AD60000A44FD07DCCF107015338130C00000000385972265F390B406E2437634B4B48031B12B8A0847000001E15B29A402F0000000000004B33460B00007A752C2A0000000000004D3900000084394B82013400ABA5CFC7AD9C0302A45A3E5A98AB000089A43382D97900008BA54AA087A70A0248A6A7AE6DBE0000BF6F94987EA40A01A06DCFA7A7A9030496C32F77891D0000A99FB1A0AFA80603B29AB9CA75930D010C0948354D3900000C0948354F37460D0028BE673D8400000000AF9D7B6E00002B007AA8933400007AA642675C2700007984CFB9C3985B768772A8A6B7B20000CAAECAAFC4B700009F94A6009F840009D09F9BA4CA9C0000CC8FC76DC87F0000C991C472A2000000A894A48CA7B501079BA2C9C69BA20000B19A5D3FA89000005CA6009DA2960901B0A7F0669FB200009D009E00B7890000DAD0F5D092820000D294D4C48BD10000B5A7A4A3B1A50402CAB6CBA6A2000000B5A7A4A3B1A8044FCDADD19D9CB00000B7778F7B8AAE0803C9AB5D3F5D3F00009EA09EA0BAB006039EA0989A8C7900009B9EF4D6B7C00000A9A7816CACA80000ABAC84705D3F000096DA635CDC8C00006F486F266F263D4784006124097B00374F6D2D6D2D6D4A3A95872322000000030000000000008D8939130000000000002E22A5C9CBC70600AB25C0B5C9B400061A2DB04CA67001082AA6BEBEBFC606002321DACBC19E03087AA08B6768380000282FBAC0B8CA7A88AD25BBA5A29900004C396C5894A6000040485A6E356E9442A32CD17EADA70000B4237923628600003E2DE9C1D7B500002F25BBA5A2990000231DB6AFB4A804023025C0B5CAB588062B2CBDBEC0C706882435A75CA20000002326BD6A82A908048B4B9A5A668000002423A09CB4BB060025259C9D8A7900001C1FCAB2C7C700002A2A9387ABA200002626A4A47D6E9D14333163A0C87500004B6F9C2D643A257049364936493647358A34438355497F1A0000A24C1D590000D38DFFBDD4CD3126"))
};

// out-build/vs/editor/browser/viewParts/minimap/minimapCharRendererFactory.js
var $G8 = class _$G8 {
  /**
   * Creates a new character renderer factory with the given scale.
   */
  static create(scale, fontFamily) {
    if (this.a && scale === this.a.scale && fontFamily === this.b) {
      return this.a;
    }
    let factory;
    if ($F8[scale]) {
      factory = new $D8($F8[scale](), scale);
    } else {
      factory = _$G8.createFromSampleData(_$G8.createSampleData(fontFamily).data, scale);
    }
    this.b = fontFamily;
    this.a = factory;
    return factory;
  }
  /**
   * Creates the font sample data, writing to a canvas.
   */
  static createSampleData(fontFamily) {
    const canvas = document.createElement("canvas");
    const ctx = canvas.getContext("2d");
    canvas.style.height = `${16}px`;
    canvas.height = 16;
    canvas.width = 96 * 10;
    canvas.style.width = 96 * 10 + "px";
    ctx.fillStyle = "#ffffff";
    ctx.font = `bold ${16}px ${fontFamily}`;
    ctx.textBaseline = "middle";
    let x = 0;
    for (const code of $B8) {
      ctx.fillText(String.fromCharCode(code), x, 16 / 2);
      x += 10;
    }
    return ctx.getImageData(
      0,
      0,
      96 * 10,
      16
      /* Constants.SAMPLED_CHAR_HEIGHT */
    );
  }
  /**
   * Creates a character renderer from the canvas sample data.
   */
  static createFromSampleData(source, scale) {
    const expectedLength = 16 * 10 * 4 * 96;
    if (source.length !== expectedLength) {
      throw new Error("Unexpected source in MinimapCharRenderer");
    }
    const charData = _$G8.d(source, scale);
    return new $D8(charData, scale);
  }
  static c(source, sourceOffset, dest, destOffset, scale) {
    const width2 = 1 * scale;
    const height = 2 * scale;
    let targetIndex = destOffset;
    let brightest = 0;
    for (let y = 0; y < height; y++) {
      const sourceY1 = y / height * 16;
      const sourceY2 = (y + 1) / height * 16;
      for (let x = 0; x < width2; x++) {
        const sourceX1 = x / width2 * 10;
        const sourceX2 = (x + 1) / width2 * 10;
        let value = 0;
        let samples = 0;
        for (let sy = sourceY1; sy < sourceY2; sy++) {
          const sourceRow = sourceOffset + Math.floor(sy) * 3840;
          const yBalance = 1 - (sy - Math.floor(sy));
          for (let sx = sourceX1; sx < sourceX2; sx++) {
            const xBalance = 1 - (sx - Math.floor(sx));
            const sourceIndex = sourceRow + Math.floor(sx) * 4;
            const weight5 = xBalance * yBalance;
            samples += weight5;
            value += source[sourceIndex] * source[sourceIndex + 3] / 255 * weight5;
          }
        }
        const final = value / samples;
        brightest = Math.max(brightest, final);
        dest[targetIndex++] = $tf(final);
      }
    }
    return brightest;
  }
  static d(data, scale) {
    const pixelsPerCharacter = 2 * scale * 1 * scale;
    const resultLen = pixelsPerCharacter * 96;
    const result = new Uint8ClampedArray(resultLen);
    let resultOffset = 0;
    let sourceOffset = 0;
    let brightest = 0;
    for (let charIndex = 0; charIndex < 96; charIndex++) {
      brightest = Math.max(brightest, this.c(data, sourceOffset, result, resultOffset, scale));
      resultOffset += pixelsPerCharacter;
      sourceOffset += 10 * 4;
    }
    if (brightest > 0) {
      const adjust = 255 / brightest;
      for (let i2 = 0; i2 < resultLen; i2++) {
        result[i2] *= adjust;
      }
    }
    return result;
  }
};

// out-build/vs/base/browser/fonts.js
var $91 = $l ? '"Segoe WPC", "Segoe UI", sans-serif' : $m ? "-apple-system, BlinkMacSystemFont, sans-serif" : 'system-ui, "Ubuntu", "Droid Sans", sans-serif';

// out-build/vs/editor/browser/viewParts/minimap/minimap.js
var POINTER_DRAG_RESET_DISTANCE2 = 140;
var GUTTER_DECORATION_WIDTH = 2;
var MinimapOptions = class _MinimapOptions {
  constructor(configuration2, theme, tokensColorTracker) {
    const options3 = configuration2.options;
    const pixelRatio = options3.get(
      149
      /* EditorOption.pixelRatio */
    );
    const layoutInfo = options3.get(
      151
      /* EditorOption.layoutInfo */
    );
    const minimapLayout = layoutInfo.minimap;
    const fontInfo = options3.get(
      52
      /* EditorOption.fontInfo */
    );
    const minimapOpts = options3.get(
      74
      /* EditorOption.minimap */
    );
    this.renderMinimap = minimapLayout.renderMinimap;
    this.size = minimapOpts.size;
    this.minimapHeightIsEditorHeight = minimapLayout.minimapHeightIsEditorHeight;
    this.scrollBeyondLastLine = options3.get(
      110
      /* EditorOption.scrollBeyondLastLine */
    );
    this.paddingTop = options3.get(
      88
      /* EditorOption.padding */
    ).top;
    this.paddingBottom = options3.get(
      88
      /* EditorOption.padding */
    ).bottom;
    this.showSlider = minimapOpts.showSlider;
    this.autohide = minimapOpts.autohide;
    this.pixelRatio = pixelRatio;
    this.typicalHalfwidthCharacterWidth = fontInfo.typicalHalfwidthCharacterWidth;
    this.lineHeight = options3.get(
      68
      /* EditorOption.lineHeight */
    );
    this.minimapLeft = minimapLayout.minimapLeft;
    this.minimapWidth = minimapLayout.minimapWidth;
    this.minimapHeight = layoutInfo.height;
    this.canvasInnerWidth = minimapLayout.minimapCanvasInnerWidth;
    this.canvasInnerHeight = minimapLayout.minimapCanvasInnerHeight;
    this.canvasOuterWidth = minimapLayout.minimapCanvasOuterWidth;
    this.canvasOuterHeight = minimapLayout.minimapCanvasOuterHeight;
    this.isSampling = minimapLayout.minimapIsSampling;
    this.editorHeight = layoutInfo.height;
    this.fontScale = minimapLayout.minimapScale;
    this.minimapLineHeight = minimapLayout.minimapLineHeight;
    this.minimapCharWidth = 1 * this.fontScale;
    this.sectionHeaderFontFamily = $91;
    this.sectionHeaderFontSize = minimapOpts.sectionHeaderFontSize * pixelRatio;
    this.sectionHeaderLetterSpacing = minimapOpts.sectionHeaderLetterSpacing;
    this.sectionHeaderFontColor = _MinimapOptions.f(theme, tokensColorTracker.getColor(
      1
      /* ColorId.DefaultForeground */
    ));
    this.charRenderer = $Qc(() => $G8.create(this.fontScale, fontInfo.fontFamily));
    this.defaultBackgroundColor = tokensColorTracker.getColor(
      2
      /* ColorId.DefaultBackground */
    );
    this.backgroundColor = _MinimapOptions.c(theme, this.defaultBackgroundColor);
    this.foregroundAlpha = _MinimapOptions.d(theme);
  }
  static c(theme, defaultBackgroundColor) {
    const themeColor = theme.getColor($kq);
    if (themeColor) {
      return new $A8(themeColor.rgba.r, themeColor.rgba.g, themeColor.rgba.b, Math.round(255 * themeColor.rgba.a));
    }
    return defaultBackgroundColor;
  }
  static d(theme) {
    const themeColor = theme.getColor($lq);
    if (themeColor) {
      return $A8._clamp(Math.round(255 * themeColor.rgba.a));
    }
    return 255;
  }
  static f(theme, defaultForegroundColor) {
    const themeColor = theme.getColor($Lo);
    if (themeColor) {
      return new $A8(themeColor.rgba.r, themeColor.rgba.g, themeColor.rgba.b, Math.round(255 * themeColor.rgba.a));
    }
    return defaultForegroundColor;
  }
  equals(other) {
    return this.renderMinimap === other.renderMinimap && this.size === other.size && this.minimapHeightIsEditorHeight === other.minimapHeightIsEditorHeight && this.scrollBeyondLastLine === other.scrollBeyondLastLine && this.paddingTop === other.paddingTop && this.paddingBottom === other.paddingBottom && this.showSlider === other.showSlider && this.autohide === other.autohide && this.pixelRatio === other.pixelRatio && this.typicalHalfwidthCharacterWidth === other.typicalHalfwidthCharacterWidth && this.lineHeight === other.lineHeight && this.minimapLeft === other.minimapLeft && this.minimapWidth === other.minimapWidth && this.minimapHeight === other.minimapHeight && this.canvasInnerWidth === other.canvasInnerWidth && this.canvasInnerHeight === other.canvasInnerHeight && this.canvasOuterWidth === other.canvasOuterWidth && this.canvasOuterHeight === other.canvasOuterHeight && this.isSampling === other.isSampling && this.editorHeight === other.editorHeight && this.fontScale === other.fontScale && this.minimapLineHeight === other.minimapLineHeight && this.minimapCharWidth === other.minimapCharWidth && this.sectionHeaderFontSize === other.sectionHeaderFontSize && this.sectionHeaderLetterSpacing === other.sectionHeaderLetterSpacing && this.defaultBackgroundColor && this.defaultBackgroundColor.equals(other.defaultBackgroundColor) && this.backgroundColor && this.backgroundColor.equals(other.backgroundColor) && this.foregroundAlpha === other.foregroundAlpha;
  }
};
var MinimapLayout = class _MinimapLayout {
  constructor(scrollTop, scrollHeight, sliderNeeded, c, sliderTop, sliderHeight, topPaddingLineCount, startLineNumber, endLineNumber) {
    this.scrollTop = scrollTop;
    this.scrollHeight = scrollHeight;
    this.sliderNeeded = sliderNeeded;
    this.c = c;
    this.sliderTop = sliderTop;
    this.sliderHeight = sliderHeight;
    this.topPaddingLineCount = topPaddingLineCount;
    this.startLineNumber = startLineNumber;
    this.endLineNumber = endLineNumber;
  }
  /**
   * Compute a desired `scrollPosition` such that the slider moves by `delta`.
   */
  getDesiredScrollTopFromDelta(delta) {
    return Math.round(this.scrollTop + delta / this.c);
  }
  getDesiredScrollTopFromTouchLocation(pageY) {
    return Math.round((pageY - this.sliderHeight / 2) / this.c);
  }
  /**
   * Intersect a line range with `this.startLineNumber` and `this.endLineNumber`.
   */
  intersectWithViewport(range) {
    const startLineNumber = Math.max(this.startLineNumber, range.startLineNumber);
    const endLineNumber = Math.min(this.endLineNumber, range.endLineNumber);
    if (startLineNumber > endLineNumber) {
      return null;
    }
    return [startLineNumber, endLineNumber];
  }
  /**
   * Get the inner minimap y coordinate for a line number.
   */
  getYForLineNumber(lineNumber, minimapLineHeight) {
    return +(lineNumber - this.startLineNumber + this.topPaddingLineCount) * minimapLineHeight;
  }
  static create(options3, viewportStartLineNumber, viewportEndLineNumber, viewportStartLineNumberVerticalOffset, viewportHeight, viewportContainsWhitespaceGaps, lineCount, realLineCount, scrollTop, scrollHeight, previousLayout) {
    const pixelRatio = options3.pixelRatio;
    const minimapLineHeight = options3.minimapLineHeight;
    const minimapLinesFitting = Math.floor(options3.canvasInnerHeight / minimapLineHeight);
    const lineHeight = options3.lineHeight;
    if (options3.minimapHeightIsEditorHeight) {
      let logicalScrollHeight = realLineCount * options3.lineHeight + options3.paddingTop + options3.paddingBottom;
      if (options3.scrollBeyondLastLine) {
        logicalScrollHeight += Math.max(0, viewportHeight - options3.lineHeight - options3.paddingBottom);
      }
      const sliderHeight2 = Math.max(1, Math.floor(viewportHeight * viewportHeight / logicalScrollHeight));
      const maxMinimapSliderTop2 = Math.max(0, options3.minimapHeight - sliderHeight2);
      const computedSliderRatio2 = maxMinimapSliderTop2 / (scrollHeight - viewportHeight);
      const sliderTop2 = scrollTop * computedSliderRatio2;
      const sliderNeeded = maxMinimapSliderTop2 > 0;
      const maxLinesFitting = Math.floor(options3.canvasInnerHeight / options3.minimapLineHeight);
      const topPaddingLineCount = Math.floor(options3.paddingTop / options3.lineHeight);
      return new _MinimapLayout(scrollTop, scrollHeight, sliderNeeded, computedSliderRatio2, sliderTop2, sliderHeight2, topPaddingLineCount, 1, Math.min(lineCount, maxLinesFitting));
    }
    let sliderHeight;
    if (viewportContainsWhitespaceGaps && viewportEndLineNumber !== lineCount) {
      const viewportLineCount = viewportEndLineNumber - viewportStartLineNumber + 1;
      sliderHeight = Math.floor(viewportLineCount * minimapLineHeight / pixelRatio);
    } else {
      const expectedViewportLineCount = viewportHeight / lineHeight;
      sliderHeight = Math.floor(expectedViewportLineCount * minimapLineHeight / pixelRatio);
    }
    const extraLinesAtTheTop = Math.floor(options3.paddingTop / lineHeight);
    let extraLinesAtTheBottom = Math.floor(options3.paddingBottom / lineHeight);
    if (options3.scrollBeyondLastLine) {
      const expectedViewportLineCount = viewportHeight / lineHeight;
      extraLinesAtTheBottom = Math.max(extraLinesAtTheBottom, expectedViewportLineCount - 1);
    }
    let maxMinimapSliderTop;
    if (extraLinesAtTheBottom > 0) {
      const expectedViewportLineCount = viewportHeight / lineHeight;
      maxMinimapSliderTop = (extraLinesAtTheTop + lineCount + extraLinesAtTheBottom - expectedViewportLineCount - 1) * minimapLineHeight / pixelRatio;
    } else {
      maxMinimapSliderTop = Math.max(0, (extraLinesAtTheTop + lineCount) * minimapLineHeight / pixelRatio - sliderHeight);
    }
    maxMinimapSliderTop = Math.min(options3.minimapHeight - sliderHeight, maxMinimapSliderTop);
    const computedSliderRatio = maxMinimapSliderTop / (scrollHeight - viewportHeight);
    const sliderTop = scrollTop * computedSliderRatio;
    if (minimapLinesFitting >= extraLinesAtTheTop + lineCount + extraLinesAtTheBottom) {
      const sliderNeeded = maxMinimapSliderTop > 0;
      return new _MinimapLayout(scrollTop, scrollHeight, sliderNeeded, computedSliderRatio, sliderTop, sliderHeight, extraLinesAtTheTop, 1, lineCount);
    } else {
      let consideringStartLineNumber;
      if (viewportStartLineNumber > 1) {
        consideringStartLineNumber = viewportStartLineNumber + extraLinesAtTheTop;
      } else {
        consideringStartLineNumber = Math.max(1, scrollTop / lineHeight);
      }
      let topPaddingLineCount;
      let startLineNumber = Math.max(1, Math.floor(consideringStartLineNumber - sliderTop * pixelRatio / minimapLineHeight));
      if (startLineNumber < extraLinesAtTheTop) {
        topPaddingLineCount = extraLinesAtTheTop - startLineNumber + 1;
        startLineNumber = 1;
      } else {
        topPaddingLineCount = 0;
        startLineNumber = Math.max(1, startLineNumber - extraLinesAtTheTop);
      }
      if (previousLayout && previousLayout.scrollHeight === scrollHeight) {
        if (previousLayout.scrollTop > scrollTop) {
          startLineNumber = Math.min(startLineNumber, previousLayout.startLineNumber);
          topPaddingLineCount = Math.max(topPaddingLineCount, previousLayout.topPaddingLineCount);
        }
        if (previousLayout.scrollTop < scrollTop) {
          startLineNumber = Math.max(startLineNumber, previousLayout.startLineNumber);
          topPaddingLineCount = Math.min(topPaddingLineCount, previousLayout.topPaddingLineCount);
        }
      }
      const endLineNumber = Math.min(lineCount, startLineNumber - topPaddingLineCount + minimapLinesFitting - 1);
      const partialLine = (scrollTop - viewportStartLineNumberVerticalOffset) / lineHeight;
      let sliderTopAligned;
      if (scrollTop >= options3.paddingTop) {
        sliderTopAligned = (viewportStartLineNumber - startLineNumber + topPaddingLineCount + partialLine) * minimapLineHeight / pixelRatio;
      } else {
        sliderTopAligned = scrollTop / options3.paddingTop * (topPaddingLineCount + partialLine) * minimapLineHeight / pixelRatio;
      }
      return new _MinimapLayout(scrollTop, scrollHeight, true, computedSliderRatio, sliderTopAligned, sliderHeight, topPaddingLineCount, startLineNumber, endLineNumber);
    }
  }
};
var MinimapLine = class _MinimapLine {
  static {
    this.INVALID = new _MinimapLine(-1);
  }
  constructor(dy) {
    this.dy = dy;
  }
  onContentChanged() {
    this.dy = -1;
  }
  onTokensChanged() {
    this.dy = -1;
  }
};
var RenderData = class {
  constructor(renderedLayout, imageData, lines) {
    this.renderedLayout = renderedLayout;
    this.c = imageData;
    this.d = new $h7({
      createLine: () => MinimapLine.INVALID
    });
    this.d._set(renderedLayout.startLineNumber, lines);
  }
  /**
   * Check if the current RenderData matches accurately the new desired layout and no painting is needed.
   */
  linesEquals(layout) {
    if (!this.scrollEquals(layout)) {
      return false;
    }
    const tmp = this.d._get();
    const lines = tmp.lines;
    for (let i2 = 0, len = lines.length; i2 < len; i2++) {
      if (lines[i2].dy === -1) {
        return false;
      }
    }
    return true;
  }
  /**
   * Check if the current RenderData matches the new layout's scroll position
   */
  scrollEquals(layout) {
    return this.renderedLayout.startLineNumber === layout.startLineNumber && this.renderedLayout.endLineNumber === layout.endLineNumber;
  }
  _get() {
    const tmp = this.d._get();
    return {
      imageData: this.c,
      rendLineNumberStart: tmp.rendLineNumberStart,
      lines: tmp.lines
    };
  }
  onLinesChanged(changeFromLineNumber, changeCount) {
    return this.d.onLinesChanged(changeFromLineNumber, changeCount);
  }
  onLinesDeleted(deleteFromLineNumber, deleteToLineNumber) {
    this.d.onLinesDeleted(deleteFromLineNumber, deleteToLineNumber);
  }
  onLinesInserted(insertFromLineNumber, insertToLineNumber) {
    this.d.onLinesInserted(insertFromLineNumber, insertToLineNumber);
  }
  onTokensChanged(ranges) {
    return this.d.onTokensChanged(ranges);
  }
};
var MinimapBuffers = class _MinimapBuffers {
  constructor(ctx, WIDTH, HEIGHT, background) {
    this.c = _MinimapBuffers.h(WIDTH, HEIGHT, background);
    this.d = [
      ctx.createImageData(WIDTH, HEIGHT),
      ctx.createImageData(WIDTH, HEIGHT)
    ];
    this.f = 0;
  }
  getBuffer() {
    this.f = 1 - this.f;
    const result = this.d[this.f];
    result.data.set(this.c);
    return result;
  }
  static h(WIDTH, HEIGHT, background) {
    const backgroundR = background.r;
    const backgroundG = background.g;
    const backgroundB = background.b;
    const backgroundA = background.a;
    const result = new Uint8ClampedArray(WIDTH * HEIGHT * 4);
    let offset = 0;
    for (let i2 = 0; i2 < HEIGHT; i2++) {
      for (let j = 0; j < WIDTH; j++) {
        result[offset] = backgroundR;
        result[offset + 1] = backgroundG;
        result[offset + 2] = backgroundB;
        result[offset + 3] = backgroundA;
        offset += 4;
      }
    }
    return result;
  }
};
var MinimapSamplingState = class _MinimapSamplingState {
  static compute(options3, viewLineCount, oldSamplingState) {
    if (options3.renderMinimap === 0 || !options3.isSampling) {
      return [null, []];
    }
    const { minimapLineCount } = EditorLayoutInfoComputer.computeContainedMinimapLineCount({
      viewLineCount,
      scrollBeyondLastLine: options3.scrollBeyondLastLine,
      paddingTop: options3.paddingTop,
      paddingBottom: options3.paddingBottom,
      height: options3.editorHeight,
      lineHeight: options3.lineHeight,
      pixelRatio: options3.pixelRatio
    });
    const ratio = viewLineCount / minimapLineCount;
    const halfRatio = ratio / 2;
    if (!oldSamplingState || oldSamplingState.minimapLines.length === 0) {
      const result2 = [];
      result2[0] = 1;
      if (minimapLineCount > 1) {
        for (let i2 = 0, lastIndex = minimapLineCount - 1; i2 < lastIndex; i2++) {
          result2[i2] = Math.round(i2 * ratio + halfRatio);
        }
        result2[minimapLineCount - 1] = viewLineCount;
      }
      return [new _MinimapSamplingState(ratio, result2), []];
    }
    const oldMinimapLines = oldSamplingState.minimapLines;
    const oldLength = oldMinimapLines.length;
    const result = [];
    let oldIndex = 0;
    let oldDeltaLineCount = 0;
    let minViewLineNumber = 1;
    const MAX_EVENT_COUNT = 10;
    let events = [];
    let lastEvent = null;
    for (let i2 = 0; i2 < minimapLineCount; i2++) {
      const fromViewLineNumber = Math.max(minViewLineNumber, Math.round(i2 * ratio));
      const toViewLineNumber = Math.max(fromViewLineNumber, Math.round((i2 + 1) * ratio));
      while (oldIndex < oldLength && oldMinimapLines[oldIndex] < fromViewLineNumber) {
        if (events.length < MAX_EVENT_COUNT) {
          const oldMinimapLineNumber = oldIndex + 1 + oldDeltaLineCount;
          if (lastEvent && lastEvent.type === "deleted" && lastEvent._oldIndex === oldIndex - 1) {
            lastEvent.deleteToLineNumber++;
          } else {
            lastEvent = { type: "deleted", _oldIndex: oldIndex, deleteFromLineNumber: oldMinimapLineNumber, deleteToLineNumber: oldMinimapLineNumber };
            events.push(lastEvent);
          }
          oldDeltaLineCount--;
        }
        oldIndex++;
      }
      let selectedViewLineNumber;
      if (oldIndex < oldLength && oldMinimapLines[oldIndex] <= toViewLineNumber) {
        selectedViewLineNumber = oldMinimapLines[oldIndex];
        oldIndex++;
      } else {
        if (i2 === 0) {
          selectedViewLineNumber = 1;
        } else if (i2 + 1 === minimapLineCount) {
          selectedViewLineNumber = viewLineCount;
        } else {
          selectedViewLineNumber = Math.round(i2 * ratio + halfRatio);
        }
        if (events.length < MAX_EVENT_COUNT) {
          const oldMinimapLineNumber = oldIndex + 1 + oldDeltaLineCount;
          if (lastEvent && lastEvent.type === "inserted" && lastEvent._i === i2 - 1) {
            lastEvent.insertToLineNumber++;
          } else {
            lastEvent = { type: "inserted", _i: i2, insertFromLineNumber: oldMinimapLineNumber, insertToLineNumber: oldMinimapLineNumber };
            events.push(lastEvent);
          }
          oldDeltaLineCount++;
        }
      }
      result[i2] = selectedViewLineNumber;
      minViewLineNumber = selectedViewLineNumber;
    }
    if (events.length < MAX_EVENT_COUNT) {
      while (oldIndex < oldLength) {
        const oldMinimapLineNumber = oldIndex + 1 + oldDeltaLineCount;
        if (lastEvent && lastEvent.type === "deleted" && lastEvent._oldIndex === oldIndex - 1) {
          lastEvent.deleteToLineNumber++;
        } else {
          lastEvent = { type: "deleted", _oldIndex: oldIndex, deleteFromLineNumber: oldMinimapLineNumber, deleteToLineNumber: oldMinimapLineNumber };
          events.push(lastEvent);
        }
        oldDeltaLineCount--;
        oldIndex++;
      }
    } else {
      events = [{ type: "flush" }];
    }
    return [new _MinimapSamplingState(ratio, result), events];
  }
  constructor(samplingRatio, minimapLines) {
    this.samplingRatio = samplingRatio;
    this.minimapLines = minimapLines;
  }
  modelLineToMinimapLine(lineNumber) {
    return Math.min(this.minimapLines.length, Math.max(1, Math.round(lineNumber / this.samplingRatio)));
  }
  /**
   * Will return null if the model line ranges are not intersecting with a sampled model line.
   */
  modelLineRangeToMinimapLineRange(fromLineNumber, toLineNumber) {
    let fromLineIndex = this.modelLineToMinimapLine(fromLineNumber) - 1;
    while (fromLineIndex > 0 && this.minimapLines[fromLineIndex - 1] >= fromLineNumber) {
      fromLineIndex--;
    }
    let toLineIndex2 = this.modelLineToMinimapLine(toLineNumber) - 1;
    while (toLineIndex2 + 1 < this.minimapLines.length && this.minimapLines[toLineIndex2 + 1] <= toLineNumber) {
      toLineIndex2++;
    }
    if (fromLineIndex === toLineIndex2) {
      const sampledLineNumber = this.minimapLines[fromLineIndex];
      if (sampledLineNumber < fromLineNumber || sampledLineNumber > toLineNumber) {
        return null;
      }
    }
    return [fromLineIndex + 1, toLineIndex2 + 1];
  }
  /**
   * Will always return a range, even if it is not intersecting with a sampled model line.
   */
  decorationLineRangeToMinimapLineRange(startLineNumber, endLineNumber) {
    let minimapLineStart = this.modelLineToMinimapLine(startLineNumber);
    let minimapLineEnd = this.modelLineToMinimapLine(endLineNumber);
    if (startLineNumber !== endLineNumber && minimapLineEnd === minimapLineStart) {
      if (minimapLineEnd === this.minimapLines.length) {
        if (minimapLineStart > 1) {
          minimapLineStart--;
        }
      } else {
        minimapLineEnd++;
      }
    }
    return [minimapLineStart, minimapLineEnd];
  }
  onLinesDeleted(e) {
    const deletedLineCount = e.toLineNumber - e.fromLineNumber + 1;
    let changeStartIndex = this.minimapLines.length;
    let changeEndIndex = 0;
    for (let i2 = this.minimapLines.length - 1; i2 >= 0; i2--) {
      if (this.minimapLines[i2] < e.fromLineNumber) {
        break;
      }
      if (this.minimapLines[i2] <= e.toLineNumber) {
        this.minimapLines[i2] = Math.max(1, e.fromLineNumber - 1);
        changeStartIndex = Math.min(changeStartIndex, i2);
        changeEndIndex = Math.max(changeEndIndex, i2);
      } else {
        this.minimapLines[i2] -= deletedLineCount;
      }
    }
    return [changeStartIndex, changeEndIndex];
  }
  onLinesInserted(e) {
    const insertedLineCount = e.toLineNumber - e.fromLineNumber + 1;
    for (let i2 = this.minimapLines.length - 1; i2 >= 0; i2--) {
      if (this.minimapLines[i2] < e.fromLineNumber) {
        break;
      }
      this.minimapLines[i2] += insertedLineCount;
    }
  }
};
var $H8 = class extends $f7 {
  constructor(context) {
    super(context);
    this.t = new $Hc(10, 1.5);
    this.tokensColorTracker = $E8.getInstance();
    this.c = [];
    this.f = null;
    this.options = new MinimapOptions(this._context.configuration, this._context.theme, this.tokensColorTracker);
    const [samplingState] = MinimapSamplingState.compute(this.options, this._context.viewModel.getLineCount(), null);
    this.h = samplingState;
    this.n = false;
    this.w = new InnerMinimap(context.theme, this);
  }
  dispose() {
    this.w.dispose();
    super.dispose();
  }
  getDomNode() {
    return this.w.getDomNode();
  }
  z() {
    const opts = new MinimapOptions(this._context.configuration, this._context.theme, this.tokensColorTracker);
    if (this.options.equals(opts)) {
      return false;
    }
    this.options = opts;
    this.C();
    this.w.onDidChangeOptions();
    return true;
  }
  // ---- begin view event handlers
  onConfigurationChanged(e) {
    return this.z();
  }
  onCursorStateChanged(e) {
    this.c = e.selections;
    this.f = null;
    return this.w.onSelectionChanged();
  }
  onDecorationsChanged(e) {
    if (e.affectsMinimap) {
      return this.w.onDecorationsChanged();
    }
    return false;
  }
  onFlushed(e) {
    if (this.h) {
      this.n = true;
    }
    return this.w.onFlushed();
  }
  onLinesChanged(e) {
    if (this.h) {
      const minimapLineRange = this.h.modelLineRangeToMinimapLineRange(e.fromLineNumber, e.fromLineNumber + e.count - 1);
      if (minimapLineRange) {
        return this.w.onLinesChanged(minimapLineRange[0], minimapLineRange[1] - minimapLineRange[0] + 1);
      } else {
        return false;
      }
    } else {
      return this.w.onLinesChanged(e.fromLineNumber, e.count);
    }
  }
  onLinesDeleted(e) {
    if (this.h) {
      const [changeStartIndex, changeEndIndex] = this.h.onLinesDeleted(e);
      if (changeStartIndex <= changeEndIndex) {
        this.w.onLinesChanged(changeStartIndex + 1, changeEndIndex - changeStartIndex + 1);
      }
      this.n = true;
      return true;
    } else {
      return this.w.onLinesDeleted(e.fromLineNumber, e.toLineNumber);
    }
  }
  onLinesInserted(e) {
    if (this.h) {
      this.h.onLinesInserted(e);
      this.n = true;
      return true;
    } else {
      return this.w.onLinesInserted(e.fromLineNumber, e.toLineNumber);
    }
  }
  onScrollChanged(e) {
    return this.w.onScrollChanged();
  }
  onThemeChanged(e) {
    this.w.onThemeChanged();
    this.z();
    return true;
  }
  onTokensChanged(e) {
    if (this.h) {
      const ranges = [];
      for (const range of e.ranges) {
        const minimapLineRange = this.h.modelLineRangeToMinimapLineRange(range.fromLineNumber, range.toLineNumber);
        if (minimapLineRange) {
          ranges.push({ fromLineNumber: minimapLineRange[0], toLineNumber: minimapLineRange[1] });
        }
      }
      if (ranges.length) {
        return this.w.onTokensChanged(ranges);
      } else {
        return false;
      }
    } else {
      return this.w.onTokensChanged(e.ranges);
    }
  }
  onTokensColorsChanged(e) {
    this.z();
    return this.w.onTokensColorsChanged();
  }
  onZonesChanged(e) {
    return this.w.onZonesChanged();
  }
  // --- end event handlers
  prepareRender(ctx) {
    if (this.n) {
      this.n = false;
      this.C();
    }
  }
  render(ctx) {
    let viewportStartLineNumber = ctx.visibleRange.startLineNumber;
    let viewportEndLineNumber = ctx.visibleRange.endLineNumber;
    if (this.h) {
      viewportStartLineNumber = this.h.modelLineToMinimapLine(viewportStartLineNumber);
      viewportEndLineNumber = this.h.modelLineToMinimapLine(viewportEndLineNumber);
    }
    const minimapCtx = {
      viewportContainsWhitespaceGaps: ctx.viewportData.whitespaceViewportData.length > 0,
      scrollWidth: ctx.scrollWidth,
      scrollHeight: ctx.scrollHeight,
      viewportStartLineNumber,
      viewportEndLineNumber,
      viewportStartLineNumberVerticalOffset: ctx.getVerticalOffsetForLineNumber(viewportStartLineNumber),
      scrollTop: ctx.scrollTop,
      scrollLeft: ctx.scrollLeft,
      viewportWidth: ctx.viewportWidth,
      viewportHeight: ctx.viewportHeight
    };
    this.w.render(minimapCtx);
  }
  //#region IMinimapModel
  C() {
    this.f = null;
    const wasSampling = Boolean(this.h);
    const [samplingState, events] = MinimapSamplingState.compute(this.options, this._context.viewModel.getLineCount(), this.h);
    this.h = samplingState;
    if (wasSampling && this.h) {
      for (const event of events) {
        switch (event.type) {
          case "deleted":
            this.w.onLinesDeleted(event.deleteFromLineNumber, event.deleteToLineNumber);
            break;
          case "inserted":
            this.w.onLinesInserted(event.insertFromLineNumber, event.insertToLineNumber);
            break;
          case "flush":
            this.w.onFlushed();
            break;
        }
      }
    }
  }
  getLineCount() {
    if (this.h) {
      return this.h.minimapLines.length;
    }
    return this._context.viewModel.getLineCount();
  }
  getRealLineCount() {
    return this._context.viewModel.getLineCount();
  }
  getLineContent(lineNumber) {
    if (this.h) {
      return this._context.viewModel.getLineContent(this.h.minimapLines[lineNumber - 1]);
    }
    return this._context.viewModel.getLineContent(lineNumber);
  }
  getLineMaxColumn(lineNumber) {
    if (this.h) {
      return this._context.viewModel.getLineMaxColumn(this.h.minimapLines[lineNumber - 1]);
    }
    return this._context.viewModel.getLineMaxColumn(lineNumber);
  }
  getMinimapLinesRenderingData(startLineNumber, endLineNumber, needed) {
    if (this.h) {
      const result = [];
      for (let lineIndex = 0, lineCount = endLineNumber - startLineNumber + 1; lineIndex < lineCount; lineIndex++) {
        if (needed[lineIndex]) {
          result[lineIndex] = this._context.viewModel.getViewLineData(this.h.minimapLines[startLineNumber + lineIndex - 1]);
        } else {
          result[lineIndex] = null;
        }
      }
      return result;
    }
    return this._context.viewModel.getMinimapLinesRenderingData(startLineNumber, endLineNumber, needed).data;
  }
  getSelections() {
    if (this.f === null) {
      if (this.h) {
        this.f = [];
        for (const selection of this.c) {
          const [minimapLineStart, minimapLineEnd] = this.h.decorationLineRangeToMinimapLineRange(selection.startLineNumber, selection.endLineNumber);
          this.f.push(new $_D(minimapLineStart, selection.startColumn, minimapLineEnd, selection.endColumn));
        }
      } else {
        this.f = this.c;
      }
    }
    return this.f;
  }
  getMinimapDecorationsInViewport(startLineNumber, endLineNumber) {
    const decorations = this.D(startLineNumber, endLineNumber).filter((decoration3) => !decoration3.options.minimap?.sectionHeaderStyle);
    if (this.h) {
      const result = [];
      for (const decoration3 of decorations) {
        if (!decoration3.options.minimap) {
          continue;
        }
        const range = decoration3.range;
        const minimapStartLineNumber = this.h.modelLineToMinimapLine(range.startLineNumber);
        const minimapEndLineNumber = this.h.modelLineToMinimapLine(range.endLineNumber);
        result.push(new $K5(new $9C(minimapStartLineNumber, range.startColumn, minimapEndLineNumber, range.endColumn), decoration3.options));
      }
      return result;
    }
    return decorations;
  }
  getSectionHeaderDecorationsInViewport(startLineNumber, endLineNumber) {
    const minimapLineHeight = this.options.minimapLineHeight;
    const sectionHeaderFontSize = this.options.sectionHeaderFontSize;
    const headerHeightInMinimapLines = sectionHeaderFontSize / minimapLineHeight;
    startLineNumber = Math.floor(Math.max(1, startLineNumber - headerHeightInMinimapLines));
    return this.D(startLineNumber, endLineNumber).filter((decoration3) => !!decoration3.options.minimap?.sectionHeaderStyle);
  }
  D(startLineNumber, endLineNumber) {
    let visibleRange;
    if (this.h) {
      const modelStartLineNumber = this.h.minimapLines[startLineNumber - 1];
      const modelEndLineNumber = this.h.minimapLines[endLineNumber - 1];
      visibleRange = new $9C(modelStartLineNumber, 1, modelEndLineNumber, this._context.viewModel.getLineMaxColumn(modelEndLineNumber));
    } else {
      visibleRange = new $9C(startLineNumber, 1, endLineNumber, this._context.viewModel.getLineMaxColumn(endLineNumber));
    }
    return this._context.viewModel.getMinimapDecorationsInRange(visibleRange);
  }
  getSectionHeaderText(decoration3, fitWidth) {
    const headerText = decoration3.options.minimap?.sectionHeaderText;
    if (!headerText) {
      return null;
    }
    const cachedText = this.t.get(headerText);
    if (cachedText) {
      return cachedText;
    }
    const fittedText = fitWidth(headerText);
    this.t.set(headerText, fittedText);
    return fittedText;
  }
  getOptions() {
    return this._context.viewModel.model.getOptions();
  }
  revealLineNumber(lineNumber) {
    if (this.h) {
      lineNumber = this.h.minimapLines[lineNumber - 1];
    }
    this._context.viewModel.revealRange(
      "mouse",
      false,
      new $9C(lineNumber, 1, lineNumber, 1),
      1,
      0
      /* ScrollType.Smooth */
    );
  }
  setScrollTop(scrollTop) {
    this._context.viewModel.viewLayout.setScrollPosition(
      {
        scrollTop
      },
      1
      /* ScrollType.Immediate */
    );
  }
};
var InnerMinimap = class _InnerMinimap extends $3c {
  constructor(theme, model) {
    super();
    this.M = false;
    this.N = false;
    this.c = theme;
    this.f = model;
    this.J = null;
    this.O = null;
    this.L = this.c.getColor($gq);
    this.h = $oZ(document.createElement("div"));
    $g7.write(
      this.h,
      9
      /* PartFingerprint.Minimap */
    );
    this.h.setClassName(this.R());
    this.h.setPosition("absolute");
    this.h.setAttribute("role", "presentation");
    this.h.setAttribute("aria-hidden", "true");
    this.m = $oZ(document.createElement("div"));
    this.m.setClassName("minimap-shadow-hidden");
    this.h.appendChild(this.m);
    this.n = $oZ(document.createElement("canvas"));
    this.n.setPosition("absolute");
    this.n.setLeft(0);
    this.h.appendChild(this.n);
    this.t = $oZ(document.createElement("canvas"));
    this.t.setPosition("absolute");
    this.t.setClassName("minimap-decorations-layer");
    this.t.setLeft(0);
    this.h.appendChild(this.t);
    this.u = $oZ(document.createElement("div"));
    this.u.setPosition("absolute");
    this.u.setClassName("minimap-slider");
    this.u.setLayerHinting(true);
    this.u.setContain("strict");
    this.h.appendChild(this.u);
    this.w = $oZ(document.createElement("div"));
    this.w.setPosition("absolute");
    this.w.setClassName("minimap-slider-horizontal");
    this.u.appendChild(this.w);
    this.S();
    this.z = $aj(this.h.domNode, $7j.POINTER_DOWN, (e) => {
      e.preventDefault();
      const renderMinimap = this.f.options.renderMinimap;
      if (renderMinimap === 0) {
        return;
      }
      if (!this.J) {
        return;
      }
      if (this.f.options.size !== "proportional") {
        if (e.button === 0 && this.J) {
          const position = $vj(this.u.domNode);
          const initialPosY = position.top + position.height / 2;
          this.P(e, initialPosY, this.J.renderedLayout);
        }
        return;
      }
      const minimapLineHeight = this.f.options.minimapLineHeight;
      const internalOffsetY = this.f.options.canvasInnerHeight / this.f.options.canvasOuterHeight * e.offsetY;
      const lineIndex = Math.floor(internalOffsetY / minimapLineHeight);
      let lineNumber = lineIndex + this.J.renderedLayout.startLineNumber - this.J.renderedLayout.topPaddingLineCount;
      lineNumber = Math.min(lineNumber, this.f.getLineCount());
      this.f.revealLineNumber(lineNumber);
    });
    this.C = new $pZ();
    this.D = $aj(this.u.domNode, $7j.POINTER_DOWN, (e) => {
      e.preventDefault();
      e.stopPropagation();
      if (e.button === 0 && this.J) {
        this.P(e, e.pageY, this.J.renderedLayout);
      }
    });
    this.F = $mZ.addTarget(this.h.domNode);
    this.G = $_i(this.h.domNode, EventType.Start, (e) => {
      e.preventDefault();
      e.stopPropagation();
      if (this.J) {
        this.u.toggleClassName("active", true);
        this.N = true;
        this.Q(e);
      }
    }, { passive: false });
    this.H = $_i(this.h.domNode, EventType.Change, (e) => {
      e.preventDefault();
      e.stopPropagation();
      if (this.J && this.N) {
        this.Q(e);
      }
    }, { passive: false });
    this.I = $aj(this.h.domNode, EventType.End, (e) => {
      e.preventDefault();
      e.stopPropagation();
      this.N = false;
      this.u.toggleClassName("active", false);
    });
  }
  P(e, initialPosY, initialSliderState) {
    if (!e.target || !(e.target instanceof Element)) {
      return;
    }
    const initialPosX = e.pageX;
    this.u.toggleClassName("active", true);
    const handlePointerMove = (posy, posx) => {
      const minimapPosition = $vj(this.h.domNode);
      const pointerOrthogonalDelta = Math.min(Math.abs(posx - initialPosX), Math.abs(posx - minimapPosition.left), Math.abs(posx - minimapPosition.left - minimapPosition.width));
      if ($l && pointerOrthogonalDelta > POINTER_DRAG_RESET_DISTANCE2) {
        this.f.setScrollTop(initialSliderState.scrollTop);
        return;
      }
      const pointerDelta = posy - initialPosY;
      this.f.setScrollTop(initialSliderState.getDesiredScrollTopFromDelta(pointerDelta));
    };
    if (e.pageY !== initialPosY) {
      handlePointerMove(e.pageY, initialPosX);
    }
    this.C.startMonitoring(e.target, e.pointerId, e.buttons, (pointerMoveData) => handlePointerMove(pointerMoveData.pageY, pointerMoveData.pageX), () => {
      this.u.toggleClassName("active", false);
    });
  }
  Q(touch) {
    const startY = this.h.domNode.getBoundingClientRect().top;
    const scrollTop = this.J.renderedLayout.getDesiredScrollTopFromTouchLocation(touch.pageY - startY);
    this.f.setScrollTop(scrollTop);
  }
  dispose() {
    this.z.dispose();
    this.C.dispose();
    this.D.dispose();
    this.F.dispose();
    this.G.dispose();
    this.H.dispose();
    this.I.dispose();
    super.dispose();
  }
  R() {
    const class_ = ["minimap"];
    if (this.f.options.showSlider === "always") {
      class_.push("slider-always");
    } else {
      class_.push("slider-mouseover");
    }
    if (this.f.options.autohide) {
      class_.push("autohide");
    }
    return class_.join(" ");
  }
  getDomNode() {
    return this.h;
  }
  S() {
    this.h.setLeft(this.f.options.minimapLeft);
    this.h.setWidth(this.f.options.minimapWidth);
    this.h.setHeight(this.f.options.minimapHeight);
    this.m.setHeight(this.f.options.minimapHeight);
    this.n.setWidth(this.f.options.canvasOuterWidth);
    this.n.setHeight(this.f.options.canvasOuterHeight);
    this.n.domNode.width = this.f.options.canvasInnerWidth;
    this.n.domNode.height = this.f.options.canvasInnerHeight;
    this.t.setWidth(this.f.options.canvasOuterWidth);
    this.t.setHeight(this.f.options.canvasOuterHeight);
    this.t.domNode.width = this.f.options.canvasInnerWidth;
    this.t.domNode.height = this.f.options.canvasInnerHeight;
    this.u.setWidth(this.f.options.minimapWidth);
  }
  U() {
    if (!this.O) {
      if (this.f.options.canvasInnerWidth > 0 && this.f.options.canvasInnerHeight > 0) {
        this.O = new MinimapBuffers(this.n.domNode.getContext("2d"), this.f.options.canvasInnerWidth, this.f.options.canvasInnerHeight, this.f.options.backgroundColor);
      }
    }
    return this.O ? this.O.getBuffer() : null;
  }
  // ---- begin view event handlers
  onDidChangeOptions() {
    this.J = null;
    this.O = null;
    this.S();
    this.h.setClassName(this.R());
  }
  onSelectionChanged() {
    this.M = true;
    return true;
  }
  onDecorationsChanged() {
    this.M = true;
    return true;
  }
  onFlushed() {
    this.J = null;
    return true;
  }
  onLinesChanged(changeFromLineNumber, changeCount) {
    if (this.J) {
      return this.J.onLinesChanged(changeFromLineNumber, changeCount);
    }
    return false;
  }
  onLinesDeleted(deleteFromLineNumber, deleteToLineNumber) {
    this.J?.onLinesDeleted(deleteFromLineNumber, deleteToLineNumber);
    return true;
  }
  onLinesInserted(insertFromLineNumber, insertToLineNumber) {
    this.J?.onLinesInserted(insertFromLineNumber, insertToLineNumber);
    return true;
  }
  onScrollChanged() {
    this.M = true;
    return true;
  }
  onThemeChanged() {
    this.L = this.c.getColor($gq);
    this.M = true;
    return true;
  }
  onTokensChanged(ranges) {
    if (this.J) {
      return this.J.onTokensChanged(ranges);
    }
    return false;
  }
  onTokensColorsChanged() {
    this.J = null;
    this.O = null;
    return true;
  }
  onZonesChanged() {
    this.J = null;
    return true;
  }
  // --- end event handlers
  render(renderingCtx) {
    const renderMinimap = this.f.options.renderMinimap;
    if (renderMinimap === 0) {
      this.m.setClassName("minimap-shadow-hidden");
      this.w.setWidth(0);
      this.w.setHeight(0);
      return;
    }
    if (renderingCtx.scrollLeft + renderingCtx.viewportWidth >= renderingCtx.scrollWidth) {
      this.m.setClassName("minimap-shadow-hidden");
    } else {
      this.m.setClassName("minimap-shadow-visible");
    }
    const layout = MinimapLayout.create(this.f.options, renderingCtx.viewportStartLineNumber, renderingCtx.viewportEndLineNumber, renderingCtx.viewportStartLineNumberVerticalOffset, renderingCtx.viewportHeight, renderingCtx.viewportContainsWhitespaceGaps, this.f.getLineCount(), this.f.getRealLineCount(), renderingCtx.scrollTop, renderingCtx.scrollHeight, this.J ? this.J.renderedLayout : null);
    this.u.setDisplay(layout.sliderNeeded ? "block" : "none");
    this.u.setTop(layout.sliderTop);
    this.u.setHeight(layout.sliderHeight);
    this.w.setLeft(0);
    this.w.setWidth(this.f.options.minimapWidth);
    this.w.setTop(0);
    this.w.setHeight(layout.sliderHeight);
    this.W(layout);
    this.J = this.gb(layout);
  }
  W(layout) {
    if (this.M) {
      this.M = false;
      const selections = this.f.getSelections();
      selections.sort($9C.compareRangesUsingStarts);
      const decorations = this.f.getMinimapDecorationsInViewport(layout.startLineNumber, layout.endLineNumber);
      decorations.sort((a, b) => (a.options.zIndex || 0) - (b.options.zIndex || 0));
      const { canvasInnerWidth, canvasInnerHeight } = this.f.options;
      const minimapLineHeight = this.f.options.minimapLineHeight;
      const minimapCharWidth = this.f.options.minimapCharWidth;
      const tabSize = this.f.getOptions().tabSize;
      const canvasContext = this.t.domNode.getContext("2d");
      canvasContext.clearRect(0, 0, canvasInnerWidth, canvasInnerHeight);
      const highlightedLines = new ContiguousLineMap(layout.startLineNumber, layout.endLineNumber, false);
      this.X(canvasContext, selections, highlightedLines, layout, minimapLineHeight);
      this.Y(canvasContext, decorations, highlightedLines, layout, minimapLineHeight);
      const lineOffsetMap = new ContiguousLineMap(layout.startLineNumber, layout.endLineNumber, null);
      this.Z(canvasContext, selections, lineOffsetMap, layout, minimapLineHeight, tabSize, minimapCharWidth, canvasInnerWidth);
      this.$(canvasContext, decorations, lineOffsetMap, layout, minimapLineHeight, tabSize, minimapCharWidth, canvasInnerWidth);
      this.db(layout);
    }
  }
  X(canvasContext, selections, highlightedLines, layout, minimapLineHeight) {
    if (!this.L || this.L.isTransparent()) {
      return;
    }
    canvasContext.fillStyle = this.L.transparent(0.5).toString();
    let y1 = 0;
    let y2 = 0;
    for (const selection of selections) {
      const intersection = layout.intersectWithViewport(selection);
      if (!intersection) {
        continue;
      }
      const [startLineNumber, endLineNumber] = intersection;
      for (let line = startLineNumber; line <= endLineNumber; line++) {
        highlightedLines.set(line, true);
      }
      const yy1 = layout.getYForLineNumber(startLineNumber, minimapLineHeight);
      const yy2 = layout.getYForLineNumber(endLineNumber, minimapLineHeight);
      if (y2 >= yy1) {
        y2 = yy2;
      } else {
        if (y2 > y1) {
          canvasContext.fillRect(MINIMAP_GUTTER_WIDTH, y1, canvasContext.canvas.width, y2 - y1);
        }
        y1 = yy1;
        y2 = yy2;
      }
    }
    if (y2 > y1) {
      canvasContext.fillRect(MINIMAP_GUTTER_WIDTH, y1, canvasContext.canvas.width, y2 - y1);
    }
  }
  Y(canvasContext, decorations, highlightedLines, layout, minimapLineHeight) {
    const highlightColors = /* @__PURE__ */ new Map();
    for (let i2 = decorations.length - 1; i2 >= 0; i2--) {
      const decoration3 = decorations[i2];
      const minimapOptions = decoration3.options.minimap;
      if (!minimapOptions || minimapOptions.position !== 1) {
        continue;
      }
      const intersection = layout.intersectWithViewport(decoration3.range);
      if (!intersection) {
        continue;
      }
      const [startLineNumber, endLineNumber] = intersection;
      const decorationColor = minimapOptions.getColor(this.c.value);
      if (!decorationColor || decorationColor.isTransparent()) {
        continue;
      }
      let highlightColor = highlightColors.get(decorationColor.toString());
      if (!highlightColor) {
        highlightColor = decorationColor.transparent(0.5).toString();
        highlightColors.set(decorationColor.toString(), highlightColor);
      }
      canvasContext.fillStyle = highlightColor;
      for (let line = startLineNumber; line <= endLineNumber; line++) {
        if (highlightedLines.has(line)) {
          continue;
        }
        highlightedLines.set(line, true);
        const y = layout.getYForLineNumber(startLineNumber, minimapLineHeight);
        canvasContext.fillRect(MINIMAP_GUTTER_WIDTH, y, canvasContext.canvas.width, minimapLineHeight);
      }
    }
  }
  Z(canvasContext, selections, lineOffsetMap, layout, lineHeight, tabSize, characterWidth, canvasInnerWidth) {
    if (!this.L || this.L.isTransparent()) {
      return;
    }
    for (const selection of selections) {
      const intersection = layout.intersectWithViewport(selection);
      if (!intersection) {
        continue;
      }
      const [startLineNumber, endLineNumber] = intersection;
      for (let line = startLineNumber; line <= endLineNumber; line++) {
        this.ab(canvasContext, lineOffsetMap, selection, this.L, layout, line, lineHeight, lineHeight, tabSize, characterWidth, canvasInnerWidth);
      }
    }
  }
  $(canvasContext, decorations, lineOffsetMap, layout, minimapLineHeight, tabSize, characterWidth, canvasInnerWidth) {
    for (const decoration3 of decorations) {
      const minimapOptions = decoration3.options.minimap;
      if (!minimapOptions) {
        continue;
      }
      const intersection = layout.intersectWithViewport(decoration3.range);
      if (!intersection) {
        continue;
      }
      const [startLineNumber, endLineNumber] = intersection;
      const decorationColor = minimapOptions.getColor(this.c.value);
      if (!decorationColor || decorationColor.isTransparent()) {
        continue;
      }
      for (let line = startLineNumber; line <= endLineNumber; line++) {
        switch (minimapOptions.position) {
          case 1:
            this.ab(canvasContext, lineOffsetMap, decoration3.range, decorationColor, layout, line, minimapLineHeight, minimapLineHeight, tabSize, characterWidth, canvasInnerWidth);
            continue;
          case 2: {
            const y = layout.getYForLineNumber(line, minimapLineHeight);
            const x = 2;
            this.cb(canvasContext, decorationColor, x, y, GUTTER_DECORATION_WIDTH, minimapLineHeight);
            continue;
          }
        }
      }
    }
  }
  ab(canvasContext, lineOffsetMap, decorationRange, decorationColor, layout, lineNumber, height, minimapLineHeight, tabSize, charWidth, canvasInnerWidth) {
    const y = layout.getYForLineNumber(lineNumber, minimapLineHeight);
    if (y + height < 0 || y > this.f.options.canvasInnerHeight) {
      return;
    }
    const { startLineNumber, endLineNumber } = decorationRange;
    const startColumn = startLineNumber === lineNumber ? decorationRange.startColumn : 1;
    const endColumn = endLineNumber === lineNumber ? decorationRange.endColumn : this.f.getLineMaxColumn(lineNumber);
    const x1 = this.bb(lineOffsetMap, lineNumber, startColumn, tabSize, charWidth, canvasInnerWidth);
    const x2 = this.bb(lineOffsetMap, lineNumber, endColumn, tabSize, charWidth, canvasInnerWidth);
    this.cb(canvasContext, decorationColor, x1, y, x2 - x1, height);
  }
  bb(lineOffsetMap, lineNumber, column, tabSize, charWidth, canvasInnerWidth) {
    if (column === 1) {
      return MINIMAP_GUTTER_WIDTH;
    }
    const minimumXOffset = (column - 1) * charWidth;
    if (minimumXOffset >= canvasInnerWidth) {
      return canvasInnerWidth;
    }
    let lineIndexToXOffset = lineOffsetMap.get(lineNumber);
    if (!lineIndexToXOffset) {
      const lineData = this.f.getLineContent(lineNumber);
      lineIndexToXOffset = [MINIMAP_GUTTER_WIDTH];
      let prevx = MINIMAP_GUTTER_WIDTH;
      for (let i2 = 1; i2 < lineData.length + 1; i2++) {
        const charCode = lineData.charCodeAt(i2 - 1);
        const dx = charCode === 9 ? tabSize * charWidth : $gg(charCode) ? 2 * charWidth : charWidth;
        const x = prevx + dx;
        if (x >= canvasInnerWidth) {
          lineIndexToXOffset[i2] = canvasInnerWidth;
          break;
        }
        lineIndexToXOffset[i2] = x;
        prevx = x;
      }
      lineOffsetMap.set(lineNumber, lineIndexToXOffset);
    }
    if (column - 1 < lineIndexToXOffset.length) {
      return lineIndexToXOffset[column - 1];
    }
    return canvasInnerWidth;
  }
  cb(canvasContext, decorationColor, x, y, width2, height) {
    canvasContext.fillStyle = decorationColor && decorationColor.toString() || "";
    canvasContext.fillRect(x, y, width2, height);
  }
  db(layout) {
    const minimapLineHeight = this.f.options.minimapLineHeight;
    const sectionHeaderFontSize = this.f.options.sectionHeaderFontSize;
    const sectionHeaderLetterSpacing = this.f.options.sectionHeaderLetterSpacing;
    const backgroundFillHeight = sectionHeaderFontSize * 1.5;
    const { canvasInnerWidth } = this.f.options;
    const backgroundColor = this.f.options.backgroundColor;
    const backgroundFill = `rgb(${backgroundColor.r} ${backgroundColor.g} ${backgroundColor.b} / .7)`;
    const foregroundColor = this.f.options.sectionHeaderFontColor;
    const foregroundFill = `rgb(${foregroundColor.r} ${foregroundColor.g} ${foregroundColor.b})`;
    const separatorStroke = foregroundFill;
    const canvasContext = this.t.domNode.getContext("2d");
    canvasContext.letterSpacing = sectionHeaderLetterSpacing + "px";
    canvasContext.font = "500 " + sectionHeaderFontSize + "px " + this.f.options.sectionHeaderFontFamily;
    canvasContext.strokeStyle = separatorStroke;
    canvasContext.lineWidth = 0.2;
    const decorations = this.f.getSectionHeaderDecorationsInViewport(layout.startLineNumber, layout.endLineNumber);
    decorations.sort((a, b) => a.range.startLineNumber - b.range.startLineNumber);
    const fitWidth = _InnerMinimap.eb.bind(null, canvasContext, canvasInnerWidth - MINIMAP_GUTTER_WIDTH);
    for (const decoration3 of decorations) {
      const y = layout.getYForLineNumber(decoration3.range.startLineNumber, minimapLineHeight) + sectionHeaderFontSize;
      const backgroundFillY = y - sectionHeaderFontSize;
      const separatorY = backgroundFillY + 2;
      const headerText = this.f.getSectionHeaderText(decoration3, fitWidth);
      _InnerMinimap.fb(canvasContext, headerText, decoration3.options.minimap?.sectionHeaderStyle === 2, backgroundFill, foregroundFill, canvasInnerWidth, backgroundFillY, backgroundFillHeight, y, separatorY);
    }
  }
  static eb(target, maxWidth, headerText) {
    if (!headerText) {
      return headerText;
    }
    const ellipsis2 = "\u2026";
    const width2 = target.measureText(headerText).width;
    const ellipsisWidth = target.measureText(ellipsis2).width;
    if (width2 <= maxWidth || width2 <= ellipsisWidth) {
      return headerText;
    }
    const len = headerText.length;
    const averageCharWidth = width2 / headerText.length;
    const maxCharCount = Math.floor((maxWidth - ellipsisWidth) / averageCharWidth) - 1;
    let halfCharCount = Math.ceil(maxCharCount / 2);
    while (halfCharCount > 0 && /\s/.test(headerText[halfCharCount - 1])) {
      --halfCharCount;
    }
    return headerText.substring(0, halfCharCount) + ellipsis2 + headerText.substring(len - (maxCharCount - halfCharCount));
  }
  static fb(target, headerText, hasSeparatorLine, backgroundFill, foregroundFill, minimapWidth, backgroundFillY, backgroundFillHeight, textY, separatorY) {
    if (headerText) {
      target.fillStyle = backgroundFill;
      target.fillRect(0, backgroundFillY, minimapWidth, backgroundFillHeight);
      target.fillStyle = foregroundFill;
      target.fillText(headerText, MINIMAP_GUTTER_WIDTH, textY);
    }
    if (hasSeparatorLine) {
      target.beginPath();
      target.moveTo(0, separatorY);
      target.lineTo(minimapWidth, separatorY);
      target.closePath();
      target.stroke();
    }
  }
  gb(layout) {
    const startLineNumber = layout.startLineNumber;
    const endLineNumber = layout.endLineNumber;
    const minimapLineHeight = this.f.options.minimapLineHeight;
    if (this.J && this.J.linesEquals(layout)) {
      const _lastData = this.J._get();
      return new RenderData(layout, _lastData.imageData, _lastData.lines);
    }
    const imageData = this.U();
    if (!imageData) {
      return null;
    }
    const [_dirtyY1, _dirtyY2, needed] = _InnerMinimap.hb(imageData, layout.topPaddingLineCount, startLineNumber, endLineNumber, minimapLineHeight, this.J);
    const lineInfo = this.f.getMinimapLinesRenderingData(startLineNumber, endLineNumber, needed);
    const tabSize = this.f.getOptions().tabSize;
    const defaultBackground = this.f.options.defaultBackgroundColor;
    const background = this.f.options.backgroundColor;
    const foregroundAlpha = this.f.options.foregroundAlpha;
    const tokensColorTracker = this.f.tokensColorTracker;
    const useLighterFont = tokensColorTracker.backgroundIsLight();
    const renderMinimap = this.f.options.renderMinimap;
    const charRenderer = this.f.options.charRenderer();
    const fontScale = this.f.options.fontScale;
    const minimapCharWidth = this.f.options.minimapCharWidth;
    const baseCharHeight = renderMinimap === 1 ? 2 : 2 + 1;
    const renderMinimapLineHeight = baseCharHeight * fontScale;
    const innerLinePadding = minimapLineHeight > renderMinimapLineHeight ? Math.floor((minimapLineHeight - renderMinimapLineHeight) / 2) : 0;
    const backgroundA = background.a / 255;
    const renderBackground = new $A8(Math.round((background.r - defaultBackground.r) * backgroundA + defaultBackground.r), Math.round((background.g - defaultBackground.g) * backgroundA + defaultBackground.g), Math.round((background.b - defaultBackground.b) * backgroundA + defaultBackground.b), 255);
    let dy = layout.topPaddingLineCount * minimapLineHeight;
    const renderedLines = [];
    for (let lineIndex = 0, lineCount = endLineNumber - startLineNumber + 1; lineIndex < lineCount; lineIndex++) {
      if (needed[lineIndex]) {
        _InnerMinimap.ib(imageData, renderBackground, background.a, useLighterFont, renderMinimap, minimapCharWidth, tokensColorTracker, foregroundAlpha, charRenderer, dy, innerLinePadding, tabSize, lineInfo[lineIndex], fontScale, minimapLineHeight);
      }
      renderedLines[lineIndex] = new MinimapLine(dy);
      dy += minimapLineHeight;
    }
    const dirtyY1 = _dirtyY1 === -1 ? 0 : _dirtyY1;
    const dirtyY2 = _dirtyY2 === -1 ? imageData.height : _dirtyY2;
    const dirtyHeight = dirtyY2 - dirtyY1;
    const ctx = this.n.domNode.getContext("2d");
    ctx.putImageData(imageData, 0, 0, 0, dirtyY1, imageData.width, dirtyHeight);
    return new RenderData(layout, imageData, renderedLines);
  }
  static hb(target, topPaddingLineCount, startLineNumber, endLineNumber, minimapLineHeight, lastRenderData) {
    const needed = [];
    if (!lastRenderData) {
      for (let i2 = 0, len = endLineNumber - startLineNumber + 1; i2 < len; i2++) {
        needed[i2] = true;
      }
      return [-1, -1, needed];
    }
    const _lastData = lastRenderData._get();
    const lastTargetData = _lastData.imageData.data;
    const lastStartLineNumber = _lastData.rendLineNumberStart;
    const lastLines = _lastData.lines;
    const lastLinesLength = lastLines.length;
    const WIDTH = target.width;
    const targetData = target.data;
    const maxDestPixel = (endLineNumber - startLineNumber + 1) * minimapLineHeight * WIDTH * 4;
    let dirtyPixel1 = -1;
    let dirtyPixel2 = -1;
    let copySourceStart = -1;
    let copySourceEnd = -1;
    let copyDestStart = -1;
    let copyDestEnd = -1;
    let dest_dy = topPaddingLineCount * minimapLineHeight;
    for (let lineNumber = startLineNumber; lineNumber <= endLineNumber; lineNumber++) {
      const lineIndex = lineNumber - startLineNumber;
      const lastLineIndex = lineNumber - lastStartLineNumber;
      const source_dy = lastLineIndex >= 0 && lastLineIndex < lastLinesLength ? lastLines[lastLineIndex].dy : -1;
      if (source_dy === -1) {
        needed[lineIndex] = true;
        dest_dy += minimapLineHeight;
        continue;
      }
      const sourceStart = source_dy * WIDTH * 4;
      const sourceEnd = (source_dy + minimapLineHeight) * WIDTH * 4;
      const destStart = dest_dy * WIDTH * 4;
      const destEnd = (dest_dy + minimapLineHeight) * WIDTH * 4;
      if (copySourceEnd === sourceStart && copyDestEnd === destStart) {
        copySourceEnd = sourceEnd;
        copyDestEnd = destEnd;
      } else {
        if (copySourceStart !== -1) {
          targetData.set(lastTargetData.subarray(copySourceStart, copySourceEnd), copyDestStart);
          if (dirtyPixel1 === -1 && copySourceStart === 0 && copySourceStart === copyDestStart) {
            dirtyPixel1 = copySourceEnd;
          }
          if (dirtyPixel2 === -1 && copySourceEnd === maxDestPixel && copySourceStart === copyDestStart) {
            dirtyPixel2 = copySourceStart;
          }
        }
        copySourceStart = sourceStart;
        copySourceEnd = sourceEnd;
        copyDestStart = destStart;
        copyDestEnd = destEnd;
      }
      needed[lineIndex] = false;
      dest_dy += minimapLineHeight;
    }
    if (copySourceStart !== -1) {
      targetData.set(lastTargetData.subarray(copySourceStart, copySourceEnd), copyDestStart);
      if (dirtyPixel1 === -1 && copySourceStart === 0 && copySourceStart === copyDestStart) {
        dirtyPixel1 = copySourceEnd;
      }
      if (dirtyPixel2 === -1 && copySourceEnd === maxDestPixel && copySourceStart === copyDestStart) {
        dirtyPixel2 = copySourceStart;
      }
    }
    const dirtyY1 = dirtyPixel1 === -1 ? -1 : dirtyPixel1 / (WIDTH * 4);
    const dirtyY2 = dirtyPixel2 === -1 ? -1 : dirtyPixel2 / (WIDTH * 4);
    return [dirtyY1, dirtyY2, needed];
  }
  static ib(target, backgroundColor, backgroundAlpha, useLighterFont, renderMinimap, charWidth, colorTracker, foregroundAlpha, minimapCharRenderer, dy, innerLinePadding, tabSize, lineData, fontScale, minimapLineHeight) {
    const content = lineData.content;
    const tokens = lineData.tokens;
    const maxDx = target.width - charWidth;
    const force1pxHeight = minimapLineHeight === 1;
    let dx = MINIMAP_GUTTER_WIDTH;
    let charIndex = 0;
    let tabsCharDelta = 0;
    for (let tokenIndex = 0, tokensLen = tokens.getCount(); tokenIndex < tokensLen; tokenIndex++) {
      const tokenEndIndex = tokens.getEndOffset(tokenIndex);
      const tokenColorId = tokens.getForeground(tokenIndex);
      const tokenColor = colorTracker.getColor(tokenColorId);
      for (; charIndex < tokenEndIndex; charIndex++) {
        if (dx > maxDx) {
          return;
        }
        const charCode = content.charCodeAt(charIndex);
        if (charCode === 9) {
          const insertSpacesCount = tabSize - (charIndex + tabsCharDelta) % tabSize;
          tabsCharDelta += insertSpacesCount - 1;
          dx += insertSpacesCount * charWidth;
        } else if (charCode === 32) {
          dx += charWidth;
        } else {
          const count = $gg(charCode) ? 2 : 1;
          for (let i2 = 0; i2 < count; i2++) {
            if (renderMinimap === 2) {
              minimapCharRenderer.blockRenderChar(target, dx, dy + innerLinePadding, tokenColor, foregroundAlpha, backgroundColor, backgroundAlpha, force1pxHeight);
            } else {
              minimapCharRenderer.renderChar(target, dx, dy + innerLinePadding, charCode, tokenColor, foregroundAlpha, backgroundColor, backgroundAlpha, fontScale, useLighterFont, force1pxHeight);
            }
            dx += charWidth;
            if (dx > maxDx) {
              return;
            }
          }
        }
      }
    }
  }
};
var ContiguousLineMap = class {
  constructor(startLineNumber, endLineNumber, defaultValue) {
    this.c = startLineNumber;
    this.d = endLineNumber;
    this.f = defaultValue;
    this.h = [];
    for (let i2 = 0, count = this.d - this.c + 1; i2 < count; i2++) {
      this.h[i2] = defaultValue;
    }
  }
  has(lineNumber) {
    return this.get(lineNumber) !== this.f;
  }
  set(lineNumber, value) {
    if (lineNumber < this.c || lineNumber > this.d) {
      return;
    }
    this.h[lineNumber - this.c] = value;
  }
  get(lineNumber) {
    if (lineNumber < this.c || lineNumber > this.d) {
      return this.f;
    }
    return this.h[lineNumber - this.c];
  }
};

// out-build/vs/editor/browser/viewParts/overlayWidgets/overlayWidgets.js
var $I8 = class extends $f7 {
  constructor(context, viewDomNode) {
    super(context);
    this.c = viewDomNode;
    const options3 = this._context.configuration.options;
    const layoutInfo = options3.get(
      151
      /* EditorOption.layoutInfo */
    );
    this.f = {};
    this.j = layoutInfo.verticalScrollbarWidth;
    this.n = layoutInfo.minimap.minimapWidth;
    this.s = layoutInfo.horizontalScrollbarHeight;
    this.t = layoutInfo.height;
    this.w = layoutInfo.width;
    this.g = { top: 0, left: 0, width: 0, height: 0 };
    this.h = $oZ(document.createElement("div"));
    $g7.write(
      this.h,
      4
      /* PartFingerprint.OverlayWidgets */
    );
    this.h.setClassName("overlayWidgets");
    this.overflowingOverlayWidgetsDomNode = $oZ(document.createElement("div"));
    $g7.write(
      this.overflowingOverlayWidgetsDomNode,
      5
      /* PartFingerprint.OverflowingOverlayWidgets */
    );
    this.overflowingOverlayWidgetsDomNode.setClassName("overflowingOverlayWidgets");
  }
  dispose() {
    super.dispose();
    this.f = {};
  }
  getDomNode() {
    return this.h;
  }
  // ---- begin view event handlers
  onConfigurationChanged(e) {
    const options3 = this._context.configuration.options;
    const layoutInfo = options3.get(
      151
      /* EditorOption.layoutInfo */
    );
    this.j = layoutInfo.verticalScrollbarWidth;
    this.n = layoutInfo.minimap.minimapWidth;
    this.s = layoutInfo.horizontalScrollbarHeight;
    this.t = layoutInfo.height;
    this.w = layoutInfo.width;
    return true;
  }
  // ---- end view event handlers
  addWidget(widget) {
    const domNode = $oZ(widget.getDomNode());
    this.f[widget.getId()] = {
      widget,
      preference: null,
      domNode
    };
    domNode.setPosition("absolute");
    domNode.setAttribute("widgetId", widget.getId());
    if (widget.allowEditorOverflow) {
      this.overflowingOverlayWidgetsDomNode.appendChild(domNode);
    } else {
      this.h.appendChild(domNode);
    }
    this.u();
    this.y();
  }
  setWidgetPosition(widget, position) {
    const widgetData = this.f[widget.getId()];
    const preference = position ? position.preference : null;
    const stack = position?.stackOridinal;
    if (widgetData.preference === preference && widgetData.stack === stack) {
      this.y();
      return false;
    }
    widgetData.preference = preference;
    widgetData.stack = stack;
    this.u();
    this.y();
    return true;
  }
  removeWidget(widget) {
    const widgetId = widget.getId();
    if (this.f.hasOwnProperty(widgetId)) {
      const widgetData = this.f[widgetId];
      const domNode = widgetData.domNode.domNode;
      delete this.f[widgetId];
      domNode.remove();
      this.u();
      this.y();
    }
  }
  y() {
    let maxMinWidth = 0;
    const keys = Object.keys(this.f);
    for (let i2 = 0, len = keys.length; i2 < len; i2++) {
      const widgetId = keys[i2];
      const widget = this.f[widgetId];
      const widgetMinWidthInPx = widget.widget.getMinContentWidthInPx?.();
      if (typeof widgetMinWidthInPx !== "undefined") {
        maxMinWidth = Math.max(maxMinWidth, widgetMinWidthInPx);
      }
    }
    this._context.viewLayout.setOverlayWidgetsMinWidth(maxMinWidth);
  }
  z(widgetData, stackCoordinates) {
    const domNode = widgetData.domNode;
    if (widgetData.preference === null) {
      domNode.setTop("");
      return;
    }
    const maxRight = 2 * this.j + this.n;
    if (widgetData.preference === 0 || widgetData.preference === 1) {
      if (widgetData.preference === 1) {
        const widgetHeight = domNode.domNode.clientHeight;
        domNode.setTop(this.t - widgetHeight - 2 * this.s);
      } else {
        domNode.setTop(0);
      }
      if (widgetData.stack !== void 0) {
        domNode.setTop(stackCoordinates[widgetData.preference]);
        stackCoordinates[widgetData.preference] += domNode.domNode.clientWidth;
      } else {
        domNode.setRight(maxRight);
      }
    } else if (widgetData.preference === 2) {
      domNode.domNode.style.right = "50%";
      if (widgetData.stack !== void 0) {
        domNode.setTop(stackCoordinates[
          2
          /* OverlayWidgetPositionPreference.TOP_CENTER */
        ]);
        stackCoordinates[
          2
          /* OverlayWidgetPositionPreference.TOP_CENTER */
        ] += domNode.domNode.clientHeight;
      } else {
        domNode.setTop(0);
      }
    } else {
      const { top: top2, left } = widgetData.preference;
      const fixedOverflowWidgets = this._context.configuration.options.get(
        44
        /* EditorOption.fixedOverflowWidgets */
      );
      if (fixedOverflowWidgets && widgetData.widget.allowEditorOverflow) {
        const editorBoundingBox = this.g;
        domNode.setTop(top2 + editorBoundingBox.top);
        domNode.setLeft(left + editorBoundingBox.left);
        domNode.setPosition("fixed");
      } else {
        domNode.setTop(top2);
        domNode.setLeft(left);
        domNode.setPosition("absolute");
      }
    }
  }
  prepareRender(ctx) {
    this.g = $vj(this.c.domNode);
  }
  render(ctx) {
    this.h.setWidth(this.w);
    const keys = Object.keys(this.f);
    const stackCoordinates = Array.from({ length: 2 + 1 }, () => 0);
    keys.sort((a, b) => (this.f[a].stack || 0) - (this.f[b].stack || 0));
    for (let i2 = 0, len = keys.length; i2 < len; i2++) {
      const widgetId = keys[i2];
      this.z(this.f[widgetId], stackCoordinates);
    }
  }
};

// out-build/vs/editor/browser/viewParts/overviewRuler/decorationsOverviewRuler.js
var Settings = class {
  constructor(config, theme) {
    const options3 = config.options;
    this.lineHeight = options3.get(
      68
      /* EditorOption.lineHeight */
    );
    this.pixelRatio = options3.get(
      149
      /* EditorOption.pixelRatio */
    );
    this.overviewRulerLanes = options3.get(
      87
      /* EditorOption.overviewRulerLanes */
    );
    this.renderBorder = options3.get(
      86
      /* EditorOption.overviewRulerBorder */
    );
    const borderColor = theme.getColor($hH);
    this.borderColor = borderColor ? borderColor.toString() : null;
    this.hideCursor = options3.get(
      61
      /* EditorOption.hideCursorInOverviewRuler */
    );
    const cursorColorSingle = theme.getColor($RG);
    this.cursorColorSingle = cursorColorSingle ? cursorColorSingle.transparent(0.7).toString() : null;
    const cursorColorPrimary = theme.getColor($TG);
    this.cursorColorPrimary = cursorColorPrimary ? cursorColorPrimary.transparent(0.7).toString() : null;
    const cursorColorSecondary = theme.getColor($VG);
    this.cursorColorSecondary = cursorColorSecondary ? cursorColorSecondary.transparent(0.7).toString() : null;
    this.themeType = theme.type;
    const minimapOpts = options3.get(
      74
      /* EditorOption.minimap */
    );
    const minimapEnabled = minimapOpts.enabled;
    const minimapSide = minimapOpts.side;
    const themeColor = theme.getColor($iH);
    const defaultBackground = $YE.getDefaultBackground();
    if (themeColor) {
      this.backgroundColor = themeColor;
    } else if (minimapEnabled && minimapSide === "right") {
      this.backgroundColor = defaultBackground;
    } else {
      this.backgroundColor = null;
    }
    const layoutInfo = options3.get(
      151
      /* EditorOption.layoutInfo */
    );
    const position = layoutInfo.overviewRuler;
    this.top = position.top;
    this.right = position.right;
    this.domWidth = position.width;
    this.domHeight = position.height;
    if (this.overviewRulerLanes === 0) {
      this.canvasWidth = 0;
      this.canvasHeight = 0;
    } else {
      this.canvasWidth = this.domWidth * this.pixelRatio | 0;
      this.canvasHeight = this.domHeight * this.pixelRatio | 0;
    }
    const [x, w] = this.c(1, this.canvasWidth, this.overviewRulerLanes);
    this.x = x;
    this.w = w;
  }
  c(canvasLeftOffset, canvasWidth, laneCount) {
    const remainingWidth = canvasWidth - canvasLeftOffset;
    if (laneCount >= 3) {
      const leftWidth = Math.floor(remainingWidth / 3);
      const rightWidth = Math.floor(remainingWidth / 3);
      const centerWidth = remainingWidth - leftWidth - rightWidth;
      const leftOffset = canvasLeftOffset;
      const centerOffset = leftOffset + leftWidth;
      const rightOffset = leftOffset + leftWidth + centerWidth;
      return [
        [
          0,
          leftOffset,
          // Left
          centerOffset,
          // Center
          leftOffset,
          // Left | Center
          rightOffset,
          // Right
          leftOffset,
          // Left | Right
          centerOffset,
          // Center | Right
          leftOffset
          // Left | Center | Right
        ],
        [
          0,
          leftWidth,
          // Left
          centerWidth,
          // Center
          leftWidth + centerWidth,
          // Left | Center
          rightWidth,
          // Right
          leftWidth + centerWidth + rightWidth,
          // Left | Right
          centerWidth + rightWidth,
          // Center | Right
          leftWidth + centerWidth + rightWidth
          // Left | Center | Right
        ]
      ];
    } else if (laneCount === 2) {
      const leftWidth = Math.floor(remainingWidth / 2);
      const rightWidth = remainingWidth - leftWidth;
      const leftOffset = canvasLeftOffset;
      const rightOffset = leftOffset + leftWidth;
      return [
        [
          0,
          leftOffset,
          // Left
          leftOffset,
          // Center
          leftOffset,
          // Left | Center
          rightOffset,
          // Right
          leftOffset,
          // Left | Right
          leftOffset,
          // Center | Right
          leftOffset
          // Left | Center | Right
        ],
        [
          0,
          leftWidth,
          // Left
          leftWidth,
          // Center
          leftWidth,
          // Left | Center
          rightWidth,
          // Right
          leftWidth + rightWidth,
          // Left | Right
          leftWidth + rightWidth,
          // Center | Right
          leftWidth + rightWidth
          // Left | Center | Right
        ]
      ];
    } else {
      const offset = canvasLeftOffset;
      const width2 = remainingWidth;
      return [
        [
          0,
          offset,
          // Left
          offset,
          // Center
          offset,
          // Left | Center
          offset,
          // Right
          offset,
          // Left | Right
          offset,
          // Center | Right
          offset
          // Left | Center | Right
        ],
        [
          0,
          width2,
          // Left
          width2,
          // Center
          width2,
          // Left | Center
          width2,
          // Right
          width2,
          // Left | Right
          width2,
          // Center | Right
          width2
          // Left | Center | Right
        ]
      ];
    }
  }
  equals(other) {
    return this.lineHeight === other.lineHeight && this.pixelRatio === other.pixelRatio && this.overviewRulerLanes === other.overviewRulerLanes && this.renderBorder === other.renderBorder && this.borderColor === other.borderColor && this.hideCursor === other.hideCursor && this.cursorColorSingle === other.cursorColorSingle && this.cursorColorPrimary === other.cursorColorPrimary && this.cursorColorSecondary === other.cursorColorSecondary && this.themeType === other.themeType && $Vn.equals(this.backgroundColor, other.backgroundColor) && this.top === other.top && this.right === other.right && this.domWidth === other.domWidth && this.domHeight === other.domHeight && this.canvasWidth === other.canvasWidth && this.canvasHeight === other.canvasHeight;
  }
};
var Constants5;
(function(Constants27) {
  Constants27[Constants27["MIN_DECORATION_HEIGHT"] = 6] = "MIN_DECORATION_HEIGHT";
})(Constants5 || (Constants5 = {}));
var OverviewRulerLane2;
(function(OverviewRulerLane4) {
  OverviewRulerLane4[OverviewRulerLane4["Left"] = 1] = "Left";
  OverviewRulerLane4[OverviewRulerLane4["Center"] = 2] = "Center";
  OverviewRulerLane4[OverviewRulerLane4["Right"] = 4] = "Right";
  OverviewRulerLane4[OverviewRulerLane4["Full"] = 7] = "Full";
})(OverviewRulerLane2 || (OverviewRulerLane2 = {}));
var ShouldRenderValue;
(function(ShouldRenderValue2) {
  ShouldRenderValue2[ShouldRenderValue2["NotNeeded"] = 0] = "NotNeeded";
  ShouldRenderValue2[ShouldRenderValue2["Maybe"] = 1] = "Maybe";
  ShouldRenderValue2[ShouldRenderValue2["Needed"] = 2] = "Needed";
})(ShouldRenderValue || (ShouldRenderValue = {}));
var $J8 = class extends $f7 {
  constructor(context) {
    super(context);
    this.c = 0;
    this.n = [];
    this.s = [];
    this.g = $oZ(document.createElement("canvas"));
    this.g.setClassName("decorationsOverviewRuler");
    this.g.setPosition("absolute");
    this.g.setLayerHinting(true);
    this.g.setContain("strict");
    this.g.setAttribute("aria-hidden", "true");
    this.t(false);
    this.f = $YE.onDidChange((e) => {
      if (e.changedColorMap) {
        this.t(true);
      }
    });
    this.j = [{ position: new $8C(1, 1), color: this.h.cursorColorSingle }];
  }
  dispose() {
    super.dispose();
    this.f.dispose();
  }
  t(renderNow) {
    const newSettings = new Settings(this._context.configuration, this._context.theme);
    if (this.h && this.h.equals(newSettings)) {
      return false;
    }
    this.h = newSettings;
    this.g.setTop(this.h.top);
    this.g.setRight(this.h.right);
    this.g.setWidth(this.h.domWidth);
    this.g.setHeight(this.h.domHeight);
    this.g.domNode.width = this.h.canvasWidth;
    this.g.domNode.height = this.h.canvasHeight;
    if (renderNow) {
      this.C();
    }
    return true;
  }
  // ---- begin view event handlers
  y() {
    this.c = 2;
    return true;
  }
  z() {
    this.c = 1;
    return true;
  }
  onConfigurationChanged(e) {
    return this.t(false) ? this.y() : false;
  }
  onCursorStateChanged(e) {
    this.j = [];
    for (let i2 = 0, len = e.selections.length; i2 < len; i2++) {
      let color2 = this.h.cursorColorSingle;
      if (len > 1) {
        color2 = i2 === 0 ? this.h.cursorColorPrimary : this.h.cursorColorSecondary;
      }
      this.j.push({ position: e.selections[i2].getPosition(), color: color2 });
    }
    this.j.sort((a, b) => $8C.compare(a.position, b.position));
    return this.z();
  }
  onDecorationsChanged(e) {
    if (e.affectsOverviewRuler) {
      return this.z();
    }
    return false;
  }
  onFlushed(e) {
    return this.y();
  }
  onScrollChanged(e) {
    return e.scrollHeightChanged ? this.y() : false;
  }
  onZonesChanged(e) {
    return this.y();
  }
  onThemeChanged(e) {
    return this.t(false) ? this.y() : false;
  }
  // ---- end view event handlers
  getDomNode() {
    return this.g.domNode;
  }
  prepareRender(ctx) {
  }
  render(editorCtx) {
    this.C();
    this.c = 0;
  }
  C() {
    const backgroundColor = this.h.backgroundColor;
    if (this.h.overviewRulerLanes === 0) {
      this.g.setBackgroundColor(backgroundColor ? $Vn.Format.CSS.formatHexA(backgroundColor) : "");
      this.g.setDisplay("none");
      return;
    }
    const decorations = this._context.viewModel.getAllOverviewRulerDecorations(this._context.theme);
    decorations.sort($L5.compareByRenderingProps);
    if (this.c === 1 && !$L5.equalsArr(this.n, decorations)) {
      this.c = 2;
    }
    if (this.c === 1 && !$zb(this.s, this.j, (a, b) => a.position.lineNumber === b.position.lineNumber && a.color === b.color)) {
      this.c = 2;
    }
    if (this.c === 1) {
      return;
    }
    this.n = decorations;
    this.s = this.j;
    this.g.setDisplay("block");
    const canvasWidth = this.h.canvasWidth;
    const canvasHeight = this.h.canvasHeight;
    const lineHeight = this.h.lineHeight;
    const viewLayout = this._context.viewLayout;
    const outerHeight = this._context.viewLayout.getScrollHeight();
    const heightRatio = canvasHeight / outerHeight;
    const minDecorationHeight = 6 * this.h.pixelRatio | 0;
    const halfMinDecorationHeight = minDecorationHeight / 2 | 0;
    const canvasCtx = this.g.domNode.getContext("2d");
    if (backgroundColor) {
      if (backgroundColor.isOpaque()) {
        canvasCtx.fillStyle = $Vn.Format.CSS.formatHexA(backgroundColor);
        canvasCtx.fillRect(0, 0, canvasWidth, canvasHeight);
      } else {
        canvasCtx.clearRect(0, 0, canvasWidth, canvasHeight);
        canvasCtx.fillStyle = $Vn.Format.CSS.formatHexA(backgroundColor);
        canvasCtx.fillRect(0, 0, canvasWidth, canvasHeight);
      }
    } else {
      canvasCtx.clearRect(0, 0, canvasWidth, canvasHeight);
    }
    const x = this.h.x;
    const w = this.h.w;
    for (const decorationGroup of decorations) {
      const color2 = decorationGroup.color;
      const decorationGroupData = decorationGroup.data;
      canvasCtx.fillStyle = color2;
      let prevLane = 0;
      let prevY1 = 0;
      let prevY2 = 0;
      for (let i2 = 0, len = decorationGroupData.length / 3; i2 < len; i2++) {
        const lane = decorationGroupData[3 * i2];
        const startLineNumber = decorationGroupData[3 * i2 + 1];
        const endLineNumber = decorationGroupData[3 * i2 + 2];
        let y1 = viewLayout.getVerticalOffsetForLineNumber(startLineNumber) * heightRatio | 0;
        let y2 = (viewLayout.getVerticalOffsetForLineNumber(endLineNumber) + lineHeight) * heightRatio | 0;
        const height = y2 - y1;
        if (height < minDecorationHeight) {
          let yCenter = (y1 + y2) / 2 | 0;
          if (yCenter < halfMinDecorationHeight) {
            yCenter = halfMinDecorationHeight;
          } else if (yCenter + halfMinDecorationHeight > canvasHeight) {
            yCenter = canvasHeight - halfMinDecorationHeight;
          }
          y1 = yCenter - halfMinDecorationHeight;
          y2 = yCenter + halfMinDecorationHeight;
        }
        if (y1 > prevY2 + 1 || lane !== prevLane) {
          if (i2 !== 0) {
            canvasCtx.fillRect(x[prevLane], prevY1, w[prevLane], prevY2 - prevY1);
          }
          prevLane = lane;
          prevY1 = y1;
          prevY2 = y2;
        } else {
          if (y2 > prevY2) {
            prevY2 = y2;
          }
        }
      }
      canvasCtx.fillRect(x[prevLane], prevY1, w[prevLane], prevY2 - prevY1);
    }
    if (!this.h.hideCursor) {
      const cursorHeight = 2 * this.h.pixelRatio | 0;
      const halfCursorHeight = cursorHeight / 2 | 0;
      const cursorX = this.h.x[
        7
        /* OverviewRulerLane.Full */
      ];
      const cursorW = this.h.w[
        7
        /* OverviewRulerLane.Full */
      ];
      let prevY1 = -100;
      let prevY2 = -100;
      let prevColor = null;
      for (let i2 = 0, len = this.j.length; i2 < len; i2++) {
        const color2 = this.j[i2].color;
        if (!color2) {
          continue;
        }
        const cursor = this.j[i2].position;
        let yCenter = viewLayout.getVerticalOffsetForLineNumber(cursor.lineNumber) * heightRatio | 0;
        if (yCenter < halfCursorHeight) {
          yCenter = halfCursorHeight;
        } else if (yCenter + halfCursorHeight > canvasHeight) {
          yCenter = canvasHeight - halfCursorHeight;
        }
        const y1 = yCenter - halfCursorHeight;
        const y2 = y1 + cursorHeight;
        if (y1 > prevY2 + 1 || color2 !== prevColor) {
          if (i2 !== 0 && prevColor) {
            canvasCtx.fillRect(cursorX, prevY1, cursorW, prevY2 - prevY1);
          }
          prevY1 = y1;
          prevY2 = y2;
        } else {
          if (y2 > prevY2) {
            prevY2 = y2;
          }
        }
        prevColor = color2;
        canvasCtx.fillStyle = color2;
      }
      if (prevColor) {
        canvasCtx.fillRect(cursorX, prevY1, cursorW, prevY2 - prevY1);
      }
    }
    if (this.h.renderBorder && this.h.borderColor && this.h.overviewRulerLanes > 0) {
      canvasCtx.beginPath();
      canvasCtx.lineWidth = 1;
      canvasCtx.strokeStyle = this.h.borderColor;
      canvasCtx.moveTo(0, 0);
      canvasCtx.lineTo(0, canvasHeight);
      canvasCtx.moveTo(1, 0);
      canvasCtx.lineTo(canvasWidth, 0);
      canvasCtx.stroke();
    }
  }
};

// out-build/vs/editor/common/viewModel/overviewZoneManager.js
var Constants6;
(function(Constants27) {
  Constants27[Constants27["MINIMUM_HEIGHT"] = 4] = "MINIMUM_HEIGHT";
})(Constants6 || (Constants6 = {}));
var $M5 = class {
  constructor(from, to, colorId) {
    this._colorZoneBrand = void 0;
    this.from = from | 0;
    this.to = to | 0;
    this.colorId = colorId | 0;
  }
  static compare(a, b) {
    if (a.colorId === b.colorId) {
      if (a.from === b.from) {
        return a.to - b.to;
      }
      return a.from - b.from;
    }
    return a.colorId - b.colorId;
  }
};
var $N5 = class {
  constructor(startLineNumber, endLineNumber, heightInLines, color2) {
    this._overviewRulerZoneBrand = void 0;
    this.startLineNumber = startLineNumber;
    this.endLineNumber = endLineNumber;
    this.heightInLines = heightInLines;
    this.color = color2;
    this.c = null;
  }
  static compare(a, b) {
    if (a.color === b.color) {
      if (a.startLineNumber === b.startLineNumber) {
        if (a.heightInLines === b.heightInLines) {
          return a.endLineNumber - b.endLineNumber;
        }
        return a.heightInLines - b.heightInLines;
      }
      return a.startLineNumber - b.startLineNumber;
    }
    return a.color < b.color ? -1 : 1;
  }
  setColorZone(colorZone) {
    this.c = colorZone;
  }
  getColorZones() {
    return this.c;
  }
};
var $O5 = class {
  constructor(getVerticalOffsetForLine) {
    this.c = getVerticalOffsetForLine;
    this.d = [];
    this.e = false;
    this.f = 0;
    this.g = 0;
    this.h = 0;
    this.j = 0;
    this.k = 1;
    this.l = 0;
    this.m = /* @__PURE__ */ Object.create(null);
    this.n = [];
  }
  getId2Color() {
    return this.n;
  }
  setZones(newZones) {
    this.d = newZones;
    this.d.sort($N5.compare);
  }
  setLineHeight(lineHeight) {
    if (this.f === lineHeight) {
      return false;
    }
    this.f = lineHeight;
    this.e = true;
    return true;
  }
  setPixelRatio(pixelRatio) {
    this.k = pixelRatio;
    this.e = true;
  }
  getDOMWidth() {
    return this.g;
  }
  getCanvasWidth() {
    return this.g * this.k;
  }
  setDOMWidth(width2) {
    if (this.g === width2) {
      return false;
    }
    this.g = width2;
    this.e = true;
    return true;
  }
  getDOMHeight() {
    return this.h;
  }
  getCanvasHeight() {
    return this.h * this.k;
  }
  setDOMHeight(height) {
    if (this.h === height) {
      return false;
    }
    this.h = height;
    this.e = true;
    return true;
  }
  getOuterHeight() {
    return this.j;
  }
  setOuterHeight(outerHeight) {
    if (this.j === outerHeight) {
      return false;
    }
    this.j = outerHeight;
    this.e = true;
    return true;
  }
  resolveColorZones() {
    const colorZonesInvalid = this.e;
    const lineHeight = Math.floor(this.f);
    const totalHeight = Math.floor(this.getCanvasHeight());
    const outerHeight = Math.floor(this.j);
    const heightRatio = totalHeight / outerHeight;
    const halfMinimumHeight = Math.floor(4 * this.k / 2);
    const allColorZones = [];
    for (let i2 = 0, len = this.d.length; i2 < len; i2++) {
      const zone = this.d[i2];
      if (!colorZonesInvalid) {
        const colorZone2 = zone.getColorZones();
        if (colorZone2) {
          allColorZones.push(colorZone2);
          continue;
        }
      }
      const offset1 = this.c(zone.startLineNumber);
      const offset2 = zone.heightInLines === 0 ? this.c(zone.endLineNumber) + lineHeight : offset1 + zone.heightInLines * lineHeight;
      const y1 = Math.floor(heightRatio * offset1);
      const y2 = Math.floor(heightRatio * offset2);
      let ycenter = Math.floor((y1 + y2) / 2);
      let halfHeight = y2 - ycenter;
      if (halfHeight < halfMinimumHeight) {
        halfHeight = halfMinimumHeight;
      }
      if (ycenter - halfHeight < 0) {
        ycenter = halfHeight;
      }
      if (ycenter + halfHeight > totalHeight) {
        ycenter = totalHeight - halfHeight;
      }
      const color2 = zone.color;
      let colorId = this.m[color2];
      if (!colorId) {
        colorId = ++this.l;
        this.m[color2] = colorId;
        this.n[colorId] = color2;
      }
      const colorZone = new $M5(ycenter - halfHeight, ycenter + halfHeight, colorId);
      zone.setColorZone(colorZone);
      allColorZones.push(colorZone);
    }
    this.e = false;
    allColorZones.sort($M5.compare);
    return allColorZones;
  }
};

// out-build/vs/editor/browser/viewParts/overviewRuler/overviewRuler.js
var $K8 = class extends $D5 {
  constructor(context, cssClassName) {
    super();
    this.a = context;
    const options3 = this.a.configuration.options;
    this.b = $oZ(document.createElement("canvas"));
    this.b.setClassName(cssClassName);
    this.b.setPosition("absolute");
    this.b.setLayerHinting(true);
    this.b.setContain("strict");
    this.c = new $O5((lineNumber) => this.a.viewLayout.getVerticalOffsetForLineNumber(lineNumber));
    this.c.setDOMWidth(0);
    this.c.setDOMHeight(0);
    this.c.setOuterHeight(this.a.viewLayout.getScrollHeight());
    this.c.setLineHeight(options3.get(
      68
      /* EditorOption.lineHeight */
    ));
    this.c.setPixelRatio(options3.get(
      149
      /* EditorOption.pixelRatio */
    ));
    this.a.addEventHandler(this);
  }
  dispose() {
    this.a.removeEventHandler(this);
    super.dispose();
  }
  // ---- begin view event handlers
  onConfigurationChanged(e) {
    const options3 = this.a.configuration.options;
    if (e.hasChanged(
      68
      /* EditorOption.lineHeight */
    )) {
      this.c.setLineHeight(options3.get(
        68
        /* EditorOption.lineHeight */
      ));
      this.f();
    }
    if (e.hasChanged(
      149
      /* EditorOption.pixelRatio */
    )) {
      this.c.setPixelRatio(options3.get(
        149
        /* EditorOption.pixelRatio */
      ));
      this.b.setWidth(this.c.getDOMWidth());
      this.b.setHeight(this.c.getDOMHeight());
      this.b.domNode.width = this.c.getCanvasWidth();
      this.b.domNode.height = this.c.getCanvasHeight();
      this.f();
    }
    return true;
  }
  onFlushed(e) {
    this.f();
    return true;
  }
  onScrollChanged(e) {
    if (e.scrollHeightChanged) {
      this.c.setOuterHeight(e.scrollHeight);
      this.f();
    }
    return true;
  }
  onZonesChanged(e) {
    this.f();
    return true;
  }
  // ---- end view event handlers
  getDomNode() {
    return this.b.domNode;
  }
  setLayout(position) {
    this.b.setTop(position.top);
    this.b.setRight(position.right);
    let hasChanged = false;
    hasChanged = this.c.setDOMWidth(position.width) || hasChanged;
    hasChanged = this.c.setDOMHeight(position.height) || hasChanged;
    if (hasChanged) {
      this.b.setWidth(this.c.getDOMWidth());
      this.b.setHeight(this.c.getDOMHeight());
      this.b.domNode.width = this.c.getCanvasWidth();
      this.b.domNode.height = this.c.getCanvasHeight();
      this.f();
    }
  }
  setZones(zones) {
    this.c.setZones(zones);
    this.f();
  }
  f() {
    if (this.c.getOuterHeight() === 0) {
      return false;
    }
    const width2 = this.c.getCanvasWidth();
    const height = this.c.getCanvasHeight();
    const colorZones = this.c.resolveColorZones();
    const id2Color = this.c.getId2Color();
    const ctx = this.b.domNode.getContext("2d");
    ctx.clearRect(0, 0, width2, height);
    if (colorZones.length > 0) {
      this.g(ctx, colorZones, id2Color, width2);
    }
    return true;
  }
  g(ctx, colorZones, id2Color, width2) {
    let currentColorId = 0;
    let currentFrom = 0;
    let currentTo = 0;
    for (const zone of colorZones) {
      const zoneColorId = zone.colorId;
      const zoneFrom = zone.from;
      const zoneTo = zone.to;
      if (zoneColorId !== currentColorId) {
        ctx.fillRect(0, currentFrom, width2, currentTo - currentFrom);
        currentColorId = zoneColorId;
        ctx.fillStyle = id2Color[currentColorId];
        currentFrom = zoneFrom;
        currentTo = zoneTo;
      } else {
        if (currentTo >= zoneFrom) {
          currentTo = Math.max(currentTo, zoneTo);
        } else {
          ctx.fillRect(0, currentFrom, width2, currentTo - currentFrom);
          currentFrom = zoneFrom;
          currentTo = zoneTo;
        }
      }
    }
    ctx.fillRect(0, currentFrom, width2, currentTo - currentFrom);
  }
};

// out-build/vs/editor/browser/viewParts/rulers/rulers.js
var $L8 = class extends $f7 {
  constructor(context) {
    super(context);
    this.domNode = $oZ(document.createElement("div"));
    this.domNode.setAttribute("role", "presentation");
    this.domNode.setAttribute("aria-hidden", "true");
    this.domNode.setClassName("view-rulers");
    this.a = [];
    const options3 = this._context.configuration.options;
    this.b = options3.get(
      107
      /* EditorOption.rulers */
    );
    this.c = options3.get(
      52
      /* EditorOption.fontInfo */
    ).typicalHalfwidthCharacterWidth;
  }
  dispose() {
    super.dispose();
  }
  // --- begin event handlers
  onConfigurationChanged(e) {
    const options3 = this._context.configuration.options;
    this.b = options3.get(
      107
      /* EditorOption.rulers */
    );
    this.c = options3.get(
      52
      /* EditorOption.fontInfo */
    ).typicalHalfwidthCharacterWidth;
    return true;
  }
  onScrollChanged(e) {
    return e.scrollHeightChanged;
  }
  // --- end event handlers
  prepareRender(ctx) {
  }
  f() {
    const currentCount = this.a.length;
    const desiredCount = this.b.length;
    if (currentCount === desiredCount) {
      return;
    }
    if (currentCount < desiredCount) {
      const { tabSize } = this._context.viewModel.model.getOptions();
      const rulerWidth = tabSize;
      let addCount = desiredCount - currentCount;
      while (addCount > 0) {
        const node = $oZ(document.createElement("div"));
        node.setClassName("view-ruler");
        node.setWidth(rulerWidth);
        this.domNode.appendChild(node);
        this.a.push(node);
        addCount--;
      }
      return;
    }
    let removeCount = currentCount - desiredCount;
    while (removeCount > 0) {
      const node = this.a.pop();
      this.domNode.removeChild(node);
      removeCount--;
    }
  }
  render(ctx) {
    this.f();
    for (let i2 = 0, len = this.b.length; i2 < len; i2++) {
      const node = this.a[i2];
      const ruler = this.b[i2];
      node.setBoxShadow(ruler.color ? `1px 0 0 0 ${ruler.color} inset` : ``);
      node.setHeight(Math.min(ctx.scrollHeight, 1e6));
      node.setLeft(ruler.column * this.c);
    }
  }
};

// out-build/vs/editor/browser/viewParts/scrollDecoration/scrollDecoration.js
var $M8 = class extends $f7 {
  constructor(context) {
    super(context);
    this.b = 0;
    this.c = 0;
    this.j();
    this.f = false;
    const options3 = this._context.configuration.options;
    const scrollbar = options3.get(
      108
      /* EditorOption.scrollbar */
    );
    this.g = scrollbar.useShadows;
    this.a = $oZ(document.createElement("div"));
    this.a.setAttribute("role", "presentation");
    this.a.setAttribute("aria-hidden", "true");
  }
  dispose() {
    super.dispose();
  }
  h() {
    const newShouldShow = this.g && this.b > 0;
    if (this.f !== newShouldShow) {
      this.f = newShouldShow;
      return true;
    }
    return false;
  }
  getDomNode() {
    return this.a;
  }
  j() {
    const options3 = this._context.configuration.options;
    const layoutInfo = options3.get(
      151
      /* EditorOption.layoutInfo */
    );
    if (layoutInfo.minimap.renderMinimap === 0 || layoutInfo.minimap.minimapWidth > 0 && layoutInfo.minimap.minimapLeft === 0) {
      this.c = layoutInfo.width;
    } else {
      this.c = layoutInfo.width - layoutInfo.verticalScrollbarWidth;
    }
  }
  // --- begin event handlers
  onConfigurationChanged(e) {
    const options3 = this._context.configuration.options;
    const scrollbar = options3.get(
      108
      /* EditorOption.scrollbar */
    );
    this.g = scrollbar.useShadows;
    this.j();
    this.h();
    return true;
  }
  onScrollChanged(e) {
    this.b = e.scrollTop;
    return this.h();
  }
  // --- end event handlers
  prepareRender(ctx) {
  }
  render(ctx) {
    this.a.setWidth(this.c);
    this.a.setClassName(this.f ? "scroll-decoration" : "");
  }
};

// out-build/vs/editor/browser/viewParts/selections/selections.js
var CornerStyle;
(function(CornerStyle2) {
  CornerStyle2[CornerStyle2["EXTERN"] = 0] = "EXTERN";
  CornerStyle2[CornerStyle2["INTERN"] = 1] = "INTERN";
  CornerStyle2[CornerStyle2["FLAT"] = 2] = "FLAT";
})(CornerStyle || (CornerStyle = {}));
var HorizontalRangeWithStyle = class {
  constructor(other) {
    this.left = other.left;
    this.width = other.width;
    this.startStyle = null;
    this.endStyle = null;
  }
};
var LineVisibleRangesWithStyle = class {
  constructor(lineNumber, ranges) {
    this.lineNumber = lineNumber;
    this.ranges = ranges;
  }
};
function toStyledRange(item) {
  return new HorizontalRangeWithStyle(item);
}
function toStyled(item) {
  return new LineVisibleRangesWithStyle(item.lineNumber, item.ranges.map(toStyledRange));
}
var $N8 = class _$N8 extends $d8 {
  static {
    this.a = "selected-text";
  }
  static {
    this.b = "top-left-radius";
  }
  static {
    this.c = "bottom-left-radius";
  }
  static {
    this.f = "top-right-radius";
  }
  static {
    this.g = "bottom-right-radius";
  }
  static {
    this.h = "monaco-editor-background";
  }
  static {
    this.r = 10;
  }
  constructor(context) {
    super();
    this.I = [];
    this.s = context;
    const options3 = this.s.configuration.options;
    this.t = options3.get(
      106
      /* EditorOption.roundedSelection */
    );
    this.w = options3.get(
      52
      /* EditorOption.fontInfo */
    ).typicalHalfwidthCharacterWidth;
    this.y = [];
    this.z = null;
    this.s.addEventHandler(this);
  }
  dispose() {
    this.s.removeEventHandler(this);
    this.z = null;
    super.dispose();
  }
  // --- begin event handlers
  onConfigurationChanged(e) {
    const options3 = this.s.configuration.options;
    this.t = options3.get(
      106
      /* EditorOption.roundedSelection */
    );
    this.w = options3.get(
      52
      /* EditorOption.fontInfo */
    ).typicalHalfwidthCharacterWidth;
    return true;
  }
  onCursorStateChanged(e) {
    this.y = e.selections.slice(0);
    return true;
  }
  onDecorationsChanged(e) {
    return true;
  }
  onFlushed(e) {
    return true;
  }
  onLinesChanged(e) {
    return true;
  }
  onLinesDeleted(e) {
    return true;
  }
  onLinesInserted(e) {
    return true;
  }
  onScrollChanged(e) {
    return e.scrollTopChanged;
  }
  onZonesChanged(e) {
    return true;
  }
  // --- end event handlers
  C(linesVisibleRanges) {
    for (let i2 = 0, len = linesVisibleRanges.length; i2 < len; i2++) {
      const lineVisibleRanges = linesVisibleRanges[i2];
      if (lineVisibleRanges.ranges.length > 1) {
        return true;
      }
    }
    return false;
  }
  D(viewport, linesVisibleRanges, previousFrame) {
    const epsilon2 = this.w / 4;
    let previousFrameTop = null;
    let previousFrameBottom = null;
    if (previousFrame && previousFrame.length > 0 && linesVisibleRanges.length > 0) {
      const topLineNumber = linesVisibleRanges[0].lineNumber;
      if (topLineNumber === viewport.startLineNumber) {
        for (let i2 = 0; !previousFrameTop && i2 < previousFrame.length; i2++) {
          if (previousFrame[i2].lineNumber === topLineNumber) {
            previousFrameTop = previousFrame[i2].ranges[0];
          }
        }
      }
      const bottomLineNumber = linesVisibleRanges[linesVisibleRanges.length - 1].lineNumber;
      if (bottomLineNumber === viewport.endLineNumber) {
        for (let i2 = previousFrame.length - 1; !previousFrameBottom && i2 >= 0; i2--) {
          if (previousFrame[i2].lineNumber === bottomLineNumber) {
            previousFrameBottom = previousFrame[i2].ranges[0];
          }
        }
      }
      if (previousFrameTop && !previousFrameTop.startStyle) {
        previousFrameTop = null;
      }
      if (previousFrameBottom && !previousFrameBottom.startStyle) {
        previousFrameBottom = null;
      }
    }
    for (let i2 = 0, len = linesVisibleRanges.length; i2 < len; i2++) {
      const curLineRange = linesVisibleRanges[i2].ranges[0];
      const curLeft = curLineRange.left;
      const curRight = curLineRange.left + curLineRange.width;
      const startStyle = {
        top: 0,
        bottom: 0
        /* CornerStyle.EXTERN */
      };
      const endStyle = {
        top: 0,
        bottom: 0
        /* CornerStyle.EXTERN */
      };
      if (i2 > 0) {
        const prevLeft = linesVisibleRanges[i2 - 1].ranges[0].left;
        const prevRight = linesVisibleRanges[i2 - 1].ranges[0].left + linesVisibleRanges[i2 - 1].ranges[0].width;
        if (abs(curLeft - prevLeft) < epsilon2) {
          startStyle.top = 2;
        } else if (curLeft > prevLeft) {
          startStyle.top = 1;
        }
        if (abs(curRight - prevRight) < epsilon2) {
          endStyle.top = 2;
        } else if (prevLeft < curRight && curRight < prevRight) {
          endStyle.top = 1;
        }
      } else if (previousFrameTop) {
        startStyle.top = previousFrameTop.startStyle.top;
        endStyle.top = previousFrameTop.endStyle.top;
      }
      if (i2 + 1 < len) {
        const nextLeft = linesVisibleRanges[i2 + 1].ranges[0].left;
        const nextRight = linesVisibleRanges[i2 + 1].ranges[0].left + linesVisibleRanges[i2 + 1].ranges[0].width;
        if (abs(curLeft - nextLeft) < epsilon2) {
          startStyle.bottom = 2;
        } else if (nextLeft < curLeft && curLeft < nextRight) {
          startStyle.bottom = 1;
        }
        if (abs(curRight - nextRight) < epsilon2) {
          endStyle.bottom = 2;
        } else if (curRight < nextRight) {
          endStyle.bottom = 1;
        }
      } else if (previousFrameBottom) {
        startStyle.bottom = previousFrameBottom.startStyle.bottom;
        endStyle.bottom = previousFrameBottom.endStyle.bottom;
      }
      curLineRange.startStyle = startStyle;
      curLineRange.endStyle = endStyle;
    }
  }
  F(selection, ctx, previousFrame) {
    const _linesVisibleRanges = ctx.linesVisibleRangesForRange(selection, true) || [];
    const linesVisibleRanges = _linesVisibleRanges.map(toStyled);
    const visibleRangesHaveGaps = this.C(linesVisibleRanges);
    if (!visibleRangesHaveGaps && this.t) {
      this.D(ctx.visibleRange, linesVisibleRanges, previousFrame);
    }
    return linesVisibleRanges;
  }
  G(top2, bottom, className, left, width2) {
    return '<div class="cslr ' + className + '" style="top:' + top2.toString() + "px;bottom:" + bottom.toString() + "px;left:" + left.toString() + "px;width:" + width2.toString() + 'px;"></div>';
  }
  H(output2, visibleStartLineNumber, hasMultipleSelections, visibleRanges) {
    if (visibleRanges.length === 0) {
      return;
    }
    const visibleRangesHaveStyle = !!visibleRanges[0].ranges[0].startStyle;
    const firstLineNumber = visibleRanges[0].lineNumber;
    const lastLineNumber = visibleRanges[visibleRanges.length - 1].lineNumber;
    for (let i2 = 0, len = visibleRanges.length; i2 < len; i2++) {
      const lineVisibleRanges = visibleRanges[i2];
      const lineNumber = lineVisibleRanges.lineNumber;
      const lineIndex = lineNumber - visibleStartLineNumber;
      const top2 = hasMultipleSelections ? lineNumber === firstLineNumber ? 1 : 0 : 0;
      const bottom = hasMultipleSelections ? lineNumber !== firstLineNumber && lineNumber === lastLineNumber ? 1 : 0 : 0;
      let innerCornerOutput = "";
      let restOfSelectionOutput = "";
      for (let j = 0, lenJ = lineVisibleRanges.ranges.length; j < lenJ; j++) {
        const visibleRange = lineVisibleRanges.ranges[j];
        if (visibleRangesHaveStyle) {
          const startStyle = visibleRange.startStyle;
          const endStyle = visibleRange.endStyle;
          if (startStyle.top === 1 || startStyle.bottom === 1) {
            innerCornerOutput += this.G(top2, bottom, _$N8.a, visibleRange.left - _$N8.r, _$N8.r);
            let className2 = _$N8.h;
            if (startStyle.top === 1) {
              className2 += " " + _$N8.f;
            }
            if (startStyle.bottom === 1) {
              className2 += " " + _$N8.g;
            }
            innerCornerOutput += this.G(top2, bottom, className2, visibleRange.left - _$N8.r, _$N8.r);
          }
          if (endStyle.top === 1 || endStyle.bottom === 1) {
            innerCornerOutput += this.G(top2, bottom, _$N8.a, visibleRange.left + visibleRange.width, _$N8.r);
            let className2 = _$N8.h;
            if (endStyle.top === 1) {
              className2 += " " + _$N8.b;
            }
            if (endStyle.bottom === 1) {
              className2 += " " + _$N8.c;
            }
            innerCornerOutput += this.G(top2, bottom, className2, visibleRange.left + visibleRange.width, _$N8.r);
          }
        }
        let className = _$N8.a;
        if (visibleRangesHaveStyle) {
          const startStyle = visibleRange.startStyle;
          const endStyle = visibleRange.endStyle;
          if (startStyle.top === 0) {
            className += " " + _$N8.b;
          }
          if (startStyle.bottom === 0) {
            className += " " + _$N8.c;
          }
          if (endStyle.top === 0) {
            className += " " + _$N8.f;
          }
          if (endStyle.bottom === 0) {
            className += " " + _$N8.g;
          }
        }
        restOfSelectionOutput += this.G(top2, bottom, className, visibleRange.left, visibleRange.width);
      }
      output2[lineIndex][0] += innerCornerOutput;
      output2[lineIndex][1] += restOfSelectionOutput;
    }
  }
  prepareRender(ctx) {
    const output = [];
    const visibleStartLineNumber = ctx.visibleRange.startLineNumber;
    const visibleEndLineNumber = ctx.visibleRange.endLineNumber;
    for (let lineNumber = visibleStartLineNumber; lineNumber <= visibleEndLineNumber; lineNumber++) {
      const lineIndex = lineNumber - visibleStartLineNumber;
      output[lineIndex] = ["", ""];
    }
    const thisFrameVisibleRangesWithStyle = [];
    for (let i2 = 0, len = this.y.length; i2 < len; i2++) {
      const selection = this.y[i2];
      if (selection.isEmpty()) {
        thisFrameVisibleRangesWithStyle[i2] = null;
        continue;
      }
      const visibleRangesWithStyle = this.F(selection, ctx, this.I[i2]);
      thisFrameVisibleRangesWithStyle[i2] = visibleRangesWithStyle;
      this.H(output, visibleStartLineNumber, this.y.length > 1, visibleRangesWithStyle);
    }
    this.I = thisFrameVisibleRangesWithStyle;
    this.z = output.map(([internalCorners, restOfSelection]) => internalCorners + restOfSelection);
  }
  render(startLineNumber, lineNumber) {
    if (!this.z) {
      return "";
    }
    const lineIndex = lineNumber - startLineNumber;
    if (lineIndex < 0 || lineIndex >= this.z.length) {
      return "";
    }
    return this.z[lineIndex];
  }
};
$ms((theme, collector) => {
  const editorSelectionForegroundColor = theme.getColor($8o);
  if (editorSelectionForegroundColor && !editorSelectionForegroundColor.isTransparent()) {
    collector.addRule(`.monaco-editor .view-line span.inline-selected-text { color: ${editorSelectionForegroundColor}; }`);
  }
});
function abs(n) {
  return n < 0 ? -n : n;
}

// out-build/vs/editor/browser/viewParts/viewCursors/viewCursor.js
var ViewCursorRenderData = class {
  constructor(top2, left, paddingLeft, width2, height, textContent, textContentClassName) {
    this.top = top2;
    this.left = left;
    this.paddingLeft = paddingLeft;
    this.width = width2;
    this.height = height;
    this.textContent = textContent;
    this.textContentClassName = textContentClassName;
  }
};
var CursorPlurality;
(function(CursorPlurality2) {
  CursorPlurality2[CursorPlurality2["Single"] = 0] = "Single";
  CursorPlurality2[CursorPlurality2["MultiPrimary"] = 1] = "MultiPrimary";
  CursorPlurality2[CursorPlurality2["MultiSecondary"] = 2] = "MultiSecondary";
})(CursorPlurality || (CursorPlurality = {}));
var $R7 = class {
  constructor(context, plurality) {
    this.a = context;
    const options3 = this.a.configuration.options;
    const fontInfo = options3.get(
      52
      /* EditorOption.fontInfo */
    );
    this.c = options3.get(
      147
      /* EditorOption.effectiveCursorStyle */
    );
    this.f = options3.get(
      68
      /* EditorOption.lineHeight */
    );
    this.g = fontInfo.typicalHalfwidthCharacterWidth;
    this.d = Math.min(options3.get(
      31
      /* EditorOption.cursorWidth */
    ), this.g);
    this.h = true;
    this.b = $oZ(document.createElement("div"));
    this.b.setClassName(`cursor ${$62}`);
    this.b.setHeight(this.f);
    this.b.setTop(0);
    this.b.setLeft(0);
    $24(this.b, fontInfo);
    this.b.setDisplay("none");
    this.i = new $8C(1, 1);
    this.j = "";
    this.setPlurality(plurality);
    this.k = "";
    this.l = null;
  }
  getDomNode() {
    return this.b;
  }
  getPosition() {
    return this.i;
  }
  setPlurality(plurality) {
    switch (plurality) {
      default:
      case CursorPlurality.Single:
        this.j = "";
        break;
      case CursorPlurality.MultiPrimary:
        this.j = "cursor-primary";
        break;
      case CursorPlurality.MultiSecondary:
        this.j = "cursor-secondary";
        break;
    }
  }
  show() {
    if (!this.h) {
      this.b.setVisibility("inherit");
      this.h = true;
    }
  }
  hide() {
    if (this.h) {
      this.b.setVisibility("hidden");
      this.h = false;
    }
  }
  onConfigurationChanged(e) {
    const options3 = this.a.configuration.options;
    const fontInfo = options3.get(
      52
      /* EditorOption.fontInfo */
    );
    this.c = options3.get(
      147
      /* EditorOption.effectiveCursorStyle */
    );
    this.f = options3.get(
      68
      /* EditorOption.lineHeight */
    );
    this.g = fontInfo.typicalHalfwidthCharacterWidth;
    this.d = Math.min(options3.get(
      31
      /* EditorOption.cursorWidth */
    ), this.g);
    $24(this.b, fontInfo);
    return true;
  }
  onCursorPositionChanged(position, pauseAnimation) {
    if (pauseAnimation) {
      this.b.domNode.style.transitionProperty = "none";
    } else {
      this.b.domNode.style.transitionProperty = "";
    }
    this.i = position;
    return true;
  }
  /**
   * If `this._position` is inside a grapheme, returns the position where the grapheme starts.
   * Also returns the next grapheme.
   */
  m() {
    const { lineNumber, column } = this.i;
    const lineContent = this.a.viewModel.getLineContent(lineNumber);
    const [startOffset, endOffset] = $ag(lineContent, column - 1);
    return [new $8C(lineNumber, startOffset + 1), lineContent.substring(startOffset, endOffset)];
  }
  n(ctx) {
    let textContent = "";
    let textContentClassName = "";
    const [position, nextGrapheme] = this.m();
    if (this.c === TextEditorCursorStyle.Line || this.c === TextEditorCursorStyle.LineThin) {
      const visibleRange = ctx.visibleRangeForPosition(position);
      if (!visibleRange || visibleRange.outsideRenderedLine) {
        return null;
      }
      const window3 = getWindow(this.b.domNode);
      let width3;
      if (this.c === TextEditorCursorStyle.Line) {
        width3 = $mk(window3, this.d > 0 ? this.d : 2);
        if (width3 > 2) {
          textContent = nextGrapheme;
          textContentClassName = this.o(position);
        }
      } else {
        width3 = $mk(window3, 1);
      }
      let left = visibleRange.left;
      let paddingLeft = 0;
      if (width3 >= 2 && left >= 1) {
        paddingLeft = 1;
        left -= paddingLeft;
      }
      const top3 = ctx.getVerticalOffsetForLineNumber(position.lineNumber) - ctx.bigNumbersDelta;
      return new ViewCursorRenderData(top3, left, paddingLeft, width3, this.f, textContent, textContentClassName);
    }
    const visibleRangeForCharacter = ctx.linesVisibleRangesForRange(new $9C(position.lineNumber, position.column, position.lineNumber, position.column + nextGrapheme.length), false);
    if (!visibleRangeForCharacter || visibleRangeForCharacter.length === 0) {
      return null;
    }
    const firstVisibleRangeForCharacter = visibleRangeForCharacter[0];
    if (firstVisibleRangeForCharacter.outsideRenderedLine || firstVisibleRangeForCharacter.ranges.length === 0) {
      return null;
    }
    const range = firstVisibleRangeForCharacter.ranges[0];
    const width2 = nextGrapheme === "	" ? this.g : range.width < 1 ? this.g : range.width;
    if (this.c === TextEditorCursorStyle.Block) {
      textContent = nextGrapheme;
      textContentClassName = this.o(position);
    }
    let top2 = ctx.getVerticalOffsetForLineNumber(position.lineNumber) - ctx.bigNumbersDelta;
    let height = this.f;
    if (this.c === TextEditorCursorStyle.Underline || this.c === TextEditorCursorStyle.UnderlineThin) {
      top2 += this.f - 2;
      height = 2;
    }
    return new ViewCursorRenderData(top2, range.left, 0, width2, height, textContent, textContentClassName);
  }
  o(position) {
    const lineData = this.a.viewModel.getViewLineData(position.lineNumber);
    const tokenIndex = lineData.tokens.findTokenIndexAtOffset(position.column - 1);
    return lineData.tokens.getClassName(tokenIndex);
  }
  prepareRender(ctx) {
    this.l = this.n(ctx);
  }
  render(ctx) {
    if (!this.l) {
      this.b.setDisplay("none");
      return null;
    }
    if (this.k !== this.l.textContent) {
      this.k = this.l.textContent;
      this.b.domNode.textContent = this.k;
    }
    this.b.setClassName(`cursor ${this.j} ${$62} ${this.l.textContentClassName}`);
    this.b.setDisplay("block");
    this.b.setTop(this.l.top);
    this.b.setLeft(this.l.left);
    this.b.setPaddingLeft(this.l.paddingLeft);
    this.b.setWidth(this.l.width);
    this.b.setLineHeight(this.l.height);
    this.b.setHeight(this.l.height);
    return {
      domNode: this.b.domNode,
      position: this.i,
      contentLeft: this.l.left,
      height: this.l.height,
      width: 2
    };
  }
};

// out-build/vs/editor/browser/viewParts/viewCursors/viewCursors.js
var $O8 = class _$O8 extends $f7 {
  static {
    this.BLINK_INTERVAL = 500;
  }
  constructor(context) {
    super(context);
    const options3 = this._context.configuration.options;
    this.a = options3.get(
      96
      /* EditorOption.readOnly */
    );
    this.b = options3.get(
      26
      /* EditorOption.cursorBlinking */
    );
    this.c = options3.get(
      147
      /* EditorOption.effectiveCursorStyle */
    );
    this.f = options3.get(
      27
      /* EditorOption.cursorSmoothCaretAnimation */
    );
    this.g = options3.get(
      37
      /* EditorOption.experimentalEditContextEnabled */
    );
    this.h = true;
    this.j = false;
    this.n = false;
    this.C = new $R7(this._context, CursorPlurality.Single);
    this.D = [];
    this.F = [];
    this.s = $oZ(document.createElement("div"));
    this.s.setAttribute("role", "presentation");
    this.s.setAttribute("aria-hidden", "true");
    this.J();
    this.s.appendChild(this.C.getDomNode());
    this.t = new $6h();
    this.w = new $lj();
    this.y = false;
    this.z = false;
    this.I();
  }
  dispose() {
    super.dispose();
    this.t.dispose();
    this.w.dispose();
  }
  getDomNode() {
    return this.s;
  }
  // --- begin event handlers
  onCompositionStart(e) {
    this.j = true;
    this.I();
    return true;
  }
  onCompositionEnd(e) {
    this.j = false;
    this.I();
    return true;
  }
  onConfigurationChanged(e) {
    const options3 = this._context.configuration.options;
    this.a = options3.get(
      96
      /* EditorOption.readOnly */
    );
    this.b = options3.get(
      26
      /* EditorOption.cursorBlinking */
    );
    this.c = options3.get(
      147
      /* EditorOption.effectiveCursorStyle */
    );
    this.f = options3.get(
      27
      /* EditorOption.cursorSmoothCaretAnimation */
    );
    this.g = options3.get(
      37
      /* EditorOption.experimentalEditContextEnabled */
    );
    this.I();
    this.J();
    this.C.onConfigurationChanged(e);
    for (let i2 = 0, len = this.D.length; i2 < len; i2++) {
      this.D[i2].onConfigurationChanged(e);
    }
    return true;
  }
  G(position, secondaryPositions, reason) {
    const pauseAnimation = this.D.length !== secondaryPositions.length || this.f === "explicit" && reason !== 3;
    this.C.setPlurality(secondaryPositions.length ? CursorPlurality.MultiPrimary : CursorPlurality.Single);
    this.C.onCursorPositionChanged(position, pauseAnimation);
    this.I();
    if (this.D.length < secondaryPositions.length) {
      const addCnt = secondaryPositions.length - this.D.length;
      for (let i2 = 0; i2 < addCnt; i2++) {
        const newCursor = new $R7(this._context, CursorPlurality.MultiSecondary);
        this.s.domNode.insertBefore(newCursor.getDomNode().domNode, this.C.getDomNode().domNode.nextSibling);
        this.D.push(newCursor);
      }
    } else if (this.D.length > secondaryPositions.length) {
      const removeCnt = this.D.length - secondaryPositions.length;
      for (let i2 = 0; i2 < removeCnt; i2++) {
        this.s.removeChild(this.D[0].getDomNode());
        this.D.splice(0, 1);
      }
    }
    for (let i2 = 0; i2 < secondaryPositions.length; i2++) {
      this.D[i2].onCursorPositionChanged(secondaryPositions[i2], pauseAnimation);
    }
  }
  onCursorStateChanged(e) {
    const positions = [];
    for (let i2 = 0, len = e.selections.length; i2 < len; i2++) {
      positions[i2] = e.selections[i2].getPosition();
    }
    this.G(positions[0], positions.slice(1), e.reason);
    const selectionIsEmpty = e.selections[0].isEmpty();
    if (this.h !== selectionIsEmpty) {
      this.h = selectionIsEmpty;
      this.J();
    }
    return true;
  }
  onDecorationsChanged(e) {
    return true;
  }
  onFlushed(e) {
    return true;
  }
  onFocusChanged(e) {
    this.z = e.isFocused;
    this.I();
    return false;
  }
  onLinesChanged(e) {
    return true;
  }
  onLinesDeleted(e) {
    return true;
  }
  onLinesInserted(e) {
    return true;
  }
  onScrollChanged(e) {
    return true;
  }
  onTokensChanged(e) {
    const shouldRender = (position) => {
      for (let i2 = 0, len = e.ranges.length; i2 < len; i2++) {
        if (e.ranges[i2].fromLineNumber <= position.lineNumber && position.lineNumber <= e.ranges[i2].toLineNumber) {
          return true;
        }
      }
      return false;
    };
    if (shouldRender(this.C.getPosition())) {
      return true;
    }
    for (const secondaryCursor of this.D) {
      if (shouldRender(secondaryCursor.getPosition())) {
        return true;
      }
    }
    return false;
  }
  onZonesChanged(e) {
    return true;
  }
  // --- end event handlers
  // ---- blinking logic
  H() {
    if (this.j && !this.g) {
      return 0;
    }
    if (!this.z) {
      return 0;
    }
    if (this.a) {
      return 5;
    }
    return this.b;
  }
  I() {
    this.t.cancel();
    this.w.cancel();
    const blinkingStyle = this.H();
    const isHidden = blinkingStyle === 0;
    const isSolid = blinkingStyle === 5;
    if (isHidden) {
      this.N();
    } else {
      this.M();
    }
    this.y = false;
    this.J();
    if (!isHidden && !isSolid) {
      if (blinkingStyle === 1) {
        this.w.cancelAndSet(() => {
          if (this.n) {
            this.N();
          } else {
            this.M();
          }
        }, _$O8.BLINK_INTERVAL, getWindow(this.s.domNode));
      } else {
        this.t.setIfNotSet(() => {
          this.y = true;
          this.J();
        }, _$O8.BLINK_INTERVAL);
      }
    }
  }
  // --- end blinking logic
  J() {
    this.s.setClassName(this.L());
  }
  L() {
    let result = "cursors-layer";
    if (!this.h) {
      result += " has-selection";
    }
    switch (this.c) {
      case TextEditorCursorStyle.Line:
        result += " cursor-line-style";
        break;
      case TextEditorCursorStyle.Block:
        result += " cursor-block-style";
        break;
      case TextEditorCursorStyle.Underline:
        result += " cursor-underline-style";
        break;
      case TextEditorCursorStyle.LineThin:
        result += " cursor-line-thin-style";
        break;
      case TextEditorCursorStyle.BlockOutline:
        result += " cursor-block-outline-style";
        break;
      case TextEditorCursorStyle.UnderlineThin:
        result += " cursor-underline-thin-style";
        break;
      default:
        result += " cursor-line-style";
    }
    if (this.y) {
      switch (this.H()) {
        case 1:
          result += " cursor-blink";
          break;
        case 2:
          result += " cursor-smooth";
          break;
        case 3:
          result += " cursor-phase";
          break;
        case 4:
          result += " cursor-expand";
          break;
        case 5:
          result += " cursor-solid";
          break;
        default:
          result += " cursor-solid";
      }
    } else {
      result += " cursor-solid";
    }
    if (this.f === "on" || this.f === "explicit") {
      result += " cursor-smooth-caret-animation";
    }
    return result;
  }
  M() {
    this.C.show();
    for (let i2 = 0, len = this.D.length; i2 < len; i2++) {
      this.D[i2].show();
    }
    this.n = true;
  }
  N() {
    this.C.hide();
    for (let i2 = 0, len = this.D.length; i2 < len; i2++) {
      this.D[i2].hide();
    }
    this.n = false;
  }
  // ---- IViewPart implementation
  prepareRender(ctx) {
    this.C.prepareRender(ctx);
    for (let i2 = 0, len = this.D.length; i2 < len; i2++) {
      this.D[i2].prepareRender(ctx);
    }
  }
  render(ctx) {
    const renderData = [];
    let renderDataLen = 0;
    const primaryRenderData = this.C.render(ctx);
    if (primaryRenderData) {
      renderData[renderDataLen++] = primaryRenderData;
    }
    for (let i2 = 0, len = this.D.length; i2 < len; i2++) {
      const secondaryRenderData = this.D[i2].render(ctx);
      if (secondaryRenderData) {
        renderData[renderDataLen++] = secondaryRenderData;
      }
    }
    this.F = renderData;
  }
  getLastRenderData() {
    return this.F;
  }
};
$ms((theme, collector) => {
  const cursorThemes = [
    { class: ".cursor", foreground: $RG, background: $SG },
    { class: ".cursor-primary", foreground: $TG, background: $UG },
    { class: ".cursor-secondary", foreground: $VG, background: $WG }
  ];
  for (const cursorTheme of cursorThemes) {
    const caret2 = theme.getColor(cursorTheme.foreground);
    if (caret2) {
      let caretBackground = theme.getColor(cursorTheme.background);
      if (!caretBackground) {
        caretBackground = caret2.opposite();
      }
      collector.addRule(`.monaco-editor .cursors-layer ${cursorTheme.class} { background-color: ${caret2}; border-color: ${caret2}; color: ${caretBackground}; }`);
      if ($es(theme.type)) {
        collector.addRule(`.monaco-editor .cursors-layer.has-selection ${cursorTheme.class} { border-left: 1px solid ${caretBackground}; border-right: 1px solid ${caretBackground}; }`);
      }
    }
  }
});

// out-build/vs/editor/browser/viewParts/viewZones/viewZones.js
var invalidFunc = () => {
  throw new Error(`Invalid change accessor`);
};
var $P8 = class extends $f7 {
  constructor(context) {
    super(context);
    const options3 = this._context.configuration.options;
    const layoutInfo = options3.get(
      151
      /* EditorOption.layoutInfo */
    );
    this.b = options3.get(
      68
      /* EditorOption.lineHeight */
    );
    this.c = layoutInfo.contentWidth;
    this.f = layoutInfo.contentLeft;
    this.domNode = $oZ(document.createElement("div"));
    this.domNode.setClassName("view-zones");
    this.domNode.setPosition("absolute");
    this.domNode.setAttribute("role", "presentation");
    this.domNode.setAttribute("aria-hidden", "true");
    this.marginDomNode = $oZ(document.createElement("div"));
    this.marginDomNode.setClassName("margin-view-zones");
    this.marginDomNode.setPosition("absolute");
    this.marginDomNode.setAttribute("role", "presentation");
    this.marginDomNode.setAttribute("aria-hidden", "true");
    this.a = {};
  }
  dispose() {
    super.dispose();
    this.a = {};
  }
  // ---- begin view event handlers
  g() {
    const whitespaces = this._context.viewLayout.getWhitespaces();
    const oldWhitespaces = /* @__PURE__ */ new Map();
    for (const whitespace of whitespaces) {
      oldWhitespaces.set(whitespace.id, whitespace);
    }
    let hadAChange = false;
    this._context.viewModel.changeWhitespace((whitespaceAccessor) => {
      const keys = Object.keys(this.a);
      for (let i2 = 0, len = keys.length; i2 < len; i2++) {
        const id2 = keys[i2];
        const zone = this.a[id2];
        const props = this.j(zone.delegate);
        zone.isInHiddenArea = props.isInHiddenArea;
        const oldWhitespace = oldWhitespaces.get(id2);
        if (oldWhitespace && (oldWhitespace.afterLineNumber !== props.afterViewLineNumber || oldWhitespace.height !== props.heightInPx)) {
          whitespaceAccessor.changeOneWhitespace(id2, props.afterViewLineNumber, props.heightInPx);
          this.z(zone.delegate, props.heightInPx);
          hadAChange = true;
        }
      }
    });
    return hadAChange;
  }
  onConfigurationChanged(e) {
    const options3 = this._context.configuration.options;
    const layoutInfo = options3.get(
      151
      /* EditorOption.layoutInfo */
    );
    this.b = options3.get(
      68
      /* EditorOption.lineHeight */
    );
    this.c = layoutInfo.contentWidth;
    this.f = layoutInfo.contentLeft;
    if (e.hasChanged(
      68
      /* EditorOption.lineHeight */
    )) {
      this.g();
    }
    return true;
  }
  onLineMappingChanged(e) {
    return this.g();
  }
  onLinesDeleted(e) {
    return true;
  }
  onScrollChanged(e) {
    return e.scrollTopChanged || e.scrollWidthChanged;
  }
  onZonesChanged(e) {
    return true;
  }
  onLinesInserted(e) {
    return true;
  }
  // ---- end view event handlers
  h(zone) {
    return zone.ordinal ?? zone.afterColumn ?? 1e4;
  }
  j(zone) {
    if (zone.afterLineNumber === 0) {
      return {
        isInHiddenArea: false,
        afterViewLineNumber: 0,
        heightInPx: this.w(zone),
        minWidthInPx: this.y(zone)
      };
    }
    let zoneAfterModelPosition;
    if (typeof zone.afterColumn !== "undefined") {
      zoneAfterModelPosition = this._context.viewModel.model.validatePosition({
        lineNumber: zone.afterLineNumber,
        column: zone.afterColumn
      });
    } else {
      const validAfterLineNumber = this._context.viewModel.model.validatePosition({
        lineNumber: zone.afterLineNumber,
        column: 1
      }).lineNumber;
      zoneAfterModelPosition = new $8C(validAfterLineNumber, this._context.viewModel.model.getLineMaxColumn(validAfterLineNumber));
    }
    let zoneBeforeModelPosition;
    if (zoneAfterModelPosition.column === this._context.viewModel.model.getLineMaxColumn(zoneAfterModelPosition.lineNumber)) {
      zoneBeforeModelPosition = this._context.viewModel.model.validatePosition({
        lineNumber: zoneAfterModelPosition.lineNumber + 1,
        column: 1
      });
    } else {
      zoneBeforeModelPosition = this._context.viewModel.model.validatePosition({
        lineNumber: zoneAfterModelPosition.lineNumber,
        column: zoneAfterModelPosition.column + 1
      });
    }
    const viewPosition = this._context.viewModel.coordinatesConverter.convertModelPositionToViewPosition(zoneAfterModelPosition, zone.afterColumnAffinity, true);
    const isVisible = zone.showInHiddenAreas || this._context.viewModel.coordinatesConverter.modelPositionIsVisible(zoneBeforeModelPosition);
    return {
      isInHiddenArea: !isVisible,
      afterViewLineNumber: viewPosition.lineNumber,
      heightInPx: isVisible ? this.w(zone) : 0,
      minWidthInPx: this.y(zone)
    };
  }
  changeViewZones(callback) {
    let zonesHaveChanged = false;
    this._context.viewModel.changeWhitespace((whitespaceAccessor) => {
      const changeAccessor = {
        addZone: (zone) => {
          zonesHaveChanged = true;
          return this.n(whitespaceAccessor, zone);
        },
        removeZone: (id2) => {
          if (!id2) {
            return;
          }
          zonesHaveChanged = this.s(whitespaceAccessor, id2) || zonesHaveChanged;
        },
        layoutZone: (id2) => {
          if (!id2) {
            return;
          }
          zonesHaveChanged = this.t(whitespaceAccessor, id2) || zonesHaveChanged;
        }
      };
      safeInvoke1Arg(callback, changeAccessor);
      changeAccessor.addZone = invalidFunc;
      changeAccessor.removeZone = invalidFunc;
      changeAccessor.layoutZone = invalidFunc;
    });
    return zonesHaveChanged;
  }
  n(whitespaceAccessor, zone) {
    const props = this.j(zone);
    const whitespaceId = whitespaceAccessor.insertWhitespace(props.afterViewLineNumber, this.h(zone), props.heightInPx, props.minWidthInPx);
    const myZone = {
      whitespaceId,
      delegate: zone,
      isInHiddenArea: props.isInHiddenArea,
      isVisible: false,
      domNode: $oZ(zone.domNode),
      marginDomNode: zone.marginDomNode ? $oZ(zone.marginDomNode) : null
    };
    this.z(myZone.delegate, props.heightInPx);
    myZone.domNode.setPosition("absolute");
    myZone.domNode.domNode.style.width = "100%";
    myZone.domNode.setDisplay("none");
    myZone.domNode.setAttribute("monaco-view-zone", myZone.whitespaceId);
    this.domNode.appendChild(myZone.domNode);
    if (myZone.marginDomNode) {
      myZone.marginDomNode.setPosition("absolute");
      myZone.marginDomNode.domNode.style.width = "100%";
      myZone.marginDomNode.setDisplay("none");
      myZone.marginDomNode.setAttribute("monaco-view-zone", myZone.whitespaceId);
      this.marginDomNode.appendChild(myZone.marginDomNode);
    }
    this.a[myZone.whitespaceId] = myZone;
    this.u();
    return myZone.whitespaceId;
  }
  s(whitespaceAccessor, id2) {
    if (this.a.hasOwnProperty(id2)) {
      const zone = this.a[id2];
      delete this.a[id2];
      whitespaceAccessor.removeWhitespace(zone.whitespaceId);
      zone.domNode.removeAttribute("monaco-visible-view-zone");
      zone.domNode.removeAttribute("monaco-view-zone");
      zone.domNode.domNode.remove();
      if (zone.marginDomNode) {
        zone.marginDomNode.removeAttribute("monaco-visible-view-zone");
        zone.marginDomNode.removeAttribute("monaco-view-zone");
        zone.marginDomNode.domNode.remove();
      }
      this.u();
      return true;
    }
    return false;
  }
  t(whitespaceAccessor, id2) {
    if (this.a.hasOwnProperty(id2)) {
      const zone = this.a[id2];
      const props = this.j(zone.delegate);
      zone.isInHiddenArea = props.isInHiddenArea;
      whitespaceAccessor.changeOneWhitespace(zone.whitespaceId, props.afterViewLineNumber, props.heightInPx);
      this.z(zone.delegate, props.heightInPx);
      this.u();
      return true;
    }
    return false;
  }
  shouldSuppressMouseDownOnViewZone(id2) {
    if (this.a.hasOwnProperty(id2)) {
      const zone = this.a[id2];
      return Boolean(zone.delegate.suppressMouseDown);
    }
    return false;
  }
  w(zone) {
    if (typeof zone.heightInPx === "number") {
      return zone.heightInPx;
    }
    if (typeof zone.heightInLines === "number") {
      return this.b * zone.heightInLines;
    }
    return this.b;
  }
  y(zone) {
    if (typeof zone.minWidthInPx === "number") {
      return zone.minWidthInPx;
    }
    return 0;
  }
  z(zone, height) {
    if (typeof zone.onComputedHeight === "function") {
      try {
        zone.onComputedHeight(height);
      } catch (e) {
        $gb(e);
      }
    }
  }
  C(zone, top2) {
    if (typeof zone.onDomNodeTop === "function") {
      try {
        zone.onDomNodeTop(top2);
      } catch (e) {
        $gb(e);
      }
    }
  }
  prepareRender(ctx) {
  }
  render(ctx) {
    const visibleWhitespaces = ctx.viewportData.whitespaceViewportData;
    const visibleZones = {};
    let hasVisibleZone = false;
    for (const visibleWhitespace of visibleWhitespaces) {
      if (this.a[visibleWhitespace.id].isInHiddenArea) {
        continue;
      }
      visibleZones[visibleWhitespace.id] = visibleWhitespace;
      hasVisibleZone = true;
    }
    const keys = Object.keys(this.a);
    for (let i2 = 0, len = keys.length; i2 < len; i2++) {
      const id2 = keys[i2];
      const zone = this.a[id2];
      let newTop = 0;
      let newHeight = 0;
      let newDisplay = "none";
      if (visibleZones.hasOwnProperty(id2)) {
        newTop = visibleZones[id2].verticalOffset - ctx.bigNumbersDelta;
        newHeight = visibleZones[id2].height;
        newDisplay = "block";
        if (!zone.isVisible) {
          zone.domNode.setAttribute("monaco-visible-view-zone", "true");
          zone.isVisible = true;
        }
        this.C(zone.delegate, ctx.getScrolledTopFromAbsoluteTop(visibleZones[id2].verticalOffset));
      } else {
        if (zone.isVisible) {
          zone.domNode.removeAttribute("monaco-visible-view-zone");
          zone.isVisible = false;
        }
        this.C(zone.delegate, ctx.getScrolledTopFromAbsoluteTop(-1e6));
      }
      zone.domNode.setTop(newTop);
      zone.domNode.setHeight(newHeight);
      zone.domNode.setDisplay(newDisplay);
      if (zone.marginDomNode) {
        zone.marginDomNode.setTop(newTop);
        zone.marginDomNode.setHeight(newHeight);
        zone.marginDomNode.setDisplay(newDisplay);
      }
    }
    if (hasVisibleZone) {
      this.domNode.setWidth(Math.max(ctx.scrollWidth, this.c));
      this.marginDomNode.setWidth(this.f);
    }
  }
};
function safeInvoke1Arg(func, arg1) {
  try {
    return func(arg1);
  } catch (e) {
    $gb(e);
  }
}

// out-build/vs/editor/browser/viewParts/whitespace/whitespace.js
var $Q8 = class extends $d8 {
  constructor(context) {
    super();
    this.a = context;
    this.b = new WhitespaceOptions(this.a.configuration);
    this.c = [];
    this.f = null;
    this.a.addEventHandler(this);
  }
  dispose() {
    this.a.removeEventHandler(this);
    this.f = null;
    super.dispose();
  }
  // --- begin event handlers
  onConfigurationChanged(e) {
    const newOptions = new WhitespaceOptions(this.a.configuration);
    if (this.b.equals(newOptions)) {
      return e.hasChanged(
        151
        /* EditorOption.layoutInfo */
      );
    }
    this.b = newOptions;
    return true;
  }
  onCursorStateChanged(e) {
    this.c = e.selections;
    if (this.b.renderWhitespace === "selection") {
      return true;
    }
    return false;
  }
  onDecorationsChanged(e) {
    return true;
  }
  onFlushed(e) {
    return true;
  }
  onLinesChanged(e) {
    return true;
  }
  onLinesDeleted(e) {
    return true;
  }
  onLinesInserted(e) {
    return true;
  }
  onScrollChanged(e) {
    return e.scrollTopChanged;
  }
  onZonesChanged(e) {
    return true;
  }
  // --- end event handlers
  prepareRender(ctx) {
    if (this.b.renderWhitespace === "none") {
      this.f = null;
      return;
    }
    const startLineNumber = ctx.visibleRange.startLineNumber;
    const endLineNumber = ctx.visibleRange.endLineNumber;
    const lineCount = endLineNumber - startLineNumber + 1;
    const needed = new Array(lineCount);
    for (let i2 = 0; i2 < lineCount; i2++) {
      needed[i2] = true;
    }
    const viewportData = this.a.viewModel.getMinimapLinesRenderingData(ctx.viewportData.startLineNumber, ctx.viewportData.endLineNumber, needed);
    this.f = [];
    for (let lineNumber = ctx.viewportData.startLineNumber; lineNumber <= ctx.viewportData.endLineNumber; lineNumber++) {
      const lineIndex = lineNumber - ctx.viewportData.startLineNumber;
      const lineData = viewportData.data[lineIndex];
      let selectionsOnLine = null;
      if (this.b.renderWhitespace === "selection") {
        const selections = this.c;
        for (const selection of selections) {
          if (selection.endLineNumber < lineNumber || selection.startLineNumber > lineNumber) {
            continue;
          }
          const startColumn = selection.startLineNumber === lineNumber ? selection.startColumn : lineData.minColumn;
          const endColumn = selection.endLineNumber === lineNumber ? selection.endColumn : lineData.maxColumn;
          if (startColumn < endColumn) {
            if (!selectionsOnLine) {
              selectionsOnLine = [];
            }
            selectionsOnLine.push(new $p7(startColumn - 1, endColumn - 1));
          }
        }
      }
      this.f[lineIndex] = this.g(ctx, lineNumber, selectionsOnLine, lineData);
    }
  }
  g(ctx, lineNumber, selections, lineData) {
    if (this.b.renderWhitespace === "selection" && !selections) {
      return "";
    }
    if (this.b.renderWhitespace === "trailing" && lineData.continuesWithWrappedLine) {
      return "";
    }
    const color2 = this.a.theme.getColor($XG);
    const USE_SVG = this.b.renderWithSVG;
    const lineContent = lineData.content;
    const len = this.b.stopRenderingLineAfter === -1 ? lineContent.length : Math.min(this.b.stopRenderingLineAfter, lineContent.length);
    const continuesWithWrappedLine = lineData.continuesWithWrappedLine;
    const fauxIndentLength = lineData.minColumn - 1;
    const onlyBoundary = this.b.renderWhitespace === "boundary";
    const onlyTrailing = this.b.renderWhitespace === "trailing";
    const lineHeight = this.b.lineHeight;
    const middotWidth = this.b.middotWidth;
    const wsmiddotWidth = this.b.wsmiddotWidth;
    const spaceWidth = this.b.spaceWidth;
    const wsmiddotDiff = Math.abs(wsmiddotWidth - spaceWidth);
    const middotDiff = Math.abs(middotWidth - spaceWidth);
    const renderSpaceCharCode = wsmiddotDiff < middotDiff ? 11825 : 183;
    const canUseHalfwidthRightwardsArrow = this.b.canUseHalfwidthRightwardsArrow;
    let result = "";
    let lineIsEmptyOrWhitespace = false;
    let firstNonWhitespaceIndex = $Of(lineContent);
    let lastNonWhitespaceIndex;
    if (firstNonWhitespaceIndex === -1) {
      lineIsEmptyOrWhitespace = true;
      firstNonWhitespaceIndex = len;
      lastNonWhitespaceIndex = len;
    } else {
      lastNonWhitespaceIndex = $Qf(lineContent);
    }
    let currentSelectionIndex = 0;
    let currentSelection = selections && selections[currentSelectionIndex];
    let maxLeft = 0;
    for (let charIndex = fauxIndentLength; charIndex < len; charIndex++) {
      const chCode = lineContent.charCodeAt(charIndex);
      if (currentSelection && charIndex >= currentSelection.endOffset) {
        currentSelectionIndex++;
        currentSelection = selections && selections[currentSelectionIndex];
      }
      if (chCode !== 9 && chCode !== 32) {
        continue;
      }
      if (onlyTrailing && !lineIsEmptyOrWhitespace && charIndex <= lastNonWhitespaceIndex) {
        continue;
      }
      if (onlyBoundary && charIndex >= firstNonWhitespaceIndex && charIndex <= lastNonWhitespaceIndex && chCode === 32) {
        const prevChCode = charIndex - 1 >= 0 ? lineContent.charCodeAt(charIndex - 1) : 0;
        const nextChCode = charIndex + 1 < len ? lineContent.charCodeAt(charIndex + 1) : 0;
        if (prevChCode !== 32 && nextChCode !== 32) {
          continue;
        }
      }
      if (onlyBoundary && continuesWithWrappedLine && charIndex === len - 1) {
        const prevCharCode = charIndex - 1 >= 0 ? lineContent.charCodeAt(charIndex - 1) : 0;
        const isSingleTrailingSpace = chCode === 32 && (prevCharCode !== 32 && prevCharCode !== 9);
        if (isSingleTrailingSpace) {
          continue;
        }
      }
      if (selections && (!currentSelection || currentSelection.startOffset > charIndex || currentSelection.endOffset <= charIndex)) {
        continue;
      }
      const visibleRange = ctx.visibleRangeForPosition(new $8C(lineNumber, charIndex + 1));
      if (!visibleRange) {
        continue;
      }
      if (USE_SVG) {
        maxLeft = Math.max(maxLeft, visibleRange.left);
        if (chCode === 9) {
          result += this.h(lineHeight, spaceWidth, visibleRange.left);
        } else {
          result += `<circle cx="${(visibleRange.left + spaceWidth / 2).toFixed(2)}" cy="${(lineHeight / 2).toFixed(2)}" r="${(spaceWidth / 7).toFixed(2)}" />`;
        }
      } else {
        if (chCode === 9) {
          result += `<div class="mwh" style="left:${visibleRange.left}px;height:${lineHeight}px;">${canUseHalfwidthRightwardsArrow ? String.fromCharCode(65515) : String.fromCharCode(8594)}</div>`;
        } else {
          result += `<div class="mwh" style="left:${visibleRange.left}px;height:${lineHeight}px;">${String.fromCharCode(renderSpaceCharCode)}</div>`;
        }
      }
    }
    if (USE_SVG) {
      maxLeft = Math.round(maxLeft + spaceWidth);
      return `<svg style="bottom:0;position:absolute;width:${maxLeft}px;height:${lineHeight}px" viewBox="0 0 ${maxLeft} ${lineHeight}" xmlns="http://www.w3.org/2000/svg" fill="${color2}">` + result + `</svg>`;
    }
    return result;
  }
  h(lineHeight, spaceWidth, left) {
    const strokeWidth = spaceWidth / 7;
    const width2 = spaceWidth;
    const dy = lineHeight / 2;
    const dx = left;
    const p1 = { x: 0, y: strokeWidth / 2 };
    const p2 = { x: 100 / 125 * width2, y: p1.y };
    const p3 = { x: p2.x - 0.2 * p2.x, y: p2.y + 0.2 * p2.x };
    const p4 = { x: p3.x + 0.1 * p2.x, y: p3.y + 0.1 * p2.x };
    const p5 = { x: p4.x + 0.35 * p2.x, y: p4.y - 0.35 * p2.x };
    const p6 = { x: p5.x, y: -p5.y };
    const p7 = { x: p4.x, y: -p4.y };
    const p8 = { x: p3.x, y: -p3.y };
    const p9 = { x: p2.x, y: -p2.y };
    const p10 = { x: p1.x, y: -p1.y };
    const p = [p1, p2, p3, p4, p5, p6, p7, p8, p9, p10];
    const parts = p.map((p11) => `${(dx + p11.x).toFixed(2)} ${(dy + p11.y).toFixed(2)}`).join(" L ");
    return `<path d="M ${parts}" />`;
  }
  render(startLineNumber, lineNumber) {
    if (!this.f) {
      return "";
    }
    const lineIndex = lineNumber - startLineNumber;
    if (lineIndex < 0 || lineIndex >= this.f.length) {
      return "";
    }
    return this.f[lineIndex];
  }
};
var WhitespaceOptions = class {
  constructor(config) {
    const options3 = config.options;
    const fontInfo = options3.get(
      52
      /* EditorOption.fontInfo */
    );
    const experimentalWhitespaceRendering = options3.get(
      40
      /* EditorOption.experimentalWhitespaceRendering */
    );
    if (experimentalWhitespaceRendering === "off") {
      this.renderWhitespace = "none";
      this.renderWithSVG = false;
    } else if (experimentalWhitespaceRendering === "svg") {
      this.renderWhitespace = options3.get(
        104
        /* EditorOption.renderWhitespace */
      );
      this.renderWithSVG = true;
    } else {
      this.renderWhitespace = options3.get(
        104
        /* EditorOption.renderWhitespace */
      );
      this.renderWithSVG = false;
    }
    this.spaceWidth = fontInfo.spaceWidth;
    this.middotWidth = fontInfo.middotWidth;
    this.wsmiddotWidth = fontInfo.wsmiddotWidth;
    this.canUseHalfwidthRightwardsArrow = fontInfo.canUseHalfwidthRightwardsArrow;
    this.lineHeight = options3.get(
      68
      /* EditorOption.lineHeight */
    );
    this.stopRenderingLineAfter = options3.get(
      122
      /* EditorOption.stopRenderingLineAfter */
    );
  }
  equals(other) {
    return this.renderWhitespace === other.renderWhitespace && this.renderWithSVG === other.renderWithSVG && this.spaceWidth === other.spaceWidth && this.middotWidth === other.middotWidth && this.wsmiddotWidth === other.wsmiddotWidth && this.canUseHalfwidthRightwardsArrow === other.canUseHalfwidthRightwardsArrow && this.lineHeight === other.lineHeight && this.stopRenderingLineAfter === other.stopRenderingLineAfter;
  }
};

// out-build/vs/editor/common/viewLayout/viewLinesViewportData.js
var $96 = class {
  constructor(selections, partialData, whitespaceViewportData, model) {
    this.selections = selections;
    this.startLineNumber = partialData.startLineNumber | 0;
    this.endLineNumber = partialData.endLineNumber | 0;
    this.relativeVerticalOffset = partialData.relativeVerticalOffset;
    this.bigNumbersDelta = partialData.bigNumbersDelta | 0;
    this.lineHeight = partialData.lineHeight | 0;
    this.whitespaceViewportData = whitespaceViewportData;
    this.a = model;
    this.visibleRange = new $9C(partialData.startLineNumber, this.a.getLineMinColumn(partialData.startLineNumber), partialData.endLineNumber, this.a.getLineMaxColumn(partialData.endLineNumber));
  }
  getViewLineRenderingData(lineNumber) {
    return this.a.getViewportViewLineRenderingData(this.visibleRange, lineNumber);
  }
  getDecorationsInViewport() {
    return this.a.getDecorationsInViewport(this.visibleRange);
  }
};

// out-build/vs/editor/common/editorTheme.js
var $k5 = class {
  get type() {
    return this.a.type;
  }
  get value() {
    return this.a;
  }
  constructor(theme) {
    this.a = theme;
  }
  update(theme) {
    this.a = theme;
  }
  getColor(color2) {
    return this.a.getColor(color2);
  }
};

// out-build/vs/editor/common/viewModel/viewContext.js
var $e7 = class {
  constructor(configuration2, theme, model) {
    this.configuration = configuration2;
    this.theme = new $k5(theme);
    this.viewModel = model;
    this.viewLayout = model.viewLayout;
  }
  addEventHandler(eventHandler) {
    this.viewModel.addViewEventHandler(eventHandler);
  }
  removeEventHandler(eventHandler) {
    this.viewModel.removeViewEventHandler(eventHandler);
  }
};

// out-build/vs/base/common/observableInternal/debugName.js
var $dd = class {
  constructor(owner, debugNameSource, referenceFn) {
    this.owner = owner;
    this.debugNameSource = debugNameSource;
    this.referenceFn = referenceFn;
  }
  getDebugName(target) {
    return $ed(target, this);
  }
};
var countPerName = /* @__PURE__ */ new Map();
var cachedDebugName = /* @__PURE__ */ new WeakMap();
function $ed(target, data) {
  const cached = cachedDebugName.get(target);
  if (cached) {
    return cached;
  }
  const dbgName = computeDebugName(target, data);
  if (dbgName) {
    let count = countPerName.get(dbgName) ?? 0;
    count++;
    countPerName.set(dbgName, count);
    const result = count === 1 ? dbgName : `${dbgName}#${count}`;
    cachedDebugName.set(target, result);
    return result;
  }
  return void 0;
}
function computeDebugName(self2, data) {
  const cached = cachedDebugName.get(self2);
  if (cached) {
    return cached;
  }
  const ownerStr = data.owner ? formatOwner(data.owner) + `.` : "";
  let result;
  const debugNameSource = data.debugNameSource;
  if (debugNameSource !== void 0) {
    if (typeof debugNameSource === "function") {
      result = debugNameSource();
      if (result !== void 0) {
        return ownerStr + result;
      }
    } else {
      return ownerStr + debugNameSource;
    }
  }
  const referenceFn = data.referenceFn;
  if (referenceFn !== void 0) {
    result = $fd(referenceFn);
    if (result !== void 0) {
      return ownerStr + result;
    }
  }
  if (data.owner !== void 0) {
    const key2 = findKey(data.owner, self2);
    if (key2 !== void 0) {
      return ownerStr + key2;
    }
  }
  return void 0;
}
function findKey(obj, value) {
  for (const key2 in obj) {
    if (obj[key2] === value) {
      return key2;
    }
  }
  return void 0;
}
var countPerClassName = /* @__PURE__ */ new Map();
var ownerId = /* @__PURE__ */ new WeakMap();
function formatOwner(owner) {
  const id2 = ownerId.get(owner);
  if (id2) {
    return id2;
  }
  const className = getClassName(owner);
  let count = countPerClassName.get(className) ?? 0;
  count++;
  countPerClassName.set(className, count);
  const result = count === 1 ? className : `${className}#${count}`;
  ownerId.set(owner, result);
  return result;
}
function getClassName(obj) {
  const ctor = obj.constructor;
  if (ctor) {
    return ctor.name;
  }
  return "Object";
}
function $fd(fn) {
  const fnSrc = fn.toString();
  const regexp = /\/\*\*\s*@description\s*([^*]*)\*\//;
  const match = regexp.exec(fnSrc);
  const result = match ? match[1] : void 0;
  return result?.trim();
}

// out-build/vs/base/common/equals.js
var $md = (a, b) => a === b;
function $nd(itemEquals = $md) {
  return (a, b) => $zb(a, b, itemEquals);
}
function $pd() {
  return (a, b) => a.equals(b);
}
function $qd(equalsOrV1, v2, equals) {
  if (equals !== void 0) {
    const v1 = equalsOrV1;
    if (v1 === void 0 || v1 === null || v2 === void 0 || v2 === null) {
      return v2 === v1;
    }
    return equals(v1, v2);
  } else {
    const equals2 = equalsOrV1;
    return (v1, v22) => {
      if (v1 === void 0 || v1 === null || v22 === void 0 || v22 === null) {
        return v22 === v1;
      }
      return equals2(v1, v22);
    };
  }
}
function $rd(a, b) {
  if (a === b) {
    return true;
  }
  if (Array.isArray(a) && Array.isArray(b)) {
    if (a.length !== b.length) {
      return false;
    }
    for (let i2 = 0; i2 < a.length; i2++) {
      if (!$rd(a[i2], b[i2])) {
        return false;
      }
    }
    return true;
  }
  if (a && typeof a === "object" && b && typeof b === "object") {
    if (Object.getPrototypeOf(a) === Object.prototype && Object.getPrototypeOf(b) === Object.prototype) {
      const aObj = a;
      const bObj = b;
      const keysA = Object.keys(aObj);
      const keysB = Object.keys(bObj);
      const keysBSet = new Set(keysB);
      if (keysA.length !== keysB.length) {
        return false;
      }
      for (const key2 of keysA) {
        if (!keysBSet.has(key2)) {
          return false;
        }
        if (!$rd(aObj[key2], bObj[key2])) {
          return false;
        }
      }
      return true;
    }
  }
  return false;
}
function $sd(t) {
  return JSON.stringify(toNormalizedJsonStructure(t));
}
var objectId = 0;
var objIds = /* @__PURE__ */ new WeakMap();
function toNormalizedJsonStructure(t) {
  if (Array.isArray(t)) {
    return t.map(toNormalizedJsonStructure);
  }
  if (t && typeof t === "object") {
    if (Object.getPrototypeOf(t) === Object.prototype) {
      const tObj = t;
      const res = /* @__PURE__ */ Object.create(null);
      for (const key2 of Object.keys(tObj).sort()) {
        res[key2] = toNormalizedJsonStructure(tObj[key2]);
      }
      return res;
    } else {
      let objId = objIds.get(t);
      if (objId === void 0) {
        objId = objectId++;
        objIds.set(t, objId);
      }
      return objId + "----2b76a038c20c4bcc";
    }
  }
  return t;
}

// out-build/vs/base/common/observableInternal/logging.js
var globalObservableLogger;
function $Yd(logger2) {
  globalObservableLogger = logger2;
}
function $Zd() {
  return globalObservableLogger;
}
var $1d = class {
  constructor() {
    this.a = 0;
    this.d = /* @__PURE__ */ new WeakMap();
  }
  b(text2) {
    return consoleTextToArgs([
      normalText(repeat("|  ", this.a)),
      text2
    ]);
  }
  c(info) {
    if (!info.hadValue) {
      return [
        normalText(` `),
        styled(formatValue(info.newValue, 60), {
          color: "green"
        }),
        normalText(` (initial)`)
      ];
    }
    return info.didChange ? [
      normalText(` `),
      styled(formatValue(info.oldValue, 70), {
        color: "red",
        strikeThrough: true
      }),
      normalText(` `),
      styled(formatValue(info.newValue, 60), {
        color: "green"
      })
    ] : [normalText(` (unchanged)`)];
  }
  handleObservableChanged(observable, info) {
    console.log(...this.b([
      formatKind("observable value changed"),
      styled(observable.debugName, { color: "BlueViolet" }),
      ...this.c(info)
    ]));
  }
  formatChanges(changes) {
    if (changes.size === 0) {
      return void 0;
    }
    return styled(" (changed deps: " + [...changes].map((o) => o.debugName).join(", ") + ")", { color: "gray" });
  }
  handleDerivedCreated(derived) {
    const existingHandleChange = derived.handleChange;
    this.d.set(derived, /* @__PURE__ */ new Set());
    derived.handleChange = (observable, change) => {
      this.d.get(derived).add(observable);
      return existingHandleChange.apply(derived, [observable, change]);
    };
  }
  handleDerivedRecomputed(derived, info) {
    const changedObservables = this.d.get(derived);
    console.log(...this.b([
      formatKind("derived recomputed"),
      styled(derived.debugName, { color: "BlueViolet" }),
      ...this.c(info),
      this.formatChanges(changedObservables),
      { data: [{ fn: derived._debugNameData.referenceFn ?? derived._computeFn }] }
    ]));
    changedObservables.clear();
  }
  handleFromEventObservableTriggered(observable, info) {
    console.log(...this.b([
      formatKind("observable from event triggered"),
      styled(observable.debugName, { color: "BlueViolet" }),
      ...this.c(info),
      { data: [{ fn: observable._getValue }] }
    ]));
  }
  handleAutorunCreated(autorun) {
    const existingHandleChange = autorun.handleChange;
    this.d.set(autorun, /* @__PURE__ */ new Set());
    autorun.handleChange = (observable, change) => {
      this.d.get(autorun).add(observable);
      return existingHandleChange.apply(autorun, [observable, change]);
    };
  }
  handleAutorunTriggered(autorun) {
    const changedObservables = this.d.get(autorun);
    console.log(...this.b([
      formatKind("autorun"),
      styled(autorun.debugName, { color: "BlueViolet" }),
      this.formatChanges(changedObservables),
      { data: [{ fn: autorun._debugNameData.referenceFn ?? autorun._runFn }] }
    ]));
    changedObservables.clear();
    this.a++;
  }
  handleAutorunFinished(autorun) {
    this.a--;
  }
  handleBeginTransaction(transaction) {
    let transactionName = transaction.getDebugName();
    if (transactionName === void 0) {
      transactionName = "";
    }
    console.log(...this.b([
      formatKind("transaction"),
      styled(transactionName, { color: "BlueViolet" }),
      { data: [{ fn: transaction._fn }] }
    ]));
    this.a++;
  }
  handleEndTransaction() {
    this.a--;
  }
};
function consoleTextToArgs(text2) {
  const styles = new Array();
  const data = [];
  let firstArg = "";
  function process2(t) {
    if ("length" in t) {
      for (const item of t) {
        if (item) {
          process2(item);
        }
      }
    } else if ("text" in t) {
      firstArg += `%c${t.text}`;
      styles.push(t.style);
      if (t.data) {
        data.push(...t.data);
      }
    } else if ("data" in t) {
      data.push(...t.data);
    }
  }
  process2(text2);
  const result = [firstArg, ...styles];
  result.push(...data);
  return result;
}
function normalText(text2) {
  return styled(text2, { color: "black" });
}
function formatKind(kind) {
  return styled(padStr(`${kind}: `, 10), { color: "black", bold: true });
}
function styled(text2, options3 = {
  color: "black"
}) {
  function objToCss(styleObj) {
    return Object.entries(styleObj).reduce((styleString, [propName, propValue]) => {
      return `${styleString}${propName}:${propValue};`;
    }, "");
  }
  const style = {
    color: options3.color
  };
  if (options3.strikeThrough) {
    style["text-decoration"] = "line-through";
  }
  if (options3.bold) {
    style["font-weight"] = "bold";
  }
  return {
    text: text2,
    style: objToCss(style)
  };
}
function formatValue(value, availableLen) {
  switch (typeof value) {
    case "number":
      return "" + value;
    case "string":
      if (value.length + 2 <= availableLen) {
        return `"${value}"`;
      }
      return `"${value.substr(0, availableLen - 7)}"+...`;
    case "boolean":
      return value ? "true" : "false";
    case "undefined":
      return "undefined";
    case "object":
      if (value === null) {
        return "null";
      }
      if (Array.isArray(value)) {
        return formatArray(value, availableLen);
      }
      return formatObject(value, availableLen);
    case "symbol":
      return value.toString();
    case "function":
      return `[[Function${value.name ? " " + value.name : ""}]]`;
    default:
      return "" + value;
  }
}
function formatArray(value, availableLen) {
  let result = "[ ";
  let first = true;
  for (const val of value) {
    if (!first) {
      result += ", ";
    }
    if (result.length - 5 > availableLen) {
      result += "...";
      break;
    }
    first = false;
    result += `${formatValue(val, availableLen - result.length)}`;
  }
  result += " ]";
  return result;
}
function formatObject(value, availableLen) {
  let result = "{ ";
  let first = true;
  for (const [key2, val] of Object.entries(value)) {
    if (!first) {
      result += ", ";
    }
    if (result.length - 5 > availableLen) {
      result += "...";
      break;
    }
    first = false;
    result += `${key2}: ${formatValue(val, availableLen - result.length)}`;
  }
  result += " }";
  return result;
}
function repeat(str, count) {
  let result = "";
  for (let i2 = 1; i2 <= count; i2++) {
    result += str;
  }
  return result;
}
function padStr(str, length) {
  while (str.length < length) {
    str += " ";
  }
  return str;
}

// out-build/vs/base/common/observableInternal/base.js
var _recomputeInitiallyAndOnChange;
function $0d(recomputeInitiallyAndOnChange) {
  _recomputeInitiallyAndOnChange = recomputeInitiallyAndOnChange;
}
var _keepObserved;
function $$d(keepObserved) {
  _keepObserved = keepObserved;
}
var _derived;
function $_d(derived) {
  _derived = derived;
}
var $ae = class {
  get TChange() {
    return null;
  }
  reportChanges() {
    this.get();
  }
  /** @sealed */
  read(reader) {
    if (reader) {
      return reader.readObservable(this);
    } else {
      return this.get();
    }
  }
  map(fnOrOwner, fnOrUndefined) {
    const owner = fnOrUndefined === void 0 ? void 0 : fnOrOwner;
    const fn = fnOrUndefined === void 0 ? fnOrOwner : fnOrUndefined;
    return _derived({
      owner,
      debugName: () => {
        const name = $fd(fn);
        if (name !== void 0) {
          return name;
        }
        const regexp = /^\s*\(?\s*([a-zA-Z_$][a-zA-Z_$0-9]*)\s*\)?\s*=>\s*\1(?:\??)\.([a-zA-Z_$][a-zA-Z_$0-9]*)\s*$/;
        const match = regexp.exec(fn.toString());
        if (match) {
          return `${this.debugName}.${match[2]}`;
        }
        if (!owner) {
          return `${this.debugName} (mapped)`;
        }
        return void 0;
      },
      debugReferenceFn: fn
    }, (reader) => fn(this.read(reader), reader));
  }
  /**
   * @sealed
   * Converts an observable of an observable value into a direct observable of the value.
  */
  flatten() {
    return _derived({
      owner: void 0,
      debugName: () => `${this.debugName} (flattened)`
    }, (reader) => this.read(reader).read(reader));
  }
  recomputeInitiallyAndOnChange(store, handleValue) {
    store.add(_recomputeInitiallyAndOnChange(this, handleValue));
    return this;
  }
  /**
   * Ensures that this observable is observed. This keeps the cache alive.
   * However, in case of deriveds, it does not force eager evaluation (only when the value is read/get).
   * Use `recomputeInitiallyAndOnChange` for eager evaluation.
   */
  keepObserved(store) {
    store.add(_keepObserved(this));
    return this;
  }
  get a() {
    return this.get();
  }
};
var $be = class extends $ae {
  constructor() {
    super(...arguments);
    this.b = /* @__PURE__ */ new Set();
  }
  addObserver(observer) {
    const len = this.b.size;
    this.b.add(observer);
    if (len === 0) {
      this.c();
    }
  }
  removeObserver(observer) {
    const deleted = this.b.delete(observer);
    if (deleted && this.b.size === 0) {
      this.f();
    }
  }
  c() {
  }
  f() {
  }
};
function $ce(fn, getDebugName) {
  const tx = new $ge(fn, getDebugName);
  try {
    fn(tx);
  } finally {
    tx.finish();
  }
}
var _globalTransaction = void 0;
function $de(fn) {
  if (_globalTransaction) {
    fn(_globalTransaction);
  } else {
    const tx = new $ge(fn, void 0);
    _globalTransaction = tx;
    try {
      fn(tx);
    } finally {
      tx.finish();
      _globalTransaction = void 0;
    }
  }
}
async function $ee(fn, getDebugName) {
  const tx = new $ge(fn, getDebugName);
  try {
    await fn(tx);
  } finally {
    tx.finish();
  }
}
function $fe(tx, fn, getDebugName) {
  if (!tx) {
    $ce(fn, getDebugName);
  } else {
    fn(tx);
  }
}
var $ge = class {
  constructor(_fn, b) {
    this._fn = _fn;
    this.b = b;
    this.a = [];
    $Zd()?.handleBeginTransaction(this);
  }
  getDebugName() {
    if (this.b) {
      return this.b();
    }
    return $fd(this._fn);
  }
  updateObserver(observer, observable) {
    this.a.push({ observer, observable });
    observer.beginUpdate(observable);
  }
  finish() {
    const updatingObservers = this.a;
    for (let i2 = 0; i2 < updatingObservers.length; i2++) {
      const { observer, observable } = updatingObservers[i2];
      observer.endUpdate(observable);
    }
    this.a = null;
    $Zd()?.handleEndTransaction();
  }
};
function $he(nameOrOwner, initialValue) {
  let debugNameData;
  if (typeof nameOrOwner === "string") {
    debugNameData = new $dd(void 0, nameOrOwner, void 0);
  } else {
    debugNameData = new $dd(nameOrOwner, void 0, void 0);
  }
  return new $ie(debugNameData, initialValue, $md);
}
var $ie = class extends $be {
  get debugName() {
    return this.e.getDebugName(this) ?? "ObservableValue";
  }
  constructor(e, initialValue, g) {
    super();
    this.e = e;
    this.g = g;
    this.d = initialValue;
  }
  get() {
    return this.d;
  }
  set(value, tx, change) {
    if (change === void 0 && this.g(this.d, value)) {
      return;
    }
    let _tx;
    if (!tx) {
      tx = _tx = new $ge(() => {
      }, () => `Setting ${this.debugName}`);
    }
    try {
      const oldValue = this.d;
      this.h(value);
      $Zd()?.handleObservableChanged(this, { oldValue, newValue: value, change, didChange: true, hadValue: true });
      for (const observer of this.b) {
        tx.updateObserver(observer, this);
        observer.handleChange(this, change);
      }
    } finally {
      if (_tx) {
        _tx.finish();
      }
    }
  }
  toString() {
    return `${this.debugName}: ${this.d}`;
  }
  h(newValue) {
    this.d = newValue;
  }
};
function $je(nameOrOwner, initialValue) {
  let debugNameData;
  if (typeof nameOrOwner === "string") {
    debugNameData = new $dd(void 0, nameOrOwner, void 0);
  } else {
    debugNameData = new $dd(nameOrOwner, void 0, void 0);
  }
  return new $ke(debugNameData, initialValue, $md);
}
var $ke = class extends $ie {
  h(newValue) {
    if (this.d === newValue) {
      return;
    }
    if (this.d) {
      this.d.dispose();
    }
    this.d = newValue;
  }
  dispose() {
    this.d?.dispose();
  }
};

// out-build/vs/base/common/observableInternal/lazyObservableValue.js
var $le = class extends $be {
  get debugName() {
    return this.h.getDebugName(this) ?? "LazyObservableValue";
  }
  constructor(h3, initialValue, j) {
    super();
    this.h = h3;
    this.j = j;
    this.e = true;
    this.g = [];
    this.l = 0;
    this.d = initialValue;
  }
  get() {
    this.k();
    return this.d;
  }
  k() {
    if (this.e) {
      return;
    }
    this.e = true;
    if (this.g.length > 0) {
      for (const observer of this.b) {
        for (const change of this.g) {
          observer.handleChange(this, change);
        }
      }
      this.g.length = 0;
    } else {
      for (const observer of this.b) {
        observer.handleChange(this, void 0);
      }
    }
  }
  m() {
    this.l++;
    if (this.l === 1) {
      for (const observer of this.b) {
        observer.beginUpdate(this);
      }
    }
  }
  n() {
    this.l--;
    if (this.l === 0) {
      this.k();
      const observers = [...this.b];
      for (const r2 of observers) {
        r2.endUpdate(this);
      }
    }
  }
  addObserver(observer) {
    const shouldCallBeginUpdate = !this.b.has(observer) && this.l > 0;
    super.addObserver(observer);
    if (shouldCallBeginUpdate) {
      observer.beginUpdate(this);
    }
  }
  removeObserver(observer) {
    const shouldCallEndUpdate = this.b.has(observer) && this.l > 0;
    super.removeObserver(observer);
    if (shouldCallEndUpdate) {
      observer.endUpdate(this);
    }
  }
  set(value, tx, change) {
    if (change === void 0 && this.j(this.d, value)) {
      return;
    }
    let _tx;
    if (!tx) {
      tx = _tx = new $ge(() => {
      }, () => `Setting ${this.debugName}`);
    }
    try {
      this.e = false;
      this.o(value);
      if (change !== void 0) {
        this.g.push(change);
      }
      tx.updateObserver({
        beginUpdate: () => this.m(),
        endUpdate: () => this.n(),
        handleChange: (observable, change2) => {
        },
        handlePossibleChange: (observable) => {
        }
      }, this);
      if (this.l > 1) {
        for (const observer of this.b) {
          observer.handlePossibleChange(this);
        }
      }
    } finally {
      if (_tx) {
        _tx.finish();
      }
    }
  }
  toString() {
    return `${this.debugName}: ${this.d}`;
  }
  o(newValue) {
    this.d = newValue;
  }
};

// out-build/vs/base/common/observableInternal/api.js
function $me(options3, initialValue) {
  if (options3.lazy) {
    return new $le(new $dd(options3.owner, options3.debugName, void 0), initialValue, options3.equalsFn ?? $md);
  }
  return new $ie(new $dd(options3.owner, options3.debugName, void 0), initialValue, options3.equalsFn ?? $md);
}

// out-build/vs/base/common/observableInternal/autorun.js
function $td(fn) {
  return new $Ad(new $dd(void 0, void 0, fn), fn, void 0, void 0);
}
function $ud(options3, fn) {
  return new $Ad(new $dd(options3.owner, options3.debugName, options3.debugReferenceFn ?? fn), fn, void 0, void 0);
}
function $vd(options3, fn) {
  return new $Ad(new $dd(options3.owner, options3.debugName, options3.debugReferenceFn ?? fn), fn, options3.createEmptyChangeSummary, options3.handleChange);
}
function $wd(options3, fn) {
  const store = new $2c();
  const disposable = $vd({
    owner: options3.owner,
    debugName: options3.debugName,
    debugReferenceFn: options3.debugReferenceFn ?? fn,
    createEmptyChangeSummary: options3.createEmptyChangeSummary,
    handleChange: options3.handleChange
  }, (reader, changeSummary) => {
    store.clear();
    fn(reader, changeSummary, store);
  });
  return $1c(() => {
    disposable.dispose();
    store.dispose();
  });
}
function $xd(fn) {
  const store = new $2c();
  const disposable = $ud({
    owner: void 0,
    debugName: void 0,
    debugReferenceFn: fn
  }, (reader) => {
    store.clear();
    fn(reader, store);
  });
  return $1c(() => {
    disposable.dispose();
    store.dispose();
  });
}
function $zd(getValue, handler, getUniqueIdentifier = (v) => v) {
  const lastValues = /* @__PURE__ */ new Map();
  return $ud({ debugReferenceFn: getValue }, (reader) => {
    const newValues = /* @__PURE__ */ new Map();
    const removedValues = new Map(lastValues);
    for (const value of getValue(reader)) {
      const id2 = getUniqueIdentifier(value);
      if (lastValues.has(id2)) {
        removedValues.delete(id2);
      } else {
        newValues.set(id2, value);
        lastValues.set(id2, value);
      }
    }
    for (const id2 of removedValues.keys()) {
      lastValues.delete(id2);
    }
    if (newValues.size || removedValues.size) {
      handler({ addedValues: [...newValues.values()], removedValues: [...removedValues.values()] });
    }
  });
}
var AutorunState;
(function(AutorunState2) {
  AutorunState2[AutorunState2["dependenciesMightHaveChanged"] = 1] = "dependenciesMightHaveChanged";
  AutorunState2[AutorunState2["stale"] = 2] = "stale";
  AutorunState2[AutorunState2["upToDate"] = 3] = "upToDate";
})(AutorunState || (AutorunState = {}));
var $Ad = class {
  get debugName() {
    return this._debugNameData.getDebugName(this) ?? "(anonymous)";
  }
  constructor(_debugNameData, _runFn, i2, j) {
    this._debugNameData = _debugNameData;
    this._runFn = _runFn;
    this.i = i2;
    this.j = j;
    this.a = 2;
    this.b = 0;
    this.c = false;
    this.f = /* @__PURE__ */ new Set();
    this.g = /* @__PURE__ */ new Set();
    this.l = false;
    this.h = this.i?.();
    $Zd()?.handleAutorunCreated(this);
    this.k();
    $Tc(this);
  }
  dispose() {
    this.c = true;
    for (const o of this.f) {
      o.removeObserver(this);
    }
    this.f.clear();
    $Uc(this);
  }
  k() {
    if (this.a === 3) {
      return;
    }
    const emptySet = this.g;
    this.g = this.f;
    this.f = emptySet;
    this.a = 3;
    const isDisposed = this.c;
    try {
      if (!isDisposed) {
        $Zd()?.handleAutorunTriggered(this);
        const changeSummary = this.h;
        try {
          this.h = this.i?.();
          this.l = true;
          this._runFn(this, changeSummary);
        } catch (e) {
          $fb(e);
        } finally {
          this.l = false;
        }
      }
    } finally {
      if (!isDisposed) {
        $Zd()?.handleAutorunFinished(this);
      }
      for (const o of this.g) {
        o.removeObserver(this);
      }
      this.g.clear();
    }
  }
  toString() {
    return `Autorun<${this.debugName}>`;
  }
  // IObserver implementation
  beginUpdate() {
    if (this.a === 3) {
      this.a = 1;
    }
    this.b++;
  }
  endUpdate() {
    try {
      if (this.b === 1) {
        do {
          if (this.a === 1) {
            this.a = 3;
            for (const d of this.f) {
              d.reportChanges();
              if (this.a === 2) {
                break;
              }
            }
          }
          this.k();
        } while (this.a !== 3);
      }
    } finally {
      this.b--;
    }
    $kd(() => this.b >= 0);
  }
  handlePossibleChange(observable) {
    if (this.a === 3 && this.f.has(observable) && !this.g.has(observable)) {
      this.a = 1;
    }
  }
  handleChange(observable, change) {
    if (this.f.has(observable) && !this.g.has(observable)) {
      try {
        const shouldReact = this.j ? this.j({
          changedObservable: observable,
          change,
          didChange: (o) => o === observable
        }, this.h) : true;
        if (shouldReact) {
          this.a = 2;
        }
      } catch (e) {
        $fb(e);
      }
    }
  }
  readObservable(observable) {
    if (!this.l) {
      throw new $vb("The reader object cannot be used outside its compute function!");
    }
    if (this.c) {
      return observable.get();
    }
    observable.addObserver(this);
    const value = observable.get();
    this.f.add(observable);
    this.g.delete(observable);
    return value;
  }
};
(function($td2) {
  $td2.Observer = $Ad;
})($td || ($td = {}));

// out-build/vs/base/common/observableInternal/derived.js
function $2d(computeFnOrOwner, computeFn) {
  if (computeFn !== void 0) {
    return new $8d(new $dd(computeFnOrOwner, void 0, computeFn), computeFn, void 0, void 0, void 0, $md);
  }
  return new $8d(new $dd(void 0, void 0, computeFnOrOwner), computeFnOrOwner, void 0, void 0, void 0, $md);
}
function $3d(owner, computeFn, setter) {
  return new $9d(new $dd(owner, void 0, computeFn), computeFn, void 0, void 0, void 0, $md, setter);
}
function $4d(options3, computeFn) {
  return new $8d(new $dd(options3.owner, options3.debugName, options3.debugReferenceFn), computeFn, void 0, void 0, options3.onLastObserverRemoved, options3.equalsFn ?? $md);
}
$_d($4d);
function $5d(options3, computeFn) {
  return new $8d(new $dd(options3.owner, options3.debugName, void 0), computeFn, options3.createEmptyChangeSummary, options3.handleChange, void 0, options3.equalityComparer ?? $md);
}
function $6d(computeFnOrOwner, computeFnOrUndefined) {
  let computeFn;
  let owner;
  if (computeFnOrUndefined === void 0) {
    computeFn = computeFnOrOwner;
    owner = void 0;
  } else {
    owner = computeFnOrOwner;
    computeFn = computeFnOrUndefined;
  }
  const store = new $2c();
  return new $8d(new $dd(owner, void 0, computeFn), (r2) => {
    store.clear();
    return computeFn(r2, store);
  }, void 0, void 0, () => store.dispose(), $md);
}
function $7d(computeFnOrOwner, computeFnOrUndefined) {
  let computeFn;
  let owner;
  if (computeFnOrUndefined === void 0) {
    computeFn = computeFnOrOwner;
    owner = void 0;
  } else {
    owner = computeFnOrOwner;
    computeFn = computeFnOrUndefined;
  }
  let store = void 0;
  return new $8d(new $dd(owner, void 0, computeFn), (r2) => {
    if (!store) {
      store = new $2c();
    } else {
      store.clear();
    }
    const result = computeFn(r2);
    if (result) {
      store.add(result);
    }
    return result;
  }, void 0, void 0, () => {
    if (store) {
      store.dispose();
      store = void 0;
    }
  }, $md);
}
var DerivedState;
(function(DerivedState2) {
  DerivedState2[DerivedState2["initial"] = 0] = "initial";
  DerivedState2[DerivedState2["dependenciesMightHaveChanged"] = 1] = "dependenciesMightHaveChanged";
  DerivedState2[DerivedState2["stale"] = 2] = "stale";
  DerivedState2[DerivedState2["upToDate"] = 3] = "upToDate";
})(DerivedState || (DerivedState = {}));
var $8d = class extends $be {
  get debugName() {
    return this._debugNameData.getDebugName(this) ?? "(anonymous)";
  }
  constructor(_debugNameData, _computeFn, q, s, t = void 0, u) {
    super();
    this._debugNameData = _debugNameData;
    this._computeFn = _computeFn;
    this.q = q;
    this.s = s;
    this.t = t;
    this.u = u;
    this.g = 0;
    this.h = void 0;
    this.j = 0;
    this.k = /* @__PURE__ */ new Set();
    this.l = /* @__PURE__ */ new Set();
    this.m = void 0;
    this.n = false;
    this.p = false;
    this.x = false;
    this.m = this.q?.();
    $Zd()?.handleDerivedCreated(this);
  }
  f() {
    this.g = 0;
    this.h = void 0;
    for (const d of this.k) {
      d.removeObserver(this);
    }
    this.k.clear();
    this.t?.();
  }
  get() {
    if (this.p) {
      throw new $vb("Cyclic deriveds are not supported yet!");
    }
    if (this.b.size === 0) {
      let result;
      try {
        this.x = true;
        result = this._computeFn(this, this.q?.());
      } finally {
        this.x = false;
      }
      this.f();
      return result;
    } else {
      do {
        if (this.g === 1) {
          for (const d of this.k) {
            d.reportChanges();
            if (this.g === 2) {
              break;
            }
          }
        }
        if (this.g === 1) {
          this.g = 3;
        }
        this.w();
      } while (this.g !== 3);
      return this.h;
    }
  }
  w() {
    if (this.g === 3) {
      return;
    }
    const emptySet = this.l;
    this.l = this.k;
    this.k = emptySet;
    const hadValue = this.g !== 0;
    const oldValue = this.h;
    this.g = 3;
    let didChange = false;
    this.p = false;
    try {
      const changeSummary = this.m;
      this.m = this.q?.();
      try {
        this.x = true;
        this.h = this._computeFn(this, changeSummary);
      } finally {
        this.x = false;
        for (const o of this.l) {
          o.removeObserver(this);
        }
        this.l.clear();
      }
      didChange = hadValue && !this.u(oldValue, this.h);
      $Zd()?.handleDerivedRecomputed(this, {
        oldValue,
        newValue: this.h,
        change: void 0,
        didChange,
        hadValue
      });
    } catch (e) {
      $fb(e);
    }
    this.p = false;
    if (didChange) {
      for (const r2 of this.b) {
        r2.handleChange(this, void 0);
      }
    }
  }
  toString() {
    return `LazyDerived<${this.debugName}>`;
  }
  // IObserver Implementation
  beginUpdate(_observable) {
    if (this.n) {
      throw new $vb("Cyclic deriveds are not supported yet!");
    }
    this.j++;
    this.n = true;
    try {
      const propagateBeginUpdate = this.j === 1;
      if (this.g === 3) {
        this.g = 1;
        if (!propagateBeginUpdate) {
          for (const r2 of this.b) {
            r2.handlePossibleChange(this);
          }
        }
      }
      if (propagateBeginUpdate) {
        for (const r2 of this.b) {
          r2.beginUpdate(this);
        }
      }
    } finally {
      this.n = false;
    }
  }
  endUpdate(_observable) {
    this.j--;
    if (this.j === 0) {
      const observers = [...this.b];
      for (const r2 of observers) {
        r2.endUpdate(this);
      }
    }
    $kd(() => this.j >= 0);
  }
  handlePossibleChange(observable) {
    if (this.g === 3 && this.k.has(observable) && !this.l.has(observable)) {
      this.g = 1;
      for (const r2 of this.b) {
        r2.handlePossibleChange(this);
      }
    }
  }
  handleChange(observable, change) {
    if (this.k.has(observable) && !this.l.has(observable)) {
      let shouldReact = false;
      try {
        shouldReact = this.s ? this.s({
          changedObservable: observable,
          change,
          didChange: (o) => o === observable
        }, this.m) : true;
      } catch (e) {
        $fb(e);
      }
      const wasUpToDate = this.g === 3;
      if (shouldReact && (this.g === 1 || wasUpToDate)) {
        this.g = 2;
        if (wasUpToDate) {
          for (const r2 of this.b) {
            r2.handlePossibleChange(this);
          }
        }
      }
    }
  }
  readObservable(observable) {
    if (!this.x) {
      throw new $vb("The reader object cannot be used outside its compute function!");
    }
    observable.addObserver(this);
    const value = observable.get();
    this.k.add(observable);
    this.l.delete(observable);
    return value;
  }
  addObserver(observer) {
    const shouldCallBeginUpdate = !this.b.has(observer) && this.j > 0;
    super.addObserver(observer);
    if (shouldCallBeginUpdate) {
      observer.beginUpdate(this);
    }
  }
  removeObserver(observer) {
    const shouldCallEndUpdate = this.b.has(observer) && this.j > 0;
    super.removeObserver(observer);
    if (shouldCallEndUpdate) {
      observer.endUpdate(this);
    }
  }
};
var $9d = class extends $8d {
  constructor(debugNameData, computeFn, createChangeSummary, handleChange, handleLastObserverRemoved = void 0, equalityComparator, set) {
    super(debugNameData, computeFn, createChangeSummary, handleChange, handleLastObserverRemoved, equalityComparator);
    this.set = set;
  }
};

// out-build/vs/base/common/observableInternal/promise.js
var $ne = class {
  /**
   * The cached value.
   * Does not force a computation of the value.
   */
  get cachedValue() {
    return this.a;
  }
  constructor(b) {
    this.b = b;
    this.a = $he(this, void 0);
  }
  /**
   * Returns the cached value.
   * Computes the value if the value has not been cached yet.
   */
  getValue() {
    let v = this.a.get();
    if (!v) {
      v = this.b();
      this.a.set(v, void 0);
    }
    return v;
  }
};
var $oe = class _$oe {
  static fromFn(fn) {
    return new _$oe(fn());
  }
  constructor(promise) {
    this.a = $he(this, void 0);
    this.promiseResult = this.a;
    this.promise = promise.then((value) => {
      $ce((tx) => {
        this.a.set(new $pe(value, void 0), tx);
      });
      return value;
    }, (error) => {
      $ce((tx) => {
        this.a.set(new $pe(void 0, error), tx);
      });
      throw error;
    });
  }
};
var $pe = class {
  constructor(data, error) {
    this.data = data;
    this.error = error;
  }
  /**
   * Returns the value if the promise resolved, otherwise throws the error.
   */
  getDataOrThrow() {
    if (this.error) {
      throw this.error;
    }
    return this.data;
  }
};
var $qe = class {
  constructor(b) {
    this.b = b;
    this.a = new $ne(() => new $oe(this.b()));
    this.cachedPromiseResult = $2d(this, (reader) => this.a.cachedValue.read(reader)?.promiseResult.read(reader));
  }
  getPromise() {
    return this.a.getValue().promise;
  }
};

// out-build/vs/base/common/observableInternal/utilsCancellation.js
function $re(observable, predicate, isError, cancellationToken) {
  if (!predicate) {
    predicate = (state) => state !== null && state !== void 0;
  }
  return new Promise((resolve, reject) => {
    let isImmediateRun = true;
    let shouldDispose = false;
    const stateObs = observable.map((state) => {
      return {
        isFinished: predicate(state),
        error: isError ? isError(state) : false,
        state
      };
    });
    const d = $td((reader) => {
      const { isFinished, error, state } = stateObs.read(reader);
      if (isFinished || error) {
        if (isImmediateRun) {
          shouldDispose = true;
        } else {
          d.dispose();
        }
        if (error) {
          reject(error === true ? state : error);
        } else {
          resolve(state);
        }
      }
    });
    if (cancellationToken) {
      const dc = cancellationToken.onCancellationRequested(() => {
        d.dispose();
        dc.dispose();
        reject(new $lb());
      });
      if (cancellationToken.isCancellationRequested) {
        d.dispose();
        dc.dispose();
        reject(new $lb());
        return;
      }
    }
    isImmediateRun = false;
    if (shouldDispose) {
      d.dispose();
    }
  });
}

// out-build/vs/base/common/observableInternal/utils.js
function $Bd(value) {
  return new ConstObservable(value);
}
var ConstObservable = class extends $ae {
  constructor(b) {
    super();
    this.b = b;
  }
  get debugName() {
    return this.toString();
  }
  get() {
    return this.b;
  }
  addObserver(observer) {
  }
  removeObserver(observer) {
  }
  toString() {
    return `Const: ${this.b}`;
  }
};
function $Cd(promise) {
  const observable = $he("promiseValue", {});
  promise.then((value) => {
    observable.set({ value }, void 0);
  });
  return observable;
}
function $Dd(...args2) {
  let owner;
  let event;
  let getValue;
  if (args2.length === 3) {
    [owner, event, getValue] = args2;
  } else {
    [event, getValue] = args2;
  }
  return new $Fd(new $dd(owner, void 0, getValue), event, getValue, () => $Fd.globalTransaction, $md);
}
function $Ed(options3, event, getValue) {
  return new $Fd(new $dd(options3.owner, options3.debugName, options3.debugReferenceFn ?? getValue), event, getValue, () => $Fd.globalTransaction, options3.equalsFn ?? $md);
}
var $Fd = class extends $be {
  constructor(k, l, _getValue, n, p) {
    super();
    this.k = k;
    this.l = l;
    this._getValue = _getValue;
    this.n = n;
    this.p = p;
    this.h = false;
    this.s = (args2) => {
      const newValue = this._getValue(args2);
      const oldValue = this.g;
      const didChange = !this.h || !this.p(oldValue, newValue);
      let didRunTransaction = false;
      if (didChange) {
        this.g = newValue;
        if (this.h) {
          didRunTransaction = true;
          $fe(this.n(), (tx) => {
            $Zd()?.handleFromEventObservableTriggered(this, { oldValue, newValue, change: void 0, didChange, hadValue: this.h });
            for (const o of this.b) {
              tx.updateObserver(o, this);
              o.handleChange(this, void 0);
            }
          }, () => {
            const name = this.q();
            return "Event fired" + (name ? `: ${name}` : "");
          });
        }
        this.h = true;
      }
      if (!didRunTransaction) {
        $Zd()?.handleFromEventObservableTriggered(this, { oldValue, newValue, change: void 0, didChange, hadValue: this.h });
      }
    };
  }
  q() {
    return this.k.getDebugName(this);
  }
  get debugName() {
    const name = this.q();
    return "From Event" + (name ? `: ${name}` : "");
  }
  c() {
    this.j = this.l(this.s);
  }
  f() {
    this.j.dispose();
    this.j = void 0;
    this.h = false;
    this.g = void 0;
  }
  get() {
    if (this.j) {
      if (!this.h) {
        this.s(void 0);
      }
      return this.g;
    } else {
      const value = this._getValue(void 0);
      return value;
    }
  }
};
(function($Dd2) {
  $Dd2.Observer = $Fd;
  function batchEventsGlobally(tx, fn) {
    let didSet = false;
    if ($Fd.globalTransaction === void 0) {
      $Fd.globalTransaction = tx;
      didSet = true;
    }
    try {
      fn();
    } finally {
      if (didSet) {
        $Fd.globalTransaction = void 0;
      }
    }
  }
  $Dd2.batchEventsGlobally = batchEventsGlobally;
})($Dd || ($Dd = {}));
function $Gd(debugName, event) {
  return new FromEventObservableSignal(debugName, event);
}
var FromEventObservableSignal = class extends $be {
  constructor(debugName, h3) {
    super();
    this.debugName = debugName;
    this.h = h3;
    this.k = () => {
      $ce((tx) => {
        for (const o of this.b) {
          tx.updateObserver(o, this);
          o.handleChange(this, void 0);
        }
      }, () => this.debugName);
    };
  }
  c() {
    this.g = this.h(this.k);
  }
  f() {
    this.g.dispose();
    this.g = void 0;
  }
  get() {
  }
};
function $Hd(debugNameOrOwner) {
  if (typeof debugNameOrOwner === "string") {
    return new ObservableSignal(debugNameOrOwner);
  } else {
    return new ObservableSignal(void 0, debugNameOrOwner);
  }
}
var ObservableSignal = class extends $be {
  get debugName() {
    return new $dd(this.h, this.g, void 0).getDebugName(this) ?? "Observable Signal";
  }
  toString() {
    return this.debugName;
  }
  constructor(g, h3) {
    super();
    this.g = g;
    this.h = h3;
  }
  trigger(tx, change) {
    if (!tx) {
      $ce((tx2) => {
        this.trigger(tx2, change);
      }, () => `Trigger signal ${this.debugName}`);
      return;
    }
    for (const o of this.b) {
      tx.updateObserver(o, this);
      o.handleChange(this, change);
    }
  }
  get() {
  }
};
function $Kd(observable, debounceMs) {
  let hasValue = false;
  let lastValue;
  let timeout = void 0;
  return $Dd((cb) => {
    const d = $td((reader) => {
      const value = observable.read(reader);
      if (!hasValue) {
        hasValue = true;
        lastValue = value;
      } else {
        if (timeout) {
          clearTimeout(timeout);
        }
        timeout = setTimeout(() => {
          lastValue = value;
          cb();
        }, debounceMs);
      }
    });
    return {
      dispose() {
        d.dispose();
        hasValue = false;
        lastValue = void 0;
      }
    };
  }, () => {
    if (hasValue) {
      return lastValue;
    } else {
      return observable.get();
    }
  });
}
function $Ld(event, timeoutMs, disposableStore) {
  const observable = $he("triggeredRecently", false);
  let timeout = void 0;
  disposableStore.add(event(() => {
    observable.set(true, void 0);
    if (timeout) {
      clearTimeout(timeout);
    }
    timeout = setTimeout(() => {
      observable.set(false, void 0);
    }, timeoutMs);
  }));
  return observable;
}
function $Md(observable) {
  const o = new $Od(false, void 0);
  observable.addObserver(o);
  return $1c(() => {
    observable.removeObserver(o);
  });
}
$$d($Md);
function $Nd(observable, handleValue) {
  const o = new $Od(true, handleValue);
  observable.addObserver(o);
  if (handleValue) {
    handleValue(observable.get());
  } else {
    observable.reportChanges();
  }
  return $1c(() => {
    observable.removeObserver(o);
  });
}
$0d($Nd);
var $Od = class {
  constructor(b, c) {
    this.b = b;
    this.c = c;
    this.a = 0;
  }
  beginUpdate(observable) {
    this.a++;
  }
  endUpdate(observable) {
    this.a--;
    if (this.a === 0 && this.b) {
      if (this.c) {
        this.c(observable.get());
      } else {
        observable.reportChanges();
      }
    }
  }
  handlePossibleChange(observable) {
  }
  handleChange(observable, change) {
  }
};
function $Pd(owner, computeFn) {
  let lastValue = void 0;
  const observable = $4d({ owner, debugReferenceFn: computeFn }, (reader) => {
    lastValue = computeFn(reader, lastValue);
    return lastValue;
  });
  return observable;
}
function $Qd(owner, computeFn) {
  let lastValue = void 0;
  const onChange = $Hd("derivedObservableWithWritableCache");
  const observable = $2d(owner, (reader) => {
    onChange.read(reader);
    lastValue = computeFn(reader, lastValue);
    return lastValue;
  });
  return Object.assign(observable, {
    clearCache: (tx) => {
      lastValue = void 0;
      onChange.trigger(tx);
    },
    setCache: (newValue, tx) => {
      lastValue = newValue;
      onChange.trigger(tx);
    }
  });
}
function $Rd(owner, items, map, keySelector) {
  let m = new ArrayMap(map, keySelector);
  const self2 = $4d({
    debugReferenceFn: map,
    owner,
    onLastObserverRemoved: () => {
      m.dispose();
      m = new ArrayMap(map);
    }
  }, (reader) => {
    m.setItems(items.read(reader));
    return m.getItems();
  });
  return self2;
}
var ArrayMap = class {
  constructor(c, f) {
    this.c = c;
    this.f = f;
    this.a = /* @__PURE__ */ new Map();
    this.b = [];
  }
  dispose() {
    this.a.forEach((entry) => entry.store.dispose());
    this.a.clear();
  }
  setItems(items) {
    const newItems = [];
    const itemsToRemove = new Set(this.a.keys());
    for (const item of items) {
      const key2 = this.f ? this.f(item) : item;
      let entry = this.a.get(key2);
      if (!entry) {
        const store = new $2c();
        const out = this.c(item, store);
        entry = { out, store };
        this.a.set(key2, entry);
      } else {
        itemsToRemove.delete(key2);
      }
      newItems.push(entry.out);
    }
    for (const item of itemsToRemove) {
      const entry = this.a.get(item);
      entry.store.dispose();
      this.a.delete(item);
    }
    this.b = newItems;
  }
  getItems() {
    return this.b;
  }
};
var $Sd = class {
  constructor(observable) {
    this.observable = observable;
  }
  get onDidChange() {
    return Event2.fromObservableLight(this.observable);
  }
  get value() {
    return this.observable.get();
  }
};
function $Td(owner, value) {
  if (value instanceof $Sd) {
    return value.observable;
  }
  return $Dd(owner, value.onDidChange, () => value.value);
}
function $Ud(owner, observables) {
  if (observables.length === 0) {
    throw new $vb();
  }
  let hasLastChangedValue = false;
  let lastChangedValue = void 0;
  const result = $Dd(owner, (cb) => {
    const store = new $2c();
    for (const o of observables) {
      store.add($ud({ debugName: () => $ed(result, new $dd(owner, void 0, void 0)) + ".updateLastChangedValue" }, (reader) => {
        hasLastChangedValue = true;
        lastChangedValue = o.read(reader);
        cb();
      }));
    }
    store.add({
      dispose() {
        hasLastChangedValue = false;
        lastChangedValue = void 0;
      }
    });
    return store;
  }, () => {
    if (hasLastChangedValue) {
      return lastChangedValue;
    } else {
      return observables[observables.length - 1].get();
    }
  });
  return result;
}
function $Vd(owner, fn) {
  return $Pd(owner, (reader, lastValue) => lastValue ?? fn(reader));
}
function $Wd(observable, cb) {
  let _previousValue;
  return $wd({
    createEmptyChangeSummary: () => ({ deltas: [], didChange: false }),
    handleChange: (context, changeSummary) => {
      if (context.didChange(observable)) {
        const e = context.change;
        if (e !== void 0) {
          changeSummary.deltas.push(e);
        }
        changeSummary.didChange = true;
      }
      return true;
    }
  }, (reader, changeSummary) => {
    const value = observable.read(reader);
    const previousValue = _previousValue;
    if (changeSummary.didChange) {
      _previousValue = value;
      cb(value, previousValue, changeSummary.deltas);
    }
  });
}
function $Xd(observable, cb) {
  const store = new $2c();
  const disposable = $Wd(observable, (value, previousValue, deltas) => {
    store.clear();
    cb(value, previousValue, deltas, store);
  });
  return {
    dispose() {
      disposable.dispose();
      store.dispose();
    }
  };
}

// out-build/vs/base/common/observableInternal/index.js
var enableLogging = false;
if (enableLogging) {
  $Yd(new $1d());
}

// out-build/vs/editor/browser/gpu/gpuUtils.js
var $y7 = new Float32Array([
  1,
  0,
  1,
  1,
  0,
  1,
  0,
  0,
  0,
  1,
  1,
  0
]);
function $z7(value) {
  if (!value) {
    throw new Error(`Value "${value}" cannot be null`);
  }
  return value;
}
function $A7(element, parentWindow, callback) {
  let observer = new parentWindow.ResizeObserver((entries2) => {
    const entry = entries2.find((entry2) => entry2.target === element);
    if (!entry) {
      return;
    }
    if (!("devicePixelContentBoxSize" in entry)) {
      observer?.disconnect();
      observer = void 0;
      return;
    }
    const width2 = entry.devicePixelContentBoxSize[0].inlineSize;
    const height = entry.devicePixelContentBoxSize[0].blockSize;
    if (width2 > 0 && height > 0) {
      callback(width2, height);
    }
  });
  try {
    observer.observe(element, { box: ["device-pixel-content-box"] });
  } catch {
    observer.disconnect();
    observer = void 0;
    throw new $vb("Could not observe device pixel dimensions");
  }
  return $1c(() => observer?.disconnect());
}

// out-build/vs/editor/browser/gpu/raster/glyphRasterizer.js
var nextId = 0;
var $B7 = class extends $3c {
  get cacheKey() {
    return `${this.fontFamily}_${this.fontSize}px`;
  }
  constructor(fontSize, fontFamily, devicePixelRatio) {
    super();
    this.fontSize = fontSize;
    this.fontFamily = fontFamily;
    this.devicePixelRatio = devicePixelRatio;
    this.id = nextId++;
    this.f = {
      source: null,
      boundingBox: {
        left: 0,
        bottom: 0,
        right: 0,
        top: 0
      },
      originOffset: {
        x: 0,
        y: 0
      },
      fontBoundingBoxAscent: 0,
      fontBoundingBoxDescent: 0
    };
    this.g = { chars: void 0, tokenMetadata: 0, charMetadata: 0 };
    const devicePixelFontSize = Math.ceil(this.fontSize * devicePixelRatio);
    this.a = new OffscreenCanvas(devicePixelFontSize * 3, devicePixelFontSize * 3);
    this.b = $z7(this.a.getContext("2d", {
      willReadFrequently: true
    }));
    this.b.textBaseline = "top";
    this.b.fillStyle = "#FFFFFF";
    this.b.font = `${devicePixelFontSize}px ${this.fontFamily}`;
    this.c = this.b.measureText("A");
  }
  // TODO: Support drawing multiple fonts and sizes
  /**
   * Rasterizes a glyph. Note that the returned object is reused across different glyphs and
   * therefore is only safe for synchronous access.
   */
  rasterizeGlyph(chars, tokenMetadata, charMetadata, colorMap) {
    if (chars === "") {
      return {
        source: this.a,
        boundingBox: { top: 0, left: 0, bottom: -1, right: -1 },
        originOffset: { x: 0, y: 0 },
        fontBoundingBoxAscent: 0,
        fontBoundingBoxDescent: 0
      };
    }
    if (this.g.chars === chars && this.g.tokenMetadata === tokenMetadata && this.g.charMetadata === charMetadata) {
      return this.f;
    }
    this.g.chars = chars;
    this.g.tokenMetadata = tokenMetadata;
    this.g.charMetadata = charMetadata;
    return this._rasterizeGlyph(chars, tokenMetadata, charMetadata, colorMap);
  }
  _rasterizeGlyph(chars, metadata, charMetadata, colorMap) {
    const devicePixelFontSize = Math.ceil(this.fontSize * this.devicePixelRatio);
    const canvasDim = devicePixelFontSize * 3;
    if (this.a.width !== canvasDim) {
      this.a.width = canvasDim;
      this.a.height = canvasDim;
    }
    this.b.clearRect(0, 0, this.a.width, this.a.height);
    const fontSb = new $cE(200);
    const fontStyle = $pE.getFontStyle(metadata);
    if (fontStyle & 1) {
      fontSb.appendString("italic ");
    }
    if (fontStyle & 2) {
      fontSb.appendString("bold ");
    }
    fontSb.appendString(`${devicePixelFontSize}px ${this.fontFamily}`);
    this.b.font = fontSb.build();
    const originX = devicePixelFontSize;
    const originY = devicePixelFontSize;
    if (charMetadata) {
      this.b.fillStyle = `#${charMetadata.toString(16).padStart(8, "0")}`;
    } else {
      this.b.fillStyle = colorMap[$pE.getForeground(metadata)];
    }
    this.b.textBaseline = "top";
    this.b.fillText(chars, originX, originY);
    const imageData = this.b.getImageData(0, 0, this.a.width, this.a.height);
    this.h(imageData, this.f.boundingBox);
    this.f.source = this.a;
    this.f.originOffset.x = this.f.boundingBox.left - originX;
    this.f.originOffset.y = this.f.boundingBox.top - originY;
    this.f.fontBoundingBoxAscent = this.c.fontBoundingBoxAscent;
    this.f.fontBoundingBoxDescent = this.c.fontBoundingBoxDescent;
    return this.f;
  }
  // TODO: Does this even need to happen when measure text is used?
  h(imageData, outBoundingBox) {
    const height = this.a.height;
    const width2 = this.a.width;
    let found = false;
    for (let y = 0; y < height; y++) {
      for (let x = 0; x < width2; x++) {
        const alphaOffset = y * width2 * 4 + x * 4 + 3;
        if (imageData.data[alphaOffset] !== 0) {
          outBoundingBox.top = y;
          found = true;
          break;
        }
      }
      if (found) {
        break;
      }
    }
    outBoundingBox.left = 0;
    found = false;
    for (let x = 0; x < width2; x++) {
      for (let y = 0; y < height; y++) {
        const alphaOffset = y * width2 * 4 + x * 4 + 3;
        if (imageData.data[alphaOffset] !== 0) {
          outBoundingBox.left = x;
          found = true;
          break;
        }
      }
      if (found) {
        break;
      }
    }
    outBoundingBox.right = width2;
    found = false;
    for (let x = width2 - 1; x >= outBoundingBox.left; x--) {
      for (let y = 0; y < height; y++) {
        const alphaOffset = y * width2 * 4 + x * 4 + 3;
        if (imageData.data[alphaOffset] !== 0) {
          outBoundingBox.right = x;
          found = true;
          break;
        }
      }
      if (found) {
        break;
      }
    }
    outBoundingBox.bottom = outBoundingBox.top;
    found = false;
    for (let y = height - 1; y >= 0; y--) {
      for (let x = 0; x < width2; x++) {
        const alphaOffset = y * width2 * 4 + x * 4 + 3;
        if (imageData.data[alphaOffset] !== 0) {
          outBoundingBox.bottom = y;
          found = true;
          break;
        }
      }
      if (found) {
        break;
      }
    }
  }
};
__decorate([
  $0t
], $B7.prototype, "cacheKey", null);

// out-build/vs/editor/browser/gpu/taskQueue.js
var TaskQueue = class extends $3c {
  constructor() {
    super();
    this.a = [];
    this.c = 0;
    this.B($1c(() => this.clear()));
  }
  enqueue(task) {
    this.a.push(task);
    this.h();
  }
  flush() {
    while (this.c < this.a.length) {
      if (!this.a[this.c]()) {
        this.c++;
      }
    }
    this.clear();
  }
  clear() {
    if (this.b) {
      this.g(this.b);
      this.b = void 0;
    }
    this.c = 0;
    this.a.length = 0;
  }
  h() {
    if (!this.b) {
      this.b = this.f(this.j.bind(this));
    }
  }
  j(deadline) {
    this.b = void 0;
    let taskDuration = 0;
    let longestTask = 0;
    let lastDeadlineRemaining = deadline.timeRemaining();
    let deadlineRemaining = 0;
    while (this.c < this.a.length) {
      taskDuration = Date.now();
      if (!this.a[this.c]()) {
        this.c++;
      }
      taskDuration = Math.max(1, Date.now() - taskDuration);
      longestTask = Math.max(taskDuration, longestTask);
      deadlineRemaining = deadline.timeRemaining();
      if (longestTask * 1.5 > deadlineRemaining) {
        if (lastDeadlineRemaining - taskDuration < -20) {
          console.warn(`task queue exceeded allotted deadline by ${Math.abs(Math.round(lastDeadlineRemaining - taskDuration))}ms`);
        }
        this.h();
        return;
      }
      lastDeadlineRemaining = deadlineRemaining;
    }
    this.clear();
  }
};
var $D7 = class extends TaskQueue {
  f(callback) {
    return $Qj().requestIdleCallback(callback);
  }
  g(identifier2) {
    $Qj().cancelIdleCallback(identifier2);
  }
};

// out-build/vs/editor/browser/gpu/atlas/textureAtlasShelfAllocator.js
var $F7 = class {
  constructor(e, f) {
    this.e = e;
    this.f = f;
    this.b = {
      x: 0,
      y: 0,
      h: 0
    };
    this.c = /* @__PURE__ */ new Set();
    this.d = 0;
    this.a = $z7(this.e.getContext("2d", {
      willReadFrequently: true
    }));
  }
  allocate(rasterizedGlyph) {
    const glyphWidth = rasterizedGlyph.boundingBox.right - rasterizedGlyph.boundingBox.left + 1;
    const glyphHeight = rasterizedGlyph.boundingBox.bottom - rasterizedGlyph.boundingBox.top + 1;
    if (glyphWidth > this.e.width || glyphHeight > this.e.height) {
      throw new $vb("Glyph is too large for the atlas page");
    }
    if (rasterizedGlyph.boundingBox.right - rasterizedGlyph.boundingBox.left + 1 > this.e.width - this.b.x) {
      this.b.x = 0;
      this.b.y += this.b.h;
      this.b.h = 1;
    }
    if (this.b.y + rasterizedGlyph.boundingBox.bottom - rasterizedGlyph.boundingBox.top + 1 > this.e.height) {
      return void 0;
    }
    this.a.drawImage(
      rasterizedGlyph.source,
      // source
      rasterizedGlyph.boundingBox.left,
      rasterizedGlyph.boundingBox.top,
      glyphWidth,
      glyphHeight,
      // destination
      this.b.x,
      this.b.y,
      glyphWidth,
      glyphHeight
    );
    const glyph = {
      pageIndex: this.f,
      glyphIndex: this.d++,
      x: this.b.x,
      y: this.b.y,
      w: glyphWidth,
      h: glyphHeight,
      originOffsetX: rasterizedGlyph.originOffset.x,
      originOffsetY: rasterizedGlyph.originOffset.y,
      fontBoundingBoxAscent: rasterizedGlyph.fontBoundingBoxAscent,
      fontBoundingBoxDescent: rasterizedGlyph.fontBoundingBoxDescent
    };
    this.b.x += glyphWidth;
    this.b.h = Math.max(this.b.h, glyphHeight);
    this.c.add(glyph);
    return glyph;
  }
  getUsagePreview() {
    const w = this.e.width;
    const h3 = this.e.height;
    const canvas = new OffscreenCanvas(w, h3);
    const ctx = $z7(canvas.getContext("2d"));
    ctx.fillStyle = "#808080";
    ctx.fillRect(0, 0, w, h3);
    const rowHeight = /* @__PURE__ */ new Map();
    const rowWidth = /* @__PURE__ */ new Map();
    for (const g of this.c) {
      rowHeight.set(g.y, Math.max(rowHeight.get(g.y) ?? 0, g.h));
      rowWidth.set(g.y, Math.max(rowWidth.get(g.y) ?? 0, g.x + g.w));
    }
    for (const g of this.c) {
      ctx.fillStyle = "#4040FF";
      ctx.fillRect(g.x, g.y, g.w, g.h);
      ctx.fillStyle = "#FF0000";
      ctx.fillRect(g.x, g.y + g.h, g.w, rowHeight.get(g.y) - g.h);
    }
    for (const [rowY, rowW] of rowWidth.entries()) {
      if (rowY !== this.b.y) {
        ctx.fillStyle = "#FF0000";
        ctx.fillRect(rowW, rowY, w - rowW, rowHeight.get(rowY));
      }
    }
    return canvas.convertToBlob();
  }
  getStats() {
    const w = this.e.width;
    const h3 = this.e.height;
    let usedPixels = 0;
    let wastedPixels = 0;
    const totalPixels = w * h3;
    const rowHeight = /* @__PURE__ */ new Map();
    const rowWidth = /* @__PURE__ */ new Map();
    for (const g of this.c) {
      rowHeight.set(g.y, Math.max(rowHeight.get(g.y) ?? 0, g.h));
      rowWidth.set(g.y, Math.max(rowWidth.get(g.y) ?? 0, g.x + g.w));
    }
    for (const g of this.c) {
      usedPixels += g.w * g.h;
      wastedPixels += g.w * (rowHeight.get(g.y) - g.h);
    }
    for (const [rowY, rowW] of rowWidth.entries()) {
      if (rowY !== this.b.y) {
        wastedPixels += (w - rowW) * rowHeight.get(rowY);
      }
    }
    return [
      `page${this.f}:`,
      `     Total: ${totalPixels} (${w}x${h3})`,
      `      Used: ${usedPixels} (${(usedPixels / totalPixels * 100).toPrecision(2)}%)`,
      `    Wasted: ${wastedPixels} (${(wastedPixels / totalPixels * 100).toPrecision(2)}%)`,
      `Efficiency: ${(usedPixels / (usedPixels + wastedPixels) * 100).toPrecision(2)}%`
    ].join("\n");
  }
};

// out-build/vs/editor/browser/gpu/atlas/textureAtlasSlabAllocator.js
var $G7 = class {
  constructor(p, q, options3) {
    this.p = p;
    this.q = q;
    this.b = [];
    this.c = new $Nc();
    this.d = [];
    this.e = /* @__PURE__ */ new Map();
    this.f = /* @__PURE__ */ new Map();
    this.j = /* @__PURE__ */ new Set();
    this.o = 0;
    this.a = $z7(this.p.getContext("2d", {
      willReadFrequently: true
    }));
    this.k = Math.min(options3?.slabW ?? 64 << Math.max(Math.floor($Qj().devicePixelRatio) - 1, 0), this.p.width);
    this.l = Math.min(options3?.slabH ?? this.k, this.p.height);
    this.m = Math.floor(this.p.width / this.k);
    this.n = Math.floor(this.p.height / this.l);
  }
  allocate(rasterizedGlyph) {
    const glyphWidth = rasterizedGlyph.boundingBox.right - rasterizedGlyph.boundingBox.left + 1;
    const glyphHeight = rasterizedGlyph.boundingBox.bottom - rasterizedGlyph.boundingBox.top + 1;
    if (glyphWidth > this.p.width || glyphHeight > this.p.height) {
      throw new $vb("Glyph is too large for the atlas page");
    }
    if (glyphWidth > this.k || glyphHeight > this.l) {
      if (this.j.size > 0) {
        return void 0;
      }
      let sizeCandidate = this.p.width;
      while (glyphWidth < sizeCandidate / 2 && glyphHeight < sizeCandidate / 2) {
        sizeCandidate /= 2;
      }
      this.k = sizeCandidate;
      this.l = sizeCandidate;
      this.m = Math.floor(this.p.width / this.k);
      this.n = Math.floor(this.p.height / this.l);
    }
    const desiredSlabSize = {
      // Nearest square number
      // TODO: This can probably be optimized
      // w: 1 << Math.ceil(Math.sqrt(glyphWidth)),
      // h: 1 << Math.ceil(Math.sqrt(glyphHeight)),
      // Nearest x px
      // w: Math.ceil(glyphWidth / nearestXPixels) * nearestXPixels,
      // h: Math.ceil(glyphHeight / nearestXPixels) * nearestXPixels,
      // Round odd numbers up
      // w: glyphWidth % 0 === 1 ? glyphWidth + 1 : glyphWidth,
      // h: glyphHeight % 0 === 1 ? glyphHeight + 1 : glyphHeight,
      // Exact number only
      w: glyphWidth,
      h: glyphHeight
    };
    let slab = this.c.get(desiredSlabSize.w, desiredSlabSize.h);
    if (slab) {
      const glyphsPerSlab = Math.floor(this.k / slab.entryW) * Math.floor(this.l / slab.entryH);
      if (slab.count >= glyphsPerSlab) {
        slab = void 0;
      }
    }
    let dx;
    let dy;
    if (!slab) {
      if (glyphWidth < glyphHeight) {
        const openRegions = this.f.get(glyphWidth);
        if (openRegions?.length) {
          for (let i2 = openRegions.length - 1; i2 >= 0; i2--) {
            const r2 = openRegions[i2];
            if (r2.w >= glyphWidth && r2.h >= glyphHeight) {
              dx = r2.x;
              dy = r2.y;
              if (glyphWidth < r2.w) {
                this.d.push({
                  x: r2.x + glyphWidth,
                  y: r2.y,
                  w: r2.w - glyphWidth,
                  h: glyphHeight
                });
              }
              r2.y += glyphHeight;
              r2.h -= glyphHeight;
              if (r2.h === 0) {
                if (i2 === openRegions.length - 1) {
                  openRegions.pop();
                } else {
                  this.d.splice(i2, 1);
                }
              }
              break;
            }
          }
        }
      } else {
        const openRegions = this.e.get(glyphHeight);
        if (openRegions?.length) {
          for (let i2 = openRegions.length - 1; i2 >= 0; i2--) {
            const r2 = openRegions[i2];
            if (r2.w >= glyphWidth && r2.h >= glyphHeight) {
              dx = r2.x;
              dy = r2.y;
              if (glyphHeight < r2.h) {
                this.d.push({
                  x: r2.x,
                  y: r2.y + glyphHeight,
                  w: glyphWidth,
                  h: r2.h - glyphHeight
                });
              }
              r2.x += glyphWidth;
              r2.w -= glyphWidth;
              if (r2.h === 0) {
                if (i2 === openRegions.length - 1) {
                  openRegions.pop();
                } else {
                  this.d.splice(i2, 1);
                }
              }
              break;
            }
          }
        }
      }
    }
    if (dx === void 0 || dy === void 0) {
      if (!slab) {
        if (this.b.length >= this.m * this.n) {
          return void 0;
        }
        slab = {
          x: Math.floor(this.b.length % this.m) * this.k,
          y: Math.floor(this.b.length / this.m) * this.l,
          entryW: desiredSlabSize.w,
          entryH: desiredSlabSize.h,
          count: 0
        };
        const unusedW = this.k % slab.entryW;
        const unusedH = this.l % slab.entryH;
        if (unusedW) {
          addEntryToMapArray(this.f, unusedW, {
            x: slab.x + this.k - unusedW,
            w: unusedW,
            y: slab.y,
            h: this.l - (unusedH ?? 0)
          });
        }
        if (unusedH) {
          addEntryToMapArray(this.e, unusedH, {
            x: slab.x,
            w: this.k,
            y: slab.y + this.l - unusedH,
            h: unusedH
          });
        }
        this.b.push(slab);
        this.c.set(desiredSlabSize.w, desiredSlabSize.h, slab);
      }
      const glyphsPerRow = Math.floor(this.k / slab.entryW);
      dx = slab.x + Math.floor(slab.count % glyphsPerRow) * slab.entryW;
      dy = slab.y + Math.floor(slab.count / glyphsPerRow) * slab.entryH;
      slab.count++;
    }
    this.a.drawImage(
      rasterizedGlyph.source,
      // source
      rasterizedGlyph.boundingBox.left,
      rasterizedGlyph.boundingBox.top,
      glyphWidth,
      glyphHeight,
      // destination
      dx,
      dy,
      glyphWidth,
      glyphHeight
    );
    const glyph = {
      pageIndex: this.q,
      glyphIndex: this.o++,
      x: dx,
      y: dy,
      w: glyphWidth,
      h: glyphHeight,
      originOffsetX: rasterizedGlyph.originOffset.x,
      originOffsetY: rasterizedGlyph.originOffset.y,
      fontBoundingBoxAscent: rasterizedGlyph.fontBoundingBoxAscent,
      fontBoundingBoxDescent: rasterizedGlyph.fontBoundingBoxDescent
    };
    this.j.add(glyph);
    return glyph;
  }
  getUsagePreview() {
    const w = this.p.width;
    const h3 = this.p.height;
    const canvas = new OffscreenCanvas(w, h3);
    const ctx = $z7(canvas.getContext("2d"));
    ctx.fillStyle = "#808080";
    ctx.fillRect(0, 0, w, h3);
    let slabEntryPixels = 0;
    let usedPixels = 0;
    let slabEdgePixels = 0;
    let restrictedPixels = 0;
    const slabW = 64 << Math.floor($Qj().devicePixelRatio) - 1;
    const slabH = slabW;
    for (const slab of this.b) {
      let x = 0;
      let y = 0;
      for (let i2 = 0; i2 < slab.count; i2++) {
        if (x + slab.entryW > slabW) {
          x = 0;
          y += slab.entryH;
        }
        ctx.fillStyle = "#FF0000";
        ctx.fillRect(slab.x + x, slab.y + y, slab.entryW, slab.entryH);
        slabEntryPixels += slab.entryW * slab.entryH;
        x += slab.entryW;
      }
      const entriesPerRow = Math.floor(slabW / slab.entryW);
      const entriesPerCol = Math.floor(slabH / slab.entryH);
      const thisSlabPixels = slab.entryW * entriesPerRow * slab.entryH * entriesPerCol;
      slabEdgePixels += slabW * slabH - thisSlabPixels;
    }
    for (const g of this.j) {
      usedPixels += g.w * g.h;
      ctx.fillStyle = "#4040FF";
      ctx.fillRect(g.x, g.y, g.w, g.h);
    }
    const unusedRegions = Array.from(this.f.values()).flat().concat(Array.from(this.e.values()).flat());
    for (const r2 of unusedRegions) {
      ctx.fillStyle = "#FF000088";
      ctx.fillRect(r2.x, r2.y, r2.w, r2.h);
      restrictedPixels += r2.w * r2.h;
    }
    ctx.globalAlpha = 0.5;
    ctx.drawImage(this.p, 0, 0);
    ctx.globalAlpha = 1;
    return canvas.convertToBlob();
  }
  getStats() {
    const w = this.p.width;
    const h3 = this.p.height;
    let slabEntryPixels = 0;
    let usedPixels = 0;
    let slabEdgePixels = 0;
    let wastedPixels = 0;
    let restrictedPixels = 0;
    const totalPixels = w * h3;
    const slabW = 64 << Math.floor($Qj().devicePixelRatio) - 1;
    const slabH = slabW;
    for (const slab of this.b) {
      let x = 0;
      let y = 0;
      for (let i2 = 0; i2 < slab.count; i2++) {
        if (x + slab.entryW > slabW) {
          x = 0;
          y += slab.entryH;
        }
        slabEntryPixels += slab.entryW * slab.entryH;
        x += slab.entryW;
      }
      const entriesPerRow = Math.floor(slabW / slab.entryW);
      const entriesPerCol = Math.floor(slabH / slab.entryH);
      const thisSlabPixels = slab.entryW * entriesPerRow * slab.entryH * entriesPerCol;
      slabEdgePixels += slabW * slabH - thisSlabPixels;
    }
    for (const g of this.j) {
      usedPixels += g.w * g.h;
    }
    const unusedRegions = Array.from(this.f.values()).flat().concat(Array.from(this.e.values()).flat());
    for (const r2 of unusedRegions) {
      restrictedPixels += r2.w * r2.h;
    }
    const edgeUsedPixels = slabEdgePixels - restrictedPixels;
    wastedPixels = slabEntryPixels - (usedPixels - edgeUsedPixels);
    const efficiency = usedPixels / (usedPixels + wastedPixels + restrictedPixels);
    return [
      `page[${this.q}]:`,
      `     Total: ${totalPixels}px (${w}x${h3})`,
      `      Used: ${usedPixels}px (${(usedPixels / totalPixels * 100).toFixed(2)}%)`,
      `    Wasted: ${wastedPixels}px (${(wastedPixels / totalPixels * 100).toFixed(2)}%)`,
      `Restricted: ${restrictedPixels}px (${(restrictedPixels / totalPixels * 100).toFixed(2)}%) (hard to allocate)`,
      `Efficiency: ${efficiency === 1 ? "100" : (efficiency * 100).toFixed(2)}%`,
      `     Slabs: ${this.b.length} of ${Math.floor(this.p.width / slabW) * Math.floor(this.p.height / slabH)}`
    ].join("\n");
  }
};
function addEntryToMapArray(map, key2, entry) {
  let list2 = map.get(key2);
  if (!list2) {
    list2 = [];
    map.set(key2, list2);
  }
  list2.push(entry);
}

// out-build/vs/editor/browser/gpu/atlas/textureAtlasPage.js
var $H7_1;
var $H7 = class $H72 extends $3c {
  static {
    $H7_1 = this;
  }
  get version() {
    return this.a;
  }
  static {
    this.maximumGlyphCount = 5e3;
  }
  get usedArea() {
    return this.b;
  }
  get source() {
    return this.c;
  }
  get glyphs() {
    return this.g.values();
  }
  constructor(textureIndex, pageSize, allocatorType, n, themeService) {
    super();
    this.n = n;
    this.a = 0;
    this.b = { left: 0, top: 0, right: 0, bottom: 0 };
    this.f = new $Pc();
    this.g = /* @__PURE__ */ new Set();
    this.c = new OffscreenCanvas(pageSize, pageSize);
    this.m = themeService.getColorTheme().tokenColorMap;
    switch (allocatorType) {
      case "shelf":
        this.j = new $F7(this.c, textureIndex);
        break;
      case "slab":
        this.j = new $G7(this.c, textureIndex);
        break;
      default:
        this.j = allocatorType(this.c, textureIndex);
        break;
    }
    this.B($1c(() => {
      this.c.width = 1;
      this.c.height = 1;
    }));
  }
  getGlyph(rasterizer, chars, tokenMetadata, charMetadata) {
    return this.f.get(chars, tokenMetadata, charMetadata, rasterizer.cacheKey) ?? this.r(rasterizer, chars, tokenMetadata, charMetadata);
  }
  r(rasterizer, chars, tokenMetadata, charMetadata) {
    if (this.g.size >= $H7_1.maximumGlyphCount) {
      return void 0;
    }
    const rasterizedGlyph = rasterizer.rasterizeGlyph(chars, tokenMetadata, charMetadata, this.m);
    const glyph = this.j.allocate(rasterizedGlyph);
    if (glyph === void 0) {
      return void 0;
    }
    this.f.set(chars, tokenMetadata, charMetadata, rasterizer.cacheKey, glyph);
    this.g.add(glyph);
    this.a++;
    this.b.right = Math.max(this.b.right, glyph.x + glyph.w - 1);
    this.b.bottom = Math.max(this.b.bottom, glyph.y + glyph.h - 1);
    if (this.n.getLevel() === LogLevel.Trace) {
      this.n.trace("New glyph", {
        chars,
        tokenMetadata,
        charMetadata,
        rasterizedGlyph,
        glyph
      });
    }
    return glyph;
  }
  getUsagePreview() {
    return this.j.getUsagePreview();
  }
  getStats() {
    return this.j.getStats();
  }
};
$H7 = $H7_1 = __decorate([
  __param(3, $wn),
  __param(4, $gs)
], $H7);

// out-build/vs/editor/browser/gpu/atlas/textureAtlas.js
var $I7_1;
var $I7 = class $I72 extends $3c {
  static {
    $I7_1 = this;
  }
  static {
    this.maximumPageCount = 16;
  }
  get pages() {
    return this.h;
  }
  constructor(n, options3, r2, s) {
    super();
    this.n = n;
    this.r = r2;
    this.s = s;
    this.c = this.B(new $4c());
    this.f = /* @__PURE__ */ new Set();
    this.h = [];
    this.j = new $Pc();
    this.m = this.B(new $ze());
    this.onDidDeleteGlyphs = this.m.event;
    this.g = options3?.allocatorType ?? "slab";
    this.B(Event2.runAndSubscribe(this.r.onDidColorThemeChange, () => {
      if (this.b) {
        this.clear();
      }
      this.b = this.r.getColorTheme().tokenColorMap;
    }));
    const dprFactor = Math.max(1, Math.floor($Qj().devicePixelRatio));
    this.pageSize = Math.min(1024 * dprFactor, this.n);
    this.t();
    this.B($1c(() => $Xc(this.h)));
  }
  t() {
    const firstPage = this.s.createInstance($H7, 0, this.pageSize, this.g);
    this.h.push(firstPage);
    const nullRasterizer = new $B7(1, "", 1);
    firstPage.getGlyph(nullRasterizer, "", 0, 0);
    nullRasterizer.dispose();
  }
  clear() {
    for (const page of this.h) {
      page.dispose();
    }
    this.h.length = 0;
    this.j.clear();
    this.f.clear();
    this.c.clear();
    this.t();
    this.m.fire();
  }
  getGlyph(rasterizer, chars, tokenMetadata, charMetadata) {
    tokenMetadata &= ~(255 | 768 | 1024);
    if (!this.f.has(rasterizer.id)) {
      this.y(rasterizer);
      this.f.add(rasterizer.id);
    }
    return this.u(this.j.get(chars, tokenMetadata, charMetadata, rasterizer.cacheKey) ?? 0, rasterizer, chars, tokenMetadata, charMetadata);
  }
  u(pageIndex, rasterizer, chars, tokenMetadata, charMetadata) {
    this.j.set(chars, tokenMetadata, charMetadata, rasterizer.cacheKey, pageIndex);
    return this.h[pageIndex].getGlyph(rasterizer, chars, tokenMetadata, charMetadata) ?? (pageIndex + 1 < this.h.length ? this.u(pageIndex + 1, rasterizer, chars, tokenMetadata, charMetadata) : void 0) ?? this.w(rasterizer, chars, tokenMetadata, charMetadata);
  }
  w(rasterizer, chars, tokenMetadata, charMetadata) {
    if (this.h.length >= $I7_1.maximumPageCount) {
      throw new Error(`Attempt to create a texture atlas page past the limit ${$I7_1.maximumPageCount}`);
    }
    this.h.push(this.s.createInstance($H7, this.h.length, this.pageSize, this.g));
    this.j.set(chars, tokenMetadata, charMetadata, rasterizer.cacheKey, this.h.length - 1);
    return this.h[this.h.length - 1].getGlyph(rasterizer, chars, tokenMetadata, charMetadata);
  }
  getUsagePreview() {
    return Promise.all(this.h.map((e) => e.getUsagePreview()));
  }
  getStats() {
    return this.h.map((e) => e.getStats());
  }
  /**
   * Warms up the atlas by rasterizing all printable ASCII characters for each token color. This
   * is distrubuted over multiple idle callbacks to avoid blocking the main thread.
   */
  y(rasterizer) {
    const colorMap = this.b;
    if (!colorMap) {
      throw new $vb("Cannot warm atlas without color map");
    }
    this.c.value?.clear();
    const taskQueue = this.c.value = new $D7();
    for (let code = 65; code <= 90; code++) {
      taskQueue.enqueue(() => {
        for (const fgColor of colorMap.keys()) {
          this.getGlyph(rasterizer, String.fromCharCode(code), fgColor << 15 & 16744448, 0);
        }
      });
    }
    for (let code = 97; code <= 122; code++) {
      taskQueue.enqueue(() => {
        for (const fgColor of colorMap.keys()) {
          this.getGlyph(rasterizer, String.fromCharCode(code), fgColor << 15 & 16744448, 0);
        }
      });
    }
    for (let code = 33; code <= 126; code++) {
      taskQueue.enqueue(() => {
        for (const fgColor of colorMap.keys()) {
          this.getGlyph(rasterizer, String.fromCharCode(code), fgColor << 15 & 16744448, 0);
        }
      });
    }
  }
};
$I7 = $I7_1 = __decorate([
  __param(2, $gs),
  __param(3, $Pk)
], $I7);

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

// out-build/vs/platform/notification/common/notification.js
var Severity2 = severity_default;
var $PJ = $Qk("notificationService");
var NotificationPriority;
(function(NotificationPriority2) {
  NotificationPriority2[NotificationPriority2["DEFAULT"] = 0] = "DEFAULT";
  NotificationPriority2[NotificationPriority2["SILENT"] = 1] = "SILENT";
  NotificationPriority2[NotificationPriority2["URGENT"] = 2] = "URGENT";
})(NotificationPriority || (NotificationPriority = {}));
var NeverShowAgainScope;
(function(NeverShowAgainScope2) {
  NeverShowAgainScope2[NeverShowAgainScope2["WORKSPACE"] = 0] = "WORKSPACE";
  NeverShowAgainScope2[NeverShowAgainScope2["PROFILE"] = 1] = "PROFILE";
  NeverShowAgainScope2[NeverShowAgainScope2["APPLICATION"] = 2] = "APPLICATION";
})(NeverShowAgainScope || (NeverShowAgainScope = {}));
function $QJ(thing) {
  if (thing) {
    const candidate = thing;
    return typeof candidate.id === "string" && typeof candidate.label === "string";
  }
  return false;
}
var NotificationsFilter;
(function(NotificationsFilter2) {
  NotificationsFilter2[NotificationsFilter2["OFF"] = 0] = "OFF";
  NotificationsFilter2[NotificationsFilter2["ERROR"] = 1] = "ERROR";
})(NotificationsFilter || (NotificationsFilter = {}));
var $RJ = class {
  constructor() {
    this.progress = new $SJ();
    this.onDidClose = Event2.None;
    this.onDidChangeVisibility = Event2.None;
  }
  updateSeverity(severity) {
  }
  updateMessage(message) {
  }
  updateActions(actions) {
  }
  close() {
  }
};
var $SJ = class {
  infinite() {
  }
  done() {
  }
  total(value) {
  }
  worked(value) {
  }
};

// out-build/vs/editor/browser/gpu/gpuDisposable.js
var GPULifecycle;
(function(GPULifecycle2) {
  async function requestDevice(fallback2) {
    try {
      if (!navigator.gpu) {
        throw new Error("This browser does not support WebGPU");
      }
      const adapter = await navigator.gpu.requestAdapter();
      if (!adapter) {
        throw new Error("This browser supports WebGPU but it appears to be disabled");
      }
      return wrapDestroyableInDisposable(await adapter.requestDevice());
    } catch (e) {
      if (fallback2) {
        fallback2(e.message);
      }
      throw e;
    }
  }
  GPULifecycle2.requestDevice = requestDevice;
  function createBuffer(device, descriptor, initialValues) {
    const buffer = device.createBuffer(descriptor);
    if (initialValues) {
      device.queue.writeBuffer(buffer, 0, $Ng(initialValues) ? initialValues() : initialValues);
    }
    return wrapDestroyableInDisposable(buffer);
  }
  GPULifecycle2.createBuffer = createBuffer;
  function createTexture(device, descriptor) {
    return wrapDestroyableInDisposable(device.createTexture(descriptor));
  }
  GPULifecycle2.createTexture = createTexture;
})(GPULifecycle || (GPULifecycle = {}));
function wrapDestroyableInDisposable(value) {
  return {
    object: value,
    dispose: () => value.destroy()
  };
}

// out-build/vs/editor/browser/gpu/bufferDirtyTracker.js
var $J7 = class {
  get dataOffset() {
    return this.a;
  }
  get dirtySize() {
    if (this.a === void 0 || this.b === void 0) {
      return void 0;
    }
    return this.b - this.a + 1;
  }
  get isDirty() {
    return this.a !== void 0;
  }
  /**
   * Flag the index(es) as modified. Returns the index flagged.
   * @param index An index to flag.
   * @param length An optional length to flag. Defaults to 1.
   */
  flag(index, length = 1) {
    this.c(index);
    if (length > 1) {
      this.c(index + length - 1);
    }
    return index;
  }
  c(index) {
    if (this.a === void 0 || index < this.a) {
      this.a = index;
    }
    if (this.b === void 0 || index > this.b) {
      this.b = index;
    }
  }
  clear() {
    this.a = void 0;
    this.b = void 0;
  }
};

// out-build/vs/editor/browser/gpu/objectCollectionBuffer.js
function $K7(propertySpecs, capacity) {
  return new ObjectCollectionBuffer(propertySpecs, capacity);
}
var ObjectCollectionBuffer = class extends $3c {
  get bufferUsedSize() {
    return this.viewUsedSize * Float32Array.BYTES_PER_ELEMENT;
  }
  get viewUsedSize() {
    return this.f.size * this.c;
  }
  get entryCount() {
    return this.f.size;
  }
  get dirtyTracker() {
    return this.a;
  }
  constructor(propertySpecs, capacity) {
    super();
    this.propertySpecs = propertySpecs;
    this.capacity = capacity;
    this.a = new $J7();
    this.b = /* @__PURE__ */ new Map();
    this.f = new $cd();
    this.g = this.B(new $ze());
    this.onDidChange = this.g.event;
    this.h = this.B(new $ze());
    this.onDidChangeBuffer = this.h.event;
    this.view = new Float32Array(capacity * propertySpecs.length);
    this.buffer = this.view.buffer;
    this.c = propertySpecs.length;
    for (let i2 = 0; i2 < propertySpecs.length; i2++) {
      const spec = {
        offset: i2,
        ...propertySpecs[i2]
      };
      this.b.set(spec.name, spec);
    }
    this.B($1c(() => $Xc(this.f)));
  }
  createEntry(data) {
    if (this.f.size === this.capacity) {
      this.j();
      this.h.fire();
    }
    const value = new ObjectCollectionBufferEntry(this.view, this.b, this.a, this.f.size, data);
    const removeFromEntries = this.f.push(value);
    const listeners = [];
    listeners.push(Event2.forward(value.onDidChange, this.g));
    listeners.push(value.onWillDispose(() => {
      const deletedEntryIndex = value.i;
      removeFromEntries();
      this.view.set(this.view.subarray(deletedEntryIndex * this.c + 2, this.f.size * this.c + 2), deletedEntryIndex * this.c);
      for (const entry of this.f) {
        if (entry.i > deletedEntryIndex) {
          entry.i--;
        }
      }
      this.a.flag(deletedEntryIndex, (this.f.size - deletedEntryIndex) * this.c);
      $Xc(listeners);
    }));
    return value;
  }
  j() {
    this.capacity *= 2;
    const newView = new Float32Array(this.capacity * this.c);
    newView.set(this.view);
    this.view = newView;
    this.buffer = this.view.buffer;
  }
};
var ObjectCollectionBufferEntry = class extends $3c {
  constructor(c, f, g, i2, data) {
    super();
    this.c = c;
    this.f = f;
    this.g = g;
    this.i = i2;
    this.a = this.B(new $ze());
    this.onDidChange = this.a.event;
    this.b = this.B(new $ze());
    this.onWillDispose = this.b.event;
    for (const propertySpec of this.f.values()) {
      this.c[this.i * this.f.size + propertySpec.offset] = data[propertySpec.name];
    }
    this.g.flag(this.i * this.f.size, this.f.size);
  }
  dispose() {
    this.b.fire();
    super.dispose();
  }
  set(propertyName, value) {
    const i2 = this.i * this.f.size + this.f.get(propertyName).offset;
    this.c[this.g.flag(i2)] = value;
    this.a.fire();
  }
  get(propertyName) {
    return this.c[this.i * this.f.size + this.f.get(propertyName).offset];
  }
  setRaw(data) {
    if (data.length !== this.f.size) {
      throw new Error(`Data length ${data.length} does not match the number of properties in the collection (${this.f.size})`);
    }
    this.c.set(data, this.i * this.f.size);
    this.g.flag(this.i * this.f.size, this.f.size);
  }
};

// out-build/vs/editor/browser/gpu/rectangleRenderer.wgsl.js
var RectangleRendererBindingId;
(function(RectangleRendererBindingId2) {
  RectangleRendererBindingId2[RectangleRendererBindingId2["Shapes"] = 0] = "Shapes";
  RectangleRendererBindingId2[RectangleRendererBindingId2["LayoutInfoUniform"] = 1] = "LayoutInfoUniform";
  RectangleRendererBindingId2[RectangleRendererBindingId2["ScrollOffset"] = 2] = "ScrollOffset";
})(RectangleRendererBindingId || (RectangleRendererBindingId = {}));
var $L7 = (
  /*wgsl*/
  `

struct Vertex {
	@location(0) position: vec2f,
};

struct LayoutInfo {
	canvasDims: vec2f,
	viewportOffset: vec2f,
	viewportDims: vec2f,
}

struct ScrollOffset {
	offset: vec2f,
}

struct Shape {
	position: vec2f,
	size: vec2f,
	color: vec4f,
};

struct VSOutput {
	@builtin(position) position: vec4f,
	@location(1)       color:    vec4f,
};

// Uniforms
@group(0) @binding(${1}) var<uniform>       layoutInfo:      LayoutInfo;

// Storage buffers
@group(0) @binding(${0})            var<storage, read> shapes:          array<Shape>;
@group(0) @binding(${2})      var<uniform>       scrollOffset:    ScrollOffset;

@vertex fn vs(
	vert: Vertex,
	@builtin(instance_index) instanceIndex: u32,
	@builtin(vertex_index) vertexIndex : u32
) -> VSOutput {
	let shape = shapes[instanceIndex];

	var vsOut: VSOutput;
	vsOut.position = vec4f(
		(
			// Top left corner
			vec2f(-1,  1) +
			// Convert pixel position to clipspace
			vec2f( 2, -2) / layoutInfo.canvasDims *
			// Shape position and size
			(layoutInfo.viewportOffset - scrollOffset.offset + shape.position + vert.position * shape.size)
		),
		0.0,
		1.0
	);
	vsOut.color = shape.color;
	return vsOut;
}

@fragment fn fs(vsOut: VSOutput) -> @location(0) vec4f {
	return vsOut.color;
}
`
);

// out-build/vs/editor/browser/gpu/rectangleRenderer.js
var $M7 = class extends $D5 {
  constructor(C, D, F, device) {
    super();
    this.C = C;
    this.D = D;
    this.F = F;
    this.n = this.B(new $4c());
    this.t = false;
    this.z = this.B($K7([
      { name: "x" },
      { name: "y" },
      { name: "width" },
      { name: "height" },
      { name: "red" },
      { name: "green" },
      { name: "blue" },
      { name: "alpha" }
    ], 32));
    this.C.addEventHandler(this);
    this.G(device);
  }
  async G(device) {
    this.a = await device;
    if (this.q.isDisposed) {
      return;
    }
    const presentationFormat = navigator.gpu.getPreferredCanvasFormat();
    this.F.configure({
      device: this.a,
      format: presentationFormat,
      alphaMode: "premultiplied"
    });
    this.c = {
      view: null,
      // Will be filled at render time
      loadOp: "load",
      storeOp: "store"
    };
    this.b = {
      label: "Monaco rectangle renderer render pass",
      colorAttachments: [this.c]
    };
    let layoutInfoUniformBuffer;
    {
      let Info;
      (function(Info2) {
        Info2[Info2["FloatsPerEntry"] = 6] = "FloatsPerEntry";
        Info2[Info2["BytesPerEntry"] = 24] = "BytesPerEntry";
        Info2[Info2["Offset_CanvasWidth____"] = 0] = "Offset_CanvasWidth____";
        Info2[Info2["Offset_CanvasHeight___"] = 1] = "Offset_CanvasHeight___";
        Info2[Info2["Offset_ViewportOffsetX"] = 2] = "Offset_ViewportOffsetX";
        Info2[Info2["Offset_ViewportOffsetY"] = 3] = "Offset_ViewportOffsetY";
        Info2[Info2["Offset_ViewportWidth__"] = 4] = "Offset_ViewportWidth__";
        Info2[Info2["Offset_ViewportHeight_"] = 5] = "Offset_ViewportHeight_";
      })(Info || (Info = {}));
      const bufferValues = new Float32Array(
        6
        /* Info.FloatsPerEntry */
      );
      const updateBufferValues = (canvasDevicePixelWidth = this.D.width, canvasDevicePixelHeight = this.D.height) => {
        bufferValues[
          0
          /* Info.Offset_CanvasWidth____ */
        ] = canvasDevicePixelWidth;
        bufferValues[
          1
          /* Info.Offset_CanvasHeight___ */
        ] = canvasDevicePixelHeight;
        bufferValues[
          2
          /* Info.Offset_ViewportOffsetX */
        ] = Math.ceil(this.C.configuration.options.get(
          151
          /* EditorOption.layoutInfo */
        ).contentLeft * $Qj().devicePixelRatio);
        bufferValues[
          3
          /* Info.Offset_ViewportOffsetY */
        ] = 0;
        bufferValues[
          4
          /* Info.Offset_ViewportWidth__ */
        ] = bufferValues[
          0
          /* Info.Offset_CanvasWidth____ */
        ] - bufferValues[
          2
          /* Info.Offset_ViewportOffsetX */
        ];
        bufferValues[
          5
          /* Info.Offset_ViewportHeight_ */
        ] = bufferValues[
          1
          /* Info.Offset_CanvasHeight___ */
        ] - bufferValues[
          3
          /* Info.Offset_ViewportOffsetY */
        ];
        return bufferValues;
      };
      layoutInfoUniformBuffer = this.B(GPULifecycle.createBuffer(this.a, {
        label: "Monaco rectangle renderer uniform buffer",
        size: 24,
        usage: GPUBufferUsage.UNIFORM | GPUBufferUsage.COPY_DST
      }, () => updateBufferValues())).object;
      this.B($A7(this.D, $Qj(), (w, h3) => {
        this.a.queue.writeBuffer(layoutInfoUniformBuffer, 0, updateBufferValues(w, h3));
      }));
    }
    const scrollOffsetBufferSize = 2;
    this.r = this.B(GPULifecycle.createBuffer(this.a, {
      label: "Monaco rectangle renderer scroll offset buffer",
      size: scrollOffsetBufferSize * Float32Array.BYTES_PER_ELEMENT,
      usage: GPUBufferUsage.UNIFORM | GPUBufferUsage.COPY_DST
    })).object;
    this.s = new Float32Array(scrollOffsetBufferSize);
    const createShapeBindBuffer = () => {
      return GPULifecycle.createBuffer(this.a, {
        label: "Monaco rectangle renderer shape buffer",
        size: this.z.buffer.byteLength,
        usage: GPUBufferUsage.STORAGE | GPUBufferUsage.COPY_DST
      });
    };
    this.n.value = createShapeBindBuffer();
    this.B(Event2.runAndSubscribe(this.z.onDidChangeBuffer, () => {
      this.n.value = createShapeBindBuffer();
      if (this.g) {
        this.H(this.g, layoutInfoUniformBuffer);
      }
    }));
    this.j = this.B(GPULifecycle.createBuffer(this.a, {
      label: "Monaco rectangle renderer vertex buffer",
      size: $y7.byteLength,
      usage: GPUBufferUsage.VERTEX | GPUBufferUsage.COPY_DST
    }, $y7)).object;
    const module2 = this.a.createShaderModule({
      label: "Monaco rectangle renderer shader module",
      code: $L7
    });
    this.g = this.a.createRenderPipeline({
      label: "Monaco rectangle renderer render pipeline",
      layout: "auto",
      vertex: {
        module: module2,
        buffers: [
          {
            arrayStride: 2 * Float32Array.BYTES_PER_ELEMENT,
            // 2 floats, 4 bytes each
            attributes: [
              { shaderLocation: 0, offset: 0, format: "float32x2" }
              // position
            ]
          }
        ]
      },
      fragment: {
        module: module2,
        targets: [
          {
            format: presentationFormat,
            blend: {
              color: {
                srcFactor: "src-alpha",
                dstFactor: "one-minus-src-alpha"
              },
              alpha: {
                srcFactor: "src-alpha",
                dstFactor: "one-minus-src-alpha"
              }
            }
          }
        ]
      }
    });
    this.H(this.g, layoutInfoUniformBuffer);
    this.t = true;
  }
  H(pipeline, layoutInfoUniformBuffer) {
    this.f = this.a.createBindGroup({
      label: "Monaco rectangle renderer bind group",
      layout: pipeline.getBindGroupLayout(0),
      entries: [
        { binding: 0, resource: { buffer: this.n.value.object } },
        { binding: 1, resource: { buffer: layoutInfoUniformBuffer } },
        { binding: 2, resource: { buffer: this.r } }
      ]
    });
  }
  register(x, y, width2, height, red, green, blue, alpha) {
    return this.z.createEntry({ x, y, width: width2, height, red, green, blue, alpha });
  }
  // #region Event handlers
  onScrollChanged(e) {
    if (this.a) {
      const dpr = $Qj().devicePixelRatio;
      this.s[0] = this.C.viewLayout.getCurrentScrollLeft() * dpr;
      this.s[1] = this.C.viewLayout.getCurrentScrollTop() * dpr;
      this.a.queue.writeBuffer(this.r, 0, this.s);
    }
    return true;
  }
  // #endregion
  I() {
    if (!this.a) {
      return;
    }
    const shapes = this.z;
    if (shapes.dirtyTracker.isDirty) {
      this.a.queue.writeBuffer(this.n.value.object, 0, shapes.buffer, shapes.dirtyTracker.dataOffset, shapes.dirtyTracker.dirtySize * shapes.view.BYTES_PER_ELEMENT);
      shapes.dirtyTracker.clear();
    }
  }
  draw(viewportData) {
    if (!this.t) {
      return;
    }
    this.I();
    const encoder = this.a.createCommandEncoder({ label: "Monaco rectangle renderer command encoder" });
    this.c.view = this.F.getCurrentTexture().createView();
    const pass = encoder.beginRenderPass(this.b);
    pass.setPipeline(this.g);
    pass.setVertexBuffer(0, this.j);
    pass.setBindGroup(0, this.f);
    pass.draw($y7.length / 2, this.z.entryCount);
    pass.end();
    const commandBuffer = encoder.finish();
    this.a.queue.submit([commandBuffer]);
  }
};

// out-build/vs/editor/browser/gpu/decorationCssRuleExtractor.js
var $N7 = class extends $3c {
  constructor() {
    super();
    this.c = /* @__PURE__ */ new Map();
    this.a = $("div.monaco-decoration-css-rule-extractor");
    this.b = $("span");
    this.a.appendChild(this.b);
    this.B($1c(() => this.a.remove()));
  }
  getStyleRules(canvas, decorationClassName) {
    const existing = this.c.get(decorationClassName);
    if (existing) {
      return existing;
    }
    this.b.className = decorationClassName;
    canvas.appendChild(this.a);
    const rules = this.f(decorationClassName);
    this.c.set(decorationClassName, rules);
    canvas.removeChild(this.a);
    return rules;
  }
  f(className) {
    const rules = [];
    const doc = $Pj();
    const stylesheets = [...doc.styleSheets];
    for (let i2 = 0; i2 < stylesheets.length; i2++) {
      const stylesheet = stylesheets[i2];
      for (const rule of stylesheet.cssRules) {
        if (rule instanceof CSSImportRule) {
          if (rule.styleSheet) {
            stylesheets.push(rule.styleSheet);
          }
        } else if (rule instanceof CSSStyleRule) {
          const searchTerm = `.${className}`;
          const index = rule.selectorText.indexOf(searchTerm);
          if (index !== -1) {
            const endOfResult = index + searchTerm.length;
            if (rule.selectorText.length === endOfResult || rule.selectorText.substring(endOfResult, endOfResult + 1).match(/[ :]/)) {
              rules.push(rule);
            }
          }
        }
      }
    }
    return rules;
  }
};

// out-build/vs/editor/browser/gpu/viewGpuContext.js
var $O7_1;
var GpuRenderLimits;
(function(GpuRenderLimits2) {
  GpuRenderLimits2[GpuRenderLimits2["maxGpuLines"] = 3e3] = "maxGpuLines";
  GpuRenderLimits2[GpuRenderLimits2["maxGpuCols"] = 200] = "maxGpuCols";
})(GpuRenderLimits || (GpuRenderLimits = {}));
var $O7 = class $O72 extends $3c {
  static {
    $O7_1 = this;
  }
  static {
    this.a = new $N7();
  }
  static get decorationCssRuleExtractor() {
    return $O7_1.a;
  }
  /**
   * The shared texture atlas to use across all views.
   *
   * @throws if called before the GPU device is resolved
   */
  static get atlas() {
    if (!$O7_1.b) {
      throw new $vb("Cannot call ViewGpuContext.textureAtlas before device is resolved");
    }
    return $O7_1.b;
  }
  /**
   * The shared texture atlas to use across all views. This is a convenience alias for
   * {@link $O7.atlas}.
   *
   * @throws if called before the GPU device is resolved
   */
  get atlas() {
    return $O7_1.atlas;
  }
  constructor(context, c, f, g) {
    super();
    this.c = c;
    this.f = f;
    this.g = g;
    this.maxGpuLines = 3e3;
    this.maxGpuCols = 200;
    this.canvas = $oZ(document.createElement("canvas"));
    this.canvas.setClassName("editorCanvas");
    this.B(Event2.runAndSubscribe(g.onDidChangeConfiguration, (e) => {
      if (!e || e.affectsConfiguration("editor.scrollbar.verticalScrollbarSize")) {
        const verticalScrollbarSize = g.getValue("editor").scrollbar?.verticalScrollbarSize ?? 14;
        this.canvas.domNode.style.boxSizing = "border-box";
        this.canvas.domNode.style.paddingRight = `${verticalScrollbarSize}px`;
      }
    }));
    this.ctx = $z7(this.canvas.domNode.getContext("webgpu"));
    this.device = GPULifecycle.requestDevice((message) => {
      const choices = [{
        label: localize(191, null),
        run: () => this.g.updateValue("editor.experimentalGpuAcceleration", "off")
      }];
      this.f.prompt(Severity2.Warning, message, choices);
    }).then((ref) => this.B(ref).object);
    this.device.then((device) => {
      if (!$O7_1.b) {
        $O7_1.b = this.c.createInstance($I7, device.limits.maxTextureDimension2D, void 0);
      }
    });
    this.rectangleRenderer = this.c.createInstance($M7, context, this.canvas.domNode, this.ctx, this.device);
    const dprObs = $he(this, $Qj().devicePixelRatio);
    this.B($_i($Qj(), "resize", () => {
      dprObs.set($Qj().devicePixelRatio, void 0);
    }));
    this.devicePixelRatio = dprObs;
    this.B($Wd(this.devicePixelRatio, () => $O7_1.atlas?.clear()));
    const canvasDevicePixelDimensions = $he(this, { width: this.canvas.domNode.width, height: this.canvas.domNode.height });
    this.B($A7(this.canvas.domNode, $Qj(), (width2, height) => {
      this.canvas.domNode.width = width2;
      this.canvas.domNode.height = height;
      canvasDevicePixelDimensions.set({ width: width2, height }, void 0);
    }));
    this.canvasDevicePixelDimensions = canvasDevicePixelDimensions;
  }
  /**
   * This method determines which lines can be and are allowed to be rendered using the GPU
   * renderer. Eventually this should trend all lines, except maybe exceptional cases like
   * decorations that use class names.
   */
  canRender(options3, viewportData, lineNumber) {
    const data = viewportData.getViewLineRenderingData(lineNumber);
    if (data.containsRTL || data.maxColumn > 200 || data.continuesWithWrappedLine || lineNumber >= 3e3) {
      return false;
    }
    if (data.inlineDecorations.length > 0) {
      let supported = true;
      for (const decoration3 of data.inlineDecorations) {
        if (decoration3.type !== 0) {
          supported = false;
          break;
        }
        const styleRules = $O7_1.a.getStyleRules(this.canvas.domNode, decoration3.inlineClassName);
        supported &&= styleRules.every((rule) => {
          if (rule.selectorText.includes(":")) {
            return false;
          }
          for (const r2 of rule.style) {
            if (!gpuSupportedDecorationCssRules.includes(r2)) {
              return false;
            }
          }
          return true;
        });
        if (!supported) {
          break;
        }
      }
      return supported;
    }
    return true;
  }
  /**
   * Like {@link canRender} but returns detailed information about why the line cannot be rendered.
   */
  canRenderDetailed(options3, viewportData, lineNumber) {
    const data = viewportData.getViewLineRenderingData(lineNumber);
    const reasons = [];
    if (data.containsRTL) {
      reasons.push("containsRTL");
    }
    if (data.maxColumn > 200) {
      reasons.push("maxColumn > maxGpuCols");
    }
    if (data.continuesWithWrappedLine) {
      reasons.push("continuesWithWrappedLine");
    }
    if (data.inlineDecorations.length > 0) {
      let supported = true;
      const problemTypes = [];
      const problemSelectors = [];
      const problemRules = [];
      for (const decoration3 of data.inlineDecorations) {
        if (decoration3.type !== 0) {
          problemTypes.push(decoration3.type);
          supported = false;
          continue;
        }
        const styleRules = $O7_1.a.getStyleRules(this.canvas.domNode, decoration3.inlineClassName);
        supported &&= styleRules.every((rule) => {
          if (rule.selectorText.includes(":")) {
            problemSelectors.push(rule.selectorText);
            return false;
          }
          for (const r2 of rule.style) {
            if (!gpuSupportedDecorationCssRules.includes(r2)) {
              problemRules.push(r2);
              return false;
            }
          }
          return true;
        });
        if (!supported) {
          continue;
        }
      }
      if (problemTypes.length > 0) {
        reasons.push(`inlineDecorations with unsupported types (${problemTypes.map((e) => `\`${e}\``).join(", ")})`);
      }
      if (problemRules.length > 0) {
        reasons.push(`inlineDecorations with unsupported CSS rules (${problemRules.map((e) => `\`${e}\``).join(", ")})`);
      }
      if (problemSelectors.length > 0) {
        reasons.push(`inlineDecorations with unsupported CSS selectors (${problemSelectors.map((e) => `\`${e}\``).join(", ")})`);
      }
    }
    if (lineNumber >= 3e3) {
      reasons.push("lineNumber >= maxGpuLines");
    }
    return reasons;
  }
};
$O7 = $O7_1 = __decorate([
  __param(1, $Pk),
  __param(2, $PJ),
  __param(3, $kl)
], $O7);
var gpuSupportedDecorationCssRules = [
  "color"
];

// out-build/vs/editor/browser/gpu/fullFileRenderStrategy.wgsl.js
var $S7 = (
  /*wgsl*/
  `
struct GlyphInfo {
	position: vec2f,
	size: vec2f,
	origin: vec2f,
};

struct Vertex {
	@location(0) position: vec2f,
};

struct Cell {
	position: vec2f,
	unused1: vec2f,
	glyphIndex: f32,
	textureIndex: f32
};

struct LayoutInfo {
	canvasDims: vec2f,
	viewportOffset: vec2f,
	viewportDims: vec2f,
}

struct ScrollOffset {
	offset: vec2f
}

struct VSOutput {
	@builtin(position) position:   vec4f,
	@location(1)       layerIndex: f32,
	@location(0)       texcoord:   vec2f,
};

// Uniforms
@group(0) @binding(${4})       var<uniform>       layoutInfo:      LayoutInfo;
@group(0) @binding(${5})  var<uniform>       atlasDims:       vec2f;
@group(0) @binding(${6})            var<uniform>       scrollOffset:    ScrollOffset;

// Storage buffers
@group(0) @binding(${0})               var<storage, read> glyphInfo:       array<array<GlyphInfo, ${$H7.maximumGlyphCount}>, ${$I7.maximumPageCount}>;
@group(0) @binding(${1})                   var<storage, read> cells:           array<Cell>;

@vertex fn vs(
	vert: Vertex,
	@builtin(instance_index) instanceIndex: u32,
	@builtin(vertex_index) vertexIndex : u32
) -> VSOutput {
	let cell = cells[instanceIndex];
	var glyph = glyphInfo[u32(cell.textureIndex)][u32(cell.glyphIndex)];

	var vsOut: VSOutput;
	// Multiple vert.position by 2,-2 to get it into clipspace which ranged from -1 to 1
	vsOut.position = vec4f(
		// Make everything relative to top left instead of center
		vec2f(-1, 1) +
		((vert.position * vec2f(2, -2)) / layoutInfo.canvasDims) * glyph.size +
		((cell.position * vec2f(2, -2)) / layoutInfo.canvasDims) +
		((glyph.origin * vec2f(2, -2)) / layoutInfo.canvasDims) +
		(((layoutInfo.viewportOffset - scrollOffset.offset * vec2(1, -1)) * 2) / layoutInfo.canvasDims),
		0.0,
		1.0
	);

	vsOut.layerIndex = cell.textureIndex;
	// Textures are flipped from natural direction on the y-axis, so flip it back
	vsOut.texcoord = vert.position;
	vsOut.texcoord = (
		// Glyph offset (0-1)
		(glyph.position / atlasDims) +
		// Glyph coordinate (0-1)
		(vsOut.texcoord * (glyph.size / atlasDims))
	);

	return vsOut;
}

@group(0) @binding(${2}) var ourSampler: sampler;
@group(0) @binding(${3})        var ourTexture: texture_2d_array<f32>;

@fragment fn fs(vsOut: VSOutput) -> @location(0) vec4f {
	return textureSample(ourTexture, ourSampler, vsOut.texcoord, u32(vsOut.layerIndex));
}
`
);

// out-build/vs/editor/browser/gpu/fullFileRenderStrategy.js
var Constants7;
(function(Constants27) {
  Constants27[Constants27["IndicesPerCell"] = 6] = "IndicesPerCell";
})(Constants7 || (Constants7 = {}));
var CellBufferInfo;
(function(CellBufferInfo2) {
  CellBufferInfo2[CellBufferInfo2["FloatsPerEntry"] = 6] = "FloatsPerEntry";
  CellBufferInfo2[CellBufferInfo2["BytesPerEntry"] = 24] = "BytesPerEntry";
  CellBufferInfo2[CellBufferInfo2["Offset_X"] = 0] = "Offset_X";
  CellBufferInfo2[CellBufferInfo2["Offset_Y"] = 1] = "Offset_Y";
  CellBufferInfo2[CellBufferInfo2["Offset_Unused1"] = 2] = "Offset_Unused1";
  CellBufferInfo2[CellBufferInfo2["Offset_Unused2"] = 3] = "Offset_Unused2";
  CellBufferInfo2[CellBufferInfo2["GlyphIndex"] = 4] = "GlyphIndex";
  CellBufferInfo2[CellBufferInfo2["TextureIndex"] = 5] = "TextureIndex";
})(CellBufferInfo || (CellBufferInfo = {}));
var $T7 = class extends $D5 {
  get bindGroupEntries() {
    return [
      { binding: 1, resource: { buffer: this.b } },
      { binding: 6, resource: { buffer: this.n } }
    ];
  }
  constructor(z, C, D) {
    super();
    this.z = z;
    this.C = C;
    this.D = D;
    this.wgsl = $S7;
    this.f = 0;
    this.g = [/* @__PURE__ */ new Set(), /* @__PURE__ */ new Set()];
    this.h = 0;
    this.j = 0;
    this.t = false;
    this.w = [[], []];
    this.z.addEventHandler(this);
    const fontFamily = this.z.configuration.options.get(
      51
      /* EditorOption.fontFamily */
    );
    const fontSize = this.z.configuration.options.get(
      54
      /* EditorOption.fontSize */
    );
    this.a = this.B(new $5c(new $B7(fontSize, fontFamily, this.C.devicePixelRatio.get())));
    const bufferSize = this.C.maxGpuLines * this.C.maxGpuCols * 6 * Float32Array.BYTES_PER_ELEMENT;
    this.b = this.B(GPULifecycle.createBuffer(this.D, {
      label: "Monaco full file cell buffer",
      size: bufferSize,
      usage: GPUBufferUsage.STORAGE | GPUBufferUsage.COPY_DST
    })).object;
    this.c = [
      new ArrayBuffer(bufferSize),
      new ArrayBuffer(bufferSize)
    ];
    const scrollOffsetBufferSize = 2;
    this.n = this.B(GPULifecycle.createBuffer(this.D, {
      label: "Monaco scroll offset buffer",
      size: scrollOffsetBufferSize * Float32Array.BYTES_PER_ELEMENT,
      usage: GPUBufferUsage.UNIFORM | GPUBufferUsage.COPY_DST
    })).object;
    this.s = new Float32Array(scrollOffsetBufferSize);
  }
  // #region Event handlers
  // The primary job of these handlers is to:
  // 1. Invalidate the up to date line cache, which will cause the line to be re-rendered when
  //    it's _within the viewport_.
  // 2. Pass relevant events on to the render function so it can force certain line ranges to be
  //    re-rendered even if they're not in the viewport. For example when a view zone is added,
  //    there are lines that used to be visible but are no longer, so those ranges must be
  //    cleared and uploaded to the GPU.
  onConfigurationChanged(e) {
    this.F();
    this.I(e);
    const fontFamily = this.z.configuration.options.get(
      51
      /* EditorOption.fontFamily */
    );
    const fontSize = this.z.configuration.options.get(
      54
      /* EditorOption.fontSize */
    );
    const devicePixelRatio = this.C.devicePixelRatio.get();
    if (this.a.value.fontFamily !== fontFamily || this.a.value.fontSize !== fontSize || this.a.value.devicePixelRatio !== devicePixelRatio) {
      this.a.value = new $B7(fontSize, fontFamily, devicePixelRatio);
    }
    return true;
  }
  onDecorationsChanged(e) {
    this.F();
    return true;
  }
  onTokensChanged(e) {
    for (const range of e.ranges) {
      this.H(range.fromLineNumber, range.toLineNumber);
    }
    return true;
  }
  onLinesDeleted(e) {
    this.G(e.fromLineNumber);
    this.I(e);
    return true;
  }
  onLinesInserted(e) {
    this.G(e.fromLineNumber);
    return true;
  }
  onLinesChanged(e) {
    this.H(e.fromLineNumber, e.fromLineNumber + e.count);
    return true;
  }
  onScrollChanged(e) {
    const dpr = $Qj().devicePixelRatio;
    this.s[0] = (e?.scrollLeft ?? this.z.viewLayout.getCurrentScrollLeft()) * dpr;
    this.s[1] = (e?.scrollTop ?? this.z.viewLayout.getCurrentScrollTop()) * dpr;
    this.D.queue.writeBuffer(this.n, 0, this.s);
    return true;
  }
  onThemeChanged(e) {
    this.F();
    return true;
  }
  onLineMappingChanged(e) {
    this.F();
    this.I(e);
    return true;
  }
  onZonesChanged(e) {
    this.F();
    this.I(e);
    return true;
  }
  // #endregion
  F() {
    this.g[0].clear();
    this.g[1].clear();
  }
  G(lineNumber) {
    for (const i2 of [0, 1]) {
      const upToDateLines = this.g[i2];
      for (const upToDateLine of upToDateLines) {
        if (upToDateLine >= lineNumber) {
          upToDateLines.delete(upToDateLine);
        }
      }
    }
  }
  H(fromLineNumber, toLineNumber) {
    for (let i2 = fromLineNumber; i2 <= toLineNumber; i2++) {
      this.g[0].delete(i2);
      this.g[1].delete(i2);
    }
  }
  reset() {
    this.F();
    for (const bufferIndex of [0, 1]) {
      const buffer = new Float32Array(this.c[bufferIndex]);
      buffer.fill(0, 0, buffer.length);
      this.D.queue.writeBuffer(this.b, 0, buffer.buffer, 0, buffer.byteLength);
    }
    this.j = 0;
  }
  update(viewportData, viewLineOptions) {
    let chars = "";
    let y = 0;
    let x = 0;
    let absoluteOffsetX = 0;
    let absoluteOffsetY = 0;
    let xOffset = 0;
    let glyph;
    let cellIndex = 0;
    let tokenStartIndex = 0;
    let tokenEndIndex = 0;
    let tokenMetadata = 0;
    let charMetadata = 0;
    let lineData;
    let decoration3;
    let content = "";
    let fillStartIndex = 0;
    let fillEndIndex = 0;
    let tokens;
    const dpr = $Qj().devicePixelRatio;
    if (!this.t) {
      this.onScrollChanged();
      this.t = true;
    }
    const cellBuffer = new Float32Array(this.c[this.f]);
    const lineIndexCount = this.C.maxGpuCols * 6;
    const upToDateLines = this.g[this.f];
    let dirtyLineStart = Number.MAX_SAFE_INTEGER;
    let dirtyLineEnd = 0;
    const queuedBufferUpdates = this.w[this.f];
    while (queuedBufferUpdates.length) {
      const e = queuedBufferUpdates.shift();
      switch (e.type) {
        case 2:
        case 8:
        case 17: {
          cellBuffer.fill(0);
          dirtyLineStart = 1;
          dirtyLineEnd = Math.max(dirtyLineEnd, this.j);
          this.j = 0;
          break;
        }
        case 10: {
          const deletedLineContentStartIndex = (e.fromLineNumber - 1) * this.C.maxGpuCols * 6;
          const deletedLineContentEndIndex = e.toLineNumber * this.C.maxGpuCols * 6;
          const nullContentStartIndex = (this.j - (e.toLineNumber - e.fromLineNumber + 1)) * this.C.maxGpuCols * 6;
          cellBuffer.set(cellBuffer.subarray(deletedLineContentEndIndex), deletedLineContentStartIndex);
          cellBuffer.fill(0, nullContentStartIndex);
          dirtyLineStart = Math.min(dirtyLineStart, e.fromLineNumber);
          dirtyLineEnd = Math.max(dirtyLineEnd, this.j);
          this.j -= e.toLineNumber - e.fromLineNumber + 1;
          break;
        }
      }
    }
    for (y = viewportData.startLineNumber; y <= viewportData.endLineNumber; y++) {
      if (!this.C.canRender(viewLineOptions, viewportData, y)) {
        fillStartIndex = (y - 1) * this.C.maxGpuCols * 6;
        fillEndIndex = y * this.C.maxGpuCols * 6;
        cellBuffer.fill(0, fillStartIndex, fillEndIndex);
        dirtyLineStart = Math.min(dirtyLineStart, y);
        dirtyLineEnd = Math.max(dirtyLineEnd, y);
        continue;
      }
      if (upToDateLines.has(y)) {
        continue;
      }
      dirtyLineStart = Math.min(dirtyLineStart, y);
      dirtyLineEnd = Math.max(dirtyLineEnd, y);
      lineData = viewportData.getViewLineRenderingData(y);
      content = lineData.content;
      xOffset = 0;
      tokens = lineData.tokens;
      tokenStartIndex = lineData.minColumn - 1;
      tokenEndIndex = 0;
      for (let tokenIndex = 0, tokensLen = tokens.getCount(); tokenIndex < tokensLen; tokenIndex++) {
        tokenEndIndex = tokens.getEndOffset(tokenIndex);
        if (tokenEndIndex <= tokenStartIndex) {
          continue;
        }
        tokenMetadata = tokens.getMetadata(tokenIndex);
        for (x = tokenStartIndex; x < tokenEndIndex; x++) {
          if (x > this.C.maxGpuCols) {
            break;
          }
          chars = content.charAt(x);
          charMetadata = 0;
          for (decoration3 of lineData.inlineDecorations) {
            if (y < decoration3.range.startLineNumber || y > decoration3.range.endLineNumber || y === decoration3.range.startLineNumber && x < decoration3.range.startColumn - 1 || y === decoration3.range.endLineNumber && x >= decoration3.range.endColumn - 1) {
              continue;
            }
            const rules = $O7.decorationCssRuleExtractor.getStyleRules(this.C.canvas.domNode, decoration3.inlineClassName);
            for (const rule of rules) {
              for (const r2 of rule.style) {
                const value = rule.styleMap.get(r2)?.toString() ?? "";
                switch (r2) {
                  case "color": {
                    const parsedColor = $Vn.Format.CSS.parse(value);
                    if (!parsedColor) {
                      throw new $vb("Invalid color format " + value);
                    }
                    charMetadata = parsedColor.toNumber24Bit();
                    break;
                  }
                  default:
                    throw new $vb("Unexpected inline decoration style");
                }
              }
            }
          }
          if (chars === " " || chars === "	") {
            cellIndex = ((y - 1) * this.C.maxGpuCols + x) * 6;
            cellBuffer.fill(
              0,
              cellIndex,
              cellIndex + 6
              /* CellBufferInfo.FloatsPerEntry */
            );
            if (chars === "	") {
              xOffset = $cF.nextRenderTabStop(x + xOffset, lineData.tabSize) - x - 1;
            }
            continue;
          }
          glyph = this.C.atlas.getGlyph(this.a.value, chars, tokenMetadata, charMetadata);
          absoluteOffsetX = Math.round((x + xOffset) * viewLineOptions.spaceWidth * dpr);
          absoluteOffsetY = Math.round(
            // Top of layout box (includes line height)
            viewportData.relativeVerticalOffset[y - viewportData.startLineNumber] * dpr + // Delta from top of layout box (includes line height) to top of the inline box (no line height)
            Math.floor((viewportData.lineHeight * dpr - (glyph.fontBoundingBoxAscent + glyph.fontBoundingBoxDescent)) / 2) + // Delta from top of inline box (no line height) to top of glyph origin. If the glyph was drawn
            // with a top baseline for example, this ends up drawing the glyph correctly using the alphabetical
            // baseline.
            glyph.fontBoundingBoxAscent
          );
          cellIndex = ((y - 1) * this.C.maxGpuCols + x) * 6;
          cellBuffer[
            cellIndex + 0
            /* CellBufferInfo.Offset_X */
          ] = absoluteOffsetX;
          cellBuffer[
            cellIndex + 1
            /* CellBufferInfo.Offset_Y */
          ] = absoluteOffsetY;
          cellBuffer[
            cellIndex + 4
            /* CellBufferInfo.GlyphIndex */
          ] = glyph.glyphIndex;
          cellBuffer[
            cellIndex + 5
            /* CellBufferInfo.TextureIndex */
          ] = glyph.pageIndex;
        }
        tokenStartIndex = tokenEndIndex;
      }
      fillStartIndex = ((y - 1) * this.C.maxGpuCols + tokenEndIndex) * 6;
      fillEndIndex = y * this.C.maxGpuCols * 6;
      cellBuffer.fill(0, fillStartIndex, fillEndIndex);
      upToDateLines.add(y);
    }
    const visibleObjectCount = (viewportData.endLineNumber - viewportData.startLineNumber + 1) * lineIndexCount;
    if (dirtyLineStart <= dirtyLineEnd) {
      this.D.queue.writeBuffer(this.b, (dirtyLineStart - 1) * lineIndexCount * Float32Array.BYTES_PER_ELEMENT, cellBuffer.buffer, (dirtyLineStart - 1) * lineIndexCount * Float32Array.BYTES_PER_ELEMENT, (dirtyLineEnd - dirtyLineStart + 1) * lineIndexCount * Float32Array.BYTES_PER_ELEMENT);
    }
    this.j = Math.max(this.j, dirtyLineEnd);
    this.f = this.f ? 0 : 1;
    this.h = visibleObjectCount;
    return visibleObjectCount;
  }
  draw(pass, viewportData) {
    if (this.h <= 0) {
      throw new $vb("Attempt to draw 0 objects");
    }
    pass.draw($y7.length / 2, this.h, void 0, (viewportData.startLineNumber - 1) * this.C.maxGpuCols);
  }
  /**
   * Queue updates that need to happen on the active buffer, not just the cache. This will be
   * deferred to when the actual cell buffer is changed since the active buffer could be locked by
   * the GPU which would block the main thread.
   */
  I(e) {
    this.w[0].push(e);
    this.w[1].push(e);
  }
};

// out-build/vs/editor/browser/viewParts/viewLinesGpu/viewLinesGpu.js
var GlyphStorageBufferInfo;
(function(GlyphStorageBufferInfo2) {
  GlyphStorageBufferInfo2[GlyphStorageBufferInfo2["FloatsPerEntry"] = 6] = "FloatsPerEntry";
  GlyphStorageBufferInfo2[GlyphStorageBufferInfo2["BytesPerEntry"] = 24] = "BytesPerEntry";
  GlyphStorageBufferInfo2[GlyphStorageBufferInfo2["Offset_TexturePosition"] = 0] = "Offset_TexturePosition";
  GlyphStorageBufferInfo2[GlyphStorageBufferInfo2["Offset_TextureSize"] = 2] = "Offset_TextureSize";
  GlyphStorageBufferInfo2[GlyphStorageBufferInfo2["Offset_OriginPosition"] = 4] = "Offset_OriginPosition";
})(GlyphStorageBufferInfo || (GlyphStorageBufferInfo = {}));
var $U7 = class $U72 extends $f7 {
  constructor(context, L, M, N) {
    super(context);
    this.L = L;
    this.M = M;
    this.N = N;
    this.G = [];
    this.H = false;
    this.J = $he("contentLeft", 0);
    this.a = this.L.canvas.domNode;
    this.B($td((reader) => {
      this.L.canvasDevicePixelDimensions.read(reader);
      const lastViewportData = this.c;
      if (lastViewportData) {
        setTimeout(() => {
          if (lastViewportData === this.c) {
            this.renderText(lastViewportData);
          }
        });
      }
    }));
    this.initWebgpu();
  }
  async initWebgpu() {
    this.g = await this.L.device;
    if (this.q.isDisposed) {
      return;
    }
    const atlas = $O7.atlas;
    this.B(atlas.onDidDeleteGlyphs(() => {
      this.G.length = 0;
      this.G[0] = 0;
      this.G[1] = 0;
      this.I.reset();
    }));
    const presentationFormat = navigator.gpu.getPreferredCanvasFormat();
    this.L.ctx.configure({
      device: this.g,
      format: presentationFormat,
      alphaMode: "premultiplied"
    });
    this.n = {
      view: null,
      // Will be filled at render time
      loadOp: "load",
      storeOp: "store"
    };
    this.j = {
      label: "Monaco render pass",
      colorAttachments: [this.n]
    };
    let layoutInfoUniformBuffer;
    {
      let Info;
      (function(Info2) {
        Info2[Info2["FloatsPerEntry"] = 6] = "FloatsPerEntry";
        Info2[Info2["BytesPerEntry"] = 24] = "BytesPerEntry";
        Info2[Info2["Offset_CanvasWidth____"] = 0] = "Offset_CanvasWidth____";
        Info2[Info2["Offset_CanvasHeight___"] = 1] = "Offset_CanvasHeight___";
        Info2[Info2["Offset_ViewportOffsetX"] = 2] = "Offset_ViewportOffsetX";
        Info2[Info2["Offset_ViewportOffsetY"] = 3] = "Offset_ViewportOffsetY";
        Info2[Info2["Offset_ViewportWidth__"] = 4] = "Offset_ViewportWidth__";
        Info2[Info2["Offset_ViewportHeight_"] = 5] = "Offset_ViewportHeight_";
      })(Info || (Info = {}));
      const bufferValues = new Float32Array(
        6
        /* Info.FloatsPerEntry */
      );
      const updateBufferValues = (canvasDevicePixelWidth = this.a.width, canvasDevicePixelHeight = this.a.height) => {
        bufferValues[
          0
          /* Info.Offset_CanvasWidth____ */
        ] = canvasDevicePixelWidth;
        bufferValues[
          1
          /* Info.Offset_CanvasHeight___ */
        ] = canvasDevicePixelHeight;
        bufferValues[
          2
          /* Info.Offset_ViewportOffsetX */
        ] = Math.ceil(this._context.configuration.options.get(
          151
          /* EditorOption.layoutInfo */
        ).contentLeft * $Qj().devicePixelRatio);
        bufferValues[
          3
          /* Info.Offset_ViewportOffsetY */
        ] = 0;
        bufferValues[
          4
          /* Info.Offset_ViewportWidth__ */
        ] = bufferValues[
          0
          /* Info.Offset_CanvasWidth____ */
        ] - bufferValues[
          2
          /* Info.Offset_ViewportOffsetX */
        ];
        bufferValues[
          5
          /* Info.Offset_ViewportHeight_ */
        ] = bufferValues[
          1
          /* Info.Offset_CanvasHeight___ */
        ] - bufferValues[
          3
          /* Info.Offset_ViewportOffsetY */
        ];
        return bufferValues;
      };
      layoutInfoUniformBuffer = this.B(GPULifecycle.createBuffer(this.g, {
        label: "Monaco uniform buffer",
        size: 24,
        usage: GPUBufferUsage.UNIFORM | GPUBufferUsage.COPY_DST
      }, () => updateBufferValues())).object;
      this.B($Wd(this.L.canvasDevicePixelDimensions, ({ width: width2, height }) => {
        this.g.queue.writeBuffer(layoutInfoUniformBuffer, 0, updateBufferValues(width2, height));
      }));
      this.B($Wd(this.J, () => {
        this.g.queue.writeBuffer(layoutInfoUniformBuffer, 0, updateBufferValues());
      }));
    }
    let atlasInfoUniformBuffer;
    {
      let Info;
      (function(Info2) {
        Info2[Info2["FloatsPerEntry"] = 2] = "FloatsPerEntry";
        Info2[Info2["BytesPerEntry"] = 8] = "BytesPerEntry";
        Info2[Info2["Offset_Width_"] = 0] = "Offset_Width_";
        Info2[Info2["Offset_Height"] = 1] = "Offset_Height";
      })(Info || (Info = {}));
      atlasInfoUniformBuffer = this.B(GPULifecycle.createBuffer(this.g, {
        label: "Monaco atlas info uniform buffer",
        size: 8,
        usage: GPUBufferUsage.UNIFORM | GPUBufferUsage.COPY_DST
      }, () => {
        const values = new Float32Array(
          2
          /* Info.FloatsPerEntry */
        );
        values[
          0
          /* Info.Offset_Width_ */
        ] = atlas.pageSize;
        values[
          1
          /* Info.Offset_Height */
        ] = atlas.pageSize;
        return values;
      })).object;
    }
    this.I = this.B(this.M.createInstance($T7, this._context, this.L, this.g));
    this.D = this.B(GPULifecycle.createBuffer(this.g, {
      label: "Monaco glyph storage buffer",
      size: $I7.maximumPageCount * ($H7.maximumGlyphCount * 24),
      usage: GPUBufferUsage.STORAGE | GPUBufferUsage.COPY_DST
    })).object;
    this.G[0] = 0;
    this.G[1] = 0;
    this.F = this.B(GPULifecycle.createTexture(this.g, {
      label: "Monaco atlas texture",
      format: "rgba8unorm",
      size: { width: atlas.pageSize, height: atlas.pageSize, depthOrArrayLayers: $I7.maximumPageCount },
      dimension: "2d",
      usage: GPUTextureUsage.TEXTURE_BINDING | GPUTextureUsage.COPY_DST | GPUTextureUsage.RENDER_ATTACHMENT
    })).object;
    this.O();
    this.C = this.B(GPULifecycle.createBuffer(this.g, {
      label: "Monaco vertex buffer",
      size: $y7.byteLength,
      usage: GPUBufferUsage.VERTEX | GPUBufferUsage.COPY_DST
    }, $y7)).object;
    const module2 = this.g.createShaderModule({
      label: "Monaco shader module",
      code: this.I.wgsl
    });
    this.t = this.g.createRenderPipeline({
      label: "Monaco render pipeline",
      layout: "auto",
      vertex: {
        module: module2,
        buffers: [
          {
            arrayStride: 2 * Float32Array.BYTES_PER_ELEMENT,
            // 2 floats, 4 bytes each
            attributes: [
              { shaderLocation: 0, offset: 0, format: "float32x2" }
              // position
            ]
          }
        ]
      },
      fragment: {
        module: module2,
        targets: [
          {
            format: presentationFormat,
            blend: {
              color: {
                srcFactor: "src-alpha",
                dstFactor: "one-minus-src-alpha"
              },
              alpha: {
                srcFactor: "src-alpha",
                dstFactor: "one-minus-src-alpha"
              }
            }
          }
        ]
      }
    });
    this.s = this.g.createBindGroup({
      label: "Monaco bind group",
      layout: this.t.getBindGroupLayout(0),
      entries: [
        // TODO: Pass in generically as array?
        { binding: 0, resource: { buffer: this.D } },
        {
          binding: 2,
          resource: this.g.createSampler({
            label: "Monaco atlas sampler",
            magFilter: "nearest",
            minFilter: "nearest"
          })
        },
        { binding: 3, resource: this.F.createView() },
        { binding: 4, resource: { buffer: layoutInfoUniformBuffer } },
        { binding: 5, resource: { buffer: atlasInfoUniformBuffer } },
        ...this.I.bindGroupEntries
      ]
    });
    this.H = true;
    if (this.b) {
      for (const viewportData of this.b) {
        this.renderText(viewportData);
      }
      this.b = void 0;
    }
  }
  O() {
    for (const [layerIndex, page] of $O7.atlas.pages.entries()) {
      if (layerIndex >= $I7.maximumPageCount) {
        console.log(`Attempt to upload atlas page [${layerIndex}], only ${$I7.maximumPageCount} are supported currently`);
        continue;
      }
      if (page.version === this.G[layerIndex]) {
        continue;
      }
      this.N.trace("Updating atlas page[", layerIndex, "] from version ", this.G[layerIndex], " to version ", page.version);
      const entryCount = 6 * $H7.maximumGlyphCount;
      const values = new Float32Array(entryCount);
      let entryOffset = 0;
      for (const glyph of page.glyphs) {
        values[
          entryOffset + 0
          /* GlyphStorageBufferInfo.Offset_TexturePosition */
        ] = glyph.x;
        values[entryOffset + 0 + 1] = glyph.y;
        values[
          entryOffset + 2
          /* GlyphStorageBufferInfo.Offset_TextureSize */
        ] = glyph.w;
        values[entryOffset + 2 + 1] = glyph.h;
        values[
          entryOffset + 4
          /* GlyphStorageBufferInfo.Offset_OriginPosition */
        ] = glyph.originOffsetX;
        values[entryOffset + 4 + 1] = glyph.originOffsetY;
        entryOffset += 6;
      }
      if (entryOffset / 6 > $H7.maximumGlyphCount) {
        throw new Error(`Attempting to write more glyphs (${entryOffset / 6}) than the GPUBuffer can hold (${$H7.maximumGlyphCount})`);
      }
      this.g.queue.writeBuffer(this.D, layerIndex * 6 * $H7.maximumGlyphCount * Float32Array.BYTES_PER_ELEMENT, values, 0, 6 * $H7.maximumGlyphCount);
      if (page.usedArea.right - page.usedArea.left > 0 && page.usedArea.bottom - page.usedArea.top > 0) {
        this.g.queue.copyExternalImageToTexture({ source: page.source }, {
          texture: this.F,
          origin: {
            x: page.usedArea.left,
            y: page.usedArea.top,
            z: layerIndex
          }
        }, {
          width: page.usedArea.right - page.usedArea.left + 1,
          height: page.usedArea.bottom - page.usedArea.top + 1
        });
      }
      this.G[layerIndex] = page.version;
    }
  }
  prepareRender(ctx) {
    throw new $vb("Should not be called");
  }
  render(ctx) {
    throw new $vb("Should not be called");
  }
  // #region Event handlers
  // Since ViewLinesGpu currently coordinates rendering to the canvas, it must listen to all
  // changed events that any GPU part listens to. This is because any drawing to the canvas will
  // clear it for that frame, so all parts must be rendered every time.
  //
  // Additionally, since this is intrinsically linked to ViewLines, it must also listen to events
  // from that side. Luckily rendering is cheap, it's only when uploaded data changes does it
  // start to cost.
  onCursorStateChanged(e) {
    return true;
  }
  onDecorationsChanged(e) {
    return true;
  }
  onFlushed(e) {
    return true;
  }
  onLinesChanged(e) {
    return true;
  }
  onLinesDeleted(e) {
    return true;
  }
  onLinesInserted(e) {
    return true;
  }
  onLineMappingChanged(e) {
    return true;
  }
  onRevealRangeRequest(e) {
    return true;
  }
  onScrollChanged(e) {
    return true;
  }
  onThemeChanged(e) {
    return true;
  }
  onZonesChanged(e) {
    return true;
  }
  onConfigurationChanged(e) {
    this.J.set(this._context.configuration.options.get(
      151
      /* EditorOption.layoutInfo */
    ).contentLeft, void 0);
    return true;
  }
  // #endregion
  renderText(viewportData) {
    if (this.H) {
      return this.P(viewportData);
    } else {
      this.b = this.b ?? [];
      this.b.push(viewportData);
    }
  }
  P(viewportData) {
    this.L.rectangleRenderer.draw(viewportData);
    const options3 = new $x7(this._context.configuration, this._context.theme.type);
    const visibleObjectCount = this.I.update(viewportData, options3);
    this.O();
    const encoder = this.g.createCommandEncoder({ label: "Monaco command encoder" });
    this.n.view = this.L.ctx.getCurrentTexture().createView({ label: "Monaco canvas texture view" });
    const pass = encoder.beginRenderPass(this.j);
    pass.setPipeline(this.t);
    pass.setVertexBuffer(0, this.C);
    const contentLeft = Math.ceil(this.J.get() * this.L.devicePixelRatio.get());
    pass.setScissorRect(contentLeft, 0, this.a.width - contentLeft, this.a.height);
    pass.setBindGroup(0, this.s);
    if (this.I?.draw) {
      this.I.draw(pass, viewportData);
    } else {
      pass.draw($y7.length / 2, visibleObjectCount);
    }
    pass.end();
    const commandBuffer = encoder.finish();
    this.g.queue.submit([commandBuffer]);
    this.c = viewportData;
    this.f = options3;
  }
  linesVisibleRangesForRange(_range, includeNewLines) {
    if (!this.c) {
      return null;
    }
    const originalEndLineNumber = _range.endLineNumber;
    const range = $9C.intersectRanges(_range, this.c.visibleRange);
    if (!range) {
      return null;
    }
    const rendStartLineNumber = this.c.startLineNumber;
    const rendEndLineNumber = this.c.endLineNumber;
    const viewportData = this.c;
    const viewLineOptions = this.f;
    if (!viewportData || !viewLineOptions) {
      return null;
    }
    const visibleRanges = [];
    let nextLineModelLineNumber = 0;
    if (includeNewLines) {
      nextLineModelLineNumber = this._context.viewModel.coordinatesConverter.convertViewPositionToModelPosition(new $8C(range.startLineNumber, 1)).lineNumber;
    }
    for (let lineNumber = range.startLineNumber; lineNumber <= range.endLineNumber; lineNumber++) {
      if (lineNumber < rendStartLineNumber || lineNumber > rendEndLineNumber) {
        continue;
      }
      const startColumn = lineNumber === range.startLineNumber ? range.startColumn : 1;
      const continuesInNextLine = lineNumber !== range.endLineNumber;
      const endColumn = continuesInNextLine ? this._context.viewModel.getLineMaxColumn(lineNumber) : range.endColumn;
      const visibleRangesForLine = this.Q(lineNumber, startColumn, endColumn);
      if (!visibleRangesForLine) {
        continue;
      }
      if (includeNewLines && lineNumber < originalEndLineNumber) {
        const currentLineModelLineNumber = nextLineModelLineNumber;
        nextLineModelLineNumber = this._context.viewModel.coordinatesConverter.convertViewPositionToModelPosition(new $8C(lineNumber + 1, 1)).lineNumber;
        if (currentLineModelLineNumber !== nextLineModelLineNumber) {
          visibleRangesForLine.ranges[visibleRangesForLine.ranges.length - 1].width += viewLineOptions.spaceWidth;
        }
      }
      visibleRanges.push(new $_6(visibleRangesForLine.outsideRenderedLine, lineNumber, $a7.from(visibleRangesForLine.ranges), continuesInNextLine));
    }
    if (visibleRanges.length === 0) {
      return null;
    }
    return visibleRanges;
  }
  Q(lineNumber, startColumn, endColumn) {
    if (this.shouldRender()) {
      return null;
    }
    const viewportData = this.c;
    const viewLineOptions = this.f;
    if (!viewportData || !viewLineOptions || lineNumber < viewportData.startLineNumber || lineNumber > viewportData.endLineNumber) {
      return null;
    }
    const lineData = viewportData.getViewLineRenderingData(lineNumber);
    const content = lineData.content;
    let resolvedStartColumn = 0;
    for (let x = 0; x < startColumn - 1; x++) {
      if (content[x] === "	") {
        resolvedStartColumn = $cF.nextRenderTabStop(resolvedStartColumn, lineData.tabSize);
      } else {
        resolvedStartColumn++;
      }
    }
    let resolvedEndColumn = resolvedStartColumn;
    for (let x = startColumn - 1; x < endColumn - 1; x++) {
      if (content[x] === "	") {
        resolvedEndColumn = $cF.nextRenderTabStop(resolvedEndColumn, lineData.tabSize);
      } else {
        resolvedEndColumn++;
      }
    }
    const result = new $d7(false, [
      new $b7(resolvedStartColumn * viewLineOptions.spaceWidth, (resolvedEndColumn - resolvedStartColumn) * viewLineOptions.spaceWidth)
    ]);
    return result;
  }
  visibleRangeForPosition(position) {
    const visibleRanges = this.Q(position.lineNumber, position.column, position.column);
    if (!visibleRanges) {
      return null;
    }
    return new $c7(visibleRanges.outsideRenderedLine, visibleRanges.ranges[0].left);
  }
  getLineWidth(lineNumber) {
    if (!this.c || !this.f) {
      return void 0;
    }
    if (!this.L.canRender(this.f, this.c, lineNumber)) {
      return void 0;
    }
    const lineData = this.c.getViewLineRenderingData(lineNumber);
    const lineRange = this.Q(lineNumber, 1, lineData.maxColumn);
    const lastRange = lineRange?.ranges.at(-1);
    if (lastRange) {
      return lastRange.width;
    }
    return void 0;
  }
  getPositionAtCoordinate(lineNumber, mouseContentHorizontalOffset) {
    if (!this.c || !this.f) {
      return void 0;
    }
    if (!this.L.canRender(this.f, this.c, lineNumber)) {
      return void 0;
    }
    const lineData = this.c.getViewLineRenderingData(lineNumber);
    const content = lineData.content;
    let visualColumnTarget = Math.round(mouseContentHorizontalOffset / this.f.spaceWidth);
    let contentColumn = 0;
    let contentColumnWithTabStops = 0;
    while (visualColumnTarget > 0) {
      let columnWithTabStopsSize = 0;
      if (content[contentColumn] === "	") {
        const tabStop = $cF.nextRenderTabStop(contentColumnWithTabStops, lineData.tabSize);
        columnWithTabStopsSize = tabStop - contentColumnWithTabStops;
      } else {
        columnWithTabStopsSize = 1;
      }
      if (visualColumnTarget - columnWithTabStopsSize / 2 < 0) {
        break;
      }
      visualColumnTarget -= columnWithTabStopsSize;
      contentColumn++;
      contentColumnWithTabStops += columnWithTabStopsSize;
    }
    return new $8C(lineNumber, Math.floor(contentColumn) + 1);
  }
};
$U7 = __decorate([
  __param(2, $Pk),
  __param(3, $wn)
], $U7);

// out-build/vs/base/common/ime.js
var $Q3 = class {
  constructor() {
    this.a = new $ze();
    this.onDidChange = this.a.event;
    this.b = true;
  }
  get enabled() {
    return this.b;
  }
  /**
   * Enable IME
   */
  enable() {
    this.b = true;
    this.a.fire();
  }
  /**
   * Disable IME
   */
  disable() {
    this.b = false;
    this.a.fire();
  }
};
var IME = new $Q3();

// out-build/vs/platform/keybinding/common/keybinding.js
var $Ty = $Qk("keybindingService");

// out-build/vs/editor/browser/controller/editContext/editContext.js
var $R8 = class extends $f7 {
};

// out-build/vs/editor/browser/controller/editContext/screenReaderUtils.js
var $77 = class _$77 {
  static a(lineNumber, linesPerPage) {
    return Math.floor((lineNumber - 1) / linesPerPage);
  }
  static b(page, linesPerPage) {
    const offset = page * linesPerPage;
    const startLineNumber = offset + 1;
    const endLineNumber = offset + linesPerPage;
    return new $9C(startLineNumber, 1, endLineNumber + 1, 1);
  }
  static fromEditorSelection(model, selection, linesPerPage, trimLongText) {
    const LIMIT_CHARS = 500;
    const selectionStartPage = _$77.a(selection.startLineNumber, linesPerPage);
    const selectionStartPageRange = _$77.b(selectionStartPage, linesPerPage);
    const selectionEndPage = _$77.a(selection.endLineNumber, linesPerPage);
    const selectionEndPageRange = _$77.b(selectionEndPage, linesPerPage);
    let pretextRange = selectionStartPageRange.intersectRanges(new $9C(1, 1, selection.startLineNumber, selection.startColumn));
    if (trimLongText && model.getValueLengthInRange(
      pretextRange,
      1
      /* EndOfLinePreference.LF */
    ) > LIMIT_CHARS) {
      const pretextStart = model.modifyPosition(pretextRange.getEndPosition(), -LIMIT_CHARS);
      pretextRange = $9C.fromPositions(pretextStart, pretextRange.getEndPosition());
    }
    const pretext = model.getValueInRange(
      pretextRange,
      1
      /* EndOfLinePreference.LF */
    );
    const lastLine = model.getLineCount();
    const lastLineMaxColumn = model.getLineMaxColumn(lastLine);
    let posttextRange = selectionEndPageRange.intersectRanges(new $9C(selection.endLineNumber, selection.endColumn, lastLine, lastLineMaxColumn));
    if (trimLongText && model.getValueLengthInRange(
      posttextRange,
      1
      /* EndOfLinePreference.LF */
    ) > LIMIT_CHARS) {
      const posttextEnd = model.modifyPosition(posttextRange.getStartPosition(), LIMIT_CHARS);
      posttextRange = $9C.fromPositions(posttextRange.getStartPosition(), posttextEnd);
    }
    const posttext = model.getValueInRange(
      posttextRange,
      1
      /* EndOfLinePreference.LF */
    );
    let text2;
    if (selectionStartPage === selectionEndPage || selectionStartPage + 1 === selectionEndPage) {
      text2 = model.getValueInRange(
        selection,
        1
        /* EndOfLinePreference.LF */
      );
    } else {
      const selectionRange1 = selectionStartPageRange.intersectRanges(selection);
      const selectionRange2 = selectionEndPageRange.intersectRanges(selection);
      text2 = model.getValueInRange(
        selectionRange1,
        1
        /* EndOfLinePreference.LF */
      ) + String.fromCharCode(8230) + model.getValueInRange(
        selectionRange2,
        1
        /* EndOfLinePreference.LF */
      );
    }
    if (trimLongText && text2.length > 2 * LIMIT_CHARS) {
      text2 = text2.substring(0, LIMIT_CHARS) + String.fromCharCode(8230) + text2.substring(text2.length - LIMIT_CHARS, text2.length);
    }
    return {
      value: pretext + text2 + posttext,
      selection,
      selectionStart: pretext.length,
      selectionEnd: pretext.length + text2.length,
      startPositionWithinEditor: pretextRange.getStartPosition(),
      newlineCountBeforeSelection: pretextRange.endLineNumber - pretextRange.startLineNumber
    };
  }
};
function $87(options3, keybindingService) {
  const accessibilitySupport = options3.get(
    2
    /* EditorOption.accessibilitySupport */
  );
  if (accessibilitySupport === 1) {
    const toggleKeybindingLabel = keybindingService.lookupKeybinding("editor.action.toggleScreenReaderAccessibilityMode")?.getAriaLabel();
    const runCommandKeybindingLabel = keybindingService.lookupKeybinding("workbench.action.showCommands")?.getAriaLabel();
    const keybindingEditorKeybindingLabel = keybindingService.lookupKeybinding("workbench.action.openGlobalKeybindings")?.getAriaLabel();
    const editorNotAccessibleMessage = localize(177, null);
    if (toggleKeybindingLabel) {
      return localize(178, null, editorNotAccessibleMessage, toggleKeybindingLabel);
    } else if (runCommandKeybindingLabel) {
      return localize(179, null, editorNotAccessibleMessage, runCommandKeybindingLabel);
    } else if (keybindingEditorKeybindingLabel) {
      return localize(180, null, editorNotAccessibleMessage, keybindingEditorKeybindingLabel);
    } else {
      return editorNotAccessibleMessage;
    }
  }
  return options3.get(
    4
    /* EditorOption.ariaLabel */
  );
}
function $97(text2) {
  let result = 0;
  let startIndex = -1;
  do {
    startIndex = text2.indexOf("\n", startIndex + 1);
    if (startIndex === -1) {
      break;
    }
    result++;
  } while (true);
  return result;
}

// out-build/vs/editor/browser/controller/editContext/textArea/textAreaEditContext.js
var VisibleTextAreaData = class {
  constructor(b, modelLineNumber, distanceToModelLineStart, widthOfHiddenLineTextBefore, distanceToModelLineEnd) {
    this.b = b;
    this.modelLineNumber = modelLineNumber;
    this.distanceToModelLineStart = distanceToModelLineStart;
    this.widthOfHiddenLineTextBefore = widthOfHiddenLineTextBefore;
    this.distanceToModelLineEnd = distanceToModelLineEnd;
    this._visibleTextAreaBrand = void 0;
    this.startPosition = null;
    this.endPosition = null;
    this.visibleTextareaStart = null;
    this.visibleTextareaEnd = null;
    this.a = null;
  }
  prepareRender(visibleRangeProvider) {
    const startModelPosition = new $8C(this.modelLineNumber, this.distanceToModelLineStart + 1);
    const endModelPosition = new $8C(this.modelLineNumber, this.b.viewModel.model.getLineMaxColumn(this.modelLineNumber) - this.distanceToModelLineEnd);
    this.startPosition = this.b.viewModel.coordinatesConverter.convertModelPositionToViewPosition(startModelPosition);
    this.endPosition = this.b.viewModel.coordinatesConverter.convertModelPositionToViewPosition(endModelPosition);
    if (this.startPosition.lineNumber === this.endPosition.lineNumber) {
      this.visibleTextareaStart = visibleRangeProvider.visibleRangeForPosition(this.startPosition);
      this.visibleTextareaEnd = visibleRangeProvider.visibleRangeForPosition(this.endPosition);
    } else {
      this.visibleTextareaStart = null;
      this.visibleTextareaEnd = null;
    }
  }
  definePresentation(tokenPresentation) {
    if (!this.a) {
      if (tokenPresentation) {
        this.a = tokenPresentation;
      } else {
        this.a = {
          foreground: 1,
          italic: false,
          bold: false,
          underline: false,
          strikethrough: false
        };
      }
    }
    return this.a;
  }
};
var canUseZeroSizeTextarea = $Ue;
var $S8 = class $S82 extends $R8 {
  constructor(context, overflowGuardContainer, viewController, visibleRangeProvider, L, M) {
    super(context);
    this.L = L;
    this.M = M;
    this.S = new $8C(1, 1);
    this.U = null;
    this.a = viewController;
    this.b = visibleRangeProvider;
    this.c = 0;
    this.f = 0;
    const options3 = this._context.configuration.options;
    const layoutInfo = options3.get(
      151
      /* EditorOption.layoutInfo */
    );
    this.Q(options3);
    this.s = layoutInfo.contentLeft;
    this.t = layoutInfo.contentWidth;
    this.w = layoutInfo.height;
    this.y = options3.get(
      52
      /* EditorOption.fontInfo */
    );
    this.z = options3.get(
      68
      /* EditorOption.lineHeight */
    );
    this.C = options3.get(
      38
      /* EditorOption.emptySelectionClipboard */
    );
    this.D = options3.get(
      25
      /* EditorOption.copyWithSyntaxHighlighting */
    );
    this.F = null;
    this.G = [new $_D(1, 1, 1, 1)];
    this.H = [new $_D(1, 1, 1, 1)];
    this.I = null;
    this.textArea = $oZ(document.createElement("textarea"));
    $g7.write(
      this.textArea,
      7
      /* PartFingerprint.TextArea */
    );
    this.textArea.setClassName(`inputarea ${$62}`);
    this.textArea.setAttribute("wrap", this.j && !this.F ? "on" : "off");
    const { tabSize } = this._context.viewModel.model.getOptions();
    this.textArea.domNode.style.tabSize = `${tabSize * this.y.spaceWidth}px`;
    this.textArea.setAttribute("autocorrect", "off");
    this.textArea.setAttribute("autocapitalize", "off");
    this.textArea.setAttribute("autocomplete", "off");
    this.textArea.setAttribute("spellcheck", "false");
    this.textArea.setAttribute("aria-label", $87(options3, this.L));
    this.textArea.setAttribute("aria-required", options3.get(
      5
      /* EditorOption.ariaRequired */
    ) ? "true" : "false");
    this.textArea.setAttribute("tabindex", String(options3.get(
      129
      /* EditorOption.tabIndex */
    )));
    this.textArea.setAttribute("role", "textbox");
    this.textArea.setAttribute("aria-roledescription", localize(181, null));
    this.textArea.setAttribute("aria-multiline", "true");
    this.textArea.setAttribute("aria-autocomplete", options3.get(
      96
      /* EditorOption.readOnly */
    ) ? "none" : "both");
    this.R();
    this.textAreaCover = $oZ(document.createElement("div"));
    this.textAreaCover.setPosition("absolute");
    overflowGuardContainer.appendChild(this.textArea);
    overflowGuardContainer.appendChild(this.textAreaCover);
    const simpleModel = {
      getLineCount: () => {
        return this._context.viewModel.getLineCount();
      },
      getLineMaxColumn: (lineNumber) => {
        return this._context.viewModel.getLineMaxColumn(lineNumber);
      },
      getValueInRange: (range, eol) => {
        return this._context.viewModel.getValueInRange(range, eol);
      },
      getValueLengthInRange: (range, eol) => {
        return this._context.viewModel.getValueLengthInRange(range, eol);
      },
      modifyPosition: (position, offset) => {
        return this._context.viewModel.modifyPosition(position, offset);
      }
    };
    const textAreaInputHost = {
      getDataToCopy: () => {
        return $37(this._context.viewModel, this.H, this.C, this.D);
      },
      getScreenReaderContent: () => {
        if (this.g === 1) {
          const selection = this.G[0];
          if ($m && selection.isEmpty()) {
            const position = selection.getStartPosition();
            let textBefore = this.O(position);
            if (textBefore.length === 0) {
              textBefore = this.P(position);
            }
            if (textBefore.length > 0) {
              return new $$7(textBefore, textBefore.length, textBefore.length, $9C.fromPositions(position), 0);
            }
          }
          const LIMIT_CHARS = 500;
          if ($m && !selection.isEmpty() && simpleModel.getValueLengthInRange(
            selection,
            0
            /* EndOfLinePreference.TextDefined */
          ) < LIMIT_CHARS) {
            const text2 = simpleModel.getValueInRange(
              selection,
              0
              /* EndOfLinePreference.TextDefined */
            );
            return new $$7(text2, 0, text2.length, selection, 0);
          }
          if ($Xe && !selection.isEmpty()) {
            const placeholderText = "vscode-placeholder";
            return new $$7(placeholderText, 0, placeholderText.length, null, void 0);
          }
          return $$7.EMPTY;
        }
        if ($1e) {
          const selection = this.G[0];
          if (selection.isEmpty()) {
            const position = selection.getStartPosition();
            const [wordAtPosition, positionOffsetInWord] = this.N(position);
            if (wordAtPosition.length > 0) {
              return new $$7(wordAtPosition, positionOffsetInWord, positionOffsetInWord, $9C.fromPositions(position), 0);
            }
          }
          return $$7.EMPTY;
        }
        const screenReaderContentState = $77.fromEditorSelection(
          simpleModel,
          this.G[0],
          this.h,
          this.g === 0
          /* AccessibilitySupport.Unknown */
        );
        return $$7.fromScreenReaderContentState(screenReaderContentState);
      },
      deduceModelPosition: (viewAnchorPosition, deltaOffset, lineFeedCnt) => {
        return this._context.viewModel.deduceModelPositionRelativeToViewPosition(viewAnchorPosition, deltaOffset, lineFeedCnt);
      }
    };
    const textAreaWrapper = this.B(new $a8(this.textArea.domNode));
    this.J = this.B(this.M.createInstance($_7, textAreaInputHost, textAreaWrapper, OS, {
      isAndroid: $1e,
      isChrome: $We,
      isFirefox: $Ue,
      isSafari: $Xe
    }));
    this.B(this.J.onKeyDown((e) => {
      this.a.emitKeyDown(e);
    }));
    this.B(this.J.onKeyUp((e) => {
      this.a.emitKeyUp(e);
    }));
    this.B(this.J.onPaste((e) => {
      let pasteOnNewLine = false;
      let multicursorText = null;
      let mode = null;
      if (e.metadata) {
        pasteOnNewLine = this.C && !!e.metadata.isFromEmptySelection;
        multicursorText = typeof e.metadata.multicursorText !== "undefined" ? e.metadata.multicursorText : null;
        mode = e.metadata.mode;
      }
      this.a.paste(e.text, pasteOnNewLine, multicursorText, mode);
    }));
    this.B(this.J.onCut(() => {
      this.a.cut();
    }));
    this.B(this.J.onType((e) => {
      if (e.replacePrevCharCnt || e.replaceNextCharCnt || e.positionDelta) {
        if ($07) {
          console.log(` => compositionType: <<${e.text}>>, ${e.replacePrevCharCnt}, ${e.replaceNextCharCnt}, ${e.positionDelta}`);
        }
        this.a.compositionType(e.text, e.replacePrevCharCnt, e.replaceNextCharCnt, e.positionDelta);
      } else {
        if ($07) {
          console.log(` => type: <<${e.text}>>`);
        }
        this.a.type(e.text);
      }
    }));
    this.B(this.J.onSelectionChangeRequest((modelSelection) => {
      this.a.setSelection(modelSelection);
    }));
    this.B(this.J.onCompositionStart((e) => {
      const ta = this.textArea.domNode;
      const modelSelection = this.H[0];
      const { distanceToModelLineStart, widthOfHiddenTextBefore } = (() => {
        const textBeforeSelection = ta.value.substring(0, Math.min(ta.selectionStart, ta.selectionEnd));
        const lineFeedOffset1 = textBeforeSelection.lastIndexOf("\n");
        const lineTextBeforeSelection = textBeforeSelection.substring(lineFeedOffset1 + 1);
        const tabOffset1 = lineTextBeforeSelection.lastIndexOf("	");
        const desiredVisibleBeforeCharCount = lineTextBeforeSelection.length - tabOffset1 - 1;
        const startModelPosition = modelSelection.getStartPosition();
        const visibleBeforeCharCount = Math.min(startModelPosition.column - 1, desiredVisibleBeforeCharCount);
        const distanceToModelLineStart2 = startModelPosition.column - 1 - visibleBeforeCharCount;
        const hiddenLineTextBefore = lineTextBeforeSelection.substring(0, lineTextBeforeSelection.length - visibleBeforeCharCount);
        const { tabSize: tabSize2 } = this._context.viewModel.model.getOptions();
        const widthOfHiddenTextBefore2 = measureText(this.textArea.domNode.ownerDocument, hiddenLineTextBefore, this.y, tabSize2);
        return { distanceToModelLineStart: distanceToModelLineStart2, widthOfHiddenTextBefore: widthOfHiddenTextBefore2 };
      })();
      const { distanceToModelLineEnd } = (() => {
        const textAfterSelection = ta.value.substring(Math.max(ta.selectionStart, ta.selectionEnd));
        const lineFeedOffset2 = textAfterSelection.indexOf("\n");
        const lineTextAfterSelection = lineFeedOffset2 === -1 ? textAfterSelection : textAfterSelection.substring(0, lineFeedOffset2);
        const tabOffset2 = lineTextAfterSelection.indexOf("	");
        const desiredVisibleAfterCharCount = tabOffset2 === -1 ? lineTextAfterSelection.length : lineTextAfterSelection.length - tabOffset2 - 1;
        const endModelPosition = modelSelection.getEndPosition();
        const visibleAfterCharCount = Math.min(this._context.viewModel.model.getLineMaxColumn(endModelPosition.lineNumber) - endModelPosition.column, desiredVisibleAfterCharCount);
        const distanceToModelLineEnd2 = this._context.viewModel.model.getLineMaxColumn(endModelPosition.lineNumber) - endModelPosition.column - visibleAfterCharCount;
        return { distanceToModelLineEnd: distanceToModelLineEnd2 };
      })();
      this._context.viewModel.revealRange(
        "keyboard",
        true,
        $9C.fromPositions(this.G[0].getStartPosition()),
        0,
        1
        /* ScrollType.Immediate */
      );
      this.F = new VisibleTextAreaData(this._context, modelSelection.startLineNumber, distanceToModelLineStart, widthOfHiddenTextBefore, distanceToModelLineEnd);
      this.textArea.setAttribute("wrap", this.j && !this.F ? "on" : "off");
      this.F.prepareRender(this.b);
      this.W();
      this.textArea.setClassName(`inputarea ${$62} ime-input`);
      this.a.compositionStart();
      this._context.viewModel.onCompositionStart();
    }));
    this.B(this.J.onCompositionUpdate((e) => {
      if (!this.F) {
        return;
      }
      this.F.prepareRender(this.b);
      this.W();
    }));
    this.B(this.J.onCompositionEnd(() => {
      this.F = null;
      this.textArea.setAttribute("wrap", this.j && !this.F ? "on" : "off");
      this.W();
      this.textArea.setClassName(`inputarea ${$62}`);
      this.a.compositionEnd();
      this._context.viewModel.onCompositionEnd();
    }));
    this.B(this.J.onFocus(() => {
      this._context.viewModel.setHasFocus(true);
    }));
    this.B(this.J.onBlur(() => {
      this._context.viewModel.setHasFocus(false);
    }));
    this.B(IME.onDidChange(() => {
      this.R();
    }));
  }
  get domNode() {
    return this.textArea;
  }
  writeScreenReaderContent(reason) {
    this.J.writeNativeTextAreaContent(reason);
  }
  getTextAreaDomNode() {
    return this.textArea.domNode;
  }
  dispose() {
    super.dispose();
    this.textArea.domNode.remove();
    this.textAreaCover.domNode.remove();
  }
  N(position) {
    const ANDROID_WORD_SEPARATORS = '`~!@#$%^&*()-=+[{]}\\|;:",.<>/?';
    const lineContent = this._context.viewModel.getLineContent(position.lineNumber);
    const wordSeparators2 = $iE(ANDROID_WORD_SEPARATORS, []);
    let goingLeft = true;
    let startColumn = position.column;
    let goingRight = true;
    let endColumn = position.column;
    let distance = 0;
    while (distance < 50 && (goingLeft || goingRight)) {
      if (goingLeft && startColumn <= 1) {
        goingLeft = false;
      }
      if (goingLeft) {
        const charCode = lineContent.charCodeAt(startColumn - 2);
        const charClass = wordSeparators2.get(charCode);
        if (charClass !== 0) {
          goingLeft = false;
        } else {
          startColumn--;
        }
      }
      if (goingRight && endColumn > lineContent.length) {
        goingRight = false;
      }
      if (goingRight) {
        const charCode = lineContent.charCodeAt(endColumn - 1);
        const charClass = wordSeparators2.get(charCode);
        if (charClass !== 0) {
          goingRight = false;
        } else {
          endColumn++;
        }
      }
      distance++;
    }
    return [lineContent.substring(startColumn - 1, endColumn - 1), position.column - startColumn];
  }
  O(position) {
    const lineContent = this._context.viewModel.getLineContent(position.lineNumber);
    const wordSeparators2 = $iE(this._context.configuration.options.get(
      136
      /* EditorOption.wordSeparators */
    ), []);
    let column = position.column;
    let distance = 0;
    while (column > 1) {
      const charCode = lineContent.charCodeAt(column - 2);
      const charClass = wordSeparators2.get(charCode);
      if (charClass !== 0 || distance > 50) {
        return lineContent.substring(column - 1, position.column - 1);
      }
      distance++;
      column--;
    }
    return lineContent.substring(0, position.column - 1);
  }
  P(position) {
    if (position.column > 1) {
      const lineContent = this._context.viewModel.getLineContent(position.lineNumber);
      const charBefore = lineContent.charAt(position.column - 2);
      if (!$5f(charBefore.charCodeAt(0))) {
        return charBefore;
      }
    }
    return "";
  }
  Q(options3) {
    this.g = options3.get(
      2
      /* EditorOption.accessibilitySupport */
    );
    const accessibilityPageSize = options3.get(
      3
      /* EditorOption.accessibilityPageSize */
    );
    if (this.g === 2 && accessibilityPageSize === EditorOptions.accessibilityPageSize.defaultValue) {
      this.h = 500;
    } else {
      this.h = accessibilityPageSize;
    }
    const layoutInfo = options3.get(
      151
      /* EditorOption.layoutInfo */
    );
    const wrappingColumn = layoutInfo.wrappingColumn;
    if (wrappingColumn !== -1 && this.g !== 1) {
      const fontInfo = options3.get(
        52
        /* EditorOption.fontInfo */
      );
      this.j = true;
      this.n = Math.round(wrappingColumn * fontInfo.typicalHalfwidthCharacterWidth);
    } else {
      this.j = false;
      this.n = canUseZeroSizeTextarea ? 0 : 1;
    }
  }
  // --- begin event handlers
  onConfigurationChanged(e) {
    const options3 = this._context.configuration.options;
    const layoutInfo = options3.get(
      151
      /* EditorOption.layoutInfo */
    );
    this.Q(options3);
    this.s = layoutInfo.contentLeft;
    this.t = layoutInfo.contentWidth;
    this.w = layoutInfo.height;
    this.y = options3.get(
      52
      /* EditorOption.fontInfo */
    );
    this.z = options3.get(
      68
      /* EditorOption.lineHeight */
    );
    this.C = options3.get(
      38
      /* EditorOption.emptySelectionClipboard */
    );
    this.D = options3.get(
      25
      /* EditorOption.copyWithSyntaxHighlighting */
    );
    this.textArea.setAttribute("wrap", this.j && !this.F ? "on" : "off");
    const { tabSize } = this._context.viewModel.model.getOptions();
    this.textArea.domNode.style.tabSize = `${tabSize * this.y.spaceWidth}px`;
    this.textArea.setAttribute("aria-label", $87(options3, this.L));
    this.textArea.setAttribute("aria-required", options3.get(
      5
      /* EditorOption.ariaRequired */
    ) ? "true" : "false");
    this.textArea.setAttribute("tabindex", String(options3.get(
      129
      /* EditorOption.tabIndex */
    )));
    if (e.hasChanged(
      34
      /* EditorOption.domReadOnly */
    ) || e.hasChanged(
      96
      /* EditorOption.readOnly */
    )) {
      this.R();
    }
    if (e.hasChanged(
      2
      /* EditorOption.accessibilitySupport */
    )) {
      this.J.writeNativeTextAreaContent("strategy changed");
    }
    return true;
  }
  onCursorStateChanged(e) {
    this.G = e.selections.slice(0);
    this.H = e.modelSelections.slice(0);
    this.J.writeNativeTextAreaContent("selection changed");
    return true;
  }
  onDecorationsChanged(e) {
    return true;
  }
  onFlushed(e) {
    return true;
  }
  onLinesChanged(e) {
    return true;
  }
  onLinesDeleted(e) {
    return true;
  }
  onLinesInserted(e) {
    return true;
  }
  onScrollChanged(e) {
    this.c = e.scrollLeft;
    this.f = e.scrollTop;
    return true;
  }
  onZonesChanged(e) {
    return true;
  }
  // --- end event handlers
  // --- begin view API
  isFocused() {
    return this.J.isFocused();
  }
  focus() {
    this.J.focusTextArea();
  }
  refreshFocusState() {
    this.J.refreshFocusState();
  }
  getLastRenderData() {
    return this.I;
  }
  setAriaOptions(options3) {
    if (options3.activeDescendant) {
      this.textArea.setAttribute("aria-haspopup", "true");
      this.textArea.setAttribute("aria-autocomplete", "list");
      this.textArea.setAttribute("aria-activedescendant", options3.activeDescendant);
    } else {
      this.textArea.setAttribute("aria-haspopup", "false");
      this.textArea.setAttribute("aria-autocomplete", "both");
      this.textArea.removeAttribute("aria-activedescendant");
    }
    if (options3.role) {
      this.textArea.setAttribute("role", options3.role);
    }
  }
  // --- end view API
  R() {
    const options3 = this._context.configuration.options;
    const useReadOnly = !IME.enabled || options3.get(
      34
      /* EditorOption.domReadOnly */
    ) && options3.get(
      96
      /* EditorOption.readOnly */
    );
    if (useReadOnly) {
      this.textArea.setAttribute("readonly", "true");
    } else {
      this.textArea.removeAttribute("readonly");
    }
  }
  prepareRender(ctx) {
    this.S = new $8C(this.G[0].positionLineNumber, this.G[0].positionColumn);
    this.U = ctx.visibleRangeForPosition(this.S);
    this.F?.prepareRender(ctx);
  }
  render(ctx) {
    this.J.writeNativeTextAreaContent("render");
    this.W();
  }
  W() {
    if (this.F) {
      const visibleStart = this.F.visibleTextareaStart;
      const visibleEnd = this.F.visibleTextareaEnd;
      const startPosition = this.F.startPosition;
      const endPosition = this.F.endPosition;
      if (startPosition && endPosition && visibleStart && visibleEnd && visibleEnd.left >= this.c && visibleStart.left <= this.c + this.t) {
        const top3 = this._context.viewLayout.getVerticalOffsetForLineNumber(this.S.lineNumber) - this.f;
        const lineCount = $97(this.textArea.domNode.value.substr(0, this.textArea.domNode.selectionStart));
        let scrollLeft = this.F.widthOfHiddenLineTextBefore;
        let left2 = this.s + visibleStart.left - this.c;
        let width2 = visibleEnd.left - visibleStart.left + 1;
        if (left2 < this.s) {
          const delta = this.s - left2;
          left2 += delta;
          scrollLeft += delta;
          width2 -= delta;
        }
        if (width2 > this.t) {
          width2 = this.t;
        }
        const viewLineData = this._context.viewModel.getViewLineData(startPosition.lineNumber);
        const startTokenIndex = viewLineData.tokens.findTokenIndexAtOffset(startPosition.column - 1);
        const endTokenIndex = viewLineData.tokens.findTokenIndexAtOffset(endPosition.column - 1);
        const textareaSpansSingleToken = startTokenIndex === endTokenIndex;
        const presentation2 = this.F.definePresentation(textareaSpansSingleToken ? viewLineData.tokens.getPresentation(startTokenIndex) : null);
        this.textArea.domNode.scrollTop = lineCount * this.z;
        this.textArea.domNode.scrollLeft = scrollLeft;
        this.Y({
          lastRenderPosition: null,
          top: top3,
          left: left2,
          width: width2,
          height: this.z,
          useCover: false,
          color: ($YE.getColorMap() || [])[presentation2.foreground],
          italic: presentation2.italic,
          bold: presentation2.bold,
          underline: presentation2.underline,
          strikethrough: presentation2.strikethrough
        });
      }
      return;
    }
    if (!this.U) {
      this.X();
      return;
    }
    const left = this.s + this.U.left - this.c;
    if (left < this.s || left > this.s + this.t) {
      this.X();
      return;
    }
    const top2 = this._context.viewLayout.getVerticalOffsetForLineNumber(this.G[0].positionLineNumber) - this.f;
    if (top2 < 0 || top2 > this.w) {
      this.X();
      return;
    }
    if ($m || this.g === 2) {
      this.Y({
        lastRenderPosition: this.S,
        top: top2,
        left: this.j ? this.s : left,
        width: this.n,
        height: this.z,
        useCover: false
      });
      this.textArea.domNode.scrollLeft = this.U.left;
      const lineCount = this.J.textAreaState.newlineCountBeforeSelection ?? $97(this.textArea.domNode.value.substring(0, this.textArea.domNode.selectionStart));
      this.textArea.domNode.scrollTop = lineCount * this.z;
      return;
    }
    this.Y({
      lastRenderPosition: this.S,
      top: top2,
      left: this.j ? this.s : left,
      width: this.n,
      height: canUseZeroSizeTextarea ? 0 : 1,
      useCover: false
    });
  }
  X() {
    this.Y({
      lastRenderPosition: null,
      top: 0,
      left: 0,
      width: this.n,
      height: canUseZeroSizeTextarea ? 0 : 1,
      useCover: true
    });
  }
  Y(renderData) {
    this.I = renderData.lastRenderPosition;
    const ta = this.textArea;
    const tac = this.textAreaCover;
    $24(ta, this.y);
    ta.setTop(renderData.top);
    ta.setLeft(renderData.left);
    ta.setWidth(renderData.width);
    ta.setHeight(renderData.height);
    ta.setColor(renderData.color ? $Vn.Format.CSS.formatHex(renderData.color) : "");
    ta.setFontStyle(renderData.italic ? "italic" : "");
    if (renderData.bold) {
      ta.setFontWeight("bold");
    }
    ta.setTextDecoration(`${renderData.underline ? " underline" : ""}${renderData.strikethrough ? " line-through" : ""}`);
    tac.setTop(renderData.useCover ? renderData.top : 0);
    tac.setLeft(renderData.useCover ? renderData.left : 0);
    tac.setWidth(renderData.useCover ? renderData.width : 0);
    tac.setHeight(renderData.useCover ? renderData.height : 0);
    const options3 = this._context.configuration.options;
    if (options3.get(
      59
      /* EditorOption.glyphMargin */
    )) {
      tac.setClassName("monaco-editor-background textAreaCover " + $y8.OUTER_CLASS_NAME);
    } else {
      if (options3.get(
        69
        /* EditorOption.lineNumbers */
      ).renderType !== 0) {
        tac.setClassName("monaco-editor-background textAreaCover " + $v8.CLASS_NAME);
      } else {
        tac.setClassName("monaco-editor-background textAreaCover");
      }
    }
  }
};
$S8 = __decorate([
  __param(4, $Ty),
  __param(5, $Pk)
], $S8);
function measureText(targetDocument, text2, fontInfo, tabSize) {
  if (text2.length === 0) {
    return 0;
  }
  const container2 = targetDocument.createElement("div");
  container2.style.position = "absolute";
  container2.style.top = "-50000px";
  container2.style.width = "50000px";
  const regularDomNode = targetDocument.createElement("span");
  $24(regularDomNode, fontInfo);
  regularDomNode.style.whiteSpace = "pre";
  regularDomNode.style.tabSize = `${tabSize * fontInfo.spaceWidth}px`;
  regularDomNode.append(text2);
  container2.appendChild(regularDomNode);
  targetDocument.body.appendChild(container2);
  const res = regularDomNode.offsetWidth;
  container2.remove();
  return res;
}

// out-build/vs/editor/browser/controller/editContext/native/nativeEditContextUtils.js
var $T8 = class extends $3c {
  constructor(b, c) {
    super();
    this.b = b;
    this.c = c;
    this.a = false;
    this.B($_i(this.b, "focus", () => this.f(true)));
    this.B($_i(this.b, "blur", () => this.f(false)));
  }
  f(focused) {
    if (this.a === focused) {
      return;
    }
    this.a = focused;
    this.c(this.a);
  }
  focus() {
    this.f(true);
    this.b.focus();
  }
  refreshFocusState() {
    const focused = this.b === $Qj().document.activeElement;
    this.f(focused);
  }
  get isFocused() {
    return this.a;
  }
};
function $U8(target, type, listener, options3) {
  target.addEventListener(type, listener, options3);
  return {
    dispose() {
      target.removeEventListener(type, listener);
    }
  };
}

// out-build/vs/editor/browser/controller/editContext/native/screenReaderSupport.js
var $V8 = class $V82 {
  constructor(l, m, n, o) {
    this.l = l;
    this.m = m;
    this.n = n;
    this.o = o;
    this.a = 1;
    this.b = 1;
    this.c = 1;
    this.d = 1;
    this.g = 1;
    this.h = 0;
    this.i = new $_D(1, 1, 1, 1);
    this.j = null;
    this.p();
    this.q();
  }
  setIgnoreSelectionChangeTime(reason) {
    this.h = Date.now();
  }
  getIgnoreSelectionChangeTime() {
    return this.h;
  }
  resetSelectionChangeTime() {
    this.h = 0;
  }
  onConfigurationChanged(e) {
    this.p();
    this.q();
    if (e.hasChanged(
      2
      /* EditorOption.accessibilitySupport */
    )) {
      this.writeScreenReaderContent();
    }
  }
  p() {
    const options3 = this.m.configuration.options;
    const layoutInfo = options3.get(
      151
      /* EditorOption.layoutInfo */
    );
    this.a = layoutInfo.contentLeft;
    this.b = layoutInfo.contentWidth;
    this.c = layoutInfo.height;
    this.f = options3.get(
      52
      /* EditorOption.fontInfo */
    );
    this.d = options3.get(
      68
      /* EditorOption.lineHeight */
    );
    this.g = options3.get(
      3
      /* EditorOption.accessibilityPageSize */
    );
  }
  q() {
    const options3 = this.m.configuration.options;
    this.l.domNode.setAttribute("role", "textbox");
    this.l.domNode.setAttribute("aria-required", options3.get(
      5
      /* EditorOption.ariaRequired */
    ) ? "true" : "false");
    this.l.domNode.setAttribute("aria-multiline", "true");
    this.l.domNode.setAttribute("aria-autocomplete", options3.get(
      96
      /* EditorOption.readOnly */
    ) ? "none" : "both");
    this.l.domNode.setAttribute("aria-roledescription", localize(176, null));
    this.l.domNode.setAttribute("aria-label", $87(options3, this.n));
    const tabSize = this.m.viewModel.model.getOptions().tabSize;
    const spaceWidth = options3.get(
      52
      /* EditorOption.fontInfo */
    ).spaceWidth;
    this.l.domNode.style.tabSize = `${tabSize * spaceWidth}px`;
  }
  onCursorStateChanged(e) {
    this.i = e.selections[0] ?? new $_D(1, 1, 1, 1);
  }
  prepareRender(ctx) {
    this.writeScreenReaderContent();
    this.j = ctx.visibleRangeForPosition(this.i.getPosition());
  }
  render(ctx) {
    if (!this.k) {
      return;
    }
    if (!this.j) {
      this.r();
      return;
    }
    const editorScrollLeft = this.m.viewLayout.getCurrentScrollLeft();
    const left = this.a + this.j.left - editorScrollLeft;
    if (left < this.a || left > this.a + this.b) {
      this.r();
      return;
    }
    const editorScrollTop = this.m.viewLayout.getCurrentScrollTop();
    const top2 = this.m.viewLayout.getVerticalOffsetForLineNumber(this.i.positionLineNumber) - editorScrollTop;
    if (top2 < 0 || top2 > this.c) {
      this.r();
      return;
    }
    this.s(top2, this.a, this.b, this.d);
    this.t();
  }
  r() {
    this.s(0, 0, this.b, 1);
  }
  s(top2, left, width2, height) {
    $24(this.l, this.f);
    this.l.setTop(top2);
    this.l.setLeft(left);
    this.l.setWidth(width2);
    this.l.setHeight(height);
  }
  t() {
    if (!this.k) {
      return;
    }
    const textContentBeforeSelection = this.k.value.substring(0, this.k.selectionStart);
    const numberOfLinesOfContentBeforeSelection = $97(textContentBeforeSelection);
    this.l.domNode.scrollTop = numberOfLinesOfContentBeforeSelection * this.d;
  }
  setAriaOptions(options3) {
    if (options3.activeDescendant) {
      this.l.setAttribute("aria-haspopup", "true");
      this.l.setAttribute("aria-autocomplete", "list");
      this.l.setAttribute("aria-activedescendant", options3.activeDescendant);
    } else {
      this.l.setAttribute("aria-haspopup", "false");
      this.l.setAttribute("aria-autocomplete", "both");
      this.l.removeAttribute("aria-activedescendant");
    }
    if (options3.role) {
      this.l.setAttribute("role", options3.role);
    }
  }
  writeScreenReaderContent() {
    const focusedElement = $Qj().document.activeElement;
    if (!focusedElement || focusedElement !== this.l.domNode) {
      return;
    }
    const isScreenReaderOptimized = this.o.isScreenReaderOptimized();
    if (isScreenReaderOptimized) {
      this.k = this.u();
      if (this.l.domNode.textContent !== this.k.value) {
        this.setIgnoreSelectionChangeTime("setValue");
        this.l.domNode.textContent = this.k.value;
      }
      this.v(this.k.selectionStart, this.k.selectionEnd);
    } else {
      this.k = void 0;
      this.setIgnoreSelectionChangeTime("setValue");
      this.l.domNode.textContent = "";
    }
  }
  get screenReaderContentState() {
    return this.k;
  }
  u() {
    const simpleModel = {
      getLineCount: () => {
        return this.m.viewModel.getLineCount();
      },
      getLineMaxColumn: (lineNumber) => {
        return this.m.viewModel.getLineMaxColumn(lineNumber);
      },
      getValueInRange: (range, eol) => {
        return this.m.viewModel.getValueInRange(range, eol);
      },
      getValueLengthInRange: (range, eol) => {
        return this.m.viewModel.getValueLengthInRange(range, eol);
      },
      modifyPosition: (position, offset) => {
        return this.m.viewModel.modifyPosition(position, offset);
      }
    };
    return $77.fromEditorSelection(
      simpleModel,
      this.i,
      this.g,
      this.o.getAccessibilitySupport() === 0
      /* AccessibilitySupport.Unknown */
    );
  }
  v(selectionOffsetStart, selectionOffsetEnd) {
    const activeDocument = $Qj().document;
    const activeDocumentSelection = activeDocument.getSelection();
    if (!activeDocumentSelection) {
      return;
    }
    const textContent = this.l.domNode.firstChild;
    if (!textContent) {
      return;
    }
    const range = new globalThis.Range();
    range.setStart(textContent, selectionOffsetStart);
    range.setEnd(textContent, selectionOffsetEnd);
    this.setIgnoreSelectionChangeTime("setRange");
    activeDocumentSelection.removeAllRanges();
    activeDocumentSelection.addRange(range);
  }
};
$V8 = __decorate([
  __param(2, $Ty),
  __param(3, $ND)
], $V8);

// out-build/vs/editor/common/core/lineRange.js
var $_C = class _$_C {
  static fromRange(range) {
    return new _$_C(range.startLineNumber, range.endLineNumber);
  }
  static fromRangeInclusive(range) {
    return new _$_C(range.startLineNumber, range.endLineNumber + 1);
  }
  static subtract(a, b) {
    if (!b) {
      return [a];
    }
    if (a.startLineNumber < b.startLineNumber && b.endLineNumberExclusive < a.endLineNumberExclusive) {
      return [
        new _$_C(a.startLineNumber, b.startLineNumber),
        new _$_C(b.endLineNumberExclusive, a.endLineNumberExclusive)
      ];
    } else if (b.startLineNumber <= a.startLineNumber && a.endLineNumberExclusive <= b.endLineNumberExclusive) {
      return [];
    } else if (b.endLineNumberExclusive < a.endLineNumberExclusive) {
      return [new _$_C(Math.max(b.endLineNumberExclusive, a.startLineNumber), a.endLineNumberExclusive)];
    } else {
      return [new _$_C(a.startLineNumber, Math.min(b.startLineNumber, a.endLineNumberExclusive))];
    }
  }
  /**
   * @param lineRanges An array of sorted line ranges.
   */
  static joinMany(lineRanges) {
    if (lineRanges.length === 0) {
      return [];
    }
    let result = new $aD(lineRanges[0].slice());
    for (let i2 = 1; i2 < lineRanges.length; i2++) {
      result = result.getUnion(new $aD(lineRanges[i2].slice()));
    }
    return result.ranges;
  }
  static join(lineRanges) {
    if (lineRanges.length === 0) {
      throw new $vb("lineRanges cannot be empty");
    }
    let startLineNumber = lineRanges[0].startLineNumber;
    let endLineNumberExclusive = lineRanges[0].endLineNumberExclusive;
    for (let i2 = 1; i2 < lineRanges.length; i2++) {
      startLineNumber = Math.min(startLineNumber, lineRanges[i2].startLineNumber);
      endLineNumberExclusive = Math.max(endLineNumberExclusive, lineRanges[i2].endLineNumberExclusive);
    }
    return new _$_C(startLineNumber, endLineNumberExclusive);
  }
  static ofLength(startLineNumber, length) {
    return new _$_C(startLineNumber, startLineNumber + length);
  }
  /**
   * @internal
   */
  static deserialize(lineRange) {
    return new _$_C(lineRange[0], lineRange[1]);
  }
  constructor(startLineNumber, endLineNumberExclusive) {
    if (startLineNumber > endLineNumberExclusive) {
      throw new $vb(`startLineNumber ${startLineNumber} cannot be after endLineNumberExclusive ${endLineNumberExclusive}`);
    }
    this.startLineNumber = startLineNumber;
    this.endLineNumberExclusive = endLineNumberExclusive;
  }
  /**
   * Indicates if this line range contains the given line number.
   */
  contains(lineNumber) {
    return this.startLineNumber <= lineNumber && lineNumber < this.endLineNumberExclusive;
  }
  /**
   * Indicates if this line range is empty.
   */
  get isEmpty() {
    return this.startLineNumber === this.endLineNumberExclusive;
  }
  /**
   * Moves this line range by the given offset of line numbers.
   */
  delta(offset) {
    return new _$_C(this.startLineNumber + offset, this.endLineNumberExclusive + offset);
  }
  deltaLength(offset) {
    return new _$_C(this.startLineNumber, this.endLineNumberExclusive + offset);
  }
  /**
   * The number of lines this line range spans.
   */
  get length() {
    return this.endLineNumberExclusive - this.startLineNumber;
  }
  /**
   * Creates a line range that combines this and the given line range.
   */
  join(other) {
    return new _$_C(Math.min(this.startLineNumber, other.startLineNumber), Math.max(this.endLineNumberExclusive, other.endLineNumberExclusive));
  }
  toString() {
    return `[${this.startLineNumber},${this.endLineNumberExclusive})`;
  }
  /**
   * The resulting range is empty if the ranges do not intersect, but touch.
   * If the ranges don't even touch, the result is undefined.
   */
  intersect(other) {
    const startLineNumber = Math.max(this.startLineNumber, other.startLineNumber);
    const endLineNumberExclusive = Math.min(this.endLineNumberExclusive, other.endLineNumberExclusive);
    if (startLineNumber <= endLineNumberExclusive) {
      return new _$_C(startLineNumber, endLineNumberExclusive);
    }
    return void 0;
  }
  intersectsStrict(other) {
    return this.startLineNumber < other.endLineNumberExclusive && other.startLineNumber < this.endLineNumberExclusive;
  }
  overlapOrTouch(other) {
    return this.startLineNumber <= other.endLineNumberExclusive && other.startLineNumber <= this.endLineNumberExclusive;
  }
  equals(b) {
    return this.startLineNumber === b.startLineNumber && this.endLineNumberExclusive === b.endLineNumberExclusive;
  }
  toInclusiveRange() {
    if (this.isEmpty) {
      return null;
    }
    return new $9C(this.startLineNumber, 1, this.endLineNumberExclusive - 1, Number.MAX_SAFE_INTEGER);
  }
  /**
   * @deprecated Using this function is discouraged because it might lead to bugs: The end position is not guaranteed to be a valid position!
  */
  toExclusiveRange() {
    return new $9C(this.startLineNumber, 1, this.endLineNumberExclusive, 1);
  }
  mapToLineArray(f) {
    const result = [];
    for (let lineNumber = this.startLineNumber; lineNumber < this.endLineNumberExclusive; lineNumber++) {
      result.push(f(lineNumber));
    }
    return result;
  }
  forEach(f) {
    for (let lineNumber = this.startLineNumber; lineNumber < this.endLineNumberExclusive; lineNumber++) {
      f(lineNumber);
    }
  }
  /**
   * @internal
   */
  serialize() {
    return [this.startLineNumber, this.endLineNumberExclusive];
  }
  includes(lineNumber) {
    return this.startLineNumber <= lineNumber && lineNumber < this.endLineNumberExclusive;
  }
  /**
   * Converts this 1-based line range to a 0-based offset range (subtracts 1!).
   * @internal
   */
  toOffsetRange() {
    return new $0C(this.startLineNumber - 1, this.endLineNumberExclusive - 1);
  }
  distanceToRange(other) {
    if (this.endLineNumberExclusive <= other.startLineNumber) {
      return other.startLineNumber - this.endLineNumberExclusive;
    }
    if (other.endLineNumberExclusive <= this.startLineNumber) {
      return this.startLineNumber - other.endLineNumberExclusive;
    }
    return 0;
  }
  distanceToLine(lineNumber) {
    if (this.contains(lineNumber)) {
      return 0;
    }
    if (lineNumber < this.startLineNumber) {
      return this.startLineNumber - lineNumber;
    }
    return lineNumber - this.endLineNumberExclusive;
  }
  addMargin(marginTop, marginBottom) {
    return new _$_C(this.startLineNumber - marginTop, this.endLineNumberExclusive + marginBottom);
  }
};
var $aD = class _$aD {
  constructor(c = []) {
    this.c = c;
  }
  get ranges() {
    return this.c;
  }
  addRange(range) {
    if (range.length === 0) {
      return;
    }
    const joinRangeStartIdx = $6(this.c, (r2) => r2.endLineNumberExclusive >= range.startLineNumber);
    const joinRangeEndIdxExclusive = $4(this.c, (r2) => r2.startLineNumber <= range.endLineNumberExclusive) + 1;
    if (joinRangeStartIdx === joinRangeEndIdxExclusive) {
      this.c.splice(joinRangeStartIdx, 0, range);
    } else if (joinRangeStartIdx === joinRangeEndIdxExclusive - 1) {
      const joinRange = this.c[joinRangeStartIdx];
      this.c[joinRangeStartIdx] = joinRange.join(range);
    } else {
      const joinRange = this.c[joinRangeStartIdx].join(this.c[joinRangeEndIdxExclusive - 1]).join(range);
      this.c.splice(joinRangeStartIdx, joinRangeEndIdxExclusive - joinRangeStartIdx, joinRange);
    }
  }
  contains(lineNumber) {
    const rangeThatStartsBeforeEnd = $3(this.c, (r2) => r2.startLineNumber <= lineNumber);
    return !!rangeThatStartsBeforeEnd && rangeThatStartsBeforeEnd.endLineNumberExclusive > lineNumber;
  }
  intersects(range) {
    const rangeThatStartsBeforeEnd = $3(this.c, (r2) => r2.startLineNumber < range.endLineNumberExclusive);
    return !!rangeThatStartsBeforeEnd && rangeThatStartsBeforeEnd.endLineNumberExclusive > range.startLineNumber;
  }
  getUnion(other) {
    if (this.c.length === 0) {
      return other;
    }
    if (other.c.length === 0) {
      return this;
    }
    const result = [];
    let i1 = 0;
    let i2 = 0;
    let current = null;
    while (i1 < this.c.length || i2 < other.c.length) {
      let next = null;
      if (i1 < this.c.length && i2 < other.c.length) {
        const lineRange1 = this.c[i1];
        const lineRange2 = other.c[i2];
        if (lineRange1.startLineNumber < lineRange2.startLineNumber) {
          next = lineRange1;
          i1++;
        } else {
          next = lineRange2;
          i2++;
        }
      } else if (i1 < this.c.length) {
        next = this.c[i1];
        i1++;
      } else {
        next = other.c[i2];
        i2++;
      }
      if (current === null) {
        current = next;
      } else {
        if (current.endLineNumberExclusive >= next.startLineNumber) {
          current = new $_C(current.startLineNumber, Math.max(current.endLineNumberExclusive, next.endLineNumberExclusive));
        } else {
          result.push(current);
          current = next;
        }
      }
    }
    if (current !== null) {
      result.push(current);
    }
    return new _$aD(result);
  }
  /**
   * Subtracts all ranges in this set from `range` and returns the result.
   */
  subtractFrom(range) {
    const joinRangeStartIdx = $6(this.c, (r2) => r2.endLineNumberExclusive >= range.startLineNumber);
    const joinRangeEndIdxExclusive = $4(this.c, (r2) => r2.startLineNumber <= range.endLineNumberExclusive) + 1;
    if (joinRangeStartIdx === joinRangeEndIdxExclusive) {
      return new _$aD([range]);
    }
    const result = [];
    let startLineNumber = range.startLineNumber;
    for (let i2 = joinRangeStartIdx; i2 < joinRangeEndIdxExclusive; i2++) {
      const r2 = this.c[i2];
      if (r2.startLineNumber > startLineNumber) {
        result.push(new $_C(startLineNumber, r2.startLineNumber));
      }
      startLineNumber = r2.endLineNumberExclusive;
    }
    if (startLineNumber < range.endLineNumberExclusive) {
      result.push(new $_C(startLineNumber, range.endLineNumberExclusive));
    }
    return new _$aD(result);
  }
  toString() {
    return this.c.map((r2) => r2.toString()).join(", ");
  }
  getIntersection(other) {
    const result = [];
    let i1 = 0;
    let i2 = 0;
    while (i1 < this.c.length && i2 < other.c.length) {
      const r1 = this.c[i1];
      const r2 = other.c[i2];
      const i3 = r1.intersect(r2);
      if (i3 && !i3.isEmpty) {
        result.push(i3);
      }
      if (r1.endLineNumberExclusive < r2.endLineNumberExclusive) {
        i1++;
      } else {
        i2++;
      }
    }
    return new _$aD(result);
  }
  getWithDelta(value) {
    return new _$aD(this.c.map((r2) => r2.delta(value)));
  }
};

// out-build/vs/editor/common/core/textLength.js
var $gD = class _$gD {
  static {
    this.zero = new _$gD(0, 0);
  }
  static lengthDiffNonNegative(start, end) {
    if (end.isLessThan(start)) {
      return _$gD.zero;
    }
    if (start.lineCount === end.lineCount) {
      return new _$gD(0, end.columnCount - start.columnCount);
    } else {
      return new _$gD(end.lineCount - start.lineCount, end.columnCount);
    }
  }
  static betweenPositions(position1, position2) {
    if (position1.lineNumber === position2.lineNumber) {
      return new _$gD(0, position2.column - position1.column);
    } else {
      return new _$gD(position2.lineNumber - position1.lineNumber, position2.column - 1);
    }
  }
  static fromPosition(pos) {
    return new _$gD(pos.lineNumber - 1, pos.column - 1);
  }
  static ofRange(range) {
    return _$gD.betweenPositions(range.getStartPosition(), range.getEndPosition());
  }
  static ofText(text2) {
    let line = 0;
    let column = 0;
    for (const c of text2) {
      if (c === "\n") {
        line++;
        column = 0;
      } else {
        column++;
      }
    }
    return new _$gD(line, column);
  }
  constructor(lineCount, columnCount) {
    this.lineCount = lineCount;
    this.columnCount = columnCount;
  }
  isZero() {
    return this.lineCount === 0 && this.columnCount === 0;
  }
  isLessThan(other) {
    if (this.lineCount !== other.lineCount) {
      return this.lineCount < other.lineCount;
    }
    return this.columnCount < other.columnCount;
  }
  isGreaterThan(other) {
    if (this.lineCount !== other.lineCount) {
      return this.lineCount > other.lineCount;
    }
    return this.columnCount > other.columnCount;
  }
  isGreaterThanOrEqualTo(other) {
    if (this.lineCount !== other.lineCount) {
      return this.lineCount > other.lineCount;
    }
    return this.columnCount >= other.columnCount;
  }
  equals(other) {
    return this.lineCount === other.lineCount && this.columnCount === other.columnCount;
  }
  compare(other) {
    if (this.lineCount !== other.lineCount) {
      return this.lineCount - other.lineCount;
    }
    return this.columnCount - other.columnCount;
  }
  add(other) {
    if (other.lineCount === 0) {
      return new _$gD(this.lineCount, this.columnCount + other.columnCount);
    } else {
      return new _$gD(this.lineCount + other.lineCount, other.columnCount);
    }
  }
  createRange(startPosition) {
    if (this.lineCount === 0) {
      return new $9C(startPosition.lineNumber, startPosition.column, startPosition.lineNumber, startPosition.column + this.columnCount);
    } else {
      return new $9C(startPosition.lineNumber, startPosition.column, startPosition.lineNumber + this.lineCount, this.columnCount + 1);
    }
  }
  toRange() {
    return new $9C(1, 1, this.lineCount + 1, this.columnCount + 1);
  }
  toLineRange() {
    return $_C.ofLength(1, this.lineCount);
  }
  addToPosition(position) {
    if (this.lineCount === 0) {
      return new $8C(position.lineNumber, position.column + this.columnCount);
    } else {
      return new $8C(position.lineNumber + this.lineCount, this.columnCount + 1);
    }
  }
  addToRange(range) {
    return $9C.fromPositions(this.addToPosition(range.getStartPosition()), this.addToPosition(range.getEndPosition()));
  }
  toString() {
    return `${this.lineCount},${this.columnCount}`;
  }
};

// out-build/vs/editor/common/core/positionToOffset.js
var $hD = class {
  constructor(text2) {
    this.text = text2;
    this.a = [];
    this.b = [];
    this.a.push(0);
    for (let i2 = 0; i2 < text2.length; i2++) {
      if (text2.charAt(i2) === "\n") {
        this.a.push(i2 + 1);
        if (i2 > 0 && text2.charAt(i2 - 1) === "\r") {
          this.b.push(i2 - 1);
        } else {
          this.b.push(i2);
        }
      }
    }
    this.b.push(text2.length);
  }
  getOffset(position) {
    return this.a[position.lineNumber - 1] + position.column - 1;
  }
  getOffsetRange(range) {
    return new $0C(this.getOffset(range.getStartPosition()), this.getOffset(range.getEndPosition()));
  }
  getPosition(offset) {
    const idx = $4(this.a, (i2) => i2 <= offset);
    const lineNumber = idx + 1;
    const column = offset - this.a[idx] + 1;
    return new $8C(lineNumber, column);
  }
  getRange(offsetRange) {
    return $9C.fromPositions(this.getPosition(offsetRange.start), this.getPosition(offsetRange.endExclusive));
  }
  getTextLength(offsetRange) {
    return $gD.ofRange(this.getRange(offsetRange));
  }
  get textLength() {
    const lineIdx = this.a.length - 1;
    return new $gD(lineIdx, this.text.length - this.a[lineIdx]);
  }
  getLineLength(lineNumber) {
    return this.b[lineNumber - 1] - this.a[lineNumber - 1];
  }
};

// out-build/vs/editor/browser/controller/editContext/native/editContextFactory.js
var EditContext;
(function(EditContext2) {
  function supported(obj) {
    return typeof obj?.EditContext === "function";
  }
  EditContext2.supported = supported;
  function create2(window3, options3) {
    return new window3.EditContext(options3);
  }
  EditContext2.create = create2;
})(EditContext || (EditContext = {}));

// out-build/vs/editor/browser/controller/editContext/native/nativeEditContextRegistry.js
var NativeEditContextRegistryImpl = class {
  constructor() {
    this.a = /* @__PURE__ */ new Map();
  }
  register(ownerID, nativeEditContext) {
    this.a.set(ownerID, nativeEditContext);
    return {
      dispose: () => {
        this.a.delete(ownerID);
      }
    };
  }
  get(ownerID) {
    return this.a.get(ownerID);
  }
};
var $W8 = new NativeEditContextRegistryImpl();

// out-build/vs/editor/browser/controller/editContext/native/nativeEditContext.js
var CompositionClassName;
(function(CompositionClassName2) {
  CompositionClassName2["NONE"] = "edit-context-composition-none";
  CompositionClassName2["SECONDARY"] = "edit-context-composition-secondary";
  CompositionClassName2["PRIMARY"] = "edit-context-composition-primary";
})(CompositionClassName || (CompositionClassName = {}));
var $X8 = class $X82 extends $R8 {
  constructor(ownerID, context, overflowGuardContainer, viewController, z, instantiationService, C) {
    super(context);
    this.z = z;
    this.C = C;
    this.g = [];
    this.h = new $_D(1, 1, 1, 1);
    this.j = new $8C(1, 1);
    this.n = -1;
    this.s = 0;
    this.t = 0;
    this.domNode = new $nZ(document.createElement("div"));
    this.domNode.setClassName(`native-edit-context`);
    this.textArea = new $nZ(document.createElement("textarea"));
    this.textArea.setClassName("native-edit-context-textarea");
    this.D();
    overflowGuardContainer.appendChild(this.domNode);
    overflowGuardContainer.appendChild(this.textArea);
    this.c = overflowGuardContainer.domNode;
    this.y = this.B(new $4c());
    this.w = this.B(new $T8(this.domNode.domNode, (newFocusValue) => {
      if (newFocusValue) {
        this.y.value = this.O(viewController);
        this.b.setIgnoreSelectionChangeTime("onFocus");
      } else {
        this.y.value = void 0;
      }
      this._context.viewModel.setHasFocus(newFocusValue);
    }));
    const window3 = getWindow(this.domNode.domNode);
    this.a = EditContext.create(window3);
    this.setEditContextOnDomNode();
    this.b = instantiationService.createInstance($V8, this.domNode, context);
    this.B($_i(this.domNode.domNode, "copy", (e) => this.N(e)));
    this.B($_i(this.domNode.domNode, "cut", (e) => {
      this.b.setIgnoreSelectionChangeTime("onCut");
      this.N(e);
      viewController.cut();
    }));
    this.B($_i(this.domNode.domNode, "keyup", (e) => viewController.emitKeyUp(new $if(e))));
    this.B($_i(this.domNode.domNode, "keydown", async (e) => {
      const standardKeyboardEvent = new $if(e);
      if (standardKeyboardEvent.keyCode === 114) {
        standardKeyboardEvent.stopPropagation();
      }
      viewController.emitKeyDown(standardKeyboardEvent);
    }));
    this.B($_i(this.domNode.domNode, "beforeinput", async (e) => {
      if (e.inputType === "insertParagraph" || e.inputType === "insertLineBreak") {
        this.H(viewController, { text: "\n", replacePrevCharCnt: 0, replaceNextCharCnt: 0, positionDelta: 0 });
      }
    }));
    this.B($U8(this.a, "textformatupdate", (e) => this.J(e)));
    this.B($U8(this.a, "characterboundsupdate", (e) => this.M(e)));
    this.B($U8(this.a, "textupdate", (e) => {
      this.G(viewController, e);
    }));
    this.B($U8(this.a, "compositionstart", (e) => {
      viewController.compositionStart();
      this._context.viewModel.onCompositionStart();
    }));
    this.B($U8(this.a, "compositionend", (e) => {
      viewController.compositionEnd();
      this._context.viewModel.onCompositionEnd();
    }));
    this.B($_i(this.textArea.domNode, "paste", (e) => {
      this.b.setIgnoreSelectionChangeTime("onPaste");
      e.preventDefault();
      if (!e.clipboardData) {
        return;
      }
      let [text2, metadata] = $67.getTextData(e.clipboardData);
      if (!text2) {
        return;
      }
      metadata = metadata || $47.INSTANCE.get(text2);
      let pasteOnNewLine = false;
      let multicursorText = null;
      let mode = null;
      if (metadata) {
        const options3 = this._context.configuration.options;
        const emptySelectionClipboard = options3.get(
          38
          /* EditorOption.emptySelectionClipboard */
        );
        pasteOnNewLine = emptySelectionClipboard && !!metadata.isFromEmptySelection;
        multicursorText = typeof metadata.multicursorText !== "undefined" ? metadata.multicursorText : null;
        mode = metadata.mode;
      }
      viewController.paste(text2, pasteOnNewLine, multicursorText, mode);
    }));
    this.B($W8.register(ownerID, this));
  }
  // --- Public methods ---
  dispose() {
    this.domNode.domNode.blur();
    this.domNode.domNode.remove();
    this.textArea.domNode.remove();
    super.dispose();
  }
  setAriaOptions(options3) {
    this.b.setAriaOptions(options3);
  }
  /* Last rendered data needed for correct hit-testing and determining the mouse position.
   * Without this, the selection will blink as incorrect mouse position is calculated */
  getLastRenderData() {
    return this.h.getPosition();
  }
  prepareRender(ctx) {
    this.b.prepareRender(ctx);
    this.F();
    this.L(ctx);
  }
  render(ctx) {
    this.b.render(ctx);
  }
  onCursorStateChanged(e) {
    this.h = e.modelSelections[0] ?? new $_D(1, 1, 1, 1);
    this.b.onCursorStateChanged(e);
    return true;
  }
  onConfigurationChanged(e) {
    this.b.onConfigurationChanged(e);
    this.D();
    return true;
  }
  onDecorationsChanged(e) {
    return true;
  }
  onFlushed(e) {
    return true;
  }
  onLinesChanged(e) {
    return true;
  }
  onLinesDeleted(e) {
    return true;
  }
  onLinesInserted(e) {
    return true;
  }
  onScrollChanged(e) {
    this.t = e.scrollLeft;
    this.s = e.scrollTop;
    return true;
  }
  onZonesChanged(e) {
    return true;
  }
  onWillPaste() {
    this.b.setIgnoreSelectionChangeTime("onWillPaste");
  }
  writeScreenReaderContent() {
    this.b.writeScreenReaderContent();
  }
  isFocused() {
    return this.w.isFocused || $Qj().document.activeElement === this.textArea.domNode;
  }
  focus() {
    this.w.focus();
    this.refreshFocusState();
  }
  refreshFocusState() {
    this.w.refreshFocusState();
  }
  // TODO: added as a workaround fix for https://github.com/microsoft/vscode/issues/229825
  // When this issue will be fixed the following should be removed.
  setEditContextOnDomNode() {
    const targetWindow = getWindow(this.domNode.domNode);
    const targetWindowId = getWindowId(targetWindow);
    if (this.n !== targetWindowId) {
      this.domNode.domNode.editContext = this.a;
      this.n = targetWindowId;
    }
  }
  // --- Private methods ---
  D() {
    const options3 = this._context.configuration.options;
    this.domNode.domNode.setAttribute("tabindex", String(options3.get(
      129
      /* EditorOption.tabIndex */
    )));
  }
  F() {
    const editContextState = this.I();
    this.a.updateText(0, Number.MAX_SAFE_INTEGER, editContextState.text);
    this.a.updateSelection(editContextState.selectionStartOffset, editContextState.selectionEndOffset);
    this.j = editContextState.textStartPositionWithinEditor;
  }
  G(viewController, e) {
    if (!this.a) {
      return;
    }
    const model = this._context.viewModel.model;
    const offsetOfStartOfText = model.getOffsetAt(this.j);
    const offsetOfSelectionEnd = model.getOffsetAt(this.h.getEndPosition());
    const offsetOfSelectionStart = model.getOffsetAt(this.h.getStartPosition());
    const selectionEndOffset = offsetOfSelectionEnd - offsetOfStartOfText;
    const selectionStartOffset = offsetOfSelectionStart - offsetOfStartOfText;
    let replaceNextCharCnt = 0;
    let replacePrevCharCnt = 0;
    if (e.updateRangeEnd > selectionEndOffset) {
      replaceNextCharCnt = e.updateRangeEnd - selectionEndOffset;
    }
    if (e.updateRangeStart < selectionStartOffset) {
      replacePrevCharCnt = selectionStartOffset - e.updateRangeStart;
    }
    let text2 = "";
    if (selectionStartOffset < e.updateRangeStart) {
      text2 += this.a.text.substring(selectionStartOffset, e.updateRangeStart);
    }
    text2 += e.text;
    if (selectionEndOffset > e.updateRangeEnd) {
      text2 += this.a.text.substring(e.updateRangeEnd, selectionEndOffset);
    }
    let positionDelta = 0;
    if (e.selectionStart === e.selectionEnd && selectionStartOffset === selectionEndOffset) {
      positionDelta = e.selectionStart - (e.updateRangeStart + e.text.length);
    }
    const typeInput = {
      text: text2,
      replacePrevCharCnt,
      replaceNextCharCnt,
      positionDelta
    };
    this.H(viewController, typeInput);
    this.F();
  }
  H(viewController, typeInput) {
    if (typeInput.replacePrevCharCnt || typeInput.replaceNextCharCnt || typeInput.positionDelta) {
      viewController.compositionType(typeInput.text, typeInput.replacePrevCharCnt, typeInput.replaceNextCharCnt, typeInput.positionDelta);
    } else {
      viewController.type(typeInput.text);
    }
  }
  I() {
    const model = this._context.viewModel.model;
    const primarySelectionStartLine = this.h.startLineNumber;
    const primarySelectionEndLine = this.h.endLineNumber;
    const endColumnOfEndLineNumber = model.getLineMaxColumn(primarySelectionEndLine);
    const rangeOfText = new $9C(primarySelectionStartLine, 1, primarySelectionEndLine, endColumnOfEndLineNumber);
    const text2 = model.getValueInRange(
      rangeOfText,
      0
      /* EndOfLinePreference.TextDefined */
    );
    const selectionStartOffset = this.h.startColumn - 1;
    const selectionEndOffset = text2.length + this.h.endColumn - endColumnOfEndLineNumber;
    const textStartPositionWithinEditor = rangeOfText.getStartPosition();
    return {
      text: text2,
      selectionStartOffset,
      selectionEndOffset,
      textStartPositionWithinEditor
    };
  }
  J(e) {
    if (!this.a) {
      return;
    }
    const formats = e.getTextFormats();
    const textStartPositionWithinEditor = this.j;
    const decorations = [];
    formats.forEach((f) => {
      const textModel = this._context.viewModel.model;
      const offsetOfEditContextText = textModel.getOffsetAt(textStartPositionWithinEditor);
      const startPositionOfDecoration = textModel.getPositionAt(offsetOfEditContextText + f.rangeStart);
      const endPositionOfDecoration = textModel.getPositionAt(offsetOfEditContextText + f.rangeEnd);
      const decorationRange = $9C.fromPositions(startPositionOfDecoration, endPositionOfDecoration);
      const thickness = f.underlineThickness.toLowerCase();
      let decorationClassName = CompositionClassName.NONE;
      switch (thickness) {
        case "thin":
          decorationClassName = CompositionClassName.SECONDARY;
          break;
        case "thick":
          decorationClassName = CompositionClassName.PRIMARY;
          break;
      }
      decorations.push({
        range: decorationRange,
        options: {
          description: "textFormatDecoration",
          inlineClassName: decorationClassName
        }
      });
    });
    this.g = this._context.viewModel.model.deltaDecorations(this.g, decorations);
  }
  L(ctx) {
    if (!this.c) {
      return;
    }
    const options3 = this._context.configuration.options;
    const lineHeight = options3.get(
      68
      /* EditorOption.lineHeight */
    );
    const contentLeft = options3.get(
      151
      /* EditorOption.layoutInfo */
    ).contentLeft;
    const parentBounds = this.c.getBoundingClientRect();
    const modelStartPosition = this.h.getStartPosition();
    const viewStartPosition = this._context.viewModel.coordinatesConverter.convertModelPositionToViewPosition(modelStartPosition);
    const verticalOffsetStart = this._context.viewLayout.getVerticalOffsetForLineNumber(viewStartPosition.lineNumber);
    const top2 = parentBounds.top + verticalOffsetStart - this.s;
    const height = (this.h.endLineNumber - this.h.startLineNumber + 1) * lineHeight;
    let left = parentBounds.left + contentLeft - this.t;
    let width2;
    if (this.h.isEmpty()) {
      const linesVisibleRanges = ctx.visibleRangeForPosition(viewStartPosition);
      if (linesVisibleRanges) {
        left += linesVisibleRanges.left;
      }
      width2 = 0;
    } else {
      width2 = parentBounds.width - contentLeft;
    }
    const selectionBounds = new DOMRect(left, top2, width2, height);
    this.a.updateSelectionBounds(selectionBounds);
    this.a.updateControlBounds(selectionBounds);
  }
  M(e) {
    if (!this.c) {
      return;
    }
    const options3 = this._context.configuration.options;
    const typicalHalfWidthCharacterWidth = options3.get(
      52
      /* EditorOption.fontInfo */
    ).typicalHalfwidthCharacterWidth;
    const lineHeight = options3.get(
      68
      /* EditorOption.lineHeight */
    );
    const contentLeft = options3.get(
      151
      /* EditorOption.layoutInfo */
    ).contentLeft;
    const parentBounds = this.c.getBoundingClientRect();
    const characterBounds = [];
    const offsetTransformer = new $hD(this.a.text);
    for (let offset = e.rangeStart; offset < e.rangeEnd; offset++) {
      const editContextStartPosition = offsetTransformer.getPosition(offset);
      const textStartLineOffsetWithinEditor = this.j.lineNumber - 1;
      const characterStartPosition = new $8C(textStartLineOffsetWithinEditor + editContextStartPosition.lineNumber, editContextStartPosition.column);
      const characterEndPosition = characterStartPosition.delta(0, 1);
      const characterModelRange = $9C.fromPositions(characterStartPosition, characterEndPosition);
      const characterViewRange = this._context.viewModel.coordinatesConverter.convertModelRangeToViewRange(characterModelRange);
      const characterLinesVisibleRanges = this.z.linesVisibleRangesForRange(characterViewRange, true) ?? [];
      const characterVerticalOffset = this._context.viewLayout.getVerticalOffsetForLineNumber(characterViewRange.startLineNumber);
      const top2 = parentBounds.top + characterVerticalOffset - this.s;
      let left = 0;
      let width2 = typicalHalfWidthCharacterWidth;
      if (characterLinesVisibleRanges.length > 0) {
        for (const visibleRange of characterLinesVisibleRanges[0].ranges) {
          left = visibleRange.left;
          width2 = visibleRange.width;
          break;
        }
      }
      characterBounds.push(new DOMRect(parentBounds.left + contentLeft + left - this.t, top2, width2, lineHeight));
    }
    this.a.updateCharacterBounds(e.rangeStart, characterBounds);
  }
  N(e) {
    const options3 = this._context.configuration.options;
    const emptySelectionClipboard = options3.get(
      38
      /* EditorOption.emptySelectionClipboard */
    );
    const copyWithSyntaxHighlighting = options3.get(
      25
      /* EditorOption.copyWithSyntaxHighlighting */
    );
    const selections = this._context.viewModel.getCursorStates().map((cursorState) => cursorState.modelState.selection);
    const dataToCopy = $37(this._context.viewModel, selections, emptySelectionClipboard, copyWithSyntaxHighlighting);
    const storedMetadata = {
      version: 1,
      isFromEmptySelection: dataToCopy.isFromEmptySelection,
      multicursorText: dataToCopy.multicursorText,
      mode: dataToCopy.mode
    };
    $47.INSTANCE.set(
      // When writing "LINE\r\n" to the clipboard and then pasting,
      // Firefox pastes "LINE\n", so let's work around this quirk
      $Ue ? dataToCopy.text.replace(/\r\n/g, "\n") : dataToCopy.text,
      storedMetadata
    );
    e.preventDefault();
    if (e.clipboardData) {
      $67.setTextData(e.clipboardData, dataToCopy.text, dataToCopy.html, storedMetadata);
    }
  }
  O(viewController) {
    let previousSelectionChangeEventTime = 0;
    return $_i(this.domNode.domNode.ownerDocument, "selectionchange", () => {
      const isScreenReaderOptimized = this.C.isScreenReaderOptimized();
      if (!this.isFocused() || !isScreenReaderOptimized) {
        return;
      }
      const screenReaderContentState = this.b.screenReaderContentState;
      if (!screenReaderContentState) {
        return;
      }
      const now = Date.now();
      const delta1 = now - previousSelectionChangeEventTime;
      previousSelectionChangeEventTime = now;
      if (delta1 < 5) {
        return;
      }
      const delta2 = now - this.b.getIgnoreSelectionChangeTime();
      this.b.resetSelectionChangeTime();
      if (delta2 < 100) {
        return;
      }
      const activeDocument = $Qj().document;
      const activeDocumentSelection = activeDocument.getSelection();
      if (!activeDocumentSelection) {
        return;
      }
      const rangeCount = activeDocumentSelection.rangeCount;
      if (rangeCount === 0) {
        return;
      }
      const range = activeDocumentSelection.getRangeAt(0);
      const viewModel = this._context.viewModel;
      const model = viewModel.model;
      const coordinatesConverter = viewModel.coordinatesConverter;
      const modelScreenReaderContentStartPositionWithinEditor = coordinatesConverter.convertViewPositionToModelPosition(screenReaderContentState.startPositionWithinEditor);
      const offsetOfStartOfScreenReaderContent = model.getOffsetAt(modelScreenReaderContentStartPositionWithinEditor);
      let offsetOfSelectionStart = range.startOffset + offsetOfStartOfScreenReaderContent;
      let offsetOfSelectionEnd = range.endOffset + offsetOfStartOfScreenReaderContent;
      const modelUsesCRLF = model.getEndOfLineSequence() === 1;
      if (modelUsesCRLF) {
        const screenReaderContentText = screenReaderContentState.value;
        const offsetTransformer = new $hD(screenReaderContentText);
        const positionOfStartWithinText = offsetTransformer.getPosition(range.startOffset);
        const positionOfEndWithinText = offsetTransformer.getPosition(range.endOffset);
        offsetOfSelectionStart += positionOfStartWithinText.lineNumber - 1;
        offsetOfSelectionEnd += positionOfEndWithinText.lineNumber - 1;
      }
      const positionOfSelectionStart = model.getPositionAt(offsetOfSelectionStart);
      const positionOfSelectionEnd = model.getPositionAt(offsetOfSelectionEnd);
      const newSelection = $_D.fromPositions(positionOfSelectionStart, positionOfSelectionEnd);
      viewController.setSelection(newSelection);
    });
  }
};
$X8 = __decorate([
  __param(5, $Pk),
  __param(6, $ND)
], $X8);

// out-build/vs/editor/browser/viewParts/rulersGpu/rulersGpu.js
var $Y8 = class extends $f7 {
  constructor(context, f) {
    super(context);
    this.f = f;
    this.c = [];
    this.B($td((reader) => this.h(reader)));
  }
  // --- begin event handlers
  onConfigurationChanged(e) {
    this.h(void 0);
    return true;
  }
  // --- end event handlers
  prepareRender(ctx) {
  }
  render(ctx) {
  }
  h(reader) {
    const options3 = this._context.configuration.options;
    const rulers = options3.get(
      107
      /* EditorOption.rulers */
    );
    const typicalHalfwidthCharacterWidth = options3.get(
      52
      /* EditorOption.fontInfo */
    ).typicalHalfwidthCharacterWidth;
    const devicePixelRatio = this.f.devicePixelRatio.read(reader);
    for (let i2 = 0, len = rulers.length; i2 < len; i2++) {
      const ruler = rulers[i2];
      const shape = this.c[i2];
      const color2 = ruler.color ? $Vn.fromHex(ruler.color) : this._context.theme.getColor($dH) ?? $Vn.white;
      const rulerData = [
        ruler.column * typicalHalfwidthCharacterWidth * devicePixelRatio,
        0,
        Math.max(1, Math.ceil(devicePixelRatio)),
        Number.MAX_SAFE_INTEGER,
        color2.rgba.r / 255,
        color2.rgba.g / 255,
        color2.rgba.b / 255,
        color2.rgba.a
      ];
      if (!shape) {
        this.c[i2] = this.f.rectangleRenderer.register(...rulerData);
      } else {
        shape.setRaw(rulerData);
      }
    }
    while (this.c.length > rulers.length) {
      this.c.splice(-1, 1)[0].dispose();
    }
  }
};

// out-build/vs/editor/browser/viewParts/gpuMark/gpuMark.js
var $Z8 = class _$Z8 extends $d8 {
  static {
    this.CLASS_NAME = "gpu-mark";
  }
  constructor(context, c) {
    super();
    this.c = c;
    this.a = context;
    this.b = null;
    this.a.addEventHandler(this);
  }
  dispose() {
    this.a.removeEventHandler(this);
    this.b = null;
    super.dispose();
  }
  // --- begin event handlers
  onConfigurationChanged(e) {
    return true;
  }
  onCursorStateChanged(e) {
    return true;
  }
  onFlushed(e) {
    return true;
  }
  onLinesChanged(e) {
    return true;
  }
  onLinesDeleted(e) {
    return true;
  }
  onLinesInserted(e) {
    return true;
  }
  onScrollChanged(e) {
    return e.scrollTopChanged;
  }
  onZonesChanged(e) {
    return true;
  }
  onDecorationsChanged(e) {
    return true;
  }
  // --- end event handlers
  prepareRender(ctx) {
    const visibleStartLineNumber = ctx.visibleRange.startLineNumber;
    const visibleEndLineNumber = ctx.visibleRange.endLineNumber;
    const viewportData = ctx.viewportData;
    const options3 = new $x7(this.a.configuration, this.a.theme.type);
    const output = [];
    for (let lineNumber = visibleStartLineNumber; lineNumber <= visibleEndLineNumber; lineNumber++) {
      const lineIndex = lineNumber - visibleStartLineNumber;
      const cannotRenderReasons = this.c.canRenderDetailed(options3, viewportData, lineNumber);
      output[lineIndex] = cannotRenderReasons.length ? `<div class="${_$Z8.CLASS_NAME}" title="Cannot render on GPU: ${cannotRenderReasons.join(", ")}"></div>` : "";
    }
    this.b = output;
  }
  render(startLineNumber, lineNumber) {
    if (!this.b) {
      return "";
    }
    const lineIndex = lineNumber - startLineNumber;
    if (lineIndex < 0 || lineIndex >= this.b.length) {
      return "";
    }
    return this.b[lineIndex];
  }
};

// out-build/vs/editor/browser/view.js
var $18 = class $182 extends $D5 {
  constructor(ownerID, commandDelegate, configuration2, colorTheme, model, userInputEvents, overflowWidgetsDomNode, N) {
    super();
    this.N = N;
    this.J = false;
    this.M = ownerID;
    this.h = [new $_D(1, 1, 1, 1)];
    this.L = null;
    this.I = $oZ(document.createElement("div"));
    $g7.write(
      this.I,
      3
      /* PartFingerprint.OverflowGuard */
    );
    this.I.setClassName("overflow-guard");
    this.C = new $17(configuration2, model, userInputEvents, commandDelegate);
    this.f = new $e7(configuration2, colorTheme, model);
    this.f.addEventHandler(this);
    this.z = [];
    this.D = this.f.configuration.options.get(
      37
      /* EditorOption.experimentalEditContextEnabled */
    );
    this.F = this.O(this.D);
    this.z.push(this.F);
    this.H = $oZ(document.createElement("div"));
    this.H.setClassName("lines-content monaco-editor-background");
    this.H.setPosition("absolute");
    this.domNode = $oZ(document.createElement("div"));
    this.domNode.setClassName(this.W());
    this.domNode.setAttribute("role", "code");
    if (this.f.configuration.options.get(
      39
      /* EditorOption.experimentalGpuAcceleration */
    ) === "on") {
      this.g = this.N.createInstance($O7, this.f);
    }
    this.c = new $o8(this.f, this.H, this.domNode, this.I);
    this.z.push(this.c);
    this.j = new $w8(this.f, this.g, this.H);
    if (this.g) {
      this.n = this.N.createInstance($U7, this.f, this.g);
    }
    this.r = new $P8(this.f);
    this.z.push(this.r);
    const decorationsOverviewRuler = new $J8(this.f);
    this.z.push(decorationsOverviewRuler);
    const scrollDecoration = new $M8(this.f);
    this.z.push(scrollDecoration);
    const contentViewOverlays = new $g8(this.f);
    this.z.push(contentViewOverlays);
    contentViewOverlays.addDynamicOverlay(new $l8(this.f));
    contentViewOverlays.addDynamicOverlay(new $N8(this.f));
    contentViewOverlays.addDynamicOverlay(new $u8(this.f));
    contentViewOverlays.addDynamicOverlay(new $n8(this.f));
    contentViewOverlays.addDynamicOverlay(new $Q8(this.f));
    const marginViewOverlays = new $h8(this.f);
    this.z.push(marginViewOverlays);
    marginViewOverlays.addDynamicOverlay(new $m8(this.f));
    marginViewOverlays.addDynamicOverlay(new $z8(this.f));
    marginViewOverlays.addDynamicOverlay(new $x8(this.f));
    marginViewOverlays.addDynamicOverlay(new $v8(this.f));
    if (this.g) {
      marginViewOverlays.addDynamicOverlay(new $Z8(this.f, this.g));
    }
    this.w = new $t8(this.f);
    this.z.push(this.w);
    const margin = new $y8(this.f);
    margin.getDomNode().appendChild(this.r.marginDomNode);
    margin.getDomNode().appendChild(marginViewOverlays.getDomNode());
    margin.getDomNode().appendChild(this.w.domNode);
    this.z.push(margin);
    this.s = new $j8(this.f, this.domNode);
    this.z.push(this.s);
    this.y = new $O8(this.f);
    this.z.push(this.y);
    this.t = new $I8(this.f, this.domNode);
    this.z.push(this.t);
    const rulers = this.g ? new $Y8(this.f, this.g) : new $L8(this.f);
    this.z.push(rulers);
    const blockOutline = new $i8(this.f);
    this.z.push(blockOutline);
    const minimap = new $H8(this.f);
    this.z.push(minimap);
    if (decorationsOverviewRuler) {
      const overviewRulerData = this.c.getOverviewRulerLayoutInfo();
      overviewRulerData.parent.insertBefore(decorationsOverviewRuler.getDomNode(), overviewRulerData.insertBefore);
    }
    this.H.appendChild(contentViewOverlays.getDomNode());
    if ("domNode" in rulers) {
      this.H.appendChild(rulers.domNode);
    }
    this.H.appendChild(this.r.domNode);
    this.H.appendChild(this.j.getDomNode());
    this.H.appendChild(this.s.domNode);
    this.H.appendChild(this.y.getDomNode());
    this.I.appendChild(margin.getDomNode());
    this.I.appendChild(this.c.getDomNode());
    if (this.g) {
      this.I.appendChild(this.g.canvas);
    }
    this.I.appendChild(scrollDecoration.getDomNode());
    this.I.appendChild(this.t.getDomNode());
    this.I.appendChild(minimap.getDomNode());
    this.I.appendChild(blockOutline.domNode);
    this.domNode.appendChild(this.I);
    if (overflowWidgetsDomNode) {
      overflowWidgetsDomNode.appendChild(this.s.overflowingContentWidgetsDomNode.domNode);
      overflowWidgetsDomNode.appendChild(this.t.overflowingOverlayWidgetsDomNode.domNode);
    } else {
      this.domNode.appendChild(this.s.overflowingContentWidgetsDomNode);
      this.domNode.appendChild(this.t.overflowingOverlayWidgetsDomNode);
    }
    this.U();
    this.G = this.B(new $c8(this.f, this.C, this.R()));
  }
  O(experimentalEditContextEnabled) {
    const domNode = getWindow(this.I.domNode);
    const isEditContextSupported = EditContext.supported(domNode);
    if (experimentalEditContextEnabled && isEditContextSupported) {
      return this.N.createInstance($X8, this.M, this.f, this.I, this.C, this.S());
    } else {
      return this.N.createInstance($S8, this.f, this.I, this.C, this.S());
    }
  }
  P() {
    const experimentalEditContextEnabled = this.f.configuration.options.get(
      37
      /* EditorOption.experimentalEditContextEnabled */
    );
    if (this.D === experimentalEditContextEnabled) {
      return;
    }
    this.D = experimentalEditContextEnabled;
    const isEditContextFocused = this.F.isFocused();
    const indexOfEditContext = this.z.indexOf(this.F);
    this.F.dispose();
    this.F = this.O(experimentalEditContextEnabled);
    if (isEditContextFocused) {
      this.F.focus();
    }
    if (indexOfEditContext !== -1) {
      this.z.splice(indexOfEditContext, 1, this.F);
    }
  }
  Q() {
    const model = this.f.viewModel.model;
    const laneModel = this.f.viewModel.glyphLanes;
    let glyphs = [];
    let maxLineNumber = 0;
    glyphs = glyphs.concat(model.getAllMarginDecorations().map((decoration3) => {
      const lane = decoration3.options.glyphMargin?.position ?? GlyphMarginLane.Center;
      maxLineNumber = Math.max(maxLineNumber, decoration3.range.endLineNumber);
      return { range: decoration3.range, lane, persist: decoration3.options.glyphMargin?.persistLane };
    }));
    glyphs = glyphs.concat(this.w.getWidgets().map((widget) => {
      const range = model.validateRange(widget.preference.range);
      maxLineNumber = Math.max(maxLineNumber, range.endLineNumber);
      return { range, lane: widget.preference.lane };
    }));
    glyphs.sort((a, b) => $9C.compareRangesUsingStarts(a.range, b.range));
    laneModel.reset(maxLineNumber);
    for (const glyph of glyphs) {
      laneModel.push(glyph.lane, glyph.range, glyph.persist);
    }
    return laneModel;
  }
  R() {
    return {
      viewDomNode: this.domNode.domNode,
      linesContentDomNode: this.H.domNode,
      viewLinesDomNode: this.j.getDomNode().domNode,
      viewLinesGpu: this.n,
      focusTextArea: () => {
        this.focus();
      },
      dispatchTextAreaEvent: (event) => {
        this.F.domNode.domNode.dispatchEvent(event);
      },
      getLastRenderData: () => {
        const lastViewCursorsRenderData = this.y.getLastRenderData() || [];
        const lastTextareaPosition = this.F.getLastRenderData();
        return new $V7(lastViewCursorsRenderData, lastTextareaPosition);
      },
      renderNow: () => {
        this.render(true, false);
      },
      shouldSuppressMouseDownOnViewZone: (viewZoneId) => {
        return this.r.shouldSuppressMouseDownOnViewZone(viewZoneId);
      },
      shouldSuppressMouseDownOnWidget: (widgetId) => {
        return this.s.shouldSuppressMouseDownOnWidget(widgetId);
      },
      getPositionFromDOMInfo: (spanNode, offset) => {
        this.Y();
        return this.j.getPositionFromDOMInfo(spanNode, offset);
      },
      visibleRangeForPosition: (lineNumber, column) => {
        this.Y();
        const position = new $8C(lineNumber, column);
        return this.j.visibleRangeForPosition(position) ?? this.n?.visibleRangeForPosition(position) ?? null;
      },
      getLineWidth: (lineNumber) => {
        this.Y();
        if (this.n) {
          const result = this.n.getLineWidth(lineNumber);
          if (result !== void 0) {
            return result;
          }
        }
        return this.j.getLineWidth(lineNumber);
      }
    };
  }
  S() {
    return {
      visibleRangeForPosition: (position) => {
        this.Y();
        return this.j.visibleRangeForPosition(position);
      },
      linesVisibleRangesForRange: (range, includeNewLines) => {
        this.Y();
        return this.j.linesVisibleRangesForRange(range, includeNewLines);
      }
    };
  }
  U() {
    const options3 = this.f.configuration.options;
    const layoutInfo = options3.get(
      151
      /* EditorOption.layoutInfo */
    );
    this.domNode.setWidth(layoutInfo.width);
    this.domNode.setHeight(layoutInfo.height);
    this.I.setWidth(layoutInfo.width);
    this.I.setHeight(layoutInfo.height);
    this.H.setWidth(16777216);
    this.H.setHeight(16777216);
  }
  W() {
    const focused = this.F.isFocused() ? " focused" : "";
    return this.f.configuration.options.get(
      148
      /* EditorOption.editorClassName */
    ) + " " + $ks(this.f.theme.type) + focused;
  }
  // --- begin event handlers
  handleEvents(events) {
    super.handleEvents(events);
    this.X();
  }
  onConfigurationChanged(e) {
    this.domNode.setClassName(this.W());
    this.P();
    this.U();
    return false;
  }
  onCursorStateChanged(e) {
    this.h = e.selections;
    return false;
  }
  onDecorationsChanged(e) {
    if (e.affectsGlyphMargin) {
      this.J = true;
    }
    return false;
  }
  onFocusChanged(e) {
    this.domNode.setClassName(this.W());
    return false;
  }
  onThemeChanged(e) {
    this.f.theme.update(e.theme);
    this.domNode.setClassName(this.W());
    return false;
  }
  // --- end event handlers
  dispose() {
    if (this.L !== null) {
      this.L.dispose();
      this.L = null;
    }
    this.s.overflowingContentWidgetsDomNode.domNode.remove();
    this.t.overflowingOverlayWidgetsDomNode.domNode.remove();
    this.f.removeEventHandler(this);
    this.g?.dispose();
    this.j.dispose();
    this.n?.dispose();
    for (const viewPart of this.z) {
      viewPart.dispose();
    }
    super.dispose();
  }
  X() {
    if (this.q.isDisposed) {
      throw new $vb();
    }
    if (this.L === null) {
      if (this.F instanceof $X8) {
        this.F.setEditContextOnDomNode();
      }
      const rendering = this.$();
      this.L = EditorRenderingCoordinator.INSTANCE.scheduleCoordinatedRendering({
        window: getWindow(this.domNode?.domNode),
        prepareRenderText: () => {
          if (this.q.isDisposed) {
            throw new $vb();
          }
          try {
            return rendering.prepareRenderText();
          } finally {
            this.L = null;
          }
        },
        renderText: () => {
          if (this.q.isDisposed) {
            throw new $vb();
          }
          return rendering.renderText();
        },
        prepareRender: (viewParts, ctx) => {
          if (this.q.isDisposed) {
            throw new $vb();
          }
          return rendering.prepareRender(viewParts, ctx);
        },
        render: (viewParts, ctx) => {
          if (this.q.isDisposed) {
            throw new $vb();
          }
          return rendering.render(viewParts, ctx);
        }
      });
    }
  }
  Y() {
    const rendering = this.$();
    safeInvokeNoArg(() => rendering.prepareRenderText());
    const data = safeInvokeNoArg(() => rendering.renderText());
    if (data) {
      const [viewParts, ctx] = data;
      safeInvokeNoArg(() => rendering.prepareRender(viewParts, ctx));
      safeInvokeNoArg(() => rendering.render(viewParts, ctx));
    }
  }
  Z() {
    const result = [];
    let resultLen = 0;
    for (const viewPart of this.z) {
      if (viewPart.shouldRender()) {
        result[resultLen++] = viewPart;
      }
    }
    return result;
  }
  $() {
    return {
      prepareRenderText: () => {
        if (this.J) {
          this.J = false;
          const model = this.Q();
          this.f.configuration.setGlyphMarginDecorationLaneCount(model.requiredLanes);
        }
        inputLatency.onRenderStart();
      },
      renderText: () => {
        if (!this.domNode.domNode.isConnected) {
          return null;
        }
        let viewPartsToRender = this.Z();
        if (!this.j.shouldRender() && viewPartsToRender.length === 0) {
          return null;
        }
        const partialViewportData = this.f.viewLayout.getLinesViewportData();
        this.f.viewModel.setViewport(partialViewportData.startLineNumber, partialViewportData.endLineNumber, partialViewportData.centeredLineNumber);
        const viewportData = new $96(this.h, partialViewportData, this.f.viewLayout.getWhitespaceViewportData(), this.f.viewModel);
        if (this.s.shouldRender()) {
          this.s.onBeforeRender(viewportData);
        }
        if (this.j.shouldRender()) {
          this.j.renderText(viewportData);
          this.j.onDidRender();
          viewPartsToRender = this.Z();
        }
        if (this.n?.shouldRender()) {
          this.n.renderText(viewportData);
          this.n.onDidRender();
        }
        return [viewPartsToRender, new $$6(this.f.viewLayout, viewportData, this.j, this.n)];
      },
      prepareRender: (viewPartsToRender, ctx) => {
        for (const viewPart of viewPartsToRender) {
          viewPart.prepareRender(ctx);
        }
      },
      render: (viewPartsToRender, ctx) => {
        for (const viewPart of viewPartsToRender) {
          viewPart.render(ctx);
          viewPart.onDidRender();
        }
      }
    };
  }
  // --- BEGIN CodeEditor helpers
  delegateVerticalScrollbarPointerDown(browserEvent) {
    this.c.delegateVerticalScrollbarPointerDown(browserEvent);
  }
  delegateScrollFromMouseWheelEvent(browserEvent) {
    this.c.delegateScrollFromMouseWheelEvent(browserEvent);
  }
  restoreState(scrollPosition) {
    this.f.viewModel.viewLayout.setScrollPosition(
      {
        scrollTop: scrollPosition.scrollTop,
        scrollLeft: scrollPosition.scrollLeft
      },
      1
      /* ScrollType.Immediate */
    );
    this.f.viewModel.visibleLinesStabilized();
  }
  getOffsetForColumn(modelLineNumber, modelColumn) {
    const modelPosition = this.f.viewModel.model.validatePosition({
      lineNumber: modelLineNumber,
      column: modelColumn
    });
    const viewPosition = this.f.viewModel.coordinatesConverter.convertModelPositionToViewPosition(modelPosition);
    this.Y();
    const visibleRange = this.j.visibleRangeForPosition(new $8C(viewPosition.lineNumber, viewPosition.column));
    if (!visibleRange) {
      return -1;
    }
    return visibleRange.left;
  }
  getTargetAtClientPoint(clientX, clientY) {
    const mouseTarget = this.G.getTargetAtClientPoint(clientX, clientY);
    if (!mouseTarget) {
      return null;
    }
    return $Z7.convertViewToModelMouseTarget(mouseTarget, this.f.viewModel.coordinatesConverter);
  }
  createOverviewRuler(cssClassName) {
    return new $K8(this.f, cssClassName);
  }
  change(callback) {
    this.r.changeViewZones(callback);
    this.X();
  }
  render(now, everything) {
    if (everything) {
      this.j.forceShouldRender();
      for (const viewPart of this.z) {
        viewPart.forceShouldRender();
      }
    }
    if (now) {
      this.Y();
    } else {
      this.X();
    }
  }
  writeScreenReaderContent(reason) {
    this.F.writeScreenReaderContent(reason);
  }
  focus() {
    this.F.focus();
  }
  isFocused() {
    return this.F.isFocused();
  }
  refreshFocusState() {
    this.F.refreshFocusState();
  }
  setAriaOptions(options3) {
    this.F.setAriaOptions(options3);
  }
  addContentWidget(widgetData) {
    this.s.addWidget(widgetData.widget);
    this.layoutContentWidget(widgetData);
    this.X();
  }
  layoutContentWidget(widgetData) {
    this.s.setWidgetPosition(widgetData.widget, widgetData.position?.position ?? null, widgetData.position?.secondaryPosition ?? null, widgetData.position?.preference ?? null, widgetData.position?.positionAffinity ?? null);
    this.X();
  }
  removeContentWidget(widgetData) {
    this.s.removeWidget(widgetData.widget);
    this.X();
  }
  addOverlayWidget(widgetData) {
    this.t.addWidget(widgetData.widget);
    this.layoutOverlayWidget(widgetData);
    this.X();
  }
  layoutOverlayWidget(widgetData) {
    const shouldRender = this.t.setWidgetPosition(widgetData.widget, widgetData.position);
    if (shouldRender) {
      this.X();
    }
  }
  removeOverlayWidget(widgetData) {
    this.t.removeWidget(widgetData.widget);
    this.X();
  }
  addGlyphMarginWidget(widgetData) {
    this.w.addWidget(widgetData.widget);
    this.J = true;
    this.X();
  }
  layoutGlyphMarginWidget(widgetData) {
    const newPreference = widgetData.position;
    const shouldRender = this.w.setWidgetPosition(widgetData.widget, newPreference);
    if (shouldRender) {
      this.J = true;
      this.X();
    }
  }
  removeGlyphMarginWidget(widgetData) {
    this.w.removeWidget(widgetData.widget);
    this.J = true;
    this.X();
  }
};
$18 = __decorate([
  __param(7, $Pk)
], $18);
function safeInvokeNoArg(func) {
  try {
    return func();
  } catch (e) {
    $gb(e);
    return null;
  }
}
var EditorRenderingCoordinator = class _EditorRenderingCoordinator {
  static {
    this.INSTANCE = new _EditorRenderingCoordinator();
  }
  constructor() {
    this.c = [];
    this.d = /* @__PURE__ */ new Map();
  }
  scheduleCoordinatedRendering(rendering) {
    this.c.push(rendering);
    this.f(rendering.window);
    return {
      dispose: () => {
        const renderingIndex = this.c.indexOf(rendering);
        if (renderingIndex === -1) {
          return;
        }
        this.c.splice(renderingIndex, 1);
        if (this.c.length === 0) {
          for (const [_, disposable] of this.d) {
            disposable.dispose();
          }
          this.d.clear();
        }
      }
    };
  }
  f(window3) {
    if (!this.d.has(window3)) {
      const runner = () => {
        this.d.delete(window3);
        this.g();
      };
      this.d.set(window3, $ij(window3, runner, 100));
    }
  }
  g() {
    const coordinatedRenderings = this.c.slice(0);
    this.c = [];
    for (const rendering of coordinatedRenderings) {
      safeInvokeNoArg(() => rendering.prepareRenderText());
    }
    const datas = [];
    for (let i2 = 0, len = coordinatedRenderings.length; i2 < len; i2++) {
      const rendering = coordinatedRenderings[i2];
      datas[i2] = safeInvokeNoArg(() => rendering.renderText());
    }
    for (let i2 = 0, len = coordinatedRenderings.length; i2 < len; i2++) {
      const rendering = coordinatedRenderings[i2];
      const data = datas[i2];
      if (!data) {
        continue;
      }
      const [viewParts, ctx] = data;
      safeInvokeNoArg(() => rendering.prepareRender(viewParts, ctx));
    }
    for (let i2 = 0, len = coordinatedRenderings.length; i2 < len; i2++) {
      const rendering = coordinatedRenderings[i2];
      const data = datas[i2];
      if (!data) {
        continue;
      }
      const [viewParts, ctx] = data;
      safeInvokeNoArg(() => rendering.render(viewParts, ctx));
    }
  }
};

// out-build/vs/editor/common/modelLineProjectionData.js
var $a5 = class {
  constructor(injectionOffsets, injectionOptions, breakOffsets, breakOffsetsVisibleColumn, wrappedTextIndentLength) {
    this.injectionOffsets = injectionOffsets;
    this.injectionOptions = injectionOptions;
    this.breakOffsets = breakOffsets;
    this.breakOffsetsVisibleColumn = breakOffsetsVisibleColumn;
    this.wrappedTextIndentLength = wrappedTextIndentLength;
  }
  getOutputLineCount() {
    return this.breakOffsets.length;
  }
  getMinOutputOffset(outputLineIndex) {
    if (outputLineIndex > 0) {
      return this.wrappedTextIndentLength;
    }
    return 0;
  }
  getLineLength(outputLineIndex) {
    const startOffset = outputLineIndex > 0 ? this.breakOffsets[outputLineIndex - 1] : 0;
    const endOffset = this.breakOffsets[outputLineIndex];
    let lineLength = endOffset - startOffset;
    if (outputLineIndex > 0) {
      lineLength += this.wrappedTextIndentLength;
    }
    return lineLength;
  }
  getMaxOutputOffset(outputLineIndex) {
    return this.getLineLength(outputLineIndex);
  }
  translateToInputOffset(outputLineIndex, outputOffset) {
    if (outputLineIndex > 0) {
      outputOffset = Math.max(0, outputOffset - this.wrappedTextIndentLength);
    }
    const offsetInInputWithInjection = outputLineIndex === 0 ? outputOffset : this.breakOffsets[outputLineIndex - 1] + outputOffset;
    let offsetInInput = offsetInInputWithInjection;
    if (this.injectionOffsets !== null) {
      for (let i2 = 0; i2 < this.injectionOffsets.length; i2++) {
        if (offsetInInput > this.injectionOffsets[i2]) {
          if (offsetInInput < this.injectionOffsets[i2] + this.injectionOptions[i2].content.length) {
            offsetInInput = this.injectionOffsets[i2];
          } else {
            offsetInInput -= this.injectionOptions[i2].content.length;
          }
        } else {
          break;
        }
      }
    }
    return offsetInInput;
  }
  translateToOutputPosition(inputOffset, affinity = 2) {
    let inputOffsetInInputWithInjection = inputOffset;
    if (this.injectionOffsets !== null) {
      for (let i2 = 0; i2 < this.injectionOffsets.length; i2++) {
        if (inputOffset < this.injectionOffsets[i2]) {
          break;
        }
        if (affinity !== 1 && inputOffset === this.injectionOffsets[i2]) {
          break;
        }
        inputOffsetInInputWithInjection += this.injectionOptions[i2].content.length;
      }
    }
    return this.a(inputOffsetInInputWithInjection, affinity);
  }
  a(offsetInInputWithInjections, affinity = 2) {
    let low = 0;
    let high = this.breakOffsets.length - 1;
    let mid = 0;
    let midStart = 0;
    while (low <= high) {
      mid = low + (high - low) / 2 | 0;
      const midStop = this.breakOffsets[mid];
      midStart = mid > 0 ? this.breakOffsets[mid - 1] : 0;
      if (affinity === 0) {
        if (offsetInInputWithInjections <= midStart) {
          high = mid - 1;
        } else if (offsetInInputWithInjections > midStop) {
          low = mid + 1;
        } else {
          break;
        }
      } else {
        if (offsetInInputWithInjections < midStart) {
          high = mid - 1;
        } else if (offsetInInputWithInjections >= midStop) {
          low = mid + 1;
        } else {
          break;
        }
      }
    }
    let outputOffset = offsetInInputWithInjections - midStart;
    if (mid > 0) {
      outputOffset += this.wrappedTextIndentLength;
    }
    return new $c5(mid, outputOffset);
  }
  normalizeOutputPosition(outputLineIndex, outputOffset, affinity) {
    if (this.injectionOffsets !== null) {
      const offsetInInputWithInjections = this.b(outputLineIndex, outputOffset);
      const normalizedOffsetInUnwrappedLine = this.c(offsetInInputWithInjections, affinity);
      if (normalizedOffsetInUnwrappedLine !== offsetInInputWithInjections) {
        return this.a(normalizedOffsetInUnwrappedLine, affinity);
      }
    }
    if (affinity === 0) {
      if (outputLineIndex > 0 && outputOffset === this.getMinOutputOffset(outputLineIndex)) {
        return new $c5(outputLineIndex - 1, this.getMaxOutputOffset(outputLineIndex - 1));
      }
    } else if (affinity === 1) {
      const maxOutputLineIndex = this.getOutputLineCount() - 1;
      if (outputLineIndex < maxOutputLineIndex && outputOffset === this.getMaxOutputOffset(outputLineIndex)) {
        return new $c5(outputLineIndex + 1, this.getMinOutputOffset(outputLineIndex + 1));
      }
    }
    return new $c5(outputLineIndex, outputOffset);
  }
  b(outputLineIndex, outputOffset) {
    if (outputLineIndex > 0) {
      outputOffset = Math.max(0, outputOffset - this.wrappedTextIndentLength);
    }
    const result = (outputLineIndex > 0 ? this.breakOffsets[outputLineIndex - 1] : 0) + outputOffset;
    return result;
  }
  c(offsetInInputWithInjections, affinity) {
    const injectedText = this.d(offsetInInputWithInjections);
    if (!injectedText) {
      return offsetInInputWithInjections;
    }
    if (affinity === 2) {
      if (offsetInInputWithInjections === injectedText.offsetInInputWithInjections + injectedText.length && hasRightCursorStop(this.injectionOptions[injectedText.injectedTextIndex].cursorStops)) {
        return injectedText.offsetInInputWithInjections + injectedText.length;
      } else {
        let result = injectedText.offsetInInputWithInjections;
        if (hasLeftCursorStop(this.injectionOptions[injectedText.injectedTextIndex].cursorStops)) {
          return result;
        }
        let index = injectedText.injectedTextIndex - 1;
        while (index >= 0 && this.injectionOffsets[index] === this.injectionOffsets[injectedText.injectedTextIndex]) {
          if (hasRightCursorStop(this.injectionOptions[index].cursorStops)) {
            break;
          }
          result -= this.injectionOptions[index].content.length;
          if (hasLeftCursorStop(this.injectionOptions[index].cursorStops)) {
            break;
          }
          index--;
        }
        return result;
      }
    } else if (affinity === 1 || affinity === 4) {
      let result = injectedText.offsetInInputWithInjections + injectedText.length;
      let index = injectedText.injectedTextIndex;
      while (index + 1 < this.injectionOffsets.length && this.injectionOffsets[index + 1] === this.injectionOffsets[index]) {
        result += this.injectionOptions[index + 1].content.length;
        index++;
      }
      return result;
    } else if (affinity === 0 || affinity === 3) {
      let result = injectedText.offsetInInputWithInjections;
      let index = injectedText.injectedTextIndex;
      while (index - 1 >= 0 && this.injectionOffsets[index - 1] === this.injectionOffsets[index]) {
        result -= this.injectionOptions[index - 1].content.length;
        index--;
      }
      return result;
    }
    $hd(affinity);
  }
  getInjectedText(outputLineIndex, outputOffset) {
    const offset = this.b(outputLineIndex, outputOffset);
    const injectedText = this.d(offset);
    if (!injectedText) {
      return null;
    }
    return {
      options: this.injectionOptions[injectedText.injectedTextIndex]
    };
  }
  d(offsetInInputWithInjections) {
    const injectionOffsets = this.injectionOffsets;
    const injectionOptions = this.injectionOptions;
    if (injectionOffsets !== null) {
      let totalInjectedTextLengthBefore = 0;
      for (let i2 = 0; i2 < injectionOffsets.length; i2++) {
        const length = injectionOptions[i2].content.length;
        const injectedTextStartOffsetInInputWithInjections = injectionOffsets[i2] + totalInjectedTextLengthBefore;
        const injectedTextEndOffsetInInputWithInjections = injectionOffsets[i2] + totalInjectedTextLengthBefore + length;
        if (injectedTextStartOffsetInInputWithInjections > offsetInInputWithInjections) {
          break;
        }
        if (offsetInInputWithInjections <= injectedTextEndOffsetInInputWithInjections) {
          return {
            injectedTextIndex: i2,
            offsetInInputWithInjections: injectedTextStartOffsetInInputWithInjections,
            length
          };
        }
        totalInjectedTextLengthBefore += length;
      }
    }
    return void 0;
  }
};
function hasRightCursorStop(cursorStop) {
  if (cursorStop === null || cursorStop === void 0) {
    return true;
  }
  return cursorStop === InjectedTextCursorStops.Right || cursorStop === InjectedTextCursorStops.Both;
}
function hasLeftCursorStop(cursorStop) {
  if (cursorStop === null || cursorStop === void 0) {
    return true;
  }
  return cursorStop === InjectedTextCursorStops.Left || cursorStop === InjectedTextCursorStops.Both;
}
var $c5 = class {
  constructor(outputLineIndex, outputOffset) {
    this.outputLineIndex = outputLineIndex;
    this.outputOffset = outputOffset;
  }
  toString() {
    return `${this.outputLineIndex}:${this.outputOffset}`;
  }
  toPosition(baseLineNumber) {
    return new $8C(baseLineNumber + this.outputLineIndex, this.outputOffset + 1);
  }
};

// out-build/vs/editor/common/textModelEvents.js
var RawContentChangedType;
(function(RawContentChangedType2) {
  RawContentChangedType2[RawContentChangedType2["Flush"] = 1] = "Flush";
  RawContentChangedType2[RawContentChangedType2["LineChanged"] = 2] = "LineChanged";
  RawContentChangedType2[RawContentChangedType2["LinesDeleted"] = 3] = "LinesDeleted";
  RawContentChangedType2[RawContentChangedType2["LinesInserted"] = 4] = "LinesInserted";
  RawContentChangedType2[RawContentChangedType2["EOLChanged"] = 5] = "EOLChanged";
})(RawContentChangedType || (RawContentChangedType = {}));
var $EE = class {
  constructor() {
    this.changeType = 1;
  }
};
var $FE = class _$FE {
  static applyInjectedText(lineText, injectedTexts) {
    if (!injectedTexts || injectedTexts.length === 0) {
      return lineText;
    }
    let result = "";
    let lastOriginalOffset = 0;
    for (const injectedText of injectedTexts) {
      result += lineText.substring(lastOriginalOffset, injectedText.column - 1);
      lastOriginalOffset = injectedText.column - 1;
      result += injectedText.options.content;
    }
    result += lineText.substring(lastOriginalOffset);
    return result;
  }
  static fromDecorations(decorations) {
    const result = [];
    for (const decoration3 of decorations) {
      if (decoration3.options.before && decoration3.options.before.content.length > 0) {
        result.push(new _$FE(decoration3.ownerId, decoration3.range.startLineNumber, decoration3.range.startColumn, decoration3.options.before, 0));
      }
      if (decoration3.options.after && decoration3.options.after.content.length > 0) {
        result.push(new _$FE(decoration3.ownerId, decoration3.range.endLineNumber, decoration3.range.endColumn, decoration3.options.after, 1));
      }
    }
    result.sort((a, b) => {
      if (a.lineNumber === b.lineNumber) {
        if (a.column === b.column) {
          return a.order - b.order;
        }
        return a.column - b.column;
      }
      return a.lineNumber - b.lineNumber;
    });
    return result;
  }
  constructor(ownerId2, lineNumber, column, options3, order) {
    this.ownerId = ownerId2;
    this.lineNumber = lineNumber;
    this.column = column;
    this.options = options3;
    this.order = order;
  }
  withText(text2) {
    return new _$FE(this.ownerId, this.lineNumber, this.column, { ...this.options, content: text2 }, this.order);
  }
};
var $GE = class {
  constructor(lineNumber, detail2, injectedText) {
    this.changeType = 2;
    this.lineNumber = lineNumber;
    this.detail = detail2;
    this.injectedText = injectedText;
  }
};
var $HE = class {
  constructor(fromLineNumber, toLineNumber) {
    this.changeType = 3;
    this.fromLineNumber = fromLineNumber;
    this.toLineNumber = toLineNumber;
  }
};
var $IE = class {
  constructor(fromLineNumber, toLineNumber, detail2, injectedTexts) {
    this.changeType = 4;
    this.injectedTexts = injectedTexts;
    this.fromLineNumber = fromLineNumber;
    this.toLineNumber = toLineNumber;
    this.detail = detail2;
  }
};
var $JE = class {
  constructor() {
    this.changeType = 5;
  }
};
var $KE = class _$KE {
  constructor(changes, versionId, isUndoing, isRedoing) {
    this.changes = changes;
    this.versionId = versionId;
    this.isUndoing = isUndoing;
    this.isRedoing = isRedoing;
    this.resultingSelection = null;
  }
  containsEvent(type) {
    for (let i2 = 0, len = this.changes.length; i2 < len; i2++) {
      const change = this.changes[i2];
      if (change.changeType === type) {
        return true;
      }
    }
    return false;
  }
  static merge(a, b) {
    const changes = [].concat(a.changes).concat(b.changes);
    const versionId = b.versionId;
    const isUndoing = a.isUndoing || b.isUndoing;
    const isRedoing = a.isRedoing || b.isRedoing;
    return new _$KE(changes, versionId, isUndoing, isRedoing);
  }
};
var $LE = class {
  constructor(changes) {
    this.changes = changes;
  }
};
var $ME = class _$ME {
  constructor(rawContentChangedEvent, contentChangedEvent) {
    this.rawContentChangedEvent = rawContentChangedEvent;
    this.contentChangedEvent = contentChangedEvent;
  }
  merge(other) {
    const rawContentChangedEvent = $KE.merge(this.rawContentChangedEvent, other.rawContentChangedEvent);
    const contentChangedEvent = _$ME.c(this.contentChangedEvent, other.contentChangedEvent);
    return new _$ME(rawContentChangedEvent, contentChangedEvent);
  }
  static c(a, b) {
    const changes = [].concat(a.changes).concat(b.changes);
    const eol = b.eol;
    const versionId = b.versionId;
    const isUndoing = a.isUndoing || b.isUndoing;
    const isRedoing = a.isRedoing || b.isRedoing;
    const isFlush = a.isFlush || b.isFlush;
    const isEolChange = a.isEolChange && b.isEolChange;
    return {
      changes,
      eol,
      isEolChange,
      versionId,
      isUndoing,
      isRedoing,
      isFlush
    };
  }
};

// out-build/vs/editor/browser/view/domLineBreaksComputer.js
var ttPolicy = $W1("domLineBreaksComputer", { createHTML: (value) => value });
var $28 = class _$28 {
  static create(targetWindow) {
    return new _$28(new WeakRef(targetWindow));
  }
  constructor(a) {
    this.a = a;
  }
  createLineBreaksComputer(fontInfo, tabSize, wrappingColumn, wrappingIndent, wordBreak) {
    const requests = [];
    const injectedTexts = [];
    return {
      addRequest: (lineText, injectedText, previousLineBreakData) => {
        requests.push(lineText);
        injectedTexts.push(injectedText);
      },
      finalize: () => {
        return createLineBreaks($Kg(this.a.deref()), requests, fontInfo, tabSize, wrappingColumn, wrappingIndent, wordBreak, injectedTexts);
      }
    };
  }
};
function createLineBreaks(targetWindow, requests, fontInfo, tabSize, firstLineBreakColumn, wrappingIndent, wordBreak, injectedTextsPerLine) {
  function createEmptyLineBreakWithPossiblyInjectedText(requestIdx) {
    const injectedTexts = injectedTextsPerLine[requestIdx];
    if (injectedTexts) {
      const lineText = $FE.applyInjectedText(requests[requestIdx], injectedTexts);
      const injectionOptions = injectedTexts.map((t) => t.options);
      const injectionOffsets = injectedTexts.map((text2) => text2.column - 1);
      return new $a5(injectionOffsets, injectionOptions, [lineText.length], [], 0);
    } else {
      return null;
    }
  }
  if (firstLineBreakColumn === -1) {
    const result2 = [];
    for (let i2 = 0, len = requests.length; i2 < len; i2++) {
      result2[i2] = createEmptyLineBreakWithPossiblyInjectedText(i2);
    }
    return result2;
  }
  const overallWidth = Math.round(firstLineBreakColumn * fontInfo.typicalHalfwidthCharacterWidth);
  const additionalIndent = wrappingIndent === 3 ? 2 : wrappingIndent === 2 ? 1 : 0;
  const additionalIndentSize = Math.round(tabSize * additionalIndent);
  const additionalIndentLength = Math.ceil(fontInfo.spaceWidth * additionalIndentSize);
  const containerDomNode = document.createElement("div");
  $24(containerDomNode, fontInfo);
  const sb = new $cE(1e4);
  const firstNonWhitespaceIndices = [];
  const wrappedTextIndentLengths = [];
  const renderLineContents = [];
  const allCharOffsets = [];
  const allVisibleColumns = [];
  for (let i2 = 0; i2 < requests.length; i2++) {
    const lineContent = $FE.applyInjectedText(requests[i2], injectedTextsPerLine[i2]);
    let firstNonWhitespaceIndex = 0;
    let wrappedTextIndentLength = 0;
    let width2 = overallWidth;
    if (wrappingIndent !== 0) {
      firstNonWhitespaceIndex = $Of(lineContent);
      if (firstNonWhitespaceIndex === -1) {
        firstNonWhitespaceIndex = 0;
      } else {
        for (let i3 = 0; i3 < firstNonWhitespaceIndex; i3++) {
          const charWidth = lineContent.charCodeAt(i3) === 9 ? tabSize - wrappedTextIndentLength % tabSize : 1;
          wrappedTextIndentLength += charWidth;
        }
        const indentWidth = Math.ceil(fontInfo.spaceWidth * wrappedTextIndentLength);
        if (indentWidth + fontInfo.typicalFullwidthCharacterWidth > overallWidth) {
          firstNonWhitespaceIndex = 0;
          wrappedTextIndentLength = 0;
        } else {
          width2 = overallWidth - indentWidth;
        }
      }
    }
    const renderLineContent = lineContent.substr(firstNonWhitespaceIndex);
    const tmp = renderLine(renderLineContent, wrappedTextIndentLength, tabSize, width2, sb, additionalIndentLength);
    firstNonWhitespaceIndices[i2] = firstNonWhitespaceIndex;
    wrappedTextIndentLengths[i2] = wrappedTextIndentLength;
    renderLineContents[i2] = renderLineContent;
    allCharOffsets[i2] = tmp[0];
    allVisibleColumns[i2] = tmp[1];
  }
  const html3 = sb.build();
  const trustedhtml = ttPolicy?.createHTML(html3) ?? html3;
  containerDomNode.innerHTML = trustedhtml;
  containerDomNode.style.position = "absolute";
  containerDomNode.style.top = "10000";
  if (wordBreak === "keepAll") {
    containerDomNode.style.wordBreak = "keep-all";
    containerDomNode.style.overflowWrap = "anywhere";
  } else {
    containerDomNode.style.wordBreak = "inherit";
    containerDomNode.style.overflowWrap = "break-word";
  }
  targetWindow.document.body.appendChild(containerDomNode);
  const range = document.createRange();
  const lineDomNodes = Array.prototype.slice.call(containerDomNode.children, 0);
  const result = [];
  for (let i2 = 0; i2 < requests.length; i2++) {
    const lineDomNode = lineDomNodes[i2];
    const breakOffsets = readLineBreaks(range, lineDomNode, renderLineContents[i2], allCharOffsets[i2]);
    if (breakOffsets === null) {
      result[i2] = createEmptyLineBreakWithPossiblyInjectedText(i2);
      continue;
    }
    const firstNonWhitespaceIndex = firstNonWhitespaceIndices[i2];
    const wrappedTextIndentLength = wrappedTextIndentLengths[i2] + additionalIndentSize;
    const visibleColumns = allVisibleColumns[i2];
    const breakOffsetsVisibleColumn = [];
    for (let j = 0, len = breakOffsets.length; j < len; j++) {
      breakOffsetsVisibleColumn[j] = visibleColumns[breakOffsets[j]];
    }
    if (firstNonWhitespaceIndex !== 0) {
      for (let j = 0, len = breakOffsets.length; j < len; j++) {
        breakOffsets[j] += firstNonWhitespaceIndex;
      }
    }
    let injectionOptions;
    let injectionOffsets;
    const curInjectedTexts = injectedTextsPerLine[i2];
    if (curInjectedTexts) {
      injectionOptions = curInjectedTexts.map((t) => t.options);
      injectionOffsets = curInjectedTexts.map((text2) => text2.column - 1);
    } else {
      injectionOptions = null;
      injectionOffsets = null;
    }
    result[i2] = new $a5(injectionOffsets, injectionOptions, breakOffsets, breakOffsetsVisibleColumn, wrappedTextIndentLength);
  }
  containerDomNode.remove();
  return result;
}
var Constants8;
(function(Constants27) {
  Constants27[Constants27["SPAN_MODULO_LIMIT"] = 16384] = "SPAN_MODULO_LIMIT";
})(Constants8 || (Constants8 = {}));
function renderLine(lineContent, initialVisibleColumn, tabSize, width2, sb, wrappingIndentLength) {
  if (wrappingIndentLength !== 0) {
    const hangingOffset = String(wrappingIndentLength);
    sb.appendString('<div style="text-indent: -');
    sb.appendString(hangingOffset);
    sb.appendString("px; padding-left: ");
    sb.appendString(hangingOffset);
    sb.appendString("px; box-sizing: border-box; width:");
  } else {
    sb.appendString('<div style="width:');
  }
  sb.appendString(String(width2));
  sb.appendString('px;">');
  const len = lineContent.length;
  let visibleColumn = initialVisibleColumn;
  let charOffset = 0;
  const charOffsets = [];
  const visibleColumns = [];
  let nextCharCode = 0 < len ? lineContent.charCodeAt(0) : 0;
  sb.appendString("<span>");
  for (let charIndex = 0; charIndex < len; charIndex++) {
    if (charIndex !== 0 && charIndex % 16384 === 0) {
      sb.appendString("</span><span>");
    }
    charOffsets[charIndex] = charOffset;
    visibleColumns[charIndex] = visibleColumn;
    const charCode = nextCharCode;
    nextCharCode = charIndex + 1 < len ? lineContent.charCodeAt(charIndex + 1) : 0;
    let producedCharacters = 1;
    let charWidth = 1;
    switch (charCode) {
      case 9:
        producedCharacters = tabSize - visibleColumn % tabSize;
        charWidth = producedCharacters;
        for (let space = 1; space <= producedCharacters; space++) {
          if (space < producedCharacters) {
            sb.appendCharCode(160);
          } else {
            sb.appendASCIICharCode(
              32
              /* CharCode.Space */
            );
          }
        }
        break;
      case 32:
        if (nextCharCode === 32) {
          sb.appendCharCode(160);
        } else {
          sb.appendASCIICharCode(
            32
            /* CharCode.Space */
          );
        }
        break;
      case 60:
        sb.appendString("&lt;");
        break;
      case 62:
        sb.appendString("&gt;");
        break;
      case 38:
        sb.appendString("&amp;");
        break;
      case 0:
        sb.appendString("&#00;");
        break;
      case 65279:
      case 8232:
      case 8233:
      case 133:
        sb.appendCharCode(65533);
        break;
      default:
        if ($gg(charCode)) {
          charWidth++;
        }
        if (charCode < 32) {
          sb.appendCharCode(9216 + charCode);
        } else {
          sb.appendCharCode(charCode);
        }
    }
    charOffset += producedCharacters;
    visibleColumn += charWidth;
  }
  sb.appendString("</span>");
  charOffsets[lineContent.length] = charOffset;
  visibleColumns[lineContent.length] = visibleColumn;
  sb.appendString("</div>");
  return [charOffsets, visibleColumns];
}
function readLineBreaks(range, lineDomNode, lineContent, charOffsets) {
  if (lineContent.length <= 1) {
    return null;
  }
  const spans = Array.prototype.slice.call(lineDomNode.children, 0);
  const breakOffsets = [];
  try {
    discoverBreaks(range, spans, charOffsets, 0, null, lineContent.length - 1, null, breakOffsets);
  } catch (err) {
    console.log(err);
    return null;
  }
  if (breakOffsets.length === 0) {
    return null;
  }
  breakOffsets.push(lineContent.length);
  return breakOffsets;
}
function discoverBreaks(range, spans, charOffsets, low, lowRects, high, highRects, result) {
  if (low === high) {
    return;
  }
  lowRects = lowRects || readClientRect(range, spans, charOffsets[low], charOffsets[low + 1]);
  highRects = highRects || readClientRect(range, spans, charOffsets[high], charOffsets[high + 1]);
  if (Math.abs(lowRects[0].top - highRects[0].top) <= 0.1) {
    return;
  }
  if (low + 1 === high) {
    result.push(high);
    return;
  }
  const mid = low + (high - low) / 2 | 0;
  const midRects = readClientRect(range, spans, charOffsets[mid], charOffsets[mid + 1]);
  discoverBreaks(range, spans, charOffsets, low, lowRects, mid, midRects, result);
  discoverBreaks(range, spans, charOffsets, mid, midRects, high, highRects, result);
}
function readClientRect(range, spans, startOffset, endOffset) {
  range.setStart(
    spans[startOffset / 16384 | 0].firstChild,
    startOffset % 16384
    /* Constants.SPAN_MODULO_LIMIT */
  );
  range.setEnd(
    spans[endOffset / 16384 | 0].firstChild,
    endOffset % 16384
    /* Constants.SPAN_MODULO_LIMIT */
  );
  return range.getClientRects();
}

// out-build/vs/editor/browser/widget/codeEditor/codeEditorContributions.js
var $38 = class extends $3c {
  constructor() {
    super();
    this.a = null;
    this.b = null;
    this.c = this.B(new $_c());
    this.f = /* @__PURE__ */ new Map();
    this.g = [];
    this.g[
      0
      /* EditorContributionInstantiation.Eager */
    ] = false;
    this.g[
      1
      /* EditorContributionInstantiation.AfterFirstRender */
    ] = false;
    this.g[
      2
      /* EditorContributionInstantiation.BeforeFirstInteraction */
    ] = false;
    this.g[
      3
      /* EditorContributionInstantiation.Eventually */
    ] = false;
  }
  initialize(editor, contributions, instantiationService) {
    this.a = editor;
    this.b = instantiationService;
    for (const desc of contributions) {
      if (this.f.has(desc.id)) {
        $gb(new Error(`Cannot have two contributions with the same id ${desc.id}`));
        continue;
      }
      this.f.set(desc.id, desc);
    }
    this.h(
      0
      /* EditorContributionInstantiation.Eager */
    );
    this.B($gj(getWindow(this.a.getDomNode()), () => {
      this.h(
        1
        /* EditorContributionInstantiation.AfterFirstRender */
      );
    }));
    this.B($gj(getWindow(this.a.getDomNode()), () => {
      this.h(
        2
        /* EditorContributionInstantiation.BeforeFirstInteraction */
      );
    }));
    this.B($gj(getWindow(this.a.getDomNode()), () => {
      this.h(
        3
        /* EditorContributionInstantiation.Eventually */
      );
    }, 5e3));
  }
  saveViewState() {
    const contributionsState = {};
    for (const [id2, contribution] of this.c) {
      if (typeof contribution.saveViewState === "function") {
        contributionsState[id2] = contribution.saveViewState();
      }
    }
    return contributionsState;
  }
  restoreViewState(contributionsState) {
    for (const [id2, contribution] of this.c) {
      if (typeof contribution.restoreViewState === "function") {
        contribution.restoreViewState(contributionsState[id2]);
      }
    }
  }
  get(id2) {
    this.m(id2);
    return this.c.get(id2) || null;
  }
  /**
   * used by tests
   */
  set(id2, value) {
    this.c.set(id2, value);
  }
  onBeforeInteractionEvent() {
    this.h(
      2
      /* EditorContributionInstantiation.BeforeFirstInteraction */
    );
  }
  onAfterModelAttached() {
    return $gj(getWindow(this.a?.getDomNode()), () => {
      this.h(
        1
        /* EditorContributionInstantiation.AfterFirstRender */
      );
    }, 50);
  }
  h(instantiation) {
    if (this.g[instantiation]) {
      return;
    }
    this.g[instantiation] = true;
    const contribs = this.j(instantiation);
    for (const contrib of contribs) {
      this.m(contrib.id);
    }
  }
  j(instantiation) {
    const result = [];
    for (const [, desc] of this.f) {
      if (desc.instantiation === instantiation) {
        result.push(desc);
      }
    }
    return result;
  }
  m(id2) {
    const desc = this.f.get(id2);
    if (!desc) {
      return;
    }
    this.f.delete(id2);
    if (!this.b || !this.a) {
      throw new Error(`Cannot instantiate contributions before being initialized!`);
    }
    try {
      const instance2 = this.b.createInstance(desc.ctor, this.a);
      this.c.set(desc.id, instance2);
      if (typeof instance2.restoreViewState === "function" && desc.instantiation !== 0) {
        console.warn(`Editor contribution '${desc.id}' should be eager instantiated because it uses saveViewState / restoreViewState.`);
      }
    } catch (err) {
      $gb(err);
    }
  }
};

// out-build/vs/editor/common/editorAction.js
var $48 = class {
  constructor(id2, label3, alias, metadata, a, b, c) {
    this.id = id2;
    this.label = label3;
    this.alias = alias;
    this.metadata = metadata;
    this.a = a;
    this.b = b;
    this.c = c;
  }
  isSupported() {
    return this.c.contextMatchesRules(this.a);
  }
  run(args2) {
    if (!this.isSupported()) {
      return Promise.resolve(void 0);
    }
    return this.b(args2);
  }
};

// out-build/vs/editor/common/editorCommon.js
var ScrollType;
(function(ScrollType3) {
  ScrollType3[ScrollType3["Smooth"] = 0] = "Smooth";
  ScrollType3[ScrollType3["Immediate"] = 1] = "Immediate";
})(ScrollType || (ScrollType = {}));
function isThemeColor(o) {
  return o && typeof o.id === "string";
}
var EditorType = {
  ICodeEditor: "vs.editor.ICodeEditor",
  IDiffEditor: "vs.editor.IDiffEditor"
};
var Handler;
(function(Handler2) {
  Handler2["CompositionStart"] = "compositionStart";
  Handler2["CompositionEnd"] = "compositionEnd";
  Handler2["Type"] = "type";
  Handler2["ReplacePreviousChar"] = "replacePreviousChar";
  Handler2["CompositionType"] = "compositionType";
  Handler2["Paste"] = "paste";
  Handler2["Cut"] = "cut";
})(Handler || (Handler = {}));

// out-build/vs/editor/common/core/eolCounter.js
var StringEOL;
(function(StringEOL2) {
  StringEOL2[StringEOL2["Unknown"] = 0] = "Unknown";
  StringEOL2[StringEOL2["Invalid"] = 3] = "Invalid";
  StringEOL2[StringEOL2["LF"] = 1] = "LF";
  StringEOL2[StringEOL2["CRLF"] = 2] = "CRLF";
})(StringEOL || (StringEOL = {}));
function $tE(text2) {
  let eolCount = 0;
  let firstLineLength = 0;
  let lastLineStart = 0;
  let eol = 0;
  for (let i2 = 0, len = text2.length; i2 < len; i2++) {
    const chr = text2.charCodeAt(i2);
    if (chr === 13) {
      if (eolCount === 0) {
        firstLineLength = i2;
      }
      eolCount++;
      if (i2 + 1 < len && text2.charCodeAt(i2 + 1) === 10) {
        eol |= 2;
        i2++;
      } else {
        eol |= 3;
      }
      lastLineStart = i2 + 1;
    } else if (chr === 10) {
      eol |= 1;
      if (eolCount === 0) {
        firstLineLength = i2;
      }
      eolCount++;
      lastLineStart = i2 + 1;
    }
  }
  if (eolCount === 0) {
    firstLineLength = text2.length;
  }
  return [eolCount, firstLineLength, text2.length - lastLineStart, eol];
}

// out-build/vs/editor/common/textModelBracketPairs.js
var $4F = class {
  constructor(range, nestingLevel, nestingLevelOfEqualBracketType, isInvalid) {
    this.range = range;
    this.nestingLevel = nestingLevel;
    this.nestingLevelOfEqualBracketType = nestingLevelOfEqualBracketType;
    this.isInvalid = isInvalid;
  }
};
var $5F = class {
  constructor(range, openingBracketRange, closingBracketRange, nestingLevel, nestingLevelOfEqualBracketType, a) {
    this.range = range;
    this.openingBracketRange = openingBracketRange;
    this.closingBracketRange = closingBracketRange;
    this.nestingLevel = nestingLevel;
    this.nestingLevelOfEqualBracketType = nestingLevelOfEqualBracketType;
    this.a = a;
  }
  get openingBracketInfo() {
    return this.a.openingBracket.bracketInfo;
  }
  get closingBracketInfo() {
    return this.a.closingBracket?.bracketInfo;
  }
};
var $6F = class extends $5F {
  constructor(range, openingBracketRange, closingBracketRange, nestingLevel, nestingLevelOfEqualBracketType, bracketPairNode, minVisibleColumnIndentation) {
    super(range, openingBracketRange, closingBracketRange, nestingLevel, nestingLevelOfEqualBracketType, bracketPairNode);
    this.minVisibleColumnIndentation = minVisibleColumnIndentation;
  }
};

// out-build/vs/editor/common/model/bracketPairsTextModelPart/bracketPairsTree/length.js
function $dF(startLineCount, startColumnCount, endLineCount, endColumnCount) {
  return startLineCount !== endLineCount ? $gF(endLineCount - startLineCount, endColumnCount) : $gF(0, endColumnCount - startColumnCount);
}
var $eF = 0;
function $fF(length) {
  return length === 0;
}
var factor = 2 ** 26;
function $gF(lineCount, columnCount) {
  return lineCount * factor + columnCount;
}
function $hF(length) {
  const l = length;
  const lineCount = Math.floor(l / factor);
  const columnCount = l - lineCount * factor;
  return new $gD(lineCount, columnCount);
}
function $iF(length) {
  return Math.floor(length / factor);
}
function $jF(length) {
  return length;
}
function $kF(l1, l2) {
  let r2 = l1 + l2;
  if (l2 >= factor) {
    r2 = r2 - l1 % factor;
  }
  return r2;
}
function $lF(items, lengthFn) {
  return items.reduce((a, b) => $kF(a, lengthFn(b)), $eF);
}
function $mF(length1, length2) {
  return length1 === length2;
}
function $nF(length1, length2) {
  const l1 = length1;
  const l2 = length2;
  const diff3 = l2 - l1;
  if (diff3 <= 0) {
    return $eF;
  }
  const lineCount1 = Math.floor(l1 / factor);
  const lineCount2 = Math.floor(l2 / factor);
  const colCount2 = l2 - lineCount2 * factor;
  if (lineCount1 === lineCount2) {
    const colCount1 = l1 - lineCount1 * factor;
    return $gF(0, colCount2 - colCount1);
  } else {
    return $gF(lineCount2 - lineCount1, colCount2);
  }
}
function $oF(length1, length2) {
  return length1 < length2;
}
function $pF(length1, length2) {
  return length1 <= length2;
}
function $qF(length1, length2) {
  return length1 >= length2;
}
function $sF(position) {
  return $gF(position.lineNumber - 1, position.column - 1);
}
function $tF(lengthStart, lengthEnd) {
  const l = lengthStart;
  const lineCount = Math.floor(l / factor);
  const colCount = l - lineCount * factor;
  const l2 = lengthEnd;
  const lineCount2 = Math.floor(l2 / factor);
  const colCount2 = l2 - lineCount2 * factor;
  return new $9C(lineCount + 1, colCount + 1, lineCount2 + 1, colCount2 + 1);
}
function $wF(str) {
  const lines = $Mf(str);
  return $gF(lines.length - 1, lines[lines.length - 1].length);
}

// out-build/vs/editor/common/model/bracketPairsTextModelPart/bracketPairsTree/beforeEditPositionMapper.js
var $CG = class _$CG {
  static fromModelContentChanges(changes) {
    const edits = changes.map((c) => {
      const range = $9C.lift(c.range);
      return new _$CG($sF(range.getStartPosition()), $sF(range.getEndPosition()), $wF(c.text));
    }).reverse();
    return edits;
  }
  constructor(startOffset, endOffset, newLength) {
    this.startOffset = startOffset;
    this.endOffset = endOffset;
    this.newLength = newLength;
  }
  toString() {
    return `[${$hF(this.startOffset)}...${$hF(this.endOffset)}) -> ${$hF(this.newLength)}`;
  }
};
var $DG = class {
  /**
   * @param edits Must be sorted by offset in ascending order.
  */
  constructor(edits) {
    this.a = 0;
    this.b = 0;
    this.d = 0;
    this.e = -1;
    this.f = edits.map((edit3) => TextEditInfoCache.from(edit3));
  }
  /**
   * @param offset Must be equal to or greater than the last offset this method has been called with.
  */
  getOffsetBeforeChange(offset) {
    this.i(offset);
    return this.h(offset);
  }
  /**
   * @param offset Must be equal to or greater than the last offset this method has been called with.
   * Returns null if there is no edit anymore.
  */
  getDistanceToNextChange(offset) {
    this.i(offset);
    const nextEdit = this.f[this.a];
    const nextChangeOffset = nextEdit ? this.g(nextEdit.offsetObj) : null;
    if (nextChangeOffset === null) {
      return null;
    }
    return $nF(offset, nextChangeOffset);
  }
  g(oldOffsetObj) {
    if (oldOffsetObj.lineCount === this.e) {
      return $gF(oldOffsetObj.lineCount + this.b, oldOffsetObj.columnCount + this.d);
    } else {
      return $gF(oldOffsetObj.lineCount + this.b, oldOffsetObj.columnCount);
    }
  }
  h(newOffset) {
    const offsetObj = $hF(newOffset);
    if (offsetObj.lineCount - this.b === this.e) {
      return $gF(offsetObj.lineCount - this.b, offsetObj.columnCount - this.d);
    } else {
      return $gF(offsetObj.lineCount - this.b, offsetObj.columnCount);
    }
  }
  i(offset) {
    while (this.a < this.f.length) {
      const nextEdit = this.f[this.a];
      const nextEditEndOffsetInCur = this.g(nextEdit.endOffsetAfterObj);
      if ($pF(nextEditEndOffsetInCur, offset)) {
        this.a++;
        const nextEditEndOffsetInCurObj = $hF(nextEditEndOffsetInCur);
        const nextEditEndOffsetBeforeInCurObj = $hF(this.g(nextEdit.endOffsetBeforeObj));
        const lineDelta = nextEditEndOffsetInCurObj.lineCount - nextEditEndOffsetBeforeInCurObj.lineCount;
        this.b += lineDelta;
        const previousColumnDelta = this.e === nextEdit.endOffsetBeforeObj.lineCount ? this.d : 0;
        const columnDelta = nextEditEndOffsetInCurObj.columnCount - nextEditEndOffsetBeforeInCurObj.columnCount;
        this.d = previousColumnDelta + columnDelta;
        this.e = nextEdit.endOffsetBeforeObj.lineCount;
      } else {
        break;
      }
    }
  }
};
var TextEditInfoCache = class _TextEditInfoCache {
  static from(edit3) {
    return new _TextEditInfoCache(edit3.startOffset, edit3.endOffset, edit3.newLength);
  }
  constructor(startOffset, endOffset, textLength) {
    this.endOffsetBeforeObj = $hF(endOffset);
    this.endOffsetAfterObj = $hF($kF(startOffset, textLength));
    this.offsetObj = $hF(startOffset);
  }
};

// out-build/vs/editor/common/model/bracketPairsTextModelPart/bracketPairsTree/smallImmutableSet.js
var emptyArr = [];
var $AF = class _$AF {
  static {
    this.a = new Array(129);
  }
  static b(items, additionalItems) {
    if (items <= 128 && additionalItems.length === 0) {
      let cached = _$AF.a[items];
      if (!cached) {
        cached = new _$AF(items, additionalItems);
        _$AF.a[items] = cached;
      }
      return cached;
    }
    return new _$AF(items, additionalItems);
  }
  static {
    this.c = _$AF.b(0, emptyArr);
  }
  static getEmpty() {
    return this.c;
  }
  constructor(d, e) {
    this.d = d;
    this.e = e;
  }
  add(value, keyProvider) {
    const key2 = keyProvider.getKey(value);
    let idx = key2 >> 5;
    if (idx === 0) {
      const newItem = 1 << key2 | this.d;
      if (newItem === this.d) {
        return this;
      }
      return _$AF.b(newItem, this.e);
    }
    idx--;
    const newItems = this.e.slice(0);
    while (newItems.length < idx) {
      newItems.push(0);
    }
    newItems[idx] |= 1 << (key2 & 31);
    return _$AF.b(this.d, newItems);
  }
  has(value, keyProvider) {
    const key2 = keyProvider.getKey(value);
    let idx = key2 >> 5;
    if (idx === 0) {
      return (this.d & 1 << key2) !== 0;
    }
    idx--;
    return ((this.e[idx] || 0) & 1 << (key2 & 31)) !== 0;
  }
  merge(other) {
    const merged = this.d | other.d;
    if (this.e === emptyArr && other.e === emptyArr) {
      if (merged === this.d) {
        return this;
      }
      if (merged === other.d) {
        return other;
      }
      return _$AF.b(merged, emptyArr);
    }
    const newItems = [];
    for (let i2 = 0; i2 < Math.max(this.e.length, other.e.length); i2++) {
      const item1 = this.e[i2] || 0;
      const item2 = other.e[i2] || 0;
      newItems.push(item1 | item2);
    }
    return _$AF.b(merged, newItems);
  }
  intersects(other) {
    if ((this.d & other.d) !== 0) {
      return true;
    }
    for (let i2 = 0; i2 < Math.min(this.e.length, other.e.length); i2++) {
      if ((this.e[i2] & other.e[i2]) !== 0) {
        return true;
      }
    }
    return false;
  }
  equals(other) {
    if (this.d !== other.d) {
      return false;
    }
    if (this.e.length !== other.e.length) {
      return false;
    }
    for (let i2 = 0; i2 < this.e.length; i2++) {
      if (this.e[i2] !== other.e[i2]) {
        return false;
      }
    }
    return true;
  }
};
var $BF = {
  getKey(value) {
    return value;
  }
};
var $CF = class {
  constructor() {
    this.a = /* @__PURE__ */ new Map();
  }
  getKey(value) {
    let existing = this.a.get(value);
    if (existing === void 0) {
      existing = this.a.size;
      this.a.set(value, existing);
    }
    return existing;
  }
  reverseLookup(value) {
    return [...this.a].find(([_key, v]) => v === value)?.[0];
  }
  reverseLookupSet(set) {
    const result = [];
    for (const [key2] of this.a) {
      if (set.has(key2, this)) {
        result.push(key2);
      }
    }
    return result;
  }
  keys() {
    return this.a.keys();
  }
};

// out-build/vs/editor/common/model/bracketPairsTextModelPart/bracketPairsTree/ast.js
var AstNodeKind;
(function(AstNodeKind2) {
  AstNodeKind2[AstNodeKind2["Text"] = 0] = "Text";
  AstNodeKind2[AstNodeKind2["Bracket"] = 1] = "Bracket";
  AstNodeKind2[AstNodeKind2["Pair"] = 2] = "Pair";
  AstNodeKind2[AstNodeKind2["UnexpectedClosingBracket"] = 3] = "UnexpectedClosingBracket";
  AstNodeKind2[AstNodeKind2["List"] = 4] = "List";
})(AstNodeKind || (AstNodeKind = {}));
var BaseAstNode = class {
  /**
   * The length of the entire node, which should equal the sum of lengths of all children.
  */
  get length() {
    return this.a;
  }
  constructor(length) {
    this.a = length;
  }
};
var $YF = class _$YF extends BaseAstNode {
  static create(openingBracket, child, closingBracket) {
    let length = openingBracket.length;
    if (child) {
      length = $kF(length, child.length);
    }
    if (closingBracket) {
      length = $kF(length, closingBracket.length);
    }
    return new _$YF(length, openingBracket, child, closingBracket, child ? child.missingOpeningBracketIds : $AF.getEmpty());
  }
  get kind() {
    return 2;
  }
  get listHeight() {
    return 0;
  }
  get childrenLength() {
    return 3;
  }
  getChild(idx) {
    switch (idx) {
      case 0:
        return this.openingBracket;
      case 1:
        return this.child;
      case 2:
        return this.closingBracket;
    }
    throw new Error("Invalid child index");
  }
  /**
   * Avoid using this property, it allocates an array!
  */
  get children() {
    const result = [];
    result.push(this.openingBracket);
    if (this.child) {
      result.push(this.child);
    }
    if (this.closingBracket) {
      result.push(this.closingBracket);
    }
    return result;
  }
  constructor(length, openingBracket, child, closingBracket, missingOpeningBracketIds) {
    super(length);
    this.openingBracket = openingBracket;
    this.child = child;
    this.closingBracket = closingBracket;
    this.missingOpeningBracketIds = missingOpeningBracketIds;
  }
  canBeReused(openBracketIds) {
    if (this.closingBracket === null) {
      return false;
    }
    if (openBracketIds.intersects(this.missingOpeningBracketIds)) {
      return false;
    }
    return true;
  }
  flattenLists() {
    return _$YF.create(this.openingBracket.flattenLists(), this.child && this.child.flattenLists(), this.closingBracket && this.closingBracket.flattenLists());
  }
  deepClone() {
    return new _$YF(this.length, this.openingBracket.deepClone(), this.child && this.child.deepClone(), this.closingBracket && this.closingBracket.deepClone(), this.missingOpeningBracketIds);
  }
  computeMinIndentation(offset, textModel) {
    return this.child ? this.child.computeMinIndentation($kF(offset, this.openingBracket.length), textModel) : Number.MAX_SAFE_INTEGER;
  }
};
var $ZF = class _$ZF extends BaseAstNode {
  /**
   * This method uses more memory-efficient list nodes that can only store 2 or 3 children.
  */
  static create23(item1, item2, item3, immutable = false) {
    let length = item1.length;
    let missingBracketIds = item1.missingOpeningBracketIds;
    if (item1.listHeight !== item2.listHeight) {
      throw new Error("Invalid list heights");
    }
    length = $kF(length, item2.length);
    missingBracketIds = missingBracketIds.merge(item2.missingOpeningBracketIds);
    if (item3) {
      if (item1.listHeight !== item3.listHeight) {
        throw new Error("Invalid list heights");
      }
      length = $kF(length, item3.length);
      missingBracketIds = missingBracketIds.merge(item3.missingOpeningBracketIds);
    }
    return immutable ? new Immutable23ListAstNode(length, item1.listHeight + 1, item1, item2, item3, missingBracketIds) : new TwoThreeListAstNode(length, item1.listHeight + 1, item1, item2, item3, missingBracketIds);
  }
  static create(items, immutable = false) {
    if (items.length === 0) {
      return this.getEmpty();
    } else {
      let length = items[0].length;
      let unopenedBrackets = items[0].missingOpeningBracketIds;
      for (let i2 = 1; i2 < items.length; i2++) {
        length = $kF(length, items[i2].length);
        unopenedBrackets = unopenedBrackets.merge(items[i2].missingOpeningBracketIds);
      }
      return immutable ? new ImmutableArrayListAstNode(length, items[0].listHeight + 1, items, unopenedBrackets) : new ArrayListAstNode(length, items[0].listHeight + 1, items, unopenedBrackets);
    }
  }
  static getEmpty() {
    return new ImmutableArrayListAstNode($eF, 0, [], $AF.getEmpty());
  }
  get kind() {
    return 4;
  }
  get missingOpeningBracketIds() {
    return this.d;
  }
  /**
   * Use ListAstNode.create.
  */
  constructor(length, listHeight, d) {
    super(length);
    this.listHeight = listHeight;
    this.d = d;
    this.b = -1;
  }
  e() {
  }
  makeLastElementMutable() {
    this.e();
    const childCount = this.childrenLength;
    if (childCount === 0) {
      return void 0;
    }
    const lastChild = this.getChild(childCount - 1);
    const mutable = lastChild.kind === 4 ? lastChild.toMutable() : lastChild;
    if (lastChild !== mutable) {
      this.f(childCount - 1, mutable);
    }
    return mutable;
  }
  makeFirstElementMutable() {
    this.e();
    const childCount = this.childrenLength;
    if (childCount === 0) {
      return void 0;
    }
    const firstChild = this.getChild(0);
    const mutable = firstChild.kind === 4 ? firstChild.toMutable() : firstChild;
    if (firstChild !== mutable) {
      this.f(0, mutable);
    }
    return mutable;
  }
  canBeReused(openBracketIds) {
    if (openBracketIds.intersects(this.missingOpeningBracketIds)) {
      return false;
    }
    if (this.childrenLength === 0) {
      return false;
    }
    let lastChild = this;
    while (lastChild.kind === 4) {
      const lastLength = lastChild.childrenLength;
      if (lastLength === 0) {
        throw new $vb();
      }
      lastChild = lastChild.getChild(lastLength - 1);
    }
    return lastChild.canBeReused(openBracketIds);
  }
  handleChildrenChanged() {
    this.e();
    const count = this.childrenLength;
    let length = this.getChild(0).length;
    let unopenedBrackets = this.getChild(0).missingOpeningBracketIds;
    for (let i2 = 1; i2 < count; i2++) {
      const child = this.getChild(i2);
      length = $kF(length, child.length);
      unopenedBrackets = unopenedBrackets.merge(child.missingOpeningBracketIds);
    }
    this.a = length;
    this.d = unopenedBrackets;
    this.b = -1;
  }
  flattenLists() {
    const items = [];
    for (const c of this.children) {
      const normalized = c.flattenLists();
      if (normalized.kind === 4) {
        items.push(...normalized.children);
      } else {
        items.push(normalized);
      }
    }
    return _$ZF.create(items);
  }
  computeMinIndentation(offset, textModel) {
    if (this.b !== -1) {
      return this.b;
    }
    let minIndentation = Number.MAX_SAFE_INTEGER;
    let childOffset = offset;
    for (let i2 = 0; i2 < this.childrenLength; i2++) {
      const child = this.getChild(i2);
      if (child) {
        minIndentation = Math.min(minIndentation, child.computeMinIndentation(childOffset, textModel));
        childOffset = $kF(childOffset, child.length);
      }
    }
    this.b = minIndentation;
    return minIndentation;
  }
};
var TwoThreeListAstNode = class _TwoThreeListAstNode extends $ZF {
  get childrenLength() {
    return this.k !== null ? 3 : 2;
  }
  getChild(idx) {
    switch (idx) {
      case 0:
        return this.h;
      case 1:
        return this.j;
      case 2:
        return this.k;
    }
    throw new Error("Invalid child index");
  }
  f(idx, node) {
    switch (idx) {
      case 0:
        this.h = node;
        return;
      case 1:
        this.j = node;
        return;
      case 2:
        this.k = node;
        return;
    }
    throw new Error("Invalid child index");
  }
  get children() {
    return this.k ? [this.h, this.j, this.k] : [this.h, this.j];
  }
  get item1() {
    return this.h;
  }
  get item2() {
    return this.j;
  }
  get item3() {
    return this.k;
  }
  constructor(length, listHeight, h3, j, k, missingOpeningBracketIds) {
    super(length, listHeight, missingOpeningBracketIds);
    this.h = h3;
    this.j = j;
    this.k = k;
  }
  deepClone() {
    return new _TwoThreeListAstNode(this.length, this.listHeight, this.h.deepClone(), this.j.deepClone(), this.k ? this.k.deepClone() : null, this.missingOpeningBracketIds);
  }
  appendChildOfSameHeight(node) {
    if (this.k) {
      throw new Error("Cannot append to a full (2,3) tree node");
    }
    this.e();
    this.k = node;
    this.handleChildrenChanged();
  }
  unappendChild() {
    if (!this.k) {
      throw new Error("Cannot remove from a non-full (2,3) tree node");
    }
    this.e();
    const result = this.k;
    this.k = null;
    this.handleChildrenChanged();
    return result;
  }
  prependChildOfSameHeight(node) {
    if (this.k) {
      throw new Error("Cannot prepend to a full (2,3) tree node");
    }
    this.e();
    this.k = this.j;
    this.j = this.h;
    this.h = node;
    this.handleChildrenChanged();
  }
  unprependChild() {
    if (!this.k) {
      throw new Error("Cannot remove from a non-full (2,3) tree node");
    }
    this.e();
    const result = this.h;
    this.h = this.j;
    this.j = this.k;
    this.k = null;
    this.handleChildrenChanged();
    return result;
  }
  toMutable() {
    return this;
  }
};
var Immutable23ListAstNode = class extends TwoThreeListAstNode {
  toMutable() {
    return new TwoThreeListAstNode(this.length, this.listHeight, this.item1, this.item2, this.item3, this.missingOpeningBracketIds);
  }
  e() {
    throw new Error("this instance is immutable");
  }
};
var ArrayListAstNode = class _ArrayListAstNode extends $ZF {
  get childrenLength() {
    return this.h.length;
  }
  getChild(idx) {
    return this.h[idx];
  }
  f(idx, child) {
    this.h[idx] = child;
  }
  get children() {
    return this.h;
  }
  constructor(length, listHeight, h3, missingOpeningBracketIds) {
    super(length, listHeight, missingOpeningBracketIds);
    this.h = h3;
  }
  deepClone() {
    const children = new Array(this.h.length);
    for (let i2 = 0; i2 < this.h.length; i2++) {
      children[i2] = this.h[i2].deepClone();
    }
    return new _ArrayListAstNode(this.length, this.listHeight, children, this.missingOpeningBracketIds);
  }
  appendChildOfSameHeight(node) {
    this.e();
    this.h.push(node);
    this.handleChildrenChanged();
  }
  unappendChild() {
    this.e();
    const item = this.h.pop();
    this.handleChildrenChanged();
    return item;
  }
  prependChildOfSameHeight(node) {
    this.e();
    this.h.unshift(node);
    this.handleChildrenChanged();
  }
  unprependChild() {
    this.e();
    const item = this.h.shift();
    this.handleChildrenChanged();
    return item;
  }
  toMutable() {
    return this;
  }
};
var ImmutableArrayListAstNode = class extends ArrayListAstNode {
  toMutable() {
    return new ArrayListAstNode(this.length, this.listHeight, [...this.children], this.missingOpeningBracketIds);
  }
  e() {
    throw new Error("this instance is immutable");
  }
};
var emptyArray = [];
var ImmutableLeafAstNode = class extends BaseAstNode {
  get listHeight() {
    return 0;
  }
  get childrenLength() {
    return 0;
  }
  getChild(idx) {
    return null;
  }
  get children() {
    return emptyArray;
  }
  flattenLists() {
    return this;
  }
  deepClone() {
    return this;
  }
};
var $1F = class extends ImmutableLeafAstNode {
  get kind() {
    return 0;
  }
  get missingOpeningBracketIds() {
    return $AF.getEmpty();
  }
  canBeReused(_openedBracketIds) {
    return true;
  }
  computeMinIndentation(offset, textModel) {
    const start = $hF(offset);
    const startLineNumber = (start.columnCount === 0 ? start.lineCount : start.lineCount + 1) + 1;
    const endLineNumber = $iF($kF(offset, this.length)) + 1;
    let result = Number.MAX_SAFE_INTEGER;
    for (let lineNumber = startLineNumber; lineNumber <= endLineNumber; lineNumber++) {
      const firstNonWsColumn = textModel.getLineFirstNonWhitespaceColumn(lineNumber);
      const lineContent = textModel.getLineContent(lineNumber);
      if (firstNonWsColumn === 0) {
        continue;
      }
      const visibleColumn = $cF.visibleColumnFromColumn(lineContent, firstNonWsColumn, textModel.getOptions().tabSize);
      result = Math.min(result, visibleColumn);
    }
    return result;
  }
};
var $2F = class _$2F extends ImmutableLeafAstNode {
  static create(length, bracketInfo, bracketIds) {
    const node = new _$2F(length, bracketInfo, bracketIds);
    return node;
  }
  get kind() {
    return 1;
  }
  get missingOpeningBracketIds() {
    return $AF.getEmpty();
  }
  constructor(length, bracketInfo, bracketIds) {
    super(length);
    this.bracketInfo = bracketInfo;
    this.bracketIds = bracketIds;
  }
  get text() {
    return this.bracketInfo.bracketText;
  }
  get languageId() {
    return this.bracketInfo.languageId;
  }
  canBeReused(_openedBracketIds) {
    return false;
  }
  computeMinIndentation(offset, textModel) {
    return Number.MAX_SAFE_INTEGER;
  }
};
var $3F = class extends ImmutableLeafAstNode {
  get kind() {
    return 3;
  }
  constructor(closingBrackets, length) {
    super(length);
    this.missingOpeningBracketIds = closingBrackets;
  }
  canBeReused(openedBracketIds) {
    return !openedBracketIds.intersects(this.missingOpeningBracketIds);
  }
  computeMinIndentation(offset, textModel) {
    return Number.MAX_SAFE_INTEGER;
  }
};

// out-build/vs/editor/common/model/bracketPairsTextModelPart/bracketPairsTree/tokenizer.js
var TokenKind;
(function(TokenKind2) {
  TokenKind2[TokenKind2["Text"] = 0] = "Text";
  TokenKind2[TokenKind2["OpeningBracket"] = 1] = "OpeningBracket";
  TokenKind2[TokenKind2["ClosingBracket"] = 2] = "ClosingBracket";
})(TokenKind || (TokenKind = {}));
var $VF = class {
  constructor(length, kind, bracketId, bracketIds, astNode) {
    this.length = length;
    this.kind = kind;
    this.bracketId = bracketId;
    this.bracketIds = bracketIds;
    this.astNode = astNode;
  }
};
var $WF = class {
  constructor(d, e) {
    this.d = d;
    this.e = e;
    this.c = new NonPeekableTextBufferTokenizer(this.d, this.e);
    this.f = $eF;
    this.g = false;
    this.h = null;
    this.a = d.getLineCount();
    this.b = d.getLineLength(this.a);
  }
  get offset() {
    return this.f;
  }
  get length() {
    return $gF(this.a - 1, this.b);
  }
  getText() {
    return this.d.getValue();
  }
  skip(length) {
    this.g = false;
    this.f = $kF(this.f, length);
    const obj = $hF(this.f);
    this.c.setPosition(obj.lineCount, obj.columnCount);
  }
  read() {
    let token;
    if (this.h) {
      this.g = false;
      token = this.h;
    } else {
      token = this.c.read();
    }
    if (token) {
      this.f = $kF(this.f, token.length);
    }
    return token;
  }
  peek() {
    if (!this.g) {
      this.h = this.c.read();
      this.g = true;
    }
    return this.h;
  }
};
var NonPeekableTextBufferTokenizer = class {
  constructor(c, d) {
    this.c = c;
    this.d = d;
    this.e = 0;
    this.f = null;
    this.g = 0;
    this.h = null;
    this.j = 0;
    this.k = null;
    this.a = c.getLineCount();
    this.b = c.getLineLength(this.a);
  }
  setPosition(lineIdx, column) {
    if (lineIdx === this.e) {
      this.g = column;
      if (this.f !== null) {
        this.j = this.g === 0 ? 0 : this.h.findTokenIndexAtOffset(this.g);
      }
    } else {
      this.e = lineIdx;
      this.g = column;
      this.f = null;
    }
    this.k = null;
  }
  read() {
    if (this.k) {
      const token = this.k;
      this.k = null;
      this.g += $jF(token.length);
      return token;
    }
    if (this.e > this.a - 1 || this.e === this.a - 1 && this.g >= this.b) {
      return null;
    }
    if (this.f === null) {
      this.h = this.c.tokenization.getLineTokens(this.e + 1);
      this.f = this.h.getLineContent();
      this.j = this.g === 0 ? 0 : this.h.findTokenIndexAtOffset(this.g);
    }
    const startLineIdx = this.e;
    const startLineCharOffset = this.g;
    let lengthHeuristic = 0;
    while (true) {
      const lineTokens = this.h;
      const tokenCount = lineTokens.getCount();
      let peekedBracketToken = null;
      if (this.j < tokenCount) {
        const tokenMetadata = lineTokens.getMetadata(this.j);
        while (this.j + 1 < tokenCount && tokenMetadata === lineTokens.getMetadata(this.j + 1)) {
          this.j++;
        }
        const isOther = $pE.getTokenType(tokenMetadata) === 0;
        const containsBracketType = $pE.containsBalancedBrackets(tokenMetadata);
        const endOffset = lineTokens.getEndOffset(this.j);
        if (containsBracketType && isOther && this.g < endOffset) {
          const languageId = lineTokens.getLanguageId(this.j);
          const text2 = this.f.substring(this.g, endOffset);
          const brackets = this.d.getSingleLanguageBracketTokens(languageId);
          const regexp = brackets.regExpGlobal;
          if (regexp) {
            regexp.lastIndex = 0;
            const match = regexp.exec(text2);
            if (match) {
              peekedBracketToken = brackets.getToken(match[0]);
              if (peekedBracketToken) {
                this.g += match.index;
              }
            }
          }
        }
        lengthHeuristic += endOffset - this.g;
        if (peekedBracketToken) {
          if (startLineIdx !== this.e || startLineCharOffset !== this.g) {
            this.k = peekedBracketToken;
            break;
          } else {
            this.g += $jF(peekedBracketToken.length);
            return peekedBracketToken;
          }
        } else {
          this.j++;
          this.g = endOffset;
        }
      } else {
        if (this.e === this.a - 1) {
          break;
        }
        this.e++;
        this.h = this.c.tokenization.getLineTokens(this.e + 1);
        this.j = 0;
        this.f = this.h.getLineContent();
        this.g = 0;
        lengthHeuristic += 33;
        if (lengthHeuristic > 1e3) {
          break;
        }
      }
      if (lengthHeuristic > 1500) {
        break;
      }
    }
    const length = $dF(startLineIdx, startLineCharOffset, this.e, this.g);
    return new $VF(length, 0, -1, $AF.getEmpty(), new $1F(length));
  }
};
var $XF = class {
  constructor(d, brackets) {
    this.d = d;
    this.a = $eF;
    this.c = 0;
    const regExpStr = brackets.getRegExpStr();
    const regexp = regExpStr ? new RegExp(regExpStr + "|\n", "gi") : null;
    const tokens = [];
    let match;
    let curLineCount = 0;
    let lastLineBreakOffset = 0;
    let lastTokenEndOffset = 0;
    let lastTokenEndLine = 0;
    const smallTextTokens0Line = [];
    for (let i2 = 0; i2 < 60; i2++) {
      smallTextTokens0Line.push(new $VF($gF(0, i2), 0, -1, $AF.getEmpty(), new $1F($gF(0, i2))));
    }
    const smallTextTokens1Line = [];
    for (let i2 = 0; i2 < 60; i2++) {
      smallTextTokens1Line.push(new $VF($gF(1, i2), 0, -1, $AF.getEmpty(), new $1F($gF(1, i2))));
    }
    if (regexp) {
      regexp.lastIndex = 0;
      while ((match = regexp.exec(d)) !== null) {
        const curOffset = match.index;
        const value = match[0];
        if (value === "\n") {
          curLineCount++;
          lastLineBreakOffset = curOffset + 1;
        } else {
          if (lastTokenEndOffset !== curOffset) {
            let token;
            if (lastTokenEndLine === curLineCount) {
              const colCount = curOffset - lastTokenEndOffset;
              if (colCount < smallTextTokens0Line.length) {
                token = smallTextTokens0Line[colCount];
              } else {
                const length = $gF(0, colCount);
                token = new $VF(length, 0, -1, $AF.getEmpty(), new $1F(length));
              }
            } else {
              const lineCount = curLineCount - lastTokenEndLine;
              const colCount = curOffset - lastLineBreakOffset;
              if (lineCount === 1 && colCount < smallTextTokens1Line.length) {
                token = smallTextTokens1Line[colCount];
              } else {
                const length = $gF(lineCount, colCount);
                token = new $VF(length, 0, -1, $AF.getEmpty(), new $1F(length));
              }
            }
            tokens.push(token);
          }
          tokens.push(brackets.getToken(value));
          lastTokenEndOffset = curOffset + value.length;
          lastTokenEndLine = curLineCount;
        }
      }
    }
    const offset = d.length;
    if (lastTokenEndOffset !== offset) {
      const length = lastTokenEndLine === curLineCount ? $gF(0, offset - lastTokenEndOffset) : $gF(curLineCount - lastTokenEndLine, offset - lastLineBreakOffset);
      tokens.push(new $VF(length, 0, -1, $AF.getEmpty(), new $1F(length)));
    }
    this.length = $gF(curLineCount, offset - lastLineBreakOffset);
    this.b = tokens;
  }
  get offset() {
    return this.a;
  }
  read() {
    return this.b[this.c++] || null;
  }
  peek() {
    return this.b[this.c] || null;
  }
  skip(length) {
    throw new $sb();
  }
  getText() {
    return this.d;
  }
};

// out-build/vs/editor/common/model/bracketPairsTextModelPart/bracketPairsTree/brackets.js
var $TF = class _$TF {
  static createFromLanguage(configuration2, denseKeyProvider) {
    function getId2(bracketInfo) {
      return denseKeyProvider.getKey(`${bracketInfo.languageId}:::${bracketInfo.bracketText}`);
    }
    const map = /* @__PURE__ */ new Map();
    for (const openingBracket of configuration2.bracketsNew.openingBrackets) {
      const length = $gF(0, openingBracket.bracketText.length);
      const openingTextId = getId2(openingBracket);
      const bracketIds = $AF.getEmpty().add(openingTextId, $BF);
      map.set(openingBracket.bracketText, new $VF(length, 1, openingTextId, bracketIds, $2F.create(length, openingBracket, bracketIds)));
    }
    for (const closingBracket of configuration2.bracketsNew.closingBrackets) {
      const length = $gF(0, closingBracket.bracketText.length);
      let bracketIds = $AF.getEmpty();
      const closingBrackets = closingBracket.getOpeningBrackets();
      for (const bracket of closingBrackets) {
        bracketIds = bracketIds.add(getId2(bracket), $BF);
      }
      map.set(closingBracket.bracketText, new $VF(length, 2, getId2(closingBrackets[0]), bracketIds, $2F.create(length, closingBracket, bracketIds)));
    }
    return new _$TF(map);
  }
  constructor(c) {
    this.c = c;
    this.a = false;
    this.b = null;
  }
  getRegExpStr() {
    if (this.isEmpty) {
      return null;
    } else {
      const keys = [...this.c.keys()];
      keys.sort();
      keys.reverse();
      return keys.map((k) => prepareBracketForRegExp2(k)).join("|");
    }
  }
  /**
   * Returns null if there is no such regexp (because there are no brackets).
  */
  get regExpGlobal() {
    if (!this.a) {
      const regExpStr = this.getRegExpStr();
      this.b = regExpStr ? new RegExp(regExpStr, "gi") : null;
      this.a = true;
    }
    return this.b;
  }
  getToken(value) {
    return this.c.get(value.toLowerCase());
  }
  findClosingTokenText(openingBracketIds) {
    for (const [closingText, info] of this.c) {
      if (info.kind === 2 && info.bracketIds.intersects(openingBracketIds)) {
        return closingText;
      }
    }
    return void 0;
  }
  get isEmpty() {
    return this.c.size === 0;
  }
};
function prepareBracketForRegExp2(str) {
  let escaped = $Af(str);
  if (/^[\w ]+/.test(str)) {
    escaped = `\\b${escaped}`;
  }
  if (/[\w ]+$/.test(str)) {
    escaped = `${escaped}\\b`;
  }
  return escaped;
}
var $UF = class {
  constructor(b, c) {
    this.b = b;
    this.c = c;
    this.a = /* @__PURE__ */ new Map();
  }
  didLanguageChange(languageId) {
    return this.a.has(languageId);
  }
  getSingleLanguageBracketTokens(languageId) {
    let singleLanguageBracketTokens = this.a.get(languageId);
    if (!singleLanguageBracketTokens) {
      singleLanguageBracketTokens = $TF.createFromLanguage(this.c(languageId), this.b);
      this.a.set(languageId, singleLanguageBracketTokens);
    }
    return singleLanguageBracketTokens;
  }
  getToken(value, languageId) {
    const singleLanguageBracketTokens = this.getSingleLanguageBracketTokens(languageId);
    return singleLanguageBracketTokens.getToken(value);
  }
};

// out-build/vs/editor/common/model/bracketPairsTextModelPart/bracketPairsTree/concat23Trees.js
function $EG(items) {
  if (items.length === 0) {
    return null;
  }
  if (items.length === 1) {
    return items[0];
  }
  let i2 = 0;
  function readNode() {
    if (i2 >= items.length) {
      return null;
    }
    const start = i2;
    const height = items[start].listHeight;
    i2++;
    while (i2 < items.length && items[i2].listHeight === height) {
      i2++;
    }
    if (i2 - start >= 2) {
      return $FG(start === 0 && i2 === items.length ? items : items.slice(start, i2), false);
    } else {
      return items[start];
    }
  }
  let first = readNode();
  let second = readNode();
  if (!second) {
    return first;
  }
  for (let item = readNode(); item; item = readNode()) {
    if (heightDiff(first, second) <= heightDiff(second, item)) {
      first = concat(first, second);
      second = item;
    } else {
      second = concat(second, item);
    }
  }
  const result = concat(first, second);
  return result;
}
function $FG(items, createImmutableLists = false) {
  if (items.length === 0) {
    return null;
  }
  if (items.length === 1) {
    return items[0];
  }
  let length = items.length;
  while (length > 3) {
    const newLength = length >> 1;
    for (let i2 = 0; i2 < newLength; i2++) {
      const j = i2 << 1;
      items[i2] = $ZF.create23(items[j], items[j + 1], j + 3 === length ? items[j + 2] : null, createImmutableLists);
    }
    length = newLength;
  }
  return $ZF.create23(items[0], items[1], length >= 3 ? items[2] : null, createImmutableLists);
}
function heightDiff(node1, node2) {
  return Math.abs(node1.listHeight - node2.listHeight);
}
function concat(node1, node2) {
  if (node1.listHeight === node2.listHeight) {
    return $ZF.create23(node1, node2, null, false);
  } else if (node1.listHeight > node2.listHeight) {
    return append(node1, node2);
  } else {
    return prepend(node2, node1);
  }
}
function append(list2, nodeToAppend) {
  list2 = list2.toMutable();
  let curNode = list2;
  const parents = [];
  let nodeToAppendOfCorrectHeight;
  while (true) {
    if (nodeToAppend.listHeight === curNode.listHeight) {
      nodeToAppendOfCorrectHeight = nodeToAppend;
      break;
    }
    if (curNode.kind !== 4) {
      throw new Error("unexpected");
    }
    parents.push(curNode);
    curNode = curNode.makeLastElementMutable();
  }
  for (let i2 = parents.length - 1; i2 >= 0; i2--) {
    const parent = parents[i2];
    if (nodeToAppendOfCorrectHeight) {
      if (parent.childrenLength >= 3) {
        nodeToAppendOfCorrectHeight = $ZF.create23(parent.unappendChild(), nodeToAppendOfCorrectHeight, null, false);
      } else {
        parent.appendChildOfSameHeight(nodeToAppendOfCorrectHeight);
        nodeToAppendOfCorrectHeight = void 0;
      }
    } else {
      parent.handleChildrenChanged();
    }
  }
  if (nodeToAppendOfCorrectHeight) {
    return $ZF.create23(list2, nodeToAppendOfCorrectHeight, null, false);
  } else {
    return list2;
  }
}
function prepend(list2, nodeToAppend) {
  list2 = list2.toMutable();
  let curNode = list2;
  const parents = [];
  while (nodeToAppend.listHeight !== curNode.listHeight) {
    if (curNode.kind !== 4) {
      throw new Error("unexpected");
    }
    parents.push(curNode);
    curNode = curNode.makeFirstElementMutable();
  }
  let nodeToPrependOfCorrectHeight = nodeToAppend;
  for (let i2 = parents.length - 1; i2 >= 0; i2--) {
    const parent = parents[i2];
    if (nodeToPrependOfCorrectHeight) {
      if (parent.childrenLength >= 3) {
        nodeToPrependOfCorrectHeight = $ZF.create23(nodeToPrependOfCorrectHeight, parent.unprependChild(), null, false);
      } else {
        parent.prependChildOfSameHeight(nodeToPrependOfCorrectHeight);
        nodeToPrependOfCorrectHeight = void 0;
      }
    } else {
      parent.handleChildrenChanged();
    }
  }
  if (nodeToPrependOfCorrectHeight) {
    return $ZF.create23(nodeToPrependOfCorrectHeight, list2, null, false);
  } else {
    return list2;
  }
}

// out-build/vs/editor/common/model/bracketPairsTextModelPart/bracketPairsTree/nodeReader.js
var $GG = class {
  constructor(node) {
    this.d = $eF;
    this.a = [node];
    this.b = [$eF];
    this.c = [];
  }
  /**
   * Returns the longest node at `offset` that satisfies the predicate.
   * @param offset must be greater than or equal to the last offset this method has been called with!
  */
  readLongestNodeAt(offset, predicate) {
    if ($oF(offset, this.d)) {
      throw new Error("Invalid offset");
    }
    this.d = offset;
    while (true) {
      const curNode = lastOrUndefined(this.a);
      if (!curNode) {
        return void 0;
      }
      const curNodeOffset = lastOrUndefined(this.b);
      if ($oF(offset, curNodeOffset)) {
        return void 0;
      }
      if ($oF(curNodeOffset, offset)) {
        if ($kF(curNodeOffset, curNode.length) <= offset) {
          this.e();
        } else {
          const nextChildIdx = getNextChildIdx(curNode);
          if (nextChildIdx !== -1) {
            this.a.push(curNode.getChild(nextChildIdx));
            this.b.push(curNodeOffset);
            this.c.push(nextChildIdx);
          } else {
            this.e();
          }
        }
      } else {
        if (predicate(curNode)) {
          this.e();
          return curNode;
        } else {
          const nextChildIdx = getNextChildIdx(curNode);
          if (nextChildIdx === -1) {
            this.e();
            return void 0;
          } else {
            this.a.push(curNode.getChild(nextChildIdx));
            this.b.push(curNodeOffset);
            this.c.push(nextChildIdx);
          }
        }
      }
    }
  }
  // Navigates to the longest node that continues after the current node.
  e() {
    while (true) {
      const currentOffset = lastOrUndefined(this.b);
      const currentNode = lastOrUndefined(this.a);
      this.a.pop();
      this.b.pop();
      if (this.c.length === 0) {
        break;
      }
      const parent = lastOrUndefined(this.a);
      const nextChildIdx = getNextChildIdx(parent, this.c[this.c.length - 1]);
      if (nextChildIdx !== -1) {
        this.a.push(parent.getChild(nextChildIdx));
        this.b.push($kF(currentOffset, currentNode.length));
        this.c[this.c.length - 1] = nextChildIdx;
        break;
      } else {
        this.c.pop();
      }
    }
  }
};
function getNextChildIdx(node, curIdx = -1) {
  while (true) {
    curIdx++;
    if (curIdx >= node.childrenLength) {
      return -1;
    }
    if (node.getChild(curIdx)) {
      return curIdx;
    }
  }
}
function lastOrUndefined(arr) {
  return arr.length > 0 ? arr[arr.length - 1] : void 0;
}

// out-build/vs/editor/common/model/bracketPairsTextModelPart/bracketPairsTree/parser.js
function $HG(tokenizer, edits, oldNode, createImmutableLists) {
  const parser2 = new Parser(tokenizer, edits, oldNode, createImmutableLists);
  return parser2.parseDocument();
}
var Parser = class {
  /**
   * Reports how many nodes were constructed in the last parse operation.
  */
  get nodesConstructed() {
    return this.c;
  }
  /**
   * Reports how many nodes were reused in the last parse operation.
  */
  get nodesReused() {
    return this.d;
  }
  constructor(e, edits, oldNode, f) {
    this.e = e;
    this.f = f;
    this.c = 0;
    this.d = 0;
    if (oldNode && f) {
      throw new Error("Not supported");
    }
    this.a = oldNode ? new $GG(oldNode) : void 0;
    this.b = new $DG(edits);
  }
  parseDocument() {
    this.c = 0;
    this.d = 0;
    let result = this.g($AF.getEmpty(), 0);
    if (!result) {
      result = $ZF.getEmpty();
    }
    return result;
  }
  g(openedBracketIds, level) {
    const items = [];
    while (true) {
      let child = this.h(openedBracketIds);
      if (!child) {
        const token = this.e.peek();
        if (!token || token.kind === 2 && token.bracketIds.intersects(openedBracketIds)) {
          break;
        }
        child = this.i(openedBracketIds, level + 1);
      }
      if (child.kind === 4 && child.childrenLength === 0) {
        continue;
      }
      items.push(child);
    }
    const result = this.a ? $EG(items) : $FG(items, this.f);
    return result;
  }
  h(openedBracketIds) {
    if (this.a) {
      const maxCacheableLength = this.b.getDistanceToNextChange(this.e.offset);
      if (maxCacheableLength === null || !$fF(maxCacheableLength)) {
        const cachedNode = this.a.readLongestNodeAt(this.b.getOffsetBeforeChange(this.e.offset), (curNode) => {
          if (maxCacheableLength !== null && !$oF(curNode.length, maxCacheableLength)) {
            return false;
          }
          const canBeReused = curNode.canBeReused(openedBracketIds);
          return canBeReused;
        });
        if (cachedNode) {
          this.d++;
          this.e.skip(cachedNode.length);
          return cachedNode;
        }
      }
    }
    return void 0;
  }
  i(openedBracketIds, level) {
    this.c++;
    const token = this.e.read();
    switch (token.kind) {
      case 2:
        return new $3F(token.bracketIds, token.length);
      case 0:
        return token.astNode;
      case 1: {
        if (level > 300) {
          return new $1F(token.length);
        }
        const set = openedBracketIds.merge(token.bracketIds);
        const child = this.g(set, level + 1);
        const nextToken = this.e.peek();
        if (nextToken && nextToken.kind === 2 && (nextToken.bracketId === token.bracketId || nextToken.bracketIds.intersects(token.bracketIds))) {
          this.e.read();
          return $YF.create(token.astNode, child, nextToken.astNode);
        } else {
          return $YF.create(token.astNode, child, null);
        }
      }
      default:
        throw new Error("unexpected");
    }
  }
};

// out-build/vs/editor/common/model/bracketPairsTextModelPart/bracketPairsTree/combineTextEditInfos.js
function $IG(textEditInfoFirst, textEditInfoSecond) {
  if (textEditInfoFirst.length === 0) {
    return textEditInfoSecond;
  }
  if (textEditInfoSecond.length === 0) {
    return textEditInfoFirst;
  }
  const s0ToS1Map = new $bc(toLengthMapping(textEditInfoFirst));
  const s1ToS2Map = toLengthMapping(textEditInfoSecond);
  s1ToS2Map.push({ modified: false, lengthBefore: void 0, lengthAfter: void 0 });
  let curItem = s0ToS1Map.dequeue();
  function nextS0ToS1MapWithS1LengthOf(s1Length) {
    if (s1Length === void 0) {
      const arr = s0ToS1Map.takeWhile((v) => true) || [];
      if (curItem) {
        arr.unshift(curItem);
      }
      return arr;
    }
    const result2 = [];
    while (curItem && !$fF(s1Length)) {
      const [item, remainingItem] = curItem.splitAt(s1Length);
      result2.push(item);
      s1Length = $nF(item.lengthAfter, s1Length);
      curItem = remainingItem ?? s0ToS1Map.dequeue();
    }
    if (!$fF(s1Length)) {
      result2.push(new LengthMapping(false, s1Length, s1Length));
    }
    return result2;
  }
  const result = [];
  function pushEdit(startOffset, endOffset, newLength) {
    if (result.length > 0 && $mF(result[result.length - 1].endOffset, startOffset)) {
      const lastResult = result[result.length - 1];
      result[result.length - 1] = new $CG(lastResult.startOffset, endOffset, $kF(lastResult.newLength, newLength));
    } else {
      result.push({ startOffset, endOffset, newLength });
    }
  }
  let s0offset = $eF;
  for (const s1ToS2 of s1ToS2Map) {
    const s0ToS1Map2 = nextS0ToS1MapWithS1LengthOf(s1ToS2.lengthBefore);
    if (s1ToS2.modified) {
      const s0Length = $lF(s0ToS1Map2, (s) => s.lengthBefore);
      const s0EndOffset = $kF(s0offset, s0Length);
      pushEdit(s0offset, s0EndOffset, s1ToS2.lengthAfter);
      s0offset = s0EndOffset;
    } else {
      for (const s1 of s0ToS1Map2) {
        const s0startOffset = s0offset;
        s0offset = $kF(s0offset, s1.lengthBefore);
        if (s1.modified) {
          pushEdit(s0startOffset, s0offset, s1.lengthAfter);
        }
      }
    }
  }
  return result;
}
var LengthMapping = class _LengthMapping {
  constructor(modified, lengthBefore, lengthAfter) {
    this.modified = modified;
    this.lengthBefore = lengthBefore;
    this.lengthAfter = lengthAfter;
  }
  splitAt(lengthAfter) {
    const remainingLengthAfter = $nF(lengthAfter, this.lengthAfter);
    if ($mF(remainingLengthAfter, $eF)) {
      return [this, void 0];
    } else if (this.modified) {
      return [
        new _LengthMapping(this.modified, this.lengthBefore, lengthAfter),
        new _LengthMapping(this.modified, $eF, remainingLengthAfter)
      ];
    } else {
      return [
        new _LengthMapping(this.modified, lengthAfter, lengthAfter),
        new _LengthMapping(this.modified, remainingLengthAfter, remainingLengthAfter)
      ];
    }
  }
  toString() {
    return `${this.modified ? "M" : "U"}:${$hF(this.lengthBefore)} -> ${$hF(this.lengthAfter)}`;
  }
};
function toLengthMapping(textEditInfos) {
  const result = [];
  let lastOffset = $eF;
  for (const textEditInfo of textEditInfos) {
    const spaceLength = $nF(lastOffset, textEditInfo.startOffset);
    if (!$fF(spaceLength)) {
      result.push(new LengthMapping(false, spaceLength, spaceLength));
    }
    const lengthBefore = $nF(textEditInfo.startOffset, textEditInfo.endOffset);
    result.push(new LengthMapping(true, lengthBefore, textEditInfo.newLength));
    lastOffset = textEditInfo.endOffset;
  }
  return result;
}

// out-build/vs/editor/common/model/bracketPairsTextModelPart/bracketPairsTree/bracketPairsTree.js
var $JG = class extends $3c {
  didLanguageChange(languageId) {
    return this.g.didLanguageChange(languageId);
  }
  constructor(m, n) {
    super();
    this.m = m;
    this.n = n;
    this.a = new $ze();
    this.f = new $CF();
    this.g = new $UF(this.f, this.n);
    this.onDidChange = this.a.event;
    this.h = [];
    this.j = [];
    if (!m.tokenization.hasTokens) {
      const brackets = this.g.getSingleLanguageBracketTokens(this.m.getLanguageId());
      const tokenizer = new $XF(this.m.getValue(), brackets);
      this.b = $HG(tokenizer, [], void 0, true);
      this.c = this.b;
    } else if (m.tokenization.backgroundTokenizationState === 2) {
      this.b = void 0;
      this.c = this.u([], void 0, false);
    } else {
      this.b = this.u([], void 0, true);
      this.c = this.b;
    }
  }
  //#region TextModel events
  handleDidChangeBackgroundTokenizationState() {
    if (this.m.tokenization.backgroundTokenizationState === 2) {
      const wasUndefined = this.b === void 0;
      this.b = void 0;
      if (!wasUndefined) {
        this.a.fire();
      }
    }
  }
  handleDidChangeTokens({ ranges }) {
    const edits = ranges.map((r2) => new $CG($gF(r2.fromLineNumber - 1, 0), $gF(r2.toLineNumber, 0), $gF(r2.toLineNumber - r2.fromLineNumber + 1, 0)));
    this.s(edits, true);
    if (!this.b) {
      this.a.fire();
    }
  }
  handleContentChanged(change) {
    const edits = $CG.fromModelContentChanges(change.changes);
    this.s(edits, false);
  }
  s(edits, tokenChange) {
    const result = $IG(this.j, edits);
    this.j = result;
    if (this.b && !tokenChange) {
      this.h = $IG(this.h, edits);
    }
  }
  //#endregion
  t() {
    if (this.j.length > 0) {
      this.c = this.u(this.j, this.c, false);
      this.j = [];
    }
    if (this.h.length > 0) {
      if (this.b) {
        this.b = this.u(this.h, this.b, false);
      }
      this.h = [];
    }
  }
  /**
   * @pure (only if isPure = true)
  */
  u(edits, previousAst, immutable) {
    const isPure = false;
    const previousAstClone = isPure ? previousAst?.deepClone() : previousAst;
    const tokenizer = new $WF(this.m, this.g);
    const result = $HG(tokenizer, edits, previousAstClone, immutable);
    return result;
  }
  getBracketsInRange(range, onlyColorizedBrackets) {
    this.t();
    const startOffset = $gF(range.startLineNumber - 1, range.startColumn - 1);
    const endOffset = $gF(range.endLineNumber - 1, range.endColumn - 1);
    return new $cc((cb) => {
      const node = this.b || this.c;
      collectBrackets(node, $eF, node.length, startOffset, endOffset, cb, 0, 0, /* @__PURE__ */ new Map(), onlyColorizedBrackets);
    });
  }
  getBracketPairsInRange(range, includeMinIndentation) {
    this.t();
    const startLength = $sF(range.getStartPosition());
    const endLength = $sF(range.getEndPosition());
    return new $cc((cb) => {
      const node = this.b || this.c;
      const context = new CollectBracketPairsContext(cb, includeMinIndentation, this.m);
      collectBracketPairs(node, $eF, node.length, startLength, endLength, context, 0, /* @__PURE__ */ new Map());
    });
  }
  getFirstBracketAfter(position) {
    this.t();
    const node = this.b || this.c;
    return getFirstBracketAfter(node, $eF, node.length, $sF(position));
  }
  getFirstBracketBefore(position) {
    this.t();
    const node = this.b || this.c;
    return getFirstBracketBefore(node, $eF, node.length, $sF(position));
  }
};
function getFirstBracketBefore(node, nodeOffsetStart, nodeOffsetEnd, position) {
  if (node.kind === 4 || node.kind === 2) {
    const lengths = [];
    for (const child of node.children) {
      nodeOffsetEnd = $kF(nodeOffsetStart, child.length);
      lengths.push({ nodeOffsetStart, nodeOffsetEnd });
      nodeOffsetStart = nodeOffsetEnd;
    }
    for (let i2 = lengths.length - 1; i2 >= 0; i2--) {
      const { nodeOffsetStart: nodeOffsetStart2, nodeOffsetEnd: nodeOffsetEnd2 } = lengths[i2];
      if ($oF(nodeOffsetStart2, position)) {
        const result = getFirstBracketBefore(node.children[i2], nodeOffsetStart2, nodeOffsetEnd2, position);
        if (result) {
          return result;
        }
      }
    }
    return null;
  } else if (node.kind === 3) {
    return null;
  } else if (node.kind === 1) {
    const range = $tF(nodeOffsetStart, nodeOffsetEnd);
    return {
      bracketInfo: node.bracketInfo,
      range
    };
  }
  return null;
}
function getFirstBracketAfter(node, nodeOffsetStart, nodeOffsetEnd, position) {
  if (node.kind === 4 || node.kind === 2) {
    for (const child of node.children) {
      nodeOffsetEnd = $kF(nodeOffsetStart, child.length);
      if ($oF(position, nodeOffsetEnd)) {
        const result = getFirstBracketAfter(child, nodeOffsetStart, nodeOffsetEnd, position);
        if (result) {
          return result;
        }
      }
      nodeOffsetStart = nodeOffsetEnd;
    }
    return null;
  } else if (node.kind === 3) {
    return null;
  } else if (node.kind === 1) {
    const range = $tF(nodeOffsetStart, nodeOffsetEnd);
    return {
      bracketInfo: node.bracketInfo,
      range
    };
  }
  return null;
}
function collectBrackets(node, nodeOffsetStart, nodeOffsetEnd, startOffset, endOffset, push, level, nestingLevelOfEqualBracketType, levelPerBracketType, onlyColorizedBrackets, parentPairIsIncomplete = false) {
  if (level > 200) {
    return true;
  }
  whileLoop: while (true) {
    switch (node.kind) {
      case 4: {
        const childCount = node.childrenLength;
        for (let i2 = 0; i2 < childCount; i2++) {
          const child = node.getChild(i2);
          if (!child) {
            continue;
          }
          nodeOffsetEnd = $kF(nodeOffsetStart, child.length);
          if ($pF(nodeOffsetStart, endOffset) && $qF(nodeOffsetEnd, startOffset)) {
            const childEndsAfterEnd = $qF(nodeOffsetEnd, endOffset);
            if (childEndsAfterEnd) {
              node = child;
              continue whileLoop;
            }
            const shouldContinue = collectBrackets(child, nodeOffsetStart, nodeOffsetEnd, startOffset, endOffset, push, level, 0, levelPerBracketType, onlyColorizedBrackets);
            if (!shouldContinue) {
              return false;
            }
          }
          nodeOffsetStart = nodeOffsetEnd;
        }
        return true;
      }
      case 2: {
        const colorize = !onlyColorizedBrackets || !node.closingBracket || node.closingBracket.bracketInfo.closesColorized(node.openingBracket.bracketInfo);
        let levelPerBracket = 0;
        if (levelPerBracketType) {
          let existing = levelPerBracketType.get(node.openingBracket.text);
          if (existing === void 0) {
            existing = 0;
          }
          levelPerBracket = existing;
          if (colorize) {
            existing++;
            levelPerBracketType.set(node.openingBracket.text, existing);
          }
        }
        const childCount = node.childrenLength;
        for (let i2 = 0; i2 < childCount; i2++) {
          const child = node.getChild(i2);
          if (!child) {
            continue;
          }
          nodeOffsetEnd = $kF(nodeOffsetStart, child.length);
          if ($pF(nodeOffsetStart, endOffset) && $qF(nodeOffsetEnd, startOffset)) {
            const childEndsAfterEnd = $qF(nodeOffsetEnd, endOffset);
            if (childEndsAfterEnd && child.kind !== 1) {
              node = child;
              if (colorize) {
                level++;
                nestingLevelOfEqualBracketType = levelPerBracket + 1;
              } else {
                nestingLevelOfEqualBracketType = levelPerBracket;
              }
              continue whileLoop;
            }
            if (colorize || child.kind !== 1 || !node.closingBracket) {
              const shouldContinue = collectBrackets(child, nodeOffsetStart, nodeOffsetEnd, startOffset, endOffset, push, colorize ? level + 1 : level, colorize ? levelPerBracket + 1 : levelPerBracket, levelPerBracketType, onlyColorizedBrackets, !node.closingBracket);
              if (!shouldContinue) {
                return false;
              }
            }
          }
          nodeOffsetStart = nodeOffsetEnd;
        }
        levelPerBracketType?.set(node.openingBracket.text, levelPerBracket);
        return true;
      }
      case 3: {
        const range = $tF(nodeOffsetStart, nodeOffsetEnd);
        return push(new $4F(range, level - 1, 0, true));
      }
      case 1: {
        const range = $tF(nodeOffsetStart, nodeOffsetEnd);
        return push(new $4F(range, level - 1, nestingLevelOfEqualBracketType - 1, parentPairIsIncomplete));
      }
      case 0:
        return true;
    }
  }
}
var CollectBracketPairsContext = class {
  constructor(push, includeMinIndentation, textModel) {
    this.push = push;
    this.includeMinIndentation = includeMinIndentation;
    this.textModel = textModel;
  }
};
function collectBracketPairs(node, nodeOffsetStart, nodeOffsetEnd, startOffset, endOffset, context, level, levelPerBracketType) {
  if (level > 200) {
    return true;
  }
  let shouldContinue = true;
  if (node.kind === 2) {
    let levelPerBracket = 0;
    if (levelPerBracketType) {
      let existing = levelPerBracketType.get(node.openingBracket.text);
      if (existing === void 0) {
        existing = 0;
      }
      levelPerBracket = existing;
      existing++;
      levelPerBracketType.set(node.openingBracket.text, existing);
    }
    const openingBracketEnd = $kF(nodeOffsetStart, node.openingBracket.length);
    let minIndentation = -1;
    if (context.includeMinIndentation) {
      minIndentation = node.computeMinIndentation(nodeOffsetStart, context.textModel);
    }
    shouldContinue = context.push(new $6F($tF(nodeOffsetStart, nodeOffsetEnd), $tF(nodeOffsetStart, openingBracketEnd), node.closingBracket ? $tF($kF(openingBracketEnd, node.child?.length || $eF), nodeOffsetEnd) : void 0, level, levelPerBracket, node, minIndentation));
    nodeOffsetStart = openingBracketEnd;
    if (shouldContinue && node.child) {
      const child = node.child;
      nodeOffsetEnd = $kF(nodeOffsetStart, child.length);
      if ($pF(nodeOffsetStart, endOffset) && $qF(nodeOffsetEnd, startOffset)) {
        shouldContinue = collectBracketPairs(child, nodeOffsetStart, nodeOffsetEnd, startOffset, endOffset, context, level + 1, levelPerBracketType);
        if (!shouldContinue) {
          return false;
        }
      }
    }
    levelPerBracketType?.set(node.openingBracket.text, levelPerBracket);
  } else {
    let curOffset = nodeOffsetStart;
    for (const child of node.children) {
      const childOffset = curOffset;
      curOffset = $kF(curOffset, child.length);
      if ($pF(childOffset, endOffset) && $pF(startOffset, curOffset)) {
        shouldContinue = collectBracketPairs(child, childOffset, curOffset, startOffset, endOffset, context, level, levelPerBracketType);
        if (!shouldContinue) {
          return false;
        }
      }
    }
  }
  return shouldContinue;
}

// out-build/vs/editor/common/model/bracketPairsTextModelPart/bracketPairsImpl.js
var $KG = class extends $3c {
  get f() {
    const maxSupportedDocumentLength = (
      /* max lines */
      5e4 * /* average column count */
      100
    );
    return this.h.getValueLength() <= maxSupportedDocumentLength;
  }
  constructor(h3, j) {
    super();
    this.h = h3;
    this.j = j;
    this.a = this.B(new $4c());
    this.c = new $ze();
    this.onDidChange = this.c.event;
    this.g = false;
  }
  //#region TextModel events
  handleLanguageConfigurationServiceChange(e) {
    if (!e.languageId || this.a.value?.object.didLanguageChange(e.languageId)) {
      this.a.clear();
      this.m();
    }
  }
  handleDidChangeOptions(e) {
    this.a.clear();
    this.m();
  }
  handleDidChangeLanguage(e) {
    this.a.clear();
    this.m();
  }
  handleDidChangeContent(change) {
    this.a.value?.object.handleContentChanged(change);
  }
  handleDidChangeBackgroundTokenizationState() {
    this.a.value?.object.handleDidChangeBackgroundTokenizationState();
  }
  handleDidChangeTokens(e) {
    this.a.value?.object.handleDidChangeTokens(e);
  }
  //#endregion
  m() {
    if (this.g && this.f) {
      if (!this.a.value) {
        const store = new $2c();
        this.a.value = createDisposableRef(store.add(new $JG(this.h, (languageId) => {
          return this.j.getLanguageConfiguration(languageId);
        })), store);
        store.add(this.a.value.object.onDidChange((e) => this.c.fire(e)));
        this.c.fire();
      }
    } else {
      if (this.a.value) {
        this.a.clear();
        this.c.fire();
      }
    }
  }
  /**
   * Returns all bracket pairs that intersect the given range.
   * The result is sorted by the start position.
  */
  getBracketPairsInRange(range) {
    this.g = true;
    this.m();
    return this.a.value?.object.getBracketPairsInRange(range, false) || $cc.empty;
  }
  getBracketPairsInRangeWithMinIndentation(range) {
    this.g = true;
    this.m();
    return this.a.value?.object.getBracketPairsInRange(range, true) || $cc.empty;
  }
  getBracketsInRange(range, onlyColorizedBrackets = false) {
    this.g = true;
    this.m();
    return this.a.value?.object.getBracketsInRange(range, onlyColorizedBrackets) || $cc.empty;
  }
  findMatchingBracketUp(_bracket, _position, maxDuration) {
    const position = this.h.validatePosition(_position);
    const languageId = this.h.getLanguageIdAtPosition(position.lineNumber, position.column);
    if (this.f) {
      const closingBracketInfo = this.j.getLanguageConfiguration(languageId).bracketsNew.getClosingBracketInfo(_bracket);
      if (!closingBracketInfo) {
        return null;
      }
      const bracketPair = this.getBracketPairsInRange($9C.fromPositions(_position, _position)).findLast((b) => closingBracketInfo.closes(b.openingBracketInfo));
      if (bracketPair) {
        return bracketPair.openingBracketRange;
      }
      return null;
    } else {
      const bracket = _bracket.toLowerCase();
      const bracketsSupport = this.j.getLanguageConfiguration(languageId).brackets;
      if (!bracketsSupport) {
        return null;
      }
      const data = bracketsSupport.textIsBracket[bracket];
      if (!data) {
        return null;
      }
      return stripBracketSearchCanceled(this.u(data, position, createTimeBasedContinueBracketSearchPredicate(maxDuration)));
    }
  }
  matchBracket(position, maxDuration) {
    if (this.f) {
      const bracketPair = this.getBracketPairsInRange($9C.fromPositions(position, position)).filter((item) => item.closingBracketRange !== void 0 && (item.openingBracketRange.containsPosition(position) || item.closingBracketRange.containsPosition(position))).findLastMaxBy($9b((item) => item.openingBracketRange.containsPosition(position) ? item.openingBracketRange : item.closingBracketRange, $9C.compareRangesUsingStarts));
      if (bracketPair) {
        return [bracketPair.openingBracketRange, bracketPair.closingBracketRange];
      }
      return null;
    } else {
      const continueSearchPredicate = createTimeBasedContinueBracketSearchPredicate(maxDuration);
      return this.s(this.h.validatePosition(position), continueSearchPredicate);
    }
  }
  n(position, lineTokens, modeBrackets, tokenIndex) {
    const tokenCount = lineTokens.getCount();
    const currentLanguageId = lineTokens.getLanguageId(tokenIndex);
    let searchStartOffset = Math.max(0, position.column - 1 - modeBrackets.maxBracketLength);
    for (let i2 = tokenIndex - 1; i2 >= 0; i2--) {
      const tokenEndOffset = lineTokens.getEndOffset(i2);
      if (tokenEndOffset <= searchStartOffset) {
        break;
      }
      if ($4E(lineTokens.getStandardTokenType(i2)) || lineTokens.getLanguageId(i2) !== currentLanguageId) {
        searchStartOffset = tokenEndOffset;
        break;
      }
    }
    let searchEndOffset = Math.min(lineTokens.getLineContent().length, position.column - 1 + modeBrackets.maxBracketLength);
    for (let i2 = tokenIndex + 1; i2 < tokenCount; i2++) {
      const tokenStartOffset = lineTokens.getStartOffset(i2);
      if (tokenStartOffset >= searchEndOffset) {
        break;
      }
      if ($4E(lineTokens.getStandardTokenType(i2)) || lineTokens.getLanguageId(i2) !== currentLanguageId) {
        searchEndOffset = tokenStartOffset;
        break;
      }
    }
    return { searchStartOffset, searchEndOffset };
  }
  s(position, continueSearchPredicate) {
    const lineNumber = position.lineNumber;
    const lineTokens = this.h.tokenization.getLineTokens(lineNumber);
    const lineText = this.h.getLineContent(lineNumber);
    const tokenIndex = lineTokens.findTokenIndexAtOffset(position.column - 1);
    if (tokenIndex < 0) {
      return null;
    }
    const currentModeBrackets = this.j.getLanguageConfiguration(lineTokens.getLanguageId(tokenIndex)).brackets;
    if (currentModeBrackets && !$4E(lineTokens.getStandardTokenType(tokenIndex))) {
      let { searchStartOffset, searchEndOffset } = this.n(position, lineTokens, currentModeBrackets, tokenIndex);
      let bestResult = null;
      while (true) {
        const foundBracket = $0E.findNextBracketInRange(currentModeBrackets.forwardRegex, lineNumber, lineText, searchStartOffset, searchEndOffset);
        if (!foundBracket) {
          break;
        }
        if (foundBracket.startColumn <= position.column && position.column <= foundBracket.endColumn) {
          const foundBracketText = lineText.substring(foundBracket.startColumn - 1, foundBracket.endColumn - 1).toLowerCase();
          const r2 = this.t(foundBracket, currentModeBrackets.textIsBracket[foundBracketText], currentModeBrackets.textIsOpenBracket[foundBracketText], continueSearchPredicate);
          if (r2) {
            if (r2 instanceof BracketSearchCanceled) {
              return null;
            }
            bestResult = r2;
          }
        }
        searchStartOffset = foundBracket.endColumn - 1;
      }
      if (bestResult) {
        return bestResult;
      }
    }
    if (tokenIndex > 0 && lineTokens.getStartOffset(tokenIndex) === position.column - 1) {
      const prevTokenIndex = tokenIndex - 1;
      const prevModeBrackets = this.j.getLanguageConfiguration(lineTokens.getLanguageId(prevTokenIndex)).brackets;
      if (prevModeBrackets && !$4E(lineTokens.getStandardTokenType(prevTokenIndex))) {
        const { searchStartOffset, searchEndOffset } = this.n(position, lineTokens, prevModeBrackets, prevTokenIndex);
        const foundBracket = $0E.findPrevBracketInRange(prevModeBrackets.reversedRegex, lineNumber, lineText, searchStartOffset, searchEndOffset);
        if (foundBracket && foundBracket.startColumn <= position.column && position.column <= foundBracket.endColumn) {
          const foundBracketText = lineText.substring(foundBracket.startColumn - 1, foundBracket.endColumn - 1).toLowerCase();
          const r2 = this.t(foundBracket, prevModeBrackets.textIsBracket[foundBracketText], prevModeBrackets.textIsOpenBracket[foundBracketText], continueSearchPredicate);
          if (r2) {
            if (r2 instanceof BracketSearchCanceled) {
              return null;
            }
            return r2;
          }
        }
      }
    }
    return null;
  }
  t(foundBracket, data, isOpen, continueSearchPredicate) {
    if (!data) {
      return null;
    }
    const matched = isOpen ? this.w(data, foundBracket.getEndPosition(), continueSearchPredicate) : this.u(data, foundBracket.getStartPosition(), continueSearchPredicate);
    if (!matched) {
      return null;
    }
    if (matched instanceof BracketSearchCanceled) {
      return matched;
    }
    return [foundBracket, matched];
  }
  u(bracket, position, continueSearchPredicate) {
    const languageId = bracket.languageId;
    const reversedBracketRegex = bracket.reversedRegex;
    let count = -1;
    let totalCallCount = 0;
    const searchPrevMatchingBracketInRange = (lineNumber, lineText, searchStartOffset, searchEndOffset) => {
      while (true) {
        if (continueSearchPredicate && ++totalCallCount % 100 === 0 && !continueSearchPredicate()) {
          return BracketSearchCanceled.INSTANCE;
        }
        const r2 = $0E.findPrevBracketInRange(reversedBracketRegex, lineNumber, lineText, searchStartOffset, searchEndOffset);
        if (!r2) {
          break;
        }
        const hitText = lineText.substring(r2.startColumn - 1, r2.endColumn - 1).toLowerCase();
        if (bracket.isOpen(hitText)) {
          count++;
        } else if (bracket.isClose(hitText)) {
          count--;
        }
        if (count === 0) {
          return r2;
        }
        searchEndOffset = r2.startColumn - 1;
      }
      return null;
    };
    for (let lineNumber = position.lineNumber; lineNumber >= 1; lineNumber--) {
      const lineTokens = this.h.tokenization.getLineTokens(lineNumber);
      const tokenCount = lineTokens.getCount();
      const lineText = this.h.getLineContent(lineNumber);
      let tokenIndex = tokenCount - 1;
      let searchStartOffset = lineText.length;
      let searchEndOffset = lineText.length;
      if (lineNumber === position.lineNumber) {
        tokenIndex = lineTokens.findTokenIndexAtOffset(position.column - 1);
        searchStartOffset = position.column - 1;
        searchEndOffset = position.column - 1;
      }
      let prevSearchInToken = true;
      for (; tokenIndex >= 0; tokenIndex--) {
        const searchInToken = lineTokens.getLanguageId(tokenIndex) === languageId && !$4E(lineTokens.getStandardTokenType(tokenIndex));
        if (searchInToken) {
          if (prevSearchInToken) {
            searchStartOffset = lineTokens.getStartOffset(tokenIndex);
          } else {
            searchStartOffset = lineTokens.getStartOffset(tokenIndex);
            searchEndOffset = lineTokens.getEndOffset(tokenIndex);
          }
        } else {
          if (prevSearchInToken && searchStartOffset !== searchEndOffset) {
            const r2 = searchPrevMatchingBracketInRange(lineNumber, lineText, searchStartOffset, searchEndOffset);
            if (r2) {
              return r2;
            }
          }
        }
        prevSearchInToken = searchInToken;
      }
      if (prevSearchInToken && searchStartOffset !== searchEndOffset) {
        const r2 = searchPrevMatchingBracketInRange(lineNumber, lineText, searchStartOffset, searchEndOffset);
        if (r2) {
          return r2;
        }
      }
    }
    return null;
  }
  w(bracket, position, continueSearchPredicate) {
    const languageId = bracket.languageId;
    const bracketRegex = bracket.forwardRegex;
    let count = 1;
    let totalCallCount = 0;
    const searchNextMatchingBracketInRange = (lineNumber, lineText, searchStartOffset, searchEndOffset) => {
      while (true) {
        if (continueSearchPredicate && ++totalCallCount % 100 === 0 && !continueSearchPredicate()) {
          return BracketSearchCanceled.INSTANCE;
        }
        const r2 = $0E.findNextBracketInRange(bracketRegex, lineNumber, lineText, searchStartOffset, searchEndOffset);
        if (!r2) {
          break;
        }
        const hitText = lineText.substring(r2.startColumn - 1, r2.endColumn - 1).toLowerCase();
        if (bracket.isOpen(hitText)) {
          count++;
        } else if (bracket.isClose(hitText)) {
          count--;
        }
        if (count === 0) {
          return r2;
        }
        searchStartOffset = r2.endColumn - 1;
      }
      return null;
    };
    const lineCount = this.h.getLineCount();
    for (let lineNumber = position.lineNumber; lineNumber <= lineCount; lineNumber++) {
      const lineTokens = this.h.tokenization.getLineTokens(lineNumber);
      const tokenCount = lineTokens.getCount();
      const lineText = this.h.getLineContent(lineNumber);
      let tokenIndex = 0;
      let searchStartOffset = 0;
      let searchEndOffset = 0;
      if (lineNumber === position.lineNumber) {
        tokenIndex = lineTokens.findTokenIndexAtOffset(position.column - 1);
        searchStartOffset = position.column - 1;
        searchEndOffset = position.column - 1;
      }
      let prevSearchInToken = true;
      for (; tokenIndex < tokenCount; tokenIndex++) {
        const searchInToken = lineTokens.getLanguageId(tokenIndex) === languageId && !$4E(lineTokens.getStandardTokenType(tokenIndex));
        if (searchInToken) {
          if (prevSearchInToken) {
            searchEndOffset = lineTokens.getEndOffset(tokenIndex);
          } else {
            searchStartOffset = lineTokens.getStartOffset(tokenIndex);
            searchEndOffset = lineTokens.getEndOffset(tokenIndex);
          }
        } else {
          if (prevSearchInToken && searchStartOffset !== searchEndOffset) {
            const r2 = searchNextMatchingBracketInRange(lineNumber, lineText, searchStartOffset, searchEndOffset);
            if (r2) {
              return r2;
            }
          }
        }
        prevSearchInToken = searchInToken;
      }
      if (prevSearchInToken && searchStartOffset !== searchEndOffset) {
        const r2 = searchNextMatchingBracketInRange(lineNumber, lineText, searchStartOffset, searchEndOffset);
        if (r2) {
          return r2;
        }
      }
    }
    return null;
  }
  findPrevBracket(_position) {
    const position = this.h.validatePosition(_position);
    if (this.f) {
      this.g = true;
      this.m();
      return this.a.value?.object.getFirstBracketBefore(position) || null;
    }
    let languageId = null;
    let modeBrackets = null;
    let bracketConfig = null;
    for (let lineNumber = position.lineNumber; lineNumber >= 1; lineNumber--) {
      const lineTokens = this.h.tokenization.getLineTokens(lineNumber);
      const tokenCount = lineTokens.getCount();
      const lineText = this.h.getLineContent(lineNumber);
      let tokenIndex = tokenCount - 1;
      let searchStartOffset = lineText.length;
      let searchEndOffset = lineText.length;
      if (lineNumber === position.lineNumber) {
        tokenIndex = lineTokens.findTokenIndexAtOffset(position.column - 1);
        searchStartOffset = position.column - 1;
        searchEndOffset = position.column - 1;
        const tokenLanguageId = lineTokens.getLanguageId(tokenIndex);
        if (languageId !== tokenLanguageId) {
          languageId = tokenLanguageId;
          modeBrackets = this.j.getLanguageConfiguration(languageId).brackets;
          bracketConfig = this.j.getLanguageConfiguration(languageId).bracketsNew;
        }
      }
      let prevSearchInToken = true;
      for (; tokenIndex >= 0; tokenIndex--) {
        const tokenLanguageId = lineTokens.getLanguageId(tokenIndex);
        if (languageId !== tokenLanguageId) {
          if (modeBrackets && bracketConfig && prevSearchInToken && searchStartOffset !== searchEndOffset) {
            const r2 = $0E.findPrevBracketInRange(modeBrackets.reversedRegex, lineNumber, lineText, searchStartOffset, searchEndOffset);
            if (r2) {
              return this.y(bracketConfig, r2);
            }
            prevSearchInToken = false;
          }
          languageId = tokenLanguageId;
          modeBrackets = this.j.getLanguageConfiguration(languageId).brackets;
          bracketConfig = this.j.getLanguageConfiguration(languageId).bracketsNew;
        }
        const searchInToken = !!modeBrackets && !$4E(lineTokens.getStandardTokenType(tokenIndex));
        if (searchInToken) {
          if (prevSearchInToken) {
            searchStartOffset = lineTokens.getStartOffset(tokenIndex);
          } else {
            searchStartOffset = lineTokens.getStartOffset(tokenIndex);
            searchEndOffset = lineTokens.getEndOffset(tokenIndex);
          }
        } else {
          if (bracketConfig && modeBrackets && prevSearchInToken && searchStartOffset !== searchEndOffset) {
            const r2 = $0E.findPrevBracketInRange(modeBrackets.reversedRegex, lineNumber, lineText, searchStartOffset, searchEndOffset);
            if (r2) {
              return this.y(bracketConfig, r2);
            }
          }
        }
        prevSearchInToken = searchInToken;
      }
      if (bracketConfig && modeBrackets && prevSearchInToken && searchStartOffset !== searchEndOffset) {
        const r2 = $0E.findPrevBracketInRange(modeBrackets.reversedRegex, lineNumber, lineText, searchStartOffset, searchEndOffset);
        if (r2) {
          return this.y(bracketConfig, r2);
        }
      }
    }
    return null;
  }
  findNextBracket(_position) {
    const position = this.h.validatePosition(_position);
    if (this.f) {
      this.g = true;
      this.m();
      return this.a.value?.object.getFirstBracketAfter(position) || null;
    }
    const lineCount = this.h.getLineCount();
    let languageId = null;
    let modeBrackets = null;
    let bracketConfig = null;
    for (let lineNumber = position.lineNumber; lineNumber <= lineCount; lineNumber++) {
      const lineTokens = this.h.tokenization.getLineTokens(lineNumber);
      const tokenCount = lineTokens.getCount();
      const lineText = this.h.getLineContent(lineNumber);
      let tokenIndex = 0;
      let searchStartOffset = 0;
      let searchEndOffset = 0;
      if (lineNumber === position.lineNumber) {
        tokenIndex = lineTokens.findTokenIndexAtOffset(position.column - 1);
        searchStartOffset = position.column - 1;
        searchEndOffset = position.column - 1;
        const tokenLanguageId = lineTokens.getLanguageId(tokenIndex);
        if (languageId !== tokenLanguageId) {
          languageId = tokenLanguageId;
          modeBrackets = this.j.getLanguageConfiguration(languageId).brackets;
          bracketConfig = this.j.getLanguageConfiguration(languageId).bracketsNew;
        }
      }
      let prevSearchInToken = true;
      for (; tokenIndex < tokenCount; tokenIndex++) {
        const tokenLanguageId = lineTokens.getLanguageId(tokenIndex);
        if (languageId !== tokenLanguageId) {
          if (bracketConfig && modeBrackets && prevSearchInToken && searchStartOffset !== searchEndOffset) {
            const r2 = $0E.findNextBracketInRange(modeBrackets.forwardRegex, lineNumber, lineText, searchStartOffset, searchEndOffset);
            if (r2) {
              return this.y(bracketConfig, r2);
            }
            prevSearchInToken = false;
          }
          languageId = tokenLanguageId;
          modeBrackets = this.j.getLanguageConfiguration(languageId).brackets;
          bracketConfig = this.j.getLanguageConfiguration(languageId).bracketsNew;
        }
        const searchInToken = !!modeBrackets && !$4E(lineTokens.getStandardTokenType(tokenIndex));
        if (searchInToken) {
          if (prevSearchInToken) {
            searchEndOffset = lineTokens.getEndOffset(tokenIndex);
          } else {
            searchStartOffset = lineTokens.getStartOffset(tokenIndex);
            searchEndOffset = lineTokens.getEndOffset(tokenIndex);
          }
        } else {
          if (bracketConfig && modeBrackets && prevSearchInToken && searchStartOffset !== searchEndOffset) {
            const r2 = $0E.findNextBracketInRange(modeBrackets.forwardRegex, lineNumber, lineText, searchStartOffset, searchEndOffset);
            if (r2) {
              return this.y(bracketConfig, r2);
            }
          }
        }
        prevSearchInToken = searchInToken;
      }
      if (bracketConfig && modeBrackets && prevSearchInToken && searchStartOffset !== searchEndOffset) {
        const r2 = $0E.findNextBracketInRange(modeBrackets.forwardRegex, lineNumber, lineText, searchStartOffset, searchEndOffset);
        if (r2) {
          return this.y(bracketConfig, r2);
        }
      }
    }
    return null;
  }
  findEnclosingBrackets(_position, maxDuration) {
    const position = this.h.validatePosition(_position);
    if (this.f) {
      const range = $9C.fromPositions(position);
      const bracketPair = this.getBracketPairsInRange($9C.fromPositions(position, position)).findLast((item) => item.closingBracketRange !== void 0 && item.range.strictContainsRange(range));
      if (bracketPair) {
        return [bracketPair.openingBracketRange, bracketPair.closingBracketRange];
      }
      return null;
    }
    const continueSearchPredicate = createTimeBasedContinueBracketSearchPredicate(maxDuration);
    const lineCount = this.h.getLineCount();
    const savedCounts = /* @__PURE__ */ new Map();
    let counts = [];
    const resetCounts = (languageId2, modeBrackets2) => {
      if (!savedCounts.has(languageId2)) {
        const tmp = [];
        for (let i2 = 0, len = modeBrackets2 ? modeBrackets2.brackets.length : 0; i2 < len; i2++) {
          tmp[i2] = 0;
        }
        savedCounts.set(languageId2, tmp);
      }
      counts = savedCounts.get(languageId2);
    };
    let totalCallCount = 0;
    const searchInRange = (modeBrackets2, lineNumber, lineText, searchStartOffset, searchEndOffset) => {
      while (true) {
        if (continueSearchPredicate && ++totalCallCount % 100 === 0 && !continueSearchPredicate()) {
          return BracketSearchCanceled.INSTANCE;
        }
        const r2 = $0E.findNextBracketInRange(modeBrackets2.forwardRegex, lineNumber, lineText, searchStartOffset, searchEndOffset);
        if (!r2) {
          break;
        }
        const hitText = lineText.substring(r2.startColumn - 1, r2.endColumn - 1).toLowerCase();
        const bracket = modeBrackets2.textIsBracket[hitText];
        if (bracket) {
          if (bracket.isOpen(hitText)) {
            counts[bracket.index]++;
          } else if (bracket.isClose(hitText)) {
            counts[bracket.index]--;
          }
          if (counts[bracket.index] === -1) {
            return this.t(r2, bracket, false, continueSearchPredicate);
          }
        }
        searchStartOffset = r2.endColumn - 1;
      }
      return null;
    };
    let languageId = null;
    let modeBrackets = null;
    for (let lineNumber = position.lineNumber; lineNumber <= lineCount; lineNumber++) {
      const lineTokens = this.h.tokenization.getLineTokens(lineNumber);
      const tokenCount = lineTokens.getCount();
      const lineText = this.h.getLineContent(lineNumber);
      let tokenIndex = 0;
      let searchStartOffset = 0;
      let searchEndOffset = 0;
      if (lineNumber === position.lineNumber) {
        tokenIndex = lineTokens.findTokenIndexAtOffset(position.column - 1);
        searchStartOffset = position.column - 1;
        searchEndOffset = position.column - 1;
        const tokenLanguageId = lineTokens.getLanguageId(tokenIndex);
        if (languageId !== tokenLanguageId) {
          languageId = tokenLanguageId;
          modeBrackets = this.j.getLanguageConfiguration(languageId).brackets;
          resetCounts(languageId, modeBrackets);
        }
      }
      let prevSearchInToken = true;
      for (; tokenIndex < tokenCount; tokenIndex++) {
        const tokenLanguageId = lineTokens.getLanguageId(tokenIndex);
        if (languageId !== tokenLanguageId) {
          if (modeBrackets && prevSearchInToken && searchStartOffset !== searchEndOffset) {
            const r2 = searchInRange(modeBrackets, lineNumber, lineText, searchStartOffset, searchEndOffset);
            if (r2) {
              return stripBracketSearchCanceled(r2);
            }
            prevSearchInToken = false;
          }
          languageId = tokenLanguageId;
          modeBrackets = this.j.getLanguageConfiguration(languageId).brackets;
          resetCounts(languageId, modeBrackets);
        }
        const searchInToken = !!modeBrackets && !$4E(lineTokens.getStandardTokenType(tokenIndex));
        if (searchInToken) {
          if (prevSearchInToken) {
            searchEndOffset = lineTokens.getEndOffset(tokenIndex);
          } else {
            searchStartOffset = lineTokens.getStartOffset(tokenIndex);
            searchEndOffset = lineTokens.getEndOffset(tokenIndex);
          }
        } else {
          if (modeBrackets && prevSearchInToken && searchStartOffset !== searchEndOffset) {
            const r2 = searchInRange(modeBrackets, lineNumber, lineText, searchStartOffset, searchEndOffset);
            if (r2) {
              return stripBracketSearchCanceled(r2);
            }
          }
        }
        prevSearchInToken = searchInToken;
      }
      if (modeBrackets && prevSearchInToken && searchStartOffset !== searchEndOffset) {
        const r2 = searchInRange(modeBrackets, lineNumber, lineText, searchStartOffset, searchEndOffset);
        if (r2) {
          return stripBracketSearchCanceled(r2);
        }
      }
    }
    return null;
  }
  y(bracketConfig, r2) {
    if (!r2) {
      return null;
    }
    let text2 = this.h.getValueInRange(r2);
    text2 = text2.toLowerCase();
    const bracketInfo = bracketConfig.getBracketInfo(text2);
    if (!bracketInfo) {
      return null;
    }
    return {
      range: r2,
      bracketInfo
    };
  }
};
function createDisposableRef(object, disposable) {
  return {
    object,
    dispose: () => disposable?.dispose()
  };
}
function createTimeBasedContinueBracketSearchPredicate(maxDuration) {
  if (typeof maxDuration === "undefined") {
    return () => true;
  } else {
    const startTime = Date.now();
    return () => {
      return Date.now() - startTime <= maxDuration;
    };
  }
}
var BracketSearchCanceled = class _BracketSearchCanceled {
  static {
    this.INSTANCE = new _BracketSearchCanceled();
  }
  constructor() {
    this._searchCanceledBrand = void 0;
  }
};
function stripBracketSearchCanceled(result) {
  if (result instanceof BracketSearchCanceled) {
    return null;
  }
  return result;
}

// out-build/vs/editor/common/model/bracketPairsTextModelPart/colorizedBracketPairsDecorationProvider.js
var $OH = class extends $3c {
  constructor(g) {
    super();
    this.g = g;
    this.b = new ColorProvider();
    this.f = new $ze();
    this.onDidChange = this.f.event;
    this.a = g.getOptions().bracketPairColorizationOptions;
    this.B(g.bracketPairs.onDidChange((e) => {
      this.f.fire();
    }));
  }
  //#region TextModel events
  handleDidChangeOptions(e) {
    this.a = this.g.getOptions().bracketPairColorizationOptions;
  }
  //#endregion
  getDecorationsInRange(range, ownerId2, filterOutValidation, onlyMinimapDecorations) {
    if (onlyMinimapDecorations) {
      return [];
    }
    if (ownerId2 === void 0) {
      return [];
    }
    if (!this.a.enabled) {
      return [];
    }
    const result = this.g.bracketPairs.getBracketsInRange(range, true).map((bracket) => ({
      id: `bracket${bracket.range.toString()}-${bracket.nestingLevel}`,
      options: {
        description: "BracketPairColorization",
        inlineClassName: this.b.getInlineClassName(bracket, this.a.independentColorPoolPerBracketType)
      },
      ownerId: 0,
      range: bracket.range
    })).toArray();
    return result;
  }
  getAllDecorations(ownerId2, filterOutValidation) {
    if (ownerId2 === void 0) {
      return [];
    }
    if (!this.a.enabled) {
      return [];
    }
    return this.getDecorationsInRange(new $9C(1, 1, this.g.getLineCount(), 1), ownerId2, filterOutValidation);
  }
};
var ColorProvider = class {
  constructor() {
    this.unexpectedClosingBracketClassName = "unexpected-closing-bracket";
  }
  getInlineClassName(bracket, independentColorPoolPerBracketType) {
    if (bracket.isInvalid) {
      return this.unexpectedClosingBracketClassName;
    }
    return this.getInlineClassNameOfLevel(independentColorPoolPerBracketType ? bracket.nestingLevelOfEqualBracketType : bracket.nestingLevel);
  }
  getInlineClassNameOfLevel(level) {
    return `bracket-highlighting-${level % 30}`;
  }
};
$ms((theme, collector) => {
  const colors = [
    $tH,
    $uH,
    $vH,
    $wH,
    $xH,
    $yH
  ];
  const colorProvider = new ColorProvider();
  collector.addRule(`.monaco-editor .${colorProvider.unexpectedClosingBracketClassName} { color: ${theme.getColor($zH)}; }`);
  const colorValues = colors.map((c) => theme.getColor(c)).filter((c) => !!c).filter((c) => !c.isTransparent());
  for (let level = 0; level < 30; level++) {
    const color2 = colorValues[level % colorValues.length];
    collector.addRule(`.monaco-editor .${colorProvider.getInlineClassNameOfLevel(level)} { color: ${color2}; }`);
  }
});

// out-build/vs/editor/common/core/textChange.js
function escapeNewLine(str) {
  return str.replace(/\n/g, "\\n").replace(/\r/g, "\\r");
}
var $dE = class _$dE {
  get oldLength() {
    return this.oldText.length;
  }
  get oldEnd() {
    return this.oldPosition + this.oldText.length;
  }
  get newLength() {
    return this.newText.length;
  }
  get newEnd() {
    return this.newPosition + this.newText.length;
  }
  constructor(oldPosition, oldText, newPosition, newText) {
    this.oldPosition = oldPosition;
    this.oldText = oldText;
    this.newPosition = newPosition;
    this.newText = newText;
  }
  toString() {
    if (this.oldText.length === 0) {
      return `(insert@${this.oldPosition} "${escapeNewLine(this.newText)}")`;
    }
    if (this.newText.length === 0) {
      return `(delete@${this.oldPosition} "${escapeNewLine(this.oldText)}")`;
    }
    return `(replace@${this.oldPosition} "${escapeNewLine(this.oldText)}" with "${escapeNewLine(this.newText)}")`;
  }
  static a(str) {
    return 4 + 2 * str.length;
  }
  static c(b, str, offset) {
    const len = str.length;
    $Hi(b, len, offset);
    offset += 4;
    for (let i2 = 0; i2 < len; i2++) {
      $Fi(b, str.charCodeAt(i2), offset);
      offset += 2;
    }
    return offset;
  }
  static d(b, offset) {
    const len = $Gi(b, offset);
    offset += 4;
    return $bE(b, offset, len);
  }
  writeSize() {
    return 4 + 4 + _$dE.a(this.oldText) + _$dE.a(this.newText);
  }
  write(b, offset) {
    $Hi(b, this.oldPosition, offset);
    offset += 4;
    $Hi(b, this.newPosition, offset);
    offset += 4;
    offset = _$dE.c(b, this.oldText, offset);
    offset = _$dE.c(b, this.newText, offset);
    return offset;
  }
  static read(b, offset, dest) {
    const oldPosition = $Gi(b, offset);
    offset += 4;
    const newPosition = $Gi(b, offset);
    offset += 4;
    const oldText = _$dE.d(b, offset);
    offset += _$dE.a(oldText);
    const newText = _$dE.d(b, offset);
    offset += _$dE.a(newText);
    dest.push(new _$dE(oldPosition, oldText, newPosition, newText));
    return offset;
  }
};
function $eE(prevEdits, currEdits) {
  if (prevEdits === null || prevEdits.length === 0) {
    return currEdits;
  }
  const compressor = new TextChangeCompressor(prevEdits, currEdits);
  return compressor.compress();
}
var TextChangeCompressor = class _TextChangeCompressor {
  constructor(prevEdits, currEdits) {
    this.a = prevEdits;
    this.c = currEdits;
    this.d = [];
    this.e = 0;
    this.f = this.a.length;
    this.g = 0;
    this.h = this.c.length;
    this.j = 0;
  }
  compress() {
    let prevIndex = 0;
    let currIndex = 0;
    let prevEdit = this.n(prevIndex);
    let currEdit = this.l(currIndex);
    while (prevIndex < this.f || currIndex < this.h) {
      if (prevEdit === null) {
        this.k(currEdit);
        currEdit = this.l(++currIndex);
        continue;
      }
      if (currEdit === null) {
        this.m(prevEdit);
        prevEdit = this.n(++prevIndex);
        continue;
      }
      if (currEdit.oldEnd <= prevEdit.newPosition) {
        this.k(currEdit);
        currEdit = this.l(++currIndex);
        continue;
      }
      if (prevEdit.newEnd <= currEdit.oldPosition) {
        this.m(prevEdit);
        prevEdit = this.n(++prevIndex);
        continue;
      }
      if (currEdit.oldPosition < prevEdit.newPosition) {
        const [e1, e2] = _TextChangeCompressor.r(currEdit, prevEdit.newPosition - currEdit.oldPosition);
        this.k(e1);
        currEdit = e2;
        continue;
      }
      if (prevEdit.newPosition < currEdit.oldPosition) {
        const [e1, e2] = _TextChangeCompressor.q(prevEdit, currEdit.oldPosition - prevEdit.newPosition);
        this.m(e1);
        prevEdit = e2;
        continue;
      }
      let mergePrev;
      let mergeCurr;
      if (currEdit.oldEnd === prevEdit.newEnd) {
        mergePrev = prevEdit;
        mergeCurr = currEdit;
        prevEdit = this.n(++prevIndex);
        currEdit = this.l(++currIndex);
      } else if (currEdit.oldEnd < prevEdit.newEnd) {
        const [e1, e2] = _TextChangeCompressor.q(prevEdit, currEdit.oldLength);
        mergePrev = e1;
        mergeCurr = currEdit;
        prevEdit = e2;
        currEdit = this.l(++currIndex);
      } else {
        const [e1, e2] = _TextChangeCompressor.r(currEdit, prevEdit.newLength);
        mergePrev = prevEdit;
        mergeCurr = e1;
        prevEdit = this.n(++prevIndex);
        currEdit = e2;
      }
      this.d[this.e++] = new $dE(mergePrev.oldPosition, mergePrev.oldText, mergeCurr.newPosition, mergeCurr.newText);
      this.g += mergePrev.newLength - mergePrev.oldLength;
      this.j += mergeCurr.newLength - mergeCurr.oldLength;
    }
    const merged = _TextChangeCompressor.s(this.d);
    const cleaned = _TextChangeCompressor.t(merged);
    return cleaned;
  }
  k(currEdit) {
    this.d[this.e++] = _TextChangeCompressor.o(this.g, currEdit);
    this.j += currEdit.newLength - currEdit.oldLength;
  }
  l(currIndex) {
    return currIndex < this.h ? this.c[currIndex] : null;
  }
  m(prevEdit) {
    this.d[this.e++] = _TextChangeCompressor.p(this.j, prevEdit);
    this.g += prevEdit.newLength - prevEdit.oldLength;
  }
  n(prevIndex) {
    return prevIndex < this.f ? this.a[prevIndex] : null;
  }
  static o(prevDeltaOffset, currEdit) {
    return new $dE(currEdit.oldPosition - prevDeltaOffset, currEdit.oldText, currEdit.newPosition, currEdit.newText);
  }
  static p(currDeltaOffset, prevEdit) {
    return new $dE(prevEdit.oldPosition, prevEdit.oldText, prevEdit.newPosition + currDeltaOffset, prevEdit.newText);
  }
  static q(edit3, offset) {
    const preText = edit3.newText.substr(0, offset);
    const postText = edit3.newText.substr(offset);
    return [
      new $dE(edit3.oldPosition, edit3.oldText, edit3.newPosition, preText),
      new $dE(edit3.oldEnd, "", edit3.newPosition + offset, postText)
    ];
  }
  static r(edit3, offset) {
    const preText = edit3.oldText.substr(0, offset);
    const postText = edit3.oldText.substr(offset);
    return [
      new $dE(edit3.oldPosition, preText, edit3.newPosition, edit3.newText),
      new $dE(edit3.oldPosition + offset, postText, edit3.newEnd, "")
    ];
  }
  static s(edits) {
    if (edits.length === 0) {
      return edits;
    }
    const result = [];
    let resultLen = 0;
    let prev = edits[0];
    for (let i2 = 1; i2 < edits.length; i2++) {
      const curr = edits[i2];
      if (prev.oldEnd === curr.oldPosition) {
        prev = new $dE(prev.oldPosition, prev.oldText + curr.oldText, prev.newPosition, prev.newText + curr.newText);
      } else {
        result[resultLen++] = prev;
        prev = curr;
      }
    }
    result[resultLen++] = prev;
    return result;
  }
  static t(edits) {
    if (edits.length === 0) {
      return edits;
    }
    const result = [];
    let resultLen = 0;
    for (let i2 = 0; i2 < edits.length; i2++) {
      const edit3 = edits[i2];
      if (edit3.oldText === edit3.newText) {
        continue;
      }
      result[resultLen++] = edit3;
    }
    return result;
  }
};

// out-build/vs/editor/common/model/editStack.js
function uriGetComparisonKey(resource) {
  return resource.toString();
}
var $PH = class _$PH {
  static create(model, beforeCursorState) {
    const alternativeVersionId = model.getAlternativeVersionId();
    const eol = getModelEOL(model);
    return new _$PH(alternativeVersionId, alternativeVersionId, eol, eol, beforeCursorState, beforeCursorState, []);
  }
  constructor(beforeVersionId, afterVersionId, beforeEOL, afterEOL, beforeCursorState, afterCursorState, changes) {
    this.beforeVersionId = beforeVersionId;
    this.afterVersionId = afterVersionId;
    this.beforeEOL = beforeEOL;
    this.afterEOL = afterEOL;
    this.beforeCursorState = beforeCursorState;
    this.afterCursorState = afterCursorState;
    this.changes = changes;
  }
  append(model, textChanges, afterEOL, afterVersionId, afterCursorState) {
    if (textChanges.length > 0) {
      this.changes = $eE(this.changes, textChanges);
    }
    this.afterEOL = afterEOL;
    this.afterVersionId = afterVersionId;
    this.afterCursorState = afterCursorState;
  }
  static c(selections) {
    return 4 + 4 * 4 * (selections ? selections.length : 0);
  }
  static d(b, selections, offset) {
    $Hi(b, selections ? selections.length : 0, offset);
    offset += 4;
    if (selections) {
      for (const selection of selections) {
        $Hi(b, selection.selectionStartLineNumber, offset);
        offset += 4;
        $Hi(b, selection.selectionStartColumn, offset);
        offset += 4;
        $Hi(b, selection.positionLineNumber, offset);
        offset += 4;
        $Hi(b, selection.positionColumn, offset);
        offset += 4;
      }
    }
    return offset;
  }
  static f(b, offset, dest) {
    const count = $Gi(b, offset);
    offset += 4;
    for (let i2 = 0; i2 < count; i2++) {
      const selectionStartLineNumber = $Gi(b, offset);
      offset += 4;
      const selectionStartColumn = $Gi(b, offset);
      offset += 4;
      const positionLineNumber = $Gi(b, offset);
      offset += 4;
      const positionColumn = $Gi(b, offset);
      offset += 4;
      dest.push(new $_D(selectionStartLineNumber, selectionStartColumn, positionLineNumber, positionColumn));
    }
    return offset;
  }
  serialize() {
    let necessarySize = 4 + 4 + 1 + 1 + _$PH.c(this.beforeCursorState) + _$PH.c(this.afterCursorState) + 4;
    for (const change of this.changes) {
      necessarySize += change.writeSize();
    }
    const b = new Uint8Array(necessarySize);
    let offset = 0;
    $Hi(b, this.beforeVersionId, offset);
    offset += 4;
    $Hi(b, this.afterVersionId, offset);
    offset += 4;
    $Li(b, this.beforeEOL, offset);
    offset += 1;
    $Li(b, this.afterEOL, offset);
    offset += 1;
    offset = _$PH.d(b, this.beforeCursorState, offset);
    offset = _$PH.d(b, this.afterCursorState, offset);
    $Hi(b, this.changes.length, offset);
    offset += 4;
    for (const change of this.changes) {
      offset = change.write(b, offset);
    }
    return b.buffer;
  }
  static deserialize(source) {
    const b = new Uint8Array(source);
    let offset = 0;
    const beforeVersionId = $Gi(b, offset);
    offset += 4;
    const afterVersionId = $Gi(b, offset);
    offset += 4;
    const beforeEOL = $Ki(b, offset);
    offset += 1;
    const afterEOL = $Ki(b, offset);
    offset += 1;
    const beforeCursorState = [];
    offset = _$PH.f(b, offset, beforeCursorState);
    const afterCursorState = [];
    offset = _$PH.f(b, offset, afterCursorState);
    const changeCount = $Gi(b, offset);
    offset += 4;
    const changes = [];
    for (let i2 = 0; i2 < changeCount; i2++) {
      offset = $dE.read(b, offset, changes);
    }
    return new _$PH(beforeVersionId, afterVersionId, beforeEOL, afterEOL, beforeCursorState, afterCursorState, changes);
  }
};
var $QH = class {
  get type() {
    return 0;
  }
  get resource() {
    if (URI.isUri(this.model)) {
      return this.model;
    }
    return this.model.uri;
  }
  constructor(label3, code, model, beforeCursorState) {
    this.label = label3;
    this.code = code;
    this.model = model;
    this.c = $PH.create(model, beforeCursorState);
  }
  toString() {
    const data = this.c instanceof $PH ? this.c : $PH.deserialize(this.c);
    return data.changes.map((change) => change.toString()).join(", ");
  }
  matchesResource(resource) {
    const uri = URI.isUri(this.model) ? this.model : this.model.uri;
    return uri.toString() === resource.toString();
  }
  setModel(model) {
    this.model = model;
  }
  canAppend(model) {
    return this.model === model && this.c instanceof $PH;
  }
  append(model, textChanges, afterEOL, afterVersionId, afterCursorState) {
    if (this.c instanceof $PH) {
      this.c.append(model, textChanges, afterEOL, afterVersionId, afterCursorState);
    }
  }
  close() {
    if (this.c instanceof $PH) {
      this.c = this.c.serialize();
    }
  }
  open() {
    if (!(this.c instanceof $PH)) {
      this.c = $PH.deserialize(this.c);
    }
  }
  undo() {
    if (URI.isUri(this.model)) {
      throw new Error(`Invalid SingleModelEditStackElement`);
    }
    if (this.c instanceof $PH) {
      this.c = this.c.serialize();
    }
    const data = $PH.deserialize(this.c);
    this.model._applyUndo(data.changes, data.beforeEOL, data.beforeVersionId, data.beforeCursorState);
  }
  redo() {
    if (URI.isUri(this.model)) {
      throw new Error(`Invalid SingleModelEditStackElement`);
    }
    if (this.c instanceof $PH) {
      this.c = this.c.serialize();
    }
    const data = $PH.deserialize(this.c);
    this.model._applyRedo(data.changes, data.afterEOL, data.afterVersionId, data.afterCursorState);
  }
  heapSize() {
    if (this.c instanceof $PH) {
      this.c = this.c.serialize();
    }
    return this.c.byteLength + 168;
  }
};
var $RH = class {
  get resources() {
    return this.d.map((editStackElement) => editStackElement.resource);
  }
  constructor(label3, code, editStackElements) {
    this.label = label3;
    this.code = code;
    this.type = 1;
    this.c = true;
    this.d = editStackElements.slice(0);
    this.f = /* @__PURE__ */ new Map();
    for (const editStackElement of this.d) {
      const key2 = uriGetComparisonKey(editStackElement.resource);
      this.f.set(key2, editStackElement);
    }
    this.g = null;
  }
  setDelegate(delegate) {
    this.g = delegate;
  }
  prepareUndoRedo() {
    if (this.g) {
      return this.g.prepareUndoRedo(this);
    }
  }
  getMissingModels() {
    const result = [];
    for (const editStackElement of this.d) {
      if (URI.isUri(editStackElement.model)) {
        result.push(editStackElement.model);
      }
    }
    return result;
  }
  matchesResource(resource) {
    const key2 = uriGetComparisonKey(resource);
    return this.f.has(key2);
  }
  setModel(model) {
    const key2 = uriGetComparisonKey(URI.isUri(model) ? model : model.uri);
    if (this.f.has(key2)) {
      this.f.get(key2).setModel(model);
    }
  }
  canAppend(model) {
    if (!this.c) {
      return false;
    }
    const key2 = uriGetComparisonKey(model.uri);
    if (this.f.has(key2)) {
      const editStackElement = this.f.get(key2);
      return editStackElement.canAppend(model);
    }
    return false;
  }
  append(model, textChanges, afterEOL, afterVersionId, afterCursorState) {
    const key2 = uriGetComparisonKey(model.uri);
    const editStackElement = this.f.get(key2);
    editStackElement.append(model, textChanges, afterEOL, afterVersionId, afterCursorState);
  }
  close() {
    this.c = false;
  }
  open() {
  }
  undo() {
    this.c = false;
    for (const editStackElement of this.d) {
      editStackElement.undo();
    }
  }
  redo() {
    for (const editStackElement of this.d) {
      editStackElement.redo();
    }
  }
  heapSize(resource) {
    const key2 = uriGetComparisonKey(resource);
    if (this.f.has(key2)) {
      const editStackElement = this.f.get(key2);
      return editStackElement.heapSize();
    }
    return 0;
  }
  split() {
    return this.d;
  }
  toString() {
    const result = [];
    for (const editStackElement of this.d) {
      result.push(`${$sh(editStackElement.resource)}: ${editStackElement}`);
    }
    return `{${result.join(", ")}}`;
  }
};
function getModelEOL(model) {
  const eol = model.getEOL();
  if (eol === "\n") {
    return 0;
  } else {
    return 1;
  }
}
function $SH(element) {
  if (!element) {
    return false;
  }
  return element instanceof $QH || element instanceof $RH;
}
var $TH = class _$TH {
  constructor(model, undoRedoService) {
    this.c = model;
    this.d = undoRedoService;
  }
  pushStackElement() {
    const lastElement = this.d.getLastElement(this.c.uri);
    if ($SH(lastElement)) {
      lastElement.close();
    }
  }
  popStackElement() {
    const lastElement = this.d.getLastElement(this.c.uri);
    if ($SH(lastElement)) {
      lastElement.open();
    }
  }
  clear() {
    this.d.removeElements(this.c.uri);
  }
  f(beforeCursorState, group2) {
    const lastElement = this.d.getLastElement(this.c.uri);
    if ($SH(lastElement) && lastElement.canAppend(this.c)) {
      return lastElement;
    }
    const newElement = new $QH(localize(832, null), "undoredo.textBufferEdit", this.c, beforeCursorState);
    this.d.pushElement(newElement, group2);
    return newElement;
  }
  pushEOL(eol) {
    const editStackElement = this.f(null, void 0);
    this.c.setEOL(eol);
    editStackElement.append(this.c, [], getModelEOL(this.c), this.c.getAlternativeVersionId(), null);
  }
  pushEditOperation(beforeCursorState, editOperations, cursorStateComputer, group2) {
    const editStackElement = this.f(beforeCursorState, group2);
    const inverseEditOperations = this.c.applyEdits(editOperations, true);
    const afterCursorState = _$TH.g(cursorStateComputer, inverseEditOperations);
    const textChanges = inverseEditOperations.map((op, index) => ({ index, textChange: op.textChange }));
    textChanges.sort((a, b) => {
      if (a.textChange.oldPosition === b.textChange.oldPosition) {
        return a.index - b.index;
      }
      return a.textChange.oldPosition - b.textChange.oldPosition;
    });
    editStackElement.append(this.c, textChanges.map((op) => op.textChange), getModelEOL(this.c), this.c.getAlternativeVersionId(), afterCursorState);
    return afterCursorState;
  }
  static g(cursorStateComputer, inverseEditOperations) {
    try {
      return cursorStateComputer ? cursorStateComputer(inverseEditOperations) : null;
    } catch (e) {
      $gb(e);
      return null;
    }
  }
};

// out-build/vs/editor/common/model/indentationGuesser.js
var SpacesDiffResult = class {
  constructor() {
    this.spacesDiff = 0;
    this.looksLikeAlignment = false;
  }
};
function spacesDiff(a, aLength, b, bLength, result) {
  result.spacesDiff = 0;
  result.looksLikeAlignment = false;
  let i2;
  for (i2 = 0; i2 < aLength && i2 < bLength; i2++) {
    const aCharCode = a.charCodeAt(i2);
    const bCharCode = b.charCodeAt(i2);
    if (aCharCode !== bCharCode) {
      break;
    }
  }
  let aSpacesCnt = 0, aTabsCount = 0;
  for (let j = i2; j < aLength; j++) {
    const aCharCode = a.charCodeAt(j);
    if (aCharCode === 32) {
      aSpacesCnt++;
    } else {
      aTabsCount++;
    }
  }
  let bSpacesCnt = 0, bTabsCount = 0;
  for (let j = i2; j < bLength; j++) {
    const bCharCode = b.charCodeAt(j);
    if (bCharCode === 32) {
      bSpacesCnt++;
    } else {
      bTabsCount++;
    }
  }
  if (aSpacesCnt > 0 && aTabsCount > 0) {
    return;
  }
  if (bSpacesCnt > 0 && bTabsCount > 0) {
    return;
  }
  const tabsDiff = Math.abs(aTabsCount - bTabsCount);
  const spacesDiff2 = Math.abs(aSpacesCnt - bSpacesCnt);
  if (tabsDiff === 0) {
    result.spacesDiff = spacesDiff2;
    if (spacesDiff2 > 0 && 0 <= bSpacesCnt - 1 && bSpacesCnt - 1 < a.length && bSpacesCnt < b.length) {
      if (b.charCodeAt(bSpacesCnt) !== 32 && a.charCodeAt(bSpacesCnt - 1) === 32) {
        if (a.charCodeAt(a.length - 1) === 44) {
          result.looksLikeAlignment = true;
        }
      }
    }
    return;
  }
  if (spacesDiff2 % tabsDiff === 0) {
    result.spacesDiff = spacesDiff2 / tabsDiff;
    return;
  }
}
function $YH(source, defaultTabSize, defaultInsertSpaces) {
  const linesCount = Math.min(source.getLineCount(), 1e4);
  let linesIndentedWithTabsCount = 0;
  let linesIndentedWithSpacesCount = 0;
  let previousLineText = "";
  let previousLineIndentation = 0;
  const ALLOWED_TAB_SIZE_GUESSES = [2, 4, 6, 8, 3, 5, 7];
  const MAX_ALLOWED_TAB_SIZE_GUESS = 8;
  const spacesDiffCount = [0, 0, 0, 0, 0, 0, 0, 0, 0];
  const tmp = new SpacesDiffResult();
  for (let lineNumber = 1; lineNumber <= linesCount; lineNumber++) {
    const currentLineLength = source.getLineLength(lineNumber);
    const currentLineText = source.getLineContent(lineNumber);
    const useCurrentLineText = currentLineLength <= 65536;
    let currentLineHasContent = false;
    let currentLineIndentation = 0;
    let currentLineSpacesCount = 0;
    let currentLineTabsCount = 0;
    for (let j = 0, lenJ = currentLineLength; j < lenJ; j++) {
      const charCode = useCurrentLineText ? currentLineText.charCodeAt(j) : source.getLineCharCode(lineNumber, j);
      if (charCode === 9) {
        currentLineTabsCount++;
      } else if (charCode === 32) {
        currentLineSpacesCount++;
      } else {
        currentLineHasContent = true;
        currentLineIndentation = j;
        break;
      }
    }
    if (!currentLineHasContent) {
      continue;
    }
    if (currentLineTabsCount > 0) {
      linesIndentedWithTabsCount++;
    } else if (currentLineSpacesCount > 1) {
      linesIndentedWithSpacesCount++;
    }
    spacesDiff(previousLineText, previousLineIndentation, currentLineText, currentLineIndentation, tmp);
    if (tmp.looksLikeAlignment) {
      if (!(defaultInsertSpaces && defaultTabSize === tmp.spacesDiff)) {
        continue;
      }
    }
    const currentSpacesDiff = tmp.spacesDiff;
    if (currentSpacesDiff <= MAX_ALLOWED_TAB_SIZE_GUESS) {
      spacesDiffCount[currentSpacesDiff]++;
    }
    previousLineText = currentLineText;
    previousLineIndentation = currentLineIndentation;
  }
  let insertSpaces = defaultInsertSpaces;
  if (linesIndentedWithTabsCount !== linesIndentedWithSpacesCount) {
    insertSpaces = linesIndentedWithTabsCount < linesIndentedWithSpacesCount;
  }
  let tabSize = defaultTabSize;
  if (insertSpaces) {
    let tabSizeScore = insertSpaces ? 0 : 0.1 * linesCount;
    ALLOWED_TAB_SIZE_GUESSES.forEach((possibleTabSize) => {
      const possibleTabSizeScore = spacesDiffCount[possibleTabSize];
      if (possibleTabSizeScore > tabSizeScore) {
        tabSizeScore = possibleTabSizeScore;
        tabSize = possibleTabSize;
      }
    });
    if (tabSize === 4 && spacesDiffCount[4] > 0 && spacesDiffCount[2] > 0 && spacesDiffCount[2] >= spacesDiffCount[4] / 2) {
      tabSize = 2;
    }
  }
  return {
    insertSpaces,
    tabSize
  };
}

// out-build/vs/editor/common/model/intervalTree.js
var ClassName;
(function(ClassName3) {
  ClassName3["EditorHintDecoration"] = "squiggly-hint";
  ClassName3["EditorInfoDecoration"] = "squiggly-info";
  ClassName3["EditorWarningDecoration"] = "squiggly-warning";
  ClassName3["EditorErrorDecoration"] = "squiggly-error";
  ClassName3["EditorUnnecessaryDecoration"] = "squiggly-unnecessary";
  ClassName3["EditorUnnecessaryInlineDecoration"] = "squiggly-inline-unnecessary";
  ClassName3["EditorDeprecatedInlineDecoration"] = "squiggly-inline-deprecated";
})(ClassName || (ClassName = {}));
var NodeColor;
(function(NodeColor3) {
  NodeColor3[NodeColor3["Black"] = 0] = "Black";
  NodeColor3[NodeColor3["Red"] = 1] = "Red";
})(NodeColor || (NodeColor = {}));
var Constants9;
(function(Constants27) {
  Constants27[Constants27["ColorMask"] = 1] = "ColorMask";
  Constants27[Constants27["ColorMaskInverse"] = 254] = "ColorMaskInverse";
  Constants27[Constants27["ColorOffset"] = 0] = "ColorOffset";
  Constants27[Constants27["IsVisitedMask"] = 2] = "IsVisitedMask";
  Constants27[Constants27["IsVisitedMaskInverse"] = 253] = "IsVisitedMaskInverse";
  Constants27[Constants27["IsVisitedOffset"] = 1] = "IsVisitedOffset";
  Constants27[Constants27["IsForValidationMask"] = 4] = "IsForValidationMask";
  Constants27[Constants27["IsForValidationMaskInverse"] = 251] = "IsForValidationMaskInverse";
  Constants27[Constants27["IsForValidationOffset"] = 2] = "IsForValidationOffset";
  Constants27[Constants27["StickinessMask"] = 24] = "StickinessMask";
  Constants27[Constants27["StickinessMaskInverse"] = 231] = "StickinessMaskInverse";
  Constants27[Constants27["StickinessOffset"] = 3] = "StickinessOffset";
  Constants27[Constants27["CollapseOnReplaceEditMask"] = 32] = "CollapseOnReplaceEditMask";
  Constants27[Constants27["CollapseOnReplaceEditMaskInverse"] = 223] = "CollapseOnReplaceEditMaskInverse";
  Constants27[Constants27["CollapseOnReplaceEditOffset"] = 5] = "CollapseOnReplaceEditOffset";
  Constants27[Constants27["IsMarginMask"] = 64] = "IsMarginMask";
  Constants27[Constants27["IsMarginMaskInverse"] = 191] = "IsMarginMaskInverse";
  Constants27[Constants27["IsMarginOffset"] = 6] = "IsMarginOffset";
  Constants27[Constants27["MIN_SAFE_DELTA"] = -1073741824] = "MIN_SAFE_DELTA";
  Constants27[Constants27["MAX_SAFE_DELTA"] = 1073741824] = "MAX_SAFE_DELTA";
})(Constants9 || (Constants9 = {}));
function $ZH(node) {
  return (node.metadata & 1) >>> 0;
}
function setNodeColor(node, color2) {
  node.metadata = node.metadata & 254 | color2 << 0;
}
function getNodeIsVisited(node) {
  return (node.metadata & 2) >>> 1 === 1;
}
function setNodeIsVisited(node, value) {
  node.metadata = node.metadata & 253 | (value ? 1 : 0) << 1;
}
function getNodeIsForValidation(node) {
  return (node.metadata & 4) >>> 2 === 1;
}
function setNodeIsForValidation(node, value) {
  node.metadata = node.metadata & 251 | (value ? 1 : 0) << 2;
}
function getNodeIsInGlyphMargin(node) {
  return (node.metadata & 64) >>> 6 === 1;
}
function setNodeIsInGlyphMargin(node, value) {
  node.metadata = node.metadata & 191 | (value ? 1 : 0) << 6;
}
function getNodeStickiness(node) {
  return (node.metadata & 24) >>> 3;
}
function _setNodeStickiness(node, stickiness2) {
  node.metadata = node.metadata & 231 | stickiness2 << 3;
}
function getCollapseOnReplaceEdit(node) {
  return (node.metadata & 32) >>> 5 === 1;
}
function setCollapseOnReplaceEdit(node, value) {
  node.metadata = node.metadata & 223 | (value ? 1 : 0) << 5;
}
var $2H = class {
  constructor(id2, start, end) {
    this.metadata = 0;
    this.parent = this;
    this.left = this;
    this.right = this;
    setNodeColor(
      this,
      1
      /* NodeColor.Red */
    );
    this.start = start;
    this.end = end;
    this.delta = 0;
    this.maxEnd = end;
    this.id = id2;
    this.ownerId = 0;
    this.options = null;
    setNodeIsForValidation(this, false);
    setNodeIsInGlyphMargin(this, false);
    _setNodeStickiness(
      this,
      1
      /* TrackedRangeStickiness.NeverGrowsWhenTypingAtEdges */
    );
    setCollapseOnReplaceEdit(this, false);
    this.cachedVersionId = 0;
    this.cachedAbsoluteStart = start;
    this.cachedAbsoluteEnd = end;
    this.range = null;
    setNodeIsVisited(this, false);
  }
  reset(versionId, start, end, range) {
    this.start = start;
    this.end = end;
    this.maxEnd = end;
    this.cachedVersionId = versionId;
    this.cachedAbsoluteStart = start;
    this.cachedAbsoluteEnd = end;
    this.range = range;
  }
  setOptions(options3) {
    this.options = options3;
    const className = this.options.className;
    setNodeIsForValidation(this, className === "squiggly-error" || className === "squiggly-warning" || className === "squiggly-info");
    setNodeIsInGlyphMargin(this, this.options.glyphMarginClassName !== null);
    _setNodeStickiness(this, this.options.stickiness);
    setCollapseOnReplaceEdit(this, this.options.collapseOnReplaceEdit);
  }
  setCachedOffsets(absoluteStart, absoluteEnd, cachedVersionId) {
    if (this.cachedVersionId !== cachedVersionId) {
      this.range = null;
    }
    this.cachedVersionId = cachedVersionId;
    this.cachedAbsoluteStart = absoluteStart;
    this.cachedAbsoluteEnd = absoluteEnd;
  }
  detach() {
    this.parent = null;
    this.left = null;
    this.right = null;
  }
};
var $3H = new $2H(null, 0, 0);
$3H.parent = $3H;
$3H.left = $3H;
$3H.right = $3H;
setNodeColor(
  $3H,
  0
  /* NodeColor.Black */
);
var $4H = class {
  constructor() {
    this.root = $3H;
    this.requestNormalizeDelta = false;
  }
  intervalSearch(start, end, filterOwnerId, filterOutValidation, cachedVersionId, onlyMarginDecorations) {
    if (this.root === $3H) {
      return [];
    }
    return intervalSearch(this, start, end, filterOwnerId, filterOutValidation, cachedVersionId, onlyMarginDecorations);
  }
  search(filterOwnerId, filterOutValidation, cachedVersionId, onlyMarginDecorations) {
    if (this.root === $3H) {
      return [];
    }
    return search(this, filterOwnerId, filterOutValidation, cachedVersionId, onlyMarginDecorations);
  }
  /**
   * Will not set `cachedAbsoluteStart` nor `cachedAbsoluteEnd` on the returned nodes!
   */
  collectNodesFromOwner(ownerId2) {
    return collectNodesFromOwner(this, ownerId2);
  }
  /**
   * Will not set `cachedAbsoluteStart` nor `cachedAbsoluteEnd` on the returned nodes!
   */
  collectNodesPostOrder() {
    return collectNodesPostOrder(this);
  }
  insert(node) {
    rbTreeInsert(this, node);
    this.a();
  }
  delete(node) {
    rbTreeDelete(this, node);
    this.a();
  }
  resolveNode(node, cachedVersionId) {
    const initialNode = node;
    let delta = 0;
    while (node !== this.root) {
      if (node === node.parent.right) {
        delta += node.parent.delta;
      }
      node = node.parent;
    }
    const nodeStart = initialNode.start + delta;
    const nodeEnd = initialNode.end + delta;
    initialNode.setCachedOffsets(nodeStart, nodeEnd, cachedVersionId);
  }
  acceptReplace(offset, length, textLength, forceMoveMarkers) {
    const nodesOfInterest = searchForEditing(this, offset, offset + length);
    for (let i2 = 0, len = nodesOfInterest.length; i2 < len; i2++) {
      const node = nodesOfInterest[i2];
      rbTreeDelete(this, node);
    }
    this.a();
    noOverlapReplace(this, offset, offset + length, textLength);
    this.a();
    for (let i2 = 0, len = nodesOfInterest.length; i2 < len; i2++) {
      const node = nodesOfInterest[i2];
      node.start = node.cachedAbsoluteStart;
      node.end = node.cachedAbsoluteEnd;
      $5H(node, offset, offset + length, textLength, forceMoveMarkers);
      node.maxEnd = node.end;
      rbTreeInsert(this, node);
    }
    this.a();
  }
  getAllInOrder() {
    return search(this, 0, false, 0, false);
  }
  a() {
    if (!this.requestNormalizeDelta) {
      return;
    }
    this.requestNormalizeDelta = false;
    normalizeDelta(this);
  }
};
function normalizeDelta(T) {
  let node = T.root;
  let delta = 0;
  while (node !== $3H) {
    if (node.left !== $3H && !getNodeIsVisited(node.left)) {
      node = node.left;
      continue;
    }
    if (node.right !== $3H && !getNodeIsVisited(node.right)) {
      delta += node.delta;
      node = node.right;
      continue;
    }
    node.start = delta + node.start;
    node.end = delta + node.end;
    node.delta = 0;
    $6H(node);
    setNodeIsVisited(node, true);
    setNodeIsVisited(node.left, false);
    setNodeIsVisited(node.right, false);
    if (node === node.parent.right) {
      delta -= node.parent.delta;
    }
    node = node.parent;
  }
  setNodeIsVisited(T.root, false);
}
var MarkerMoveSemantics;
(function(MarkerMoveSemantics2) {
  MarkerMoveSemantics2[MarkerMoveSemantics2["MarkerDefined"] = 0] = "MarkerDefined";
  MarkerMoveSemantics2[MarkerMoveSemantics2["ForceMove"] = 1] = "ForceMove";
  MarkerMoveSemantics2[MarkerMoveSemantics2["ForceStay"] = 2] = "ForceStay";
})(MarkerMoveSemantics || (MarkerMoveSemantics = {}));
function adjustMarkerBeforeColumn(markerOffset, markerStickToPreviousCharacter, checkOffset, moveSemantics) {
  if (markerOffset < checkOffset) {
    return true;
  }
  if (markerOffset > checkOffset) {
    return false;
  }
  if (moveSemantics === 1) {
    return false;
  }
  if (moveSemantics === 2) {
    return true;
  }
  return markerStickToPreviousCharacter;
}
function $5H(node, start, end, textLength, forceMoveMarkers) {
  const nodeStickiness = getNodeStickiness(node);
  const startStickToPreviousCharacter = nodeStickiness === 0 || nodeStickiness === 2;
  const endStickToPreviousCharacter = nodeStickiness === 1 || nodeStickiness === 2;
  const deletingCnt = end - start;
  const insertingCnt = textLength;
  const commonLength = Math.min(deletingCnt, insertingCnt);
  const nodeStart = node.start;
  let startDone = false;
  const nodeEnd = node.end;
  let endDone = false;
  if (start <= nodeStart && nodeEnd <= end && getCollapseOnReplaceEdit(node)) {
    node.start = start;
    startDone = true;
    node.end = start;
    endDone = true;
  }
  {
    const moveSemantics = forceMoveMarkers ? 1 : deletingCnt > 0 ? 2 : 0;
    if (!startDone && adjustMarkerBeforeColumn(nodeStart, startStickToPreviousCharacter, start, moveSemantics)) {
      startDone = true;
    }
    if (!endDone && adjustMarkerBeforeColumn(nodeEnd, endStickToPreviousCharacter, start, moveSemantics)) {
      endDone = true;
    }
  }
  if (commonLength > 0 && !forceMoveMarkers) {
    const moveSemantics = deletingCnt > insertingCnt ? 2 : 0;
    if (!startDone && adjustMarkerBeforeColumn(nodeStart, startStickToPreviousCharacter, start + commonLength, moveSemantics)) {
      startDone = true;
    }
    if (!endDone && adjustMarkerBeforeColumn(nodeEnd, endStickToPreviousCharacter, start + commonLength, moveSemantics)) {
      endDone = true;
    }
  }
  {
    const moveSemantics = forceMoveMarkers ? 1 : 0;
    if (!startDone && adjustMarkerBeforeColumn(nodeStart, startStickToPreviousCharacter, end, moveSemantics)) {
      node.start = start + insertingCnt;
      startDone = true;
    }
    if (!endDone && adjustMarkerBeforeColumn(nodeEnd, endStickToPreviousCharacter, end, moveSemantics)) {
      node.end = start + insertingCnt;
      endDone = true;
    }
  }
  const deltaColumn = insertingCnt - deletingCnt;
  if (!startDone) {
    node.start = Math.max(0, nodeStart + deltaColumn);
  }
  if (!endDone) {
    node.end = Math.max(0, nodeEnd + deltaColumn);
  }
  if (node.start > node.end) {
    node.end = node.start;
  }
}
function searchForEditing(T, start, end) {
  let node = T.root;
  let delta = 0;
  let nodeMaxEnd = 0;
  let nodeStart = 0;
  let nodeEnd = 0;
  const result = [];
  let resultLen = 0;
  while (node !== $3H) {
    if (getNodeIsVisited(node)) {
      setNodeIsVisited(node.left, false);
      setNodeIsVisited(node.right, false);
      if (node === node.parent.right) {
        delta -= node.parent.delta;
      }
      node = node.parent;
      continue;
    }
    if (!getNodeIsVisited(node.left)) {
      nodeMaxEnd = delta + node.maxEnd;
      if (nodeMaxEnd < start) {
        setNodeIsVisited(node, true);
        continue;
      }
      if (node.left !== $3H) {
        node = node.left;
        continue;
      }
    }
    nodeStart = delta + node.start;
    if (nodeStart > end) {
      setNodeIsVisited(node, true);
      continue;
    }
    nodeEnd = delta + node.end;
    if (nodeEnd >= start) {
      node.setCachedOffsets(nodeStart, nodeEnd, 0);
      result[resultLen++] = node;
    }
    setNodeIsVisited(node, true);
    if (node.right !== $3H && !getNodeIsVisited(node.right)) {
      delta += node.delta;
      node = node.right;
      continue;
    }
  }
  setNodeIsVisited(T.root, false);
  return result;
}
function noOverlapReplace(T, start, end, textLength) {
  let node = T.root;
  let delta = 0;
  let nodeMaxEnd = 0;
  let nodeStart = 0;
  const editDelta = textLength - (end - start);
  while (node !== $3H) {
    if (getNodeIsVisited(node)) {
      setNodeIsVisited(node.left, false);
      setNodeIsVisited(node.right, false);
      if (node === node.parent.right) {
        delta -= node.parent.delta;
      }
      $6H(node);
      node = node.parent;
      continue;
    }
    if (!getNodeIsVisited(node.left)) {
      nodeMaxEnd = delta + node.maxEnd;
      if (nodeMaxEnd < start) {
        setNodeIsVisited(node, true);
        continue;
      }
      if (node.left !== $3H) {
        node = node.left;
        continue;
      }
    }
    nodeStart = delta + node.start;
    if (nodeStart > end) {
      node.start += editDelta;
      node.end += editDelta;
      node.delta += editDelta;
      if (node.delta < -1073741824 || node.delta > 1073741824) {
        T.requestNormalizeDelta = true;
      }
      setNodeIsVisited(node, true);
      continue;
    }
    setNodeIsVisited(node, true);
    if (node.right !== $3H && !getNodeIsVisited(node.right)) {
      delta += node.delta;
      node = node.right;
      continue;
    }
  }
  setNodeIsVisited(T.root, false);
}
function collectNodesFromOwner(T, ownerId2) {
  let node = T.root;
  const result = [];
  let resultLen = 0;
  while (node !== $3H) {
    if (getNodeIsVisited(node)) {
      setNodeIsVisited(node.left, false);
      setNodeIsVisited(node.right, false);
      node = node.parent;
      continue;
    }
    if (node.left !== $3H && !getNodeIsVisited(node.left)) {
      node = node.left;
      continue;
    }
    if (node.ownerId === ownerId2) {
      result[resultLen++] = node;
    }
    setNodeIsVisited(node, true);
    if (node.right !== $3H && !getNodeIsVisited(node.right)) {
      node = node.right;
      continue;
    }
  }
  setNodeIsVisited(T.root, false);
  return result;
}
function collectNodesPostOrder(T) {
  let node = T.root;
  const result = [];
  let resultLen = 0;
  while (node !== $3H) {
    if (getNodeIsVisited(node)) {
      setNodeIsVisited(node.left, false);
      setNodeIsVisited(node.right, false);
      node = node.parent;
      continue;
    }
    if (node.left !== $3H && !getNodeIsVisited(node.left)) {
      node = node.left;
      continue;
    }
    if (node.right !== $3H && !getNodeIsVisited(node.right)) {
      node = node.right;
      continue;
    }
    result[resultLen++] = node;
    setNodeIsVisited(node, true);
  }
  setNodeIsVisited(T.root, false);
  return result;
}
function search(T, filterOwnerId, filterOutValidation, cachedVersionId, onlyMarginDecorations) {
  let node = T.root;
  let delta = 0;
  let nodeStart = 0;
  let nodeEnd = 0;
  const result = [];
  let resultLen = 0;
  while (node !== $3H) {
    if (getNodeIsVisited(node)) {
      setNodeIsVisited(node.left, false);
      setNodeIsVisited(node.right, false);
      if (node === node.parent.right) {
        delta -= node.parent.delta;
      }
      node = node.parent;
      continue;
    }
    if (node.left !== $3H && !getNodeIsVisited(node.left)) {
      node = node.left;
      continue;
    }
    nodeStart = delta + node.start;
    nodeEnd = delta + node.end;
    node.setCachedOffsets(nodeStart, nodeEnd, cachedVersionId);
    let include = true;
    if (filterOwnerId && node.ownerId && node.ownerId !== filterOwnerId) {
      include = false;
    }
    if (filterOutValidation && getNodeIsForValidation(node)) {
      include = false;
    }
    if (onlyMarginDecorations && !getNodeIsInGlyphMargin(node)) {
      include = false;
    }
    if (include) {
      result[resultLen++] = node;
    }
    setNodeIsVisited(node, true);
    if (node.right !== $3H && !getNodeIsVisited(node.right)) {
      delta += node.delta;
      node = node.right;
      continue;
    }
  }
  setNodeIsVisited(T.root, false);
  return result;
}
function intervalSearch(T, intervalStart, intervalEnd, filterOwnerId, filterOutValidation, cachedVersionId, onlyMarginDecorations) {
  let node = T.root;
  let delta = 0;
  let nodeMaxEnd = 0;
  let nodeStart = 0;
  let nodeEnd = 0;
  const result = [];
  let resultLen = 0;
  while (node !== $3H) {
    if (getNodeIsVisited(node)) {
      setNodeIsVisited(node.left, false);
      setNodeIsVisited(node.right, false);
      if (node === node.parent.right) {
        delta -= node.parent.delta;
      }
      node = node.parent;
      continue;
    }
    if (!getNodeIsVisited(node.left)) {
      nodeMaxEnd = delta + node.maxEnd;
      if (nodeMaxEnd < intervalStart) {
        setNodeIsVisited(node, true);
        continue;
      }
      if (node.left !== $3H) {
        node = node.left;
        continue;
      }
    }
    nodeStart = delta + node.start;
    if (nodeStart > intervalEnd) {
      setNodeIsVisited(node, true);
      continue;
    }
    nodeEnd = delta + node.end;
    if (nodeEnd >= intervalStart) {
      node.setCachedOffsets(nodeStart, nodeEnd, cachedVersionId);
      let include = true;
      if (filterOwnerId && node.ownerId && node.ownerId !== filterOwnerId) {
        include = false;
      }
      if (filterOutValidation && getNodeIsForValidation(node)) {
        include = false;
      }
      if (onlyMarginDecorations && !getNodeIsInGlyphMargin(node)) {
        include = false;
      }
      if (include) {
        result[resultLen++] = node;
      }
    }
    setNodeIsVisited(node, true);
    if (node.right !== $3H && !getNodeIsVisited(node.right)) {
      delta += node.delta;
      node = node.right;
      continue;
    }
  }
  setNodeIsVisited(T.root, false);
  return result;
}
function rbTreeInsert(T, newNode) {
  if (T.root === $3H) {
    newNode.parent = $3H;
    newNode.left = $3H;
    newNode.right = $3H;
    setNodeColor(
      newNode,
      0
      /* NodeColor.Black */
    );
    T.root = newNode;
    return T.root;
  }
  treeInsert(T, newNode);
  recomputeMaxEndWalkToRoot(newNode.parent);
  let x = newNode;
  while (x !== T.root && $ZH(x.parent) === 1) {
    if (x.parent === x.parent.parent.left) {
      const y = x.parent.parent.right;
      if ($ZH(y) === 1) {
        setNodeColor(
          x.parent,
          0
          /* NodeColor.Black */
        );
        setNodeColor(
          y,
          0
          /* NodeColor.Black */
        );
        setNodeColor(
          x.parent.parent,
          1
          /* NodeColor.Red */
        );
        x = x.parent.parent;
      } else {
        if (x === x.parent.right) {
          x = x.parent;
          leftRotate2(T, x);
        }
        setNodeColor(
          x.parent,
          0
          /* NodeColor.Black */
        );
        setNodeColor(
          x.parent.parent,
          1
          /* NodeColor.Red */
        );
        rightRotate(T, x.parent.parent);
      }
    } else {
      const y = x.parent.parent.left;
      if ($ZH(y) === 1) {
        setNodeColor(
          x.parent,
          0
          /* NodeColor.Black */
        );
        setNodeColor(
          y,
          0
          /* NodeColor.Black */
        );
        setNodeColor(
          x.parent.parent,
          1
          /* NodeColor.Red */
        );
        x = x.parent.parent;
      } else {
        if (x === x.parent.left) {
          x = x.parent;
          rightRotate(T, x);
        }
        setNodeColor(
          x.parent,
          0
          /* NodeColor.Black */
        );
        setNodeColor(
          x.parent.parent,
          1
          /* NodeColor.Red */
        );
        leftRotate2(T, x.parent.parent);
      }
    }
  }
  setNodeColor(
    T.root,
    0
    /* NodeColor.Black */
  );
  return newNode;
}
function treeInsert(T, z) {
  let delta = 0;
  let x = T.root;
  const zAbsoluteStart = z.start;
  const zAbsoluteEnd = z.end;
  while (true) {
    const cmp4 = $7H(zAbsoluteStart, zAbsoluteEnd, x.start + delta, x.end + delta);
    if (cmp4 < 0) {
      if (x.left === $3H) {
        z.start -= delta;
        z.end -= delta;
        z.maxEnd -= delta;
        x.left = z;
        break;
      } else {
        x = x.left;
      }
    } else {
      if (x.right === $3H) {
        z.start -= delta + x.delta;
        z.end -= delta + x.delta;
        z.maxEnd -= delta + x.delta;
        x.right = z;
        break;
      } else {
        delta += x.delta;
        x = x.right;
      }
    }
  }
  z.parent = x;
  z.left = $3H;
  z.right = $3H;
  setNodeColor(
    z,
    1
    /* NodeColor.Red */
  );
}
function rbTreeDelete(T, z) {
  let x;
  let y;
  if (z.left === $3H) {
    x = z.right;
    y = z;
    x.delta += z.delta;
    if (x.delta < -1073741824 || x.delta > 1073741824) {
      T.requestNormalizeDelta = true;
    }
    x.start += z.delta;
    x.end += z.delta;
  } else if (z.right === $3H) {
    x = z.left;
    y = z;
  } else {
    y = leftest(z.right);
    x = y.right;
    x.start += y.delta;
    x.end += y.delta;
    x.delta += y.delta;
    if (x.delta < -1073741824 || x.delta > 1073741824) {
      T.requestNormalizeDelta = true;
    }
    y.start += z.delta;
    y.end += z.delta;
    y.delta = z.delta;
    if (y.delta < -1073741824 || y.delta > 1073741824) {
      T.requestNormalizeDelta = true;
    }
  }
  if (y === T.root) {
    T.root = x;
    setNodeColor(
      x,
      0
      /* NodeColor.Black */
    );
    z.detach();
    resetSentinel();
    $6H(x);
    T.root.parent = $3H;
    return;
  }
  const yWasRed = $ZH(y) === 1;
  if (y === y.parent.left) {
    y.parent.left = x;
  } else {
    y.parent.right = x;
  }
  if (y === z) {
    x.parent = y.parent;
  } else {
    if (y.parent === z) {
      x.parent = y;
    } else {
      x.parent = y.parent;
    }
    y.left = z.left;
    y.right = z.right;
    y.parent = z.parent;
    setNodeColor(y, $ZH(z));
    if (z === T.root) {
      T.root = y;
    } else {
      if (z === z.parent.left) {
        z.parent.left = y;
      } else {
        z.parent.right = y;
      }
    }
    if (y.left !== $3H) {
      y.left.parent = y;
    }
    if (y.right !== $3H) {
      y.right.parent = y;
    }
  }
  z.detach();
  if (yWasRed) {
    recomputeMaxEndWalkToRoot(x.parent);
    if (y !== z) {
      recomputeMaxEndWalkToRoot(y);
      recomputeMaxEndWalkToRoot(y.parent);
    }
    resetSentinel();
    return;
  }
  recomputeMaxEndWalkToRoot(x);
  recomputeMaxEndWalkToRoot(x.parent);
  if (y !== z) {
    recomputeMaxEndWalkToRoot(y);
    recomputeMaxEndWalkToRoot(y.parent);
  }
  let w;
  while (x !== T.root && $ZH(x) === 0) {
    if (x === x.parent.left) {
      w = x.parent.right;
      if ($ZH(w) === 1) {
        setNodeColor(
          w,
          0
          /* NodeColor.Black */
        );
        setNodeColor(
          x.parent,
          1
          /* NodeColor.Red */
        );
        leftRotate2(T, x.parent);
        w = x.parent.right;
      }
      if ($ZH(w.left) === 0 && $ZH(w.right) === 0) {
        setNodeColor(
          w,
          1
          /* NodeColor.Red */
        );
        x = x.parent;
      } else {
        if ($ZH(w.right) === 0) {
          setNodeColor(
            w.left,
            0
            /* NodeColor.Black */
          );
          setNodeColor(
            w,
            1
            /* NodeColor.Red */
          );
          rightRotate(T, w);
          w = x.parent.right;
        }
        setNodeColor(w, $ZH(x.parent));
        setNodeColor(
          x.parent,
          0
          /* NodeColor.Black */
        );
        setNodeColor(
          w.right,
          0
          /* NodeColor.Black */
        );
        leftRotate2(T, x.parent);
        x = T.root;
      }
    } else {
      w = x.parent.left;
      if ($ZH(w) === 1) {
        setNodeColor(
          w,
          0
          /* NodeColor.Black */
        );
        setNodeColor(
          x.parent,
          1
          /* NodeColor.Red */
        );
        rightRotate(T, x.parent);
        w = x.parent.left;
      }
      if ($ZH(w.left) === 0 && $ZH(w.right) === 0) {
        setNodeColor(
          w,
          1
          /* NodeColor.Red */
        );
        x = x.parent;
      } else {
        if ($ZH(w.left) === 0) {
          setNodeColor(
            w.right,
            0
            /* NodeColor.Black */
          );
          setNodeColor(
            w,
            1
            /* NodeColor.Red */
          );
          leftRotate2(T, w);
          w = x.parent.left;
        }
        setNodeColor(w, $ZH(x.parent));
        setNodeColor(
          x.parent,
          0
          /* NodeColor.Black */
        );
        setNodeColor(
          w.left,
          0
          /* NodeColor.Black */
        );
        rightRotate(T, x.parent);
        x = T.root;
      }
    }
  }
  setNodeColor(
    x,
    0
    /* NodeColor.Black */
  );
  resetSentinel();
}
function leftest(node) {
  while (node.left !== $3H) {
    node = node.left;
  }
  return node;
}
function resetSentinel() {
  $3H.parent = $3H;
  $3H.delta = 0;
  $3H.start = 0;
  $3H.end = 0;
}
function leftRotate2(T, x) {
  const y = x.right;
  y.delta += x.delta;
  if (y.delta < -1073741824 || y.delta > 1073741824) {
    T.requestNormalizeDelta = true;
  }
  y.start += x.delta;
  y.end += x.delta;
  x.right = y.left;
  if (y.left !== $3H) {
    y.left.parent = x;
  }
  y.parent = x.parent;
  if (x.parent === $3H) {
    T.root = y;
  } else if (x === x.parent.left) {
    x.parent.left = y;
  } else {
    x.parent.right = y;
  }
  y.left = x;
  x.parent = y;
  $6H(x);
  $6H(y);
}
function rightRotate(T, y) {
  const x = y.left;
  y.delta -= x.delta;
  if (y.delta < -1073741824 || y.delta > 1073741824) {
    T.requestNormalizeDelta = true;
  }
  y.start -= x.delta;
  y.end -= x.delta;
  y.left = x.right;
  if (x.right !== $3H) {
    x.right.parent = y;
  }
  x.parent = y.parent;
  if (y.parent === $3H) {
    T.root = x;
  } else if (y === y.parent.right) {
    y.parent.right = x;
  } else {
    y.parent.left = x;
  }
  x.right = y;
  y.parent = x;
  $6H(y);
  $6H(x);
}
function computeMaxEnd(node) {
  let maxEnd = node.end;
  if (node.left !== $3H) {
    const leftMaxEnd = node.left.maxEnd;
    if (leftMaxEnd > maxEnd) {
      maxEnd = leftMaxEnd;
    }
  }
  if (node.right !== $3H) {
    const rightMaxEnd = node.right.maxEnd + node.delta;
    if (rightMaxEnd > maxEnd) {
      maxEnd = rightMaxEnd;
    }
  }
  return maxEnd;
}
function $6H(node) {
  node.maxEnd = computeMaxEnd(node);
}
function recomputeMaxEndWalkToRoot(node) {
  while (node !== $3H) {
    const maxEnd = computeMaxEnd(node);
    if (node.maxEnd === maxEnd) {
      return;
    }
    node.maxEnd = maxEnd;
    node = node.parent;
  }
}
function $7H(aStart, aEnd, bStart, bEnd) {
  if (aStart === bStart) {
    return aEnd - bEnd;
  }
  return aStart - bStart;
}

// out-build/vs/editor/common/model/pieceTreeTextBuffer/rbTreeBase.js
var $8H = class {
  constructor(piece, color2) {
    this.piece = piece;
    this.color = color2;
    this.size_left = 0;
    this.lf_left = 0;
    this.parent = this;
    this.left = this;
    this.right = this;
  }
  next() {
    if (this.right !== $9H) {
      return $0H(this.right);
    }
    let node = this;
    while (node.parent !== $9H) {
      if (node.parent.left === node) {
        break;
      }
      node = node.parent;
    }
    if (node.parent === $9H) {
      return $9H;
    } else {
      return node.parent;
    }
  }
  prev() {
    if (this.left !== $9H) {
      return $$H(this.left);
    }
    let node = this;
    while (node.parent !== $9H) {
      if (node.parent.right === node) {
        break;
      }
      node = node.parent;
    }
    if (node.parent === $9H) {
      return $9H;
    } else {
      return node.parent;
    }
  }
  detach() {
    this.parent = null;
    this.left = null;
    this.right = null;
  }
};
var NodeColor2;
(function(NodeColor3) {
  NodeColor3[NodeColor3["Black"] = 0] = "Black";
  NodeColor3[NodeColor3["Red"] = 1] = "Red";
})(NodeColor2 || (NodeColor2 = {}));
var $9H = new $8H(
  null,
  0
  /* NodeColor.Black */
);
$9H.parent = $9H;
$9H.left = $9H;
$9H.right = $9H;
$9H.color = 0;
function $0H(node) {
  while (node.left !== $9H) {
    node = node.left;
  }
  return node;
}
function $$H(node) {
  while (node.right !== $9H) {
    node = node.right;
  }
  return node;
}
function calculateSize(node) {
  if (node === $9H) {
    return 0;
  }
  return node.size_left + node.piece.length + calculateSize(node.right);
}
function calculateLF(node) {
  if (node === $9H) {
    return 0;
  }
  return node.lf_left + node.piece.lineFeedCnt + calculateLF(node.right);
}
function resetSentinel2() {
  $9H.parent = $9H;
}
function $_H(tree, x) {
  const y = x.right;
  y.size_left += x.size_left + (x.piece ? x.piece.length : 0);
  y.lf_left += x.lf_left + (x.piece ? x.piece.lineFeedCnt : 0);
  x.right = y.left;
  if (y.left !== $9H) {
    y.left.parent = x;
  }
  y.parent = x.parent;
  if (x.parent === $9H) {
    tree.root = y;
  } else if (x.parent.left === x) {
    x.parent.left = y;
  } else {
    x.parent.right = y;
  }
  y.left = x;
  x.parent = y;
}
function $aI(tree, y) {
  const x = y.left;
  y.left = x.right;
  if (x.right !== $9H) {
    x.right.parent = y;
  }
  x.parent = y.parent;
  y.size_left -= x.size_left + (x.piece ? x.piece.length : 0);
  y.lf_left -= x.lf_left + (x.piece ? x.piece.lineFeedCnt : 0);
  if (y.parent === $9H) {
    tree.root = x;
  } else if (y === y.parent.right) {
    y.parent.right = x;
  } else {
    y.parent.left = x;
  }
  x.right = y;
  y.parent = x;
}
function $bI(tree, z) {
  let x;
  let y;
  if (z.left === $9H) {
    y = z;
    x = y.right;
  } else if (z.right === $9H) {
    y = z;
    x = y.left;
  } else {
    y = $0H(z.right);
    x = y.right;
  }
  if (y === tree.root) {
    tree.root = x;
    x.color = 0;
    z.detach();
    resetSentinel2();
    tree.root.parent = $9H;
    return;
  }
  const yWasRed = y.color === 1;
  if (y === y.parent.left) {
    y.parent.left = x;
  } else {
    y.parent.right = x;
  }
  if (y === z) {
    x.parent = y.parent;
    $eI(tree, x);
  } else {
    if (y.parent === z) {
      x.parent = y;
    } else {
      x.parent = y.parent;
    }
    $eI(tree, x);
    y.left = z.left;
    y.right = z.right;
    y.parent = z.parent;
    y.color = z.color;
    if (z === tree.root) {
      tree.root = y;
    } else {
      if (z === z.parent.left) {
        z.parent.left = y;
      } else {
        z.parent.right = y;
      }
    }
    if (y.left !== $9H) {
      y.left.parent = y;
    }
    if (y.right !== $9H) {
      y.right.parent = y;
    }
    y.size_left = z.size_left;
    y.lf_left = z.lf_left;
    $eI(tree, y);
  }
  z.detach();
  if (x.parent.left === x) {
    const newSizeLeft = calculateSize(x);
    const newLFLeft = calculateLF(x);
    if (newSizeLeft !== x.parent.size_left || newLFLeft !== x.parent.lf_left) {
      const delta = newSizeLeft - x.parent.size_left;
      const lf_delta = newLFLeft - x.parent.lf_left;
      x.parent.size_left = newSizeLeft;
      x.parent.lf_left = newLFLeft;
      $dI(tree, x.parent, delta, lf_delta);
    }
  }
  $eI(tree, x.parent);
  if (yWasRed) {
    resetSentinel2();
    return;
  }
  let w;
  while (x !== tree.root && x.color === 0) {
    if (x === x.parent.left) {
      w = x.parent.right;
      if (w.color === 1) {
        w.color = 0;
        x.parent.color = 1;
        $_H(tree, x.parent);
        w = x.parent.right;
      }
      if (w.left.color === 0 && w.right.color === 0) {
        w.color = 1;
        x = x.parent;
      } else {
        if (w.right.color === 0) {
          w.left.color = 0;
          w.color = 1;
          $aI(tree, w);
          w = x.parent.right;
        }
        w.color = x.parent.color;
        x.parent.color = 0;
        w.right.color = 0;
        $_H(tree, x.parent);
        x = tree.root;
      }
    } else {
      w = x.parent.left;
      if (w.color === 1) {
        w.color = 0;
        x.parent.color = 1;
        $aI(tree, x.parent);
        w = x.parent.left;
      }
      if (w.left.color === 0 && w.right.color === 0) {
        w.color = 1;
        x = x.parent;
      } else {
        if (w.left.color === 0) {
          w.right.color = 0;
          w.color = 1;
          $_H(tree, w);
          w = x.parent.left;
        }
        w.color = x.parent.color;
        x.parent.color = 0;
        w.left.color = 0;
        $aI(tree, x.parent);
        x = tree.root;
      }
    }
  }
  x.color = 0;
  resetSentinel2();
}
function $cI(tree, x) {
  $eI(tree, x);
  while (x !== tree.root && x.parent.color === 1) {
    if (x.parent === x.parent.parent.left) {
      const y = x.parent.parent.right;
      if (y.color === 1) {
        x.parent.color = 0;
        y.color = 0;
        x.parent.parent.color = 1;
        x = x.parent.parent;
      } else {
        if (x === x.parent.right) {
          x = x.parent;
          $_H(tree, x);
        }
        x.parent.color = 0;
        x.parent.parent.color = 1;
        $aI(tree, x.parent.parent);
      }
    } else {
      const y = x.parent.parent.left;
      if (y.color === 1) {
        x.parent.color = 0;
        y.color = 0;
        x.parent.parent.color = 1;
        x = x.parent.parent;
      } else {
        if (x === x.parent.left) {
          x = x.parent;
          $aI(tree, x);
        }
        x.parent.color = 0;
        x.parent.parent.color = 1;
        $_H(tree, x.parent.parent);
      }
    }
  }
  tree.root.color = 0;
}
function $dI(tree, x, delta, lineFeedCntDelta) {
  while (x !== tree.root && x !== $9H) {
    if (x.parent.left === x) {
      x.parent.size_left += delta;
      x.parent.lf_left += lineFeedCntDelta;
    }
    x = x.parent;
  }
}
function $eI(tree, x) {
  let delta = 0;
  let lf_delta = 0;
  if (x === tree.root) {
    return;
  }
  while (x !== tree.root && x === x.parent.right) {
    x = x.parent;
  }
  if (x === tree.root) {
    return;
  }
  x = x.parent;
  delta = calculateSize(x.left) - x.size_left;
  lf_delta = calculateLF(x.left) - x.lf_left;
  x.size_left += delta;
  x.lf_left += lf_delta;
  while (x !== tree.root && (delta !== 0 || lf_delta !== 0)) {
    if (x.parent.left === x) {
      x.parent.size_left += delta;
      x.parent.lf_left += lf_delta;
    }
    x = x.parent;
  }
}

// out-build/vs/editor/common/model/textModelSearch.js
var LIMIT_FIND_COUNT = 999;
var $fI = class {
  constructor(searchString, isRegex, matchCase, wordSeparators2) {
    this.searchString = searchString;
    this.isRegex = isRegex;
    this.matchCase = matchCase;
    this.wordSeparators = wordSeparators2;
  }
  parseSearchRequest() {
    if (this.searchString === "") {
      return null;
    }
    let multiline;
    if (this.isRegex) {
      multiline = $gI(this.searchString);
    } else {
      multiline = this.searchString.indexOf("\n") >= 0;
    }
    let regex = null;
    try {
      regex = $Jf(this.searchString, this.isRegex, {
        matchCase: this.matchCase,
        wholeWord: false,
        multiline,
        global: true,
        unicode: true
      });
    } catch (err) {
      return null;
    }
    if (!regex) {
      return null;
    }
    let canUseSimpleSearch = !this.isRegex && !multiline;
    if (canUseSimpleSearch && this.searchString.toLowerCase() !== this.searchString.toUpperCase()) {
      canUseSimpleSearch = this.matchCase;
    }
    return new $iG(regex, this.wordSeparators ? $iE(this.wordSeparators, []) : null, canUseSimpleSearch ? this.searchString : null);
  }
};
function $gI(searchString) {
  if (!searchString || searchString.length === 0) {
    return false;
  }
  for (let i2 = 0, len = searchString.length; i2 < len; i2++) {
    const chCode = searchString.charCodeAt(i2);
    if (chCode === 10) {
      return true;
    }
    if (chCode === 92) {
      i2++;
      if (i2 >= len) {
        break;
      }
      const nextChCode = searchString.charCodeAt(i2);
      if (nextChCode === 110 || nextChCode === 114 || nextChCode === 87) {
        return true;
      }
    }
  }
  return false;
}
function $hI(range, rawMatches, captureMatches) {
  if (!captureMatches) {
    return new $eG(range, null);
  }
  const matches = [];
  for (let i2 = 0, len = rawMatches.length; i2 < len; i2++) {
    matches[i2] = rawMatches[i2];
  }
  return new $eG(range, matches);
}
var LineFeedCounter = class {
  constructor(text2) {
    const lineFeedsOffsets = [];
    let lineFeedsOffsetsLen = 0;
    for (let i2 = 0, textLen = text2.length; i2 < textLen; i2++) {
      if (text2.charCodeAt(i2) === 10) {
        lineFeedsOffsets[lineFeedsOffsetsLen++] = i2;
      }
    }
    this.a = lineFeedsOffsets;
  }
  findLineFeedCountBeforeOffset(offset) {
    const lineFeedsOffsets = this.a;
    let min = 0;
    let max = lineFeedsOffsets.length - 1;
    if (max === -1) {
      return 0;
    }
    if (offset <= lineFeedsOffsets[0]) {
      return 0;
    }
    while (min < max) {
      const mid = min + ((max - min) / 2 >> 0);
      if (lineFeedsOffsets[mid] >= offset) {
        max = mid - 1;
      } else {
        if (lineFeedsOffsets[mid + 1] >= offset) {
          min = mid;
          max = mid;
        } else {
          min = mid + 1;
        }
      }
    }
    return min + 1;
  }
};
var $iI = class {
  static findMatches(model, searchParams, searchRange, captureMatches, limitResultCount) {
    const searchData = searchParams.parseSearchRequest();
    if (!searchData) {
      return [];
    }
    if (searchData.regex.multiline) {
      return this.b(model, searchRange, new $kI(searchData.wordSeparators, searchData.regex), captureMatches, limitResultCount);
    }
    return this.c(model, searchRange, searchData, captureMatches, limitResultCount);
  }
  /**
   * Multiline search always executes on the lines concatenated with \n.
   * We must therefore compensate for the count of \n in case the model is CRLF
   */
  static a(model, deltaOffset, text2, lfCounter, matchIndex, match0) {
    let startOffset;
    let lineFeedCountBeforeMatch = 0;
    if (lfCounter) {
      lineFeedCountBeforeMatch = lfCounter.findLineFeedCountBeforeOffset(matchIndex);
      startOffset = deltaOffset + matchIndex + lineFeedCountBeforeMatch;
    } else {
      startOffset = deltaOffset + matchIndex;
    }
    let endOffset;
    if (lfCounter) {
      const lineFeedCountBeforeEndOfMatch = lfCounter.findLineFeedCountBeforeOffset(matchIndex + match0.length);
      const lineFeedCountInMatch = lineFeedCountBeforeEndOfMatch - lineFeedCountBeforeMatch;
      endOffset = startOffset + match0.length + lineFeedCountInMatch;
    } else {
      endOffset = startOffset + match0.length;
    }
    const startPosition = model.getPositionAt(startOffset);
    const endPosition = model.getPositionAt(endOffset);
    return new $9C(startPosition.lineNumber, startPosition.column, endPosition.lineNumber, endPosition.column);
  }
  static b(model, searchRange, searcher, captureMatches, limitResultCount) {
    const deltaOffset = model.getOffsetAt(searchRange.getStartPosition());
    const text2 = model.getValueInRange(
      searchRange,
      1
      /* EndOfLinePreference.LF */
    );
    const lfCounter = model.getEOL() === "\r\n" ? new LineFeedCounter(text2) : null;
    const result = [];
    let counter = 0;
    let m;
    searcher.reset(0);
    while (m = searcher.next(text2)) {
      result[counter++] = $hI(this.a(model, deltaOffset, text2, lfCounter, m.index, m[0]), m, captureMatches);
      if (counter >= limitResultCount) {
        return result;
      }
    }
    return result;
  }
  static c(model, searchRange, searchData, captureMatches, limitResultCount) {
    const result = [];
    let resultLen = 0;
    if (searchRange.startLineNumber === searchRange.endLineNumber) {
      const text3 = model.getLineContent(searchRange.startLineNumber).substring(searchRange.startColumn - 1, searchRange.endColumn - 1);
      resultLen = this.d(searchData, text3, searchRange.startLineNumber, searchRange.startColumn - 1, resultLen, result, captureMatches, limitResultCount);
      return result;
    }
    const text2 = model.getLineContent(searchRange.startLineNumber).substring(searchRange.startColumn - 1);
    resultLen = this.d(searchData, text2, searchRange.startLineNumber, searchRange.startColumn - 1, resultLen, result, captureMatches, limitResultCount);
    for (let lineNumber = searchRange.startLineNumber + 1; lineNumber < searchRange.endLineNumber && resultLen < limitResultCount; lineNumber++) {
      resultLen = this.d(searchData, model.getLineContent(lineNumber), lineNumber, 0, resultLen, result, captureMatches, limitResultCount);
    }
    if (resultLen < limitResultCount) {
      const text3 = model.getLineContent(searchRange.endLineNumber).substring(0, searchRange.endColumn - 1);
      resultLen = this.d(searchData, text3, searchRange.endLineNumber, 0, resultLen, result, captureMatches, limitResultCount);
    }
    return result;
  }
  static d(searchData, text2, lineNumber, deltaOffset, resultLen, result, captureMatches, limitResultCount) {
    const wordSeparators2 = searchData.wordSeparators;
    if (!captureMatches && searchData.simpleSearch) {
      const searchString = searchData.simpleSearch;
      const searchStringLen = searchString.length;
      const textLength = text2.length;
      let lastMatchIndex = -searchStringLen;
      while ((lastMatchIndex = text2.indexOf(searchString, lastMatchIndex + searchStringLen)) !== -1) {
        if (!wordSeparators2 || $jI(wordSeparators2, text2, textLength, lastMatchIndex, searchStringLen)) {
          result[resultLen++] = new $eG(new $9C(lineNumber, lastMatchIndex + 1 + deltaOffset, lineNumber, lastMatchIndex + 1 + searchStringLen + deltaOffset), null);
          if (resultLen >= limitResultCount) {
            return resultLen;
          }
        }
      }
      return resultLen;
    }
    const searcher = new $kI(searchData.wordSeparators, searchData.regex);
    let m;
    searcher.reset(0);
    do {
      m = searcher.next(text2);
      if (m) {
        result[resultLen++] = $hI(new $9C(lineNumber, m.index + 1 + deltaOffset, lineNumber, m.index + 1 + m[0].length + deltaOffset), m, captureMatches);
        if (resultLen >= limitResultCount) {
          return resultLen;
        }
      }
    } while (m);
    return resultLen;
  }
  static findNextMatch(model, searchParams, searchStart, captureMatches) {
    const searchData = searchParams.parseSearchRequest();
    if (!searchData) {
      return null;
    }
    const searcher = new $kI(searchData.wordSeparators, searchData.regex);
    if (searchData.regex.multiline) {
      return this.e(model, searchStart, searcher, captureMatches);
    }
    return this.f(model, searchStart, searcher, captureMatches);
  }
  static e(model, searchStart, searcher, captureMatches) {
    const searchTextStart = new $8C(searchStart.lineNumber, 1);
    const deltaOffset = model.getOffsetAt(searchTextStart);
    const lineCount = model.getLineCount();
    const text2 = model.getValueInRange(
      new $9C(searchTextStart.lineNumber, searchTextStart.column, lineCount, model.getLineMaxColumn(lineCount)),
      1
      /* EndOfLinePreference.LF */
    );
    const lfCounter = model.getEOL() === "\r\n" ? new LineFeedCounter(text2) : null;
    searcher.reset(searchStart.column - 1);
    const m = searcher.next(text2);
    if (m) {
      return $hI(this.a(model, deltaOffset, text2, lfCounter, m.index, m[0]), m, captureMatches);
    }
    if (searchStart.lineNumber !== 1 || searchStart.column !== 1) {
      return this.e(model, new $8C(1, 1), searcher, captureMatches);
    }
    return null;
  }
  static f(model, searchStart, searcher, captureMatches) {
    const lineCount = model.getLineCount();
    const startLineNumber = searchStart.lineNumber;
    const text2 = model.getLineContent(startLineNumber);
    const r2 = this.g(searcher, text2, startLineNumber, searchStart.column, captureMatches);
    if (r2) {
      return r2;
    }
    for (let i2 = 1; i2 <= lineCount; i2++) {
      const lineIndex = (startLineNumber + i2 - 1) % lineCount;
      const text3 = model.getLineContent(lineIndex + 1);
      const r3 = this.g(searcher, text3, lineIndex + 1, 1, captureMatches);
      if (r3) {
        return r3;
      }
    }
    return null;
  }
  static g(searcher, text2, lineNumber, fromColumn, captureMatches) {
    searcher.reset(fromColumn - 1);
    const m = searcher.next(text2);
    if (m) {
      return $hI(new $9C(lineNumber, m.index + 1, lineNumber, m.index + 1 + m[0].length), m, captureMatches);
    }
    return null;
  }
  static findPreviousMatch(model, searchParams, searchStart, captureMatches) {
    const searchData = searchParams.parseSearchRequest();
    if (!searchData) {
      return null;
    }
    const searcher = new $kI(searchData.wordSeparators, searchData.regex);
    if (searchData.regex.multiline) {
      return this.h(model, searchStart, searcher, captureMatches);
    }
    return this.j(model, searchStart, searcher, captureMatches);
  }
  static h(model, searchStart, searcher, captureMatches) {
    const matches = this.b(model, new $9C(1, 1, searchStart.lineNumber, searchStart.column), searcher, captureMatches, 10 * LIMIT_FIND_COUNT);
    if (matches.length > 0) {
      return matches[matches.length - 1];
    }
    const lineCount = model.getLineCount();
    if (searchStart.lineNumber !== lineCount || searchStart.column !== model.getLineMaxColumn(lineCount)) {
      return this.h(model, new $8C(lineCount, model.getLineMaxColumn(lineCount)), searcher, captureMatches);
    }
    return null;
  }
  static j(model, searchStart, searcher, captureMatches) {
    const lineCount = model.getLineCount();
    const startLineNumber = searchStart.lineNumber;
    const text2 = model.getLineContent(startLineNumber).substring(0, searchStart.column - 1);
    const r2 = this.k(searcher, text2, startLineNumber, captureMatches);
    if (r2) {
      return r2;
    }
    for (let i2 = 1; i2 <= lineCount; i2++) {
      const lineIndex = (lineCount + startLineNumber - i2 - 1) % lineCount;
      const text3 = model.getLineContent(lineIndex + 1);
      const r3 = this.k(searcher, text3, lineIndex + 1, captureMatches);
      if (r3) {
        return r3;
      }
    }
    return null;
  }
  static k(searcher, text2, lineNumber, captureMatches) {
    let bestResult = null;
    let m;
    searcher.reset(0);
    while (m = searcher.next(text2)) {
      bestResult = $hI(new $9C(lineNumber, m.index + 1, lineNumber, m.index + 1 + m[0].length), m, captureMatches);
    }
    return bestResult;
  }
};
function leftIsWordBounday(wordSeparators2, text2, textLength, matchStartIndex, matchLength) {
  if (matchStartIndex === 0) {
    return true;
  }
  const charBefore = text2.charCodeAt(matchStartIndex - 1);
  if (wordSeparators2.get(charBefore) !== 0) {
    return true;
  }
  if (charBefore === 13 || charBefore === 10) {
    return true;
  }
  if (matchLength > 0) {
    const firstCharInMatch = text2.charCodeAt(matchStartIndex);
    if (wordSeparators2.get(firstCharInMatch) !== 0) {
      return true;
    }
  }
  return false;
}
function rightIsWordBounday(wordSeparators2, text2, textLength, matchStartIndex, matchLength) {
  if (matchStartIndex + matchLength === textLength) {
    return true;
  }
  const charAfter = text2.charCodeAt(matchStartIndex + matchLength);
  if (wordSeparators2.get(charAfter) !== 0) {
    return true;
  }
  if (charAfter === 13 || charAfter === 10) {
    return true;
  }
  if (matchLength > 0) {
    const lastCharInMatch = text2.charCodeAt(matchStartIndex + matchLength - 1);
    if (wordSeparators2.get(lastCharInMatch) !== 0) {
      return true;
    }
  }
  return false;
}
function $jI(wordSeparators2, text2, textLength, matchStartIndex, matchLength) {
  return leftIsWordBounday(wordSeparators2, text2, textLength, matchStartIndex, matchLength) && rightIsWordBounday(wordSeparators2, text2, textLength, matchStartIndex, matchLength);
}
var $kI = class {
  constructor(wordSeparators2, searchRegex) {
    this._wordSeparators = wordSeparators2;
    this.a = searchRegex;
    this.b = -1;
    this.c = 0;
  }
  reset(lastIndex) {
    this.a.lastIndex = lastIndex;
    this.b = -1;
    this.c = 0;
  }
  next(text2) {
    const textLength = text2.length;
    let m;
    do {
      if (this.b + this.c === textLength) {
        return null;
      }
      m = this.a.exec(text2);
      if (!m) {
        return null;
      }
      const matchStartIndex = m.index;
      const matchLength = m[0].length;
      if (matchStartIndex === this.b && matchLength === this.c) {
        if (matchLength === 0) {
          if ($8f(text2, textLength, this.a.lastIndex) > 65535) {
            this.a.lastIndex += 2;
          } else {
            this.a.lastIndex += 1;
          }
          continue;
        }
        return null;
      }
      this.b = matchStartIndex;
      this.c = matchLength;
      if (!this._wordSeparators || $jI(this._wordSeparators, text2, textLength, matchStartIndex, matchLength)) {
        return m;
      }
    } while (m);
    return null;
  }
};

// out-build/vs/editor/common/model/pieceTreeTextBuffer/pieceTreeBase.js
var AverageBufferSize = 65535;
function createUintArray(arr) {
  let r2;
  if (arr[arr.length - 1] < 65536) {
    r2 = new Uint16Array(arr.length);
  } else {
    r2 = new Uint32Array(arr.length);
  }
  r2.set(arr, 0);
  return r2;
}
var LineStarts = class {
  constructor(lineStarts, cr, lf, crlf, isBasicASCII) {
    this.lineStarts = lineStarts;
    this.cr = cr;
    this.lf = lf;
    this.crlf = crlf;
    this.isBasicASCII = isBasicASCII;
  }
};
function $lI(str, readonly = true) {
  const r2 = [0];
  let rLength = 1;
  for (let i2 = 0, len = str.length; i2 < len; i2++) {
    const chr = str.charCodeAt(i2);
    if (chr === 13) {
      if (i2 + 1 < len && str.charCodeAt(i2 + 1) === 10) {
        r2[rLength++] = i2 + 2;
        i2++;
      } else {
        r2[rLength++] = i2 + 1;
      }
    } else if (chr === 10) {
      r2[rLength++] = i2 + 1;
    }
  }
  if (readonly) {
    return createUintArray(r2);
  } else {
    return r2;
  }
}
function $mI(r2, str) {
  r2.length = 0;
  r2[0] = 0;
  let rLength = 1;
  let cr = 0, lf = 0, crlf = 0;
  let isBasicASCII = true;
  for (let i2 = 0, len = str.length; i2 < len; i2++) {
    const chr = str.charCodeAt(i2);
    if (chr === 13) {
      if (i2 + 1 < len && str.charCodeAt(i2 + 1) === 10) {
        crlf++;
        r2[rLength++] = i2 + 2;
        i2++;
      } else {
        cr++;
        r2[rLength++] = i2 + 1;
      }
    } else if (chr === 10) {
      lf++;
      r2[rLength++] = i2 + 1;
    } else {
      if (isBasicASCII) {
        if (chr !== 9 && (chr < 32 || chr > 126)) {
          isBasicASCII = false;
        }
      }
    }
  }
  const result = new LineStarts(createUintArray(r2), cr, lf, crlf, isBasicASCII);
  r2.length = 0;
  return result;
}
var $nI = class {
  constructor(bufferIndex, start, end, lineFeedCnt, length) {
    this.bufferIndex = bufferIndex;
    this.start = start;
    this.end = end;
    this.lineFeedCnt = lineFeedCnt;
    this.length = length;
  }
};
var $oI = class {
  constructor(buffer, lineStarts) {
    this.buffer = buffer;
    this.lineStarts = lineStarts;
  }
};
var PieceTreeSnapshot = class {
  constructor(tree, BOM) {
    this.a = [];
    this.c = tree;
    this.d = BOM;
    this.b = 0;
    if (tree.root !== $9H) {
      tree.iterate(tree.root, (node) => {
        if (node !== $9H) {
          this.a.push(node.piece);
        }
        return true;
      });
    }
  }
  read() {
    if (this.a.length === 0) {
      if (this.b === 0) {
        this.b++;
        return this.d;
      } else {
        return null;
      }
    }
    if (this.b > this.a.length - 1) {
      return null;
    }
    if (this.b === 0) {
      return this.d + this.c.getPieceContent(this.a[this.b++]);
    }
    return this.c.getPieceContent(this.a[this.b++]);
  }
};
var PieceTreeSearchCache = class {
  constructor(limit) {
    this.a = limit;
    this.b = [];
  }
  get(offset) {
    for (let i2 = this.b.length - 1; i2 >= 0; i2--) {
      const nodePos = this.b[i2];
      if (nodePos.nodeStartOffset <= offset && nodePos.nodeStartOffset + nodePos.node.piece.length >= offset) {
        return nodePos;
      }
    }
    return null;
  }
  get2(lineNumber) {
    for (let i2 = this.b.length - 1; i2 >= 0; i2--) {
      const nodePos = this.b[i2];
      if (nodePos.nodeStartLineNumber && nodePos.nodeStartLineNumber < lineNumber && nodePos.nodeStartLineNumber + nodePos.node.piece.lineFeedCnt >= lineNumber) {
        return nodePos;
      }
    }
    return null;
  }
  set(nodePosition) {
    if (this.b.length >= this.a) {
      this.b.shift();
    }
    this.b.push(nodePosition);
  }
  validate(offset) {
    let hasInvalidVal = false;
    const tmp = this.b;
    for (let i2 = 0; i2 < tmp.length; i2++) {
      const nodePos = tmp[i2];
      if (nodePos.node.parent === null || nodePos.nodeStartOffset >= offset) {
        tmp[i2] = null;
        hasInvalidVal = true;
        continue;
      }
    }
    if (hasInvalidVal) {
      const newArr = [];
      for (const entry of tmp) {
        if (entry !== null) {
          newArr.push(entry);
        }
      }
      this.b = newArr;
    }
  }
};
var $pI = class {
  constructor(chunks, eol, eolNormalized) {
    this.create(chunks, eol, eolNormalized);
  }
  create(chunks, eol, eolNormalized) {
    this.a = [
      new $oI("", [0])
    ];
    this.g = { line: 0, column: 0 };
    this.root = $9H;
    this.b = 1;
    this.c = 0;
    this.d = eol;
    this.e = eol.length;
    this.f = eolNormalized;
    let lastNode = null;
    for (let i2 = 0, len = chunks.length; i2 < len; i2++) {
      if (chunks[i2].buffer.length > 0) {
        if (!chunks[i2].lineStarts) {
          chunks[i2].lineStarts = $lI(chunks[i2].buffer);
        }
        const piece = new $nI(i2 + 1, { line: 0, column: 0 }, { line: chunks[i2].lineStarts.length - 1, column: chunks[i2].buffer.length - chunks[i2].lineStarts[chunks[i2].lineStarts.length - 1] }, chunks[i2].lineStarts.length - 1, chunks[i2].buffer.length);
        this.a.push(chunks[i2]);
        lastNode = this.S(lastNode, piece);
      }
    }
    this.h = new PieceTreeSearchCache(1);
    this.j = { lineNumber: 0, value: "" };
    this.y();
  }
  normalizeEOL(eol) {
    const averageBufferSize = AverageBufferSize;
    const min = averageBufferSize - Math.floor(averageBufferSize / 3);
    const max = min * 2;
    let tempChunk = "";
    let tempChunkLen = 0;
    const chunks = [];
    this.iterate(this.root, (node) => {
      const str = this.R(node);
      const len = str.length;
      if (tempChunkLen <= min || tempChunkLen + len < max) {
        tempChunk += str;
        tempChunkLen += len;
        return true;
      }
      const text2 = tempChunk.replace(/\r\n|\r|\n/g, eol);
      chunks.push(new $oI(text2, $lI(text2)));
      tempChunk = str;
      tempChunkLen = len;
      return true;
    });
    if (tempChunkLen > 0) {
      const text2 = tempChunk.replace(/\r\n|\r|\n/g, eol);
      chunks.push(new $oI(text2, $lI(text2)));
    }
    this.create(chunks, eol, true);
  }
  // #region Buffer API
  getEOL() {
    return this.d;
  }
  setEOL(newEOL) {
    this.d = newEOL;
    this.e = this.d.length;
    this.normalizeEOL(newEOL);
  }
  createSnapshot(BOM) {
    return new PieceTreeSnapshot(this, BOM);
  }
  equal(other) {
    if (this.getLength() !== other.getLength()) {
      return false;
    }
    if (this.getLineCount() !== other.getLineCount()) {
      return false;
    }
    let offset = 0;
    const ret = this.iterate(this.root, (node) => {
      if (node === $9H) {
        return true;
      }
      const str = this.R(node);
      const len = str.length;
      const startPosition = other.G(offset);
      const endPosition = other.G(offset + len);
      const val = other.getValueInRange2(startPosition, endPosition);
      offset += len;
      return str === val;
    });
    return ret;
  }
  getOffsetAt(lineNumber, column) {
    let leftLen = 0;
    let x = this.root;
    while (x !== $9H) {
      if (x.left !== $9H && x.lf_left + 1 >= lineNumber) {
        x = x.left;
      } else if (x.lf_left + x.piece.lineFeedCnt + 1 >= lineNumber) {
        leftLen += x.size_left;
        const accumualtedValInCurrentIndex = this.B(x, lineNumber - x.lf_left - 2);
        return leftLen += accumualtedValInCurrentIndex + column - 1;
      } else {
        lineNumber -= x.lf_left + x.piece.lineFeedCnt;
        leftLen += x.size_left + x.piece.length;
        x = x.right;
      }
    }
    return leftLen;
  }
  getPositionAt(offset) {
    offset = Math.floor(offset);
    offset = Math.max(0, offset);
    let x = this.root;
    let lfCnt = 0;
    const originalOffset = offset;
    while (x !== $9H) {
      if (x.size_left !== 0 && x.size_left >= offset) {
        x = x.left;
      } else if (x.size_left + x.piece.length >= offset) {
        const out = this.A(x, offset - x.size_left);
        lfCnt += x.lf_left + out.index;
        if (out.index === 0) {
          const lineStartOffset = this.getOffsetAt(lfCnt + 1, 1);
          const column = originalOffset - lineStartOffset;
          return new $8C(lfCnt + 1, column + 1);
        }
        return new $8C(lfCnt + 1, out.remainder + 1);
      } else {
        offset -= x.size_left + x.piece.length;
        lfCnt += x.lf_left + x.piece.lineFeedCnt;
        if (x.right === $9H) {
          const lineStartOffset = this.getOffsetAt(lfCnt + 1, 1);
          const column = originalOffset - offset - lineStartOffset;
          return new $8C(lfCnt + 1, column + 1);
        } else {
          x = x.right;
        }
      }
    }
    return new $8C(1, 1);
  }
  getValueInRange(range, eol) {
    if (range.startLineNumber === range.endLineNumber && range.startColumn === range.endColumn) {
      return "";
    }
    const startPosition = this.H(range.startLineNumber, range.startColumn);
    const endPosition = this.H(range.endLineNumber, range.endColumn);
    const value = this.getValueInRange2(startPosition, endPosition);
    if (eol) {
      if (eol !== this.d || !this.f) {
        return value.replace(/\r\n|\r|\n/g, eol);
      }
      if (eol === this.getEOL() && this.f) {
        if (eol === "\r\n") {
        }
        return value;
      }
      return value.replace(/\r\n|\r|\n/g, eol);
    }
    return value;
  }
  getValueInRange2(startPosition, endPosition) {
    if (startPosition.node === endPosition.node) {
      const node = startPosition.node;
      const buffer2 = this.a[node.piece.bufferIndex].buffer;
      const startOffset2 = this.u(node.piece.bufferIndex, node.piece.start);
      return buffer2.substring(startOffset2 + startPosition.remainder, startOffset2 + endPosition.remainder);
    }
    let x = startPosition.node;
    const buffer = this.a[x.piece.bufferIndex].buffer;
    const startOffset = this.u(x.piece.bufferIndex, x.piece.start);
    let ret = buffer.substring(startOffset + startPosition.remainder, startOffset + x.piece.length);
    x = x.next();
    while (x !== $9H) {
      const buffer2 = this.a[x.piece.bufferIndex].buffer;
      const startOffset2 = this.u(x.piece.bufferIndex, x.piece.start);
      if (x === endPosition.node) {
        ret += buffer2.substring(startOffset2, startOffset2 + endPosition.remainder);
        break;
      } else {
        ret += buffer2.substr(startOffset2, x.piece.length);
      }
      x = x.next();
    }
    return ret;
  }
  getLinesContent() {
    const lines = [];
    let linesLength = 0;
    let currentLine = "";
    let danglingCR = false;
    this.iterate(this.root, (node) => {
      if (node === $9H) {
        return true;
      }
      const piece = node.piece;
      let pieceLength = piece.length;
      if (pieceLength === 0) {
        return true;
      }
      const buffer = this.a[piece.bufferIndex].buffer;
      const lineStarts = this.a[piece.bufferIndex].lineStarts;
      const pieceStartLine = piece.start.line;
      const pieceEndLine = piece.end.line;
      let pieceStartOffset = lineStarts[pieceStartLine] + piece.start.column;
      if (danglingCR) {
        if (buffer.charCodeAt(pieceStartOffset) === 10) {
          pieceStartOffset++;
          pieceLength--;
        }
        lines[linesLength++] = currentLine;
        currentLine = "";
        danglingCR = false;
        if (pieceLength === 0) {
          return true;
        }
      }
      if (pieceStartLine === pieceEndLine) {
        if (!this.f && buffer.charCodeAt(pieceStartOffset + pieceLength - 1) === 13) {
          danglingCR = true;
          currentLine += buffer.substr(pieceStartOffset, pieceLength - 1);
        } else {
          currentLine += buffer.substr(pieceStartOffset, pieceLength);
        }
        return true;
      }
      currentLine += this.f ? buffer.substring(pieceStartOffset, Math.max(pieceStartOffset, lineStarts[pieceStartLine + 1] - this.e)) : buffer.substring(pieceStartOffset, lineStarts[pieceStartLine + 1]).replace(/(\r\n|\r|\n)$/, "");
      lines[linesLength++] = currentLine;
      for (let line = pieceStartLine + 1; line < pieceEndLine; line++) {
        currentLine = this.f ? buffer.substring(lineStarts[line], lineStarts[line + 1] - this.e) : buffer.substring(lineStarts[line], lineStarts[line + 1]).replace(/(\r\n|\r|\n)$/, "");
        lines[linesLength++] = currentLine;
      }
      if (!this.f && buffer.charCodeAt(lineStarts[pieceEndLine] + piece.end.column - 1) === 13) {
        danglingCR = true;
        if (piece.end.column === 0) {
          linesLength--;
        } else {
          currentLine = buffer.substr(lineStarts[pieceEndLine], piece.end.column - 1);
        }
      } else {
        currentLine = buffer.substr(lineStarts[pieceEndLine], piece.end.column);
      }
      return true;
    });
    if (danglingCR) {
      lines[linesLength++] = currentLine;
      currentLine = "";
    }
    lines[linesLength++] = currentLine;
    return lines;
  }
  getLength() {
    return this.c;
  }
  getLineCount() {
    return this.b;
  }
  getLineContent(lineNumber) {
    if (this.j.lineNumber === lineNumber) {
      return this.j.value;
    }
    this.j.lineNumber = lineNumber;
    if (lineNumber === this.b) {
      this.j.value = this.getLineRawContent(lineNumber);
    } else if (this.f) {
      this.j.value = this.getLineRawContent(lineNumber, this.e);
    } else {
      this.j.value = this.getLineRawContent(lineNumber).replace(/(\r\n|\r|\n)$/, "");
    }
    return this.j.value;
  }
  l(nodePos) {
    if (nodePos.remainder === nodePos.node.piece.length) {
      const matchingNode = nodePos.node.next();
      if (!matchingNode) {
        return 0;
      }
      const buffer = this.a[matchingNode.piece.bufferIndex];
      const startOffset = this.u(matchingNode.piece.bufferIndex, matchingNode.piece.start);
      return buffer.buffer.charCodeAt(startOffset);
    } else {
      const buffer = this.a[nodePos.node.piece.bufferIndex];
      const startOffset = this.u(nodePos.node.piece.bufferIndex, nodePos.node.piece.start);
      const targetOffset = startOffset + nodePos.remainder;
      return buffer.buffer.charCodeAt(targetOffset);
    }
  }
  getLineCharCode(lineNumber, index) {
    const nodePos = this.H(lineNumber, index + 1);
    return this.l(nodePos);
  }
  getLineLength(lineNumber) {
    if (lineNumber === this.getLineCount()) {
      const startOffset = this.getOffsetAt(lineNumber, 1);
      return this.getLength() - startOffset;
    }
    return this.getOffsetAt(lineNumber + 1, 1) - this.getOffsetAt(lineNumber, 1) - this.e;
  }
  getCharCode(offset) {
    const nodePos = this.G(offset);
    return this.l(nodePos);
  }
  getNearestChunk(offset) {
    const nodePos = this.G(offset);
    if (nodePos.remainder === nodePos.node.piece.length) {
      const matchingNode = nodePos.node.next();
      if (!matchingNode || matchingNode === $9H) {
        return "";
      }
      const buffer = this.a[matchingNode.piece.bufferIndex];
      const startOffset = this.u(matchingNode.piece.bufferIndex, matchingNode.piece.start);
      return buffer.buffer.substring(startOffset, startOffset + matchingNode.piece.length);
    } else {
      const buffer = this.a[nodePos.node.piece.bufferIndex];
      const startOffset = this.u(nodePos.node.piece.bufferIndex, nodePos.node.piece.start);
      const targetOffset = startOffset + nodePos.remainder;
      const targetEnd = startOffset + nodePos.node.piece.length;
      return buffer.buffer.substring(targetOffset, targetEnd);
    }
  }
  findMatchesInNode(node, searcher, startLineNumber, startColumn, startCursor, endCursor, searchData, captureMatches, limitResultCount, resultLen, result) {
    const buffer = this.a[node.piece.bufferIndex];
    const startOffsetInBuffer = this.u(node.piece.bufferIndex, node.piece.start);
    const start = this.u(node.piece.bufferIndex, startCursor);
    const end = this.u(node.piece.bufferIndex, endCursor);
    let m;
    const ret = { line: 0, column: 0 };
    let searchText;
    let offsetInBuffer;
    if (searcher._wordSeparators) {
      searchText = buffer.buffer.substring(start, end);
      offsetInBuffer = (offset) => offset + start;
      searcher.reset(0);
    } else {
      searchText = buffer.buffer;
      offsetInBuffer = (offset) => offset;
      searcher.reset(start);
    }
    do {
      m = searcher.next(searchText);
      if (m) {
        if (offsetInBuffer(m.index) >= end) {
          return resultLen;
        }
        this.s(node, offsetInBuffer(m.index) - startOffsetInBuffer, ret);
        const lineFeedCnt = this.t(node.piece.bufferIndex, startCursor, ret);
        const retStartColumn = ret.line === startCursor.line ? ret.column - startCursor.column + startColumn : ret.column + 1;
        const retEndColumn = retStartColumn + m[0].length;
        result[resultLen++] = $hI(new $9C(startLineNumber + lineFeedCnt, retStartColumn, startLineNumber + lineFeedCnt, retEndColumn), m, captureMatches);
        if (offsetInBuffer(m.index) + m[0].length >= end) {
          return resultLen;
        }
        if (resultLen >= limitResultCount) {
          return resultLen;
        }
      }
    } while (m);
    return resultLen;
  }
  findMatchesLineByLine(searchRange, searchData, captureMatches, limitResultCount) {
    const result = [];
    let resultLen = 0;
    const searcher = new $kI(searchData.wordSeparators, searchData.regex);
    let startPosition = this.H(searchRange.startLineNumber, searchRange.startColumn);
    if (startPosition === null) {
      return [];
    }
    const endPosition = this.H(searchRange.endLineNumber, searchRange.endColumn);
    if (endPosition === null) {
      return [];
    }
    let start = this.s(startPosition.node, startPosition.remainder);
    const end = this.s(endPosition.node, endPosition.remainder);
    if (startPosition.node === endPosition.node) {
      this.findMatchesInNode(startPosition.node, searcher, searchRange.startLineNumber, searchRange.startColumn, start, end, searchData, captureMatches, limitResultCount, resultLen, result);
      return result;
    }
    let startLineNumber = searchRange.startLineNumber;
    let currentNode = startPosition.node;
    while (currentNode !== endPosition.node) {
      const lineBreakCnt = this.t(currentNode.piece.bufferIndex, start, currentNode.piece.end);
      if (lineBreakCnt >= 1) {
        const lineStarts = this.a[currentNode.piece.bufferIndex].lineStarts;
        const startOffsetInBuffer = this.u(currentNode.piece.bufferIndex, currentNode.piece.start);
        const nextLineStartOffset = lineStarts[start.line + lineBreakCnt];
        const startColumn3 = startLineNumber === searchRange.startLineNumber ? searchRange.startColumn : 1;
        resultLen = this.findMatchesInNode(currentNode, searcher, startLineNumber, startColumn3, start, this.s(currentNode, nextLineStartOffset - startOffsetInBuffer), searchData, captureMatches, limitResultCount, resultLen, result);
        if (resultLen >= limitResultCount) {
          return result;
        }
        startLineNumber += lineBreakCnt;
      }
      const startColumn2 = startLineNumber === searchRange.startLineNumber ? searchRange.startColumn - 1 : 0;
      if (startLineNumber === searchRange.endLineNumber) {
        const text2 = this.getLineContent(startLineNumber).substring(startColumn2, searchRange.endColumn - 1);
        resultLen = this.n(searchData, searcher, text2, searchRange.endLineNumber, startColumn2, resultLen, result, captureMatches, limitResultCount);
        return result;
      }
      resultLen = this.n(searchData, searcher, this.getLineContent(startLineNumber).substr(startColumn2), startLineNumber, startColumn2, resultLen, result, captureMatches, limitResultCount);
      if (resultLen >= limitResultCount) {
        return result;
      }
      startLineNumber++;
      startPosition = this.H(startLineNumber, 1);
      currentNode = startPosition.node;
      start = this.s(startPosition.node, startPosition.remainder);
    }
    if (startLineNumber === searchRange.endLineNumber) {
      const startColumn2 = startLineNumber === searchRange.startLineNumber ? searchRange.startColumn - 1 : 0;
      const text2 = this.getLineContent(startLineNumber).substring(startColumn2, searchRange.endColumn - 1);
      resultLen = this.n(searchData, searcher, text2, searchRange.endLineNumber, startColumn2, resultLen, result, captureMatches, limitResultCount);
      return result;
    }
    const startColumn = startLineNumber === searchRange.startLineNumber ? searchRange.startColumn : 1;
    resultLen = this.findMatchesInNode(endPosition.node, searcher, startLineNumber, startColumn, start, end, searchData, captureMatches, limitResultCount, resultLen, result);
    return result;
  }
  n(searchData, searcher, text2, lineNumber, deltaOffset, resultLen, result, captureMatches, limitResultCount) {
    const wordSeparators2 = searchData.wordSeparators;
    if (!captureMatches && searchData.simpleSearch) {
      const searchString = searchData.simpleSearch;
      const searchStringLen = searchString.length;
      const textLength = text2.length;
      let lastMatchIndex = -searchStringLen;
      while ((lastMatchIndex = text2.indexOf(searchString, lastMatchIndex + searchStringLen)) !== -1) {
        if (!wordSeparators2 || $jI(wordSeparators2, text2, textLength, lastMatchIndex, searchStringLen)) {
          result[resultLen++] = new $eG(new $9C(lineNumber, lastMatchIndex + 1 + deltaOffset, lineNumber, lastMatchIndex + 1 + searchStringLen + deltaOffset), null);
          if (resultLen >= limitResultCount) {
            return resultLen;
          }
        }
      }
      return resultLen;
    }
    let m;
    searcher.reset(0);
    do {
      m = searcher.next(text2);
      if (m) {
        result[resultLen++] = $hI(new $9C(lineNumber, m.index + 1 + deltaOffset, lineNumber, m.index + 1 + m[0].length + deltaOffset), m, captureMatches);
        if (resultLen >= limitResultCount) {
          return resultLen;
        }
      }
    } while (m);
    return resultLen;
  }
  // #endregion
  // #region Piece Table
  insert(offset, value, eolNormalized = false) {
    this.f = this.f && eolNormalized;
    this.j.lineNumber = 0;
    this.j.value = "";
    if (this.root !== $9H) {
      const { node, remainder, nodeStartOffset } = this.G(offset);
      const piece = node.piece;
      const bufferIndex = piece.bufferIndex;
      const insertPosInBuffer = this.s(node, remainder);
      if (node.piece.bufferIndex === 0 && piece.end.line === this.g.line && piece.end.column === this.g.column && nodeStartOffset + piece.length === offset && value.length < AverageBufferSize) {
        this.F(node, value);
        this.y();
        return;
      }
      if (nodeStartOffset === offset) {
        this.o(value, node);
        this.h.validate(offset);
      } else if (nodeStartOffset + node.piece.length > offset) {
        const nodesToDel = [];
        let newRightPiece = new $nI(piece.bufferIndex, insertPosInBuffer, piece.end, this.t(piece.bufferIndex, insertPosInBuffer, piece.end), this.u(bufferIndex, piece.end) - this.u(bufferIndex, insertPosInBuffer));
        if (this.K() && this.M(value)) {
          const headOfRight = this.I(node, remainder);
          if (headOfRight === 10) {
            const newStart = { line: newRightPiece.start.line + 1, column: 0 };
            newRightPiece = new $nI(newRightPiece.bufferIndex, newStart, newRightPiece.end, this.t(newRightPiece.bufferIndex, newStart, newRightPiece.end), newRightPiece.length - 1);
            value += "\n";
          }
        }
        if (this.K() && this.L(value)) {
          const tailOfLeft = this.I(node, remainder - 1);
          if (tailOfLeft === 13) {
            const previousPos = this.s(node, remainder - 1);
            this.C(node, previousPos);
            value = "\r" + value;
            if (node.piece.length === 0) {
              nodesToDel.push(node);
            }
          } else {
            this.C(node, insertPosInBuffer);
          }
        } else {
          this.C(node, insertPosInBuffer);
        }
        const newPieces = this.w(value);
        if (newRightPiece.length > 0) {
          this.S(node, newRightPiece);
        }
        let tmpNode = node;
        for (let k = 0; k < newPieces.length; k++) {
          tmpNode = this.S(tmpNode, newPieces[k]);
        }
        this.v(nodesToDel);
      } else {
        this.q(value, node);
      }
    } else {
      const pieces = this.w(value);
      let node = this.T(null, pieces[0]);
      for (let k = 1; k < pieces.length; k++) {
        node = this.S(node, pieces[k]);
      }
    }
    this.y();
  }
  delete(offset, cnt) {
    this.j.lineNumber = 0;
    this.j.value = "";
    if (cnt <= 0 || this.root === $9H) {
      return;
    }
    const startPosition = this.G(offset);
    const endPosition = this.G(offset + cnt);
    const startNode = startPosition.node;
    const endNode = endPosition.node;
    if (startNode === endNode) {
      const startSplitPosInBuffer2 = this.s(startNode, startPosition.remainder);
      const endSplitPosInBuffer2 = this.s(startNode, endPosition.remainder);
      if (startPosition.nodeStartOffset === offset) {
        if (cnt === startNode.piece.length) {
          const next = startNode.next();
          $bI(this, startNode);
          this.N(next);
          this.y();
          return;
        }
        this.D(startNode, endSplitPosInBuffer2);
        this.h.validate(offset);
        this.N(startNode);
        this.y();
        return;
      }
      if (startPosition.nodeStartOffset + startNode.piece.length === offset + cnt) {
        this.C(startNode, startSplitPosInBuffer2);
        this.O(startNode);
        this.y();
        return;
      }
      this.E(startNode, startSplitPosInBuffer2, endSplitPosInBuffer2);
      this.y();
      return;
    }
    const nodesToDel = [];
    const startSplitPosInBuffer = this.s(startNode, startPosition.remainder);
    this.C(startNode, startSplitPosInBuffer);
    this.h.validate(offset);
    if (startNode.piece.length === 0) {
      nodesToDel.push(startNode);
    }
    const endSplitPosInBuffer = this.s(endNode, endPosition.remainder);
    this.D(endNode, endSplitPosInBuffer);
    if (endNode.piece.length === 0) {
      nodesToDel.push(endNode);
    }
    const secondNode = startNode.next();
    for (let node = secondNode; node !== $9H && node !== endNode; node = node.next()) {
      nodesToDel.push(node);
    }
    const prev = startNode.piece.length === 0 ? startNode.prev() : startNode;
    this.v(nodesToDel);
    this.O(prev);
    this.y();
  }
  o(value, node) {
    const nodesToDel = [];
    if (this.K() && this.M(value) && this.L(node)) {
      const piece = node.piece;
      const newStart = { line: piece.start.line + 1, column: 0 };
      const nPiece = new $nI(piece.bufferIndex, newStart, piece.end, this.t(piece.bufferIndex, newStart, piece.end), piece.length - 1);
      node.piece = nPiece;
      value += "\n";
      $dI(this, node, -1, -1);
      if (node.piece.length === 0) {
        nodesToDel.push(node);
      }
    }
    const newPieces = this.w(value);
    let newNode = this.T(node, newPieces[newPieces.length - 1]);
    for (let k = newPieces.length - 2; k >= 0; k--) {
      newNode = this.T(newNode, newPieces[k]);
    }
    this.N(newNode);
    this.v(nodesToDel);
  }
  q(value, node) {
    if (this.Q(value, node)) {
      value += "\n";
    }
    const newPieces = this.w(value);
    const newNode = this.S(node, newPieces[0]);
    let tmpNode = newNode;
    for (let k = 1; k < newPieces.length; k++) {
      tmpNode = this.S(tmpNode, newPieces[k]);
    }
    this.N(newNode);
  }
  s(node, remainder, ret) {
    const piece = node.piece;
    const bufferIndex = node.piece.bufferIndex;
    const lineStarts = this.a[bufferIndex].lineStarts;
    const startOffset = lineStarts[piece.start.line] + piece.start.column;
    const offset = startOffset + remainder;
    let low = piece.start.line;
    let high = piece.end.line;
    let mid = 0;
    let midStop = 0;
    let midStart = 0;
    while (low <= high) {
      mid = low + (high - low) / 2 | 0;
      midStart = lineStarts[mid];
      if (mid === high) {
        break;
      }
      midStop = lineStarts[mid + 1];
      if (offset < midStart) {
        high = mid - 1;
      } else if (offset >= midStop) {
        low = mid + 1;
      } else {
        break;
      }
    }
    if (ret) {
      ret.line = mid;
      ret.column = offset - midStart;
      return null;
    }
    return {
      line: mid,
      column: offset - midStart
    };
  }
  t(bufferIndex, start, end) {
    if (end.column === 0) {
      return end.line - start.line;
    }
    const lineStarts = this.a[bufferIndex].lineStarts;
    if (end.line === lineStarts.length - 1) {
      return end.line - start.line;
    }
    const nextLineStartOffset = lineStarts[end.line + 1];
    const endOffset = lineStarts[end.line] + end.column;
    if (nextLineStartOffset > endOffset + 1) {
      return end.line - start.line;
    }
    const previousCharOffset = endOffset - 1;
    const buffer = this.a[bufferIndex].buffer;
    if (buffer.charCodeAt(previousCharOffset) === 13) {
      return end.line - start.line + 1;
    } else {
      return end.line - start.line;
    }
  }
  u(bufferIndex, cursor) {
    const lineStarts = this.a[bufferIndex].lineStarts;
    return lineStarts[cursor.line] + cursor.column;
  }
  v(nodes) {
    for (let i2 = 0; i2 < nodes.length; i2++) {
      $bI(this, nodes[i2]);
    }
  }
  w(text2) {
    if (text2.length > AverageBufferSize) {
      const newPieces = [];
      while (text2.length > AverageBufferSize) {
        const lastChar = text2.charCodeAt(AverageBufferSize - 1);
        let splitText;
        if (lastChar === 13 || lastChar >= 55296 && lastChar <= 56319) {
          splitText = text2.substring(0, AverageBufferSize - 1);
          text2 = text2.substring(AverageBufferSize - 1);
        } else {
          splitText = text2.substring(0, AverageBufferSize);
          text2 = text2.substring(AverageBufferSize);
        }
        const lineStarts3 = $lI(splitText);
        newPieces.push(new $nI(
          this.a.length,
          /* buffer index */
          { line: 0, column: 0 },
          { line: lineStarts3.length - 1, column: splitText.length - lineStarts3[lineStarts3.length - 1] },
          lineStarts3.length - 1,
          splitText.length
        ));
        this.a.push(new $oI(splitText, lineStarts3));
      }
      const lineStarts2 = $lI(text2);
      newPieces.push(new $nI(
        this.a.length,
        /* buffer index */
        { line: 0, column: 0 },
        { line: lineStarts2.length - 1, column: text2.length - lineStarts2[lineStarts2.length - 1] },
        lineStarts2.length - 1,
        text2.length
      ));
      this.a.push(new $oI(text2, lineStarts2));
      return newPieces;
    }
    let startOffset = this.a[0].buffer.length;
    const lineStarts = $lI(text2, false);
    let start = this.g;
    if (this.a[0].lineStarts[this.a[0].lineStarts.length - 1] === startOffset && startOffset !== 0 && this.L(text2) && this.M(this.a[0].buffer)) {
      this.g = { line: this.g.line, column: this.g.column + 1 };
      start = this.g;
      for (let i2 = 0; i2 < lineStarts.length; i2++) {
        lineStarts[i2] += startOffset + 1;
      }
      this.a[0].lineStarts = this.a[0].lineStarts.concat(lineStarts.slice(1));
      this.a[0].buffer += "_" + text2;
      startOffset += 1;
    } else {
      if (startOffset !== 0) {
        for (let i2 = 0; i2 < lineStarts.length; i2++) {
          lineStarts[i2] += startOffset;
        }
      }
      this.a[0].lineStarts = this.a[0].lineStarts.concat(lineStarts.slice(1));
      this.a[0].buffer += text2;
    }
    const endOffset = this.a[0].buffer.length;
    const endIndex = this.a[0].lineStarts.length - 1;
    const endColumn = endOffset - this.a[0].lineStarts[endIndex];
    const endPos = { line: endIndex, column: endColumn };
    const newPiece = new $nI(
      0,
      /** todo@peng */
      start,
      endPos,
      this.t(0, start, endPos),
      endOffset - startOffset
    );
    this.g = endPos;
    return [newPiece];
  }
  getLinesRawContent() {
    return this.U(this.root);
  }
  getLineRawContent(lineNumber, endOffset = 0) {
    let x = this.root;
    let ret = "";
    const cache2 = this.h.get2(lineNumber);
    if (cache2) {
      x = cache2.node;
      const prevAccumulatedValue = this.B(x, lineNumber - cache2.nodeStartLineNumber - 1);
      const buffer = this.a[x.piece.bufferIndex].buffer;
      const startOffset = this.u(x.piece.bufferIndex, x.piece.start);
      if (cache2.nodeStartLineNumber + x.piece.lineFeedCnt === lineNumber) {
        ret = buffer.substring(startOffset + prevAccumulatedValue, startOffset + x.piece.length);
      } else {
        const accumulatedValue = this.B(x, lineNumber - cache2.nodeStartLineNumber);
        return buffer.substring(startOffset + prevAccumulatedValue, startOffset + accumulatedValue - endOffset);
      }
    } else {
      let nodeStartOffset = 0;
      const originalLineNumber = lineNumber;
      while (x !== $9H) {
        if (x.left !== $9H && x.lf_left >= lineNumber - 1) {
          x = x.left;
        } else if (x.lf_left + x.piece.lineFeedCnt > lineNumber - 1) {
          const prevAccumulatedValue = this.B(x, lineNumber - x.lf_left - 2);
          const accumulatedValue = this.B(x, lineNumber - x.lf_left - 1);
          const buffer = this.a[x.piece.bufferIndex].buffer;
          const startOffset = this.u(x.piece.bufferIndex, x.piece.start);
          nodeStartOffset += x.size_left;
          this.h.set({
            node: x,
            nodeStartOffset,
            nodeStartLineNumber: originalLineNumber - (lineNumber - 1 - x.lf_left)
          });
          return buffer.substring(startOffset + prevAccumulatedValue, startOffset + accumulatedValue - endOffset);
        } else if (x.lf_left + x.piece.lineFeedCnt === lineNumber - 1) {
          const prevAccumulatedValue = this.B(x, lineNumber - x.lf_left - 2);
          const buffer = this.a[x.piece.bufferIndex].buffer;
          const startOffset = this.u(x.piece.bufferIndex, x.piece.start);
          ret = buffer.substring(startOffset + prevAccumulatedValue, startOffset + x.piece.length);
          break;
        } else {
          lineNumber -= x.lf_left + x.piece.lineFeedCnt;
          nodeStartOffset += x.size_left + x.piece.length;
          x = x.right;
        }
      }
    }
    x = x.next();
    while (x !== $9H) {
      const buffer = this.a[x.piece.bufferIndex].buffer;
      if (x.piece.lineFeedCnt > 0) {
        const accumulatedValue = this.B(x, 0);
        const startOffset = this.u(x.piece.bufferIndex, x.piece.start);
        ret += buffer.substring(startOffset, startOffset + accumulatedValue - endOffset);
        return ret;
      } else {
        const startOffset = this.u(x.piece.bufferIndex, x.piece.start);
        ret += buffer.substr(startOffset, x.piece.length);
      }
      x = x.next();
    }
    return ret;
  }
  y() {
    let x = this.root;
    let lfCnt = 1;
    let len = 0;
    while (x !== $9H) {
      lfCnt += x.lf_left + x.piece.lineFeedCnt;
      len += x.size_left + x.piece.length;
      x = x.right;
    }
    this.b = lfCnt;
    this.c = len;
    this.h.validate(this.c);
  }
  // #region node operations
  A(node, accumulatedValue) {
    const piece = node.piece;
    const pos = this.s(node, accumulatedValue);
    const lineCnt = pos.line - piece.start.line;
    if (this.u(piece.bufferIndex, piece.end) - this.u(piece.bufferIndex, piece.start) === accumulatedValue) {
      const realLineCnt = this.t(node.piece.bufferIndex, piece.start, pos);
      if (realLineCnt !== lineCnt) {
        return { index: realLineCnt, remainder: 0 };
      }
    }
    return { index: lineCnt, remainder: pos.column };
  }
  B(node, index) {
    if (index < 0) {
      return 0;
    }
    const piece = node.piece;
    const lineStarts = this.a[piece.bufferIndex].lineStarts;
    const expectedLineStartIndex = piece.start.line + index + 1;
    if (expectedLineStartIndex > piece.end.line) {
      return lineStarts[piece.end.line] + piece.end.column - lineStarts[piece.start.line] - piece.start.column;
    } else {
      return lineStarts[expectedLineStartIndex] - lineStarts[piece.start.line] - piece.start.column;
    }
  }
  C(node, pos) {
    const piece = node.piece;
    const originalLFCnt = piece.lineFeedCnt;
    const originalEndOffset = this.u(piece.bufferIndex, piece.end);
    const newEnd = pos;
    const newEndOffset = this.u(piece.bufferIndex, newEnd);
    const newLineFeedCnt = this.t(piece.bufferIndex, piece.start, newEnd);
    const lf_delta = newLineFeedCnt - originalLFCnt;
    const size_delta = newEndOffset - originalEndOffset;
    const newLength = piece.length + size_delta;
    node.piece = new $nI(piece.bufferIndex, piece.start, newEnd, newLineFeedCnt, newLength);
    $dI(this, node, size_delta, lf_delta);
  }
  D(node, pos) {
    const piece = node.piece;
    const originalLFCnt = piece.lineFeedCnt;
    const originalStartOffset = this.u(piece.bufferIndex, piece.start);
    const newStart = pos;
    const newLineFeedCnt = this.t(piece.bufferIndex, newStart, piece.end);
    const newStartOffset = this.u(piece.bufferIndex, newStart);
    const lf_delta = newLineFeedCnt - originalLFCnt;
    const size_delta = originalStartOffset - newStartOffset;
    const newLength = piece.length + size_delta;
    node.piece = new $nI(piece.bufferIndex, newStart, piece.end, newLineFeedCnt, newLength);
    $dI(this, node, size_delta, lf_delta);
  }
  E(node, start, end) {
    const piece = node.piece;
    const originalStartPos = piece.start;
    const originalEndPos = piece.end;
    const oldLength = piece.length;
    const oldLFCnt = piece.lineFeedCnt;
    const newEnd = start;
    const newLineFeedCnt = this.t(piece.bufferIndex, piece.start, newEnd);
    const newLength = this.u(piece.bufferIndex, start) - this.u(piece.bufferIndex, originalStartPos);
    node.piece = new $nI(piece.bufferIndex, piece.start, newEnd, newLineFeedCnt, newLength);
    $dI(this, node, newLength - oldLength, newLineFeedCnt - oldLFCnt);
    const newPiece = new $nI(piece.bufferIndex, end, originalEndPos, this.t(piece.bufferIndex, end, originalEndPos), this.u(piece.bufferIndex, originalEndPos) - this.u(piece.bufferIndex, end));
    const newNode = this.S(node, newPiece);
    this.N(newNode);
  }
  F(node, value) {
    if (this.Q(value, node)) {
      value += "\n";
    }
    const hitCRLF = this.K() && this.L(value) && this.M(node);
    const startOffset = this.a[0].buffer.length;
    this.a[0].buffer += value;
    const lineStarts = $lI(value, false);
    for (let i2 = 0; i2 < lineStarts.length; i2++) {
      lineStarts[i2] += startOffset;
    }
    if (hitCRLF) {
      const prevStartOffset = this.a[0].lineStarts[this.a[0].lineStarts.length - 2];
      this.a[0].lineStarts.pop();
      this.g = { line: this.g.line - 1, column: startOffset - prevStartOffset };
    }
    this.a[0].lineStarts = this.a[0].lineStarts.concat(lineStarts.slice(1));
    const endIndex = this.a[0].lineStarts.length - 1;
    const endColumn = this.a[0].buffer.length - this.a[0].lineStarts[endIndex];
    const newEnd = { line: endIndex, column: endColumn };
    const newLength = node.piece.length + value.length;
    const oldLineFeedCnt = node.piece.lineFeedCnt;
    const newLineFeedCnt = this.t(0, node.piece.start, newEnd);
    const lf_delta = newLineFeedCnt - oldLineFeedCnt;
    node.piece = new $nI(node.piece.bufferIndex, node.piece.start, newEnd, newLineFeedCnt, newLength);
    this.g = newEnd;
    $dI(this, node, value.length, lf_delta);
  }
  G(offset) {
    let x = this.root;
    const cache2 = this.h.get(offset);
    if (cache2) {
      return {
        node: cache2.node,
        nodeStartOffset: cache2.nodeStartOffset,
        remainder: offset - cache2.nodeStartOffset
      };
    }
    let nodeStartOffset = 0;
    while (x !== $9H) {
      if (x.size_left > offset) {
        x = x.left;
      } else if (x.size_left + x.piece.length >= offset) {
        nodeStartOffset += x.size_left;
        const ret = {
          node: x,
          remainder: offset - x.size_left,
          nodeStartOffset
        };
        this.h.set(ret);
        return ret;
      } else {
        offset -= x.size_left + x.piece.length;
        nodeStartOffset += x.size_left + x.piece.length;
        x = x.right;
      }
    }
    return null;
  }
  H(lineNumber, column) {
    let x = this.root;
    let nodeStartOffset = 0;
    while (x !== $9H) {
      if (x.left !== $9H && x.lf_left >= lineNumber - 1) {
        x = x.left;
      } else if (x.lf_left + x.piece.lineFeedCnt > lineNumber - 1) {
        const prevAccumualtedValue = this.B(x, lineNumber - x.lf_left - 2);
        const accumulatedValue = this.B(x, lineNumber - x.lf_left - 1);
        nodeStartOffset += x.size_left;
        return {
          node: x,
          remainder: Math.min(prevAccumualtedValue + column - 1, accumulatedValue),
          nodeStartOffset
        };
      } else if (x.lf_left + x.piece.lineFeedCnt === lineNumber - 1) {
        const prevAccumualtedValue = this.B(x, lineNumber - x.lf_left - 2);
        if (prevAccumualtedValue + column - 1 <= x.piece.length) {
          return {
            node: x,
            remainder: prevAccumualtedValue + column - 1,
            nodeStartOffset
          };
        } else {
          column -= x.piece.length - prevAccumualtedValue;
          break;
        }
      } else {
        lineNumber -= x.lf_left + x.piece.lineFeedCnt;
        nodeStartOffset += x.size_left + x.piece.length;
        x = x.right;
      }
    }
    x = x.next();
    while (x !== $9H) {
      if (x.piece.lineFeedCnt > 0) {
        const accumulatedValue = this.B(x, 0);
        const nodeStartOffset2 = this.J(x);
        return {
          node: x,
          remainder: Math.min(column - 1, accumulatedValue),
          nodeStartOffset: nodeStartOffset2
        };
      } else {
        if (x.piece.length >= column - 1) {
          const nodeStartOffset2 = this.J(x);
          return {
            node: x,
            remainder: column - 1,
            nodeStartOffset: nodeStartOffset2
          };
        } else {
          column -= x.piece.length;
        }
      }
      x = x.next();
    }
    return null;
  }
  I(node, offset) {
    if (node.piece.lineFeedCnt < 1) {
      return -1;
    }
    const buffer = this.a[node.piece.bufferIndex];
    const newOffset = this.u(node.piece.bufferIndex, node.piece.start) + offset;
    return buffer.buffer.charCodeAt(newOffset);
  }
  J(node) {
    if (!node) {
      return 0;
    }
    let pos = node.size_left;
    while (node !== this.root) {
      if (node.parent.right === node) {
        pos += node.parent.size_left + node.parent.piece.length;
      }
      node = node.parent;
    }
    return pos;
  }
  // #endregion
  // #region CRLF
  K() {
    return !(this.f && this.d === "\n");
  }
  L(val) {
    if (typeof val === "string") {
      return val.charCodeAt(0) === 10;
    }
    if (val === $9H || val.piece.lineFeedCnt === 0) {
      return false;
    }
    const piece = val.piece;
    const lineStarts = this.a[piece.bufferIndex].lineStarts;
    const line = piece.start.line;
    const startOffset = lineStarts[line] + piece.start.column;
    if (line === lineStarts.length - 1) {
      return false;
    }
    const nextLineOffset = lineStarts[line + 1];
    if (nextLineOffset > startOffset + 1) {
      return false;
    }
    return this.a[piece.bufferIndex].buffer.charCodeAt(startOffset) === 10;
  }
  M(val) {
    if (typeof val === "string") {
      return val.charCodeAt(val.length - 1) === 13;
    }
    if (val === $9H || val.piece.lineFeedCnt === 0) {
      return false;
    }
    return this.I(val, val.piece.length - 1) === 13;
  }
  N(nextNode) {
    if (this.K() && this.L(nextNode)) {
      const node = nextNode.prev();
      if (this.M(node)) {
        this.P(node, nextNode);
      }
    }
  }
  O(node) {
    if (this.K() && this.M(node)) {
      const nextNode = node.next();
      if (this.L(nextNode)) {
        this.P(node, nextNode);
      }
    }
  }
  P(prev, next) {
    const nodesToDel = [];
    const lineStarts = this.a[prev.piece.bufferIndex].lineStarts;
    let newEnd;
    if (prev.piece.end.column === 0) {
      newEnd = { line: prev.piece.end.line - 1, column: lineStarts[prev.piece.end.line] - lineStarts[prev.piece.end.line - 1] - 1 };
    } else {
      newEnd = { line: prev.piece.end.line, column: prev.piece.end.column - 1 };
    }
    const prevNewLength = prev.piece.length - 1;
    const prevNewLFCnt = prev.piece.lineFeedCnt - 1;
    prev.piece = new $nI(prev.piece.bufferIndex, prev.piece.start, newEnd, prevNewLFCnt, prevNewLength);
    $dI(this, prev, -1, -1);
    if (prev.piece.length === 0) {
      nodesToDel.push(prev);
    }
    const newStart = { line: next.piece.start.line + 1, column: 0 };
    const newLength = next.piece.length - 1;
    const newLineFeedCnt = this.t(next.piece.bufferIndex, newStart, next.piece.end);
    next.piece = new $nI(next.piece.bufferIndex, newStart, next.piece.end, newLineFeedCnt, newLength);
    $dI(this, next, -1, -1);
    if (next.piece.length === 0) {
      nodesToDel.push(next);
    }
    const pieces = this.w("\r\n");
    this.S(prev, pieces[0]);
    for (let i2 = 0; i2 < nodesToDel.length; i2++) {
      $bI(this, nodesToDel[i2]);
    }
  }
  Q(value, node) {
    if (this.K() && this.M(value)) {
      const nextNode = node.next();
      if (this.L(nextNode)) {
        value += "\n";
        if (nextNode.piece.length === 1) {
          $bI(this, nextNode);
        } else {
          const piece = nextNode.piece;
          const newStart = { line: piece.start.line + 1, column: 0 };
          const newLength = piece.length - 1;
          const newLineFeedCnt = this.t(piece.bufferIndex, newStart, piece.end);
          nextNode.piece = new $nI(piece.bufferIndex, newStart, piece.end, newLineFeedCnt, newLength);
          $dI(this, nextNode, -1, -1);
        }
        return true;
      }
    }
    return false;
  }
  // #endregion
  // #endregion
  // #region Tree operations
  iterate(node, callback) {
    if (node === $9H) {
      return callback($9H);
    }
    const leftRet = this.iterate(node.left, callback);
    if (!leftRet) {
      return leftRet;
    }
    return callback(node) && this.iterate(node.right, callback);
  }
  R(node) {
    if (node === $9H) {
      return "";
    }
    const buffer = this.a[node.piece.bufferIndex];
    const piece = node.piece;
    const startOffset = this.u(piece.bufferIndex, piece.start);
    const endOffset = this.u(piece.bufferIndex, piece.end);
    const currentContent = buffer.buffer.substring(startOffset, endOffset);
    return currentContent;
  }
  getPieceContent(piece) {
    const buffer = this.a[piece.bufferIndex];
    const startOffset = this.u(piece.bufferIndex, piece.start);
    const endOffset = this.u(piece.bufferIndex, piece.end);
    const currentContent = buffer.buffer.substring(startOffset, endOffset);
    return currentContent;
  }
  /**
   *      node              node
   *     /  \              /  \
   *    a   b    <----   a    b
   *                         /
   *                        z
   */
  S(node, p) {
    const z = new $8H(
      p,
      1
      /* NodeColor.Red */
    );
    z.left = $9H;
    z.right = $9H;
    z.parent = $9H;
    z.size_left = 0;
    z.lf_left = 0;
    const x = this.root;
    if (x === $9H) {
      this.root = z;
      z.color = 0;
    } else if (node.right === $9H) {
      node.right = z;
      z.parent = node;
    } else {
      const nextNode = $0H(node.right);
      nextNode.left = z;
      z.parent = nextNode;
    }
    $cI(this, z);
    return z;
  }
  /**
   *      node              node
   *     /  \              /  \
   *    a   b     ---->   a    b
   *                       \
   *                        z
   */
  T(node, p) {
    const z = new $8H(
      p,
      1
      /* NodeColor.Red */
    );
    z.left = $9H;
    z.right = $9H;
    z.parent = $9H;
    z.size_left = 0;
    z.lf_left = 0;
    if (this.root === $9H) {
      this.root = z;
      z.color = 0;
    } else if (node.left === $9H) {
      node.left = z;
      z.parent = node;
    } else {
      const prevNode = $$H(node.left);
      prevNode.right = z;
      z.parent = prevNode;
    }
    $cI(this, z);
    return z;
  }
  U(node) {
    let str = "";
    this.iterate(node, (node2) => {
      str += this.R(node2);
      return true;
    });
    return str;
  }
};

// out-build/vs/editor/common/model/pieceTreeTextBuffer/pieceTreeTextBuffer.js
var $qI = class _$qI extends $3c {
  constructor(chunks, BOM, eol, containsRTL, containsUnusualLineTerminators, isBasicASCII, eolNormalized) {
    super();
    this.m = this.B(new $ze());
    this.onDidChangeContent = this.m.event;
    this.f = BOM;
    this.j = !isBasicASCII;
    this.g = containsRTL;
    this.h = containsUnusualLineTerminators;
    this.c = new $pI(chunks, eol, eolNormalized);
  }
  // #region TextBuffer
  equals(other) {
    if (!(other instanceof _$qI)) {
      return false;
    }
    if (this.f !== other.f) {
      return false;
    }
    if (this.getEOL() !== other.getEOL()) {
      return false;
    }
    return this.c.equal(other.c);
  }
  mightContainRTL() {
    return this.g;
  }
  mightContainUnusualLineTerminators() {
    return this.h;
  }
  resetMightContainUnusualLineTerminators() {
    this.h = false;
  }
  mightContainNonBasicASCII() {
    return this.j;
  }
  getBOM() {
    return this.f;
  }
  getEOL() {
    return this.c.getEOL();
  }
  createSnapshot(preserveBOM) {
    return this.c.createSnapshot(preserveBOM ? this.f : "");
  }
  getOffsetAt(lineNumber, column) {
    return this.c.getOffsetAt(lineNumber, column);
  }
  getPositionAt(offset) {
    return this.c.getPositionAt(offset);
  }
  getRangeAt(start, length) {
    const end = start + length;
    const startPosition = this.getPositionAt(start);
    const endPosition = this.getPositionAt(end);
    return new $9C(startPosition.lineNumber, startPosition.column, endPosition.lineNumber, endPosition.column);
  }
  getValueInRange(range, eol = 0) {
    if (range.isEmpty()) {
      return "";
    }
    const lineEnding = this.n(eol);
    return this.c.getValueInRange(range, lineEnding);
  }
  getValueLengthInRange(range, eol = 0) {
    if (range.isEmpty()) {
      return 0;
    }
    if (range.startLineNumber === range.endLineNumber) {
      return range.endColumn - range.startColumn;
    }
    const startOffset = this.getOffsetAt(range.startLineNumber, range.startColumn);
    const endOffset = this.getOffsetAt(range.endLineNumber, range.endColumn);
    let eolOffsetCompensation = 0;
    const desiredEOL = this.n(eol);
    const actualEOL = this.getEOL();
    if (desiredEOL.length !== actualEOL.length) {
      const delta = desiredEOL.length - actualEOL.length;
      const eolCount = range.endLineNumber - range.startLineNumber;
      eolOffsetCompensation = delta * eolCount;
    }
    return endOffset - startOffset + eolOffsetCompensation;
  }
  getCharacterCountInRange(range, eol = 0) {
    if (this.j) {
      let result = 0;
      const fromLineNumber = range.startLineNumber;
      const toLineNumber = range.endLineNumber;
      for (let lineNumber = fromLineNumber; lineNumber <= toLineNumber; lineNumber++) {
        const lineContent = this.getLineContent(lineNumber);
        const fromOffset = lineNumber === fromLineNumber ? range.startColumn - 1 : 0;
        const toOffset = lineNumber === toLineNumber ? range.endColumn - 1 : lineContent.length;
        for (let offset = fromOffset; offset < toOffset; offset++) {
          if ($5f(lineContent.charCodeAt(offset))) {
            result = result + 1;
            offset = offset + 1;
          } else {
            result = result + 1;
          }
        }
      }
      result += this.n(eol).length * (toLineNumber - fromLineNumber);
      return result;
    }
    return this.getValueLengthInRange(range, eol);
  }
  getNearestChunk(offset) {
    return this.c.getNearestChunk(offset);
  }
  getLength() {
    return this.c.getLength();
  }
  getLineCount() {
    return this.c.getLineCount();
  }
  getLinesContent() {
    return this.c.getLinesContent();
  }
  getLineContent(lineNumber) {
    return this.c.getLineContent(lineNumber);
  }
  getLineCharCode(lineNumber, index) {
    return this.c.getLineCharCode(lineNumber, index);
  }
  getCharCode(offset) {
    return this.c.getCharCode(offset);
  }
  getLineLength(lineNumber) {
    return this.c.getLineLength(lineNumber);
  }
  getLineMinColumn(lineNumber) {
    return 1;
  }
  getLineMaxColumn(lineNumber) {
    return this.getLineLength(lineNumber) + 1;
  }
  getLineFirstNonWhitespaceColumn(lineNumber) {
    const result = $Of(this.getLineContent(lineNumber));
    if (result === -1) {
      return 0;
    }
    return result + 1;
  }
  getLineLastNonWhitespaceColumn(lineNumber) {
    const result = $Qf(this.getLineContent(lineNumber));
    if (result === -1) {
      return 0;
    }
    return result + 2;
  }
  n(eol) {
    switch (eol) {
      case 1:
        return "\n";
      case 2:
        return "\r\n";
      case 0:
        return this.getEOL();
      default:
        throw new Error("Unknown EOL preference");
    }
  }
  setEOL(newEOL) {
    this.c.setEOL(newEOL);
  }
  applyEdits(rawOperations, recordTrimAutoWhitespace, computeUndoEdits) {
    let mightContainRTL = this.g;
    let mightContainUnusualLineTerminators = this.h;
    let mightContainNonBasicASCII = this.j;
    let canReduceOperations = true;
    let operations = [];
    for (let i2 = 0; i2 < rawOperations.length; i2++) {
      const op = rawOperations[i2];
      if (canReduceOperations && op._isTracked) {
        canReduceOperations = false;
      }
      const validatedRange = op.range;
      if (op.text) {
        let textMightContainNonBasicASCII = true;
        if (!mightContainNonBasicASCII) {
          textMightContainNonBasicASCII = !$dg(op.text);
          mightContainNonBasicASCII = textMightContainNonBasicASCII;
        }
        if (!mightContainRTL && textMightContainNonBasicASCII) {
          mightContainRTL = $cg(op.text);
        }
        if (!mightContainUnusualLineTerminators && textMightContainNonBasicASCII) {
          mightContainUnusualLineTerminators = $fg(op.text);
        }
      }
      let validText = "";
      let eolCount = 0;
      let firstLineLength = 0;
      let lastLineLength = 0;
      if (op.text) {
        let strEOL;
        [eolCount, firstLineLength, lastLineLength, strEOL] = $tE(op.text);
        const bufferEOL = this.getEOL();
        const expectedStrEOL = bufferEOL === "\r\n" ? 2 : 1;
        if (strEOL === 0 || strEOL === expectedStrEOL) {
          validText = op.text;
        } else {
          validText = op.text.replace(/\r\n|\r|\n/g, bufferEOL);
        }
      }
      operations[i2] = {
        sortIndex: i2,
        identifier: op.identifier || null,
        range: validatedRange,
        rangeOffset: this.getOffsetAt(validatedRange.startLineNumber, validatedRange.startColumn),
        rangeLength: this.getValueLengthInRange(validatedRange),
        text: validText,
        eolCount,
        firstLineLength,
        lastLineLength,
        forceMoveMarkers: Boolean(op.forceMoveMarkers),
        isAutoWhitespaceEdit: op.isAutoWhitespaceEdit || false
      };
    }
    operations.sort(_$qI.u);
    let hasTouchingRanges = false;
    for (let i2 = 0, count = operations.length - 1; i2 < count; i2++) {
      const rangeEnd = operations[i2].range.getEndPosition();
      const nextRangeStart = operations[i2 + 1].range.getStartPosition();
      if (nextRangeStart.isBeforeOrEqual(rangeEnd)) {
        if (nextRangeStart.isBefore(rangeEnd)) {
          throw new Error("Overlapping ranges are not allowed!");
        }
        hasTouchingRanges = true;
      }
    }
    if (canReduceOperations) {
      operations = this.s(operations);
    }
    const reverseRanges = computeUndoEdits || recordTrimAutoWhitespace ? _$qI._getInverseEditRanges(operations) : [];
    const newTrimAutoWhitespaceCandidates = [];
    if (recordTrimAutoWhitespace) {
      for (let i2 = 0; i2 < operations.length; i2++) {
        const op = operations[i2];
        const reverseRange = reverseRanges[i2];
        if (op.isAutoWhitespaceEdit && op.range.isEmpty()) {
          for (let lineNumber = reverseRange.startLineNumber; lineNumber <= reverseRange.endLineNumber; lineNumber++) {
            let currentLineContent = "";
            if (lineNumber === reverseRange.startLineNumber) {
              currentLineContent = this.getLineContent(op.range.startLineNumber);
              if ($Of(currentLineContent) !== -1) {
                continue;
              }
            }
            newTrimAutoWhitespaceCandidates.push({ lineNumber, oldContent: currentLineContent });
          }
        }
      }
    }
    let reverseOperations = null;
    if (computeUndoEdits) {
      let reverseRangeDeltaOffset = 0;
      reverseOperations = [];
      for (let i2 = 0; i2 < operations.length; i2++) {
        const op = operations[i2];
        const reverseRange = reverseRanges[i2];
        const bufferText = this.getValueInRange(op.range);
        const reverseRangeOffset = op.rangeOffset + reverseRangeDeltaOffset;
        reverseRangeDeltaOffset += op.text.length - bufferText.length;
        reverseOperations[i2] = {
          sortIndex: op.sortIndex,
          identifier: op.identifier,
          range: reverseRange,
          text: bufferText,
          textChange: new $dE(op.rangeOffset, bufferText, reverseRangeOffset, op.text)
        };
      }
      if (!hasTouchingRanges) {
        reverseOperations.sort((a, b) => a.sortIndex - b.sortIndex);
      }
    }
    this.g = mightContainRTL;
    this.h = mightContainUnusualLineTerminators;
    this.j = mightContainNonBasicASCII;
    const contentChanges = this.t(operations);
    let trimAutoWhitespaceLineNumbers = null;
    if (recordTrimAutoWhitespace && newTrimAutoWhitespaceCandidates.length > 0) {
      newTrimAutoWhitespaceCandidates.sort((a, b) => b.lineNumber - a.lineNumber);
      trimAutoWhitespaceLineNumbers = [];
      for (let i2 = 0, len = newTrimAutoWhitespaceCandidates.length; i2 < len; i2++) {
        const lineNumber = newTrimAutoWhitespaceCandidates[i2].lineNumber;
        if (i2 > 0 && newTrimAutoWhitespaceCandidates[i2 - 1].lineNumber === lineNumber) {
          continue;
        }
        const prevContent = newTrimAutoWhitespaceCandidates[i2].oldContent;
        const lineContent = this.getLineContent(lineNumber);
        if (lineContent.length === 0 || lineContent === prevContent || $Of(lineContent) !== -1) {
          continue;
        }
        trimAutoWhitespaceLineNumbers.push(lineNumber);
      }
    }
    this.m.fire();
    return new $jG(reverseOperations, contentChanges, trimAutoWhitespaceLineNumbers);
  }
  /**
   * Transform operations such that they represent the same logic edit,
   * but that they also do not cause OOM crashes.
   */
  s(operations) {
    if (operations.length < 1e3) {
      return operations;
    }
    return [this._toSingleEditOperation(operations)];
  }
  _toSingleEditOperation(operations) {
    let forceMoveMarkers = false;
    const firstEditRange = operations[0].range;
    const lastEditRange = operations[operations.length - 1].range;
    const entireEditRange = new $9C(firstEditRange.startLineNumber, firstEditRange.startColumn, lastEditRange.endLineNumber, lastEditRange.endColumn);
    let lastEndLineNumber = firstEditRange.startLineNumber;
    let lastEndColumn = firstEditRange.startColumn;
    const result = [];
    for (let i2 = 0, len = operations.length; i2 < len; i2++) {
      const operation = operations[i2];
      const range = operation.range;
      forceMoveMarkers = forceMoveMarkers || operation.forceMoveMarkers;
      result.push(this.getValueInRange(new $9C(lastEndLineNumber, lastEndColumn, range.startLineNumber, range.startColumn)));
      if (operation.text.length > 0) {
        result.push(operation.text);
      }
      lastEndLineNumber = range.endLineNumber;
      lastEndColumn = range.endColumn;
    }
    const text2 = result.join("");
    const [eolCount, firstLineLength, lastLineLength] = $tE(text2);
    return {
      sortIndex: 0,
      identifier: operations[0].identifier,
      range: entireEditRange,
      rangeOffset: this.getOffsetAt(entireEditRange.startLineNumber, entireEditRange.startColumn),
      rangeLength: this.getValueLengthInRange(
        entireEditRange,
        0
        /* EndOfLinePreference.TextDefined */
      ),
      text: text2,
      eolCount,
      firstLineLength,
      lastLineLength,
      forceMoveMarkers,
      isAutoWhitespaceEdit: false
    };
  }
  t(operations) {
    operations.sort(_$qI.w);
    const contentChanges = [];
    for (let i2 = 0; i2 < operations.length; i2++) {
      const op = operations[i2];
      const startLineNumber = op.range.startLineNumber;
      const startColumn = op.range.startColumn;
      const endLineNumber = op.range.endLineNumber;
      const endColumn = op.range.endColumn;
      if (startLineNumber === endLineNumber && startColumn === endColumn && op.text.length === 0) {
        continue;
      }
      if (op.text) {
        this.c.delete(op.rangeOffset, op.rangeLength);
        this.c.insert(op.rangeOffset, op.text, true);
      } else {
        this.c.delete(op.rangeOffset, op.rangeLength);
      }
      const contentChangeRange = new $9C(startLineNumber, startColumn, endLineNumber, endColumn);
      contentChanges.push({
        range: contentChangeRange,
        rangeLength: op.rangeLength,
        text: op.text,
        rangeOffset: op.rangeOffset,
        forceMoveMarkers: op.forceMoveMarkers
      });
    }
    return contentChanges;
  }
  findMatchesLineByLine(searchRange, searchData, captureMatches, limitResultCount) {
    return this.c.findMatchesLineByLine(searchRange, searchData, captureMatches, limitResultCount);
  }
  // #endregion
  // #region helper
  // testing purpose.
  getPieceTree() {
    return this.c;
  }
  static _getInverseEditRange(range, text2) {
    const startLineNumber = range.startLineNumber;
    const startColumn = range.startColumn;
    const [eolCount, firstLineLength, lastLineLength] = $tE(text2);
    let resultRange;
    if (text2.length > 0) {
      const lineCount = eolCount + 1;
      if (lineCount === 1) {
        resultRange = new $9C(startLineNumber, startColumn, startLineNumber, startColumn + firstLineLength);
      } else {
        resultRange = new $9C(startLineNumber, startColumn, startLineNumber + lineCount - 1, lastLineLength + 1);
      }
    } else {
      resultRange = new $9C(startLineNumber, startColumn, startLineNumber, startColumn);
    }
    return resultRange;
  }
  /**
   * Assumes `operations` are validated and sorted ascending
   */
  static _getInverseEditRanges(operations) {
    const result = [];
    let prevOpEndLineNumber = 0;
    let prevOpEndColumn = 0;
    let prevOp = null;
    for (let i2 = 0, len = operations.length; i2 < len; i2++) {
      const op = operations[i2];
      let startLineNumber;
      let startColumn;
      if (prevOp) {
        if (prevOp.range.endLineNumber === op.range.startLineNumber) {
          startLineNumber = prevOpEndLineNumber;
          startColumn = prevOpEndColumn + (op.range.startColumn - prevOp.range.endColumn);
        } else {
          startLineNumber = prevOpEndLineNumber + (op.range.startLineNumber - prevOp.range.endLineNumber);
          startColumn = op.range.startColumn;
        }
      } else {
        startLineNumber = op.range.startLineNumber;
        startColumn = op.range.startColumn;
      }
      let resultRange;
      if (op.text.length > 0) {
        const lineCount = op.eolCount + 1;
        if (lineCount === 1) {
          resultRange = new $9C(startLineNumber, startColumn, startLineNumber, startColumn + op.firstLineLength);
        } else {
          resultRange = new $9C(startLineNumber, startColumn, startLineNumber + lineCount - 1, op.lastLineLength + 1);
        }
      } else {
        resultRange = new $9C(startLineNumber, startColumn, startLineNumber, startColumn);
      }
      prevOpEndLineNumber = resultRange.endLineNumber;
      prevOpEndColumn = resultRange.endColumn;
      result.push(resultRange);
      prevOp = op;
    }
    return result;
  }
  static u(a, b) {
    const r2 = $9C.compareRangesUsingEnds(a.range, b.range);
    if (r2 === 0) {
      return a.sortIndex - b.sortIndex;
    }
    return r2;
  }
  static w(a, b) {
    const r2 = $9C.compareRangesUsingEnds(a.range, b.range);
    if (r2 === 0) {
      return b.sortIndex - a.sortIndex;
    }
    return -r2;
  }
};

// out-build/vs/editor/common/model/pieceTreeTextBuffer/pieceTreeTextBufferBuilder.js
var PieceTreeTextBufferFactory = class {
  constructor(a, b, c, d, e, f, g, h3, j) {
    this.a = a;
    this.b = b;
    this.c = c;
    this.d = d;
    this.e = e;
    this.f = f;
    this.g = g;
    this.h = h3;
    this.j = j;
  }
  k(defaultEOL) {
    const totalEOLCount = this.c + this.d + this.e;
    const totalCRCount = this.c + this.e;
    if (totalEOLCount === 0) {
      return defaultEOL === 1 ? "\n" : "\r\n";
    }
    if (totalCRCount > totalEOLCount / 2) {
      return "\r\n";
    }
    return "\n";
  }
  create(defaultEOL) {
    const eol = this.k(defaultEOL);
    const chunks = this.a;
    if (this.j && (eol === "\r\n" && (this.c > 0 || this.d > 0) || eol === "\n" && (this.c > 0 || this.e > 0))) {
      for (let i2 = 0, len = chunks.length; i2 < len; i2++) {
        const str = chunks[i2].buffer.replace(/\r\n|\r|\n/g, eol);
        const newLineStart = $lI(str);
        chunks[i2] = new $oI(str, newLineStart);
      }
    }
    const textBuffer = new $qI(chunks, this.b, eol, this.f, this.g, this.h, this.j);
    return { textBuffer, disposable: textBuffer };
  }
  getFirstLineText(lengthLimit) {
    return this.a[0].buffer.substr(0, lengthLimit).split(/\r\n|\r|\n/)[0];
  }
};
var $rI = class {
  constructor() {
    this.a = [];
    this.b = "";
    this.c = false;
    this.d = 0;
    this.e = [];
    this.f = 0;
    this.g = 0;
    this.h = 0;
    this.j = false;
    this.k = false;
    this.l = true;
  }
  acceptChunk(chunk) {
    if (chunk.length === 0) {
      return;
    }
    if (this.a.length === 0) {
      if ($ng(chunk)) {
        this.b = $mg;
        chunk = chunk.substr(1);
      }
    }
    const lastChar = chunk.charCodeAt(chunk.length - 1);
    if (lastChar === 13 || lastChar >= 55296 && lastChar <= 56319) {
      this.m(chunk.substr(0, chunk.length - 1), false);
      this.c = true;
      this.d = lastChar;
    } else {
      this.m(chunk, false);
      this.c = false;
      this.d = lastChar;
    }
  }
  m(chunk, allowEmptyStrings) {
    if (!allowEmptyStrings && chunk.length === 0) {
      return;
    }
    if (this.c) {
      this.n(String.fromCharCode(this.d) + chunk);
    } else {
      this.n(chunk);
    }
  }
  n(chunk) {
    const lineStarts = $mI(this.e, chunk);
    this.a.push(new $oI(chunk, lineStarts.lineStarts));
    this.f += lineStarts.cr;
    this.g += lineStarts.lf;
    this.h += lineStarts.crlf;
    if (!lineStarts.isBasicASCII) {
      this.l = false;
      if (!this.j) {
        this.j = $cg(chunk);
      }
      if (!this.k) {
        this.k = $fg(chunk);
      }
    }
  }
  finish(normalizeEOL = true) {
    this.o();
    return new PieceTreeTextBufferFactory(this.a, this.b, this.f, this.g, this.h, this.j, this.k, this.l, normalizeEOL);
  }
  o() {
    if (this.a.length === 0) {
      this.m("", true);
    }
    if (this.c) {
      this.c = false;
      const lastChunk = this.a[this.a.length - 1];
      lastChunk.buffer += String.fromCharCode(this.d);
      const newLineStarts = $lI(lastChunk.buffer);
      lastChunk.lineStarts = newLineStarts;
      if (this.d === 13) {
        this.f++;
      }
    }
  }
};

// out-build/vs/editor/common/languages/nullTokenize.js
var $sI = new class {
  clone() {
    return this;
  }
  equals(other) {
    return this === other;
  }
}();
function $uI(languageId, state) {
  const tokens = new Uint32Array(2);
  tokens[0] = 0;
  tokens[1] = (languageId << 0 | 0 << 8 | 0 << 11 | 1 << 15 | 2 << 24) >>> 0;
  return new $PE(tokens, state === null ? $sI : state);
}

// out-build/vs/editor/common/model/fixedArray.js
var $vI = class {
  constructor(b) {
    this.b = b;
    this.a = [];
  }
  get(index) {
    if (index < this.a.length) {
      return this.a[index];
    }
    return this.b;
  }
  set(index, value) {
    while (index >= this.a.length) {
      this.a[this.a.length] = this.b;
    }
    this.a[index] = value;
  }
  replace(index, oldLength, newLength) {
    if (index >= this.a.length) {
      return;
    }
    if (oldLength === 0) {
      this.insert(index, newLength);
      return;
    } else if (newLength === 0) {
      this.delete(index, oldLength);
      return;
    }
    const before = this.a.slice(0, index);
    const after = this.a.slice(index + oldLength);
    const insertArr = arrayFill(newLength, this.b);
    this.a = before.concat(insertArr, after);
  }
  delete(deleteIndex, deleteCount) {
    if (deleteCount === 0 || deleteIndex >= this.a.length) {
      return;
    }
    this.a.splice(deleteIndex, deleteCount);
  }
  insert(insertIndex, insertCount) {
    if (insertCount === 0 || insertIndex >= this.a.length) {
      return;
    }
    const arr = [];
    for (let i2 = 0; i2 < insertCount; i2++) {
      arr[i2] = this.b;
    }
    this.a = $Yb(this.a, insertIndex, arr);
  }
};
function arrayFill(length, value) {
  const arr = [];
  for (let i2 = 0; i2 < length; i2++) {
    arr[i2] = value;
  }
  return arr;
}

// out-build/vs/editor/common/tokens/contiguousTokensEditing.js
var $zE = new Uint32Array(0).buffer;
var $AE = class _$AE {
  static deleteBeginning(lineTokens, toChIndex) {
    if (lineTokens === null || lineTokens === $zE) {
      return lineTokens;
    }
    return _$AE.delete(lineTokens, 0, toChIndex);
  }
  static deleteEnding(lineTokens, fromChIndex) {
    if (lineTokens === null || lineTokens === $zE) {
      return lineTokens;
    }
    const tokens = $BE(lineTokens);
    const lineTextLength = tokens[tokens.length - 2];
    return _$AE.delete(lineTokens, fromChIndex, lineTextLength);
  }
  static delete(lineTokens, fromChIndex, toChIndex) {
    if (lineTokens === null || lineTokens === $zE || fromChIndex === toChIndex) {
      return lineTokens;
    }
    const tokens = $BE(lineTokens);
    const tokensCount = tokens.length >>> 1;
    if (fromChIndex === 0 && tokens[tokens.length - 2] === toChIndex) {
      return $zE;
    }
    const fromTokenIndex = $xE.findIndexInTokensArray(tokens, fromChIndex);
    const fromTokenStartOffset = fromTokenIndex > 0 ? tokens[fromTokenIndex - 1 << 1] : 0;
    const fromTokenEndOffset = tokens[fromTokenIndex << 1];
    if (toChIndex < fromTokenEndOffset) {
      const delta2 = toChIndex - fromChIndex;
      for (let i2 = fromTokenIndex; i2 < tokensCount; i2++) {
        tokens[i2 << 1] -= delta2;
      }
      return lineTokens;
    }
    let dest;
    let lastEnd;
    if (fromTokenStartOffset !== fromChIndex) {
      tokens[fromTokenIndex << 1] = fromChIndex;
      dest = fromTokenIndex + 1 << 1;
      lastEnd = fromChIndex;
    } else {
      dest = fromTokenIndex << 1;
      lastEnd = fromTokenStartOffset;
    }
    const delta = toChIndex - fromChIndex;
    for (let tokenIndex = fromTokenIndex + 1; tokenIndex < tokensCount; tokenIndex++) {
      const tokenEndOffset = tokens[tokenIndex << 1] - delta;
      if (tokenEndOffset > lastEnd) {
        tokens[dest++] = tokenEndOffset;
        tokens[dest++] = tokens[(tokenIndex << 1) + 1];
        lastEnd = tokenEndOffset;
      }
    }
    if (dest === tokens.length) {
      return lineTokens;
    }
    const tmp = new Uint32Array(dest);
    tmp.set(tokens.subarray(0, dest), 0);
    return tmp.buffer;
  }
  static append(lineTokens, _otherTokens) {
    if (_otherTokens === $zE) {
      return lineTokens;
    }
    if (lineTokens === $zE) {
      return _otherTokens;
    }
    if (lineTokens === null) {
      return lineTokens;
    }
    if (_otherTokens === null) {
      return null;
    }
    const myTokens = $BE(lineTokens);
    const otherTokens = $BE(_otherTokens);
    const otherTokensCount = otherTokens.length >>> 1;
    const result = new Uint32Array(myTokens.length + otherTokens.length);
    result.set(myTokens, 0);
    let dest = myTokens.length;
    const delta = myTokens[myTokens.length - 2];
    for (let i2 = 0; i2 < otherTokensCount; i2++) {
      result[dest++] = otherTokens[i2 << 1] + delta;
      result[dest++] = otherTokens[(i2 << 1) + 1];
    }
    return result.buffer;
  }
  static insert(lineTokens, chIndex, textLength) {
    if (lineTokens === null || lineTokens === $zE) {
      return lineTokens;
    }
    const tokens = $BE(lineTokens);
    const tokensCount = tokens.length >>> 1;
    let fromTokenIndex = $xE.findIndexInTokensArray(tokens, chIndex);
    if (fromTokenIndex > 0) {
      const fromTokenStartOffset = tokens[fromTokenIndex - 1 << 1];
      if (fromTokenStartOffset === chIndex) {
        fromTokenIndex--;
      }
    }
    for (let tokenIndex = fromTokenIndex; tokenIndex < tokensCount; tokenIndex++) {
      tokens[tokenIndex << 1] += textLength;
    }
    return lineTokens;
  }
};
function $BE(arr) {
  if (arr instanceof Uint32Array) {
    return arr;
  } else {
    return new Uint32Array(arr);
  }
}

// out-build/vs/editor/common/tokens/contiguousMultilineTokens.js
var $CE = class _$CE {
  static deserialize(buff, offset, result) {
    const view32 = new Uint32Array(buff.buffer);
    const startLineNumber = $Gi(buff, offset);
    offset += 4;
    const count = $Gi(buff, offset);
    offset += 4;
    const tokens = [];
    for (let i2 = 0; i2 < count; i2++) {
      const byteCount = $Gi(buff, offset);
      offset += 4;
      tokens.push(view32.subarray(offset / 4, offset / 4 + byteCount / 4));
      offset += byteCount;
    }
    result.push(new _$CE(startLineNumber, tokens));
    return offset;
  }
  /**
   * (Inclusive) start line number for these tokens.
   */
  get startLineNumber() {
    return this.a;
  }
  /**
   * (Inclusive) end line number for these tokens.
   */
  get endLineNumber() {
    return this.a + this.b.length - 1;
  }
  constructor(startLineNumber, tokens) {
    this.a = startLineNumber;
    this.b = tokens;
  }
  getLineRange() {
    return new $_C(this.a, this.a + this.b.length);
  }
  /**
   * @see {@link b}
   */
  getLineTokens(lineNumber) {
    return this.b[lineNumber - this.a];
  }
  appendLineTokens(lineTokens) {
    this.b.push(lineTokens);
  }
  serializeSize() {
    let result = 0;
    result += 4;
    result += 4;
    for (let i2 = 0; i2 < this.b.length; i2++) {
      const lineTokens = this.b[i2];
      if (!(lineTokens instanceof Uint32Array)) {
        throw new Error(`Not supported!`);
      }
      result += 4;
      result += lineTokens.byteLength;
    }
    return result;
  }
  serialize(destination, offset) {
    $Hi(destination, this.a, offset);
    offset += 4;
    $Hi(destination, this.b.length, offset);
    offset += 4;
    for (let i2 = 0; i2 < this.b.length; i2++) {
      const lineTokens = this.b[i2];
      if (!(lineTokens instanceof Uint32Array)) {
        throw new Error(`Not supported!`);
      }
      $Hi(destination, lineTokens.byteLength, offset);
      offset += 4;
      destination.set(new Uint8Array(lineTokens.buffer), offset);
      offset += lineTokens.byteLength;
    }
    return offset;
  }
  applyEdit(range, text2) {
    const [eolCount, firstLineLength] = $tE(text2);
    this.c(range);
    this.d(new $8C(range.startLineNumber, range.startColumn), eolCount, firstLineLength);
  }
  c(range) {
    if (range.startLineNumber === range.endLineNumber && range.startColumn === range.endColumn) {
      return;
    }
    const firstLineIndex = range.startLineNumber - this.a;
    const lastLineIndex = range.endLineNumber - this.a;
    if (lastLineIndex < 0) {
      const deletedLinesCount = lastLineIndex - firstLineIndex;
      this.a -= deletedLinesCount;
      return;
    }
    if (firstLineIndex >= this.b.length) {
      return;
    }
    if (firstLineIndex < 0 && lastLineIndex >= this.b.length) {
      this.a = 0;
      this.b = [];
      return;
    }
    if (firstLineIndex === lastLineIndex) {
      this.b[firstLineIndex] = $AE.delete(this.b[firstLineIndex], range.startColumn - 1, range.endColumn - 1);
      return;
    }
    if (firstLineIndex >= 0) {
      this.b[firstLineIndex] = $AE.deleteEnding(this.b[firstLineIndex], range.startColumn - 1);
      if (lastLineIndex < this.b.length) {
        const lastLineTokens = $AE.deleteBeginning(this.b[lastLineIndex], range.endColumn - 1);
        this.b[firstLineIndex] = $AE.append(this.b[firstLineIndex], lastLineTokens);
        this.b.splice(firstLineIndex + 1, lastLineIndex - firstLineIndex);
      } else {
        this.b[firstLineIndex] = $AE.append(this.b[firstLineIndex], null);
        this.b = this.b.slice(0, firstLineIndex + 1);
      }
    } else {
      const deletedBefore = -firstLineIndex;
      this.a -= deletedBefore;
      this.b[lastLineIndex] = $AE.deleteBeginning(this.b[lastLineIndex], range.endColumn - 1);
      this.b = this.b.slice(lastLineIndex);
    }
  }
  d(position, eolCount, firstLineLength) {
    if (eolCount === 0 && firstLineLength === 0) {
      return;
    }
    const lineIndex = position.lineNumber - this.a;
    if (lineIndex < 0) {
      this.a += eolCount;
      return;
    }
    if (lineIndex >= this.b.length) {
      return;
    }
    if (eolCount === 0) {
      this.b[lineIndex] = $AE.insert(this.b[lineIndex], position.column - 1, firstLineLength);
      return;
    }
    this.b[lineIndex] = $AE.deleteEnding(this.b[lineIndex], position.column - 1);
    this.b[lineIndex] = $AE.insert(this.b[lineIndex], position.column - 1, firstLineLength);
    this.e(position.lineNumber, eolCount);
  }
  e(insertIndex, insertCount) {
    if (insertCount === 0) {
      return;
    }
    const lineTokens = [];
    for (let i2 = 0; i2 < insertCount; i2++) {
      lineTokens[i2] = null;
    }
    this.b = $Yb(this.b, insertIndex, lineTokens);
  }
};

// out-build/vs/editor/common/tokens/contiguousMultilineTokensBuilder.js
var $wI = class {
  static deserialize(buff) {
    let offset = 0;
    const count = $Gi(buff, offset);
    offset += 4;
    const result = [];
    for (let i2 = 0; i2 < count; i2++) {
      offset = $CE.deserialize(buff, offset, result);
    }
    return result;
  }
  constructor() {
    this.a = [];
  }
  add(lineNumber, lineTokens) {
    if (this.a.length > 0) {
      const last = this.a[this.a.length - 1];
      if (last.endLineNumber + 1 === lineNumber) {
        last.appendLineTokens(lineTokens);
        return;
      }
    }
    this.a.push(new $CE(lineNumber, [lineTokens]));
  }
  finalize() {
    return this.a;
  }
  serialize() {
    const size = this.b();
    const result = new Uint8Array(size);
    this.c(result);
    return result;
  }
  b() {
    let result = 0;
    result += 4;
    for (let i2 = 0; i2 < this.a.length; i2++) {
      result += this.a[i2].serializeSize();
    }
    return result;
  }
  c(destination) {
    let offset = 0;
    $Hi(destination, this.a.length, offset);
    offset += 4;
    for (let i2 = 0; i2 < this.a.length; i2++) {
      offset = this.a[i2].serialize(destination, offset);
    }
  }
};

// out-build/vs/editor/common/model/textModelTokens.js
var Constants10;
(function(Constants27) {
  Constants27[Constants27["CHEAP_TOKENIZATION_LENGTH_LIMIT"] = 2048] = "CHEAP_TOKENIZATION_LENGTH_LIMIT";
})(Constants10 || (Constants10 = {}));
var $xI = class {
  constructor(lineCount, tokenizationSupport) {
    this.tokenizationSupport = tokenizationSupport;
    this.a = this.tokenizationSupport.getInitialState();
    this.store = new $zI(lineCount);
  }
  getStartState(lineNumber) {
    return this.store.getStartState(lineNumber, this.a);
  }
  getFirstInvalidLine() {
    return this.store.getFirstInvalidLine(this.a);
  }
};
var $yI = class extends $xI {
  constructor(lineCount, tokenizationSupport, _textModel, _languageIdCodec) {
    super(lineCount, tokenizationSupport);
    this._textModel = _textModel;
    this._languageIdCodec = _languageIdCodec;
  }
  updateTokensUntilLine(builder, lineNumber) {
    const languageId = this._textModel.getLanguageId();
    while (true) {
      const lineToTokenize = this.getFirstInvalidLine();
      if (!lineToTokenize || lineToTokenize.lineNumber > lineNumber) {
        break;
      }
      const text2 = this._textModel.getLineContent(lineToTokenize.lineNumber);
      const r2 = safeTokenize(this._languageIdCodec, languageId, this.tokenizationSupport, text2, true, lineToTokenize.startState);
      builder.add(lineToTokenize.lineNumber, r2.tokens);
      this.store.setEndState(lineToTokenize.lineNumber, r2.endState);
    }
  }
  /** assumes state is up to date */
  getTokenTypeIfInsertingCharacter(position, character) {
    const lineStartState = this.getStartState(position.lineNumber);
    if (!lineStartState) {
      return 0;
    }
    const languageId = this._textModel.getLanguageId();
    const lineContent = this._textModel.getLineContent(position.lineNumber);
    const text2 = lineContent.substring(0, position.column - 1) + character + lineContent.substring(position.column - 1);
    const r2 = safeTokenize(this._languageIdCodec, languageId, this.tokenizationSupport, text2, true, lineStartState);
    const lineTokens = new $xE(r2.tokens, text2, this._languageIdCodec);
    if (lineTokens.getCount() === 0) {
      return 0;
    }
    const tokenIndex = lineTokens.findTokenIndexAtOffset(position.column - 1);
    return lineTokens.getStandardTokenType(tokenIndex);
  }
  /** assumes state is up to date */
  tokenizeLineWithEdit(lineNumber, edit3) {
    const lineStartState = this.getStartState(lineNumber);
    if (!lineStartState) {
      return { mainLineTokens: null, additionalLines: null };
    }
    const curLineContent = this._textModel.getLineContent(lineNumber);
    const newLineContent = edit3.lineEdit.apply(curLineContent);
    const languageId = this._textModel.getLanguageIdAtPosition(lineNumber, 0);
    const result = safeTokenize(this._languageIdCodec, languageId, this.tokenizationSupport, newLineContent, true, lineStartState);
    let additionalLines = null;
    if (edit3.additionalLines) {
      additionalLines = [];
      let state = result.endState;
      for (const line of edit3.additionalLines) {
        const r2 = safeTokenize(this._languageIdCodec, languageId, this.tokenizationSupport, line, true, state);
        additionalLines.push(new $xE(r2.tokens, line, this._languageIdCodec));
        state = r2.endState;
      }
    }
    const mainLineTokens = new $xE(result.tokens, newLineContent, this._languageIdCodec);
    return { mainLineTokens, additionalLines };
  }
  hasAccurateTokensForLine(lineNumber) {
    const firstInvalidLineNumber = this.store.getFirstInvalidEndStateLineNumberOrMax();
    return lineNumber < firstInvalidLineNumber;
  }
  isCheapToTokenize(lineNumber) {
    const firstInvalidLineNumber = this.store.getFirstInvalidEndStateLineNumberOrMax();
    if (lineNumber < firstInvalidLineNumber) {
      return true;
    }
    if (lineNumber === firstInvalidLineNumber && this._textModel.getLineLength(lineNumber) < 2048) {
      return true;
    }
    return false;
  }
  /**
   * The result is not cached.
   */
  tokenizeHeuristically(builder, startLineNumber, endLineNumber) {
    if (endLineNumber <= this.store.getFirstInvalidEndStateLineNumberOrMax()) {
      return { heuristicTokens: false };
    }
    if (startLineNumber <= this.store.getFirstInvalidEndStateLineNumberOrMax()) {
      this.updateTokensUntilLine(builder, endLineNumber);
      return { heuristicTokens: false };
    }
    let state = this.b(startLineNumber);
    const languageId = this._textModel.getLanguageId();
    for (let lineNumber = startLineNumber; lineNumber <= endLineNumber; lineNumber++) {
      const text2 = this._textModel.getLineContent(lineNumber);
      const r2 = safeTokenize(this._languageIdCodec, languageId, this.tokenizationSupport, text2, true, state);
      builder.add(lineNumber, r2.tokens);
      state = r2.endState;
    }
    return { heuristicTokens: true };
  }
  b(lineNumber) {
    let nonWhitespaceColumn = this._textModel.getLineFirstNonWhitespaceColumn(lineNumber);
    const likelyRelevantLines = [];
    let initialState = null;
    for (let i2 = lineNumber - 1; nonWhitespaceColumn > 1 && i2 >= 1; i2--) {
      const newNonWhitespaceIndex = this._textModel.getLineFirstNonWhitespaceColumn(i2);
      if (newNonWhitespaceIndex === 0) {
        continue;
      }
      if (newNonWhitespaceIndex < nonWhitespaceColumn) {
        likelyRelevantLines.push(this._textModel.getLineContent(i2));
        nonWhitespaceColumn = newNonWhitespaceIndex;
        initialState = this.getStartState(i2);
        if (initialState) {
          break;
        }
      }
    }
    if (!initialState) {
      initialState = this.tokenizationSupport.getInitialState();
    }
    likelyRelevantLines.reverse();
    const languageId = this._textModel.getLanguageId();
    let state = initialState;
    for (const line of likelyRelevantLines) {
      const r2 = safeTokenize(this._languageIdCodec, languageId, this.tokenizationSupport, line, false, state);
      state = r2.endState;
    }
    return state;
  }
};
var $zI = class {
  constructor(d) {
    this.d = d;
    this.a = new $AI();
    this.b = new $BI();
    this.b.addRange(new $0C(1, d + 1));
  }
  getEndState(lineNumber) {
    return this.a.getEndState(lineNumber);
  }
  /**
   * @returns if the end state has changed.
   */
  setEndState(lineNumber, state) {
    if (!state) {
      throw new $vb("Cannot set null/undefined state");
    }
    this.b.delete(lineNumber);
    const r2 = this.a.setEndState(lineNumber, state);
    if (r2 && lineNumber < this.d) {
      this.b.addRange(new $0C(lineNumber + 1, lineNumber + 2));
    }
    return r2;
  }
  acceptChange(range, newLineCount) {
    this.d += newLineCount - range.length;
    this.a.acceptChange(range, newLineCount);
    this.b.addRangeAndResize(new $0C(range.startLineNumber, range.endLineNumberExclusive), newLineCount);
  }
  acceptChanges(changes) {
    for (const c of changes) {
      const [eolCount] = $tE(c.text);
      this.acceptChange(new $_C(c.range.startLineNumber, c.range.endLineNumber + 1), eolCount + 1);
    }
  }
  invalidateEndStateRange(range) {
    this.b.addRange(new $0C(range.startLineNumber, range.endLineNumberExclusive));
  }
  getFirstInvalidEndStateLineNumber() {
    return this.b.min;
  }
  getFirstInvalidEndStateLineNumberOrMax() {
    return this.getFirstInvalidEndStateLineNumber() || Number.MAX_SAFE_INTEGER;
  }
  allStatesValid() {
    return this.b.min === null;
  }
  getStartState(lineNumber, initialState) {
    if (lineNumber === 1) {
      return initialState;
    }
    return this.getEndState(lineNumber - 1);
  }
  getFirstInvalidLine(initialState) {
    const lineNumber = this.getFirstInvalidEndStateLineNumber();
    if (lineNumber === null) {
      return null;
    }
    const startState = this.getStartState(lineNumber, initialState);
    if (!startState) {
      throw new $vb("Start state must be defined");
    }
    return { lineNumber, startState };
  }
};
var $AI = class {
  constructor() {
    this.a = new $vI(null);
  }
  getEndState(lineNumber) {
    return this.a.get(lineNumber);
  }
  setEndState(lineNumber, state) {
    const oldState = this.a.get(lineNumber);
    if (oldState && oldState.equals(state)) {
      return false;
    }
    this.a.set(lineNumber, state);
    return true;
  }
  acceptChange(range, newLineCount) {
    let length = range.length;
    if (newLineCount > 0 && length > 0) {
      length--;
      newLineCount--;
    }
    this.a.replace(range.startLineNumber, length, newLineCount);
  }
  acceptChanges(changes) {
    for (const c of changes) {
      const [eolCount] = $tE(c.text);
      this.acceptChange(new $_C(c.range.startLineNumber, c.range.endLineNumber + 1), eolCount + 1);
    }
  }
};
var $BI = class {
  constructor() {
    this.a = [];
  }
  getRanges() {
    return this.a;
  }
  get min() {
    if (this.a.length === 0) {
      return null;
    }
    return this.a[0].start;
  }
  removeMin() {
    if (this.a.length === 0) {
      return null;
    }
    const range = this.a[0];
    if (range.start + 1 === range.endExclusive) {
      this.a.shift();
    } else {
      this.a[0] = new $0C(range.start + 1, range.endExclusive);
    }
    return range.start;
  }
  delete(value) {
    const idx = this.a.findIndex((r2) => r2.contains(value));
    if (idx !== -1) {
      const range = this.a[idx];
      if (range.start === value) {
        if (range.endExclusive === value + 1) {
          this.a.splice(idx, 1);
        } else {
          this.a[idx] = new $0C(value + 1, range.endExclusive);
        }
      } else {
        if (range.endExclusive === value + 1) {
          this.a[idx] = new $0C(range.start, value);
        } else {
          this.a.splice(idx, 1, new $0C(range.start, value), new $0C(value + 1, range.endExclusive));
        }
      }
    }
  }
  addRange(range) {
    $0C.addRange(range, this.a);
  }
  addRangeAndResize(range, newLength) {
    let idxFirstMightBeIntersecting = 0;
    while (!(idxFirstMightBeIntersecting >= this.a.length || range.start <= this.a[idxFirstMightBeIntersecting].endExclusive)) {
      idxFirstMightBeIntersecting++;
    }
    let idxFirstIsAfter = idxFirstMightBeIntersecting;
    while (!(idxFirstIsAfter >= this.a.length || range.endExclusive < this.a[idxFirstIsAfter].start)) {
      idxFirstIsAfter++;
    }
    const delta = newLength - range.length;
    for (let i2 = idxFirstIsAfter; i2 < this.a.length; i2++) {
      this.a[i2] = this.a[i2].delta(delta);
    }
    if (idxFirstMightBeIntersecting === idxFirstIsAfter) {
      const newRange = new $0C(range.start, range.start + newLength);
      if (!newRange.isEmpty) {
        this.a.splice(idxFirstMightBeIntersecting, 0, newRange);
      }
    } else {
      const start = Math.min(range.start, this.a[idxFirstMightBeIntersecting].start);
      const endEx = Math.max(range.endExclusive, this.a[idxFirstIsAfter - 1].endExclusive);
      const newRange = new $0C(start, endEx + delta);
      if (!newRange.isEmpty) {
        this.a.splice(idxFirstMightBeIntersecting, idxFirstIsAfter - idxFirstMightBeIntersecting, newRange);
      } else {
        this.a.splice(idxFirstMightBeIntersecting, idxFirstIsAfter - idxFirstMightBeIntersecting);
      }
    }
  }
  toString() {
    return this.a.map((r2) => r2.toString()).join(" + ");
  }
};
function safeTokenize(languageIdCodec, languageId, tokenizationSupport, text2, hasEOL, state) {
  let r2 = null;
  if (tokenizationSupport) {
    try {
      r2 = tokenizationSupport.tokenizeEncoded(text2, hasEOL, state.clone());
    } catch (e) {
      $gb(e);
    }
  }
  if (!r2) {
    r2 = $uI(languageIdCodec.encodeLanguageId(languageId), state);
  }
  $xE.convertToEndOffset(r2.tokens, text2.length);
  return r2;
}
var $CI = class {
  constructor(b, d) {
    this.b = b;
    this.d = d;
    this.a = false;
    this.f = false;
  }
  dispose() {
    this.a = true;
  }
  handleChanges() {
    this.g();
  }
  g() {
    if (this.f || !this.b._textModel.isAttachedToEditor() || !this.k()) {
      return;
    }
    this.f = true;
    $_h((deadline) => {
      this.f = false;
      this.h(deadline);
    });
  }
  /**
   * Tokenize until the deadline occurs, but try to yield every 1-2ms.
   */
  h(deadline) {
    const endTime = Date.now() + deadline.timeRemaining();
    const execute = () => {
      if (this.a || !this.b._textModel.isAttachedToEditor() || !this.k()) {
        return;
      }
      this.j();
      if (Date.now() < endTime) {
        $E(execute);
      } else {
        this.g();
      }
    };
    execute();
  }
  /**
   * Tokenize for at least 1ms.
   */
  j() {
    const lineCount = this.b._textModel.getLineCount();
    const builder = new $wI();
    const sw = $te.create(false);
    do {
      if (sw.elapsed() > 1) {
        break;
      }
      const tokenizedLineNumber = this.l(builder);
      if (tokenizedLineNumber >= lineCount) {
        break;
      }
    } while (this.k());
    this.d.setTokens(builder.finalize());
    this.checkFinished();
  }
  k() {
    if (!this.b) {
      return false;
    }
    return !this.b.store.allStatesValid();
  }
  l(builder) {
    const firstInvalidLine = this.b?.getFirstInvalidLine();
    if (!firstInvalidLine) {
      return this.b._textModel.getLineCount() + 1;
    }
    this.b.updateTokensUntilLine(builder, firstInvalidLine.lineNumber);
    return firstInvalidLine.lineNumber;
  }
  checkFinished() {
    if (this.a) {
      return;
    }
    if (this.b.store.allStatesValid()) {
      this.d.backgroundTokenizationFinished();
    }
  }
  requestTokens(startLineNumber, endLineNumberExclusive) {
    this.b.store.invalidateEndStateRange(new $_C(startLineNumber, endLineNumberExclusive));
  }
};

// out-build/vs/editor/common/model/tokens.js
var $DI = class {
  constructor() {
    this.c = new $ze();
    this.onDidChangeVisibleRanges = this.c.event;
    this.d = /* @__PURE__ */ new Set();
  }
  attachView() {
    const view = new AttachedViewImpl((state) => {
      this.c.fire({ view, state });
    });
    this.d.add(view);
    return view;
  }
  detachView(view) {
    this.d.delete(view);
    this.c.fire({ view, state: void 0 });
  }
};
var AttachedViewImpl = class {
  constructor(c) {
    this.c = c;
  }
  setVisibleLines(visibleLines, stabilized) {
    const visibleLineRanges = visibleLines.map((line) => new $_C(line.startLineNumber, line.endLineNumber + 1));
    this.c({ visibleLineRanges, stabilized });
  }
};
var $EI = class extends $3c {
  get lineRanges() {
    return this.g;
  }
  constructor(h3) {
    super();
    this.h = h3;
    this.c = this.B(new $8h(() => this.j(), 50));
    this.f = [];
    this.g = [];
  }
  j() {
    if ($zb(this.f, this.g, (a, b) => a.equals(b))) {
      return;
    }
    this.f = this.g;
    this.h();
  }
  handleStateChange(state) {
    this.g = state.visibleLineRanges;
    if (state.stabilized) {
      this.c.cancel();
      this.j();
    } else {
      this.c.schedule();
    }
  }
};
var $FI = class extends $3c {
  get backgroundTokenizationState() {
    return this.f;
  }
  constructor(j, m, n) {
    super();
    this.j = j;
    this.m = m;
    this.n = n;
    this.f = 1;
    this.g = this.B(new $ze());
    this.onDidChangeBackgroundTokenizationState = this.g.event;
    this.h = this.B(new $ze());
    this.onDidChangeTokens = this.h.event;
  }
  tokenizeIfCheap(lineNumber) {
    if (this.isCheapToTokenize(lineNumber)) {
      this.forceTokenization(lineNumber);
    }
  }
};

// out-build/vs/editor/common/model/treeSitterTokens.js
var $II = class extends $FI {
  constructor(t, languageIdCodec, textModel, languageId) {
    super(languageIdCodec, textModel, languageId);
    this.t = t;
    this.c = null;
    this.s = this.B(new $4c());
    this.u();
  }
  u() {
    const newLanguage = this.n();
    if (!this.c || this.r !== newLanguage) {
      this.r = newLanguage;
      this.c = $ZE.get(newLanguage);
      this.s.value = this.c?.onDidChangeTokens((e) => {
        if (e.textModel === this.m) {
          this.h.fire(e.changes);
        }
      });
    }
  }
  getLineTokens(lineNumber) {
    const content = this.m.getLineContent(lineNumber);
    if (this.c) {
      const rawTokens = this.c.tokenizeEncoded(lineNumber, this.m);
      if (rawTokens) {
        return new $xE(rawTokens, content, this.j);
      }
    }
    return $xE.createEmpty(content, this.j);
  }
  resetTokenization(fireTokenChangeEvent = true) {
    if (fireTokenChangeEvent) {
      this.h.fire({
        semanticTokensApplied: false,
        ranges: [
          {
            fromLineNumber: 1,
            toLineNumber: this.m.getLineCount()
          }
        ]
      });
    }
    this.u();
  }
  handleDidChangeAttached() {
  }
  handleDidChangeContent(e) {
    if (e.isFlush) {
      this.resetTokenization(false);
    }
  }
  forceTokenization(lineNumber) {
  }
  hasAccurateTokensForLine(lineNumber) {
    return true;
  }
  isCheapToTokenize(lineNumber) {
    return true;
  }
  getTokenTypeIfInsertingCharacter(lineNumber, column, character) {
    return 0;
  }
  tokenizeLineWithEdit(lineNumber, edit3) {
    return { mainLineTokens: null, additionalLines: null };
  }
  get hasTokens() {
    const hasTree = this.t.getParseResult(this.m) !== void 0;
    return hasTree;
  }
};

// out-build/vs/editor/common/services/treeSitterParserService.js
var $GI = "editor.experimental.preferTreeSitter";
var $HI = $Qk("treeSitterParserService");

// out-build/vs/editor/common/tokens/contiguousTokensStore.js
var $JI = class _$JI {
  constructor(languageIdCodec) {
    this.c = [];
    this.d = 0;
    this.e = languageIdCodec;
  }
  flush() {
    this.c = [];
    this.d = 0;
  }
  get hasTokens() {
    return this.c.length > 0;
  }
  getTokens(topLevelLanguageId, lineIndex, lineText) {
    let rawLineTokens = null;
    if (lineIndex < this.d) {
      rawLineTokens = this.c[lineIndex];
    }
    if (rawLineTokens !== null && rawLineTokens !== $zE) {
      return new $xE($BE(rawLineTokens), lineText, this.e);
    }
    const lineTokens = new Uint32Array(2);
    lineTokens[0] = lineText.length;
    lineTokens[1] = getDefaultMetadata(this.e.encodeLanguageId(topLevelLanguageId));
    return new $xE(lineTokens, lineText, this.e);
  }
  static f(topLevelLanguageId, lineTextLength, _tokens) {
    const tokens = _tokens ? $BE(_tokens) : null;
    if (lineTextLength === 0) {
      let hasDifferentLanguageId = false;
      if (tokens && tokens.length > 1) {
        hasDifferentLanguageId = $pE.getLanguageId(tokens[1]) !== topLevelLanguageId;
      }
      if (!hasDifferentLanguageId) {
        return $zE;
      }
    }
    if (!tokens || tokens.length === 0) {
      const tokens2 = new Uint32Array(2);
      tokens2[0] = lineTextLength;
      tokens2[1] = getDefaultMetadata(topLevelLanguageId);
      return tokens2.buffer;
    }
    tokens[tokens.length - 2] = lineTextLength;
    if (tokens.byteOffset === 0 && tokens.byteLength === tokens.buffer.byteLength) {
      return tokens.buffer;
    }
    return tokens;
  }
  g(lineIndex) {
    while (lineIndex >= this.d) {
      this.c[this.d] = null;
      this.d++;
    }
  }
  h(start, deleteCount) {
    if (deleteCount === 0) {
      return;
    }
    if (start + deleteCount > this.d) {
      deleteCount = this.d - start;
    }
    this.c.splice(start, deleteCount);
    this.d -= deleteCount;
  }
  j(insertIndex, insertCount) {
    if (insertCount === 0) {
      return;
    }
    const lineTokens = [];
    for (let i2 = 0; i2 < insertCount; i2++) {
      lineTokens[i2] = null;
    }
    this.c = $Yb(this.c, insertIndex, lineTokens);
    this.d += insertCount;
  }
  setTokens(topLevelLanguageId, lineIndex, lineTextLength, _tokens, checkEquality) {
    const tokens = _$JI.f(this.e.encodeLanguageId(topLevelLanguageId), lineTextLength, _tokens);
    this.g(lineIndex);
    const oldTokens = this.c[lineIndex];
    this.c[lineIndex] = tokens;
    if (checkEquality) {
      return !_$JI.k(oldTokens, tokens);
    }
    return false;
  }
  static k(_a5, _b2) {
    if (!_a5 || !_b2) {
      return !_a5 && !_b2;
    }
    const a = $BE(_a5);
    const b = $BE(_b2);
    if (a.length !== b.length) {
      return false;
    }
    for (let i2 = 0, len = a.length; i2 < len; i2++) {
      if (a[i2] !== b[i2]) {
        return false;
      }
    }
    return true;
  }
  //#region Editing
  acceptEdit(range, eolCount, firstLineLength) {
    this.l(range);
    this.m(new $8C(range.startLineNumber, range.startColumn), eolCount, firstLineLength);
  }
  l(range) {
    const firstLineIndex = range.startLineNumber - 1;
    if (firstLineIndex >= this.d) {
      return;
    }
    if (range.startLineNumber === range.endLineNumber) {
      if (range.startColumn === range.endColumn) {
        return;
      }
      this.c[firstLineIndex] = $AE.delete(this.c[firstLineIndex], range.startColumn - 1, range.endColumn - 1);
      return;
    }
    this.c[firstLineIndex] = $AE.deleteEnding(this.c[firstLineIndex], range.startColumn - 1);
    const lastLineIndex = range.endLineNumber - 1;
    let lastLineTokens = null;
    if (lastLineIndex < this.d) {
      lastLineTokens = $AE.deleteBeginning(this.c[lastLineIndex], range.endColumn - 1);
    }
    this.c[firstLineIndex] = $AE.append(this.c[firstLineIndex], lastLineTokens);
    this.h(range.startLineNumber, range.endLineNumber - range.startLineNumber);
  }
  m(position, eolCount, firstLineLength) {
    if (eolCount === 0 && firstLineLength === 0) {
      return;
    }
    const lineIndex = position.lineNumber - 1;
    if (lineIndex >= this.d) {
      return;
    }
    if (eolCount === 0) {
      this.c[lineIndex] = $AE.insert(this.c[lineIndex], position.column - 1, firstLineLength);
      return;
    }
    this.c[lineIndex] = $AE.deleteEnding(this.c[lineIndex], position.column - 1);
    this.c[lineIndex] = $AE.insert(this.c[lineIndex], position.column - 1, firstLineLength);
    this.j(position.lineNumber, eolCount);
  }
  //#endregion
  setMultilineTokens(tokens, textModel) {
    if (tokens.length === 0) {
      return { changes: [] };
    }
    const ranges = [];
    for (let i2 = 0, len = tokens.length; i2 < len; i2++) {
      const element = tokens[i2];
      let minChangedLineNumber = 0;
      let maxChangedLineNumber = 0;
      let hasChange = false;
      for (let lineNumber = element.startLineNumber; lineNumber <= element.endLineNumber; lineNumber++) {
        if (hasChange) {
          this.setTokens(textModel.getLanguageId(), lineNumber - 1, textModel.getLineLength(lineNumber), element.getLineTokens(lineNumber), false);
          maxChangedLineNumber = lineNumber;
        } else {
          const lineHasChange = this.setTokens(textModel.getLanguageId(), lineNumber - 1, textModel.getLineLength(lineNumber), element.getLineTokens(lineNumber), true);
          if (lineHasChange) {
            hasChange = true;
            minChangedLineNumber = lineNumber;
            maxChangedLineNumber = lineNumber;
          }
        }
      }
      if (hasChange) {
        ranges.push({ fromLineNumber: minChangedLineNumber, toLineNumber: maxChangedLineNumber });
      }
    }
    return { changes: ranges };
  }
};
function getDefaultMetadata(topLevelLanguageId) {
  return (topLevelLanguageId << 0 | 0 << 8 | 0 << 11 | 1 << 15 | 2 << 24 | 1024) >>> 0;
}

// out-build/vs/editor/common/tokens/sparseTokensStore.js
var $KI = class _$KI {
  constructor(languageIdCodec) {
    this.c = [];
    this.d = false;
    this.e = languageIdCodec;
  }
  flush() {
    this.c = [];
    this.d = false;
  }
  isEmpty() {
    return this.c.length === 0;
  }
  set(pieces, isComplete) {
    this.c = pieces || [];
    this.d = isComplete;
  }
  setPartial(_range, pieces) {
    let range = _range;
    if (pieces.length > 0) {
      const _firstRange = pieces[0].getRange();
      const _lastRange = pieces[pieces.length - 1].getRange();
      if (!_firstRange || !_lastRange) {
        return _range;
      }
      range = _range.plusRange(_firstRange).plusRange(_lastRange);
    }
    let insertPosition = null;
    for (let i2 = 0, len = this.c.length; i2 < len; i2++) {
      const piece = this.c[i2];
      if (piece.endLineNumber < range.startLineNumber) {
        continue;
      }
      if (piece.startLineNumber > range.endLineNumber) {
        insertPosition = insertPosition || { index: i2 };
        break;
      }
      piece.removeTokens(range);
      if (piece.isEmpty()) {
        this.c.splice(i2, 1);
        i2--;
        len--;
        continue;
      }
      if (piece.endLineNumber < range.startLineNumber) {
        continue;
      }
      if (piece.startLineNumber > range.endLineNumber) {
        insertPosition = insertPosition || { index: i2 };
        continue;
      }
      const [a, b] = piece.split(range);
      if (a.isEmpty()) {
        insertPosition = insertPosition || { index: i2 };
        continue;
      }
      if (b.isEmpty()) {
        continue;
      }
      this.c.splice(i2, 1, a, b);
      i2++;
      len++;
      insertPosition = insertPosition || { index: i2 };
    }
    insertPosition = insertPosition || { index: this.c.length };
    if (pieces.length > 0) {
      this.c = $Yb(this.c, insertPosition.index, pieces);
    }
    return range;
  }
  isComplete() {
    return this.d;
  }
  addSparseTokens(lineNumber, aTokens) {
    if (aTokens.getLineContent().length === 0) {
      return aTokens;
    }
    const pieces = this.c;
    if (pieces.length === 0) {
      return aTokens;
    }
    const pieceIndex = _$KI.f(pieces, lineNumber);
    const bTokens = pieces[pieceIndex].getLineTokens(lineNumber);
    if (!bTokens) {
      return aTokens;
    }
    const aLen = aTokens.getCount();
    const bLen = bTokens.getCount();
    let aIndex = 0;
    const result = [];
    let resultLen = 0;
    let lastEndOffset = 0;
    const emitToken = (endOffset, metadata) => {
      if (endOffset === lastEndOffset) {
        return;
      }
      lastEndOffset = endOffset;
      result[resultLen++] = endOffset;
      result[resultLen++] = metadata;
    };
    for (let bIndex = 0; bIndex < bLen; bIndex++) {
      const bStartCharacter = bTokens.getStartCharacter(bIndex);
      const bEndCharacter = bTokens.getEndCharacter(bIndex);
      const bMetadata = bTokens.getMetadata(bIndex);
      const bMask = ((bMetadata & 1 ? 2048 : 0) | (bMetadata & 2 ? 4096 : 0) | (bMetadata & 4 ? 8192 : 0) | (bMetadata & 8 ? 16384 : 0) | (bMetadata & 16 ? 16744448 : 0) | (bMetadata & 32 ? 4278190080 : 0)) >>> 0;
      const aMask = ~bMask >>> 0;
      while (aIndex < aLen && aTokens.getEndOffset(aIndex) <= bStartCharacter) {
        emitToken(aTokens.getEndOffset(aIndex), aTokens.getMetadata(aIndex));
        aIndex++;
      }
      if (aIndex < aLen && aTokens.getStartOffset(aIndex) < bStartCharacter) {
        emitToken(bStartCharacter, aTokens.getMetadata(aIndex));
      }
      while (aIndex < aLen && aTokens.getEndOffset(aIndex) < bEndCharacter) {
        emitToken(aTokens.getEndOffset(aIndex), aTokens.getMetadata(aIndex) & aMask | bMetadata & bMask);
        aIndex++;
      }
      if (aIndex < aLen) {
        emitToken(bEndCharacter, aTokens.getMetadata(aIndex) & aMask | bMetadata & bMask);
        if (aTokens.getEndOffset(aIndex) === bEndCharacter) {
          aIndex++;
        }
      } else {
        const aMergeIndex = Math.min(Math.max(0, aIndex - 1), aLen - 1);
        emitToken(bEndCharacter, aTokens.getMetadata(aMergeIndex) & aMask | bMetadata & bMask);
      }
    }
    while (aIndex < aLen) {
      emitToken(aTokens.getEndOffset(aIndex), aTokens.getMetadata(aIndex));
      aIndex++;
    }
    return new $xE(new Uint32Array(result), aTokens.getLineContent(), this.e);
  }
  static f(pieces, lineNumber) {
    let low = 0;
    let high = pieces.length - 1;
    while (low < high) {
      let mid = low + Math.floor((high - low) / 2);
      if (pieces[mid].endLineNumber < lineNumber) {
        low = mid + 1;
      } else if (pieces[mid].startLineNumber > lineNumber) {
        high = mid - 1;
      } else {
        while (mid > low && pieces[mid - 1].startLineNumber <= lineNumber && lineNumber <= pieces[mid - 1].endLineNumber) {
          mid--;
        }
        return mid;
      }
    }
    return low;
  }
  acceptEdit(range, eolCount, firstLineLength, lastLineLength, firstCharCode) {
    for (const piece of this.c) {
      piece.acceptEdit(range, eolCount, firstLineLength, lastLineLength, firstCharCode);
    }
  }
};

// out-build/vs/editor/common/model/tokenizationTextModelPart.js
var $LI_1;
var $LI = $LI_1 = class $LI2 extends $UH {
  constructor(t, u, w, y, z, C, D) {
    super();
    this.t = t;
    this.u = u;
    this.w = w;
    this.y = y;
    this.z = z;
    this.C = C;
    this.D = D;
    this.a = new $KI(this.z.languageIdCodec);
    this.h = this.B(new $ze());
    this.onDidChangeLanguage = this.h.event;
    this.j = this.B(new $ze());
    this.onDidChangeLanguageConfiguration = this.j.event;
    this.m = this.B(new $ze());
    this.onDidChangeTokens = this.m.event;
    this.r = this.B(new $2c());
    this.B(Event2.filter($ZE.onDidChange, (e) => e.changedLanguages.includes(this.w))(() => {
      this.I();
    }));
    this.I();
  }
  F() {
    return this.B(new GrammarTokens(this.z.languageIdCodec, this.t, () => this.w, this.y));
  }
  G() {
    return this.B(new $II(this.D, this.z.languageIdCodec, this.t, () => this.w));
  }
  H(useTreeSitter) {
    const needsReset = this.n !== void 0;
    this.n?.dispose();
    this.n = useTreeSitter ? this.G() : this.F();
    this.r.clear();
    this.r.add(this.n.onDidChangeTokens((e) => {
      this.J(e);
    }));
    this.r.add(this.n.onDidChangeBackgroundTokenizationState((e) => {
      this.u.handleDidChangeBackgroundTokenizationState();
    }));
    if (needsReset) {
      this.n.resetTokenization();
    }
  }
  I() {
    if ($ZE.get(this.w)) {
      if (!(this.n instanceof $II)) {
        this.H(true);
      }
    } else {
      if (!(this.n instanceof GrammarTokens)) {
        this.H(false);
      }
    }
  }
  _hasListeners() {
    return this.h.hasListeners() || this.j.hasListeners() || this.m.hasListeners();
  }
  handleLanguageConfigurationServiceChange(e) {
    if (e.affects(this.w)) {
      this.j.fire({});
    }
  }
  handleDidChangeContent(e) {
    if (e.isFlush) {
      this.a.flush();
    } else if (!e.isEolChange) {
      for (const c of e.changes) {
        const [eolCount, firstLineLength, lastLineLength] = $tE(c.text);
        this.a.acceptEdit(
          c.range,
          eolCount,
          firstLineLength,
          lastLineLength,
          c.text.length > 0 ? c.text.charCodeAt(0) : 0
          /* CharCode.Null */
        );
      }
    }
    this.n.handleDidChangeContent(e);
  }
  handleDidChangeAttached() {
    this.n.handleDidChangeAttached();
  }
  /**
   * Includes grammar and semantic tokens.
   */
  getLineTokens(lineNumber) {
    this.L(lineNumber);
    const syntacticTokens = this.n.getLineTokens(lineNumber);
    return this.a.addSparseTokens(lineNumber, syntacticTokens);
  }
  J(e) {
    if (!this.t._isDisposing()) {
      this.u.handleDidChangeTokens(e);
      this.m.fire(e);
    }
  }
  // #region Grammar Tokens
  L(lineNumber) {
    if (lineNumber < 1 || lineNumber > this.t.getLineCount()) {
      throw new $vb("Illegal value for lineNumber");
    }
  }
  get hasTokens() {
    return this.n.hasTokens;
  }
  resetTokenization() {
    this.n.resetTokenization();
  }
  get backgroundTokenizationState() {
    return this.n.backgroundTokenizationState;
  }
  forceTokenization(lineNumber) {
    this.L(lineNumber);
    this.n.forceTokenization(lineNumber);
  }
  hasAccurateTokensForLine(lineNumber) {
    this.L(lineNumber);
    return this.n.hasAccurateTokensForLine(lineNumber);
  }
  isCheapToTokenize(lineNumber) {
    this.L(lineNumber);
    return this.n.isCheapToTokenize(lineNumber);
  }
  tokenizeIfCheap(lineNumber) {
    this.L(lineNumber);
    this.n.tokenizeIfCheap(lineNumber);
  }
  getTokenTypeIfInsertingCharacter(lineNumber, column, character) {
    return this.n.getTokenTypeIfInsertingCharacter(lineNumber, column, character);
  }
  tokenizeLineWithEdit(lineNumber, edit3) {
    return this.n.tokenizeLineWithEdit(lineNumber, edit3);
  }
  // #endregion
  // #region Semantic Tokens
  setSemanticTokens(tokens, isComplete) {
    this.a.set(tokens, isComplete);
    this.J({
      semanticTokensApplied: tokens !== null,
      ranges: [{ fromLineNumber: 1, toLineNumber: this.t.getLineCount() }]
    });
  }
  hasCompleteSemanticTokens() {
    return this.a.isComplete();
  }
  hasSomeSemanticTokens() {
    return !this.a.isEmpty();
  }
  setPartialSemanticTokens(range, tokens) {
    if (this.hasCompleteSemanticTokens()) {
      return;
    }
    const changedRange = this.t.validateRange(this.a.setPartial(range, tokens));
    this.J({
      semanticTokensApplied: true,
      ranges: [
        {
          fromLineNumber: changedRange.startLineNumber,
          toLineNumber: changedRange.endLineNumber
        }
      ]
    });
  }
  // #endregion
  // #region Utility Methods
  getWordAtPosition(_position) {
    this.g();
    const position = this.t.validatePosition(_position);
    const lineContent = this.t.getLineContent(position.lineNumber);
    const lineTokens = this.getLineTokens(position.lineNumber);
    const tokenIndex = lineTokens.findTokenIndexAtOffset(position.column - 1);
    const [rbStartOffset, rbEndOffset] = $LI_1.N(lineTokens, tokenIndex);
    const rightBiasedWord = $MD(position.column, this.M(lineTokens.getLanguageId(tokenIndex)).getWordDefinition(), lineContent.substring(rbStartOffset, rbEndOffset), rbStartOffset);
    if (rightBiasedWord && rightBiasedWord.startColumn <= _position.column && _position.column <= rightBiasedWord.endColumn) {
      return rightBiasedWord;
    }
    if (tokenIndex > 0 && rbStartOffset === position.column - 1) {
      const [lbStartOffset, lbEndOffset] = $LI_1.N(lineTokens, tokenIndex - 1);
      const leftBiasedWord = $MD(position.column, this.M(lineTokens.getLanguageId(tokenIndex - 1)).getWordDefinition(), lineContent.substring(lbStartOffset, lbEndOffset), lbStartOffset);
      if (leftBiasedWord && leftBiasedWord.startColumn <= _position.column && _position.column <= leftBiasedWord.endColumn) {
        return leftBiasedWord;
      }
    }
    return null;
  }
  M(languageId) {
    return this.C.getLanguageConfiguration(languageId);
  }
  static N(lineTokens, tokenIndex) {
    const languageId = lineTokens.getLanguageId(tokenIndex);
    let startOffset = 0;
    for (let i2 = tokenIndex; i2 >= 0 && lineTokens.getLanguageId(i2) === languageId; i2--) {
      startOffset = lineTokens.getStartOffset(i2);
    }
    let endOffset = lineTokens.getLineContent().length;
    for (let i2 = tokenIndex, tokenCount = lineTokens.getCount(); i2 < tokenCount && lineTokens.getLanguageId(i2) === languageId; i2++) {
      endOffset = lineTokens.getEndOffset(i2);
    }
    return [startOffset, endOffset];
  }
  getWordUntilPosition(position) {
    const wordAtPosition = this.getWordAtPosition(position);
    if (!wordAtPosition) {
      return { word: "", startColumn: position.column, endColumn: position.column };
    }
    return {
      word: wordAtPosition.word.substr(0, position.column - wordAtPosition.startColumn),
      startColumn: wordAtPosition.startColumn,
      endColumn: position.column
    };
  }
  // #endregion
  // #region Language Id handling
  getLanguageId() {
    return this.w;
  }
  getLanguageIdAtPosition(lineNumber, column) {
    const position = this.t.validatePosition(new $8C(lineNumber, column));
    const lineTokens = this.getLineTokens(position.lineNumber);
    return lineTokens.getLanguageId(lineTokens.findTokenIndexAtOffset(position.column - 1));
  }
  setLanguageId(languageId, source = "api") {
    if (this.w === languageId) {
      return;
    }
    const e = {
      oldLanguage: this.w,
      newLanguage: languageId,
      source
    };
    this.w = languageId;
    this.u.handleDidChangeLanguage(e);
    this.n.resetTokenization();
    this.I();
    this.h.fire(e);
    this.j.fire({});
  }
};
$LI = $LI_1 = __decorate([
  __param(4, $1E),
  __param(5, $NF),
  __param(6, $HI)
], $LI);
var GrammarTokens = class extends $FI {
  constructor(languageIdCodec, textModel, getLanguageId, attachedViews) {
    super(languageIdCodec, textModel, getLanguageId);
    this.r = null;
    this.t = null;
    this.u = this.B(new $4c());
    this.w = new $JI(this.j);
    this.C = this.B(new $4c());
    this.D = this.B(new $_c());
    this.B($YE.onDidChange((e) => {
      const languageId = this.n();
      if (e.changedLanguages.indexOf(languageId) === -1) {
        return;
      }
      this.resetTokenization();
    }));
    this.resetTokenization();
    this.B(attachedViews.onDidChangeVisibleRanges(({ view, state }) => {
      if (state) {
        let existing = this.D.get(view);
        if (!existing) {
          existing = new $EI(() => this.H(existing.lineRanges));
          this.D.set(view, existing);
        }
        existing.handleStateChange(state);
      } else {
        this.D.deleteAndDispose(view);
      }
    }));
  }
  resetTokenization(fireTokenChangeEvent = true) {
    this.w.flush();
    this.y?.flush();
    if (this.z) {
      this.z = new $zI(this.m.getLineCount());
    }
    if (fireTokenChangeEvent) {
      this.h.fire({
        semanticTokensApplied: false,
        ranges: [
          {
            fromLineNumber: 1,
            toLineNumber: this.m.getLineCount()
          }
        ]
      });
    }
    const initializeTokenization = () => {
      if (this.m.isTooLargeForTokenization()) {
        return [null, null];
      }
      const tokenizationSupport2 = $YE.get(this.n());
      if (!tokenizationSupport2) {
        return [null, null];
      }
      let initialState2;
      try {
        initialState2 = tokenizationSupport2.getInitialState();
      } catch (e) {
        $gb(e);
        return [null, null];
      }
      return [tokenizationSupport2, initialState2];
    };
    const [tokenizationSupport, initialState] = initializeTokenization();
    if (tokenizationSupport && initialState) {
      this.r = new $yI(this.m.getLineCount(), tokenizationSupport, this.m, this.j);
    } else {
      this.r = null;
    }
    this.u.clear();
    this.t = null;
    if (this.r) {
      const b = {
        setTokens: (tokens) => {
          this.F(tokens);
        },
        backgroundTokenizationFinished: () => {
          if (this.f === 2) {
            return;
          }
          const newState = 2;
          this.f = newState;
          this.g.fire();
        },
        setEndState: (lineNumber, state) => {
          if (!this.r) {
            return;
          }
          const firstInvalidEndStateLineNumber = this.r.store.getFirstInvalidEndStateLineNumber();
          if (firstInvalidEndStateLineNumber !== null && lineNumber >= firstInvalidEndStateLineNumber) {
            this.r?.store.setEndState(lineNumber, state);
          }
        }
      };
      if (tokenizationSupport && tokenizationSupport.createBackgroundTokenizer && !tokenizationSupport.backgroundTokenizerShouldOnlyVerifyTokens) {
        this.u.value = tokenizationSupport.createBackgroundTokenizer(this.m, b);
      }
      if (!this.u.value && !this.m.isTooLargeForTokenization()) {
        this.u.value = this.t = new $CI(this.r, b);
        this.t.handleChanges();
      }
      if (tokenizationSupport?.backgroundTokenizerShouldOnlyVerifyTokens && tokenizationSupport.createBackgroundTokenizer) {
        this.y = new $JI(this.j);
        this.z = new $zI(this.m.getLineCount());
        this.C.clear();
        this.C.value = tokenizationSupport.createBackgroundTokenizer(this.m, {
          setTokens: (tokens) => {
            this.y?.setMultilineTokens(tokens, this.m);
          },
          backgroundTokenizationFinished() {
          },
          setEndState: (lineNumber, state) => {
            this.z?.setEndState(lineNumber, state);
          }
        });
      } else {
        this.y = void 0;
        this.z = void 0;
        this.C.value = void 0;
      }
    }
    this.G();
  }
  handleDidChangeAttached() {
    this.t?.handleChanges();
  }
  handleDidChangeContent(e) {
    if (e.isFlush) {
      this.resetTokenization(false);
    } else if (!e.isEolChange) {
      for (const c of e.changes) {
        const [eolCount, firstLineLength] = $tE(c.text);
        this.w.acceptEdit(c.range, eolCount, firstLineLength);
        this.y?.acceptEdit(c.range, eolCount, firstLineLength);
      }
      this.z?.acceptChanges(e.changes);
      if (this.r) {
        this.r.store.acceptChanges(e.changes);
      }
      this.t?.handleChanges();
    }
  }
  F(tokens) {
    const { changes } = this.w.setMultilineTokens(tokens, this.m);
    if (changes.length > 0) {
      this.h.fire({ semanticTokensApplied: false, ranges: changes });
    }
    return { changes };
  }
  G() {
    const ranges = $_C.joinMany([...this.D].map(([_, s]) => s.lineRanges));
    this.H(ranges);
  }
  H(ranges) {
    for (const range of ranges) {
      this.I(range.startLineNumber, range.endLineNumberExclusive - 1);
    }
  }
  I(startLineNumber, endLineNumber) {
    if (!this.r) {
      return;
    }
    startLineNumber = Math.max(1, Math.min(this.m.getLineCount(), startLineNumber));
    endLineNumber = Math.min(this.m.getLineCount(), endLineNumber);
    const builder = new $wI();
    const { heuristicTokens } = this.r.tokenizeHeuristically(builder, startLineNumber, endLineNumber);
    const changedTokens = this.F(builder.finalize());
    if (heuristicTokens) {
      for (const c of changedTokens.changes) {
        this.u.value?.requestTokens(c.fromLineNumber, c.toLineNumber + 1);
      }
    }
    this.t?.checkFinished();
  }
  forceTokenization(lineNumber) {
    const builder = new $wI();
    this.r?.updateTokensUntilLine(builder, lineNumber);
    this.F(builder.finalize());
    this.t?.checkFinished();
  }
  hasAccurateTokensForLine(lineNumber) {
    if (!this.r) {
      return true;
    }
    return this.r.hasAccurateTokensForLine(lineNumber);
  }
  isCheapToTokenize(lineNumber) {
    if (!this.r) {
      return true;
    }
    return this.r.isCheapToTokenize(lineNumber);
  }
  getLineTokens(lineNumber) {
    const lineText = this.m.getLineContent(lineNumber);
    const result = this.w.getTokens(this.m.getLanguageId(), lineNumber - 1, lineText);
    if (this.y && this.z && this.r) {
      if (this.z.getFirstInvalidEndStateLineNumberOrMax() > lineNumber && this.r.store.getFirstInvalidEndStateLineNumberOrMax() > lineNumber) {
        const backgroundResult = this.y.getTokens(this.m.getLanguageId(), lineNumber - 1, lineText);
        if (!result.equals(backgroundResult) && this.C.value?.reportMismatchingTokens) {
          this.C.value.reportMismatchingTokens(lineNumber);
        }
      }
    }
    return result;
  }
  getTokenTypeIfInsertingCharacter(lineNumber, column, character) {
    if (!this.r) {
      return 0;
    }
    const position = this.m.validatePosition(new $8C(lineNumber, column));
    this.forceTokenization(position.lineNumber);
    return this.r.getTokenTypeIfInsertingCharacter(position, character);
  }
  tokenizeLineWithEdit(lineNumber, edit3) {
    if (!this.r) {
      return { mainLineTokens: null, additionalLines: null };
    }
    this.forceTokenization(lineNumber);
    return this.r.tokenizeLineWithEdit(lineNumber, edit3);
  }
  get hasTokens() {
    return this.w.hasTokens;
  }
};

// out-build/vs/platform/undoRedo/common/undoRedo.js
var $_F = $Qk("undoRedoService");
var UndoRedoElementType;
(function(UndoRedoElementType2) {
  UndoRedoElementType2[UndoRedoElementType2["Resource"] = 0] = "Resource";
  UndoRedoElementType2[UndoRedoElementType2["Workspace"] = 1] = "Workspace";
})(UndoRedoElementType || (UndoRedoElementType = {}));
var $aG = class {
  constructor(resource, elements) {
    this.resource = resource;
    this.elements = elements;
  }
};
var $bG = class _$bG {
  static {
    this.a = 0;
  }
  constructor() {
    this.id = _$bG.a++;
    this.b = 1;
  }
  nextOrder() {
    if (this.id === 0) {
      return 0;
    }
    return this.b++;
  }
  static {
    this.None = new _$bG();
  }
};
var $cG = class _$cG {
  static {
    this.a = 0;
  }
  constructor() {
    this.id = _$cG.a++;
    this.b = 1;
  }
  nextOrder() {
    if (this.id === 0) {
      return 0;
    }
    return this.b++;
  }
  static {
    this.None = new _$cG();
  }
};

// out-build/vs/editor/common/model/textModel.js
var $QI_1;
function $MI(text2) {
  const builder = new $rI();
  builder.acceptChunk(text2);
  return builder.finish();
}
function $NI(stream) {
  return new Promise((resolve, reject) => {
    const builder = new $rI();
    let done = false;
    $ui(stream, {
      onData: (chunk) => {
        builder.acceptChunk(typeof chunk === "string" ? chunk : chunk.toString());
      },
      onError: (error) => {
        if (!done) {
          done = true;
          reject(error);
        }
      },
      onEnd: () => {
        if (!done) {
          done = true;
          resolve(builder.finish());
        }
      }
    });
  });
}
function $OI(snapshot) {
  const builder = new $rI();
  let chunk;
  while (typeof (chunk = snapshot.read()) === "string") {
    builder.acceptChunk(chunk);
  }
  return builder.finish();
}
function $PI(value, defaultEOL) {
  let factory;
  if (typeof value === "string") {
    factory = $MI(value);
  } else if ($fG(value)) {
    factory = $OI(value);
  } else {
    factory = value;
  }
  return factory.create(defaultEOL);
}
var MODEL_ID = 0;
var LIMIT_FIND_COUNT2 = 999;
var LONG_LINE_BOUNDARY = 1e4;
var TextModelSnapshot = class {
  constructor(source) {
    this.a = source;
    this.b = false;
  }
  read() {
    if (this.b) {
      return null;
    }
    const result = [];
    let resultCnt = 0;
    let resultLength = 0;
    do {
      const tmp = this.a.read();
      if (tmp === null) {
        this.b = true;
        if (resultCnt === 0) {
          return null;
        } else {
          return result.join("");
        }
      }
      if (tmp.length > 0) {
        result[resultCnt++] = tmp;
        resultLength += tmp.length;
      }
      if (resultLength >= 64 * 1024) {
        return result.join("");
      }
    } while (true);
  }
};
var invalidFunc2 = () => {
  throw new Error(`Invalid change accessor`);
};
var StringOffsetValidationType;
(function(StringOffsetValidationType2) {
  StringOffsetValidationType2[StringOffsetValidationType2["Relaxed"] = 0] = "Relaxed";
  StringOffsetValidationType2[StringOffsetValidationType2["SurrogatePairs"] = 1] = "SurrogatePairs";
})(StringOffsetValidationType || (StringOffsetValidationType = {}));
var $QI = class $QI2 extends $3c {
  static {
    $QI_1 = this;
  }
  static {
    this._MODEL_SYNC_LIMIT = 50 * 1024 * 1024;
  }
  static {
    this.a = 20 * 1024 * 1024;
  }
  static {
    this.b = 300 * 1e3;
  }
  static {
    this.f = 256 * 1024 * 1024;
  }
  static {
    this.DEFAULT_CREATION_OPTIONS = {
      isForSimpleWidget: false,
      tabSize: $HD.tabSize,
      indentSize: $HD.indentSize,
      insertSpaces: $HD.insertSpaces,
      detectIndentation: false,
      defaultEOL: 1,
      trimAutoWhitespace: $HD.trimAutoWhitespace,
      largeFileOptimizations: $HD.largeFileOptimizations,
      bracketPairColorizationOptions: $HD.bracketPairColorizationOptions
    };
  }
  static resolveOptions(textBuffer, options3) {
    if (options3.detectIndentation) {
      const guessedIndentation = $YH(textBuffer, options3.tabSize, options3.insertSpaces);
      return new $dG({
        tabSize: guessedIndentation.tabSize,
        indentSize: "tabSize",
        // TODO@Alex: guess indentSize independent of tabSize
        insertSpaces: guessedIndentation.insertSpaces,
        trimAutoWhitespace: options3.trimAutoWhitespace,
        defaultEOL: options3.defaultEOL,
        bracketPairColorizationOptions: options3.bracketPairColorizationOptions
      });
    }
    return new $dG(options3);
  }
  get onDidChangeLanguage() {
    return this.bb.onDidChangeLanguage;
  }
  get onDidChangeLanguageConfiguration() {
    return this.bb.onDidChangeLanguageConfiguration;
  }
  get onDidChangeTokens() {
    return this.bb.onDidChangeTokens;
  }
  onDidChangeContent(listener) {
    return this.w.slowEvent((e) => listener(e.contentChangedEvent));
  }
  onDidChangeContentOrInjectedText(listener) {
    return $Zc(this.w.fastEvent((e) => listener(e)), this.u.event((e) => listener(e)));
  }
  _isDisposing() {
    return this.I;
  }
  get tokenization() {
    return this.bb;
  }
  get bracketPairs() {
    return this.cb;
  }
  get guides() {
    return this.db;
  }
  constructor(source, languageIdOrSelection, creationOptions, associatedResource = null, fb, gb, hb, ib) {
    super();
    this.fb = fb;
    this.gb = gb;
    this.hb = hb;
    this.ib = ib;
    this.g = this.B(new $ze());
    this.onWillDispose = this.g.event;
    this.h = this.B(new DidChangeDecorationsEmitter((affectedInjectedTextLines) => this.zb(affectedInjectedTextLines)));
    this.onDidChangeDecorations = this.h.event;
    this.n = this.B(new $ze());
    this.onDidChangeOptions = this.n.event;
    this.s = this.B(new $ze());
    this.onDidChangeAttached = this.s.event;
    this.u = this.B(new $ze());
    this.w = this.B(new DidChangeContentEmitter());
    this.G = this.B(new $4c());
    this.X = 0;
    this.eb = new $DI();
    MODEL_ID++;
    this.id = "$model" + MODEL_ID;
    this.isForSimpleWidget = creationOptions.isForSimpleWidget;
    if (typeof associatedResource === "undefined" || associatedResource === null) {
      this.y = URI.parse("inmemory://model/" + MODEL_ID);
    } else {
      this.y = associatedResource;
    }
    this.z = 0;
    const { textBuffer, disposable } = $PI(source, creationOptions.defaultEOL);
    this.C = textBuffer;
    this.D = disposable;
    this.F = $QI_1.resolveOptions(this.C, creationOptions);
    const languageId = typeof languageIdOrSelection === "string" ? languageIdOrSelection : languageIdOrSelection.languageId;
    if (typeof languageIdOrSelection !== "string") {
      this.G.value = languageIdOrSelection.onDidChange(() => this.Gb(languageIdOrSelection.languageId));
    }
    this.cb = this.B(new $KG(this, this.hb));
    this.db = this.B(new $WH(this, this.hb));
    this.ab = this.B(new $OH(this));
    this.bb = this.ib.createInstance($LI, this, this.cb, languageId, this.eb);
    const bufferLineCount = this.C.getLineCount();
    const bufferTextLength = this.C.getValueLengthInRange(
      new $9C(1, 1, bufferLineCount, this.C.getLineLength(bufferLineCount) + 1),
      0
      /* model.EndOfLinePreference.TextDefined */
    );
    if (creationOptions.largeFileOptimizations) {
      this.O = bufferTextLength > $QI_1.a || bufferLineCount > $QI_1.b;
      this.P = bufferTextLength > $QI_1.f;
    } else {
      this.O = false;
      this.P = false;
    }
    this.N = bufferTextLength > $QI_1._MODEL_SYNC_LIMIT;
    this.J = 1;
    this.L = 1;
    this.M = null;
    this.H = false;
    this.I = false;
    this.W = $tg(MODEL_ID);
    this.Y = 0;
    this.Z = /* @__PURE__ */ Object.create(null);
    this.$ = new DecorationsTrees();
    this.Q = new $TH(this, this.fb);
    this.R = false;
    this.S = false;
    this.U = null;
    this.B(this.ab.onDidChange(() => {
      this.h.beginDeferredEmit();
      this.h.fire();
      this.h.endDeferredEmit();
    }));
    this.gb.requestRichLanguageFeatures(languageId);
    this.B(this.hb.onDidChange((e) => {
      this.cb.handleLanguageConfigurationServiceChange(e);
      this.bb.handleLanguageConfigurationServiceChange(e);
    }));
  }
  dispose() {
    this.I = true;
    this.g.fire();
    this.bb.dispose();
    this.H = true;
    super.dispose();
    this.D.dispose();
    this.I = false;
    const emptyDisposedTextBuffer = new $qI([], "", "\n", false, false, true, true);
    emptyDisposedTextBuffer.dispose();
    this.C = emptyDisposedTextBuffer;
    this.D = $3c.None;
  }
  _hasListeners() {
    return this.g.hasListeners() || this.h.hasListeners() || this.bb._hasListeners() || this.n.hasListeners() || this.s.hasListeners() || this.u.hasListeners() || this.w.hasListeners();
  }
  jb() {
    if (this.H) {
      throw new $vb("Model is disposed!");
    }
  }
  equalsTextBuffer(other) {
    this.jb();
    return this.C.equals(other);
  }
  getTextBuffer() {
    this.jb();
    return this.C;
  }
  kb(rawChange, change) {
    if (this.I) {
      return;
    }
    this.bb.handleDidChangeContent(change);
    this.cb.handleDidChangeContent(change);
    this.w.fire(new $ME(rawChange, change));
  }
  setValue(value) {
    this.jb();
    if (value === null || value === void 0) {
      throw $nb();
    }
    const { textBuffer, disposable } = $PI(value, this.F.defaultEOL);
    this.mb(textBuffer, disposable);
  }
  lb(range, rangeOffset, rangeLength, text2, isUndoing, isRedoing, isFlush, isEolChange) {
    return {
      changes: [{
        range,
        rangeOffset,
        rangeLength,
        text: text2
      }],
      eol: this.C.getEOL(),
      isEolChange,
      versionId: this.getVersionId(),
      isUndoing,
      isRedoing,
      isFlush
    };
  }
  mb(textBuffer, textBufferDisposable) {
    this.jb();
    const oldFullModelRange = this.getFullModelRange();
    const oldModelValueLength = this.getValueLengthInRange(oldFullModelRange);
    const endLineNumber = this.getLineCount();
    const endColumn = this.getLineMaxColumn(endLineNumber);
    this.C = textBuffer;
    this.D.dispose();
    this.D = textBufferDisposable;
    this.pb();
    this.Z = /* @__PURE__ */ Object.create(null);
    this.$ = new DecorationsTrees();
    this.Q.clear();
    this.U = null;
    this.kb(new $KE([
      new $EE()
    ], this.J, false, false), this.lb(new $9C(1, 1, endLineNumber, endColumn), 0, oldModelValueLength, this.getValue(), false, false, true, false));
  }
  setEOL(eol) {
    this.jb();
    const newEOL = eol === 1 ? "\r\n" : "\n";
    if (this.C.getEOL() === newEOL) {
      return;
    }
    const oldFullModelRange = this.getFullModelRange();
    const oldModelValueLength = this.getValueLengthInRange(oldFullModelRange);
    const endLineNumber = this.getLineCount();
    const endColumn = this.getLineMaxColumn(endLineNumber);
    this.nb();
    this.C.setEOL(newEOL);
    this.pb();
    this.ob();
    this.kb(new $KE([
      new $JE()
    ], this.J, false, false), this.lb(new $9C(1, 1, endLineNumber, endColumn), 0, oldModelValueLength, this.getValue(), false, false, false, true));
  }
  nb() {
    this.$.ensureAllNodesHaveRanges(this);
  }
  ob() {
    const versionId = this.getVersionId();
    const allDecorations = this.$.collectNodesPostOrder();
    for (let i2 = 0, len = allDecorations.length; i2 < len; i2++) {
      const node = allDecorations[i2];
      const range = node.range;
      const delta = node.cachedAbsoluteStart - node.start;
      const startOffset = this.C.getOffsetAt(range.startLineNumber, range.startColumn);
      const endOffset = this.C.getOffsetAt(range.endLineNumber, range.endColumn);
      node.cachedAbsoluteStart = startOffset;
      node.cachedAbsoluteEnd = endOffset;
      node.cachedVersionId = versionId;
      node.start = startOffset - delta;
      node.end = endOffset - delta;
      $6H(node);
    }
  }
  onBeforeAttached() {
    this.z++;
    if (this.z === 1) {
      this.bb.handleDidChangeAttached();
      this.s.fire(void 0);
    }
    return this.eb.attachView();
  }
  onBeforeDetached(view) {
    this.z--;
    if (this.z === 0) {
      this.bb.handleDidChangeAttached();
      this.s.fire(void 0);
    }
    this.eb.detachView(view);
  }
  isAttachedToEditor() {
    return this.z > 0;
  }
  getAttachedEditorCount() {
    return this.z;
  }
  isTooLargeForSyncing() {
    return this.N;
  }
  isTooLargeForTokenization() {
    return this.O;
  }
  isTooLargeForHeapOperation() {
    return this.P;
  }
  isDisposed() {
    return this.H;
  }
  isDominatedByLongLines() {
    this.jb();
    if (this.isTooLargeForTokenization()) {
      return false;
    }
    let smallLineCharCount = 0;
    let longLineCharCount = 0;
    const lineCount = this.C.getLineCount();
    for (let lineNumber = 1; lineNumber <= lineCount; lineNumber++) {
      const lineLength = this.C.getLineLength(lineNumber);
      if (lineLength >= LONG_LINE_BOUNDARY) {
        longLineCharCount += lineLength;
      } else {
        smallLineCharCount += lineLength;
      }
    }
    return longLineCharCount > smallLineCharCount;
  }
  get uri() {
    return this.y;
  }
  //#region Options
  getOptions() {
    this.jb();
    return this.F;
  }
  getFormattingOptions() {
    return {
      tabSize: this.F.indentSize,
      insertSpaces: this.F.insertSpaces
    };
  }
  updateOptions(_newOpts) {
    this.jb();
    const tabSize = typeof _newOpts.tabSize !== "undefined" ? _newOpts.tabSize : this.F.tabSize;
    const indentSize = typeof _newOpts.indentSize !== "undefined" ? _newOpts.indentSize : this.F.originalIndentSize;
    const insertSpaces = typeof _newOpts.insertSpaces !== "undefined" ? _newOpts.insertSpaces : this.F.insertSpaces;
    const trimAutoWhitespace = typeof _newOpts.trimAutoWhitespace !== "undefined" ? _newOpts.trimAutoWhitespace : this.F.trimAutoWhitespace;
    const bracketPairColorizationOptions = typeof _newOpts.bracketColorizationOptions !== "undefined" ? _newOpts.bracketColorizationOptions : this.F.bracketPairColorizationOptions;
    const newOpts = new $dG({
      tabSize,
      indentSize,
      insertSpaces,
      defaultEOL: this.F.defaultEOL,
      trimAutoWhitespace,
      bracketPairColorizationOptions
    });
    if (this.F.equals(newOpts)) {
      return;
    }
    const e = this.F.createChangeEvent(newOpts);
    this.F = newOpts;
    this.cb.handleDidChangeOptions(e);
    this.ab.handleDidChangeOptions(e);
    this.n.fire(e);
  }
  detectIndentation(defaultInsertSpaces, defaultTabSize) {
    this.jb();
    const guessedIndentation = $YH(this.C, defaultTabSize, defaultInsertSpaces);
    this.updateOptions({
      insertSpaces: guessedIndentation.insertSpaces,
      tabSize: guessedIndentation.tabSize,
      indentSize: guessedIndentation.tabSize
      // TODO@Alex: guess indentSize independent of tabSize
    });
  }
  normalizeIndentation(str) {
    this.jb();
    return $BG(str, this.F.indentSize, this.F.insertSpaces);
  }
  //#endregion
  //#region Reading
  getVersionId() {
    this.jb();
    return this.J;
  }
  mightContainRTL() {
    return this.C.mightContainRTL();
  }
  mightContainUnusualLineTerminators() {
    return this.C.mightContainUnusualLineTerminators();
  }
  removeUnusualLineTerminators(selections = null) {
    const matches = this.findMatches(
      $eg.source,
      false,
      true,
      false,
      null,
      false,
      1073741824
      /* Constants.MAX_SAFE_SMALL_INTEGER */
    );
    this.C.resetMightContainUnusualLineTerminators();
    this.pushEditOperations(selections, matches.map((m) => ({ range: m.range, text: null })), () => null);
  }
  mightContainNonBasicASCII() {
    return this.C.mightContainNonBasicASCII();
  }
  getAlternativeVersionId() {
    this.jb();
    return this.L;
  }
  getInitialUndoRedoSnapshot() {
    this.jb();
    return this.M;
  }
  getOffsetAt(rawPosition) {
    this.jb();
    const position = this.rb(
      rawPosition.lineNumber,
      rawPosition.column,
      0
      /* StringOffsetValidationType.Relaxed */
    );
    return this.C.getOffsetAt(position.lineNumber, position.column);
  }
  getPositionAt(rawOffset) {
    this.jb();
    const offset = Math.min(this.C.getLength(), Math.max(0, rawOffset));
    return this.C.getPositionAt(offset);
  }
  pb() {
    this.J = this.J + 1;
    this.L = this.J;
  }
  _overwriteVersionId(versionId) {
    this.J = versionId;
  }
  _overwriteAlternativeVersionId(newAlternativeVersionId) {
    this.L = newAlternativeVersionId;
  }
  _overwriteInitialUndoRedoSnapshot(newInitialUndoRedoSnapshot) {
    this.M = newInitialUndoRedoSnapshot;
  }
  getValue(eol, preserveBOM = false) {
    this.jb();
    if (this.isTooLargeForHeapOperation()) {
      throw new $vb("Operation would exceed heap memory limits");
    }
    const fullModelRange = this.getFullModelRange();
    const fullModelValue = this.getValueInRange(fullModelRange, eol);
    if (preserveBOM) {
      return this.C.getBOM() + fullModelValue;
    }
    return fullModelValue;
  }
  createSnapshot(preserveBOM = false) {
    return new TextModelSnapshot(this.C.createSnapshot(preserveBOM));
  }
  getValueLength(eol, preserveBOM = false) {
    this.jb();
    const fullModelRange = this.getFullModelRange();
    const fullModelValue = this.getValueLengthInRange(fullModelRange, eol);
    if (preserveBOM) {
      return this.C.getBOM().length + fullModelValue;
    }
    return fullModelValue;
  }
  getValueInRange(rawRange, eol = 0) {
    this.jb();
    return this.C.getValueInRange(this.validateRange(rawRange), eol);
  }
  getValueLengthInRange(rawRange, eol = 0) {
    this.jb();
    return this.C.getValueLengthInRange(this.validateRange(rawRange), eol);
  }
  getCharacterCountInRange(rawRange, eol = 0) {
    this.jb();
    return this.C.getCharacterCountInRange(this.validateRange(rawRange), eol);
  }
  getLineCount() {
    this.jb();
    return this.C.getLineCount();
  }
  getLineContent(lineNumber) {
    this.jb();
    if (lineNumber < 1 || lineNumber > this.getLineCount()) {
      throw new $vb("Illegal value for lineNumber");
    }
    return this.C.getLineContent(lineNumber);
  }
  getLineLength(lineNumber) {
    this.jb();
    if (lineNumber < 1 || lineNumber > this.getLineCount()) {
      throw new $vb("Illegal value for lineNumber");
    }
    return this.C.getLineLength(lineNumber);
  }
  getLinesContent() {
    this.jb();
    if (this.isTooLargeForHeapOperation()) {
      throw new $vb("Operation would exceed heap memory limits");
    }
    return this.C.getLinesContent();
  }
  getEOL() {
    this.jb();
    return this.C.getEOL();
  }
  getEndOfLineSequence() {
    this.jb();
    return this.C.getEOL() === "\n" ? 0 : 1;
  }
  getLineMinColumn(lineNumber) {
    this.jb();
    return 1;
  }
  getLineMaxColumn(lineNumber) {
    this.jb();
    if (lineNumber < 1 || lineNumber > this.getLineCount()) {
      throw new $vb("Illegal value for lineNumber");
    }
    return this.C.getLineLength(lineNumber) + 1;
  }
  getLineFirstNonWhitespaceColumn(lineNumber) {
    this.jb();
    if (lineNumber < 1 || lineNumber > this.getLineCount()) {
      throw new $vb("Illegal value for lineNumber");
    }
    return this.C.getLineFirstNonWhitespaceColumn(lineNumber);
  }
  getLineLastNonWhitespaceColumn(lineNumber) {
    this.jb();
    if (lineNumber < 1 || lineNumber > this.getLineCount()) {
      throw new $vb("Illegal value for lineNumber");
    }
    return this.C.getLineLastNonWhitespaceColumn(lineNumber);
  }
  /**
   * Validates `range` is within buffer bounds, but allows it to sit in between surrogate pairs, etc.
   * Will try to not allocate if possible.
   */
  _validateRangeRelaxedNoAllocations(range) {
    const linesCount = this.C.getLineCount();
    const initialStartLineNumber = range.startLineNumber;
    const initialStartColumn = range.startColumn;
    let startLineNumber = Math.floor(typeof initialStartLineNumber === "number" && !isNaN(initialStartLineNumber) ? initialStartLineNumber : 1);
    let startColumn = Math.floor(typeof initialStartColumn === "number" && !isNaN(initialStartColumn) ? initialStartColumn : 1);
    if (startLineNumber < 1) {
      startLineNumber = 1;
      startColumn = 1;
    } else if (startLineNumber > linesCount) {
      startLineNumber = linesCount;
      startColumn = this.getLineMaxColumn(startLineNumber);
    } else {
      if (startColumn <= 1) {
        startColumn = 1;
      } else {
        const maxColumn = this.getLineMaxColumn(startLineNumber);
        if (startColumn >= maxColumn) {
          startColumn = maxColumn;
        }
      }
    }
    const initialEndLineNumber = range.endLineNumber;
    const initialEndColumn = range.endColumn;
    let endLineNumber = Math.floor(typeof initialEndLineNumber === "number" && !isNaN(initialEndLineNumber) ? initialEndLineNumber : 1);
    let endColumn = Math.floor(typeof initialEndColumn === "number" && !isNaN(initialEndColumn) ? initialEndColumn : 1);
    if (endLineNumber < 1) {
      endLineNumber = 1;
      endColumn = 1;
    } else if (endLineNumber > linesCount) {
      endLineNumber = linesCount;
      endColumn = this.getLineMaxColumn(endLineNumber);
    } else {
      if (endColumn <= 1) {
        endColumn = 1;
      } else {
        const maxColumn = this.getLineMaxColumn(endLineNumber);
        if (endColumn >= maxColumn) {
          endColumn = maxColumn;
        }
      }
    }
    if (initialStartLineNumber === startLineNumber && initialStartColumn === startColumn && initialEndLineNumber === endLineNumber && initialEndColumn === endColumn && range instanceof $9C && !(range instanceof $_D)) {
      return range;
    }
    return new $9C(startLineNumber, startColumn, endLineNumber, endColumn);
  }
  qb(lineNumber, column, validationType) {
    if (typeof lineNumber !== "number" || typeof column !== "number") {
      return false;
    }
    if (isNaN(lineNumber) || isNaN(column)) {
      return false;
    }
    if (lineNumber < 1 || column < 1) {
      return false;
    }
    if ((lineNumber | 0) !== lineNumber || (column | 0) !== column) {
      return false;
    }
    const lineCount = this.C.getLineCount();
    if (lineNumber > lineCount) {
      return false;
    }
    if (column === 1) {
      return true;
    }
    const maxColumn = this.getLineMaxColumn(lineNumber);
    if (column > maxColumn) {
      return false;
    }
    if (validationType === 1) {
      const charCodeBefore = this.C.getLineCharCode(lineNumber, column - 2);
      if ($5f(charCodeBefore)) {
        return false;
      }
    }
    return true;
  }
  rb(_lineNumber, _column, validationType) {
    const lineNumber = Math.floor(typeof _lineNumber === "number" && !isNaN(_lineNumber) ? _lineNumber : 1);
    const column = Math.floor(typeof _column === "number" && !isNaN(_column) ? _column : 1);
    const lineCount = this.C.getLineCount();
    if (lineNumber < 1) {
      return new $8C(1, 1);
    }
    if (lineNumber > lineCount) {
      return new $8C(lineCount, this.getLineMaxColumn(lineCount));
    }
    if (column <= 1) {
      return new $8C(lineNumber, 1);
    }
    const maxColumn = this.getLineMaxColumn(lineNumber);
    if (column >= maxColumn) {
      return new $8C(lineNumber, maxColumn);
    }
    if (validationType === 1) {
      const charCodeBefore = this.C.getLineCharCode(lineNumber, column - 2);
      if ($5f(charCodeBefore)) {
        return new $8C(lineNumber, column - 1);
      }
    }
    return new $8C(lineNumber, column);
  }
  validatePosition(position) {
    const validationType = 1;
    this.jb();
    if (position instanceof $8C) {
      if (this.qb(position.lineNumber, position.column, validationType)) {
        return position;
      }
    }
    return this.rb(position.lineNumber, position.column, validationType);
  }
  sb(range, validationType) {
    const startLineNumber = range.startLineNumber;
    const startColumn = range.startColumn;
    const endLineNumber = range.endLineNumber;
    const endColumn = range.endColumn;
    if (!this.qb(
      startLineNumber,
      startColumn,
      0
      /* StringOffsetValidationType.Relaxed */
    )) {
      return false;
    }
    if (!this.qb(
      endLineNumber,
      endColumn,
      0
      /* StringOffsetValidationType.Relaxed */
    )) {
      return false;
    }
    if (validationType === 1) {
      const charCodeBeforeStart = startColumn > 1 ? this.C.getLineCharCode(startLineNumber, startColumn - 2) : 0;
      const charCodeBeforeEnd = endColumn > 1 && endColumn <= this.C.getLineLength(endLineNumber) ? this.C.getLineCharCode(endLineNumber, endColumn - 2) : 0;
      const startInsideSurrogatePair = $5f(charCodeBeforeStart);
      const endInsideSurrogatePair = $5f(charCodeBeforeEnd);
      if (!startInsideSurrogatePair && !endInsideSurrogatePair) {
        return true;
      }
      return false;
    }
    return true;
  }
  validateRange(_range) {
    const validationType = 1;
    this.jb();
    if (_range instanceof $9C && !(_range instanceof $_D)) {
      if (this.sb(_range, validationType)) {
        return _range;
      }
    }
    const start = this.rb(
      _range.startLineNumber,
      _range.startColumn,
      0
      /* StringOffsetValidationType.Relaxed */
    );
    const end = this.rb(
      _range.endLineNumber,
      _range.endColumn,
      0
      /* StringOffsetValidationType.Relaxed */
    );
    const startLineNumber = start.lineNumber;
    const startColumn = start.column;
    const endLineNumber = end.lineNumber;
    const endColumn = end.column;
    if (validationType === 1) {
      const charCodeBeforeStart = startColumn > 1 ? this.C.getLineCharCode(startLineNumber, startColumn - 2) : 0;
      const charCodeBeforeEnd = endColumn > 1 && endColumn <= this.C.getLineLength(endLineNumber) ? this.C.getLineCharCode(endLineNumber, endColumn - 2) : 0;
      const startInsideSurrogatePair = $5f(charCodeBeforeStart);
      const endInsideSurrogatePair = $5f(charCodeBeforeEnd);
      if (!startInsideSurrogatePair && !endInsideSurrogatePair) {
        return new $9C(startLineNumber, startColumn, endLineNumber, endColumn);
      }
      if (startLineNumber === endLineNumber && startColumn === endColumn) {
        return new $9C(startLineNumber, startColumn - 1, endLineNumber, endColumn - 1);
      }
      if (startInsideSurrogatePair && endInsideSurrogatePair) {
        return new $9C(startLineNumber, startColumn - 1, endLineNumber, endColumn + 1);
      }
      if (startInsideSurrogatePair) {
        return new $9C(startLineNumber, startColumn - 1, endLineNumber, endColumn);
      }
      return new $9C(startLineNumber, startColumn, endLineNumber, endColumn + 1);
    }
    return new $9C(startLineNumber, startColumn, endLineNumber, endColumn);
  }
  modifyPosition(rawPosition, offset) {
    this.jb();
    const candidate = this.getOffsetAt(rawPosition) + offset;
    return this.getPositionAt(Math.min(this.C.getLength(), Math.max(0, candidate)));
  }
  getFullModelRange() {
    this.jb();
    const lineCount = this.getLineCount();
    return new $9C(1, 1, lineCount, this.getLineMaxColumn(lineCount));
  }
  tb(searchRange, searchData, captureMatches, limitResultCount) {
    return this.C.findMatchesLineByLine(searchRange, searchData, captureMatches, limitResultCount);
  }
  findMatches(searchString, rawSearchScope, isRegex, matchCase, wordSeparators2, captureMatches, limitResultCount = LIMIT_FIND_COUNT2) {
    this.jb();
    let searchRanges = null;
    if (rawSearchScope !== null) {
      if (!Array.isArray(rawSearchScope)) {
        rawSearchScope = [rawSearchScope];
      }
      if (rawSearchScope.every((searchScope) => $9C.isIRange(searchScope))) {
        searchRanges = rawSearchScope.map((searchScope) => this.validateRange(searchScope));
      }
    }
    if (searchRanges === null) {
      searchRanges = [this.getFullModelRange()];
    }
    searchRanges = searchRanges.sort((d1, d2) => d1.startLineNumber - d2.startLineNumber || d1.startColumn - d2.startColumn);
    const uniqueSearchRanges = [];
    uniqueSearchRanges.push(searchRanges.reduce((prev, curr) => {
      if ($9C.areIntersecting(prev, curr)) {
        return prev.plusRange(curr);
      }
      uniqueSearchRanges.push(prev);
      return curr;
    }));
    let matchMapper;
    if (!isRegex && searchString.indexOf("\n") < 0) {
      const searchParams = new $fI(searchString, isRegex, matchCase, wordSeparators2);
      const searchData = searchParams.parseSearchRequest();
      if (!searchData) {
        return [];
      }
      matchMapper = (searchRange) => this.tb(searchRange, searchData, captureMatches, limitResultCount);
    } else {
      matchMapper = (searchRange) => $iI.findMatches(this, new $fI(searchString, isRegex, matchCase, wordSeparators2), searchRange, captureMatches, limitResultCount);
    }
    return uniqueSearchRanges.map(matchMapper).reduce((arr, matches) => arr.concat(matches), []);
  }
  findNextMatch(searchString, rawSearchStart, isRegex, matchCase, wordSeparators2, captureMatches) {
    this.jb();
    const searchStart = this.validatePosition(rawSearchStart);
    if (!isRegex && searchString.indexOf("\n") < 0) {
      const searchParams = new $fI(searchString, isRegex, matchCase, wordSeparators2);
      const searchData = searchParams.parseSearchRequest();
      if (!searchData) {
        return null;
      }
      const lineCount = this.getLineCount();
      let searchRange = new $9C(searchStart.lineNumber, searchStart.column, lineCount, this.getLineMaxColumn(lineCount));
      let ret = this.tb(searchRange, searchData, captureMatches, 1);
      $iI.findNextMatch(this, new $fI(searchString, isRegex, matchCase, wordSeparators2), searchStart, captureMatches);
      if (ret.length > 0) {
        return ret[0];
      }
      searchRange = new $9C(1, 1, searchStart.lineNumber, this.getLineMaxColumn(searchStart.lineNumber));
      ret = this.tb(searchRange, searchData, captureMatches, 1);
      if (ret.length > 0) {
        return ret[0];
      }
      return null;
    }
    return $iI.findNextMatch(this, new $fI(searchString, isRegex, matchCase, wordSeparators2), searchStart, captureMatches);
  }
  findPreviousMatch(searchString, rawSearchStart, isRegex, matchCase, wordSeparators2, captureMatches) {
    this.jb();
    const searchStart = this.validatePosition(rawSearchStart);
    return $iI.findPreviousMatch(this, new $fI(searchString, isRegex, matchCase, wordSeparators2), searchStart, captureMatches);
  }
  //#endregion
  //#region Editing
  pushStackElement() {
    this.Q.pushStackElement();
  }
  popStackElement() {
    this.Q.popStackElement();
  }
  pushEOL(eol) {
    const currentEOL = this.getEOL() === "\n" ? 0 : 1;
    if (currentEOL === eol) {
      return;
    }
    try {
      this.h.beginDeferredEmit();
      this.w.beginDeferredEmit();
      if (this.M === null) {
        this.M = this.fb.createSnapshot(this.uri);
      }
      this.Q.pushEOL(eol);
    } finally {
      this.w.endDeferredEmit();
      this.h.endDeferredEmit();
    }
  }
  ub(rawOperation) {
    if (rawOperation instanceof $hG) {
      return rawOperation;
    }
    return new $hG(rawOperation.identifier || null, this.validateRange(rawOperation.range), rawOperation.text, rawOperation.forceMoveMarkers || false, rawOperation.isAutoWhitespaceEdit || false, rawOperation._isTracked || false);
  }
  vb(rawOperations) {
    const result = [];
    for (let i2 = 0, len = rawOperations.length; i2 < len; i2++) {
      result[i2] = this.ub(rawOperations[i2]);
    }
    return result;
  }
  pushEditOperations(beforeCursorState, editOperations, cursorStateComputer, group2) {
    try {
      this.h.beginDeferredEmit();
      this.w.beginDeferredEmit();
      return this.wb(beforeCursorState, this.vb(editOperations), cursorStateComputer, group2);
    } finally {
      this.w.endDeferredEmit();
      this.h.endDeferredEmit();
    }
  }
  wb(beforeCursorState, editOperations, cursorStateComputer, group2) {
    if (this.F.trimAutoWhitespace && this.U) {
      const incomingEdits = editOperations.map((op) => {
        return {
          range: this.validateRange(op.range),
          text: op.text
        };
      });
      let editsAreNearCursors = true;
      if (beforeCursorState) {
        for (let i2 = 0, len = beforeCursorState.length; i2 < len; i2++) {
          const sel = beforeCursorState[i2];
          let foundEditNearSel = false;
          for (let j = 0, lenJ = incomingEdits.length; j < lenJ; j++) {
            const editRange = incomingEdits[j].range;
            const selIsAbove = editRange.startLineNumber > sel.endLineNumber;
            const selIsBelow = sel.startLineNumber > editRange.endLineNumber;
            if (!selIsAbove && !selIsBelow) {
              foundEditNearSel = true;
              break;
            }
          }
          if (!foundEditNearSel) {
            editsAreNearCursors = false;
            break;
          }
        }
      }
      if (editsAreNearCursors) {
        for (let i2 = 0, len = this.U.length; i2 < len; i2++) {
          const trimLineNumber = this.U[i2];
          const maxLineColumn = this.getLineMaxColumn(trimLineNumber);
          let allowTrimLine = true;
          for (let j = 0, lenJ = incomingEdits.length; j < lenJ; j++) {
            const editRange = incomingEdits[j].range;
            const editText = incomingEdits[j].text;
            if (trimLineNumber < editRange.startLineNumber || trimLineNumber > editRange.endLineNumber) {
              continue;
            }
            if (trimLineNumber === editRange.startLineNumber && editRange.startColumn === maxLineColumn && editRange.isEmpty() && editText && editText.length > 0 && editText.charAt(0) === "\n") {
              continue;
            }
            if (trimLineNumber === editRange.startLineNumber && editRange.startColumn === 1 && editRange.isEmpty() && editText && editText.length > 0 && editText.charAt(editText.length - 1) === "\n") {
              continue;
            }
            allowTrimLine = false;
            break;
          }
          if (allowTrimLine) {
            const trimRange = new $9C(trimLineNumber, 1, trimLineNumber, maxLineColumn);
            editOperations.push(new $hG(null, trimRange, null, false, false, false));
          }
        }
      }
      this.U = null;
    }
    if (this.M === null) {
      this.M = this.fb.createSnapshot(this.uri);
    }
    return this.Q.pushEditOperation(beforeCursorState, editOperations, cursorStateComputer, group2);
  }
  _applyUndo(changes, eol, resultingAlternativeVersionId, resultingSelection) {
    const edits = changes.map((change) => {
      const rangeStart = this.getPositionAt(change.newPosition);
      const rangeEnd = this.getPositionAt(change.newEnd);
      return {
        range: new $9C(rangeStart.lineNumber, rangeStart.column, rangeEnd.lineNumber, rangeEnd.column),
        text: change.oldText
      };
    });
    this.xb(edits, eol, true, false, resultingAlternativeVersionId, resultingSelection);
  }
  _applyRedo(changes, eol, resultingAlternativeVersionId, resultingSelection) {
    const edits = changes.map((change) => {
      const rangeStart = this.getPositionAt(change.oldPosition);
      const rangeEnd = this.getPositionAt(change.oldEnd);
      return {
        range: new $9C(rangeStart.lineNumber, rangeStart.column, rangeEnd.lineNumber, rangeEnd.column),
        text: change.newText
      };
    });
    this.xb(edits, eol, false, true, resultingAlternativeVersionId, resultingSelection);
  }
  xb(edits, eol, isUndoing, isRedoing, resultingAlternativeVersionId, resultingSelection) {
    try {
      this.h.beginDeferredEmit();
      this.w.beginDeferredEmit();
      this.R = isUndoing;
      this.S = isRedoing;
      this.applyEdits(edits, false);
      this.setEOL(eol);
      this._overwriteAlternativeVersionId(resultingAlternativeVersionId);
    } finally {
      this.R = false;
      this.S = false;
      this.w.endDeferredEmit(resultingSelection);
      this.h.endDeferredEmit();
    }
  }
  applyEdits(rawOperations, computeUndoEdits = false) {
    try {
      this.h.beginDeferredEmit();
      this.w.beginDeferredEmit();
      const operations = this.vb(rawOperations);
      return this.yb(operations, computeUndoEdits);
    } finally {
      this.w.endDeferredEmit();
      this.h.endDeferredEmit();
    }
  }
  yb(rawOperations, computeUndoEdits) {
    const oldLineCount = this.C.getLineCount();
    const result = this.C.applyEdits(rawOperations, this.F.trimAutoWhitespace, computeUndoEdits);
    const newLineCount = this.C.getLineCount();
    const contentChanges = result.changes;
    this.U = result.trimAutoWhitespaceLineNumbers;
    if (contentChanges.length !== 0) {
      for (let i2 = 0, len = contentChanges.length; i2 < len; i2++) {
        const change = contentChanges[i2];
        this.$.acceptReplace(change.rangeOffset, change.rangeLength, change.text.length, change.forceMoveMarkers);
      }
      const rawContentChanges = [];
      this.pb();
      let lineCount = oldLineCount;
      for (let i2 = 0, len = contentChanges.length; i2 < len; i2++) {
        const change = contentChanges[i2];
        const [eolCount] = $tE(change.text);
        this.h.fire();
        const startLineNumber = change.range.startLineNumber;
        const endLineNumber = change.range.endLineNumber;
        const deletingLinesCnt = endLineNumber - startLineNumber;
        const insertingLinesCnt = eolCount;
        const editingLinesCnt = Math.min(deletingLinesCnt, insertingLinesCnt);
        const changeLineCountDelta = insertingLinesCnt - deletingLinesCnt;
        const currentEditStartLineNumber = newLineCount - lineCount - changeLineCountDelta + startLineNumber;
        const firstEditLineNumber = currentEditStartLineNumber;
        const lastInsertedLineNumber = currentEditStartLineNumber + insertingLinesCnt;
        const decorationsWithInjectedTextInEditedRange = this.$.getInjectedTextInInterval(this, this.getOffsetAt(new $8C(firstEditLineNumber, 1)), this.getOffsetAt(new $8C(lastInsertedLineNumber, this.getLineMaxColumn(lastInsertedLineNumber))), 0);
        const injectedTextInEditedRange = $FE.fromDecorations(decorationsWithInjectedTextInEditedRange);
        const injectedTextInEditedRangeQueue = new $bc(injectedTextInEditedRange);
        for (let j = editingLinesCnt; j >= 0; j--) {
          const editLineNumber = startLineNumber + j;
          const currentEditLineNumber = currentEditStartLineNumber + j;
          injectedTextInEditedRangeQueue.takeFromEndWhile((r2) => r2.lineNumber > currentEditLineNumber);
          const decorationsInCurrentLine = injectedTextInEditedRangeQueue.takeFromEndWhile((r2) => r2.lineNumber === currentEditLineNumber);
          rawContentChanges.push(new $GE(editLineNumber, this.getLineContent(currentEditLineNumber), decorationsInCurrentLine));
        }
        if (editingLinesCnt < deletingLinesCnt) {
          const spliceStartLineNumber = startLineNumber + editingLinesCnt;
          rawContentChanges.push(new $HE(spliceStartLineNumber + 1, endLineNumber));
        }
        if (editingLinesCnt < insertingLinesCnt) {
          const injectedTextInEditedRangeQueue2 = new $bc(injectedTextInEditedRange);
          const spliceLineNumber = startLineNumber + editingLinesCnt;
          const cnt = insertingLinesCnt - editingLinesCnt;
          const fromLineNumber = newLineCount - lineCount - cnt + spliceLineNumber + 1;
          const injectedTexts = [];
          const newLines = [];
          for (let i3 = 0; i3 < cnt; i3++) {
            const lineNumber = fromLineNumber + i3;
            newLines[i3] = this.getLineContent(lineNumber);
            injectedTextInEditedRangeQueue2.takeWhile((r2) => r2.lineNumber < lineNumber);
            injectedTexts[i3] = injectedTextInEditedRangeQueue2.takeWhile((r2) => r2.lineNumber === lineNumber);
          }
          rawContentChanges.push(new $IE(spliceLineNumber + 1, startLineNumber + insertingLinesCnt, newLines, injectedTexts));
        }
        lineCount += changeLineCountDelta;
      }
      this.kb(new $KE(rawContentChanges, this.getVersionId(), this.R, this.S), {
        changes: contentChanges,
        eol: this.C.getEOL(),
        isEolChange: false,
        versionId: this.getVersionId(),
        isUndoing: this.R,
        isRedoing: this.S,
        isFlush: false
      });
    }
    return result.reverseEdits === null ? void 0 : result.reverseEdits;
  }
  undo() {
    return this.fb.undo(this.uri);
  }
  canUndo() {
    return this.fb.canUndo(this.uri);
  }
  redo() {
    return this.fb.redo(this.uri);
  }
  canRedo() {
    return this.fb.canRedo(this.uri);
  }
  //#endregion
  //#region Decorations
  zb(affectedInjectedTextLines) {
    if (affectedInjectedTextLines === null || affectedInjectedTextLines.size === 0) {
      return;
    }
    const affectedLines = Array.from(affectedInjectedTextLines);
    const lineChangeEvents = affectedLines.map((lineNumber) => new $GE(lineNumber, this.getLineContent(lineNumber), this.Bb(lineNumber)));
    this.u.fire(new $LE(lineChangeEvents));
  }
  changeDecorations(callback, ownerId2 = 0) {
    this.jb();
    try {
      this.h.beginDeferredEmit();
      return this.Ab(ownerId2, callback);
    } finally {
      this.h.endDeferredEmit();
    }
  }
  Ab(ownerId2, callback) {
    const changeAccessor = {
      addDecoration: (range, options3) => {
        return this.Fb(ownerId2, [], [{ range, options: options3 }])[0];
      },
      changeDecoration: (id2, newRange) => {
        this.Db(id2, newRange);
      },
      changeDecorationOptions: (id2, options3) => {
        this.Eb(id2, _normalizeOptions(options3));
      },
      removeDecoration: (id2) => {
        this.Fb(ownerId2, [id2], []);
      },
      deltaDecorations: (oldDecorations, newDecorations) => {
        if (oldDecorations.length === 0 && newDecorations.length === 0) {
          return [];
        }
        return this.Fb(ownerId2, oldDecorations, newDecorations);
      }
    };
    let result = null;
    try {
      result = callback(changeAccessor);
    } catch (e) {
      $gb(e);
    }
    changeAccessor.addDecoration = invalidFunc2;
    changeAccessor.changeDecoration = invalidFunc2;
    changeAccessor.changeDecorationOptions = invalidFunc2;
    changeAccessor.removeDecoration = invalidFunc2;
    changeAccessor.deltaDecorations = invalidFunc2;
    return result;
  }
  deltaDecorations(oldDecorations, newDecorations, ownerId2 = 0) {
    this.jb();
    if (!oldDecorations) {
      oldDecorations = [];
    }
    if (oldDecorations.length === 0 && newDecorations.length === 0) {
      return [];
    }
    try {
      this.X++;
      if (this.X > 1) {
        console.warn(`Invoking deltaDecorations recursively could lead to leaking decorations.`);
        $gb(new Error(`Invoking deltaDecorations recursively could lead to leaking decorations.`));
      }
      this.h.beginDeferredEmit();
      return this.Fb(ownerId2, oldDecorations, newDecorations);
    } finally {
      this.h.endDeferredEmit();
      this.X--;
    }
  }
  _getTrackedRange(id2) {
    return this.getDecorationRange(id2);
  }
  _setTrackedRange(id2, newRange, newStickiness) {
    const node = id2 ? this.Z[id2] : null;
    if (!node) {
      if (!newRange) {
        return null;
      }
      return this.Fb(0, [], [{ range: newRange, options: TRACKED_RANGE_OPTIONS[newStickiness] }], true)[0];
    }
    if (!newRange) {
      this.$.delete(node);
      delete this.Z[node.id];
      return null;
    }
    const range = this._validateRangeRelaxedNoAllocations(newRange);
    const startOffset = this.C.getOffsetAt(range.startLineNumber, range.startColumn);
    const endOffset = this.C.getOffsetAt(range.endLineNumber, range.endColumn);
    this.$.delete(node);
    node.reset(this.getVersionId(), startOffset, endOffset, range);
    node.setOptions(TRACKED_RANGE_OPTIONS[newStickiness]);
    this.$.insert(node);
    return node.id;
  }
  removeAllDecorationsWithOwnerId(ownerId2) {
    if (this.H) {
      return;
    }
    const nodes = this.$.collectNodesFromOwner(ownerId2);
    for (let i2 = 0, len = nodes.length; i2 < len; i2++) {
      const node = nodes[i2];
      this.$.delete(node);
      delete this.Z[node.id];
    }
  }
  getDecorationOptions(decorationId) {
    const node = this.Z[decorationId];
    if (!node) {
      return null;
    }
    return node.options;
  }
  getDecorationRange(decorationId) {
    const node = this.Z[decorationId];
    if (!node) {
      return null;
    }
    return this.$.getNodeRange(this, node);
  }
  getLineDecorations(lineNumber, ownerId2 = 0, filterOutValidation = false) {
    if (lineNumber < 1 || lineNumber > this.getLineCount()) {
      return [];
    }
    return this.getLinesDecorations(lineNumber, lineNumber, ownerId2, filterOutValidation);
  }
  getLinesDecorations(_startLineNumber, _endLineNumber, ownerId2 = 0, filterOutValidation = false, onlyMarginDecorations = false) {
    const lineCount = this.getLineCount();
    const startLineNumber = Math.min(lineCount, Math.max(1, _startLineNumber));
    const endLineNumber = Math.min(lineCount, Math.max(1, _endLineNumber));
    const endColumn = this.getLineMaxColumn(endLineNumber);
    const range = new $9C(startLineNumber, 1, endLineNumber, endColumn);
    const decorations = this.Cb(range, ownerId2, filterOutValidation, onlyMarginDecorations);
    $3b(decorations, this.ab.getDecorationsInRange(range, ownerId2, filterOutValidation));
    return decorations;
  }
  getDecorationsInRange(range, ownerId2 = 0, filterOutValidation = false, onlyMinimapDecorations = false, onlyMarginDecorations = false) {
    const validatedRange = this.validateRange(range);
    const decorations = this.Cb(validatedRange, ownerId2, filterOutValidation, onlyMarginDecorations);
    $3b(decorations, this.ab.getDecorationsInRange(validatedRange, ownerId2, filterOutValidation, onlyMinimapDecorations));
    return decorations;
  }
  getOverviewRulerDecorations(ownerId2 = 0, filterOutValidation = false) {
    return this.$.getAll(this, ownerId2, filterOutValidation, true, false);
  }
  getInjectedTextDecorations(ownerId2 = 0) {
    return this.$.getAllInjectedText(this, ownerId2);
  }
  Bb(lineNumber) {
    const startOffset = this.C.getOffsetAt(lineNumber, 1);
    const endOffset = startOffset + this.C.getLineLength(lineNumber);
    const result = this.$.getInjectedTextInInterval(this, startOffset, endOffset, 0);
    return $FE.fromDecorations(result).filter((t) => t.lineNumber === lineNumber);
  }
  getAllDecorations(ownerId2 = 0, filterOutValidation = false) {
    let result = this.$.getAll(this, ownerId2, filterOutValidation, false, false);
    result = result.concat(this.ab.getAllDecorations(ownerId2, filterOutValidation));
    return result;
  }
  getAllMarginDecorations(ownerId2 = 0) {
    return this.$.getAll(this, ownerId2, false, false, true);
  }
  Cb(filterRange, filterOwnerId, filterOutValidation, onlyMarginDecorations) {
    const startOffset = this.C.getOffsetAt(filterRange.startLineNumber, filterRange.startColumn);
    const endOffset = this.C.getOffsetAt(filterRange.endLineNumber, filterRange.endColumn);
    return this.$.getAllInInterval(this, startOffset, endOffset, filterOwnerId, filterOutValidation, onlyMarginDecorations);
  }
  getRangeAt(start, end) {
    return this.C.getRangeAt(start, end - start);
  }
  Db(decorationId, _range) {
    const node = this.Z[decorationId];
    if (!node) {
      return;
    }
    if (node.options.after) {
      const oldRange = this.getDecorationRange(decorationId);
      this.h.recordLineAffectedByInjectedText(oldRange.endLineNumber);
    }
    if (node.options.before) {
      const oldRange = this.getDecorationRange(decorationId);
      this.h.recordLineAffectedByInjectedText(oldRange.startLineNumber);
    }
    const range = this._validateRangeRelaxedNoAllocations(_range);
    const startOffset = this.C.getOffsetAt(range.startLineNumber, range.startColumn);
    const endOffset = this.C.getOffsetAt(range.endLineNumber, range.endColumn);
    this.$.delete(node);
    node.reset(this.getVersionId(), startOffset, endOffset, range);
    this.$.insert(node);
    this.h.checkAffectedAndFire(node.options);
    if (node.options.after) {
      this.h.recordLineAffectedByInjectedText(range.endLineNumber);
    }
    if (node.options.before) {
      this.h.recordLineAffectedByInjectedText(range.startLineNumber);
    }
  }
  Eb(decorationId, options3) {
    const node = this.Z[decorationId];
    if (!node) {
      return;
    }
    const nodeWasInOverviewRuler = node.options.overviewRuler && node.options.overviewRuler.color ? true : false;
    const nodeIsInOverviewRuler = options3.overviewRuler && options3.overviewRuler.color ? true : false;
    this.h.checkAffectedAndFire(node.options);
    this.h.checkAffectedAndFire(options3);
    if (node.options.after || options3.after) {
      const nodeRange = this.$.getNodeRange(this, node);
      this.h.recordLineAffectedByInjectedText(nodeRange.endLineNumber);
    }
    if (node.options.before || options3.before) {
      const nodeRange = this.$.getNodeRange(this, node);
      this.h.recordLineAffectedByInjectedText(nodeRange.startLineNumber);
    }
    const movedInOverviewRuler = nodeWasInOverviewRuler !== nodeIsInOverviewRuler;
    const changedWhetherInjectedText = isOptionsInjectedText(options3) !== isNodeInjectedText(node);
    if (movedInOverviewRuler || changedWhetherInjectedText) {
      this.$.delete(node);
      node.setOptions(options3);
      this.$.insert(node);
    } else {
      node.setOptions(options3);
    }
  }
  Fb(ownerId2, oldDecorationsIds, newDecorations, suppressEvents = false) {
    const versionId = this.getVersionId();
    const oldDecorationsLen = oldDecorationsIds.length;
    let oldDecorationIndex = 0;
    const newDecorationsLen = newDecorations.length;
    let newDecorationIndex = 0;
    this.h.beginDeferredEmit();
    try {
      const result = new Array(newDecorationsLen);
      while (oldDecorationIndex < oldDecorationsLen || newDecorationIndex < newDecorationsLen) {
        let node = null;
        if (oldDecorationIndex < oldDecorationsLen) {
          do {
            node = this.Z[oldDecorationsIds[oldDecorationIndex++]];
          } while (!node && oldDecorationIndex < oldDecorationsLen);
          if (node) {
            if (node.options.after) {
              const nodeRange = this.$.getNodeRange(this, node);
              this.h.recordLineAffectedByInjectedText(nodeRange.endLineNumber);
            }
            if (node.options.before) {
              const nodeRange = this.$.getNodeRange(this, node);
              this.h.recordLineAffectedByInjectedText(nodeRange.startLineNumber);
            }
            this.$.delete(node);
            if (!suppressEvents) {
              this.h.checkAffectedAndFire(node.options);
            }
          }
        }
        if (newDecorationIndex < newDecorationsLen) {
          if (!node) {
            const internalDecorationId = ++this.Y;
            const decorationId = `${this.W};${internalDecorationId}`;
            node = new $2H(decorationId, 0, 0);
            this.Z[decorationId] = node;
          }
          const newDecoration = newDecorations[newDecorationIndex];
          const range = this._validateRangeRelaxedNoAllocations(newDecoration.range);
          const options3 = _normalizeOptions(newDecoration.options);
          const startOffset = this.C.getOffsetAt(range.startLineNumber, range.startColumn);
          const endOffset = this.C.getOffsetAt(range.endLineNumber, range.endColumn);
          node.ownerId = ownerId2;
          node.reset(versionId, startOffset, endOffset, range);
          node.setOptions(options3);
          if (node.options.after) {
            this.h.recordLineAffectedByInjectedText(range.endLineNumber);
          }
          if (node.options.before) {
            this.h.recordLineAffectedByInjectedText(range.startLineNumber);
          }
          if (!suppressEvents) {
            this.h.checkAffectedAndFire(options3);
          }
          this.$.insert(node);
          result[newDecorationIndex] = node.id;
          newDecorationIndex++;
        } else {
          if (node) {
            delete this.Z[node.id];
          }
        }
      }
      return result;
    } finally {
      this.h.endDeferredEmit();
    }
  }
  //#endregion
  //#region Tokenization
  // TODO move them to the tokenization part.
  getLanguageId() {
    return this.tokenization.getLanguageId();
  }
  setLanguage(languageIdOrSelection, source) {
    if (typeof languageIdOrSelection === "string") {
      this.G.clear();
      this.Gb(languageIdOrSelection, source);
    } else {
      this.G.value = languageIdOrSelection.onDidChange(() => this.Gb(languageIdOrSelection.languageId, source));
      this.Gb(languageIdOrSelection.languageId, source);
    }
  }
  Gb(languageId, source) {
    this.tokenization.setLanguageId(languageId, source);
    this.gb.requestRichLanguageFeatures(languageId);
  }
  getLanguageIdAtPosition(lineNumber, column) {
    return this.tokenization.getLanguageIdAtPosition(lineNumber, column);
  }
  getWordAtPosition(position) {
    return this.bb.getWordAtPosition(position);
  }
  getWordUntilPosition(position) {
    return this.bb.getWordUntilPosition(position);
  }
  //#endregion
  normalizePosition(position, affinity) {
    return position;
  }
  /**
   * Gets the column at which indentation stops at a given line.
   * @internal
  */
  getLineIndentColumn(lineNumber) {
    return $RI(this.getLineContent(lineNumber)) + 1;
  }
};
$QI = $QI_1 = __decorate([
  __param(4, $_F),
  __param(5, $1E),
  __param(6, $NF),
  __param(7, $Pk)
], $QI);
function $RI(line) {
  let indent = 0;
  for (const c of line) {
    if (c === " " || c === "	") {
      indent++;
    } else {
      break;
    }
  }
  return indent;
}
function isNodeInOverviewRuler(node) {
  return node.options.overviewRuler && node.options.overviewRuler.color ? true : false;
}
function isOptionsInjectedText(options3) {
  return !!options3.after || !!options3.before;
}
function isNodeInjectedText(node) {
  return !!node.options.after || !!node.options.before;
}
var DecorationsTrees = class {
  constructor() {
    this.a = new $4H();
    this.b = new $4H();
    this.d = new $4H();
  }
  ensureAllNodesHaveRanges(host) {
    this.getAll(host, 0, false, false, false);
  }
  f(host, nodes) {
    for (const node of nodes) {
      if (node.range === null) {
        node.range = host.getRangeAt(node.cachedAbsoluteStart, node.cachedAbsoluteEnd);
      }
    }
    return nodes;
  }
  getAllInInterval(host, start, end, filterOwnerId, filterOutValidation, onlyMarginDecorations) {
    const versionId = host.getVersionId();
    const result = this.g(start, end, filterOwnerId, filterOutValidation, versionId, onlyMarginDecorations);
    return this.f(host, result);
  }
  g(start, end, filterOwnerId, filterOutValidation, cachedVersionId, onlyMarginDecorations) {
    const r0 = this.a.intervalSearch(start, end, filterOwnerId, filterOutValidation, cachedVersionId, onlyMarginDecorations);
    const r1 = this.b.intervalSearch(start, end, filterOwnerId, filterOutValidation, cachedVersionId, onlyMarginDecorations);
    const r2 = this.d.intervalSearch(start, end, filterOwnerId, filterOutValidation, cachedVersionId, onlyMarginDecorations);
    return r0.concat(r1).concat(r2);
  }
  getInjectedTextInInterval(host, start, end, filterOwnerId) {
    const versionId = host.getVersionId();
    const result = this.d.intervalSearch(start, end, filterOwnerId, false, versionId, false);
    return this.f(host, result).filter((i2) => i2.options.showIfCollapsed || !i2.range.isEmpty());
  }
  getAllInjectedText(host, filterOwnerId) {
    const versionId = host.getVersionId();
    const result = this.d.search(filterOwnerId, false, versionId, false);
    return this.f(host, result).filter((i2) => i2.options.showIfCollapsed || !i2.range.isEmpty());
  }
  getAll(host, filterOwnerId, filterOutValidation, overviewRulerOnly, onlyMarginDecorations) {
    const versionId = host.getVersionId();
    const result = this.h(filterOwnerId, filterOutValidation, overviewRulerOnly, versionId, onlyMarginDecorations);
    return this.f(host, result);
  }
  h(filterOwnerId, filterOutValidation, overviewRulerOnly, cachedVersionId, onlyMarginDecorations) {
    if (overviewRulerOnly) {
      return this.b.search(filterOwnerId, filterOutValidation, cachedVersionId, onlyMarginDecorations);
    } else {
      const r0 = this.a.search(filterOwnerId, filterOutValidation, cachedVersionId, onlyMarginDecorations);
      const r1 = this.b.search(filterOwnerId, filterOutValidation, cachedVersionId, onlyMarginDecorations);
      const r2 = this.d.search(filterOwnerId, filterOutValidation, cachedVersionId, onlyMarginDecorations);
      return r0.concat(r1).concat(r2);
    }
  }
  collectNodesFromOwner(ownerId2) {
    const r0 = this.a.collectNodesFromOwner(ownerId2);
    const r1 = this.b.collectNodesFromOwner(ownerId2);
    const r2 = this.d.collectNodesFromOwner(ownerId2);
    return r0.concat(r1).concat(r2);
  }
  collectNodesPostOrder() {
    const r0 = this.a.collectNodesPostOrder();
    const r1 = this.b.collectNodesPostOrder();
    const r2 = this.d.collectNodesPostOrder();
    return r0.concat(r1).concat(r2);
  }
  insert(node) {
    if (isNodeInjectedText(node)) {
      this.d.insert(node);
    } else if (isNodeInOverviewRuler(node)) {
      this.b.insert(node);
    } else {
      this.a.insert(node);
    }
  }
  delete(node) {
    if (isNodeInjectedText(node)) {
      this.d.delete(node);
    } else if (isNodeInOverviewRuler(node)) {
      this.b.delete(node);
    } else {
      this.a.delete(node);
    }
  }
  getNodeRange(host, node) {
    const versionId = host.getVersionId();
    if (node.cachedVersionId !== versionId) {
      this.k(node, versionId);
    }
    if (node.range === null) {
      node.range = host.getRangeAt(node.cachedAbsoluteStart, node.cachedAbsoluteEnd);
    }
    return node.range;
  }
  k(node, cachedVersionId) {
    if (isNodeInjectedText(node)) {
      this.d.resolveNode(node, cachedVersionId);
    } else if (isNodeInOverviewRuler(node)) {
      this.b.resolveNode(node, cachedVersionId);
    } else {
      this.a.resolveNode(node, cachedVersionId);
    }
  }
  acceptReplace(offset, length, textLength, forceMoveMarkers) {
    this.a.acceptReplace(offset, length, textLength, forceMoveMarkers);
    this.b.acceptReplace(offset, length, textLength, forceMoveMarkers);
    this.d.acceptReplace(offset, length, textLength, forceMoveMarkers);
  }
};
function cleanClassName(className) {
  return className.replace(/[^a-z0-9\-_]/gi, " ");
}
var DecorationOptions = class {
  constructor(options3) {
    this.color = options3.color || "";
    this.darkColor = options3.darkColor || "";
  }
};
var $SI = class extends DecorationOptions {
  constructor(options3) {
    super(options3);
    this.a = null;
    this.position = typeof options3.position === "number" ? options3.position : OverviewRulerLane.Center;
  }
  getColor(theme) {
    if (!this.a) {
      if (theme.type !== "light" && this.darkColor) {
        this.a = this.b(this.darkColor, theme);
      } else {
        this.a = this.b(this.color, theme);
      }
    }
    return this.a;
  }
  invalidateCachedColor() {
    this.a = null;
  }
  b(color2, theme) {
    if (typeof color2 === "string") {
      return color2;
    }
    const c = color2 ? theme.getColor(color2.id) : null;
    if (!c) {
      return "";
    }
    return c.toString();
  }
};
var $TI = class {
  constructor(options3) {
    this.position = options3?.position ?? GlyphMarginLane.Center;
    this.persistLane = options3?.persistLane;
  }
};
var $UI = class extends DecorationOptions {
  constructor(options3) {
    super(options3);
    this.position = options3.position;
    this.sectionHeaderStyle = options3.sectionHeaderStyle ?? null;
    this.sectionHeaderText = options3.sectionHeaderText ?? null;
  }
  getColor(theme) {
    if (!this.a) {
      if (theme.type !== "light" && this.darkColor) {
        this.a = this.b(this.darkColor, theme);
      } else {
        this.a = this.b(this.color, theme);
      }
    }
    return this.a;
  }
  invalidateCachedColor() {
    this.a = void 0;
  }
  b(color2, theme) {
    if (typeof color2 === "string") {
      return $Vn.fromHex(color2);
    }
    return theme.getColor(color2.id);
  }
};
var $VI = class _$VI {
  static from(options3) {
    if (options3 instanceof _$VI) {
      return options3;
    }
    return new _$VI(options3);
  }
  constructor(options3) {
    this.content = options3.content || "";
    this.tokens = options3.tokens ?? null;
    this.inlineClassName = options3.inlineClassName || null;
    this.inlineClassNameAffectsLetterSpacing = options3.inlineClassNameAffectsLetterSpacing || false;
    this.attachedData = options3.attachedData || null;
    this.cursorStops = options3.cursorStops || null;
  }
};
var $WI = class _$WI {
  static register(options3) {
    return new _$WI(options3);
  }
  static createDynamic(options3) {
    return new _$WI(options3);
  }
  constructor(options3) {
    this.description = options3.description;
    this.blockClassName = options3.blockClassName ? cleanClassName(options3.blockClassName) : null;
    this.blockDoesNotCollapse = options3.blockDoesNotCollapse ?? null;
    this.blockIsAfterEnd = options3.blockIsAfterEnd ?? null;
    this.blockPadding = options3.blockPadding ?? null;
    this.stickiness = options3.stickiness || 0;
    this.zIndex = options3.zIndex || 0;
    this.className = options3.className ? cleanClassName(options3.className) : null;
    this.shouldFillLineOnLineBreak = options3.shouldFillLineOnLineBreak ?? null;
    this.hoverMessage = options3.hoverMessage || null;
    this.glyphMarginHoverMessage = options3.glyphMarginHoverMessage || null;
    this.lineNumberHoverMessage = options3.lineNumberHoverMessage || null;
    this.isWholeLine = options3.isWholeLine || false;
    this.showIfCollapsed = options3.showIfCollapsed || false;
    this.collapseOnReplaceEdit = options3.collapseOnReplaceEdit || false;
    this.overviewRuler = options3.overviewRuler ? new $SI(options3.overviewRuler) : null;
    this.minimap = options3.minimap ? new $UI(options3.minimap) : null;
    this.glyphMargin = options3.glyphMarginClassName ? new $TI(options3.glyphMargin) : null;
    this.glyphMarginClassName = options3.glyphMarginClassName ? cleanClassName(options3.glyphMarginClassName) : null;
    this.linesDecorationsClassName = options3.linesDecorationsClassName ? cleanClassName(options3.linesDecorationsClassName) : null;
    this.lineNumberClassName = options3.lineNumberClassName ? cleanClassName(options3.lineNumberClassName) : null;
    this.linesDecorationsTooltip = options3.linesDecorationsTooltip ? $yf(options3.linesDecorationsTooltip) : null;
    this.firstLineDecorationClassName = options3.firstLineDecorationClassName ? cleanClassName(options3.firstLineDecorationClassName) : null;
    this.marginClassName = options3.marginClassName ? cleanClassName(options3.marginClassName) : null;
    this.inlineClassName = options3.inlineClassName ? cleanClassName(options3.inlineClassName) : null;
    this.inlineClassNameAffectsLetterSpacing = options3.inlineClassNameAffectsLetterSpacing || false;
    this.beforeContentClassName = options3.beforeContentClassName ? cleanClassName(options3.beforeContentClassName) : null;
    this.afterContentClassName = options3.afterContentClassName ? cleanClassName(options3.afterContentClassName) : null;
    this.after = options3.after ? $VI.from(options3.after) : null;
    this.before = options3.before ? $VI.from(options3.before) : null;
    this.hideInCommentTokens = options3.hideInCommentTokens ?? false;
    this.hideInStringTokens = options3.hideInStringTokens ?? false;
  }
};
$WI.EMPTY = $WI.register({ description: "empty" });
var TRACKED_RANGE_OPTIONS = [
  $WI.register({
    description: "tracked-range-always-grows-when-typing-at-edges",
    stickiness: 0
    /* model.TrackedRangeStickiness.AlwaysGrowsWhenTypingAtEdges */
  }),
  $WI.register({
    description: "tracked-range-never-grows-when-typing-at-edges",
    stickiness: 1
    /* model.TrackedRangeStickiness.NeverGrowsWhenTypingAtEdges */
  }),
  $WI.register({
    description: "tracked-range-grows-only-when-typing-before",
    stickiness: 2
    /* model.TrackedRangeStickiness.GrowsOnlyWhenTypingBefore */
  }),
  $WI.register({
    description: "tracked-range-grows-only-when-typing-after",
    stickiness: 3
    /* model.TrackedRangeStickiness.GrowsOnlyWhenTypingAfter */
  })
];
function _normalizeOptions(options3) {
  if (options3 instanceof $WI) {
    return options3;
  }
  return $WI.createDynamic(options3);
}
var DidChangeDecorationsEmitter = class extends $3c {
  constructor(w) {
    super();
    this.w = w;
    this.a = this.B(new $ze());
    this.event = this.a.event;
    this.n = null;
    this.b = 0;
    this.f = false;
    this.g = false;
    this.h = false;
    this.s = false;
    this.u = false;
  }
  hasListeners() {
    return this.a.hasListeners();
  }
  beginDeferredEmit() {
    this.b++;
  }
  endDeferredEmit() {
    this.b--;
    if (this.b === 0) {
      if (this.f) {
        this.z();
      }
      this.n?.clear();
      this.n = null;
    }
  }
  recordLineAffectedByInjectedText(lineNumber) {
    if (!this.n) {
      this.n = /* @__PURE__ */ new Set();
    }
    this.n.add(lineNumber);
  }
  checkAffectedAndFire(options3) {
    this.g ||= !!options3.minimap?.position;
    this.h ||= !!options3.overviewRuler?.color;
    this.s ||= !!options3.glyphMarginClassName;
    this.u ||= !!options3.lineNumberClassName;
    this.y();
  }
  fire() {
    this.g = true;
    this.h = true;
    this.s = true;
    this.y();
  }
  y() {
    if (this.b === 0) {
      this.z();
    } else {
      this.f = true;
    }
  }
  z() {
    this.w(this.n);
    const event = {
      affectsMinimap: this.g,
      affectsOverviewRuler: this.h,
      affectsGlyphMargin: this.s,
      affectsLineNumber: this.u
    };
    this.f = false;
    this.g = false;
    this.h = false;
    this.s = false;
    this.a.fire(event);
  }
};
var DidChangeContentEmitter = class extends $3c {
  constructor() {
    super();
    this.a = this.B(new $ze());
    this.fastEvent = this.a.event;
    this.b = this.B(new $ze());
    this.slowEvent = this.b.event;
    this.f = 0;
    this.g = null;
  }
  hasListeners() {
    return this.a.hasListeners() || this.b.hasListeners();
  }
  beginDeferredEmit() {
    this.f++;
  }
  endDeferredEmit(resultingSelection = null) {
    this.f--;
    if (this.f === 0) {
      if (this.g !== null) {
        this.g.rawContentChangedEvent.resultingSelection = resultingSelection;
        const e = this.g;
        this.g = null;
        this.a.fire(e);
        this.b.fire(e);
      }
    }
  }
  fire(e) {
    if (this.f > 0) {
      if (this.g) {
        this.g = this.g.merge(e);
      } else {
        this.g = e;
      }
      return;
    }
    this.a.fire(e);
    this.b.fire(e);
  }
};

// out-build/vs/editor/common/services/languageFeatures.js
var $mP = $Qk("ILanguageFeaturesService");

// out-build/vs/editor/common/viewModel/monospaceLineBreaksComputer.js
var $58 = class _$58 {
  static create(options3) {
    return new _$58(options3.get(
      139
      /* EditorOption.wordWrapBreakBeforeCharacters */
    ), options3.get(
      138
      /* EditorOption.wordWrapBreakAfterCharacters */
    ));
  }
  constructor(breakBeforeChars, breakAfterChars) {
    this.a = new WrappingCharacterClassifier(breakBeforeChars, breakAfterChars);
  }
  createLineBreaksComputer(fontInfo, tabSize, wrappingColumn, wrappingIndent, wordBreak) {
    const requests = [];
    const injectedTexts = [];
    const previousBreakingData = [];
    return {
      addRequest: (lineText, injectedText, previousLineBreakData) => {
        requests.push(lineText);
        injectedTexts.push(injectedText);
        previousBreakingData.push(previousLineBreakData);
      },
      finalize: () => {
        const columnsForFullWidthChar = fontInfo.typicalFullwidthCharacterWidth / fontInfo.typicalHalfwidthCharacterWidth;
        const result = [];
        for (let i2 = 0, len = requests.length; i2 < len; i2++) {
          const injectedText = injectedTexts[i2];
          const previousLineBreakData = previousBreakingData[i2];
          if (previousLineBreakData && !previousLineBreakData.injectionOptions && !injectedText) {
            result[i2] = createLineBreaksFromPreviousLineBreaks(this.a, previousLineBreakData, requests[i2], tabSize, wrappingColumn, columnsForFullWidthChar, wrappingIndent, wordBreak);
          } else {
            result[i2] = createLineBreaks2(this.a, requests[i2], injectedText, tabSize, wrappingColumn, columnsForFullWidthChar, wrappingIndent, wordBreak);
          }
        }
        arrPool1.length = 0;
        arrPool2.length = 0;
        return result;
      }
    };
  }
};
var CharacterClass;
(function(CharacterClass3) {
  CharacterClass3[CharacterClass3["NONE"] = 0] = "NONE";
  CharacterClass3[CharacterClass3["BREAK_BEFORE"] = 1] = "BREAK_BEFORE";
  CharacterClass3[CharacterClass3["BREAK_AFTER"] = 2] = "BREAK_AFTER";
  CharacterClass3[CharacterClass3["BREAK_IDEOGRAPHIC"] = 3] = "BREAK_IDEOGRAPHIC";
})(CharacterClass || (CharacterClass = {}));
var WrappingCharacterClassifier = class extends $fE {
  constructor(BREAK_BEFORE, BREAK_AFTER) {
    super(
      0
      /* CharacterClass.NONE */
    );
    for (let i2 = 0; i2 < BREAK_BEFORE.length; i2++) {
      this.set(
        BREAK_BEFORE.charCodeAt(i2),
        1
        /* CharacterClass.BREAK_BEFORE */
      );
    }
    for (let i2 = 0; i2 < BREAK_AFTER.length; i2++) {
      this.set(
        BREAK_AFTER.charCodeAt(i2),
        2
        /* CharacterClass.BREAK_AFTER */
      );
    }
  }
  get(charCode) {
    if (charCode >= 0 && charCode < 256) {
      return this.a[charCode];
    } else {
      if (charCode >= 12352 && charCode <= 12543 || charCode >= 13312 && charCode <= 19903 || charCode >= 19968 && charCode <= 40959) {
        return 3;
      }
      return this.b.get(charCode) || this.c;
    }
  }
};
var arrPool1 = [];
var arrPool2 = [];
function createLineBreaksFromPreviousLineBreaks(classifier, previousBreakingData, lineText, tabSize, firstLineBreakColumn, columnsForFullWidthChar, wrappingIndent, wordBreak) {
  if (firstLineBreakColumn === -1) {
    return null;
  }
  const len = lineText.length;
  if (len <= 1) {
    return null;
  }
  const isKeepAll = wordBreak === "keepAll";
  const prevBreakingOffsets = previousBreakingData.breakOffsets;
  const prevBreakingOffsetsVisibleColumn = previousBreakingData.breakOffsetsVisibleColumn;
  const wrappedTextIndentLength = computeWrappedTextIndentLength(lineText, tabSize, firstLineBreakColumn, columnsForFullWidthChar, wrappingIndent);
  const wrappedLineBreakColumn = firstLineBreakColumn - wrappedTextIndentLength;
  const breakingOffsets = arrPool1;
  const breakingOffsetsVisibleColumn = arrPool2;
  let breakingOffsetsCount = 0;
  let lastBreakingOffset = 0;
  let lastBreakingOffsetVisibleColumn = 0;
  let breakingColumn = firstLineBreakColumn;
  const prevLen = prevBreakingOffsets.length;
  let prevIndex = 0;
  if (prevIndex >= 0) {
    let bestDistance = Math.abs(prevBreakingOffsetsVisibleColumn[prevIndex] - breakingColumn);
    while (prevIndex + 1 < prevLen) {
      const distance = Math.abs(prevBreakingOffsetsVisibleColumn[prevIndex + 1] - breakingColumn);
      if (distance >= bestDistance) {
        break;
      }
      bestDistance = distance;
      prevIndex++;
    }
  }
  while (prevIndex < prevLen) {
    let prevBreakOffset = prevIndex < 0 ? 0 : prevBreakingOffsets[prevIndex];
    let prevBreakOffsetVisibleColumn = prevIndex < 0 ? 0 : prevBreakingOffsetsVisibleColumn[prevIndex];
    if (lastBreakingOffset > prevBreakOffset) {
      prevBreakOffset = lastBreakingOffset;
      prevBreakOffsetVisibleColumn = lastBreakingOffsetVisibleColumn;
    }
    let breakOffset = 0;
    let breakOffsetVisibleColumn = 0;
    let forcedBreakOffset = 0;
    let forcedBreakOffsetVisibleColumn = 0;
    if (prevBreakOffsetVisibleColumn <= breakingColumn) {
      let visibleColumn = prevBreakOffsetVisibleColumn;
      let prevCharCode = prevBreakOffset === 0 ? 0 : lineText.charCodeAt(prevBreakOffset - 1);
      let prevCharCodeClass = prevBreakOffset === 0 ? 0 : classifier.get(prevCharCode);
      let entireLineFits = true;
      for (let i2 = prevBreakOffset; i2 < len; i2++) {
        const charStartOffset = i2;
        const charCode = lineText.charCodeAt(i2);
        let charCodeClass;
        let charWidth;
        if ($5f(charCode)) {
          i2++;
          charCodeClass = 0;
          charWidth = 2;
        } else {
          charCodeClass = classifier.get(charCode);
          charWidth = computeCharWidth(charCode, visibleColumn, tabSize, columnsForFullWidthChar);
        }
        if (charStartOffset > lastBreakingOffset && canBreak(prevCharCode, prevCharCodeClass, charCode, charCodeClass, isKeepAll)) {
          breakOffset = charStartOffset;
          breakOffsetVisibleColumn = visibleColumn;
        }
        visibleColumn += charWidth;
        if (visibleColumn > breakingColumn) {
          if (charStartOffset > lastBreakingOffset) {
            forcedBreakOffset = charStartOffset;
            forcedBreakOffsetVisibleColumn = visibleColumn - charWidth;
          } else {
            forcedBreakOffset = i2 + 1;
            forcedBreakOffsetVisibleColumn = visibleColumn;
          }
          if (visibleColumn - breakOffsetVisibleColumn > wrappedLineBreakColumn) {
            breakOffset = 0;
          }
          entireLineFits = false;
          break;
        }
        prevCharCode = charCode;
        prevCharCodeClass = charCodeClass;
      }
      if (entireLineFits) {
        if (breakingOffsetsCount > 0) {
          breakingOffsets[breakingOffsetsCount] = prevBreakingOffsets[prevBreakingOffsets.length - 1];
          breakingOffsetsVisibleColumn[breakingOffsetsCount] = prevBreakingOffsetsVisibleColumn[prevBreakingOffsets.length - 1];
          breakingOffsetsCount++;
        }
        break;
      }
    }
    if (breakOffset === 0) {
      let visibleColumn = prevBreakOffsetVisibleColumn;
      let charCode = lineText.charCodeAt(prevBreakOffset);
      let charCodeClass = classifier.get(charCode);
      let hitATabCharacter = false;
      for (let i2 = prevBreakOffset - 1; i2 >= lastBreakingOffset; i2--) {
        const charStartOffset = i2 + 1;
        const prevCharCode = lineText.charCodeAt(i2);
        if (prevCharCode === 9) {
          hitATabCharacter = true;
          break;
        }
        let prevCharCodeClass;
        let prevCharWidth;
        if ($6f(prevCharCode)) {
          i2--;
          prevCharCodeClass = 0;
          prevCharWidth = 2;
        } else {
          prevCharCodeClass = classifier.get(prevCharCode);
          prevCharWidth = $gg(prevCharCode) ? columnsForFullWidthChar : 1;
        }
        if (visibleColumn <= breakingColumn) {
          if (forcedBreakOffset === 0) {
            forcedBreakOffset = charStartOffset;
            forcedBreakOffsetVisibleColumn = visibleColumn;
          }
          if (visibleColumn <= breakingColumn - wrappedLineBreakColumn) {
            break;
          }
          if (canBreak(prevCharCode, prevCharCodeClass, charCode, charCodeClass, isKeepAll)) {
            breakOffset = charStartOffset;
            breakOffsetVisibleColumn = visibleColumn;
            break;
          }
        }
        visibleColumn -= prevCharWidth;
        charCode = prevCharCode;
        charCodeClass = prevCharCodeClass;
      }
      if (breakOffset !== 0) {
        const remainingWidthOfNextLine = wrappedLineBreakColumn - (forcedBreakOffsetVisibleColumn - breakOffsetVisibleColumn);
        if (remainingWidthOfNextLine <= tabSize) {
          const charCodeAtForcedBreakOffset = lineText.charCodeAt(forcedBreakOffset);
          let charWidth;
          if ($5f(charCodeAtForcedBreakOffset)) {
            charWidth = 2;
          } else {
            charWidth = computeCharWidth(charCodeAtForcedBreakOffset, forcedBreakOffsetVisibleColumn, tabSize, columnsForFullWidthChar);
          }
          if (remainingWidthOfNextLine - charWidth < 0) {
            breakOffset = 0;
          }
        }
      }
      if (hitATabCharacter) {
        prevIndex--;
        continue;
      }
    }
    if (breakOffset === 0) {
      breakOffset = forcedBreakOffset;
      breakOffsetVisibleColumn = forcedBreakOffsetVisibleColumn;
    }
    if (breakOffset <= lastBreakingOffset) {
      const charCode = lineText.charCodeAt(lastBreakingOffset);
      if ($5f(charCode)) {
        breakOffset = lastBreakingOffset + 2;
        breakOffsetVisibleColumn = lastBreakingOffsetVisibleColumn + 2;
      } else {
        breakOffset = lastBreakingOffset + 1;
        breakOffsetVisibleColumn = lastBreakingOffsetVisibleColumn + computeCharWidth(charCode, lastBreakingOffsetVisibleColumn, tabSize, columnsForFullWidthChar);
      }
    }
    lastBreakingOffset = breakOffset;
    breakingOffsets[breakingOffsetsCount] = breakOffset;
    lastBreakingOffsetVisibleColumn = breakOffsetVisibleColumn;
    breakingOffsetsVisibleColumn[breakingOffsetsCount] = breakOffsetVisibleColumn;
    breakingOffsetsCount++;
    breakingColumn = breakOffsetVisibleColumn + wrappedLineBreakColumn;
    while (prevIndex < 0 || prevIndex < prevLen && prevBreakingOffsetsVisibleColumn[prevIndex] < breakOffsetVisibleColumn) {
      prevIndex++;
    }
    let bestDistance = Math.abs(prevBreakingOffsetsVisibleColumn[prevIndex] - breakingColumn);
    while (prevIndex + 1 < prevLen) {
      const distance = Math.abs(prevBreakingOffsetsVisibleColumn[prevIndex + 1] - breakingColumn);
      if (distance >= bestDistance) {
        break;
      }
      bestDistance = distance;
      prevIndex++;
    }
  }
  if (breakingOffsetsCount === 0) {
    return null;
  }
  breakingOffsets.length = breakingOffsetsCount;
  breakingOffsetsVisibleColumn.length = breakingOffsetsCount;
  arrPool1 = previousBreakingData.breakOffsets;
  arrPool2 = previousBreakingData.breakOffsetsVisibleColumn;
  previousBreakingData.breakOffsets = breakingOffsets;
  previousBreakingData.breakOffsetsVisibleColumn = breakingOffsetsVisibleColumn;
  previousBreakingData.wrappedTextIndentLength = wrappedTextIndentLength;
  return previousBreakingData;
}
function createLineBreaks2(classifier, _lineText, injectedTexts, tabSize, firstLineBreakColumn, columnsForFullWidthChar, wrappingIndent, wordBreak) {
  const lineText = $FE.applyInjectedText(_lineText, injectedTexts);
  let injectionOptions;
  let injectionOffsets;
  if (injectedTexts && injectedTexts.length > 0) {
    injectionOptions = injectedTexts.map((t) => t.options);
    injectionOffsets = injectedTexts.map((text2) => text2.column - 1);
  } else {
    injectionOptions = null;
    injectionOffsets = null;
  }
  if (firstLineBreakColumn === -1) {
    if (!injectionOptions) {
      return null;
    }
    return new $a5(injectionOffsets, injectionOptions, [lineText.length], [], 0);
  }
  const len = lineText.length;
  if (len <= 1) {
    if (!injectionOptions) {
      return null;
    }
    return new $a5(injectionOffsets, injectionOptions, [lineText.length], [], 0);
  }
  const isKeepAll = wordBreak === "keepAll";
  const wrappedTextIndentLength = computeWrappedTextIndentLength(lineText, tabSize, firstLineBreakColumn, columnsForFullWidthChar, wrappingIndent);
  const wrappedLineBreakColumn = firstLineBreakColumn - wrappedTextIndentLength;
  const breakingOffsets = [];
  const breakingOffsetsVisibleColumn = [];
  let breakingOffsetsCount = 0;
  let breakOffset = 0;
  let breakOffsetVisibleColumn = 0;
  let breakingColumn = firstLineBreakColumn;
  let prevCharCode = lineText.charCodeAt(0);
  let prevCharCodeClass = classifier.get(prevCharCode);
  let visibleColumn = computeCharWidth(prevCharCode, 0, tabSize, columnsForFullWidthChar);
  let startOffset = 1;
  if ($5f(prevCharCode)) {
    visibleColumn += 1;
    prevCharCode = lineText.charCodeAt(1);
    prevCharCodeClass = classifier.get(prevCharCode);
    startOffset++;
  }
  for (let i2 = startOffset; i2 < len; i2++) {
    const charStartOffset = i2;
    const charCode = lineText.charCodeAt(i2);
    let charCodeClass;
    let charWidth;
    if ($5f(charCode)) {
      i2++;
      charCodeClass = 0;
      charWidth = 2;
    } else {
      charCodeClass = classifier.get(charCode);
      charWidth = computeCharWidth(charCode, visibleColumn, tabSize, columnsForFullWidthChar);
    }
    if (canBreak(prevCharCode, prevCharCodeClass, charCode, charCodeClass, isKeepAll)) {
      breakOffset = charStartOffset;
      breakOffsetVisibleColumn = visibleColumn;
    }
    visibleColumn += charWidth;
    if (visibleColumn > breakingColumn) {
      if (breakOffset === 0 || visibleColumn - breakOffsetVisibleColumn > wrappedLineBreakColumn) {
        breakOffset = charStartOffset;
        breakOffsetVisibleColumn = visibleColumn - charWidth;
      }
      breakingOffsets[breakingOffsetsCount] = breakOffset;
      breakingOffsetsVisibleColumn[breakingOffsetsCount] = breakOffsetVisibleColumn;
      breakingOffsetsCount++;
      breakingColumn = breakOffsetVisibleColumn + wrappedLineBreakColumn;
      breakOffset = 0;
    }
    prevCharCode = charCode;
    prevCharCodeClass = charCodeClass;
  }
  if (breakingOffsetsCount === 0 && (!injectedTexts || injectedTexts.length === 0)) {
    return null;
  }
  breakingOffsets[breakingOffsetsCount] = len;
  breakingOffsetsVisibleColumn[breakingOffsetsCount] = visibleColumn;
  return new $a5(injectionOffsets, injectionOptions, breakingOffsets, breakingOffsetsVisibleColumn, wrappedTextIndentLength);
}
function computeCharWidth(charCode, visibleColumn, tabSize, columnsForFullWidthChar) {
  if (charCode === 9) {
    return tabSize - visibleColumn % tabSize;
  }
  if ($gg(charCode)) {
    return columnsForFullWidthChar;
  }
  if (charCode < 32) {
    return columnsForFullWidthChar;
  }
  return 1;
}
function tabCharacterWidth(visibleColumn, tabSize) {
  return tabSize - visibleColumn % tabSize;
}
function canBreak(prevCharCode, prevCharCodeClass, charCode, charCodeClass, isKeepAll) {
  return charCode !== 32 && (prevCharCodeClass === 2 && charCodeClass !== 2 || prevCharCodeClass !== 1 && charCodeClass === 1 || !isKeepAll && prevCharCodeClass === 3 && charCodeClass !== 2 || !isKeepAll && charCodeClass === 3 && prevCharCodeClass !== 1);
}
function computeWrappedTextIndentLength(lineText, tabSize, firstLineBreakColumn, columnsForFullWidthChar, wrappingIndent) {
  let wrappedTextIndentLength = 0;
  if (wrappingIndent !== 0) {
    const firstNonWhitespaceIndex = $Of(lineText);
    if (firstNonWhitespaceIndex !== -1) {
      for (let i2 = 0; i2 < firstNonWhitespaceIndex; i2++) {
        const charWidth = lineText.charCodeAt(i2) === 9 ? tabCharacterWidth(wrappedTextIndentLength, tabSize) : 1;
        wrappedTextIndentLength += charWidth;
      }
      const numberOfAdditionalTabs = wrappingIndent === 3 ? 2 : wrappingIndent === 2 ? 1 : 0;
      for (let i2 = 0; i2 < numberOfAdditionalTabs; i2++) {
        const charWidth = tabCharacterWidth(wrappedTextIndentLength, tabSize);
        wrappedTextIndentLength += charWidth;
      }
      if (wrappedTextIndentLength + columnsForFullWidthChar > firstLineBreakColumn) {
        wrappedTextIndentLength = 0;
      }
    }
  }
  return wrappedTextIndentLength;
}

// out-build/vs/editor/common/cursor/oneCursor.js
var $78 = class _$78 {
  constructor(context) {
    this.a = null;
    this.b = true;
    this.g(context, new $h5(new $9C(1, 1, 1, 1), 0, 0, new $8C(1, 1), 0), new $h5(new $9C(1, 1, 1, 1), 0, 0, new $8C(1, 1), 0));
  }
  dispose(context) {
    this.d(context);
  }
  startTrackingSelection(context) {
    this.b = true;
    this.c(context);
  }
  stopTrackingSelection(context) {
    this.b = false;
    this.d(context);
  }
  c(context) {
    if (!this.b) {
      return;
    }
    this.a = context.model._setTrackedRange(
      this.a,
      this.modelState.selection,
      0
      /* TrackedRangeStickiness.AlwaysGrowsWhenTypingAtEdges */
    );
  }
  d(context) {
    this.a = context.model._setTrackedRange(
      this.a,
      null,
      0
      /* TrackedRangeStickiness.AlwaysGrowsWhenTypingAtEdges */
    );
  }
  asCursorState() {
    return new $e5(this.modelState, this.viewState);
  }
  readSelectionFromMarkers(context) {
    const range = context.model._getTrackedRange(this.a);
    if (this.modelState.selection.isEmpty() && !range.isEmpty()) {
      return $_D.fromRange(range.collapseToEnd(), this.modelState.selection.getDirection());
    }
    return $_D.fromRange(range, this.modelState.selection.getDirection());
  }
  ensureValidState(context) {
    this.g(context, this.modelState, this.viewState);
  }
  setState(context, modelState, viewState) {
    this.g(context, modelState, viewState);
  }
  static e(viewModel, position, cacheInput, cacheOutput) {
    if (position.equals(cacheInput)) {
      return cacheOutput;
    }
    return viewModel.normalizePosition(
      position,
      2
      /* PositionAffinity.None */
    );
  }
  static f(viewModel, viewState) {
    const position = viewState.position;
    const sStartPosition = viewState.selectionStart.getStartPosition();
    const sEndPosition = viewState.selectionStart.getEndPosition();
    const validPosition = viewModel.normalizePosition(
      position,
      2
      /* PositionAffinity.None */
    );
    const validSStartPosition = this.e(viewModel, sStartPosition, position, validPosition);
    const validSEndPosition = this.e(viewModel, sEndPosition, sStartPosition, validSStartPosition);
    if (position.equals(validPosition) && sStartPosition.equals(validSStartPosition) && sEndPosition.equals(validSEndPosition)) {
      return viewState;
    }
    return new $h5($9C.fromPositions(validSStartPosition, validSEndPosition), viewState.selectionStartKind, viewState.selectionStartLeftoverVisibleColumns + sStartPosition.column - validSStartPosition.column, validPosition, viewState.leftoverVisibleColumns + position.column - validPosition.column);
  }
  g(context, modelState, viewState) {
    if (viewState) {
      viewState = _$78.f(context.viewModel, viewState);
    }
    if (!modelState) {
      if (!viewState) {
        return;
      }
      const selectionStart = context.model.validateRange(context.coordinatesConverter.convertViewRangeToModelRange(viewState.selectionStart));
      const position = context.model.validatePosition(context.coordinatesConverter.convertViewPositionToModelPosition(viewState.position));
      modelState = new $h5(selectionStart, viewState.selectionStartKind, viewState.selectionStartLeftoverVisibleColumns, position, viewState.leftoverVisibleColumns);
    } else {
      const selectionStart = context.model.validateRange(modelState.selectionStart);
      const selectionStartLeftoverVisibleColumns = modelState.selectionStart.equalsRange(selectionStart) ? modelState.selectionStartLeftoverVisibleColumns : 0;
      const position = context.model.validatePosition(modelState.position);
      const leftoverVisibleColumns = modelState.position.equals(position) ? modelState.leftoverVisibleColumns : 0;
      modelState = new $h5(selectionStart, modelState.selectionStartKind, selectionStartLeftoverVisibleColumns, position, leftoverVisibleColumns);
    }
    if (!viewState) {
      const viewSelectionStart1 = context.coordinatesConverter.convertModelPositionToViewPosition(new $8C(modelState.selectionStart.startLineNumber, modelState.selectionStart.startColumn));
      const viewSelectionStart2 = context.coordinatesConverter.convertModelPositionToViewPosition(new $8C(modelState.selectionStart.endLineNumber, modelState.selectionStart.endColumn));
      const viewSelectionStart = new $9C(viewSelectionStart1.lineNumber, viewSelectionStart1.column, viewSelectionStart2.lineNumber, viewSelectionStart2.column);
      const viewPosition = context.coordinatesConverter.convertModelPositionToViewPosition(modelState.position);
      viewState = new $h5(viewSelectionStart, modelState.selectionStartKind, modelState.selectionStartLeftoverVisibleColumns, viewPosition, modelState.leftoverVisibleColumns);
    } else {
      const viewSelectionStart = context.coordinatesConverter.validateViewRange(viewState.selectionStart, modelState.selectionStart);
      const viewPosition = context.coordinatesConverter.validateViewPosition(viewState.position, modelState.position);
      viewState = new $h5(viewSelectionStart, modelState.selectionStartKind, modelState.selectionStartLeftoverVisibleColumns, viewPosition, modelState.leftoverVisibleColumns);
    }
    this.modelState = modelState;
    this.viewState = viewState;
    this.c(context);
  }
};

// out-build/vs/editor/common/cursor/cursorCollection.js
var $88 = class {
  constructor(context) {
    this.a = context;
    this.b = [new $78(context)];
    this.d = 0;
  }
  dispose() {
    for (const cursor of this.b) {
      cursor.dispose(this.a);
    }
  }
  startTrackingSelections() {
    for (const cursor of this.b) {
      cursor.startTrackingSelection(this.a);
    }
  }
  stopTrackingSelections() {
    for (const cursor of this.b) {
      cursor.stopTrackingSelection(this.a);
    }
  }
  updateContext(context) {
    this.a = context;
  }
  ensureValidState() {
    for (const cursor of this.b) {
      cursor.ensureValidState(this.a);
    }
  }
  readSelectionFromMarkers() {
    return this.b.map((c) => c.readSelectionFromMarkers(this.a));
  }
  getAll() {
    return this.b.map((c) => c.asCursorState());
  }
  getViewPositions() {
    return this.b.map((c) => c.viewState.position);
  }
  getTopMostViewPosition() {
    return $$(this.b, $9b((c) => c.viewState.position, $8C.compare)).viewState.position;
  }
  getBottomMostViewPosition() {
    return $0(this.b, $9b((c) => c.viewState.position, $8C.compare)).viewState.position;
  }
  getSelections() {
    return this.b.map((c) => c.modelState.selection);
  }
  getViewSelections() {
    return this.b.map((c) => c.viewState.selection);
  }
  setSelections(selections) {
    this.setStates($e5.fromModelSelections(selections));
  }
  getPrimaryCursor() {
    return this.b[0].asCursorState();
  }
  setStates(states) {
    if (states === null) {
      return;
    }
    this.b[0].setState(this.a, states[0].modelState, states[0].viewState);
    this.e(states.slice(1));
  }
  /**
   * Creates or disposes secondary cursors as necessary to match the number of `secondarySelections`.
   */
  e(secondaryStates) {
    const secondaryCursorsLength = this.b.length - 1;
    const secondaryStatesLength = secondaryStates.length;
    if (secondaryCursorsLength < secondaryStatesLength) {
      const createCnt = secondaryStatesLength - secondaryCursorsLength;
      for (let i2 = 0; i2 < createCnt; i2++) {
        this.f();
      }
    } else if (secondaryCursorsLength > secondaryStatesLength) {
      const removeCnt = secondaryCursorsLength - secondaryStatesLength;
      for (let i2 = 0; i2 < removeCnt; i2++) {
        this.g(this.b.length - 2);
      }
    }
    for (let i2 = 0; i2 < secondaryStatesLength; i2++) {
      this.b[i2 + 1].setState(this.a, secondaryStates[i2].modelState, secondaryStates[i2].viewState);
    }
  }
  killSecondaryCursors() {
    this.e([]);
  }
  f() {
    this.b.push(new $78(this.a));
    this.d = this.b.length - 1;
  }
  getLastAddedCursorIndex() {
    if (this.b.length === 1 || this.d === 0) {
      return 0;
    }
    return this.d;
  }
  g(removeIndex) {
    if (this.d >= removeIndex + 1) {
      this.d--;
    }
    this.b[removeIndex + 1].dispose(this.a);
    this.b.splice(removeIndex + 1, 1);
  }
  normalize() {
    if (this.b.length === 1) {
      return;
    }
    const cursors = this.b.slice(0);
    const sortedCursors = [];
    for (let i2 = 0, len = cursors.length; i2 < len; i2++) {
      sortedCursors.push({
        index: i2,
        selection: cursors[i2].modelState.selection
      });
    }
    sortedCursors.sort($9b((s) => s.selection, $9C.compareRangesUsingStarts));
    for (let sortedCursorIndex = 0; sortedCursorIndex < sortedCursors.length - 1; sortedCursorIndex++) {
      const current = sortedCursors[sortedCursorIndex];
      const next = sortedCursors[sortedCursorIndex + 1];
      const currentSelection = current.selection;
      const nextSelection = next.selection;
      if (!this.a.cursorConfig.multiCursorMergeOverlapping) {
        continue;
      }
      let shouldMergeCursors;
      if (nextSelection.isEmpty() || currentSelection.isEmpty()) {
        shouldMergeCursors = nextSelection.getStartPosition().isBeforeOrEqual(currentSelection.getEndPosition());
      } else {
        shouldMergeCursors = nextSelection.getStartPosition().isBefore(currentSelection.getEndPosition());
      }
      if (shouldMergeCursors) {
        const winnerSortedCursorIndex = current.index < next.index ? sortedCursorIndex : sortedCursorIndex + 1;
        const looserSortedCursorIndex = current.index < next.index ? sortedCursorIndex + 1 : sortedCursorIndex;
        const looserIndex = sortedCursors[looserSortedCursorIndex].index;
        const winnerIndex = sortedCursors[winnerSortedCursorIndex].index;
        const looserSelection = sortedCursors[looserSortedCursorIndex].selection;
        const winnerSelection = sortedCursors[winnerSortedCursorIndex].selection;
        if (!looserSelection.equalsSelection(winnerSelection)) {
          const resultingRange = looserSelection.plusRange(winnerSelection);
          const looserSelectionIsLTR = looserSelection.selectionStartLineNumber === looserSelection.startLineNumber && looserSelection.selectionStartColumn === looserSelection.startColumn;
          const winnerSelectionIsLTR = winnerSelection.selectionStartLineNumber === winnerSelection.startLineNumber && winnerSelection.selectionStartColumn === winnerSelection.startColumn;
          let resultingSelectionIsLTR;
          if (looserIndex === this.d) {
            resultingSelectionIsLTR = looserSelectionIsLTR;
            this.d = winnerIndex;
          } else {
            resultingSelectionIsLTR = winnerSelectionIsLTR;
          }
          let resultingSelection;
          if (resultingSelectionIsLTR) {
            resultingSelection = new $_D(resultingRange.startLineNumber, resultingRange.startColumn, resultingRange.endLineNumber, resultingRange.endColumn);
          } else {
            resultingSelection = new $_D(resultingRange.endLineNumber, resultingRange.endColumn, resultingRange.startLineNumber, resultingRange.startColumn);
          }
          sortedCursors[winnerSortedCursorIndex].selection = resultingSelection;
          const resultingState = $e5.fromModelSelection(resultingSelection);
          cursors[winnerIndex].setState(this.a, resultingState.modelState, resultingState.viewState);
        }
        for (const sortedCursor of sortedCursors) {
          if (sortedCursor.index > looserIndex) {
            sortedCursor.index--;
          }
        }
        cursors.splice(looserIndex, 1);
        sortedCursors.splice(looserSortedCursorIndex, 1);
        this.g(looserIndex - 1);
        sortedCursorIndex--;
      }
    }
  }
};

// out-build/vs/editor/common/cursor/cursorContext.js
var $68 = class {
  constructor(model, viewModel, coordinatesConverter, cursorConfig) {
    this._cursorContextBrand = void 0;
    this.model = model;
    this.viewModel = viewModel;
    this.coordinatesConverter = coordinatesConverter;
    this.cursorConfig = cursorConfig;
  }
};

// out-build/vs/editor/common/viewEvents.js
var ViewEventType;
(function(ViewEventType2) {
  ViewEventType2[ViewEventType2["ViewCompositionStart"] = 0] = "ViewCompositionStart";
  ViewEventType2[ViewEventType2["ViewCompositionEnd"] = 1] = "ViewCompositionEnd";
  ViewEventType2[ViewEventType2["ViewConfigurationChanged"] = 2] = "ViewConfigurationChanged";
  ViewEventType2[ViewEventType2["ViewCursorStateChanged"] = 3] = "ViewCursorStateChanged";
  ViewEventType2[ViewEventType2["ViewDecorationsChanged"] = 4] = "ViewDecorationsChanged";
  ViewEventType2[ViewEventType2["ViewFlushed"] = 5] = "ViewFlushed";
  ViewEventType2[ViewEventType2["ViewFocusChanged"] = 6] = "ViewFocusChanged";
  ViewEventType2[ViewEventType2["ViewLanguageConfigurationChanged"] = 7] = "ViewLanguageConfigurationChanged";
  ViewEventType2[ViewEventType2["ViewLineMappingChanged"] = 8] = "ViewLineMappingChanged";
  ViewEventType2[ViewEventType2["ViewLinesChanged"] = 9] = "ViewLinesChanged";
  ViewEventType2[ViewEventType2["ViewLinesDeleted"] = 10] = "ViewLinesDeleted";
  ViewEventType2[ViewEventType2["ViewLinesInserted"] = 11] = "ViewLinesInserted";
  ViewEventType2[ViewEventType2["ViewRevealRangeRequest"] = 12] = "ViewRevealRangeRequest";
  ViewEventType2[ViewEventType2["ViewScrollChanged"] = 13] = "ViewScrollChanged";
  ViewEventType2[ViewEventType2["ViewThemeChanged"] = 14] = "ViewThemeChanged";
  ViewEventType2[ViewEventType2["ViewTokensChanged"] = 15] = "ViewTokensChanged";
  ViewEventType2[ViewEventType2["ViewTokensColorsChanged"] = 16] = "ViewTokensColorsChanged";
  ViewEventType2[ViewEventType2["ViewZonesChanged"] = 17] = "ViewZonesChanged";
})(ViewEventType || (ViewEventType = {}));
var $l5 = class {
  constructor() {
    this.type = 0;
  }
};
var $m5 = class {
  constructor() {
    this.type = 1;
  }
};
var $n5 = class {
  constructor(source) {
    this.type = 2;
    this._source = source;
  }
  hasChanged(id2) {
    return this._source.hasChanged(id2);
  }
};
var $o5 = class {
  constructor(selections, modelSelections, reason) {
    this.selections = selections;
    this.modelSelections = modelSelections;
    this.reason = reason;
    this.type = 3;
  }
};
var $p5 = class {
  constructor(source) {
    this.type = 4;
    if (source) {
      this.affectsMinimap = source.affectsMinimap;
      this.affectsOverviewRuler = source.affectsOverviewRuler;
      this.affectsGlyphMargin = source.affectsGlyphMargin;
      this.affectsLineNumber = source.affectsLineNumber;
    } else {
      this.affectsMinimap = true;
      this.affectsOverviewRuler = true;
      this.affectsGlyphMargin = true;
      this.affectsLineNumber = true;
    }
  }
};
var $q5 = class {
  constructor() {
    this.type = 5;
  }
};
var $r5 = class {
  constructor(isFocused) {
    this.type = 6;
    this.isFocused = isFocused;
  }
};
var $s5 = class {
  constructor() {
    this.type = 7;
  }
};
var $t5 = class {
  constructor() {
    this.type = 8;
  }
};
var $u5 = class {
  constructor(fromLineNumber, count) {
    this.fromLineNumber = fromLineNumber;
    this.count = count;
    this.type = 9;
  }
};
var $v5 = class {
  constructor(fromLineNumber, toLineNumber) {
    this.type = 10;
    this.fromLineNumber = fromLineNumber;
    this.toLineNumber = toLineNumber;
  }
};
var $w5 = class {
  constructor(fromLineNumber, toLineNumber) {
    this.type = 11;
    this.fromLineNumber = fromLineNumber;
    this.toLineNumber = toLineNumber;
  }
};
var VerticalRevealType;
(function(VerticalRevealType2) {
  VerticalRevealType2[VerticalRevealType2["Simple"] = 0] = "Simple";
  VerticalRevealType2[VerticalRevealType2["Center"] = 1] = "Center";
  VerticalRevealType2[VerticalRevealType2["CenterIfOutsideViewport"] = 2] = "CenterIfOutsideViewport";
  VerticalRevealType2[VerticalRevealType2["Top"] = 3] = "Top";
  VerticalRevealType2[VerticalRevealType2["Bottom"] = 4] = "Bottom";
  VerticalRevealType2[VerticalRevealType2["NearTop"] = 5] = "NearTop";
  VerticalRevealType2[VerticalRevealType2["NearTopIfOutsideViewport"] = 6] = "NearTopIfOutsideViewport";
})(VerticalRevealType || (VerticalRevealType = {}));
var $x5 = class {
  constructor(source, minimalReveal, range, selections, verticalType, revealHorizontal, scrollType) {
    this.source = source;
    this.minimalReveal = minimalReveal;
    this.range = range;
    this.selections = selections;
    this.verticalType = verticalType;
    this.revealHorizontal = revealHorizontal;
    this.scrollType = scrollType;
    this.type = 12;
  }
};
var $y5 = class {
  constructor(source) {
    this.type = 13;
    this.scrollWidth = source.scrollWidth;
    this.scrollLeft = source.scrollLeft;
    this.scrollHeight = source.scrollHeight;
    this.scrollTop = source.scrollTop;
    this.scrollWidthChanged = source.scrollWidthChanged;
    this.scrollLeftChanged = source.scrollLeftChanged;
    this.scrollHeightChanged = source.scrollHeightChanged;
    this.scrollTopChanged = source.scrollTopChanged;
  }
};
var $z5 = class {
  constructor(theme) {
    this.theme = theme;
    this.type = 14;
  }
};
var $A5 = class {
  constructor(ranges) {
    this.type = 15;
    this.ranges = ranges;
  }
};
var $B5 = class {
  constructor() {
    this.type = 16;
  }
};
var $C5 = class {
  constructor() {
    this.type = 17;
  }
};

// out-build/vs/editor/common/viewModelEventDispatcher.js
var $98 = class extends $3c {
  constructor() {
    super();
    this.c = this.B(new $ze());
    this.onEvent = this.c.event;
    this.f = [];
    this.g = null;
    this.h = false;
    this.j = null;
    this.m = 0;
    this.n = [];
  }
  emitOutgoingEvent(e) {
    this.r(e);
    this.s();
  }
  r(e) {
    for (let i2 = 0, len = this.n.length; i2 < len; i2++) {
      const mergeResult = this.n[i2].kind === e.kind ? this.n[i2].attemptToMerge(e) : null;
      if (mergeResult) {
        this.n[i2] = mergeResult;
        return;
      }
    }
    this.n.push(e);
  }
  s() {
    while (this.n.length > 0) {
      if (this.j || this.h) {
        return;
      }
      const event = this.n.shift();
      if (event.isNoOp()) {
        continue;
      }
      this.c.fire(event);
    }
  }
  addViewEventHandler(eventHandler) {
    for (let i2 = 0, len = this.f.length; i2 < len; i2++) {
      if (this.f[i2] === eventHandler) {
        console.warn("Detected duplicate listener in ViewEventDispatcher", eventHandler);
      }
    }
    this.f.push(eventHandler);
  }
  removeViewEventHandler(eventHandler) {
    for (let i2 = 0; i2 < this.f.length; i2++) {
      if (this.f[i2] === eventHandler) {
        this.f.splice(i2, 1);
        break;
      }
    }
  }
  beginEmitViewEvents() {
    this.m++;
    if (this.m === 1) {
      this.j = new $08();
    }
    return this.j;
  }
  endEmitViewEvents() {
    this.m--;
    if (this.m === 0) {
      const outgoingEvents = this.j.outgoingEvents;
      const viewEvents = this.j.viewEvents;
      this.j = null;
      for (const outgoingEvent of outgoingEvents) {
        this.r(outgoingEvent);
      }
      if (viewEvents.length > 0) {
        this.t(viewEvents);
      }
    }
    this.s();
  }
  emitSingleViewEvent(event) {
    try {
      const eventsCollector = this.beginEmitViewEvents();
      eventsCollector.emitViewEvent(event);
    } finally {
      this.endEmitViewEvents();
    }
  }
  t(events) {
    if (this.g) {
      this.g = this.g.concat(events);
    } else {
      this.g = events;
    }
    if (!this.h) {
      this.u();
    }
  }
  u() {
    try {
      this.h = true;
      this.w();
    } finally {
      this.h = false;
    }
  }
  w() {
    while (this.g) {
      const events = this.g;
      this.g = null;
      const eventHandlers = this.f.slice(0);
      for (const eventHandler of eventHandlers) {
        eventHandler.handleEvents(events);
      }
    }
  }
};
var $08 = class {
  constructor() {
    this.viewEvents = [];
    this.outgoingEvents = [];
  }
  emitViewEvent(event) {
    this.viewEvents.push(event);
  }
  emitOutgoingEvent(e) {
    this.outgoingEvents.push(e);
  }
};
var OutgoingViewModelEventKind;
(function(OutgoingViewModelEventKind2) {
  OutgoingViewModelEventKind2[OutgoingViewModelEventKind2["ContentSizeChanged"] = 0] = "ContentSizeChanged";
  OutgoingViewModelEventKind2[OutgoingViewModelEventKind2["FocusChanged"] = 1] = "FocusChanged";
  OutgoingViewModelEventKind2[OutgoingViewModelEventKind2["ScrollChanged"] = 2] = "ScrollChanged";
  OutgoingViewModelEventKind2[OutgoingViewModelEventKind2["ViewZonesChanged"] = 3] = "ViewZonesChanged";
  OutgoingViewModelEventKind2[OutgoingViewModelEventKind2["HiddenAreasChanged"] = 4] = "HiddenAreasChanged";
  OutgoingViewModelEventKind2[OutgoingViewModelEventKind2["ReadOnlyEditAttempt"] = 5] = "ReadOnlyEditAttempt";
  OutgoingViewModelEventKind2[OutgoingViewModelEventKind2["CursorStateChanged"] = 6] = "CursorStateChanged";
  OutgoingViewModelEventKind2[OutgoingViewModelEventKind2["ModelDecorationsChanged"] = 7] = "ModelDecorationsChanged";
  OutgoingViewModelEventKind2[OutgoingViewModelEventKind2["ModelLanguageChanged"] = 8] = "ModelLanguageChanged";
  OutgoingViewModelEventKind2[OutgoingViewModelEventKind2["ModelLanguageConfigurationChanged"] = 9] = "ModelLanguageConfigurationChanged";
  OutgoingViewModelEventKind2[OutgoingViewModelEventKind2["ModelContentChanged"] = 10] = "ModelContentChanged";
  OutgoingViewModelEventKind2[OutgoingViewModelEventKind2["ModelOptionsChanged"] = 11] = "ModelOptionsChanged";
  OutgoingViewModelEventKind2[OutgoingViewModelEventKind2["ModelTokensChanged"] = 12] = "ModelTokensChanged";
})(OutgoingViewModelEventKind || (OutgoingViewModelEventKind = {}));
var $$8 = class _$$8 {
  constructor(oldContentWidth, oldContentHeight, contentWidth, contentHeight) {
    this.kind = 0;
    this.c = oldContentWidth;
    this.d = oldContentHeight;
    this.contentWidth = contentWidth;
    this.contentHeight = contentHeight;
    this.contentWidthChanged = this.c !== this.contentWidth;
    this.contentHeightChanged = this.d !== this.contentHeight;
  }
  isNoOp() {
    return !this.contentWidthChanged && !this.contentHeightChanged;
  }
  attemptToMerge(other) {
    if (other.kind !== this.kind) {
      return null;
    }
    return new _$$8(this.c, this.d, other.contentWidth, other.contentHeight);
  }
};
var $_8 = class _$_8 {
  constructor(oldHasFocus, hasFocus) {
    this.kind = 1;
    this.oldHasFocus = oldHasFocus;
    this.hasFocus = hasFocus;
  }
  isNoOp() {
    return this.oldHasFocus === this.hasFocus;
  }
  attemptToMerge(other) {
    if (other.kind !== this.kind) {
      return null;
    }
    return new _$_8(this.oldHasFocus, other.hasFocus);
  }
};
var $a9 = class _$a9 {
  constructor(oldScrollWidth, oldScrollLeft, oldScrollHeight, oldScrollTop, scrollWidth, scrollLeft, scrollHeight, scrollTop) {
    this.kind = 2;
    this.c = oldScrollWidth;
    this.d = oldScrollLeft;
    this.f = oldScrollHeight;
    this.g = oldScrollTop;
    this.scrollWidth = scrollWidth;
    this.scrollLeft = scrollLeft;
    this.scrollHeight = scrollHeight;
    this.scrollTop = scrollTop;
    this.scrollWidthChanged = this.c !== this.scrollWidth;
    this.scrollLeftChanged = this.d !== this.scrollLeft;
    this.scrollHeightChanged = this.f !== this.scrollHeight;
    this.scrollTopChanged = this.g !== this.scrollTop;
  }
  isNoOp() {
    return !this.scrollWidthChanged && !this.scrollLeftChanged && !this.scrollHeightChanged && !this.scrollTopChanged;
  }
  attemptToMerge(other) {
    if (other.kind !== this.kind) {
      return null;
    }
    return new _$a9(this.c, this.d, this.f, this.g, other.scrollWidth, other.scrollLeft, other.scrollHeight, other.scrollTop);
  }
};
var $b9 = class {
  constructor() {
    this.kind = 3;
  }
  isNoOp() {
    return false;
  }
  attemptToMerge(other) {
    if (other.kind !== this.kind) {
      return null;
    }
    return this;
  }
};
var $c9 = class {
  constructor() {
    this.kind = 4;
  }
  isNoOp() {
    return false;
  }
  attemptToMerge(other) {
    if (other.kind !== this.kind) {
      return null;
    }
    return this;
  }
};
var $d9 = class _$d9 {
  constructor(oldSelections, selections, oldModelVersionId, modelVersionId, source, reason, reachedMaxCursorCount) {
    this.kind = 6;
    this.oldSelections = oldSelections;
    this.selections = selections;
    this.oldModelVersionId = oldModelVersionId;
    this.modelVersionId = modelVersionId;
    this.source = source;
    this.reason = reason;
    this.reachedMaxCursorCount = reachedMaxCursorCount;
  }
  static c(a, b) {
    if (!a && !b) {
      return true;
    }
    if (!a || !b) {
      return false;
    }
    const aLen = a.length;
    const bLen = b.length;
    if (aLen !== bLen) {
      return false;
    }
    for (let i2 = 0; i2 < aLen; i2++) {
      if (!a[i2].equalsSelection(b[i2])) {
        return false;
      }
    }
    return true;
  }
  isNoOp() {
    return _$d9.c(this.oldSelections, this.selections) && this.oldModelVersionId === this.modelVersionId;
  }
  attemptToMerge(other) {
    if (other.kind !== this.kind) {
      return null;
    }
    return new _$d9(this.oldSelections, other.selections, this.oldModelVersionId, other.modelVersionId, other.source, other.reason, this.reachedMaxCursorCount || other.reachedMaxCursorCount);
  }
};
var $e9 = class {
  constructor() {
    this.kind = 5;
  }
  isNoOp() {
    return false;
  }
  attemptToMerge(other) {
    if (other.kind !== this.kind) {
      return null;
    }
    return this;
  }
};
var $f9 = class {
  constructor(event) {
    this.event = event;
    this.kind = 7;
  }
  isNoOp() {
    return false;
  }
  attemptToMerge(other) {
    return null;
  }
};
var $g9 = class {
  constructor(event) {
    this.event = event;
    this.kind = 8;
  }
  isNoOp() {
    return false;
  }
  attemptToMerge(other) {
    return null;
  }
};
var $h9 = class {
  constructor(event) {
    this.event = event;
    this.kind = 9;
  }
  isNoOp() {
    return false;
  }
  attemptToMerge(other) {
    return null;
  }
};
var $i9 = class {
  constructor(event) {
    this.event = event;
    this.kind = 10;
  }
  isNoOp() {
    return false;
  }
  attemptToMerge(other) {
    return null;
  }
};
var $j9 = class {
  constructor(event) {
    this.event = event;
    this.kind = 11;
  }
  isNoOp() {
    return false;
  }
  attemptToMerge(other) {
    return null;
  }
};
var $k9 = class {
  constructor(event) {
    this.event = event;
    this.kind = 12;
  }
  isNoOp() {
    return false;
  }
  attemptToMerge(other) {
    return null;
  }
};

// out-build/vs/editor/common/cursor/cursor.js
var $l9 = class extends $3c {
  constructor(model, viewModel, coordinatesConverter, cursorConfig) {
    super();
    this.c = model;
    this.f = this.c.getVersionId();
    this.g = viewModel;
    this.h = coordinatesConverter;
    this.context = new $68(this.c, this.g, this.h, cursorConfig);
    this.n = new $88(this.context);
    this.t = false;
    this.u = false;
    this.w = null;
    this.y = null;
    this.z = [];
    this.C = 0;
  }
  dispose() {
    this.n.dispose();
    this.z = $Xc(this.z);
    super.dispose();
  }
  updateConfiguration(cursorConfig) {
    this.context = new $68(this.c, this.g, this.h, cursorConfig);
    this.n.updateContext(this.context);
  }
  onLineMappingChanged(eventsCollector) {
    if (this.f !== this.c.getVersionId()) {
      return;
    }
    this.setStates(eventsCollector, "viewModel", 0, this.getCursorStates());
  }
  setHasFocus(hasFocus) {
    this.t = hasFocus;
  }
  D() {
    if (this.z.length > 0) {
      const selections = this.n.getSelections();
      for (let i2 = 0; i2 < this.z.length; i2++) {
        const autoClosedAction = this.z[i2];
        if (!autoClosedAction.isValid(selections)) {
          autoClosedAction.dispose();
          this.z.splice(i2, 1);
          i2--;
        }
      }
    }
  }
  // ------ some getters/setters
  getPrimaryCursorState() {
    return this.n.getPrimaryCursor();
  }
  getLastAddedCursorIndex() {
    return this.n.getLastAddedCursorIndex();
  }
  getCursorStates() {
    return this.n.getAll();
  }
  setStates(eventsCollector, source, reason, states) {
    let reachedMaxCursorCount = false;
    const multiCursorLimit = this.context.cursorConfig.multiCursorLimit;
    if (states !== null && states.length > multiCursorLimit) {
      states = states.slice(0, multiCursorLimit);
      reachedMaxCursorCount = true;
    }
    const oldState = CursorModelState.from(this.c, this);
    this.n.setStates(states);
    this.n.normalize();
    this.y = null;
    this.D();
    return this.I(eventsCollector, source, reason, oldState, reachedMaxCursorCount);
  }
  setCursorColumnSelectData(columnSelectData) {
    this.y = columnSelectData;
  }
  revealAll(eventsCollector, source, minimalReveal, verticalType, revealHorizontal, scrollType) {
    const viewPositions = this.n.getViewPositions();
    let revealViewRange = null;
    let revealViewSelections = null;
    if (viewPositions.length > 1) {
      revealViewSelections = this.n.getViewSelections();
    } else {
      revealViewRange = $9C.fromPositions(viewPositions[0], viewPositions[0]);
    }
    eventsCollector.emitViewEvent(new $x5(source, minimalReveal, revealViewRange, revealViewSelections, verticalType, revealHorizontal, scrollType));
  }
  revealPrimary(eventsCollector, source, minimalReveal, verticalType, revealHorizontal, scrollType) {
    const primaryCursor = this.n.getPrimaryCursor();
    const revealViewSelections = [primaryCursor.viewState.selection];
    eventsCollector.emitViewEvent(new $x5(source, minimalReveal, null, revealViewSelections, verticalType, revealHorizontal, scrollType));
  }
  saveState() {
    const result = [];
    const selections = this.n.getSelections();
    for (let i2 = 0, len = selections.length; i2 < len; i2++) {
      const selection = selections[i2];
      result.push({
        inSelectionMode: !selection.isEmpty(),
        selectionStart: {
          lineNumber: selection.selectionStartLineNumber,
          column: selection.selectionStartColumn
        },
        position: {
          lineNumber: selection.positionLineNumber,
          column: selection.positionColumn
        }
      });
    }
    return result;
  }
  restoreState(eventsCollector, states) {
    const desiredSelections = [];
    for (let i2 = 0, len = states.length; i2 < len; i2++) {
      const state = states[i2];
      let positionLineNumber = 1;
      let positionColumn = 1;
      if (state.position && state.position.lineNumber) {
        positionLineNumber = state.position.lineNumber;
      }
      if (state.position && state.position.column) {
        positionColumn = state.position.column;
      }
      let selectionStartLineNumber = positionLineNumber;
      let selectionStartColumn = positionColumn;
      if (state.selectionStart && state.selectionStart.lineNumber) {
        selectionStartLineNumber = state.selectionStart.lineNumber;
      }
      if (state.selectionStart && state.selectionStart.column) {
        selectionStartColumn = state.selectionStart.column;
      }
      desiredSelections.push({
        selectionStartLineNumber,
        selectionStartColumn,
        positionLineNumber,
        positionColumn
      });
    }
    this.setStates(eventsCollector, "restoreState", 0, $e5.fromModelSelections(desiredSelections));
    this.revealAll(
      eventsCollector,
      "restoreState",
      false,
      0,
      true,
      1
      /* editorCommon.ScrollType.Immediate */
    );
  }
  onModelContentChanged(eventsCollector, event) {
    if (event instanceof $LE) {
      if (this.u) {
        return;
      }
      this.u = true;
      try {
        this.setStates(eventsCollector, "modelChange", 0, this.getCursorStates());
      } finally {
        this.u = false;
      }
    } else {
      const e = event.rawContentChangedEvent;
      this.f = e.versionId;
      if (this.u) {
        return;
      }
      const hadFlushEvent = e.containsEvent(
        1
        /* RawContentChangedType.Flush */
      );
      this.C = 0;
      if (hadFlushEvent) {
        this.n.dispose();
        this.n = new $88(this.context);
        this.D();
        this.I(eventsCollector, "model", 1, null, false);
      } else {
        if (this.t && e.resultingSelection && e.resultingSelection.length > 0) {
          const cursorState = $e5.fromModelSelections(e.resultingSelection);
          if (this.setStates(eventsCollector, "modelChange", e.isUndoing ? 5 : e.isRedoing ? 6 : 2, cursorState)) {
            this.revealAll(
              eventsCollector,
              "modelChange",
              false,
              0,
              true,
              0
              /* editorCommon.ScrollType.Smooth */
            );
          }
        } else {
          const selectionsFromMarkers = this.n.readSelectionFromMarkers();
          this.setStates(eventsCollector, "modelChange", 2, $e5.fromModelSelections(selectionsFromMarkers));
        }
      }
    }
  }
  getSelection() {
    return this.n.getPrimaryCursor().modelState.selection;
  }
  getTopMostViewPosition() {
    return this.n.getTopMostViewPosition();
  }
  getBottomMostViewPosition() {
    return this.n.getBottomMostViewPosition();
  }
  getCursorColumnSelectData() {
    if (this.y) {
      return this.y;
    }
    const primaryCursor = this.n.getPrimaryCursor();
    const viewSelectionStart = primaryCursor.viewState.selectionStart.getStartPosition();
    const viewPosition = primaryCursor.viewState.position;
    return {
      isReal: false,
      fromViewLineNumber: viewSelectionStart.lineNumber,
      fromViewVisualColumn: this.context.cursorConfig.visibleColumnFromColumn(this.g, viewSelectionStart),
      toViewLineNumber: viewPosition.lineNumber,
      toViewVisualColumn: this.context.cursorConfig.visibleColumnFromColumn(this.g, viewPosition)
    };
  }
  getSelections() {
    return this.n.getSelections();
  }
  getPosition() {
    return this.n.getPrimaryCursor().modelState.position;
  }
  setSelections(eventsCollector, source, selections, reason) {
    this.setStates(eventsCollector, source, reason, $e5.fromModelSelections(selections));
  }
  getPrevEditOperationType() {
    return this.C;
  }
  setPrevEditOperationType(type) {
    this.C = type;
  }
  // ------ auxiliary handling logic
  F(autoClosedCharactersRanges, autoClosedEnclosingRanges) {
    const autoClosedCharactersDeltaDecorations = [];
    const autoClosedEnclosingDeltaDecorations = [];
    for (let i2 = 0, len = autoClosedCharactersRanges.length; i2 < len; i2++) {
      autoClosedCharactersDeltaDecorations.push({
        range: autoClosedCharactersRanges[i2],
        options: {
          description: "auto-closed-character",
          inlineClassName: "auto-closed-character",
          stickiness: 1
          /* TrackedRangeStickiness.NeverGrowsWhenTypingAtEdges */
        }
      });
      autoClosedEnclosingDeltaDecorations.push({
        range: autoClosedEnclosingRanges[i2],
        options: {
          description: "auto-closed-enclosing",
          stickiness: 1
          /* TrackedRangeStickiness.NeverGrowsWhenTypingAtEdges */
        }
      });
    }
    const autoClosedCharactersDecorations = this.c.deltaDecorations([], autoClosedCharactersDeltaDecorations);
    const autoClosedEnclosingDecorations = this.c.deltaDecorations([], autoClosedEnclosingDeltaDecorations);
    this.z.push(new AutoClosedAction(this.c, autoClosedCharactersDecorations, autoClosedEnclosingDecorations));
  }
  G(opResult) {
    if (!opResult) {
      return;
    }
    if (opResult.shouldPushStackElementBefore) {
      this.c.pushStackElement();
    }
    const result = $m9.executeCommands(this.c, this.n.getSelections(), opResult.commands);
    if (result) {
      this.H(result);
      const autoClosedCharactersRanges = [];
      const autoClosedEnclosingRanges = [];
      for (let i2 = 0; i2 < opResult.commands.length; i2++) {
        const command4 = opResult.commands[i2];
        if (command4 instanceof $O6 && command4.enclosingRange && command4.closeCharacterRange) {
          autoClosedCharactersRanges.push(command4.closeCharacterRange);
          autoClosedEnclosingRanges.push(command4.enclosingRange);
        }
      }
      if (autoClosedCharactersRanges.length > 0) {
        this.F(autoClosedCharactersRanges, autoClosedEnclosingRanges);
      }
      this.C = opResult.type;
    }
    if (opResult.shouldPushStackElementAfter) {
      this.c.pushStackElement();
    }
  }
  H(cursorState) {
    if (!cursorState || cursorState.length === 0) {
      cursorState = this.n.readSelectionFromMarkers();
    }
    this.y = null;
    this.n.setSelections(cursorState);
    this.n.normalize();
  }
  // -----------------------------------------------------------------------------------------------------------
  // ----- emitting events
  I(eventsCollector, source, reason, oldState, reachedMaxCursorCount) {
    const newState = CursorModelState.from(this.c, this);
    if (newState.equals(oldState)) {
      return false;
    }
    const selections = this.n.getSelections();
    const viewSelections = this.n.getViewSelections();
    eventsCollector.emitViewEvent(new $o5(viewSelections, selections, reason));
    if (!oldState || oldState.cursorState.length !== newState.cursorState.length || newState.cursorState.some((newCursorState, i2) => !newCursorState.modelState.equals(oldState.cursorState[i2].modelState))) {
      const oldSelections = oldState ? oldState.cursorState.map((s) => s.modelState.selection) : null;
      const oldModelVersionId = oldState ? oldState.modelVersionId : 0;
      eventsCollector.emitOutgoingEvent(new $d9(oldSelections, selections, oldModelVersionId, newState.modelVersionId, source || "keyboard", reason, reachedMaxCursorCount));
    }
    return true;
  }
  // -----------------------------------------------------------------------------------------------------------
  // ----- handlers beyond this point
  J(edits) {
    if (!edits.length) {
      return null;
    }
    const indices = [];
    for (let i2 = 0, len = edits.length; i2 < len; i2++) {
      const edit3 = edits[i2];
      if (!edit3.text || edit3.text.indexOf("\n") >= 0) {
        return null;
      }
      const m = edit3.text.match(/([)\]}>'"`])([^)\]}>'"`]*)$/);
      if (!m) {
        return null;
      }
      const closeChar = m[1];
      const autoClosingPairsCandidates = this.context.cursorConfig.autoClosingPairs.autoClosingPairsCloseSingleChar.get(closeChar);
      if (!autoClosingPairsCandidates || autoClosingPairsCandidates.length !== 1) {
        return null;
      }
      const openChar = autoClosingPairsCandidates[0].open;
      const closeCharIndex = edit3.text.length - m[2].length - 1;
      const openCharIndex = edit3.text.lastIndexOf(openChar, closeCharIndex - 1);
      if (openCharIndex === -1) {
        return null;
      }
      indices.push([openCharIndex, closeCharIndex]);
    }
    return indices;
  }
  executeEdits(eventsCollector, source, edits, cursorStateComputer) {
    let autoClosingIndices = null;
    if (source === "snippet") {
      autoClosingIndices = this.J(edits);
    }
    if (autoClosingIndices) {
      edits[0]._isTracked = true;
    }
    const autoClosedCharactersRanges = [];
    const autoClosedEnclosingRanges = [];
    const selections = this.c.pushEditOperations(this.getSelections(), edits, (undoEdits) => {
      if (autoClosingIndices) {
        for (let i2 = 0, len = autoClosingIndices.length; i2 < len; i2++) {
          const [openCharInnerIndex, closeCharInnerIndex] = autoClosingIndices[i2];
          const undoEdit = undoEdits[i2];
          const lineNumber = undoEdit.range.startLineNumber;
          const openCharIndex = undoEdit.range.startColumn - 1 + openCharInnerIndex;
          const closeCharIndex = undoEdit.range.startColumn - 1 + closeCharInnerIndex;
          autoClosedCharactersRanges.push(new $9C(lineNumber, closeCharIndex + 1, lineNumber, closeCharIndex + 2));
          autoClosedEnclosingRanges.push(new $9C(lineNumber, openCharIndex + 1, lineNumber, closeCharIndex + 2));
        }
      }
      const selections2 = cursorStateComputer(undoEdits);
      if (selections2) {
        this.u = true;
      }
      return selections2;
    });
    if (selections) {
      this.u = false;
      this.setSelections(
        eventsCollector,
        source,
        selections,
        0
        /* CursorChangeReason.NotSet */
      );
    }
    if (autoClosedCharactersRanges.length > 0) {
      this.F(autoClosedCharactersRanges, autoClosedEnclosingRanges);
    }
  }
  L(callback, eventsCollector, source, cursorChangeReason = 0) {
    if (this.context.cursorConfig.readOnly) {
      return;
    }
    const oldState = CursorModelState.from(this.c, this);
    this.n.stopTrackingSelections();
    this.u = true;
    try {
      this.n.ensureValidState();
      callback();
    } catch (err) {
      $gb(err);
    }
    this.u = false;
    this.n.startTrackingSelections();
    this.D();
    if (this.I(eventsCollector, source, cursorChangeReason, oldState, false)) {
      this.revealAll(
        eventsCollector,
        source,
        false,
        0,
        true,
        0
        /* editorCommon.ScrollType.Smooth */
      );
    }
  }
  getAutoClosedCharacters() {
    return AutoClosedAction.getAllAutoClosedCharacters(this.z);
  }
  startComposition(eventsCollector) {
    this.w = new CompositionState(this.c, this.getSelections());
  }
  endComposition(eventsCollector, source) {
    const compositionOutcome = this.w ? this.w.deduceOutcome(this.c, this.getSelections()) : null;
    this.w = null;
    this.L(() => {
      if (source === "keyboard") {
        this.G($S6.compositionEndWithInterceptors(this.C, this.context.cursorConfig, this.c, compositionOutcome, this.getSelections(), this.getAutoClosedCharacters()));
      }
    }, eventsCollector, source);
  }
  type(eventsCollector, text2, source) {
    this.L(() => {
      if (source === "keyboard") {
        const len = text2.length;
        let offset = 0;
        while (offset < len) {
          const charLength = $$f(text2, offset);
          const chr = text2.substr(offset, charLength);
          this.G($S6.typeWithInterceptors(!!this.w, this.C, this.context.cursorConfig, this.c, this.getSelections(), this.getAutoClosedCharacters(), chr));
          offset += charLength;
        }
      } else {
        this.G($S6.typeWithoutInterceptors(this.C, this.context.cursorConfig, this.c, this.getSelections(), text2));
      }
    }, eventsCollector, source);
  }
  compositionType(eventsCollector, text2, replacePrevCharCnt, replaceNextCharCnt, positionDelta, source) {
    if (text2.length === 0 && replacePrevCharCnt === 0 && replaceNextCharCnt === 0) {
      if (positionDelta !== 0) {
        const newSelections = this.getSelections().map((selection) => {
          const position = selection.getPosition();
          return new $_D(position.lineNumber, position.column + positionDelta, position.lineNumber, position.column + positionDelta);
        });
        this.setSelections(
          eventsCollector,
          source,
          newSelections,
          0
          /* CursorChangeReason.NotSet */
        );
      }
      return;
    }
    this.L(() => {
      this.G($S6.compositionType(this.C, this.context.cursorConfig, this.c, this.getSelections(), text2, replacePrevCharCnt, replaceNextCharCnt, positionDelta));
    }, eventsCollector, source);
  }
  paste(eventsCollector, text2, pasteOnNewLine, multicursorText, source) {
    this.L(
      () => {
        this.G($S6.paste(this.context.cursorConfig, this.c, this.getSelections(), text2, pasteOnNewLine, multicursorText || []));
      },
      eventsCollector,
      source,
      4
      /* CursorChangeReason.Paste */
    );
  }
  cut(eventsCollector, source) {
    this.L(() => {
      this.G($l6.cut(this.context.cursorConfig, this.c, this.getSelections()));
    }, eventsCollector, source);
  }
  executeCommand(eventsCollector, command4, source) {
    this.L(() => {
      this.n.killSecondaryCursors();
      this.G(new $i5(0, [command4], {
        shouldPushStackElementBefore: false,
        shouldPushStackElementAfter: false
      }));
    }, eventsCollector, source);
  }
  executeCommands(eventsCollector, commands2, source) {
    this.L(() => {
      this.G(new $i5(0, commands2, {
        shouldPushStackElementBefore: false,
        shouldPushStackElementAfter: false
      }));
    }, eventsCollector, source);
  }
};
var CursorModelState = class _CursorModelState {
  static from(model, cursor) {
    return new _CursorModelState(model.getVersionId(), cursor.getCursorStates());
  }
  constructor(modelVersionId, cursorState) {
    this.modelVersionId = modelVersionId;
    this.cursorState = cursorState;
  }
  equals(other) {
    if (!other) {
      return false;
    }
    if (this.modelVersionId !== other.modelVersionId) {
      return false;
    }
    if (this.cursorState.length !== other.cursorState.length) {
      return false;
    }
    for (let i2 = 0, len = this.cursorState.length; i2 < len; i2++) {
      if (!this.cursorState[i2].equals(other.cursorState[i2])) {
        return false;
      }
    }
    return true;
  }
};
var AutoClosedAction = class {
  static getAllAutoClosedCharacters(autoClosedActions) {
    let autoClosedCharacters = [];
    for (const autoClosedAction of autoClosedActions) {
      autoClosedCharacters = autoClosedCharacters.concat(autoClosedAction.getAutoClosedCharactersRanges());
    }
    return autoClosedCharacters;
  }
  constructor(model, autoClosedCharactersDecorations, autoClosedEnclosingDecorations) {
    this.c = model;
    this.d = autoClosedCharactersDecorations;
    this.f = autoClosedEnclosingDecorations;
  }
  dispose() {
    this.d = this.c.deltaDecorations(this.d, []);
    this.f = this.c.deltaDecorations(this.f, []);
  }
  getAutoClosedCharactersRanges() {
    const result = [];
    for (let i2 = 0; i2 < this.d.length; i2++) {
      const decorationRange = this.c.getDecorationRange(this.d[i2]);
      if (decorationRange) {
        result.push(decorationRange);
      }
    }
    return result;
  }
  isValid(selections) {
    const enclosingRanges = [];
    for (let i2 = 0; i2 < this.f.length; i2++) {
      const decorationRange = this.c.getDecorationRange(this.f[i2]);
      if (decorationRange) {
        enclosingRanges.push(decorationRange);
        if (decorationRange.startLineNumber !== decorationRange.endLineNumber) {
          return false;
        }
      }
    }
    enclosingRanges.sort($9C.compareRangesUsingStarts);
    selections.sort($9C.compareRangesUsingStarts);
    for (let i2 = 0; i2 < selections.length; i2++) {
      if (i2 >= enclosingRanges.length) {
        return false;
      }
      if (!enclosingRanges[i2].strictContainsRange(selections[i2])) {
        return false;
      }
    }
    return true;
  }
};
var $m9 = class {
  static executeCommands(model, selectionsBefore, commands2) {
    const ctx = {
      model,
      selectionsBefore,
      trackedRanges: [],
      trackedRangesDirection: []
    };
    const result = this.c(ctx, commands2);
    for (let i2 = 0, len = ctx.trackedRanges.length; i2 < len; i2++) {
      ctx.model._setTrackedRange(
        ctx.trackedRanges[i2],
        null,
        0
        /* TrackedRangeStickiness.AlwaysGrowsWhenTypingAtEdges */
      );
    }
    return result;
  }
  static c(ctx, commands2) {
    if (this.d(commands2)) {
      return null;
    }
    const commandsData = this.f(ctx, commands2);
    if (commandsData.operations.length === 0) {
      return null;
    }
    const rawOperations = commandsData.operations;
    const loserCursorsMap = this.h(rawOperations);
    if (loserCursorsMap.hasOwnProperty("0")) {
      console.warn("Ignoring commands");
      return null;
    }
    const filteredOperations = [];
    for (let i2 = 0, len = rawOperations.length; i2 < len; i2++) {
      if (!loserCursorsMap.hasOwnProperty(rawOperations[i2].identifier.major.toString())) {
        filteredOperations.push(rawOperations[i2]);
      }
    }
    if (commandsData.hadTrackedEditOperation && filteredOperations.length > 0) {
      filteredOperations[0]._isTracked = true;
    }
    let selectionsAfter = ctx.model.pushEditOperations(ctx.selectionsBefore, filteredOperations, (inverseEditOperations) => {
      const groupedInverseEditOperations = [];
      for (let i2 = 0; i2 < ctx.selectionsBefore.length; i2++) {
        groupedInverseEditOperations[i2] = [];
      }
      for (const op of inverseEditOperations) {
        if (!op.identifier) {
          continue;
        }
        groupedInverseEditOperations[op.identifier.major].push(op);
      }
      const minorBasedSorter = (a, b) => {
        return a.identifier.minor - b.identifier.minor;
      };
      const cursorSelections = [];
      for (let i2 = 0; i2 < ctx.selectionsBefore.length; i2++) {
        if (groupedInverseEditOperations[i2].length > 0) {
          groupedInverseEditOperations[i2].sort(minorBasedSorter);
          cursorSelections[i2] = commands2[i2].computeCursorState(ctx.model, {
            getInverseEditOperations: () => {
              return groupedInverseEditOperations[i2];
            },
            getTrackedSelection: (id2) => {
              const idx = parseInt(id2, 10);
              const range = ctx.model._getTrackedRange(ctx.trackedRanges[idx]);
              if (ctx.trackedRangesDirection[idx] === 0) {
                return new $_D(range.startLineNumber, range.startColumn, range.endLineNumber, range.endColumn);
              }
              return new $_D(range.endLineNumber, range.endColumn, range.startLineNumber, range.startColumn);
            }
          });
        } else {
          cursorSelections[i2] = ctx.selectionsBefore[i2];
        }
      }
      return cursorSelections;
    });
    if (!selectionsAfter) {
      selectionsAfter = ctx.selectionsBefore;
    }
    const losingCursors = [];
    for (const losingCursorIndex in loserCursorsMap) {
      if (loserCursorsMap.hasOwnProperty(losingCursorIndex)) {
        losingCursors.push(parseInt(losingCursorIndex, 10));
      }
    }
    losingCursors.sort((a, b) => {
      return b - a;
    });
    for (const losingCursor of losingCursors) {
      selectionsAfter.splice(losingCursor, 1);
    }
    return selectionsAfter;
  }
  static d(commands2) {
    for (let i2 = 0, len = commands2.length; i2 < len; i2++) {
      if (commands2[i2]) {
        return false;
      }
    }
    return true;
  }
  static f(ctx, commands2) {
    let operations = [];
    let hadTrackedEditOperation = false;
    for (let i2 = 0, len = commands2.length; i2 < len; i2++) {
      const command4 = commands2[i2];
      if (command4) {
        const r2 = this.g(ctx, i2, command4);
        operations = operations.concat(r2.operations);
        hadTrackedEditOperation = hadTrackedEditOperation || r2.hadTrackedEditOperation;
      }
    }
    return {
      operations,
      hadTrackedEditOperation
    };
  }
  static g(ctx, majorIdentifier, command4) {
    const operations = [];
    let operationMinor = 0;
    const addEditOperation = (range, text2, forceMoveMarkers = false) => {
      if ($9C.isEmpty(range) && text2 === "") {
        return;
      }
      operations.push({
        identifier: {
          major: majorIdentifier,
          minor: operationMinor++
        },
        range,
        text: text2,
        forceMoveMarkers,
        isAutoWhitespaceEdit: command4.insertsAutoWhitespace
      });
    };
    let hadTrackedEditOperation = false;
    const addTrackedEditOperation = (selection, text2, forceMoveMarkers) => {
      hadTrackedEditOperation = true;
      addEditOperation(selection, text2, forceMoveMarkers);
    };
    const trackSelection = (_selection, trackPreviousOnEmpty) => {
      const selection = $_D.liftSelection(_selection);
      let stickiness2;
      if (selection.isEmpty()) {
        if (typeof trackPreviousOnEmpty === "boolean") {
          if (trackPreviousOnEmpty) {
            stickiness2 = 2;
          } else {
            stickiness2 = 3;
          }
        } else {
          const maxLineColumn = ctx.model.getLineMaxColumn(selection.startLineNumber);
          if (selection.startColumn === maxLineColumn) {
            stickiness2 = 2;
          } else {
            stickiness2 = 3;
          }
        }
      } else {
        stickiness2 = 1;
      }
      const l = ctx.trackedRanges.length;
      const id2 = ctx.model._setTrackedRange(null, selection, stickiness2);
      ctx.trackedRanges[l] = id2;
      ctx.trackedRangesDirection[l] = selection.getDirection();
      return l.toString();
    };
    const editOperationBuilder = {
      addEditOperation,
      addTrackedEditOperation,
      trackSelection
    };
    try {
      command4.getEditOperations(ctx.model, editOperationBuilder);
    } catch (e) {
      $gb(e);
      return {
        operations: [],
        hadTrackedEditOperation: false
      };
    }
    return {
      operations,
      hadTrackedEditOperation
    };
  }
  static h(operations) {
    operations = operations.slice(0);
    operations.sort((a, b) => {
      return -$9C.compareRangesUsingEnds(a.range, b.range);
    });
    const loserCursorsMap = {};
    for (let i2 = 1; i2 < operations.length; i2++) {
      const previousOp = operations[i2 - 1];
      const currentOp = operations[i2];
      if ($9C.getStartPosition(previousOp.range).isBefore($9C.getEndPosition(currentOp.range))) {
        let loserMajor;
        if (previousOp.identifier.major > currentOp.identifier.major) {
          loserMajor = previousOp.identifier.major;
        } else {
          loserMajor = currentOp.identifier.major;
        }
        loserCursorsMap[loserMajor.toString()] = true;
        for (let j = 0; j < operations.length; j++) {
          if (operations[j].identifier.major === loserMajor) {
            operations.splice(j, 1);
            if (j < i2) {
              i2--;
            }
            j--;
          }
        }
        if (i2 > 0) {
          i2--;
        }
      }
    }
    return loserCursorsMap;
  }
};
var CompositionLineState = class {
  constructor(text2, lineNumber, startSelectionOffset, endSelectionOffset) {
    this.text = text2;
    this.lineNumber = lineNumber;
    this.startSelectionOffset = startSelectionOffset;
    this.endSelectionOffset = endSelectionOffset;
  }
};
var CompositionState = class _CompositionState {
  static d(textModel, selections) {
    const result = [];
    for (const selection of selections) {
      if (selection.startLineNumber !== selection.endLineNumber) {
        return null;
      }
      const lineNumber = selection.startLineNumber;
      result.push(new CompositionLineState(textModel.getLineContent(lineNumber), lineNumber, selection.startColumn - 1, selection.endColumn - 1));
    }
    return result;
  }
  constructor(textModel, selections) {
    this.c = _CompositionState.d(textModel, selections);
  }
  /**
   * Returns the inserted text during this composition.
   * If the composition resulted in existing text being changed (i.e. not a pure insertion) it returns null.
   */
  deduceOutcome(textModel, selections) {
    if (!this.c) {
      return null;
    }
    const current = _CompositionState.d(textModel, selections);
    if (!current) {
      return null;
    }
    if (this.c.length !== current.length) {
      return null;
    }
    const result = [];
    for (let i2 = 0, len = this.c.length; i2 < len; i2++) {
      result.push(_CompositionState.f(this.c[i2], current[i2]));
    }
    return result;
  }
  static f(original, current) {
    const commonPrefix = Math.min(original.startSelectionOffset, current.startSelectionOffset, $3f(original.text, current.text));
    const commonSuffix = Math.min(original.text.length - original.endSelectionOffset, current.text.length - current.endSelectionOffset, $4f(original.text, current.text));
    const deletedText = original.text.substring(commonPrefix, original.text.length - commonSuffix);
    const insertedTextStartOffset = commonPrefix;
    const insertedTextEndOffset = current.text.length - commonSuffix;
    const insertedText = current.text.substring(insertedTextStartOffset, insertedTextEndOffset);
    const insertedTextRange = new $9C(current.lineNumber, insertedTextStartOffset + 1, current.lineNumber, insertedTextEndOffset + 1);
    return new $T6(deletedText, original.startSelectionOffset - commonPrefix, original.endSelectionOffset - commonPrefix, insertedText, current.startSelectionOffset - commonPrefix, current.endSelectionOffset - commonPrefix, insertedTextRange);
  }
};

// out-build/vs/editor/common/languages/textToHtmlTokenizer.js
var fallback = {
  getInitialState: () => $sI,
  tokenizeEncoded: (buffer, hasEOL, state) => $uI(0, state)
};
function $n9(languageService, text2, languageId) {
  return $q9(text2, languageService.languageIdCodec, $YE.get(languageId) || fallback);
}
async function $o9(languageService, text2, languageId) {
  if (!languageId) {
    return $q9(text2, languageService.languageIdCodec, fallback);
  }
  const tokenizationSupport = await $YE.getOrCreate(languageId);
  return $q9(text2, languageService.languageIdCodec, tokenizationSupport || fallback);
}
function $p9(text2, viewLineTokens, colorMap, startOffset, endOffset, tabSize, useNbsp) {
  let result = `<div>`;
  let charIndex = startOffset;
  let tabsCharDelta = 0;
  let prevIsSpace = true;
  for (let tokenIndex = 0, tokenCount = viewLineTokens.getCount(); tokenIndex < tokenCount; tokenIndex++) {
    const tokenEndIndex = viewLineTokens.getEndOffset(tokenIndex);
    if (tokenEndIndex <= startOffset) {
      continue;
    }
    let partContent = "";
    for (; charIndex < tokenEndIndex && charIndex < endOffset; charIndex++) {
      const charCode = text2.charCodeAt(charIndex);
      switch (charCode) {
        case 9: {
          let insertSpacesCount = tabSize - (charIndex + tabsCharDelta) % tabSize;
          tabsCharDelta += insertSpacesCount - 1;
          while (insertSpacesCount > 0) {
            if (useNbsp && prevIsSpace) {
              partContent += "&#160;";
              prevIsSpace = false;
            } else {
              partContent += " ";
              prevIsSpace = true;
            }
            insertSpacesCount--;
          }
          break;
        }
        case 60:
          partContent += "&lt;";
          prevIsSpace = false;
          break;
        case 62:
          partContent += "&gt;";
          prevIsSpace = false;
          break;
        case 38:
          partContent += "&amp;";
          prevIsSpace = false;
          break;
        case 0:
          partContent += "&#00;";
          prevIsSpace = false;
          break;
        case 65279:
        case 8232:
        case 8233:
        case 133:
          partContent += "\uFFFD";
          prevIsSpace = false;
          break;
        case 13:
          partContent += "&#8203";
          prevIsSpace = false;
          break;
        case 32:
          if (useNbsp && prevIsSpace) {
            partContent += "&#160;";
            prevIsSpace = false;
          } else {
            partContent += " ";
            prevIsSpace = true;
          }
          break;
        default:
          partContent += String.fromCharCode(charCode);
          prevIsSpace = false;
      }
    }
    result += `<span style="${viewLineTokens.getInlineStyle(tokenIndex, colorMap)}">${partContent}</span>`;
    if (tokenEndIndex > endOffset || charIndex >= endOffset) {
      break;
    }
  }
  result += `</div>`;
  return result;
}
function $q9(text2, languageIdCodec, tokenizationSupport) {
  let result = `<div class="monaco-tokenized-source">`;
  const lines = $Mf(text2);
  let currentState = tokenizationSupport.getInitialState();
  for (let i2 = 0, len = lines.length; i2 < len; i2++) {
    const line = lines[i2];
    if (i2 > 0) {
      result += `<br/>`;
    }
    const tokenizationResult = tokenizationSupport.tokenizeEncoded(line, true, currentState);
    $xE.convertToEndOffset(tokenizationResult.tokens, line.length);
    const lineTokens = new $xE(tokenizationResult.tokens, line, languageIdCodec);
    const viewLineTokens = lineTokens.inflate();
    let startOffset = 0;
    for (let j = 0, lenJ = viewLineTokens.getCount(); j < lenJ; j++) {
      const type = viewLineTokens.getClassName(j);
      const endIndex = viewLineTokens.getEndOffset(j);
      result += `<span class="${type}">${$zf(line.substring(startOffset, endIndex))}</span>`;
      startOffset = endIndex;
    }
    currentState = tokenizationResult.endState;
  }
  result += `</div>`;
  return result;
}

// out-build/vs/editor/common/viewLayout/linesLayout.js
var PendingChanges = class {
  constructor() {
    this.c = false;
    this.d = [];
    this.e = [];
    this.f = [];
  }
  insert(x) {
    this.c = true;
    this.d.push(x);
  }
  change(x) {
    this.c = true;
    this.e.push(x);
  }
  remove(x) {
    this.c = true;
    this.f.push(x);
  }
  mustCommit() {
    return this.c;
  }
  commit(linesLayout) {
    if (!this.c) {
      return;
    }
    const inserts = this.d;
    const changes = this.e;
    const removes = this.f;
    this.c = false;
    this.d = [];
    this.e = [];
    this.f = [];
    linesLayout._commitPendingChanges(inserts, changes, removes);
  }
};
var $r9 = class {
  constructor(id2, afterLineNumber, ordinal, height, minWidth) {
    this.id = id2;
    this.afterLineNumber = afterLineNumber;
    this.ordinal = ordinal;
    this.height = height;
    this.minWidth = minWidth;
    this.prefixSum = 0;
  }
};
var $s9 = class _$s9 {
  static {
    this.c = 0;
  }
  constructor(lineCount, lineHeight, paddingTop, paddingBottom) {
    this.d = $tg(++_$s9.c);
    this.e = new PendingChanges();
    this.f = 0;
    this.g = [];
    this.h = -1;
    this.j = -1;
    this.k = lineCount;
    this.l = lineHeight;
    this.m = paddingTop;
    this.n = paddingBottom;
  }
  /**
   * Find the insertion index for a new value inside a sorted array of values.
   * If the value is already present in the sorted array, the insertion index will be after the already existing value.
   */
  static findInsertionIndex(arr, afterLineNumber, ordinal) {
    let low = 0;
    let high = arr.length;
    while (low < high) {
      const mid = low + high >>> 1;
      if (afterLineNumber === arr[mid].afterLineNumber) {
        if (ordinal < arr[mid].ordinal) {
          high = mid;
        } else {
          low = mid + 1;
        }
      } else if (afterLineNumber < arr[mid].afterLineNumber) {
        high = mid;
      } else {
        low = mid + 1;
      }
    }
    return low;
  }
  /**
   * Change the height of a line in pixels.
   */
  setLineHeight(lineHeight) {
    this.o();
    this.l = lineHeight;
  }
  /**
   * Changes the padding used to calculate vertical offsets.
   */
  setPadding(paddingTop, paddingBottom) {
    this.m = paddingTop;
    this.n = paddingBottom;
  }
  /**
   * Set the number of lines.
   *
   * @param lineCount New number of lines.
   */
  onFlushed(lineCount) {
    this.o();
    this.k = lineCount;
  }
  changeWhitespace(callback) {
    let hadAChange = false;
    try {
      const accessor = {
        insertWhitespace: (afterLineNumber, ordinal, heightInPx, minWidth) => {
          hadAChange = true;
          afterLineNumber = afterLineNumber | 0;
          ordinal = ordinal | 0;
          heightInPx = heightInPx | 0;
          minWidth = minWidth | 0;
          const id2 = this.d + ++this.f;
          this.e.insert(new $r9(id2, afterLineNumber, ordinal, heightInPx, minWidth));
          return id2;
        },
        changeOneWhitespace: (id2, newAfterLineNumber, newHeight) => {
          hadAChange = true;
          newAfterLineNumber = newAfterLineNumber | 0;
          newHeight = newHeight | 0;
          this.e.change({ id: id2, newAfterLineNumber, newHeight });
        },
        removeWhitespace: (id2) => {
          hadAChange = true;
          this.e.remove({ id: id2 });
        }
      };
      callback(accessor);
    } finally {
      this.e.commit(this);
    }
    return hadAChange;
  }
  _commitPendingChanges(inserts, changes, removes) {
    if (inserts.length > 0 || removes.length > 0) {
      this.j = -1;
    }
    if (inserts.length + changes.length + removes.length <= 1) {
      for (const insert of inserts) {
        this.p(insert);
      }
      for (const change of changes) {
        this.r(change.id, change.newAfterLineNumber, change.newHeight);
      }
      for (const remove of removes) {
        const index = this.q(remove.id);
        if (index === -1) {
          continue;
        }
        this.s(index);
      }
      return;
    }
    const toRemove = /* @__PURE__ */ new Set();
    for (const remove of removes) {
      toRemove.add(remove.id);
    }
    const toChange = /* @__PURE__ */ new Map();
    for (const change of changes) {
      toChange.set(change.id, change);
    }
    const applyRemoveAndChange = (whitespaces) => {
      const result2 = [];
      for (const whitespace of whitespaces) {
        if (toRemove.has(whitespace.id)) {
          continue;
        }
        if (toChange.has(whitespace.id)) {
          const change = toChange.get(whitespace.id);
          whitespace.afterLineNumber = change.newAfterLineNumber;
          whitespace.height = change.newHeight;
        }
        result2.push(whitespace);
      }
      return result2;
    };
    const result = applyRemoveAndChange(this.g).concat(applyRemoveAndChange(inserts));
    result.sort((a, b) => {
      if (a.afterLineNumber === b.afterLineNumber) {
        return a.ordinal - b.ordinal;
      }
      return a.afterLineNumber - b.afterLineNumber;
    });
    this.g = result;
    this.h = -1;
  }
  o() {
    if (this.e.mustCommit()) {
      this.e.commit(this);
    }
  }
  p(whitespace) {
    const insertIndex = _$s9.findInsertionIndex(this.g, whitespace.afterLineNumber, whitespace.ordinal);
    this.g.splice(insertIndex, 0, whitespace);
    this.h = Math.min(this.h, insertIndex - 1);
  }
  q(id2) {
    const arr = this.g;
    for (let i2 = 0, len = arr.length; i2 < len; i2++) {
      if (arr[i2].id === id2) {
        return i2;
      }
    }
    return -1;
  }
  r(id2, newAfterLineNumber, newHeight) {
    const index = this.q(id2);
    if (index === -1) {
      return;
    }
    if (this.g[index].height !== newHeight) {
      this.g[index].height = newHeight;
      this.h = Math.min(this.h, index - 1);
    }
    if (this.g[index].afterLineNumber !== newAfterLineNumber) {
      const whitespace = this.g[index];
      this.s(index);
      whitespace.afterLineNumber = newAfterLineNumber;
      this.p(whitespace);
    }
  }
  s(removeIndex) {
    this.g.splice(removeIndex, 1);
    this.h = Math.min(this.h, removeIndex - 1);
  }
  /**
   * Notify the layouter that lines have been deleted (a continuous zone of lines).
   *
   * @param fromLineNumber The line number at which the deletion started, inclusive
   * @param toLineNumber The line number at which the deletion ended, inclusive
   */
  onLinesDeleted(fromLineNumber, toLineNumber) {
    this.o();
    fromLineNumber = fromLineNumber | 0;
    toLineNumber = toLineNumber | 0;
    this.k -= toLineNumber - fromLineNumber + 1;
    for (let i2 = 0, len = this.g.length; i2 < len; i2++) {
      const afterLineNumber = this.g[i2].afterLineNumber;
      if (fromLineNumber <= afterLineNumber && afterLineNumber <= toLineNumber) {
        this.g[i2].afterLineNumber = fromLineNumber - 1;
      } else if (afterLineNumber > toLineNumber) {
        this.g[i2].afterLineNumber -= toLineNumber - fromLineNumber + 1;
      }
    }
  }
  /**
   * Notify the layouter that lines have been inserted (a continuous zone of lines).
   *
   * @param fromLineNumber The line number at which the insertion started, inclusive
   * @param toLineNumber The line number at which the insertion ended, inclusive.
   */
  onLinesInserted(fromLineNumber, toLineNumber) {
    this.o();
    fromLineNumber = fromLineNumber | 0;
    toLineNumber = toLineNumber | 0;
    this.k += toLineNumber - fromLineNumber + 1;
    for (let i2 = 0, len = this.g.length; i2 < len; i2++) {
      const afterLineNumber = this.g[i2].afterLineNumber;
      if (fromLineNumber <= afterLineNumber) {
        this.g[i2].afterLineNumber += toLineNumber - fromLineNumber + 1;
      }
    }
  }
  /**
   * Get the sum of all the whitespaces.
   */
  getWhitespacesTotalHeight() {
    this.o();
    if (this.g.length === 0) {
      return 0;
    }
    return this.getWhitespacesAccumulatedHeight(this.g.length - 1);
  }
  /**
   * Return the sum of the heights of the whitespaces at [0..index].
   * This includes the whitespace at `index`.
   *
   * @param index The index of the whitespace.
   * @return The sum of the heights of all whitespaces before the one at `index`, including the one at `index`.
   */
  getWhitespacesAccumulatedHeight(index) {
    this.o();
    index = index | 0;
    let startIndex = Math.max(0, this.h + 1);
    if (startIndex === 0) {
      this.g[0].prefixSum = this.g[0].height;
      startIndex++;
    }
    for (let i2 = startIndex; i2 <= index; i2++) {
      this.g[i2].prefixSum = this.g[i2 - 1].prefixSum + this.g[i2].height;
    }
    this.h = Math.max(this.h, index);
    return this.g[index].prefixSum;
  }
  /**
   * Get the sum of heights for all objects.
   *
   * @return The sum of heights for all objects.
   */
  getLinesTotalHeight() {
    this.o();
    const linesHeight = this.l * this.k;
    const whitespacesHeight = this.getWhitespacesTotalHeight();
    return linesHeight + whitespacesHeight + this.m + this.n;
  }
  /**
   * Returns the accumulated height of whitespaces before the given line number.
   *
   * @param lineNumber The line number
   */
  getWhitespaceAccumulatedHeightBeforeLineNumber(lineNumber) {
    this.o();
    lineNumber = lineNumber | 0;
    const lastWhitespaceBeforeLineNumber = this.t(lineNumber);
    if (lastWhitespaceBeforeLineNumber === -1) {
      return 0;
    }
    return this.getWhitespacesAccumulatedHeight(lastWhitespaceBeforeLineNumber);
  }
  t(lineNumber) {
    lineNumber = lineNumber | 0;
    const arr = this.g;
    let low = 0;
    let high = arr.length - 1;
    while (low <= high) {
      const delta = high - low | 0;
      const halfDelta = delta / 2 | 0;
      const mid = low + halfDelta | 0;
      if (arr[mid].afterLineNumber < lineNumber) {
        if (mid + 1 >= arr.length || arr[mid + 1].afterLineNumber >= lineNumber) {
          return mid;
        } else {
          low = mid + 1 | 0;
        }
      } else {
        high = mid - 1 | 0;
      }
    }
    return -1;
  }
  u(lineNumber) {
    lineNumber = lineNumber | 0;
    const lastWhitespaceBeforeLineNumber = this.t(lineNumber);
    const firstWhitespaceAfterLineNumber = lastWhitespaceBeforeLineNumber + 1;
    if (firstWhitespaceAfterLineNumber < this.g.length) {
      return firstWhitespaceAfterLineNumber;
    }
    return -1;
  }
  /**
   * Find the index of the first whitespace which has `afterLineNumber` >= `lineNumber`.
   * @return The index of the first whitespace with `afterLineNumber` >= `lineNumber` or -1 if no whitespace is found.
   */
  getFirstWhitespaceIndexAfterLineNumber(lineNumber) {
    this.o();
    lineNumber = lineNumber | 0;
    return this.u(lineNumber);
  }
  /**
   * Get the vertical offset (the sum of heights for all objects above) a certain line number.
   *
   * @param lineNumber The line number
   * @return The sum of heights for all objects above `lineNumber`.
   */
  getVerticalOffsetForLineNumber(lineNumber, includeViewZones = false) {
    this.o();
    lineNumber = lineNumber | 0;
    let previousLinesHeight;
    if (lineNumber > 1) {
      previousLinesHeight = this.l * (lineNumber - 1);
    } else {
      previousLinesHeight = 0;
    }
    const previousWhitespacesHeight = this.getWhitespaceAccumulatedHeightBeforeLineNumber(lineNumber - (includeViewZones ? 1 : 0));
    return previousLinesHeight + previousWhitespacesHeight + this.m;
  }
  /**
   * Get the vertical offset (the sum of heights for all objects above) a certain line number.
   *
   * @param lineNumber The line number
   * @return The sum of heights for all objects above `lineNumber`.
   */
  getVerticalOffsetAfterLineNumber(lineNumber, includeViewZones = false) {
    this.o();
    lineNumber = lineNumber | 0;
    const previousLinesHeight = this.l * lineNumber;
    const previousWhitespacesHeight = this.getWhitespaceAccumulatedHeightBeforeLineNumber(lineNumber + (includeViewZones ? 1 : 0));
    return previousLinesHeight + previousWhitespacesHeight + this.m;
  }
  /**
   * Returns if there is any whitespace in the document.
   */
  hasWhitespace() {
    this.o();
    return this.getWhitespacesCount() > 0;
  }
  /**
   * The maximum min width for all whitespaces.
   */
  getWhitespaceMinWidth() {
    this.o();
    if (this.j === -1) {
      let minWidth = 0;
      for (let i2 = 0, len = this.g.length; i2 < len; i2++) {
        minWidth = Math.max(minWidth, this.g[i2].minWidth);
      }
      this.j = minWidth;
    }
    return this.j;
  }
  /**
   * Check if `verticalOffset` is below all lines.
   */
  isAfterLines(verticalOffset) {
    this.o();
    const totalHeight = this.getLinesTotalHeight();
    return verticalOffset > totalHeight;
  }
  isInTopPadding(verticalOffset) {
    if (this.m === 0) {
      return false;
    }
    this.o();
    return verticalOffset < this.m;
  }
  isInBottomPadding(verticalOffset) {
    if (this.n === 0) {
      return false;
    }
    this.o();
    const totalHeight = this.getLinesTotalHeight();
    return verticalOffset >= totalHeight - this.n;
  }
  /**
   * Find the first line number that is at or after vertical offset `verticalOffset`.
   * i.e. if getVerticalOffsetForLine(line) is x and getVerticalOffsetForLine(line + 1) is y, then
   * getLineNumberAtOrAfterVerticalOffset(i) = line, x <= i < y.
   *
   * @param verticalOffset The vertical offset to search at.
   * @return The line number at or after vertical offset `verticalOffset`.
   */
  getLineNumberAtOrAfterVerticalOffset(verticalOffset) {
    this.o();
    verticalOffset = verticalOffset | 0;
    if (verticalOffset < 0) {
      return 1;
    }
    const linesCount = this.k | 0;
    const lineHeight = this.l;
    let minLineNumber = 1;
    let maxLineNumber = linesCount;
    while (minLineNumber < maxLineNumber) {
      const midLineNumber = (minLineNumber + maxLineNumber) / 2 | 0;
      const midLineNumberVerticalOffset = this.getVerticalOffsetForLineNumber(midLineNumber) | 0;
      if (verticalOffset >= midLineNumberVerticalOffset + lineHeight) {
        minLineNumber = midLineNumber + 1;
      } else if (verticalOffset >= midLineNumberVerticalOffset) {
        return midLineNumber;
      } else {
        maxLineNumber = midLineNumber;
      }
    }
    if (minLineNumber > linesCount) {
      return linesCount;
    }
    return minLineNumber;
  }
  /**
   * Get all the lines and their relative vertical offsets that are positioned between `verticalOffset1` and `verticalOffset2`.
   *
   * @param verticalOffset1 The beginning of the viewport.
   * @param verticalOffset2 The end of the viewport.
   * @return A structure describing the lines positioned between `verticalOffset1` and `verticalOffset2`.
   */
  getLinesViewportData(verticalOffset1, verticalOffset2) {
    this.o();
    verticalOffset1 = verticalOffset1 | 0;
    verticalOffset2 = verticalOffset2 | 0;
    const lineHeight = this.l;
    const startLineNumber = this.getLineNumberAtOrAfterVerticalOffset(verticalOffset1) | 0;
    const startLineNumberVerticalOffset = this.getVerticalOffsetForLineNumber(startLineNumber) | 0;
    let endLineNumber = this.k | 0;
    let whitespaceIndex = this.getFirstWhitespaceIndexAfterLineNumber(startLineNumber) | 0;
    const whitespaceCount = this.getWhitespacesCount() | 0;
    let currentWhitespaceHeight;
    let currentWhitespaceAfterLineNumber;
    if (whitespaceIndex === -1) {
      whitespaceIndex = whitespaceCount;
      currentWhitespaceAfterLineNumber = endLineNumber + 1;
      currentWhitespaceHeight = 0;
    } else {
      currentWhitespaceAfterLineNumber = this.getAfterLineNumberForWhitespaceIndex(whitespaceIndex) | 0;
      currentWhitespaceHeight = this.getHeightForWhitespaceIndex(whitespaceIndex) | 0;
    }
    let currentVerticalOffset = startLineNumberVerticalOffset;
    let currentLineRelativeOffset = currentVerticalOffset;
    const STEP_SIZE2 = 5e5;
    let bigNumbersDelta = 0;
    if (startLineNumberVerticalOffset >= STEP_SIZE2) {
      bigNumbersDelta = Math.floor(startLineNumberVerticalOffset / STEP_SIZE2) * STEP_SIZE2;
      bigNumbersDelta = Math.floor(bigNumbersDelta / lineHeight) * lineHeight;
      currentLineRelativeOffset -= bigNumbersDelta;
    }
    const linesOffsets = [];
    const verticalCenter = verticalOffset1 + (verticalOffset2 - verticalOffset1) / 2;
    let centeredLineNumber = -1;
    for (let lineNumber = startLineNumber; lineNumber <= endLineNumber; lineNumber++) {
      if (centeredLineNumber === -1) {
        const currentLineTop = currentVerticalOffset;
        const currentLineBottom = currentVerticalOffset + lineHeight;
        if (currentLineTop <= verticalCenter && verticalCenter < currentLineBottom || currentLineTop > verticalCenter) {
          centeredLineNumber = lineNumber;
        }
      }
      currentVerticalOffset += lineHeight;
      linesOffsets[lineNumber - startLineNumber] = currentLineRelativeOffset;
      currentLineRelativeOffset += lineHeight;
      while (currentWhitespaceAfterLineNumber === lineNumber) {
        currentLineRelativeOffset += currentWhitespaceHeight;
        currentVerticalOffset += currentWhitespaceHeight;
        whitespaceIndex++;
        if (whitespaceIndex >= whitespaceCount) {
          currentWhitespaceAfterLineNumber = endLineNumber + 1;
        } else {
          currentWhitespaceAfterLineNumber = this.getAfterLineNumberForWhitespaceIndex(whitespaceIndex) | 0;
          currentWhitespaceHeight = this.getHeightForWhitespaceIndex(whitespaceIndex) | 0;
        }
      }
      if (currentVerticalOffset >= verticalOffset2) {
        endLineNumber = lineNumber;
        break;
      }
    }
    if (centeredLineNumber === -1) {
      centeredLineNumber = endLineNumber;
    }
    const endLineNumberVerticalOffset = this.getVerticalOffsetForLineNumber(endLineNumber) | 0;
    let completelyVisibleStartLineNumber = startLineNumber;
    let completelyVisibleEndLineNumber = endLineNumber;
    if (completelyVisibleStartLineNumber < completelyVisibleEndLineNumber) {
      if (startLineNumberVerticalOffset < verticalOffset1) {
        completelyVisibleStartLineNumber++;
      }
    }
    if (completelyVisibleStartLineNumber < completelyVisibleEndLineNumber) {
      if (endLineNumberVerticalOffset + lineHeight > verticalOffset2) {
        completelyVisibleEndLineNumber--;
      }
    }
    return {
      bigNumbersDelta,
      startLineNumber,
      endLineNumber,
      relativeVerticalOffset: linesOffsets,
      centeredLineNumber,
      completelyVisibleStartLineNumber,
      completelyVisibleEndLineNumber,
      lineHeight: this.l
    };
  }
  getVerticalOffsetForWhitespaceIndex(whitespaceIndex) {
    this.o();
    whitespaceIndex = whitespaceIndex | 0;
    const afterLineNumber = this.getAfterLineNumberForWhitespaceIndex(whitespaceIndex);
    let previousLinesHeight;
    if (afterLineNumber >= 1) {
      previousLinesHeight = this.l * afterLineNumber;
    } else {
      previousLinesHeight = 0;
    }
    let previousWhitespacesHeight;
    if (whitespaceIndex > 0) {
      previousWhitespacesHeight = this.getWhitespacesAccumulatedHeight(whitespaceIndex - 1);
    } else {
      previousWhitespacesHeight = 0;
    }
    return previousLinesHeight + previousWhitespacesHeight + this.m;
  }
  getWhitespaceIndexAtOrAfterVerticallOffset(verticalOffset) {
    this.o();
    verticalOffset = verticalOffset | 0;
    let minWhitespaceIndex = 0;
    let maxWhitespaceIndex = this.getWhitespacesCount() - 1;
    if (maxWhitespaceIndex < 0) {
      return -1;
    }
    const maxWhitespaceVerticalOffset = this.getVerticalOffsetForWhitespaceIndex(maxWhitespaceIndex);
    const maxWhitespaceHeight = this.getHeightForWhitespaceIndex(maxWhitespaceIndex);
    if (verticalOffset >= maxWhitespaceVerticalOffset + maxWhitespaceHeight) {
      return -1;
    }
    while (minWhitespaceIndex < maxWhitespaceIndex) {
      const midWhitespaceIndex = Math.floor((minWhitespaceIndex + maxWhitespaceIndex) / 2);
      const midWhitespaceVerticalOffset = this.getVerticalOffsetForWhitespaceIndex(midWhitespaceIndex);
      const midWhitespaceHeight = this.getHeightForWhitespaceIndex(midWhitespaceIndex);
      if (verticalOffset >= midWhitespaceVerticalOffset + midWhitespaceHeight) {
        minWhitespaceIndex = midWhitespaceIndex + 1;
      } else if (verticalOffset >= midWhitespaceVerticalOffset) {
        return midWhitespaceIndex;
      } else {
        maxWhitespaceIndex = midWhitespaceIndex;
      }
    }
    return minWhitespaceIndex;
  }
  /**
   * Get exactly the whitespace that is layouted at `verticalOffset`.
   *
   * @param verticalOffset The vertical offset.
   * @return Precisely the whitespace that is layouted at `verticaloffset` or null.
   */
  getWhitespaceAtVerticalOffset(verticalOffset) {
    this.o();
    verticalOffset = verticalOffset | 0;
    const candidateIndex = this.getWhitespaceIndexAtOrAfterVerticallOffset(verticalOffset);
    if (candidateIndex < 0) {
      return null;
    }
    if (candidateIndex >= this.getWhitespacesCount()) {
      return null;
    }
    const candidateTop = this.getVerticalOffsetForWhitespaceIndex(candidateIndex);
    if (candidateTop > verticalOffset) {
      return null;
    }
    const candidateHeight = this.getHeightForWhitespaceIndex(candidateIndex);
    const candidateId = this.getIdForWhitespaceIndex(candidateIndex);
    const candidateAfterLineNumber = this.getAfterLineNumberForWhitespaceIndex(candidateIndex);
    return {
      id: candidateId,
      afterLineNumber: candidateAfterLineNumber,
      verticalOffset: candidateTop,
      height: candidateHeight
    };
  }
  /**
   * Get a list of whitespaces that are positioned between `verticalOffset1` and `verticalOffset2`.
   *
   * @param verticalOffset1 The beginning of the viewport.
   * @param verticalOffset2 The end of the viewport.
   * @return An array with all the whitespaces in the viewport. If no whitespace is in viewport, the array is empty.
   */
  getWhitespaceViewportData(verticalOffset1, verticalOffset2) {
    this.o();
    verticalOffset1 = verticalOffset1 | 0;
    verticalOffset2 = verticalOffset2 | 0;
    const startIndex = this.getWhitespaceIndexAtOrAfterVerticallOffset(verticalOffset1);
    const endIndex = this.getWhitespacesCount() - 1;
    if (startIndex < 0) {
      return [];
    }
    const result = [];
    for (let i2 = startIndex; i2 <= endIndex; i2++) {
      const top2 = this.getVerticalOffsetForWhitespaceIndex(i2);
      const height = this.getHeightForWhitespaceIndex(i2);
      if (top2 >= verticalOffset2) {
        break;
      }
      result.push({
        id: this.getIdForWhitespaceIndex(i2),
        afterLineNumber: this.getAfterLineNumberForWhitespaceIndex(i2),
        verticalOffset: top2,
        height
      });
    }
    return result;
  }
  /**
   * Get all whitespaces.
   */
  getWhitespaces() {
    this.o();
    return this.g.slice(0);
  }
  /**
   * The number of whitespaces.
   */
  getWhitespacesCount() {
    this.o();
    return this.g.length;
  }
  /**
   * Get the `id` for whitespace at index `index`.
   *
   * @param index The index of the whitespace.
   * @return `id` of whitespace at `index`.
   */
  getIdForWhitespaceIndex(index) {
    this.o();
    index = index | 0;
    return this.g[index].id;
  }
  /**
   * Get the `afterLineNumber` for whitespace at index `index`.
   *
   * @param index The index of the whitespace.
   * @return `afterLineNumber` of whitespace at `index`.
   */
  getAfterLineNumberForWhitespaceIndex(index) {
    this.o();
    index = index | 0;
    return this.g[index].afterLineNumber;
  }
  /**
   * Get the `height` for whitespace at index `index`.
   *
   * @param index The index of the whitespace.
   * @return `height` of whitespace at `index`.
   */
  getHeightForWhitespaceIndex(index) {
    this.o();
    index = index | 0;
    return this.g[index].height;
  }
};

// out-build/vs/editor/common/viewLayout/viewLayout.js
var SMOOTH_SCROLLING_TIME = 125;
var EditorScrollDimensions = class {
  constructor(width2, contentWidth, height, contentHeight) {
    width2 = width2 | 0;
    contentWidth = contentWidth | 0;
    height = height | 0;
    contentHeight = contentHeight | 0;
    if (width2 < 0) {
      width2 = 0;
    }
    if (contentWidth < 0) {
      contentWidth = 0;
    }
    if (height < 0) {
      height = 0;
    }
    if (contentHeight < 0) {
      contentHeight = 0;
    }
    this.width = width2;
    this.contentWidth = contentWidth;
    this.scrollWidth = Math.max(width2, contentWidth);
    this.height = height;
    this.contentHeight = contentHeight;
    this.scrollHeight = Math.max(height, contentHeight);
  }
  equals(other) {
    return this.width === other.width && this.contentWidth === other.contentWidth && this.height === other.height && this.contentHeight === other.contentHeight;
  }
};
var EditorScrollable = class extends $3c {
  constructor(smoothScrollDuration, scheduleAtNextAnimationFrame) {
    super();
    this.c = this.B(new $ze());
    this.onDidContentSizeChange = this.c.event;
    this.b = new EditorScrollDimensions(0, 0, 0, 0);
    this.a = this.B(new $AD({
      forceIntegerValues: true,
      smoothScrollDuration,
      scheduleAtNextAnimationFrame
    }));
    this.onDidScroll = this.a.onScroll;
  }
  getScrollable() {
    return this.a;
  }
  setSmoothScrollDuration(smoothScrollDuration) {
    this.a.setSmoothScrollDuration(smoothScrollDuration);
  }
  validateScrollPosition(scrollPosition) {
    return this.a.validateScrollPosition(scrollPosition);
  }
  getScrollDimensions() {
    return this.b;
  }
  setScrollDimensions(dimensions) {
    if (this.b.equals(dimensions)) {
      return;
    }
    const oldDimensions = this.b;
    this.b = dimensions;
    this.a.setScrollDimensions({
      width: dimensions.width,
      scrollWidth: dimensions.scrollWidth,
      height: dimensions.height,
      scrollHeight: dimensions.scrollHeight
    }, true);
    const contentWidthChanged = oldDimensions.contentWidth !== dimensions.contentWidth;
    const contentHeightChanged = oldDimensions.contentHeight !== dimensions.contentHeight;
    if (contentWidthChanged || contentHeightChanged) {
      this.c.fire(new $$8(oldDimensions.contentWidth, oldDimensions.contentHeight, dimensions.contentWidth, dimensions.contentHeight));
    }
  }
  getFutureScrollPosition() {
    return this.a.getFutureScrollPosition();
  }
  getCurrentScrollPosition() {
    return this.a.getCurrentScrollPosition();
  }
  setScrollPositionNow(update) {
    this.a.setScrollPositionNow(update);
  }
  setScrollPositionSmooth(update) {
    this.a.setScrollPositionSmooth(update);
  }
  hasPendingScrollAnimation() {
    return this.a.hasPendingScrollAnimation();
  }
};
var $t9 = class extends $3c {
  constructor(configuration2, lineCount, scheduleAtNextAnimationFrame) {
    super();
    this.a = configuration2;
    const options3 = this.a.options;
    const layoutInfo = options3.get(
      151
      /* EditorOption.layoutInfo */
    );
    const padding = options3.get(
      88
      /* EditorOption.padding */
    );
    this.b = new $s9(lineCount, options3.get(
      68
      /* EditorOption.lineHeight */
    ), padding.top, padding.bottom);
    this.c = 0;
    this.f = 0;
    this.g = this.B(new EditorScrollable(0, scheduleAtNextAnimationFrame));
    this.h();
    this.g.setScrollDimensions(new EditorScrollDimensions(layoutInfo.contentWidth, 0, layoutInfo.height, 0));
    this.onDidScroll = this.g.onDidScroll;
    this.onDidContentSizeChange = this.g.onDidContentSizeChange;
    this.n();
  }
  dispose() {
    super.dispose();
  }
  getScrollable() {
    return this.g.getScrollable();
  }
  onHeightMaybeChanged() {
    this.n();
  }
  h() {
    this.g.setSmoothScrollDuration(this.a.options.get(
      119
      /* EditorOption.smoothScrolling */
    ) ? SMOOTH_SCROLLING_TIME : 0);
  }
  // ---- begin view event handlers
  onConfigurationChanged(e) {
    const options3 = this.a.options;
    if (e.hasChanged(
      68
      /* EditorOption.lineHeight */
    )) {
      this.b.setLineHeight(options3.get(
        68
        /* EditorOption.lineHeight */
      ));
    }
    if (e.hasChanged(
      88
      /* EditorOption.padding */
    )) {
      const padding = options3.get(
        88
        /* EditorOption.padding */
      );
      this.b.setPadding(padding.top, padding.bottom);
    }
    if (e.hasChanged(
      151
      /* EditorOption.layoutInfo */
    )) {
      const layoutInfo = options3.get(
        151
        /* EditorOption.layoutInfo */
      );
      const width2 = layoutInfo.contentWidth;
      const height = layoutInfo.height;
      const scrollDimensions = this.g.getScrollDimensions();
      const contentWidth = scrollDimensions.contentWidth;
      this.g.setScrollDimensions(new EditorScrollDimensions(width2, scrollDimensions.contentWidth, height, this.m(width2, height, contentWidth)));
    } else {
      this.n();
    }
    if (e.hasChanged(
      119
      /* EditorOption.smoothScrolling */
    )) {
      this.h();
    }
  }
  onFlushed(lineCount) {
    this.b.onFlushed(lineCount);
  }
  onLinesDeleted(fromLineNumber, toLineNumber) {
    this.b.onLinesDeleted(fromLineNumber, toLineNumber);
  }
  onLinesInserted(fromLineNumber, toLineNumber) {
    this.b.onLinesInserted(fromLineNumber, toLineNumber);
  }
  // ---- end view event handlers
  j(width2, scrollWidth) {
    const options3 = this.a.options;
    const scrollbar = options3.get(
      108
      /* EditorOption.scrollbar */
    );
    if (scrollbar.horizontal === 2) {
      return 0;
    }
    if (width2 >= scrollWidth) {
      return 0;
    }
    return scrollbar.horizontalScrollbarSize;
  }
  m(width2, height, contentWidth) {
    const options3 = this.a.options;
    let result = this.b.getLinesTotalHeight();
    if (options3.get(
      110
      /* EditorOption.scrollBeyondLastLine */
    )) {
      result += Math.max(0, height - options3.get(
        68
        /* EditorOption.lineHeight */
      ) - options3.get(
        88
        /* EditorOption.padding */
      ).bottom);
    } else if (!options3.get(
      108
      /* EditorOption.scrollbar */
    ).ignoreHorizontalScrollbarInContentHeight) {
      result += this.j(width2, contentWidth);
    }
    return result;
  }
  n() {
    const scrollDimensions = this.g.getScrollDimensions();
    const width2 = scrollDimensions.width;
    const height = scrollDimensions.height;
    const contentWidth = scrollDimensions.contentWidth;
    this.g.setScrollDimensions(new EditorScrollDimensions(width2, scrollDimensions.contentWidth, height, this.m(width2, height, contentWidth)));
  }
  // ---- Layouting logic
  getCurrentViewport() {
    const scrollDimensions = this.g.getScrollDimensions();
    const currentScrollPosition = this.g.getCurrentScrollPosition();
    return new $E5(currentScrollPosition.scrollTop, currentScrollPosition.scrollLeft, scrollDimensions.width, scrollDimensions.height);
  }
  getFutureViewport() {
    const scrollDimensions = this.g.getScrollDimensions();
    const currentScrollPosition = this.g.getFutureScrollPosition();
    return new $E5(currentScrollPosition.scrollTop, currentScrollPosition.scrollLeft, scrollDimensions.width, scrollDimensions.height);
  }
  r() {
    const options3 = this.a.options;
    const maxLineWidth = this.c;
    const wrappingInfo = options3.get(
      152
      /* EditorOption.wrappingInfo */
    );
    const fontInfo = options3.get(
      52
      /* EditorOption.fontInfo */
    );
    const layoutInfo = options3.get(
      151
      /* EditorOption.layoutInfo */
    );
    if (wrappingInfo.isViewportWrapping) {
      const minimap = options3.get(
        74
        /* EditorOption.minimap */
      );
      if (maxLineWidth > layoutInfo.contentWidth + fontInfo.typicalHalfwidthCharacterWidth) {
        if (minimap.enabled && minimap.side === "right") {
          return maxLineWidth + layoutInfo.verticalScrollbarWidth;
        }
      }
      return maxLineWidth;
    } else {
      const extraHorizontalSpace = options3.get(
        109
        /* EditorOption.scrollBeyondLastColumn */
      ) * fontInfo.typicalHalfwidthCharacterWidth;
      const whitespaceMinWidth = this.b.getWhitespaceMinWidth();
      return Math.max(maxLineWidth + extraHorizontalSpace + layoutInfo.verticalScrollbarWidth, whitespaceMinWidth, this.f);
    }
  }
  setMaxLineWidth(maxLineWidth) {
    this.c = maxLineWidth;
    this.s();
  }
  setOverlayWidgetsMinWidth(maxMinWidth) {
    this.f = maxMinWidth;
    this.s();
  }
  s() {
    const scrollDimensions = this.g.getScrollDimensions();
    this.g.setScrollDimensions(new EditorScrollDimensions(scrollDimensions.width, this.r(), scrollDimensions.height, scrollDimensions.contentHeight));
    this.n();
  }
  // ---- view state
  saveState() {
    const currentScrollPosition = this.g.getFutureScrollPosition();
    const scrollTop = currentScrollPosition.scrollTop;
    const firstLineNumberInViewport = this.b.getLineNumberAtOrAfterVerticalOffset(scrollTop);
    const whitespaceAboveFirstLine = this.b.getWhitespaceAccumulatedHeightBeforeLineNumber(firstLineNumberInViewport);
    return {
      scrollTop,
      scrollTopWithoutViewZones: scrollTop - whitespaceAboveFirstLine,
      scrollLeft: currentScrollPosition.scrollLeft
    };
  }
  // ----
  changeWhitespace(callback) {
    const hadAChange = this.b.changeWhitespace(callback);
    if (hadAChange) {
      this.onHeightMaybeChanged();
    }
    return hadAChange;
  }
  getVerticalOffsetForLineNumber(lineNumber, includeViewZones = false) {
    return this.b.getVerticalOffsetForLineNumber(lineNumber, includeViewZones);
  }
  getVerticalOffsetAfterLineNumber(lineNumber, includeViewZones = false) {
    return this.b.getVerticalOffsetAfterLineNumber(lineNumber, includeViewZones);
  }
  isAfterLines(verticalOffset) {
    return this.b.isAfterLines(verticalOffset);
  }
  isInTopPadding(verticalOffset) {
    return this.b.isInTopPadding(verticalOffset);
  }
  isInBottomPadding(verticalOffset) {
    return this.b.isInBottomPadding(verticalOffset);
  }
  getLineNumberAtVerticalOffset(verticalOffset) {
    return this.b.getLineNumberAtOrAfterVerticalOffset(verticalOffset);
  }
  getWhitespaceAtVerticalOffset(verticalOffset) {
    return this.b.getWhitespaceAtVerticalOffset(verticalOffset);
  }
  getLinesViewportData() {
    const visibleBox = this.getCurrentViewport();
    return this.b.getLinesViewportData(visibleBox.top, visibleBox.top + visibleBox.height);
  }
  getLinesViewportDataAtScrollTop(scrollTop) {
    const scrollDimensions = this.g.getScrollDimensions();
    if (scrollTop + scrollDimensions.height > scrollDimensions.scrollHeight) {
      scrollTop = scrollDimensions.scrollHeight - scrollDimensions.height;
    }
    if (scrollTop < 0) {
      scrollTop = 0;
    }
    return this.b.getLinesViewportData(scrollTop, scrollTop + scrollDimensions.height);
  }
  getWhitespaceViewportData() {
    const visibleBox = this.getCurrentViewport();
    return this.b.getWhitespaceViewportData(visibleBox.top, visibleBox.top + visibleBox.height);
  }
  getWhitespaces() {
    return this.b.getWhitespaces();
  }
  // ----
  getContentWidth() {
    const scrollDimensions = this.g.getScrollDimensions();
    return scrollDimensions.contentWidth;
  }
  getScrollWidth() {
    const scrollDimensions = this.g.getScrollDimensions();
    return scrollDimensions.scrollWidth;
  }
  getContentHeight() {
    const scrollDimensions = this.g.getScrollDimensions();
    return scrollDimensions.contentHeight;
  }
  getScrollHeight() {
    const scrollDimensions = this.g.getScrollDimensions();
    return scrollDimensions.scrollHeight;
  }
  getCurrentScrollLeft() {
    const currentScrollPosition = this.g.getCurrentScrollPosition();
    return currentScrollPosition.scrollLeft;
  }
  getCurrentScrollTop() {
    const currentScrollPosition = this.g.getCurrentScrollPosition();
    return currentScrollPosition.scrollTop;
  }
  validateScrollPosition(scrollPosition) {
    return this.g.validateScrollPosition(scrollPosition);
  }
  setScrollPosition(position, type) {
    if (type === 1) {
      this.g.setScrollPositionNow(position);
    } else {
      this.g.setScrollPositionSmooth(position);
    }
  }
  hasPendingScrollAnimation() {
    return this.g.hasPendingScrollAnimation();
  }
  deltaScrollNow(deltaScrollLeft, deltaScrollTop) {
    const currentScrollPosition = this.g.getCurrentScrollPosition();
    this.g.setScrollPositionNow({
      scrollLeft: currentScrollPosition.scrollLeft + deltaScrollLeft,
      scrollTop: currentScrollPosition.scrollTop + deltaScrollTop
    });
  }
};

// out-build/vs/editor/common/viewModel/viewModelDecorations.js
var $x9 = class {
  constructor(editorId, model, configuration2, linesCollection, coordinatesConverter) {
    this.a = editorId;
    this.b = model;
    this.c = configuration2;
    this.d = linesCollection;
    this.e = coordinatesConverter;
    this.f = /* @__PURE__ */ Object.create(null);
    this.g = null;
    this.h = null;
  }
  k() {
    this.g = null;
    this.h = null;
  }
  dispose() {
    this.f = /* @__PURE__ */ Object.create(null);
    this.k();
  }
  reset() {
    this.f = /* @__PURE__ */ Object.create(null);
    this.k();
  }
  onModelDecorationsChanged() {
    this.f = /* @__PURE__ */ Object.create(null);
    this.k();
  }
  onLineMappingChanged() {
    this.f = /* @__PURE__ */ Object.create(null);
    this.k();
  }
  l(modelDecoration) {
    const id2 = modelDecoration.id;
    let r2 = this.f[id2];
    if (!r2) {
      const modelRange = modelDecoration.range;
      const options3 = modelDecoration.options;
      let viewRange;
      if (options3.isWholeLine) {
        const start = this.e.convertModelPositionToViewPosition(new $8C(modelRange.startLineNumber, 1), 0, false, true);
        const end = this.e.convertModelPositionToViewPosition(
          new $8C(modelRange.endLineNumber, this.b.getLineMaxColumn(modelRange.endLineNumber)),
          1
          /* PositionAffinity.Right */
        );
        viewRange = new $9C(start.lineNumber, start.column, end.lineNumber, end.column);
      } else {
        viewRange = this.e.convertModelRangeToViewRange(
          modelRange,
          1
          /* PositionAffinity.Right */
        );
      }
      r2 = new $K5(viewRange, options3);
      this.f[id2] = r2;
    }
    return r2;
  }
  getMinimapDecorationsInRange(range) {
    return this.m(range, true, false).decorations;
  }
  getDecorationsViewportData(viewRange) {
    let cacheIsValid = this.g !== null;
    cacheIsValid = cacheIsValid && viewRange.equalsRange(this.h);
    if (!cacheIsValid) {
      this.g = this.m(viewRange, false, false);
      this.h = viewRange;
    }
    return this.g;
  }
  getInlineDecorationsOnLine(lineNumber, onlyMinimapDecorations = false, onlyMarginDecorations = false) {
    const range = new $9C(lineNumber, this.d.getViewLineMinColumn(lineNumber), lineNumber, this.d.getViewLineMaxColumn(lineNumber));
    return this.m(range, onlyMinimapDecorations, onlyMarginDecorations).inlineDecorations[0];
  }
  m(viewRange, onlyMinimapDecorations, onlyMarginDecorations) {
    const modelDecorations = this.d.getDecorationsInRange(viewRange, this.a, filterValidationDecorations(this.c.options), onlyMinimapDecorations, onlyMarginDecorations);
    const startLineNumber = viewRange.startLineNumber;
    const endLineNumber = viewRange.endLineNumber;
    const decorationsInViewport = [];
    let decorationsInViewportLen = 0;
    const inlineDecorations = [];
    for (let j = startLineNumber; j <= endLineNumber; j++) {
      inlineDecorations[j - startLineNumber] = [];
    }
    for (let i2 = 0, len = modelDecorations.length; i2 < len; i2++) {
      const modelDecoration = modelDecorations[i2];
      const decorationOptions = modelDecoration.options;
      if (!$y9(this.b, modelDecoration)) {
        continue;
      }
      const viewModelDecoration = this.l(modelDecoration);
      const viewRange2 = viewModelDecoration.range;
      decorationsInViewport[decorationsInViewportLen++] = viewModelDecoration;
      if (decorationOptions.inlineClassName) {
        const inlineDecoration = new $I5(
          viewRange2,
          decorationOptions.inlineClassName,
          decorationOptions.inlineClassNameAffectsLetterSpacing ? 3 : 0
          /* InlineDecorationType.Regular */
        );
        const intersectedStartLineNumber = Math.max(startLineNumber, viewRange2.startLineNumber);
        const intersectedEndLineNumber = Math.min(endLineNumber, viewRange2.endLineNumber);
        for (let j = intersectedStartLineNumber; j <= intersectedEndLineNumber; j++) {
          inlineDecorations[j - startLineNumber].push(inlineDecoration);
        }
      }
      if (decorationOptions.beforeContentClassName) {
        if (startLineNumber <= viewRange2.startLineNumber && viewRange2.startLineNumber <= endLineNumber) {
          const inlineDecoration = new $I5(
            new $9C(viewRange2.startLineNumber, viewRange2.startColumn, viewRange2.startLineNumber, viewRange2.startColumn),
            decorationOptions.beforeContentClassName,
            1
            /* InlineDecorationType.Before */
          );
          inlineDecorations[viewRange2.startLineNumber - startLineNumber].push(inlineDecoration);
        }
      }
      if (decorationOptions.afterContentClassName) {
        if (startLineNumber <= viewRange2.endLineNumber && viewRange2.endLineNumber <= endLineNumber) {
          const inlineDecoration = new $I5(
            new $9C(viewRange2.endLineNumber, viewRange2.endColumn, viewRange2.endLineNumber, viewRange2.endColumn),
            decorationOptions.afterContentClassName,
            2
            /* InlineDecorationType.After */
          );
          inlineDecorations[viewRange2.endLineNumber - startLineNumber].push(inlineDecoration);
        }
      }
    }
    return {
      decorations: decorationsInViewport,
      inlineDecorations
    };
  }
};
function $y9(model, decoration3) {
  if (decoration3.options.hideInCommentTokens && $z9(model, decoration3)) {
    return false;
  }
  if (decoration3.options.hideInStringTokens && $A9(model, decoration3)) {
    return false;
  }
  return true;
}
function $z9(model, decoration3) {
  return testTokensInRange(
    model,
    decoration3.range,
    (tokenType) => tokenType === 1
    /* StandardTokenType.Comment */
  );
}
function $A9(model, decoration3) {
  return testTokensInRange(
    model,
    decoration3.range,
    (tokenType) => tokenType === 2
    /* StandardTokenType.String */
  );
}
function testTokensInRange(model, range, callback) {
  for (let lineNumber = range.startLineNumber; lineNumber <= range.endLineNumber; lineNumber++) {
    const lineTokens = model.tokenization.getLineTokens(lineNumber);
    const isFirstLine = lineNumber === range.startLineNumber;
    const isEndLine = lineNumber === range.endLineNumber;
    let tokenIdx = isFirstLine ? lineTokens.findTokenIndexAtOffset(range.startColumn - 1) : 0;
    while (tokenIdx < lineTokens.getCount()) {
      if (isEndLine) {
        const startOffset = lineTokens.getStartOffset(tokenIdx);
        if (startOffset > range.endColumn - 1) {
          break;
        }
      }
      const callbackResult = callback(lineTokens.getStandardTokenType(tokenIdx));
      if (!callbackResult) {
        return false;
      }
      tokenIdx++;
    }
  }
  return true;
}

// out-build/vs/editor/common/viewModel/modelLineProjection.js
function $u9(lineBreakData, isVisible) {
  if (lineBreakData === null) {
    if (isVisible) {
      return IdentityModelLineProjection.INSTANCE;
    }
    return HiddenModelLineProjection.INSTANCE;
  } else {
    return new ModelLineProjection(lineBreakData, isVisible);
  }
}
var ModelLineProjection = class {
  constructor(lineBreakData, isVisible) {
    this.a = lineBreakData;
    this.b = isVisible;
  }
  isVisible() {
    return this.b;
  }
  setVisible(isVisible) {
    this.b = isVisible;
    return this;
  }
  getProjectionData() {
    return this.a;
  }
  getViewLineCount() {
    if (!this.b) {
      return 0;
    }
    return this.a.getOutputLineCount();
  }
  getViewLineContent(model, modelLineNumber, outputLineIndex) {
    this.d();
    const startOffsetInInputWithInjections = outputLineIndex > 0 ? this.a.breakOffsets[outputLineIndex - 1] : 0;
    const endOffsetInInputWithInjections = this.a.breakOffsets[outputLineIndex];
    let r2;
    if (this.a.injectionOffsets !== null) {
      const injectedTexts = this.a.injectionOffsets.map((offset, idx) => new $FE(0, 0, offset + 1, this.a.injectionOptions[idx], 0));
      const lineWithInjections = $FE.applyInjectedText(model.getLineContent(modelLineNumber), injectedTexts);
      r2 = lineWithInjections.substring(startOffsetInInputWithInjections, endOffsetInInputWithInjections);
    } else {
      r2 = model.getValueInRange({
        startLineNumber: modelLineNumber,
        startColumn: startOffsetInInputWithInjections + 1,
        endLineNumber: modelLineNumber,
        endColumn: endOffsetInInputWithInjections + 1
      });
    }
    if (outputLineIndex > 0) {
      r2 = spaces(this.a.wrappedTextIndentLength) + r2;
    }
    return r2;
  }
  getViewLineLength(model, modelLineNumber, outputLineIndex) {
    this.d();
    return this.a.getLineLength(outputLineIndex);
  }
  getViewLineMinColumn(_model, _modelLineNumber, outputLineIndex) {
    this.d();
    return this.a.getMinOutputOffset(outputLineIndex) + 1;
  }
  getViewLineMaxColumn(model, modelLineNumber, outputLineIndex) {
    this.d();
    return this.a.getMaxOutputOffset(outputLineIndex) + 1;
  }
  /**
   * Try using {@link getViewLinesData} instead.
  */
  getViewLineData(model, modelLineNumber, outputLineIndex) {
    const arr = new Array();
    this.getViewLinesData(model, modelLineNumber, outputLineIndex, 1, 0, [true], arr);
    return arr[0];
  }
  getViewLinesData(model, modelLineNumber, outputLineIdx, lineCount, globalStartIndex, needed, result) {
    this.d();
    const lineBreakData = this.a;
    const injectionOffsets = lineBreakData.injectionOffsets;
    const injectionOptions = lineBreakData.injectionOptions;
    let inlineDecorationsPerOutputLine = null;
    if (injectionOffsets) {
      inlineDecorationsPerOutputLine = [];
      let totalInjectedTextLengthBefore = 0;
      let currentInjectedOffset = 0;
      for (let outputLineIndex = 0; outputLineIndex < lineBreakData.getOutputLineCount(); outputLineIndex++) {
        const inlineDecorations = new Array();
        inlineDecorationsPerOutputLine[outputLineIndex] = inlineDecorations;
        const lineStartOffsetInInputWithInjections = outputLineIndex > 0 ? lineBreakData.breakOffsets[outputLineIndex - 1] : 0;
        const lineEndOffsetInInputWithInjections = lineBreakData.breakOffsets[outputLineIndex];
        while (currentInjectedOffset < injectionOffsets.length) {
          const length = injectionOptions[currentInjectedOffset].content.length;
          const injectedTextStartOffsetInInputWithInjections = injectionOffsets[currentInjectedOffset] + totalInjectedTextLengthBefore;
          const injectedTextEndOffsetInInputWithInjections = injectedTextStartOffsetInInputWithInjections + length;
          if (injectedTextStartOffsetInInputWithInjections > lineEndOffsetInInputWithInjections) {
            break;
          }
          if (lineStartOffsetInInputWithInjections < injectedTextEndOffsetInInputWithInjections) {
            const options3 = injectionOptions[currentInjectedOffset];
            if (options3.inlineClassName) {
              const offset = outputLineIndex > 0 ? lineBreakData.wrappedTextIndentLength : 0;
              const start = offset + Math.max(injectedTextStartOffsetInInputWithInjections - lineStartOffsetInInputWithInjections, 0);
              const end = offset + Math.min(injectedTextEndOffsetInInputWithInjections - lineStartOffsetInInputWithInjections, lineEndOffsetInInputWithInjections - lineStartOffsetInInputWithInjections);
              if (start !== end) {
                inlineDecorations.push(new $J5(start, end, options3.inlineClassName, options3.inlineClassNameAffectsLetterSpacing));
              }
            }
          }
          if (injectedTextEndOffsetInInputWithInjections <= lineEndOffsetInInputWithInjections) {
            totalInjectedTextLengthBefore += length;
            currentInjectedOffset++;
          } else {
            break;
          }
        }
      }
    }
    let lineWithInjections;
    if (injectionOffsets) {
      const tokensToInsert = [];
      for (let idx = 0; idx < injectionOffsets.length; idx++) {
        const offset = injectionOffsets[idx];
        const tokens = injectionOptions[idx].tokens;
        if (tokens) {
          tokens.forEach((range, info) => {
            tokensToInsert.push({
              offset,
              text: range.substring(injectionOptions[idx].content),
              tokenMetadata: info.metadata
            });
          });
        } else {
          tokensToInsert.push({
            offset,
            text: injectionOptions[idx].content,
            tokenMetadata: $xE.defaultTokenMetadata
          });
        }
      }
      lineWithInjections = model.tokenization.getLineTokens(modelLineNumber).withInserted(tokensToInsert);
    } else {
      lineWithInjections = model.tokenization.getLineTokens(modelLineNumber);
    }
    for (let outputLineIndex = outputLineIdx; outputLineIndex < outputLineIdx + lineCount; outputLineIndex++) {
      const globalIndex = globalStartIndex + outputLineIndex - outputLineIdx;
      if (!needed[globalIndex]) {
        result[globalIndex] = null;
        continue;
      }
      result[globalIndex] = this.c(lineWithInjections, inlineDecorationsPerOutputLine ? inlineDecorationsPerOutputLine[outputLineIndex] : null, outputLineIndex);
    }
  }
  c(lineWithInjections, inlineDecorations, outputLineIndex) {
    this.d();
    const lineBreakData = this.a;
    const deltaStartIndex = outputLineIndex > 0 ? lineBreakData.wrappedTextIndentLength : 0;
    const lineStartOffsetInInputWithInjections = outputLineIndex > 0 ? lineBreakData.breakOffsets[outputLineIndex - 1] : 0;
    const lineEndOffsetInInputWithInjections = lineBreakData.breakOffsets[outputLineIndex];
    const tokens = lineWithInjections.sliceAndInflate(lineStartOffsetInInputWithInjections, lineEndOffsetInInputWithInjections, deltaStartIndex);
    let lineContent = tokens.getLineContent();
    if (outputLineIndex > 0) {
      lineContent = spaces(lineBreakData.wrappedTextIndentLength) + lineContent;
    }
    const minColumn = this.a.getMinOutputOffset(outputLineIndex) + 1;
    const maxColumn = lineContent.length + 1;
    const continuesWithWrappedLine = outputLineIndex + 1 < this.getViewLineCount();
    const startVisibleColumn = outputLineIndex === 0 ? 0 : lineBreakData.breakOffsetsVisibleColumn[outputLineIndex - 1];
    return new $G5(lineContent, continuesWithWrappedLine, minColumn, maxColumn, startVisibleColumn, tokens, inlineDecorations);
  }
  getModelColumnOfViewPosition(outputLineIndex, outputColumn) {
    this.d();
    return this.a.translateToInputOffset(outputLineIndex, outputColumn - 1) + 1;
  }
  getViewPositionOfModelPosition(deltaLineNumber, inputColumn, affinity = 2) {
    this.d();
    const r2 = this.a.translateToOutputPosition(inputColumn - 1, affinity);
    return r2.toPosition(deltaLineNumber);
  }
  getViewLineNumberOfModelPosition(deltaLineNumber, inputColumn) {
    this.d();
    const r2 = this.a.translateToOutputPosition(inputColumn - 1);
    return deltaLineNumber + r2.outputLineIndex;
  }
  normalizePosition(outputLineIndex, outputPosition, affinity) {
    const baseViewLineNumber = outputPosition.lineNumber - outputLineIndex;
    const normalizedOutputPosition = this.a.normalizeOutputPosition(outputLineIndex, outputPosition.column - 1, affinity);
    const result = normalizedOutputPosition.toPosition(baseViewLineNumber);
    return result;
  }
  getInjectedTextAt(outputLineIndex, outputColumn) {
    return this.a.getInjectedText(outputLineIndex, outputColumn - 1);
  }
  d() {
    if (!this.b) {
      throw new Error("Not supported");
    }
  }
};
var IdentityModelLineProjection = class _IdentityModelLineProjection {
  static {
    this.INSTANCE = new _IdentityModelLineProjection();
  }
  constructor() {
  }
  isVisible() {
    return true;
  }
  setVisible(isVisible) {
    if (isVisible) {
      return this;
    }
    return HiddenModelLineProjection.INSTANCE;
  }
  getProjectionData() {
    return null;
  }
  getViewLineCount() {
    return 1;
  }
  getViewLineContent(model, modelLineNumber, _outputLineIndex) {
    return model.getLineContent(modelLineNumber);
  }
  getViewLineLength(model, modelLineNumber, _outputLineIndex) {
    return model.getLineLength(modelLineNumber);
  }
  getViewLineMinColumn(model, modelLineNumber, _outputLineIndex) {
    return model.getLineMinColumn(modelLineNumber);
  }
  getViewLineMaxColumn(model, modelLineNumber, _outputLineIndex) {
    return model.getLineMaxColumn(modelLineNumber);
  }
  getViewLineData(model, modelLineNumber, _outputLineIndex) {
    const lineTokens = model.tokenization.getLineTokens(modelLineNumber);
    const lineContent = lineTokens.getLineContent();
    return new $G5(lineContent, false, 1, lineContent.length + 1, 0, lineTokens.inflate(), null);
  }
  getViewLinesData(model, modelLineNumber, _fromOuputLineIndex, _toOutputLineIndex, globalStartIndex, needed, result) {
    if (!needed[globalStartIndex]) {
      result[globalStartIndex] = null;
      return;
    }
    result[globalStartIndex] = this.getViewLineData(model, modelLineNumber, 0);
  }
  getModelColumnOfViewPosition(_outputLineIndex, outputColumn) {
    return outputColumn;
  }
  getViewPositionOfModelPosition(deltaLineNumber, inputColumn) {
    return new $8C(deltaLineNumber, inputColumn);
  }
  getViewLineNumberOfModelPosition(deltaLineNumber, _inputColumn) {
    return deltaLineNumber;
  }
  normalizePosition(outputLineIndex, outputPosition, affinity) {
    return outputPosition;
  }
  getInjectedTextAt(_outputLineIndex, _outputColumn) {
    return null;
  }
};
var HiddenModelLineProjection = class _HiddenModelLineProjection {
  static {
    this.INSTANCE = new _HiddenModelLineProjection();
  }
  constructor() {
  }
  isVisible() {
    return false;
  }
  setVisible(isVisible) {
    if (!isVisible) {
      return this;
    }
    return IdentityModelLineProjection.INSTANCE;
  }
  getProjectionData() {
    return null;
  }
  getViewLineCount() {
    return 0;
  }
  getViewLineContent(_model, _modelLineNumber, _outputLineIndex) {
    throw new Error("Not supported");
  }
  getViewLineLength(_model, _modelLineNumber, _outputLineIndex) {
    throw new Error("Not supported");
  }
  getViewLineMinColumn(_model, _modelLineNumber, _outputLineIndex) {
    throw new Error("Not supported");
  }
  getViewLineMaxColumn(_model, _modelLineNumber, _outputLineIndex) {
    throw new Error("Not supported");
  }
  getViewLineData(_model, _modelLineNumber, _outputLineIndex) {
    throw new Error("Not supported");
  }
  getViewLinesData(_model, _modelLineNumber, _fromOuputLineIndex, _toOutputLineIndex, _globalStartIndex, _needed, _result) {
    throw new Error("Not supported");
  }
  getModelColumnOfViewPosition(_outputLineIndex, _outputColumn) {
    throw new Error("Not supported");
  }
  getViewPositionOfModelPosition(_deltaLineNumber, _inputColumn) {
    throw new Error("Not supported");
  }
  getViewLineNumberOfModelPosition(_deltaLineNumber, _inputColumn) {
    throw new Error("Not supported");
  }
  normalizePosition(outputLineIndex, outputPosition, affinity) {
    throw new Error("Not supported");
  }
  getInjectedTextAt(_outputLineIndex, _outputColumn) {
    throw new Error("Not supported");
  }
};
var _spaces = [""];
function spaces(count) {
  if (count >= _spaces.length) {
    for (let i2 = 1; i2 <= count; i2++) {
      _spaces[i2] = _makeSpaces(i2);
    }
  }
  return _spaces[count];
}
function _makeSpaces(count) {
  return new Array(count + 1).join(" ");
}

// out-build/vs/editor/common/model/prefixSumComputer.js
var $wM = class {
  constructor(values) {
    this.a = values;
    this.b = new Uint32Array(values.length);
    this.c = new Int32Array(1);
    this.c[0] = -1;
  }
  getCount() {
    return this.a.length;
  }
  insertValues(insertIndex, insertValues) {
    insertIndex = $uf(insertIndex);
    const oldValues = this.a;
    const oldPrefixSum = this.b;
    const insertValuesLen = insertValues.length;
    if (insertValuesLen === 0) {
      return false;
    }
    this.a = new Uint32Array(oldValues.length + insertValuesLen);
    this.a.set(oldValues.subarray(0, insertIndex), 0);
    this.a.set(oldValues.subarray(insertIndex), insertIndex + insertValuesLen);
    this.a.set(insertValues, insertIndex);
    if (insertIndex - 1 < this.c[0]) {
      this.c[0] = insertIndex - 1;
    }
    this.b = new Uint32Array(this.a.length);
    if (this.c[0] >= 0) {
      this.b.set(oldPrefixSum.subarray(0, this.c[0] + 1));
    }
    return true;
  }
  setValue(index, value) {
    index = $uf(index);
    value = $uf(value);
    if (this.a[index] === value) {
      return false;
    }
    this.a[index] = value;
    if (index - 1 < this.c[0]) {
      this.c[0] = index - 1;
    }
    return true;
  }
  removeValues(startIndex, count) {
    startIndex = $uf(startIndex);
    count = $uf(count);
    const oldValues = this.a;
    const oldPrefixSum = this.b;
    if (startIndex >= oldValues.length) {
      return false;
    }
    const maxCount = oldValues.length - startIndex;
    if (count >= maxCount) {
      count = maxCount;
    }
    if (count === 0) {
      return false;
    }
    this.a = new Uint32Array(oldValues.length - count);
    this.a.set(oldValues.subarray(0, startIndex), 0);
    this.a.set(oldValues.subarray(startIndex + count), startIndex);
    this.b = new Uint32Array(this.a.length);
    if (startIndex - 1 < this.c[0]) {
      this.c[0] = startIndex - 1;
    }
    if (this.c[0] >= 0) {
      this.b.set(oldPrefixSum.subarray(0, this.c[0] + 1));
    }
    return true;
  }
  getTotalSum() {
    if (this.a.length === 0) {
      return 0;
    }
    return this.d(this.a.length - 1);
  }
  /**
   * Returns the sum of the first `index + 1` many items.
   * @returns `SUM(0 <= j <= index, values[j])`.
   */
  getPrefixSum(index) {
    if (index < 0) {
      return 0;
    }
    index = $uf(index);
    return this.d(index);
  }
  d(index) {
    if (index <= this.c[0]) {
      return this.b[index];
    }
    let startIndex = this.c[0] + 1;
    if (startIndex === 0) {
      this.b[0] = this.a[0];
      startIndex++;
    }
    if (index >= this.a.length) {
      index = this.a.length - 1;
    }
    for (let i2 = startIndex; i2 <= index; i2++) {
      this.b[i2] = this.b[i2 - 1] + this.a[i2];
    }
    this.c[0] = Math.max(this.c[0], index);
    return this.b[index];
  }
  getIndexOf(sum) {
    sum = Math.floor(sum);
    this.getTotalSum();
    let low = 0;
    let high = this.a.length - 1;
    let mid = 0;
    let midStop = 0;
    let midStart = 0;
    while (low <= high) {
      mid = low + (high - low) / 2 | 0;
      midStop = this.b[mid];
      midStart = midStop - this.a[mid];
      if (sum < midStart) {
        high = mid - 1;
      } else if (sum >= midStop) {
        low = mid + 1;
      } else {
        break;
      }
    }
    return new $yM(mid, sum - midStart);
  }
};
var $xM = class {
  constructor(values) {
    this.a = values;
    this.b = false;
    this.c = -1;
    this.d = [];
    this.e = [];
  }
  /**
   * @returns SUM(0 <= j < values.length, values[j])
   */
  getTotalSum() {
    this.g();
    return this.e.length;
  }
  /**
   * Returns the sum of the first `count` many items.
   * @returns `SUM(0 <= j < count, values[j])`.
   */
  getPrefixSum(count) {
    this.g();
    if (count === 0) {
      return 0;
    }
    return this.d[count - 1];
  }
  /**
   * @returns `result`, such that `getPrefixSum(result.index) + result.remainder = sum`
   */
  getIndexOf(sum) {
    this.g();
    const idx = this.e[sum];
    const viewLinesAbove = idx > 0 ? this.d[idx - 1] : 0;
    return new $yM(idx, sum - viewLinesAbove);
  }
  removeValues(start, deleteCount) {
    this.a.splice(start, deleteCount);
    this.f(start);
  }
  insertValues(insertIndex, insertArr) {
    this.a = $Yb(this.a, insertIndex, insertArr);
    this.f(insertIndex);
  }
  f(index) {
    this.b = false;
    this.c = Math.min(this.c, index - 1);
  }
  g() {
    if (this.b) {
      return;
    }
    for (let i2 = this.c + 1, len = this.a.length; i2 < len; i2++) {
      const value = this.a[i2];
      const sumAbove = i2 > 0 ? this.d[i2 - 1] : 0;
      this.d[i2] = sumAbove + value;
      for (let j = 0; j < value; j++) {
        this.e[sumAbove + j] = i2;
      }
    }
    this.d.length = this.a.length;
    this.e.length = this.d[this.d.length - 1];
    this.b = true;
    this.c = this.a.length - 1;
  }
  setValue(index, value) {
    if (this.a[index] === value) {
      return;
    }
    this.a[index] = value;
    this.f(index);
  }
};
var $yM = class {
  constructor(index, remainder) {
    this.index = index;
    this.remainder = remainder;
    this._prefixSumIndexOfResultBrand = void 0;
    this.index = index;
    this.remainder = remainder;
  }
};

// out-build/vs/editor/common/viewModel/viewModelLines.js
var $v9 = class {
  constructor(editorId, model, domLineBreaksComputerFactory, monospaceLineBreaksComputerFactory, fontInfo, tabSize, wrappingStrategy, wrappingColumn, wrappingIndent, wordBreak) {
    this.c = editorId;
    this.d = model;
    this.e = -1;
    this.f = domLineBreaksComputerFactory;
    this.h = monospaceLineBreaksComputerFactory;
    this.k = fontInfo;
    this.l = tabSize;
    this.q = wrappingStrategy;
    this.m = wrappingColumn;
    this.n = wrappingIndent;
    this.o = wordBreak;
    this.w(
      /*resetHiddenAreas*/
      true,
      null
    );
  }
  dispose() {
    this.v = this.d.deltaDecorations(this.v, []);
  }
  createCoordinatesConverter() {
    return new CoordinatesConverter(this);
  }
  w(resetHiddenAreas, previousLineBreaks) {
    this.s = [];
    if (resetHiddenAreas) {
      this.v = this.d.deltaDecorations(this.v, []);
    }
    const linesContent = this.d.getLinesContent();
    const injectedTextDecorations = this.d.getInjectedTextDecorations(this.c);
    const lineCount = linesContent.length;
    const lineBreaksComputer = this.createLineBreaksComputer();
    const injectedTextQueue = new $bc($FE.fromDecorations(injectedTextDecorations));
    for (let i2 = 0; i2 < lineCount; i2++) {
      const lineInjectedText = injectedTextQueue.takeWhile((t) => t.lineNumber === i2 + 1);
      lineBreaksComputer.addRequest(linesContent[i2], lineInjectedText, previousLineBreaks ? previousLineBreaks[i2] : null);
    }
    const linesBreaks = lineBreaksComputer.finalize();
    const values = [];
    const hiddenAreas = this.v.map((areaId) => this.d.getDecorationRange(areaId)).sort($9C.compareRangesUsingStarts);
    let hiddenAreaStart = 1, hiddenAreaEnd = 0;
    let hiddenAreaIdx = -1;
    let nextLineNumberToUpdateHiddenArea = hiddenAreaIdx + 1 < hiddenAreas.length ? hiddenAreaEnd + 1 : lineCount + 2;
    for (let i2 = 0; i2 < lineCount; i2++) {
      const lineNumber = i2 + 1;
      if (lineNumber === nextLineNumberToUpdateHiddenArea) {
        hiddenAreaIdx++;
        hiddenAreaStart = hiddenAreas[hiddenAreaIdx].startLineNumber;
        hiddenAreaEnd = hiddenAreas[hiddenAreaIdx].endLineNumber;
        nextLineNumberToUpdateHiddenArea = hiddenAreaIdx + 1 < hiddenAreas.length ? hiddenAreaEnd + 1 : lineCount + 2;
      }
      const isInHiddenArea = lineNumber >= hiddenAreaStart && lineNumber <= hiddenAreaEnd;
      const line = $u9(linesBreaks[i2], !isInHiddenArea);
      values[i2] = line.getViewLineCount();
      this.s[i2] = line;
    }
    this.e = this.d.getVersionId();
    this.u = new $xM(values);
  }
  getHiddenAreas() {
    return this.v.map((decId) => this.d.getDecorationRange(decId));
  }
  setHiddenAreas(_ranges) {
    const validatedRanges = _ranges.map((r2) => this.d.validateRange(r2));
    const newRanges = normalizeLineRanges(validatedRanges);
    const oldRanges = this.v.map((areaId) => this.d.getDecorationRange(areaId)).sort($9C.compareRangesUsingStarts);
    if (newRanges.length === oldRanges.length) {
      let hasDifference = false;
      for (let i2 = 0; i2 < newRanges.length; i2++) {
        if (!newRanges[i2].equalsRange(oldRanges[i2])) {
          hasDifference = true;
          break;
        }
      }
      if (!hasDifference) {
        return false;
      }
    }
    const newDecorations = newRanges.map((r2) => ({
      range: r2,
      options: $WI.EMPTY
    }));
    this.v = this.d.deltaDecorations(this.v, newDecorations);
    const hiddenAreas = newRanges;
    let hiddenAreaStart = 1, hiddenAreaEnd = 0;
    let hiddenAreaIdx = -1;
    let nextLineNumberToUpdateHiddenArea = hiddenAreaIdx + 1 < hiddenAreas.length ? hiddenAreaEnd + 1 : this.s.length + 2;
    let hasVisibleLine = false;
    for (let i2 = 0; i2 < this.s.length; i2++) {
      const lineNumber = i2 + 1;
      if (lineNumber === nextLineNumberToUpdateHiddenArea) {
        hiddenAreaIdx++;
        hiddenAreaStart = hiddenAreas[hiddenAreaIdx].startLineNumber;
        hiddenAreaEnd = hiddenAreas[hiddenAreaIdx].endLineNumber;
        nextLineNumberToUpdateHiddenArea = hiddenAreaIdx + 1 < hiddenAreas.length ? hiddenAreaEnd + 1 : this.s.length + 2;
      }
      let lineChanged = false;
      if (lineNumber >= hiddenAreaStart && lineNumber <= hiddenAreaEnd) {
        if (this.s[i2].isVisible()) {
          this.s[i2] = this.s[i2].setVisible(false);
          lineChanged = true;
        }
      } else {
        hasVisibleLine = true;
        if (!this.s[i2].isVisible()) {
          this.s[i2] = this.s[i2].setVisible(true);
          lineChanged = true;
        }
      }
      if (lineChanged) {
        const newOutputLineCount = this.s[i2].getViewLineCount();
        this.u.setValue(i2, newOutputLineCount);
      }
    }
    if (!hasVisibleLine) {
      this.setHiddenAreas([]);
    }
    return true;
  }
  modelPositionIsVisible(modelLineNumber, _modelColumn) {
    if (modelLineNumber < 1 || modelLineNumber > this.s.length) {
      return false;
    }
    return this.s[modelLineNumber - 1].isVisible();
  }
  getModelLineViewLineCount(modelLineNumber) {
    if (modelLineNumber < 1 || modelLineNumber > this.s.length) {
      return 1;
    }
    return this.s[modelLineNumber - 1].getViewLineCount();
  }
  setTabSize(newTabSize) {
    if (this.l === newTabSize) {
      return false;
    }
    this.l = newTabSize;
    this.w(
      /*resetHiddenAreas*/
      false,
      null
    );
    return true;
  }
  setWrappingSettings(fontInfo, wrappingStrategy, wrappingColumn, wrappingIndent, wordBreak) {
    const equalFontInfo = this.k.equals(fontInfo);
    const equalWrappingStrategy = this.q === wrappingStrategy;
    const equalWrappingColumn = this.m === wrappingColumn;
    const equalWrappingIndent = this.n === wrappingIndent;
    const equalWordBreak = this.o === wordBreak;
    if (equalFontInfo && equalWrappingStrategy && equalWrappingColumn && equalWrappingIndent && equalWordBreak) {
      return false;
    }
    const onlyWrappingColumnChanged = equalFontInfo && equalWrappingStrategy && !equalWrappingColumn && equalWrappingIndent && equalWordBreak;
    this.k = fontInfo;
    this.q = wrappingStrategy;
    this.m = wrappingColumn;
    this.n = wrappingIndent;
    this.o = wordBreak;
    let previousLineBreaks = null;
    if (onlyWrappingColumnChanged) {
      previousLineBreaks = [];
      for (let i2 = 0, len = this.s.length; i2 < len; i2++) {
        previousLineBreaks[i2] = this.s[i2].getProjectionData();
      }
    }
    this.w(
      /*resetHiddenAreas*/
      false,
      previousLineBreaks
    );
    return true;
  }
  createLineBreaksComputer() {
    const lineBreaksComputerFactory = this.q === "advanced" ? this.f : this.h;
    return lineBreaksComputerFactory.createLineBreaksComputer(this.k, this.l, this.m, this.n, this.o);
  }
  onModelFlushed() {
    this.w(
      /*resetHiddenAreas*/
      true,
      null
    );
  }
  onModelLinesDeleted(versionId, fromLineNumber, toLineNumber) {
    if (!versionId || versionId <= this.e) {
      return null;
    }
    const outputFromLineNumber = fromLineNumber === 1 ? 1 : this.u.getPrefixSum(fromLineNumber - 1) + 1;
    const outputToLineNumber = this.u.getPrefixSum(toLineNumber);
    this.s.splice(fromLineNumber - 1, toLineNumber - fromLineNumber + 1);
    this.u.removeValues(fromLineNumber - 1, toLineNumber - fromLineNumber + 1);
    return new $v5(outputFromLineNumber, outputToLineNumber);
  }
  onModelLinesInserted(versionId, fromLineNumber, _toLineNumber, lineBreaks) {
    if (!versionId || versionId <= this.e) {
      return null;
    }
    const isInHiddenArea = fromLineNumber > 2 && !this.s[fromLineNumber - 2].isVisible();
    const outputFromLineNumber = fromLineNumber === 1 ? 1 : this.u.getPrefixSum(fromLineNumber - 1) + 1;
    let totalOutputLineCount = 0;
    const insertLines = [];
    const insertPrefixSumValues = [];
    for (let i2 = 0, len = lineBreaks.length; i2 < len; i2++) {
      const line = $u9(lineBreaks[i2], !isInHiddenArea);
      insertLines.push(line);
      const outputLineCount = line.getViewLineCount();
      totalOutputLineCount += outputLineCount;
      insertPrefixSumValues[i2] = outputLineCount;
    }
    this.s = this.s.slice(0, fromLineNumber - 1).concat(insertLines).concat(this.s.slice(fromLineNumber - 1));
    this.u.insertValues(fromLineNumber - 1, insertPrefixSumValues);
    return new $w5(outputFromLineNumber, outputFromLineNumber + totalOutputLineCount - 1);
  }
  onModelLineChanged(versionId, lineNumber, lineBreakData) {
    if (versionId !== null && versionId <= this.e) {
      return [false, null, null, null];
    }
    const lineIndex = lineNumber - 1;
    const oldOutputLineCount = this.s[lineIndex].getViewLineCount();
    const isVisible = this.s[lineIndex].isVisible();
    const line = $u9(lineBreakData, isVisible);
    this.s[lineIndex] = line;
    const newOutputLineCount = this.s[lineIndex].getViewLineCount();
    let lineMappingChanged = false;
    let changeFrom = 0;
    let changeTo = -1;
    let insertFrom = 0;
    let insertTo = -1;
    let deleteFrom = 0;
    let deleteTo = -1;
    if (oldOutputLineCount > newOutputLineCount) {
      changeFrom = this.u.getPrefixSum(lineNumber - 1) + 1;
      changeTo = changeFrom + newOutputLineCount - 1;
      deleteFrom = changeTo + 1;
      deleteTo = deleteFrom + (oldOutputLineCount - newOutputLineCount) - 1;
      lineMappingChanged = true;
    } else if (oldOutputLineCount < newOutputLineCount) {
      changeFrom = this.u.getPrefixSum(lineNumber - 1) + 1;
      changeTo = changeFrom + oldOutputLineCount - 1;
      insertFrom = changeTo + 1;
      insertTo = insertFrom + (newOutputLineCount - oldOutputLineCount) - 1;
      lineMappingChanged = true;
    } else {
      changeFrom = this.u.getPrefixSum(lineNumber - 1) + 1;
      changeTo = changeFrom + newOutputLineCount - 1;
    }
    this.u.setValue(lineIndex, newOutputLineCount);
    const viewLinesChangedEvent = changeFrom <= changeTo ? new $u5(changeFrom, changeTo - changeFrom + 1) : null;
    const viewLinesInsertedEvent = insertFrom <= insertTo ? new $w5(insertFrom, insertTo) : null;
    const viewLinesDeletedEvent = deleteFrom <= deleteTo ? new $v5(deleteFrom, deleteTo) : null;
    return [lineMappingChanged, viewLinesChangedEvent, viewLinesInsertedEvent, viewLinesDeletedEvent];
  }
  acceptVersionId(versionId) {
    this.e = versionId;
    if (this.s.length === 1 && !this.s[0].isVisible()) {
      this.setHiddenAreas([]);
    }
  }
  getViewLineCount() {
    return this.u.getTotalSum();
  }
  x(viewLineNumber) {
    if (viewLineNumber < 1) {
      return 1;
    }
    const viewLineCount = this.getViewLineCount();
    if (viewLineNumber > viewLineCount) {
      return viewLineCount;
    }
    return viewLineNumber | 0;
  }
  getActiveIndentGuide(viewLineNumber, minLineNumber, maxLineNumber) {
    viewLineNumber = this.x(viewLineNumber);
    minLineNumber = this.x(minLineNumber);
    maxLineNumber = this.x(maxLineNumber);
    const modelPosition = this.convertViewPositionToModelPosition(viewLineNumber, this.getViewLineMinColumn(viewLineNumber));
    const modelMinPosition = this.convertViewPositionToModelPosition(minLineNumber, this.getViewLineMinColumn(minLineNumber));
    const modelMaxPosition = this.convertViewPositionToModelPosition(maxLineNumber, this.getViewLineMinColumn(maxLineNumber));
    const result = this.d.guides.getActiveIndentGuide(modelPosition.lineNumber, modelMinPosition.lineNumber, modelMaxPosition.lineNumber);
    const viewStartPosition = this.convertModelPositionToViewPosition(result.startLineNumber, 1);
    const viewEndPosition = this.convertModelPositionToViewPosition(result.endLineNumber, this.d.getLineMaxColumn(result.endLineNumber));
    return {
      startLineNumber: viewStartPosition.lineNumber,
      endLineNumber: viewEndPosition.lineNumber,
      indent: result.indent
    };
  }
  // #region ViewLineInfo
  y(viewLineNumber) {
    viewLineNumber = this.x(viewLineNumber);
    const r2 = this.u.getIndexOf(viewLineNumber - 1);
    const lineIndex = r2.index;
    const remainder = r2.remainder;
    return new ViewLineInfo(lineIndex + 1, remainder);
  }
  z(viewLineInfo) {
    return this.s[viewLineInfo.modelLineNumber - 1].getViewLineMinColumn(this.d, viewLineInfo.modelLineNumber, viewLineInfo.modelLineWrappedLineIdx);
  }
  A(viewLineInfo) {
    return this.s[viewLineInfo.modelLineNumber - 1].getViewLineMaxColumn(this.d, viewLineInfo.modelLineNumber, viewLineInfo.modelLineWrappedLineIdx);
  }
  B(viewLineInfo) {
    const line = this.s[viewLineInfo.modelLineNumber - 1];
    const minViewColumn = line.getViewLineMinColumn(this.d, viewLineInfo.modelLineNumber, viewLineInfo.modelLineWrappedLineIdx);
    const column = line.getModelColumnOfViewPosition(viewLineInfo.modelLineWrappedLineIdx, minViewColumn);
    return new $8C(viewLineInfo.modelLineNumber, column);
  }
  C(viewLineInfo) {
    const line = this.s[viewLineInfo.modelLineNumber - 1];
    const maxViewColumn = line.getViewLineMaxColumn(this.d, viewLineInfo.modelLineNumber, viewLineInfo.modelLineWrappedLineIdx);
    const column = line.getModelColumnOfViewPosition(viewLineInfo.modelLineWrappedLineIdx, maxViewColumn);
    return new $8C(viewLineInfo.modelLineNumber, column);
  }
  D(viewStartLineNumber, viewEndLineNumber) {
    const startViewLine = this.y(viewStartLineNumber);
    const endViewLine = this.y(viewEndLineNumber);
    const result = new Array();
    let lastVisibleModelPos = this.B(startViewLine);
    let viewLines = new Array();
    for (let curModelLine = startViewLine.modelLineNumber; curModelLine <= endViewLine.modelLineNumber; curModelLine++) {
      const line = this.s[curModelLine - 1];
      if (line.isVisible()) {
        const startOffset = curModelLine === startViewLine.modelLineNumber ? startViewLine.modelLineWrappedLineIdx : 0;
        const endOffset = curModelLine === endViewLine.modelLineNumber ? endViewLine.modelLineWrappedLineIdx + 1 : line.getViewLineCount();
        for (let i2 = startOffset; i2 < endOffset; i2++) {
          viewLines.push(new ViewLineInfo(curModelLine, i2));
        }
      }
      if (!line.isVisible() && lastVisibleModelPos) {
        const lastVisibleModelPos2 = new $8C(curModelLine - 1, this.d.getLineMaxColumn(curModelLine - 1) + 1);
        const modelRange = $9C.fromPositions(lastVisibleModelPos, lastVisibleModelPos2);
        result.push(new ViewLineInfoGroupedByModelRange(modelRange, viewLines));
        viewLines = [];
        lastVisibleModelPos = null;
      } else if (line.isVisible() && !lastVisibleModelPos) {
        lastVisibleModelPos = new $8C(curModelLine, 1);
      }
    }
    if (lastVisibleModelPos) {
      const modelRange = $9C.fromPositions(lastVisibleModelPos, this.C(endViewLine));
      result.push(new ViewLineInfoGroupedByModelRange(modelRange, viewLines));
    }
    return result;
  }
  // #endregion
  getViewLinesBracketGuides(viewStartLineNumber, viewEndLineNumber, activeViewPosition, options3) {
    const modelActivePosition = activeViewPosition ? this.convertViewPositionToModelPosition(activeViewPosition.lineNumber, activeViewPosition.column) : null;
    const resultPerViewLine = [];
    for (const group2 of this.D(viewStartLineNumber, viewEndLineNumber)) {
      const modelRangeStartLineNumber = group2.modelRange.startLineNumber;
      const bracketGuidesPerModelLine = this.d.guides.getLinesBracketGuides(modelRangeStartLineNumber, group2.modelRange.endLineNumber, modelActivePosition, options3);
      for (const viewLineInfo of group2.viewLines) {
        const bracketGuides = bracketGuidesPerModelLine[viewLineInfo.modelLineNumber - modelRangeStartLineNumber];
        const result = bracketGuides.map((g) => {
          if (g.forWrappedLinesAfterColumn !== -1) {
            const p2 = this.s[viewLineInfo.modelLineNumber - 1].getViewPositionOfModelPosition(0, g.forWrappedLinesAfterColumn);
            if (p2.lineNumber >= viewLineInfo.modelLineWrappedLineIdx) {
              return void 0;
            }
          }
          if (g.forWrappedLinesBeforeOrAtColumn !== -1) {
            const p2 = this.s[viewLineInfo.modelLineNumber - 1].getViewPositionOfModelPosition(0, g.forWrappedLinesBeforeOrAtColumn);
            if (p2.lineNumber < viewLineInfo.modelLineWrappedLineIdx) {
              return void 0;
            }
          }
          if (!g.horizontalLine) {
            return g;
          }
          let column = -1;
          if (g.column !== -1) {
            const p2 = this.s[viewLineInfo.modelLineNumber - 1].getViewPositionOfModelPosition(0, g.column);
            if (p2.lineNumber === viewLineInfo.modelLineWrappedLineIdx) {
              column = p2.column;
            } else if (p2.lineNumber < viewLineInfo.modelLineWrappedLineIdx) {
              column = this.z(viewLineInfo);
            } else if (p2.lineNumber > viewLineInfo.modelLineWrappedLineIdx) {
              return void 0;
            }
          }
          const viewPosition = this.convertModelPositionToViewPosition(viewLineInfo.modelLineNumber, g.horizontalLine.endColumn);
          const p = this.s[viewLineInfo.modelLineNumber - 1].getViewPositionOfModelPosition(0, g.horizontalLine.endColumn);
          if (p.lineNumber === viewLineInfo.modelLineWrappedLineIdx) {
            return new $7F(g.visibleColumn, column, g.className, new $8F(g.horizontalLine.top, viewPosition.column), -1, -1);
          } else if (p.lineNumber < viewLineInfo.modelLineWrappedLineIdx) {
            return void 0;
          } else {
            if (g.visibleColumn !== -1) {
              return void 0;
            }
            return new $7F(g.visibleColumn, column, g.className, new $8F(g.horizontalLine.top, this.A(viewLineInfo)), -1, -1);
          }
        });
        resultPerViewLine.push(result.filter((r2) => !!r2));
      }
    }
    return resultPerViewLine;
  }
  getViewLinesIndentGuides(viewStartLineNumber, viewEndLineNumber) {
    viewStartLineNumber = this.x(viewStartLineNumber);
    viewEndLineNumber = this.x(viewEndLineNumber);
    const modelStart = this.convertViewPositionToModelPosition(viewStartLineNumber, this.getViewLineMinColumn(viewStartLineNumber));
    const modelEnd = this.convertViewPositionToModelPosition(viewEndLineNumber, this.getViewLineMaxColumn(viewEndLineNumber));
    let result = [];
    const resultRepeatCount = [];
    const resultRepeatOption = [];
    const modelStartLineIndex = modelStart.lineNumber - 1;
    const modelEndLineIndex = modelEnd.lineNumber - 1;
    let reqStart = null;
    for (let modelLineIndex = modelStartLineIndex; modelLineIndex <= modelEndLineIndex; modelLineIndex++) {
      const line = this.s[modelLineIndex];
      if (line.isVisible()) {
        const viewLineStartIndex = line.getViewLineNumberOfModelPosition(0, modelLineIndex === modelStartLineIndex ? modelStart.column : 1);
        const viewLineEndIndex = line.getViewLineNumberOfModelPosition(0, this.d.getLineMaxColumn(modelLineIndex + 1));
        const count = viewLineEndIndex - viewLineStartIndex + 1;
        let option = 0;
        if (count > 1 && line.getViewLineMinColumn(this.d, modelLineIndex + 1, viewLineEndIndex) === 1) {
          option = viewLineStartIndex === 0 ? 1 : 2;
        }
        resultRepeatCount.push(count);
        resultRepeatOption.push(option);
        if (reqStart === null) {
          reqStart = new $8C(modelLineIndex + 1, 0);
        }
      } else {
        if (reqStart !== null) {
          result = result.concat(this.d.guides.getLinesIndentGuides(reqStart.lineNumber, modelLineIndex));
          reqStart = null;
        }
      }
    }
    if (reqStart !== null) {
      result = result.concat(this.d.guides.getLinesIndentGuides(reqStart.lineNumber, modelEnd.lineNumber));
      reqStart = null;
    }
    const viewLineCount = viewEndLineNumber - viewStartLineNumber + 1;
    const viewIndents = new Array(viewLineCount);
    let currIndex = 0;
    for (let i2 = 0, len = result.length; i2 < len; i2++) {
      let value = result[i2];
      const count = Math.min(viewLineCount - currIndex, resultRepeatCount[i2]);
      const option = resultRepeatOption[i2];
      let blockAtIndex;
      if (option === 2) {
        blockAtIndex = 0;
      } else if (option === 1) {
        blockAtIndex = 1;
      } else {
        blockAtIndex = count;
      }
      for (let j = 0; j < count; j++) {
        if (j === blockAtIndex) {
          value = 0;
        }
        viewIndents[currIndex++] = value;
      }
    }
    return viewIndents;
  }
  getViewLineContent(viewLineNumber) {
    const info = this.y(viewLineNumber);
    return this.s[info.modelLineNumber - 1].getViewLineContent(this.d, info.modelLineNumber, info.modelLineWrappedLineIdx);
  }
  getViewLineLength(viewLineNumber) {
    const info = this.y(viewLineNumber);
    return this.s[info.modelLineNumber - 1].getViewLineLength(this.d, info.modelLineNumber, info.modelLineWrappedLineIdx);
  }
  getViewLineMinColumn(viewLineNumber) {
    const info = this.y(viewLineNumber);
    return this.s[info.modelLineNumber - 1].getViewLineMinColumn(this.d, info.modelLineNumber, info.modelLineWrappedLineIdx);
  }
  getViewLineMaxColumn(viewLineNumber) {
    const info = this.y(viewLineNumber);
    return this.s[info.modelLineNumber - 1].getViewLineMaxColumn(this.d, info.modelLineNumber, info.modelLineWrappedLineIdx);
  }
  getViewLineData(viewLineNumber) {
    const info = this.y(viewLineNumber);
    return this.s[info.modelLineNumber - 1].getViewLineData(this.d, info.modelLineNumber, info.modelLineWrappedLineIdx);
  }
  getViewLinesData(viewStartLineNumber, viewEndLineNumber, needed) {
    viewStartLineNumber = this.x(viewStartLineNumber);
    viewEndLineNumber = this.x(viewEndLineNumber);
    const start = this.u.getIndexOf(viewStartLineNumber - 1);
    let viewLineNumber = viewStartLineNumber;
    const startModelLineIndex = start.index;
    const startRemainder = start.remainder;
    const result = [];
    for (let modelLineIndex = startModelLineIndex, len = this.d.getLineCount(); modelLineIndex < len; modelLineIndex++) {
      const line = this.s[modelLineIndex];
      if (!line.isVisible()) {
        continue;
      }
      const fromViewLineIndex = modelLineIndex === startModelLineIndex ? startRemainder : 0;
      let remainingViewLineCount = line.getViewLineCount() - fromViewLineIndex;
      let lastLine = false;
      if (viewLineNumber + remainingViewLineCount > viewEndLineNumber) {
        lastLine = true;
        remainingViewLineCount = viewEndLineNumber - viewLineNumber + 1;
      }
      line.getViewLinesData(this.d, modelLineIndex + 1, fromViewLineIndex, remainingViewLineCount, viewLineNumber - viewStartLineNumber, needed, result);
      viewLineNumber += remainingViewLineCount;
      if (lastLine) {
        break;
      }
    }
    return result;
  }
  validateViewPosition(viewLineNumber, viewColumn, expectedModelPosition) {
    viewLineNumber = this.x(viewLineNumber);
    const r2 = this.u.getIndexOf(viewLineNumber - 1);
    const lineIndex = r2.index;
    const remainder = r2.remainder;
    const line = this.s[lineIndex];
    const minColumn = line.getViewLineMinColumn(this.d, lineIndex + 1, remainder);
    const maxColumn = line.getViewLineMaxColumn(this.d, lineIndex + 1, remainder);
    if (viewColumn < minColumn) {
      viewColumn = minColumn;
    }
    if (viewColumn > maxColumn) {
      viewColumn = maxColumn;
    }
    const computedModelColumn = line.getModelColumnOfViewPosition(remainder, viewColumn);
    const computedModelPosition = this.d.validatePosition(new $8C(lineIndex + 1, computedModelColumn));
    if (computedModelPosition.equals(expectedModelPosition)) {
      return new $8C(viewLineNumber, viewColumn);
    }
    return this.convertModelPositionToViewPosition(expectedModelPosition.lineNumber, expectedModelPosition.column);
  }
  validateViewRange(viewRange, expectedModelRange) {
    const validViewStart = this.validateViewPosition(viewRange.startLineNumber, viewRange.startColumn, expectedModelRange.getStartPosition());
    const validViewEnd = this.validateViewPosition(viewRange.endLineNumber, viewRange.endColumn, expectedModelRange.getEndPosition());
    return new $9C(validViewStart.lineNumber, validViewStart.column, validViewEnd.lineNumber, validViewEnd.column);
  }
  convertViewPositionToModelPosition(viewLineNumber, viewColumn) {
    const info = this.y(viewLineNumber);
    const inputColumn = this.s[info.modelLineNumber - 1].getModelColumnOfViewPosition(info.modelLineWrappedLineIdx, viewColumn);
    return this.d.validatePosition(new $8C(info.modelLineNumber, inputColumn));
  }
  convertViewRangeToModelRange(viewRange) {
    const start = this.convertViewPositionToModelPosition(viewRange.startLineNumber, viewRange.startColumn);
    const end = this.convertViewPositionToModelPosition(viewRange.endLineNumber, viewRange.endColumn);
    return new $9C(start.lineNumber, start.column, end.lineNumber, end.column);
  }
  convertModelPositionToViewPosition(_modelLineNumber, _modelColumn, affinity = 2, allowZeroLineNumber = false, belowHiddenRanges = false) {
    const validPosition = this.d.validatePosition(new $8C(_modelLineNumber, _modelColumn));
    const inputLineNumber = validPosition.lineNumber;
    const inputColumn = validPosition.column;
    let lineIndex = inputLineNumber - 1, lineIndexChanged = false;
    if (belowHiddenRanges) {
      while (lineIndex < this.s.length && !this.s[lineIndex].isVisible()) {
        lineIndex++;
        lineIndexChanged = true;
      }
    } else {
      while (lineIndex > 0 && !this.s[lineIndex].isVisible()) {
        lineIndex--;
        lineIndexChanged = true;
      }
    }
    if (lineIndex === 0 && !this.s[lineIndex].isVisible()) {
      return new $8C(allowZeroLineNumber ? 0 : 1, 1);
    }
    const deltaLineNumber = 1 + this.u.getPrefixSum(lineIndex);
    let r2;
    if (lineIndexChanged) {
      if (belowHiddenRanges) {
        r2 = this.s[lineIndex].getViewPositionOfModelPosition(deltaLineNumber, 1, affinity);
      } else {
        r2 = this.s[lineIndex].getViewPositionOfModelPosition(deltaLineNumber, this.d.getLineMaxColumn(lineIndex + 1), affinity);
      }
    } else {
      r2 = this.s[inputLineNumber - 1].getViewPositionOfModelPosition(deltaLineNumber, inputColumn, affinity);
    }
    return r2;
  }
  /**
   * @param affinity The affinity in case of an empty range. Has no effect for non-empty ranges.
  */
  convertModelRangeToViewRange(modelRange, affinity = 0) {
    if (modelRange.isEmpty()) {
      const start = this.convertModelPositionToViewPosition(modelRange.startLineNumber, modelRange.startColumn, affinity);
      return $9C.fromPositions(start);
    } else {
      const start = this.convertModelPositionToViewPosition(
        modelRange.startLineNumber,
        modelRange.startColumn,
        1
        /* PositionAffinity.Right */
      );
      const end = this.convertModelPositionToViewPosition(
        modelRange.endLineNumber,
        modelRange.endColumn,
        0
        /* PositionAffinity.Left */
      );
      return new $9C(start.lineNumber, start.column, end.lineNumber, end.column);
    }
  }
  getViewLineNumberOfModelPosition(modelLineNumber, modelColumn) {
    let lineIndex = modelLineNumber - 1;
    if (this.s[lineIndex].isVisible()) {
      const deltaLineNumber2 = 1 + this.u.getPrefixSum(lineIndex);
      return this.s[lineIndex].getViewLineNumberOfModelPosition(deltaLineNumber2, modelColumn);
    }
    while (lineIndex > 0 && !this.s[lineIndex].isVisible()) {
      lineIndex--;
    }
    if (lineIndex === 0 && !this.s[lineIndex].isVisible()) {
      return 1;
    }
    const deltaLineNumber = 1 + this.u.getPrefixSum(lineIndex);
    return this.s[lineIndex].getViewLineNumberOfModelPosition(deltaLineNumber, this.d.getLineMaxColumn(lineIndex + 1));
  }
  getDecorationsInRange(range, ownerId2, filterOutValidation, onlyMinimapDecorations, onlyMarginDecorations) {
    const modelStart = this.convertViewPositionToModelPosition(range.startLineNumber, range.startColumn);
    const modelEnd = this.convertViewPositionToModelPosition(range.endLineNumber, range.endColumn);
    if (modelEnd.lineNumber - modelStart.lineNumber <= range.endLineNumber - range.startLineNumber) {
      return this.d.getDecorationsInRange(new $9C(modelStart.lineNumber, 1, modelEnd.lineNumber, modelEnd.column), ownerId2, filterOutValidation, onlyMinimapDecorations, onlyMarginDecorations);
    }
    let result = [];
    const modelStartLineIndex = modelStart.lineNumber - 1;
    const modelEndLineIndex = modelEnd.lineNumber - 1;
    let reqStart = null;
    for (let modelLineIndex = modelStartLineIndex; modelLineIndex <= modelEndLineIndex; modelLineIndex++) {
      const line = this.s[modelLineIndex];
      if (line.isVisible()) {
        if (reqStart === null) {
          reqStart = new $8C(modelLineIndex + 1, modelLineIndex === modelStartLineIndex ? modelStart.column : 1);
        }
      } else {
        if (reqStart !== null) {
          const maxLineColumn = this.d.getLineMaxColumn(modelLineIndex);
          result = result.concat(this.d.getDecorationsInRange(new $9C(reqStart.lineNumber, reqStart.column, modelLineIndex, maxLineColumn), ownerId2, filterOutValidation, onlyMinimapDecorations));
          reqStart = null;
        }
      }
    }
    if (reqStart !== null) {
      result = result.concat(this.d.getDecorationsInRange(new $9C(reqStart.lineNumber, reqStart.column, modelEnd.lineNumber, modelEnd.column), ownerId2, filterOutValidation, onlyMinimapDecorations));
      reqStart = null;
    }
    result.sort((a, b) => {
      const res = $9C.compareRangesUsingStarts(a.range, b.range);
      if (res === 0) {
        if (a.id < b.id) {
          return -1;
        }
        if (a.id > b.id) {
          return 1;
        }
        return 0;
      }
      return res;
    });
    const finalResult = [];
    let finalResultLen = 0;
    let prevDecId = null;
    for (const dec of result) {
      const decId = dec.id;
      if (prevDecId === decId) {
        continue;
      }
      prevDecId = decId;
      finalResult[finalResultLen++] = dec;
    }
    return finalResult;
  }
  getInjectedTextAt(position) {
    const info = this.y(position.lineNumber);
    return this.s[info.modelLineNumber - 1].getInjectedTextAt(info.modelLineWrappedLineIdx, position.column);
  }
  normalizePosition(position, affinity) {
    const info = this.y(position.lineNumber);
    return this.s[info.modelLineNumber - 1].normalizePosition(info.modelLineWrappedLineIdx, position, affinity);
  }
  getLineIndentColumn(lineNumber) {
    const info = this.y(lineNumber);
    if (info.modelLineWrappedLineIdx === 0) {
      return this.d.getLineIndentColumn(info.modelLineNumber);
    }
    return 0;
  }
};
function normalizeLineRanges(ranges) {
  if (ranges.length === 0) {
    return [];
  }
  const sortedRanges = ranges.slice();
  sortedRanges.sort($9C.compareRangesUsingStarts);
  const result = [];
  let currentRangeStart = sortedRanges[0].startLineNumber;
  let currentRangeEnd = sortedRanges[0].endLineNumber;
  for (let i2 = 1, len = sortedRanges.length; i2 < len; i2++) {
    const range = sortedRanges[i2];
    if (range.startLineNumber > currentRangeEnd + 1) {
      result.push(new $9C(currentRangeStart, 1, currentRangeEnd, 1));
      currentRangeStart = range.startLineNumber;
      currentRangeEnd = range.endLineNumber;
    } else if (range.endLineNumber > currentRangeEnd) {
      currentRangeEnd = range.endLineNumber;
    }
  }
  result.push(new $9C(currentRangeStart, 1, currentRangeEnd, 1));
  return result;
}
var ViewLineInfo = class {
  get isWrappedLineContinuation() {
    return this.modelLineWrappedLineIdx > 0;
  }
  constructor(modelLineNumber, modelLineWrappedLineIdx) {
    this.modelLineNumber = modelLineNumber;
    this.modelLineWrappedLineIdx = modelLineWrappedLineIdx;
  }
};
var ViewLineInfoGroupedByModelRange = class {
  constructor(modelRange, viewLines) {
    this.modelRange = modelRange;
    this.viewLines = viewLines;
  }
};
var CoordinatesConverter = class {
  constructor(lines) {
    this.c = lines;
  }
  // View -> Model conversion and related methods
  convertViewPositionToModelPosition(viewPosition) {
    return this.c.convertViewPositionToModelPosition(viewPosition.lineNumber, viewPosition.column);
  }
  convertViewRangeToModelRange(viewRange) {
    return this.c.convertViewRangeToModelRange(viewRange);
  }
  validateViewPosition(viewPosition, expectedModelPosition) {
    return this.c.validateViewPosition(viewPosition.lineNumber, viewPosition.column, expectedModelPosition);
  }
  validateViewRange(viewRange, expectedModelRange) {
    return this.c.validateViewRange(viewRange, expectedModelRange);
  }
  // Model -> View conversion and related methods
  convertModelPositionToViewPosition(modelPosition, affinity, allowZero, belowHiddenRanges) {
    return this.c.convertModelPositionToViewPosition(modelPosition.lineNumber, modelPosition.column, affinity, allowZero, belowHiddenRanges);
  }
  convertModelRangeToViewRange(modelRange, affinity) {
    return this.c.convertModelRangeToViewRange(modelRange, affinity);
  }
  modelPositionIsVisible(modelPosition) {
    return this.c.modelPositionIsVisible(modelPosition.lineNumber, modelPosition.column);
  }
  getModelLineViewLineCount(modelLineNumber) {
    return this.c.getModelLineViewLineCount(modelLineNumber);
  }
  getViewLineNumberOfModelPosition(modelLineNumber, modelColumn) {
    return this.c.getViewLineNumberOfModelPosition(modelLineNumber, modelColumn);
  }
};
var IndentGuideRepeatOption;
(function(IndentGuideRepeatOption2) {
  IndentGuideRepeatOption2[IndentGuideRepeatOption2["BlockNone"] = 0] = "BlockNone";
  IndentGuideRepeatOption2[IndentGuideRepeatOption2["BlockSubsequent"] = 1] = "BlockSubsequent";
  IndentGuideRepeatOption2[IndentGuideRepeatOption2["BlockAll"] = 2] = "BlockAll";
})(IndentGuideRepeatOption || (IndentGuideRepeatOption = {}));
var $w9 = class {
  constructor(model) {
    this.model = model;
  }
  dispose() {
  }
  createCoordinatesConverter() {
    return new IdentityCoordinatesConverter(this);
  }
  getHiddenAreas() {
    return [];
  }
  setHiddenAreas(_ranges) {
    return false;
  }
  setTabSize(_newTabSize) {
    return false;
  }
  setWrappingSettings(_fontInfo, _wrappingStrategy, _wrappingColumn, _wrappingIndent) {
    return false;
  }
  createLineBreaksComputer() {
    const result = [];
    return {
      addRequest: (lineText, injectedText, previousLineBreakData) => {
        result.push(null);
      },
      finalize: () => {
        return result;
      }
    };
  }
  onModelFlushed() {
  }
  onModelLinesDeleted(_versionId, fromLineNumber, toLineNumber) {
    return new $v5(fromLineNumber, toLineNumber);
  }
  onModelLinesInserted(_versionId, fromLineNumber, toLineNumber, lineBreaks) {
    return new $w5(fromLineNumber, toLineNumber);
  }
  onModelLineChanged(_versionId, lineNumber, lineBreakData) {
    return [false, new $u5(lineNumber, 1), null, null];
  }
  acceptVersionId(_versionId) {
  }
  getViewLineCount() {
    return this.model.getLineCount();
  }
  getActiveIndentGuide(viewLineNumber, _minLineNumber, _maxLineNumber) {
    return {
      startLineNumber: viewLineNumber,
      endLineNumber: viewLineNumber,
      indent: 0
    };
  }
  getViewLinesBracketGuides(startLineNumber, endLineNumber, activePosition) {
    return new Array(endLineNumber - startLineNumber + 1).fill([]);
  }
  getViewLinesIndentGuides(viewStartLineNumber, viewEndLineNumber) {
    const viewLineCount = viewEndLineNumber - viewStartLineNumber + 1;
    const result = new Array(viewLineCount);
    for (let i2 = 0; i2 < viewLineCount; i2++) {
      result[i2] = 0;
    }
    return result;
  }
  getViewLineContent(viewLineNumber) {
    return this.model.getLineContent(viewLineNumber);
  }
  getViewLineLength(viewLineNumber) {
    return this.model.getLineLength(viewLineNumber);
  }
  getViewLineMinColumn(viewLineNumber) {
    return this.model.getLineMinColumn(viewLineNumber);
  }
  getViewLineMaxColumn(viewLineNumber) {
    return this.model.getLineMaxColumn(viewLineNumber);
  }
  getViewLineData(viewLineNumber) {
    const lineTokens = this.model.tokenization.getLineTokens(viewLineNumber);
    const lineContent = lineTokens.getLineContent();
    return new $G5(lineContent, false, 1, lineContent.length + 1, 0, lineTokens.inflate(), null);
  }
  getViewLinesData(viewStartLineNumber, viewEndLineNumber, needed) {
    const lineCount = this.model.getLineCount();
    viewStartLineNumber = Math.min(Math.max(1, viewStartLineNumber), lineCount);
    viewEndLineNumber = Math.min(Math.max(1, viewEndLineNumber), lineCount);
    const result = [];
    for (let lineNumber = viewStartLineNumber; lineNumber <= viewEndLineNumber; lineNumber++) {
      const idx = lineNumber - viewStartLineNumber;
      result[idx] = needed[idx] ? this.getViewLineData(lineNumber) : null;
    }
    return result;
  }
  getDecorationsInRange(range, ownerId2, filterOutValidation, onlyMinimapDecorations, onlyMarginDecorations) {
    return this.model.getDecorationsInRange(range, ownerId2, filterOutValidation, onlyMinimapDecorations, onlyMarginDecorations);
  }
  normalizePosition(position, affinity) {
    return this.model.normalizePosition(position, affinity);
  }
  getLineIndentColumn(lineNumber) {
    return this.model.getLineIndentColumn(lineNumber);
  }
  getInjectedTextAt(position) {
    return null;
  }
};
var IdentityCoordinatesConverter = class {
  constructor(lines) {
    this.c = lines;
  }
  d(pos) {
    return this.c.model.validatePosition(pos);
  }
  e(range) {
    return this.c.model.validateRange(range);
  }
  // View -> Model conversion and related methods
  convertViewPositionToModelPosition(viewPosition) {
    return this.d(viewPosition);
  }
  convertViewRangeToModelRange(viewRange) {
    return this.e(viewRange);
  }
  validateViewPosition(_viewPosition, expectedModelPosition) {
    return this.d(expectedModelPosition);
  }
  validateViewRange(_viewRange, expectedModelRange) {
    return this.e(expectedModelRange);
  }
  // Model -> View conversion and related methods
  convertModelPositionToViewPosition(modelPosition) {
    return this.d(modelPosition);
  }
  convertModelRangeToViewRange(modelRange) {
    return this.e(modelRange);
  }
  modelPositionIsVisible(modelPosition) {
    const lineCount = this.c.model.getLineCount();
    if (modelPosition.lineNumber < 1 || modelPosition.lineNumber > lineCount) {
      return false;
    }
    return true;
  }
  modelRangeIsVisible(modelRange) {
    const lineCount = this.c.model.getLineCount();
    if (modelRange.startLineNumber < 1 || modelRange.startLineNumber > lineCount) {
      return false;
    }
    if (modelRange.endLineNumber < 1 || modelRange.endLineNumber > lineCount) {
      return false;
    }
    return true;
  }
  getModelLineViewLineCount(modelLineNumber) {
    return 1;
  }
  getViewLineNumberOfModelPosition(modelLineNumber, modelColumn) {
    return modelLineNumber;
  }
};

// out-build/vs/editor/common/viewModel/glyphLanesModel.js
var MAX_LANE = GlyphMarginLane.Right;
var $B9 = class {
  constructor(maxLine) {
    this.b = 0;
    this.c = 1;
    this.a = new Uint8Array(Math.ceil((maxLine + 1) * MAX_LANE / 8));
  }
  reset(maxLine) {
    const bytes = Math.ceil((maxLine + 1) * MAX_LANE / 8);
    if (this.a.length < bytes) {
      this.a = new Uint8Array(bytes);
    } else {
      this.a.fill(0);
    }
    this.c = 1;
  }
  get requiredLanes() {
    return this.c;
  }
  push(lane, range, persist) {
    if (persist) {
      this.b |= 1 << lane - 1;
    }
    for (let i2 = range.startLineNumber; i2 <= range.endLineNumber; i2++) {
      const bit = MAX_LANE * i2 + (lane - 1);
      this.a[bit >>> 3] |= 1 << bit % 8;
      this.c = Math.max(this.c, this.d(i2));
    }
  }
  getLanesAtLine(lineNumber) {
    const lanes = [];
    let bit = MAX_LANE * lineNumber;
    for (let i2 = 0; i2 < MAX_LANE; i2++) {
      if (this.b & 1 << i2 || this.a[bit >>> 3] & 1 << bit % 8) {
        lanes.push(i2 + 1);
      }
      bit++;
    }
    return lanes.length ? lanes : [GlyphMarginLane.Center];
  }
  d(lineNumber) {
    let bit = MAX_LANE * lineNumber;
    let count = 0;
    for (let i2 = 0; i2 < MAX_LANE; i2++) {
      if (this.b & 1 << i2 || this.a[bit >>> 3] & 1 << bit % 8) {
        count++;
      }
      bit++;
    }
    return count;
  }
};

// out-build/vs/editor/common/viewModel/viewModelImpl.js
var USE_IDENTITY_LINES_COLLECTION = true;
var $C9 = class extends $3c {
  constructor(editorId, configuration2, model, domLineBreaksComputerFactory, monospaceLineBreaksComputerFactory, scheduleAtNextAnimationFrame, t, u, w, y) {
    super();
    this.t = t;
    this.u = u;
    this.w = w;
    this.y = y;
    this.I = new HiddenAreasModel();
    this.J = [];
    this.a = editorId;
    this.b = configuration2;
    this.model = model;
    this.c = new $98();
    this.onEvent = this.c.onEvent;
    this.cursorConfig = new $d5(this.model.getLanguageId(), this.model.getOptions(), this.b, this.t);
    this.f = this.B(new $8h(() => this.z(), 0));
    this.g = false;
    this.h = ViewportStart.create(this.model);
    this.glyphLanes = new $B9(0);
    if (USE_IDENTITY_LINES_COLLECTION && this.model.isTooLargeForTokenization()) {
      this.m = new $w9(this.model);
    } else {
      const options3 = this.b.options;
      const fontInfo = options3.get(
        52
        /* EditorOption.fontInfo */
      );
      const wrappingStrategy = options3.get(
        144
        /* EditorOption.wrappingStrategy */
      );
      const wrappingInfo = options3.get(
        152
        /* EditorOption.wrappingInfo */
      );
      const wrappingIndent = options3.get(
        143
        /* EditorOption.wrappingIndent */
      );
      const wordBreak = options3.get(
        134
        /* EditorOption.wordBreak */
      );
      this.m = new $v9(this.a, this.model, domLineBreaksComputerFactory, monospaceLineBreaksComputerFactory, fontInfo, this.model.getOptions().tabSize, wrappingStrategy, wrappingInfo.wrappingColumn, wrappingIndent, wordBreak);
    }
    this.coordinatesConverter = this.m.createCoordinatesConverter();
    this.n = this.B(new $l9(model, this, this.coordinatesConverter, this.cursorConfig));
    this.viewLayout = this.B(new $t9(this.b, this.getLineCount(), scheduleAtNextAnimationFrame));
    this.B(this.viewLayout.onDidScroll((e) => {
      if (e.scrollTopChanged) {
        this.D();
      }
      if (e.scrollTopChanged) {
        this.h.invalidate();
      }
      this.c.emitSingleViewEvent(new $y5(e));
      this.c.emitOutgoingEvent(new $a9(e.oldScrollWidth, e.oldScrollLeft, e.oldScrollHeight, e.oldScrollTop, e.scrollWidth, e.scrollLeft, e.scrollHeight, e.scrollTop));
    }));
    this.B(this.viewLayout.onDidContentSizeChange((e) => {
      this.c.emitOutgoingEvent(e);
    }));
    this.s = new $x9(this.a, this.model, this.b, this.m, this.coordinatesConverter);
    this.H();
    this.B(this.b.onDidChangeFast((e) => {
      try {
        const eventsCollector = this.c.beginEmitViewEvents();
        this.G(eventsCollector, e);
      } finally {
        this.c.endEmitViewEvents();
      }
    }));
    this.B($E8.getInstance().onDidChange(() => {
      this.c.emitSingleViewEvent(new $B5());
    }));
    this.B(this.u.onDidColorThemeChange((theme) => {
      this.P();
      this.c.emitSingleViewEvent(new $z5(theme));
    }));
    this.z();
  }
  dispose() {
    super.dispose();
    this.s.dispose();
    this.m.dispose();
    this.h.dispose();
    this.c.dispose();
  }
  createLineBreaksComputer() {
    return this.m.createLineBreaksComputer();
  }
  addViewEventHandler(eventHandler) {
    this.c.addViewEventHandler(eventHandler);
  }
  removeViewEventHandler(eventHandler) {
    this.c.removeViewEventHandler(eventHandler);
  }
  z() {
    this.b.setViewLineCount(this.m.getViewLineCount());
  }
  C() {
    const linesViewportData = this.viewLayout.getLinesViewportData();
    const viewVisibleRange = new $9C(linesViewportData.startLineNumber, this.getLineMinColumn(linesViewportData.startLineNumber), linesViewportData.endLineNumber, this.getLineMaxColumn(linesViewportData.endLineNumber));
    const modelVisibleRanges = this.L(viewVisibleRange);
    return modelVisibleRanges;
  }
  visibleLinesStabilized() {
    const modelVisibleRanges = this.C();
    this.w.setVisibleLines(modelVisibleRanges, true);
  }
  D() {
    const modelVisibleRanges = this.C();
    this.w.setVisibleLines(modelVisibleRanges, false);
  }
  setHasFocus(hasFocus) {
    this.g = hasFocus;
    this.n.setHasFocus(hasFocus);
    this.c.emitSingleViewEvent(new $r5(hasFocus));
    this.c.emitOutgoingEvent(new $_8(!hasFocus, hasFocus));
  }
  onCompositionStart() {
    this.c.emitSingleViewEvent(new $l5());
  }
  onCompositionEnd() {
    this.c.emitSingleViewEvent(new $m5());
  }
  F() {
    if (this.h.isValid && this.viewLayout.getCurrentScrollTop() > 0) {
      const previousViewportStartViewPosition = new $8C(this.h.viewLineNumber, this.getLineMinColumn(this.h.viewLineNumber));
      const previousViewportStartModelPosition = this.coordinatesConverter.convertViewPositionToModelPosition(previousViewportStartViewPosition);
      return new StableViewport(previousViewportStartModelPosition, this.h.startLineDelta);
    }
    return new StableViewport(null, 0);
  }
  G(eventsCollector, e) {
    const stableViewport = this.F();
    const options3 = this.b.options;
    const fontInfo = options3.get(
      52
      /* EditorOption.fontInfo */
    );
    const wrappingStrategy = options3.get(
      144
      /* EditorOption.wrappingStrategy */
    );
    const wrappingInfo = options3.get(
      152
      /* EditorOption.wrappingInfo */
    );
    const wrappingIndent = options3.get(
      143
      /* EditorOption.wrappingIndent */
    );
    const wordBreak = options3.get(
      134
      /* EditorOption.wordBreak */
    );
    if (this.m.setWrappingSettings(fontInfo, wrappingStrategy, wrappingInfo.wrappingColumn, wrappingIndent, wordBreak)) {
      eventsCollector.emitViewEvent(new $q5());
      eventsCollector.emitViewEvent(new $t5());
      eventsCollector.emitViewEvent(new $p5(null));
      this.n.onLineMappingChanged(eventsCollector);
      this.s.onLineMappingChanged();
      this.viewLayout.onFlushed(this.getLineCount());
      this.f.schedule();
    }
    if (e.hasChanged(
      96
      /* EditorOption.readOnly */
    )) {
      this.s.reset();
      eventsCollector.emitViewEvent(new $p5(null));
    }
    if (e.hasChanged(
      103
      /* EditorOption.renderValidationDecorations */
    )) {
      this.s.reset();
      eventsCollector.emitViewEvent(new $p5(null));
    }
    eventsCollector.emitViewEvent(new $n5(e));
    this.viewLayout.onConfigurationChanged(e);
    stableViewport.recoverViewportStart(this.coordinatesConverter, this.viewLayout);
    if ($d5.shouldRecreate(e)) {
      this.cursorConfig = new $d5(this.model.getLanguageId(), this.model.getOptions(), this.b, this.t);
      this.n.updateConfiguration(this.cursorConfig);
    }
  }
  H() {
    this.B(this.model.onDidChangeContentOrInjectedText((e) => {
      try {
        const eventsCollector = this.c.beginEmitViewEvents();
        let hadOtherModelChange = false;
        let hadModelLineChangeThatChangedLineMapping = false;
        const changes = e instanceof $ME ? e.rawContentChangedEvent.changes : e.changes;
        const versionId = e instanceof $ME ? e.rawContentChangedEvent.versionId : null;
        const lineBreaksComputer = this.m.createLineBreaksComputer();
        for (const change of changes) {
          switch (change.changeType) {
            case 4: {
              for (let lineIdx = 0; lineIdx < change.detail.length; lineIdx++) {
                const line = change.detail[lineIdx];
                let injectedText = change.injectedTexts[lineIdx];
                if (injectedText) {
                  injectedText = injectedText.filter((element) => !element.ownerId || element.ownerId === this.a);
                }
                lineBreaksComputer.addRequest(line, injectedText, null);
              }
              break;
            }
            case 2: {
              let injectedText = null;
              if (change.injectedText) {
                injectedText = change.injectedText.filter((element) => !element.ownerId || element.ownerId === this.a);
              }
              lineBreaksComputer.addRequest(change.detail, injectedText, null);
              break;
            }
          }
        }
        const lineBreaks = lineBreaksComputer.finalize();
        const lineBreakQueue = new $bc(lineBreaks);
        for (const change of changes) {
          switch (change.changeType) {
            case 1: {
              this.m.onModelFlushed();
              eventsCollector.emitViewEvent(new $q5());
              this.s.reset();
              this.viewLayout.onFlushed(this.getLineCount());
              hadOtherModelChange = true;
              break;
            }
            case 3: {
              const linesDeletedEvent = this.m.onModelLinesDeleted(versionId, change.fromLineNumber, change.toLineNumber);
              if (linesDeletedEvent !== null) {
                eventsCollector.emitViewEvent(linesDeletedEvent);
                this.viewLayout.onLinesDeleted(linesDeletedEvent.fromLineNumber, linesDeletedEvent.toLineNumber);
              }
              hadOtherModelChange = true;
              break;
            }
            case 4: {
              const insertedLineBreaks = lineBreakQueue.takeCount(change.detail.length);
              const linesInsertedEvent = this.m.onModelLinesInserted(versionId, change.fromLineNumber, change.toLineNumber, insertedLineBreaks);
              if (linesInsertedEvent !== null) {
                eventsCollector.emitViewEvent(linesInsertedEvent);
                this.viewLayout.onLinesInserted(linesInsertedEvent.fromLineNumber, linesInsertedEvent.toLineNumber);
              }
              hadOtherModelChange = true;
              break;
            }
            case 2: {
              const changedLineBreakData = lineBreakQueue.dequeue();
              const [lineMappingChanged, linesChangedEvent, linesInsertedEvent, linesDeletedEvent] = this.m.onModelLineChanged(versionId, change.lineNumber, changedLineBreakData);
              hadModelLineChangeThatChangedLineMapping = lineMappingChanged;
              if (linesChangedEvent) {
                eventsCollector.emitViewEvent(linesChangedEvent);
              }
              if (linesInsertedEvent) {
                eventsCollector.emitViewEvent(linesInsertedEvent);
                this.viewLayout.onLinesInserted(linesInsertedEvent.fromLineNumber, linesInsertedEvent.toLineNumber);
              }
              if (linesDeletedEvent) {
                eventsCollector.emitViewEvent(linesDeletedEvent);
                this.viewLayout.onLinesDeleted(linesDeletedEvent.fromLineNumber, linesDeletedEvent.toLineNumber);
              }
              break;
            }
            case 5: {
              break;
            }
          }
        }
        if (versionId !== null) {
          this.m.acceptVersionId(versionId);
        }
        this.viewLayout.onHeightMaybeChanged();
        if (!hadOtherModelChange && hadModelLineChangeThatChangedLineMapping) {
          eventsCollector.emitViewEvent(new $t5());
          eventsCollector.emitViewEvent(new $p5(null));
          this.n.onLineMappingChanged(eventsCollector);
          this.s.onLineMappingChanged();
        }
      } finally {
        this.c.endEmitViewEvents();
      }
      const viewportStartWasValid = this.h.isValid;
      this.h.invalidate();
      this.b.setModelLineCount(this.model.getLineCount());
      this.z();
      if (!this.g && this.model.getAttachedEditorCount() >= 2 && viewportStartWasValid) {
        const modelRange = this.model._getTrackedRange(this.h.modelTrackedRange);
        if (modelRange) {
          const viewPosition = this.coordinatesConverter.convertModelPositionToViewPosition(modelRange.getStartPosition());
          const viewPositionTop = this.viewLayout.getVerticalOffsetForLineNumber(viewPosition.lineNumber);
          this.viewLayout.setScrollPosition(
            { scrollTop: viewPositionTop + this.h.startLineDelta },
            1
            /* ScrollType.Immediate */
          );
        }
      }
      try {
        const eventsCollector = this.c.beginEmitViewEvents();
        if (e instanceof $ME) {
          eventsCollector.emitOutgoingEvent(new $i9(e.contentChangedEvent));
        }
        this.n.onModelContentChanged(eventsCollector, e);
      } finally {
        this.c.endEmitViewEvents();
      }
      this.D();
    }));
    this.B(this.model.onDidChangeTokens((e) => {
      const viewRanges = [];
      for (let j = 0, lenJ = e.ranges.length; j < lenJ; j++) {
        const modelRange = e.ranges[j];
        const viewStartLineNumber = this.coordinatesConverter.convertModelPositionToViewPosition(new $8C(modelRange.fromLineNumber, 1)).lineNumber;
        const viewEndLineNumber = this.coordinatesConverter.convertModelPositionToViewPosition(new $8C(modelRange.toLineNumber, this.model.getLineMaxColumn(modelRange.toLineNumber))).lineNumber;
        viewRanges[j] = {
          fromLineNumber: viewStartLineNumber,
          toLineNumber: viewEndLineNumber
        };
      }
      this.c.emitSingleViewEvent(new $A5(viewRanges));
      this.c.emitOutgoingEvent(new $k9(e));
    }));
    this.B(this.model.onDidChangeLanguageConfiguration((e) => {
      this.c.emitSingleViewEvent(new $s5());
      this.cursorConfig = new $d5(this.model.getLanguageId(), this.model.getOptions(), this.b, this.t);
      this.n.updateConfiguration(this.cursorConfig);
      this.c.emitOutgoingEvent(new $h9(e));
    }));
    this.B(this.model.onDidChangeLanguage((e) => {
      this.cursorConfig = new $d5(this.model.getLanguageId(), this.model.getOptions(), this.b, this.t);
      this.n.updateConfiguration(this.cursorConfig);
      this.c.emitOutgoingEvent(new $g9(e));
    }));
    this.B(this.model.onDidChangeOptions((e) => {
      if (this.m.setTabSize(this.model.getOptions().tabSize)) {
        try {
          const eventsCollector = this.c.beginEmitViewEvents();
          eventsCollector.emitViewEvent(new $q5());
          eventsCollector.emitViewEvent(new $t5());
          eventsCollector.emitViewEvent(new $p5(null));
          this.n.onLineMappingChanged(eventsCollector);
          this.s.onLineMappingChanged();
          this.viewLayout.onFlushed(this.getLineCount());
        } finally {
          this.c.endEmitViewEvents();
        }
        this.f.schedule();
      }
      this.cursorConfig = new $d5(this.model.getLanguageId(), this.model.getOptions(), this.b, this.t);
      this.n.updateConfiguration(this.cursorConfig);
      this.c.emitOutgoingEvent(new $j9(e));
    }));
    this.B(this.model.onDidChangeDecorations((e) => {
      this.s.onModelDecorationsChanged();
      this.c.emitSingleViewEvent(new $p5(e));
      this.c.emitOutgoingEvent(new $f9(e));
    }));
  }
  /**
   * @param forceUpdate If true, the hidden areas will be updated even if the new ranges are the same as the previous ranges.
   * This is because the model might have changed, which resets the hidden areas, but not the last cached value.
   * This needs a better fix in the future.
  */
  setHiddenAreas(ranges, source, forceUpdate) {
    this.I.setHiddenAreas(source, ranges);
    const mergedRanges = this.I.getMergedRanges();
    if (mergedRanges === this.J && !forceUpdate) {
      return;
    }
    this.J = mergedRanges;
    const stableViewport = this.F();
    let lineMappingChanged = false;
    try {
      const eventsCollector = this.c.beginEmitViewEvents();
      lineMappingChanged = this.m.setHiddenAreas(mergedRanges);
      if (lineMappingChanged) {
        eventsCollector.emitViewEvent(new $q5());
        eventsCollector.emitViewEvent(new $t5());
        eventsCollector.emitViewEvent(new $p5(null));
        this.n.onLineMappingChanged(eventsCollector);
        this.s.onLineMappingChanged();
        this.viewLayout.onFlushed(this.getLineCount());
        this.viewLayout.onHeightMaybeChanged();
      }
      const firstModelLineInViewPort = stableViewport.viewportStartModelPosition?.lineNumber;
      const firstModelLineIsHidden = firstModelLineInViewPort && mergedRanges.some((range) => range.startLineNumber <= firstModelLineInViewPort && firstModelLineInViewPort <= range.endLineNumber);
      if (!firstModelLineIsHidden) {
        stableViewport.recoverViewportStart(this.coordinatesConverter, this.viewLayout);
      }
    } finally {
      this.c.endEmitViewEvents();
    }
    this.f.schedule();
    if (lineMappingChanged) {
      this.c.emitOutgoingEvent(new $c9());
    }
  }
  getVisibleRangesPlusViewportAboveBelow() {
    const layoutInfo = this.b.options.get(
      151
      /* EditorOption.layoutInfo */
    );
    const lineHeight = this.b.options.get(
      68
      /* EditorOption.lineHeight */
    );
    const linesAround = Math.max(20, Math.round(layoutInfo.height / lineHeight));
    const partialData = this.viewLayout.getLinesViewportData();
    const startViewLineNumber = Math.max(1, partialData.completelyVisibleStartLineNumber - linesAround);
    const endViewLineNumber = Math.min(this.getLineCount(), partialData.completelyVisibleEndLineNumber + linesAround);
    return this.L(new $9C(startViewLineNumber, this.getLineMinColumn(startViewLineNumber), endViewLineNumber, this.getLineMaxColumn(endViewLineNumber)));
  }
  getVisibleRanges() {
    const visibleViewRange = this.getCompletelyVisibleViewRange();
    return this.L(visibleViewRange);
  }
  getHiddenAreas() {
    return this.m.getHiddenAreas();
  }
  L(visibleViewRange) {
    const visibleRange = this.coordinatesConverter.convertViewRangeToModelRange(visibleViewRange);
    const hiddenAreas = this.m.getHiddenAreas();
    if (hiddenAreas.length === 0) {
      return [visibleRange];
    }
    const result = [];
    let resultLen = 0;
    let startLineNumber = visibleRange.startLineNumber;
    let startColumn = visibleRange.startColumn;
    const endLineNumber = visibleRange.endLineNumber;
    const endColumn = visibleRange.endColumn;
    for (let i2 = 0, len = hiddenAreas.length; i2 < len; i2++) {
      const hiddenStartLineNumber = hiddenAreas[i2].startLineNumber;
      const hiddenEndLineNumber = hiddenAreas[i2].endLineNumber;
      if (hiddenEndLineNumber < startLineNumber) {
        continue;
      }
      if (hiddenStartLineNumber > endLineNumber) {
        continue;
      }
      if (startLineNumber < hiddenStartLineNumber) {
        result[resultLen++] = new $9C(startLineNumber, startColumn, hiddenStartLineNumber - 1, this.model.getLineMaxColumn(hiddenStartLineNumber - 1));
      }
      startLineNumber = hiddenEndLineNumber + 1;
      startColumn = 1;
    }
    if (startLineNumber < endLineNumber || startLineNumber === endLineNumber && startColumn < endColumn) {
      result[resultLen++] = new $9C(startLineNumber, startColumn, endLineNumber, endColumn);
    }
    return result;
  }
  getCompletelyVisibleViewRange() {
    const partialData = this.viewLayout.getLinesViewportData();
    const startViewLineNumber = partialData.completelyVisibleStartLineNumber;
    const endViewLineNumber = partialData.completelyVisibleEndLineNumber;
    return new $9C(startViewLineNumber, this.getLineMinColumn(startViewLineNumber), endViewLineNumber, this.getLineMaxColumn(endViewLineNumber));
  }
  getCompletelyVisibleViewRangeAtScrollTop(scrollTop) {
    const partialData = this.viewLayout.getLinesViewportDataAtScrollTop(scrollTop);
    const startViewLineNumber = partialData.completelyVisibleStartLineNumber;
    const endViewLineNumber = partialData.completelyVisibleEndLineNumber;
    return new $9C(startViewLineNumber, this.getLineMinColumn(startViewLineNumber), endViewLineNumber, this.getLineMaxColumn(endViewLineNumber));
  }
  saveState() {
    const compatViewState = this.viewLayout.saveState();
    const scrollTop = compatViewState.scrollTop;
    const firstViewLineNumber = this.viewLayout.getLineNumberAtVerticalOffset(scrollTop);
    const firstPosition = this.coordinatesConverter.convertViewPositionToModelPosition(new $8C(firstViewLineNumber, this.getLineMinColumn(firstViewLineNumber)));
    const firstPositionDeltaTop = this.viewLayout.getVerticalOffsetForLineNumber(firstViewLineNumber) - scrollTop;
    return {
      scrollLeft: compatViewState.scrollLeft,
      firstPosition,
      firstPositionDeltaTop
    };
  }
  reduceRestoreState(state) {
    if (typeof state.firstPosition === "undefined") {
      return this.M(state);
    }
    const modelPosition = this.model.validatePosition(state.firstPosition);
    const viewPosition = this.coordinatesConverter.convertModelPositionToViewPosition(modelPosition);
    const scrollTop = this.viewLayout.getVerticalOffsetForLineNumber(viewPosition.lineNumber) - state.firstPositionDeltaTop;
    return {
      scrollLeft: state.scrollLeft,
      scrollTop
    };
  }
  M(state) {
    return {
      scrollLeft: state.scrollLeft,
      scrollTop: state.scrollTopWithoutViewZones
    };
  }
  N() {
    return this.model.getOptions().tabSize;
  }
  getLineCount() {
    return this.m.getViewLineCount();
  }
  /**
   * Gives a hint that a lot of requests are about to come in for these line numbers.
   */
  setViewport(startLineNumber, endLineNumber, centeredLineNumber) {
    this.h.update(this, startLineNumber);
  }
  getActiveIndentGuide(lineNumber, minLineNumber, maxLineNumber) {
    return this.m.getActiveIndentGuide(lineNumber, minLineNumber, maxLineNumber);
  }
  getLinesIndentGuides(startLineNumber, endLineNumber) {
    return this.m.getViewLinesIndentGuides(startLineNumber, endLineNumber);
  }
  getBracketGuidesInRangeByLine(startLineNumber, endLineNumber, activePosition, options3) {
    return this.m.getViewLinesBracketGuides(startLineNumber, endLineNumber, activePosition, options3);
  }
  getLineContent(lineNumber) {
    return this.m.getViewLineContent(lineNumber);
  }
  getLineLength(lineNumber) {
    return this.m.getViewLineLength(lineNumber);
  }
  getLineMinColumn(lineNumber) {
    return this.m.getViewLineMinColumn(lineNumber);
  }
  getLineMaxColumn(lineNumber) {
    return this.m.getViewLineMaxColumn(lineNumber);
  }
  getLineFirstNonWhitespaceColumn(lineNumber) {
    const result = $Of(this.getLineContent(lineNumber));
    if (result === -1) {
      return 0;
    }
    return result + 1;
  }
  getLineLastNonWhitespaceColumn(lineNumber) {
    const result = $Qf(this.getLineContent(lineNumber));
    if (result === -1) {
      return 0;
    }
    return result + 2;
  }
  getMinimapDecorationsInRange(range) {
    return this.s.getMinimapDecorationsInRange(range);
  }
  getDecorationsInViewport(visibleRange) {
    return this.s.getDecorationsViewportData(visibleRange).decorations;
  }
  getInjectedTextAt(viewPosition) {
    return this.m.getInjectedTextAt(viewPosition);
  }
  getViewportViewLineRenderingData(visibleRange, lineNumber) {
    const allInlineDecorations = this.s.getDecorationsViewportData(visibleRange).inlineDecorations;
    const inlineDecorations = allInlineDecorations[lineNumber - visibleRange.startLineNumber];
    return this.O(lineNumber, inlineDecorations);
  }
  getViewLineRenderingData(lineNumber) {
    const inlineDecorations = this.s.getInlineDecorationsOnLine(lineNumber);
    return this.O(lineNumber, inlineDecorations);
  }
  O(lineNumber, inlineDecorations) {
    const mightContainRTL = this.model.mightContainRTL();
    const mightContainNonBasicASCII = this.model.mightContainNonBasicASCII();
    const tabSize = this.N();
    const lineData = this.m.getViewLineData(lineNumber);
    if (lineData.inlineDecorations) {
      inlineDecorations = [
        ...inlineDecorations,
        ...lineData.inlineDecorations.map((d) => d.toInlineDecoration(lineNumber))
      ];
    }
    return new $H5(lineData.minColumn, lineData.maxColumn, lineData.content, lineData.continuesWithWrappedLine, mightContainRTL, mightContainNonBasicASCII, lineData.tokens, inlineDecorations, tabSize, lineData.startVisibleColumn);
  }
  getViewLineData(lineNumber) {
    return this.m.getViewLineData(lineNumber);
  }
  getMinimapLinesRenderingData(startLineNumber, endLineNumber, needed) {
    const result = this.m.getViewLinesData(startLineNumber, endLineNumber, needed);
    return new $F5(this.N(), result);
  }
  getAllOverviewRulerDecorations(theme) {
    const decorations = this.model.getOverviewRulerDecorations(this.a, filterValidationDecorations(this.b.options));
    const result = new OverviewRulerDecorations();
    for (const decoration3 of decorations) {
      const decorationOptions = decoration3.options;
      const opts = decorationOptions.overviewRuler;
      if (!opts) {
        continue;
      }
      const lane = opts.position;
      if (lane === 0) {
        continue;
      }
      const color2 = opts.getColor(theme.value);
      const viewStartLineNumber = this.coordinatesConverter.getViewLineNumberOfModelPosition(decoration3.range.startLineNumber, decoration3.range.startColumn);
      const viewEndLineNumber = this.coordinatesConverter.getViewLineNumberOfModelPosition(decoration3.range.endLineNumber, decoration3.range.endColumn);
      result.accept(color2, decorationOptions.zIndex, viewStartLineNumber, viewEndLineNumber, lane);
    }
    return result.asArray;
  }
  P() {
    const decorations = this.model.getOverviewRulerDecorations();
    for (const decoration3 of decorations) {
      const opts1 = decoration3.options.overviewRuler;
      opts1?.invalidateCachedColor();
      const opts2 = decoration3.options.minimap;
      opts2?.invalidateCachedColor();
    }
  }
  getValueInRange(range, eol) {
    const modelRange = this.coordinatesConverter.convertViewRangeToModelRange(range);
    return this.model.getValueInRange(modelRange, eol);
  }
  getValueLengthInRange(range, eol) {
    const modelRange = this.coordinatesConverter.convertViewRangeToModelRange(range);
    return this.model.getValueLengthInRange(modelRange, eol);
  }
  modifyPosition(position, offset) {
    const modelPosition = this.coordinatesConverter.convertViewPositionToModelPosition(position);
    const resultModelPosition = this.model.modifyPosition(modelPosition, offset);
    return this.coordinatesConverter.convertModelPositionToViewPosition(resultModelPosition);
  }
  deduceModelPositionRelativeToViewPosition(viewAnchorPosition, deltaOffset, lineFeedCnt) {
    const modelAnchor = this.coordinatesConverter.convertViewPositionToModelPosition(viewAnchorPosition);
    if (this.model.getEOL().length === 2) {
      if (deltaOffset < 0) {
        deltaOffset -= lineFeedCnt;
      } else {
        deltaOffset += lineFeedCnt;
      }
    }
    const modelAnchorOffset = this.model.getOffsetAt(modelAnchor);
    const resultOffset = modelAnchorOffset + deltaOffset;
    return this.model.getPositionAt(resultOffset);
  }
  getPlainTextToCopy(modelRanges, emptySelectionClipboard, forceCRLF) {
    const newLineCharacter = forceCRLF ? "\r\n" : this.model.getEOL();
    modelRanges = modelRanges.slice(0);
    modelRanges.sort($9C.compareRangesUsingStarts);
    let hasEmptyRange = false;
    let hasNonEmptyRange = false;
    for (const range of modelRanges) {
      if (range.isEmpty()) {
        hasEmptyRange = true;
      } else {
        hasNonEmptyRange = true;
      }
    }
    if (!hasNonEmptyRange) {
      if (!emptySelectionClipboard) {
        return "";
      }
      const modelLineNumbers = modelRanges.map((r2) => r2.startLineNumber);
      let result2 = "";
      for (let i2 = 0; i2 < modelLineNumbers.length; i2++) {
        if (i2 > 0 && modelLineNumbers[i2 - 1] === modelLineNumbers[i2]) {
          continue;
        }
        result2 += this.model.getLineContent(modelLineNumbers[i2]) + newLineCharacter;
      }
      return result2;
    }
    if (hasEmptyRange && emptySelectionClipboard) {
      const result2 = [];
      let prevModelLineNumber = 0;
      for (const modelRange of modelRanges) {
        const modelLineNumber = modelRange.startLineNumber;
        if (modelRange.isEmpty()) {
          if (modelLineNumber !== prevModelLineNumber) {
            result2.push(this.model.getLineContent(modelLineNumber));
          }
        } else {
          result2.push(this.model.getValueInRange(
            modelRange,
            forceCRLF ? 2 : 0
            /* EndOfLinePreference.TextDefined */
          ));
        }
        prevModelLineNumber = modelLineNumber;
      }
      return result2.length === 1 ? result2[0] : result2;
    }
    const result = [];
    for (const modelRange of modelRanges) {
      if (!modelRange.isEmpty()) {
        result.push(this.model.getValueInRange(
          modelRange,
          forceCRLF ? 2 : 0
          /* EndOfLinePreference.TextDefined */
        ));
      }
    }
    return result.length === 1 ? result[0] : result;
  }
  getRichTextToCopy(modelRanges, emptySelectionClipboard) {
    const languageId = this.model.getLanguageId();
    if (languageId === $KF) {
      return null;
    }
    if (modelRanges.length !== 1) {
      return null;
    }
    let range = modelRanges[0];
    if (range.isEmpty()) {
      if (!emptySelectionClipboard) {
        return null;
      }
      const lineNumber = range.startLineNumber;
      range = new $9C(lineNumber, this.model.getLineMinColumn(lineNumber), lineNumber, this.model.getLineMaxColumn(lineNumber));
    }
    const fontInfo = this.b.options.get(
      52
      /* EditorOption.fontInfo */
    );
    const colorMap = this.R();
    const hasBadChars = /[:;\\\/<>]/.test(fontInfo.fontFamily);
    const useDefaultFontFamily = hasBadChars || fontInfo.fontFamily === EDITOR_FONT_DEFAULTS.fontFamily;
    let fontFamily;
    if (useDefaultFontFamily) {
      fontFamily = EDITOR_FONT_DEFAULTS.fontFamily;
    } else {
      fontFamily = fontInfo.fontFamily;
      fontFamily = fontFamily.replace(/"/g, "'");
      const hasQuotesOrIsList = /[,']/.test(fontFamily);
      if (!hasQuotesOrIsList) {
        const needsQuotes = /[+ ]/.test(fontFamily);
        if (needsQuotes) {
          fontFamily = `'${fontFamily}'`;
        }
      }
      fontFamily = `${fontFamily}, ${EDITOR_FONT_DEFAULTS.fontFamily}`;
    }
    return {
      mode: languageId,
      html: `<div style="color: ${colorMap[
        1
        /* ColorId.DefaultForeground */
      ]};background-color: ${colorMap[
        2
        /* ColorId.DefaultBackground */
      ]};font-family: ${fontFamily};font-weight: ${fontInfo.fontWeight};font-size: ${fontInfo.fontSize}px;line-height: ${fontInfo.lineHeight}px;white-space: pre;">` + this.Q(range, colorMap) + "</div>"
    };
  }
  Q(modelRange, colorMap) {
    const startLineNumber = modelRange.startLineNumber;
    const startColumn = modelRange.startColumn;
    const endLineNumber = modelRange.endLineNumber;
    const endColumn = modelRange.endColumn;
    const tabSize = this.N();
    let result = "";
    for (let lineNumber = startLineNumber; lineNumber <= endLineNumber; lineNumber++) {
      const lineTokens = this.model.tokenization.getLineTokens(lineNumber);
      const lineContent = lineTokens.getLineContent();
      const startOffset = lineNumber === startLineNumber ? startColumn - 1 : 0;
      const endOffset = lineNumber === endLineNumber ? endColumn - 1 : lineContent.length;
      if (lineContent === "") {
        result += "<br>";
      } else {
        result += $p9(lineContent, lineTokens.inflate(), colorMap, startOffset, endOffset, tabSize, $l);
      }
    }
    return result;
  }
  R() {
    const colorMap = $YE.getColorMap();
    const result = ["#000000"];
    if (colorMap) {
      for (let i2 = 1, len = colorMap.length; i2 < len; i2++) {
        result[i2] = $Vn.Format.CSS.formatHex(colorMap[i2]);
      }
    }
    return result;
  }
  //#region cursor operations
  getPrimaryCursorState() {
    return this.n.getPrimaryCursorState();
  }
  getLastAddedCursorIndex() {
    return this.n.getLastAddedCursorIndex();
  }
  getCursorStates() {
    return this.n.getCursorStates();
  }
  setCursorStates(source, reason, states) {
    return this.U((eventsCollector) => this.n.setStates(eventsCollector, source, reason, states));
  }
  getCursorColumnSelectData() {
    return this.n.getCursorColumnSelectData();
  }
  getCursorAutoClosedCharacters() {
    return this.n.getAutoClosedCharacters();
  }
  setCursorColumnSelectData(columnSelectData) {
    this.n.setCursorColumnSelectData(columnSelectData);
  }
  getPrevEditOperationType() {
    return this.n.getPrevEditOperationType();
  }
  setPrevEditOperationType(type) {
    this.n.setPrevEditOperationType(type);
  }
  getSelection() {
    return this.n.getSelection();
  }
  getSelections() {
    return this.n.getSelections();
  }
  getPosition() {
    return this.n.getPrimaryCursorState().modelState.position;
  }
  setSelections(source, selections, reason = 0) {
    this.U((eventsCollector) => this.n.setSelections(eventsCollector, source, selections, reason));
  }
  saveCursorState() {
    return this.n.saveState();
  }
  restoreCursorState(states) {
    this.U((eventsCollector) => this.n.restoreState(eventsCollector, states));
  }
  S(callback) {
    if (this.n.context.cursorConfig.readOnly) {
      this.c.emitOutgoingEvent(new $e9());
      return;
    }
    this.U(callback);
  }
  executeEdits(source, edits, cursorStateComputer) {
    this.S((eventsCollector) => this.n.executeEdits(eventsCollector, source, edits, cursorStateComputer));
  }
  startComposition() {
    this.S((eventsCollector) => this.n.startComposition(eventsCollector));
  }
  endComposition(source) {
    this.S((eventsCollector) => this.n.endComposition(eventsCollector, source));
  }
  type(text2, source) {
    this.S((eventsCollector) => this.n.type(eventsCollector, text2, source));
  }
  compositionType(text2, replacePrevCharCnt, replaceNextCharCnt, positionDelta, source) {
    this.S((eventsCollector) => this.n.compositionType(eventsCollector, text2, replacePrevCharCnt, replaceNextCharCnt, positionDelta, source));
  }
  paste(text2, pasteOnNewLine, multicursorText, source) {
    this.S((eventsCollector) => this.n.paste(eventsCollector, text2, pasteOnNewLine, multicursorText, source));
  }
  cut(source) {
    this.S((eventsCollector) => this.n.cut(eventsCollector, source));
  }
  executeCommand(command4, source) {
    this.S((eventsCollector) => this.n.executeCommand(eventsCollector, command4, source));
  }
  executeCommands(commands2, source) {
    this.S((eventsCollector) => this.n.executeCommands(eventsCollector, commands2, source));
  }
  revealAllCursors(source, revealHorizontal, minimalReveal = false) {
    this.U((eventsCollector) => this.n.revealAll(
      eventsCollector,
      source,
      minimalReveal,
      0,
      revealHorizontal,
      0
      /* ScrollType.Smooth */
    ));
  }
  revealPrimaryCursor(source, revealHorizontal, minimalReveal = false) {
    this.U((eventsCollector) => this.n.revealPrimary(
      eventsCollector,
      source,
      minimalReveal,
      0,
      revealHorizontal,
      0
      /* ScrollType.Smooth */
    ));
  }
  revealTopMostCursor(source) {
    const viewPosition = this.n.getTopMostViewPosition();
    const viewRange = new $9C(viewPosition.lineNumber, viewPosition.column, viewPosition.lineNumber, viewPosition.column);
    this.U((eventsCollector) => eventsCollector.emitViewEvent(new $x5(
      source,
      false,
      viewRange,
      null,
      0,
      true,
      0
      /* ScrollType.Smooth */
    )));
  }
  revealBottomMostCursor(source) {
    const viewPosition = this.n.getBottomMostViewPosition();
    const viewRange = new $9C(viewPosition.lineNumber, viewPosition.column, viewPosition.lineNumber, viewPosition.column);
    this.U((eventsCollector) => eventsCollector.emitViewEvent(new $x5(
      source,
      false,
      viewRange,
      null,
      0,
      true,
      0
      /* ScrollType.Smooth */
    )));
  }
  revealRange(source, revealHorizontal, viewRange, verticalType, scrollType) {
    this.U((eventsCollector) => eventsCollector.emitViewEvent(new $x5(source, false, viewRange, null, verticalType, revealHorizontal, scrollType)));
  }
  //#endregion
  //#region viewLayout
  changeWhitespace(callback) {
    const hadAChange = this.viewLayout.changeWhitespace(callback);
    if (hadAChange) {
      this.c.emitSingleViewEvent(new $C5());
      this.c.emitOutgoingEvent(new $b9());
    }
  }
  //#endregion
  U(callback) {
    return this.y.batchChanges(() => {
      try {
        const eventsCollector = this.c.beginEmitViewEvents();
        return callback(eventsCollector);
      } finally {
        this.c.endEmitViewEvents();
      }
    });
  }
  batchEvents(callback) {
    this.U(() => {
      callback();
    });
  }
  normalizePosition(position, affinity) {
    return this.m.normalizePosition(position, affinity);
  }
  /**
   * Gets the column at which indentation stops at a given line.
   * @internal
  */
  getLineIndentColumn(lineNumber) {
    return this.m.getLineIndentColumn(lineNumber);
  }
};
var ViewportStart = class _ViewportStart {
  static create(model) {
    const viewportStartLineTrackedRange = model._setTrackedRange(
      null,
      new $9C(1, 1, 1, 1),
      1
      /* TrackedRangeStickiness.NeverGrowsWhenTypingAtEdges */
    );
    return new _ViewportStart(model, 1, false, viewportStartLineTrackedRange, 0);
  }
  get viewLineNumber() {
    return this.b;
  }
  get isValid() {
    return this.c;
  }
  get modelTrackedRange() {
    return this.f;
  }
  get startLineDelta() {
    return this.g;
  }
  constructor(a, b, c, f, g) {
    this.a = a;
    this.b = b;
    this.c = c;
    this.f = f;
    this.g = g;
  }
  dispose() {
    this.a._setTrackedRange(
      this.f,
      null,
      1
      /* TrackedRangeStickiness.NeverGrowsWhenTypingAtEdges */
    );
  }
  update(viewModel, startLineNumber) {
    const position = viewModel.coordinatesConverter.convertViewPositionToModelPosition(new $8C(startLineNumber, viewModel.getLineMinColumn(startLineNumber)));
    const viewportStartLineTrackedRange = viewModel.model._setTrackedRange(
      this.f,
      new $9C(position.lineNumber, position.column, position.lineNumber, position.column),
      1
      /* TrackedRangeStickiness.NeverGrowsWhenTypingAtEdges */
    );
    const viewportStartLineTop = viewModel.viewLayout.getVerticalOffsetForLineNumber(startLineNumber);
    const scrollTop = viewModel.viewLayout.getCurrentScrollTop();
    this.b = startLineNumber;
    this.c = true;
    this.f = viewportStartLineTrackedRange;
    this.g = scrollTop - viewportStartLineTop;
  }
  invalidate() {
    this.c = false;
  }
};
var OverviewRulerDecorations = class {
  constructor() {
    this.a = /* @__PURE__ */ Object.create(null);
    this.asArray = [];
  }
  accept(color2, zIndex, startLineNumber, endLineNumber, lane) {
    const prevGroup = this.a[color2];
    if (prevGroup) {
      const prevData = prevGroup.data;
      const prevLane = prevData[prevData.length - 3];
      const prevEndLineNumber = prevData[prevData.length - 1];
      if (prevLane === lane && prevEndLineNumber + 1 >= startLineNumber) {
        if (endLineNumber > prevEndLineNumber) {
          prevData[prevData.length - 1] = endLineNumber;
        }
        return;
      }
      prevData.push(lane, startLineNumber, endLineNumber);
    } else {
      const group2 = new $L5(color2, zIndex, [lane, startLineNumber, endLineNumber]);
      this.a[color2] = group2;
      this.asArray.push(group2);
    }
  }
};
var HiddenAreasModel = class {
  constructor() {
    this.a = /* @__PURE__ */ new Map();
    this.b = false;
    this.c = [];
  }
  setHiddenAreas(source, ranges) {
    const existing = this.a.get(source);
    if (existing && rangeArraysEqual(existing, ranges)) {
      return;
    }
    this.a.set(source, ranges);
    this.b = true;
  }
  /**
   * The returned array is immutable.
  */
  getMergedRanges() {
    if (!this.b) {
      return this.c;
    }
    this.b = false;
    const newRanges = Array.from(this.a.values()).reduce((r2, hiddenAreas) => mergeLineRangeArray(r2, hiddenAreas), []);
    if (rangeArraysEqual(this.c, newRanges)) {
      return this.c;
    }
    this.c = newRanges;
    return this.c;
  }
};
function mergeLineRangeArray(arr1, arr2) {
  const result = [];
  let i2 = 0;
  let j = 0;
  while (i2 < arr1.length && j < arr2.length) {
    const item1 = arr1[i2];
    const item2 = arr2[j];
    if (item1.endLineNumber < item2.startLineNumber - 1) {
      result.push(arr1[i2++]);
    } else if (item2.endLineNumber < item1.startLineNumber - 1) {
      result.push(arr2[j++]);
    } else {
      const startLineNumber = Math.min(item1.startLineNumber, item2.startLineNumber);
      const endLineNumber = Math.max(item1.endLineNumber, item2.endLineNumber);
      result.push(new $9C(startLineNumber, 1, endLineNumber, 1));
      i2++;
      j++;
    }
  }
  while (i2 < arr1.length) {
    result.push(arr1[i2++]);
  }
  while (j < arr2.length) {
    result.push(arr2[j++]);
  }
  return result;
}
function rangeArraysEqual(arr1, arr2) {
  if (arr1.length !== arr2.length) {
    return false;
  }
  for (let i2 = 0; i2 < arr1.length; i2++) {
    if (!arr1[i2].equalsRange(arr2[i2])) {
      return false;
    }
  }
  return true;
}
var StableViewport = class {
  constructor(viewportStartModelPosition, startLineDelta) {
    this.viewportStartModelPosition = viewportStartModelPosition;
    this.startLineDelta = startLineDelta;
  }
  recoverViewportStart(coordinatesConverter, viewLayout) {
    if (!this.viewportStartModelPosition) {
      return;
    }
    const viewPosition = coordinatesConverter.convertModelPositionToViewPosition(this.viewportStartModelPosition);
    const viewPositionTop = viewLayout.getVerticalOffsetForLineNumber(viewPosition.lineNumber);
    viewLayout.setScrollPosition(
      { scrollTop: viewPositionTop + this.startLineDelta },
      1
      /* ScrollType.Immediate */
    );
  }
};

// out-build/vs/platform/instantiation/common/serviceCollection.js
var $Ok = class {
  constructor(...entries2) {
    this.a = /* @__PURE__ */ new Map();
    for (const [id2, service] of entries2) {
      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/editor/browser/widget/codeEditor/codeEditorWidget.js
var $D9_1;
var $D9 = class $D92 extends $3c {
  static {
    $D9_1 = this;
  }
  static {
    this.b = $WI.register({
      description: "workbench-dnd-target",
      className: "dnd-target"
    });
  }
  //#endregion
  get isSimpleWidget() {
    return this.rb.isSimpleWidget;
  }
  get contextMenuId() {
    return this.rb.contextMenuId;
  }
  get contextKeyService() {
    return this.wb;
  }
  constructor(domElement, _options, codeEditorWidgetOptions, instantiationService, codeEditorService, commandService, contextKeyService, themeService, notificationService, accessibilityService, Jb, languageFeaturesService) {
    super();
    this.Jb = Jb;
    this.c = $Ae();
    this.f = this.B(new $38());
    this.g = this.B(new $ze());
    this.onDidDispose = this.g.event;
    this.h = this.B(new $ze({ deliveryQueue: this.c }));
    this.onDidChangeModelContent = this.h.event;
    this.j = this.B(new $ze({ deliveryQueue: this.c }));
    this.onDidChangeModelLanguage = this.j.event;
    this.m = this.B(new $ze({ deliveryQueue: this.c }));
    this.onDidChangeModelLanguageConfiguration = this.m.event;
    this.n = this.B(new $ze({ deliveryQueue: this.c }));
    this.onDidChangeModelOptions = this.n.event;
    this.t = this.B(new $ze({ deliveryQueue: this.c }));
    this.onDidChangeModelDecorations = this.t.event;
    this.u = this.B(new $ze({ deliveryQueue: this.c }));
    this.onDidChangeModelTokens = this.u.event;
    this.w = this.B(new $ze({ deliveryQueue: this.c }));
    this.onDidChangeConfiguration = this.w.event;
    this.y = this.B(new $ze({ deliveryQueue: this.c }));
    this.onWillChangeModel = this.y.event;
    this.z = this.B(new $ze({ deliveryQueue: this.c }));
    this.onDidChangeModel = this.z.event;
    this.C = this.B(new $ze({ deliveryQueue: this.c }));
    this.onDidChangeCursorPosition = this.C.event;
    this.D = this.B(new $ze({ deliveryQueue: this.c }));
    this.onDidChangeCursorSelection = this.D.event;
    this.F = this.B(new InteractionEmitter(this.f, this.c));
    this.onDidAttemptReadOnlyEdit = this.F.event;
    this.G = this.B(new $ze({ deliveryQueue: this.c }));
    this.onDidLayoutChange = this.G.event;
    this.H = this.B(new $E9({ deliveryQueue: this.c }));
    this.onDidFocusEditorText = this.H.onDidChangeToTrue;
    this.onDidBlurEditorText = this.H.onDidChangeToFalse;
    this.I = this.B(new $E9({ deliveryQueue: this.c }));
    this.onDidFocusEditorWidget = this.I.onDidChangeToTrue;
    this.onDidBlurEditorWidget = this.I.onDidChangeToFalse;
    this.J = this.B(new InteractionEmitter(this.f, this.c));
    this.onWillType = this.J.event;
    this.L = this.B(new InteractionEmitter(this.f, this.c));
    this.onDidType = this.L.event;
    this.M = this.B(new InteractionEmitter(this.f, this.c));
    this.onDidCompositionStart = this.M.event;
    this.N = this.B(new InteractionEmitter(this.f, this.c));
    this.onDidCompositionEnd = this.N.event;
    this.O = this.B(new InteractionEmitter(this.f, this.c));
    this.onDidPaste = this.O.event;
    this.P = this.B(new InteractionEmitter(this.f, this.c));
    this.onMouseUp = this.P.event;
    this.Q = this.B(new InteractionEmitter(this.f, this.c));
    this.onMouseDown = this.Q.event;
    this.R = this.B(new InteractionEmitter(this.f, this.c));
    this.onMouseDrag = this.R.event;
    this.S = this.B(new InteractionEmitter(this.f, this.c));
    this.onMouseDrop = this.S.event;
    this.U = this.B(new InteractionEmitter(this.f, this.c));
    this.onMouseDropCanceled = this.U.event;
    this.W = this.B(new InteractionEmitter(this.f, this.c));
    this.onDropIntoEditor = this.W.event;
    this.X = this.B(new InteractionEmitter(this.f, this.c));
    this.onContextMenu = this.X.event;
    this.Y = this.B(new InteractionEmitter(this.f, this.c));
    this.onMouseMove = this.Y.event;
    this.Z = this.B(new InteractionEmitter(this.f, this.c));
    this.onMouseLeave = this.Z.event;
    this.$ = this.B(new InteractionEmitter(this.f, this.c));
    this.onMouseWheel = this.$.event;
    this.ab = this.B(new InteractionEmitter(this.f, this.c));
    this.onKeyUp = this.ab.event;
    this.bb = this.B(new InteractionEmitter(this.f, this.c));
    this.onKeyDown = this.bb.event;
    this.db = this.B(new $ze({ deliveryQueue: this.c }));
    this.onDidContentSizeChange = this.db.event;
    this.eb = this.B(new $ze({ deliveryQueue: this.c }));
    this.onDidScrollChange = this.eb.event;
    this.fb = this.B(new $ze({ deliveryQueue: this.c }));
    this.onDidChangeViewZones = this.fb.event;
    this.gb = this.B(new $ze({ deliveryQueue: this.c }));
    this.onDidChangeHiddenAreas = this.gb.event;
    this.hb = 0;
    this.ib = this.B(new $ze());
    this.onWillTriggerEditorOperationEvent = this.ib.event;
    this.jb = this.B(new $ze());
    this.onBeginUpdate = this.jb.event;
    this.lb = this.B(new $ze());
    this.onEndUpdate = this.lb.event;
    this.mb = this.B(new $ze());
    this.onBeforeExecuteEdit = this.mb.event;
    this.tb = /* @__PURE__ */ new Map();
    this.Hb = null;
    this.Ib = this.createDecorationsCollection();
    this.inComposition = false;
    codeEditorService.willCreateCodeEditor();
    const options3 = { ..._options };
    this.ob = domElement;
    this.pb = options3.overflowWidgetsDomNode;
    delete options3.overflowWidgetsDomNode;
    this.qb = ++EDITOR_ID;
    this.Fb = {};
    this.Gb = {};
    this.nb = codeEditorWidgetOptions.telemetryData;
    this.rb = this.B(this.Kb(codeEditorWidgetOptions.isSimpleWidget || false, codeEditorWidgetOptions.contextMenuId ?? (codeEditorWidgetOptions.isSimpleWidget ? $bJ.SimpleEditorContext : $bJ.EditorContext), options3, accessibilityService));
    this.B(this.rb.onDidChange((e) => {
      this.w.fire(e);
      const options4 = this.rb.options;
      if (e.hasChanged(
        151
        /* EditorOption.layoutInfo */
      )) {
        const layoutInfo = options4.get(
          151
          /* EditorOption.layoutInfo */
        );
        this.G.fire(layoutInfo);
      }
    }));
    this.wb = this.B(contextKeyService.createScoped(this.ob));
    this.xb = notificationService;
    this.yb = codeEditorService;
    this.zb = commandService;
    this.Ab = themeService;
    this.B(new EditorContextKeysManager(this, this.wb));
    this.B(new $F9(this, this.wb, languageFeaturesService));
    this.vb = this.B(instantiationService.createChild(new $Ok([$on, this.wb])));
    this.ub = null;
    this.Bb = new CodeEditorWidgetFocusTracker(domElement, this.pb);
    this.B(this.Bb.onChange(() => {
      this.I.setValue(this.Bb.hasFocus());
    }));
    this.Cb = {};
    this.Db = {};
    this.Eb = {};
    let contributions;
    if (Array.isArray(codeEditorWidgetOptions.contributions)) {
      contributions = codeEditorWidgetOptions.contributions;
    } else {
      contributions = EditorExtensionsRegistry.getEditorContributions();
    }
    this.f.initialize(this, contributions, this.vb);
    for (const action of EditorExtensionsRegistry.getEditorActions()) {
      if (this.tb.has(action.id)) {
        $gb(new Error(`Cannot have two actions with the same id ${action.id}`));
        continue;
      }
      const internalAction = new $48(action.id, action.label, action.alias, action.metadata, action.precondition ?? void 0, (args2) => {
        return this.vb.invokeFunction((accessor) => {
          return Promise.resolve(action.runEditorCommand(accessor, this, args2));
        });
      }, this.wb);
      this.tb.set(internalAction.id, internalAction);
    }
    const isDropIntoEnabled = () => {
      return !this.rb.options.get(
        96
        /* EditorOption.readOnly */
      ) && this.rb.options.get(
        36
        /* EditorOption.dropIntoEditor */
      ).enabled;
    };
    this.B(new $Ak(this.ob, {
      onDragOver: (e) => {
        if (!isDropIntoEnabled()) {
          return;
        }
        const target = this.getTargetAtClientPoint(e.clientX, e.clientY);
        if (target?.position) {
          this.ic(target.position);
        }
      },
      onDrop: async (e) => {
        if (!isDropIntoEnabled()) {
          return;
        }
        this.jc();
        if (!e.dataTransfer) {
          return;
        }
        const target = this.getTargetAtClientPoint(e.clientX, e.clientY);
        if (target?.position) {
          this.W.fire({ position: target.position, event: e });
        }
      },
      onDragLeave: () => {
        this.jc();
      },
      onDragEnd: () => {
        this.jc();
      }
    }));
    this.yb.addCodeEditor(this);
  }
  writeScreenReaderContent(reason) {
    this.ub?.view.writeScreenReaderContent(reason);
  }
  Kb(isSimpleWidget, contextMenuId, options3, accessibilityService) {
    return new $$4(isSimpleWidget, contextMenuId, options3, this.ob, accessibilityService);
  }
  getId() {
    return this.getEditorType() + ":" + this.qb;
  }
  getEditorType() {
    return EditorType.ICodeEditor;
  }
  dispose() {
    this.yb.removeCodeEditor(this);
    this.Bb.dispose();
    this.tb.clear();
    this.Cb = {};
    this.Db = {};
    this.Lb();
    this.dc(this.ec());
    this.g.fire();
    super.dispose();
  }
  invokeWithinContext(fn) {
    return this.vb.invokeFunction(fn);
  }
  updateOptions(newOptions) {
    this.rb.updateOptions(newOptions || {});
  }
  getOptions() {
    return this.rb.options;
  }
  getOption(id2) {
    return this.rb.options.get(id2);
  }
  getRawOptions() {
    return this.rb.getRawOptions();
  }
  getOverflowWidgetsDomNode() {
    return this.pb;
  }
  getConfiguredWordAtPosition(position) {
    if (!this.ub) {
      return null;
    }
    return $m6.getWordAtPosition(this.ub.model, this.rb.options.get(
      136
      /* EditorOption.wordSeparators */
    ), this.rb.options.get(
      135
      /* EditorOption.wordSegmenterLocales */
    ), position);
  }
  getValue(options3 = null) {
    if (!this.ub) {
      return "";
    }
    const preserveBOM = options3 && options3.preserveBOM ? true : false;
    let eolPreference = 0;
    if (options3 && options3.lineEnding && options3.lineEnding === "\n") {
      eolPreference = 1;
    } else if (options3 && options3.lineEnding && options3.lineEnding === "\r\n") {
      eolPreference = 2;
    }
    return this.ub.model.getValue(eolPreference, preserveBOM);
  }
  setValue(newValue) {
    try {
      this.kc();
      if (!this.ub) {
        return;
      }
      this.ub.model.setValue(newValue);
    } finally {
      this.lc();
    }
  }
  getModel() {
    if (!this.ub) {
      return null;
    }
    return this.ub.model;
  }
  setModel(_model = null) {
    try {
      this.kc();
      const model = _model;
      if (this.ub === null && model === null) {
        return;
      }
      if (this.ub && this.ub.model === model) {
        return;
      }
      const e = {
        oldModelUrl: this.ub?.model.uri || null,
        newModelUrl: model?.uri || null
      };
      this.y.fire(e);
      const hasTextFocus = this.hasTextFocus();
      const detachedModel = this.ec();
      this.bc(model);
      if (hasTextFocus && this.hasModel()) {
        this.focus();
      }
      this.Lb();
      this.z.fire(e);
      this.dc(detachedModel);
      this.sb = this.f.onAfterModelAttached();
    } finally {
      this.lc();
    }
  }
  Lb() {
    this.Fb = {};
    if (this.Gb) {
      for (const decorationType in this.Gb) {
        const subTypes = this.Gb[decorationType];
        for (const subType in subTypes) {
          this.gc(decorationType + "-" + subType);
        }
      }
      this.Gb = {};
    }
  }
  getVisibleRanges() {
    if (!this.ub) {
      return [];
    }
    return this.ub.viewModel.getVisibleRanges();
  }
  getVisibleRangesPlusViewportAboveBelow() {
    if (!this.ub) {
      return [];
    }
    return this.ub.viewModel.getVisibleRangesPlusViewportAboveBelow();
  }
  getWhitespaces() {
    if (!this.ub) {
      return [];
    }
    return this.ub.viewModel.viewLayout.getWhitespaces();
  }
  static Mb(modelData, modelLineNumber, modelColumn, includeViewZones) {
    const modelPosition = modelData.model.validatePosition({
      lineNumber: modelLineNumber,
      column: modelColumn
    });
    const viewPosition = modelData.viewModel.coordinatesConverter.convertModelPositionToViewPosition(modelPosition);
    return modelData.viewModel.viewLayout.getVerticalOffsetAfterLineNumber(viewPosition.lineNumber, includeViewZones);
  }
  getTopForLineNumber(lineNumber, includeViewZones = false) {
    if (!this.ub) {
      return -1;
    }
    return $D9_1.Nb(this.ub, lineNumber, 1, includeViewZones);
  }
  getTopForPosition(lineNumber, column) {
    if (!this.ub) {
      return -1;
    }
    return $D9_1.Nb(this.ub, lineNumber, column, false);
  }
  static Nb(modelData, modelLineNumber, modelColumn, includeViewZones = false) {
    const modelPosition = modelData.model.validatePosition({
      lineNumber: modelLineNumber,
      column: modelColumn
    });
    const viewPosition = modelData.viewModel.coordinatesConverter.convertModelPositionToViewPosition(modelPosition);
    return modelData.viewModel.viewLayout.getVerticalOffsetForLineNumber(viewPosition.lineNumber, includeViewZones);
  }
  getBottomForLineNumber(lineNumber, includeViewZones = false) {
    if (!this.ub) {
      return -1;
    }
    const maxCol = this.ub.model.getLineMaxColumn(lineNumber);
    return $D9_1.Mb(this.ub, lineNumber, maxCol, includeViewZones);
  }
  setHiddenAreas(ranges, source, forceUpdate) {
    this.ub?.viewModel.setHiddenAreas(ranges.map((r2) => $9C.lift(r2)), source, forceUpdate);
  }
  getVisibleColumnFromPosition(rawPosition) {
    if (!this.ub) {
      return rawPosition.column;
    }
    const position = this.ub.model.validatePosition(rawPosition);
    const tabSize = this.ub.model.getOptions().tabSize;
    return $cF.visibleColumnFromColumn(this.ub.model.getLineContent(position.lineNumber), position.column, tabSize) + 1;
  }
  getStatusbarColumn(rawPosition) {
    if (!this.ub) {
      return rawPosition.column;
    }
    const position = this.ub.model.validatePosition(rawPosition);
    const tabSize = this.ub.model.getOptions().tabSize;
    return $cF.toStatusbarColumn(this.ub.model.getLineContent(position.lineNumber), position.column, tabSize);
  }
  getPosition() {
    if (!this.ub) {
      return null;
    }
    return this.ub.viewModel.getPosition();
  }
  setPosition(position, source = "api") {
    if (!this.ub) {
      return;
    }
    if (!$8C.isIPosition(position)) {
      throw new Error("Invalid arguments");
    }
    this.ub.viewModel.setSelections(source, [{
      selectionStartLineNumber: position.lineNumber,
      selectionStartColumn: position.column,
      positionLineNumber: position.lineNumber,
      positionColumn: position.column
    }]);
  }
  Ob(modelRange, verticalType, revealHorizontal, scrollType) {
    if (!this.ub) {
      return;
    }
    if (!$9C.isIRange(modelRange)) {
      throw new Error("Invalid arguments");
    }
    const validatedModelRange = this.ub.model.validateRange(modelRange);
    const viewRange = this.ub.viewModel.coordinatesConverter.convertModelRangeToViewRange(validatedModelRange);
    this.ub.viewModel.revealRange("api", revealHorizontal, viewRange, verticalType, scrollType);
  }
  revealLine(lineNumber, scrollType = 0) {
    this.Pb(lineNumber, 0, scrollType);
  }
  revealLineInCenter(lineNumber, scrollType = 0) {
    this.Pb(lineNumber, 1, scrollType);
  }
  revealLineInCenterIfOutsideViewport(lineNumber, scrollType = 0) {
    this.Pb(lineNumber, 2, scrollType);
  }
  revealLineNearTop(lineNumber, scrollType = 0) {
    this.Pb(lineNumber, 5, scrollType);
  }
  Pb(lineNumber, revealType, scrollType) {
    if (typeof lineNumber !== "number") {
      throw new Error("Invalid arguments");
    }
    this.Ob(new $9C(lineNumber, 1, lineNumber, 1), revealType, false, scrollType);
  }
  revealPosition(position, scrollType = 0) {
    this.Qb(position, 0, true, scrollType);
  }
  revealPositionInCenter(position, scrollType = 0) {
    this.Qb(position, 1, true, scrollType);
  }
  revealPositionInCenterIfOutsideViewport(position, scrollType = 0) {
    this.Qb(position, 2, true, scrollType);
  }
  revealPositionNearTop(position, scrollType = 0) {
    this.Qb(position, 5, true, scrollType);
  }
  Qb(position, verticalType, revealHorizontal, scrollType) {
    if (!$8C.isIPosition(position)) {
      throw new Error("Invalid arguments");
    }
    this.Ob(new $9C(position.lineNumber, position.column, position.lineNumber, position.column), verticalType, revealHorizontal, scrollType);
  }
  getSelection() {
    if (!this.ub) {
      return null;
    }
    return this.ub.viewModel.getSelection();
  }
  getSelections() {
    if (!this.ub) {
      return null;
    }
    return this.ub.viewModel.getSelections();
  }
  setSelection(something, source = "api") {
    const isSelection = $_D.isISelection(something);
    const isRange = $9C.isIRange(something);
    if (!isSelection && !isRange) {
      throw new Error("Invalid arguments");
    }
    if (isSelection) {
      this.Rb(something, source);
    } else if (isRange) {
      const selection = {
        selectionStartLineNumber: something.startLineNumber,
        selectionStartColumn: something.startColumn,
        positionLineNumber: something.endLineNumber,
        positionColumn: something.endColumn
      };
      this.Rb(selection, source);
    }
  }
  Rb(sel, source) {
    if (!this.ub) {
      return;
    }
    const selection = new $_D(sel.selectionStartLineNumber, sel.selectionStartColumn, sel.positionLineNumber, sel.positionColumn);
    this.ub.viewModel.setSelections(source, [selection]);
  }
  revealLines(startLineNumber, endLineNumber, scrollType = 0) {
    this.Sb(startLineNumber, endLineNumber, 0, scrollType);
  }
  revealLinesInCenter(startLineNumber, endLineNumber, scrollType = 0) {
    this.Sb(startLineNumber, endLineNumber, 1, scrollType);
  }
  revealLinesInCenterIfOutsideViewport(startLineNumber, endLineNumber, scrollType = 0) {
    this.Sb(startLineNumber, endLineNumber, 2, scrollType);
  }
  revealLinesNearTop(startLineNumber, endLineNumber, scrollType = 0) {
    this.Sb(startLineNumber, endLineNumber, 5, scrollType);
  }
  Sb(startLineNumber, endLineNumber, verticalType, scrollType) {
    if (typeof startLineNumber !== "number" || typeof endLineNumber !== "number") {
      throw new Error("Invalid arguments");
    }
    this.Ob(new $9C(startLineNumber, 1, endLineNumber, 1), verticalType, false, scrollType);
  }
  revealRange(range, scrollType = 0, revealVerticalInCenter = false, revealHorizontal = true) {
    this.Tb(range, revealVerticalInCenter ? 1 : 0, revealHorizontal, scrollType);
  }
  revealRangeInCenter(range, scrollType = 0) {
    this.Tb(range, 1, true, scrollType);
  }
  revealRangeInCenterIfOutsideViewport(range, scrollType = 0) {
    this.Tb(range, 2, true, scrollType);
  }
  revealRangeNearTop(range, scrollType = 0) {
    this.Tb(range, 5, true, scrollType);
  }
  revealRangeNearTopIfOutsideViewport(range, scrollType = 0) {
    this.Tb(range, 6, true, scrollType);
  }
  revealRangeAtTop(range, scrollType = 0) {
    this.Tb(range, 3, true, scrollType);
  }
  Tb(range, verticalType, revealHorizontal, scrollType) {
    if (!$9C.isIRange(range)) {
      throw new Error("Invalid arguments");
    }
    this.Ob($9C.lift(range), verticalType, revealHorizontal, scrollType);
  }
  setSelections(ranges, source = "api", reason = 0) {
    if (!this.ub) {
      return;
    }
    if (!ranges || ranges.length === 0) {
      throw new Error("Invalid arguments");
    }
    for (let i2 = 0, len = ranges.length; i2 < len; i2++) {
      if (!$_D.isISelection(ranges[i2])) {
        throw new Error("Invalid arguments");
      }
    }
    this.ub.viewModel.setSelections(source, ranges, reason);
  }
  getContentWidth() {
    if (!this.ub) {
      return -1;
    }
    return this.ub.viewModel.viewLayout.getContentWidth();
  }
  getScrollWidth() {
    if (!this.ub) {
      return -1;
    }
    return this.ub.viewModel.viewLayout.getScrollWidth();
  }
  getScrollLeft() {
    if (!this.ub) {
      return -1;
    }
    return this.ub.viewModel.viewLayout.getCurrentScrollLeft();
  }
  getContentHeight() {
    if (!this.ub) {
      return -1;
    }
    return this.ub.viewModel.viewLayout.getContentHeight();
  }
  getScrollHeight() {
    if (!this.ub) {
      return -1;
    }
    return this.ub.viewModel.viewLayout.getScrollHeight();
  }
  getScrollTop() {
    if (!this.ub) {
      return -1;
    }
    return this.ub.viewModel.viewLayout.getCurrentScrollTop();
  }
  setScrollLeft(newScrollLeft, scrollType = 1) {
    if (!this.ub) {
      return;
    }
    if (typeof newScrollLeft !== "number") {
      throw new Error("Invalid arguments");
    }
    this.ub.viewModel.viewLayout.setScrollPosition({
      scrollLeft: newScrollLeft
    }, scrollType);
  }
  setScrollTop(newScrollTop, scrollType = 1) {
    if (!this.ub) {
      return;
    }
    if (typeof newScrollTop !== "number") {
      throw new Error("Invalid arguments");
    }
    this.ub.viewModel.viewLayout.setScrollPosition({
      scrollTop: newScrollTop
    }, scrollType);
  }
  setScrollPosition(position, scrollType = 1) {
    if (!this.ub) {
      return;
    }
    this.ub.viewModel.viewLayout.setScrollPosition(position, scrollType);
  }
  hasPendingScrollAnimation() {
    if (!this.ub) {
      return false;
    }
    return this.ub.viewModel.viewLayout.hasPendingScrollAnimation();
  }
  saveViewState() {
    if (!this.ub) {
      return null;
    }
    const contributionsState = this.f.saveViewState();
    const cursorState = this.ub.viewModel.saveCursorState();
    const viewState = this.ub.viewModel.saveState();
    return {
      cursorState,
      viewState,
      contributionsState
    };
  }
  restoreViewState(s) {
    if (!this.ub || !this.ub.hasRealView) {
      return;
    }
    const codeEditorState = s;
    if (codeEditorState && codeEditorState.cursorState && codeEditorState.viewState) {
      const cursorState = codeEditorState.cursorState;
      if (Array.isArray(cursorState)) {
        if (cursorState.length > 0) {
          this.ub.viewModel.restoreCursorState(cursorState);
        }
      } else {
        this.ub.viewModel.restoreCursorState([cursorState]);
      }
      this.f.restoreViewState(codeEditorState.contributionsState || {});
      const reducedState = this.ub.viewModel.reduceRestoreState(codeEditorState.viewState);
      this.ub.view.restoreState(reducedState);
    }
  }
  handleInitialized() {
    this._getViewModel()?.visibleLinesStabilized();
  }
  onVisible() {
    this.ub?.view.refreshFocusState();
  }
  onHide() {
    this.ub?.view.refreshFocusState();
    this.Bb.refreshState();
  }
  getContribution(id2) {
    return this.f.get(id2);
  }
  getActions() {
    return Array.from(this.tb.values());
  }
  getSupportedActions() {
    let result = this.getActions();
    result = result.filter((action) => action.isSupported());
    return result;
  }
  getAction(id2) {
    return this.tb.get(id2) || null;
  }
  trigger(source, handlerId, payload) {
    payload = payload || {};
    try {
      this.ib.fire({ source, handlerId, payload });
      this.kc();
      switch (handlerId) {
        case "compositionStart":
          this.Vb();
          return;
        case "compositionEnd":
          this.Wb(source);
          return;
        case "type": {
          const args2 = payload;
          this.Xb(source, args2.text || "");
          return;
        }
        case "replacePreviousChar": {
          const args2 = payload;
          this.Yb(source, args2.text || "", args2.replaceCharCnt || 0, 0, 0);
          return;
        }
        case "compositionType": {
          const args2 = payload;
          this.Yb(source, args2.text || "", args2.replacePrevCharCnt || 0, args2.replaceNextCharCnt || 0, args2.positionDelta || 0);
          return;
        }
        case "paste": {
          const args2 = payload;
          this.Zb(source, args2.text || "", args2.pasteOnNewLine || false, args2.multicursorText || null, args2.mode || null, args2.clipboardEvent);
          return;
        }
        case "cut":
          this.$b(source);
          return;
      }
      const action = this.getAction(handlerId);
      if (action) {
        Promise.resolve(action.run(payload)).then(void 0, $gb);
        return;
      }
      if (!this.ub) {
        return;
      }
      if (this.ac(source, handlerId, payload)) {
        return;
      }
      this.Ub(handlerId, payload);
    } finally {
      this.lc();
    }
  }
  Ub(handlerId, payload) {
    this.zb.executeCommand(handlerId, payload);
  }
  Vb() {
    if (!this.ub) {
      return;
    }
    this.inComposition = true;
    this.ub.viewModel.startComposition();
    this.M.fire();
  }
  Wb(source) {
    if (!this.ub) {
      return;
    }
    this.inComposition = false;
    this.ub.viewModel.endComposition(source);
    this.N.fire();
  }
  Xb(source, text2) {
    if (!this.ub || text2.length === 0) {
      return;
    }
    if (source === "keyboard") {
      this.J.fire(text2);
    }
    this.ub.viewModel.type(text2, source);
    if (source === "keyboard") {
      this.L.fire(text2);
    }
  }
  Yb(source, text2, replacePrevCharCnt, replaceNextCharCnt, positionDelta) {
    if (!this.ub) {
      return;
    }
    this.ub.viewModel.compositionType(text2, replacePrevCharCnt, replaceNextCharCnt, positionDelta, source);
  }
  Zb(source, text2, pasteOnNewLine, multicursorText, mode, clipboardEvent) {
    if (!this.ub) {
      return;
    }
    const viewModel = this.ub.viewModel;
    const startPosition = viewModel.getSelection().getStartPosition();
    viewModel.paste(text2, pasteOnNewLine, multicursorText, source);
    const endPosition = viewModel.getSelection().getStartPosition();
    if (source === "keyboard") {
      this.O.fire({
        clipboardEvent,
        range: new $9C(startPosition.lineNumber, startPosition.column, endPosition.lineNumber, endPosition.column),
        languageId: mode
      });
    }
  }
  $b(source) {
    if (!this.ub) {
      return;
    }
    this.ub.viewModel.cut(source);
  }
  ac(source, handlerId, payload) {
    const command4 = EditorExtensionsRegistry.getEditorCommand(handlerId);
    if (command4) {
      payload = payload || {};
      payload.source = source;
      this.vb.invokeFunction((accessor) => {
        Promise.resolve(command4.runEditorCommand(accessor, this, payload)).then(void 0, $gb);
      });
      return true;
    }
    return false;
  }
  _getViewModel() {
    if (!this.ub) {
      return null;
    }
    return this.ub.viewModel;
  }
  pushUndoStop() {
    if (!this.ub) {
      return false;
    }
    if (this.rb.options.get(
      96
      /* EditorOption.readOnly */
    )) {
      return false;
    }
    this.ub.model.pushStackElement();
    return true;
  }
  popUndoStop() {
    if (!this.ub) {
      return false;
    }
    if (this.rb.options.get(
      96
      /* EditorOption.readOnly */
    )) {
      return false;
    }
    this.ub.model.popStackElement();
    return true;
  }
  executeEdits(source, edits, endCursorState) {
    if (!this.ub) {
      return false;
    }
    if (this.rb.options.get(
      96
      /* EditorOption.readOnly */
    )) {
      return false;
    }
    let cursorStateComputer;
    if (!endCursorState) {
      cursorStateComputer = () => null;
    } else if (Array.isArray(endCursorState)) {
      cursorStateComputer = () => endCursorState;
    } else {
      cursorStateComputer = endCursorState;
    }
    this.mb.fire({ source: source ?? void 0 });
    this.ub.viewModel.executeEdits(source, edits, cursorStateComputer);
    return true;
  }
  executeCommand(source, command4) {
    if (!this.ub) {
      return;
    }
    this.ub.viewModel.executeCommand(command4, source);
  }
  executeCommands(source, commands2) {
    if (!this.ub) {
      return;
    }
    this.ub.viewModel.executeCommands(commands2, source);
  }
  createDecorationsCollection(decorations) {
    return new EditorDecorationsCollection(this, decorations);
  }
  changeDecorations(callback) {
    if (!this.ub) {
      return null;
    }
    return this.ub.model.changeDecorations(callback, this.qb);
  }
  getLineDecorations(lineNumber) {
    if (!this.ub) {
      return null;
    }
    return this.ub.model.getLineDecorations(lineNumber, this.qb, filterValidationDecorations(this.rb.options));
  }
  getDecorationsInRange(range) {
    if (!this.ub) {
      return null;
    }
    return this.ub.model.getDecorationsInRange(range, this.qb, filterValidationDecorations(this.rb.options));
  }
  /**
   * @deprecated
   */
  deltaDecorations(oldDecorations, newDecorations) {
    if (!this.ub) {
      return [];
    }
    if (oldDecorations.length === 0 && newDecorations.length === 0) {
      return oldDecorations;
    }
    return this.ub.model.deltaDecorations(oldDecorations, newDecorations, this.qb);
  }
  removeDecorations(decorationIds) {
    if (!this.ub || decorationIds.length === 0) {
      return;
    }
    this.ub.model.changeDecorations((changeAccessor) => {
      changeAccessor.deltaDecorations(decorationIds, []);
    });
  }
  setDecorationsByType(description, decorationTypeKey, decorationOptions) {
    const newDecorationsSubTypes = {};
    const oldDecorationsSubTypes = this.Gb[decorationTypeKey] || {};
    this.Gb[decorationTypeKey] = newDecorationsSubTypes;
    const newModelDecorations = [];
    for (const decorationOption of decorationOptions) {
      let typeKey = decorationTypeKey;
      if (decorationOption.renderOptions) {
        const subType = $Xi(decorationOption.renderOptions).toString(16);
        typeKey = decorationTypeKey + "-" + subType;
        if (!oldDecorationsSubTypes[subType] && !newDecorationsSubTypes[subType]) {
          this.fc(description, typeKey, decorationOption.renderOptions, decorationTypeKey);
        }
        newDecorationsSubTypes[subType] = true;
      }
      const opts = this.hc(typeKey, !!decorationOption.hoverMessage);
      if (decorationOption.hoverMessage) {
        opts.hoverMessage = decorationOption.hoverMessage;
      }
      newModelDecorations.push({ range: decorationOption.range, options: opts });
    }
    for (const subType in oldDecorationsSubTypes) {
      if (!newDecorationsSubTypes[subType]) {
        this.gc(decorationTypeKey + "-" + subType);
      }
    }
    const oldDecorationsIds = this.Fb[decorationTypeKey] || [];
    this.changeDecorations((accessor) => this.Fb[decorationTypeKey] = accessor.deltaDecorations(oldDecorationsIds, newModelDecorations));
  }
  setDecorationsByTypeFast(decorationTypeKey, ranges) {
    const oldDecorationsSubTypes = this.Gb[decorationTypeKey] || {};
    for (const subType in oldDecorationsSubTypes) {
      this.gc(decorationTypeKey + "-" + subType);
    }
    this.Gb[decorationTypeKey] = {};
    const opts = $WI.createDynamic(this.hc(decorationTypeKey, false));
    const newModelDecorations = new Array(ranges.length);
    for (let i2 = 0, len = ranges.length; i2 < len; i2++) {
      newModelDecorations[i2] = { range: ranges[i2], options: opts };
    }
    const oldDecorationsIds = this.Fb[decorationTypeKey] || [];
    this.changeDecorations((accessor) => this.Fb[decorationTypeKey] = accessor.deltaDecorations(oldDecorationsIds, newModelDecorations));
  }
  removeDecorationsByType(decorationTypeKey) {
    const oldDecorationsIds = this.Fb[decorationTypeKey];
    if (oldDecorationsIds) {
      this.changeDecorations((accessor) => accessor.deltaDecorations(oldDecorationsIds, []));
    }
    if (this.Fb.hasOwnProperty(decorationTypeKey)) {
      delete this.Fb[decorationTypeKey];
    }
    if (this.Gb.hasOwnProperty(decorationTypeKey)) {
      delete this.Gb[decorationTypeKey];
    }
  }
  getLayoutInfo() {
    const options3 = this.rb.options;
    const layoutInfo = options3.get(
      151
      /* EditorOption.layoutInfo */
    );
    return layoutInfo;
  }
  createOverviewRuler(cssClassName) {
    if (!this.ub || !this.ub.hasRealView) {
      return null;
    }
    return this.ub.view.createOverviewRuler(cssClassName);
  }
  getContainerDomNode() {
    return this.ob;
  }
  getDomNode() {
    if (!this.ub || !this.ub.hasRealView) {
      return null;
    }
    return this.ub.view.domNode.domNode;
  }
  delegateVerticalScrollbarPointerDown(browserEvent) {
    if (!this.ub || !this.ub.hasRealView) {
      return;
    }
    this.ub.view.delegateVerticalScrollbarPointerDown(browserEvent);
  }
  delegateScrollFromMouseWheelEvent(browserEvent) {
    if (!this.ub || !this.ub.hasRealView) {
      return;
    }
    this.ub.view.delegateScrollFromMouseWheelEvent(browserEvent);
  }
  layout(dimension, postponeRendering = false) {
    this.rb.observeContainer(dimension);
    if (!postponeRendering) {
      this.render();
    }
  }
  focus() {
    if (!this.ub || !this.ub.hasRealView) {
      return;
    }
    this.ub.view.focus();
  }
  hasTextFocus() {
    if (!this.ub || !this.ub.hasRealView) {
      return false;
    }
    return this.ub.view.isFocused();
  }
  hasWidgetFocus() {
    return this.Bb && this.Bb.hasFocus();
  }
  addContentWidget(widget) {
    const widgetData = {
      widget,
      position: widget.getPosition()
    };
    if (this.Cb.hasOwnProperty(widget.getId())) {
      console.warn("Overwriting a content widget with the same id:" + widget.getId());
    }
    this.Cb[widget.getId()] = widgetData;
    if (this.ub && this.ub.hasRealView) {
      this.ub.view.addContentWidget(widgetData);
    }
  }
  layoutContentWidget(widget) {
    const widgetId = widget.getId();
    if (this.Cb.hasOwnProperty(widgetId)) {
      const widgetData = this.Cb[widgetId];
      widgetData.position = widget.getPosition();
      if (this.ub && this.ub.hasRealView) {
        this.ub.view.layoutContentWidget(widgetData);
      }
    }
  }
  removeContentWidget(widget) {
    const widgetId = widget.getId();
    if (this.Cb.hasOwnProperty(widgetId)) {
      const widgetData = this.Cb[widgetId];
      delete this.Cb[widgetId];
      if (this.ub && this.ub.hasRealView) {
        this.ub.view.removeContentWidget(widgetData);
      }
    }
  }
  addOverlayWidget(widget) {
    const widgetData = {
      widget,
      position: widget.getPosition()
    };
    if (this.Db.hasOwnProperty(widget.getId())) {
      console.warn("Overwriting an overlay widget with the same id.");
    }
    this.Db[widget.getId()] = widgetData;
    if (this.ub && this.ub.hasRealView) {
      this.ub.view.addOverlayWidget(widgetData);
    }
  }
  layoutOverlayWidget(widget) {
    const widgetId = widget.getId();
    if (this.Db.hasOwnProperty(widgetId)) {
      const widgetData = this.Db[widgetId];
      widgetData.position = widget.getPosition();
      if (this.ub && this.ub.hasRealView) {
        this.ub.view.layoutOverlayWidget(widgetData);
      }
    }
  }
  removeOverlayWidget(widget) {
    const widgetId = widget.getId();
    if (this.Db.hasOwnProperty(widgetId)) {
      const widgetData = this.Db[widgetId];
      delete this.Db[widgetId];
      if (this.ub && this.ub.hasRealView) {
        this.ub.view.removeOverlayWidget(widgetData);
      }
    }
  }
  addGlyphMarginWidget(widget) {
    const widgetData = {
      widget,
      position: widget.getPosition()
    };
    if (this.Eb.hasOwnProperty(widget.getId())) {
      console.warn("Overwriting a glyph margin widget with the same id.");
    }
    this.Eb[widget.getId()] = widgetData;
    if (this.ub && this.ub.hasRealView) {
      this.ub.view.addGlyphMarginWidget(widgetData);
    }
  }
  layoutGlyphMarginWidget(widget) {
    const widgetId = widget.getId();
    if (this.Eb.hasOwnProperty(widgetId)) {
      const widgetData = this.Eb[widgetId];
      widgetData.position = widget.getPosition();
      if (this.ub && this.ub.hasRealView) {
        this.ub.view.layoutGlyphMarginWidget(widgetData);
      }
    }
  }
  removeGlyphMarginWidget(widget) {
    const widgetId = widget.getId();
    if (this.Eb.hasOwnProperty(widgetId)) {
      const widgetData = this.Eb[widgetId];
      delete this.Eb[widgetId];
      if (this.ub && this.ub.hasRealView) {
        this.ub.view.removeGlyphMarginWidget(widgetData);
      }
    }
  }
  changeViewZones(callback) {
    if (!this.ub || !this.ub.hasRealView) {
      return;
    }
    this.ub.view.change(callback);
  }
  getTargetAtClientPoint(clientX, clientY) {
    if (!this.ub || !this.ub.hasRealView) {
      return null;
    }
    return this.ub.view.getTargetAtClientPoint(clientX, clientY);
  }
  getScrolledVisiblePosition(rawPosition) {
    if (!this.ub || !this.ub.hasRealView) {
      return null;
    }
    const position = this.ub.model.validatePosition(rawPosition);
    const options3 = this.rb.options;
    const layoutInfo = options3.get(
      151
      /* EditorOption.layoutInfo */
    );
    const top2 = $D9_1.Nb(this.ub, position.lineNumber, position.column) - this.getScrollTop();
    const left = this.ub.view.getOffsetForColumn(position.lineNumber, position.column) + layoutInfo.glyphMarginWidth + layoutInfo.lineNumbersWidth + layoutInfo.decorationsWidth - this.getScrollLeft();
    return {
      top: top2,
      left,
      height: options3.get(
        68
        /* EditorOption.lineHeight */
      )
    };
  }
  getOffsetForColumn(lineNumber, column) {
    if (!this.ub || !this.ub.hasRealView) {
      return -1;
    }
    return this.ub.view.getOffsetForColumn(lineNumber, column);
  }
  render(forceRedraw = false) {
    if (!this.ub || !this.ub.hasRealView) {
      return;
    }
    this.ub.viewModel.batchEvents(() => {
      this.ub.view.render(true, forceRedraw);
    });
  }
  setAriaOptions(options3) {
    if (!this.ub || !this.ub.hasRealView) {
      return;
    }
    this.ub.view.setAriaOptions(options3);
  }
  applyFontInfo(target) {
    $24(target, this.rb.options.get(
      52
      /* EditorOption.fontInfo */
    ));
  }
  setBanner(domNode, domNodeHeight) {
    if (this.Hb && this.ob.contains(this.Hb)) {
      this.Hb.remove();
    }
    this.Hb = domNode;
    this.rb.setReservedHeight(domNode ? domNodeHeight : 0);
    if (this.Hb) {
      this.ob.prepend(this.Hb);
    }
  }
  bc(model) {
    if (!model) {
      this.ub = null;
      return;
    }
    const listenersToRemove = [];
    this.ob.setAttribute("data-mode-id", model.getLanguageId());
    this.rb.setIsDominatedByLongLines(model.isDominatedByLongLines());
    this.rb.setModelLineCount(model.getLineCount());
    const attachedView = model.onBeforeAttached();
    const viewModel = new $C9(this.qb, this.rb, model, $28.create(getWindow(this.ob)), $58.create(this.rb.options), (callback) => $jj(getWindow(this.ob), callback), this.Jb, this.Ab, attachedView, {
      batchChanges: (cb) => {
        try {
          this.kc();
          return cb();
        } finally {
          this.lc();
        }
      }
    });
    listenersToRemove.push(model.onWillDispose(() => this.setModel(null)));
    listenersToRemove.push(viewModel.onEvent((e) => {
      switch (e.kind) {
        case 0:
          this.db.fire(e);
          break;
        case 1:
          this.H.setValue(e.hasFocus);
          break;
        case 2:
          this.eb.fire(e);
          break;
        case 3:
          this.fb.fire();
          break;
        case 4:
          this.gb.fire();
          break;
        case 5:
          this.F.fire();
          break;
        case 6: {
          if (e.reachedMaxCursorCount) {
            const multiCursorLimit = this.getOption(
              81
              /* EditorOption.multiCursorLimit */
            );
            const message = localize(194, null, multiCursorLimit);
            this.xb.prompt(Severity2.Warning, message, [
              {
                label: "Find and Replace",
                run: () => {
                  this.zb.executeCommand("editor.action.startFindReplaceAction");
                }
              },
              {
                label: localize(195, null),
                run: () => {
                  this.zb.executeCommand("workbench.action.openSettings2", {
                    query: "editor.multiCursorLimit"
                  });
                }
              }
            ]);
          }
          const positions = [];
          for (let i2 = 0, len = e.selections.length; i2 < len; i2++) {
            positions[i2] = e.selections[i2].getPosition();
          }
          const e1 = {
            position: positions[0],
            secondaryPositions: positions.slice(1),
            reason: e.reason,
            source: e.source
          };
          this.C.fire(e1);
          const e2 = {
            selection: e.selections[0],
            secondarySelections: e.selections.slice(1),
            modelVersionId: e.modelVersionId,
            oldSelections: e.oldSelections,
            oldModelVersionId: e.oldModelVersionId,
            source: e.source,
            reason: e.reason
          };
          this.D.fire(e2);
          break;
        }
        case 7:
          this.t.fire(e.event);
          break;
        case 8:
          this.ob.setAttribute("data-mode-id", model.getLanguageId());
          this.j.fire(e.event);
          break;
        case 9:
          this.m.fire(e.event);
          break;
        case 10:
          this.h.fire(e.event);
          break;
        case 11:
          this.n.fire(e.event);
          break;
        case 12:
          this.u.fire(e.event);
          break;
      }
    }));
    const [view, hasRealView] = this.cc(viewModel);
    if (hasRealView) {
      this.ob.appendChild(view.domNode.domNode);
      let keys = Object.keys(this.Cb);
      for (let i2 = 0, len = keys.length; i2 < len; i2++) {
        const widgetId = keys[i2];
        view.addContentWidget(this.Cb[widgetId]);
      }
      keys = Object.keys(this.Db);
      for (let i2 = 0, len = keys.length; i2 < len; i2++) {
        const widgetId = keys[i2];
        view.addOverlayWidget(this.Db[widgetId]);
      }
      keys = Object.keys(this.Eb);
      for (let i2 = 0, len = keys.length; i2 < len; i2++) {
        const widgetId = keys[i2];
        view.addGlyphMarginWidget(this.Eb[widgetId]);
      }
      view.render(false, true);
      view.domNode.domNode.setAttribute("data-uri", model.uri.toString());
    }
    this.ub = new ModelData(model, viewModel, view, hasRealView, listenersToRemove, attachedView);
  }
  cc(viewModel) {
    let commandDelegate;
    if (this.isSimpleWidget) {
      commandDelegate = {
        paste: (text2, pasteOnNewLine, multicursorText, mode) => {
          this.Zb("keyboard", text2, pasteOnNewLine, multicursorText, mode);
        },
        type: (text2) => {
          this.Xb("keyboard", text2);
        },
        compositionType: (text2, replacePrevCharCnt, replaceNextCharCnt, positionDelta) => {
          this.Yb("keyboard", text2, replacePrevCharCnt, replaceNextCharCnt, positionDelta);
        },
        startComposition: () => {
          this.Vb();
        },
        endComposition: () => {
          this.Wb("keyboard");
        },
        cut: () => {
          this.$b("keyboard");
        }
      };
    } else {
      commandDelegate = {
        paste: (text2, pasteOnNewLine, multicursorText, mode) => {
          const payload = { text: text2, pasteOnNewLine, multicursorText, mode };
          this.zb.executeCommand("paste", payload);
        },
        type: (text2) => {
          const payload = { text: text2 };
          this.zb.executeCommand("type", payload);
        },
        compositionType: (text2, replacePrevCharCnt, replaceNextCharCnt, positionDelta) => {
          if (replaceNextCharCnt || positionDelta) {
            const payload = { text: text2, replacePrevCharCnt, replaceNextCharCnt, positionDelta };
            this.zb.executeCommand("compositionType", payload);
          } else {
            const payload = { text: text2, replaceCharCnt: replacePrevCharCnt };
            this.zb.executeCommand("replacePreviousChar", payload);
          }
        },
        startComposition: () => {
          this.zb.executeCommand("compositionStart", {});
        },
        endComposition: () => {
          this.zb.executeCommand("compositionEnd", {});
        },
        cut: () => {
          this.zb.executeCommand("cut", {});
        }
      };
    }
    const viewUserInputEvents = new $Z7(viewModel.coordinatesConverter);
    viewUserInputEvents.onKeyDown = (e) => this.bb.fire(e);
    viewUserInputEvents.onKeyUp = (e) => this.ab.fire(e);
    viewUserInputEvents.onContextMenu = (e) => this.X.fire(e);
    viewUserInputEvents.onMouseMove = (e) => this.Y.fire(e);
    viewUserInputEvents.onMouseLeave = (e) => this.Z.fire(e);
    viewUserInputEvents.onMouseDown = (e) => this.Q.fire(e);
    viewUserInputEvents.onMouseUp = (e) => this.P.fire(e);
    viewUserInputEvents.onMouseDrag = (e) => this.R.fire(e);
    viewUserInputEvents.onMouseDrop = (e) => this.S.fire(e);
    viewUserInputEvents.onMouseDropCanceled = (e) => this.U.fire(e);
    viewUserInputEvents.onMouseWheel = (e) => this.$.fire(e);
    const view = new $18(this.getId(), commandDelegate, this.rb, this.Ab.getColorTheme(), viewModel, viewUserInputEvents, this.pb, this.vb);
    return [view, true];
  }
  dc(detachedModel) {
    detachedModel?.removeAllDecorationsWithOwnerId(this.qb);
  }
  ec() {
    this.sb?.dispose();
    this.sb = void 0;
    if (!this.ub) {
      return null;
    }
    const model = this.ub.model;
    const removeDomNode = this.ub.hasRealView ? this.ub.view.domNode.domNode : null;
    this.ub.dispose();
    this.ub = null;
    this.ob.removeAttribute("data-mode-id");
    if (removeDomNode && this.ob.contains(removeDomNode)) {
      removeDomNode.remove();
    }
    if (this.Hb && this.ob.contains(this.Hb)) {
      this.Hb.remove();
    }
    return model;
  }
  fc(description, key2, options3, parentTypeKey) {
    this.yb.registerDecorationType(description, key2, options3, parentTypeKey, this);
  }
  gc(key2) {
    this.yb.removeDecorationType(key2);
  }
  hc(typeKey, writable) {
    return this.yb.resolveDecorationOptions(typeKey, writable);
  }
  getTelemetryData() {
    return this.nb;
  }
  hasModel() {
    return this.ub !== null;
  }
  ic(position) {
    const newDecorations = [{
      range: new $9C(position.lineNumber, position.column, position.lineNumber, position.column),
      options: $D9_1.b
    }];
    this.Ib.set(newDecorations);
    this.revealPosition(
      position,
      1
      /* editorCommon.ScrollType.Immediate */
    );
  }
  jc() {
    this.Ib.clear();
  }
  setContextValue(key2, value) {
    this.wb.createKey(key2, value);
  }
  kc() {
    this.hb++;
    if (this.hb === 1) {
      this.jb.fire();
    }
  }
  lc() {
    this.hb--;
    if (this.hb === 0) {
      this.lb.fire();
    }
  }
};
$D9 = $D9_1 = __decorate([
  __param(3, $Pk),
  __param(4, $U5),
  __param(5, $sn),
  __param(6, $on),
  __param(7, $gs),
  __param(8, $PJ),
  __param(9, $ND),
  __param(10, $NF),
  __param(11, $mP)
], $D9);
var EDITOR_ID = 0;
var ModelData = class {
  constructor(model, viewModel, view, hasRealView, listenersToRemove, attachedView) {
    this.model = model;
    this.viewModel = viewModel;
    this.view = view;
    this.hasRealView = hasRealView;
    this.listenersToRemove = listenersToRemove;
    this.attachedView = attachedView;
  }
  dispose() {
    $Xc(this.listenersToRemove);
    this.model.onBeforeDetached(this.attachedView);
    if (this.hasRealView) {
      this.view.dispose();
    }
    this.viewModel.dispose();
  }
};
var BooleanEventValue;
(function(BooleanEventValue2) {
  BooleanEventValue2[BooleanEventValue2["NotSet"] = 0] = "NotSet";
  BooleanEventValue2[BooleanEventValue2["False"] = 1] = "False";
  BooleanEventValue2[BooleanEventValue2["True"] = 2] = "True";
})(BooleanEventValue || (BooleanEventValue = {}));
var $E9 = class extends $3c {
  constructor(g) {
    super();
    this.g = g;
    this.b = this.B(new $ze(this.g));
    this.onDidChangeToTrue = this.b.event;
    this.c = this.B(new $ze(this.g));
    this.onDidChangeToFalse = this.c.event;
    this.f = 0;
  }
  setValue(_value) {
    const value = _value ? 2 : 1;
    if (this.f === value) {
      return;
    }
    this.f = value;
    if (this.f === 2) {
      this.b.fire();
    } else if (this.f === 1) {
      this.c.fire();
    }
  }
};
var InteractionEmitter = class extends $ze {
  constructor(h3, deliveryQueue) {
    super({ deliveryQueue });
    this.h = h3;
  }
  fire(event) {
    this.h.onBeforeInteractionEvent();
    super.fire(event);
  }
};
var EditorContextKeysManager = class extends $3c {
  constructor(editor, contextKeyService) {
    super();
    this.b = editor;
    contextKeyService.createKey("editorId", editor.getId());
    this.c = EditorContextKeys.editorSimpleInput.bindTo(contextKeyService);
    this.f = EditorContextKeys.focus.bindTo(contextKeyService);
    this.g = EditorContextKeys.textInputFocus.bindTo(contextKeyService);
    this.h = EditorContextKeys.editorTextFocus.bindTo(contextKeyService);
    this.j = EditorContextKeys.tabMovesFocus.bindTo(contextKeyService);
    this.m = EditorContextKeys.readOnly.bindTo(contextKeyService);
    this.n = EditorContextKeys.inDiffEditor.bindTo(contextKeyService);
    this.t = EditorContextKeys.columnSelection.bindTo(contextKeyService);
    this.u = EditorContextKeys.hasMultipleSelections.bindTo(contextKeyService);
    this.w = EditorContextKeys.hasNonEmptySelection.bindTo(contextKeyService);
    this.y = EditorContextKeys.canUndo.bindTo(contextKeyService);
    this.z = EditorContextKeys.canRedo.bindTo(contextKeyService);
    this.B(this.b.onDidChangeConfiguration(() => this.C()));
    this.B(this.b.onDidChangeCursorSelection(() => this.D()));
    this.B(this.b.onDidFocusEditorWidget(() => this.F()));
    this.B(this.b.onDidBlurEditorWidget(() => this.F()));
    this.B(this.b.onDidFocusEditorText(() => this.F()));
    this.B(this.b.onDidBlurEditorText(() => this.F()));
    this.B(this.b.onDidChangeModel(() => this.G()));
    this.B(this.b.onDidChangeConfiguration(() => this.G()));
    this.B($94.onDidChangeTabFocus((tabFocusMode) => this.j.set(tabFocusMode)));
    this.C();
    this.D();
    this.F();
    this.G();
    this.c.set(this.b.isSimpleWidget);
  }
  C() {
    const options3 = this.b.getOptions();
    this.j.set($94.getTabFocusMode());
    this.m.set(options3.get(
      96
      /* EditorOption.readOnly */
    ));
    this.n.set(options3.get(
      63
      /* EditorOption.inDiffEditor */
    ));
    this.t.set(options3.get(
      22
      /* EditorOption.columnSelection */
    ));
  }
  D() {
    const selections = this.b.getSelections();
    if (!selections) {
      this.u.reset();
      this.w.reset();
    } else {
      this.u.set(selections.length > 1);
      this.w.set(selections.some((s) => !s.isEmpty()));
    }
  }
  F() {
    this.f.set(this.b.hasWidgetFocus() && !this.b.isSimpleWidget);
    this.h.set(this.b.hasTextFocus() && !this.b.isSimpleWidget);
    this.g.set(this.b.hasTextFocus());
  }
  G() {
    const model = this.b.getModel();
    this.y.set(Boolean(model && model.canUndo()));
    this.z.set(Boolean(model && model.canRedo()));
  }
};
var $F9 = class extends $3c {
  constructor(L, M, N) {
    super();
    this.L = L;
    this.M = M;
    this.N = N;
    this.b = EditorContextKeys.languageId.bindTo(M);
    this.c = EditorContextKeys.hasCompletionItemProvider.bindTo(M);
    this.f = EditorContextKeys.hasCodeActionsProvider.bindTo(M);
    this.g = EditorContextKeys.hasCodeLensProvider.bindTo(M);
    this.h = EditorContextKeys.hasDefinitionProvider.bindTo(M);
    this.j = EditorContextKeys.hasDeclarationProvider.bindTo(M);
    this.m = EditorContextKeys.hasImplementationProvider.bindTo(M);
    this.n = EditorContextKeys.hasTypeDefinitionProvider.bindTo(M);
    this.t = EditorContextKeys.hasHoverProvider.bindTo(M);
    this.u = EditorContextKeys.hasDocumentHighlightProvider.bindTo(M);
    this.w = EditorContextKeys.hasDocumentSymbolProvider.bindTo(M);
    this.y = EditorContextKeys.hasReferenceProvider.bindTo(M);
    this.z = EditorContextKeys.hasRenameProvider.bindTo(M);
    this.H = EditorContextKeys.hasSignatureHelpProvider.bindTo(M);
    this.I = EditorContextKeys.hasInlayHintsProvider.bindTo(M);
    this.C = EditorContextKeys.hasDocumentFormattingProvider.bindTo(M);
    this.D = EditorContextKeys.hasDocumentSelectionFormattingProvider.bindTo(M);
    this.F = EditorContextKeys.hasMultipleDocumentFormattingProvider.bindTo(M);
    this.G = EditorContextKeys.hasMultipleDocumentSelectionFormattingProvider.bindTo(M);
    this.J = EditorContextKeys.isInEmbeddedEditor.bindTo(M);
    const update = () => this.O();
    this.B(L.onDidChangeModel(update));
    this.B(L.onDidChangeModelLanguage(update));
    this.B(N.completionProvider.onDidChange(update));
    this.B(N.codeActionProvider.onDidChange(update));
    this.B(N.codeLensProvider.onDidChange(update));
    this.B(N.definitionProvider.onDidChange(update));
    this.B(N.declarationProvider.onDidChange(update));
    this.B(N.implementationProvider.onDidChange(update));
    this.B(N.typeDefinitionProvider.onDidChange(update));
    this.B(N.hoverProvider.onDidChange(update));
    this.B(N.documentHighlightProvider.onDidChange(update));
    this.B(N.documentSymbolProvider.onDidChange(update));
    this.B(N.referenceProvider.onDidChange(update));
    this.B(N.renameProvider.onDidChange(update));
    this.B(N.documentFormattingEditProvider.onDidChange(update));
    this.B(N.documentRangeFormattingEditProvider.onDidChange(update));
    this.B(N.signatureHelpProvider.onDidChange(update));
    this.B(N.inlayHintsProvider.onDidChange(update));
    update();
  }
  dispose() {
    super.dispose();
  }
  reset() {
    this.M.bufferChangeEvents(() => {
      this.b.reset();
      this.c.reset();
      this.f.reset();
      this.g.reset();
      this.h.reset();
      this.j.reset();
      this.m.reset();
      this.n.reset();
      this.t.reset();
      this.u.reset();
      this.w.reset();
      this.y.reset();
      this.z.reset();
      this.C.reset();
      this.D.reset();
      this.H.reset();
      this.J.reset();
    });
  }
  O() {
    const model = this.L.getModel();
    if (!model) {
      this.reset();
      return;
    }
    this.M.bufferChangeEvents(() => {
      this.b.set(model.getLanguageId());
      this.c.set(this.N.completionProvider.has(model));
      this.f.set(this.N.codeActionProvider.has(model));
      this.g.set(this.N.codeLensProvider.has(model));
      this.h.set(this.N.definitionProvider.has(model));
      this.j.set(this.N.declarationProvider.has(model));
      this.m.set(this.N.implementationProvider.has(model));
      this.n.set(this.N.typeDefinitionProvider.has(model));
      this.t.set(this.N.hoverProvider.has(model));
      this.u.set(this.N.documentHighlightProvider.has(model));
      this.w.set(this.N.documentSymbolProvider.has(model));
      this.y.set(this.N.referenceProvider.has(model));
      this.z.set(this.N.renameProvider.has(model));
      this.H.set(this.N.signatureHelpProvider.has(model));
      this.I.set(this.N.inlayHintsProvider.has(model));
      this.C.set(this.N.documentFormattingEditProvider.has(model) || this.N.documentRangeFormattingEditProvider.has(model));
      this.D.set(this.N.documentRangeFormattingEditProvider.has(model));
      this.F.set(this.N.documentFormattingEditProvider.all(model).length + this.N.documentRangeFormattingEditProvider.all(model).length > 1);
      this.G.set(this.N.documentRangeFormattingEditProvider.all(model).length > 1);
      this.J.set(model.uri.scheme === Schemas.walkThroughSnippet || model.uri.scheme === Schemas.vscodeChatCodeBlock);
    });
  }
};
var CodeEditorWidgetFocusTracker = class extends $3c {
  constructor(domElement, overflowWidgetsDomNode) {
    super();
    this.g = this.B(new $ze());
    this.onChange = this.g.event;
    this.j = void 0;
    this.b = false;
    this.c = this.B($_j(domElement));
    this.h = false;
    this.B(this.c.onDidFocus(() => {
      this.b = true;
      this.m();
    }));
    this.B(this.c.onDidBlur(() => {
      this.b = false;
      this.m();
    }));
    if (overflowWidgetsDomNode) {
      this.f = this.B($_j(overflowWidgetsDomNode));
      this.B(this.f.onDidFocus(() => {
        this.h = true;
        this.m();
      }));
      this.B(this.f.onDidBlur(() => {
        this.h = false;
        this.m();
      }));
    }
  }
  m() {
    const focused = this.b || this.h;
    if (this.j !== focused) {
      this.j = focused;
      this.g.fire(void 0);
    }
  }
  hasFocus() {
    return this.j ?? false;
  }
  refreshState() {
    this.c.refreshState();
    this.f?.refreshState?.();
  }
};
var EditorDecorationsCollection = class {
  get length() {
    return this.b.length;
  }
  constructor(d, decorations) {
    this.d = d;
    this.b = [];
    this.c = false;
    if (Array.isArray(decorations) && decorations.length > 0) {
      this.set(decorations);
    }
  }
  onDidChange(listener, thisArgs, disposables) {
    return this.d.onDidChangeModelDecorations((e) => {
      if (this.c) {
        return;
      }
      listener.call(thisArgs, e);
    }, disposables);
  }
  getRange(index) {
    if (!this.d.hasModel()) {
      return null;
    }
    if (index >= this.b.length) {
      return null;
    }
    return this.d.getModel().getDecorationRange(this.b[index]);
  }
  getRanges() {
    if (!this.d.hasModel()) {
      return [];
    }
    const model = this.d.getModel();
    const result = [];
    for (const decorationId of this.b) {
      const range = model.getDecorationRange(decorationId);
      if (range) {
        result.push(range);
      }
    }
    return result;
  }
  has(decoration3) {
    return this.b.includes(decoration3.id);
  }
  clear() {
    if (this.b.length === 0) {
      return;
    }
    this.set([]);
  }
  set(newDecorations) {
    try {
      this.c = true;
      this.d.changeDecorations((accessor) => {
        this.b = accessor.deltaDecorations(this.b, newDecorations);
      });
    } finally {
      this.c = false;
    }
    return this.b;
  }
  append(newDecorations) {
    let newDecorationIds = [];
    try {
      this.c = true;
      this.d.changeDecorations((accessor) => {
        newDecorationIds = accessor.deltaDecorations([], newDecorations);
        this.b = this.b.concat(newDecorationIds);
      });
    } finally {
      this.c = false;
    }
    return newDecorationIds;
  }
};
var squigglyStart = encodeURIComponent(`<svg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 6 3' enable-background='new 0 0 6 3' height='3' width='6'><g fill='`);
var squigglyEnd = encodeURIComponent(`'><polygon points='5.5,0 2.5,3 1.1,3 4.1,0'/><polygon points='4,0 6,2 6,0.6 5.4,0'/><polygon points='0,2 1,3 2.4,3 0,0.6'/></g></svg>`);
function getSquigglySVGData(color2) {
  return squigglyStart + encodeURIComponent(color2.toString()) + squigglyEnd;
}
var dotdotdotStart = encodeURIComponent(`<svg xmlns="http://www.w3.org/2000/svg" height="3" width="12"><g fill="`);
var dotdotdotEnd = encodeURIComponent(`"><circle cx="1" cy="1" r="1"/><circle cx="5" cy="1" r="1"/><circle cx="9" cy="1" r="1"/></g></svg>`);
function getDotDotDotSVGData(color2) {
  return dotdotdotStart + encodeURIComponent(color2.toString()) + dotdotdotEnd;
}
$ms((theme, collector) => {
  const errorForeground = theme.getColor($Vo);
  if (errorForeground) {
    collector.addRule(`.monaco-editor .${"squiggly-error"} { background: url("data:image/svg+xml,${getSquigglySVGData(errorForeground)}") repeat-x bottom left; }`);
  }
  const warningForeground = theme.getColor($Yo);
  if (warningForeground) {
    collector.addRule(`.monaco-editor .${"squiggly-warning"} { background: url("data:image/svg+xml,${getSquigglySVGData(warningForeground)}") repeat-x bottom left; }`);
  }
  const infoForeground = theme.getColor($2o);
  if (infoForeground) {
    collector.addRule(`.monaco-editor .${"squiggly-info"} { background: url("data:image/svg+xml,${getSquigglySVGData(infoForeground)}") repeat-x bottom left; }`);
  }
  const hintForeground = theme.getColor($4o);
  if (hintForeground) {
    collector.addRule(`.monaco-editor .${"squiggly-hint"} { background: url("data:image/svg+xml,${getDotDotDotSVGData(hintForeground)}") no-repeat bottom left; }`);
  }
  const unnecessaryForeground = theme.getColor($lH);
  if (unnecessaryForeground) {
    collector.addRule(`.monaco-editor.showUnused .${"squiggly-inline-unnecessary"} { opacity: ${unnecessaryForeground.rgba.a}; }`);
  }
});

// out-build/vs/base/common/hotReload.js
function hotReloadDisabled() {
  return true;
}
function $L3() {
  return !hotReloadDisabled() && env && !!env["VSCODE_DEV"];
}
function $M3(handler) {
  if (!$L3()) {
    return { dispose() {
    } };
  } else {
    const handlers = registerGlobalHotReloadHandler();
    handlers.add(handler);
    return {
      dispose() {
        handlers.delete(handler);
      }
    };
  }
}
function registerGlobalHotReloadHandler() {
  if (!hotReloadHandlers) {
    hotReloadHandlers = /* @__PURE__ */ new Set();
  }
  const g = globalThis;
  if (!g.$hotReload_applyNewExports) {
    g.$hotReload_applyNewExports = (args2) => {
      const args22 = { config: { mode: void 0 }, ...args2 };
      const results = [];
      for (const h3 of hotReloadHandlers) {
        const result = h3(args22);
        if (result) {
          results.push(result);
        }
      }
      if (results.length > 0) {
        return (newExports) => {
          let result = false;
          for (const r2 of results) {
            if (r2(newExports)) {
              result = true;
            }
          }
          return result;
        };
      }
      return void 0;
    };
  }
  return hotReloadHandlers;
}
var hotReloadHandlers = void 0;
if ($L3()) {
  $M3(({ oldExports, newSrc, config }) => {
    if (config.mode !== "patch-prototype") {
      return void 0;
    }
    return (newExports) => {
      for (const key2 in newExports) {
        const exportedItem = newExports[key2];
        console.log(`[hot-reload] Patching prototype methods of '${key2}'`, { exportedItem });
        if (typeof exportedItem === "function" && exportedItem.prototype) {
          const oldExportedItem = oldExports[key2];
          if (oldExportedItem) {
            for (const prop of Object.getOwnPropertyNames(exportedItem.prototype)) {
              const descriptor = Object.getOwnPropertyDescriptor(exportedItem.prototype, prop);
              const oldDescriptor = Object.getOwnPropertyDescriptor(oldExportedItem.prototype, prop);
              if (descriptor?.value?.toString() !== oldDescriptor?.value?.toString()) {
                console.log(`[hot-reload] Patching prototype method '${key2}.${prop}'`);
              }
              Object.defineProperty(oldExportedItem.prototype, prop, descriptor);
            }
            newExports[key2] = oldExportedItem;
          }
        }
      }
      return true;
    };
  });
}

// out-build/vs/base/common/hotReloadHelpers.js
function $N3(value, reader) {
  $O3([value], reader);
  return value;
}
function $O3(values, reader) {
  if ($L3()) {
    const o = $Gd("reload", (event) => $M3(({ oldExports }) => {
      if (![...Object.values(oldExports)].some((v) => values.includes(v))) {
        return void 0;
      }
      return (_newExports) => {
        event(void 0);
        return true;
      };
    }));
    o.read(reader);
  }
}
var classes = /* @__PURE__ */ new Map();
function $P3(clazz) {
  if (!$L3()) {
    return $Bd(clazz);
  }
  const id2 = clazz.name;
  let existing = classes.get(id2);
  if (!existing) {
    existing = $he(id2, clazz);
    classes.set(id2, existing);
  } else {
    setTimeout(() => {
      existing.set(clazz, void 0);
    }, 0);
  }
  return existing;
}

// out-build/vs/platform/observable/common/platformObservableUtils.js
function $G9(key2, defaultValue, configurationService) {
  return $Ed({ debugName: () => `Configuration Key "${key2}"` }, (handleChange) => configurationService.onDidChangeConfiguration((e) => {
    if (e.affectsConfiguration(key2)) {
      handleChange(e);
    }
  }), () => configurationService.getValue(key2) ?? defaultValue);
}
function $H9(key2, service, computeValue) {
  const boundKey = key2.bindTo(service);
  return $ud({ debugName: () => `Set Context Key "${key2.key}"` }, (reader) => {
    boundKey.set(computeValue(reader));
  });
}

// out-build/vs/platform/accessibilitySignal/browser/accessibilitySignalService.js
var $I9 = $Qk("accessibilitySignalService");
var $J9 = Symbol("AcknowledgeDocCommentsToken");
var $K9 = class $K92 extends $3c {
  constructor(f, g, h3) {
    super();
    this.f = f;
    this.g = g;
    this.h = h3;
    this.a = /* @__PURE__ */ new Map();
    this.b = $Dd(this, this.g.onDidChangeScreenReaderOptimized, () => (
      /** @description accessibilityService.onDidChangeScreenReaderOptimized */
      this.g.isScreenReaderOptimized()
    ));
    this.c = /* @__PURE__ */ new Set();
    this.n = /* @__PURE__ */ new Set();
    this.r = new $rf((signal) => $G9(signal.settingsKey, { sound: "off", announcement: "off" }, this.f));
    this.t = new $rf({ getCacheKey: $sd }, (arg) => {
      return $2d((reader) => {
        const setting = this.r.get(arg.signal).read(reader);
        if (arg.modality === "sound" || arg.modality === void 0) {
          if (checkEnabledState(setting.sound, () => this.b.read(reader), arg.userGesture)) {
            return true;
          }
        }
        if (arg.modality === "announcement" || arg.modality === void 0) {
          if (checkEnabledState(setting.announcement, () => this.b.read(reader), arg.userGesture)) {
            return true;
          }
        }
        return false;
      }).recomputeInitiallyAndOnChange(this.q);
    });
  }
  getEnabledState(signal, userGesture, modality) {
    return new $Sd(this.t.get({ signal, userGesture, modality }));
  }
  async playSignal(signal, options3 = {}) {
    const shouldPlayAnnouncement = options3.modality === "announcement" || options3.modality === void 0;
    const announcementMessage = signal.announcementMessage;
    if (shouldPlayAnnouncement && this.isAnnouncementEnabled(signal, options3.userGesture) && announcementMessage) {
      this.g.status(announcementMessage);
    }
    const shouldPlaySound = options3.modality === "sound" || options3.modality === void 0;
    if (shouldPlaySound && this.isSoundEnabled(signal, options3.userGesture)) {
      this.j(signal, options3.source);
      await this.playSound(signal.sound.getSound(), options3.allowManyInParallel);
    }
  }
  async playSignals(signals) {
    for (const signal of signals) {
      this.j("signal" in signal ? signal.signal : signal, "source" in signal ? signal.source : void 0);
    }
    const signalArray = signals.map((s) => "signal" in s ? s.signal : s);
    const announcements = signalArray.filter((signal) => this.isAnnouncementEnabled(signal)).map((s) => s.announcementMessage);
    if (announcements.length) {
      this.g.status(announcements.join(", "));
    }
    const sounds = new Set(signalArray.filter((signal) => this.isSoundEnabled(signal)).map((signal) => signal.sound.getSound()));
    await Promise.all(Array.from(sounds).map((sound) => this.playSound(sound, true)));
  }
  j(signal, source) {
    const isScreenReaderOptimized = this.g.isScreenReaderOptimized();
    const key2 = signal.name + (source ? `::${source}` : "") + (isScreenReaderOptimized ? "{screenReaderOptimized}" : "");
    if (this.c.has(key2) || this.m() === 0) {
      return;
    }
    this.c.add(key2);
    this.h.publicLog2("signal.played", {
      signal: signal.name,
      source: source ?? "",
      isScreenReaderOptimized
    });
  }
  m() {
    const volume = this.f.getValue("accessibility.signalOptions.volume");
    if (typeof volume !== "number") {
      return 50;
    }
    return Math.max(Math.min(volume, 100), 0);
  }
  async playSound(sound, allowManyInParallel = false) {
    if (!allowManyInParallel && this.n.has(sound)) {
      return;
    }
    this.n.add(sound);
    const url = $ih.asBrowserUri(`vs/platform/accessibilitySignal/browser/media/${sound.fileName}`).toString(true);
    try {
      const sound2 = this.a.get(url);
      if (sound2) {
        sound2.volume = this.m() / 100;
        sound2.currentTime = 0;
        await sound2.play();
      } else {
        const playedSound = await playAudio(url, this.m() / 100);
        this.a.set(url, playedSound);
      }
    } catch (e) {
      if (!e.message.includes("play() can only be initiated by a user gesture")) {
        console.error("Error while playing sound", e);
      }
    } finally {
      this.n.delete(sound);
    }
  }
  playSignalLoop(signal, milliseconds) {
    let playing = true;
    const playSound = () => {
      if (playing) {
        this.playSignal(signal, { allowManyInParallel: true }).finally(() => {
          setTimeout(() => {
            if (playing) {
              playSound();
            }
          }, milliseconds);
        });
      }
    };
    playSound();
    return $1c(() => playing = false);
  }
  isAnnouncementEnabled(signal, userGesture) {
    if (!signal.announcementMessage) {
      return false;
    }
    return this.t.get({ signal, userGesture: !!userGesture, modality: "announcement" }).get();
  }
  isSoundEnabled(signal, userGesture) {
    return this.t.get({ signal, userGesture: !!userGesture, modality: "sound" }).get();
  }
  onSoundEnabledChanged(signal) {
    return this.getEnabledState(signal, false).onDidChange;
  }
  getDelayMs(signal, modality, mode) {
    if (!this.f.getValue("accessibility.signalOptions.debouncePositionChanges")) {
      return 0;
    }
    let value;
    if (signal.name === $N9.errorAtPosition.name && mode === "positional") {
      value = this.f.getValue("accessibility.signalOptions.experimental.delays.errorAtPosition");
    } else if (signal.name === $N9.warningAtPosition.name && mode === "positional") {
      value = this.f.getValue("accessibility.signalOptions.experimental.delays.warningAtPosition");
    } else {
      value = this.f.getValue("accessibility.signalOptions.experimental.delays.general");
    }
    return modality === "sound" ? value.sound : value.announcement;
  }
};
$K9 = __decorate([
  __param(0, $kl),
  __param(1, $ND),
  __param(2, $zv)
], $K9);
function checkEnabledState(state, getScreenReaderAttached, isTriggeredByUserGesture) {
  return state === "on" || state === "always" || state === "auto" && getScreenReaderAttached() || state === "userGesture" && isTriggeredByUserGesture;
}
function playAudio(url, volume) {
  return new Promise((resolve, reject) => {
    const audio = new Audio(url);
    audio.volume = volume;
    audio.addEventListener("ended", () => {
      resolve(audio);
    });
    audio.addEventListener("error", (e) => {
      reject(e.error);
    });
    audio.play().catch((e) => {
      reject(e);
    });
  });
}
var $L9 = class _$L9 {
  static a(options3) {
    const sound = new _$L9(options3.fileName);
    return sound;
  }
  static {
    this.error = _$L9.a({ fileName: "error.mp3" });
  }
  static {
    this.warning = _$L9.a({ fileName: "warning.mp3" });
  }
  static {
    this.success = _$L9.a({ fileName: "success.mp3" });
  }
  static {
    this.foldedArea = _$L9.a({ fileName: "foldedAreas.mp3" });
  }
  static {
    this.break = _$L9.a({ fileName: "break.mp3" });
  }
  static {
    this.quickFixes = _$L9.a({ fileName: "quickFixes.mp3" });
  }
  static {
    this.taskCompleted = _$L9.a({ fileName: "taskCompleted.mp3" });
  }
  static {
    this.taskFailed = _$L9.a({ fileName: "taskFailed.mp3" });
  }
  static {
    this.terminalBell = _$L9.a({ fileName: "terminalBell.mp3" });
  }
  static {
    this.diffLineInserted = _$L9.a({ fileName: "diffLineInserted.mp3" });
  }
  static {
    this.diffLineDeleted = _$L9.a({ fileName: "diffLineDeleted.mp3" });
  }
  static {
    this.diffLineModified = _$L9.a({ fileName: "diffLineModified.mp3" });
  }
  static {
    this.requestSent = _$L9.a({ fileName: "requestSent.mp3" });
  }
  static {
    this.responseReceived1 = _$L9.a({ fileName: "responseReceived1.mp3" });
  }
  static {
    this.responseReceived2 = _$L9.a({ fileName: "responseReceived2.mp3" });
  }
  static {
    this.responseReceived3 = _$L9.a({ fileName: "responseReceived3.mp3" });
  }
  static {
    this.responseReceived4 = _$L9.a({ fileName: "responseReceived4.mp3" });
  }
  static {
    this.clear = _$L9.a({ fileName: "clear.mp3" });
  }
  static {
    this.save = _$L9.a({ fileName: "save.mp3" });
  }
  static {
    this.format = _$L9.a({ fileName: "format.mp3" });
  }
  static {
    this.voiceRecordingStarted = _$L9.a({ fileName: "voiceRecordingStarted.mp3" });
  }
  static {
    this.voiceRecordingStopped = _$L9.a({ fileName: "voiceRecordingStopped.mp3" });
  }
  static {
    this.progress = _$L9.a({ fileName: "progress.mp3" });
  }
  constructor(fileName) {
    this.fileName = fileName;
  }
};
var $M9 = class {
  constructor(randomOneOf) {
    this.randomOneOf = randomOneOf;
  }
  getSound(deterministic = false) {
    if (deterministic || this.randomOneOf.length === 1) {
      return this.randomOneOf[0];
    } else {
      const index = Math.floor(Math.random() * this.randomOneOf.length);
      return this.randomOneOf[index];
    }
  }
};
var $N9 = class _$N9 {
  constructor(sound, name, legacySoundSettingsKey, settingsKey, legacyAnnouncementSettingsKey, announcementMessage) {
    this.sound = sound;
    this.name = name;
    this.legacySoundSettingsKey = legacySoundSettingsKey;
    this.settingsKey = settingsKey;
    this.legacyAnnouncementSettingsKey = legacyAnnouncementSettingsKey;
    this.announcementMessage = announcementMessage;
  }
  static {
    this.a = /* @__PURE__ */ new Set();
  }
  static b(options3) {
    const soundSource = new $M9("randomOneOf" in options3.sound ? options3.sound.randomOneOf : [options3.sound]);
    const signal = new _$N9(soundSource, options3.name, options3.legacySoundSettingsKey, options3.settingsKey, options3.legacyAnnouncementSettingsKey, options3.announcementMessage);
    _$N9.a.add(signal);
    return signal;
  }
  static get allAccessibilitySignals() {
    return [...this.a];
  }
  static {
    this.errorAtPosition = _$N9.b({
      name: localize(1611, null),
      sound: $L9.error,
      announcementMessage: localize(1612, null),
      settingsKey: "accessibility.signals.positionHasError",
      delaySettingsKey: "accessibility.signalOptions.delays.errorAtPosition"
    });
  }
  static {
    this.warningAtPosition = _$N9.b({
      name: localize(1613, null),
      sound: $L9.warning,
      announcementMessage: localize(1614, null),
      settingsKey: "accessibility.signals.positionHasWarning",
      delaySettingsKey: "accessibility.signalOptions.delays.warningAtPosition"
    });
  }
  static {
    this.errorOnLine = _$N9.b({
      name: localize(1615, null),
      sound: $L9.error,
      legacySoundSettingsKey: "audioCues.lineHasError",
      legacyAnnouncementSettingsKey: "accessibility.alert.error",
      announcementMessage: localize(1616, null),
      settingsKey: "accessibility.signals.lineHasError"
    });
  }
  static {
    this.warningOnLine = _$N9.b({
      name: localize(1617, null),
      sound: $L9.warning,
      legacySoundSettingsKey: "audioCues.lineHasWarning",
      legacyAnnouncementSettingsKey: "accessibility.alert.warning",
      announcementMessage: localize(1618, null),
      settingsKey: "accessibility.signals.lineHasWarning"
    });
  }
  static {
    this.foldedArea = _$N9.b({
      name: localize(1619, null),
      sound: $L9.foldedArea,
      legacySoundSettingsKey: "audioCues.lineHasFoldedArea",
      legacyAnnouncementSettingsKey: "accessibility.alert.foldedArea",
      announcementMessage: localize(1620, null),
      settingsKey: "accessibility.signals.lineHasFoldedArea"
    });
  }
  static {
    this.break = _$N9.b({
      name: localize(1621, null),
      sound: $L9.break,
      legacySoundSettingsKey: "audioCues.lineHasBreakpoint",
      legacyAnnouncementSettingsKey: "accessibility.alert.breakpoint",
      announcementMessage: localize(1622, null),
      settingsKey: "accessibility.signals.lineHasBreakpoint"
    });
  }
  static {
    this.inlineSuggestion = _$N9.b({
      name: localize(1623, null),
      sound: $L9.quickFixes,
      legacySoundSettingsKey: "audioCues.lineHasInlineSuggestion",
      settingsKey: "accessibility.signals.lineHasInlineSuggestion"
    });
  }
  static {
    this.terminalQuickFix = _$N9.b({
      name: localize(1624, null),
      sound: $L9.quickFixes,
      legacySoundSettingsKey: "audioCues.terminalQuickFix",
      legacyAnnouncementSettingsKey: "accessibility.alert.terminalQuickFix",
      announcementMessage: localize(1625, null),
      settingsKey: "accessibility.signals.terminalQuickFix"
    });
  }
  static {
    this.onDebugBreak = _$N9.b({
      name: localize(1626, null),
      sound: $L9.break,
      legacySoundSettingsKey: "audioCues.onDebugBreak",
      legacyAnnouncementSettingsKey: "accessibility.alert.onDebugBreak",
      announcementMessage: localize(1627, null),
      settingsKey: "accessibility.signals.onDebugBreak"
    });
  }
  static {
    this.noInlayHints = _$N9.b({
      name: localize(1628, null),
      sound: $L9.error,
      legacySoundSettingsKey: "audioCues.noInlayHints",
      legacyAnnouncementSettingsKey: "accessibility.alert.noInlayHints",
      announcementMessage: localize(1629, null),
      settingsKey: "accessibility.signals.noInlayHints"
    });
  }
  static {
    this.taskCompleted = _$N9.b({
      name: localize(1630, null),
      sound: $L9.taskCompleted,
      legacySoundSettingsKey: "audioCues.taskCompleted",
      legacyAnnouncementSettingsKey: "accessibility.alert.taskCompleted",
      announcementMessage: localize(1631, null),
      settingsKey: "accessibility.signals.taskCompleted"
    });
  }
  static {
    this.taskFailed = _$N9.b({
      name: localize(1632, null),
      sound: $L9.taskFailed,
      legacySoundSettingsKey: "audioCues.taskFailed",
      legacyAnnouncementSettingsKey: "accessibility.alert.taskFailed",
      announcementMessage: localize(1633, null),
      settingsKey: "accessibility.signals.taskFailed"
    });
  }
  static {
    this.terminalCommandFailed = _$N9.b({
      name: localize(1634, null),
      sound: $L9.error,
      legacySoundSettingsKey: "audioCues.terminalCommandFailed",
      legacyAnnouncementSettingsKey: "accessibility.alert.terminalCommandFailed",
      announcementMessage: localize(1635, null),
      settingsKey: "accessibility.signals.terminalCommandFailed"
    });
  }
  static {
    this.terminalCommandSucceeded = _$N9.b({
      name: localize(1636, null),
      sound: $L9.success,
      announcementMessage: localize(1637, null),
      settingsKey: "accessibility.signals.terminalCommandSucceeded"
    });
  }
  static {
    this.terminalBell = _$N9.b({
      name: localize(1638, null),
      sound: $L9.terminalBell,
      legacySoundSettingsKey: "audioCues.terminalBell",
      legacyAnnouncementSettingsKey: "accessibility.alert.terminalBell",
      announcementMessage: localize(1639, null),
      settingsKey: "accessibility.signals.terminalBell"
    });
  }
  static {
    this.notebookCellCompleted = _$N9.b({
      name: localize(1640, null),
      sound: $L9.taskCompleted,
      legacySoundSettingsKey: "audioCues.notebookCellCompleted",
      legacyAnnouncementSettingsKey: "accessibility.alert.notebookCellCompleted",
      announcementMessage: localize(1641, null),
      settingsKey: "accessibility.signals.notebookCellCompleted"
    });
  }
  static {
    this.notebookCellFailed = _$N9.b({
      name: localize(1642, null),
      sound: $L9.taskFailed,
      legacySoundSettingsKey: "audioCues.notebookCellFailed",
      legacyAnnouncementSettingsKey: "accessibility.alert.notebookCellFailed",
      announcementMessage: localize(1643, null),
      settingsKey: "accessibility.signals.notebookCellFailed"
    });
  }
  static {
    this.diffLineInserted = _$N9.b({
      name: localize(1644, null),
      sound: $L9.diffLineInserted,
      legacySoundSettingsKey: "audioCues.diffLineInserted",
      settingsKey: "accessibility.signals.diffLineInserted"
    });
  }
  static {
    this.diffLineDeleted = _$N9.b({
      name: localize(1645, null),
      sound: $L9.diffLineDeleted,
      legacySoundSettingsKey: "audioCues.diffLineDeleted",
      settingsKey: "accessibility.signals.diffLineDeleted"
    });
  }
  static {
    this.diffLineModified = _$N9.b({
      name: localize(1646, null),
      sound: $L9.diffLineModified,
      legacySoundSettingsKey: "audioCues.diffLineModified",
      settingsKey: "accessibility.signals.diffLineModified"
    });
  }
  static {
    this.chatRequestSent = _$N9.b({
      name: localize(1647, null),
      sound: $L9.requestSent,
      legacySoundSettingsKey: "audioCues.chatRequestSent",
      legacyAnnouncementSettingsKey: "accessibility.alert.chatRequestSent",
      announcementMessage: localize(1648, null),
      settingsKey: "accessibility.signals.chatRequestSent"
    });
  }
  static {
    this.chatResponseReceived = _$N9.b({
      name: localize(1649, null),
      legacySoundSettingsKey: "audioCues.chatResponseReceived",
      sound: {
        randomOneOf: [
          $L9.responseReceived1,
          $L9.responseReceived2,
          $L9.responseReceived3,
          $L9.responseReceived4
        ]
      },
      settingsKey: "accessibility.signals.chatResponseReceived"
    });
  }
  static {
    this.codeActionTriggered = _$N9.b({
      name: localize(1650, null),
      sound: $L9.voiceRecordingStarted,
      legacySoundSettingsKey: "audioCues.codeActionRequestTriggered",
      legacyAnnouncementSettingsKey: "accessibility.alert.codeActionRequestTriggered",
      announcementMessage: localize(1651, null),
      settingsKey: "accessibility.signals.codeActionTriggered"
    });
  }
  static {
    this.codeActionApplied = _$N9.b({
      name: localize(1652, null),
      legacySoundSettingsKey: "audioCues.codeActionApplied",
      sound: $L9.voiceRecordingStopped,
      settingsKey: "accessibility.signals.codeActionApplied"
    });
  }
  static {
    this.progress = _$N9.b({
      name: localize(1653, null),
      sound: $L9.progress,
      legacySoundSettingsKey: "audioCues.chatResponsePending",
      legacyAnnouncementSettingsKey: "accessibility.alert.progress",
      announcementMessage: localize(1654, null),
      settingsKey: "accessibility.signals.progress"
    });
  }
  static {
    this.clear = _$N9.b({
      name: localize(1655, null),
      sound: $L9.clear,
      legacySoundSettingsKey: "audioCues.clear",
      legacyAnnouncementSettingsKey: "accessibility.alert.clear",
      announcementMessage: localize(1656, null),
      settingsKey: "accessibility.signals.clear"
    });
  }
  static {
    this.save = _$N9.b({
      name: localize(1657, null),
      sound: $L9.save,
      legacySoundSettingsKey: "audioCues.save",
      legacyAnnouncementSettingsKey: "accessibility.alert.save",
      announcementMessage: localize(1658, null),
      settingsKey: "accessibility.signals.save"
    });
  }
  static {
    this.format = _$N9.b({
      name: localize(1659, null),
      sound: $L9.format,
      legacySoundSettingsKey: "audioCues.format",
      legacyAnnouncementSettingsKey: "accessibility.alert.format",
      announcementMessage: localize(1660, null),
      settingsKey: "accessibility.signals.format"
    });
  }
  static {
    this.voiceRecordingStarted = _$N9.b({
      name: localize(1661, null),
      sound: $L9.voiceRecordingStarted,
      legacySoundSettingsKey: "audioCues.voiceRecordingStarted",
      settingsKey: "accessibility.signals.voiceRecordingStarted"
    });
  }
  static {
    this.voiceRecordingStopped = _$N9.b({
      name: localize(1662, null),
      sound: $L9.voiceRecordingStopped,
      legacySoundSettingsKey: "audioCues.voiceRecordingStopped",
      settingsKey: "accessibility.signals.voiceRecordingStopped"
    });
  }
};

// out-build/vs/platform/progress/common/progress.js
var $TJ = $Qk("progressService");
var ProgressLocation;
(function(ProgressLocation4) {
  ProgressLocation4[ProgressLocation4["Explorer"] = 1] = "Explorer";
  ProgressLocation4[ProgressLocation4["Scm"] = 3] = "Scm";
  ProgressLocation4[ProgressLocation4["Extensions"] = 5] = "Extensions";
  ProgressLocation4[ProgressLocation4["Window"] = 10] = "Window";
  ProgressLocation4[ProgressLocation4["Notification"] = 15] = "Notification";
  ProgressLocation4[ProgressLocation4["Dialog"] = 20] = "Dialog";
})(ProgressLocation || (ProgressLocation = {}));
var $UJ = Object.freeze({
  total() {
  },
  worked() {
  },
  done() {
  }
});
var $VJ = class {
  static {
    this.None = Object.freeze({ report() {
    } });
  }
  get value() {
    return this.a;
  }
  constructor(b) {
    this.b = b;
  }
  report(item) {
    this.a = item;
    this.b(this.a);
  }
};
var $XJ = class $XJ2 extends $3c {
  constructor(options3, progressService) {
    super();
    this.a = new $gi();
    progressService.withProgress(options3, (reporter) => {
      this.b = reporter;
      if (this.c) {
        reporter.report(this.c);
      }
      return this.a.p;
    });
    this.B($1c(() => this.a.complete()));
  }
  report(step) {
    if (this.b) {
      this.b.report(step);
    } else {
      this.c = step;
    }
  }
};
$XJ = __decorate([
  __param(1, $TJ)
], $XJ);
var $YJ = class extends $3c {
  constructor(g) {
    super();
    this.g = g;
    this.a = 0;
    this.b = this.B(new $2c());
  }
  start(progressDelay) {
    this.stop();
    const newOperationId = ++this.a;
    const newOperationToken = new $ad();
    this.f = setTimeout(() => {
      if (newOperationId === this.a) {
        this.c = this.g.show(true);
      }
    }, progressDelay);
    this.b.add($1c(() => clearTimeout(this.f)));
    this.b.add($1c(() => newOperationToken.cancel()));
    this.b.add($1c(() => this.c ? this.c.done() : void 0));
    return {
      id: newOperationId,
      token: newOperationToken.token,
      stop: () => this.h(newOperationId),
      isCurrent: () => this.a === newOperationId
    };
  }
  stop() {
    this.h(this.a);
  }
  h(operationId) {
    if (this.a === operationId) {
      this.b.clear();
    }
  }
};
var $ZJ = $Qk("editorProgressService");

// out-build/vs/editor/browser/stableEditorScroll.js
var $O9 = class _$O9 {
  static capture(editor) {
    if (editor.getScrollTop() === 0 || editor.hasPendingScrollAnimation()) {
      return new _$O9(editor.getScrollTop(), editor.getContentHeight(), null, 0, null);
    }
    let visiblePosition = null;
    let visiblePositionScrollDelta = 0;
    const visibleRanges = editor.getVisibleRanges();
    if (visibleRanges.length > 0) {
      visiblePosition = visibleRanges[0].getStartPosition();
      const visiblePositionScrollTop = editor.getTopForPosition(visiblePosition.lineNumber, visiblePosition.column);
      visiblePositionScrollDelta = editor.getScrollTop() - visiblePositionScrollTop;
    }
    return new _$O9(editor.getScrollTop(), editor.getContentHeight(), visiblePosition, visiblePositionScrollDelta, editor.getPosition());
  }
  constructor(a, b, c, d, e) {
    this.a = a;
    this.b = b;
    this.c = c;
    this.d = d;
    this.e = e;
  }
  restore(editor) {
    if (this.b === editor.getContentHeight() && this.a === editor.getScrollTop()) {
      return;
    }
    if (this.c) {
      const visiblePositionScrollTop = editor.getTopForPosition(this.c.lineNumber, this.c.column);
      editor.setScrollTop(visiblePositionScrollTop + this.d);
    }
  }
  restoreRelativeVerticalPositionOfCursor(editor) {
    if (this.b === editor.getContentHeight() && this.a === editor.getScrollTop()) {
      return;
    }
    const currentCursorPosition = editor.getPosition();
    if (!this.e || !currentCursorPosition) {
      return;
    }
    const offset = editor.getTopForLineNumber(currentCursorPosition.lineNumber) - editor.getTopForLineNumber(this.e.lineNumber);
    editor.setScrollTop(
      editor.getScrollTop() + offset,
      1
      /* ScrollType.Immediate */
    );
  }
};
var $P9 = class _$P9 {
  static capture(editor) {
    if (editor.hasPendingScrollAnimation()) {
      return new _$P9(editor.getScrollTop(), editor.getContentHeight(), null, 0);
    }
    let visiblePosition = null;
    let visiblePositionScrollDelta = 0;
    const visibleRanges = editor.getVisibleRanges();
    if (visibleRanges.length > 0) {
      visiblePosition = visibleRanges.at(-1).getEndPosition();
      const visiblePositionScrollBottom = editor.getBottomForLineNumber(visiblePosition.lineNumber);
      visiblePositionScrollDelta = visiblePositionScrollBottom - editor.getScrollTop();
    }
    return new _$P9(editor.getScrollTop(), editor.getContentHeight(), visiblePosition, visiblePositionScrollDelta);
  }
  constructor(a, b, c, d) {
    this.a = a;
    this.b = b;
    this.c = c;
    this.d = d;
  }
  restore(editor) {
    if (this.b === editor.getContentHeight() && this.a === editor.getScrollTop()) {
      return;
    }
    if (this.c) {
      const visiblePositionScrollBottom = editor.getBottomForLineNumber(this.c.lineNumber);
      editor.setScrollTop(
        visiblePositionScrollBottom - this.d,
        1
        /* ScrollType.Immediate */
      );
    }
  }
};

// out-build/vs/base/browser/dnd.js
var $jZ = class extends $3c {
  constructor(container2, callback) {
    super();
    this.B($_i(container2, "dragover", (e) => {
      e.preventDefault();
      if (!this.a) {
        this.a = setTimeout(() => {
          callback();
          this.a = null;
        }, 800);
      }
    }));
    ["dragleave", "drop", "dragend"].forEach((type) => {
      this.B($_i(container2, type, () => {
        this.b();
      }));
    });
  }
  b() {
    if (this.a) {
      clearTimeout(this.a);
      this.a = null;
    }
  }
  dispose() {
    super.dispose();
    this.b();
  }
};
var $kZ = {
  /**
   * Application specific resource transfer type
   */
  RESOURCES: "ResourceURLs",
  /**
   * Browser specific transfer type to download
   */
  DOWNLOAD_URL: "DownloadURL",
  /**
   * Browser specific transfer type for files
   */
  FILES: "Files",
  /**
   * Typically transfer type for copy/paste transfers.
   */
  TEXT: $YC.text,
  /**
   * Internal type used to pass around text/uri-list data.
   *
   * This is needed to work around https://bugs.chromium.org/p/chromium/issues/detail?id=239745.
   */
  INTERNAL_URI_LIST: "application/vnd.code.uri-list"
};
function $lZ(event, label3, clazz, backgroundColor, foregroundColor) {
  const dragImage = document.createElement("div");
  dragImage.className = clazz;
  dragImage.textContent = label3;
  if (foregroundColor) {
    dragImage.style.color = foregroundColor;
  }
  if (backgroundColor) {
    dragImage.style.background = backgroundColor;
  }
  if (event.dataTransfer) {
    const ownerDocument = getWindow(event).document;
    ownerDocument.body.appendChild(dragImage);
    event.dataTransfer.setDragImage(dragImage, -10, -10);
    setTimeout(() => dragImage.remove(), 0);
  }
}

// out-build/vs/base/browser/ui/hover/hoverDelegateFactory.js
var nullHoverDelegateFactory = () => ({
  get delay() {
    return -1;
  },
  dispose: () => {
  },
  showHover: () => {
    return void 0;
  }
});
var hoverDelegateFactory = nullHoverDelegateFactory;
var defaultHoverDelegateMouse = new $sf(() => hoverDelegateFactory("mouse", false));
var defaultHoverDelegateElement = new $sf(() => hoverDelegateFactory("element", false));
function $IZ(hoverDelegateProvider) {
  hoverDelegateFactory = hoverDelegateProvider;
}
function $JZ(placement) {
  if (placement === "element") {
    return defaultHoverDelegateElement.value;
  }
  return defaultHoverDelegateMouse.value;
}
function $KZ() {
  return hoverDelegateFactory("element", true);
}

// out-build/vs/base/browser/cssValue.js
function asFragment(raw) {
  return raw;
}
function $ZZ(cssPropertyValue, dflt) {
  if (cssPropertyValue !== void 0) {
    const variableMatch = cssPropertyValue.match(/^\s*var\((.+)\)$/);
    if (variableMatch) {
      const varArguments = variableMatch[1].split(",", 2);
      if (varArguments.length === 2) {
        dflt = $ZZ(varArguments[1].trim(), dflt);
      }
      return `var(${varArguments[0]}, ${dflt})`;
    }
    return cssPropertyValue;
  }
  return dflt;
}
function $1Z(value) {
  const out = value.replaceAll(/[^\w.%+-]/gi, "");
  if (out !== value) {
    console.warn(`CSS size ${value} modified to ${out} to be safe for CSS`);
  }
  return asFragment(out);
}
function $2Z(value) {
  const out = value.replaceAll(/[^[0-9a-fA-F#]]/gi, "");
  if (out !== value) {
    console.warn(`CSS hex color ${value} modified to ${out} to be safe for CSS`);
  }
  return asFragment(out);
}
function $3Z(value) {
  const out = value.replaceAll(/[^_\-a-z0-9]/gi, "");
  if (out !== value) {
    console.warn(`CSS ident value ${value} modified to ${out} to be safe for CSS`);
  }
  return asFragment(out);
}
function $4Z(value) {
  return asFragment(`'${value.replaceAll(/'/g, "\\000027")}'`);
}
function $5Z(uri) {
  if (!uri) {
    return asFragment(`url('')`);
  }
  return $7Z`url(${$4Z($ih.uriToBrowserUri(uri).toString(true))})`;
}
function $6Z(value, escapingExpected = false) {
  const out = CSS.escape(value);
  if (!escapingExpected && out !== value) {
    console.warn(`CSS class name ${value} modified to ${out} to be safe for CSS`);
  }
  return asFragment(out);
}
function $7Z(strings, ...values) {
  return asFragment(strings.reduce((result, str, i2) => {
    const value = values[i2] || "";
    return result + str + value;
  }, ""));
}
var $8Z = class {
  constructor() {
    this.a = [];
  }
  push(...parts) {
    this.a.push(...parts);
  }
  join(joiner = "\n") {
    return asFragment(this.a.join(joiner));
  }
};

// out-build/vs/base/browser/ui/list/splice.js
var $a1 = class {
  constructor(a) {
    this.a = a;
  }
  splice(start, deleteCount, elements) {
    this.a.forEach((s) => s.splice(start, deleteCount, elements));
  }
};

// out-build/vs/base/common/naturalLanguage/korean.js
function $Il(code) {
  const result = disassembleKorean(code);
  if (result && result.length > 0) {
    return new Uint32Array(result);
  }
  return void 0;
}
var codeBufferLength = 0;
var codeBuffer = new Uint32Array(10);
function disassembleKorean(code) {
  codeBufferLength = 0;
  getCodesFromArray(
    code,
    modernConsonants,
    4352
    /* HangulRangeStartCode.InitialConsonant */
  );
  if (codeBufferLength > 0) {
    return codeBuffer.subarray(0, codeBufferLength);
  }
  getCodesFromArray(
    code,
    modernVowels,
    4449
    /* HangulRangeStartCode.Vowel */
  );
  if (codeBufferLength > 0) {
    return codeBuffer.subarray(0, codeBufferLength);
  }
  getCodesFromArray(
    code,
    modernFinalConsonants,
    4520
    /* HangulRangeStartCode.FinalConsonant */
  );
  if (codeBufferLength > 0) {
    return codeBuffer.subarray(0, codeBufferLength);
  }
  getCodesFromArray(
    code,
    compatibilityJamo,
    12593
    /* HangulRangeStartCode.CompatibilityJamo */
  );
  if (codeBufferLength) {
    return codeBuffer.subarray(0, codeBufferLength);
  }
  if (code >= 44032 && code <= 55203) {
    const hangulIndex = code - 44032;
    const vowelAndFinalConsonantProduct = hangulIndex % 588;
    const initialConsonantIndex = Math.floor(hangulIndex / 588);
    const vowelIndex = Math.floor(vowelAndFinalConsonantProduct / 28);
    const finalConsonantIndex = vowelAndFinalConsonantProduct % 28 - 1;
    if (initialConsonantIndex < modernConsonants.length) {
      getCodesFromArray(initialConsonantIndex, modernConsonants, 0);
    } else if (4352 + initialConsonantIndex - 12593 < compatibilityJamo.length) {
      getCodesFromArray(
        4352 + initialConsonantIndex,
        compatibilityJamo,
        12593
        /* HangulRangeStartCode.CompatibilityJamo */
      );
    }
    if (vowelIndex < modernVowels.length) {
      getCodesFromArray(vowelIndex, modernVowels, 0);
    } else if (4449 + vowelIndex - 12593 < compatibilityJamo.length) {
      getCodesFromArray(
        4449 + vowelIndex - 12593,
        compatibilityJamo,
        12593
        /* HangulRangeStartCode.CompatibilityJamo */
      );
    }
    if (finalConsonantIndex >= 0) {
      if (finalConsonantIndex < modernFinalConsonants.length) {
        getCodesFromArray(finalConsonantIndex, modernFinalConsonants, 0);
      } else if (4520 + finalConsonantIndex - 12593 < compatibilityJamo.length) {
        getCodesFromArray(
          4520 + finalConsonantIndex - 12593,
          compatibilityJamo,
          12593
          /* HangulRangeStartCode.CompatibilityJamo */
        );
      }
    }
    if (codeBufferLength > 0) {
      return codeBuffer.subarray(0, codeBufferLength);
    }
  }
  return void 0;
}
function getCodesFromArray(code, array2, arrayStartIndex) {
  if (code >= arrayStartIndex && code < arrayStartIndex + array2.length) {
    addCodesToBuffer(array2[code - arrayStartIndex]);
  }
}
function addCodesToBuffer(codes) {
  if (codes === 0) {
    return;
  }
  codeBuffer[codeBufferLength++] = codes & 255;
  if (codes >> 8) {
    codeBuffer[codeBufferLength++] = codes >> 8 & 255;
  }
  if (codes >> 16) {
    codeBuffer[codeBufferLength++] = codes >> 16 & 255;
  }
}
var HangulRangeStartCode;
(function(HangulRangeStartCode2) {
  HangulRangeStartCode2[HangulRangeStartCode2["InitialConsonant"] = 4352] = "InitialConsonant";
  HangulRangeStartCode2[HangulRangeStartCode2["Vowel"] = 4449] = "Vowel";
  HangulRangeStartCode2[HangulRangeStartCode2["FinalConsonant"] = 4520] = "FinalConsonant";
  HangulRangeStartCode2[HangulRangeStartCode2["CompatibilityJamo"] = 12593] = "CompatibilityJamo";
})(HangulRangeStartCode || (HangulRangeStartCode = {}));
var AsciiCode;
(function(AsciiCode2) {
  AsciiCode2[AsciiCode2["NUL"] = 0] = "NUL";
  AsciiCode2[AsciiCode2["A"] = 65] = "A";
  AsciiCode2[AsciiCode2["B"] = 66] = "B";
  AsciiCode2[AsciiCode2["C"] = 67] = "C";
  AsciiCode2[AsciiCode2["D"] = 68] = "D";
  AsciiCode2[AsciiCode2["E"] = 69] = "E";
  AsciiCode2[AsciiCode2["F"] = 70] = "F";
  AsciiCode2[AsciiCode2["G"] = 71] = "G";
  AsciiCode2[AsciiCode2["H"] = 72] = "H";
  AsciiCode2[AsciiCode2["I"] = 73] = "I";
  AsciiCode2[AsciiCode2["J"] = 74] = "J";
  AsciiCode2[AsciiCode2["K"] = 75] = "K";
  AsciiCode2[AsciiCode2["L"] = 76] = "L";
  AsciiCode2[AsciiCode2["M"] = 77] = "M";
  AsciiCode2[AsciiCode2["N"] = 78] = "N";
  AsciiCode2[AsciiCode2["O"] = 79] = "O";
  AsciiCode2[AsciiCode2["P"] = 80] = "P";
  AsciiCode2[AsciiCode2["Q"] = 81] = "Q";
  AsciiCode2[AsciiCode2["R"] = 82] = "R";
  AsciiCode2[AsciiCode2["S"] = 83] = "S";
  AsciiCode2[AsciiCode2["T"] = 84] = "T";
  AsciiCode2[AsciiCode2["U"] = 85] = "U";
  AsciiCode2[AsciiCode2["V"] = 86] = "V";
  AsciiCode2[AsciiCode2["W"] = 87] = "W";
  AsciiCode2[AsciiCode2["X"] = 88] = "X";
  AsciiCode2[AsciiCode2["Y"] = 89] = "Y";
  AsciiCode2[AsciiCode2["Z"] = 90] = "Z";
  AsciiCode2[AsciiCode2["a"] = 97] = "a";
  AsciiCode2[AsciiCode2["b"] = 98] = "b";
  AsciiCode2[AsciiCode2["c"] = 99] = "c";
  AsciiCode2[AsciiCode2["d"] = 100] = "d";
  AsciiCode2[AsciiCode2["e"] = 101] = "e";
  AsciiCode2[AsciiCode2["f"] = 102] = "f";
  AsciiCode2[AsciiCode2["g"] = 103] = "g";
  AsciiCode2[AsciiCode2["h"] = 104] = "h";
  AsciiCode2[AsciiCode2["i"] = 105] = "i";
  AsciiCode2[AsciiCode2["j"] = 106] = "j";
  AsciiCode2[AsciiCode2["k"] = 107] = "k";
  AsciiCode2[AsciiCode2["l"] = 108] = "l";
  AsciiCode2[AsciiCode2["m"] = 109] = "m";
  AsciiCode2[AsciiCode2["n"] = 110] = "n";
  AsciiCode2[AsciiCode2["o"] = 111] = "o";
  AsciiCode2[AsciiCode2["p"] = 112] = "p";
  AsciiCode2[AsciiCode2["q"] = 113] = "q";
  AsciiCode2[AsciiCode2["r"] = 114] = "r";
  AsciiCode2[AsciiCode2["s"] = 115] = "s";
  AsciiCode2[AsciiCode2["t"] = 116] = "t";
  AsciiCode2[AsciiCode2["u"] = 117] = "u";
  AsciiCode2[AsciiCode2["v"] = 118] = "v";
  AsciiCode2[AsciiCode2["w"] = 119] = "w";
  AsciiCode2[AsciiCode2["x"] = 120] = "x";
  AsciiCode2[AsciiCode2["y"] = 121] = "y";
  AsciiCode2[AsciiCode2["z"] = 122] = "z";
})(AsciiCode || (AsciiCode = {}));
var AsciiCodeCombo;
(function(AsciiCodeCombo2) {
  AsciiCodeCombo2[AsciiCodeCombo2["fa"] = 24934] = "fa";
  AsciiCodeCombo2[AsciiCodeCombo2["fg"] = 26470] = "fg";
  AsciiCodeCombo2[AsciiCodeCombo2["fq"] = 29030] = "fq";
  AsciiCodeCombo2[AsciiCodeCombo2["fr"] = 29286] = "fr";
  AsciiCodeCombo2[AsciiCodeCombo2["ft"] = 29798] = "ft";
  AsciiCodeCombo2[AsciiCodeCombo2["fv"] = 30310] = "fv";
  AsciiCodeCombo2[AsciiCodeCombo2["fx"] = 30822] = "fx";
  AsciiCodeCombo2[AsciiCodeCombo2["hk"] = 27496] = "hk";
  AsciiCodeCombo2[AsciiCodeCombo2["hl"] = 27752] = "hl";
  AsciiCodeCombo2[AsciiCodeCombo2["ho"] = 28520] = "ho";
  AsciiCodeCombo2[AsciiCodeCombo2["ml"] = 27757] = "ml";
  AsciiCodeCombo2[AsciiCodeCombo2["nj"] = 27246] = "nj";
  AsciiCodeCombo2[AsciiCodeCombo2["nl"] = 27758] = "nl";
  AsciiCodeCombo2[AsciiCodeCombo2["np"] = 28782] = "np";
  AsciiCodeCombo2[AsciiCodeCombo2["qt"] = 29809] = "qt";
  AsciiCodeCombo2[AsciiCodeCombo2["rt"] = 29810] = "rt";
  AsciiCodeCombo2[AsciiCodeCombo2["sg"] = 26483] = "sg";
  AsciiCodeCombo2[AsciiCodeCombo2["sw"] = 30579] = "sw";
})(AsciiCodeCombo || (AsciiCodeCombo = {}));
var modernConsonants = new Uint8Array([
  114,
  // ㄱ
  82,
  // ㄲ
  115,
  // ㄴ
  101,
  // ㄷ
  69,
  // ㄸ
  102,
  // ㄹ
  97,
  // ㅁ
  113,
  // ㅂ
  81,
  // ㅃ
  116,
  // ㅅ
  84,
  // ㅆ
  100,
  // ㅇ
  119,
  // ㅈ
  87,
  // ㅉ
  99,
  // ㅊ
  122,
  // ㅋ
  120,
  // ㅌ
  118,
  // ㅍ
  103
  // ㅎ
]);
var modernVowels = new Uint16Array([
  107,
  //  -> ㅏ
  111,
  //  -> ㅐ
  105,
  //  -> ㅑ
  79,
  //  -> ㅒ
  106,
  //  -> ㅓ
  112,
  //  -> ㅔ
  117,
  //  -> ㅕ
  80,
  //  -> ㅖ
  104,
  //  -> ㅗ
  27496,
  //  -> ㅘ
  28520,
  //  -> ㅙ
  27752,
  //  -> ㅚ
  121,
  //  -> ㅛ
  110,
  //  -> ㅜ
  27246,
  //  -> ㅝ
  28782,
  //  -> ㅞ
  27758,
  //  -> ㅟ
  98,
  //  -> ㅠ
  109,
  //  -> ㅡ
  27757,
  //  -> ㅢ
  108
  //  -> ㅣ
]);
var modernFinalConsonants = new Uint16Array([
  114,
  // ㄱ
  82,
  // ㄲ
  29810,
  // ㄳ
  115,
  // ㄴ
  30579,
  // ㄵ
  26483,
  // ㄶ
  101,
  // ㄷ
  102,
  // ㄹ
  29286,
  // ㄺ
  24934,
  // ㄻ
  29030,
  // ㄼ
  29798,
  // ㄽ
  30822,
  // ㄾ
  30310,
  // ㄿ
  26470,
  // ㅀ
  97,
  // ㅁ
  113,
  // ㅂ
  29809,
  // ㅄ
  116,
  // ㅅ
  84,
  // ㅆ
  100,
  // ㅇ
  119,
  // ㅈ
  99,
  // ㅊ
  122,
  // ㅋ
  120,
  // ㅌ
  118,
  // ㅍ
  103
  // ㅎ
]);
var compatibilityJamo = new Uint16Array([
  114,
  // ㄱ
  82,
  // ㄲ
  29810,
  // ㄳ
  115,
  // ㄴ
  30579,
  // ㄵ
  26483,
  // ㄶ
  101,
  // ㄷ
  69,
  // ㄸ
  102,
  // ㄹ
  29286,
  // ㄺ
  24934,
  // ㄻ
  29030,
  // ㄼ
  29798,
  // ㄽ
  30822,
  // ㄾ
  30310,
  // ㄿ
  26470,
  // ㅀ
  97,
  // ㅁ
  113,
  // ㅂ
  81,
  // ㅃ
  29809,
  // ㅄ
  116,
  // ㅅ
  84,
  // ㅆ
  100,
  // ㅇ
  119,
  // ㅈ
  87,
  // ㅉ
  99,
  // ㅊ
  122,
  // ㅋ
  120,
  // ㅌ
  118,
  // ㅍ
  103,
  // ㅎ
  107,
  // ㅏ
  111,
  // ㅐ
  105,
  // ㅑ
  79,
  // ㅒ
  106,
  // ㅓ
  112,
  // ㅔ
  117,
  // ㅕ
  80,
  // ㅖ
  104,
  // ㅗ
  27496,
  // ㅘ
  28520,
  // ㅙ
  27752,
  // ㅚ
  121,
  // ㅛ
  110,
  // ㅜ
  27246,
  // ㅝ
  28782,
  // ㅞ
  27758,
  // ㅟ
  98,
  // ㅠ
  109,
  // ㅡ
  27757,
  // ㅢ
  108
  // ㅣ
  // HF: Hangul Filler (everything after this is archaic)
  // ㅥ
  // ㅦ
  // ㅧ
  // ㅨ
  // ㅩ
  // ㅪ
  // ㅫ
  // ㅬ
  // ㅮ
  // ㅯ
  // ㅰ
  // ㅱ
  // ㅲ
  // ㅳ
  // ㅴ
  // ㅵ
  // ㅶ
  // ㅷ
  // ㅸ
  // ㅹ
  // ㅺ
  // ㅻ
  // ㅼ
  // ㅽ
  // ㅾ
  // ㅿ
  // ㆀ
  // ㆁ
  // ㆂ
  // ㆃ
  // ㆄ
  // ㆅ
  // ㆆ
  // ㆇ
  // ㆈ
  // ㆉ
  // ㆊ
  // ㆋ
  // ㆌ
  // ㆍ
  // ㆎ
]);

// out-build/vs/base/common/filters.js
function or(...filter) {
  return function(word, wordToMatchAgainst) {
    for (let i2 = 0, len = filter.length; i2 < len; i2++) {
      const match = filter[i2](word, wordToMatchAgainst);
      if (match) {
        return match;
      }
    }
    return null;
  };
}
var $Kl = _matchesPrefix.bind(void 0, false);
var $Ll = _matchesPrefix.bind(void 0, true);
function _matchesPrefix(ignoreCase, word, wordToMatchAgainst) {
  if (!wordToMatchAgainst || wordToMatchAgainst.length < word.length) {
    return null;
  }
  let matches;
  if (ignoreCase) {
    matches = $2f(wordToMatchAgainst, word);
  } else {
    matches = wordToMatchAgainst.indexOf(word) === 0;
  }
  if (!matches) {
    return null;
  }
  return word.length > 0 ? [{ start: 0, end: word.length }] : [];
}
function $Ml(word, wordToMatchAgainst) {
  const index = wordToMatchAgainst.toLowerCase().indexOf(word.toLowerCase());
  if (index === -1) {
    return null;
  }
  return [{ start: index, end: index + word.length }];
}
function $Nl(word, wordToMatchAgainst) {
  return _matchesSubString(word.toLowerCase(), wordToMatchAgainst.toLowerCase(), 0, 0);
}
function _matchesSubString(word, wordToMatchAgainst, i2, j) {
  if (i2 === word.length) {
    return [];
  } else if (j === wordToMatchAgainst.length) {
    return null;
  } else {
    if (word[i2] === wordToMatchAgainst[j]) {
      let result = null;
      if (result = _matchesSubString(word, wordToMatchAgainst, i2 + 1, j + 1)) {
        return join({ start: j, end: j + 1 }, result);
      }
      return null;
    }
    return _matchesSubString(word, wordToMatchAgainst, i2, j + 1);
  }
}
function isLower(code) {
  return 97 <= code && code <= 122;
}
function $Ol(code) {
  return 65 <= code && code <= 90;
}
function isNumber(code) {
  return 48 <= code && code <= 57;
}
function isWhitespace(code) {
  return code === 32 || code === 9 || code === 10 || code === 13;
}
var wordSeparators = /* @__PURE__ */ new Set();
"()[]{}<>`'\"-/;:,.?!".split("").forEach((s) => wordSeparators.add(s.charCodeAt(0)));
function isWordSeparator(code) {
  return isWhitespace(code) || wordSeparators.has(code);
}
function charactersMatch(codeA, codeB) {
  return codeA === codeB || isWordSeparator(codeA) && isWordSeparator(codeB);
}
var alternateCharsCache = /* @__PURE__ */ new Map();
function getAlternateCodes(code) {
  if (alternateCharsCache.has(code)) {
    return alternateCharsCache.get(code);
  }
  let result;
  const codes = $Il(code);
  if (codes) {
    result = codes;
  }
  alternateCharsCache.set(code, result);
  return result;
}
function isAlphanumeric(code) {
  return isLower(code) || $Ol(code) || isNumber(code);
}
function join(head, tail) {
  if (tail.length === 0) {
    tail = [head];
  } else if (head.end === tail[0].start) {
    tail[0].start = head.start;
  } else {
    tail.unshift(head);
  }
  return tail;
}
function nextAnchor(camelCaseWord, start) {
  for (let i2 = start; i2 < camelCaseWord.length; i2++) {
    const c = camelCaseWord.charCodeAt(i2);
    if ($Ol(c) || isNumber(c) || i2 > 0 && !isAlphanumeric(camelCaseWord.charCodeAt(i2 - 1))) {
      return i2;
    }
  }
  return camelCaseWord.length;
}
function _matchesCamelCase(word, camelCaseWord, i2, j) {
  if (i2 === word.length) {
    return [];
  } else if (j === camelCaseWord.length) {
    return null;
  } else if (word[i2] !== camelCaseWord[j].toLowerCase()) {
    return null;
  } else {
    let result = null;
    let nextUpperIndex = j + 1;
    result = _matchesCamelCase(word, camelCaseWord, i2 + 1, j + 1);
    while (!result && (nextUpperIndex = nextAnchor(camelCaseWord, nextUpperIndex)) < camelCaseWord.length) {
      result = _matchesCamelCase(word, camelCaseWord, i2 + 1, nextUpperIndex);
      nextUpperIndex++;
    }
    return result === null ? null : join({ start: j, end: j + 1 }, result);
  }
}
function analyzeCamelCaseWord(word) {
  let upper = 0, lower = 0, alpha = 0, numeric = 0, code = 0;
  for (let i2 = 0; i2 < word.length; i2++) {
    code = word.charCodeAt(i2);
    if ($Ol(code)) {
      upper++;
    }
    if (isLower(code)) {
      lower++;
    }
    if (isAlphanumeric(code)) {
      alpha++;
    }
    if (isNumber(code)) {
      numeric++;
    }
  }
  const upperPercent = upper / word.length;
  const lowerPercent = lower / word.length;
  const alphaPercent = alpha / word.length;
  const numericPercent = numeric / word.length;
  return { upperPercent, lowerPercent, alphaPercent, numericPercent };
}
function isUpperCaseWord(analysis) {
  const { upperPercent, lowerPercent } = analysis;
  return lowerPercent === 0 && upperPercent > 0.6;
}
function isCamelCaseWord(analysis) {
  const { upperPercent, lowerPercent, alphaPercent, numericPercent } = analysis;
  return lowerPercent > 0.2 && upperPercent < 0.8 && alphaPercent > 0.6 && numericPercent < 0.2;
}
function isCamelCasePattern(word) {
  let upper = 0, lower = 0, code = 0, whitespace = 0;
  for (let i2 = 0; i2 < word.length; i2++) {
    code = word.charCodeAt(i2);
    if ($Ol(code)) {
      upper++;
    }
    if (isLower(code)) {
      lower++;
    }
    if (isWhitespace(code)) {
      whitespace++;
    }
  }
  if ((upper === 0 || lower === 0) && whitespace === 0) {
    return word.length <= 30;
  } else {
    return upper <= 5;
  }
}
function $Pl(word, camelCaseWord) {
  if (!camelCaseWord) {
    return null;
  }
  camelCaseWord = camelCaseWord.trim();
  if (camelCaseWord.length === 0) {
    return null;
  }
  if (!isCamelCasePattern(word)) {
    return null;
  }
  if (camelCaseWord.length > 60) {
    camelCaseWord = camelCaseWord.substring(0, 60);
  }
  const analysis = analyzeCamelCaseWord(camelCaseWord);
  if (!isCamelCaseWord(analysis)) {
    if (!isUpperCaseWord(analysis)) {
      return null;
    }
    camelCaseWord = camelCaseWord.toLowerCase();
  }
  let result = null;
  let i2 = 0;
  word = word.toLowerCase();
  while (i2 < camelCaseWord.length && (result = _matchesCamelCase(word, camelCaseWord, 0, i2)) === null) {
    i2 = nextAnchor(camelCaseWord, i2 + 1);
  }
  return result;
}
function $Ql(word, target, contiguous = false) {
  if (!target || target.length === 0) {
    return null;
  }
  let result = null;
  let targetIndex = 0;
  word = word.toLowerCase();
  target = target.toLowerCase();
  while (targetIndex < target.length) {
    result = _matchesWords(word, target, 0, targetIndex, contiguous);
    if (result !== null) {
      break;
    }
    targetIndex = nextWord(target, targetIndex + 1);
  }
  return result;
}
function _matchesWords(word, target, wordIndex, targetIndex, contiguous) {
  let targetIndexOffset = 0;
  if (wordIndex === word.length) {
    return [];
  } else if (targetIndex === target.length) {
    return null;
  } else if (!charactersMatch(word.charCodeAt(wordIndex), target.charCodeAt(targetIndex))) {
    const altChars = getAlternateCodes(word.charCodeAt(wordIndex));
    if (!altChars) {
      return null;
    }
    for (let k = 0; k < altChars.length; k++) {
      if (!charactersMatch(altChars[k], target.charCodeAt(targetIndex + k))) {
        return null;
      }
    }
    targetIndexOffset += altChars.length - 1;
  }
  let result = null;
  let nextWordIndex = targetIndex + targetIndexOffset + 1;
  result = _matchesWords(word, target, wordIndex + 1, nextWordIndex, contiguous);
  if (!contiguous) {
    while (!result && (nextWordIndex = nextWord(target, nextWordIndex)) < target.length) {
      result = _matchesWords(word, target, wordIndex + 1, nextWordIndex, contiguous);
      nextWordIndex++;
    }
  }
  if (!result) {
    return null;
  }
  if (word.charCodeAt(wordIndex) !== target.charCodeAt(targetIndex)) {
    const altChars = getAlternateCodes(word.charCodeAt(wordIndex));
    if (!altChars) {
      return result;
    }
    for (let k = 0; k < altChars.length; k++) {
      if (altChars[k] !== target.charCodeAt(targetIndex + k)) {
        return result;
      }
    }
  }
  return join({ start: targetIndex, end: targetIndex + targetIndexOffset + 1 }, result);
}
function nextWord(word, start) {
  for (let i2 = start; i2 < word.length; i2++) {
    if (isWordSeparator(word.charCodeAt(i2)) || i2 > 0 && isWordSeparator(word.charCodeAt(i2 - 1))) {
      return i2;
    }
  }
  return word.length;
}
var fuzzyContiguousFilter = or($Ll, $Pl, $Ml);
var fuzzySeparateFilter = or($Ll, $Pl, $Nl);
var fuzzyRegExpCache = new $Hc(1e4);
function $Rl(word, wordToMatchAgainst, enableSeparateSubstringMatching = false) {
  if (typeof word !== "string" || typeof wordToMatchAgainst !== "string") {
    return null;
  }
  let regexp = fuzzyRegExpCache.get(word);
  if (!regexp) {
    regexp = new RegExp($Hf(word), "i");
    fuzzyRegExpCache.set(word, regexp);
  }
  const match = regexp.exec(wordToMatchAgainst);
  if (match) {
    return [{ start: match.index, end: match.index + match[0].length }];
  }
  return enableSeparateSubstringMatching ? fuzzySeparateFilter(word, wordToMatchAgainst) : fuzzyContiguousFilter(word, wordToMatchAgainst);
}
function $Sl(pattern, word) {
  const score2 = $Xl(pattern, pattern.toLowerCase(), 0, word, word.toLowerCase(), 0, { firstMatchCanBeWeak: true, boostFullMatch: true });
  return score2 ? $Ul(score2) : null;
}
function $Tl(pattern, lowPattern, patternPos, word, lowWord, wordPos) {
  const max = Math.min(13, pattern.length);
  for (; patternPos < max; patternPos++) {
    const result = $Xl(pattern, lowPattern, patternPos, word, lowWord, wordPos, { firstMatchCanBeWeak: true, boostFullMatch: true });
    if (result) {
      return result;
    }
  }
  return [0, wordPos];
}
function $Ul(score2) {
  if (typeof score2 === "undefined") {
    return [];
  }
  const res = [];
  const wordPos = score2[1];
  for (let i2 = score2.length - 1; i2 > 1; i2--) {
    const pos = score2[i2] + wordPos;
    const last = res[res.length - 1];
    if (last && last.end === pos) {
      last.end = pos + 1;
    } else {
      res.push({ start: pos, end: pos + 1 });
    }
  }
  return res;
}
var _maxLen = 128;
function initTable() {
  const table = [];
  const row = [];
  for (let i2 = 0; i2 <= _maxLen; i2++) {
    row[i2] = 0;
  }
  for (let i2 = 0; i2 <= _maxLen; i2++) {
    table.push(row.slice(0));
  }
  return table;
}
function initArr(maxLen) {
  const row = [];
  for (let i2 = 0; i2 <= maxLen; i2++) {
    row[i2] = 0;
  }
  return row;
}
var _minWordMatchPos = initArr(2 * _maxLen);
var _maxWordMatchPos = initArr(2 * _maxLen);
var _diag = initTable();
var _table = initTable();
var _arrows = initTable();
var _debug = false;
function printTable(table, pattern, patternLen, word, wordLen) {
  function pad(s, n, pad2 = " ") {
    while (s.length < n) {
      s = pad2 + s;
    }
    return s;
  }
  let ret = ` |   |${word.split("").map((c) => pad(c, 3)).join("|")}
`;
  for (let i2 = 0; i2 <= patternLen; i2++) {
    if (i2 === 0) {
      ret += " |";
    } else {
      ret += `${pattern[i2 - 1]}|`;
    }
    ret += table[i2].slice(0, wordLen + 1).map((n) => pad(n.toString(), 3)).join("|") + "\n";
  }
  return ret;
}
function printTables(pattern, patternStart, word, wordStart) {
  pattern = pattern.substr(patternStart);
  word = word.substr(wordStart);
  console.log(printTable(_table, pattern, pattern.length, word, word.length));
  console.log(printTable(_arrows, pattern, pattern.length, word, word.length));
  console.log(printTable(_diag, pattern, pattern.length, word, word.length));
}
function isSeparatorAtPos(value, index) {
  if (index < 0 || index >= value.length) {
    return false;
  }
  const code = value.codePointAt(index);
  switch (code) {
    case 95:
    case 45:
    case 46:
    case 32:
    case 47:
    case 92:
    case 39:
    case 34:
    case 58:
    case 36:
    case 60:
    case 62:
    case 40:
    case 41:
    case 91:
    case 93:
    case 123:
    case 125:
      return true;
    case void 0:
      return false;
    default:
      if ($hg(code)) {
        return true;
      }
      return false;
  }
}
function isWhitespaceAtPos(value, index) {
  if (index < 0 || index >= value.length) {
    return false;
  }
  const code = value.charCodeAt(index);
  switch (code) {
    case 32:
    case 9:
      return true;
    default:
      return false;
  }
}
function isUpperCaseAtPos(pos, word, wordLow) {
  return word[pos] !== wordLow[pos];
}
function $Vl(patternLow, patternPos, patternLen, wordLow, wordPos, wordLen, fillMinWordPosArr = false) {
  while (patternPos < patternLen && wordPos < wordLen) {
    if (patternLow[patternPos] === wordLow[wordPos]) {
      if (fillMinWordPosArr) {
        _minWordMatchPos[patternPos] = wordPos;
      }
      patternPos += 1;
    }
    wordPos += 1;
  }
  return patternPos === patternLen;
}
var Arrow;
(function(Arrow3) {
  Arrow3[Arrow3["Diag"] = 1] = "Diag";
  Arrow3[Arrow3["Left"] = 2] = "Left";
  Arrow3[Arrow3["LeftLeft"] = 3] = "LeftLeft";
})(Arrow || (Arrow = {}));
var FuzzyScore;
(function(FuzzyScore2) {
  FuzzyScore2.Default = [-100, 0];
  function isDefault(score2) {
    return !score2 || score2.length === 2 && score2[0] === -100 && score2[1] === 0;
  }
  FuzzyScore2.isDefault = isDefault;
})(FuzzyScore || (FuzzyScore = {}));
var $Wl = class {
  static {
    this.default = { boostFullMatch: true, firstMatchCanBeWeak: false };
  }
  constructor(firstMatchCanBeWeak, boostFullMatch) {
    this.firstMatchCanBeWeak = firstMatchCanBeWeak;
    this.boostFullMatch = boostFullMatch;
  }
};
function $Xl(pattern, patternLow, patternStart, word, wordLow, wordStart, options3 = $Wl.default) {
  const patternLen = pattern.length > _maxLen ? _maxLen : pattern.length;
  const wordLen = word.length > _maxLen ? _maxLen : word.length;
  if (patternStart >= patternLen || wordStart >= wordLen || patternLen - patternStart > wordLen - wordStart) {
    return void 0;
  }
  if (!$Vl(patternLow, patternStart, patternLen, wordLow, wordStart, wordLen, true)) {
    return void 0;
  }
  _fillInMaxWordMatchPos(patternLen, wordLen, patternStart, wordStart, patternLow, wordLow);
  let row = 1;
  let column = 1;
  let patternPos = patternStart;
  let wordPos = wordStart;
  const hasStrongFirstMatch = [false];
  for (row = 1, patternPos = patternStart; patternPos < patternLen; row++, patternPos++) {
    const minWordMatchPos = _minWordMatchPos[patternPos];
    const maxWordMatchPos = _maxWordMatchPos[patternPos];
    const nextMaxWordMatchPos = patternPos + 1 < patternLen ? _maxWordMatchPos[patternPos + 1] : wordLen;
    for (column = minWordMatchPos - wordStart + 1, wordPos = minWordMatchPos; wordPos < nextMaxWordMatchPos; column++, wordPos++) {
      let score2 = Number.MIN_SAFE_INTEGER;
      let canComeDiag = false;
      if (wordPos <= maxWordMatchPos) {
        score2 = _doScore(pattern, patternLow, patternPos, patternStart, word, wordLow, wordPos, wordLen, wordStart, _diag[row - 1][column - 1] === 0, hasStrongFirstMatch);
      }
      let diagScore = 0;
      if (score2 !== Number.MAX_SAFE_INTEGER) {
        canComeDiag = true;
        diagScore = score2 + _table[row - 1][column - 1];
      }
      const canComeLeft = wordPos > minWordMatchPos;
      const leftScore = canComeLeft ? _table[row][column - 1] + (_diag[row][column - 1] > 0 ? -5 : 0) : 0;
      const canComeLeftLeft = wordPos > minWordMatchPos + 1 && _diag[row][column - 1] > 0;
      const leftLeftScore = canComeLeftLeft ? _table[row][column - 2] + (_diag[row][column - 2] > 0 ? -5 : 0) : 0;
      if (canComeLeftLeft && (!canComeLeft || leftLeftScore >= leftScore) && (!canComeDiag || leftLeftScore >= diagScore)) {
        _table[row][column] = leftLeftScore;
        _arrows[row][column] = 3;
        _diag[row][column] = 0;
      } else if (canComeLeft && (!canComeDiag || leftScore >= diagScore)) {
        _table[row][column] = leftScore;
        _arrows[row][column] = 2;
        _diag[row][column] = 0;
      } else if (canComeDiag) {
        _table[row][column] = diagScore;
        _arrows[row][column] = 1;
        _diag[row][column] = _diag[row - 1][column - 1] + 1;
      } else {
        throw new Error(`not possible`);
      }
    }
  }
  if (_debug) {
    printTables(pattern, patternStart, word, wordStart);
  }
  if (!hasStrongFirstMatch[0] && !options3.firstMatchCanBeWeak) {
    return void 0;
  }
  row--;
  column--;
  const result = [_table[row][column], wordStart];
  let backwardsDiagLength = 0;
  let maxMatchColumn = 0;
  while (row >= 1) {
    let diagColumn = column;
    do {
      const arrow = _arrows[row][diagColumn];
      if (arrow === 3) {
        diagColumn = diagColumn - 2;
      } else if (arrow === 2) {
        diagColumn = diagColumn - 1;
      } else {
        break;
      }
    } while (diagColumn >= 1);
    if (backwardsDiagLength > 1 && patternLow[patternStart + row - 1] === wordLow[wordStart + column - 1] && !isUpperCaseAtPos(diagColumn + wordStart - 1, word, wordLow) && backwardsDiagLength + 1 > _diag[row][diagColumn]) {
      diagColumn = column;
    }
    if (diagColumn === column) {
      backwardsDiagLength++;
    } else {
      backwardsDiagLength = 1;
    }
    if (!maxMatchColumn) {
      maxMatchColumn = diagColumn;
    }
    row--;
    column = diagColumn - 1;
    result.push(column);
  }
  if (wordLen - wordStart === patternLen && options3.boostFullMatch) {
    result[0] += 2;
  }
  const skippedCharsCount = maxMatchColumn - patternLen;
  result[0] -= skippedCharsCount;
  return result;
}
function _fillInMaxWordMatchPos(patternLen, wordLen, patternStart, wordStart, patternLow, wordLow) {
  let patternPos = patternLen - 1;
  let wordPos = wordLen - 1;
  while (patternPos >= patternStart && wordPos >= wordStart) {
    if (patternLow[patternPos] === wordLow[wordPos]) {
      _maxWordMatchPos[patternPos] = wordPos;
      patternPos--;
    }
    wordPos--;
  }
}
function _doScore(pattern, patternLow, patternPos, patternStart, word, wordLow, wordPos, wordLen, wordStart, newMatchStart, outFirstMatchStrong) {
  if (patternLow[patternPos] !== wordLow[wordPos]) {
    return Number.MIN_SAFE_INTEGER;
  }
  let score2 = 1;
  let isGapLocation = false;
  if (wordPos === patternPos - patternStart) {
    score2 = pattern[patternPos] === word[wordPos] ? 7 : 5;
  } else if (isUpperCaseAtPos(wordPos, word, wordLow) && (wordPos === 0 || !isUpperCaseAtPos(wordPos - 1, word, wordLow))) {
    score2 = pattern[patternPos] === word[wordPos] ? 7 : 5;
    isGapLocation = true;
  } else if (isSeparatorAtPos(wordLow, wordPos) && (wordPos === 0 || !isSeparatorAtPos(wordLow, wordPos - 1))) {
    score2 = 5;
  } else if (isSeparatorAtPos(wordLow, wordPos - 1) || isWhitespaceAtPos(wordLow, wordPos - 1)) {
    score2 = 5;
    isGapLocation = true;
  }
  if (score2 > 1 && patternPos === patternStart) {
    outFirstMatchStrong[0] = true;
  }
  if (!isGapLocation) {
    isGapLocation = isUpperCaseAtPos(wordPos, word, wordLow) || isSeparatorAtPos(wordLow, wordPos - 1) || isWhitespaceAtPos(wordLow, wordPos - 1);
  }
  if (patternPos === patternStart) {
    if (wordPos > wordStart) {
      score2 -= isGapLocation ? 3 : 5;
    }
  } else {
    if (newMatchStart) {
      score2 += isGapLocation ? 2 : 0;
    } else {
      score2 += isGapLocation ? 0 : 1;
    }
  }
  if (wordPos + 1 === wordLen) {
    score2 -= isGapLocation ? 3 : 5;
  }
  return score2;
}
function $Yl(pattern, lowPattern, patternPos, word, lowWord, wordPos, options3) {
  return fuzzyScoreWithPermutations(pattern, lowPattern, patternPos, word, lowWord, wordPos, true, options3);
}
function fuzzyScoreWithPermutations(pattern, lowPattern, patternPos, word, lowWord, wordPos, aggressive, options3) {
  let top2 = $Xl(pattern, lowPattern, patternPos, word, lowWord, wordPos, options3);
  if (top2 && !aggressive) {
    return top2;
  }
  if (pattern.length >= 3) {
    const tries = Math.min(7, pattern.length - 1);
    for (let movingPatternPos = patternPos + 1; movingPatternPos < tries; movingPatternPos++) {
      const newPattern = nextTypoPermutation(pattern, movingPatternPos);
      if (newPattern) {
        const candidate = $Xl(newPattern, newPattern.toLowerCase(), patternPos, word, lowWord, wordPos, options3);
        if (candidate) {
          candidate[0] -= 3;
          if (!top2 || candidate[0] > top2[0]) {
            top2 = candidate;
          }
        }
      }
    }
  }
  return top2;
}
function nextTypoPermutation(pattern, patternPos) {
  if (patternPos + 1 >= pattern.length) {
    return void 0;
  }
  const swap1 = pattern[patternPos];
  const swap2 = pattern[patternPos + 1];
  if (swap1 === swap2) {
    return void 0;
  }
  return pattern.slice(0, patternPos) + swap2 + swap1 + pattern.slice(patternPos + 2);
}

// out-build/vs/base/browser/ui/list/list.js
var ListDragOverEffectType;
(function(ListDragOverEffectType2) {
  ListDragOverEffectType2[ListDragOverEffectType2["Copy"] = 0] = "Copy";
  ListDragOverEffectType2[ListDragOverEffectType2["Move"] = 1] = "Move";
})(ListDragOverEffectType || (ListDragOverEffectType = {}));
var ListDragOverEffectPosition;
(function(ListDragOverEffectPosition2) {
  ListDragOverEffectPosition2["Over"] = "drop-target";
  ListDragOverEffectPosition2["Before"] = "drop-target-before";
  ListDragOverEffectPosition2["After"] = "drop-target-after";
})(ListDragOverEffectPosition || (ListDragOverEffectPosition = {}));
var $l1 = class extends Error {
  constructor(user, message) {
    super(`ListError [${user}] ${message}`);
  }
};
var $m1 = class {
  constructor() {
    this.c = /* @__PURE__ */ new WeakMap();
  }
  getHeight(element) {
    return this.c.get(element) ?? this.d(element);
  }
  setDynamicHeight(element, height) {
    if (height > 0) {
      this.c.set(element, height);
    }
  }
};

// out-build/vs/base/common/range.js
var Range2;
(function(Range5) {
  function intersect(one, other) {
    if (one.start >= other.end || other.start >= one.end) {
      return { start: 0, end: 0 };
    }
    const start = Math.max(one.start, other.start);
    const end = Math.min(one.end, other.end);
    if (end - start <= 0) {
      return { start: 0, end: 0 };
    }
    return { start, end };
  }
  Range5.intersect = intersect;
  function isEmpty(range) {
    return range.end - range.start <= 0;
  }
  Range5.isEmpty = isEmpty;
  function intersects4(one, other) {
    return !isEmpty(intersect(one, other));
  }
  Range5.intersects = intersects4;
  function relativeComplement2(one, other) {
    const result = [];
    const first = { start: one.start, end: Math.min(other.start, one.end) };
    const second = { start: Math.max(other.end, one.start), end: one.end };
    if (!isEmpty(first)) {
      result.push(first);
    }
    if (!isEmpty(second)) {
      result.push(second);
    }
    return result;
  }
  Range5.relativeComplement = relativeComplement2;
})(Range2 || (Range2 = {}));

// out-build/vs/base/browser/ui/list/rangeMap.js
function $b1(range, groups) {
  const result = [];
  for (const r2 of groups) {
    if (range.start >= r2.range.end) {
      continue;
    }
    if (range.end < r2.range.start) {
      break;
    }
    const intersection = Range2.intersect(range, r2.range);
    if (Range2.isEmpty(intersection)) {
      continue;
    }
    result.push({
      range: intersection,
      size: r2.size
    });
  }
  return result;
}
function $c1({ start, end }, much) {
  return { start: start + much, end: end + much };
}
function $d1(groups) {
  const result = [];
  let previousGroup = null;
  for (const group2 of groups) {
    const start = group2.range.start;
    const end = group2.range.end;
    const size = group2.size;
    if (previousGroup && size === previousGroup.size) {
      previousGroup.range.end = end;
      continue;
    }
    previousGroup = { range: { start, end }, size };
    result.push(previousGroup);
  }
  return result;
}
function concat2(...groups) {
  return $d1(groups.reduce((r2, g) => r2.concat(g), []));
}
var $e1 = class {
  get paddingTop() {
    return this.c;
  }
  set paddingTop(paddingTop) {
    this.b = this.b + paddingTop - this.c;
    this.c = paddingTop;
  }
  constructor(topPadding) {
    this.a = [];
    this.b = 0;
    this.c = 0;
    this.c = topPadding ?? 0;
    this.b = this.c;
  }
  splice(index, deleteCount, items = []) {
    const diff3 = items.length - deleteCount;
    const before = $b1({ start: 0, end: index }, this.a);
    const after = $b1({ start: index + deleteCount, end: Number.POSITIVE_INFINITY }, this.a).map((g) => ({ range: $c1(g.range, diff3), size: g.size }));
    const middle = items.map((item, i2) => ({
      range: { start: index + i2, end: index + i2 + 1 },
      size: item.size
    }));
    this.a = concat2(before, middle, after);
    this.b = this.c + this.a.reduce((t, g) => t + g.size * (g.range.end - g.range.start), 0);
  }
  /**
   * Returns the number of items in the range map.
   */
  get count() {
    const len = this.a.length;
    if (!len) {
      return 0;
    }
    return this.a[len - 1].range.end;
  }
  /**
   * Returns the sum of the sizes of all items in the range map.
   */
  get size() {
    return this.b;
  }
  /**
   * Returns the index of the item at the given position.
   */
  indexAt(position) {
    if (position < 0) {
      return -1;
    }
    if (position < this.c) {
      return 0;
    }
    let index = 0;
    let size = this.c;
    for (const group2 of this.a) {
      const count = group2.range.end - group2.range.start;
      const newSize = size + count * group2.size;
      if (position < newSize) {
        return index + Math.floor((position - size) / group2.size);
      }
      index += count;
      size = newSize;
    }
    return index;
  }
  /**
   * Returns the index of the item right after the item at the
   * index of the given position.
   */
  indexAfter(position) {
    return Math.min(this.indexAt(position) + 1, this.count);
  }
  /**
   * Returns the start position of the item at the given index.
   */
  positionAt(index) {
    if (index < 0) {
      return -1;
    }
    let position = 0;
    let count = 0;
    for (const group2 of this.a) {
      const groupCount = group2.range.end - group2.range.start;
      const newCount = count + groupCount;
      if (index < newCount) {
        return this.c + position + (index - count) * group2.size;
      }
      position += groupCount * group2.size;
      count = newCount;
    }
    return -1;
  }
};

// out-build/vs/base/browser/ui/list/rowCache.js
var $f1 = class {
  constructor(d) {
    this.d = d;
    this.a = /* @__PURE__ */ new Map();
    this.b = /* @__PURE__ */ new Set();
    this.c = false;
  }
  /**
   * Returns a row either by creating a new one or reusing
   * a previously released row which shares the same templateId.
   *
   * @returns A row and `isReusingConnectedDomNode` if the row's node is already in the dom in a stale position.
   */
  alloc(templateId) {
    let result = this.g(templateId).pop();
    let isStale = false;
    if (result) {
      isStale = this.b.has(result.domNode);
      if (isStale) {
        this.b.delete(result.domNode);
      }
    } else {
      const domNode = $(".monaco-list-row");
      const renderer = this.h(templateId);
      const templateData = renderer.renderTemplate(domNode);
      result = { domNode, templateId, templateData };
    }
    return { row: result, isReusingConnectedDomNode: isStale };
  }
  /**
   * Releases the row for eventual reuse.
   */
  release(row) {
    if (!row) {
      return;
    }
    this.e(row);
  }
  /**
   * Begin a set of changes that use the cache. This lets us skip work when a row is removed and then inserted again.
   */
  transact(makeChanges) {
    if (this.c) {
      throw new Error("Already in transaction");
    }
    this.c = true;
    try {
      makeChanges();
    } finally {
      for (const domNode of this.b) {
        this.f(domNode);
      }
      this.b.clear();
      this.c = false;
    }
  }
  e(row) {
    const { domNode, templateId } = row;
    if (domNode) {
      if (this.c) {
        this.b.add(domNode);
      } else {
        this.f(domNode);
      }
    }
    const cache2 = this.g(templateId);
    cache2.push(row);
  }
  f(domNode) {
    domNode.classList.remove("scrolling");
    domNode.remove();
  }
  g(templateId) {
    let result = this.a.get(templateId);
    if (!result) {
      result = [];
      this.a.set(templateId, result);
    }
    return result;
  }
  dispose() {
    this.a.forEach((cachedRows, templateId) => {
      for (const cachedRow of cachedRows) {
        const renderer = this.h(templateId);
        renderer.disposeTemplate(cachedRow.templateData);
        cachedRow.templateData = null;
      }
    });
    this.a.clear();
    this.b.clear();
  }
  h(templateId) {
    const renderer = this.d.get(templateId);
    if (!renderer) {
      throw new Error(`No renderer found for ${templateId}`);
    }
    return renderer;
  }
};

// out-build/vs/base/browser/ui/list/listView.js
var StaticDND = {
  CurrentDragAndDropData: void 0
};
var ListViewTargetSector;
(function(ListViewTargetSector2) {
  ListViewTargetSector2[ListViewTargetSector2["TOP"] = 0] = "TOP";
  ListViewTargetSector2[ListViewTargetSector2["CENTER_TOP"] = 1] = "CENTER_TOP";
  ListViewTargetSector2[ListViewTargetSector2["CENTER_BOTTOM"] = 2] = "CENTER_BOTTOM";
  ListViewTargetSector2[ListViewTargetSector2["BOTTOM"] = 3] = "BOTTOM";
})(ListViewTargetSector || (ListViewTargetSector = {}));
var DefaultOptions = {
  useShadows: true,
  verticalScrollMode: 1,
  setRowLineHeight: true,
  setRowHeight: true,
  supportDynamicHeights: false,
  dnd: {
    getDragElements(e) {
      return [e];
    },
    getDragURI() {
      return null;
    },
    onDragStart() {
    },
    onDragOver() {
      return false;
    },
    drop() {
    },
    dispose() {
    }
  },
  horizontalScrolling: false,
  transformOptimization: true,
  alwaysConsumeMouseWheel: true
};
var $g1 = class {
  get context() {
    return this.d;
  }
  set context(value) {
    this.d = value;
  }
  constructor(elements) {
    this.elements = elements;
  }
  update() {
  }
  getData() {
    return this.elements;
  }
};
var $h1 = class {
  constructor(elements) {
    this.elements = elements;
  }
  update() {
  }
  getData() {
    return this.elements;
  }
};
var $i1 = class {
  constructor() {
    this.types = [];
    this.files = [];
  }
  update(dataTransfer) {
    if (dataTransfer.types) {
      this.types.splice(0, this.types.length, ...dataTransfer.types);
    }
    if (dataTransfer.files) {
      this.files.splice(0, this.files.length);
      for (let i2 = 0; i2 < dataTransfer.files.length; i2++) {
        const file = dataTransfer.files.item(i2);
        if (file && (file.size || file.type)) {
          this.files.push(file);
        }
      }
    }
  }
  getData() {
    return {
      types: this.types,
      files: this.files
    };
  }
};
function equalsDragFeedback(f1, f2) {
  if (Array.isArray(f1) && Array.isArray(f2)) {
    return $zb(f1, f2);
  }
  return f1 === f2;
}
var ListViewAccessibilityProvider = class {
  constructor(accessibilityProvider) {
    if (accessibilityProvider?.getSetSize) {
      this.getSetSize = accessibilityProvider.getSetSize.bind(accessibilityProvider);
    } else {
      this.getSetSize = (e, i2, l) => l;
    }
    if (accessibilityProvider?.getPosInSet) {
      this.getPosInSet = accessibilityProvider.getPosInSet.bind(accessibilityProvider);
    } else {
      this.getPosInSet = (e, i2) => i2 + 1;
    }
    if (accessibilityProvider?.getRole) {
      this.getRole = accessibilityProvider.getRole.bind(accessibilityProvider);
    } else {
      this.getRole = (_) => "listitem";
    }
    if (accessibilityProvider?.isChecked) {
      this.isChecked = accessibilityProvider.isChecked.bind(accessibilityProvider);
    } else {
      this.isChecked = (_) => void 0;
    }
  }
};
var $j1 = class _$j1 {
  static {
    this.c = 0;
  }
  get contentHeight() {
    return this.g.size;
  }
  get contentWidth() {
    return this.E ?? 0;
  }
  get onDidScroll() {
    return this.q.onScroll;
  }
  get onWillScroll() {
    return this.q.onWillScroll;
  }
  get containerDomNode() {
    return this.o;
  }
  get scrollableElementDomNode() {
    return this.q.getDomNode();
  }
  get Q() {
    return this.P;
  }
  set Q(value) {
    if (value === this.P) {
      return;
    }
    if (value && this.B) {
      throw new Error("Horizontal scrolling and dynamic heights not supported simultaneously");
    }
    this.P = value;
    this.domNode.classList.toggle("horizontal-scrolling", this.P);
    if (this.P) {
      for (const item of this.d) {
        this.ab(item);
      }
      this.X();
      this.q.setScrollDimensions({ width: $yj(this.domNode) });
      this.o.style.width = `${Math.max(this.E || 0, this.n)}px`;
    } else {
      this.u.cancel();
      this.q.setScrollDimensions({ width: this.n, scrollWidth: this.n });
      this.o.style.width = "";
    }
  }
  constructor(container2, R, renderers, options3 = DefaultOptions) {
    this.R = R;
    this.domId = `list_id_${++_$j1.c}`;
    this.j = /* @__PURE__ */ new Map();
    this.n = 0;
    this.s = 0;
    this.t = null;
    this.u = new $Sh(50);
    this.v = false;
    this.x = $3c.None;
    this.y = 0;
    this.G = false;
    this.K = $3c.None;
    this.L = $3c.None;
    this.M = new $2c();
    this.N = new $ze();
    this.O = new $ze();
    this.onDidChangeContentHeight = Event2.latch(this.N.event, void 0, this.M);
    this.onDidChangeContentWidth = Event2.latch(this.O.event, void 0, this.M);
    this.P = false;
    if (options3.horizontalScrolling && options3.supportDynamicHeights) {
      throw new Error("Horizontal scrolling and dynamic heights not supported simultaneously");
    }
    this.d = [];
    this.f = 0;
    this.g = this.S(options3.paddingTop ?? 0);
    for (const renderer of renderers) {
      this.j.set(renderer.templateId, renderer);
    }
    this.h = this.M.add(new $f1(this.j));
    this.k = 0;
    this.m = 0;
    this.domNode = document.createElement("div");
    this.domNode.className = "monaco-list";
    this.domNode.classList.add(this.domId);
    this.domNode.tabIndex = 0;
    this.domNode.classList.toggle("mouse-support", typeof options3.mouseSupport === "boolean" ? options3.mouseSupport : true);
    this.P = options3.horizontalScrolling ?? DefaultOptions.horizontalScrolling;
    this.domNode.classList.toggle("horizontal-scrolling", this.P);
    this.C = typeof options3.paddingBottom === "undefined" ? 0 : options3.paddingBottom;
    this.D = new ListViewAccessibilityProvider(options3.accessibilityProvider);
    this.o = document.createElement("div");
    this.o.className = "monaco-list-rows";
    const transformOptimization = options3.transformOptimization ?? DefaultOptions.transformOptimization;
    if (transformOptimization) {
      this.o.style.transform = "translate3d(0px, 0px, 0px)";
      this.o.style.overflow = "hidden";
      this.o.style.contain = "strict";
    }
    this.M.add($mZ.addTarget(this.o));
    this.p = this.M.add(new $AD({
      forceIntegerValues: true,
      smoothScrollDuration: options3.smoothScrolling ?? false ? 125 : 0,
      scheduleAtNextAnimationFrame: (cb) => $jj(getWindow(this.domNode), cb)
    }));
    this.q = this.M.add(new $BZ(this.o, {
      alwaysConsumeMouseWheel: options3.alwaysConsumeMouseWheel ?? DefaultOptions.alwaysConsumeMouseWheel,
      horizontal: 1,
      vertical: options3.verticalScrollMode ?? DefaultOptions.verticalScrollMode,
      useShadows: options3.useShadows ?? DefaultOptions.useShadows,
      mouseWheelScrollSensitivity: options3.mouseWheelScrollSensitivity,
      fastScrollSensitivity: options3.fastScrollSensitivity,
      scrollByPage: options3.scrollByPage
    }, this.p));
    this.domNode.appendChild(this.q.getDomNode());
    container2.appendChild(this.domNode);
    this.q.onScroll(this.ib, this, this.M);
    this.M.add($_i(this.o, EventType.Change, (e) => this.jb(e)));
    this.M.add($_i(this.q.getDomNode(), "scroll", (e) => e.target.scrollTop = 0));
    this.M.add($_i(this.domNode, "dragover", (e) => this.lb(this.hb(e))));
    this.M.add($_i(this.domNode, "drop", (e) => this.nb(this.hb(e))));
    this.M.add($_i(this.domNode, "dragleave", (e) => this.mb(this.hb(e))));
    this.M.add($_i(this.domNode, "dragend", (e) => this.ob(e)));
    this.z = options3.setRowLineHeight ?? DefaultOptions.setRowLineHeight;
    this.A = options3.setRowHeight ?? DefaultOptions.setRowHeight;
    this.B = options3.supportDynamicHeights ?? DefaultOptions.supportDynamicHeights;
    this.F = options3.dnd ?? this.M.add(DefaultOptions.dnd);
    this.layout(options3.initialSize?.height, options3.initialSize?.width);
  }
  updateOptions(options3) {
    if (options3.paddingBottom !== void 0) {
      this.C = options3.paddingBottom;
      this.q.setScrollDimensions({ scrollHeight: this.scrollHeight });
    }
    if (options3.smoothScrolling !== void 0) {
      this.p.setSmoothScrollDuration(options3.smoothScrolling ? 125 : 0);
    }
    if (options3.horizontalScrolling !== void 0) {
      this.Q = options3.horizontalScrolling;
    }
    let scrollableOptions;
    if (options3.scrollByPage !== void 0) {
      scrollableOptions = { ...scrollableOptions ?? {}, scrollByPage: options3.scrollByPage };
    }
    if (options3.mouseWheelScrollSensitivity !== void 0) {
      scrollableOptions = { ...scrollableOptions ?? {}, mouseWheelScrollSensitivity: options3.mouseWheelScrollSensitivity };
    }
    if (options3.fastScrollSensitivity !== void 0) {
      scrollableOptions = { ...scrollableOptions ?? {}, fastScrollSensitivity: options3.fastScrollSensitivity };
    }
    if (scrollableOptions) {
      this.q.updateOptions(scrollableOptions);
    }
    if (options3.paddingTop !== void 0 && options3.paddingTop !== this.g.paddingTop) {
      const lastRenderRange = this.vb(this.k, this.m);
      const offset = options3.paddingTop - this.g.paddingTop;
      this.g.paddingTop = options3.paddingTop;
      this.Y(lastRenderRange, Math.max(0, this.k + offset), this.m, void 0, void 0, true);
      this.setScrollTop(this.k);
      this.V();
      if (this.B) {
        this.wb(this.k, this.m);
      }
    }
  }
  delegateScrollFromMouseWheelEvent(browserEvent) {
    this.q.delegateScrollFromMouseWheelEvent(browserEvent);
  }
  delegateVerticalScrollbarPointerDown(browserEvent) {
    this.q.delegateVerticalScrollbarPointerDown(browserEvent);
  }
  updateElementHeight(index, size, anchorIndex) {
    if (index < 0 || index >= this.d.length) {
      return;
    }
    const originalSize = this.d[index].size;
    if (typeof size === "undefined") {
      if (!this.B) {
        console.warn("Dynamic heights not supported", new Error().stack);
        return;
      }
      this.d[index].lastDynamicHeightWidth = void 0;
      size = originalSize + this.xb(index);
    }
    if (originalSize === size) {
      return;
    }
    const lastRenderRange = this.vb(this.k, this.m);
    let heightDiff2 = 0;
    if (index < lastRenderRange.start) {
      heightDiff2 = size - originalSize;
    } else {
      if (anchorIndex !== null && anchorIndex > index && anchorIndex < lastRenderRange.end) {
        heightDiff2 = size - originalSize;
      } else {
        heightDiff2 = 0;
      }
    }
    this.g.splice(index, 1, [{ size }]);
    this.d[index].size = size;
    this.Y(lastRenderRange, Math.max(0, this.k + heightDiff2), this.m, void 0, void 0, true);
    this.setScrollTop(this.k);
    this.V();
    if (this.B) {
      this.wb(this.k, this.m);
    }
  }
  S(paddingTop) {
    return new $e1(paddingTop);
  }
  splice(start, deleteCount, elements = []) {
    if (this.v) {
      throw new Error("Can't run recursive splices.");
    }
    this.v = true;
    try {
      return this.U(start, deleteCount, elements);
    } finally {
      this.v = false;
      this.N.fire(this.contentHeight);
    }
  }
  U(start, deleteCount, elements = []) {
    const previousRenderRange = this.vb(this.k, this.m);
    const deleteRange = { start, end: start + deleteCount };
    const removeRange = Range2.intersect(previousRenderRange, deleteRange);
    const rowsToDispose = /* @__PURE__ */ new Map();
    for (let i2 = removeRange.end - 1; i2 >= removeRange.start; i2--) {
      const item = this.d[i2];
      item.dragStartDisposable.dispose();
      item.checkedDisposable.dispose();
      if (item.row) {
        let rows = rowsToDispose.get(item.templateId);
        if (!rows) {
          rows = [];
          rowsToDispose.set(item.templateId, rows);
        }
        const renderer = this.j.get(item.templateId);
        if (renderer && renderer.disposeElement) {
          renderer.disposeElement(item.element, i2, item.row.templateData, item.size);
        }
        rows.unshift(item.row);
      }
      item.row = null;
      item.stale = true;
    }
    const previousRestRange = { start: start + deleteCount, end: this.d.length };
    const previousRenderedRestRange = Range2.intersect(previousRestRange, previousRenderRange);
    const previousUnrenderedRestRanges = Range2.relativeComplement(previousRestRange, previousRenderRange);
    const inserted = elements.map((element) => ({
      id: String(this.f++),
      element,
      templateId: this.R.getTemplateId(element),
      size: this.R.getHeight(element),
      width: void 0,
      hasDynamicHeight: !!this.R.hasDynamicHeight && this.R.hasDynamicHeight(element),
      lastDynamicHeightWidth: void 0,
      row: null,
      uri: void 0,
      dropTarget: false,
      dragStartDisposable: $3c.None,
      checkedDisposable: $3c.None,
      stale: false
    }));
    let deleted;
    if (start === 0 && deleteCount >= this.d.length) {
      this.g = this.S(this.g.paddingTop);
      this.g.splice(0, 0, inserted);
      deleted = this.d;
      this.d = inserted;
    } else {
      this.g.splice(start, deleteCount, inserted);
      deleted = this.d.splice(start, deleteCount, ...inserted);
    }
    const delta = elements.length - deleteCount;
    const renderRange = this.vb(this.k, this.m);
    const renderedRestRange = $c1(previousRenderedRestRange, delta);
    const updateRange = Range2.intersect(renderRange, renderedRestRange);
    for (let i2 = updateRange.start; i2 < updateRange.end; i2++) {
      this.bb(this.d[i2], i2);
    }
    const removeRanges = Range2.relativeComplement(renderedRestRange, renderRange);
    for (const range of removeRanges) {
      for (let i2 = range.start; i2 < range.end; i2++) {
        this.db(i2);
      }
    }
    const unrenderedRestRanges = previousUnrenderedRestRanges.map((r2) => $c1(r2, delta));
    const elementsRange = { start, end: start + elements.length };
    const insertRanges = [elementsRange, ...unrenderedRestRanges].map((r2) => Range2.intersect(renderRange, r2)).reverse();
    for (const range of insertRanges) {
      for (let i2 = range.end - 1; i2 >= range.start; i2--) {
        const item = this.d[i2];
        const rows = rowsToDispose.get(item.templateId);
        const row = rows?.pop();
        this.Z(i2, row);
      }
    }
    for (const rows of rowsToDispose.values()) {
      for (const row of rows) {
        this.h.release(row);
      }
    }
    this.V();
    if (this.B) {
      this.wb(this.scrollTop, this.renderHeight);
    }
    return deleted.map((i2) => i2.element);
  }
  V() {
    this.s = this.contentHeight;
    this.o.style.height = `${this.s}px`;
    if (!this.t) {
      this.t = $jj(getWindow(this.domNode), () => {
        this.q.setScrollDimensions({ scrollHeight: this.scrollHeight });
        this.X();
        this.t = null;
      });
    }
  }
  W() {
    if (!this.Q) {
      this.u.cancel();
      return;
    }
    this.u.trigger(() => this.X());
  }
  X() {
    if (!this.Q) {
      return;
    }
    let scrollWidth = 0;
    for (const item of this.d) {
      if (typeof item.width !== "undefined") {
        scrollWidth = Math.max(scrollWidth, item.width);
      }
    }
    this.E = scrollWidth;
    this.q.setScrollDimensions({ scrollWidth: scrollWidth === 0 ? 0 : scrollWidth + 10 });
    this.O.fire(this.E);
  }
  updateWidth(index) {
    if (!this.Q || typeof this.E === "undefined") {
      return;
    }
    const item = this.d[index];
    this.ab(item);
    if (typeof item.width !== "undefined" && item.width > this.E) {
      this.E = item.width;
      this.q.setScrollDimensions({ scrollWidth: this.E + 10 });
      this.O.fire(this.E);
    }
  }
  rerender() {
    if (!this.B) {
      return;
    }
    for (const item of this.d) {
      item.lastDynamicHeightWidth = void 0;
    }
    this.wb(this.k, this.m);
  }
  get length() {
    return this.d.length;
  }
  get renderHeight() {
    const scrollDimensions = this.q.getScrollDimensions();
    return scrollDimensions.height;
  }
  get firstVisibleIndex() {
    const range = this.vb(this.k, this.m);
    return range.start;
  }
  get firstMostlyVisibleIndex() {
    const firstVisibleIndex = this.firstVisibleIndex;
    const firstElTop = this.g.positionAt(firstVisibleIndex);
    const nextElTop = this.g.positionAt(firstVisibleIndex + 1);
    if (nextElTop !== -1) {
      const firstElMidpoint = (nextElTop - firstElTop) / 2 + firstElTop;
      if (firstElMidpoint < this.scrollTop) {
        return firstVisibleIndex + 1;
      }
    }
    return firstVisibleIndex;
  }
  get lastVisibleIndex() {
    const range = this.vb(this.k, this.m);
    return range.end - 1;
  }
  element(index) {
    return this.d[index].element;
  }
  indexOf(element) {
    return this.d.findIndex((item) => item.element === element);
  }
  domElement(index) {
    const row = this.d[index].row;
    return row && row.domNode;
  }
  elementHeight(index) {
    return this.d[index].size;
  }
  elementTop(index) {
    return this.g.positionAt(index);
  }
  indexAt(position) {
    return this.g.indexAt(position);
  }
  indexAfter(position) {
    return this.g.indexAfter(position);
  }
  layout(height, width2) {
    const scrollDimensions = {
      height: typeof height === "number" ? height : $Aj(this.domNode)
    };
    if (this.t) {
      this.t.dispose();
      this.t = null;
      scrollDimensions.scrollHeight = this.scrollHeight;
    }
    this.q.setScrollDimensions(scrollDimensions);
    if (typeof width2 !== "undefined") {
      this.n = width2;
      if (this.B) {
        this.wb(this.scrollTop, this.renderHeight);
      }
    }
    if (this.Q) {
      this.q.setScrollDimensions({
        width: typeof width2 === "number" ? width2 : $yj(this.domNode)
      });
    }
  }
  // Render
  Y(previousRenderRange, renderTop, renderHeight, renderLeft, scrollWidth, updateItemsInDOM = false) {
    const renderRange = this.vb(renderTop, renderHeight);
    const rangesToInsert = Range2.relativeComplement(renderRange, previousRenderRange).reverse();
    const rangesToRemove = Range2.relativeComplement(previousRenderRange, renderRange);
    if (updateItemsInDOM) {
      const rangesToUpdate = Range2.intersect(previousRenderRange, renderRange);
      for (let i2 = rangesToUpdate.start; i2 < rangesToUpdate.end; i2++) {
        this.bb(this.d[i2], i2);
      }
    }
    this.h.transact(() => {
      for (const range of rangesToRemove) {
        for (let i2 = range.start; i2 < range.end; i2++) {
          this.db(i2);
        }
      }
      for (const range of rangesToInsert) {
        for (let i2 = range.end - 1; i2 >= range.start; i2--) {
          this.Z(i2);
        }
      }
    });
    if (renderLeft !== void 0) {
      this.o.style.left = `-${renderLeft}px`;
    }
    this.o.style.top = `-${renderTop}px`;
    if (this.Q && scrollWidth !== void 0) {
      this.o.style.width = `${Math.max(scrollWidth, this.n)}px`;
    }
    this.k = renderTop;
    this.m = renderHeight;
  }
  // DOM operations
  Z(index, row) {
    const item = this.d[index];
    if (!item.row) {
      if (row) {
        item.row = row;
        item.stale = true;
      } else {
        const result = this.h.alloc(item.templateId);
        item.row = result.row;
        item.stale ||= result.isReusingConnectedDomNode;
      }
    }
    const role = this.D.getRole(item.element) || "listitem";
    item.row.domNode.setAttribute("role", role);
    const checked = this.D.isChecked(item.element);
    if (typeof checked === "boolean") {
      item.row.domNode.setAttribute("aria-checked", String(!!checked));
    } else if (checked) {
      const update = (checked2) => item.row.domNode.setAttribute("aria-checked", String(!!checked2));
      update(checked.value);
      item.checkedDisposable = checked.onDidChange(() => update(checked.value));
    }
    if (item.stale || !item.row.domNode.parentElement) {
      const referenceNode = this.d.at(index + 1)?.row?.domNode ?? null;
      if (item.row.domNode.parentElement !== this.o || item.row.domNode.nextElementSibling !== referenceNode) {
        this.o.insertBefore(item.row.domNode, referenceNode);
      }
      item.stale = false;
    }
    this.bb(item, index);
    const renderer = this.j.get(item.templateId);
    if (!renderer) {
      throw new Error(`No renderer found for template id ${item.templateId}`);
    }
    renderer?.renderElement(item.element, index, item.row.templateData, item.size);
    const uri = this.F.getDragURI(item.element);
    item.dragStartDisposable.dispose();
    item.row.domNode.draggable = !!uri;
    if (uri) {
      item.dragStartDisposable = $_i(item.row.domNode, "dragstart", (event) => this.kb(item.element, uri, event));
    }
    if (this.Q) {
      this.ab(item);
      this.W();
    }
  }
  ab(item) {
    if (!item.row || !item.row.domNode) {
      return;
    }
    item.row.domNode.style.width = "fit-content";
    item.width = $yj(item.row.domNode);
    const style = getWindow(item.row.domNode).getComputedStyle(item.row.domNode);
    if (style.paddingLeft) {
      item.width += parseFloat(style.paddingLeft);
    }
    if (style.paddingRight) {
      item.width += parseFloat(style.paddingRight);
    }
    item.row.domNode.style.width = "";
  }
  bb(item, index) {
    item.row.domNode.style.top = `${this.elementTop(index)}px`;
    if (this.A) {
      item.row.domNode.style.height = `${item.size}px`;
    }
    if (this.z) {
      item.row.domNode.style.lineHeight = `${item.size}px`;
    }
    item.row.domNode.setAttribute("data-index", `${index}`);
    item.row.domNode.setAttribute("data-last-element", index === this.length - 1 ? "true" : "false");
    item.row.domNode.setAttribute("data-parity", index % 2 === 0 ? "even" : "odd");
    item.row.domNode.setAttribute("aria-setsize", String(this.D.getSetSize(item.element, index, this.length)));
    item.row.domNode.setAttribute("aria-posinset", String(this.D.getPosInSet(item.element, index)));
    item.row.domNode.setAttribute("id", this.getElementDomId(index));
    item.row.domNode.classList.toggle("drop-target", item.dropTarget);
  }
  db(index) {
    const item = this.d[index];
    item.dragStartDisposable.dispose();
    item.checkedDisposable.dispose();
    if (item.row) {
      const renderer = this.j.get(item.templateId);
      if (renderer && renderer.disposeElement) {
        renderer.disposeElement(item.element, index, item.row.templateData, item.size);
      }
      this.h.release(item.row);
      item.row = null;
    }
    if (this.Q) {
      this.W();
    }
  }
  getScrollTop() {
    const scrollPosition = this.q.getScrollPosition();
    return scrollPosition.scrollTop;
  }
  setScrollTop(scrollTop, reuseAnimation) {
    if (this.t) {
      this.t.dispose();
      this.t = null;
      this.q.setScrollDimensions({ scrollHeight: this.scrollHeight });
    }
    this.q.setScrollPosition({ scrollTop, reuseAnimation });
  }
  getScrollLeft() {
    const scrollPosition = this.q.getScrollPosition();
    return scrollPosition.scrollLeft;
  }
  setScrollLeft(scrollLeft) {
    if (this.t) {
      this.t.dispose();
      this.t = null;
      this.q.setScrollDimensions({ scrollWidth: this.E });
    }
    this.q.setScrollPosition({ scrollLeft });
  }
  get scrollTop() {
    return this.getScrollTop();
  }
  set scrollTop(scrollTop) {
    this.setScrollTop(scrollTop);
  }
  get scrollHeight() {
    return this.s + (this.Q ? 10 : 0) + this.C;
  }
  // Events
  get onMouseClick() {
    return Event2.map(this.M.add(new $9Z(this.domNode, "click")).event, (e) => this.eb(e), this.M);
  }
  get onMouseDblClick() {
    return Event2.map(this.M.add(new $9Z(this.domNode, "dblclick")).event, (e) => this.eb(e), this.M);
  }
  get onMouseMiddleClick() {
    return Event2.filter(Event2.map(this.M.add(new $9Z(this.domNode, "auxclick")).event, (e) => this.eb(e), this.M), (e) => e.browserEvent.button === 1, this.M);
  }
  get onMouseUp() {
    return Event2.map(this.M.add(new $9Z(this.domNode, "mouseup")).event, (e) => this.eb(e), this.M);
  }
  get onMouseDown() {
    return Event2.map(this.M.add(new $9Z(this.domNode, "mousedown")).event, (e) => this.eb(e), this.M);
  }
  get onMouseOver() {
    return Event2.map(this.M.add(new $9Z(this.domNode, "mouseover")).event, (e) => this.eb(e), this.M);
  }
  get onMouseMove() {
    return Event2.map(this.M.add(new $9Z(this.domNode, "mousemove")).event, (e) => this.eb(e), this.M);
  }
  get onMouseOut() {
    return Event2.map(this.M.add(new $9Z(this.domNode, "mouseout")).event, (e) => this.eb(e), this.M);
  }
  get onContextMenu() {
    return Event2.any(Event2.map(this.M.add(new $9Z(this.domNode, "contextmenu")).event, (e) => this.eb(e), this.M), Event2.map(this.M.add(new $9Z(this.domNode, EventType.Contextmenu)).event, (e) => this.gb(e), this.M));
  }
  get onTouchStart() {
    return Event2.map(this.M.add(new $9Z(this.domNode, "touchstart")).event, (e) => this.fb(e), this.M);
  }
  get onTap() {
    return Event2.map(this.M.add(new $9Z(this.o, EventType.Tap)).event, (e) => this.gb(e), this.M);
  }
  eb(browserEvent) {
    const index = this.ub(browserEvent.target || null);
    const item = typeof index === "undefined" ? void 0 : this.d[index];
    const element = item && item.element;
    return { browserEvent, index, element };
  }
  fb(browserEvent) {
    const index = this.ub(browserEvent.target || null);
    const item = typeof index === "undefined" ? void 0 : this.d[index];
    const element = item && item.element;
    return { browserEvent, index, element };
  }
  gb(browserEvent) {
    const index = this.ub(browserEvent.initialTarget || null);
    const item = typeof index === "undefined" ? void 0 : this.d[index];
    const element = item && item.element;
    return { browserEvent, index, element };
  }
  hb(browserEvent) {
    const index = this.ub(browserEvent.target || null);
    const item = typeof index === "undefined" ? void 0 : this.d[index];
    const element = item && item.element;
    const sector = this.tb(browserEvent, index);
    return { browserEvent, index, element, sector };
  }
  ib(e) {
    try {
      const previousRenderRange = this.vb(this.k, this.m);
      this.Y(previousRenderRange, e.scrollTop, e.height, e.scrollLeft, e.scrollWidth);
      if (this.B) {
        this.wb(e.scrollTop, e.height, e.inSmoothScrolling);
      }
    } catch (err) {
      console.error("Got bad scroll event:", e);
      throw err;
    }
  }
  jb(event) {
    event.preventDefault();
    event.stopPropagation();
    this.scrollTop -= event.translationY;
  }
  // DND
  kb(element, uri, event) {
    if (!event.dataTransfer) {
      return;
    }
    const elements = this.F.getDragElements(element);
    event.dataTransfer.effectAllowed = "copyMove";
    event.dataTransfer.setData($kZ.TEXT, uri);
    if (event.dataTransfer.setDragImage) {
      let label3;
      if (this.F.getDragLabel) {
        label3 = this.F.getDragLabel(elements, event);
      }
      if (typeof label3 === "undefined") {
        label3 = String(elements.length);
      }
      const dragImage = $(".monaco-drag-image");
      dragImage.textContent = label3;
      const getDragImageContainer = (e) => {
        while (e && !e.classList.contains("monaco-workbench")) {
          e = e.parentElement;
        }
        return e || this.domNode.ownerDocument;
      };
      const container2 = getDragImageContainer(this.domNode);
      container2.appendChild(dragImage);
      event.dataTransfer.setDragImage(dragImage, -10, -10);
      setTimeout(() => dragImage.remove(), 0);
    }
    this.domNode.classList.add("dragging");
    this.H = new $g1(elements);
    StaticDND.CurrentDragAndDropData = new $h1(elements);
    this.F.onDragStart?.(this.H, event);
  }
  lb(event) {
    event.browserEvent.preventDefault();
    this.L.dispose();
    if (StaticDND.CurrentDragAndDropData && StaticDND.CurrentDragAndDropData.getData() === "vscode-ui") {
      return false;
    }
    this.qb(event.browserEvent);
    if (!event.browserEvent.dataTransfer) {
      return false;
    }
    if (!this.H) {
      if (StaticDND.CurrentDragAndDropData) {
        this.H = StaticDND.CurrentDragAndDropData;
      } else {
        if (!event.browserEvent.dataTransfer.types) {
          return false;
        }
        this.H = new $i1();
      }
    }
    const result = this.F.onDragOver(this.H, event.element, event.index, event.sector, event.browserEvent);
    this.G = typeof result === "boolean" ? result : result.accept;
    if (!this.G) {
      this.I = void 0;
      this.K.dispose();
      return false;
    }
    event.browserEvent.dataTransfer.dropEffect = typeof result !== "boolean" && result.effect?.type === 0 ? "copy" : "move";
    let feedback;
    if (typeof result !== "boolean" && result.feedback) {
      feedback = result.feedback;
    } else {
      if (typeof event.index === "undefined") {
        feedback = [-1];
      } else {
        feedback = [event.index];
      }
    }
    feedback = $Rb(feedback).filter((i2) => i2 >= -1 && i2 < this.length).sort((a, b) => a - b);
    feedback = feedback[0] === -1 ? [-1] : feedback;
    let dragOverEffectPosition = typeof result !== "boolean" && result.effect && result.effect.position ? result.effect.position : "drop-target";
    if (equalsDragFeedback(this.I, feedback) && this.J === dragOverEffectPosition) {
      return true;
    }
    this.I = feedback;
    this.J = dragOverEffectPosition;
    this.K.dispose();
    if (feedback[0] === -1) {
      this.domNode.classList.add(dragOverEffectPosition);
      this.o.classList.add(dragOverEffectPosition);
      this.K = $1c(() => {
        this.domNode.classList.remove(dragOverEffectPosition);
        this.o.classList.remove(dragOverEffectPosition);
      });
    } else {
      if (feedback.length > 1 && dragOverEffectPosition !== "drop-target") {
        throw new Error("Can't use multiple feedbacks with position different than 'over'");
      }
      if (dragOverEffectPosition === "drop-target-after") {
        if (feedback[0] < this.length - 1) {
          feedback[0] += 1;
          dragOverEffectPosition = "drop-target-before";
        }
      }
      for (const index of feedback) {
        const item = this.d[index];
        item.dropTarget = true;
        item.row?.domNode.classList.add(dragOverEffectPosition);
      }
      this.K = $1c(() => {
        for (const index of feedback) {
          const item = this.d[index];
          item.dropTarget = false;
          item.row?.domNode.classList.remove(dragOverEffectPosition);
        }
      });
    }
    return true;
  }
  mb(event) {
    this.L.dispose();
    this.L = $Xh(() => this.pb(), 100, this.M);
    if (this.H) {
      this.F.onDragLeave?.(this.H, event.element, event.index, event.browserEvent);
    }
  }
  nb(event) {
    if (!this.G) {
      return;
    }
    const dragData = this.H;
    this.sb();
    this.pb();
    this.domNode.classList.remove("dragging");
    this.H = void 0;
    StaticDND.CurrentDragAndDropData = void 0;
    if (!dragData || !event.browserEvent.dataTransfer) {
      return;
    }
    event.browserEvent.preventDefault();
    dragData.update(event.browserEvent.dataTransfer);
    this.F.drop(dragData, event.element, event.index, event.sector, event.browserEvent);
  }
  ob(event) {
    this.G = false;
    this.sb();
    this.pb();
    this.domNode.classList.remove("dragging");
    this.H = void 0;
    StaticDND.CurrentDragAndDropData = void 0;
    this.F.onDragEnd?.(event);
  }
  pb() {
    this.I = void 0;
    this.J = void 0;
    this.K.dispose();
    this.K = $3c.None;
  }
  // DND scroll top animation
  qb(event) {
    if (!this.w) {
      const viewTop = $sj(this.domNode).top;
      this.w = $qk(getWindow(this.domNode), this.rb.bind(this, viewTop));
    }
    this.x.dispose();
    this.x = $Xh(() => {
      if (this.w) {
        this.w.dispose();
        this.w = void 0;
      }
    }, 1e3, this.M);
    this.y = event.pageY;
  }
  rb(viewTop) {
    if (this.y === void 0) {
      return;
    }
    const diff3 = this.y - viewTop;
    const upperLimit = this.renderHeight - 35;
    if (diff3 < 35) {
      this.scrollTop += Math.max(-14, Math.floor(0.3 * (diff3 - 35)));
    } else if (diff3 > upperLimit) {
      this.scrollTop += Math.min(14, Math.floor(0.3 * (diff3 - upperLimit)));
    }
  }
  sb() {
    this.x.dispose();
    if (this.w) {
      this.w.dispose();
      this.w = void 0;
    }
  }
  // Util
  tb(browserEvent, targetIndex) {
    if (targetIndex === void 0) {
      return void 0;
    }
    const relativePosition = browserEvent.offsetY / this.d[targetIndex].size;
    const sector = Math.floor(relativePosition / 0.25);
    return $4i(sector, 0, 3);
  }
  ub(target) {
    const scrollableElement = this.q.getDomNode();
    let element = target;
    while (($Uj(element) || $2j(element)) && element !== this.o && scrollableElement.contains(element)) {
      const rawIndex = element.getAttribute("data-index");
      if (rawIndex) {
        const index = Number(rawIndex);
        if (!isNaN(index)) {
          return index;
        }
      }
      element = element.parentElement;
    }
    return void 0;
  }
  vb(renderTop, renderHeight) {
    return {
      start: this.g.indexAt(renderTop),
      end: this.g.indexAfter(renderTop + renderHeight - 1)
    };
  }
  /**
   * Given a stable rendered state, checks every rendered element whether it needs
   * to be probed for dynamic height. Adjusts scroll height and top if necessary.
   */
  wb(renderTop, renderHeight, inSmoothScrolling) {
    const previousRenderRange = this.vb(renderTop, renderHeight);
    let anchorElementIndex;
    let anchorElementTopDelta;
    if (renderTop === this.elementTop(previousRenderRange.start)) {
      anchorElementIndex = previousRenderRange.start;
      anchorElementTopDelta = 0;
    } else if (previousRenderRange.end - previousRenderRange.start > 1) {
      anchorElementIndex = previousRenderRange.start + 1;
      anchorElementTopDelta = this.elementTop(anchorElementIndex) - renderTop;
    }
    let heightDiff2 = 0;
    while (true) {
      const renderRange = this.vb(renderTop, renderHeight);
      let didChange = false;
      for (let i2 = renderRange.start; i2 < renderRange.end; i2++) {
        const diff3 = this.xb(i2);
        if (diff3 !== 0) {
          this.g.splice(i2, 1, [this.d[i2]]);
        }
        heightDiff2 += diff3;
        didChange = didChange || diff3 !== 0;
      }
      if (!didChange) {
        if (heightDiff2 !== 0) {
          this.V();
        }
        const unrenderRanges = Range2.relativeComplement(previousRenderRange, renderRange);
        for (const range of unrenderRanges) {
          for (let i2 = range.start; i2 < range.end; i2++) {
            if (this.d[i2].row) {
              this.db(i2);
            }
          }
        }
        const renderRanges = Range2.relativeComplement(renderRange, previousRenderRange).reverse();
        for (const range of renderRanges) {
          for (let i2 = range.end - 1; i2 >= range.start; i2--) {
            this.Z(i2);
          }
        }
        for (let i2 = renderRange.start; i2 < renderRange.end; i2++) {
          if (this.d[i2].row) {
            this.bb(this.d[i2], i2);
          }
        }
        if (typeof anchorElementIndex === "number") {
          const deltaScrollTop = this.p.getFutureScrollPosition().scrollTop - renderTop;
          const newScrollTop = this.elementTop(anchorElementIndex) - anchorElementTopDelta + deltaScrollTop;
          this.setScrollTop(newScrollTop, inSmoothScrolling);
        }
        this.N.fire(this.contentHeight);
        return;
      }
    }
  }
  xb(index) {
    const item = this.d[index];
    if (!!this.R.getDynamicHeight) {
      const newSize = this.R.getDynamicHeight(item.element);
      if (newSize !== null) {
        const size2 = item.size;
        item.size = newSize;
        item.lastDynamicHeightWidth = this.n;
        return newSize - size2;
      }
    }
    if (!item.hasDynamicHeight || item.lastDynamicHeightWidth === this.n) {
      return 0;
    }
    if (!!this.R.hasDynamicHeight && !this.R.hasDynamicHeight(item.element)) {
      return 0;
    }
    const size = item.size;
    if (item.row) {
      item.row.domNode.style.height = "";
      item.size = item.row.domNode.offsetHeight;
      if (item.size === 0 && !$Dj(item.row.domNode, getWindow(item.row.domNode).document.body)) {
        console.warn("Measuring item node that is not in DOM! Add ListView to the DOM before measuring row height!", new Error().stack);
      }
      item.lastDynamicHeightWidth = this.n;
      return item.size - size;
    }
    const { row } = this.h.alloc(item.templateId);
    row.domNode.style.height = "";
    this.o.appendChild(row.domNode);
    const renderer = this.j.get(item.templateId);
    if (!renderer) {
      throw new $vb("Missing renderer for templateId: " + item.templateId);
    }
    renderer.renderElement(item.element, index, row.templateData, void 0);
    item.size = row.domNode.offsetHeight;
    renderer.disposeElement?.(item.element, index, row.templateData, void 0);
    this.R.setDynamicHeight?.(item.element, item.size);
    item.lastDynamicHeightWidth = this.n;
    row.domNode.remove();
    this.h.release(row);
    return item.size - size;
  }
  getElementDomId(index) {
    return `${this.domId}_${index}`;
  }
  // Dispose
  dispose() {
    for (const item of this.d) {
      item.dragStartDisposable.dispose();
      item.checkedDisposable.dispose();
      if (item.row) {
        const renderer = this.j.get(item.row.templateId);
        if (renderer) {
          renderer.disposeElement?.(item.element, -1, item.row.templateData, void 0);
          renderer.disposeTemplate(item.row.templateData);
        }
      }
    }
    this.d = [];
    this.domNode?.remove();
    this.w?.dispose();
    this.M.dispose();
  }
};
__decorate([
  $0t
], $j1.prototype, "onMouseClick", null);
__decorate([
  $0t
], $j1.prototype, "onMouseDblClick", null);
__decorate([
  $0t
], $j1.prototype, "onMouseMiddleClick", null);
__decorate([
  $0t
], $j1.prototype, "onMouseUp", null);
__decorate([
  $0t
], $j1.prototype, "onMouseDown", null);
__decorate([
  $0t
], $j1.prototype, "onMouseOver", null);
__decorate([
  $0t
], $j1.prototype, "onMouseMove", null);
__decorate([
  $0t
], $j1.prototype, "onMouseOut", null);
__decorate([
  $0t
], $j1.prototype, "onContextMenu", null);
__decorate([
  $0t
], $j1.prototype, "onTouchStart", null);
__decorate([
  $0t
], $j1.prototype, "onTap", null);

// out-build/vs/base/browser/ui/list/listWidget.js
var TraitRenderer = class {
  constructor(d) {
    this.d = d;
    this.c = [];
  }
  get templateId() {
    return `template:${this.d.name}`;
  }
  renderTemplate(container2) {
    return container2;
  }
  renderElement(element, index, templateData) {
    const renderedElementIndex = this.c.findIndex((el) => el.templateData === templateData);
    if (renderedElementIndex >= 0) {
      const rendered = this.c[renderedElementIndex];
      this.d.unrender(templateData);
      rendered.index = index;
    } else {
      const rendered = { index, templateData };
      this.c.push(rendered);
    }
    this.d.renderIndex(index, templateData);
  }
  splice(start, deleteCount, insertCount) {
    const rendered = [];
    for (const renderedElement of this.c) {
      if (renderedElement.index < start) {
        rendered.push(renderedElement);
      } else if (renderedElement.index >= start + deleteCount) {
        rendered.push({
          index: renderedElement.index + insertCount - deleteCount,
          templateData: renderedElement.templateData
        });
      }
    }
    this.c = rendered;
  }
  renderIndexes(indexes) {
    for (const { index, templateData } of this.c) {
      if (indexes.indexOf(index) > -1) {
        this.d.renderIndex(index, templateData);
      }
    }
  }
  disposeTemplate(templateData) {
    const index = this.c.findIndex((el) => el.templateData === templateData);
    if (index < 0) {
      return;
    }
    this.c.splice(index, 1);
  }
};
var Trait = class {
  get name() {
    return this.g;
  }
  get renderer() {
    return new TraitRenderer(this);
  }
  constructor(g) {
    this.g = g;
    this.c = [];
    this.d = [];
    this.f = new $ze();
    this.onChange = this.f.event;
  }
  splice(start, deleteCount, elements) {
    const diff3 = elements.length - deleteCount;
    const end = start + deleteCount;
    const sortedIndexes = [];
    let i2 = 0;
    while (i2 < this.d.length && this.d[i2] < start) {
      sortedIndexes.push(this.d[i2++]);
    }
    for (let j = 0; j < elements.length; j++) {
      if (elements[j]) {
        sortedIndexes.push(j + start);
      }
    }
    while (i2 < this.d.length && this.d[i2] >= end) {
      sortedIndexes.push(this.d[i2++] + diff3);
    }
    this.renderer.splice(start, deleteCount, elements.length);
    this.h(sortedIndexes, sortedIndexes);
  }
  renderIndex(index, container2) {
    container2.classList.toggle(this.g, this.contains(index));
  }
  unrender(container2) {
    container2.classList.remove(this.g);
  }
  /**
   * Sets the indexes which should have this trait.
   *
   * @param indexes Indexes which should have this trait.
   * @return The old indexes which had this trait.
   */
  set(indexes, browserEvent) {
    return this.h(indexes, [...indexes].sort(numericSort), browserEvent);
  }
  h(indexes, sortedIndexes, browserEvent) {
    const result = this.c;
    const sortedResult = this.d;
    this.c = indexes;
    this.d = sortedIndexes;
    const toRender = disjunction(sortedResult, indexes);
    this.renderer.renderIndexes(toRender);
    this.f.fire({ indexes, browserEvent });
    return result;
  }
  get() {
    return this.c;
  }
  contains(index) {
    return $Bb(this.d, index, numericSort) >= 0;
  }
  dispose() {
    $Xc(this.f);
  }
};
__decorate([
  $0t
], Trait.prototype, "renderer", null);
var SelectionTrait = class extends Trait {
  constructor(k) {
    super("selected");
    this.k = k;
  }
  renderIndex(index, container2) {
    super.renderIndex(index, container2);
    if (this.k) {
      if (this.contains(index)) {
        container2.setAttribute("aria-selected", "true");
      } else {
        container2.setAttribute("aria-selected", "false");
      }
    }
  }
};
var TraitSpliceable = class {
  constructor(c, d, f) {
    this.c = c;
    this.d = d;
    this.f = f;
  }
  splice(start, deleteCount, elements) {
    if (!this.f) {
      return this.c.splice(start, deleteCount, new Array(elements.length).fill(false));
    }
    const pastElementsWithTrait = this.c.get().map((i2) => this.f.getId(this.d.element(i2)).toString());
    if (pastElementsWithTrait.length === 0) {
      return this.c.splice(start, deleteCount, new Array(elements.length).fill(false));
    }
    const pastElementsWithTraitSet = new Set(pastElementsWithTrait);
    const elementsWithTrait = elements.map((e) => pastElementsWithTraitSet.has(this.f.getId(e).toString()));
    this.c.splice(start, deleteCount, elementsWithTrait);
  }
};
function isListElementDescendantOfClass(e, className) {
  if (e.classList.contains(className)) {
    return true;
  }
  if (e.classList.contains("monaco-list")) {
    return false;
  }
  if (!e.parentElement) {
    return false;
  }
  return isListElementDescendantOfClass(e.parentElement, className);
}
function $n1(e) {
  return isListElementDescendantOfClass(e, "monaco-editor");
}
function $o1(e) {
  return isListElementDescendantOfClass(e, "monaco-custom-toggle");
}
function $p1(e) {
  return isListElementDescendantOfClass(e, "action-item");
}
function $r1(e) {
  return isListElementDescendantOfClass(e, "monaco-tree-sticky-row");
}
function $s1(e) {
  return e.classList.contains("monaco-tree-sticky-container");
}
function $t1(e) {
  if (e.tagName === "A" && e.classList.contains("monaco-button") || e.tagName === "DIV" && e.classList.contains("monaco-button-dropdown")) {
    return true;
  }
  if (e.classList.contains("monaco-list")) {
    return false;
  }
  if (!e.parentElement) {
    return false;
  }
  return $t1(e.parentElement);
}
var KeyboardController = class {
  get g() {
    return Event2.chain(this.c.add(new $9Z(this.k.domNode, "keydown")).event, ($149) => $149.filter((e) => !$Fk(e.target)).map((e) => new $if(e)));
  }
  constructor(h3, k, options3) {
    this.h = h3;
    this.k = k;
    this.c = new $2c();
    this.d = new $2c();
    this.f = options3.multipleSelectionSupport;
    this.c.add(this.g((e) => {
      switch (e.keyCode) {
        case 3:
          return this.l(e);
        case 16:
          return this.o(e);
        case 18:
          return this.p(e);
        case 11:
          return this.q(e);
        case 12:
          return this.s(e);
        case 9:
          return this.u(e);
        case 31:
          if (this.f && ($m ? e.metaKey : e.ctrlKey)) {
            this.t(e);
          }
      }
    }));
  }
  updateOptions(optionsUpdate) {
    if (optionsUpdate.multipleSelectionSupport !== void 0) {
      this.f = optionsUpdate.multipleSelectionSupport;
    }
  }
  l(e) {
    e.preventDefault();
    e.stopPropagation();
    this.h.setSelection(this.h.getFocus(), e.browserEvent);
  }
  o(e) {
    e.preventDefault();
    e.stopPropagation();
    this.h.focusPrevious(1, false, e.browserEvent);
    const el = this.h.getFocus()[0];
    this.h.setAnchor(el);
    this.h.reveal(el);
    this.k.domNode.focus();
  }
  p(e) {
    e.preventDefault();
    e.stopPropagation();
    this.h.focusNext(1, false, e.browserEvent);
    const el = this.h.getFocus()[0];
    this.h.setAnchor(el);
    this.h.reveal(el);
    this.k.domNode.focus();
  }
  q(e) {
    e.preventDefault();
    e.stopPropagation();
    this.h.focusPreviousPage(e.browserEvent);
    const el = this.h.getFocus()[0];
    this.h.setAnchor(el);
    this.h.reveal(el);
    this.k.domNode.focus();
  }
  s(e) {
    e.preventDefault();
    e.stopPropagation();
    this.h.focusNextPage(e.browserEvent);
    const el = this.h.getFocus()[0];
    this.h.setAnchor(el);
    this.h.reveal(el);
    this.k.domNode.focus();
  }
  t(e) {
    e.preventDefault();
    e.stopPropagation();
    this.h.setSelection($Ub(this.h.length), e.browserEvent);
    this.h.setAnchor(void 0);
    this.k.domNode.focus();
  }
  u(e) {
    if (this.h.getSelection().length) {
      e.preventDefault();
      e.stopPropagation();
      this.h.setSelection([], e.browserEvent);
      this.h.setAnchor(void 0);
      this.k.domNode.focus();
    }
  }
  dispose() {
    this.c.dispose();
    this.d.dispose();
  }
};
__decorate([
  $0t
], KeyboardController.prototype, "g", null);
var TypeNavigationMode;
(function(TypeNavigationMode2) {
  TypeNavigationMode2[TypeNavigationMode2["Automatic"] = 0] = "Automatic";
  TypeNavigationMode2[TypeNavigationMode2["Trigger"] = 1] = "Trigger";
})(TypeNavigationMode || (TypeNavigationMode = {}));
var TypeNavigationControllerState;
(function(TypeNavigationControllerState2) {
  TypeNavigationControllerState2[TypeNavigationControllerState2["Idle"] = 0] = "Idle";
  TypeNavigationControllerState2[TypeNavigationControllerState2["Typing"] = 1] = "Typing";
})(TypeNavigationControllerState || (TypeNavigationControllerState = {}));
var $u1 = new class {
  mightProducePrintableCharacter(event) {
    if (event.ctrlKey || event.metaKey || event.altKey) {
      return false;
    }
    return event.keyCode >= 31 && event.keyCode <= 56 || event.keyCode >= 21 && event.keyCode <= 30 || event.keyCode >= 98 && event.keyCode <= 107 || event.keyCode >= 85 && event.keyCode <= 95;
  }
}();
var TypeNavigationController = class {
  constructor(o, p, q, s, t) {
    this.o = o;
    this.p = p;
    this.q = q;
    this.s = s;
    this.t = t;
    this.c = false;
    this.d = TypeNavigationControllerState.Idle;
    this.f = TypeNavigationMode.Automatic;
    this.g = false;
    this.h = -1;
    this.k = new $2c();
    this.l = new $2c();
    this.updateOptions(o.options);
  }
  updateOptions(options3) {
    if (options3.typeNavigationEnabled ?? true) {
      this.u();
    } else {
      this.v();
    }
    this.f = options3.typeNavigationMode ?? TypeNavigationMode.Automatic;
  }
  trigger() {
    this.g = !this.g;
  }
  u() {
    if (this.c) {
      return;
    }
    let typing = false;
    const onChar = Event2.chain(this.k.add(new $9Z(this.p.domNode, "keydown")).event, ($149) => $149.filter((e) => !$Fk(e.target)).filter(() => this.f === TypeNavigationMode.Automatic || this.g).map((event) => new $if(event)).filter((e) => typing || this.s(e)).filter((e) => this.t.mightProducePrintableCharacter(e)).forEach((e) => $9j.stop(e, true)).map((event) => event.browserEvent.key));
    const onClear = Event2.debounce(onChar, () => null, 800, void 0, void 0, void 0, this.k);
    const onInput = Event2.reduce(Event2.any(onChar, onClear), (r2, i2) => i2 === null ? null : (r2 || "") + i2, void 0, this.k);
    onInput(this.x, this, this.k);
    onClear(this.w, this, this.k);
    onChar(() => typing = true, void 0, this.k);
    onClear(() => typing = false, void 0, this.k);
    this.c = true;
    this.g = false;
  }
  v() {
    if (!this.c) {
      return;
    }
    this.k.clear();
    this.c = false;
    this.g = false;
  }
  w() {
    const focus = this.o.getFocus();
    if (focus.length > 0 && focus[0] === this.h) {
      const ariaLabel = this.o.options.accessibilityProvider?.getAriaLabel(this.o.element(focus[0]));
      if (typeof ariaLabel === "string") {
        $$Z(ariaLabel);
      } else if (ariaLabel) {
        $$Z(ariaLabel.get());
      }
    }
    this.h = -1;
  }
  x(word) {
    if (!word) {
      this.d = TypeNavigationControllerState.Idle;
      this.g = false;
      return;
    }
    const focus = this.o.getFocus();
    const start = focus.length > 0 ? focus[0] : 0;
    const delta = this.d === TypeNavigationControllerState.Idle ? 1 : 0;
    this.d = TypeNavigationControllerState.Typing;
    for (let i2 = 0; i2 < this.o.length; i2++) {
      const index = (start + i2 + delta) % this.o.length;
      const label3 = this.q.getKeyboardNavigationLabel(this.p.element(index));
      const labelStr = label3 && label3.toString();
      if (this.o.options.typeNavigationEnabled) {
        if (typeof labelStr !== "undefined") {
          if ($Ll(word, labelStr)) {
            this.h = start;
            this.o.setFocus([index]);
            this.o.reveal(index);
            return;
          }
          const fuzzy = $Sl(word, labelStr);
          if (fuzzy) {
            const fuzzyScore = fuzzy[0].end - fuzzy[0].start;
            if (fuzzyScore > 1 && fuzzy.length === 1) {
              this.h = start;
              this.o.setFocus([index]);
              this.o.reveal(index);
              return;
            }
          }
        }
      } else if (typeof labelStr === "undefined" || $Ll(word, labelStr)) {
        this.h = start;
        this.o.setFocus([index]);
        this.o.reveal(index);
        return;
      }
    }
  }
  dispose() {
    this.v();
    this.k.dispose();
    this.l.dispose();
  }
};
var DOMFocusController = class {
  constructor(d, f) {
    this.d = d;
    this.f = f;
    this.c = new $2c();
    const onKeyDown = Event2.chain(this.c.add(new $9Z(f.domNode, "keydown")).event, ($149) => $149.filter((e) => !$Fk(e.target)).map((e) => new $if(e)));
    const onTab = Event2.chain(onKeyDown, ($149) => $149.filter((e) => e.keyCode === 2 && !e.ctrlKey && !e.metaKey && !e.shiftKey && !e.altKey));
    onTab(this.g, this, this.c);
  }
  g(e) {
    if (e.target !== this.f.domNode) {
      return;
    }
    const focus = this.d.getFocus();
    if (focus.length === 0) {
      return;
    }
    const focusedDomElement = this.f.domElement(focus[0]);
    if (!focusedDomElement) {
      return;
    }
    const tabIndexElement = focusedDomElement.querySelector("[tabIndex]");
    if (!tabIndexElement || !$Uj(tabIndexElement) || tabIndexElement.tabIndex === -1) {
      return;
    }
    const style = getWindow(tabIndexElement).getComputedStyle(tabIndexElement);
    if (style.visibility === "hidden" || style.display === "none") {
      return;
    }
    e.preventDefault();
    e.stopPropagation();
    tabIndexElement.focus();
  }
  dispose() {
    this.c.dispose();
  }
};
function $v1(event) {
  return $m ? event.browserEvent.metaKey : event.browserEvent.ctrlKey;
}
function $w1(event) {
  return event.browserEvent.shiftKey;
}
function isMouseRightClick(event) {
  return $3j(event) && event.button === 2;
}
var DefaultMultipleSelectionController = {
  isSelectionSingleChangeEvent: $v1,
  isSelectionRangeChangeEvent: $w1
};
var $x1 = class {
  constructor(o) {
    this.o = o;
    this.g = new $2c();
    this.k = new $ze();
    this.onPointer = this.k.event;
    if (o.options.multipleSelectionSupport !== false) {
      this.d = this.o.options.multipleSelectionController || DefaultMultipleSelectionController;
    }
    this.f = typeof o.options.mouseSupport === "undefined" || !!o.options.mouseSupport;
    if (this.f) {
      o.onMouseDown(this.t, this, this.g);
      o.onContextMenu(this.u, this, this.g);
      o.onMouseDblClick(this.w, this, this.g);
      o.onTouchStart(this.t, this, this.g);
      this.g.add($mZ.addTarget(o.getHTMLElement()));
    }
    Event2.any(o.onMouseClick, o.onMouseMiddleClick, o.onTap)(this.v, this, this.g);
  }
  updateOptions(optionsUpdate) {
    if (optionsUpdate.multipleSelectionSupport !== void 0) {
      this.d = void 0;
      if (optionsUpdate.multipleSelectionSupport) {
        this.d = this.o.options.multipleSelectionController || DefaultMultipleSelectionController;
      }
    }
  }
  p(event) {
    if (!this.d) {
      return false;
    }
    return this.d.isSelectionSingleChangeEvent(event);
  }
  q(event) {
    if (!this.d) {
      return false;
    }
    return this.d.isSelectionRangeChangeEvent(event);
  }
  s(event) {
    return this.p(event) || this.q(event);
  }
  t(e) {
    if ($n1(e.browserEvent.target)) {
      return;
    }
    if ($Lj() !== e.browserEvent.target) {
      this.o.domFocus();
    }
  }
  u(e) {
    if ($Fk(e.browserEvent.target) || $n1(e.browserEvent.target)) {
      return;
    }
    const focus = typeof e.index === "undefined" ? [] : [e.index];
    this.o.setFocus(focus, e.browserEvent);
  }
  v(e) {
    if (!this.f) {
      return;
    }
    if ($Fk(e.browserEvent.target) || $n1(e.browserEvent.target)) {
      return;
    }
    if (e.browserEvent.isHandledByList) {
      return;
    }
    e.browserEvent.isHandledByList = true;
    const focus = e.index;
    if (typeof focus === "undefined") {
      this.o.setFocus([], e.browserEvent);
      this.o.setSelection([], e.browserEvent);
      this.o.setAnchor(void 0);
      return;
    }
    if (this.s(e)) {
      return this.x(e);
    }
    this.o.setFocus([focus], e.browserEvent);
    this.o.setAnchor(focus);
    if (!isMouseRightClick(e.browserEvent)) {
      this.o.setSelection([focus], e.browserEvent);
    }
    this.k.fire(e);
  }
  w(e) {
    if ($Fk(e.browserEvent.target) || $n1(e.browserEvent.target)) {
      return;
    }
    if (this.s(e)) {
      return;
    }
    if (e.browserEvent.isHandledByList) {
      return;
    }
    e.browserEvent.isHandledByList = true;
    const focus = this.o.getFocus();
    this.o.setSelection(focus, e.browserEvent);
  }
  x(e) {
    const focus = e.index;
    let anchor = this.o.getAnchor();
    if (this.q(e)) {
      if (typeof anchor === "undefined") {
        const currentFocus = this.o.getFocus()[0];
        anchor = currentFocus ?? focus;
        this.o.setAnchor(anchor);
      }
      const min = Math.min(anchor, focus);
      const max = Math.max(anchor, focus);
      const rangeSelection = $Ub(min, max + 1);
      const selection = this.o.getSelection();
      const contiguousRange = getContiguousRangeContaining(disjunction(selection, [anchor]), anchor);
      if (contiguousRange.length === 0) {
        return;
      }
      const newSelection = disjunction(rangeSelection, relativeComplement(selection, contiguousRange));
      this.o.setSelection(newSelection, e.browserEvent);
      this.o.setFocus([focus], e.browserEvent);
    } else if (this.p(e)) {
      const selection = this.o.getSelection();
      const newSelection = selection.filter((i2) => i2 !== focus);
      this.o.setFocus([focus]);
      this.o.setAnchor(focus);
      if (selection.length === newSelection.length) {
        this.o.setSelection([...newSelection, focus], e.browserEvent);
      } else {
        this.o.setSelection(newSelection, e.browserEvent);
      }
    }
  }
  dispose() {
    this.g.dispose();
  }
};
var $y1 = class {
  constructor(c, d) {
    this.c = c;
    this.d = d;
  }
  style(styles) {
    const suffix = this.d && `.${this.d}`;
    const content = [];
    if (styles.listBackground) {
      content.push(`.monaco-list${suffix} .monaco-list-rows { background: ${styles.listBackground}; }`);
    }
    if (styles.listFocusBackground) {
      content.push(`.monaco-list${suffix}:focus .monaco-list-row.focused { background-color: ${styles.listFocusBackground}; }`);
      content.push(`.monaco-list${suffix}:focus .monaco-list-row.focused:hover { background-color: ${styles.listFocusBackground}; }`);
    }
    if (styles.listFocusForeground) {
      content.push(`.monaco-list${suffix}:focus .monaco-list-row.focused { color: ${styles.listFocusForeground}; }`);
    }
    if (styles.listActiveSelectionBackground) {
      content.push(`.monaco-list${suffix}:focus .monaco-list-row.selected { background-color: ${styles.listActiveSelectionBackground}; }`);
      content.push(`.monaco-list${suffix}:focus .monaco-list-row.selected:hover { background-color: ${styles.listActiveSelectionBackground}; }`);
    }
    if (styles.listActiveSelectionForeground) {
      content.push(`.monaco-list${suffix}:focus .monaco-list-row.selected { color: ${styles.listActiveSelectionForeground}; }`);
    }
    if (styles.listActiveSelectionIconForeground) {
      content.push(`.monaco-list${suffix}:focus .monaco-list-row.selected .codicon { color: ${styles.listActiveSelectionIconForeground}; }`);
    }
    if (styles.listFocusAndSelectionBackground) {
      content.push(`
				.monaco-drag-image,
				.monaco-list${suffix}:focus .monaco-list-row.selected.focused { background-color: ${styles.listFocusAndSelectionBackground}; }
			`);
    }
    if (styles.listFocusAndSelectionForeground) {
      content.push(`
				.monaco-drag-image,
				.monaco-list${suffix}:focus .monaco-list-row.selected.focused { color: ${styles.listFocusAndSelectionForeground}; }
			`);
    }
    if (styles.listInactiveFocusForeground) {
      content.push(`.monaco-list${suffix} .monaco-list-row.focused { color:  ${styles.listInactiveFocusForeground}; }`);
      content.push(`.monaco-list${suffix} .monaco-list-row.focused:hover { color:  ${styles.listInactiveFocusForeground}; }`);
    }
    if (styles.listInactiveSelectionIconForeground) {
      content.push(`.monaco-list${suffix} .monaco-list-row.focused .codicon { color:  ${styles.listInactiveSelectionIconForeground}; }`);
    }
    if (styles.listInactiveFocusBackground) {
      content.push(`.monaco-list${suffix} .monaco-list-row.focused { background-color:  ${styles.listInactiveFocusBackground}; }`);
      content.push(`.monaco-list${suffix} .monaco-list-row.focused:hover { background-color:  ${styles.listInactiveFocusBackground}; }`);
    }
    if (styles.listInactiveSelectionBackground) {
      content.push(`.monaco-list${suffix} .monaco-list-row.selected { background-color:  ${styles.listInactiveSelectionBackground}; }`);
      content.push(`.monaco-list${suffix} .monaco-list-row.selected:hover { background-color:  ${styles.listInactiveSelectionBackground}; }`);
    }
    if (styles.listInactiveSelectionForeground) {
      content.push(`.monaco-list${suffix} .monaco-list-row.selected { color: ${styles.listInactiveSelectionForeground}; }`);
    }
    if (styles.listHoverBackground) {
      content.push(`.monaco-list${suffix}:not(.drop-target):not(.dragging) .monaco-list-row:hover:not(.selected):not(.focused) { background-color: ${styles.listHoverBackground}; }`);
    }
    if (styles.listHoverForeground) {
      content.push(`.monaco-list${suffix}:not(.drop-target):not(.dragging) .monaco-list-row:hover:not(.selected):not(.focused) { color:  ${styles.listHoverForeground}; }`);
    }
    const focusAndSelectionOutline = $ZZ(styles.listFocusAndSelectionOutline, $ZZ(styles.listSelectionOutline, styles.listFocusOutline ?? ""));
    if (focusAndSelectionOutline) {
      content.push(`.monaco-list${suffix}:focus .monaco-list-row.focused.selected { outline: 1px solid ${focusAndSelectionOutline}; outline-offset: -1px;}`);
    }
    if (styles.listFocusOutline) {
      content.push(`
				.monaco-drag-image,
				.monaco-list${suffix}:focus .monaco-list-row.focused { outline: 1px solid ${styles.listFocusOutline}; outline-offset: -1px; }
				.monaco-workbench.context-menu-visible .monaco-list${suffix}.last-focused .monaco-list-row.focused { outline: 1px solid ${styles.listFocusOutline}; outline-offset: -1px; }
			`);
    }
    const inactiveFocusAndSelectionOutline = $ZZ(styles.listSelectionOutline, styles.listInactiveFocusOutline ?? "");
    if (inactiveFocusAndSelectionOutline) {
      content.push(`.monaco-list${suffix} .monaco-list-row.focused.selected { outline: 1px dotted ${inactiveFocusAndSelectionOutline}; outline-offset: -1px; }`);
    }
    if (styles.listSelectionOutline) {
      content.push(`.monaco-list${suffix} .monaco-list-row.selected { outline: 1px dotted ${styles.listSelectionOutline}; outline-offset: -1px; }`);
    }
    if (styles.listInactiveFocusOutline) {
      content.push(`.monaco-list${suffix} .monaco-list-row.focused { outline: 1px dotted ${styles.listInactiveFocusOutline}; outline-offset: -1px; }`);
    }
    if (styles.listHoverOutline) {
      content.push(`.monaco-list${suffix} .monaco-list-row:hover { outline: 1px dashed ${styles.listHoverOutline}; outline-offset: -1px; }`);
    }
    if (styles.listDropOverBackground) {
      content.push(`
				.monaco-list${suffix}.drop-target,
				.monaco-list${suffix} .monaco-list-rows.drop-target,
				.monaco-list${suffix} .monaco-list-row.drop-target { background-color: ${styles.listDropOverBackground} !important; color: inherit !important; }
			`);
    }
    if (styles.listDropBetweenBackground) {
      content.push(`
			.monaco-list${suffix} .monaco-list-rows.drop-target-before .monaco-list-row:first-child::before,
			.monaco-list${suffix} .monaco-list-row.drop-target-before::before {
				content: ""; position: absolute; top: 0px; left: 0px; width: 100%; height: 1px;
				background-color: ${styles.listDropBetweenBackground};
			}`);
      content.push(`
			.monaco-list${suffix} .monaco-list-rows.drop-target-after .monaco-list-row:last-child::after,
			.monaco-list${suffix} .monaco-list-row.drop-target-after::after {
				content: ""; position: absolute; bottom: 0px; left: 0px; width: 100%; height: 1px;
				background-color: ${styles.listDropBetweenBackground};
			}`);
    }
    if (styles.tableColumnsBorder) {
      content.push(`
				.monaco-table > .monaco-split-view2,
				.monaco-table > .monaco-split-view2 .monaco-sash.vertical::before,
				.monaco-workbench:not(.reduce-motion) .monaco-table:hover > .monaco-split-view2,
				.monaco-workbench:not(.reduce-motion) .monaco-table:hover > .monaco-split-view2 .monaco-sash.vertical::before {
					border-color: ${styles.tableColumnsBorder};
				}

				.monaco-workbench:not(.reduce-motion) .monaco-table > .monaco-split-view2,
				.monaco-workbench:not(.reduce-motion) .monaco-table > .monaco-split-view2 .monaco-sash.vertical::before {
					border-color: transparent;
				}
			`);
    }
    if (styles.tableOddRowsBackgroundColor) {
      content.push(`
				.monaco-table .monaco-list-row[data-parity=odd]:not(.focused):not(.selected):not(:hover) .monaco-table-tr,
				.monaco-table .monaco-list:not(:focus) .monaco-list-row[data-parity=odd].focused:not(.selected):not(:hover) .monaco-table-tr,
				.monaco-table .monaco-list:not(.focused) .monaco-list-row[data-parity=odd].focused:not(.selected):not(:hover) .monaco-table-tr {
					background-color: ${styles.tableOddRowsBackgroundColor};
				}
			`);
    }
    this.c.textContent = content.join("\n");
  }
};
var $z1 = {
  listFocusBackground: "#7FB0D0",
  listActiveSelectionBackground: "#0E639C",
  listActiveSelectionForeground: "#FFFFFF",
  listActiveSelectionIconForeground: "#FFFFFF",
  listFocusAndSelectionOutline: "#90C2F9",
  listFocusAndSelectionBackground: "#094771",
  listFocusAndSelectionForeground: "#FFFFFF",
  listInactiveSelectionBackground: "#3F3F46",
  listInactiveSelectionIconForeground: "#FFFFFF",
  listHoverBackground: "#2A2D2E",
  listDropOverBackground: "#383B3D",
  listDropBetweenBackground: "#EEEEEE",
  treeIndentGuidesStroke: "#a9a9a9",
  treeInactiveIndentGuidesStroke: $Vn.fromHex("#a9a9a9").transparent(0.4).toString(),
  tableColumnsBorder: $Vn.fromHex("#cccccc").transparent(0.2).toString(),
  tableOddRowsBackgroundColor: $Vn.fromHex("#cccccc").transparent(0.04).toString(),
  listBackground: void 0,
  listFocusForeground: void 0,
  listInactiveSelectionForeground: void 0,
  listInactiveFocusForeground: void 0,
  listInactiveFocusBackground: void 0,
  listHoverForeground: void 0,
  listFocusOutline: void 0,
  listInactiveFocusOutline: void 0,
  listSelectionOutline: void 0,
  listHoverOutline: void 0,
  treeStickyScrollBackground: void 0,
  treeStickyScrollBorder: void 0,
  treeStickyScrollShadow: void 0
};
var DefaultOptions2 = {
  keyboardSupport: true,
  mouseSupport: true,
  multipleSelectionSupport: true,
  dnd: {
    getDragURI() {
      return null;
    },
    onDragStart() {
    },
    onDragOver() {
      return false;
    },
    drop() {
    },
    dispose() {
    }
  }
};
function getContiguousRangeContaining(range, value) {
  const index = range.indexOf(value);
  if (index === -1) {
    return [];
  }
  const result = [];
  let i2 = index - 1;
  while (i2 >= 0 && range[i2] === value - (index - i2)) {
    result.push(range[i2--]);
  }
  result.reverse();
  i2 = index;
  while (i2 < range.length && range[i2] === value + (i2 - index)) {
    result.push(range[i2++]);
  }
  return result;
}
function disjunction(one, other) {
  const result = [];
  let i2 = 0, j = 0;
  while (i2 < one.length || j < other.length) {
    if (i2 >= one.length) {
      result.push(other[j++]);
    } else if (j >= other.length) {
      result.push(one[i2++]);
    } else if (one[i2] === other[j]) {
      result.push(one[i2]);
      i2++;
      j++;
      continue;
    } else if (one[i2] < other[j]) {
      result.push(one[i2++]);
    } else {
      result.push(other[j++]);
    }
  }
  return result;
}
function relativeComplement(one, other) {
  const result = [];
  let i2 = 0, j = 0;
  while (i2 < one.length || j < other.length) {
    if (i2 >= one.length) {
      result.push(other[j++]);
    } else if (j >= other.length) {
      result.push(one[i2++]);
    } else if (one[i2] === other[j]) {
      i2++;
      j++;
      continue;
    } else if (one[i2] < other[j]) {
      result.push(one[i2++]);
    } else {
      j++;
    }
  }
  return result;
}
var numericSort = (a, b) => a - b;
var PipelineRenderer = class {
  constructor(c, d) {
    this.c = c;
    this.d = d;
  }
  get templateId() {
    return this.c;
  }
  renderTemplate(container2) {
    return this.d.map((r2) => r2.renderTemplate(container2));
  }
  renderElement(element, index, templateData, height) {
    let i2 = 0;
    for (const renderer of this.d) {
      renderer.renderElement(element, index, templateData[i2++], height);
    }
  }
  disposeElement(element, index, templateData, height) {
    let i2 = 0;
    for (const renderer of this.d) {
      renderer.disposeElement?.(element, index, templateData[i2], height);
      i2 += 1;
    }
  }
  disposeTemplate(templateData) {
    let i2 = 0;
    for (const renderer of this.d) {
      renderer.disposeTemplate(templateData[i2++]);
    }
  }
};
var AccessibiltyRenderer = class {
  constructor(c) {
    this.c = c;
    this.templateId = "a18n";
  }
  renderTemplate(container2) {
    return { container: container2, disposables: new $2c() };
  }
  renderElement(element, index, data) {
    const ariaLabel = this.c.getAriaLabel(element);
    const observable = ariaLabel && typeof ariaLabel !== "string" ? ariaLabel : $Bd(ariaLabel);
    data.disposables.add($td((reader) => {
      this.d(reader.readObservable(observable), data.container);
    }));
    const ariaLevel = this.c.getAriaLevel && this.c.getAriaLevel(element);
    if (typeof ariaLevel === "number") {
      data.container.setAttribute("aria-level", `${ariaLevel}`);
    } else {
      data.container.removeAttribute("aria-level");
    }
  }
  d(ariaLabel, element) {
    if (ariaLabel) {
      element.setAttribute("aria-label", ariaLabel);
    } else {
      element.removeAttribute("aria-label");
    }
  }
  disposeElement(element, index, templateData, height) {
    templateData.disposables.clear();
  }
  disposeTemplate(templateData) {
    templateData.disposables.dispose();
  }
};
var ListViewDragAndDrop = class {
  constructor(c, d) {
    this.c = c;
    this.d = d;
  }
  getDragElements(element) {
    const selection = this.c.getSelectedElements();
    const elements = selection.indexOf(element) > -1 ? selection : [element];
    return elements;
  }
  getDragURI(element) {
    return this.d.getDragURI(element);
  }
  getDragLabel(elements, originalEvent) {
    if (this.d.getDragLabel) {
      return this.d.getDragLabel(elements, originalEvent);
    }
    return void 0;
  }
  onDragStart(data, originalEvent) {
    this.d.onDragStart?.(data, originalEvent);
  }
  onDragOver(data, targetElement, targetIndex, targetSector, originalEvent) {
    return this.d.onDragOver(data, targetElement, targetIndex, targetSector, originalEvent);
  }
  onDragLeave(data, targetElement, targetIndex, originalEvent) {
    this.d.onDragLeave?.(data, targetElement, targetIndex, originalEvent);
  }
  onDragEnd(originalEvent) {
    this.d.onDragEnd?.(originalEvent);
  }
  drop(data, targetElement, targetIndex, targetSector, originalEvent) {
    this.d.drop(data, targetElement, targetIndex, targetSector, originalEvent);
  }
  dispose() {
    this.d.dispose();
  }
};
var $A1 = class {
  get onDidChangeFocus() {
    return Event2.map(this.k.wrapEvent(this.d.onChange), (e) => this.H(e), this.z);
  }
  get onDidChangeSelection() {
    return Event2.map(this.k.wrapEvent(this.f.onChange), (e) => this.H(e), this.z);
  }
  get domId() {
    return this.o.domId;
  }
  get onDidScroll() {
    return this.o.onDidScroll;
  }
  get onMouseClick() {
    return this.o.onMouseClick;
  }
  get onMouseDblClick() {
    return this.o.onMouseDblClick;
  }
  get onMouseMiddleClick() {
    return this.o.onMouseMiddleClick;
  }
  get onPointer() {
    return this.x.onPointer;
  }
  get onMouseUp() {
    return this.o.onMouseUp;
  }
  get onMouseDown() {
    return this.o.onMouseDown;
  }
  get onMouseOver() {
    return this.o.onMouseOver;
  }
  get onMouseMove() {
    return this.o.onMouseMove;
  }
  get onMouseOut() {
    return this.o.onMouseOut;
  }
  get onTouchStart() {
    return this.o.onTouchStart;
  }
  get onTap() {
    return this.o.onTap;
  }
  /**
   * Possible context menu trigger events:
   * - ContextMenu key
   * - Shift F10
   * - Ctrl Option Shift M (macOS with VoiceOver)
   * - Mouse right click
   */
  get onContextMenu() {
    let didJustPressContextMenuKey = false;
    const fromKeyDown = Event2.chain(this.z.add(new $9Z(this.o.domNode, "keydown")).event, ($149) => $149.map((e) => new $if(e)).filter((e) => didJustPressContextMenuKey = e.keyCode === 58 || e.shiftKey && e.keyCode === 68).map((e) => $9j.stop(e, true)).filter(() => false));
    const fromKeyUp = Event2.chain(this.z.add(new $9Z(this.o.domNode, "keyup")).event, ($149) => $149.forEach(() => didJustPressContextMenuKey = false).map((e) => new $if(e)).filter((e) => e.keyCode === 58 || e.shiftKey && e.keyCode === 68).map((e) => $9j.stop(e, true)).map(({ browserEvent }) => {
      const focus = this.getFocus();
      const index = focus.length ? focus[0] : void 0;
      const element = typeof index !== "undefined" ? this.o.element(index) : void 0;
      const anchor = typeof index !== "undefined" ? this.o.domElement(index) : this.o.domNode;
      return { index, element, anchor, browserEvent };
    }));
    const fromMouse = Event2.chain(this.o.onContextMenu, ($149) => $149.filter((_) => !didJustPressContextMenuKey).map(({ element, index, browserEvent }) => ({ element, index, anchor: new $lf(getWindow(this.o.domNode), browserEvent), browserEvent })));
    return Event2.any(fromKeyDown, fromKeyUp, fromMouse);
  }
  get onKeyDown() {
    return this.z.add(new $9Z(this.o.domNode, "keydown")).event;
  }
  get onKeyUp() {
    return this.z.add(new $9Z(this.o.domNode, "keyup")).event;
  }
  get onKeyPress() {
    return this.z.add(new $9Z(this.o.domNode, "keypress")).event;
  }
  get onDidFocus() {
    return Event2.signal(this.z.add(new $9Z(this.o.domNode, "focus", true)).event);
  }
  get onDidBlur() {
    return Event2.signal(this.z.add(new $9Z(this.o.domNode, "blur", true)).event);
  }
  constructor(B, container2, virtualDelegate, renderers, C = DefaultOptions2) {
    this.B = B;
    this.C = C;
    this.d = new Trait("focused");
    this.g = new Trait("anchor");
    this.k = new $He();
    this.y = "";
    this.z = new $2c();
    this.A = new $ze();
    this.onDidDispose = this.A.event;
    const role = this.C.accessibilityProvider && this.C.accessibilityProvider.getWidgetRole ? this.C.accessibilityProvider?.getWidgetRole() : "list";
    this.f = new SelectionTrait(role !== "listbox");
    const baseRenderers = [this.d.renderer, this.f.renderer];
    this.v = C.accessibilityProvider;
    if (this.v) {
      baseRenderers.push(new AccessibiltyRenderer(this.v));
      this.v.onDidChangeActiveDescendant?.(this.J, this, this.z);
    }
    renderers = renderers.map((r2) => new PipelineRenderer(r2.templateId, [...baseRenderers, r2]));
    const viewOptions = {
      ...C,
      dnd: C.dnd && new ListViewDragAndDrop(this, C.dnd)
    };
    this.o = this.D(container2, virtualDelegate, renderers, viewOptions);
    this.o.domNode.setAttribute("role", role);
    if (C.styleController) {
      this.t = C.styleController(this.o.domId);
    } else {
      const styleElement = $VZ(this.o.domNode);
      this.t = new $y1(styleElement, this.o.domId);
    }
    this.q = new $a1([
      new TraitSpliceable(this.d, this.o, C.identityProvider),
      new TraitSpliceable(this.f, this.o, C.identityProvider),
      new TraitSpliceable(this.g, this.o, C.identityProvider),
      this.o
    ]);
    this.z.add(this.d);
    this.z.add(this.f);
    this.z.add(this.g);
    this.z.add(this.o);
    this.z.add(this.A);
    this.z.add(new DOMFocusController(this, this.o));
    if (typeof C.keyboardSupport !== "boolean" || C.keyboardSupport) {
      this.w = new KeyboardController(this, this.o, C);
      this.z.add(this.w);
    }
    if (C.keyboardNavigationLabelProvider) {
      const delegate = C.keyboardNavigationDelegate || $u1;
      this.u = new TypeNavigationController(this, this.o, C.keyboardNavigationLabelProvider, C.keyboardNavigationEventFilter ?? (() => true), delegate);
      this.z.add(this.u);
    }
    this.x = this.E(C);
    this.z.add(this.x);
    this.onDidChangeFocus(this.I, this, this.z);
    this.onDidChangeSelection(this.K, this, this.z);
    if (this.v) {
      this.ariaLabel = this.v.getWidgetAriaLabel();
    }
    if (this.C.multipleSelectionSupport !== false) {
      this.o.domNode.setAttribute("aria-multiselectable", "true");
    }
  }
  D(container2, virtualDelegate, renderers, viewOptions) {
    return new $j1(container2, virtualDelegate, renderers, viewOptions);
  }
  E(options3) {
    return new $x1(this);
  }
  updateOptions(optionsUpdate = {}) {
    this.C = { ...this.C, ...optionsUpdate };
    this.u?.updateOptions(this.C);
    if (this.C.multipleSelectionController !== void 0) {
      if (this.C.multipleSelectionSupport) {
        this.o.domNode.setAttribute("aria-multiselectable", "true");
      } else {
        this.o.domNode.removeAttribute("aria-multiselectable");
      }
    }
    this.x.updateOptions(optionsUpdate);
    this.w?.updateOptions(optionsUpdate);
    this.o.updateOptions(optionsUpdate);
  }
  get options() {
    return this.C;
  }
  splice(start, deleteCount, elements = []) {
    if (start < 0 || start > this.o.length) {
      throw new $l1(this.B, `Invalid start index: ${start}`);
    }
    if (deleteCount < 0) {
      throw new $l1(this.B, `Invalid delete count: ${deleteCount}`);
    }
    if (deleteCount === 0 && elements.length === 0) {
      return;
    }
    this.k.bufferEvents(() => this.q.splice(start, deleteCount, elements));
  }
  updateWidth(index) {
    this.o.updateWidth(index);
  }
  updateElementHeight(index, size) {
    this.o.updateElementHeight(index, size, null);
  }
  rerender() {
    this.o.rerender();
  }
  element(index) {
    return this.o.element(index);
  }
  indexOf(element) {
    return this.o.indexOf(element);
  }
  indexAt(position) {
    return this.o.indexAt(position);
  }
  get length() {
    return this.o.length;
  }
  get contentHeight() {
    return this.o.contentHeight;
  }
  get contentWidth() {
    return this.o.contentWidth;
  }
  get onDidChangeContentHeight() {
    return this.o.onDidChangeContentHeight;
  }
  get onDidChangeContentWidth() {
    return this.o.onDidChangeContentWidth;
  }
  get scrollTop() {
    return this.o.getScrollTop();
  }
  set scrollTop(scrollTop) {
    this.o.setScrollTop(scrollTop);
  }
  get scrollLeft() {
    return this.o.getScrollLeft();
  }
  set scrollLeft(scrollLeft) {
    this.o.setScrollLeft(scrollLeft);
  }
  get scrollHeight() {
    return this.o.scrollHeight;
  }
  get renderHeight() {
    return this.o.renderHeight;
  }
  get firstVisibleIndex() {
    return this.o.firstVisibleIndex;
  }
  get firstMostlyVisibleIndex() {
    return this.o.firstMostlyVisibleIndex;
  }
  get lastVisibleIndex() {
    return this.o.lastVisibleIndex;
  }
  get ariaLabel() {
    return this.y;
  }
  set ariaLabel(value) {
    this.y = value;
    this.o.domNode.setAttribute("aria-label", value);
  }
  domFocus() {
    this.o.domNode.focus({ preventScroll: true });
  }
  layout(height, width2) {
    this.o.layout(height, width2);
  }
  triggerTypeNavigation() {
    this.u?.trigger();
  }
  setSelection(indexes, browserEvent) {
    for (const index of indexes) {
      if (index < 0 || index >= this.length) {
        throw new $l1(this.B, `Invalid index ${index}`);
      }
    }
    this.f.set(indexes, browserEvent);
  }
  getSelection() {
    return this.f.get();
  }
  getSelectedElements() {
    return this.getSelection().map((i2) => this.o.element(i2));
  }
  setAnchor(index) {
    if (typeof index === "undefined") {
      this.g.set([]);
      return;
    }
    if (index < 0 || index >= this.length) {
      throw new $l1(this.B, `Invalid index ${index}`);
    }
    this.g.set([index]);
  }
  getAnchor() {
    return this.g.get().at(0);
  }
  getAnchorElement() {
    const anchor = this.getAnchor();
    return typeof anchor === "undefined" ? void 0 : this.element(anchor);
  }
  setFocus(indexes, browserEvent) {
    for (const index of indexes) {
      if (index < 0 || index >= this.length) {
        throw new $l1(this.B, `Invalid index ${index}`);
      }
    }
    this.d.set(indexes, browserEvent);
  }
  focusNext(n = 1, loop = false, browserEvent, filter) {
    if (this.length === 0) {
      return;
    }
    const focus = this.d.get();
    const index = this.F(focus.length > 0 ? focus[0] + n : 0, loop, filter);
    if (index > -1) {
      this.setFocus([index], browserEvent);
    }
  }
  focusPrevious(n = 1, loop = false, browserEvent, filter) {
    if (this.length === 0) {
      return;
    }
    const focus = this.d.get();
    const index = this.G(focus.length > 0 ? focus[0] - n : 0, loop, filter);
    if (index > -1) {
      this.setFocus([index], browserEvent);
    }
  }
  async focusNextPage(browserEvent, filter) {
    let lastPageIndex = this.o.indexAt(this.o.getScrollTop() + this.o.renderHeight);
    lastPageIndex = lastPageIndex === 0 ? 0 : lastPageIndex - 1;
    const currentlyFocusedElementIndex = this.getFocus()[0];
    if (currentlyFocusedElementIndex !== lastPageIndex && (currentlyFocusedElementIndex === void 0 || lastPageIndex > currentlyFocusedElementIndex)) {
      const lastGoodPageIndex = this.G(lastPageIndex, false, filter);
      if (lastGoodPageIndex > -1 && currentlyFocusedElementIndex !== lastGoodPageIndex) {
        this.setFocus([lastGoodPageIndex], browserEvent);
      } else {
        this.setFocus([lastPageIndex], browserEvent);
      }
    } else {
      const previousScrollTop = this.o.getScrollTop();
      let nextpageScrollTop = previousScrollTop + this.o.renderHeight;
      if (lastPageIndex > currentlyFocusedElementIndex) {
        nextpageScrollTop -= this.o.elementHeight(lastPageIndex);
      }
      this.o.setScrollTop(nextpageScrollTop);
      if (this.o.getScrollTop() !== previousScrollTop) {
        this.setFocus([]);
        await $Wh(0);
        await this.focusNextPage(browserEvent, filter);
      }
    }
  }
  async focusPreviousPage(browserEvent, filter, getPaddingTop = () => 0) {
    let firstPageIndex;
    const paddingTop = getPaddingTop();
    const scrollTop = this.o.getScrollTop() + paddingTop;
    if (scrollTop === 0) {
      firstPageIndex = this.o.indexAt(scrollTop);
    } else {
      firstPageIndex = this.o.indexAfter(scrollTop - 1);
    }
    const currentlyFocusedElementIndex = this.getFocus()[0];
    if (currentlyFocusedElementIndex !== firstPageIndex && (currentlyFocusedElementIndex === void 0 || currentlyFocusedElementIndex >= firstPageIndex)) {
      const firstGoodPageIndex = this.F(firstPageIndex, false, filter);
      if (firstGoodPageIndex > -1 && currentlyFocusedElementIndex !== firstGoodPageIndex) {
        this.setFocus([firstGoodPageIndex], browserEvent);
      } else {
        this.setFocus([firstPageIndex], browserEvent);
      }
    } else {
      const previousScrollTop = scrollTop;
      this.o.setScrollTop(scrollTop - this.o.renderHeight - paddingTop);
      if (this.o.getScrollTop() + getPaddingTop() !== previousScrollTop) {
        this.setFocus([]);
        await $Wh(0);
        await this.focusPreviousPage(browserEvent, filter, getPaddingTop);
      }
    }
  }
  focusLast(browserEvent, filter) {
    if (this.length === 0) {
      return;
    }
    const index = this.G(this.length - 1, false, filter);
    if (index > -1) {
      this.setFocus([index], browserEvent);
    }
  }
  focusFirst(browserEvent, filter) {
    this.focusNth(0, browserEvent, filter);
  }
  focusNth(n, browserEvent, filter) {
    if (this.length === 0) {
      return;
    }
    const index = this.F(n, false, filter);
    if (index > -1) {
      this.setFocus([index], browserEvent);
    }
  }
  F(index, loop = false, filter) {
    for (let i2 = 0; i2 < this.length; i2++) {
      if (index >= this.length && !loop) {
        return -1;
      }
      index = index % this.length;
      if (!filter || filter(this.element(index))) {
        return index;
      }
      index++;
    }
    return -1;
  }
  G(index, loop = false, filter) {
    for (let i2 = 0; i2 < this.length; i2++) {
      if (index < 0 && !loop) {
        return -1;
      }
      index = (this.length + index % this.length) % this.length;
      if (!filter || filter(this.element(index))) {
        return index;
      }
      index--;
    }
    return -1;
  }
  getFocus() {
    return this.d.get();
  }
  getFocusedElements() {
    return this.getFocus().map((i2) => this.o.element(i2));
  }
  reveal(index, relativeTop, paddingTop = 0) {
    if (index < 0 || index >= this.length) {
      throw new $l1(this.B, `Invalid index ${index}`);
    }
    const scrollTop = this.o.getScrollTop();
    const elementTop = this.o.elementTop(index);
    const elementHeight = this.o.elementHeight(index);
    if ($Dg(relativeTop)) {
      const m = elementHeight - this.o.renderHeight + paddingTop;
      this.o.setScrollTop(m * $4i(relativeTop, 0, 1) + elementTop - paddingTop);
    } else {
      const viewItemBottom = elementTop + elementHeight;
      const scrollBottom = scrollTop + this.o.renderHeight;
      if (elementTop < scrollTop + paddingTop && viewItemBottom >= scrollBottom) {
      } else if (elementTop < scrollTop + paddingTop || viewItemBottom >= scrollBottom && elementHeight >= this.o.renderHeight) {
        this.o.setScrollTop(elementTop - paddingTop);
      } else if (viewItemBottom >= scrollBottom) {
        this.o.setScrollTop(viewItemBottom - this.o.renderHeight);
      }
    }
  }
  /**
   * Returns the relative position of an element rendered in the list.
   * Returns `null` if the element isn't *entirely* in the visible viewport.
   */
  getRelativeTop(index, paddingTop = 0) {
    if (index < 0 || index >= this.length) {
      throw new $l1(this.B, `Invalid index ${index}`);
    }
    const scrollTop = this.o.getScrollTop();
    const elementTop = this.o.elementTop(index);
    const elementHeight = this.o.elementHeight(index);
    if (elementTop < scrollTop + paddingTop || elementTop + elementHeight > scrollTop + this.o.renderHeight) {
      return null;
    }
    const m = elementHeight - this.o.renderHeight + paddingTop;
    return Math.abs((scrollTop + paddingTop - elementTop) / m);
  }
  isDOMFocused() {
    return $Mj(this.o.domNode);
  }
  getHTMLElement() {
    return this.o.domNode;
  }
  getScrollableElement() {
    return this.o.scrollableElementDomNode;
  }
  getElementID(index) {
    return this.o.getElementDomId(index);
  }
  getElementTop(index) {
    return this.o.elementTop(index);
  }
  style(styles) {
    this.t.style(styles);
  }
  H({ indexes, browserEvent }) {
    return { indexes, elements: indexes.map((i2) => this.o.element(i2)), browserEvent };
  }
  I() {
    const focus = this.d.get();
    this.o.domNode.classList.toggle("element-focused", focus.length > 0);
    this.J();
  }
  J() {
    const focus = this.d.get();
    if (focus.length > 0) {
      let id2;
      if (this.v?.getActiveDescendantId) {
        id2 = this.v.getActiveDescendantId(this.o.element(focus[0]));
      }
      this.o.domNode.setAttribute("aria-activedescendant", id2 || this.o.getElementDomId(focus[0]));
    } else {
      this.o.domNode.removeAttribute("aria-activedescendant");
    }
  }
  K() {
    const selection = this.f.get();
    this.o.domNode.classList.toggle("selection-none", selection.length === 0);
    this.o.domNode.classList.toggle("selection-single", selection.length === 1);
    this.o.domNode.classList.toggle("selection-multiple", selection.length > 1);
  }
  dispose() {
    this.A.fire();
    this.z.dispose();
    this.A.dispose();
  }
};
__decorate([
  $0t
], $A1.prototype, "onDidChangeFocus", null);
__decorate([
  $0t
], $A1.prototype, "onDidChangeSelection", null);
__decorate([
  $0t
], $A1.prototype, "onContextMenu", null);
__decorate([
  $0t
], $A1.prototype, "onKeyDown", null);
__decorate([
  $0t
], $A1.prototype, "onKeyUp", null);
__decorate([
  $0t
], $A1.prototype, "onKeyPress", null);
__decorate([
  $0t
], $A1.prototype, "onDidFocus", null);
__decorate([
  $0t
], $A1.prototype, "onDidBlur", null);

// out-build/vs/base/common/iconLabels.js
var iconStartMarker = "$(";
var iconsRegex = new RegExp(`\\$\\(${ThemeIcon.iconNameExpression}(?:${ThemeIcon.iconModifierExpression})?\\)`, "g");
var escapeIconsRegex = new RegExp(`(\\\\)?${iconsRegex.source}`, "g");
function $8l(text2) {
  return text2.replace(escapeIconsRegex, (match, escaped) => escaped ? match : `\\${match}`);
}
var markdownEscapedIconsRegex = new RegExp(`\\\\${iconsRegex.source}`, "g");
function $9l(text2) {
  return text2.replace(markdownEscapedIconsRegex, (match) => `\\${match}`);
}
var stripIconsRegex = new RegExp(`(\\s)?(\\\\)?${iconsRegex.source}(\\s)?`, "g");
function $0l(text2) {
  if (text2.indexOf(iconStartMarker) === -1) {
    return text2;
  }
  return text2.replace(stripIconsRegex, (match, preWhitespace, escaped, postWhitespace) => escaped ? match : preWhitespace || postWhitespace || "");
}
function $$l(text2) {
  if (!text2) {
    return "";
  }
  return text2.replace(/\$\((.*?)\)/g, (_match, codiconName) => ` ${codiconName} `).trim();
}
var _parseIconsRegex = new RegExp(`\\$\\(${ThemeIcon.iconNameCharacter}+\\)`, "g");
function $_l(input) {
  _parseIconsRegex.lastIndex = 0;
  let text2 = "";
  const iconOffsets = [];
  let iconsOffset = 0;
  while (true) {
    const pos = _parseIconsRegex.lastIndex;
    const match = _parseIconsRegex.exec(input);
    const chars = input.substring(pos, match?.index);
    if (chars.length > 0) {
      text2 += chars;
      for (let i2 = 0; i2 < chars.length; i2++) {
        iconOffsets.push(iconsOffset);
      }
    }
    if (!match) {
      break;
    }
    iconsOffset += match[0].length;
  }
  return { text: text2, iconOffsets };
}
function $am(query, target, enableSeparateSubstringMatching = false) {
  const { text: text2, iconOffsets } = target;
  if (!iconOffsets || iconOffsets.length === 0) {
    return $Rl(query, text2, enableSeparateSubstringMatching);
  }
  const wordToMatchAgainstWithoutIconsTrimmed = $Ff(text2, " ");
  const leadingWhitespaceOffset = text2.length - wordToMatchAgainstWithoutIconsTrimmed.length;
  const matches = $Rl(query, wordToMatchAgainstWithoutIconsTrimmed, enableSeparateSubstringMatching);
  if (matches) {
    for (const match of matches) {
      const iconOffset = iconOffsets[match.start + leadingWhitespaceOffset] + leadingWhitespaceOffset;
      match.start += iconOffset;
      match.end += iconOffset;
    }
  }
  return matches;
}

// out-build/vs/base/common/htmlContent.js
var MarkdownStringTextNewlineStyle;
(function(MarkdownStringTextNewlineStyle2) {
  MarkdownStringTextNewlineStyle2[MarkdownStringTextNewlineStyle2["Paragraph"] = 0] = "Paragraph";
  MarkdownStringTextNewlineStyle2[MarkdownStringTextNewlineStyle2["Break"] = 1] = "Break";
})(MarkdownStringTextNewlineStyle || (MarkdownStringTextNewlineStyle = {}));
var $bm = class {
  constructor(value = "", isTrustedOrOptions = false) {
    this.value = value;
    if (typeof this.value !== "string") {
      throw $nb("value");
    }
    if (typeof isTrustedOrOptions === "boolean") {
      this.isTrusted = isTrustedOrOptions;
      this.supportThemeIcons = false;
      this.supportHtml = false;
    } else {
      this.isTrusted = isTrustedOrOptions.isTrusted ?? void 0;
      this.supportThemeIcons = isTrustedOrOptions.supportThemeIcons ?? false;
      this.supportHtml = isTrustedOrOptions.supportHtml ?? false;
    }
  }
  appendText(value, newlineStyle = 0) {
    this.value += $fm(this.supportThemeIcons ? $8l(value) : value).replace(/([ \t]+)/g, (_match, g1) => "&nbsp;".repeat(g1.length)).replace(/\>/gm, "\\>").replace(/\n/g, newlineStyle === 1 ? "\\\n" : "\n\n");
    return this;
  }
  appendMarkdown(value) {
    this.value += value;
    return this;
  }
  appendCodeblock(langId, code) {
    this.value += `
${$gm(code, langId)}
`;
    return this;
  }
  appendLink(target, label3, title) {
    this.value += "[";
    this.value += this.c(label3, "]");
    this.value += "](";
    this.value += this.c(String(target), ")");
    if (title) {
      this.value += ` "${this.c(this.c(title, '"'), ")")}"`;
    }
    this.value += ")";
    return this;
  }
  c(value, ch) {
    const r2 = new RegExp($Af(ch), "g");
    return value.replace(r2, (match, offset) => {
      if (value.charAt(offset - 1) !== "\\") {
        return `\\${match}`;
      } else {
        return match;
      }
    });
  }
};
function $cm(oneOrMany) {
  if ($dm(oneOrMany)) {
    return !oneOrMany.value;
  } else if (Array.isArray(oneOrMany)) {
    return oneOrMany.every($cm);
  } else {
    return true;
  }
}
function $dm(thing) {
  if (thing instanceof $bm) {
    return true;
  } else if (thing && typeof thing === "object") {
    return typeof thing.value === "string" && (typeof thing.isTrusted === "boolean" || typeof thing.isTrusted === "object" || thing.isTrusted === void 0) && (typeof thing.supportThemeIcons === "boolean" || thing.supportThemeIcons === void 0);
  }
  return false;
}
function $em(a, b) {
  if (a === b) {
    return true;
  } else if (!a || !b) {
    return false;
  } else {
    return a.value === b.value && a.isTrusted === b.isTrusted && a.supportThemeIcons === b.supportThemeIcons && a.supportHtml === b.supportHtml && (a.baseUri === b.baseUri || !!a.baseUri && !!b.baseUri && $oh(URI.from(a.baseUri), URI.from(b.baseUri)));
  }
}
function $fm(text2) {
  return text2.replace(/[\\`*_{}[\]()#+\-!~]/g, "\\$&");
}
function $gm(code, langId) {
  const longestFenceLength = code.match(/^`+/gm)?.reduce((a, b) => a.length > b.length ? a : b).length ?? 0;
  const desiredFenceLength = longestFenceLength >= 3 ? longestFenceLength + 1 : 3;
  return [
    `${"`".repeat(desiredFenceLength)}${langId}`,
    code,
    `${"`".repeat(desiredFenceLength)}`
  ].join("\n");
}
function $hm(input) {
  return input.replace(/"/g, "&quot;");
}
function $im(text2) {
  if (!text2) {
    return text2;
  }
  return text2.replace(/\\([\\`*_{}[\]()#+\-.!~])/g, "$1");
}
function $jm(href) {
  const dimensions = [];
  const splitted = href.split("|").map((s) => s.trim());
  href = splitted[0];
  const parameters = splitted[1];
  if (parameters) {
    const heightFromParams = /height=(\d+)/.exec(parameters);
    const widthFromParams = /width=(\d+)/.exec(parameters);
    const height = heightFromParams ? heightFromParams[1] : "";
    const width2 = widthFromParams ? widthFromParams[1] : "";
    const widthIsFinite = isFinite(parseInt(width2));
    const heightIsFinite = isFinite(parseInt(height));
    if (widthIsFinite) {
      dimensions.push(`width="${width2}"`);
    }
    if (heightIsFinite) {
      dimensions.push(`height="${height}"`);
    }
  }
  return { href, dimensions };
}

// out-build/vs/base/common/idGenerator.js
var $lW = class {
  constructor(prefix) {
    this.a = prefix;
    this.b = 0;
  }
  nextId() {
    return this.a + ++this.b;
  }
};
var $mW = new $lW("id#");

// out-build/vs/base/common/marked/marked.js
function _getDefaults() {
  return {
    async: false,
    breaks: false,
    extensions: null,
    gfm: true,
    hooks: null,
    pedantic: false,
    renderer: null,
    silent: false,
    tokenizer: null,
    walkTokens: null
  };
}
var _defaults = _getDefaults();
function changeDefaults(newDefaults) {
  _defaults = newDefaults;
}
var escapeTest = /[&<>"']/;
var escapeReplace = new RegExp(escapeTest.source, "g");
var escapeTestNoEncode = /[<>"']|&(?!(#\d{1,7}|#[Xx][a-fA-F0-9]{1,6}|\w+);)/;
var escapeReplaceNoEncode = new RegExp(escapeTestNoEncode.source, "g");
var escapeReplacements = {
  "&": "&amp;",
  "<": "&lt;",
  ">": "&gt;",
  '"': "&quot;",
  "'": "&#39;"
};
var getEscapeReplacement = (ch) => escapeReplacements[ch];
function escape$1(html3, encode) {
  if (encode) {
    if (escapeTest.test(html3)) {
      return html3.replace(escapeReplace, getEscapeReplacement);
    }
  } else {
    if (escapeTestNoEncode.test(html3)) {
      return html3.replace(escapeReplaceNoEncode, getEscapeReplacement);
    }
  }
  return html3;
}
var caret = /(^|[^\[])\^/g;
function edit(regex, opt) {
  let source = typeof regex === "string" ? regex : regex.source;
  opt = opt || "";
  const obj = {
    replace: (name, val) => {
      let valSource = typeof val === "string" ? val : val.source;
      valSource = valSource.replace(caret, "$1");
      source = source.replace(name, valSource);
      return obj;
    },
    getRegex: () => {
      return new RegExp(source, opt);
    }
  };
  return obj;
}
function cleanUrl(href) {
  try {
    href = encodeURI(href).replace(/%25/g, "%");
  } catch {
    return null;
  }
  return href;
}
var noopTest = { exec: () => null };
function splitCells(tableRow, count) {
  const row = tableRow.replace(/\|/g, (match, offset, str) => {
    let escaped = false;
    let curr = offset;
    while (--curr >= 0 && str[curr] === "\\")
      escaped = !escaped;
    if (escaped) {
      return "|";
    } else {
      return " |";
    }
  }), cells = row.split(/ \|/);
  let i2 = 0;
  if (!cells[0].trim()) {
    cells.shift();
  }
  if (cells.length > 0 && !cells[cells.length - 1].trim()) {
    cells.pop();
  }
  if (count) {
    if (cells.length > count) {
      cells.splice(count);
    } else {
      while (cells.length < count)
        cells.push("");
    }
  }
  for (; i2 < cells.length; i2++) {
    cells[i2] = cells[i2].trim().replace(/\\\|/g, "|");
  }
  return cells;
}
function rtrim(str, c, invert) {
  const l = str.length;
  if (l === 0) {
    return "";
  }
  let suffLen = 0;
  while (suffLen < l) {
    const currChar = str.charAt(l - suffLen - 1);
    if (currChar === c && !invert) {
      suffLen++;
    } else if (currChar !== c && invert) {
      suffLen++;
    } else {
      break;
    }
  }
  return str.slice(0, l - suffLen);
}
function findClosingBracket(str, b) {
  if (str.indexOf(b[1]) === -1) {
    return -1;
  }
  let level = 0;
  for (let i2 = 0; i2 < str.length; i2++) {
    if (str[i2] === "\\") {
      i2++;
    } else if (str[i2] === b[0]) {
      level++;
    } else if (str[i2] === b[1]) {
      level--;
      if (level < 0) {
        return i2;
      }
    }
  }
  return -1;
}
function outputLink(cap, link2, raw, lexer2) {
  const href = link2.href;
  const title = link2.title ? escape$1(link2.title) : null;
  const text2 = cap[1].replace(/\\([\[\]])/g, "$1");
  if (cap[0].charAt(0) !== "!") {
    lexer2.state.inLink = true;
    const token = {
      type: "link",
      raw,
      href,
      title,
      text: text2,
      tokens: lexer2.inlineTokens(text2)
    };
    lexer2.state.inLink = false;
    return token;
  }
  return {
    type: "image",
    raw,
    href,
    title,
    text: escape$1(text2)
  };
}
function indentCodeCompensation(raw, text2) {
  const matchIndentToCode = raw.match(/^(\s+)(?:```)/);
  if (matchIndentToCode === null) {
    return text2;
  }
  const indentToCode = matchIndentToCode[1];
  return text2.split("\n").map((node) => {
    const matchIndentInNode = node.match(/^\s+/);
    if (matchIndentInNode === null) {
      return node;
    }
    const [indentInNode] = matchIndentInNode;
    if (indentInNode.length >= indentToCode.length) {
      return node.slice(indentToCode.length);
    }
    return node;
  }).join("\n");
}
var _Tokenizer = class {
  options;
  rules;
  // set by the lexer
  lexer;
  // set by the lexer
  constructor(options3) {
    this.options = options3 || _defaults;
  }
  space(src) {
    const cap = this.rules.block.newline.exec(src);
    if (cap && cap[0].length > 0) {
      return {
        type: "space",
        raw: cap[0]
      };
    }
  }
  code(src) {
    const cap = this.rules.block.code.exec(src);
    if (cap) {
      const text2 = cap[0].replace(/^ {1,4}/gm, "");
      return {
        type: "code",
        raw: cap[0],
        codeBlockStyle: "indented",
        text: !this.options.pedantic ? rtrim(text2, "\n") : text2
      };
    }
  }
  fences(src) {
    const cap = this.rules.block.fences.exec(src);
    if (cap) {
      const raw = cap[0];
      const text2 = indentCodeCompensation(raw, cap[3] || "");
      return {
        type: "code",
        raw,
        lang: cap[2] ? cap[2].trim().replace(this.rules.inline.anyPunctuation, "$1") : cap[2],
        text: text2
      };
    }
  }
  heading(src) {
    const cap = this.rules.block.heading.exec(src);
    if (cap) {
      let text2 = cap[2].trim();
      if (/#$/.test(text2)) {
        const trimmed = rtrim(text2, "#");
        if (this.options.pedantic) {
          text2 = trimmed.trim();
        } else if (!trimmed || / $/.test(trimmed)) {
          text2 = trimmed.trim();
        }
      }
      return {
        type: "heading",
        raw: cap[0],
        depth: cap[1].length,
        text: text2,
        tokens: this.lexer.inline(text2)
      };
    }
  }
  hr(src) {
    const cap = this.rules.block.hr.exec(src);
    if (cap) {
      return {
        type: "hr",
        raw: rtrim(cap[0], "\n")
      };
    }
  }
  blockquote(src) {
    const cap = this.rules.block.blockquote.exec(src);
    if (cap) {
      let lines = rtrim(cap[0], "\n").split("\n");
      let raw = "";
      let text2 = "";
      const tokens = [];
      while (lines.length > 0) {
        let inBlockquote = false;
        const currentLines = [];
        let i2;
        for (i2 = 0; i2 < lines.length; i2++) {
          if (/^ {0,3}>/.test(lines[i2])) {
            currentLines.push(lines[i2]);
            inBlockquote = true;
          } else if (!inBlockquote) {
            currentLines.push(lines[i2]);
          } else {
            break;
          }
        }
        lines = lines.slice(i2);
        const currentRaw = currentLines.join("\n");
        const currentText = currentRaw.replace(/\n {0,3}((?:=+|-+) *)(?=\n|$)/g, "\n    $1").replace(/^ {0,3}>[ \t]?/gm, "");
        raw = raw ? `${raw}
${currentRaw}` : currentRaw;
        text2 = text2 ? `${text2}
${currentText}` : currentText;
        const top2 = this.lexer.state.top;
        this.lexer.state.top = true;
        this.lexer.blockTokens(currentText, tokens, true);
        this.lexer.state.top = top2;
        if (lines.length === 0) {
          break;
        }
        const lastToken = tokens[tokens.length - 1];
        if (lastToken?.type === "code") {
          break;
        } else if (lastToken?.type === "blockquote") {
          const oldToken = lastToken;
          const newText = oldToken.raw + "\n" + lines.join("\n");
          const newToken = this.blockquote(newText);
          tokens[tokens.length - 1] = newToken;
          raw = raw.substring(0, raw.length - oldToken.raw.length) + newToken.raw;
          text2 = text2.substring(0, text2.length - oldToken.text.length) + newToken.text;
          break;
        } else if (lastToken?.type === "list") {
          const oldToken = lastToken;
          const newText = oldToken.raw + "\n" + lines.join("\n");
          const newToken = this.list(newText);
          tokens[tokens.length - 1] = newToken;
          raw = raw.substring(0, raw.length - lastToken.raw.length) + newToken.raw;
          text2 = text2.substring(0, text2.length - oldToken.raw.length) + newToken.raw;
          lines = newText.substring(tokens[tokens.length - 1].raw.length).split("\n");
          continue;
        }
      }
      return {
        type: "blockquote",
        raw,
        tokens,
        text: text2
      };
    }
  }
  list(src) {
    let cap = this.rules.block.list.exec(src);
    if (cap) {
      let bull = cap[1].trim();
      const isordered = bull.length > 1;
      const list2 = {
        type: "list",
        raw: "",
        ordered: isordered,
        start: isordered ? +bull.slice(0, -1) : "",
        loose: false,
        items: []
      };
      bull = isordered ? `\\d{1,9}\\${bull.slice(-1)}` : `\\${bull}`;
      if (this.options.pedantic) {
        bull = isordered ? bull : "[*+-]";
      }
      const itemRegex = new RegExp(`^( {0,3}${bull})((?:[	 ][^\\n]*)?(?:\\n|$))`);
      let endsWithBlankLine = false;
      while (src) {
        let endEarly = false;
        let raw = "";
        let itemContents = "";
        if (!(cap = itemRegex.exec(src))) {
          break;
        }
        if (this.rules.block.hr.test(src)) {
          break;
        }
        raw = cap[0];
        src = src.substring(raw.length);
        let line = cap[2].split("\n", 1)[0].replace(/^\t+/, (t) => " ".repeat(3 * t.length));
        let nextLine = src.split("\n", 1)[0];
        let blankLine = !line.trim();
        let indent = 0;
        if (this.options.pedantic) {
          indent = 2;
          itemContents = line.trimStart();
        } else if (blankLine) {
          indent = cap[1].length + 1;
        } else {
          indent = cap[2].search(/[^ ]/);
          indent = indent > 4 ? 1 : indent;
          itemContents = line.slice(indent);
          indent += cap[1].length;
        }
        if (blankLine && /^ *$/.test(nextLine)) {
          raw += nextLine + "\n";
          src = src.substring(nextLine.length + 1);
          endEarly = true;
        }
        if (!endEarly) {
          const nextBulletRegex = new RegExp(`^ {0,${Math.min(3, indent - 1)}}(?:[*+-]|\\d{1,9}[.)])((?:[ 	][^\\n]*)?(?:\\n|$))`);
          const hrRegex = new RegExp(`^ {0,${Math.min(3, indent - 1)}}((?:- *){3,}|(?:_ *){3,}|(?:\\* *){3,})(?:\\n+|$)`);
          const fencesBeginRegex = new RegExp(`^ {0,${Math.min(3, indent - 1)}}(?:\`\`\`|~~~)`);
          const headingBeginRegex = new RegExp(`^ {0,${Math.min(3, indent - 1)}}#`);
          while (src) {
            const rawLine = src.split("\n", 1)[0];
            nextLine = rawLine;
            if (this.options.pedantic) {
              nextLine = nextLine.replace(/^ {1,4}(?=( {4})*[^ ])/g, "  ");
            }
            if (fencesBeginRegex.test(nextLine)) {
              break;
            }
            if (headingBeginRegex.test(nextLine)) {
              break;
            }
            if (nextBulletRegex.test(nextLine)) {
              break;
            }
            if (hrRegex.test(src)) {
              break;
            }
            if (nextLine.search(/[^ ]/) >= indent || !nextLine.trim()) {
              itemContents += "\n" + nextLine.slice(indent);
            } else {
              if (blankLine) {
                break;
              }
              if (line.search(/[^ ]/) >= 4) {
                break;
              }
              if (fencesBeginRegex.test(line)) {
                break;
              }
              if (headingBeginRegex.test(line)) {
                break;
              }
              if (hrRegex.test(line)) {
                break;
              }
              itemContents += "\n" + nextLine;
            }
            if (!blankLine && !nextLine.trim()) {
              blankLine = true;
            }
            raw += rawLine + "\n";
            src = src.substring(rawLine.length + 1);
            line = nextLine.slice(indent);
          }
        }
        if (!list2.loose) {
          if (endsWithBlankLine) {
            list2.loose = true;
          } else if (/\n *\n *$/.test(raw)) {
            endsWithBlankLine = true;
          }
        }
        let istask = null;
        let ischecked;
        if (this.options.gfm) {
          istask = /^\[[ xX]\] /.exec(itemContents);
          if (istask) {
            ischecked = istask[0] !== "[ ] ";
            itemContents = itemContents.replace(/^\[[ xX]\] +/, "");
          }
        }
        list2.items.push({
          type: "list_item",
          raw,
          task: !!istask,
          checked: ischecked,
          loose: false,
          text: itemContents,
          tokens: []
        });
        list2.raw += raw;
      }
      list2.items[list2.items.length - 1].raw = list2.items[list2.items.length - 1].raw.trimEnd();
      list2.items[list2.items.length - 1].text = list2.items[list2.items.length - 1].text.trimEnd();
      list2.raw = list2.raw.trimEnd();
      for (let i2 = 0; i2 < list2.items.length; i2++) {
        this.lexer.state.top = false;
        list2.items[i2].tokens = this.lexer.blockTokens(list2.items[i2].text, []);
        if (!list2.loose) {
          const spacers = list2.items[i2].tokens.filter((t) => t.type === "space");
          const hasMultipleLineBreaks = spacers.length > 0 && spacers.some((t) => /\n.*\n/.test(t.raw));
          list2.loose = hasMultipleLineBreaks;
        }
      }
      if (list2.loose) {
        for (let i2 = 0; i2 < list2.items.length; i2++) {
          list2.items[i2].loose = true;
        }
      }
      return list2;
    }
  }
  html(src) {
    const cap = this.rules.block.html.exec(src);
    if (cap) {
      const token = {
        type: "html",
        block: true,
        raw: cap[0],
        pre: cap[1] === "pre" || cap[1] === "script" || cap[1] === "style",
        text: cap[0]
      };
      return token;
    }
  }
  def(src) {
    const cap = this.rules.block.def.exec(src);
    if (cap) {
      const tag2 = cap[1].toLowerCase().replace(/\s+/g, " ");
      const href = cap[2] ? cap[2].replace(/^<(.*)>$/, "$1").replace(this.rules.inline.anyPunctuation, "$1") : "";
      const title = cap[3] ? cap[3].substring(1, cap[3].length - 1).replace(this.rules.inline.anyPunctuation, "$1") : cap[3];
      return {
        type: "def",
        tag: tag2,
        raw: cap[0],
        href,
        title
      };
    }
  }
  table(src) {
    const cap = this.rules.block.table.exec(src);
    if (!cap) {
      return;
    }
    if (!/[:|]/.test(cap[2])) {
      return;
    }
    const headers = splitCells(cap[1]);
    const aligns = cap[2].replace(/^\||\| *$/g, "").split("|");
    const rows = cap[3] && cap[3].trim() ? cap[3].replace(/\n[ \t]*$/, "").split("\n") : [];
    const item = {
      type: "table",
      raw: cap[0],
      header: [],
      align: [],
      rows: []
    };
    if (headers.length !== aligns.length) {
      return;
    }
    for (const align of aligns) {
      if (/^ *-+: *$/.test(align)) {
        item.align.push("right");
      } else if (/^ *:-+: *$/.test(align)) {
        item.align.push("center");
      } else if (/^ *:-+ *$/.test(align)) {
        item.align.push("left");
      } else {
        item.align.push(null);
      }
    }
    for (let i2 = 0; i2 < headers.length; i2++) {
      item.header.push({
        text: headers[i2],
        tokens: this.lexer.inline(headers[i2]),
        header: true,
        align: item.align[i2]
      });
    }
    for (const row of rows) {
      item.rows.push(splitCells(row, item.header.length).map((cell, i2) => {
        return {
          text: cell,
          tokens: this.lexer.inline(cell),
          header: false,
          align: item.align[i2]
        };
      }));
    }
    return item;
  }
  lheading(src) {
    const cap = this.rules.block.lheading.exec(src);
    if (cap) {
      return {
        type: "heading",
        raw: cap[0],
        depth: cap[2].charAt(0) === "=" ? 1 : 2,
        text: cap[1],
        tokens: this.lexer.inline(cap[1])
      };
    }
  }
  paragraph(src) {
    const cap = this.rules.block.paragraph.exec(src);
    if (cap) {
      const text2 = cap[1].charAt(cap[1].length - 1) === "\n" ? cap[1].slice(0, -1) : cap[1];
      return {
        type: "paragraph",
        raw: cap[0],
        text: text2,
        tokens: this.lexer.inline(text2)
      };
    }
  }
  text(src) {
    const cap = this.rules.block.text.exec(src);
    if (cap) {
      return {
        type: "text",
        raw: cap[0],
        text: cap[0],
        tokens: this.lexer.inline(cap[0])
      };
    }
  }
  escape(src) {
    const cap = this.rules.inline.escape.exec(src);
    if (cap) {
      return {
        type: "escape",
        raw: cap[0],
        text: escape$1(cap[1])
      };
    }
  }
  tag(src) {
    const cap = this.rules.inline.tag.exec(src);
    if (cap) {
      if (!this.lexer.state.inLink && /^<a /i.test(cap[0])) {
        this.lexer.state.inLink = true;
      } else if (this.lexer.state.inLink && /^<\/a>/i.test(cap[0])) {
        this.lexer.state.inLink = false;
      }
      if (!this.lexer.state.inRawBlock && /^<(pre|code|kbd|script)(\s|>)/i.test(cap[0])) {
        this.lexer.state.inRawBlock = true;
      } else if (this.lexer.state.inRawBlock && /^<\/(pre|code|kbd|script)(\s|>)/i.test(cap[0])) {
        this.lexer.state.inRawBlock = false;
      }
      return {
        type: "html",
        raw: cap[0],
        inLink: this.lexer.state.inLink,
        inRawBlock: this.lexer.state.inRawBlock,
        block: false,
        text: cap[0]
      };
    }
  }
  link(src) {
    const cap = this.rules.inline.link.exec(src);
    if (cap) {
      const trimmedUrl = cap[2].trim();
      if (!this.options.pedantic && /^</.test(trimmedUrl)) {
        if (!/>$/.test(trimmedUrl)) {
          return;
        }
        const rtrimSlash = rtrim(trimmedUrl.slice(0, -1), "\\");
        if ((trimmedUrl.length - rtrimSlash.length) % 2 === 0) {
          return;
        }
      } else {
        const lastParenIndex = findClosingBracket(cap[2], "()");
        if (lastParenIndex > -1) {
          const start = cap[0].indexOf("!") === 0 ? 5 : 4;
          const linkLen = start + cap[1].length + lastParenIndex;
          cap[2] = cap[2].substring(0, lastParenIndex);
          cap[0] = cap[0].substring(0, linkLen).trim();
          cap[3] = "";
        }
      }
      let href = cap[2];
      let title = "";
      if (this.options.pedantic) {
        const link2 = /^([^'"]*[^\s])\s+(['"])(.*)\2/.exec(href);
        if (link2) {
          href = link2[1];
          title = link2[3];
        }
      } else {
        title = cap[3] ? cap[3].slice(1, -1) : "";
      }
      href = href.trim();
      if (/^</.test(href)) {
        if (this.options.pedantic && !/>$/.test(trimmedUrl)) {
          href = href.slice(1);
        } else {
          href = href.slice(1, -1);
        }
      }
      return outputLink(cap, {
        href: href ? href.replace(this.rules.inline.anyPunctuation, "$1") : href,
        title: title ? title.replace(this.rules.inline.anyPunctuation, "$1") : title
      }, cap[0], this.lexer);
    }
  }
  reflink(src, links) {
    let cap;
    if ((cap = this.rules.inline.reflink.exec(src)) || (cap = this.rules.inline.nolink.exec(src))) {
      const linkString = (cap[2] || cap[1]).replace(/\s+/g, " ");
      const link2 = links[linkString.toLowerCase()];
      if (!link2) {
        const text2 = cap[0].charAt(0);
        return {
          type: "text",
          raw: text2,
          text: text2
        };
      }
      return outputLink(cap, link2, cap[0], this.lexer);
    }
  }
  emStrong(src, maskedSrc, prevChar = "") {
    let match = this.rules.inline.emStrongLDelim.exec(src);
    if (!match)
      return;
    if (match[3] && prevChar.match(/[\p{L}\p{N}]/u))
      return;
    const nextChar = match[1] || match[2] || "";
    if (!nextChar || !prevChar || this.rules.inline.punctuation.exec(prevChar)) {
      const lLength = [...match[0]].length - 1;
      let rDelim, rLength, delimTotal = lLength, midDelimTotal = 0;
      const endReg = match[0][0] === "*" ? this.rules.inline.emStrongRDelimAst : this.rules.inline.emStrongRDelimUnd;
      endReg.lastIndex = 0;
      maskedSrc = maskedSrc.slice(-1 * src.length + lLength);
      while ((match = endReg.exec(maskedSrc)) != null) {
        rDelim = match[1] || match[2] || match[3] || match[4] || match[5] || match[6];
        if (!rDelim)
          continue;
        rLength = [...rDelim].length;
        if (match[3] || match[4]) {
          delimTotal += rLength;
          continue;
        } else if (match[5] || match[6]) {
          if (lLength % 3 && !((lLength + rLength) % 3)) {
            midDelimTotal += rLength;
            continue;
          }
        }
        delimTotal -= rLength;
        if (delimTotal > 0)
          continue;
        rLength = Math.min(rLength, rLength + delimTotal + midDelimTotal);
        const lastCharLength = [...match[0]][0].length;
        const raw = src.slice(0, lLength + match.index + lastCharLength + rLength);
        if (Math.min(lLength, rLength) % 2) {
          const text3 = raw.slice(1, -1);
          return {
            type: "em",
            raw,
            text: text3,
            tokens: this.lexer.inlineTokens(text3)
          };
        }
        const text2 = raw.slice(2, -2);
        return {
          type: "strong",
          raw,
          text: text2,
          tokens: this.lexer.inlineTokens(text2)
        };
      }
    }
  }
  codespan(src) {
    const cap = this.rules.inline.code.exec(src);
    if (cap) {
      let text2 = cap[2].replace(/\n/g, " ");
      const hasNonSpaceChars = /[^ ]/.test(text2);
      const hasSpaceCharsOnBothEnds = /^ /.test(text2) && / $/.test(text2);
      if (hasNonSpaceChars && hasSpaceCharsOnBothEnds) {
        text2 = text2.substring(1, text2.length - 1);
      }
      text2 = escape$1(text2, true);
      return {
        type: "codespan",
        raw: cap[0],
        text: text2
      };
    }
  }
  br(src) {
    const cap = this.rules.inline.br.exec(src);
    if (cap) {
      return {
        type: "br",
        raw: cap[0]
      };
    }
  }
  del(src) {
    const cap = this.rules.inline.del.exec(src);
    if (cap) {
      return {
        type: "del",
        raw: cap[0],
        text: cap[2],
        tokens: this.lexer.inlineTokens(cap[2])
      };
    }
  }
  autolink(src) {
    const cap = this.rules.inline.autolink.exec(src);
    if (cap) {
      let text2, href;
      if (cap[2] === "@") {
        text2 = escape$1(cap[1]);
        href = "mailto:" + text2;
      } else {
        text2 = escape$1(cap[1]);
        href = text2;
      }
      return {
        type: "link",
        raw: cap[0],
        text: text2,
        href,
        tokens: [
          {
            type: "text",
            raw: text2,
            text: text2
          }
        ]
      };
    }
  }
  url(src) {
    let cap;
    if (cap = this.rules.inline.url.exec(src)) {
      let text2, href;
      if (cap[2] === "@") {
        text2 = escape$1(cap[0]);
        href = "mailto:" + text2;
      } else {
        let prevCapZero;
        do {
          prevCapZero = cap[0];
          cap[0] = this.rules.inline._backpedal.exec(cap[0])?.[0] ?? "";
        } while (prevCapZero !== cap[0]);
        text2 = escape$1(cap[0]);
        if (cap[1] === "www.") {
          href = "http://" + cap[0];
        } else {
          href = cap[0];
        }
      }
      return {
        type: "link",
        raw: cap[0],
        text: text2,
        href,
        tokens: [
          {
            type: "text",
            raw: text2,
            text: text2
          }
        ]
      };
    }
  }
  inlineText(src) {
    const cap = this.rules.inline.text.exec(src);
    if (cap) {
      let text2;
      if (this.lexer.state.inRawBlock) {
        text2 = cap[0];
      } else {
        text2 = escape$1(cap[0]);
      }
      return {
        type: "text",
        raw: cap[0],
        text: text2
      };
    }
  }
};
var newline = /^(?: *(?:\n|$))+/;
var blockCode = /^( {4}[^\n]+(?:\n(?: *(?:\n|$))*)?)+/;
var fences = /^ {0,3}(`{3,}(?=[^`\n]*(?:\n|$))|~{3,})([^\n]*)(?:\n|$)(?:|([\s\S]*?)(?:\n|$))(?: {0,3}\1[~`]* *(?=\n|$)|$)/;
var hr = /^ {0,3}((?:-[\t ]*){3,}|(?:_[ \t]*){3,}|(?:\*[ \t]*){3,})(?:\n+|$)/;
var heading = /^ {0,3}(#{1,6})(?=\s|$)(.*)(?:\n+|$)/;
var bullet = /(?:[*+-]|\d{1,9}[.)])/;
var lheading = edit(/^(?!bull |blockCode|fences|blockquote|heading|html)((?:.|\n(?!\s*?\n|bull |blockCode|fences|blockquote|heading|html))+?)\n {0,3}(=+|-+) *(?:\n+|$)/).replace(/bull/g, bullet).replace(/blockCode/g, / {4}/).replace(/fences/g, / {0,3}(?:`{3,}|~{3,})/).replace(/blockquote/g, / {0,3}>/).replace(/heading/g, / {0,3}#{1,6}/).replace(/html/g, / {0,3}<[^\n>]+>\n/).getRegex();
var _paragraph = /^([^\n]+(?:\n(?!hr|heading|lheading|blockquote|fences|list|html|table| +\n)[^\n]+)*)/;
var blockText = /^[^\n]+/;
var _blockLabel = /(?!\s*\])(?:\\.|[^\[\]\\])+/;
var def = edit(/^ {0,3}\[(label)\]: *(?:\n *)?([^<\s][^\s]*|<.*?>)(?:(?: +(?:\n *)?| *\n *)(title))? *(?:\n+|$)/).replace("label", _blockLabel).replace("title", /(?:"(?:\\"?|[^"\\])*"|'[^'\n]*(?:\n[^'\n]+)*\n?'|\([^()]*\))/).getRegex();
var list = edit(/^( {0,3}bull)([ \t][^\n]+?)?(?:\n|$)/).replace(/bull/g, bullet).getRegex();
var _tag = "address|article|aside|base|basefont|blockquote|body|caption|center|col|colgroup|dd|details|dialog|dir|div|dl|dt|fieldset|figcaption|figure|footer|form|frame|frameset|h[1-6]|head|header|hr|html|iframe|legend|li|link|main|menu|menuitem|meta|nav|noframes|ol|optgroup|option|p|param|search|section|summary|table|tbody|td|tfoot|th|thead|title|tr|track|ul";
var _comment = /<!--(?:-?>|[\s\S]*?(?:-->|$))/;
var html2 = edit("^ {0,3}(?:<(script|pre|style|textarea)[\\s>][\\s\\S]*?(?:</\\1>[^\\n]*\\n+|$)|comment[^\\n]*(\\n+|$)|<\\?[\\s\\S]*?(?:\\?>\\n*|$)|<![A-Z][\\s\\S]*?(?:>\\n*|$)|<!\\[CDATA\\[[\\s\\S]*?(?:\\]\\]>\\n*|$)|</?(tag)(?: +|\\n|/?>)[\\s\\S]*?(?:(?:\\n *)+\\n|$)|<(?!script|pre|style|textarea)([a-z][\\w-]*)(?:attribute)*? */?>(?=[ \\t]*(?:\\n|$))[\\s\\S]*?(?:(?:\\n *)+\\n|$)|</(?!script|pre|style|textarea)[a-z][\\w-]*\\s*>(?=[ \\t]*(?:\\n|$))[\\s\\S]*?(?:(?:\\n *)+\\n|$))", "i").replace("comment", _comment).replace("tag", _tag).replace("attribute", / +[a-zA-Z:_][\w.:-]*(?: *= *"[^"\n]*"| *= *'[^'\n]*'| *= *[^\s"'=<>`]+)?/).getRegex();
var paragraph = edit(_paragraph).replace("hr", hr).replace("heading", " {0,3}#{1,6}(?:\\s|$)").replace("|lheading", "").replace("|table", "").replace("blockquote", " {0,3}>").replace("fences", " {0,3}(?:`{3,}(?=[^`\\n]*\\n)|~{3,})[^\\n]*\\n").replace("list", " {0,3}(?:[*+-]|1[.)]) ").replace("html", "</?(?:tag)(?: +|\\n|/?>)|<(?:script|pre|style|textarea|!--)").replace("tag", _tag).getRegex();
var blockquote = edit(/^( {0,3}> ?(paragraph|[^\n]*)(?:\n|$))+/).replace("paragraph", paragraph).getRegex();
var blockNormal = {
  blockquote,
  code: blockCode,
  def,
  fences,
  heading,
  hr,
  html: html2,
  lheading,
  list,
  newline,
  paragraph,
  table: noopTest,
  text: blockText
};
var gfmTable = edit("^ *([^\\n ].*)\\n {0,3}((?:\\| *)?:?-+:? *(?:\\| *:?-+:? *)*(?:\\| *)?)(?:\\n((?:(?! *\\n|hr|heading|blockquote|code|fences|list|html).*(?:\\n|$))*)\\n*|$)").replace("hr", hr).replace("heading", " {0,3}#{1,6}(?:\\s|$)").replace("blockquote", " {0,3}>").replace("code", " {4}[^\\n]").replace("fences", " {0,3}(?:`{3,}(?=[^`\\n]*\\n)|~{3,})[^\\n]*\\n").replace("list", " {0,3}(?:[*+-]|1[.)]) ").replace("html", "</?(?:tag)(?: +|\\n|/?>)|<(?:script|pre|style|textarea|!--)").replace("tag", _tag).getRegex();
var blockGfm = {
  ...blockNormal,
  table: gfmTable,
  paragraph: edit(_paragraph).replace("hr", hr).replace("heading", " {0,3}#{1,6}(?:\\s|$)").replace("|lheading", "").replace("table", gfmTable).replace("blockquote", " {0,3}>").replace("fences", " {0,3}(?:`{3,}(?=[^`\\n]*\\n)|~{3,})[^\\n]*\\n").replace("list", " {0,3}(?:[*+-]|1[.)]) ").replace("html", "</?(?:tag)(?: +|\\n|/?>)|<(?:script|pre|style|textarea|!--)").replace("tag", _tag).getRegex()
};
var blockPedantic = {
  ...blockNormal,
  html: edit(`^ *(?:comment *(?:\\n|\\s*$)|<(tag)[\\s\\S]+?</\\1> *(?:\\n{2,}|\\s*$)|<tag(?:"[^"]*"|'[^']*'|\\s[^'"/>\\s]*)*?/?> *(?:\\n{2,}|\\s*$))`).replace("comment", _comment).replace(/tag/g, "(?!(?:a|em|strong|small|s|cite|q|dfn|abbr|data|time|code|var|samp|kbd|sub|sup|i|b|u|mark|ruby|rt|rp|bdi|bdo|span|br|wbr|ins|del|img)\\b)\\w+(?!:|[^\\w\\s@]*@)\\b").getRegex(),
  def: /^ *\[([^\]]+)\]: *<?([^\s>]+)>?(?: +(["(][^\n]+[")]))? *(?:\n+|$)/,
  heading: /^(#{1,6})(.*)(?:\n+|$)/,
  fences: noopTest,
  // fences not supported
  lheading: /^(.+?)\n {0,3}(=+|-+) *(?:\n+|$)/,
  paragraph: edit(_paragraph).replace("hr", hr).replace("heading", " *#{1,6} *[^\n]").replace("lheading", lheading).replace("|table", "").replace("blockquote", " {0,3}>").replace("|fences", "").replace("|list", "").replace("|html", "").replace("|tag", "").getRegex()
};
var escape = /^\\([!"#$%&'()*+,\-./:;<=>?@\[\]\\^_`{|}~])/;
var inlineCode = /^(`+)([^`]|[^`][\s\S]*?[^`])\1(?!`)/;
var br = /^( {2,}|\\)\n(?!\s*$)/;
var inlineText = /^(`+|[^`])(?:(?= {2,}\n)|[\s\S]*?(?:(?=[\\<!\[`*_]|\b_|$)|[^ ](?= {2,}\n)))/;
var _punctuation = "\\p{P}\\p{S}";
var punctuation = edit(/^((?![*_])[\spunctuation])/, "u").replace(/punctuation/g, _punctuation).getRegex();
var blockSkip = /\[[^[\]]*?\]\([^\(\)]*?\)|`[^`]*?`|<[^<>]*?>/g;
var emStrongLDelim = edit(/^(?:\*+(?:((?!\*)[punct])|[^\s*]))|^_+(?:((?!_)[punct])|([^\s_]))/, "u").replace(/punct/g, _punctuation).getRegex();
var emStrongRDelimAst = edit("^[^_*]*?__[^_*]*?\\*[^_*]*?(?=__)|[^*]+(?=[^*])|(?!\\*)[punct](\\*+)(?=[\\s]|$)|[^punct\\s](\\*+)(?!\\*)(?=[punct\\s]|$)|(?!\\*)[punct\\s](\\*+)(?=[^punct\\s])|[\\s](\\*+)(?!\\*)(?=[punct])|(?!\\*)[punct](\\*+)(?!\\*)(?=[punct])|[^punct\\s](\\*+)(?=[^punct\\s])", "gu").replace(/punct/g, _punctuation).getRegex();
var emStrongRDelimUnd = edit("^[^_*]*?\\*\\*[^_*]*?_[^_*]*?(?=\\*\\*)|[^_]+(?=[^_])|(?!_)[punct](_+)(?=[\\s]|$)|[^punct\\s](_+)(?!_)(?=[punct\\s]|$)|(?!_)[punct\\s](_+)(?=[^punct\\s])|[\\s](_+)(?!_)(?=[punct])|(?!_)[punct](_+)(?!_)(?=[punct])", "gu").replace(/punct/g, _punctuation).getRegex();
var anyPunctuation = edit(/\\([punct])/, "gu").replace(/punct/g, _punctuation).getRegex();
var autolink = edit(/^<(scheme:[^\s\x00-\x1f<>]*|email)>/).replace("scheme", /[a-zA-Z][a-zA-Z0-9+.-]{1,31}/).replace("email", /[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+(@)[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)+(?![-_])/).getRegex();
var _inlineComment = edit(_comment).replace("(?:-->|$)", "-->").getRegex();
var tag = edit("^comment|^</[a-zA-Z][\\w:-]*\\s*>|^<[a-zA-Z][\\w-]*(?:attribute)*?\\s*/?>|^<\\?[\\s\\S]*?\\?>|^<![a-zA-Z]+\\s[\\s\\S]*?>|^<!\\[CDATA\\[[\\s\\S]*?\\]\\]>").replace("comment", _inlineComment).replace("attribute", /\s+[a-zA-Z:_][\w.:-]*(?:\s*=\s*"[^"]*"|\s*=\s*'[^']*'|\s*=\s*[^\s"'=<>`]+)?/).getRegex();
var _inlineLabel = /(?:\[(?:\\.|[^\[\]\\])*\]|\\.|`[^`]*`|[^\[\]\\`])*?/;
var link = edit(/^!?\[(label)\]\(\s*(href)(?:\s+(title))?\s*\)/).replace("label", _inlineLabel).replace("href", /<(?:\\.|[^\n<>\\])+>|[^\s\x00-\x1f]*/).replace("title", /"(?:\\"?|[^"\\])*"|'(?:\\'?|[^'\\])*'|\((?:\\\)?|[^)\\])*\)/).getRegex();
var reflink = edit(/^!?\[(label)\]\[(ref)\]/).replace("label", _inlineLabel).replace("ref", _blockLabel).getRegex();
var nolink = edit(/^!?\[(ref)\](?:\[\])?/).replace("ref", _blockLabel).getRegex();
var reflinkSearch = edit("reflink|nolink(?!\\()", "g").replace("reflink", reflink).replace("nolink", nolink).getRegex();
var inlineNormal = {
  _backpedal: noopTest,
  // only used for GFM url
  anyPunctuation,
  autolink,
  blockSkip,
  br,
  code: inlineCode,
  del: noopTest,
  emStrongLDelim,
  emStrongRDelimAst,
  emStrongRDelimUnd,
  escape,
  link,
  nolink,
  punctuation,
  reflink,
  reflinkSearch,
  tag,
  text: inlineText,
  url: noopTest
};
var inlinePedantic = {
  ...inlineNormal,
  link: edit(/^!?\[(label)\]\((.*?)\)/).replace("label", _inlineLabel).getRegex(),
  reflink: edit(/^!?\[(label)\]\s*\[([^\]]*)\]/).replace("label", _inlineLabel).getRegex()
};
var inlineGfm = {
  ...inlineNormal,
  escape: edit(escape).replace("])", "~|])").getRegex(),
  url: edit(/^((?:ftp|https?):\/\/|www\.)(?:[a-zA-Z0-9\-]+\.?)+[^\s<]*|^email/, "i").replace("email", /[A-Za-z0-9._+-]+(@)[a-zA-Z0-9-_]+(?:\.[a-zA-Z0-9-_]*[a-zA-Z0-9])+(?![-_])/).getRegex(),
  _backpedal: /(?:[^?!.,:;*_'"~()&]+|\([^)]*\)|&(?![a-zA-Z0-9]+;$)|[?!.,:;*_'"~)]+(?!$))+/,
  del: /^(~~?)(?=[^\s~])([\s\S]*?[^\s~])\1(?=[^~]|$)/,
  text: /^([`~]+|[^`~])(?:(?= {2,}\n)|(?=[a-zA-Z0-9.!#$%&'*+\/=?_`{\|}~-]+@)|[\s\S]*?(?:(?=[\\<!\[`*~_]|\b_|https?:\/\/|ftp:\/\/|www\.|$)|[^ ](?= {2,}\n)|[^a-zA-Z0-9.!#$%&'*+\/=?_`{\|}~-](?=[a-zA-Z0-9.!#$%&'*+\/=?_`{\|}~-]+@)))/
};
var inlineBreaks = {
  ...inlineGfm,
  br: edit(br).replace("{2,}", "*").getRegex(),
  text: edit(inlineGfm.text).replace("\\b_", "\\b_| {2,}\\n").replace(/\{2,\}/g, "*").getRegex()
};
var block = {
  normal: blockNormal,
  gfm: blockGfm,
  pedantic: blockPedantic
};
var inline = {
  normal: inlineNormal,
  gfm: inlineGfm,
  breaks: inlineBreaks,
  pedantic: inlinePedantic
};
var _Lexer = class __Lexer {
  tokens;
  options;
  state;
  tokenizer;
  inlineQueue;
  constructor(options3) {
    this.tokens = [];
    this.tokens.links = /* @__PURE__ */ Object.create(null);
    this.options = options3 || _defaults;
    this.options.tokenizer = this.options.tokenizer || new _Tokenizer();
    this.tokenizer = this.options.tokenizer;
    this.tokenizer.options = this.options;
    this.tokenizer.lexer = this;
    this.inlineQueue = [];
    this.state = {
      inLink: false,
      inRawBlock: false,
      top: true
    };
    const rules = {
      block: block.normal,
      inline: inline.normal
    };
    if (this.options.pedantic) {
      rules.block = block.pedantic;
      rules.inline = inline.pedantic;
    } else if (this.options.gfm) {
      rules.block = block.gfm;
      if (this.options.breaks) {
        rules.inline = inline.breaks;
      } else {
        rules.inline = inline.gfm;
      }
    }
    this.tokenizer.rules = rules;
  }
  /**
   * Expose Rules
   */
  static get rules() {
    return {
      block,
      inline
    };
  }
  /**
   * Static Lex Method
   */
  static lex(src, options3) {
    const lexer2 = new __Lexer(options3);
    return lexer2.lex(src);
  }
  /**
   * Static Lex Inline Method
   */
  static lexInline(src, options3) {
    const lexer2 = new __Lexer(options3);
    return lexer2.inlineTokens(src);
  }
  /**
   * Preprocessing
   */
  lex(src) {
    src = src.replace(/\r\n|\r/g, "\n");
    this.blockTokens(src, this.tokens);
    for (let i2 = 0; i2 < this.inlineQueue.length; i2++) {
      const next = this.inlineQueue[i2];
      this.inlineTokens(next.src, next.tokens);
    }
    this.inlineQueue = [];
    return this.tokens;
  }
  blockTokens(src, tokens = [], lastParagraphClipped = false) {
    if (this.options.pedantic) {
      src = src.replace(/\t/g, "    ").replace(/^ +$/gm, "");
    } else {
      src = src.replace(/^( *)(\t+)/gm, (_, leading, tabs) => {
        return leading + "    ".repeat(tabs.length);
      });
    }
    let token;
    let lastToken;
    let cutSrc;
    while (src) {
      if (this.options.extensions && this.options.extensions.block && this.options.extensions.block.some((extTokenizer) => {
        if (token = extTokenizer.call({ lexer: this }, src, tokens)) {
          src = src.substring(token.raw.length);
          tokens.push(token);
          return true;
        }
        return false;
      })) {
        continue;
      }
      if (token = this.tokenizer.space(src)) {
        src = src.substring(token.raw.length);
        if (token.raw.length === 1 && tokens.length > 0) {
          tokens[tokens.length - 1].raw += "\n";
        } else {
          tokens.push(token);
        }
        continue;
      }
      if (token = this.tokenizer.code(src)) {
        src = src.substring(token.raw.length);
        lastToken = tokens[tokens.length - 1];
        if (lastToken && (lastToken.type === "paragraph" || lastToken.type === "text")) {
          lastToken.raw += "\n" + token.raw;
          lastToken.text += "\n" + token.text;
          this.inlineQueue[this.inlineQueue.length - 1].src = lastToken.text;
        } else {
          tokens.push(token);
        }
        continue;
      }
      if (token = this.tokenizer.fences(src)) {
        src = src.substring(token.raw.length);
        tokens.push(token);
        continue;
      }
      if (token = this.tokenizer.heading(src)) {
        src = src.substring(token.raw.length);
        tokens.push(token);
        continue;
      }
      if (token = this.tokenizer.hr(src)) {
        src = src.substring(token.raw.length);
        tokens.push(token);
        continue;
      }
      if (token = this.tokenizer.blockquote(src)) {
        src = src.substring(token.raw.length);
        tokens.push(token);
        continue;
      }
      if (token = this.tokenizer.list(src)) {
        src = src.substring(token.raw.length);
        tokens.push(token);
        continue;
      }
      if (token = this.tokenizer.html(src)) {
        src = src.substring(token.raw.length);
        tokens.push(token);
        continue;
      }
      if (token = this.tokenizer.def(src)) {
        src = src.substring(token.raw.length);
        lastToken = tokens[tokens.length - 1];
        if (lastToken && (lastToken.type === "paragraph" || lastToken.type === "text")) {
          lastToken.raw += "\n" + token.raw;
          lastToken.text += "\n" + token.raw;
          this.inlineQueue[this.inlineQueue.length - 1].src = lastToken.text;
        } else if (!this.tokens.links[token.tag]) {
          this.tokens.links[token.tag] = {
            href: token.href,
            title: token.title
          };
        }
        continue;
      }
      if (token = this.tokenizer.table(src)) {
        src = src.substring(token.raw.length);
        tokens.push(token);
        continue;
      }
      if (token = this.tokenizer.lheading(src)) {
        src = src.substring(token.raw.length);
        tokens.push(token);
        continue;
      }
      cutSrc = src;
      if (this.options.extensions && this.options.extensions.startBlock) {
        let startIndex = Infinity;
        const tempSrc = src.slice(1);
        let tempStart;
        this.options.extensions.startBlock.forEach((getStartIndex) => {
          tempStart = getStartIndex.call({ lexer: this }, tempSrc);
          if (typeof tempStart === "number" && tempStart >= 0) {
            startIndex = Math.min(startIndex, tempStart);
          }
        });
        if (startIndex < Infinity && startIndex >= 0) {
          cutSrc = src.substring(0, startIndex + 1);
        }
      }
      if (this.state.top && (token = this.tokenizer.paragraph(cutSrc))) {
        lastToken = tokens[tokens.length - 1];
        if (lastParagraphClipped && lastToken?.type === "paragraph") {
          lastToken.raw += "\n" + token.raw;
          lastToken.text += "\n" + token.text;
          this.inlineQueue.pop();
          this.inlineQueue[this.inlineQueue.length - 1].src = lastToken.text;
        } else {
          tokens.push(token);
        }
        lastParagraphClipped = cutSrc.length !== src.length;
        src = src.substring(token.raw.length);
        continue;
      }
      if (token = this.tokenizer.text(src)) {
        src = src.substring(token.raw.length);
        lastToken = tokens[tokens.length - 1];
        if (lastToken && lastToken.type === "text") {
          lastToken.raw += "\n" + token.raw;
          lastToken.text += "\n" + token.text;
          this.inlineQueue.pop();
          this.inlineQueue[this.inlineQueue.length - 1].src = lastToken.text;
        } else {
          tokens.push(token);
        }
        continue;
      }
      if (src) {
        const errMsg = "Infinite loop on byte: " + src.charCodeAt(0);
        if (this.options.silent) {
          console.error(errMsg);
          break;
        } else {
          throw new Error(errMsg);
        }
      }
    }
    this.state.top = true;
    return tokens;
  }
  inline(src, tokens = []) {
    this.inlineQueue.push({ src, tokens });
    return tokens;
  }
  /**
   * Lexing/Compiling
   */
  inlineTokens(src, tokens = []) {
    let token, lastToken, cutSrc;
    let maskedSrc = src;
    let match;
    let keepPrevChar, prevChar;
    if (this.tokens.links) {
      const links = Object.keys(this.tokens.links);
      if (links.length > 0) {
        while ((match = this.tokenizer.rules.inline.reflinkSearch.exec(maskedSrc)) != null) {
          if (links.includes(match[0].slice(match[0].lastIndexOf("[") + 1, -1))) {
            maskedSrc = maskedSrc.slice(0, match.index) + "[" + "a".repeat(match[0].length - 2) + "]" + maskedSrc.slice(this.tokenizer.rules.inline.reflinkSearch.lastIndex);
          }
        }
      }
    }
    while ((match = this.tokenizer.rules.inline.blockSkip.exec(maskedSrc)) != null) {
      maskedSrc = maskedSrc.slice(0, match.index) + "[" + "a".repeat(match[0].length - 2) + "]" + maskedSrc.slice(this.tokenizer.rules.inline.blockSkip.lastIndex);
    }
    while ((match = this.tokenizer.rules.inline.anyPunctuation.exec(maskedSrc)) != null) {
      maskedSrc = maskedSrc.slice(0, match.index) + "++" + maskedSrc.slice(this.tokenizer.rules.inline.anyPunctuation.lastIndex);
    }
    while (src) {
      if (!keepPrevChar) {
        prevChar = "";
      }
      keepPrevChar = false;
      if (this.options.extensions && this.options.extensions.inline && this.options.extensions.inline.some((extTokenizer) => {
        if (token = extTokenizer.call({ lexer: this }, src, tokens)) {
          src = src.substring(token.raw.length);
          tokens.push(token);
          return true;
        }
        return false;
      })) {
        continue;
      }
      if (token = this.tokenizer.escape(src)) {
        src = src.substring(token.raw.length);
        tokens.push(token);
        continue;
      }
      if (token = this.tokenizer.tag(src)) {
        src = src.substring(token.raw.length);
        lastToken = tokens[tokens.length - 1];
        if (lastToken && token.type === "text" && lastToken.type === "text") {
          lastToken.raw += token.raw;
          lastToken.text += token.text;
        } else {
          tokens.push(token);
        }
        continue;
      }
      if (token = this.tokenizer.link(src)) {
        src = src.substring(token.raw.length);
        tokens.push(token);
        continue;
      }
      if (token = this.tokenizer.reflink(src, this.tokens.links)) {
        src = src.substring(token.raw.length);
        lastToken = tokens[tokens.length - 1];
        if (lastToken && token.type === "text" && lastToken.type === "text") {
          lastToken.raw += token.raw;
          lastToken.text += token.text;
        } else {
          tokens.push(token);
        }
        continue;
      }
      if (token = this.tokenizer.emStrong(src, maskedSrc, prevChar)) {
        src = src.substring(token.raw.length);
        tokens.push(token);
        continue;
      }
      if (token = this.tokenizer.codespan(src)) {
        src = src.substring(token.raw.length);
        tokens.push(token);
        continue;
      }
      if (token = this.tokenizer.br(src)) {
        src = src.substring(token.raw.length);
        tokens.push(token);
        continue;
      }
      if (token = this.tokenizer.del(src)) {
        src = src.substring(token.raw.length);
        tokens.push(token);
        continue;
      }
      if (token = this.tokenizer.autolink(src)) {
        src = src.substring(token.raw.length);
        tokens.push(token);
        continue;
      }
      if (!this.state.inLink && (token = this.tokenizer.url(src))) {
        src = src.substring(token.raw.length);
        tokens.push(token);
        continue;
      }
      cutSrc = src;
      if (this.options.extensions && this.options.extensions.startInline) {
        let startIndex = Infinity;
        const tempSrc = src.slice(1);
        let tempStart;
        this.options.extensions.startInline.forEach((getStartIndex) => {
          tempStart = getStartIndex.call({ lexer: this }, tempSrc);
          if (typeof tempStart === "number" && tempStart >= 0) {
            startIndex = Math.min(startIndex, tempStart);
          }
        });
        if (startIndex < Infinity && startIndex >= 0) {
          cutSrc = src.substring(0, startIndex + 1);
        }
      }
      if (token = this.tokenizer.inlineText(cutSrc)) {
        src = src.substring(token.raw.length);
        if (token.raw.slice(-1) !== "_") {
          prevChar = token.raw.slice(-1);
        }
        keepPrevChar = true;
        lastToken = tokens[tokens.length - 1];
        if (lastToken && lastToken.type === "text") {
          lastToken.raw += token.raw;
          lastToken.text += token.text;
        } else {
          tokens.push(token);
        }
        continue;
      }
      if (src) {
        const errMsg = "Infinite loop on byte: " + src.charCodeAt(0);
        if (this.options.silent) {
          console.error(errMsg);
          break;
        } else {
          throw new Error(errMsg);
        }
      }
    }
    return tokens;
  }
};
var _Renderer = class {
  options;
  parser;
  // set by the parser
  constructor(options3) {
    this.options = options3 || _defaults;
  }
  space(token) {
    return "";
  }
  code({ text: text2, lang, escaped }) {
    const langString = (lang || "").match(/^\S*/)?.[0];
    const code = text2.replace(/\n$/, "") + "\n";
    if (!langString) {
      return "<pre><code>" + (escaped ? code : escape$1(code, true)) + "</code></pre>\n";
    }
    return '<pre><code class="language-' + escape$1(langString) + '">' + (escaped ? code : escape$1(code, true)) + "</code></pre>\n";
  }
  blockquote({ tokens }) {
    const body = this.parser.parse(tokens);
    return `<blockquote>
${body}</blockquote>
`;
  }
  html({ text: text2 }) {
    return text2;
  }
  heading({ tokens, depth }) {
    return `<h${depth}>${this.parser.parseInline(tokens)}</h${depth}>
`;
  }
  hr(token) {
    return "<hr>\n";
  }
  list(token) {
    const ordered = token.ordered;
    const start = token.start;
    let body = "";
    for (let j = 0; j < token.items.length; j++) {
      const item = token.items[j];
      body += this.listitem(item);
    }
    const type = ordered ? "ol" : "ul";
    const startAttr = ordered && start !== 1 ? ' start="' + start + '"' : "";
    return "<" + type + startAttr + ">\n" + body + "</" + type + ">\n";
  }
  listitem(item) {
    let itemBody = "";
    if (item.task) {
      const checkbox = this.checkbox({ checked: !!item.checked });
      if (item.loose) {
        if (item.tokens.length > 0 && item.tokens[0].type === "paragraph") {
          item.tokens[0].text = checkbox + " " + item.tokens[0].text;
          if (item.tokens[0].tokens && item.tokens[0].tokens.length > 0 && item.tokens[0].tokens[0].type === "text") {
            item.tokens[0].tokens[0].text = checkbox + " " + item.tokens[0].tokens[0].text;
          }
        } else {
          item.tokens.unshift({
            type: "text",
            raw: checkbox + " ",
            text: checkbox + " "
          });
        }
      } else {
        itemBody += checkbox + " ";
      }
    }
    itemBody += this.parser.parse(item.tokens, !!item.loose);
    return `<li>${itemBody}</li>
`;
  }
  checkbox({ checked }) {
    return "<input " + (checked ? 'checked="" ' : "") + 'disabled="" type="checkbox">';
  }
  paragraph({ tokens }) {
    return `<p>${this.parser.parseInline(tokens)}</p>
`;
  }
  table(token) {
    let header = "";
    let cell = "";
    for (let j = 0; j < token.header.length; j++) {
      cell += this.tablecell(token.header[j]);
    }
    header += this.tablerow({ text: cell });
    let body = "";
    for (let j = 0; j < token.rows.length; j++) {
      const row = token.rows[j];
      cell = "";
      for (let k = 0; k < row.length; k++) {
        cell += this.tablecell(row[k]);
      }
      body += this.tablerow({ text: cell });
    }
    if (body)
      body = `<tbody>${body}</tbody>`;
    return "<table>\n<thead>\n" + header + "</thead>\n" + body + "</table>\n";
  }
  tablerow({ text: text2 }) {
    return `<tr>
${text2}</tr>
`;
  }
  tablecell(token) {
    const content = this.parser.parseInline(token.tokens);
    const type = token.header ? "th" : "td";
    const tag2 = token.align ? `<${type} align="${token.align}">` : `<${type}>`;
    return tag2 + content + `</${type}>
`;
  }
  /**
   * span level renderer
   */
  strong({ tokens }) {
    return `<strong>${this.parser.parseInline(tokens)}</strong>`;
  }
  em({ tokens }) {
    return `<em>${this.parser.parseInline(tokens)}</em>`;
  }
  codespan({ text: text2 }) {
    return `<code>${text2}</code>`;
  }
  br(token) {
    return "<br>";
  }
  del({ tokens }) {
    return `<del>${this.parser.parseInline(tokens)}</del>`;
  }
  link({ href, title, tokens }) {
    const text2 = this.parser.parseInline(tokens);
    const cleanHref = cleanUrl(href);
    if (cleanHref === null) {
      return text2;
    }
    href = cleanHref;
    let out = '<a href="' + href + '"';
    if (title) {
      out += ' title="' + title + '"';
    }
    out += ">" + text2 + "</a>";
    return out;
  }
  image({ href, title, text: text2 }) {
    const cleanHref = cleanUrl(href);
    if (cleanHref === null) {
      return text2;
    }
    href = cleanHref;
    let out = `<img src="${href}" alt="${text2}"`;
    if (title) {
      out += ` title="${title}"`;
    }
    out += ">";
    return out;
  }
  text(token) {
    return "tokens" in token && token.tokens ? this.parser.parseInline(token.tokens) : token.text;
  }
};
var _TextRenderer = class {
  // no need for block level renderers
  strong({ text: text2 }) {
    return text2;
  }
  em({ text: text2 }) {
    return text2;
  }
  codespan({ text: text2 }) {
    return text2;
  }
  del({ text: text2 }) {
    return text2;
  }
  html({ text: text2 }) {
    return text2;
  }
  text({ text: text2 }) {
    return text2;
  }
  link({ text: text2 }) {
    return "" + text2;
  }
  image({ text: text2 }) {
    return "" + text2;
  }
  br() {
    return "";
  }
};
var _Parser = class __Parser {
  options;
  renderer;
  textRenderer;
  constructor(options3) {
    this.options = options3 || _defaults;
    this.options.renderer = this.options.renderer || new _Renderer();
    this.renderer = this.options.renderer;
    this.renderer.options = this.options;
    this.renderer.parser = this;
    this.textRenderer = new _TextRenderer();
  }
  /**
   * Static Parse Method
   */
  static parse(tokens, options3) {
    const parser2 = new __Parser(options3);
    return parser2.parse(tokens);
  }
  /**
   * Static Parse Inline Method
   */
  static parseInline(tokens, options3) {
    const parser2 = new __Parser(options3);
    return parser2.parseInline(tokens);
  }
  /**
   * Parse Loop
   */
  parse(tokens, top2 = true) {
    let out = "";
    for (let i2 = 0; i2 < tokens.length; i2++) {
      const anyToken = tokens[i2];
      if (this.options.extensions && this.options.extensions.renderers && this.options.extensions.renderers[anyToken.type]) {
        const genericToken = anyToken;
        const ret = this.options.extensions.renderers[genericToken.type].call({ parser: this }, genericToken);
        if (ret !== false || !["space", "hr", "heading", "code", "table", "blockquote", "list", "html", "paragraph", "text"].includes(genericToken.type)) {
          out += ret || "";
          continue;
        }
      }
      const token = anyToken;
      switch (token.type) {
        case "space": {
          out += this.renderer.space(token);
          continue;
        }
        case "hr": {
          out += this.renderer.hr(token);
          continue;
        }
        case "heading": {
          out += this.renderer.heading(token);
          continue;
        }
        case "code": {
          out += this.renderer.code(token);
          continue;
        }
        case "table": {
          out += this.renderer.table(token);
          continue;
        }
        case "blockquote": {
          out += this.renderer.blockquote(token);
          continue;
        }
        case "list": {
          out += this.renderer.list(token);
          continue;
        }
        case "html": {
          out += this.renderer.html(token);
          continue;
        }
        case "paragraph": {
          out += this.renderer.paragraph(token);
          continue;
        }
        case "text": {
          let textToken = token;
          let body = this.renderer.text(textToken);
          while (i2 + 1 < tokens.length && tokens[i2 + 1].type === "text") {
            textToken = tokens[++i2];
            body += "\n" + this.renderer.text(textToken);
          }
          if (top2) {
            out += this.renderer.paragraph({
              type: "paragraph",
              raw: body,
              text: body,
              tokens: [{ type: "text", raw: body, text: body }]
            });
          } else {
            out += body;
          }
          continue;
        }
        default: {
          const errMsg = 'Token with "' + token.type + '" type was not found.';
          if (this.options.silent) {
            console.error(errMsg);
            return "";
          } else {
            throw new Error(errMsg);
          }
        }
      }
    }
    return out;
  }
  /**
   * Parse Inline Tokens
   */
  parseInline(tokens, renderer) {
    renderer = renderer || this.renderer;
    let out = "";
    for (let i2 = 0; i2 < tokens.length; i2++) {
      const anyToken = tokens[i2];
      if (this.options.extensions && this.options.extensions.renderers && this.options.extensions.renderers[anyToken.type]) {
        const ret = this.options.extensions.renderers[anyToken.type].call({ parser: this }, anyToken);
        if (ret !== false || !["escape", "html", "link", "image", "strong", "em", "codespan", "br", "del", "text"].includes(anyToken.type)) {
          out += ret || "";
          continue;
        }
      }
      const token = anyToken;
      switch (token.type) {
        case "escape": {
          out += renderer.text(token);
          break;
        }
        case "html": {
          out += renderer.html(token);
          break;
        }
        case "link": {
          out += renderer.link(token);
          break;
        }
        case "image": {
          out += renderer.image(token);
          break;
        }
        case "strong": {
          out += renderer.strong(token);
          break;
        }
        case "em": {
          out += renderer.em(token);
          break;
        }
        case "codespan": {
          out += renderer.codespan(token);
          break;
        }
        case "br": {
          out += renderer.br(token);
          break;
        }
        case "del": {
          out += renderer.del(token);
          break;
        }
        case "text": {
          out += renderer.text(token);
          break;
        }
        default: {
          const errMsg = 'Token with "' + token.type + '" type was not found.';
          if (this.options.silent) {
            console.error(errMsg);
            return "";
          } else {
            throw new Error(errMsg);
          }
        }
      }
    }
    return out;
  }
};
var _Hooks = class {
  options;
  constructor(options3) {
    this.options = options3 || _defaults;
  }
  static passThroughHooks = /* @__PURE__ */ new Set([
    "preprocess",
    "postprocess",
    "processAllTokens"
  ]);
  /**
   * Process markdown before marked
   */
  preprocess(markdown) {
    return markdown;
  }
  /**
   * Process HTML after marked is finished
   */
  postprocess(html3) {
    return html3;
  }
  /**
   * Process all tokens before walk tokens
   */
  processAllTokens(tokens) {
    return tokens;
  }
};
var Marked = class {
  defaults = _getDefaults();
  options = this.setOptions;
  parse = this.parseMarkdown(_Lexer.lex, _Parser.parse);
  parseInline = this.parseMarkdown(_Lexer.lexInline, _Parser.parseInline);
  Parser = _Parser;
  Renderer = _Renderer;
  TextRenderer = _TextRenderer;
  Lexer = _Lexer;
  Tokenizer = _Tokenizer;
  Hooks = _Hooks;
  constructor(...args2) {
    this.use(...args2);
  }
  /**
   * Run callback for every token
   */
  walkTokens(tokens, callback) {
    let values = [];
    for (const token of tokens) {
      values = values.concat(callback.call(this, token));
      switch (token.type) {
        case "table": {
          const tableToken = token;
          for (const cell of tableToken.header) {
            values = values.concat(this.walkTokens(cell.tokens, callback));
          }
          for (const row of tableToken.rows) {
            for (const cell of row) {
              values = values.concat(this.walkTokens(cell.tokens, callback));
            }
          }
          break;
        }
        case "list": {
          const listToken = token;
          values = values.concat(this.walkTokens(listToken.items, callback));
          break;
        }
        default: {
          const genericToken = token;
          if (this.defaults.extensions?.childTokens?.[genericToken.type]) {
            this.defaults.extensions.childTokens[genericToken.type].forEach((childTokens) => {
              const tokens2 = genericToken[childTokens].flat(Infinity);
              values = values.concat(this.walkTokens(tokens2, callback));
            });
          } else if (genericToken.tokens) {
            values = values.concat(this.walkTokens(genericToken.tokens, callback));
          }
        }
      }
    }
    return values;
  }
  use(...args2) {
    const extensions = this.defaults.extensions || { renderers: {}, childTokens: {} };
    args2.forEach((pack) => {
      const opts = { ...pack };
      opts.async = this.defaults.async || opts.async || false;
      if (pack.extensions) {
        pack.extensions.forEach((ext) => {
          if (!ext.name) {
            throw new Error("extension name required");
          }
          if ("renderer" in ext) {
            const prevRenderer = extensions.renderers[ext.name];
            if (prevRenderer) {
              extensions.renderers[ext.name] = function(...args3) {
                let ret = ext.renderer.apply(this, args3);
                if (ret === false) {
                  ret = prevRenderer.apply(this, args3);
                }
                return ret;
              };
            } else {
              extensions.renderers[ext.name] = ext.renderer;
            }
          }
          if ("tokenizer" in ext) {
            if (!ext.level || ext.level !== "block" && ext.level !== "inline") {
              throw new Error("extension level must be 'block' or 'inline'");
            }
            const extLevel = extensions[ext.level];
            if (extLevel) {
              extLevel.unshift(ext.tokenizer);
            } else {
              extensions[ext.level] = [ext.tokenizer];
            }
            if (ext.start) {
              if (ext.level === "block") {
                if (extensions.startBlock) {
                  extensions.startBlock.push(ext.start);
                } else {
                  extensions.startBlock = [ext.start];
                }
              } else if (ext.level === "inline") {
                if (extensions.startInline) {
                  extensions.startInline.push(ext.start);
                } else {
                  extensions.startInline = [ext.start];
                }
              }
            }
          }
          if ("childTokens" in ext && ext.childTokens) {
            extensions.childTokens[ext.name] = ext.childTokens;
          }
        });
        opts.extensions = extensions;
      }
      if (pack.renderer) {
        const renderer = this.defaults.renderer || new _Renderer(this.defaults);
        for (const prop in pack.renderer) {
          if (!(prop in renderer)) {
            throw new Error(`renderer '${prop}' does not exist`);
          }
          if (["options", "parser"].includes(prop)) {
            continue;
          }
          const rendererProp = prop;
          const rendererFunc = pack.renderer[rendererProp];
          const prevRenderer = renderer[rendererProp];
          renderer[rendererProp] = (...args3) => {
            let ret = rendererFunc.apply(renderer, args3);
            if (ret === false) {
              ret = prevRenderer.apply(renderer, args3);
            }
            return ret || "";
          };
        }
        opts.renderer = renderer;
      }
      if (pack.tokenizer) {
        const tokenizer = this.defaults.tokenizer || new _Tokenizer(this.defaults);
        for (const prop in pack.tokenizer) {
          if (!(prop in tokenizer)) {
            throw new Error(`tokenizer '${prop}' does not exist`);
          }
          if (["options", "rules", "lexer"].includes(prop)) {
            continue;
          }
          const tokenizerProp = prop;
          const tokenizerFunc = pack.tokenizer[tokenizerProp];
          const prevTokenizer = tokenizer[tokenizerProp];
          tokenizer[tokenizerProp] = (...args3) => {
            let ret = tokenizerFunc.apply(tokenizer, args3);
            if (ret === false) {
              ret = prevTokenizer.apply(tokenizer, args3);
            }
            return ret;
          };
        }
        opts.tokenizer = tokenizer;
      }
      if (pack.hooks) {
        const hooks = this.defaults.hooks || new _Hooks();
        for (const prop in pack.hooks) {
          if (!(prop in hooks)) {
            throw new Error(`hook '${prop}' does not exist`);
          }
          if (prop === "options") {
            continue;
          }
          const hooksProp = prop;
          const hooksFunc = pack.hooks[hooksProp];
          const prevHook = hooks[hooksProp];
          if (_Hooks.passThroughHooks.has(prop)) {
            hooks[hooksProp] = (arg) => {
              if (this.defaults.async) {
                return Promise.resolve(hooksFunc.call(hooks, arg)).then((ret2) => {
                  return prevHook.call(hooks, ret2);
                });
              }
              const ret = hooksFunc.call(hooks, arg);
              return prevHook.call(hooks, ret);
            };
          } else {
            hooks[hooksProp] = (...args3) => {
              let ret = hooksFunc.apply(hooks, args3);
              if (ret === false) {
                ret = prevHook.apply(hooks, args3);
              }
              return ret;
            };
          }
        }
        opts.hooks = hooks;
      }
      if (pack.walkTokens) {
        const walkTokens2 = this.defaults.walkTokens;
        const packWalktokens = pack.walkTokens;
        opts.walkTokens = function(token) {
          let values = [];
          values.push(packWalktokens.call(this, token));
          if (walkTokens2) {
            values = values.concat(walkTokens2.call(this, token));
          }
          return values;
        };
      }
      this.defaults = { ...this.defaults, ...opts };
    });
    return this;
  }
  setOptions(opt) {
    this.defaults = { ...this.defaults, ...opt };
    return this;
  }
  lexer(src, options3) {
    return _Lexer.lex(src, options3 ?? this.defaults);
  }
  parser(tokens, options3) {
    return _Parser.parse(tokens, options3 ?? this.defaults);
  }
  parseMarkdown(lexer2, parser2) {
    const parse4 = (src, options3) => {
      const origOpt = { ...options3 };
      const opt = { ...this.defaults, ...origOpt };
      const throwError = this.onError(!!opt.silent, !!opt.async);
      if (this.defaults.async === true && origOpt.async === false) {
        return throwError(new Error("marked(): The async option was set to true by an extension. Remove async: false from the parse options object to return a Promise."));
      }
      if (typeof src === "undefined" || src === null) {
        return throwError(new Error("marked(): input parameter is undefined or null"));
      }
      if (typeof src !== "string") {
        return throwError(new Error("marked(): input parameter is of type " + Object.prototype.toString.call(src) + ", string expected"));
      }
      if (opt.hooks) {
        opt.hooks.options = opt;
      }
      if (opt.async) {
        return Promise.resolve(opt.hooks ? opt.hooks.preprocess(src) : src).then((src2) => lexer2(src2, opt)).then((tokens) => opt.hooks ? opt.hooks.processAllTokens(tokens) : tokens).then((tokens) => opt.walkTokens ? Promise.all(this.walkTokens(tokens, opt.walkTokens)).then(() => tokens) : tokens).then((tokens) => parser2(tokens, opt)).then((html3) => opt.hooks ? opt.hooks.postprocess(html3) : html3).catch(throwError);
      }
      try {
        if (opt.hooks) {
          src = opt.hooks.preprocess(src);
        }
        let tokens = lexer2(src, opt);
        if (opt.hooks) {
          tokens = opt.hooks.processAllTokens(tokens);
        }
        if (opt.walkTokens) {
          this.walkTokens(tokens, opt.walkTokens);
        }
        let html3 = parser2(tokens, opt);
        if (opt.hooks) {
          html3 = opt.hooks.postprocess(html3);
        }
        return html3;
      } catch (e) {
        return throwError(e);
      }
    };
    return parse4;
  }
  onError(silent, async) {
    return (e) => {
      e.message += "\nPlease report this to https://github.com/markedjs/marked.";
      if (silent) {
        const msg = "<p>An error occurred:</p><pre>" + escape$1(e.message + "", true) + "</pre>";
        if (async) {
          return Promise.resolve(msg);
        }
        return msg;
      }
      if (async) {
        return Promise.reject(e);
      }
      throw e;
    };
  }
};
var markedInstance = new Marked();
function marked(src, opt) {
  return markedInstance.parse(src, opt);
}
marked.options = marked.setOptions = function(options3) {
  markedInstance.setOptions(options3);
  marked.defaults = markedInstance.defaults;
  changeDefaults(marked.defaults);
  return marked;
};
marked.getDefaults = _getDefaults;
marked.defaults = _defaults;
marked.use = function(...args2) {
  markedInstance.use(...args2);
  marked.defaults = markedInstance.defaults;
  changeDefaults(marked.defaults);
  return marked;
};
marked.walkTokens = function(tokens, callback) {
  return markedInstance.walkTokens(tokens, callback);
};
marked.parseInline = markedInstance.parseInline;
marked.Parser = _Parser;
marked.parser = _Parser.parse;
marked.Renderer = _Renderer;
marked.TextRenderer = _TextRenderer;
marked.Lexer = _Lexer;
marked.lexer = _Lexer.lex;
marked.Tokenizer = _Tokenizer;
marked.Hooks = _Hooks;
marked.parse = marked;
var options = marked.options;
var setOptions = marked.setOptions;
var use = marked.use;
var walkTokens = marked.walkTokens;
var parseInline = marked.parseInline;
var parse = marked;
var parser = _Parser.parse;
var lexer = _Lexer.lex;

// out-build/vs/base/browser/formattedTextRenderer.js
function $QZ(text2, options3 = {}) {
  const element = $SZ(options3);
  element.textContent = text2;
  return element;
}
function $RZ(formattedText, options3 = {}) {
  const element = $SZ(options3);
  _renderFormattedText(element, parseFormattedText(formattedText, !!options3.renderCodeSegments), options3.actionHandler, options3.renderCodeSegments);
  return element;
}
function $SZ(options3) {
  const tagName = options3.inline ? "span" : "div";
  const element = document.createElement(tagName);
  if (options3.className) {
    element.className = options3.className;
  }
  return element;
}
var StringStream = class {
  constructor(source) {
    this.b = source;
    this.c = 0;
  }
  eos() {
    return this.c >= this.b.length;
  }
  next() {
    const next = this.peek();
    this.advance();
    return next;
  }
  peek() {
    return this.b[this.c];
  }
  advance() {
    this.c++;
  }
};
var FormatType;
(function(FormatType2) {
  FormatType2[FormatType2["Invalid"] = 0] = "Invalid";
  FormatType2[FormatType2["Root"] = 1] = "Root";
  FormatType2[FormatType2["Text"] = 2] = "Text";
  FormatType2[FormatType2["Bold"] = 3] = "Bold";
  FormatType2[FormatType2["Italics"] = 4] = "Italics";
  FormatType2[FormatType2["Action"] = 5] = "Action";
  FormatType2[FormatType2["ActionClose"] = 6] = "ActionClose";
  FormatType2[FormatType2["Code"] = 7] = "Code";
  FormatType2[FormatType2["NewLine"] = 8] = "NewLine";
})(FormatType || (FormatType = {}));
function _renderFormattedText(element, treeNode, actionHandler, renderCodeSegments) {
  let child;
  if (treeNode.type === 2) {
    child = document.createTextNode(treeNode.content || "");
  } else if (treeNode.type === 3) {
    child = document.createElement("b");
  } else if (treeNode.type === 4) {
    child = document.createElement("i");
  } else if (treeNode.type === 7 && renderCodeSegments) {
    child = document.createElement("code");
  } else if (treeNode.type === 5 && actionHandler) {
    const a = document.createElement("a");
    actionHandler.disposables.add($aj(a, "click", (event) => {
      actionHandler.callback(String(treeNode.index), event);
    }));
    child = a;
  } else if (treeNode.type === 8) {
    child = document.createElement("br");
  } else if (treeNode.type === 1) {
    child = element;
  }
  if (child && element !== child) {
    element.appendChild(child);
  }
  if (child && Array.isArray(treeNode.children)) {
    treeNode.children.forEach((nodeChild) => {
      _renderFormattedText(child, nodeChild, actionHandler, renderCodeSegments);
    });
  }
}
function parseFormattedText(content, parseCodeSegments) {
  const root = {
    type: 1,
    children: []
  };
  let actionViewItemIndex = 0;
  let current = root;
  const stack = [];
  const stream = new StringStream(content);
  while (!stream.eos()) {
    let next = stream.next();
    const isEscapedFormatType = next === "\\" && formatTagType(stream.peek(), parseCodeSegments) !== 0;
    if (isEscapedFormatType) {
      next = stream.next();
    }
    if (!isEscapedFormatType && isFormatTag(next, parseCodeSegments) && next === stream.peek()) {
      stream.advance();
      if (current.type === 2) {
        current = stack.pop();
      }
      const type = formatTagType(next, parseCodeSegments);
      if (current.type === type || current.type === 5 && type === 6) {
        current = stack.pop();
      } else {
        const newCurrent = {
          type,
          children: []
        };
        if (type === 5) {
          newCurrent.index = actionViewItemIndex;
          actionViewItemIndex++;
        }
        current.children.push(newCurrent);
        stack.push(current);
        current = newCurrent;
      }
    } else if (next === "\n") {
      if (current.type === 2) {
        current = stack.pop();
      }
      current.children.push({
        type: 8
        /* FormatType.NewLine */
      });
    } else {
      if (current.type !== 2) {
        const textCurrent = {
          type: 2,
          content: next
        };
        current.children.push(textCurrent);
        stack.push(current);
        current = textCurrent;
      } else {
        current.content += next;
      }
    }
  }
  if (current.type === 2) {
    current = stack.pop();
  }
  if (stack.length) {
  }
  return root;
}
function isFormatTag(char, supportCodeSegments) {
  return formatTagType(char, supportCodeSegments) !== 0;
}
function formatTagType(char, supportCodeSegments) {
  switch (char) {
    case "*":
      return 3;
    case "_":
      return 4;
    case "[":
      return 5;
    case "]":
      return 6;
    case "`":
      return supportCodeSegments ? 7 : 0;
    default:
      return 0;
  }
}

// out-build/vs/base/browser/ui/iconLabel/iconLabels.js
var labelWithIconsRegex = new RegExp(`(\\\\)?\\$\\((${ThemeIcon.iconNameExpression}(?:${ThemeIcon.iconModifierExpression})?)\\)`, "g");
function $B1(text2) {
  const elements = new Array();
  let match;
  let textStart = 0, textStop = 0;
  while ((match = labelWithIconsRegex.exec(text2)) !== null) {
    textStop = match.index || 0;
    if (textStart < textStop) {
      elements.push(text2.substring(textStart, textStop));
    }
    textStart = (match.index || 0) + match[0].length;
    const [, escaped, codicon] = match;
    elements.push(escaped ? `$(${codicon})` : $C1({ id: codicon }));
  }
  if (textStart < text2.length) {
    elements.push(text2.substring(textStart));
  }
  return elements;
}
function $C1(icon2) {
  const node = $(`span`);
  node.classList.add(...ThemeIcon.asClassNameArray(icon2));
  return node;
}

// out-build/vs/base/browser/markdownRenderer.js
var defaultMarkedRenderers = Object.freeze({
  image: ({ href, title, text: text2 }) => {
    let dimensions = [];
    let attributes = [];
    if (href) {
      ({ href, dimensions } = $jm(href));
      attributes.push(`src="${$hm(href)}"`);
    }
    if (text2) {
      attributes.push(`alt="${$hm(text2)}"`);
    }
    if (title) {
      attributes.push(`title="${$hm(title)}"`);
    }
    if (dimensions.length) {
      attributes = attributes.concat(dimensions);
    }
    return "<img " + attributes.join(" ") + ">";
  },
  paragraph({ tokens }) {
    return `<p>${this.parser.parseInline(tokens)}</p>`;
  },
  link({ href, title, tokens }) {
    let text2 = this.parser.parseInline(tokens);
    if (typeof href !== "string") {
      return "";
    }
    if (href === text2) {
      text2 = $im(text2);
    }
    title = typeof title === "string" ? $hm($im(title)) : "";
    href = $im(href);
    href = href.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;").replace(/"/g, "&quot;").replace(/'/g, "&#39;");
    return `<a href="${href}" title="${title || href}" draggable="false">${text2}</a>`;
  }
});
function $D1(markdown, options3 = {}, markedOptions = {}) {
  const disposables = new $2c();
  let isDisposed = false;
  const element = $SZ(options3);
  const { renderer, codeBlocks, syncCodeBlocks } = createMarkdownRenderer(options3, markdown);
  const value = preprocessMarkdownString(markdown);
  let renderedMarkdown;
  if (options3.fillInIncompleteTokens) {
    const opts = {
      ..._defaults,
      ...markedOptions,
      renderer
    };
    const tokens = lexer(value, opts);
    const newTokens = $H1(tokens);
    renderedMarkdown = parser(newTokens, opts);
  } else {
    renderedMarkdown = parse(value, { ...markedOptions, renderer, async: false });
  }
  if (markdown.supportThemeIcons) {
    const elements = $B1(renderedMarkdown);
    renderedMarkdown = elements.map((e) => typeof e === "string" ? e : e.outerHTML).join("");
  }
  const htmlParser = new DOMParser();
  const markdownHtmlDoc = htmlParser.parseFromString(sanitizeRenderedMarkdown({ isTrusted: markdown.isTrusted, ...options3.sanitizerOptions }, renderedMarkdown), "text/html");
  rewriteRenderedLinks(markdown, options3, markdownHtmlDoc.body);
  element.innerHTML = sanitizeRenderedMarkdown({ isTrusted: markdown.isTrusted, ...options3.sanitizerOptions }, markdownHtmlDoc.body.innerHTML);
  if (codeBlocks.length > 0) {
    Promise.all(codeBlocks).then((tuples) => {
      if (isDisposed) {
        return;
      }
      const renderedElements = new Map(tuples);
      const placeholderElements = element.querySelectorAll(`div[data-code]`);
      for (const placeholderElement of placeholderElements) {
        const renderedElement = renderedElements.get(placeholderElement.dataset["code"] ?? "");
        if (renderedElement) {
          $dk(placeholderElement, renderedElement);
        }
      }
      options3.asyncRenderCallback?.();
    });
  } else if (syncCodeBlocks.length > 0) {
    const renderedElements = new Map(syncCodeBlocks);
    const placeholderElements = element.querySelectorAll(`div[data-code]`);
    for (const placeholderElement of placeholderElements) {
      const renderedElement = renderedElements.get(placeholderElement.dataset["code"] ?? "");
      if (renderedElement) {
        $dk(placeholderElement, renderedElement);
      }
    }
  }
  if (options3.asyncRenderCallback) {
    for (const img of element.getElementsByTagName("img")) {
      const listener = disposables.add($_i(img, "load", () => {
        listener.dispose();
        options3.asyncRenderCallback();
      }));
    }
  }
  if (options3.actionHandler) {
    const onClick2 = options3.actionHandler.disposables.add(new $9Z(element, "click"));
    const onAuxClick = options3.actionHandler.disposables.add(new $9Z(element, "auxclick"));
    options3.actionHandler.disposables.add(Event2.any(onClick2.event, onAuxClick.event)((e) => {
      const mouseEvent = new $lf(getWindow(element), e);
      if (!mouseEvent.leftButton && !mouseEvent.middleButton) {
        return;
      }
      activateLink(markdown, options3, mouseEvent);
    }));
    options3.actionHandler.disposables.add($_i(element, "keydown", (e) => {
      const keyboardEvent = new $if(e);
      if (!keyboardEvent.equals(
        10
        /* KeyCode.Space */
      ) && !keyboardEvent.equals(
        3
        /* KeyCode.Enter */
      )) {
        return;
      }
      activateLink(markdown, options3, keyboardEvent);
    }));
  }
  return {
    element,
    dispose: () => {
      isDisposed = true;
      disposables.dispose();
    }
  };
}
function rewriteRenderedLinks(markdown, options3, root) {
  for (const el of root.querySelectorAll("img, audio, video, source")) {
    const src = el.getAttribute("src");
    if (src) {
      let href = src;
      try {
        if (markdown.baseUri) {
          href = resolveWithBaseUri(URI.from(markdown.baseUri), href);
        }
      } catch (err) {
      }
      el.setAttribute("src", massageHref(markdown, href, true));
      if (options3.remoteImageIsAllowed) {
        const uri = URI.parse(href);
        if (uri.scheme !== Schemas.file && uri.scheme !== Schemas.data && !options3.remoteImageIsAllowed(uri)) {
          el.replaceWith($("", void 0, el.outerHTML));
        }
      }
    }
  }
  for (const el of root.querySelectorAll("a")) {
    const href = el.getAttribute("href");
    el.setAttribute("href", "");
    if (!href || /^data:|javascript:/i.test(href) || /^command:/i.test(href) && !markdown.isTrusted || /^command:(\/\/\/)?_workbench\.downloadResource/i.test(href)) {
      el.replaceWith(...el.childNodes);
    } else {
      let resolvedHref = massageHref(markdown, href, false);
      if (markdown.baseUri) {
        resolvedHref = resolveWithBaseUri(URI.from(markdown.baseUri), href);
      }
      el.dataset.href = resolvedHref;
    }
  }
}
function createMarkdownRenderer(options3, markdown) {
  const renderer = new _Renderer();
  renderer.image = defaultMarkedRenderers.image;
  renderer.link = defaultMarkedRenderers.link;
  renderer.paragraph = defaultMarkedRenderers.paragraph;
  const codeBlocks = [];
  const syncCodeBlocks = [];
  if (options3.codeBlockRendererSync) {
    renderer.code = ({ text: text2, lang, raw }) => {
      const id2 = $mW.nextId();
      const value = options3.codeBlockRendererSync(postProcessCodeBlockLanguageId(lang), text2, raw);
      syncCodeBlocks.push([id2, value]);
      return `<div class="code" data-code="${id2}">${$zf(text2)}</div>`;
    };
  } else if (options3.codeBlockRenderer) {
    renderer.code = ({ text: text2, lang }) => {
      const id2 = $mW.nextId();
      const value = options3.codeBlockRenderer(postProcessCodeBlockLanguageId(lang), text2);
      codeBlocks.push(value.then((element) => [id2, element]));
      return `<div class="code" data-code="${id2}">${$zf(text2)}</div>`;
    };
  }
  if (!markdown.supportHtml) {
    renderer.html = ({ text: text2 }) => {
      if (options3.sanitizerOptions?.replaceWithPlaintext) {
        return $zf(text2);
      }
      const match = markdown.isTrusted ? text2.match(/^(<span[^>]+>)|(<\/\s*span>)$/) : void 0;
      return match ? text2 : "";
    };
  }
  return { renderer, codeBlocks, syncCodeBlocks };
}
function preprocessMarkdownString(markdown) {
  let value = markdown.value;
  if (value.length > 1e5) {
    value = `${value.substr(0, 1e5)}\u2026`;
  }
  if (markdown.supportThemeIcons) {
    value = $9l(value);
  }
  return value;
}
function activateLink(markdown, options3, event) {
  const target = event.target.closest("a[data-href]");
  if (!$Uj(target)) {
    return;
  }
  try {
    let href = target.dataset["href"];
    if (href) {
      if (markdown.baseUri) {
        href = resolveWithBaseUri(URI.from(markdown.baseUri), href);
      }
      options3.actionHandler.callback(href, event);
    }
  } catch (err) {
    $gb(err);
  } finally {
    event.preventDefault();
  }
}
function uriMassage(markdown, part) {
  let data;
  try {
    data = $bu(decodeURIComponent(part));
  } catch (e) {
  }
  if (!data) {
    return part;
  }
  data = $Nv(data, (value) => {
    if (markdown.uris && markdown.uris[value]) {
      return URI.revive(markdown.uris[value]);
    } else {
      return void 0;
    }
  });
  return encodeURIComponent(JSON.stringify(data));
}
function massageHref(markdown, href, isDomUri) {
  const data = markdown.uris && markdown.uris[href];
  let uri = URI.revive(data);
  if (isDomUri) {
    if (href.startsWith(Schemas.data + ":")) {
      return href;
    }
    if (!uri) {
      uri = URI.parse(href);
    }
    return $ih.uriToBrowserUri(uri).toString(true);
  }
  if (!uri) {
    return href;
  }
  if (URI.parse(href).toString() === uri.toString()) {
    return href;
  }
  if (uri.query) {
    uri = uri.with({ query: uriMassage(markdown, uri.query) });
  }
  return uri.toString();
}
function postProcessCodeBlockLanguageId(lang) {
  if (!lang) {
    return "";
  }
  const parts = lang.split(/[\s+|:|,|\{|\?]/, 1);
  if (parts.length) {
    return parts[0];
  }
  return lang;
}
function resolveWithBaseUri(baseUri, href) {
  const hasScheme = /^\w[\w\d+.-]*:/.test(href);
  if (hasScheme) {
    return href;
  }
  if (baseUri.path.endsWith("/")) {
    return $yh(baseUri, href).toString();
  } else {
    return $yh($uh(baseUri), href).toString();
  }
}
var selfClosingTags = ["area", "base", "br", "col", "command", "embed", "hr", "img", "input", "keygen", "link", "meta", "param", "source", "track", "wbr"];
function sanitizeRenderedMarkdown(options3, renderedMarkdown) {
  const { config, allowedSchemes } = getSanitizerOptions(options3);
  const store = new $2c();
  store.add(addDompurifyHook("uponSanitizeAttribute", (element, e) => {
    if (e.attrName === "style" || e.attrName === "class") {
      if (element.tagName === "SPAN") {
        if (e.attrName === "style") {
          e.keepAttr = /^(color\:(#[0-9a-fA-F]+|var\(--vscode(-[a-zA-Z0-9]+)+\));)?(background-color\:(#[0-9a-fA-F]+|var\(--vscode(-[a-zA-Z0-9]+)+\));)?(border-radius:[0-9]+px;)?$/.test(e.attrValue);
          return;
        } else if (e.attrName === "class") {
          e.keepAttr = /^codicon codicon-[a-z\-]+( codicon-modifier-[a-z\-]+)?$/.test(e.attrValue);
          return;
        }
      }
      e.keepAttr = false;
      return;
    } else if (element.tagName === "INPUT" && element.attributes.getNamedItem("type")?.value === "checkbox") {
      if (e.attrName === "type" && e.attrValue === "checkbox" || e.attrName === "disabled" || e.attrName === "checked") {
        e.keepAttr = true;
        return;
      }
      e.keepAttr = false;
    }
  }));
  store.add(addDompurifyHook("uponSanitizeElement", (element, e) => {
    if (e.tagName === "input") {
      if (element.attributes.getNamedItem("type")?.value === "checkbox") {
        element.setAttribute("disabled", "");
      } else if (!options3.replaceWithPlaintext) {
        element.remove();
      }
    }
    if (options3.replaceWithPlaintext && !e.allowedTags[e.tagName] && e.tagName !== "body") {
      if (element.parentElement) {
        let startTagText;
        let endTagText;
        if (e.tagName === "#comment") {
          startTagText = `<!--${element.textContent}-->`;
        } else {
          const isSelfClosing = selfClosingTags.includes(e.tagName);
          const attrString = element.attributes.length ? " " + Array.from(element.attributes).map((attr) => `${attr.name}="${attr.value}"`).join(" ") : "";
          startTagText = `<${e.tagName}${attrString}>`;
          if (!isSelfClosing) {
            endTagText = `</${e.tagName}>`;
          }
        }
        const fragment = document.createDocumentFragment();
        const textNode = element.parentElement.ownerDocument.createTextNode(startTagText);
        fragment.appendChild(textNode);
        const endTagTextNode = endTagText ? element.parentElement.ownerDocument.createTextNode(endTagText) : void 0;
        while (element.firstChild) {
          fragment.appendChild(element.firstChild);
        }
        if (endTagTextNode) {
          fragment.appendChild(endTagTextNode);
        }
        if (element.nodeType === Node.COMMENT_NODE) {
          element.parentElement.insertBefore(fragment, element);
        } else {
          element.parentElement.replaceChild(fragment, element);
        }
      }
    }
  }));
  store.add($uk(allowedSchemes));
  try {
    return purify.sanitize(renderedMarkdown, { ...config, RETURN_TRUSTED_TYPE: true });
  } finally {
    store.dispose();
  }
}
var $E1 = [
  "align",
  "autoplay",
  "alt",
  "checked",
  "class",
  "colspan",
  "controls",
  "data-code",
  "data-href",
  "disabled",
  "draggable",
  "height",
  "href",
  "loop",
  "muted",
  "playsinline",
  "poster",
  "rowspan",
  "src",
  "style",
  "target",
  "title",
  "type",
  "width",
  "start"
];
function getSanitizerOptions(options3) {
  const allowedSchemes = [
    Schemas.http,
    Schemas.https,
    Schemas.mailto,
    Schemas.data,
    Schemas.file,
    Schemas.vscodeFileResource,
    Schemas.vscodeRemote,
    Schemas.vscodeRemoteResource
  ];
  if (options3.isTrusted) {
    allowedSchemes.push(Schemas.command);
  }
  return {
    config: {
      // allowedTags should included everything that markdown renders to.
      // Since we have our own sanitize function for marked, it's possible we missed some tag so let dompurify make sure.
      // HTML tags that can result from markdown are from reading https://spec.commonmark.org/0.29/
      // HTML table tags that can result from markdown are from https://github.github.com/gfm/#tables-extension-
      ALLOWED_TAGS: options3.allowedTags ?? [...$vk],
      ALLOWED_ATTR: $E1,
      ALLOW_UNKNOWN_PROTOCOLS: true
    },
    allowedSchemes
  };
}
function $F1(string) {
  return typeof string === "string" ? string : $G1(string);
}
function $G1(markdown, withCodeBlocks) {
  let value = markdown.value ?? "";
  if (value.length > 1e5) {
    value = `${value.substr(0, 1e5)}\u2026`;
  }
  const html3 = parse(value, { async: false, renderer: withCodeBlocks ? plainTextWithCodeBlocksRenderer.value : plainTextRenderer.value });
  return sanitizeRenderedMarkdown({ isTrusted: false }, html3).toString().replace(/&(#\d+|[a-zA-Z]+);/g, (m) => unescapeInfo.get(m) ?? m).trim();
}
var unescapeInfo = /* @__PURE__ */ new Map([
  ["&quot;", '"'],
  ["&nbsp;", " "],
  ["&amp;", "&"],
  ["&#39;", "'"],
  ["&lt;", "<"],
  ["&gt;", ">"]
]);
function createRenderer() {
  const renderer = new _Renderer();
  renderer.code = ({ text: text2 }) => {
    return $zf(text2);
  };
  renderer.blockquote = ({ text: text2 }) => {
    return text2 + "\n";
  };
  renderer.html = (_) => {
    return "";
  };
  renderer.heading = function({ tokens }) {
    return this.parser.parseInline(tokens) + "\n";
  };
  renderer.hr = () => {
    return "";
  };
  renderer.list = function({ items }) {
    return items.map((x) => this.listitem(x)).join("\n") + "\n";
  };
  renderer.listitem = ({ text: text2 }) => {
    return text2 + "\n";
  };
  renderer.paragraph = function({ tokens }) {
    return this.parser.parseInline(tokens) + "\n";
  };
  renderer.table = function({ header, rows }) {
    return header.map((cell) => this.tablecell(cell)).join(" ") + "\n" + rows.map((cells) => cells.map((cell) => this.tablecell(cell)).join(" ")).join("\n") + "\n";
  };
  renderer.tablerow = ({ text: text2 }) => {
    return text2;
  };
  renderer.tablecell = function({ tokens }) {
    return this.parser.parseInline(tokens);
  };
  renderer.strong = ({ text: text2 }) => {
    return text2;
  };
  renderer.em = ({ text: text2 }) => {
    return text2;
  };
  renderer.codespan = ({ text: text2 }) => {
    return $zf(text2);
  };
  renderer.br = (_) => {
    return "\n";
  };
  renderer.del = ({ text: text2 }) => {
    return text2;
  };
  renderer.image = (_) => {
    return "";
  };
  renderer.text = ({ text: text2 }) => {
    return text2;
  };
  renderer.link = ({ text: text2 }) => {
    return text2;
  };
  return renderer;
}
var plainTextRenderer = new $sf(createRenderer);
var plainTextWithCodeBlocksRenderer = new $sf(() => {
  const renderer = createRenderer();
  renderer.code = ({ text: text2 }) => {
    return `
\`\`\`
${$zf(text2)}
\`\`\`
`;
  };
  return renderer;
});
function mergeRawTokenText(tokens) {
  let mergedTokenText = "";
  tokens.forEach((token) => {
    mergedTokenText += token.raw;
  });
  return mergedTokenText;
}
function completeSingleLinePattern(token) {
  if (!token.tokens) {
    return void 0;
  }
  for (let i2 = token.tokens.length - 1; i2 >= 0; i2--) {
    const subtoken = token.tokens[i2];
    if (subtoken.type === "text") {
      const lines = subtoken.raw.split("\n");
      const lastLine = lines[lines.length - 1];
      if (lastLine.includes("`")) {
        return completeCodespan(token);
      } else if (lastLine.includes("**")) {
        return completeDoublestar(token);
      } else if (lastLine.match(/\*\w/)) {
        return completeStar(token);
      } else if (lastLine.match(/(^|\s)__\w/)) {
        return completeDoubleUnderscore(token);
      } else if (lastLine.match(/(^|\s)_\w/)) {
        return completeUnderscore(token);
      } else if (
        // Text with start of link target
        hasLinkTextAndStartOfLinkTarget(lastLine) || // This token doesn't have the link text, eg if it contains other markdown constructs that are in other subtokens.
        // But some preceding token does have an unbalanced [ at least
        hasStartOfLinkTargetAndNoLinkText(lastLine) && token.tokens.slice(0, i2).some((t) => t.type === "text" && t.raw.match(/\[[^\]]*$/))
      ) {
        const nextTwoSubTokens = token.tokens.slice(i2 + 1);
        if (
          // If the link was parsed as a link, then look for a link token and a text token with a quote
          nextTwoSubTokens[0]?.type === "link" && nextTwoSubTokens[1]?.type === "text" && nextTwoSubTokens[1].raw.match(/^ *"[^"]*$/) || // And if the link was not parsed as a link (eg command link), just look for a single quote in this token
          lastLine.match(/^[^"]* +"[^"]*$/)
        ) {
          return completeLinkTargetArg(token);
        }
        return completeLinkTarget(token);
      } else if (lastLine.match(/(^|\s)\[\w*/)) {
        return completeLinkText(token);
      }
    }
  }
  return void 0;
}
function hasLinkTextAndStartOfLinkTarget(str) {
  return !!str.match(/(^|\s)\[.*\]\(\w*/);
}
function hasStartOfLinkTargetAndNoLinkText(str) {
  return !!str.match(/^[^\[]*\]\([^\)]*$/);
}
function completeListItemPattern(list2) {
  const lastListItem = list2.items[list2.items.length - 1];
  const lastListSubToken = lastListItem.tokens ? lastListItem.tokens[lastListItem.tokens.length - 1] : void 0;
  let newToken;
  if (lastListSubToken?.type === "text" && !("inRawBlock" in lastListItem)) {
    newToken = completeSingleLinePattern(lastListSubToken);
  }
  if (!newToken || newToken.type !== "paragraph") {
    return;
  }
  const previousListItemsText = mergeRawTokenText(list2.items.slice(0, -1));
  const lastListItemLead = lastListItem.raw.match(/^(\s*(-|\d+\.|\*) +)/)?.[0];
  if (!lastListItemLead) {
    return;
  }
  const newListItemText = lastListItemLead + mergeRawTokenText(lastListItem.tokens.slice(0, -1)) + newToken.raw;
  const newList = lexer(previousListItemsText + newListItemText)[0];
  if (newList.type !== "list") {
    return;
  }
  return newList;
}
var maxIncompleteTokensFixRounds = 3;
function $H1(tokens) {
  for (let i2 = 0; i2 < maxIncompleteTokensFixRounds; i2++) {
    const newTokens = fillInIncompleteTokensOnce(tokens);
    if (newTokens) {
      tokens = newTokens;
    } else {
      break;
    }
  }
  return tokens;
}
function fillInIncompleteTokensOnce(tokens) {
  let i2;
  let newTokens;
  for (i2 = 0; i2 < tokens.length; i2++) {
    const token = tokens[i2];
    if (token.type === "paragraph" && token.raw.match(/(\n|^)\|/)) {
      newTokens = completeTable(tokens.slice(i2));
      break;
    }
    if (i2 === tokens.length - 1 && token.type === "list") {
      const newListToken = completeListItemPattern(token);
      if (newListToken) {
        newTokens = [newListToken];
        break;
      }
    }
    if (i2 === tokens.length - 1 && token.type === "paragraph") {
      const newToken = completeSingleLinePattern(token);
      if (newToken) {
        newTokens = [newToken];
        break;
      }
    }
  }
  if (newTokens) {
    const newTokensList = [
      ...tokens.slice(0, i2),
      ...newTokens
    ];
    newTokensList.links = tokens.links;
    return newTokensList;
  }
  return null;
}
function completeCodespan(token) {
  return completeWithString(token, "`");
}
function completeStar(tokens) {
  return completeWithString(tokens, "*");
}
function completeUnderscore(tokens) {
  return completeWithString(tokens, "_");
}
function completeLinkTarget(tokens) {
  return completeWithString(tokens, ")");
}
function completeLinkTargetArg(tokens) {
  return completeWithString(tokens, '")');
}
function completeLinkText(tokens) {
  return completeWithString(tokens, "](https://microsoft.com)");
}
function completeDoublestar(tokens) {
  return completeWithString(tokens, "**");
}
function completeDoubleUnderscore(tokens) {
  return completeWithString(tokens, "__");
}
function completeWithString(tokens, closingString) {
  const mergedRawText = mergeRawTokenText(Array.isArray(tokens) ? tokens : [tokens]);
  return lexer(mergedRawText + closingString)[0];
}
function completeTable(tokens) {
  const mergedRawText = mergeRawTokenText(tokens);
  const lines = mergedRawText.split("\n");
  let numCols;
  let hasSeparatorRow = false;
  for (let i2 = 0; i2 < lines.length; i2++) {
    const line = lines[i2].trim();
    if (typeof numCols === "undefined" && line.match(/^\s*\|/)) {
      const line1Matches = line.match(/(\|[^\|]+)(?=\||$)/g);
      if (line1Matches) {
        numCols = line1Matches.length;
      }
    } else if (typeof numCols === "number") {
      if (line.match(/^\s*\|/)) {
        if (i2 !== lines.length - 1) {
          return void 0;
        }
        hasSeparatorRow = true;
      } else {
        return void 0;
      }
    }
  }
  if (typeof numCols === "number" && numCols > 0) {
    const prefixText = hasSeparatorRow ? lines.slice(0, -1).join("\n") : mergedRawText;
    const line1EndsInPipe = !!prefixText.match(/\|\s*$/);
    const newRawText = prefixText + (line1EndsInPipe ? "" : "|") + `
|${" --- |".repeat(numCols)}`;
    return lexer(newRawText);
  }
  return void 0;
}
function addDompurifyHook(hook, cb) {
  purify.addHook(hook, cb);
  return $1c(() => purify.removeHook(hook));
}

// out-build/vs/base/browser/ui/hover/hoverDelegate2.js
var baseHoverDelegate = {
  showHover: () => void 0,
  showDelayedHover: () => void 0,
  setupDelayedHover: () => $3c.None,
  setupDelayedHoverAtMouse: () => $3c.None,
  hideHover: () => void 0,
  showAndFocusLastHover: () => void 0,
  setupManagedHover: () => null,
  showManagedHover: () => void 0
};
function $I1(hoverDelegate) {
  baseHoverDelegate = hoverDelegate;
}
function $J1() {
  return baseHoverDelegate;
}

// out-build/vs/base/browser/ui/selectBox/selectBoxCustom.js
var $7 = $;
var SELECT_OPTION_ENTRY_TEMPLATE_ID = "selectOption.entry.template";
var SelectListRenderer = class {
  get templateId() {
    return SELECT_OPTION_ENTRY_TEMPLATE_ID;
  }
  renderTemplate(container2) {
    const data = /* @__PURE__ */ Object.create(null);
    data.root = container2;
    data.text = $bk(container2, $7(".option-text"));
    data.detail = $bk(container2, $7(".option-detail"));
    data.decoratorRight = $bk(container2, $7(".option-decorator-right"));
    return data;
  }
  renderElement(element, index, templateData) {
    const data = templateData;
    const text2 = element.text;
    const detail2 = element.detail;
    const decoratorRight = element.decoratorRight;
    const isDisabled = element.isDisabled;
    data.text.textContent = text2;
    data.detail.textContent = !!detail2 ? detail2 : "";
    data.decoratorRight.innerText = !!decoratorRight ? decoratorRight : "";
    if (isDisabled) {
      data.root.classList.add("option-disabled");
    } else {
      data.root.classList.remove("option-disabled");
    }
  }
  disposeTemplate(_templateData) {
  }
};
var $K1 = class _$K1 extends $3c {
  static {
    this.a = 32;
  }
  static {
    this.b = 2;
  }
  static {
    this.c = 3;
  }
  constructor(options3, selected, contextViewProvider, styles, selectBoxOptions) {
    super();
    this.m = [];
    this.F = 0;
    this.H = false;
    this.J = false;
    this.N = false;
    this.f = false;
    this.s = styles;
    this.g = selectBoxOptions || /* @__PURE__ */ Object.create(null);
    if (typeof this.g.minBottomMargin !== "number") {
      this.g.minBottomMargin = _$K1.a;
    } else if (this.g.minBottomMargin < 0) {
      this.g.minBottomMargin = 0;
    }
    this.h = document.createElement("select");
    this.h.className = "monaco-select-box monaco-select-box-dropdown-padding";
    if (typeof this.g.ariaLabel === "string") {
      this.h.setAttribute("aria-label", this.g.ariaLabel);
    }
    if (typeof this.g.ariaDescription === "string") {
      this.h.setAttribute("aria-description", this.g.ariaDescription);
    }
    this.r = new $ze();
    this.B(this.r);
    this.Q();
    this.P(contextViewProvider);
    this.n = selected || 0;
    if (options3) {
      this.setOptions(options3, selected);
    }
    this.S();
  }
  O(title) {
    if (!this.M && title) {
      this.M = this.B($J1().setupManagedHover($JZ("mouse"), this.h, title));
    } else if (this.M) {
      this.M.update(title);
    }
  }
  // IDelegate - List renderer
  getHeight() {
    return 22;
  }
  getTemplateId() {
    return SELECT_OPTION_ENTRY_TEMPLATE_ID;
  }
  P(contextViewProvider) {
    this.u = contextViewProvider;
    this.w = $(".monaco-select-box-dropdown-container");
    this.w.classList.add("monaco-select-box-dropdown-padding");
    this.I = $bk(this.w, $7(".select-box-details-pane"));
    const widthControlOuterDiv = $bk(this.w, $7(".select-box-dropdown-container-width-control"));
    const widthControlInnerDiv = $bk(widthControlOuterDiv, $7(".width-control-div"));
    this.D = document.createElement("span");
    this.D.className = "option-text-width-control";
    $bk(widthControlInnerDiv, this.D);
    this.G = 0;
    this.y = $VZ(this.w);
    this.w.setAttribute("draggable", "true");
    this.B($_i(this.w, $7j.DRAG_START, (e) => {
      $9j.stop(e, true);
    }));
  }
  Q() {
    this.B($aj(this.h, "change", (e) => {
      this.n = e.target.selectedIndex;
      this.r.fire({
        index: e.target.selectedIndex,
        selected: e.target.value
      });
      if (!!this.m[this.n] && !!this.m[this.n].text) {
        this.O(this.m[this.n].text);
      }
    }));
    this.B($_i(this.h, $7j.CLICK, (e) => {
      $9j.stop(e);
      if (this.f) {
        this.Z(true);
      } else {
        this.Y();
      }
    }));
    this.B($_i(this.h, $7j.MOUSE_DOWN, (e) => {
      $9j.stop(e);
    }));
    let listIsVisibleOnTouchStart;
    this.B($_i(this.h, "touchstart", (e) => {
      listIsVisibleOnTouchStart = this.f;
    }));
    this.B($_i(this.h, "touchend", (e) => {
      $9j.stop(e);
      if (listIsVisibleOnTouchStart) {
        this.Z(true);
      } else {
        this.Y();
      }
    }));
    this.B($_i(this.h, $7j.KEY_DOWN, (e) => {
      const event = new $if(e);
      let showDropDown = false;
      if ($m) {
        if (event.keyCode === 18 || event.keyCode === 16 || event.keyCode === 10 || event.keyCode === 3) {
          showDropDown = true;
        }
      } else {
        if (event.keyCode === 18 && event.altKey || event.keyCode === 16 && event.altKey || event.keyCode === 10 || event.keyCode === 3) {
          showDropDown = true;
        }
      }
      if (showDropDown) {
        this.Y();
        $9j.stop(e, true);
      }
    }));
  }
  get onDidSelect() {
    return this.r.event;
  }
  setOptions(options3, selected) {
    if (!$zb(this.m, options3)) {
      this.m = options3;
      this.h.options.length = 0;
      this.H = false;
      this.L = void 0;
      this.m.forEach((option, index) => {
        this.h.add(this.X(option.text, index, option.isDisabled));
        if (typeof option.description === "string") {
          this.H = true;
        }
      });
    }
    if (selected !== void 0) {
      this.select(selected);
      this.F = this.n;
    }
  }
  setEnabled(enable) {
    this.h.disabled = !enable;
  }
  R() {
    this.z?.splice(0, this.z.length, this.m);
  }
  select(index) {
    if (index >= 0 && index < this.m.length) {
      this.n = index;
    } else if (index > this.m.length - 1) {
      this.select(this.m.length - 1);
    } else if (this.n < 0) {
      this.n = 0;
    }
    this.h.selectedIndex = this.n;
    if (!!this.m[this.n] && !!this.m[this.n].text) {
      this.O(this.m[this.n].text);
    }
  }
  setAriaLabel(label3) {
    this.g.ariaLabel = label3;
    this.h.setAttribute("aria-label", this.g.ariaLabel);
  }
  focus() {
    if (this.h) {
      this.h.tabIndex = 0;
      this.h.focus();
    }
  }
  blur() {
    if (this.h) {
      this.h.tabIndex = -1;
      this.h.blur();
    }
  }
  setFocusable(focusable) {
    this.h.tabIndex = focusable ? 0 : -1;
  }
  render(container2) {
    this.j = container2;
    container2.classList.add("select-container");
    container2.appendChild(this.h);
    this.U();
  }
  S() {
    const content = [];
    if (this.s.listFocusBackground) {
      content.push(`.monaco-select-box-dropdown-container > .select-box-dropdown-list-container .monaco-list .monaco-list-row.focused { background-color: ${this.s.listFocusBackground} !important; }`);
    }
    if (this.s.listFocusForeground) {
      content.push(`.monaco-select-box-dropdown-container > .select-box-dropdown-list-container .monaco-list .monaco-list-row.focused { color: ${this.s.listFocusForeground} !important; }`);
    }
    if (this.s.decoratorRightForeground) {
      content.push(`.monaco-select-box-dropdown-container > .select-box-dropdown-list-container .monaco-list .monaco-list-row:not(.focused) .option-decorator-right { color: ${this.s.decoratorRightForeground}; }`);
    }
    if (this.s.selectBackground && this.s.selectBorder && this.s.selectBorder !== this.s.selectBackground) {
      content.push(`.monaco-select-box-dropdown-container { border: 1px solid ${this.s.selectBorder} } `);
      content.push(`.monaco-select-box-dropdown-container > .select-box-details-pane.border-top { border-top: 1px solid ${this.s.selectBorder} } `);
      content.push(`.monaco-select-box-dropdown-container > .select-box-details-pane.border-bottom { border-bottom: 1px solid ${this.s.selectBorder} } `);
    } else if (this.s.selectListBorder) {
      content.push(`.monaco-select-box-dropdown-container > .select-box-details-pane.border-top { border-top: 1px solid ${this.s.selectListBorder} } `);
      content.push(`.monaco-select-box-dropdown-container > .select-box-details-pane.border-bottom { border-bottom: 1px solid ${this.s.selectListBorder} } `);
    }
    if (this.s.listHoverForeground) {
      content.push(`.monaco-select-box-dropdown-container > .select-box-dropdown-list-container .monaco-list .monaco-list-row:not(.option-disabled):not(.focused):hover { color: ${this.s.listHoverForeground} !important; }`);
    }
    if (this.s.listHoverBackground) {
      content.push(`.monaco-select-box-dropdown-container > .select-box-dropdown-list-container .monaco-list .monaco-list-row:not(.option-disabled):not(.focused):hover { background-color: ${this.s.listHoverBackground} !important; }`);
    }
    if (this.s.listFocusOutline) {
      content.push(`.monaco-select-box-dropdown-container > .select-box-dropdown-list-container .monaco-list .monaco-list-row.focused { outline: 1.6px dotted ${this.s.listFocusOutline} !important; outline-offset: -1.6px !important; }`);
    }
    if (this.s.listHoverOutline) {
      content.push(`.monaco-select-box-dropdown-container > .select-box-dropdown-list-container .monaco-list .monaco-list-row:not(.option-disabled):not(.focused):hover { outline: 1.6px dashed ${this.s.listHoverOutline} !important; outline-offset: -1.6px !important; }`);
    }
    content.push(`.monaco-select-box-dropdown-container > .select-box-dropdown-list-container .monaco-list .monaco-list-row.option-disabled.focused { background-color: transparent !important; color: inherit !important; outline: none !important; }`);
    content.push(`.monaco-select-box-dropdown-container > .select-box-dropdown-list-container .monaco-list .monaco-list-row.option-disabled:hover { background-color: transparent !important; color: inherit !important; outline: none !important; }`);
    this.y.textContent = content.join("\n");
  }
  U() {
    const background = this.s.selectBackground ?? "";
    const foreground = this.s.selectForeground ?? "";
    const border = this.s.selectBorder ?? "";
    this.h.style.backgroundColor = background;
    this.h.style.color = foreground;
    this.h.style.borderColor = border;
  }
  W() {
    const background = this.s.selectBackground ?? "";
    const listBackground = $ZZ(this.s.selectListBackground, background);
    this.C.style.backgroundColor = listBackground;
    this.I.style.backgroundColor = listBackground;
    const optionsBorder = this.s.focusBorder ?? "";
    this.w.style.outlineColor = optionsBorder;
    this.w.style.outlineOffset = "-1px";
    this.z.style(this.s);
  }
  X(value, index, disabled) {
    const option = document.createElement("option");
    option.value = value;
    option.text = value;
    option.disabled = !!disabled;
    return option;
  }
  // ContextView dropdown methods
  Y() {
    this.I.innerText = "";
    if (!this.u || this.f) {
      return;
    }
    this.eb(this.w);
    this.R();
    this.u.showContextView({
      getAnchor: () => this.h,
      render: (container2) => this.ab(container2, true),
      layout: () => {
        this.cb();
      },
      onHide: () => {
        this.w.classList.remove("visible");
        this.h.classList.remove("synthetic-focus");
      },
      anchorPosition: this.G
    }, this.g.optionsAsChildren ? this.j : void 0);
    this.f = true;
    this.Z(false);
    this.u.showContextView({
      getAnchor: () => this.h,
      render: (container2) => this.ab(container2),
      layout: () => this.cb(),
      onHide: () => {
        this.w.classList.remove("visible");
        this.h.classList.remove("synthetic-focus");
      },
      anchorPosition: this.G
    }, this.g.optionsAsChildren ? this.j : void 0);
    this.F = this.n;
    this.f = true;
    this.h.setAttribute("aria-expanded", "true");
  }
  Z(focusSelect) {
    if (!this.u || !this.f) {
      return;
    }
    this.f = false;
    this.h.setAttribute("aria-expanded", "false");
    if (focusSelect) {
      this.h.focus();
    }
    this.u.hideContextView();
  }
  ab(container2, preLayoutPosition) {
    container2.appendChild(this.w);
    this.cb(preLayoutPosition);
    return {
      dispose: () => {
        this.w.remove();
      }
    };
  }
  // Iterate over detailed descriptions, find max height
  bb() {
    let maxDetailsPaneHeight = 0;
    this.m.forEach((_option, index) => {
      this.jb(index);
      if (this.I.offsetHeight > maxDetailsPaneHeight) {
        maxDetailsPaneHeight = this.I.offsetHeight;
      }
    });
    return maxDetailsPaneHeight;
  }
  cb(preLayoutPosition) {
    if (this.J) {
      return false;
    }
    if (this.z) {
      this.w.classList.add("visible");
      const window3 = getWindow(this.h);
      const selectPosition = $vj(this.h);
      const styles = getWindow(this.h).getComputedStyle(this.h);
      const verticalPadding = parseFloat(styles.getPropertyValue("--dropdown-padding-top")) + parseFloat(styles.getPropertyValue("--dropdown-padding-bottom"));
      const maxSelectDropDownHeightBelow = window3.innerHeight - selectPosition.top - selectPosition.height - (this.g.minBottomMargin || 0);
      const maxSelectDropDownHeightAbove = selectPosition.top - _$K1.b;
      const selectWidth = this.h.offsetWidth;
      const selectMinWidth = this.db(this.D);
      const selectOptimalWidth = Math.max(selectMinWidth, Math.round(selectWidth)).toString() + "px";
      this.w.style.width = selectOptimalWidth;
      this.z.getHTMLElement().style.height = "";
      this.z.layout();
      let listHeight = this.z.contentHeight;
      if (this.H && this.L === void 0) {
        this.L = this.bb();
      }
      const maxDetailsPaneHeight = this.H ? this.L : 0;
      const minRequiredDropDownHeight = listHeight + verticalPadding + maxDetailsPaneHeight;
      const maxVisibleOptionsBelow = Math.floor((maxSelectDropDownHeightBelow - verticalPadding - maxDetailsPaneHeight) / this.getHeight());
      const maxVisibleOptionsAbove = Math.floor((maxSelectDropDownHeightAbove - verticalPadding - maxDetailsPaneHeight) / this.getHeight());
      if (preLayoutPosition) {
        if (selectPosition.top + selectPosition.height > window3.innerHeight - 22 || selectPosition.top < _$K1.b || maxVisibleOptionsBelow < 1 && maxVisibleOptionsAbove < 1) {
          return false;
        }
        if (maxVisibleOptionsBelow < _$K1.c && maxVisibleOptionsAbove > maxVisibleOptionsBelow && this.m.length > maxVisibleOptionsBelow) {
          this.G = 1;
          this.C.remove();
          this.I.remove();
          this.w.appendChild(this.I);
          this.w.appendChild(this.C);
          this.I.classList.remove("border-top");
          this.I.classList.add("border-bottom");
        } else {
          this.G = 0;
          this.C.remove();
          this.I.remove();
          this.w.appendChild(this.C);
          this.w.appendChild(this.I);
          this.I.classList.remove("border-bottom");
          this.I.classList.add("border-top");
        }
        return true;
      }
      if (selectPosition.top + selectPosition.height > window3.innerHeight - 22 || selectPosition.top < _$K1.b || this.G === 0 && maxVisibleOptionsBelow < 1 || this.G === 1 && maxVisibleOptionsAbove < 1) {
        this.Z(true);
        return false;
      }
      if (this.G === 0) {
        if (this.f && maxVisibleOptionsBelow + maxVisibleOptionsAbove < 1) {
          this.Z(true);
          return false;
        }
        if (minRequiredDropDownHeight > maxSelectDropDownHeightBelow) {
          listHeight = maxVisibleOptionsBelow * this.getHeight();
        }
      } else {
        if (minRequiredDropDownHeight > maxSelectDropDownHeightAbove) {
          listHeight = maxVisibleOptionsAbove * this.getHeight();
        }
      }
      this.z.layout(listHeight);
      this.z.domFocus();
      if (this.z.length > 0) {
        this.z.setFocus([this.n || 0]);
        this.z.reveal(this.z.getFocus()[0] || 0);
      }
      if (this.H) {
        this.z.getHTMLElement().style.height = listHeight + verticalPadding + "px";
        this.w.style.height = "";
      } else {
        this.w.style.height = listHeight + verticalPadding + "px";
      }
      this.jb(this.n);
      this.w.style.width = selectOptimalWidth;
      this.C.setAttribute("tabindex", "0");
      this.h.classList.add("synthetic-focus");
      this.w.classList.add("synthetic-focus");
      return true;
    } else {
      return false;
    }
  }
  db(container2) {
    let elementWidth = 0;
    if (container2) {
      let longest = 0;
      let longestLength = 0;
      this.m.forEach((option, index) => {
        const detailLength = !!option.detail ? option.detail.length : 0;
        const rightDecoratorLength = !!option.decoratorRight ? option.decoratorRight.length : 0;
        const len = option.text.length + detailLength + rightDecoratorLength;
        if (len > longestLength) {
          longest = index;
          longestLength = len;
        }
      });
      container2.textContent = this.m[longest].text + (!!this.m[longest].decoratorRight ? this.m[longest].decoratorRight + " " : "");
      elementWidth = $xj(container2);
    }
    return elementWidth;
  }
  eb(parent) {
    if (this.z) {
      return;
    }
    this.C = $bk(parent, $7(".select-box-dropdown-list-container"));
    this.t = new SelectListRenderer();
    this.z = this.B(new $A1("SelectBoxCustom", this.C, this, [this.t], {
      useShadows: false,
      verticalScrollMode: 3,
      keyboardSupport: false,
      mouseSupport: false,
      accessibilityProvider: {
        getAriaLabel: (element) => {
          let label3 = element.text;
          if (element.detail) {
            label3 += `. ${element.detail}`;
          }
          if (element.decoratorRight) {
            label3 += `. ${element.decoratorRight}`;
          }
          if (element.description) {
            label3 += `. ${element.description}`;
          }
          return label3;
        },
        getWidgetAriaLabel: () => localize(28, null),
        getRole: () => $m ? "" : "option",
        getWidgetRole: () => "listbox"
      }
    }));
    if (this.g.ariaLabel) {
      this.z.ariaLabel = this.g.ariaLabel;
    }
    const onKeyDown = this.B(new $9Z(this.C, "keydown"));
    const onSelectDropDownKeyDown = Event2.chain(onKeyDown.event, ($149) => $149.filter(() => this.z.length > 0).map((e) => new $if(e)));
    this.B(Event2.chain(onSelectDropDownKeyDown, ($149) => $149.filter(
      (e) => e.keyCode === 3
      /* KeyCode.Enter */
    ))(this.lb, this));
    this.B(Event2.chain(onSelectDropDownKeyDown, ($149) => $149.filter(
      (e) => e.keyCode === 2
      /* KeyCode.Tab */
    ))(this.lb, this));
    this.B(Event2.chain(onSelectDropDownKeyDown, ($149) => $149.filter(
      (e) => e.keyCode === 9
      /* KeyCode.Escape */
    ))(this.kb, this));
    this.B(Event2.chain(onSelectDropDownKeyDown, ($149) => $149.filter(
      (e) => e.keyCode === 16
      /* KeyCode.UpArrow */
    ))(this.nb, this));
    this.B(Event2.chain(onSelectDropDownKeyDown, ($149) => $149.filter(
      (e) => e.keyCode === 18
      /* KeyCode.DownArrow */
    ))(this.mb, this));
    this.B(Event2.chain(onSelectDropDownKeyDown, ($149) => $149.filter(
      (e) => e.keyCode === 12
      /* KeyCode.PageDown */
    ))(this.pb, this));
    this.B(Event2.chain(onSelectDropDownKeyDown, ($149) => $149.filter(
      (e) => e.keyCode === 11
      /* KeyCode.PageUp */
    ))(this.ob, this));
    this.B(Event2.chain(onSelectDropDownKeyDown, ($149) => $149.filter(
      (e) => e.keyCode === 14
      /* KeyCode.Home */
    ))(this.qb, this));
    this.B(Event2.chain(onSelectDropDownKeyDown, ($149) => $149.filter(
      (e) => e.keyCode === 13
      /* KeyCode.End */
    ))(this.rb, this));
    this.B(Event2.chain(onSelectDropDownKeyDown, ($149) => $149.filter((e) => e.keyCode >= 21 && e.keyCode <= 56 || e.keyCode >= 85 && e.keyCode <= 113))(this.sb, this));
    this.B($_i(this.z.getHTMLElement(), $7j.POINTER_UP, (e) => this.fb(e)));
    this.B(this.z.onMouseOver((e) => typeof e.index !== "undefined" && this.z.setFocus([e.index])));
    this.B(this.z.onDidChangeFocus((e) => this.ib(e)));
    this.B($_i(this.w, $7j.FOCUS_OUT, (e) => {
      if (!this.f || $Dj(e.relatedTarget, this.w)) {
        return;
      }
      this.gb();
    }));
    this.z.getHTMLElement().setAttribute("aria-label", this.g.ariaLabel || "");
    this.z.getHTMLElement().setAttribute("aria-expanded", "true");
    this.W();
  }
  // List methods
  // List mouse controller - active exit, select option, fire onDidSelect if change, return focus to parent select
  // Also takes in touchend events
  fb(e) {
    if (!this.z.length) {
      return;
    }
    $9j.stop(e);
    const target = e.target;
    if (!target) {
      return;
    }
    if (target.classList.contains("slider")) {
      return;
    }
    const listRowElement = target.closest(".monaco-list-row");
    if (!listRowElement) {
      return;
    }
    const index = Number(listRowElement.getAttribute("data-index"));
    const disabled = listRowElement.classList.contains("option-disabled");
    if (index >= 0 && index < this.m.length && !disabled) {
      this.n = index;
      this.select(this.n);
      this.z.setFocus([this.n]);
      this.z.reveal(this.z.getFocus()[0]);
      if (this.n !== this.F) {
        this.F = this.n;
        this.r.fire({
          index: this.h.selectedIndex,
          selected: this.m[this.n].text
        });
        if (!!this.m[this.n] && !!this.m[this.n].text) {
          this.O(this.m[this.n].text);
        }
      }
      this.Z(true);
    }
  }
  // List Exit - passive - implicit no selection change, hide drop-down
  gb() {
    if (this.N) {
      return;
    }
    if (this.n !== this.F) {
      this.select(this.F);
    }
    this.Z(false);
  }
  hb(text2, actionHandler) {
    const cleanRenderedMarkdown2 = (element) => {
      for (let i2 = 0; i2 < element.childNodes.length; i2++) {
        const child = element.childNodes.item(i2);
        const tagName = child.tagName && child.tagName.toLowerCase();
        if (tagName === "img") {
          child.remove();
        } else {
          cleanRenderedMarkdown2(child);
        }
      }
    };
    const rendered = $D1({ value: text2, supportThemeIcons: true }, { actionHandler });
    rendered.element.classList.add("select-box-description-markdown");
    cleanRenderedMarkdown2(rendered.element);
    return rendered.element;
  }
  // List Focus Change - passive - update details pane with newly focused element's data
  ib(e) {
    if (!this.f || !this.H) {
      return;
    }
    this.jb(e.indexes[0]);
  }
  jb(selectedIndex) {
    this.I.innerText = "";
    const option = this.m[selectedIndex];
    const description = option?.description ?? "";
    const descriptionIsMarkdown = option?.descriptionIsMarkdown ?? false;
    if (description) {
      if (descriptionIsMarkdown) {
        const actionHandler = option.descriptionMarkdownActionHandler;
        this.I.appendChild(this.hb(description, actionHandler));
      } else {
        this.I.innerText = description;
      }
      this.I.style.display = "block";
    } else {
      this.I.style.display = "none";
    }
    this.J = true;
    this.u.layout();
    this.J = false;
  }
  // List keyboard controller
  // List exit - active - hide ContextView dropdown, reset selection, return focus to parent select
  kb(e) {
    $9j.stop(e);
    this.select(this.F);
    this.Z(true);
  }
  // List exit - active - hide ContextView dropdown, return focus to parent select, fire onDidSelect if change
  lb(e) {
    $9j.stop(e);
    if (this.n !== this.F) {
      this.F = this.n;
      this.r.fire({
        index: this.h.selectedIndex,
        selected: this.m[this.n].text
      });
      if (!!this.m[this.n] && !!this.m[this.n].text) {
        this.O(this.m[this.n].text);
      }
    }
    this.Z(true);
  }
  // List navigation - have to handle a disabled option (jump over)
  mb(e) {
    if (this.n < this.m.length - 1) {
      $9j.stop(e, true);
      const nextOptionDisabled = this.m[this.n + 1].isDisabled;
      if (nextOptionDisabled && this.m.length > this.n + 2) {
        this.n += 2;
      } else if (nextOptionDisabled) {
        return;
      } else {
        this.n++;
      }
      this.select(this.n);
      this.z.setFocus([this.n]);
      this.z.reveal(this.z.getFocus()[0]);
    }
  }
  nb(e) {
    if (this.n > 0) {
      $9j.stop(e, true);
      const previousOptionDisabled = this.m[this.n - 1].isDisabled;
      if (previousOptionDisabled && this.n > 1) {
        this.n -= 2;
      } else {
        this.n--;
      }
      this.select(this.n);
      this.z.setFocus([this.n]);
      this.z.reveal(this.z.getFocus()[0]);
    }
  }
  ob(e) {
    $9j.stop(e);
    this.z.focusPreviousPage();
    setTimeout(() => {
      this.n = this.z.getFocus()[0];
      if (this.m[this.n].isDisabled && this.n < this.m.length - 1) {
        this.n++;
        this.z.setFocus([this.n]);
      }
      this.z.reveal(this.n);
      this.select(this.n);
    }, 1);
  }
  pb(e) {
    $9j.stop(e);
    this.z.focusNextPage();
    setTimeout(() => {
      this.n = this.z.getFocus()[0];
      if (this.m[this.n].isDisabled && this.n > 0) {
        this.n--;
        this.z.setFocus([this.n]);
      }
      this.z.reveal(this.n);
      this.select(this.n);
    }, 1);
  }
  qb(e) {
    $9j.stop(e);
    if (this.m.length < 2) {
      return;
    }
    this.n = 0;
    if (this.m[this.n].isDisabled && this.n > 1) {
      this.n++;
    }
    this.z.setFocus([this.n]);
    this.z.reveal(this.n);
    this.select(this.n);
  }
  rb(e) {
    $9j.stop(e);
    if (this.m.length < 2) {
      return;
    }
    this.n = this.m.length - 1;
    if (this.m[this.n].isDisabled && this.n > 1) {
      this.n--;
    }
    this.z.setFocus([this.n]);
    this.z.reveal(this.n);
    this.select(this.n);
  }
  // Mimic option first character navigation of native select
  sb(e) {
    const ch = KeyCodeUtils.toString(e.keyCode);
    let optionIndex = -1;
    for (let i2 = 0; i2 < this.m.length - 1; i2++) {
      optionIndex = (i2 + this.n + 1) % this.m.length;
      if (this.m[optionIndex].text.charAt(0).toUpperCase() === ch && !this.m[optionIndex].isDisabled) {
        this.select(optionIndex);
        this.z.setFocus([optionIndex]);
        this.z.reveal(this.z.getFocus()[0]);
        $9j.stop(e);
        break;
      }
    }
  }
  dispose() {
    this.Z(false);
    super.dispose();
  }
};

// out-build/vs/base/browser/ui/selectBox/selectBoxNative.js
var $L1 = class extends $3c {
  constructor(options3, selected, styles, selectBoxOptions) {
    super();
    this.f = 0;
    this.b = selectBoxOptions || /* @__PURE__ */ Object.create(null);
    this.c = [];
    this.a = document.createElement("select");
    this.a.className = "monaco-select-box";
    if (typeof this.b.ariaLabel === "string") {
      this.a.setAttribute("aria-label", this.b.ariaLabel);
    }
    if (typeof this.b.ariaDescription === "string") {
      this.a.setAttribute("aria-description", this.b.ariaDescription);
    }
    this.g = this.B(new $ze());
    this.h = styles;
    this.j();
    this.setOptions(options3, selected);
  }
  j() {
    this.B($mZ.addTarget(this.a));
    [EventType.Tap].forEach((eventType) => {
      this.B($_i(this.a, eventType, (e) => {
        this.a.focus();
      }));
    });
    this.B($aj(this.a, "click", (e) => {
      $9j.stop(e, true);
    }));
    this.B($aj(this.a, "change", (e) => {
      this.a.title = e.target.value;
      this.g.fire({
        index: e.target.selectedIndex,
        selected: e.target.value
      });
    }));
    this.B($aj(this.a, "keydown", (e) => {
      let showSelect = false;
      if ($m) {
        if (e.keyCode === 18 || e.keyCode === 16 || e.keyCode === 10) {
          showSelect = true;
        }
      } else {
        if (e.keyCode === 18 && e.altKey || e.keyCode === 10 || e.keyCode === 3) {
          showSelect = true;
        }
      }
      if (showSelect) {
        e.stopPropagation();
      }
    }));
  }
  get onDidSelect() {
    return this.g.event;
  }
  setOptions(options3, selected) {
    if (!this.c || !$zb(this.c, options3)) {
      this.c = options3;
      this.a.options.length = 0;
      this.c.forEach((option, index) => {
        this.a.add(this.m(option.text, index, option.isDisabled));
      });
    }
    if (selected !== void 0) {
      this.select(selected);
    }
  }
  select(index) {
    if (this.c.length === 0) {
      this.f = 0;
    } else if (index >= 0 && index < this.c.length) {
      this.f = index;
    } else if (index > this.c.length - 1) {
      this.select(this.c.length - 1);
    } else if (this.f < 0) {
      this.f = 0;
    }
    this.a.selectedIndex = this.f;
    if (this.f < this.c.length && typeof this.c[this.f].text === "string") {
      this.a.title = this.c[this.f].text;
    } else {
      this.a.title = "";
    }
  }
  setAriaLabel(label3) {
    this.b.ariaLabel = label3;
    this.a.setAttribute("aria-label", label3);
  }
  focus() {
    if (this.a) {
      this.a.tabIndex = 0;
      this.a.focus();
    }
  }
  blur() {
    if (this.a) {
      this.a.tabIndex = -1;
      this.a.blur();
    }
  }
  setEnabled(enable) {
    this.a.disabled = !enable;
  }
  setFocusable(focusable) {
    this.a.tabIndex = focusable ? 0 : -1;
  }
  render(container2) {
    container2.classList.add("select-container");
    container2.appendChild(this.a);
    this.setOptions(this.c, this.f);
    this.applyStyles();
  }
  style(styles) {
    this.h = styles;
    this.applyStyles();
  }
  applyStyles() {
    if (this.a) {
      this.a.style.backgroundColor = this.h.selectBackground ?? "";
      this.a.style.color = this.h.selectForeground ?? "";
      this.a.style.borderColor = this.h.selectBorder ?? "";
    }
  }
  m(value, index, disabled) {
    const option = document.createElement("option");
    option.value = value;
    option.text = value;
    option.disabled = !!disabled;
    return option;
  }
};

// out-build/vs/base/browser/ui/selectBox/selectBox.js
var $M1 = {
  ...$z1,
  selectBackground: "#3C3C3C",
  selectForeground: "#F0F0F0",
  selectBorder: "#3C3C3C",
  decoratorRightForeground: void 0,
  selectListBackground: void 0,
  selectListBorder: void 0,
  focusBorder: void 0
};
var $N1 = class extends $qZ {
  constructor(options3, selected, contextViewProvider, styles, selectBoxOptions) {
    super();
    if ($m && !selectBoxOptions?.useCustomDrawn) {
      this.a = new $L1(options3, selected, styles, selectBoxOptions);
    } else {
      this.a = new $K1(options3, selected, contextViewProvider, styles, selectBoxOptions);
    }
    this.B(this.a);
  }
  // Public SelectBox Methods - routed through delegate interface
  get onDidSelect() {
    return this.a.onDidSelect;
  }
  setOptions(options3, selected) {
    this.a.setOptions(options3, selected);
  }
  select(index) {
    this.a.select(index);
  }
  setAriaLabel(label3) {
    this.a.setAriaLabel(label3);
  }
  focus() {
    this.a.focus();
  }
  blur() {
    this.a.blur();
  }
  setFocusable(focusable) {
    this.a.setFocusable(focusable);
  }
  setEnabled(enabled) {
    this.a.setEnabled(enabled);
  }
  render(container2) {
    this.a.render(container2);
  }
};

// out-build/vs/base/browser/ui/actionbar/actionViewItems.js
var $T1 = class extends $3c {
  get action() {
    return this._action;
  }
  constructor(context, action, u = {}) {
    super();
    this.u = u;
    this._context = context || this;
    this._action = action;
    if (action instanceof $Um) {
      this.B(action.onDidChange((event) => {
        if (!this.element) {
          return;
        }
        this.w(event);
      }));
    }
  }
  w(event) {
    if (event.enabled !== void 0) {
      this.z();
    }
    if (event.checked !== void 0) {
      this.J();
    }
    if (event.class !== void 0) {
      this.I();
    }
    if (event.label !== void 0) {
      this.C();
      this.G();
    }
    if (event.tooltip !== void 0) {
      this.G();
    }
  }
  get actionRunner() {
    if (!this.j) {
      this.j = this.B(new $Vm());
    }
    return this.j;
  }
  set actionRunner(actionRunner) {
    this.j = actionRunner;
  }
  isEnabled() {
    return this._action.enabled;
  }
  setActionContext(newContext) {
    this._context = newContext;
  }
  render(container2) {
    const element = this.element = container2;
    this.B($mZ.addTarget(container2));
    const enableDragging = this.u && this.u.draggable;
    if (enableDragging) {
      container2.draggable = true;
      if ($Ue) {
        this.B($_i(container2, $7j.DRAG_START, (e) => e.dataTransfer?.setData($kZ.TEXT, this._action.label)));
      }
    }
    this.B($_i(element, EventType.Tap, (e) => this.onClick(e, true)));
    this.B($_i(element, $7j.MOUSE_DOWN, (e) => {
      if (!enableDragging) {
        $9j.stop(e, true);
      }
      if (this._action.enabled && e.button === 0) {
        element.classList.add("active");
      }
    }));
    if ($m) {
      this.B($_i(element, $7j.CONTEXT_MENU, (e) => {
        if (e.button === 0 && e.ctrlKey === true) {
          this.onClick(e);
        }
      }));
    }
    this.B($_i(element, $7j.CLICK, (e) => {
      $9j.stop(e, true);
      if (!(this.u && this.u.isMenu)) {
        this.onClick(e);
      }
    }));
    this.B($_i(element, $7j.DBLCLICK, (e) => {
      $9j.stop(e, true);
    }));
    [$7j.MOUSE_UP, $7j.MOUSE_OUT].forEach((event) => {
      this.B($_i(element, event, (e) => {
        $9j.stop(e);
        element.classList.remove("active");
      }));
    });
  }
  onClick(event, preserveFocus = false) {
    $9j.stop(event, true);
    const context = $Ig(this._context) ? this.u?.useEventAsContext ? event : { preserveFocus } : this._context;
    this.actionRunner.run(this._action, context);
  }
  // Only set the tabIndex on the element once it is about to get focused
  // That way this element wont be a tab stop when it is not needed #106441
  focus() {
    if (this.element) {
      this.element.tabIndex = 0;
      this.element.focus();
      this.element.classList.add("focused");
    }
  }
  isFocused() {
    return !!this.element?.classList.contains("focused");
  }
  blur() {
    if (this.element) {
      this.element.blur();
      this.element.tabIndex = -1;
      this.element.classList.remove("focused");
    }
  }
  setFocusable(focusable) {
    if (this.element) {
      this.element.tabIndex = focusable ? 0 : -1;
    }
  }
  get trapsArrowNavigation() {
    return false;
  }
  z() {
  }
  C() {
  }
  D() {
    return this.action.class;
  }
  F() {
    return this.action.tooltip;
  }
  G() {
    if (!this.element) {
      return;
    }
    const title = this.F() ?? "";
    this.H();
    if (this.u.hoverDelegate?.showNativeHover) {
      this.element.title = title;
    } else {
      if (!this.f && title !== "") {
        const hoverDelegate = this.u.hoverDelegate ?? $JZ("element");
        this.f = this.q.add($J1().setupManagedHover(hoverDelegate, this.element, title));
      } else if (this.f) {
        this.f.update(title);
      }
    }
  }
  H() {
    if (this.element) {
      const title = this.F() ?? "";
      this.element.setAttribute("aria-label", title);
    }
  }
  I() {
  }
  J() {
  }
  dispose() {
    if (this.element) {
      this.element.remove();
      this.element = void 0;
    }
    this._context = void 0;
    super.dispose();
  }
};
var $U1 = class extends $T1 {
  constructor(context, action, options3) {
    super(context, action, options3);
    this.u = options3;
    this.u.icon = options3.icon !== void 0 ? options3.icon : false;
    this.u.label = options3.label !== void 0 ? options3.label : true;
    this.N = "";
  }
  render(container2) {
    super.render(container2);
    $Jg(this.element);
    const label3 = document.createElement("a");
    label3.classList.add("action-label");
    label3.setAttribute("role", this.O());
    this.L = label3;
    this.element.appendChild(label3);
    if (this.u.label && this.u.keybinding && !this.u.keybindingNotRenderedWithLabel) {
      const kbLabel = document.createElement("span");
      kbLabel.classList.add("keybinding");
      kbLabel.textContent = this.u.keybinding;
      this.element.appendChild(kbLabel);
    }
    this.I();
    this.C();
    this.G();
    this.z();
    this.J();
  }
  O() {
    if (this._action.id === $Wm.ID) {
      return "presentation";
    } else {
      if (this.u.isMenu) {
        return "menuitem";
      } else if (this.u.isTabList) {
        return "tab";
      } else {
        return "button";
      }
    }
  }
  // Only set the tabIndex on the element once it is about to get focused
  // That way this element wont be a tab stop when it is not needed #106441
  focus() {
    if (this.L) {
      this.L.tabIndex = 0;
      this.L.focus();
    }
  }
  isFocused() {
    return !!this.L && this.L?.tabIndex === 0;
  }
  blur() {
    if (this.L) {
      this.L.tabIndex = -1;
    }
  }
  setFocusable(focusable) {
    if (this.L) {
      this.L.tabIndex = focusable ? 0 : -1;
    }
  }
  C() {
    if (this.u.label && this.L) {
      this.L.textContent = this.action.label;
    }
  }
  F() {
    let title = null;
    if (this.action.tooltip) {
      title = this.action.tooltip;
    } else if (this.action.label) {
      title = this.action.label;
      if (this.u.keybinding) {
        title = localize(0, null, title, this.u.keybinding);
      }
    }
    return title ?? void 0;
  }
  I() {
    if (this.N && this.L) {
      this.L.classList.remove(...this.N.split(" "));
    }
    if (this.u.icon) {
      this.N = this.D();
      if (this.L) {
        this.L.classList.add("codicon");
        if (this.N) {
          this.L.classList.add(...this.N.split(" "));
        }
      }
      this.z();
    } else {
      this.L?.classList.remove("codicon");
    }
  }
  z() {
    if (this.action.enabled) {
      if (this.L) {
        this.L.removeAttribute("aria-disabled");
        this.L.classList.remove("disabled");
      }
      this.element?.classList.remove("disabled");
    } else {
      if (this.L) {
        this.L.setAttribute("aria-disabled", "true");
        this.L.classList.add("disabled");
      }
      this.element?.classList.add("disabled");
    }
  }
  H() {
    if (this.L) {
      const title = this.F() ?? "";
      this.L.setAttribute("aria-label", title);
    }
  }
  J() {
    if (this.L) {
      if (this.action.checked !== void 0) {
        this.L.classList.toggle("checked", this.action.checked);
        if (this.u.isTabList) {
          this.L.setAttribute("aria-selected", this.action.checked ? "true" : "false");
        } else {
          this.L.setAttribute("aria-checked", this.action.checked ? "true" : "false");
          this.L.setAttribute("role", "checkbox");
        }
      } else {
        this.L.classList.remove("checked");
        this.L.removeAttribute(this.u.isTabList ? "aria-selected" : "aria-checked");
        this.L.setAttribute("role", this.O());
      }
    }
  }
};
var $V1 = class extends $T1 {
  constructor(ctx, action, options3, selected, contextViewProvider, styles, selectBoxOptions) {
    super(ctx, action);
    this.b = new $N1(options3, selected, contextViewProvider, styles, selectBoxOptions);
    this.b.setFocusable(false);
    this.B(this.b);
    this.g();
  }
  setOptions(options3, selected) {
    this.b.setOptions(options3, selected);
  }
  select(index) {
    this.b.select(index);
  }
  g() {
    this.B(this.b.onDidSelect((e) => this.m(e.selected, e.index)));
  }
  m(option, index) {
    this.actionRunner.run(this._action, this.n(option, index));
  }
  n(option, index) {
    return option;
  }
  setFocusable(focusable) {
    this.b.setFocusable(focusable);
  }
  focus() {
    this.b?.focus();
  }
  blur() {
    this.b?.blur();
  }
  render(container2) {
    this.b.render(container2);
  }
};

// out-build/vs/base/browser/ui/actionbar/actionbar.js
var ActionsOrientation;
(function(ActionsOrientation2) {
  ActionsOrientation2[ActionsOrientation2["HORIZONTAL"] = 0] = "HORIZONTAL";
  ActionsOrientation2[ActionsOrientation2["VERTICAL"] = 1] = "VERTICAL";
})(ActionsOrientation || (ActionsOrientation = {}));
var $LZ = class extends $3c {
  constructor(container2, options3 = {}) {
    super();
    this.j = this.B(new $2c());
    this.s = this.B(new $_c());
    this.y = false;
    this.z = true;
    this.D = this.B(new $ze());
    this.onDidBlur = this.D.event;
    this.F = this.B(new $ze({ onWillAddFirstListener: () => this.G = true }));
    this.onDidCancel = this.F.event;
    this.G = false;
    this.H = this.B(new $ze());
    this.onDidRun = this.H.event;
    this.I = this.B(new $ze());
    this.onWillRun = this.I.event;
    this.b = options3;
    this.m = options3.context ?? null;
    this.n = this.b.orientation ?? 0;
    this.r = {
      keyDown: this.b.triggerKeys?.keyDown ?? false,
      keys: this.b.triggerKeys?.keys ?? [
        3,
        10
        /* KeyCode.Space */
      ]
    };
    this.f = options3.hoverDelegate ?? this.B($KZ());
    if (this.b.actionRunner) {
      this.g = this.b.actionRunner;
    } else {
      this.g = new $Vm();
      this.j.add(this.g);
    }
    this.j.add(this.g.onDidRun((e) => this.H.fire(e)));
    this.j.add(this.g.onWillRun((e) => this.I.fire(e)));
    this.viewItems = [];
    this.u = void 0;
    this.domNode = document.createElement("div");
    this.domNode.className = "monaco-action-bar";
    let previousKeys;
    let nextKeys;
    switch (this.n) {
      case 0:
        previousKeys = [
          15
          /* KeyCode.LeftArrow */
        ];
        nextKeys = [
          17
          /* KeyCode.RightArrow */
        ];
        break;
      case 1:
        previousKeys = [
          16
          /* KeyCode.UpArrow */
        ];
        nextKeys = [
          18
          /* KeyCode.DownArrow */
        ];
        this.domNode.className += " vertical";
        break;
    }
    this.B($_i(this.domNode, $7j.KEY_DOWN, (e) => {
      const event = new $if(e);
      let eventHandled = true;
      const focusedItem = typeof this.u === "number" ? this.viewItems[this.u] : void 0;
      if (previousKeys && (event.equals(previousKeys[0]) || event.equals(previousKeys[1]))) {
        eventHandled = this.Q();
      } else if (nextKeys && (event.equals(nextKeys[0]) || event.equals(nextKeys[1]))) {
        eventHandled = this.P();
      } else if (event.equals(
        9
        /* KeyCode.Escape */
      ) && this.G) {
        this.F.fire();
      } else if (event.equals(
        14
        /* KeyCode.Home */
      )) {
        eventHandled = this.N();
      } else if (event.equals(
        13
        /* KeyCode.End */
      )) {
        eventHandled = this.O();
      } else if (event.equals(
        2
        /* KeyCode.Tab */
      ) && focusedItem instanceof $T1 && focusedItem.trapsArrowNavigation) {
        eventHandled = this.P(void 0, true);
      } else if (this.L(event)) {
        if (this.r.keyDown) {
          this.S(event);
        } else {
          this.y = true;
        }
      } else {
        eventHandled = false;
      }
      if (eventHandled) {
        event.preventDefault();
        event.stopPropagation();
      }
    }));
    this.B($_i(this.domNode, $7j.KEY_UP, (e) => {
      const event = new $if(e);
      if (this.L(event)) {
        if (!this.r.keyDown && this.y) {
          this.y = false;
          this.S(event);
        }
        event.preventDefault();
        event.stopPropagation();
      } else if (event.equals(
        2
        /* KeyCode.Tab */
      ) || event.equals(
        1024 | 2
        /* KeyCode.Tab */
      ) || event.equals(
        16
        /* KeyCode.UpArrow */
      ) || event.equals(
        18
        /* KeyCode.DownArrow */
      ) || event.equals(
        15
        /* KeyCode.LeftArrow */
      ) || event.equals(
        17
        /* KeyCode.RightArrow */
      )) {
        this.M();
      }
    }));
    this.w = this.B($_j(this.domNode));
    this.B(this.w.onDidBlur(() => {
      if ($Lj() === this.domNode || !$Dj($Lj(), this.domNode)) {
        this.D.fire();
        this.t = this.u;
        this.u = void 0;
        this.y = false;
      }
    }));
    this.B(this.w.onDidFocus(() => this.M()));
    this.C = document.createElement("ul");
    this.C.className = "actions-container";
    if (this.b.highlightToggledItems) {
      this.C.classList.add("highlight-toggled");
    }
    this.C.setAttribute("role", this.b.ariaRole || "toolbar");
    if (this.b.ariaLabel) {
      this.C.setAttribute("aria-label", this.b.ariaLabel);
    }
    this.domNode.appendChild(this.C);
    container2.appendChild(this.domNode);
  }
  J() {
    if (this.length() >= 1) {
      this.C.setAttribute("role", this.b.ariaRole || "toolbar");
    } else {
      this.C.setAttribute("role", "presentation");
    }
  }
  setAriaLabel(label3) {
    if (label3) {
      this.C.setAttribute("aria-label", label3);
    } else {
      this.C.removeAttribute("aria-label");
    }
  }
  // Some action bars should not be focusable at times
  // When an action bar is not focusable make sure to make all the elements inside it not focusable
  // When an action bar is focusable again, make sure the first item can be focused
  setFocusable(focusable) {
    this.z = focusable;
    if (this.z) {
      const firstEnabled = this.viewItems.find((vi) => vi instanceof $T1 && vi.isEnabled());
      if (firstEnabled instanceof $T1) {
        firstEnabled.setFocusable(true);
      }
    } else {
      this.viewItems.forEach((vi) => {
        if (vi instanceof $T1) {
          vi.setFocusable(false);
        }
      });
    }
  }
  L(event) {
    let ret = false;
    this.r.keys.forEach((keyCode) => {
      ret = ret || event.equals(keyCode);
    });
    return ret;
  }
  M() {
    for (let i2 = 0; i2 < this.C.children.length; i2++) {
      const elem = this.C.children[i2];
      if ($Dj($Lj(), elem)) {
        this.u = i2;
        this.viewItems[this.u]?.showHover?.();
        break;
      }
    }
  }
  get context() {
    return this.m;
  }
  set context(context) {
    this.m = context;
    this.viewItems.forEach((i2) => i2.setActionContext(context));
  }
  get actionRunner() {
    return this.g;
  }
  set actionRunner(actionRunner) {
    this.g = actionRunner;
    this.j.clear();
    this.j.add(this.g.onDidRun((e) => this.H.fire(e)));
    this.j.add(this.g.onWillRun((e) => this.I.fire(e)));
    this.viewItems.forEach((item) => item.actionRunner = actionRunner);
  }
  getContainer() {
    return this.domNode;
  }
  hasAction(action) {
    return this.viewItems.findIndex((candidate) => candidate.action.id === action.id) !== -1;
  }
  getAction(indexOrElement) {
    if (typeof indexOrElement === "number") {
      return this.viewItems[indexOrElement]?.action;
    }
    if ($Uj(indexOrElement)) {
      while (indexOrElement.parentElement !== this.C) {
        if (!indexOrElement.parentElement) {
          return void 0;
        }
        indexOrElement = indexOrElement.parentElement;
      }
      for (let i2 = 0; i2 < this.C.childNodes.length; i2++) {
        if (this.C.childNodes[i2] === indexOrElement) {
          return this.viewItems[i2].action;
        }
      }
    }
    return void 0;
  }
  push(arg, options3 = {}) {
    const actions = Array.isArray(arg) ? arg : [arg];
    let index = $Dg(options3.index) ? options3.index : null;
    actions.forEach((action) => {
      const actionViewItemElement = document.createElement("li");
      actionViewItemElement.className = "action-item";
      actionViewItemElement.setAttribute("role", "presentation");
      let item;
      const viewItemOptions = { hoverDelegate: this.f, ...options3, isTabList: this.b.ariaRole === "tablist" };
      if (this.b.actionViewItemProvider) {
        item = this.b.actionViewItemProvider(action, viewItemOptions);
      }
      if (!item) {
        item = new $U1(this.context, action, viewItemOptions);
      }
      if (!this.b.allowContextMenu) {
        this.s.set(item, $_i(actionViewItemElement, $7j.CONTEXT_MENU, (e) => {
          $9j.stop(e, true);
        }));
      }
      item.actionRunner = this.g;
      item.setActionContext(this.context);
      item.render(actionViewItemElement);
      if (this.z && item instanceof $T1 && this.viewItems.length === 0) {
        item.setFocusable(true);
      }
      if (index === null || index < 0 || index >= this.C.children.length) {
        this.C.appendChild(actionViewItemElement);
        this.viewItems.push(item);
      } else {
        this.C.insertBefore(actionViewItemElement, this.C.children[index]);
        this.viewItems.splice(index, 0, item);
        index++;
      }
    });
    if (typeof this.u === "number") {
      this.focus(this.u);
    }
    this.J();
  }
  getWidth(index) {
    if (index >= 0 && index < this.C.children.length) {
      const item = this.C.children.item(index);
      if (item) {
        return item.clientWidth;
      }
    }
    return 0;
  }
  getHeight(index) {
    if (index >= 0 && index < this.C.children.length) {
      const item = this.C.children.item(index);
      if (item) {
        return item.clientHeight;
      }
    }
    return 0;
  }
  pull(index) {
    if (index >= 0 && index < this.viewItems.length) {
      this.C.childNodes[index].remove();
      this.s.deleteAndDispose(this.viewItems[index]);
      $Xc(this.viewItems.splice(index, 1));
      this.J();
    }
  }
  clear() {
    if (this.isEmpty()) {
      return;
    }
    this.viewItems = $Xc(this.viewItems);
    this.s.clearAndDisposeAll();
    $$i(this.C);
    this.J();
  }
  length() {
    return this.viewItems.length;
  }
  isEmpty() {
    return this.viewItems.length === 0;
  }
  focus(arg) {
    let selectFirst = false;
    let index = void 0;
    if (arg === void 0) {
      selectFirst = true;
    } else if (typeof arg === "number") {
      index = arg;
    } else if (typeof arg === "boolean") {
      selectFirst = arg;
    }
    if (selectFirst && typeof this.u === "undefined") {
      const firstEnabled = this.viewItems.findIndex((item) => item.isEnabled());
      this.u = firstEnabled === -1 ? void 0 : firstEnabled;
      this.R(void 0, void 0, true);
    } else {
      if (index !== void 0) {
        this.u = index;
      }
      this.R(void 0, void 0, true);
    }
  }
  N() {
    this.u = this.length() - 1;
    return this.P(true);
  }
  O() {
    this.u = 0;
    return this.Q(true);
  }
  P(forceLoop, forceFocus) {
    if (typeof this.u === "undefined") {
      this.u = this.viewItems.length - 1;
    } else if (this.viewItems.length <= 1) {
      return false;
    }
    const startIndex = this.u;
    let item;
    do {
      if (!forceLoop && this.b.preventLoopNavigation && this.u + 1 >= this.viewItems.length) {
        this.u = startIndex;
        return false;
      }
      this.u = (this.u + 1) % this.viewItems.length;
      item = this.viewItems[this.u];
    } while (this.u !== startIndex && (this.b.focusOnlyEnabledItems && !item.isEnabled() || item.action.id === $Wm.ID));
    this.R(void 0, void 0, forceFocus);
    return true;
  }
  Q(forceLoop) {
    if (typeof this.u === "undefined") {
      this.u = 0;
    } else if (this.viewItems.length <= 1) {
      return false;
    }
    const startIndex = this.u;
    let item;
    do {
      this.u = this.u - 1;
      if (this.u < 0) {
        if (!forceLoop && this.b.preventLoopNavigation) {
          this.u = startIndex;
          return false;
        }
        this.u = this.viewItems.length - 1;
      }
      item = this.viewItems[this.u];
    } while (this.u !== startIndex && (this.b.focusOnlyEnabledItems && !item.isEnabled() || item.action.id === $Wm.ID));
    this.R(true);
    return true;
  }
  R(fromRight, preventScroll, forceFocus = false) {
    if (typeof this.u === "undefined") {
      this.C.focus({ preventScroll });
    }
    if (this.t !== void 0 && this.t !== this.u) {
      this.viewItems[this.t]?.blur();
    }
    const actionViewItem = this.u !== void 0 ? this.viewItems[this.u] : void 0;
    if (actionViewItem) {
      let focusItem = true;
      if (!$Ng(actionViewItem.focus)) {
        focusItem = false;
      }
      if (this.b.focusOnlyEnabledItems && $Ng(actionViewItem.isEnabled) && !actionViewItem.isEnabled()) {
        focusItem = false;
      }
      if (actionViewItem.action.id === $Wm.ID) {
        focusItem = false;
      }
      if (!focusItem) {
        this.C.focus({ preventScroll });
        this.t = void 0;
      } else if (forceFocus || this.t !== this.u) {
        actionViewItem.focus(fromRight);
        this.t = this.u;
      }
      if (focusItem) {
        actionViewItem.showHover?.();
      }
    }
  }
  S(event) {
    if (typeof this.u === "undefined") {
      return;
    }
    const actionViewItem = this.viewItems[this.u];
    if (actionViewItem instanceof $T1) {
      const context = actionViewItem._context === null || actionViewItem._context === void 0 ? event : actionViewItem._context;
      this.run(actionViewItem._action, context);
    }
  }
  async run(action, context) {
    await this.g.run(action, context);
  }
  dispose() {
    this.m = void 0;
    this.viewItems = $Xc(this.viewItems);
    this.getContainer().remove();
    super.dispose();
  }
};
function $MZ(actions) {
  if (!actions.length) {
    return actions;
  }
  let firstIndexOfAction = -1;
  for (let i2 = 0; i2 < actions.length; i2++) {
    if (actions[i2].id === $Wm.ID) {
      continue;
    }
    firstIndexOfAction = i2;
    break;
  }
  if (firstIndexOfAction === -1) {
    return [];
  }
  actions = actions.slice(firstIndexOfAction);
  for (let h3 = actions.length - 1; h3 >= 0; h3--) {
    const isSeparator = actions[h3].id === $Wm.ID;
    if (isSeparator) {
      actions.splice(h3, 1);
    } else {
      break;
    }
  }
  let foundAction = false;
  for (let k = actions.length - 1; k >= 0; k--) {
    const isSeparator = actions[k].id === $Wm.ID;
    if (isSeparator && !foundAction) {
      actions.splice(k, 1);
    } else if (!isSeparator) {
      foundAction = true;
    } else if (isSeparator) {
      foundAction = false;
    }
  }
  return actions;
}

// out-build/vs/editor/browser/widget/diffEditor/utils.js
function $Q9(arr1, arr2, keySelector, combine) {
  if (arr1.length === 0) {
    return arr2;
  }
  if (arr2.length === 0) {
    return arr1;
  }
  const result = [];
  let i2 = 0;
  let j = 0;
  while (i2 < arr1.length && j < arr2.length) {
    const val1 = arr1[i2];
    const val2 = arr2[j];
    const key1 = keySelector(val1);
    const key2 = keySelector(val2);
    if (key1 < key2) {
      result.push(val1);
      i2++;
    } else if (key1 > key2) {
      result.push(val2);
      j++;
    } else {
      result.push(combine(val1, val2));
      i2++;
      j++;
    }
  }
  while (i2 < arr1.length) {
    result.push(arr1[i2]);
    i2++;
  }
  while (j < arr2.length) {
    result.push(arr2[j]);
    j++;
  }
  return result;
}
function $R9(editor, decorations) {
  const d = new $2c();
  const decorationsCollection = editor.createDecorationsCollection();
  d.add($ud({ debugName: () => `Apply decorations from ${decorations.debugName}` }, (reader) => {
    const d2 = decorations.read(reader);
    decorationsCollection.set(d2);
  }));
  d.add({
    dispose: () => {
      decorationsCollection.clear();
    }
  });
  return d;
}
function $S9(parent, child) {
  parent.appendChild(child);
  return $1c(() => {
    child.remove();
  });
}
function $T9(parent, child) {
  parent.prepend(child);
  return $1c(() => {
    child.remove();
  });
}
var $U9 = class extends $3c {
  get width() {
    return this.g;
  }
  get height() {
    return this.h;
  }
  get automaticLayout() {
    return this.n;
  }
  constructor(element, dimension) {
    super();
    this.n = false;
    this.f = this.B(new $14(element, dimension));
    this.g = $he(this, this.f.getWidth());
    this.h = $he(this, this.f.getHeight());
    this.B(this.f.onDidChange((e) => $ce((tx) => {
      this.g.set(this.f.getWidth(), tx);
      this.h.set(this.f.getHeight(), tx);
    })));
  }
  observe(dimension) {
    this.f.observe(dimension);
  }
  setAutomaticLayout(automaticLayout) {
    this.n = automaticLayout;
    if (automaticLayout) {
      this.f.startObserving();
    } else {
      this.f.stopObserving();
    }
  }
};
function $V9(targetWindow, base, store) {
  let targetVal = base.get();
  let startVal = targetVal;
  let curVal = targetVal;
  const result = $he("animatedValue", targetVal);
  let animationStartMs = -1;
  const durationMs = 300;
  let animationFrame = void 0;
  store.add($vd({
    createEmptyChangeSummary: () => ({ animate: false }),
    handleChange: (ctx, s) => {
      if (ctx.didChange(base)) {
        s.animate = s.animate || ctx.change;
      }
      return true;
    }
  }, (reader, s) => {
    if (animationFrame !== void 0) {
      targetWindow.cancelAnimationFrame(animationFrame);
      animationFrame = void 0;
    }
    startVal = curVal;
    targetVal = base.read(reader);
    animationStartMs = Date.now() - (s.animate ? 0 : durationMs);
    update();
  }));
  function update() {
    const passedMs = Date.now() - animationStartMs;
    curVal = Math.floor(easeOutExpo(passedMs, startVal, targetVal - startVal, durationMs));
    if (passedMs < durationMs) {
      animationFrame = targetWindow.requestAnimationFrame(update);
    } else {
      curVal = targetVal;
    }
    result.set(curVal, void 0);
  }
  return result;
}
function easeOutExpo(t, b, c, d) {
  return t === d ? b + c : c * (-Math.pow(2, -10 * t / d) + 1) + b;
}
var $X9 = class extends $3c {
  constructor(editor, viewZone, htmlElement) {
    super();
    this.B(new $Z9(editor, htmlElement));
    this.B($19(htmlElement, {
      height: viewZone.actualHeight,
      top: viewZone.actualTop
    }));
  }
};
var $Y9 = class {
  get afterLineNumber() {
    return this.h.get();
  }
  constructor(h3, heightInPx) {
    this.h = h3;
    this.heightInPx = heightInPx;
    this.domNode = document.createElement("div");
    this.f = $he(this, void 0);
    this.g = $he(this, void 0);
    this.actualTop = this.f;
    this.actualHeight = this.g;
    this.showInHiddenAreas = true;
    this.onChange = this.h;
    this.onDomNodeTop = (top2) => {
      this.f.set(top2, void 0);
    };
    this.onComputedHeight = (height) => {
      this.g.set(height, void 0);
    };
  }
};
var $Z9 = class _$Z9 {
  static {
    this.f = 0;
  }
  constructor(k, n) {
    this.k = k;
    this.n = n;
    this.g = `managedOverlayWidget-${_$Z9.f++}`;
    this.h = {
      getId: () => this.g,
      getDomNode: () => this.n,
      getPosition: () => null
    };
    this.k.addOverlayWidget(this.h);
  }
  dispose() {
    this.k.removeOverlayWidget(this.h);
  }
};
function $19(domNode, style) {
  return $td((reader) => {
    for (let [key2, val] of Object.entries(style)) {
      if (val && typeof val === "object" && "read" in val) {
        val = val.read(reader);
      }
      if (typeof val === "number") {
        val = `${val}px`;
      }
      key2 = key2.replace(/[A-Z]/g, (m) => "-" + m.toLowerCase());
      domNode.style[key2] = val;
    }
  });
}
function $29(editor, viewZones, setIsUpdating, zoneIds) {
  const store = new $2c();
  const lastViewZoneIds = [];
  store.add($xd((reader, store2) => {
    const curViewZones = viewZones.read(reader);
    const viewZonIdsPerViewZone = /* @__PURE__ */ new Map();
    const viewZoneIdPerOnChangeObservable = /* @__PURE__ */ new Map();
    if (setIsUpdating) {
      setIsUpdating(true);
    }
    editor.changeViewZones((a) => {
      for (const id2 of lastViewZoneIds) {
        a.removeZone(id2);
        zoneIds?.delete(id2);
      }
      lastViewZoneIds.length = 0;
      for (const z of curViewZones) {
        const id2 = a.addZone(z);
        if (z.setZoneId) {
          z.setZoneId(id2);
        }
        lastViewZoneIds.push(id2);
        zoneIds?.add(id2);
        viewZonIdsPerViewZone.set(z, id2);
      }
    });
    if (setIsUpdating) {
      setIsUpdating(false);
    }
    store2.add($vd({
      createEmptyChangeSummary() {
        return { zoneIds: [] };
      },
      handleChange(context, changeSummary) {
        const id2 = viewZoneIdPerOnChangeObservable.get(context.changedObservable);
        if (id2 !== void 0) {
          changeSummary.zoneIds.push(id2);
        }
        return true;
      }
    }, (reader2, changeSummary) => {
      for (const vz of curViewZones) {
        if (vz.onChange) {
          viewZoneIdPerOnChangeObservable.set(vz.onChange, viewZonIdsPerViewZone.get(vz));
          vz.onChange.read(reader2);
        }
      }
      if (setIsUpdating) {
        setIsUpdating(true);
      }
      editor.changeViewZones((a) => {
        for (const id2 of changeSummary.zoneIds) {
          a.layoutZone(id2);
        }
      });
      if (setIsUpdating) {
        setIsUpdating(false);
      }
    }));
  }));
  store.add({
    dispose() {
      if (setIsUpdating) {
        setIsUpdating(true);
      }
      editor.changeViewZones((a) => {
        for (const id2 of lastViewZoneIds) {
          a.removeZone(id2);
        }
      });
      zoneIds?.clear();
      if (setIsUpdating) {
        setIsUpdating(false);
      }
    }
  });
  return store;
}
var $39 = class extends $ad {
  dispose() {
    super.dispose(true);
  }
};
function $49(posInOriginal, mappings) {
  const mapping2 = $1(mappings, (m) => m.original.startLineNumber <= posInOriginal.lineNumber);
  if (!mapping2) {
    return $9C.fromPositions(posInOriginal);
  }
  if (mapping2.original.endLineNumberExclusive <= posInOriginal.lineNumber) {
    const newLineNumber = posInOriginal.lineNumber - mapping2.original.endLineNumberExclusive + mapping2.modified.endLineNumberExclusive;
    return $9C.fromPositions(new $8C(newLineNumber, posInOriginal.column));
  }
  if (!mapping2.innerChanges) {
    return $9C.fromPositions(new $8C(mapping2.modified.startLineNumber, 1));
  }
  const innerMapping = $1(mapping2.innerChanges, (m) => m.originalRange.getStartPosition().isBeforeOrEqual(posInOriginal));
  if (!innerMapping) {
    const newLineNumber = posInOriginal.lineNumber - mapping2.original.startLineNumber + mapping2.modified.startLineNumber;
    return $9C.fromPositions(new $8C(newLineNumber, posInOriginal.column));
  }
  if (innerMapping.originalRange.containsPosition(posInOriginal)) {
    return innerMapping.modifiedRange;
  } else {
    const l = lengthBetweenPositions(innerMapping.originalRange.getEndPosition(), posInOriginal);
    return $9C.fromPositions(l.addToPosition(innerMapping.modifiedRange.getEndPosition()));
  }
}
function lengthBetweenPositions(position1, position2) {
  if (position1.lineNumber === position2.lineNumber) {
    return new $gD(0, position2.column - position1.column);
  } else {
    return new $gD(position2.lineNumber - position1.lineNumber, position2.column - 1);
  }
}
function $59(arr, filter) {
  let prev;
  return arr.filter((cur) => {
    const result = filter(cur, prev);
    prev = cur;
    return result;
  });
}
var $69 = class {
  static create(value, debugOwner = void 0) {
    return new BaseRefCounted(value, value, debugOwner);
  }
  static createWithDisposable(value, disposable, debugOwner = void 0) {
    const store = new $2c();
    store.add(disposable);
    store.add(value);
    return new BaseRefCounted(value, store, debugOwner);
  }
  static createOfNonDisposable(value, disposable, debugOwner = void 0) {
    return new BaseRefCounted(value, disposable, debugOwner);
  }
};
var BaseRefCounted = class extends $69 {
  constructor(object, k, n) {
    super();
    this.object = object;
    this.k = k;
    this.n = n;
    this.f = 1;
    this.g = false;
    this.h = [];
    if (n) {
      this.o(n);
    }
  }
  o(debugOwner) {
    if (debugOwner) {
      this.h.push(debugOwner);
    }
  }
  createNewRef(debugOwner) {
    this.f++;
    if (debugOwner) {
      this.o(debugOwner);
    }
    return new ClonedRefCounted(this, debugOwner);
  }
  dispose() {
    if (this.g) {
      return;
    }
    this.g = true;
    this._decreaseRefCount(this.n);
  }
  _decreaseRefCount(debugOwner) {
    this.f--;
    if (this.f === 0) {
      this.k.dispose();
    }
    if (debugOwner) {
      const idx = this.h.indexOf(debugOwner);
      if (idx !== -1) {
        this.h.splice(idx, 1);
      }
    }
  }
};
var ClonedRefCounted = class extends $69 {
  constructor(g, h3) {
    super();
    this.g = g;
    this.h = h3;
    this.f = false;
  }
  get object() {
    return this.g.object;
  }
  createNewRef(debugOwner) {
    return this.g.createNewRef(debugOwner);
  }
  dispose() {
    if (this.f) {
      return;
    }
    this.f = true;
    this.g._decreaseRefCount(this.h);
  }
};

// out-build/vs/editor/common/core/offsetEdit.js
var $cD = class _$cD {
  static {
    this.empty = new _$cD([]);
  }
  static fromJson(data) {
    return new _$cD(data.map($dD.fromJson));
  }
  static replace(range, newText) {
    return new _$cD([new $dD(range, newText)]);
  }
  static insert(offset, insertText) {
    return _$cD.replace($0C.emptyAt(offset), insertText);
  }
  constructor(edits) {
    this.edits = edits;
    let lastEndEx = -1;
    for (const edit3 of edits) {
      if (!(edit3.replaceRange.start >= lastEndEx)) {
        throw new $vb(`Edits must be disjoint and sorted. Found ${edit3} after ${lastEndEx}`);
      }
      lastEndEx = edit3.replaceRange.endExclusive;
    }
  }
  normalize() {
    const edits = [];
    let lastEdit;
    for (const edit3 of this.edits) {
      if (edit3.newText.length === 0 && edit3.replaceRange.length === 0) {
        continue;
      }
      if (lastEdit && lastEdit.replaceRange.endExclusive === edit3.replaceRange.start) {
        lastEdit = new $dD(lastEdit.replaceRange.join(edit3.replaceRange), lastEdit.newText + edit3.newText);
      } else {
        if (lastEdit) {
          edits.push(lastEdit);
        }
        lastEdit = edit3;
      }
    }
    if (lastEdit) {
      edits.push(lastEdit);
    }
    return new _$cD(edits);
  }
  toString() {
    const edits = this.edits.map((e) => e.toString()).join(", ");
    return `[${edits}]`;
  }
  apply(str) {
    const resultText = [];
    let pos = 0;
    for (const edit3 of this.edits) {
      resultText.push(str.substring(pos, edit3.replaceRange.start));
      resultText.push(edit3.newText);
      pos = edit3.replaceRange.endExclusive;
    }
    resultText.push(str.substring(pos));
    return resultText.join("");
  }
  compose(other) {
    return joinEdits(this, other);
  }
  /**
   * Creates an edit that reverts this edit.
   */
  inverse(originalStr) {
    const edits = [];
    let offset = 0;
    for (const e of this.edits) {
      edits.push(new $dD($0C.ofStartAndLength(e.replaceRange.start + offset, e.newText.length), originalStr.substring(e.replaceRange.start, e.replaceRange.endExclusive)));
      offset += e.newText.length - e.replaceRange.length;
    }
    return new _$cD(edits);
  }
  getNewTextRanges() {
    const ranges = [];
    let offset = 0;
    for (const e of this.edits) {
      ranges.push($0C.ofStartAndLength(e.replaceRange.start + offset, e.newText.length));
      offset += e.newText.length - e.replaceRange.length;
    }
    return ranges;
  }
  get isEmpty() {
    return this.edits.length === 0;
  }
  tryRebase(base, noOverlap) {
    const newEdits = [];
    let baseIdx = 0;
    let ourIdx = 0;
    let offset = 0;
    while (ourIdx < this.edits.length || baseIdx < base.edits.length) {
      const baseEdit = base.edits[baseIdx];
      const ourEdit = this.edits[ourIdx];
      if (!ourEdit) {
        break;
      } else if (!baseEdit) {
        newEdits.push(new $dD(ourEdit.replaceRange.delta(offset), ourEdit.newText));
        ourIdx++;
      } else if (ourEdit.replaceRange.intersectsOrTouches(baseEdit.replaceRange)) {
        ourIdx++;
        if (noOverlap) {
          return void 0;
        }
      } else if (ourEdit.replaceRange.start < baseEdit.replaceRange.start) {
        newEdits.push(new $dD(ourEdit.replaceRange.delta(offset), ourEdit.newText));
        ourIdx++;
      } else {
        baseIdx++;
        offset += baseEdit.newText.length - baseEdit.replaceRange.length;
      }
    }
    return new _$cD(newEdits);
  }
  applyToOffset(originalOffset) {
    let accumulatedDelta = 0;
    for (const edit3 of this.edits) {
      if (edit3.replaceRange.start <= originalOffset) {
        if (originalOffset < edit3.replaceRange.endExclusive) {
          return edit3.replaceRange.start + accumulatedDelta;
        }
        accumulatedDelta += edit3.newText.length - edit3.replaceRange.length;
      } else {
        break;
      }
    }
    return originalOffset + accumulatedDelta;
  }
  applyToOffsetRange(originalRange) {
    return new $0C(this.applyToOffset(originalRange.start), this.applyToOffset(originalRange.endExclusive));
  }
  applyInverseToOffset(postEditsOffset) {
    let accumulatedDelta = 0;
    for (const edit3 of this.edits) {
      const editLength = edit3.newText.length;
      if (edit3.replaceRange.start <= postEditsOffset - accumulatedDelta) {
        if (postEditsOffset - accumulatedDelta < edit3.replaceRange.start + editLength) {
          return edit3.replaceRange.start;
        }
        accumulatedDelta += editLength - edit3.replaceRange.length;
      } else {
        break;
      }
    }
    return postEditsOffset - accumulatedDelta;
  }
};
var $dD = class _$dD {
  static fromJson(data) {
    return new _$dD($0C.ofStartAndLength(data.pos, data.len), data.txt);
  }
  static insert(offset, text2) {
    return new _$dD($0C.emptyAt(offset), text2);
  }
  constructor(replaceRange, newText) {
    this.replaceRange = replaceRange;
    this.newText = newText;
  }
  toString() {
    return `${this.replaceRange} -> "${this.newText}"`;
  }
  get isEmpty() {
    return this.newText.length === 0 && this.replaceRange.length === 0;
  }
};
function joinEdits(edits1, edits2) {
  edits1 = edits1.normalize();
  edits2 = edits2.normalize();
  if (edits1.isEmpty) {
    return edits2;
  }
  if (edits2.isEmpty) {
    return edits1;
  }
  const edit1Queue = [...edits1.edits];
  const result = [];
  let edit1ToEdit2 = 0;
  for (const edit22 of edits2.edits) {
    while (true) {
      const edit1 = edit1Queue[0];
      if (!edit1 || edit1.replaceRange.start + edit1ToEdit2 + edit1.newText.length >= edit22.replaceRange.start) {
        break;
      }
      edit1Queue.shift();
      result.push(edit1);
      edit1ToEdit2 += edit1.newText.length - edit1.replaceRange.length;
    }
    const firstEdit1ToEdit2 = edit1ToEdit2;
    let firstIntersecting;
    let lastIntersecting;
    while (true) {
      const edit1 = edit1Queue[0];
      if (!edit1 || edit1.replaceRange.start + edit1ToEdit2 > edit22.replaceRange.endExclusive) {
        break;
      }
      if (!firstIntersecting) {
        firstIntersecting = edit1;
      }
      lastIntersecting = edit1;
      edit1Queue.shift();
      edit1ToEdit2 += edit1.newText.length - edit1.replaceRange.length;
    }
    if (!firstIntersecting) {
      result.push(new $dD(edit22.replaceRange.delta(-edit1ToEdit2), edit22.newText));
    } else {
      let prefix = "";
      const prefixLength = edit22.replaceRange.start - (firstIntersecting.replaceRange.start + firstEdit1ToEdit2);
      if (prefixLength > 0) {
        prefix = firstIntersecting.newText.slice(0, prefixLength);
      }
      const suffixLength = lastIntersecting.replaceRange.endExclusive + edit1ToEdit2 - edit22.replaceRange.endExclusive;
      if (suffixLength > 0) {
        const e = new $dD($0C.ofStartAndLength(lastIntersecting.replaceRange.endExclusive, 0), lastIntersecting.newText.slice(-suffixLength));
        edit1Queue.unshift(e);
        edit1ToEdit2 -= e.newText.length - e.replaceRange.length;
      }
      const newText = prefix + edit22.newText;
      const newReplaceRange = new $0C(Math.min(firstIntersecting.replaceRange.start, edit22.replaceRange.start - firstEdit1ToEdit2), edit22.replaceRange.endExclusive - edit1ToEdit2);
      result.push(new $dD(newReplaceRange, newText));
    }
  }
  while (true) {
    const item = edit1Queue.shift();
    if (!item) {
      break;
    }
    result.push(item);
  }
  return new $cD(result).normalize();
}

// out-build/vs/editor/common/core/lineEdit.js
var $eD = class _$eD {
  static {
    this.empty = new _$eD([]);
  }
  static deserialize(data) {
    return new _$eD(data.map((e) => $fD.deserialize(e)));
  }
  static fromEdit(edit3, initialValue) {
    const textEdit = $iD.fromOffsetEdit(edit3, initialValue);
    return _$eD.fromTextEdit(textEdit, initialValue);
  }
  static fromTextEdit(edit3, initialValue) {
    const edits = edit3.edits;
    const result = [];
    const currentEdits = [];
    for (let i2 = 0; i2 < edits.length; i2++) {
      const edit4 = edits[i2];
      const nextEditRange = i2 + 1 < edits.length ? edits[i2 + 1] : void 0;
      currentEdits.push(edit4);
      if (nextEditRange && nextEditRange.range.startLineNumber === edit4.range.endLineNumber) {
        continue;
      }
      const singleEdit = $jD.joinEdits(currentEdits, initialValue);
      currentEdits.length = 0;
      const singleLineEdit = $fD.fromSingleTextEdit(singleEdit, initialValue);
      result.push(singleLineEdit);
    }
    return new _$eD(result);
  }
  static createFromUnsorted(edits) {
    const result = edits.slice();
    result.sort($9b((i2) => i2.lineRange.startLineNumber, $$b));
    return new _$eD(result);
  }
  constructor(edits) {
    this.edits = edits;
    $id($ld(edits, (i1, i2) => i1.lineRange.endLineNumberExclusive <= i2.lineRange.startLineNumber));
  }
  toEdit(initialValue) {
    const edits = [];
    for (const edit3 of this.edits) {
      const singleEdit = edit3.toSingleEdit(initialValue);
      edits.push(singleEdit);
    }
    return new $cD(edits);
  }
  toString() {
    return this.edits.map((e) => e.toString()).join(",");
  }
  serialize() {
    return this.edits.map((e) => e.serialize());
  }
  getNewLineRanges() {
    const ranges = [];
    let offset = 0;
    for (const e of this.edits) {
      ranges.push($_C.ofLength(e.lineRange.startLineNumber + offset, e.newLines.length));
      offset += e.newLines.length - e.lineRange.length;
    }
    return ranges;
  }
  mapLineNumber(lineNumber) {
    let lineDelta = 0;
    for (const e of this.edits) {
      if (e.lineRange.endLineNumberExclusive > lineNumber) {
        break;
      }
      lineDelta += e.newLines.length - e.lineRange.length;
    }
    return lineNumber + lineDelta;
  }
  mapLineRange(lineRange) {
    return new $_C(this.mapLineNumber(lineRange.startLineNumber), this.mapLineNumber(lineRange.endLineNumberExclusive));
  }
  rebase(base) {
    return new _$eD(this.edits.map((e) => new $fD(base.mapLineRange(e.lineRange), e.newLines)));
  }
  humanReadablePatch(originalLines) {
    const result = [];
    function pushLine(originalLineNumber, modifiedLineNumber, kind, content) {
      const specialChar = kind === "unmodified" ? " " : kind === "deleted" ? "-" : "+";
      if (content === void 0) {
        content = "[[[[[ WARNING: LINE DOES NOT EXIST ]]]]]";
      }
      const origLn = originalLineNumber === -1 ? "   " : originalLineNumber.toString().padStart(3, " ");
      const modLn = modifiedLineNumber === -1 ? "   " : modifiedLineNumber.toString().padStart(3, " ");
      result.push(`${specialChar} ${origLn} ${modLn} ${content}`);
    }
    function pushSeperator() {
      result.push("---");
    }
    let lineDelta = 0;
    let first = true;
    for (const edits of $Fb(this.edits, (e1, e2) => e1.lineRange.distanceToRange(e2.lineRange) <= 5)) {
      if (!first) {
        pushSeperator();
      } else {
        first = false;
      }
      let lastLineNumber = edits[0].lineRange.startLineNumber - 2;
      for (const edit3 of edits) {
        for (let i2 = Math.max(1, lastLineNumber); i2 < edit3.lineRange.startLineNumber; i2++) {
          pushLine(i2, i2 + lineDelta, "unmodified", originalLines[i2 - 1]);
        }
        const range = edit3.lineRange;
        const newLines = edit3.newLines;
        for (const replaceLineNumber of range.mapToLineArray((n) => n)) {
          const line = originalLines[replaceLineNumber - 1];
          pushLine(replaceLineNumber, -1, "deleted", line);
        }
        for (let i2 = 0; i2 < newLines.length; i2++) {
          const line = newLines[i2];
          pushLine(-1, range.startLineNumber + lineDelta + i2, "added", line);
        }
        lastLineNumber = range.endLineNumberExclusive;
        lineDelta += edit3.newLines.length - edit3.lineRange.length;
      }
      for (let i2 = lastLineNumber; i2 <= Math.min(lastLineNumber + 2, originalLines.length); i2++) {
        pushLine(i2, i2 + lineDelta, "unmodified", originalLines[i2 - 1]);
      }
    }
    return result.join("\n");
  }
  apply(lines) {
    const result = [];
    let currentLineIndex = 0;
    for (const edit3 of this.edits) {
      while (currentLineIndex < edit3.lineRange.startLineNumber - 1) {
        result.push(lines[currentLineIndex]);
        currentLineIndex++;
      }
      for (const newLine of edit3.newLines) {
        result.push(newLine);
      }
      currentLineIndex = edit3.lineRange.endLineNumberExclusive - 1;
    }
    while (currentLineIndex < lines.length) {
      result.push(lines[currentLineIndex]);
      currentLineIndex++;
    }
    return result;
  }
  toSingleEdit() {
  }
};
var $fD = class _$fD {
  static deserialize(e) {
    return new _$fD($_C.ofLength(e[0], e[1] - e[0]), e[2]);
  }
  static fromSingleTextEdit(edit3, initialValue) {
    const newLines = $Mf(edit3.text);
    let startLineNumber = edit3.range.startLineNumber;
    const survivingFirstLineText = initialValue.getValueOfRange($9C.fromPositions(new $8C(edit3.range.startLineNumber, 1), edit3.range.getStartPosition()));
    newLines[0] = survivingFirstLineText + newLines[0];
    let endLineNumberEx = edit3.range.endLineNumber + 1;
    const editEndLineNumberMaxColumn = initialValue.getTransformer().getLineLength(edit3.range.endLineNumber) + 1;
    const survivingEndLineText = initialValue.getValueOfRange($9C.fromPositions(edit3.range.getEndPosition(), new $8C(edit3.range.endLineNumber, editEndLineNumberMaxColumn)));
    newLines[newLines.length - 1] = newLines[newLines.length - 1] + survivingEndLineText;
    const startBeforeNewLine = edit3.range.startColumn === initialValue.getTransformer().getLineLength(edit3.range.startLineNumber) + 1;
    const endAfterNewLine = edit3.range.endColumn === 1;
    if (startBeforeNewLine && newLines[0].length === survivingFirstLineText.length) {
      startLineNumber++;
      newLines.shift();
    }
    if (newLines.length > 0 && startLineNumber < endLineNumberEx && endAfterNewLine && newLines[newLines.length - 1].length === survivingEndLineText.length) {
      endLineNumberEx--;
      newLines.pop();
    }
    return new _$fD(new $_C(startLineNumber, endLineNumberEx), newLines);
  }
  constructor(lineRange, newLines) {
    this.lineRange = lineRange;
    this.newLines = newLines;
  }
  toSingleTextEdit(initialValue) {
    if (this.newLines.length === 0) {
      const textLen = initialValue.getTransformer().textLength;
      if (this.lineRange.endLineNumberExclusive === textLen.lineCount + 2) {
        let startPos;
        if (this.lineRange.startLineNumber > 1) {
          const startLineNumber = this.lineRange.startLineNumber - 1;
          const startColumn = initialValue.getTransformer().getLineLength(startLineNumber) + 1;
          startPos = new $8C(startLineNumber, startColumn);
        } else {
          startPos = new $8C(1, 1);
        }
        const lastPosition = textLen.addToPosition(new $8C(1, 1));
        return new $jD($9C.fromPositions(startPos, lastPosition), "");
      } else {
        return new $jD(new $9C(this.lineRange.startLineNumber, 1, this.lineRange.endLineNumberExclusive, 1), "");
      }
    } else if (this.lineRange.isEmpty) {
      let endLineNumber;
      let column;
      let text2;
      const insertionLine = this.lineRange.startLineNumber;
      if (insertionLine === initialValue.getTransformer().textLength.lineCount + 2) {
        endLineNumber = insertionLine - 1;
        column = initialValue.getTransformer().getLineLength(endLineNumber) + 1;
        text2 = this.newLines.map((l) => "\n" + l).join("");
      } else {
        endLineNumber = insertionLine;
        column = 1;
        text2 = this.newLines.map((l) => l + "\n").join("");
      }
      return new $jD($9C.fromPositions(new $8C(endLineNumber, column)), text2);
    } else {
      const endLineNumber = this.lineRange.endLineNumberExclusive - 1;
      const endLineNumberMaxColumn = initialValue.getTransformer().getLineLength(endLineNumber) + 1;
      const range = new $9C(this.lineRange.startLineNumber, 1, endLineNumber, endLineNumberMaxColumn);
      const text2 = this.newLines.join("\n");
      return new $jD(range, text2);
    }
  }
  toSingleEdit(initialValue) {
    const textEdit = this.toSingleTextEdit(initialValue);
    const range = initialValue.getTransformer().getOffsetRange(textEdit.range);
    return new $dD(range, textEdit.text);
  }
  toString() {
    return `${this.lineRange}->${JSON.stringify(this.newLines)}`;
  }
  serialize() {
    return [
      this.lineRange.startLineNumber,
      this.lineRange.endLineNumberExclusive,
      this.newLines
    ];
  }
  removeCommonSuffixPrefixLines(initialValue) {
    let startLineNumber = this.lineRange.startLineNumber;
    let endLineNumberEx = this.lineRange.endLineNumberExclusive;
    let trimStartCount = 0;
    while (startLineNumber < endLineNumberEx && trimStartCount < this.newLines.length && this.newLines[trimStartCount] === initialValue.getLineAt(startLineNumber)) {
      startLineNumber++;
      trimStartCount++;
    }
    let trimEndCount = 0;
    while (startLineNumber < endLineNumberEx && trimEndCount + trimStartCount < this.newLines.length && this.newLines[this.newLines.length - 1 - trimEndCount] === initialValue.getLineAt(endLineNumberEx - 1)) {
      endLineNumberEx--;
      trimEndCount++;
    }
    if (trimStartCount === 0 && trimEndCount === 0) {
      return this;
    }
    return new _$fD(new $_C(startLineNumber, endLineNumberEx), this.newLines.slice(trimStartCount, this.newLines.length - trimEndCount));
  }
  toLineEdit() {
    return new $eD([this]);
  }
};

// out-build/vs/editor/common/core/textEdit.js
var $iD = class _$iD {
  static fromOffsetEdit(edit3, initialState) {
    const edits = edit3.edits.map((e) => new $jD(initialState.getTransformer().getRange(e.replaceRange), e.newText));
    return new _$iD(edits);
  }
  static single(originalRange, newText) {
    return new _$iD([new $jD(originalRange, newText)]);
  }
  static insert(position, newText) {
    return new _$iD([new $jD($9C.fromPositions(position, position), newText)]);
  }
  constructor(edits) {
    this.edits = edits;
    $kd(() => $ld(edits, (a, b) => a.range.getEndPosition().isBeforeOrEqual(b.range.getStartPosition())));
  }
  /**
   * Joins touching edits and removes empty edits.
   */
  normalize() {
    const edits = [];
    for (const edit3 of this.edits) {
      if (edits.length > 0 && edits[edits.length - 1].range.getEndPosition().equals(edit3.range.getStartPosition())) {
        const last = edits[edits.length - 1];
        edits[edits.length - 1] = new $jD(last.range.plusRange(edit3.range), last.text + edit3.text);
      } else if (!edit3.isEmpty) {
        edits.push(edit3);
      }
    }
    return new _$iD(edits);
  }
  mapPosition(position) {
    let lineDelta = 0;
    let curLine = 0;
    let columnDeltaInCurLine = 0;
    for (const edit3 of this.edits) {
      const start = edit3.range.getStartPosition();
      if (position.isBeforeOrEqual(start)) {
        break;
      }
      const end = edit3.range.getEndPosition();
      const len = $gD.ofText(edit3.text);
      if (position.isBefore(end)) {
        const startPos = new $8C(start.lineNumber + lineDelta, start.column + (start.lineNumber + lineDelta === curLine ? columnDeltaInCurLine : 0));
        const endPos = len.addToPosition(startPos);
        return rangeFromPositions(startPos, endPos);
      }
      if (start.lineNumber + lineDelta !== curLine) {
        columnDeltaInCurLine = 0;
      }
      lineDelta += len.lineCount - (edit3.range.endLineNumber - edit3.range.startLineNumber);
      if (len.lineCount === 0) {
        if (end.lineNumber !== start.lineNumber) {
          columnDeltaInCurLine += len.columnCount - (end.column - 1);
        } else {
          columnDeltaInCurLine += len.columnCount - (end.column - start.column);
        }
      } else {
        columnDeltaInCurLine = len.columnCount;
      }
      curLine = end.lineNumber + lineDelta;
    }
    return new $8C(position.lineNumber + lineDelta, position.column + (position.lineNumber + lineDelta === curLine ? columnDeltaInCurLine : 0));
  }
  mapRange(range) {
    function getStart(p) {
      return p instanceof $8C ? p : p.getStartPosition();
    }
    function getEnd(p) {
      return p instanceof $8C ? p : p.getEndPosition();
    }
    const start = getStart(this.mapPosition(range.getStartPosition()));
    const end = getEnd(this.mapPosition(range.getEndPosition()));
    return rangeFromPositions(start, end);
  }
  // TODO: `doc` is not needed for this!
  inverseMapPosition(positionAfterEdit, doc) {
    const reversed = this.inverse(doc);
    return reversed.mapPosition(positionAfterEdit);
  }
  inverseMapRange(range, doc) {
    const reversed = this.inverse(doc);
    return reversed.mapRange(range);
  }
  apply(text2) {
    let result = "";
    let lastEditEnd = new $8C(1, 1);
    for (const edit3 of this.edits) {
      const editRange = edit3.range;
      const editStart = editRange.getStartPosition();
      const editEnd = editRange.getEndPosition();
      const r3 = rangeFromPositions(lastEditEnd, editStart);
      if (!r3.isEmpty()) {
        result += text2.getValueOfRange(r3);
      }
      result += edit3.text;
      lastEditEnd = editEnd;
    }
    const r2 = rangeFromPositions(lastEditEnd, text2.endPositionExclusive);
    if (!r2.isEmpty()) {
      result += text2.getValueOfRange(r2);
    }
    return result;
  }
  applyToString(str) {
    const strText = new $nD(str);
    return this.apply(strText);
  }
  inverse(doc) {
    const ranges = this.getNewRanges();
    return new _$iD(this.edits.map((e, idx) => new $jD(ranges[idx], doc.getValueOfRange(e.range))));
  }
  getNewRanges() {
    const newRanges = [];
    let previousEditEndLineNumber = 0;
    let lineOffset = 0;
    let columnOffset = 0;
    for (const edit3 of this.edits) {
      const textLength = $gD.ofText(edit3.text);
      const newRangeStart = $8C.lift({
        lineNumber: edit3.range.startLineNumber + lineOffset,
        column: edit3.range.startColumn + (edit3.range.startLineNumber === previousEditEndLineNumber ? columnOffset : 0)
      });
      const newRange = textLength.createRange(newRangeStart);
      newRanges.push(newRange);
      lineOffset = newRange.endLineNumber - edit3.range.endLineNumber;
      columnOffset = newRange.endColumn - edit3.range.endColumn;
      previousEditEndLineNumber = edit3.range.endLineNumber;
    }
    return newRanges;
  }
  toSingle(text2) {
    if (this.edits.length === 0) {
      throw new $vb();
    }
    if (this.edits.length === 1) {
      return this.edits[0];
    }
    const startPos = this.edits[0].range.getStartPosition();
    const endPos = this.edits[this.edits.length - 1].range.getEndPosition();
    let newText = "";
    for (let i2 = 0; i2 < this.edits.length; i2++) {
      const curEdit = this.edits[i2];
      newText += curEdit.text;
      if (i2 < this.edits.length - 1) {
        const nextEdit = this.edits[i2 + 1];
        const gapRange = $9C.fromPositions(curEdit.range.getEndPosition(), nextEdit.range.getStartPosition());
        const gapText = text2.getValueOfRange(gapRange);
        newText += gapText;
      }
    }
    return new $jD($9C.fromPositions(startPos, endPos), newText);
  }
  equals(other) {
    return $zb(this.edits, other.edits, (a, b) => a.equals(b));
  }
};
var $jD = class _$jD {
  static joinEdits(edits, initialValue) {
    if (edits.length === 0) {
      throw new $vb();
    }
    if (edits.length === 1) {
      return edits[0];
    }
    const startPos = edits[0].range.getStartPosition();
    const endPos = edits[edits.length - 1].range.getEndPosition();
    let newText = "";
    for (let i2 = 0; i2 < edits.length; i2++) {
      const curEdit = edits[i2];
      newText += curEdit.text;
      if (i2 < edits.length - 1) {
        const nextEdit = edits[i2 + 1];
        const gapRange = $9C.fromPositions(curEdit.range.getEndPosition(), nextEdit.range.getStartPosition());
        const gapText = initialValue.getValueOfRange(gapRange);
        newText += gapText;
      }
    }
    return new _$jD($9C.fromPositions(startPos, endPos), newText);
  }
  constructor(range, text2) {
    this.range = range;
    this.text = text2;
  }
  get isEmpty() {
    return this.range.isEmpty() && this.text.length === 0;
  }
  static equals(first, second) {
    return first.range.equalsRange(second.range) && first.text === second.text;
  }
  toSingleEditOperation() {
    return {
      range: this.range,
      text: this.text
    };
  }
  toEdit() {
    return new $iD([this]);
  }
  equals(other) {
    return _$jD.equals(this, other);
  }
  extendToCoverRange(range, initialValue) {
    if (this.range.containsRange(range)) {
      return this;
    }
    const newRange = this.range.plusRange(range);
    const textBefore = initialValue.getValueOfRange($9C.fromPositions(newRange.getStartPosition(), this.range.getStartPosition()));
    const textAfter = initialValue.getValueOfRange($9C.fromPositions(this.range.getEndPosition(), newRange.getEndPosition()));
    const newText = textBefore + this.text + textAfter;
    return new _$jD(newRange, newText);
  }
  extendToFullLine(initialValue) {
    const newRange = new $9C(this.range.startLineNumber, 1, this.range.endLineNumber, initialValue.getTransformer().getLineLength(this.range.endLineNumber) + 1);
    return this.extendToCoverRange(newRange, initialValue);
  }
  removeCommonPrefix(text2) {
    const normalizedOriginalText = text2.getValueOfRange(this.range).replaceAll("\r\n", "\n");
    const normalizedModifiedText = this.text.replaceAll("\r\n", "\n");
    const commonPrefixLen = $3f(normalizedOriginalText, normalizedModifiedText);
    const start = $gD.ofText(normalizedOriginalText.substring(0, commonPrefixLen)).addToPosition(this.range.getStartPosition());
    const newText = normalizedModifiedText.substring(commonPrefixLen);
    const range = $9C.fromPositions(start, this.range.getEndPosition());
    return new _$jD(range, newText);
  }
  isEffectiveDeletion(text2) {
    let newText = this.text.replaceAll("\r\n", "\n");
    let existingText = text2.getValueOfRange(this.range).replaceAll("\r\n", "\n");
    const l = $3f(newText, existingText);
    newText = newText.substring(l);
    existingText = existingText.substring(l);
    const r2 = $4f(newText, existingText);
    newText = newText.substring(0, newText.length - r2);
    existingText = existingText.substring(0, existingText.length - r2);
    return newText === "";
  }
};
function rangeFromPositions(start, end) {
  if (start.lineNumber === end.lineNumber && start.column === Number.MAX_SAFE_INTEGER) {
    return $9C.fromPositions(end, end);
  } else if (!start.isBeforeOrEqual(end)) {
    throw new $vb("start must be before end");
  }
  return new $9C(start.lineNumber, start.column, end.lineNumber, end.column);
}
var $kD = class {
  constructor() {
    this.c = void 0;
  }
  get endPositionExclusive() {
    return this.length.addToPosition(new $8C(1, 1));
  }
  get lineRange() {
    return this.length.toLineRange();
  }
  getValue() {
    return this.getValueOfRange(this.length.toRange());
  }
  getLineLength(lineNumber) {
    return this.getValueOfRange(new $9C(lineNumber, 1, lineNumber, Number.MAX_SAFE_INTEGER)).length;
  }
  getTransformer() {
    if (!this.c) {
      this.c = new $hD(this.getValue());
    }
    return this.c;
  }
  getLineAt(lineNumber) {
    return this.getValueOfRange(new $9C(lineNumber, 1, lineNumber, Number.MAX_SAFE_INTEGER));
  }
  getLines() {
    const value = this.getValue();
    return $Mf(value);
  }
};
var $lD = class extends $kD {
  constructor(d, f) {
    $id(f >= 1);
    super();
    this.d = d;
    this.f = f;
  }
  getValueOfRange(range) {
    if (range.startLineNumber === range.endLineNumber) {
      return this.d(range.startLineNumber).substring(range.startColumn - 1, range.endColumn - 1);
    }
    let result = this.d(range.startLineNumber).substring(range.startColumn - 1);
    for (let i2 = range.startLineNumber + 1; i2 < range.endLineNumber; i2++) {
      result += "\n" + this.d(i2);
    }
    result += "\n" + this.d(range.endLineNumber).substring(0, range.endColumn - 1);
    return result;
  }
  getLineLength(lineNumber) {
    return this.d(lineNumber).length;
  }
  get length() {
    const lastLine = this.d(this.f);
    return new $gD(this.f - 1, lastLine.length);
  }
};
var $mD = class extends $lD {
  constructor(lines) {
    super((lineNumber) => lines[lineNumber - 1], lines.length);
  }
};
var $nD = class extends $kD {
  constructor(value) {
    super();
    this.value = value;
    this.d = new $hD(this.value);
  }
  getValueOfRange(range) {
    return this.d.getOffsetRange(range).substring(this.value);
  }
  get length() {
    return this.d.textLength;
  }
};

// out-build/vs/editor/common/diff/rangeMapping.js
var $pD = class _$pD {
  static inverse(mapping2, originalLineCount, modifiedLineCount) {
    const result = [];
    let lastOriginalEndLineNumber = 1;
    let lastModifiedEndLineNumber = 1;
    for (const m of mapping2) {
      const r3 = new _$pD(new $_C(lastOriginalEndLineNumber, m.original.startLineNumber), new $_C(lastModifiedEndLineNumber, m.modified.startLineNumber));
      if (!r3.modified.isEmpty) {
        result.push(r3);
      }
      lastOriginalEndLineNumber = m.original.endLineNumberExclusive;
      lastModifiedEndLineNumber = m.modified.endLineNumberExclusive;
    }
    const r2 = new _$pD(new $_C(lastOriginalEndLineNumber, originalLineCount + 1), new $_C(lastModifiedEndLineNumber, modifiedLineCount + 1));
    if (!r2.modified.isEmpty) {
      result.push(r2);
    }
    return result;
  }
  static clip(mapping2, originalRange, modifiedRange) {
    const result = [];
    for (const m of mapping2) {
      const original = m.original.intersect(originalRange);
      const modified = m.modified.intersect(modifiedRange);
      if (original && !original.isEmpty && modified && !modified.isEmpty) {
        result.push(new _$pD(original, modified));
      }
    }
    return result;
  }
  constructor(originalRange, modifiedRange) {
    this.original = originalRange;
    this.modified = modifiedRange;
  }
  toString() {
    return `{${this.original.toString()}->${this.modified.toString()}}`;
  }
  flip() {
    return new _$pD(this.modified, this.original);
  }
  join(other) {
    return new _$pD(this.original.join(other.original), this.modified.join(other.modified));
  }
  get changedLineCount() {
    return Math.max(this.original.length, this.modified.length);
  }
  /**
   * This method assumes that the LineRangeMapping describes a valid diff!
   * I.e. if one range is empty, the other range cannot be the entire document.
   * It avoids various problems when the line range points to non-existing line-numbers.
  */
  toRangeMapping() {
    const origInclusiveRange = this.original.toInclusiveRange();
    const modInclusiveRange = this.modified.toInclusiveRange();
    if (origInclusiveRange && modInclusiveRange) {
      return new $rD(origInclusiveRange, modInclusiveRange);
    } else if (this.original.startLineNumber === 1 || this.modified.startLineNumber === 1) {
      if (!(this.modified.startLineNumber === 1 && this.original.startLineNumber === 1)) {
        throw new $vb("not a valid diff");
      }
      return new $rD(new $9C(this.original.startLineNumber, 1, this.original.endLineNumberExclusive, 1), new $9C(this.modified.startLineNumber, 1, this.modified.endLineNumberExclusive, 1));
    } else {
      return new $rD(new $9C(this.original.startLineNumber - 1, Number.MAX_SAFE_INTEGER, this.original.endLineNumberExclusive - 1, Number.MAX_SAFE_INTEGER), new $9C(this.modified.startLineNumber - 1, Number.MAX_SAFE_INTEGER, this.modified.endLineNumberExclusive - 1, Number.MAX_SAFE_INTEGER));
    }
  }
  /**
   * This method assumes that the LineRangeMapping describes a valid diff!
   * I.e. if one range is empty, the other range cannot be the entire document.
   * It avoids various problems when the line range points to non-existing line-numbers.
  */
  toRangeMapping2(original, modified) {
    if (isValidLineNumber(this.original.endLineNumberExclusive, original) && isValidLineNumber(this.modified.endLineNumberExclusive, modified)) {
      return new $rD(new $9C(this.original.startLineNumber, 1, this.original.endLineNumberExclusive, 1), new $9C(this.modified.startLineNumber, 1, this.modified.endLineNumberExclusive, 1));
    }
    if (!this.original.isEmpty && !this.modified.isEmpty) {
      return new $rD($9C.fromPositions(new $8C(this.original.startLineNumber, 1), normalizePosition(new $8C(this.original.endLineNumberExclusive - 1, Number.MAX_SAFE_INTEGER), original)), $9C.fromPositions(new $8C(this.modified.startLineNumber, 1), normalizePosition(new $8C(this.modified.endLineNumberExclusive - 1, Number.MAX_SAFE_INTEGER), modified)));
    }
    if (this.original.startLineNumber > 1 && this.modified.startLineNumber > 1) {
      return new $rD($9C.fromPositions(normalizePosition(new $8C(this.original.startLineNumber - 1, Number.MAX_SAFE_INTEGER), original), normalizePosition(new $8C(this.original.endLineNumberExclusive - 1, Number.MAX_SAFE_INTEGER), original)), $9C.fromPositions(normalizePosition(new $8C(this.modified.startLineNumber - 1, Number.MAX_SAFE_INTEGER), modified), normalizePosition(new $8C(this.modified.endLineNumberExclusive - 1, Number.MAX_SAFE_INTEGER), modified)));
    }
    throw new $vb();
  }
};
function normalizePosition(position, content) {
  if (position.lineNumber < 1) {
    return new $8C(1, 1);
  }
  if (position.lineNumber > content.length) {
    return new $8C(content.length, content[content.length - 1].length + 1);
  }
  const line = content[position.lineNumber - 1];
  if (position.column > line.length + 1) {
    return new $8C(position.lineNumber, line.length + 1);
  }
  return position;
}
function isValidLineNumber(lineNumber, lines) {
  return lineNumber >= 1 && lineNumber <= lines.length;
}
var $qD = class _$qD extends $pD {
  static fromRangeMappings(rangeMappings) {
    const originalRange = $_C.join(rangeMappings.map((r2) => $_C.fromRangeInclusive(r2.originalRange)));
    const modifiedRange = $_C.join(rangeMappings.map((r2) => $_C.fromRangeInclusive(r2.modifiedRange)));
    return new _$qD(originalRange, modifiedRange, rangeMappings);
  }
  constructor(originalRange, modifiedRange, innerChanges) {
    super(originalRange, modifiedRange);
    this.innerChanges = innerChanges;
  }
  flip() {
    return new _$qD(this.modified, this.original, this.innerChanges?.map((c) => c.flip()));
  }
  withInnerChangesFromLineRanges() {
    return new _$qD(this.original, this.modified, [this.toRangeMapping()]);
  }
};
var $rD = class _$rD {
  static fromEdit(edit3) {
    const newRanges = edit3.getNewRanges();
    const result = edit3.edits.map((e, idx) => new _$rD(e.range, newRanges[idx]));
    return result;
  }
  static fromEditJoin(edit3) {
    const newRanges = edit3.getNewRanges();
    const result = edit3.edits.map((e, idx) => new _$rD(e.range, newRanges[idx]));
    return _$rD.join(result);
  }
  static join(rangeMappings) {
    if (rangeMappings.length === 0) {
      throw new $vb("Cannot join an empty list of range mappings");
    }
    let result = rangeMappings[0];
    for (let i2 = 1; i2 < rangeMappings.length; i2++) {
      result = result.join(rangeMappings[i2]);
    }
    return result;
  }
  static assertSorted(rangeMappings) {
    for (let i2 = 1; i2 < rangeMappings.length; i2++) {
      const previous = rangeMappings[i2 - 1];
      const current = rangeMappings[i2];
      if (!(previous.originalRange.getEndPosition().isBeforeOrEqual(current.originalRange.getStartPosition()) && previous.modifiedRange.getEndPosition().isBeforeOrEqual(current.modifiedRange.getStartPosition()))) {
        throw new $vb("Range mappings must be sorted");
      }
    }
  }
  constructor(originalRange, modifiedRange) {
    this.originalRange = originalRange;
    this.modifiedRange = modifiedRange;
  }
  toString() {
    return `{${this.originalRange.toString()}->${this.modifiedRange.toString()}}`;
  }
  flip() {
    return new _$rD(this.modifiedRange, this.originalRange);
  }
  /**
   * Creates a single text edit that describes the change from the original to the modified text.
  */
  toTextEdit(modified) {
    const newText = modified.getValueOfRange(this.modifiedRange);
    return new $jD(this.originalRange, newText);
  }
  join(other) {
    return new _$rD(this.originalRange.plusRange(other.originalRange), this.modifiedRange.plusRange(other.modifiedRange));
  }
};
function $sD(alignments, originalLines, modifiedLines, dontAssertStartLine = false) {
  const changes = [];
  for (const g of $Fb(alignments.map((a) => $tD(a, originalLines, modifiedLines)), (a1, a2) => a1.original.overlapOrTouch(a2.original) || a1.modified.overlapOrTouch(a2.modified))) {
    const first = g[0];
    const last = g[g.length - 1];
    changes.push(new $qD(first.original.join(last.original), first.modified.join(last.modified), g.map((a) => a.innerChanges[0])));
  }
  $kd(() => {
    if (!dontAssertStartLine && changes.length > 0) {
      if (changes[0].modified.startLineNumber !== changes[0].original.startLineNumber) {
        return false;
      }
      if (modifiedLines.length.lineCount - changes[changes.length - 1].modified.endLineNumberExclusive !== originalLines.length.lineCount - changes[changes.length - 1].original.endLineNumberExclusive) {
        return false;
      }
    }
    return $ld(changes, (m1, m2) => m2.original.startLineNumber - m1.original.endLineNumberExclusive === m2.modified.startLineNumber - m1.modified.endLineNumberExclusive && // There has to be an unchanged line in between (otherwise both diffs should have been joined)
    m1.original.endLineNumberExclusive < m2.original.startLineNumber && m1.modified.endLineNumberExclusive < m2.modified.startLineNumber);
  });
  return changes;
}
function $tD(rangeMapping, originalLines, modifiedLines) {
  let lineStartDelta = 0;
  let lineEndDelta = 0;
  if (rangeMapping.modifiedRange.endColumn === 1 && rangeMapping.originalRange.endColumn === 1 && rangeMapping.originalRange.startLineNumber + lineStartDelta <= rangeMapping.originalRange.endLineNumber && rangeMapping.modifiedRange.startLineNumber + lineStartDelta <= rangeMapping.modifiedRange.endLineNumber) {
    lineEndDelta = -1;
  }
  if (rangeMapping.modifiedRange.startColumn - 1 >= modifiedLines.getLineLength(rangeMapping.modifiedRange.startLineNumber) && rangeMapping.originalRange.startColumn - 1 >= originalLines.getLineLength(rangeMapping.originalRange.startLineNumber) && rangeMapping.originalRange.startLineNumber <= rangeMapping.originalRange.endLineNumber + lineEndDelta && rangeMapping.modifiedRange.startLineNumber <= rangeMapping.modifiedRange.endLineNumber + lineEndDelta) {
    lineStartDelta = 1;
  }
  const originalLineRange = new $_C(rangeMapping.originalRange.startLineNumber + lineStartDelta, rangeMapping.originalRange.endLineNumber + 1 + lineEndDelta);
  const modifiedLineRange = new $_C(rangeMapping.modifiedRange.startLineNumber + lineStartDelta, rangeMapping.modifiedRange.endLineNumber + 1 + lineEndDelta);
  return new $qD(originalLineRange, modifiedLineRange, [rangeMapping]);
}
function $uD(changes) {
  const lineRangeMapping = [];
  for (const change of changes) {
    let originalRange;
    if (change.originalEndLineNumber === 0) {
      originalRange = new $_C(change.originalStartLineNumber + 1, change.originalStartLineNumber + 1);
    } else {
      originalRange = new $_C(change.originalStartLineNumber, change.originalEndLineNumber + 1);
    }
    let modifiedRange;
    if (change.modifiedEndLineNumber === 0) {
      modifiedRange = new $_C(change.modifiedStartLineNumber + 1, change.modifiedStartLineNumber + 1);
    } else {
      modifiedRange = new $_C(change.modifiedStartLineNumber, change.modifiedEndLineNumber + 1);
    }
    lineRangeMapping.push(new $pD(originalRange, modifiedRange));
  }
  return lineRangeMapping;
}

// out-build/vs/platform/theme/common/iconRegistry.js
var $8r = {
  IconContribution: "base.contributions.icons"
};
var IconContribution;
(function(IconContribution2) {
  function getDefinition(contribution, registry4) {
    let definition = contribution.defaults;
    while (ThemeIcon.isThemeIcon(definition)) {
      const c = iconRegistry.getIcon(definition.id);
      if (!c) {
        return void 0;
      }
      definition = c.defaults;
    }
    return definition;
  }
  IconContribution2.getDefinition = getDefinition;
})(IconContribution || (IconContribution = {}));
var IconFontDefinition;
(function(IconFontDefinition2) {
  function toJSONObject(iconFont) {
    return {
      weight: iconFont.weight,
      style: iconFont.style,
      src: iconFont.src.map((s) => ({ format: s.format, location: s.location.toString() }))
    };
  }
  IconFontDefinition2.toJSONObject = toJSONObject;
  function fromJSONObject(json) {
    const stringOrUndef = (s) => $zg(s) ? s : void 0;
    if (json && Array.isArray(json.src) && json.src.every((s) => $zg(s.format) && $zg(s.location))) {
      return {
        weight: stringOrUndef(json.weight),
        style: stringOrUndef(json.style),
        src: json.src.map((s) => ({ format: s.format, location: URI.parse(s.location) }))
      };
    }
    return void 0;
  }
  IconFontDefinition2.fromJSONObject = fromJSONObject;
})(IconFontDefinition || (IconFontDefinition = {}));
var IconRegistry = class {
  constructor() {
    this.a = new $ze();
    this.onDidChange = this.a.event;
    this.d = {
      definitions: {
        icons: {
          type: "object",
          properties: {
            fontId: { type: "string", description: localize(2411, null) },
            fontCharacter: { type: "string", description: localize(2412, null) }
          },
          additionalProperties: false,
          defaultSnippets: [{ body: { fontCharacter: "\\\\e030" } }]
        }
      },
      type: "object",
      properties: {}
    };
    this.e = { type: "string", pattern: `^${ThemeIcon.iconNameExpression}$`, enum: [], enumDescriptions: [] };
    this.b = {};
    this.f = {};
  }
  registerIcon(id2, defaults, description, deprecationMessage) {
    const existing = this.b[id2];
    if (existing) {
      if (description && !existing.description) {
        existing.description = description;
        this.d.properties[id2].markdownDescription = `${description} $(${id2})`;
        const enumIndex = this.e.enum.indexOf(id2);
        if (enumIndex !== -1) {
          this.e.enumDescriptions[enumIndex] = description;
        }
        this.a.fire();
      }
      return existing;
    }
    const iconContribution = { id: id2, description, defaults, deprecationMessage };
    this.b[id2] = iconContribution;
    const propertySchema = { $ref: "#/definitions/icons" };
    if (deprecationMessage) {
      propertySchema.deprecationMessage = deprecationMessage;
    }
    if (description) {
      propertySchema.markdownDescription = `${description}: $(${id2})`;
    }
    this.d.properties[id2] = propertySchema;
    this.e.enum.push(id2);
    this.e.enumDescriptions.push(description || "");
    this.a.fire();
    return { id: id2 };
  }
  deregisterIcon(id2) {
    delete this.b[id2];
    delete this.d.properties[id2];
    const index = this.e.enum.indexOf(id2);
    if (index !== -1) {
      this.e.enum.splice(index, 1);
      this.e.enumDescriptions.splice(index, 1);
    }
    this.a.fire();
  }
  getIcons() {
    return Object.keys(this.b).map((id2) => this.b[id2]);
  }
  getIcon(id2) {
    return this.b[id2];
  }
  getIconSchema() {
    return this.d;
  }
  getIconReferenceSchema() {
    return this.e;
  }
  registerIconFont(id2, definition) {
    const existing = this.f[id2];
    if (existing) {
      return existing;
    }
    this.f[id2] = definition;
    this.a.fire();
    return definition;
  }
  deregisterIconFont(id2) {
    delete this.f[id2];
  }
  getIconFont(id2) {
    return this.f[id2];
  }
  toString() {
    const sorter3 = (i1, i2) => {
      return i1.id.localeCompare(i2.id);
    };
    const classNames = (i2) => {
      while (ThemeIcon.isThemeIcon(i2.defaults)) {
        i2 = this.b[i2.defaults.id];
      }
      return `codicon codicon-${i2 ? i2.id : ""}`;
    };
    const reference = [];
    reference.push(`| preview     | identifier                        | default codicon ID                | description`);
    reference.push(`| ----------- | --------------------------------- | --------------------------------- | --------------------------------- |`);
    const contributions = Object.keys(this.b).map((key2) => this.b[key2]);
    for (const i2 of contributions.filter((i3) => !!i3.description).sort(sorter3)) {
      reference.push(`|<i class="${classNames(i2)}"></i>|${i2.id}|${ThemeIcon.isThemeIcon(i2.defaults) ? i2.defaults.id : i2.id}|${i2.description || ""}|`);
    }
    reference.push(`| preview     | identifier                        `);
    reference.push(`| ----------- | --------------------------------- |`);
    for (const i2 of contributions.filter((i3) => !ThemeIcon.isThemeIcon(i3.defaults)).sort(sorter3)) {
      reference.push(`|<i class="${classNames(i2)}"></i>|${i2.id}|`);
    }
    return reference.join("\n");
  }
};
var iconRegistry = new IconRegistry();
$Wn.add($8r.IconContribution, iconRegistry);
function $9r(id2, defaults, description, deprecationMessage) {
  return iconRegistry.registerIcon(id2, defaults, description, deprecationMessage);
}
function $0r() {
  return iconRegistry;
}
function initialize() {
  const codiconFontCharacters = $2l();
  for (const icon2 in codiconFontCharacters) {
    const fontCharacter = "\\" + codiconFontCharacters[icon2].toString(16);
    iconRegistry.registerIcon(icon2, { fontCharacter });
  }
}
initialize();
var $$r = "vscode://schemas/icons";
var schemaRegistry2 = $Wn.as($Xn.JSONContribution);
schemaRegistry2.registerSchema($$r, iconRegistry.getIconSchema());
var delayer2 = new $8h(() => schemaRegistry2.notifySchemaChanged($$r), 200);
iconRegistry.onDidChange(() => {
  if (!delayer2.isScheduled()) {
    delayer2.schedule();
  }
});
var $_r = $9r("widget-close", $6l.close, localize(2413, null));
var $as = $9r("goto-previous-location", $6l.arrowUp, localize(2414, null));
var $bs = $9r("goto-next-location", $6l.arrowDown, localize(2415, null));
var $cs = ThemeIcon.modify($6l.sync, "spin");
var $ds = ThemeIcon.modify($6l.loading, "spin");

// out-build/vs/editor/browser/widget/diffEditor/components/accessibleDiffViewer.js
var accessibleDiffViewerInsertIcon = $9r("diff-review-insert", $6l.add, localize(208, null));
var accessibleDiffViewerRemoveIcon = $9r("diff-review-remove", $6l.remove, localize(209, null));
var accessibleDiffViewerCloseIcon = $9r("diff-review-close", $6l.close, localize(210, null));
var $h$ = class $h$2 extends $3c {
  static {
    this._ttPolicy = $W1("diffReview", { createHTML: (value) => value });
  }
  constructor(c, f, j, m, n, s, t, u, w) {
    super();
    this.c = c;
    this.f = f;
    this.j = j;
    this.m = m;
    this.n = n;
    this.s = s;
    this.t = t;
    this.u = u;
    this.w = w;
    this.y = $6d(this, (reader, store) => {
      const visible = this.f.read(reader);
      this.c.style.visibility = visible ? "visible" : "hidden";
      if (!visible) {
        return null;
      }
      const model = store.add(this.w.createInstance(ViewModel, this.t, this.u, this.j, this.m));
      const view = store.add(this.w.createInstance(View, this.c, model, this.n, this.s, this.u));
      return { model, view };
    }).recomputeInitiallyAndOnChange(this.q);
  }
  next() {
    $ce((tx) => {
      const isVisible = this.f.get();
      this.j(true, tx);
      if (isVisible) {
        this.y.get().model.nextGroup(tx);
      }
    });
  }
  prev() {
    $ce((tx) => {
      this.j(true, tx);
      this.y.get().model.previousGroup(tx);
    });
  }
  close() {
    $ce((tx) => {
      this.j(false, tx);
    });
  }
};
$h$ = __decorate([
  __param(8, $Pk)
], $h$);
var ViewModel = class ViewModel2 extends $3c {
  constructor(j, m, n, canClose, s) {
    super();
    this.j = j;
    this.m = m;
    this.n = n;
    this.canClose = canClose;
    this.s = s;
    this.c = $he(this, []);
    this.f = $he(this, 0);
    this.h = $he(this, 0);
    this.groups = this.c;
    this.currentGroup = this.f.map((idx, r2) => this.c.read(r2)[idx]);
    this.currentGroupIndex = this.f;
    this.currentElement = this.h.map((idx, r2) => this.currentGroup.read(r2)?.lines[idx]);
    this.B($td((reader) => {
      const diffs = this.j.read(reader);
      if (!diffs) {
        this.c.set([], void 0);
        return;
      }
      const groups = computeViewElementGroups(diffs, this.m.getOriginalModel().getLineCount(), this.m.getModifiedModel().getLineCount());
      $ce((tx) => {
        const p = this.m.getModifiedPosition();
        if (p) {
          const nextGroup = groups.findIndex((g) => p?.lineNumber < g.range.modified.endLineNumberExclusive);
          if (nextGroup !== -1) {
            this.f.set(nextGroup, tx);
          }
        }
        this.c.set(groups, tx);
      });
    }));
    this.B($td((reader) => {
      const currentViewItem = this.currentElement.read(reader);
      if (currentViewItem?.type === LineType.Deleted) {
        this.s.playSignal($N9.diffLineDeleted, { source: "accessibleDiffViewer.currentElementChanged" });
      } else if (currentViewItem?.type === LineType.Added) {
        this.s.playSignal($N9.diffLineInserted, { source: "accessibleDiffViewer.currentElementChanged" });
      }
    }));
    this.B($td((reader) => {
      const currentViewItem = this.currentElement.read(reader);
      if (currentViewItem && currentViewItem.type !== LineType.Header) {
        const lineNumber = currentViewItem.modifiedLineNumber ?? currentViewItem.diff.modified.startLineNumber;
        this.m.modifiedSetSelection($9C.fromPositions(new $8C(lineNumber, 1)));
      }
    }));
  }
  t(delta, tx) {
    const groups = this.groups.get();
    if (!groups || groups.length <= 1) {
      return;
    }
    $fe(tx, (tx2) => {
      this.f.set($0C.ofLength(groups.length).clipCyclic(this.f.get() + delta), tx2);
      this.h.set(0, tx2);
    });
  }
  nextGroup(tx) {
    this.t(1, tx);
  }
  previousGroup(tx) {
    this.t(-1, tx);
  }
  u(delta) {
    const group2 = this.currentGroup.get();
    if (!group2 || group2.lines.length <= 1) {
      return;
    }
    $ce((tx) => {
      this.h.set($0C.ofLength(group2.lines.length).clip(this.h.get() + delta), tx);
    });
  }
  goToNextLine() {
    this.u(1);
  }
  goToPreviousLine() {
    this.u(-1);
  }
  goToLine(line) {
    const group2 = this.currentGroup.get();
    if (!group2) {
      return;
    }
    const idx = group2.lines.indexOf(line);
    if (idx === -1) {
      return;
    }
    $ce((tx) => {
      this.h.set(idx, tx);
    });
  }
  revealCurrentElementInEditor() {
    if (!this.canClose.get()) {
      return;
    }
    this.n(false, void 0);
    const curElem = this.currentElement.get();
    if (curElem) {
      if (curElem.type === LineType.Deleted) {
        this.m.originalReveal($9C.fromPositions(new $8C(curElem.originalLineNumber, 1)));
      } else {
        this.m.modifiedReveal(curElem.type !== LineType.Header ? $9C.fromPositions(new $8C(curElem.modifiedLineNumber, 1)) : void 0);
      }
    }
  }
  close() {
    if (!this.canClose.get()) {
      return;
    }
    this.n(false, void 0);
    this.m.modifiedFocus();
  }
};
ViewModel = __decorate([
  __param(4, $I9)
], ViewModel);
var viewElementGroupLineMargin = 3;
function computeViewElementGroups(diffs, originalLineCount, modifiedLineCount) {
  const result = [];
  for (const g of $Fb(diffs, (a, b) => b.modified.startLineNumber - a.modified.endLineNumberExclusive < 2 * viewElementGroupLineMargin)) {
    const viewElements = [];
    viewElements.push(new HeaderViewElement());
    const origFullRange = new $_C(Math.max(1, g[0].original.startLineNumber - viewElementGroupLineMargin), Math.min(g[g.length - 1].original.endLineNumberExclusive + viewElementGroupLineMargin, originalLineCount + 1));
    const modifiedFullRange = new $_C(Math.max(1, g[0].modified.startLineNumber - viewElementGroupLineMargin), Math.min(g[g.length - 1].modified.endLineNumberExclusive + viewElementGroupLineMargin, modifiedLineCount + 1));
    $Gb(g, (a, b) => {
      const origRange = new $_C(a ? a.original.endLineNumberExclusive : origFullRange.startLineNumber, b ? b.original.startLineNumber : origFullRange.endLineNumberExclusive);
      const modifiedRange2 = new $_C(a ? a.modified.endLineNumberExclusive : modifiedFullRange.startLineNumber, b ? b.modified.startLineNumber : modifiedFullRange.endLineNumberExclusive);
      origRange.forEach((origLineNumber) => {
        viewElements.push(new UnchangedLineViewElement(origLineNumber, modifiedRange2.startLineNumber + (origLineNumber - origRange.startLineNumber)));
      });
      if (b) {
        b.original.forEach((origLineNumber) => {
          viewElements.push(new DeletedLineViewElement(b, origLineNumber));
        });
        b.modified.forEach((modifiedLineNumber) => {
          viewElements.push(new AddedLineViewElement(b, modifiedLineNumber));
        });
      }
    });
    const modifiedRange = g[0].modified.join(g[g.length - 1].modified);
    const originalRange = g[0].original.join(g[g.length - 1].original);
    result.push(new ViewElementGroup(new $pD(modifiedRange, originalRange), viewElements));
  }
  return result;
}
var LineType;
(function(LineType2) {
  LineType2[LineType2["Header"] = 0] = "Header";
  LineType2[LineType2["Unchanged"] = 1] = "Unchanged";
  LineType2[LineType2["Deleted"] = 2] = "Deleted";
  LineType2[LineType2["Added"] = 3] = "Added";
})(LineType || (LineType = {}));
var ViewElementGroup = class {
  constructor(range, lines) {
    this.range = range;
    this.lines = lines;
  }
};
var HeaderViewElement = class {
  constructor() {
    this.type = LineType.Header;
  }
};
var DeletedLineViewElement = class {
  constructor(diff3, originalLineNumber) {
    this.diff = diff3;
    this.originalLineNumber = originalLineNumber;
    this.type = LineType.Deleted;
    this.modifiedLineNumber = void 0;
  }
};
var AddedLineViewElement = class {
  constructor(diff3, modifiedLineNumber) {
    this.diff = diff3;
    this.modifiedLineNumber = modifiedLineNumber;
    this.type = LineType.Added;
    this.originalLineNumber = void 0;
  }
};
var UnchangedLineViewElement = class {
  constructor(originalLineNumber, modifiedLineNumber) {
    this.originalLineNumber = originalLineNumber;
    this.modifiedLineNumber = modifiedLineNumber;
    this.type = LineType.Unchanged;
  }
};
var View = class View2 extends $3c {
  constructor(j, m, n, s, t, u) {
    super();
    this.j = j;
    this.m = m;
    this.n = n;
    this.s = s;
    this.t = t;
    this.u = u;
    this.domNode = this.j;
    this.domNode.className = "monaco-component diff-review monaco-editor-background";
    const actionBarContainer = document.createElement("div");
    actionBarContainer.className = "diff-review-actions";
    this.h = this.B(new $LZ(actionBarContainer));
    this.B($td((reader) => {
      this.h.clear();
      if (this.m.canClose.read(reader)) {
        this.h.push(new $Um("diffreview.close", localize(211, null), "close-diff-review " + ThemeIcon.asClassName(accessibleDiffViewerCloseIcon), true, async () => m.close()), { label: false, icon: true });
      }
    }));
    this.c = document.createElement("div");
    this.c.className = "diff-review-content";
    this.c.setAttribute("role", "code");
    this.f = this.B(new $CZ(this.c, {}));
    $dk(this.domNode, this.f.getDomNode(), actionBarContainer);
    this.B($td((r2) => {
      this.s.read(r2);
      this.n.read(r2);
      this.f.scanDomNode();
    }));
    this.B($1c(() => {
      $dk(this.domNode);
    }));
    this.B($19(this.domNode, { width: this.n, height: this.s }));
    this.B($19(this.c, { width: this.n, height: this.s }));
    this.B($xd((reader, store) => {
      this.m.currentGroup.read(reader);
      this.w(store);
    }));
    this.B($aj(this.domNode, "keydown", (e) => {
      if (e.equals(
        18
        /* KeyCode.DownArrow */
      ) || e.equals(
        2048 | 18
        /* KeyCode.DownArrow */
      ) || e.equals(
        512 | 18
        /* KeyCode.DownArrow */
      )) {
        e.preventDefault();
        this.m.goToNextLine();
      }
      if (e.equals(
        16
        /* KeyCode.UpArrow */
      ) || e.equals(
        2048 | 16
        /* KeyCode.UpArrow */
      ) || e.equals(
        512 | 16
        /* KeyCode.UpArrow */
      )) {
        e.preventDefault();
        this.m.goToPreviousLine();
      }
      if (e.equals(
        9
        /* KeyCode.Escape */
      ) || e.equals(
        2048 | 9
        /* KeyCode.Escape */
      ) || e.equals(
        512 | 9
        /* KeyCode.Escape */
      ) || e.equals(
        1024 | 9
        /* KeyCode.Escape */
      )) {
        e.preventDefault();
        this.m.close();
      }
      if (e.equals(
        10
        /* KeyCode.Space */
      ) || e.equals(
        3
        /* KeyCode.Enter */
      )) {
        e.preventDefault();
        this.m.revealCurrentElementInEditor();
      }
    }));
  }
  w(store) {
    const originalOptions = this.t.getOriginalOptions();
    const modifiedOptions = this.t.getModifiedOptions();
    const container2 = document.createElement("div");
    container2.className = "diff-review-table";
    container2.setAttribute("role", "list");
    container2.setAttribute("aria-label", localize(212, null));
    $24(container2, modifiedOptions.get(
      52
      /* EditorOption.fontInfo */
    ));
    $dk(this.c, container2);
    const originalModel = this.t.getOriginalModel();
    const modifiedModel = this.t.getModifiedModel();
    if (!originalModel || !modifiedModel) {
      return;
    }
    const originalModelOpts = originalModel.getOptions();
    const modifiedModelOpts = modifiedModel.getOptions();
    const lineHeight = modifiedOptions.get(
      68
      /* EditorOption.lineHeight */
    );
    const group2 = this.m.currentGroup.get();
    for (const viewItem of group2?.lines || []) {
      if (!group2) {
        break;
      }
      let row;
      if (viewItem.type === LineType.Header) {
        const header = document.createElement("div");
        header.className = "diff-review-row";
        header.setAttribute("role", "listitem");
        const r2 = group2.range;
        const diffIndex = this.m.currentGroupIndex.get();
        const diffsLength = this.m.groups.get().length;
        const getAriaLines = (lines) => lines === 0 ? localize(213, null) : lines === 1 ? localize(214, null) : localize(215, null, lines);
        const originalChangedLinesCntAria = getAriaLines(r2.original.length);
        const modifiedChangedLinesCntAria = getAriaLines(r2.modified.length);
        header.setAttribute("aria-label", localize(216, null, diffIndex + 1, diffsLength, r2.original.startLineNumber, originalChangedLinesCntAria, r2.modified.startLineNumber, modifiedChangedLinesCntAria));
        const cell = document.createElement("div");
        cell.className = "diff-review-cell diff-review-summary";
        cell.appendChild(document.createTextNode(`${diffIndex + 1}/${diffsLength}: @@ -${r2.original.startLineNumber},${r2.original.length} +${r2.modified.startLineNumber},${r2.modified.length} @@`));
        header.appendChild(cell);
        row = header;
      } else {
        row = this.y(viewItem, lineHeight, this.n.get(), originalOptions, originalModel, originalModelOpts, modifiedOptions, modifiedModel, modifiedModelOpts);
      }
      container2.appendChild(row);
      const isSelectedObs = $2d((reader) => (
        /** @description isSelected */
        this.m.currentElement.read(reader) === viewItem
      ));
      store.add($td((reader) => {
        const isSelected = isSelectedObs.read(reader);
        row.tabIndex = isSelected ? 0 : -1;
        if (isSelected) {
          row.focus();
        }
      }));
      store.add($_i(row, "focus", () => {
        this.m.goToLine(viewItem);
      }));
    }
    this.f.scanDomNode();
  }
  y(item, lineHeight, width2, originalOptions, originalModel, originalModelOpts, modifiedOptions, modifiedModel, modifiedModelOpts) {
    const originalLayoutInfo = originalOptions.get(
      151
      /* EditorOption.layoutInfo */
    );
    const originalLineNumbersWidth = originalLayoutInfo.glyphMarginWidth + originalLayoutInfo.lineNumbersWidth;
    const modifiedLayoutInfo = modifiedOptions.get(
      151
      /* EditorOption.layoutInfo */
    );
    const modifiedLineNumbersWidth = 10 + modifiedLayoutInfo.glyphMarginWidth + modifiedLayoutInfo.lineNumbersWidth;
    let rowClassName = "diff-review-row";
    let lineNumbersExtraClassName = "";
    const spacerClassName = "diff-review-spacer";
    let spacerIcon = null;
    switch (item.type) {
      case LineType.Added:
        rowClassName = "diff-review-row line-insert";
        lineNumbersExtraClassName = " char-insert";
        spacerIcon = accessibleDiffViewerInsertIcon;
        break;
      case LineType.Deleted:
        rowClassName = "diff-review-row line-delete";
        lineNumbersExtraClassName = " char-delete";
        spacerIcon = accessibleDiffViewerRemoveIcon;
        break;
    }
    const row = document.createElement("div");
    row.style.minWidth = width2 + "px";
    row.className = rowClassName;
    row.setAttribute("role", "listitem");
    row.ariaLevel = "";
    const cell = document.createElement("div");
    cell.className = "diff-review-cell";
    cell.style.height = `${lineHeight}px`;
    row.appendChild(cell);
    const originalLineNumber = document.createElement("span");
    originalLineNumber.style.width = originalLineNumbersWidth + "px";
    originalLineNumber.style.minWidth = originalLineNumbersWidth + "px";
    originalLineNumber.className = "diff-review-line-number" + lineNumbersExtraClassName;
    if (item.originalLineNumber !== void 0) {
      originalLineNumber.appendChild(document.createTextNode(String(item.originalLineNumber)));
    } else {
      originalLineNumber.innerText = "\xA0";
    }
    cell.appendChild(originalLineNumber);
    const modifiedLineNumber = document.createElement("span");
    modifiedLineNumber.style.width = modifiedLineNumbersWidth + "px";
    modifiedLineNumber.style.minWidth = modifiedLineNumbersWidth + "px";
    modifiedLineNumber.style.paddingRight = "10px";
    modifiedLineNumber.className = "diff-review-line-number" + lineNumbersExtraClassName;
    if (item.modifiedLineNumber !== void 0) {
      modifiedLineNumber.appendChild(document.createTextNode(String(item.modifiedLineNumber)));
    } else {
      modifiedLineNumber.innerText = "\xA0";
    }
    cell.appendChild(modifiedLineNumber);
    const spacer = document.createElement("span");
    spacer.className = spacerClassName;
    if (spacerIcon) {
      const spacerCodicon = document.createElement("span");
      spacerCodicon.className = ThemeIcon.asClassName(spacerIcon);
      spacerCodicon.innerText = "\xA0\xA0";
      spacer.appendChild(spacerCodicon);
    } else {
      spacer.innerText = "\xA0\xA0";
    }
    cell.appendChild(spacer);
    let lineContent;
    if (item.modifiedLineNumber !== void 0) {
      let html3 = this.z(modifiedModel, modifiedOptions, modifiedModelOpts.tabSize, item.modifiedLineNumber, this.u.languageIdCodec);
      if ($h$._ttPolicy) {
        html3 = $h$._ttPolicy.createHTML(html3);
      }
      cell.insertAdjacentHTML("beforeend", html3);
      lineContent = modifiedModel.getLineContent(item.modifiedLineNumber);
    } else {
      let html3 = this.z(originalModel, originalOptions, originalModelOpts.tabSize, item.originalLineNumber, this.u.languageIdCodec);
      if ($h$._ttPolicy) {
        html3 = $h$._ttPolicy.createHTML(html3);
      }
      cell.insertAdjacentHTML("beforeend", html3);
      lineContent = originalModel.getLineContent(item.originalLineNumber);
    }
    if (lineContent.length === 0) {
      lineContent = localize(217, null);
    }
    let ariaLabel = "";
    switch (item.type) {
      case LineType.Unchanged:
        if (item.originalLineNumber === item.modifiedLineNumber) {
          ariaLabel = localize(218, null, lineContent, item.originalLineNumber);
        } else {
          ariaLabel = localize(219, null, lineContent, item.originalLineNumber, item.modifiedLineNumber);
        }
        break;
      case LineType.Added:
        ariaLabel = localize(220, null, lineContent, item.modifiedLineNumber);
        break;
      case LineType.Deleted:
        ariaLabel = localize(221, null, lineContent, item.originalLineNumber);
        break;
    }
    row.setAttribute("aria-label", ariaLabel);
    return row;
  }
  z(model, options3, tabSize, lineNumber, languageIdCodec) {
    const lineContent = model.getLineContent(lineNumber);
    const fontInfo = options3.get(
      52
      /* EditorOption.fontInfo */
    );
    const lineTokens = $xE.createEmpty(lineContent, languageIdCodec);
    const isBasicASCII = $H5.isBasicASCII(lineContent, model.mightContainNonBasicASCII());
    const containsRTL = $H5.containsRTL(lineContent, isBasicASCII, model.mightContainRTL());
    const r2 = $w7(new $q7(fontInfo.isMonospace && !options3.get(
      33
      /* EditorOption.disableMonospaceOptimizations */
    ), fontInfo.canUseHalfwidthRightwardsArrow, lineContent, false, isBasicASCII, containsRTL, 0, lineTokens, [], tabSize, 0, fontInfo.spaceWidth, fontInfo.middotWidth, fontInfo.wsmiddotWidth, options3.get(
      122
      /* EditorOption.stopRenderingLineAfter */
    ), options3.get(
      104
      /* EditorOption.renderWhitespace */
    ), options3.get(
      99
      /* EditorOption.renderControlCharacters */
    ), options3.get(
      53
      /* EditorOption.fontLigatures */
    ) !== EditorFontLigatures.OFF, null));
    return r2.html;
  }
};
View = __decorate([
  __param(5, $1E)
], View);
var $i$ = class {
  constructor(c) {
    this.c = c;
  }
  getOriginalModel() {
    return this.c.original.getModel();
  }
  getOriginalOptions() {
    return this.c.original.getOptions();
  }
  originalReveal(range) {
    this.c.original.revealRange(range);
    this.c.original.setSelection(range);
    this.c.original.focus();
  }
  getModifiedModel() {
    return this.c.modified.getModel();
  }
  getModifiedOptions() {
    return this.c.modified.getOptions();
  }
  modifiedReveal(range) {
    if (range) {
      this.c.modified.revealRange(range);
      this.c.modified.setSelection(range);
    }
    this.c.modified.focus();
  }
  modifiedSetSelection(range) {
    this.c.modified.setSelection(range);
  }
  modifiedFocus() {
    this.c.modified.focus();
  }
  getModifiedPosition() {
    return this.c.modified.getPosition() ?? void 0;
  }
};

// out-build/vs/editor/browser/widget/diffEditor/registrations.contribution.js
var $N0 = $5n("diffEditor.move.border", "#8b8b8b9c", localize(248, null));
var $O0 = $5n("diffEditor.moveActive.border", "#FFA500", localize(249, null));
var $P0 = $5n("diffEditor.unchangedRegionShadow", { dark: "#000000", light: "#737373BF", hcDark: "#000000", hcLight: "#737373BF" }, localize(250, null));
var $Q0 = $9r("diff-insert", $6l.add, localize(251, null));
var $R0 = $9r("diff-remove", $6l.remove, localize(252, null));
var $S0 = $WI.register({
  className: "line-insert",
  description: "line-insert",
  isWholeLine: true,
  linesDecorationsClassName: "insert-sign " + ThemeIcon.asClassName($Q0),
  marginClassName: "gutter-insert"
});
var $T0 = $WI.register({
  className: "line-delete",
  description: "line-delete",
  isWholeLine: true,
  linesDecorationsClassName: "delete-sign " + ThemeIcon.asClassName($R0),
  marginClassName: "gutter-delete"
});
var $U0 = $WI.register({
  className: "line-insert",
  description: "line-insert",
  isWholeLine: true,
  marginClassName: "gutter-insert"
});
var $V0 = $WI.register({
  className: "line-delete",
  description: "line-delete",
  isWholeLine: true,
  marginClassName: "gutter-delete"
});
var $W0 = $WI.register({
  className: "char-insert",
  description: "char-insert",
  shouldFillLineOnLineBreak: true
});
var $X0 = $WI.register({
  className: "char-insert",
  description: "char-insert",
  isWholeLine: true
});
var $Y0 = $WI.register({
  className: "char-insert diff-range-empty",
  description: "char-insert diff-range-empty"
});
var $Z0 = $WI.register({
  className: "char-delete",
  description: "char-delete",
  shouldFillLineOnLineBreak: true
});
var $10 = $WI.register({
  className: "char-delete",
  description: "char-delete",
  isWholeLine: true
});
var $20 = $WI.register({
  className: "char-delete diff-range-empty",
  description: "char-delete diff-range-empty"
});

// out-build/vs/editor/common/services/editorWorker.js
var $I0 = $Qk("editorWorkerService");

// out-build/vs/editor/browser/widget/diffEditor/diffProviderFactoryService.js
var $L0_1;
var $J0 = $Qk("diffProviderFactoryService");
var $K0 = class $K02 {
  constructor(a) {
    this.a = a;
  }
  createDiffProvider(options3) {
    return this.a.createInstance($L0, options3);
  }
};
$K0 = __decorate([
  __param(0, $Pk)
], $K0);
$SC(
  $J0,
  $K0,
  1
  /* InstantiationType.Delayed */
);
var $L0 = class $L02 {
  static {
    $L0_1 = this;
  }
  static {
    this.e = /* @__PURE__ */ new Map();
  }
  constructor(options3, f, g) {
    this.f = f;
    this.g = g;
    this.a = new $ze();
    this.onDidChange = this.a.event;
    this.b = "advanced";
    this.d = void 0;
    this.setOptions(options3);
  }
  dispose() {
    this.d?.dispose();
  }
  async computeDiff(original, modified, options3, cancellationToken) {
    if (typeof this.b !== "string") {
      return this.b.computeDiff(original, modified, options3, cancellationToken);
    }
    if (original.isDisposed() || modified.isDisposed()) {
      return {
        changes: [],
        identical: true,
        quitEarly: false,
        moves: []
      };
    }
    if (original.getLineCount() === 1 && original.getLineMaxColumn(1) === 1) {
      if (modified.getLineCount() === 1 && modified.getLineMaxColumn(1) === 1) {
        return {
          changes: [],
          identical: true,
          quitEarly: false,
          moves: []
        };
      }
      return {
        changes: [
          new $qD(new $_C(1, 2), new $_C(1, modified.getLineCount() + 1), [
            new $rD(original.getFullModelRange(), modified.getFullModelRange())
          ])
        ],
        identical: false,
        quitEarly: false,
        moves: []
      };
    }
    const uriKey = JSON.stringify([original.uri.toString(), modified.uri.toString()]);
    const context = JSON.stringify([original.id, modified.id, original.getAlternativeVersionId(), modified.getAlternativeVersionId(), JSON.stringify(options3)]);
    const c = $L0_1.e.get(uriKey);
    if (c && c.context === context) {
      return c.result;
    }
    const sw = $te.create();
    const result = await this.f.computeDiff(original.uri, modified.uri, options3, this.b);
    const timeMs = sw.elapsed();
    this.g.publicLog2("diffEditor.computeDiff", {
      timeMs,
      timedOut: result?.quitEarly ?? true,
      detectedMoves: options3.computeMoves ? result?.moves.length ?? 0 : -1
    });
    if (cancellationToken.isCancellationRequested) {
      return {
        changes: [],
        identical: false,
        quitEarly: true,
        moves: []
      };
    }
    if (!result) {
      throw new Error("no diff result available");
    }
    if ($L0_1.e.size > 10) {
      $L0_1.e.delete($L0_1.e.keys().next().value);
    }
    $L0_1.e.set(uriKey, { result, context });
    return result;
  }
  setOptions(newOptions) {
    let didChange = false;
    if (newOptions.diffAlgorithm) {
      if (this.b !== newOptions.diffAlgorithm) {
        this.d?.dispose();
        this.d = void 0;
        this.b = newOptions.diffAlgorithm;
        if (typeof newOptions.diffAlgorithm !== "string") {
          this.d = newOptions.diffAlgorithm.onDidChange(() => this.a.fire());
        }
        didChange = true;
      }
    }
    if (didChange) {
      this.a.fire();
    }
  }
};
$L0 = $L0_1 = __decorate([
  __param(1, $I0),
  __param(2, $zv)
], $L0);

// out-build/vs/editor/common/diff/linesDiffComputer.js
var $vD = class {
  constructor(changes, moves, hitTimeout) {
    this.changes = changes;
    this.moves = moves;
    this.hitTimeout = hitTimeout;
  }
};
var $wD = class _$wD {
  constructor(lineRangeMapping, changes) {
    this.lineRangeMapping = lineRangeMapping;
    this.changes = changes;
  }
  flip() {
    return new _$wD(this.lineRangeMapping.flip(), this.changes.map((c) => c.flip()));
  }
};

// out-build/vs/editor/common/diff/defaultLinesDiffComputer/algorithms/diffAlgorithm.js
var $e0 = class _$e0 {
  static trivial(seq1, seq2) {
    return new _$e0([new $f0($0C.ofLength(seq1.length), $0C.ofLength(seq2.length))], false);
  }
  static trivialTimedOut(seq1, seq2) {
    return new _$e0([new $f0($0C.ofLength(seq1.length), $0C.ofLength(seq2.length))], true);
  }
  constructor(diffs, hitTimeout) {
    this.diffs = diffs;
    this.hitTimeout = hitTimeout;
  }
};
var $f0 = class _$f0 {
  static invert(sequenceDiffs, doc1Length) {
    const result = [];
    $Gb(sequenceDiffs, (a, b) => {
      result.push(_$f0.fromOffsetPairs(a ? a.getEndExclusives() : $g0.zero, b ? b.getStarts() : new $g0(doc1Length, (a ? a.seq2Range.endExclusive - a.seq1Range.endExclusive : 0) + doc1Length)));
    });
    return result;
  }
  static fromOffsetPairs(start, endExclusive) {
    return new _$f0(new $0C(start.offset1, endExclusive.offset1), new $0C(start.offset2, endExclusive.offset2));
  }
  static assertSorted(sequenceDiffs) {
    let last = void 0;
    for (const cur of sequenceDiffs) {
      if (last) {
        if (!(last.seq1Range.endExclusive <= cur.seq1Range.start && last.seq2Range.endExclusive <= cur.seq2Range.start)) {
          throw new $vb("Sequence diffs must be sorted");
        }
      }
      last = cur;
    }
  }
  constructor(seq1Range, seq2Range) {
    this.seq1Range = seq1Range;
    this.seq2Range = seq2Range;
  }
  swap() {
    return new _$f0(this.seq2Range, this.seq1Range);
  }
  toString() {
    return `${this.seq1Range} <-> ${this.seq2Range}`;
  }
  join(other) {
    return new _$f0(this.seq1Range.join(other.seq1Range), this.seq2Range.join(other.seq2Range));
  }
  delta(offset) {
    if (offset === 0) {
      return this;
    }
    return new _$f0(this.seq1Range.delta(offset), this.seq2Range.delta(offset));
  }
  deltaStart(offset) {
    if (offset === 0) {
      return this;
    }
    return new _$f0(this.seq1Range.deltaStart(offset), this.seq2Range.deltaStart(offset));
  }
  deltaEnd(offset) {
    if (offset === 0) {
      return this;
    }
    return new _$f0(this.seq1Range.deltaEnd(offset), this.seq2Range.deltaEnd(offset));
  }
  intersectsOrTouches(other) {
    return this.seq1Range.intersectsOrTouches(other.seq1Range) || this.seq2Range.intersectsOrTouches(other.seq2Range);
  }
  intersect(other) {
    const i1 = this.seq1Range.intersect(other.seq1Range);
    const i2 = this.seq2Range.intersect(other.seq2Range);
    if (!i1 || !i2) {
      return void 0;
    }
    return new _$f0(i1, i2);
  }
  getStarts() {
    return new $g0(this.seq1Range.start, this.seq2Range.start);
  }
  getEndExclusives() {
    return new $g0(this.seq1Range.endExclusive, this.seq2Range.endExclusive);
  }
};
var $g0 = class _$g0 {
  static {
    this.zero = new _$g0(0, 0);
  }
  static {
    this.max = new _$g0(Number.MAX_SAFE_INTEGER, Number.MAX_SAFE_INTEGER);
  }
  constructor(offset1, offset2) {
    this.offset1 = offset1;
    this.offset2 = offset2;
  }
  toString() {
    return `${this.offset1} <-> ${this.offset2}`;
  }
  delta(offset) {
    if (offset === 0) {
      return this;
    }
    return new _$g0(this.offset1 + offset, this.offset2 + offset);
  }
  equals(other) {
    return this.offset1 === other.offset1 && this.offset2 === other.offset2;
  }
};
var $h0 = class _$h0 {
  static {
    this.instance = new _$h0();
  }
  isValid() {
    return true;
  }
};
var $i0 = class {
  constructor(e) {
    this.e = e;
    this.c = Date.now();
    this.d = true;
    if (e <= 0) {
      throw new $vb("timeout must be positive");
    }
  }
  // Recommendation: Set a log-point `{this.disable()}` in the body
  isValid() {
    const valid2 = Date.now() - this.c < this.e;
    if (!valid2 && this.d) {
      this.d = false;
    }
    return this.d;
  }
  disable() {
    this.e = Number.MAX_SAFE_INTEGER;
    this.isValid = () => true;
    this.d = true;
  }
};

// out-build/vs/editor/common/diff/defaultLinesDiffComputer/utils.js
var $j0 = class {
  constructor(width2, height) {
    this.width = width2;
    this.height = height;
    this.a = [];
    this.a = new Array(width2 * height);
  }
  get(x, y) {
    return this.a[x + y * this.width];
  }
  set(x, y, value) {
    this.a[x + y * this.width] = value;
  }
};
function $k0(charCode) {
  return charCode === 32 || charCode === 9;
}
var $l0 = class _$l0 {
  static {
    this.a = /* @__PURE__ */ new Map();
  }
  static b(chr) {
    let key2 = this.a.get(chr);
    if (key2 === void 0) {
      key2 = this.a.size;
      this.a.set(chr, key2);
    }
    return key2;
  }
  constructor(range, lines, source) {
    this.range = range;
    this.lines = lines;
    this.source = source;
    this.d = [];
    let counter = 0;
    for (let i2 = range.startLineNumber - 1; i2 < range.endLineNumberExclusive - 1; i2++) {
      const line = lines[i2];
      for (let j = 0; j < line.length; j++) {
        counter++;
        const chr = line[j];
        const key3 = _$l0.b(chr);
        this.d[key3] = (this.d[key3] || 0) + 1;
      }
      counter++;
      const key2 = _$l0.b("\n");
      this.d[key2] = (this.d[key2] || 0) + 1;
    }
    this.c = counter;
  }
  computeSimilarity(other) {
    let sumDifferences = 0;
    const maxLength = Math.max(this.d.length, other.d.length);
    for (let i2 = 0; i2 < maxLength; i2++) {
      sumDifferences += Math.abs((this.d[i2] ?? 0) - (other.d[i2] ?? 0));
    }
    return 1 - sumDifferences / (this.c + other.c);
  }
};

// out-build/vs/editor/common/diff/defaultLinesDiffComputer/algorithms/dynamicProgrammingDiffing.js
var $m0 = class {
  compute(sequence1, sequence2, timeout = $h0.instance, equalityScore) {
    if (sequence1.length === 0 || sequence2.length === 0) {
      return $e0.trivial(sequence1, sequence2);
    }
    const lcsLengths = new $j0(sequence1.length, sequence2.length);
    const directions = new $j0(sequence1.length, sequence2.length);
    const lengths = new $j0(sequence1.length, sequence2.length);
    for (let s12 = 0; s12 < sequence1.length; s12++) {
      for (let s22 = 0; s22 < sequence2.length; s22++) {
        if (!timeout.isValid()) {
          return $e0.trivialTimedOut(sequence1, sequence2);
        }
        const horizontalLen = s12 === 0 ? 0 : lcsLengths.get(s12 - 1, s22);
        const verticalLen = s22 === 0 ? 0 : lcsLengths.get(s12, s22 - 1);
        let extendedSeqScore;
        if (sequence1.getElement(s12) === sequence2.getElement(s22)) {
          if (s12 === 0 || s22 === 0) {
            extendedSeqScore = 0;
          } else {
            extendedSeqScore = lcsLengths.get(s12 - 1, s22 - 1);
          }
          if (s12 > 0 && s22 > 0 && directions.get(s12 - 1, s22 - 1) === 3) {
            extendedSeqScore += lengths.get(s12 - 1, s22 - 1);
          }
          extendedSeqScore += equalityScore ? equalityScore(s12, s22) : 1;
        } else {
          extendedSeqScore = -1;
        }
        const newValue = Math.max(horizontalLen, verticalLen, extendedSeqScore);
        if (newValue === extendedSeqScore) {
          const prevLen = s12 > 0 && s22 > 0 ? lengths.get(s12 - 1, s22 - 1) : 0;
          lengths.set(s12, s22, prevLen + 1);
          directions.set(s12, s22, 3);
        } else if (newValue === horizontalLen) {
          lengths.set(s12, s22, 0);
          directions.set(s12, s22, 1);
        } else if (newValue === verticalLen) {
          lengths.set(s12, s22, 0);
          directions.set(s12, s22, 2);
        }
        lcsLengths.set(s12, s22, newValue);
      }
    }
    const result = [];
    let lastAligningPosS1 = sequence1.length;
    let lastAligningPosS2 = sequence2.length;
    function reportDecreasingAligningPositions(s12, s22) {
      if (s12 + 1 !== lastAligningPosS1 || s22 + 1 !== lastAligningPosS2) {
        result.push(new $f0(new $0C(s12 + 1, lastAligningPosS1), new $0C(s22 + 1, lastAligningPosS2)));
      }
      lastAligningPosS1 = s12;
      lastAligningPosS2 = s22;
    }
    let s1 = sequence1.length - 1;
    let s2 = sequence2.length - 1;
    while (s1 >= 0 && s2 >= 0) {
      if (directions.get(s1, s2) === 3) {
        reportDecreasingAligningPositions(s1, s2);
        s1--;
        s2--;
      } else {
        if (directions.get(s1, s2) === 1) {
          s1--;
        } else {
          s2--;
        }
      }
    }
    reportDecreasingAligningPositions(-1, -1);
    result.reverse();
    return new $e0(result, false);
  }
};

// out-build/vs/editor/common/diff/defaultLinesDiffComputer/algorithms/myersDiffAlgorithm.js
var $n0 = class {
  compute(seq1, seq2, timeout = $h0.instance) {
    if (seq1.length === 0 || seq2.length === 0) {
      return $e0.trivial(seq1, seq2);
    }
    const seqX = seq1;
    const seqY = seq2;
    function getXAfterSnake(x, y) {
      while (x < seqX.length && y < seqY.length && seqX.getElement(x) === seqY.getElement(y)) {
        x++;
        y++;
      }
      return x;
    }
    let d = 0;
    const V = new FastInt32Array();
    V.set(0, getXAfterSnake(0, 0));
    const paths = new FastArrayNegativeIndices();
    paths.set(0, V.get(0) === 0 ? null : new SnakePath(null, 0, 0, V.get(0)));
    let k = 0;
    loop: while (true) {
      d++;
      if (!timeout.isValid()) {
        return $e0.trivialTimedOut(seqX, seqY);
      }
      const lowerBound = -Math.min(d, seqY.length + d % 2);
      const upperBound = Math.min(d, seqX.length + d % 2);
      for (k = lowerBound; k <= upperBound; k += 2) {
        let step = 0;
        const maxXofDLineTop = k === upperBound ? -1 : V.get(k + 1);
        const maxXofDLineLeft = k === lowerBound ? -1 : V.get(k - 1) + 1;
        step++;
        const x = Math.min(Math.max(maxXofDLineTop, maxXofDLineLeft), seqX.length);
        const y = x - k;
        step++;
        if (x > seqX.length || y > seqY.length) {
          continue;
        }
        const newMaxX = getXAfterSnake(x, y);
        V.set(k, newMaxX);
        const lastPath = x === maxXofDLineTop ? paths.get(k + 1) : paths.get(k - 1);
        paths.set(k, newMaxX !== x ? new SnakePath(lastPath, x, y, newMaxX - x) : lastPath);
        if (V.get(k) === seqX.length && V.get(k) - k === seqY.length) {
          break loop;
        }
      }
    }
    let path = paths.get(k);
    const result = [];
    let lastAligningPosS1 = seqX.length;
    let lastAligningPosS2 = seqY.length;
    while (true) {
      const endX = path ? path.x + path.length : 0;
      const endY = path ? path.y + path.length : 0;
      if (endX !== lastAligningPosS1 || endY !== lastAligningPosS2) {
        result.push(new $f0(new $0C(endX, lastAligningPosS1), new $0C(endY, lastAligningPosS2)));
      }
      if (!path) {
        break;
      }
      lastAligningPosS1 = path.x;
      lastAligningPosS2 = path.y;
      path = path.prev;
    }
    result.reverse();
    return new $e0(result, false);
  }
};
var SnakePath = class {
  constructor(prev, x, y, length) {
    this.prev = prev;
    this.x = x;
    this.y = y;
    this.length = length;
  }
};
var FastInt32Array = class {
  constructor() {
    this.a = new Int32Array(10);
    this.b = new Int32Array(10);
  }
  get(idx) {
    if (idx < 0) {
      idx = -idx - 1;
      return this.b[idx];
    } else {
      return this.a[idx];
    }
  }
  set(idx, value) {
    if (idx < 0) {
      idx = -idx - 1;
      if (idx >= this.b.length) {
        const arr = this.b;
        this.b = new Int32Array(arr.length * 2);
        this.b.set(arr);
      }
      this.b[idx] = value;
    } else {
      if (idx >= this.a.length) {
        const arr = this.a;
        this.a = new Int32Array(arr.length * 2);
        this.a.set(arr);
      }
      this.a[idx] = value;
    }
  }
};
var FastArrayNegativeIndices = class {
  constructor() {
    this.a = [];
    this.b = [];
  }
  get(idx) {
    if (idx < 0) {
      idx = -idx - 1;
      return this.b[idx];
    } else {
      return this.a[idx];
    }
  }
  set(idx, value) {
    if (idx < 0) {
      idx = -idx - 1;
      this.b[idx] = value;
    } else {
      this.a[idx] = value;
    }
  }
};

// out-build/vs/editor/common/diff/defaultLinesDiffComputer/linesSliceCharSequence.js
var $o0 = class {
  constructor(lines, g, considerWhitespaceChanges) {
    this.lines = lines;
    this.g = g;
    this.considerWhitespaceChanges = considerWhitespaceChanges;
    this.b = [];
    this.c = [];
    this.d = [];
    this.f = [];
    this.c.push(0);
    for (let lineNumber = this.g.startLineNumber; lineNumber <= this.g.endLineNumber; lineNumber++) {
      let line = lines[lineNumber - 1];
      let lineStartOffset = 0;
      if (lineNumber === this.g.startLineNumber && this.g.startColumn > 1) {
        lineStartOffset = this.g.startColumn - 1;
        line = line.substring(lineStartOffset);
      }
      this.d.push(lineStartOffset);
      let trimmedWsLength = 0;
      if (!considerWhitespaceChanges) {
        const trimmedStartLine = line.trimStart();
        trimmedWsLength = line.length - trimmedStartLine.length;
        line = trimmedStartLine.trimEnd();
      }
      this.f.push(trimmedWsLength);
      const lineLength = lineNumber === this.g.endLineNumber ? Math.min(this.g.endColumn - 1 - lineStartOffset - trimmedWsLength, line.length) : line.length;
      for (let i2 = 0; i2 < lineLength; i2++) {
        this.b.push(line.charCodeAt(i2));
      }
      if (lineNumber < this.g.endLineNumber) {
        this.b.push("\n".charCodeAt(0));
        this.c.push(this.b.length);
      }
    }
  }
  toString() {
    return `Slice: "${this.text}"`;
  }
  get text() {
    return this.getText(new $0C(0, this.length));
  }
  getText(range) {
    return this.b.slice(range.start, range.endExclusive).map((e) => String.fromCharCode(e)).join("");
  }
  getElement(offset) {
    return this.b[offset];
  }
  get length() {
    return this.b.length;
  }
  getBoundaryScore(length) {
    const prevCategory = getCategory(length > 0 ? this.b[length - 1] : -1);
    const nextCategory = getCategory(length < this.b.length ? this.b[length] : -1);
    if (prevCategory === 7 && nextCategory === 8) {
      return 0;
    }
    if (prevCategory === 8) {
      return 150;
    }
    let score2 = 0;
    if (prevCategory !== nextCategory) {
      score2 += 10;
      if (prevCategory === 0 && nextCategory === 1) {
        score2 += 1;
      }
    }
    score2 += getCategoryBoundaryScore(prevCategory);
    score2 += getCategoryBoundaryScore(nextCategory);
    return score2;
  }
  translateOffset(offset, preference = "right") {
    const i2 = $4(this.c, (value) => value <= offset);
    const lineOffset = offset - this.c[i2];
    return new $8C(this.g.startLineNumber + i2, 1 + this.d[i2] + lineOffset + (lineOffset === 0 && preference === "left" ? 0 : this.f[i2]));
  }
  translateRange(range) {
    const pos1 = this.translateOffset(range.start, "right");
    const pos2 = this.translateOffset(range.endExclusive, "left");
    if (pos2.isBefore(pos1)) {
      return $9C.fromPositions(pos2, pos2);
    }
    return $9C.fromPositions(pos1, pos2);
  }
  /**
   * Finds the word that contains the character at the given offset
   */
  findWordContaining(offset) {
    if (offset < 0 || offset >= this.b.length) {
      return void 0;
    }
    if (!isWordChar(this.b[offset])) {
      return void 0;
    }
    let start = offset;
    while (start > 0 && isWordChar(this.b[start - 1])) {
      start--;
    }
    let end = offset;
    while (end < this.b.length && isWordChar(this.b[end])) {
      end++;
    }
    return new $0C(start, end);
  }
  countLinesIn(range) {
    return this.translateOffset(range.endExclusive).lineNumber - this.translateOffset(range.start).lineNumber;
  }
  isStronglyEqual(offset1, offset2) {
    return this.b[offset1] === this.b[offset2];
  }
  extendToFullLines(range) {
    const start = $3(this.c, (x) => x <= range.start) ?? 0;
    const end = $5(this.c, (x) => range.endExclusive <= x) ?? this.b.length;
    return new $0C(start, end);
  }
};
function isWordChar(charCode) {
  return charCode >= 97 && charCode <= 122 || charCode >= 65 && charCode <= 90 || charCode >= 48 && charCode <= 57;
}
var CharBoundaryCategory;
(function(CharBoundaryCategory2) {
  CharBoundaryCategory2[CharBoundaryCategory2["WordLower"] = 0] = "WordLower";
  CharBoundaryCategory2[CharBoundaryCategory2["WordUpper"] = 1] = "WordUpper";
  CharBoundaryCategory2[CharBoundaryCategory2["WordNumber"] = 2] = "WordNumber";
  CharBoundaryCategory2[CharBoundaryCategory2["End"] = 3] = "End";
  CharBoundaryCategory2[CharBoundaryCategory2["Other"] = 4] = "Other";
  CharBoundaryCategory2[CharBoundaryCategory2["Separator"] = 5] = "Separator";
  CharBoundaryCategory2[CharBoundaryCategory2["Space"] = 6] = "Space";
  CharBoundaryCategory2[CharBoundaryCategory2["LineBreakCR"] = 7] = "LineBreakCR";
  CharBoundaryCategory2[CharBoundaryCategory2["LineBreakLF"] = 8] = "LineBreakLF";
})(CharBoundaryCategory || (CharBoundaryCategory = {}));
var score = {
  [
    0
    /* CharBoundaryCategory.WordLower */
  ]: 0,
  [
    1
    /* CharBoundaryCategory.WordUpper */
  ]: 0,
  [
    2
    /* CharBoundaryCategory.WordNumber */
  ]: 0,
  [
    3
    /* CharBoundaryCategory.End */
  ]: 10,
  [
    4
    /* CharBoundaryCategory.Other */
  ]: 2,
  [
    5
    /* CharBoundaryCategory.Separator */
  ]: 30,
  [
    6
    /* CharBoundaryCategory.Space */
  ]: 3,
  [
    7
    /* CharBoundaryCategory.LineBreakCR */
  ]: 10,
  [
    8
    /* CharBoundaryCategory.LineBreakLF */
  ]: 10
};
function getCategoryBoundaryScore(category8) {
  return score[category8];
}
function getCategory(charCode) {
  if (charCode === 10) {
    return 8;
  } else if (charCode === 13) {
    return 7;
  } else if ($k0(charCode)) {
    return 6;
  } else if (charCode >= 97 && charCode <= 122) {
    return 0;
  } else if (charCode >= 65 && charCode <= 90) {
    return 1;
  } else if (charCode >= 48 && charCode <= 57) {
    return 2;
  } else if (charCode === -1) {
    return 3;
  } else if (charCode === 44 || charCode === 59) {
    return 5;
  } else {
    return 4;
  }
}

// out-build/vs/editor/common/diff/defaultLinesDiffComputer/computeMovedLines.js
function $p0(changes, originalLines, modifiedLines, hashedOriginalLines, hashedModifiedLines, timeout) {
  let { moves, excludedChanges } = computeMovesFromSimpleDeletionsToSimpleInsertions(changes, originalLines, modifiedLines, timeout);
  if (!timeout.isValid()) {
    return [];
  }
  const filteredChanges = changes.filter((c) => !excludedChanges.has(c));
  const unchangedMoves = computeUnchangedMoves(filteredChanges, hashedOriginalLines, hashedModifiedLines, originalLines, modifiedLines, timeout);
  $3b(moves, unchangedMoves);
  moves = joinCloseConsecutiveMoves(moves);
  moves = moves.filter((current) => {
    const lines = current.original.toOffsetRange().slice(originalLines).map((l) => l.trim());
    const originalText = lines.join("\n");
    return originalText.length >= 15 && countWhere(lines, (l) => l.length >= 2) >= 2;
  });
  moves = removeMovesInSameDiff(changes, moves);
  return moves;
}
function countWhere(arr, predicate) {
  let count = 0;
  for (const t of arr) {
    if (predicate(t)) {
      count++;
    }
  }
  return count;
}
function computeMovesFromSimpleDeletionsToSimpleInsertions(changes, originalLines, modifiedLines, timeout) {
  const moves = [];
  const deletions = changes.filter((c) => c.modified.isEmpty && c.original.length >= 3).map((d) => new $l0(d.original, originalLines, d));
  const insertions = new Set(changes.filter((c) => c.original.isEmpty && c.modified.length >= 3).map((d) => new $l0(d.modified, modifiedLines, d)));
  const excludedChanges = /* @__PURE__ */ new Set();
  for (const deletion of deletions) {
    let highestSimilarity = -1;
    let best;
    for (const insertion of insertions) {
      const similarity = deletion.computeSimilarity(insertion);
      if (similarity > highestSimilarity) {
        highestSimilarity = similarity;
        best = insertion;
      }
    }
    if (highestSimilarity > 0.9 && best) {
      insertions.delete(best);
      moves.push(new $pD(deletion.range, best.range));
      excludedChanges.add(deletion.source);
      excludedChanges.add(best.source);
    }
    if (!timeout.isValid()) {
      return { moves, excludedChanges };
    }
  }
  return { moves, excludedChanges };
}
function computeUnchangedMoves(changes, hashedOriginalLines, hashedModifiedLines, originalLines, modifiedLines, timeout) {
  const moves = [];
  const original3LineHashes = new $Lc();
  for (const change of changes) {
    for (let i2 = change.original.startLineNumber; i2 < change.original.endLineNumberExclusive - 2; i2++) {
      const key2 = `${hashedOriginalLines[i2 - 1]}:${hashedOriginalLines[i2 + 1 - 1]}:${hashedOriginalLines[i2 + 2 - 1]}`;
      original3LineHashes.add(key2, { range: new $_C(i2, i2 + 3) });
    }
  }
  const possibleMappings = [];
  changes.sort($9b((c) => c.modified.startLineNumber, $$b));
  for (const change of changes) {
    let lastMappings = [];
    for (let i2 = change.modified.startLineNumber; i2 < change.modified.endLineNumberExclusive - 2; i2++) {
      const key2 = `${hashedModifiedLines[i2 - 1]}:${hashedModifiedLines[i2 + 1 - 1]}:${hashedModifiedLines[i2 + 2 - 1]}`;
      const currentModifiedRange = new $_C(i2, i2 + 3);
      const nextMappings = [];
      original3LineHashes.forEach(key2, ({ range }) => {
        for (const lastMapping of lastMappings) {
          if (lastMapping.originalLineRange.endLineNumberExclusive + 1 === range.endLineNumberExclusive && lastMapping.modifiedLineRange.endLineNumberExclusive + 1 === currentModifiedRange.endLineNumberExclusive) {
            lastMapping.originalLineRange = new $_C(lastMapping.originalLineRange.startLineNumber, range.endLineNumberExclusive);
            lastMapping.modifiedLineRange = new $_C(lastMapping.modifiedLineRange.startLineNumber, currentModifiedRange.endLineNumberExclusive);
            nextMappings.push(lastMapping);
            return;
          }
        }
        const mapping2 = {
          modifiedLineRange: currentModifiedRange,
          originalLineRange: range
        };
        possibleMappings.push(mapping2);
        nextMappings.push(mapping2);
      });
      lastMappings = nextMappings;
    }
    if (!timeout.isValid()) {
      return [];
    }
  }
  possibleMappings.sort($ac($9b((m) => m.modifiedLineRange.length, $$b)));
  const modifiedSet = new $aD();
  const originalSet = new $aD();
  for (const mapping2 of possibleMappings) {
    const diffOrigToMod = mapping2.modifiedLineRange.startLineNumber - mapping2.originalLineRange.startLineNumber;
    const modifiedSections = modifiedSet.subtractFrom(mapping2.modifiedLineRange);
    const originalTranslatedSections = originalSet.subtractFrom(mapping2.originalLineRange).getWithDelta(diffOrigToMod);
    const modifiedIntersectedSections = modifiedSections.getIntersection(originalTranslatedSections);
    for (const s of modifiedIntersectedSections.ranges) {
      if (s.length < 3) {
        continue;
      }
      const modifiedLineRange = s;
      const originalLineRange = s.delta(-diffOrigToMod);
      moves.push(new $pD(originalLineRange, modifiedLineRange));
      modifiedSet.addRange(modifiedLineRange);
      originalSet.addRange(originalLineRange);
    }
  }
  moves.sort($9b((m) => m.original.startLineNumber, $$b));
  const monotonousChanges = new $8(changes);
  for (let i2 = 0; i2 < moves.length; i2++) {
    const move = moves[i2];
    const firstTouchingChangeOrig = monotonousChanges.findLastMonotonous((c) => c.original.startLineNumber <= move.original.startLineNumber);
    const firstTouchingChangeMod = $3(changes, (c) => c.modified.startLineNumber <= move.modified.startLineNumber);
    const linesAbove = Math.max(move.original.startLineNumber - firstTouchingChangeOrig.original.startLineNumber, move.modified.startLineNumber - firstTouchingChangeMod.modified.startLineNumber);
    const lastTouchingChangeOrig = monotonousChanges.findLastMonotonous((c) => c.original.startLineNumber < move.original.endLineNumberExclusive);
    const lastTouchingChangeMod = $3(changes, (c) => c.modified.startLineNumber < move.modified.endLineNumberExclusive);
    const linesBelow = Math.max(lastTouchingChangeOrig.original.endLineNumberExclusive - move.original.endLineNumberExclusive, lastTouchingChangeMod.modified.endLineNumberExclusive - move.modified.endLineNumberExclusive);
    let extendToTop;
    for (extendToTop = 0; extendToTop < linesAbove; extendToTop++) {
      const origLine = move.original.startLineNumber - extendToTop - 1;
      const modLine = move.modified.startLineNumber - extendToTop - 1;
      if (origLine > originalLines.length || modLine > modifiedLines.length) {
        break;
      }
      if (modifiedSet.contains(modLine) || originalSet.contains(origLine)) {
        break;
      }
      if (!areLinesSimilar(originalLines[origLine - 1], modifiedLines[modLine - 1], timeout)) {
        break;
      }
    }
    if (extendToTop > 0) {
      originalSet.addRange(new $_C(move.original.startLineNumber - extendToTop, move.original.startLineNumber));
      modifiedSet.addRange(new $_C(move.modified.startLineNumber - extendToTop, move.modified.startLineNumber));
    }
    let extendToBottom;
    for (extendToBottom = 0; extendToBottom < linesBelow; extendToBottom++) {
      const origLine = move.original.endLineNumberExclusive + extendToBottom;
      const modLine = move.modified.endLineNumberExclusive + extendToBottom;
      if (origLine > originalLines.length || modLine > modifiedLines.length) {
        break;
      }
      if (modifiedSet.contains(modLine) || originalSet.contains(origLine)) {
        break;
      }
      if (!areLinesSimilar(originalLines[origLine - 1], modifiedLines[modLine - 1], timeout)) {
        break;
      }
    }
    if (extendToBottom > 0) {
      originalSet.addRange(new $_C(move.original.endLineNumberExclusive, move.original.endLineNumberExclusive + extendToBottom));
      modifiedSet.addRange(new $_C(move.modified.endLineNumberExclusive, move.modified.endLineNumberExclusive + extendToBottom));
    }
    if (extendToTop > 0 || extendToBottom > 0) {
      moves[i2] = new $pD(new $_C(move.original.startLineNumber - extendToTop, move.original.endLineNumberExclusive + extendToBottom), new $_C(move.modified.startLineNumber - extendToTop, move.modified.endLineNumberExclusive + extendToBottom));
    }
  }
  return moves;
}
function areLinesSimilar(line1, line2, timeout) {
  if (line1.trim() === line2.trim()) {
    return true;
  }
  if (line1.length > 300 && line2.length > 300) {
    return false;
  }
  const myersDiffingAlgorithm = new $n0();
  const result = myersDiffingAlgorithm.compute(new $o0([line1], new $9C(1, 1, 1, line1.length), false), new $o0([line2], new $9C(1, 1, 1, line2.length), false), timeout);
  let commonNonSpaceCharCount = 0;
  const inverted = $f0.invert(result.diffs, line1.length);
  for (const seq of inverted) {
    seq.seq1Range.forEach((idx) => {
      if (!$k0(line1.charCodeAt(idx))) {
        commonNonSpaceCharCount++;
      }
    });
  }
  function countNonWsChars(str) {
    let count = 0;
    for (let i2 = 0; i2 < line1.length; i2++) {
      if (!$k0(str.charCodeAt(i2))) {
        count++;
      }
    }
    return count;
  }
  const longerLineLength = countNonWsChars(line1.length > line2.length ? line1 : line2);
  const r2 = commonNonSpaceCharCount / longerLineLength > 0.6 && longerLineLength > 10;
  return r2;
}
function joinCloseConsecutiveMoves(moves) {
  if (moves.length === 0) {
    return moves;
  }
  moves.sort($9b((m) => m.original.startLineNumber, $$b));
  const result = [moves[0]];
  for (let i2 = 1; i2 < moves.length; i2++) {
    const last = result[result.length - 1];
    const current = moves[i2];
    const originalDist = current.original.startLineNumber - last.original.endLineNumberExclusive;
    const modifiedDist = current.modified.startLineNumber - last.modified.endLineNumberExclusive;
    const currentMoveAfterLast = originalDist >= 0 && modifiedDist >= 0;
    if (currentMoveAfterLast && originalDist + modifiedDist <= 2) {
      result[result.length - 1] = last.join(current);
      continue;
    }
    result.push(current);
  }
  return result;
}
function removeMovesInSameDiff(changes, moves) {
  const changesMonotonous = new $8(changes);
  moves = moves.filter((m) => {
    const diffBeforeEndOfMoveOriginal = changesMonotonous.findLastMonotonous((c) => c.original.startLineNumber < m.original.endLineNumberExclusive) || new $pD(new $_C(1, 1), new $_C(1, 1));
    const diffBeforeEndOfMoveModified = $3(changes, (c) => c.modified.startLineNumber < m.modified.endLineNumberExclusive);
    const differentDiffs = diffBeforeEndOfMoveOriginal !== diffBeforeEndOfMoveModified;
    return differentDiffs;
  });
  return moves;
}

// out-build/vs/editor/common/diff/defaultLinesDiffComputer/heuristicSequenceOptimizations.js
function $r0(sequence1, sequence2, sequenceDiffs) {
  let result = sequenceDiffs;
  result = joinSequenceDiffsByShifting(sequence1, sequence2, result);
  result = joinSequenceDiffsByShifting(sequence1, sequence2, result);
  result = shiftSequenceDiffs(sequence1, sequence2, result);
  return result;
}
function joinSequenceDiffsByShifting(sequence1, sequence2, sequenceDiffs) {
  if (sequenceDiffs.length === 0) {
    return sequenceDiffs;
  }
  const result = [];
  result.push(sequenceDiffs[0]);
  for (let i2 = 1; i2 < sequenceDiffs.length; i2++) {
    const prevResult = result[result.length - 1];
    let cur = sequenceDiffs[i2];
    if (cur.seq1Range.isEmpty || cur.seq2Range.isEmpty) {
      const length = cur.seq1Range.start - prevResult.seq1Range.endExclusive;
      let d;
      for (d = 1; d <= length; d++) {
        if (sequence1.getElement(cur.seq1Range.start - d) !== sequence1.getElement(cur.seq1Range.endExclusive - d) || sequence2.getElement(cur.seq2Range.start - d) !== sequence2.getElement(cur.seq2Range.endExclusive - d)) {
          break;
        }
      }
      d--;
      if (d === length) {
        result[result.length - 1] = new $f0(new $0C(prevResult.seq1Range.start, cur.seq1Range.endExclusive - length), new $0C(prevResult.seq2Range.start, cur.seq2Range.endExclusive - length));
        continue;
      }
      cur = cur.delta(-d);
    }
    result.push(cur);
  }
  const result2 = [];
  for (let i2 = 0; i2 < result.length - 1; i2++) {
    const nextResult = result[i2 + 1];
    let cur = result[i2];
    if (cur.seq1Range.isEmpty || cur.seq2Range.isEmpty) {
      const length = nextResult.seq1Range.start - cur.seq1Range.endExclusive;
      let d;
      for (d = 0; d < length; d++) {
        if (!sequence1.isStronglyEqual(cur.seq1Range.start + d, cur.seq1Range.endExclusive + d) || !sequence2.isStronglyEqual(cur.seq2Range.start + d, cur.seq2Range.endExclusive + d)) {
          break;
        }
      }
      if (d === length) {
        result[i2 + 1] = new $f0(new $0C(cur.seq1Range.start + length, nextResult.seq1Range.endExclusive), new $0C(cur.seq2Range.start + length, nextResult.seq2Range.endExclusive));
        continue;
      }
      if (d > 0) {
        cur = cur.delta(d);
      }
    }
    result2.push(cur);
  }
  if (result.length > 0) {
    result2.push(result[result.length - 1]);
  }
  return result2;
}
function shiftSequenceDiffs(sequence1, sequence2, sequenceDiffs) {
  if (!sequence1.getBoundaryScore || !sequence2.getBoundaryScore) {
    return sequenceDiffs;
  }
  for (let i2 = 0; i2 < sequenceDiffs.length; i2++) {
    const prevDiff = i2 > 0 ? sequenceDiffs[i2 - 1] : void 0;
    const diff3 = sequenceDiffs[i2];
    const nextDiff = i2 + 1 < sequenceDiffs.length ? sequenceDiffs[i2 + 1] : void 0;
    const seq1ValidRange = new $0C(prevDiff ? prevDiff.seq1Range.endExclusive + 1 : 0, nextDiff ? nextDiff.seq1Range.start - 1 : sequence1.length);
    const seq2ValidRange = new $0C(prevDiff ? prevDiff.seq2Range.endExclusive + 1 : 0, nextDiff ? nextDiff.seq2Range.start - 1 : sequence2.length);
    if (diff3.seq1Range.isEmpty) {
      sequenceDiffs[i2] = shiftDiffToBetterPosition(diff3, sequence1, sequence2, seq1ValidRange, seq2ValidRange);
    } else if (diff3.seq2Range.isEmpty) {
      sequenceDiffs[i2] = shiftDiffToBetterPosition(diff3.swap(), sequence2, sequence1, seq2ValidRange, seq1ValidRange).swap();
    }
  }
  return sequenceDiffs;
}
function shiftDiffToBetterPosition(diff3, sequence1, sequence2, seq1ValidRange, seq2ValidRange) {
  const maxShiftLimit = 100;
  let deltaBefore = 1;
  while (diff3.seq1Range.start - deltaBefore >= seq1ValidRange.start && diff3.seq2Range.start - deltaBefore >= seq2ValidRange.start && sequence2.isStronglyEqual(diff3.seq2Range.start - deltaBefore, diff3.seq2Range.endExclusive - deltaBefore) && deltaBefore < maxShiftLimit) {
    deltaBefore++;
  }
  deltaBefore--;
  let deltaAfter = 0;
  while (diff3.seq1Range.start + deltaAfter < seq1ValidRange.endExclusive && diff3.seq2Range.endExclusive + deltaAfter < seq2ValidRange.endExclusive && sequence2.isStronglyEqual(diff3.seq2Range.start + deltaAfter, diff3.seq2Range.endExclusive + deltaAfter) && deltaAfter < maxShiftLimit) {
    deltaAfter++;
  }
  if (deltaBefore === 0 && deltaAfter === 0) {
    return diff3;
  }
  let bestDelta = 0;
  let bestScore = -1;
  for (let delta = -deltaBefore; delta <= deltaAfter; delta++) {
    const seq2OffsetStart = diff3.seq2Range.start + delta;
    const seq2OffsetEndExclusive = diff3.seq2Range.endExclusive + delta;
    const seq1Offset = diff3.seq1Range.start + delta;
    const score2 = sequence1.getBoundaryScore(seq1Offset) + sequence2.getBoundaryScore(seq2OffsetStart) + sequence2.getBoundaryScore(seq2OffsetEndExclusive);
    if (score2 > bestScore) {
      bestScore = score2;
      bestDelta = delta;
    }
  }
  return diff3.delta(bestDelta);
}
function $s0(sequence1, sequence2, sequenceDiffs) {
  const result = [];
  for (const s of sequenceDiffs) {
    const last = result[result.length - 1];
    if (!last) {
      result.push(s);
      continue;
    }
    if (s.seq1Range.start - last.seq1Range.endExclusive <= 2 || s.seq2Range.start - last.seq2Range.endExclusive <= 2) {
      result[result.length - 1] = new $f0(last.seq1Range.join(s.seq1Range), last.seq2Range.join(s.seq2Range));
    } else {
      result.push(s);
    }
  }
  return result;
}
function $t0(sequence1, sequence2, sequenceDiffs) {
  const equalMappings = $f0.invert(sequenceDiffs, sequence1.length);
  const additional = [];
  let lastPoint = new $g0(0, 0);
  function scanWord(pair, equalMapping) {
    if (pair.offset1 < lastPoint.offset1 || pair.offset2 < lastPoint.offset2) {
      return;
    }
    const w1 = sequence1.findWordContaining(pair.offset1);
    const w2 = sequence2.findWordContaining(pair.offset2);
    if (!w1 || !w2) {
      return;
    }
    let w = new $f0(w1, w2);
    const equalPart = w.intersect(equalMapping);
    let equalChars1 = equalPart.seq1Range.length;
    let equalChars2 = equalPart.seq2Range.length;
    while (equalMappings.length > 0) {
      const next = equalMappings[0];
      const intersects4 = next.seq1Range.intersects(w.seq1Range) || next.seq2Range.intersects(w.seq2Range);
      if (!intersects4) {
        break;
      }
      const v1 = sequence1.findWordContaining(next.seq1Range.start);
      const v2 = sequence2.findWordContaining(next.seq2Range.start);
      const v = new $f0(v1, v2);
      const equalPart2 = v.intersect(next);
      equalChars1 += equalPart2.seq1Range.length;
      equalChars2 += equalPart2.seq2Range.length;
      w = w.join(v);
      if (w.seq1Range.endExclusive >= next.seq1Range.endExclusive) {
        equalMappings.shift();
      } else {
        break;
      }
    }
    if (equalChars1 + equalChars2 < (w.seq1Range.length + w.seq2Range.length) * 2 / 3) {
      additional.push(w);
    }
    lastPoint = w.getEndExclusives();
  }
  while (equalMappings.length > 0) {
    const next = equalMappings.shift();
    if (next.seq1Range.isEmpty) {
      continue;
    }
    scanWord(next.getStarts(), next);
    scanWord(next.getEndExclusives().delta(-1), next);
  }
  const merged = mergeSequenceDiffs(sequenceDiffs, additional);
  return merged;
}
function mergeSequenceDiffs(sequenceDiffs1, sequenceDiffs2) {
  const result = [];
  while (sequenceDiffs1.length > 0 || sequenceDiffs2.length > 0) {
    const sd1 = sequenceDiffs1[0];
    const sd2 = sequenceDiffs2[0];
    let next;
    if (sd1 && (!sd2 || sd1.seq1Range.start < sd2.seq1Range.start)) {
      next = sequenceDiffs1.shift();
    } else {
      next = sequenceDiffs2.shift();
    }
    if (result.length > 0 && result[result.length - 1].seq1Range.endExclusive >= next.seq1Range.start) {
      result[result.length - 1] = result[result.length - 1].join(next);
    } else {
      result.push(next);
    }
  }
  return result;
}
function $u0(sequence1, _sequence2, sequenceDiffs) {
  let diffs = sequenceDiffs;
  if (diffs.length === 0) {
    return diffs;
  }
  let counter = 0;
  let shouldRepeat;
  do {
    shouldRepeat = false;
    const result = [
      diffs[0]
    ];
    for (let i2 = 1; i2 < diffs.length; i2++) {
      let shouldJoinDiffs2 = function(before, after) {
        const unchangedRange = new $0C(lastResult.seq1Range.endExclusive, cur.seq1Range.start);
        const unchangedText = sequence1.getText(unchangedRange);
        const unchangedTextWithoutWs = unchangedText.replace(/\s/g, "");
        if (unchangedTextWithoutWs.length <= 4 && (before.seq1Range.length + before.seq2Range.length > 5 || after.seq1Range.length + after.seq2Range.length > 5)) {
          return true;
        }
        return false;
      };
      var shouldJoinDiffs = shouldJoinDiffs2;
      const cur = diffs[i2];
      const lastResult = result[result.length - 1];
      const shouldJoin = shouldJoinDiffs2(lastResult, cur);
      if (shouldJoin) {
        shouldRepeat = true;
        result[result.length - 1] = result[result.length - 1].join(cur);
      } else {
        result.push(cur);
      }
    }
    diffs = result;
  } while (counter++ < 10 && shouldRepeat);
  return diffs;
}
function $v0(sequence1, sequence2, sequenceDiffs) {
  let diffs = sequenceDiffs;
  if (diffs.length === 0) {
    return diffs;
  }
  let counter = 0;
  let shouldRepeat;
  do {
    shouldRepeat = false;
    const result = [
      diffs[0]
    ];
    for (let i2 = 1; i2 < diffs.length; i2++) {
      let shouldJoinDiffs2 = function(before, after) {
        const unchangedRange = new $0C(lastResult.seq1Range.endExclusive, cur.seq1Range.start);
        const unchangedLineCount = sequence1.countLinesIn(unchangedRange);
        if (unchangedLineCount > 5 || unchangedRange.length > 500) {
          return false;
        }
        const unchangedText = sequence1.getText(unchangedRange).trim();
        if (unchangedText.length > 20 || unchangedText.split(/\r\n|\r|\n/).length > 1) {
          return false;
        }
        const beforeLineCount1 = sequence1.countLinesIn(before.seq1Range);
        const beforeSeq1Length = before.seq1Range.length;
        const beforeLineCount2 = sequence2.countLinesIn(before.seq2Range);
        const beforeSeq2Length = before.seq2Range.length;
        const afterLineCount1 = sequence1.countLinesIn(after.seq1Range);
        const afterSeq1Length = after.seq1Range.length;
        const afterLineCount2 = sequence2.countLinesIn(after.seq2Range);
        const afterSeq2Length = after.seq2Range.length;
        const max = 2 * 40 + 50;
        function cap(v) {
          return Math.min(v, max);
        }
        if (Math.pow(Math.pow(cap(beforeLineCount1 * 40 + beforeSeq1Length), 1.5) + Math.pow(cap(beforeLineCount2 * 40 + beforeSeq2Length), 1.5), 1.5) + Math.pow(Math.pow(cap(afterLineCount1 * 40 + afterSeq1Length), 1.5) + Math.pow(cap(afterLineCount2 * 40 + afterSeq2Length), 1.5), 1.5) > (max ** 1.5) ** 1.5 * 1.3) {
          return true;
        }
        return false;
      };
      var shouldJoinDiffs = shouldJoinDiffs2;
      const cur = diffs[i2];
      const lastResult = result[result.length - 1];
      const shouldJoin = shouldJoinDiffs2(lastResult, cur);
      if (shouldJoin) {
        shouldRepeat = true;
        result[result.length - 1] = result[result.length - 1].join(cur);
      } else {
        result.push(cur);
      }
    }
    diffs = result;
  } while (counter++ < 10 && shouldRepeat);
  const newDiffs = [];
  $Hb(diffs, (prev, cur, next) => {
    let newDiff = cur;
    function shouldMarkAsChanged(text2) {
      return text2.length > 0 && text2.trim().length <= 3 && cur.seq1Range.length + cur.seq2Range.length > 100;
    }
    const fullRange1 = sequence1.extendToFullLines(cur.seq1Range);
    const prefix = sequence1.getText(new $0C(fullRange1.start, cur.seq1Range.start));
    if (shouldMarkAsChanged(prefix)) {
      newDiff = newDiff.deltaStart(-prefix.length);
    }
    const suffix = sequence1.getText(new $0C(cur.seq1Range.endExclusive, fullRange1.endExclusive));
    if (shouldMarkAsChanged(suffix)) {
      newDiff = newDiff.deltaEnd(suffix.length);
    }
    const availableSpace = $f0.fromOffsetPairs(prev ? prev.getEndExclusives() : $g0.zero, next ? next.getStarts() : $g0.max);
    const result = newDiff.intersect(availableSpace);
    if (newDiffs.length > 0 && result.getStarts().equals(newDiffs[newDiffs.length - 1].getEndExclusives())) {
      newDiffs[newDiffs.length - 1] = newDiffs[newDiffs.length - 1].join(result);
    } else {
      newDiffs.push(result);
    }
  });
  return newDiffs;
}

// out-build/vs/editor/common/diff/defaultLinesDiffComputer/lineSequence.js
var $q0 = class {
  constructor(a, b) {
    this.a = a;
    this.b = b;
  }
  getElement(offset) {
    return this.a[offset];
  }
  get length() {
    return this.a.length;
  }
  getBoundaryScore(length) {
    const indentationBefore = length === 0 ? 0 : getIndentation(this.b[length - 1]);
    const indentationAfter = length === this.b.length ? 0 : getIndentation(this.b[length]);
    return 1e3 - (indentationBefore + indentationAfter);
  }
  getText(range) {
    return this.b.slice(range.start, range.endExclusive).join("\n");
  }
  isStronglyEqual(offset1, offset2) {
    return this.b[offset1] === this.b[offset2];
  }
};
function getIndentation(str) {
  let i2 = 0;
  while (i2 < str.length && (str.charCodeAt(i2) === 32 || str.charCodeAt(i2) === 9)) {
    i2++;
  }
  return i2;
}

// out-build/vs/editor/common/diff/defaultLinesDiffComputer/defaultLinesDiffComputer.js
var $w0 = class {
  constructor() {
    this.e = new $m0();
    this.f = new $n0();
  }
  computeDiff(originalLines, modifiedLines, options3) {
    if (originalLines.length <= 1 && $zb(originalLines, modifiedLines, (a, b) => a === b)) {
      return new $vD([], [], false);
    }
    if (originalLines.length === 1 && originalLines[0].length === 0 || modifiedLines.length === 1 && modifiedLines[0].length === 0) {
      return new $vD([
        new $qD(new $_C(1, originalLines.length + 1), new $_C(1, modifiedLines.length + 1), [
          new $rD(new $9C(1, 1, originalLines.length, originalLines[originalLines.length - 1].length + 1), new $9C(1, 1, modifiedLines.length, modifiedLines[modifiedLines.length - 1].length + 1))
        ])
      ], [], false);
    }
    const timeout = options3.maxComputationTimeMs === 0 ? $h0.instance : new $i0(options3.maxComputationTimeMs);
    const considerWhitespaceChanges = !options3.ignoreTrimWhitespace;
    const perfectHashes = /* @__PURE__ */ new Map();
    function getOrCreateHash(text2) {
      let hash = perfectHashes.get(text2);
      if (hash === void 0) {
        hash = perfectHashes.size;
        perfectHashes.set(text2, hash);
      }
      return hash;
    }
    const originalLinesHashes = originalLines.map((l) => getOrCreateHash(l.trim()));
    const modifiedLinesHashes = modifiedLines.map((l) => getOrCreateHash(l.trim()));
    const sequence1 = new $q0(originalLinesHashes, originalLines);
    const sequence2 = new $q0(modifiedLinesHashes, modifiedLines);
    const lineAlignmentResult = (() => {
      if (sequence1.length + sequence2.length < 1700) {
        return this.e.compute(sequence1, sequence2, timeout, (offset1, offset2) => originalLines[offset1] === modifiedLines[offset2] ? modifiedLines[offset2].length === 0 ? 0.1 : 1 + Math.log(1 + modifiedLines[offset2].length) : 0.99);
      }
      return this.f.compute(sequence1, sequence2, timeout);
    })();
    let lineAlignments = lineAlignmentResult.diffs;
    let hitTimeout = lineAlignmentResult.hitTimeout;
    lineAlignments = $r0(sequence1, sequence2, lineAlignments);
    lineAlignments = $u0(sequence1, sequence2, lineAlignments);
    const alignments = [];
    const scanForWhitespaceChanges = (equalLinesCount) => {
      if (!considerWhitespaceChanges) {
        return;
      }
      for (let i2 = 0; i2 < equalLinesCount; i2++) {
        const seq1Offset = seq1LastStart + i2;
        const seq2Offset = seq2LastStart + i2;
        if (originalLines[seq1Offset] !== modifiedLines[seq2Offset]) {
          const characterDiffs = this.h(originalLines, modifiedLines, new $f0(new $0C(seq1Offset, seq1Offset + 1), new $0C(seq2Offset, seq2Offset + 1)), timeout, considerWhitespaceChanges);
          for (const a of characterDiffs.mappings) {
            alignments.push(a);
          }
          if (characterDiffs.hitTimeout) {
            hitTimeout = true;
          }
        }
      }
    };
    let seq1LastStart = 0;
    let seq2LastStart = 0;
    for (const diff3 of lineAlignments) {
      $kd(() => diff3.seq1Range.start - seq1LastStart === diff3.seq2Range.start - seq2LastStart);
      const equalLinesCount = diff3.seq1Range.start - seq1LastStart;
      scanForWhitespaceChanges(equalLinesCount);
      seq1LastStart = diff3.seq1Range.endExclusive;
      seq2LastStart = diff3.seq2Range.endExclusive;
      const characterDiffs = this.h(originalLines, modifiedLines, diff3, timeout, considerWhitespaceChanges);
      if (characterDiffs.hitTimeout) {
        hitTimeout = true;
      }
      for (const a of characterDiffs.mappings) {
        alignments.push(a);
      }
    }
    scanForWhitespaceChanges(originalLines.length - seq1LastStart);
    const changes = $sD(alignments, new $mD(originalLines), new $mD(modifiedLines));
    let moves = [];
    if (options3.computeMoves) {
      moves = this.g(changes, originalLines, modifiedLines, originalLinesHashes, modifiedLinesHashes, timeout, considerWhitespaceChanges);
    }
    $kd(() => {
      function validatePosition(pos, lines) {
        if (pos.lineNumber < 1 || pos.lineNumber > lines.length) {
          return false;
        }
        const line = lines[pos.lineNumber - 1];
        if (pos.column < 1 || pos.column > line.length + 1) {
          return false;
        }
        return true;
      }
      function validateRange(range, lines) {
        if (range.startLineNumber < 1 || range.startLineNumber > lines.length + 1) {
          return false;
        }
        if (range.endLineNumberExclusive < 1 || range.endLineNumberExclusive > lines.length + 1) {
          return false;
        }
        return true;
      }
      for (const c of changes) {
        if (!c.innerChanges) {
          return false;
        }
        for (const ic of c.innerChanges) {
          const valid2 = validatePosition(ic.modifiedRange.getStartPosition(), modifiedLines) && validatePosition(ic.modifiedRange.getEndPosition(), modifiedLines) && validatePosition(ic.originalRange.getStartPosition(), originalLines) && validatePosition(ic.originalRange.getEndPosition(), originalLines);
          if (!valid2) {
            return false;
          }
        }
        if (!validateRange(c.modified, modifiedLines) || !validateRange(c.original, originalLines)) {
          return false;
        }
      }
      return true;
    });
    return new $vD(changes, moves, hitTimeout);
  }
  g(changes, originalLines, modifiedLines, hashedOriginalLines, hashedModifiedLines, timeout, considerWhitespaceChanges) {
    const moves = $p0(changes, originalLines, modifiedLines, hashedOriginalLines, hashedModifiedLines, timeout);
    const movesWithDiffs = moves.map((m) => {
      const moveChanges = this.h(originalLines, modifiedLines, new $f0(m.original.toOffsetRange(), m.modified.toOffsetRange()), timeout, considerWhitespaceChanges);
      const mappings = $sD(moveChanges.mappings, new $mD(originalLines), new $mD(modifiedLines), true);
      return new $wD(m, mappings);
    });
    return movesWithDiffs;
  }
  h(originalLines, modifiedLines, diff3, timeout, considerWhitespaceChanges) {
    const lineRangeMapping = toLineRangeMapping(diff3);
    const rangeMapping = lineRangeMapping.toRangeMapping2(originalLines, modifiedLines);
    const slice1 = new $o0(originalLines, rangeMapping.originalRange, considerWhitespaceChanges);
    const slice2 = new $o0(modifiedLines, rangeMapping.modifiedRange, considerWhitespaceChanges);
    const diffResult = slice1.length + slice2.length < 500 ? this.e.compute(slice1, slice2, timeout) : this.f.compute(slice1, slice2, timeout);
    const check = false;
    let diffs = diffResult.diffs;
    if (check) {
      $f0.assertSorted(diffs);
    }
    diffs = $r0(slice1, slice2, diffs);
    if (check) {
      $f0.assertSorted(diffs);
    }
    diffs = $t0(slice1, slice2, diffs);
    if (check) {
      $f0.assertSorted(diffs);
    }
    diffs = $s0(slice1, slice2, diffs);
    if (check) {
      $f0.assertSorted(diffs);
    }
    diffs = $v0(slice1, slice2, diffs);
    if (check) {
      $f0.assertSorted(diffs);
    }
    const result = diffs.map((d) => new $rD(slice1.translateRange(d.seq1Range), slice2.translateRange(d.seq2Range)));
    if (check) {
      $rD.assertSorted(result);
    }
    return {
      mappings: result,
      hitTimeout: diffResult.hitTimeout
    };
  }
};
function toLineRangeMapping(sequenceDiff) {
  return new $pD(new $_C(sequenceDiff.seq1Range.start + 1, sequenceDiff.seq1Range.endExclusive + 1), new $_C(sequenceDiff.seq2Range.start + 1, sequenceDiff.seq2Range.endExclusive + 1));
}

// out-build/vs/editor/browser/widget/diffEditor/diffEditorViewModel.js
var $b$ = class $b$2 extends $3c {
  setActiveMovedText(movedText) {
    this.t.set(movedText, void 0);
  }
  setHoveredMovedText(movedText) {
    this.u.set(movedText, void 0);
  }
  constructor(model, z, C) {
    super();
    this.model = model;
    this.z = z;
    this.C = C;
    this.g = $he(this, false);
    this.isDiffUpToDate = this.g;
    this.j = $he(this, void 0);
    this.diff = this.j;
    this.n = $he(this, void 0);
    this.unchangedRegions = $2d(this, (r2) => {
      if (this.z.hideUnchangedRegions.read(r2)) {
        return this.n.read(r2)?.regions ?? [];
      } else {
        $ce((tx) => {
          for (const r3 of this.n.get()?.regions || []) {
            r3.collapseAll(tx);
          }
        });
        return [];
      }
    });
    this.movedTextToCompare = $he(this, void 0);
    this.t = $he(this, void 0);
    this.u = $he(this, void 0);
    this.activeMovedText = $2d(this, (r2) => this.movedTextToCompare.read(r2) ?? this.u.read(r2) ?? this.t.read(r2));
    this.w = new $ad();
    this.y = $2d(this, (reader) => {
      const diffProvider = this.C.createDiffProvider({
        diffAlgorithm: this.z.diffAlgorithm.read(reader)
      });
      const onChangeSignal = $Gd("onDidChange", diffProvider.onDidChange);
      return {
        diffProvider,
        onChangeSignal
      };
    });
    this.B($1c(() => this.w.cancel()));
    const contentChangedSignal = $Hd("contentChangedSignal");
    const debouncer = this.B(new $8h(() => contentChangedSignal.trigger(void 0), 200));
    this.B($td((reader) => {
      const lastUnchangedRegions = this.n.read(reader);
      if (!lastUnchangedRegions || lastUnchangedRegions.regions.some((r2) => r2.isDragged.read(reader))) {
        return;
      }
      const lastUnchangedRegionsOrigRanges = lastUnchangedRegions.originalDecorationIds.map((id2) => model.original.getDecorationRange(id2)).map((r2) => r2 ? $_C.fromRangeInclusive(r2) : void 0);
      const lastUnchangedRegionsModRanges = lastUnchangedRegions.modifiedDecorationIds.map((id2) => model.modified.getDecorationRange(id2)).map((r2) => r2 ? $_C.fromRangeInclusive(r2) : void 0);
      const updatedLastUnchangedRegions = lastUnchangedRegions.regions.map((r2, idx) => !lastUnchangedRegionsOrigRanges[idx] || !lastUnchangedRegionsModRanges[idx] ? void 0 : new $e$(lastUnchangedRegionsOrigRanges[idx].startLineNumber, lastUnchangedRegionsModRanges[idx].startLineNumber, lastUnchangedRegionsOrigRanges[idx].length, r2.visibleLineCountTop.read(reader), r2.visibleLineCountBottom.read(reader))).filter($Hg);
      const newRanges = [];
      let didChange = false;
      for (const touching of $Fb(updatedLastUnchangedRegions, (a, b) => a.getHiddenModifiedRange(reader).endLineNumberExclusive === b.getHiddenModifiedRange(reader).startLineNumber)) {
        if (touching.length > 1) {
          didChange = true;
          const sumLineCount = touching.reduce((sum, r3) => sum + r3.lineCount, 0);
          const r2 = new $e$(touching[0].originalLineNumber, touching[0].modifiedLineNumber, sumLineCount, touching[0].visibleLineCountTop.get(), touching[touching.length - 1].visibleLineCountBottom.get());
          newRanges.push(r2);
        } else {
          newRanges.push(touching[0]);
        }
      }
      if (didChange) {
        const originalDecorationIds = model.original.deltaDecorations(lastUnchangedRegions.originalDecorationIds, newRanges.map((r2) => ({ range: r2.originalUnchangedRange.toInclusiveRange(), options: { description: "unchanged" } })));
        const modifiedDecorationIds = model.modified.deltaDecorations(lastUnchangedRegions.modifiedDecorationIds, newRanges.map((r2) => ({ range: r2.modifiedUnchangedRange.toInclusiveRange(), options: { description: "unchanged" } })));
        $ce((tx) => {
          this.n.set({
            regions: newRanges,
            originalDecorationIds,
            modifiedDecorationIds
          }, tx);
        });
      }
    }));
    const updateUnchangedRegions = (result, tx, reader) => {
      const newUnchangedRegions = $e$.fromDiffs(result.changes, model.original.getLineCount(), model.modified.getLineCount(), this.z.hideUnchangedRegionsMinimumLineCount.read(reader), this.z.hideUnchangedRegionsContextLineCount.read(reader));
      let visibleRegions = void 0;
      const lastUnchangedRegions = this.n.get();
      if (lastUnchangedRegions) {
        const lastUnchangedRegionsOrigRanges = lastUnchangedRegions.originalDecorationIds.map((id2) => model.original.getDecorationRange(id2)).map((r2) => r2 ? $_C.fromRangeInclusive(r2) : void 0);
        const lastUnchangedRegionsModRanges = lastUnchangedRegions.modifiedDecorationIds.map((id2) => model.modified.getDecorationRange(id2)).map((r2) => r2 ? $_C.fromRangeInclusive(r2) : void 0);
        const updatedLastUnchangedRegions = $59(lastUnchangedRegions.regions.map((r2, idx) => {
          if (!lastUnchangedRegionsOrigRanges[idx] || !lastUnchangedRegionsModRanges[idx]) {
            return void 0;
          }
          const length = lastUnchangedRegionsOrigRanges[idx].length;
          return new $e$(
            lastUnchangedRegionsOrigRanges[idx].startLineNumber,
            lastUnchangedRegionsModRanges[idx].startLineNumber,
            length,
            // The visible area can shrink by edits -> we have to account for this
            Math.min(r2.visibleLineCountTop.get(), length),
            Math.min(r2.visibleLineCountBottom.get(), length - r2.visibleLineCountTop.get())
          );
        }).filter($Hg), (cur, prev) => !prev || cur.modifiedLineNumber >= prev.modifiedLineNumber + prev.lineCount && cur.originalLineNumber >= prev.originalLineNumber + prev.lineCount);
        let hiddenRegions = updatedLastUnchangedRegions.map((r2) => new $pD(r2.getHiddenOriginalRange(reader), r2.getHiddenModifiedRange(reader)));
        hiddenRegions = $pD.clip(hiddenRegions, $_C.ofLength(1, model.original.getLineCount()), $_C.ofLength(1, model.modified.getLineCount()));
        visibleRegions = $pD.inverse(hiddenRegions, model.original.getLineCount(), model.modified.getLineCount());
      }
      const newUnchangedRegions2 = [];
      if (visibleRegions) {
        for (const r2 of newUnchangedRegions) {
          const intersecting = visibleRegions.filter((f) => f.original.intersectsStrict(r2.originalUnchangedRange) && f.modified.intersectsStrict(r2.modifiedUnchangedRange));
          newUnchangedRegions2.push(...r2.setVisibleRanges(intersecting, tx));
        }
      } else {
        newUnchangedRegions2.push(...newUnchangedRegions);
      }
      const originalDecorationIds = model.original.deltaDecorations(lastUnchangedRegions?.originalDecorationIds || [], newUnchangedRegions2.map((r2) => ({ range: r2.originalUnchangedRange.toInclusiveRange(), options: { description: "unchanged" } })));
      const modifiedDecorationIds = model.modified.deltaDecorations(lastUnchangedRegions?.modifiedDecorationIds || [], newUnchangedRegions2.map((r2) => ({ range: r2.modifiedUnchangedRange.toInclusiveRange(), options: { description: "unchanged" } })));
      this.n.set({
        regions: newUnchangedRegions2,
        originalDecorationIds,
        modifiedDecorationIds
      }, tx);
    };
    this.B(model.modified.onDidChangeContent((e) => {
      const diff3 = this.j.get();
      if (diff3) {
        const textEdits = $CG.fromModelContentChanges(e.changes);
        const result = applyModifiedEdits(this.h, textEdits, model.original, model.modified);
        if (result) {
          this.h = result;
          $ce((tx) => {
            this.j.set($c$.fromDiffResult(this.h), tx);
            updateUnchangedRegions(result, tx);
            const currentSyncedMovedText = this.movedTextToCompare.get();
            this.movedTextToCompare.set(currentSyncedMovedText ? this.h.moves.find((m) => m.lineRangeMapping.modified.intersect(currentSyncedMovedText.lineRangeMapping.modified)) : void 0, tx);
          });
        }
      }
      this.g.set(false, void 0);
      debouncer.schedule();
    }));
    this.B(model.original.onDidChangeContent((e) => {
      const diff3 = this.j.get();
      if (diff3) {
        const textEdits = $CG.fromModelContentChanges(e.changes);
        const result = applyOriginalEdits(this.h, textEdits, model.original, model.modified);
        if (result) {
          this.h = result;
          $ce((tx) => {
            this.j.set($c$.fromDiffResult(this.h), tx);
            updateUnchangedRegions(result, tx);
            const currentSyncedMovedText = this.movedTextToCompare.get();
            this.movedTextToCompare.set(currentSyncedMovedText ? this.h.moves.find((m) => m.lineRangeMapping.modified.intersect(currentSyncedMovedText.lineRangeMapping.modified)) : void 0, tx);
          });
        }
      }
      this.g.set(false, void 0);
      debouncer.schedule();
    }));
    this.B($xd(async (reader, store) => {
      this.z.hideUnchangedRegionsMinimumLineCount.read(reader);
      this.z.hideUnchangedRegionsContextLineCount.read(reader);
      debouncer.cancel();
      contentChangedSignal.read(reader);
      const documentDiffProvider = this.y.read(reader);
      documentDiffProvider.onChangeSignal.read(reader);
      $N3($w0, reader);
      $N3($r0, reader);
      this.g.set(false, void 0);
      let originalTextEditInfos = [];
      store.add(model.original.onDidChangeContent((e) => {
        const edits = $CG.fromModelContentChanges(e.changes);
        originalTextEditInfos = $IG(originalTextEditInfos, edits);
      }));
      let modifiedTextEditInfos = [];
      store.add(model.modified.onDidChangeContent((e) => {
        const edits = $CG.fromModelContentChanges(e.changes);
        modifiedTextEditInfos = $IG(modifiedTextEditInfos, edits);
      }));
      let result = await documentDiffProvider.diffProvider.computeDiff(model.original, model.modified, {
        ignoreTrimWhitespace: this.z.ignoreTrimWhitespace.read(reader),
        maxComputationTimeMs: this.z.maxComputationTimeMs.read(reader),
        computeMoves: this.z.showMoves.read(reader)
      }, this.w.token);
      if (this.w.token.isCancellationRequested) {
        return;
      }
      if (model.original.isDisposed() || model.modified.isDisposed()) {
        return;
      }
      result = normalizeDocumentDiff(result, model.original, model.modified);
      result = applyOriginalEdits(result, originalTextEditInfos, model.original, model.modified) ?? result;
      result = applyModifiedEdits(result, modifiedTextEditInfos, model.original, model.modified) ?? result;
      $ce((tx) => {
        updateUnchangedRegions(result, tx);
        this.h = result;
        const state = $c$.fromDiffResult(result);
        this.j.set(state, tx);
        this.g.set(true, tx);
        const currentSyncedMovedText = this.movedTextToCompare.get();
        this.movedTextToCompare.set(currentSyncedMovedText ? this.h.moves.find((m) => m.lineRangeMapping.modified.intersect(currentSyncedMovedText.lineRangeMapping.modified)) : void 0, tx);
      });
    }));
  }
  ensureModifiedLineIsVisible(lineNumber, preference, tx) {
    if (this.diff.get()?.mappings.length === 0) {
      return;
    }
    const unchangedRegions = this.n.get()?.regions || [];
    for (const r2 of unchangedRegions) {
      if (r2.getHiddenModifiedRange(void 0).contains(lineNumber)) {
        r2.showModifiedLine(lineNumber, preference, tx);
        return;
      }
    }
  }
  ensureOriginalLineIsVisible(lineNumber, preference, tx) {
    if (this.diff.get()?.mappings.length === 0) {
      return;
    }
    const unchangedRegions = this.n.get()?.regions || [];
    for (const r2 of unchangedRegions) {
      if (r2.getHiddenOriginalRange(void 0).contains(lineNumber)) {
        r2.showOriginalLine(lineNumber, preference, tx);
        return;
      }
    }
  }
  async waitForDiff() {
    await $re(this.isDiffUpToDate, (s) => s);
  }
  serializeState() {
    const regions = this.n.get();
    return {
      collapsedRegions: regions?.regions.map((r2) => ({ range: r2.getHiddenModifiedRange(void 0).serialize() }))
    };
  }
  restoreSerializedState(state) {
    const ranges = state.collapsedRegions?.map((r2) => $_C.deserialize(r2.range));
    const regions = this.n.get();
    if (!regions || !ranges) {
      return;
    }
    $ce((tx) => {
      for (const r2 of regions.regions) {
        for (const range of ranges) {
          if (r2.modifiedUnchangedRange.intersect(range)) {
            r2.setHiddenModifiedRange(range, tx);
            break;
          }
        }
      }
    });
  }
};
$b$ = __decorate([
  __param(2, $J0)
], $b$);
function normalizeDocumentDiff(diff3, original, modified) {
  return {
    changes: diff3.changes.map((c) => new $qD(c.original, c.modified, c.innerChanges ? c.innerChanges.map((i2) => normalizeRangeMapping(i2, original, modified)) : void 0)),
    moves: diff3.moves,
    identical: diff3.identical,
    quitEarly: diff3.quitEarly
  };
}
function normalizeRangeMapping(rangeMapping, original, modified) {
  let originalRange = rangeMapping.originalRange;
  let modifiedRange = rangeMapping.modifiedRange;
  if (originalRange.startColumn === 1 && modifiedRange.startColumn === 1 && (originalRange.endColumn !== 1 || modifiedRange.endColumn !== 1) && originalRange.endColumn === original.getLineMaxColumn(originalRange.endLineNumber) && modifiedRange.endColumn === modified.getLineMaxColumn(modifiedRange.endLineNumber) && originalRange.endLineNumber < original.getLineCount() && modifiedRange.endLineNumber < modified.getLineCount()) {
    originalRange = originalRange.setEndPosition(originalRange.endLineNumber + 1, 1);
    modifiedRange = modifiedRange.setEndPosition(modifiedRange.endLineNumber + 1, 1);
  }
  return new $rD(originalRange, modifiedRange);
}
var $c$ = class _$c$ {
  static fromDiffResult(result) {
    return new _$c$(result.changes.map((c) => new $d$(c)), result.moves || [], result.identical, result.quitEarly);
  }
  constructor(mappings, movedTexts, identical, quitEarly) {
    this.mappings = mappings;
    this.movedTexts = movedTexts;
    this.identical = identical;
    this.quitEarly = quitEarly;
  }
};
var $d$ = class {
  constructor(lineRangeMapping) {
    this.lineRangeMapping = lineRangeMapping;
  }
};
var $e$ = class _$e$ {
  static fromDiffs(changes, originalLineCount, modifiedLineCount, minHiddenLineCount, minContext) {
    const inversedMappings = $qD.inverse(changes, originalLineCount, modifiedLineCount);
    const result = [];
    for (const mapping2 of inversedMappings) {
      let origStart = mapping2.original.startLineNumber;
      let modStart = mapping2.modified.startLineNumber;
      let length = mapping2.original.length;
      const atStart = origStart === 1 && modStart === 1;
      const atEnd = origStart + length === originalLineCount + 1 && modStart + length === modifiedLineCount + 1;
      if ((atStart || atEnd) && length >= minContext + minHiddenLineCount) {
        if (atStart && !atEnd) {
          length -= minContext;
        }
        if (atEnd && !atStart) {
          origStart += minContext;
          modStart += minContext;
          length -= minContext;
        }
        result.push(new _$e$(origStart, modStart, length, 0, 0));
      } else if (length >= minContext * 2 + minHiddenLineCount) {
        origStart += minContext;
        modStart += minContext;
        length -= minContext * 2;
        result.push(new _$e$(origStart, modStart, length, 0, 0));
      }
    }
    return result;
  }
  get originalUnchangedRange() {
    return $_C.ofLength(this.originalLineNumber, this.lineCount);
  }
  get modifiedUnchangedRange() {
    return $_C.ofLength(this.modifiedLineNumber, this.lineCount);
  }
  constructor(originalLineNumber, modifiedLineNumber, lineCount, visibleLineCountTop, visibleLineCountBottom) {
    this.originalLineNumber = originalLineNumber;
    this.modifiedLineNumber = modifiedLineNumber;
    this.lineCount = lineCount;
    this.d = $he(this, 0);
    this.visibleLineCountTop = this.d;
    this.g = $he(this, 0);
    this.visibleLineCountBottom = this.g;
    this.h = $2d(this, (reader) => (
      /** @description isVisible */
      this.visibleLineCountTop.read(reader) + this.visibleLineCountBottom.read(reader) === this.lineCount && !this.isDragged.read(reader)
    ));
    this.isDragged = $he(this, void 0);
    const visibleLineCountTop2 = Math.max(Math.min(visibleLineCountTop, this.lineCount), 0);
    const visibleLineCountBottom2 = Math.max(Math.min(visibleLineCountBottom, this.lineCount - visibleLineCountTop), 0);
    $jd(visibleLineCountTop === visibleLineCountTop2);
    $jd(visibleLineCountBottom === visibleLineCountBottom2);
    this.d.set(visibleLineCountTop2, void 0);
    this.g.set(visibleLineCountBottom2, void 0);
  }
  setVisibleRanges(visibleRanges, tx) {
    const result = [];
    const hiddenModified = new $aD(visibleRanges.map((r2) => r2.modified)).subtractFrom(this.modifiedUnchangedRange);
    let originalStartLineNumber = this.originalLineNumber;
    let modifiedStartLineNumber = this.modifiedLineNumber;
    const modifiedEndLineNumberEx = this.modifiedLineNumber + this.lineCount;
    if (hiddenModified.ranges.length === 0) {
      this.showAll(tx);
      result.push(this);
    } else {
      let i2 = 0;
      for (const r2 of hiddenModified.ranges) {
        const isLast = i2 === hiddenModified.ranges.length - 1;
        i2++;
        const length = (isLast ? modifiedEndLineNumberEx : r2.endLineNumberExclusive) - modifiedStartLineNumber;
        const newR = new _$e$(originalStartLineNumber, modifiedStartLineNumber, length, 0, 0);
        newR.setHiddenModifiedRange(r2, tx);
        result.push(newR);
        originalStartLineNumber = newR.originalUnchangedRange.endLineNumberExclusive;
        modifiedStartLineNumber = newR.modifiedUnchangedRange.endLineNumberExclusive;
      }
    }
    return result;
  }
  shouldHideControls(reader) {
    return this.h.read(reader);
  }
  getHiddenOriginalRange(reader) {
    return $_C.ofLength(this.originalLineNumber + this.d.read(reader), this.lineCount - this.d.read(reader) - this.g.read(reader));
  }
  getHiddenModifiedRange(reader) {
    return $_C.ofLength(this.modifiedLineNumber + this.d.read(reader), this.lineCount - this.d.read(reader) - this.g.read(reader));
  }
  setHiddenModifiedRange(range, tx) {
    const visibleLineCountTop = range.startLineNumber - this.modifiedLineNumber;
    const visibleLineCountBottom = this.modifiedLineNumber + this.lineCount - range.endLineNumberExclusive;
    this.setState(visibleLineCountTop, visibleLineCountBottom, tx);
  }
  getMaxVisibleLineCountTop() {
    return this.lineCount - this.g.get();
  }
  getMaxVisibleLineCountBottom() {
    return this.lineCount - this.d.get();
  }
  showMoreAbove(count = 10, tx) {
    const maxVisibleLineCountTop = this.getMaxVisibleLineCountTop();
    this.d.set(Math.min(this.d.get() + count, maxVisibleLineCountTop), tx);
  }
  showMoreBelow(count = 10, tx) {
    const maxVisibleLineCountBottom = this.lineCount - this.d.get();
    this.g.set(Math.min(this.g.get() + count, maxVisibleLineCountBottom), tx);
  }
  showAll(tx) {
    this.g.set(this.lineCount - this.d.get(), tx);
  }
  showModifiedLine(lineNumber, preference, tx) {
    const top2 = lineNumber + 1 - (this.modifiedLineNumber + this.d.get());
    const bottom = this.modifiedLineNumber - this.g.get() + this.lineCount - lineNumber;
    if (preference === 0 && top2 < bottom || preference === 1) {
      this.d.set(this.d.get() + top2, tx);
    } else {
      this.g.set(this.g.get() + bottom, tx);
    }
  }
  showOriginalLine(lineNumber, preference, tx) {
    const top2 = lineNumber - this.originalLineNumber;
    const bottom = this.originalLineNumber + this.lineCount - lineNumber;
    if (preference === 0 && top2 < bottom || preference === 1) {
      this.d.set(Math.min(this.d.get() + bottom - top2, this.getMaxVisibleLineCountTop()), tx);
    } else {
      this.g.set(Math.min(this.g.get() + top2 - bottom, this.getMaxVisibleLineCountBottom()), tx);
    }
  }
  collapseAll(tx) {
    this.d.set(0, tx);
    this.g.set(0, tx);
  }
  setState(visibleLineCountTop, visibleLineCountBottom, tx) {
    visibleLineCountTop = Math.max(Math.min(visibleLineCountTop, this.lineCount), 0);
    visibleLineCountBottom = Math.max(Math.min(visibleLineCountBottom, this.lineCount - visibleLineCountTop), 0);
    this.d.set(visibleLineCountTop, tx);
    this.g.set(visibleLineCountBottom, tx);
  }
};
var RevealPreference;
(function(RevealPreference2) {
  RevealPreference2[RevealPreference2["FromCloserSide"] = 0] = "FromCloserSide";
  RevealPreference2[RevealPreference2["FromTop"] = 1] = "FromTop";
  RevealPreference2[RevealPreference2["FromBottom"] = 2] = "FromBottom";
})(RevealPreference || (RevealPreference = {}));
function applyOriginalEdits(diff3, textEdits, originalTextModel, modifiedTextModel) {
  return void 0;
}
function applyModifiedEdits(diff3, textEdits, originalTextModel, modifiedTextModel) {
  return void 0;
}

// out-build/vs/editor/browser/widget/diffEditor/components/diffEditorViewZones/inlineDiffDeletedCodeMargin.js
var $60 = class extends $3c {
  get visibility() {
    return this.b;
  }
  set visibility(_visibility) {
    if (this.b !== _visibility) {
      this.b = _visibility;
      this.a.style.visibility = _visibility ? "visible" : "hidden";
    }
  }
  constructor(c, f, g, h3, j, m, n, r2, s) {
    super();
    this.c = c;
    this.f = f;
    this.g = g;
    this.h = h3;
    this.j = j;
    this.m = m;
    this.n = n;
    this.r = r2;
    this.s = s;
    this.b = false;
    this.f.style.zIndex = "10";
    this.a = document.createElement("div");
    this.a.className = ThemeIcon.asClassName($6l.lightBulb) + " lightbulb-glyph";
    this.a.style.position = "absolute";
    const lineHeight = this.g.getOption(
      68
      /* EditorOption.lineHeight */
    );
    this.a.style.right = "0px";
    this.a.style.visibility = "hidden";
    this.a.style.height = `${lineHeight}px`;
    this.a.style.lineHeight = `${lineHeight}px`;
    this.f.appendChild(this.a);
    let currentLineNumberOffset = 0;
    const useShadowDOM = g.getOption(
      132
      /* EditorOption.useShadowDOM */
    ) && !$u;
    const showContextMenu = (x, y) => {
      this.r.showContextMenu({
        domForShadowRoot: useShadowDOM ? g.getDomNode() ?? void 0 : void 0,
        getAnchor: () => ({ x, y }),
        getActions: () => {
          const actions = [];
          const isDeletion2 = h3.modified.isEmpty;
          actions.push(new $Um("diff.clipboard.copyDeletedContent", isDeletion2 ? h3.original.length > 1 ? localize(223, null) : localize(224, null) : h3.original.length > 1 ? localize(225, null) : localize(226, null), void 0, true, async () => {
            const originalText = this.n.getValueInRange(h3.original.toExclusiveRange());
            await this.s.writeText(originalText);
          }));
          if (h3.original.length > 1) {
            actions.push(new $Um("diff.clipboard.copyDeletedLineContent", isDeletion2 ? localize(227, null, h3.original.startLineNumber + currentLineNumberOffset) : localize(228, null, h3.original.startLineNumber + currentLineNumberOffset), void 0, true, async () => {
              let lineContent = this.n.getLineContent(h3.original.startLineNumber + currentLineNumberOffset);
              if (lineContent === "") {
                const eof = this.n.getEndOfLineSequence();
                lineContent = eof === 0 ? "\n" : "\r\n";
              }
              await this.s.writeText(lineContent);
            }));
          }
          const readOnly = g.getOption(
            96
            /* EditorOption.readOnly */
          );
          if (!readOnly) {
            actions.push(new $Um("diff.inline.revertChange", localize(229, null), void 0, true, async () => {
              this.j.revert(this.h);
            }));
          }
          return actions;
        },
        autoSelectFirstItem: true
      });
    };
    this.B($aj(this.a, "mousedown", (e) => {
      if (!e.leftButton) {
        return;
      }
      const { top: top2, height } = $vj(this.a);
      const pad = Math.floor(lineHeight / 3);
      e.preventDefault();
      showContextMenu(e.posx, top2 + height + pad);
    }));
    this.B(g.onMouseMove((e) => {
      if ((e.target.type === 8 || e.target.type === 5) && e.target.detail.viewZoneId === this.c()) {
        currentLineNumberOffset = this.t(this.f, e.event.browserEvent.y, lineHeight);
        this.visibility = true;
      } else {
        this.visibility = false;
      }
    }));
    this.B(g.onMouseDown((e) => {
      if (!e.event.leftButton) {
        return;
      }
      if (e.target.type === 8 || e.target.type === 5) {
        const viewZoneId = e.target.detail.viewZoneId;
        if (viewZoneId === this.c()) {
          e.event.preventDefault();
          currentLineNumberOffset = this.t(this.f, e.event.browserEvent.y, lineHeight);
          showContextMenu(e.event.posx, e.event.posy + lineHeight);
        }
      }
    }));
  }
  t(marginDomNode, y, lineHeight) {
    const { top: top2 } = $vj(marginDomNode);
    const offset = y - top2;
    const lineNumberOffset = Math.floor(offset / lineHeight);
    const newTop = lineNumberOffset * lineHeight;
    this.a.style.top = `${newTop}px`;
    if (this.m) {
      let acc = 0;
      for (let i2 = 0; i2 < this.m.length; i2++) {
        acc += this.m[i2];
        if (lineNumberOffset < acc) {
          return i2;
        }
      }
    }
    return lineNumberOffset;
  }
};

// out-build/vs/editor/browser/widget/diffEditor/components/diffEditorViewZones/renderLines.js
var ttPolicy2 = $W1("diffEditorWidget", { createHTML: (value) => value });
function $70(source, options3, decorations, domNode) {
  $24(domNode, options3.fontInfo);
  const hasCharChanges = decorations.length > 0;
  const sb = new $cE(1e4);
  let maxCharsPerLine = 0;
  let renderedLineCount = 0;
  const viewLineCounts = [];
  for (let lineIndex = 0; lineIndex < source.lineTokens.length; lineIndex++) {
    const lineNumber = lineIndex + 1;
    const lineTokens = source.lineTokens[lineIndex];
    const lineBreakData = source.lineBreakData[lineIndex];
    const actualDecorations = $m7.filter(decorations, lineNumber, 1, Number.MAX_SAFE_INTEGER);
    if (lineBreakData) {
      let lastBreakOffset = 0;
      for (const breakOffset of lineBreakData.breakOffsets) {
        const viewLineTokens = lineTokens.sliceAndInflate(lastBreakOffset, breakOffset, 0);
        maxCharsPerLine = Math.max(maxCharsPerLine, renderOriginalLine(renderedLineCount, viewLineTokens, $m7.extractWrapped(actualDecorations, lastBreakOffset, breakOffset), hasCharChanges, source.mightContainNonBasicASCII, source.mightContainRTL, options3, sb));
        renderedLineCount++;
        lastBreakOffset = breakOffset;
      }
      viewLineCounts.push(lineBreakData.breakOffsets.length);
    } else {
      viewLineCounts.push(1);
      maxCharsPerLine = Math.max(maxCharsPerLine, renderOriginalLine(renderedLineCount, lineTokens, actualDecorations, hasCharChanges, source.mightContainNonBasicASCII, source.mightContainRTL, options3, sb));
      renderedLineCount++;
    }
  }
  maxCharsPerLine += options3.scrollBeyondLastColumn;
  const html3 = sb.build();
  const trustedhtml = ttPolicy2 ? ttPolicy2.createHTML(html3) : html3;
  domNode.innerHTML = trustedhtml;
  const minWidthInPx = maxCharsPerLine * options3.typicalHalfwidthCharacterWidth;
  return {
    heightInLines: renderedLineCount,
    minWidthInPx,
    viewLineCounts
  };
}
var $80 = class {
  constructor(lineTokens, lineBreakData = lineTokens.map((t) => null), mightContainNonBasicASCII = true, mightContainRTL = true) {
    this.lineTokens = lineTokens;
    this.lineBreakData = lineBreakData;
    this.mightContainNonBasicASCII = mightContainNonBasicASCII;
    this.mightContainRTL = mightContainRTL;
  }
};
var $90 = class _$90 {
  static fromEditor(editor) {
    const modifiedEditorOptions = editor.getOptions();
    const fontInfo = modifiedEditorOptions.get(
      52
      /* EditorOption.fontInfo */
    );
    const layoutInfo = modifiedEditorOptions.get(
      151
      /* EditorOption.layoutInfo */
    );
    return new _$90(editor.getModel()?.getOptions().tabSize || 0, fontInfo, modifiedEditorOptions.get(
      33
      /* EditorOption.disableMonospaceOptimizations */
    ), fontInfo.typicalHalfwidthCharacterWidth, modifiedEditorOptions.get(
      109
      /* EditorOption.scrollBeyondLastColumn */
    ), modifiedEditorOptions.get(
      68
      /* EditorOption.lineHeight */
    ), layoutInfo.decorationsWidth, modifiedEditorOptions.get(
      122
      /* EditorOption.stopRenderingLineAfter */
    ), modifiedEditorOptions.get(
      104
      /* EditorOption.renderWhitespace */
    ), modifiedEditorOptions.get(
      99
      /* EditorOption.renderControlCharacters */
    ), modifiedEditorOptions.get(
      53
      /* EditorOption.fontLigatures */
    ));
  }
  constructor(tabSize, fontInfo, disableMonospaceOptimizations, typicalHalfwidthCharacterWidth, scrollBeyondLastColumn, lineHeight, lineDecorationsWidth, stopRenderingLineAfter, renderWhitespace, renderControlCharacters, fontLigatures) {
    this.tabSize = tabSize;
    this.fontInfo = fontInfo;
    this.disableMonospaceOptimizations = disableMonospaceOptimizations;
    this.typicalHalfwidthCharacterWidth = typicalHalfwidthCharacterWidth;
    this.scrollBeyondLastColumn = scrollBeyondLastColumn;
    this.lineHeight = lineHeight;
    this.lineDecorationsWidth = lineDecorationsWidth;
    this.stopRenderingLineAfter = stopRenderingLineAfter;
    this.renderWhitespace = renderWhitespace;
    this.renderControlCharacters = renderControlCharacters;
    this.fontLigatures = fontLigatures;
  }
};
function renderOriginalLine(viewLineIdx, lineTokens, decorations, hasCharChanges, mightContainNonBasicASCII, mightContainRTL, options3, sb) {
  sb.appendString('<div class="view-line');
  if (!hasCharChanges) {
    sb.appendString(" char-delete");
  }
  sb.appendString('" style="top:');
  sb.appendString(String(viewLineIdx * options3.lineHeight));
  sb.appendString('px;width:1000000px;">');
  const lineContent = lineTokens.getLineContent();
  const isBasicASCII = $H5.isBasicASCII(lineContent, mightContainNonBasicASCII);
  const containsRTL = $H5.containsRTL(lineContent, isBasicASCII, mightContainRTL);
  const output = $u7(new $q7(
    options3.fontInfo.isMonospace && !options3.disableMonospaceOptimizations,
    options3.fontInfo.canUseHalfwidthRightwardsArrow,
    lineContent,
    false,
    isBasicASCII,
    containsRTL,
    0,
    lineTokens,
    decorations,
    options3.tabSize,
    0,
    options3.fontInfo.spaceWidth,
    options3.fontInfo.middotWidth,
    options3.fontInfo.wsmiddotWidth,
    options3.stopRenderingLineAfter,
    options3.renderWhitespace,
    options3.renderControlCharacters,
    options3.fontLigatures !== EditorFontLigatures.OFF,
    null
    // Send no selections, original line cannot be selected
  ), sb);
  sb.appendString("</div>");
  return output.characterMapping.getHorizontalOffset(output.characterMapping.length);
}

// out-build/vs/platform/clipboard/common/clipboardService.js
var $30 = $Qk("clipboardService");

// out-build/vs/platform/contextview/browser/contextView.js
var $40 = $Qk("contextViewService");
var $50 = $Qk("contextMenuService");

// out-build/vs/editor/browser/widget/diffEditor/components/diffEditorViewZones/diffEditorViewZones.js
var $00 = class $002 extends $3c {
  constructor(u, y, z, C, D, F, G, H, I, J) {
    super();
    this.u = u;
    this.y = y;
    this.z = z;
    this.C = C;
    this.D = D;
    this.F = F;
    this.G = G;
    this.H = H;
    this.I = I;
    this.J = J;
    this.b = $he(this, 0);
    this.g = $he(this, 0);
    this.h = $V9(this.u, this.g, this.q);
    this.j = $he(this, 0);
    this.s = $he(this, 0);
    this.t = $V9(this.u, this.s, this.q);
    const state = $he("invalidateAlignmentsState", 0);
    const updateImmediately = this.B(new $8h(() => {
      state.set(state.get() + 1, void 0);
    }, 0));
    this.B(this.y.original.onDidChangeViewZones((_args) => {
      if (!this.F()) {
        updateImmediately.schedule();
      }
    }));
    this.B(this.y.modified.onDidChangeViewZones((_args) => {
      if (!this.F()) {
        updateImmediately.schedule();
      }
    }));
    this.B(this.y.original.onDidChangeConfiguration((args2) => {
      if (args2.hasChanged(
        152
        /* EditorOption.wrappingInfo */
      ) || args2.hasChanged(
        68
        /* EditorOption.lineHeight */
      )) {
        updateImmediately.schedule();
      }
    }));
    this.B(this.y.modified.onDidChangeConfiguration((args2) => {
      if (args2.hasChanged(
        152
        /* EditorOption.wrappingInfo */
      ) || args2.hasChanged(
        68
        /* EditorOption.lineHeight */
      )) {
        updateImmediately.schedule();
      }
    }));
    const originalModelTokenizationCompleted = this.z.map((m) => m ? $Dd(
      this,
      m.model.original.onDidChangeTokens,
      () => m.model.original.tokenization.backgroundTokenizationState === 2
      /* BackgroundTokenizationState.Completed */
    ) : void 0).map((m, reader) => m?.read(reader));
    const alignments = $2d((reader) => {
      const diffModel = this.z.read(reader);
      const diff3 = diffModel?.diff.read(reader);
      if (!diffModel || !diff3) {
        return null;
      }
      state.read(reader);
      const renderSideBySide = this.C.renderSideBySide.read(reader);
      const innerHunkAlignment = renderSideBySide;
      return computeRangeAlignment(this.y.original, this.y.modified, diff3.mappings, this.G, this.H, innerHunkAlignment);
    });
    const alignmentsSyncedMovedText = $2d((reader) => {
      const syncedMovedText = this.z.read(reader)?.movedTextToCompare.read(reader);
      if (!syncedMovedText) {
        return null;
      }
      state.read(reader);
      const mappings = syncedMovedText.changes.map((c) => new $d$(c));
      return computeRangeAlignment(this.y.original, this.y.modified, mappings, this.G, this.H, true);
    });
    function createFakeLinesDiv() {
      const r2 = document.createElement("div");
      r2.className = "diagonal-fill";
      return r2;
    }
    const alignmentViewZonesDisposables = this.B(new $2c());
    this.viewZones = $6d(this, (reader, store) => {
      alignmentViewZonesDisposables.clear();
      const alignmentsVal = alignments.read(reader) || [];
      const origViewZones = [];
      const modViewZones = [];
      const modifiedTopPaddingVal = this.j.read(reader);
      if (modifiedTopPaddingVal > 0) {
        modViewZones.push({
          afterLineNumber: 0,
          domNode: document.createElement("div"),
          heightInPx: modifiedTopPaddingVal,
          showInHiddenAreas: true,
          suppressMouseDown: true
        });
      }
      const originalTopPaddingVal = this.b.read(reader);
      if (originalTopPaddingVal > 0) {
        origViewZones.push({
          afterLineNumber: 0,
          domNode: document.createElement("div"),
          heightInPx: originalTopPaddingVal,
          showInHiddenAreas: true,
          suppressMouseDown: true
        });
      }
      const renderSideBySide = this.C.renderSideBySide.read(reader);
      const deletedCodeLineBreaksComputer = !renderSideBySide ? this.y.modified._getViewModel()?.createLineBreaksComputer() : void 0;
      if (deletedCodeLineBreaksComputer) {
        const originalModel = this.y.original.getModel();
        for (const a of alignmentsVal) {
          if (a.diff) {
            for (let i2 = a.originalRange.startLineNumber; i2 < a.originalRange.endLineNumberExclusive; i2++) {
              if (i2 > originalModel.getLineCount()) {
                return { orig: origViewZones, mod: modViewZones };
              }
              deletedCodeLineBreaksComputer?.addRequest(originalModel.getLineContent(i2), null, null);
            }
          }
        }
      }
      const lineBreakData = deletedCodeLineBreaksComputer?.finalize() ?? [];
      let lineBreakDataIdx = 0;
      const modLineHeight = this.y.modified.getOption(
        68
        /* EditorOption.lineHeight */
      );
      const syncedMovedText = this.z.read(reader)?.movedTextToCompare.read(reader);
      const mightContainNonBasicASCII = this.y.original.getModel()?.mightContainNonBasicASCII() ?? false;
      const mightContainRTL = this.y.original.getModel()?.mightContainRTL() ?? false;
      const renderOptions = $90.fromEditor(this.y.modified);
      for (const a of alignmentsVal) {
        if (a.diff && !renderSideBySide && (!this.C.useTrueInlineDiffRendering.read(reader) || !$$0(a.diff))) {
          if (!a.originalRange.isEmpty) {
            originalModelTokenizationCompleted.read(reader);
            const deletedCodeDomNode = document.createElement("div");
            deletedCodeDomNode.classList.add("view-lines", "line-delete", "monaco-mouse-cursor-text");
            const originalModel = this.y.original.getModel();
            if (a.originalRange.endLineNumberExclusive - 1 > originalModel.getLineCount()) {
              return { orig: origViewZones, mod: modViewZones };
            }
            const source = new $80(a.originalRange.mapToLineArray((l) => originalModel.tokenization.getLineTokens(l)), a.originalRange.mapToLineArray((_) => lineBreakData[lineBreakDataIdx++]), mightContainNonBasicASCII, mightContainRTL);
            const decorations = [];
            for (const i2 of a.diff.innerChanges || []) {
              decorations.push(new $I5(
                i2.originalRange.delta(-(a.diff.original.startLineNumber - 1)),
                $Z0.className,
                0
                /* InlineDecorationType.Regular */
              ));
            }
            const result = $70(source, renderOptions, decorations, deletedCodeDomNode);
            const marginDomNode2 = document.createElement("div");
            marginDomNode2.className = "inline-deleted-margin-view-zone";
            $24(marginDomNode2, renderOptions.fontInfo);
            if (this.C.renderIndicators.read(reader)) {
              for (let i2 = 0; i2 < result.heightInLines; i2++) {
                const marginElement = document.createElement("div");
                marginElement.className = `delete-sign ${ThemeIcon.asClassName($R0)}`;
                marginElement.setAttribute("style", `position:absolute;top:${i2 * modLineHeight}px;width:${renderOptions.lineDecorationsWidth}px;height:${modLineHeight}px;right:0;`);
                marginDomNode2.appendChild(marginElement);
              }
            }
            let zoneId = void 0;
            alignmentViewZonesDisposables.add(new $60(() => $Kg(zoneId), marginDomNode2, this.y.modified, a.diff, this.D, result.viewLineCounts, this.y.original.getModel(), this.J, this.I));
            for (let i2 = 0; i2 < result.viewLineCounts.length; i2++) {
              const count = result.viewLineCounts[i2];
              if (count > 1) {
                origViewZones.push({
                  afterLineNumber: a.originalRange.startLineNumber + i2,
                  domNode: createFakeLinesDiv(),
                  heightInPx: (count - 1) * modLineHeight,
                  showInHiddenAreas: true,
                  suppressMouseDown: true
                });
              }
            }
            modViewZones.push({
              afterLineNumber: a.modifiedRange.startLineNumber - 1,
              domNode: deletedCodeDomNode,
              heightInPx: result.heightInLines * modLineHeight,
              minWidthInPx: result.minWidthInPx,
              marginDomNode: marginDomNode2,
              setZoneId(id2) {
                zoneId = id2;
              },
              showInHiddenAreas: true,
              suppressMouseDown: true
            });
          }
          const marginDomNode = document.createElement("div");
          marginDomNode.className = "gutter-delete";
          origViewZones.push({
            afterLineNumber: a.originalRange.endLineNumberExclusive - 1,
            domNode: createFakeLinesDiv(),
            heightInPx: a.modifiedHeightInPx,
            marginDomNode,
            showInHiddenAreas: true,
            suppressMouseDown: true
          });
        } else {
          const delta = a.modifiedHeightInPx - a.originalHeightInPx;
          if (delta > 0) {
            if (syncedMovedText?.lineRangeMapping.original.delta(-1).deltaLength(2).contains(a.originalRange.endLineNumberExclusive - 1)) {
              continue;
            }
            origViewZones.push({
              afterLineNumber: a.originalRange.endLineNumberExclusive - 1,
              domNode: createFakeLinesDiv(),
              heightInPx: delta,
              showInHiddenAreas: true,
              suppressMouseDown: true
            });
          } else {
            let createViewZoneMarginArrow2 = function() {
              const arrow = document.createElement("div");
              arrow.className = "arrow-revert-change " + ThemeIcon.asClassName($6l.arrowRight);
              store.add($_i(arrow, "mousedown", (e) => e.stopPropagation()));
              store.add($_i(arrow, "click", (e) => {
                e.stopPropagation();
                D.revert(a.diff);
              }));
              return $("div", {}, arrow);
            };
            var createViewZoneMarginArrow = createViewZoneMarginArrow2;
            if (syncedMovedText?.lineRangeMapping.modified.delta(-1).deltaLength(2).contains(a.modifiedRange.endLineNumberExclusive - 1)) {
              continue;
            }
            let marginDomNode = void 0;
            if (a.diff && a.diff.modified.isEmpty && this.C.shouldRenderOldRevertArrows.read(reader)) {
              marginDomNode = createViewZoneMarginArrow2();
            }
            modViewZones.push({
              afterLineNumber: a.modifiedRange.endLineNumberExclusive - 1,
              domNode: createFakeLinesDiv(),
              heightInPx: -delta,
              marginDomNode,
              showInHiddenAreas: true,
              suppressMouseDown: true
            });
          }
        }
      }
      for (const a of alignmentsSyncedMovedText.read(reader) ?? []) {
        if (!syncedMovedText?.lineRangeMapping.original.intersect(a.originalRange) || !syncedMovedText?.lineRangeMapping.modified.intersect(a.modifiedRange)) {
          continue;
        }
        const delta = a.modifiedHeightInPx - a.originalHeightInPx;
        if (delta > 0) {
          origViewZones.push({
            afterLineNumber: a.originalRange.endLineNumberExclusive - 1,
            domNode: createFakeLinesDiv(),
            heightInPx: delta,
            showInHiddenAreas: true,
            suppressMouseDown: true
          });
        } else {
          modViewZones.push({
            afterLineNumber: a.modifiedRange.endLineNumberExclusive - 1,
            domNode: createFakeLinesDiv(),
            heightInPx: -delta,
            showInHiddenAreas: true,
            suppressMouseDown: true
          });
        }
      }
      return { orig: origViewZones, mod: modViewZones };
    });
    let ignoreChange = false;
    this.B(this.y.original.onDidScrollChange((e) => {
      if (e.scrollLeftChanged && !ignoreChange) {
        ignoreChange = true;
        this.y.modified.setScrollLeft(e.scrollLeft);
        ignoreChange = false;
      }
    }));
    this.B(this.y.modified.onDidScrollChange((e) => {
      if (e.scrollLeftChanged && !ignoreChange) {
        ignoreChange = true;
        this.y.original.setScrollLeft(e.scrollLeft);
        ignoreChange = false;
      }
    }));
    this.f = $Dd(this.y.original.onDidScrollChange, () => (
      /** @description original.getScrollTop */
      this.y.original.getScrollTop()
    ));
    this.n = $Dd(this.y.modified.onDidScrollChange, () => (
      /** @description modified.getScrollTop */
      this.y.modified.getScrollTop()
    ));
    this.B($td((reader) => {
      const newScrollTopModified = this.f.read(reader) - (this.h.get() - this.t.read(reader)) - (this.b.get() - this.j.read(reader));
      if (newScrollTopModified !== this.y.modified.getScrollTop()) {
        this.y.modified.setScrollTop(
          newScrollTopModified,
          1
          /* ScrollType.Immediate */
        );
      }
    }));
    this.B($td((reader) => {
      const newScrollTopOriginal = this.n.read(reader) - (this.t.get() - this.h.read(reader)) - (this.j.get() - this.b.read(reader));
      if (newScrollTopOriginal !== this.y.original.getScrollTop()) {
        this.y.original.setScrollTop(
          newScrollTopOriginal,
          1
          /* ScrollType.Immediate */
        );
      }
    }));
    this.B($td((reader) => {
      const m = this.z.read(reader)?.movedTextToCompare.read(reader);
      let deltaOrigToMod = 0;
      if (m) {
        const trueTopOriginal = this.y.original.getTopForLineNumber(m.lineRangeMapping.original.startLineNumber, true) - this.b.get();
        const trueTopModified = this.y.modified.getTopForLineNumber(m.lineRangeMapping.modified.startLineNumber, true) - this.j.get();
        deltaOrigToMod = trueTopModified - trueTopOriginal;
      }
      if (deltaOrigToMod > 0) {
        this.j.set(0, void 0);
        this.b.set(deltaOrigToMod, void 0);
      } else if (deltaOrigToMod < 0) {
        this.j.set(-deltaOrigToMod, void 0);
        this.b.set(0, void 0);
      } else {
        setTimeout(() => {
          this.j.set(0, void 0);
          this.b.set(0, void 0);
        }, 400);
      }
      if (this.y.modified.hasTextFocus()) {
        this.g.set(this.s.get() - deltaOrigToMod, void 0, true);
      } else {
        this.s.set(this.g.get() + deltaOrigToMod, void 0, true);
      }
    }));
  }
};
$00 = __decorate([
  __param(8, $30),
  __param(9, $50)
], $00);
function computeRangeAlignment(originalEditor, modifiedEditor, diffs, originalEditorAlignmentViewZones, modifiedEditorAlignmentViewZones, innerHunkAlignment) {
  const originalLineHeightOverrides = new $bc(getAdditionalLineHeights(originalEditor, originalEditorAlignmentViewZones));
  const modifiedLineHeightOverrides = new $bc(getAdditionalLineHeights(modifiedEditor, modifiedEditorAlignmentViewZones));
  const origLineHeight = originalEditor.getOption(
    68
    /* EditorOption.lineHeight */
  );
  const modLineHeight = modifiedEditor.getOption(
    68
    /* EditorOption.lineHeight */
  );
  const result = [];
  let lastOriginalLineNumber = 0;
  let lastModifiedLineNumber = 0;
  function handleAlignmentsOutsideOfDiffs(untilOriginalLineNumberExclusive, untilModifiedLineNumberExclusive) {
    while (true) {
      let origNext = originalLineHeightOverrides.peek();
      let modNext = modifiedLineHeightOverrides.peek();
      if (origNext && origNext.lineNumber >= untilOriginalLineNumberExclusive) {
        origNext = void 0;
      }
      if (modNext && modNext.lineNumber >= untilModifiedLineNumberExclusive) {
        modNext = void 0;
      }
      if (!origNext && !modNext) {
        break;
      }
      const distOrig = origNext ? origNext.lineNumber - lastOriginalLineNumber : Number.MAX_VALUE;
      const distNext = modNext ? modNext.lineNumber - lastModifiedLineNumber : Number.MAX_VALUE;
      if (distOrig < distNext) {
        originalLineHeightOverrides.dequeue();
        modNext = {
          lineNumber: origNext.lineNumber - lastOriginalLineNumber + lastModifiedLineNumber,
          heightInPx: 0
        };
      } else if (distOrig > distNext) {
        modifiedLineHeightOverrides.dequeue();
        origNext = {
          lineNumber: modNext.lineNumber - lastModifiedLineNumber + lastOriginalLineNumber,
          heightInPx: 0
        };
      } else {
        originalLineHeightOverrides.dequeue();
        modifiedLineHeightOverrides.dequeue();
      }
      result.push({
        originalRange: $_C.ofLength(origNext.lineNumber, 1),
        modifiedRange: $_C.ofLength(modNext.lineNumber, 1),
        originalHeightInPx: origLineHeight + origNext.heightInPx,
        modifiedHeightInPx: modLineHeight + modNext.heightInPx,
        diff: void 0
      });
    }
  }
  for (const m of diffs) {
    let emitAlignment2 = function(origLineNumberExclusive, modLineNumberExclusive, forceAlignment = false) {
      if (origLineNumberExclusive < lastOrigLineNumber || modLineNumberExclusive < lastModLineNumber) {
        return;
      }
      if (first) {
        first = false;
      } else if (!forceAlignment && (origLineNumberExclusive === lastOrigLineNumber || modLineNumberExclusive === lastModLineNumber)) {
        return;
      }
      const originalRange = new $_C(lastOrigLineNumber, origLineNumberExclusive);
      const modifiedRange = new $_C(lastModLineNumber, modLineNumberExclusive);
      if (originalRange.isEmpty && modifiedRange.isEmpty) {
        return;
      }
      const originalAdditionalHeight = originalLineHeightOverrides.takeWhile((v) => v.lineNumber < origLineNumberExclusive)?.reduce((p, c2) => p + c2.heightInPx, 0) ?? 0;
      const modifiedAdditionalHeight = modifiedLineHeightOverrides.takeWhile((v) => v.lineNumber < modLineNumberExclusive)?.reduce((p, c2) => p + c2.heightInPx, 0) ?? 0;
      result.push({
        originalRange,
        modifiedRange,
        originalHeightInPx: originalRange.length * origLineHeight + originalAdditionalHeight,
        modifiedHeightInPx: modifiedRange.length * modLineHeight + modifiedAdditionalHeight,
        diff: m.lineRangeMapping
      });
      lastOrigLineNumber = origLineNumberExclusive;
      lastModLineNumber = modLineNumberExclusive;
    };
    var emitAlignment = emitAlignment2;
    const c = m.lineRangeMapping;
    handleAlignmentsOutsideOfDiffs(c.original.startLineNumber, c.modified.startLineNumber);
    let first = true;
    let lastModLineNumber = c.modified.startLineNumber;
    let lastOrigLineNumber = c.original.startLineNumber;
    if (innerHunkAlignment) {
      for (const i2 of c.innerChanges || []) {
        if (i2.originalRange.startColumn > 1 && i2.modifiedRange.startColumn > 1) {
          emitAlignment2(i2.originalRange.startLineNumber, i2.modifiedRange.startLineNumber);
        }
        const originalModel = originalEditor.getModel();
        const maxColumn = i2.originalRange.endLineNumber <= originalModel.getLineCount() ? originalModel.getLineMaxColumn(i2.originalRange.endLineNumber) : Number.MAX_SAFE_INTEGER;
        if (i2.originalRange.endColumn < maxColumn) {
          emitAlignment2(i2.originalRange.endLineNumber, i2.modifiedRange.endLineNumber);
        }
      }
    }
    emitAlignment2(c.original.endLineNumberExclusive, c.modified.endLineNumberExclusive, true);
    lastOriginalLineNumber = c.original.endLineNumberExclusive;
    lastModifiedLineNumber = c.modified.endLineNumberExclusive;
  }
  handleAlignmentsOutsideOfDiffs(Number.MAX_VALUE, Number.MAX_VALUE);
  return result;
}
function getAdditionalLineHeights(editor, viewZonesToIgnore) {
  const viewZoneHeights = [];
  const wrappingZoneHeights = [];
  const hasWrapping = editor.getOption(
    152
    /* EditorOption.wrappingInfo */
  ).wrappingColumn !== -1;
  const coordinatesConverter = editor._getViewModel().coordinatesConverter;
  const editorLineHeight = editor.getOption(
    68
    /* EditorOption.lineHeight */
  );
  if (hasWrapping) {
    for (let i2 = 1; i2 <= editor.getModel().getLineCount(); i2++) {
      const lineCount = coordinatesConverter.getModelLineViewLineCount(i2);
      if (lineCount > 1) {
        wrappingZoneHeights.push({ lineNumber: i2, heightInPx: editorLineHeight * (lineCount - 1) });
      }
    }
  }
  for (const w of editor.getWhitespaces()) {
    if (viewZonesToIgnore.has(w.id)) {
      continue;
    }
    const modelLineNumber = w.afterLineNumber === 0 ? 0 : coordinatesConverter.convertViewPositionToModelPosition(new $8C(w.afterLineNumber, 1)).lineNumber;
    viewZoneHeights.push({ lineNumber: modelLineNumber, heightInPx: w.height });
  }
  const result = $Q9(viewZoneHeights, wrappingZoneHeights, (v) => v.lineNumber, (v1, v2) => ({ lineNumber: v1.lineNumber, heightInPx: v1.heightInPx + v2.heightInPx }));
  return result;
}
function $$0(mapping2) {
  if (!mapping2.innerChanges) {
    return false;
  }
  return mapping2.innerChanges.every((c) => $_0(c.modifiedRange) && $_0(c.originalRange) || c.originalRange.equalsRange(new $9C(1, 1, 1, 1)));
}
function $_0(range) {
  return range.startLineNumber === range.endLineNumber;
}

// out-build/vs/editor/browser/widget/diffEditor/features/movedBlocksLinesFeature.js
var $j$ = class _$j$ extends $3c {
  static {
    this.movedCodeBlockPadding = 4;
  }
  constructor(n, r2, s, t, u) {
    super();
    this.n = n;
    this.r = r2;
    this.s = s;
    this.t = t;
    this.u = u;
    this.c = $Dd(this, this.u.original.onDidScrollChange, () => this.u.original.getScrollTop());
    this.f = $Dd(this, this.u.modified.onDidScrollChange, () => this.u.modified.getScrollTop());
    this.j = $Gd("onDidChangeViewZones", this.u.modified.onDidChangeViewZones);
    this.width = $he(this, 0);
    this.w = $Gd("modified.onDidChangeViewZones", this.u.modified.onDidChangeViewZones);
    this.y = $Gd("original.onDidChangeViewZones", this.u.original.onDidChangeViewZones);
    this.C = $6d(this, (reader, store) => {
      this.a.replaceChildren();
      const model = this.r.read(reader);
      const moves = model?.diff.read(reader)?.movedTexts;
      if (!moves || moves.length === 0) {
        this.width.set(0, void 0);
        return;
      }
      this.j.read(reader);
      const infoOrig = this.s.read(reader);
      const infoMod = this.t.read(reader);
      if (!infoOrig || !infoMod) {
        this.width.set(0, void 0);
        return;
      }
      this.w.read(reader);
      this.y.read(reader);
      const lines = moves.map((move) => {
        function computeLineStart(range, editor) {
          const t1 = editor.getTopForLineNumber(range.startLineNumber, true);
          const t2 = editor.getTopForLineNumber(range.endLineNumberExclusive, true);
          return (t1 + t2) / 2;
        }
        const start = computeLineStart(move.lineRangeMapping.original, this.u.original);
        const startOffset = this.c.read(reader);
        const end = computeLineStart(move.lineRangeMapping.modified, this.u.modified);
        const endOffset = this.f.read(reader);
        const from = start - startOffset;
        const to = end - endOffset;
        const top2 = Math.min(start, end);
        const bottom = Math.max(start, end);
        return { range: new $0C(top2, bottom), from, to, fromWithoutScroll: start, toWithoutScroll: end, move };
      });
      lines.sort($0b($9b((l) => l.fromWithoutScroll > l.toWithoutScroll, $_b), $9b((l) => l.fromWithoutScroll > l.toWithoutScroll ? l.fromWithoutScroll : -l.toWithoutScroll, $$b)));
      const layout = LinesLayout.compute(lines.map((l) => l.range));
      const padding = 10;
      const lineAreaLeft = infoOrig.verticalScrollbarWidth;
      const lineAreaWidth = (layout.getTrackCount() - 1) * 10 + padding * 2;
      const width2 = lineAreaLeft + lineAreaWidth + (infoMod.contentLeft - _$j$.movedCodeBlockPadding);
      let idx = 0;
      for (const line of lines) {
        const track = layout.getTrack(idx);
        const verticalY = lineAreaLeft + padding + track * 10;
        const arrowHeight = 15;
        const arrowWidth = 15;
        const right = width2;
        const rectWidth = infoMod.glyphMarginWidth + infoMod.lineNumbersWidth;
        const rectHeight = 18;
        const rect = document.createElementNS("http://www.w3.org/2000/svg", "rect");
        rect.classList.add("arrow-rectangle");
        rect.setAttribute("x", `${right - rectWidth}`);
        rect.setAttribute("y", `${line.to - rectHeight / 2}`);
        rect.setAttribute("width", `${rectWidth}`);
        rect.setAttribute("height", `${rectHeight}`);
        this.a.appendChild(rect);
        const g = document.createElementNS("http://www.w3.org/2000/svg", "g");
        const path = document.createElementNS("http://www.w3.org/2000/svg", "path");
        path.setAttribute("d", `M ${0} ${line.from} L ${verticalY} ${line.from} L ${verticalY} ${line.to} L ${right - arrowWidth} ${line.to}`);
        path.setAttribute("fill", "none");
        g.appendChild(path);
        const arrowRight = document.createElementNS("http://www.w3.org/2000/svg", "polygon");
        arrowRight.classList.add("arrow");
        store.add($td((reader2) => {
          path.classList.toggle("currentMove", line.move === model.activeMovedText.read(reader2));
          arrowRight.classList.toggle("currentMove", line.move === model.activeMovedText.read(reader2));
        }));
        arrowRight.setAttribute("points", `${right - arrowWidth},${line.to - arrowHeight / 2} ${right},${line.to} ${right - arrowWidth},${line.to + arrowHeight / 2}`);
        g.appendChild(arrowRight);
        this.a.appendChild(g);
        idx++;
      }
      this.width.set(lineAreaWidth, void 0);
    });
    this.a = document.createElementNS("http://www.w3.org/2000/svg", "svg");
    this.a.setAttribute("class", "moved-blocks-lines");
    this.n.appendChild(this.a);
    this.B($1c(() => this.a.remove()));
    this.B($td((reader) => {
      const info = this.s.read(reader);
      const info2 = this.t.read(reader);
      if (!info || !info2) {
        return;
      }
      this.a.style.left = `${info.width - info.verticalScrollbarWidth}px`;
      this.a.style.height = `${info.height}px`;
      this.a.style.width = `${info.verticalScrollbarWidth + info.contentLeft - _$j$.movedCodeBlockPadding + this.width.read(reader)}px`;
    }));
    this.B($Nd(this.C));
    const movedBlockViewZones = $2d((reader) => {
      const model = this.r.read(reader);
      const d = model?.diff.read(reader);
      if (!d) {
        return [];
      }
      return d.movedTexts.map((move) => ({
        move,
        original: new $Y9($Bd(move.lineRangeMapping.original.startLineNumber - 1), 18),
        modified: new $Y9($Bd(move.lineRangeMapping.modified.startLineNumber - 1), 18)
      }));
    });
    this.B($29(this.u.original, movedBlockViewZones.map((zones) => (
      /** @description movedBlockViewZones.original */
      zones.map((z) => z.original)
    ))));
    this.B($29(this.u.modified, movedBlockViewZones.map((zones) => (
      /** @description movedBlockViewZones.modified */
      zones.map((z) => z.modified)
    ))));
    this.B($xd((reader, store) => {
      const blocks = movedBlockViewZones.read(reader);
      for (const b of blocks) {
        store.add(new MovedBlockOverlayWidget(this.u.original, b.original, b.move, "original", this.r.get()));
        store.add(new MovedBlockOverlayWidget(this.u.modified, b.modified, b.move, "modified", this.r.get()));
      }
    }));
    const originalHasFocus = $Gd("original.onDidFocusEditorWidget", (e) => this.u.original.onDidFocusEditorWidget(() => setTimeout(() => e(void 0), 0)));
    const modifiedHasFocus = $Gd("modified.onDidFocusEditorWidget", (e) => this.u.modified.onDidFocusEditorWidget(() => setTimeout(() => e(void 0), 0)));
    let lastChangedEditor = "modified";
    this.B($vd({
      createEmptyChangeSummary: () => void 0,
      handleChange: (ctx, summary) => {
        if (ctx.didChange(originalHasFocus)) {
          lastChangedEditor = "original";
        }
        if (ctx.didChange(modifiedHasFocus)) {
          lastChangedEditor = "modified";
        }
        return true;
      }
    }, (reader) => {
      originalHasFocus.read(reader);
      modifiedHasFocus.read(reader);
      const m = this.r.read(reader);
      if (!m) {
        return;
      }
      const diff3 = m.diff.read(reader);
      let movedText = void 0;
      if (diff3 && lastChangedEditor === "original") {
        const originalPos = this.u.originalCursor.read(reader);
        if (originalPos) {
          movedText = diff3.movedTexts.find((m2) => m2.lineRangeMapping.original.contains(originalPos.lineNumber));
        }
      }
      if (diff3 && lastChangedEditor === "modified") {
        const modifiedPos = this.u.modifiedCursor.read(reader);
        if (modifiedPos) {
          movedText = diff3.movedTexts.find((m2) => m2.lineRangeMapping.modified.contains(modifiedPos.lineNumber));
        }
      }
      if (movedText !== m.movedTextToCompare.get()) {
        m.movedTextToCompare.set(void 0, void 0);
      }
      m.setActiveMovedText(movedText);
    }));
  }
};
var LinesLayout = class _LinesLayout {
  static compute(lines) {
    const setsPerTrack = [];
    const trackPerLineIdx = [];
    for (const line of lines) {
      let trackIdx = setsPerTrack.findIndex((set) => !set.intersectsStrict(line));
      if (trackIdx === -1) {
        const maxTrackCount = 6;
        if (setsPerTrack.length >= maxTrackCount) {
          trackIdx = $_(setsPerTrack, $9b((set) => set.intersectWithRangeLength(line), $$b));
        } else {
          trackIdx = setsPerTrack.length;
          setsPerTrack.push(new $$C());
        }
      }
      setsPerTrack[trackIdx].addRange(line);
      trackPerLineIdx.push(trackIdx);
    }
    return new _LinesLayout(setsPerTrack.length, trackPerLineIdx);
  }
  constructor(a, c) {
    this.a = a;
    this.c = c;
  }
  getTrack(lineIdx) {
    return this.c[lineIdx];
  }
  getTrackCount() {
    return this.a;
  }
};
var MovedBlockOverlayWidget = class extends $X9 {
  constructor(n, _viewZone, r2, u, w) {
    const root = h("div.diff-hidden-lines-widget");
    super(n, _viewZone, root.root);
    this.n = n;
    this.r = r2;
    this.u = u;
    this.w = w;
    this.f = h("div.diff-moved-code-block", { style: { marginRight: "4px" } }, [
      h("div.text-content@textContent"),
      h("div.action-bar@actionBar")
    ]);
    root.root.appendChild(this.f.root);
    const editorLayout = $Dd(this.n.onDidLayoutChange, () => this.n.getLayoutInfo());
    this.B($19(this.f.root, {
      paddingRight: editorLayout.map((l) => l.verticalScrollbarWidth)
    }));
    let text2;
    if (r2.changes.length > 0) {
      text2 = this.u === "original" ? localize(242, null, this.r.lineRangeMapping.modified.startLineNumber, this.r.lineRangeMapping.modified.endLineNumberExclusive - 1) : localize(243, null, this.r.lineRangeMapping.original.startLineNumber, this.r.lineRangeMapping.original.endLineNumberExclusive - 1);
    } else {
      text2 = this.u === "original" ? localize(244, null, this.r.lineRangeMapping.modified.startLineNumber, this.r.lineRangeMapping.modified.endLineNumberExclusive - 1) : localize(245, null, this.r.lineRangeMapping.original.startLineNumber, this.r.lineRangeMapping.original.endLineNumberExclusive - 1);
    }
    const actionBar = this.B(new $LZ(this.f.actionBar, {
      highlightToggledItems: true
    }));
    const caption = new $Um("", text2, "", false);
    actionBar.push(caption, { icon: false, label: true });
    const actionCompare = new $Um("", "Compare", ThemeIcon.asClassName($6l.compareChanges), true, () => {
      this.n.focus();
      this.w.movedTextToCompare.set(this.w.movedTextToCompare.get() === r2 ? void 0 : this.r, void 0);
    });
    this.B($td((reader) => {
      const isActive2 = this.w.movedTextToCompare.read(reader) === r2;
      actionCompare.checked = isActive2;
    }));
    actionBar.push(actionCompare, { icon: false, label: true });
  }
};

// out-build/vs/editor/browser/widget/diffEditor/components/diffEditorDecorations.js
var $k$ = class extends $3c {
  constructor(a, b, c, widget) {
    super();
    this.a = a;
    this.b = b;
    this.c = c;
    this.f = $2d(this, (reader) => {
      const diffModel = this.b.read(reader);
      const diff3 = diffModel?.diff.read(reader);
      if (!diff3) {
        return null;
      }
      const movedTextToCompare = this.b.read(reader).movedTextToCompare.read(reader);
      const renderIndicators = this.c.renderIndicators.read(reader);
      const showEmptyDecorations = this.c.showEmptyDecorations.read(reader);
      const originalDecorations = [];
      const modifiedDecorations = [];
      if (!movedTextToCompare) {
        for (const m of diff3.mappings) {
          if (!m.lineRangeMapping.original.isEmpty) {
            originalDecorations.push({ range: m.lineRangeMapping.original.toInclusiveRange(), options: renderIndicators ? $T0 : $V0 });
          }
          if (!m.lineRangeMapping.modified.isEmpty) {
            modifiedDecorations.push({ range: m.lineRangeMapping.modified.toInclusiveRange(), options: renderIndicators ? $S0 : $U0 });
          }
          if (m.lineRangeMapping.modified.isEmpty || m.lineRangeMapping.original.isEmpty) {
            if (!m.lineRangeMapping.original.isEmpty) {
              originalDecorations.push({ range: m.lineRangeMapping.original.toInclusiveRange(), options: $10 });
            }
            if (!m.lineRangeMapping.modified.isEmpty) {
              modifiedDecorations.push({ range: m.lineRangeMapping.modified.toInclusiveRange(), options: $X0 });
            }
          } else {
            const useInlineDiff = this.c.useTrueInlineDiffRendering.read(reader) && $$0(m.lineRangeMapping);
            for (const i2 of m.lineRangeMapping.innerChanges || []) {
              if (m.lineRangeMapping.original.contains(i2.originalRange.startLineNumber)) {
                originalDecorations.push({ range: i2.originalRange, options: i2.originalRange.isEmpty() && showEmptyDecorations ? $20 : $Z0 });
              }
              if (m.lineRangeMapping.modified.contains(i2.modifiedRange.startLineNumber)) {
                modifiedDecorations.push({ range: i2.modifiedRange, options: i2.modifiedRange.isEmpty() && showEmptyDecorations && !useInlineDiff ? $Y0 : $W0 });
              }
              if (useInlineDiff) {
                const deletedText = diffModel.model.original.getValueInRange(i2.originalRange);
                modifiedDecorations.push({
                  range: i2.modifiedRange,
                  options: {
                    description: "deleted-text",
                    before: {
                      content: deletedText,
                      inlineClassName: "inline-deleted-text"
                    },
                    zIndex: 1e5,
                    showIfCollapsed: true
                  }
                });
              }
            }
          }
        }
      }
      if (movedTextToCompare) {
        for (const m of movedTextToCompare.changes) {
          const fullRangeOriginal = m.original.toInclusiveRange();
          if (fullRangeOriginal) {
            originalDecorations.push({ range: fullRangeOriginal, options: renderIndicators ? $T0 : $V0 });
          }
          const fullRangeModified = m.modified.toInclusiveRange();
          if (fullRangeModified) {
            modifiedDecorations.push({ range: fullRangeModified, options: renderIndicators ? $S0 : $U0 });
          }
          for (const i2 of m.innerChanges || []) {
            originalDecorations.push({ range: i2.originalRange, options: $Z0 });
            modifiedDecorations.push({ range: i2.modifiedRange, options: $W0 });
          }
        }
      }
      const activeMovedText = this.b.read(reader).activeMovedText.read(reader);
      for (const m of diff3.movedTexts) {
        originalDecorations.push({
          range: m.lineRangeMapping.original.toInclusiveRange(),
          options: {
            description: "moved",
            blockClassName: "movedOriginal" + (m === activeMovedText ? " currentMove" : ""),
            blockPadding: [$j$.movedCodeBlockPadding, 0, $j$.movedCodeBlockPadding, $j$.movedCodeBlockPadding]
          }
        });
        modifiedDecorations.push({
          range: m.lineRangeMapping.modified.toInclusiveRange(),
          options: {
            description: "moved",
            blockClassName: "movedModified" + (m === activeMovedText ? " currentMove" : ""),
            blockPadding: [4, 0, 4, 4]
          }
        });
      }
      return { originalDecorations, modifiedDecorations };
    });
    this.B($R9(this.a.original, this.f.map((d) => d?.originalDecorations || [])));
    this.B($R9(this.a.modified, this.f.map((d) => d?.modifiedDecorations || [])));
  }
};

// out-build/vs/editor/browser/observableCodeEditor.js
function $79(editor) {
  return $89.get(editor);
}
var $89 = class _$89 extends $3c {
  static {
    this.a = /* @__PURE__ */ new Map();
  }
  /**
   * Make sure that editor is not disposed yet!
  */
  static get(editor) {
    let result = _$89.a.get(editor);
    if (!result) {
      result = new _$89(editor);
      _$89.a.set(editor, result);
      const d = editor.onDidDispose(() => {
        const item = _$89.a.get(editor);
        if (item) {
          _$89.a.delete(editor);
          item.dispose();
          d.dispose();
        }
      });
    }
    return result;
  }
  f() {
    this.b++;
    if (this.b === 1) {
      this.c = new $ge(() => {
      });
    }
  }
  g() {
    this.b--;
    if (this.b === 0) {
      const t = this.c;
      this.c = void 0;
      t.finish();
    }
  }
  constructor(editor) {
    super();
    this.editor = editor;
    this.b = 0;
    this.c = void 0;
    this.j = $he(this, this.editor.getModel());
    this.model = this.j;
    this.isReadonly = $Dd(this, this.editor.onDidChangeConfiguration, () => this.editor.getOption(
      96
      /* EditorOption.readOnly */
    ));
    this.m = $me({ owner: this, lazy: true }, this.editor.getModel()?.getVersionId() ?? null);
    this.versionId = this.m;
    this.n = $me({ owner: this, equalsFn: $qd($nd($_D.selectionsEqual)), lazy: true }, this.editor.getSelections() ?? null);
    this.selections = this.n;
    this.positions = $4d({ owner: this, equalsFn: $qd($nd($8C.equals)) }, (reader) => this.selections.read(reader)?.map((s) => s.getStartPosition()) ?? null);
    this.isFocused = $Dd(this, (e) => {
      const d1 = this.editor.onDidFocusEditorWidget(e);
      const d2 = this.editor.onDidBlurEditorWidget(e);
      return {
        dispose() {
          d1.dispose();
          d2.dispose();
        }
      };
    }, () => this.editor.hasWidgetFocus());
    this.isTextFocused = $Dd(this, (e) => {
      const d1 = this.editor.onDidFocusEditorText(e);
      const d2 = this.editor.onDidBlurEditorText(e);
      return {
        dispose() {
          d1.dispose();
          d2.dispose();
        }
      };
    }, () => this.editor.hasTextFocus());
    this.inComposition = $Dd(this, (e) => {
      const d1 = this.editor.onDidCompositionStart(() => {
        e(void 0);
      });
      const d2 = this.editor.onDidCompositionEnd(() => {
        e(void 0);
      });
      return {
        dispose() {
          d1.dispose();
          d2.dispose();
        }
      };
    }, () => this.editor.inComposition);
    this.value = $3d(this, (reader) => {
      this.versionId.read(reader);
      return this.model.read(reader)?.getValue() ?? "";
    }, (value, tx) => {
      const model = this.model.get();
      if (model !== null) {
        if (value !== model.getValue()) {
          model.setValue(value);
        }
      }
    });
    this.valueIsEmpty = $2d(this, (reader) => {
      this.versionId.read(reader);
      return this.editor.getModel()?.getValueLength() === 0;
    });
    this.cursorSelection = $4d({ owner: this, equalsFn: $qd($_D.selectionsEqual) }, (reader) => this.selections.read(reader)?.[0] ?? null);
    this.cursorPosition = $4d({ owner: this, equalsFn: $8C.equals }, (reader) => this.selections.read(reader)?.[0]?.getPosition() ?? null);
    this.cursorLineNumber = $2d(this, (reader) => this.cursorPosition.read(reader)?.lineNumber ?? null);
    this.onDidType = $Hd(this);
    this.scrollTop = $Dd(this.editor.onDidScrollChange, () => this.editor.getScrollTop());
    this.scrollLeft = $Dd(this.editor.onDidScrollChange, () => this.editor.getScrollLeft());
    this.layoutInfo = $Dd(this.editor.onDidLayoutChange, () => this.editor.getLayoutInfo());
    this.layoutInfoContentLeft = this.layoutInfo.map((l) => l.contentLeft);
    this.layoutInfoDecorationsLeft = this.layoutInfo.map((l) => l.decorationsLeft);
    this.contentWidth = $Dd(this.editor.onDidContentSizeChange, () => this.editor.getContentWidth());
    this.r = 0;
    this.B(this.editor.onBeginUpdate(() => this.f()));
    this.B(this.editor.onEndUpdate(() => this.g()));
    this.B(this.editor.onDidChangeModel(() => {
      this.f();
      try {
        this.j.set(this.editor.getModel(), this.c);
        this.h();
      } finally {
        this.g();
      }
    }));
    this.B(this.editor.onDidType((e) => {
      this.f();
      try {
        this.h();
        this.onDidType.trigger(this.c, e);
      } finally {
        this.g();
      }
    }));
    this.B(this.editor.onDidChangeModelContent((e) => {
      this.f();
      try {
        this.m.set(this.editor.getModel()?.getVersionId() ?? null, this.c, e);
        this.h();
      } finally {
        this.g();
      }
    }));
    this.B(this.editor.onDidChangeCursorSelection((e) => {
      this.f();
      try {
        this.n.set(this.editor.getSelections(), this.c, e);
        this.h();
      } finally {
        this.g();
      }
    }));
  }
  forceUpdate(cb) {
    this.f();
    try {
      this.h();
      if (!cb) {
        return void 0;
      }
      return cb(this.c);
    } finally {
      this.g();
    }
  }
  h() {
    this.f();
    try {
      this.j.set(this.editor.getModel(), this.c);
      this.m.set(this.editor.getModel()?.getVersionId() ?? null, this.c, void 0);
      this.n.set(this.editor.getSelections(), this.c, void 0);
    } finally {
      this.g();
    }
  }
  getOption(id2) {
    return $Dd(this, (cb) => this.editor.onDidChangeConfiguration((e) => {
      if (e.hasChanged(id2)) {
        cb(void 0);
      }
    }), () => this.editor.getOption(id2));
  }
  setDecorations(decorations) {
    const d = new $2c();
    const decorationsCollection = this.editor.createDecorationsCollection();
    d.add($ud({ owner: this, debugName: () => `Apply decorations from ${decorations.debugName}` }, (reader) => {
      const d2 = decorations.read(reader);
      decorationsCollection.set(d2);
    }));
    d.add({
      dispose: () => {
        decorationsCollection.clear();
      }
    });
    return d;
  }
  createOverlayWidget(widget) {
    const overlayWidgetId = "observableOverlayWidget" + this.r++;
    const w = {
      getDomNode: () => widget.domNode,
      getPosition: () => widget.position.get(),
      getId: () => overlayWidgetId,
      allowEditorOverflow: widget.allowEditorOverflow,
      getMinContentWidthInPx: () => widget.minContentWidthInPx.get()
    };
    this.editor.addOverlayWidget(w);
    const d = $td((reader) => {
      widget.position.read(reader);
      widget.minContentWidthInPx.read(reader);
      this.editor.layoutOverlayWidget(w);
    });
    return $1c(() => {
      d.dispose();
      this.editor.removeOverlayWidget(w);
    });
  }
};

// out-build/vs/editor/browser/widget/diffEditor/features/overviewRulerFeature.js
var $f$_1;
var $f$ = class $f$2 extends $3c {
  static {
    $f$_1 = this;
  }
  static {
    this.a = 15;
  }
  static {
    this.ENTIRE_DIFF_OVERVIEW_WIDTH = this.a * 2;
  }
  constructor(b, c, f, g, j, n, s) {
    super();
    this.b = b;
    this.c = c;
    this.f = f;
    this.g = g;
    this.j = j;
    this.n = n;
    this.s = s;
    this.width = $f$_1.ENTIRE_DIFF_OVERVIEW_WIDTH;
    const currentColorTheme = $Dd(this.s.onDidColorThemeChange, () => this.s.getColorTheme());
    const currentColors = $2d((reader) => {
      const theme = currentColorTheme.read(reader);
      const insertColor = theme.getColor($Ip) || (theme.getColor($Cp) || $Ap).transparent(2);
      const removeColor = theme.getColor($Jp) || (theme.getColor($Dp) || $Bp).transparent(2);
      return { insertColor, removeColor };
    });
    const viewportDomElement = $oZ(document.createElement("div"));
    viewportDomElement.setClassName("diffViewport");
    viewportDomElement.setPosition("absolute");
    const diffOverviewRoot = h("div.diffOverview", {
      style: { position: "absolute", top: "0px", width: $f$_1.ENTIRE_DIFF_OVERVIEW_WIDTH + "px" }
    }).root;
    this.B($S9(diffOverviewRoot, viewportDomElement.domNode));
    this.B($aj(diffOverviewRoot, $7j.POINTER_DOWN, (e) => {
      this.b.modified.delegateVerticalScrollbarPointerDown(e);
    }));
    this.B($_i(diffOverviewRoot, $7j.MOUSE_WHEEL, (e) => {
      this.b.modified.delegateScrollFromMouseWheelEvent(e);
    }, { passive: false }));
    this.B($S9(this.c, diffOverviewRoot));
    this.B($xd((reader, store) => {
      const m = this.f.read(reader);
      const originalOverviewRuler = this.b.original.createOverviewRuler("original diffOverviewRuler");
      if (originalOverviewRuler) {
        store.add(originalOverviewRuler);
        store.add($S9(diffOverviewRoot, originalOverviewRuler.getDomNode()));
      }
      const modifiedOverviewRuler = this.b.modified.createOverviewRuler("modified diffOverviewRuler");
      if (modifiedOverviewRuler) {
        store.add(modifiedOverviewRuler);
        store.add($S9(diffOverviewRoot, modifiedOverviewRuler.getDomNode()));
      }
      if (!originalOverviewRuler || !modifiedOverviewRuler) {
        return;
      }
      const origViewZonesChanged = $Gd("viewZoneChanged", this.b.original.onDidChangeViewZones);
      const modViewZonesChanged = $Gd("viewZoneChanged", this.b.modified.onDidChangeViewZones);
      const origHiddenRangesChanged = $Gd("hiddenRangesChanged", this.b.original.onDidChangeHiddenAreas);
      const modHiddenRangesChanged = $Gd("hiddenRangesChanged", this.b.modified.onDidChangeHiddenAreas);
      store.add($td((reader2) => {
        origViewZonesChanged.read(reader2);
        modViewZonesChanged.read(reader2);
        origHiddenRangesChanged.read(reader2);
        modHiddenRangesChanged.read(reader2);
        const colors = currentColors.read(reader2);
        const diff3 = m?.diff.read(reader2)?.mappings;
        function createZones(ranges, color2, editor) {
          const vm = editor._getViewModel();
          if (!vm) {
            return [];
          }
          return ranges.filter((d) => d.length > 0).map((r2) => {
            const start = vm.coordinatesConverter.convertModelPositionToViewPosition(new $8C(r2.startLineNumber, 1));
            const end = vm.coordinatesConverter.convertModelPositionToViewPosition(new $8C(r2.endLineNumberExclusive, 1));
            const lineCount = end.lineNumber - start.lineNumber;
            return new $N5(start.lineNumber, end.lineNumber, lineCount, color2.toString());
          });
        }
        const originalZones = createZones((diff3 || []).map((d) => d.lineRangeMapping.original), colors.removeColor, this.b.original);
        const modifiedZones = createZones((diff3 || []).map((d) => d.lineRangeMapping.modified), colors.insertColor, this.b.modified);
        originalOverviewRuler?.setZones(originalZones);
        modifiedOverviewRuler?.setZones(modifiedZones);
      }));
      store.add($td((reader2) => {
        const height = this.j.read(reader2);
        const width2 = this.g.read(reader2);
        const layoutInfo = this.n.read(reader2);
        if (layoutInfo) {
          const freeSpace = $f$_1.ENTIRE_DIFF_OVERVIEW_WIDTH - 2 * $f$_1.a;
          originalOverviewRuler.setLayout({
            top: 0,
            height,
            right: freeSpace + $f$_1.a,
            width: $f$_1.a
          });
          modifiedOverviewRuler.setLayout({
            top: 0,
            height,
            right: 0,
            width: $f$_1.a
          });
          const scrollTop = this.b.modifiedScrollTop.read(reader2);
          const scrollHeight = this.b.modifiedScrollHeight.read(reader2);
          const scrollBarOptions = this.b.modified.getOption(
            108
            /* EditorOption.scrollbar */
          );
          const state = new $tZ(scrollBarOptions.verticalHasArrows ? scrollBarOptions.arrowSize : 0, scrollBarOptions.verticalScrollbarSize, 0, layoutInfo.height, scrollHeight, scrollTop);
          viewportDomElement.setTop(state.getSliderPosition());
          viewportDomElement.setHeight(state.getSliderSize());
        } else {
          viewportDomElement.setTop(0);
          viewportDomElement.setHeight(0);
        }
        diffOverviewRoot.style.height = height + "px";
        diffOverviewRoot.style.left = width2 - $f$_1.ENTIRE_DIFF_OVERVIEW_WIDTH + "px";
        viewportDomElement.setWidth($f$_1.ENTIRE_DIFF_OVERVIEW_WIDTH);
      }));
    }));
  }
};
$f$ = $f$_1 = __decorate([
  __param(6, $gs)
], $f$);

// out-build/vs/editor/browser/widget/diffEditor/components/diffEditorEditors.js
var $g$ = class $g$2 extends $3c {
  get onDidContentSizeChange() {
    return this.a.event;
  }
  constructor(b, c, f, g, h3, j, m) {
    super();
    this.b = b;
    this.c = c;
    this.f = f;
    this.g = g;
    this.h = h3;
    this.j = j;
    this.m = m;
    this.original = this.B(this.n(this.f.editorOptions.get(), this.g.originalEditor || {}));
    this.modified = this.B(this.r(this.f.editorOptions.get(), this.g.modifiedEditor || {}));
    this.a = this.B(new $ze());
    this.modifiedScrollTop = $Dd(this, this.modified.onDidScrollChange, () => (
      /** @description modified.getScrollTop */
      this.modified.getScrollTop()
    ));
    this.modifiedScrollHeight = $Dd(this, this.modified.onDidScrollChange, () => (
      /** @description modified.getScrollHeight */
      this.modified.getScrollHeight()
    ));
    this.modifiedObs = $79(this.modified);
    this.originalObs = $79(this.original);
    this.modifiedModel = this.modifiedObs.model;
    this.modifiedSelections = $Dd(this, this.modified.onDidChangeCursorSelection, () => this.modified.getSelections() ?? []);
    this.modifiedCursor = $4d({ owner: this, equalsFn: $8C.equals }, (reader) => this.modifiedSelections.read(reader)[0]?.getPosition() ?? new $8C(1, 1));
    this.originalCursor = $Dd(this, this.original.onDidChangeCursorPosition, () => this.original.getPosition() ?? new $8C(1, 1));
    this.isOriginalFocused = $79(this.original).isFocused;
    this.isModifiedFocused = $79(this.modified).isFocused;
    this.isFocused = $2d(this, (reader) => this.isOriginalFocused.read(reader) || this.isModifiedFocused.read(reader));
    this.g = null;
    this.B($vd({
      createEmptyChangeSummary: () => ({}),
      handleChange: (ctx, changeSummary) => {
        if (ctx.didChange(f.editorOptions)) {
          Object.assign(changeSummary, ctx.change.changedOptions);
        }
        return true;
      }
    }, (reader, changeSummary) => {
      f.editorOptions.read(reader);
      this.f.renderSideBySide.read(reader);
      this.modified.updateOptions(this.u(reader, changeSummary));
      this.original.updateOptions(this.t(reader, changeSummary));
    }));
  }
  n(options3, codeEditorWidgetOptions) {
    const leftHandSideOptions = this.t(void 0, options3);
    const editor = this.s(this.j, this.b, leftHandSideOptions, codeEditorWidgetOptions);
    editor.setContextValue("isInDiffLeftEditor", true);
    return editor;
  }
  r(options3, codeEditorWidgetOptions) {
    const rightHandSideOptions = this.u(void 0, options3);
    const editor = this.s(this.j, this.c, rightHandSideOptions, codeEditorWidgetOptions);
    editor.setContextValue("isInDiffRightEditor", true);
    return editor;
  }
  s(instantiationService, container2, options3, editorWidgetOptions) {
    const editor = this.h(instantiationService, container2, options3, editorWidgetOptions);
    this.B(editor.onDidContentSizeChange((e) => {
      const width2 = this.original.getContentWidth() + this.modified.getContentWidth() + $f$.ENTIRE_DIFF_OVERVIEW_WIDTH;
      const height = Math.max(this.modified.getContentHeight(), this.original.getContentHeight());
      this.a.fire({
        contentHeight: height,
        contentWidth: width2,
        contentHeightChanged: e.contentHeightChanged,
        contentWidthChanged: e.contentWidthChanged
      });
    }));
    return editor;
  }
  t(_reader, changedOptions) {
    const result = this.w(changedOptions);
    if (!this.f.renderSideBySide.get()) {
      result.wordWrapOverride1 = "off";
      result.wordWrapOverride2 = "off";
      result.stickyScroll = { enabled: false };
      result.unicodeHighlight = { nonBasicASCII: false, ambiguousCharacters: false, invisibleCharacters: false };
    } else {
      result.unicodeHighlight = this.f.editorOptions.get().unicodeHighlight || {};
      result.wordWrapOverride1 = this.f.diffWordWrap.get();
    }
    result.glyphMargin = this.f.renderSideBySide.get();
    if (changedOptions.originalAriaLabel) {
      result.ariaLabel = changedOptions.originalAriaLabel;
    }
    result.ariaLabel = this.y(result.ariaLabel);
    result.readOnly = !this.f.originalEditable.get();
    result.dropIntoEditor = { enabled: !result.readOnly };
    result.extraEditorClassName = "original-in-monaco-diff-editor";
    return result;
  }
  u(reader, changedOptions) {
    const result = this.w(changedOptions);
    if (changedOptions.modifiedAriaLabel) {
      result.ariaLabel = changedOptions.modifiedAriaLabel;
    }
    result.ariaLabel = this.y(result.ariaLabel);
    result.wordWrapOverride1 = this.f.diffWordWrap.get();
    result.revealHorizontalRightPadding = EditorOptions.revealHorizontalRightPadding.defaultValue + $f$.ENTIRE_DIFF_OVERVIEW_WIDTH;
    result.scrollbar.verticalHasArrows = false;
    result.extraEditorClassName = "modified-in-monaco-diff-editor";
    return result;
  }
  w(options3) {
    const clonedOptions = {
      ...options3,
      dimension: {
        height: 0,
        width: 0
      }
    };
    clonedOptions.inDiffEditor = true;
    clonedOptions.automaticLayout = false;
    clonedOptions.scrollbar = { ...clonedOptions.scrollbar || {} };
    clonedOptions.folding = false;
    clonedOptions.codeLens = this.f.diffCodeLens.get();
    clonedOptions.fixedOverflowWidgets = true;
    clonedOptions.minimap = { ...clonedOptions.minimap || {} };
    clonedOptions.minimap.enabled = false;
    if (this.f.hideUnchangedRegions.get()) {
      clonedOptions.stickyScroll = { enabled: false };
    } else {
      clonedOptions.stickyScroll = this.f.editorOptions.get().stickyScroll;
    }
    return clonedOptions;
  }
  y(ariaLabel) {
    if (!ariaLabel) {
      ariaLabel = "";
    }
    const ariaNavigationTip = localize(222, null, this.m.lookupKeybinding("editor.action.accessibilityHelp")?.getAriaLabel());
    if (this.f.accessibilityVerbose.get()) {
      return ariaLabel + ariaNavigationTip;
    } else if (ariaLabel) {
      return ariaLabel.replaceAll(ariaNavigationTip, "");
    }
    return "";
  }
};
$g$ = __decorate([
  __param(5, $Pk),
  __param(6, $Ty)
], $g$);

// out-build/vs/base/browser/ui/sash/sash.js
var DEBUG = false;
var OrthogonalEdge;
(function(OrthogonalEdge2) {
  OrthogonalEdge2["North"] = "north";
  OrthogonalEdge2["South"] = "south";
  OrthogonalEdge2["East"] = "east";
  OrthogonalEdge2["West"] = "west";
})(OrthogonalEdge || (OrthogonalEdge = {}));
var Orientation;
(function(Orientation2) {
  Orientation2[Orientation2["VERTICAL"] = 0] = "VERTICAL";
  Orientation2[Orientation2["HORIZONTAL"] = 1] = "HORIZONTAL";
})(Orientation || (Orientation = {}));
var SashState;
(function(SashState2) {
  SashState2[SashState2["Disabled"] = 0] = "Disabled";
  SashState2[SashState2["AtMinimum"] = 1] = "AtMinimum";
  SashState2[SashState2["AtMaximum"] = 2] = "AtMaximum";
  SashState2[SashState2["Enabled"] = 3] = "Enabled";
})(SashState || (SashState = {}));
var globalSize = 4;
var onDidChangeGlobalSize = new $ze();
function $o2(size) {
  globalSize = size;
  onDidChangeGlobalSize.fire(size);
}
var globalHoverDelay = 300;
var onDidChangeHoverDelay = new $ze();
function $p2(size) {
  globalHoverDelay = size;
  onDidChangeHoverDelay.fire(size);
}
var MouseEventFactory = class {
  constructor(b) {
    this.b = b;
    this.a = new $2c();
  }
  get onPointerMove() {
    return this.a.add(new $9Z(getWindow(this.b), "mousemove")).event;
  }
  get onPointerUp() {
    return this.a.add(new $9Z(getWindow(this.b), "mouseup")).event;
  }
  dispose() {
    this.a.dispose();
  }
};
__decorate([
  $0t
], MouseEventFactory.prototype, "onPointerMove", null);
__decorate([
  $0t
], MouseEventFactory.prototype, "onPointerUp", null);
var GestureEventFactory = class {
  get onPointerMove() {
    return this.a.add(new $9Z(this.b, EventType.Change)).event;
  }
  get onPointerUp() {
    return this.a.add(new $9Z(this.b, EventType.End)).event;
  }
  constructor(b) {
    this.b = b;
    this.a = new $2c();
  }
  dispose() {
    this.a.dispose();
  }
};
__decorate([
  $0t
], GestureEventFactory.prototype, "onPointerMove", null);
__decorate([
  $0t
], GestureEventFactory.prototype, "onPointerUp", null);
var OrthogonalPointerEventFactory = class {
  get onPointerMove() {
    return this.a.onPointerMove;
  }
  get onPointerUp() {
    return this.a.onPointerUp;
  }
  constructor(a) {
    this.a = a;
  }
  dispose() {
  }
};
__decorate([
  $0t
], OrthogonalPointerEventFactory.prototype, "onPointerMove", null);
__decorate([
  $0t
], OrthogonalPointerEventFactory.prototype, "onPointerUp", null);
var PointerEventsDisabledCssClass = "pointer-events-disabled";
var $q2 = class _$q2 extends $3c {
  get state() {
    return this.j;
  }
  get orthogonalStartSash() {
    return this.w;
  }
  get orthogonalEndSash() {
    return this.D;
  }
  /**
   * The state of a sash defines whether it can be interacted with by the user
   * as well as what mouse cursor to use, when hovered.
   */
  set state(state) {
    if (this.j === state) {
      return;
    }
    this.a.classList.toggle(
      "disabled",
      state === 0
      /* SashState.Disabled */
    );
    this.a.classList.toggle(
      "minimum",
      state === 1
      /* SashState.AtMinimum */
    );
    this.a.classList.toggle(
      "maximum",
      state === 2
      /* SashState.AtMaximum */
    );
    this.j = state;
    this.m.fire(state);
  }
  /**
   * A reference to another sash, perpendicular to this one, which
   * aligns at the start of this one. A corner sash will be created
   * automatically at that location.
   *
   * The start of a horizontal sash is its left-most position.
   * The start of a vertical sash is its top-most position.
   */
  set orthogonalStartSash(sash) {
    if (this.w === sash) {
      return;
    }
    this.y.clear();
    this.u.clear();
    if (sash) {
      const onChange = (state) => {
        this.y.clear();
        if (state !== 0) {
          this.z = $bk(this.a, $(".orthogonal-drag-handle.start"));
          this.y.add($1c(() => this.z.remove()));
          this.y.add(new $9Z(this.z, "mouseenter")).event(() => _$q2.J(sash), void 0, this.y);
          this.y.add(new $9Z(this.z, "mouseleave")).event(() => _$q2.L(sash), void 0, this.y);
        }
      };
      this.u.add(sash.m.event(onChange, this));
      onChange(sash.state);
    }
    this.w = sash;
  }
  /**
   * A reference to another sash, perpendicular to this one, which
   * aligns at the end of this one. A corner sash will be created
   * automatically at that location.
   *
   * The end of a horizontal sash is its right-most position.
   * The end of a vertical sash is its bottom-most position.
   */
  set orthogonalEndSash(sash) {
    if (this.D === sash) {
      return;
    }
    this.F.clear();
    this.C.clear();
    if (sash) {
      const onChange = (state) => {
        this.F.clear();
        if (state !== 0) {
          this.G = $bk(this.a, $(".orthogonal-drag-handle.end"));
          this.F.add($1c(() => this.G.remove()));
          this.F.add(new $9Z(this.G, "mouseenter")).event(() => _$q2.J(sash), void 0, this.F);
          this.F.add(new $9Z(this.G, "mouseleave")).event(() => _$q2.L(sash), void 0, this.F);
        }
      };
      this.C.add(sash.m.event(onChange, this));
      onChange(sash.state);
    }
    this.D = sash;
  }
  constructor(container2, layoutProvider, options3) {
    super();
    this.g = globalHoverDelay;
    this.h = this.B(new $Sh(this.g));
    this.j = 3;
    this.m = this.B(new $ze());
    this.n = this.B(new $ze());
    this.r = this.B(new $ze());
    this.s = this.B(new $ze());
    this.t = this.B(new $ze());
    this.u = this.B(new $2c());
    this.y = this.B(new $2c());
    this.C = this.B(new $2c());
    this.F = this.B(new $2c());
    this.onDidStart = this.n.event;
    this.onDidChange = this.r.event;
    this.onDidReset = this.s.event;
    this.onDidEnd = this.t.event;
    this.linkedSash = void 0;
    this.a = $bk(container2, $(".monaco-sash"));
    if (options3.orthogonalEdge) {
      this.a.classList.add(`orthogonal-edge-${options3.orthogonalEdge}`);
    }
    if ($m) {
      this.a.classList.add("mac");
    }
    const onMouseDown = this.B(new $9Z(this.a, "mousedown")).event;
    this.B(onMouseDown((e) => this.H(e, new MouseEventFactory(container2)), this));
    const onMouseDoubleClick = this.B(new $9Z(this.a, "dblclick")).event;
    this.B(onMouseDoubleClick(this.I, this));
    const onMouseEnter = this.B(new $9Z(this.a, "mouseenter")).event;
    this.B(onMouseEnter(() => _$q2.J(this)));
    const onMouseLeave = this.B(new $9Z(this.a, "mouseleave")).event;
    this.B(onMouseLeave(() => _$q2.L(this)));
    this.B($mZ.addTarget(this.a));
    const onTouchStart = this.B(new $9Z(this.a, EventType.Start)).event;
    this.B(onTouchStart((e) => this.H(e, new GestureEventFactory(this.a)), this));
    const onTap = this.B(new $9Z(this.a, EventType.Tap)).event;
    let doubleTapTimeout = void 0;
    this.B(onTap((event) => {
      if (doubleTapTimeout) {
        clearTimeout(doubleTapTimeout);
        doubleTapTimeout = void 0;
        this.I(event);
        return;
      }
      clearTimeout(doubleTapTimeout);
      doubleTapTimeout = setTimeout(() => doubleTapTimeout = void 0, 250);
    }, this));
    if (typeof options3.size === "number") {
      this.f = options3.size;
      if (options3.orientation === 0) {
        this.a.style.width = `${this.f}px`;
      } else {
        this.a.style.height = `${this.f}px`;
      }
    } else {
      this.f = globalSize;
      this.B(onDidChangeGlobalSize.event((size) => {
        this.f = size;
        this.layout();
      }));
    }
    this.B(onDidChangeHoverDelay.event((delay) => this.g = delay));
    this.b = layoutProvider;
    this.orthogonalStartSash = options3.orthogonalStartSash;
    this.orthogonalEndSash = options3.orthogonalEndSash;
    this.c = options3.orientation || 0;
    if (this.c === 1) {
      this.a.classList.add("horizontal");
      this.a.classList.remove("vertical");
    } else {
      this.a.classList.remove("horizontal");
      this.a.classList.add("vertical");
    }
    this.a.classList.toggle("debug", DEBUG);
    this.layout();
  }
  H(event, pointerEventFactory) {
    $9j.stop(event);
    let isMultisashResize = false;
    if (!event.__orthogonalSashEvent) {
      const orthogonalSash = this.M(event);
      if (orthogonalSash) {
        isMultisashResize = true;
        event.__orthogonalSashEvent = true;
        orthogonalSash.H(event, new OrthogonalPointerEventFactory(pointerEventFactory));
      }
    }
    if (this.linkedSash && !event.__linkedSashEvent) {
      event.__linkedSashEvent = true;
      this.linkedSash.H(event, new OrthogonalPointerEventFactory(pointerEventFactory));
    }
    if (!this.state) {
      return;
    }
    const iframes = this.a.ownerDocument.getElementsByTagName("iframe");
    for (const iframe of iframes) {
      iframe.classList.add(PointerEventsDisabledCssClass);
    }
    const startX = event.pageX;
    const startY = event.pageY;
    const altKey = event.altKey;
    const startEvent = { startX, currentX: startX, startY, currentY: startY, altKey };
    this.a.classList.add("active");
    this.n.fire(startEvent);
    const style = $VZ(this.a);
    const updateStyle = () => {
      let cursor = "";
      if (isMultisashResize) {
        cursor = "all-scroll";
      } else if (this.c === 1) {
        if (this.state === 1) {
          cursor = "s-resize";
        } else if (this.state === 2) {
          cursor = "n-resize";
        } else {
          cursor = $m ? "row-resize" : "ns-resize";
        }
      } else {
        if (this.state === 1) {
          cursor = "e-resize";
        } else if (this.state === 2) {
          cursor = "w-resize";
        } else {
          cursor = $m ? "col-resize" : "ew-resize";
        }
      }
      style.textContent = `* { cursor: ${cursor} !important; }`;
    };
    const disposables = new $2c();
    updateStyle();
    if (!isMultisashResize) {
      this.m.event(updateStyle, null, disposables);
    }
    const onPointerMove = (e) => {
      $9j.stop(e, false);
      const event2 = { startX, currentX: e.pageX, startY, currentY: e.pageY, altKey };
      this.r.fire(event2);
    };
    const onPointerUp = (e) => {
      $9j.stop(e, false);
      style.remove();
      this.a.classList.remove("active");
      this.t.fire();
      disposables.dispose();
      for (const iframe of iframes) {
        iframe.classList.remove(PointerEventsDisabledCssClass);
      }
    };
    pointerEventFactory.onPointerMove(onPointerMove, null, disposables);
    pointerEventFactory.onPointerUp(onPointerUp, null, disposables);
    disposables.add(pointerEventFactory);
  }
  I(e) {
    const orthogonalSash = this.M(e);
    if (orthogonalSash) {
      orthogonalSash.s.fire();
    }
    if (this.linkedSash) {
      this.linkedSash.s.fire();
    }
    this.s.fire();
  }
  static J(sash, fromLinkedSash = false) {
    if (sash.a.classList.contains("active")) {
      sash.h.cancel();
      sash.a.classList.add("hover");
    } else {
      sash.h.trigger(() => sash.a.classList.add("hover"), sash.g).then(void 0, () => {
      });
    }
    if (!fromLinkedSash && sash.linkedSash) {
      _$q2.J(sash.linkedSash, true);
    }
  }
  static L(sash, fromLinkedSash = false) {
    sash.h.cancel();
    sash.a.classList.remove("hover");
    if (!fromLinkedSash && sash.linkedSash) {
      _$q2.L(sash.linkedSash, true);
    }
  }
  /**
   * Forcefully stop any user interactions with this sash.
   * Useful when hiding a parent component, while the user is still
   * interacting with the sash.
   */
  clearSashHoverState() {
    _$q2.L(this);
  }
  /**
   * Layout the sash. The sash will size and position itself
   * based on its provided {@link ISashLayoutProvider layout provider}.
   */
  layout() {
    if (this.c === 0) {
      const verticalProvider = this.b;
      this.a.style.left = verticalProvider.getVerticalSashLeft(this) - this.f / 2 + "px";
      if (verticalProvider.getVerticalSashTop) {
        this.a.style.top = verticalProvider.getVerticalSashTop(this) + "px";
      }
      if (verticalProvider.getVerticalSashHeight) {
        this.a.style.height = verticalProvider.getVerticalSashHeight(this) + "px";
      }
    } else {
      const horizontalProvider = this.b;
      this.a.style.top = horizontalProvider.getHorizontalSashTop(this) - this.f / 2 + "px";
      if (horizontalProvider.getHorizontalSashLeft) {
        this.a.style.left = horizontalProvider.getHorizontalSashLeft(this) + "px";
      }
      if (horizontalProvider.getHorizontalSashWidth) {
        this.a.style.width = horizontalProvider.getHorizontalSashWidth(this) + "px";
      }
    }
  }
  M(e) {
    const target = e.initialTarget ?? e.target;
    if (!target || !$Uj(target)) {
      return void 0;
    }
    if (target.classList.contains("orthogonal-drag-handle")) {
      return target.classList.contains("start") ? this.orthogonalStartSash : this.orthogonalEndSash;
    }
    return void 0;
  }
  dispose() {
    super.dispose();
    this.a.remove();
  }
};

// out-build/vs/editor/browser/widget/diffEditor/components/diffEditorSash.js
var $l$ = class {
  resetSash() {
    this.a.set(void 0, void 0);
  }
  constructor(b, dimensions) {
    this.b = b;
    this.dimensions = dimensions;
    this.sashLeft = $3d(this, (reader) => {
      const ratio = this.a.read(reader) ?? this.b.splitViewDefaultRatio.read(reader);
      return this.c(ratio, reader);
    }, (value, tx) => {
      const contentWidth = this.dimensions.width.get();
      this.a.set(value / contentWidth, tx);
    });
    this.a = $he(this, void 0);
  }
  /** @pure */
  c(desiredRatio, reader) {
    const contentWidth = this.dimensions.width.read(reader);
    const midPoint = Math.floor(this.b.splitViewDefaultRatio.read(reader) * contentWidth);
    const sashLeft = this.b.enableSplitViewResizing.read(reader) ? Math.floor(desiredRatio * contentWidth) : midPoint;
    const MINIMUM_EDITOR_WIDTH = 100;
    if (contentWidth <= MINIMUM_EDITOR_WIDTH * 2) {
      return midPoint;
    }
    if (sashLeft < MINIMUM_EDITOR_WIDTH) {
      return MINIMUM_EDITOR_WIDTH;
    }
    if (sashLeft > contentWidth - MINIMUM_EDITOR_WIDTH) {
      return contentWidth - MINIMUM_EDITOR_WIDTH;
    }
    return sashLeft;
  }
};
var $m$ = class extends $3c {
  constructor(c, f, g, h3, sashLeft, j) {
    super();
    this.c = c;
    this.f = f;
    this.g = g;
    this.h = h3;
    this.sashLeft = sashLeft;
    this.j = j;
    this.a = this.B(new $q2(this.c, {
      getVerticalSashTop: (_sash) => 0,
      getVerticalSashLeft: (_sash) => this.sashLeft.get(),
      getVerticalSashHeight: (_sash) => this.f.height.get()
    }, {
      orientation: 0
      /* Orientation.VERTICAL */
    }));
    this.b = void 0;
    this.B(this.a.onDidStart(() => {
      this.b = this.sashLeft.get();
    }));
    this.B(this.a.onDidChange((e) => {
      this.sashLeft.set(this.b + (e.currentX - e.startX), void 0);
    }));
    this.B(this.a.onDidEnd(() => this.a.layout()));
    this.B(this.a.onDidReset(() => this.j()));
    this.B($td((reader) => {
      const sashes = this.h.read(reader);
      if (sashes) {
        this.a.orthogonalEndSash = sashes.bottom;
      }
    }));
    this.B($td((reader) => {
      const enabled = this.g.read(reader);
      this.a.state = enabled ? 3 : 0;
      this.sashLeft.read(reader);
      this.f.height.read(reader);
      this.a.layout();
    }));
  }
};

// out-build/vs/editor/browser/widget/diffEditor/delegatingEditorImpl.js
var $n$ = class _$n$ extends $3c {
  constructor() {
    super(...arguments);
    this.b = ++_$n$.a;
    this.f = this.B(new $ze());
    this.onDidDispose = this.f.event;
  }
  static {
    this.a = 0;
  }
  getId() {
    return this.getEditorType() + ":v2:" + this.b;
  }
  // #region editorBrowser.IDiffEditor: Delegating to modified Editor
  getVisibleColumnFromPosition(position) {
    return this.g.getVisibleColumnFromPosition(position);
  }
  getStatusbarColumn(position) {
    return this.g.getStatusbarColumn(position);
  }
  getPosition() {
    return this.g.getPosition();
  }
  setPosition(position, source = "api") {
    this.g.setPosition(position, source);
  }
  revealLine(lineNumber, scrollType = 0) {
    this.g.revealLine(lineNumber, scrollType);
  }
  revealLineInCenter(lineNumber, scrollType = 0) {
    this.g.revealLineInCenter(lineNumber, scrollType);
  }
  revealLineInCenterIfOutsideViewport(lineNumber, scrollType = 0) {
    this.g.revealLineInCenterIfOutsideViewport(lineNumber, scrollType);
  }
  revealLineNearTop(lineNumber, scrollType = 0) {
    this.g.revealLineNearTop(lineNumber, scrollType);
  }
  revealPosition(position, scrollType = 0) {
    this.g.revealPosition(position, scrollType);
  }
  revealPositionInCenter(position, scrollType = 0) {
    this.g.revealPositionInCenter(position, scrollType);
  }
  revealPositionInCenterIfOutsideViewport(position, scrollType = 0) {
    this.g.revealPositionInCenterIfOutsideViewport(position, scrollType);
  }
  revealPositionNearTop(position, scrollType = 0) {
    this.g.revealPositionNearTop(position, scrollType);
  }
  getSelection() {
    return this.g.getSelection();
  }
  getSelections() {
    return this.g.getSelections();
  }
  setSelection(something, source = "api") {
    this.g.setSelection(something, source);
  }
  setSelections(ranges, source = "api") {
    this.g.setSelections(ranges, source);
  }
  revealLines(startLineNumber, endLineNumber, scrollType = 0) {
    this.g.revealLines(startLineNumber, endLineNumber, scrollType);
  }
  revealLinesInCenter(startLineNumber, endLineNumber, scrollType = 0) {
    this.g.revealLinesInCenter(startLineNumber, endLineNumber, scrollType);
  }
  revealLinesInCenterIfOutsideViewport(startLineNumber, endLineNumber, scrollType = 0) {
    this.g.revealLinesInCenterIfOutsideViewport(startLineNumber, endLineNumber, scrollType);
  }
  revealLinesNearTop(startLineNumber, endLineNumber, scrollType = 0) {
    this.g.revealLinesNearTop(startLineNumber, endLineNumber, scrollType);
  }
  revealRange(range, scrollType = 0, revealVerticalInCenter = false, revealHorizontal = true) {
    this.g.revealRange(range, scrollType, revealVerticalInCenter, revealHorizontal);
  }
  revealRangeInCenter(range, scrollType = 0) {
    this.g.revealRangeInCenter(range, scrollType);
  }
  revealRangeInCenterIfOutsideViewport(range, scrollType = 0) {
    this.g.revealRangeInCenterIfOutsideViewport(range, scrollType);
  }
  revealRangeNearTop(range, scrollType = 0) {
    this.g.revealRangeNearTop(range, scrollType);
  }
  revealRangeNearTopIfOutsideViewport(range, scrollType = 0) {
    this.g.revealRangeNearTopIfOutsideViewport(range, scrollType);
  }
  revealRangeAtTop(range, scrollType = 0) {
    this.g.revealRangeAtTop(range, scrollType);
  }
  getSupportedActions() {
    return this.g.getSupportedActions();
  }
  focus() {
    this.g.focus();
  }
  trigger(source, handlerId, payload) {
    this.g.trigger(source, handlerId, payload);
  }
  createDecorationsCollection(decorations) {
    return this.g.createDecorationsCollection(decorations);
  }
  changeDecorations(callback) {
    return this.g.changeDecorations(callback);
  }
};

// out-build/vs/editor/common/config/diffEditor.js
var $M0 = {
  enableSplitViewResizing: true,
  splitViewDefaultRatio: 0.5,
  renderSideBySide: true,
  renderMarginRevertIcon: true,
  renderGutterMenu: true,
  maxComputationTime: 5e3,
  maxFileSize: 50,
  ignoreTrimWhitespace: true,
  renderIndicators: true,
  originalEditable: false,
  diffCodeLens: false,
  renderOverviewRuler: true,
  diffWordWrap: "inherit",
  diffAlgorithm: "advanced",
  accessibilityVerbose: false,
  experimental: {
    showMoves: false,
    showEmptyDecorations: true,
    useTrueInlineView: false
  },
  hideUnchangedRegions: {
    enabled: false,
    contextLineCount: 3,
    minimumLineCount: 3,
    revealLineCount: 20
  },
  isInEmbeddedEditor: false,
  onlyShowAccessibleDiffViewer: false,
  renderSideBySideInlineBreakpoint: 900,
  useInlineViewWhenSpaceIsLimited: true,
  compactMode: false
};

// out-build/vs/editor/browser/widget/diffEditor/diffEditorOptions.js
var $a$ = class $a$2 {
  get editorOptions() {
    return this.a;
  }
  constructor(options3, d) {
    this.d = d;
    this.b = $he(this, 0);
    this.c = $Dd(this, this.d.onDidChangeScreenReaderOptimized, () => this.d.isScreenReaderOptimized());
    this.couldShowInlineViewBecauseOfSize = $2d(this, (reader) => this.a.read(reader).renderSideBySide && this.b.read(reader) <= this.a.read(reader).renderSideBySideInlineBreakpoint);
    this.renderOverviewRuler = $2d(this, (reader) => this.a.read(reader).renderOverviewRuler);
    this.renderSideBySide = $2d(this, (reader) => {
      if (this.compactMode.read(reader)) {
        if (this.g.read(reader)) {
          return false;
        }
      }
      return this.a.read(reader).renderSideBySide && !(this.a.read(reader).useInlineViewWhenSpaceIsLimited && this.couldShowInlineViewBecauseOfSize.read(reader) && !this.c.read(reader));
    });
    this.readOnly = $2d(this, (reader) => this.a.read(reader).readOnly);
    this.shouldRenderOldRevertArrows = $2d(this, (reader) => {
      if (!this.a.read(reader).renderMarginRevertIcon) {
        return false;
      }
      if (!this.renderSideBySide.read(reader)) {
        return false;
      }
      if (this.readOnly.read(reader)) {
        return false;
      }
      if (this.shouldRenderGutterMenu.read(reader)) {
        return false;
      }
      return true;
    });
    this.shouldRenderGutterMenu = $2d(this, (reader) => this.a.read(reader).renderGutterMenu);
    this.renderIndicators = $2d(this, (reader) => this.a.read(reader).renderIndicators);
    this.enableSplitViewResizing = $2d(this, (reader) => this.a.read(reader).enableSplitViewResizing);
    this.splitViewDefaultRatio = $2d(this, (reader) => this.a.read(reader).splitViewDefaultRatio);
    this.ignoreTrimWhitespace = $2d(this, (reader) => this.a.read(reader).ignoreTrimWhitespace);
    this.maxComputationTimeMs = $2d(this, (reader) => this.a.read(reader).maxComputationTime);
    this.showMoves = $2d(this, (reader) => this.a.read(reader).experimental.showMoves && this.renderSideBySide.read(reader));
    this.isInEmbeddedEditor = $2d(this, (reader) => this.a.read(reader).isInEmbeddedEditor);
    this.diffWordWrap = $2d(this, (reader) => this.a.read(reader).diffWordWrap);
    this.originalEditable = $2d(this, (reader) => this.a.read(reader).originalEditable);
    this.diffCodeLens = $2d(this, (reader) => this.a.read(reader).diffCodeLens);
    this.accessibilityVerbose = $2d(this, (reader) => this.a.read(reader).accessibilityVerbose);
    this.diffAlgorithm = $2d(this, (reader) => this.a.read(reader).diffAlgorithm);
    this.showEmptyDecorations = $2d(this, (reader) => this.a.read(reader).experimental.showEmptyDecorations);
    this.onlyShowAccessibleDiffViewer = $2d(this, (reader) => this.a.read(reader).onlyShowAccessibleDiffViewer);
    this.compactMode = $2d(this, (reader) => this.a.read(reader).compactMode);
    this.e = $2d(this, (reader) => this.a.read(reader).experimental.useTrueInlineView);
    this.useTrueInlineDiffRendering = $2d(this, (reader) => !this.renderSideBySide.read(reader) && this.e.read(reader));
    this.hideUnchangedRegions = $2d(this, (reader) => this.a.read(reader).hideUnchangedRegions.enabled);
    this.hideUnchangedRegionsRevealLineCount = $2d(this, (reader) => this.a.read(reader).hideUnchangedRegions.revealLineCount);
    this.hideUnchangedRegionsContextLineCount = $2d(this, (reader) => this.a.read(reader).hideUnchangedRegions.contextLineCount);
    this.hideUnchangedRegionsMinimumLineCount = $2d(this, (reader) => this.a.read(reader).hideUnchangedRegions.minimumLineCount);
    this.f = $he(this, void 0);
    this.g = this.f.map(this, (model) => $Vd(this, (reader) => {
      const diffs = model?.diff.read(reader);
      return diffs ? isSimpleDiff(diffs, this.e.read(reader)) : void 0;
    })).flatten().map(this, (v) => !!v);
    this.inlineViewHideOriginalLineNumbers = this.compactMode;
    const optionsCopy = { ...options3, ...validateDiffEditorOptions(options3, $M0) };
    this.a = $he(this, optionsCopy);
  }
  updateOptions(changedOptions) {
    const newDiffEditorOptions = validateDiffEditorOptions(changedOptions, this.a.get());
    const newOptions = { ...this.a.get(), ...changedOptions, ...newDiffEditorOptions };
    this.a.set(newOptions, void 0, { changedOptions });
  }
  setWidth(width2) {
    this.b.set(width2, void 0);
  }
  setModel(model) {
    this.f.set(model, void 0);
  }
};
$a$ = __decorate([
  __param(1, $ND)
], $a$);
function isSimpleDiff(diff3, supportsTrueDiffRendering) {
  return diff3.mappings.every((m) => isInsertion(m.lineRangeMapping) || isDeletion(m.lineRangeMapping) || supportsTrueDiffRendering && $$0(m.lineRangeMapping));
}
function isInsertion(mapping2) {
  return mapping2.original.length === 0;
}
function isDeletion(mapping2) {
  return mapping2.modified.length === 0;
}
function validateDiffEditorOptions(options3, defaults) {
  return {
    enableSplitViewResizing: boolean(options3.enableSplitViewResizing, defaults.enableSplitViewResizing),
    splitViewDefaultRatio: clampedFloat(options3.splitViewDefaultRatio, 0.5, 0.1, 0.9),
    renderSideBySide: boolean(options3.renderSideBySide, defaults.renderSideBySide),
    renderMarginRevertIcon: boolean(options3.renderMarginRevertIcon, defaults.renderMarginRevertIcon),
    maxComputationTime: clampedInt(
      options3.maxComputationTime,
      defaults.maxComputationTime,
      0,
      1073741824
      /* Constants.MAX_SAFE_SMALL_INTEGER */
    ),
    maxFileSize: clampedInt(
      options3.maxFileSize,
      defaults.maxFileSize,
      0,
      1073741824
      /* Constants.MAX_SAFE_SMALL_INTEGER */
    ),
    ignoreTrimWhitespace: boolean(options3.ignoreTrimWhitespace, defaults.ignoreTrimWhitespace),
    renderIndicators: boolean(options3.renderIndicators, defaults.renderIndicators),
    originalEditable: boolean(options3.originalEditable, defaults.originalEditable),
    diffCodeLens: boolean(options3.diffCodeLens, defaults.diffCodeLens),
    renderOverviewRuler: boolean(options3.renderOverviewRuler, defaults.renderOverviewRuler),
    diffWordWrap: stringSet(options3.diffWordWrap, defaults.diffWordWrap, ["off", "on", "inherit"]),
    diffAlgorithm: stringSet(options3.diffAlgorithm, defaults.diffAlgorithm, ["legacy", "advanced"], { "smart": "legacy", "experimental": "advanced" }),
    accessibilityVerbose: boolean(options3.accessibilityVerbose, defaults.accessibilityVerbose),
    experimental: {
      showMoves: boolean(options3.experimental?.showMoves, defaults.experimental.showMoves),
      showEmptyDecorations: boolean(options3.experimental?.showEmptyDecorations, defaults.experimental.showEmptyDecorations),
      useTrueInlineView: boolean(options3.experimental?.useTrueInlineView, defaults.experimental.useTrueInlineView)
    },
    hideUnchangedRegions: {
      enabled: boolean(options3.hideUnchangedRegions?.enabled ?? options3.experimental?.collapseUnchangedRegions, defaults.hideUnchangedRegions.enabled),
      contextLineCount: clampedInt(
        options3.hideUnchangedRegions?.contextLineCount,
        defaults.hideUnchangedRegions.contextLineCount,
        0,
        1073741824
        /* Constants.MAX_SAFE_SMALL_INTEGER */
      ),
      minimumLineCount: clampedInt(
        options3.hideUnchangedRegions?.minimumLineCount,
        defaults.hideUnchangedRegions.minimumLineCount,
        0,
        1073741824
        /* Constants.MAX_SAFE_SMALL_INTEGER */
      ),
      revealLineCount: clampedInt(
        options3.hideUnchangedRegions?.revealLineCount,
        defaults.hideUnchangedRegions.revealLineCount,
        0,
        1073741824
        /* Constants.MAX_SAFE_SMALL_INTEGER */
      )
    },
    isInEmbeddedEditor: boolean(options3.isInEmbeddedEditor, defaults.isInEmbeddedEditor),
    onlyShowAccessibleDiffViewer: boolean(options3.onlyShowAccessibleDiffViewer, defaults.onlyShowAccessibleDiffViewer),
    renderSideBySideInlineBreakpoint: clampedInt(
      options3.renderSideBySideInlineBreakpoint,
      defaults.renderSideBySideInlineBreakpoint,
      0,
      1073741824
      /* Constants.MAX_SAFE_SMALL_INTEGER */
    ),
    useInlineViewWhenSpaceIsLimited: boolean(options3.useInlineViewWhenSpaceIsLimited, defaults.useInlineViewWhenSpaceIsLimited),
    renderGutterMenu: boolean(options3.renderGutterMenu, defaults.renderGutterMenu),
    compactMode: boolean(options3.compactMode, defaults.compactMode)
  };
}

// out-build/vs/base/browser/ui/dropdown/dropdown.js
var BaseDropdown = class extends $Vm {
  constructor(container2, options3) {
    super();
    this.j = this.B(new $ze());
    this.onDidChangeVisibility = this.j.event;
    this.a = $bk(container2, $(".monaco-dropdown"));
    this.c = $bk(this.a, $(".dropdown-label"));
    let labelRenderer = options3.labelRenderer;
    if (!labelRenderer) {
      labelRenderer = (container3) => {
        container3.textContent = options3.label || "";
        return null;
      };
    }
    for (const event of [$7j.CLICK, $7j.MOUSE_DOWN, EventType.Tap]) {
      this.B($_i(this.element, event, (e) => $9j.stop(e, true)));
    }
    for (const event of [$7j.MOUSE_DOWN, EventType.Tap]) {
      this.B($_i(this.c, event, (e) => {
        if ($3j(e) && (e.detail > 1 || e.button !== 0)) {
          return;
        }
        if (this.h) {
          this.hide();
        } else {
          this.show();
        }
      }));
    }
    this.B($_i(this.c, $7j.KEY_UP, (e) => {
      const event = new $if(e);
      if (event.equals(
        3
        /* KeyCode.Enter */
      ) || event.equals(
        10
        /* KeyCode.Space */
      )) {
        $9j.stop(e, true);
        if (this.h) {
          this.hide();
        } else {
          this.show();
        }
      }
    }));
    const cleanupFn = labelRenderer(this.c);
    if (cleanupFn) {
      this.B(cleanupFn);
    }
    this.B($mZ.addTarget(this.c));
  }
  get element() {
    return this.a;
  }
  get label() {
    return this.c;
  }
  set tooltip(tooltip) {
    if (this.c) {
      if (!this.n && tooltip !== "") {
        this.n = this.B($J1().setupManagedHover($JZ("mouse"), this.c, tooltip));
      } else if (this.n) {
        this.n.update(tooltip);
      }
    }
  }
  show() {
    if (!this.h) {
      this.h = true;
      this.j.fire(true);
    }
  }
  hide() {
    if (this.h) {
      this.h = false;
      this.j.fire(false);
    }
  }
  isVisible() {
    return !!this.h;
  }
  r(_e, activeElement) {
    this.hide();
  }
  dispose() {
    super.dispose();
    this.hide();
    if (this.b) {
      this.b.remove();
      this.b = void 0;
    }
    if (this.g) {
      this.g.remove();
      this.g = void 0;
    }
    if (this.c) {
      this.c.remove();
      this.c = void 0;
    }
  }
};
var $i2 = class extends BaseDropdown {
  constructor(container2, w) {
    super(container2, w);
    this.w = w;
    this.t = [];
    this.y = w.actions || [];
  }
  set menuOptions(options3) {
    this.s = options3;
  }
  get menuOptions() {
    return this.s;
  }
  get y() {
    if (this.w.actionProvider) {
      return this.w.actionProvider.getActions();
    }
    return this.t;
  }
  set y(actions) {
    this.t = actions;
  }
  show() {
    super.show();
    this.element.classList.add("active");
    this.w.contextMenuProvider.showContextMenu({
      getAnchor: () => this.element,
      getActions: () => this.y,
      getActionsContext: () => this.menuOptions ? this.menuOptions.context : null,
      getActionViewItem: (action, options3) => this.menuOptions && this.menuOptions.actionViewItemProvider ? this.menuOptions.actionViewItemProvider(action, options3) : void 0,
      getKeyBinding: (action) => this.menuOptions && this.menuOptions.getKeyBinding ? this.menuOptions.getKeyBinding(action) : void 0,
      getMenuClassName: () => this.w.menuClassName || "",
      onHide: () => this.z(),
      actionRunner: this.menuOptions ? this.menuOptions.actionRunner : void 0,
      anchorAlignment: this.menuOptions ? this.menuOptions.anchorAlignment : 0,
      domForShadowRoot: this.w.menuAsChild ? this.element : void 0,
      skipTelemetry: this.w.skipTelemetry
    });
  }
  hide() {
    super.hide();
  }
  z() {
    this.hide();
    this.element.classList.remove("active");
  }
};

// out-build/vs/base/browser/ui/dropdown/dropdownActionViewItem.js
var $L2 = class extends $T1 {
  constructor(action, menuActionsOrProvider, contextMenuProvider, options3 = /* @__PURE__ */ Object.create(null)) {
    super(null, action, options3);
    this.t = null;
    this.y = this.B(new $ze());
    this.onDidChangeVisibility = this.y.event;
    this.b = menuActionsOrProvider;
    this.n = contextMenuProvider;
    this.u = options3;
    if (this.u.actionRunner) {
      this.actionRunner = this.u.actionRunner;
    }
  }
  render(container2) {
    this.t = container2;
    const labelRenderer = (el) => {
      this.element = $bk(el, $("a.action-label"));
      let classNames = [];
      if (typeof this.u.classNames === "string") {
        classNames = this.u.classNames.split(/\s+/g).filter((s) => !!s);
      } else if (this.u.classNames) {
        classNames = this.u.classNames;
      }
      if (!classNames.find((c) => c === "icon")) {
        classNames.push("codicon");
      }
      this.element.classList.add(...classNames);
      this.element.setAttribute("role", "button");
      this.element.setAttribute("aria-haspopup", "true");
      this.element.setAttribute("aria-expanded", "false");
      if (this._action.label) {
        this.B($J1().setupManagedHover(this.u.hoverDelegate ?? $JZ("mouse"), this.element, this._action.label));
      }
      this.element.ariaLabel = this._action.label || "";
      return null;
    };
    const isActionsArray = Array.isArray(this.b);
    const options3 = {
      contextMenuProvider: this.n,
      labelRenderer,
      menuAsChild: this.u.menuAsChild,
      actions: isActionsArray ? this.b : void 0,
      actionProvider: isActionsArray ? void 0 : this.b,
      skipTelemetry: this.u.skipTelemetry
    };
    this.m = this.B(new $i2(container2, options3));
    this.B(this.m.onDidChangeVisibility((visible) => {
      this.element?.setAttribute("aria-expanded", `${visible}`);
      this.y.fire(visible);
    }));
    this.m.menuOptions = {
      actionViewItemProvider: this.u.actionViewItemProvider,
      actionRunner: this.actionRunner,
      getKeyBinding: this.u.keybindingProvider,
      context: this._context
    };
    if (this.u.anchorAlignmentProvider) {
      const that = this;
      this.m.menuOptions = {
        ...this.m.menuOptions,
        get anchorAlignment() {
          return that.u.anchorAlignmentProvider();
        }
      };
    }
    this.G();
    this.z();
  }
  F() {
    let title = null;
    if (this.action.tooltip) {
      title = this.action.tooltip;
    } else if (this.action.label) {
      title = this.action.label;
    }
    return title ?? void 0;
  }
  setActionContext(newContext) {
    super.setActionContext(newContext);
    if (this.m) {
      if (this.m.menuOptions) {
        this.m.menuOptions.context = newContext;
      } else {
        this.m.menuOptions = { context: newContext };
      }
    }
  }
  show() {
    this.m?.show();
  }
  z() {
    const disabled = !this.action.enabled;
    this.t?.classList.toggle("disabled", disabled);
    this.element?.classList.toggle("disabled", disabled);
  }
};
var $M2 = class extends $U1 {
  constructor(context, action, options3, m) {
    super(context, action, options3);
    this.m = m;
  }
  render(container2) {
    super.render(container2);
    if (this.element) {
      this.element.classList.add("action-dropdown-item");
      const menuActionsProvider = {
        getActions: () => {
          const actionsProvider = this.u.menuActionsOrProvider;
          return Array.isArray(actionsProvider) ? actionsProvider : actionsProvider.getActions();
        }
      };
      const menuActionClassNames = this.u.menuActionClassNames || [];
      const separator = h("div.action-dropdown-item-separator", [h("div", {})]).root;
      separator.classList.toggle("prominent", menuActionClassNames.includes("prominent"));
      $bk(this.element, separator);
      this.g = this.B(new $L2(this.B(new $Um("dropdownAction", localize(8, null))), menuActionsProvider, this.m, { classNames: ["dropdown", ...ThemeIcon.asClassNameArray($6l.dropDownButton), ...menuActionClassNames], hoverDelegate: this.u.hoverDelegate }));
      this.g.render(this.element);
      this.B($_i(this.element, $7j.KEY_DOWN, (e) => {
        if (menuActionsProvider.getActions().length === 0) {
          return;
        }
        const event = new $if(e);
        let handled = false;
        if (this.g?.isFocused() && event.equals(
          15
          /* KeyCode.LeftArrow */
        )) {
          handled = true;
          this.g?.blur();
          this.focus();
        } else if (this.isFocused() && event.equals(
          17
          /* KeyCode.RightArrow */
        )) {
          handled = true;
          this.blur();
          this.g?.focus();
        }
        if (handled) {
          event.preventDefault();
          event.stopPropagation();
        }
      }));
    }
  }
  blur() {
    super.blur();
    this.g?.blur();
  }
  setFocusable(focusable) {
    super.setFocusable(focusable);
    this.g?.setFocusable(focusable);
  }
};

// out-build/vs/base/browser/ui/toolbar/toolbar.js
var $f3 = class extends $3c {
  constructor(container2, contextMenuProvider, options3 = {
    orientation: 0
    /* ActionsOrientation.HORIZONTAL */
  }) {
    super();
    this.u = [];
    this.w = false;
    this.z = this.B(new $Fe());
    this.onDidChangeDropdownVisibility = this.z.event;
    this.C = this.B(new $2c());
    options3.hoverDelegate = options3.hoverDelegate ?? this.B($KZ());
    this.f = options3;
    this.n = this.B(new $g3(() => this.t?.show(), options3.toggleMenuTitle));
    this.y = document.createElement("div");
    this.y.className = "monaco-toolbar";
    container2.appendChild(this.y);
    this.m = this.B(new $LZ(this.y, {
      orientation: options3.orientation,
      ariaLabel: options3.ariaLabel,
      actionRunner: options3.actionRunner,
      allowContextMenu: options3.allowContextMenu,
      highlightToggledItems: options3.highlightToggledItems,
      hoverDelegate: options3.hoverDelegate,
      actionViewItemProvider: (action, viewItemOptions) => {
        if (action.id === $g3.ID) {
          this.t = new $L2(action, action.menuActions, contextMenuProvider, {
            actionViewItemProvider: this.f.actionViewItemProvider,
            actionRunner: this.actionRunner,
            keybindingProvider: this.f.getKeyBinding,
            classNames: ThemeIcon.asClassNameArray(options3.moreIcon ?? $6l.toolBarMore),
            anchorAlignmentProvider: this.f.anchorAlignmentProvider,
            menuAsChild: !!this.f.renderDropdownAsChildElement,
            skipTelemetry: this.f.skipTelemetry,
            isMenu: true,
            hoverDelegate: this.f.hoverDelegate
          });
          this.t.setActionContext(this.m.context);
          this.C.add(this.z.add(this.t.onDidChangeVisibility));
          return this.t;
        }
        if (options3.actionViewItemProvider) {
          const result = options3.actionViewItemProvider(action, viewItemOptions);
          if (result) {
            return result;
          }
        }
        if (action instanceof $Xm) {
          const result = new $L2(action, action.actions, contextMenuProvider, {
            actionViewItemProvider: this.f.actionViewItemProvider,
            actionRunner: this.actionRunner,
            keybindingProvider: this.f.getKeyBinding,
            classNames: action.class,
            anchorAlignmentProvider: this.f.anchorAlignmentProvider,
            menuAsChild: !!this.f.renderDropdownAsChildElement,
            skipTelemetry: this.f.skipTelemetry,
            hoverDelegate: this.f.hoverDelegate
          });
          result.setActionContext(this.m.context);
          this.u.push(result);
          this.C.add(this.z.add(result.onDidChangeVisibility));
          return result;
        }
        return void 0;
      }
    }));
  }
  set actionRunner(actionRunner) {
    this.m.actionRunner = actionRunner;
  }
  get actionRunner() {
    return this.m.actionRunner;
  }
  set context(context) {
    this.m.context = context;
    this.t?.setActionContext(context);
    for (const actionViewItem of this.u) {
      actionViewItem.setActionContext(context);
    }
  }
  getElement() {
    return this.y;
  }
  focus() {
    this.m.focus();
  }
  getItemsWidth() {
    let itemsWidth = 0;
    for (let i2 = 0; i2 < this.m.length(); i2++) {
      itemsWidth += this.m.getWidth(i2);
    }
    return itemsWidth;
  }
  getItemAction(indexOrElement) {
    return this.m.getAction(indexOrElement);
  }
  getItemWidth(index) {
    return this.m.getWidth(index);
  }
  getItemsLength() {
    return this.m.length();
  }
  setAriaLabel(label3) {
    this.m.setAriaLabel(label3);
  }
  setActions(primaryActions, secondaryActions) {
    this.F();
    const primaryActionsToSet = primaryActions ? primaryActions.slice(0) : [];
    this.w = !!(secondaryActions && secondaryActions.length > 0);
    if (this.w && secondaryActions) {
      this.n.menuActions = secondaryActions.slice(0);
      primaryActionsToSet.push(this.n);
    }
    primaryActionsToSet.forEach((action) => {
      this.m.push(action, { icon: this.f.icon ?? true, label: this.f.label ?? false, keybinding: this.D(action) });
    });
  }
  isEmpty() {
    return this.m.isEmpty();
  }
  D(action) {
    const key2 = this.f.getKeyBinding?.(action);
    return key2?.getLabel() ?? void 0;
  }
  F() {
    this.u = [];
    this.C.clear();
    this.m.clear();
  }
  dispose() {
    this.F();
    this.C.dispose();
    super.dispose();
  }
};
var $g3 = class _$g3 extends $Um {
  static {
    this.ID = "toolbar.toggle.more";
  }
  constructor(toggleDropdownMenu, title) {
    title = title || localize(30, null);
    super(_$g3.ID, title, void 0, true);
    this.a = [];
    this.b = toggleDropdownMenu;
  }
  async run() {
    this.b();
  }
  get menuActions() {
    return this.a;
  }
  set menuActions(actions) {
    this.a = actions;
  }
};

// out-build/vs/base/common/keybindingLabels.js
var $W2 = class {
  constructor(mac, windows, linux = windows) {
    this.modifierLabels = [null];
    this.modifierLabels[
      2
      /* OperatingSystem.Macintosh */
    ] = mac;
    this.modifierLabels[
      1
      /* OperatingSystem.Windows */
    ] = windows;
    this.modifierLabels[
      3
      /* OperatingSystem.Linux */
    ] = linux;
  }
  toLabel(OS2, chords, keyLabelProvider) {
    if (chords.length === 0) {
      return null;
    }
    const result = [];
    for (let i2 = 0, len = chords.length; i2 < len; i2++) {
      const chord = chords[i2];
      const keyLabel = keyLabelProvider(chord);
      if (keyLabel === null) {
        return null;
      }
      result[i2] = _simpleAsString(chord, keyLabel, this.modifierLabels[OS2]);
    }
    return result.join(" ");
  }
};
var $X2 = new $W2({
  ctrlKey: "\u2303",
  shiftKey: "\u21E7",
  altKey: "\u2325",
  metaKey: "\u2318",
  separator: ""
}, {
  ctrlKey: localize(125, null),
  shiftKey: localize(126, null),
  altKey: localize(127, null),
  metaKey: localize(128, null),
  separator: "+"
}, {
  ctrlKey: localize(129, null),
  shiftKey: localize(130, null),
  altKey: localize(131, null),
  metaKey: localize(132, null),
  separator: "+"
});
var $Y2 = new $W2({
  ctrlKey: localize(133, null),
  shiftKey: localize(134, null),
  altKey: localize(135, null),
  metaKey: localize(136, null),
  separator: "+"
}, {
  ctrlKey: localize(137, null),
  shiftKey: localize(138, null),
  altKey: localize(139, null),
  metaKey: localize(140, null),
  separator: "+"
}, {
  ctrlKey: localize(141, null),
  shiftKey: localize(142, null),
  altKey: localize(143, null),
  metaKey: localize(144, null),
  separator: "+"
});
var $Z2 = new $W2({
  ctrlKey: "Ctrl",
  shiftKey: "Shift",
  altKey: "Alt",
  metaKey: "Cmd",
  separator: "+"
}, {
  ctrlKey: "Ctrl",
  shiftKey: "Shift",
  altKey: "Alt",
  metaKey: "Super",
  separator: "+"
});
var $12 = new $W2({
  ctrlKey: "ctrl",
  shiftKey: "shift",
  altKey: "alt",
  metaKey: "cmd",
  separator: "+"
}, {
  ctrlKey: "ctrl",
  shiftKey: "shift",
  altKey: "alt",
  metaKey: "win",
  separator: "+"
}, {
  ctrlKey: "ctrl",
  shiftKey: "shift",
  altKey: "alt",
  metaKey: "meta",
  separator: "+"
});
function _simpleAsString(modifiers, key2, labels2) {
  if (key2 === null) {
    return "";
  }
  const result = [];
  if (modifiers.ctrlKey) {
    result.push(labels2.ctrlKey);
  }
  if (modifiers.shiftKey) {
    result.push(labels2.shiftKey);
  }
  if (modifiers.altKey) {
    result.push(labels2.altKey);
  }
  if (modifiers.metaKey) {
    result.push(labels2.metaKey);
  }
  if (key2 !== "") {
    result.push(key2);
  }
  return result.join(labels2.separator);
}

// out-build/vs/platform/action/common/action.js
function $un(thing) {
  return thing && typeof thing === "object" && typeof thing.original === "string" && typeof thing.value === "string";
}
function $vn(thing) {
  return thing ? thing.condition !== void 0 : false;
}

// out-build/vs/base/common/performance.js
function _definePolyfillMarks(timeOrigin) {
  const _data = [];
  if (typeof timeOrigin === "number") {
    _data.push("code/timeOrigin", timeOrigin);
  }
  function mark(name, markOptions) {
    _data.push(name, markOptions?.startTime ?? Date.now());
  }
  function getMarks() {
    const result = [];
    for (let i2 = 0; i2 < _data.length; i2 += 2) {
      result.push({
        name: _data[i2],
        startTime: _data[i2 + 1]
      });
    }
    return result;
  }
  return { mark, getMarks };
}
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, markOptions) {
          performance.mark(name, markOptions);
        },
        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(sharedObj) {
  if (!sharedObj.MonacoPerformanceMarks) {
    sharedObj.MonacoPerformanceMarks = _define();
  }
  return sharedObj.MonacoPerformanceMarks;
}
var perf = _factory(globalThis);
var $S = perf.mark;
var $T = perf.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 = {}));
function $ev(thing) {
  const candidate = thing;
  return candidate?.changed instanceof Map || candidate?.deleted instanceof Set;
}
var StorageState;
(function(StorageState2) {
  StorageState2[StorageState2["None"] = 0] = "None";
  StorageState2[StorageState2["Initialized"] = 1] = "Initialized";
  StorageState2[StorageState2["Closed"] = 2] = "Closed";
})(StorageState || (StorageState = {}));
var $fv = class _$fv extends $3c {
  static {
    this.a = 100;
  }
  constructor(r2, s = /* @__PURE__ */ Object.create(null)) {
    super();
    this.r = r2;
    this.s = s;
    this.b = this.B(new $Ce());
    this.onDidChangeStorage = this.b.event;
    this.c = StorageState.None;
    this.f = /* @__PURE__ */ new Map();
    this.g = this.B(new $Th(_$fv.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, key2) => this.w(key2, value));
      e.deleted?.forEach((key2) => this.w(key2, void 0));
    } finally {
      this.b.resume();
    }
  }
  w(key2, value) {
    if (this.c === StorageState.Closed) {
      return;
    }
    let changed = false;
    if ($Ig(value)) {
      changed = this.f.delete(key2);
    } else {
      const currentValue = this.f.get(key2);
      if (currentValue !== value) {
        this.f.set(key2, value);
        changed = true;
      }
    }
    if (changed) {
      this.b.fire({ key: key2, 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(key2, fallbackValue) {
    const value = this.f.get(key2);
    if ($Ig(value)) {
      return fallbackValue;
    }
    return value;
  }
  getBoolean(key2, fallbackValue) {
    const value = this.get(key2);
    if ($Ig(value)) {
      return fallbackValue;
    }
    return value === "true";
  }
  getNumber(key2, fallbackValue) {
    const value = this.get(key2);
    if ($Ig(value)) {
      return fallbackValue;
    }
    return parseInt(value, 10);
  }
  getObject(key2, fallbackValue) {
    const value = this.get(key2);
    if ($Ig(value)) {
      return fallbackValue;
    }
    return $bu(value);
  }
  async set(key2, value, external = false) {
    if (this.c === StorageState.Closed) {
      return;
    }
    if ($Ig(value)) {
      return this.delete(key2, external);
    }
    const valueStr = $Bg(value) || Array.isArray(value) ? $au(value) : String(value);
    const currentValue = this.f.get(key2);
    if (currentValue === valueStr) {
      return;
    }
    this.f.set(key2, valueStr);
    this.j.set(key2, valueStr);
    this.h.delete(key2);
    this.b.fire({ key: key2, external });
    return this.D();
  }
  async delete(key2, external = false) {
    if (this.c === StorageState.Closed) {
      return;
    }
    const wasDeleted = this.f.delete(key2);
    if (!wasDeleted) {
      return;
    }
    if (!this.h.has(key2)) {
      this.h.add(key2);
    }
    this.j.delete(key2);
    this.b.fire({ key: key2, 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;
  }
};
var $gv = class {
  constructor() {
    this.onDidChangeItemsExternal = Event2.None;
    this.a = /* @__PURE__ */ new Map();
  }
  async getItems() {
    return this.a;
  }
  async updateItems(request) {
    request.insert?.forEach((value, key2) => this.a.set(key2, value));
    request.delete?.forEach((key2) => this.a.delete(key2));
  }
  async optimize() {
  }
  async close() {
  }
};

// out-build/vs/platform/environment/common/environment.js
var $Xk = $Qk("environmentService");
var $Yk = $Rk($Xk);

// out-build/vs/base/common/ternarySearchTree.js
var $Sk = class {
  constructor() {
    this.b = "";
    this.c = 0;
  }
  reset(key2) {
    this.b = key2;
    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 $Tk = class {
  constructor(e = true) {
    this.e = e;
  }
  reset(key2) {
    this.b = key2;
    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 ? $Uf(a, this.b, 0, a.length, this.c, this.d) : $Wf(a, this.b, 0, a.length, this.c, this.d);
  }
  value() {
    return this.b.substring(this.c, this.d);
  }
};
var $Uk = class {
  constructor(f = true, g = true) {
    this.f = f;
    this.g = g;
  }
  reset(key2) {
    this.d = 0;
    this.e = 0;
    this.b = key2;
    this.c = key2.length;
    for (let pos = key2.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 ? $Uf(a, this.b, 0, a.length, this.d, this.e) : $Wf(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 $Vk = class {
  constructor(f, g) {
    this.f = f;
    this.g = g;
    this.d = [];
    this.e = 0;
  }
  reset(key2) {
    this.c = key2;
    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 $Uk(false, !this.f(key2));
      this.b.reset(key2.path);
      if (this.b.value()) {
        this.d.push(
          3
          /* UriIteratorState.Path */
        );
      }
    }
    if (!this.g(key2)) {
      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 $Vf(a, this.c.scheme);
    } else if (this.d[this.e] === 2) {
      return $Vf(a, this.c.authority);
    } else if (this.d[this.e] === 3) {
      return this.b.cmp(a);
    } else if (this.d[this.e] === 4) {
      return $Tf(a, this.c.query);
    } else if (this.d[this.e] === 5) {
      return $Tf(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 $Wk = class _$Wk {
  static forUris(ignorePathCasing = () => false, ignoreQueryAndFragment = () => false) {
    return new _$Wk(new $Vk(ignorePathCasing, ignoreQueryAndFragment));
  }
  static forPaths(ignorePathCasing = false) {
    return new _$Wk(new $Uk(void 0, !ignorePathCasing));
  }
  static forStrings() {
    return new _$Wk(new $Sk());
  }
  static forConfigKeys() {
    return new _$Wk(new $Tk());
  }
  constructor(segments) {
    this.b = segments;
  }
  clear() {
    this.c = void 0;
  }
  fill(values, keys) {
    if (keys) {
      const arr = keys.slice(0);
      $Zb(arr);
      for (const k of arr) {
        this.set(k, values);
      }
    } else {
      const arr = values.slice(0);
      $Zb(arr);
      for (const entry of arr) {
        this.set(entry[0], entry[1]);
      }
    }
  }
  set(key2, element) {
    const iter = this.b.reset(key2);
    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 = key2;
    for (let i2 = stack.length - 1; i2 >= 0; i2--) {
      const node2 = stack[i2][1];
      node2.updateHeight();
      const bf = node2.balanceFactor();
      if (bf < -1 || bf > 1) {
        const d1 = stack[i2][0];
        const d2 = stack[i2 + 1][0];
        if (d1 === 1 && d2 === 1) {
          stack[i2][1] = node2.rotateLeft();
        } else if (d1 === -1 && d2 === -1) {
          stack[i2][1] = node2.rotateRight();
        } else if (d1 === 1 && d2 === -1) {
          node2.right = stack[i2 + 1][1] = stack[i2 + 1][1].rotateRight();
          stack[i2][1] = node2.rotateLeft();
        } else if (d1 === -1 && d2 === 1) {
          node2.left = stack[i2 + 1][1] = stack[i2 + 1][1].rotateLeft();
          stack[i2][1] = node2.rotateRight();
        } else {
          throw new Error();
        }
        if (i2 > 0) {
          switch (stack[i2 - 1][0]) {
            case -1:
              stack[i2 - 1][1].left = stack[i2][1];
              break;
            case 1:
              stack[i2 - 1][1].right = stack[i2][1];
              break;
            case 0:
              stack[i2 - 1][1].mid = stack[i2][1];
              break;
          }
        } else {
          this.c = stack[0][1];
        }
      }
    }
    return oldElement;
  }
  get(key2) {
    return this.d(key2)?.value;
  }
  d(key2) {
    const iter = this.b.reset(key2);
    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(key2) {
    const node = this.d(key2);
    return !(node?.value === void 0 && node?.mid === void 0);
  }
  delete(key2) {
    return this.e(key2, false);
  }
  deleteSuperstr(key2) {
    return this.e(key2, true);
  }
  e(key2, superStr) {
    const iter = this.b.reset(key2);
    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: key3, value, segment } = min;
          this.e(min.key, false);
          node.key = key3;
          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 i2 = stack.length - 1; i2 >= 0; i2--) {
      const node2 = stack[i2][1];
      node2.updateHeight();
      const bf = node2.balanceFactor();
      if (bf > 1) {
        if (node2.right.balanceFactor() >= 0) {
          stack[i2][1] = node2.rotateLeft();
        } else {
          node2.right = node2.right.rotateRight();
          stack[i2][1] = node2.rotateLeft();
        }
      } else if (bf < -1) {
        if (node2.left.balanceFactor() <= 0) {
          stack[i2][1] = node2.rotateRight();
        } else {
          node2.left = node2.left.rotateLeft();
          stack[i2][1] = node2.rotateRight();
        }
      }
      if (i2 > 0) {
        switch (stack[i2 - 1][0]) {
          case -1:
            stack[i2 - 1][1].left = stack[i2][1];
            break;
          case 1:
            stack[i2 - 1][1].right = stack[i2][1];
            break;
          case 0:
            stack[i2 - 1][1].mid = stack[i2][1];
            break;
        }
      } else {
        this.c = stack[0][1];
      }
    }
  }
  f(node) {
    while (node.left) {
      node = node.left;
    }
    return node;
  }
  findSubstr(key2) {
    const iter = this.b.reset(key2);
    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(key2) {
    return this.g(key2, false);
  }
  g(key2, allowValue) {
    const iter = this.b.reset(key2);
    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(key2) {
    return this.g(key2, true) !== void 0;
  }
  forEach(callback) {
    for (const [key2, value] of this) {
      callback(value, key2);
    }
  }
  *[Symbol.iterator]() {
    yield* this.h(this.c);
  }
  h(node) {
    const result = [];
    this.j(node, result);
    return result[Symbol.iterator]();
  }
  j(node, bucket) {
    if (!node) {
      return;
    }
    if (node.left) {
      this.j(node.left, bucket);
    }
    if (node.value) {
      bucket.push([node.key, node.value]);
    }
    if (node.mid) {
      this.j(node.mid, bucket);
    }
    if (node.right) {
      this.j(node.right, bucket);
    }
  }
  // for debug/testing
  _isBalanced() {
    const nodeIsBalanced = (node) => {
      if (!node) {
        return true;
      }
      const bf = node.balanceFactor();
      if (bf < -1 || bf > 1) {
        return false;
      }
      return nodeIsBalanced(node.left) && nodeIsBalanced(node.right);
    };
    return nodeIsBalanced(this.c);
  }
};

// out-build/vs/platform/files/common/files.js
var $km = $Qk("fileService");
var FileType;
(function(FileType3) {
  FileType3[FileType3["Unknown"] = 0] = "Unknown";
  FileType3[FileType3["File"] = 1] = "File";
  FileType3[FileType3["Directory"] = 2] = "Directory";
  FileType3[FileType3["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 $nm(provider) {
  return !!(provider.capabilities & 2);
}
function $om(provider) {
  return !!(provider.capabilities & 8);
}
function $pm(provider) {
  return !!(provider.capabilities & 131072);
}
function $qm(provider) {
  return !!(provider.capabilities & 4);
}
function $rm(provider) {
  return !!(provider.capabilities & 16);
}
function $sm(provider) {
  if (!$nm(provider)) {
    return false;
  }
  return !!(provider.capabilities & 16384);
}
function $tm(provider) {
  if (!$nm(provider)) {
    return false;
  }
  return !!(provider.capabilities & 32768);
}
function $um(provider) {
  return !!(provider.capabilities & 65536);
}
function $vm(provider) {
  return !!(provider.capabilities & 2048);
}
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 $wm = class _$wm extends Error {
  static create(error, code) {
    const providerError = new _$wm(error.toString(), code);
    $zm(providerError, code);
    return providerError;
  }
  constructor(message, code) {
    super(message);
    this.code = code;
  }
};
function $xm(error, code) {
  return $wm.create(error, code);
}
function $ym(error) {
  if (!error) {
    return $xm(localize(1910, null), FileSystemProviderErrorCode.Unknown);
  }
  return error;
}
function $zm(error, code) {
  error.name = code ? `${code} (FileSystemError)` : `FileSystemError`;
  return error;
}
function $Am(error) {
  if (!error) {
    return FileSystemProviderErrorCode.Unknown;
  }
  if (error instanceof $wm) {
    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 $Bm(error) {
  if (error instanceof $Fm) {
    return error.fileOperationResult;
  }
  switch ($Am(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 $Cm = class {
  constructor(resource, operation, target) {
    this.resource = resource;
    this.operation = operation;
    this.target = target;
  }
  isOperation(operation) {
    return this.operation === operation;
  }
};
var FileChangeType;
(function(FileChangeType3) {
  FileChangeType3[FileChangeType3["UPDATED"] = 0] = "UPDATED";
  FileChangeType3[FileChangeType3["ADDED"] = 1] = "ADDED";
  FileChangeType3[FileChangeType3["DELETED"] = 2] = "DELETED";
})(FileChangeType || (FileChangeType = {}));
var $Dm = class _$Dm {
  static {
    this.a = null;
  }
  constructor(changes, c) {
    this.c = c;
    this.b = void 0;
    this.d = new $sf(() => {
      const added = $Wk.forUris(() => this.c);
      added.fill(this.rawAdded.map((resource) => [resource, true]));
      return added;
    });
    this.f = new $sf(() => {
      const updated = $Wk.forUris(() => this.c);
      updated.fill(this.rawUpdated.map((resource) => [resource, true]));
      return updated;
    });
    this.g = new $sf(() => {
      const deleted = $Wk.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 !== _$Dm.a) {
        if (typeof change.cId === "number") {
          if (this.b === void 0) {
            this.b = change.cId;
          } else if (this.b !== change.cId) {
            this.b = _$Dm.a;
          }
        } else {
          if (this.b !== void 0) {
            this.b = _$Dm.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, options3, ...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 (options3.includeChildren && this.d.value.findSuperstr(resource)) {
        return true;
      }
    }
    if (!hasTypesFilter || types.includes(
      0
      /* FileChangeType.UPDATED */
    )) {
      if (this.f.value.get(resource)) {
        return true;
      }
      if (options3.includeChildren && this.f.value.findSuperstr(resource)) {
        return true;
      }
    }
    if (!hasTypesFilter || types.includes(
      2
      /* FileChangeType.DELETED */
    )) {
      if (this.g.value.findSubstr(resource)) {
        return true;
      }
      if (options3.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";
  }
};
var $Fm = class extends Error {
  constructor(message, fileOperationResult, options3) {
    super(message);
    this.fileOperationResult = fileOperationResult;
    this.options = options3;
  }
};
var $Gm = class extends $Fm {
  constructor(message, fileOperationResult, size, options3) {
    super(message, fileOperationResult, options3);
    this.fileOperationResult = fileOperationResult;
    this.size = size;
  }
};
var $Hm = class extends $Fm {
  constructor(message, stat, options3) {
    super(message, 2, options3);
    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 $Im = {
  OFF: "off",
  AFTER_DELAY: "afterDelay",
  ON_FOCUS_CHANGE: "onFocusChange",
  ON_WINDOW_CHANGE: "onWindowChange"
};
var $Jm = {
  OFF: "off",
  ON_EXIT: "onExit",
  ON_EXIT_AND_WINDOW_CLOSE: "onExitAndWindowClose"
};
var $Km = "files.associations";
var $Lm = "files.exclude";
var $Mm = "files.readonlyInclude";
var $Nm = "files.readonlyExclude";
var $Om = "files.readonlyFromPermissions";
var FileKind;
(function(FileKind2) {
  FileKind2[FileKind2["FILE"] = 0] = "FILE";
  FileKind2[FileKind2["FOLDER"] = 1] = "FOLDER";
  FileKind2[FileKind2["ROOT_FOLDER"] = 2] = "ROOT_FOLDER";
})(FileKind || (FileKind = {}));
var $Pm = "";
function $Qm(stat) {
  if (typeof stat.size !== "number" || typeof stat.mtime !== "number") {
    return void 0;
  }
  return stat.mtime.toString(29) + stat.size.toString(31);
}
async function $Rm(file, fileService) {
  if (fileService.hasProvider(URI.from({ scheme: file.scheme }))) {
    return;
  }
  return new Promise((resolve) => {
    const disposable = fileService.onDidChangeFileSystemProviderRegistrations((e) => {
      if (e.scheme === file.scheme && e.added) {
        disposable.dispose();
        resolve();
      }
    });
  });
}
var $Sm = class _$Sm {
  static {
    this.KB = 1024;
  }
  static {
    this.MB = _$Sm.KB * _$Sm.KB;
  }
  static {
    this.GB = _$Sm.MB * _$Sm.KB;
  }
  static {
    this.TB = _$Sm.GB * _$Sm.KB;
  }
  static formatSize(size) {
    if (!$Dg(size)) {
      size = 0;
    }
    if (size < _$Sm.KB) {
      return localize(1911, null, size.toFixed(0));
    }
    if (size < _$Sm.MB) {
      return localize(1912, null, (size / _$Sm.KB).toFixed(2));
    }
    if (size < _$Sm.GB) {
      return localize(1913, null, (size / _$Sm.MB).toFixed(2));
    }
    if (size < _$Sm.TB) {
      return localize(1914, null, (size / _$Sm.GB).toFixed(2));
    }
    return localize(1915, null, (size / _$Sm.TB).toFixed(2));
  }
};
function $Tm(arg) {
  const isRemote = typeof arg === "string" || arg?.scheme === Schemas.vscodeRemote;
  const isLocal = typeof arg !== "string" && arg?.scheme === Schemas.file;
  if (isLocal) {
    return 1024 * $Sm.MB;
  }
  if (isRemote) {
    return 10 * $Sm.MB;
  }
  if ($r) {
    return 50 * $Sm.MB;
  }
  return 1024 * $Sm.MB;
}

// out-build/vs/platform/workspace/common/workspace.js
var $Zk = $Qk("contextService");
function $1k(obj) {
  const singleFolderIdentifier = obj;
  return typeof singleFolderIdentifier?.id === "string" && URI.isUri(singleFolderIdentifier.uri);
}
function $2k(obj) {
  const emptyWorkspaceIdentifier = obj;
  return typeof emptyWorkspaceIdentifier?.id === "string" && !$1k(obj) && !$6k(obj);
}
var $3k = { id: "ext-dev" };
var $4k = { id: "empty-window" };
function $5k(arg0, isExtensionDevelopment) {
  if (typeof arg0 === "string" || typeof arg0 === "undefined") {
    if (typeof arg0 === "string") {
      return {
        id: $rc(arg0)
      };
    }
    if (isExtensionDevelopment) {
      return $3k;
    }
    return $4k;
  }
  const workspace2 = arg0;
  if (workspace2.configuration) {
    return {
      id: workspace2.id,
      configPath: workspace2.configuration
    };
  }
  if (workspace2.folders.length === 1) {
    return {
      id: workspace2.id,
      uri: workspace2.folders[0].uri
    };
  }
  return {
    id: workspace2.id
  };
}
function $6k(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 = {}));
function $8k(thing) {
  const candidate = thing;
  return !!(candidate && typeof candidate === "object" && typeof candidate.id === "string" && Array.isArray(candidate.folders));
}
function $9k(thing) {
  const candidate = thing;
  return !!(candidate && typeof candidate === "object" && URI.isUri(candidate.uri) && typeof candidate.name === "string" && typeof candidate.toResource === "function");
}
var $0k = class {
  constructor(h3, folders, j, k, l) {
    this.h = h3;
    this.j = j;
    this.k = k;
    this.l = l;
    this.c = $Wk.forUris(this.l, () => true);
    this.folders = folders;
  }
  update(workspace2) {
    this.h = workspace2.id;
    this.k = workspace2.configuration;
    this.j = workspace2.transient;
    this.l = workspace2.l;
    this.folders = workspace2.folders;
  }
  get folders() {
    return this.g;
  }
  set folders(folders) {
    this.g = folders;
    this.n();
  }
  get id() {
    return this.h;
  }
  get transient() {
    return this.j;
  }
  get configuration() {
    return this.k;
  }
  set configuration(configuration2) {
    this.k = configuration2;
  }
  getFolder(resource) {
    if (!resource) {
      return null;
    }
    return this.c.findSubstr(resource) || null;
  }
  n() {
    this.c = $Wk.forUris(this.l, () => true);
    for (const folder of this.folders) {
      this.c.set(folder.uri, folder);
    }
  }
  toJSON() {
    return { id: this.id, folders: this.folders, transient: this.transient, configuration: this.configuration };
  }
};
var $$k = class {
  constructor(data, raw) {
    this.raw = raw;
    this.uri = data.uri;
    this.index = data.index;
    this.name = data.name;
  }
  toResource(relativePath) {
    return $vh(this.uri, relativePath);
  }
  toJSON() {
    return { uri: this.uri, name: this.name, index: this.index };
  }
};
function $_k(resource) {
  return new $$k({ uri: resource, index: 0, name: $rh(resource) }, { uri: resource.toString() });
}
var $al = "code-workspace";
var $bl = `.${$al}`;
var $cl = [{ name: localize(2536, null), extensions: [$al] }];
var $dl = "workspace.json";
function $el(path, environmentService) {
  return $mh.isEqualOrParent(path, environmentService.untitledWorkspacesHome);
}
function $fl(arg1) {
  let path;
  if (URI.isUri(arg1)) {
    path = arg1;
  } else {
    path = arg1.configuration;
  }
  return path?.scheme === Schemas.tmp;
}
var $gl = "4064f6ec-cb38-4ad0-af64-ee6467e63c82";
function $hl(workspace2) {
  return workspace2.id === $gl;
}
function $il(path, environmentService) {
  return !$el(path, environmentService) && !$fl(path);
}
function $jl(path) {
  const ext = typeof path === "string" ? $sc(path) : $th(path);
  return ext === $bl;
}

// out-build/vs/platform/uriIdentity/common/uriIdentity.js
var $vl = $Qk("IUriIdentityService");

// 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 $os(value) {
  return _UUIDPattern.test(value);
}
var $ps = 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 i2 = 0; i2 < bucket.length; i2++) {
        bucket[i2] = Math.floor(Math.random() * 256);
      }
      return bucket;
    };
  }
  const _data = new Uint8Array(16);
  const _hex = [];
  for (let i2 = 0; i2 < 256; i2++) {
    _hex.push(i2.toString(16).padStart(2, "0"));
  }
  return function generateUuid() {
    getRandomValues(_data);
    _data[6] = _data[6] & 15 | 64;
    _data[8] = _data[8] & 63 | 128;
    let i2 = 0;
    let result = "";
    result += _hex[_data[i2++]];
    result += _hex[_data[i2++]];
    result += _hex[_data[i2++]];
    result += _hex[_data[i2++]];
    result += "-";
    result += _hex[_data[i2++]];
    result += _hex[_data[i2++]];
    result += "-";
    result += _hex[_data[i2++]];
    result += _hex[_data[i2++]];
    result += "-";
    result += _hex[_data[i2++]];
    result += _hex[_data[i2++]];
    result += "-";
    result += _hex[_data[i2++]];
    result += _hex[_data[i2++]];
    result += _hex[_data[i2++]];
    result += _hex[_data[i2++]];
    result += _hex[_data[i2++]];
    result += _hex[_data[i2++]];
    return result;
  };
}();

// 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 $qs(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 $rs = $Qk("IUserDataProfilesService");
function $ss(profile, scheme) {
  return {
    id: profile.id,
    isDefault: profile.isDefault,
    name: profile.name,
    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 $ts(id2, name, location3, profilesCacheHome, options3, defaultProfile) {
  return {
    id: id2,
    name,
    location: location3,
    isDefault: false,
    icon: options3?.icon,
    globalStorageHome: defaultProfile && options3?.useDefaultFlags?.globalState ? defaultProfile.globalStorageHome : $vh(location3, "globalStorage"),
    settingsResource: defaultProfile && options3?.useDefaultFlags?.settings ? defaultProfile.settingsResource : $vh(location3, "settings.json"),
    keybindingsResource: defaultProfile && options3?.useDefaultFlags?.keybindings ? defaultProfile.keybindingsResource : $vh(location3, "keybindings.json"),
    tasksResource: defaultProfile && options3?.useDefaultFlags?.tasks ? defaultProfile.tasksResource : $vh(location3, "tasks.json"),
    snippetsHome: defaultProfile && options3?.useDefaultFlags?.snippets ? defaultProfile.snippetsHome : $vh(location3, "snippets"),
    extensionsResource: defaultProfile && options3?.useDefaultFlags?.extensions ? defaultProfile.extensionsResource : $vh(location3, "extensions.json"),
    cacheHome: $vh(profilesCacheHome, id2),
    useDefaultFlags: options3?.useDefaultFlags,
    isTransient: options3?.transient,
    workspaces: options3?.workspaces
  };
}
var $us = class $us2 extends $3c {
  static {
    this.b = "userDataProfiles";
  }
  static {
    this.c = "profileAssociations";
  }
  get defaultProfile() {
    return this.profiles[0];
  }
  get profiles() {
    return [...this.C.profiles, ...this.r.profiles];
  }
  constructor(s, t, u, y) {
    super();
    this.s = s;
    this.t = t;
    this.u = u;
    this.y = y;
    this.g = this.B(new $ze());
    this.onDidChangeProfiles = this.g.event;
    this.h = this.B(new $ze());
    this.onWillCreateProfile = this.h.event;
    this.j = this.B(new $ze());
    this.onWillRemoveProfile = this.j.event;
    this.m = this.B(new $ze());
    this.onDidResetWorkspaces = this.m.event;
    this.n = /* @__PURE__ */ new Map();
    this.r = {
      profiles: [],
      emptyWindows: /* @__PURE__ */ new Map()
    };
    this.profilesHome = $vh(this.s.userRoamingDataHome, "profiles");
    this.f = $vh(this.s.cacheHome, "CachedProfilesData");
  }
  init() {
    this.z = void 0;
  }
  get C() {
    if (!this.z) {
      const defaultProfile = this.D();
      const profiles2 = [defaultProfile];
      try {
        for (const storedProfile of this.N()) {
          if (!storedProfile.name || !$zg(storedProfile.name) || !storedProfile.location) {
            this.y.warn("Skipping the invalid stored profile", storedProfile.location || storedProfile.name);
            continue;
          }
          profiles2.push($ts($sh(storedProfile.location), storedProfile.name, storedProfile.location, this.f, { icon: storedProfile.icon, useDefaultFlags: storedProfile.useDefaultFlags }, defaultProfile));
        }
      } catch (error) {
        this.y.error(error);
      }
      const emptyWindows = /* @__PURE__ */ new Map();
      if (profiles2.length) {
        try {
          const profileAssociaitions = this.P();
          if (profileAssociaitions.workspaces) {
            for (const [workspacePath, profileId] of Object.entries(profileAssociaitions.workspaces)) {
              const workspace2 = URI.parse(workspacePath);
              const profile = profiles2.find((p) => p.id === profileId);
              if (profile) {
                const workspaces = profile.workspaces ? profile.workspaces.slice(0) : [];
                workspaces.push(workspace2);
                profile.workspaces = workspaces;
              }
            }
          }
          if (profileAssociaitions.emptyWindows) {
            for (const [windowId, profileId] of Object.entries(profileAssociaitions.emptyWindows)) {
              const profile = profiles2.find((p) => p.id === profileId);
              if (profile) {
                emptyWindows.set(windowId, profile);
              }
            }
          }
        } catch (error) {
          this.y.error(error);
        }
      }
      this.z = { profiles: profiles2, emptyWindows };
    }
    return this.z;
  }
  D() {
    const defaultProfile = $ts("__default__profile__", localize(2489, null), this.s.userRoamingDataHome, this.f);
    return { ...defaultProfile, extensionsResource: this.R() ?? 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($Xi($ps()).toString(16), name, { transient: true }, workspaceIdentifier);
  }
  async createNamedProfile(name, options3, workspaceIdentifier) {
    return this.createProfile($Xi($ps()).toString(16), name, options3, workspaceIdentifier);
  }
  async createProfile(id2, name, options3, workspaceIdentifier) {
    const profile = await this.F(id2, name, options3, workspaceIdentifier);
    return profile;
  }
  async F(id2, name, options3, workspaceIdentifier) {
    if (!$zg(name) || !name) {
      throw new Error("Name of the profile is mandatory and must be of type `string`");
    }
    let profileCreationPromise = this.n.get(name);
    if (!profileCreationPromise) {
      profileCreationPromise = (async () => {
        try {
          const existing = this.profiles.find((p) => p.id === id2 || !p.isTransient && !options3?.transient && p.name === name);
          if (existing) {
            throw new Error(`Profile with ${name} name already exists`);
          }
          const workspace2 = workspaceIdentifier ? this.G(workspaceIdentifier) : void 0;
          if (URI.isUri(workspace2)) {
            options3 = { ...options3, workspaces: [workspace2] };
          }
          const profile = $ts(id2, name, $vh(this.profilesHome, id2), this.f, options3, this.defaultProfile);
          await this.t.createFolder(profile.location);
          const joiners = [];
          this.h.fire({
            profile,
            join(promise) {
              joiners.push(promise);
            }
          });
          await Promises.settled(joiners);
          if (workspace2 && !URI.isUri(workspace2)) {
            this.L(workspace2, profile, !!profile.isTransient);
          }
          this.I([profile], [], []);
          return profile;
        } finally {
          this.n.delete(name);
        }
      })();
      this.n.set(name, profileCreationPromise);
    }
    return profileCreationPromise;
  }
  async updateProfile(profile, options3) {
    const profilesToUpdate = [];
    for (const existing of this.profiles) {
      let profileToUpdate;
      if (profile.id === existing.id) {
        if (!existing.isDefault) {
          profileToUpdate = $ts(existing.id, options3.name ?? existing.name, existing.location, this.f, {
            icon: options3.icon === null ? void 0 : options3.icon ?? existing.icon,
            transient: options3.transient ?? existing.isTransient,
            useDefaultFlags: options3.useDefaultFlags ?? existing.useDefaultFlags,
            workspaces: options3.workspaces ?? existing.workspaces
          }, this.defaultProfile);
        } else if (options3.workspaces) {
          profileToUpdate = existing;
          profileToUpdate.workspaces = options3.workspaces;
        }
      } else if (options3.workspaces) {
        const workspaces = existing.workspaces?.filter((w1) => !options3.workspaces?.some((w2) => this.u.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.I([], [], 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 (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.j.fire({
      profile,
      join(promise) {
        joiners.push(promise);
      }
    });
    try {
      await Promise.allSettled(joiners);
    } catch (error) {
      this.y.error(error);
    }
    this.I([], [profile], []);
    try {
      await this.t.del(profile.cacheHome, { recursive: true });
    } catch (error) {
      if ($Bm(error) !== 1) {
        this.y.error(error);
      }
    }
  }
  async setProfileForWorkspace(workspaceIdentifier, profileToSet) {
    const profile = this.profiles.find((p) => p.id === profileToSet.id);
    if (!profile) {
      throw new Error(`Profile '${profileToSet.name}' does not exist`);
    }
    const workspace2 = this.G(workspaceIdentifier);
    if (URI.isUri(workspace2)) {
      const workspaces = profile.workspaces ? [...profile.workspaces] : [];
      if (!workspaces.some((w) => this.u.extUri.isEqual(w, workspace2))) {
        workspaces.push(workspace2);
        await this.updateProfile(profile, { workspaces });
      }
    } else {
      this.L(workspace2, profile, false);
      this.M(this.profiles);
    }
  }
  unsetWorkspace(workspaceIdentifier, transient = false) {
    const workspace2 = this.G(workspaceIdentifier);
    if (URI.isUri(workspace2)) {
      const currentlyAssociatedProfile = this.getProfileForWorkspace(workspaceIdentifier);
      if (currentlyAssociatedProfile) {
        this.updateProfile(currentlyAssociatedProfile, { workspaces: currentlyAssociatedProfile.workspaces?.filter((w) => !this.u.extUri.isEqual(w, workspace2)) });
      }
    } else {
      this.L(workspace2, void 0, transient);
      this.M(this.profiles);
    }
  }
  async resetWorkspaces() {
    this.r.emptyWindows.clear();
    this.C.emptyWindows.clear();
    for (const profile of this.profiles) {
      profile.workspaces = void 0;
    }
    this.I([], [], this.profiles);
    this.m.fire();
  }
  async cleanUp() {
    if (await this.t.exists(this.profilesHome)) {
      const stat = await this.t.resolve(this.profilesHome);
      await Promise.all((stat.children || []).filter((child) => child.isDirectory && this.profiles.every((p) => !this.u.extUri.isEqual(p.location, child.resource))).map((child) => this.t.del(child.resource, { recursive: true })));
    }
  }
  async cleanUpTransientProfiles() {
    const unAssociatedTransientProfiles = this.r.profiles.filter((p) => !this.H(p));
    await Promise.allSettled(unAssociatedTransientProfiles.map((p) => this.removeProfile(p)));
  }
  getProfileForWorkspace(workspaceIdentifier) {
    const workspace2 = this.G(workspaceIdentifier);
    return URI.isUri(workspace2) ? this.profiles.find((p) => p.workspaces?.some((w) => this.u.extUri.isEqual(w, workspace2))) : this.C.emptyWindows.get(workspace2) ?? this.r.emptyWindows.get(workspace2);
  }
  G(workspaceIdentifier) {
    if ($1k(workspaceIdentifier)) {
      return workspaceIdentifier.uri;
    }
    if ($6k(workspaceIdentifier)) {
      return workspaceIdentifier.configPath;
    }
    return workspaceIdentifier.id;
  }
  H(profile) {
    if (profile.workspaces?.length) {
      return true;
    }
    if ([...this.C.emptyWindows.values()].some((windowProfile) => this.u.extUri.isEqual(windowProfile.location, profile.location))) {
      return true;
    }
    if ([...this.r.emptyWindows.values()].some((windowProfile) => this.u.extUri.isEqual(windowProfile.location, profile.location))) {
      return true;
    }
    return false;
  }
  I(added, removed, updated) {
    const allProfiles = [...this.profiles, ...added];
    const transientProfiles = this.r.profiles;
    this.r.profiles = [];
    const profiles2 = [];
    for (let profile of allProfiles) {
      if (removed.some((p) => profile.id === p.id)) {
        for (const windowId of [...this.C.emptyWindows.keys()]) {
          if (profile.id === this.C.emptyWindows.get(windowId)?.id) {
            this.C.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.r.profiles.push(profile);
        } else {
          if (transientProfile) {
            for (const [windowId, p] of this.r.emptyWindows.entries()) {
              if (profile.id === p.id) {
                this.r.emptyWindows.delete(windowId);
                this.C.emptyWindows.set(windowId, profile);
                break;
              }
            }
          }
        }
      }
      if (profile.workspaces?.length === 0) {
        profile.workspaces = void 0;
      }
      profiles2.push(profile);
    }
    this.M(profiles2);
    this.J(added, removed, updated);
  }
  J(added, removed, updated) {
    this.g.fire({ added, removed, updated, all: this.profiles });
  }
  L(windowId, newProfile, transient) {
    transient = newProfile?.isTransient ? true : transient;
    if (transient) {
      if (newProfile) {
        this.r.emptyWindows.set(windowId, newProfile);
      } else {
        this.r.emptyWindows.delete(windowId);
      }
    } else {
      this.r.emptyWindows.delete(windowId);
      if (newProfile) {
        this.C.emptyWindows.set(windowId, newProfile);
      } else {
        this.C.emptyWindows.delete(windowId);
      }
    }
  }
  M(profiles2) {
    const storedProfiles = [];
    const workspaces = {};
    const emptyWindows = {};
    for (const profile of profiles2) {
      if (profile.isTransient) {
        continue;
      }
      if (!profile.isDefault) {
        storedProfiles.push({ location: profile.location, name: profile.name, icon: profile.icon, useDefaultFlags: profile.useDefaultFlags });
      }
      if (profile.workspaces) {
        for (const workspace2 of profile.workspaces) {
          workspaces[workspace2.toString()] = profile.id;
        }
      }
    }
    for (const [windowId, profile] of this.C.emptyWindows.entries()) {
      emptyWindows[windowId.toString()] = profile.id;
    }
    this.Q({ workspaces, emptyWindows });
    this.O(storedProfiles);
    this.z = void 0;
  }
  N() {
    return [];
  }
  O(storedProfiles) {
    throw new Error("not implemented");
  }
  P() {
    return {};
  }
  Q(storedProfileAssociations) {
    throw new Error("not implemented");
  }
  R() {
    return void 0;
  }
};
$us = __decorate([
  __param(0, $Xk),
  __param(1, $km),
  __param(2, $vl),
  __param(3, $wn)
], $us);

// out-build/vs/platform/storage/common/storage.js
var $hv = "__$__isNewStorageMarker";
var $iv = "__$__targetStorageMarker";
var $jv = $Qk("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 $kv(storage) {
  const keysRaw = storage.get($iv);
  if (keysRaw) {
    try {
      return JSON.parse(keysRaw);
    } catch (error) {
    }
  }
  return /* @__PURE__ */ Object.create(null);
}
var $lv = class _$lv extends $3c {
  static {
    this.a = 60 * 1e3;
  }
  // every minute
  constructor(m = { flushInterval: _$lv.a }) {
    super();
    this.m = m;
    this.b = this.B(new $Ce());
    this.c = this.B(new $Ce());
    this.onDidChangeTarget = this.c.event;
    this.f = this.B(new $ze());
    this.onWillSaveState = this.f.event;
    this.h = this.B(new $8h(() => this.n(), this.m.flushInterval));
    this.j = this.B(new $4c());
    this.C = void 0;
    this.F = void 0;
    this.H = void 0;
  }
  onDidChangeValue(scope, key2, disposable) {
    return Event2.filter(this.b.event, (e) => e.scope === scope && (key2 === void 0 || e.key === key2), disposable);
  }
  n() {
    this.j.value = $_h(() => {
      if (this.r()) {
        this.flush();
      }
      this.h.schedule();
    });
  }
  r() {
    return true;
  }
  t() {
    $Xc([this.j, this.h]);
  }
  initialize() {
    if (!this.g) {
      this.g = (async () => {
        $S("code/willInitStorage");
        try {
          await this.O();
        } finally {
          $S("code/didInitStorage");
        }
        this.h.schedule();
      })();
    }
    return this.g;
  }
  u(scope, event) {
    const { key: key2, external } = event;
    if (key2 === $iv) {
      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: key2, target: this.J(scope)[key2], external });
    }
  }
  w(reason) {
    this.f.fire({ reason });
  }
  get(key2, scope, fallbackValue) {
    return this.P(scope)?.get(key2, fallbackValue);
  }
  getBoolean(key2, scope, fallbackValue) {
    return this.P(scope)?.getBoolean(key2, fallbackValue);
  }
  getNumber(key2, scope, fallbackValue) {
    return this.P(scope)?.getNumber(key2, fallbackValue);
  }
  getObject(key2, scope, fallbackValue) {
    return this.P(scope)?.getObject(key2, fallbackValue);
  }
  storeAll(entries2, external) {
    this.y(() => {
      for (const entry of entries2) {
        this.store(entry.key, entry.value, entry.scope, entry.target, external);
      }
    });
  }
  store(key2, value, scope, target, external = false) {
    if ($Ig(value)) {
      this.remove(key2, scope, external);
      return;
    }
    this.y(() => {
      this.z(key2, scope, target);
      this.P(scope)?.set(key2, value, external);
    });
  }
  remove(key2, scope, external = false) {
    this.y(() => {
      this.z(key2, scope, void 0);
      this.P(scope)?.delete(key2, 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 key2 of Object.keys(keyTargets)) {
      const keyTarget = keyTargets[key2];
      if (keyTarget === target) {
        keys.push(key2);
      }
    }
    return keys;
  }
  z(key2, scope, target, external = false) {
    const keyTargets = this.J(scope);
    if (typeof target === "number") {
      if (keyTargets[key2] !== target) {
        keyTargets[key2] = target;
        this.P(scope)?.set($iv, JSON.stringify(keyTargets), external);
      }
    } else {
      if (typeof keyTargets[key2] === "number") {
        delete keyTargets[key2];
        this.P(scope)?.set($iv, 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 ? $kv(storage) : /* @__PURE__ */ Object.create(null);
  }
  isNew(scope) {
    return this.getBoolean($hv, 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 $ov(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 ($qs(to)) {
      return this.R(to, preserveData);
    }
    return this.S(to, preserveData);
  }
  M(from, to) {
    if (from.id === to.id) {
      return false;
    }
    if ($mv(to) && $mv(from)) {
      return false;
    }
    return true;
  }
  N(oldStorage, newStorage, scope) {
    this.y(() => {
      const handledkeys = /* @__PURE__ */ new Set();
      for (const [key2, oldValue] of oldStorage) {
        handledkeys.add(key2);
        const newValue = newStorage.get(key2);
        if (newValue !== oldValue) {
          this.u(scope, { key: key2, external: true });
        }
      }
      for (const [key2] of newStorage.items) {
        if (!handledkeys.has(key2)) {
          this.u(scope, { key: key2, external: true });
        }
      }
    });
  }
};
function $mv(profile) {
  return profile.isDefault || !!profile.useDefaultFlags?.globalState;
}
var $nv = class extends $lv {
  constructor() {
    super();
    this.U = this.B(new $fv(new $gv(), { hint: StorageHint.STORAGE_IN_MEMORY }));
    this.W = this.B(new $fv(new $gv(), { hint: StorageHint.STORAGE_IN_MEMORY }));
    this.X = this.B(new $fv(new $gv(), { hint: StorageHint.STORAGE_IN_MEMORY }));
    this.B(this.X.onDidChangeStorage((e) => this.u(1, e)));
    this.B(this.W.onDidChangeStorage((e) => this.u(0, e)));
    this.B(this.U.onDidChangeStorage((e) => this.u(-1, e)));
  }
  P(scope) {
    switch (scope) {
      case -1:
        return this.U;
      case 0:
        return this.W;
      default:
        return this.X;
    }
  }
  Q(scope) {
    switch (scope) {
      case -1:
        return "inMemory (application)";
      case 0:
        return "inMemory (profile)";
      default:
        return "inMemory (workspace)";
    }
  }
  async O() {
  }
  async R() {
  }
  async S() {
  }
  r() {
    return false;
  }
  hasScope(scope) {
    return false;
  }
};
async function $ov(application, profile, workspace2, 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, key2) => {
    applicationItems.set(key2, value);
    applicationItemsParsed.set(key2, safeParse(value));
  });
  const profileItems = /* @__PURE__ */ new Map();
  const profileItemsParsed = /* @__PURE__ */ new Map();
  profile.forEach((value, key2) => {
    profileItems.set(key2, value);
    profileItemsParsed.set(key2, safeParse(value));
  });
  const workspaceItems = /* @__PURE__ */ new Map();
  const workspaceItemsParsed = /* @__PURE__ */ new Map();
  workspace2.forEach((value, key2) => {
    workspaceItems.set(key2, value);
    workspaceItemsParsed.set(key2, 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, key2) => {
    applicationValues.push({ key: key2, 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, key2) => {
      profileValues.push({ key: key2, value });
    });
    console.table(profileValues);
    console.groupEnd();
    console.log(profileItemsParsed);
  }
  console.group(`Storage: Workspace (path: ${workspacePath})`);
  const workspaceValues = [];
  workspaceItems.forEach((value, key2) => {
    workspaceValues.push({ key: key2, value });
  });
  console.table(workspaceValues);
  console.groupEnd();
  console.log(workspaceItemsParsed);
}

// out-build/vs/platform/theme/browser/defaultStyles.js
function overrideStyles(override, styles) {
  const result = { ...styles };
  for (const key2 in override) {
    const val = override[key2];
    result[key2] = val !== void 0 ? $Zn(val) : void 0;
  }
  return result;
}
var $o$ = {
  keybindingLabelBackground: $Zn($ar),
  keybindingLabelForeground: $Zn($br),
  keybindingLabelBorder: $Zn($cr),
  keybindingLabelBottomBorder: $Zn($dr),
  keybindingLabelShadow: $Zn($Rp)
};
var $q$ = {
  buttonForeground: $Zn($Sq),
  buttonSeparator: $Zn($Tq),
  buttonBackground: $Zn($Uq),
  buttonHoverBackground: $Zn($Vq),
  buttonSecondaryForeground: $Zn($Xq),
  buttonSecondaryBackground: $Zn($Yq),
  buttonSecondaryHoverBackground: $Zn($Zq),
  buttonBorder: $Zn($Wq)
};
var $s$ = {
  progressBarBackground: $Zn($Go)
};
var $u$ = {
  inputActiveOptionBorder: $Zn($Aq),
  inputActiveOptionForeground: $Zn($Dq),
  inputActiveOptionBackground: $Zn($Cq)
};
var $v$ = {
  activeForeground: $Zn($1q),
  activeBackground: $Zn($2q),
  activeBorder: $Zn($3q),
  inactiveForeground: $Zn($4q),
  inactiveBackground: $Zn($5q),
  inactiveBorder: $Zn($6q),
  inactiveHoverBackground: $Zn($7q)
};
var $x$ = {
  checkboxBackground: $Zn($8q),
  checkboxBorder: $Zn($$q),
  checkboxForeground: $Zn($0q)
};
var $z$ = {
  dialogBackground: $Zn($Qo),
  dialogForeground: $Zn($Ro),
  dialogShadow: $Zn($Rp),
  dialogBorder: $Zn($ko),
  errorIconForeground: $Zn($bq),
  warningIconForeground: $Zn($cq),
  infoIconForeground: $Zn($dq),
  textLinkForeground: $Zn($no)
};
var $B$ = {
  inputBackground: $Zn($xq),
  inputForeground: $Zn($yq),
  inputBorder: $Zn($zq),
  inputValidationInfoBorder: $Zn($Hq),
  inputValidationInfoBackground: $Zn($Fq),
  inputValidationInfoForeground: $Zn($Gq),
  inputValidationWarningBorder: $Zn($Kq),
  inputValidationWarningBackground: $Zn($Iq),
  inputValidationWarningForeground: $Zn($Jq),
  inputValidationErrorBorder: $Zn($Nq),
  inputValidationErrorBackground: $Zn($Lq),
  inputValidationErrorForeground: $Zn($Mq)
};
function $C$(override) {
  return overrideStyles(override, $B$);
}
var $D$ = {
  listFilterWidgetBackground: $Zn($zr),
  listFilterWidgetOutline: $Zn($Ar),
  listFilterWidgetNoMatchesOutline: $Zn($Br),
  listFilterWidgetShadow: $Zn($Cr),
  inputBoxStyles: $B$,
  toggleStyles: $u$
};
var $E$ = {
  badgeBackground: $Zn($wo),
  badgeForeground: $Zn($xo),
  badgeBorder: $Zn($ko)
};
var $G$ = {
  breadcrumbsBackground: $Zn($Xp),
  breadcrumbsForeground: $Zn($Wp),
  breadcrumbsHoverForeground: $Zn($Yp),
  breadcrumbsFocusForeground: $Zn($Yp),
  breadcrumbsFocusAndSelectionForeground: $Zn($Zp)
};
var $I$ = {
  listBackground: void 0,
  listInactiveFocusForeground: void 0,
  listFocusBackground: $Zn($er),
  listFocusForeground: $Zn($fr),
  listFocusOutline: $Zn($gr),
  listActiveSelectionBackground: $Zn($ir),
  listActiveSelectionForeground: $Zn($jr),
  listActiveSelectionIconForeground: $Zn($kr),
  listFocusAndSelectionOutline: $Zn($hr),
  listFocusAndSelectionBackground: $Zn($ir),
  listFocusAndSelectionForeground: $Zn($jr),
  listInactiveSelectionBackground: $Zn($lr),
  listInactiveSelectionIconForeground: $Zn($nr),
  listInactiveSelectionForeground: $Zn($mr),
  listInactiveFocusBackground: $Zn($or),
  listInactiveFocusOutline: $Zn($pr),
  listHoverBackground: $Zn($qr),
  listHoverForeground: $Zn($rr),
  listDropOverBackground: $Zn($sr),
  listDropBetweenBackground: $Zn($tr),
  listSelectionOutline: $Zn($lo),
  listHoverOutline: $Zn($lo),
  treeIndentGuidesStroke: $Zn($Gr),
  treeInactiveIndentGuidesStroke: $Zn($Hr),
  treeStickyScrollBackground: void 0,
  treeStickyScrollBorder: void 0,
  treeStickyScrollShadow: $Zn($Co),
  tableColumnsBorder: $Zn($Ir),
  tableOddRowsBackgroundColor: $Zn($Jr)
};
function $J$(override) {
  return overrideStyles(override, $I$);
}
var $K$ = {
  selectBackground: $Zn($Oq),
  selectListBackground: $Zn($Pq),
  selectForeground: $Zn($Qq),
  decoratorRightForeground: $Zn($Yr),
  selectBorder: $Zn($Rq),
  focusBorder: $Zn($jo),
  listFocusBackground: $Zn($4r),
  listInactiveSelectionIconForeground: $Zn($3r),
  listFocusForeground: $Zn($2r),
  listFocusOutline: $1n($lo, $Vn.transparent.toString()),
  listHoverBackground: $Zn($qr),
  listHoverForeground: $Zn($rr),
  listHoverOutline: $Zn($lo),
  selectListBorder: $Zn($So),
  listBackground: void 0,
  listActiveSelectionBackground: void 0,
  listActiveSelectionForeground: void 0,
  listActiveSelectionIconForeground: void 0,
  listFocusAndSelectionBackground: void 0,
  listDropOverBackground: void 0,
  listDropBetweenBackground: void 0,
  listInactiveSelectionBackground: void 0,
  listInactiveSelectionForeground: void 0,
  listInactiveFocusBackground: void 0,
  listInactiveFocusOutline: void 0,
  listSelectionOutline: void 0,
  listFocusAndSelectionForeground: void 0,
  listFocusAndSelectionOutline: void 0,
  listInactiveFocusForeground: void 0,
  tableColumnsBorder: void 0,
  tableOddRowsBackgroundColor: void 0,
  treeIndentGuidesStroke: void 0,
  treeInactiveIndentGuidesStroke: void 0,
  treeStickyScrollBackground: void 0,
  treeStickyScrollBorder: void 0,
  treeStickyScrollShadow: void 0
};
function $L$(override) {
  return overrideStyles(override, $K$);
}
var $M$ = {
  shadowColor: $Zn($Rp),
  borderColor: $Zn($Or),
  foregroundColor: $Zn($Pr),
  backgroundColor: $Zn($Qr),
  selectionForegroundColor: $Zn($Rr),
  selectionBackgroundColor: $Zn($Sr),
  selectionBorderColor: $Zn($Tr),
  separatorColor: $Zn($Ur),
  scrollbarShadow: $Zn($Co),
  scrollbarSliderBackground: $Zn($Do),
  scrollbarSliderHoverBackground: $Zn($Eo),
  scrollbarSliderActiveBackground: $Zn($Fo)
};

// out-build/vs/platform/actions/browser/menuEntryActionViewItem.js
function $O$(groups, primaryGroup) {
  const target = { primary: [], secondary: [] };
  getContextMenuActionsImpl(groups, target, primaryGroup);
  return target;
}
function $P$(groups, primaryGroup) {
  const target = [];
  getContextMenuActionsImpl(groups, target, primaryGroup);
  return target;
}
function getContextMenuActionsImpl(groups, target, primaryGroup) {
  const modifierKeyEmitter = $yk.getInstance();
  const useAlternativeActions = modifierKeyEmitter.keyStatus.altKey || ($l || $n) && modifierKeyEmitter.keyStatus.shiftKey;
  fillInActions(groups, target, useAlternativeActions, primaryGroup ? (actionGroup) => actionGroup === primaryGroup : (actionGroup) => actionGroup === "navigation");
}
function $Q$(groups, primaryGroup, shouldInlineSubmenu, useSeparatorsInPrimaryActions) {
  const target = { primary: [], secondary: [] };
  $S$(groups, target, primaryGroup, shouldInlineSubmenu, useSeparatorsInPrimaryActions);
  return target;
}
function $R$(groups, primaryGroup, shouldInlineSubmenu, useSeparatorsInPrimaryActions) {
  const target = [];
  $S$(groups, target, primaryGroup, shouldInlineSubmenu, useSeparatorsInPrimaryActions);
  return target;
}
function $S$(groups, target, primaryGroup, shouldInlineSubmenu, useSeparatorsInPrimaryActions) {
  const isPrimaryAction = typeof primaryGroup === "string" ? (actionGroup) => actionGroup === primaryGroup : primaryGroup;
  fillInActions(groups, target, false, isPrimaryAction, shouldInlineSubmenu, useSeparatorsInPrimaryActions);
}
function fillInActions(groups, target, useAlternativeActions, isPrimaryAction = (actionGroup) => actionGroup === "navigation", shouldInlineSubmenu = () => false, useSeparatorsInPrimaryActions = false) {
  let primaryBucket;
  let secondaryBucket;
  if (Array.isArray(target)) {
    primaryBucket = target;
    secondaryBucket = target;
  } else {
    primaryBucket = target.primary;
    secondaryBucket = target.secondary;
  }
  const submenuInfo = /* @__PURE__ */ new Set();
  for (const [group2, actions] of groups) {
    let target2;
    if (isPrimaryAction(group2)) {
      target2 = primaryBucket;
      if (target2.length > 0 && useSeparatorsInPrimaryActions) {
        target2.push(new $Wm());
      }
    } else {
      target2 = secondaryBucket;
      if (target2.length > 0) {
        target2.push(new $Wm());
      }
    }
    for (let action of actions) {
      if (useAlternativeActions) {
        action = action instanceof $fJ && action.alt ? action.alt : action;
      }
      const newLen = target2.push(action);
      if (action instanceof $Xm) {
        submenuInfo.add({ group: group2, action, index: newLen - 1 });
      }
    }
  }
  for (const { group: group2, action, index } of submenuInfo) {
    const target2 = isPrimaryAction(group2) ? primaryBucket : secondaryBucket;
    const submenuActions = action.actions;
    if (shouldInlineSubmenu(action, group2, target2.length)) {
      target2.splice(index, 1, ...submenuActions);
    }
  }
}
var $T$ = class $T$2 extends $U1 {
  constructor(action, t, X, Y, Z, ab, bb, cb) {
    super(void 0, action, { icon: !!(action.class || action.item.icon), label: !action.class && !action.item.icon, draggable: t?.draggable, keybinding: t?.keybinding, hoverDelegate: t?.hoverDelegate });
    this.t = t;
    this.X = X;
    this.Y = Y;
    this.Z = Z;
    this.ab = ab;
    this.bb = bb;
    this.cb = cb;
    this.n = false;
    this.r = this.B(new $4c());
    this.s = $yk.getInstance();
  }
  get db() {
    return this._action;
  }
  get eb() {
    return this.n && this.db.alt || this.db;
  }
  async onClick(event) {
    event.preventDefault();
    event.stopPropagation();
    try {
      await this.actionRunner.run(this.eb, this._context);
    } catch (err) {
      this.Y.error(err);
    }
  }
  render(container2) {
    super.render(container2);
    container2.classList.add("menu-entry");
    if (this.u.icon) {
      this.ib(this.db.item);
    }
    if (this.db.alt) {
      let isMouseOver = false;
      const updateAltState = () => {
        const wantsAltCommand = !!this.db.alt?.enabled && (!this.cb.isMotionReduced() || isMouseOver) && (this.s.keyStatus.altKey || this.s.keyStatus.shiftKey && isMouseOver);
        if (wantsAltCommand !== this.n) {
          this.n = wantsAltCommand;
          this.C();
          this.G();
          this.I();
        }
      };
      this.B(this.s.event(updateAltState));
      this.B($_i(container2, "mouseleave", (_) => {
        isMouseOver = false;
        updateAltState();
      }));
      this.B($_i(container2, "mouseenter", (_) => {
        isMouseOver = true;
        updateAltState();
      }));
      updateAltState();
    }
  }
  C() {
    if (this.u.label && this.L) {
      this.L.textContent = this.eb.label;
    }
  }
  F() {
    const keybinding = this.X.lookupKeybinding(this.eb.id, this.Z);
    const keybindingLabel = keybinding && keybinding.getLabel();
    const tooltip = this.eb.tooltip || this.eb.label;
    let title = keybindingLabel ? localize(1672, null, tooltip, keybindingLabel) : tooltip;
    if (!this.n && this.db.alt?.enabled) {
      const altTooltip = this.db.alt.tooltip || this.db.alt.label;
      const altKeybinding = this.X.lookupKeybinding(this.db.alt.id, this.Z);
      const altKeybindingLabel = altKeybinding && altKeybinding.getLabel();
      const altTitleSection = altKeybindingLabel ? localize(1673, null, altTooltip, altKeybindingLabel) : altTooltip;
      title = localize(1674, null, title, $X2.modifierLabels[OS].altKey, altTitleSection);
    }
    return title;
  }
  I() {
    if (this.u.icon) {
      if (this.eb !== this.db) {
        if (this.db.alt) {
          this.ib(this.db.alt.item);
        }
      } else {
        this.ib(this.db.item);
      }
    }
  }
  ib(item) {
    this.r.value = void 0;
    const { element, L: label3 } = this;
    if (!element || !label3) {
      return;
    }
    const icon2 = this.eb.checked && $vn(item.toggled) && item.toggled.icon ? item.toggled.icon : item.icon;
    if (!icon2) {
      return;
    }
    if (ThemeIcon.isThemeIcon(icon2)) {
      const iconClasses = ThemeIcon.asClassNameArray(icon2);
      label3.classList.add(...iconClasses);
      this.r.value = $1c(() => {
        label3.classList.remove(...iconClasses);
      });
    } else {
      label3.style.backgroundImage = $fs(this.ab.getColorTheme().type) ? $5Z(icon2.dark) : $5Z(icon2.light);
      label3.classList.add("icon");
      this.r.value = $Zc($1c(() => {
        label3.style.backgroundImage = "";
        label3.classList.remove("icon");
      }), this.ab.onDidColorThemeChange(() => {
        this.I();
      }));
    }
  }
};
$T$ = __decorate([
  __param(2, $Ty),
  __param(3, $PJ),
  __param(4, $on),
  __param(5, $gs),
  __param(6, $50),
  __param(7, $ND)
], $T$);
var $U$ = class _$U$ extends $T$ {
  render(container2) {
    this.u.label = true;
    this.u.icon = false;
    super.render(container2);
    container2.classList.add("text-only");
    container2.classList.toggle("use-comma", this.t?.useComma ?? false);
  }
  C() {
    const kb = this.X.lookupKeybinding(this._action.id, this.Z);
    if (!kb) {
      return super.C();
    }
    if (this.L) {
      const kb2 = _$U$.c(kb);
      if (this.t?.conversational) {
        this.L.textContent = localize(1675, null, this._action.label, kb2);
      } else {
        this.L.textContent = localize(1676, null, this._action.label, kb2);
      }
    }
  }
  static c(kb) {
    return kb.getLabel()?.replace(/\benter\b/gi, "\u23CE").replace(/\bEscape\b/gi, "Esc");
  }
};
var $V$ = class $V$2 extends $L2 {
  constructor(action, options3, g, r2, O) {
    const dropdownOptions = {
      ...options3,
      menuAsChild: options3?.menuAsChild ?? false,
      classNames: options3?.classNames ?? (ThemeIcon.isThemeIcon(action.item.icon) ? ThemeIcon.asClassName(action.item.icon) : void 0),
      keybindingProvider: options3?.keybindingProvider ?? ((action2) => g.lookupKeybinding(action2.id))
    };
    super(action, { getActions: () => action.actions }, r2, dropdownOptions);
    this.g = g;
    this.r = r2;
    this.O = O;
  }
  render(container2) {
    super.render(container2);
    $Jg(this.element);
    container2.classList.add("menu-entry");
    const action = this._action;
    const { icon: icon2 } = action.item;
    if (icon2 && !ThemeIcon.isThemeIcon(icon2)) {
      this.element.classList.add("icon");
      const setBackgroundImage = () => {
        if (this.element) {
          this.element.style.backgroundImage = $fs(this.O.getColorTheme().type) ? $5Z(icon2.dark) : $5Z(icon2.light);
        }
      };
      setBackgroundImage();
      this.B(this.O.onDidColorThemeChange(() => {
        setBackgroundImage();
      }));
    }
  }
};
$V$ = __decorate([
  __param(2, $Ty),
  __param(3, $50),
  __param(4, $gs)
], $V$);
var $W$ = class $W$2 extends $T1 {
  get onDidChangeDropdownVisibility() {
    return this.g.onDidChangeVisibility;
  }
  constructor(submenuAction, options3, n, r2, s, t, y, L) {
    super(null, submenuAction);
    this.n = n;
    this.r = r2;
    this.s = s;
    this.t = t;
    this.y = y;
    this.L = L;
    this.h = null;
    this.b = options3;
    this.m = `${submenuAction.item.submenu.id}_lastActionId`;
    let defaultAction;
    const defaultActionId = options3?.persistLastActionId ? L.get(
      this.m,
      1
      /* StorageScope.WORKSPACE */
    ) : void 0;
    if (defaultActionId) {
      defaultAction = submenuAction.actions.find((a) => defaultActionId === a.id);
    }
    if (!defaultAction) {
      defaultAction = submenuAction.actions[0];
    }
    this.c = this.y.createInstance($T$, defaultAction, { keybinding: this.N(defaultAction) });
    const dropdownOptions = {
      keybindingProvider: (action) => this.n.lookupKeybinding(action.id),
      ...options3,
      menuAsChild: options3?.menuAsChild ?? true,
      classNames: options3?.classNames ?? ["codicon", "codicon-chevron-down"],
      actionRunner: options3?.actionRunner ?? new $Vm()
    };
    this.g = new $L2(submenuAction, submenuAction.actions, this.s, dropdownOptions);
    this.B(this.g.actionRunner.onDidRun((e) => {
      if (e.action instanceof $fJ) {
        this.M(e.action);
      }
    }));
  }
  M(lastAction) {
    if (this.b?.persistLastActionId) {
      this.L.store(
        this.m,
        lastAction.id,
        1,
        1
        /* StorageTarget.MACHINE */
      );
    }
    this.c.dispose();
    this.c = this.y.createInstance($T$, lastAction, { keybinding: this.N(lastAction) });
    this.c.actionRunner = new class extends $Vm {
      async u(action, context) {
        await action.run(void 0);
      }
    }();
    if (this.h) {
      this.c.render($ck(this.h, $(".action-container")));
    }
  }
  N(defaultAction) {
    let defaultActionKeybinding;
    if (this.b?.renderKeybindingWithDefaultActionLabel) {
      const kb = this.n.lookupKeybinding(defaultAction.id);
      if (kb) {
        defaultActionKeybinding = `(${kb.getLabel()})`;
      }
    }
    return defaultActionKeybinding;
  }
  setActionContext(newContext) {
    super.setActionContext(newContext);
    this.c.setActionContext(newContext);
    this.g.setActionContext(newContext);
  }
  render(container2) {
    this.h = container2;
    super.render(this.h);
    this.h.classList.add("monaco-dropdown-with-default");
    const primaryContainer = $(".action-container");
    this.c.render($bk(this.h, primaryContainer));
    this.B($_i(primaryContainer, $7j.KEY_DOWN, (e) => {
      const event = new $if(e);
      if (event.equals(
        17
        /* KeyCode.RightArrow */
      )) {
        this.c.element.tabIndex = -1;
        this.g.focus();
        event.stopPropagation();
      }
    }));
    const dropdownContainer = $(".dropdown-action-container");
    this.g.render($bk(this.h, dropdownContainer));
    this.B($_i(dropdownContainer, $7j.KEY_DOWN, (e) => {
      const event = new $if(e);
      if (event.equals(
        15
        /* KeyCode.LeftArrow */
      )) {
        this.c.element.tabIndex = 0;
        this.g.setFocusable(false);
        this.c.element?.focus();
        event.stopPropagation();
      }
    }));
  }
  focus(fromRight) {
    if (fromRight) {
      this.g.focus();
    } else {
      this.c.element.tabIndex = 0;
      this.c.element.focus();
    }
  }
  blur() {
    this.c.element.tabIndex = -1;
    this.g.blur();
    this.h.blur();
  }
  setFocusable(focusable) {
    if (focusable) {
      this.c.element.tabIndex = 0;
    } else {
      this.c.element.tabIndex = -1;
      this.g.setFocusable(false);
    }
  }
  dispose() {
    this.c.dispose();
    this.g.dispose();
    super.dispose();
  }
};
$W$ = __decorate([
  __param(2, $Ty),
  __param(3, $PJ),
  __param(4, $50),
  __param(5, $cJ),
  __param(6, $Pk),
  __param(7, $jv)
], $W$);
var SubmenuEntrySelectActionViewItem = class SubmenuEntrySelectActionViewItem2 extends $V1 {
  constructor(action, contextViewService) {
    super(null, action, action.actions.map((a) => ({
      text: a.id === $Wm.ID ? "\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500" : a.label,
      isDisabled: !a.enabled
    })), 0, contextViewService, $K$, { ariaLabel: action.tooltip, optionsAsChildren: true });
    this.select(Math.max(0, action.actions.findIndex((a) => a.checked)));
  }
  render(container2) {
    super.render(container2);
    container2.style.borderColor = $Zn($Rq);
  }
  m(option, index) {
    const action = this.action.actions[index];
    if (action) {
      this.actionRunner.run(action);
    }
  }
};
SubmenuEntrySelectActionViewItem = __decorate([
  __param(1, $40)
], SubmenuEntrySelectActionViewItem);
function $X$(instaService, action, options3) {
  if (action instanceof $fJ) {
    return instaService.createInstance($T$, action, options3);
  } else if (action instanceof $eJ) {
    if (action.item.isSelection) {
      return instaService.createInstance(SubmenuEntrySelectActionViewItem, action);
    } else {
      if (action.item.rememberDefaultAction) {
        return instaService.createInstance($W$, action, { ...options3, persistLastActionId: true });
      } else {
        return instaService.createInstance($V$, action, options3);
      }
    }
  } else {
    return void 0;
  }
}

// out-build/vs/platform/actions/common/menuService.js
var PersistedMenuHideState_1;
var MenuInfo_1;
var $Y$ = class $Y$2 {
  constructor(d, f, storageService) {
    this.d = d;
    this.f = f;
    this.c = new PersistedMenuHideState(storageService);
  }
  createMenu(id2, contextKeyService, options3) {
    return new MenuImpl(id2, this.c, { emitEventsForSubmenuChanges: false, eventDebounceDelay: 50, ...options3 }, this.d, this.f, contextKeyService);
  }
  getMenuActions(id2, contextKeyService, options3) {
    const menu = new MenuImpl(id2, this.c, { emitEventsForSubmenuChanges: false, eventDebounceDelay: 50, ...options3 }, this.d, this.f, contextKeyService);
    const actions = menu.getActions(options3);
    menu.dispose();
    return actions;
  }
  getMenuContexts(id2) {
    const menuInfo = new MenuInfoSnapshot(id2, false);
    return /* @__PURE__ */ new Set([...menuInfo.structureContextKeys, ...menuInfo.preconditionContextKeys, ...menuInfo.toggledContextKeys]);
  }
  resetHiddenStates(ids) {
    this.c.reset(ids);
  }
};
$Y$ = __decorate([
  __param(0, $sn),
  __param(1, $Ty),
  __param(2, $jv)
], $Y$);
var PersistedMenuHideState = class PersistedMenuHideState2 {
  static {
    PersistedMenuHideState_1 = this;
  }
  static {
    this.c = "menu.hiddenCommands";
  }
  constructor(k) {
    this.k = k;
    this.d = new $2c();
    this.f = new $ze();
    this.onDidChange = this.f.event;
    this.h = false;
    this.j = /* @__PURE__ */ new Map();
    try {
      const raw = k.get(PersistedMenuHideState_1.c, 0, "{}");
      this.i = JSON.parse(raw);
    } catch (err) {
      this.i = /* @__PURE__ */ Object.create(null);
    }
    this.d.add(k.onDidChangeValue(0, PersistedMenuHideState_1.c, this.d)(() => {
      if (!this.h) {
        try {
          const raw = k.get(PersistedMenuHideState_1.c, 0, "{}");
          this.i = JSON.parse(raw);
        } catch (err) {
          console.log("FAILED to read storage after UPDATE", err);
        }
      }
      this.f.fire();
    }));
  }
  dispose() {
    this.f.dispose();
    this.d.dispose();
  }
  l(menu, commandId) {
    return this.j.get(`${menu.id}/${commandId}`) ?? false;
  }
  setDefaultState(menu, commandId, hidden) {
    this.j.set(`${menu.id}/${commandId}`, hidden);
  }
  isHidden(menu, commandId) {
    const hiddenByDefault = this.l(menu, commandId);
    const state = this.i[menu.id]?.includes(commandId) ?? false;
    return hiddenByDefault ? !state : state;
  }
  updateHidden(menu, commandId, hidden) {
    const hiddenByDefault = this.l(menu, commandId);
    if (hiddenByDefault) {
      hidden = !hidden;
    }
    const entries2 = this.i[menu.id];
    if (!hidden) {
      if (entries2) {
        const idx = entries2.indexOf(commandId);
        if (idx >= 0) {
          $Ab(entries2, idx);
        }
        if (entries2.length === 0) {
          delete this.i[menu.id];
        }
      }
    } else {
      if (!entries2) {
        this.i[menu.id] = [commandId];
      } else {
        const idx = entries2.indexOf(commandId);
        if (idx < 0) {
          entries2.push(commandId);
        }
      }
    }
    this.m();
  }
  reset(menus) {
    if (menus === void 0) {
      this.i = /* @__PURE__ */ Object.create(null);
      this.m();
    } else {
      for (const { id: id2 } of menus) {
        if (this.i[id2]) {
          delete this.i[id2];
        }
      }
      this.m();
    }
  }
  m() {
    try {
      this.h = true;
      const raw = JSON.stringify(this.i);
      this.k.store(
        PersistedMenuHideState_1.c,
        raw,
        0,
        0
        /* StorageTarget.USER */
      );
    } finally {
      this.h = false;
    }
  }
};
PersistedMenuHideState = PersistedMenuHideState_1 = __decorate([
  __param(0, $jv)
], PersistedMenuHideState);
var MenuInfoSnapshot = class _MenuInfoSnapshot {
  constructor(j, k) {
    this.j = j;
    this.k = k;
    this.c = [];
    this.d = /* @__PURE__ */ new Set();
    this.f = /* @__PURE__ */ new Set();
    this.h = /* @__PURE__ */ new Set();
    this.i = /* @__PURE__ */ new Set();
    this.refresh();
  }
  get allMenuIds() {
    return this.d;
  }
  get structureContextKeys() {
    return this.f;
  }
  get preconditionContextKeys() {
    return this.h;
  }
  get toggledContextKeys() {
    return this.i;
  }
  refresh() {
    this.c.length = 0;
    this.d.clear();
    this.f.clear();
    this.h.clear();
    this.i.clear();
    const menuItems = this.l($dJ.getMenuItems(this.j));
    let group2;
    for (const item of menuItems) {
      const groupName = item.group || "";
      if (!group2 || group2[0] !== groupName) {
        group2 = [groupName, []];
        this.c.push(group2);
      }
      group2[1].push(item);
      this.m(item);
    }
    this.d.add(this.j);
  }
  l(menuItems) {
    return menuItems;
  }
  m(item) {
    _MenuInfoSnapshot.n(item.when, this.f);
    if ($_I(item)) {
      if (item.command.precondition) {
        _MenuInfoSnapshot.n(item.command.precondition, this.h);
      }
      if (item.command.toggled) {
        const toggledExpression = item.command.toggled.condition || item.command.toggled;
        _MenuInfoSnapshot.n(toggledExpression, this.i);
      }
    } else if (this.k) {
      $dJ.getMenuItems(item.submenu).forEach(this.m, this);
      this.d.add(item.submenu);
    }
  }
  static n(exp, set) {
    if (exp) {
      for (const key2 of exp.keys()) {
        set.add(key2);
      }
    }
  }
};
var MenuInfo = MenuInfo_1 = class MenuInfo2 extends MenuInfoSnapshot {
  constructor(_id, o, _collectContextKeysForSubmenus, p, q, r2) {
    super(_id, _collectContextKeysForSubmenus);
    this.o = o;
    this.p = p;
    this.q = q;
    this.r = r2;
    this.refresh();
  }
  createActionGroups(options3) {
    const result = [];
    for (const group2 of this.c) {
      const [id2, items] = group2;
      let activeActions;
      for (const item of items) {
        if (this.r.contextMatchesRules(item.when)) {
          const isMenuItem = $_I(item);
          if (isMenuItem) {
            this.o.setDefaultState(this.j, item.command.id, !!item.isHiddenByDefault);
          }
          const menuHide = createMenuHide(this.j, isMenuItem ? item.command : item, this.o);
          if (isMenuItem) {
            const menuKeybinding = $Z$(this.p, this.q, item.command.id, item.when);
            (activeActions ??= []).push(new $fJ(item.command, item.alt, options3, menuHide, menuKeybinding, this.r, this.p));
          } else {
            const groups = new MenuInfo_1(item.submenu, this.o, this.k, this.p, this.q, this.r).createActionGroups(options3);
            const submenuActions = $Wm.join(...groups.map((g) => g[1]));
            if (submenuActions.length > 0) {
              (activeActions ??= []).push(new $eJ(item, menuHide, submenuActions));
            }
          }
        }
      }
      if (activeActions && activeActions.length > 0) {
        result.push([id2, activeActions]);
      }
    }
    return result;
  }
  l(menuItems) {
    return menuItems.sort(MenuInfo_1.t);
  }
  static t(a, b) {
    const aGroup = a.group;
    const bGroup = b.group;
    if (aGroup !== bGroup) {
      if (!aGroup) {
        return 1;
      } else if (!bGroup) {
        return -1;
      }
      if (aGroup === "navigation") {
        return -1;
      } else if (bGroup === "navigation") {
        return 1;
      }
      const value = aGroup.localeCompare(bGroup);
      if (value !== 0) {
        return value;
      }
    }
    const aPrio = a.order || 0;
    const bPrio = b.order || 0;
    if (aPrio < bPrio) {
      return -1;
    } else if (aPrio > bPrio) {
      return 1;
    }
    return MenuInfo_1.u($_I(a) ? a.command.title : a.title, $_I(b) ? b.command.title : b.title);
  }
  static u(a, b) {
    const aStr = typeof a === "string" ? a : a.original;
    const bStr = typeof b === "string" ? b : b.original;
    return aStr.localeCompare(bStr);
  }
};
MenuInfo = MenuInfo_1 = __decorate([
  __param(3, $sn),
  __param(4, $Ty),
  __param(5, $on)
], MenuInfo);
var MenuImpl = class MenuImpl2 {
  constructor(id2, hiddenStates, options3, commandService, keybindingService, contextKeyService) {
    this.d = new $2c();
    this.c = new MenuInfo(id2, hiddenStates, options3.emitEventsForSubmenuChanges, commandService, keybindingService, contextKeyService);
    const rebuildMenuSoon = new $8h(() => {
      this.c.refresh();
      this.f.fire({ menu: this, isStructuralChange: true, isEnablementChange: true, isToggleChange: true });
    }, options3.eventDebounceDelay);
    this.d.add(rebuildMenuSoon);
    this.d.add($dJ.onDidChangeMenu((e) => {
      for (const id3 of this.c.allMenuIds) {
        if (e.has(id3)) {
          rebuildMenuSoon.schedule();
          break;
        }
      }
    }));
    const lazyListener = this.d.add(new $2c());
    const merge2 = (events) => {
      let isStructuralChange = false;
      let isEnablementChange = false;
      let isToggleChange = false;
      for (const item of events) {
        isStructuralChange = isStructuralChange || item.isStructuralChange;
        isEnablementChange = isEnablementChange || item.isEnablementChange;
        isToggleChange = isToggleChange || item.isToggleChange;
        if (isStructuralChange && isEnablementChange && isToggleChange) {
          break;
        }
      }
      return { menu: this, isStructuralChange, isEnablementChange, isToggleChange };
    };
    const startLazyListener = () => {
      lazyListener.add(contextKeyService.onDidChangeContext((e) => {
        const isStructuralChange = e.affectsSome(this.c.structureContextKeys);
        const isEnablementChange = e.affectsSome(this.c.preconditionContextKeys);
        const isToggleChange = e.affectsSome(this.c.toggledContextKeys);
        if (isStructuralChange || isEnablementChange || isToggleChange) {
          this.f.fire({ menu: this, isStructuralChange, isEnablementChange, isToggleChange });
        }
      }));
      lazyListener.add(hiddenStates.onDidChange((e) => {
        this.f.fire({ menu: this, isStructuralChange: true, isEnablementChange: false, isToggleChange: false });
      }));
    };
    this.f = new $De({
      // start/stop context key listener
      onWillAddFirstListener: startLazyListener,
      onDidRemoveLastListener: lazyListener.clear.bind(lazyListener),
      delay: options3.eventDebounceDelay,
      merge: merge2
    });
    this.onDidChange = this.f.event;
  }
  getActions(options3) {
    return this.c.createActionGroups(options3);
  }
  dispose() {
    this.d.dispose();
    this.f.dispose();
  }
};
MenuImpl = __decorate([
  __param(3, $sn),
  __param(4, $Ty),
  __param(5, $on)
], MenuImpl);
function createMenuHide(menu, command4, states) {
  const id2 = $aJ(command4) ? command4.submenu.id : command4.id;
  const title = typeof command4.title === "string" ? command4.title : command4.title.value;
  const hide3 = $Zm({
    id: `hide/${menu.id}/${id2}`,
    label: localize(1680, null, title),
    run() {
      states.updateHidden(menu, id2, true);
    }
  });
  const toggle = $Zm({
    id: `toggle/${menu.id}/${id2}`,
    label: title,
    get checked() {
      return !states.isHidden(menu, id2);
    },
    run() {
      states.updateHidden(menu, id2, !!this.checked);
    }
  });
  return {
    hide: hide3,
    toggle,
    get isHidden() {
      return !toggle.checked;
    }
  };
}
function $Z$(commandService, keybindingService, commandId, when = void 0, enabled = true) {
  return $Zm({
    id: `configureKeybinding/${commandId}`,
    label: localize(1681, null),
    enabled,
    run() {
      const hasKeybinding = !!keybindingService.lookupKeybinding(commandId);
      const whenValue = !hasKeybinding && when ? when.serialize() : void 0;
      commandService.executeCommand("workbench.action.openGlobalKeybindings", `@command:${commandId}` + (whenValue ? ` +when:${whenValue}` : ""));
    }
  });
}

// out-build/vs/platform/actions/browser/actionViewItemService.js
var $1$ = $Qk("IActionViewItemService");
var ActionViewItemService = class {
  constructor() {
    this.a = /* @__PURE__ */ new Map();
    this.b = new $ze();
    this.onDidChange = this.b.event;
  }
  dispose() {
    this.b.dispose();
  }
  register(menu, commandOrSubmenuId, provider, event) {
    const id2 = this.c(menu, commandOrSubmenuId);
    if (this.a.has(id2)) {
      throw new Error(`A provider for the command ${commandOrSubmenuId} and menu ${menu} is already registered.`);
    }
    this.a.set(id2, provider);
    const listener = event?.(() => {
      this.b.fire(menu);
    });
    return $1c(() => {
      listener?.dispose();
      this.a.delete(id2);
    });
  }
  lookUp(menu, commandOrMenuId) {
    return this.a.get(this.c(menu, commandOrMenuId));
  }
  c(menu, commandOrMenuId) {
    return `${menu.id}/${commandOrMenuId instanceof $bJ ? commandOrMenuId.id : commandOrMenuId}`;
  }
};
$SC(
  $1$,
  ActionViewItemService,
  1
  /* InstantiationType.Delayed */
);

// out-build/vs/platform/actions/browser/toolbar.js
var HiddenItemStrategy;
(function(HiddenItemStrategy2) {
  HiddenItemStrategy2[HiddenItemStrategy2["NoHide"] = -1] = "NoHide";
  HiddenItemStrategy2[HiddenItemStrategy2["Ignore"] = 0] = "Ignore";
  HiddenItemStrategy2[HiddenItemStrategy2["RenderInSecondaryGroup"] = 1] = "RenderInSecondaryGroup";
})(HiddenItemStrategy || (HiddenItemStrategy = {}));
var $3$ = class $3$2 extends $f3 {
  constructor(container2, H, I, J, L, M, N, telemetryService) {
    super(container2, L, {
      // defaults
      getKeyBinding: (action) => M.lookupKeybinding(action.id) ?? void 0,
      // options (override defaults)
      ...H,
      // mandatory (overide options)
      allowContextMenu: true,
      skipTelemetry: typeof H?.telemetrySource === "string"
    });
    this.H = H;
    this.I = I;
    this.J = J;
    this.L = L;
    this.M = M;
    this.N = N;
    this.G = this.q.add(new $2c());
    const telemetrySource = H?.telemetrySource;
    if (telemetrySource) {
      this.q.add(this.m.onDidRun((e) => telemetryService.publicLog2("workbenchActionExecuted", { id: e.action.id, from: telemetrySource })));
    }
  }
  setActions(_primary, _secondary = [], menuIds) {
    this.G.clear();
    const primary = _primary.slice();
    const secondary = _secondary.slice();
    const toggleActions = [];
    let toggleActionsCheckedCount = 0;
    const extraSecondary = [];
    let someAreHidden = false;
    if (this.H?.hiddenItemStrategy !== -1) {
      for (let i2 = 0; i2 < primary.length; i2++) {
        const action = primary[i2];
        if (!(action instanceof $fJ) && !(action instanceof $eJ)) {
          continue;
        }
        if (!action.hideActions) {
          continue;
        }
        toggleActions.push(action.hideActions.toggle);
        if (action.hideActions.toggle.checked) {
          toggleActionsCheckedCount++;
        }
        if (action.hideActions.isHidden) {
          someAreHidden = true;
          primary[i2] = void 0;
          if (this.H?.hiddenItemStrategy !== 0) {
            extraSecondary[i2] = action;
          }
        }
      }
    }
    if (this.H?.overflowBehavior !== void 0) {
      const exemptedIds = $d(new Set(this.H.overflowBehavior.exempted), Iterable.map(primary, (a) => a?.id));
      const maxItems = this.H.overflowBehavior.maxItems - exemptedIds.size;
      let count = 0;
      for (let i2 = 0; i2 < primary.length; i2++) {
        const action = primary[i2];
        if (!action) {
          continue;
        }
        count++;
        if (exemptedIds.has(action.id)) {
          continue;
        }
        if (count >= maxItems) {
          primary[i2] = void 0;
          extraSecondary[i2] = action;
        }
      }
    }
    $Nb(primary);
    $Nb(extraSecondary);
    super.setActions(primary, $Wm.join(extraSecondary, secondary));
    if (toggleActions.length > 0 || primary.length > 0) {
      this.G.add($_i(this.getElement(), "contextmenu", (e) => {
        const event = new $lf(getWindow(this.getElement()), e);
        const action = this.getItemAction(event.target);
        if (!action) {
          return;
        }
        event.preventDefault();
        event.stopPropagation();
        const primaryActions = [];
        if (action instanceof $fJ && action.menuKeybinding) {
          primaryActions.push(action.menuKeybinding);
        } else if (!(action instanceof $eJ || action instanceof $g3)) {
          const supportsKeybindings = !!this.M.lookupKeybinding(action.id);
          primaryActions.push($Z$(this.N, this.M, action.id, void 0, supportsKeybindings));
        }
        if (toggleActions.length > 0) {
          let noHide = false;
          if (toggleActionsCheckedCount === 1 && this.H?.hiddenItemStrategy === 0) {
            noHide = true;
            for (let i2 = 0; i2 < toggleActions.length; i2++) {
              if (toggleActions[i2].checked) {
                toggleActions[i2] = $Zm({
                  id: action.id,
                  label: action.label,
                  checked: true,
                  enabled: false,
                  run() {
                  }
                });
                break;
              }
            }
          }
          if (!noHide && (action instanceof $fJ || action instanceof $eJ)) {
            if (!action.hideActions) {
              return;
            }
            primaryActions.push(action.hideActions.hide);
          } else {
            primaryActions.push($Zm({
              id: "label",
              label: localize(1677, null),
              enabled: false,
              run() {
              }
            }));
          }
        }
        const actions = $Wm.join(primaryActions, toggleActions);
        if (this.H?.resetMenu && !menuIds) {
          menuIds = [this.H.resetMenu];
        }
        if (someAreHidden && menuIds) {
          actions.push(new $Wm());
          actions.push($Zm({
            id: "resetThisMenu",
            label: localize(1678, null),
            run: () => this.I.resetHiddenStates(menuIds)
          }));
        }
        if (actions.length === 0) {
          return;
        }
        this.L.showContextMenu({
          getAnchor: () => event,
          getActions: () => actions,
          // add context menu actions (iff appicable)
          menuId: this.H?.contextMenu,
          menuActionOptions: { renderShortTitle: true, ...this.H?.menuOptions },
          skipTelemetry: typeof this.H?.telemetrySource === "string",
          contextKeyService: this.J
        });
      }));
    }
  }
};
$3$ = __decorate([
  __param(2, $cJ),
  __param(3, $on),
  __param(4, $50),
  __param(5, $Ty),
  __param(6, $sn),
  __param(7, $zv)
], $3$);
var $4$ = class $4$2 extends $3$ {
  constructor(container2, menuId, options3, menuService, contextKeyService, contextMenuService, keybindingService, commandService, telemetryService, actionViewService, instaService) {
    super(container2, {
      resetMenu: menuId,
      ...options3,
      actionViewItemProvider: (action, opts) => {
        let provider = actionViewService.lookUp(menuId, action instanceof $eJ ? action.item.submenu.id : action.id);
        if (!provider) {
          provider = options3?.actionViewItemProvider;
        }
        const viewItem = provider?.(action, opts);
        if (viewItem) {
          return viewItem;
        }
        return $X$(instaService, action, opts);
      }
    }, menuService, contextKeyService, contextMenuService, keybindingService, commandService, telemetryService);
    this.b = this.q.add(new $ze());
    this.onDidChangeMenuItems = this.b.event;
    const menu = this.q.add(menuService.createMenu(menuId, contextKeyService, { emitEventsForSubmenuChanges: true, eventDebounceDelay: options3?.eventDebounceDelay }));
    const updateToolbar = () => {
      const { primary, secondary } = $Q$(menu.getActions(options3?.menuOptions), options3?.toolbarOptions?.primaryGroup, options3?.toolbarOptions?.shouldInlineSubmenu, options3?.toolbarOptions?.useSeparatorsInPrimaryActions);
      container2.classList.toggle("has-no-actions", primary.length === 0 && secondary.length === 0);
      super.setActions(primary, secondary);
    };
    this.q.add(menu.onDidChange(() => {
      updateToolbar();
      this.b.fire(this);
    }));
    this.q.add(actionViewService.onDidChange((e) => {
      if (e === menuId) {
        updateToolbar();
      }
    }));
    updateToolbar();
  }
  /**
   * @deprecated The WorkbenchToolBar does not support this method because it works with menus.
   */
  setActions() {
    throw new $vb("This toolbar is populated from a menu.");
  }
};
$4$ = __decorate([
  __param(3, $cJ),
  __param(4, $on),
  __param(5, $50),
  __param(6, $Ty),
  __param(7, $sn),
  __param(8, $zv),
  __param(9, $1$),
  __param(10, $Pk)
], $4$);

// out-build/vs/platform/hover/browser/hover.js
var $5$ = $Qk("hoverService");
var $6$ = class $6$2 extends $3c {
  get delay() {
    if (this.u()) {
      return 0;
    }
    return this.g;
  }
  constructor(placement, m, n = {}, s, t) {
    super();
    this.placement = placement;
    this.m = m;
    this.n = n;
    this.s = s;
    this.t = t;
    this.c = 0;
    this.f = 200;
    this.j = this.B(new $2c());
    this.g = this.s.getValue("workbench.hover.delay");
    this.B(this.s.onDidChangeConfiguration((e) => {
      if (e.affectsConfiguration("workbench.hover.delay")) {
        this.g = this.s.getValue("workbench.hover.delay");
      }
    }));
  }
  showHover(options3, focus) {
    const overrideOptions = typeof this.n === "function" ? this.n(options3, focus) : this.n;
    this.j.clear();
    const targets = $Uj(options3.target) ? [options3.target] : options3.target.targetElements;
    for (const target of targets) {
      this.j.add($aj(target, "keydown", (e) => {
        if (e.equals(
          9
          /* KeyCode.Escape */
        )) {
          this.t.hideHover();
        }
      }));
    }
    const id2 = $Uj(options3.content) ? void 0 : typeof options3.content === "string" ? options3.content.toString() : options3.content.value;
    return this.t.showHover({
      ...options3,
      ...overrideOptions,
      persistence: {
        hideOnKeyDown: true,
        ...overrideOptions.persistence
      },
      id: id2,
      appearance: {
        ...options3.appearance,
        compact: true,
        skipFadeInAnimation: this.u(),
        ...overrideOptions.appearance
      }
    }, focus);
  }
  u() {
    return this.m && Date.now() - this.c < this.f;
  }
  setInstantHoverTimeLimit(timeLimit) {
    if (!this.m) {
      throw new Error("Instant hover is not enabled");
    }
    this.f = timeLimit;
  }
  onDidHideHover() {
    this.j.clear();
    if (this.m) {
      this.c = Date.now();
    }
  }
};
$6$ = __decorate([
  __param(3, $kl),
  __param(4, $5$)
], $6$);
var $7$ = {
  showHover: function() {
    throw new Error("Native hover function not implemented.");
  },
  delay: 0,
  showNativeHover: true
};

// out-build/vs/editor/common/model/textModelText.js
var $8$ = class extends $kD {
  constructor(d) {
    super();
    this.d = d;
  }
  getValueOfRange(range) {
    return this.d.getValueInRange(range);
  }
  getLineLength(lineNumber) {
    return this.d.getLineLength(lineNumber);
  }
  get length() {
    const lastLineNumber = this.d.getLineCount();
    const lastLineLen = this.d.getLineLength(lastLineNumber);
    return new $gD(lastLineNumber - 1, lastLineLen);
  }
};

// out-build/vs/editor/browser/widget/multiDiffEditor/utils.js
var $9$ = class extends $Vm {
  constructor(a) {
    super();
    this.a = a;
  }
  u(action, _context) {
    const ctx = this.a();
    return super.u(action, ctx);
  }
};

// out-build/vs/editor/browser/widget/diffEditor/utils/editorGutter.js
var $0$ = class extends $3c {
  constructor(m, n, r2) {
    super();
    this.m = m;
    this.n = n;
    this.r = r2;
    this.a = $Dd(this, this.m.onDidScrollChange, (e) => (
      /** @description editor.onDidScrollChange */
      this.m.getScrollTop()
    ));
    this.b = this.a.map((scrollTop) => (
      /** @description isScrollTopZero */
      scrollTop === 0
    ));
    this.c = $Dd(this, this.m.onDidChangeModel, (e) => (
      /** @description editor.onDidChangeModel */
      this.m.hasModel()
    ));
    this.f = $Gd("onDidChangeViewZones", this.m.onDidChangeViewZones);
    this.g = $Gd("onDidContentSizeChange", this.m.onDidContentSizeChange);
    this.j = $Hd("domNodeSizeChanged");
    this.s = /* @__PURE__ */ new Map();
    this.n.className = "gutter monaco-editor";
    const scrollDecoration = this.n.appendChild(h("div.scroll-decoration", { role: "presentation", ariaHidden: "true", style: { width: "100%" } }).root);
    const o = new ResizeObserver(() => {
      $ce((tx) => {
        this.j.trigger(tx);
      });
    });
    o.observe(this.n);
    this.B($1c(() => o.disconnect()));
    this.B($td((reader) => {
      scrollDecoration.className = this.b.read(reader) ? "" : "scroll-decoration";
    }));
    this.B($td((reader) => (
      /** @description EditorGutter.Render */
      this.t(reader)
    )));
  }
  dispose() {
    super.dispose();
    $dk(this.n);
  }
  t(reader) {
    if (!this.c.read(reader)) {
      return;
    }
    this.j.read(reader);
    this.f.read(reader);
    this.g.read(reader);
    const scrollTop = this.a.read(reader);
    const visibleRanges = this.m.getVisibleRanges();
    const unusedIds = new Set(this.s.keys());
    const viewRange = $0C.ofStartAndLength(0, this.n.clientHeight);
    if (!viewRange.isEmpty) {
      for (const visibleRange of visibleRanges) {
        const visibleRange2 = new $_C(visibleRange.startLineNumber, visibleRange.endLineNumber + 1);
        const gutterItems = this.r.getIntersectingGutterItems(visibleRange2, reader);
        $ce((tx) => {
          for (const gutterItem of gutterItems) {
            if (!gutterItem.range.intersect(visibleRange2)) {
              continue;
            }
            unusedIds.delete(gutterItem.id);
            let view = this.s.get(gutterItem.id);
            if (!view) {
              const viewDomNode = document.createElement("div");
              this.n.appendChild(viewDomNode);
              const gutterItemObs = $he("item", gutterItem);
              const itemView = this.r.createView(gutterItemObs, viewDomNode);
              view = new ManagedGutterItemView(gutterItemObs, itemView, viewDomNode);
              this.s.set(gutterItem.id, view);
            } else {
              view.item.set(gutterItem, tx);
            }
            const top2 = gutterItem.range.startLineNumber <= this.m.getModel().getLineCount() ? this.m.getTopForLineNumber(gutterItem.range.startLineNumber, true) - scrollTop : this.m.getBottomForLineNumber(gutterItem.range.startLineNumber - 1, false) - scrollTop;
            const bottom = gutterItem.range.endLineNumberExclusive === 1 ? Math.max(top2, this.m.getTopForLineNumber(gutterItem.range.startLineNumber, false) - scrollTop) : Math.max(top2, this.m.getBottomForLineNumber(gutterItem.range.endLineNumberExclusive - 1, true) - scrollTop);
            const height = bottom - top2;
            view.domNode.style.top = `${top2}px`;
            view.domNode.style.height = `${height}px`;
            view.gutterItemView.layout($0C.ofStartAndLength(top2, height), viewRange);
          }
        });
      }
    }
    for (const id2 of unusedIds) {
      const view = this.s.get(id2);
      view.gutterItemView.dispose();
      view.domNode.remove();
      this.s.delete(id2);
    }
  }
};
var ManagedGutterItemView = class {
  constructor(item, gutterItemView, domNode) {
    this.item = item;
    this.gutterItemView = gutterItemView;
    this.domNode = domNode;
  }
};

// out-build/vs/editor/browser/widget/diffEditor/features/gutterFeature.js
var emptyArr2 = [];
var width = 35;
var $$$ = class $$$2 extends $3c {
  constructor(diffEditorRoot, u, w, y, z, C, D, F, G) {
    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.b = this.B(this.G.createMenu($bJ.DiffEditorHunkToolbar, this.F));
    this.f = $Dd(this, this.b.onDidChange, () => this.b.getActions());
    this.j = this.f.map((a) => a.length > 0);
    this.n = $2d(this, (reader) => this.y.renderSideBySide.read(reader) && this.j.read(reader));
    this.width = $2d(this, (reader) => this.j.read(reader) ? width : 0);
    this.t = h("div.gutter@gutter", { style: { position: "absolute", height: "100%", width: width + "px" } }, []);
    this.H = $2d(this, (reader) => {
      const model = this.u.read(reader);
      if (!model) {
        return void 0;
      }
      const mappings = model.diff.read(reader)?.mappings;
      const cursorPosition = this.w.modifiedCursor.read(reader);
      if (!cursorPosition) {
        return void 0;
      }
      return mappings?.find((m) => m.lineRangeMapping.modified.contains(cursorPosition.lineNumber));
    });
    this.I = $2d(this, (reader) => {
      const model = this.u.read(reader);
      const diff3 = model?.diff.read(reader);
      if (!diff3) {
        return emptyArr2;
      }
      const selections = this.w.modifiedSelections.read(reader);
      if (selections.every((s) => s.isEmpty())) {
        return emptyArr2;
      }
      const selectedLineNumbers = new $aD(selections.map((s) => $_C.fromRangeInclusive(s)));
      const selectedMappings = diff3.mappings.filter((m) => m.lineRangeMapping.innerChanges && selectedLineNumbers.intersects(m.lineRangeMapping.modified));
      const result = selectedMappings.map((mapping2) => ({
        mapping: mapping2,
        rangeMappings: mapping2.lineRangeMapping.innerChanges.filter((c) => selections.some((s) => $9C.areIntersecting(c.modifiedRange, s)))
      }));
      if (result.length === 0 || result.every((r2) => r2.rangeMappings.length === 0)) {
        return emptyArr2;
      }
      return result;
    });
    this.B($T9(diffEditorRoot, this.t.root));
    this.B($_i(this.t.root, "click", () => {
      this.w.modified.focus();
    }));
    this.B($19(this.t.root, { display: this.j.map((a) => a ? "block" : "none") }));
    $7d(this, (reader) => {
      const showSash = this.n.read(reader);
      return !showSash ? void 0 : new $m$(diffEditorRoot, this.z.dimensions, this.y.enableSplitViewResizing, this.C, $3d(this, (reader2) => this.z.sashLeft.read(reader2) - width, (v, tx) => this.z.sashLeft.set(v + width, tx)), () => this.z.resetSash());
    }).recomputeInitiallyAndOnChange(this.q);
    const gutterItems = $2d(this, (reader) => {
      const model = this.u.read(reader);
      if (!model) {
        return [];
      }
      const diffs = model.diff.read(reader);
      if (!diffs) {
        return [];
      }
      const selection = this.I.read(reader);
      if (selection.length > 0) {
        const m = $qD.fromRangeMappings(selection.flatMap((s) => s.rangeMappings));
        return [
          new DiffGutterItem(m, true, $bJ.DiffEditorSelectionToolbar, void 0, model.model.original.uri, model.model.modified.uri)
        ];
      }
      const currentDiff = this.H.read(reader);
      return diffs.mappings.map((m) => new DiffGutterItem(m.lineRangeMapping.withInnerChangesFromLineRanges(), m.lineRangeMapping === currentDiff?.lineRangeMapping, $bJ.DiffEditorHunkToolbar, void 0, model.model.original.uri, model.model.modified.uri));
    });
    this.B(new $0$(this.w.modified, this.t.root, {
      getIntersectingGutterItems: (range, reader) => gutterItems.read(reader),
      createView: (item, target) => {
        return this.D.createInstance(DiffToolBar, item, target, this);
      }
    }));
    this.B($_i(this.t.gutter, $7j.MOUSE_WHEEL, (e) => {
      if (this.w.modified.getOption(
        108
        /* EditorOption.scrollbar */
      ).handleMouseWheel) {
        this.w.modified.delegateScrollFromMouseWheelEvent(e);
      }
    }, { passive: false }));
  }
  computeStagedValue(mapping2) {
    const c = mapping2.innerChanges ?? [];
    const modified = new $8$(this.w.modifiedModel.get());
    const original = new $8$(this.w.original.getModel());
    const edit3 = new $iD(c.map((c2) => c2.toTextEdit(modified)));
    const value = edit3.apply(original);
    return value;
  }
  layout(left) {
    this.t.gutter.style.left = left + "px";
  }
};
$$$ = __decorate([
  __param(6, $Pk),
  __param(7, $on),
  __param(8, $cJ)
], $$$);
var DiffGutterItem = class {
  constructor(mapping2, showAlways, menuId, rangeOverride, originalUri, modifiedUri) {
    this.mapping = mapping2;
    this.showAlways = showAlways;
    this.menuId = menuId;
    this.rangeOverride = rangeOverride;
    this.originalUri = originalUri;
    this.modifiedUri = modifiedUri;
  }
  get id() {
    return this.mapping.modified.toString();
  }
  get range() {
    return this.rangeOverride ?? this.mapping.modified;
  }
};
var DiffToolBar = class DiffToolBar2 extends $3c {
  constructor(t, target, gutter, instantiationService) {
    super();
    this.t = t;
    this.b = h("div.gutterItem", { style: { height: "20px", width: "34px" } }, [
      h("div.background@background", {}, []),
      h("div.buttons@buttons", {}, [])
    ]);
    this.f = this.t.map(this, (item) => item.showAlways);
    this.j = this.t.map(this, (item) => item.menuId);
    this.n = $he(this, false);
    this.u = void 0;
    this.w = void 0;
    const hoverDelegate = this.B(instantiationService.createInstance($6$, "element", true, { position: {
      hoverPosition: 1
      /* HoverPosition.RIGHT */
    } }));
    this.B($S9(target, this.b.root));
    this.B($td((reader) => {
      const showAlways = this.f.read(reader);
      this.b.root.classList.toggle("noTransition", true);
      this.b.root.classList.toggle("showAlways", showAlways);
      setTimeout(() => {
        this.b.root.classList.toggle("noTransition", false);
      }, 0);
    }));
    this.B($xd((reader, store) => {
      this.b.buttons.replaceChildren();
      const i2 = store.add(instantiationService.createInstance($4$, this.b.buttons, this.j.read(reader), {
        orientation: 1,
        hoverDelegate,
        toolbarOptions: {
          primaryGroup: (g) => g.startsWith("primary")
        },
        overflowBehavior: { maxItems: this.n.read(reader) ? 1 : 3 },
        hiddenItemStrategy: 0,
        actionRunner: new $9$(() => {
          const item = this.t.get();
          const mapping2 = item.mapping;
          return {
            mapping: mapping2,
            originalWithModifiedChanges: gutter.computeStagedValue(mapping2),
            originalUri: item.originalUri,
            modifiedUri: item.modifiedUri
          };
        }),
        menuOptions: {
          shouldForwardArgs: true
        }
      }));
      store.add(i2.onDidChangeMenuItems(() => {
        if (this.u) {
          this.layout(this.u, this.w);
        }
      }));
    }));
  }
  layout(itemRange, viewRange) {
    this.u = itemRange;
    this.w = viewRange;
    let itemHeight = this.b.buttons.clientHeight;
    this.n.set(this.t.get().mapping.original.startLineNumber === 1 && itemRange.length < 30, void 0);
    itemHeight = this.b.buttons.clientHeight;
    const middleHeight = itemRange.length / 2 - itemHeight / 2;
    const margin = itemHeight;
    let effectiveCheckboxTop = itemRange.start + middleHeight;
    const preferredViewPortRange = $0C.tryCreate(margin, viewRange.endExclusive - margin - itemHeight);
    const preferredParentRange = $0C.tryCreate(itemRange.start + margin, itemRange.endExclusive - itemHeight - margin);
    if (preferredParentRange && preferredViewPortRange && preferredParentRange.start < preferredParentRange.endExclusive) {
      effectiveCheckboxTop = preferredViewPortRange.clip(effectiveCheckboxTop);
      effectiveCheckboxTop = preferredParentRange.clip(effectiveCheckboxTop);
    }
    this.b.buttons.style.top = `${effectiveCheckboxTop - itemRange.start}px`;
  }
};
DiffToolBar = __decorate([
  __param(3, $Pk)
], DiffToolBar);

// out-build/vs/editor/browser/widget/diffEditor/features/hideUnchangedRegionsFeature.js
var $_$_1;
var $_$ = class $_$2 extends $3c {
  static {
    $_$_1 = this;
  }
  static {
    this.a = $he($_$_1, () => ({
      dispose() {
      },
      getBreadcrumbItems(startRange, reader) {
        return [];
      }
    }));
  }
  static setBreadcrumbsSourceFactory(factory) {
    this.a.set(factory, void 0);
  }
  get isUpdatingHiddenAreas() {
    return this.c;
  }
  constructor(f, g, j, n) {
    super();
    this.f = f;
    this.g = g;
    this.j = j;
    this.n = n;
    this.b = $7d(this, (reader) => {
      const m = this.f.modifiedModel.read(reader);
      const factory = $_$_1.a.read(reader);
      return !m || !factory ? void 0 : factory(m, this.n);
    });
    this.c = false;
    this.B(this.f.original.onDidChangeCursorPosition((e) => {
      if (e.reason === 1) {
        return;
      }
      const m = this.g.get();
      $ce((tx) => {
        for (const s of this.f.original.getSelections() || []) {
          m?.ensureOriginalLineIsVisible(s.getStartPosition().lineNumber, 0, tx);
          m?.ensureOriginalLineIsVisible(s.getEndPosition().lineNumber, 0, tx);
        }
      });
    }));
    this.B(this.f.modified.onDidChangeCursorPosition((e) => {
      if (e.reason === 1) {
        return;
      }
      const m = this.g.get();
      $ce((tx) => {
        for (const s of this.f.modified.getSelections() || []) {
          m?.ensureModifiedLineIsVisible(s.getStartPosition().lineNumber, 0, tx);
          m?.ensureModifiedLineIsVisible(s.getEndPosition().lineNumber, 0, tx);
        }
      });
    }));
    const unchangedRegions = this.g.map((m, reader) => {
      const regions = m?.unchangedRegions.read(reader) ?? [];
      if (regions.length === 1 && regions[0].modifiedLineNumber === 1 && regions[0].lineCount === this.f.modifiedModel.read(reader)?.getLineCount()) {
        return [];
      }
      return regions;
    });
    this.viewZones = $6d(this, (reader, store) => {
      const modifiedOutlineSource = this.b.read(reader);
      if (!modifiedOutlineSource) {
        return { origViewZones: [], modViewZones: [] };
      }
      const origViewZones = [];
      const modViewZones = [];
      const sideBySide = this.j.renderSideBySide.read(reader);
      const compactMode = this.j.compactMode.read(reader);
      const curUnchangedRegions = unchangedRegions.read(reader);
      for (let i2 = 0; i2 < curUnchangedRegions.length; i2++) {
        const r2 = curUnchangedRegions[i2];
        if (r2.shouldHideControls(reader)) {
          continue;
        }
        if (compactMode && (i2 === 0 || i2 === curUnchangedRegions.length - 1)) {
          continue;
        }
        if (compactMode) {
          {
            const d = $2d(this, (reader2) => (
              /** @description hiddenOriginalRangeStart */
              r2.getHiddenOriginalRange(reader2).startLineNumber - 1
            ));
            const origVz = new $Y9(d, 12);
            origViewZones.push(origVz);
            store.add(new CompactCollapsedCodeOverlayWidget(this.f.original, origVz, r2, !sideBySide));
          }
          {
            const d = $2d(this, (reader2) => (
              /** @description hiddenModifiedRangeStart */
              r2.getHiddenModifiedRange(reader2).startLineNumber - 1
            ));
            const modViewZone = new $Y9(d, 12);
            modViewZones.push(modViewZone);
            store.add(new CompactCollapsedCodeOverlayWidget(this.f.modified, modViewZone, r2));
          }
        } else {
          {
            const d = $2d(this, (reader2) => (
              /** @description hiddenOriginalRangeStart */
              r2.getHiddenOriginalRange(reader2).startLineNumber - 1
            ));
            const origVz = new $Y9(d, 24);
            origViewZones.push(origVz);
            store.add(new CollapsedCodeOverlayWidget(this.f.original, origVz, r2, r2.originalUnchangedRange, !sideBySide, modifiedOutlineSource, (l) => this.g.get().ensureModifiedLineIsVisible(l, 2, void 0), this.j));
          }
          {
            const d = $2d(this, (reader2) => (
              /** @description hiddenModifiedRangeStart */
              r2.getHiddenModifiedRange(reader2).startLineNumber - 1
            ));
            const modViewZone = new $Y9(d, 24);
            modViewZones.push(modViewZone);
            store.add(new CollapsedCodeOverlayWidget(this.f.modified, modViewZone, r2, r2.modifiedUnchangedRange, false, modifiedOutlineSource, (l) => this.g.get().ensureModifiedLineIsVisible(l, 2, void 0), this.j));
          }
        }
      }
      return { origViewZones, modViewZones };
    });
    const unchangedLinesDecoration = {
      description: "unchanged lines",
      className: "diff-unchanged-lines",
      isWholeLine: true
    };
    const unchangedLinesDecorationShow = {
      description: "Fold Unchanged",
      glyphMarginHoverMessage: new $bm(void 0, { isTrusted: true, supportThemeIcons: true }).appendMarkdown(localize(235, null)),
      glyphMarginClassName: "fold-unchanged " + ThemeIcon.asClassName($6l.fold),
      zIndex: 10001
    };
    this.B($R9(this.f.original, $2d(this, (reader) => {
      const curUnchangedRegions = unchangedRegions.read(reader);
      const result = curUnchangedRegions.map((r2) => ({
        range: r2.originalUnchangedRange.toInclusiveRange(),
        options: unchangedLinesDecoration
      }));
      for (const r2 of curUnchangedRegions) {
        if (r2.shouldHideControls(reader)) {
          result.push({
            range: $9C.fromPositions(new $8C(r2.originalLineNumber, 1)),
            options: unchangedLinesDecorationShow
          });
        }
      }
      return result;
    })));
    this.B($R9(this.f.modified, $2d(this, (reader) => {
      const curUnchangedRegions = unchangedRegions.read(reader);
      const result = curUnchangedRegions.map((r2) => ({
        range: r2.modifiedUnchangedRange.toInclusiveRange(),
        options: unchangedLinesDecoration
      }));
      for (const r2 of curUnchangedRegions) {
        if (r2.shouldHideControls(reader)) {
          result.push({
            range: $_C.ofLength(r2.modifiedLineNumber, 1).toInclusiveRange(),
            options: unchangedLinesDecorationShow
          });
        }
      }
      return result;
    })));
    this.B($td((reader) => {
      const curUnchangedRegions = unchangedRegions.read(reader);
      this.c = true;
      try {
        this.f.original.setHiddenAreas(curUnchangedRegions.map((r2) => r2.getHiddenOriginalRange(reader).toInclusiveRange()).filter($Hg));
        this.f.modified.setHiddenAreas(curUnchangedRegions.map((r2) => r2.getHiddenModifiedRange(reader).toInclusiveRange()).filter($Hg));
      } finally {
        this.c = false;
      }
    }));
    this.B(this.f.modified.onMouseUp((event) => {
      if (!event.event.rightButton && event.target.position && event.target.element?.className.includes("fold-unchanged")) {
        const lineNumber = event.target.position.lineNumber;
        const model = this.g.get();
        if (!model) {
          return;
        }
        const region = model.unchangedRegions.get().find((r2) => r2.modifiedUnchangedRange.includes(lineNumber));
        if (!region) {
          return;
        }
        region.collapseAll(void 0);
        event.event.stopPropagation();
        event.event.preventDefault();
      }
    }));
    this.B(this.f.original.onMouseUp((event) => {
      if (!event.event.rightButton && event.target.position && event.target.element?.className.includes("fold-unchanged")) {
        const lineNumber = event.target.position.lineNumber;
        const model = this.g.get();
        if (!model) {
          return;
        }
        const region = model.unchangedRegions.get().find((r2) => r2.originalUnchangedRange.includes(lineNumber));
        if (!region) {
          return;
        }
        region.collapseAll(void 0);
        event.event.stopPropagation();
        event.event.preventDefault();
      }
    }));
  }
};
$_$ = $_$_1 = __decorate([
  __param(3, $Pk)
], $_$);
var CompactCollapsedCodeOverlayWidget = class extends $X9 {
  constructor(editor, _viewZone, g, n = false) {
    const root = h("div.diff-hidden-lines-widget");
    super(editor, _viewZone, root.root);
    this.g = g;
    this.n = n;
    this.f = h("div.diff-hidden-lines-compact", [
      h("div.line-left", []),
      h("div.text@text", []),
      h("div.line-right", [])
    ]);
    root.root.appendChild(this.f.root);
    if (this.n) {
      this.f.root.replaceChildren();
    }
    this.B($td((reader) => {
      if (!this.n) {
        const lineCount = this.g.getHiddenModifiedRange(reader).length;
        const linesHiddenText = localize(236, null, lineCount);
        this.f.text.innerText = linesHiddenText;
      }
    }));
  }
};
var CollapsedCodeOverlayWidget = class extends $X9 {
  constructor(g, _viewZone, n, u, w, y, C, D) {
    const root = h("div.diff-hidden-lines-widget");
    super(g, _viewZone, root.root);
    this.g = g;
    this.n = n;
    this.u = u;
    this.w = w;
    this.y = y;
    this.C = C;
    this.D = D;
    this.f = h("div.diff-hidden-lines", [
      h("div.top@top", { title: localize(237, null) }),
      h("div.center@content", { style: { display: "flex" } }, [
        h("div@first", { style: { display: "flex", justifyContent: "center", alignItems: "center", flexShrink: "0" } }, [$("a", { title: localize(238, null), role: "button", onclick: () => {
          this.n.showAll(void 0);
        } }, ...$B1("$(unfold)"))]),
        h("div@others", { style: { display: "flex", justifyContent: "center", alignItems: "center" } })
      ]),
      h("div.bottom@bottom", { title: localize(239, null), role: "button" })
    ]);
    root.root.appendChild(this.f.root);
    if (!this.w) {
      this.B($19(this.f.first, { width: $79(this.g).layoutInfoContentLeft }));
    } else {
      $dk(this.f.first);
    }
    this.B($td((reader) => {
      const isFullyRevealed = this.n.visibleLineCountTop.read(reader) + this.n.visibleLineCountBottom.read(reader) === this.n.lineCount;
      this.f.bottom.classList.toggle("canMoveTop", !isFullyRevealed);
      this.f.bottom.classList.toggle("canMoveBottom", this.n.visibleLineCountBottom.read(reader) > 0);
      this.f.top.classList.toggle("canMoveTop", this.n.visibleLineCountTop.read(reader) > 0);
      this.f.top.classList.toggle("canMoveBottom", !isFullyRevealed);
      const isDragged = this.n.isDragged.read(reader);
      const domNode = this.g.getDomNode();
      if (domNode) {
        domNode.classList.toggle("draggingUnchangedRegion", !!isDragged);
        if (isDragged === "top") {
          domNode.classList.toggle("canMoveTop", this.n.visibleLineCountTop.read(reader) > 0);
          domNode.classList.toggle("canMoveBottom", !isFullyRevealed);
        } else if (isDragged === "bottom") {
          domNode.classList.toggle("canMoveTop", !isFullyRevealed);
          domNode.classList.toggle("canMoveBottom", this.n.visibleLineCountBottom.read(reader) > 0);
        } else {
          domNode.classList.toggle("canMoveTop", false);
          domNode.classList.toggle("canMoveBottom", false);
        }
      }
    }));
    const editor = this.g;
    this.B($_i(this.f.top, "mousedown", (e) => {
      if (e.button !== 0) {
        return;
      }
      this.f.top.classList.toggle("dragging", true);
      this.f.root.classList.toggle("dragging", true);
      e.preventDefault();
      const startTop = e.clientY;
      let didMove = false;
      const cur = this.n.visibleLineCountTop.get();
      this.n.isDragged.set("top", void 0);
      const window3 = getWindow(this.f.top);
      const mouseMoveListener = $_i(window3, "mousemove", (e2) => {
        const currentTop = e2.clientY;
        const delta = currentTop - startTop;
        didMove = didMove || Math.abs(delta) > 2;
        const lineDelta = Math.round(delta / editor.getOption(
          68
          /* EditorOption.lineHeight */
        ));
        const newVal = Math.max(0, Math.min(cur + lineDelta, this.n.getMaxVisibleLineCountTop()));
        this.n.visibleLineCountTop.set(newVal, void 0);
      });
      const mouseUpListener = $_i(window3, "mouseup", (e2) => {
        if (!didMove) {
          this.n.showMoreAbove(this.D.hideUnchangedRegionsRevealLineCount.get(), void 0);
        }
        this.f.top.classList.toggle("dragging", false);
        this.f.root.classList.toggle("dragging", false);
        this.n.isDragged.set(void 0, void 0);
        mouseMoveListener.dispose();
        mouseUpListener.dispose();
      });
    }));
    this.B($_i(this.f.bottom, "mousedown", (e) => {
      if (e.button !== 0) {
        return;
      }
      this.f.bottom.classList.toggle("dragging", true);
      this.f.root.classList.toggle("dragging", true);
      e.preventDefault();
      const startTop = e.clientY;
      let didMove = false;
      const cur = this.n.visibleLineCountBottom.get();
      this.n.isDragged.set("bottom", void 0);
      const window3 = getWindow(this.f.bottom);
      const mouseMoveListener = $_i(window3, "mousemove", (e2) => {
        const currentTop = e2.clientY;
        const delta = currentTop - startTop;
        didMove = didMove || Math.abs(delta) > 2;
        const lineDelta = Math.round(delta / editor.getOption(
          68
          /* EditorOption.lineHeight */
        ));
        const newVal = Math.max(0, Math.min(cur - lineDelta, this.n.getMaxVisibleLineCountBottom()));
        const top2 = this.u.endLineNumberExclusive > editor.getModel().getLineCount() ? editor.getContentHeight() : editor.getTopForLineNumber(this.u.endLineNumberExclusive);
        this.n.visibleLineCountBottom.set(newVal, void 0);
        const top22 = this.u.endLineNumberExclusive > editor.getModel().getLineCount() ? editor.getContentHeight() : editor.getTopForLineNumber(this.u.endLineNumberExclusive);
        editor.setScrollTop(editor.getScrollTop() + (top22 - top2));
      });
      const mouseUpListener = $_i(window3, "mouseup", (e2) => {
        this.n.isDragged.set(void 0, void 0);
        if (!didMove) {
          const top2 = editor.getTopForLineNumber(this.u.endLineNumberExclusive);
          this.n.showMoreBelow(this.D.hideUnchangedRegionsRevealLineCount.get(), void 0);
          const top22 = editor.getTopForLineNumber(this.u.endLineNumberExclusive);
          editor.setScrollTop(editor.getScrollTop() + (top22 - top2));
        }
        this.f.bottom.classList.toggle("dragging", false);
        this.f.root.classList.toggle("dragging", false);
        mouseMoveListener.dispose();
        mouseUpListener.dispose();
      });
    }));
    this.B($td((reader) => {
      const children = [];
      if (!this.w) {
        const lineCount = n.getHiddenModifiedRange(reader).length;
        const linesHiddenText = localize(240, null, lineCount);
        const span = $("span", { title: localize(241, null) }, linesHiddenText);
        span.addEventListener("dblclick", (e) => {
          if (e.button !== 0) {
            return;
          }
          e.preventDefault();
          this.n.showAll(void 0);
        });
        children.push(span);
        const range = this.n.getHiddenModifiedRange(reader);
        const items = this.y.getBreadcrumbItems(range, reader);
        if (items.length > 0) {
          children.push($("span", void 0, "\xA0\xA0|\xA0\xA0"));
          for (let i2 = 0; i2 < items.length; i2++) {
            const item = items[i2];
            const icon2 = SymbolKinds.toIcon(item.kind);
            const divItem = h("div.breadcrumb-item", {
              style: { display: "flex", alignItems: "center" }
            }, [
              $C1(icon2),
              "\xA0",
              item.name,
              ...i2 === items.length - 1 ? [] : [$C1($6l.chevronRight)]
            ]).root;
            children.push(divItem);
            divItem.onclick = () => {
              this.C(item.startLineNumber);
            };
          }
        }
      }
      $dk(this.f.others, ...children);
    }));
  }
};

// out-build/vs/editor/browser/widget/diffEditor/features/revertButtonsFeature.js
var emptyArr3 = [];
var $a_ = class extends $3c {
  constructor(a, b, f, g) {
    super();
    this.a = a;
    this.b = b;
    this.f = f;
    this.g = g;
    this.j = $2d(this, (reader) => {
      const model = this.b.read(reader);
      const diff3 = model?.diff.read(reader);
      if (!diff3) {
        return emptyArr3;
      }
      const selections = this.a.modifiedSelections.read(reader);
      if (selections.every((s) => s.isEmpty())) {
        return emptyArr3;
      }
      const selectedLineNumbers = new $aD(selections.map((s) => $_C.fromRangeInclusive(s)));
      const selectedMappings = diff3.mappings.filter((m) => m.lineRangeMapping.innerChanges && selectedLineNumbers.intersects(m.lineRangeMapping.modified));
      const result = selectedMappings.map((mapping2) => ({
        mapping: mapping2,
        rangeMappings: mapping2.lineRangeMapping.innerChanges.filter((c) => selections.some((s) => $9C.areIntersecting(c.modifiedRange, s)))
      }));
      if (result.length === 0 || result.every((r2) => r2.rangeMappings.length === 0)) {
        return emptyArr3;
      }
      return result;
    });
    this.B($xd((reader, store) => {
      if (!this.f.shouldRenderOldRevertArrows.read(reader)) {
        return;
      }
      const model = this.b.read(reader);
      const diff3 = model?.diff.read(reader);
      if (!model || !diff3) {
        return;
      }
      if (model.movedTextToCompare.read(reader)) {
        return;
      }
      const glyphWidgetsModified = [];
      const selectedDiffs = this.j.read(reader);
      const selectedDiffsSet = new Set(selectedDiffs.map((d) => d.mapping));
      if (selectedDiffs.length > 0) {
        const selections = this.a.modifiedSelections.read(reader);
        const btn = store.add(new $b_(selections[selections.length - 1].positionLineNumber, this.g, selectedDiffs.flatMap((d) => d.rangeMappings), true));
        this.a.modified.addGlyphMarginWidget(btn);
        glyphWidgetsModified.push(btn);
      }
      for (const m of diff3.mappings) {
        if (selectedDiffsSet.has(m)) {
          continue;
        }
        if (!m.lineRangeMapping.modified.isEmpty && m.lineRangeMapping.innerChanges) {
          const btn = store.add(new $b_(m.lineRangeMapping.modified.startLineNumber, this.g, m.lineRangeMapping, false));
          this.a.modified.addGlyphMarginWidget(btn);
          glyphWidgetsModified.push(btn);
        }
      }
      store.add($1c(() => {
        for (const w of glyphWidgetsModified) {
          this.a.modified.removeGlyphMarginWidget(w);
        }
      }));
    }));
  }
};
var $b_ = class _$b_ extends $3c {
  static {
    this.counter = 0;
  }
  getId() {
    return this.a;
  }
  constructor(f, g, j, n) {
    super();
    this.f = f;
    this.g = g;
    this.j = j;
    this.n = n;
    this.a = `revertButton${_$b_.counter++}`;
    this.b = h("div.revertButton", {
      title: this.n ? localize(246, null) : localize(247, null)
    }, [$C1($6l.arrowRight)]).root;
    this.B($_i(this.b, $7j.MOUSE_DOWN, (e) => {
      if (e.button !== 2) {
        e.stopPropagation();
        e.preventDefault();
      }
    }));
    this.B($_i(this.b, $7j.MOUSE_UP, (e) => {
      e.stopPropagation();
      e.preventDefault();
    }));
    this.B($_i(this.b, $7j.CLICK, (e) => {
      if (this.j instanceof $pD) {
        this.g.revert(this.j);
      } else {
        this.g.revertRangeMappings(this.j);
      }
      e.stopPropagation();
      e.preventDefault();
    }));
  }
  /**
   * Get the dom node of the glyph widget.
   */
  getDomNode() {
    return this.b;
  }
  /**
   * Get the placement of the glyph widget.
   */
  getPosition() {
    return {
      lane: GlyphMarginLane.Right,
      range: {
        startColumn: 1,
        startLineNumber: this.f,
        endColumn: 1,
        endLineNumber: this.f
      },
      zIndex: 10001
    };
  }
};

// out-build/vs/editor/browser/widget/diffEditor/diffEditorWidget.js
var $c_ = class $c_2 extends $n$ {
  static {
    this.ENTIRE_DIFF_OVERVIEW_WIDTH = $f$.ENTIRE_DIFF_OVERVIEW_WIDTH;
  }
  get onDidContentSizeChange() {
    return this.L.onDidContentSizeChange;
  }
  get collapseUnchangedRegions() {
    return this.J.hideUnchangedRegions.get();
  }
  constructor(P, options3, codeEditorWidgetOptions, Q, R, codeEditorService, S, U) {
    super();
    this.P = P;
    this.Q = Q;
    this.R = R;
    this.S = S;
    this.U = U;
    this.j = h("div.monaco-diff-editor.side-by-side", { style: { position: "relative", height: "100%" } }, [
      h("div.editor.original@original", { style: { position: "absolute", height: "100%" } }),
      h("div.editor.modified@modified", { style: { position: "absolute", height: "100%" } }),
      h("div.accessibleDiffViewer@accessibleDiffViewer", { style: { position: "absolute", height: "100%" } })
    ]);
    this.n = this.B($je(this, void 0));
    this.t = $2d(this, (reader) => this.n.read(reader)?.object);
    this.onDidChangeModel = Event2.fromObservableLight(this.t);
    this.u = this.B(this.Q.createScoped(this.P));
    this.y = this.B(this.R.createChild(new $Ok([$on, this.u])));
    this.F = $he(this, void 0);
    this.G = $he(this, false);
    this.H = $2d(this, (reader) => this.J.onlyShowAccessibleDiffViewer.read(reader) ? true : this.G.read(reader));
    this.N = $he(this, void 0);
    this.X = $2d(this, (reader) => {
      const fullWidth = this.z.width.read(reader);
      const fullHeight = this.z.height.read(reader);
      if (this.z.automaticLayout) {
        this.j.root.style.height = "100%";
      } else {
        this.j.root.style.height = fullHeight + "px";
      }
      const sash = this.D.read(reader);
      const gutter = this.O.read(reader);
      const gutterWidth = gutter?.width.read(reader) ?? 0;
      const overviewRulerPartWidth = this.M.read(reader)?.width ?? 0;
      let originalLeft, originalWidth, modifiedLeft, modifiedWidth, gutterLeft;
      const sideBySide = !!sash;
      if (sideBySide) {
        const sashLeft = sash.sashLeft.read(reader);
        const movedBlocksLinesWidth = this.N.read(reader)?.width.read(reader) ?? 0;
        originalLeft = 0;
        originalWidth = sashLeft - gutterWidth - movedBlocksLinesWidth;
        gutterLeft = sashLeft - gutterWidth;
        modifiedLeft = sashLeft;
        modifiedWidth = fullWidth - modifiedLeft - overviewRulerPartWidth;
      } else {
        gutterLeft = 0;
        const shouldHideOriginalLineNumbers = this.J.inlineViewHideOriginalLineNumbers.read(reader);
        originalLeft = gutterWidth;
        if (shouldHideOriginalLineNumbers) {
          originalWidth = 0;
        } else {
          originalWidth = Math.max(5, this.L.originalObs.layoutInfoDecorationsLeft.read(reader));
        }
        modifiedLeft = gutterWidth + originalWidth;
        modifiedWidth = fullWidth - modifiedLeft - overviewRulerPartWidth;
      }
      this.j.original.style.left = originalLeft + "px";
      this.j.original.style.width = originalWidth + "px";
      this.L.original.layout({ width: originalWidth, height: fullHeight }, true);
      gutter?.layout(gutterLeft);
      this.j.modified.style.left = modifiedLeft + "px";
      this.j.modified.style.width = modifiedWidth + "px";
      this.L.modified.layout({ width: modifiedWidth, height: fullHeight }, true);
      return {
        modifiedEditor: this.L.modified.getLayoutInfo(),
        originalEditor: this.L.original.getLayoutInfo()
      };
    });
    this.$ = this.t.map((m, r2) => m?.diff.read(r2));
    this.onDidUpdateDiff = Event2.fromObservableLight(this.$);
    codeEditorService.willCreateDiffEditor();
    this.u.createKey("isInDiffEditor", true);
    this.P.appendChild(this.j.root);
    this.B($1c(() => this.j.root.remove()));
    this.z = this.B(new $U9(this.j.root, options3.dimension));
    this.z.setAutomaticLayout(options3.automaticLayout ?? false);
    this.J = this.y.createInstance($a$, options3);
    this.B($td((reader) => {
      this.J.setWidth(this.z.width.read(reader));
    }));
    this.u.createKey(EditorContextKeys.isEmbeddedDiffEditor.key, false);
    this.B($H9(EditorContextKeys.isEmbeddedDiffEditor, this.u, (reader) => this.J.isInEmbeddedEditor.read(reader)));
    this.B($H9(EditorContextKeys.comparingMovedCode, this.u, (reader) => !!this.t.read(reader)?.movedTextToCompare.read(reader)));
    this.B($H9(EditorContextKeys.diffEditorRenderSideBySideInlineBreakpointReached, this.u, (reader) => this.J.couldShowInlineViewBecauseOfSize.read(reader)));
    this.B($H9(EditorContextKeys.diffEditorInlineMode, this.u, (reader) => !this.J.renderSideBySide.read(reader)));
    this.B($H9(EditorContextKeys.hasChanges, this.u, (reader) => (this.t.read(reader)?.diff.read(reader)?.mappings.length ?? 0) > 0));
    this.L = this.B(this.y.createInstance($g$, this.j.original, this.j.modified, this.J, codeEditorWidgetOptions, (i2, c, o, o2) => this.W(i2, c, o, o2)));
    this.B($H9(EditorContextKeys.diffEditorOriginalWritable, this.u, (reader) => this.J.originalEditable.read(reader)));
    this.B($H9(EditorContextKeys.diffEditorModifiedWritable, this.u, (reader) => !this.J.readOnly.read(reader)));
    this.B($H9(EditorContextKeys.diffEditorOriginalUri, this.u, (reader) => this.t.read(reader)?.model.original.uri.toString() ?? ""));
    this.B($H9(EditorContextKeys.diffEditorModifiedUri, this.u, (reader) => this.t.read(reader)?.model.modified.uri.toString() ?? ""));
    this.M = $7d(this, (reader) => !this.J.renderOverviewRuler.read(reader) ? void 0 : this.y.createInstance($N3($f$, reader), this.L, this.j.root, this.t, this.z.width, this.z.height, this.X.map((i2) => i2.modifiedEditor))).recomputeInitiallyAndOnChange(this.q);
    const dimensions = {
      height: this.z.height,
      width: this.z.width.map((w, reader) => w - (this.M.read(reader)?.width ?? 0))
    };
    this.C = new $l$(this.J, dimensions);
    this.D = $7d(this, (reader) => {
      const showSash = this.J.renderSideBySide.read(reader);
      this.j.root.classList.toggle("side-by-side", showSash);
      return !showSash ? void 0 : new $m$(this.j.root, dimensions, this.J.enableSplitViewResizing, this.F, this.C.sashLeft, () => this.C.resetSash());
    }).recomputeInitiallyAndOnChange(this.q);
    const unchangedRangesFeature = $7d(this, (reader) => (
      /** @description UnchangedRangesFeature */
      this.y.createInstance($N3($_$, reader), this.L, this.t, this.J)
    )).recomputeInitiallyAndOnChange(this.q);
    $7d(this, (reader) => (
      /** @description DiffEditorDecorations */
      this.y.createInstance($N3($k$, reader), this.L, this.t, this.J, this)
    )).recomputeInitiallyAndOnChange(this.q);
    const origViewZoneIdsToIgnore = /* @__PURE__ */ new Set();
    const modViewZoneIdsToIgnore = /* @__PURE__ */ new Set();
    let isUpdatingViewZones = false;
    const viewZoneManager = $7d(this, (reader) => (
      /** @description ViewZoneManager */
      this.y.createInstance($N3($00, reader), getWindow(this.P), this.L, this.t, this.J, this, () => isUpdatingViewZones || unchangedRangesFeature.get().isUpdatingHiddenAreas, origViewZoneIdsToIgnore, modViewZoneIdsToIgnore)
    )).recomputeInitiallyAndOnChange(this.q);
    const originalViewZones = $2d(this, (reader) => {
      const orig = viewZoneManager.read(reader).viewZones.read(reader).orig;
      const orig2 = unchangedRangesFeature.read(reader).viewZones.read(reader).origViewZones;
      return orig.concat(orig2);
    });
    const modifiedViewZones = $2d(this, (reader) => {
      const mod = viewZoneManager.read(reader).viewZones.read(reader).mod;
      const mod2 = unchangedRangesFeature.read(reader).viewZones.read(reader).modViewZones;
      return mod.concat(mod2);
    });
    this.B($29(this.L.original, originalViewZones, (isUpdatingOrigViewZones) => {
      isUpdatingViewZones = isUpdatingOrigViewZones;
    }, origViewZoneIdsToIgnore));
    let scrollState;
    this.B($29(this.L.modified, modifiedViewZones, (isUpdatingModViewZones) => {
      isUpdatingViewZones = isUpdatingModViewZones;
      if (isUpdatingViewZones) {
        scrollState = $O9.capture(this.L.modified);
      } else {
        scrollState?.restore(this.L.modified);
        scrollState = void 0;
      }
    }, modViewZoneIdsToIgnore));
    this.I = $7d(this, (reader) => this.y.createInstance($N3($h$, reader), this.j.accessibleDiffViewer, this.H, (visible, tx) => this.G.set(visible, tx), this.J.onlyShowAccessibleDiffViewer.map((v) => !v), this.z.width, this.z.height, this.t.map((m, r2) => m?.diff.read(r2)?.mappings.map((m2) => m2.lineRangeMapping)), new $i$(this.L))).recomputeInitiallyAndOnChange(this.q);
    const visibility = this.H.map((v) => v ? "hidden" : "visible");
    this.B($19(this.j.modified, { visibility }));
    this.B($19(this.j.original, { visibility }));
    this.Y();
    codeEditorService.addDiffEditor(this);
    this.O = $7d(this, (reader) => {
      return this.J.shouldRenderGutterMenu.read(reader) ? this.y.createInstance($N3($$$, reader), this.j.root, this.t, this.L, this.J, this.C, this.F) : void 0;
    });
    this.B($Nd(this.X));
    $7d(this, (reader) => (
      /** @description MovedBlocksLinesPart */
      new ($N3($j$, reader))(this.j.root, this.t, this.X.map((i2) => i2.originalEditor), this.X.map((i2) => i2.modifiedEditor), this.L)
    )).recomputeInitiallyAndOnChange(this.q, (value) => {
      this.N.set(value, void 0);
    });
    this.B(Event2.runAndSubscribe(this.L.modified.onDidChangeCursorPosition, (e) => this.bb(e, true)));
    this.B(Event2.runAndSubscribe(this.L.original.onDidChangeCursorPosition, (e) => this.bb(e, false)));
    const isInitializingDiff = this.t.map(this, (m, reader) => {
      if (!m) {
        return void 0;
      }
      return m.diff.read(reader) === void 0 && !m.isDiffUpToDate.read(reader);
    });
    this.B($xd((reader, store) => {
      if (isInitializingDiff.read(reader) === true) {
        const r2 = this.U.show(true, 1e3);
        store.add($1c(() => r2.done()));
      }
    }));
    this.B($xd((reader, store) => {
      store.add(new ($N3($a_, reader))(this.L, this.t, this.J, this));
    }));
    this.B($xd((reader, store) => {
      const model = this.t.read(reader);
      if (!model) {
        return;
      }
      for (const m of [model.model.original, model.model.modified]) {
        store.add(m.onWillDispose((e) => {
          $gb(new $vb("TextModel got disposed before DiffEditorWidget model got reset"));
          this.setModel(null);
        }));
      }
    }));
    this.B($td((reader) => {
      this.J.setModel(this.t.read(reader));
    }));
  }
  getViewWidth() {
    return this.z.width.get();
  }
  getContentHeight() {
    return this.L.modified.getContentHeight();
  }
  W(instantiationService, container2, options3, editorWidgetOptions) {
    const editor = instantiationService.createInstance($D9, container2, options3, editorWidgetOptions);
    return editor;
  }
  Y() {
    const contributions = EditorExtensionsRegistry.getDiffEditorContributions();
    for (const desc of contributions) {
      try {
        this.B(this.y.createInstance(desc.ctor, this));
      } catch (err) {
        $gb(err);
      }
    }
  }
  get g() {
    return this.L.modified;
  }
  getEditorType() {
    return EditorType.IDiffEditor;
  }
  onVisible() {
    this.L.original.onVisible();
    this.L.modified.onVisible();
  }
  onHide() {
    this.L.original.onHide();
    this.L.modified.onHide();
  }
  layout(dimension) {
    this.z.observe(dimension);
  }
  hasTextFocus() {
    return this.L.original.hasTextFocus() || this.L.modified.hasTextFocus();
  }
  saveViewState() {
    const originalViewState = this.L.original.saveViewState();
    const modifiedViewState = this.L.modified.saveViewState();
    return {
      original: originalViewState,
      modified: modifiedViewState,
      modelState: this.t.get()?.serializeState()
    };
  }
  restoreViewState(s) {
    if (s && s.original && s.modified) {
      const diffEditorState = s;
      this.L.original.restoreViewState(diffEditorState.original);
      this.L.modified.restoreViewState(diffEditorState.modified);
      if (diffEditorState.modelState) {
        this.t.get()?.restoreSerializedState(diffEditorState.modelState);
      }
    }
  }
  handleInitialized() {
    this.L.original.handleInitialized();
    this.L.modified.handleInitialized();
  }
  createViewModel(model) {
    return this.y.createInstance($b$, model, this.J);
  }
  getModel() {
    return this.t.get()?.model ?? null;
  }
  setModel(model) {
    const vm = !model ? null : "model" in model ? $69.create(model).createNewRef(this) : $69.create(this.createViewModel(model), this);
    this.setDiffModel(vm);
  }
  setDiffModel(viewModel, tx) {
    const currentModel = this.t.get();
    if (!viewModel && currentModel) {
      this.I.get().close();
    }
    if (this.t.get() !== viewModel?.object) {
      $fe(tx, (tx2) => {
        const vm = viewModel?.object;
        $Dd.batchEventsGlobally(tx2, () => {
          this.L.original.setModel(vm ? vm.model.original : null);
          this.L.modified.setModel(vm ? vm.model.modified : null);
        });
        const prevValueRef = this.n.get()?.createNewRef(this);
        this.n.set(viewModel?.createNewRef(this), tx2);
        setTimeout(() => {
          prevValueRef?.dispose();
        }, 0);
      });
    }
  }
  /**
   * @param changedOptions Only has values for top-level options that have actually changed.
   */
  updateOptions(changedOptions) {
    this.J.updateOptions(changedOptions);
  }
  getDomNode() {
    return this.j.root;
  }
  getContainerDomNode() {
    return this.P;
  }
  getOriginalEditor() {
    return this.L.original;
  }
  getModifiedEditor() {
    return this.L.modified;
  }
  setBoundarySashes(sashes) {
    this.F.set(sashes, void 0);
  }
  get ignoreTrimWhitespace() {
    return this.J.ignoreTrimWhitespace.get();
  }
  get maxComputationTime() {
    return this.J.maxComputationTimeMs.get();
  }
  get renderSideBySide() {
    return this.J.renderSideBySide.get();
  }
  /**
   * @deprecated Use `this.getDiffComputationResult().changes2` instead.
   */
  getLineChanges() {
    const diffState = this.t.get()?.diff.get();
    if (!diffState) {
      return null;
    }
    return $d_(diffState);
  }
  getDiffComputationResult() {
    const diffState = this.t.get()?.diff.get();
    if (!diffState) {
      return null;
    }
    return {
      changes: this.getLineChanges(),
      changes2: diffState.mappings.map((m) => m.lineRangeMapping),
      identical: diffState.identical,
      quitEarly: diffState.quitEarly
    };
  }
  revert(diff3) {
    const model = this.t.get();
    if (!model || !model.isDiffUpToDate.get()) {
      return;
    }
    this.L.modified.executeEdits("diffEditor", [
      {
        range: diff3.modified.toExclusiveRange(),
        text: model.model.original.getValueInRange(diff3.original.toExclusiveRange())
      }
    ]);
  }
  revertRangeMappings(diffs) {
    const model = this.t.get();
    if (!model || !model.isDiffUpToDate.get()) {
      return;
    }
    const changes = diffs.map((c) => ({
      range: c.modifiedRange,
      text: model.model.original.getValueInRange(c.originalRange)
    }));
    this.L.modified.executeEdits("diffEditor", changes);
  }
  ab(diff3) {
    this.L.modified.setPosition(new $8C(diff3.lineRangeMapping.modified.startLineNumber, 1));
    this.L.modified.revealRangeInCenter(diff3.lineRangeMapping.modified.toExclusiveRange());
  }
  goToDiff(target) {
    const diffs = this.t.get()?.diff.get()?.mappings;
    if (!diffs || diffs.length === 0) {
      return;
    }
    const curLineNumber = this.L.modified.getPosition().lineNumber;
    let diff3;
    if (target === "next") {
      diff3 = diffs.find((d) => d.lineRangeMapping.modified.startLineNumber > curLineNumber) ?? diffs[0];
    } else {
      diff3 = $1(diffs, (d) => d.lineRangeMapping.modified.startLineNumber < curLineNumber) ?? diffs[diffs.length - 1];
    }
    this.ab(diff3);
    if (diff3.lineRangeMapping.modified.isEmpty) {
      this.S.playSignal($N9.diffLineDeleted, { source: "diffEditor.goToDiff" });
    } else if (diff3.lineRangeMapping.original.isEmpty) {
      this.S.playSignal($N9.diffLineInserted, { source: "diffEditor.goToDiff" });
    } else if (diff3) {
      this.S.playSignal($N9.diffLineModified, { source: "diffEditor.goToDiff" });
    }
  }
  revealFirstDiff() {
    const diffModel = this.t.get();
    if (!diffModel) {
      return;
    }
    this.waitForDiff().then(() => {
      const diffs = diffModel.diff.get()?.mappings;
      if (!diffs || diffs.length === 0) {
        return;
      }
      this.ab(diffs[0]);
    });
  }
  accessibleDiffViewerNext() {
    this.I.get().next();
  }
  accessibleDiffViewerPrev() {
    this.I.get().prev();
  }
  async waitForDiff() {
    const diffModel = this.t.get();
    if (!diffModel) {
      return;
    }
    await diffModel.waitForDiff();
  }
  mapToOtherSide() {
    const isModifiedFocus = this.L.modified.hasWidgetFocus();
    const source = isModifiedFocus ? this.L.modified : this.L.original;
    const destination = isModifiedFocus ? this.L.original : this.L.modified;
    let destinationSelection;
    const sourceSelection = source.getSelection();
    if (sourceSelection) {
      const mappings = this.t.get()?.diff.get()?.mappings.map((m) => isModifiedFocus ? m.lineRangeMapping.flip() : m.lineRangeMapping);
      if (mappings) {
        const newRange1 = $49(sourceSelection.getStartPosition(), mappings);
        const newRange2 = $49(sourceSelection.getEndPosition(), mappings);
        destinationSelection = $9C.plusRange(newRange1, newRange2);
      }
    }
    return { destination, destinationSelection };
  }
  switchSide() {
    const { destination, destinationSelection } = this.mapToOtherSide();
    destination.focus();
    if (destinationSelection) {
      destination.setSelection(destinationSelection);
    }
  }
  exitCompareMove() {
    const model = this.t.get();
    if (!model) {
      return;
    }
    model.movedTextToCompare.set(void 0, void 0);
  }
  collapseAllUnchangedRegions() {
    const unchangedRegions = this.t.get()?.unchangedRegions.get();
    if (!unchangedRegions) {
      return;
    }
    $ce((tx) => {
      for (const region of unchangedRegions) {
        region.collapseAll(tx);
      }
    });
  }
  showAllUnchangedRegions() {
    const unchangedRegions = this.t.get()?.unchangedRegions.get();
    if (!unchangedRegions) {
      return;
    }
    $ce((tx) => {
      for (const region of unchangedRegions) {
        region.showAll(tx);
      }
    });
  }
  bb(e, isModifiedEditor) {
    if (e?.reason === 3) {
      const diff3 = this.t.get()?.diff.get()?.mappings.find((m) => isModifiedEditor ? m.lineRangeMapping.modified.contains(e.position.lineNumber) : m.lineRangeMapping.original.contains(e.position.lineNumber));
      if (diff3?.lineRangeMapping.modified.isEmpty) {
        this.S.playSignal($N9.diffLineDeleted, { source: "diffEditor.cursorPositionChanged" });
      } else if (diff3?.lineRangeMapping.original.isEmpty) {
        this.S.playSignal($N9.diffLineInserted, { source: "diffEditor.cursorPositionChanged" });
      } else if (diff3) {
        this.S.playSignal($N9.diffLineModified, { source: "diffEditor.cursorPositionChanged" });
      }
    }
  }
};
$c_ = __decorate([
  __param(3, $on),
  __param(4, $Pk),
  __param(5, $U5),
  __param(6, $I9),
  __param(7, $ZJ)
], $c_);
function $d_(state) {
  return state.mappings.map((x) => {
    const m = x.lineRangeMapping;
    let originalStartLineNumber;
    let originalEndLineNumber;
    let modifiedStartLineNumber;
    let modifiedEndLineNumber;
    let innerChanges = m.innerChanges;
    if (m.original.isEmpty) {
      originalStartLineNumber = m.original.startLineNumber - 1;
      originalEndLineNumber = 0;
      innerChanges = void 0;
    } else {
      originalStartLineNumber = m.original.startLineNumber;
      originalEndLineNumber = m.original.endLineNumberExclusive - 1;
    }
    if (m.modified.isEmpty) {
      modifiedStartLineNumber = m.modified.startLineNumber - 1;
      modifiedEndLineNumber = 0;
      innerChanges = void 0;
    } else {
      modifiedStartLineNumber = m.modified.startLineNumber;
      modifiedEndLineNumber = m.modified.endLineNumberExclusive - 1;
    }
    return {
      originalStartLineNumber,
      originalEndLineNumber,
      modifiedStartLineNumber,
      modifiedEndLineNumber,
      charChanges: innerChanges?.map((m2) => ({
        originalStartLineNumber: m2.originalRange.startLineNumber,
        originalStartColumn: m2.originalRange.startColumn,
        originalEndLineNumber: m2.originalRange.endLineNumber,
        originalEndColumn: m2.originalRange.endColumn,
        modifiedStartLineNumber: m2.modifiedRange.startLineNumber,
        modifiedStartColumn: m2.modifiedRange.startColumn,
        modifiedEndLineNumber: m2.modifiedRange.endLineNumber,
        modifiedEndColumn: m2.modifiedRange.endColumn
      }))
    };
  });
}

// out-build/vs/editor/browser/widget/diffEditor/commands.js
var $e_ = class extends $gJ {
  constructor() {
    super({
      id: "diffEditor.toggleCollapseUnchangedRegions",
      title: localize2(196, "Toggle Collapse Unchanged Regions"),
      icon: $6l.map,
      toggled: $7m.has("config.diffEditor.hideUnchangedRegions.enabled"),
      precondition: $7m.has("isInDiffEditor"),
      menu: {
        when: $7m.has("isInDiffEditor"),
        id: $bJ.EditorTitle,
        order: 22,
        group: "navigation"
      }
    });
  }
  run(accessor, ...args2) {
    const configurationService = accessor.get($kl);
    const newValue = !configurationService.getValue("diffEditor.hideUnchangedRegions.enabled");
    configurationService.updateValue("diffEditor.hideUnchangedRegions.enabled", newValue);
  }
};
var $f_ = class extends $gJ {
  constructor() {
    super({
      id: "diffEditor.toggleShowMovedCodeBlocks",
      title: localize2(197, "Toggle Show Moved Code Blocks"),
      precondition: $7m.has("isInDiffEditor")
    });
  }
  run(accessor, ...args2) {
    const configurationService = accessor.get($kl);
    const newValue = !configurationService.getValue("diffEditor.experimental.showMoves");
    configurationService.updateValue("diffEditor.experimental.showMoves", newValue);
  }
};
var $g_ = class extends $gJ {
  constructor() {
    super({
      id: "diffEditor.toggleUseInlineViewWhenSpaceIsLimited",
      title: localize2(198, "Toggle Use Inline View When Space Is Limited"),
      precondition: $7m.has("isInDiffEditor")
    });
  }
  run(accessor, ...args2) {
    const configurationService = accessor.get($kl);
    const newValue = !configurationService.getValue("diffEditor.useInlineViewWhenSpaceIsLimited");
    configurationService.updateValue("diffEditor.useInlineViewWhenSpaceIsLimited", newValue);
  }
};
var diffEditorCategory = localize2(199, "Diff Editor");
var $h_ = class extends $25 {
  constructor() {
    super({
      id: "diffEditor.switchSide",
      title: localize2(200, "Switch Side"),
      icon: $6l.arrowSwap,
      precondition: $7m.has("isInDiffEditor"),
      f1: true,
      category: diffEditorCategory
    });
  }
  runEditorCommand(accessor, editor, arg) {
    const diffEditor = $p_(accessor);
    if (diffEditor instanceof $c_) {
      if (arg && arg.dryRun) {
        return { destinationSelection: diffEditor.mapToOtherSide().destinationSelection };
      } else {
        diffEditor.switchSide();
      }
    }
    return void 0;
  }
};
var $i_ = class extends $25 {
  constructor() {
    super({
      id: "diffEditor.exitCompareMove",
      title: localize2(201, "Exit Compare Move"),
      icon: $6l.close,
      precondition: EditorContextKeys.comparingMovedCode,
      f1: false,
      category: diffEditorCategory,
      keybinding: {
        weight: 1e4,
        primary: 9
      }
    });
  }
  runEditorCommand(accessor, editor, ...args2) {
    const diffEditor = $p_(accessor);
    if (diffEditor instanceof $c_) {
      diffEditor.exitCompareMove();
    }
  }
};
var $j_ = class extends $25 {
  constructor() {
    super({
      id: "diffEditor.collapseAllUnchangedRegions",
      title: localize2(202, "Collapse All Unchanged Regions"),
      icon: $6l.fold,
      precondition: $7m.has("isInDiffEditor"),
      f1: true,
      category: diffEditorCategory
    });
  }
  runEditorCommand(accessor, editor, ...args2) {
    const diffEditor = $p_(accessor);
    if (diffEditor instanceof $c_) {
      diffEditor.collapseAllUnchangedRegions();
    }
  }
};
var $k_ = class extends $25 {
  constructor() {
    super({
      id: "diffEditor.showAllUnchangedRegions",
      title: localize2(203, "Show All Unchanged Regions"),
      icon: $6l.unfold,
      precondition: $7m.has("isInDiffEditor"),
      f1: true,
      category: diffEditorCategory
    });
  }
  runEditorCommand(accessor, editor, ...args2) {
    const diffEditor = $p_(accessor);
    if (diffEditor instanceof $c_) {
      diffEditor.showAllUnchangedRegions();
    }
  }
};
var $l_ = class extends $gJ {
  constructor() {
    super({
      id: "diffEditor.revert",
      title: localize2(204, "Revert"),
      f1: false,
      category: diffEditorCategory
    });
  }
  run(accessor, arg) {
    const diffEditor = $o_(accessor, arg.originalUri, arg.modifiedUri);
    if (diffEditor instanceof $c_) {
      diffEditor.revertRangeMappings(arg.mapping.innerChanges ?? []);
    }
    return void 0;
  }
};
var accessibleDiffViewerCategory = localize2(205, "Accessible Diff Viewer");
var $m_ = class _$m_ extends $gJ {
  static {
    this.id = "editor.action.accessibleDiffViewer.next";
  }
  constructor() {
    super({
      id: _$m_.id,
      title: localize2(206, "Go to Next Difference"),
      category: accessibleDiffViewerCategory,
      precondition: $7m.has("isInDiffEditor"),
      keybinding: {
        primary: 65,
        weight: 100
        /* KeybindingWeight.EditorContrib */
      },
      f1: true
    });
  }
  run(accessor) {
    const diffEditor = $p_(accessor);
    diffEditor?.accessibleDiffViewerNext();
  }
};
var $n_ = class _$n_ extends $gJ {
  static {
    this.id = "editor.action.accessibleDiffViewer.prev";
  }
  constructor() {
    super({
      id: _$n_.id,
      title: localize2(207, "Go to Previous Difference"),
      category: accessibleDiffViewerCategory,
      precondition: $7m.has("isInDiffEditor"),
      keybinding: {
        primary: 1024 | 65,
        weight: 100
        /* KeybindingWeight.EditorContrib */
      },
      f1: true
    });
  }
  run(accessor) {
    const diffEditor = $p_(accessor);
    diffEditor?.accessibleDiffViewerPrev();
  }
};
function $o_(accessor, originalUri, modifiedUri) {
  const codeEditorService = accessor.get($U5);
  const diffEditors = codeEditorService.listDiffEditors();
  return diffEditors.find((diffEditor) => {
    const modified = diffEditor.getModifiedEditor();
    const original = diffEditor.getOriginalEditor();
    return modified && modified.getModel()?.uri.toString() === modifiedUri.toString() && original && original.getModel()?.uri.toString() === originalUri.toString();
  }) || null;
}
function $p_(accessor) {
  const codeEditorService = accessor.get($U5);
  const diffEditors = codeEditorService.listDiffEditors();
  const activeElement = $Lj();
  if (activeElement) {
    for (const d of diffEditors) {
      const container2 = d.getContainerDomNode();
      if (isElementOrParentOf(container2, activeElement)) {
        return d;
      }
    }
  }
  return null;
}
function isElementOrParentOf(elementOrParent, element) {
  let e = element;
  while (e) {
    if (e === elementOrParent) {
      return true;
    }
    e = e.parentElement;
  }
  return false;
}

// out-build/vs/editor/browser/widget/diffEditor/diffEditor.contribution.js
$hJ($e_);
$hJ($f_);
$hJ($g_);
$dJ.appendMenuItem($bJ.EditorTitle, {
  command: {
    id: new $g_().desc.id,
    title: localize(230, null),
    toggled: $7m.has("config.diffEditor.useInlineViewWhenSpaceIsLimited"),
    precondition: $7m.has("isInDiffEditor")
  },
  order: 11,
  group: "1_diff",
  when: $7m.and(EditorContextKeys.diffEditorRenderSideBySideInlineBreakpointReached, $7m.has("isInDiffEditor"))
});
$dJ.appendMenuItem($bJ.EditorTitle, {
  command: {
    id: new $f_().desc.id,
    title: localize(231, null),
    icon: $6l.move,
    toggled: $an.create("config.diffEditor.experimental.showMoves", true),
    precondition: $7m.has("isInDiffEditor")
  },
  order: 10,
  group: "1_diff",
  when: $7m.has("isInDiffEditor")
});
$hJ($l_);
for (const ctx of [
  { icon: $6l.arrowRight, key: EditorContextKeys.diffEditorInlineMode.toNegated() },
  { icon: $6l.discard, key: EditorContextKeys.diffEditorInlineMode }
]) {
  $dJ.appendMenuItem($bJ.DiffEditorHunkToolbar, {
    command: {
      id: new $l_().desc.id,
      title: localize(232, null),
      icon: ctx.icon
    },
    when: $7m.and(EditorContextKeys.diffEditorModifiedWritable, ctx.key),
    order: 5,
    group: "primary"
  });
  $dJ.appendMenuItem($bJ.DiffEditorSelectionToolbar, {
    command: {
      id: new $l_().desc.id,
      title: localize(233, null),
      icon: ctx.icon
    },
    when: $7m.and(EditorContextKeys.diffEditorModifiedWritable, ctx.key),
    order: 5,
    group: "primary"
  });
}
$hJ($h_);
$hJ($i_);
$hJ($j_);
$hJ($k_);
$dJ.appendMenuItem($bJ.EditorTitle, {
  command: {
    id: $m_.id,
    title: localize(234, null),
    precondition: $7m.has("isInDiffEditor")
  },
  order: 10,
  group: "2_diff",
  when: $7m.and(EditorContextKeys.accessibleDiffViewerVisible.negate(), $7m.has("isInDiffEditor"))
});
$tn.registerCommandAlias("editor.action.diffReview.next", $m_.id);
$hJ($m_);
$tn.registerCommandAlias("editor.action.diffReview.prev", $n_.id);
$hJ($n_);

// out-build/vs/editor/contrib/anchorSelect/browser/anchorSelect.js
var SelectionAnchorController_1;
var $q_ = new $nn("selectionAnchorSet", false);
var SelectionAnchorController = class SelectionAnchorController2 {
  static {
    SelectionAnchorController_1 = this;
  }
  static {
    this.ID = "editor.contrib.selectionAnchorController";
  }
  static get(editor) {
    return editor.getContribution(SelectionAnchorController_1.ID);
  }
  constructor(d, contextKeyService) {
    this.d = d;
    this.b = $q_.bindTo(contextKeyService);
    this.c = d.onDidChangeModel(() => this.b.reset());
  }
  setSelectionAnchor() {
    if (this.d.hasModel()) {
      const position = this.d.getPosition();
      this.d.changeDecorations((accessor) => {
        if (this.a) {
          accessor.removeDecoration(this.a);
        }
        this.a = accessor.addDecoration($_D.fromPositions(position, position), {
          description: "selection-anchor",
          stickiness: 1,
          hoverMessage: new $bm().appendText(localize(873, null)),
          className: "selection-anchor"
        });
      });
      this.b.set(!!this.a);
      $$Z(localize(874, null, position.lineNumber, position.column));
    }
  }
  goToSelectionAnchor() {
    if (this.d.hasModel() && this.a) {
      const anchorPosition = this.d.getModel().getDecorationRange(this.a);
      if (anchorPosition) {
        this.d.setPosition(anchorPosition.getStartPosition());
      }
    }
  }
  selectFromAnchorToCursor() {
    if (this.d.hasModel() && this.a) {
      const start = this.d.getModel().getDecorationRange(this.a);
      if (start) {
        const end = this.d.getPosition();
        this.d.setSelection($_D.fromPositions(start.getStartPosition(), end));
        this.cancelSelectionAnchor();
      }
    }
  }
  cancelSelectionAnchor() {
    if (this.a) {
      const decorationId = this.a;
      this.d.changeDecorations((accessor) => {
        accessor.removeDecoration(decorationId);
        this.a = void 0;
      });
      this.b.set(false);
    }
  }
  dispose() {
    this.cancelSelectionAnchor();
    this.c.dispose();
  }
};
SelectionAnchorController = SelectionAnchorController_1 = __decorate([
  __param(1, $on)
], SelectionAnchorController);
var SetSelectionAnchor = class extends $Z5 {
  constructor() {
    super({
      id: "editor.action.setSelectionAnchor",
      label: localize2(875, "Set Selection Anchor"),
      precondition: void 0,
      kbOpts: {
        kbExpr: EditorContextKeys.editorTextFocus,
        primary: $$e(
          2048 | 41,
          2048 | 32
          /* KeyCode.KeyB */
        ),
        weight: 100
        /* KeybindingWeight.EditorContrib */
      }
    });
  }
  async run(_accessor, editor) {
    SelectionAnchorController.get(editor)?.setSelectionAnchor();
  }
};
var GoToSelectionAnchor = class extends $Z5 {
  constructor() {
    super({
      id: "editor.action.goToSelectionAnchor",
      label: localize2(876, "Go to Selection Anchor"),
      precondition: $q_
    });
  }
  async run(_accessor, editor) {
    SelectionAnchorController.get(editor)?.goToSelectionAnchor();
  }
};
var SelectFromAnchorToCursor = class extends $Z5 {
  constructor() {
    super({
      id: "editor.action.selectFromAnchorToCursor",
      label: localize2(877, "Select from Anchor to Cursor"),
      precondition: $q_,
      kbOpts: {
        kbExpr: EditorContextKeys.editorTextFocus,
        primary: $$e(
          2048 | 41,
          2048 | 41
          /* KeyCode.KeyK */
        ),
        weight: 100
        /* KeybindingWeight.EditorContrib */
      }
    });
  }
  async run(_accessor, editor) {
    SelectionAnchorController.get(editor)?.selectFromAnchorToCursor();
  }
};
var CancelSelectionAnchor = class extends $Z5 {
  constructor() {
    super({
      id: "editor.action.cancelSelectionAnchor",
      label: localize2(878, "Cancel Selection Anchor"),
      precondition: $q_,
      kbOpts: {
        kbExpr: EditorContextKeys.editorTextFocus,
        primary: 9,
        weight: 100
        /* KeybindingWeight.EditorContrib */
      }
    });
  }
  async run(_accessor, editor) {
    SelectionAnchorController.get(editor)?.cancelSelectionAnchor();
  }
};
$85(
  SelectionAnchorController.ID,
  SelectionAnchorController,
  4
  /* EditorContributionInstantiation.Lazy */
);
$55(SetSelectionAnchor);
$55(GoToSelectionAnchor);
$55(SelectFromAnchorToCursor);
$55(CancelSelectionAnchor);

// out-build/vs/editor/contrib/bracketMatching/browser/bracketMatching.js
var overviewRulerBracketMatchForeground = $5n("editorOverviewRuler.bracketMatchForeground", "#A0A0A0", localize(879, null));
var JumpToBracketAction = class extends $Z5 {
  constructor() {
    super({
      id: "editor.action.jumpToBracket",
      label: localize2(881, "Go to Bracket"),
      precondition: void 0,
      kbOpts: {
        kbExpr: EditorContextKeys.editorTextFocus,
        primary: 2048 | 1024 | 93,
        weight: 100
        /* KeybindingWeight.EditorContrib */
      }
    });
  }
  run(accessor, editor) {
    $r_.get(editor)?.jumpToBracket();
  }
};
var SelectToBracketAction = class extends $Z5 {
  constructor() {
    super({
      id: "editor.action.selectToBracket",
      label: localize2(882, "Select to Bracket"),
      precondition: void 0,
      metadata: {
        description: localize2(883, "Select the text inside and including the brackets or curly braces"),
        args: [{
          name: "args",
          schema: {
            type: "object",
            properties: {
              "selectBrackets": {
                type: "boolean",
                default: true
              }
            }
          }
        }]
      }
    });
  }
  run(accessor, editor, args2) {
    let selectBrackets = true;
    if (args2 && args2.selectBrackets === false) {
      selectBrackets = false;
    }
    $r_.get(editor)?.selectToBracket(selectBrackets);
  }
};
var RemoveBracketsAction = class extends $Z5 {
  constructor() {
    super({
      id: "editor.action.removeBrackets",
      label: localize2(884, "Remove Brackets"),
      precondition: void 0,
      kbOpts: {
        kbExpr: EditorContextKeys.editorTextFocus,
        primary: 2048 | 512 | 1,
        weight: 100
        /* KeybindingWeight.EditorContrib */
      }
    });
  }
  run(accessor, editor) {
    $r_.get(editor)?.removeBrackets(this.id);
  }
};
var BracketsData = class {
  constructor(position, brackets, options3) {
    this.position = position;
    this.brackets = brackets;
    this.options = options3;
  }
};
var $r_ = class _$r_ extends $3c {
  static {
    this.ID = "editor.contrib.bracketMatchingController";
  }
  static get(editor) {
    return editor.getContribution(_$r_.ID);
  }
  constructor(editor) {
    super();
    this.a = editor;
    this.b = [];
    this.c = 0;
    this.f = this.a.createDecorationsCollection();
    this.g = this.B(new $8h(() => this.n(), 50));
    this.h = this.a.getOption(
      73
      /* EditorOption.matchBrackets */
    );
    this.g.schedule();
    this.B(editor.onDidChangeCursorPosition((e) => {
      if (this.h === "never") {
        return;
      }
      this.g.schedule();
    }));
    this.B(editor.onDidChangeModelContent((e) => {
      this.g.schedule();
    }));
    this.B(editor.onDidChangeModel((e) => {
      this.b = [];
      this.g.schedule();
    }));
    this.B(editor.onDidChangeModelLanguageConfiguration((e) => {
      this.b = [];
      this.g.schedule();
    }));
    this.B(editor.onDidChangeConfiguration((e) => {
      if (e.hasChanged(
        73
        /* EditorOption.matchBrackets */
      )) {
        this.h = this.a.getOption(
          73
          /* EditorOption.matchBrackets */
        );
        this.f.clear();
        this.b = [];
        this.c = 0;
        this.g.schedule();
      }
    }));
    this.B(editor.onDidBlurEditorWidget(() => {
      this.g.schedule();
    }));
    this.B(editor.onDidFocusEditorWidget(() => {
      this.g.schedule();
    }));
  }
  jumpToBracket() {
    if (!this.a.hasModel()) {
      return;
    }
    const model = this.a.getModel();
    const newSelections = this.a.getSelections().map((selection) => {
      const position = selection.getStartPosition();
      const brackets = model.bracketPairs.matchBracket(position);
      let newCursorPosition = null;
      if (brackets) {
        if (brackets[0].containsPosition(position) && !brackets[1].containsPosition(position)) {
          newCursorPosition = brackets[1].getStartPosition();
        } else if (brackets[1].containsPosition(position)) {
          newCursorPosition = brackets[0].getStartPosition();
        }
      } else {
        const enclosingBrackets = model.bracketPairs.findEnclosingBrackets(position);
        if (enclosingBrackets) {
          newCursorPosition = enclosingBrackets[1].getStartPosition();
        } else {
          const nextBracket = model.bracketPairs.findNextBracket(position);
          if (nextBracket && nextBracket.range) {
            newCursorPosition = nextBracket.range.getStartPosition();
          }
        }
      }
      if (newCursorPosition) {
        return new $_D(newCursorPosition.lineNumber, newCursorPosition.column, newCursorPosition.lineNumber, newCursorPosition.column);
      }
      return new $_D(position.lineNumber, position.column, position.lineNumber, position.column);
    });
    this.a.setSelections(newSelections);
    this.a.revealRange(newSelections[0]);
  }
  selectToBracket(selectBrackets) {
    if (!this.a.hasModel()) {
      return;
    }
    const model = this.a.getModel();
    const newSelections = [];
    this.a.getSelections().forEach((selection) => {
      const position = selection.getStartPosition();
      let brackets = model.bracketPairs.matchBracket(position);
      if (!brackets) {
        brackets = model.bracketPairs.findEnclosingBrackets(position);
        if (!brackets) {
          const nextBracket = model.bracketPairs.findNextBracket(position);
          if (nextBracket && nextBracket.range) {
            brackets = model.bracketPairs.matchBracket(nextBracket.range.getStartPosition());
          }
        }
      }
      let selectFrom = null;
      let selectTo = null;
      if (brackets) {
        brackets.sort($9C.compareRangesUsingStarts);
        const [open2, close2] = brackets;
        selectFrom = selectBrackets ? open2.getStartPosition() : open2.getEndPosition();
        selectTo = selectBrackets ? close2.getEndPosition() : close2.getStartPosition();
        if (close2.containsPosition(position)) {
          const tmp = selectFrom;
          selectFrom = selectTo;
          selectTo = tmp;
        }
      }
      if (selectFrom && selectTo) {
        newSelections.push(new $_D(selectFrom.lineNumber, selectFrom.column, selectTo.lineNumber, selectTo.column));
      }
    });
    if (newSelections.length > 0) {
      this.a.setSelections(newSelections);
      this.a.revealRange(newSelections[0]);
    }
  }
  removeBrackets(editSource) {
    if (!this.a.hasModel()) {
      return;
    }
    const model = this.a.getModel();
    this.a.getSelections().forEach((selection) => {
      const position = selection.getPosition();
      let brackets = model.bracketPairs.matchBracket(position);
      if (!brackets) {
        brackets = model.bracketPairs.findEnclosingBrackets(position);
      }
      if (brackets) {
        this.a.pushUndoStop();
        this.a.executeEdits(editSource, [
          { range: brackets[0], text: "" },
          { range: brackets[1], text: "" }
        ]);
        this.a.pushUndoStop();
      }
    });
  }
  static {
    this.j = $WI.register({
      description: "bracket-match-overview",
      stickiness: 1,
      className: "bracket-match",
      overviewRuler: {
        color: $hs(overviewRulerBracketMatchForeground),
        position: OverviewRulerLane.Center
      }
    });
  }
  static {
    this.m = $WI.register({
      description: "bracket-match-no-overview",
      stickiness: 1,
      className: "bracket-match"
    });
  }
  n() {
    if (this.h === "never") {
      return;
    }
    this.r();
    const newDecorations = [];
    let newDecorationsLen = 0;
    for (const bracketData of this.b) {
      const brackets = bracketData.brackets;
      if (brackets) {
        newDecorations[newDecorationsLen++] = { range: brackets[0], options: bracketData.options };
        newDecorations[newDecorationsLen++] = { range: brackets[1], options: bracketData.options };
      }
    }
    this.f.set(newDecorations);
  }
  r() {
    if (!this.a.hasModel() || !this.a.hasWidgetFocus()) {
      this.b = [];
      this.c = 0;
      return;
    }
    const selections = this.a.getSelections();
    if (selections.length > 100) {
      this.b = [];
      this.c = 0;
      return;
    }
    const model = this.a.getModel();
    const versionId = model.getVersionId();
    let previousData = [];
    if (this.c === versionId) {
      previousData = this.b;
    }
    const positions = [];
    let positionsLen = 0;
    for (let i2 = 0, len = selections.length; i2 < len; i2++) {
      const selection = selections[i2];
      if (selection.isEmpty()) {
        positions[positionsLen++] = selection.getStartPosition();
      }
    }
    if (positions.length > 1) {
      positions.sort($8C.compare);
    }
    const newData = [];
    let newDataLen = 0;
    let previousIndex = 0;
    const previousLen = previousData.length;
    for (let i2 = 0, len = positions.length; i2 < len; i2++) {
      const position = positions[i2];
      while (previousIndex < previousLen && previousData[previousIndex].position.isBefore(position)) {
        previousIndex++;
      }
      if (previousIndex < previousLen && previousData[previousIndex].position.equals(position)) {
        newData[newDataLen++] = previousData[previousIndex];
      } else {
        let brackets = model.bracketPairs.matchBracket(
          position,
          20
          /* give at most 20ms to compute */
        );
        let options3 = _$r_.j;
        if (!brackets && this.h === "always") {
          brackets = model.bracketPairs.findEnclosingBrackets(
            position,
            20
            /* give at most 20ms to compute */
          );
          options3 = _$r_.m;
        }
        newData[newDataLen++] = new BracketsData(position, brackets, options3);
      }
    }
    this.b = newData;
    this.c = versionId;
  }
};
$85(
  $r_.ID,
  $r_,
  1
  /* EditorContributionInstantiation.AfterFirstRender */
);
$55(SelectToBracketAction);
$55(JumpToBracketAction);
$55(RemoveBracketsAction);
$dJ.appendMenuItem($bJ.MenubarGoMenu, {
  group: "5_infile_nav",
  command: {
    id: "editor.action.jumpToBracket",
    title: localize(880, null)
  },
  order: 2
});

// out-build/vs/editor/contrib/caretOperations/browser/moveCaretCommand.js
var $s_ = class {
  constructor(selection, isMovingLeft) {
    this.a = selection;
    this.b = isMovingLeft;
  }
  getEditOperations(model, builder) {
    if (this.a.startLineNumber !== this.a.endLineNumber || this.a.isEmpty()) {
      return;
    }
    const lineNumber = this.a.startLineNumber;
    const startColumn = this.a.startColumn;
    const endColumn = this.a.endColumn;
    if (this.b && startColumn === 1) {
      return;
    }
    if (!this.b && endColumn === model.getLineMaxColumn(lineNumber)) {
      return;
    }
    if (this.b) {
      const rangeBefore = new $9C(lineNumber, startColumn - 1, lineNumber, startColumn);
      const charBefore = model.getValueInRange(rangeBefore);
      builder.addEditOperation(rangeBefore, null);
      builder.addEditOperation(new $9C(lineNumber, endColumn, lineNumber, endColumn), charBefore);
    } else {
      const rangeAfter = new $9C(lineNumber, endColumn, lineNumber, endColumn + 1);
      const charAfter = model.getValueInRange(rangeAfter);
      builder.addEditOperation(rangeAfter, null);
      builder.addEditOperation(new $9C(lineNumber, startColumn, lineNumber, startColumn), charAfter);
    }
  }
  computeCursorState(model, helper) {
    if (this.b) {
      return new $_D(this.a.startLineNumber, this.a.startColumn - 1, this.a.endLineNumber, this.a.endColumn - 1);
    } else {
      return new $_D(this.a.startLineNumber, this.a.startColumn + 1, this.a.endLineNumber, this.a.endColumn + 1);
    }
  }
};

// out-build/vs/editor/contrib/caretOperations/browser/caretOperations.js
var MoveCaretAction = class extends $Z5 {
  constructor(left, opts) {
    super(opts);
    this.d = left;
  }
  run(accessor, editor) {
    if (!editor.hasModel()) {
      return;
    }
    const commands2 = [];
    const selections = editor.getSelections();
    for (const selection of selections) {
      commands2.push(new $s_(selection, this.d));
    }
    editor.pushUndoStop();
    editor.executeCommands(this.id, commands2);
    editor.pushUndoStop();
  }
};
var MoveCaretLeftAction = class extends MoveCaretAction {
  constructor() {
    super(true, {
      id: "editor.action.moveCarretLeftAction",
      label: localize2(885, "Move Selected Text Left"),
      precondition: EditorContextKeys.writable
    });
  }
};
var MoveCaretRightAction = class extends MoveCaretAction {
  constructor() {
    super(false, {
      id: "editor.action.moveCarretRightAction",
      label: localize2(886, "Move Selected Text Right"),
      precondition: EditorContextKeys.writable
    });
  }
};
$55(MoveCaretLeftAction);
$55(MoveCaretRightAction);

// out-build/vs/editor/contrib/caretOperations/browser/transpose.js
var TransposeLettersAction = class extends $Z5 {
  constructor() {
    super({
      id: "editor.action.transposeLetters",
      label: localize2(887, "Transpose Letters"),
      precondition: EditorContextKeys.writable,
      kbOpts: {
        kbExpr: EditorContextKeys.textInputFocus,
        primary: 0,
        mac: {
          primary: 256 | 50
          /* KeyCode.KeyT */
        },
        weight: 100
        /* KeybindingWeight.EditorContrib */
      }
    });
  }
  run(accessor, editor) {
    if (!editor.hasModel()) {
      return;
    }
    const model = editor.getModel();
    const commands2 = [];
    const selections = editor.getSelections();
    for (const selection of selections) {
      if (!selection.isEmpty()) {
        continue;
      }
      const lineNumber = selection.startLineNumber;
      const column = selection.startColumn;
      const lastColumn = model.getLineMaxColumn(lineNumber);
      if (lineNumber === 1 && (column === 1 || column === 2 && lastColumn === 2)) {
        continue;
      }
      const endPosition = column === lastColumn ? selection.getPosition() : $k6.rightPosition(model, selection.getPosition().lineNumber, selection.getPosition().column);
      const middlePosition = $k6.leftPosition(model, endPosition);
      const beginPosition = $k6.leftPosition(model, middlePosition);
      const leftChar = model.getValueInRange($9C.fromPositions(beginPosition, middlePosition));
      const rightChar = model.getValueInRange($9C.fromPositions(middlePosition, endPosition));
      const replaceRange = $9C.fromPositions(beginPosition, endPosition);
      commands2.push(new $b6(replaceRange, rightChar + leftChar));
    }
    if (commands2.length > 0) {
      editor.pushUndoStop();
      editor.executeCommands(this.id, commands2);
      editor.pushUndoStop();
    }
  }
};
$55(TransposeLettersAction);

// out-build/vs/base/common/dataTransfer.js
function $jE(stringOrPromise) {
  return {
    asString: async () => stringOrPromise,
    asFile: () => void 0,
    value: typeof stringOrPromise === "string" ? stringOrPromise : void 0
  };
}
function $kE(fileName, uri, data) {
  const file = { id: $ps(), name: fileName, uri, data };
  return {
    asString: async () => "",
    asFile: () => file,
    value: void 0
  };
}
var $lE = class {
  constructor() {
    this.a = /* @__PURE__ */ new Map();
  }
  get size() {
    let size = 0;
    for (const _ of this.a) {
      size++;
    }
    return size;
  }
  has(mimeType) {
    return this.a.has(this.b(mimeType));
  }
  matches(pattern) {
    const mimes = [...this.a.keys()];
    if (Iterable.some(this, ([_, item]) => item.asFile())) {
      mimes.push("files");
    }
    return matchesMimeType_normalized(normalizeMimeType(pattern), mimes);
  }
  get(mimeType) {
    return this.a.get(this.b(mimeType))?.[0];
  }
  /**
   * Add a new entry to this data transfer.
   *
   * This does not replace existing entries for `mimeType`.
   */
  append(mimeType, value) {
    const existing = this.a.get(mimeType);
    if (existing) {
      existing.push(value);
    } else {
      this.a.set(this.b(mimeType), [value]);
    }
  }
  /**
   * Set the entry for a given mime type.
   *
   * This replaces all existing entries for `mimeType`.
   */
  replace(mimeType, value) {
    this.a.set(this.b(mimeType), [value]);
  }
  /**
   * Remove all entries for `mimeType`.
   */
  delete(mimeType) {
    this.a.delete(this.b(mimeType));
  }
  /**
   * Iterate over all `[mime, item]` pairs in this data transfer.
   *
   * There may be multiple entries for each mime type.
   */
  *[Symbol.iterator]() {
    for (const [mine, items] of this.a) {
      for (const item of items) {
        yield [mine, item];
      }
    }
  }
  b(mimeType) {
    return normalizeMimeType(mimeType);
  }
};
function normalizeMimeType(mimeType) {
  return mimeType.toLowerCase();
}
function $mE(pattern, mimeTypes) {
  return matchesMimeType_normalized(normalizeMimeType(pattern), mimeTypes.map(normalizeMimeType));
}
function matchesMimeType_normalized(normalizedPattern, normalizedMimeTypes) {
  if (normalizedPattern === "*/*") {
    return normalizedMimeTypes.length > 0;
  }
  if (normalizedMimeTypes.includes(normalizedPattern)) {
    return true;
  }
  const wildcard = normalizedPattern.match(/^([a-z]+)\/([a-z]+|\*)$/i);
  if (!wildcard) {
    return false;
  }
  const [_, type, subtype] = wildcard;
  if (subtype === "*") {
    return normalizedMimeTypes.some((mime) => mime.startsWith(type + "/"));
  }
  return false;
}
var $nE = Object.freeze({
  // http://amundsen.com/hypermedia/urilist/
  create: (entries2) => {
    return $Rb(entries2.map((x) => x.toString())).join("\r\n");
  },
  split: (str) => {
    return str.split("\r\n");
  },
  parse: (str) => {
    return $nE.split(str).filter((value) => !value.startsWith("#"));
  }
});

// out-build/vs/base/common/hierarchicalKind.js
var $oE = class _$oE {
  static {
    this.sep = ".";
  }
  static {
    this.None = new _$oE("@@none@@");
  }
  static {
    this.Empty = new _$oE("");
  }
  constructor(value) {
    this.value = value;
  }
  equals(other) {
    return this.value === other.value;
  }
  contains(other) {
    return this.equals(other) || this.value === "" || other.value.startsWith(this.value + _$oE.sep);
  }
  intersects(other) {
    return this.contains(other) || other.contains(this);
  }
  append(...parts) {
    return new _$oE((this.value ? [this.value, ...parts] : parts).join(_$oE.sep));
  }
};

// out-build/vs/platform/quickinput/common/quickInput.js
var $XM = { ctrlCmd: false, alt: false };
var QuickInputHideReason;
(function(QuickInputHideReason2) {
  QuickInputHideReason2[QuickInputHideReason2["Blur"] = 1] = "Blur";
  QuickInputHideReason2[QuickInputHideReason2["Gesture"] = 2] = "Gesture";
  QuickInputHideReason2[QuickInputHideReason2["Other"] = 3] = "Other";
})(QuickInputHideReason || (QuickInputHideReason = {}));
var QuickInputType;
(function(QuickInputType2) {
  QuickInputType2["QuickPick"] = "quickPick";
  QuickInputType2["InputBox"] = "inputBox";
  QuickInputType2["QuickWidget"] = "quickWidget";
})(QuickInputType || (QuickInputType = {}));
var ItemActivation;
(function(ItemActivation2) {
  ItemActivation2[ItemActivation2["NONE"] = 0] = "NONE";
  ItemActivation2[ItemActivation2["FIRST"] = 1] = "FIRST";
  ItemActivation2[ItemActivation2["SECOND"] = 2] = "SECOND";
  ItemActivation2[ItemActivation2["LAST"] = 3] = "LAST";
})(ItemActivation || (ItemActivation = {}));
var QuickPickFocus;
(function(QuickPickFocus2) {
  QuickPickFocus2[QuickPickFocus2["First"] = 1] = "First";
  QuickPickFocus2[QuickPickFocus2["Second"] = 2] = "Second";
  QuickPickFocus2[QuickPickFocus2["Last"] = 3] = "Last";
  QuickPickFocus2[QuickPickFocus2["Next"] = 4] = "Next";
  QuickPickFocus2[QuickPickFocus2["Previous"] = 5] = "Previous";
  QuickPickFocus2[QuickPickFocus2["NextPage"] = 6] = "NextPage";
  QuickPickFocus2[QuickPickFocus2["PreviousPage"] = 7] = "PreviousPage";
  QuickPickFocus2[QuickPickFocus2["NextSeparator"] = 8] = "NextSeparator";
  QuickPickFocus2[QuickPickFocus2["PreviousSeparator"] = 9] = "PreviousSeparator";
})(QuickPickFocus || (QuickPickFocus = {}));
var QuickInputButtonLocation;
(function(QuickInputButtonLocation3) {
  QuickInputButtonLocation3[QuickInputButtonLocation3["Title"] = 1] = "Title";
  QuickInputButtonLocation3[QuickInputButtonLocation3["Inline"] = 2] = "Inline";
})(QuickInputButtonLocation || (QuickInputButtonLocation = {}));
var $YM = class {
  constructor(a) {
    this.a = a;
  }
  getItemLabel(entry) {
    return entry.label;
  }
  getItemDescription(entry) {
    if (this.a?.skipDescription) {
      return void 0;
    }
    return entry.description;
  }
  getItemPath(entry) {
    if (this.a?.skipPath) {
      return void 0;
    }
    if (entry.resource?.scheme === Schemas.file) {
      return entry.resource.fsPath;
    }
    return entry.resource?.path;
  }
};
var $ZM = new $YM();
var $1M = $Qk("quickInputService");

// out-build/vs/base/common/labels.js
function $Zt(resource, formatting) {
  const { os, tildify: tildifier, relative: relatifier } = formatting;
  if (relatifier) {
    const relativePath = getRelativePathLabel(resource, relatifier, os);
    if (typeof relativePath === "string") {
      return relativePath;
    }
  }
  let absolutePath = resource.fsPath;
  if (os === 1 && !$l) {
    absolutePath = absolutePath.replace(/\//g, "\\");
  } else if (os !== 1 && $l) {
    absolutePath = absolutePath.replace(/\\/g, "/");
  }
  if (os !== 1 && tildifier?.userHome) {
    const userHome = tildifier.userHome.fsPath;
    let userHomeCandidate;
    if (resource.scheme !== tildifier.userHome.scheme && resource.path[0] === $kc.sep && resource.path[1] !== $kc.sep) {
      userHomeCandidate = tildifier.userHome.with({ path: resource.path }).fsPath;
    } else {
      userHomeCandidate = absolutePath;
    }
    absolutePath = $2t(userHomeCandidate, userHome, os);
  }
  const pathLib = os === 1 ? $jc : $kc;
  return pathLib.normalize($1t(
    absolutePath,
    os === 1
    /* OperatingSystem.Windows */
  ));
}
function getRelativePathLabel(resource, relativePathProvider, os) {
  const pathLib = os === 1 ? $jc : $kc;
  const extUriLib = os === 3 ? $lh : $nh;
  const workspace2 = relativePathProvider.getWorkspace();
  const firstFolder = workspace2.folders.at(0);
  if (!firstFolder) {
    return void 0;
  }
  if (resource.scheme !== firstFolder.uri.scheme && resource.path[0] === $kc.sep && resource.path[1] !== $kc.sep) {
    resource = firstFolder.uri.with({ path: resource.path });
  }
  const folder = relativePathProvider.getWorkspaceFolder(resource);
  if (!folder) {
    return void 0;
  }
  let relativePathLabel = void 0;
  if (extUriLib.isEqual(folder.uri, resource)) {
    relativePathLabel = "";
  } else {
    relativePathLabel = extUriLib.relativePath(folder.uri, resource) ?? "";
  }
  if (relativePathLabel) {
    relativePathLabel = pathLib.normalize(relativePathLabel);
  }
  if (workspace2.folders.length > 1 && !relativePathProvider.noPrefix) {
    const rootName = folder.name ? folder.name : extUriLib.basenameOrAuthority(folder.uri);
    relativePathLabel = relativePathLabel ? `${rootName} \u2022 ${relativePathLabel}` : rootName;
  }
  return relativePathLabel;
}
function $1t(path, isWindowsOS = $l) {
  if ($5g(path, isWindowsOS)) {
    return path.charAt(0).toUpperCase() + path.slice(1);
  }
  return path;
}
var normalizedUserHomeCached = /* @__PURE__ */ Object.create(null);
function $2t(path, userHome, os = OS) {
  if (os === 1 || !path || !userHome) {
    return path;
  }
  let normalizedUserHome = normalizedUserHomeCached.original === userHome ? normalizedUserHomeCached.normalized : void 0;
  if (!normalizedUserHome) {
    normalizedUserHome = userHome;
    if ($l) {
      normalizedUserHome = $Tg(normalizedUserHome);
    }
    normalizedUserHome = `${$Gf(normalizedUserHome, $kc.sep)}${$kc.sep}`;
    normalizedUserHomeCached = { original: userHome, normalized: normalizedUserHome };
  }
  let normalizedPath = path;
  if ($l) {
    normalizedPath = $Tg(normalizedPath);
  }
  if (os === 3 ? normalizedPath.startsWith(normalizedUserHome) : $2f(normalizedPath, normalizedUserHome)) {
    return `~/${normalizedPath.substr(normalizedUserHome.length)}`;
  }
  return path;
}
function $3t(path, userHome) {
  return path.replace(/^~($|\/|\\)/, `${userHome}$1`);
}
var ellipsis = "\u2026";
var unc = "\\\\";
var home = "~";
function $4t(paths, pathSeparator = sep) {
  const shortenedPaths = new Array(paths.length);
  let match = false;
  for (let pathIndex = 0; pathIndex < paths.length; pathIndex++) {
    const originalPath = paths[pathIndex];
    if (originalPath === "") {
      shortenedPaths[pathIndex] = `.${pathSeparator}`;
      continue;
    }
    if (!originalPath) {
      shortenedPaths[pathIndex] = originalPath;
      continue;
    }
    match = true;
    let prefix = "";
    let trimmedPath = originalPath;
    if (trimmedPath.indexOf(unc) === 0) {
      prefix = trimmedPath.substr(0, trimmedPath.indexOf(unc) + unc.length);
      trimmedPath = trimmedPath.substr(trimmedPath.indexOf(unc) + unc.length);
    } else if (trimmedPath.indexOf(pathSeparator) === 0) {
      prefix = trimmedPath.substr(0, trimmedPath.indexOf(pathSeparator) + pathSeparator.length);
      trimmedPath = trimmedPath.substr(trimmedPath.indexOf(pathSeparator) + pathSeparator.length);
    } else if (trimmedPath.indexOf(home) === 0) {
      prefix = trimmedPath.substr(0, trimmedPath.indexOf(home) + home.length);
      trimmedPath = trimmedPath.substr(trimmedPath.indexOf(home) + home.length);
    }
    const segments = trimmedPath.split(pathSeparator);
    for (let subpathLength = 1; match && subpathLength <= segments.length; subpathLength++) {
      for (let start = segments.length - subpathLength; match && start >= 0; start--) {
        match = false;
        let subpath = segments.slice(start, start + subpathLength).join(pathSeparator);
        for (let otherPathIndex = 0; !match && otherPathIndex < paths.length; otherPathIndex++) {
          if (otherPathIndex !== pathIndex && paths[otherPathIndex] && paths[otherPathIndex].indexOf(subpath) > -1) {
            const isSubpathEnding = start + subpathLength === segments.length;
            const subpathWithSep = start > 0 && paths[otherPathIndex].indexOf(pathSeparator) > -1 ? pathSeparator + subpath : subpath;
            const isOtherPathEnding = paths[otherPathIndex].endsWith(subpathWithSep);
            match = !isSubpathEnding || isOtherPathEnding;
          }
        }
        if (!match) {
          let result = "";
          if (segments[0].endsWith(":") || prefix !== "") {
            if (start === 1) {
              start = 0;
              subpathLength++;
              subpath = segments[0] + pathSeparator + subpath;
            }
            if (start > 0) {
              result = segments[0] + pathSeparator;
            }
            result = prefix + result;
          }
          if (start > 0) {
            result = result + ellipsis + pathSeparator;
          }
          result = result + subpath;
          if (start + subpathLength < segments.length) {
            result = result + pathSeparator + ellipsis;
          }
          shortenedPaths[pathIndex] = result;
        }
      }
    }
    if (match) {
      shortenedPaths[pathIndex] = originalPath;
    }
  }
  return shortenedPaths;
}
var Type;
(function(Type4) {
  Type4[Type4["TEXT"] = 0] = "TEXT";
  Type4[Type4["VARIABLE"] = 1] = "VARIABLE";
  Type4[Type4["SEPARATOR"] = 2] = "SEPARATOR";
})(Type || (Type = {}));
function $5t(template, values = /* @__PURE__ */ Object.create(null)) {
  const segments = [];
  let inVariable = false;
  let curVal = "";
  for (const char of template) {
    if (char === "$" || inVariable && char === "{") {
      if (curVal) {
        segments.push({ value: curVal, type: Type.TEXT });
      }
      curVal = "";
      inVariable = true;
    } else if (char === "}" && inVariable) {
      const resolved = values[curVal];
      if (typeof resolved === "string") {
        if (resolved.length) {
          segments.push({ value: resolved, type: Type.VARIABLE });
        }
      } else if (resolved) {
        const prevSegment = segments[segments.length - 1];
        if (!prevSegment || prevSegment.type !== Type.SEPARATOR) {
          segments.push({ value: resolved.label, type: Type.SEPARATOR });
        }
      }
      curVal = "";
      inVariable = false;
    } else {
      curVal += char;
    }
  }
  if (curVal && !inVariable) {
    segments.push({ value: curVal, type: Type.TEXT });
  }
  return segments.filter((segment, index) => {
    if (segment.type === Type.SEPARATOR) {
      const left = segments[index - 1];
      const right = segments[index + 1];
      return [left, right].every((segment2) => segment2 && (segment2.type === Type.VARIABLE || segment2.type === Type.TEXT) && segment2.value.length > 0);
    }
    return true;
  }).map((segment) => segment.value).join("");
}
function $6t(label3, forceDisableMnemonics) {
  if ($m || forceDisableMnemonics) {
    return label3.replace(/\(&&\w\)|&&/g, "").replace(/&/g, $m ? "&" : "&&");
  }
  return label3.replace(/&&|&/g, (m) => m === "&" ? "&&" : "&");
}
function $7t(label3, forceDisableMnemonics) {
  if ($m || forceDisableMnemonics) {
    return label3.replace(/\(&&\w\)|&&/g, "");
  }
  if ($l) {
    return label3.replace(/&&|&/g, (m) => m === "&" ? "&&" : "&");
  }
  return label3.replace(/&&/g, "_");
}
function $8t(label3) {
  return label3.replace(/&/g, "&&");
}
function $9t(recentLabel) {
  if (recentLabel.endsWith("]")) {
    const lastIndexOfSquareBracket = recentLabel.lastIndexOf(" [", recentLabel.length - 2);
    if (lastIndexOfSquareBracket !== -1) {
      const split = splitName(recentLabel.substring(0, lastIndexOfSquareBracket));
      const remoteNameWithSpace = recentLabel.substring(lastIndexOfSquareBracket);
      return { name: split.name + remoteNameWithSpace, parentPath: split.parentPath };
    }
  }
  return splitName(recentLabel);
}
function splitName(fullPath) {
  const p = fullPath.indexOf("/") !== -1 ? $kc : $jc;
  const name = p.basename(fullPath);
  const parentPath = p.dirname(fullPath);
  if (name.length) {
    return { name, parentPath };
  }
  return { name: parentPath, parentPath: "" };
}

// out-build/vs/platform/dialogs/common/dialogs.js
var $Yv = $Qk("dialogService");
var DialogKind;
(function(DialogKind2) {
  DialogKind2[DialogKind2["Confirmation"] = 1] = "Confirmation";
  DialogKind2[DialogKind2["Prompt"] = 2] = "Prompt";
  DialogKind2[DialogKind2["Input"] = 3] = "Input";
})(DialogKind || (DialogKind = {}));
var $Zv = class {
  a(dialog) {
    return this.d(dialog, DialogKind.Confirmation);
  }
  b(dialog) {
    return this.d(dialog, DialogKind.Prompt);
  }
  c(dialog) {
    return this.d(dialog, DialogKind.Input);
  }
  d(dialog, kind) {
    const buttons = [];
    switch (kind) {
      case DialogKind.Confirmation: {
        const confirmationDialog = dialog;
        if (confirmationDialog.primaryButton) {
          buttons.push(confirmationDialog.primaryButton);
        } else {
          buttons.push(localize(1729, null));
        }
        if (confirmationDialog.cancelButton) {
          buttons.push(confirmationDialog.cancelButton);
        } else {
          buttons.push(localize(1730, null));
        }
        break;
      }
      case DialogKind.Prompt: {
        const promptDialog = dialog;
        if (Array.isArray(promptDialog.buttons) && promptDialog.buttons.length > 0) {
          buttons.push(...promptDialog.buttons.map((button) => button.label));
        }
        if (promptDialog.cancelButton) {
          if (promptDialog.cancelButton === true) {
            buttons.push(localize(1731, null));
          } else if (typeof promptDialog.cancelButton === "string") {
            buttons.push(promptDialog.cancelButton);
          } else {
            if (promptDialog.cancelButton.label) {
              buttons.push(promptDialog.cancelButton.label);
            } else {
              buttons.push(localize(1732, null));
            }
          }
        }
        if (buttons.length === 0) {
          buttons.push(localize(1733, null));
        }
        break;
      }
      case DialogKind.Input: {
        const inputDialog = dialog;
        if (inputDialog.primaryButton) {
          buttons.push(inputDialog.primaryButton);
        } else {
          buttons.push(localize(1734, null));
        }
        if (inputDialog.cancelButton) {
          buttons.push(inputDialog.cancelButton);
        } else {
          buttons.push(localize(1735, null));
        }
        break;
      }
    }
    return buttons;
  }
  e(type) {
    if (typeof type === "string") {
      return type;
    }
    if (typeof type === "number") {
      return type === severity_default.Info ? "info" : type === severity_default.Error ? "error" : type === severity_default.Warning ? "warning" : "none";
    }
    return void 0;
  }
  f(prompt, buttonIndex, checkboxChecked) {
    const promptButtons = [...prompt.buttons ?? []];
    if (prompt.cancelButton && typeof prompt.cancelButton !== "string" && typeof prompt.cancelButton !== "boolean") {
      promptButtons.push(prompt.cancelButton);
    }
    let result = promptButtons[buttonIndex]?.run({ checkboxChecked });
    if (!(result instanceof Promise)) {
      result = Promise.resolve(result);
    }
    return { result, checkboxChecked };
  }
};
var $1v = $Qk("fileDialogService");
var ConfirmResult;
(function(ConfirmResult2) {
  ConfirmResult2[ConfirmResult2["SAVE"] = 0] = "SAVE";
  ConfirmResult2[ConfirmResult2["DONT_SAVE"] = 1] = "DONT_SAVE";
  ConfirmResult2[ConfirmResult2["CANCEL"] = 2] = "CANCEL";
})(ConfirmResult || (ConfirmResult = {}));
var MAX_CONFIRM_FILES = 10;
function $2v(fileNamesOrResources) {
  const message = [];
  message.push(...fileNamesOrResources.slice(0, MAX_CONFIRM_FILES).map((fileNameOrResource) => typeof fileNameOrResource === "string" ? fileNameOrResource : $sh(fileNameOrResource)));
  if (fileNamesOrResources.length > MAX_CONFIRM_FILES) {
    if (fileNamesOrResources.length - MAX_CONFIRM_FILES === 1) {
      message.push(localize(1736, null));
    } else {
      message.push(localize(1737, null, fileNamesOrResources.length - MAX_CONFIRM_FILES));
    }
  }
  message.push("");
  return message.join("\n");
}

// out-build/vs/platform/files/browser/webFileSystemAccess.js
var WebFileSystemAccess;
(function(WebFileSystemAccess2) {
  function supported(obj) {
    if (typeof obj?.showDirectoryPicker === "function") {
      return true;
    }
    return false;
  }
  WebFileSystemAccess2.supported = supported;
  function isFileSystemHandle(handle2) {
    const candidate = handle2;
    if (!candidate) {
      return false;
    }
    return typeof candidate.kind === "string" && typeof candidate.queryPermission === "function" && typeof candidate.requestPermission === "function";
  }
  WebFileSystemAccess2.isFileSystemHandle = isFileSystemHandle;
  function isFileSystemFileHandle(handle2) {
    return handle2.kind === "file";
  }
  WebFileSystemAccess2.isFileSystemFileHandle = isFileSystemFileHandle;
  function isFileSystemDirectoryHandle(handle2) {
    return handle2.kind === "directory";
  }
  WebFileSystemAccess2.isFileSystemDirectoryHandle = isFileSystemDirectoryHandle;
})(WebFileSystemAccess || (WebFileSystemAccess = {}));
var WebFileSystemObserver;
(function(WebFileSystemObserver2) {
  function supported(obj) {
    return typeof obj?.FileSystemObserver === "function";
  }
  WebFileSystemObserver2.supported = supported;
})(WebFileSystemObserver || (WebFileSystemObserver = {}));

// out-build/vs/base/browser/indexedDB.js
var MissingStoresError = class extends Error {
  constructor(db) {
    super("Missing stores");
    this.db = db;
  }
};
var $01 = class extends Error {
  constructor(dbName) {
    super(`IndexedDB database '${dbName}' is closed.`);
    this.code = "DBClosed";
  }
};
var $$1 = class _$$1 {
  static async create(name, version2, stores) {
    const database = await _$$1.a(name, version2, stores);
    return new _$$1(database, name);
  }
  static async a(name, version2, stores) {
    $S(`code/willOpenDatabase/${name}`);
    try {
      return await _$$1.b(name, version2, stores);
    } catch (err) {
      if (err instanceof MissingStoresError) {
        console.info(`Attempting to recreate the IndexedDB once.`, name);
        try {
          await _$$1.d(err.db);
        } catch (error) {
          console.error(`Error while deleting the IndexedDB`, $qb(error));
          throw error;
        }
        return await _$$1.b(name, version2, stores);
      }
      throw err;
    } finally {
      $S(`code/didOpenDatabase/${name}`);
    }
  }
  static b(name, version2, stores) {
    return new Promise((c, e) => {
      const request = indexedDB.open(name, version2);
      request.onerror = () => e(request.error);
      request.onsuccess = () => {
        const db = request.result;
        for (const store of stores) {
          if (!db.objectStoreNames.contains(store)) {
            console.error(`Error while opening IndexedDB. Could not find '${store}'' object store`);
            e(new MissingStoresError(db));
            return;
          }
        }
        c(db);
      };
      request.onupgradeneeded = () => {
        const db = request.result;
        for (const store of stores) {
          if (!db.objectStoreNames.contains(store)) {
            db.createObjectStore(store);
          }
        }
      };
    });
  }
  static d(database) {
    return new Promise((c, e) => {
      database.close();
      const deleteRequest = indexedDB.deleteDatabase(database.name);
      deleteRequest.onerror = (err) => e(deleteRequest.error);
      deleteRequest.onsuccess = () => c();
    });
  }
  static {
    this.PWB_CHANGED_CONNECTION_KEY = "pwb-changed-connections";
  }
  static {
    this.g = "pwb-connections";
  }
  pwbAddToSessionSet(key2) {
    const connectionString = sessionStorage.getItem(key2);
    let connectionSet;
    if (connectionString) {
      connectionSet = new Set(JSON.parse(connectionString));
      if (connectionSet.has(this.j)) {
        return;
      }
    } else {
      connectionSet = /* @__PURE__ */ new Set();
    }
    connectionSet.add(this.j);
    sessionStorage.setItem(key2, JSON.stringify(Array.from(connectionSet)));
  }
  pwbRemoveFromSessionSet(key2) {
    const connectionString = sessionStorage.getItem(key2);
    if (connectionString) {
      const connectionSet = new Set(JSON.parse(connectionString));
      if (connectionSet.delete(this.j)) {
        sessionStorage.setItem(key2, JSON.stringify(Array.from(connectionSet)));
      }
    }
  }
  pwbSaveDB() {
    this.f = true;
    this.pwbAddToSessionSet(_$$1.g);
  }
  pwbRemoveDB() {
    this.f = false;
    this.pwbRemoveFromSessionSet(_$$1.g);
  }
  async pwbOpen(stores) {
    if (!this.h) {
      throw new $01(this.j);
    }
    if (!this.f) {
      this.h = await _$$1.a(this.j, void 0, stores);
      this.pwbSaveDB();
    }
  }
  pwbClose() {
    if (this.i.length) {
      this.i.splice(0, this.i.length).forEach((transaction) => transaction.abort());
    }
    this.h?.close();
    this.pwbRemoveDB();
  }
  constructor(database, j) {
    this.j = j;
    this.f = true;
    this.h = null;
    this.i = [];
    this.h = database;
    this.pwbSaveDB();
  }
  hasPendingTransactions() {
    return this.i.length > 0;
  }
  close() {
    if (this.i.length) {
      this.i.splice(0, this.i.length).forEach((transaction) => transaction.abort());
    }
    this.h?.close();
    this.pwbRemoveDB();
    this.h = null;
  }
  async runInTransaction(store, transactionMode, dbRequestFn) {
    if (!this.h) {
      throw new $01(this.j);
    }
    const transaction = this.h.transaction(store, transactionMode);
    this.i.push(transaction);
    return new Promise((c, e) => {
      transaction.oncomplete = () => {
        if (Array.isArray(request)) {
          c(request.map((r2) => r2.result));
        } else {
          c(request.result);
        }
      };
      transaction.onerror = () => e(transaction.error ? $ub.fromError(transaction.error) : new $ub("unknown error"));
      transaction.onabort = () => e(transaction.error ? $ub.fromError(transaction.error) : new $ub("unknown error"));
      const request = dbRequestFn(transaction.objectStore(store));
    }).finally(() => this.i.splice(this.i.indexOf(transaction), 1));
  }
  async getKeyValues(store, isValid2) {
    if (!this.h) {
      throw new $01(this.j);
    }
    const transaction = this.h.transaction(store, "readonly");
    this.i.push(transaction);
    return new Promise((resolve) => {
      const items = /* @__PURE__ */ new Map();
      const objectStore = transaction.objectStore(store);
      const cursor = objectStore.openCursor();
      if (!cursor) {
        return resolve(items);
      }
      cursor.onsuccess = () => {
        if (cursor.result) {
          if (isValid2(cursor.result.value)) {
            items.set(cursor.result.key.toString(), cursor.result.value);
          }
          cursor.result.continue();
        } else {
          resolve(items);
        }
      };
      const onError2 = (error) => {
        console.error(`IndexedDB getKeyValues(): ${$1m(error, true)}`);
        resolve(items);
      };
      cursor.onerror = () => onError2(cursor.error);
      transaction.onerror = () => onError2(transaction.error);
    }).finally(() => this.i.splice(this.i.indexOf(transaction), 1));
  }
};

// out-build/vs/platform/files/browser/htmlFileSystemProvider.js
var $t_ = class extends $3c {
  get capabilities() {
    if (!this.b) {
      this.b = 2 | 16;
      if ($n) {
        this.b |= 1024;
      }
    }
    return this.b;
  }
  //#endregion
  constructor(c, f, g) {
    super();
    this.c = c;
    this.f = f;
    this.g = g;
    this.onDidChangeCapabilities = Event2.None;
    this.a = $n ? $lh : $nh;
    this.h = this.B(new $ze());
    this.onDidChangeFile = this.h.event;
    this.m = /* @__PURE__ */ new Map();
    this.n = /* @__PURE__ */ new Map();
  }
  //#region File Metadata Resolving
  async stat(resource) {
    try {
      const handle2 = await this.getHandle(resource);
      if (!handle2) {
        throw this.y(resource, "No such file or directory, stat", FileSystemProviderErrorCode.FileNotFound);
      }
      if (WebFileSystemAccess.isFileSystemFileHandle(handle2)) {
        const file = await handle2.getFile();
        return {
          type: FileType.File,
          mtime: file.lastModified,
          ctime: 0,
          size: file.size
        };
      }
      return {
        type: FileType.Directory,
        mtime: 0,
        ctime: 0,
        size: 0
      };
    } catch (error) {
      throw this.w(error);
    }
  }
  async readdir(resource) {
    try {
      const handle2 = await this.t(resource);
      if (!handle2) {
        throw this.y(resource, "No such file or directory, readdir", FileSystemProviderErrorCode.FileNotFound);
      }
      const result = [];
      for await (const [name, child] of handle2) {
        result.push([name, WebFileSystemAccess.isFileSystemFileHandle(child) ? FileType.File : FileType.Directory]);
      }
      return result;
    } catch (error) {
      throw this.w(error);
    }
  }
  //#endregion
  //#region File Reading/Writing
  readFileStream(resource, opts, token) {
    const stream = $qi((data) => $Ci.concat(data.map((data2) => $Ci.wrap(data2))).buffer, {
      // Set a highWaterMark to prevent the stream
      // for file upload to produce large buffers
      // in-memory
      highWaterMark: 10
    });
    (async () => {
      try {
        const handle2 = await this.s(resource);
        if (!handle2) {
          throw this.y(resource, "No such file or directory, readFile", FileSystemProviderErrorCode.FileNotFound);
        }
        const file = await handle2.getFile();
        if (typeof opts.length === "number" || typeof opts.position === "number") {
          let buffer = new Uint8Array(await file.arrayBuffer());
          if (typeof opts?.position === "number") {
            buffer = buffer.slice(opts.position);
          }
          if (typeof opts?.length === "number") {
            buffer = buffer.slice(0, opts.length);
          }
          stream.end(buffer);
        } else {
          const reader = file.stream().getReader();
          let res = await reader.read();
          while (!res.done) {
            if (token.isCancellationRequested) {
              break;
            }
            await stream.write(res.value);
            if (token.isCancellationRequested) {
              break;
            }
            res = await reader.read();
          }
          stream.end(void 0);
        }
      } catch (error) {
        stream.error(this.w(error));
        stream.end();
      }
    })();
    return stream;
  }
  async readFile(resource) {
    try {
      const handle2 = await this.s(resource);
      if (!handle2) {
        throw this.y(resource, "No such file or directory, readFile", FileSystemProviderErrorCode.FileNotFound);
      }
      const file = await handle2.getFile();
      return new Uint8Array(await file.arrayBuffer());
    } catch (error) {
      throw this.w(error);
    }
  }
  async writeFile(resource, content, opts) {
    try {
      let handle2 = await this.s(resource);
      if (!opts.create || !opts.overwrite) {
        if (handle2) {
          if (!opts.overwrite) {
            throw this.y(resource, "File already exists, writeFile", FileSystemProviderErrorCode.FileExists);
          }
        } else {
          if (!opts.create) {
            throw this.y(resource, "No such file, writeFile", FileSystemProviderErrorCode.FileNotFound);
          }
        }
      }
      if (!handle2) {
        const parent = await this.t(this.a.dirname(resource));
        if (!parent) {
          throw this.y(resource, "No such parent directory, writeFile", FileSystemProviderErrorCode.FileNotFound);
        }
        handle2 = await parent.getFileHandle(this.a.basename(resource), { create: true });
        if (!handle2) {
          throw this.y(resource, "Unable to create file , writeFile", FileSystemProviderErrorCode.Unknown);
        }
      }
      const writable = await handle2.createWritable();
      await writable.write(content);
      await writable.close();
    } catch (error) {
      throw this.w(error);
    }
  }
  //#endregion
  //#region Move/Copy/Delete/Create Folder
  async mkdir(resource) {
    try {
      const parent = await this.t(this.a.dirname(resource));
      if (!parent) {
        throw this.y(resource, "No such parent directory, mkdir", FileSystemProviderErrorCode.FileNotFound);
      }
      await parent.getDirectoryHandle(this.a.basename(resource), { create: true });
    } catch (error) {
      throw this.w(error);
    }
  }
  async delete(resource, opts) {
    try {
      const parent = await this.t(this.a.dirname(resource));
      if (!parent) {
        throw this.y(resource, "No such parent directory, delete", FileSystemProviderErrorCode.FileNotFound);
      }
      return parent.removeEntry(this.a.basename(resource), { recursive: opts.recursive });
    } catch (error) {
      throw this.w(error);
    }
  }
  async rename(from, to, opts) {
    try {
      if (this.a.isEqual(from, to)) {
        return;
      }
      const fileHandle = await this.s(from);
      if (fileHandle) {
        const file = await fileHandle.getFile();
        const contents = new Uint8Array(await file.arrayBuffer());
        await this.writeFile(to, contents, { create: true, overwrite: opts.overwrite, unlock: false, atomic: false });
        await this.delete(from, { recursive: false, useTrash: false, atomic: false });
      } else {
        throw this.y(from, localize(1902, null), FileSystemProviderErrorCode.Unavailable);
      }
    } catch (error) {
      throw this.w(error);
    }
  }
  watch(resource, opts) {
    const disposables = new $2c();
    this.j(resource, opts, disposables).catch((error) => this.g.error(`[File Watcher ('FileSystemObserver')] Error: ${error} (${resource})`));
    return disposables;
  }
  async j(resource, opts, disposables) {
    if (!WebFileSystemObserver.supported(globalThis)) {
      return;
    }
    const handle2 = await this.getHandle(resource);
    if (!handle2 || disposables.isDisposed) {
      return;
    }
    const observer = new globalThis.FileSystemObserver((records) => {
      if (disposables.isDisposed) {
        return;
      }
      const events = [];
      for (const record of records) {
        if (this.g.getLevel() === LogLevel.Trace) {
          this.g.trace(`[File Watcher ('FileSystemObserver')] [${record.type}] ${$vh(resource, ...record.relativePathComponents)}`);
        }
        switch (record.type) {
          case "appeared":
            events.push({
              resource: $vh(resource, ...record.relativePathComponents),
              type: 1
              /* FileChangeType.ADDED */
            });
            break;
          case "disappeared":
            events.push({
              resource: $vh(resource, ...record.relativePathComponents),
              type: 2
              /* FileChangeType.DELETED */
            });
            break;
          case "modified":
            events.push({
              resource: $vh(resource, ...record.relativePathComponents),
              type: 0
              /* FileChangeType.UPDATED */
            });
            break;
          case "errored":
            this.g.trace(`[File Watcher ('FileSystemObserver')] errored, disposing observer (${resource})`);
            disposables.dispose();
        }
      }
      if (events.length) {
        this.h.fire(events);
      }
    });
    try {
      await observer.observe(handle2, opts.recursive ? { recursive: true } : void 0);
    } finally {
      if (disposables.isDisposed) {
        observer.disconnect();
      } else {
        disposables.add($1c(() => observer.disconnect()));
      }
    }
  }
  registerFileHandle(handle2) {
    return this.r(handle2, this.m);
  }
  registerDirectoryHandle(handle2) {
    return this.r(handle2, this.n);
  }
  get directories() {
    return this.n.values();
  }
  async r(handle2, map) {
    let handleId = `/${handle2.name}`;
    if (map.has(handleId) && !await map.get(handleId)?.isSameEntry(handle2)) {
      const fileExt = $sc(handle2.name);
      const fileName = $rc(handle2.name, fileExt);
      let handleIdCounter = 1;
      do {
        handleId = `/${fileName}-${handleIdCounter++}${fileExt}`;
      } while (map.has(handleId) && !await map.get(handleId)?.isSameEntry(handle2));
    }
    map.set(handleId, handle2);
    try {
      await this.c?.runInTransaction(this.f, "readwrite", (objectStore) => objectStore.put(handle2, handleId));
      this.c?.pwbAddToSessionSet($$1.PWB_CHANGED_CONNECTION_KEY);
    } catch (error) {
      this.g.error(error);
    }
    return URI.from({ scheme: Schemas.file, path: handleId });
  }
  async getHandle(resource) {
    let handle2 = await this.u(resource);
    if (!handle2) {
      const parent = await this.t(this.a.dirname(resource));
      if (parent) {
        const name = $lh.basename(resource);
        try {
          handle2 = await parent.getFileHandle(name);
        } catch (error) {
          try {
            handle2 = await parent.getDirectoryHandle(name);
          } catch (error2) {
          }
        }
      }
    }
    return handle2;
  }
  async s(resource) {
    const handle2 = await this.u(resource);
    if (handle2 instanceof FileSystemFileHandle) {
      return handle2;
    }
    const parent = await this.t(this.a.dirname(resource));
    try {
      return await parent?.getFileHandle($lh.basename(resource));
    } catch (error) {
      return void 0;
    }
  }
  async t(resource) {
    const handle2 = await this.u(resource);
    if (handle2 instanceof FileSystemDirectoryHandle) {
      return handle2;
    }
    const parentUri = this.a.dirname(resource);
    if (this.a.isEqual(parentUri, resource)) {
      return void 0;
    }
    const parent = await this.t(parentUri);
    try {
      return await parent?.getDirectoryHandle($lh.basename(resource));
    } catch (error) {
      return void 0;
    }
  }
  async u(resource) {
    if (this.a.dirname(resource).path !== "/") {
      return void 0;
    }
    const handleId = resource.path.replace(/\/$/, "");
    const inMemoryHandle = this.m.get(handleId) ?? this.n.get(handleId);
    if (inMemoryHandle) {
      return inMemoryHandle;
    }
    const persistedHandle = await this.c?.runInTransaction(this.f, "readonly", (store) => store.get(handleId));
    if (WebFileSystemAccess.isFileSystemHandle(persistedHandle)) {
      let hasPermissions = await persistedHandle.queryPermission() === "granted";
      try {
        if (!hasPermissions) {
          hasPermissions = await persistedHandle.requestPermission() === "granted";
        }
      } catch (error) {
        this.g.error(error);
      }
      if (hasPermissions) {
        if (WebFileSystemAccess.isFileSystemFileHandle(persistedHandle)) {
          this.m.set(handleId, persistedHandle);
        } else if (WebFileSystemAccess.isFileSystemDirectoryHandle(persistedHandle)) {
          this.n.set(handleId, persistedHandle);
        }
        return persistedHandle;
      }
    }
    throw this.y(resource, "No file system handle registered", FileSystemProviderErrorCode.Unavailable);
  }
  //#endregion
  w(error) {
    if (error instanceof $wm) {
      return error;
    }
    let code = FileSystemProviderErrorCode.Unknown;
    if (error.name === "NotAllowedError") {
      error = new Error(localize(1903, null));
      code = FileSystemProviderErrorCode.Unavailable;
    }
    return $xm(error, code);
  }
  y(resource, msg, code) {
    return $xm(new Error(`${msg} (${$lc(resource.path)})`), code);
  }
};

// out-build/vs/platform/opener/common/opener.js
var $O4 = $Qk("openerService");
function $P4(uri, selection) {
  return uri.with({ fragment: `${selection.startLineNumber},${selection.startColumn}${selection.endLineNumber ? `-${selection.endLineNumber}${selection.endColumn ? `,${selection.endColumn}` : ""}` : ""}` });
}
function $Q4(uri) {
  let selection = void 0;
  const match = /^L?(\d+)(?:,(\d+))?(-L?(\d+)(?:,(\d+))?)?/.exec(uri.fragment);
  if (match) {
    selection = {
      startLineNumber: parseInt(match[1]),
      startColumn: match[2] ? parseInt(match[2]) : 1,
      endLineNumber: match[4] ? parseInt(match[4]) : void 0,
      endColumn: match[4] ? match[5] ? parseInt(match[5]) : 1 : void 0
    };
    uri = uri.with({ fragment: "" });
  }
  return { selection, uri };
}

// out-build/vs/platform/dnd/browser/dnd.js
var $u_ = {
  EDITORS: "CodeEditors",
  FILES: "CodeFiles",
  SYMBOLS: "application/vnd.code.symbols"
};
function $v_(e) {
  const editors = [];
  if (e.dataTransfer && e.dataTransfer.types.length > 0) {
    const rawEditorsData = e.dataTransfer.getData($u_.EDITORS);
    if (rawEditorsData) {
      try {
        editors.push(...$bu(rawEditorsData));
      } catch (error) {
      }
    } else {
      try {
        const rawResourcesData = e.dataTransfer.getData($kZ.RESOURCES);
        editors.push(...$x_(rawResourcesData));
      } catch (error) {
      }
    }
    if (e.dataTransfer?.files) {
      for (let i2 = 0; i2 < e.dataTransfer.files.length; i2++) {
        const file = e.dataTransfer.files[i2];
        if (file && $E_(file)) {
          try {
            editors.push({ resource: URI.file($E_(file)), isExternal: true, allowWorkspaceOpen: true });
          } catch (error) {
          }
        }
      }
    }
    const rawCodeFiles = e.dataTransfer.getData($u_.FILES);
    if (rawCodeFiles) {
      try {
        const codeFiles = JSON.parse(rawCodeFiles);
        for (const codeFile of codeFiles) {
          editors.push({ resource: URI.file(codeFile), isExternal: true, allowWorkspaceOpen: true });
        }
      } catch (error) {
      }
    }
    const contributions = $Wn.as($A_.DragAndDropContribution).getAll();
    for (const contribution of contributions) {
      const data = e.dataTransfer.getData(contribution.dataFormatKey);
      if (data) {
        try {
          editors.push(...contribution.getEditorInputs(data));
        } catch (error) {
        }
      }
    }
  }
  const coalescedEditors = [];
  const seen = new $Ec();
  for (const editor of editors) {
    if (!editor.resource) {
      coalescedEditors.push(editor);
    } else if (!seen.has(editor.resource)) {
      coalescedEditors.push(editor);
      seen.set(editor.resource, true);
    }
  }
  return coalescedEditors;
}
async function $w_(accessor, e) {
  const editors = $v_(e);
  if (e.dataTransfer && $r && $z_(e, $kZ.FILES)) {
    const files = e.dataTransfer.items;
    if (files) {
      const instantiationService = accessor.get($Pk);
      const filesData = await instantiationService.invokeFunction((accessor2) => extractFilesDropData(accessor2, e));
      for (const fileData of filesData) {
        editors.push({ resource: fileData.resource, contents: fileData.contents?.toString(), isExternal: true, allowWorkspaceOpen: fileData.isDirectory });
      }
    }
  }
  return editors;
}
function $x_(rawResourcesData) {
  const editors = [];
  if (rawResourcesData) {
    const resourcesRaw = JSON.parse(rawResourcesData);
    for (const resourceRaw of resourcesRaw) {
      if (resourceRaw.indexOf(":") > 0) {
        const { selection, uri } = $Q4(URI.parse(resourceRaw));
        editors.push({ resource: uri, options: { selection } });
      }
    }
  }
  return editors;
}
async function extractFilesDropData(accessor, event) {
  if (WebFileSystemAccess.supported($Y)) {
    const items = event.dataTransfer?.items;
    if (items) {
      return extractFileTransferData(accessor, items);
    }
  }
  const files = event.dataTransfer?.files;
  if (!files) {
    return [];
  }
  return $y_(accessor, files);
}
async function extractFileTransferData(accessor, items) {
  const fileSystemProvider = accessor.get($km).getProvider(Schemas.file);
  if (!(fileSystemProvider instanceof $t_)) {
    return [];
  }
  const results = [];
  for (let i2 = 0; i2 < items.length; i2++) {
    const file = items[i2];
    if (file) {
      const result = new $gi();
      results.push(result);
      (async () => {
        try {
          const handle2 = await file.getAsFileSystemHandle();
          if (!handle2) {
            result.complete(void 0);
            return;
          }
          if (WebFileSystemAccess.isFileSystemFileHandle(handle2)) {
            result.complete({
              resource: await fileSystemProvider.registerFileHandle(handle2),
              isDirectory: false
            });
          } else if (WebFileSystemAccess.isFileSystemDirectoryHandle(handle2)) {
            result.complete({
              resource: await fileSystemProvider.registerDirectoryHandle(handle2),
              isDirectory: true
            });
          } else {
            result.complete(void 0);
          }
        } catch (error) {
          result.complete(void 0);
        }
      })();
    }
  }
  return $Mb(await Promise.all(results.map((result) => result.p)));
}
async function $y_(accessor, files) {
  const dialogService = accessor.get($Yv);
  const results = [];
  for (let i2 = 0; i2 < files.length; i2++) {
    const file = files.item(i2);
    if (file) {
      if (file.size > 100 * $Sm.MB) {
        dialogService.warn(localize(1743, null));
        continue;
      }
      const result = new $gi();
      results.push(result);
      const reader = new FileReader();
      reader.onerror = () => result.complete(void 0);
      reader.onabort = () => result.complete(void 0);
      reader.onload = async (event) => {
        const name = file.name;
        const loadResult = event.target?.result ?? void 0;
        if (typeof name !== "string" || typeof loadResult === "undefined") {
          result.complete(void 0);
          return;
        }
        result.complete({
          resource: URI.from({ scheme: Schemas.untitled, path: name }),
          contents: typeof loadResult === "string" ? $Ci.fromString(loadResult) : $Ci.wrap(new Uint8Array(loadResult))
        });
      };
      reader.readAsArrayBuffer(file);
    }
  }
  return $Mb(await Promise.all(results.map((result) => result.p)));
}
function $z_(event, ...dragTypesToFind) {
  if (!event.dataTransfer) {
    return false;
  }
  const dragTypes = event.dataTransfer.types;
  const lowercaseDragTypes = [];
  for (let i2 = 0; i2 < dragTypes.length; i2++) {
    lowercaseDragTypes.push(dragTypes[i2].toLowerCase());
  }
  for (const dragType of dragTypesToFind) {
    if (lowercaseDragTypes.indexOf(dragType.toLowerCase()) >= 0) {
      return true;
    }
  }
  return false;
}
var DragAndDropContributionRegistry = class {
  constructor() {
    this.a = /* @__PURE__ */ new Map();
  }
  register(contribution) {
    if (this.a.has(contribution.dataFormatKey)) {
      throw new Error(`A drag and drop contributiont with key '${contribution.dataFormatKey}' was already registered.`);
    }
    this.a.set(contribution.dataFormatKey, contribution);
  }
  getAll() {
    return this.a.values();
  }
};
var $A_ = {
  DragAndDropContribution: "workbench.contributions.dragAndDrop"
};
$Wn.add($A_.DragAndDropContribution, new DragAndDropContributionRegistry());
var $B_ = class _$B_ {
  static {
    this.a = new _$B_();
  }
  constructor() {
  }
  static getInstance() {
    return _$B_.a;
  }
  hasData(proto) {
    return proto && proto === this.c;
  }
  clearData(proto) {
    if (this.hasData(proto)) {
      this.c = void 0;
      this.b = void 0;
    }
  }
  getData(proto) {
    if (this.hasData(proto)) {
      return this.b;
    }
    return void 0;
  }
  setData(data, proto) {
    if (proto) {
      this.b = data;
      this.c = proto;
    }
  }
};
function $C_(e) {
  const rawSymbolsData = e.dataTransfer?.getData($u_.SYMBOLS);
  if (rawSymbolsData) {
    try {
      return JSON.parse(rawSymbolsData);
    } catch (error) {
    }
  }
  return [];
}
function $D_(symbolsData, e) {
  e.dataTransfer?.setData($u_.SYMBOLS, JSON.stringify(symbolsData));
}
function $E_(file) {
  if ($p && typeof globalThis.vscode?.webUtils?.getPathForFile === "function") {
    return globalThis.vscode.webUtils.getPathForFile(file);
  }
  return void 0;
}

// out-build/vs/editor/browser/dnd.js
function $F_(dataTransfer) {
  const vsDataTransfer = new $lE();
  for (const item of dataTransfer.items) {
    const type = item.type;
    if (item.kind === "string") {
      const asStringValue = new Promise((resolve) => item.getAsString(resolve));
      vsDataTransfer.append(type, $jE(asStringValue));
    } else if (item.kind === "file") {
      const file = item.getAsFile();
      if (file) {
        vsDataTransfer.append(type, createFileDataTransferItemFromFile(file));
      }
    }
  }
  return vsDataTransfer;
}
function createFileDataTransferItemFromFile(file) {
  const path = $E_(file);
  const uri = path ? URI.parse(path) : void 0;
  return $kE(file.name, uri, async () => {
    return new Uint8Array(await file.arrayBuffer());
  });
}
var INTERNAL_DND_MIME_TYPES = Object.freeze([
  $u_.EDITORS,
  $u_.FILES,
  $kZ.RESOURCES,
  $kZ.INTERNAL_URI_LIST
]);
function $G_(sourceDataTransfer, overwriteUriList = false) {
  const vsDataTransfer = $F_(sourceDataTransfer);
  const uriList = vsDataTransfer.get($kZ.INTERNAL_URI_LIST);
  if (uriList) {
    vsDataTransfer.replace($YC.uriList, uriList);
  } else {
    if (overwriteUriList || !vsDataTransfer.has($YC.uriList)) {
      const editorData = [];
      for (const item of sourceDataTransfer.items) {
        const file = item.getAsFile();
        if (file) {
          const path = $E_(file);
          try {
            if (path) {
              editorData.push(URI.file(path).toString());
            } else {
              editorData.push(URI.parse(file.name, true).toString());
            }
          } catch {
          }
        }
      }
      if (editorData.length) {
        vsDataTransfer.replace($YC.uriList, $jE($nE.create(editorData)));
      }
    }
  }
  for (const internal of INTERNAL_DND_MIME_TYPES) {
    vsDataTransfer.delete(internal);
  }
  return vsDataTransfer;
}

// out-build/vs/editor/browser/services/bulkEditService.js
var $H_ = $Qk("IWorkspaceEditService");
var $I_ = class {
  constructor(metadata) {
    this.metadata = metadata;
  }
  static convert(edit3) {
    return edit3.edits.map((edit4) => {
      if ($J_.is(edit4)) {
        return $J_.lift(edit4);
      }
      if ($K_.is(edit4)) {
        return $K_.lift(edit4);
      }
      throw new Error("Unsupported edit");
    });
  }
};
var $J_ = class _$J_ extends $I_ {
  static is(candidate) {
    if (candidate instanceof _$J_) {
      return true;
    }
    return $Bg(candidate) && URI.isUri(candidate.resource) && $Bg(candidate.textEdit);
  }
  static lift(edit3) {
    if (edit3 instanceof _$J_) {
      return edit3;
    } else {
      return new _$J_(edit3.resource, edit3.textEdit, edit3.versionId, edit3.metadata);
    }
  }
  constructor(resource, textEdit, versionId = void 0, metadata) {
    super(metadata);
    this.resource = resource;
    this.textEdit = textEdit;
    this.versionId = versionId;
  }
};
var $K_ = class _$K_ extends $I_ {
  static is(candidate) {
    if (candidate instanceof _$K_) {
      return true;
    } else {
      return $Bg(candidate) && (Boolean(candidate.newResource) || Boolean(candidate.oldResource));
    }
  }
  static lift(edit3) {
    if (edit3 instanceof _$K_) {
      return edit3;
    } else {
      return new _$K_(edit3.oldResource, edit3.newResource, edit3.options, edit3.metadata);
    }
  }
  constructor(oldResource, newResource, options3 = {}, metadata) {
    super(metadata);
    this.oldResource = oldResource;
    this.newResource = newResource;
    this.options = options3;
  }
};

// out-build/vs/editor/contrib/editorState/browser/keybindingCancellation.js
var IEditorCancellationTokens = $Qk("IEditorCancelService");
var ctxCancellableOperation = new $nn("cancellableOperation", false, localize(1014, null));
$SC(
  IEditorCancellationTokens,
  class {
    constructor() {
      this.a = /* @__PURE__ */ new WeakMap();
    }
    add(editor, cts) {
      let data = this.a.get(editor);
      if (!data) {
        data = editor.invokeWithinContext((accessor) => {
          const key2 = ctxCancellableOperation.bindTo(accessor.get($on));
          const tokens = new $cd();
          return { key: key2, tokens };
        });
        this.a.set(editor, data);
      }
      let removeFn;
      data.key.set(true);
      removeFn = data.tokens.push(cts);
      return () => {
        if (removeFn) {
          removeFn();
          data.key.set(!data.tokens.isEmpty());
          removeFn = void 0;
        }
      };
    }
    cancel(editor) {
      const data = this.a.get(editor);
      if (!data) {
        return;
      }
      const cts = data.tokens.pop();
      if (cts) {
        cts.cancel();
        data.key.set(!data.tokens.isEmpty());
      }
    }
  },
  1
  /* InstantiationType.Delayed */
);
var $L_ = class extends $ad {
  constructor(editor, parent) {
    super(parent);
    this.editor = editor;
    this.a = editor.invokeWithinContext((accessor) => accessor.get(IEditorCancellationTokens).add(editor, this));
  }
  dispose() {
    this.a();
    super.dispose();
  }
};
$45(new class extends $Y5 {
  constructor() {
    super({
      id: "editor.cancelOperation",
      kbOpts: {
        weight: 100,
        primary: 9
        /* KeyCode.Escape */
      },
      precondition: ctxCancellableOperation
    });
  }
  runEditorCommand(accessor, editor) {
    accessor.get(IEditorCancellationTokens).cancel(editor);
  }
}());

// out-build/vs/editor/contrib/editorState/browser/editorState.js
var CodeEditorStateFlag;
(function(CodeEditorStateFlag2) {
  CodeEditorStateFlag2[CodeEditorStateFlag2["Value"] = 1] = "Value";
  CodeEditorStateFlag2[CodeEditorStateFlag2["Selection"] = 2] = "Selection";
  CodeEditorStateFlag2[CodeEditorStateFlag2["Position"] = 4] = "Position";
  CodeEditorStateFlag2[CodeEditorStateFlag2["Scroll"] = 8] = "Scroll";
})(CodeEditorStateFlag || (CodeEditorStateFlag = {}));
var $M_ = class _$M_ {
  constructor(editor, flags) {
    this.a = flags;
    if ((this.a & 1) !== 0) {
      const model = editor.getModel();
      this.d = model ? $wf("{0}#{1}", model.uri.toString(), model.getVersionId()) : null;
    } else {
      this.d = null;
    }
    if ((this.a & 4) !== 0) {
      this.b = editor.getPosition();
    } else {
      this.b = null;
    }
    if ((this.a & 2) !== 0) {
      this.c = editor.getSelection();
    } else {
      this.c = null;
    }
    if ((this.a & 8) !== 0) {
      this.f = editor.getScrollLeft();
      this.g = editor.getScrollTop();
    } else {
      this.f = -1;
      this.g = -1;
    }
  }
  h(other) {
    if (!(other instanceof _$M_)) {
      return false;
    }
    const state = other;
    if (this.d !== state.d) {
      return false;
    }
    if (this.f !== state.f || this.g !== state.g) {
      return false;
    }
    if (!this.b && state.b || this.b && !state.b || this.b && state.b && !this.b.equals(state.b)) {
      return false;
    }
    if (!this.c && state.c || this.c && !state.c || this.c && state.c && !this.c.equalsRange(state.c)) {
      return false;
    }
    return true;
  }
  validate(editor) {
    return this.h(new _$M_(editor, this.a));
  }
};
var $N_ = class extends $L_ {
  constructor(editor, flags, range, parent) {
    super(editor, parent);
    this.b = new $2c();
    if (flags & 4) {
      this.b.add(editor.onDidChangeCursorPosition((e) => {
        if (!range || !$9C.containsPosition(range, e.position)) {
          this.cancel();
        }
      }));
    }
    if (flags & 2) {
      this.b.add(editor.onDidChangeCursorSelection((e) => {
        if (!range || !$9C.containsRange(range, e.selection)) {
          this.cancel();
        }
      }));
    }
    if (flags & 8) {
      this.b.add(editor.onDidScrollChange((_) => this.cancel()));
    }
    if (flags & 1) {
      this.b.add(editor.onDidChangeModel((_) => this.cancel()));
      this.b.add(editor.onDidChangeModelContent((_) => this.cancel()));
    }
  }
  dispose() {
    this.b.dispose();
    super.dispose();
  }
};
var $O_ = class extends $ad {
  constructor(model, parent) {
    super(parent);
    this.a = model.onDidChangeContent(() => this.cancel());
  }
  dispose() {
    this.a.dispose();
    super.dispose();
  }
};

// out-build/vs/editor/contrib/inlineProgress/browser/inlineProgress.js
var inlineProgressDecoration = $WI.register({
  description: "inline-progress-widget",
  stickiness: 1,
  showIfCollapsed: true,
  after: {
    content: $wg,
    inlineClassName: "inline-editor-progress-decoration",
    inlineClassNameAffectsLetterSpacing: true
  }
});
var InlineProgressWidget = class _InlineProgressWidget extends $3c {
  static {
    this.a = "editor.widget.inlineProgressWidget";
  }
  constructor(f, g, h3, title, j) {
    super();
    this.f = f;
    this.g = g;
    this.h = h3;
    this.j = j;
    this.allowEditorOverflow = false;
    this.suppressMouseDown = true;
    this.m(title);
    this.g.addContentWidget(this);
    this.g.layoutContentWidget(this);
  }
  m(title) {
    this.b = $(".inline-progress-widget");
    this.b.role = "button";
    this.b.title = title;
    const iconElement = $("span.icon");
    this.b.append(iconElement);
    iconElement.classList.add(...ThemeIcon.asClassNameArray($6l.loading), "codicon-modifier-spin");
    const updateSize = () => {
      const lineHeight = this.g.getOption(
        68
        /* EditorOption.lineHeight */
      );
      this.b.style.height = `${lineHeight}px`;
      this.b.style.width = `${Math.ceil(0.8 * lineHeight)}px`;
    };
    updateSize();
    this.B(this.g.onDidChangeConfiguration((c) => {
      if (c.hasChanged(
        54
        /* EditorOption.fontSize */
      ) || c.hasChanged(
        68
        /* EditorOption.lineHeight */
      )) {
        updateSize();
      }
    }));
    this.B($_i(this.b, $7j.CLICK, (e) => {
      this.j.cancel();
    }));
  }
  getId() {
    return _InlineProgressWidget.a + "." + this.f;
  }
  getDomNode() {
    return this.b;
  }
  getPosition() {
    return {
      position: { lineNumber: this.h.startLineNumber, column: this.h.startColumn },
      preference: [
        0
        /* ContentWidgetPositionPreference.EXACT */
      ]
    };
  }
  dispose() {
    super.dispose();
    this.g.removeContentWidget(this);
  }
};
var $P_ = class $P_2 extends $3c {
  constructor(m, n, r2) {
    super();
    this.m = m;
    this.n = n;
    this.r = r2;
    this.a = 500;
    this.b = this.B(new $4c());
    this.g = this.B(new $4c());
    this.h = 0;
    this.f = n.createDecorationsCollection();
  }
  dispose() {
    super.dispose();
    this.f.clear();
  }
  async showWhile(position, title, promise, delegate, delayOverride) {
    const operationId = this.h++;
    this.j = operationId;
    this.s();
    this.b.value = $Xh(() => {
      const range = $9C.fromPositions(position);
      const decorationIds = this.f.set([{
        range,
        options: inlineProgressDecoration
      }]);
      if (decorationIds.length > 0) {
        this.g.value = this.r.createInstance(InlineProgressWidget, this.m, this.n, range, title, delegate);
      }
    }, delayOverride ?? this.a);
    try {
      return await promise;
    } finally {
      if (this.j === operationId) {
        this.s();
        this.j = void 0;
      }
    }
  }
  s() {
    this.b.clear();
    this.f.clear();
    this.g.clear();
  }
};
$P_ = __decorate([
  __param(2, $Pk)
], $P_);

// out-build/vs/editor/browser/widget/markdownRenderer/browser/markdownRenderer.js
var $Q_1;
var $Q_ = class $Q_2 {
  static {
    $Q_1 = this;
  }
  static {
    this.a = $W1("tokenizeToString", {
      createHTML(html3) {
        return html3;
      }
    });
  }
  constructor(c, d, f) {
    this.c = c;
    this.d = d;
    this.f = f;
    this.b = new $ze();
    this.onDidRenderAsync = this.b.event;
  }
  dispose() {
    this.b.dispose();
  }
  render(markdown, options3, markedOptions) {
    if (!markdown) {
      const element = document.createElement("span");
      return { element, dispose: () => {
      } };
    }
    const disposables = new $2c();
    const rendered = disposables.add($D1(markdown, { ...this.g(markdown, disposables), ...options3 }, markedOptions));
    rendered.element.classList.add("rendered-markdown");
    return {
      element: rendered.element,
      dispose: () => disposables.dispose()
    };
  }
  g(markdown, disposables) {
    return {
      codeBlockRenderer: async (languageAlias, value) => {
        let languageId;
        if (languageAlias) {
          languageId = this.d.getLanguageIdByLanguageName(languageAlias);
        } else if (this.c.editor) {
          languageId = this.c.editor.getModel()?.getLanguageId();
        }
        if (!languageId) {
          languageId = $KF;
        }
        const html3 = await $o9(this.d, value, languageId);
        const element = document.createElement("span");
        element.innerHTML = $Q_1.a?.createHTML(html3) ?? html3;
        if (this.c.editor) {
          const fontInfo = this.c.editor.getOption(
            52
            /* EditorOption.fontInfo */
          );
          $24(element, fontInfo);
        } else if (this.c.codeBlockFontFamily) {
          element.style.fontFamily = this.c.codeBlockFontFamily;
        }
        if (this.c.codeBlockFontSize !== void 0) {
          element.style.fontSize = this.c.codeBlockFontSize;
        }
        return element;
      },
      asyncRenderCallback: () => this.b.fire(),
      actionHandler: {
        callback: (link2) => this.h(link2, markdown),
        disposables
      }
    };
  }
  async h(link2, markdown) {
    await $R_(this.f, link2, markdown.isTrusted);
  }
};
$Q_ = $Q_1 = __decorate([
  __param(1, $1E),
  __param(2, $O4)
], $Q_);
async function $R_(openerService, link2, isTrusted) {
  try {
    return await openerService.open(link2, {
      fromUserGesture: true,
      allowContributedOpeners: true,
      allowCommands: toAllowCommandsOption(isTrusted)
    });
  } catch (e) {
    $gb(e);
    return false;
  }
}
function toAllowCommandsOption(isTrusted) {
  if (isTrusted === true) {
    return true;
  }
  if (isTrusted && Array.isArray(isTrusted.enabledCommands)) {
    return isTrusted.enabledCommands;
  }
  return false;
}

// out-build/vs/editor/contrib/message/browser/messageController.js
var $S_1;
var $S_ = class $S_2 {
  static {
    $S_1 = this;
  }
  static {
    this.ID = "editor.contrib.messageController";
  }
  static {
    this.MESSAGE_VISIBLE = new $nn("messageVisible", false, localize(1331, null));
  }
  static get(editor) {
    return editor.getContribution($S_1.ID);
  }
  constructor(editor, contextKeyService, i2) {
    this.i = i2;
    this.d = new $4c();
    this.f = new $2c();
    this.h = false;
    this.a = editor;
    this.b = $S_1.MESSAGE_VISIBLE.bindTo(contextKeyService);
  }
  dispose() {
    this.g?.dispose();
    this.f.dispose();
    this.d.dispose();
    this.b.reset();
  }
  isVisible() {
    return this.b.get();
  }
  showMessage(message, position) {
    $$Z($dm(message) ? message.value : message);
    this.b.set(true);
    this.d.clear();
    this.f.clear();
    this.g = $dm(message) ? $D1(message, {
      actionHandler: {
        callback: (url) => {
          this.closeMessage();
          $R_(this.i, url, $dm(message) ? message.isTrusted : void 0);
        },
        disposables: this.f
      }
    }) : void 0;
    this.d.value = new MessageWidget(this.a, position, typeof message === "string" ? message : this.g.element);
    this.f.add(Event2.debounce(this.a.onDidBlurEditorText, (last, event) => event, 0)(() => {
      if (this.h) {
        return;
      }
      if (this.d.value && $Dj($Lj(), this.d.value.getDomNode())) {
        return;
      }
      this.closeMessage();
    }));
    this.f.add(this.a.onDidChangeCursorPosition(() => this.closeMessage()));
    this.f.add(this.a.onDidDispose(() => this.closeMessage()));
    this.f.add(this.a.onDidChangeModel(() => this.closeMessage()));
    this.f.add($_i(this.d.value.getDomNode(), $7j.MOUSE_ENTER, () => this.h = true, true));
    this.f.add($_i(this.d.value.getDomNode(), $7j.MOUSE_LEAVE, () => this.h = false, true));
    let bounds;
    this.f.add(this.a.onMouseMove((e) => {
      if (!e.target.position) {
        return;
      }
      if (!bounds) {
        bounds = new $9C(position.lineNumber - 3, 1, e.target.position.lineNumber + 3, 1);
      } else if (!bounds.containsPosition(e.target.position)) {
        this.closeMessage();
      }
    }));
  }
  closeMessage() {
    this.b.reset();
    this.f.clear();
    if (this.d.value) {
      this.f.add(MessageWidget.fadeOut(this.d.value));
    }
  }
};
$S_ = $S_1 = __decorate([
  __param(1, $on),
  __param(2, $O4)
], $S_);
var MessageCommand = $Y5.bindToContribution($S_.get);
$45(new MessageCommand({
  id: "leaveEditorMessage",
  precondition: $S_.MESSAGE_VISIBLE,
  handler: (c) => c.closeMessage(),
  kbOpts: {
    weight: 100 + 30,
    primary: 9
    /* KeyCode.Escape */
  }
}));
var MessageWidget = class {
  static fadeOut(messageWidget) {
    const dispose = () => {
      messageWidget.dispose();
      clearTimeout(handle2);
      messageWidget.getDomNode().removeEventListener("animationend", dispose);
    };
    const handle2 = setTimeout(dispose, 110);
    messageWidget.getDomNode().addEventListener("animationend", dispose);
    messageWidget.getDomNode().classList.add("fadeOut");
    return { dispose };
  }
  constructor(editor, { lineNumber, column }, text2) {
    this.allowEditorOverflow = true;
    this.suppressMouseDown = false;
    this.a = editor;
    this.a.revealLinesInCenterIfOutsideViewport(
      lineNumber,
      lineNumber,
      0
      /* ScrollType.Smooth */
    );
    this.b = { lineNumber, column };
    this.d = document.createElement("div");
    this.d.classList.add("monaco-editor-overlaymessage");
    this.d.style.marginLeft = "-6px";
    const anchorTop = document.createElement("div");
    anchorTop.classList.add("anchor", "top");
    this.d.appendChild(anchorTop);
    const message = document.createElement("div");
    if (typeof text2 === "string") {
      message.classList.add("message");
      message.textContent = text2;
    } else {
      text2.classList.add("message");
      message.appendChild(text2);
    }
    this.d.appendChild(message);
    const anchorBottom = document.createElement("div");
    anchorBottom.classList.add("anchor", "below");
    this.d.appendChild(anchorBottom);
    this.a.addContentWidget(this);
    this.d.classList.add("fadeIn");
  }
  dispose() {
    this.a.removeContentWidget(this);
  }
  getId() {
    return "messageoverlay";
  }
  getDomNode() {
    return this.d;
  }
  getPosition() {
    return {
      position: this.b,
      preference: [
        1,
        2
      ],
      positionAffinity: 1
    };
  }
  afterRender(position) {
    this.d.classList.toggle(
      "below",
      position === 2
      /* ContentWidgetPositionPreference.BELOW */
    );
  }
};
$85(
  $S_.ID,
  $S_,
  4
  /* EditorContributionInstantiation.Lazy */
);

// out-build/vs/editor/contrib/dropOrPasteInto/browser/defaultProviders.js
var SimplePasteAndDropProvider = class {
  constructor(kind) {
    this.copyMimeTypes = [];
    this.kind = kind;
    this.providedDropEditKinds = [this.kind];
    this.providedPasteEditKinds = [this.kind];
  }
  async provideDocumentPasteEdits(_model, _ranges, dataTransfer, context, token) {
    const edit3 = await this.a(dataTransfer, token);
    if (!edit3) {
      return void 0;
    }
    return {
      edits: [{ insertText: edit3.insertText, title: edit3.title, kind: edit3.kind, handledMimeType: edit3.handledMimeType, yieldTo: edit3.yieldTo }],
      dispose() {
      }
    };
  }
  async provideDocumentDropEdits(_model, _position, dataTransfer, token) {
    const edit3 = await this.a(dataTransfer, token);
    if (!edit3) {
      return;
    }
    return {
      edits: [{ insertText: edit3.insertText, title: edit3.title, kind: edit3.kind, handledMimeType: edit3.handledMimeType, yieldTo: edit3.yieldTo }],
      dispose() {
      }
    };
  }
};
var $V_ = class _$V_ extends SimplePasteAndDropProvider {
  static {
    this.id = "text";
  }
  constructor() {
    super($oE.Empty.append("text", "plain"));
    this.id = _$V_.id;
    this.dropMimeTypes = [$YC.text];
    this.pasteMimeTypes = [$YC.text];
  }
  async a(dataTransfer, _token) {
    const textEntry = dataTransfer.get($YC.text);
    if (!textEntry) {
      return;
    }
    if (dataTransfer.has($YC.uriList)) {
      return;
    }
    const insertText = await textEntry.asString();
    return {
      handledMimeType: $YC.text,
      title: localize(1001, null),
      insertText,
      kind: this.kind
    };
  }
};
var PathProvider = class extends SimplePasteAndDropProvider {
  constructor() {
    super($oE.Empty.append("uri", "path", "absolute"));
    this.dropMimeTypes = [$YC.uriList];
    this.pasteMimeTypes = [$YC.uriList];
  }
  async a(dataTransfer, token) {
    const entries2 = await extractUriList(dataTransfer);
    if (!entries2.length || token.isCancellationRequested) {
      return;
    }
    let uriCount = 0;
    const insertText = entries2.map(({ uri, originalText }) => {
      if (uri.scheme === Schemas.file) {
        return uri.fsPath;
      } else {
        uriCount++;
        return originalText;
      }
    }).join(" ");
    let label3;
    if (uriCount > 0) {
      label3 = entries2.length > 1 ? localize(1002, null) : localize(1003, null);
    } else {
      label3 = entries2.length > 1 ? localize(1004, null) : localize(1005, null);
    }
    return {
      handledMimeType: $YC.uriList,
      insertText,
      title: label3,
      kind: this.kind
    };
  }
};
var RelativePathProvider = class RelativePathProvider2 extends SimplePasteAndDropProvider {
  constructor(b) {
    super($oE.Empty.append("uri", "path", "relative"));
    this.b = b;
    this.dropMimeTypes = [$YC.uriList];
    this.pasteMimeTypes = [$YC.uriList];
  }
  async a(dataTransfer, token) {
    const entries2 = await extractUriList(dataTransfer);
    if (!entries2.length || token.isCancellationRequested) {
      return;
    }
    const relativeUris = $Mb(entries2.map(({ uri }) => {
      const root = this.b.getWorkspaceFolder(uri);
      return root ? $xh(root.uri, uri) : void 0;
    }));
    if (!relativeUris.length) {
      return;
    }
    return {
      handledMimeType: $YC.uriList,
      insertText: relativeUris.join(" "),
      title: entries2.length > 1 ? localize(1006, null) : localize(1007, null),
      kind: this.kind
    };
  }
};
RelativePathProvider = __decorate([
  __param(0, $Zk)
], RelativePathProvider);
var PasteHtmlProvider = class {
  constructor() {
    this.kind = new $oE("html");
    this.providedPasteEditKinds = [this.kind];
    this.copyMimeTypes = [];
    this.pasteMimeTypes = ["text/html"];
    this.a = [{ mimeType: $YC.text }];
  }
  async provideDocumentPasteEdits(_model, _ranges, dataTransfer, context, token) {
    if (context.triggerKind !== DocumentPasteTriggerKind.PasteAs && !context.only?.contains(this.kind)) {
      return;
    }
    const entry = dataTransfer.get("text/html");
    const htmlText = await entry?.asString();
    if (!htmlText || token.isCancellationRequested) {
      return;
    }
    return {
      dispose() {
      },
      edits: [{
        insertText: htmlText,
        yieldTo: this.a,
        title: localize(1008, null),
        kind: this.kind
      }]
    };
  }
};
async function extractUriList(dataTransfer) {
  const urlListEntry = dataTransfer.get($YC.uriList);
  if (!urlListEntry) {
    return [];
  }
  const strUriList = await urlListEntry.asString();
  const entries2 = [];
  for (const entry of $nE.parse(strUriList)) {
    try {
      entries2.push({ uri: URI.parse(entry), originalText: entry });
    } catch {
    }
  }
  return entries2;
}
var genericLanguageSelector = { scheme: "*", hasAccessToAllModels: true };
var $W_ = class $W_2 extends $3c {
  constructor(languageFeaturesService, workspaceContextService) {
    super();
    this.B(languageFeaturesService.documentDropEditProvider.register(genericLanguageSelector, new $V_()));
    this.B(languageFeaturesService.documentDropEditProvider.register(genericLanguageSelector, new PathProvider()));
    this.B(languageFeaturesService.documentDropEditProvider.register(genericLanguageSelector, new RelativePathProvider(workspaceContextService)));
  }
};
$W_ = __decorate([
  __param(0, $mP),
  __param(1, $Zk)
], $W_);
var $X_ = class $X_2 extends $3c {
  constructor(languageFeaturesService, workspaceContextService) {
    super();
    this.B(languageFeaturesService.documentPasteEditProvider.register(genericLanguageSelector, new $V_()));
    this.B(languageFeaturesService.documentPasteEditProvider.register(genericLanguageSelector, new PathProvider()));
    this.B(languageFeaturesService.documentPasteEditProvider.register(genericLanguageSelector, new RelativePathProvider(workspaceContextService)));
    this.B(languageFeaturesService.documentPasteEditProvider.register(genericLanguageSelector, new PasteHtmlProvider()));
  }
};
$X_ = __decorate([
  __param(0, $mP),
  __param(1, $Zk)
], $X_);

// out-build/vs/editor/contrib/snippet/browser/snippetParser.js
var TokenType2;
(function(TokenType4) {
  TokenType4[TokenType4["Dollar"] = 0] = "Dollar";
  TokenType4[TokenType4["Colon"] = 1] = "Colon";
  TokenType4[TokenType4["Comma"] = 2] = "Comma";
  TokenType4[TokenType4["CurlyOpen"] = 3] = "CurlyOpen";
  TokenType4[TokenType4["CurlyClose"] = 4] = "CurlyClose";
  TokenType4[TokenType4["Backslash"] = 5] = "Backslash";
  TokenType4[TokenType4["Forwardslash"] = 6] = "Forwardslash";
  TokenType4[TokenType4["Pipe"] = 7] = "Pipe";
  TokenType4[TokenType4["Int"] = 8] = "Int";
  TokenType4[TokenType4["VariableName"] = 9] = "VariableName";
  TokenType4[TokenType4["Format"] = 10] = "Format";
  TokenType4[TokenType4["Plus"] = 11] = "Plus";
  TokenType4[TokenType4["Dash"] = 12] = "Dash";
  TokenType4[TokenType4["QuestionMark"] = 13] = "QuestionMark";
  TokenType4[TokenType4["EOF"] = 14] = "EOF";
})(TokenType2 || (TokenType2 = {}));
var $Z_ = class _$Z_ {
  constructor() {
    this.value = "";
    this.pos = 0;
  }
  static {
    this.d = {
      [
        36
        /* CharCode.DollarSign */
      ]: 0,
      [
        58
        /* CharCode.Colon */
      ]: 1,
      [
        44
        /* CharCode.Comma */
      ]: 2,
      [
        123
        /* CharCode.OpenCurlyBrace */
      ]: 3,
      [
        125
        /* CharCode.CloseCurlyBrace */
      ]: 4,
      [
        92
        /* CharCode.Backslash */
      ]: 5,
      [
        47
        /* CharCode.Slash */
      ]: 6,
      [
        124
        /* CharCode.Pipe */
      ]: 7,
      [
        43
        /* CharCode.Plus */
      ]: 11,
      [
        45
        /* CharCode.Dash */
      ]: 12,
      [
        63
        /* CharCode.QuestionMark */
      ]: 13
    };
  }
  static isDigitCharacter(ch) {
    return ch >= 48 && ch <= 57;
  }
  static isVariableCharacter(ch) {
    return ch === 95 || ch >= 97 && ch <= 122 || ch >= 65 && ch <= 90;
  }
  text(value) {
    this.value = value;
    this.pos = 0;
  }
  tokenText(token) {
    return this.value.substr(token.pos, token.len);
  }
  next() {
    if (this.pos >= this.value.length) {
      return { type: 14, pos: this.pos, len: 0 };
    }
    const pos = this.pos;
    let len = 0;
    let ch = this.value.charCodeAt(pos);
    let type;
    type = _$Z_.d[ch];
    if (typeof type === "number") {
      this.pos += 1;
      return { type, pos, len: 1 };
    }
    if (_$Z_.isDigitCharacter(ch)) {
      type = 8;
      do {
        len += 1;
        ch = this.value.charCodeAt(pos + len);
      } while (_$Z_.isDigitCharacter(ch));
      this.pos += len;
      return { type, pos, len };
    }
    if (_$Z_.isVariableCharacter(ch)) {
      type = 9;
      do {
        ch = this.value.charCodeAt(pos + ++len);
      } while (_$Z_.isVariableCharacter(ch) || _$Z_.isDigitCharacter(ch));
      this.pos += len;
      return { type, pos, len };
    }
    type = 10;
    do {
      len += 1;
      ch = this.value.charCodeAt(pos + len);
    } while (!isNaN(ch) && typeof _$Z_.d[ch] === "undefined" && !_$Z_.isDigitCharacter(ch) && !_$Z_.isVariableCharacter(ch));
    this.pos += len;
    return { type, pos, len };
  }
};
var $1_ = class {
  constructor() {
    this.d = [];
  }
  appendChild(child) {
    if (child instanceof $2_ && this.d[this.d.length - 1] instanceof $2_) {
      this.d[this.d.length - 1].value += child.value;
    } else {
      child.parent = this;
      this.d.push(child);
    }
    return this;
  }
  replace(child, others) {
    const { parent } = child;
    const idx = parent.children.indexOf(child);
    const newChildren = parent.children.slice(0);
    newChildren.splice(idx, 1, ...others);
    parent.d = newChildren;
    (function _fixParent(children, parent2) {
      for (const child2 of children) {
        child2.parent = parent2;
        _fixParent(child2.children, child2);
      }
    })(others, parent);
  }
  get children() {
    return this.d;
  }
  get rightMostDescendant() {
    if (this.d.length > 0) {
      return this.d[this.d.length - 1].rightMostDescendant;
    }
    return this;
  }
  get snippet() {
    let candidate = this;
    while (true) {
      if (!candidate) {
        return void 0;
      }
      if (candidate instanceof $9_) {
        return candidate;
      }
      candidate = candidate.parent;
    }
  }
  toString() {
    return this.children.reduce((prev, cur) => prev + cur.toString(), "");
  }
  len() {
    return 0;
  }
};
var $2_ = class _$2_ extends $1_ {
  static escape(value) {
    return value.replace(/\$|}|\\/g, "\\$&");
  }
  constructor(value) {
    super();
    this.value = value;
  }
  toString() {
    return this.value;
  }
  toTextmateString() {
    return _$2_.escape(this.value);
  }
  len() {
    return this.value.length;
  }
  clone() {
    return new _$2_(this.value);
  }
};
var $3_ = class extends $1_ {
};
var $4_ = class _$4_ extends $3_ {
  static compareByIndex(a, b) {
    if (a.index === b.index) {
      return 0;
    } else if (a.isFinalTabstop) {
      return 1;
    } else if (b.isFinalTabstop) {
      return -1;
    } else if (a.index < b.index) {
      return -1;
    } else if (a.index > b.index) {
      return 1;
    } else {
      return 0;
    }
  }
  constructor(index) {
    super();
    this.index = index;
  }
  get isFinalTabstop() {
    return this.index === 0;
  }
  get choice() {
    return this.d.length === 1 && this.d[0] instanceof $5_ ? this.d[0] : void 0;
  }
  toTextmateString() {
    let transformString = "";
    if (this.transform) {
      transformString = this.transform.toTextmateString();
    }
    if (this.children.length === 0 && !this.transform) {
      return `$${this.index}`;
    } else if (this.children.length === 0) {
      return `\${${this.index}${transformString}}`;
    } else if (this.choice) {
      return `\${${this.index}|${this.choice.toTextmateString()}|${transformString}}`;
    } else {
      return `\${${this.index}:${this.children.map((child) => child.toTextmateString()).join("")}${transformString}}`;
    }
  }
  clone() {
    const ret = new _$4_(this.index);
    if (this.transform) {
      ret.transform = this.transform.clone();
    }
    ret.d = this.children.map((child) => child.clone());
    return ret;
  }
};
var $5_ = class _$5_ extends $1_ {
  constructor() {
    super(...arguments);
    this.options = [];
  }
  appendChild(marker) {
    if (marker instanceof $2_) {
      marker.parent = this;
      this.options.push(marker);
    }
    return this;
  }
  toString() {
    return this.options[0].value;
  }
  toTextmateString() {
    return this.options.map((option) => option.value.replace(/\||,|\\/g, "\\$&")).join(",");
  }
  len() {
    return this.options[0].len();
  }
  clone() {
    const ret = new _$5_();
    this.options.forEach(ret.appendChild, ret);
    return ret;
  }
};
var $6_ = class _$6_ extends $1_ {
  constructor() {
    super(...arguments);
    this.regexp = new RegExp("");
  }
  resolve(value) {
    const _this = this;
    let didMatch = false;
    let ret = value.replace(this.regexp, function() {
      didMatch = true;
      return _this.f(Array.prototype.slice.call(arguments, 0, -2));
    });
    if (!didMatch && this.d.some((child) => child instanceof $7_ && Boolean(child.elseValue))) {
      ret = this.f([]);
    }
    return ret;
  }
  f(groups) {
    let ret = "";
    for (const marker of this.d) {
      if (marker instanceof $7_) {
        let value = groups[marker.index] || "";
        value = marker.resolve(value);
        ret += value;
      } else {
        ret += marker.toString();
      }
    }
    return ret;
  }
  toString() {
    return "";
  }
  toTextmateString() {
    return `/${this.regexp.source}/${this.children.map((c) => c.toTextmateString())}/${(this.regexp.ignoreCase ? "i" : "") + (this.regexp.global ? "g" : "")}`;
  }
  clone() {
    const ret = new _$6_();
    ret.regexp = new RegExp(this.regexp.source, (this.regexp.ignoreCase ? "i" : "") + (this.regexp.global ? "g" : ""));
    ret.d = this.children.map((child) => child.clone());
    return ret;
  }
};
var $7_ = class _$7_ extends $1_ {
  constructor(index, shorthandName, ifValue, elseValue) {
    super();
    this.index = index;
    this.shorthandName = shorthandName;
    this.ifValue = ifValue;
    this.elseValue = elseValue;
  }
  resolve(value) {
    if (this.shorthandName === "upcase") {
      return !value ? "" : value.toLocaleUpperCase();
    } else if (this.shorthandName === "downcase") {
      return !value ? "" : value.toLocaleLowerCase();
    } else if (this.shorthandName === "capitalize") {
      return !value ? "" : value[0].toLocaleUpperCase() + value.substr(1);
    } else if (this.shorthandName === "pascalcase") {
      return !value ? "" : this.f(value);
    } else if (this.shorthandName === "camelcase") {
      return !value ? "" : this.g(value);
    } else if (Boolean(value) && typeof this.ifValue === "string") {
      return this.ifValue;
    } else if (!Boolean(value) && typeof this.elseValue === "string") {
      return this.elseValue;
    } else {
      return value || "";
    }
  }
  f(value) {
    const match = value.match(/[a-z0-9]+/gi);
    if (!match) {
      return value;
    }
    return match.map((word) => {
      return word.charAt(0).toUpperCase() + word.substr(1);
    }).join("");
  }
  g(value) {
    const match = value.match(/[a-z0-9]+/gi);
    if (!match) {
      return value;
    }
    return match.map((word, index) => {
      if (index === 0) {
        return word.charAt(0).toLowerCase() + word.substr(1);
      }
      return word.charAt(0).toUpperCase() + word.substr(1);
    }).join("");
  }
  toTextmateString() {
    let value = "${";
    value += this.index;
    if (this.shorthandName) {
      value += `:/${this.shorthandName}`;
    } else if (this.ifValue && this.elseValue) {
      value += `:?${this.ifValue}:${this.elseValue}`;
    } else if (this.ifValue) {
      value += `:+${this.ifValue}`;
    } else if (this.elseValue) {
      value += `:-${this.elseValue}`;
    }
    value += "}";
    return value;
  }
  clone() {
    const ret = new _$7_(this.index, this.shorthandName, this.ifValue, this.elseValue);
    return ret;
  }
};
var $8_ = class _$8_ extends $3_ {
  constructor(name) {
    super();
    this.name = name;
  }
  resolve(resolver) {
    let value = resolver.resolve(this);
    if (this.transform) {
      value = this.transform.resolve(value || "");
    }
    if (value !== void 0) {
      this.d = [new $2_(value)];
      return true;
    }
    return false;
  }
  toTextmateString() {
    let transformString = "";
    if (this.transform) {
      transformString = this.transform.toTextmateString();
    }
    if (this.children.length === 0) {
      return `\${${this.name}${transformString}}`;
    } else {
      return `\${${this.name}:${this.children.map((child) => child.toTextmateString()).join("")}${transformString}}`;
    }
  }
  clone() {
    const ret = new _$8_(this.name);
    if (this.transform) {
      ret.transform = this.transform.clone();
    }
    ret.d = this.children.map((child) => child.clone());
    return ret;
  }
};
function walk(marker, visitor) {
  const stack = [...marker];
  while (stack.length > 0) {
    const marker2 = stack.shift();
    const recurse = visitor(marker2);
    if (!recurse) {
      break;
    }
    stack.unshift(...marker2.children);
  }
}
var $9_ = class _$9_ extends $1_ {
  get placeholderInfo() {
    if (!this.f) {
      const all = [];
      let last;
      this.walk(function(candidate) {
        if (candidate instanceof $4_) {
          all.push(candidate);
          last = !last || last.index < candidate.index ? candidate : last;
        }
        return true;
      });
      this.f = { all, last };
    }
    return this.f;
  }
  get placeholders() {
    const { all } = this.placeholderInfo;
    return all;
  }
  offset(marker) {
    let pos = 0;
    let found = false;
    this.walk((candidate) => {
      if (candidate === marker) {
        found = true;
        return false;
      }
      pos += candidate.len();
      return true;
    });
    if (!found) {
      return -1;
    }
    return pos;
  }
  fullLen(marker) {
    let ret = 0;
    walk([marker], (marker2) => {
      ret += marker2.len();
      return true;
    });
    return ret;
  }
  enclosingPlaceholders(placeholder) {
    const ret = [];
    let { parent } = placeholder;
    while (parent) {
      if (parent instanceof $4_) {
        ret.push(parent);
      }
      parent = parent.parent;
    }
    return ret;
  }
  resolveVariables(resolver) {
    this.walk((candidate) => {
      if (candidate instanceof $8_) {
        if (candidate.resolve(resolver)) {
          this.f = void 0;
        }
      }
      return true;
    });
    return this;
  }
  appendChild(child) {
    this.f = void 0;
    return super.appendChild(child);
  }
  replace(child, others) {
    this.f = void 0;
    return super.replace(child, others);
  }
  toTextmateString() {
    return this.children.reduce((prev, cur) => prev + cur.toTextmateString(), "");
  }
  clone() {
    const ret = new _$9_();
    this.d = this.children.map((child) => child.clone());
    return ret;
  }
  walk(visitor) {
    walk(this.children, visitor);
  }
};
var $0_ = class _$0_ {
  constructor() {
    this.d = new $Z_();
    this.f = { type: 14, pos: 0, len: 0 };
  }
  static escape(value) {
    return value.replace(/\$|}|\\/g, "\\$&");
  }
  /**
   * Takes a snippet and returns the insertable string, e.g return the snippet-string
   * without any placeholder, tabstop, variables etc...
   */
  static asInsertText(value) {
    return new _$0_().parse(value).toString();
  }
  static guessNeedsClipboard(template) {
    return /\${?CLIPBOARD/.test(template);
  }
  parse(value, insertFinalTabstop, enforceFinalTabstop) {
    const snippet = new $9_();
    this.parseFragment(value, snippet);
    this.ensureFinalTabstop(snippet, enforceFinalTabstop ?? false, insertFinalTabstop ?? false);
    return snippet;
  }
  parseFragment(value, snippet) {
    const offset = snippet.children.length;
    this.d.text(value);
    this.f = this.d.next();
    while (this.j(snippet)) {
    }
    const placeholderDefaultValues = /* @__PURE__ */ new Map();
    const incompletePlaceholders = [];
    snippet.walk((marker) => {
      if (marker instanceof $4_) {
        if (marker.isFinalTabstop) {
          placeholderDefaultValues.set(0, void 0);
        } else if (!placeholderDefaultValues.has(marker.index) && marker.children.length > 0) {
          placeholderDefaultValues.set(marker.index, marker.children);
        } else {
          incompletePlaceholders.push(marker);
        }
      }
      return true;
    });
    const fillInIncompletePlaceholder = (placeholder, stack2) => {
      const defaultValues = placeholderDefaultValues.get(placeholder.index);
      if (!defaultValues) {
        return;
      }
      const clone2 = new $4_(placeholder.index);
      clone2.transform = placeholder.transform;
      for (const child of defaultValues) {
        const newChild = child.clone();
        clone2.appendChild(newChild);
        if (newChild instanceof $4_ && placeholderDefaultValues.has(newChild.index) && !stack2.has(newChild.index)) {
          stack2.add(newChild.index);
          fillInIncompletePlaceholder(newChild, stack2);
          stack2.delete(newChild.index);
        }
      }
      snippet.replace(placeholder, [clone2]);
    };
    const stack = /* @__PURE__ */ new Set();
    for (const placeholder of incompletePlaceholders) {
      fillInIncompletePlaceholder(placeholder, stack);
    }
    return snippet.children.slice(offset);
  }
  ensureFinalTabstop(snippet, enforceFinalTabstop, insertFinalTabstop) {
    if (enforceFinalTabstop || insertFinalTabstop && snippet.placeholders.length > 0) {
      const finalTabstop = snippet.placeholders.find((p) => p.index === 0);
      if (!finalTabstop) {
        snippet.appendChild(new $4_(0));
      }
    }
  }
  g(type, value) {
    if (type === void 0 || this.f.type === type) {
      const ret = !value ? true : this.d.tokenText(this.f);
      this.f = this.d.next();
      return ret;
    }
    return false;
  }
  h(token) {
    this.d.pos = token.pos + token.len;
    this.f = token;
    return false;
  }
  i(type) {
    const start = this.f;
    while (this.f.type !== type) {
      if (this.f.type === 14) {
        return false;
      } else if (this.f.type === 5) {
        const nextToken = this.d.next();
        if (nextToken.type !== 0 && nextToken.type !== 4 && nextToken.type !== 5) {
          return false;
        }
      }
      this.f = this.d.next();
    }
    const value = this.d.value.substring(start.pos, this.f.pos).replace(/\\(\$|}|\\)/g, "$1");
    this.f = this.d.next();
    return value;
  }
  j(marker) {
    return this.k(marker) || this.l(marker) || this.m(marker) || this.o(marker) || this.s(marker);
  }
  // \$, \\, \} -> just text
  k(marker) {
    let value;
    if (value = this.g(5, true)) {
      value = this.g(0, true) || this.g(4, true) || this.g(5, true) || value;
      marker.appendChild(new $2_(value));
      return true;
    }
    return false;
  }
  // $foo -> variable, $1 -> tabstop
  l(parent) {
    let value;
    const token = this.f;
    const match = this.g(
      0
      /* TokenType.Dollar */
    ) && (value = this.g(9, true) || this.g(8, true));
    if (!match) {
      return this.h(token);
    }
    parent.appendChild(/^\d+$/.test(value) ? new $4_(Number(value)) : new $8_(value));
    return true;
  }
  // ${1:<children>}, ${1} -> placeholder
  m(parent) {
    let index;
    const token = this.f;
    const match = this.g(
      0
      /* TokenType.Dollar */
    ) && this.g(
      3
      /* TokenType.CurlyOpen */
    ) && (index = this.g(8, true));
    if (!match) {
      return this.h(token);
    }
    const placeholder = new $4_(Number(index));
    if (this.g(
      1
      /* TokenType.Colon */
    )) {
      while (true) {
        if (this.g(
          4
          /* TokenType.CurlyClose */
        )) {
          parent.appendChild(placeholder);
          return true;
        }
        if (this.j(placeholder)) {
          continue;
        }
        parent.appendChild(new $2_("${" + index + ":"));
        placeholder.children.forEach(parent.appendChild, parent);
        return true;
      }
    } else if (placeholder.index > 0 && this.g(
      7
      /* TokenType.Pipe */
    )) {
      const choice = new $5_();
      while (true) {
        if (this.n(choice)) {
          if (this.g(
            2
            /* TokenType.Comma */
          )) {
            continue;
          }
          if (this.g(
            7
            /* TokenType.Pipe */
          )) {
            placeholder.appendChild(choice);
            if (this.g(
              4
              /* TokenType.CurlyClose */
            )) {
              parent.appendChild(placeholder);
              return true;
            }
          }
        }
        this.h(token);
        return false;
      }
    } else if (this.g(
      6
      /* TokenType.Forwardslash */
    )) {
      if (this.q(placeholder)) {
        parent.appendChild(placeholder);
        return true;
      }
      this.h(token);
      return false;
    } else if (this.g(
      4
      /* TokenType.CurlyClose */
    )) {
      parent.appendChild(placeholder);
      return true;
    } else {
      return this.h(token);
    }
  }
  n(parent) {
    const token = this.f;
    const values = [];
    while (true) {
      if (this.f.type === 2 || this.f.type === 7) {
        break;
      }
      let value;
      if (value = this.g(5, true)) {
        value = this.g(2, true) || this.g(7, true) || this.g(5, true) || value;
      } else {
        value = this.g(void 0, true);
      }
      if (!value) {
        this.h(token);
        return false;
      }
      values.push(value);
    }
    if (values.length === 0) {
      this.h(token);
      return false;
    }
    parent.appendChild(new $2_(values.join("")));
    return true;
  }
  // ${foo:<children>}, ${foo} -> variable
  o(parent) {
    let name;
    const token = this.f;
    const match = this.g(
      0
      /* TokenType.Dollar */
    ) && this.g(
      3
      /* TokenType.CurlyOpen */
    ) && (name = this.g(9, true));
    if (!match) {
      return this.h(token);
    }
    const variable = new $8_(name);
    if (this.g(
      1
      /* TokenType.Colon */
    )) {
      while (true) {
        if (this.g(
          4
          /* TokenType.CurlyClose */
        )) {
          parent.appendChild(variable);
          return true;
        }
        if (this.j(variable)) {
          continue;
        }
        parent.appendChild(new $2_("${" + name + ":"));
        variable.children.forEach(parent.appendChild, parent);
        return true;
      }
    } else if (this.g(
      6
      /* TokenType.Forwardslash */
    )) {
      if (this.q(variable)) {
        parent.appendChild(variable);
        return true;
      }
      this.h(token);
      return false;
    } else if (this.g(
      4
      /* TokenType.CurlyClose */
    )) {
      parent.appendChild(variable);
      return true;
    } else {
      return this.h(token);
    }
  }
  q(parent) {
    const transform = new $6_();
    let regexValue = "";
    let regexOptions = "";
    while (true) {
      if (this.g(
        6
        /* TokenType.Forwardslash */
      )) {
        break;
      }
      let escaped;
      if (escaped = this.g(5, true)) {
        escaped = this.g(6, true) || escaped;
        regexValue += escaped;
        continue;
      }
      if (this.f.type !== 14) {
        regexValue += this.g(void 0, true);
        continue;
      }
      return false;
    }
    while (true) {
      if (this.g(
        6
        /* TokenType.Forwardslash */
      )) {
        break;
      }
      let escaped;
      if (escaped = this.g(5, true)) {
        escaped = this.g(5, true) || this.g(6, true) || escaped;
        transform.appendChild(new $2_(escaped));
        continue;
      }
      if (this.r(transform) || this.s(transform)) {
        continue;
      }
      return false;
    }
    while (true) {
      if (this.g(
        4
        /* TokenType.CurlyClose */
      )) {
        break;
      }
      if (this.f.type !== 14) {
        regexOptions += this.g(void 0, true);
        continue;
      }
      return false;
    }
    try {
      transform.regexp = new RegExp(regexValue, regexOptions);
    } catch (e) {
      return false;
    }
    parent.transform = transform;
    return true;
  }
  r(parent) {
    const token = this.f;
    if (!this.g(
      0
      /* TokenType.Dollar */
    )) {
      return false;
    }
    let complex = false;
    if (this.g(
      3
      /* TokenType.CurlyOpen */
    )) {
      complex = true;
    }
    const index = this.g(8, true);
    if (!index) {
      this.h(token);
      return false;
    } else if (!complex) {
      parent.appendChild(new $7_(Number(index)));
      return true;
    } else if (this.g(
      4
      /* TokenType.CurlyClose */
    )) {
      parent.appendChild(new $7_(Number(index)));
      return true;
    } else if (!this.g(
      1
      /* TokenType.Colon */
    )) {
      this.h(token);
      return false;
    }
    if (this.g(
      6
      /* TokenType.Forwardslash */
    )) {
      const shorthand = this.g(9, true);
      if (!shorthand || !this.g(
        4
        /* TokenType.CurlyClose */
      )) {
        this.h(token);
        return false;
      } else {
        parent.appendChild(new $7_(Number(index), shorthand));
        return true;
      }
    } else if (this.g(
      11
      /* TokenType.Plus */
    )) {
      const ifValue = this.i(
        4
        /* TokenType.CurlyClose */
      );
      if (ifValue) {
        parent.appendChild(new $7_(Number(index), void 0, ifValue, void 0));
        return true;
      }
    } else if (this.g(
      12
      /* TokenType.Dash */
    )) {
      const elseValue = this.i(
        4
        /* TokenType.CurlyClose */
      );
      if (elseValue) {
        parent.appendChild(new $7_(Number(index), void 0, void 0, elseValue));
        return true;
      }
    } else if (this.g(
      13
      /* TokenType.QuestionMark */
    )) {
      const ifValue = this.i(
        1
        /* TokenType.Colon */
      );
      if (ifValue) {
        const elseValue = this.i(
          4
          /* TokenType.CurlyClose */
        );
        if (elseValue) {
          parent.appendChild(new $7_(Number(index), void 0, ifValue, elseValue));
          return true;
        }
      }
    } else {
      const elseValue = this.i(
        4
        /* TokenType.CurlyClose */
      );
      if (elseValue) {
        parent.appendChild(new $7_(Number(index), void 0, void 0, elseValue));
        return true;
      }
    }
    this.h(token);
    return false;
  }
  s(marker) {
    if (this.f.type !== 14) {
      marker.appendChild(new $2_(this.d.tokenText(this.f)));
      this.g(void 0);
      return true;
    }
    return false;
  }
};

// out-build/vs/editor/contrib/dropOrPasteInto/browser/edit.js
function $$_(uri, ranges, edit3) {
  if (typeof edit3.insertText === "string" ? edit3.insertText === "" : edit3.insertText.snippet === "") {
    return {
      edits: edit3.additionalEdit?.edits ?? []
    };
  }
  return {
    edits: [
      ...ranges.map((range) => new $J_(uri, { range, text: typeof edit3.insertText === "string" ? $0_.escape(edit3.insertText) + "$0" : edit3.insertText.snippet, insertAsSnippet: true })),
      ...edit3.additionalEdit?.edits ?? []
    ]
  };
}
function $__(edits) {
  function yieldsTo(yTo, other) {
    if ("mimeType" in yTo) {
      return yTo.mimeType === other.handledMimeType;
    }
    return !!other.kind && yTo.kind.contains(other.kind);
  }
  const yieldsToMap = /* @__PURE__ */ new Map();
  for (const edit3 of edits) {
    for (const yTo of edit3.yieldTo ?? []) {
      for (const other of edits) {
        if (other === edit3) {
          continue;
        }
        if (yieldsTo(yTo, other)) {
          let arr = yieldsToMap.get(edit3);
          if (!arr) {
            arr = [];
            yieldsToMap.set(edit3, arr);
          }
          arr.push(other);
        }
      }
    }
  }
  if (!yieldsToMap.size) {
    return Array.from(edits);
  }
  const visited = /* @__PURE__ */ new Set();
  const tempStack = [];
  function visit(nodes) {
    if (!nodes.length) {
      return [];
    }
    const node = nodes[0];
    if (tempStack.includes(node)) {
      console.warn("Yield to cycle detected", node);
      return nodes;
    }
    if (visited.has(node)) {
      return visit(nodes.slice(1));
    }
    let pre = [];
    const yTo = yieldsToMap.get(node);
    if (yTo) {
      tempStack.push(node);
      pre = visit(yTo);
      tempStack.pop();
    }
    visited.add(node);
    return [...pre, node, ...visit(nodes.slice(1))];
  }
  return visit(Array.from(edits));
}

// out-build/vs/base/browser/ui/button/button.js
var $j2 = {
  buttonBackground: "#0E639C",
  buttonHoverBackground: "#006BB3",
  buttonSeparator: $Vn.white.toString(),
  buttonForeground: $Vn.white.toString(),
  buttonBorder: void 0,
  buttonSecondaryBackground: void 0,
  buttonSecondaryForeground: void 0,
  buttonSecondaryHoverBackground: void 0
};
var $k2 = class extends $3c {
  get onDidClick() {
    return this.j.event;
  }
  get onDidEscape() {
    return this.m.event;
  }
  constructor(container2, options3) {
    super();
    this.c = "";
    this.j = this.B(new $ze());
    this.m = this.B(new $ze());
    this.a = options3;
    this.b = document.createElement("a");
    this.b.classList.add("monaco-button");
    this.b.tabIndex = 0;
    this.b.setAttribute("role", "button");
    this.b.classList.toggle("secondary", !!options3.secondary);
    const background = options3.secondary ? options3.buttonSecondaryBackground : options3.buttonBackground;
    const foreground = options3.secondary ? options3.buttonSecondaryForeground : options3.buttonForeground;
    this.b.style.color = foreground || "";
    this.b.style.backgroundColor = background || "";
    if (options3.supportShortLabel) {
      this.g = document.createElement("div");
      this.g.classList.add("monaco-button-label-short");
      this.b.appendChild(this.g);
      this.f = document.createElement("div");
      this.f.classList.add("monaco-button-label");
      this.b.appendChild(this.f);
      this.b.classList.add("monaco-text-button-with-short-label");
    }
    if (typeof options3.title === "string") {
      this.setTitle(options3.title);
    }
    if (typeof options3.ariaLabel === "string") {
      this.b.setAttribute("aria-label", options3.ariaLabel);
    }
    container2.appendChild(this.b);
    this.B($mZ.addTarget(this.b));
    [$7j.CLICK, EventType.Tap].forEach((eventType) => {
      this.B($_i(this.b, eventType, (e) => {
        if (!this.enabled) {
          $9j.stop(e);
          return;
        }
        this.j.fire(e);
      }));
    });
    this.B($_i(this.b, $7j.KEY_DOWN, (e) => {
      const event = new $if(e);
      let eventHandled = false;
      if (this.enabled && (event.equals(
        3
        /* KeyCode.Enter */
      ) || event.equals(
        10
        /* KeyCode.Space */
      ))) {
        this.j.fire(e);
        eventHandled = true;
      } else if (event.equals(
        9
        /* KeyCode.Escape */
      )) {
        this.m.fire(e);
        this.b.blur();
        eventHandled = true;
      }
      if (eventHandled) {
        $9j.stop(event, true);
      }
    }));
    this.B($_i(this.b, $7j.MOUSE_OVER, (e) => {
      if (!this.b.classList.contains("disabled")) {
        this.s(true);
      }
    }));
    this.B($_i(this.b, $7j.MOUSE_OUT, (e) => {
      this.s(false);
    }));
    this.n = this.B($_j(this.b));
    this.B(this.n.onDidFocus(() => {
      if (this.enabled) {
        this.s(true);
      }
    }));
    this.B(this.n.onDidBlur(() => {
      if (this.enabled) {
        this.s(false);
      }
    }));
  }
  dispose() {
    super.dispose();
    this.b.remove();
  }
  r(content) {
    const elements = [];
    for (let segment of $B1(content)) {
      if (typeof segment === "string") {
        segment = segment.trim();
        if (segment === "") {
          continue;
        }
        const node = document.createElement("span");
        node.textContent = segment;
        elements.push(node);
      } else {
        elements.push(segment);
      }
    }
    return elements;
  }
  s(hover) {
    let background;
    if (this.a.secondary) {
      background = hover ? this.a.buttonSecondaryHoverBackground : this.a.buttonSecondaryBackground;
    } else {
      background = hover ? this.a.buttonHoverBackground : this.a.buttonBackground;
    }
    if (background) {
      this.b.style.backgroundColor = background;
    }
  }
  get element() {
    return this.b;
  }
  set label(value) {
    if (this.c === value) {
      return;
    }
    if ($dm(this.c) && $dm(value) && $em(this.c, value)) {
      return;
    }
    this.b.classList.add("monaco-text-button");
    const labelElement = this.a.supportShortLabel ? this.f : this.b;
    if ($dm(value)) {
      const rendered = $D1(value, { inline: true });
      rendered.dispose();
      const root = rendered.element.querySelector("p")?.innerHTML;
      if (root) {
        const sanitized = purify.sanitize(root, { ADD_TAGS: ["b", "i", "u", "code", "span"], ALLOWED_ATTR: ["class"], RETURN_TRUSTED_TYPE: true });
        labelElement.innerHTML = sanitized;
      } else {
        $dk(labelElement);
      }
    } else {
      if (this.a.supportIcons) {
        $dk(labelElement, ...this.r(value));
      } else {
        labelElement.textContent = value;
      }
    }
    let title = "";
    if (typeof this.a.title === "string") {
      title = this.a.title;
    } else if (this.a.title) {
      title = $F1(value);
    }
    this.setTitle(title);
    if (typeof this.a.ariaLabel === "string") {
      this.b.setAttribute("aria-label", this.a.ariaLabel);
    } else if (this.a.ariaLabel) {
      this.b.setAttribute("aria-label", title);
    }
    this.c = value;
  }
  get label() {
    return this.c;
  }
  set labelShort(value) {
    if (!this.a.supportShortLabel || !this.g) {
      return;
    }
    if (this.a.supportIcons) {
      $dk(this.g, ...this.r(value));
    } else {
      this.g.textContent = value;
    }
  }
  set icon(icon2) {
    this.b.classList.add(...ThemeIcon.asClassNameArray(icon2));
  }
  set enabled(value) {
    if (value) {
      this.b.classList.remove("disabled");
      this.b.setAttribute("aria-disabled", String(false));
      this.b.tabIndex = 0;
    } else {
      this.b.classList.add("disabled");
      this.b.setAttribute("aria-disabled", String(true));
    }
  }
  get enabled() {
    return !this.b.classList.contains("disabled");
  }
  set checked(value) {
    if (value) {
      this.b.classList.add("checked");
      this.b.setAttribute("aria-checked", "true");
    } else {
      this.b.classList.remove("checked");
      this.b.setAttribute("aria-checked", "false");
    }
  }
  get checked() {
    return this.b.classList.contains("checked");
  }
  setTitle(title) {
    if (!this.h && title !== "") {
      this.h = this.B($J1().setupManagedHover(this.a.hoverDelegate ?? $JZ("element"), this.b, title));
    } else if (this.h) {
      this.h.update(title);
    }
  }
  focus() {
    this.b.focus();
  }
  hasFocus() {
    return $Mj(this.b);
  }
};
var $l2 = class extends $3c {
  constructor(container2, options3) {
    super();
    this.h = this.B(new $ze());
    this.onDidClick = this.h.event;
    this.element = document.createElement("div");
    this.element.classList.add("monaco-button-dropdown");
    container2.appendChild(this.element);
    if (!options3.hoverDelegate) {
      options3 = { ...options3, hoverDelegate: this.B($KZ()) };
    }
    this.a = this.B(new $k2(this.element, options3));
    this.B(this.a.onDidClick((e) => this.h.fire(e)));
    this.b = this.B(new $Um("primaryAction", $F1(this.a.label), void 0, true, async () => this.h.fire(void 0)));
    this.f = document.createElement("div");
    this.f.classList.add("monaco-button-dropdown-separator");
    this.g = document.createElement("div");
    this.f.appendChild(this.g);
    this.element.appendChild(this.f);
    const border = options3.buttonBorder;
    if (border) {
      this.f.style.borderTop = "1px solid " + border;
      this.f.style.borderBottom = "1px solid " + border;
    }
    const buttonBackground = options3.secondary ? options3.buttonSecondaryBackground : options3.buttonBackground;
    this.f.style.backgroundColor = buttonBackground ?? "";
    this.g.style.backgroundColor = options3.buttonSeparator ?? "";
    this.c = this.B(new $k2(this.element, { ...options3, title: localize(1, null), supportIcons: true }));
    this.c.element.setAttribute("aria-haspopup", "true");
    this.c.element.setAttribute("aria-expanded", "false");
    this.c.element.classList.add("monaco-dropdown-button");
    this.c.icon = $6l.dropDownButton;
    this.B(this.c.onDidClick((e) => {
      const actions = Array.isArray(options3.actions) ? options3.actions : options3.actions.getActions();
      options3.contextMenuProvider.showContextMenu({
        getAnchor: () => this.c.element,
        getActions: () => options3.addPrimaryActionToDropdown === false ? [...actions] : [this.b, ...actions],
        actionRunner: options3.actionRunner,
        onHide: () => this.c.element.setAttribute("aria-expanded", "false")
      });
      this.c.element.setAttribute("aria-expanded", "true");
    }));
  }
  dispose() {
    super.dispose();
    this.element.remove();
  }
  set label(value) {
    this.a.label = value;
    this.b.label = value;
  }
  set icon(icon2) {
    this.a.icon = icon2;
  }
  set enabled(enabled) {
    this.a.enabled = enabled;
    this.c.enabled = enabled;
    this.element.classList.toggle("disabled", !enabled);
  }
  get enabled() {
    return this.a.enabled;
  }
  set checked(value) {
    this.a.checked = value;
  }
  get checked() {
    return this.a.checked;
  }
  focus() {
    this.a.focus();
  }
  hasFocus() {
    return this.a.hasFocus() || this.c.hasFocus();
  }
};
var $m2 = class {
  constructor(container2, d) {
    this.d = d;
    this.b = document.createElement("div");
    this.b.classList.add("monaco-description-button");
    this.a = new $k2(this.b, d);
    this.c = document.createElement("div");
    this.c.classList.add("monaco-button-description");
    this.b.appendChild(this.c);
    container2.appendChild(this.b);
  }
  get onDidClick() {
    return this.a.onDidClick;
  }
  get element() {
    return this.b;
  }
  set label(value) {
    this.a.label = value;
  }
  set icon(icon2) {
    this.a.icon = icon2;
  }
  get enabled() {
    return this.a.enabled;
  }
  set enabled(enabled) {
    this.a.enabled = enabled;
  }
  set checked(value) {
    this.a.checked = value;
  }
  get checked() {
    return this.a.checked;
  }
  focus() {
    this.a.focus();
  }
  hasFocus() {
    return this.a.hasFocus();
  }
  dispose() {
    this.a.dispose();
  }
  set description(value) {
    if (this.d.supportIcons) {
      $dk(this.c, ...$B1(value));
    } else {
      this.c.textContent = value;
    }
  }
};
var $n2 = class {
  constructor(c) {
    this.c = c;
    this.a = [];
    this.b = new $2c();
  }
  dispose() {
    this.b.dispose();
  }
  get buttons() {
    return this.a;
  }
  clear() {
    this.b.clear();
    this.a.length = 0;
  }
  addButton(options3) {
    const button = this.b.add(new $k2(this.c, options3));
    this.d(button);
    return button;
  }
  addButtonWithDescription(options3) {
    const button = this.b.add(new $m2(this.c, options3));
    this.d(button);
    return button;
  }
  addButtonWithDropdown(options3) {
    const button = this.b.add(new $l2(this.c, options3));
    this.d(button);
    return button;
  }
  d(button) {
    this.a.push(button);
    const index = this.a.length - 1;
    this.b.add($_i(button.element, $7j.KEY_DOWN, (e) => {
      const event = new $if(e);
      let eventHandled = true;
      let buttonIndexToFocus;
      if (event.equals(
        15
        /* KeyCode.LeftArrow */
      )) {
        buttonIndexToFocus = index > 0 ? index - 1 : this.a.length - 1;
      } else if (event.equals(
        17
        /* KeyCode.RightArrow */
      )) {
        buttonIndexToFocus = index === this.a.length - 1 ? 0 : index + 1;
      } else {
        eventHandled = false;
      }
      if (eventHandled && typeof buttonIndexToFocus === "number") {
        this.a[buttonIndexToFocus].focus();
        $9j.stop(e, true);
      }
    }));
  }
};

// out-build/vs/base/browser/ui/keybindingLabel/keybindingLabel.js
var $11 = $;
var $22 = {
  keybindingLabelBackground: void 0,
  keybindingLabelForeground: void 0,
  keybindingLabelBorder: void 0,
  keybindingLabelBottomBorder: void 0,
  keybindingLabelShadow: void 0
};
var $32 = class _$32 extends $3c {
  constructor(container2, r2, options3) {
    super();
    this.r = r2;
    this.g = /* @__PURE__ */ new Set();
    this.f = options3 || /* @__PURE__ */ Object.create(null);
    const labelForeground = this.f.keybindingLabelForeground;
    this.c = $bk(container2, $11(".monaco-keybinding"));
    if (labelForeground) {
      this.c.style.color = labelForeground;
    }
    this.h = this.B($J1().setupManagedHover($JZ("mouse"), this.c, ""));
    this.n = false;
    container2.appendChild(this.c);
  }
  get element() {
    return this.c;
  }
  set(keybinding, matches) {
    if (this.n && this.j === keybinding && _$32.C(this.m, matches)) {
      return;
    }
    this.j = keybinding;
    this.m = matches;
    this.s();
  }
  s() {
    this.t();
    if (this.j) {
      const chords = this.j.getChords();
      if (chords[0]) {
        this.u(this.c, chords[0], this.m ? this.m.firstPart : null);
      }
      for (let i2 = 1; i2 < chords.length; i2++) {
        $bk(this.c, $11("span.monaco-keybinding-key-chord-separator", void 0, " "));
        this.u(this.c, chords[i2], this.m ? this.m.chordPart : null);
      }
      const title = this.f.disableTitle ?? false ? void 0 : this.j.getAriaLabel() || void 0;
      this.h.update(title);
      this.c.setAttribute("aria-label", title || "");
    } else if (this.f && this.f.renderUnboundKeybindings) {
      this.y(this.c);
    }
    this.n = true;
  }
  t() {
    $$i(this.c);
    this.g.clear();
  }
  u(parent, chord, match) {
    const modifierLabels = $X2.modifierLabels[this.r];
    if (chord.ctrlKey) {
      this.w(parent, modifierLabels.ctrlKey, Boolean(match?.ctrlKey), modifierLabels.separator);
    }
    if (chord.shiftKey) {
      this.w(parent, modifierLabels.shiftKey, Boolean(match?.shiftKey), modifierLabels.separator);
    }
    if (chord.altKey) {
      this.w(parent, modifierLabels.altKey, Boolean(match?.altKey), modifierLabels.separator);
    }
    if (chord.metaKey) {
      this.w(parent, modifierLabels.metaKey, Boolean(match?.metaKey), modifierLabels.separator);
    }
    const keyLabel = chord.keyLabel;
    if (keyLabel) {
      this.w(parent, keyLabel, Boolean(match?.keyCode), "");
    }
  }
  w(parent, label3, highlight, separator) {
    $bk(parent, this.z(label3, highlight ? ".highlight" : ""));
    if (separator) {
      $bk(parent, $11("span.monaco-keybinding-key-separator", void 0, separator));
    }
  }
  y(parent) {
    $bk(parent, this.z(localize(25, null)));
  }
  z(label3, extraClass = "") {
    const keyElement = $11("span.monaco-keybinding-key" + extraClass, void 0, label3);
    this.g.add(keyElement);
    if (this.f.keybindingLabelBackground) {
      keyElement.style.backgroundColor = this.f.keybindingLabelBackground;
    }
    if (this.f.keybindingLabelBorder) {
      keyElement.style.borderColor = this.f.keybindingLabelBorder;
    }
    if (this.f.keybindingLabelBottomBorder) {
      keyElement.style.borderBottomColor = this.f.keybindingLabelBottomBorder;
    }
    if (this.f.keybindingLabelShadow) {
      keyElement.style.boxShadow = `inset 0 -1px 0 ${this.f.keybindingLabelShadow}`;
    }
    return keyElement;
  }
  static C(a, b) {
    if (a === b || !a && !b) {
      return true;
    }
    return !!a && !!b && $Pv(a.firstPart, b.firstPart) && $Pv(a.chordPart, b.chordPart);
  }
};

// out-build/vs/platform/actionWidget/browser/actionList.js
var $aab = "acceptSelectedCodeAction";
var $bab = "previewSelectedCodeAction";
var ActionListItemKind;
(function(ActionListItemKind2) {
  ActionListItemKind2["Action"] = "action";
  ActionListItemKind2["Header"] = "header";
})(ActionListItemKind || (ActionListItemKind = {}));
var HeaderRenderer = class {
  get templateId() {
    return "header";
  }
  renderTemplate(container2) {
    container2.classList.add("group-header");
    const text2 = document.createElement("span");
    container2.append(text2);
    return { container: container2, text: text2 };
  }
  renderElement(element, _index, templateData) {
    templateData.text.textContent = element.group?.title ?? "";
  }
  disposeTemplate(_templateData) {
  }
};
var ActionItemRenderer = class ActionItemRenderer2 {
  get templateId() {
    return "action";
  }
  constructor(a, b) {
    this.a = a;
    this.b = b;
  }
  renderTemplate(container2) {
    container2.classList.add(this.templateId);
    const icon2 = document.createElement("div");
    icon2.className = "icon";
    container2.append(icon2);
    const text2 = document.createElement("span");
    text2.className = "title";
    container2.append(text2);
    const keybinding = new $32(container2, OS);
    return { container: container2, icon: icon2, text: text2, keybinding };
  }
  renderElement(element, _index, data) {
    if (element.group?.icon) {
      data.icon.className = ThemeIcon.asClassName(element.group.icon);
      if (element.group.icon.color) {
        data.icon.style.color = $Zn(element.group.icon.color.id);
      }
    } else {
      data.icon.className = ThemeIcon.asClassName($6l.lightBulb);
      data.icon.style.color = "var(--vscode-editorLightBulb-foreground)";
    }
    if (!element.item || !element.label) {
      return;
    }
    $gk(!element.hideIcon, data.icon);
    data.text.textContent = stripNewlines(element.label);
    data.keybinding.set(element.keybinding);
    $gk(!!element.keybinding, data.keybinding.element);
    const actionTitle = this.b.lookupKeybinding($aab)?.getLabel();
    const previewTitle = this.b.lookupKeybinding($bab)?.getLabel();
    data.container.classList.toggle("option-disabled", element.disabled);
    if (element.disabled) {
      data.container.title = element.label;
    } else if (actionTitle && previewTitle) {
      if (this.a && element.canPreview) {
        data.container.title = localize(1682, null, actionTitle, previewTitle);
      } else {
        data.container.title = localize(1683, null, actionTitle);
      }
    } else {
      data.container.title = "";
    }
  }
  disposeTemplate(templateData) {
    templateData.keybinding.dispose();
  }
};
ActionItemRenderer = __decorate([
  __param(1, $Ty)
], ActionItemRenderer);
var AcceptSelectedEvent = class extends UIEvent {
  constructor() {
    super("acceptSelectedAction");
  }
};
var PreviewSelectedEvent = class extends UIEvent {
  constructor() {
    super("previewSelectedAction");
  }
};
function getKeyboardNavigationLabel(item) {
  if (item.kind === "action") {
    return item.label;
  }
  return void 0;
}
var $cab = class $cab2 extends $3c {
  constructor(user, preview, items, h3, j, m) {
    super();
    this.h = h3;
    this.j = j;
    this.m = m;
    this.b = 24;
    this.c = 26;
    this.g = this.B(new $ad());
    this.domNode = document.createElement("div");
    this.domNode.classList.add("actionList");
    const virtualDelegate = {
      getHeight: (element) => element.kind === "header" ? this.c : this.b,
      getTemplateId: (element) => element.kind
    };
    this.a = this.B(new $A1(user, this.domNode, virtualDelegate, [
      new ActionItemRenderer(preview, this.m),
      new HeaderRenderer()
    ], {
      keyboardSupport: false,
      typeNavigationEnabled: true,
      keyboardNavigationLabelProvider: { getKeyboardNavigationLabel },
      accessibilityProvider: {
        getAriaLabel: (element) => {
          if (element.kind === "action") {
            let label3 = element.label ? stripNewlines(element?.label) : "";
            if (element.disabled) {
              label3 = localize(1684, null, label3, element.disabled);
            }
            return label3;
          }
          return null;
        },
        getWidgetAriaLabel: () => localize(1685, null),
        getRole: (e) => e.kind === "action" ? "option" : "separator",
        getWidgetRole: () => "listbox"
      }
    }));
    this.a.style($I$);
    this.B(this.a.onMouseClick((e) => this.u(e)));
    this.B(this.a.onMouseOver((e) => this.t(e)));
    this.B(this.a.onDidChangeFocus(() => this.s()));
    this.B(this.a.onDidChangeSelection((e) => this.r(e)));
    this.f = items;
    this.a.splice(0, this.a.length, this.f);
    if (this.a.length) {
      this.focusNext();
    }
  }
  n(element) {
    return !element.disabled && element.kind === "action";
  }
  hide(didCancel) {
    this.h.onHide(didCancel);
    this.g.cancel();
    this.j.hideContextView();
  }
  layout(minWidth) {
    const numHeaders = this.f.filter((item) => item.kind === "header").length;
    const itemsHeight = this.f.length * this.b;
    const heightWithHeaders = itemsHeight + numHeaders * this.c - numHeaders * this.b;
    this.a.layout(heightWithHeaders);
    let maxWidth = minWidth;
    if (this.f.length >= 50) {
      maxWidth = 380;
    } else {
      const itemWidths = this.f.map((_, index) => {
        const element = this.domNode.ownerDocument.getElementById(this.a.getElementID(index));
        if (element) {
          element.style.width = "auto";
          const width2 = element.getBoundingClientRect().width;
          element.style.width = "";
          return width2;
        }
        return 0;
      });
      maxWidth = Math.max(...itemWidths, minWidth);
    }
    const maxVhPrecentage = 0.7;
    const height = Math.min(heightWithHeaders, this.domNode.ownerDocument.body.clientHeight * maxVhPrecentage);
    this.a.layout(height, maxWidth);
    this.domNode.style.height = `${height}px`;
    this.a.domFocus();
    return maxWidth;
  }
  focusPrevious() {
    this.a.focusPrevious(1, true, void 0, this.n);
  }
  focusNext() {
    this.a.focusNext(1, true, void 0, this.n);
  }
  acceptSelected(preview) {
    const focused = this.a.getFocus();
    if (focused.length === 0) {
      return;
    }
    const focusIndex = focused[0];
    const element = this.a.element(focusIndex);
    if (!this.n(element)) {
      return;
    }
    const event = preview ? new PreviewSelectedEvent() : new AcceptSelectedEvent();
    this.a.setSelection([focusIndex], event);
  }
  r(e) {
    if (!e.elements.length) {
      return;
    }
    const element = e.elements[0];
    if (element.item && this.n(element)) {
      this.h.onSelect(element.item, e.browserEvent instanceof PreviewSelectedEvent);
    } else {
      this.a.setSelection([]);
    }
  }
  s() {
    const focused = this.a.getFocus();
    if (focused.length === 0) {
      return;
    }
    const focusIndex = focused[0];
    const element = this.a.element(focusIndex);
    this.h.onFocus?.(element.item);
  }
  async t(e) {
    const element = e.element;
    if (element && element.item && this.n(element)) {
      if (this.h.onHover && !element.disabled && element.kind === "action") {
        const result = await this.h.onHover(element.item, this.g.token);
        element.canPreview = result ? result.canPreview : void 0;
      }
      if (e.index) {
        this.a.splice(e.index, 1, [element]);
      }
    }
    this.a.setFocus(typeof e.index === "number" ? [e.index] : []);
  }
  u(e) {
    if (e.element && this.n(e.element)) {
      this.a.setFocus([]);
    }
  }
};
$cab = __decorate([
  __param(4, $40),
  __param(5, $Ty)
], $cab);
function stripNewlines(str) {
  return str.replace(/\r\n|\r|\n/g, " ");
}

// out-build/vs/platform/actionWidget/browser/actionWidget.js
$5n("actionBar.toggledBackground", $Cq, localize(1686, null));
var ActionWidgetContextKeys = {
  Visible: new $nn("codeActionMenuVisible", false, localize(1687, null))
};
var $dab = $Qk("actionWidgetService");
var ActionWidgetService = class ActionWidgetService2 extends $3c {
  get isVisible() {
    return ActionWidgetContextKeys.Visible.getValue(this.c) || false;
  }
  constructor(b, c, f) {
    super();
    this.b = b;
    this.c = c;
    this.f = f;
    this.a = this.B(new $4c());
  }
  show(user, supportsPreview, items, delegate, anchor, container2, actionBarActions) {
    const visibleContext = ActionWidgetContextKeys.Visible.bindTo(this.c);
    const list2 = this.f.createInstance($cab, user, supportsPreview, items, delegate);
    this.b.showContextView({
      getAnchor: () => anchor,
      render: (container3) => {
        visibleContext.set(true);
        return this.g(container3, list2, actionBarActions ?? []);
      },
      onHide: (didCancel) => {
        visibleContext.reset();
        this.j(didCancel);
      }
    }, container2, false);
  }
  acceptSelected(preview) {
    this.a.value?.acceptSelected(preview);
  }
  focusPrevious() {
    this.a?.value?.focusPrevious();
  }
  focusNext() {
    this.a?.value?.focusNext();
  }
  hide(didCancel) {
    this.a.value?.hide(didCancel);
    this.a.clear();
  }
  clear() {
    this.a.clear();
  }
  g(element, list2, actionBarActions) {
    const widget = document.createElement("div");
    widget.classList.add("action-widget");
    element.appendChild(widget);
    this.a.value = list2;
    if (this.a.value) {
      widget.appendChild(this.a.value.domNode);
    } else {
      throw new Error("List has no value");
    }
    const renderDisposables = new $2c();
    const menuBlock = document.createElement("div");
    const block2 = element.appendChild(menuBlock);
    block2.classList.add("context-view-block");
    renderDisposables.add($_i(block2, $7j.MOUSE_DOWN, (e) => e.stopPropagation()));
    const pointerBlockDiv = document.createElement("div");
    const pointerBlock = element.appendChild(pointerBlockDiv);
    pointerBlock.classList.add("context-view-pointerBlock");
    renderDisposables.add($_i(pointerBlock, $7j.POINTER_MOVE, () => pointerBlock.remove()));
    renderDisposables.add($_i(pointerBlock, $7j.MOUSE_DOWN, () => pointerBlock.remove()));
    let actionBarWidth = 0;
    if (actionBarActions.length) {
      const actionBar = this.h(".action-widget-action-bar", actionBarActions);
      if (actionBar) {
        widget.appendChild(actionBar.getContainer().parentElement);
        renderDisposables.add(actionBar);
        actionBarWidth = actionBar.getContainer().offsetWidth;
      }
    }
    const width2 = this.a.value?.layout(actionBarWidth);
    widget.style.width = `${width2}px`;
    const focusTracker = renderDisposables.add($_j(element));
    renderDisposables.add(focusTracker.onDidBlur(() => this.hide(true)));
    return renderDisposables;
  }
  h(className, actions) {
    if (!actions.length) {
      return void 0;
    }
    const container2 = $(className);
    const actionBar = new $LZ(container2);
    actionBar.push(actions, { icon: false, label: true });
    return actionBar;
  }
  j(didCancel) {
    this.a.value?.hide(didCancel);
  }
};
ActionWidgetService = __decorate([
  __param(0, $40),
  __param(1, $on),
  __param(2, $Pk)
], ActionWidgetService);
$SC(
  $dab,
  ActionWidgetService,
  1
  /* InstantiationType.Delayed */
);
var weight = 100 + 1e3;
$hJ(class extends $gJ {
  constructor() {
    super({
      id: "hideCodeActionWidget",
      title: localize2(1688, "Hide action widget"),
      precondition: ActionWidgetContextKeys.Visible,
      keybinding: {
        weight,
        primary: 9,
        secondary: [
          1024 | 9
          /* KeyCode.Escape */
        ]
      }
    });
  }
  run(accessor) {
    accessor.get($dab).hide(true);
  }
});
$hJ(class extends $gJ {
  constructor() {
    super({
      id: "selectPrevCodeAction",
      title: localize2(1689, "Select previous action"),
      precondition: ActionWidgetContextKeys.Visible,
      keybinding: {
        weight,
        primary: 16,
        secondary: [
          2048 | 16
          /* KeyCode.UpArrow */
        ],
        mac: { primary: 16, secondary: [
          2048 | 16,
          256 | 46
          /* KeyCode.KeyP */
        ] }
      }
    });
  }
  run(accessor) {
    const widgetService = accessor.get($dab);
    if (widgetService instanceof ActionWidgetService) {
      widgetService.focusPrevious();
    }
  }
});
$hJ(class extends $gJ {
  constructor() {
    super({
      id: "selectNextCodeAction",
      title: localize2(1690, "Select next action"),
      precondition: ActionWidgetContextKeys.Visible,
      keybinding: {
        weight,
        primary: 18,
        secondary: [
          2048 | 18
          /* KeyCode.DownArrow */
        ],
        mac: { primary: 18, secondary: [
          2048 | 18,
          256 | 44
          /* KeyCode.KeyN */
        ] }
      }
    });
  }
  run(accessor) {
    const widgetService = accessor.get($dab);
    if (widgetService instanceof ActionWidgetService) {
      widgetService.focusNext();
    }
  }
});
$hJ(class extends $gJ {
  constructor() {
    super({
      id: $aab,
      title: localize2(1691, "Accept selected action"),
      precondition: ActionWidgetContextKeys.Visible,
      keybinding: {
        weight,
        primary: 3,
        secondary: [
          2048 | 89
          /* KeyCode.Period */
        ]
      }
    });
  }
  run(accessor) {
    const widgetService = accessor.get($dab);
    if (widgetService instanceof ActionWidgetService) {
      widgetService.acceptSelected();
    }
  }
});
$hJ(class extends $gJ {
  constructor() {
    super({
      id: $bab,
      title: localize2(1692, "Preview selected action"),
      precondition: ActionWidgetContextKeys.Visible,
      keybinding: {
        weight,
        primary: 2048 | 3
      }
    });
  }
  run(accessor) {
    const widgetService = accessor.get($dab);
    if (widgetService instanceof ActionWidgetService) {
      widgetService.acceptSelected(true);
    }
  }
});

// out-build/vs/editor/contrib/dropOrPasteInto/browser/postEditWidget.js
var PostEditWidget_1;
var PostEditWidget = class PostEditWidget2 extends $3c {
  static {
    PostEditWidget_1 = this;
  }
  static {
    this.a = "editor.widget.postEditWidget";
  }
  constructor(g, h3, visibleContext, j, m, n, r2, s, contextKeyService, t, u) {
    super();
    this.g = g;
    this.h = h3;
    this.j = j;
    this.m = m;
    this.n = n;
    this.r = r2;
    this.s = s;
    this.t = t;
    this.u = u;
    this.allowEditorOverflow = true;
    this.suppressMouseDown = true;
    this.z();
    this.f = visibleContext.bindTo(contextKeyService);
    this.f.set(true);
    this.B($1c(() => this.f.reset()));
    this.h.addContentWidget(this);
    this.h.layoutContentWidget(this);
    this.B($1c(() => this.h.removeContentWidget(this)));
    this.B(this.h.onDidChangeCursorPosition((e) => {
      this.dispose();
    }));
    this.B(Event2.runAndSubscribe(t.onDidUpdateKeybindings, () => {
      this.w();
    }));
  }
  w() {
    const binding = this.t.lookupKeybinding(this.j.id)?.getLabel();
    this.c.element.title = this.j.label + (binding ? ` (${binding})` : "");
  }
  z() {
    this.b = $(".post-edit-widget");
    this.c = this.B(new $k2(this.b, {
      supportIcons: true
    }));
    this.c.label = "$(insert)";
    this.B($_i(this.b, $7j.CLICK, () => this.showSelector()));
  }
  getId() {
    return PostEditWidget_1.a + "." + this.g;
  }
  getDomNode() {
    return this.b;
  }
  getPosition() {
    return {
      position: this.m.getEndPosition(),
      preference: [
        2
        /* ContentWidgetPositionPreference.BELOW */
      ]
    };
  }
  showSelector() {
    const pos = $vj(this.c.element);
    const anchor = { x: pos.left + pos.width, y: pos.top + pos.height };
    this.u.show("postEditWidget", false, this.n.allEdits.map((edit3, i2) => {
      return {
        kind: "action",
        item: edit3,
        label: edit3.title,
        disabled: false,
        canPreview: false,
        group: { title: "", icon: ThemeIcon.fromId(i2 === this.n.activeEditIndex ? $6l.check.id : $6l.blank.id) }
      };
    }), {
      onHide: () => {
        this.h.focus();
      },
      onSelect: (item) => {
        this.u.hide(false);
        const i2 = this.n.allEdits.findIndex((edit3) => edit3 === item);
        if (i2 !== this.n.activeEditIndex) {
          return this.r(i2);
        }
      }
    }, anchor, this.h.getDomNode() ?? void 0, this.s);
  }
};
PostEditWidget = PostEditWidget_1 = __decorate([
  __param(8, $on),
  __param(9, $Ty),
  __param(10, $dab)
], PostEditWidget);
var $eab = class $eab2 extends $3c {
  constructor(b, c, f, g, h3, j, m, n) {
    super();
    this.b = b;
    this.c = c;
    this.f = f;
    this.g = g;
    this.h = h3;
    this.j = j;
    this.m = m;
    this.n = n;
    this.a = this.B(new $4c());
    this.B(Event2.any(c.onDidChangeModel, c.onDidChangeModelContent)(() => this.clear()));
  }
  async applyEditAndShowIfNeeded(ranges, edits, canShowWidget, resolve, token) {
    const model = this.c.getModel();
    if (!model || !ranges.length) {
      return;
    }
    const edit3 = edits.allEdits.at(edits.activeEditIndex);
    if (!edit3) {
      return;
    }
    const onDidSelectEdit = async (newEditIndex) => {
      const model2 = this.c.getModel();
      if (!model2) {
        return;
      }
      await model2.undo();
      this.applyEditAndShowIfNeeded(ranges, { activeEditIndex: newEditIndex, allEdits: edits.allEdits }, canShowWidget, resolve, token);
    };
    const handleError = (e, message) => {
      if ($kb(e)) {
        return;
      }
      this.n.error(message);
      if (canShowWidget) {
        this.show(ranges[0], edits, onDidSelectEdit);
      }
    };
    let resolvedEdit;
    try {
      resolvedEdit = await resolve(edit3, token);
    } catch (e) {
      return handleError(e, localize(1012, null, edit3.title, $1m(e)));
    }
    if (token.isCancellationRequested) {
      return;
    }
    const combinedWorkspaceEdit = $$_(model.uri, ranges, resolvedEdit);
    const primaryRange = ranges[0];
    const editTrackingDecoration = model.deltaDecorations([], [{
      range: primaryRange,
      options: {
        description: "paste-line-suffix",
        stickiness: 0
        /* TrackedRangeStickiness.AlwaysGrowsWhenTypingAtEdges */
      }
    }]);
    this.c.focus();
    let editResult;
    let editRange;
    try {
      editResult = await this.m.apply(combinedWorkspaceEdit, { editor: this.c, token });
      editRange = model.getDecorationRange(editTrackingDecoration[0]);
    } catch (e) {
      return handleError(e, localize(1013, null, edit3.title, $1m(e)));
    } finally {
      model.deltaDecorations(editTrackingDecoration, []);
    }
    if (token.isCancellationRequested) {
      return;
    }
    if (canShowWidget && editResult.isApplied && edits.allEdits.length > 1) {
      this.show(editRange ?? primaryRange, edits, onDidSelectEdit);
    }
  }
  show(range, edits, onDidSelectEdit) {
    this.clear();
    if (this.c.hasModel()) {
      this.a.value = this.j.createInstance(PostEditWidget, this.b, this.c, this.f, this.g, range, edits, onDidSelectEdit, this.h());
    }
  }
  clear() {
    this.a.clear();
  }
  tryShowSelector() {
    this.a.value?.showSelector();
  }
};
$eab = __decorate([
  __param(5, $Pk),
  __param(6, $H_),
  __param(7, $PJ)
], $eab);

// out-build/vs/editor/contrib/dropOrPasteInto/browser/copyPasteController.js
var $iab_1;
var $fab = "editor.changePasteType";
var $gab = "editor.pasteAs.preferences";
var $hab = new $nn("pasteWidgetVisible", false, localize(992, null));
var vscodeClipboardMime = "application/vnd.code.copymetadata";
var $iab = class $iab2 extends $3c {
  static {
    $iab_1 = this;
  }
  static {
    this.ID = "editor.contrib.copyPasteActionController";
  }
  static get(editor) {
    return editor.getContribution($iab_1.ID);
  }
  static setConfigureDefaultAction(action) {
    $iab_1.a = action;
  }
  constructor(editor, instantiationService, m, n, r2, s, t, u, w) {
    super();
    this.m = m;
    this.n = n;
    this.r = r2;
    this.s = s;
    this.t = t;
    this.u = u;
    this.w = w;
    this.c = editor;
    const container2 = editor.getContainerDomNode();
    this.B($_i(container2, "copy", (e) => this.z(e)));
    this.B($_i(container2, "cut", (e) => this.z(e)));
    this.B($_i(container2, "paste", (e) => this.C(e), true));
    this.h = this.B(new $P_("pasteIntoEditor", editor, instantiationService));
    this.j = this.B(instantiationService.createInstance($eab, "pasteIntoEditor", editor, $hab, { id: $fab, label: localize(993, null) }, () => $iab_1.a ? [$iab_1.a] : []));
  }
  changePasteType() {
    this.j.tryShowSelector();
  }
  pasteAs(preferred) {
    this.c.focus();
    try {
      this.g = { preferred };
      this.r.executeCommand("editor.action.clipboardPasteAction");
    } finally {
      this.g = void 0;
    }
  }
  clearWidgets() {
    this.j.clear();
  }
  y() {
    return this.c.getOption(
      89
      /* EditorOption.pasteAs */
    ).enabled;
  }
  async finishedPaste() {
    await this.f;
  }
  z(e) {
    if (!this.c.hasTextFocus()) {
      return;
    }
    this.n.clearInternalState?.();
    if (!e.clipboardData || !this.y()) {
      return;
    }
    const model = this.c.getModel();
    const selections = this.c.getSelections();
    if (!model || !selections?.length) {
      return;
    }
    const enableEmptySelectionClipboard = this.c.getOption(
      38
      /* EditorOption.emptySelectionClipboard */
    );
    let ranges = selections;
    const wasFromEmptySelection = selections.length === 1 && selections[0].isEmpty();
    if (wasFromEmptySelection) {
      if (!enableEmptySelectionClipboard) {
        return;
      }
      ranges = [new $9C(ranges[0].startLineNumber, 1, ranges[0].startLineNumber, 1 + model.getLineLength(ranges[0].startLineNumber))];
    }
    const toCopy = this.c._getViewModel()?.getPlainTextToCopy(selections, enableEmptySelectionClipboard, $l);
    const multicursorText = Array.isArray(toCopy) ? toCopy : null;
    const defaultPastePayload = {
      multicursorText,
      pasteOnNewLine: wasFromEmptySelection,
      mode: null
    };
    const providers2 = this.t.documentPasteEditProvider.ordered(model).filter((x) => !!x.prepareDocumentPaste);
    if (!providers2.length) {
      this.H(e.clipboardData, { defaultPastePayload });
      return;
    }
    const dataTransfer = $F_(e.clipboardData);
    const providerCopyMimeTypes = providers2.flatMap((x) => x.copyMimeTypes ?? []);
    const handle2 = $ps();
    this.H(e.clipboardData, {
      id: handle2,
      providerCopyMimeTypes,
      defaultPastePayload
    });
    const promise = $Hh(async (token) => {
      const results = $Mb(await Promise.all(providers2.map(async (provider) => {
        try {
          return await provider.prepareDocumentPaste(model, ranges, dataTransfer, token);
        } catch (err) {
          console.error(err);
          return void 0;
        }
      })));
      results.reverse();
      for (const result of results) {
        for (const [mime, value] of result) {
          dataTransfer.replace(mime, value);
        }
      }
      return dataTransfer;
    });
    $iab_1.b?.dataTransferPromise.cancel();
    $iab_1.b = { handle: handle2, dataTransferPromise: promise };
  }
  async C(e) {
    if (!e.clipboardData || !this.c.hasTextFocus()) {
      return;
    }
    $S_.get(this.c)?.closeMessage();
    this.f?.cancel();
    this.f = void 0;
    const model = this.c.getModel();
    const selections = this.c.getSelections();
    if (!selections?.length || !model) {
      return;
    }
    if (this.c.getOption(
      96
      /* EditorOption.readOnly */
    ) || !this.y() && !this.g) {
      return;
    }
    const metadata = this.I(e);
    const dataTransfer = $G_(e.clipboardData);
    dataTransfer.delete(vscodeClipboardMime);
    const fileTypes = Array.from(e.clipboardData.files).map((file) => file.type);
    const allPotentialMimeTypes = [
      ...e.clipboardData.types,
      ...fileTypes,
      ...metadata?.providerCopyMimeTypes ?? [],
      // TODO: always adds `uri-list` because this get set if there are resources in the system clipboard.
      // However we can only check the system clipboard async. For this early check, just add it in.
      // We filter providers again once we have the final dataTransfer we will use.
      $YC.uriList
    ];
    const allProviders = this.t.documentPasteEditProvider.ordered(model).filter((provider) => {
      const preference = this.g?.preferred;
      if (preference) {
        if (!this.O(provider, preference)) {
          return false;
        }
      }
      return provider.pasteMimeTypes?.some((type) => $mE(type, allPotentialMimeTypes));
    });
    if (!allProviders.length) {
      if (this.g?.preferred) {
        this.D(selections, this.g.preferred);
        e.preventDefault();
        e.stopImmediatePropagation();
      }
      return;
    }
    e.preventDefault();
    e.stopImmediatePropagation();
    if (this.g) {
      this.G(this.g.preferred, allProviders, selections, dataTransfer, metadata);
    } else {
      this.F(allProviders, selections, dataTransfer, metadata, e);
    }
  }
  D(selections, preference) {
    const kindLabel = "only" in preference ? preference.only.value : "preferences" in preference ? preference.preferences.length ? preference.preferences.map((preference2) => preference2.value).join(", ") : localize(994, null) : preference.providerId;
    $S_.get(this.c)?.showMessage(localize(995, null, kindLabel), selections[0].getStartPosition());
  }
  F(allProviders, selections, dataTransfer, metadata, clipboardEvent) {
    const editor = this.c;
    if (!editor.hasModel()) {
      return;
    }
    const editorStateCts = new $N_(editor, 1 | 2, void 0);
    const p = $Hh(async (pToken) => {
      const editor2 = this.c;
      if (!editor2.hasModel()) {
        return;
      }
      const model = editor2.getModel();
      const disposables = new $2c();
      const cts = disposables.add(new $ad(pToken));
      disposables.add(editorStateCts.token.onCancellationRequested(() => cts.cancel()));
      const token = cts.token;
      try {
        await this.J(dataTransfer, metadata, token);
        if (token.isCancellationRequested) {
          return;
        }
        const supportedProviders = allProviders.filter((provider) => this.N(provider, dataTransfer));
        if (!supportedProviders.length || supportedProviders.length === 1 && supportedProviders[0] instanceof $V_) {
          return this.M(dataTransfer, metadata, token, clipboardEvent);
        }
        const context = {
          triggerKind: DocumentPasteTriggerKind.Automatic
        };
        const editSession = await this.L(supportedProviders, dataTransfer, model, selections, context, token);
        disposables.add(editSession);
        if (token.isCancellationRequested) {
          return;
        }
        if (editSession.edits.length === 1 && editSession.edits[0].provider instanceof $V_) {
          return this.M(dataTransfer, metadata, token, clipboardEvent);
        }
        if (editSession.edits.length) {
          const canShowWidget = editor2.getOption(
            89
            /* EditorOption.pasteAs */
          ).showPasteSelector === "afterPaste";
          return this.j.applyEditAndShowIfNeeded(selections, { activeEditIndex: this.P(model, editSession.edits), allEdits: editSession.edits }, canShowWidget, (edit3, token2) => {
            return new Promise((resolve, reject) => {
              (async () => {
                try {
                  const resolveP = edit3.provider.resolveDocumentPasteEdit?.(edit3, token2);
                  const showP = new $gi();
                  const resolved = resolveP && await this.h.showWhile(selections[0].getEndPosition(), localize(996, null), Promise.race([showP.p, resolveP]), {
                    cancel: () => {
                      showP.cancel();
                      return reject(new $lb());
                    }
                  }, 0);
                  if (resolved) {
                    edit3.additionalEdit = resolved.additionalEdit;
                  }
                  return resolve(edit3);
                } catch (err) {
                  return reject(err);
                }
              })();
            });
          }, token);
        }
        await this.M(dataTransfer, metadata, token, clipboardEvent);
      } finally {
        disposables.dispose();
        if (this.f === p) {
          this.f = void 0;
        }
      }
    });
    this.h.showWhile(selections[0].getEndPosition(), localize(997, null), p, {
      cancel: async () => {
        try {
          p.cancel();
          if (editorStateCts.token.isCancellationRequested) {
            return;
          }
          await this.M(dataTransfer, metadata, editorStateCts.token, clipboardEvent);
        } finally {
          editorStateCts.dispose();
        }
      }
    }).then(() => {
      editorStateCts.dispose();
    });
    this.f = p;
  }
  G(preference, allProviders, selections, dataTransfer, metadata) {
    const p = $Hh(async (token) => {
      const editor = this.c;
      if (!editor.hasModel()) {
        return;
      }
      const model = editor.getModel();
      const disposables = new $2c();
      const tokenSource = disposables.add(new $N_(editor, 1 | 2, void 0, token));
      try {
        await this.J(dataTransfer, metadata, tokenSource.token);
        if (tokenSource.token.isCancellationRequested) {
          return;
        }
        let supportedProviders = allProviders.filter((provider) => this.N(provider, dataTransfer, preference));
        if (preference) {
          supportedProviders = supportedProviders.filter((provider) => this.O(provider, preference));
        }
        const context = {
          triggerKind: DocumentPasteTriggerKind.PasteAs,
          only: preference && "only" in preference ? preference.only : void 0
        };
        let editSession = disposables.add(await this.L(supportedProviders, dataTransfer, model, selections, context, tokenSource.token));
        if (tokenSource.token.isCancellationRequested) {
          return;
        }
        if (preference) {
          editSession = {
            edits: editSession.edits.filter((edit3) => {
              if ("only" in preference) {
                return preference.only.contains(edit3.kind);
              } else if ("preferences" in preference) {
                return preference.preferences.some((preference2) => preference2.contains(edit3.kind));
              } else {
                return preference.providerId === edit3.provider.id;
              }
            }),
            dispose: editSession.dispose
          };
        }
        if (!editSession.edits.length) {
          if (preference) {
            this.D(selections, preference);
          }
          return;
        }
        let pickedEdit;
        if (preference) {
          pickedEdit = editSession.edits.at(0);
        } else {
          const configureDefaultItem = {
            id: "editor.pasteAs.default",
            label: localize(998, null),
            edit: void 0
          };
          const selected = await this.u.pick([
            ...editSession.edits.map((edit3) => ({
              label: edit3.title,
              description: edit3.kind?.value,
              edit: edit3
            })),
            ...$iab_1.a ? [
              $Rg({ type: "separator" }),
              {
                label: $iab_1.a.label,
                edit: void 0
              }
            ] : []
          ], {
            placeHolder: localize(999, null)
          });
          if (selected === configureDefaultItem) {
            $iab_1.a?.run();
            return;
          }
          pickedEdit = selected?.edit;
        }
        if (!pickedEdit) {
          return;
        }
        const combinedWorkspaceEdit = $$_(model.uri, selections, pickedEdit);
        await this.m.apply(combinedWorkspaceEdit, { editor: this.c });
      } finally {
        disposables.dispose();
        if (this.f === p) {
          this.f = void 0;
        }
      }
    });
    this.w.withProgress({
      location: 10,
      title: localize(1e3, null)
    }, () => p);
  }
  H(dataTransfer, metadata) {
    dataTransfer.setData(vscodeClipboardMime, JSON.stringify(metadata));
  }
  I(e) {
    if (!e.clipboardData) {
      return;
    }
    const rawMetadata = e.clipboardData.getData(vscodeClipboardMime);
    if (rawMetadata) {
      try {
        return JSON.parse(rawMetadata);
      } catch {
        return void 0;
      }
    }
    const [_, metadata] = $67.getTextData(e.clipboardData);
    if (metadata) {
      return {
        defaultPastePayload: {
          mode: metadata.mode,
          multicursorText: metadata.multicursorText ?? null,
          pasteOnNewLine: !!metadata.isFromEmptySelection
        }
      };
    }
    return void 0;
  }
  async J(dataTransfer, metadata, token) {
    if (metadata?.id && $iab_1.b?.handle === metadata.id) {
      const toMergeDataTransfer = await $iab_1.b.dataTransferPromise;
      if (token.isCancellationRequested) {
        return;
      }
      for (const [key2, value] of toMergeDataTransfer) {
        dataTransfer.replace(key2, value);
      }
    }
    if (!dataTransfer.has($YC.uriList)) {
      const resources = await this.n.readResources();
      if (token.isCancellationRequested) {
        return;
      }
      if (resources.length) {
        dataTransfer.append($YC.uriList, $jE($nE.create(resources)));
      }
    }
  }
  async L(providers2, dataTransfer, model, selections, context, token) {
    const disposables = new $2c();
    const results = await $Ih(Promise.all(providers2.map(async (provider) => {
      try {
        const edits2 = await provider.provideDocumentPasteEdits?.(model, selections, dataTransfer, context, token);
        if (edits2) {
          disposables.add(edits2);
        }
        return edits2?.edits?.map((edit3) => ({ ...edit3, provider }));
      } catch (err) {
        if (!$kb(err)) {
          console.error(err);
        }
        return void 0;
      }
    })), token);
    const edits = $Mb(results ?? []).flat().filter((edit3) => {
      return !context.only || context.only.contains(edit3.kind);
    });
    return {
      edits: $__(edits),
      dispose: () => disposables.dispose()
    };
  }
  async M(dataTransfer, metadata, token, clipboardEvent) {
    const textDataTransfer = dataTransfer.get($YC.text) ?? dataTransfer.get("text");
    const text2 = await textDataTransfer?.asString() ?? "";
    if (token.isCancellationRequested) {
      return;
    }
    const payload = {
      clipboardEvent,
      text: text2,
      pasteOnNewLine: metadata?.defaultPastePayload.pasteOnNewLine ?? false,
      multicursorText: metadata?.defaultPastePayload.multicursorText ?? null,
      mode: null
    };
    this.c.trigger("keyboard", "paste", payload);
  }
  /**
   * Filter out providers if they:
   * - Don't handle any of the data transfer types we have
   * - Don't match the preferred paste kind
   */
  N(provider, dataTransfer, preference) {
    if (!provider.pasteMimeTypes?.some((type) => dataTransfer.matches(type))) {
      return false;
    }
    return !preference || this.O(provider, preference);
  }
  O(provider, preference) {
    if ("only" in preference) {
      return provider.providedPasteEditKinds.some((providedKind) => preference.only.contains(providedKind));
    } else if ("preferences" in preference) {
      return preference.preferences.some((providedKind) => preference.preferences.some((preferredKind) => preferredKind.contains(providedKind)));
    } else {
      return provider.id === preference.providerId;
    }
  }
  P(model, edits) {
    const preferredProviders = this.s.getValue($gab, { resource: model.uri });
    for (const config of Array.isArray(preferredProviders) ? preferredProviders : []) {
      const desiredKind = new $oE(config);
      const editIndex = edits.findIndex((edit3) => desiredKind.contains(edit3.kind));
      if (editIndex >= 0) {
        return editIndex;
      }
    }
    return 0;
  }
};
$iab = $iab_1 = __decorate([
  __param(1, $Pk),
  __param(2, $H_),
  __param(3, $30),
  __param(4, $sn),
  __param(5, $kl),
  __param(6, $mP),
  __param(7, $1M),
  __param(8, $TJ)
], $iab);

// out-build/vs/editor/contrib/clipboard/browser/clipboard.js
var CLIPBOARD_CONTEXT_MENU_GROUP = "9_cutcopypaste";
var supportsCut = $p || document.queryCommandSupported("cut");
var supportsCopy = $p || document.queryCommandSupported("copy");
var supportsPaste = typeof navigator.clipboard === "undefined" || $Ue ? document.queryCommandSupported("paste") : true;
function registerCommand3(command4) {
  command4.register();
  return command4;
}
var $jab = supportsCut ? registerCommand3(new $W5({
  id: "editor.action.clipboardCutAction",
  precondition: void 0,
  kbOpts: (
    // Do not bind cut keybindings in the browser,
    // since browsers do that for us and it avoids security prompts
    $p ? {
      primary: 2048 | 54,
      win: { primary: 2048 | 54, secondary: [
        1024 | 20
        /* KeyCode.Delete */
      ] },
      weight: 100
      /* KeybindingWeight.EditorContrib */
    } : void 0
  ),
  menuOpts: [{
    menuId: $bJ.MenubarEditMenu,
    group: "2_ccp",
    title: localize(888, null),
    order: 1
  }, {
    menuId: $bJ.EditorContext,
    group: CLIPBOARD_CONTEXT_MENU_GROUP,
    title: localize(889, null),
    when: EditorContextKeys.writable,
    order: 1
  }, {
    menuId: $bJ.CommandPalette,
    group: "",
    title: localize(890, null),
    order: 1
  }, {
    menuId: $bJ.SimpleEditorContext,
    group: CLIPBOARD_CONTEXT_MENU_GROUP,
    title: localize(891, null),
    when: EditorContextKeys.writable,
    order: 1
  }]
})) : void 0;
var $kab = supportsCopy ? registerCommand3(new $W5({
  id: "editor.action.clipboardCopyAction",
  precondition: void 0,
  kbOpts: (
    // Do not bind copy keybindings in the browser,
    // since browsers do that for us and it avoids security prompts
    $p ? {
      primary: 2048 | 33,
      win: { primary: 2048 | 33, secondary: [
        2048 | 19
        /* KeyCode.Insert */
      ] },
      weight: 100
      /* KeybindingWeight.EditorContrib */
    } : void 0
  ),
  menuOpts: [{
    menuId: $bJ.MenubarEditMenu,
    group: "2_ccp",
    title: localize(892, null),
    order: 2
  }, {
    menuId: $bJ.EditorContext,
    group: CLIPBOARD_CONTEXT_MENU_GROUP,
    title: localize(893, null),
    order: 2
  }, {
    menuId: $bJ.CommandPalette,
    group: "",
    title: localize(894, null),
    order: 1
  }, {
    menuId: $bJ.SimpleEditorContext,
    group: CLIPBOARD_CONTEXT_MENU_GROUP,
    title: localize(895, null),
    order: 2
  }]
})) : void 0;
$dJ.appendMenuItem($bJ.MenubarEditMenu, { submenu: $bJ.MenubarCopy, title: localize2(900, "Copy As"), group: "2_ccp", order: 3 });
$dJ.appendMenuItem($bJ.EditorContext, { submenu: $bJ.EditorContextCopy, title: localize2(901, "Copy As"), group: CLIPBOARD_CONTEXT_MENU_GROUP, order: 3 });
$dJ.appendMenuItem($bJ.EditorContext, { submenu: $bJ.EditorContextShare, title: localize2(902, "Share"), group: "11_share", order: -1, when: $7m.and($7m.notEquals("resourceScheme", "output"), EditorContextKeys.editorTextFocus) });
$dJ.appendMenuItem($bJ.ExplorerContext, { submenu: $bJ.ExplorerContextShare, title: localize2(903, "Share"), group: "11_share", order: -1 });
var $lab = supportsPaste ? registerCommand3(new $W5({
  id: "editor.action.clipboardPasteAction",
  precondition: void 0,
  kbOpts: (
    // Do not bind paste keybindings in the browser,
    // since browsers do that for us and it avoids security prompts
    $p ? {
      primary: 2048 | 52,
      win: { primary: 2048 | 52, secondary: [
        1024 | 19
        /* KeyCode.Insert */
      ] },
      linux: { primary: 2048 | 52, secondary: [
        1024 | 19
        /* KeyCode.Insert */
      ] },
      weight: 100
      /* KeybindingWeight.EditorContrib */
    } : void 0
  ),
  menuOpts: [{
    menuId: $bJ.MenubarEditMenu,
    group: "2_ccp",
    title: localize(896, null),
    order: 4
  }, {
    menuId: $bJ.EditorContext,
    group: CLIPBOARD_CONTEXT_MENU_GROUP,
    title: localize(897, null),
    when: EditorContextKeys.writable,
    order: 4
  }, {
    menuId: $bJ.CommandPalette,
    group: "",
    title: localize(898, null),
    order: 1
  }, {
    menuId: $bJ.SimpleEditorContext,
    group: CLIPBOARD_CONTEXT_MENU_GROUP,
    title: localize(899, null),
    when: EditorContextKeys.writable,
    order: 4
  }]
})) : void 0;
var ExecCommandCopyWithSyntaxHighlightingAction = class extends $Z5 {
  constructor() {
    super({
      id: "editor.action.clipboardCopyWithSyntaxHighlightingAction",
      label: localize2(904, "Copy With Syntax Highlighting"),
      precondition: void 0,
      kbOpts: {
        kbExpr: EditorContextKeys.textInputFocus,
        primary: 0,
        weight: 100
        /* KeybindingWeight.EditorContrib */
      }
    });
  }
  run(accessor, editor) {
    if (!editor.hasModel()) {
      return;
    }
    const emptySelectionClipboard = editor.getOption(
      38
      /* EditorOption.emptySelectionClipboard */
    );
    if (!emptySelectionClipboard && editor.getSelection().isEmpty()) {
      return;
    }
    $57.forceCopyWithSyntaxHighlighting = true;
    editor.focus();
    editor.getContainerDomNode().ownerDocument.execCommand("copy");
    $57.forceCopyWithSyntaxHighlighting = false;
  }
};
function registerExecCommandImpl(target, browserCommand) {
  if (!target) {
    return;
  }
  target.addImplementation(1e4, "code-editor", (accessor, args2) => {
    const focusedEditor = accessor.get($U5).getFocusedCodeEditor();
    if (focusedEditor && focusedEditor.hasTextFocus()) {
      const emptySelectionClipboard = focusedEditor.getOption(
        38
        /* EditorOption.emptySelectionClipboard */
      );
      const selection = focusedEditor.getSelection();
      if (selection && selection.isEmpty() && !emptySelectionClipboard) {
        return true;
      }
      if (focusedEditor.getOption(
        37
        /* EditorOption.experimentalEditContextEnabled */
      ) && browserCommand === "cut") {
        focusedEditor.getContainerDomNode().ownerDocument.execCommand("copy");
        focusedEditor.trigger(void 0, "cut", void 0);
      } else {
        focusedEditor.getContainerDomNode().ownerDocument.execCommand(browserCommand);
      }
      return true;
    }
    return false;
  });
  target.addImplementation(0, "generic-dom", (accessor, args2) => {
    $Pj().execCommand(browserCommand);
    return true;
  });
}
registerExecCommandImpl($jab, "cut");
registerExecCommandImpl($kab, "copy");
if ($lab) {
  $lab.addImplementation(1e4, "code-editor", (accessor, args2) => {
    const codeEditorService = accessor.get($U5);
    const clipboardService = accessor.get($30);
    const focusedEditor = codeEditorService.getFocusedCodeEditor();
    if (focusedEditor && focusedEditor.hasModel() && focusedEditor.hasTextFocus()) {
      let result;
      const experimentalEditContextEnabled = focusedEditor.getOption(
        37
        /* EditorOption.experimentalEditContextEnabled */
      );
      if (experimentalEditContextEnabled) {
        const nativeEditContext = $W8.get(focusedEditor.getId());
        if (nativeEditContext) {
          const textArea = nativeEditContext.textArea;
          nativeEditContext.onWillPaste();
          textArea.focus();
          result = focusedEditor.getContainerDomNode().ownerDocument.execCommand("paste");
          textArea.domNode.textContent = "";
          nativeEditContext.domNode.focus();
        } else {
          result = false;
        }
      } else {
        result = focusedEditor.getContainerDomNode().ownerDocument.execCommand("paste");
      }
      if (result) {
        return $iab.get(focusedEditor)?.finishedPaste() ?? Promise.resolve();
      } else if ($r) {
        return (async () => {
          const clipboardText = await clipboardService.readText();
          if (clipboardText !== "") {
            const metadata = $47.INSTANCE.get(clipboardText);
            let pasteOnNewLine = false;
            let multicursorText = null;
            let mode = null;
            if (metadata) {
              pasteOnNewLine = focusedEditor.getOption(
                38
                /* EditorOption.emptySelectionClipboard */
              ) && !!metadata.isFromEmptySelection;
              multicursorText = typeof metadata.multicursorText !== "undefined" ? metadata.multicursorText : null;
              mode = metadata.mode;
            }
            focusedEditor.trigger("keyboard", "paste", {
              text: clipboardText,
              pasteOnNewLine,
              multicursorText,
              mode
            });
          }
        })();
      }
      return true;
    }
    return false;
  });
  $lab.addImplementation(0, "generic-dom", (accessor, args2) => {
    $Pj().execCommand("paste");
    return true;
  });
}
if (supportsCopy) {
  $55(ExecCommandCopyWithSyntaxHighlightingAction);
}

// out-build/vs/editor/common/config/editorConfigurationSchema.js
var $mab = Object.freeze({
  id: "editor",
  order: 5,
  type: "object",
  title: localize(258, null),
  scope: 5
});
var editorConfiguration = {
  ...$mab,
  properties: {
    "editor.tabSize": {
      type: "number",
      default: $HD.tabSize,
      minimum: 1,
      markdownDescription: localize(259, null, "`#editor.detectIndentation#`")
    },
    "editor.indentSize": {
      "anyOf": [
        {
          type: "string",
          enum: ["tabSize"]
        },
        {
          type: "number",
          minimum: 1
        }
      ],
      default: "tabSize",
      markdownDescription: localize(260, null)
    },
    "editor.insertSpaces": {
      type: "boolean",
      default: $HD.insertSpaces,
      markdownDescription: localize(261, null, "`#editor.detectIndentation#`")
    },
    "editor.detectIndentation": {
      type: "boolean",
      default: $HD.detectIndentation,
      markdownDescription: localize(262, null, "`#editor.tabSize#`", "`#editor.insertSpaces#`")
    },
    "editor.trimAutoWhitespace": {
      type: "boolean",
      default: $HD.trimAutoWhitespace,
      description: localize(263, null)
    },
    "editor.largeFileOptimizations": {
      type: "boolean",
      default: $HD.largeFileOptimizations,
      description: localize(264, null)
    },
    "editor.wordBasedSuggestions": {
      enum: ["off", "currentDocument", "matchingDocuments", "allDocuments"],
      default: "matchingDocuments",
      enumDescriptions: [
        localize(265, null),
        localize(266, null),
        localize(267, null),
        localize(268, null)
      ],
      description: localize(269, null)
    },
    "editor.semanticHighlighting.enabled": {
      enum: [true, false, "configuredByTheme"],
      enumDescriptions: [
        localize(270, null),
        localize(271, null),
        localize(272, null)
      ],
      default: "configuredByTheme",
      description: localize(273, null)
    },
    "editor.stablePeek": {
      type: "boolean",
      default: false,
      markdownDescription: localize(274, null)
    },
    "editor.maxTokenizationLineLength": {
      type: "integer",
      default: 2e4,
      description: localize(275, null)
    },
    "editor.experimental.asyncTokenization": {
      type: "boolean",
      default: true,
      description: localize(276, null),
      tags: ["experimental"]
    },
    "editor.experimental.asyncTokenizationLogging": {
      type: "boolean",
      default: false,
      description: localize(277, null)
    },
    "editor.experimental.asyncTokenizationVerification": {
      type: "boolean",
      default: false,
      description: localize(278, null),
      tags: ["experimental"]
    },
    "editor.experimental.treeSitterTelemetry": {
      type: "boolean",
      default: false,
      markdownDescription: localize(279, null),
      tags: ["experimental", "onExP"]
    },
    "editor.experimental.preferTreeSitter": {
      type: "array",
      items: {
        type: "string",
        enum: ["typescript"]
      },
      default: [],
      markdownDescription: localize(280, null),
      tags: ["experimental"]
    },
    "editor.language.brackets": {
      type: ["array", "null"],
      default: null,
      // We want to distinguish the empty array from not configured.
      description: localize(281, null),
      items: {
        type: "array",
        items: [
          {
            type: "string",
            description: localize(282, null)
          },
          {
            type: "string",
            description: localize(283, null)
          }
        ]
      }
    },
    "editor.language.colorizedBracketPairs": {
      type: ["array", "null"],
      default: null,
      // We want to distinguish the empty array from not configured.
      description: localize(284, null),
      items: {
        type: "array",
        items: [
          {
            type: "string",
            description: localize(285, null)
          },
          {
            type: "string",
            description: localize(286, null)
          }
        ]
      }
    },
    "diffEditor.maxComputationTime": {
      type: "number",
      default: $M0.maxComputationTime,
      description: localize(287, null)
    },
    "diffEditor.maxFileSize": {
      type: "number",
      default: $M0.maxFileSize,
      description: localize(288, null)
    },
    "diffEditor.renderSideBySide": {
      type: "boolean",
      default: $M0.renderSideBySide,
      description: localize(289, null)
    },
    "diffEditor.renderSideBySideInlineBreakpoint": {
      type: "number",
      default: $M0.renderSideBySideInlineBreakpoint,
      description: localize(290, null)
    },
    "diffEditor.useInlineViewWhenSpaceIsLimited": {
      type: "boolean",
      default: $M0.useInlineViewWhenSpaceIsLimited,
      description: localize(291, null)
    },
    "diffEditor.renderMarginRevertIcon": {
      type: "boolean",
      default: $M0.renderMarginRevertIcon,
      description: localize(292, null)
    },
    "diffEditor.renderGutterMenu": {
      type: "boolean",
      default: $M0.renderGutterMenu,
      description: localize(293, null)
    },
    "diffEditor.ignoreTrimWhitespace": {
      type: "boolean",
      default: $M0.ignoreTrimWhitespace,
      description: localize(294, null)
    },
    "diffEditor.renderIndicators": {
      type: "boolean",
      default: $M0.renderIndicators,
      description: localize(295, null)
    },
    "diffEditor.codeLens": {
      type: "boolean",
      default: $M0.diffCodeLens,
      description: localize(296, null)
    },
    "diffEditor.wordWrap": {
      type: "string",
      enum: ["off", "on", "inherit"],
      default: $M0.diffWordWrap,
      markdownEnumDescriptions: [
        localize(297, null),
        localize(298, null),
        localize(299, null, "`#editor.wordWrap#`")
      ]
    },
    "diffEditor.diffAlgorithm": {
      type: "string",
      enum: ["legacy", "advanced"],
      default: $M0.diffAlgorithm,
      markdownEnumDescriptions: [
        localize(300, null),
        localize(301, null)
      ]
    },
    "diffEditor.hideUnchangedRegions.enabled": {
      type: "boolean",
      default: $M0.hideUnchangedRegions.enabled,
      markdownDescription: localize(302, null)
    },
    "diffEditor.hideUnchangedRegions.revealLineCount": {
      type: "integer",
      default: $M0.hideUnchangedRegions.revealLineCount,
      markdownDescription: localize(303, null),
      minimum: 1
    },
    "diffEditor.hideUnchangedRegions.minimumLineCount": {
      type: "integer",
      default: $M0.hideUnchangedRegions.minimumLineCount,
      markdownDescription: localize(304, null),
      minimum: 1
    },
    "diffEditor.hideUnchangedRegions.contextLineCount": {
      type: "integer",
      default: $M0.hideUnchangedRegions.contextLineCount,
      markdownDescription: localize(305, null),
      minimum: 1
    },
    "diffEditor.experimental.showMoves": {
      type: "boolean",
      default: $M0.experimental.showMoves,
      markdownDescription: localize(306, null)
    },
    "diffEditor.experimental.showEmptyDecorations": {
      type: "boolean",
      default: $M0.experimental.showEmptyDecorations,
      description: localize(307, null)
    },
    "diffEditor.experimental.useTrueInlineView": {
      type: "boolean",
      default: $M0.experimental.useTrueInlineView,
      description: localize(308, null)
    }
  }
};
function isConfigurationPropertySchema(x) {
  return typeof x.type !== "undefined" || typeof x.anyOf !== "undefined";
}
for (const editorOption of editorOptionsRegistry) {
  const schema9 = editorOption.schema;
  if (typeof schema9 !== "undefined") {
    if (isConfigurationPropertySchema(schema9)) {
      editorConfiguration.properties[`editor.${editorOption.name}`] = schema9;
    } else {
      for (const key2 in schema9) {
        if (Object.hasOwnProperty.call(schema9, key2)) {
          editorConfiguration.properties[key2] = schema9[key2];
        }
      }
    }
  }
}
var configurationRegistry2 = $Wn.as($Ht.Configuration);
configurationRegistry2.registerConfiguration(editorConfiguration);

// out-build/vs/editor/contrib/codeAction/common/types.js
var $pab = new class {
  constructor() {
    this.QuickFix = new $oE("quickfix");
    this.Refactor = new $oE("refactor");
    this.RefactorExtract = this.Refactor.append("extract");
    this.RefactorInline = this.Refactor.append("inline");
    this.RefactorMove = this.Refactor.append("move");
    this.RefactorRewrite = this.Refactor.append("rewrite");
    this.Notebook = new $oE("notebook");
    this.Source = new $oE("source");
    this.SourceOrganizeImports = this.Source.append("organizeImports");
    this.SourceFixAll = this.Source.append("fixAll");
    this.SurroundWith = this.Refactor.append("surround");
  }
}();
var CodeActionAutoApply;
(function(CodeActionAutoApply2) {
  CodeActionAutoApply2["IfSingle"] = "ifSingle";
  CodeActionAutoApply2["First"] = "first";
  CodeActionAutoApply2["Never"] = "never";
})(CodeActionAutoApply || (CodeActionAutoApply = {}));
var CodeActionTriggerSource;
(function(CodeActionTriggerSource2) {
  CodeActionTriggerSource2["Refactor"] = "refactor";
  CodeActionTriggerSource2["RefactorPreview"] = "refactor preview";
  CodeActionTriggerSource2["Lightbulb"] = "lightbulb";
  CodeActionTriggerSource2["Default"] = "other (default)";
  CodeActionTriggerSource2["SourceAction"] = "source action";
  CodeActionTriggerSource2["QuickFix"] = "quick fix action";
  CodeActionTriggerSource2["FixAll"] = "fix all";
  CodeActionTriggerSource2["OrganizeImports"] = "organize imports";
  CodeActionTriggerSource2["AutoFix"] = "auto fix";
  CodeActionTriggerSource2["QuickFixHover"] = "quick fix hover window";
  CodeActionTriggerSource2["OnSave"] = "save participants";
  CodeActionTriggerSource2["ProblemsView"] = "problems view";
})(CodeActionTriggerSource || (CodeActionTriggerSource = {}));
function $qab(filter, providedKind) {
  if (filter.include && !filter.include.intersects(providedKind)) {
    return false;
  }
  if (filter.excludes) {
    if (filter.excludes.some((exclude) => excludesAction(providedKind, exclude, filter.include))) {
      return false;
    }
  }
  if (!filter.includeSourceActions && $pab.Source.contains(providedKind)) {
    return false;
  }
  return true;
}
function $rab(filter, action) {
  const actionKind = action.kind ? new $oE(action.kind) : void 0;
  if (filter.include) {
    if (!actionKind || !filter.include.contains(actionKind)) {
      return false;
    }
  }
  if (filter.excludes) {
    if (actionKind && filter.excludes.some((exclude) => excludesAction(actionKind, exclude, filter.include))) {
      return false;
    }
  }
  if (!filter.includeSourceActions) {
    if (actionKind && $pab.Source.contains(actionKind)) {
      return false;
    }
  }
  if (filter.onlyIncludePreferredActions) {
    if (!action.isPreferred) {
      return false;
    }
  }
  return true;
}
function excludesAction(providedKind, exclude, include) {
  if (!exclude.contains(providedKind)) {
    return false;
  }
  if (include && exclude.contains(include)) {
    return false;
  }
  return true;
}
var $sab = class _$sab {
  static fromUser(arg, defaults) {
    if (!arg || typeof arg !== "object") {
      return new _$sab(defaults.kind, defaults.apply, false);
    }
    return new _$sab(_$sab.b(arg, defaults.kind), _$sab.a(arg, defaults.apply), _$sab.c(arg));
  }
  static a(arg, defaultAutoApply) {
    switch (typeof arg.apply === "string" ? arg.apply.toLowerCase() : "") {
      case "first":
        return "first";
      case "never":
        return "never";
      case "ifsingle":
        return "ifSingle";
      default:
        return defaultAutoApply;
    }
  }
  static b(arg, defaultKind) {
    return typeof arg.kind === "string" ? new $oE(arg.kind) : defaultKind;
  }
  static c(arg) {
    return typeof arg.preferred === "boolean" ? arg.preferred : false;
  }
  constructor(kind, apply2, preferred) {
    this.kind = kind;
    this.apply = apply2;
    this.preferred = preferred;
  }
};
var $tab = class {
  constructor(action, provider, highlightRange2) {
    this.action = action;
    this.provider = provider;
    this.highlightRange = highlightRange2;
  }
  async resolve(token) {
    if (this.provider?.resolveCodeAction && !this.action.edit) {
      let action;
      try {
        action = await this.provider.resolveCodeAction(this.action, token);
      } catch (err) {
        $hb(err);
      }
      if (action) {
        this.action.edit = action.edit;
      }
    }
    return this;
  }
};

// out-build/vs/editor/contrib/codeAction/browser/codeAction.js
var $uab = "editor.action.codeAction";
var $vab = "editor.action.quickFix";
var $wab = "editor.action.autoFix";
var $xab = "editor.action.refactor";
var $zab = "editor.action.sourceAction";
var $Aab = "editor.action.organizeImports";
var $Bab = "editor.action.fixAll";
var ManagedCodeActionSet = class _ManagedCodeActionSet extends $3c {
  static c(a, b) {
    if (a.isPreferred && !b.isPreferred) {
      return -1;
    } else if (!a.isPreferred && b.isPreferred) {
      return 1;
    } else {
      return 0;
    }
  }
  static f({ action: a }, { action: b }) {
    if (a.isAI && !b.isAI) {
      return 1;
    } else if (!a.isAI && b.isAI) {
      return -1;
    }
    if ($Qb(a.diagnostics)) {
      return $Qb(b.diagnostics) ? _ManagedCodeActionSet.c(a, b) : -1;
    } else if ($Qb(b.diagnostics)) {
      return 1;
    } else {
      return _ManagedCodeActionSet.c(a, b);
    }
  }
  constructor(actions, documentation, disposables) {
    super();
    this.documentation = documentation;
    this.B(disposables);
    this.allActions = [...actions].sort(_ManagedCodeActionSet.f);
    this.validActions = this.allActions.filter(({ action }) => !action.disabled);
  }
  get hasAutoFix() {
    return this.validActions.some(({ action: fix }) => !!fix.kind && $pab.QuickFix.contains(new $oE(fix.kind)) && !!fix.isPreferred);
  }
  get hasAIFix() {
    return this.validActions.some(({ action: fix }) => !!fix.isAI);
  }
  get allAIFixes() {
    return this.validActions.every(({ action: fix }) => !!fix.isAI);
  }
};
var emptyCodeActionsResponse = { actions: [], documentation: void 0 };
async function $Cab(registry4, model, rangeOrSelection, trigger, progress, token) {
  const filter = trigger.filter || {};
  const notebookFilter = {
    ...filter,
    excludes: [...filter.excludes || [], $pab.Notebook]
  };
  const codeActionContext = {
    only: filter.include?.value,
    trigger: trigger.type
  };
  const cts = new $O_(model, token);
  const excludeNotebookCodeActions = trigger.type === 2;
  const providers2 = getCodeActionProviders(registry4, model, excludeNotebookCodeActions ? notebookFilter : filter);
  const disposables = new $2c();
  const promises = providers2.map(async (provider) => {
    const handle2 = setTimeout(() => progress.report(provider), 1250);
    try {
      const providedCodeActions = await provider.provideCodeActions(model, rangeOrSelection, codeActionContext, cts.token);
      if (providedCodeActions) {
        disposables.add(providedCodeActions);
      }
      if (cts.token.isCancellationRequested) {
        return emptyCodeActionsResponse;
      }
      const filteredActions = (providedCodeActions?.actions || []).filter((action) => action && $rab(filter, action));
      const documentation = getDocumentationFromProvider(provider, filteredActions, filter.include);
      return {
        actions: filteredActions.map((action) => new $tab(action, provider)),
        documentation
      };
    } catch (err) {
      if ($kb(err)) {
        throw err;
      }
      $hb(err);
      return emptyCodeActionsResponse;
    } finally {
      clearTimeout(handle2);
    }
  });
  const listener = registry4.onDidChange(() => {
    const newProviders = registry4.all(model);
    if (!$zb(newProviders, providers2)) {
      cts.cancel();
    }
  });
  try {
    const actions = await Promise.all(promises);
    const allActions = actions.map((x) => x.actions).flat();
    const allDocumentation = [
      ...$Mb(actions.map((x) => x.documentation)),
      ...getAdditionalDocumentationForShowingActions(registry4, model, trigger, allActions)
    ];
    return new ManagedCodeActionSet(allActions, allDocumentation, disposables);
  } finally {
    listener.dispose();
    cts.dispose();
  }
}
function getCodeActionProviders(registry4, model, filter) {
  return registry4.all(model).filter((provider) => {
    if (!provider.providedCodeActionKinds) {
      return true;
    }
    return provider.providedCodeActionKinds.some((kind) => $qab(filter, new $oE(kind)));
  });
}
function* getAdditionalDocumentationForShowingActions(registry4, model, trigger, actionsToShow) {
  if (model && actionsToShow.length) {
    for (const provider of registry4.all(model)) {
      if (provider._getAdditionalMenuItems) {
        yield* provider._getAdditionalMenuItems?.({ trigger: trigger.type, only: trigger.filter?.include?.value }, actionsToShow.map((item) => item.action));
      }
    }
  }
}
function getDocumentationFromProvider(provider, providedCodeActions, only) {
  if (!provider.documentation) {
    return void 0;
  }
  const documentation = provider.documentation.map((entry) => ({ kind: new $oE(entry.kind), command: entry.command }));
  if (only) {
    let currentBest;
    for (const entry of documentation) {
      if (entry.kind.contains(only)) {
        if (!currentBest) {
          currentBest = entry;
        } else {
          if (currentBest.kind.contains(entry.kind)) {
            currentBest = entry;
          }
        }
      }
    }
    if (currentBest) {
      return currentBest?.command;
    }
  }
  for (const action of providedCodeActions) {
    if (!action.kind) {
      continue;
    }
    for (const entry of documentation) {
      if (entry.kind.contains(new $oE(action.kind))) {
        return entry.command;
      }
    }
  }
  return void 0;
}
var ApplyCodeActionReason;
(function(ApplyCodeActionReason2) {
  ApplyCodeActionReason2["OnSave"] = "onSave";
  ApplyCodeActionReason2["FromProblemsView"] = "fromProblemsView";
  ApplyCodeActionReason2["FromCodeActions"] = "fromCodeActions";
  ApplyCodeActionReason2["FromAILightbulb"] = "fromAILightbulb";
  ApplyCodeActionReason2["FromProblemsHover"] = "fromProblemsHover";
})(ApplyCodeActionReason || (ApplyCodeActionReason = {}));
async function $Dab(accessor, item, codeActionReason, options3, token = CancellationToken.None) {
  const bulkEditService = accessor.get($H_);
  const commandService = accessor.get($sn);
  const telemetryService = accessor.get($zv);
  const notificationService = accessor.get($PJ);
  const accessibilitySignalService = accessor.get($I9);
  telemetryService.publicLog2("codeAction.applyCodeAction", {
    codeActionTitle: item.action.title,
    codeActionKind: item.action.kind,
    codeActionIsPreferred: !!item.action.isPreferred,
    reason: codeActionReason
  });
  accessibilitySignalService.playSignal($N9.codeActionTriggered);
  await item.resolve(token);
  if (token.isCancellationRequested) {
    return;
  }
  if (item.action.edit?.edits.length) {
    const result = await bulkEditService.apply(item.action.edit, {
      editor: options3?.editor,
      label: item.action.title,
      quotableLabel: item.action.title,
      code: "undoredo.codeAction",
      respectAutoSaveConfig: codeActionReason !== ApplyCodeActionReason.OnSave,
      showPreview: options3?.preview
    });
    if (!result.isApplied) {
      return;
    }
  }
  if (item.action.command) {
    try {
      await commandService.executeCommand(item.action.command.id, ...item.action.command.arguments || []);
    } catch (err) {
      const message = asMessage(err);
      notificationService.error(typeof message === "string" ? message : localize(905, null));
    }
  }
  setTimeout(() => accessibilitySignalService.playSignal($N9.codeActionApplied), 100);
}
function asMessage(err) {
  if (typeof err === "string") {
    return err;
  } else if (err instanceof Error && typeof err.message === "string") {
    return err.message;
  } else {
    return void 0;
  }
}
$tn.registerCommand("_executeCodeActionProvider", async function(accessor, resource, rangeOrSelection, kind, itemResolveCount) {
  if (!(resource instanceof URI)) {
    throw $nb();
  }
  const { codeActionProvider } = accessor.get($mP);
  const model = accessor.get($sG).getModel(resource);
  if (!model) {
    throw $nb();
  }
  const validatedRangeOrSelection = $_D.isISelection(rangeOrSelection) ? $_D.liftSelection(rangeOrSelection) : $9C.isIRange(rangeOrSelection) ? model.validateRange(rangeOrSelection) : void 0;
  if (!validatedRangeOrSelection) {
    throw $nb();
  }
  const include = typeof kind === "string" ? new $oE(kind) : void 0;
  const codeActionSet = await $Cab(codeActionProvider, model, validatedRangeOrSelection, { type: 1, triggerAction: CodeActionTriggerSource.Default, filter: { includeSourceActions: true, include } }, $VJ.None, CancellationToken.None);
  const resolving = [];
  const resolveCount = Math.min(codeActionSet.validActions.length, typeof itemResolveCount === "number" ? itemResolveCount : 0);
  for (let i2 = 0; i2 < resolveCount; i2++) {
    resolving.push(codeActionSet.validActions[i2].resolve(CancellationToken.None));
  }
  try {
    await Promise.all(resolving);
    return codeActionSet.validActions.map((item) => item.action);
  } finally {
    setTimeout(() => codeActionSet.dispose(), 100);
  }
});

// out-build/vs/editor/contrib/codeAction/browser/codeActionKeybindingResolver.js
var $Eab_1;
var $Eab = class $Eab2 {
  static {
    $Eab_1 = this;
  }
  static {
    this.a = [
      $xab,
      $uab,
      $zab,
      $Aab,
      $Bab
    ];
  }
  constructor(b) {
    this.b = b;
  }
  getResolver() {
    const allCodeActionBindings = new $sf(() => this.b.getKeybindings().filter((item) => $Eab_1.a.indexOf(item.command) >= 0).filter((item) => item.resolvedKeybinding).map((item) => {
      let commandArgs = item.commandArgs;
      if (item.command === $Aab) {
        commandArgs = { kind: $pab.SourceOrganizeImports.value };
      } else if (item.command === $Bab) {
        commandArgs = { kind: $pab.SourceFixAll.value };
      }
      return {
        resolvedKeybinding: item.resolvedKeybinding,
        ...$sab.fromUser(commandArgs, {
          kind: $oE.None,
          apply: "never"
          /* CodeActionAutoApply.Never */
        })
      };
    }));
    return (action) => {
      if (action.kind) {
        const binding = this.c(action, allCodeActionBindings.value);
        return binding?.resolvedKeybinding;
      }
      return void 0;
    };
  }
  c(action, candidates) {
    if (!action.kind) {
      return void 0;
    }
    const kind = new $oE(action.kind);
    return candidates.filter((candidate) => candidate.kind.contains(kind)).filter((candidate) => {
      if (candidate.preferred) {
        return action.isPreferred;
      }
      return true;
    }).reduceRight((currentBest, candidate) => {
      if (!currentBest) {
        return candidate;
      }
      return currentBest.kind.contains(candidate.kind) ? candidate : currentBest;
    }, void 0);
  }
};
$Eab = $Eab_1 = __decorate([
  __param(0, $Ty)
], $Eab);

// out-build/vs/editor/contrib/symbolIcons/browser/symbolIcons.js
var $Fab = $5n("symbolIcon.arrayForeground", $eo, localize(1531, null));
var $Gab = $5n("symbolIcon.booleanForeground", $eo, localize(1532, null));
var $Hab = $5n("symbolIcon.classForeground", {
  dark: "#EE9D28",
  light: "#D67E00",
  hcDark: "#EE9D28",
  hcLight: "#D67E00"
}, localize(1533, null));
var $Iab = $5n("symbolIcon.colorForeground", $eo, localize(1534, null));
var $Jab = $5n("symbolIcon.constantForeground", $eo, localize(1535, null));
var $Kab = $5n("symbolIcon.constructorForeground", {
  dark: "#B180D7",
  light: "#652D90",
  hcDark: "#B180D7",
  hcLight: "#652D90"
}, localize(1536, null));
var $Lab = $5n("symbolIcon.enumeratorForeground", {
  dark: "#EE9D28",
  light: "#D67E00",
  hcDark: "#EE9D28",
  hcLight: "#D67E00"
}, localize(1537, null));
var $Mab = $5n("symbolIcon.enumeratorMemberForeground", {
  dark: "#75BEFF",
  light: "#007ACC",
  hcDark: "#75BEFF",
  hcLight: "#007ACC"
}, localize(1538, null));
var $Nab = $5n("symbolIcon.eventForeground", {
  dark: "#EE9D28",
  light: "#D67E00",
  hcDark: "#EE9D28",
  hcLight: "#D67E00"
}, localize(1539, null));
var $Oab = $5n("symbolIcon.fieldForeground", {
  dark: "#75BEFF",
  light: "#007ACC",
  hcDark: "#75BEFF",
  hcLight: "#007ACC"
}, localize(1540, null));
var $Pab = $5n("symbolIcon.fileForeground", $eo, localize(1541, null));
var $Qab = $5n("symbolIcon.folderForeground", $eo, localize(1542, null));
var $Rab = $5n("symbolIcon.functionForeground", {
  dark: "#B180D7",
  light: "#652D90",
  hcDark: "#B180D7",
  hcLight: "#652D90"
}, localize(1543, null));
var $Sab = $5n("symbolIcon.interfaceForeground", {
  dark: "#75BEFF",
  light: "#007ACC",
  hcDark: "#75BEFF",
  hcLight: "#007ACC"
}, localize(1544, null));
var $Tab = $5n("symbolIcon.keyForeground", $eo, localize(1545, null));
var $Uab = $5n("symbolIcon.keywordForeground", $eo, localize(1546, null));
var $Vab = $5n("symbolIcon.methodForeground", {
  dark: "#B180D7",
  light: "#652D90",
  hcDark: "#B180D7",
  hcLight: "#652D90"
}, localize(1547, null));
var $Wab = $5n("symbolIcon.moduleForeground", $eo, localize(1548, null));
var $Xab = $5n("symbolIcon.namespaceForeground", $eo, localize(1549, null));
var $Yab = $5n("symbolIcon.nullForeground", $eo, localize(1550, null));
var $Zab = $5n("symbolIcon.numberForeground", $eo, localize(1551, null));
var $1ab = $5n("symbolIcon.objectForeground", $eo, localize(1552, null));
var $2ab = $5n("symbolIcon.operatorForeground", $eo, localize(1553, null));
var $3ab = $5n("symbolIcon.packageForeground", $eo, localize(1554, null));
var $4ab = $5n("symbolIcon.propertyForeground", $eo, localize(1555, null));
var $5ab = $5n("symbolIcon.referenceForeground", $eo, localize(1556, null));
var $6ab = $5n("symbolIcon.snippetForeground", $eo, localize(1557, null));
var $7ab = $5n("symbolIcon.stringForeground", $eo, localize(1558, null));
var $8ab = $5n("symbolIcon.structForeground", $eo, localize(1559, null));
var $9ab = $5n("symbolIcon.textForeground", $eo, localize(1560, null));
var $0ab = $5n("symbolIcon.typeParameterForeground", $eo, localize(1561, null));
var $$ab = $5n("symbolIcon.unitForeground", $eo, localize(1562, null));
var $_ab = $5n("symbolIcon.variableForeground", {
  dark: "#75BEFF",
  light: "#007ACC",
  hcDark: "#75BEFF",
  hcLight: "#007ACC"
}, localize(1563, null));

// out-build/vs/editor/contrib/codeAction/browser/codeActionMenu.js
var uncategorizedCodeActionGroup = Object.freeze({ kind: $oE.Empty, title: localize(941, null) });
var codeActionGroups = Object.freeze([
  { kind: $pab.QuickFix, title: localize(942, null) },
  { kind: $pab.RefactorExtract, title: localize(943, null), icon: $6l.wrench },
  { kind: $pab.RefactorInline, title: localize(944, null), icon: $6l.wrench },
  { kind: $pab.RefactorRewrite, title: localize(945, null), icon: $6l.wrench },
  { kind: $pab.RefactorMove, title: localize(946, null), icon: $6l.wrench },
  { kind: $pab.SurroundWith, title: localize(947, null), icon: $6l.surroundWith },
  { kind: $pab.Source, title: localize(948, null), icon: $6l.symbolFile },
  uncategorizedCodeActionGroup
]);
function $abb(inputCodeActions, showHeaders, keybindingResolver) {
  if (!showHeaders) {
    return inputCodeActions.map((action) => {
      return {
        kind: "action",
        item: action,
        group: uncategorizedCodeActionGroup,
        disabled: !!action.action.disabled,
        label: action.action.disabled || action.action.title,
        canPreview: !!action.action.edit?.edits.length
      };
    });
  }
  const menuEntries = codeActionGroups.map((group2) => ({ group: group2, actions: [] }));
  for (const action of inputCodeActions) {
    const kind = action.action.kind ? new $oE(action.action.kind) : $oE.None;
    for (const menuEntry of menuEntries) {
      if (menuEntry.group.kind.contains(kind)) {
        menuEntry.actions.push(action);
        break;
      }
    }
  }
  const allMenuItems = [];
  for (const menuEntry of menuEntries) {
    if (menuEntry.actions.length) {
      allMenuItems.push({ kind: "header", group: menuEntry.group });
      for (const action of menuEntry.actions) {
        const group2 = menuEntry.group;
        allMenuItems.push({
          kind: "action",
          item: action,
          group: action.action.isAI ? { title: group2.title, kind: group2.kind, icon: $6l.sparkle } : group2,
          label: action.action.title,
          disabled: !!action.action.disabled,
          keybinding: keybindingResolver(action.action)
        });
      }
    }
  }
  return allMenuItems;
}

// out-build/vs/editor/contrib/codeAction/browser/lightBulbWidget.js
var $bbb_1;
var GUTTER_LIGHTBULB_ICON = $9r("gutter-lightbulb", $6l.lightBulb, localize(949, null));
var GUTTER_LIGHTBULB_AUTO_FIX_ICON = $9r("gutter-lightbulb-auto-fix", $6l.lightbulbAutofix, localize(950, null));
var GUTTER_LIGHTBULB_AIFIX_ICON = $9r("gutter-lightbulb-sparkle", $6l.lightbulbSparkle, localize(951, null));
var GUTTER_LIGHTBULB_AIFIX_AUTO_FIX_ICON = $9r("gutter-lightbulb-aifix-auto-fix", $6l.lightbulbSparkleAutofix, localize(952, null));
var GUTTER_SPARKLE_FILLED_ICON = $9r("gutter-lightbulb-sparkle-filled", $6l.sparkleFilled, localize(953, null));
var LightBulbState;
(function(LightBulbState2) {
  let Type4;
  (function(Type5) {
    Type5[Type5["Hidden"] = 0] = "Hidden";
    Type5[Type5["Showing"] = 1] = "Showing";
  })(Type4 = LightBulbState2.Type || (LightBulbState2.Type = {}));
  LightBulbState2.Hidden = {
    type: 0
    /* Type.Hidden */
  };
  class Showing {
    constructor(actions, trigger, editorPosition, widgetPosition) {
      this.actions = actions;
      this.trigger = trigger;
      this.editorPosition = editorPosition;
      this.widgetPosition = widgetPosition;
      this.type = 1;
    }
  }
  LightBulbState2.Showing = Showing;
})(LightBulbState || (LightBulbState = {}));
var $bbb = class $bbb2 extends $3c {
  static {
    $bbb_1 = this;
  }
  static {
    this.b = $WI.register({
      description: "codicon-gutter-lightbulb-decoration",
      glyphMarginClassName: ThemeIcon.asClassName($6l.lightBulb),
      glyphMargin: { position: GlyphMarginLane.Left },
      stickiness: 1
    });
  }
  static {
    this.ID = "editor.contrib.lightbulbWidget";
  }
  static {
    this.c = [
      0
      /* ContentWidgetPositionPreference.EXACT */
    ];
  }
  constructor(u, w) {
    super();
    this.u = u;
    this.w = w;
    this.g = this.B(new $ze());
    this.onClick = this.g.event;
    this.h = LightBulbState.Hidden;
    this.j = LightBulbState.Hidden;
    this.m = [];
    this.n = [
      "codicon-" + GUTTER_LIGHTBULB_ICON.id,
      "codicon-" + GUTTER_LIGHTBULB_AIFIX_AUTO_FIX_ICON.id,
      "codicon-" + GUTTER_LIGHTBULB_AUTO_FIX_ICON.id,
      "codicon-" + GUTTER_LIGHTBULB_AIFIX_ICON.id,
      "codicon-" + GUTTER_SPARKLE_FILLED_ICON.id
    ];
    this.t = $bbb_1.b;
    this.f = $("div.lightBulbWidget");
    this.f.role = "listbox";
    this.B($mZ.ignoreTarget(this.f));
    this.u.addContentWidget(this);
    this.B(this.u.onDidChangeModelContent((_) => {
      const editorModel = this.u.getModel();
      if (this.z.type !== 1 || !editorModel || this.z.editorPosition.lineNumber >= editorModel.getLineCount()) {
        this.hide();
      }
      if (this.C.type !== 1 || !editorModel || this.C.editorPosition.lineNumber >= editorModel.getLineCount()) {
        this.gutterHide();
      }
    }));
    this.B($bj(this.f, (e) => {
      if (this.z.type !== 1) {
        return;
      }
      this.u.focus();
      e.preventDefault();
      const { top: top2, height } = $vj(this.f);
      const lineHeight = this.u.getOption(
        68
        /* EditorOption.lineHeight */
      );
      let pad = Math.floor(lineHeight / 3);
      if (this.z.widgetPosition.position !== null && this.z.widgetPosition.position.lineNumber < this.z.editorPosition.lineNumber) {
        pad += lineHeight;
      }
      this.g.fire({
        x: e.posx,
        y: top2 + height + pad,
        actions: this.z.actions,
        trigger: this.z.trigger
      });
    }));
    this.B($_i(this.f, "mouseenter", (e) => {
      if ((e.buttons & 1) !== 1) {
        return;
      }
      this.hide();
    }));
    this.B(Event2.runAndSubscribe(this.w.onDidUpdateKeybindings, () => {
      this.r = this.w.lookupKeybinding($wab)?.getLabel() ?? void 0;
      this.s = this.w.lookupKeybinding($vab)?.getLabel() ?? void 0;
      this.D();
    }));
    this.B(this.u.onMouseDown(async (e) => {
      if (!e.target.element || !this.n.some((cls) => e.target.element && e.target.element.classList.contains(cls))) {
        return;
      }
      if (this.C.type !== 1) {
        return;
      }
      this.u.focus();
      const { top: top2, height } = $vj(e.target.element);
      const lineHeight = this.u.getOption(
        68
        /* EditorOption.lineHeight */
      );
      let pad = Math.floor(lineHeight / 3);
      if (this.C.widgetPosition.position !== null && this.C.widgetPosition.position.lineNumber < this.C.editorPosition.lineNumber) {
        pad += lineHeight;
      }
      this.g.fire({
        x: e.event.posx,
        y: top2 + height + pad,
        actions: this.C.actions,
        trigger: this.C.trigger
      });
    }));
  }
  dispose() {
    super.dispose();
    this.u.removeContentWidget(this);
    if (this.a) {
      this.I(this.a);
    }
  }
  getId() {
    return "LightBulbWidget";
  }
  getDomNode() {
    return this.f;
  }
  getPosition() {
    return this.h.type === 1 ? this.h.widgetPosition : null;
  }
  update(actions, trigger, atPosition) {
    if (actions.validActions.length <= 0) {
      this.gutterHide();
      return this.hide();
    }
    const hasTextFocus = this.u.hasTextFocus();
    if (!hasTextFocus) {
      this.gutterHide();
      return this.hide();
    }
    const options3 = this.u.getOptions();
    if (!options3.get(
      66
      /* EditorOption.lightbulb */
    ).enabled) {
      this.gutterHide();
      return this.hide();
    }
    const model = this.u.getModel();
    if (!model) {
      this.gutterHide();
      return this.hide();
    }
    const { lineNumber, column } = model.validatePosition(atPosition);
    const tabSize = model.getOptions().tabSize;
    const fontInfo = this.u.getOptions().get(
      52
      /* EditorOption.fontInfo */
    );
    const lineContent = model.getLineContent(lineNumber);
    const indent = $VH(lineContent, tabSize);
    const lineHasSpace = fontInfo.spaceWidth * indent > 22;
    const isFolded = (lineNumber2) => {
      return lineNumber2 > 2 && this.u.getTopForLineNumber(lineNumber2) === this.u.getTopForLineNumber(lineNumber2 - 1);
    };
    const currLineDecorations = this.u.getLineDecorations(lineNumber);
    let hasDecoration = false;
    if (currLineDecorations) {
      for (const decoration3 of currLineDecorations) {
        const glyphClass = decoration3.options.glyphMarginClassName;
        if (glyphClass && !this.n.some((className) => glyphClass.includes(className))) {
          hasDecoration = true;
          break;
        }
      }
    }
    let effectiveLineNumber = lineNumber;
    let effectiveColumnNumber = 1;
    if (!lineHasSpace) {
      const isLineEmptyOrIndented = (lineNumber2) => {
        const lineContent2 = model.getLineContent(lineNumber2);
        return /^\s*$|^\s+/.test(lineContent2) || lineContent2.length <= effectiveColumnNumber;
      };
      if (lineNumber > 1 && !isFolded(lineNumber - 1)) {
        const lineCount = model.getLineCount();
        const endLine = lineNumber === lineCount;
        const prevLineEmptyOrIndented = lineNumber > 1 && isLineEmptyOrIndented(lineNumber - 1);
        const nextLineEmptyOrIndented = !endLine && isLineEmptyOrIndented(lineNumber + 1);
        const currLineEmptyOrIndented = isLineEmptyOrIndented(lineNumber);
        const notEmpty = !nextLineEmptyOrIndented && !prevLineEmptyOrIndented;
        if (!nextLineEmptyOrIndented && !prevLineEmptyOrIndented && !hasDecoration) {
          this.C = new LightBulbState.Showing(actions, trigger, atPosition, {
            position: { lineNumber: effectiveLineNumber, column: effectiveColumnNumber },
            preference: $bbb_1.c
          });
          this.G();
          return this.hide();
        } else if (prevLineEmptyOrIndented || endLine || prevLineEmptyOrIndented && !currLineEmptyOrIndented) {
          effectiveLineNumber -= 1;
        } else if (nextLineEmptyOrIndented || notEmpty && currLineEmptyOrIndented) {
          effectiveLineNumber += 1;
        }
      } else if (lineNumber === 1 && (lineNumber === model.getLineCount() || !isLineEmptyOrIndented(lineNumber + 1) && !isLineEmptyOrIndented(lineNumber))) {
        this.C = new LightBulbState.Showing(actions, trigger, atPosition, {
          position: { lineNumber: effectiveLineNumber, column: effectiveColumnNumber },
          preference: $bbb_1.c
        });
        if (hasDecoration) {
          this.gutterHide();
        } else {
          this.G();
          return this.hide();
        }
      } else if (lineNumber < model.getLineCount() && !isFolded(lineNumber + 1)) {
        effectiveLineNumber += 1;
      } else if (column * fontInfo.spaceWidth < 22) {
        return this.hide();
      }
      effectiveColumnNumber = /^\S\s*$/.test(model.getLineContent(effectiveLineNumber)) ? 2 : 1;
    }
    this.z = new LightBulbState.Showing(actions, trigger, atPosition, {
      position: { lineNumber: effectiveLineNumber, column: effectiveColumnNumber },
      preference: $bbb_1.c
    });
    if (this.a) {
      this.I(this.a);
      this.gutterHide();
    }
    const validActions = actions.validActions;
    const actionKind = actions.validActions[0].action.kind;
    if (validActions.length !== 1 || !actionKind) {
      this.u.layoutContentWidget(this);
      return;
    }
    this.u.layoutContentWidget(this);
  }
  hide() {
    if (this.z === LightBulbState.Hidden) {
      return;
    }
    this.z = LightBulbState.Hidden;
    this.u.layoutContentWidget(this);
  }
  gutterHide() {
    if (this.C === LightBulbState.Hidden) {
      return;
    }
    if (this.a) {
      this.I(this.a);
    }
    this.C = LightBulbState.Hidden;
  }
  get z() {
    return this.h;
  }
  set z(value) {
    this.h = value;
    this.D();
  }
  get C() {
    return this.j;
  }
  set C(value) {
    this.j = value;
    this.F();
  }
  D() {
    this.f.classList.remove(...this.m);
    this.m = [];
    if (this.z.type !== 1) {
      return;
    }
    let icon2;
    let autoRun = false;
    if (this.z.actions.allAIFixes) {
      icon2 = $6l.sparkleFilled;
      if (this.z.actions.validActions.length === 1) {
        autoRun = true;
      }
    } else if (this.z.actions.hasAutoFix) {
      if (this.z.actions.hasAIFix) {
        icon2 = $6l.lightbulbSparkleAutofix;
      } else {
        icon2 = $6l.lightbulbAutofix;
      }
    } else if (this.z.actions.hasAIFix) {
      icon2 = $6l.lightbulbSparkle;
    } else {
      icon2 = $6l.lightBulb;
    }
    this.L(this.z.actions.hasAutoFix, autoRun);
    this.m = ThemeIcon.asClassNameArray(icon2);
    this.f.classList.add(...this.m);
  }
  F() {
    if (this.C.type !== 1) {
      return;
    }
    let icon2;
    let autoRun = false;
    if (this.C.actions.allAIFixes) {
      icon2 = GUTTER_SPARKLE_FILLED_ICON;
      if (this.C.actions.validActions.length === 1) {
        autoRun = true;
      }
    } else if (this.C.actions.hasAutoFix) {
      if (this.C.actions.hasAIFix) {
        icon2 = GUTTER_LIGHTBULB_AIFIX_AUTO_FIX_ICON;
      } else {
        icon2 = GUTTER_LIGHTBULB_AUTO_FIX_ICON;
      }
    } else if (this.C.actions.hasAIFix) {
      icon2 = GUTTER_LIGHTBULB_AIFIX_ICON;
    } else {
      icon2 = GUTTER_LIGHTBULB_ICON;
    }
    this.L(this.C.actions.hasAutoFix, autoRun);
    const GUTTER_DECORATION = $WI.register({
      description: "codicon-gutter-lightbulb-decoration",
      glyphMarginClassName: ThemeIcon.asClassName(icon2),
      glyphMargin: { position: GlyphMarginLane.Left },
      stickiness: 1
    });
    this.t = GUTTER_DECORATION;
  }
  /* Gutter Helper Functions */
  G() {
    const selection = this.u.getSelection();
    if (!selection) {
      return;
    }
    if (this.a === void 0) {
      this.H(selection.startLineNumber);
    } else {
      this.J(this.a, selection.startLineNumber);
    }
  }
  H(lineNumber) {
    this.u.changeDecorations((accessor) => {
      this.a = accessor.addDecoration(new $9C(lineNumber, 0, lineNumber, 0), this.t);
    });
  }
  I(decorationId) {
    this.u.changeDecorations((accessor) => {
      accessor.removeDecoration(decorationId);
      this.a = void 0;
    });
  }
  J(decorationId, lineNumber) {
    this.u.changeDecorations((accessor) => {
      accessor.changeDecoration(decorationId, new $9C(lineNumber, 0, lineNumber, 0));
      accessor.changeDecorationOptions(decorationId, this.t);
    });
  }
  L(autoFix, autoRun) {
    if (this.z.type !== 1) {
      return;
    }
    if (autoRun) {
      this.M = localize(954, null, this.z.actions.validActions[0].action.title);
    } else if (autoFix && this.r) {
      this.M = localize(955, null, this.r);
    } else if (!autoFix && this.s) {
      this.M = localize(956, null, this.s);
    } else if (!autoFix) {
      this.M = localize(957, null);
    }
  }
  set M(value) {
    this.f.title = value;
  }
};
$bbb = $bbb_1 = __decorate([
  __param(1, $Ty)
], $bbb);

// out-build/vs/platform/markers/common/markers.js
var MarkerTag;
(function(MarkerTag3) {
  MarkerTag3[MarkerTag3["Unnecessary"] = 1] = "Unnecessary";
  MarkerTag3[MarkerTag3["Deprecated"] = 2] = "Deprecated";
})(MarkerTag || (MarkerTag = {}));
var MarkerSeverity;
(function(MarkerSeverity3) {
  MarkerSeverity3[MarkerSeverity3["Hint"] = 1] = "Hint";
  MarkerSeverity3[MarkerSeverity3["Info"] = 2] = "Info";
  MarkerSeverity3[MarkerSeverity3["Warning"] = 4] = "Warning";
  MarkerSeverity3[MarkerSeverity3["Error"] = 8] = "Error";
})(MarkerSeverity || (MarkerSeverity = {}));
(function(MarkerSeverity3) {
  function compare8(a, b) {
    return b - a;
  }
  MarkerSeverity3.compare = compare8;
  const _displayStrings = /* @__PURE__ */ Object.create(null);
  _displayStrings[MarkerSeverity3.Error] = localize(1998, null);
  _displayStrings[MarkerSeverity3.Warning] = localize(1999, null);
  _displayStrings[MarkerSeverity3.Info] = localize(2e3, null);
  function toString(a) {
    return _displayStrings[a] || "";
  }
  MarkerSeverity3.toString = toString;
  function fromSeverity(severity) {
    switch (severity) {
      case severity_default.Error:
        return MarkerSeverity3.Error;
      case severity_default.Warning:
        return MarkerSeverity3.Warning;
      case severity_default.Info:
        return MarkerSeverity3.Info;
      case severity_default.Ignore:
        return MarkerSeverity3.Hint;
    }
  }
  MarkerSeverity3.fromSeverity = fromSeverity;
  function toSeverity(severity) {
    switch (severity) {
      case MarkerSeverity3.Error:
        return severity_default.Error;
      case MarkerSeverity3.Warning:
        return severity_default.Warning;
      case MarkerSeverity3.Info:
        return severity_default.Info;
      case MarkerSeverity3.Hint:
        return severity_default.Ignore;
    }
  }
  MarkerSeverity3.toSeverity = toSeverity;
})(MarkerSeverity || (MarkerSeverity = {}));
var IMarkerData;
(function(IMarkerData2) {
  const emptyString = "";
  function makeKey(markerData) {
    return makeKeyOptionalMessage(markerData, true);
  }
  IMarkerData2.makeKey = makeKey;
  function makeKeyOptionalMessage(markerData, useMessage) {
    const result = [emptyString];
    if (markerData.source) {
      result.push(markerData.source.replace("\xA6", "\\\xA6"));
    } else {
      result.push(emptyString);
    }
    if (markerData.code) {
      if (typeof markerData.code === "string") {
        result.push(markerData.code.replace("\xA6", "\\\xA6"));
      } else {
        result.push(markerData.code.value.replace("\xA6", "\\\xA6"));
      }
    } else {
      result.push(emptyString);
    }
    if (markerData.severity !== void 0 && markerData.severity !== null) {
      result.push(MarkerSeverity.toString(markerData.severity));
    } else {
      result.push(emptyString);
    }
    if (markerData.message && useMessage) {
      result.push(markerData.message.replace("\xA6", "\\\xA6"));
    } else {
      result.push(emptyString);
    }
    if (markerData.startLineNumber !== void 0 && markerData.startLineNumber !== null) {
      result.push(markerData.startLineNumber.toString());
    } else {
      result.push(emptyString);
    }
    if (markerData.startColumn !== void 0 && markerData.startColumn !== null) {
      result.push(markerData.startColumn.toString());
    } else {
      result.push(emptyString);
    }
    if (markerData.endLineNumber !== void 0 && markerData.endLineNumber !== null) {
      result.push(markerData.endLineNumber.toString());
    } else {
      result.push(emptyString);
    }
    if (markerData.endColumn !== void 0 && markerData.endColumn !== null) {
      result.push(markerData.endColumn.toString());
    } else {
      result.push(emptyString);
    }
    result.push(emptyString);
    return result.join("\xA6");
  }
  IMarkerData2.makeKeyOptionalMessage = makeKeyOptionalMessage;
})(IMarkerData || (IMarkerData = {}));
var $DE = $Qk("markerService");

// out-build/vs/editor/contrib/codeAction/browser/codeActionModel.js
var $cbb = new $nn("supportedCodeAction", "");
var $dbb = "_typescript.applyFixAllCodeAction";
var CodeActionOracle = class extends $3c {
  constructor(f, g, h3, j = 250) {
    super();
    this.f = f;
    this.g = g;
    this.h = h3;
    this.j = j;
    this.c = this.B(new $6h());
    this.B(this.g.onMarkerChanged((e) => this.m(e)));
    this.B(this.f.onDidChangeCursorPosition(() => this.n()));
  }
  trigger(trigger) {
    const selection = this.r(trigger);
    this.h(selection ? { trigger, selection } : void 0);
  }
  m(resources) {
    const model = this.f.getModel();
    if (model && resources.some((resource) => $oh(resource, model.uri))) {
      this.n();
    }
  }
  n() {
    this.c.cancelAndSet(() => {
      this.trigger({ type: 2, triggerAction: CodeActionTriggerSource.Default });
    }, this.j);
  }
  r(trigger) {
    if (!this.f.hasModel()) {
      return void 0;
    }
    const selection = this.f.getSelection();
    if (trigger.type === 1) {
      return selection;
    }
    const enabled = this.f.getOption(
      66
      /* EditorOption.lightbulb */
    ).enabled;
    if (enabled === ShowLightbulbIconMode.Off) {
      return void 0;
    } else if (enabled === ShowLightbulbIconMode.On) {
      return selection;
    } else if (enabled === ShowLightbulbIconMode.OnCode) {
      const isSelectionEmpty = selection.isEmpty();
      if (!isSelectionEmpty) {
        return selection;
      }
      const model = this.f.getModel();
      const { lineNumber, column } = selection.getPosition();
      const line = model.getLineContent(lineNumber);
      if (line.length === 0) {
        return void 0;
      } else if (column === 1) {
        if (/\s/.test(line[0])) {
          return void 0;
        }
      } else if (column === model.getLineMaxColumn(lineNumber)) {
        if (/\s/.test(line[line.length - 1])) {
          return void 0;
        }
      } else {
        if (/\s/.test(line[column - 2]) && /\s/.test(line[column - 1])) {
          return void 0;
        }
      }
    }
    return selection;
  }
};
var CodeActionsState;
(function(CodeActionsState2) {
  let Type4;
  (function(Type5) {
    Type5[Type5["Empty"] = 0] = "Empty";
    Type5[Type5["Triggered"] = 1] = "Triggered";
  })(Type4 = CodeActionsState2.Type || (CodeActionsState2.Type = {}));
  CodeActionsState2.Empty = {
    type: 0
    /* Type.Empty */
  };
  class Triggered {
    constructor(trigger, position, c) {
      this.trigger = trigger;
      this.position = position;
      this.c = c;
      this.type = 1;
      this.actions = c.catch((e) => {
        if ($kb(e)) {
          return emptyCodeActionSet;
        }
        throw e;
      });
    }
    cancel() {
      this.c.cancel();
    }
  }
  CodeActionsState2.Triggered = Triggered;
})(CodeActionsState || (CodeActionsState = {}));
var emptyCodeActionSet = Object.freeze({
  allActions: [],
  validActions: [],
  dispose: () => {
  },
  documentation: [],
  hasAutoFix: false,
  hasAIFix: false,
  allAIFixes: false
});
var $ebb = class extends $3c {
  constructor(m, n, r2, contextKeyService, s, t, u) {
    super();
    this.m = m;
    this.n = n;
    this.r = r2;
    this.s = s;
    this.t = t;
    this.u = u;
    this.c = this.B(new $4c());
    this.f = CodeActionsState.Empty;
    this.h = this.B(new $ze());
    this.onDidChangeState = this.h.event;
    this.j = false;
    this.g = $cbb.bindTo(contextKeyService);
    this.B(this.m.onDidChangeModel(() => this.y()));
    this.B(this.m.onDidChangeModelLanguage(() => this.y()));
    this.B(this.n.onDidChange(() => this.y()));
    this.B(this.m.onDidChangeConfiguration((e) => {
      if (e.hasChanged(
        66
        /* EditorOption.lightbulb */
      )) {
        this.y();
      }
    }));
    this.y();
  }
  dispose() {
    if (this.j) {
      return;
    }
    this.j = true;
    super.dispose();
    this.z(CodeActionsState.Empty, true);
  }
  w() {
    const model = this.m?.getModel();
    return this.t ? this.t.getValue("editor.codeActionWidget.includeNearbyQuickFixes", { resource: model?.uri }) : false;
  }
  y() {
    if (this.j) {
      return;
    }
    this.c.value = void 0;
    this.z(CodeActionsState.Empty);
    const model = this.m.getModel();
    if (model && this.n.has(model) && !this.m.getOption(
      96
      /* EditorOption.readOnly */
    )) {
      const supportedActions = this.n.all(model).flatMap((provider) => provider.providedCodeActionKinds ?? []);
      this.g.set(supportedActions.join(" "));
      this.c.value = new CodeActionOracle(this.m, this.r, (trigger) => {
        if (!trigger) {
          this.z(CodeActionsState.Empty);
          return;
        }
        const startPosition = trigger.selection.getStartPosition();
        const actions = $Hh(async (token) => {
          if (this.w() && trigger.trigger.type === 1 && (trigger.trigger.triggerAction === CodeActionTriggerSource.QuickFix || trigger.trigger.filter?.include?.contains($pab.QuickFix))) {
            const codeActionSet = await $Cab(this.n, model, trigger.selection, trigger.trigger, $VJ.None, token);
            const allCodeActions = [...codeActionSet.allActions];
            if (token.isCancellationRequested) {
              return emptyCodeActionSet;
            }
            const foundQuickfix = codeActionSet.validActions?.some((action) => action.action.kind ? $pab.QuickFix.contains(new $oE(action.action.kind)) : false);
            const allMarkers = this.r.read({ resource: model.uri });
            if (foundQuickfix) {
              for (const action of codeActionSet.validActions) {
                if (action.action.command?.arguments?.some((arg) => typeof arg === "string" && arg.includes($dbb))) {
                  action.action.diagnostics = [...allMarkers.filter((marker) => marker.relatedInformation)];
                }
              }
              return { validActions: codeActionSet.validActions, allActions: allCodeActions, documentation: codeActionSet.documentation, hasAutoFix: codeActionSet.hasAutoFix, hasAIFix: codeActionSet.hasAIFix, allAIFixes: codeActionSet.allAIFixes, dispose: () => {
                codeActionSet.dispose();
              } };
            } else if (!foundQuickfix) {
              if (allMarkers.length > 0) {
                const currPosition = trigger.selection.getPosition();
                let trackedPosition = currPosition;
                let distance = Number.MAX_VALUE;
                const currentActions = [...codeActionSet.validActions];
                for (const marker of allMarkers) {
                  const col = marker.endColumn;
                  const row = marker.endLineNumber;
                  const startRow = marker.startLineNumber;
                  if (row === currPosition.lineNumber || startRow === currPosition.lineNumber) {
                    trackedPosition = new $8C(row, col);
                    const newCodeActionTrigger = {
                      type: trigger.trigger.type,
                      triggerAction: trigger.trigger.triggerAction,
                      filter: { include: trigger.trigger.filter?.include ? trigger.trigger.filter?.include : $pab.QuickFix },
                      autoApply: trigger.trigger.autoApply,
                      context: { notAvailableMessage: trigger.trigger.context?.notAvailableMessage || "", position: trackedPosition }
                    };
                    const selectionAsPosition = new $_D(trackedPosition.lineNumber, trackedPosition.column, trackedPosition.lineNumber, trackedPosition.column);
                    const actionsAtMarker = await $Cab(this.n, model, selectionAsPosition, newCodeActionTrigger, $VJ.None, token);
                    if (actionsAtMarker.validActions.length !== 0) {
                      for (const action of actionsAtMarker.validActions) {
                        if (action.action.command?.arguments?.some((arg) => typeof arg === "string" && arg.includes($dbb))) {
                          action.action.diagnostics = [...allMarkers.filter((marker2) => marker2.relatedInformation)];
                        }
                      }
                      if (codeActionSet.allActions.length === 0) {
                        allCodeActions.push(...actionsAtMarker.allActions);
                      }
                      if (Math.abs(currPosition.column - col) < distance) {
                        currentActions.unshift(...actionsAtMarker.validActions);
                      } else {
                        currentActions.push(...actionsAtMarker.validActions);
                      }
                    }
                    distance = Math.abs(currPosition.column - col);
                  }
                }
                const filteredActions = currentActions.filter((action, index, self2) => self2.findIndex((a) => a.action.title === action.action.title) === index);
                filteredActions.sort((a, b) => {
                  if (a.action.isPreferred && !b.action.isPreferred) {
                    return -1;
                  } else if (!a.action.isPreferred && b.action.isPreferred) {
                    return 1;
                  } else if (a.action.isAI && !b.action.isAI) {
                    return 1;
                  } else if (!a.action.isAI && b.action.isAI) {
                    return -1;
                  } else {
                    return 0;
                  }
                });
                return { validActions: filteredActions, allActions: allCodeActions, documentation: codeActionSet.documentation, hasAutoFix: codeActionSet.hasAutoFix, hasAIFix: codeActionSet.hasAIFix, allAIFixes: codeActionSet.allAIFixes, dispose: () => {
                  codeActionSet.dispose();
                } };
              }
            }
          }
          if (trigger.trigger.type === 1) {
            const sw = new $te();
            const codeActions = await $Cab(this.n, model, trigger.selection, trigger.trigger, $VJ.None, token);
            if (this.u) {
              this.u.publicLog2("codeAction.invokedDurations", {
                codeActions: codeActions.validActions.length,
                duration: sw.elapsed()
              });
            }
            return codeActions;
          }
          return $Cab(this.n, model, trigger.selection, trigger.trigger, $VJ.None, token);
        });
        if (trigger.trigger.type === 1) {
          this.s?.showWhile(actions, 250);
        }
        const newState = new CodeActionsState.Triggered(trigger.trigger, startPosition, actions);
        let isManualToAutoTransition = false;
        if (this.f.type === 1) {
          isManualToAutoTransition = this.f.trigger.type === 1 && newState.type === 1 && newState.trigger.type === 2 && this.f.position !== newState.position;
        }
        if (!isManualToAutoTransition) {
          this.z(newState);
        } else {
          setTimeout(() => {
            this.z(newState);
          }, 500);
        }
      }, void 0);
      this.c.value.trigger({ type: 2, triggerAction: CodeActionTriggerSource.Default });
    } else {
      this.g.reset();
    }
  }
  trigger(trigger) {
    this.c.value?.trigger(trigger);
  }
  z(newState, skipNotify) {
    if (newState === this.f) {
      return;
    }
    if (this.f.type === 1) {
      this.f.cancel();
    }
    this.f = newState;
    if (!skipNotify && !this.j) {
      this.h.fire(newState);
    }
  }
};

// out-build/vs/editor/contrib/codeAction/browser/codeActionController.js
var $fbb_1;
var DECORATION_CLASS_NAME = "quickfix-edit-highlight";
var $fbb = class $fbb2 extends $3c {
  static {
    $fbb_1 = this;
  }
  static {
    this.ID = "editor.contrib.codeActionController";
  }
  static get(editor) {
    return editor.getContribution($fbb_1.ID);
  }
  constructor(editor, markerService, contextKeyService, instantiationService, languageFeaturesService, progressService, m, n, r2, s, t, u) {
    super();
    this.m = m;
    this.n = n;
    this.r = r2;
    this.s = s;
    this.t = t;
    this.u = u;
    this.f = this.B(new $4c());
    this.g = false;
    this.j = false;
    this.a = editor;
    this.b = this.B(new $ebb(this.a, languageFeaturesService.codeActionProvider, markerService, contextKeyService, progressService, n, this.t));
    this.B(this.b.onDidChangeState((newState) => this.C(newState)));
    this.c = new $sf(() => {
      const widget = this.a.getContribution($bbb.ID);
      if (widget) {
        this.B(widget.onClick((e) => this.w(e.actions, e)));
      }
      return widget;
    });
    this.h = instantiationService.createInstance($Eab);
    this.B(this.a.onDidLayoutChange(() => this.r.hide()));
  }
  dispose() {
    this.j = true;
    super.dispose();
  }
  async w(actions, at) {
    if (actions.allAIFixes && actions.validActions.length === 1) {
      const actionItem = actions.validActions[0];
      const command4 = actionItem.action.command;
      if (command4 && command4.id === "inlineChat.start") {
        if (command4.arguments && command4.arguments.length >= 1) {
          command4.arguments[0] = { ...command4.arguments[0], autoSend: false };
        }
      }
      await this.applyCodeAction(actionItem, false, false, ApplyCodeActionReason.FromAILightbulb);
      return;
    }
    await this.showCodeActionList(actions, at, { includeDisabledActions: false, fromLightbulb: true });
  }
  showCodeActions(_trigger, actions, at) {
    return this.showCodeActionList(actions, at, { includeDisabledActions: false, fromLightbulb: false });
  }
  hideCodeActions() {
    this.r.hide();
  }
  manualTriggerAtCurrentPosition(notAvailableMessage, triggerAction, filter, autoApply) {
    if (!this.a.hasModel()) {
      return;
    }
    $S_.get(this.a)?.closeMessage();
    const triggerPosition = this.a.getPosition();
    this.z({ type: 1, triggerAction, filter, autoApply, context: { notAvailableMessage, position: triggerPosition } });
  }
  z(trigger) {
    return this.b.trigger(trigger);
  }
  async applyCodeAction(action, retrigger, preview, actionReason) {
    const progress = this.u.show(true, 500);
    try {
      await this.s.invokeFunction($Dab, action, actionReason, { preview, editor: this.a });
    } finally {
      if (retrigger) {
        this.z({ type: 2, triggerAction: CodeActionTriggerSource.QuickFix, filter: {} });
      }
      progress.done();
    }
  }
  hideLightBulbWidget() {
    this.c.rawValue?.hide();
    this.c.rawValue?.gutterHide();
  }
  async C(newState) {
    if (newState.type !== 1) {
      this.hideLightBulbWidget();
      return;
    }
    let actions;
    try {
      actions = await newState.actions;
    } catch (e) {
      $gb(e);
      return;
    }
    if (this.j) {
      return;
    }
    const selection = this.a.getSelection();
    if (selection?.startLineNumber !== newState.position.lineNumber) {
      return;
    }
    this.c.value?.update(actions, newState.trigger, newState.position);
    if (newState.trigger.type === 1) {
      if (newState.trigger.filter?.include) {
        const validActionToApply = this.F(newState.trigger, actions);
        if (validActionToApply) {
          try {
            this.hideLightBulbWidget();
            await this.applyCodeAction(validActionToApply, false, false, ApplyCodeActionReason.FromCodeActions);
          } finally {
            actions.dispose();
          }
          return;
        }
        if (newState.trigger.context) {
          const invalidAction = this.D(newState.trigger, actions);
          if (invalidAction && invalidAction.action.disabled) {
            $S_.get(this.a)?.showMessage(invalidAction.action.disabled, newState.trigger.context.position);
            actions.dispose();
            return;
          }
        }
      }
      const includeDisabledActions = !!newState.trigger.filter?.include;
      if (newState.trigger.context) {
        if (!actions.allActions.length || !includeDisabledActions && !actions.validActions.length) {
          $S_.get(this.a)?.showMessage(newState.trigger.context.notAvailableMessage, newState.trigger.context.position);
          this.f.value = actions;
          actions.dispose();
          return;
        }
      }
      this.f.value = actions;
      this.showCodeActionList(actions, this.H(newState.position), { includeDisabledActions, fromLightbulb: false });
    } else {
      if (this.r.isVisible) {
        actions.dispose();
      } else {
        this.f.value = actions;
      }
    }
  }
  D(trigger, actions) {
    if (!actions.allActions.length) {
      return void 0;
    }
    if (trigger.autoApply === "first" && actions.validActions.length === 0 || trigger.autoApply === "ifSingle" && actions.allActions.length === 1) {
      return actions.allActions.find(({ action }) => action.disabled);
    }
    return void 0;
  }
  F(trigger, actions) {
    if (!actions.validActions.length) {
      return void 0;
    }
    if (trigger.autoApply === "first" && actions.validActions.length > 0 || trigger.autoApply === "ifSingle" && actions.validActions.length === 1) {
      return actions.validActions[0];
    }
    return void 0;
  }
  static {
    this.G = $WI.register({
      description: "quickfix-highlight",
      className: DECORATION_CLASS_NAME
    });
  }
  async showCodeActionList(actions, at, options3) {
    const currentDecorations = this.a.createDecorationsCollection();
    const editorDom = this.a.getDomNode();
    if (!editorDom) {
      return;
    }
    const actionsToShow = options3.includeDisabledActions && (this.g || actions.validActions.length === 0) ? actions.allActions : actions.validActions;
    if (!actionsToShow.length) {
      return;
    }
    const anchor = $8C.isIPosition(at) ? this.H(at) : at;
    const delegate = {
      onSelect: async (action, preview) => {
        this.applyCodeAction(
          action,
          /* retrigger */
          true,
          !!preview,
          options3.fromLightbulb ? ApplyCodeActionReason.FromAILightbulb : ApplyCodeActionReason.FromCodeActions
        );
        this.r.hide(false);
        currentDecorations.clear();
      },
      onHide: (didCancel) => {
        this.a?.focus();
        currentDecorations.clear();
      },
      onHover: async (action, token) => {
        if (token.isCancellationRequested) {
          return;
        }
        let canPreview = false;
        const actionKind = action.action.kind;
        if (actionKind) {
          const hierarchicalKind = new $oE(actionKind);
          const refactorKinds = [
            $pab.RefactorExtract,
            $pab.RefactorInline,
            $pab.RefactorRewrite,
            $pab.RefactorMove,
            $pab.Source
          ];
          canPreview = refactorKinds.some((refactorKind) => refactorKind.contains(hierarchicalKind));
        }
        return { canPreview: canPreview || !!action.action.edit?.edits.length };
      },
      onFocus: (action) => {
        if (action && action.action) {
          const ranges = action.action.ranges;
          const diagnostics = action.action.diagnostics;
          currentDecorations.clear();
          if (ranges && ranges.length > 0) {
            const decorations = diagnostics && diagnostics?.length > 1 ? diagnostics.map((diagnostic) => ({ range: diagnostic, options: $fbb_1.G })) : ranges.map((range) => ({ range, options: $fbb_1.G }));
            currentDecorations.set(decorations);
          } else if (diagnostics && diagnostics.length > 0) {
            const decorations = diagnostics.map((diagnostic2) => ({ range: diagnostic2, options: $fbb_1.G }));
            currentDecorations.set(decorations);
            const diagnostic = diagnostics[0];
            if (diagnostic.startLineNumber && diagnostic.startColumn) {
              const selectionText = this.a.getModel()?.getWordAtPosition({ lineNumber: diagnostic.startLineNumber, column: diagnostic.startColumn })?.word;
              $_Z(localize(938, null, selectionText, diagnostic.startLineNumber, diagnostic.startColumn));
            }
          }
        } else {
          currentDecorations.clear();
        }
      }
    };
    this.r.show("codeActionWidget", true, $abb(actionsToShow, this.I(), this.h.getResolver()), delegate, anchor, editorDom, this.J(actions, at, options3));
  }
  H(position) {
    if (!this.a.hasModel()) {
      return { x: 0, y: 0 };
    }
    this.a.revealPosition(
      position,
      1
      /* ScrollType.Immediate */
    );
    this.a.render();
    const cursorCoords = this.a.getScrolledVisiblePosition(position);
    const editorCoords = $vj(this.a.getDomNode());
    const x = editorCoords.left + cursorCoords.left;
    const y = editorCoords.top + cursorCoords.top + cursorCoords.height;
    return { x, y };
  }
  I() {
    const model = this.a?.getModel();
    return this.n.getValue("editor.codeActionWidget.showHeaders", { resource: model?.uri });
  }
  J(actions, at, options3) {
    if (options3.fromLightbulb) {
      return [];
    }
    const resultActions = actions.documentation.map((command4) => ({
      id: command4.id,
      label: command4.title,
      tooltip: command4.tooltip ?? "",
      class: void 0,
      enabled: true,
      run: () => this.m.executeCommand(command4.id, ...command4.arguments ?? [])
    }));
    if (options3.includeDisabledActions && actions.validActions.length > 0 && actions.allActions.length !== actions.validActions.length) {
      resultActions.push(this.g ? {
        id: "hideMoreActions",
        label: localize(939, null),
        enabled: true,
        tooltip: "",
        class: void 0,
        run: () => {
          this.g = false;
          return this.showCodeActionList(actions, at, options3);
        }
      } : {
        id: "showMoreActions",
        label: localize(940, null),
        enabled: true,
        tooltip: "",
        class: void 0,
        run: () => {
          this.g = true;
          return this.showCodeActionList(actions, at, options3);
        }
      });
    }
    return resultActions;
  }
};
$fbb = $fbb_1 = __decorate([
  __param(1, $DE),
  __param(2, $on),
  __param(3, $Pk),
  __param(4, $mP),
  __param(5, $ZJ),
  __param(6, $sn),
  __param(7, $kl),
  __param(8, $dab),
  __param(9, $Pk),
  __param(10, $zv),
  __param(11, $ZJ)
], $fbb);
$ms((theme, collector) => {
  const addBackgroundColorRule = (selector, color2) => {
    if (color2) {
      collector.addRule(`.monaco-editor ${selector} { background-color: ${color2}; }`);
    }
  };
  addBackgroundColorRule(".quickfix-edit-highlight", theme.getColor($cp));
  const findMatchHighlightBorder = theme.getColor($gp);
  if (findMatchHighlightBorder) {
    collector.addRule(`.monaco-editor .quickfix-edit-highlight { border: 1px ${$es(theme.type) ? "dotted" : "solid"} ${findMatchHighlightBorder}; box-sizing: border-box; }`);
  }
});

// out-build/vs/editor/contrib/codeAction/browser/codeActionCommands.js
function contextKeyForSupportedActions(kind) {
  return $7m.regex($cbb.keys()[0], new RegExp("(\\s|^)" + $Af(kind.value) + "\\b"));
}
var argsSchema = {
  type: "object",
  defaultSnippets: [{ body: { kind: "" } }],
  properties: {
    "kind": {
      type: "string",
      description: localize(906, null)
    },
    "apply": {
      type: "string",
      description: localize(907, null),
      default: "ifSingle",
      enum: [
        "first",
        "ifSingle",
        "never"
        /* CodeActionAutoApply.Never */
      ],
      enumDescriptions: [
        localize(908, null),
        localize(909, null),
        localize(910, null)
      ]
    },
    "preferred": {
      type: "boolean",
      default: false,
      description: localize(911, null)
    }
  }
};
function triggerCodeActionsForEditorSelection(editor, notAvailableMessage, filter, autoApply, triggerAction = CodeActionTriggerSource.Default) {
  if (editor.hasModel()) {
    const controller = $fbb.get(editor);
    controller?.manualTriggerAtCurrentPosition(notAvailableMessage, triggerAction, filter, autoApply);
  }
}
var $gbb = class extends $Z5 {
  constructor() {
    super({
      id: $vab,
      label: localize2(928, "Quick Fix..."),
      precondition: $7m.and(EditorContextKeys.writable, EditorContextKeys.hasCodeActionsProvider),
      kbOpts: {
        kbExpr: EditorContextKeys.textInputFocus,
        primary: 2048 | 89,
        weight: 100
        /* KeybindingWeight.EditorContrib */
      }
    });
  }
  run(_accessor, editor) {
    return triggerCodeActionsForEditorSelection(editor, localize(912, null), void 0, void 0, CodeActionTriggerSource.QuickFix);
  }
};
var $hbb = class extends $Y5 {
  constructor() {
    super({
      id: $uab,
      precondition: $7m.and(EditorContextKeys.writable, EditorContextKeys.hasCodeActionsProvider),
      metadata: {
        description: "Trigger a code action",
        args: [{ name: "args", schema: argsSchema }]
      }
    });
  }
  runEditorCommand(_accessor, editor, userArgs) {
    const args2 = $sab.fromUser(userArgs, {
      kind: $oE.Empty,
      apply: "ifSingle"
    });
    return triggerCodeActionsForEditorSelection(editor, typeof userArgs?.kind === "string" ? args2.preferred ? localize(913, null, userArgs.kind) : localize(914, null, userArgs.kind) : args2.preferred ? localize(915, null) : localize(916, null), {
      include: args2.kind,
      includeSourceActions: true,
      onlyIncludePreferredActions: args2.preferred
    }, args2.apply);
  }
};
var $ibb = class extends $Z5 {
  constructor() {
    super({
      id: $xab,
      label: localize2(929, "Refactor..."),
      precondition: $7m.and(EditorContextKeys.writable, EditorContextKeys.hasCodeActionsProvider),
      kbOpts: {
        kbExpr: EditorContextKeys.textInputFocus,
        primary: 2048 | 1024 | 48,
        mac: {
          primary: 256 | 1024 | 48
          /* KeyCode.KeyR */
        },
        weight: 100
        /* KeybindingWeight.EditorContrib */
      },
      contextMenuOpts: {
        group: "1_modification",
        order: 2,
        when: $7m.and(EditorContextKeys.writable, contextKeyForSupportedActions($pab.Refactor))
      },
      metadata: {
        description: "Refactor...",
        args: [{ name: "args", schema: argsSchema }]
      }
    });
  }
  run(_accessor, editor, userArgs) {
    const args2 = $sab.fromUser(userArgs, {
      kind: $pab.Refactor,
      apply: "never"
      /* CodeActionAutoApply.Never */
    });
    return triggerCodeActionsForEditorSelection(editor, typeof userArgs?.kind === "string" ? args2.preferred ? localize(917, null, userArgs.kind) : localize(918, null, userArgs.kind) : args2.preferred ? localize(919, null) : localize(920, null), {
      include: $pab.Refactor.contains(args2.kind) ? args2.kind : $oE.None,
      onlyIncludePreferredActions: args2.preferred
    }, args2.apply, CodeActionTriggerSource.Refactor);
  }
};
var $jbb = class extends $Z5 {
  constructor() {
    super({
      id: $zab,
      label: localize2(930, "Source Action..."),
      precondition: $7m.and(EditorContextKeys.writable, EditorContextKeys.hasCodeActionsProvider),
      contextMenuOpts: {
        group: "1_modification",
        order: 2.1,
        when: $7m.and(EditorContextKeys.writable, contextKeyForSupportedActions($pab.Source))
      },
      metadata: {
        description: "Source Action...",
        args: [{ name: "args", schema: argsSchema }]
      }
    });
  }
  run(_accessor, editor, userArgs) {
    const args2 = $sab.fromUser(userArgs, {
      kind: $pab.Source,
      apply: "never"
      /* CodeActionAutoApply.Never */
    });
    return triggerCodeActionsForEditorSelection(editor, typeof userArgs?.kind === "string" ? args2.preferred ? localize(921, null, userArgs.kind) : localize(922, null, userArgs.kind) : args2.preferred ? localize(923, null) : localize(924, null), {
      include: $pab.Source.contains(args2.kind) ? args2.kind : $oE.None,
      includeSourceActions: true,
      onlyIncludePreferredActions: args2.preferred
    }, args2.apply, CodeActionTriggerSource.SourceAction);
  }
};
var $kbb = class extends $Z5 {
  constructor() {
    super({
      id: $Aab,
      label: localize2(931, "Organize Imports"),
      precondition: $7m.and(EditorContextKeys.writable, contextKeyForSupportedActions($pab.SourceOrganizeImports)),
      kbOpts: {
        kbExpr: EditorContextKeys.textInputFocus,
        primary: 1024 | 512 | 45,
        weight: 100
        /* KeybindingWeight.EditorContrib */
      },
      metadata: {
        description: localize2(932, "Organize imports in the current file. Also called 'Optimize Imports' by some tools")
      }
    });
  }
  run(_accessor, editor) {
    return triggerCodeActionsForEditorSelection(editor, localize(925, null), { include: $pab.SourceOrganizeImports, includeSourceActions: true }, "ifSingle", CodeActionTriggerSource.OrganizeImports);
  }
};
var $lbb = class extends $Z5 {
  constructor() {
    super({
      id: $Bab,
      label: localize2(933, "Fix All"),
      precondition: $7m.and(EditorContextKeys.writable, contextKeyForSupportedActions($pab.SourceFixAll))
    });
  }
  run(_accessor, editor) {
    return triggerCodeActionsForEditorSelection(editor, localize(926, null), { include: $pab.SourceFixAll, includeSourceActions: true }, "ifSingle", CodeActionTriggerSource.FixAll);
  }
};
var $mbb = class extends $Z5 {
  constructor() {
    super({
      id: $wab,
      label: localize2(934, "Auto Fix..."),
      precondition: $7m.and(EditorContextKeys.writable, contextKeyForSupportedActions($pab.QuickFix)),
      kbOpts: {
        kbExpr: EditorContextKeys.textInputFocus,
        primary: 512 | 1024 | 89,
        mac: {
          primary: 2048 | 512 | 89
          /* KeyCode.Period */
        },
        weight: 100
        /* KeybindingWeight.EditorContrib */
      }
    });
  }
  run(_accessor, editor) {
    return triggerCodeActionsForEditorSelection(editor, localize(927, null), {
      include: $pab.QuickFix,
      onlyIncludePreferredActions: true
    }, "ifSingle", CodeActionTriggerSource.AutoFix);
  }
};

// out-build/vs/editor/contrib/codeAction/browser/codeActionContributions.js
$85(
  $fbb.ID,
  $fbb,
  3
  /* EditorContributionInstantiation.Eventually */
);
$85(
  $bbb.ID,
  $bbb,
  4
  /* EditorContributionInstantiation.Lazy */
);
$55($gbb);
$55($ibb);
$55($jbb);
$55($kbb);
$55($mbb);
$55($lbb);
$45(new $hbb());
$Wn.as($Ht.Configuration).registerConfiguration({
  ...$mab,
  properties: {
    "editor.codeActionWidget.showHeaders": {
      type: "boolean",
      scope: 5,
      description: localize(935, null),
      default: true
    }
  }
});
$Wn.as($Ht.Configuration).registerConfiguration({
  ...$mab,
  properties: {
    "editor.codeActionWidget.includeNearbyQuickFixes": {
      type: "boolean",
      scope: 5,
      description: localize(936, null),
      default: true
    }
  }
});
$Wn.as($Ht.Configuration).registerConfiguration({
  ...$mab,
  properties: {
    "editor.codeActions.triggerOnFocusChange": {
      type: "boolean",
      scope: 5,
      markdownDescription: localize(937, null, "`#editor.codeActionsOnSave#`", "`#files.autoSave#`", "`afterDelay`", "`always`"),
      default: false
    }
  }
});

// out-build/vs/editor/contrib/codelens/browser/codelens.js
var $nbb = class {
  constructor() {
    this.lenses = [];
    this.c = new $2c();
  }
  dispose() {
    this.c.dispose();
  }
  get isDisposed() {
    return this.c.isDisposed;
  }
  add(list2, provider) {
    this.c.add(list2);
    for (const symbol of list2.lenses) {
      this.lenses.push({ symbol, provider });
    }
  }
};
async function $obb(registry4, model, token) {
  const provider = registry4.ordered(model);
  const providerRanks = /* @__PURE__ */ new Map();
  const result = new $nbb();
  const promises = provider.map(async (provider2, i2) => {
    providerRanks.set(provider2, i2);
    try {
      const list2 = await Promise.resolve(provider2.provideCodeLenses(model, token));
      if (list2) {
        result.add(list2, provider2);
      }
    } catch (err) {
      $hb(err);
    }
  });
  await Promise.all(promises);
  result.lenses = result.lenses.sort((a, b) => {
    if (a.symbol.range.startLineNumber < b.symbol.range.startLineNumber) {
      return -1;
    } else if (a.symbol.range.startLineNumber > b.symbol.range.startLineNumber) {
      return 1;
    } else if (providerRanks.get(a.provider) < providerRanks.get(b.provider)) {
      return -1;
    } else if (providerRanks.get(a.provider) > providerRanks.get(b.provider)) {
      return 1;
    } else if (a.symbol.range.startColumn < b.symbol.range.startColumn) {
      return -1;
    } else if (a.symbol.range.startColumn > b.symbol.range.startColumn) {
      return 1;
    } else {
      return 0;
    }
  });
  return result;
}
$tn.registerCommand("_executeCodeLensProvider", function(accessor, ...args2) {
  let [uri, itemResolveCount] = args2;
  $Jg(URI.isUri(uri));
  $Jg(typeof itemResolveCount === "number" || !itemResolveCount);
  const { codeLensProvider } = accessor.get($mP);
  const model = accessor.get($sG).getModel(uri);
  if (!model) {
    throw $nb();
  }
  const result = [];
  const disposables = new $2c();
  return $obb(codeLensProvider, model, CancellationToken.None).then((value) => {
    disposables.add(value);
    const resolve = [];
    for (const item of value.lenses) {
      if (itemResolveCount === void 0 || itemResolveCount === null || Boolean(item.symbol.command)) {
        result.push(item.symbol);
      } else if (itemResolveCount-- > 0 && item.provider.resolveCodeLens) {
        resolve.push(Promise.resolve(item.provider.resolveCodeLens(model, item.symbol, CancellationToken.None)).then((symbol) => result.push(symbol || item.symbol)));
      }
    }
    return Promise.all(resolve);
  }).then(() => {
    return result;
  }).finally(() => {
    setTimeout(() => disposables.dispose(), 100);
  });
});

// out-build/vs/editor/contrib/codelens/browser/codeLensCache.js
var $pbb = $Qk("ICodeLensCache");
var CacheItem = class {
  constructor(lineCount, data) {
    this.lineCount = lineCount;
    this.data = data;
  }
};
var $qbb = class $qbb2 {
  constructor(storageService) {
    this.a = new class {
      provideCodeLenses() {
        throw new Error("not supported");
      }
    }();
    this.b = new $Hc(20, 0.75);
    const oldkey = "codelens/cache";
    $gj($Y, () => storageService.remove(
      oldkey,
      1
      /* StorageScope.WORKSPACE */
    ));
    const key2 = "codelens/cache2";
    const raw = storageService.get(key2, 1, "{}");
    this.f(raw);
    const onWillSaveStateBecauseOfShutdown = Event2.filter(storageService.onWillSaveState, (e) => e.reason === WillSaveStateReason.SHUTDOWN);
    Event2.once(onWillSaveStateBecauseOfShutdown)((e) => {
      storageService.store(
        key2,
        this.c(),
        1,
        1
        /* StorageTarget.MACHINE */
      );
    });
  }
  put(model, data) {
    const copyItems = data.lenses.map((item2) => {
      return {
        range: item2.symbol.range,
        command: item2.symbol.command && { id: "", title: item2.symbol.command?.title }
      };
    });
    const copyModel = new $nbb();
    copyModel.add({ lenses: copyItems, dispose: () => {
    } }, this.a);
    const item = new CacheItem(model.getLineCount(), copyModel);
    this.b.set(model.uri.toString(), item);
  }
  get(model) {
    const item = this.b.get(model.uri.toString());
    return item && item.lineCount === model.getLineCount() ? item.data : void 0;
  }
  delete(model) {
    this.b.delete(model.uri.toString());
  }
  // --- persistence
  c() {
    const data = /* @__PURE__ */ Object.create(null);
    for (const [key2, value] of this.b) {
      const lines = /* @__PURE__ */ new Set();
      for (const d of value.data.lenses) {
        lines.add(d.symbol.range.startLineNumber);
      }
      data[key2] = {
        lineCount: value.lineCount,
        lines: [...lines.values()]
      };
    }
    return JSON.stringify(data);
  }
  f(raw) {
    try {
      const data = JSON.parse(raw);
      for (const key2 in data) {
        const element = data[key2];
        const lenses = [];
        for (const line of element.lines) {
          lenses.push({ range: new $9C(line, 1, line, 11) });
        }
        const model = new $nbb();
        model.add({ lenses, dispose() {
        } }, this.a);
        this.b.set(key2, new CacheItem(element.lineCount, model));
      }
    } catch {
    }
  }
};
$qbb = __decorate([
  __param(0, $jv)
], $qbb);
$SC(
  $pbb,
  $qbb,
  1
  /* InstantiationType.Delayed */
);

// out-build/vs/editor/contrib/codelens/browser/codelensWidget.js
var CodeLensViewZone = class {
  constructor(afterLineNumber, heightInPx, onHeight) {
    this.afterColumn = 1073741824;
    this.afterLineNumber = afterLineNumber;
    this.heightInPx = heightInPx;
    this.b = onHeight;
    this.suppressMouseDown = true;
    this.domNode = document.createElement("div");
  }
  onComputedHeight(height) {
    if (this.a === void 0) {
      this.a = height;
    } else if (this.a !== height) {
      this.a = height;
      this.b();
    }
  }
  isVisible() {
    return this.a !== 0 && this.domNode.hasAttribute("monaco-visible-view-zone");
  }
};
var CodeLensContentWidget = class _CodeLensContentWidget {
  static {
    this.a = 0;
  }
  constructor(editor, line) {
    this.allowEditorOverflow = false;
    this.suppressMouseDown = true;
    this.e = /* @__PURE__ */ new Map();
    this.g = true;
    this.d = editor;
    this.b = `codelens.widget-${_CodeLensContentWidget.a++}`;
    this.updatePosition(line);
    this.c = document.createElement("span");
    this.c.className = `codelens-decoration`;
  }
  withCommands(lenses, animate) {
    this.e.clear();
    const children = [];
    let hasSymbol = false;
    for (let i2 = 0; i2 < lenses.length; i2++) {
      const lens = lenses[i2];
      if (!lens) {
        continue;
      }
      hasSymbol = true;
      if (lens.command) {
        const title = $B1(lens.command.title.trim());
        if (lens.command.id) {
          const id2 = `c${_CodeLensContentWidget.a++}`;
          children.push($("a", { id: id2, title: lens.command.tooltip, role: "button" }, ...title));
          this.e.set(id2, lens.command);
        } else {
          children.push($("span", { title: lens.command.tooltip }, ...title));
        }
        if (i2 + 1 < lenses.length) {
          children.push($("span", void 0, "\xA0|\xA0"));
        }
      }
    }
    if (!hasSymbol) {
      $dk(this.c, $("span", void 0, "no commands"));
    } else {
      $dk(this.c, ...children);
      if (this.g && animate) {
        this.c.classList.add("fadein");
      }
      this.g = false;
    }
  }
  getCommand(link2) {
    return link2.parentElement === this.c ? this.e.get(link2.id) : void 0;
  }
  getId() {
    return this.b;
  }
  getDomNode() {
    return this.c;
  }
  updatePosition(line) {
    const column = this.d.getModel().getLineFirstNonWhitespaceColumn(line);
    this.f = {
      position: { lineNumber: line, column },
      preference: [
        1
        /* ContentWidgetPositionPreference.ABOVE */
      ]
    };
  }
  getPosition() {
    return this.f || null;
  }
};
var $rbb = class {
  constructor() {
    this.a = [];
    this.b = [];
    this.c = [];
  }
  addDecoration(decoration3, callback) {
    this.b.push(decoration3);
    this.c.push(callback);
  }
  removeDecoration(decorationId) {
    this.a.push(decorationId);
  }
  commit(changeAccessor) {
    const resultingDecorations = changeAccessor.deltaDecorations(this.a, this.b);
    for (let i2 = 0, len = resultingDecorations.length; i2 < len; i2++) {
      this.c[i2](resultingDecorations[i2]);
    }
  }
};
var codeLensDecorationOptions = $WI.register({
  collapseOnReplaceEdit: true,
  description: "codelens"
});
var $sbb = class {
  constructor(data, editor, helper, viewZoneChangeAccessor, heightInPx, updateCallback) {
    this.g = false;
    this.a = editor;
    this.f = data;
    this.e = [];
    let range;
    const lenses = [];
    this.f.forEach((codeLensData, i2) => {
      if (codeLensData.symbol.command) {
        lenses.push(codeLensData.symbol);
      }
      helper.addDecoration({
        range: codeLensData.symbol.range,
        options: codeLensDecorationOptions
      }, (id2) => this.e[i2] = id2);
      if (!range) {
        range = $9C.lift(codeLensData.symbol.range);
      } else {
        range = $9C.plusRange(range, codeLensData.symbol.range);
      }
    });
    this.b = new CodeLensViewZone(range.startLineNumber - 1, heightInPx, updateCallback);
    this.c = viewZoneChangeAccessor.addZone(this.b);
    if (lenses.length > 0) {
      this.h();
      this.d.withCommands(lenses, false);
    }
  }
  h() {
    if (!this.d) {
      this.d = new CodeLensContentWidget(this.a, this.b.afterLineNumber + 1);
      this.a.addContentWidget(this.d);
    } else {
      this.a.layoutContentWidget(this.d);
    }
  }
  dispose(helper, viewZoneChangeAccessor) {
    this.e.forEach(helper.removeDecoration, helper);
    this.e = [];
    viewZoneChangeAccessor?.removeZone(this.c);
    if (this.d) {
      this.a.removeContentWidget(this.d);
      this.d = void 0;
    }
    this.g = true;
  }
  isDisposed() {
    return this.g;
  }
  isValid() {
    return this.e.some((id2, i2) => {
      const range = this.a.getModel().getDecorationRange(id2);
      const symbol = this.f[i2].symbol;
      return !!(range && $9C.isEmpty(symbol.range) === range.isEmpty());
    });
  }
  updateCodeLensSymbols(data, helper) {
    this.e.forEach(helper.removeDecoration, helper);
    this.e = [];
    this.f = data;
    this.f.forEach((codeLensData, i2) => {
      helper.addDecoration({
        range: codeLensData.symbol.range,
        options: codeLensDecorationOptions
      }, (id2) => this.e[i2] = id2);
    });
  }
  updateHeight(height, viewZoneChangeAccessor) {
    this.b.heightInPx = height;
    viewZoneChangeAccessor.layoutZone(this.c);
    if (this.d) {
      this.a.layoutContentWidget(this.d);
    }
  }
  computeIfNecessary(model) {
    if (!this.b.isVisible()) {
      return null;
    }
    for (let i2 = 0; i2 < this.e.length; i2++) {
      const range = model.getDecorationRange(this.e[i2]);
      if (range) {
        this.f[i2].symbol.range = range;
      }
    }
    return this.f;
  }
  updateCommands(symbols) {
    this.h();
    this.d.withCommands(symbols, true);
    for (let i2 = 0; i2 < this.f.length; i2++) {
      const resolved = symbols[i2];
      if (resolved) {
        const { symbol } = this.f[i2];
        symbol.command = resolved.command || symbol.command;
      }
    }
  }
  getCommand(link2) {
    return this.d?.getCommand(link2);
  }
  getLineNumber() {
    const range = this.a.getModel().getDecorationRange(this.e[0]);
    if (range) {
      return range.startLineNumber;
    }
    return -1;
  }
  update(viewZoneChangeAccessor) {
    if (this.isValid()) {
      const range = this.a.getModel().getDecorationRange(this.e[0]);
      if (range) {
        this.b.afterLineNumber = range.startLineNumber - 1;
        viewZoneChangeAccessor.layoutZone(this.c);
        if (this.d) {
          this.d.updatePosition(range.startLineNumber);
          this.a.layoutContentWidget(this.d);
        }
      }
    }
  }
  getItems() {
    return this.f;
  }
};

// out-build/vs/editor/common/services/languageFeatureDebounce.js
var $tbb = $Qk("ILanguageFeatureDebounceService");
var IdentityHash;
(function(IdentityHash2) {
  const _hashes = /* @__PURE__ */ new WeakMap();
  let pool = 0;
  function of(obj) {
    let value = _hashes.get(obj);
    if (value === void 0) {
      value = ++pool;
      _hashes.set(obj, value);
    }
    return value;
  }
  IdentityHash2.of = of;
})(IdentityHash || (IdentityHash = {}));
var NullDebounceInformation = class {
  constructor(a) {
    this.a = a;
  }
  get(_model) {
    return this.a;
  }
  update(_model, _value) {
    return this.a;
  }
  default() {
    return this.a;
  }
};
var FeatureDebounceInformation = class {
  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 = new $Hc(50, 0.7);
  }
  h(model) {
    return model.id + this.d.all(model).reduce((hashVal, obj) => $Yi(IdentityHash.of(obj), hashVal), 0);
  }
  get(model) {
    const key2 = this.h(model);
    const avg = this.a.get(key2);
    return avg ? $4i(avg.value, this.f, this.g) : this.default();
  }
  update(model, value) {
    const key2 = this.h(model);
    let avg = this.a.get(key2);
    if (!avg) {
      avg = new $8i(6);
      this.a.set(key2, avg);
    }
    const newValue = $4i(avg.update(value), this.f, this.g);
    if (!$0g(model.uri, "output")) {
      this.b.trace(`[DEBOUNCE: ${this.c}] for ${model.uri.toString()} is ${newValue}ms`);
    }
    return newValue;
  }
  i() {
    const result = new $7i();
    for (const [, avg] of this.a) {
      result.update(avg.value);
    }
    return result.value;
  }
  default() {
    const value = this.i() | 0 || this.e;
    return $4i(value, this.f, this.g);
  }
};
var $ubb = class $ubb2 {
  constructor(c, envService) {
    this.c = c;
    this.a = /* @__PURE__ */ new Map();
    this.b = envService.isExtensionDevelopment || !envService.isBuilt;
  }
  for(feature, name, config) {
    const min = config?.min ?? 50;
    const max = config?.max ?? min ** 2;
    const extra = config?.key ?? void 0;
    const key2 = `${IdentityHash.of(feature)},${min}${extra ? "," + extra : ""}`;
    let info = this.a.get(key2);
    if (!info) {
      if (this.b) {
        this.c.debug(`[DEBOUNCE: ${name}] is disabled in developed mode`);
        info = new NullDebounceInformation(min * 1.5);
      } else {
        info = new FeatureDebounceInformation(
          this.c,
          name,
          feature,
          this.d() | 0 || min * 1.5,
          // default is overall default or derived from min-value
          min,
          max
        );
      }
      this.a.set(key2, info);
    }
    return info;
  }
  d() {
    const result = new $7i();
    for (const info of this.a.values()) {
      result.update(info.default());
    }
    return result.value;
  }
};
$ubb = __decorate([
  __param(0, $wn),
  __param(1, $Xk)
], $ubb);
$SC(
  $tbb,
  $ubb,
  1
  /* InstantiationType.Delayed */
);

// out-build/vs/editor/contrib/codelens/browser/codelensController.js
var $vbb = class $vbb2 {
  static {
    this.ID = "css.editor.codeLens";
  }
  constructor(n, o, debounceService, p, q, r2) {
    this.n = n;
    this.o = o;
    this.p = p;
    this.q = q;
    this.r = r2;
    this.a = new $2c();
    this.b = new $2c();
    this.c = [];
    this.j = new $2c();
    this.d = debounceService.for(o.codeLensProvider, "CodeLensProvide", { min: 250 });
    this.f = debounceService.for(o.codeLensProvider, "CodeLensResolve", { min: 250, salt: "resolve" });
    this.g = new $8h(() => this.z(), this.f.default());
    this.a.add(this.n.onDidChangeModel(() => this.v()));
    this.a.add(this.n.onDidChangeModelLanguage(() => this.v()));
    this.a.add(this.n.onDidChangeConfiguration((e) => {
      if (e.hasChanged(
        52
        /* EditorOption.fontInfo */
      ) || e.hasChanged(
        19
        /* EditorOption.codeLensFontSize */
      ) || e.hasChanged(
        18
        /* EditorOption.codeLensFontFamily */
      )) {
        this.t();
      }
      if (e.hasChanged(
        17
        /* EditorOption.codeLens */
      )) {
        this.v();
      }
    }));
    this.a.add(o.codeLensProvider.onDidChange(this.v, this));
    this.v();
    this.t();
  }
  dispose() {
    this.u();
    this.a.dispose();
    this.j.dispose();
    this.k?.dispose();
  }
  s() {
    const lineHeightFactor = Math.max(1.3, this.n.getOption(
      68
      /* EditorOption.lineHeight */
    ) / this.n.getOption(
      54
      /* EditorOption.fontSize */
    ));
    let fontSize = this.n.getOption(
      19
      /* EditorOption.codeLensFontSize */
    );
    if (!fontSize || fontSize < 5) {
      fontSize = this.n.getOption(
        54
        /* EditorOption.fontSize */
      ) * 0.9 | 0;
    }
    return {
      fontSize,
      codeLensHeight: fontSize * lineHeightFactor | 0
    };
  }
  t() {
    const { codeLensHeight, fontSize } = this.s();
    const fontFamily = this.n.getOption(
      18
      /* EditorOption.codeLensFontFamily */
    );
    const editorFontInfo = this.n.getOption(
      52
      /* EditorOption.fontInfo */
    );
    const { style } = this.n.getContainerDomNode();
    style.setProperty("--vscode-editorCodeLens-lineHeight", `${codeLensHeight}px`);
    style.setProperty("--vscode-editorCodeLens-fontSize", `${fontSize}px`);
    style.setProperty("--vscode-editorCodeLens-fontFeatureSettings", editorFontInfo.fontFeatureSettings);
    if (fontFamily) {
      style.setProperty("--vscode-editorCodeLens-fontFamily", fontFamily);
      style.setProperty("--vscode-editorCodeLens-fontFamilyDefault", EDITOR_FONT_DEFAULTS.fontFamily);
    }
    this.n.changeViewZones((accessor) => {
      for (const lens of this.c) {
        lens.updateHeight(codeLensHeight, accessor);
      }
    });
  }
  u() {
    this.h?.cancel();
    this.h = void 0;
    this.m?.cancel();
    this.m = void 0;
    this.b.clear();
    this.j.clear();
    this.k?.dispose();
  }
  v() {
    this.u();
    const model = this.n.getModel();
    if (!model) {
      return;
    }
    if (!this.n.getOption(
      17
      /* EditorOption.codeLens */
    ) || model.isTooLargeForTokenization()) {
      return;
    }
    const cachedLenses = this.r.get(model);
    if (cachedLenses) {
      this.x(cachedLenses);
    }
    if (!this.o.codeLensProvider.has(model)) {
      if (cachedLenses) {
        $Xh(() => {
          const cachedLensesNow = this.r.get(model);
          if (cachedLenses === cachedLensesNow) {
            this.r.delete(model);
            this.v();
          }
        }, 30 * 1e3, this.b);
      }
      return;
    }
    for (const provider of this.o.codeLensProvider.all(model)) {
      if (typeof provider.onDidChange === "function") {
        const registration = provider.onDidChange(() => scheduler.schedule());
        this.b.add(registration);
      }
    }
    const scheduler = new $8h(() => {
      const t1 = Date.now();
      this.h?.cancel();
      this.h = $Hh((token) => $obb(this.o.codeLensProvider, model, token));
      this.h.then((result) => {
        if (this.k) {
          this.j.add(this.k);
        }
        this.k = result;
        this.r.put(model, result);
        const newDelay = this.d.update(model, Date.now() - t1);
        scheduler.delay = newDelay;
        this.x(result);
        this.y();
      }, $gb);
    }, this.d.get(model));
    this.b.add(scheduler);
    this.b.add($1c(() => this.g.cancel()));
    this.b.add(this.n.onDidChangeModelContent(() => {
      this.n.changeDecorations((decorationsAccessor) => {
        this.n.changeViewZones((viewZonesAccessor) => {
          const toDispose = [];
          let lastLensLineNumber = -1;
          this.c.forEach((lens) => {
            if (!lens.isValid() || lastLensLineNumber === lens.getLineNumber()) {
              toDispose.push(lens);
            } else {
              lens.update(viewZonesAccessor);
              lastLensLineNumber = lens.getLineNumber();
            }
          });
          const helper = new $rbb();
          toDispose.forEach((l) => {
            l.dispose(helper, viewZonesAccessor);
            this.c.splice(this.c.indexOf(l), 1);
          });
          helper.commit(decorationsAccessor);
        });
      });
      scheduler.schedule();
      this.g.cancel();
      this.m?.cancel();
      this.m = void 0;
    }));
    this.b.add(this.n.onDidFocusEditorText(() => {
      scheduler.schedule();
    }));
    this.b.add(this.n.onDidBlurEditorText(() => {
      scheduler.cancel();
    }));
    this.b.add(this.n.onDidScrollChange((e) => {
      if (e.scrollTopChanged && this.c.length > 0) {
        this.y();
      }
    }));
    this.b.add(this.n.onDidLayoutChange(() => {
      this.y();
    }));
    this.b.add($1c(() => {
      if (this.n.getModel()) {
        const scrollState = $O9.capture(this.n);
        this.n.changeDecorations((decorationsAccessor) => {
          this.n.changeViewZones((viewZonesAccessor) => {
            this.w(decorationsAccessor, viewZonesAccessor);
          });
        });
        scrollState.restore(this.n);
      } else {
        this.w(void 0, void 0);
      }
    }));
    this.b.add(this.n.onMouseDown((e) => {
      if (e.target.type !== 9) {
        return;
      }
      let target = e.target.element;
      if (target?.tagName === "SPAN") {
        target = target.parentElement;
      }
      if (target?.tagName === "A") {
        for (const lens of this.c) {
          const command4 = lens.getCommand(target);
          if (command4) {
            this.p.executeCommand(command4.id, ...command4.arguments || []).catch((err) => this.q.error(err));
            break;
          }
        }
      }
    }));
    scheduler.schedule();
  }
  w(decChangeAccessor, viewZoneChangeAccessor) {
    const helper = new $rbb();
    for (const lens of this.c) {
      lens.dispose(helper, viewZoneChangeAccessor);
    }
    if (decChangeAccessor) {
      helper.commit(decChangeAccessor);
    }
    this.c.length = 0;
  }
  x(symbols) {
    if (!this.n.hasModel()) {
      return;
    }
    const maxLineNumber = this.n.getModel().getLineCount();
    const groups = [];
    let lastGroup;
    for (const symbol of symbols.lenses) {
      const line = symbol.symbol.range.startLineNumber;
      if (line < 1 || line > maxLineNumber) {
        continue;
      } else if (lastGroup && lastGroup[lastGroup.length - 1].symbol.range.startLineNumber === line) {
        lastGroup.push(symbol);
      } else {
        lastGroup = [symbol];
        groups.push(lastGroup);
      }
    }
    if (!groups.length && !this.c.length) {
      return;
    }
    const scrollState = $O9.capture(this.n);
    const layoutInfo = this.s();
    this.n.changeDecorations((decorationsAccessor) => {
      this.n.changeViewZones((viewZoneAccessor) => {
        const helper = new $rbb();
        let codeLensIndex = 0;
        let groupsIndex = 0;
        while (groupsIndex < groups.length && codeLensIndex < this.c.length) {
          const symbolsLineNumber = groups[groupsIndex][0].symbol.range.startLineNumber;
          const codeLensLineNumber = this.c[codeLensIndex].getLineNumber();
          if (codeLensLineNumber < symbolsLineNumber) {
            this.c[codeLensIndex].dispose(helper, viewZoneAccessor);
            this.c.splice(codeLensIndex, 1);
          } else if (codeLensLineNumber === symbolsLineNumber) {
            this.c[codeLensIndex].updateCodeLensSymbols(groups[groupsIndex], helper);
            groupsIndex++;
            codeLensIndex++;
          } else {
            this.c.splice(codeLensIndex, 0, new $sbb(groups[groupsIndex], this.n, helper, viewZoneAccessor, layoutInfo.codeLensHeight, () => this.y()));
            codeLensIndex++;
            groupsIndex++;
          }
        }
        while (codeLensIndex < this.c.length) {
          this.c[codeLensIndex].dispose(helper, viewZoneAccessor);
          this.c.splice(codeLensIndex, 1);
        }
        while (groupsIndex < groups.length) {
          this.c.push(new $sbb(groups[groupsIndex], this.n, helper, viewZoneAccessor, layoutInfo.codeLensHeight, () => this.y()));
          groupsIndex++;
        }
        helper.commit(decorationsAccessor);
      });
    });
    scrollState.restore(this.n);
  }
  y() {
    const model = this.n.getModel();
    if (model) {
      this.g.schedule();
    }
  }
  z() {
    this.m?.cancel();
    this.m = void 0;
    const model = this.n.getModel();
    if (!model) {
      return;
    }
    const toResolve = [];
    const lenses = [];
    this.c.forEach((lens) => {
      const request = lens.computeIfNecessary(model);
      if (request) {
        toResolve.push(request);
        lenses.push(lens);
      }
    });
    if (toResolve.length === 0) {
      return;
    }
    const t1 = Date.now();
    const resolvePromise = $Hh((token) => {
      const promises = toResolve.map((request, i2) => {
        const resolvedSymbols = new Array(request.length);
        const promises2 = request.map((request2, i3) => {
          if (!request2.symbol.command && typeof request2.provider.resolveCodeLens === "function") {
            return Promise.resolve(request2.provider.resolveCodeLens(model, request2.symbol, token)).then((symbol) => {
              resolvedSymbols[i3] = symbol;
            }, $hb);
          } else {
            resolvedSymbols[i3] = request2.symbol;
            return Promise.resolve(void 0);
          }
        });
        return Promise.all(promises2).then(() => {
          if (!token.isCancellationRequested && !lenses[i2].isDisposed()) {
            lenses[i2].updateCommands(resolvedSymbols);
          }
        });
      });
      return Promise.all(promises);
    });
    this.m = resolvePromise;
    this.m.then(() => {
      const newDelay = this.f.update(model, Date.now() - t1);
      this.g.delay = newDelay;
      if (this.k) {
        this.r.put(model, this.k);
      }
      this.j.clear();
      if (resolvePromise === this.m) {
        this.m = void 0;
      }
    }, (err) => {
      $gb(err);
      if (resolvePromise === this.m) {
        this.m = void 0;
      }
    });
  }
  async getModel() {
    await this.h;
    await this.m;
    return !this.k?.isDisposed ? this.k : void 0;
  }
};
$vbb = __decorate([
  __param(1, $mP),
  __param(2, $tbb),
  __param(3, $sn),
  __param(4, $PJ),
  __param(5, $pbb)
], $vbb);
$85(
  $vbb.ID,
  $vbb,
  1
  /* EditorContributionInstantiation.AfterFirstRender */
);
$55(class ShowLensesInCurrentLine extends $Z5 {
  constructor() {
    super({
      id: "codelens.showLensesInCurrentLine",
      precondition: EditorContextKeys.hasCodeLensProvider,
      label: localize2(959, "Show CodeLens Commands For Current Line")
    });
  }
  async run(accessor, editor) {
    if (!editor.hasModel()) {
      return;
    }
    const quickInputService = accessor.get($1M);
    const commandService = accessor.get($sn);
    const notificationService = accessor.get($PJ);
    const lineNumber = editor.getSelection().positionLineNumber;
    const codelensController = editor.getContribution($vbb.ID);
    if (!codelensController) {
      return;
    }
    const model = await codelensController.getModel();
    if (!model) {
      return;
    }
    const items = [];
    for (const lens of model.lenses) {
      if (lens.symbol.command && lens.symbol.range.startLineNumber === lineNumber) {
        items.push({
          label: lens.symbol.command.title,
          command: lens.symbol.command
        });
      }
    }
    if (items.length === 0) {
      return;
    }
    const item = await quickInputService.pick(items, {
      canPickMany: false,
      placeHolder: localize(958, null)
    });
    if (!item) {
      return;
    }
    let command4 = item.command;
    if (model.isDisposed) {
      const newModel = await codelensController.getModel();
      const newLens = newModel?.lenses.find((lens) => lens.symbol.range.startLineNumber === lineNumber && lens.symbol.command?.title === command4.title);
      if (!newLens || !newLens.symbol.command) {
        return;
      }
      command4 = newLens.symbol.command;
    }
    try {
      await commandService.executeCommand(command4.id, ...command4.arguments || []);
    } catch (err) {
      notificationService.error(err);
    }
  }
});

// out-build/vs/editor/common/editorFeatures.js
var editorFeatures = [];
function $T_(ctor) {
  editorFeatures.push(ctor);
}
function $U_() {
  return editorFeatures.slice(0);
}

// out-build/vs/editor/contrib/hover/browser/hoverTypes.js
var HoverAnchorType;
(function(HoverAnchorType2) {
  HoverAnchorType2[HoverAnchorType2["Range"] = 1] = "Range";
  HoverAnchorType2[HoverAnchorType2["ForeignElement"] = 2] = "ForeignElement";
})(HoverAnchorType || (HoverAnchorType = {}));
var $ybb = class {
  constructor(priority, range, initialMousePosX, initialMousePosY) {
    this.priority = priority;
    this.range = range;
    this.initialMousePosX = initialMousePosX;
    this.initialMousePosY = initialMousePosY;
    this.type = 1;
  }
  equals(other) {
    return other.type === 1 && this.range.equalsRange(other.range);
  }
  canAdoptVisibleHover(lastAnchor, showAtPosition) {
    return lastAnchor.type === 1 && showAtPosition.lineNumber === this.range.startLineNumber;
  }
};
var $zbb = class {
  constructor(priority, owner, range, initialMousePosX, initialMousePosY, supportsMarkerHover) {
    this.priority = priority;
    this.owner = owner;
    this.range = range;
    this.initialMousePosX = initialMousePosX;
    this.initialMousePosY = initialMousePosY;
    this.supportsMarkerHover = supportsMarkerHover;
    this.type = 2;
  }
  equals(other) {
    return other.type === 2 && this.owner === other.owner;
  }
  canAdoptVisibleHover(lastAnchor, showAtPosition) {
    return lastAnchor.type === 2 && this.owner === lastAnchor.owner;
  }
};
var $Abb = class {
  constructor(renderedHoverParts) {
    this.renderedHoverParts = renderedHoverParts;
  }
  dispose() {
    for (const part of this.renderedHoverParts) {
      part.dispose();
    }
  }
};
var $Bbb = new class HoverParticipantRegistry {
  constructor() {
    this._participants = [];
  }
  register(ctor) {
    this._participants.push(ctor);
  }
  getAll() {
    return this._participants;
  }
}();

// out-build/vs/editor/contrib/colorPicker/browser/defaultDocumentColorProvider.js
var $Cbb = class $Cbb2 {
  constructor(a) {
    this.a = a;
  }
  async provideDocumentColors(model, _token) {
    return this.a.computeDefaultDocumentColors(model.uri);
  }
  provideColorPresentations(_model, colorInfo, _token) {
    const range = colorInfo.range;
    const colorFromInfo = colorInfo.color;
    const alpha = colorFromInfo.alpha;
    const color2 = new $Vn(new $Sn(Math.round(255 * colorFromInfo.red), Math.round(255 * colorFromInfo.green), Math.round(255 * colorFromInfo.blue), alpha));
    const rgb = alpha ? $Vn.Format.CSS.formatRGB(color2) : $Vn.Format.CSS.formatRGBA(color2);
    const hsl = alpha ? $Vn.Format.CSS.formatHSL(color2) : $Vn.Format.CSS.formatHSLA(color2);
    const hex = alpha ? $Vn.Format.CSS.formatHex(color2) : $Vn.Format.CSS.formatHexA(color2);
    const colorPresentations = [];
    colorPresentations.push({ label: rgb, textEdit: { range, text: rgb } });
    colorPresentations.push({ label: hsl, textEdit: { range, text: hsl } });
    colorPresentations.push({ label: hex, textEdit: { range, text: hex } });
    return colorPresentations;
  }
};
$Cbb = __decorate([
  __param(0, $I0)
], $Cbb);
var $Dbb = class $Dbb2 extends $3c {
  constructor(_languageFeaturesService, editorWorkerService) {
    super();
    this.B(_languageFeaturesService.colorProvider.register("*", new $Cbb(editorWorkerService)));
  }
};
$Dbb = __decorate([
  __param(0, $mP),
  __param(1, $I0)
], $Dbb);

// out-build/vs/editor/contrib/colorPicker/browser/color.js
async function $Ebb(colorProviderRegistry, model, token, defaultColorDecoratorsEnablement = "auto") {
  return $Ibb(new ColorDataCollector(), colorProviderRegistry, model, token, defaultColorDecoratorsEnablement);
}
function $Fbb(model, colorInfo, provider, token) {
  return Promise.resolve(provider.provideColorPresentations(model, colorInfo, token));
}
var ColorDataCollector = class {
  constructor() {
  }
  async compute(provider, model, token, colors) {
    const documentColors = await provider.provideDocumentColors(model, token);
    if (Array.isArray(documentColors)) {
      for (const colorInfo of documentColors) {
        colors.push({ colorInfo, provider });
      }
    }
    return Array.isArray(documentColors);
  }
};
var $Gbb = class {
  constructor() {
  }
  async compute(provider, model, token, colors) {
    const documentColors = await provider.provideDocumentColors(model, token);
    if (Array.isArray(documentColors)) {
      for (const colorInfo of documentColors) {
        colors.push({ range: colorInfo.range, color: [colorInfo.color.red, colorInfo.color.green, colorInfo.color.blue, colorInfo.color.alpha] });
      }
    }
    return Array.isArray(documentColors);
  }
};
var $Hbb = class {
  constructor(a) {
    this.a = a;
  }
  async compute(provider, model, _token, colors) {
    const documentColors = await provider.provideColorPresentations(model, this.a, CancellationToken.None);
    if (Array.isArray(documentColors)) {
      colors.push(...documentColors);
    }
    return Array.isArray(documentColors);
  }
};
async function $Ibb(collector, colorProviderRegistry, model, token, defaultColorDecoratorsEnablement) {
  let validDocumentColorProviderFound = false;
  let defaultProvider;
  const colorData = [];
  const documentColorProviders = colorProviderRegistry.ordered(model);
  for (let i2 = documentColorProviders.length - 1; i2 >= 0; i2--) {
    const provider = documentColorProviders[i2];
    if (defaultColorDecoratorsEnablement !== "always" && provider instanceof $Cbb) {
      defaultProvider = provider;
    } else {
      try {
        if (await collector.compute(provider, model, token, colorData)) {
          validDocumentColorProviderFound = true;
        }
      } catch (e) {
        $hb(e);
      }
    }
  }
  if (validDocumentColorProviderFound) {
    return colorData;
  }
  if (defaultProvider && defaultColorDecoratorsEnablement !== "never") {
    await collector.compute(defaultProvider, model, token, colorData);
    return colorData;
  }
  return [];
}
function $Jbb(accessor, resource) {
  const { colorProvider: colorProviderRegistry } = accessor.get($mP);
  const model = accessor.get($sG).getModel(resource);
  if (!model) {
    throw $nb();
  }
  const defaultColorDecoratorsEnablement = accessor.get($kl).getValue("editor.defaultColorDecorators", { resource });
  return { model, colorProviderRegistry, defaultColorDecoratorsEnablement };
}

// out-build/vs/editor/contrib/colorPicker/browser/colorDetector.js
var $Lbb_1;
var $Kbb = /* @__PURE__ */ Object.create({});
var $Lbb = class $Lbb2 extends $3c {
  static {
    $Lbb_1 = this;
  }
  static {
    this.ID = "editor.contrib.colorDetector";
  }
  static {
    this.RECOMPUTE_TIME = 1e3;
  }
  // ms
  constructor(C, D, F, languageFeatureDebounceService) {
    super();
    this.C = C;
    this.D = D;
    this.F = F;
    this.f = this.B(new $2c());
    this.n = [];
    this.s = /* @__PURE__ */ new Map();
    this.t = this.C.createDecorationsCollection();
    this.y = new $86(this.C);
    this.z = new $Mbb();
    this.L = this.B(new $2c());
    this.m = languageFeatureDebounceService.for(F.colorProvider, "Document Colors", { min: $Lbb_1.RECOMPUTE_TIME });
    this.B(C.onDidChangeModel(() => {
      this.u = this.isEnabled();
      this.G();
    }));
    this.B(C.onDidChangeModelLanguage(() => this.G()));
    this.B(F.colorProvider.onDidChange(() => this.G()));
    this.B(C.onDidChangeConfiguration((e) => {
      const prevIsEnabled = this.u;
      this.u = this.isEnabled();
      this.w = this.C.getOption(
        153
        /* EditorOption.defaultColorDecorators */
      );
      const updatedColorDecoratorsSetting = prevIsEnabled !== this.u || e.hasChanged(
        21
        /* EditorOption.colorDecoratorsLimit */
      );
      const updatedDefaultColorDecoratorsSetting = e.hasChanged(
        153
        /* EditorOption.defaultColorDecorators */
      );
      if (updatedColorDecoratorsSetting || updatedDefaultColorDecoratorsSetting) {
        if (this.u) {
          this.G();
        } else {
          this.N();
        }
      }
    }));
    this.j = null;
    this.h = null;
    this.u = this.isEnabled();
    this.w = this.C.getOption(
      153
      /* EditorOption.defaultColorDecorators */
    );
    this.G();
  }
  isEnabled() {
    const model = this.C.getModel();
    if (!model) {
      return false;
    }
    const languageId = model.getLanguageId();
    const deprecatedConfig = this.D.getValue(languageId);
    if (deprecatedConfig && typeof deprecatedConfig === "object") {
      const colorDecorators = deprecatedConfig["colorDecorators"];
      if (colorDecorators && colorDecorators["enable"] !== void 0 && !colorDecorators["enable"]) {
        return colorDecorators["enable"];
      }
    }
    return this.C.getOption(
      20
      /* EditorOption.colorDecorators */
    );
  }
  get limitReporter() {
    return this.z;
  }
  static get(editor) {
    return editor.getContribution(this.ID);
  }
  dispose() {
    this.I();
    this.N();
    super.dispose();
  }
  G() {
    this.I();
    if (!this.u) {
      return;
    }
    const model = this.C.getModel();
    if (!model || !this.F.colorProvider.has(model)) {
      return;
    }
    this.f.add(this.C.onDidChangeModelContent(() => {
      if (!this.j) {
        this.j = new $6h();
        this.j.cancelAndSet(() => {
          this.j = null;
          this.H();
        }, this.m.get(model));
      }
    }));
    this.H();
  }
  async H() {
    this.h = $Hh(async (token) => {
      const model = this.C.getModel();
      if (!model) {
        return [];
      }
      const sw = new $te(false);
      const colors = await $Ebb(this.F.colorProvider, model, token, this.w);
      this.m.update(model, sw.elapsed());
      return colors;
    });
    try {
      const colors = await this.h;
      this.J(colors);
      this.M(colors);
      this.h = null;
    } catch (e) {
      $gb(e);
    }
  }
  I() {
    if (this.j) {
      this.j.cancel();
      this.j = null;
    }
    if (this.h) {
      this.h.cancel();
      this.h = null;
    }
    this.f.clear();
  }
  J(colorDatas) {
    const decorations = colorDatas.map((c) => ({
      range: {
        startLineNumber: c.colorInfo.range.startLineNumber,
        startColumn: c.colorInfo.range.startColumn,
        endLineNumber: c.colorInfo.range.endLineNumber,
        endColumn: c.colorInfo.range.endColumn
      },
      options: $WI.EMPTY
    }));
    this.C.changeDecorations((changeAccessor) => {
      this.n = changeAccessor.deltaDecorations(this.n, decorations);
      this.s = /* @__PURE__ */ new Map();
      this.n.forEach((id2, i2) => this.s.set(id2, colorDatas[i2]));
    });
  }
  M(colorData) {
    this.L.clear();
    const decorations = [];
    const limit = this.C.getOption(
      21
      /* EditorOption.colorDecoratorsLimit */
    );
    for (let i2 = 0; i2 < colorData.length && decorations.length < limit; i2++) {
      const { red, green, blue, alpha } = colorData[i2].colorInfo.color;
      const rgba = new $Sn(Math.round(red * 255), Math.round(green * 255), Math.round(blue * 255), alpha);
      const color2 = `rgba(${rgba.r}, ${rgba.g}, ${rgba.b}, ${rgba.a})`;
      const ref = this.L.add(this.y.createClassNameRef({
        backgroundColor: color2
      }));
      decorations.push({
        range: {
          startLineNumber: colorData[i2].colorInfo.range.startLineNumber,
          startColumn: colorData[i2].colorInfo.range.startColumn,
          endLineNumber: colorData[i2].colorInfo.range.endLineNumber,
          endColumn: colorData[i2].colorInfo.range.endColumn
        },
        options: {
          description: "colorDetector",
          before: {
            content: $wg,
            inlineClassName: `${ref.className} colorpicker-color-decoration`,
            inlineClassNameAffectsLetterSpacing: true,
            attachedData: $Kbb
          }
        }
      });
    }
    const limited = limit < colorData.length ? limit : false;
    this.z.update(colorData.length, limited);
    this.t.set(decorations);
  }
  N() {
    this.C.removeDecorations(this.n);
    this.n = [];
    this.t.clear();
    this.L.clear();
  }
  getColorData(position) {
    const model = this.C.getModel();
    if (!model) {
      return null;
    }
    const decorations = model.getDecorationsInRange($9C.fromPositions(position, position)).filter((d) => this.s.has(d.id));
    if (decorations.length === 0) {
      return null;
    }
    return this.s.get(decorations[0].id);
  }
  isColorDecoration(decoration3) {
    return this.t.has(decoration3);
  }
};
$Lbb = $Lbb_1 = __decorate([
  __param(1, $kl),
  __param(2, $mP),
  __param(3, $tbb)
], $Lbb);
var $Mbb = class {
  constructor() {
    this.f = new $ze();
    this.onDidChange = this.f.event;
    this.h = 0;
    this.j = false;
  }
  get computed() {
    return this.h;
  }
  get limited() {
    return this.j;
  }
  update(computed, limited) {
    if (computed !== this.h || limited !== this.j) {
      this.h = computed;
      this.j = limited;
      this.f.fire();
    }
  }
};

// out-build/vs/editor/contrib/hover/browser/hoverActionIds.js
var $Nbb = "editor.action.showHover";
var $Obb = "editor.action.showDefinitionPreviewHover";
var $Pbb = "editor.action.scrollUpHover";
var $Qbb = "editor.action.scrollDownHover";
var $Rbb = "editor.action.scrollLeftHover";
var $Sbb = "editor.action.scrollRightHover";
var $Tbb = "editor.action.pageUpHover";
var $Ubb = "editor.action.pageDownHover";
var $Vbb = "editor.action.goToTopHover";
var $Wbb = "editor.action.goToBottomHover";
var $Xbb = "editor.action.increaseHoverVerbosityLevel";
var $Ybb = "editor.action.increaseHoverVerbosityLevelFromAccessibleView";
var $Zbb = localize(1183, null);
var $1bb = "editor.action.decreaseHoverVerbosityLevel";
var $2bb = "editor.action.decreaseHoverVerbosityLevelFromAccessibleView";
var $3bb = localize(1184, null);

// out-build/vs/editor/contrib/inlineCompletions/browser/controller/commandIds.js
var $4bb = "editor.action.inlineSuggest.commit";
var $5bb = "editor.action.inlineSuggest.showPrevious";
var $6bb = "editor.action.inlineSuggest.showNext";

// out-build/vs/editor/contrib/inlineCompletions/browser/hintsWidget/inlineCompletionsHintsWidget.js
var $ydb_1;
var $xdb = class $xdb2 extends $3c {
  constructor(n, r2, s) {
    super();
    this.n = n;
    this.r = r2;
    this.s = s;
    this.f = $Dd(this, this.n.onDidChangeConfiguration, () => this.n.getOption(
      64
      /* EditorOption.inlineSuggest */
    ).showToolbar === "always");
    this.j = void 0;
    this.m = $2d(this, (reader) => {
      const ghostText = this.r.read(reader)?.primaryGhostText.read(reader);
      if (!this.f.read(reader) || !ghostText || ghostText.parts.length === 0) {
        this.j = void 0;
        return null;
      }
      const firstColumn = ghostText.parts[0].column;
      if (this.j && this.j.lineNumber !== ghostText.lineNumber) {
        this.j = void 0;
      }
      const position = new $8C(ghostText.lineNumber, Math.min(firstColumn, this.j?.column ?? Number.MAX_SAFE_INTEGER));
      this.j = position;
      return position;
    });
    this.B($xd((reader, store) => {
      const model = this.r.read(reader);
      if (!model || !this.f.read(reader)) {
        return;
      }
      const contentWidgetValue = $6d((reader2, store2) => {
        const contentWidget = store2.add(this.s.createInstance($ydb, this.n, true, this.m, model.selectedInlineCompletionIndex, model.inlineCompletionsCount, model.activeCommands));
        n.addContentWidget(contentWidget);
        store2.add($1c(() => n.removeContentWidget(contentWidget)));
        store2.add($td((reader3) => {
          const position = this.m.read(reader3);
          if (!position) {
            return;
          }
          if (model.lastTriggerKind.read(reader3) !== InlineCompletionTriggerKind.Explicit) {
            model.triggerExplicitly();
          }
        }));
        return contentWidget;
      });
      const hadPosition = $Pd(this, (reader2, lastValue) => !!this.m.read(reader2) || !!lastValue);
      store.add($td((reader2) => {
        if (hadPosition.read(reader2)) {
          contentWidgetValue.read(reader2);
        }
      }));
    }));
  }
};
$xdb = __decorate([
  __param(2, $Pk)
], $xdb);
var inlineSuggestionHintsNextIcon = $9r("inline-suggestion-hints-next", $6l.chevronRight, localize(1281, null));
var inlineSuggestionHintsPreviousIcon = $9r("inline-suggestion-hints-previous", $6l.chevronLeft, localize(1282, null));
var $ydb = class $ydb2 extends $3c {
  static {
    $ydb_1 = this;
  }
  static {
    this.f = false;
  }
  static get dropDownVisible() {
    return this.f;
  }
  static {
    this.id = 0;
  }
  n(commandId, label3, iconClassName) {
    const action = new $Um(commandId, label3, iconClassName, true, () => this.J.executeCommand(commandId));
    const kb = this.L.lookupKeybinding(commandId, this.M);
    let tooltip = label3;
    if (kb) {
      tooltip = localize(1283, null, label3, kb.getLabel());
    }
    action.tooltip = tooltip;
    return action;
  }
  constructor(C, D, F, G, H, I, J, instantiationService, L, M, N) {
    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.j = `InlineSuggestionHintsContentWidget${$ydb_1.id++}`;
    this.allowEditorOverflow = true;
    this.suppressMouseDown = false;
    this.m = h("div.inlineSuggestionsHints", { className: this.D ? ".withBorder" : "" }, [
      h("div@toolBar")
    ]);
    this.r = this.n($5bb, localize(1284, null), ThemeIcon.asClassName(inlineSuggestionHintsPreviousIcon));
    this.s = new $Um("inlineSuggestionHints.availableSuggestionCount", "", void 0, false);
    this.t = this.n($6bb, localize(1285, null), ThemeIcon.asClassName(inlineSuggestionHintsNextIcon));
    this.w = this.B(this.N.createMenu($bJ.InlineCompletionsActions, this.M));
    this.y = this.B(new $8h(() => {
      this.s.label = "";
    }, 100));
    this.z = this.B(new $8h(() => {
      this.r.enabled = this.t.enabled = false;
    }, 100));
    this.u = this.B(instantiationService.createInstance($zdb, this.m.toolBar, $bJ.InlineSuggestionToolbar, {
      menuOptions: { renderShortTitle: true },
      toolbarOptions: { primaryGroup: (g) => g.startsWith("primary") },
      actionViewItemProvider: (action, options3) => {
        if (action instanceof $fJ) {
          return instantiationService.createInstance(StatusBarViewItem, action, void 0);
        }
        if (action === this.s) {
          const a = new ActionViewItemWithClassName(void 0, action, { label: true, icon: false });
          a.setClass("availableSuggestionCount");
          return a;
        }
        return void 0;
      },
      telemetrySource: "InlineSuggestionToolbar"
    }));
    this.u.setPrependedPrimaryActions([
      this.r,
      this.s,
      this.t
    ]);
    this.B(this.u.onDidChangeDropdownVisibility((e) => {
      $ydb_1.f = e;
    }));
    this.B($td((reader) => {
      this.F.read(reader);
      this.C.layoutContentWidget(this);
    }));
    this.B($td((reader) => {
      const suggestionCount = this.H.read(reader);
      const currentSuggestionIdx = this.G.read(reader);
      if (suggestionCount !== void 0) {
        this.y.cancel();
        this.s.label = `${currentSuggestionIdx + 1}/${suggestionCount}`;
      } else {
        this.y.schedule();
      }
      if (suggestionCount !== void 0 && suggestionCount > 1) {
        this.z.cancel();
        this.r.enabled = this.t.enabled = true;
      } else {
        this.z.schedule();
      }
    }));
    this.B($td((reader) => {
      const extraCommands = this.I.read(reader);
      const extraActions = extraCommands.map((c) => ({
        class: void 0,
        id: c.id,
        enabled: true,
        tooltip: c.tooltip || "",
        label: c.title,
        run: (event) => {
          return this.J.executeCommand(c.id);
        }
      }));
      for (const [_, group2] of this.w.getActions()) {
        for (const action of group2) {
          if (action instanceof $fJ) {
            extraActions.push(action);
          }
        }
      }
      if (extraActions.length > 0) {
        extraActions.unshift(new $Wm());
      }
      this.u.setAdditionalSecondaryActions(extraActions);
    }));
  }
  getId() {
    return this.j;
  }
  getDomNode() {
    return this.m.root;
  }
  getPosition() {
    return {
      position: this.F.get(),
      preference: [
        1,
        2
        /* ContentWidgetPositionPreference.BELOW */
      ],
      positionAffinity: 3
    };
  }
};
$ydb = $ydb_1 = __decorate([
  __param(6, $sn),
  __param(7, $Pk),
  __param(8, $Ty),
  __param(9, $on),
  __param(10, $cJ)
], $ydb);
var ActionViewItemWithClassName = class extends $U1 {
  constructor() {
    super(...arguments);
    this.m = void 0;
  }
  setClass(className) {
    this.m = className;
  }
  render(container2) {
    super.render(container2);
    if (this.m) {
      container2.classList.add(this.m);
    }
  }
  G() {
  }
};
var StatusBarViewItem = class extends $T$ {
  C() {
    const kb = this.X.lookupKeybinding(this._action.id, this.Z, true);
    if (!kb) {
      return super.C();
    }
    if (this.L) {
      const div = h("div.keybinding").root;
      const k = this.B(new $32(div, OS, { disableTitle: true, ...$22 }));
      k.set(kb);
      this.L.textContent = this._action.label;
      this.L.appendChild(div);
      this.L.classList.add("inlineSuggestionStatusBarItemLabel");
    }
  }
  G() {
  }
};
var $zdb = class $zdb2 extends $3$ {
  constructor(container2, P, Q, R, S, contextMenuService, keybindingService, commandService, telemetryService) {
    super(container2, { resetMenu: P, ...Q }, R, S, contextMenuService, keybindingService, commandService, telemetryService);
    this.P = P;
    this.Q = Q;
    this.R = R;
    this.S = S;
    this.j = this.q.add(this.R.createMenu(this.P, this.S, { emitEventsForSubmenuChanges: true }));
    this.r = [];
    this.s = [];
    this.O = [];
    this.q.add(this.j.onDidChange(() => this.U()));
    this.U();
  }
  U() {
    const { primary, secondary } = $Q$(this.j.getActions(this.Q?.menuOptions), this.Q?.toolbarOptions?.primaryGroup, this.Q?.toolbarOptions?.shouldInlineSubmenu, this.Q?.toolbarOptions?.useSeparatorsInPrimaryActions);
    secondary.push(...this.r);
    primary.unshift(...this.s);
    primary.push(...this.O);
    this.setActions(primary, secondary);
  }
  setPrependedPrimaryActions(actions) {
    if ($zb(this.s, actions, (a, b) => a === b)) {
      return;
    }
    this.s = actions;
    this.U();
  }
  setAdditionalPrimaryActions(actions) {
    if ($zb(this.O, actions, (a, b) => a === b)) {
      return;
    }
    this.O = actions;
    this.U();
  }
  setAdditionalSecondaryActions(actions) {
    if ($zb(this.r, actions, (a, b) => a === b)) {
      return;
    }
    this.r = actions;
    this.U();
  }
};
$zdb = __decorate([
  __param(3, $cJ),
  __param(4, $on),
  __param(5, $50),
  __param(6, $Ty),
  __param(7, $sn),
  __param(8, $zv)
], $zdb);

// out-build/vs/editor/contrib/hover/browser/hoverUtils.js
function $Adb(element, posx, posy) {
  const elementRect = $vj(element);
  if (posx < elementRect.left || posx > elementRect.left + elementRect.width || posy < elementRect.top || posy > elementRect.top + elementRect.height) {
    return false;
  }
  return true;
}

// out-build/vs/editor/contrib/hover/browser/hoverOperation.js
var HoverOperationState;
(function(HoverOperationState2) {
  HoverOperationState2[HoverOperationState2["Idle"] = 0] = "Idle";
  HoverOperationState2[HoverOperationState2["FirstWait"] = 1] = "FirstWait";
  HoverOperationState2[HoverOperationState2["SecondWait"] = 2] = "SecondWait";
  HoverOperationState2[HoverOperationState2["WaitingForAsync"] = 3] = "WaitingForAsync";
  HoverOperationState2[HoverOperationState2["WaitingForAsyncShowingLoading"] = 4] = "WaitingForAsyncShowingLoading";
})(HoverOperationState || (HoverOperationState = {}));
var HoverStartMode;
(function(HoverStartMode2) {
  HoverStartMode2[HoverStartMode2["Delayed"] = 0] = "Delayed";
  HoverStartMode2[HoverStartMode2["Immediate"] = 1] = "Immediate";
})(HoverStartMode || (HoverStartMode = {}));
var HoverStartSource;
(function(HoverStartSource2) {
  HoverStartSource2[HoverStartSource2["Mouse"] = 0] = "Mouse";
  HoverStartSource2[HoverStartSource2["Click"] = 1] = "Click";
  HoverStartSource2[HoverStartSource2["Keyboard"] = 2] = "Keyboard";
})(HoverStartSource || (HoverStartSource = {}));
var $wbb = class {
  constructor(value, isComplete, hasLoadingMessage, options3) {
    this.value = value;
    this.isComplete = isComplete;
    this.hasLoadingMessage = hasLoadingMessage;
    this.options = options3;
  }
};
var $xbb = class extends $3c {
  constructor(r2, s) {
    super();
    this.r = r2;
    this.s = s;
    this.a = this.B(new $ze());
    this.onResult = this.a.event;
    this.b = this.B(new Debouncer((options3) => this.C(options3), 0));
    this.c = this.B(new Debouncer((options3) => this.D(options3), 0));
    this.f = this.B(new Debouncer((options3) => this.F(options3), 0));
    this.g = 0;
    this.h = null;
    this.j = false;
    this.m = [];
  }
  dispose() {
    if (this.h) {
      this.h.cancel();
      this.h = null;
    }
    this.n = void 0;
    super.dispose();
  }
  get t() {
    return this.r.getOption(
      62
      /* EditorOption.hover */
    ).delay;
  }
  get u() {
    return this.t / 2;
  }
  get w() {
    return this.t - this.u;
  }
  get y() {
    return 3 * this.t;
  }
  z(state, options3) {
    this.g = state;
    this.G(options3);
  }
  C(options3) {
    this.z(2, options3);
    this.c.schedule(options3, this.w);
    if (this.s.computeAsync) {
      this.j = false;
      this.h = $li((token) => this.s.computeAsync(options3, token));
      (async () => {
        try {
          for await (const item of this.h) {
            if (item) {
              this.m.push(item);
              this.G(options3);
            }
          }
          this.j = true;
          if (this.g === 3 || this.g === 4) {
            this.z(0, options3);
          }
        } catch (e) {
          $gb(e);
        }
      })();
    } else {
      this.j = true;
    }
  }
  D(options3) {
    if (this.s.computeSync) {
      this.m = this.m.concat(this.s.computeSync(options3));
    }
    this.z(this.j ? 0 : 3, options3);
  }
  F(options3) {
    if (this.g === 3) {
      this.z(4, options3);
    }
  }
  G(options3) {
    if (this.g === 1 || this.g === 2) {
      return;
    }
    const isComplete = this.g === 0;
    const hasLoadingMessage = this.g === 4;
    this.a.fire(new $wbb(this.m.slice(0), isComplete, hasLoadingMessage, options3));
  }
  start(mode, options3) {
    if (mode === 0) {
      if (this.g === 0) {
        this.z(1, options3);
        this.b.schedule(options3, this.u);
        this.f.schedule(options3, this.y);
      }
    } else {
      switch (this.g) {
        case 0:
          this.C(options3);
          this.c.cancel();
          this.D(options3);
          break;
        case 2:
          this.c.cancel();
          this.D(options3);
          break;
      }
    }
  }
  cancel() {
    this.b.cancel();
    this.c.cancel();
    this.f.cancel();
    if (this.h) {
      this.h.cancel();
      this.h = null;
    }
    this.m = [];
    this.n = void 0;
    this.g = 0;
  }
  get options() {
    return this.n;
  }
};
var Debouncer = class extends $3c {
  constructor(runner, debounceTimeMs) {
    super();
    this.a = this.B(new $8h(() => runner(this.b), debounceTimeMs));
  }
  schedule(options3, debounceTimeMs) {
    this.b = options3;
    this.a.schedule(debounceTimeMs);
  }
  cancel() {
    this.a.cancel();
  }
};

// out-build/vs/base/browser/ui/resizable/resizable.js
var $_2 = class {
  constructor() {
    this.a = new $ze();
    this.onDidWillResize = this.a.event;
    this.b = new $ze();
    this.onDidResize = this.b.event;
    this.h = new $2c();
    this.i = new $rj(0, 0);
    this.j = new $rj(0, 0);
    this.k = new $rj(Number.MAX_SAFE_INTEGER, Number.MAX_SAFE_INTEGER);
    this.domNode = document.createElement("div");
    this.d = new $q2(this.domNode, { getVerticalSashLeft: () => this.i.width }, {
      orientation: 0
      /* Orientation.VERTICAL */
    });
    this.g = new $q2(this.domNode, { getVerticalSashLeft: () => 0 }, {
      orientation: 0
      /* Orientation.VERTICAL */
    });
    this.c = new $q2(this.domNode, { getHorizontalSashTop: () => 0 }, { orientation: 1, orthogonalEdge: OrthogonalEdge.North });
    this.f = new $q2(this.domNode, { getHorizontalSashTop: () => this.i.height }, { orientation: 1, orthogonalEdge: OrthogonalEdge.South });
    this.c.orthogonalStartSash = this.g;
    this.c.orthogonalEndSash = this.d;
    this.f.orthogonalStartSash = this.g;
    this.f.orthogonalEndSash = this.d;
    let currentSize;
    let deltaY = 0;
    let deltaX = 0;
    this.h.add(Event2.any(this.c.onDidStart, this.d.onDidStart, this.f.onDidStart, this.g.onDidStart)(() => {
      if (currentSize === void 0) {
        this.a.fire();
        currentSize = this.i;
        deltaY = 0;
        deltaX = 0;
      }
    }));
    this.h.add(Event2.any(this.c.onDidEnd, this.d.onDidEnd, this.f.onDidEnd, this.g.onDidEnd)(() => {
      if (currentSize !== void 0) {
        currentSize = void 0;
        deltaY = 0;
        deltaX = 0;
        this.b.fire({ dimension: this.i, done: true });
      }
    }));
    this.h.add(this.d.onDidChange((e) => {
      if (currentSize) {
        deltaX = e.currentX - e.startX;
        this.layout(currentSize.height + deltaY, currentSize.width + deltaX);
        this.b.fire({ dimension: this.i, done: false, east: true });
      }
    }));
    this.h.add(this.g.onDidChange((e) => {
      if (currentSize) {
        deltaX = -(e.currentX - e.startX);
        this.layout(currentSize.height + deltaY, currentSize.width + deltaX);
        this.b.fire({ dimension: this.i, done: false, west: true });
      }
    }));
    this.h.add(this.c.onDidChange((e) => {
      if (currentSize) {
        deltaY = -(e.currentY - e.startY);
        this.layout(currentSize.height + deltaY, currentSize.width + deltaX);
        this.b.fire({ dimension: this.i, done: false, north: true });
      }
    }));
    this.h.add(this.f.onDidChange((e) => {
      if (currentSize) {
        deltaY = e.currentY - e.startY;
        this.layout(currentSize.height + deltaY, currentSize.width + deltaX);
        this.b.fire({ dimension: this.i, done: false, south: true });
      }
    }));
    this.h.add(Event2.any(this.d.onDidReset, this.g.onDidReset)((e) => {
      if (this.l) {
        this.layout(this.i.height, this.l.width);
        this.b.fire({ dimension: this.i, done: true });
      }
    }));
    this.h.add(Event2.any(this.c.onDidReset, this.f.onDidReset)((e) => {
      if (this.l) {
        this.layout(this.l.height, this.i.width);
        this.b.fire({ dimension: this.i, done: true });
      }
    }));
  }
  dispose() {
    this.c.dispose();
    this.f.dispose();
    this.d.dispose();
    this.g.dispose();
    this.h.dispose();
    this.b.dispose();
    this.a.dispose();
    this.domNode.remove();
  }
  enableSashes(north, east, south, west) {
    this.c.state = north ? 3 : 0;
    this.d.state = east ? 3 : 0;
    this.f.state = south ? 3 : 0;
    this.g.state = west ? 3 : 0;
  }
  layout(height = this.size.height, width2 = this.size.width) {
    const { height: minHeight, width: minWidth } = this.j;
    const { height: maxHeight, width: maxWidth } = this.k;
    height = Math.max(minHeight, Math.min(maxHeight, height));
    width2 = Math.max(minWidth, Math.min(maxWidth, width2));
    const newSize = new $rj(width2, height);
    if (!$rj.equals(newSize, this.i)) {
      this.domNode.style.height = height + "px";
      this.domNode.style.width = width2 + "px";
      this.i = newSize;
      this.c.layout();
      this.d.layout();
      this.f.layout();
      this.g.layout();
    }
  }
  clearSashHoverState() {
    this.d.clearSashHoverState();
    this.g.clearSashHoverState();
    this.c.clearSashHoverState();
    this.f.clearSashHoverState();
  }
  get size() {
    return this.i;
  }
  set maxSize(value) {
    this.k = value;
  }
  get maxSize() {
    return this.k;
  }
  set minSize(value) {
    this.j = value;
  }
  get minSize() {
    return this.j;
  }
  set preferredSize(value) {
    this.l = value;
  }
  get preferredSize() {
    return this.l;
  }
};

// out-build/vs/editor/contrib/hover/browser/resizableContentWidget.js
var TOP_HEIGHT = 30;
var BOTTOM_HEIGHT = 24;
var $Bdb = class extends $3c {
  constructor(f, minimumSize = new $rj(10, 10)) {
    super();
    this.f = f;
    this.allowEditorOverflow = true;
    this.suppressMouseDown = false;
    this.a = this.B(new $_2());
    this.b = null;
    this.c = false;
    this.a.domNode.style.position = "absolute";
    this.a.minSize = $rj.lift(minimumSize);
    this.a.layout(minimumSize.height, minimumSize.width);
    this.a.enableSashes(true, true, true, true);
    this.B(this.a.onDidResize((e) => {
      this.m(new $rj(e.dimension.width, e.dimension.height));
      if (e.done) {
        this.c = false;
      }
    }));
    this.B(this.a.onDidWillResize(() => {
      this.c = true;
    }));
  }
  get isResizing() {
    return this.c;
  }
  getDomNode() {
    return this.a.domNode;
  }
  getPosition() {
    return this.b;
  }
  get position() {
    return this.b?.position ? $8C.lift(this.b.position) : void 0;
  }
  g(position) {
    const editorDomNode = this.f.getDomNode();
    const mouseBox = this.f.getScrolledVisiblePosition(position);
    if (!editorDomNode || !mouseBox) {
      return;
    }
    const editorBox = $vj(editorDomNode);
    return editorBox.top + mouseBox.top - TOP_HEIGHT;
  }
  h(position) {
    const editorDomNode = this.f.getDomNode();
    const mouseBox = this.f.getScrolledVisiblePosition(position);
    if (!editorDomNode || !mouseBox) {
      return;
    }
    const editorBox = $vj(editorDomNode);
    const bodyBox = $qj(editorDomNode.ownerDocument.body);
    const mouseBottom = editorBox.top + mouseBox.top + mouseBox.height;
    return bodyBox.height - mouseBottom - BOTTOM_HEIGHT;
  }
  j(widgetHeight, showAtPosition) {
    const maxHeightBelow = Math.min(this.h(showAtPosition) ?? Infinity, widgetHeight);
    const maxHeightAbove = Math.min(this.g(showAtPosition) ?? Infinity, widgetHeight);
    const maxHeight = Math.min(Math.max(maxHeightAbove, maxHeightBelow), widgetHeight);
    const height = Math.min(widgetHeight, maxHeight);
    let renderingAbove;
    if (this.f.getOption(
      62
      /* EditorOption.hover */
    ).above) {
      renderingAbove = height <= maxHeightAbove ? 1 : 2;
    } else {
      renderingAbove = height <= maxHeightBelow ? 2 : 1;
    }
    if (renderingAbove === 1) {
      this.a.enableSashes(true, true, false, false);
    } else {
      this.a.enableSashes(false, true, true, false);
    }
    return renderingAbove;
  }
  m(dimension) {
    this.a.layout(dimension.height, dimension.width);
  }
};

// out-build/vs/base/browser/ui/hover/hoverWidget.js
var $13 = $;
var HoverPosition;
(function(HoverPosition2) {
  HoverPosition2[HoverPosition2["LEFT"] = 0] = "LEFT";
  HoverPosition2[HoverPosition2["RIGHT"] = 1] = "RIGHT";
  HoverPosition2[HoverPosition2["BELOW"] = 2] = "BELOW";
  HoverPosition2[HoverPosition2["ABOVE"] = 3] = "ABOVE";
})(HoverPosition || (HoverPosition = {}));
var $DZ = class extends $3c {
  constructor(fadeIn) {
    super();
    this.containerDomNode = document.createElement("div");
    this.containerDomNode.className = "monaco-hover";
    this.containerDomNode.classList.toggle("fade-in", !!fadeIn);
    this.containerDomNode.tabIndex = 0;
    this.containerDomNode.setAttribute("role", "tooltip");
    this.contentsDomNode = document.createElement("div");
    this.contentsDomNode.className = "monaco-hover-content";
    this.scrollbar = this.B(new $CZ(this.contentsDomNode, {
      consumeMouseWheelIfScrollbarIsNeeded: true
    }));
    this.containerDomNode.appendChild(this.scrollbar.getDomNode());
  }
  onContentsChanged() {
    this.scrollbar.scanDomNode();
  }
};
var $EZ = class _$EZ extends $3c {
  static render(parent, actionOptions, keybindingLabel) {
    return new _$EZ(parent, actionOptions, keybindingLabel);
  }
  constructor(parent, actionOptions, keybindingLabel) {
    super();
    this.actionLabel = actionOptions.label;
    this.actionKeybindingLabel = keybindingLabel;
    this.actionContainer = $bk(parent, $13("div.action-container"));
    this.actionContainer.setAttribute("tabindex", "0");
    this.a = $bk(this.actionContainer, $13("a.action"));
    this.a.setAttribute("role", "button");
    if (actionOptions.iconClass) {
      $bk(this.a, $13(`span.icon.${actionOptions.iconClass}`));
    }
    this.actionRenderedLabel = keybindingLabel ? `${actionOptions.label} (${keybindingLabel})` : actionOptions.label;
    const label3 = $bk(this.a, $13("span"));
    label3.textContent = this.actionRenderedLabel;
    this.q.add(new $GZ(this.actionContainer, actionOptions.run));
    this.q.add(new $HZ(this.actionContainer, actionOptions.run, [
      3,
      10
      /* KeyCode.Space */
    ]));
    this.setEnabled(true);
  }
  setEnabled(enabled) {
    if (enabled) {
      this.actionContainer.classList.remove("disabled");
      this.actionContainer.removeAttribute("aria-disabled");
    } else {
      this.actionContainer.classList.add("disabled");
      this.actionContainer.setAttribute("aria-disabled", "true");
    }
  }
};
function $FZ(shouldHaveHint, keybinding) {
  return shouldHaveHint && keybinding ? localize(15, null, keybinding) : shouldHaveHint ? localize(16, null) : "";
}
var $GZ = class extends $3c {
  constructor(container2, run) {
    super();
    this.B($_i(container2, $7j.CLICK, (e) => {
      e.stopPropagation();
      e.preventDefault();
      run(container2);
    }));
  }
};
var $HZ = class extends $3c {
  constructor(container2, run, keyCodes) {
    super();
    this.B($_i(container2, $7j.KEY_DOWN, (e) => {
      const event = new $if(e);
      if (keyCodes.some((keyCode) => event.equals(keyCode))) {
        e.stopPropagation();
        e.preventDefault();
        run(container2);
      }
    }));
  }
};

// out-build/vs/editor/contrib/hover/browser/contentHoverWidget.js
var $yfb_1;
var HORIZONTAL_SCROLLING_BY = 30;
var CONTAINER_HEIGHT_PADDING = 6;
var $yfb = class $yfb2 extends $Bdb {
  static {
    $yfb_1 = this;
  }
  static {
    this.ID = "editor.contrib.resizableContentHoverWidget";
  }
  static {
    this.n = new $rj(0, 0);
  }
  get isVisibleFromKeyboard() {
    return this.r?.source === 2;
  }
  get isVisible() {
    return this.z.get() ?? false;
  }
  get isFocused() {
    return this.C.get() ?? false;
  }
  constructor(editor, contextKeyService, F, G, H) {
    const minimumHeight = editor.getOption(
      68
      /* EditorOption.lineHeight */
    ) + 8;
    const minimumWidth = 150;
    const minimumSize = new $rj(minimumWidth, minimumHeight);
    super(editor, minimumSize);
    this.F = F;
    this.G = G;
    this.H = H;
    this.w = this.B(new $DZ(true));
    this.D = this.B(new $ze());
    this.onDidResize = this.D.event;
    this.t = minimumSize;
    this.z = EditorContextKeys.hoverVisible.bindTo(contextKeyService);
    this.C = EditorContextKeys.hoverFocused.bindTo(contextKeyService);
    $bk(this.a.domNode, this.w.containerDomNode);
    this.a.domNode.style.zIndex = "50";
    this.B(this.f.onDidLayoutChange(() => {
      if (this.isVisible) {
        this.bb();
      }
    }));
    this.B(this.f.onDidChangeConfiguration((e) => {
      if (e.hasChanged(
        52
        /* EditorOption.fontInfo */
      )) {
        this.Z();
      }
    }));
    const focusTracker = this.B($_j(this.a.domNode));
    this.B(focusTracker.onDidFocus(() => {
      this.C.set(true);
    }));
    this.B(focusTracker.onDidBlur(() => {
      this.C.set(false);
    }));
    this.Y(void 0);
    this.f.addContentWidget(this);
  }
  dispose() {
    super.dispose();
    this.r?.dispose();
    this.f.removeContentWidget(this);
  }
  getId() {
    return $yfb_1.ID;
  }
  static I(container2, width2, height) {
    const transformedWidth = typeof width2 === "number" ? `${width2}px` : width2;
    const transformedHeight = typeof height === "number" ? `${height}px` : height;
    container2.style.width = transformedWidth;
    container2.style.height = transformedHeight;
  }
  J(width2, height) {
    const contentsDomNode = this.w.contentsDomNode;
    return $yfb_1.I(contentsDomNode, width2, height);
  }
  L(width2, height) {
    const containerDomNode = this.w.containerDomNode;
    return $yfb_1.I(containerDomNode, width2, height);
  }
  M(width2, height) {
    this.J(width2, height);
    this.L(width2, height);
    this.ab();
  }
  static N(container2, width2, height) {
    const transformedWidth = typeof width2 === "number" ? `${width2}px` : width2;
    const transformedHeight = typeof height === "number" ? `${height}px` : height;
    container2.style.maxWidth = transformedWidth;
    container2.style.maxHeight = transformedHeight;
  }
  O(width2, height) {
    $yfb_1.N(this.w.contentsDomNode, width2, height);
    $yfb_1.N(this.w.containerDomNode, width2, height);
    this.w.containerDomNode.style.setProperty("--vscode-hover-maxWidth", typeof width2 === "number" ? `${width2}px` : width2);
    this.ab();
  }
  P(size) {
    this.O("none", "none");
    const width2 = size.width;
    const height = size.height;
    this.M(width2, height);
  }
  Q() {
    const maxRenderingWidth = this.X() ?? Infinity;
    const maxRenderingHeight = this.U() ?? Infinity;
    this.a.maxSize = new $rj(maxRenderingWidth, maxRenderingHeight);
    this.O(maxRenderingWidth, maxRenderingHeight);
  }
  m(size) {
    $yfb_1.n = new $rj(size.width, size.height);
    this.P(size);
    this.a.layout(size.height, size.width);
    this.Q();
    this.w.scrollbar.scanDomNode();
    this.f.layoutContentWidget(this);
    this.D.fire();
  }
  S() {
    const position = this.r?.showAtPosition;
    if (!position) {
      return;
    }
    return this.s === 1 ? this.g(position) : this.h(position);
  }
  U() {
    const availableSpace = this.S();
    if (!availableSpace) {
      return;
    }
    let maximumHeight = CONTAINER_HEIGHT_PADDING;
    Array.from(this.w.contentsDomNode.children).forEach((hoverPart) => {
      maximumHeight += hoverPart.clientHeight;
    });
    return Math.min(availableSpace, maximumHeight);
  }
  W() {
    this.w.containerDomNode.style.setProperty("--vscode-hover-whiteSpace", "nowrap");
    this.w.containerDomNode.style.setProperty("--vscode-hover-sourceWhiteSpace", "nowrap");
    const overflowing = Array.from(this.w.contentsDomNode.children).some((hoverElement) => {
      return hoverElement.scrollWidth > hoverElement.clientWidth;
    });
    this.w.containerDomNode.style.removeProperty("--vscode-hover-whiteSpace");
    this.w.containerDomNode.style.removeProperty("--vscode-hover-sourceWhiteSpace");
    return overflowing;
  }
  X() {
    if (!this.f || !this.f.hasModel()) {
      return;
    }
    const overflowing = this.W();
    const initialWidth = typeof this.u === "undefined" ? 0 : this.u - 2;
    if (overflowing || this.w.containerDomNode.clientWidth < initialWidth) {
      const bodyBoxWidth = $qj(this.w.containerDomNode.ownerDocument.body).width;
      const horizontalPadding = 14;
      return bodyBoxWidth - horizontalPadding;
    } else {
      return this.w.containerDomNode.clientWidth + 2;
    }
  }
  isMouseGettingCloser(posx, posy) {
    if (!this.r) {
      return false;
    }
    if (this.r.initialMousePosX === void 0 || this.r.initialMousePosY === void 0) {
      this.r.initialMousePosX = posx;
      this.r.initialMousePosY = posy;
      return false;
    }
    const widgetRect = $vj(this.getDomNode());
    if (this.r.closestMouseDistance === void 0) {
      this.r.closestMouseDistance = computeDistanceFromPointToRectangle(this.r.initialMousePosX, this.r.initialMousePosY, widgetRect.left, widgetRect.top, widgetRect.width, widgetRect.height);
    }
    const distance = computeDistanceFromPointToRectangle(posx, posy, widgetRect.left, widgetRect.top, widgetRect.width, widgetRect.height);
    if (distance > this.r.closestMouseDistance + 4) {
      return false;
    }
    this.r.closestMouseDistance = Math.min(this.r.closestMouseDistance, distance);
    return true;
  }
  Y(renderedHover) {
    this.r?.dispose();
    this.r = renderedHover;
    this.z.set(!!renderedHover);
    this.w.containerDomNode.classList.toggle("hidden", !renderedHover);
  }
  Z() {
    const { fontSize, lineHeight } = this.f.getOption(
      52
      /* EditorOption.fontInfo */
    );
    const contentsDomNode = this.w.contentsDomNode;
    contentsDomNode.style.fontSize = `${fontSize}px`;
    contentsDomNode.style.lineHeight = `${lineHeight / fontSize}`;
    const codeClasses = Array.prototype.slice.call(this.w.contentsDomNode.getElementsByClassName("code"));
    codeClasses.forEach((node) => this.f.applyFontInfo(node));
  }
  $(node) {
    const contentsDomNode = this.w.contentsDomNode;
    contentsDomNode.style.paddingBottom = "";
    contentsDomNode.textContent = "";
    contentsDomNode.appendChild(node);
  }
  ab() {
    this.f.layoutContentWidget(this);
    this.w.onContentsChanged();
  }
  bb() {
    const height = Math.max(this.f.getLayoutInfo().height / 4, 250, $yfb_1.n.height);
    const width2 = Math.max(this.f.getLayoutInfo().width * 0.66, 750, $yfb_1.n.width);
    this.O(width2, height);
  }
  cb(renderedHover) {
    this.Y(renderedHover);
    this.Z();
    this.$(renderedHover.domNode);
    this.bb();
    this.onContentsChanged();
    this.f.render();
  }
  getPosition() {
    if (!this.r) {
      return null;
    }
    return {
      position: this.r.showAtPosition,
      secondaryPosition: this.r.showAtSecondaryPosition,
      positionAffinity: this.r.shouldAppearBeforeContent ? 3 : void 0,
      preference: [
        this.s ?? 1
        /* ContentWidgetPositionPreference.ABOVE */
      ]
    };
  }
  show(renderedHover) {
    if (!this.f || !this.f.hasModel()) {
      return;
    }
    this.cb(renderedHover);
    const widgetHeight = $Bj(this.w.containerDomNode);
    const widgetPosition = renderedHover.showAtPosition;
    this.s = this.j(widgetHeight, widgetPosition) ?? 1;
    this.onContentsChanged();
    if (renderedHover.shouldFocus) {
      this.w.containerDomNode.focus();
    }
    this.D.fire();
    const hoverFocused = this.w.containerDomNode.ownerDocument.activeElement === this.w.containerDomNode;
    const accessibleViewHint = hoverFocused && $FZ(this.F.getValue("accessibility.verbosity.hover") === true && this.G.isScreenReaderOptimized(), this.H.lookupKeybinding("editor.action.accessibleView")?.getAriaLabel() ?? "");
    if (accessibleViewHint) {
      this.w.contentsDomNode.ariaLabel = this.w.contentsDomNode.textContent + ", " + accessibleViewHint;
    }
  }
  hide() {
    if (!this.r) {
      return;
    }
    const hoverStoleFocus = this.r.shouldFocus || this.C.get();
    this.Y(void 0);
    this.a.maxSize = new $rj(Infinity, Infinity);
    this.a.clearSashHoverState();
    this.C.set(false);
    this.f.layoutContentWidget(this);
    if (hoverStoleFocus) {
      this.f.focus();
    }
  }
  db() {
    const layoutInfo = this.f.getLayoutInfo();
    this.a.layout(layoutInfo.height, layoutInfo.width);
    this.M("auto", "auto");
  }
  setMinimumDimensions(dimensions) {
    this.t = new $rj(Math.max(this.t.width, dimensions.width), Math.max(this.t.height, dimensions.height));
    this.eb();
  }
  eb() {
    const width2 = typeof this.u === "undefined" ? this.t.width : Math.min(this.u, this.t.width);
    this.a.minSize = new $rj(width2, this.t.height);
  }
  onContentsChanged() {
    this.db();
    const containerDomNode = this.w.containerDomNode;
    let height = $Bj(containerDomNode);
    let width2 = $xj(containerDomNode);
    this.a.layout(height, width2);
    this.M(width2, height);
    height = $Bj(containerDomNode);
    width2 = $xj(containerDomNode);
    this.u = width2;
    this.eb();
    this.a.layout(height, width2);
    if (this.r?.showAtPosition) {
      const widgetHeight = $Bj(this.w.containerDomNode);
      this.s = this.j(widgetHeight, this.r.showAtPosition);
    }
    this.ab();
  }
  focus() {
    this.w.containerDomNode.focus();
  }
  scrollUp() {
    const scrollTop = this.w.scrollbar.getScrollPosition().scrollTop;
    const fontInfo = this.f.getOption(
      52
      /* EditorOption.fontInfo */
    );
    this.w.scrollbar.setScrollPosition({ scrollTop: scrollTop - fontInfo.lineHeight });
  }
  scrollDown() {
    const scrollTop = this.w.scrollbar.getScrollPosition().scrollTop;
    const fontInfo = this.f.getOption(
      52
      /* EditorOption.fontInfo */
    );
    this.w.scrollbar.setScrollPosition({ scrollTop: scrollTop + fontInfo.lineHeight });
  }
  scrollLeft() {
    const scrollLeft = this.w.scrollbar.getScrollPosition().scrollLeft;
    this.w.scrollbar.setScrollPosition({ scrollLeft: scrollLeft - HORIZONTAL_SCROLLING_BY });
  }
  scrollRight() {
    const scrollLeft = this.w.scrollbar.getScrollPosition().scrollLeft;
    this.w.scrollbar.setScrollPosition({ scrollLeft: scrollLeft + HORIZONTAL_SCROLLING_BY });
  }
  pageUp() {
    const scrollTop = this.w.scrollbar.getScrollPosition().scrollTop;
    const scrollHeight = this.w.scrollbar.getScrollDimensions().height;
    this.w.scrollbar.setScrollPosition({ scrollTop: scrollTop - scrollHeight });
  }
  pageDown() {
    const scrollTop = this.w.scrollbar.getScrollPosition().scrollTop;
    const scrollHeight = this.w.scrollbar.getScrollDimensions().height;
    this.w.scrollbar.setScrollPosition({ scrollTop: scrollTop + scrollHeight });
  }
  goToTop() {
    this.w.scrollbar.setScrollPosition({ scrollTop: 0 });
  }
  goToBottom() {
    this.w.scrollbar.setScrollPosition({ scrollTop: this.w.scrollbar.getScrollDimensions().scrollHeight });
  }
};
$yfb = $yfb_1 = __decorate([
  __param(1, $on),
  __param(2, $kl),
  __param(3, $ND),
  __param(4, $Ty)
], $yfb);
function computeDistanceFromPointToRectangle(pointX, pointY, left, top2, width2, height) {
  const x = left + width2 / 2;
  const y = top2 + height / 2;
  const dx = Math.max(Math.abs(pointX - x) - width2 / 2, 0);
  const dy = Math.max(Math.abs(pointY - y) - height / 2, 0);
  return Math.sqrt(dx * dx + dy * dy);
}

// out-build/vs/editor/contrib/hover/browser/contentHoverComputer.js
var $Ddb = class _$Ddb {
  constructor(a, b) {
    this.a = a;
    this.b = b;
  }
  static c(editor, anchor) {
    if (anchor.type !== 1 && !anchor.supportsMarkerHover) {
      return [];
    }
    const model = editor.getModel();
    const lineNumber = anchor.range.startLineNumber;
    if (lineNumber > model.getLineCount()) {
      return [];
    }
    const maxColumn = model.getLineMaxColumn(lineNumber);
    return editor.getLineDecorations(lineNumber).filter((d) => {
      if (d.options.isWholeLine) {
        return true;
      }
      const startColumn = d.range.startLineNumber === lineNumber ? d.range.startColumn : 1;
      const endColumn = d.range.endLineNumber === lineNumber ? d.range.endColumn : maxColumn;
      if (d.options.showIfCollapsed) {
        if (startColumn > anchor.range.startColumn + 1 || anchor.range.endColumn - 1 > endColumn) {
          return false;
        }
      } else {
        if (startColumn > anchor.range.startColumn || anchor.range.endColumn > endColumn) {
          return false;
        }
      }
      return true;
    });
  }
  computeAsync(options3, token) {
    const anchor = options3.anchor;
    if (!this.a.hasModel() || !anchor) {
      return $ji.EMPTY;
    }
    const lineDecorations = _$Ddb.c(this.a, anchor);
    return $ji.merge(this.b.map((participant) => {
      if (!participant.computeAsync) {
        return $ji.EMPTY;
      }
      return participant.computeAsync(anchor, lineDecorations, options3.source, token);
    }));
  }
  computeSync(options3) {
    if (!this.a.hasModel()) {
      return [];
    }
    const anchor = options3.anchor;
    const lineDecorations = _$Ddb.c(this.a, anchor);
    let result = [];
    for (const participant of this.b) {
      result = result.concat(participant.computeSync(anchor, lineDecorations, options3.source));
    }
    return $Mb(result);
  }
};

// out-build/vs/editor/contrib/hover/browser/contentHoverTypes.js
var $Edb = class {
  constructor(hoverParts, isComplete, options3) {
    this.hoverParts = hoverParts;
    this.isComplete = isComplete;
    this.options = options3;
  }
  filter(anchor) {
    const filteredHoverParts = this.hoverParts.filter((m) => m.isValidForHoverAnchor(anchor));
    if (filteredHoverParts.length === this.hoverParts.length) {
      return this;
    }
    return new $Fdb(this, filteredHoverParts, this.isComplete, this.options);
  }
};
var $Fdb = class extends $Edb {
  constructor(a, messages, isComplete, options3) {
    super(messages, isComplete, options3);
    this.a = a;
  }
  filter(anchor) {
    return this.a.filter(anchor);
  }
};

// out-build/vs/editor/contrib/hover/browser/contentHoverStatusBar.js
var $21 = $;
var $Cdb = class $Cdb2 extends $3c {
  get hasContent() {
    return this.b;
  }
  constructor(c, f) {
    super();
    this.c = c;
    this.f = f;
    this.actions = [];
    this.b = false;
    this.hoverElement = $21("div.hover-row.status-bar");
    this.hoverElement.tabIndex = 0;
    this.a = $bk(this.hoverElement, $21("div.actions"));
  }
  addAction(actionOptions) {
    const keybinding = this.c.lookupKeybinding(actionOptions.commandId);
    const keybindingLabel = keybinding ? keybinding.getLabel() : null;
    this.b = true;
    const action = this.B($EZ.render(this.a, actionOptions, keybindingLabel));
    this.B(this.f.setupManagedHover($JZ("element"), action.actionContainer, action.actionRenderedLabel));
    this.actions.push(action);
    return action;
  }
  append(element) {
    const result = $bk(this.a, element);
    this.b = true;
    return result;
  }
};
$Cdb = __decorate([
  __param(0, $Ty),
  __param(1, $5$)
], $Cdb);

// out-build/vs/editor/contrib/hover/browser/getHover.js
var $Gdb = class {
  constructor(provider, hover, ordinal) {
    this.provider = provider;
    this.hover = hover;
    this.ordinal = ordinal;
  }
};
async function executeProvider(provider, ordinal, model, position, token) {
  const result = await Promise.resolve(provider.provideHover(model, position, token)).catch($hb);
  if (!result || !isValid(result)) {
    return void 0;
  }
  return new $Gdb(provider, result, ordinal);
}
function $Hdb(registry4, model, position, token, recursive = false) {
  const providers2 = registry4.ordered(model, recursive);
  const promises = providers2.map((provider, index) => executeProvider(provider, index, model, position, token));
  return $ji.fromPromisesResolveOrder(promises).coalesce();
}
function $Idb(registry4, model, position, token, recursive = false) {
  return $Hdb(registry4, model, position, token, recursive).map((item) => item.hover).toPromise();
}
$35("_executeHoverProvider", (accessor, model, position) => {
  const languageFeaturesService = accessor.get($mP);
  return $Idb(languageFeaturesService.hoverProvider, model, position, CancellationToken.None);
});
$35("_executeHoverProvider_recursive", (accessor, model, position) => {
  const languageFeaturesService = accessor.get($mP);
  return $Idb(languageFeaturesService.hoverProvider, model, position, CancellationToken.None, true);
});
function isValid(result) {
  const hasRange = typeof result.range !== "undefined";
  const hasHtmlContent = typeof result.contents !== "undefined" && result.contents && result.contents.length > 0;
  return hasRange && hasHtmlContent;
}

// out-build/vs/editor/contrib/hover/browser/markdownHoverParticipant.js
var $23 = $;
var increaseHoverVerbosityIcon = $9r("hover-increase-verbosity", $6l.add, localize(1208, null));
var decreaseHoverVerbosityIcon = $9r("hover-decrease-verbosity", $6l.remove, localize(1209, null));
var $Jdb = class {
  constructor(owner, range, contents, isBeforeContent, ordinal, source = void 0) {
    this.owner = owner;
    this.range = range;
    this.contents = contents;
    this.isBeforeContent = isBeforeContent;
    this.ordinal = ordinal;
    this.source = source;
  }
  isValidForHoverAnchor(anchor) {
    return anchor.type === 1 && this.range.startColumn <= anchor.range.startColumn && this.range.endColumn >= anchor.range.endColumn;
  }
};
var HoverSource = class {
  constructor(hover, hoverProvider, hoverPosition) {
    this.hover = hover;
    this.hoverProvider = hoverProvider;
    this.hoverPosition = hoverPosition;
  }
  supportsVerbosityAction(hoverVerbosityAction) {
    switch (hoverVerbosityAction) {
      case HoverVerbosityAction.Increase:
        return this.hover.canIncreaseVerbosity ?? false;
      case HoverVerbosityAction.Decrease:
        return this.hover.canDecreaseVerbosity ?? false;
    }
  }
};
var $Kdb = class $Kdb2 {
  constructor(b, c, f, g, h3, i2, j, k) {
    this.b = b;
    this.c = c;
    this.f = f;
    this.g = g;
    this.h = h3;
    this.i = i2;
    this.j = j;
    this.k = k;
    this.hoverOrdinal = 3;
  }
  createLoadingMessage(anchor) {
    return new $Jdb(this, anchor.range, [new $bm().appendText(localize(1210, null))], false, 2e3);
  }
  computeSync(anchor, lineDecorations) {
    if (!this.b.hasModel() || anchor.type !== 1) {
      return [];
    }
    const model = this.b.getModel();
    const lineNumber = anchor.range.startLineNumber;
    const maxColumn = model.getLineMaxColumn(lineNumber);
    const result = [];
    let index = 1e3;
    const lineLength = model.getLineLength(lineNumber);
    const languageId = model.getLanguageIdAtPosition(anchor.range.startLineNumber, anchor.range.startColumn);
    const stopRenderingLineAfter = this.b.getOption(
      122
      /* EditorOption.stopRenderingLineAfter */
    );
    const maxTokenizationLineLength = this.g.getValue("editor.maxTokenizationLineLength", {
      overrideIdentifier: languageId
    });
    let stopRenderingMessage = false;
    if (stopRenderingLineAfter >= 0 && lineLength > stopRenderingLineAfter && anchor.range.startColumn >= stopRenderingLineAfter) {
      stopRenderingMessage = true;
      result.push(new $Jdb(this, anchor.range, [{
        value: localize(1211, null)
      }], false, index++));
    }
    if (!stopRenderingMessage && typeof maxTokenizationLineLength === "number" && lineLength >= maxTokenizationLineLength) {
      result.push(new $Jdb(this, anchor.range, [{
        value: localize(1212, null)
      }], false, index++));
    }
    let isBeforeContent = false;
    for (const d of lineDecorations) {
      const startColumn = d.range.startLineNumber === lineNumber ? d.range.startColumn : 1;
      const endColumn = d.range.endLineNumber === lineNumber ? d.range.endColumn : maxColumn;
      const hoverMessage = d.options.hoverMessage;
      if (!hoverMessage || $cm(hoverMessage)) {
        continue;
      }
      if (d.options.beforeContentClassName) {
        isBeforeContent = true;
      }
      const range = new $9C(anchor.range.startLineNumber, startColumn, anchor.range.startLineNumber, endColumn);
      result.push(new $Jdb(this, range, $5b(hoverMessage), isBeforeContent, index++));
    }
    return result;
  }
  computeAsync(anchor, lineDecorations, source, token) {
    if (!this.b.hasModel() || anchor.type !== 1) {
      return $ji.EMPTY;
    }
    const model = this.b.getModel();
    const hoverProviderRegistry = this.h.hoverProvider;
    if (!hoverProviderRegistry.has(model)) {
      return $ji.EMPTY;
    }
    const markdownHovers = this.l(hoverProviderRegistry, model, anchor, token);
    return markdownHovers;
  }
  l(hoverProviderRegistry, model, anchor, token) {
    const position = anchor.range.getStartPosition();
    const hoverProviderResults = $Hdb(hoverProviderRegistry, model, position, token);
    const markdownHovers = hoverProviderResults.filter((item) => !$cm(item.hover.contents)).map((item) => {
      const range = item.hover.range ? $9C.lift(item.hover.range) : anchor.range;
      const hoverSource = new HoverSource(item.hover, item.provider, position);
      return new $Jdb(this, range, item.hover.contents, false, item.ordinal, hoverSource);
    });
    return markdownHovers;
  }
  renderHoverParts(context, hoverParts) {
    this.a = new MarkdownRenderedHoverParts(hoverParts, context.fragment, this, this.b, this.c, this.f, this.k, this.i, this.j, this.g, context.onContentsChanged);
    return this.a;
  }
  getAccessibleContent(hoverPart) {
    return this.a?.getAccessibleContent(hoverPart) ?? "";
  }
  doesMarkdownHoverAtIndexSupportVerbosityAction(index, action) {
    return this.a?.doesMarkdownHoverAtIndexSupportVerbosityAction(index, action) ?? false;
  }
  updateMarkdownHoverVerbosityLevel(action, index, focus) {
    return Promise.resolve(this.a?.updateMarkdownHoverPartVerbosityLevel(action, index, focus));
  }
};
$Kdb = __decorate([
  __param(1, $1E),
  __param(2, $O4),
  __param(3, $kl),
  __param(4, $mP),
  __param(5, $Ty),
  __param(6, $5$),
  __param(7, $sn)
], $Kdb);
var RenderedMarkdownHoverPart = class {
  constructor(hoverPart, hoverElement, disposables) {
    this.hoverPart = hoverPart;
    this.hoverElement = hoverElement;
    this.disposables = disposables;
  }
  get hoverAccessibleContent() {
    return this.hoverElement.innerText.trim();
  }
  dispose() {
    this.disposables.dispose();
  }
};
var MarkdownRenderedHoverParts = class {
  constructor(hoverParts, hoverPartsContainer, c, f, g, h3, i2, j, k, l, m) {
    this.c = c;
    this.f = f;
    this.g = g;
    this.h = h3;
    this.i = i2;
    this.j = j;
    this.k = k;
    this.l = l;
    this.m = m;
    this.a = /* @__PURE__ */ new Map();
    this.b = new $2c();
    this.renderedHoverParts = this.n(hoverParts, hoverPartsContainer, this.m);
    this.b.add($1c(() => {
      this.renderedHoverParts.forEach((renderedHoverPart) => {
        renderedHoverPart.dispose();
      });
      this.a.forEach((operation) => {
        operation.tokenSource.dispose(true);
      });
    }));
  }
  n(hoverParts, hoverPartsContainer, onFinishedRendering) {
    hoverParts.sort($9b((hover) => hover.ordinal, $$b));
    return hoverParts.map((hoverPart) => {
      const renderedHoverPart = this.o(hoverPart, onFinishedRendering);
      hoverPartsContainer.appendChild(renderedHoverPart.hoverElement);
      return renderedHoverPart;
    });
  }
  o(hoverPart, onFinishedRendering) {
    const renderedMarkdownPart = this.p(hoverPart, onFinishedRendering);
    const renderedMarkdownElement = renderedMarkdownPart.hoverElement;
    const hoverSource = hoverPart.source;
    const disposables = new $2c();
    disposables.add(renderedMarkdownPart);
    if (!hoverSource) {
      return new RenderedMarkdownHoverPart(hoverPart, renderedMarkdownElement, disposables);
    }
    const canIncreaseVerbosity = hoverSource.supportsVerbosityAction(HoverVerbosityAction.Increase);
    const canDecreaseVerbosity = hoverSource.supportsVerbosityAction(HoverVerbosityAction.Decrease);
    if (!canIncreaseVerbosity && !canDecreaseVerbosity) {
      return new RenderedMarkdownHoverPart(hoverPart, renderedMarkdownElement, disposables);
    }
    const actionsContainer = $23("div.verbosity-actions");
    renderedMarkdownElement.prepend(actionsContainer);
    disposables.add(this.q(actionsContainer, HoverVerbosityAction.Increase, canIncreaseVerbosity));
    disposables.add(this.q(actionsContainer, HoverVerbosityAction.Decrease, canDecreaseVerbosity));
    return new RenderedMarkdownHoverPart(hoverPart, renderedMarkdownElement, disposables);
  }
  p(markdownHover, onFinishedRendering) {
    const renderedMarkdownHover = renderMarkdownInContainer(this.f, markdownHover, this.g, this.h, onFinishedRendering);
    return renderedMarkdownHover;
  }
  q(container2, action, actionEnabled) {
    const store = new $2c();
    const isActionIncrease = action === HoverVerbosityAction.Increase;
    const actionElement = $bk(container2, $23(ThemeIcon.asCSSSelector(isActionIncrease ? increaseHoverVerbosityIcon : decreaseHoverVerbosityIcon)));
    actionElement.tabIndex = 0;
    const hoverDelegate = new $6$("mouse", false, { target: container2, position: {
      hoverPosition: 0
      /* HoverPosition.LEFT */
    } }, this.l, this.k);
    store.add(this.k.setupManagedHover(hoverDelegate, actionElement, $Mdb(this.j, action)));
    if (!actionEnabled) {
      actionElement.classList.add("disabled");
      return store;
    }
    actionElement.classList.add("enabled");
    const actionFunction = () => this.i.executeCommand(action === HoverVerbosityAction.Increase ? $Xbb : $1bb);
    store.add(new $GZ(actionElement, actionFunction));
    store.add(new $HZ(actionElement, actionFunction, [
      3,
      10
      /* KeyCode.Space */
    ]));
    return store;
  }
  async updateMarkdownHoverPartVerbosityLevel(action, index, focus = true) {
    const model = this.f.getModel();
    if (!model) {
      return void 0;
    }
    const hoverRenderedPart = this.u(index);
    const hoverSource = hoverRenderedPart?.hoverPart.source;
    if (!hoverRenderedPart || !hoverSource?.supportsVerbosityAction(action)) {
      return void 0;
    }
    const newHover = await this.r(hoverSource, model, action);
    if (!newHover) {
      return void 0;
    }
    const newHoverSource = new HoverSource(newHover, hoverSource.hoverProvider, hoverSource.hoverPosition);
    const initialHoverPart = hoverRenderedPart.hoverPart;
    const newHoverPart = new $Jdb(this.c, initialHoverPart.range, newHover.contents, initialHoverPart.isBeforeContent, initialHoverPart.ordinal, newHoverSource);
    const newHoverRenderedPart = this.o(newHoverPart, this.m);
    this.s(index, newHoverRenderedPart, newHoverPart);
    if (focus) {
      this.t(index);
    }
    return {
      hoverPart: newHoverPart,
      hoverElement: newHoverRenderedPart.hoverElement
    };
  }
  getAccessibleContent(hoverPart) {
    const renderedHoverPartIndex = this.renderedHoverParts.findIndex((renderedHoverPart2) => renderedHoverPart2.hoverPart === hoverPart);
    if (renderedHoverPartIndex === -1) {
      return void 0;
    }
    const renderedHoverPart = this.u(renderedHoverPartIndex);
    if (!renderedHoverPart) {
      return void 0;
    }
    const hoverElementInnerText = renderedHoverPart.hoverElement.innerText;
    const accessibleContent = hoverElementInnerText.replace(/[^\S\n\r]+/gu, " ");
    return accessibleContent;
  }
  doesMarkdownHoverAtIndexSupportVerbosityAction(index, action) {
    const hoverRenderedPart = this.u(index);
    const hoverSource = hoverRenderedPart?.hoverPart.source;
    if (!hoverRenderedPart || !hoverSource?.supportsVerbosityAction(action)) {
      return false;
    }
    return true;
  }
  async r(hoverSource, model, action) {
    let verbosityDelta = action === HoverVerbosityAction.Increase ? 1 : -1;
    const provider = hoverSource.hoverProvider;
    const ongoingHoverOperation = this.a.get(provider);
    if (ongoingHoverOperation) {
      ongoingHoverOperation.tokenSource.cancel();
      verbosityDelta += ongoingHoverOperation.verbosityDelta;
    }
    const tokenSource = new $ad();
    this.a.set(provider, { verbosityDelta, tokenSource });
    const context = { verbosityRequest: { verbosityDelta, previousHover: hoverSource.hover } };
    let hover;
    try {
      hover = await Promise.resolve(provider.provideHover(model, hoverSource.hoverPosition, tokenSource.token, context));
    } catch (e) {
      $hb(e);
    }
    tokenSource.dispose();
    this.a.delete(provider);
    return hover;
  }
  s(index, renderedHoverPart, hoverPart) {
    if (index >= this.renderedHoverParts.length || index < 0) {
      return;
    }
    const currentRenderedHoverPart = this.renderedHoverParts[index];
    const currentRenderedMarkdown = currentRenderedHoverPart.hoverElement;
    const renderedMarkdown = renderedHoverPart.hoverElement;
    const renderedChildrenElements = Array.from(renderedMarkdown.children);
    currentRenderedMarkdown.replaceChildren(...renderedChildrenElements);
    const newRenderedHoverPart = new RenderedMarkdownHoverPart(hoverPart, currentRenderedMarkdown, renderedHoverPart.disposables);
    currentRenderedMarkdown.focus();
    currentRenderedHoverPart.dispose();
    this.renderedHoverParts[index] = newRenderedHoverPart;
  }
  t(index) {
    this.renderedHoverParts[index].hoverElement.focus();
  }
  u(index) {
    return this.renderedHoverParts[index];
  }
  dispose() {
    this.b.dispose();
  }
};
function $Ldb(context, markdownHovers, editor, languageService, openerService) {
  markdownHovers.sort($9b((hover) => hover.ordinal, $$b));
  const renderedHoverParts = [];
  for (const markdownHover of markdownHovers) {
    renderedHoverParts.push(renderMarkdownInContainer(editor, markdownHover, languageService, openerService, context.onContentsChanged));
  }
  return new $Abb(renderedHoverParts);
}
function renderMarkdownInContainer(editor, markdownHover, languageService, openerService, onFinishedRendering) {
  const disposables = new $2c();
  const renderedMarkdown = $23("div.hover-row");
  const renderedMarkdownContents = $23("div.hover-row-contents");
  renderedMarkdown.appendChild(renderedMarkdownContents);
  const markdownStrings = markdownHover.contents;
  for (const markdownString of markdownStrings) {
    if ($cm(markdownString)) {
      continue;
    }
    const markdownHoverElement = $23("div.markdown-hover");
    const hoverContentsElement = $bk(markdownHoverElement, $23("div.hover-contents"));
    const renderer = disposables.add(new $Q_({ editor }, languageService, openerService));
    disposables.add(renderer.onDidRenderAsync(() => {
      hoverContentsElement.className = "hover-contents code-hover-contents";
      onFinishedRendering();
    }));
    const renderedContents = disposables.add(renderer.render(markdownString));
    hoverContentsElement.appendChild(renderedContents.element);
    renderedMarkdownContents.appendChild(markdownHoverElement);
  }
  const renderedHoverPart = {
    hoverPart: markdownHover,
    hoverElement: renderedMarkdown,
    dispose() {
      disposables.dispose();
    }
  };
  return renderedHoverPart;
}
function $Mdb(keybindingService, action) {
  switch (action) {
    case HoverVerbosityAction.Increase: {
      const kb = keybindingService.lookupKeybinding($Xbb);
      return kb ? localize(1213, null, kb.getLabel()) : localize(1214, null);
    }
    case HoverVerbosityAction.Decrease: {
      const kb = keybindingService.lookupKeybinding($1bb);
      return kb ? localize(1215, null, kb.getLabel()) : localize(1216, null);
    }
  }
}

// out-build/vs/editor/contrib/colorPicker/browser/colorPickerParts/colorPickerSaturationBox.js
var $31 = $;
var $Odb = class extends $3c {
  constructor(container2, r2, t) {
    super();
    this.r = r2;
    this.t = t;
    this.m = new $ze();
    this.onDidChange = this.m.event;
    this.n = new $ze();
    this.onColorFlushed = this.n.event;
    this.a = $31(".saturation-wrap");
    $bk(container2, this.a);
    this.c = document.createElement("canvas");
    this.c.className = "saturation-box";
    $bk(this.a, this.c);
    this.b = $31(".saturation-selection");
    $bk(this.a, this.b);
    this.layout();
    this.B($_i(this.a, $7j.POINTER_DOWN, (e) => this.u(e)));
    this.B(this.r.onDidChangeColor(this.C, this));
    this.j = null;
  }
  get domNode() {
    return this.a;
  }
  get canvas() {
    return this.c;
  }
  u(e) {
    if (!e.target || !(e.target instanceof Element)) {
      return;
    }
    this.j = this.B(new $pZ());
    const origin = $vj(this.a);
    if (e.target !== this.b) {
      this.w(e.offsetX, e.offsetY);
    }
    this.j.startMonitoring(e.target, e.pointerId, e.buttons, (event) => this.w(event.pageX - origin.left, event.pageY - origin.top), () => null);
    const pointerUpListener = $_i(e.target.ownerDocument, $7j.POINTER_UP, () => {
      this.n.fire();
      pointerUpListener.dispose();
      if (this.j) {
        this.j.stopMonitoring(true);
        this.j = null;
      }
    }, true);
  }
  w(left, top2) {
    const s = Math.max(0, Math.min(1, left / this.f));
    const v = Math.max(0, Math.min(1, 1 - top2 / this.g));
    this.z(s, v);
    this.m.fire({ s, v });
  }
  layout() {
    this.f = this.a.offsetWidth;
    this.g = this.a.offsetHeight;
    this.c.width = this.f * this.t;
    this.c.height = this.g * this.t;
    this.y();
    const hsva = this.r.color.hsva;
    this.z(hsva.s, hsva.v);
  }
  y() {
    const hsva = this.r.color.hsva;
    const saturatedColor = new $Vn(new $Un(hsva.h, 1, 1, 1));
    const ctx = this.c.getContext("2d");
    const whiteGradient = ctx.createLinearGradient(0, 0, this.c.width, 0);
    whiteGradient.addColorStop(0, "rgba(255, 255, 255, 1)");
    whiteGradient.addColorStop(0.5, "rgba(255, 255, 255, 0.5)");
    whiteGradient.addColorStop(1, "rgba(255, 255, 255, 0)");
    const blackGradient = ctx.createLinearGradient(0, 0, 0, this.c.height);
    blackGradient.addColorStop(0, "rgba(0, 0, 0, 0)");
    blackGradient.addColorStop(1, "rgba(0, 0, 0, 1)");
    ctx.rect(0, 0, this.c.width, this.c.height);
    ctx.fillStyle = $Vn.Format.CSS.format(saturatedColor);
    ctx.fill();
    ctx.fillStyle = whiteGradient;
    ctx.fill();
    ctx.fillStyle = blackGradient;
    ctx.fill();
  }
  z(s, v) {
    this.b.style.left = `${s * this.f}px`;
    this.b.style.top = `${this.g - v * this.g}px`;
  }
  C(color2) {
    if (this.j && this.j.isMonitoring()) {
      return;
    }
    this.y();
    const hsva = color2.hsva;
    this.z(hsva.s, hsva.v);
  }
};

// out-build/vs/editor/contrib/colorPicker/browser/colorPickerParts/colorPickerInsertButton.js
var $Pdb = class extends $3c {
  constructor(container2) {
    super();
    this.b = this.B(new $ze());
    this.onClicked = this.b.event;
    this.a = $bk(container2, document.createElement("button"));
    this.a.classList.add("insert-button");
    this.a.textContent = "Insert";
    this.B($_i(this.a, $7j.CLICK, () => {
      this.b.fire();
    }));
  }
  get button() {
    return this.a;
  }
};

// out-build/vs/editor/contrib/colorPicker/browser/colorPickerParts/colorPickerStrip.js
var $33 = $;
var $Tdb = class extends $3c {
  constructor(container2, t, type) {
    super();
    this.t = t;
    this.n = new $ze();
    this.onDidChange = this.n.event;
    this.s = new $ze();
    this.onColorFlushed = this.s.event;
    if (type === "standalone") {
      this.c = $bk(container2, $33(".standalone-strip"));
      this.f = $bk(this.c, $33(".standalone-overlay"));
    } else {
      this.c = $bk(container2, $33(".strip"));
      this.f = $bk(this.c, $33(".overlay"));
    }
    this.j = $bk(this.c, $33(".slider"));
    this.j.style.top = `0px`;
    this.B($_i(this.c, $7j.POINTER_DOWN, (e) => this.w(e)));
    this.B(t.onDidChangeColor(this.u, this));
    this.layout();
  }
  layout() {
    this.m = this.c.offsetHeight - this.j.offsetHeight;
    const value = this.C(this.t.color);
    this.z(value);
  }
  u(color2) {
    const value = this.C(color2);
    this.z(value);
  }
  w(e) {
    if (!e.target || !(e.target instanceof Element)) {
      return;
    }
    const monitor = this.B(new $pZ());
    const origin = $vj(this.c);
    this.c.classList.add("grabbing");
    if (e.target !== this.j) {
      this.y(e.offsetY);
    }
    monitor.startMonitoring(e.target, e.pointerId, e.buttons, (event) => this.y(event.pageY - origin.top), () => null);
    const pointerUpListener = $_i(e.target.ownerDocument, $7j.POINTER_UP, () => {
      this.s.fire();
      pointerUpListener.dispose();
      monitor.stopMonitoring(true);
      this.c.classList.remove("grabbing");
    }, true);
  }
  y(top2) {
    const value = Math.max(0, Math.min(1, 1 - top2 / this.m));
    this.z(value);
    this.n.fire(value);
  }
  z(value) {
    this.j.style.top = `${(1 - value) * this.m}px`;
  }
};
var $Udb = class extends $Tdb {
  constructor(container2, model, type) {
    super(container2, model, type);
    this.c.classList.add("opacity-strip");
    this.u(this.t.color);
  }
  u(color2) {
    super.u(color2);
    const { r: r2, g, b } = color2.rgba;
    const opaque = new $Vn(new $Sn(r2, g, b, 1));
    const transparent = new $Vn(new $Sn(r2, g, b, 0));
    this.f.style.background = `linear-gradient(to bottom, ${opaque} 0%, ${transparent} 100%)`;
  }
  C(color2) {
    return color2.hsva.a;
  }
};
var $Vdb = class extends $Tdb {
  constructor(container2, model, type) {
    super(container2, model, type);
    this.c.classList.add("hue-strip");
  }
  C(color2) {
    return 1 - color2.hsva.h / 360;
  }
};

// out-build/vs/editor/contrib/colorPicker/browser/colorPickerParts/colorPickerBody.js
var $41 = $;
var $Wdb = class extends $3c {
  constructor(container2, m, n, type) {
    super();
    this.m = m;
    this.n = n;
    this.j = null;
    this.b = $41(".colorpicker-body");
    $bk(container2, this.b);
    this.c = new $Odb(this.b, this.m, this.n);
    this.B(this.c);
    this.B(this.c.onDidChange(this.t, this));
    this.B(this.c.onColorFlushed(this.r, this));
    this.g = new $Udb(this.b, this.m, type);
    this.B(this.g);
    this.B(this.g.onDidChange(this.u, this));
    this.B(this.g.onColorFlushed(this.r, this));
    this.f = new $Vdb(this.b, this.m, type);
    this.B(this.f);
    this.B(this.f.onDidChange(this.w, this));
    this.B(this.f.onColorFlushed(this.r, this));
    if (type === "standalone") {
      this.j = this.B(new $Pdb(this.b));
      this.b.classList.add("standalone-colorpicker");
    }
  }
  r() {
    this.m.flushColor();
  }
  t({ s, v }) {
    const hsva = this.m.color.hsva;
    this.m.color = new $Vn(new $Un(hsva.h, s, v, hsva.a));
  }
  u(a) {
    const hsva = this.m.color.hsva;
    this.m.color = new $Vn(new $Un(hsva.h, hsva.s, hsva.v, a));
  }
  w(value) {
    const hsva = this.m.color.hsva;
    const h3 = (1 - value) * 360;
    this.m.color = new $Vn(new $Un(h3 === 360 ? 0 : h3, hsva.s, hsva.v, hsva.a));
  }
  get domNode() {
    return this.b;
  }
  get saturationBox() {
    return this.c;
  }
  get opacityStrip() {
    return this.g;
  }
  get hueStrip() {
    return this.f;
  }
  get enterButton() {
    return this.j;
  }
  layout() {
    this.c.layout();
    this.g.layout();
    this.f.layout();
  }
};

// out-build/vs/editor/contrib/colorPicker/browser/colorPickerParts/colorPickerCloseButton.js
var $42 = $;
var $Xdb = class extends $3c {
  constructor(container2) {
    super();
    this.b = this.B(new $ze());
    this.onClicked = this.b.event;
    this.a = document.createElement("div");
    this.a.classList.add("close-button");
    $bk(container2, this.a);
    const innerDiv = document.createElement("div");
    innerDiv.classList.add("close-button-inner-div");
    $bk(this.a, innerDiv);
    const closeButton = $bk(innerDiv, $42(".button" + ThemeIcon.asCSSSelector($9r("color-picker-close", $6l.close, localize(960, null)))));
    closeButton.classList.add("close-icon");
    this.B($_i(this.a, $7j.CLICK, () => {
      this.b.fire();
    }));
  }
};

// out-build/vs/editor/contrib/colorPicker/browser/colorPickerParts/colorPickerHeader.js
var $43 = $;
var $Ydb = class extends $3c {
  constructor(container2, m, themeService, n) {
    super();
    this.m = m;
    this.n = n;
    this.h = null;
    this.b = $43(".colorpicker-header");
    $bk(container2, this.b);
    this.c = $bk(this.b, $43(".picked-color"));
    $bk(this.c, $43("span.codicon.codicon-color-mode"));
    this.f = $bk(this.c, document.createElement("span"));
    this.f.classList.add("picked-color-presentation");
    const tooltip = localize(961, null);
    this.c.setAttribute("title", tooltip);
    this.g = $bk(this.b, $43(".original-color"));
    this.g.style.backgroundColor = $Vn.Format.CSS.format(this.m.originalColor) || "";
    this.j = themeService.getColorTheme().getColor($jp) || $Vn.white;
    this.B(themeService.onDidColorThemeChange((theme) => {
      this.j = theme.getColor($jp) || $Vn.white;
    }));
    this.B($_i(this.c, $7j.CLICK, () => this.m.selectNextColorPresentation()));
    this.B($_i(this.g, $7j.CLICK, () => {
      this.m.color = this.m.originalColor;
      this.m.flushColor();
    }));
    this.B(m.onDidChangeColor(this.r, this));
    this.B(m.onDidChangePresentation(this.s, this));
    this.c.style.backgroundColor = $Vn.Format.CSS.format(m.color) || "";
    this.c.classList.toggle("light", m.color.rgba.a < 0.5 ? this.j.isLighter() : m.color.isLighter());
    this.r(this.m.color);
    if (this.n === "standalone") {
      this.b.classList.add("standalone-colorpicker");
      this.h = this.B(new $Xdb(this.b));
    }
  }
  get domNode() {
    return this.b;
  }
  get closeButton() {
    return this.h;
  }
  get pickedColorNode() {
    return this.c;
  }
  get originalColorNode() {
    return this.g;
  }
  r(color2) {
    this.c.style.backgroundColor = $Vn.Format.CSS.format(color2) || "";
    this.c.classList.toggle("light", color2.rgba.a < 0.5 ? this.j.isLighter() : color2.isLighter());
    this.s();
  }
  s() {
    this.f.textContent = this.m.presentation ? this.m.presentation.label : "";
  }
};

// out-build/vs/editor/contrib/colorPicker/browser/colorPickerWidget.js
var $51 = $;
var $Zdb = class _$Zdb extends $qZ {
  static {
    this.a = "editor.contrib.colorPickerWidget";
  }
  constructor(container2, model, g, themeService, type) {
    super();
    this.model = model;
    this.g = g;
    this.B($_1.getInstance(getWindow(container2)).onDidChange(() => this.layout()));
    this.c = $51(".colorpicker-widget");
    container2.appendChild(this.c);
    this.header = this.B(new $Ydb(this.c, this.model, themeService, type));
    this.body = this.B(new $Wdb(this.c, this.model, this.g, type));
  }
  getId() {
    return _$Zdb.a;
  }
  layout() {
    this.body.layout();
  }
  get domNode() {
    return this.c;
  }
};

// out-build/vs/editor/contrib/colorPicker/browser/colorPickerModel.js
var $Ndb = class {
  get color() {
    return this.a;
  }
  set color(color2) {
    if (this.a.equals(color2)) {
      return;
    }
    this.a = color2;
    this.d.fire(color2);
  }
  get presentation() {
    return this.colorPresentations[this.f];
  }
  get colorPresentations() {
    return this.b;
  }
  set colorPresentations(colorPresentations) {
    this.b = colorPresentations;
    if (this.f > colorPresentations.length - 1) {
      this.f = 0;
    }
    this.e.fire(this.presentation);
  }
  constructor(color2, availableColorPresentations, f) {
    this.f = f;
    this.c = new $ze();
    this.onColorFlushed = this.c.event;
    this.d = new $ze();
    this.onDidChangeColor = this.d.event;
    this.e = new $ze();
    this.onDidChangePresentation = this.e.event;
    this.originalColor = color2;
    this.a = color2;
    this.b = availableColorPresentations;
  }
  selectNextColorPresentation() {
    this.f = (this.f + 1) % this.colorPresentations.length;
    this.flushColor();
    this.e.fire(this.presentation);
  }
  guessColorPresentation(color2, originalText) {
    let presentationIndex = -1;
    for (let i2 = 0; i2 < this.colorPresentations.length; i2++) {
      if (originalText.toLowerCase() === this.colorPresentations[i2].label) {
        presentationIndex = i2;
        break;
      }
    }
    if (presentationIndex === -1) {
      const originalTextPrefix = originalText.split("(")[0].toLowerCase();
      for (let i2 = 0; i2 < this.colorPresentations.length; i2++) {
        if (this.colorPresentations[i2].label.toLowerCase().startsWith(originalTextPrefix)) {
          presentationIndex = i2;
          break;
        }
      }
    }
    if (presentationIndex !== -1 && presentationIndex !== this.f) {
      this.f = presentationIndex;
      this.e.fire(this.presentation);
    }
  }
  flushColor() {
    this.c.fire(this.a);
  }
};

// out-build/vs/editor/contrib/colorPicker/browser/colorPickerParticipantUtils.js
var ColorPickerWidgetType;
(function(ColorPickerWidgetType2) {
  ColorPickerWidgetType2["Hover"] = "hover";
  ColorPickerWidgetType2["Standalone"] = "standalone";
})(ColorPickerWidgetType || (ColorPickerWidgetType = {}));
async function $Qdb(editorModel, colorInfo, provider) {
  const originalText = editorModel.getValueInRange(colorInfo.range);
  const { red, green, blue, alpha } = colorInfo.color;
  const rgba = new $Sn(Math.round(red * 255), Math.round(green * 255), Math.round(blue * 255), alpha);
  const color2 = new $Vn(rgba);
  const colorPresentations = await $Fbb(editorModel, colorInfo, provider, CancellationToken.None);
  const model = new $Ndb(color2, [], 0);
  model.colorPresentations = colorPresentations || [];
  model.guessColorPresentation(color2, originalText);
  return {
    range: $9C.lift(colorInfo.range),
    model,
    provider
  };
}
function $Rdb(editor, range, model) {
  const textEdits = [];
  const edit3 = model.presentation.textEdit ?? { range, text: model.presentation.label, forceMoveMarkers: false };
  textEdits.push(edit3);
  if (model.presentation.additionalTextEdits) {
    textEdits.push(...model.presentation.additionalTextEdits);
  }
  const replaceRange = $9C.lift(edit3.range);
  const trackedRange = editor.getModel()._setTrackedRange(
    null,
    replaceRange,
    3
    /* TrackedRangeStickiness.GrowsOnlyWhenTypingAfter */
  );
  editor.executeEdits("colorpicker", textEdits);
  editor.pushUndoStop();
  return editor.getModel()._getTrackedRange(trackedRange) ?? replaceRange;
}
async function $Sdb(editorModel, colorPickerModel, color2, range, colorHover) {
  const colorPresentations = await $Fbb(editorModel, {
    range,
    color: {
      red: color2.rgba.r / 255,
      green: color2.rgba.g / 255,
      blue: color2.rgba.b / 255,
      alpha: color2.rgba.a
    }
  }, colorHover.provider, CancellationToken.None);
  colorPickerModel.colorPresentations = colorPresentations || [];
}

// out-build/vs/editor/contrib/colorPicker/browser/hoverColorPicker/hoverColorPickerParticipant.js
var $1db = class _$1db {
  constructor(owner, range, model, provider) {
    this.owner = owner;
    this.range = range;
    this.model = model;
    this.provider = provider;
    this.forceShowAtRange = true;
  }
  isValidForHoverAnchor(anchor) {
    return anchor.type === 1 && this.range.startColumn <= anchor.range.startColumn && this.range.endColumn >= anchor.range.endColumn;
  }
  static fromBaseColor(owner, color2) {
    return new _$1db(owner, color2.range, color2.model, color2.provider);
  }
};
var $2db = class $2db2 {
  constructor(b, c) {
    this.b = b;
    this.c = c;
    this.hoverOrdinal = 2;
  }
  computeSync(_anchor, _lineDecorations, source) {
    return [];
  }
  computeAsync(anchor, lineDecorations, source, token) {
    return $ji.fromPromise(this.f(anchor, lineDecorations, source));
  }
  async f(_anchor, lineDecorations, source) {
    if (!this.b.hasModel()) {
      return [];
    }
    if (!this.g(source)) {
      return [];
    }
    const colorDetector = $Lbb.get(this.b);
    if (!colorDetector) {
      return [];
    }
    for (const d of lineDecorations) {
      if (!colorDetector.isColorDecoration(d)) {
        continue;
      }
      const colorData = colorDetector.getColorData(d.range.getStartPosition());
      if (colorData) {
        const colorHover = $1db.fromBaseColor(this, await $Qdb(this.b.getModel(), colorData.colorInfo, colorData.provider));
        return [colorHover];
      }
    }
    return [];
  }
  g(source) {
    const decoratorActivatedOn = this.b.getOption(
      154
      /* EditorOption.colorDecoratorsActivatedOn */
    );
    switch (source) {
      case 0:
        return decoratorActivatedOn === "hover" || decoratorActivatedOn === "clickAndHover";
      case 1:
        return decoratorActivatedOn === "click" || decoratorActivatedOn === "clickAndHover";
      case 2:
        return true;
    }
  }
  renderHoverParts(context, hoverParts) {
    const editor = this.b;
    if (hoverParts.length === 0 || !editor.hasModel()) {
      return new $Abb([]);
    }
    if (context.setMinimumDimensions) {
      const minimumHeight = editor.getOption(
        68
        /* EditorOption.lineHeight */
      ) + 8;
      context.setMinimumDimensions(new $rj(302, minimumHeight));
    }
    const disposables = new $2c();
    const colorHover = hoverParts[0];
    const editorModel = editor.getModel();
    const model = colorHover.model;
    this.a = disposables.add(new $Zdb(
      context.fragment,
      model,
      editor.getOption(
        149
        /* EditorOption.pixelRatio */
      ),
      this.c,
      "hover"
      /* ColorPickerWidgetType.Hover */
    ));
    let editorUpdatedByColorPicker = false;
    let range = new $9C(colorHover.range.startLineNumber, colorHover.range.startColumn, colorHover.range.endLineNumber, colorHover.range.endColumn);
    disposables.add(model.onColorFlushed(async (color2) => {
      await $Sdb(editorModel, model, color2, range, colorHover);
      editorUpdatedByColorPicker = true;
      range = $Rdb(editor, range, model);
    }));
    disposables.add(model.onDidChangeColor((color2) => {
      $Sdb(editorModel, model, color2, range, colorHover);
    }));
    disposables.add(editor.onDidChangeModelContent((e) => {
      if (editorUpdatedByColorPicker) {
        editorUpdatedByColorPicker = false;
      } else {
        context.hide();
        editor.focus();
      }
    }));
    const renderedHoverPart = {
      hoverPart: $1db.fromBaseColor(this, colorHover),
      hoverElement: this.a.domNode,
      dispose() {
        disposables.dispose();
      }
    };
    return new $Abb([renderedHoverPart]);
  }
  getAccessibleContent(hoverPart) {
    return localize(962, null);
  }
  handleResize() {
    this.a?.layout();
  }
  handleHide() {
    this.a?.dispose();
    this.a = void 0;
  }
  isColorPickerVisible() {
    return !!this.a;
  }
};
$2db = __decorate([
  __param(1, $gs)
], $2db);

// out-build/vs/editor/contrib/gotoSymbol/browser/link/clickLinkGesture.js
function hasModifier(e, modifier) {
  return !!e[modifier];
}
var $3db = class {
  constructor(source, opts) {
    this.target = source.target;
    this.isLeftClick = source.event.leftButton;
    this.isMiddleClick = source.event.middleButton;
    this.isRightClick = source.event.rightButton;
    this.hasTriggerModifier = hasModifier(source.event, opts.triggerModifier);
    this.hasSideBySideModifier = hasModifier(source.event, opts.triggerSideBySideModifier);
    this.isNoneOrSingleMouseDown = source.event.detail <= 1;
  }
};
var $4db = class {
  constructor(source, opts) {
    this.keyCodeIsTriggerKey = source.keyCode === opts.triggerKey;
    this.keyCodeIsSideBySideKey = source.keyCode === opts.triggerSideBySideKey;
    this.hasTriggerModifier = hasModifier(source, opts.triggerModifier);
  }
};
var $5db = class {
  constructor(triggerKey, triggerModifier, triggerSideBySideKey, triggerSideBySideModifier) {
    this.triggerKey = triggerKey;
    this.triggerModifier = triggerModifier;
    this.triggerSideBySideKey = triggerSideBySideKey;
    this.triggerSideBySideModifier = triggerSideBySideModifier;
  }
  equals(other) {
    return this.triggerKey === other.triggerKey && this.triggerModifier === other.triggerModifier && this.triggerSideBySideKey === other.triggerSideBySideKey && this.triggerSideBySideModifier === other.triggerSideBySideModifier;
  }
};
function createOptions(multiCursorModifier2) {
  if (multiCursorModifier2 === "altKey") {
    if ($m) {
      return new $5db(57, "metaKey", 6, "altKey");
    }
    return new $5db(5, "ctrlKey", 6, "altKey");
  }
  if ($m) {
    return new $5db(6, "altKey", 57, "metaKey");
  }
  return new $5db(6, "altKey", 5, "ctrlKey");
}
var $6db = class extends $3c {
  constructor(editor, opts) {
    super();
    this.a = this.B(new $ze());
    this.onMouseMoveOrRelevantKeyDown = this.a.event;
    this.b = this.B(new $ze());
    this.onExecute = this.b.event;
    this.c = this.B(new $ze());
    this.onCancel = this.c.event;
    this.f = editor;
    this.g = opts?.extractLineNumberFromMouseEvent ?? ((e) => e.target.position ? e.target.position.lineNumber : 0);
    this.h = createOptions(this.f.getOption(
      79
      /* EditorOption.multiCursorModifier */
    ));
    this.j = null;
    this.m = false;
    this.n = 0;
    this.B(this.f.onDidChangeConfiguration((e) => {
      if (e.hasChanged(
        79
        /* EditorOption.multiCursorModifier */
      )) {
        const newOpts = createOptions(this.f.getOption(
          79
          /* EditorOption.multiCursorModifier */
        ));
        if (this.h.equals(newOpts)) {
          return;
        }
        this.h = newOpts;
        this.j = null;
        this.m = false;
        this.n = 0;
        this.c.fire();
      }
    }));
    this.B(this.f.onMouseMove((e) => this.s(new $3db(e, this.h))));
    this.B(this.f.onMouseDown((e) => this.t(new $3db(e, this.h))));
    this.B(this.f.onMouseUp((e) => this.u(new $3db(e, this.h))));
    this.B(this.f.onKeyDown((e) => this.w(new $4db(e, this.h))));
    this.B(this.f.onKeyUp((e) => this.y(new $4db(e, this.h))));
    this.B(this.f.onMouseDrag(() => this.z()));
    this.B(this.f.onDidChangeCursorSelection((e) => this.r(e)));
    this.B(this.f.onDidChangeModel((e) => this.z()));
    this.B(this.f.onDidChangeModelContent(() => this.z()));
    this.B(this.f.onDidScrollChange((e) => {
      if (e.scrollTopChanged || e.scrollLeftChanged) {
        this.z();
      }
    }));
  }
  r(e) {
    if (e.selection && e.selection.startColumn !== e.selection.endColumn) {
      this.z();
    }
  }
  s(mouseEvent) {
    this.j = mouseEvent;
    this.a.fire([mouseEvent, null]);
  }
  t(mouseEvent) {
    this.m = mouseEvent.hasTriggerModifier;
    this.n = this.g(mouseEvent);
  }
  u(mouseEvent) {
    const currentLineNumber = this.g(mouseEvent);
    if (this.m && this.n && this.n === currentLineNumber) {
      this.b.fire(mouseEvent);
    }
  }
  w(e) {
    if (this.j && (e.keyCodeIsTriggerKey || e.keyCodeIsSideBySideKey && e.hasTriggerModifier)) {
      this.a.fire([this.j, e]);
    } else if (e.hasTriggerModifier) {
      this.c.fire();
    }
  }
  y(e) {
    if (e.keyCodeIsTriggerKey) {
      this.c.fire();
    }
  }
  z() {
    this.j = null;
    this.m = false;
    this.c.fire();
  }
};

// out-build/vs/editor/contrib/inlayHints/browser/inlayHints.js
var $7db = class {
  constructor(range, direction) {
    this.range = range;
    this.direction = direction;
  }
};
var $8db = class _$8db {
  constructor(hint, anchor, provider) {
    this.hint = hint;
    this.anchor = anchor;
    this.provider = provider;
    this.c = false;
  }
  with(delta) {
    const result = new _$8db(this.hint, delta.anchor, this.provider);
    result.c = this.c;
    result.d = this.d;
    return result;
  }
  async resolve(token) {
    if (typeof this.provider.resolveInlayHint !== "function") {
      return;
    }
    if (this.d) {
      await this.d;
      if (token.isCancellationRequested) {
        return;
      }
      return this.resolve(token);
    }
    if (!this.c) {
      this.d = this.e(token).finally(() => this.d = void 0);
    }
    await this.d;
  }
  async e(token) {
    try {
      const newHint = await Promise.resolve(this.provider.resolveInlayHint(this.hint, token));
      this.hint.tooltip = newHint?.tooltip ?? this.hint.tooltip;
      this.hint.label = newHint?.label ?? this.hint.label;
      this.hint.textEdits = newHint?.textEdits ?? this.hint.textEdits;
      this.c = true;
    } catch (err) {
      $hb(err);
      this.c = false;
    }
  }
};
var $9db = class _$9db {
  static {
    this.c = Object.freeze({ dispose() {
    }, hints: [] });
  }
  static async create(registry4, model, ranges, token) {
    const data = [];
    const promises = registry4.ordered(model).reverse().map((provider) => ranges.map(async (range) => {
      try {
        const result = await provider.provideInlayHints(model, range, token);
        if (result?.hints.length || provider.onDidChangeInlayHints) {
          data.push([result ?? _$9db.c, provider]);
        }
      } catch (err) {
        $hb(err);
      }
    }));
    await Promise.all(promises.flat());
    if (token.isCancellationRequested || model.isDisposed()) {
      throw new $lb();
    }
    return new _$9db(ranges, data, model);
  }
  constructor(ranges, data, model) {
    this.d = new $2c();
    this.ranges = ranges;
    this.provider = /* @__PURE__ */ new Set();
    const items = [];
    for (const [list2, provider] of data) {
      this.d.add(list2);
      this.provider.add(provider);
      for (const hint of list2.hints) {
        const position = model.validatePosition(hint.position);
        let direction = "before";
        const wordRange = _$9db.e(model, position);
        let range;
        if (wordRange.getStartPosition().isBefore(position)) {
          range = $9C.fromPositions(wordRange.getStartPosition(), position);
          direction = "after";
        } else {
          range = $9C.fromPositions(position, wordRange.getEndPosition());
          direction = "before";
        }
        items.push(new $8db(hint, new $7db(range, direction), provider));
      }
    }
    this.items = items.sort((a, b) => $8C.compare(a.hint.position, b.hint.position));
  }
  dispose() {
    this.d.dispose();
  }
  static e(model, position) {
    const line = position.lineNumber;
    const word = model.getWordAtPosition(position);
    if (word) {
      return new $9C(line, word.startColumn, line, word.endColumn);
    }
    model.tokenization.tokenizeIfCheap(line);
    const tokens = model.tokenization.getLineTokens(line);
    const offset = position.column - 1;
    const idx = tokens.findTokenIndexAtOffset(offset);
    let start = tokens.getStartOffset(idx);
    let end = tokens.getEndOffset(idx);
    if (end - start === 1) {
      if (start === offset && idx > 1) {
        start = tokens.getStartOffset(idx - 1);
        end = tokens.getEndOffset(idx - 1);
      } else if (end === offset && idx < tokens.getCount() - 1) {
        start = tokens.getStartOffset(idx + 1);
        end = tokens.getEndOffset(idx + 1);
      }
    }
    return new $9C(line, start + 1, line, end + 1);
  }
};
function $0db(command4) {
  return URI.from({
    scheme: Schemas.command,
    path: command4.id,
    query: command4.arguments && encodeURIComponent(JSON.stringify(command4.arguments))
  }).toString();
}

// out-build/vs/editor/browser/editorBrowser.js
var ContentWidgetPositionPreference;
(function(ContentWidgetPositionPreference3) {
  ContentWidgetPositionPreference3[ContentWidgetPositionPreference3["EXACT"] = 0] = "EXACT";
  ContentWidgetPositionPreference3[ContentWidgetPositionPreference3["ABOVE"] = 1] = "ABOVE";
  ContentWidgetPositionPreference3[ContentWidgetPositionPreference3["BELOW"] = 2] = "BELOW";
})(ContentWidgetPositionPreference || (ContentWidgetPositionPreference = {}));
var OverlayWidgetPositionPreference;
(function(OverlayWidgetPositionPreference3) {
  OverlayWidgetPositionPreference3[OverlayWidgetPositionPreference3["TOP_RIGHT_CORNER"] = 0] = "TOP_RIGHT_CORNER";
  OverlayWidgetPositionPreference3[OverlayWidgetPositionPreference3["BOTTOM_RIGHT_CORNER"] = 1] = "BOTTOM_RIGHT_CORNER";
  OverlayWidgetPositionPreference3[OverlayWidgetPositionPreference3["TOP_CENTER"] = 2] = "TOP_CENTER";
})(OverlayWidgetPositionPreference || (OverlayWidgetPositionPreference = {}));
var MouseTargetType;
(function(MouseTargetType3) {
  MouseTargetType3[MouseTargetType3["UNKNOWN"] = 0] = "UNKNOWN";
  MouseTargetType3[MouseTargetType3["TEXTAREA"] = 1] = "TEXTAREA";
  MouseTargetType3[MouseTargetType3["GUTTER_GLYPH_MARGIN"] = 2] = "GUTTER_GLYPH_MARGIN";
  MouseTargetType3[MouseTargetType3["GUTTER_LINE_NUMBERS"] = 3] = "GUTTER_LINE_NUMBERS";
  MouseTargetType3[MouseTargetType3["GUTTER_LINE_DECORATIONS"] = 4] = "GUTTER_LINE_DECORATIONS";
  MouseTargetType3[MouseTargetType3["GUTTER_VIEW_ZONE"] = 5] = "GUTTER_VIEW_ZONE";
  MouseTargetType3[MouseTargetType3["CONTENT_TEXT"] = 6] = "CONTENT_TEXT";
  MouseTargetType3[MouseTargetType3["CONTENT_EMPTY"] = 7] = "CONTENT_EMPTY";
  MouseTargetType3[MouseTargetType3["CONTENT_VIEW_ZONE"] = 8] = "CONTENT_VIEW_ZONE";
  MouseTargetType3[MouseTargetType3["CONTENT_WIDGET"] = 9] = "CONTENT_WIDGET";
  MouseTargetType3[MouseTargetType3["OVERVIEW_RULER"] = 10] = "OVERVIEW_RULER";
  MouseTargetType3[MouseTargetType3["SCROLLBAR"] = 11] = "SCROLLBAR";
  MouseTargetType3[MouseTargetType3["OVERLAY_WIDGET"] = 12] = "OVERLAY_WIDGET";
  MouseTargetType3[MouseTargetType3["OUTSIDE_EDITOR"] = 13] = "OUTSIDE_EDITOR";
})(MouseTargetType || (MouseTargetType = {}));
var DiffEditorState;
(function(DiffEditorState2) {
  DiffEditorState2[DiffEditorState2["Idle"] = 0] = "Idle";
  DiffEditorState2[DiffEditorState2["ComputingDiff"] = 1] = "ComputingDiff";
  DiffEditorState2[DiffEditorState2["DiffComputed"] = 2] = "DiffComputed";
})(DiffEditorState || (DiffEditorState = {}));
function $P5(thing) {
  if (thing && typeof thing.getEditorType === "function") {
    return thing.getEditorType() === EditorType.ICodeEditor;
  } else {
    return false;
  }
}
function $Q5(thing) {
  if (thing && typeof thing.getEditorType === "function") {
    return thing.getEditorType() === EditorType.IDiffEditor;
  } else {
    return false;
  }
}
function $R5(thing) {
  return !!thing && typeof thing === "object" && typeof thing.onDidChangeActiveEditor === "function";
}
function $S5(thing) {
  if ($P5(thing)) {
    return thing;
  }
  if ($Q5(thing)) {
    return thing.getModifiedEditor();
  }
  if ($R5(thing) && $P5(thing.activeCodeEditor)) {
    return thing.activeCodeEditor;
  }
  return null;
}
function $T5(thing) {
  if ($P5(thing) || $Q5(thing)) {
    return thing;
  }
  return null;
}

// out-build/vs/editor/browser/widget/codeEditor/embeddedCodeEditorWidget.js
var $bdb = class $bdb2 extends $D9 {
  constructor(domElement, options3, codeEditorWidgetOptions, parentEditor, instantiationService, codeEditorService, commandService, contextKeyService, themeService, notificationService, accessibilityService, languageConfigurationService, languageFeaturesService) {
    super(domElement, { ...parentEditor.getRawOptions(), overflowWidgetsDomNode: parentEditor.getOverflowWidgetsDomNode() }, codeEditorWidgetOptions, instantiationService, codeEditorService, commandService, contextKeyService, themeService, notificationService, accessibilityService, languageConfigurationService, languageFeaturesService);
    this.kb = parentEditor;
    this.mc = options3;
    super.updateOptions(this.mc);
    this.B(parentEditor.onDidChangeConfiguration((e) => this.nc(e)));
  }
  getParentEditor() {
    return this.kb;
  }
  nc(e) {
    super.updateOptions(this.kb.getRawOptions());
    super.updateOptions(this.mc);
  }
  updateOptions(newOptions) {
    $Ov(this.mc, newOptions, true);
    super.updateOptions(this.mc);
  }
};
$bdb = __decorate([
  __param(4, $Pk),
  __param(5, $U5),
  __param(6, $sn),
  __param(7, $on),
  __param(8, $gs),
  __param(9, $PJ),
  __param(10, $ND),
  __param(11, $NF),
  __param(12, $mP)
], $bdb);

// out-build/vs/editor/contrib/zoneWidget/browser/zoneWidget.js
var defaultColor = new $Vn(new $Sn(0, 122, 204));
var defaultOptions = {
  showArrow: true,
  showFrame: true,
  className: "",
  frameColor: defaultColor,
  arrowColor: defaultColor,
  keepEditorSelection: false
};
var WIDGET_ID = "vs.editor.contrib.zoneWidget";
var ViewZoneDelegate = class {
  constructor(domNode, afterLineNumber, afterColumn, heightInLines, onDomNodeTop, onComputedHeight, showInHiddenAreas, ordinal) {
    this.id = "";
    this.domNode = domNode;
    this.afterLineNumber = afterLineNumber;
    this.afterColumn = afterColumn;
    this.heightInLines = heightInLines;
    this.showInHiddenAreas = showInHiddenAreas;
    this.ordinal = ordinal;
    this.a = onDomNodeTop;
    this.b = onComputedHeight;
  }
  onDomNodeTop(top2) {
    this.a(top2);
  }
  onComputedHeight(height) {
    this.b(height);
  }
};
var $$db = class {
  constructor(id2, domNode) {
    this.a = id2;
    this.b = domNode;
  }
  getId() {
    return this.a;
  }
  getDomNode() {
    return this.b;
  }
  getPosition() {
    return null;
  }
};
var Arrow2 = class _Arrow {
  static {
    this.a = new $lW(".arrow-decoration-");
  }
  constructor(g) {
    this.g = g;
    this.b = _Arrow.a.nextId();
    this.c = this.g.createDecorationsCollection();
    this.d = null;
    this.f = -1;
  }
  dispose() {
    this.hide();
    $YZ(this.b);
  }
  set color(value) {
    if (this.d !== value) {
      this.d = value;
      this.h();
    }
  }
  set height(value) {
    if (this.f !== value) {
      this.f = value;
      this.h();
    }
  }
  h() {
    $YZ(this.b);
    $XZ(`.monaco-editor ${this.b}`, `border-style: solid; border-color: transparent; border-bottom-color: ${this.d}; border-width: ${this.f}px; bottom: -${this.f}px !important; margin-left: -${this.f}px; `);
  }
  show(where) {
    if (where.column === 1) {
      where = { lineNumber: where.lineNumber, column: 2 };
    }
    this.c.set([{
      range: $9C.fromPositions(where),
      options: {
        description: "zone-widget-arrow",
        className: this.b,
        stickiness: 1
        /* TrackedRangeStickiness.NeverGrowsWhenTypingAtEdges */
      }
    }]);
  }
  hide() {
    this.c.clear();
  }
};
var $_db = class {
  constructor(editor, options3 = {}) {
    this.f = null;
    this.g = null;
    this.h = null;
    this.j = false;
    this.l = null;
    this.n = new $2c();
    this.container = null;
    this.w = false;
    this.editor = editor;
    this.k = this.editor.createDecorationsCollection();
    this.options = $Lv(options3);
    $Ov(this.options, defaultOptions, false);
    this.domNode = document.createElement("div");
    if (!this.options.isAccessible) {
      this.domNode.setAttribute("aria-hidden", "true");
      this.domNode.setAttribute("role", "presentation");
    }
    this.n.add(this.editor.onDidLayoutChange((info) => {
      const width2 = this.q(info);
      this.domNode.style.width = width2 + "px";
      this.domNode.style.left = this.t(info) + "px";
      this.C(width2);
    }));
  }
  dispose() {
    if (this.g) {
      this.editor.removeOverlayWidget(this.g);
      this.g = null;
    }
    if (this.l) {
      this.editor.changeViewZones((accessor) => {
        if (this.l) {
          accessor.removeZone(this.l.id);
        }
        this.l = null;
      });
    }
    this.k.clear();
    this.n.dispose();
  }
  create() {
    this.domNode.classList.add("zone-widget");
    if (this.options.className) {
      this.domNode.classList.add(this.options.className);
    }
    this.container = document.createElement("div");
    this.container.classList.add("zone-widget-container");
    this.domNode.appendChild(this.container);
    if (this.options.showArrow) {
      this.f = new Arrow2(this.editor);
      this.n.add(this.f);
    }
    this.B(this.container);
    this.F();
    this.o();
  }
  style(styles) {
    if (styles.frameColor) {
      this.options.frameColor = styles.frameColor;
    }
    if (styles.arrowColor) {
      this.options.arrowColor = styles.arrowColor;
    }
    this.o();
  }
  o() {
    if (this.container && this.options.frameColor) {
      const frameColor = this.options.frameColor.toString();
      this.container.style.borderTopColor = frameColor;
      this.container.style.borderBottomColor = frameColor;
    }
    if (this.f && this.options.arrowColor) {
      const arrowColor = this.options.arrowColor.toString();
      this.f.color = arrowColor;
    }
  }
  q(info) {
    return info.width - info.minimap.minimapWidth - info.verticalScrollbarWidth;
  }
  t(info) {
    if (info.minimap.minimapWidth > 0 && info.minimap.minimapLeft === 0) {
      return info.minimap.minimapWidth;
    }
    return 0;
  }
  u(top2) {
    this.domNode.style.top = top2 + "px";
  }
  v(height) {
    this.domNode.style.height = `${height}px`;
    if (this.container) {
      const containerHeight = height - this.x();
      this.container.style.height = `${containerHeight}px`;
      const layoutInfo = this.editor.getLayoutInfo();
      this.D(containerHeight, this.q(layoutInfo));
    }
    this.h?.layout();
  }
  get position() {
    const range = this.k.getRange(0);
    if (!range) {
      return void 0;
    }
    return range.getStartPosition();
  }
  hasFocus() {
    return this.domNode.contains($Lj());
  }
  show(rangeOrPos, heightInLines) {
    const range = $9C.isIRange(rangeOrPos) ? $9C.lift(rangeOrPos) : $9C.fromPositions(rangeOrPos);
    this.w = true;
    this.y(range, heightInLines);
    this.w = false;
    this.k.set([{ range, options: $WI.EMPTY }]);
  }
  updatePositionAndHeight(rangeOrPos, heightInLines) {
    if (this.l) {
      rangeOrPos = $9C.isIRange(rangeOrPos) ? $9C.getStartPosition(rangeOrPos) : rangeOrPos;
      this.l.afterLineNumber = rangeOrPos.lineNumber;
      this.l.afterColumn = rangeOrPos.column;
      this.l.heightInLines = heightInLines ?? this.l.heightInLines;
      this.editor.changeViewZones((accessor) => {
        accessor.layoutZone(this.l.id);
      });
      this.k.set([{
        range: $9C.isIRange(rangeOrPos) ? rangeOrPos : $9C.fromPositions(rangeOrPos),
        options: $WI.EMPTY
      }]);
      this.G();
    }
  }
  hide() {
    if (this.l) {
      this.editor.changeViewZones((accessor) => {
        if (this.l) {
          accessor.removeZone(this.l.id);
        }
      });
      this.l = null;
    }
    if (this.g) {
      this.editor.removeOverlayWidget(this.g);
      this.g = null;
    }
    this.f?.hide();
    this.k.clear();
    this.j = false;
  }
  x() {
    const lineHeight = this.editor.getOption(
      68
      /* EditorOption.lineHeight */
    );
    let result = 0;
    if (this.options.showArrow) {
      const arrowHeight = Math.round(lineHeight / 3);
      result += 2 * arrowHeight;
    }
    if (this.options.showFrame) {
      const frameThickness = Math.round(lineHeight / 9);
      result += 2 * frameThickness;
    }
    return result;
  }
  y(where, heightInLines) {
    const position = where.getStartPosition();
    const layoutInfo = this.editor.getLayoutInfo();
    const width2 = this.q(layoutInfo);
    this.domNode.style.width = `${width2}px`;
    this.domNode.style.left = this.t(layoutInfo) + "px";
    const viewZoneDomNode = document.createElement("div");
    viewZoneDomNode.style.overflow = "hidden";
    const lineHeight = this.editor.getOption(
      68
      /* EditorOption.lineHeight */
    );
    if (!this.options.allowUnlimitedHeight) {
      const maxHeightInLines = Math.max(12, this.editor.getLayoutInfo().height / lineHeight * 0.8);
      heightInLines = Math.min(heightInLines, maxHeightInLines);
    }
    let arrowHeight = 0;
    let frameThickness = 0;
    if (this.f && this.options.showArrow) {
      arrowHeight = Math.round(lineHeight / 3);
      this.f.height = arrowHeight;
      this.f.show(position);
    }
    if (this.options.showFrame) {
      frameThickness = Math.round(lineHeight / 9);
    }
    this.editor.changeViewZones((accessor) => {
      if (this.l) {
        accessor.removeZone(this.l.id);
      }
      if (this.g) {
        this.editor.removeOverlayWidget(this.g);
        this.g = null;
      }
      this.domNode.style.top = "-1000px";
      this.l = new ViewZoneDelegate(viewZoneDomNode, position.lineNumber, position.column, heightInLines, (top2) => this.u(top2), (height) => this.v(height), this.options.showInHiddenAreas, this.options.ordinal);
      this.l.id = accessor.addZone(this.l);
      this.g = new $$db(WIDGET_ID + this.l.id, this.domNode);
      this.editor.addOverlayWidget(this.g);
    });
    this.G();
    if (this.container && this.options.showFrame) {
      const width3 = this.options.frameWidth ? this.options.frameWidth : frameThickness;
      this.container.style.borderTopWidth = width3 + "px";
      this.container.style.borderBottomWidth = width3 + "px";
    }
    const containerHeight = heightInLines * lineHeight - this.x();
    if (this.container) {
      this.container.style.top = arrowHeight + "px";
      this.container.style.height = containerHeight + "px";
      this.container.style.overflow = "hidden";
    }
    this.D(containerHeight, width2);
    if (!this.options.keepEditorSelection) {
      this.editor.setSelection(where);
    }
    const model = this.editor.getModel();
    if (model) {
      const range = model.validateRange(new $9C(where.startLineNumber, 1, where.endLineNumber + 1, 1));
      this.z(range, range.startLineNumber === model.getLineCount());
    }
  }
  z(range, isLastLine) {
    if (isLastLine) {
      this.editor.revealLineNearTop(
        range.endLineNumber,
        0
        /* ScrollType.Smooth */
      );
    } else {
      this.editor.revealRange(
        range,
        0
        /* ScrollType.Smooth */
      );
    }
  }
  A(className, classToReplace) {
    if (!this.container) {
      return;
    }
    if (classToReplace) {
      this.container.classList.remove(classToReplace);
    }
    this.container.classList.add(className);
  }
  C(widthInPixel) {
  }
  D(heightInPixel, widthInPixel) {
  }
  E(newHeightInLines) {
    if (this.l && this.l.heightInLines !== newHeightInLines) {
      this.editor.changeViewZones((accessor) => {
        if (this.l) {
          this.l.heightInLines = newHeightInLines;
          accessor.layoutZone(this.l.id);
        }
      });
      this.G();
    }
  }
  // --- sash
  F() {
    if (this.h) {
      return;
    }
    this.h = this.n.add(new $q2(this.domNode, this, {
      orientation: 1
      /* Orientation.HORIZONTAL */
    }));
    if (!this.options.isResizeable) {
      this.h.state = 0;
    }
    let data;
    this.n.add(this.h.onDidStart((e) => {
      if (this.l) {
        data = {
          startY: e.startY,
          heightInLines: this.l.heightInLines,
          ...this.I()
        };
      }
    }));
    this.n.add(this.h.onDidEnd(() => {
      data = void 0;
    }));
    this.n.add(this.h.onDidChange((evt) => {
      if (data) {
        const lineDelta = (evt.currentY - data.startY) / this.editor.getOption(
          68
          /* EditorOption.lineHeight */
        );
        const roundedLineDelta = lineDelta < 0 ? Math.ceil(lineDelta) : Math.floor(lineDelta);
        const newHeightInLines = data.heightInLines + roundedLineDelta;
        if (newHeightInLines > data.minLines && newHeightInLines < data.maxLines) {
          this.j = true;
          this.E(newHeightInLines);
        }
      }
    }));
  }
  G() {
    if (this.h) {
      const { minLines, maxLines } = this.I();
      this.h.state = minLines === maxLines ? 0 : 3;
    }
  }
  get H() {
    return this.j;
  }
  I() {
    return { minLines: 5, maxLines: 35 };
  }
  getHorizontalSashLeft() {
    return 0;
  }
  getHorizontalSashTop() {
    return (this.domNode.style.height === null ? 0 : parseInt(this.domNode.style.height)) - this.x() / 2;
  }
  getHorizontalSashWidth() {
    const layoutInfo = this.editor.getLayoutInfo();
    return layoutInfo.width - layoutInfo.minimap.minimapWidth;
  }
};

// out-build/vs/editor/contrib/peekView/browser/peekView.js
var $aeb = $Qk("IPeekViewService");
$SC(
  $aeb,
  class {
    constructor() {
      this.a = /* @__PURE__ */ new Map();
    }
    addExclusiveWidget(editor, widget) {
      const existing = this.a.get(editor);
      if (existing) {
        existing.listener.dispose();
        existing.widget.dispose();
      }
      const remove = () => {
        const data = this.a.get(editor);
        if (data && data.widget === widget) {
          data.listener.dispose();
          this.a.delete(editor);
        }
      };
      this.a.set(editor, { widget, listener: widget.onDidClose(remove) });
    }
  },
  1
  /* InstantiationType.Delayed */
);
var PeekContext;
(function(PeekContext2) {
  PeekContext2.inPeekEditor = new $nn("inReferenceSearchEditor", true, localize(1360, null));
  PeekContext2.notInPeekEditor = PeekContext2.inPeekEditor.toNegated();
})(PeekContext || (PeekContext = {}));
var PeekContextController = class PeekContextController2 {
  static {
    this.ID = "editor.contrib.referenceController";
  }
  constructor(editor, contextKeyService) {
    if (editor instanceof $bdb) {
      PeekContext.inPeekEditor.bindTo(contextKeyService);
    }
  }
  dispose() {
  }
};
PeekContextController = __decorate([
  __param(1, $on)
], PeekContextController);
$85(
  PeekContextController.ID,
  PeekContextController,
  0
  /* EditorContributionInstantiation.Eager */
);
function $beb(accessor) {
  const editor = accessor.get($U5).getFocusedCodeEditor();
  if (editor instanceof $bdb) {
    return editor.getParentEditor();
  }
  return editor;
}
var defaultOptions2 = {
  headerBackgroundColor: $Vn.white,
  primaryHeadingColor: $Vn.fromHex("#333333"),
  secondaryHeadingColor: $Vn.fromHex("#6c6c6cb3")
};
var $ceb = class $ceb2 extends $_db {
  constructor(editor, options3, Q) {
    super(editor, options3);
    this.Q = Q;
    this.p = new $ze();
    this.onDidClose = this.p.event;
    $Ov(this.options, defaultOptions2, false);
  }
  dispose() {
    if (!this.s) {
      this.s = true;
      super.dispose();
      this.p.fire(this);
    }
  }
  style(styles) {
    const options3 = this.options;
    if (styles.headerBackgroundColor) {
      options3.headerBackgroundColor = styles.headerBackgroundColor;
    }
    if (styles.primaryHeadingColor) {
      options3.primaryHeadingColor = styles.primaryHeadingColor;
    }
    if (styles.secondaryHeadingColor) {
      options3.secondaryHeadingColor = styles.secondaryHeadingColor;
    }
    super.style(styles);
  }
  o() {
    super.o();
    const options3 = this.options;
    if (this.J && options3.headerBackgroundColor) {
      this.J.style.backgroundColor = options3.headerBackgroundColor.toString();
    }
    if (this.L && options3.primaryHeadingColor) {
      this.L.style.color = options3.primaryHeadingColor.toString();
    }
    if (this.M && options3.secondaryHeadingColor) {
      this.M.style.color = options3.secondaryHeadingColor.toString();
    }
    if (this.P && options3.frameColor) {
      this.P.style.borderColor = options3.frameColor.toString();
    }
  }
  B(container2) {
    this.A("peekview-widget");
    this.J = $(".head");
    this.P = $(".body");
    this.T(this.J);
    this.X(this.P);
    container2.appendChild(this.J);
    container2.appendChild(this.P);
  }
  T(container2, noCloseAction) {
    this.K = $(".peekview-title");
    if (this.options.supportOnTitleClick) {
      this.K.classList.add("clickable");
      $aj(this.K, "click", (event) => this.W(event));
    }
    $bk(this.J, this.K);
    this.U(this.K);
    this.L = $("span.filename");
    this.M = $("span.dirname");
    this.N = $("span.meta");
    $bk(this.K, this.L, this.M, this.N);
    const actionsContainer = $(".peekview-actions");
    $bk(this.J, actionsContainer);
    const actionBarOptions = this.V();
    this.O = new $LZ(actionsContainer, actionBarOptions);
    this.n.add(this.O);
    if (!noCloseAction) {
      this.O.push(new $Um("peekview.close", localize(1361, null), ThemeIcon.asClassName($6l.close), true, () => {
        this.dispose();
        return Promise.resolve();
      }), { label: false, icon: true });
    }
  }
  U(container2) {
  }
  V() {
    return {
      actionViewItemProvider: $X$.bind(void 0, this.Q),
      orientation: 0
      /* ActionsOrientation.HORIZONTAL */
    };
  }
  W(event) {
  }
  setTitle(primaryHeading, secondaryHeading) {
    if (this.L && this.M) {
      this.L.innerText = primaryHeading;
      this.L.setAttribute("title", primaryHeading);
      if (secondaryHeading) {
        this.M.innerText = secondaryHeading;
      } else {
        $$i(this.M);
      }
    }
  }
  setMetaTitle(value) {
    if (this.N) {
      if (value) {
        this.N.innerText = value;
        $hk(this.N);
      } else {
        $ik(this.N);
      }
    }
  }
  D(heightInPixel, widthInPixel) {
    if (!this.w && heightInPixel < 0) {
      this.dispose();
      return;
    }
    const headHeight = Math.ceil(this.editor.getOption(
      68
      /* EditorOption.lineHeight */
    ) * 1.2);
    const bodyHeight = Math.round(heightInPixel - (headHeight + 2));
    this.Z(headHeight, widthInPixel);
    this.ab(bodyHeight, widthInPixel);
  }
  Z(heightInPixel, widthInPixel) {
    if (this.J) {
      this.J.style.height = `${heightInPixel}px`;
      this.J.style.lineHeight = this.J.style.height;
    }
  }
  ab(heightInPixel, widthInPixel) {
    if (this.P) {
      this.P.style.height = `${heightInPixel}px`;
    }
  }
};
$ceb = __decorate([
  __param(2, $Pk)
], $ceb);
var $deb = $5n("peekViewTitle.background", { dark: "#252526", light: "#F3F3F3", hcDark: $Vn.black, hcLight: $Vn.white }, localize(1362, null));
var $eeb = $5n("peekViewTitleLabel.foreground", { dark: $Vn.white, light: $Vn.black, hcDark: $Vn.white, hcLight: $Lo }, localize(1363, null));
var $feb = $5n("peekViewTitleDescription.foreground", { dark: "#ccccccb3", light: "#616161", hcDark: "#FFFFFF99", hcLight: "#292929" }, localize(1364, null));
var $geb = $5n("peekView.border", { dark: $2o, light: $2o, hcDark: $ko, hcLight: $ko }, localize(1365, null));
var $heb = $5n("peekViewResult.background", { dark: "#252526", light: "#F3F3F3", hcDark: $Vn.black, hcLight: $Vn.white }, localize(1366, null));
var $ieb = $5n("peekViewResult.lineForeground", { dark: "#bbbbbb", light: "#646465", hcDark: $Vn.white, hcLight: $Lo }, localize(1367, null));
var $jeb = $5n("peekViewResult.fileForeground", { dark: $Vn.white, light: "#1E1E1E", hcDark: $Vn.white, hcLight: $Lo }, localize(1368, null));
var $keb = $5n("peekViewResult.selectionBackground", { dark: "#3399ff33", light: "#3399ff33", hcDark: null, hcLight: null }, localize(1369, null));
var $leb = $5n("peekViewResult.selectionForeground", { dark: $Vn.white, light: "#6C6C6C", hcDark: $Vn.white, hcLight: $Lo }, localize(1370, null));
var $meb = $5n("peekViewEditor.background", { dark: "#001F33", light: "#F2F8FC", hcDark: $Vn.black, hcLight: $Vn.white }, localize(1371, null));
var $neb = $5n("peekViewEditorGutter.background", $meb, localize(1372, null));
var $oeb = $5n("peekViewEditorStickyScroll.background", $meb, localize(1373, null));
var $peb = $5n("peekViewResult.matchHighlightBackground", { dark: "#ea5c004d", light: "#ea5c004d", hcDark: null, hcLight: null }, localize(1374, null));
var $qeb = $5n("peekViewEditor.matchHighlightBackground", { dark: "#ff8f0099", light: "#f5d802de", hcDark: null, hcLight: null }, localize(1375, null));
var $reb = $5n("peekViewEditor.matchHighlightBorder", { dark: null, light: null, hcDark: $lo, hcLight: $lo }, localize(1376, null));

// out-build/vs/base/browser/ui/list/listPaging.js
var PagedRenderer = class {
  get templateId() {
    return this.a.templateId;
  }
  constructor(a, b) {
    this.a = a;
    this.b = b;
  }
  renderTemplate(container2) {
    const data = this.a.renderTemplate(container2);
    return { data, disposable: $3c.None };
  }
  renderElement(index, _, data, height) {
    data.disposable?.dispose();
    if (!data.data) {
      return;
    }
    const model = this.b();
    if (model.isResolved(index)) {
      return this.a.renderElement(model.get(index), index, data.data, height);
    }
    const cts = new $ad();
    const promise = model.resolve(index, cts.token);
    data.disposable = { dispose: () => cts.cancel() };
    this.a.renderPlaceholder(index, data.data);
    promise.then((entry) => this.a.renderElement(entry, index, data.data, height));
  }
  disposeTemplate(data) {
    if (data.disposable) {
      data.disposable.dispose();
      data.disposable = void 0;
    }
    if (data.data) {
      this.a.disposeTemplate(data.data);
      data.data = void 0;
    }
  }
};
var PagedAccessibilityProvider = class {
  constructor(a, b) {
    this.a = a;
    this.b = b;
  }
  getWidgetAriaLabel() {
    return this.b.getWidgetAriaLabel();
  }
  getAriaLabel(index) {
    const model = this.a();
    if (!model.isResolved(index)) {
      return null;
    }
    return this.b.getAriaLabel(model.get(index));
  }
};
function fromPagedListOptions(modelProvider, options3) {
  return {
    ...options3,
    accessibilityProvider: options3.accessibilityProvider && new PagedAccessibilityProvider(modelProvider, options3.accessibilityProvider)
  };
}
var $422 = class {
  constructor(user, container2, virtualDelegate, renderers, options3 = {}) {
    const modelProvider = () => this.model;
    const pagedRenderers = renderers.map((r2) => new PagedRenderer(r2, modelProvider));
    this.a = new $A1(user, container2, virtualDelegate, pagedRenderers, fromPagedListOptions(modelProvider, options3));
  }
  updateOptions(options3) {
    this.a.updateOptions(options3);
  }
  getHTMLElement() {
    return this.a.getHTMLElement();
  }
  isDOMFocused() {
    return $Mj(this.getHTMLElement());
  }
  domFocus() {
    this.a.domFocus();
  }
  get onDidFocus() {
    return this.a.onDidFocus;
  }
  get onDidBlur() {
    return this.a.onDidBlur;
  }
  get widget() {
    return this.a;
  }
  get onDidDispose() {
    return this.a.onDidDispose;
  }
  get onMouseClick() {
    return Event2.map(this.a.onMouseClick, ({ element, index, browserEvent }) => ({ element: element === void 0 ? void 0 : this.b.get(element), index, browserEvent }));
  }
  get onMouseDblClick() {
    return Event2.map(this.a.onMouseDblClick, ({ element, index, browserEvent }) => ({ element: element === void 0 ? void 0 : this.b.get(element), index, browserEvent }));
  }
  get onTap() {
    return Event2.map(this.a.onTap, ({ element, index, browserEvent }) => ({ element: element === void 0 ? void 0 : this.b.get(element), index, browserEvent }));
  }
  get onPointer() {
    return Event2.map(this.a.onPointer, ({ element, index, browserEvent }) => ({ element: element === void 0 ? void 0 : this.b.get(element), index, browserEvent }));
  }
  get onDidChangeFocus() {
    return Event2.map(this.a.onDidChangeFocus, ({ elements, indexes, browserEvent }) => ({ elements: elements.map((e) => this.b.get(e)), indexes, browserEvent }));
  }
  get onDidChangeSelection() {
    return Event2.map(this.a.onDidChangeSelection, ({ elements, indexes, browserEvent }) => ({ elements: elements.map((e) => this.b.get(e)), indexes, browserEvent }));
  }
  get onContextMenu() {
    return Event2.map(this.a.onContextMenu, ({ element, index, anchor, browserEvent }) => typeof element === "undefined" ? { element, index, anchor, browserEvent } : { element: this.b.get(element), index, anchor, browserEvent });
  }
  get model() {
    return this.b;
  }
  set model(model) {
    this.b = model;
    this.a.splice(0, this.a.length, $Ub(model.length));
  }
  get length() {
    return this.a.length;
  }
  get scrollTop() {
    return this.a.scrollTop;
  }
  set scrollTop(scrollTop) {
    this.a.scrollTop = scrollTop;
  }
  get scrollLeft() {
    return this.a.scrollLeft;
  }
  set scrollLeft(scrollLeft) {
    this.a.scrollLeft = scrollLeft;
  }
  setAnchor(index) {
    this.a.setAnchor(index);
  }
  getAnchor() {
    return this.a.getAnchor();
  }
  setFocus(indexes) {
    this.a.setFocus(indexes);
  }
  focusNext(n, loop) {
    this.a.focusNext(n, loop);
  }
  focusPrevious(n, loop) {
    this.a.focusPrevious(n, loop);
  }
  focusNextPage() {
    return this.a.focusNextPage();
  }
  focusPreviousPage() {
    return this.a.focusPreviousPage();
  }
  focusLast() {
    this.a.focusLast();
  }
  focusFirst() {
    this.a.focusFirst();
  }
  getFocus() {
    return this.a.getFocus();
  }
  setSelection(indexes, browserEvent) {
    this.a.setSelection(indexes, browserEvent);
  }
  getSelection() {
    return this.a.getSelection();
  }
  getSelectedElements() {
    return this.getSelection().map((i2) => this.model.get(i2));
  }
  layout(height, width2) {
    this.a.layout(height, width2);
  }
  triggerTypeNavigation() {
    this.a.triggerTypeNavigation();
  }
  reveal(index, relativeTop) {
    this.a.reveal(index, relativeTop);
  }
  style(styles) {
    this.a.style(styles);
  }
  dispose() {
    this.a.dispose();
  }
};

// out-build/vs/base/browser/ui/splitview/splitview.js
var defaultStyles = {
  separatorBorder: $Vn.transparent
};
var LayoutPriority;
(function(LayoutPriority2) {
  LayoutPriority2[LayoutPriority2["Normal"] = 0] = "Normal";
  LayoutPriority2[LayoutPriority2["Low"] = 1] = "Low";
  LayoutPriority2[LayoutPriority2["High"] = 2] = "High";
})(LayoutPriority || (LayoutPriority = {}));
var ViewItem = class {
  set size(size) {
    this.a = size;
  }
  get size() {
    return this.a;
  }
  get cachedVisibleSize() {
    return this.b;
  }
  get visible() {
    return typeof this.b === "undefined";
  }
  setVisible(visible, size) {
    if (visible === this.visible) {
      return;
    }
    if (visible) {
      this.size = $4i(this.b, this.viewMinimumSize, this.viewMaximumSize);
      this.b = void 0;
    } else {
      this.b = typeof size === "number" ? size : this.size;
      this.size = 0;
    }
    this.c.classList.toggle("visible", visible);
    try {
      this.view.setVisible?.(visible);
    } catch (e) {
      console.error("Splitview: Failed to set visible view");
      console.error(e);
    }
  }
  get minimumSize() {
    return this.visible ? this.view.minimumSize : 0;
  }
  get viewMinimumSize() {
    return this.view.minimumSize;
  }
  get maximumSize() {
    return this.visible ? this.view.maximumSize : 0;
  }
  get viewMaximumSize() {
    return this.view.maximumSize;
  }
  get priority() {
    return this.view.priority;
  }
  get proportionalLayout() {
    return this.view.proportionalLayout ?? true;
  }
  get snap() {
    return !!this.view.snap;
  }
  set enabled(enabled) {
    this.c.style.pointerEvents = enabled ? "" : "none";
  }
  constructor(c, view, size, d) {
    this.c = c;
    this.view = view;
    this.d = d;
    this.b = void 0;
    if (typeof size === "number") {
      this.a = size;
      this.b = void 0;
      c.classList.add("visible");
    } else {
      this.a = 0;
      this.b = size.cachedVisibleSize;
    }
  }
  layout(offset, layoutContext) {
    this.layoutContainer(offset);
    try {
      this.view.layout(this.size, offset, layoutContext);
    } catch (e) {
      console.error("Splitview: Failed to layout view");
      console.error(e);
    }
  }
  dispose() {
    this.d.dispose();
  }
};
var VerticalViewItem = class extends ViewItem {
  layoutContainer(offset) {
    this.c.style.top = `${offset}px`;
    this.c.style.height = `${this.size}px`;
  }
};
var HorizontalViewItem = class extends ViewItem {
  layoutContainer(offset) {
    this.c.style.left = `${offset}px`;
    this.c.style.width = `${this.size}px`;
  }
};
var State;
(function(State14) {
  State14[State14["Idle"] = 0] = "Idle";
  State14[State14["Busy"] = 1] = "Busy";
})(State || (State = {}));
var Sizing;
(function(Sizing3) {
  Sizing3.Distribute = { type: "distribute" };
  function Split(index) {
    return { type: "split", index };
  }
  Sizing3.Split = Split;
  function Auto(index) {
    return { type: "auto", index };
  }
  Sizing3.Auto = Auto;
  function Invisible(cachedVisibleSize) {
    return { type: "invisible", cachedVisibleSize };
  }
  Sizing3.Invisible = Invisible;
})(Sizing || (Sizing = {}));
var $r2 = class extends $3c {
  /**
   * The sum of all views' sizes.
   */
  get contentSize() {
    return this.j;
  }
  /**
   * The amount of views in this {@link $r2}.
   */
  get length() {
    return this.n.length;
  }
  /**
   * The minimum size of this {@link $r2}.
   */
  get minimumSize() {
    return this.n.reduce((r2, item) => r2 + item.minimumSize, 0);
  }
  /**
   * The maximum size of this {@link $r2}.
   */
  get maximumSize() {
    return this.length === 0 ? Number.POSITIVE_INFINITY : this.n.reduce((r2, item) => r2 + item.maximumSize, 0);
  }
  get orthogonalStartSash() {
    return this.F;
  }
  get orthogonalEndSash() {
    return this.G;
  }
  get startSnappingEnabled() {
    return this.H;
  }
  get endSnappingEnabled() {
    return this.I;
  }
  /**
   * A reference to a sash, perpendicular to all sashes in this {@link $r2},
   * located at the left- or top-most side of the SplitView.
   * Corner sashes will be created automatically at the intersections.
   */
  set orthogonalStartSash(sash) {
    for (const sashItem of this.sashItems) {
      sashItem.sash.orthogonalStartSash = sash;
    }
    this.F = sash;
  }
  /**
   * A reference to a sash, perpendicular to all sashes in this {@link $r2},
   * located at the right- or bottom-most side of the SplitView.
   * Corner sashes will be created automatically at the intersections.
   */
  set orthogonalEndSash(sash) {
    for (const sashItem of this.sashItems) {
      sashItem.sash.orthogonalEndSash = sash;
    }
    this.G = sash;
  }
  /**
   * The internal sashes within this {@link $r2}.
   */
  get sashes() {
    return this.sashItems.map((s) => s.sash);
  }
  /**
   * Enable/disable snapping at the beginning of this {@link $r2}.
   */
  set startSnappingEnabled(startSnappingEnabled) {
    if (this.H === startSnappingEnabled) {
      return;
    }
    this.H = startSnappingEnabled;
    this.X();
  }
  /**
   * Enable/disable snapping at the end of this {@link $r2}.
   */
  set endSnappingEnabled(endSnappingEnabled) {
    if (this.I === endSnappingEnabled) {
      return;
    }
    this.I = endSnappingEnabled;
    this.X();
  }
  /**
   * Create a new {@link $r2} instance.
   */
  constructor(container2, options3 = {}) {
    super();
    this.g = 0;
    this.j = 0;
    this.m = void 0;
    this.n = [];
    this.sashItems = [];
    this.u = State.Idle;
    this.C = this.B(new $ze());
    this.D = this.B(new $ze());
    this.H = true;
    this.I = true;
    this.onDidSashChange = this.C.event;
    this.onDidSashReset = this.D.event;
    this.orientation = options3.orientation ?? 0;
    this.w = options3.inverseAltBehavior ?? false;
    this.y = options3.proportionalLayout ?? true;
    this.z = options3.getSashOrthogonalSize;
    this.el = document.createElement("div");
    this.el.classList.add("monaco-split-view2");
    this.el.classList.add(this.orientation === 0 ? "vertical" : "horizontal");
    container2.appendChild(this.el);
    this.a = $bk(this.el, $(".sash-container"));
    this.b = $(".split-view-container");
    this.c = this.B(new $AD({
      forceIntegerValues: true,
      smoothScrollDuration: 125,
      scheduleAtNextAnimationFrame: (callback) => $jj(getWindow(this.el), callback)
    }));
    this.f = this.B(new $BZ(this.b, {
      vertical: this.orientation === 0 ? options3.scrollbarVisibility ?? 1 : 2,
      horizontal: this.orientation === 1 ? options3.scrollbarVisibility ?? 1 : 2
      /* ScrollbarVisibility.Hidden */
    }, this.c));
    const onDidScrollViewContainer = this.B(new $9Z(this.b, "scroll")).event;
    this.B(onDidScrollViewContainer((_) => {
      const position = this.f.getScrollPosition();
      const scrollLeft = Math.abs(this.b.scrollLeft - position.scrollLeft) <= 1 ? void 0 : this.b.scrollLeft;
      const scrollTop = Math.abs(this.b.scrollTop - position.scrollTop) <= 1 ? void 0 : this.b.scrollTop;
      if (scrollLeft !== void 0 || scrollTop !== void 0) {
        this.f.setScrollPosition({ scrollLeft, scrollTop });
      }
    }));
    this.onDidScroll = this.f.onScroll;
    this.B(this.onDidScroll((e) => {
      if (e.scrollTopChanged) {
        this.b.scrollTop = e.scrollTop;
      }
      if (e.scrollLeftChanged) {
        this.b.scrollLeft = e.scrollLeft;
      }
    }));
    $bk(this.el, this.f.getDomNode());
    this.style(options3.styles || defaultStyles);
    if (options3.descriptor) {
      this.g = options3.descriptor.size;
      options3.descriptor.views.forEach((viewDescriptor3, index) => {
        const sizing = $Gg(viewDescriptor3.visible) || viewDescriptor3.visible ? viewDescriptor3.size : { type: "invisible", cachedVisibleSize: viewDescriptor3.size };
        const view = viewDescriptor3.view;
        this.P(view, sizing, index, true);
      });
      this.j = this.n.reduce((r2, i2) => r2 + i2.size, 0);
      this.J();
    }
  }
  style(styles) {
    if (styles.separatorBorder.isTransparent()) {
      this.el.classList.remove("separator-border");
      this.el.style.removeProperty("--separator-border");
    } else {
      this.el.classList.add("separator-border");
      this.el.style.setProperty("--separator-border", styles.separatorBorder.toString());
    }
  }
  /**
   * Add a {@link IView view} to this {@link $r2}.
   *
   * @param view The view to add.
   * @param size Either a fixed size, or a dynamic {@link Sizing} strategy.
   * @param index The index to insert the view on.
   * @param skipLayout Whether layout should be skipped.
   */
  addView(view, size, index = this.n.length, skipLayout) {
    this.P(view, size, index, skipLayout);
  }
  /**
   * Remove a {@link IView view} from this {@link $r2}.
   *
   * @param index The index where the {@link IView view} is located.
   * @param sizing Whether to distribute other {@link IView view}'s sizes.
   */
  removeView(index, sizing) {
    if (index < 0 || index >= this.n.length) {
      throw new Error("Index out of bounds");
    }
    if (this.u !== State.Idle) {
      throw new Error("Cant modify splitview");
    }
    this.u = State.Busy;
    try {
      if (sizing?.type === "auto") {
        if (this.ab()) {
          sizing = { type: "distribute" };
        } else {
          sizing = { type: "split", index: sizing.index };
        }
      }
      const referenceViewItem = sizing?.type === "split" ? this.n[sizing.index] : void 0;
      const viewItemToRemove = this.n.splice(index, 1)[0];
      if (referenceViewItem) {
        referenceViewItem.size += viewItemToRemove.size;
      }
      if (this.n.length >= 1) {
        const sashIndex = Math.max(index - 1, 0);
        const sashItem = this.sashItems.splice(sashIndex, 1)[0];
        sashItem.disposable.dispose();
      }
      this.Q();
      if (sizing?.type === "distribute") {
        this.distributeViewSizes();
      }
      const result = viewItemToRemove.view;
      viewItemToRemove.dispose();
      return result;
    } finally {
      this.u = State.Idle;
    }
  }
  removeAllViews() {
    if (this.u !== State.Idle) {
      throw new Error("Cant modify splitview");
    }
    this.u = State.Busy;
    try {
      const viewItems = this.n.splice(0, this.n.length);
      for (const viewItem of viewItems) {
        viewItem.dispose();
      }
      const sashItems = this.sashItems.splice(0, this.sashItems.length);
      for (const sashItem of sashItems) {
        sashItem.disposable.dispose();
      }
      this.Q();
      return viewItems.map((i2) => i2.view);
    } finally {
      this.u = State.Idle;
    }
  }
  /**
   * Move a {@link IView view} to a different index.
   *
   * @param from The source index.
   * @param to The target index.
   */
  moveView(from, to) {
    if (this.u !== State.Idle) {
      throw new Error("Cant modify splitview");
    }
    const cachedVisibleSize = this.getViewCachedVisibleSize(from);
    const sizing = typeof cachedVisibleSize === "undefined" ? this.getViewSize(from) : Sizing.Invisible(cachedVisibleSize);
    const view = this.removeView(from);
    this.addView(view, sizing, to);
  }
  /**
   * Swap two {@link IView views}.
   *
   * @param from The source index.
   * @param to The target index.
   */
  swapViews(from, to) {
    if (this.u !== State.Idle) {
      throw new Error("Cant modify splitview");
    }
    if (from > to) {
      return this.swapViews(to, from);
    }
    const fromSize = this.getViewSize(from);
    const toSize2 = this.getViewSize(to);
    const toView = this.removeView(to);
    const fromView = this.removeView(from);
    this.addView(toView, fromSize, from);
    this.addView(fromView, toSize2, to);
  }
  /**
   * Returns whether the {@link IView view} is visible.
   *
   * @param index The {@link IView view} index.
   */
  isViewVisible(index) {
    if (index < 0 || index >= this.n.length) {
      throw new Error("Index out of bounds");
    }
    const viewItem = this.n[index];
    return viewItem.visible;
  }
  /**
   * Set a {@link IView view}'s visibility.
   *
   * @param index The {@link IView view} index.
   * @param visible Whether the {@link IView view} should be visible.
   */
  setViewVisible(index, visible) {
    if (index < 0 || index >= this.n.length) {
      throw new Error("Index out of bounds");
    }
    const viewItem = this.n[index];
    viewItem.setVisible(visible);
    this.S(index);
    this.U();
    this.J();
  }
  /**
   * Returns the {@link IView view}'s size previously to being hidden.
   *
   * @param index The {@link IView view} index.
   */
  getViewCachedVisibleSize(index) {
    if (index < 0 || index >= this.n.length) {
      throw new Error("Index out of bounds");
    }
    const viewItem = this.n[index];
    return viewItem.cachedVisibleSize;
  }
  /**
   * Layout the {@link $r2}.
   *
   * @param size The entire size of the {@link $r2}.
   * @param layoutContext An optional layout context to pass along to {@link IView views}.
   */
  layout(size, layoutContext) {
    const previousSize = Math.max(this.g, this.j);
    this.g = size;
    this.h = layoutContext;
    if (!this.m) {
      const indexes = $Ub(this.n.length);
      const lowPriorityIndexes = indexes.filter(
        (i2) => this.n[i2].priority === 1
        /* LayoutPriority.Low */
      );
      const highPriorityIndexes = indexes.filter(
        (i2) => this.n[i2].priority === 2
        /* LayoutPriority.High */
      );
      this.R(this.n.length - 1, size - previousSize, void 0, lowPriorityIndexes, highPriorityIndexes);
    } else {
      let total = 0;
      for (let i2 = 0; i2 < this.n.length; i2++) {
        const item = this.n[i2];
        const proportion = this.m[i2];
        if (typeof proportion === "number") {
          total += proportion;
        } else {
          size -= item.size;
        }
      }
      for (let i2 = 0; i2 < this.n.length; i2++) {
        const item = this.n[i2];
        const proportion = this.m[i2];
        if (typeof proportion === "number" && total > 0) {
          item.size = $4i(Math.round(proportion * size / total), item.minimumSize, item.maximumSize);
        }
      }
    }
    this.S();
    this.U();
  }
  J() {
    if (this.y && this.j > 0) {
      this.m = this.n.map((v) => v.proportionalLayout && v.visible ? v.size / this.j : void 0);
    }
  }
  L({ sash, start, alt }) {
    for (const item of this.n) {
      item.enabled = false;
    }
    const index = this.sashItems.findIndex((item) => item.sash === sash);
    const disposable = $Zc($_i(this.el.ownerDocument.body, "keydown", (e) => resetSashDragState(this.t.current, e.altKey)), $_i(this.el.ownerDocument.body, "keyup", () => resetSashDragState(this.t.current, false)));
    const resetSashDragState = (start2, alt2) => {
      const sizes = this.n.map((i2) => i2.size);
      let minDelta = Number.NEGATIVE_INFINITY;
      let maxDelta = Number.POSITIVE_INFINITY;
      if (this.w) {
        alt2 = !alt2;
      }
      if (alt2) {
        const isLastSash = index === this.sashItems.length - 1;
        if (isLastSash) {
          const viewItem = this.n[index];
          minDelta = (viewItem.minimumSize - viewItem.size) / 2;
          maxDelta = (viewItem.maximumSize - viewItem.size) / 2;
        } else {
          const viewItem = this.n[index + 1];
          minDelta = (viewItem.size - viewItem.maximumSize) / 2;
          maxDelta = (viewItem.size - viewItem.minimumSize) / 2;
        }
      }
      let snapBefore;
      let snapAfter;
      if (!alt2) {
        const upIndexes = $Ub(index, -1);
        const downIndexes = $Ub(index + 1, this.n.length);
        const minDeltaUp = upIndexes.reduce((r2, i2) => r2 + (this.n[i2].minimumSize - sizes[i2]), 0);
        const maxDeltaUp = upIndexes.reduce((r2, i2) => r2 + (this.n[i2].viewMaximumSize - sizes[i2]), 0);
        const maxDeltaDown = downIndexes.length === 0 ? Number.POSITIVE_INFINITY : downIndexes.reduce((r2, i2) => r2 + (sizes[i2] - this.n[i2].minimumSize), 0);
        const minDeltaDown = downIndexes.length === 0 ? Number.NEGATIVE_INFINITY : downIndexes.reduce((r2, i2) => r2 + (sizes[i2] - this.n[i2].viewMaximumSize), 0);
        const minDelta2 = Math.max(minDeltaUp, minDeltaDown);
        const maxDelta2 = Math.min(maxDeltaDown, maxDeltaUp);
        const snapBeforeIndex = this.Z(upIndexes);
        const snapAfterIndex = this.Z(downIndexes);
        if (typeof snapBeforeIndex === "number") {
          const viewItem = this.n[snapBeforeIndex];
          const halfSize = Math.floor(viewItem.viewMinimumSize / 2);
          snapBefore = {
            index: snapBeforeIndex,
            limitDelta: viewItem.visible ? minDelta2 - halfSize : minDelta2 + halfSize,
            size: viewItem.size
          };
        }
        if (typeof snapAfterIndex === "number") {
          const viewItem = this.n[snapAfterIndex];
          const halfSize = Math.floor(viewItem.viewMinimumSize / 2);
          snapAfter = {
            index: snapAfterIndex,
            limitDelta: viewItem.visible ? maxDelta2 + halfSize : maxDelta2 - halfSize,
            size: viewItem.size
          };
        }
      }
      this.t = { start: start2, current: start2, index, sizes, minDelta, maxDelta, alt: alt2, snapBefore, snapAfter, disposable };
    };
    resetSashDragState(start, alt);
  }
  M({ current }) {
    const { index, start, sizes, alt, minDelta, maxDelta, snapBefore, snapAfter } = this.t;
    this.t.current = current;
    const delta = current - start;
    const newDelta = this.R(index, delta, sizes, void 0, void 0, minDelta, maxDelta, snapBefore, snapAfter);
    if (alt) {
      const isLastSash = index === this.sashItems.length - 1;
      const newSizes = this.n.map((i2) => i2.size);
      const viewItemIndex = isLastSash ? index : index + 1;
      const viewItem = this.n[viewItemIndex];
      const newMinDelta = viewItem.size - viewItem.maximumSize;
      const newMaxDelta = viewItem.size - viewItem.minimumSize;
      const resizeIndex = isLastSash ? index - 1 : index + 1;
      this.R(resizeIndex, -newDelta, newSizes, void 0, void 0, newMinDelta, newMaxDelta);
    }
    this.S();
    this.U();
  }
  N(index) {
    this.C.fire(index);
    this.t.disposable.dispose();
    this.J();
    for (const item of this.n) {
      item.enabled = true;
    }
  }
  O(item, size) {
    const index = this.n.indexOf(item);
    if (index < 0 || index >= this.n.length) {
      return;
    }
    size = typeof size === "number" ? size : item.size;
    size = $4i(size, item.minimumSize, item.maximumSize);
    if (this.w && index > 0) {
      this.R(index - 1, Math.floor((item.size - size) / 2));
      this.S();
      this.U();
    } else {
      item.size = size;
      this.Q([index], void 0);
    }
  }
  /**
   * Resize a {@link IView view} within the {@link $r2}.
   *
   * @param index The {@link IView view} index.
   * @param size The {@link IView view} size.
   */
  resizeView(index, size) {
    if (index < 0 || index >= this.n.length) {
      return;
    }
    if (this.u !== State.Idle) {
      throw new Error("Cant modify splitview");
    }
    this.u = State.Busy;
    try {
      const indexes = $Ub(this.n.length).filter((i2) => i2 !== index);
      const lowPriorityIndexes = [...indexes.filter(
        (i2) => this.n[i2].priority === 1
        /* LayoutPriority.Low */
      ), index];
      const highPriorityIndexes = indexes.filter(
        (i2) => this.n[i2].priority === 2
        /* LayoutPriority.High */
      );
      const item = this.n[index];
      size = Math.round(size);
      size = $4i(size, item.minimumSize, Math.min(item.maximumSize, this.g));
      item.size = size;
      this.Q(lowPriorityIndexes, highPriorityIndexes);
    } finally {
      this.u = State.Idle;
    }
  }
  /**
   * Returns whether all other {@link IView views} are at their minimum size.
   */
  isViewExpanded(index) {
    if (index < 0 || index >= this.n.length) {
      return false;
    }
    for (const item of this.n) {
      if (item !== this.n[index] && item.size > item.minimumSize) {
        return false;
      }
    }
    return true;
  }
  /**
   * Distribute the entire {@link $r2} size among all {@link IView views}.
   */
  distributeViewSizes() {
    const flexibleViewItems = [];
    let flexibleSize = 0;
    for (const item of this.n) {
      if (item.maximumSize - item.minimumSize > 0) {
        flexibleViewItems.push(item);
        flexibleSize += item.size;
      }
    }
    const size = Math.floor(flexibleSize / flexibleViewItems.length);
    for (const item of flexibleViewItems) {
      item.size = $4i(size, item.minimumSize, item.maximumSize);
    }
    const indexes = $Ub(this.n.length);
    const lowPriorityIndexes = indexes.filter(
      (i2) => this.n[i2].priority === 1
      /* LayoutPriority.Low */
    );
    const highPriorityIndexes = indexes.filter(
      (i2) => this.n[i2].priority === 2
      /* LayoutPriority.High */
    );
    this.Q(lowPriorityIndexes, highPriorityIndexes);
  }
  /**
   * Returns the size of a {@link IView view}.
   */
  getViewSize(index) {
    if (index < 0 || index >= this.n.length) {
      return -1;
    }
    return this.n[index].size;
  }
  P(view, size, index = this.n.length, skipLayout) {
    if (this.u !== State.Idle) {
      throw new Error("Cant modify splitview");
    }
    this.u = State.Busy;
    try {
      const container2 = $(".split-view-view");
      if (index === this.n.length) {
        this.b.appendChild(container2);
      } else {
        this.b.insertBefore(container2, this.b.children.item(index));
      }
      const onChangeDisposable = view.onDidChange((size2) => this.O(item, size2));
      const containerDisposable = $1c(() => container2.remove());
      const disposable = $Zc(onChangeDisposable, containerDisposable);
      let viewSize;
      if (typeof size === "number") {
        viewSize = size;
      } else {
        if (size.type === "auto") {
          if (this.ab()) {
            size = { type: "distribute" };
          } else {
            size = { type: "split", index: size.index };
          }
        }
        if (size.type === "split") {
          viewSize = this.getViewSize(size.index) / 2;
        } else if (size.type === "invisible") {
          viewSize = { cachedVisibleSize: size.cachedVisibleSize };
        } else {
          viewSize = view.minimumSize;
        }
      }
      const item = this.orientation === 0 ? new VerticalViewItem(container2, view, viewSize, disposable) : new HorizontalViewItem(container2, view, viewSize, disposable);
      this.n.splice(index, 0, item);
      if (this.n.length > 1) {
        const opts = { orthogonalStartSash: this.orthogonalStartSash, orthogonalEndSash: this.orthogonalEndSash };
        const sash = this.orientation === 0 ? new $q2(this.a, { getHorizontalSashTop: (s) => this.Y(s), getHorizontalSashWidth: this.z }, {
          ...opts,
          orientation: 1
          /* Orientation.HORIZONTAL */
        }) : new $q2(this.a, { getVerticalSashLeft: (s) => this.Y(s), getVerticalSashHeight: this.z }, {
          ...opts,
          orientation: 0
          /* Orientation.VERTICAL */
        });
        const sashEventMapper = this.orientation === 0 ? (e) => ({ sash, start: e.startY, current: e.currentY, alt: e.altKey }) : (e) => ({ sash, start: e.startX, current: e.currentX, alt: e.altKey });
        const onStart = Event2.map(sash.onDidStart, sashEventMapper);
        const onStartDisposable = onStart(this.L, this);
        const onChange = Event2.map(sash.onDidChange, sashEventMapper);
        const onChangeDisposable2 = onChange(this.M, this);
        const onEnd = Event2.map(sash.onDidEnd, () => this.sashItems.findIndex((item2) => item2.sash === sash));
        const onEndDisposable = onEnd(this.N, this);
        const onDidResetDisposable = sash.onDidReset(() => {
          const index2 = this.sashItems.findIndex((item2) => item2.sash === sash);
          const upIndexes = $Ub(index2, -1);
          const downIndexes = $Ub(index2 + 1, this.n.length);
          const snapBeforeIndex = this.Z(upIndexes);
          const snapAfterIndex = this.Z(downIndexes);
          if (typeof snapBeforeIndex === "number" && !this.n[snapBeforeIndex].visible) {
            return;
          }
          if (typeof snapAfterIndex === "number" && !this.n[snapAfterIndex].visible) {
            return;
          }
          this.D.fire(index2);
        });
        const disposable2 = $Zc(onStartDisposable, onChangeDisposable2, onEndDisposable, onDidResetDisposable, sash);
        const sashItem = { sash, disposable: disposable2 };
        this.sashItems.splice(index - 1, 0, sashItem);
      }
      container2.appendChild(view.element);
      let highPriorityIndexes;
      if (typeof size !== "number" && size.type === "split") {
        highPriorityIndexes = [size.index];
      }
      if (!skipLayout) {
        this.Q([index], highPriorityIndexes);
      }
      if (!skipLayout && typeof size !== "number" && size.type === "distribute") {
        this.distributeViewSizes();
      }
    } finally {
      this.u = State.Idle;
    }
  }
  Q(lowPriorityIndexes, highPriorityIndexes) {
    const contentSize = this.n.reduce((r2, i2) => r2 + i2.size, 0);
    this.R(this.n.length - 1, this.g - contentSize, void 0, lowPriorityIndexes, highPriorityIndexes);
    this.S();
    this.U();
    this.J();
  }
  R(index, delta, sizes = this.n.map((i2) => i2.size), lowPriorityIndexes, highPriorityIndexes, overloadMinDelta = Number.NEGATIVE_INFINITY, overloadMaxDelta = Number.POSITIVE_INFINITY, snapBefore, snapAfter) {
    if (index < 0 || index >= this.n.length) {
      return 0;
    }
    const upIndexes = $Ub(index, -1);
    const downIndexes = $Ub(index + 1, this.n.length);
    if (highPriorityIndexes) {
      for (const index2 of highPriorityIndexes) {
        $1b(upIndexes, index2);
        $1b(downIndexes, index2);
      }
    }
    if (lowPriorityIndexes) {
      for (const index2 of lowPriorityIndexes) {
        $2b(upIndexes, index2);
        $2b(downIndexes, index2);
      }
    }
    const upItems = upIndexes.map((i2) => this.n[i2]);
    const upSizes = upIndexes.map((i2) => sizes[i2]);
    const downItems = downIndexes.map((i2) => this.n[i2]);
    const downSizes = downIndexes.map((i2) => sizes[i2]);
    const minDeltaUp = upIndexes.reduce((r2, i2) => r2 + (this.n[i2].minimumSize - sizes[i2]), 0);
    const maxDeltaUp = upIndexes.reduce((r2, i2) => r2 + (this.n[i2].maximumSize - sizes[i2]), 0);
    const maxDeltaDown = downIndexes.length === 0 ? Number.POSITIVE_INFINITY : downIndexes.reduce((r2, i2) => r2 + (sizes[i2] - this.n[i2].minimumSize), 0);
    const minDeltaDown = downIndexes.length === 0 ? Number.NEGATIVE_INFINITY : downIndexes.reduce((r2, i2) => r2 + (sizes[i2] - this.n[i2].maximumSize), 0);
    const minDelta = Math.max(minDeltaUp, minDeltaDown, overloadMinDelta);
    const maxDelta = Math.min(maxDeltaDown, maxDeltaUp, overloadMaxDelta);
    let snapped = false;
    if (snapBefore) {
      const snapView = this.n[snapBefore.index];
      const visible = delta >= snapBefore.limitDelta;
      snapped = visible !== snapView.visible;
      snapView.setVisible(visible, snapBefore.size);
    }
    if (!snapped && snapAfter) {
      const snapView = this.n[snapAfter.index];
      const visible = delta < snapAfter.limitDelta;
      snapped = visible !== snapView.visible;
      snapView.setVisible(visible, snapAfter.size);
    }
    if (snapped) {
      return this.R(index, delta, sizes, lowPriorityIndexes, highPriorityIndexes, overloadMinDelta, overloadMaxDelta);
    }
    delta = $4i(delta, minDelta, maxDelta);
    for (let i2 = 0, deltaUp = delta; i2 < upItems.length; i2++) {
      const item = upItems[i2];
      const size = $4i(upSizes[i2] + deltaUp, item.minimumSize, item.maximumSize);
      const viewDelta = size - upSizes[i2];
      deltaUp -= viewDelta;
      item.size = size;
    }
    for (let i2 = 0, deltaDown = delta; i2 < downItems.length; i2++) {
      const item = downItems[i2];
      const size = $4i(downSizes[i2] - deltaDown, item.minimumSize, item.maximumSize);
      const viewDelta = size - downSizes[i2];
      deltaDown += viewDelta;
      item.size = size;
    }
    return delta;
  }
  S(lowPriorityIndex) {
    const contentSize = this.n.reduce((r2, i2) => r2 + i2.size, 0);
    let emptyDelta = this.g - contentSize;
    const indexes = $Ub(this.n.length - 1, -1);
    const lowPriorityIndexes = indexes.filter(
      (i2) => this.n[i2].priority === 1
      /* LayoutPriority.Low */
    );
    const highPriorityIndexes = indexes.filter(
      (i2) => this.n[i2].priority === 2
      /* LayoutPriority.High */
    );
    for (const index of highPriorityIndexes) {
      $1b(indexes, index);
    }
    for (const index of lowPriorityIndexes) {
      $2b(indexes, index);
    }
    if (typeof lowPriorityIndex === "number") {
      $2b(indexes, lowPriorityIndex);
    }
    for (let i2 = 0; emptyDelta !== 0 && i2 < indexes.length; i2++) {
      const item = this.n[indexes[i2]];
      const size = $4i(item.size + emptyDelta, item.minimumSize, item.maximumSize);
      const viewDelta = size - item.size;
      emptyDelta -= viewDelta;
      item.size = size;
    }
  }
  U() {
    this.j = this.n.reduce((r2, i2) => r2 + i2.size, 0);
    let offset = 0;
    for (const viewItem of this.n) {
      viewItem.layout(offset, this.h);
      offset += viewItem.size;
    }
    this.sashItems.forEach((item) => item.sash.layout());
    this.X();
    this.W();
  }
  W() {
    if (this.orientation === 0) {
      this.f.setScrollDimensions({
        height: this.g,
        scrollHeight: this.j
      });
    } else {
      this.f.setScrollDimensions({
        width: this.g,
        scrollWidth: this.j
      });
    }
  }
  X() {
    let previous = false;
    const collapsesDown = this.n.map((i2) => previous = i2.size - i2.minimumSize > 0 || previous);
    previous = false;
    const expandsDown = this.n.map((i2) => previous = i2.maximumSize - i2.size > 0 || previous);
    const reverseViews = [...this.n].reverse();
    previous = false;
    const collapsesUp = reverseViews.map((i2) => previous = i2.size - i2.minimumSize > 0 || previous).reverse();
    previous = false;
    const expandsUp = reverseViews.map((i2) => previous = i2.maximumSize - i2.size > 0 || previous).reverse();
    let position = 0;
    for (let index = 0; index < this.sashItems.length; index++) {
      const { sash } = this.sashItems[index];
      const viewItem = this.n[index];
      position += viewItem.size;
      const min = !(collapsesDown[index] && expandsUp[index + 1]);
      const max = !(expandsDown[index] && collapsesUp[index + 1]);
      if (min && max) {
        const upIndexes = $Ub(index, -1);
        const downIndexes = $Ub(index + 1, this.n.length);
        const snapBeforeIndex = this.Z(upIndexes);
        const snapAfterIndex = this.Z(downIndexes);
        const snappedBefore = typeof snapBeforeIndex === "number" && !this.n[snapBeforeIndex].visible;
        const snappedAfter = typeof snapAfterIndex === "number" && !this.n[snapAfterIndex].visible;
        if (snappedBefore && collapsesUp[index] && (position > 0 || this.startSnappingEnabled)) {
          sash.state = 1;
        } else if (snappedAfter && collapsesDown[index] && (position < this.j || this.endSnappingEnabled)) {
          sash.state = 2;
        } else {
          sash.state = 0;
        }
      } else if (min && !max) {
        sash.state = 1;
      } else if (!min && max) {
        sash.state = 2;
      } else {
        sash.state = 3;
      }
    }
  }
  Y(sash) {
    let position = 0;
    for (let i2 = 0; i2 < this.sashItems.length; i2++) {
      position += this.n[i2].size;
      if (this.sashItems[i2].sash === sash) {
        return position;
      }
    }
    return 0;
  }
  Z(indexes) {
    for (const index of indexes) {
      const viewItem = this.n[index];
      if (!viewItem.visible) {
        continue;
      }
      if (viewItem.snap) {
        return index;
      }
    }
    for (const index of indexes) {
      const viewItem = this.n[index];
      if (viewItem.visible && viewItem.maximumSize - viewItem.minimumSize > 0) {
        return void 0;
      }
      if (!viewItem.visible && viewItem.snap) {
        return index;
      }
    }
    return void 0;
  }
  ab() {
    let min = void 0, max = void 0;
    for (const view of this.n) {
      min = min === void 0 ? view.size : Math.min(min, view.size);
      max = max === void 0 ? view.size : Math.max(max, view.size);
      if (max - min > 2) {
        return false;
      }
    }
    return true;
  }
  dispose() {
    this.t?.disposable.dispose();
    $Xc(this.n);
    this.n = [];
    this.sashItems.forEach((i2) => i2.disposable.dispose());
    this.sashItems = [];
    super.dispose();
  }
};

// out-build/vs/base/browser/ui/table/tableWidget.js
var TableListRenderer = class _TableListRenderer {
  static {
    this.TemplateId = "row";
  }
  constructor(f, renderers, g) {
    this.f = f;
    this.g = g;
    this.templateId = _TableListRenderer.TemplateId;
    this.e = /* @__PURE__ */ new Set();
    const rendererMap = new Map(renderers.map((r2) => [r2.templateId, r2]));
    this.d = [];
    for (const column of f) {
      const renderer = rendererMap.get(column.templateId);
      if (!renderer) {
        throw new Error(`Table cell renderer for template id ${column.templateId} not found.`);
      }
      this.d.push(renderer);
    }
  }
  renderTemplate(container2) {
    const rowContainer = $bk(container2, $(".monaco-table-tr"));
    const cellContainers = [];
    const cellTemplateData = [];
    for (let i2 = 0; i2 < this.f.length; i2++) {
      const renderer = this.d[i2];
      const cellContainer = $bk(rowContainer, $(".monaco-table-td", { "data-col-index": i2 }));
      cellContainer.style.width = `${this.g(i2)}px`;
      cellContainers.push(cellContainer);
      cellTemplateData.push(renderer.renderTemplate(cellContainer));
    }
    const result = { container: container2, cellContainers, cellTemplateData };
    this.e.add(result);
    return result;
  }
  renderElement(element, index, templateData, height) {
    for (let i2 = 0; i2 < this.f.length; i2++) {
      const column = this.f[i2];
      const cell = column.project(element);
      const renderer = this.d[i2];
      renderer.renderElement(cell, index, templateData.cellTemplateData[i2], height);
    }
  }
  disposeElement(element, index, templateData, height) {
    for (let i2 = 0; i2 < this.f.length; i2++) {
      const renderer = this.d[i2];
      if (renderer.disposeElement) {
        const column = this.f[i2];
        const cell = column.project(element);
        renderer.disposeElement(cell, index, templateData.cellTemplateData[i2], height);
      }
    }
  }
  disposeTemplate(templateData) {
    for (let i2 = 0; i2 < this.f.length; i2++) {
      const renderer = this.d[i2];
      renderer.disposeTemplate(templateData.cellTemplateData[i2]);
    }
    $$i(templateData.container);
    this.e.delete(templateData);
  }
  layoutColumn(index, size) {
    for (const { cellContainers } of this.e) {
      cellContainers[index].style.width = `${size}px`;
    }
  }
};
function asListVirtualDelegate(delegate) {
  return {
    getHeight(row) {
      return delegate.getHeight(row);
    },
    getTemplateId() {
      return TableListRenderer.TemplateId;
    }
  };
}
var ColumnHeader = class extends $3c {
  get minimumSize() {
    return this.column.minimumWidth ?? 120;
  }
  get maximumSize() {
    return this.column.maximumWidth ?? Number.POSITIVE_INFINITY;
  }
  get onDidChange() {
    return this.column.onDidChangeWidthConstraints ?? Event2.None;
  }
  constructor(column, g) {
    super();
    this.column = column;
    this.g = g;
    this.f = new $ze();
    this.onDidLayout = this.f.event;
    this.element = $(".monaco-table-th", { "data-col-index": g }, column.label);
    if (column.tooltip) {
      this.B($J1().setupManagedHover($JZ("mouse"), this.element, column.tooltip));
    }
  }
  layout(size) {
    this.f.fire([this.g, size]);
  }
};
var $e3 = class _$e3 {
  static {
    this.d = 0;
  }
  get onDidChangeFocus() {
    return this.g.onDidChangeFocus;
  }
  get onDidChangeSelection() {
    return this.g.onDidChangeSelection;
  }
  get onDidScroll() {
    return this.g.onDidScroll;
  }
  get onMouseClick() {
    return this.g.onMouseClick;
  }
  get onMouseDblClick() {
    return this.g.onMouseDblClick;
  }
  get onMouseMiddleClick() {
    return this.g.onMouseMiddleClick;
  }
  get onPointer() {
    return this.g.onPointer;
  }
  get onMouseUp() {
    return this.g.onMouseUp;
  }
  get onMouseDown() {
    return this.g.onMouseDown;
  }
  get onMouseOver() {
    return this.g.onMouseOver;
  }
  get onMouseMove() {
    return this.g.onMouseMove;
  }
  get onMouseOut() {
    return this.g.onMouseOut;
  }
  get onTouchStart() {
    return this.g.onTouchStart;
  }
  get onTap() {
    return this.g.onTap;
  }
  get onContextMenu() {
    return this.g.onContextMenu;
  }
  get onDidFocus() {
    return this.g.onDidFocus;
  }
  get onDidBlur() {
    return this.g.onDidBlur;
  }
  get scrollTop() {
    return this.g.scrollTop;
  }
  set scrollTop(scrollTop) {
    this.g.scrollTop = scrollTop;
  }
  get scrollLeft() {
    return this.g.scrollLeft;
  }
  set scrollLeft(scrollLeft) {
    this.g.scrollLeft = scrollLeft;
  }
  get scrollHeight() {
    return this.g.scrollHeight;
  }
  get renderHeight() {
    return this.g.renderHeight;
  }
  get onDidDispose() {
    return this.g.onDidDispose;
  }
  constructor(user, container2, p, q, renderers, _options) {
    this.p = p;
    this.q = q;
    this.domId = `table_id_${++_$e3.d}`;
    this.k = new $2c();
    this.m = 0;
    this.o = 0;
    this.domNode = $bk(container2, $(`.monaco-table.${this.domId}`));
    const headers = q.map((c, i2) => this.k.add(new ColumnHeader(c, i2)));
    const descriptor = {
      size: headers.reduce((a, b) => a + b.column.weight, 0),
      views: headers.map((view) => ({ size: view.column.weight, view }))
    };
    this.f = this.k.add(new $r2(this.domNode, {
      orientation: 1,
      scrollbarVisibility: 2,
      getSashOrthogonalSize: () => this.o,
      descriptor
    }));
    this.f.el.style.height = `${p.headerRowHeight}px`;
    this.f.el.style.lineHeight = `${p.headerRowHeight}px`;
    const renderer = new TableListRenderer(q, renderers, (i2) => this.f.getViewSize(i2));
    this.g = this.k.add(new $A1(user, this.domNode, asListVirtualDelegate(p), [renderer], _options));
    Event2.any(...headers.map((h3) => h3.onDidLayout))(([index, size]) => renderer.layoutColumn(index, size), null, this.k);
    this.f.onDidSashReset((index) => {
      const totalWeight = q.reduce((r2, c) => r2 + c.weight, 0);
      const size = q[index].weight / totalWeight * this.m;
      this.f.resizeView(index, size);
    }, null, this.k);
    this.j = $VZ(this.domNode);
    this.style($z1);
  }
  getColumnLabels() {
    return this.q.map((c) => c.label);
  }
  resizeColumn(index, percentage) {
    const size = Math.round(percentage / 100 * this.m);
    this.f.resizeView(index, size);
  }
  updateOptions(options3) {
    this.g.updateOptions(options3);
  }
  splice(start, deleteCount, elements = []) {
    this.g.splice(start, deleteCount, elements);
  }
  rerender() {
    this.g.rerender();
  }
  row(index) {
    return this.g.element(index);
  }
  indexOf(element) {
    return this.g.indexOf(element);
  }
  get length() {
    return this.g.length;
  }
  getHTMLElement() {
    return this.domNode;
  }
  layout(height, width2) {
    height = height ?? $Aj(this.domNode);
    width2 = width2 ?? $yj(this.domNode);
    this.m = width2;
    this.o = height;
    this.f.layout(width2);
    const listHeight = height - this.p.headerRowHeight;
    this.g.getHTMLElement().style.height = `${listHeight}px`;
    this.g.layout(listHeight, width2);
  }
  triggerTypeNavigation() {
    this.g.triggerTypeNavigation();
  }
  style(styles) {
    const content = [];
    content.push(`.monaco-table.${this.domId} > .monaco-split-view2 .monaco-sash.vertical::before {
			top: ${this.p.headerRowHeight + 1}px;
			height: calc(100% - ${this.p.headerRowHeight}px);
		}`);
    this.j.textContent = content.join("\n");
    this.g.style(styles);
  }
  domFocus() {
    this.g.domFocus();
  }
  setAnchor(index) {
    this.g.setAnchor(index);
  }
  getAnchor() {
    return this.g.getAnchor();
  }
  getSelectedElements() {
    return this.g.getSelectedElements();
  }
  setSelection(indexes, browserEvent) {
    this.g.setSelection(indexes, browserEvent);
  }
  getSelection() {
    return this.g.getSelection();
  }
  setFocus(indexes, browserEvent) {
    this.g.setFocus(indexes, browserEvent);
  }
  focusNext(n = 1, loop = false, browserEvent) {
    this.g.focusNext(n, loop, browserEvent);
  }
  focusPrevious(n = 1, loop = false, browserEvent) {
    this.g.focusPrevious(n, loop, browserEvent);
  }
  focusNextPage(browserEvent) {
    return this.g.focusNextPage(browserEvent);
  }
  focusPreviousPage(browserEvent) {
    return this.g.focusPreviousPage(browserEvent);
  }
  focusFirst(browserEvent) {
    this.g.focusFirst(browserEvent);
  }
  focusLast(browserEvent) {
    this.g.focusLast(browserEvent);
  }
  getFocus() {
    return this.g.getFocus();
  }
  getFocusedElements() {
    return this.g.getFocusedElements();
  }
  getRelativeTop(index) {
    return this.g.getRelativeTop(index);
  }
  reveal(index, relativeTop) {
    this.g.reveal(index, relativeTop);
  }
  dispose() {
    this.k.dispose();
  }
};

// out-build/vs/base/browser/ui/toggle/toggle.js
var $O1 = {
  inputActiveOptionBorder: "#007ACC00",
  inputActiveOptionForeground: "#FFFFFF",
  inputActiveOptionBackground: "#0E639C50"
};
var $P1 = class extends $T1 {
  constructor(context, action, options3) {
    super(context, action, options3);
    this.a = this.B(new $Q1({
      actionClassName: this._action.class,
      isChecked: !!this._action.checked,
      title: this.u.keybinding ? `${this._action.label} (${this.u.keybinding})` : this._action.label,
      notFocusable: true,
      inputActiveOptionBackground: options3.toggleStyles?.inputActiveOptionBackground,
      inputActiveOptionBorder: options3.toggleStyles?.inputActiveOptionBorder,
      inputActiveOptionForeground: options3.toggleStyles?.inputActiveOptionForeground,
      hoverDelegate: options3.hoverDelegate
    }));
    this.B(this.a.onChange(() => this._action.checked = !!this.a && this.a.checked));
  }
  render(container2) {
    this.element = container2;
    this.element.appendChild(this.a.domNode);
  }
  z() {
    if (this.a) {
      if (this.isEnabled()) {
        this.a.enable();
      } else {
        this.a.disable();
      }
    }
  }
  J() {
    this.a.checked = !!this._action.checked;
  }
  focus() {
    this.a.domNode.tabIndex = 0;
    this.a.focus();
  }
  blur() {
    this.a.domNode.tabIndex = -1;
    this.a.domNode.blur();
  }
  setFocusable(focusable) {
    this.a.domNode.tabIndex = focusable ? 0 : -1;
  }
};
var $Q1 = class extends $qZ {
  constructor(opts) {
    super();
    this.a = this.B(new $ze());
    this.onChange = this.a.event;
    this.c = this.B(new $ze());
    this.onKeyDown = this.c.event;
    this.g = opts;
    this.w = this.g.isChecked;
    const classes2 = ["monaco-custom-toggle"];
    if (this.g.icon) {
      this.t = this.g.icon;
      classes2.push(...ThemeIcon.asClassNameArray(this.t));
    }
    if (this.g.actionClassName) {
      classes2.push(...this.g.actionClassName.split(" "));
    }
    if (this.w) {
      classes2.push("checked");
    }
    this.domNode = document.createElement("div");
    this.y = this.B($J1().setupManagedHover(opts.hoverDelegate ?? $JZ("mouse"), this.domNode, this.g.title));
    this.domNode.classList.add(...classes2);
    if (!this.g.notFocusable) {
      this.domNode.tabIndex = 0;
    }
    this.domNode.setAttribute("role", "checkbox");
    this.domNode.setAttribute("aria-checked", String(this.w));
    this.domNode.setAttribute("aria-label", this.g.title);
    this.H();
    this.b(this.domNode, (ev) => {
      if (this.enabled) {
        this.checked = !this.w;
        this.a.fire(false);
        ev.preventDefault();
      }
    });
    this.B(this.G(this.domNode));
    this.s(this.domNode, (keyboardEvent) => {
      if (keyboardEvent.keyCode === 10 || keyboardEvent.keyCode === 3) {
        this.checked = !this.w;
        this.a.fire(true);
        keyboardEvent.preventDefault();
        keyboardEvent.stopPropagation();
        return;
      }
      this.c.fire(keyboardEvent);
    });
  }
  get enabled() {
    return this.domNode.getAttribute("aria-disabled") !== "true";
  }
  focus() {
    this.domNode.focus();
  }
  get checked() {
    return this.w;
  }
  set checked(newIsChecked) {
    this.w = newIsChecked;
    this.domNode.setAttribute("aria-checked", String(this.w));
    this.domNode.classList.toggle("checked", this.w);
    this.H();
  }
  setIcon(icon2) {
    if (this.t) {
      this.domNode.classList.remove(...ThemeIcon.asClassNameArray(this.t));
    }
    this.t = icon2;
    if (this.t) {
      this.domNode.classList.add(...ThemeIcon.asClassNameArray(this.t));
    }
  }
  width() {
    return 2 + 2 + 2 + 16;
  }
  H() {
    if (this.domNode) {
      this.domNode.style.borderColor = this.w && this.g.inputActiveOptionBorder || "";
      this.domNode.style.color = this.w && this.g.inputActiveOptionForeground || "inherit";
      this.domNode.style.backgroundColor = this.w && this.g.inputActiveOptionBackground || "";
    }
  }
  enable() {
    this.domNode.setAttribute("aria-disabled", String(false));
  }
  disable() {
    this.domNode.setAttribute("aria-disabled", String(true));
  }
  setTitle(newTitle) {
    this.y.update(newTitle);
    this.domNode.setAttribute("aria-label", newTitle);
  }
  set visible(visible) {
    this.domNode.style.display = visible ? "" : "none";
  }
  get visible() {
    return this.domNode.style.display !== "none";
  }
};
var $R1 = class _$R1 extends $qZ {
  static {
    this.CLASS_NAME = "monaco-checkbox";
  }
  constructor(h3, n, styles) {
    super();
    this.h = h3;
    this.n = n;
    this.a = this.B(new $ze());
    this.onChange = this.a.event;
    this.c = this.B(new $Q1({ title: this.h, isChecked: this.n, icon: $6l.check, actionClassName: _$R1.CLASS_NAME, ...$O1 }));
    this.domNode = this.c.domNode;
    this.g = styles;
    this.r();
    this.B(this.c.onChange((keyboard) => {
      this.r();
      this.a.fire(keyboard);
    }));
  }
  get checked() {
    return this.c.checked;
  }
  get enabled() {
    return this.c.enabled;
  }
  set checked(newIsChecked) {
    this.c.checked = newIsChecked;
    this.r();
  }
  focus() {
    this.domNode.focus();
  }
  hasFocus() {
    return $Mj(this.domNode);
  }
  enable() {
    this.c.enable();
  }
  disable() {
    this.c.disable();
  }
  r() {
    this.domNode.style.color = this.g.checkboxForeground || "";
    this.domNode.style.backgroundColor = this.g.checkboxBackground || "";
    this.domNode.style.borderColor = this.g.checkboxBorder || "";
  }
};
var $S1 = class extends $T1 {
  constructor(context, action, options3) {
    super(context, action, options3);
    this.a = this.B(new $R1(this._action.label, !!this._action.checked, options3.checkboxStyles));
    this.B(this.a.onChange(() => this.c()));
  }
  render(container2) {
    this.element = container2;
    this.element.classList.add("checkbox-action-item");
    this.element.appendChild(this.a.domNode);
    if (this.u.label && this._action.label) {
      const label3 = this.element.appendChild($("span.checkbox-label", void 0, this._action.label));
      this.B($_i(label3, $7j.CLICK, (e) => {
        this.a.checked = !this.a.checked;
        e.stopPropagation();
        e.preventDefault();
        this.c();
      }));
    }
    this.z();
    this.I();
    this.J();
  }
  c() {
    this._action.checked = !!this.a && this.a.checked;
    this.actionRunner.run(this._action, this._context);
  }
  z() {
    if (this.isEnabled()) {
      this.a.enable();
    } else {
      this.a.disable();
    }
    if (this.action.enabled) {
      this.element?.classList.remove("disabled");
    } else {
      this.element?.classList.add("disabled");
    }
  }
  J() {
    this.a.checked = !!this._action.checked;
  }
  I() {
    if (this.b) {
      this.a.domNode.classList.remove(...this.b.split(" "));
    }
    this.b = this.D();
    if (this.b) {
      this.a.domNode.classList.add(...this.b.split(" "));
    }
  }
  focus() {
    this.a.domNode.tabIndex = 0;
    this.a.focus();
  }
  blur() {
    this.a.domNode.tabIndex = -1;
    this.a.domNode.blur();
  }
  setFocusable(focusable) {
    this.a.domNode.tabIndex = focusable ? 0 : -1;
  }
};

// out-build/vs/base/browser/ui/findinput/findInputToggles.js
var NLS_CASE_SENSITIVE_TOGGLE_LABEL = localize(10, null);
var NLS_WHOLE_WORD_TOGGLE_LABEL = localize(11, null);
var NLS_REGEX_TOGGLE_LABEL = localize(12, null);
var $N2 = class extends $Q1 {
  constructor(opts) {
    super({
      icon: $6l.caseSensitive,
      title: NLS_CASE_SENSITIVE_TOGGLE_LABEL + opts.appendTitle,
      isChecked: opts.isChecked,
      hoverDelegate: opts.hoverDelegate ?? $JZ("element"),
      inputActiveOptionBorder: opts.inputActiveOptionBorder,
      inputActiveOptionForeground: opts.inputActiveOptionForeground,
      inputActiveOptionBackground: opts.inputActiveOptionBackground
    });
  }
};
var $O2 = class extends $Q1 {
  constructor(opts) {
    super({
      icon: $6l.wholeWord,
      title: NLS_WHOLE_WORD_TOGGLE_LABEL + opts.appendTitle,
      isChecked: opts.isChecked,
      hoverDelegate: opts.hoverDelegate ?? $JZ("element"),
      inputActiveOptionBorder: opts.inputActiveOptionBorder,
      inputActiveOptionForeground: opts.inputActiveOptionForeground,
      inputActiveOptionBackground: opts.inputActiveOptionBackground
    });
  }
};
var $P2 = class extends $Q1 {
  constructor(opts) {
    super({
      icon: $6l.regex,
      title: NLS_REGEX_TOGGLE_LABEL + opts.appendTitle,
      isChecked: opts.isChecked,
      hoverDelegate: opts.hoverDelegate ?? $JZ("element"),
      inputActiveOptionBorder: opts.inputActiveOptionBorder,
      inputActiveOptionForeground: opts.inputActiveOptionForeground,
      inputActiveOptionBackground: opts.inputActiveOptionBackground
    });
  }
};

// out-build/vs/base/common/navigator.js
var $E2 = class {
  constructor(a, b = 0, c = a.length, d = b - 1) {
    this.a = a;
    this.b = b;
    this.c = c;
    this.d = d;
  }
  current() {
    if (this.d === this.b - 1 || this.d === this.c) {
      return null;
    }
    return this.a[this.d];
  }
  next() {
    this.d = Math.min(this.d + 1, this.c);
    return this.current();
  }
  previous() {
    this.d = Math.max(this.d - 1, this.b - 1);
    return this.current();
  }
  first() {
    this.d = this.b;
    return this.current();
  }
  last() {
    this.d = this.c - 1;
    return this.current();
  }
};

// out-build/vs/base/common/history.js
var $F2 = class {
  constructor(c = /* @__PURE__ */ new Set(), limit = 10) {
    this.c = c;
    this.a = limit;
    this.d();
    if (this.c.onDidChange) {
      this.c.onDidChange(() => this.d());
    }
  }
  getHistory() {
    return this.h;
  }
  add(t) {
    this.c.delete(t);
    this.c.add(t);
    this.d();
  }
  next() {
    return this.b.next();
  }
  previous() {
    if (this.g() !== 0) {
      return this.b.previous();
    }
    return null;
  }
  current() {
    return this.b.current();
  }
  first() {
    return this.b.first();
  }
  last() {
    return this.b.last();
  }
  isFirst() {
    return this.g() === 0;
  }
  isLast() {
    return this.g() >= this.h.length - 1;
  }
  isNowhere() {
    return this.b.current() === null;
  }
  has(t) {
    return this.c.has(t);
  }
  clear() {
    this.c.clear();
    this.d();
  }
  d() {
    this.f();
    const elements = this.h;
    this.b = new $E2(elements, 0, elements.length, elements.length);
  }
  f() {
    const data = this.h;
    if (data.length > this.a) {
      const replaceValue = data.slice(data.length - this.a);
      if (this.c.replace) {
        this.c.replace(replaceValue);
      } else {
        this.c = new Set(replaceValue);
      }
    }
  }
  g() {
    const currentElement = this.b.current();
    if (!currentElement) {
      return -1;
    }
    return this.h.indexOf(currentElement);
  }
  get h() {
    const elements = [];
    this.c.forEach((e) => elements.push(e));
    return elements;
  }
};
var $G2 = class {
  get size() {
    return this.f;
  }
  constructor(history, g = 10, h3 = (t) => t) {
    this.g = g;
    this.h = h3;
    if (history.length < 1) {
      throw new Error("not supported");
    }
    this.f = 1;
    this.b = this.c = this.d = {
      value: history[0],
      previous: void 0,
      next: void 0
    };
    this.a = new $e([history[0]], h3);
    for (let i2 = 1; i2 < history.length; i2++) {
      this.add(history[i2]);
    }
  }
  add(value) {
    const node = {
      value,
      previous: this.c,
      next: void 0
    };
    this.c.next = node;
    this.c = node;
    this.d = this.c;
    this.f++;
    if (this.a.has(value)) {
      this.j(value);
    } else {
      this.a.add(value);
    }
    while (this.f > this.g) {
      this.a.delete(this.b.value);
      this.b = this.b.next;
      this.b.previous = void 0;
      this.f--;
    }
  }
  /**
   * @returns old last value
   */
  replaceLast(value) {
    if (this.h(this.c.value) === this.h(value)) {
      return value;
    }
    const oldValue = this.c.value;
    this.a.delete(oldValue);
    this.c.value = value;
    if (this.a.has(value)) {
      this.j(value);
    } else {
      this.a.add(value);
    }
    return oldValue;
  }
  prepend(value) {
    if (this.f === this.g || this.a.has(value)) {
      return;
    }
    const node = {
      value,
      previous: void 0,
      next: this.b
    };
    this.b.previous = node;
    this.b = node;
    this.f++;
    this.a.add(value);
  }
  isAtEnd() {
    return this.d === this.c;
  }
  current() {
    return this.d.value;
  }
  previous() {
    if (this.d.previous) {
      this.d = this.d.previous;
    }
    return this.d.value;
  }
  next() {
    if (this.d.next) {
      this.d = this.d.next;
    }
    return this.d.value;
  }
  has(t) {
    return this.a.has(t);
  }
  resetCursor() {
    this.d = this.c;
    return this.d.value;
  }
  *[Symbol.iterator]() {
    let node = this.b;
    while (node) {
      yield node.value;
      node = node.next;
    }
  }
  j(value) {
    let temp = this.b;
    const valueKey = this.h(value);
    while (temp !== this.c) {
      if (this.h(temp.value) === valueKey) {
        if (temp === this.b) {
          this.b = this.b.next;
          this.b.previous = void 0;
        } else {
          temp.previous.next = temp.next;
          temp.next.previous = temp.previous;
        }
        this.f--;
      }
      temp = temp.next;
    }
  }
};

// out-build/vs/base/browser/ui/inputbox/inputBox.js
var $52 = $;
var MessageType;
(function(MessageType5) {
  MessageType5[MessageType5["INFO"] = 1] = "INFO";
  MessageType5[MessageType5["WARNING"] = 2] = "WARNING";
  MessageType5[MessageType5["ERROR"] = 3] = "ERROR";
})(MessageType || (MessageType = {}));
var $H2 = {
  inputBackground: "#3C3C3C",
  inputForeground: "#CCCCCC",
  inputValidationInfoBorder: "#55AAFF",
  inputValidationInfoBackground: "#063B49",
  inputValidationWarningBorder: "#B89500",
  inputValidationWarningBackground: "#352A05",
  inputValidationErrorBorder: "#BE1100",
  inputValidationErrorBackground: "#5A1D1D",
  inputBorder: void 0,
  inputValidationErrorForeground: void 0,
  inputValidationInfoForeground: void 0,
  inputValidationWarningForeground: void 0
};
var $I2 = class extends $qZ {
  constructor(container2, contextViewProvider, options3) {
    super();
    this.H = "idle";
    this.M = Number.POSITIVE_INFINITY;
    this.O = this.B(new $4c());
    this.P = this.B(new $ze());
    this.onDidChange = this.P.event;
    this.Q = this.B(new $ze());
    this.onDidHeightChange = this.Q.event;
    this.a = contextViewProvider;
    this.h = options3;
    this.n = null;
    this.r = this.h.placeholder || "";
    this.t = this.h.tooltip ?? (this.r || "");
    this.w = this.h.ariaLabel || "";
    if (this.h.validationOptions) {
      this.y = this.h.validationOptions.validation;
    }
    this.element = $bk(container2, $52(".monaco-inputbox.idle"));
    const tagName = this.h.flexibleHeight ? "textarea" : "input";
    const wrapper = $bk(this.element, $52(".ibwrapper"));
    this.c = $bk(wrapper, $52(tagName + ".input.empty"));
    this.c.setAttribute("autocorrect", "off");
    this.c.setAttribute("autocapitalize", "off");
    this.c.setAttribute("spellcheck", "false");
    this.D(this.c, () => this.element.classList.add("synthetic-focus"));
    this.C(this.c, () => this.element.classList.remove("synthetic-focus"));
    if (this.h.flexibleHeight) {
      this.M = typeof this.h.flexibleMaxHeight === "number" ? this.h.flexibleMaxHeight : Number.POSITIVE_INFINITY;
      this.I = $bk(wrapper, $52("div.mirror"));
      this.I.innerText = "\xA0";
      this.N = new $AZ(this.element, {
        vertical: 1
        /* ScrollbarVisibility.Auto */
      });
      if (this.h.flexibleWidth) {
        this.c.setAttribute("wrap", "off");
        this.I.style.whiteSpace = "pre";
        this.I.style.wordWrap = "initial";
      }
      $bk(container2, this.N.getDomNode());
      this.B(this.N);
      this.B(this.N.onScroll((e) => this.c.scrollTop = e.scrollTop));
      const onSelectionChange = this.B(new $9Z(container2.ownerDocument, "selectionchange"));
      const onAnchoredSelectionChange = Event2.filter(onSelectionChange.event, () => {
        const selection = container2.ownerDocument.getSelection();
        return selection?.anchorNode === wrapper;
      });
      this.B(onAnchoredSelectionChange(this.U, this));
      this.B(this.onDidHeightChange(this.U, this));
    } else {
      this.c.type = this.h.type || "text";
      this.c.setAttribute("wrap", "off");
    }
    if (this.w) {
      this.c.setAttribute("aria-label", this.w);
    }
    if (this.r && !this.h.showPlaceholderOnFocus) {
      this.setPlaceHolder(this.r);
    }
    if (this.t) {
      this.setTooltip(this.t);
    }
    this.z(this.c, () => this.Z());
    this.C(this.c, () => this.R());
    this.D(this.c, () => this.S());
    this.B(this.G(this.c));
    setTimeout(() => this.ab(), 0);
    if (this.h.actions) {
      this.g = this.B(new $LZ(this.element));
      this.g.push(this.h.actions, { icon: true, label: false });
    }
    this.bb();
  }
  R() {
    this.Y();
    if (this.h.showPlaceholderOnFocus) {
      this.c.setAttribute("placeholder", "");
    }
  }
  S() {
    this.X();
    if (this.h.showPlaceholderOnFocus) {
      this.c.setAttribute("placeholder", this.r || "");
    }
  }
  setPlaceHolder(placeHolder) {
    this.r = placeHolder;
    this.c.setAttribute("placeholder", placeHolder);
  }
  setTooltip(tooltip) {
    this.t = tooltip;
    if (!this.O.value) {
      this.O.value = this.B($J1().setupDelayedHoverAtMouse(this.c, () => ({
        content: tooltip,
        appearance: {
          compact: true
        }
      })));
    }
  }
  setAriaLabel(label3) {
    this.w = label3;
    if (label3) {
      this.c.setAttribute("aria-label", this.w);
    } else {
      this.c.removeAttribute("aria-label");
    }
  }
  getAriaLabel() {
    return this.w;
  }
  get mirrorElement() {
    return this.I;
  }
  get inputElement() {
    return this.c;
  }
  get value() {
    return this.c.value;
  }
  set value(newValue) {
    if (this.c.value !== newValue) {
      this.c.value = newValue;
      this.Z();
    }
  }
  get step() {
    return this.c.step;
  }
  set step(newValue) {
    this.c.step = newValue;
  }
  get height() {
    return typeof this.J === "number" ? this.J : $Bj(this.element);
  }
  focus() {
    this.c.focus();
  }
  blur() {
    this.c.blur();
  }
  hasFocus() {
    return $Mj(this.c);
  }
  select(range = null) {
    this.c.select();
    if (range) {
      this.c.setSelectionRange(range.start, range.end);
      if (range.end === this.c.value.length) {
        this.c.scrollLeft = this.c.scrollWidth;
      }
    }
  }
  isSelectionAtEnd() {
    return this.c.selectionEnd === this.c.value.length && this.c.selectionStart === this.c.selectionEnd;
  }
  getSelection() {
    const selectionStart = this.c.selectionStart;
    if (selectionStart === null) {
      return null;
    }
    const selectionEnd = this.c.selectionEnd ?? selectionStart;
    return {
      start: selectionStart,
      end: selectionEnd
    };
  }
  enable() {
    this.c.removeAttribute("disabled");
  }
  disable() {
    this.blur();
    this.c.disabled = true;
    this.Y();
  }
  setEnabled(enabled) {
    if (enabled) {
      this.enable();
    } else {
      this.disable();
    }
  }
  get width() {
    return $xj(this.c);
  }
  set width(width2) {
    if (this.h.flexibleHeight && this.h.flexibleWidth) {
      let horizontalPadding = 0;
      if (this.I) {
        const paddingLeft = parseFloat(this.I.style.paddingLeft || "") || 0;
        const paddingRight = parseFloat(this.I.style.paddingRight || "") || 0;
        horizontalPadding = paddingLeft + paddingRight;
      }
      this.c.style.width = width2 - horizontalPadding + "px";
    } else {
      this.c.style.width = width2 + "px";
    }
    if (this.I) {
      this.I.style.width = width2 + "px";
    }
  }
  set paddingRight(paddingRight) {
    this.c.style.width = `calc(100% - ${paddingRight}px)`;
    if (this.I) {
      this.I.style.paddingRight = paddingRight + "px";
    }
  }
  U() {
    if (typeof this.L !== "number" || typeof this.J !== "number" || !this.N) {
      return;
    }
    const scrollHeight = this.L;
    const height = this.J;
    const scrollTop = this.c.scrollTop;
    this.N.setScrollDimensions({ scrollHeight, height });
    this.N.setScrollPosition({ scrollTop });
  }
  showMessage(message, force) {
    if (this.H === "open" && $Pv(this.n, message)) {
      return;
    }
    this.n = message;
    this.element.classList.remove("idle");
    this.element.classList.remove("info");
    this.element.classList.remove("warning");
    this.element.classList.remove("error");
    this.element.classList.add(this.W(message.type));
    const styles = this.stylesForType(this.n.type);
    this.element.style.border = `1px solid ${$ZZ(styles.border, "transparent")}`;
    if (this.n.content && (this.hasFocus() || force)) {
      this.X();
    }
  }
  hideMessage() {
    this.n = null;
    this.element.classList.remove("info");
    this.element.classList.remove("warning");
    this.element.classList.remove("error");
    this.element.classList.add("idle");
    this.Y();
    this.bb();
  }
  isInputValid() {
    return !!this.y && !this.y(this.value);
  }
  validate() {
    let errorMsg = null;
    if (this.y) {
      errorMsg = this.y(this.value);
      if (errorMsg) {
        this.inputElement.setAttribute("aria-invalid", "true");
        this.showMessage(errorMsg);
      } else if (this.inputElement.hasAttribute("aria-invalid")) {
        this.inputElement.removeAttribute("aria-invalid");
        this.hideMessage();
      }
    }
    return errorMsg?.type;
  }
  stylesForType(type) {
    const styles = this.h.inputBoxStyles;
    switch (type) {
      case 1:
        return { border: styles.inputValidationInfoBorder, background: styles.inputValidationInfoBackground, foreground: styles.inputValidationInfoForeground };
      case 2:
        return { border: styles.inputValidationWarningBorder, background: styles.inputValidationWarningBackground, foreground: styles.inputValidationWarningForeground };
      default:
        return { border: styles.inputValidationErrorBorder, background: styles.inputValidationErrorBackground, foreground: styles.inputValidationErrorForeground };
    }
  }
  W(type) {
    switch (type) {
      case 1:
        return "info";
      case 2:
        return "warning";
      default:
        return "error";
    }
  }
  X() {
    if (!this.a || !this.n) {
      return;
    }
    let div;
    const layout = () => div.style.width = $xj(this.element) + "px";
    this.a.showContextView({
      getAnchor: () => this.element,
      anchorAlignment: 1,
      render: (container2) => {
        if (!this.n) {
          return null;
        }
        div = $bk(container2, $52(".monaco-inputbox-container"));
        layout();
        const renderOptions = {
          inline: true,
          className: "monaco-inputbox-message"
        };
        const spanElement = this.n.formatContent ? $RZ(this.n.content, renderOptions) : $QZ(this.n.content, renderOptions);
        spanElement.classList.add(this.W(this.n.type));
        const styles = this.stylesForType(this.n.type);
        spanElement.style.backgroundColor = styles.background ?? "";
        spanElement.style.color = styles.foreground ?? "";
        spanElement.style.border = styles.border ? `1px solid ${styles.border}` : "";
        $bk(div, spanElement);
        return null;
      },
      onHide: () => {
        this.H = "closed";
      },
      layout
    });
    let alertText;
    if (this.n.type === 3) {
      alertText = localize(19, null, this.n.content);
    } else if (this.n.type === 2) {
      alertText = localize(20, null, this.n.content);
    } else {
      alertText = localize(21, null, this.n.content);
    }
    $$Z(alertText);
    this.H = "open";
  }
  Y() {
    if (!this.a) {
      return;
    }
    if (this.H === "open") {
      this.a.hideContextView();
    }
    this.H = "idle";
  }
  Z() {
    this.P.fire(this.value);
    this.validate();
    this.ab();
    this.c.classList.toggle("empty", !this.value);
    if (this.H === "open" && this.a) {
      this.a.layout();
    }
  }
  ab() {
    if (!this.I) {
      return;
    }
    const value = this.value;
    const lastCharCode = value.charCodeAt(value.length - 1);
    const suffix = lastCharCode === 10 ? " " : "";
    const mirrorTextContent = (value + suffix).replace(/\u000c/g, "");
    if (mirrorTextContent) {
      this.I.textContent = value + suffix;
    } else {
      this.I.innerText = "\xA0";
    }
    this.layout();
  }
  bb() {
    const styles = this.h.inputBoxStyles;
    const background = styles.inputBackground ?? "";
    const foreground = styles.inputForeground ?? "";
    const border = styles.inputBorder ?? "";
    this.element.style.backgroundColor = background;
    this.element.style.color = foreground;
    this.c.style.backgroundColor = "inherit";
    this.c.style.color = foreground;
    this.element.style.border = `1px solid ${$ZZ(border, "transparent")}`;
  }
  layout() {
    if (!this.I) {
      return;
    }
    const previousHeight = this.L;
    this.L = $Bj(this.I);
    if (previousHeight !== this.L) {
      this.J = Math.min(this.L, this.M);
      this.c.style.height = this.J + "px";
      this.Q.fire(this.L);
    }
  }
  insertAtCursor(text2) {
    const inputElement = this.inputElement;
    const start = inputElement.selectionStart;
    const end = inputElement.selectionEnd;
    const content = inputElement.value;
    if (start !== null && end !== null) {
      this.value = content.substr(0, start) + text2 + content.substr(end);
      inputElement.setSelectionRange(start + 1, start + 1);
      this.layout();
    }
  }
  dispose() {
    this.Y();
    this.n = null;
    this.g?.dispose();
    super.dispose();
  }
};
var $J2 = class extends $I2 {
  constructor(container2, contextViewProvider, options3) {
    const NLS_PLACEHOLDER_HISTORY_HINT_SUFFIX_NO_PARENS = localize(22, null, `\u21C5`);
    const NLS_PLACEHOLDER_HISTORY_HINT_SUFFIX_IN_PARENS = localize(23, null, `\u21C5`);
    super(container2, contextViewProvider, options3);
    this.eb = this.B(new $ze());
    this.onDidFocus = this.eb.event;
    this.fb = this.B(new $ze());
    this.onDidBlur = this.fb.event;
    this.cb = new $F2(options3.history, 100);
    const addSuffix = () => {
      if (options3.showHistoryHint && options3.showHistoryHint() && !this.r.endsWith(NLS_PLACEHOLDER_HISTORY_HINT_SUFFIX_NO_PARENS) && !this.r.endsWith(NLS_PLACEHOLDER_HISTORY_HINT_SUFFIX_IN_PARENS) && this.cb.getHistory().length) {
        const suffix = this.r.endsWith(")") ? NLS_PLACEHOLDER_HISTORY_HINT_SUFFIX_NO_PARENS : NLS_PLACEHOLDER_HISTORY_HINT_SUFFIX_IN_PARENS;
        const suffixedPlaceholder = this.r + suffix;
        if (options3.showPlaceholderOnFocus && !$Mj(this.c)) {
          this.r = suffixedPlaceholder;
        } else {
          this.setPlaceHolder(suffixedPlaceholder);
        }
      }
    };
    this.db = new MutationObserver((mutationList, observer) => {
      mutationList.forEach((mutation) => {
        if (!mutation.target.textContent) {
          addSuffix();
        }
      });
    });
    this.db.observe(this.c, { attributeFilter: ["class"] });
    this.D(this.c, () => addSuffix());
    this.C(this.c, () => {
      const resetPlaceholder = (historyHint) => {
        if (!this.r.endsWith(historyHint)) {
          return false;
        } else {
          const revertedPlaceholder = this.r.slice(0, this.r.length - historyHint.length);
          if (options3.showPlaceholderOnFocus) {
            this.r = revertedPlaceholder;
          } else {
            this.setPlaceHolder(revertedPlaceholder);
          }
          return true;
        }
      };
      if (!resetPlaceholder(NLS_PLACEHOLDER_HISTORY_HINT_SUFFIX_IN_PARENS)) {
        resetPlaceholder(NLS_PLACEHOLDER_HISTORY_HINT_SUFFIX_NO_PARENS);
      }
    });
  }
  dispose() {
    super.dispose();
    if (this.db) {
      this.db.disconnect();
      this.db = void 0;
    }
  }
  addToHistory(always) {
    if (this.value && (always || this.value !== this.ib())) {
      this.cb.add(this.value);
    }
  }
  prependHistory(restoredHistory) {
    const newHistory = this.getHistory();
    this.clearHistory();
    restoredHistory.forEach((item) => {
      this.cb.add(item);
    });
    newHistory.forEach((item) => {
      this.cb.add(item);
    });
  }
  getHistory() {
    return this.cb.getHistory();
  }
  isAtFirstInHistory() {
    return this.cb.isFirst();
  }
  isAtLastInHistory() {
    return this.cb.isLast();
  }
  isNowhereInHistory() {
    return this.cb.isNowhere();
  }
  showNextValue() {
    if (!this.cb.has(this.value)) {
      this.addToHistory();
    }
    let next = this.kb();
    if (next) {
      next = next === this.value ? this.kb() : next;
    }
    this.value = next ?? "";
    $_Z(this.value ? this.value : localize(24, null));
  }
  showPreviousValue() {
    if (!this.cb.has(this.value)) {
      this.addToHistory();
    }
    let previous = this.jb();
    if (previous) {
      previous = previous === this.value ? this.jb() : previous;
    }
    if (previous) {
      this.value = previous;
      $_Z(this.value);
    }
  }
  clearHistory() {
    this.cb.clear();
  }
  setPlaceHolder(placeHolder) {
    super.setPlaceHolder(placeHolder);
    this.setTooltip(placeHolder);
  }
  R() {
    super.R();
    this.fb.fire();
  }
  S() {
    super.S();
    this.eb.fire();
  }
  ib() {
    let currentValue = this.cb.current();
    if (!currentValue) {
      currentValue = this.cb.last();
      this.cb.next();
    }
    return currentValue;
  }
  jb() {
    return this.cb.previous() || this.cb.first();
  }
  kb() {
    return this.cb.next();
  }
};

// out-build/vs/base/browser/ui/findinput/findInput.js
var NLS_DEFAULT_LABEL = localize(9, null);
var $Q2 = class extends $qZ {
  static {
    this.OPTION_CHANGE = "optionChange";
  }
  constructor(parent, contextViewProvider, options3) {
    super();
    this.w = true;
    this.y = false;
    this.H = this.B(new $4c());
    this.N = [];
    this.O = this.B(new $ze());
    this.onDidOptionChange = this.O.event;
    this.P = this.B(new $ze());
    this.onKeyDown = this.P.event;
    this.Q = this.B(new $ze());
    this.onMouseDown = this.Q.event;
    this.R = this.B(new $ze());
    this.onInput = this.R.event;
    this.S = this.B(new $ze());
    this.onKeyUp = this.S.event;
    this.U = this.B(new $ze());
    this.onCaseSensitiveKeyDown = this.U.event;
    this.W = this.B(new $ze());
    this.onRegexKeyDown = this.W.event;
    this.Y = 0;
    this.a = options3.placeholder || "";
    this.c = options3.validation;
    this.h = options3.label || NLS_DEFAULT_LABEL;
    this.n = !!options3.showCommonFindToggles;
    const appendCaseSensitiveLabel = options3.appendCaseSensitiveLabel || "";
    const appendWholeWordsLabel = options3.appendWholeWordsLabel || "";
    const appendRegexLabel = options3.appendRegexLabel || "";
    const flexibleHeight = !!options3.flexibleHeight;
    const flexibleWidth = !!options3.flexibleWidth;
    const flexibleMaxHeight = options3.flexibleMaxHeight;
    this.domNode = document.createElement("div");
    this.domNode.classList.add("monaco-findInput");
    this.inputBox = this.B(new $J2(this.domNode, contextViewProvider, {
      placeholder: this.a || "",
      ariaLabel: this.h || "",
      validationOptions: {
        validation: this.c
      },
      showHistoryHint: options3.showHistoryHint,
      flexibleHeight,
      flexibleWidth,
      flexibleMaxHeight,
      inputBoxStyles: options3.inputBoxStyles,
      history: options3.history
    }));
    const hoverDelegate = this.B($KZ());
    if (this.n) {
      this.J = this.B(new $P2({
        appendTitle: appendRegexLabel,
        isChecked: false,
        hoverDelegate,
        ...options3.toggleStyles
      }));
      this.B(this.J.onChange((viaKeyboard) => {
        this.O.fire(viaKeyboard);
        if (!viaKeyboard && this.w) {
          this.inputBox.focus();
        }
        this.validate();
      }));
      this.B(this.J.onKeyDown((e) => {
        this.W.fire(e);
      }));
      this.L = this.B(new $O2({
        appendTitle: appendWholeWordsLabel,
        isChecked: false,
        hoverDelegate,
        ...options3.toggleStyles
      }));
      this.B(this.L.onChange((viaKeyboard) => {
        this.O.fire(viaKeyboard);
        if (!viaKeyboard && this.w) {
          this.inputBox.focus();
        }
        this.validate();
      }));
      this.M = this.B(new $N2({
        appendTitle: appendCaseSensitiveLabel,
        isChecked: false,
        hoverDelegate,
        ...options3.toggleStyles
      }));
      this.B(this.M.onChange((viaKeyboard) => {
        this.O.fire(viaKeyboard);
        if (!viaKeyboard && this.w) {
          this.inputBox.focus();
        }
        this.validate();
      }));
      this.B(this.M.onKeyDown((e) => {
        this.U.fire(e);
      }));
      const indexes = [this.M.domNode, this.L.domNode, this.J.domNode];
      this.s(this.domNode, (event) => {
        if (event.equals(
          15
          /* KeyCode.LeftArrow */
        ) || event.equals(
          17
          /* KeyCode.RightArrow */
        ) || event.equals(
          9
          /* KeyCode.Escape */
        )) {
          const index = indexes.indexOf(this.domNode.ownerDocument.activeElement);
          if (index >= 0) {
            let newIndex = -1;
            if (event.equals(
              17
              /* KeyCode.RightArrow */
            )) {
              newIndex = (index + 1) % indexes.length;
            } else if (event.equals(
              15
              /* KeyCode.LeftArrow */
            )) {
              if (index === 0) {
                newIndex = indexes.length - 1;
              } else {
                newIndex = index - 1;
              }
            }
            if (event.equals(
              9
              /* KeyCode.Escape */
            )) {
              indexes[index].blur();
              this.inputBox.focus();
            } else if (newIndex >= 0) {
              indexes[newIndex].focus();
            }
            $9j.stop(event, true);
          }
        }
      });
    }
    this.I = document.createElement("div");
    this.I.className = "controls";
    this.I.style.display = this.n ? "" : "none";
    if (this.M) {
      this.I.append(this.M.domNode);
    }
    if (this.L) {
      this.I.appendChild(this.L.domNode);
    }
    if (this.J) {
      this.I.appendChild(this.J.domNode);
    }
    this.setAdditionalToggles(options3?.additionalToggles);
    if (this.I) {
      this.domNode.appendChild(this.I);
    }
    parent?.appendChild(this.domNode);
    this.B($_i(this.inputBox.inputElement, "compositionstart", (e) => {
      this.y = true;
    }));
    this.B($_i(this.inputBox.inputElement, "compositionend", (e) => {
      this.y = false;
      this.R.fire();
    }));
    this.s(this.inputBox.inputElement, (e) => this.P.fire(e));
    this.u(this.inputBox.inputElement, (e) => this.S.fire(e));
    this.z(this.inputBox.inputElement, (e) => this.R.fire());
    this.f(this.inputBox.inputElement, (e) => this.Q.fire(e));
  }
  get isImeSessionInProgress() {
    return this.y;
  }
  get onDidChange() {
    return this.inputBox.onDidChange;
  }
  layout(style) {
    this.inputBox.layout();
    this.X(style.collapsedFindWidget);
  }
  enable() {
    this.domNode.classList.remove("disabled");
    this.inputBox.enable();
    this.J?.enable();
    this.L?.enable();
    this.M?.enable();
    for (const toggle of this.N) {
      toggle.enable();
    }
  }
  disable() {
    this.domNode.classList.add("disabled");
    this.inputBox.disable();
    this.J?.disable();
    this.L?.disable();
    this.M?.disable();
    for (const toggle of this.N) {
      toggle.disable();
    }
  }
  setFocusInputOnOptionClick(value) {
    this.w = value;
  }
  setEnabled(enabled) {
    if (enabled) {
      this.enable();
    } else {
      this.disable();
    }
  }
  setAdditionalToggles(toggles) {
    for (const currentToggle of this.N) {
      currentToggle.domNode.remove();
    }
    this.N = [];
    this.H.value = new $2c();
    for (const toggle of toggles ?? []) {
      this.H.value.add(toggle);
      this.I.appendChild(toggle.domNode);
      this.H.value.add(toggle.onChange((viaKeyboard) => {
        this.O.fire(viaKeyboard);
        if (!viaKeyboard && this.w) {
          this.inputBox.focus();
        }
      }));
      this.N.push(toggle);
    }
    if (this.N.length > 0) {
      this.I.style.display = "";
    }
    this.X();
  }
  X(controlsHidden = false) {
    if (controlsHidden) {
      this.inputBox.paddingRight = 0;
    } else {
      this.inputBox.paddingRight = (this.M?.width() ?? 0) + (this.L?.width() ?? 0) + (this.J?.width() ?? 0) + this.N.reduce((r2, t) => r2 + t.width(), 0);
    }
  }
  clear() {
    this.Z();
    this.setValue("");
    this.focus();
  }
  getValue() {
    return this.inputBox.value;
  }
  setValue(value) {
    if (this.inputBox.value !== value) {
      this.inputBox.value = value;
    }
  }
  onSearchSubmit() {
    this.inputBox.addToHistory();
  }
  select() {
    this.inputBox.select();
  }
  focus() {
    this.inputBox.focus();
  }
  getCaseSensitive() {
    return this.M?.checked ?? false;
  }
  setCaseSensitive(value) {
    if (this.M) {
      this.M.checked = value;
    }
  }
  getWholeWords() {
    return this.L?.checked ?? false;
  }
  setWholeWords(value) {
    if (this.L) {
      this.L.checked = value;
    }
  }
  getRegex() {
    return this.J?.checked ?? false;
  }
  setRegex(value) {
    if (this.J) {
      this.J.checked = value;
      this.validate();
    }
  }
  focusOnCaseSensitive() {
    this.M?.focus();
  }
  focusOnRegex() {
    this.J?.focus();
  }
  highlightFindOptions() {
    this.domNode.classList.remove("highlight-" + this.Y);
    this.Y = 1 - this.Y;
    this.domNode.classList.add("highlight-" + this.Y);
  }
  validate() {
    this.inputBox.validate();
  }
  showMessage(message) {
    this.inputBox.showMessage(message);
  }
  clearMessage() {
    this.inputBox.hideMessage();
  }
  Z() {
    this.inputBox.hideMessage();
  }
};

// out-build/vs/base/browser/ui/tree/tree.js
var TreeVisibility;
(function(TreeVisibility2) {
  TreeVisibility2[TreeVisibility2["Hidden"] = 0] = "Hidden";
  TreeVisibility2[TreeVisibility2["Visible"] = 1] = "Visible";
  TreeVisibility2[TreeVisibility2["Recurse"] = 2] = "Recurse";
})(TreeVisibility || (TreeVisibility = {}));
var ObjectTreeElementCollapseState;
(function(ObjectTreeElementCollapseState2) {
  ObjectTreeElementCollapseState2[ObjectTreeElementCollapseState2["Expanded"] = 0] = "Expanded";
  ObjectTreeElementCollapseState2[ObjectTreeElementCollapseState2["Collapsed"] = 1] = "Collapsed";
  ObjectTreeElementCollapseState2[ObjectTreeElementCollapseState2["PreserveOrExpanded"] = 2] = "PreserveOrExpanded";
  ObjectTreeElementCollapseState2[ObjectTreeElementCollapseState2["PreserveOrCollapsed"] = 3] = "PreserveOrCollapsed";
})(ObjectTreeElementCollapseState || (ObjectTreeElementCollapseState = {}));
var TreeMouseEventTarget;
(function(TreeMouseEventTarget2) {
  TreeMouseEventTarget2[TreeMouseEventTarget2["Unknown"] = 0] = "Unknown";
  TreeMouseEventTarget2[TreeMouseEventTarget2["Twistie"] = 1] = "Twistie";
  TreeMouseEventTarget2[TreeMouseEventTarget2["Element"] = 2] = "Element";
  TreeMouseEventTarget2[TreeMouseEventTarget2["Filter"] = 3] = "Filter";
})(TreeMouseEventTarget || (TreeMouseEventTarget = {}));
var TreeDragOverBubble;
(function(TreeDragOverBubble2) {
  TreeDragOverBubble2[TreeDragOverBubble2["Down"] = 0] = "Down";
  TreeDragOverBubble2[TreeDragOverBubble2["Up"] = 1] = "Up";
})(TreeDragOverBubble || (TreeDragOverBubble = {}));
var $i3 = class extends Error {
  constructor(user, message) {
    super(`TreeError [${user}] ${message}`);
  }
};
var $j3 = class {
  constructor(a) {
    this.a = a;
    this.b = /* @__PURE__ */ new WeakMap();
  }
  map(key2) {
    let result = this.b.get(key2);
    if (!result) {
      result = this.a(key2);
      this.b.set(key2, result);
    }
    return result;
  }
};

// out-build/vs/base/common/diff/diffChange.js
var $4C = class {
  /**
   * Constructs a new DiffChange with the given sequence information
   * and content.
   */
  constructor(originalStart, originalLength, modifiedStart, modifiedLength) {
    this.originalStart = originalStart;
    this.originalLength = originalLength;
    this.modifiedStart = modifiedStart;
    this.modifiedLength = modifiedLength;
  }
  /**
   * The end point (exclusive) of the change in the original sequence.
   */
  getOriginalEnd() {
    return this.originalStart + this.originalLength;
  }
  /**
   * The end point (exclusive) of the change in the modified sequence.
   */
  getModifiedEnd() {
    return this.modifiedStart + this.modifiedLength;
  }
};

// out-build/vs/base/common/diff/diff.js
var $5C = class {
  constructor(a) {
    this.a = a;
  }
  getElements() {
    const source = this.a;
    const characters = new Int32Array(source.length);
    for (let i2 = 0, len = source.length; i2 < len; i2++) {
      characters[i2] = source.charCodeAt(i2);
    }
    return characters;
  }
};
function $6C(original, modified, pretty2) {
  return new $7C(new $5C(original), new $5C(modified)).ComputeDiff(pretty2).changes;
}
var Debug = class {
  static Assert(condition, message) {
    if (!condition) {
      throw new Error(message);
    }
  }
};
var MyArray = class {
  /**
   * Copies a range of elements from an Array starting at the specified source index and pastes
   * them to another Array starting at the specified destination index. The length and the indexes
   * are specified as 64-bit integers.
   * sourceArray:
   *		The Array that contains the data to copy.
   * sourceIndex:
   *		A 64-bit integer that represents the index in the sourceArray at which copying begins.
   * destinationArray:
   *		The Array that receives the data.
   * destinationIndex:
   *		A 64-bit integer that represents the index in the destinationArray at which storing begins.
   * length:
   *		A 64-bit integer that represents the number of elements to copy.
   */
  static Copy(sourceArray, sourceIndex, destinationArray, destinationIndex, length) {
    for (let i2 = 0; i2 < length; i2++) {
      destinationArray[destinationIndex + i2] = sourceArray[sourceIndex + i2];
    }
  }
  static Copy2(sourceArray, sourceIndex, destinationArray, destinationIndex, length) {
    for (let i2 = 0; i2 < length; i2++) {
      destinationArray[destinationIndex + i2] = sourceArray[sourceIndex + i2];
    }
  }
};
var LocalConstants;
(function(LocalConstants2) {
  LocalConstants2[LocalConstants2["MaxDifferencesHistory"] = 1447] = "MaxDifferencesHistory";
})(LocalConstants || (LocalConstants = {}));
var DiffChangeHelper = class {
  /**
   * Constructs a new DiffChangeHelper for the given DiffSequences.
   */
  constructor() {
    this.a = [];
    this.b = 1073741824;
    this.c = 1073741824;
    this.d = 0;
    this.e = 0;
  }
  /**
   * Marks the beginning of the next change in the set of differences.
   */
  MarkNextChange() {
    if (this.d > 0 || this.e > 0) {
      this.a.push(new $4C(this.b, this.d, this.c, this.e));
    }
    this.d = 0;
    this.e = 0;
    this.b = 1073741824;
    this.c = 1073741824;
  }
  /**
   * Adds the original element at the given position to the elements
   * affected by the current change. The modified index gives context
   * to the change position with respect to the original sequence.
   * @param originalIndex The index of the original element to add.
   * @param modifiedIndex The index of the modified element that provides corresponding position in the modified sequence.
   */
  AddOriginalElement(originalIndex, modifiedIndex) {
    this.b = Math.min(this.b, originalIndex);
    this.c = Math.min(this.c, modifiedIndex);
    this.d++;
  }
  /**
   * Adds the modified element at the given position to the elements
   * affected by the current change. The original index gives context
   * to the change position with respect to the modified sequence.
   * @param originalIndex The index of the original element that provides corresponding position in the original sequence.
   * @param modifiedIndex The index of the modified element to add.
   */
  AddModifiedElement(originalIndex, modifiedIndex) {
    this.b = Math.min(this.b, originalIndex);
    this.c = Math.min(this.c, modifiedIndex);
    this.e++;
  }
  /**
   * Retrieves all of the changes marked by the class.
   */
  getChanges() {
    if (this.d > 0 || this.e > 0) {
      this.MarkNextChange();
    }
    return this.a;
  }
  /**
   * Retrieves all of the changes marked by the class in the reverse order
   */
  getReverseChanges() {
    if (this.d > 0 || this.e > 0) {
      this.MarkNextChange();
    }
    this.a.reverse();
    return this.a;
  }
};
var $7C = class _$7C {
  /**
   * Constructs the DiffFinder
   */
  constructor(originalSequence, modifiedSequence, continueProcessingPredicate = null) {
    this.a = continueProcessingPredicate;
    this.b = originalSequence;
    this.c = modifiedSequence;
    const [originalStringElements, originalElementsOrHash, originalHasStrings] = _$7C.o(originalSequence);
    const [modifiedStringElements, modifiedElementsOrHash, modifiedHasStrings] = _$7C.o(modifiedSequence);
    this.d = originalHasStrings && modifiedHasStrings;
    this.e = originalStringElements;
    this.f = originalElementsOrHash;
    this.g = modifiedStringElements;
    this.h = modifiedElementsOrHash;
    this.k = [];
    this.m = [];
  }
  static n(arr) {
    return arr.length > 0 && typeof arr[0] === "string";
  }
  static o(sequence) {
    const elements = sequence.getElements();
    if (_$7C.n(elements)) {
      const hashes = new Int32Array(elements.length);
      for (let i2 = 0, len = elements.length; i2 < len; i2++) {
        hashes[i2] = $1i(elements[i2], 0);
      }
      return [elements, hashes, true];
    }
    if (elements instanceof Int32Array) {
      return [[], elements, false];
    }
    return [[], new Int32Array(elements), false];
  }
  p(originalIndex, newIndex) {
    if (this.f[originalIndex] !== this.h[newIndex]) {
      return false;
    }
    return this.d ? this.e[originalIndex] === this.g[newIndex] : true;
  }
  q(originalIndex, newIndex) {
    if (!this.p(originalIndex, newIndex)) {
      return false;
    }
    const originalElement = _$7C.r(this.b, originalIndex);
    const modifiedElement = _$7C.r(this.c, newIndex);
    return originalElement === modifiedElement;
  }
  static r(sequence, index) {
    if (typeof sequence.getStrictElement === "function") {
      return sequence.getStrictElement(index);
    }
    return null;
  }
  s(index1, index2) {
    if (this.f[index1] !== this.f[index2]) {
      return false;
    }
    return this.d ? this.e[index1] === this.e[index2] : true;
  }
  u(index1, index2) {
    if (this.h[index1] !== this.h[index2]) {
      return false;
    }
    return this.d ? this.g[index1] === this.g[index2] : true;
  }
  ComputeDiff(pretty2) {
    return this.v(0, this.f.length - 1, 0, this.h.length - 1, pretty2);
  }
  /**
   * Computes the differences between the original and modified input
   * sequences on the bounded range.
   * @returns An array of the differences between the two input sequences.
   */
  v(originalStart, originalEnd, modifiedStart, modifiedEnd, pretty2) {
    const quitEarlyArr = [false];
    let changes = this.w(originalStart, originalEnd, modifiedStart, modifiedEnd, quitEarlyArr);
    if (pretty2) {
      changes = this.z(changes);
    }
    return {
      quitEarly: quitEarlyArr[0],
      changes
    };
  }
  /**
   * Private helper method which computes the differences on the bounded range
   * recursively.
   * @returns An array of the differences between the two input sequences.
   */
  w(originalStart, originalEnd, modifiedStart, modifiedEnd, quitEarlyArr) {
    quitEarlyArr[0] = false;
    while (originalStart <= originalEnd && modifiedStart <= modifiedEnd && this.p(originalStart, modifiedStart)) {
      originalStart++;
      modifiedStart++;
    }
    while (originalEnd >= originalStart && modifiedEnd >= modifiedStart && this.p(originalEnd, modifiedEnd)) {
      originalEnd--;
      modifiedEnd--;
    }
    if (originalStart > originalEnd || modifiedStart > modifiedEnd) {
      let changes;
      if (modifiedStart <= modifiedEnd) {
        Debug.Assert(originalStart === originalEnd + 1, "originalStart should only be one more than originalEnd");
        changes = [
          new $4C(originalStart, 0, modifiedStart, modifiedEnd - modifiedStart + 1)
        ];
      } else if (originalStart <= originalEnd) {
        Debug.Assert(modifiedStart === modifiedEnd + 1, "modifiedStart should only be one more than modifiedEnd");
        changes = [
          new $4C(originalStart, originalEnd - originalStart + 1, modifiedStart, 0)
        ];
      } else {
        Debug.Assert(originalStart === originalEnd + 1, "originalStart should only be one more than originalEnd");
        Debug.Assert(modifiedStart === modifiedEnd + 1, "modifiedStart should only be one more than modifiedEnd");
        changes = [];
      }
      return changes;
    }
    const midOriginalArr = [0];
    const midModifiedArr = [0];
    const result = this.y(originalStart, originalEnd, modifiedStart, modifiedEnd, midOriginalArr, midModifiedArr, quitEarlyArr);
    const midOriginal = midOriginalArr[0];
    const midModified = midModifiedArr[0];
    if (result !== null) {
      return result;
    } else if (!quitEarlyArr[0]) {
      const leftChanges = this.w(originalStart, midOriginal, modifiedStart, midModified, quitEarlyArr);
      let rightChanges = [];
      if (!quitEarlyArr[0]) {
        rightChanges = this.w(midOriginal + 1, originalEnd, midModified + 1, modifiedEnd, quitEarlyArr);
      } else {
        rightChanges = [
          new $4C(midOriginal + 1, originalEnd - (midOriginal + 1) + 1, midModified + 1, modifiedEnd - (midModified + 1) + 1)
        ];
      }
      return this.H(leftChanges, rightChanges);
    }
    return [
      new $4C(originalStart, originalEnd - originalStart + 1, modifiedStart, modifiedEnd - modifiedStart + 1)
    ];
  }
  x(diagonalForwardBase, diagonalForwardStart, diagonalForwardEnd, diagonalForwardOffset, diagonalReverseBase, diagonalReverseStart, diagonalReverseEnd, diagonalReverseOffset, forwardPoints, reversePoints, originalIndex, originalEnd, midOriginalArr, modifiedIndex, modifiedEnd, midModifiedArr, deltaIsEven, quitEarlyArr) {
    let forwardChanges = null;
    let reverseChanges = null;
    let changeHelper = new DiffChangeHelper();
    let diagonalMin = diagonalForwardStart;
    let diagonalMax = diagonalForwardEnd;
    let diagonalRelative = midOriginalArr[0] - midModifiedArr[0] - diagonalForwardOffset;
    let lastOriginalIndex = -1073741824;
    let historyIndex = this.k.length - 1;
    do {
      const diagonal = diagonalRelative + diagonalForwardBase;
      if (diagonal === diagonalMin || diagonal < diagonalMax && forwardPoints[diagonal - 1] < forwardPoints[diagonal + 1]) {
        originalIndex = forwardPoints[diagonal + 1];
        modifiedIndex = originalIndex - diagonalRelative - diagonalForwardOffset;
        if (originalIndex < lastOriginalIndex) {
          changeHelper.MarkNextChange();
        }
        lastOriginalIndex = originalIndex;
        changeHelper.AddModifiedElement(originalIndex + 1, modifiedIndex);
        diagonalRelative = diagonal + 1 - diagonalForwardBase;
      } else {
        originalIndex = forwardPoints[diagonal - 1] + 1;
        modifiedIndex = originalIndex - diagonalRelative - diagonalForwardOffset;
        if (originalIndex < lastOriginalIndex) {
          changeHelper.MarkNextChange();
        }
        lastOriginalIndex = originalIndex - 1;
        changeHelper.AddOriginalElement(originalIndex, modifiedIndex + 1);
        diagonalRelative = diagonal - 1 - diagonalForwardBase;
      }
      if (historyIndex >= 0) {
        forwardPoints = this.k[historyIndex];
        diagonalForwardBase = forwardPoints[0];
        diagonalMin = 1;
        diagonalMax = forwardPoints.length - 1;
      }
    } while (--historyIndex >= -1);
    forwardChanges = changeHelper.getReverseChanges();
    if (quitEarlyArr[0]) {
      let originalStartPoint = midOriginalArr[0] + 1;
      let modifiedStartPoint = midModifiedArr[0] + 1;
      if (forwardChanges !== null && forwardChanges.length > 0) {
        const lastForwardChange = forwardChanges[forwardChanges.length - 1];
        originalStartPoint = Math.max(originalStartPoint, lastForwardChange.getOriginalEnd());
        modifiedStartPoint = Math.max(modifiedStartPoint, lastForwardChange.getModifiedEnd());
      }
      reverseChanges = [
        new $4C(originalStartPoint, originalEnd - originalStartPoint + 1, modifiedStartPoint, modifiedEnd - modifiedStartPoint + 1)
      ];
    } else {
      changeHelper = new DiffChangeHelper();
      diagonalMin = diagonalReverseStart;
      diagonalMax = diagonalReverseEnd;
      diagonalRelative = midOriginalArr[0] - midModifiedArr[0] - diagonalReverseOffset;
      lastOriginalIndex = 1073741824;
      historyIndex = deltaIsEven ? this.m.length - 1 : this.m.length - 2;
      do {
        const diagonal = diagonalRelative + diagonalReverseBase;
        if (diagonal === diagonalMin || diagonal < diagonalMax && reversePoints[diagonal - 1] >= reversePoints[diagonal + 1]) {
          originalIndex = reversePoints[diagonal + 1] - 1;
          modifiedIndex = originalIndex - diagonalRelative - diagonalReverseOffset;
          if (originalIndex > lastOriginalIndex) {
            changeHelper.MarkNextChange();
          }
          lastOriginalIndex = originalIndex + 1;
          changeHelper.AddOriginalElement(originalIndex + 1, modifiedIndex + 1);
          diagonalRelative = diagonal + 1 - diagonalReverseBase;
        } else {
          originalIndex = reversePoints[diagonal - 1];
          modifiedIndex = originalIndex - diagonalRelative - diagonalReverseOffset;
          if (originalIndex > lastOriginalIndex) {
            changeHelper.MarkNextChange();
          }
          lastOriginalIndex = originalIndex;
          changeHelper.AddModifiedElement(originalIndex + 1, modifiedIndex + 1);
          diagonalRelative = diagonal - 1 - diagonalReverseBase;
        }
        if (historyIndex >= 0) {
          reversePoints = this.m[historyIndex];
          diagonalReverseBase = reversePoints[0];
          diagonalMin = 1;
          diagonalMax = reversePoints.length - 1;
        }
      } while (--historyIndex >= -1);
      reverseChanges = changeHelper.getChanges();
    }
    return this.H(forwardChanges, reverseChanges);
  }
  /**
   * Given the range to compute the diff on, this method finds the point:
   * (midOriginal, midModified)
   * that exists in the middle of the LCS of the two sequences and
   * is the point at which the LCS problem may be broken down recursively.
   * This method will try to keep the LCS trace in memory. If the LCS recursion
   * point is calculated and the full trace is available in memory, then this method
   * will return the change list.
   * @param originalStart The start bound of the original sequence range
   * @param originalEnd The end bound of the original sequence range
   * @param modifiedStart The start bound of the modified sequence range
   * @param modifiedEnd The end bound of the modified sequence range
   * @param midOriginal The middle point of the original sequence range
   * @param midModified The middle point of the modified sequence range
   * @returns The diff changes, if available, otherwise null
   */
  y(originalStart, originalEnd, modifiedStart, modifiedEnd, midOriginalArr, midModifiedArr, quitEarlyArr) {
    let originalIndex = 0, modifiedIndex = 0;
    let diagonalForwardStart = 0, diagonalForwardEnd = 0;
    let diagonalReverseStart = 0, diagonalReverseEnd = 0;
    originalStart--;
    modifiedStart--;
    midOriginalArr[0] = 0;
    midModifiedArr[0] = 0;
    this.k = [];
    this.m = [];
    const maxDifferences = originalEnd - originalStart + (modifiedEnd - modifiedStart);
    const numDiagonals = maxDifferences + 1;
    const forwardPoints = new Int32Array(numDiagonals);
    const reversePoints = new Int32Array(numDiagonals);
    const diagonalForwardBase = modifiedEnd - modifiedStart;
    const diagonalReverseBase = originalEnd - originalStart;
    const diagonalForwardOffset = originalStart - modifiedStart;
    const diagonalReverseOffset = originalEnd - modifiedEnd;
    const delta = diagonalReverseBase - diagonalForwardBase;
    const deltaIsEven = delta % 2 === 0;
    forwardPoints[diagonalForwardBase] = originalStart;
    reversePoints[diagonalReverseBase] = originalEnd;
    quitEarlyArr[0] = false;
    for (let numDifferences = 1; numDifferences <= maxDifferences / 2 + 1; numDifferences++) {
      let furthestOriginalIndex = 0;
      let furthestModifiedIndex = 0;
      diagonalForwardStart = this.J(diagonalForwardBase - numDifferences, numDifferences, diagonalForwardBase, numDiagonals);
      diagonalForwardEnd = this.J(diagonalForwardBase + numDifferences, numDifferences, diagonalForwardBase, numDiagonals);
      for (let diagonal = diagonalForwardStart; diagonal <= diagonalForwardEnd; diagonal += 2) {
        if (diagonal === diagonalForwardStart || diagonal < diagonalForwardEnd && forwardPoints[diagonal - 1] < forwardPoints[diagonal + 1]) {
          originalIndex = forwardPoints[diagonal + 1];
        } else {
          originalIndex = forwardPoints[diagonal - 1] + 1;
        }
        modifiedIndex = originalIndex - (diagonal - diagonalForwardBase) - diagonalForwardOffset;
        const tempOriginalIndex = originalIndex;
        while (originalIndex < originalEnd && modifiedIndex < modifiedEnd && this.p(originalIndex + 1, modifiedIndex + 1)) {
          originalIndex++;
          modifiedIndex++;
        }
        forwardPoints[diagonal] = originalIndex;
        if (originalIndex + modifiedIndex > furthestOriginalIndex + furthestModifiedIndex) {
          furthestOriginalIndex = originalIndex;
          furthestModifiedIndex = modifiedIndex;
        }
        if (!deltaIsEven && Math.abs(diagonal - diagonalReverseBase) <= numDifferences - 1) {
          if (originalIndex >= reversePoints[diagonal]) {
            midOriginalArr[0] = originalIndex;
            midModifiedArr[0] = modifiedIndex;
            if (tempOriginalIndex <= reversePoints[diagonal] && 1447 > 0 && numDifferences <= 1447 + 1) {
              return this.x(diagonalForwardBase, diagonalForwardStart, diagonalForwardEnd, diagonalForwardOffset, diagonalReverseBase, diagonalReverseStart, diagonalReverseEnd, diagonalReverseOffset, forwardPoints, reversePoints, originalIndex, originalEnd, midOriginalArr, modifiedIndex, modifiedEnd, midModifiedArr, deltaIsEven, quitEarlyArr);
            } else {
              return null;
            }
          }
        }
      }
      const matchLengthOfLongest = (furthestOriginalIndex - originalStart + (furthestModifiedIndex - modifiedStart) - numDifferences) / 2;
      if (this.a !== null && !this.a(furthestOriginalIndex, matchLengthOfLongest)) {
        quitEarlyArr[0] = true;
        midOriginalArr[0] = furthestOriginalIndex;
        midModifiedArr[0] = furthestModifiedIndex;
        if (matchLengthOfLongest > 0 && 1447 > 0 && numDifferences <= 1447 + 1) {
          return this.x(diagonalForwardBase, diagonalForwardStart, diagonalForwardEnd, diagonalForwardOffset, diagonalReverseBase, diagonalReverseStart, diagonalReverseEnd, diagonalReverseOffset, forwardPoints, reversePoints, originalIndex, originalEnd, midOriginalArr, modifiedIndex, modifiedEnd, midModifiedArr, deltaIsEven, quitEarlyArr);
        } else {
          originalStart++;
          modifiedStart++;
          return [
            new $4C(originalStart, originalEnd - originalStart + 1, modifiedStart, modifiedEnd - modifiedStart + 1)
          ];
        }
      }
      diagonalReverseStart = this.J(diagonalReverseBase - numDifferences, numDifferences, diagonalReverseBase, numDiagonals);
      diagonalReverseEnd = this.J(diagonalReverseBase + numDifferences, numDifferences, diagonalReverseBase, numDiagonals);
      for (let diagonal = diagonalReverseStart; diagonal <= diagonalReverseEnd; diagonal += 2) {
        if (diagonal === diagonalReverseStart || diagonal < diagonalReverseEnd && reversePoints[diagonal - 1] >= reversePoints[diagonal + 1]) {
          originalIndex = reversePoints[diagonal + 1] - 1;
        } else {
          originalIndex = reversePoints[diagonal - 1];
        }
        modifiedIndex = originalIndex - (diagonal - diagonalReverseBase) - diagonalReverseOffset;
        const tempOriginalIndex = originalIndex;
        while (originalIndex > originalStart && modifiedIndex > modifiedStart && this.p(originalIndex, modifiedIndex)) {
          originalIndex--;
          modifiedIndex--;
        }
        reversePoints[diagonal] = originalIndex;
        if (deltaIsEven && Math.abs(diagonal - diagonalForwardBase) <= numDifferences) {
          if (originalIndex <= forwardPoints[diagonal]) {
            midOriginalArr[0] = originalIndex;
            midModifiedArr[0] = modifiedIndex;
            if (tempOriginalIndex >= forwardPoints[diagonal] && 1447 > 0 && numDifferences <= 1447 + 1) {
              return this.x(diagonalForwardBase, diagonalForwardStart, diagonalForwardEnd, diagonalForwardOffset, diagonalReverseBase, diagonalReverseStart, diagonalReverseEnd, diagonalReverseOffset, forwardPoints, reversePoints, originalIndex, originalEnd, midOriginalArr, modifiedIndex, modifiedEnd, midModifiedArr, deltaIsEven, quitEarlyArr);
            } else {
              return null;
            }
          }
        }
      }
      if (numDifferences <= 1447) {
        let temp = new Int32Array(diagonalForwardEnd - diagonalForwardStart + 2);
        temp[0] = diagonalForwardBase - diagonalForwardStart + 1;
        MyArray.Copy2(forwardPoints, diagonalForwardStart, temp, 1, diagonalForwardEnd - diagonalForwardStart + 1);
        this.k.push(temp);
        temp = new Int32Array(diagonalReverseEnd - diagonalReverseStart + 2);
        temp[0] = diagonalReverseBase - diagonalReverseStart + 1;
        MyArray.Copy2(reversePoints, diagonalReverseStart, temp, 1, diagonalReverseEnd - diagonalReverseStart + 1);
        this.m.push(temp);
      }
    }
    return this.x(diagonalForwardBase, diagonalForwardStart, diagonalForwardEnd, diagonalForwardOffset, diagonalReverseBase, diagonalReverseStart, diagonalReverseEnd, diagonalReverseOffset, forwardPoints, reversePoints, originalIndex, originalEnd, midOriginalArr, modifiedIndex, modifiedEnd, midModifiedArr, deltaIsEven, quitEarlyArr);
  }
  /**
   * Shifts the given changes to provide a more intuitive diff.
   * While the first element in a diff matches the first element after the diff,
   * we shift the diff down.
   *
   * @param changes The list of changes to shift
   * @returns The shifted changes
   */
  z(changes) {
    for (let i2 = 0; i2 < changes.length; i2++) {
      const change = changes[i2];
      const originalStop = i2 < changes.length - 1 ? changes[i2 + 1].originalStart : this.f.length;
      const modifiedStop = i2 < changes.length - 1 ? changes[i2 + 1].modifiedStart : this.h.length;
      const checkOriginal = change.originalLength > 0;
      const checkModified = change.modifiedLength > 0;
      while (change.originalStart + change.originalLength < originalStop && change.modifiedStart + change.modifiedLength < modifiedStop && (!checkOriginal || this.s(change.originalStart, change.originalStart + change.originalLength)) && (!checkModified || this.u(change.modifiedStart, change.modifiedStart + change.modifiedLength))) {
        const startStrictEqual = this.q(change.originalStart, change.modifiedStart);
        const endStrictEqual = this.q(change.originalStart + change.originalLength, change.modifiedStart + change.modifiedLength);
        if (endStrictEqual && !startStrictEqual) {
          break;
        }
        change.originalStart++;
        change.modifiedStart++;
      }
      const mergedChangeArr = [null];
      if (i2 < changes.length - 1 && this.I(changes[i2], changes[i2 + 1], mergedChangeArr)) {
        changes[i2] = mergedChangeArr[0];
        changes.splice(i2 + 1, 1);
        i2--;
        continue;
      }
    }
    for (let i2 = changes.length - 1; i2 >= 0; i2--) {
      const change = changes[i2];
      let originalStop = 0;
      let modifiedStop = 0;
      if (i2 > 0) {
        const prevChange = changes[i2 - 1];
        originalStop = prevChange.originalStart + prevChange.originalLength;
        modifiedStop = prevChange.modifiedStart + prevChange.modifiedLength;
      }
      const checkOriginal = change.originalLength > 0;
      const checkModified = change.modifiedLength > 0;
      let bestDelta = 0;
      let bestScore = this.G(change.originalStart, change.originalLength, change.modifiedStart, change.modifiedLength);
      for (let delta = 1; ; delta++) {
        const originalStart = change.originalStart - delta;
        const modifiedStart = change.modifiedStart - delta;
        if (originalStart < originalStop || modifiedStart < modifiedStop) {
          break;
        }
        if (checkOriginal && !this.s(originalStart, originalStart + change.originalLength)) {
          break;
        }
        if (checkModified && !this.u(modifiedStart, modifiedStart + change.modifiedLength)) {
          break;
        }
        const touchingPreviousChange = originalStart === originalStop && modifiedStart === modifiedStop;
        const score2 = (touchingPreviousChange ? 5 : 0) + this.G(originalStart, change.originalLength, modifiedStart, change.modifiedLength);
        if (score2 > bestScore) {
          bestScore = score2;
          bestDelta = delta;
        }
      }
      change.originalStart -= bestDelta;
      change.modifiedStart -= bestDelta;
      const mergedChangeArr = [null];
      if (i2 > 0 && this.I(changes[i2 - 1], changes[i2], mergedChangeArr)) {
        changes[i2 - 1] = mergedChangeArr[0];
        changes.splice(i2, 1);
        i2++;
        continue;
      }
    }
    if (this.d) {
      for (let i2 = 1, len = changes.length; i2 < len; i2++) {
        const aChange = changes[i2 - 1];
        const bChange = changes[i2];
        const matchedLength = bChange.originalStart - aChange.originalStart - aChange.originalLength;
        const aOriginalStart = aChange.originalStart;
        const bOriginalEnd = bChange.originalStart + bChange.originalLength;
        const abOriginalLength = bOriginalEnd - aOriginalStart;
        const aModifiedStart = aChange.modifiedStart;
        const bModifiedEnd = bChange.modifiedStart + bChange.modifiedLength;
        const abModifiedLength = bModifiedEnd - aModifiedStart;
        if (matchedLength < 5 && abOriginalLength < 20 && abModifiedLength < 20) {
          const t = this.A(aOriginalStart, abOriginalLength, aModifiedStart, abModifiedLength, matchedLength);
          if (t) {
            const [originalMatchStart, modifiedMatchStart] = t;
            if (originalMatchStart !== aChange.originalStart + aChange.originalLength || modifiedMatchStart !== aChange.modifiedStart + aChange.modifiedLength) {
              aChange.originalLength = originalMatchStart - aChange.originalStart;
              aChange.modifiedLength = modifiedMatchStart - aChange.modifiedStart;
              bChange.originalStart = originalMatchStart + matchedLength;
              bChange.modifiedStart = modifiedMatchStart + matchedLength;
              bChange.originalLength = bOriginalEnd - bChange.originalStart;
              bChange.modifiedLength = bModifiedEnd - bChange.modifiedStart;
            }
          }
        }
      }
    }
    return changes;
  }
  A(originalStart, originalLength, modifiedStart, modifiedLength, desiredLength) {
    if (originalLength < desiredLength || modifiedLength < desiredLength) {
      return null;
    }
    const originalMax = originalStart + originalLength - desiredLength + 1;
    const modifiedMax = modifiedStart + modifiedLength - desiredLength + 1;
    let bestScore = 0;
    let bestOriginalStart = 0;
    let bestModifiedStart = 0;
    for (let i2 = originalStart; i2 < originalMax; i2++) {
      for (let j = modifiedStart; j < modifiedMax; j++) {
        const score2 = this.B(i2, j, desiredLength);
        if (score2 > 0 && score2 > bestScore) {
          bestScore = score2;
          bestOriginalStart = i2;
          bestModifiedStart = j;
        }
      }
    }
    if (bestScore > 0) {
      return [bestOriginalStart, bestModifiedStart];
    }
    return null;
  }
  B(originalStart, modifiedStart, length) {
    let score2 = 0;
    for (let l = 0; l < length; l++) {
      if (!this.p(originalStart + l, modifiedStart + l)) {
        return 0;
      }
      score2 += this.e[originalStart + l].length;
    }
    return score2;
  }
  C(index) {
    if (index <= 0 || index >= this.f.length - 1) {
      return true;
    }
    return this.d && /^\s*$/.test(this.e[index]);
  }
  D(originalStart, originalLength) {
    if (this.C(originalStart) || this.C(originalStart - 1)) {
      return true;
    }
    if (originalLength > 0) {
      const originalEnd = originalStart + originalLength;
      if (this.C(originalEnd - 1) || this.C(originalEnd)) {
        return true;
      }
    }
    return false;
  }
  E(index) {
    if (index <= 0 || index >= this.h.length - 1) {
      return true;
    }
    return this.d && /^\s*$/.test(this.g[index]);
  }
  F(modifiedStart, modifiedLength) {
    if (this.E(modifiedStart) || this.E(modifiedStart - 1)) {
      return true;
    }
    if (modifiedLength > 0) {
      const modifiedEnd = modifiedStart + modifiedLength;
      if (this.E(modifiedEnd - 1) || this.E(modifiedEnd)) {
        return true;
      }
    }
    return false;
  }
  G(originalStart, originalLength, modifiedStart, modifiedLength) {
    const originalScore = this.D(originalStart, originalLength) ? 1 : 0;
    const modifiedScore = this.F(modifiedStart, modifiedLength) ? 1 : 0;
    return originalScore + modifiedScore;
  }
  /**
   * Concatenates the two input DiffChange lists and returns the resulting
   * list.
   * @param The left changes
   * @param The right changes
   * @returns The concatenated list
   */
  H(left, right) {
    const mergedChangeArr = [];
    if (left.length === 0 || right.length === 0) {
      return right.length > 0 ? right : left;
    } else if (this.I(left[left.length - 1], right[0], mergedChangeArr)) {
      const result = new Array(left.length + right.length - 1);
      MyArray.Copy(left, 0, result, 0, left.length - 1);
      result[left.length - 1] = mergedChangeArr[0];
      MyArray.Copy(right, 1, result, left.length, right.length - 1);
      return result;
    } else {
      const result = new Array(left.length + right.length);
      MyArray.Copy(left, 0, result, 0, left.length);
      MyArray.Copy(right, 0, result, left.length, right.length);
      return result;
    }
  }
  /**
   * Returns true if the two changes overlap and can be merged into a single
   * change
   * @param left The left change
   * @param right The right change
   * @param mergedChange The merged change if the two overlap, null otherwise
   * @returns True if the two changes overlap
   */
  I(left, right, mergedChangeArr) {
    Debug.Assert(left.originalStart <= right.originalStart, "Left change is not less than or equal to right change");
    Debug.Assert(left.modifiedStart <= right.modifiedStart, "Left change is not less than or equal to right change");
    if (left.originalStart + left.originalLength >= right.originalStart || left.modifiedStart + left.modifiedLength >= right.modifiedStart) {
      const originalStart = left.originalStart;
      let originalLength = left.originalLength;
      const modifiedStart = left.modifiedStart;
      let modifiedLength = left.modifiedLength;
      if (left.originalStart + left.originalLength >= right.originalStart) {
        originalLength = right.originalStart + right.originalLength - left.originalStart;
      }
      if (left.modifiedStart + left.modifiedLength >= right.modifiedStart) {
        modifiedLength = right.modifiedStart + right.modifiedLength - left.modifiedStart;
      }
      mergedChangeArr[0] = new $4C(originalStart, originalLength, modifiedStart, modifiedLength);
      return true;
    } else {
      mergedChangeArr[0] = null;
      return false;
    }
  }
  /**
   * Helper method used to clip a diagonal index to the range of valid
   * diagonals. This also decides whether or not the diagonal index,
   * if it exceeds the boundary, should be clipped to the boundary or clipped
   * one inside the boundary depending on the Even/Odd status of the boundary
   * and numDifferences.
   * @param diagonal The index of the diagonal to clip.
   * @param numDifferences The current number of differences being iterated upon.
   * @param diagonalBaseIndex The base reference diagonal.
   * @param numDiagonals The total number of diagonals.
   * @returns The clipped diagonal index.
   */
  J(diagonal, numDifferences, diagonalBaseIndex, numDiagonals) {
    if (diagonal >= 0 && diagonal < numDiagonals) {
      return diagonal;
    }
    const diagonalsBelow = diagonalBaseIndex;
    const diagonalsAbove = numDiagonals - diagonalBaseIndex - 1;
    const diffEven = numDifferences % 2 === 0;
    if (diagonal < 0) {
      const lowerBoundEven = diagonalsBelow % 2 === 0;
      return diffEven === lowerBoundEven ? 0 : 1;
    } else {
      const upperBoundEven = diagonalsAbove % 2 === 0;
      return diffEven === upperBoundEven ? numDiagonals - 1 : numDiagonals - 2;
    }
  }
};

// out-build/vs/base/browser/ui/tree/indexTreeModel.js
function $k3(obj) {
  return typeof obj === "object" && "visibility" in obj && "data" in obj;
}
function $l3(visibility) {
  switch (visibility) {
    case true:
      return 1;
    case false:
      return 0;
    default:
      return visibility;
  }
}
function isCollapsibleStateUpdate(update) {
  return typeof update.collapsible === "boolean";
}
var $m3 = class {
  constructor(q, rootElement, options3 = {}) {
    this.q = q;
    this.rootRef = [];
    this.d = new $He();
    this.f = new $ze();
    this.onDidSpliceModel = this.f.event;
    this.g = new $ze();
    this.onDidSpliceRenderedNodes = this.g.event;
    this.h = new $ze();
    this.onDidChangeCollapseState = this.d.wrapEvent(this.h.event);
    this.j = new $ze();
    this.onDidChangeRenderNodeCount = this.d.wrapEvent(this.j.event);
    this.p = new $Sh($ue);
    this.k = typeof options3.collapseByDefault === "undefined" ? false : options3.collapseByDefault;
    this.l = options3.allowNonCollapsibleParents ?? false;
    this.m = options3.filter;
    this.o = typeof options3.autoExpandSingleChildren === "undefined" ? false : options3.autoExpandSingleChildren;
    this.c = {
      parent: void 0,
      element: rootElement,
      children: [],
      depth: 0,
      visibleChildrenCount: 0,
      visibleChildIndex: -1,
      collapsible: false,
      collapsed: false,
      renderNodeCount: 0,
      visibility: 1,
      visible: true,
      filterData: void 0
    };
  }
  splice(location3, deleteCount, toInsert = Iterable.empty(), options3 = {}) {
    if (location3.length === 0) {
      throw new $i3(this.q, "Invalid tree location");
    }
    if (options3.diffIdentityProvider) {
      this.s(options3.diffIdentityProvider, location3, deleteCount, toInsert, options3);
    } else {
      this.t(location3, deleteCount, toInsert, options3);
    }
  }
  s(identity, location3, deleteCount, toInsertIterable = Iterable.empty(), options3, recurseLevels = options3.diffDepth ?? 0) {
    const { parentNode } = this.H(location3);
    if (!parentNode.lastDiffIds) {
      return this.t(location3, deleteCount, toInsertIterable, options3);
    }
    const toInsert = [...toInsertIterable];
    const index = location3[location3.length - 1];
    const diff3 = new $7C({ getElements: () => parentNode.lastDiffIds }, {
      getElements: () => [
        ...parentNode.children.slice(0, index),
        ...toInsert,
        ...parentNode.children.slice(index + deleteCount)
      ].map((e) => identity.getId(e.element).toString())
    }).ComputeDiff(false);
    if (diff3.quitEarly) {
      parentNode.lastDiffIds = void 0;
      return this.t(location3, deleteCount, toInsert, options3);
    }
    const locationPrefix = location3.slice(0, -1);
    const recurseSplice = (fromOriginal, fromModified, count) => {
      if (recurseLevels > 0) {
        for (let i2 = 0; i2 < count; i2++) {
          fromOriginal--;
          fromModified--;
          this.s(identity, [...locationPrefix, fromOriginal, 0], Number.MAX_SAFE_INTEGER, toInsert[fromModified].children, options3, recurseLevels - 1);
        }
      }
    };
    let lastStartO = Math.min(parentNode.children.length, index + deleteCount);
    let lastStartM = toInsert.length;
    for (const change of diff3.changes.sort((a, b) => b.originalStart - a.originalStart)) {
      recurseSplice(lastStartO, lastStartM, lastStartO - (change.originalStart + change.originalLength));
      lastStartO = change.originalStart;
      lastStartM = change.modifiedStart - index;
      this.t([...locationPrefix, lastStartO], change.originalLength, Iterable.slice(toInsert, lastStartM, lastStartM + change.modifiedLength), options3);
    }
    recurseSplice(lastStartO, lastStartM, lastStartO);
  }
  t(location3, deleteCount, toInsert = Iterable.empty(), { onDidCreateNode, onDidDeleteNode, diffIdentityProvider }) {
    const { parentNode, listIndex, revealed, visible } = this.H(location3);
    const treeListElementsToInsert = [];
    const nodesToInsertIterator = Iterable.map(toInsert, (el) => this.x(el, parentNode, parentNode.visible ? 1 : 0, revealed, treeListElementsToInsert, onDidCreateNode));
    const lastIndex = location3[location3.length - 1];
    let visibleChildStartIndex = 0;
    for (let i2 = lastIndex; i2 >= 0 && i2 < parentNode.children.length; i2--) {
      const child = parentNode.children[i2];
      if (child.visible) {
        visibleChildStartIndex = child.visibleChildIndex;
        break;
      }
    }
    const nodesToInsert = [];
    let insertedVisibleChildrenCount = 0;
    let renderNodeCount = 0;
    for (const child of nodesToInsertIterator) {
      nodesToInsert.push(child);
      renderNodeCount += child.renderNodeCount;
      if (child.visible) {
        child.visibleChildIndex = visibleChildStartIndex + insertedVisibleChildrenCount++;
      }
    }
    const deletedNodes = $8b(parentNode.children, lastIndex, deleteCount, nodesToInsert);
    if (!diffIdentityProvider) {
      parentNode.lastDiffIds = void 0;
    } else if (parentNode.lastDiffIds) {
      $8b(parentNode.lastDiffIds, lastIndex, deleteCount, nodesToInsert.map((n) => diffIdentityProvider.getId(n.element).toString()));
    } else {
      parentNode.lastDiffIds = parentNode.children.map((n) => diffIdentityProvider.getId(n.element).toString());
    }
    let deletedVisibleChildrenCount = 0;
    for (const child of deletedNodes) {
      if (child.visible) {
        deletedVisibleChildrenCount++;
      }
    }
    if (deletedVisibleChildrenCount !== 0) {
      for (let i2 = lastIndex + nodesToInsert.length; i2 < parentNode.children.length; i2++) {
        const child = parentNode.children[i2];
        if (child.visible) {
          child.visibleChildIndex -= deletedVisibleChildrenCount;
        }
      }
    }
    parentNode.visibleChildrenCount += insertedVisibleChildrenCount - deletedVisibleChildrenCount;
    if (deletedNodes.length > 0 && onDidDeleteNode) {
      const visit = (node2) => {
        onDidDeleteNode(node2);
        node2.children.forEach(visit);
      };
      deletedNodes.forEach(visit);
    }
    if (revealed && visible) {
      const visibleDeleteCount = deletedNodes.reduce((r2, node2) => r2 + (node2.visible ? node2.renderNodeCount : 0), 0);
      this.C(parentNode, renderNodeCount - visibleDeleteCount);
      this.g.fire({ start: listIndex, deleteCount: visibleDeleteCount, elements: treeListElementsToInsert });
    }
    this.f.fire({ insertedNodes: nodesToInsert, deletedNodes });
    let node = parentNode;
    while (node) {
      if (node.visibility === 2) {
        this.p.trigger(() => this.refilter());
        break;
      }
      node = node.parent;
    }
  }
  rerender(location3) {
    if (location3.length === 0) {
      throw new $i3(this.q, "Invalid tree location");
    }
    const { node, listIndex, revealed } = this.G(location3);
    if (node.visible && revealed) {
      this.g.fire({ start: listIndex, deleteCount: 1, elements: [node] });
    }
  }
  has(location3) {
    return this.E(location3);
  }
  getListIndex(location3) {
    const { listIndex, visible, revealed } = this.G(location3);
    return visible && revealed ? listIndex : -1;
  }
  getListRenderCount(location3) {
    return this.F(location3).renderNodeCount;
  }
  isCollapsible(location3) {
    return this.F(location3).collapsible;
  }
  setCollapsible(location3, collapsible) {
    const node = this.F(location3);
    if (typeof collapsible === "undefined") {
      collapsible = !node.collapsible;
    }
    const update = { collapsible };
    return this.d.bufferEvents(() => this.u(location3, update));
  }
  isCollapsed(location3) {
    return this.F(location3).collapsed;
  }
  setCollapsed(location3, collapsed2, recursive) {
    const node = this.F(location3);
    if (typeof collapsed2 === "undefined") {
      collapsed2 = !node.collapsed;
    }
    const update = { collapsed: collapsed2, recursive: recursive || false };
    return this.d.bufferEvents(() => this.u(location3, update));
  }
  u(location3, update) {
    const { node, listIndex, revealed } = this.G(location3);
    const result = this.v(node, listIndex, revealed, update);
    if (node !== this.c && this.o && result && !isCollapsibleStateUpdate(update) && node.collapsible && !node.collapsed && !update.recursive) {
      let onlyVisibleChildIndex = -1;
      for (let i2 = 0; i2 < node.children.length; i2++) {
        const child = node.children[i2];
        if (child.visible) {
          if (onlyVisibleChildIndex > -1) {
            onlyVisibleChildIndex = -1;
            break;
          } else {
            onlyVisibleChildIndex = i2;
          }
        }
      }
      if (onlyVisibleChildIndex > -1) {
        this.u([...location3, onlyVisibleChildIndex], update);
      }
    }
    return result;
  }
  v(node, listIndex, revealed, update) {
    const result = this.w(node, update, false);
    if (!revealed || !node.visible || !result) {
      return result;
    }
    const previousRenderNodeCount = node.renderNodeCount;
    const toInsert = this.y(node);
    const deleteCount = previousRenderNodeCount - (listIndex === -1 ? 0 : 1);
    this.g.fire({ start: listIndex + 1, deleteCount, elements: toInsert.slice(1) });
    return result;
  }
  w(node, update, deep) {
    let result;
    if (node === this.c) {
      result = false;
    } else {
      if (isCollapsibleStateUpdate(update)) {
        result = node.collapsible !== update.collapsible;
        node.collapsible = update.collapsible;
      } else if (!node.collapsible) {
        result = false;
      } else {
        result = node.collapsed !== update.collapsed;
        node.collapsed = update.collapsed;
      }
      if (result) {
        this.h.fire({ node, deep });
      }
    }
    if (!isCollapsibleStateUpdate(update) && update.recursive) {
      for (const child of node.children) {
        result = this.w(child, update, true) || result;
      }
    }
    return result;
  }
  expandTo(location3) {
    this.d.bufferEvents(() => {
      let node = this.F(location3);
      while (node.parent) {
        node = node.parent;
        location3 = location3.slice(0, location3.length - 1);
        if (node.collapsed) {
          this.u(location3, { collapsed: false, recursive: false });
        }
      }
    });
  }
  refilter() {
    const previousRenderNodeCount = this.c.renderNodeCount;
    const toInsert = this.A(this.c);
    this.g.fire({ start: 0, deleteCount: previousRenderNodeCount, elements: toInsert });
    this.p.cancel();
  }
  x(treeElement, parent, parentVisibility, revealed, treeListElements, onDidCreateNode) {
    const node = {
      parent,
      element: treeElement.element,
      children: [],
      depth: parent.depth + 1,
      visibleChildrenCount: 0,
      visibleChildIndex: -1,
      collapsible: typeof treeElement.collapsible === "boolean" ? treeElement.collapsible : typeof treeElement.collapsed !== "undefined",
      collapsed: typeof treeElement.collapsed === "undefined" ? this.k : treeElement.collapsed,
      renderNodeCount: 1,
      visibility: 1,
      visible: true,
      filterData: void 0
    };
    const visibility = this.D(node, parentVisibility);
    node.visibility = visibility;
    if (revealed) {
      treeListElements.push(node);
    }
    const childElements = treeElement.children || Iterable.empty();
    const childRevealed = revealed && visibility !== 0 && !node.collapsed;
    let visibleChildrenCount = 0;
    let renderNodeCount = 1;
    for (const el of childElements) {
      const child = this.x(el, node, visibility, childRevealed, treeListElements, onDidCreateNode);
      node.children.push(child);
      renderNodeCount += child.renderNodeCount;
      if (child.visible) {
        child.visibleChildIndex = visibleChildrenCount++;
      }
    }
    if (!this.l) {
      node.collapsible = node.collapsible || node.children.length > 0;
    }
    node.visibleChildrenCount = visibleChildrenCount;
    node.visible = visibility === 2 ? visibleChildrenCount > 0 : visibility === 1;
    if (!node.visible) {
      node.renderNodeCount = 0;
      if (revealed) {
        treeListElements.pop();
      }
    } else if (!node.collapsed) {
      node.renderNodeCount = renderNodeCount;
    }
    onDidCreateNode?.(node);
    return node;
  }
  y(node) {
    const previousRenderNodeCount = node.renderNodeCount;
    const result = [];
    this.z(node, result);
    this.C(node.parent, result.length - previousRenderNodeCount);
    return result;
  }
  z(node, result) {
    if (node.visible === false) {
      return 0;
    }
    result.push(node);
    node.renderNodeCount = 1;
    if (!node.collapsed) {
      for (const child of node.children) {
        node.renderNodeCount += this.z(child, result);
      }
    }
    this.j.fire(node);
    return node.renderNodeCount;
  }
  A(node) {
    const previousRenderNodeCount = node.renderNodeCount;
    const result = [];
    this.B(node, node.visible ? 1 : 0, result);
    this.C(node.parent, result.length - previousRenderNodeCount);
    return result;
  }
  B(node, parentVisibility, result, revealed = true) {
    let visibility;
    if (node !== this.c) {
      visibility = this.D(node, parentVisibility);
      if (visibility === 0) {
        node.visible = false;
        node.renderNodeCount = 0;
        return false;
      }
      if (revealed) {
        result.push(node);
      }
    }
    const resultStartLength = result.length;
    node.renderNodeCount = node === this.c ? 0 : 1;
    let hasVisibleDescendants = false;
    if (!node.collapsed || visibility !== 0) {
      let visibleChildIndex = 0;
      for (const child of node.children) {
        hasVisibleDescendants = this.B(child, visibility, result, revealed && !node.collapsed) || hasVisibleDescendants;
        if (child.visible) {
          child.visibleChildIndex = visibleChildIndex++;
        }
      }
      node.visibleChildrenCount = visibleChildIndex;
    } else {
      node.visibleChildrenCount = 0;
    }
    if (node !== this.c) {
      node.visible = visibility === 2 ? hasVisibleDescendants : visibility === 1;
      node.visibility = visibility;
    }
    if (!node.visible) {
      node.renderNodeCount = 0;
      if (revealed) {
        result.pop();
      }
    } else if (!node.collapsed) {
      node.renderNodeCount += result.length - resultStartLength;
    }
    this.j.fire(node);
    return node.visible;
  }
  C(node, diff3) {
    if (diff3 === 0) {
      return;
    }
    while (node) {
      node.renderNodeCount += diff3;
      this.j.fire(node);
      node = node.parent;
    }
  }
  D(node, parentVisibility) {
    const result = this.m ? this.m.filter(node.element, parentVisibility) : 1;
    if (typeof result === "boolean") {
      node.filterData = void 0;
      return result ? 1 : 0;
    } else if ($k3(result)) {
      node.filterData = result.data;
      return $l3(result.visibility);
    } else {
      node.filterData = void 0;
      return $l3(result);
    }
  }
  // cheap
  E(location3, node = this.c) {
    if (!location3 || location3.length === 0) {
      return true;
    }
    const [index, ...rest] = location3;
    if (index < 0 || index > node.children.length) {
      return false;
    }
    return this.E(rest, node.children[index]);
  }
  // cheap
  F(location3, node = this.c) {
    if (!location3 || location3.length === 0) {
      return node;
    }
    const [index, ...rest] = location3;
    if (index < 0 || index > node.children.length) {
      throw new $i3(this.q, "Invalid tree location");
    }
    return this.F(rest, node.children[index]);
  }
  // expensive
  G(location3) {
    if (location3.length === 0) {
      return { node: this.c, listIndex: -1, revealed: true, visible: false };
    }
    const { parentNode, listIndex, revealed, visible } = this.H(location3);
    const index = location3[location3.length - 1];
    if (index < 0 || index > parentNode.children.length) {
      throw new $i3(this.q, "Invalid tree location");
    }
    const node = parentNode.children[index];
    return { node, listIndex, revealed, visible: visible && node.visible };
  }
  H(location3, node = this.c, listIndex = 0, revealed = true, visible = true) {
    const [index, ...rest] = location3;
    if (index < 0 || index > node.children.length) {
      throw new $i3(this.q, "Invalid tree location");
    }
    for (let i2 = 0; i2 < index; i2++) {
      listIndex += node.children[i2].renderNodeCount;
    }
    revealed = revealed && !node.collapsed;
    visible = visible && node.visible;
    if (rest.length === 0) {
      return { parentNode: node, listIndex, revealed, visible };
    }
    return this.H(rest, node.children[index], listIndex + 1, revealed, visible);
  }
  getNode(location3 = []) {
    return this.F(location3);
  }
  // TODO@joao perf!
  getNodeLocation(node) {
    const location3 = [];
    let indexTreeNode = node;
    while (indexTreeNode.parent) {
      location3.push(indexTreeNode.parent.children.indexOf(indexTreeNode));
      indexTreeNode = indexTreeNode.parent;
    }
    return location3.reverse();
  }
  getParentNodeLocation(location3) {
    if (location3.length === 0) {
      return void 0;
    } else if (location3.length === 1) {
      return [];
    } else {
      return $yb(location3)[0];
    }
  }
  getFirstElementChild(location3) {
    const node = this.F(location3);
    if (node.children.length === 0) {
      return void 0;
    }
    return node.children[0].element;
  }
  getLastElementAncestor(location3 = []) {
    const node = this.F(location3);
    if (node.children.length === 0) {
      return void 0;
    }
    return this.I(node);
  }
  I(node) {
    if (node.children.length === 0) {
      return node.element;
    }
    return this.I(node.children[node.children.length - 1]);
  }
};

// out-build/vs/base/browser/ui/tree/abstractTree.js
var TreeElementsDragAndDropData = class extends $g1 {
  set context(context) {
    this.c.context = context;
  }
  get context() {
    return this.c.context;
  }
  constructor(c) {
    super(c.elements.map((node) => node.element));
    this.c = c;
  }
};
function asTreeDragAndDropData(data) {
  if (data instanceof $g1) {
    return new TreeElementsDragAndDropData(data);
  }
  return data;
}
var TreeNodeListDragAndDrop = class {
  constructor(d, f) {
    this.d = d;
    this.f = f;
    this.b = $3c.None;
    this.c = new $2c();
  }
  getDragURI(node) {
    return this.f.getDragURI(node.element);
  }
  getDragLabel(nodes, originalEvent) {
    if (this.f.getDragLabel) {
      return this.f.getDragLabel(nodes.map((node) => node.element), originalEvent);
    }
    return void 0;
  }
  onDragStart(data, originalEvent) {
    this.f.onDragStart?.(asTreeDragAndDropData(data), originalEvent);
  }
  onDragOver(data, targetNode, targetIndex, targetSector, originalEvent, raw = true) {
    const result = this.f.onDragOver(asTreeDragAndDropData(data), targetNode && targetNode.element, targetIndex, targetSector, originalEvent);
    const didChangeAutoExpandNode = this.a !== targetNode;
    if (didChangeAutoExpandNode) {
      this.b.dispose();
      this.a = targetNode;
    }
    if (typeof targetNode === "undefined") {
      return result;
    }
    if (didChangeAutoExpandNode && typeof result !== "boolean" && result.autoExpand) {
      this.b = $Xh(() => {
        const model2 = this.d();
        const ref2 = model2.getNodeLocation(targetNode);
        if (model2.isCollapsed(ref2)) {
          model2.setCollapsed(ref2, false);
        }
        this.a = void 0;
      }, 500, this.c);
    }
    if (typeof result === "boolean" || !result.accept || typeof result.bubble === "undefined" || result.feedback) {
      if (!raw) {
        const accept = typeof result === "boolean" ? result : result.accept;
        const effect = typeof result === "boolean" ? void 0 : result.effect;
        return { accept, effect, feedback: [targetIndex] };
      }
      return result;
    }
    if (result.bubble === 1) {
      const model2 = this.d();
      const ref2 = model2.getNodeLocation(targetNode);
      const parentRef = model2.getParentNodeLocation(ref2);
      const parentNode = model2.getNode(parentRef);
      const parentIndex = parentRef && model2.getListIndex(parentRef);
      return this.onDragOver(data, parentNode, parentIndex, targetSector, originalEvent, false);
    }
    const model = this.d();
    const ref = model.getNodeLocation(targetNode);
    const start = model.getListIndex(ref);
    const length = model.getListRenderCount(ref);
    return { ...result, feedback: $Ub(start, start + length) };
  }
  drop(data, targetNode, targetIndex, targetSector, originalEvent) {
    this.b.dispose();
    this.a = void 0;
    this.f.drop(asTreeDragAndDropData(data), targetNode && targetNode.element, targetIndex, targetSector, originalEvent);
  }
  onDragEnd(originalEvent) {
    this.f.onDragEnd?.(originalEvent);
  }
  dispose() {
    this.c.dispose();
    this.f.dispose();
  }
};
function asListOptions(modelProvider, disposableStore, options3) {
  return options3 && {
    ...options3,
    identityProvider: options3.identityProvider && {
      getId(el) {
        return options3.identityProvider.getId(el.element);
      }
    },
    dnd: options3.dnd && disposableStore.add(new TreeNodeListDragAndDrop(modelProvider, options3.dnd)),
    multipleSelectionController: options3.multipleSelectionController && {
      isSelectionSingleChangeEvent(e) {
        return options3.multipleSelectionController.isSelectionSingleChangeEvent({ ...e, element: e.element });
      },
      isSelectionRangeChangeEvent(e) {
        return options3.multipleSelectionController.isSelectionRangeChangeEvent({ ...e, element: e.element });
      }
    },
    accessibilityProvider: options3.accessibilityProvider && {
      ...options3.accessibilityProvider,
      getSetSize(node) {
        const model = modelProvider();
        const ref = model.getNodeLocation(node);
        const parentRef = model.getParentNodeLocation(ref);
        const parentNode = model.getNode(parentRef);
        return parentNode.visibleChildrenCount;
      },
      getPosInSet(node) {
        return node.visibleChildIndex + 1;
      },
      isChecked: options3.accessibilityProvider && options3.accessibilityProvider.isChecked ? (node) => {
        return options3.accessibilityProvider.isChecked(node.element);
      } : void 0,
      getRole: options3.accessibilityProvider && options3.accessibilityProvider.getRole ? (node) => {
        return options3.accessibilityProvider.getRole(node.element);
      } : () => "treeitem",
      getAriaLabel(e) {
        return options3.accessibilityProvider.getAriaLabel(e.element);
      },
      getWidgetAriaLabel() {
        return options3.accessibilityProvider.getWidgetAriaLabel();
      },
      getWidgetRole: options3.accessibilityProvider && options3.accessibilityProvider.getWidgetRole ? () => options3.accessibilityProvider.getWidgetRole() : () => "tree",
      getAriaLevel: options3.accessibilityProvider && options3.accessibilityProvider.getAriaLevel ? (node) => options3.accessibilityProvider.getAriaLevel(node.element) : (node) => {
        return node.depth;
      },
      getActiveDescendantId: options3.accessibilityProvider.getActiveDescendantId && ((node) => {
        return options3.accessibilityProvider.getActiveDescendantId(node.element);
      })
    },
    keyboardNavigationLabelProvider: options3.keyboardNavigationLabelProvider && {
      ...options3.keyboardNavigationLabelProvider,
      getKeyboardNavigationLabel(node) {
        return options3.keyboardNavigationLabelProvider.getKeyboardNavigationLabel(node.element);
      }
    }
  };
}
var $n3 = class {
  constructor(a) {
    this.a = a;
  }
  getHeight(element) {
    return this.a.getHeight(element.element);
  }
  getTemplateId(element) {
    return this.a.getTemplateId(element.element);
  }
  hasDynamicHeight(element) {
    return !!this.a.hasDynamicHeight && this.a.hasDynamicHeight(element.element);
  }
  setDynamicHeight(element, height) {
    this.a.setDynamicHeight?.(element.element, height);
  }
};
var $o3 = class _$o3 {
  static lift(state) {
    return state instanceof _$o3 ? state : new _$o3(state);
  }
  static empty(scrollTop = 0) {
    return new _$o3({
      focus: [],
      selection: [],
      expanded: /* @__PURE__ */ Object.create(null),
      scrollTop
    });
  }
  constructor(state) {
    this.focus = new Set(state.focus);
    this.selection = new Set(state.selection);
    if (state.expanded instanceof Array) {
      this.expanded = /* @__PURE__ */ Object.create(null);
      for (const id2 of state.expanded) {
        this.expanded[id2] = 1;
      }
    } else {
      this.expanded = state.expanded;
    }
    this.expanded = state.expanded;
    this.scrollTop = state.scrollTop;
  }
  toJSON() {
    return {
      focus: Array.from(this.focus),
      selection: Array.from(this.selection),
      expanded: this.expanded,
      scrollTop: this.scrollTop
    };
  }
};
var RenderIndentGuides;
(function(RenderIndentGuides2) {
  RenderIndentGuides2["None"] = "none";
  RenderIndentGuides2["OnHover"] = "onHover";
  RenderIndentGuides2["Always"] = "always";
})(RenderIndentGuides || (RenderIndentGuides = {}));
var EventCollection = class {
  get elements() {
    return this.b;
  }
  constructor(onDidChange, b = []) {
    this.b = b;
    this.a = new $2c();
    this.onDidChange = Event2.forEach(onDidChange, (elements) => this.b = elements, this.a);
  }
  dispose() {
    this.a.dispose();
  }
};
var $p3 = class _$p3 {
  static {
    this.a = 8;
  }
  constructor(o, p, onDidChangeCollapseState, q, s, options3 = {}) {
    this.o = o;
    this.p = p;
    this.q = q;
    this.s = s;
    this.b = /* @__PURE__ */ new Map();
    this.c = /* @__PURE__ */ new Map();
    this.d = _$p3.a;
    this.f = false;
    this.g = false;
    this.j = /* @__PURE__ */ new Set();
    this.k = $3c.None;
    this.m = new $2c();
    this.templateId = o.templateId;
    this.updateOptions(options3);
    Event2.map(onDidChangeCollapseState, (e) => e.node)(this.u, this, this.m);
    o.onDidChangeTwistieState?.(this.t, this, this.m);
  }
  updateOptions(options3 = {}) {
    if (typeof options3.indent !== "undefined") {
      const indent = $4i(options3.indent, 0, 40);
      if (indent !== this.d) {
        this.d = indent;
        for (const [node, templateData] of this.c) {
          this.v(node, templateData);
        }
      }
    }
    if (typeof options3.renderIndentGuides !== "undefined") {
      const shouldRenderIndentGuides = options3.renderIndentGuides !== RenderIndentGuides.None;
      if (shouldRenderIndentGuides !== this.g) {
        this.g = shouldRenderIndentGuides;
        for (const [node, templateData] of this.c) {
          this.w(node, templateData);
        }
        this.k.dispose();
        if (shouldRenderIndentGuides) {
          const disposables = new $2c();
          this.q.onDidChange(this.x, this, disposables);
          this.k = disposables;
          this.x(this.q.elements);
        }
      }
    }
    if (typeof options3.hideTwistiesOfChildlessElements !== "undefined") {
      this.f = options3.hideTwistiesOfChildlessElements;
    }
  }
  renderTemplate(container2) {
    const el = $bk(container2, $(".monaco-tl-row"));
    const indent = $bk(el, $(".monaco-tl-indent"));
    const twistie = $bk(el, $(".monaco-tl-twistie"));
    const contents = $bk(el, $(".monaco-tl-contents"));
    const templateData = this.o.renderTemplate(contents);
    return { container: container2, indent, twistie, indentGuidesDisposable: $3c.None, templateData };
  }
  renderElement(node, index, templateData, height) {
    this.c.set(node, templateData);
    this.b.set(node.element, node);
    this.v(node, templateData);
    this.o.renderElement(node, index, templateData.templateData, height);
  }
  disposeElement(node, index, templateData, height) {
    templateData.indentGuidesDisposable.dispose();
    this.o.disposeElement?.(node, index, templateData.templateData, height);
    if (typeof height === "number") {
      this.c.delete(node);
      this.b.delete(node.element);
    }
  }
  disposeTemplate(templateData) {
    this.o.disposeTemplate(templateData.templateData);
  }
  t(element) {
    const node = this.b.get(element);
    if (!node) {
      return;
    }
    this.u(node);
  }
  u(node) {
    const templateData = this.c.get(node);
    if (!templateData) {
      return;
    }
    this.x(this.q.elements);
    this.v(node, templateData);
  }
  v(node, templateData) {
    const indent = _$p3.a + (node.depth - 1) * this.d;
    templateData.twistie.style.paddingLeft = `${indent}px`;
    templateData.indent.style.width = `${indent + this.d - 16}px`;
    if (node.collapsible) {
      templateData.container.setAttribute("aria-expanded", String(!node.collapsed));
    } else {
      templateData.container.removeAttribute("aria-expanded");
    }
    templateData.twistie.classList.remove(...ThemeIcon.asClassNameArray($6l.treeItemExpanded));
    let twistieRendered = false;
    if (this.o.renderTwistie) {
      twistieRendered = this.o.renderTwistie(node.element, templateData.twistie);
    }
    if (node.collapsible && (!this.f || node.visibleChildrenCount > 0)) {
      if (!twistieRendered) {
        templateData.twistie.classList.add(...ThemeIcon.asClassNameArray($6l.treeItemExpanded));
      }
      templateData.twistie.classList.add("collapsible");
      templateData.twistie.classList.toggle("collapsed", node.collapsed);
    } else {
      templateData.twistie.classList.remove("collapsible", "collapsed");
    }
    this.w(node, templateData);
  }
  w(node, templateData) {
    $$i(templateData.indent);
    templateData.indentGuidesDisposable.dispose();
    if (!this.g) {
      return;
    }
    const disposableStore = new $2c();
    while (true) {
      const ref = this.p.getNodeLocation(node);
      const parentRef = this.p.getParentNodeLocation(ref);
      if (!parentRef) {
        break;
      }
      const parent = this.p.getNode(parentRef);
      const guide = $(".indent-guide", { style: `width: ${this.d}px` });
      if (this.j.has(parent)) {
        guide.classList.add("active");
      }
      if (templateData.indent.childElementCount === 0) {
        templateData.indent.appendChild(guide);
      } else {
        templateData.indent.insertBefore(guide, templateData.indent.firstElementChild);
      }
      this.s.add(parent, guide);
      disposableStore.add($1c(() => this.s.delete(parent, guide)));
      node = parent;
    }
    templateData.indentGuidesDisposable = disposableStore;
  }
  x(nodes) {
    if (!this.g) {
      return;
    }
    const set = /* @__PURE__ */ new Set();
    nodes.forEach((node) => {
      const ref = this.p.getNodeLocation(node);
      try {
        const parentRef = this.p.getParentNodeLocation(ref);
        if (node.collapsible && node.children.length > 0 && !node.collapsed) {
          set.add(node);
        } else if (parentRef) {
          set.add(this.p.getNode(parentRef));
        }
      } catch {
      }
    });
    this.j.forEach((node) => {
      if (!set.has(node)) {
        this.s.forEach(node, (line) => line.classList.remove("active"));
      }
    });
    set.forEach((node) => {
      if (!this.j.has(node)) {
        this.s.forEach(node, (line) => line.classList.add("active"));
      }
    });
    this.j = set;
  }
  dispose() {
    this.c.clear();
    this.b.clear();
    this.k.dispose();
    $Xc(this.m);
  }
};
function $q3(patternLower, wordLower) {
  const index = wordLower.toLowerCase().indexOf(patternLower);
  let score2;
  if (index > -1) {
    score2 = [Number.MAX_SAFE_INTEGER, 0];
    for (let i2 = patternLower.length; i2 > 0; i2--) {
      score2.push(index + i2 - 1);
    }
  }
  return score2;
}
var $r3 = class {
  get totalCount() {
    return this.a;
  }
  get matchCount() {
    return this.b;
  }
  set findMatchType(type) {
    this.d = type;
  }
  get findMatchType() {
    return this.d;
  }
  set findMode(mode) {
    this.f = mode;
  }
  get findMode() {
    return this.f;
  }
  set pattern(pattern) {
    this.g = pattern;
    this.j = pattern.toLowerCase();
  }
  constructor(m, o, p) {
    this.m = m;
    this.o = o;
    this.p = p;
    this.a = 0;
    this.b = 0;
    this.d = TreeFindMatchType.Fuzzy;
    this.f = TreeFindMode.Highlight;
    this.g = "";
    this.j = "";
    this.k = new $2c();
  }
  filter(element, parentVisibility) {
    let visibility = 1;
    if (this.o) {
      const result = this.o.filter(element, parentVisibility);
      if (typeof result === "boolean") {
        visibility = result ? 1 : 0;
      } else if ($k3(result)) {
        visibility = $l3(result.visibility);
      } else {
        visibility = result;
      }
      if (visibility === 0) {
        return false;
      }
    }
    this.a++;
    if (!this.g) {
      this.b++;
      return { data: FuzzyScore.Default, visibility };
    }
    const label3 = this.m.getKeyboardNavigationLabel(element);
    const labels2 = Array.isArray(label3) ? label3 : [label3];
    for (const l of labels2) {
      const labelStr = l && l.toString();
      if (typeof labelStr === "undefined") {
        return { data: FuzzyScore.Default, visibility };
      }
      let score2;
      if (this.d === TreeFindMatchType.Contiguous) {
        score2 = $q3(this.j, labelStr.toLowerCase());
      } else {
        score2 = $Xl(this.g, this.j, 0, labelStr, labelStr.toLowerCase(), 0, { firstMatchCanBeWeak: true, boostFullMatch: true });
      }
      if (score2) {
        this.b++;
        return labels2.length === 1 ? { data: score2, visibility } : { data: { label: labelStr, score: score2 }, visibility };
      }
    }
    if (this.f === TreeFindMode.Filter) {
      if (typeof this.p === "number") {
        return this.p;
      } else if (this.p) {
        return this.p(element);
      } else {
        return 2;
      }
    } else {
      return { data: FuzzyScore.Default, visibility };
    }
  }
  reset() {
    this.a = 0;
    this.b = 0;
  }
  dispose() {
    $Xc(this.k);
  }
};
var TreeFindToggle = class extends $Q1 {
  constructor(contribution, opts, hoverDelegate) {
    super({
      icon: contribution.icon,
      title: contribution.title,
      isChecked: contribution.isChecked,
      inputActiveOptionBorder: opts.inputActiveOptionBorder,
      inputActiveOptionForeground: opts.inputActiveOptionForeground,
      inputActiveOptionBackground: opts.inputActiveOptionBackground,
      hoverDelegate
    });
    this.id = contribution.id;
  }
};
var $s3 = class {
  constructor(startStates) {
    this.a = new Map(startStates.map((state) => [state.id, { ...state }]));
  }
  states() {
    return Array.from(this.a.values());
  }
  get(id2) {
    const state = this.a.get(id2);
    if (state === void 0) {
      throw new Error(`No state found for toggle id ${id2}`);
    }
    return state.isChecked;
  }
  set(id2, value) {
    const state = this.a.get(id2);
    if (state === void 0) {
      throw new Error(`No state found for toggle id ${id2}`);
    }
    if (state.isChecked === value) {
      return false;
    }
    state.isChecked = value;
    return true;
  }
};
var unthemedFindWidgetStyles = {
  inputBoxStyles: $H2,
  toggleStyles: $O1,
  listFilterWidgetBackground: void 0,
  listFilterWidgetNoMatchesOutline: void 0,
  listFilterWidgetOutline: void 0,
  listFilterWidgetShadow: void 0
};
var TreeFindMode;
(function(TreeFindMode2) {
  TreeFindMode2[TreeFindMode2["Highlight"] = 0] = "Highlight";
  TreeFindMode2[TreeFindMode2["Filter"] = 1] = "Filter";
})(TreeFindMode || (TreeFindMode = {}));
var TreeFindMatchType;
(function(TreeFindMatchType2) {
  TreeFindMatchType2[TreeFindMatchType2["Fuzzy"] = 0] = "Fuzzy";
  TreeFindMatchType2[TreeFindMatchType2["Contiguous"] = 1] = "Contiguous";
})(TreeFindMatchType || (TreeFindMatchType = {}));
var FindWidget = class extends $3c {
  get value() {
    return this.b.inputBox.value;
  }
  set value(value) {
    this.b.inputBox.value = value;
  }
  constructor(container2, g, contextViewProvider, placeholder, toggleContributions = [], options3) {
    super();
    this.g = g;
    this.a = h(".monaco-tree-type-filter", [
      h(".monaco-tree-type-filter-input@findInput"),
      h(".monaco-tree-type-filter-actionbar@actionbar")
    ]);
    this.f = [];
    this._onDidDisable = new $ze();
    this.onDidDisable = this._onDidDisable.event;
    container2.appendChild(this.a.root);
    this.B($1c(() => this.a.root.remove()));
    const styles = options3?.styles ?? unthemedFindWidgetStyles;
    if (styles.listFilterWidgetBackground) {
      this.a.root.style.backgroundColor = styles.listFilterWidgetBackground;
    }
    if (styles.listFilterWidgetShadow) {
      this.a.root.style.boxShadow = `0 0 8px 2px ${styles.listFilterWidgetShadow}`;
    }
    const toggleHoverDelegate = this.B($KZ());
    this.f = toggleContributions.map((contribution) => this.B(new TreeFindToggle(contribution, styles.toggleStyles, toggleHoverDelegate)));
    this.onDidToggleChange = Event2.any(...this.f.map((toggle) => Event2.map(toggle.onChange, () => ({ id: toggle.id, isChecked: toggle.checked }))));
    const history = options3?.history || [];
    this.b = this.B(new $Q2(this.a.findInput, contextViewProvider, {
      label: localize(31, null),
      placeholder,
      additionalToggles: this.f,
      showCommonFindToggles: false,
      inputBoxStyles: styles.inputBoxStyles,
      toggleStyles: styles.toggleStyles,
      history: new Set(history)
    }));
    this.c = this.B(new $LZ(this.a.actionbar));
    const emitter = this.B(new $9Z(this.b.inputBox.inputElement, "keydown"));
    const onKeyDown = Event2.chain(emitter.event, ($149) => $149.map((e) => new $if(e)));
    this.B(onKeyDown((e) => {
      if (e.equals(
        3
        /* KeyCode.Enter */
      )) {
        e.preventDefault();
        e.stopPropagation();
        this.b.inputBox.addToHistory();
        this.g.domFocus();
        return;
      }
      if (e.equals(
        18
        /* KeyCode.DownArrow */
      )) {
        e.preventDefault();
        e.stopPropagation();
        if (this.b.inputBox.isAtLastInHistory() || this.b.inputBox.isNowhereInHistory()) {
          this.b.inputBox.addToHistory();
          this.g.domFocus();
        } else {
          this.b.inputBox.showNextValue();
        }
        return;
      }
      if (e.equals(
        16
        /* KeyCode.UpArrow */
      )) {
        e.preventDefault();
        e.stopPropagation();
        this.b.inputBox.showPreviousValue();
        return;
      }
    }));
    const closeAction = this.B(new $Um("close", localize(32, null), "codicon codicon-close", true, () => this.dispose()));
    this.c.push(closeAction, { icon: true, label: false });
    this.onDidChangeValue = this.b.onDidChange;
  }
  setToggleState(id2, checked) {
    const toggle = this.f.find((toggle2) => toggle2.id === id2);
    if (toggle) {
      toggle.checked = checked;
    }
  }
  setPlaceHolder(placeHolder) {
    this.b.inputBox.setPlaceHolder(placeHolder);
  }
  getHistory() {
    return this.b.inputBox.getHistory();
  }
  focus() {
    this.b.focus();
  }
  select() {
    this.b.select();
    this.b.inputBox.addToHistory(true);
  }
  showMessage(message) {
    this.b.showMessage(message);
  }
  clearMessage() {
    this.b.clearMessage();
  }
  async dispose() {
    this._onDidDisable.fire();
    this.a.root.classList.add("disabled");
    await $Wh(300);
    super.dispose();
  }
};
var DefaultTreeToggles;
(function(DefaultTreeToggles2) {
  DefaultTreeToggles2["Mode"] = "mode";
  DefaultTreeToggles2["MatchType"] = "matchType";
})(DefaultTreeToggles || (DefaultTreeToggles = {}));
var $t3 = class {
  get pattern() {
    return this.b;
  }
  get j() {
    return this.g;
  }
  set j(value) {
    this.g = value;
    this.k?.setPlaceHolder(value);
  }
  constructor(s, t, u, v = {}) {
    this.s = s;
    this.t = t;
    this.u = u;
    this.v = v;
    this.b = "";
    this.d = "";
    this.m = new $ze();
    this.onDidChangePattern = this.m.event;
    this.o = new $ze();
    this.onDidChangeOpenState = this.o.event;
    this.p = new $2c();
    this.q = new $2c();
    this.f = new $s3(v.toggles ?? []);
    this.g = v.placeholder ?? localize(33, null);
  }
  isOpened() {
    return !!this.k;
  }
  open() {
    if (this.k) {
      this.k.focus();
      this.k.select();
      return;
    }
    this.s.updateOptions({ paddingTop: 30 });
    this.k = new FindWidget(this.s.getHTMLElement(), this.s, this.u, this.j, this.f.states(), { ...this.v, history: this.a });
    this.p.add(this.k);
    this.k.onDidChangeValue(this.w, this, this.p);
    this.k.onDidDisable(this.close, this, this.p);
    this.k.onDidToggleChange(this.y, this, this.p);
    this.k.focus();
    this.k.value = this.d;
    this.k.select();
    this.o.fire(true);
  }
  close() {
    if (!this.k) {
      return;
    }
    this.s.updateOptions({ paddingTop: 0 });
    this.a = this.k.getHistory();
    this.k = void 0;
    this.p.clear();
    this.d = this.pattern;
    this.w("");
    this.s.domFocus();
    this.o.fire(false);
  }
  w(pattern) {
    this.b = pattern;
    this.m.fire(pattern);
    this.t.pattern = pattern;
    this.x(pattern);
  }
  y(e) {
    this.f.set(e.id, e.isChecked);
  }
  z(id2, checked) {
    this.f.set(id2, checked);
    this.k?.setToggleState(id2, checked);
  }
  A(showNotFound, warningMessage) {
    if (showNotFound) {
      if (this.s.options.showNotFoundMessage ?? true) {
        this.k?.showMessage({ type: 2, content: warningMessage ?? localize(34, null) });
      } else {
        this.k?.showMessage({
          type: 2
          /* MessageType.WARNING */
        });
      }
    } else {
      this.k?.clearMessage();
    }
  }
  B(results) {
    if (!results) {
      $$Z(localize(35, null));
    } else {
      $$Z(localize(36, null, results));
    }
  }
  dispose() {
    this.a = void 0;
    this.m.dispose();
    this.p.dispose();
    this.q.dispose();
  }
};
var $u3 = class extends $t3 {
  get mode() {
    return this.f.get(DefaultTreeToggles.Mode) ? TreeFindMode.Filter : TreeFindMode.Highlight;
  }
  set mode(mode) {
    if (mode === this.mode) {
      return;
    }
    const isFilterMode = mode === TreeFindMode.Filter;
    this.z(DefaultTreeToggles.Mode, isFilterMode);
    this.j = isFilterMode ? localize(37, null) : localize(38, null);
    this.t.findMode = mode;
    this.s.refilter();
    this.H();
    this.C.fire(mode);
  }
  get matchType() {
    return this.f.get(DefaultTreeToggles.MatchType) ? TreeFindMatchType.Fuzzy : TreeFindMatchType.Contiguous;
  }
  set matchType(matchType) {
    if (matchType === this.matchType) {
      return;
    }
    this.z(DefaultTreeToggles.MatchType, matchType === TreeFindMatchType.Fuzzy);
    this.t.findMatchType = matchType;
    this.s.refilter();
    this.H();
    this.D.fire(matchType);
  }
  constructor(tree, t, contextViewProvider, options3 = {}) {
    const defaultFindMode = options3.defaultFindMode ?? TreeFindMode.Highlight;
    const defaultFindMatchType = options3.defaultFindMatchType ?? TreeFindMatchType.Fuzzy;
    const toggleContributions = [{
      id: DefaultTreeToggles.Mode,
      icon: $6l.listFilter,
      title: localize(39, null),
      isChecked: defaultFindMode === TreeFindMode.Filter
    }, {
      id: DefaultTreeToggles.MatchType,
      icon: $6l.searchFuzzy,
      title: localize(40, null),
      isChecked: defaultFindMatchType === TreeFindMatchType.Fuzzy
    }];
    t.findMatchType = defaultFindMatchType;
    t.findMode = defaultFindMode;
    super(tree, t, contextViewProvider, { ...options3, toggles: toggleContributions });
    this.t = t;
    this.C = new $ze();
    this.onDidChangeMode = this.C.event;
    this.D = new $ze();
    this.onDidChangeMatchType = this.D.event;
    this.q.add(this.s.onDidChangeModel(() => {
      if (!this.isOpened()) {
        return;
      }
      if (this.pattern.length !== 0) {
        this.s.refilter();
      }
      this.H();
    }));
    this.q.add(this.s.onWillRefilter(() => this.t.reset()));
  }
  updateOptions(optionsUpdate = {}) {
    if (optionsUpdate.defaultFindMode !== void 0) {
      this.mode = optionsUpdate.defaultFindMode;
    }
    if (optionsUpdate.defaultFindMatchType !== void 0) {
      this.matchType = optionsUpdate.defaultFindMatchType;
    }
  }
  x(pattern) {
    this.s.refilter();
    if (pattern) {
      this.s.focusNext(0, true, void 0, (node) => this.shouldAllowFocus(node));
    }
    const focus = this.s.getFocus();
    if (focus.length > 0) {
      const element = focus[0];
      if (this.s.getRelativeTop(element) === null) {
        this.s.reveal(element, 0.5);
      }
    }
    this.H();
  }
  shouldAllowFocus(node) {
    if (!this.isOpened() || !this.pattern) {
      return true;
    }
    if (this.t.totalCount > 0 && this.t.matchCount <= 1) {
      return true;
    }
    return !FuzzyScore.isDefault(node.filterData);
  }
  y(e) {
    if (e.id === DefaultTreeToggles.Mode) {
      this.mode = e.isChecked ? TreeFindMode.Filter : TreeFindMode.Highlight;
    } else if (e.id === DefaultTreeToggles.MatchType) {
      this.matchType = e.isChecked ? TreeFindMatchType.Fuzzy : TreeFindMatchType.Contiguous;
    }
  }
  H() {
    const noMatches = this.t.matchCount === 0 && this.t.totalCount > 0;
    const showNotFound = noMatches && this.pattern.length > 0;
    this.A(showNotFound);
    if (this.pattern.length) {
      this.B(this.t.matchCount);
    }
  }
};
function stickyScrollNodeStateEquals(node1, node2) {
  return node1.position === node2.position && stickyScrollNodeEquals(node1, node2);
}
function stickyScrollNodeEquals(node1, node2) {
  return node1.node.element === node2.node.element && node1.startIndex === node2.startIndex && node1.height === node2.height && node1.endIndex === node2.endIndex;
}
var StickyScrollState = class {
  constructor(stickyNodes = []) {
    this.stickyNodes = stickyNodes;
  }
  get count() {
    return this.stickyNodes.length;
  }
  equal(state) {
    return $zb(this.stickyNodes, state.stickyNodes, stickyScrollNodeStateEquals);
  }
  contains(element) {
    return this.stickyNodes.some((node) => node.node.element === element.element);
  }
  lastNodePartiallyVisible() {
    if (this.count === 0) {
      return false;
    }
    const lastStickyNode = this.stickyNodes[this.count - 1];
    if (this.count === 1) {
      return lastStickyNode.position !== 0;
    }
    const secondLastStickyNode = this.stickyNodes[this.count - 2];
    return secondLastStickyNode.position + secondLastStickyNode.height !== lastStickyNode.position;
  }
  animationStateChanged(previousState) {
    if (!$zb(this.stickyNodes, previousState.stickyNodes, stickyScrollNodeEquals)) {
      return false;
    }
    if (this.count === 0) {
      return false;
    }
    const lastStickyNode = this.stickyNodes[this.count - 1];
    const previousLastStickyNode = previousState.stickyNodes[previousState.count - 1];
    return lastStickyNode.position !== previousLastStickyNode.position;
  }
};
var DefaultStickyScrollDelegate = class {
  constrainStickyScrollNodes(stickyNodes, stickyScrollMaxItemCount, maxWidgetHeight) {
    for (let i2 = 0; i2 < stickyNodes.length; i2++) {
      const stickyNode = stickyNodes[i2];
      const stickyNodeBottom = stickyNode.position + stickyNode.height;
      if (stickyNodeBottom > maxWidgetHeight || i2 >= stickyScrollMaxItemCount) {
        return stickyNodes.slice(0, i2);
      }
    }
    return stickyNodes;
  }
};
var StickyScrollController = class extends $3c {
  constructor(j, m, s, renderers, t, options3 = {}) {
    super();
    this.j = j;
    this.m = m;
    this.s = s;
    this.t = t;
    this.c = 0.4;
    const stickyScrollOptions = this.validateStickySettings(options3);
    this.b = stickyScrollOptions.stickyScrollMaxItemCount;
    this.a = options3.stickyScrollDelegate ?? new DefaultStickyScrollDelegate();
    this.g = options3.paddingTop ?? 0;
    this.f = this.B(new StickyScrollWidget(s.getScrollableElement(), s, j, renderers, t, options3.accessibilityProvider));
    this.onDidChangeHasFocus = this.f.onDidChangeHasFocus;
    this.onContextMenu = this.f.onContextMenu;
    this.B(s.onDidScroll(() => this.w()));
    this.B(s.onDidChangeContentHeight(() => this.w()));
    this.B(j.onDidChangeCollapseState(() => this.w()));
    this.B(m.onDidSpliceRenderedNodes((e) => {
      const state = this.f.state;
      if (!state) {
        return;
      }
      const hasRemovedStickyNode = e.deleteCount > 0 && state.stickyNodes.some((stickyNode) => !this.m.has(this.m.getNodeLocation(stickyNode.node)));
      if (hasRemovedStickyNode) {
        this.w();
        return;
      }
      const shouldRerenderStickyNodes = state.stickyNodes.some((stickyNode) => {
        const listIndex = this.m.getListIndex(this.m.getNodeLocation(stickyNode.node));
        return listIndex >= e.start && listIndex < e.start + e.deleteCount && state.contains(stickyNode.node);
      });
      if (shouldRerenderStickyNodes) {
        this.f.rerender();
      }
    }));
    this.w();
  }
  get height() {
    return this.f.height;
  }
  get count() {
    return this.f.count;
  }
  getNode(node) {
    return this.f.getNode(node);
  }
  u(height) {
    let index;
    if (height === 0) {
      index = this.s.firstVisibleIndex;
    } else {
      index = this.s.indexAt(height + this.s.scrollTop);
    }
    if (index < 0 || index >= this.s.length) {
      return void 0;
    }
    return this.s.element(index);
  }
  w() {
    const firstVisibleNode = this.u(this.g);
    if (!firstVisibleNode || this.j.scrollTop <= this.g) {
      this.f.setState(void 0);
      return;
    }
    const stickyState = this.y(firstVisibleNode);
    this.f.setState(stickyState);
  }
  y(firstVisibleNode) {
    const stickyNodes = [];
    let firstVisibleNodeUnderWidget = firstVisibleNode;
    let stickyNodesHeight = 0;
    let nextStickyNode = this.C(firstVisibleNodeUnderWidget, void 0, stickyNodesHeight);
    while (nextStickyNode) {
      stickyNodes.push(nextStickyNode);
      stickyNodesHeight += nextStickyNode.height;
      if (stickyNodes.length <= this.b) {
        firstVisibleNodeUnderWidget = this.z(nextStickyNode);
        if (!firstVisibleNodeUnderWidget) {
          break;
        }
      }
      nextStickyNode = this.C(firstVisibleNodeUnderWidget, nextStickyNode.node, stickyNodesHeight);
    }
    const contrainedStickyNodes = this.I(stickyNodes);
    return contrainedStickyNodes.length ? new StickyScrollState(contrainedStickyNodes) : void 0;
  }
  z(previousStickyNode) {
    return this.u(previousStickyNode.position + previousStickyNode.height);
  }
  C(firstVisibleNodeUnderWidget, previousStickyNode, stickyNodesHeight) {
    const nextStickyNode = this.G(firstVisibleNodeUnderWidget, previousStickyNode);
    if (!nextStickyNode) {
      return void 0;
    }
    if (nextStickyNode === firstVisibleNodeUnderWidget) {
      if (!this.L(firstVisibleNodeUnderWidget)) {
        return void 0;
      }
      if (this.D(firstVisibleNodeUnderWidget, stickyNodesHeight)) {
        return void 0;
      }
    }
    return this.F(nextStickyNode, stickyNodesHeight);
  }
  D(node, stickyNodesHeight) {
    const nodeIndex = this.M(node);
    const elementTop = this.s.getElementTop(nodeIndex);
    const stickyPosition = stickyNodesHeight;
    return this.s.scrollTop === elementTop - stickyPosition;
  }
  F(node, currentStickyNodesHeight) {
    const height = this.t.getHeight(node);
    const { startIndex, endIndex } = this.O(node);
    const position = this.H(endIndex, currentStickyNodesHeight, height);
    return { node, position, height, startIndex, endIndex };
  }
  G(node, previousAncestor = void 0) {
    let currentAncestor = node;
    let parentOfcurrentAncestor = this.J(currentAncestor);
    while (parentOfcurrentAncestor) {
      if (parentOfcurrentAncestor === previousAncestor) {
        return currentAncestor;
      }
      currentAncestor = parentOfcurrentAncestor;
      parentOfcurrentAncestor = this.J(currentAncestor);
    }
    if (previousAncestor === void 0) {
      return currentAncestor;
    }
    return void 0;
  }
  H(lastDescendantIndex, stickyRowPositionTop, stickyNodeHeight) {
    let lastChildRelativeTop = this.s.getRelativeTop(lastDescendantIndex);
    if (lastChildRelativeTop === null && this.s.firstVisibleIndex === lastDescendantIndex && lastDescendantIndex + 1 < this.s.length) {
      const nodeHeight = this.t.getHeight(this.s.element(lastDescendantIndex));
      const nextNodeRelativeTop = this.s.getRelativeTop(lastDescendantIndex + 1);
      lastChildRelativeTop = nextNodeRelativeTop ? nextNodeRelativeTop - nodeHeight / this.s.renderHeight : null;
    }
    if (lastChildRelativeTop === null) {
      return stickyRowPositionTop;
    }
    const lastChildNode = this.s.element(lastDescendantIndex);
    const lastChildHeight = this.t.getHeight(lastChildNode);
    const topOfLastChild = lastChildRelativeTop * this.s.renderHeight;
    const bottomOfLastChild = topOfLastChild + lastChildHeight;
    if (stickyRowPositionTop + stickyNodeHeight > bottomOfLastChild && stickyRowPositionTop <= bottomOfLastChild) {
      return bottomOfLastChild - stickyNodeHeight;
    }
    return stickyRowPositionTop;
  }
  I(stickyNodes) {
    if (stickyNodes.length === 0) {
      return [];
    }
    const maximumStickyWidgetHeight = this.s.renderHeight * this.c;
    const lastStickyNode = stickyNodes[stickyNodes.length - 1];
    if (stickyNodes.length <= this.b && lastStickyNode.position + lastStickyNode.height <= maximumStickyWidgetHeight) {
      return stickyNodes;
    }
    const constrainedStickyNodes = this.a.constrainStickyScrollNodes(stickyNodes, this.b, maximumStickyWidgetHeight);
    if (!constrainedStickyNodes.length) {
      return [];
    }
    const lastConstrainedStickyNode = constrainedStickyNodes[constrainedStickyNodes.length - 1];
    if (constrainedStickyNodes.length > this.b || lastConstrainedStickyNode.position + lastConstrainedStickyNode.height > maximumStickyWidgetHeight) {
      throw new Error("stickyScrollDelegate violates constraints");
    }
    return constrainedStickyNodes;
  }
  J(node) {
    const nodeLocation = this.m.getNodeLocation(node);
    const parentLocation = this.m.getParentNodeLocation(nodeLocation);
    return parentLocation ? this.m.getNode(parentLocation) : void 0;
  }
  L(node) {
    const nodeLocation = this.m.getNodeLocation(node);
    return this.m.getListRenderCount(nodeLocation) > 1;
  }
  M(node) {
    const nodeLocation = this.m.getNodeLocation(node);
    const nodeIndex = this.m.getListIndex(nodeLocation);
    return nodeIndex;
  }
  O(node) {
    const nodeLocation = this.m.getNodeLocation(node);
    const startIndex = this.m.getListIndex(nodeLocation);
    if (startIndex < 0) {
      throw new Error("Node not found in tree");
    }
    const renderCount = this.m.getListRenderCount(nodeLocation);
    const endIndex = startIndex + renderCount - 1;
    return { startIndex, endIndex };
  }
  nodePositionTopBelowWidget(node) {
    const ancestors = [];
    let currentAncestor = this.J(node);
    while (currentAncestor) {
      ancestors.push(currentAncestor);
      currentAncestor = this.J(currentAncestor);
    }
    let widgetHeight = 0;
    for (let i2 = 0; i2 < ancestors.length && i2 < this.b; i2++) {
      widgetHeight += this.t.getHeight(ancestors[i2]);
    }
    return widgetHeight;
  }
  getFocus() {
    return this.f.getFocus();
  }
  domFocus() {
    this.f.domFocus();
  }
  // Whether sticky scroll was the last focused part in the tree or not
  focusedLast() {
    return this.f.focusedLast();
  }
  updateOptions(optionsUpdate = {}) {
    if (optionsUpdate.paddingTop !== void 0) {
      this.g = optionsUpdate.paddingTop;
    }
    if (optionsUpdate.stickyScrollMaxItemCount !== void 0) {
      const validatedOptions = this.validateStickySettings(optionsUpdate);
      if (this.b !== validatedOptions.stickyScrollMaxItemCount) {
        this.b = validatedOptions.stickyScrollMaxItemCount;
        this.w();
      }
    }
  }
  validateStickySettings(options3) {
    let stickyScrollMaxItemCount = 7;
    if (typeof options3.stickyScrollMaxItemCount === "number") {
      stickyScrollMaxItemCount = Math.max(options3.stickyScrollMaxItemCount, 1);
    }
    return { stickyScrollMaxItemCount };
  }
};
var StickyScrollWidget = class {
  get state() {
    return this.b;
  }
  constructor(container2, g, j, k, m, o) {
    this.g = g;
    this.j = j;
    this.k = k;
    this.m = m;
    this.o = o;
    this.c = [];
    this.d = new $2c();
    this.a = $(".monaco-tree-sticky-container.empty");
    container2.appendChild(this.a);
    const shadow = $(".monaco-tree-sticky-container-shadow");
    this.a.appendChild(shadow);
    this.f = new StickyScrollFocus(this.a, g);
    this.onDidChangeHasFocus = this.f.onDidChangeHasFocus;
    this.onContextMenu = this.f.onContextMenu;
  }
  get height() {
    if (!this.b) {
      return 0;
    }
    const lastElement = this.b.stickyNodes[this.b.count - 1];
    return lastElement.position + lastElement.height;
  }
  get count() {
    return this.b?.count ?? 0;
  }
  getNode(node) {
    return this.b?.stickyNodes.find((stickyNode) => stickyNode.node === node);
  }
  setState(state) {
    const wasVisible = !!this.b && this.b.count > 0;
    const isVisible = !!state && state.count > 0;
    if (!wasVisible && !isVisible || wasVisible && isVisible && this.b.equal(state)) {
      return;
    }
    if (wasVisible !== isVisible) {
      this.t(isVisible);
    }
    if (!isVisible) {
      this.b = void 0;
      this.c = [];
      this.d.clear();
      return;
    }
    const lastStickyNode = state.stickyNodes[state.count - 1];
    if (this.b && state.animationStateChanged(this.b)) {
      this.c[this.b.count - 1].style.top = `${lastStickyNode.position}px`;
    } else {
      this.p(state);
    }
    this.b = state;
    this.a.style.height = `${lastStickyNode.position + lastStickyNode.height}px`;
  }
  p(state) {
    this.d.clear();
    const elements = Array(state.count);
    for (let stickyIndex = state.count - 1; stickyIndex >= 0; stickyIndex--) {
      const stickyNode = state.stickyNodes[stickyIndex];
      const { element, disposable } = this.q(stickyNode, stickyIndex, state.count);
      elements[stickyIndex] = element;
      this.a.appendChild(element);
      this.d.add(disposable);
    }
    this.f.updateElements(elements, state);
    this.c = elements;
  }
  rerender() {
    if (this.b) {
      this.p(this.b);
    }
  }
  q(stickyNode, stickyIndex, stickyNodesTotal) {
    const nodeIndex = stickyNode.startIndex;
    const stickyElement = document.createElement("div");
    stickyElement.style.top = `${stickyNode.position}px`;
    if (this.j.options.setRowHeight !== false) {
      stickyElement.style.height = `${stickyNode.height}px`;
    }
    if (this.j.options.setRowLineHeight !== false) {
      stickyElement.style.lineHeight = `${stickyNode.height}px`;
    }
    stickyElement.classList.add("monaco-tree-sticky-row");
    stickyElement.classList.add("monaco-list-row");
    stickyElement.setAttribute("data-index", `${nodeIndex}`);
    stickyElement.setAttribute("data-parity", nodeIndex % 2 === 0 ? "even" : "odd");
    stickyElement.setAttribute("id", this.g.getElementID(nodeIndex));
    const accessibilityDisposable = this.s(stickyElement, stickyNode.node.element, stickyIndex, stickyNodesTotal);
    const nodeTemplateId = this.m.getTemplateId(stickyNode.node);
    const renderer = this.k.find((renderer2) => renderer2.templateId === nodeTemplateId);
    if (!renderer) {
      throw new Error(`No renderer found for template id ${nodeTemplateId}`);
    }
    let nodeCopy = stickyNode.node;
    if (nodeCopy === this.j.getNode(this.j.getNodeLocation(stickyNode.node))) {
      nodeCopy = new Proxy(stickyNode.node, {});
    }
    const templateData = renderer.renderTemplate(stickyElement);
    renderer.renderElement(nodeCopy, stickyNode.startIndex, templateData, stickyNode.height);
    const disposable = $1c(() => {
      accessibilityDisposable.dispose();
      renderer.disposeElement(nodeCopy, stickyNode.startIndex, templateData, stickyNode.height);
      renderer.disposeTemplate(templateData);
      stickyElement.remove();
    });
    return { element: stickyElement, disposable };
  }
  s(container2, element, stickyIndex, stickyNodesTotal) {
    if (!this.o) {
      return $3c.None;
    }
    if (this.o.getSetSize) {
      container2.setAttribute("aria-setsize", String(this.o.getSetSize(element, stickyIndex, stickyNodesTotal)));
    }
    if (this.o.getPosInSet) {
      container2.setAttribute("aria-posinset", String(this.o.getPosInSet(element, stickyIndex)));
    }
    if (this.o.getRole) {
      container2.setAttribute("role", this.o.getRole(element) ?? "treeitem");
    }
    const ariaLabel = this.o.getAriaLabel(element);
    const observable = ariaLabel && typeof ariaLabel !== "string" ? ariaLabel : $Bd(ariaLabel);
    const result = $td((reader) => {
      const value = reader.readObservable(observable);
      if (value) {
        container2.setAttribute("aria-label", value);
      } else {
        container2.removeAttribute("aria-label");
      }
    });
    if (typeof ariaLabel === "string") {
    } else if (ariaLabel) {
      container2.setAttribute("aria-label", ariaLabel.get());
    }
    const ariaLevel = this.o.getAriaLevel && this.o.getAriaLevel(element);
    if (typeof ariaLevel === "number") {
      container2.setAttribute("aria-level", `${ariaLevel}`);
    }
    container2.setAttribute("aria-selected", String(false));
    return result;
  }
  t(visible) {
    this.a.classList.toggle("empty", !visible);
    if (!visible) {
      this.f.updateElements([], void 0);
    }
  }
  getFocus() {
    return this.f.getFocus();
  }
  domFocus() {
    this.f.domFocus();
  }
  focusedLast() {
    return this.f.focusedLast();
  }
  dispose() {
    this.f.dispose();
    this.d.dispose();
    this.a.remove();
  }
};
var StickyScrollFocus = class extends $3c {
  get m() {
    return this.j;
  }
  set m(hasFocus) {
    if (hasFocus !== this.j) {
      this.f.fire(hasFocus);
      this.j = hasFocus;
    }
  }
  constructor(s, t) {
    super();
    this.s = s;
    this.t = t;
    this.a = -1;
    this.b = [];
    this.f = new $ze();
    this.onDidChangeHasFocus = this.f.event;
    this.g = new $ze();
    this.onContextMenu = this.g.event;
    this.j = false;
    this.B($_i(this.s, "focus", () => this.M()));
    this.B($_i(this.s, "blur", () => this.O()));
    this.B(this.t.onDidFocus(() => this.L(false)));
    this.B(this.t.onKeyDown((e) => this.w(e)));
    this.B(this.t.onMouseDown((e) => this.y(e)));
    this.B(this.t.onContextMenu((e) => this.u(e)));
  }
  u(e) {
    const target = e.browserEvent.target;
    if (!$s1(target) && !$r1(target)) {
      if (this.focusedLast()) {
        this.t.domFocus();
      }
      return;
    }
    if (!$4j(e.browserEvent)) {
      if (!this.c) {
        throw new Error("Context menu should not be triggered when state is undefined");
      }
      const stickyIndex = this.c.stickyNodes.findIndex((stickyNode2) => stickyNode2.node.element === e.element?.element);
      if (stickyIndex === -1) {
        throw new Error("Context menu should not be triggered when element is not in sticky scroll widget");
      }
      this.s.focus();
      this.F(stickyIndex);
      return;
    }
    if (!this.c || this.a < 0) {
      throw new Error("Context menu key should not be triggered when focus is not in sticky scroll widget");
    }
    const stickyNode = this.c.stickyNodes[this.a];
    const element = stickyNode.node.element;
    const anchor = this.b[this.a];
    this.g.fire({ element, anchor, browserEvent: e.browserEvent, isStickyScroll: true });
  }
  w(e) {
    if (this.m && this.c) {
      if (e.key === "ArrowUp") {
        this.z(Math.max(0, this.a - 1));
        e.preventDefault();
        e.stopPropagation();
      } else if (e.key === "ArrowDown" || e.key === "ArrowRight") {
        if (this.a >= this.c.count - 1) {
          const nodeIndexToFocus = this.c.stickyNodes[this.c.count - 1].startIndex + 1;
          this.t.domFocus();
          this.t.setFocus([nodeIndexToFocus]);
          this.C(nodeIndexToFocus, this.c);
        } else {
          this.z(this.a + 1);
        }
        e.preventDefault();
        e.stopPropagation();
      }
    }
  }
  y(e) {
    const target = e.browserEvent.target;
    if (!$s1(target) && !$r1(target)) {
      return;
    }
    e.browserEvent.preventDefault();
    e.browserEvent.stopPropagation();
  }
  updateElements(elements, state) {
    if (state && state.count === 0) {
      throw new Error("Sticky scroll state must be undefined when there are no sticky nodes");
    }
    if (state && state.count !== elements.length) {
      throw new Error("Sticky scroll focus received illigel state");
    }
    const previousIndex = this.a;
    this.D();
    this.b = elements;
    this.c = state;
    if (state) {
      const newFocusedIndex = $4i(previousIndex, 0, state.count - 1);
      this.F(newFocusedIndex);
    } else {
      if (this.m) {
        this.t.domFocus();
      }
    }
    this.s.tabIndex = state ? 0 : -1;
  }
  z(stickyIndex) {
    const state = this.c;
    if (!state) {
      throw new Error("Cannot set focus when state is undefined");
    }
    this.F(stickyIndex);
    if (stickyIndex < state.count - 1) {
      return;
    }
    if (state.lastNodePartiallyVisible()) {
      const lastStickyNode = state.stickyNodes[stickyIndex];
      this.C(lastStickyNode.endIndex + 1, state);
    }
  }
  C(nodeIndex, state) {
    const lastStickyNode = state.stickyNodes[state.count - 1];
    const secondLastStickyNode = state.count > 1 ? state.stickyNodes[state.count - 2] : void 0;
    const elementScrollTop = this.t.getElementTop(nodeIndex);
    const elementTargetViewTop = secondLastStickyNode ? secondLastStickyNode.position + secondLastStickyNode.height + lastStickyNode.height : lastStickyNode.height;
    this.t.scrollTop = elementScrollTop - elementTargetViewTop;
  }
  getFocus() {
    if (!this.c || this.a === -1) {
      return void 0;
    }
    return this.c.stickyNodes[this.a].node.element;
  }
  domFocus() {
    if (!this.c) {
      throw new Error("Cannot focus when state is undefined");
    }
    this.s.focus();
  }
  focusedLast() {
    if (!this.c) {
      return false;
    }
    return this.t.getHTMLElement().classList.contains("sticky-scroll-focused");
  }
  D() {
    if (this.a === -1) {
      return;
    }
    this.G(this.b[this.a], false);
    this.a = -1;
  }
  F(newFocusIndex) {
    if (0 > newFocusIndex) {
      throw new Error("addFocus() can not remove focus");
    }
    if (!this.c && newFocusIndex >= 0) {
      throw new Error("Cannot set focus index when state is undefined");
    }
    if (this.c && newFocusIndex >= this.c.count) {
      throw new Error("Cannot set focus index to an index that does not exist");
    }
    const oldIndex = this.a;
    if (oldIndex >= 0) {
      this.G(this.b[oldIndex], false);
    }
    if (newFocusIndex >= 0) {
      this.G(this.b[newFocusIndex], true);
    }
    this.a = newFocusIndex;
  }
  G(element, focused) {
    this.I(element, focused && this.m);
    this.J(element, focused);
  }
  H(focused) {
    if (this.a === -1) {
      return;
    }
    this.I(this.b[this.a], focused);
  }
  I(element, focused) {
    element.classList.toggle("focused", focused);
  }
  J(element, focused) {
    element.classList.toggle("passive-focused", focused);
  }
  L(focused) {
    this.t.getHTMLElement().classList.toggle("sticky-scroll-focused", focused);
  }
  M() {
    if (!this.c || this.b.length === 0) {
      throw new Error("Cannot focus when state is undefined or elements are empty");
    }
    this.m = true;
    this.L(true);
    this.H(true);
    if (this.a === -1) {
      this.F(0);
    }
  }
  O() {
    this.m = false;
    this.H(false);
  }
  dispose() {
    this.L(false);
    this.f.fire(false);
    super.dispose();
  }
};
function asTreeMouseEvent(event) {
  let target = TreeMouseEventTarget.Unknown;
  if ($Hj(event.browserEvent.target, "monaco-tl-twistie", "monaco-tl-row")) {
    target = TreeMouseEventTarget.Twistie;
  } else if ($Hj(event.browserEvent.target, "monaco-tl-contents", "monaco-tl-row")) {
    target = TreeMouseEventTarget.Element;
  } else if ($Hj(event.browserEvent.target, "monaco-tree-type-filter", "monaco-list")) {
    target = TreeMouseEventTarget.Filter;
  }
  return {
    browserEvent: event.browserEvent,
    element: event.element ? event.element.element : null,
    target
  };
}
function asTreeContextMenuEvent(event) {
  const isStickyScroll = $s1(event.browserEvent.target);
  return {
    element: event.element ? event.element.element : null,
    browserEvent: event.browserEvent,
    anchor: event.anchor,
    isStickyScroll
  };
}
function dfs(node, fn) {
  fn(node);
  node.children.forEach((child) => dfs(child, fn));
}
var Trait2 = class {
  get f() {
    if (!this.d) {
      this.d = this.m();
    }
    return this.d;
  }
  constructor(g, j) {
    this.g = g;
    this.j = j;
    this.a = [];
    this.c = new $ze();
    this.onDidChange = this.c.event;
  }
  set(nodes, browserEvent) {
    if (!browserEvent?.__forceEvent && $zb(this.a, nodes)) {
      return;
    }
    this.k(nodes, false, browserEvent);
  }
  k(nodes, silent, browserEvent) {
    this.a = [...nodes];
    this.b = void 0;
    this.d = void 0;
    if (!silent) {
      const that = this;
      this.c.fire({ get elements() {
        return that.get();
      }, browserEvent });
    }
  }
  get() {
    if (!this.b) {
      this.b = this.a.map((node) => node.element);
    }
    return [...this.b];
  }
  getNodes() {
    return this.a;
  }
  has(node) {
    return this.f.has(node);
  }
  onDidModelSplice({ insertedNodes, deletedNodes }) {
    if (!this.j) {
      const set = this.m();
      const visit = (node) => set.delete(node);
      deletedNodes.forEach((node) => dfs(node, visit));
      this.set([...set.values()]);
      return;
    }
    const deletedNodesIdSet = /* @__PURE__ */ new Set();
    const deletedNodesVisitor = (node) => deletedNodesIdSet.add(this.j.getId(node.element).toString());
    deletedNodes.forEach((node) => dfs(node, deletedNodesVisitor));
    const insertedNodesMap = /* @__PURE__ */ new Map();
    const insertedNodesVisitor = (node) => insertedNodesMap.set(this.j.getId(node.element).toString(), node);
    insertedNodes.forEach((node) => dfs(node, insertedNodesVisitor));
    const nodes = [];
    for (const node of this.a) {
      const id2 = this.j.getId(node.element).toString();
      const wasDeleted = deletedNodesIdSet.has(id2);
      if (!wasDeleted) {
        nodes.push(node);
      } else {
        const insertedNode = insertedNodesMap.get(id2);
        if (insertedNode && insertedNode.visible) {
          nodes.push(insertedNode);
        }
      }
    }
    if (this.a.length > 0 && nodes.length === 0) {
      const node = this.g();
      if (node) {
        nodes.push(node);
      }
    }
    this.k(nodes, true);
  }
  m() {
    const set = /* @__PURE__ */ new Set();
    for (const node of this.a) {
      set.add(node);
    }
    return set;
  }
};
var TreeNodeListMouseController = class extends $x1 {
  constructor(list2, c, y) {
    super(list2);
    this.c = c;
    this.y = y;
  }
  v(e) {
    if ($t1(e.browserEvent.target) || $Fk(e.browserEvent.target) || $n1(e.browserEvent.target)) {
      return;
    }
    if (e.browserEvent.isHandledByList) {
      return;
    }
    const node = e.element;
    if (!node) {
      return super.v(e);
    }
    if (this.q(e) || this.p(e)) {
      return super.v(e);
    }
    const target = e.browserEvent.target;
    const onTwistie = target.classList.contains("monaco-tl-twistie") || target.classList.contains("monaco-icon-label") && target.classList.contains("folder-icon") && e.browserEvent.offsetX < 16;
    const isStickyElement = $r1(e.browserEvent.target);
    let expandOnlyOnTwistieClick = false;
    if (isStickyElement) {
      expandOnlyOnTwistieClick = true;
    } else if (typeof this.c.expandOnlyOnTwistieClick === "function") {
      expandOnlyOnTwistieClick = this.c.expandOnlyOnTwistieClick(node.element);
    } else {
      expandOnlyOnTwistieClick = !!this.c.expandOnlyOnTwistieClick;
    }
    if (!isStickyElement) {
      if (expandOnlyOnTwistieClick && !onTwistie && e.browserEvent.detail !== 2) {
        return super.v(e);
      }
      if (!this.c.expandOnDoubleClick && e.browserEvent.detail === 2) {
        return super.v(e);
      }
    } else {
      this.A(e, node);
    }
    if (node.collapsible && (!isStickyElement || onTwistie)) {
      const location3 = this.c.getNodeLocation(node);
      const recursive = e.browserEvent.altKey;
      this.c.setFocus([location3]);
      this.c.toggleCollapsed(location3, recursive);
      if (onTwistie) {
        e.browserEvent.isHandledByList = true;
        return;
      }
    }
    if (!isStickyElement) {
      super.v(e);
    }
  }
  A(e, node) {
    if ($o1(e.browserEvent.target) || $p1(e.browserEvent.target)) {
      return;
    }
    const stickyScrollController = this.y();
    if (!stickyScrollController) {
      throw new Error("Sticky scroll controller not found");
    }
    const nodeIndex = this.o.indexOf(node);
    const elementScrollTop = this.o.getElementTop(nodeIndex);
    const elementTargetViewTop = stickyScrollController.nodePositionTopBelowWidget(node);
    this.c.scrollTop = elementScrollTop - elementTargetViewTop;
    this.o.domFocus();
    this.o.setFocus([nodeIndex]);
    this.o.setSelection([nodeIndex]);
  }
  w(e) {
    const onTwistie = e.browserEvent.target.classList.contains("monaco-tl-twistie");
    if (onTwistie || !this.c.expandOnDoubleClick) {
      return;
    }
    if (e.browserEvent.isHandledByList) {
      return;
    }
    super.w(e);
  }
  // to make sure dom focus is not stolen (for example with context menu)
  t(e) {
    const target = e.browserEvent.target;
    if (!$s1(target) && !$r1(target)) {
      super.t(e);
      return;
    }
  }
  u(e) {
    const target = e.browserEvent.target;
    if (!$s1(target) && !$r1(target)) {
      super.u(e);
      return;
    }
  }
};
var TreeNodeList = class extends $A1 {
  constructor(user, container2, virtualDelegate, renderers, c, p, s, options3) {
    super(user, container2, virtualDelegate, renderers, options3);
    this.c = c;
    this.p = p;
    this.s = s;
  }
  E(options3) {
    return new TreeNodeListMouseController(this, options3.tree, options3.stickyScrollProvider);
  }
  splice(start, deleteCount, elements = []) {
    super.splice(start, deleteCount, elements);
    if (elements.length === 0) {
      return;
    }
    const additionalFocus = [];
    const additionalSelection = [];
    let anchor;
    elements.forEach((node, index) => {
      if (this.c.has(node)) {
        additionalFocus.push(start + index);
      }
      if (this.p.has(node)) {
        additionalSelection.push(start + index);
      }
      if (this.s.has(node)) {
        anchor = start + index;
      }
    });
    if (additionalFocus.length > 0) {
      super.setFocus($Rb([...super.getFocus(), ...additionalFocus]));
    }
    if (additionalSelection.length > 0) {
      super.setSelection($Rb([...super.getSelection(), ...additionalSelection]));
    }
    if (typeof anchor === "number") {
      super.setAnchor(anchor);
    }
  }
  setFocus(indexes, browserEvent, fromAPI = false) {
    super.setFocus(indexes, browserEvent);
    if (!fromAPI) {
      this.c.set(indexes.map((i2) => this.element(i2)), browserEvent);
    }
  }
  setSelection(indexes, browserEvent, fromAPI = false) {
    super.setSelection(indexes, browserEvent);
    if (!fromAPI) {
      this.p.set(indexes.map((i2) => this.element(i2)), browserEvent);
    }
  }
  setAnchor(index, fromAPI = false) {
    super.setAnchor(index);
    if (!fromAPI) {
      if (typeof index === "undefined") {
        this.s.set([]);
      } else {
        this.s.set([this.element(index)]);
      }
    }
  }
};
var AbstractTreePart;
(function(AbstractTreePart2) {
  AbstractTreePart2[AbstractTreePart2["Tree"] = 0] = "Tree";
  AbstractTreePart2[AbstractTreePart2["StickyScroll"] = 1] = "StickyScroll";
})(AbstractTreePart || (AbstractTreePart = {}));
var $v3 = class {
  get onDidScroll() {
    return this.j.onDidScroll;
  }
  get onDidChangeFocus() {
    return this.y.wrapEvent(this.q.onDidChange);
  }
  get onDidChangeSelection() {
    return this.y.wrapEvent(this.w.onDidChange);
  }
  get onMouseClick() {
    return Event2.map(this.j.onMouseClick, asTreeMouseEvent);
  }
  get onMouseDblClick() {
    return Event2.filter(Event2.map(this.j.onMouseDblClick, asTreeMouseEvent), (e) => e.target !== TreeMouseEventTarget.Filter);
  }
  get onMouseOver() {
    return Event2.map(this.j.onMouseOver, asTreeMouseEvent);
  }
  get onMouseOut() {
    return Event2.map(this.j.onMouseOut, asTreeMouseEvent);
  }
  get onContextMenu() {
    return Event2.any(Event2.filter(Event2.map(this.j.onContextMenu, asTreeContextMenuEvent), (e) => !e.isStickyScroll), this.C?.onContextMenu ?? Event2.None);
  }
  get onTap() {
    return Event2.map(this.j.onTap, asTreeMouseEvent);
  }
  get onPointer() {
    return Event2.map(this.j.onPointer, asTreeMouseEvent);
  }
  get onKeyDown() {
    return this.j.onKeyDown;
  }
  get onKeyUp() {
    return this.j.onKeyUp;
  }
  get onKeyPress() {
    return this.j.onKeyPress;
  }
  get onDidFocus() {
    return this.j.onDidFocus;
  }
  get onDidBlur() {
    return this.j.onDidBlur;
  }
  get onDidChangeModel() {
    return Event2.any(this.G.event, this.F.event);
  }
  get onDidChangeCollapseState() {
    return this.I.event;
  }
  get onDidChangeRenderNodeCount() {
    return this.J.event;
  }
  get findMode() {
    return this.z?.mode ?? TreeFindMode.Highlight;
  }
  set findMode(findMode) {
    if (this.z) {
      this.z.mode = findMode;
    }
  }
  get findMatchType() {
    return this.z?.matchType ?? TreeFindMatchType.Fuzzy;
  }
  set findMatchType(findFuzzy) {
    if (this.z) {
      this.z.matchType = findFuzzy;
    }
  }
  get onDidChangeFindPattern() {
    return this.z ? this.z.onDidChangePattern : Event2.None;
  }
  get expandOnDoubleClick() {
    return typeof this.P.expandOnDoubleClick === "undefined" ? true : this.P.expandOnDoubleClick;
  }
  get expandOnlyOnTwistieClick() {
    return typeof this.P.expandOnlyOnTwistieClick === "undefined" ? true : this.P.expandOnlyOnTwistieClick;
  }
  get onDidDispose() {
    return this.j.onDidDispose;
  }
  constructor(O, container2, delegate, renderers, P = {}) {
    this.O = O;
    this.P = P;
    this.y = new $He();
    this.onDidChangeFindOpenState = Event2.None;
    this.onDidChangeStickyScrollFocused = Event2.None;
    this.E = new $2c();
    this.F = this.E.add(new $ze());
    this.G = this.E.add(new $Ie());
    this.H = this.E.add(new $Ie());
    this.I = this.E.add(new $Ie());
    this.J = this.E.add(new $Ie());
    this.K = this.E.add(new $Ie());
    this.L = new $ze();
    this.onWillRefilter = this.L.event;
    this.M = new $ze();
    this.onDidUpdateOptions = this.M.event;
    this.W = new $2c();
    if (P.keyboardNavigationLabelProvider && (P.findWidgetEnabled ?? true)) {
      this.A = new $r3(P.keyboardNavigationLabelProvider, P.filter, P.defaultFindVisibility);
      P = { ...P, filter: this.A };
      this.E.add(this.A);
    }
    this.o = this.V(O, P);
    this.p = new $n3(delegate);
    const activeNodes = this.E.add(new EventCollection(this.K.event));
    const renderedIndentGuides = new $Lc();
    this.k = renderers.map((r2) => new $p3(r2, this.o, this.I.event, activeNodes, renderedIndentGuides, P));
    for (const r2 of this.k) {
      this.E.add(r2);
    }
    this.q = new Trait2(() => this.j.getFocusedElements()[0], P.identityProvider);
    this.w = new Trait2(() => this.j.getSelectedElements()[0], P.identityProvider);
    this.x = new Trait2(() => this.j.getAnchorElement(), P.identityProvider);
    this.j = new TreeNodeList(O, container2, this.p, this.k, this.q, this.w, this.x, { ...asListOptions(() => this.o, this.E, P), tree: this, stickyScrollProvider: () => this.C });
    this.X(this.o);
    if (P.keyboardSupport !== false) {
      const onKeyDown = Event2.chain(this.j.onKeyDown, ($149) => $149.filter((e) => !$Fk(e.target)).map((e) => new $if(e)));
      Event2.chain(onKeyDown, ($149) => $149.filter(
        (e) => e.keyCode === 15
        /* KeyCode.LeftArrow */
      ))(this.R, this, this.E);
      Event2.chain(onKeyDown, ($149) => $149.filter(
        (e) => e.keyCode === 17
        /* KeyCode.RightArrow */
      ))(this.S, this, this.E);
      Event2.chain(onKeyDown, ($149) => $149.filter(
        (e) => e.keyCode === 10
        /* KeyCode.Space */
      ))(this.U, this, this.E);
    }
    if ((P.findWidgetEnabled ?? true) && P.keyboardNavigationLabelProvider && P.contextViewProvider) {
      const findOptions = {
        styles: P.findWidgetStyles,
        defaultFindMode: P.defaultFindMode,
        defaultFindMatchType: P.defaultFindMatchType,
        showNotFoundMessage: P.showNotFoundMessage
      };
      this.z = this.E.add(new $u3(this, this.A, P.contextViewProvider, findOptions));
      this.B = (node) => this.z.shouldAllowFocus(node);
      this.onDidChangeFindOpenState = this.z.onDidChangeOpenState;
      this.onDidChangeFindMode = this.z.onDidChangeMode;
      this.onDidChangeFindMatchType = this.z.onDidChangeMatchType;
    } else {
      this.onDidChangeFindMode = Event2.None;
      this.onDidChangeFindMatchType = Event2.None;
    }
    if (P.enableStickyScroll) {
      this.C = new StickyScrollController(this, this.o, this.j, this.k, this.p, P);
      this.onDidChangeStickyScrollFocused = this.C.onDidChangeHasFocus;
    }
    this.D = $VZ(this.j.getHTMLElement());
    this.getHTMLElement().classList.toggle("always", this.P.renderIndentGuides === RenderIndentGuides.Always);
  }
  updateOptions(optionsUpdate = {}) {
    this.P = { ...this.P, ...optionsUpdate };
    for (const renderer of this.k) {
      renderer.updateOptions(optionsUpdate);
    }
    this.j.updateOptions(this.P);
    this.z?.updateOptions(optionsUpdate);
    this.Q(optionsUpdate);
    this.M.fire(this.P);
    this.getHTMLElement().classList.toggle("always", this.P.renderIndentGuides === RenderIndentGuides.Always);
  }
  get options() {
    return this.P;
  }
  Q(optionsUpdate) {
    if (!this.C && this.P.enableStickyScroll) {
      this.C = new StickyScrollController(this, this.o, this.j, this.k, this.p, this.P);
      this.onDidChangeStickyScrollFocused = this.C.onDidChangeHasFocus;
    } else if (this.C && !this.P.enableStickyScroll) {
      this.onDidChangeStickyScrollFocused = Event2.None;
      this.C.dispose();
      this.C = void 0;
    }
    this.C?.updateOptions(optionsUpdate);
  }
  updateWidth(element) {
    const index = this.o.getListIndex(element);
    if (index === -1) {
      return;
    }
    this.j.updateWidth(index);
  }
  // Widget
  getHTMLElement() {
    return this.j.getHTMLElement();
  }
  get contentHeight() {
    return this.j.contentHeight;
  }
  get contentWidth() {
    return this.j.contentWidth;
  }
  get onDidChangeContentHeight() {
    return this.j.onDidChangeContentHeight;
  }
  get onDidChangeContentWidth() {
    return this.j.onDidChangeContentWidth;
  }
  get scrollTop() {
    return this.j.scrollTop;
  }
  set scrollTop(scrollTop) {
    this.j.scrollTop = scrollTop;
  }
  get scrollLeft() {
    return this.j.scrollLeft;
  }
  set scrollLeft(scrollLeft) {
    this.j.scrollLeft = scrollLeft;
  }
  get scrollHeight() {
    return this.j.scrollHeight;
  }
  get renderHeight() {
    return this.j.renderHeight;
  }
  get firstVisibleElement() {
    let index = this.j.firstVisibleIndex;
    if (this.C) {
      index += this.C.count;
    }
    if (index < 0 || index >= this.j.length) {
      return void 0;
    }
    const node = this.j.element(index);
    return node.element;
  }
  get lastVisibleElement() {
    const index = this.j.lastVisibleIndex;
    const node = this.j.element(index);
    return node.element;
  }
  get ariaLabel() {
    return this.j.ariaLabel;
  }
  set ariaLabel(value) {
    this.j.ariaLabel = value;
  }
  get selectionSize() {
    return this.w.getNodes().length;
  }
  domFocus() {
    if (this.C?.focusedLast()) {
      this.C.domFocus();
    } else {
      this.j.domFocus();
    }
  }
  isDOMFocused() {
    return $Mj(this.getHTMLElement());
  }
  layout(height, width2) {
    this.j.layout(height, width2);
  }
  style(styles) {
    const suffix = `.${this.j.domId}`;
    const content = [];
    if (styles.treeIndentGuidesStroke) {
      content.push(`.monaco-list${suffix}:hover .monaco-tl-indent > .indent-guide, .monaco-list${suffix}.always .monaco-tl-indent > .indent-guide  { border-color: ${styles.treeInactiveIndentGuidesStroke}; }`);
      content.push(`.monaco-list${suffix} .monaco-tl-indent > .indent-guide.active { border-color: ${styles.treeIndentGuidesStroke}; }`);
    }
    const stickyScrollBackground = styles.treeStickyScrollBackground ?? styles.listBackground;
    if (stickyScrollBackground) {
      content.push(`.monaco-list${suffix} .monaco-scrollable-element .monaco-tree-sticky-container { background-color: ${stickyScrollBackground}; }`);
      content.push(`.monaco-list${suffix} .monaco-scrollable-element .monaco-tree-sticky-container .monaco-tree-sticky-row { background-color: ${stickyScrollBackground}; }`);
    }
    if (styles.treeStickyScrollBorder) {
      content.push(`.monaco-list${suffix} .monaco-scrollable-element .monaco-tree-sticky-container { border-bottom: 1px solid ${styles.treeStickyScrollBorder}; }`);
    }
    if (styles.treeStickyScrollShadow) {
      content.push(`.monaco-list${suffix} .monaco-scrollable-element .monaco-tree-sticky-container .monaco-tree-sticky-container-shadow { box-shadow: ${styles.treeStickyScrollShadow} 0 6px 6px -6px inset; height: 3px; }`);
    }
    if (styles.listFocusForeground) {
      content.push(`.monaco-list${suffix}.sticky-scroll-focused .monaco-scrollable-element .monaco-tree-sticky-container:focus .monaco-list-row.focused { color: ${styles.listFocusForeground}; }`);
      content.push(`.monaco-list${suffix}:not(.sticky-scroll-focused) .monaco-scrollable-element .monaco-tree-sticky-container .monaco-list-row.focused { color: inherit; }`);
    }
    const focusAndSelectionOutline = $ZZ(styles.listFocusAndSelectionOutline, $ZZ(styles.listSelectionOutline, styles.listFocusOutline ?? ""));
    if (focusAndSelectionOutline) {
      content.push(`.monaco-list${suffix}.sticky-scroll-focused .monaco-scrollable-element .monaco-tree-sticky-container:focus .monaco-list-row.focused.selected { outline: 1px solid ${focusAndSelectionOutline}; outline-offset: -1px;}`);
      content.push(`.monaco-list${suffix}:not(.sticky-scroll-focused) .monaco-scrollable-element .monaco-tree-sticky-container .monaco-list-row.focused.selected { outline: inherit;}`);
    }
    if (styles.listFocusOutline) {
      content.push(`.monaco-list${suffix}.sticky-scroll-focused .monaco-scrollable-element .monaco-tree-sticky-container:focus .monaco-list-row.focused { outline: 1px solid ${styles.listFocusOutline}; outline-offset: -1px; }`);
      content.push(`.monaco-list${suffix}:not(.sticky-scroll-focused) .monaco-scrollable-element .monaco-tree-sticky-container .monaco-list-row.focused { outline: inherit; }`);
      content.push(`.monaco-workbench.context-menu-visible .monaco-list${suffix}.last-focused.sticky-scroll-focused .monaco-scrollable-element .monaco-tree-sticky-container .monaco-list-row.passive-focused { outline: 1px solid ${styles.listFocusOutline}; outline-offset: -1px; }`);
      content.push(`.monaco-workbench.context-menu-visible .monaco-list${suffix}.last-focused.sticky-scroll-focused .monaco-list-rows .monaco-list-row.focused { outline: inherit; }`);
      content.push(`.monaco-workbench.context-menu-visible .monaco-list${suffix}.last-focused:not(.sticky-scroll-focused) .monaco-tree-sticky-container .monaco-list-rows .monaco-list-row.focused { outline: inherit; }`);
    }
    this.D.textContent = content.join("\n");
    this.j.style(styles);
  }
  // Tree navigation
  getParentElement(location3) {
    const parentRef = this.o.getParentNodeLocation(location3);
    const parentNode = this.o.getNode(parentRef);
    return parentNode.element;
  }
  getFirstElementChild(location3) {
    return this.o.getFirstElementChild(location3);
  }
  // Tree
  getNode(location3) {
    return this.o.getNode(location3);
  }
  getNodeLocation(node) {
    return this.o.getNodeLocation(node);
  }
  collapse(location3, recursive = false) {
    return this.o.setCollapsed(location3, true, recursive);
  }
  expand(location3, recursive = false) {
    return this.o.setCollapsed(location3, false, recursive);
  }
  toggleCollapsed(location3, recursive = false) {
    return this.o.setCollapsed(location3, void 0, recursive);
  }
  expandAll() {
    this.o.setCollapsed(this.o.rootRef, false, true);
  }
  collapseAll() {
    this.o.setCollapsed(this.o.rootRef, true, true);
  }
  isCollapsible(location3) {
    return this.o.isCollapsible(location3);
  }
  setCollapsible(location3, collapsible) {
    return this.o.setCollapsible(location3, collapsible);
  }
  isCollapsed(location3) {
    return this.o.isCollapsed(location3);
  }
  expandTo(location3) {
    this.o.expandTo(location3);
  }
  triggerTypeNavigation() {
    this.j.triggerTypeNavigation();
  }
  openFind() {
    this.z?.open();
  }
  closeFind() {
    this.z?.close();
  }
  refilter() {
    this.L.fire(void 0);
    this.o.refilter();
  }
  setAnchor(element) {
    if (typeof element === "undefined") {
      return this.j.setAnchor(void 0);
    }
    this.y.bufferEvents(() => {
      const node = this.o.getNode(element);
      this.x.set([node]);
      const index = this.o.getListIndex(element);
      if (index > -1) {
        this.j.setAnchor(index, true);
      }
    });
  }
  getAnchor() {
    return this.x.get().at(0);
  }
  setSelection(elements, browserEvent) {
    this.y.bufferEvents(() => {
      const nodes = elements.map((e) => this.o.getNode(e));
      this.w.set(nodes, browserEvent);
      const indexes = elements.map((e) => this.o.getListIndex(e)).filter((i2) => i2 > -1);
      this.j.setSelection(indexes, browserEvent, true);
    });
  }
  getSelection() {
    return this.w.get();
  }
  setFocus(elements, browserEvent) {
    this.y.bufferEvents(() => {
      const nodes = elements.map((e) => this.o.getNode(e));
      this.q.set(nodes, browserEvent);
      const indexes = elements.map((e) => this.o.getListIndex(e)).filter((i2) => i2 > -1);
      this.j.setFocus(indexes, browserEvent, true);
    });
  }
  focusNext(n = 1, loop = false, browserEvent, filter = $4j(browserEvent) && browserEvent.altKey ? void 0 : this.B) {
    this.j.focusNext(n, loop, browserEvent, filter);
  }
  focusPrevious(n = 1, loop = false, browserEvent, filter = $4j(browserEvent) && browserEvent.altKey ? void 0 : this.B) {
    this.j.focusPrevious(n, loop, browserEvent, filter);
  }
  focusNextPage(browserEvent, filter = $4j(browserEvent) && browserEvent.altKey ? void 0 : this.B) {
    return this.j.focusNextPage(browserEvent, filter);
  }
  focusPreviousPage(browserEvent, filter = $4j(browserEvent) && browserEvent.altKey ? void 0 : this.B) {
    return this.j.focusPreviousPage(browserEvent, filter, () => this.C?.height ?? 0);
  }
  focusLast(browserEvent, filter = $4j(browserEvent) && browserEvent.altKey ? void 0 : this.B) {
    this.j.focusLast(browserEvent, filter);
  }
  focusFirst(browserEvent, filter = $4j(browserEvent) && browserEvent.altKey ? void 0 : this.B) {
    this.j.focusFirst(browserEvent, filter);
  }
  getFocus() {
    return this.q.get();
  }
  getStickyScrollFocus() {
    const focus = this.C?.getFocus();
    return focus !== void 0 ? [focus] : [];
  }
  getFocusedPart() {
    return this.C?.focusedLast() ? 1 : 0;
  }
  reveal(location3, relativeTop) {
    this.o.expandTo(location3);
    const index = this.o.getListIndex(location3);
    if (index === -1) {
      return;
    }
    if (!this.C) {
      this.j.reveal(index, relativeTop);
    } else {
      const paddingTop = this.C.nodePositionTopBelowWidget(this.getNode(location3));
      this.j.reveal(index, relativeTop, paddingTop);
    }
  }
  /**
   * Returns the relative position of an element rendered in the list.
   * Returns `null` if the element isn't *entirely* in the visible viewport.
   */
  getRelativeTop(location3) {
    const index = this.o.getListIndex(location3);
    if (index === -1) {
      return null;
    }
    const stickyScrollNode = this.C?.getNode(this.getNode(location3));
    return this.j.getRelativeTop(index, stickyScrollNode?.position ?? this.C?.height);
  }
  getViewState(identityProvider3 = this.options.identityProvider) {
    if (!identityProvider3) {
      throw new $i3(this.O, "Can't get tree view state without an identity provider");
    }
    const getId2 = (element) => identityProvider3.getId(element).toString();
    const state = $o3.empty(this.scrollTop);
    for (const focus of this.getFocus()) {
      state.focus.add(getId2(focus));
    }
    for (const selection of this.getSelection()) {
      state.selection.add(getId2(selection));
    }
    const root = this.o.getNode();
    const queue = [root];
    while (queue.length > 0) {
      const node = queue.shift();
      if (node !== root && node.collapsible) {
        state.expanded[getId2(node.element)] = node.collapsed ? 0 : 1;
      }
      queue.push(...node.children);
    }
    return state;
  }
  // List
  R(e) {
    e.preventDefault();
    e.stopPropagation();
    const nodes = this.j.getFocusedElements();
    if (nodes.length === 0) {
      return;
    }
    const node = nodes[0];
    const location3 = this.o.getNodeLocation(node);
    const didChange = this.o.setCollapsed(location3, true);
    if (!didChange) {
      const parentLocation = this.o.getParentNodeLocation(location3);
      if (!parentLocation) {
        return;
      }
      const parentListIndex = this.o.getListIndex(parentLocation);
      this.j.reveal(parentListIndex);
      this.j.setFocus([parentListIndex]);
    }
  }
  S(e) {
    e.preventDefault();
    e.stopPropagation();
    const nodes = this.j.getFocusedElements();
    if (nodes.length === 0) {
      return;
    }
    const node = nodes[0];
    const location3 = this.o.getNodeLocation(node);
    const didChange = this.o.setCollapsed(location3, false);
    if (!didChange) {
      if (!node.children.some((child) => child.visible)) {
        return;
      }
      const [focusedIndex] = this.j.getFocus();
      const firstChildIndex = focusedIndex + 1;
      this.j.reveal(firstChildIndex);
      this.j.setFocus([firstChildIndex]);
    }
  }
  U(e) {
    e.preventDefault();
    e.stopPropagation();
    const nodes = this.j.getFocusedElements();
    if (nodes.length === 0) {
      return;
    }
    const node = nodes[0];
    const location3 = this.o.getNodeLocation(node);
    const recursive = e.browserEvent.altKey;
    this.o.setCollapsed(location3, void 0, recursive);
  }
  X(model) {
    this.W.clear();
    this.W.add(model.onDidSpliceRenderedNodes(({ start, deleteCount, elements }) => this.j.splice(start, deleteCount, elements)));
    const onDidModelSplice = Event2.forEach(model.onDidSpliceModel, (e) => {
      this.y.bufferEvents(() => {
        this.q.onDidModelSplice(e);
        this.w.onDidModelSplice(e);
      });
    }, this.W);
    onDidModelSplice(() => null, null, this.W);
    const activeNodesEmitter = this.W.add(new $ze());
    const activeNodesDebounce = this.W.add(new $Sh(0));
    this.W.add(Event2.any(onDidModelSplice, this.q.onDidChange, this.w.onDidChange)(() => {
      activeNodesDebounce.trigger(() => {
        const set = /* @__PURE__ */ new Set();
        for (const node of this.q.getNodes()) {
          set.add(node);
        }
        for (const node of this.w.getNodes()) {
          set.add(node);
        }
        activeNodesEmitter.fire([...set.values()]);
      });
    }));
    this.K.input = activeNodesEmitter.event;
    this.G.input = Event2.signal(model.onDidSpliceModel);
    this.I.input = model.onDidChangeCollapseState;
    this.J.input = model.onDidChangeRenderNodeCount;
    this.H.input = model.onDidSpliceModel;
  }
  navigate(start) {
    return new TreeNavigator(this.j, this.o, start);
  }
  dispose() {
    $Xc(this.E);
    this.C?.dispose();
    this.j.dispose();
    this.W.dispose();
  }
};
var TreeNavigator = class {
  constructor(b, c, start) {
    this.b = b;
    this.c = c;
    if (start) {
      this.a = this.c.getListIndex(start);
    } else {
      this.a = -1;
    }
  }
  current() {
    if (this.a < 0 || this.a >= this.b.length) {
      return null;
    }
    return this.b.element(this.a).element;
  }
  previous() {
    this.a--;
    return this.current();
  }
  next() {
    this.a++;
    return this.current();
  }
  first() {
    this.a = 0;
    return this.current();
  }
  last() {
    this.a = this.b.length - 1;
    return this.current();
  }
};

// out-build/vs/base/browser/ui/tree/objectTreeModel.js
var $w3 = class {
  get size() {
    return this.d.size;
  }
  constructor(k, options3 = {}) {
    this.k = k;
    this.rootRef = null;
    this.d = /* @__PURE__ */ new Map();
    this.f = /* @__PURE__ */ new Map();
    this.c = new $m3(k, null, options3);
    this.onDidSpliceModel = this.c.onDidSpliceModel;
    this.onDidSpliceRenderedNodes = this.c.onDidSpliceRenderedNodes;
    this.onDidChangeCollapseState = this.c.onDidChangeCollapseState;
    this.onDidChangeRenderNodeCount = this.c.onDidChangeRenderNodeCount;
    if (options3.sorter) {
      this.j = {
        compare(a, b) {
          return options3.sorter.compare(a.element, b.element);
        }
      };
    }
    this.h = options3.identityProvider;
  }
  setChildren(element, children = Iterable.empty(), options3 = {}) {
    const location3 = this.o(element);
    this.l(location3, this.m(children), options3);
  }
  l(location3, children = Iterable.empty(), options3) {
    const insertedElements = /* @__PURE__ */ new Set();
    const insertedElementIds = /* @__PURE__ */ new Set();
    const onDidCreateNode = (node) => {
      if (node.element === null) {
        return;
      }
      const tnode = node;
      insertedElements.add(tnode.element);
      this.d.set(tnode.element, tnode);
      if (this.h) {
        const id2 = this.h.getId(tnode.element).toString();
        insertedElementIds.add(id2);
        this.f.set(id2, tnode);
      }
      options3.onDidCreateNode?.(tnode);
    };
    const onDidDeleteNode = (node) => {
      if (node.element === null) {
        return;
      }
      const tnode = node;
      if (!insertedElements.has(tnode.element)) {
        this.d.delete(tnode.element);
      }
      if (this.h) {
        const id2 = this.h.getId(tnode.element).toString();
        if (!insertedElementIds.has(id2)) {
          this.f.delete(id2);
        }
      }
      options3.onDidDeleteNode?.(tnode);
    };
    this.c.splice([...location3, 0], Number.MAX_VALUE, children, { ...options3, onDidCreateNode, onDidDeleteNode });
  }
  m(elements = Iterable.empty()) {
    if (this.j) {
      elements = [...elements].sort(this.j.compare.bind(this.j));
    }
    return Iterable.map(elements, (treeElement) => {
      let node = this.d.get(treeElement.element);
      if (!node && this.h) {
        const id2 = this.h.getId(treeElement.element).toString();
        node = this.f.get(id2);
      }
      if (!node) {
        let collapsed3;
        if (typeof treeElement.collapsed === "undefined") {
          collapsed3 = void 0;
        } else if (treeElement.collapsed === ObjectTreeElementCollapseState.Collapsed || treeElement.collapsed === ObjectTreeElementCollapseState.PreserveOrCollapsed) {
          collapsed3 = true;
        } else if (treeElement.collapsed === ObjectTreeElementCollapseState.Expanded || treeElement.collapsed === ObjectTreeElementCollapseState.PreserveOrExpanded) {
          collapsed3 = false;
        } else {
          collapsed3 = Boolean(treeElement.collapsed);
        }
        return {
          ...treeElement,
          children: this.m(treeElement.children),
          collapsed: collapsed3
        };
      }
      const collapsible = typeof treeElement.collapsible === "boolean" ? treeElement.collapsible : node.collapsible;
      let collapsed2;
      if (typeof treeElement.collapsed === "undefined" || treeElement.collapsed === ObjectTreeElementCollapseState.PreserveOrCollapsed || treeElement.collapsed === ObjectTreeElementCollapseState.PreserveOrExpanded) {
        collapsed2 = node.collapsed;
      } else if (treeElement.collapsed === ObjectTreeElementCollapseState.Collapsed) {
        collapsed2 = true;
      } else if (treeElement.collapsed === ObjectTreeElementCollapseState.Expanded) {
        collapsed2 = false;
      } else {
        collapsed2 = Boolean(treeElement.collapsed);
      }
      return {
        ...treeElement,
        collapsible,
        collapsed: collapsed2,
        children: this.m(treeElement.children)
      };
    });
  }
  rerender(element) {
    const location3 = this.o(element);
    this.c.rerender(location3);
  }
  resort(element = null, recursive = true) {
    if (!this.j) {
      return;
    }
    const location3 = this.o(element);
    const node = this.c.getNode(location3);
    this.l(location3, this.n(node, recursive), {});
  }
  n(node, recursive, first = true) {
    let childrenNodes = [...node.children];
    if (recursive || first) {
      childrenNodes = childrenNodes.sort(this.j.compare.bind(this.j));
    }
    return Iterable.map(childrenNodes, (node2) => ({
      element: node2.element,
      collapsible: node2.collapsible,
      collapsed: node2.collapsed,
      children: this.n(node2, recursive, false)
    }));
  }
  getFirstElementChild(ref = null) {
    const location3 = this.o(ref);
    return this.c.getFirstElementChild(location3);
  }
  getLastElementAncestor(ref = null) {
    const location3 = this.o(ref);
    return this.c.getLastElementAncestor(location3);
  }
  has(element) {
    return this.d.has(element);
  }
  getListIndex(element) {
    const location3 = this.o(element);
    return this.c.getListIndex(location3);
  }
  getListRenderCount(element) {
    const location3 = this.o(element);
    return this.c.getListRenderCount(location3);
  }
  isCollapsible(element) {
    const location3 = this.o(element);
    return this.c.isCollapsible(location3);
  }
  setCollapsible(element, collapsible) {
    const location3 = this.o(element);
    return this.c.setCollapsible(location3, collapsible);
  }
  isCollapsed(element) {
    const location3 = this.o(element);
    return this.c.isCollapsed(location3);
  }
  setCollapsed(element, collapsed2, recursive) {
    const location3 = this.o(element);
    return this.c.setCollapsed(location3, collapsed2, recursive);
  }
  expandTo(element) {
    const location3 = this.o(element);
    this.c.expandTo(location3);
  }
  refilter() {
    this.c.refilter();
  }
  getNode(element = null) {
    if (element === null) {
      return this.c.getNode(this.c.rootRef);
    }
    const node = this.d.get(element);
    if (!node) {
      throw new $i3(this.k, `Tree element not found: ${element}`);
    }
    return node;
  }
  getNodeLocation(node) {
    return node.element;
  }
  getParentNodeLocation(element) {
    if (element === null) {
      throw new $i3(this.k, `Invalid getParentNodeLocation call`);
    }
    const node = this.d.get(element);
    if (!node) {
      throw new $i3(this.k, `Tree element not found: ${element}`);
    }
    const location3 = this.c.getNodeLocation(node);
    const parentLocation = this.c.getParentNodeLocation(location3);
    const parent = this.c.getNode(parentLocation);
    return parent.element;
  }
  o(element) {
    if (element === null) {
      return [];
    }
    const node = this.d.get(element);
    if (!node) {
      throw new $i3(this.k, `Tree element not found: ${element}`);
    }
    return this.c.getNodeLocation(node);
  }
};

// out-build/vs/base/browser/ui/tree/compressedObjectTreeModel.js
function noCompress(element) {
  const elements = [element.element];
  const incompressible = element.incompressible || false;
  return {
    element: { elements, incompressible },
    children: Iterable.map(Iterable.from(element.children), noCompress),
    collapsible: element.collapsible,
    collapsed: element.collapsed
  };
}
function $x3(element) {
  const elements = [element.element];
  const incompressible = element.incompressible || false;
  let childrenIterator;
  let children;
  while (true) {
    [children, childrenIterator] = Iterable.consume(Iterable.from(element.children), 2);
    if (children.length !== 1) {
      break;
    }
    if (children[0].incompressible) {
      break;
    }
    element = children[0];
    elements.push(element.element);
  }
  return {
    element: { elements, incompressible },
    children: Iterable.map(Iterable.concat(children, childrenIterator), $x3),
    collapsible: element.collapsible,
    collapsed: element.collapsed
  };
}
function _decompress(element, index = 0) {
  let children;
  if (index < element.element.elements.length - 1) {
    children = [_decompress(element, index + 1)];
  } else {
    children = Iterable.map(Iterable.from(element.children), (el) => _decompress(el, 0));
  }
  if (index === 0 && element.element.incompressible) {
    return {
      element: element.element.elements[index],
      children,
      incompressible: true,
      collapsible: element.collapsible,
      collapsed: element.collapsed
    };
  }
  return {
    element: element.element.elements[index],
    children,
    collapsible: element.collapsible,
    collapsed: element.collapsed
  };
}
function $y3(element) {
  return _decompress(element, 0);
}
function splice(treeElement, element, children) {
  if (treeElement.element === element) {
    return { ...treeElement, children };
  }
  return { ...treeElement, children: Iterable.map(Iterable.from(treeElement.children), (e) => splice(e, element, children)) };
}
var wrapIdentityProvider = (base) => ({
  getId(node) {
    return node.elements.map((e) => base.getId(e).toString()).join("\0");
  }
});
var $z3 = class {
  get onDidSpliceRenderedNodes() {
    return this.c.onDidSpliceRenderedNodes;
  }
  get onDidSpliceModel() {
    return this.c.onDidSpliceModel;
  }
  get onDidChangeCollapseState() {
    return this.c.onDidChangeCollapseState;
  }
  get onDidChangeRenderNodeCount() {
    return this.c.onDidChangeRenderNodeCount;
  }
  get size() {
    return this.d.size;
  }
  constructor(h3, options3 = {}) {
    this.h = h3;
    this.rootRef = null;
    this.d = /* @__PURE__ */ new Map();
    this.c = new $w3(h3, options3);
    this.f = typeof options3.compressionEnabled === "undefined" ? true : options3.compressionEnabled;
    this.g = options3.identityProvider;
  }
  setChildren(element, children = Iterable.empty(), options3) {
    const diffIdentityProvider = options3.diffIdentityProvider && wrapIdentityProvider(options3.diffIdentityProvider);
    if (element === null) {
      const compressedChildren = Iterable.map(children, this.f ? $x3 : noCompress);
      this.j(null, compressedChildren, { diffIdentityProvider, diffDepth: Infinity });
      return;
    }
    const compressedNode = this.d.get(element);
    if (!compressedNode) {
      throw new $i3(this.h, "Unknown compressed tree node");
    }
    const node = this.c.getNode(compressedNode);
    const compressedParentNode = this.c.getParentNodeLocation(compressedNode);
    const parent = this.c.getNode(compressedParentNode);
    const decompressedElement = $y3(node);
    const splicedElement = splice(decompressedElement, element, children);
    const recompressedElement = (this.f ? $x3 : noCompress)(splicedElement);
    const elementComparator = options3.diffIdentityProvider ? (a, b) => options3.diffIdentityProvider.getId(a) === options3.diffIdentityProvider.getId(b) : void 0;
    if ($zb(recompressedElement.element.elements, node.element.elements, elementComparator)) {
      this.j(compressedNode, recompressedElement.children || Iterable.empty(), { diffIdentityProvider, diffDepth: 1 });
      return;
    }
    const parentChildren = parent.children.map((child) => child === node ? recompressedElement : child);
    this.j(parent.element, parentChildren, {
      diffIdentityProvider,
      diffDepth: node.depth - parent.depth
    });
  }
  isCompressionEnabled() {
    return this.f;
  }
  setCompressionEnabled(enabled) {
    if (enabled === this.f) {
      return;
    }
    this.f = enabled;
    const root = this.c.getNode();
    const rootChildren = root.children;
    const decompressedRootChildren = Iterable.map(rootChildren, $y3);
    const recompressedRootChildren = Iterable.map(decompressedRootChildren, enabled ? $x3 : noCompress);
    this.j(null, recompressedRootChildren, {
      diffIdentityProvider: this.g,
      diffDepth: Infinity
    });
  }
  j(node, children, options3) {
    const insertedElements = /* @__PURE__ */ new Set();
    const onDidCreateNode = (node2) => {
      for (const element of node2.element.elements) {
        insertedElements.add(element);
        this.d.set(element, node2.element);
      }
    };
    const onDidDeleteNode = (node2) => {
      for (const element of node2.element.elements) {
        if (!insertedElements.has(element)) {
          this.d.delete(element);
        }
      }
    };
    this.c.setChildren(node, children, { ...options3, onDidCreateNode, onDidDeleteNode });
  }
  has(element) {
    return this.d.has(element);
  }
  getListIndex(location3) {
    const node = this.getCompressedNode(location3);
    return this.c.getListIndex(node);
  }
  getListRenderCount(location3) {
    const node = this.getCompressedNode(location3);
    return this.c.getListRenderCount(node);
  }
  getNode(location3) {
    if (typeof location3 === "undefined") {
      return this.c.getNode();
    }
    const node = this.getCompressedNode(location3);
    return this.c.getNode(node);
  }
  // TODO: review this
  getNodeLocation(node) {
    const compressedNode = this.c.getNodeLocation(node);
    if (compressedNode === null) {
      return null;
    }
    return compressedNode.elements[compressedNode.elements.length - 1];
  }
  // TODO: review this
  getParentNodeLocation(location3) {
    const compressedNode = this.getCompressedNode(location3);
    const parentNode = this.c.getParentNodeLocation(compressedNode);
    if (parentNode === null) {
      return null;
    }
    return parentNode.elements[parentNode.elements.length - 1];
  }
  getFirstElementChild(location3) {
    const compressedNode = this.getCompressedNode(location3);
    return this.c.getFirstElementChild(compressedNode);
  }
  getLastElementAncestor(location3) {
    const compressedNode = typeof location3 === "undefined" ? void 0 : this.getCompressedNode(location3);
    return this.c.getLastElementAncestor(compressedNode);
  }
  isCollapsible(location3) {
    const compressedNode = this.getCompressedNode(location3);
    return this.c.isCollapsible(compressedNode);
  }
  setCollapsible(location3, collapsible) {
    const compressedNode = this.getCompressedNode(location3);
    return this.c.setCollapsible(compressedNode, collapsible);
  }
  isCollapsed(location3) {
    const compressedNode = this.getCompressedNode(location3);
    return this.c.isCollapsed(compressedNode);
  }
  setCollapsed(location3, collapsed2, recursive) {
    const compressedNode = this.getCompressedNode(location3);
    return this.c.setCollapsed(compressedNode, collapsed2, recursive);
  }
  expandTo(location3) {
    const compressedNode = this.getCompressedNode(location3);
    this.c.expandTo(compressedNode);
  }
  rerender(location3) {
    const compressedNode = this.getCompressedNode(location3);
    this.c.rerender(compressedNode);
  }
  refilter() {
    this.c.refilter();
  }
  resort(location3 = null, recursive = true) {
    const compressedNode = this.getCompressedNode(location3);
    this.c.resort(compressedNode, recursive);
  }
  getCompressedNode(element) {
    if (element === null) {
      return null;
    }
    const node = this.d.get(element);
    if (!node) {
      throw new $i3(this.h, `Tree element not found: ${element}`);
    }
    return node;
  }
};
var $A3 = (elements) => elements[elements.length - 1];
var CompressedTreeNodeWrapper = class _CompressedTreeNodeWrapper {
  get element() {
    return this.d.element === null ? null : this.c(this.d.element);
  }
  get children() {
    return this.d.children.map((node) => new _CompressedTreeNodeWrapper(this.c, node));
  }
  get depth() {
    return this.d.depth;
  }
  get visibleChildrenCount() {
    return this.d.visibleChildrenCount;
  }
  get visibleChildIndex() {
    return this.d.visibleChildIndex;
  }
  get collapsible() {
    return this.d.collapsible;
  }
  get collapsed() {
    return this.d.collapsed;
  }
  get visible() {
    return this.d.visible;
  }
  get filterData() {
    return this.d.filterData;
  }
  constructor(c, d) {
    this.c = c;
    this.d = d;
  }
};
function mapOptions(compressedNodeUnwrapper, options3) {
  return {
    ...options3,
    identityProvider: options3.identityProvider && {
      getId(node) {
        return options3.identityProvider.getId(compressedNodeUnwrapper(node));
      }
    },
    sorter: options3.sorter && {
      compare(node, otherNode) {
        return options3.sorter.compare(node.elements[0], otherNode.elements[0]);
      }
    },
    filter: options3.filter && {
      filter(node, parentVisibility) {
        const elements = node.elements;
        for (let i2 = 0; i2 < elements.length - 1; i2++) {
          const result = options3.filter.filter(elements[i2], parentVisibility);
          parentVisibility = $l3($k3(result) ? result.visibility : result);
        }
        return options3.filter.filter(elements[elements.length - 1], parentVisibility);
      }
    }
  };
}
var $B3 = class {
  get onDidSpliceModel() {
    return Event2.map(this.f.onDidSpliceModel, ({ insertedNodes, deletedNodes }) => ({
      insertedNodes: insertedNodes.map((node) => this.d.map(node)),
      deletedNodes: deletedNodes.map((node) => this.d.map(node))
    }));
  }
  get onDidSpliceRenderedNodes() {
    return Event2.map(this.f.onDidSpliceRenderedNodes, ({ start, deleteCount, elements }) => ({
      start,
      deleteCount,
      elements: elements.map((node) => this.d.map(node))
    }));
  }
  get onDidChangeCollapseState() {
    return Event2.map(this.f.onDidChangeCollapseState, ({ node, deep }) => ({
      node: this.d.map(node),
      deep
    }));
  }
  get onDidChangeRenderNodeCount() {
    return Event2.map(this.f.onDidChangeRenderNodeCount, (node) => this.d.map(node));
  }
  constructor(user, options3 = {}) {
    this.rootRef = null;
    this.c = options3.elementMapper || $A3;
    const compressedNodeUnwrapper = (node) => this.c(node.elements);
    this.d = new $j3((node) => new CompressedTreeNodeWrapper(compressedNodeUnwrapper, node));
    this.f = new $z3(user, mapOptions(compressedNodeUnwrapper, options3));
  }
  setChildren(element, children = Iterable.empty(), options3 = {}) {
    this.f.setChildren(element, children, options3);
  }
  isCompressionEnabled() {
    return this.f.isCompressionEnabled();
  }
  setCompressionEnabled(enabled) {
    this.f.setCompressionEnabled(enabled);
  }
  has(location3) {
    return this.f.has(location3);
  }
  getListIndex(location3) {
    return this.f.getListIndex(location3);
  }
  getListRenderCount(location3) {
    return this.f.getListRenderCount(location3);
  }
  getNode(location3) {
    return this.d.map(this.f.getNode(location3));
  }
  getNodeLocation(node) {
    return node.element;
  }
  getParentNodeLocation(location3) {
    return this.f.getParentNodeLocation(location3);
  }
  getFirstElementChild(location3) {
    const result = this.f.getFirstElementChild(location3);
    if (result === null || typeof result === "undefined") {
      return result;
    }
    return this.c(result.elements);
  }
  getLastElementAncestor(location3) {
    const result = this.f.getLastElementAncestor(location3);
    if (result === null || typeof result === "undefined") {
      return result;
    }
    return this.c(result.elements);
  }
  isCollapsible(location3) {
    return this.f.isCollapsible(location3);
  }
  setCollapsible(location3, collapsed2) {
    return this.f.setCollapsible(location3, collapsed2);
  }
  isCollapsed(location3) {
    return this.f.isCollapsed(location3);
  }
  setCollapsed(location3, collapsed2, recursive) {
    return this.f.setCollapsed(location3, collapsed2, recursive);
  }
  expandTo(location3) {
    return this.f.expandTo(location3);
  }
  rerender(location3) {
    return this.f.rerender(location3);
  }
  refilter() {
    return this.f.refilter();
  }
  resort(element = null, recursive = true) {
    return this.f.resort(element, recursive);
  }
  getCompressedTreeNode(location3 = null) {
    return this.f.getNode(location3);
  }
};

// out-build/vs/base/browser/ui/tree/objectTree.js
var $C3 = class extends $v3 {
  get onDidChangeCollapseState() {
    return this.o.onDidChangeCollapseState;
  }
  constructor(Z, container2, delegate, renderers, options3 = {}) {
    super(Z, container2, delegate, renderers, options3);
    this.Z = Z;
  }
  setChildren(element, children = Iterable.empty(), options3) {
    this.o.setChildren(element, children, options3);
  }
  rerender(element) {
    if (element === void 0) {
      this.j.rerender();
      return;
    }
    this.o.rerender(element);
  }
  updateElementHeight(element, height) {
    const elementIndex = this.o.getListIndex(element);
    if (elementIndex === -1) {
      return;
    }
    this.j.updateElementHeight(elementIndex, height);
  }
  resort(element, recursive = true) {
    this.o.resort(element, recursive);
  }
  hasElement(element) {
    return this.o.has(element);
  }
  V(user, options3) {
    return new $w3(user, options3);
  }
};
var CompressibleRenderer = class {
  get a() {
    return this.b();
  }
  constructor(b, c, d) {
    this.b = b;
    this.c = c;
    this.d = d;
    this.templateId = d.templateId;
    if (d.onDidChangeTwistieState) {
      this.onDidChangeTwistieState = d.onDidChangeTwistieState;
    }
  }
  renderTemplate(container2) {
    const data = this.d.renderTemplate(container2);
    return { compressedTreeNode: void 0, data };
  }
  renderElement(node, index, templateData, height) {
    let compressedTreeNode = this.c.getCompressedNode(node);
    if (!compressedTreeNode) {
      compressedTreeNode = this.a.getCompressedTreeNode(node.element);
    }
    if (compressedTreeNode.element.elements.length === 1) {
      templateData.compressedTreeNode = void 0;
      this.d.renderElement(node, index, templateData.data, height);
    } else {
      templateData.compressedTreeNode = compressedTreeNode;
      this.d.renderCompressedElements(compressedTreeNode, index, templateData.data, height);
    }
  }
  disposeElement(node, index, templateData, height) {
    if (templateData.compressedTreeNode) {
      this.d.disposeCompressedElements?.(templateData.compressedTreeNode, index, templateData.data, height);
    } else {
      this.d.disposeElement?.(node, index, templateData.data, height);
    }
  }
  disposeTemplate(templateData) {
    this.d.disposeTemplate(templateData.data);
  }
  renderTwistie(element, twistieElement) {
    if (this.d.renderTwistie) {
      return this.d.renderTwistie(element, twistieElement);
    }
    return false;
  }
};
__decorate([
  $0t
], CompressibleRenderer.prototype, "a", null);
var CompressibleStickyScrollDelegate = class {
  constructor(b) {
    this.b = b;
    this.a = /* @__PURE__ */ new Map();
  }
  getCompressedNode(node) {
    return this.a.get(node);
  }
  constrainStickyScrollNodes(stickyNodes, stickyScrollMaxItemCount, maxWidgetHeight) {
    this.a.clear();
    if (stickyNodes.length === 0) {
      return [];
    }
    for (let i2 = 0; i2 < stickyNodes.length; i2++) {
      const stickyNode = stickyNodes[i2];
      const stickyNodeBottom = stickyNode.position + stickyNode.height;
      const followingReachesMaxHeight = i2 + 1 < stickyNodes.length && stickyNodeBottom + stickyNodes[i2 + 1].height > maxWidgetHeight;
      if (followingReachesMaxHeight || i2 >= stickyScrollMaxItemCount - 1 && stickyScrollMaxItemCount < stickyNodes.length) {
        const uncompressedStickyNodes = stickyNodes.slice(0, i2);
        const overflowingStickyNodes = stickyNodes.slice(i2);
        const compressedStickyNode = this.c(overflowingStickyNodes);
        return [...uncompressedStickyNodes, compressedStickyNode];
      }
    }
    return stickyNodes;
  }
  c(stickyNodes) {
    if (stickyNodes.length === 0) {
      throw new Error("Can't compress empty sticky nodes");
    }
    const compressionModel = this.b();
    if (!compressionModel.isCompressionEnabled()) {
      return stickyNodes[0];
    }
    const elements = [];
    for (let i2 = 0; i2 < stickyNodes.length; i2++) {
      const stickyNode = stickyNodes[i2];
      const compressedNode2 = compressionModel.getCompressedTreeNode(stickyNode.node.element);
      if (compressedNode2.element) {
        if (i2 !== 0 && compressedNode2.element.incompressible) {
          break;
        }
        elements.push(...compressedNode2.element.elements);
      }
    }
    if (elements.length < 2) {
      return stickyNodes[0];
    }
    const lastStickyNode = stickyNodes[stickyNodes.length - 1];
    const compressedElement = { elements, incompressible: false };
    const compressedNode = { ...lastStickyNode.node, children: [], element: compressedElement };
    const stickyTreeNode = new Proxy(stickyNodes[0].node, {});
    const compressedStickyNode = {
      node: stickyTreeNode,
      startIndex: stickyNodes[0].startIndex,
      endIndex: lastStickyNode.endIndex,
      position: stickyNodes[0].position,
      height: stickyNodes[0].height
    };
    this.a.set(stickyTreeNode, compressedNode);
    return compressedStickyNode;
  }
};
function asObjectTreeOptions(compressedTreeNodeProvider, options3) {
  return options3 && {
    ...options3,
    keyboardNavigationLabelProvider: options3.keyboardNavigationLabelProvider && {
      getKeyboardNavigationLabel(e) {
        let compressedTreeNode;
        try {
          compressedTreeNode = compressedTreeNodeProvider().getCompressedTreeNode(e);
        } catch {
          return options3.keyboardNavigationLabelProvider.getKeyboardNavigationLabel(e);
        }
        if (compressedTreeNode.element.elements.length === 1) {
          return options3.keyboardNavigationLabelProvider.getKeyboardNavigationLabel(e);
        } else {
          return options3.keyboardNavigationLabelProvider.getCompressedNodeKeyboardNavigationLabel(compressedTreeNode.element.elements);
        }
      }
    }
  };
}
var $D3 = class extends $C3 {
  constructor(user, container2, delegate, renderers, options3 = {}) {
    const compressedTreeNodeProvider = () => this;
    const stickyScrollDelegate = new CompressibleStickyScrollDelegate(() => this.o);
    const compressibleRenderers = renderers.map((r2) => new CompressibleRenderer(compressedTreeNodeProvider, stickyScrollDelegate, r2));
    super(user, container2, delegate, compressibleRenderers, { ...asObjectTreeOptions(compressedTreeNodeProvider, options3), stickyScrollDelegate });
  }
  setChildren(element, children = Iterable.empty(), options3) {
    this.o.setChildren(element, children, options3);
  }
  V(user, options3) {
    return new $B3(user, options3);
  }
  updateOptions(optionsUpdate = {}) {
    super.updateOptions(optionsUpdate);
    if (typeof optionsUpdate.compressionEnabled !== "undefined") {
      this.o.setCompressionEnabled(optionsUpdate.compressionEnabled);
    }
  }
  getCompressedTreeNode(element = null) {
    return this.o.getCompressedTreeNode(element);
  }
};

// out-build/vs/base/browser/ui/tree/asyncDataTree.js
function createAsyncDataTreeNode(props) {
  return {
    ...props,
    children: [],
    refreshPromise: void 0,
    stale: true,
    slow: false,
    forceExpanded: false
  };
}
function isAncestor(ancestor, descendant) {
  if (!descendant.parent) {
    return false;
  } else if (descendant.parent === ancestor) {
    return true;
  } else {
    return isAncestor(ancestor, descendant.parent);
  }
}
function intersects(node, other) {
  return node === other || isAncestor(node, other) || isAncestor(other, node);
}
var AsyncDataTreeNodeWrapper = class _AsyncDataTreeNodeWrapper {
  get element() {
    return this.a.element.element;
  }
  get children() {
    return this.a.children.map((node) => new _AsyncDataTreeNodeWrapper(node));
  }
  get depth() {
    return this.a.depth;
  }
  get visibleChildrenCount() {
    return this.a.visibleChildrenCount;
  }
  get visibleChildIndex() {
    return this.a.visibleChildIndex;
  }
  get collapsible() {
    return this.a.collapsible;
  }
  get collapsed() {
    return this.a.collapsed;
  }
  get visible() {
    return this.a.visible;
  }
  get filterData() {
    return this.a.filterData;
  }
  constructor(a) {
    this.a = a;
  }
};
var AsyncDataTreeRenderer = class {
  constructor(b, d, onDidChangeTwistieState) {
    this.b = b;
    this.d = d;
    this.onDidChangeTwistieState = onDidChangeTwistieState;
    this.a = /* @__PURE__ */ new Map();
    this.templateId = b.templateId;
  }
  renderTemplate(container2) {
    const templateData = this.b.renderTemplate(container2);
    return { templateData };
  }
  renderElement(node, index, templateData, height) {
    this.b.renderElement(this.d.map(node), index, templateData.templateData, height);
  }
  renderTwistie(element, twistieElement) {
    if (element.slow) {
      twistieElement.classList.add(...ThemeIcon.asClassNameArray($6l.treeItemLoading));
      return true;
    } else {
      twistieElement.classList.remove(...ThemeIcon.asClassNameArray($6l.treeItemLoading));
      return false;
    }
  }
  disposeElement(node, index, templateData, height) {
    this.b.disposeElement?.(this.d.map(node), index, templateData.templateData, height);
  }
  disposeTemplate(templateData) {
    this.b.disposeTemplate(templateData.templateData);
  }
  dispose() {
    this.a.clear();
  }
};
function asTreeEvent(e) {
  return {
    browserEvent: e.browserEvent,
    elements: e.elements.map((e2) => e2.element)
  };
}
function asTreeMouseEvent2(e) {
  return {
    browserEvent: e.browserEvent,
    element: e.element && e.element.element,
    target: e.target
  };
}
function asTreeContextMenuEvent2(e) {
  return {
    browserEvent: e.browserEvent,
    element: e.element && e.element.element,
    anchor: e.anchor,
    isStickyScroll: e.isStickyScroll
  };
}
var AsyncDataTreeElementsDragAndDropData = class extends $g1 {
  set context(context) {
    this.f.context = context;
  }
  get context() {
    return this.f.context;
  }
  constructor(f) {
    super(f.elements.map((node) => node.element));
    this.f = f;
  }
};
function asAsyncDataTreeDragAndDropData(data) {
  if (data instanceof $g1) {
    return new AsyncDataTreeElementsDragAndDropData(data);
  }
  return data;
}
var AsyncDataTreeNodeListDragAndDrop = class {
  constructor(a) {
    this.a = a;
  }
  getDragURI(node) {
    return this.a.getDragURI(node.element);
  }
  getDragLabel(nodes, originalEvent) {
    if (this.a.getDragLabel) {
      return this.a.getDragLabel(nodes.map((node) => node.element), originalEvent);
    }
    return void 0;
  }
  onDragStart(data, originalEvent) {
    this.a.onDragStart?.(asAsyncDataTreeDragAndDropData(data), originalEvent);
  }
  onDragOver(data, targetNode, targetIndex, targetSector, originalEvent, raw = true) {
    return this.a.onDragOver(asAsyncDataTreeDragAndDropData(data), targetNode && targetNode.element, targetIndex, targetSector, originalEvent);
  }
  drop(data, targetNode, targetIndex, targetSector, originalEvent) {
    this.a.drop(asAsyncDataTreeDragAndDropData(data), targetNode && targetNode.element, targetIndex, targetSector, originalEvent);
  }
  onDragEnd(originalEvent) {
    this.a.onDragEnd?.(originalEvent);
  }
  dispose() {
    this.a.dispose();
  }
};
var AsyncFindFilter = class extends $r3 {
  constructor(findProvider, keyboardNavigationLabelProvider, filter) {
    super(keyboardNavigationLabelProvider, filter);
    this.findProvider = findProvider;
    this.isFindSessionActive = false;
  }
  filter(element, parentVisibility) {
    const filterResult = super.filter(element, parentVisibility);
    if (!this.isFindSessionActive || this.findMode === TreeFindMode.Highlight || !this.findProvider.isVisible) {
      return filterResult;
    }
    const visibility = $k3(filterResult) ? filterResult.visibility : filterResult;
    if ($l3(visibility) === 0) {
      return 0;
    }
    return this.findProvider.isVisible(element) ? filterResult : 0;
  }
};
var AsyncFindController = class extends $u3 {
  constructor(tree, O, t, contextViewProvider, options3) {
    super(tree, t, contextViewProvider, options3);
    this.O = O;
    this.t = t;
    this.K = false;
    this.L = false;
    this.M = new $Th(250);
    this.q.add($1c(async () => {
      if (this.K) {
        await this.O.endSession?.();
      }
    }));
  }
  x(_pattern) {
    this.A(false);
    this.I?.cancel();
    this.I = new $ad();
    this.M.trigger(() => this.R());
  }
  async R() {
    const token = this.I?.token;
    if (!token || token.isCancellationRequested) {
      return;
    }
    const pattern = this.pattern;
    if (pattern === "") {
      if (this.K) {
        this.L = true;
        await this.U();
        this.L = false;
        if (!token.isCancellationRequested) {
          this.t.reset();
          super.x("");
        }
      }
      return;
    }
    if (!this.K) {
      this.S();
    }
    this.L = true;
    this.J = void 0;
    const findMetadata = await this.O.find(pattern, { matchType: this.matchType, findMode: this.mode }, token);
    if (token.isCancellationRequested || findMetadata === void 0) {
      return;
    }
    this.L = false;
    this.J = findMetadata;
    this.t.reset();
    super.x(pattern);
    if (findMetadata.warningMessage) {
      this.A(true, findMetadata.warningMessage);
    }
  }
  S() {
    this.K = true;
    this.t.isFindSessionActive = true;
    this.O.startSession?.();
  }
  async U() {
    this.K = false;
    this.t.isFindSessionActive = false;
    await this.O.endSession?.();
  }
  H() {
    if (this.L || !this.J) {
      return;
    }
    const showNotFound = this.J.matchCount === 0 && this.pattern.length > 0;
    this.A(showNotFound);
    if (this.pattern.length) {
      this.B(this.J.matchCount);
    }
  }
  y(e) {
    this.f.set(e.id, e.isChecked);
    this.t.findMode = this.mode;
    this.t.findMatchType = this.matchType;
    this.j = this.mode === TreeFindMode.Filter ? localize(41, null) : localize(42, null);
    this.x(this.pattern);
  }
  shouldAllowFocus(node) {
    return this.shouldFocusWhenNavigating(node);
  }
  shouldFocusWhenNavigating(node) {
    if (!this.K || !this.J) {
      return true;
    }
    const element = node.element?.element;
    if (element && this.J.isMatch(element)) {
      return true;
    }
    return !FuzzyScore.isDefault(node.filterData);
  }
};
function asObjectTreeOptions2(options3) {
  return options3 && {
    ...options3,
    collapseByDefault: true,
    identityProvider: options3.identityProvider && {
      getId(el) {
        return options3.identityProvider.getId(el.element);
      }
    },
    dnd: options3.dnd && new AsyncDataTreeNodeListDragAndDrop(options3.dnd),
    multipleSelectionController: options3.multipleSelectionController && {
      isSelectionSingleChangeEvent(e) {
        return options3.multipleSelectionController.isSelectionSingleChangeEvent({ ...e, element: e.element });
      },
      isSelectionRangeChangeEvent(e) {
        return options3.multipleSelectionController.isSelectionRangeChangeEvent({ ...e, element: e.element });
      }
    },
    accessibilityProvider: options3.accessibilityProvider && {
      ...options3.accessibilityProvider,
      getPosInSet: void 0,
      getSetSize: void 0,
      getRole: options3.accessibilityProvider.getRole ? (el) => {
        return options3.accessibilityProvider.getRole(el.element);
      } : () => "treeitem",
      isChecked: options3.accessibilityProvider.isChecked ? (e) => {
        return !!options3.accessibilityProvider?.isChecked(e.element);
      } : void 0,
      getAriaLabel(e) {
        return options3.accessibilityProvider.getAriaLabel(e.element);
      },
      getWidgetAriaLabel() {
        return options3.accessibilityProvider.getWidgetAriaLabel();
      },
      getWidgetRole: options3.accessibilityProvider.getWidgetRole ? () => options3.accessibilityProvider.getWidgetRole() : () => "tree",
      getAriaLevel: options3.accessibilityProvider.getAriaLevel && ((node) => {
        return options3.accessibilityProvider.getAriaLevel(node.element);
      }),
      getActiveDescendantId: options3.accessibilityProvider.getActiveDescendantId && ((node) => {
        return options3.accessibilityProvider.getActiveDescendantId(node.element);
      })
    },
    filter: options3.filter && {
      filter(e, parentVisibility) {
        return options3.filter.filter(e.element, parentVisibility);
      }
    },
    keyboardNavigationLabelProvider: options3.keyboardNavigationLabelProvider && {
      ...options3.keyboardNavigationLabelProvider,
      getKeyboardNavigationLabel(e) {
        return options3.keyboardNavigationLabelProvider.getKeyboardNavigationLabel(e.element);
      }
    },
    sorter: void 0,
    expandOnlyOnTwistieClick: typeof options3.expandOnlyOnTwistieClick === "undefined" ? void 0 : typeof options3.expandOnlyOnTwistieClick !== "function" ? options3.expandOnlyOnTwistieClick : (e) => options3.expandOnlyOnTwistieClick(e.element),
    defaultFindVisibility: (e) => {
      if (e.hasChildren && e.stale) {
        return 1;
      } else if (typeof options3.defaultFindVisibility === "number") {
        return options3.defaultFindVisibility;
      } else if (typeof options3.defaultFindVisibility === "undefined") {
        return 2;
      } else {
        return options3.defaultFindVisibility(e.element);
      }
    }
  };
}
function dfs2(node, fn) {
  fn(node);
  node.children.forEach((child) => dfs2(child, fn));
}
var $E3 = class {
  get onDidScroll() {
    return this.b.onDidScroll;
  }
  get onDidChangeFocus() {
    return Event2.map(this.b.onDidChangeFocus, asTreeEvent);
  }
  get onDidChangeSelection() {
    return Event2.map(this.b.onDidChangeSelection, asTreeEvent);
  }
  get onKeyDown() {
    return this.b.onKeyDown;
  }
  get onMouseClick() {
    return Event2.map(this.b.onMouseClick, asTreeMouseEvent2);
  }
  get onMouseDblClick() {
    return Event2.map(this.b.onMouseDblClick, asTreeMouseEvent2);
  }
  get onContextMenu() {
    return Event2.map(this.b.onContextMenu, asTreeContextMenuEvent2);
  }
  get onTap() {
    return Event2.map(this.b.onTap, asTreeMouseEvent2);
  }
  get onPointer() {
    return Event2.map(this.b.onPointer, asTreeMouseEvent2);
  }
  get onDidFocus() {
    return this.b.onDidFocus;
  }
  get onDidBlur() {
    return this.b.onDidBlur;
  }
  /**
   * To be used internally only!
   * @deprecated
   */
  get onDidChangeModel() {
    return this.b.onDidChangeModel;
  }
  get onDidChangeCollapseState() {
    return this.b.onDidChangeCollapseState;
  }
  get onDidUpdateOptions() {
    return this.b.onDidUpdateOptions;
  }
  get onDidChangeStickyScrollFocused() {
    return this.b.onDidChangeStickyScrollFocused;
  }
  get findMode() {
    return this.h ? this.h.mode : this.b.findMode;
  }
  set findMode(mode) {
    this.h ? this.h.mode = mode : this.b.findMode = mode;
  }
  get findMatchType() {
    return this.h ? this.h.matchType : this.b.findMatchType;
  }
  set findMatchType(matchType) {
    this.h ? this.h.matchType = matchType : this.b.findMatchType = matchType;
  }
  get expandOnlyOnTwistieClick() {
    if (typeof this.b.expandOnlyOnTwistieClick === "boolean") {
      return this.b.expandOnlyOnTwistieClick;
    }
    const fn = this.b.expandOnlyOnTwistieClick;
    return (element) => fn(this.f.get(element === this.d.element ? null : element) || null);
  }
  get onDidDispose() {
    return this.b.onDidDispose;
  }
  constructor(z, container2, delegate, renderers, A, options3 = {}) {
    this.z = z;
    this.A = A;
    this.f = /* @__PURE__ */ new Map();
    this.k = /* @__PURE__ */ new Map();
    this.m = /* @__PURE__ */ new Map();
    this.q = new $ze();
    this.t = new $ze();
    this.u = new $j3((node) => new AsyncDataTreeNodeWrapper(node));
    this.w = new $2c();
    this.o = options3.identityProvider;
    this.p = typeof options3.autoExpandSingleChildren === "undefined" ? false : options3.autoExpandSingleChildren;
    this.g = options3.sorter;
    this.j = (e) => options3.collapseByDefault ? options3.collapseByDefault(e) ? ObjectTreeElementCollapseState.PreserveOrCollapsed : ObjectTreeElementCollapseState.PreserveOrExpanded : void 0;
    let asyncFindEnabled = false;
    let findFilter;
    if (options3.findProvider && (options3.findWidgetEnabled ?? true) && options3.keyboardNavigationLabelProvider && options3.contextViewProvider) {
      asyncFindEnabled = true;
      findFilter = new AsyncFindFilter(options3.findProvider, options3.keyboardNavigationLabelProvider, options3.filter);
    }
    this.b = this.B(z, container2, delegate, renderers, { ...options3, findWidgetEnabled: !asyncFindEnabled, filter: findFilter ?? options3.filter });
    this.d = createAsyncDataTreeNode({
      element: void 0,
      parent: null,
      hasChildren: true,
      defaultCollapseState: void 0
    });
    if (this.o) {
      this.d = {
        ...this.d,
        id: null
      };
    }
    this.f.set(null, this.d);
    this.b.onDidChangeCollapseState(this.J, this, this.w);
    if (asyncFindEnabled) {
      const findOptions = { styles: options3.findWidgetStyles, showNotFoundMessage: options3.showNotFoundMessage };
      this.h = this.w.add(new AsyncFindController(this.b, options3.findProvider, findFilter, this.b.options.contextViewProvider, findOptions));
      this.y = (node) => this.h.shouldFocusWhenNavigating(node);
      this.onDidChangeFindOpenState = this.h.onDidChangeOpenState;
      this.onDidChangeFindMode = this.h.onDidChangeMode;
      this.onDidChangeFindMatchType = this.h.onDidChangeMatchType;
    } else {
      this.onDidChangeFindOpenState = this.b.onDidChangeFindOpenState;
      this.onDidChangeFindMode = this.b.onDidChangeFindMode;
      this.onDidChangeFindMatchType = this.b.onDidChangeFindMatchType;
    }
  }
  B(user, container2, delegate, renderers, options3) {
    const objectTreeDelegate = new $n3(delegate);
    const objectTreeRenderers = renderers.map((r2) => new AsyncDataTreeRenderer(r2, this.u, this.t.event));
    const objectTreeOptions = asObjectTreeOptions2(options3) || {};
    return new $C3(user, container2, objectTreeDelegate, objectTreeRenderers, objectTreeOptions);
  }
  updateOptions(options3 = {}) {
    this.b.updateOptions(options3);
  }
  get options() {
    return this.b.options;
  }
  // Widget
  getHTMLElement() {
    return this.b.getHTMLElement();
  }
  get contentHeight() {
    return this.b.contentHeight;
  }
  get contentWidth() {
    return this.b.contentWidth;
  }
  get onDidChangeContentHeight() {
    return this.b.onDidChangeContentHeight;
  }
  get onDidChangeContentWidth() {
    return this.b.onDidChangeContentWidth;
  }
  get scrollTop() {
    return this.b.scrollTop;
  }
  set scrollTop(scrollTop) {
    this.b.scrollTop = scrollTop;
  }
  get scrollLeft() {
    return this.b.scrollLeft;
  }
  set scrollLeft(scrollLeft) {
    this.b.scrollLeft = scrollLeft;
  }
  get scrollHeight() {
    return this.b.scrollHeight;
  }
  get renderHeight() {
    return this.b.renderHeight;
  }
  get lastVisibleElement() {
    return this.b.lastVisibleElement.element;
  }
  get ariaLabel() {
    return this.b.ariaLabel;
  }
  set ariaLabel(value) {
    this.b.ariaLabel = value;
  }
  domFocus() {
    this.b.domFocus();
  }
  isDOMFocused() {
    return this.b.isDOMFocused();
  }
  navigate(start) {
    let startNode;
    if (start) {
      startNode = this.D(start);
    }
    return new AsyncDataTreeNavigator(this.b.navigate(startNode));
  }
  layout(height, width2) {
    this.b.layout(height, width2);
  }
  style(styles) {
    this.b.style(styles);
  }
  // Model
  getInput() {
    return this.d.element;
  }
  async setInput(input, viewState) {
    this.m.forEach((promise) => promise.cancel());
    this.m.clear();
    this.d.element = input;
    const viewStateContext = viewState && { viewState, focus: [], selection: [] };
    await this.C(input, true, false, viewStateContext);
    if (viewStateContext) {
      this.b.setFocus(viewStateContext.focus);
      this.b.setSelection(viewStateContext.selection);
    }
    if (viewState && typeof viewState.scrollTop === "number") {
      this.scrollTop = viewState.scrollTop;
    }
  }
  async updateChildren(element = this.d.element, recursive = true, rerender = false, options3) {
    await this.C(element, recursive, rerender, void 0, options3);
  }
  async C(element = this.d.element, recursive = true, rerender = false, viewStateContext, options3) {
    if (typeof this.d.element === "undefined") {
      throw new $i3(this.z, "Tree input not set");
    }
    if (this.d.refreshPromise) {
      await this.d.refreshPromise;
      await Event2.toPromise(this.q.event);
    }
    const node = this.D(element);
    await this.E(node, recursive, viewStateContext, options3);
    if (rerender) {
      try {
        this.b.rerender(node);
      } catch {
      }
    }
  }
  resort(element = this.d.element, recursive = true) {
    this.b.resort(this.D(element), recursive);
  }
  hasNode(element) {
    return element === this.d.element || this.f.has(element);
  }
  // View
  rerender(element) {
    if (element === void 0 || element === this.d.element) {
      this.b.rerender();
      return;
    }
    const node = this.D(element);
    this.b.rerender(node);
  }
  updateElementHeight(element, height) {
    const node = this.D(element);
    this.b.updateElementHeight(node, height);
  }
  updateWidth(element) {
    const node = this.D(element);
    this.b.updateWidth(node);
  }
  // Tree
  getNode(element = this.d.element) {
    const dataNode = this.D(element);
    const node = this.b.getNode(dataNode === this.d ? null : dataNode);
    return this.u.map(node);
  }
  collapse(element, recursive = false) {
    const node = this.D(element);
    return this.b.collapse(node === this.d ? null : node, recursive);
  }
  async expand(element, recursive = false) {
    if (typeof this.d.element === "undefined") {
      throw new $i3(this.z, "Tree input not set");
    }
    if (this.d.refreshPromise) {
      await this.d.refreshPromise;
      await Event2.toPromise(this.q.event);
    }
    const node = this.D(element);
    if (this.b.hasElement(node) && !this.b.isCollapsible(node)) {
      return false;
    }
    if (node.refreshPromise) {
      await this.d.refreshPromise;
      await Event2.toPromise(this.q.event);
    }
    if (node !== this.d && !node.refreshPromise && !this.b.isCollapsed(node)) {
      return false;
    }
    const result = this.b.expand(node === this.d ? null : node, recursive);
    if (node.refreshPromise) {
      await this.d.refreshPromise;
      await Event2.toPromise(this.q.event);
    }
    return result;
  }
  toggleCollapsed(element, recursive = false) {
    return this.b.toggleCollapsed(this.D(element), recursive);
  }
  expandAll() {
    this.b.expandAll();
  }
  async expandTo(element) {
    if (!this.A.getParent) {
      throw new Error("Can't expand to element without getParent method");
    }
    const elements = [];
    while (!this.hasNode(element)) {
      element = this.A.getParent(element);
      if (element !== this.d.element) {
        elements.push(element);
      }
    }
    for (const element2 of Iterable.reverse(elements)) {
      await this.expand(element2);
    }
    this.b.expandTo(this.D(element));
  }
  collapseAll() {
    this.b.collapseAll();
  }
  isCollapsible(element) {
    return this.b.isCollapsible(this.D(element));
  }
  isCollapsed(element) {
    return this.b.isCollapsed(this.D(element));
  }
  triggerTypeNavigation() {
    this.b.triggerTypeNavigation();
  }
  openFind() {
    if (this.h) {
      this.h.open();
    } else {
      this.b.openFind();
    }
  }
  closeFind() {
    if (this.h) {
      this.h.close();
    } else {
      this.b.closeFind();
    }
  }
  refilter() {
    this.b.refilter();
  }
  setAnchor(element) {
    this.b.setAnchor(typeof element === "undefined" ? void 0 : this.D(element));
  }
  getAnchor() {
    const node = this.b.getAnchor();
    return node?.element;
  }
  setSelection(elements, browserEvent) {
    const nodes = elements.map((e) => this.D(e));
    this.b.setSelection(nodes, browserEvent);
  }
  getSelection() {
    const nodes = this.b.getSelection();
    return nodes.map((n) => n.element);
  }
  setFocus(elements, browserEvent) {
    const nodes = elements.map((e) => this.D(e));
    this.b.setFocus(nodes, browserEvent);
  }
  focusNext(n = 1, loop = false, browserEvent) {
    this.b.focusNext(n, loop, browserEvent, this.y);
  }
  focusPrevious(n = 1, loop = false, browserEvent) {
    this.b.focusPrevious(n, loop, browserEvent, this.y);
  }
  focusNextPage(browserEvent) {
    return this.b.focusNextPage(browserEvent, this.y);
  }
  focusPreviousPage(browserEvent) {
    return this.b.focusPreviousPage(browserEvent, this.y);
  }
  focusLast(browserEvent) {
    this.b.focusLast(browserEvent, this.y);
  }
  focusFirst(browserEvent) {
    this.b.focusFirst(browserEvent, this.y);
  }
  getFocus() {
    const nodes = this.b.getFocus();
    return nodes.map((n) => n.element);
  }
  getStickyScrollFocus() {
    const nodes = this.b.getStickyScrollFocus();
    return nodes.map((n) => n.element);
  }
  getFocusedPart() {
    return this.b.getFocusedPart();
  }
  reveal(element, relativeTop) {
    this.b.reveal(this.D(element), relativeTop);
  }
  getRelativeTop(element) {
    return this.b.getRelativeTop(this.D(element));
  }
  // Tree navigation
  getParentElement(element) {
    const node = this.b.getParentElement(this.D(element));
    return node && node.element;
  }
  getFirstElementChild(element = this.d.element) {
    const dataNode = this.D(element);
    const node = this.b.getFirstElementChild(dataNode === this.d ? null : dataNode);
    return node && node.element;
  }
  // Implementation
  D(element) {
    const node = this.f.get(element === this.d.element ? null : element);
    if (!node) {
      const nodeIdentity = this.o?.getId(element).toString();
      throw new $i3(this.z, `Data tree node not found${nodeIdentity ? `: ${nodeIdentity}` : ""}`);
    }
    return node;
  }
  async E(node, recursive, viewStateContext, options3) {
    if (this.w.isDisposed) {
      return;
    }
    await this.F(node, recursive, viewStateContext);
    if (this.w.isDisposed) {
      return;
    }
    this.L(node, viewStateContext, options3);
  }
  async F(node, recursive, viewStateContext) {
    let result;
    this.k.forEach((refreshPromise, refreshNode) => {
      if (!result && intersects(refreshNode, node)) {
        result = refreshPromise.then(() => this.F(node, recursive, viewStateContext));
      }
    });
    if (result) {
      return result;
    }
    if (node !== this.d) {
      const treeNode = this.b.getNode(node);
      if (treeNode.collapsed) {
        node.hasChildren = !!this.A.hasChildren(node.element);
        node.stale = true;
        this.K(node, [], recursive, viewStateContext);
        return;
      }
    }
    return this.G(node, recursive, viewStateContext);
  }
  async G(node, recursive, viewStateContext) {
    let done;
    node.refreshPromise = new Promise((c) => done = c);
    this.k.set(node, node.refreshPromise);
    node.refreshPromise.finally(() => {
      node.refreshPromise = void 0;
      this.k.delete(node);
    });
    try {
      const childrenToRefresh = await this.H(node, recursive, viewStateContext);
      node.stale = false;
      await Promises.settled(childrenToRefresh.map((child) => this.G(child, recursive, viewStateContext)));
    } finally {
      done();
    }
  }
  async H(node, recursive, viewStateContext) {
    node.hasChildren = !!this.A.hasChildren(node.element);
    let childrenPromise;
    if (!node.hasChildren) {
      childrenPromise = Promise.resolve(Iterable.empty());
    } else {
      const children = this.I(node);
      if ($Eg(children)) {
        childrenPromise = Promise.resolve(children);
      } else {
        const slowTimeout = $Wh(800);
        slowTimeout.then(() => {
          node.slow = true;
          this.t.fire(node);
        }, (_) => null);
        childrenPromise = children.finally(() => slowTimeout.cancel());
      }
    }
    try {
      const children = await childrenPromise;
      return this.K(node, children, recursive, viewStateContext);
    } catch (err) {
      if (node !== this.d && this.b.hasElement(node)) {
        this.b.collapse(node);
      }
      if ($kb(err)) {
        return [];
      }
      throw err;
    } finally {
      if (node.slow) {
        node.slow = false;
        this.t.fire(node);
      }
    }
  }
  I(node) {
    let result = this.m.get(node);
    if (result) {
      return result;
    }
    const children = this.A.getChildren(node.element);
    if ($Eg(children)) {
      return this.N(children);
    } else {
      result = $Hh(async () => this.N(await children));
      this.m.set(node, result);
      return result.finally(() => {
        this.m.delete(node);
      });
    }
  }
  J({ node, deep }) {
    if (node.element === null) {
      return;
    }
    if (!node.collapsed && node.element.stale) {
      if (deep) {
        this.collapse(node.element.element);
      } else {
        this.E(node.element, false).catch($gb);
      }
    }
  }
  K(node, childrenElementsIterable, recursive, viewStateContext) {
    const childrenElements = [...childrenElementsIterable];
    if (node.children.length === 0 && childrenElements.length === 0) {
      return [];
    }
    const nodesToForget = /* @__PURE__ */ new Map();
    const childrenTreeNodesById = /* @__PURE__ */ new Map();
    for (const child of node.children) {
      nodesToForget.set(child.element, child);
      if (this.o) {
        childrenTreeNodesById.set(child.id, { node: child, collapsed: this.b.hasElement(child) && this.b.isCollapsed(child) });
      }
    }
    const childrenToRefresh = [];
    const children = childrenElements.map((element) => {
      const hasChildren = !!this.A.hasChildren(element);
      if (!this.o) {
        const asyncDataTreeNode = createAsyncDataTreeNode({ element, parent: node, hasChildren, defaultCollapseState: this.j(element) });
        if (hasChildren && asyncDataTreeNode.defaultCollapseState === ObjectTreeElementCollapseState.PreserveOrExpanded) {
          childrenToRefresh.push(asyncDataTreeNode);
        }
        return asyncDataTreeNode;
      }
      const id2 = this.o.getId(element).toString();
      const result = childrenTreeNodesById.get(id2);
      if (result) {
        const asyncDataTreeNode = result.node;
        nodesToForget.delete(asyncDataTreeNode.element);
        this.f.delete(asyncDataTreeNode.element);
        this.f.set(element, asyncDataTreeNode);
        asyncDataTreeNode.element = element;
        asyncDataTreeNode.hasChildren = hasChildren;
        if (recursive) {
          if (result.collapsed) {
            asyncDataTreeNode.children.forEach((node2) => dfs2(node2, (node3) => this.f.delete(node3.element)));
            asyncDataTreeNode.children.splice(0, asyncDataTreeNode.children.length);
            asyncDataTreeNode.stale = true;
          } else {
            childrenToRefresh.push(asyncDataTreeNode);
          }
        } else if (hasChildren && !result.collapsed) {
          childrenToRefresh.push(asyncDataTreeNode);
        }
        return asyncDataTreeNode;
      }
      const childAsyncDataTreeNode = createAsyncDataTreeNode({ element, parent: node, id: id2, hasChildren, defaultCollapseState: this.j(element) });
      if (viewStateContext && viewStateContext.viewState.focus && viewStateContext.viewState.focus.indexOf(id2) > -1) {
        viewStateContext.focus.push(childAsyncDataTreeNode);
      }
      if (viewStateContext && viewStateContext.viewState.selection && viewStateContext.viewState.selection.indexOf(id2) > -1) {
        viewStateContext.selection.push(childAsyncDataTreeNode);
      }
      if (viewStateContext && viewStateContext.viewState.expanded && viewStateContext.viewState.expanded.indexOf(id2) > -1) {
        childrenToRefresh.push(childAsyncDataTreeNode);
      } else if (hasChildren && childAsyncDataTreeNode.defaultCollapseState === ObjectTreeElementCollapseState.PreserveOrExpanded) {
        childrenToRefresh.push(childAsyncDataTreeNode);
      }
      return childAsyncDataTreeNode;
    });
    for (const node2 of nodesToForget.values()) {
      dfs2(node2, (node3) => this.f.delete(node3.element));
    }
    for (const child of children) {
      this.f.set(child.element, child);
    }
    $8b(node.children, 0, node.children.length, children);
    if (node !== this.d && this.p && children.length === 1 && childrenToRefresh.length === 0) {
      children[0].forceExpanded = true;
      childrenToRefresh.push(children[0]);
    }
    return childrenToRefresh;
  }
  L(node, viewStateContext, options3) {
    const children = node.children.map((node2) => this.M(node2, viewStateContext));
    const objectTreeOptions = options3 && {
      ...options3,
      diffIdentityProvider: options3.diffIdentityProvider && {
        getId(node2) {
          return options3.diffIdentityProvider.getId(node2.element);
        }
      }
    };
    this.b.setChildren(node === this.d ? null : node, children, objectTreeOptions);
    if (node !== this.d) {
      this.b.setCollapsible(node, node.hasChildren);
    }
    this.q.fire();
  }
  M(node, viewStateContext) {
    if (node.stale) {
      return {
        element: node,
        collapsible: node.hasChildren,
        collapsed: true
      };
    }
    let collapsed2;
    if (viewStateContext && viewStateContext.viewState.expanded && node.id && viewStateContext.viewState.expanded.indexOf(node.id) > -1) {
      collapsed2 = false;
    } else if (node.forceExpanded) {
      collapsed2 = false;
      node.forceExpanded = false;
    } else {
      collapsed2 = node.defaultCollapseState;
    }
    return {
      element: node,
      children: node.hasChildren ? Iterable.map(node.children, (child) => this.M(child, viewStateContext)) : [],
      collapsible: node.hasChildren,
      collapsed: collapsed2
    };
  }
  N(children) {
    if (this.g) {
      children = [...children].sort(this.g.compare.bind(this.g));
    }
    return children;
  }
  // view state
  getViewState() {
    if (!this.o) {
      throw new $i3(this.z, "Can't get tree view state without an identity provider");
    }
    const getId2 = (element) => this.o.getId(element).toString();
    const focus = this.getFocus().map(getId2);
    const selection = this.getSelection().map(getId2);
    const expanded2 = [];
    const root = this.b.getNode();
    const stack = [root];
    while (stack.length > 0) {
      const node = stack.pop();
      if (node !== root && node.collapsible && !node.collapsed) {
        expanded2.push(getId2(node.element.element));
      }
      stack.push(...node.children);
    }
    return { focus, selection, expanded: expanded2, scrollTop: this.scrollTop };
  }
  dispose() {
    this.w.dispose();
    this.b.dispose();
  }
};
var CompressibleAsyncDataTreeNodeWrapper = class _CompressibleAsyncDataTreeNodeWrapper {
  get element() {
    return {
      elements: this.a.element.elements.map((e) => e.element),
      incompressible: this.a.element.incompressible
    };
  }
  get children() {
    return this.a.children.map((node) => new _CompressibleAsyncDataTreeNodeWrapper(node));
  }
  get depth() {
    return this.a.depth;
  }
  get visibleChildrenCount() {
    return this.a.visibleChildrenCount;
  }
  get visibleChildIndex() {
    return this.a.visibleChildIndex;
  }
  get collapsible() {
    return this.a.collapsible;
  }
  get collapsed() {
    return this.a.collapsed;
  }
  get visible() {
    return this.a.visible;
  }
  get filterData() {
    return this.a.filterData;
  }
  constructor(a) {
    this.a = a;
  }
};
var CompressibleAsyncDataTreeRenderer = class {
  constructor(d, f, g, onDidChangeTwistieState) {
    this.d = d;
    this.f = f;
    this.g = g;
    this.onDidChangeTwistieState = onDidChangeTwistieState;
    this.a = /* @__PURE__ */ new Map();
    this.b = [];
    this.templateId = d.templateId;
  }
  renderTemplate(container2) {
    const templateData = this.d.renderTemplate(container2);
    return { templateData };
  }
  renderElement(node, index, templateData, height) {
    this.d.renderElement(this.f.map(node), index, templateData.templateData, height);
  }
  renderCompressedElements(node, index, templateData, height) {
    this.d.renderCompressedElements(this.g().map(node), index, templateData.templateData, height);
  }
  renderTwistie(element, twistieElement) {
    if (element.slow) {
      twistieElement.classList.add(...ThemeIcon.asClassNameArray($6l.treeItemLoading));
      return true;
    } else {
      twistieElement.classList.remove(...ThemeIcon.asClassNameArray($6l.treeItemLoading));
      return false;
    }
  }
  disposeElement(node, index, templateData, height) {
    this.d.disposeElement?.(this.f.map(node), index, templateData.templateData, height);
  }
  disposeCompressedElements(node, index, templateData, height) {
    this.d.disposeCompressedElements?.(this.g().map(node), index, templateData.templateData, height);
  }
  disposeTemplate(templateData) {
    this.d.disposeTemplate(templateData.templateData);
  }
  dispose() {
    this.a.clear();
    this.b = $Xc(this.b);
  }
};
function asCompressibleObjectTreeOptions(options3) {
  const objectTreeOptions = options3 && asObjectTreeOptions2(options3);
  return objectTreeOptions && {
    ...objectTreeOptions,
    keyboardNavigationLabelProvider: objectTreeOptions.keyboardNavigationLabelProvider && {
      ...objectTreeOptions.keyboardNavigationLabelProvider,
      getCompressedNodeKeyboardNavigationLabel(els) {
        return options3.keyboardNavigationLabelProvider.getCompressedNodeKeyboardNavigationLabel(els.map((e) => e.element));
      }
    }
  };
}
var $F3 = class extends $E3 {
  constructor(user, container2, virtualDelegate, x, renderers, dataSource, options3 = {}) {
    super(user, container2, virtualDelegate, renderers, dataSource, options3);
    this.x = x;
    this.s = new $j3((node) => new CompressibleAsyncDataTreeNodeWrapper(node));
    this.v = options3.filter;
  }
  getCompressedTreeNode(e) {
    const node = this.D(e);
    return this.b.getCompressedTreeNode(node).element;
  }
  B(user, container2, delegate, renderers, options3) {
    const objectTreeDelegate = new $n3(delegate);
    const objectTreeRenderers = renderers.map((r2) => new CompressibleAsyncDataTreeRenderer(r2, this.u, () => this.s, this.t.event));
    const objectTreeOptions = asCompressibleObjectTreeOptions(options3) || {};
    return new $D3(user, container2, objectTreeDelegate, objectTreeRenderers, objectTreeOptions);
  }
  M(node, viewStateContext) {
    return {
      incompressible: this.x.isIncompressible(node.element),
      ...super.M(node, viewStateContext)
    };
  }
  updateOptions(options3 = {}) {
    this.b.updateOptions(options3);
  }
  getViewState() {
    if (!this.o) {
      throw new $i3(this.z, "Can't get tree view state without an identity provider");
    }
    const getId2 = (element) => this.o.getId(element).toString();
    const focus = this.getFocus().map(getId2);
    const selection = this.getSelection().map(getId2);
    const expanded2 = [];
    const root = this.b.getCompressedTreeNode();
    const stack = [root];
    while (stack.length > 0) {
      const node = stack.pop();
      if (node !== root && node.collapsible && !node.collapsed) {
        for (const asyncNode of node.element.elements) {
          expanded2.push(getId2(asyncNode.element));
        }
      }
      stack.push(...node.children);
    }
    return { focus, selection, expanded: expanded2, scrollTop: this.scrollTop };
  }
  L(node, viewStateContext, options3) {
    if (!this.o) {
      return super.L(node, viewStateContext);
    }
    const getId2 = (element) => this.o.getId(element).toString();
    const getUncompressedIds = (nodes) => {
      const result = /* @__PURE__ */ new Set();
      for (const node2 of nodes) {
        const compressedNode = this.b.getCompressedTreeNode(node2 === this.d ? null : node2);
        if (!compressedNode.element) {
          continue;
        }
        for (const node3 of compressedNode.element.elements) {
          result.add(getId2(node3.element));
        }
      }
      return result;
    };
    const oldSelection = getUncompressedIds(this.b.getSelection());
    const oldFocus = getUncompressedIds(this.b.getFocus());
    super.L(node, viewStateContext, options3);
    const selection = this.getSelection();
    let didChangeSelection = false;
    const focus = this.getFocus();
    let didChangeFocus = false;
    const visit = (node2) => {
      const compressedNode = node2.element;
      if (compressedNode) {
        for (let i2 = 0; i2 < compressedNode.elements.length; i2++) {
          const id2 = getId2(compressedNode.elements[i2].element);
          const element = compressedNode.elements[compressedNode.elements.length - 1].element;
          if (oldSelection.has(id2) && selection.indexOf(element) === -1) {
            selection.push(element);
            didChangeSelection = true;
          }
          if (oldFocus.has(id2) && focus.indexOf(element) === -1) {
            focus.push(element);
            didChangeFocus = true;
          }
        }
      }
      node2.children.forEach(visit);
    };
    visit(this.b.getCompressedTreeNode(node === this.d ? null : node));
    if (didChangeSelection) {
      this.setSelection(selection);
    }
    if (didChangeFocus) {
      this.setFocus(focus);
    }
  }
  // For compressed async data trees, `TreeVisibility.Recurse` doesn't currently work
  // and we have to filter everything beforehand
  // Related to #85193 and #85835
  N(children) {
    if (this.v) {
      children = Iterable.filter(children, (e) => {
        const result = this.v.filter(
          e,
          1
          /* TreeVisibility.Visible */
        );
        const visibility = getVisibility(result);
        if (visibility === 2) {
          throw new Error("Recursive tree visibility not supported in async data compressed trees");
        }
        return visibility === 1;
      });
    }
    return super.N(children);
  }
  navigate(start) {
    return super.navigate(start);
  }
};
function getVisibility(filterResult) {
  if (typeof filterResult === "boolean") {
    return filterResult ? 1 : 0;
  } else if ($k3(filterResult)) {
    return $l3(filterResult.visibility);
  } else {
    return $l3(filterResult);
  }
}
var AsyncDataTreeNavigator = class {
  constructor(a) {
    this.a = a;
  }
  current() {
    const current = this.a.current();
    if (current === null) {
      return null;
    }
    return current.element;
  }
  previous() {
    this.a.previous();
    return this.current();
  }
  first() {
    this.a.first();
    return this.current();
  }
  last() {
    this.a.last();
    return this.current();
  }
  next() {
    this.a.next();
    return this.current();
  }
};

// out-build/vs/base/browser/ui/tree/dataTree.js
var $G3 = class extends $v3 {
  constructor(f, container2, delegate, renderers, g, options3 = {}) {
    super(f, container2, delegate, renderers, options3);
    this.f = f;
    this.g = g;
    this.d = /* @__PURE__ */ new Map();
    this.c = options3.identityProvider;
  }
  // Model
  getInput() {
    return this.b;
  }
  setInput(input, viewState) {
    if (viewState && !this.c) {
      throw new $i3(this.f, "Can't restore tree view state without an identity provider");
    }
    this.b = input;
    if (!input) {
      this.d.clear();
      this.o.setChildren(null, Iterable.empty());
      return;
    }
    if (!viewState) {
      this.m(input);
      return;
    }
    const focus = [];
    const selection = [];
    const isCollapsed = (element) => {
      const id2 = this.c.getId(element).toString();
      return !viewState.expanded[id2];
    };
    const onDidCreateNode = (node) => {
      const id2 = this.c.getId(node.element).toString();
      if (viewState.focus.has(id2)) {
        focus.push(node.element);
      }
      if (viewState.selection.has(id2)) {
        selection.push(node.element);
      }
    };
    this.m(input, isCollapsed, onDidCreateNode);
    this.setFocus(focus);
    this.setSelection(selection);
    if (viewState && typeof viewState.scrollTop === "number") {
      this.scrollTop = viewState.scrollTop;
    }
  }
  updateChildren(element = this.b) {
    if (typeof this.b === "undefined") {
      throw new $i3(this.f, "Tree input not set");
    }
    let isCollapsed;
    if (this.c) {
      isCollapsed = (element2) => {
        const id2 = this.c.getId(element2).toString();
        const node = this.d.get(id2);
        if (!node) {
          return void 0;
        }
        return node.collapsed;
      };
    }
    this.m(element, isCollapsed);
  }
  resort(element = this.b, recursive = true) {
    this.o.resort(element === this.b ? null : element, recursive);
  }
  // View
  refresh(element) {
    if (element === void 0) {
      this.j.rerender();
      return;
    }
    this.o.rerender(element);
  }
  // Implementation
  m(element, isCollapsed, onDidCreateNode) {
    let onDidDeleteNode;
    if (this.c) {
      const insertedElements = /* @__PURE__ */ new Set();
      const outerOnDidCreateNode = onDidCreateNode;
      onDidCreateNode = (node) => {
        const id2 = this.c.getId(node.element).toString();
        insertedElements.add(id2);
        this.d.set(id2, node);
        outerOnDidCreateNode?.(node);
      };
      onDidDeleteNode = (node) => {
        const id2 = this.c.getId(node.element).toString();
        if (!insertedElements.has(id2)) {
          this.d.delete(id2);
        }
      };
    }
    this.o.setChildren(element === this.b ? null : element, this.s(element, isCollapsed).elements, { onDidCreateNode, onDidDeleteNode });
  }
  s(element, isCollapsed) {
    const children = [...this.g.getChildren(element)];
    const elements = Iterable.map(children, (element2) => {
      const { elements: children2, size } = this.s(element2, isCollapsed);
      const collapsible = this.g.hasChildren ? this.g.hasChildren(element2) : void 0;
      const collapsed2 = size === 0 ? void 0 : isCollapsed && isCollapsed(element2);
      return { element: element2, children: children2, collapsible, collapsed: collapsed2 };
    });
    return { elements, size: children.length };
  }
  V(user, options3) {
    return new $w3(user, options3);
  }
};

// out-build/vs/platform/contextkey/common/contextkeys.js
var $seb = new $nn("isMac", $m, localize(1715, null));
var $teb = new $nn("isLinux", $n, localize(1716, null));
var $ueb = new $nn("isWindows", $l, localize(1717, null));
var $veb = new $nn("isWeb", $r, localize(1718, null));
var $web = new $nn("isMacNative", $m && !$r, localize(1719, null));
var $xeb = new $nn("isIOS", $u, localize(1720, null));
var $yeb = new $nn("isMobile", $v, localize(1721, null));
var $zeb = new $nn("isDevelopment", false, true);
var $Aeb = new $nn("productQualityType", "", localize(1722, null));
var $Beb = "inputFocus";
var $Ceb = new $nn($Beb, false, localize(1723, null));

// out-build/vs/platform/list/browser/listService.js
var $Deb = $Qk("listService");
var $Eeb = class {
  get lastFocusedList() {
    return this.c;
  }
  constructor() {
    this.a = new $2c();
    this.b = [];
    this.c = void 0;
  }
  d(widget) {
    if (widget === this.c) {
      return;
    }
    this.c?.getHTMLElement().classList.remove("last-focused");
    this.c = widget;
    this.c?.getHTMLElement().classList.add("last-focused");
  }
  register(widget, extraContextKeys) {
    if (this.b.some((l) => l.widget === widget)) {
      throw new Error("Cannot register the same widget multiple times");
    }
    const registeredList = { widget, extraContextKeys };
    this.b.push(registeredList);
    if ($Mj(widget.getHTMLElement())) {
      this.d(widget);
    }
    return $Zc(widget.onDidFocus(() => this.d(widget)), $1c(() => this.b.splice(this.b.indexOf(registeredList), 1)), widget.onDidDispose(() => {
      this.b = this.b.filter((l) => l !== registeredList);
      if (this.c === widget) {
        this.d(void 0);
      }
    }));
  }
  dispose() {
    this.a.dispose();
  }
};
var $Feb = new $nn("listScrollAtBoundary", "none");
var $Geb = $7m.or($Feb.isEqualTo("top"), $Feb.isEqualTo("both"));
var $Heb = $7m.or($Feb.isEqualTo("bottom"), $Feb.isEqualTo("both"));
var $Ieb = new $nn("listFocus", true);
var $Jeb = new $nn("treestickyScrollFocused", false);
var $Keb = new $nn("listSupportsMultiselect", true);
var $Leb = $7m.and($Ieb, $7m.not($Beb), $Jeb.negate());
var $Meb = new $nn("listHasSelectionOrFocus", false);
var $Neb = new $nn("listDoubleSelection", false);
var $Oeb = new $nn("listMultiSelection", false);
var $Peb = new $nn("listSelectionNavigation", false);
var $Qeb = new $nn("listSupportsFind", true);
var $Reb = new $nn("treeElementCanCollapse", false);
var $Seb = new $nn("treeElementHasParent", false);
var $Teb = new $nn("treeElementCanExpand", false);
var $Ueb = new $nn("treeElementHasChild", false);
var $Veb = new $nn("treeFindOpen", false);
var WorkbenchListTypeNavigationModeKey = "listTypeNavigationMode";
var WorkbenchListAutomaticKeyboardNavigationLegacyKey = "listAutomaticKeyboardNavigation";
function createScopedContextKeyService(contextKeyService, widget) {
  const result = contextKeyService.createScoped(widget.getHTMLElement());
  $Ieb.bindTo(result);
  return result;
}
function createScrollObserver(contextKeyService, widget) {
  const listScrollAt = $Feb.bindTo(contextKeyService);
  const update = () => {
    const atTop = widget.scrollTop === 0;
    const atBottom = widget.scrollHeight - widget.renderHeight - widget.scrollTop < 1;
    if (atTop && atBottom) {
      listScrollAt.set("both");
    } else if (atTop) {
      listScrollAt.set("top");
    } else if (atBottom) {
      listScrollAt.set("bottom");
    } else {
      listScrollAt.set("none");
    }
  };
  update();
  return widget.onDidScroll(update);
}
var multiSelectModifierSettingKey = "workbench.list.multiSelectModifier";
var openModeSettingKey = "workbench.list.openMode";
var horizontalScrollingKey = "workbench.list.horizontalScrolling";
var defaultFindModeSettingKey = "workbench.list.defaultFindMode";
var typeNavigationModeSettingKey = "workbench.list.typeNavigationMode";
var keyboardNavigationSettingKey = "workbench.list.keyboardNavigation";
var scrollByPageKey = "workbench.list.scrollByPage";
var defaultFindMatchTypeSettingKey = "workbench.list.defaultFindMatchType";
var treeIndentKey = "workbench.tree.indent";
var treeRenderIndentGuidesKey = "workbench.tree.renderIndentGuides";
var listSmoothScrolling = "workbench.list.smoothScrolling";
var mouseWheelScrollSensitivityKey = "workbench.list.mouseWheelScrollSensitivity";
var fastScrollSensitivityKey = "workbench.list.fastScrollSensitivity";
var treeExpandMode = "workbench.tree.expandMode";
var treeStickyScroll = "workbench.tree.enableStickyScroll";
var treeStickyScrollMaxElements = "workbench.tree.stickyScrollMaxItemCount";
function useAltAsMultipleSelectionModifier(configurationService) {
  return configurationService.getValue(multiSelectModifierSettingKey) === "alt";
}
var MultipleSelectionController = class extends $3c {
  constructor(b) {
    super();
    this.b = b;
    this.a = useAltAsMultipleSelectionModifier(b);
    this.c();
  }
  c() {
    this.B(this.b.onDidChangeConfiguration((e) => {
      if (e.affectsConfiguration(multiSelectModifierSettingKey)) {
        this.a = useAltAsMultipleSelectionModifier(this.b);
      }
    }));
  }
  isSelectionSingleChangeEvent(event) {
    if (this.a) {
      return event.browserEvent.altKey;
    }
    return $v1(event);
  }
  isSelectionRangeChangeEvent(event) {
    return $w1(event);
  }
};
function toWorkbenchListOptions(accessor, options3) {
  const configurationService = accessor.get($kl);
  const keybindingService = accessor.get($Ty);
  const disposables = new $2c();
  const result = {
    ...options3,
    keyboardNavigationDelegate: { mightProducePrintableCharacter(e) {
      return keybindingService.mightProducePrintableCharacter(e);
    } },
    smoothScrolling: Boolean(configurationService.getValue(listSmoothScrolling)),
    mouseWheelScrollSensitivity: configurationService.getValue(mouseWheelScrollSensitivityKey),
    fastScrollSensitivity: configurationService.getValue(fastScrollSensitivityKey),
    multipleSelectionController: options3.multipleSelectionController ?? disposables.add(new MultipleSelectionController(configurationService)),
    keyboardNavigationEventFilter: createKeyboardNavigationEventFilter(keybindingService),
    scrollByPage: Boolean(configurationService.getValue(scrollByPageKey))
  };
  return [result, disposables];
}
var $Web = class $Web2 extends $A1 {
  get onDidOpen() {
    return this.Q.onDidOpen;
  }
  constructor(user, container2, delegate, renderers, options3, contextKeyService, listService, configurationService, instantiationService) {
    const horizontalScrolling = typeof options3.horizontalScrolling !== "undefined" ? options3.horizontalScrolling : Boolean(configurationService.getValue(horizontalScrollingKey));
    const [workbenchListOptions, workbenchListOptionsDisposable] = instantiationService.invokeFunction(toWorkbenchListOptions, options3);
    super(user, container2, delegate, renderers, {
      keyboardSupport: false,
      ...workbenchListOptions,
      horizontalScrolling
    });
    this.z.add(workbenchListOptionsDisposable);
    this.contextKeyService = createScopedContextKeyService(contextKeyService, this);
    this.z.add(createScrollObserver(this.contextKeyService, this));
    this.h = $Keb.bindTo(this.contextKeyService);
    this.h.set(options3.multipleSelectionSupport !== false);
    const listSelectionNavigation = $Peb.bindTo(this.contextKeyService);
    listSelectionNavigation.set(Boolean(options3.selectionNavigation));
    this.L = $Meb.bindTo(this.contextKeyService);
    this.M = $Neb.bindTo(this.contextKeyService);
    this.N = $Oeb.bindTo(this.contextKeyService);
    this.O = options3.horizontalScrolling;
    this.P = useAltAsMultipleSelectionModifier(configurationService);
    this.z.add(this.contextKeyService);
    this.z.add(listService.register(this));
    this.R(options3.overrideStyles);
    this.z.add(this.onDidChangeSelection(() => {
      const selection = this.getSelection();
      const focus = this.getFocus();
      this.contextKeyService.bufferChangeEvents(() => {
        this.L.set(selection.length > 0 || focus.length > 0);
        this.N.set(selection.length > 1);
        this.M.set(selection.length === 2);
      });
    }));
    this.z.add(this.onDidChangeFocus(() => {
      const selection = this.getSelection();
      const focus = this.getFocus();
      this.L.set(selection.length > 0 || focus.length > 0);
    }));
    this.z.add(configurationService.onDidChangeConfiguration((e) => {
      if (e.affectsConfiguration(multiSelectModifierSettingKey)) {
        this.P = useAltAsMultipleSelectionModifier(configurationService);
      }
      let options4 = {};
      if (e.affectsConfiguration(horizontalScrollingKey) && this.O === void 0) {
        const horizontalScrolling2 = Boolean(configurationService.getValue(horizontalScrollingKey));
        options4 = { ...options4, horizontalScrolling: horizontalScrolling2 };
      }
      if (e.affectsConfiguration(scrollByPageKey)) {
        const scrollByPage = Boolean(configurationService.getValue(scrollByPageKey));
        options4 = { ...options4, scrollByPage };
      }
      if (e.affectsConfiguration(listSmoothScrolling)) {
        const smoothScrolling = Boolean(configurationService.getValue(listSmoothScrolling));
        options4 = { ...options4, smoothScrolling };
      }
      if (e.affectsConfiguration(mouseWheelScrollSensitivityKey)) {
        const mouseWheelScrollSensitivity = configurationService.getValue(mouseWheelScrollSensitivityKey);
        options4 = { ...options4, mouseWheelScrollSensitivity };
      }
      if (e.affectsConfiguration(fastScrollSensitivityKey)) {
        const fastScrollSensitivity = configurationService.getValue(fastScrollSensitivityKey);
        options4 = { ...options4, fastScrollSensitivity };
      }
      if (Object.keys(options4).length > 0) {
        this.updateOptions(options4);
      }
    }));
    this.Q = new ListResourceNavigator(this, { configurationService, ...options3 });
    this.z.add(this.Q);
  }
  updateOptions(options3) {
    super.updateOptions(options3);
    if (options3.overrideStyles !== void 0) {
      this.R(options3.overrideStyles);
    }
    if (options3.multipleSelectionSupport !== void 0) {
      this.h.set(!!options3.multipleSelectionSupport);
    }
  }
  R(styles) {
    this.style(styles ? $J$(styles) : $I$);
  }
  get useAltAsMultipleSelectionModifier() {
    return this.P;
  }
};
$Web = __decorate([
  __param(5, $on),
  __param(6, $Deb),
  __param(7, $kl),
  __param(8, $Pk)
], $Web);
var $Xeb = class $Xeb2 extends $422 {
  get onDidOpen() {
    return this.h.onDidOpen;
  }
  constructor(user, container2, delegate, renderers, options3, contextKeyService, listService, configurationService, instantiationService) {
    const horizontalScrolling = typeof options3.horizontalScrolling !== "undefined" ? options3.horizontalScrolling : Boolean(configurationService.getValue(horizontalScrollingKey));
    const [workbenchListOptions, workbenchListOptionsDisposable] = instantiationService.invokeFunction(toWorkbenchListOptions, options3);
    super(user, container2, delegate, renderers, {
      keyboardSupport: false,
      ...workbenchListOptions,
      horizontalScrolling
    });
    this.c = new $2c();
    this.c.add(workbenchListOptionsDisposable);
    this.contextKeyService = createScopedContextKeyService(contextKeyService, this);
    this.c.add(createScrollObserver(this.contextKeyService, this.widget));
    this.g = options3.horizontalScrolling;
    this.d = $Keb.bindTo(this.contextKeyService);
    this.d.set(options3.multipleSelectionSupport !== false);
    const listSelectionNavigation = $Peb.bindTo(this.contextKeyService);
    listSelectionNavigation.set(Boolean(options3.selectionNavigation));
    this.f = useAltAsMultipleSelectionModifier(configurationService);
    this.c.add(this.contextKeyService);
    this.c.add(listService.register(this));
    this.j(options3.overrideStyles);
    this.c.add(configurationService.onDidChangeConfiguration((e) => {
      if (e.affectsConfiguration(multiSelectModifierSettingKey)) {
        this.f = useAltAsMultipleSelectionModifier(configurationService);
      }
      let options4 = {};
      if (e.affectsConfiguration(horizontalScrollingKey) && this.g === void 0) {
        const horizontalScrolling2 = Boolean(configurationService.getValue(horizontalScrollingKey));
        options4 = { ...options4, horizontalScrolling: horizontalScrolling2 };
      }
      if (e.affectsConfiguration(scrollByPageKey)) {
        const scrollByPage = Boolean(configurationService.getValue(scrollByPageKey));
        options4 = { ...options4, scrollByPage };
      }
      if (e.affectsConfiguration(listSmoothScrolling)) {
        const smoothScrolling = Boolean(configurationService.getValue(listSmoothScrolling));
        options4 = { ...options4, smoothScrolling };
      }
      if (e.affectsConfiguration(mouseWheelScrollSensitivityKey)) {
        const mouseWheelScrollSensitivity = configurationService.getValue(mouseWheelScrollSensitivityKey);
        options4 = { ...options4, mouseWheelScrollSensitivity };
      }
      if (e.affectsConfiguration(fastScrollSensitivityKey)) {
        const fastScrollSensitivity = configurationService.getValue(fastScrollSensitivityKey);
        options4 = { ...options4, fastScrollSensitivity };
      }
      if (Object.keys(options4).length > 0) {
        this.updateOptions(options4);
      }
    }));
    this.h = new ListResourceNavigator(this, { configurationService, ...options3 });
    this.c.add(this.h);
  }
  updateOptions(options3) {
    super.updateOptions(options3);
    if (options3.overrideStyles !== void 0) {
      this.j(options3.overrideStyles);
    }
    if (options3.multipleSelectionSupport !== void 0) {
      this.d.set(!!options3.multipleSelectionSupport);
    }
  }
  j(styles) {
    this.style(styles ? $J$(styles) : $I$);
  }
  get useAltAsMultipleSelectionModifier() {
    return this.f;
  }
  dispose() {
    this.c.dispose();
    super.dispose();
  }
};
$Xeb = __decorate([
  __param(5, $on),
  __param(6, $Deb),
  __param(7, $kl),
  __param(8, $Pk)
], $Xeb);
var $Yeb = class $Yeb2 extends $e3 {
  get onDidOpen() {
    return this.y.onDidOpen;
  }
  constructor(user, container2, delegate, columns, renderers, options3, contextKeyService, listService, configurationService, instantiationService) {
    const horizontalScrolling = typeof options3.horizontalScrolling !== "undefined" ? options3.horizontalScrolling : Boolean(configurationService.getValue(horizontalScrollingKey));
    const [workbenchListOptions, workbenchListOptionsDisposable] = instantiationService.invokeFunction(toWorkbenchListOptions, options3);
    super(user, container2, delegate, columns, renderers, {
      keyboardSupport: false,
      ...workbenchListOptions,
      horizontalScrolling
    });
    this.k.add(workbenchListOptionsDisposable);
    this.contextKeyService = createScopedContextKeyService(contextKeyService, this);
    this.k.add(createScrollObserver(this.contextKeyService, this));
    this.s = $Keb.bindTo(this.contextKeyService);
    this.s.set(options3.multipleSelectionSupport !== false);
    const listSelectionNavigation = $Peb.bindTo(this.contextKeyService);
    listSelectionNavigation.set(Boolean(options3.selectionNavigation));
    this.t = $Meb.bindTo(this.contextKeyService);
    this.u = $Neb.bindTo(this.contextKeyService);
    this.v = $Oeb.bindTo(this.contextKeyService);
    this.w = options3.horizontalScrolling;
    this.x = useAltAsMultipleSelectionModifier(configurationService);
    this.k.add(this.contextKeyService);
    this.k.add(listService.register(this));
    this.z(options3.overrideStyles);
    this.k.add(this.onDidChangeSelection(() => {
      const selection = this.getSelection();
      const focus = this.getFocus();
      this.contextKeyService.bufferChangeEvents(() => {
        this.t.set(selection.length > 0 || focus.length > 0);
        this.v.set(selection.length > 1);
        this.u.set(selection.length === 2);
      });
    }));
    this.k.add(this.onDidChangeFocus(() => {
      const selection = this.getSelection();
      const focus = this.getFocus();
      this.t.set(selection.length > 0 || focus.length > 0);
    }));
    this.k.add(configurationService.onDidChangeConfiguration((e) => {
      if (e.affectsConfiguration(multiSelectModifierSettingKey)) {
        this.x = useAltAsMultipleSelectionModifier(configurationService);
      }
      let options4 = {};
      if (e.affectsConfiguration(horizontalScrollingKey) && this.w === void 0) {
        const horizontalScrolling2 = Boolean(configurationService.getValue(horizontalScrollingKey));
        options4 = { ...options4, horizontalScrolling: horizontalScrolling2 };
      }
      if (e.affectsConfiguration(scrollByPageKey)) {
        const scrollByPage = Boolean(configurationService.getValue(scrollByPageKey));
        options4 = { ...options4, scrollByPage };
      }
      if (e.affectsConfiguration(listSmoothScrolling)) {
        const smoothScrolling = Boolean(configurationService.getValue(listSmoothScrolling));
        options4 = { ...options4, smoothScrolling };
      }
      if (e.affectsConfiguration(mouseWheelScrollSensitivityKey)) {
        const mouseWheelScrollSensitivity = configurationService.getValue(mouseWheelScrollSensitivityKey);
        options4 = { ...options4, mouseWheelScrollSensitivity };
      }
      if (e.affectsConfiguration(fastScrollSensitivityKey)) {
        const fastScrollSensitivity = configurationService.getValue(fastScrollSensitivityKey);
        options4 = { ...options4, fastScrollSensitivity };
      }
      if (Object.keys(options4).length > 0) {
        this.updateOptions(options4);
      }
    }));
    this.y = new TableResourceNavigator(this, { configurationService, ...options3 });
    this.k.add(this.y);
  }
  updateOptions(options3) {
    super.updateOptions(options3);
    if (options3.overrideStyles !== void 0) {
      this.z(options3.overrideStyles);
    }
    if (options3.multipleSelectionSupport !== void 0) {
      this.s.set(!!options3.multipleSelectionSupport);
    }
  }
  z(styles) {
    this.style(styles ? $J$(styles) : $I$);
  }
  get useAltAsMultipleSelectionModifier() {
    return this.x;
  }
  dispose() {
    this.k.dispose();
    super.dispose();
  }
};
$Yeb = __decorate([
  __param(6, $on),
  __param(7, $Deb),
  __param(8, $kl),
  __param(9, $Pk)
], $Yeb);
function $Zeb(typeArg = "keydown", preserveFocus, pinned) {
  const e = new KeyboardEvent(typeArg);
  e.preserveFocus = preserveFocus;
  e.pinned = pinned;
  e.__forceEvent = true;
  return e;
}
var ResourceNavigator = class extends $3c {
  constructor(c, options3) {
    super();
    this.c = c;
    this.b = this.B(new $ze());
    this.onDidOpen = this.b.event;
    this.B(Event2.filter(this.c.onDidChangeSelection, (e) => $4j(e.browserEvent))((e) => this.f(e)));
    this.B(this.c.onPointer((e) => this.g(e.element, e.browserEvent)));
    this.B(this.c.onMouseDblClick((e) => this.h(e.element, e.browserEvent)));
    if (typeof options3?.openOnSingleClick !== "boolean" && options3?.configurationService) {
      this.a = options3?.configurationService.getValue(openModeSettingKey) !== "doubleClick";
      this.B(options3?.configurationService.onDidChangeConfiguration((e) => {
        if (e.affectsConfiguration(openModeSettingKey)) {
          this.a = options3?.configurationService.getValue(openModeSettingKey) !== "doubleClick";
        }
      }));
    } else {
      this.a = options3?.openOnSingleClick ?? true;
    }
  }
  f(event) {
    if (event.elements.length !== 1) {
      return;
    }
    const selectionKeyboardEvent = event.browserEvent;
    const preserveFocus = typeof selectionKeyboardEvent.preserveFocus === "boolean" ? selectionKeyboardEvent.preserveFocus : true;
    const pinned = typeof selectionKeyboardEvent.pinned === "boolean" ? selectionKeyboardEvent.pinned : !preserveFocus;
    const sideBySide = false;
    this.j(this.getSelectedElement(), preserveFocus, pinned, sideBySide, event.browserEvent);
  }
  g(element, browserEvent) {
    if (!this.a) {
      return;
    }
    const isDoubleClick = browserEvent.detail === 2;
    if (isDoubleClick) {
      return;
    }
    const isMiddleClick = browserEvent.button === 1;
    const preserveFocus = true;
    const pinned = isMiddleClick;
    const sideBySide = browserEvent.ctrlKey || browserEvent.metaKey || browserEvent.altKey;
    this.j(element, preserveFocus, pinned, sideBySide, browserEvent);
  }
  h(element, browserEvent) {
    if (!browserEvent) {
      return;
    }
    const target = browserEvent.target;
    const onTwistie = target.classList.contains("monaco-tl-twistie") || target.classList.contains("monaco-icon-label") && target.classList.contains("folder-icon") && browserEvent.offsetX < 16;
    if (onTwistie) {
      return;
    }
    const preserveFocus = false;
    const pinned = true;
    const sideBySide = browserEvent.ctrlKey || browserEvent.metaKey || browserEvent.altKey;
    this.j(element, preserveFocus, pinned, sideBySide, browserEvent);
  }
  j(element, preserveFocus, pinned, sideBySide, browserEvent) {
    if (!element) {
      return;
    }
    this.b.fire({
      editorOptions: {
        preserveFocus,
        pinned,
        revealIfVisible: true
      },
      sideBySide,
      element,
      browserEvent
    });
  }
};
var ListResourceNavigator = class extends ResourceNavigator {
  constructor(widget, options3) {
    super(widget, options3);
    this.c = widget;
  }
  getSelectedElement() {
    return this.c.getSelectedElements()[0];
  }
};
var TableResourceNavigator = class extends ResourceNavigator {
  constructor(widget, options3) {
    super(widget, options3);
  }
  getSelectedElement() {
    return this.c.getSelectedElements()[0];
  }
};
var TreeResourceNavigator = class extends ResourceNavigator {
  constructor(widget, options3) {
    super(widget, options3);
  }
  getSelectedElement() {
    return this.c.getSelection()[0] ?? void 0;
  }
};
function createKeyboardNavigationEventFilter(keybindingService) {
  let inMultiChord = false;
  return (event) => {
    if (event.toKeyCodeChord().isModifierKey()) {
      return false;
    }
    if (inMultiChord) {
      inMultiChord = false;
      return false;
    }
    const result = keybindingService.softDispatch(event, event.target);
    if (result.kind === 1) {
      inMultiChord = true;
      return false;
    }
    inMultiChord = false;
    return result.kind === 0;
  };
}
var $1eb = class $1eb2 extends $C3 {
  get contextKeyService() {
    return this.d.contextKeyService;
  }
  get useAltAsMultipleSelectionModifier() {
    return this.d.useAltAsMultipleSelectionModifier;
  }
  get onDidOpen() {
    return this.d.onDidOpen;
  }
  constructor(user, container2, delegate, renderers, options3, instantiationService, contextKeyService, listService, configurationService) {
    const { options: treeOptions, getTypeNavigationMode, disposable } = instantiationService.invokeFunction(workbenchTreeDataPreamble, options3);
    super(user, container2, delegate, renderers, treeOptions);
    this.E.add(disposable);
    this.d = new WorkbenchTreeInternals(this, options3, getTypeNavigationMode, options3.overrideStyles, contextKeyService, listService, configurationService);
    this.E.add(this.d);
  }
  updateOptions(options3) {
    super.updateOptions(options3);
    this.d.updateOptions(options3);
  }
};
$1eb = __decorate([
  __param(5, $Pk),
  __param(6, $on),
  __param(7, $Deb),
  __param(8, $kl)
], $1eb);
var $2eb = class $2eb2 extends $D3 {
  get contextKeyService() {
    return this.c.contextKeyService;
  }
  get useAltAsMultipleSelectionModifier() {
    return this.c.useAltAsMultipleSelectionModifier;
  }
  get onDidOpen() {
    return this.c.onDidOpen;
  }
  constructor(user, container2, delegate, renderers, options3, instantiationService, contextKeyService, listService, configurationService) {
    const { options: treeOptions, getTypeNavigationMode, disposable } = instantiationService.invokeFunction(workbenchTreeDataPreamble, options3);
    super(user, container2, delegate, renderers, treeOptions);
    this.E.add(disposable);
    this.c = new WorkbenchTreeInternals(this, options3, getTypeNavigationMode, options3.overrideStyles, contextKeyService, listService, configurationService);
    this.E.add(this.c);
  }
  updateOptions(options3 = {}) {
    super.updateOptions(options3);
    if (options3.overrideStyles) {
      this.c.updateStyleOverrides(options3.overrideStyles);
    }
    this.c.updateOptions(options3);
  }
};
$2eb = __decorate([
  __param(5, $Pk),
  __param(6, $on),
  __param(7, $Deb),
  __param(8, $kl)
], $2eb);
var $3eb = class $3eb2 extends $G3 {
  get contextKeyService() {
    return this.u.contextKeyService;
  }
  get useAltAsMultipleSelectionModifier() {
    return this.u.useAltAsMultipleSelectionModifier;
  }
  get onDidOpen() {
    return this.u.onDidOpen;
  }
  constructor(user, container2, delegate, renderers, dataSource, options3, instantiationService, contextKeyService, listService, configurationService) {
    const { options: treeOptions, getTypeNavigationMode, disposable } = instantiationService.invokeFunction(workbenchTreeDataPreamble, options3);
    super(user, container2, delegate, renderers, dataSource, treeOptions);
    this.E.add(disposable);
    this.u = new WorkbenchTreeInternals(this, options3, getTypeNavigationMode, options3.overrideStyles, contextKeyService, listService, configurationService);
    this.E.add(this.u);
  }
  updateOptions(options3 = {}) {
    super.updateOptions(options3);
    if (options3.overrideStyles !== void 0) {
      this.u.updateStyleOverrides(options3.overrideStyles);
    }
    this.u.updateOptions(options3);
  }
};
$3eb = __decorate([
  __param(6, $Pk),
  __param(7, $on),
  __param(8, $Deb),
  __param(9, $kl)
], $3eb);
var $4eb = class $4eb2 extends $E3 {
  get contextKeyService() {
    return this.O.contextKeyService;
  }
  get useAltAsMultipleSelectionModifier() {
    return this.O.useAltAsMultipleSelectionModifier;
  }
  get onDidOpen() {
    return this.O.onDidOpen;
  }
  constructor(user, container2, delegate, renderers, dataSource, options3, instantiationService, contextKeyService, listService, configurationService) {
    const { options: treeOptions, getTypeNavigationMode, disposable } = instantiationService.invokeFunction(workbenchTreeDataPreamble, options3);
    super(user, container2, delegate, renderers, dataSource, treeOptions);
    this.w.add(disposable);
    this.O = new WorkbenchTreeInternals(this, options3, getTypeNavigationMode, options3.overrideStyles, contextKeyService, listService, configurationService);
    this.w.add(this.O);
  }
  updateOptions(options3 = {}) {
    super.updateOptions(options3);
    if (options3.overrideStyles) {
      this.O.updateStyleOverrides(options3.overrideStyles);
    }
    this.O.updateOptions(options3);
  }
};
$4eb = __decorate([
  __param(6, $Pk),
  __param(7, $on),
  __param(8, $Deb),
  __param(9, $kl)
], $4eb);
var $5eb = class $5eb2 extends $F3 {
  get contextKeyService() {
    return this.S.contextKeyService;
  }
  get useAltAsMultipleSelectionModifier() {
    return this.S.useAltAsMultipleSelectionModifier;
  }
  get onDidOpen() {
    return this.S.onDidOpen;
  }
  constructor(user, container2, virtualDelegate, compressionDelegate, renderers, dataSource, options3, instantiationService, contextKeyService, listService, configurationService) {
    const { options: treeOptions, getTypeNavigationMode, disposable } = instantiationService.invokeFunction(workbenchTreeDataPreamble, options3);
    super(user, container2, virtualDelegate, compressionDelegate, renderers, dataSource, treeOptions);
    this.w.add(disposable);
    this.S = new WorkbenchTreeInternals(this, options3, getTypeNavigationMode, options3.overrideStyles, contextKeyService, listService, configurationService);
    this.w.add(this.S);
  }
  updateOptions(options3) {
    super.updateOptions(options3);
    this.S.updateOptions(options3);
  }
};
$5eb = __decorate([
  __param(7, $Pk),
  __param(8, $on),
  __param(9, $Deb),
  __param(10, $kl)
], $5eb);
function getDefaultTreeFindMode(configurationService) {
  const value = configurationService.getValue(defaultFindModeSettingKey);
  if (value === "highlight") {
    return TreeFindMode.Highlight;
  } else if (value === "filter") {
    return TreeFindMode.Filter;
  }
  const deprecatedValue = configurationService.getValue(keyboardNavigationSettingKey);
  if (deprecatedValue === "simple" || deprecatedValue === "highlight") {
    return TreeFindMode.Highlight;
  } else if (deprecatedValue === "filter") {
    return TreeFindMode.Filter;
  }
  return void 0;
}
function getDefaultTreeFindMatchType(configurationService) {
  const value = configurationService.getValue(defaultFindMatchTypeSettingKey);
  if (value === "fuzzy") {
    return TreeFindMatchType.Fuzzy;
  } else if (value === "contiguous") {
    return TreeFindMatchType.Contiguous;
  }
  return void 0;
}
function workbenchTreeDataPreamble(accessor, options3) {
  const configurationService = accessor.get($kl);
  const contextViewService = accessor.get($40);
  const contextKeyService = accessor.get($on);
  const instantiationService = accessor.get($Pk);
  const getTypeNavigationMode = () => {
    const modeString = contextKeyService.getContextKeyValue(WorkbenchListTypeNavigationModeKey);
    if (modeString === "automatic") {
      return TypeNavigationMode.Automatic;
    } else if (modeString === "trigger") {
      return TypeNavigationMode.Trigger;
    }
    const modeBoolean = contextKeyService.getContextKeyValue(WorkbenchListAutomaticKeyboardNavigationLegacyKey);
    if (modeBoolean === false) {
      return TypeNavigationMode.Trigger;
    }
    const configString = configurationService.getValue(typeNavigationModeSettingKey);
    if (configString === "automatic") {
      return TypeNavigationMode.Automatic;
    } else if (configString === "trigger") {
      return TypeNavigationMode.Trigger;
    }
    return void 0;
  };
  const horizontalScrolling = options3.horizontalScrolling !== void 0 ? options3.horizontalScrolling : Boolean(configurationService.getValue(horizontalScrollingKey));
  const [workbenchListOptions, disposable] = instantiationService.invokeFunction(toWorkbenchListOptions, options3);
  const paddingBottom = options3.paddingBottom;
  const renderIndentGuides = options3.renderIndentGuides !== void 0 ? options3.renderIndentGuides : configurationService.getValue(treeRenderIndentGuidesKey);
  return {
    getTypeNavigationMode,
    disposable,
    // eslint-disable-next-line local/code-no-dangerous-type-assertions
    options: {
      // ...options, // TODO@Joao why is this not splatted here?
      keyboardSupport: false,
      ...workbenchListOptions,
      indent: typeof configurationService.getValue(treeIndentKey) === "number" ? configurationService.getValue(treeIndentKey) : void 0,
      renderIndentGuides,
      smoothScrolling: Boolean(configurationService.getValue(listSmoothScrolling)),
      defaultFindMode: getDefaultTreeFindMode(configurationService),
      defaultFindMatchType: getDefaultTreeFindMatchType(configurationService),
      horizontalScrolling,
      scrollByPage: Boolean(configurationService.getValue(scrollByPageKey)),
      paddingBottom,
      hideTwistiesOfChildlessElements: options3.hideTwistiesOfChildlessElements,
      expandOnlyOnTwistieClick: options3.expandOnlyOnTwistieClick ?? configurationService.getValue(treeExpandMode) === "doubleClick",
      contextViewProvider: contextViewService,
      findWidgetStyles: $D$,
      enableStickyScroll: Boolean(configurationService.getValue(treeStickyScroll)),
      stickyScrollMaxItemCount: Number(configurationService.getValue(treeStickyScrollMaxElements))
    }
  };
}
var WorkbenchTreeInternals = class WorkbenchTreeInternals2 {
  get onDidOpen() {
    return this.p.onDidOpen;
  }
  constructor(q, options3, getTypeNavigationMode, overrideStyles2, contextKeyService, listService, configurationService) {
    this.q = q;
    this.o = [];
    this.contextKeyService = createScopedContextKeyService(contextKeyService, q);
    this.o.push(createScrollObserver(this.contextKeyService, q));
    this.a = $Keb.bindTo(this.contextKeyService);
    this.a.set(options3.multipleSelectionSupport !== false);
    const listSelectionNavigation = $Peb.bindTo(this.contextKeyService);
    listSelectionNavigation.set(Boolean(options3.selectionNavigation));
    this.b = $Qeb.bindTo(this.contextKeyService);
    this.b.set(options3.findWidgetEnabled ?? true);
    this.c = $Meb.bindTo(this.contextKeyService);
    this.d = $Neb.bindTo(this.contextKeyService);
    this.f = $Oeb.bindTo(this.contextKeyService);
    this.g = $Reb.bindTo(this.contextKeyService);
    this.h = $Seb.bindTo(this.contextKeyService);
    this.i = $Teb.bindTo(this.contextKeyService);
    this.j = $Ueb.bindTo(this.contextKeyService);
    this.k = $Veb.bindTo(this.contextKeyService);
    this.m = $Jeb.bindTo(this.contextKeyService);
    this.n = useAltAsMultipleSelectionModifier(configurationService);
    this.updateStyleOverrides(overrideStyles2);
    const updateCollapseContextKeys = () => {
      const focus = q.getFocus()[0];
      if (!focus) {
        return;
      }
      const node = q.getNode(focus);
      this.g.set(node.collapsible && !node.collapsed);
      this.h.set(!!q.getParentElement(focus));
      this.i.set(node.collapsible && node.collapsed);
      this.j.set(!!q.getFirstElementChild(focus));
    };
    const interestingContextKeys = /* @__PURE__ */ new Set();
    interestingContextKeys.add(WorkbenchListTypeNavigationModeKey);
    interestingContextKeys.add(WorkbenchListAutomaticKeyboardNavigationLegacyKey);
    this.o.push(this.contextKeyService, listService.register(q), q.onDidChangeSelection(() => {
      const selection = q.getSelection();
      const focus = q.getFocus();
      this.contextKeyService.bufferChangeEvents(() => {
        this.c.set(selection.length > 0 || focus.length > 0);
        this.f.set(selection.length > 1);
        this.d.set(selection.length === 2);
      });
    }), q.onDidChangeFocus(() => {
      const selection = q.getSelection();
      const focus = q.getFocus();
      this.c.set(selection.length > 0 || focus.length > 0);
      updateCollapseContextKeys();
    }), q.onDidChangeCollapseState(updateCollapseContextKeys), q.onDidChangeModel(updateCollapseContextKeys), q.onDidChangeFindOpenState((enabled) => this.k.set(enabled)), q.onDidChangeStickyScrollFocused((focused) => this.m.set(focused)), configurationService.onDidChangeConfiguration((e) => {
      let newOptions = {};
      if (e.affectsConfiguration(multiSelectModifierSettingKey)) {
        this.n = useAltAsMultipleSelectionModifier(configurationService);
      }
      if (e.affectsConfiguration(treeIndentKey)) {
        const indent = configurationService.getValue(treeIndentKey);
        newOptions = { ...newOptions, indent };
      }
      if (e.affectsConfiguration(treeRenderIndentGuidesKey) && options3.renderIndentGuides === void 0) {
        const renderIndentGuides = configurationService.getValue(treeRenderIndentGuidesKey);
        newOptions = { ...newOptions, renderIndentGuides };
      }
      if (e.affectsConfiguration(listSmoothScrolling)) {
        const smoothScrolling = Boolean(configurationService.getValue(listSmoothScrolling));
        newOptions = { ...newOptions, smoothScrolling };
      }
      if (e.affectsConfiguration(defaultFindModeSettingKey) || e.affectsConfiguration(keyboardNavigationSettingKey)) {
        const defaultFindMode = getDefaultTreeFindMode(configurationService);
        newOptions = { ...newOptions, defaultFindMode };
      }
      if (e.affectsConfiguration(typeNavigationModeSettingKey) || e.affectsConfiguration(keyboardNavigationSettingKey)) {
        const typeNavigationMode = getTypeNavigationMode();
        newOptions = { ...newOptions, typeNavigationMode };
      }
      if (e.affectsConfiguration(defaultFindMatchTypeSettingKey)) {
        const defaultFindMatchType = getDefaultTreeFindMatchType(configurationService);
        newOptions = { ...newOptions, defaultFindMatchType };
      }
      if (e.affectsConfiguration(horizontalScrollingKey) && options3.horizontalScrolling === void 0) {
        const horizontalScrolling = Boolean(configurationService.getValue(horizontalScrollingKey));
        newOptions = { ...newOptions, horizontalScrolling };
      }
      if (e.affectsConfiguration(scrollByPageKey)) {
        const scrollByPage = Boolean(configurationService.getValue(scrollByPageKey));
        newOptions = { ...newOptions, scrollByPage };
      }
      if (e.affectsConfiguration(treeExpandMode) && options3.expandOnlyOnTwistieClick === void 0) {
        newOptions = { ...newOptions, expandOnlyOnTwistieClick: configurationService.getValue(treeExpandMode) === "doubleClick" };
      }
      if (e.affectsConfiguration(treeStickyScroll)) {
        const enableStickyScroll = configurationService.getValue(treeStickyScroll);
        newOptions = { ...newOptions, enableStickyScroll };
      }
      if (e.affectsConfiguration(treeStickyScrollMaxElements)) {
        const stickyScrollMaxItemCount = Math.max(1, configurationService.getValue(treeStickyScrollMaxElements));
        newOptions = { ...newOptions, stickyScrollMaxItemCount };
      }
      if (e.affectsConfiguration(mouseWheelScrollSensitivityKey)) {
        const mouseWheelScrollSensitivity = configurationService.getValue(mouseWheelScrollSensitivityKey);
        newOptions = { ...newOptions, mouseWheelScrollSensitivity };
      }
      if (e.affectsConfiguration(fastScrollSensitivityKey)) {
        const fastScrollSensitivity = configurationService.getValue(fastScrollSensitivityKey);
        newOptions = { ...newOptions, fastScrollSensitivity };
      }
      if (Object.keys(newOptions).length > 0) {
        q.updateOptions(newOptions);
      }
    }), this.contextKeyService.onDidChangeContext((e) => {
      if (e.affectsSome(interestingContextKeys)) {
        q.updateOptions({ typeNavigationMode: getTypeNavigationMode() });
      }
    }));
    this.p = new TreeResourceNavigator(q, { configurationService, ...options3 });
    this.o.push(this.p);
  }
  get useAltAsMultipleSelectionModifier() {
    return this.n;
  }
  updateOptions(options3) {
    if (options3.multipleSelectionSupport !== void 0) {
      this.a.set(!!options3.multipleSelectionSupport);
    }
  }
  updateStyleOverrides(overrideStyles2) {
    this.q.style(overrideStyles2 ? $J$(overrideStyles2) : $I$);
  }
  dispose() {
    this.o = $Xc(this.o);
  }
};
WorkbenchTreeInternals = __decorate([
  __param(4, $on),
  __param(5, $Deb),
  __param(6, $kl)
], WorkbenchTreeInternals);
var configurationRegistry3 = $Wn.as($Ht.Configuration);
configurationRegistry3.registerConfiguration({
  id: "workbench",
  order: 7,
  title: localize(1965, null),
  type: "object",
  properties: {
    [multiSelectModifierSettingKey]: {
      type: "string",
      enum: ["ctrlCmd", "alt"],
      markdownEnumDescriptions: [
        localize(1966, null),
        localize(1967, null)
      ],
      default: "ctrlCmd",
      description: localize(1968, null)
    },
    [openModeSettingKey]: {
      type: "string",
      enum: ["singleClick", "doubleClick"],
      default: "singleClick",
      description: localize(1969, null)
    },
    [horizontalScrollingKey]: {
      type: "boolean",
      default: false,
      description: localize(1970, null)
    },
    [scrollByPageKey]: {
      type: "boolean",
      default: false,
      description: localize(1971, null)
    },
    [treeIndentKey]: {
      type: "number",
      default: 8,
      minimum: 4,
      maximum: 40,
      description: localize(1972, null)
    },
    [treeRenderIndentGuidesKey]: {
      type: "string",
      enum: ["none", "onHover", "always"],
      default: "onHover",
      description: localize(1973, null)
    },
    [listSmoothScrolling]: {
      type: "boolean",
      default: false,
      description: localize(1974, null)
    },
    [mouseWheelScrollSensitivityKey]: {
      type: "number",
      default: 1,
      markdownDescription: localize(1975, null)
    },
    [fastScrollSensitivityKey]: {
      type: "number",
      default: 5,
      markdownDescription: localize(1976, null)
    },
    [defaultFindModeSettingKey]: {
      type: "string",
      enum: ["highlight", "filter"],
      enumDescriptions: [
        localize(1977, null),
        localize(1978, null)
      ],
      default: "highlight",
      description: localize(1979, null)
    },
    [keyboardNavigationSettingKey]: {
      type: "string",
      enum: ["simple", "highlight", "filter"],
      enumDescriptions: [
        localize(1980, null),
        localize(1981, null),
        localize(1982, null)
      ],
      default: "highlight",
      description: localize(1983, null),
      deprecated: true,
      deprecationMessage: localize(1984, null)
    },
    [defaultFindMatchTypeSettingKey]: {
      type: "string",
      enum: ["fuzzy", "contiguous"],
      enumDescriptions: [
        localize(1985, null),
        localize(1986, null)
      ],
      default: "fuzzy",
      description: localize(1987, null)
    },
    [treeExpandMode]: {
      type: "string",
      enum: ["singleClick", "doubleClick"],
      default: "singleClick",
      description: localize(1988, null)
    },
    [treeStickyScroll]: {
      type: "boolean",
      default: true,
      description: localize(1989, null)
    },
    [treeStickyScrollMaxElements]: {
      type: "number",
      minimum: 1,
      default: 7,
      markdownDescription: localize(1990, null, "`#workbench.tree.enableStickyScroll#`")
    },
    [typeNavigationModeSettingKey]: {
      type: "string",
      enum: ["automatic", "trigger"],
      default: "automatic",
      markdownDescription: localize(1991, null)
    }
  }
});

// out-build/vs/editor/contrib/gotoSymbol/browser/referencesModel.js
var $6eb = class {
  constructor(isProviderFirst, parent, link2, d) {
    this.isProviderFirst = isProviderFirst;
    this.parent = parent;
    this.link = link2;
    this.d = d;
    this.id = $mW.nextId();
  }
  get uri() {
    return this.link.uri;
  }
  get range() {
    return this.c ?? this.link.targetSelectionRange ?? this.link.range;
  }
  set range(value) {
    this.c = value;
    this.d(this);
  }
  get ariaMessage() {
    const preview = this.parent.getPreview(this)?.preview(this.range);
    if (!preview) {
      return localize(1163, null, $sh(this.uri), this.range.startLineNumber, this.range.startColumn);
    } else {
      return localize(1164, null, preview.value, $sh(this.uri), this.range.startLineNumber, this.range.startColumn);
    }
  }
};
var $7eb = class {
  constructor(c) {
    this.c = c;
  }
  dispose() {
    this.c.dispose();
  }
  preview(range, n = 8) {
    const model = this.c.object.textEditorModel;
    if (!model) {
      return void 0;
    }
    const { startLineNumber, startColumn, endLineNumber, endColumn } = range;
    const word = model.getWordUntilPosition({ lineNumber: startLineNumber, column: startColumn - n });
    const beforeRange = new $9C(startLineNumber, word.startColumn, startLineNumber, startColumn);
    const afterRange = new $9C(
      endLineNumber,
      endColumn,
      endLineNumber,
      1073741824
      /* Constants.MAX_SAFE_SMALL_INTEGER */
    );
    const before = model.getValueInRange(beforeRange).replace(/^\s+/, "");
    const inside = model.getValueInRange(range);
    const after = model.getValueInRange(afterRange).replace(/\s+$/, "");
    return {
      value: before + inside + after,
      highlight: { start: before.length, end: before.length + inside.length }
    };
  }
};
var $8eb = class {
  constructor(parent, uri) {
    this.parent = parent;
    this.uri = uri;
    this.children = [];
    this.c = new $Ec();
  }
  dispose() {
    $Xc(this.c.values());
    this.c.clear();
  }
  getPreview(child) {
    return this.c.get(child.uri);
  }
  get ariaMessage() {
    const len = this.children.length;
    if (len === 1) {
      return localize(1165, null, $sh(this.uri), this.uri.fsPath);
    } else {
      return localize(1166, null, len, $sh(this.uri), this.uri.fsPath);
    }
  }
  async resolve(textModelResolverService) {
    if (this.c.size !== 0) {
      return this;
    }
    for (const child of this.children) {
      if (this.c.has(child.uri)) {
        continue;
      }
      try {
        const ref = await textModelResolverService.createModelReference(child.uri);
        this.c.set(child.uri, new $7eb(ref));
      } catch (err) {
        $gb(err);
      }
    }
    return this;
  }
};
var $9eb = class _$9eb {
  constructor(links, title) {
    this.groups = [];
    this.references = [];
    this._onDidChangeReferenceRange = new $ze();
    this.onDidChangeReferenceRange = this._onDidChangeReferenceRange.event;
    this.c = links;
    this.d = title;
    const [providersFirst] = links;
    links.sort(_$9eb.e);
    let current;
    for (const link2 of links) {
      if (!current || !$lh.isEqual(current.uri, link2.uri, true)) {
        current = new $8eb(this, link2.uri);
        this.groups.push(current);
      }
      if (current.children.length === 0 || _$9eb.e(link2, current.children[current.children.length - 1]) !== 0) {
        const oneRef = new $6eb(providersFirst === link2, current, link2, (ref) => this._onDidChangeReferenceRange.fire(ref));
        this.references.push(oneRef);
        current.children.push(oneRef);
      }
    }
  }
  dispose() {
    $Xc(this.groups);
    this._onDidChangeReferenceRange.dispose();
    this.groups.length = 0;
  }
  clone() {
    return new _$9eb(this.c, this.d);
  }
  get title() {
    return this.d;
  }
  get isEmpty() {
    return this.groups.length === 0;
  }
  get ariaMessage() {
    if (this.isEmpty) {
      return localize(1167, null);
    } else if (this.references.length === 1) {
      return localize(1168, null, this.references[0].uri.fsPath);
    } else if (this.groups.length === 1) {
      return localize(1169, null, this.references.length, this.groups[0].uri.fsPath);
    } else {
      return localize(1170, null, this.references.length, this.groups.length);
    }
  }
  nextOrPreviousReference(reference, next) {
    const { parent } = reference;
    let idx = parent.children.indexOf(reference);
    const childCount = parent.children.length;
    const groupCount = parent.parent.groups.length;
    if (groupCount === 1 || next && idx + 1 < childCount || !next && idx > 0) {
      if (next) {
        idx = (idx + 1) % childCount;
      } else {
        idx = (idx + childCount - 1) % childCount;
      }
      return parent.children[idx];
    }
    idx = parent.parent.groups.indexOf(parent);
    if (next) {
      idx = (idx + 1) % groupCount;
      return parent.parent.groups[idx].children[0];
    } else {
      idx = (idx + groupCount - 1) % groupCount;
      return parent.parent.groups[idx].children[parent.parent.groups[idx].children.length - 1];
    }
  }
  nearestReference(resource, position) {
    const nearest = this.references.map((ref, idx) => {
      return {
        idx,
        prefixLen: $3f(ref.uri.toString(), resource.toString()),
        offsetDist: Math.abs(ref.range.startLineNumber - position.lineNumber) * 100 + Math.abs(ref.range.startColumn - position.column)
      };
    }).sort((a, b) => {
      if (a.prefixLen > b.prefixLen) {
        return -1;
      } else if (a.prefixLen < b.prefixLen) {
        return 1;
      } else if (a.offsetDist < b.offsetDist) {
        return -1;
      } else if (a.offsetDist > b.offsetDist) {
        return 1;
      } else {
        return 0;
      }
    })[0];
    if (nearest) {
      return this.references[nearest.idx];
    }
    return void 0;
  }
  referenceAt(resource, position) {
    for (const ref of this.references) {
      if (ref.uri.toString() === resource.toString()) {
        if ($9C.containsPosition(ref.range, position)) {
          return ref;
        }
      }
    }
    return void 0;
  }
  firstReference() {
    for (const ref of this.references) {
      if (ref.isProviderFirst) {
        return ref;
      }
    }
    return this.references[0];
  }
  static e(a, b) {
    return $lh.compare(a.uri, b.uri) || $9C.compareRangesUsingStarts(a.range, b.range);
  }
};

// out-build/vs/base/browser/ui/countBadge/countBadge.js
var $D2 = class extends $3c {
  constructor(container2, h3, j) {
    super();
    this.h = h3;
    this.j = j;
    this.b = 0;
    this.g = this.B(new $4c());
    this.a = $bk(container2, $(".monaco-count-badge"));
    this.B($1c(() => container2.removeChild(this.a)));
    this.c = this.h.countFormat || "{0}";
    this.f = this.h.titleFormat || "";
    this.setCount(this.h.count || 0);
    this.m();
  }
  setCount(count) {
    this.b = count;
    this.n();
  }
  setCountFormat(countFormat) {
    this.c = countFormat;
    this.n();
  }
  setTitleFormat(titleFormat) {
    this.f = titleFormat;
    this.m();
    this.n();
  }
  m() {
    if (this.f !== "" && !this.g.value) {
      this.g.value = $J1().setupDelayedHoverAtMouse(this.a, () => ({ content: $wf(this.f, this.b), appearance: { compact: true } }));
    } else if (this.f === "" && this.g.value) {
      this.g.value = void 0;
    }
  }
  n() {
    this.a.textContent = $wf(this.c, this.b);
    this.a.style.backgroundColor = this.j.badgeBackground ?? "";
    this.a.style.color = this.j.badgeForeground ?? "";
    if (this.j.badgeBorder) {
      this.a.style.border = `1px solid ${this.j.badgeBorder}`;
    }
  }
};

// out-build/vs/base/browser/ui/highlightedlabel/highlightedLabel.js
var $S2 = class _$S2 extends $3c {
  /**
   * Create a new {@link $S2}.
   *
   * @param container The parent container to append to.
   */
  constructor(container2, m) {
    super();
    this.m = m;
    this.b = "";
    this.c = "";
    this.f = [];
    this.h = false;
    this.g = m?.supportIcons ?? false;
    this.a = $bk(container2, $("span.monaco-highlighted-label"));
  }
  /**
   * The label's DOM node.
   */
  get element() {
    return this.a;
  }
  /**
   * Set the label and highlights.
   *
   * @param text The label to display.
   * @param highlights The ranges to highlight.
   * @param title An optional title for the hover tooltip.
   * @param escapeNewLines Whether to escape new lines.
   * @returns
   */
  set(text2, highlights = [], title = "", escapeNewLines) {
    if (!text2) {
      text2 = "";
    }
    if (escapeNewLines) {
      text2 = _$S2.escapeNewLines(text2, highlights);
    }
    if (this.h && this.b === text2 && this.c === title && $Pv(this.f, highlights)) {
      return;
    }
    this.b = text2;
    this.c = title;
    this.f = highlights;
    this.n();
  }
  n() {
    const children = [];
    let pos = 0;
    for (const highlight of this.f) {
      if (highlight.end === highlight.start) {
        continue;
      }
      if (pos < highlight.start) {
        const substring2 = this.b.substring(pos, highlight.start);
        if (this.g) {
          children.push(...$B1(substring2));
        } else {
          children.push(substring2);
        }
        pos = highlight.start;
      }
      const substring = this.b.substring(pos, highlight.end);
      const element = $("span.highlight", void 0, ...this.g ? $B1(substring) : [substring]);
      if (highlight.extraClasses) {
        element.classList.add(...highlight.extraClasses);
      }
      children.push(element);
      pos = highlight.end;
    }
    if (pos < this.b.length) {
      const substring = this.b.substring(pos);
      if (this.g) {
        children.push(...$B1(substring));
      } else {
        children.push(substring);
      }
    }
    $dk(this.a, ...children);
    if (this.m?.hoverDelegate?.showNativeHover) {
      this.a.title = this.c;
    } else {
      if (!this.j && this.c !== "") {
        const hoverDelegate = this.m?.hoverDelegate ?? $JZ("mouse");
        this.j = this.B($J1().setupManagedHover(hoverDelegate, this.a, this.c));
      } else if (this.j) {
        this.j.update(this.c);
      }
    }
    this.h = true;
  }
  static escapeNewLines(text2, highlights) {
    let total = 0;
    let extra = 0;
    return text2.replace(/\r\n|\r|\n/g, (match, offset) => {
      extra = match === "\r\n" ? -1 : 0;
      offset += total;
      for (const highlight of highlights) {
        if (highlight.end <= offset) {
          continue;
        }
        if (highlight.start >= offset) {
          highlight.start += extra;
        }
        if (highlight.end >= offset) {
          highlight.end += extra;
        }
      }
      total += extra;
      return "\u23CE";
    });
  }
};

// out-build/vs/base/browser/ui/iconLabel/iconLabel.js
var FastLabelNode = class {
  constructor(e) {
    this.e = e;
  }
  get element() {
    return this.e;
  }
  set textContent(content) {
    if (this.a || content === this.b) {
      return;
    }
    this.b = content;
    this.e.textContent = content;
  }
  set classNames(classNames) {
    if (this.a || $Pv(classNames, this.c)) {
      return;
    }
    this.c = classNames;
    this.e.classList.value = "";
    this.e.classList.add(...classNames);
  }
  set empty(empty) {
    if (this.a || empty === this.d) {
      return;
    }
    this.d = empty;
    this.e.style.marginLeft = empty ? "0" : "";
  }
  dispose() {
    this.a = true;
  }
};
var $T2 = class extends $3c {
  constructor(container2, options3) {
    super();
    this.r = /* @__PURE__ */ new Map();
    this.a = options3;
    this.b = this.B(new FastLabelNode($bk(container2, $(".monaco-icon-label"))));
    this.j = $bk(this.b.element, $(".monaco-icon-label-container"));
    this.c = $bk(this.j, $("span.monaco-icon-name-container"));
    if (options3?.supportHighlights || options3?.supportIcons) {
      this.f = this.B(new LabelWithHighlights(this.c, !!options3.supportIcons));
    } else {
      this.f = new Label(this.c);
    }
    this.n = options3?.hoverDelegate ?? $JZ("mouse");
  }
  get element() {
    return this.b.element;
  }
  setLabel(label3, description, options3) {
    const labelClasses = ["monaco-icon-label"];
    const containerClasses = ["monaco-icon-label-container"];
    let ariaLabel = "";
    if (options3) {
      if (options3.extraClasses) {
        labelClasses.push(...options3.extraClasses);
      }
      if (options3.italic) {
        labelClasses.push("italic");
      }
      if (options3.strikethrough) {
        labelClasses.push("strikethrough");
      }
      if (options3.disabledCommand) {
        containerClasses.push("disabled");
      }
      if (options3.title) {
        if (typeof options3.title === "string") {
          ariaLabel += options3.title;
        } else {
          ariaLabel += label3;
        }
      }
    }
    const existingIconNode = this.b.element.querySelector(".monaco-icon-label-iconpath");
    if (options3?.iconPath) {
      let iconNode;
      if (!existingIconNode || !$Uj(existingIconNode)) {
        iconNode = $(".monaco-icon-label-iconpath");
        this.b.element.prepend(iconNode);
      } else {
        iconNode = existingIconNode;
      }
      iconNode.style.backgroundImage = $5Z(options3?.iconPath);
    } else if (existingIconNode) {
      existingIconNode.remove();
    }
    this.b.classNames = labelClasses;
    this.b.element.setAttribute("aria-label", ariaLabel);
    this.j.classList.value = "";
    this.j.classList.add(...containerClasses);
    this.s(options3?.descriptionTitle ? this.j : this.element, options3?.title);
    this.f.setLabel(label3, options3);
    if (description || this.g) {
      const descriptionNode = this.u();
      if (descriptionNode instanceof $S2) {
        descriptionNode.set(description || "", options3 ? options3.descriptionMatches : void 0, void 0, options3?.labelEscapeNewLines);
        this.s(descriptionNode.element, options3?.descriptionTitle);
      } else {
        descriptionNode.textContent = description && options3?.labelEscapeNewLines ? $S2.escapeNewLines(description, []) : description || "";
        this.s(descriptionNode.element, options3?.descriptionTitle || "");
        descriptionNode.empty = !description;
      }
    }
    if (options3?.suffix || this.h) {
      const suffixNode = this.t();
      suffixNode.textContent = options3?.suffix ?? "";
    }
  }
  s(htmlElement, tooltip) {
    const previousCustomHover = this.r.get(htmlElement);
    if (previousCustomHover) {
      previousCustomHover.dispose();
      this.r.delete(htmlElement);
    }
    if (!tooltip) {
      htmlElement.removeAttribute("title");
      return;
    }
    let hoverTarget = htmlElement;
    if (this.a?.hoverTargetOverride) {
      if (!$Dj(htmlElement, this.a.hoverTargetOverride)) {
        throw new Error("hoverTargetOverrride must be an ancestor of the htmlElement");
      }
      hoverTarget = this.a.hoverTargetOverride;
    }
    if (this.n.showNativeHover) {
      let setupNativeHover2 = function(htmlElement2, tooltip2) {
        if ($zg(tooltip2)) {
          htmlElement2.title = $0l(tooltip2);
        } else if (tooltip2?.markdownNotSupportedFallback) {
          htmlElement2.title = tooltip2.markdownNotSupportedFallback;
        } else {
          htmlElement2.removeAttribute("title");
        }
      };
      var setupNativeHover = setupNativeHover2;
      setupNativeHover2(hoverTarget, tooltip);
    } else {
      const hoverDisposable = $J1().setupManagedHover(this.n, hoverTarget, tooltip);
      if (hoverDisposable) {
        this.r.set(htmlElement, hoverDisposable);
      }
    }
  }
  dispose() {
    super.dispose();
    for (const disposable of this.r.values()) {
      disposable.dispose();
    }
    this.r.clear();
  }
  t() {
    if (!this.h) {
      const suffixContainer = this.B(new FastLabelNode($ak(this.c, $("span.monaco-icon-suffix-container"))));
      this.h = this.B(new FastLabelNode($bk(suffixContainer.element, $("span.label-suffix"))));
    }
    return this.h;
  }
  u() {
    if (!this.g) {
      const descriptionContainer = this.B(new FastLabelNode($bk(this.j, $("span.monaco-icon-description-container"))));
      if (this.a?.supportDescriptionHighlights) {
        this.g = this.B(new $S2($bk(descriptionContainer.element, $("span.label-description")), { supportIcons: !!this.a.supportIcons }));
      } else {
        this.g = this.B(new FastLabelNode($bk(descriptionContainer.element, $("span.label-description"))));
      }
    }
    return this.g;
  }
};
var Label = class {
  constructor(d) {
    this.d = d;
    this.a = void 0;
    this.b = void 0;
  }
  setLabel(label3, options3) {
    if (this.a === label3 && $Pv(this.c, options3)) {
      return;
    }
    this.a = label3;
    this.c = options3;
    if (typeof label3 === "string") {
      if (!this.b) {
        this.d.innerText = "";
        this.d.classList.remove("multiple");
        this.b = $bk(this.d, $("a.label-name", { id: options3?.domId }));
      }
      this.b.textContent = label3;
    } else {
      this.d.innerText = "";
      this.d.classList.add("multiple");
      this.b = void 0;
      for (let i2 = 0; i2 < label3.length; i2++) {
        const l = label3[i2];
        const id2 = options3?.domId && `${options3?.domId}_${i2}`;
        $bk(this.d, $("a.label-name", { id: id2, "data-icon-label-count": label3.length, "data-icon-label-index": i2, "role": "treeitem" }, l));
        if (i2 < label3.length - 1) {
          $bk(this.d, $("span.label-separator", void 0, options3?.separator || "/"));
        }
      }
    }
  }
};
function splitMatches(labels2, separator, matches) {
  if (!matches) {
    return void 0;
  }
  let labelStart = 0;
  return labels2.map((label3) => {
    const labelRange = { start: labelStart, end: labelStart + label3.length };
    const result = matches.map((match) => Range2.intersect(labelRange, match)).filter((range) => !Range2.isEmpty(range)).map(({ start, end }) => ({ start: start - labelStart, end: end - labelStart }));
    labelStart = labelRange.end + separator.length;
    return result;
  });
}
var LabelWithHighlights = class extends $3c {
  constructor(f, g) {
    super();
    this.f = f;
    this.g = g;
    this.a = void 0;
    this.b = void 0;
  }
  setLabel(label3, options3) {
    if (this.a === label3 && $Pv(this.c, options3)) {
      return;
    }
    this.a = label3;
    this.c = options3;
    if (typeof label3 === "string") {
      if (!this.b) {
        this.f.innerText = "";
        this.f.classList.remove("multiple");
        this.b = this.B(new $S2($bk(this.f, $("a.label-name", { id: options3?.domId })), { supportIcons: this.g }));
      }
      this.b.set(label3, options3?.matches, void 0, options3?.labelEscapeNewLines);
    } else {
      this.f.innerText = "";
      this.f.classList.add("multiple");
      this.b = void 0;
      const separator = options3?.separator || "/";
      const matches = splitMatches(label3, separator, options3?.matches);
      for (let i2 = 0; i2 < label3.length; i2++) {
        const l = label3[i2];
        const m = matches ? matches[i2] : void 0;
        const id2 = options3?.domId && `${options3?.domId}_${i2}`;
        const name = $("a.label-name", { id: id2, "data-icon-label-count": label3.length, "data-icon-label-index": i2, "role": "treeitem" });
        const highlightedLabel = this.B(new $S2($bk(this.f, name), { supportIcons: this.g }));
        highlightedLabel.set(l, m, void 0, options3?.labelEscapeNewLines);
        if (i2 < label3.length - 1) {
          $bk(name, $("span.label-separator", void 0, separator));
        }
      }
    }
  }
};

// out-build/vs/platform/label/common/label.js
var $ZI = $Qk("labelService");
var Verbosity;
(function(Verbosity3) {
  Verbosity3[Verbosity3["SHORT"] = 0] = "SHORT";
  Verbosity3[Verbosity3["MEDIUM"] = 1] = "MEDIUM";
  Verbosity3[Verbosity3["LONG"] = 2] = "LONG";
})(Verbosity || (Verbosity = {}));

// out-build/vs/editor/contrib/gotoSymbol/browser/peek/referencesTree.js
var $bfb_1;
var $0eb = class $0eb2 {
  constructor(a) {
    this.a = a;
  }
  hasChildren(element) {
    if (element instanceof $9eb) {
      return true;
    }
    if (element instanceof $8eb) {
      return true;
    }
    return false;
  }
  getChildren(element) {
    if (element instanceof $9eb) {
      return element.groups;
    }
    if (element instanceof $8eb) {
      return element.resolve(this.a).then((val) => {
        return val.children;
      });
    }
    throw new Error("bad tree");
  }
};
$0eb = __decorate([
  __param(0, $oG)
], $0eb);
var $$eb = class {
  getHeight() {
    return 23;
  }
  getTemplateId(element) {
    if (element instanceof $8eb) {
      return $bfb.id;
    } else {
      return $cfb.id;
    }
  }
};
var $_eb = class $_eb2 {
  constructor(a) {
    this.a = a;
  }
  getKeyboardNavigationLabel(element) {
    if (element instanceof $6eb) {
      const parts = element.parent.getPreview(element)?.preview(element.range);
      if (parts) {
        return parts.value;
      }
    }
    return $sh(element.uri);
  }
  mightProducePrintableCharacter(event) {
    return this.a.mightProducePrintableCharacter(event);
  }
};
$_eb = __decorate([
  __param(0, $Ty)
], $_eb);
var $afb = class {
  getId(element) {
    return element instanceof $6eb ? element.id : element.uri;
  }
};
var FileReferencesTemplate = class FileReferencesTemplate2 extends $3c {
  constructor(container2, a) {
    super();
    this.a = a;
    const parent = document.createElement("div");
    parent.classList.add("reference-file");
    this.file = this.B(new $T2(parent, { supportHighlights: true }));
    this.badge = this.B(new $D2($bk(parent, $(".count")), {}, $E$));
    container2.appendChild(parent);
  }
  set(element, matches) {
    const parent = $uh(element.uri);
    this.file.setLabel(this.a.getUriBasenameLabel(element.uri), this.a.getUriLabel(parent, { relative: true }), { title: this.a.getUriLabel(element.uri), matches });
    const len = element.children.length;
    this.badge.setCount(len);
    if (len > 1) {
      this.badge.setTitleFormat(localize(1157, null, len));
    } else {
      this.badge.setTitleFormat(localize(1158, null, len));
    }
  }
};
FileReferencesTemplate = __decorate([
  __param(1, $ZI)
], FileReferencesTemplate);
var $bfb = class $bfb2 {
  static {
    $bfb_1 = this;
  }
  static {
    this.id = "FileReferencesRenderer";
  }
  constructor(a) {
    this.a = a;
    this.templateId = $bfb_1.id;
  }
  renderTemplate(container2) {
    return this.a.createInstance(FileReferencesTemplate, container2);
  }
  renderElement(node, index, template) {
    template.set(node.element, $Ul(node.filterData));
  }
  disposeTemplate(templateData) {
    templateData.dispose();
  }
};
$bfb = $bfb_1 = __decorate([
  __param(0, $Pk)
], $bfb);
var OneReferenceTemplate = class extends $3c {
  constructor(container2) {
    super();
    this.label = this.B(new $S2(container2));
  }
  set(element, score2) {
    const preview = element.parent.getPreview(element)?.preview(element.range);
    if (!preview || !preview.value) {
      this.label.set(`${$sh(element.uri)}:${element.range.startLineNumber + 1}:${element.range.startColumn + 1}`);
    } else {
      const { value, highlight } = preview;
      if (score2 && !FuzzyScore.isDefault(score2)) {
        this.label.element.classList.toggle("referenceMatch", false);
        this.label.set(value, $Ul(score2));
      } else {
        this.label.element.classList.toggle("referenceMatch", true);
        this.label.set(value, [highlight]);
      }
    }
  }
};
var $cfb = class _$cfb {
  constructor() {
    this.templateId = _$cfb.id;
  }
  static {
    this.id = "OneReferenceRenderer";
  }
  renderTemplate(container2) {
    return new OneReferenceTemplate(container2);
  }
  renderElement(node, index, templateData) {
    templateData.set(node.element, node.filterData);
  }
  disposeTemplate(templateData) {
    templateData.dispose();
  }
};
var $dfb = class {
  getWidgetAriaLabel() {
    return localize(1159, null);
  }
  getAriaLabel(element) {
    return element.ariaMessage;
  }
};

// out-build/vs/editor/contrib/gotoSymbol/browser/peek/referencesWidget.js
var DecorationsManager = class _DecorationsManager {
  static {
    this.a = $WI.register({
      description: "reference-decoration",
      stickiness: 1,
      className: "reference-decoration"
    });
  }
  constructor(g, h3) {
    this.g = g;
    this.h = h3;
    this.b = /* @__PURE__ */ new Map();
    this.c = /* @__PURE__ */ new Set();
    this.d = new $2c();
    this.f = new $2c();
    this.d.add(this.g.onDidChangeModel(() => this.j()));
    this.j();
  }
  dispose() {
    this.f.dispose();
    this.d.dispose();
    this.removeDecorations();
  }
  j() {
    this.f.clear();
    const model = this.g.getModel();
    if (!model) {
      return;
    }
    for (const ref of this.h.references) {
      if (ref.uri.toString() === model.uri.toString()) {
        this.k(ref.parent);
        return;
      }
    }
  }
  k(reference) {
    if (!this.g.hasModel()) {
      return;
    }
    this.f.add(this.g.getModel().onDidChangeDecorations(() => this.l()));
    const newDecorations = [];
    const newDecorationsActualIndex = [];
    for (let i2 = 0, len = reference.children.length; i2 < len; i2++) {
      const oneReference = reference.children[i2];
      if (this.c.has(oneReference.id)) {
        continue;
      }
      if (oneReference.uri.toString() !== this.g.getModel().uri.toString()) {
        continue;
      }
      newDecorations.push({
        range: oneReference.range,
        options: _DecorationsManager.a
      });
      newDecorationsActualIndex.push(i2);
    }
    this.g.changeDecorations((changeAccessor) => {
      const decorations = changeAccessor.deltaDecorations([], newDecorations);
      for (let i2 = 0; i2 < decorations.length; i2++) {
        this.b.set(decorations[i2], reference.children[newDecorationsActualIndex[i2]]);
      }
    });
  }
  l() {
    const toRemove = [];
    const model = this.g.getModel();
    if (!model) {
      return;
    }
    for (const [decorationId, reference] of this.b) {
      const newRange = model.getDecorationRange(decorationId);
      if (!newRange) {
        continue;
      }
      let ignore = false;
      if ($9C.equalsRange(newRange, reference.range)) {
        continue;
      }
      if ($9C.spansMultipleLines(newRange)) {
        ignore = true;
      } else {
        const lineLength = reference.range.endColumn - reference.range.startColumn;
        const newLineLength = newRange.endColumn - newRange.startColumn;
        if (lineLength !== newLineLength) {
          ignore = true;
        }
      }
      if (ignore) {
        this.c.add(reference.id);
        toRemove.push(decorationId);
      } else {
        reference.range = newRange;
      }
    }
    for (let i2 = 0, len = toRemove.length; i2 < len; i2++) {
      this.b.delete(toRemove[i2]);
    }
    this.g.removeDecorations(toRemove);
  }
  removeDecorations() {
    this.g.removeDecorations([...this.b.keys()]);
    this.b.clear();
  }
};
var $efb = class {
  constructor() {
    this.ratio = 0.7;
    this.heightInLines = 18;
  }
  static fromJSON(raw) {
    let ratio;
    let heightInLines;
    try {
      const data = JSON.parse(raw);
      ratio = data.ratio;
      heightInLines = data.heightInLines;
    } catch {
    }
    return {
      ratio: ratio || 0.7,
      heightInLines: heightInLines || 18
    };
  }
};
var ReferencesTree = class extends $4eb {
};
var $ffb = class $ffb2 extends $ceb {
  constructor(editor, kb, layoutData, themeService, lb, mb, nb, ob, pb) {
    super(editor, { showFrame: false, showArrow: true, isResizeable: true, isAccessible: true, supportOnTitleClick: true }, mb);
    this.kb = kb;
    this.layoutData = layoutData;
    this.lb = lb;
    this.mb = mb;
    this.nb = nb;
    this.ob = ob;
    this.pb = pb;
    this.c = new $2c();
    this.d = new $2c();
    this.m = new $ze();
    this.onDidSelectReference = this.m.event;
    this.ib = new $rj(0, 0);
    this.jb = false;
    this.qb(themeService.getColorTheme());
    this.d.add(themeService.onDidColorThemeChange(this.qb.bind(this)));
    this.nb.addExclusiveWidget(editor, this);
    this.create();
  }
  get isClosing() {
    return this.jb;
  }
  dispose() {
    this.jb = true;
    this.setModel(void 0);
    this.d.dispose();
    this.c.dispose();
    $Xc(this.db);
    $Xc(this.fb);
    $Xc(this.r);
    $Xc(this.eb);
    this.cb.dispose();
    super.dispose();
  }
  qb(theme) {
    const borderColor = theme.getColor($geb) || $Vn.transparent;
    this.style({
      arrowColor: borderColor,
      frameColor: borderColor,
      headerBackgroundColor: theme.getColor($deb) || $Vn.transparent,
      primaryHeadingColor: theme.getColor($eeb),
      secondaryHeadingColor: theme.getColor($feb)
    });
  }
  show(where) {
    super.show(where, this.layoutData.heightInLines || 18);
  }
  focusOnReferenceTree() {
    this.r.domFocus();
  }
  focusOnPreviewEditor() {
    this.db.focus();
  }
  isPreviewEditorFocused() {
    return this.db.hasTextFocus();
  }
  W(e) {
    if (this.db && this.db.getModel()) {
      this.m.fire({
        element: this.wb(),
        kind: e.ctrlKey || e.metaKey || e.altKey ? "side" : "open",
        source: "title"
      });
    }
  }
  X(containerElement) {
    this.A("reference-zone-widget");
    this.hb = $bk(containerElement, $("div.messages"));
    $ik(this.hb);
    this.cb = new $r2(containerElement, {
      orientation: 1
      /* Orientation.HORIZONTAL */
    });
    this.gb = $bk(containerElement, $("div.preview.inline"));
    const options3 = {
      scrollBeyondLastLine: false,
      scrollbar: {
        verticalScrollbarSize: 14,
        horizontal: "auto",
        useShadows: true,
        verticalHasArrows: false,
        horizontalHasArrows: false,
        alwaysConsumeMouseWheel: true
      },
      overviewRulerLanes: 2,
      fixedOverflowWidgets: true,
      minimap: {
        enabled: false
      }
    };
    this.db = this.mb.createInstance($bdb, this.gb, options3, {}, this.editor);
    $ik(this.gb);
    this.fb = this.mb.createInstance($QI, localize(1160, null), $KF, $QI.DEFAULT_CREATION_OPTIONS, null);
    this.bb = $bk(containerElement, $("div.ref-tree.inline"));
    const treeOptions = {
      keyboardSupport: this.kb,
      accessibilityProvider: new $dfb(),
      keyboardNavigationLabelProvider: this.mb.createInstance($_eb),
      identityProvider: new $afb(),
      openOnSingleClick: true,
      selectionNavigation: true,
      overrideStyles: {
        listBackground: $heb
      }
    };
    if (this.kb) {
      this.d.add($aj(this.bb, "keydown", (e) => {
        if (e.equals(
          9
          /* KeyCode.Escape */
        )) {
          this.pb.dispatchEvent(e, e.target);
          e.stopPropagation();
        }
      }, true));
    }
    this.r = this.mb.createInstance(ReferencesTree, "ReferencesWidget", this.bb, new $$eb(), [
      this.mb.createInstance($bfb),
      this.mb.createInstance($cfb)
    ], this.mb.createInstance($0eb), treeOptions);
    this.cb.addView({
      onDidChange: Event2.None,
      element: this.gb,
      minimumSize: 200,
      maximumSize: Number.MAX_VALUE,
      layout: (width2) => {
        this.db.layout({ height: this.ib.height, width: width2 });
      }
    }, Sizing.Distribute);
    this.cb.addView({
      onDidChange: Event2.None,
      element: this.bb,
      minimumSize: 100,
      maximumSize: Number.MAX_VALUE,
      layout: (width2) => {
        this.bb.style.height = `${this.ib.height}px`;
        this.bb.style.width = `${width2}px`;
        this.r.layout(this.ib.height, width2);
      }
    }, Sizing.Distribute);
    this.n.add(this.cb.onDidSashChange(() => {
      if (this.ib.width) {
        this.layoutData.ratio = this.cb.getViewSize(0) / this.ib.width;
      }
    }, void 0));
    const onEvent = (element, kind) => {
      if (element instanceof $6eb) {
        if (kind === "show") {
          this.yb(element, false);
        }
        this.m.fire({ element, kind, source: "tree" });
      }
    };
    this.n.add(this.r.onDidOpen((e) => {
      if (e.sideBySide) {
        onEvent(e.element, "side");
      } else if (e.editorOptions.pinned) {
        onEvent(e.element, "goto");
      } else {
        onEvent(e.element, "show");
      }
    }));
    $ik(this.bb);
  }
  C(width2) {
    if (this.ib) {
      this.ab(this.ib.height, width2);
    }
  }
  ab(heightInPixel, widthInPixel) {
    super.ab(heightInPixel, widthInPixel);
    this.ib = new $rj(widthInPixel, heightInPixel);
    this.layoutData.heightInLines = this.l ? this.l.heightInLines : this.layoutData.heightInLines;
    this.cb.layout(widthInPixel);
    this.cb.resizeView(0, widthInPixel * this.layoutData.ratio);
  }
  setSelection(selection) {
    return this.yb(selection, true).then(() => {
      if (!this.a) {
        return;
      }
      this.r.setSelection([selection]);
      this.r.setFocus([selection]);
    });
  }
  setModel(newModel) {
    this.c.clear();
    this.a = newModel;
    if (this.a) {
      return this.vb();
    }
    return Promise.resolve();
  }
  vb() {
    if (!this.a) {
      return Promise.resolve(void 0);
    }
    if (this.a.isEmpty) {
      this.setTitle("");
      this.hb.innerText = localize(1161, null);
      $hk(this.hb);
      return Promise.resolve(void 0);
    }
    $ik(this.hb);
    this.b = new DecorationsManager(this.db, this.a);
    this.c.add(this.b);
    this.c.add(this.a.onDidChangeReferenceRange((reference) => this.r.rerender(reference)));
    this.c.add(this.db.onMouseDown((e) => {
      const { event, target } = e;
      if (event.detail !== 2) {
        return;
      }
      const element = this.wb();
      if (!element) {
        return;
      }
      this.m.fire({
        element: { uri: element.uri, range: target.range },
        kind: event.ctrlKey || event.metaKey || event.altKey ? "side" : "open",
        source: "editor"
      });
    }));
    this.container.classList.add("results-loaded");
    $hk(this.bb);
    $hk(this.gb);
    this.cb.layout(this.ib.width);
    this.focusOnReferenceTree();
    return this.r.setInput(this.a.groups.length === 1 ? this.a.groups[0] : this.a);
  }
  wb() {
    const [element] = this.r.getFocus();
    if (element instanceof $6eb) {
      return element;
    } else if (element instanceof $8eb) {
      if (element.children.length > 0) {
        return element.children[0];
      }
    }
    return void 0;
  }
  async revealReference(reference) {
    await this.yb(reference, false);
    this.m.fire({ element: reference, kind: "goto", source: "tree" });
  }
  async yb(reference, revealParent) {
    if (this.xb === reference) {
      return;
    }
    this.xb = reference;
    if (reference.uri.scheme !== Schemas.inMemory) {
      this.setTitle($rh(reference.uri), this.ob.getUriLabel($uh(reference.uri)));
    } else {
      this.setTitle(localize(1162, null));
    }
    const promise = this.lb.createModelReference(reference.uri);
    if (this.r.getInput() === reference.parent) {
      this.r.reveal(reference);
    } else {
      if (revealParent) {
        this.r.reveal(reference.parent);
      }
      await this.r.expand(reference.parent);
      this.r.reveal(reference);
    }
    const ref = await promise;
    if (!this.a) {
      ref.dispose();
      return;
    }
    $Xc(this.eb);
    const model = ref.object;
    if (model) {
      const scrollType = this.db.getModel() === model.textEditorModel ? 0 : 1;
      const sel = $9C.lift(reference.range).collapseToStart();
      this.eb = ref;
      this.db.setModel(model.textEditorModel);
      this.db.setSelection(sel);
      this.db.revealRangeInCenter(sel, scrollType);
    } else {
      this.db.setModel(this.fb);
      ref.dispose();
    }
  }
};
$ffb = __decorate([
  __param(3, $gs),
  __param(4, $oG),
  __param(5, $Pk),
  __param(6, $aeb),
  __param(7, $ZI),
  __param(8, $Ty)
], $ffb);

// out-build/vs/editor/contrib/gotoSymbol/browser/peek/referencesController.js
var $hfb_1;
var $gfb = new $nn("referenceSearchVisible", false, localize(1154, null));
var $hfb = class $hfb2 {
  static {
    $hfb_1 = this;
  }
  static {
    this.ID = "editor.contrib.referencesController";
  }
  static get(editor) {
    return editor.getContribution($hfb_1.ID);
  }
  constructor(h3, i2, contextKeyService, j, k, l, m, n) {
    this.h = h3;
    this.i = i2;
    this.j = j;
    this.k = k;
    this.l = l;
    this.m = m;
    this.n = n;
    this.a = new $2c();
    this.e = 0;
    this.f = false;
    this.g = $gfb.bindTo(contextKeyService);
  }
  dispose() {
    this.g.reset();
    this.a.dispose();
    this.b?.dispose();
    this.c?.dispose();
    this.b = void 0;
    this.c = void 0;
  }
  toggleWidget(range, modelPromise, peekMode) {
    let widgetPosition;
    if (this.b) {
      widgetPosition = this.b.position;
    }
    this.closeWidget();
    if (!!widgetPosition && range.containsPosition(widgetPosition)) {
      return;
    }
    this.d = peekMode;
    this.g.set(true);
    this.a.add(this.i.onDidChangeModelLanguage(() => {
      this.closeWidget();
    }));
    this.a.add(this.i.onDidChangeModel(() => {
      if (!this.f) {
        this.closeWidget();
      }
    }));
    const storageKey = "peekViewLayout";
    const data = $efb.fromJSON(this.m.get(storageKey, 0, "{}"));
    this.b = this.l.createInstance($ffb, this.i, this.h, data);
    this.b.setTitle(localize(1155, null));
    this.b.show(range);
    this.a.add(this.b.onDidClose(() => {
      modelPromise.cancel();
      if (this.b) {
        this.m.store(
          storageKey,
          JSON.stringify(this.b.layoutData),
          0,
          1
          /* StorageTarget.MACHINE */
        );
        if (!this.b.isClosing) {
          this.closeWidget();
        }
        this.b = void 0;
      } else {
        this.closeWidget();
      }
    }));
    this.a.add(this.b.onDidSelectReference((event) => {
      const { element, kind } = event;
      if (!element) {
        return;
      }
      switch (kind) {
        case "open":
          if (event.source !== "editor" || !this.n.getValue("editor.stablePeek")) {
            this.openReference(element, false, false);
          }
          break;
        case "side":
          this.openReference(element, true, false);
          break;
        case "goto":
          if (peekMode) {
            this.o(element, true);
          } else {
            this.openReference(element, false, true);
          }
          break;
      }
    }));
    const requestId = ++this.e;
    modelPromise.then((model) => {
      if (requestId !== this.e || !this.b) {
        model.dispose();
        return void 0;
      }
      this.c?.dispose();
      this.c = model;
      return this.b.setModel(this.c).then(() => {
        if (this.b && this.c && this.i.hasModel()) {
          if (!this.c.isEmpty) {
            this.b.setMetaTitle(localize(1156, null, this.c.title, this.c.references.length));
          } else {
            this.b.setMetaTitle("");
          }
          const uri = this.i.getModel().uri;
          const pos = new $8C(range.startLineNumber, range.startColumn);
          const selection = this.c.nearestReference(uri, pos);
          if (selection) {
            return this.b.setSelection(selection).then(() => {
              if (this.b && this.i.getOption(
                91
                /* EditorOption.peekWidgetDefaultFocus */
              ) === "editor") {
                this.b.focusOnPreviewEditor();
              }
            });
          }
        }
        return void 0;
      });
    }, (error) => {
      this.k.error(error);
    });
  }
  changeFocusBetweenPreviewAndReferences() {
    if (!this.b) {
      return;
    }
    if (this.b.isPreviewEditorFocused()) {
      this.b.focusOnReferenceTree();
    } else {
      this.b.focusOnPreviewEditor();
    }
  }
  async goToNextOrPreviousReference(fwd) {
    if (!this.i.hasModel() || !this.c || !this.b) {
      return;
    }
    const currentPosition = this.b.position;
    if (!currentPosition) {
      return;
    }
    const source = this.c.nearestReference(this.i.getModel().uri, currentPosition);
    if (!source) {
      return;
    }
    const target = this.c.nextOrPreviousReference(source, fwd);
    const editorFocus = this.i.hasTextFocus();
    const previewEditorFocus = this.b.isPreviewEditorFocused();
    await this.b.setSelection(target);
    await this.o(target, false);
    if (editorFocus) {
      this.i.focus();
    } else if (this.b && previewEditorFocus) {
      this.b.focusOnPreviewEditor();
    }
  }
  async revealReference(reference) {
    if (!this.i.hasModel() || !this.c || !this.b) {
      return;
    }
    await this.b.revealReference(reference);
  }
  closeWidget(focusEditor = true) {
    this.b?.dispose();
    this.c?.dispose();
    this.g.reset();
    this.a.clear();
    this.b = void 0;
    this.c = void 0;
    if (focusEditor) {
      this.i.focus();
    }
    this.e += 1;
  }
  o(ref, pinned) {
    this.b?.hide();
    this.f = true;
    const range = $9C.lift(ref.range).collapseToStart();
    return this.j.openCodeEditor({
      resource: ref.uri,
      options: { selection: range, selectionSource: "code.jump", pinned }
    }, this.i).then((openedEditor) => {
      this.f = false;
      if (!openedEditor || !this.b) {
        this.closeWidget();
        return;
      }
      if (this.i === openedEditor) {
        this.b.show(range);
        this.b.focusOnReferenceTree();
      } else {
        const other = $hfb_1.get(openedEditor);
        const model = this.c.clone();
        this.closeWidget();
        openedEditor.focus();
        other?.toggleWidget(range, $Hh((_) => Promise.resolve(model)), this.d ?? false);
      }
    }, (err) => {
      this.f = false;
      $gb(err);
    });
  }
  openReference(ref, sideBySide, pinned) {
    if (!sideBySide) {
      this.closeWidget();
    }
    const { uri, range } = ref;
    this.j.openCodeEditor({
      resource: uri,
      options: { selection: range, selectionSource: "code.jump", pinned }
    }, this.i, sideBySide);
  }
};
$hfb = $hfb_1 = __decorate([
  __param(2, $on),
  __param(3, $U5),
  __param(4, $PJ),
  __param(5, $Pk),
  __param(6, $jv),
  __param(7, $kl)
], $hfb);
function withController(accessor, fn) {
  const outerEditor = $beb(accessor);
  if (!outerEditor) {
    return;
  }
  const controller = $hfb.get(outerEditor);
  if (controller) {
    fn(controller);
  }
}
$0I.registerCommandAndKeybindingRule({
  id: "togglePeekWidgetFocus",
  weight: 100,
  primary: $$e(
    2048 | 41,
    60
    /* KeyCode.F2 */
  ),
  when: $7m.or($gfb, PeekContext.inPeekEditor),
  handler(accessor) {
    withController(accessor, (controller) => {
      controller.changeFocusBetweenPreviewAndReferences();
    });
  }
});
$0I.registerCommandAndKeybindingRule({
  id: "goToNextReference",
  weight: 100 - 10,
  primary: 62,
  secondary: [
    70
    /* KeyCode.F12 */
  ],
  when: $7m.or($gfb, PeekContext.inPeekEditor),
  handler(accessor) {
    withController(accessor, (controller) => {
      controller.goToNextOrPreviousReference(true);
    });
  }
});
$0I.registerCommandAndKeybindingRule({
  id: "goToPreviousReference",
  weight: 100 - 10,
  primary: 1024 | 62,
  secondary: [
    1024 | 70
    /* KeyCode.F12 */
  ],
  when: $7m.or($gfb, PeekContext.inPeekEditor),
  handler(accessor) {
    withController(accessor, (controller) => {
      controller.goToNextOrPreviousReference(false);
    });
  }
});
$tn.registerCommandAlias("goToNextReferenceFromEmbeddedEditor", "goToNextReference");
$tn.registerCommandAlias("goToPreviousReferenceFromEmbeddedEditor", "goToPreviousReference");
$tn.registerCommandAlias("closeReferenceSearchEditor", "closeReferenceSearch");
$tn.registerCommand("closeReferenceSearch", (accessor) => withController(accessor, (controller) => controller.closeWidget()));
$0I.registerKeybindingRule({
  id: "closeReferenceSearch",
  weight: 100 - 101,
  primary: 9,
  secondary: [
    1024 | 9
    /* KeyCode.Escape */
  ],
  when: $7m.and(PeekContext.inPeekEditor, $7m.not("config.editor.stablePeek"))
});
$0I.registerKeybindingRule({
  id: "closeReferenceSearch",
  weight: 200 + 50,
  primary: 9,
  secondary: [
    1024 | 9
    /* KeyCode.Escape */
  ],
  when: $7m.and($gfb, $7m.not("config.editor.stablePeek"), $7m.or(EditorContextKeys.editorTextFocus, $Ceb.negate()))
});
$0I.registerCommandAndKeybindingRule({
  id: "revealReference",
  weight: 200,
  primary: 3,
  mac: {
    primary: 3,
    secondary: [
      2048 | 18
      /* KeyCode.DownArrow */
    ]
  },
  when: $7m.and($gfb, $Leb, $Reb.negate(), $Teb.negate()),
  handler(accessor) {
    const listService = accessor.get($Deb);
    const focus = listService.lastFocusedList?.getFocus();
    if (Array.isArray(focus) && focus[0] instanceof $6eb) {
      withController(accessor, (controller) => controller.revealReference(focus[0]));
    }
  }
});
$0I.registerCommandAndKeybindingRule({
  id: "openReferenceToSide",
  weight: 100,
  primary: 2048 | 3,
  mac: {
    primary: 256 | 3
    /* KeyCode.Enter */
  },
  when: $7m.and($gfb, $Leb, $Reb.negate(), $Teb.negate()),
  handler(accessor) {
    const listService = accessor.get($Deb);
    const focus = listService.lastFocusedList?.getFocus();
    if (Array.isArray(focus) && focus[0] instanceof $6eb) {
      withController(accessor, (controller) => controller.openReference(focus[0], true, true));
    }
  }
});
$tn.registerCommand("openReference", (accessor) => {
  const listService = accessor.get($Deb);
  const focus = listService.lastFocusedList?.getFocus();
  if (Array.isArray(focus) && focus[0] instanceof $6eb) {
    withController(accessor, (controller) => controller.openReference(focus[0], false, true));
  }
});

// out-build/vs/editor/contrib/gotoSymbol/browser/symbolNavigation.js
var $ifb = new $nn("hasSymbols", false, localize(1171, null));
var $jfb = $Qk("ISymbolNavigationService");
var SymbolNavigationService = class SymbolNavigationService2 {
  constructor(contextKeyService, g, h3, i2) {
    this.g = g;
    this.h = h3;
    this.i = i2;
    this.b = void 0;
    this.c = -1;
    this.f = false;
    this.a = $ifb.bindTo(contextKeyService);
  }
  reset() {
    this.a.reset();
    this.d?.dispose();
    this.e?.dispose();
    this.b = void 0;
    this.c = -1;
  }
  put(anchor) {
    const refModel = anchor.parent.parent;
    if (refModel.references.length <= 1) {
      this.reset();
      return;
    }
    this.b = refModel;
    this.c = refModel.references.indexOf(anchor);
    this.a.set(true);
    this.j();
    const editorState = new EditorState(this.g);
    const listener = editorState.onDidChange((_) => {
      if (this.f) {
        return;
      }
      const editor = this.g.getActiveCodeEditor();
      if (!editor) {
        return;
      }
      const model = editor.getModel();
      const position = editor.getPosition();
      if (!model || !position) {
        return;
      }
      let seenUri = false;
      let seenPosition = false;
      for (const reference of refModel.references) {
        if ($oh(reference.uri, model.uri)) {
          seenUri = true;
          seenPosition = seenPosition || $9C.containsPosition(reference.range, position);
        } else if (seenUri) {
          break;
        }
      }
      if (!seenUri || !seenPosition) {
        this.reset();
      }
    });
    this.d = $Zc(editorState, listener);
  }
  revealNext(source) {
    if (!this.b) {
      return Promise.resolve();
    }
    this.c += 1;
    this.c %= this.b.references.length;
    const reference = this.b.references[this.c];
    this.j();
    this.f = true;
    return this.g.openCodeEditor({
      resource: reference.uri,
      options: {
        selection: $9C.collapseToStart(reference.range),
        selectionRevealType: 3
        /* TextEditorSelectionRevealType.NearTopIfOutsideViewport */
      }
    }, source).finally(() => {
      this.f = false;
    });
  }
  j() {
    this.e?.dispose();
    const kb = this.i.lookupKeybinding("editor.gotoNextSymbolFromResult");
    const message = kb ? localize(1172, null, this.c + 1, this.b.references.length, kb.getLabel()) : localize(1173, null, this.c + 1, this.b.references.length);
    this.e = this.h.status(message);
  }
};
SymbolNavigationService = __decorate([
  __param(0, $on),
  __param(1, $U5),
  __param(2, $PJ),
  __param(3, $Ty)
], SymbolNavigationService);
$SC(
  $jfb,
  SymbolNavigationService,
  1
  /* InstantiationType.Delayed */
);
$45(new class extends $Y5 {
  constructor() {
    super({
      id: "editor.gotoNextSymbolFromResult",
      precondition: $ifb,
      kbOpts: {
        weight: 100,
        primary: 70
        /* KeyCode.F12 */
      }
    });
  }
  runEditorCommand(accessor, editor) {
    return accessor.get($jfb).revealNext(editor);
  }
}());
$0I.registerCommandAndKeybindingRule({
  id: "editor.gotoNextSymbolFromResult.cancel",
  weight: 100,
  when: $ifb,
  primary: 9,
  handler(accessor) {
    accessor.get($jfb).reset();
  }
});
var EditorState = class EditorState2 {
  constructor(editorService) {
    this.a = /* @__PURE__ */ new Map();
    this.b = new $2c();
    this.c = new $ze();
    this.onDidChange = this.c.event;
    this.b.add(editorService.onCodeEditorRemove(this.e, this));
    this.b.add(editorService.onCodeEditorAdd(this.d, this));
    editorService.listCodeEditors().forEach(this.d, this);
  }
  dispose() {
    this.b.dispose();
    this.c.dispose();
    $Xc(this.a.values());
  }
  d(editor) {
    this.a.set(editor, $Zc(editor.onDidChangeCursorPosition((_) => this.c.fire({ editor })), editor.onDidChangeModelContent((_) => this.c.fire({ editor }))));
  }
  e(editor) {
    this.a.get(editor)?.dispose();
    this.a.delete(editor);
  }
};
EditorState = __decorate([
  __param(0, $U5)
], EditorState);

// out-build/vs/editor/contrib/gotoSymbol/browser/goToSymbol.js
function shouldIncludeLocationLink(sourceModel, loc) {
  if (loc.uri.scheme === sourceModel.uri.scheme) {
    return true;
  }
  if ($$g(loc.uri, Schemas.walkThroughSnippet, Schemas.vscodeChatCodeBlock, Schemas.vscodeChatCodeCompareBlock)) {
    return false;
  }
  return true;
}
async function getLocationLinks(model, position, registry4, recursive, provide) {
  const provider = registry4.ordered(model, recursive);
  const promises = provider.map((provider2) => {
    return Promise.resolve(provide(provider2, model, position)).then(void 0, (err) => {
      $hb(err);
      return void 0;
    });
  });
  const values = await Promise.all(promises);
  return $Mb(values.flat()).filter((loc) => shouldIncludeLocationLink(model, loc));
}
function $kfb(registry4, model, position, recursive, token) {
  return getLocationLinks(model, position, registry4, recursive, (provider, model2, position2) => {
    return provider.provideDefinition(model2, position2, token);
  });
}
function $lfb(registry4, model, position, recursive, token) {
  return getLocationLinks(model, position, registry4, recursive, (provider, model2, position2) => {
    return provider.provideDeclaration(model2, position2, token);
  });
}
function $mfb(registry4, model, position, recursive, token) {
  return getLocationLinks(model, position, registry4, recursive, (provider, model2, position2) => {
    return provider.provideImplementation(model2, position2, token);
  });
}
function $nfb(registry4, model, position, recursive, token) {
  return getLocationLinks(model, position, registry4, recursive, (provider, model2, position2) => {
    return provider.provideTypeDefinition(model2, position2, token);
  });
}
function $ofb(registry4, model, position, compact, recursive, token) {
  return getLocationLinks(model, position, registry4, recursive, async (provider, model2, position2) => {
    const result = (await provider.provideReferences(model2, position2, { includeDeclaration: true }, token))?.filter((ref) => shouldIncludeLocationLink(model2, ref));
    if (!compact || !result || result.length !== 2) {
      return result;
    }
    const resultWithoutDeclaration = (await provider.provideReferences(model2, position2, { includeDeclaration: false }, token))?.filter((ref) => shouldIncludeLocationLink(model2, ref));
    if (resultWithoutDeclaration && resultWithoutDeclaration.length === 1) {
      return resultWithoutDeclaration;
    }
    return result;
  });
}
async function _sortedAndDeduped(callback) {
  const rawLinks = await callback();
  const model = new $9eb(rawLinks, "");
  const modelLinks = model.references.map((ref) => ref.link);
  model.dispose();
  return modelLinks;
}
$35("_executeDefinitionProvider", (accessor, model, position) => {
  const languageFeaturesService = accessor.get($mP);
  const promise = $kfb(languageFeaturesService.definitionProvider, model, position, false, CancellationToken.None);
  return _sortedAndDeduped(() => promise);
});
$35("_executeDefinitionProvider_recursive", (accessor, model, position) => {
  const languageFeaturesService = accessor.get($mP);
  const promise = $kfb(languageFeaturesService.definitionProvider, model, position, true, CancellationToken.None);
  return _sortedAndDeduped(() => promise);
});
$35("_executeTypeDefinitionProvider", (accessor, model, position) => {
  const languageFeaturesService = accessor.get($mP);
  const promise = $nfb(languageFeaturesService.typeDefinitionProvider, model, position, false, CancellationToken.None);
  return _sortedAndDeduped(() => promise);
});
$35("_executeTypeDefinitionProvider_recursive", (accessor, model, position) => {
  const languageFeaturesService = accessor.get($mP);
  const promise = $nfb(languageFeaturesService.typeDefinitionProvider, model, position, true, CancellationToken.None);
  return _sortedAndDeduped(() => promise);
});
$35("_executeDeclarationProvider", (accessor, model, position) => {
  const languageFeaturesService = accessor.get($mP);
  const promise = $lfb(languageFeaturesService.declarationProvider, model, position, false, CancellationToken.None);
  return _sortedAndDeduped(() => promise);
});
$35("_executeDeclarationProvider_recursive", (accessor, model, position) => {
  const languageFeaturesService = accessor.get($mP);
  const promise = $lfb(languageFeaturesService.declarationProvider, model, position, true, CancellationToken.None);
  return _sortedAndDeduped(() => promise);
});
$35("_executeReferenceProvider", (accessor, model, position) => {
  const languageFeaturesService = accessor.get($mP);
  const promise = $ofb(languageFeaturesService.referenceProvider, model, position, false, false, CancellationToken.None);
  return _sortedAndDeduped(() => promise);
});
$35("_executeReferenceProvider_recursive", (accessor, model, position) => {
  const languageFeaturesService = accessor.get($mP);
  const promise = $ofb(languageFeaturesService.referenceProvider, model, position, false, true, CancellationToken.None);
  return _sortedAndDeduped(() => promise);
});
$35("_executeImplementationProvider", (accessor, model, position) => {
  const languageFeaturesService = accessor.get($mP);
  const promise = $mfb(languageFeaturesService.implementationProvider, model, position, false, CancellationToken.None);
  return _sortedAndDeduped(() => promise);
});
$35("_executeImplementationProvider_recursive", (accessor, model, position) => {
  const languageFeaturesService = accessor.get($mP);
  const promise = $mfb(languageFeaturesService.implementationProvider, model, position, true, CancellationToken.None);
  return _sortedAndDeduped(() => promise);
});

// out-build/vs/editor/contrib/gotoSymbol/browser/goToCommands.js
$dJ.appendMenuItem($bJ.EditorContext, {
  submenu: $bJ.EditorContextPeek,
  title: localize(1114, null),
  group: "navigation",
  order: 100
});
var $pfb = class _$pfb {
  static is(thing) {
    if (!thing || typeof thing !== "object") {
      return false;
    }
    if (thing instanceof _$pfb) {
      return true;
    }
    if ($8C.isIPosition(thing.position) && thing.model) {
      return true;
    }
    return false;
  }
  constructor(model, position) {
    this.model = model;
    this.position = position;
  }
};
var $qfb = class _$qfb extends $25 {
  static {
    this.d = /* @__PURE__ */ new Map();
  }
  static {
    this.f = /* @__PURE__ */ new Set();
  }
  static all() {
    return _$qfb.d.values();
  }
  static g(opts) {
    const result = { ...opts, f1: true };
    if (result.menu) {
      for (const item of Iterable.wrap(result.menu)) {
        if (item.id === $bJ.EditorContext || item.id === $bJ.EditorContextPeek) {
          item.when = $7m.and(opts.precondition, item.when);
        }
      }
    }
    return result;
  }
  constructor(configuration2, opts) {
    super(_$qfb.g(opts));
    this.configuration = configuration2;
    _$qfb.d.set(opts.id, this);
  }
  runEditorCommand(accessor, editor, arg, range) {
    if (!editor.hasModel()) {
      return Promise.resolve(void 0);
    }
    const notificationService = accessor.get($PJ);
    const editorService = accessor.get($U5);
    const progressService = accessor.get($ZJ);
    const symbolNavService = accessor.get($jfb);
    const languageFeaturesService = accessor.get($mP);
    const instaService = accessor.get($Pk);
    const model = editor.getModel();
    const position = editor.getPosition();
    const anchor = $pfb.is(arg) ? arg : new $pfb(model, position);
    const cts = new $N_(
      editor,
      1 | 4
      /* CodeEditorStateFlag.Position */
    );
    const promise = $Ih(this.h(languageFeaturesService, anchor.model, anchor.position, cts.token), cts.token).then(async (references) => {
      if (!references || cts.token.isCancellationRequested) {
        return;
      }
      $$Z(references.ariaMessage);
      let altAction;
      if (references.referenceAt(model.uri, position)) {
        const altActionId = this.k(editor);
        if (!_$qfb.f.has(altActionId) && _$qfb.d.has(altActionId)) {
          altAction = _$qfb.d.get(altActionId);
        }
      }
      const referenceCount = references.references.length;
      if (referenceCount === 0) {
        if (!this.configuration.muteMessage) {
          const info = model.getWordAtPosition(position);
          $S_.get(editor)?.showMessage(this.j(info), position);
        }
      } else if (referenceCount === 1 && altAction) {
        _$qfb.f.add(this.desc.id);
        instaService.invokeFunction((accessor2) => altAction.runEditorCommand(accessor2, editor, arg, range).finally(() => {
          _$qfb.f.delete(this.desc.id);
        }));
      } else {
        return this.m(editorService, symbolNavService, editor, references, range);
      }
    }, (err) => {
      notificationService.error(err);
    }).finally(() => {
      cts.dispose();
    });
    progressService.showWhile(promise, 250);
    return promise;
  }
  async m(editorService, symbolNavService, editor, model, range) {
    const gotoLocation = this.l(editor);
    if (!(editor instanceof $bdb) && (this.configuration.openInPeek || gotoLocation === "peek" && model.references.length > 1)) {
      this.o(editor, model, range);
    } else {
      const next = model.firstReference();
      const peek = model.references.length > 1 && gotoLocation === "gotoAndPeek";
      const targetEditor = await this.n(editor, editorService, next, this.configuration.openToSide, !peek);
      if (peek && targetEditor) {
        this.o(targetEditor, model, range);
      } else {
        model.dispose();
      }
      if (gotoLocation === "goto") {
        symbolNavService.put(next);
      }
    }
  }
  async n(editor, editorService, reference, sideBySide, highlight) {
    let range = void 0;
    if ($RE(reference)) {
      range = reference.targetSelectionRange;
    }
    if (!range) {
      range = reference.range;
    }
    if (!range) {
      return void 0;
    }
    const targetEditor = await editorService.openCodeEditor({
      resource: reference.uri,
      options: {
        selection: $9C.collapseToStart(range),
        selectionRevealType: 3,
        selectionSource: "code.jump"
        /* TextEditorSelectionSource.JUMP */
      }
    }, editor, sideBySide);
    if (!targetEditor) {
      return void 0;
    }
    if (highlight) {
      const modelNow = targetEditor.getModel();
      const decorations = targetEditor.createDecorationsCollection([{ range, options: { description: "symbol-navigate-action-highlight", className: "symbolHighlight" } }]);
      setTimeout(() => {
        if (targetEditor.getModel() === modelNow) {
          decorations.clear();
        }
      }, 350);
    }
    return targetEditor;
  }
  o(target, model, range) {
    const controller = $hfb.get(target);
    if (controller && target.hasModel()) {
      controller.toggleWidget(range ?? target.getSelection(), $Hh((_) => Promise.resolve(model)), this.configuration.openInPeek);
    } else {
      model.dispose();
    }
  }
};
var $rfb = class extends $qfb {
  async h(languageFeaturesService, model, position, token) {
    return new $9eb(await $kfb(languageFeaturesService.definitionProvider, model, position, false, token), localize(1115, null));
  }
  j(info) {
    return info && info.word ? localize(1116, null, info.word) : localize(1117, null);
  }
  k(editor) {
    return editor.getOption(
      60
      /* EditorOption.gotoLocation */
    ).alternativeDefinitionCommand;
  }
  l(editor) {
    return editor.getOption(
      60
      /* EditorOption.gotoLocation */
    ).multipleDefinitions;
  }
};
$hJ(class GoToDefinitionAction extends $rfb {
  static {
    this.id = "editor.action.revealDefinition";
  }
  constructor() {
    super({
      openToSide: false,
      openInPeek: false,
      muteMessage: false
    }, {
      id: GoToDefinitionAction.id,
      title: {
        ...localize2(1141, "Go to Definition"),
        mnemonicTitle: localize(1118, null)
      },
      precondition: EditorContextKeys.hasDefinitionProvider,
      keybinding: [{
        when: EditorContextKeys.editorTextFocus,
        primary: 70,
        weight: 100
        /* KeybindingWeight.EditorContrib */
      }, {
        when: $7m.and(EditorContextKeys.editorTextFocus, $veb),
        primary: 2048 | 70,
        weight: 100
        /* KeybindingWeight.EditorContrib */
      }],
      menu: [{
        id: $bJ.EditorContext,
        group: "navigation",
        order: 1.1
      }, {
        id: $bJ.MenubarGoMenu,
        precondition: null,
        group: "4_symbol_nav",
        order: 2
      }]
    });
    $tn.registerCommandAlias("editor.action.goToDeclaration", GoToDefinitionAction.id);
  }
});
$hJ(class OpenDefinitionToSideAction extends $rfb {
  static {
    this.id = "editor.action.revealDefinitionAside";
  }
  constructor() {
    super({
      openToSide: true,
      openInPeek: false,
      muteMessage: false
    }, {
      id: OpenDefinitionToSideAction.id,
      title: localize2(1142, "Open Definition to the Side"),
      precondition: $7m.and(EditorContextKeys.hasDefinitionProvider, EditorContextKeys.isInEmbeddedEditor.toNegated()),
      keybinding: [{
        when: EditorContextKeys.editorTextFocus,
        primary: $$e(
          2048 | 41,
          70
          /* KeyCode.F12 */
        ),
        weight: 100
        /* KeybindingWeight.EditorContrib */
      }, {
        when: $7m.and(EditorContextKeys.editorTextFocus, $veb),
        primary: $$e(
          2048 | 41,
          2048 | 70
          /* KeyCode.F12 */
        ),
        weight: 100
        /* KeybindingWeight.EditorContrib */
      }]
    });
    $tn.registerCommandAlias("editor.action.openDeclarationToTheSide", OpenDefinitionToSideAction.id);
  }
});
$hJ(class PeekDefinitionAction extends $rfb {
  static {
    this.id = "editor.action.peekDefinition";
  }
  constructor() {
    super({
      openToSide: false,
      openInPeek: true,
      muteMessage: false
    }, {
      id: PeekDefinitionAction.id,
      title: localize2(1143, "Peek Definition"),
      precondition: $7m.and(EditorContextKeys.hasDefinitionProvider, PeekContext.notInPeekEditor, EditorContextKeys.isInEmbeddedEditor.toNegated()),
      keybinding: {
        when: EditorContextKeys.editorTextFocus,
        primary: 512 | 70,
        linux: {
          primary: 2048 | 1024 | 68
          /* KeyCode.F10 */
        },
        weight: 100
        /* KeybindingWeight.EditorContrib */
      },
      menu: {
        id: $bJ.EditorContextPeek,
        group: "peek",
        order: 2
      }
    });
    $tn.registerCommandAlias("editor.action.previewDeclaration", PeekDefinitionAction.id);
  }
});
var DeclarationAction = class extends $qfb {
  async h(languageFeaturesService, model, position, token) {
    return new $9eb(await $lfb(languageFeaturesService.declarationProvider, model, position, false, token), localize(1119, null));
  }
  j(info) {
    return info && info.word ? localize(1120, null, info.word) : localize(1121, null);
  }
  k(editor) {
    return editor.getOption(
      60
      /* EditorOption.gotoLocation */
    ).alternativeDeclarationCommand;
  }
  l(editor) {
    return editor.getOption(
      60
      /* EditorOption.gotoLocation */
    ).multipleDeclarations;
  }
};
$hJ(class GoToDeclarationAction extends DeclarationAction {
  static {
    this.id = "editor.action.revealDeclaration";
  }
  constructor() {
    super({
      openToSide: false,
      openInPeek: false,
      muteMessage: false
    }, {
      id: GoToDeclarationAction.id,
      title: {
        ...localize2(1144, "Go to Declaration"),
        mnemonicTitle: localize(1122, null)
      },
      precondition: $7m.and(EditorContextKeys.hasDeclarationProvider, EditorContextKeys.isInEmbeddedEditor.toNegated()),
      menu: [{
        id: $bJ.EditorContext,
        group: "navigation",
        order: 1.3
      }, {
        id: $bJ.MenubarGoMenu,
        precondition: null,
        group: "4_symbol_nav",
        order: 3
      }]
    });
  }
  j(info) {
    return info && info.word ? localize(1123, null, info.word) : localize(1124, null);
  }
});
$hJ(class PeekDeclarationAction extends DeclarationAction {
  constructor() {
    super({
      openToSide: false,
      openInPeek: true,
      muteMessage: false
    }, {
      id: "editor.action.peekDeclaration",
      title: localize2(1145, "Peek Declaration"),
      precondition: $7m.and(EditorContextKeys.hasDeclarationProvider, PeekContext.notInPeekEditor, EditorContextKeys.isInEmbeddedEditor.toNegated()),
      menu: {
        id: $bJ.EditorContextPeek,
        group: "peek",
        order: 3
      }
    });
  }
});
var TypeDefinitionAction = class extends $qfb {
  async h(languageFeaturesService, model, position, token) {
    return new $9eb(await $nfb(languageFeaturesService.typeDefinitionProvider, model, position, false, token), localize(1125, null));
  }
  j(info) {
    return info && info.word ? localize(1126, null, info.word) : localize(1127, null);
  }
  k(editor) {
    return editor.getOption(
      60
      /* EditorOption.gotoLocation */
    ).alternativeTypeDefinitionCommand;
  }
  l(editor) {
    return editor.getOption(
      60
      /* EditorOption.gotoLocation */
    ).multipleTypeDefinitions;
  }
};
$hJ(class GoToTypeDefinitionAction extends TypeDefinitionAction {
  static {
    this.ID = "editor.action.goToTypeDefinition";
  }
  constructor() {
    super({
      openToSide: false,
      openInPeek: false,
      muteMessage: false
    }, {
      id: GoToTypeDefinitionAction.ID,
      title: {
        ...localize2(1146, "Go to Type Definition"),
        mnemonicTitle: localize(1128, null)
      },
      precondition: EditorContextKeys.hasTypeDefinitionProvider,
      keybinding: {
        when: EditorContextKeys.editorTextFocus,
        primary: 0,
        weight: 100
        /* KeybindingWeight.EditorContrib */
      },
      menu: [{
        id: $bJ.EditorContext,
        group: "navigation",
        order: 1.4
      }, {
        id: $bJ.MenubarGoMenu,
        precondition: null,
        group: "4_symbol_nav",
        order: 3
      }]
    });
  }
});
$hJ(class PeekTypeDefinitionAction extends TypeDefinitionAction {
  static {
    this.ID = "editor.action.peekTypeDefinition";
  }
  constructor() {
    super({
      openToSide: false,
      openInPeek: true,
      muteMessage: false
    }, {
      id: PeekTypeDefinitionAction.ID,
      title: localize2(1147, "Peek Type Definition"),
      precondition: $7m.and(EditorContextKeys.hasTypeDefinitionProvider, PeekContext.notInPeekEditor, EditorContextKeys.isInEmbeddedEditor.toNegated()),
      menu: {
        id: $bJ.EditorContextPeek,
        group: "peek",
        order: 4
      }
    });
  }
});
var ImplementationAction = class extends $qfb {
  async h(languageFeaturesService, model, position, token) {
    return new $9eb(await $mfb(languageFeaturesService.implementationProvider, model, position, false, token), localize(1129, null));
  }
  j(info) {
    return info && info.word ? localize(1130, null, info.word) : localize(1131, null);
  }
  k(editor) {
    return editor.getOption(
      60
      /* EditorOption.gotoLocation */
    ).alternativeImplementationCommand;
  }
  l(editor) {
    return editor.getOption(
      60
      /* EditorOption.gotoLocation */
    ).multipleImplementations;
  }
};
$hJ(class GoToImplementationAction extends ImplementationAction {
  static {
    this.ID = "editor.action.goToImplementation";
  }
  constructor() {
    super({
      openToSide: false,
      openInPeek: false,
      muteMessage: false
    }, {
      id: GoToImplementationAction.ID,
      title: {
        ...localize2(1148, "Go to Implementations"),
        mnemonicTitle: localize(1132, null)
      },
      precondition: EditorContextKeys.hasImplementationProvider,
      keybinding: {
        when: EditorContextKeys.editorTextFocus,
        primary: 2048 | 70,
        weight: 100
        /* KeybindingWeight.EditorContrib */
      },
      menu: [{
        id: $bJ.EditorContext,
        group: "navigation",
        order: 1.45
      }, {
        id: $bJ.MenubarGoMenu,
        precondition: null,
        group: "4_symbol_nav",
        order: 4
      }]
    });
  }
});
$hJ(class PeekImplementationAction extends ImplementationAction {
  static {
    this.ID = "editor.action.peekImplementation";
  }
  constructor() {
    super({
      openToSide: false,
      openInPeek: true,
      muteMessage: false
    }, {
      id: PeekImplementationAction.ID,
      title: localize2(1149, "Peek Implementations"),
      precondition: $7m.and(EditorContextKeys.hasImplementationProvider, PeekContext.notInPeekEditor, EditorContextKeys.isInEmbeddedEditor.toNegated()),
      keybinding: {
        when: EditorContextKeys.editorTextFocus,
        primary: 2048 | 1024 | 70,
        weight: 100
        /* KeybindingWeight.EditorContrib */
      },
      menu: {
        id: $bJ.EditorContextPeek,
        group: "peek",
        order: 5
      }
    });
  }
});
var ReferencesAction = class extends $qfb {
  j(info) {
    return info ? localize(1133, null, info.word) : localize(1134, null);
  }
  k(editor) {
    return editor.getOption(
      60
      /* EditorOption.gotoLocation */
    ).alternativeReferenceCommand;
  }
  l(editor) {
    return editor.getOption(
      60
      /* EditorOption.gotoLocation */
    ).multipleReferences;
  }
};
$hJ(class GoToReferencesAction extends ReferencesAction {
  constructor() {
    super({
      openToSide: false,
      openInPeek: false,
      muteMessage: false
    }, {
      id: "editor.action.goToReferences",
      title: {
        ...localize2(1150, "Go to References"),
        mnemonicTitle: localize(1135, null)
      },
      precondition: $7m.and(EditorContextKeys.hasReferenceProvider, PeekContext.notInPeekEditor, EditorContextKeys.isInEmbeddedEditor.toNegated()),
      keybinding: {
        when: EditorContextKeys.editorTextFocus,
        primary: 1024 | 70,
        weight: 100
        /* KeybindingWeight.EditorContrib */
      },
      menu: [{
        id: $bJ.EditorContext,
        group: "navigation",
        order: 1.45
      }, {
        id: $bJ.MenubarGoMenu,
        precondition: null,
        group: "4_symbol_nav",
        order: 5
      }]
    });
  }
  async h(languageFeaturesService, model, position, token) {
    return new $9eb(await $ofb(languageFeaturesService.referenceProvider, model, position, true, false, token), localize(1136, null));
  }
});
$hJ(class PeekReferencesAction extends ReferencesAction {
  constructor() {
    super({
      openToSide: false,
      openInPeek: true,
      muteMessage: false
    }, {
      id: "editor.action.referenceSearch.trigger",
      title: localize2(1151, "Peek References"),
      precondition: $7m.and(EditorContextKeys.hasReferenceProvider, PeekContext.notInPeekEditor, EditorContextKeys.isInEmbeddedEditor.toNegated()),
      menu: {
        id: $bJ.EditorContextPeek,
        group: "peek",
        order: 6
      }
    });
  }
  async h(languageFeaturesService, model, position, token) {
    return new $9eb(await $ofb(languageFeaturesService.referenceProvider, model, position, false, false, token), localize(1137, null));
  }
});
var GenericGoToLocationAction = class extends $qfb {
  constructor(config, e, p) {
    super(config, {
      id: "editor.action.goToLocation",
      title: localize2(1152, "Go to Any Symbol"),
      precondition: $7m.and(PeekContext.notInPeekEditor, EditorContextKeys.isInEmbeddedEditor.toNegated())
    });
    this.e = e;
    this.p = p;
  }
  async h(languageFeaturesService, _model, _position, _token) {
    return new $9eb(this.e, localize(1138, null));
  }
  j(info) {
    return info && localize(1139, null, info.word) || "";
  }
  l(editor) {
    return this.p ?? editor.getOption(
      60
      /* EditorOption.gotoLocation */
    ).multipleReferences;
  }
  k() {
    return "";
  }
};
$tn.registerCommand({
  id: "editor.action.goToLocations",
  metadata: {
    description: "Go to locations from a position in a file",
    args: [
      { name: "uri", description: "The text document in which to start", constraint: URI },
      { name: "position", description: "The position at which to start", constraint: $8C.isIPosition },
      { name: "locations", description: "An array of locations.", constraint: Array },
      { name: "multiple", description: "Define what to do when having multiple results, either `peek`, `gotoAndPeek`, or `goto`" },
      { name: "noResultsMessage", description: "Human readable message that shows when locations is empty." }
    ]
  },
  handler: async (accessor, resource, position, references, multiple, noResultsMessage, openInPeek) => {
    $Jg(URI.isUri(resource));
    $Jg($8C.isIPosition(position));
    $Jg(Array.isArray(references));
    $Jg(typeof multiple === "undefined" || typeof multiple === "string");
    $Jg(typeof openInPeek === "undefined" || typeof openInPeek === "boolean");
    const editorService = accessor.get($U5);
    const editor = await editorService.openCodeEditor({ resource }, editorService.getFocusedCodeEditor());
    if ($P5(editor)) {
      editor.setPosition(position);
      editor.revealPositionInCenterIfOutsideViewport(
        position,
        0
        /* ScrollType.Smooth */
      );
      return editor.invokeWithinContext((accessor2) => {
        const command4 = new class extends GenericGoToLocationAction {
          j(info) {
            return noResultsMessage || super.j(info);
          }
        }({
          muteMessage: !Boolean(noResultsMessage),
          openInPeek: Boolean(openInPeek),
          openToSide: false
        }, references, multiple);
        accessor2.get($Pk).invokeFunction(command4.run.bind(command4), editor);
      });
    }
  }
});
$tn.registerCommand({
  id: "editor.action.peekLocations",
  metadata: {
    description: "Peek locations from a position in a file",
    args: [
      { name: "uri", description: "The text document in which to start", constraint: URI },
      { name: "position", description: "The position at which to start", constraint: $8C.isIPosition },
      { name: "locations", description: "An array of locations.", constraint: Array },
      { name: "multiple", description: "Define what to do when having multiple results, either `peek`, `gotoAndPeek`, or `goto`" }
    ]
  },
  handler: async (accessor, resource, position, references, multiple) => {
    accessor.get($sn).executeCommand("editor.action.goToLocations", resource, position, references, multiple, void 0, true);
  }
});
$tn.registerCommand({
  id: "editor.action.findReferences",
  handler: (accessor, resource, position) => {
    $Jg(URI.isUri(resource));
    $Jg($8C.isIPosition(position));
    const languageFeaturesService = accessor.get($mP);
    const codeEditorService = accessor.get($U5);
    return codeEditorService.openCodeEditor({ resource }, codeEditorService.getFocusedCodeEditor()).then((control) => {
      if (!$P5(control) || !control.hasModel()) {
        return void 0;
      }
      const controller = $hfb.get(control);
      if (!controller) {
        return void 0;
      }
      const references = $Hh((token) => $ofb(languageFeaturesService.referenceProvider, control.getModel(), $8C.lift(position), false, false, token).then((references2) => new $9eb(references2, localize(1140, null))));
      const range = new $9C(position.lineNumber, position.column, position.lineNumber, position.column);
      return Promise.resolve(controller.toggleWidget(range, references, false));
    });
  }
});
$tn.registerCommandAlias("editor.action.showReferences", "editor.action.peekLocations");

// out-build/vs/editor/contrib/inlayHints/browser/inlayHintsLocations.js
async function $sfb(accessor, editor, anchor, part) {
  const resolverService = accessor.get($oG);
  const contextMenuService = accessor.get($50);
  const commandService = accessor.get($sn);
  const instaService = accessor.get($Pk);
  const notificationService = accessor.get($PJ);
  await part.item.resolve(CancellationToken.None);
  if (!part.part.location) {
    return;
  }
  const location3 = part.part.location;
  const menuActions = [];
  const filter = new Set($dJ.getMenuItems($bJ.EditorContext).map((item) => $_I(item) ? item.command.id : $ps()));
  for (const delegate of $qfb.all()) {
    if (filter.has(delegate.desc.id)) {
      menuActions.push(new $Um(delegate.desc.id, $fJ.label(delegate.desc, { renderShortTitle: true }), void 0, true, async () => {
        const ref = await resolverService.createModelReference(location3.uri);
        try {
          const symbolAnchor = new $pfb(ref.object.textEditorModel, $9C.getStartPosition(location3.range));
          const range = part.item.anchor.range;
          await instaService.invokeFunction(delegate.runEditorCommand.bind(delegate), editor, symbolAnchor, range);
        } finally {
          ref.dispose();
        }
      }));
    }
  }
  if (part.part.command) {
    const { command: command4 } = part.part;
    menuActions.push(new $Wm());
    menuActions.push(new $Um(command4.id, command4.title, void 0, true, async () => {
      try {
        await commandService.executeCommand(command4.id, ...command4.arguments ?? []);
      } catch (err) {
        notificationService.notify({
          severity: Severity2.Error,
          source: part.item.provider.displayName,
          message: err
        });
      }
    }));
  }
  const useShadowDOM = editor.getOption(
    132
    /* EditorOption.useShadowDOM */
  );
  contextMenuService.showContextMenu({
    domForShadowRoot: useShadowDOM ? editor.getDomNode() ?? void 0 : void 0,
    getAnchor: () => {
      const box = $vj(anchor);
      return { x: box.left, y: box.top + box.height + 8 };
    },
    getActions: () => menuActions,
    onHide: () => {
      editor.focus();
    },
    autoSelectFirstItem: true
  });
}
async function $tfb(accessor, event, editor, location3) {
  const resolverService = accessor.get($oG);
  const ref = await resolverService.createModelReference(location3.uri);
  await editor.invokeWithinContext(async (accessor2) => {
    const openToSide = event.hasSideBySideModifier;
    const contextKeyService = accessor2.get($on);
    const isInPeek = PeekContext.inPeekEditor.getValue(contextKeyService);
    const canPeek = !openToSide && editor.getOption(
      93
      /* EditorOption.definitionLinkOpensInPeek */
    ) && !isInPeek;
    const action = new $rfb({ openToSide, openInPeek: canPeek, muteMessage: true }, { title: { value: "", original: "" }, id: "", precondition: void 0 });
    return action.run(accessor2, new $pfb(ref.object.textEditorModel, $9C.getStartPosition(location3.range)), $9C.lift(location3.range));
  });
  ref.dispose();
}

// out-build/vs/editor/contrib/inlayHints/browser/inlayHintsController.js
var $vfb_1;
var InlayHintsCache = class _InlayHintsCache {
  constructor() {
    this.a = new $Hc(50);
  }
  get(model) {
    const key2 = _InlayHintsCache.b(model);
    return this.a.get(key2);
  }
  set(model, value) {
    const key2 = _InlayHintsCache.b(model);
    this.a.set(key2, value);
  }
  static b(model) {
    return `${model.uri.toString()}/${model.getVersionId()}`;
  }
};
var IInlayHintsCache = $Qk("IInlayHintsCache");
$SC(
  IInlayHintsCache,
  InlayHintsCache,
  1
  /* InstantiationType.Delayed */
);
var $ufb = class {
  constructor(item, index) {
    this.item = item;
    this.index = index;
  }
  get part() {
    const label3 = this.item.hint.label;
    if (typeof label3 === "string") {
      return { label: label3 };
    } else {
      return label3[this.index];
    }
  }
};
var ActiveInlayHintInfo = class {
  constructor(part, hasTriggerModifier2) {
    this.part = part;
    this.hasTriggerModifier = hasTriggerModifier2;
  }
};
var RenderMode;
(function(RenderMode2) {
  RenderMode2[RenderMode2["Normal"] = 0] = "Normal";
  RenderMode2[RenderMode2["Invisible"] = 1] = "Invisible";
})(RenderMode || (RenderMode = {}));
var $vfb = class $vfb2 {
  static {
    $vfb_1 = this;
  }
  static {
    this.ID = "editor.contrib.InlayHints";
  }
  static {
    this.a = 1500;
  }
  static {
    this.b = {};
  }
  static get(editor) {
    return editor.getContribution($vfb_1.ID) ?? void 0;
  }
  constructor(o, q, _featureDebounce, s, t, u, v) {
    this.o = o;
    this.q = q;
    this.s = s;
    this.t = t;
    this.u = u;
    this.v = v;
    this.f = new $2c();
    this.g = new $2c();
    this.j = /* @__PURE__ */ new Map();
    this.k = new $86(this.o);
    this.m = 0;
    this.h = _featureDebounce.for(q.inlayHintsProvider, "InlayHint", { min: 25 });
    this.f.add(q.inlayHintsProvider.onDidChange(() => this.w()));
    this.f.add(o.onDidChangeModel(() => this.w()));
    this.f.add(o.onDidChangeModelLanguage(() => this.w()));
    this.f.add(o.onDidChangeConfiguration((e) => {
      if (e.hasChanged(
        146
        /* EditorOption.inlayHints */
      )) {
        this.w();
      }
    }));
    this.w();
  }
  dispose() {
    this.g.dispose();
    this.J();
    this.f.dispose();
  }
  w() {
    this.g.clear();
    this.J();
    const options3 = this.o.getOption(
      146
      /* EditorOption.inlayHints */
    );
    if (options3.enabled === "off") {
      return;
    }
    const model = this.o.getModel();
    if (!model || !this.q.inlayHintsProvider.has(model)) {
      return;
    }
    if (options3.enabled === "on") {
      this.m = 0;
    } else {
      let defaultMode;
      let altMode;
      if (options3.enabled === "onUnlessPressed") {
        defaultMode = 0;
        altMode = 1;
      } else {
        defaultMode = 1;
        altMode = 0;
      }
      this.m = defaultMode;
      this.g.add($yk.getInstance().event((e) => {
        if (!this.o.hasModel()) {
          return;
        }
        const newRenderMode = e.altKey && e.ctrlKey && !(e.shiftKey || e.metaKey) ? altMode : defaultMode;
        if (newRenderMode !== this.m) {
          this.m = newRenderMode;
          const model2 = this.o.getModel();
          const copies = this.E(model2);
          this.G([model2.getFullModelRange()], copies);
          scheduler.schedule(0);
        }
      }));
    }
    const cached = this.s.get(model);
    if (cached) {
      this.G([model.getFullModelRange()], cached);
    }
    this.g.add($1c(() => {
      if (!model.isDisposed()) {
        this.D(model);
      }
    }));
    let cts;
    const watchedProviders = /* @__PURE__ */ new Set();
    const scheduler = new $8h(async () => {
      const t1 = Date.now();
      cts?.dispose(true);
      cts = new $ad();
      const listener = model.onWillDispose(() => cts?.cancel());
      try {
        const myToken = cts.token;
        const inlayHints = await $9db.create(this.q.inlayHintsProvider, model, this.F(), myToken);
        scheduler.delay = this.h.update(model, Date.now() - t1);
        if (myToken.isCancellationRequested) {
          inlayHints.dispose();
          return;
        }
        for (const provider of inlayHints.provider) {
          if (typeof provider.onDidChangeInlayHints === "function" && !watchedProviders.has(provider)) {
            watchedProviders.add(provider);
            this.g.add(provider.onDidChangeInlayHints(() => {
              if (!scheduler.isScheduled()) {
                scheduler.schedule();
              }
            }));
          }
        }
        this.g.add(inlayHints);
        this.G(inlayHints.ranges, inlayHints.items);
        this.D(model);
      } catch (err) {
        $gb(err);
      } finally {
        cts.dispose();
        listener.dispose();
      }
    }, this.h.get(model));
    this.g.add(scheduler);
    this.g.add($1c(() => cts?.dispose(true)));
    scheduler.schedule(0);
    this.g.add(this.o.onDidScrollChange((e) => {
      if (e.scrollTopChanged || !scheduler.isScheduled()) {
        scheduler.schedule();
      }
    }));
    const cursor = this.g.add(new $4c());
    this.g.add(this.o.onDidChangeModelContent((e) => {
      cts?.cancel();
      const delay = Math.max(scheduler.delay, 800);
      this.l = { position: this.o.getPosition(), notEarlierThan: Date.now() + delay };
      cursor.value = $Xh(() => scheduler.schedule(0), delay);
      scheduler.schedule();
    }));
    this.g.add(this.o.onDidChangeConfiguration((e) => {
      if (e.hasChanged(
        146
        /* EditorOption.inlayHints */
      )) {
        scheduler.schedule();
      }
    }));
    this.g.add(this.z(() => scheduler.schedule(0)));
    this.g.add(this.x());
    this.g.add(this.A());
  }
  x() {
    const store = new $2c();
    const gesture = store.add(new $6db(this.o));
    const sessionStore = new $2c();
    store.add(sessionStore);
    store.add(gesture.onMouseMoveOrRelevantKeyDown((e) => {
      const [mouseEvent] = e;
      const labelPart = this.B(mouseEvent);
      const model = this.o.getModel();
      if (!labelPart || !model) {
        sessionStore.clear();
        return;
      }
      const cts = new $ad();
      sessionStore.add($1c(() => cts.dispose(true)));
      labelPart.item.resolve(cts.token);
      this.n = labelPart.part.command || labelPart.part.location ? new ActiveInlayHintInfo(labelPart, mouseEvent.hasTriggerModifier) : void 0;
      const lineNumber = model.validatePosition(labelPart.item.hint.position).lineNumber;
      const range = new $9C(lineNumber, 1, lineNumber, model.getLineMaxColumn(lineNumber));
      const lineHints = this.y(range);
      this.G([range], lineHints);
      sessionStore.add($1c(() => {
        this.n = void 0;
        this.G([range], lineHints);
      }));
    }));
    store.add(gesture.onCancel(() => sessionStore.clear()));
    store.add(gesture.onExecute(async (e) => {
      const label3 = this.B(e);
      if (label3) {
        const part = label3.part;
        if (part.location) {
          this.v.invokeFunction($tfb, e, this.o, part.location);
        } else if (Command.is(part.command)) {
          await this.C(part.command, label3.item);
        }
      }
    }));
    return store;
  }
  y(range) {
    const lineHints = /* @__PURE__ */ new Set();
    for (const data of this.j.values()) {
      if (range.containsRange(data.item.anchor.range)) {
        lineHints.add(data.item);
      }
    }
    return Array.from(lineHints);
  }
  z(updateInlayHints) {
    return this.o.onMouseUp(async (e) => {
      if (e.event.detail !== 2) {
        return;
      }
      const part = this.B(e);
      if (!part) {
        return;
      }
      e.event.preventDefault();
      await part.item.resolve(CancellationToken.None);
      if ($Qb(part.item.hint.textEdits)) {
        const edits = part.item.hint.textEdits.map((edit3) => $bD.replace($9C.lift(edit3.range), edit3.text));
        this.o.executeEdits("inlayHint.default", edits);
        updateInlayHints();
      }
    });
  }
  A() {
    return this.o.onContextMenu(async (e) => {
      if (!$Uj(e.event.target)) {
        return;
      }
      const part = this.B(e);
      if (part) {
        await this.v.invokeFunction($sfb, this.o, e.event.target, part);
      }
    });
  }
  B(e) {
    if (e.target.type !== 6) {
      return void 0;
    }
    const options3 = e.target.detail.injectedText?.options;
    if (options3 instanceof $VI && options3?.attachedData instanceof $ufb) {
      return options3.attachedData;
    }
    return void 0;
  }
  async C(command4, item) {
    try {
      await this.t.executeCommand(command4.id, ...command4.arguments ?? []);
    } catch (err) {
      this.u.notify({
        severity: Severity2.Error,
        source: item.provider.displayName,
        message: err
      });
    }
  }
  D(model) {
    const hints = this.E(model);
    this.s.set(model, hints);
  }
  // return inlay hints but with an anchor that reflects "updates"
  // that happened after receiving them, e.g adding new lines before a hint
  E(model) {
    const items = /* @__PURE__ */ new Map();
    for (const [id2, obj] of this.j) {
      if (items.has(obj.item)) {
        continue;
      }
      const range = model.getDecorationRange(id2);
      if (range) {
        const anchor = new $7db(range, obj.item.anchor.direction);
        const copy = obj.item.with({ anchor });
        items.set(obj.item, copy);
      }
    }
    return Array.from(items.values());
  }
  F() {
    const extra = 30;
    const model = this.o.getModel();
    const visibleRanges = this.o.getVisibleRangesPlusViewportAboveBelow();
    const result = [];
    for (const range of visibleRanges.sort($9C.compareRangesUsingStarts)) {
      const extendedRange = model.validateRange(new $9C(range.startLineNumber - extra, range.startColumn, range.endLineNumber + extra, range.endColumn));
      if (result.length === 0 || !$9C.areIntersectingOrTouching(result[result.length - 1], extendedRange)) {
        result.push(extendedRange);
      } else {
        result[result.length - 1] = $9C.plusRange(result[result.length - 1], extendedRange);
      }
    }
    return result;
  }
  G(ranges, items) {
    const itemFixedLengths = /* @__PURE__ */ new Map();
    if (this.l && this.l.notEarlierThan > Date.now() && ranges.some((range) => range.containsPosition(this.l.position))) {
      const { position } = this.l;
      this.l = void 0;
      const lengths = /* @__PURE__ */ new Map();
      for (const deco of this.o.getLineDecorations(position.lineNumber) ?? []) {
        const data = this.j.get(deco.id);
        if (deco.range.startColumn > position.column) {
          continue;
        }
        const opts = data?.decoration.options[data.item.anchor.direction];
        if (opts && opts.attachedData !== $vfb_1.b) {
          const len = lengths.get(data.item) ?? 0;
          lengths.set(data.item, len + opts.content.length);
        }
      }
      const newItemsWithFixedLength = items.filter((item) => item.anchor.range.startLineNumber === position.lineNumber && item.anchor.range.endColumn <= position.column);
      const fixedLengths = Array.from(lengths.values());
      let lastItem;
      while (true) {
        const targetItem = newItemsWithFixedLength.shift();
        const fixedLength = fixedLengths.shift();
        if (!fixedLength && !targetItem) {
          break;
        }
        if (targetItem) {
          itemFixedLengths.set(targetItem, fixedLength ?? 0);
          lastItem = targetItem;
        } else if (lastItem && fixedLength) {
          let len = itemFixedLengths.get(lastItem);
          len += fixedLength;
          len += fixedLengths.reduce((p, c) => p + c, 0);
          fixedLengths.length = 0;
          break;
        }
      }
    }
    const newDecorationsData = [];
    const addInjectedText = (item, ref, content, cursorStops, attachedData) => {
      const opts = {
        content,
        inlineClassNameAffectsLetterSpacing: true,
        inlineClassName: ref.className,
        cursorStops,
        attachedData
      };
      newDecorationsData.push({
        item,
        classNameRef: ref,
        decoration: {
          range: item.anchor.range,
          options: {
            // className: "rangeHighlight", // DEBUG highlight to see to what range a hint is attached
            description: "InlayHint",
            showIfCollapsed: item.anchor.range.isEmpty(),
            // "original" range is empty
            collapseOnReplaceEdit: !item.anchor.range.isEmpty(),
            stickiness: 0,
            [item.anchor.direction]: this.m === 0 ? opts : void 0
          }
        }
      });
    };
    const addInjectedWhitespace = (item, isLast) => {
      const marginRule = this.k.createClassNameRef({
        width: `${fontSize / 3 | 0}px`,
        display: "inline-block"
      });
      addInjectedText(item, marginRule, "\u200A", isLast ? InjectedTextCursorStops.Right : InjectedTextCursorStops.None, $vfb_1.b);
    };
    const { fontSize, fontFamily, padding, isUniform } = this.I();
    const maxLength = this.o.getOption(
      146
      /* EditorOption.inlayHints */
    ).maximumLength;
    const fontFamilyVar = "--code-editorInlayHintsFontFamily";
    this.o.getContainerDomNode().style.setProperty(fontFamilyVar, fontFamily);
    let currentLineInfo = { line: 0, totalLen: 0 };
    for (let i2 = 0; i2 < items.length; i2++) {
      const item = items[i2];
      if (currentLineInfo.line !== item.anchor.range.startLineNumber) {
        currentLineInfo = { line: item.anchor.range.startLineNumber, totalLen: 0 };
      }
      if (maxLength && currentLineInfo.totalLen > maxLength) {
        continue;
      }
      if (item.hint.paddingLeft) {
        addInjectedWhitespace(item, false);
      }
      const parts = typeof item.hint.label === "string" ? [{ label: item.hint.label }] : item.hint.label;
      const itemFixedLength = itemFixedLengths.get(item);
      let itemActualLength = 0;
      for (let i3 = 0; i3 < parts.length; i3++) {
        const part = parts[i3];
        const isFirst = i3 === 0;
        const isLast = i3 === parts.length - 1;
        const cssProperties = {
          fontSize: `${fontSize}px`,
          fontFamily: `var(${fontFamilyVar}), ${EDITOR_FONT_DEFAULTS.fontFamily}`,
          verticalAlign: isUniform ? "baseline" : "middle",
          unicodeBidi: "isolate"
        };
        if ($Qb(item.hint.textEdits)) {
          cssProperties.cursor = "default";
        }
        this.H(cssProperties, item.hint);
        if ((part.command || part.location) && this.n?.part.item === item && this.n.part.index === i3) {
          cssProperties.textDecoration = "underline";
          if (this.n.hasTriggerModifier) {
            cssProperties.color = $hs($6o);
            cssProperties.cursor = "pointer";
          }
        }
        let textlabel = part.label;
        currentLineInfo.totalLen += textlabel.length;
        let tooLong = false;
        const over = maxLength !== 0 ? currentLineInfo.totalLen - maxLength : 0;
        if (over > 0) {
          textlabel = textlabel.slice(0, -over) + "\u2026";
          tooLong = true;
        }
        itemActualLength += textlabel.length;
        if (itemFixedLength !== void 0) {
          const overFixedLength = itemActualLength - itemFixedLength;
          if (overFixedLength >= 0) {
            itemActualLength -= overFixedLength;
            textlabel = textlabel.slice(0, -(1 + overFixedLength)) + "\u2026";
            tooLong = true;
          }
        }
        if (padding) {
          if (isFirst && (isLast || tooLong)) {
            cssProperties.padding = `1px ${Math.max(1, fontSize / 4) | 0}px`;
            cssProperties.borderRadius = `${fontSize / 4 | 0}px`;
          } else if (isFirst) {
            cssProperties.padding = `1px 0 1px ${Math.max(1, fontSize / 4) | 0}px`;
            cssProperties.borderRadius = `${fontSize / 4 | 0}px 0 0 ${fontSize / 4 | 0}px`;
          } else if (isLast || tooLong) {
            cssProperties.padding = `1px ${Math.max(1, fontSize / 4) | 0}px 1px 0`;
            cssProperties.borderRadius = `0 ${fontSize / 4 | 0}px ${fontSize / 4 | 0}px 0`;
          } else {
            cssProperties.padding = `1px 0 1px 0`;
          }
        }
        addInjectedText(item, this.k.createClassNameRef(cssProperties), fixSpace(textlabel), isLast && !item.hint.paddingRight ? InjectedTextCursorStops.Right : InjectedTextCursorStops.None, new $ufb(item, i3));
        if (tooLong) {
          break;
        }
      }
      if (itemFixedLength !== void 0 && itemActualLength < itemFixedLength) {
        const pad = itemFixedLength - itemActualLength;
        addInjectedText(item, this.k.createClassNameRef({}), "\u200A".repeat(pad), InjectedTextCursorStops.None);
      }
      if (item.hint.paddingRight) {
        addInjectedWhitespace(item, true);
      }
      if (newDecorationsData.length > $vfb_1.a) {
        break;
      }
    }
    const decorationIdsToReplace = [];
    for (const [id2, metadata] of this.j) {
      const range = this.o.getModel()?.getDecorationRange(id2);
      if (range && ranges.some((r2) => r2.containsRange(range))) {
        decorationIdsToReplace.push(id2);
        metadata.classNameRef.dispose();
        this.j.delete(id2);
      }
    }
    const scrollState = $O9.capture(this.o);
    this.o.changeDecorations((accessor) => {
      const newDecorationIds = accessor.deltaDecorations(decorationIdsToReplace, newDecorationsData.map((d) => d.decoration));
      for (let i2 = 0; i2 < newDecorationIds.length; i2++) {
        const data = newDecorationsData[i2];
        this.j.set(newDecorationIds[i2], data);
      }
    });
    scrollState.restore(this.o);
  }
  H(props, hint) {
    if (hint.kind === InlayHintKind.Parameter) {
      props.backgroundColor = $hs($sp);
      props.color = $hs($rp);
    } else if (hint.kind === InlayHintKind.Type) {
      props.backgroundColor = $hs($qp);
      props.color = $hs($pp);
    } else {
      props.backgroundColor = $hs($op);
      props.color = $hs($np);
    }
  }
  I() {
    const options3 = this.o.getOption(
      146
      /* EditorOption.inlayHints */
    );
    const padding = options3.padding;
    const editorFontSize = this.o.getOption(
      54
      /* EditorOption.fontSize */
    );
    const editorFontFamily = this.o.getOption(
      51
      /* EditorOption.fontFamily */
    );
    let fontSize = options3.fontSize;
    if (!fontSize || fontSize < 5 || fontSize > editorFontSize) {
      fontSize = editorFontSize;
    }
    const fontFamily = options3.fontFamily || editorFontFamily;
    const isUniform = !padding && fontFamily === editorFontFamily && fontSize === editorFontSize;
    return { fontSize, fontFamily, padding, isUniform };
  }
  J() {
    this.o.removeDecorations(Array.from(this.j.keys()));
    for (const obj of this.j.values()) {
      obj.classNameRef.dispose();
    }
    this.j.clear();
  }
  // --- accessibility
  getInlayHintsForLine(line) {
    if (!this.o.hasModel()) {
      return [];
    }
    const set = /* @__PURE__ */ new Set();
    const result = [];
    for (const deco of this.o.getLineDecorations(line)) {
      const data = this.j.get(deco.id);
      if (data && !set.has(data.item.hint)) {
        set.add(data.item.hint);
        result.push(data.item);
      }
    }
    return result;
  }
};
$vfb = $vfb_1 = __decorate([
  __param(1, $mP),
  __param(2, $tbb),
  __param(3, IInlayHintsCache),
  __param(4, $sn),
  __param(5, $PJ),
  __param(6, $Pk)
], $vfb);
function fixSpace(str) {
  const noBreakWhitespace = "\xA0";
  return str.replace(/[ \t]/g, noBreakWhitespace);
}
$tn.registerCommand("_executeInlayHintProvider", async (accessor, ...args2) => {
  const [uri, range] = args2;
  $Jg(URI.isUri(uri));
  $Jg($9C.isIRange(range));
  const { inlayHintsProvider } = accessor.get($mP);
  const ref = await accessor.get($oG).createModelReference(uri);
  try {
    const model = await $9db.create(inlayHintsProvider, ref.object.textEditorModel, [$9C.lift(range)], CancellationToken.None);
    const result = model.items.map((i2) => i2.hint);
    setTimeout(() => model.dispose(), 0);
    return result;
  } finally {
    ref.dispose();
  }
});

// out-build/vs/editor/contrib/inlayHints/browser/inlayHintsHover.js
var InlayHintsHoverAnchor = class extends $zbb {
  constructor(part, owner, initialMousePosX, initialMousePosY) {
    super(10, owner, part.item.anchor.range, initialMousePosX, initialMousePosY, true);
    this.part = part;
  }
};
var $wfb = class $wfb2 extends $Kdb {
  constructor(editor, languageService, openerService, keybindingService, hoverService, configurationService, m, languageFeaturesService, commandService) {
    super(editor, languageService, openerService, configurationService, languageFeaturesService, keybindingService, hoverService, commandService);
    this.m = m;
    this.hoverOrdinal = 6;
  }
  suggestHoverAnchor(mouseEvent) {
    const controller = $vfb.get(this.b);
    if (!controller) {
      return null;
    }
    if (mouseEvent.target.type !== 6) {
      return null;
    }
    const options3 = mouseEvent.target.detail.injectedText?.options;
    if (!(options3 instanceof $VI && options3.attachedData instanceof $ufb)) {
      return null;
    }
    return new InlayHintsHoverAnchor(options3.attachedData, this, mouseEvent.event.posx, mouseEvent.event.posy);
  }
  computeSync() {
    return [];
  }
  computeAsync(anchor, _lineDecorations, source, token) {
    if (!(anchor instanceof InlayHintsHoverAnchor)) {
      return $ji.EMPTY;
    }
    return new $ji(async (executor) => {
      const { part } = anchor;
      await part.item.resolve(token);
      if (token.isCancellationRequested) {
        return;
      }
      let itemTooltip;
      if (typeof part.item.hint.tooltip === "string") {
        itemTooltip = new $bm().appendText(part.item.hint.tooltip);
      } else if (part.item.hint.tooltip) {
        itemTooltip = part.item.hint.tooltip;
      }
      if (itemTooltip) {
        executor.emitOne(new $Jdb(this, anchor.range, [itemTooltip], false, 0));
      }
      if ($Qb(part.item.hint.textEdits)) {
        executor.emitOne(new $Jdb(this, anchor.range, [new $bm().appendText(localize(1242, null))], false, 10001));
      }
      let partTooltip;
      if (typeof part.part.tooltip === "string") {
        partTooltip = new $bm().appendText(part.part.tooltip);
      } else if (part.part.tooltip) {
        partTooltip = part.part.tooltip;
      }
      if (partTooltip) {
        executor.emitOne(new $Jdb(this, anchor.range, [partTooltip], false, 1));
      }
      if (part.part.location || part.part.command) {
        let linkHint;
        const useMetaKey = this.b.getOption(
          79
          /* EditorOption.multiCursorModifier */
        ) === "altKey";
        const kb = useMetaKey ? $m ? localize(1243, null) : localize(1244, null) : $m ? localize(1245, null) : localize(1246, null);
        if (part.part.location && part.part.command) {
          linkHint = new $bm().appendText(localize(1247, null, kb));
        } else if (part.part.location) {
          linkHint = new $bm().appendText(localize(1248, null, kb));
        } else if (part.part.command) {
          linkHint = new $bm(`[${localize(1249, null)}](${$0db(part.part.command)} "${part.part.command.title}") (${kb})`, { isTrusted: true });
        }
        if (linkHint) {
          executor.emitOne(new $Jdb(this, anchor.range, [linkHint], false, 1e4));
        }
      }
      const iterable = await this.n(part, token);
      for await (const item of iterable) {
        executor.emitOne(item);
      }
    });
  }
  async n(part, token) {
    if (!part.part.location) {
      return $ji.EMPTY;
    }
    const { uri, range } = part.part.location;
    const ref = await this.m.createModelReference(uri);
    try {
      const model = ref.object.textEditorModel;
      if (!this.h.hoverProvider.has(model)) {
        return $ji.EMPTY;
      }
      return $Hdb(this.h.hoverProvider, model, new $8C(range.startLineNumber, range.startColumn), token).filter((item) => !$cm(item.hover.contents)).map((item) => new $Jdb(this, part.item.anchor.range, item.hover.contents, false, 2 + item.ordinal));
    } finally {
      ref.dispose();
    }
  }
};
$wfb = __decorate([
  __param(1, $1E),
  __param(2, $O4),
  __param(3, $Ty),
  __param(4, $5$),
  __param(5, $kl),
  __param(6, $oG),
  __param(7, $mP),
  __param(8, $sn)
], $wfb);

// out-build/vs/editor/contrib/hover/browser/contentHoverRendered.js
var $xfb_1;
var RenderedContentHoverParts_1;
var $xfb = $xfb_1 = class $xfb2 extends $3c {
  constructor(editor, hoverResult, participants, context, keybindingService, hoverService) {
    super();
    const parts = hoverResult.hoverParts;
    this.a = this.B(new RenderedContentHoverParts(editor, participants, parts, context, keybindingService, hoverService));
    const contentHoverComputerOptions = hoverResult.options;
    const anchor = contentHoverComputerOptions.anchor;
    const { showAtPosition, showAtSecondaryPosition } = $xfb_1.computeHoverPositions(editor, anchor.range, parts);
    this.shouldAppearBeforeContent = parts.some((m) => m.isBeforeContent);
    this.showAtPosition = showAtPosition;
    this.showAtSecondaryPosition = showAtSecondaryPosition;
    this.initialMousePosX = anchor.initialMousePosX;
    this.initialMousePosY = anchor.initialMousePosY;
    this.shouldFocus = contentHoverComputerOptions.shouldFocus;
    this.source = contentHoverComputerOptions.source;
  }
  get domNode() {
    return this.a.domNode;
  }
  get domNodeHasChildren() {
    return this.a.domNodeHasChildren;
  }
  get focusedHoverPartIndex() {
    return this.a.focusedHoverPartIndex;
  }
  focusHoverPartWithIndex(index) {
    this.a.focusHoverPartWithIndex(index);
  }
  getAccessibleWidgetContent() {
    return this.a.getAccessibleContent();
  }
  getAccessibleWidgetContentAtIndex(index) {
    return this.a.getAccessibleHoverContentAtIndex(index);
  }
  async updateHoverVerbosityLevel(action, index, focus) {
    this.a.updateHoverVerbosityLevel(action, index, focus);
  }
  doesHoverAtIndexSupportVerbosityAction(index, action) {
    return this.a.doesHoverAtIndexSupportVerbosityAction(index, action);
  }
  isColorPickerVisible() {
    return this.a.isColorPickerVisible();
  }
  static computeHoverPositions(editor, anchorRange, hoverParts) {
    let startColumnBoundary = 1;
    if (editor.hasModel()) {
      const viewModel = editor._getViewModel();
      const coordinatesConverter = viewModel.coordinatesConverter;
      const anchorViewRange = coordinatesConverter.convertModelRangeToViewRange(anchorRange);
      const anchorViewMinColumn = viewModel.getLineMinColumn(anchorViewRange.startLineNumber);
      const anchorViewRangeStart = new $8C(anchorViewRange.startLineNumber, anchorViewMinColumn);
      startColumnBoundary = coordinatesConverter.convertViewPositionToModelPosition(anchorViewRangeStart).column;
    }
    const anchorStartLineNumber = anchorRange.startLineNumber;
    let secondaryPositionColumn = anchorRange.startColumn;
    let forceShowAtRange;
    for (const hoverPart of hoverParts) {
      const hoverPartRange = hoverPart.range;
      const hoverPartRangeOnAnchorStartLine = hoverPartRange.startLineNumber === anchorStartLineNumber;
      const hoverPartRangeOnAnchorEndLine = hoverPartRange.endLineNumber === anchorStartLineNumber;
      const hoverPartRangeIsOnAnchorLine = hoverPartRangeOnAnchorStartLine && hoverPartRangeOnAnchorEndLine;
      if (hoverPartRangeIsOnAnchorLine) {
        const hoverPartStartColumn = hoverPartRange.startColumn;
        const minSecondaryPositionColumn = Math.min(secondaryPositionColumn, hoverPartStartColumn);
        secondaryPositionColumn = Math.max(minSecondaryPositionColumn, startColumnBoundary);
      }
      if (hoverPart.forceShowAtRange) {
        forceShowAtRange = hoverPartRange;
      }
    }
    let showAtPosition;
    let showAtSecondaryPosition;
    if (forceShowAtRange) {
      const forceShowAtPosition = forceShowAtRange.getStartPosition();
      showAtPosition = forceShowAtPosition;
      showAtSecondaryPosition = forceShowAtPosition;
    } else {
      showAtPosition = anchorRange.getStartPosition();
      showAtSecondaryPosition = new $8C(anchorStartLineNumber, secondaryPositionColumn);
    }
    return {
      showAtPosition,
      showAtSecondaryPosition
    };
  }
};
$xfb = $xfb_1 = __decorate([
  __param(4, $Ty),
  __param(5, $5$)
], $xfb);
var RenderedStatusBar = class {
  constructor(fragment, a) {
    this.a = a;
    fragment.appendChild(this.a.hoverElement);
  }
  get hoverElement() {
    return this.a.hoverElement;
  }
  get actions() {
    return this.a.actions;
  }
  dispose() {
    this.a.dispose();
  }
};
var RenderedContentHoverParts = class RenderedContentHoverParts2 extends $3c {
  static {
    RenderedContentHoverParts_1 = this;
  }
  static {
    this.a = $WI.register({
      description: "content-hover-highlight",
      className: "hoverHighlight"
    });
  }
  constructor(editor, participants, hoverParts, context, keybindingService, hoverService) {
    super();
    this.b = [];
    this.j = -1;
    this.f = context;
    this.c = document.createDocumentFragment();
    this.B(this.r(participants, hoverParts, context, keybindingService, hoverService));
    this.B(this.u());
    this.B(this.n(editor, hoverParts));
    this.w(participants);
  }
  n(editor, hoverParts) {
    if (hoverParts.length === 0) {
      return $3c.None;
    }
    let highlightRange2 = hoverParts[0].range;
    for (const hoverPart of hoverParts) {
      const hoverPartRange = hoverPart.range;
      highlightRange2 = $9C.plusRange(highlightRange2, hoverPartRange);
    }
    const highlightDecoration = editor.createDecorationsCollection();
    highlightDecoration.set([{
      range: highlightRange2,
      options: RenderedContentHoverParts_1.a
    }]);
    return $1c(() => {
      highlightDecoration.clear();
    });
  }
  r(participants, hoverParts, hoverContext, keybindingService, hoverService) {
    const statusBar = new $Cdb(keybindingService, hoverService);
    const hoverRenderingContext = {
      fragment: this.c,
      statusBar,
      ...hoverContext
    };
    const disposables = new $2c();
    for (const participant of participants) {
      const renderedHoverParts = this.s(hoverParts, participant, hoverRenderingContext);
      disposables.add(renderedHoverParts);
      for (const renderedHoverPart of renderedHoverParts.renderedHoverParts) {
        this.b.push({
          type: "hoverPart",
          participant,
          hoverPart: renderedHoverPart.hoverPart,
          hoverElement: renderedHoverPart.hoverElement
        });
      }
    }
    const renderedStatusBar = this.t(this.c, statusBar);
    if (renderedStatusBar) {
      disposables.add(renderedStatusBar);
      this.b.push({
        type: "statusBar",
        hoverElement: renderedStatusBar.hoverElement,
        actions: renderedStatusBar.actions
      });
    }
    return $1c(() => {
      disposables.dispose();
    });
  }
  s(hoverParts, participant, hoverRenderingContext) {
    const hoverPartsForParticipant = hoverParts.filter((hoverPart) => hoverPart.owner === participant);
    const hasHoverPartsForParticipant = hoverPartsForParticipant.length > 0;
    if (!hasHoverPartsForParticipant) {
      return new $Abb([]);
    }
    return participant.renderHoverParts(hoverRenderingContext, hoverPartsForParticipant);
  }
  t(fragment, statusBar) {
    if (!statusBar.hasContent) {
      return void 0;
    }
    return new RenderedStatusBar(fragment, statusBar);
  }
  u() {
    const disposables = new $2c();
    this.b.forEach((renderedPart, index) => {
      const element = renderedPart.hoverElement;
      element.tabIndex = 0;
      disposables.add($_i(element, $7j.FOCUS_IN, (event) => {
        event.stopPropagation();
        this.j = index;
      }));
      disposables.add($_i(element, $7j.FOCUS_OUT, (event) => {
        event.stopPropagation();
        this.j = -1;
      }));
    });
    return disposables;
  }
  w(participants) {
    const markdownHoverParticipant = participants.find((p) => {
      return p instanceof $Kdb && !(p instanceof $wfb);
    });
    if (markdownHoverParticipant) {
      this.g = markdownHoverParticipant;
    }
    this.h = participants.find((p) => p instanceof $2db);
  }
  focusHoverPartWithIndex(index) {
    if (index < 0 || index >= this.b.length) {
      return;
    }
    this.b[index].hoverElement.focus();
  }
  getAccessibleContent() {
    const content = [];
    for (let i2 = 0; i2 < this.b.length; i2++) {
      content.push(this.getAccessibleHoverContentAtIndex(i2));
    }
    return content.join("\n\n");
  }
  getAccessibleHoverContentAtIndex(index) {
    const renderedPart = this.b[index];
    if (!renderedPart) {
      return "";
    }
    if (renderedPart.type === "statusBar") {
      const statusBarDescription = [localize(1178, null)];
      for (const action of renderedPart.actions) {
        const keybinding = action.actionKeybindingLabel;
        if (keybinding) {
          statusBarDescription.push(localize(1179, null, action.actionLabel, keybinding));
        } else {
          statusBarDescription.push(localize(1180, null, action.actionLabel));
        }
      }
      return statusBarDescription.join("\n");
    }
    return renderedPart.participant.getAccessibleContent(renderedPart.hoverPart);
  }
  async updateHoverVerbosityLevel(action, index, focus) {
    if (!this.g) {
      return;
    }
    const normalizedMarkdownHoverIndex = this.y(this.g, index);
    if (normalizedMarkdownHoverIndex === void 0) {
      return;
    }
    const renderedPart = await this.g.updateMarkdownHoverVerbosityLevel(action, normalizedMarkdownHoverIndex, focus);
    if (!renderedPart) {
      return;
    }
    this.b[index] = {
      type: "hoverPart",
      participant: this.g,
      hoverPart: renderedPart.hoverPart,
      hoverElement: renderedPart.hoverElement
    };
    this.f.onContentsChanged();
  }
  doesHoverAtIndexSupportVerbosityAction(index, action) {
    if (!this.g) {
      return false;
    }
    const normalizedMarkdownHoverIndex = this.y(this.g, index);
    if (normalizedMarkdownHoverIndex === void 0) {
      return false;
    }
    return this.g.doesMarkdownHoverAtIndexSupportVerbosityAction(normalizedMarkdownHoverIndex, action);
  }
  isColorPickerVisible() {
    return this.h?.isColorPickerVisible() ?? false;
  }
  y(markdownHoverParticipant, index) {
    const renderedPart = this.b[index];
    if (!renderedPart || renderedPart.type !== "hoverPart") {
      return void 0;
    }
    const isHoverPartMarkdownHover = renderedPart.participant === markdownHoverParticipant;
    if (!isHoverPartMarkdownHover) {
      return void 0;
    }
    const firstIndexOfMarkdownHovers = this.b.findIndex((renderedPart2) => renderedPart2.type === "hoverPart" && renderedPart2.participant === markdownHoverParticipant);
    if (firstIndexOfMarkdownHovers === -1) {
      throw new $vb();
    }
    return index - firstIndexOfMarkdownHovers;
  }
  get domNode() {
    return this.c;
  }
  get domNodeHasChildren() {
    return this.c.hasChildNodes();
  }
  get focusedHoverPartIndex() {
    return this.j;
  }
};
RenderedContentHoverParts = RenderedContentHoverParts_1 = __decorate([
  __param(4, $Ty),
  __param(5, $5$)
], RenderedContentHoverParts);

// out-build/vs/editor/contrib/hover/browser/contentHoverWidgetWrapper.js
var $zfb = class $zfb2 extends $3c {
  constructor(n, r2, s, t) {
    super();
    this.n = n;
    this.r = r2;
    this.s = s;
    this.t = t;
    this.c = null;
    this.m = this.B(new $ze());
    this.onContentsChanged = this.m.event;
    this.g = this.B(this.r.createInstance($yfb, this.n));
    this.h = this.u();
    this.j = this.B(new $xbb(this.n, new $Ddb(this.n, this.h)));
    this.w();
  }
  u() {
    const participants = [];
    for (const participant of $Bbb.getAll()) {
      const participantInstance = this.r.createInstance(participant, this.n);
      participants.push(participantInstance);
    }
    participants.sort((p1, p2) => p1.hoverOrdinal - p2.hoverOrdinal);
    this.B(this.g.onDidResize(() => {
      this.h.forEach((participant) => participant.handleResize?.());
    }));
    return participants;
  }
  w() {
    this.B(this.j.onResult((result) => {
      const messages = result.hasLoadingMessage ? this.F(result) : result.value;
      this.G(new $Edb(messages, result.isComplete, result.options));
    }));
    const contentHoverWidgetNode = this.g.getDomNode();
    this.B($aj(contentHoverWidgetNode, "keydown", (e) => {
      if (e.equals(
        9
        /* KeyCode.Escape */
      )) {
        this.hide();
      }
    }));
    this.B($aj(contentHoverWidgetNode, "mouseleave", (e) => {
      this.M(e);
    }));
    this.B($YE.onDidChange(() => {
      if (this.g.position && this.c) {
        this.D(this.c);
      }
    }));
  }
  /**
   * Returns true if the hover shows now or will show.
   */
  z(anchor, mode, source, focus, mouseEvent) {
    const contentHoverIsVisible = this.g.position && this.c;
    if (!contentHoverIsVisible) {
      if (anchor) {
        this.C(anchor, mode, source, focus, false);
        return true;
      }
      return false;
    }
    const isHoverSticky = this.n.getOption(
      62
      /* EditorOption.hover */
    ).sticky;
    const isMouseGettingCloser = mouseEvent && this.g.isMouseGettingCloser(mouseEvent.event.posx, mouseEvent.event.posy);
    const isHoverStickyAndIsMouseGettingCloser = isHoverSticky && isMouseGettingCloser;
    if (isHoverStickyAndIsMouseGettingCloser) {
      if (anchor) {
        this.C(anchor, mode, source, focus, true);
      }
      return true;
    }
    if (!anchor) {
      this.D(null);
      return false;
    }
    const currentAnchorEqualsPreviousAnchor = this.c && this.c.options.anchor.equals(anchor);
    if (currentAnchorEqualsPreviousAnchor) {
      return true;
    }
    const currentAnchorCompatibleWithPreviousAnchor = this.c && anchor.canAdoptVisibleHover(this.c.options.anchor, this.g.position);
    if (!currentAnchorCompatibleWithPreviousAnchor) {
      this.D(null);
      this.C(anchor, mode, source, focus, false);
      return true;
    }
    if (this.c) {
      this.D(this.c.filter(anchor));
    }
    this.C(anchor, mode, source, focus, false);
    return true;
  }
  C(anchor, mode, source, shouldFocus, insistOnKeepingHoverVisible) {
    const currentAnchorEqualToPreviousHover = this.j.options && this.j.options.anchor.equals(anchor);
    if (currentAnchorEqualToPreviousHover) {
      return;
    }
    this.j.cancel();
    const contentHoverComputerOptions = {
      anchor,
      source,
      shouldFocus,
      insistOnKeepingHoverVisible
    };
    this.j.start(mode, contentHoverComputerOptions);
  }
  D(hoverResult) {
    let currentHoverResult = hoverResult;
    const currentResultEqualToPreviousResult = this.c === currentHoverResult;
    if (currentResultEqualToPreviousResult) {
      return;
    }
    const currentHoverResultIsEmpty = currentHoverResult && currentHoverResult.hoverParts.length === 0;
    if (currentHoverResultIsEmpty) {
      currentHoverResult = null;
    }
    this.c = currentHoverResult;
    if (this.c) {
      this.H(this.c);
    } else {
      this.I();
    }
  }
  F(hoverResult) {
    for (const participant of this.h) {
      if (!participant.createLoadingMessage) {
        continue;
      }
      const loadingMessage = participant.createLoadingMessage(hoverResult.options.anchor);
      if (!loadingMessage) {
        continue;
      }
      return hoverResult.value.slice(0).concat([loadingMessage]);
    }
    return hoverResult.value;
  }
  G(hoverResult) {
    const previousHoverIsVisibleWithCompleteResult = this.g.position && this.c && this.c.isComplete;
    if (!previousHoverIsVisibleWithCompleteResult) {
      this.D(hoverResult);
    }
    const isCurrentHoverResultComplete = hoverResult.isComplete;
    if (!isCurrentHoverResultComplete) {
      return;
    }
    const currentHoverResultIsEmpty = hoverResult.hoverParts.length === 0;
    const insistOnKeepingPreviousHoverVisible = hoverResult.options.insistOnKeepingHoverVisible;
    const shouldKeepPreviousHoverVisible = currentHoverResultIsEmpty && insistOnKeepingPreviousHoverVisible;
    if (shouldKeepPreviousHoverVisible) {
      return;
    }
    this.D(hoverResult);
  }
  H(hoverResult) {
    const context = this.J();
    this.f = new $xfb(this.n, hoverResult, this.h, context, this.s, this.t);
    if (this.f.domNodeHasChildren) {
      this.g.show(this.f);
    } else {
      this.f.dispose();
    }
  }
  I() {
    this.g.hide();
    this.h.forEach((participant) => participant.handleHide?.());
  }
  J() {
    const hide3 = () => {
      this.hide();
    };
    const onContentsChanged = () => {
      this.m.fire();
      this.g.onContentsChanged();
    };
    const setMinimumDimensions = (dimensions) => {
      this.g.setMinimumDimensions(dimensions);
    };
    return { hide: hide3, onContentsChanged, setMinimumDimensions };
  }
  showsOrWillShow(mouseEvent) {
    const isContentWidgetResizing = this.g.isResizing;
    if (isContentWidgetResizing) {
      return true;
    }
    const anchorCandidates = this.L(mouseEvent);
    const anchorCandidatesExist = anchorCandidates.length > 0;
    if (!anchorCandidatesExist) {
      return this.z(null, 0, 0, false, mouseEvent);
    }
    const anchor = anchorCandidates[0];
    return this.z(anchor, 0, 0, false, mouseEvent);
  }
  L(mouseEvent) {
    const anchorCandidates = [];
    for (const participant of this.h) {
      if (!participant.suggestHoverAnchor) {
        continue;
      }
      const anchor = participant.suggestHoverAnchor(mouseEvent);
      if (!anchor) {
        continue;
      }
      anchorCandidates.push(anchor);
    }
    const target = mouseEvent.target;
    switch (target.type) {
      case 6: {
        anchorCandidates.push(new $ybb(0, target.range, mouseEvent.event.posx, mouseEvent.event.posy));
        break;
      }
      case 7: {
        const epsilon2 = this.n.getOption(
          52
          /* EditorOption.fontInfo */
        ).typicalHalfwidthCharacterWidth / 2;
        const mouseIsWithinLinesAndCloseToHover = !target.detail.isAfterLines && typeof target.detail.horizontalDistanceToText === "number" && target.detail.horizontalDistanceToText < epsilon2;
        if (!mouseIsWithinLinesAndCloseToHover) {
          break;
        }
        anchorCandidates.push(new $ybb(0, target.range, mouseEvent.event.posx, mouseEvent.event.posy));
        break;
      }
    }
    anchorCandidates.sort((a, b) => b.priority - a.priority);
    return anchorCandidates;
  }
  M(e) {
    const editorDomNode = this.n.getDomNode();
    const isMousePositionOutsideOfEditor = !editorDomNode || !$Adb(editorDomNode, e.x, e.y);
    if (isMousePositionOutsideOfEditor) {
      this.hide();
    }
  }
  startShowingAtRange(range, mode, source, focus) {
    this.z(new $ybb(0, range, void 0, void 0), mode, source, focus, null);
  }
  getWidgetContent() {
    const node = this.g.getDomNode();
    if (!node.textContent) {
      return void 0;
    }
    return node.textContent;
  }
  async updateHoverVerbosityLevel(action, index, focus) {
    this.f?.updateHoverVerbosityLevel(action, index, focus);
  }
  doesHoverAtIndexSupportVerbosityAction(index, action) {
    return this.f?.doesHoverAtIndexSupportVerbosityAction(index, action) ?? false;
  }
  getAccessibleWidgetContent() {
    return this.f?.getAccessibleWidgetContent();
  }
  getAccessibleWidgetContentAtIndex(index) {
    return this.f?.getAccessibleWidgetContentAtIndex(index);
  }
  focusedHoverPartIndex() {
    return this.f?.focusedHoverPartIndex ?? -1;
  }
  containsNode(node) {
    return node ? this.g.getDomNode().contains(node) : false;
  }
  focus() {
    this.g.focus();
  }
  focusHoverPartWithIndex(index) {
    this.f?.focusHoverPartWithIndex(index);
  }
  scrollUp() {
    this.g.scrollUp();
  }
  scrollDown() {
    this.g.scrollDown();
  }
  scrollLeft() {
    this.g.scrollLeft();
  }
  scrollRight() {
    this.g.scrollRight();
  }
  pageUp() {
    this.g.pageUp();
  }
  pageDown() {
    this.g.pageDown();
  }
  goToTop() {
    this.g.goToTop();
  }
  goToBottom() {
    this.g.goToBottom();
  }
  hide() {
    this.j.cancel();
    this.D(null);
  }
  getDomNode() {
    return this.g.getDomNode();
  }
  get isColorPickerVisible() {
    return this.f?.isColorPickerVisible() ?? false;
  }
  get isVisibleFromKeyboard() {
    return this.g.isVisibleFromKeyboard;
  }
  get isVisible() {
    return this.g.isVisible;
  }
  get isFocused() {
    return this.g.isFocused;
  }
  get isResizing() {
    return this.g.isResizing;
  }
  get widget() {
    return this.g;
  }
};
$zfb = __decorate([
  __param(1, $Pk),
  __param(2, $Ty),
  __param(3, $5$)
], $zfb);

// out-build/vs/editor/contrib/hover/browser/contentHoverController.js
var $Afb_1;
var _sticky = false;
var $Afb = class $Afb2 extends $3c {
  static {
    $Afb_1 = this;
  }
  static {
    this.ID = "editor.contrib.contentHover";
  }
  constructor(m, n, r2) {
    super();
    this.m = m;
    this.n = n;
    this.r = r2;
    this.a = this.B(new $ze());
    this.onHoverContentsChanged = this.a.event;
    this.shouldKeepOpenOnEditorMouseMoveOrLeave = false;
    this.b = new $2c();
    this.j = false;
    this.g = this.B(new $8h(() => this.M(this.f), 0));
    this.s();
    this.B(this.m.onDidChangeConfiguration((e) => {
      if (e.hasChanged(
        62
        /* EditorOption.hover */
      )) {
        this.t();
        this.s();
      }
    }));
  }
  static get(editor) {
    return editor.getContribution($Afb_1.ID);
  }
  s() {
    const hoverOpts = this.m.getOption(
      62
      /* EditorOption.hover */
    );
    this.h = {
      enabled: hoverOpts.enabled,
      sticky: hoverOpts.sticky,
      hidingDelay: hoverOpts.hidingDelay
    };
    if (hoverOpts.enabled) {
      this.b.add(this.m.onMouseDown((e) => this.z(e)));
      this.b.add(this.m.onMouseUp(() => this.F()));
      this.b.add(this.m.onMouseMove((e) => this.I(e)));
      this.b.add(this.m.onKeyDown((e) => this.N(e)));
      this.b.add(this.m.onMouseLeave((e) => this.G(e)));
      this.b.add(this.m.onDidChangeModel(() => this.u()));
      this.b.add(this.m.onDidChangeModelContent(() => this.w()));
      this.b.add(this.m.onDidScrollChange((e) => this.y(e)));
    } else {
      this.u();
    }
  }
  t() {
    this.b.clear();
  }
  u() {
    this.w();
    this.hideContentHover();
  }
  w() {
    this.f = void 0;
    this.g.cancel();
  }
  y(e) {
    if (e.scrollTopChanged || e.scrollLeftChanged) {
      this.hideContentHover();
    }
  }
  z(mouseEvent) {
    this.j = true;
    const shouldKeepHoverWidgetVisible = this.C(mouseEvent);
    if (shouldKeepHoverWidgetVisible) {
      return;
    }
    this.hideContentHover();
  }
  C(mouseEvent) {
    return this.D(mouseEvent) || this.R() || $Cfb(mouseEvent);
  }
  D(mouseEvent) {
    if (!this.c) {
      return false;
    }
    return $Adb(this.c.getDomNode(), mouseEvent.event.posx, mouseEvent.event.posy);
  }
  F() {
    this.j = false;
  }
  G(mouseEvent) {
    if (this.shouldKeepOpenOnEditorMouseMoveOrLeave) {
      return;
    }
    this.w();
    const shouldKeepHoverWidgetVisible = this.C(mouseEvent);
    if (shouldKeepHoverWidgetVisible) {
      return;
    }
    if (_sticky) {
      return;
    }
    this.hideContentHover();
  }
  H(mouseEvent) {
    const isHoverSticky = this.h.sticky;
    const isMouseOnStickyContentHoverWidget = (mouseEvent2, isHoverSticky2) => {
      const isMouseOnContentHoverWidget = this.D(mouseEvent2);
      return isHoverSticky2 && isMouseOnContentHoverWidget;
    };
    const isMouseOnColorPicker = (mouseEvent2) => {
      const isMouseOnContentHoverWidget = this.D(mouseEvent2);
      const isColorPickerVisible = this.c?.isColorPickerVisible ?? false;
      return isMouseOnContentHoverWidget && isColorPickerVisible;
    };
    const isTextSelectedWithinContentHoverWidget = (mouseEvent2, sticky) => {
      return (sticky && this.c?.containsNode(mouseEvent2.event.browserEvent.view?.document.activeElement) && !mouseEvent2.event.browserEvent.view?.getSelection()?.isCollapsed) ?? false;
    };
    return isMouseOnStickyContentHoverWidget(mouseEvent, isHoverSticky) || isMouseOnColorPicker(mouseEvent) || isTextSelectedWithinContentHoverWidget(mouseEvent, isHoverSticky);
  }
  I(mouseEvent) {
    const shouldReactToEditorMouseMove = this.J(mouseEvent);
    if (!shouldReactToEditorMouseMove) {
      return;
    }
    const shouldRescheduleHoverComputation = this.L();
    if (shouldRescheduleHoverComputation) {
      if (!this.g.isScheduled()) {
        this.g.schedule(this.h.hidingDelay);
      }
      return;
    }
    this.M(mouseEvent);
  }
  J(mouseEvent) {
    if (this.shouldKeepOpenOnEditorMouseMoveOrLeave) {
      return false;
    }
    this.f = mouseEvent;
    if (this.c && (this.c.isFocused || this.c.isResizing || this.j && this.c.isColorPickerVisible)) {
      return false;
    }
    const sticky = this.h.sticky;
    if (sticky && this.c?.isVisibleFromKeyboard) {
      return false;
    }
    const shouldNotRecomputeCurrentHoverWidget = this.H(mouseEvent);
    if (shouldNotRecomputeCurrentHoverWidget) {
      this.g.cancel();
      return false;
    }
    return true;
  }
  L() {
    const hidingDelay = this.h.hidingDelay;
    const isContentHoverWidgetVisible = this.c?.isVisible ?? false;
    return isContentHoverWidgetVisible && this.h.sticky && hidingDelay > 0;
  }
  M(mouseEvent) {
    if (!mouseEvent) {
      return;
    }
    const contentWidget = this.Q();
    if (contentWidget.showsOrWillShow(mouseEvent)) {
      return;
    }
    if (_sticky) {
      return;
    }
    this.hideContentHover();
  }
  N(e) {
    if (!this.m.hasModel()) {
      return;
    }
    const isPotentialKeyboardShortcut = this.O(e);
    const isModifierKeyPressed = this.P(e);
    if (isPotentialKeyboardShortcut || isModifierKeyPressed) {
      return;
    }
    this.hideContentHover();
  }
  O(e) {
    if (!this.m.hasModel() || !this.c) {
      return false;
    }
    const resolvedKeyboardEvent = this.r.softDispatch(e, this.m.getDomNode());
    const moreChordsAreNeeded = resolvedKeyboardEvent.kind === 1;
    const isHoverAction = resolvedKeyboardEvent.kind === 2 && (resolvedKeyboardEvent.commandId === $Nbb || resolvedKeyboardEvent.commandId === $Xbb || resolvedKeyboardEvent.commandId === $1bb) && this.c.isVisible;
    return moreChordsAreNeeded || isHoverAction;
  }
  P(e) {
    return e.keyCode === 5 || e.keyCode === 6 || e.keyCode === 57 || e.keyCode === 4;
  }
  hideContentHover() {
    if (_sticky) {
      return;
    }
    if ($ydb.dropDownVisible) {
      return;
    }
    this.c?.hide();
  }
  Q() {
    if (!this.c) {
      this.c = this.n.createInstance($zfb, this.m);
      this.b.add(this.c.onContentsChanged(() => this.a.fire()));
    }
    return this.c;
  }
  showContentHover(range, mode, source, focus) {
    this.Q().startShowingAtRange(range, mode, source, focus);
  }
  R() {
    return this.c?.widget.isResizing || false;
  }
  focusedHoverPartIndex() {
    return this.Q().focusedHoverPartIndex();
  }
  doesHoverAtIndexSupportVerbosityAction(index, action) {
    return this.Q().doesHoverAtIndexSupportVerbosityAction(index, action);
  }
  updateHoverVerbosityLevel(action, index, focus) {
    this.Q().updateHoverVerbosityLevel(action, index, focus);
  }
  focus() {
    this.c?.focus();
  }
  focusHoverPartWithIndex(index) {
    this.c?.focusHoverPartWithIndex(index);
  }
  scrollUp() {
    this.c?.scrollUp();
  }
  scrollDown() {
    this.c?.scrollDown();
  }
  scrollLeft() {
    this.c?.scrollLeft();
  }
  scrollRight() {
    this.c?.scrollRight();
  }
  pageUp() {
    this.c?.pageUp();
  }
  pageDown() {
    this.c?.pageDown();
  }
  goToTop() {
    this.c?.goToTop();
  }
  goToBottom() {
    this.c?.goToBottom();
  }
  getWidgetContent() {
    return this.c?.getWidgetContent();
  }
  getAccessibleWidgetContent() {
    return this.c?.getAccessibleWidgetContent();
  }
  getAccessibleWidgetContentAtIndex(index) {
    return this.c?.getAccessibleWidgetContentAtIndex(index);
  }
  get isColorPickerVisible() {
    return this.c?.isColorPickerVisible;
  }
  get isHoverVisible() {
    return this.c?.isVisible;
  }
  dispose() {
    super.dispose();
    this.t();
    this.b.dispose();
    this.c?.dispose();
  }
};
$Afb = $Afb_1 = __decorate([
  __param(1, $Pk),
  __param(2, $Ty)
], $Afb);

// out-build/vs/editor/contrib/colorPicker/browser/hoverColorPicker/hoverColorPickerContribution.js
var $Bfb = class extends $3c {
  static {
    this.ID = "editor.contrib.colorContribution";
  }
  static {
    this.RECOMPUTE_TIME = 1e3;
  }
  // ms
  constructor(a) {
    super();
    this.a = a;
    this.B(a.onMouseDown((e) => this.b(e)));
  }
  dispose() {
    super.dispose();
  }
  b(mouseEvent) {
    const colorDecoratorsActivatedOn = this.a.getOption(
      154
      /* EditorOption.colorDecoratorsActivatedOn */
    );
    if (colorDecoratorsActivatedOn !== "click" && colorDecoratorsActivatedOn !== "clickAndHover") {
      return;
    }
    if (!$Cfb(mouseEvent)) {
      return;
    }
    const hoverController = this.a.getContribution($Afb.ID);
    if (!hoverController) {
      return;
    }
    if (hoverController.isColorPickerVisible) {
      return;
    }
    const targetRange = mouseEvent.target.range;
    if (!targetRange) {
      return;
    }
    const range = new $9C(targetRange.startLineNumber, targetRange.startColumn + 1, targetRange.endLineNumber, targetRange.endColumn + 1);
    hoverController.showContentHover(range, 1, 1, false);
  }
};
function $Cfb(mouseEvent) {
  const target = mouseEvent.target;
  return !!target && target.type === 6 && target.detail.injectedText?.options.attachedData === $Kbb;
}

// out-build/vs/editor/contrib/colorPicker/browser/standaloneColorPicker/standaloneColorPickerParticipant.js
var $Dfb = class _$Dfb {
  constructor(owner, range, model, provider) {
    this.owner = owner;
    this.range = range;
    this.model = model;
    this.provider = provider;
  }
  static fromBaseColor(owner, color2) {
    return new _$Dfb(owner, color2.range, color2.model, color2.provider);
  }
};
var $Efb = class $Efb2 {
  constructor(b, c) {
    this.b = b;
    this.c = c;
    this.hoverOrdinal = 2;
    this.a = null;
  }
  async createColorHover(defaultColorInfo, defaultColorProvider, colorProviderRegistry) {
    if (!this.b.hasModel()) {
      return null;
    }
    const colorDetector = $Lbb.get(this.b);
    if (!colorDetector) {
      return null;
    }
    const colors = await $Ebb(colorProviderRegistry, this.b.getModel(), CancellationToken.None);
    let foundColorInfo = null;
    let foundColorProvider = null;
    for (const colorData of colors) {
      const colorInfo2 = colorData.colorInfo;
      if ($9C.containsRange(colorInfo2.range, defaultColorInfo.range)) {
        foundColorInfo = colorInfo2;
        foundColorProvider = colorData.provider;
      }
    }
    const colorInfo = foundColorInfo ?? defaultColorInfo;
    const colorProvider = foundColorProvider ?? defaultColorProvider;
    const foundInEditor = !!foundColorInfo;
    const colorHover = $Dfb.fromBaseColor(this, await $Qdb(this.b.getModel(), colorInfo, colorProvider));
    return { colorHover, foundInEditor };
  }
  async updateEditorModel(colorHoverData) {
    if (!this.b.hasModel()) {
      return;
    }
    const colorPickerModel = colorHoverData.model;
    let range = new $9C(colorHoverData.range.startLineNumber, colorHoverData.range.startColumn, colorHoverData.range.endLineNumber, colorHoverData.range.endColumn);
    if (this.a) {
      await $Sdb(this.b.getModel(), colorPickerModel, this.a, range, colorHoverData);
      range = $Rdb(this.b, range, colorPickerModel);
    }
  }
  renderHoverParts(context, hoverParts) {
    if (hoverParts.length === 0 || !this.b.hasModel()) {
      return void 0;
    }
    if (context.setMinimumDimensions) {
      const minimumHeight = this.b.getOption(
        68
        /* EditorOption.lineHeight */
      ) + 8;
      context.setMinimumDimensions(new $rj(302, minimumHeight));
    }
    const disposables = new $2c();
    const colorHover = hoverParts[0];
    const editorModel = this.b.getModel();
    const model = colorHover.model;
    const colorPicker = disposables.add(new $Zdb(
      context.fragment,
      model,
      this.b.getOption(
        149
        /* EditorOption.pixelRatio */
      ),
      this.c,
      "standalone"
      /* ColorPickerWidgetType.Standalone */
    ));
    let editorUpdatedByColorPicker = false;
    const range = new $9C(colorHover.range.startLineNumber, colorHover.range.startColumn, colorHover.range.endLineNumber, colorHover.range.endColumn);
    const color2 = colorHover.model.color;
    this.a = color2;
    $Sdb(editorModel, model, color2, range, colorHover);
    disposables.add(model.onColorFlushed((color3) => {
      this.a = color3;
    }));
    disposables.add(model.onDidChangeColor((color3) => {
      $Sdb(editorModel, model, color3, range, colorHover);
    }));
    disposables.add(this.b.onDidChangeModelContent((e) => {
      if (editorUpdatedByColorPicker) {
        editorUpdatedByColorPicker = false;
      } else {
        context.hide();
        this.b.focus();
      }
    }));
    return { hoverPart: colorHover, colorPicker, disposables };
  }
};
$Efb = __decorate([
  __param(1, $gs)
], $Efb);

// out-build/vs/editor/contrib/colorPicker/browser/standaloneColorPicker/standaloneColorPickerWidget.js
var $Ffb_1;
var StandaloneColorPickerResult = class {
  // The color picker result consists of: an array of color results and a boolean indicating if the color was found in the editor
  constructor(value, foundInEditor) {
    this.value = value;
    this.foundInEditor = foundInEditor;
  }
};
var PADDING = 8;
var CLOSE_BUTTON_WIDTH = 22;
var $Ffb = class $Ffb2 extends $3c {
  static {
    $Ffb_1 = this;
  }
  static {
    this.ID = "editor.contrib.standaloneColorPickerWidget";
  }
  constructor(j, m, n, _instantiationService, r2, s, t, u) {
    super();
    this.j = j;
    this.m = m;
    this.n = n;
    this.r = r2;
    this.s = s;
    this.t = t;
    this.u = u;
    this.allowEditorOverflow = true;
    this.a = void 0;
    this.c = document.createElement("div");
    this.f = null;
    this.g = false;
    this.h = this.B(new $ze());
    this.onResult = this.h.event;
    this.m.set(true);
    this.b = _instantiationService.createInstance($Efb, this.j);
    this.a = this.j._getViewModel()?.getPrimaryCursorState().modelState.position;
    const editorSelection = this.j.getSelection();
    const selection = editorSelection ? {
      startLineNumber: editorSelection.startLineNumber,
      startColumn: editorSelection.startColumn,
      endLineNumber: editorSelection.endLineNumber,
      endColumn: editorSelection.endColumn
    } : { startLineNumber: 0, endLineNumber: 0, endColumn: 0, startColumn: 0 };
    const focusTracker = this.B($_j(this.c));
    this.B(focusTracker.onDidBlur((_) => {
      this.hide();
    }));
    this.B(focusTracker.onDidFocus((_) => {
      this.focus();
    }));
    this.B(this.j.onDidChangeCursorPosition(() => {
      if (!this.g) {
        this.hide();
      } else {
        this.g = false;
      }
    }));
    this.B(this.j.onMouseMove((e) => {
      const classList = e.target.element?.classList;
      if (classList && classList.contains("colorpicker-color-decoration")) {
        this.hide();
      }
    }));
    this.B(this.onResult((result) => {
      this.z(result.value, result.foundInEditor);
    }));
    this.w(selection);
    this.c.style.zIndex = "50";
    this.j.addContentWidget(this);
  }
  updateEditor() {
    if (this.f) {
      this.b.updateEditorModel(this.f);
    }
  }
  getId() {
    return $Ffb_1.ID;
  }
  getDomNode() {
    return this.c;
  }
  getPosition() {
    if (!this.a) {
      return null;
    }
    const positionPreference = this.j.getOption(
      62
      /* EditorOption.hover */
    ).above;
    return {
      position: this.a,
      secondaryPosition: this.a,
      preference: positionPreference ? [
        1,
        2
        /* ContentWidgetPositionPreference.BELOW */
      ] : [
        2,
        1
        /* ContentWidgetPositionPreference.ABOVE */
      ],
      positionAffinity: 2
      /* PositionAffinity.None */
    };
  }
  hide() {
    this.dispose();
    this.m.set(false);
    this.n.set(false);
    this.j.removeContentWidget(this);
    this.j.focus();
  }
  focus() {
    this.n.set(true);
    this.c.focus();
  }
  async w(selection) {
    const computeAsyncResult = await this.y(selection);
    if (!computeAsyncResult) {
      return;
    }
    this.h.fire(new StandaloneColorPickerResult(computeAsyncResult.result, computeAsyncResult.foundInEditor));
  }
  async y(range) {
    if (!this.j.hasModel()) {
      return null;
    }
    const colorInfo = {
      range,
      color: { red: 0, green: 0, blue: 0, alpha: 1 }
    };
    const colorHoverResult = await this.b.createColorHover(colorInfo, new $Cbb(this.t), this.s.colorProvider);
    if (!colorHoverResult) {
      return null;
    }
    return { result: colorHoverResult.colorHover, foundInEditor: colorHoverResult.foundInEditor };
  }
  z(colorHover, foundInEditor) {
    const fragment = document.createDocumentFragment();
    const statusBar = this.B(new $Cdb(this.r, this.u));
    const context = {
      fragment,
      statusBar,
      onContentsChanged: () => {
      },
      hide: () => this.hide()
    };
    this.f = colorHover;
    const renderedHoverPart = this.b.renderHoverParts(context, [colorHover]);
    if (!renderedHoverPart) {
      return;
    }
    this.B(renderedHoverPart.disposables);
    const colorPicker = renderedHoverPart.colorPicker;
    this.c.classList.add("standalone-colorpicker-body");
    this.c.style.maxHeight = Math.max(this.j.getLayoutInfo().height / 4, 250) + "px";
    this.c.style.maxWidth = Math.max(this.j.getLayoutInfo().width * 0.66, 500) + "px";
    this.c.tabIndex = 0;
    this.c.appendChild(fragment);
    colorPicker.layout();
    const colorPickerBody = colorPicker.body;
    const saturationBoxWidth = colorPickerBody.saturationBox.domNode.clientWidth;
    const widthOfOriginalColorBox = colorPickerBody.domNode.clientWidth - saturationBoxWidth - CLOSE_BUTTON_WIDTH - PADDING;
    const enterButton = colorPicker.body.enterButton;
    enterButton?.onClicked(() => {
      this.updateEditor();
      this.hide();
    });
    const colorPickerHeader = colorPicker.header;
    const pickedColorNode = colorPickerHeader.pickedColorNode;
    pickedColorNode.style.width = saturationBoxWidth + PADDING + "px";
    const originalColorNode = colorPickerHeader.originalColorNode;
    originalColorNode.style.width = widthOfOriginalColorBox + "px";
    const closeButton = colorPicker.header.closeButton;
    closeButton?.onClicked(() => {
      this.hide();
    });
    if (foundInEditor) {
      if (enterButton) {
        enterButton.button.textContent = "Replace";
      }
      this.g = true;
      this.j.setSelection(colorHover.range);
    }
    this.j.layoutContentWidget(this);
  }
};
$Ffb = $Ffb_1 = __decorate([
  __param(3, $Pk),
  __param(4, $Ty),
  __param(5, $mP),
  __param(6, $I0),
  __param(7, $5$)
], $Ffb);

// out-build/vs/editor/contrib/colorPicker/browser/standaloneColorPicker/standaloneColorPickerController.js
var $Gfb_1;
var $Gfb = class $Gfb2 extends $3c {
  static {
    $Gfb_1 = this;
  }
  static {
    this.ID = "editor.contrib.standaloneColorPickerController";
  }
  constructor(f, _contextKeyService, g) {
    super();
    this.f = f;
    this.g = g;
    this.a = null;
    this.b = EditorContextKeys.standaloneColorPickerVisible.bindTo(_contextKeyService);
    this.c = EditorContextKeys.standaloneColorPickerFocused.bindTo(_contextKeyService);
  }
  showOrFocus() {
    if (!this.f.hasModel()) {
      return;
    }
    if (!this.b.get()) {
      this.a = this.g.createInstance($Ffb, this.f, this.b, this.c);
    } else if (!this.c.get()) {
      this.a?.focus();
    }
  }
  hide() {
    this.c.set(false);
    this.b.set(false);
    this.a?.hide();
    this.f.focus();
  }
  insertColor() {
    this.a?.updateEditor();
    this.hide();
  }
  static get(editor) {
    return editor.getContribution($Gfb_1.ID);
  }
};
$Gfb = $Gfb_1 = __decorate([
  __param(1, $on),
  __param(2, $Pk)
], $Gfb);

// out-build/vs/editor/contrib/colorPicker/browser/standaloneColorPicker/standaloneColorPickerActions.js
var $Hfb = class extends $25 {
  constructor() {
    super({
      id: "editor.action.showOrFocusStandaloneColorPicker",
      title: {
        ...localize2(964, "Show or Focus Standalone Color Picker"),
        mnemonicTitle: localize(963, null)
      },
      precondition: void 0,
      menu: [
        { id: $bJ.CommandPalette }
      ],
      metadata: {
        description: localize2(965, "Show or focus a standalone color picker which uses the default color provider. It displays hex/rgb/hsl colors.")
      }
    });
  }
  runEditorCommand(_accessor, editor) {
    $Gfb.get(editor)?.showOrFocus();
  }
};
var $Ifb = class extends $Z5 {
  constructor() {
    super({
      id: "editor.action.hideColorPicker",
      label: localize2(966, "Hide the Color Picker"),
      precondition: EditorContextKeys.standaloneColorPickerVisible.isEqualTo(true),
      kbOpts: {
        primary: 9,
        weight: 100
        /* KeybindingWeight.EditorContrib */
      },
      metadata: {
        description: localize2(967, "Hide the standalone color picker.")
      }
    });
  }
  run(_accessor, editor) {
    $Gfb.get(editor)?.hide();
  }
};
var $Jfb = class extends $Z5 {
  constructor() {
    super({
      id: "editor.action.insertColorWithStandaloneColorPicker",
      label: localize2(968, "Insert Color with Standalone Color Picker"),
      precondition: EditorContextKeys.standaloneColorPickerFocused.isEqualTo(true),
      kbOpts: {
        primary: 3,
        weight: 100
        /* KeybindingWeight.EditorContrib */
      },
      metadata: {
        description: localize2(969, "Insert hex/rgb/hsl colors with the focused standalone color picker.")
      }
    });
  }
  run(_accessor, editor) {
    $Gfb.get(editor)?.insertColor();
  }
};

// out-build/vs/editor/contrib/colorPicker/browser/colorPickerContribution.js
$55($Ifb);
$55($Jfb);
$hJ($Hfb);
$85(
  $Bfb.ID,
  $Bfb,
  2
  /* EditorContributionInstantiation.BeforeFirstInteraction */
);
$85(
  $Gfb.ID,
  $Gfb,
  1
  /* EditorContributionInstantiation.AfterFirstRender */
);
$85(
  $Lbb.ID,
  $Lbb,
  1
  /* EditorContributionInstantiation.AfterFirstRender */
);
$T_($Dbb);
$Bbb.register($2db);
$tn.registerCommand("_executeDocumentColorProvider", function(accessor, ...args2) {
  const [resource] = args2;
  if (!(resource instanceof URI)) {
    throw $nb();
  }
  const { model, colorProviderRegistry, defaultColorDecoratorsEnablement } = $Jbb(accessor, resource);
  return $Ibb(new $Gbb(), colorProviderRegistry, model, CancellationToken.None, defaultColorDecoratorsEnablement);
});
$tn.registerCommand("_executeColorPresentationProvider", function(accessor, ...args2) {
  const [color2, context] = args2;
  const { uri, range } = context;
  if (!(uri instanceof URI) || !Array.isArray(color2) || color2.length !== 4 || !$9C.isIRange(range)) {
    throw $nb();
  }
  const { model, colorProviderRegistry, defaultColorDecoratorsEnablement } = $Jbb(accessor, uri);
  const [red, green, blue, alpha] = color2;
  return $Ibb(new $Hbb({ range, color: { red, green, blue, alpha } }), colorProviderRegistry, model, CancellationToken.None, defaultColorDecoratorsEnablement);
});

// out-build/vs/editor/contrib/comment/browser/blockCommentCommand.js
var $Kfb = class _$Kfb {
  constructor(selection, insertSpace, d) {
    this.d = d;
    this.a = selection;
    this.b = insertSpace;
    this.c = null;
  }
  static _haystackHasNeedleAtOffset(haystack, needle, offset) {
    if (offset < 0) {
      return false;
    }
    const needleLength = needle.length;
    const haystackLength = haystack.length;
    if (offset + needleLength > haystackLength) {
      return false;
    }
    for (let i2 = 0; i2 < needleLength; i2++) {
      const codeA = haystack.charCodeAt(offset + i2);
      const codeB = needle.charCodeAt(i2);
      if (codeA === codeB) {
        continue;
      }
      if (codeA >= 65 && codeA <= 90 && codeA + 32 === codeB) {
        continue;
      }
      if (codeB >= 65 && codeB <= 90 && codeB + 32 === codeA) {
        continue;
      }
      return false;
    }
    return true;
  }
  e(selection, startToken, endToken, insertSpace, model, builder) {
    const startLineNumber = selection.startLineNumber;
    const startColumn = selection.startColumn;
    const endLineNumber = selection.endLineNumber;
    const endColumn = selection.endColumn;
    const startLineText = model.getLineContent(startLineNumber);
    const endLineText = model.getLineContent(endLineNumber);
    let startTokenIndex = startLineText.lastIndexOf(startToken, startColumn - 1 + startToken.length);
    let endTokenIndex = endLineText.indexOf(endToken, endColumn - 1 - endToken.length);
    if (startTokenIndex !== -1 && endTokenIndex !== -1) {
      if (startLineNumber === endLineNumber) {
        const lineBetweenTokens = startLineText.substring(startTokenIndex + startToken.length, endTokenIndex);
        if (lineBetweenTokens.indexOf(endToken) >= 0) {
          startTokenIndex = -1;
          endTokenIndex = -1;
        }
      } else {
        const startLineAfterStartToken = startLineText.substring(startTokenIndex + startToken.length);
        const endLineBeforeEndToken = endLineText.substring(0, endTokenIndex);
        if (startLineAfterStartToken.indexOf(endToken) >= 0 || endLineBeforeEndToken.indexOf(endToken) >= 0) {
          startTokenIndex = -1;
          endTokenIndex = -1;
        }
      }
    }
    let ops;
    if (startTokenIndex !== -1 && endTokenIndex !== -1) {
      if (insertSpace && startTokenIndex + startToken.length < startLineText.length && startLineText.charCodeAt(startTokenIndex + startToken.length) === 32) {
        startToken = startToken + " ";
      }
      if (insertSpace && endTokenIndex > 0 && endLineText.charCodeAt(endTokenIndex - 1) === 32) {
        endToken = " " + endToken;
        endTokenIndex -= 1;
      }
      ops = _$Kfb._createRemoveBlockCommentOperations(new $9C(startLineNumber, startTokenIndex + startToken.length + 1, endLineNumber, endTokenIndex + 1), startToken, endToken);
    } else {
      ops = _$Kfb._createAddBlockCommentOperations(selection, startToken, endToken, this.b);
      this.c = ops.length === 1 ? endToken : null;
    }
    for (const op of ops) {
      builder.addTrackedEditOperation(op.range, op.text);
    }
  }
  static _createRemoveBlockCommentOperations(r2, startToken, endToken) {
    const res = [];
    if (!$9C.isEmpty(r2)) {
      res.push($bD.delete(new $9C(r2.startLineNumber, r2.startColumn - startToken.length, r2.startLineNumber, r2.startColumn)));
      res.push($bD.delete(new $9C(r2.endLineNumber, r2.endColumn, r2.endLineNumber, r2.endColumn + endToken.length)));
    } else {
      res.push($bD.delete(new $9C(r2.startLineNumber, r2.startColumn - startToken.length, r2.endLineNumber, r2.endColumn + endToken.length)));
    }
    return res;
  }
  static _createAddBlockCommentOperations(r2, startToken, endToken, insertSpace) {
    const res = [];
    if (!$9C.isEmpty(r2)) {
      res.push($bD.insert(new $8C(r2.startLineNumber, r2.startColumn), startToken + (insertSpace ? " " : "")));
      res.push($bD.insert(new $8C(r2.endLineNumber, r2.endColumn), (insertSpace ? " " : "") + endToken));
    } else {
      res.push($bD.replace(new $9C(r2.startLineNumber, r2.startColumn, r2.endLineNumber, r2.endColumn), startToken + "  " + endToken));
    }
    return res;
  }
  getEditOperations(model, builder) {
    const startLineNumber = this.a.startLineNumber;
    const startColumn = this.a.startColumn;
    model.tokenization.tokenizeIfCheap(startLineNumber);
    const languageId = model.getLanguageIdAtPosition(startLineNumber, startColumn);
    const config = this.d.getLanguageConfiguration(languageId).comments;
    if (!config || !config.blockCommentStartToken || !config.blockCommentEndToken) {
      return;
    }
    this.e(this.a, config.blockCommentStartToken, config.blockCommentEndToken, this.b, model, builder);
  }
  computeCursorState(model, helper) {
    const inverseEditOperations = helper.getInverseEditOperations();
    if (inverseEditOperations.length === 2) {
      const startTokenEditOperation = inverseEditOperations[0];
      const endTokenEditOperation = inverseEditOperations[1];
      return new $_D(startTokenEditOperation.range.endLineNumber, startTokenEditOperation.range.endColumn, endTokenEditOperation.range.startLineNumber, endTokenEditOperation.range.startColumn);
    } else {
      const srcRange = inverseEditOperations[0].range;
      const deltaColumn = this.c ? -this.c.length - 1 : 0;
      return new $_D(srcRange.endLineNumber, srcRange.endColumn + deltaColumn, srcRange.endLineNumber, srcRange.endColumn + deltaColumn);
    }
  }
};

// out-build/vs/editor/contrib/comment/browser/lineCommentCommand.js
var Type2;
(function(Type4) {
  Type4[Type4["Toggle"] = 0] = "Toggle";
  Type4[Type4["ForceAdd"] = 1] = "ForceAdd";
  Type4[Type4["ForceRemove"] = 2] = "ForceRemove";
})(Type2 || (Type2 = {}));
var $Lfb = class _$Lfb {
  constructor(l, selection, indentSize, type, insertSpace, ignoreEmptyLines, ignoreFirstLine) {
    this.l = l;
    this.a = selection;
    this.b = indentSize;
    this.c = type;
    this.d = insertSpace;
    this.f = null;
    this.g = 0;
    this.h = false;
    this.e = ignoreEmptyLines;
    this.k = ignoreFirstLine || false;
  }
  /**
   * Do an initial pass over the lines and gather info about the line comment string.
   * Returns null if any of the lines doesn't support a line comment string.
   */
  static m(model, startLineNumber, endLineNumber, languageConfigurationService) {
    model.tokenization.tokenizeIfCheap(startLineNumber);
    const languageId = model.getLanguageIdAtPosition(startLineNumber, 1);
    const config = languageConfigurationService.getLanguageConfiguration(languageId).comments;
    const commentStr = config ? config.lineCommentToken : null;
    if (!commentStr) {
      return null;
    }
    const lines = [];
    for (let i2 = 0, lineCount = endLineNumber - startLineNumber + 1; i2 < lineCount; i2++) {
      lines[i2] = {
        ignore: false,
        commentStr,
        commentStrOffset: 0,
        commentStrLength: commentStr.length
      };
    }
    return lines;
  }
  /**
   * Analyze lines and decide which lines are relevant and what the toggle should do.
   * Also, build up several offsets and lengths useful in the generation of editor operations.
   */
  static _analyzeLines(type, insertSpace, model, lines, startLineNumber, ignoreEmptyLines, ignoreFirstLine, languageConfigurationService) {
    let onlyWhitespaceLines = true;
    let shouldRemoveComments;
    if (type === 0) {
      shouldRemoveComments = true;
    } else if (type === 1) {
      shouldRemoveComments = false;
    } else {
      shouldRemoveComments = true;
    }
    for (let i2 = 0, lineCount = lines.length; i2 < lineCount; i2++) {
      const lineData = lines[i2];
      const lineNumber = startLineNumber + i2;
      if (lineNumber === startLineNumber && ignoreFirstLine) {
        lineData.ignore = true;
        continue;
      }
      const lineContent = model.getLineContent(lineNumber);
      const lineContentStartOffset = $Of(lineContent);
      if (lineContentStartOffset === -1) {
        lineData.ignore = ignoreEmptyLines;
        lineData.commentStrOffset = lineContent.length;
        continue;
      }
      onlyWhitespaceLines = false;
      lineData.ignore = false;
      lineData.commentStrOffset = lineContentStartOffset;
      if (shouldRemoveComments && !$Kfb._haystackHasNeedleAtOffset(lineContent, lineData.commentStr, lineContentStartOffset)) {
        if (type === 0) {
          shouldRemoveComments = false;
        } else if (type === 1) {
        } else {
          lineData.ignore = true;
        }
      }
      if (shouldRemoveComments && insertSpace) {
        const commentStrEndOffset = lineContentStartOffset + lineData.commentStrLength;
        if (commentStrEndOffset < lineContent.length && lineContent.charCodeAt(commentStrEndOffset) === 32) {
          lineData.commentStrLength += 1;
        }
      }
    }
    if (type === 0 && onlyWhitespaceLines) {
      shouldRemoveComments = false;
      for (let i2 = 0, lineCount = lines.length; i2 < lineCount; i2++) {
        lines[i2].ignore = false;
      }
    }
    return {
      supported: true,
      shouldRemoveComments,
      lines
    };
  }
  /**
   * Analyze all lines and decide exactly what to do => not supported | insert line comments | remove line comments
   */
  static _gatherPreflightData(type, insertSpace, model, startLineNumber, endLineNumber, ignoreEmptyLines, ignoreFirstLine, languageConfigurationService) {
    const lines = _$Lfb.m(model, startLineNumber, endLineNumber, languageConfigurationService);
    if (lines === null) {
      return {
        supported: false
      };
    }
    return _$Lfb._analyzeLines(type, insertSpace, model, lines, startLineNumber, ignoreEmptyLines, ignoreFirstLine, languageConfigurationService);
  }
  /**
   * Given a successful analysis, execute either insert line comments, either remove line comments
   */
  n(model, builder, data, s) {
    let ops;
    if (data.shouldRemoveComments) {
      ops = _$Lfb._createRemoveLineCommentsOperations(data.lines, s.startLineNumber);
    } else {
      _$Lfb._normalizeInsertionPoint(model, data.lines, s.startLineNumber, this.b);
      ops = this.q(data.lines, s.startLineNumber);
    }
    const cursorPosition = new $8C(s.positionLineNumber, s.positionColumn);
    for (let i2 = 0, len = ops.length; i2 < len; i2++) {
      builder.addEditOperation(ops[i2].range, ops[i2].text);
      if ($9C.isEmpty(ops[i2].range) && $9C.getStartPosition(ops[i2].range).equals(cursorPosition)) {
        const lineContent = model.getLineContent(cursorPosition.lineNumber);
        if (lineContent.length + 1 === cursorPosition.column) {
          this.g = (ops[i2].text || "").length;
        }
      }
    }
    this.f = builder.trackSelection(s);
  }
  o(model, s, startToken, endToken) {
    let startLineNumber = s.startLineNumber;
    let endLineNumber = s.endLineNumber;
    const startTokenAllowedBeforeColumn = endToken.length + Math.max(model.getLineFirstNonWhitespaceColumn(s.startLineNumber), s.startColumn);
    let startTokenIndex = model.getLineContent(startLineNumber).lastIndexOf(startToken, startTokenAllowedBeforeColumn - 1);
    let endTokenIndex = model.getLineContent(endLineNumber).indexOf(endToken, s.endColumn - 1 - startToken.length);
    if (startTokenIndex !== -1 && endTokenIndex === -1) {
      endTokenIndex = model.getLineContent(startLineNumber).indexOf(endToken, startTokenIndex + startToken.length);
      endLineNumber = startLineNumber;
    }
    if (startTokenIndex === -1 && endTokenIndex !== -1) {
      startTokenIndex = model.getLineContent(endLineNumber).lastIndexOf(startToken, endTokenIndex);
      startLineNumber = endLineNumber;
    }
    if (s.isEmpty() && (startTokenIndex === -1 || endTokenIndex === -1)) {
      startTokenIndex = model.getLineContent(startLineNumber).indexOf(startToken);
      if (startTokenIndex !== -1) {
        endTokenIndex = model.getLineContent(startLineNumber).indexOf(endToken, startTokenIndex + startToken.length);
      }
    }
    if (startTokenIndex !== -1 && model.getLineContent(startLineNumber).charCodeAt(startTokenIndex + startToken.length) === 32) {
      startToken += " ";
    }
    if (endTokenIndex !== -1 && model.getLineContent(endLineNumber).charCodeAt(endTokenIndex - 1) === 32) {
      endToken = " " + endToken;
      endTokenIndex -= 1;
    }
    if (startTokenIndex !== -1 && endTokenIndex !== -1) {
      return $Kfb._createRemoveBlockCommentOperations(new $9C(startLineNumber, startTokenIndex + startToken.length + 1, endLineNumber, endTokenIndex + 1), startToken, endToken);
    }
    return null;
  }
  /**
   * Given an unsuccessful analysis, delegate to the block comment command
   */
  p(model, builder, s) {
    model.tokenization.tokenizeIfCheap(s.startLineNumber);
    const languageId = model.getLanguageIdAtPosition(s.startLineNumber, 1);
    const config = this.l.getLanguageConfiguration(languageId).comments;
    if (!config || !config.blockCommentStartToken || !config.blockCommentEndToken) {
      return;
    }
    const startToken = config.blockCommentStartToken;
    const endToken = config.blockCommentEndToken;
    let ops = this.o(model, s, startToken, endToken);
    if (!ops) {
      if (s.isEmpty()) {
        const lineContent = model.getLineContent(s.startLineNumber);
        let firstNonWhitespaceIndex = $Of(lineContent);
        if (firstNonWhitespaceIndex === -1) {
          firstNonWhitespaceIndex = lineContent.length;
        }
        ops = $Kfb._createAddBlockCommentOperations(new $9C(s.startLineNumber, firstNonWhitespaceIndex + 1, s.startLineNumber, lineContent.length + 1), startToken, endToken, this.d);
      } else {
        ops = $Kfb._createAddBlockCommentOperations(new $9C(s.startLineNumber, model.getLineFirstNonWhitespaceColumn(s.startLineNumber), s.endLineNumber, model.getLineMaxColumn(s.endLineNumber)), startToken, endToken, this.d);
      }
      if (ops.length === 1) {
        this.g = startToken.length + 1;
      }
    }
    this.f = builder.trackSelection(s);
    for (const op of ops) {
      builder.addEditOperation(op.range, op.text);
    }
  }
  getEditOperations(model, builder) {
    let s = this.a;
    this.h = false;
    if (s.startLineNumber === s.endLineNumber && this.k) {
      builder.addEditOperation(new $9C(s.startLineNumber, model.getLineMaxColumn(s.startLineNumber), s.startLineNumber + 1, 1), s.startLineNumber === model.getLineCount() ? "" : "\n");
      this.f = builder.trackSelection(s);
      return;
    }
    if (s.startLineNumber < s.endLineNumber && s.endColumn === 1) {
      this.h = true;
      s = s.setEndPosition(s.endLineNumber - 1, model.getLineMaxColumn(s.endLineNumber - 1));
    }
    const data = _$Lfb._gatherPreflightData(this.c, this.d, model, s.startLineNumber, s.endLineNumber, this.e, this.k, this.l);
    if (data.supported) {
      return this.n(model, builder, data, s);
    }
    return this.p(model, builder, s);
  }
  computeCursorState(model, helper) {
    let result = helper.getTrackedSelection(this.f);
    if (this.h) {
      result = result.setEndPosition(result.endLineNumber + 1, 1);
    }
    return new $_D(result.selectionStartLineNumber, result.selectionStartColumn + this.g, result.positionLineNumber, result.positionColumn + this.g);
  }
  /**
   * Generate edit operations in the remove line comment case
   */
  static _createRemoveLineCommentsOperations(lines, startLineNumber) {
    const res = [];
    for (let i2 = 0, len = lines.length; i2 < len; i2++) {
      const lineData = lines[i2];
      if (lineData.ignore) {
        continue;
      }
      res.push($bD.delete(new $9C(startLineNumber + i2, lineData.commentStrOffset + 1, startLineNumber + i2, lineData.commentStrOffset + lineData.commentStrLength + 1)));
    }
    return res;
  }
  /**
   * Generate edit operations in the add line comment case
   */
  q(lines, startLineNumber) {
    const res = [];
    const afterCommentStr = this.d ? " " : "";
    for (let i2 = 0, len = lines.length; i2 < len; i2++) {
      const lineData = lines[i2];
      if (lineData.ignore) {
        continue;
      }
      res.push($bD.insert(new $8C(startLineNumber + i2, lineData.commentStrOffset + 1), lineData.commentStr + afterCommentStr));
    }
    return res;
  }
  static r(currentVisibleColumn, indentSize, isTab, columnSize) {
    if (isTab) {
      return currentVisibleColumn + (indentSize - currentVisibleColumn % indentSize);
    }
    return currentVisibleColumn + columnSize;
  }
  /**
   * Adjust insertion points to have them vertically aligned in the add line comment case
   */
  static _normalizeInsertionPoint(model, lines, startLineNumber, indentSize) {
    let minVisibleColumn = 1073741824;
    let j;
    let lenJ;
    for (let i2 = 0, len = lines.length; i2 < len; i2++) {
      if (lines[i2].ignore) {
        continue;
      }
      const lineContent = model.getLineContent(startLineNumber + i2);
      let currentVisibleColumn = 0;
      for (let j2 = 0, lenJ2 = lines[i2].commentStrOffset; currentVisibleColumn < minVisibleColumn && j2 < lenJ2; j2++) {
        currentVisibleColumn = _$Lfb.r(currentVisibleColumn, indentSize, lineContent.charCodeAt(j2) === 9, 1);
      }
      if (currentVisibleColumn < minVisibleColumn) {
        minVisibleColumn = currentVisibleColumn;
      }
    }
    minVisibleColumn = Math.floor(minVisibleColumn / indentSize) * indentSize;
    for (let i2 = 0, len = lines.length; i2 < len; i2++) {
      if (lines[i2].ignore) {
        continue;
      }
      const lineContent = model.getLineContent(startLineNumber + i2);
      let currentVisibleColumn = 0;
      for (j = 0, lenJ = lines[i2].commentStrOffset; currentVisibleColumn < minVisibleColumn && j < lenJ; j++) {
        currentVisibleColumn = _$Lfb.r(currentVisibleColumn, indentSize, lineContent.charCodeAt(j) === 9, 1);
      }
      if (currentVisibleColumn > minVisibleColumn) {
        lines[i2].commentStrOffset = j - 1;
      } else {
        lines[i2].commentStrOffset = j;
      }
    }
  }
};

// out-build/vs/editor/contrib/comment/browser/comment.js
var CommentLineAction = class extends $Z5 {
  constructor(type, opts) {
    super(opts);
    this.d = type;
  }
  run(accessor, editor) {
    const languageConfigurationService = accessor.get($NF);
    if (!editor.hasModel()) {
      return;
    }
    const model = editor.getModel();
    const commands2 = [];
    const modelOptions = model.getOptions();
    const commentsOptions = editor.getOption(
      23
      /* EditorOption.comments */
    );
    const selections = editor.getSelections().map((selection, index) => ({ selection, index, ignoreFirstLine: false }));
    selections.sort((a, b) => $9C.compareRangesUsingStarts(a.selection, b.selection));
    let prev = selections[0];
    for (let i2 = 1; i2 < selections.length; i2++) {
      const curr = selections[i2];
      if (prev.selection.endLineNumber === curr.selection.startLineNumber) {
        if (prev.index < curr.index) {
          curr.ignoreFirstLine = true;
        } else {
          prev.ignoreFirstLine = true;
          prev = curr;
        }
      }
    }
    for (const selection of selections) {
      commands2.push(new $Lfb(languageConfigurationService, selection.selection, modelOptions.indentSize, this.d, commentsOptions.insertSpace, commentsOptions.ignoreEmptyLines, selection.ignoreFirstLine));
    }
    editor.pushUndoStop();
    editor.executeCommands(this.id, commands2);
    editor.pushUndoStop();
  }
};
var ToggleCommentLineAction = class extends CommentLineAction {
  constructor() {
    super(0, {
      id: "editor.action.commentLine",
      label: localize2(972, "Toggle Line Comment"),
      precondition: EditorContextKeys.writable,
      kbOpts: {
        kbExpr: EditorContextKeys.editorTextFocus,
        primary: 2048 | 90,
        weight: 100
        /* KeybindingWeight.EditorContrib */
      },
      menuOpts: {
        menuId: $bJ.MenubarEditMenu,
        group: "5_insert",
        title: localize(970, null),
        order: 1
      }
    });
  }
};
var AddLineCommentAction = class extends CommentLineAction {
  constructor() {
    super(1, {
      id: "editor.action.addCommentLine",
      label: localize2(973, "Add Line Comment"),
      precondition: EditorContextKeys.writable,
      kbOpts: {
        kbExpr: EditorContextKeys.editorTextFocus,
        primary: $$e(
          2048 | 41,
          2048 | 33
          /* KeyCode.KeyC */
        ),
        weight: 100
        /* KeybindingWeight.EditorContrib */
      }
    });
  }
};
var RemoveLineCommentAction = class extends CommentLineAction {
  constructor() {
    super(2, {
      id: "editor.action.removeCommentLine",
      label: localize2(974, "Remove Line Comment"),
      precondition: EditorContextKeys.writable,
      kbOpts: {
        kbExpr: EditorContextKeys.editorTextFocus,
        primary: $$e(
          2048 | 41,
          2048 | 51
          /* KeyCode.KeyU */
        ),
        weight: 100
        /* KeybindingWeight.EditorContrib */
      }
    });
  }
};
var BlockCommentAction = class extends $Z5 {
  constructor() {
    super({
      id: "editor.action.blockComment",
      label: localize2(975, "Toggle Block Comment"),
      precondition: EditorContextKeys.writable,
      kbOpts: {
        kbExpr: EditorContextKeys.editorTextFocus,
        primary: 1024 | 512 | 31,
        linux: {
          primary: 2048 | 1024 | 31
          /* KeyCode.KeyA */
        },
        weight: 100
        /* KeybindingWeight.EditorContrib */
      },
      menuOpts: {
        menuId: $bJ.MenubarEditMenu,
        group: "5_insert",
        title: localize(971, null),
        order: 2
      }
    });
  }
  run(accessor, editor) {
    const languageConfigurationService = accessor.get($NF);
    if (!editor.hasModel()) {
      return;
    }
    const commentsOptions = editor.getOption(
      23
      /* EditorOption.comments */
    );
    const commands2 = [];
    const selections = editor.getSelections();
    for (const selection of selections) {
      commands2.push(new $Kfb(selection, commentsOptions.insertSpace, languageConfigurationService));
    }
    editor.pushUndoStop();
    editor.executeCommands(this.id, commands2);
    editor.pushUndoStop();
  }
};
$55(ToggleCommentLineAction);
$55(AddLineCommentAction);
$55(RemoveLineCommentAction);
$55(BlockCommentAction);

// out-build/vs/editor/contrib/contextmenu/browser/contextmenu.js
var $Mfb_1;
var $Mfb = class $Mfb2 {
  static {
    $Mfb_1 = this;
  }
  static {
    this.ID = "editor.contrib.contextmenu";
  }
  static get(editor) {
    return editor.getContribution($Mfb_1.ID);
  }
  constructor(editor, d, f, g, h3, i2, j, k) {
    this.d = d;
    this.f = f;
    this.g = g;
    this.h = h3;
    this.i = i2;
    this.j = j;
    this.k = k;
    this.a = new $2c();
    this.b = 0;
    this.c = editor;
    this.a.add(this.c.onContextMenu((e) => this.l(e)));
    this.a.add(this.c.onMouseWheel((e) => {
      if (this.b > 0) {
        const view = this.f.getContextViewElement();
        const target = e.srcElement;
        if (!(target.shadowRoot && $Kj(view) === target.shadowRoot)) {
          this.f.hideContextView();
        }
      }
    }));
    this.a.add(this.c.onKeyDown((e) => {
      if (!this.c.getOption(
        24
        /* EditorOption.contextmenu */
      )) {
        return;
      }
      if (e.keyCode === 58) {
        e.preventDefault();
        e.stopPropagation();
        this.showContextMenu();
      }
    }));
  }
  l(e) {
    if (!this.c.hasModel()) {
      return;
    }
    if (!this.c.getOption(
      24
      /* EditorOption.contextmenu */
    )) {
      this.c.focus();
      if (e.target.position && !this.c.getSelection().containsPosition(e.target.position)) {
        this.c.setPosition(e.target.position);
      }
      return;
    }
    if (e.target.type === 12) {
      return;
    }
    if (e.target.type === 6 && e.target.detail.injectedText) {
      return;
    }
    e.event.preventDefault();
    e.event.stopPropagation();
    if (e.target.type === 11) {
      return this.o(e.event);
    }
    if (e.target.type !== 6 && e.target.type !== 7 && e.target.type !== 1) {
      return;
    }
    this.c.focus();
    if (e.target.position) {
      let hasSelectionAtPosition = false;
      for (const selection of this.c.getSelections()) {
        if (selection.containsPosition(e.target.position)) {
          hasSelectionAtPosition = true;
          break;
        }
      }
      if (!hasSelectionAtPosition) {
        this.c.setPosition(e.target.position);
      }
    }
    let anchor = null;
    if (e.target.type !== 1) {
      anchor = e.event;
    }
    this.showContextMenu(anchor);
  }
  showContextMenu(anchor) {
    if (!this.c.getOption(
      24
      /* EditorOption.contextmenu */
    )) {
      return;
    }
    if (!this.c.hasModel()) {
      return;
    }
    const menuActions = this.m(this.c.getModel(), this.c.contextMenuId);
    if (menuActions.length > 0) {
      this.n(menuActions, anchor);
    }
  }
  m(model, menuId) {
    const result = [];
    const groups = this.i.getMenuActions(menuId, this.g, { arg: model.uri });
    for (const group2 of groups) {
      const [, actions] = group2;
      let addedItems = 0;
      for (const action of actions) {
        if (action instanceof $eJ) {
          const subActions = this.m(model, action.item.submenu);
          if (subActions.length > 0) {
            result.push(new $Xm(action.id, action.label, subActions));
            addedItems++;
          }
        } else {
          result.push(action);
          addedItems++;
        }
      }
      if (addedItems) {
        result.push(new $Wm());
      }
    }
    if (result.length) {
      result.pop();
    }
    return result;
  }
  n(actions, event = null) {
    if (!this.c.hasModel()) {
      return;
    }
    const oldHoverSetting = this.c.getOption(
      62
      /* EditorOption.hover */
    );
    this.c.updateOptions({
      hover: {
        enabled: false
      }
    });
    let anchor = event;
    if (!anchor) {
      this.c.revealPosition(
        this.c.getPosition(),
        1
        /* ScrollType.Immediate */
      );
      this.c.render();
      const cursorCoords = this.c.getScrolledVisiblePosition(this.c.getPosition());
      const editorCoords = $vj(this.c.getDomNode());
      const posx = editorCoords.left + cursorCoords.left;
      const posy = editorCoords.top + cursorCoords.top + cursorCoords.height;
      anchor = { x: posx, y: posy };
    }
    const useShadowDOM = this.c.getOption(
      132
      /* EditorOption.useShadowDOM */
    ) && !$u;
    this.b++;
    this.d.showContextMenu({
      domForShadowRoot: useShadowDOM ? this.c.getOverflowWidgetsDomNode() ?? this.c.getDomNode() : void 0,
      getAnchor: () => anchor,
      getActions: () => actions,
      getActionViewItem: (action) => {
        const keybinding = this.p(action);
        if (keybinding) {
          return new $U1(action, action, { label: true, keybinding: keybinding.getLabel(), isMenu: true });
        }
        const customActionViewItem = action;
        if (typeof customActionViewItem.getActionViewItem === "function") {
          return customActionViewItem.getActionViewItem();
        }
        return new $U1(action, action, { icon: true, label: true, isMenu: true });
      },
      getKeyBinding: (action) => {
        return this.p(action);
      },
      onHide: (wasCancelled) => {
        this.b--;
        this.c.updateOptions({
          hover: oldHoverSetting
        });
      }
    });
  }
  o(anchor) {
    if (!this.c.hasModel()) {
      return;
    }
    if ($hl(this.k.getWorkspace())) {
      return;
    }
    const minimapOptions = this.c.getOption(
      74
      /* EditorOption.minimap */
    );
    let lastId = 0;
    const createAction = (opts) => {
      return {
        id: `menu-action-${++lastId}`,
        label: opts.label,
        tooltip: "",
        class: void 0,
        enabled: typeof opts.enabled === "undefined" ? true : opts.enabled,
        checked: opts.checked,
        run: opts.run
      };
    };
    const createSubmenuAction = (label3, actions2) => {
      return new $Xm(`menu-action-${++lastId}`, label3, actions2, void 0);
    };
    const createEnumAction = (label3, enabled, configName, configuredValue, options3) => {
      if (!enabled) {
        return createAction({ label: label3, enabled, run: () => {
        } });
      }
      const createRunner = (value) => {
        return () => {
          this.j.updateValue(configName, value);
        };
      };
      const actions2 = [];
      for (const option of options3) {
        actions2.push(createAction({
          label: option.label,
          checked: configuredValue === option.value,
          run: createRunner(option.value)
        }));
      }
      return createSubmenuAction(label3, actions2);
    };
    const actions = [];
    actions.push(createAction({
      label: localize(976, null),
      checked: minimapOptions.enabled,
      run: () => {
        this.j.updateValue(`editor.minimap.enabled`, !minimapOptions.enabled);
      }
    }));
    actions.push(new $Wm());
    actions.push(createAction({
      label: localize(977, null),
      enabled: minimapOptions.enabled,
      checked: minimapOptions.renderCharacters,
      run: () => {
        this.j.updateValue(`editor.minimap.renderCharacters`, !minimapOptions.renderCharacters);
      }
    }));
    actions.push(createEnumAction(localize(978, null), minimapOptions.enabled, "editor.minimap.size", minimapOptions.size, [{
      label: localize(979, null),
      value: "proportional"
    }, {
      label: localize(980, null),
      value: "fill"
    }, {
      label: localize(981, null),
      value: "fit"
    }]));
    actions.push(createEnumAction(localize(982, null), minimapOptions.enabled, "editor.minimap.showSlider", minimapOptions.showSlider, [{
      label: localize(983, null),
      value: "mouseover"
    }, {
      label: localize(984, null),
      value: "always"
    }]));
    const useShadowDOM = this.c.getOption(
      132
      /* EditorOption.useShadowDOM */
    ) && !$u;
    this.b++;
    this.d.showContextMenu({
      domForShadowRoot: useShadowDOM ? this.c.getDomNode() : void 0,
      getAnchor: () => anchor,
      getActions: () => actions,
      onHide: (wasCancelled) => {
        this.b--;
        this.c.focus();
      }
    });
  }
  p(action) {
    return this.h.lookupKeybinding(action.id);
  }
  dispose() {
    if (this.b > 0) {
      this.f.hideContextView();
    }
    this.a.dispose();
  }
};
$Mfb = $Mfb_1 = __decorate([
  __param(1, $50),
  __param(2, $40),
  __param(3, $on),
  __param(4, $Ty),
  __param(5, $cJ),
  __param(6, $kl),
  __param(7, $Zk)
], $Mfb);
var ShowContextMenu = class extends $Z5 {
  constructor() {
    super({
      id: "editor.action.showContextMenu",
      label: localize2(985, "Show Editor Context Menu"),
      precondition: void 0,
      kbOpts: {
        kbExpr: EditorContextKeys.textInputFocus,
        primary: 1024 | 68,
        weight: 100
        /* KeybindingWeight.EditorContrib */
      }
    });
  }
  run(accessor, editor) {
    $Mfb.get(editor)?.showContextMenu();
  }
};
$85(
  $Mfb.ID,
  $Mfb,
  2
  /* EditorContributionInstantiation.BeforeFirstInteraction */
);
$55(ShowContextMenu);

// out-build/vs/editor/contrib/cursorUndo/browser/cursorUndo.js
var CursorState = class {
  constructor(selections) {
    this.selections = selections;
  }
  equals(other) {
    const thisLen = this.selections.length;
    const otherLen = other.selections.length;
    if (thisLen !== otherLen) {
      return false;
    }
    for (let i2 = 0; i2 < thisLen; i2++) {
      if (!this.selections[i2].equalsSelection(other.selections[i2])) {
        return false;
      }
    }
    return true;
  }
};
var StackElement = class {
  constructor(cursorState, scrollTop, scrollLeft) {
    this.cursorState = cursorState;
    this.scrollTop = scrollTop;
    this.scrollLeft = scrollLeft;
  }
};
var $Nfb = class _$Nfb extends $3c {
  static {
    this.ID = "editor.contrib.cursorUndoRedoController";
  }
  static get(editor) {
    return editor.getContribution(_$Nfb.ID);
  }
  constructor(editor) {
    super();
    this.a = editor;
    this.b = false;
    this.c = [];
    this.f = [];
    this.B(editor.onDidChangeModel((e) => {
      this.c = [];
      this.f = [];
    }));
    this.B(editor.onDidChangeModelContent((e) => {
      this.c = [];
      this.f = [];
    }));
    this.B(editor.onDidChangeCursorSelection((e) => {
      if (this.b) {
        return;
      }
      if (!e.oldSelections) {
        return;
      }
      if (e.oldModelVersionId !== e.modelVersionId) {
        return;
      }
      const prevState = new CursorState(e.oldSelections);
      const isEqualToLastUndoStack = this.c.length > 0 && this.c[this.c.length - 1].cursorState.equals(prevState);
      if (!isEqualToLastUndoStack) {
        this.c.push(new StackElement(prevState, editor.getScrollTop(), editor.getScrollLeft()));
        this.f = [];
        if (this.c.length > 50) {
          this.c.shift();
        }
      }
    }));
  }
  cursorUndo() {
    if (!this.a.hasModel() || this.c.length === 0) {
      return;
    }
    this.f.push(new StackElement(new CursorState(this.a.getSelections()), this.a.getScrollTop(), this.a.getScrollLeft()));
    this.g(this.c.pop());
  }
  cursorRedo() {
    if (!this.a.hasModel() || this.f.length === 0) {
      return;
    }
    this.c.push(new StackElement(new CursorState(this.a.getSelections()), this.a.getScrollTop(), this.a.getScrollLeft()));
    this.g(this.f.pop());
  }
  g(stackElement) {
    this.b = true;
    this.a.setSelections(stackElement.cursorState.selections);
    this.a.setScrollPosition({
      scrollTop: stackElement.scrollTop,
      scrollLeft: stackElement.scrollLeft
    });
    this.b = false;
  }
};
var $Ofb = class extends $Z5 {
  constructor() {
    super({
      id: "cursorUndo",
      label: localize2(986, "Cursor Undo"),
      precondition: void 0,
      kbOpts: {
        kbExpr: EditorContextKeys.textInputFocus,
        primary: 2048 | 51,
        weight: 100
        /* KeybindingWeight.EditorContrib */
      }
    });
  }
  run(accessor, editor, args2) {
    $Nfb.get(editor)?.cursorUndo();
  }
};
var $Pfb = class extends $Z5 {
  constructor() {
    super({
      id: "cursorRedo",
      label: localize2(987, "Cursor Redo"),
      precondition: void 0
    });
  }
  run(accessor, editor, args2) {
    $Nfb.get(editor)?.cursorRedo();
  }
};
$85(
  $Nfb.ID,
  $Nfb,
  0
  /* EditorContributionInstantiation.Eager */
);
$55($Ofb);
$55($Pfb);

// out-build/vs/editor/contrib/dnd/browser/dragAndDropCommand.js
var $Qfb = class {
  constructor(selection, targetPosition, copy) {
    this.a = selection;
    this.b = targetPosition;
    this.d = copy;
    this.c = null;
  }
  getEditOperations(model, builder) {
    const text2 = model.getValueInRange(this.a);
    if (!this.d) {
      builder.addEditOperation(this.a, null);
    }
    builder.addEditOperation(new $9C(this.b.lineNumber, this.b.column, this.b.lineNumber, this.b.column), text2);
    if (this.a.containsPosition(this.b) && !(this.d && (this.a.getEndPosition().equals(this.b) || this.a.getStartPosition().equals(this.b)))) {
      this.c = this.a;
      return;
    }
    if (this.d) {
      this.c = new $_D(this.b.lineNumber, this.b.column, this.a.endLineNumber - this.a.startLineNumber + this.b.lineNumber, this.a.startLineNumber === this.a.endLineNumber ? this.b.column + this.a.endColumn - this.a.startColumn : this.a.endColumn);
      return;
    }
    if (this.b.lineNumber > this.a.endLineNumber) {
      this.c = new $_D(this.b.lineNumber - this.a.endLineNumber + this.a.startLineNumber, this.b.column, this.b.lineNumber, this.a.startLineNumber === this.a.endLineNumber ? this.b.column + this.a.endColumn - this.a.startColumn : this.a.endColumn);
      return;
    }
    if (this.b.lineNumber < this.a.endLineNumber) {
      this.c = new $_D(this.b.lineNumber, this.b.column, this.b.lineNumber + this.a.endLineNumber - this.a.startLineNumber, this.a.startLineNumber === this.a.endLineNumber ? this.b.column + this.a.endColumn - this.a.startColumn : this.a.endColumn);
      return;
    }
    if (this.a.endColumn <= this.b.column) {
      this.c = new $_D(this.b.lineNumber - this.a.endLineNumber + this.a.startLineNumber, this.a.startLineNumber === this.a.endLineNumber ? this.b.column - this.a.endColumn + this.a.startColumn : this.b.column - this.a.endColumn + this.a.startColumn, this.b.lineNumber, this.a.startLineNumber === this.a.endLineNumber ? this.b.column : this.a.endColumn);
    } else {
      this.c = new $_D(this.b.lineNumber - this.a.endLineNumber + this.a.startLineNumber, this.b.column, this.b.lineNumber, this.b.column + this.a.endColumn - this.a.startColumn);
    }
  }
  computeCursorState(model, helper) {
    return this.c;
  }
};

// out-build/vs/editor/contrib/dnd/browser/dnd.js
function hasTriggerModifier(e) {
  if ($m) {
    return e.altKey;
  } else {
    return e.ctrlKey;
  }
}
var $Rfb = class _$Rfb extends $3c {
  static {
    this.ID = "editor.contrib.dragAndDrop";
  }
  static {
    this.TRIGGER_KEY_VALUE = $m ? 6 : 5;
  }
  static get(editor) {
    return editor.getContribution(_$Rfb.ID);
  }
  constructor(editor) {
    super();
    this.a = editor;
    this.c = this.a.createDecorationsCollection();
    this.B(this.a.onMouseDown((e) => this.n(e)));
    this.B(this.a.onMouseUp((e) => this.r(e)));
    this.B(this.a.onMouseDrag((e) => this.s(e)));
    this.B(this.a.onMouseDrop((e) => this.u(e)));
    this.B(this.a.onMouseDropCanceled(() => this.t()));
    this.B(this.a.onKeyDown((e) => this.j(e)));
    this.B(this.a.onKeyUp((e) => this.m(e)));
    this.B(this.a.onDidBlurEditorWidget(() => this.h()));
    this.B(this.a.onDidBlurEditorText(() => this.h()));
    this.f = false;
    this.g = false;
    this.b = null;
  }
  h() {
    this.y();
    this.b = null;
    this.f = false;
    this.g = false;
  }
  j(e) {
    if (!this.a.getOption(
      35
      /* EditorOption.dragAndDrop */
    ) || this.a.getOption(
      22
      /* EditorOption.columnSelection */
    )) {
      return;
    }
    if (hasTriggerModifier(e)) {
      this.g = true;
    }
    if (this.f && hasTriggerModifier(e)) {
      this.a.updateOptions({
        mouseStyle: "copy"
      });
    }
  }
  m(e) {
    if (!this.a.getOption(
      35
      /* EditorOption.dragAndDrop */
    ) || this.a.getOption(
      22
      /* EditorOption.columnSelection */
    )) {
      return;
    }
    if (hasTriggerModifier(e)) {
      this.g = false;
    }
    if (this.f && e.keyCode === _$Rfb.TRIGGER_KEY_VALUE) {
      this.a.updateOptions({
        mouseStyle: "default"
      });
    }
  }
  n(mouseEvent) {
    this.f = true;
  }
  r(mouseEvent) {
    this.f = false;
    this.a.updateOptions({
      mouseStyle: "text"
    });
  }
  s(mouseEvent) {
    const target = mouseEvent.target;
    if (this.b === null) {
      const selections = this.a.getSelections() || [];
      const possibleSelections = selections.filter((selection) => target.position && selection.containsPosition(target.position));
      if (possibleSelections.length === 1) {
        this.b = possibleSelections[0];
      } else {
        return;
      }
    }
    if (hasTriggerModifier(mouseEvent.event)) {
      this.a.updateOptions({
        mouseStyle: "copy"
      });
    } else {
      this.a.updateOptions({
        mouseStyle: "default"
      });
    }
    if (target.position) {
      if (this.b.containsPosition(target.position)) {
        this.y();
      } else {
        this.showAt(target.position);
      }
    }
  }
  t() {
    this.a.updateOptions({
      mouseStyle: "text"
    });
    this.y();
    this.b = null;
    this.f = false;
  }
  u(mouseEvent) {
    if (mouseEvent.target && (this.z(mouseEvent.target) || this.C(mouseEvent.target)) && mouseEvent.target.position) {
      const newCursorPosition = new $8C(mouseEvent.target.position.lineNumber, mouseEvent.target.position.column);
      if (this.b === null) {
        let newSelections = null;
        if (mouseEvent.event.shiftKey) {
          const primarySelection = this.a.getSelection();
          if (primarySelection) {
            const { selectionStartLineNumber, selectionStartColumn } = primarySelection;
            newSelections = [new $_D(selectionStartLineNumber, selectionStartColumn, newCursorPosition.lineNumber, newCursorPosition.column)];
          }
        } else {
          newSelections = (this.a.getSelections() || []).map((selection) => {
            if (selection.containsPosition(newCursorPosition)) {
              return new $_D(newCursorPosition.lineNumber, newCursorPosition.column, newCursorPosition.lineNumber, newCursorPosition.column);
            } else {
              return selection;
            }
          });
        }
        this.a.setSelections(
          newSelections || [],
          "mouse",
          3
          /* CursorChangeReason.Explicit */
        );
      } else if (!this.b.containsPosition(newCursorPosition) || (hasTriggerModifier(mouseEvent.event) || this.g) && (this.b.getEndPosition().equals(newCursorPosition) || this.b.getStartPosition().equals(newCursorPosition))) {
        this.a.pushUndoStop();
        this.a.executeCommand(_$Rfb.ID, new $Qfb(this.b, newCursorPosition, hasTriggerModifier(mouseEvent.event) || this.g));
        this.a.pushUndoStop();
      }
    }
    this.a.updateOptions({
      mouseStyle: "text"
    });
    this.y();
    this.b = null;
    this.f = false;
  }
  static {
    this.w = $WI.register({
      description: "dnd-target",
      className: "dnd-target"
    });
  }
  showAt(position) {
    this.c.set([{
      range: new $9C(position.lineNumber, position.column, position.lineNumber, position.column),
      options: _$Rfb.w
    }]);
    this.a.revealPosition(
      position,
      1
      /* ScrollType.Immediate */
    );
  }
  y() {
    this.c.clear();
  }
  z(target) {
    return target.type === 6 || target.type === 7;
  }
  C(target) {
    return target.type === 2 || target.type === 3 || target.type === 4;
  }
  dispose() {
    this.y();
    this.b = null;
    this.f = false;
    this.g = false;
    super.dispose();
  }
};
$85(
  $Rfb.ID,
  $Rfb,
  2
  /* EditorContributionInstantiation.BeforeFirstInteraction */
);

// out-build/vs/editor/contrib/dropOrPasteInto/browser/copyPasteContribution.js
var $Y_ = "editor.action.pasteAs";
$85(
  $iab.ID,
  $iab,
  0
  /* EditorContributionInstantiation.Eager */
);
$T_($X_);
$45(new class extends $Y5 {
  constructor() {
    super({
      id: $fab,
      precondition: $hab,
      kbOpts: {
        weight: 100,
        primary: 2048 | 89
      }
    });
  }
  runEditorCommand(_accessor, editor) {
    return $iab.get(editor)?.changePasteType();
  }
}());
$45(new class extends $Y5 {
  constructor() {
    super({
      id: "editor.hidePasteWidget",
      precondition: $hab,
      kbOpts: {
        weight: 100,
        primary: 9
      }
    });
  }
  runEditorCommand(_accessor, editor) {
    $iab.get(editor)?.clearWidgets();
  }
}());
$55(class PasteAsAction extends $Z5 {
  static {
    this.d = {
      oneOf: [
        {
          type: "object",
          required: ["kind"],
          properties: {
            kind: {
              type: "string",
              description: localize(988, null)
            }
          }
        },
        {
          type: "object",
          required: ["preferences"],
          properties: {
            preferences: {
              type: "array",
              description: localize(989, null),
              items: { type: "string" }
            }
          }
        }
      ]
    };
  }
  constructor() {
    super({
      id: $Y_,
      label: localize2(990, "Paste As..."),
      precondition: EditorContextKeys.writable,
      metadata: {
        description: "Paste as",
        args: [{
          name: "args",
          schema: PasteAsAction.d
        }]
      }
    });
  }
  run(_accessor, editor, args2) {
    let preference;
    if (args2) {
      if ("kind" in args2) {
        preference = { only: new $oE(args2.kind) };
      } else if ("preferences" in args2) {
        preference = { preferences: args2.preferences.map((kind) => new $oE(kind)) };
      }
    }
    return $iab.get(editor)?.pasteAs(preference);
  }
});
$55(class extends $Z5 {
  constructor() {
    super({
      id: "editor.action.pasteAsText",
      label: localize2(991, "Paste as Text"),
      precondition: EditorContextKeys.writable
    });
  }
  run(_accessor, editor) {
    return $iab.get(editor)?.pasteAs({ providerId: $V_.id });
  }
});

// out-build/vs/editor/common/services/treeViewsDnd.js
var $Sfb = class {
  constructor() {
    this.a = /* @__PURE__ */ new Map();
  }
  removeDragOperationTransfer(uuid) {
    if (uuid && this.a.has(uuid)) {
      const operation = this.a.get(uuid);
      this.a.delete(uuid);
      return operation;
    }
    return void 0;
  }
  addDragOperationTransfer(uuid, transferPromise) {
    this.a.set(uuid, transferPromise);
  }
};
var $Tfb = class {
  constructor(identifier2) {
    this.identifier = identifier2;
  }
};

// out-build/vs/editor/common/services/treeViewsDndService.js
var $Ufb = $Qk("treeViewsDndService");
$SC(
  $Ufb,
  $Sfb,
  1
  /* InstantiationType.Delayed */
);

// out-build/vs/editor/contrib/dropOrPasteInto/browser/dropIntoEditorController.js
var $Yfb_1;
var $Vfb = "editor.dropIntoEditor.preferences";
var $Wfb = "editor.changeDropType";
var $Xfb = new $nn("dropWidgetVisible", false, localize(1009, null));
var $Yfb = class $Yfb2 extends $3c {
  static {
    $Yfb_1 = this;
  }
  static {
    this.ID = "editor.contrib.dropIntoEditorController";
  }
  static get(editor) {
    return editor.getContribution($Yfb_1.ID);
  }
  static setConfigureDefaultAction(action) {
    this.a = action;
  }
  constructor(editor, instantiationService, h3, j, m) {
    super();
    this.h = h3;
    this.j = j;
    this.m = m;
    this.g = $B_.getInstance();
    this.c = this.B(instantiationService.createInstance($P_, "dropIntoEditor", editor));
    this.f = this.B(instantiationService.createInstance($eab, "dropIntoEditor", editor, $Xfb, { id: $Wfb, label: localize(1010, null) }, () => $Yfb_1.a ? [$Yfb_1.a] : []));
    this.B(editor.onDropIntoEditor((e) => this.n(editor, e.position, e.event)));
  }
  clearWidgets() {
    this.f.clear();
  }
  changeDropType() {
    this.f.tryShowSelector();
  }
  async n(editor, position, dragEvent) {
    if (!dragEvent.dataTransfer || !editor.hasModel()) {
      return;
    }
    $Yfb_1.b?.cancel();
    editor.focus();
    editor.setPosition(position);
    const p = $Hh(async (token) => {
      const disposables = new $2c();
      const tokenSource = disposables.add(new $N_(editor, 1, void 0, token));
      try {
        const ourDataTransfer = await this.t(dragEvent);
        if (ourDataTransfer.size === 0 || tokenSource.token.isCancellationRequested) {
          return;
        }
        const model = editor.getModel();
        if (!model) {
          return;
        }
        const providers2 = this.j.documentDropEditProvider.ordered(model).filter((provider) => {
          if (!provider.dropMimeTypes) {
            return true;
          }
          return provider.dropMimeTypes.some((mime) => ourDataTransfer.matches(mime));
        });
        const editSession = disposables.add(await this.r(providers2, model, position, ourDataTransfer, tokenSource.token));
        if (tokenSource.token.isCancellationRequested) {
          return;
        }
        if (editSession.edits.length) {
          const activeEditIndex = this.s(model, editSession.edits);
          const canShowWidget = editor.getOption(
            36
            /* EditorOption.dropIntoEditor */
          ).showDropSelector === "afterDrop";
          await this.f.applyEditAndShowIfNeeded([$9C.fromPositions(position)], { activeEditIndex, allEdits: editSession.edits }, canShowWidget, async (edit3) => edit3, token);
        }
      } finally {
        disposables.dispose();
        if ($Yfb_1.b === p) {
          $Yfb_1.b = void 0;
        }
      }
    });
    this.c.showWhile(position, localize(1011, null), p, { cancel: () => p.cancel() });
    $Yfb_1.b = p;
  }
  async r(providers2, model, position, dataTransfer, token) {
    const disposables = new $2c();
    const results = await $Ih(Promise.all(providers2.map(async (provider) => {
      try {
        const edits2 = await provider.provideDocumentDropEdits(model, position, dataTransfer, token);
        if (edits2) {
          disposables.add(edits2);
        }
        return edits2?.edits.map((edit3) => ({ ...edit3, providerId: provider.id }));
      } catch (err) {
        if (!$kb(err)) {
          console.error(err);
        }
        console.error(err);
      }
      return void 0;
    })), token);
    const edits = $Mb(results ?? []).flat();
    return {
      edits: $__(edits),
      dispose: () => disposables.dispose()
    };
  }
  s(model, edits) {
    const preferredProviders = this.h.getValue($Vfb, { resource: model.uri });
    for (const config of Array.isArray(preferredProviders) ? preferredProviders : []) {
      const desiredKind = new $oE(config);
      const editIndex = edits.findIndex((edit3) => edit3.kind && desiredKind.contains(edit3.kind));
      if (editIndex >= 0) {
        return editIndex;
      }
    }
    return 0;
  }
  async t(dragEvent) {
    if (!dragEvent.dataTransfer) {
      return new $lE();
    }
    const dataTransfer = $G_(dragEvent.dataTransfer);
    if (this.g.hasData($Tfb.prototype)) {
      const data = this.g.getData($Tfb.prototype);
      if (Array.isArray(data)) {
        for (const id2 of data) {
          const treeDataTransfer = await this.m.removeDragOperationTransfer(id2.identifier);
          if (treeDataTransfer) {
            for (const [type, value] of treeDataTransfer) {
              dataTransfer.replace(type, value);
            }
          }
        }
      }
    }
    return dataTransfer;
  }
};
$Yfb = $Yfb_1 = __decorate([
  __param(1, $Pk),
  __param(2, $kl),
  __param(3, $mP),
  __param(4, $Ufb)
], $Yfb);

// out-build/vs/editor/contrib/dropOrPasteInto/browser/dropIntoEditorContribution.js
$85(
  $Yfb.ID,
  $Yfb,
  2
  /* EditorContributionInstantiation.BeforeFirstInteraction */
);
$T_($W_);
$45(new class extends $Y5 {
  constructor() {
    super({
      id: $Wfb,
      precondition: $Xfb,
      kbOpts: {
        weight: 100,
        primary: 2048 | 89
      }
    });
  }
  runEditorCommand(_accessor, editor, _args) {
    $Yfb.get(editor)?.changeDropType();
  }
}());
$45(new class extends $Y5 {
  constructor() {
    super({
      id: "editor.hideDropWidget",
      precondition: $Xfb,
      kbOpts: {
        weight: 100,
        primary: 9
      }
    });
  }
  runEditorCommand(_accessor, editor, _args) {
    $Yfb.get(editor)?.clearWidgets();
  }
}());

// out-build/vs/editor/contrib/find/browser/findDecorations.js
var $Zfb = class _$Zfb {
  constructor(editor) {
    this.a = editor;
    this.b = [];
    this.c = [];
    this.d = [];
    this.e = null;
    this.f = null;
    this.g = this.a.getPosition();
  }
  dispose() {
    this.a.removeDecorations(this.j());
    this.b = [];
    this.c = [];
    this.d = [];
    this.e = null;
    this.f = null;
  }
  reset() {
    this.b = [];
    this.c = [];
    this.d = [];
    this.e = null;
    this.f = null;
  }
  getCount() {
    return this.b.length;
  }
  /** @deprecated use getFindScopes to support multiple selections */
  getFindScope() {
    if (this.d[0]) {
      return this.a.getModel().getDecorationRange(this.d[0]);
    }
    return null;
  }
  getFindScopes() {
    if (this.d.length) {
      const scopes = this.d.map((findScopeDecorationId) => this.a.getModel().getDecorationRange(findScopeDecorationId)).filter((element) => !!element);
      if (scopes.length) {
        return scopes;
      }
    }
    return null;
  }
  getStartPosition() {
    return this.g;
  }
  setStartPosition(newStartPosition) {
    this.g = newStartPosition;
    this.setCurrentFindMatch(null);
  }
  h(decorationId) {
    const index = this.b.indexOf(decorationId);
    if (index >= 0) {
      return index + 1;
    }
    return 1;
  }
  getDecorationRangeAt(index) {
    const decorationId = index < this.b.length ? this.b[index] : null;
    if (decorationId) {
      return this.a.getModel().getDecorationRange(decorationId);
    }
    return null;
  }
  getCurrentMatchesPosition(desiredRange) {
    const candidates = this.a.getModel().getDecorationsInRange(desiredRange);
    for (const candidate of candidates) {
      const candidateOpts = candidate.options;
      if (candidateOpts === _$Zfb._FIND_MATCH_DECORATION || candidateOpts === _$Zfb._CURRENT_FIND_MATCH_DECORATION) {
        return this.h(candidate.id);
      }
    }
    return 0;
  }
  setCurrentFindMatch(nextMatch) {
    let newCurrentDecorationId = null;
    let matchPosition = 0;
    if (nextMatch) {
      for (let i2 = 0, len = this.b.length; i2 < len; i2++) {
        const range = this.a.getModel().getDecorationRange(this.b[i2]);
        if (nextMatch.equalsRange(range)) {
          newCurrentDecorationId = this.b[i2];
          matchPosition = i2 + 1;
          break;
        }
      }
    }
    if (this.f !== null || newCurrentDecorationId !== null) {
      this.a.changeDecorations((changeAccessor) => {
        if (this.f !== null) {
          changeAccessor.changeDecorationOptions(this.f, _$Zfb._FIND_MATCH_DECORATION);
          this.f = null;
        }
        if (newCurrentDecorationId !== null) {
          this.f = newCurrentDecorationId;
          changeAccessor.changeDecorationOptions(this.f, _$Zfb._CURRENT_FIND_MATCH_DECORATION);
        }
        if (this.e !== null) {
          changeAccessor.removeDecoration(this.e);
          this.e = null;
        }
        if (newCurrentDecorationId !== null) {
          let rng = this.a.getModel().getDecorationRange(newCurrentDecorationId);
          if (rng.startLineNumber !== rng.endLineNumber && rng.endColumn === 1) {
            const lineBeforeEnd = rng.endLineNumber - 1;
            const lineBeforeEndMaxColumn = this.a.getModel().getLineMaxColumn(lineBeforeEnd);
            rng = new $9C(rng.startLineNumber, rng.startColumn, lineBeforeEnd, lineBeforeEndMaxColumn);
          }
          this.e = changeAccessor.addDecoration(rng, _$Zfb.l);
        }
      });
    }
    return matchPosition;
  }
  set(findMatches, findScopes) {
    this.a.changeDecorations((accessor) => {
      let findMatchesOptions = _$Zfb._FIND_MATCH_DECORATION;
      const newOverviewRulerApproximateDecorations = [];
      if (findMatches.length > 1e3) {
        findMatchesOptions = _$Zfb._FIND_MATCH_NO_OVERVIEW_DECORATION;
        const lineCount = this.a.getModel().getLineCount();
        const height = this.a.getLayoutInfo().height;
        const approxPixelsPerLine = height / lineCount;
        const mergeLinesDelta = Math.max(2, Math.ceil(3 / approxPixelsPerLine));
        let prevStartLineNumber = findMatches[0].range.startLineNumber;
        let prevEndLineNumber = findMatches[0].range.endLineNumber;
        for (let i2 = 1, len = findMatches.length; i2 < len; i2++) {
          const range = findMatches[i2].range;
          if (prevEndLineNumber + mergeLinesDelta >= range.startLineNumber) {
            if (range.endLineNumber > prevEndLineNumber) {
              prevEndLineNumber = range.endLineNumber;
            }
          } else {
            newOverviewRulerApproximateDecorations.push({
              range: new $9C(prevStartLineNumber, 1, prevEndLineNumber, 1),
              options: _$Zfb.k
            });
            prevStartLineNumber = range.startLineNumber;
            prevEndLineNumber = range.endLineNumber;
          }
        }
        newOverviewRulerApproximateDecorations.push({
          range: new $9C(prevStartLineNumber, 1, prevEndLineNumber, 1),
          options: _$Zfb.k
        });
      }
      const newFindMatchesDecorations = new Array(findMatches.length);
      for (let i2 = 0, len = findMatches.length; i2 < len; i2++) {
        newFindMatchesDecorations[i2] = {
          range: findMatches[i2].range,
          options: findMatchesOptions
        };
      }
      this.b = accessor.deltaDecorations(this.b, newFindMatchesDecorations);
      this.c = accessor.deltaDecorations(this.c, newOverviewRulerApproximateDecorations);
      if (this.e) {
        accessor.removeDecoration(this.e);
        this.e = null;
      }
      if (this.d.length) {
        this.d.forEach((findScopeDecorationId) => accessor.removeDecoration(findScopeDecorationId));
        this.d = [];
      }
      if (findScopes?.length) {
        this.d = findScopes.map((findScope) => accessor.addDecoration(findScope, _$Zfb.m));
      }
    });
  }
  matchBeforePosition(position) {
    if (this.b.length === 0) {
      return null;
    }
    for (let i2 = this.b.length - 1; i2 >= 0; i2--) {
      const decorationId = this.b[i2];
      const r2 = this.a.getModel().getDecorationRange(decorationId);
      if (!r2 || r2.endLineNumber > position.lineNumber) {
        continue;
      }
      if (r2.endLineNumber < position.lineNumber) {
        return r2;
      }
      if (r2.endColumn > position.column) {
        continue;
      }
      return r2;
    }
    return this.a.getModel().getDecorationRange(this.b[this.b.length - 1]);
  }
  matchAfterPosition(position) {
    if (this.b.length === 0) {
      return null;
    }
    for (let i2 = 0, len = this.b.length; i2 < len; i2++) {
      const decorationId = this.b[i2];
      const r2 = this.a.getModel().getDecorationRange(decorationId);
      if (!r2 || r2.startLineNumber < position.lineNumber) {
        continue;
      }
      if (r2.startLineNumber > position.lineNumber) {
        return r2;
      }
      if (r2.startColumn < position.column) {
        continue;
      }
      return r2;
    }
    return this.a.getModel().getDecorationRange(this.b[0]);
  }
  j() {
    let result = [];
    result = result.concat(this.b);
    result = result.concat(this.c);
    if (this.d.length) {
      result.push(...this.d);
    }
    if (this.e) {
      result.push(this.e);
    }
    return result;
  }
  static {
    this._CURRENT_FIND_MATCH_DECORATION = $WI.register({
      description: "current-find-match",
      stickiness: 1,
      zIndex: 13,
      className: "currentFindMatch",
      inlineClassName: "currentFindMatchInline",
      showIfCollapsed: true,
      overviewRuler: {
        color: $hs($_p),
        position: OverviewRulerLane.Center
      },
      minimap: {
        color: $hs($eq),
        position: 1
        /* MinimapPosition.Inline */
      }
    });
  }
  static {
    this._FIND_MATCH_DECORATION = $WI.register({
      description: "find-match",
      stickiness: 1,
      zIndex: 10,
      className: "findMatch",
      inlineClassName: "findMatchInline",
      showIfCollapsed: true,
      overviewRuler: {
        color: $hs($_p),
        position: OverviewRulerLane.Center
      },
      minimap: {
        color: $hs($eq),
        position: 1
        /* MinimapPosition.Inline */
      }
    });
  }
  static {
    this._FIND_MATCH_NO_OVERVIEW_DECORATION = $WI.register({
      description: "find-match-no-overview",
      stickiness: 1,
      className: "findMatch",
      showIfCollapsed: true
    });
  }
  static {
    this.k = $WI.register({
      description: "find-match-only-overview",
      stickiness: 1,
      overviewRuler: {
        color: $hs($_p),
        position: OverviewRulerLane.Center
      }
    });
  }
  static {
    this.l = $WI.register({
      description: "find-range-highlight",
      stickiness: 1,
      className: "rangeHighlight",
      isWholeLine: true
    });
  }
  static {
    this.m = $WI.register({
      description: "find-scope",
      className: "findScope",
      isWholeLine: true
    });
  }
};

// out-build/vs/editor/contrib/find/browser/replaceAllCommand.js
var $2fb = class {
  constructor(editorSelection, ranges, replaceStrings) {
    this.a = editorSelection;
    this.c = ranges;
    this.d = replaceStrings;
    this.b = null;
  }
  getEditOperations(model, builder) {
    if (this.c.length > 0) {
      const ops = [];
      for (let i2 = 0; i2 < this.c.length; i2++) {
        ops.push({
          range: this.c[i2],
          text: this.d[i2]
        });
      }
      ops.sort((o1, o2) => {
        return $9C.compareRangesUsingStarts(o1.range, o2.range);
      });
      const resultOps = [];
      let previousOp = ops[0];
      for (let i2 = 1; i2 < ops.length; i2++) {
        if (previousOp.range.endLineNumber === ops[i2].range.startLineNumber && previousOp.range.endColumn === ops[i2].range.startColumn) {
          previousOp.range = previousOp.range.plusRange(ops[i2].range);
          previousOp.text = previousOp.text + ops[i2].text;
        } else {
          resultOps.push(previousOp);
          previousOp = ops[i2];
        }
      }
      resultOps.push(previousOp);
      for (const op of resultOps) {
        builder.addEditOperation(op.range, op.text);
      }
    }
    this.b = builder.trackSelection(this.a);
  }
  computeCursorState(model, helper) {
    return helper.getTrackedSelection(this.b);
  }
};

// out-build/vs/base/common/search.js
function $V3(matches, pattern) {
  if (matches && matches[0] !== "") {
    const containsHyphens = validateSpecificSpecialCharacter(matches, pattern, "-");
    const containsUnderscores = validateSpecificSpecialCharacter(matches, pattern, "_");
    if (containsHyphens && !containsUnderscores) {
      return buildReplaceStringForSpecificSpecialCharacter(matches, pattern, "-");
    } else if (!containsHyphens && containsUnderscores) {
      return buildReplaceStringForSpecificSpecialCharacter(matches, pattern, "_");
    }
    if (matches[0].toUpperCase() === matches[0]) {
      return pattern.toUpperCase();
    } else if (matches[0].toLowerCase() === matches[0]) {
      return pattern.toLowerCase();
    } else if ($qg(matches[0][0]) && pattern.length > 0) {
      return pattern[0].toUpperCase() + pattern.substr(1);
    } else if (matches[0][0].toUpperCase() !== matches[0][0] && pattern.length > 0) {
      return pattern[0].toLowerCase() + pattern.substr(1);
    } else {
      return pattern;
    }
  } else {
    return pattern;
  }
}
function validateSpecificSpecialCharacter(matches, pattern, specialCharacter) {
  const doesContainSpecialCharacter = matches[0].indexOf(specialCharacter) !== -1 && pattern.indexOf(specialCharacter) !== -1;
  return doesContainSpecialCharacter && matches[0].split(specialCharacter).length === pattern.split(specialCharacter).length;
}
function buildReplaceStringForSpecificSpecialCharacter(matches, pattern, specialCharacter) {
  const splitPatternAtSpecialCharacter = pattern.split(specialCharacter);
  const splitMatchAtSpecialCharacter = matches[0].split(specialCharacter);
  let replaceString = "";
  splitPatternAtSpecialCharacter.forEach((splitValue, index) => {
    replaceString += $V3([splitMatchAtSpecialCharacter[index]], splitValue) + specialCharacter;
  });
  return replaceString.slice(0, -1);
}

// out-build/vs/editor/contrib/find/browser/replacePattern.js
var ReplacePatternKind;
(function(ReplacePatternKind2) {
  ReplacePatternKind2[ReplacePatternKind2["StaticValue"] = 0] = "StaticValue";
  ReplacePatternKind2[ReplacePatternKind2["DynamicPieces"] = 1] = "DynamicPieces";
})(ReplacePatternKind || (ReplacePatternKind = {}));
var StaticValueReplacePattern = class {
  constructor(staticValue) {
    this.staticValue = staticValue;
    this.kind = 0;
  }
};
var DynamicPiecesReplacePattern = class {
  constructor(pieces) {
    this.pieces = pieces;
    this.kind = 1;
  }
};
var $3fb = class _$3fb {
  static fromStaticValue(value) {
    return new _$3fb([$4fb.staticValue(value)]);
  }
  get hasReplacementPatterns() {
    return this.a.kind === 1;
  }
  constructor(pieces) {
    if (!pieces || pieces.length === 0) {
      this.a = new StaticValueReplacePattern("");
    } else if (pieces.length === 1 && pieces[0].staticValue !== null) {
      this.a = new StaticValueReplacePattern(pieces[0].staticValue);
    } else {
      this.a = new DynamicPiecesReplacePattern(pieces);
    }
  }
  buildReplaceString(matches, preserveCase) {
    if (this.a.kind === 0) {
      if (preserveCase) {
        return $V3(matches, this.a.staticValue);
      } else {
        return this.a.staticValue;
      }
    }
    let result = "";
    for (let i2 = 0, len = this.a.pieces.length; i2 < len; i2++) {
      const piece = this.a.pieces[i2];
      if (piece.staticValue !== null) {
        result += piece.staticValue;
        continue;
      }
      let match = _$3fb.b(piece.matchIndex, matches);
      if (piece.caseOps !== null && piece.caseOps.length > 0) {
        const repl = [];
        const lenOps = piece.caseOps.length;
        let opIdx = 0;
        for (let idx = 0, len2 = match.length; idx < len2; idx++) {
          if (opIdx >= lenOps) {
            repl.push(match.slice(idx));
            break;
          }
          switch (piece.caseOps[opIdx]) {
            case "U":
              repl.push(match[idx].toUpperCase());
              break;
            case "u":
              repl.push(match[idx].toUpperCase());
              opIdx++;
              break;
            case "L":
              repl.push(match[idx].toLowerCase());
              break;
            case "l":
              repl.push(match[idx].toLowerCase());
              opIdx++;
              break;
            default:
              repl.push(match[idx]);
          }
        }
        match = repl.join("");
      }
      result += match;
    }
    return result;
  }
  static b(matchIndex, matches) {
    if (matches === null) {
      return "";
    }
    if (matchIndex === 0) {
      return matches[0];
    }
    let remainder = "";
    while (matchIndex > 0) {
      if (matchIndex < matches.length) {
        const match = matches[matchIndex] || "";
        return match + remainder;
      }
      remainder = String(matchIndex % 10) + remainder;
      matchIndex = Math.floor(matchIndex / 10);
    }
    return "$" + remainder;
  }
};
var $4fb = class _$4fb {
  static staticValue(value) {
    return new _$4fb(value, -1, null);
  }
  static matchIndex(index) {
    return new _$4fb(null, index, null);
  }
  static caseOps(index, caseOps) {
    return new _$4fb(null, index, caseOps);
  }
  constructor(staticValue, matchIndex, caseOps) {
    this.staticValue = staticValue;
    this.matchIndex = matchIndex;
    if (!caseOps || caseOps.length === 0) {
      this.caseOps = null;
    } else {
      this.caseOps = caseOps.slice(0);
    }
  }
};
var ReplacePieceBuilder = class {
  constructor(source) {
    this.a = source;
    this.b = 0;
    this.c = [];
    this.d = 0;
    this.e = "";
  }
  emitUnchanged(toCharIndex) {
    this.f(this.a.substring(this.b, toCharIndex));
    this.b = toCharIndex;
  }
  emitStatic(value, toCharIndex) {
    this.f(value);
    this.b = toCharIndex;
  }
  f(value) {
    if (value.length === 0) {
      return;
    }
    this.e += value;
  }
  emitMatchIndex(index, toCharIndex, caseOps) {
    if (this.e.length !== 0) {
      this.c[this.d++] = $4fb.staticValue(this.e);
      this.e = "";
    }
    this.c[this.d++] = $4fb.caseOps(index, caseOps);
    this.b = toCharIndex;
  }
  finalize() {
    this.emitUnchanged(this.a.length);
    if (this.e.length !== 0) {
      this.c[this.d++] = $4fb.staticValue(this.e);
      this.e = "";
    }
    return new $3fb(this.c);
  }
};
function $5fb(replaceString) {
  if (!replaceString || replaceString.length === 0) {
    return new $3fb(null);
  }
  const caseOps = [];
  const result = new ReplacePieceBuilder(replaceString);
  for (let i2 = 0, len = replaceString.length; i2 < len; i2++) {
    const chCode = replaceString.charCodeAt(i2);
    if (chCode === 92) {
      i2++;
      if (i2 >= len) {
        break;
      }
      const nextChCode = replaceString.charCodeAt(i2);
      switch (nextChCode) {
        case 92:
          result.emitUnchanged(i2 - 1);
          result.emitStatic("\\", i2 + 1);
          break;
        case 110:
          result.emitUnchanged(i2 - 1);
          result.emitStatic("\n", i2 + 1);
          break;
        case 116:
          result.emitUnchanged(i2 - 1);
          result.emitStatic("	", i2 + 1);
          break;
        case 117:
        case 85:
        case 108:
        case 76:
          result.emitUnchanged(i2 - 1);
          result.emitStatic("", i2 + 1);
          caseOps.push(String.fromCharCode(nextChCode));
          break;
      }
      continue;
    }
    if (chCode === 36) {
      i2++;
      if (i2 >= len) {
        break;
      }
      const nextChCode = replaceString.charCodeAt(i2);
      if (nextChCode === 36) {
        result.emitUnchanged(i2 - 1);
        result.emitStatic("$", i2 + 1);
        continue;
      }
      if (nextChCode === 48 || nextChCode === 38) {
        result.emitUnchanged(i2 - 1);
        result.emitMatchIndex(0, i2 + 1, caseOps);
        caseOps.length = 0;
        continue;
      }
      if (49 <= nextChCode && nextChCode <= 57) {
        let matchIndex = nextChCode - 48;
        if (i2 + 1 < len) {
          const nextNextChCode = replaceString.charCodeAt(i2 + 1);
          if (48 <= nextNextChCode && nextNextChCode <= 57) {
            i2++;
            matchIndex = matchIndex * 10 + (nextNextChCode - 48);
            result.emitUnchanged(i2 - 2);
            result.emitMatchIndex(matchIndex, i2 + 1, caseOps);
            caseOps.length = 0;
            continue;
          }
        }
        result.emitUnchanged(i2 - 1);
        result.emitMatchIndex(matchIndex, i2 + 1, caseOps);
        caseOps.length = 0;
        continue;
      }
    }
  }
  return result.finalize();
}

// out-build/vs/editor/contrib/find/browser/findModel.js
var $6fb = new $nn("findWidgetVisible", false);
var $7fb = $6fb.toNegated();
var $8fb = new $nn("findInputFocussed", false);
var $9fb = new $nn("replaceInputFocussed", false);
var $0fb = {
  primary: 512 | 33,
  mac: {
    primary: 2048 | 512 | 33
    /* KeyCode.KeyC */
  }
};
var $$fb = {
  primary: 512 | 53,
  mac: {
    primary: 2048 | 512 | 53
    /* KeyCode.KeyW */
  }
};
var $_fb = {
  primary: 512 | 48,
  mac: {
    primary: 2048 | 512 | 48
    /* KeyCode.KeyR */
  }
};
var $agb = {
  primary: 512 | 42,
  mac: {
    primary: 2048 | 512 | 42
    /* KeyCode.KeyL */
  }
};
var $bgb = {
  primary: 512 | 46,
  mac: {
    primary: 2048 | 512 | 46
    /* KeyCode.KeyP */
  }
};
var $cgb = {
  StartFindAction: "actions.find",
  StartFindWithSelection: "actions.findWithSelection",
  StartFindWithArgs: "editor.actions.findWithArgs",
  NextMatchFindAction: "editor.action.nextMatchFindAction",
  PreviousMatchFindAction: "editor.action.previousMatchFindAction",
  GoToMatchFindAction: "editor.action.goToMatchFindAction",
  NextSelectionMatchFindAction: "editor.action.nextSelectionMatchFindAction",
  PreviousSelectionMatchFindAction: "editor.action.previousSelectionMatchFindAction",
  StartFindReplaceAction: "editor.action.startFindReplaceAction",
  CloseFindWidgetCommand: "closeFindWidget",
  ToggleCaseSensitiveCommand: "toggleFindCaseSensitive",
  ToggleWholeWordCommand: "toggleFindWholeWord",
  ToggleRegexCommand: "toggleFindRegex",
  ToggleSearchScopeCommand: "toggleFindInSelection",
  TogglePreserveCaseCommand: "togglePreserveCase",
  ReplaceOneAction: "editor.action.replaceOne",
  ReplaceAllAction: "editor.action.replaceAll",
  SelectAllMatchesAction: "editor.action.selectAllMatches"
};
var $dgb = 19999;
var RESEARCH_DELAY = 240;
var $egb = class _$egb {
  constructor(editor, state) {
    this.c = new $2c();
    this.a = editor;
    this.b = state;
    this.j = false;
    this.g = new $6h();
    this.d = new $Zfb(editor);
    this.c.add(this.d);
    this.h = new $8h(() => {
      if (!this.a.hasModel()) {
        return;
      }
      return this.n(false);
    }, 100);
    this.c.add(this.h);
    this.c.add(this.a.onDidChangeCursorPosition((e) => {
      if (e.reason === 3 || e.reason === 5 || e.reason === 6) {
        this.d.setStartPosition(this.a.getPosition());
      }
    }));
    this.f = false;
    this.c.add(this.a.onDidChangeModelContent((e) => {
      if (this.f) {
        return;
      }
      if (e.isFlush) {
        this.d.reset();
      }
      this.d.setStartPosition(this.a.getPosition());
      this.h.schedule();
    }));
    this.c.add(this.b.onFindReplaceStateChange((e) => this.k(e)));
    this.n(false, this.b.searchScope);
  }
  dispose() {
    this.j = true;
    $Xc(this.g);
    this.c.dispose();
  }
  k(e) {
    if (this.j) {
      return;
    }
    if (!this.a.hasModel()) {
      return;
    }
    if (e.searchString || e.isReplaceRevealed || e.isRegex || e.wholeWord || e.matchCase || e.searchScope) {
      const model = this.a.getModel();
      if (model.isTooLargeForSyncing()) {
        this.g.cancel();
        this.g.setIfNotSet(() => {
          if (e.searchScope) {
            this.n(e.moveCursor, this.b.searchScope);
          } else {
            this.n(e.moveCursor);
          }
        }, RESEARCH_DELAY);
      } else {
        if (e.searchScope) {
          this.n(e.moveCursor, this.b.searchScope);
        } else {
          this.n(e.moveCursor);
        }
      }
    }
  }
  static l(model, findScope) {
    if (findScope) {
      return findScope;
    }
    return model.getFullModelRange();
  }
  n(moveCursor, newFindScope) {
    let findScopes = null;
    if (typeof newFindScope !== "undefined") {
      if (newFindScope !== null) {
        if (!Array.isArray(newFindScope)) {
          findScopes = [newFindScope];
        } else {
          findScopes = newFindScope;
        }
      }
    } else {
      findScopes = this.d.getFindScopes();
    }
    if (findScopes !== null) {
      findScopes = findScopes.map((findScope) => {
        if (findScope.startLineNumber !== findScope.endLineNumber) {
          let endLineNumber = findScope.endLineNumber;
          if (findScope.endColumn === 1) {
            endLineNumber = endLineNumber - 1;
          }
          return new $9C(findScope.startLineNumber, 1, endLineNumber, this.a.getModel().getLineMaxColumn(endLineNumber));
        }
        return findScope;
      });
    }
    const findMatches = this.y(findScopes, false, $dgb);
    this.d.set(findMatches, findScopes);
    const editorSelection = this.a.getSelection();
    let currentMatchesPosition = this.d.getCurrentMatchesPosition(editorSelection);
    if (currentMatchesPosition === 0 && findMatches.length > 0) {
      const matchAfterSelection = $6(findMatches.map((match) => match.range), (range) => $9C.compareRangesUsingStarts(range, editorSelection) >= 0);
      currentMatchesPosition = matchAfterSelection > 0 ? matchAfterSelection - 1 + 1 : currentMatchesPosition;
    }
    this.b.changeMatchInfo(currentMatchesPosition, this.d.getCount(), void 0);
    if (moveCursor && this.a.getOption(
      43
      /* EditorOption.find */
    ).cursorMoveOnType) {
      this.u(this.d.getStartPosition());
    }
  }
  o() {
    return this.b.matchesCount > 0;
  }
  p() {
    if (!this.o()) {
      const findScope = this.d.getFindScope();
      if (findScope) {
        this.a.revealRangeInCenterIfOutsideViewport(
          findScope,
          0
          /* ScrollType.Smooth */
        );
      }
      return true;
    }
    return false;
  }
  q(match) {
    const matchesPosition = this.d.setCurrentFindMatch(match);
    this.b.changeMatchInfo(matchesPosition, this.d.getCount(), match);
    this.a.setSelection(match);
    this.a.revealRangeInCenterIfOutsideViewport(
      match,
      0
      /* ScrollType.Smooth */
    );
  }
  r(before) {
    const isUsingLineStops = this.b.isRegex && (this.b.searchString.indexOf("^") >= 0 || this.b.searchString.indexOf("$") >= 0);
    let { lineNumber, column } = before;
    const model = this.a.getModel();
    if (isUsingLineStops || column === 1) {
      if (lineNumber === 1) {
        lineNumber = model.getLineCount();
      } else {
        lineNumber--;
      }
      column = model.getLineMaxColumn(lineNumber);
    } else {
      column--;
    }
    return new $8C(lineNumber, column);
  }
  s(before, isRecursed = false) {
    if (!this.b.canNavigateBack()) {
      const nextMatchRange = this.d.matchAfterPosition(before);
      if (nextMatchRange) {
        this.q(nextMatchRange);
      }
      return;
    }
    if (this.d.getCount() < $dgb) {
      let prevMatchRange = this.d.matchBeforePosition(before);
      if (prevMatchRange && prevMatchRange.isEmpty() && prevMatchRange.getStartPosition().equals(before)) {
        before = this.r(before);
        prevMatchRange = this.d.matchBeforePosition(before);
      }
      if (prevMatchRange) {
        this.q(prevMatchRange);
      }
      return;
    }
    if (this.p()) {
      return;
    }
    const findScope = this.d.getFindScope();
    const searchRange = _$egb.l(this.a.getModel(), findScope);
    if (searchRange.getEndPosition().isBefore(before)) {
      before = searchRange.getEndPosition();
    }
    if (before.isBefore(searchRange.getStartPosition())) {
      before = searchRange.getEndPosition();
    }
    const { lineNumber, column } = before;
    const model = this.a.getModel();
    let position = new $8C(lineNumber, column);
    let prevMatch = model.findPreviousMatch(this.b.searchString, position, this.b.isRegex, this.b.matchCase, this.b.wholeWord ? this.a.getOption(
      136
      /* EditorOption.wordSeparators */
    ) : null, false);
    if (prevMatch && prevMatch.range.isEmpty() && prevMatch.range.getStartPosition().equals(position)) {
      position = this.r(position);
      prevMatch = model.findPreviousMatch(this.b.searchString, position, this.b.isRegex, this.b.matchCase, this.b.wholeWord ? this.a.getOption(
        136
        /* EditorOption.wordSeparators */
      ) : null, false);
    }
    if (!prevMatch) {
      return;
    }
    if (!isRecursed && !searchRange.containsRange(prevMatch.range)) {
      return this.s(prevMatch.range.getStartPosition(), true);
    }
    this.q(prevMatch.range);
  }
  moveToPrevMatch() {
    this.s(this.a.getSelection().getStartPosition());
  }
  t(after) {
    const isUsingLineStops = this.b.isRegex && (this.b.searchString.indexOf("^") >= 0 || this.b.searchString.indexOf("$") >= 0);
    let { lineNumber, column } = after;
    const model = this.a.getModel();
    if (isUsingLineStops || column === model.getLineMaxColumn(lineNumber)) {
      if (lineNumber === model.getLineCount()) {
        lineNumber = 1;
      } else {
        lineNumber++;
      }
      column = 1;
    } else {
      column++;
    }
    return new $8C(lineNumber, column);
  }
  u(after) {
    if (!this.b.canNavigateForward()) {
      const prevMatchRange = this.d.matchBeforePosition(after);
      if (prevMatchRange) {
        this.q(prevMatchRange);
      }
      return;
    }
    if (this.d.getCount() < $dgb) {
      let nextMatchRange = this.d.matchAfterPosition(after);
      if (nextMatchRange && nextMatchRange.isEmpty() && nextMatchRange.getStartPosition().equals(after)) {
        after = this.t(after);
        nextMatchRange = this.d.matchAfterPosition(after);
      }
      if (nextMatchRange) {
        this.q(nextMatchRange);
      }
      return;
    }
    const nextMatch = this.v(after, false, true);
    if (nextMatch) {
      this.q(nextMatch.range);
    }
  }
  v(after, captureMatches, forceMove, isRecursed = false) {
    if (this.p()) {
      return null;
    }
    const findScope = this.d.getFindScope();
    const searchRange = _$egb.l(this.a.getModel(), findScope);
    if (searchRange.getEndPosition().isBefore(after)) {
      after = searchRange.getStartPosition();
    }
    if (after.isBefore(searchRange.getStartPosition())) {
      after = searchRange.getStartPosition();
    }
    const { lineNumber, column } = after;
    const model = this.a.getModel();
    let position = new $8C(lineNumber, column);
    let nextMatch = model.findNextMatch(this.b.searchString, position, this.b.isRegex, this.b.matchCase, this.b.wholeWord ? this.a.getOption(
      136
      /* EditorOption.wordSeparators */
    ) : null, captureMatches);
    if (forceMove && nextMatch && nextMatch.range.isEmpty() && nextMatch.range.getStartPosition().equals(position)) {
      position = this.t(position);
      nextMatch = model.findNextMatch(this.b.searchString, position, this.b.isRegex, this.b.matchCase, this.b.wholeWord ? this.a.getOption(
        136
        /* EditorOption.wordSeparators */
      ) : null, captureMatches);
    }
    if (!nextMatch) {
      return null;
    }
    if (!isRecursed && !searchRange.containsRange(nextMatch.range)) {
      return this.v(nextMatch.range.getEndPosition(), captureMatches, forceMove, true);
    }
    return nextMatch;
  }
  moveToNextMatch() {
    this.u(this.a.getSelection().getEndPosition());
  }
  w(index) {
    const decorationRange = this.d.getDecorationRangeAt(index);
    if (decorationRange) {
      this.q(decorationRange);
    }
  }
  moveToMatch(index) {
    this.w(index);
  }
  x() {
    if (this.b.isRegex) {
      return $5fb(this.b.replaceString);
    }
    return $3fb.fromStaticValue(this.b.replaceString);
  }
  replace() {
    if (!this.o()) {
      return;
    }
    const replacePattern = this.x();
    const selection = this.a.getSelection();
    const nextMatch = this.v(selection.getStartPosition(), true, false);
    if (nextMatch) {
      if (selection.equalsRange(nextMatch.range)) {
        const replaceString = replacePattern.buildReplaceString(nextMatch.matches, this.b.preserveCase);
        const command4 = new $b6(selection, replaceString);
        this.B("replace", command4);
        this.d.setStartPosition(new $8C(selection.startLineNumber, selection.startColumn + replaceString.length));
        this.n(true);
      } else {
        this.d.setStartPosition(this.a.getPosition());
        this.q(nextMatch.range);
      }
    }
  }
  y(findScopes, captureMatches, limitResultCount) {
    const searchRanges = (findScopes || [null]).map((scope) => _$egb.l(this.a.getModel(), scope));
    return this.a.getModel().findMatches(this.b.searchString, searchRanges, this.b.isRegex, this.b.matchCase, this.b.wholeWord ? this.a.getOption(
      136
      /* EditorOption.wordSeparators */
    ) : null, captureMatches, limitResultCount);
  }
  replaceAll() {
    if (!this.o()) {
      return;
    }
    const findScopes = this.d.getFindScopes();
    if (findScopes === null && this.b.matchesCount >= $dgb) {
      this.z();
    } else {
      this.A(findScopes);
    }
    this.n(false);
  }
  z() {
    const searchParams = new $fI(this.b.searchString, this.b.isRegex, this.b.matchCase, this.b.wholeWord ? this.a.getOption(
      136
      /* EditorOption.wordSeparators */
    ) : null);
    const searchData = searchParams.parseSearchRequest();
    if (!searchData) {
      return;
    }
    let searchRegex = searchData.regex;
    if (!searchRegex.multiline) {
      let mod = "mu";
      if (searchRegex.ignoreCase) {
        mod += "i";
      }
      if (searchRegex.global) {
        mod += "g";
      }
      searchRegex = new RegExp(searchRegex.source, mod);
    }
    const model = this.a.getModel();
    const modelText = model.getValue(
      1
      /* EndOfLinePreference.LF */
    );
    const fullModelRange = model.getFullModelRange();
    const replacePattern = this.x();
    let resultText;
    const preserveCase = this.b.preserveCase;
    if (replacePattern.hasReplacementPatterns || preserveCase) {
      resultText = modelText.replace(searchRegex, function() {
        return replacePattern.buildReplaceString(arguments, preserveCase);
      });
    } else {
      resultText = modelText.replace(searchRegex, replacePattern.buildReplaceString(null, preserveCase));
    }
    const command4 = new $h6(fullModelRange, resultText, this.a.getSelection());
    this.B("replaceAll", command4);
  }
  A(findScopes) {
    const replacePattern = this.x();
    const matches = this.y(
      findScopes,
      replacePattern.hasReplacementPatterns || this.b.preserveCase,
      1073741824
      /* Constants.MAX_SAFE_SMALL_INTEGER */
    );
    const replaceStrings = [];
    for (let i2 = 0, len = matches.length; i2 < len; i2++) {
      replaceStrings[i2] = replacePattern.buildReplaceString(matches[i2].matches, this.b.preserveCase);
    }
    const command4 = new $2fb(this.a.getSelection(), matches.map((m) => m.range), replaceStrings);
    this.B("replaceAll", command4);
  }
  selectAllMatches() {
    if (!this.o()) {
      return;
    }
    const findScopes = this.d.getFindScopes();
    const matches = this.y(
      findScopes,
      false,
      1073741824
      /* Constants.MAX_SAFE_SMALL_INTEGER */
    );
    let selections = matches.map((m) => new $_D(m.range.startLineNumber, m.range.startColumn, m.range.endLineNumber, m.range.endColumn));
    const editorSelection = this.a.getSelection();
    for (let i2 = 0, len = selections.length; i2 < len; i2++) {
      const sel = selections[i2];
      if (sel.equalsRange(editorSelection)) {
        selections = [editorSelection].concat(selections.slice(0, i2)).concat(selections.slice(i2 + 1));
        break;
      }
    }
    this.a.setSelections(selections);
  }
  B(source, command4) {
    try {
      this.f = true;
      this.a.pushUndoStop();
      this.a.executeCommand(source, command4);
      this.a.pushUndoStop();
    } finally {
      this.f = false;
    }
  }
};

// out-build/vs/editor/contrib/find/browser/findOptionsWidget.js
var $fgb = class _$fgb extends $qZ {
  static {
    this.a = "editor.contrib.findOptionsWidget";
  }
  constructor(editor, state, keybindingService) {
    super();
    this.H = this.B(new $8h(() => this.O(), 2e3));
    this.M = false;
    this.c = editor;
    this.g = state;
    this.h = keybindingService;
    this.n = document.createElement("div");
    this.n.className = "findOptionsWidget";
    this.n.style.display = "none";
    this.n.style.top = "10px";
    this.n.style.zIndex = "12";
    this.n.setAttribute("role", "presentation");
    this.n.setAttribute("aria-hidden", "true");
    const toggleStyles = {
      inputActiveOptionBorder: $Zn($Aq),
      inputActiveOptionForeground: $Zn($Dq),
      inputActiveOptionBackground: $Zn($Cq)
    };
    const hoverDelegate = this.B($KZ());
    this.w = this.B(new $N2({
      appendTitle: this.y($cgb.ToggleCaseSensitiveCommand),
      isChecked: this.g.matchCase,
      hoverDelegate,
      ...toggleStyles
    }));
    this.n.appendChild(this.w.domNode);
    this.B(this.w.onChange(() => {
      this.g.change({
        matchCase: this.w.checked
      }, false);
    }));
    this.t = this.B(new $O2({
      appendTitle: this.y($cgb.ToggleWholeWordCommand),
      isChecked: this.g.wholeWord,
      hoverDelegate,
      ...toggleStyles
    }));
    this.n.appendChild(this.t.domNode);
    this.B(this.t.onChange(() => {
      this.g.change({
        wholeWord: this.t.checked
      }, false);
    }));
    this.r = this.B(new $P2({
      appendTitle: this.y($cgb.ToggleRegexCommand),
      isChecked: this.g.isRegex,
      hoverDelegate,
      ...toggleStyles
    }));
    this.n.appendChild(this.r.domNode);
    this.B(this.r.onChange(() => {
      this.g.change({
        isRegex: this.r.checked
      }, false);
    }));
    this.c.addOverlayWidget(this);
    this.B(this.g.onFindReplaceStateChange((e) => {
      let somethingChanged = false;
      if (e.isRegex) {
        this.r.checked = this.g.isRegex;
        somethingChanged = true;
      }
      if (e.wholeWord) {
        this.t.checked = this.g.wholeWord;
        somethingChanged = true;
      }
      if (e.matchCase) {
        this.w.checked = this.g.matchCase;
        somethingChanged = true;
      }
      if (!this.g.isRevealed && somethingChanged) {
        this.I();
      }
    }));
    this.B($_i(this.n, $7j.MOUSE_LEAVE, (e) => this.J()));
    this.B($_i(this.n, "mouseover", (e) => this.L()));
  }
  y(actionId) {
    const kb = this.h.lookupKeybinding(actionId);
    if (!kb) {
      return "";
    }
    return ` (${kb.getLabel()})`;
  }
  dispose() {
    this.c.removeOverlayWidget(this);
    super.dispose();
  }
  // ----- IOverlayWidget API
  getId() {
    return _$fgb.a;
  }
  getDomNode() {
    return this.n;
  }
  getPosition() {
    return {
      preference: 0
      /* OverlayWidgetPositionPreference.TOP_RIGHT_CORNER */
    };
  }
  highlightFindOptions() {
    this.I();
  }
  I() {
    this.N();
    this.H.schedule();
  }
  J() {
    this.H.schedule();
  }
  L() {
    this.H.cancel();
  }
  N() {
    if (this.M) {
      return;
    }
    this.M = true;
    this.n.style.display = "block";
  }
  O() {
    if (!this.M) {
      return;
    }
    this.M = false;
    this.n.style.display = "none";
  }
};

// out-build/vs/editor/contrib/find/browser/findState.js
var FindOptionOverride;
(function(FindOptionOverride2) {
  FindOptionOverride2[FindOptionOverride2["NotSet"] = 0] = "NotSet";
  FindOptionOverride2[FindOptionOverride2["True"] = 1] = "True";
  FindOptionOverride2[FindOptionOverride2["False"] = 2] = "False";
})(FindOptionOverride || (FindOptionOverride = {}));
function effectiveOptionValue(override, value) {
  if (override === 1) {
    return true;
  }
  if (override === 2) {
    return false;
  }
  return value;
}
var $1fb = class extends $3c {
  get searchString() {
    return this.a;
  }
  get replaceString() {
    return this.b;
  }
  get isRevealed() {
    return this.c;
  }
  get isReplaceRevealed() {
    return this.f;
  }
  get isRegex() {
    return effectiveOptionValue(this.h, this.g);
  }
  get wholeWord() {
    return effectiveOptionValue(this.m, this.j);
  }
  get matchCase() {
    return effectiveOptionValue(this.r, this.n);
  }
  get preserveCase() {
    return effectiveOptionValue(this.t, this.s);
  }
  get actualIsRegex() {
    return this.g;
  }
  get actualWholeWord() {
    return this.j;
  }
  get actualMatchCase() {
    return this.n;
  }
  get actualPreserveCase() {
    return this.s;
  }
  get searchScope() {
    return this.u;
  }
  get matchesPosition() {
    return this.w;
  }
  get matchesCount() {
    return this.y;
  }
  get currentMatch() {
    return this.z;
  }
  get isSearching() {
    return this.D;
  }
  get filters() {
    return this.F;
  }
  constructor() {
    super();
    this.G = this.B(new $ze());
    this.onFindReplaceStateChange = this.G.event;
    this.a = "";
    this.b = "";
    this.c = false;
    this.f = false;
    this.g = false;
    this.h = 0;
    this.j = false;
    this.m = 0;
    this.n = false;
    this.r = 0;
    this.s = false;
    this.t = 0;
    this.u = null;
    this.w = 0;
    this.y = 0;
    this.z = null;
    this.C = true;
    this.D = false;
    this.F = null;
  }
  changeMatchInfo(matchesPosition, matchesCount, currentMatch) {
    const changeEvent = {
      moveCursor: false,
      updateHistory: false,
      searchString: false,
      replaceString: false,
      isRevealed: false,
      isReplaceRevealed: false,
      isRegex: false,
      wholeWord: false,
      matchCase: false,
      preserveCase: false,
      searchScope: false,
      matchesPosition: false,
      matchesCount: false,
      currentMatch: false,
      loop: false,
      isSearching: false,
      filters: false
    };
    let somethingChanged = false;
    if (matchesCount === 0) {
      matchesPosition = 0;
    }
    if (matchesPosition > matchesCount) {
      matchesPosition = matchesCount;
    }
    if (this.w !== matchesPosition) {
      this.w = matchesPosition;
      changeEvent.matchesPosition = true;
      somethingChanged = true;
    }
    if (this.y !== matchesCount) {
      this.y = matchesCount;
      changeEvent.matchesCount = true;
      somethingChanged = true;
    }
    if (typeof currentMatch !== "undefined") {
      if (!$9C.equalsRange(this.z, currentMatch)) {
        this.z = currentMatch;
        changeEvent.currentMatch = true;
        somethingChanged = true;
      }
    }
    if (somethingChanged) {
      this.G.fire(changeEvent);
    }
  }
  change(newState, moveCursor, updateHistory = true) {
    const changeEvent = {
      moveCursor,
      updateHistory,
      searchString: false,
      replaceString: false,
      isRevealed: false,
      isReplaceRevealed: false,
      isRegex: false,
      wholeWord: false,
      matchCase: false,
      preserveCase: false,
      searchScope: false,
      matchesPosition: false,
      matchesCount: false,
      currentMatch: false,
      loop: false,
      isSearching: false,
      filters: false
    };
    let somethingChanged = false;
    const oldEffectiveIsRegex = this.isRegex;
    const oldEffectiveWholeWords = this.wholeWord;
    const oldEffectiveMatchCase = this.matchCase;
    const oldEffectivePreserveCase = this.preserveCase;
    if (typeof newState.searchString !== "undefined") {
      if (this.a !== newState.searchString) {
        this.a = newState.searchString;
        changeEvent.searchString = true;
        somethingChanged = true;
      }
    }
    if (typeof newState.replaceString !== "undefined") {
      if (this.b !== newState.replaceString) {
        this.b = newState.replaceString;
        changeEvent.replaceString = true;
        somethingChanged = true;
      }
    }
    if (typeof newState.isRevealed !== "undefined") {
      if (this.c !== newState.isRevealed) {
        this.c = newState.isRevealed;
        changeEvent.isRevealed = true;
        somethingChanged = true;
      }
    }
    if (typeof newState.isReplaceRevealed !== "undefined") {
      if (this.f !== newState.isReplaceRevealed) {
        this.f = newState.isReplaceRevealed;
        changeEvent.isReplaceRevealed = true;
        somethingChanged = true;
      }
    }
    if (typeof newState.isRegex !== "undefined") {
      this.g = newState.isRegex;
    }
    if (typeof newState.wholeWord !== "undefined") {
      this.j = newState.wholeWord;
    }
    if (typeof newState.matchCase !== "undefined") {
      this.n = newState.matchCase;
    }
    if (typeof newState.preserveCase !== "undefined") {
      this.s = newState.preserveCase;
    }
    if (typeof newState.searchScope !== "undefined") {
      if (!newState.searchScope?.every((newSearchScope) => {
        return this.u?.some((existingSearchScope) => {
          return !$9C.equalsRange(existingSearchScope, newSearchScope);
        });
      })) {
        this.u = newState.searchScope;
        changeEvent.searchScope = true;
        somethingChanged = true;
      }
    }
    if (typeof newState.loop !== "undefined") {
      if (this.C !== newState.loop) {
        this.C = newState.loop;
        changeEvent.loop = true;
        somethingChanged = true;
      }
    }
    if (typeof newState.isSearching !== "undefined") {
      if (this.D !== newState.isSearching) {
        this.D = newState.isSearching;
        changeEvent.isSearching = true;
        somethingChanged = true;
      }
    }
    if (typeof newState.filters !== "undefined") {
      if (this.F) {
        this.F.update(newState.filters);
      } else {
        this.F = newState.filters;
      }
      changeEvent.filters = true;
      somethingChanged = true;
    }
    this.h = typeof newState.isRegexOverride !== "undefined" ? newState.isRegexOverride : 0;
    this.m = typeof newState.wholeWordOverride !== "undefined" ? newState.wholeWordOverride : 0;
    this.r = typeof newState.matchCaseOverride !== "undefined" ? newState.matchCaseOverride : 0;
    this.t = typeof newState.preserveCaseOverride !== "undefined" ? newState.preserveCaseOverride : 0;
    if (oldEffectiveIsRegex !== this.isRegex) {
      somethingChanged = true;
      changeEvent.isRegex = true;
    }
    if (oldEffectiveWholeWords !== this.wholeWord) {
      somethingChanged = true;
      changeEvent.wholeWord = true;
    }
    if (oldEffectiveMatchCase !== this.matchCase) {
      somethingChanged = true;
      changeEvent.matchCase = true;
    }
    if (oldEffectivePreserveCase !== this.preserveCase) {
      somethingChanged = true;
      changeEvent.preserveCase = true;
    }
    if (somethingChanged) {
      this.G.fire(changeEvent);
    }
  }
  canNavigateBack() {
    return this.H() || this.matchesPosition !== 1;
  }
  canNavigateForward() {
    return this.H() || this.matchesPosition < this.matchesCount;
  }
  H() {
    return this.C || this.matchesCount >= $dgb;
  }
};

// out-build/vs/base/browser/ui/findinput/replaceInput.js
var NLS_DEFAULT_LABEL2 = localize(13, null);
var NLS_PRESERVE_CASE_LABEL = localize(14, null);
var PreserveCaseToggle = class extends $Q1 {
  constructor(opts) {
    super({
      // TODO: does this need its own icon?
      icon: $6l.preserveCase,
      title: NLS_PRESERVE_CASE_LABEL + opts.appendTitle,
      isChecked: opts.isChecked,
      hoverDelegate: opts.hoverDelegate ?? $JZ("element"),
      inputActiveOptionBorder: opts.inputActiveOptionBorder,
      inputActiveOptionForeground: opts.inputActiveOptionForeground,
      inputActiveOptionBackground: opts.inputActiveOptionBackground
    });
  }
};
var $R2 = class extends $qZ {
  static {
    this.OPTION_CHANGE = "optionChange";
  }
  constructor(parent, contextViewProvider, M, options3) {
    super();
    this.M = M;
    this.n = true;
    this.t = 0;
    this.w = this.B(new $ze());
    this.onDidOptionChange = this.w.event;
    this.y = this.B(new $ze());
    this.onKeyDown = this.y.event;
    this.H = this.B(new $ze());
    this.onMouseDown = this.H.event;
    this.I = this.B(new $ze());
    this.onInput = this.I.event;
    this.J = this.B(new $ze());
    this.onKeyUp = this.J.event;
    this.L = this.B(new $ze());
    this.onPreserveCaseKeyDown = this.L.event;
    this.O = 0;
    this.a = contextViewProvider;
    this.c = options3.placeholder || "";
    this.g = options3.validation;
    this.h = options3.label || NLS_DEFAULT_LABEL2;
    const appendPreserveCaseLabel = options3.appendPreserveCaseLabel || "";
    const history = options3.history || [];
    const flexibleHeight = !!options3.flexibleHeight;
    const flexibleWidth = !!options3.flexibleWidth;
    const flexibleMaxHeight = options3.flexibleMaxHeight;
    this.domNode = document.createElement("div");
    this.domNode.classList.add("monaco-findInput");
    this.inputBox = this.B(new $J2(this.domNode, this.a, {
      ariaLabel: this.h || "",
      placeholder: this.c || "",
      validationOptions: {
        validation: this.g
      },
      history: new Set(history),
      showHistoryHint: options3.showHistoryHint,
      flexibleHeight,
      flexibleWidth,
      flexibleMaxHeight,
      inputBoxStyles: options3.inputBoxStyles
    }));
    this.r = this.B(new PreserveCaseToggle({
      appendTitle: appendPreserveCaseLabel,
      isChecked: false,
      ...options3.toggleStyles
    }));
    this.B(this.r.onChange((viaKeyboard) => {
      this.w.fire(viaKeyboard);
      if (!viaKeyboard && this.n) {
        this.inputBox.focus();
      }
      this.validate();
    }));
    this.B(this.r.onKeyDown((e) => {
      this.L.fire(e);
    }));
    if (this.M) {
      this.t = this.r.width();
    } else {
      this.t = 0;
    }
    const indexes = [this.r.domNode];
    this.s(this.domNode, (event) => {
      if (event.equals(
        15
        /* KeyCode.LeftArrow */
      ) || event.equals(
        17
        /* KeyCode.RightArrow */
      ) || event.equals(
        9
        /* KeyCode.Escape */
      )) {
        const index = indexes.indexOf(this.domNode.ownerDocument.activeElement);
        if (index >= 0) {
          let newIndex = -1;
          if (event.equals(
            17
            /* KeyCode.RightArrow */
          )) {
            newIndex = (index + 1) % indexes.length;
          } else if (event.equals(
            15
            /* KeyCode.LeftArrow */
          )) {
            if (index === 0) {
              newIndex = indexes.length - 1;
            } else {
              newIndex = index - 1;
            }
          }
          if (event.equals(
            9
            /* KeyCode.Escape */
          )) {
            indexes[index].blur();
            this.inputBox.focus();
          } else if (newIndex >= 0) {
            indexes[newIndex].focus();
          }
          $9j.stop(event, true);
        }
      }
    });
    const controls = document.createElement("div");
    controls.className = "controls";
    controls.style.display = this.M ? "block" : "none";
    controls.appendChild(this.r.domNode);
    this.domNode.appendChild(controls);
    parent?.appendChild(this.domNode);
    this.s(this.inputBox.inputElement, (e) => this.y.fire(e));
    this.u(this.inputBox.inputElement, (e) => this.J.fire(e));
    this.z(this.inputBox.inputElement, (e) => this.I.fire());
    this.f(this.inputBox.inputElement, (e) => this.H.fire(e));
  }
  enable() {
    this.domNode.classList.remove("disabled");
    this.inputBox.enable();
    this.r.enable();
  }
  disable() {
    this.domNode.classList.add("disabled");
    this.inputBox.disable();
    this.r.disable();
  }
  setFocusInputOnOptionClick(value) {
    this.n = value;
  }
  setEnabled(enabled) {
    if (enabled) {
      this.enable();
    } else {
      this.disable();
    }
  }
  clear() {
    this.P();
    this.setValue("");
    this.focus();
  }
  getValue() {
    return this.inputBox.value;
  }
  setValue(value) {
    if (this.inputBox.value !== value) {
      this.inputBox.value = value;
    }
  }
  onSearchSubmit() {
    this.inputBox.addToHistory();
  }
  N() {
  }
  select() {
    this.inputBox.select();
  }
  focus() {
    this.inputBox.focus();
  }
  getPreserveCase() {
    return this.r.checked;
  }
  setPreserveCase(value) {
    this.r.checked = value;
  }
  focusOnPreserve() {
    this.r.focus();
  }
  highlightFindOptions() {
    this.domNode.classList.remove("highlight-" + this.O);
    this.O = 1 - this.O;
    this.domNode.classList.add("highlight-" + this.O);
  }
  validate() {
    this.inputBox?.validate();
  }
  showMessage(message) {
    this.inputBox?.showMessage(message);
  }
  clearMessage() {
    this.inputBox?.hideMessage();
  }
  P() {
    this.inputBox?.hideMessage();
  }
  set width(newWidth) {
    this.inputBox.paddingRight = this.t;
    this.domNode.style.width = newWidth + "px";
  }
  dispose() {
    super.dispose();
  }
};

// out-build/vs/platform/history/browser/contextScopedHistoryWidget.js
var $7bb = new $nn("suggestWidgetVisible", false, localize(1953, null));
var HistoryNavigationWidgetFocusContext = "historyNavigationWidgetFocus";
var HistoryNavigationForwardsEnablementContext = "historyNavigationForwardsEnabled";
var HistoryNavigationBackwardsEnablementContext = "historyNavigationBackwardsEnabled";
var lastFocusedWidget = void 0;
var widgets = [];
function $8bb(scopedContextKeyService, widget) {
  if (widgets.includes(widget)) {
    throw new Error("Cannot register the same widget multiple times");
  }
  widgets.push(widget);
  const disposableStore = new $2c();
  const historyNavigationWidgetFocus = new $nn(HistoryNavigationWidgetFocusContext, false).bindTo(scopedContextKeyService);
  const historyNavigationForwardsEnablement = new $nn(HistoryNavigationForwardsEnablementContext, true).bindTo(scopedContextKeyService);
  const historyNavigationBackwardsEnablement = new $nn(HistoryNavigationBackwardsEnablementContext, true).bindTo(scopedContextKeyService);
  const onDidFocus = () => {
    historyNavigationWidgetFocus.set(true);
    lastFocusedWidget = widget;
  };
  const onDidBlur = () => {
    historyNavigationWidgetFocus.set(false);
    if (lastFocusedWidget === widget) {
      lastFocusedWidget = void 0;
    }
  };
  if ($Mj(widget.element)) {
    onDidFocus();
  }
  disposableStore.add(widget.onDidFocus(() => onDidFocus()));
  disposableStore.add(widget.onDidBlur(() => onDidBlur()));
  disposableStore.add($1c(() => {
    widgets.splice(widgets.indexOf(widget), 1);
    onDidBlur();
  }));
  return {
    historyNavigationForwardsEnablement,
    historyNavigationBackwardsEnablement,
    dispose() {
      disposableStore.dispose();
    }
  };
}
var $9bb = class $9bb2 extends $J2 {
  constructor(container2, contextViewProvider, options3, contextKeyService) {
    super(container2, contextViewProvider, options3);
    const scopedContextKeyService = this.B(contextKeyService.createScoped(this.element));
    this.B($8bb(scopedContextKeyService, this));
  }
};
$9bb = __decorate([
  __param(3, $on)
], $9bb);
var $0bb = class $0bb2 extends $Q2 {
  constructor(container2, contextViewProvider, options3, contextKeyService) {
    super(container2, contextViewProvider, options3);
    const scopedContextKeyService = this.B(contextKeyService.createScoped(this.inputBox.element));
    this.B($8bb(scopedContextKeyService, this.inputBox));
  }
};
$0bb = __decorate([
  __param(3, $on)
], $0bb);
var $$bb = class $$bb2 extends $R2 {
  constructor(container2, contextViewProvider, options3, contextKeyService, showReplaceOptions = false) {
    super(container2, contextViewProvider, showReplaceOptions, options3);
    const scopedContextKeyService = this.B(contextKeyService.createScoped(this.inputBox.element));
    this.B($8bb(scopedContextKeyService, this.inputBox));
  }
};
$$bb = __decorate([
  __param(3, $on)
], $$bb);
$0I.registerCommandAndKeybindingRule({
  id: "history.showPrevious",
  weight: 200,
  when: $7m.and($7m.has(HistoryNavigationWidgetFocusContext), $7m.equals(HistoryNavigationBackwardsEnablementContext, true), $7m.not("isComposing"), $7bb.isEqualTo(false)),
  primary: 16,
  secondary: [
    512 | 16
    /* KeyCode.UpArrow */
  ],
  handler: (accessor) => {
    lastFocusedWidget?.showPreviousValue();
  }
});
$0I.registerCommandAndKeybindingRule({
  id: "history.showNext",
  weight: 200,
  when: $7m.and($7m.has(HistoryNavigationWidgetFocusContext), $7m.equals(HistoryNavigationForwardsEnablementContext, true), $7m.not("isComposing"), $7bb.isEqualTo(false)),
  primary: 18,
  secondary: [
    512 | 18
    /* KeyCode.DownArrow */
  ],
  handler: (accessor) => {
    lastFocusedWidget?.showNextValue();
  }
});

// out-build/vs/platform/history/browser/historyWidgetKeybindingHint.js
function $ggb(keybindingService) {
  return keybindingService.lookupKeybinding("history.showPrevious")?.getElectronAccelerator() === "Up" && keybindingService.lookupKeybinding("history.showNext")?.getElectronAccelerator() === "Down";
}

// out-build/vs/editor/contrib/find/browser/findWidget.js
var findCollapsedIcon = $9r("find-collapsed", $6l.chevronRight, localize(1031, null));
var findExpandedIcon = $9r("find-expanded", $6l.chevronDown, localize(1032, null));
var $hgb = $9r("find-selection", $6l.selection, localize(1033, null));
var $igb = $9r("find-replace", $6l.replace, localize(1034, null));
var $jgb = $9r("find-replace-all", $6l.replaceAll, localize(1035, null));
var $kgb = $9r("find-previous-match", $6l.arrowUp, localize(1036, null));
var $lgb = $9r("find-next-match", $6l.arrowDown, localize(1037, null));
var NLS_FIND_DIALOG_LABEL = localize(1038, null);
var NLS_FIND_INPUT_LABEL = localize(1039, null);
var NLS_FIND_INPUT_PLACEHOLDER = localize(1040, null);
var NLS_PREVIOUS_MATCH_BTN_LABEL = localize(1041, null);
var NLS_NEXT_MATCH_BTN_LABEL = localize(1042, null);
var NLS_TOGGLE_SELECTION_FIND_TITLE = localize(1043, null);
var NLS_CLOSE_BTN_LABEL = localize(1044, null);
var NLS_REPLACE_INPUT_LABEL = localize(1045, null);
var NLS_REPLACE_INPUT_PLACEHOLDER = localize(1046, null);
var NLS_REPLACE_BTN_LABEL = localize(1047, null);
var NLS_REPLACE_ALL_BTN_LABEL = localize(1048, null);
var NLS_TOGGLE_REPLACE_MODE_BTN_LABEL = localize(1049, null);
var NLS_MATCHES_COUNT_LIMIT_TITLE = localize(1050, null, $dgb);
var $mgb = localize(1051, null);
var $ngb = localize(1052, null);
var FIND_WIDGET_INITIAL_WIDTH = 419;
var PART_WIDTH = 275;
var FIND_INPUT_AREA_WIDTH = PART_WIDTH - 54;
var MAX_MATCHES_COUNT_WIDTH = 69;
var FIND_INPUT_AREA_HEIGHT = 33;
var ctrlEnterReplaceAllWarningPromptedKey = "ctrlEnterReplaceAll.windows.donotask";
var ctrlKeyMod2 = $m ? 256 : 2048;
var $ogb = class {
  constructor(afterLineNumber) {
    this.afterLineNumber = afterLineNumber;
    this.heightInPx = FIND_INPUT_AREA_HEIGHT;
    this.suppressMouseDown = false;
    this.domNode = document.createElement("div");
    this.domNode.className = "dock-find-viewzone";
  }
};
function stopPropagationForMultiLineUpwards(event, value, textarea) {
  const isMultiline2 = !!value.match(/\n/);
  if (textarea && isMultiline2 && textarea.selectionStart > 0) {
    event.stopPropagation();
    return;
  }
}
function stopPropagationForMultiLineDownwards(event, value, textarea) {
  const isMultiline2 = !!value.match(/\n/);
  if (textarea && isMultiline2 && textarea.selectionEnd < textarea.value.length) {
    event.stopPropagation();
    return;
  }
}
var $pgb = class _$pgb extends $qZ {
  static {
    this.a = "editor.contrib.findWidget";
  }
  constructor(codeEditor, controller, state, contextViewProvider, keybindingService, contextKeyService, themeService, storageService, notificationService, ib, jb) {
    super();
    this.ib = ib;
    this.jb = jb;
    this.I = null;
    this.sb = [];
    this.c = codeEditor;
    this.h = controller;
    this.g = state;
    this.n = contextViewProvider;
    this.r = keybindingService;
    this.t = contextKeyService;
    this.w = storageService;
    this.y = notificationService;
    this.Z = !!storageService.getBoolean(
      ctrlEnterReplaceAllWarningPromptedKey,
      0
      /* StorageScope.PROFILE */
    );
    this.W = false;
    this.X = false;
    this.Y = false;
    this.hb = new $Sh(500);
    this.B($1c(() => this.hb.cancel()));
    this.B(this.g.onFindReplaceStateChange((e) => this.lb(e)));
    this.Gb();
    this.rb();
    this.yb();
    this.J.inputBox.layout();
    this.B(this.c.onDidChangeConfiguration((e) => {
      if (e.hasChanged(
        96
        /* EditorOption.readOnly */
      )) {
        if (this.c.getOption(
          96
          /* EditorOption.readOnly */
        )) {
          this.g.change({ isReplaceRevealed: false }, false);
        }
        this.rb();
      }
      if (e.hasChanged(
        151
        /* EditorOption.layoutInfo */
      )) {
        this.yb();
      }
      if (e.hasChanged(
        2
        /* EditorOption.accessibilitySupport */
      )) {
        this.Hb();
      }
      if (e.hasChanged(
        43
        /* EditorOption.find */
      )) {
        const supportLoop = this.c.getOption(
          43
          /* EditorOption.find */
        ).loop;
        this.g.change({ loop: supportLoop }, false);
        const addExtraSpaceOnTop = this.c.getOption(
          43
          /* EditorOption.find */
        ).addExtraSpaceOnTop;
        if (addExtraSpaceOnTop && !this.db) {
          this.db = new $ogb(0);
          this.wb();
        }
        if (!addExtraSpaceOnTop && this.db) {
          this.xb();
        }
      }
    }));
    this.Hb();
    this.B(this.c.onDidChangeCursorSelection(() => {
      if (this.W) {
        this.qb();
      }
    }));
    this.B(this.c.onDidFocusEditorWidget(async () => {
      if (this.W) {
        const globalBufferTerm = await this.h.getGlobalBufferTerm();
        if (globalBufferTerm && globalBufferTerm !== this.g.searchString) {
          this.g.change({ searchString: globalBufferTerm }, false);
          this.J.select();
        }
      }
    }));
    this.ab = $8fb.bindTo(contextKeyService);
    this.$ = this.B($_j(this.J.inputBox.inputElement));
    this.B(this.$.onDidFocus(() => {
      this.ab.set(true);
      this.Bb();
    }));
    this.B(this.$.onDidBlur(() => {
      this.ab.set(false);
    }));
    this.cb = $9fb.bindTo(contextKeyService);
    this.bb = this.B($_j(this.L.inputBox.inputElement));
    this.B(this.bb.onDidFocus(() => {
      this.cb.set(true);
      this.Bb();
    }));
    this.B(this.bb.onDidBlur(() => {
      this.cb.set(false);
    }));
    this.c.addOverlayWidget(this);
    if (this.c.getOption(
      43
      /* EditorOption.find */
    ).addExtraSpaceOnTop) {
      this.db = new $ogb(0);
    }
    this.B(this.c.onDidChangeModel(() => {
      if (!this.W) {
        return;
      }
      this.eb = void 0;
    }));
    this.B(this.c.onDidScrollChange((e) => {
      if (e.scrollTopChanged) {
        this.vb();
        return;
      }
      setTimeout(() => {
        this.vb();
      }, 0);
    }));
  }
  // ----- IOverlayWidget API
  getId() {
    return _$pgb.a;
  }
  getDomNode() {
    return this.H;
  }
  getPosition() {
    if (this.W) {
      return {
        preference: 0
        /* OverlayWidgetPositionPreference.TOP_RIGHT_CORNER */
      };
    }
    return null;
  }
  // ----- React to state changes
  lb(e) {
    if (e.searchString) {
      try {
        this.Y = true;
        this.J.setValue(this.g.searchString);
      } finally {
        this.Y = false;
      }
      this.rb();
    }
    if (e.replaceString) {
      this.L.inputBox.value = this.g.replaceString;
    }
    if (e.isRevealed) {
      if (this.g.isRevealed) {
        this.tb();
      } else {
        this.ub(true);
      }
    }
    if (e.isReplaceRevealed) {
      if (this.g.isReplaceRevealed) {
        if (!this.c.getOption(
          96
          /* EditorOption.readOnly */
        ) && !this.X) {
          this.X = true;
          this.L.width = $xj(this.J.domNode);
          this.rb();
          this.L.inputBox.layout();
        }
      } else {
        if (this.X) {
          this.X = false;
          this.rb();
        }
      }
    }
    if ((e.isRevealed || e.isReplaceRevealed) && (this.g.isRevealed || this.g.isReplaceRevealed)) {
      if (this.Ab()) {
        this.wb();
      }
    }
    if (e.isRegex) {
      this.J.setRegex(this.g.isRegex);
    }
    if (e.wholeWord) {
      this.J.setWholeWords(this.g.wholeWord);
    }
    if (e.matchCase) {
      this.J.setCaseSensitive(this.g.matchCase);
    }
    if (e.preserveCase) {
      this.L.setPreserveCase(this.g.preserveCase);
    }
    if (e.searchScope) {
      if (this.g.searchScope) {
        this.Q.checked = true;
      } else {
        this.Q.checked = false;
      }
      this.qb();
    }
    if (e.searchString || e.matchesCount || e.matchesPosition) {
      const showRedOutline = this.g.searchString.length > 0 && this.g.matchesCount === 0;
      this.H.classList.toggle("no-results", showRedOutline);
      this.ob();
      this.rb();
    }
    if (e.searchString || e.currentMatch) {
      this.vb();
    }
    if (e.updateHistory) {
      this.mb();
    }
    if (e.loop) {
      this.rb();
    }
  }
  mb() {
    this.hb.trigger(this.nb.bind(this)).then(void 0, $gb);
  }
  nb() {
    if (this.g.searchString) {
      this.J.inputBox.addToHistory();
    }
    if (this.g.replaceString) {
      this.L.inputBox.addToHistory();
    }
  }
  ob() {
    this.N.style.minWidth = MAX_MATCHES_COUNT_WIDTH + "px";
    if (this.g.matchesCount >= $dgb) {
      this.N.title = NLS_MATCHES_COUNT_LIMIT_TITLE;
    } else {
      this.N.title = "";
    }
    this.N.firstChild?.remove();
    let label3;
    if (this.g.matchesCount > 0) {
      let matchesCount = String(this.g.matchesCount);
      if (this.g.matchesCount >= $dgb) {
        matchesCount += "+";
      }
      let matchesPosition = String(this.g.matchesPosition);
      if (matchesPosition === "0") {
        matchesPosition = "?";
      }
      label3 = $wf($mgb, matchesPosition, matchesCount);
    } else {
      label3 = $ngb;
    }
    this.N.appendChild(document.createTextNode(label3));
    $$Z(this.pb(label3, this.g.currentMatch, this.g.searchString));
    MAX_MATCHES_COUNT_WIDTH = Math.max(MAX_MATCHES_COUNT_WIDTH, this.N.clientWidth);
  }
  // ----- actions
  pb(label3, currentMatch, searchString) {
    if (label3 === $ngb) {
      return searchString === "" ? localize(1053, null, label3) : localize(1054, null, label3, searchString);
    }
    if (currentMatch) {
      const ariaLabel = localize(1055, null, label3, searchString, currentMatch.startLineNumber + ":" + currentMatch.startColumn);
      const model = this.c.getModel();
      if (model && currentMatch.startLineNumber <= model.getLineCount() && currentMatch.startLineNumber >= 1) {
        const lineContent = model.getLineContent(currentMatch.startLineNumber);
        return `${lineContent}, ${ariaLabel}`;
      }
      return ariaLabel;
    }
    return localize(1056, null, label3, searchString);
  }
  /**
   * If 'selection find' is ON we should not disable the button (its function is to cancel 'selection find').
   * If 'selection find' is OFF we enable the button only if there is a selection.
   */
  qb() {
    const selection = this.c.getSelection();
    const isSelection = selection ? selection.startLineNumber !== selection.endLineNumber || selection.startColumn !== selection.endColumn : false;
    const isChecked = this.Q.checked;
    if (this.W && (isChecked || isSelection)) {
      this.Q.enable();
    } else {
      this.Q.disable();
    }
  }
  rb() {
    this.J.setEnabled(this.W);
    this.L.setEnabled(this.W && this.X);
    this.qb();
    this.R.setEnabled(this.W);
    const findInputIsNonEmpty = this.g.searchString.length > 0;
    const matchesCount = this.g.matchesCount ? true : false;
    this.O.setEnabled(this.W && findInputIsNonEmpty && matchesCount && this.g.canNavigateBack());
    this.P.setEnabled(this.W && findInputIsNonEmpty && matchesCount && this.g.canNavigateForward());
    this.S.setEnabled(this.W && this.X && findInputIsNonEmpty);
    this.U.setEnabled(this.W && this.X && findInputIsNonEmpty);
    this.H.classList.toggle("replaceToggled", this.X);
    this.M.setExpanded(this.X);
    const canReplace = !this.c.getOption(
      96
      /* EditorOption.readOnly */
    );
    this.M.setEnabled(this.W && canReplace);
  }
  tb() {
    this.sb.forEach((e) => {
      clearTimeout(e);
    });
    this.sb = [];
    if (!this.W) {
      this.W = true;
      const selection = this.c.getSelection();
      switch (this.c.getOption(
        43
        /* EditorOption.find */
      ).autoFindInSelection) {
        case "always":
          this.Q.checked = true;
          break;
        case "never":
          this.Q.checked = false;
          break;
        case "multiline": {
          const isSelectionMultipleLine = !!selection && selection.startLineNumber !== selection.endLineNumber;
          this.Q.checked = isSelectionMultipleLine;
          break;
        }
        default:
          break;
      }
      this.yb();
      this.rb();
      this.sb.push(setTimeout(() => {
        this.H.classList.add("visible");
        this.H.setAttribute("aria-hidden", "false");
      }, 0));
      this.sb.push(setTimeout(() => {
        this.J.validate();
      }, 200));
      this.c.layoutOverlayWidget(this);
      let adjustEditorScrollTop = true;
      if (this.c.getOption(
        43
        /* EditorOption.find */
      ).seedSearchStringFromSelection && selection) {
        const domNode = this.c.getDomNode();
        if (domNode) {
          const editorCoords = $vj(domNode);
          const startCoords = this.c.getScrolledVisiblePosition(selection.getStartPosition());
          const startLeft = editorCoords.left + (startCoords ? startCoords.left : 0);
          const startTop = startCoords ? startCoords.top : 0;
          if (this.db && startTop < this.db.heightInPx) {
            if (selection.endLineNumber > selection.startLineNumber) {
              adjustEditorScrollTop = false;
            }
            const leftOfFindWidget = $sj(this.H).left;
            if (startLeft > leftOfFindWidget) {
              adjustEditorScrollTop = false;
            }
            const endCoords = this.c.getScrolledVisiblePosition(selection.getEndPosition());
            const endLeft = editorCoords.left + (endCoords ? endCoords.left : 0);
            if (endLeft > leftOfFindWidget) {
              adjustEditorScrollTop = false;
            }
          }
        }
      }
      this.wb(adjustEditorScrollTop);
    }
  }
  ub(focusTheEditor) {
    this.sb.forEach((e) => {
      clearTimeout(e);
    });
    this.sb = [];
    if (this.W) {
      this.W = false;
      this.rb();
      this.H.classList.remove("visible");
      this.H.setAttribute("aria-hidden", "true");
      this.J.clearMessage();
      if (focusTheEditor) {
        this.c.focus();
      }
      this.c.layoutOverlayWidget(this);
      this.xb();
    }
  }
  vb(targetScrollTop) {
    const addExtraSpaceOnTop = this.c.getOption(
      43
      /* EditorOption.find */
    ).addExtraSpaceOnTop;
    if (!addExtraSpaceOnTop) {
      this.xb();
      return;
    }
    if (!this.W) {
      return;
    }
    const viewZone = this.db;
    if (this.eb !== void 0 || !viewZone) {
      return;
    }
    this.c.changeViewZones((accessor) => {
      viewZone.heightInPx = this.zb();
      this.eb = accessor.addZone(viewZone);
      this.c.setScrollTop(targetScrollTop || this.c.getScrollTop() + viewZone.heightInPx);
    });
  }
  wb(adjustScroll = true) {
    if (!this.W) {
      return;
    }
    const addExtraSpaceOnTop = this.c.getOption(
      43
      /* EditorOption.find */
    ).addExtraSpaceOnTop;
    if (!addExtraSpaceOnTop) {
      return;
    }
    if (this.db === void 0) {
      this.db = new $ogb(0);
    }
    const viewZone = this.db;
    this.c.changeViewZones((accessor) => {
      if (this.eb !== void 0) {
        const newHeight = this.zb();
        if (newHeight === viewZone.heightInPx) {
          return;
        }
        const scrollAdjustment = newHeight - viewZone.heightInPx;
        viewZone.heightInPx = newHeight;
        accessor.layoutZone(this.eb);
        if (adjustScroll) {
          this.c.setScrollTop(this.c.getScrollTop() + scrollAdjustment);
        }
        return;
      } else {
        let scrollAdjustment = this.zb();
        scrollAdjustment -= this.c.getOption(
          88
          /* EditorOption.padding */
        ).top;
        if (scrollAdjustment <= 0) {
          return;
        }
        viewZone.heightInPx = scrollAdjustment;
        this.eb = accessor.addZone(viewZone);
        if (adjustScroll) {
          this.c.setScrollTop(this.c.getScrollTop() + scrollAdjustment);
        }
      }
    });
  }
  xb() {
    this.c.changeViewZones((accessor) => {
      if (this.eb !== void 0) {
        accessor.removeZone(this.eb);
        this.eb = void 0;
        if (this.db) {
          this.c.setScrollTop(this.c.getScrollTop() - this.db.heightInPx);
          this.db = void 0;
        }
      }
    });
  }
  yb() {
    if (!this.W) {
      return;
    }
    if (!this.H.isConnected) {
      return;
    }
    const layoutInfo = this.c.getLayoutInfo();
    const editorContentWidth = layoutInfo.contentWidth;
    if (editorContentWidth <= 0) {
      this.H.classList.add("hiddenEditor");
      return;
    } else if (this.H.classList.contains("hiddenEditor")) {
      this.H.classList.remove("hiddenEditor");
    }
    const editorWidth = layoutInfo.width;
    const minimapWidth = layoutInfo.minimap.minimapWidth;
    let collapsedFindWidget = false;
    let reducedFindWidget = false;
    let narrowFindWidget = false;
    if (this.gb) {
      const widgetWidth = $xj(this.H);
      if (widgetWidth > FIND_WIDGET_INITIAL_WIDTH) {
        this.H.style.maxWidth = `${editorWidth - 28 - minimapWidth - 15}px`;
        this.L.width = $xj(this.J.domNode);
        return;
      }
    }
    if (FIND_WIDGET_INITIAL_WIDTH + 28 + minimapWidth >= editorWidth) {
      reducedFindWidget = true;
    }
    if (FIND_WIDGET_INITIAL_WIDTH + 28 + minimapWidth - MAX_MATCHES_COUNT_WIDTH >= editorWidth) {
      narrowFindWidget = true;
    }
    if (FIND_WIDGET_INITIAL_WIDTH + 28 + minimapWidth - MAX_MATCHES_COUNT_WIDTH >= editorWidth + 50) {
      collapsedFindWidget = true;
    }
    this.H.classList.toggle("collapsed-find-widget", collapsedFindWidget);
    this.H.classList.toggle("narrow-find-widget", narrowFindWidget);
    this.H.classList.toggle("reduced-find-widget", reducedFindWidget);
    if (!narrowFindWidget && !collapsedFindWidget) {
      this.H.style.maxWidth = `${editorWidth - 28 - minimapWidth - 15}px`;
    }
    this.J.layout({ collapsedFindWidget, narrowFindWidget, reducedFindWidget });
    if (this.gb) {
      const findInputWidth = this.J.inputBox.element.clientWidth;
      if (findInputWidth > 0) {
        this.L.width = findInputWidth;
      }
    } else if (this.X) {
      this.L.width = $xj(this.J.domNode);
    }
  }
  zb() {
    let totalheight = 0;
    totalheight += 4;
    totalheight += this.J.inputBox.height + 2;
    if (this.X) {
      totalheight += 4;
      totalheight += this.L.inputBox.height + 2;
    }
    totalheight += 4;
    return totalheight;
  }
  Ab() {
    const totalHeight = this.zb();
    if (this.I !== null && this.I === totalHeight) {
      return false;
    }
    this.I = totalHeight;
    this.H.style.height = `${totalHeight}px`;
    return true;
  }
  // ----- Public
  focusFindInput() {
    this.J.select();
    this.J.focus();
  }
  focusReplaceInput() {
    this.L.select();
    this.L.focus();
  }
  highlightFindOptions() {
    this.J.highlightFindOptions();
  }
  Bb() {
    if (!this.c.hasModel()) {
      return;
    }
    if (this.Q.checked) {
      const selections = this.c.getSelections();
      selections.map((selection) => {
        if (selection.endColumn === 1 && selection.endLineNumber > selection.startLineNumber) {
          selection = selection.setEndPosition(selection.endLineNumber - 1, this.c.getModel().getLineMaxColumn(selection.endLineNumber - 1));
        }
        const currentMatch = this.g.currentMatch;
        if (selection.startLineNumber !== selection.endLineNumber) {
          if (!$9C.equalsRange(selection, currentMatch)) {
            return selection;
          }
        }
        return null;
      }).filter((element) => !!element);
      if (selections.length) {
        this.g.change({ searchScope: selections }, true);
      }
    }
  }
  Cb(e) {
    if (e.middleButton) {
      e.stopPropagation();
    }
  }
  Db(e) {
    if (e.equals(
      ctrlKeyMod2 | 3
      /* KeyCode.Enter */
    )) {
      if (this.r.dispatchEvent(e, e.target)) {
        e.preventDefault();
        return;
      } else {
        this.J.inputBox.insertAtCursor("\n");
        e.preventDefault();
        return;
      }
    }
    if (e.equals(
      2
      /* KeyCode.Tab */
    )) {
      if (this.X) {
        this.L.focus();
      } else {
        this.J.focusOnCaseSensitive();
      }
      e.preventDefault();
      return;
    }
    if (e.equals(
      2048 | 18
      /* KeyCode.DownArrow */
    )) {
      this.c.focus();
      e.preventDefault();
      return;
    }
    if (e.equals(
      16
      /* KeyCode.UpArrow */
    )) {
      return stopPropagationForMultiLineUpwards(e, this.J.getValue(), this.J.domNode.querySelector("textarea"));
    }
    if (e.equals(
      18
      /* KeyCode.DownArrow */
    )) {
      return stopPropagationForMultiLineDownwards(e, this.J.getValue(), this.J.domNode.querySelector("textarea"));
    }
  }
  Eb(e) {
    if (e.equals(
      ctrlKeyMod2 | 3
      /* KeyCode.Enter */
    )) {
      if (this.r.dispatchEvent(e, e.target)) {
        e.preventDefault();
        return;
      } else {
        if ($l && $p && !this.Z) {
          this.y.info(localize(1057, null));
          this.Z = true;
          this.w.store(
            ctrlEnterReplaceAllWarningPromptedKey,
            true,
            0,
            0
            /* StorageTarget.USER */
          );
        }
        this.L.inputBox.insertAtCursor("\n");
        e.preventDefault();
        return;
      }
    }
    if (e.equals(
      2
      /* KeyCode.Tab */
    )) {
      this.J.focusOnCaseSensitive();
      e.preventDefault();
      return;
    }
    if (e.equals(
      1024 | 2
      /* KeyCode.Tab */
    )) {
      this.J.focus();
      e.preventDefault();
      return;
    }
    if (e.equals(
      2048 | 18
      /* KeyCode.DownArrow */
    )) {
      this.c.focus();
      e.preventDefault();
      return;
    }
    if (e.equals(
      16
      /* KeyCode.UpArrow */
    )) {
      return stopPropagationForMultiLineUpwards(e, this.L.inputBox.value, this.L.inputBox.element.querySelector("textarea"));
    }
    if (e.equals(
      18
      /* KeyCode.DownArrow */
    )) {
      return stopPropagationForMultiLineDownwards(e, this.L.inputBox.value, this.L.inputBox.element.querySelector("textarea"));
    }
  }
  // ----- sash
  getVerticalSashLeft(_sash) {
    return 0;
  }
  // ----- initialization
  Fb(actionId) {
    const kb = this.r.lookupKeybinding(actionId);
    if (!kb) {
      return "";
    }
    return ` (${kb.getLabel()})`;
  }
  Gb() {
    const flexibleHeight = true;
    const flexibleWidth = true;
    const findSearchHistoryConfig = this.c.getOption(
      43
      /* EditorOption.find */
    ).history;
    this.J = this.B(new $0bb(null, this.n, {
      width: FIND_INPUT_AREA_WIDTH,
      label: NLS_FIND_INPUT_LABEL,
      placeholder: NLS_FIND_INPUT_PLACEHOLDER,
      appendCaseSensitiveLabel: this.Fb($cgb.ToggleCaseSensitiveCommand),
      appendWholeWordsLabel: this.Fb($cgb.ToggleWholeWordCommand),
      appendRegexLabel: this.Fb($cgb.ToggleRegexCommand),
      validation: (value) => {
        if (value.length === 0 || !this.J.getRegex()) {
          return null;
        }
        try {
          new RegExp(value, "gu");
          return null;
        } catch (e) {
          return { content: e.message };
        }
      },
      flexibleHeight,
      flexibleWidth,
      flexibleMaxHeight: 118,
      showCommonFindToggles: true,
      showHistoryHint: () => $ggb(this.r),
      inputBoxStyles: $B$,
      toggleStyles: $u$,
      history: findSearchHistoryConfig === "workspace" ? this.jb : /* @__PURE__ */ new Set([])
    }, this.t));
    this.J.setRegex(!!this.g.isRegex);
    this.J.setCaseSensitive(!!this.g.matchCase);
    this.J.setWholeWords(!!this.g.wholeWord);
    this.B(this.J.onKeyDown((e) => this.Db(e)));
    this.B(this.J.inputBox.onDidChange(() => {
      if (this.Y) {
        return;
      }
      this.g.change({ searchString: this.J.getValue() }, true);
    }));
    this.B(this.J.onDidOptionChange(() => {
      this.g.change({
        isRegex: this.J.getRegex(),
        wholeWord: this.J.getWholeWords(),
        matchCase: this.J.getCaseSensitive()
      }, true);
    }));
    this.B(this.J.onCaseSensitiveKeyDown((e) => {
      if (e.equals(
        1024 | 2
        /* KeyCode.Tab */
      )) {
        if (this.X) {
          this.L.focus();
          e.preventDefault();
        }
      }
    }));
    this.B(this.J.onRegexKeyDown((e) => {
      if (e.equals(
        2
        /* KeyCode.Tab */
      )) {
        if (this.X) {
          this.L.focusOnPreserve();
          e.preventDefault();
        }
      }
    }));
    this.B(this.J.inputBox.onDidHeightChange((e) => {
      if (this.Ab()) {
        this.wb();
      }
    }));
    if ($n) {
      this.B(this.J.onMouseDown((e) => this.Cb(e)));
    }
    this.N = document.createElement("div");
    this.N.className = "matchesCount";
    this.ob();
    const hoverDelegate = this.B($KZ());
    this.O = this.B(new $qgb({
      label: NLS_PREVIOUS_MATCH_BTN_LABEL + this.Fb($cgb.PreviousMatchFindAction),
      icon: $kgb,
      hoverDelegate,
      onTrigger: () => {
        $Kg(this.c.getAction($cgb.PreviousMatchFindAction)).run().then(void 0, $gb);
      }
    }, this.ib));
    this.P = this.B(new $qgb({
      label: NLS_NEXT_MATCH_BTN_LABEL + this.Fb($cgb.NextMatchFindAction),
      icon: $lgb,
      hoverDelegate,
      onTrigger: () => {
        $Kg(this.c.getAction($cgb.NextMatchFindAction)).run().then(void 0, $gb);
      }
    }, this.ib));
    const findPart = document.createElement("div");
    findPart.className = "find-part";
    findPart.appendChild(this.J.domNode);
    const actionsContainer = document.createElement("div");
    actionsContainer.className = "find-actions";
    findPart.appendChild(actionsContainer);
    actionsContainer.appendChild(this.N);
    actionsContainer.appendChild(this.O.domNode);
    actionsContainer.appendChild(this.P.domNode);
    this.Q = this.B(new $Q1({
      icon: $hgb,
      title: NLS_TOGGLE_SELECTION_FIND_TITLE + this.Fb($cgb.ToggleSearchScopeCommand),
      isChecked: false,
      hoverDelegate,
      inputActiveOptionBackground: $Zn($Cq),
      inputActiveOptionBorder: $Zn($Aq),
      inputActiveOptionForeground: $Zn($Dq)
    }));
    this.B(this.Q.onChange(() => {
      if (this.Q.checked) {
        if (this.c.hasModel()) {
          let selections = this.c.getSelections();
          selections = selections.map((selection) => {
            if (selection.endColumn === 1 && selection.endLineNumber > selection.startLineNumber) {
              selection = selection.setEndPosition(selection.endLineNumber - 1, this.c.getModel().getLineMaxColumn(selection.endLineNumber - 1));
            }
            if (!selection.isEmpty()) {
              return selection;
            }
            return null;
          }).filter((element) => !!element);
          if (selections.length) {
            this.g.change({ searchScope: selections }, true);
          }
        }
      } else {
        this.g.change({ searchScope: null }, true);
      }
    }));
    actionsContainer.appendChild(this.Q.domNode);
    this.R = this.B(new $qgb({
      label: NLS_CLOSE_BTN_LABEL + this.Fb($cgb.CloseFindWidgetCommand),
      icon: $_r,
      hoverDelegate,
      onTrigger: () => {
        this.g.change({ isRevealed: false, searchScope: null }, false);
      },
      onKeyDown: (e) => {
        if (e.equals(
          2
          /* KeyCode.Tab */
        )) {
          if (this.X) {
            if (this.S.isEnabled()) {
              this.S.focus();
            } else {
              this.c.focus();
            }
            e.preventDefault();
          }
        }
      }
    }, this.ib));
    this.L = this.B(new $$bb(null, void 0, {
      label: NLS_REPLACE_INPUT_LABEL,
      placeholder: NLS_REPLACE_INPUT_PLACEHOLDER,
      appendPreserveCaseLabel: this.Fb($cgb.TogglePreserveCaseCommand),
      history: [],
      flexibleHeight,
      flexibleWidth,
      flexibleMaxHeight: 118,
      showHistoryHint: () => $ggb(this.r),
      inputBoxStyles: $B$,
      toggleStyles: $u$
    }, this.t, true));
    this.L.setPreserveCase(!!this.g.preserveCase);
    this.B(this.L.onKeyDown((e) => this.Eb(e)));
    this.B(this.L.inputBox.onDidChange(() => {
      this.g.change({ replaceString: this.L.inputBox.value }, false);
    }));
    this.B(this.L.inputBox.onDidHeightChange((e) => {
      if (this.X && this.Ab()) {
        this.wb();
      }
    }));
    this.B(this.L.onDidOptionChange(() => {
      this.g.change({
        preserveCase: this.L.getPreserveCase()
      }, true);
    }));
    this.B(this.L.onPreserveCaseKeyDown((e) => {
      if (e.equals(
        2
        /* KeyCode.Tab */
      )) {
        if (this.O.isEnabled()) {
          this.O.focus();
        } else if (this.P.isEnabled()) {
          this.P.focus();
        } else if (this.Q.enabled) {
          this.Q.focus();
        } else if (this.R.isEnabled()) {
          this.R.focus();
        }
        e.preventDefault();
      }
    }));
    const replaceHoverDelegate = this.B($KZ());
    this.S = this.B(new $qgb({
      label: NLS_REPLACE_BTN_LABEL + this.Fb($cgb.ReplaceOneAction),
      icon: $igb,
      hoverDelegate: replaceHoverDelegate,
      onTrigger: () => {
        this.h.replace();
      },
      onKeyDown: (e) => {
        if (e.equals(
          1024 | 2
          /* KeyCode.Tab */
        )) {
          this.R.focus();
          e.preventDefault();
        }
      }
    }, this.ib));
    this.U = this.B(new $qgb({
      label: NLS_REPLACE_ALL_BTN_LABEL + this.Fb($cgb.ReplaceAllAction),
      icon: $jgb,
      hoverDelegate: replaceHoverDelegate,
      onTrigger: () => {
        this.h.replaceAll();
      }
    }, this.ib));
    const replacePart = document.createElement("div");
    replacePart.className = "replace-part";
    replacePart.appendChild(this.L.domNode);
    const replaceActionsContainer = document.createElement("div");
    replaceActionsContainer.className = "replace-actions";
    replacePart.appendChild(replaceActionsContainer);
    replaceActionsContainer.appendChild(this.S.domNode);
    replaceActionsContainer.appendChild(this.U.domNode);
    this.M = this.B(new $qgb({
      label: NLS_TOGGLE_REPLACE_MODE_BTN_LABEL,
      className: "codicon toggle left",
      onTrigger: () => {
        this.g.change({ isReplaceRevealed: !this.X }, false);
        if (this.X) {
          this.L.width = $xj(this.J.domNode);
          this.L.inputBox.layout();
        }
        this.wb();
      }
    }, this.ib));
    this.M.setExpanded(this.X);
    this.H = document.createElement("div");
    this.H.className = "editor-widget find-widget";
    this.H.setAttribute("aria-hidden", "true");
    this.H.ariaLabel = NLS_FIND_DIALOG_LABEL;
    this.H.role = "dialog";
    this.H.style.width = `${FIND_WIDGET_INITIAL_WIDTH}px`;
    this.H.appendChild(this.M.domNode);
    this.H.appendChild(findPart);
    this.H.appendChild(this.R.domNode);
    this.H.appendChild(replacePart);
    this.fb = this.B(new $q2(this.H, this, { orientation: 0, size: 2 }));
    this.gb = false;
    let originalWidth = FIND_WIDGET_INITIAL_WIDTH;
    this.B(this.fb.onDidStart(() => {
      originalWidth = $xj(this.H);
    }));
    this.B(this.fb.onDidChange((evt) => {
      this.gb = true;
      const width2 = originalWidth + evt.startX - evt.currentX;
      if (width2 < FIND_WIDGET_INITIAL_WIDTH) {
        return;
      }
      const maxWidth = parseFloat($pj(this.H).maxWidth) || 0;
      if (width2 > maxWidth) {
        return;
      }
      this.H.style.width = `${width2}px`;
      if (this.X) {
        this.L.width = $xj(this.J.domNode);
      }
      this.J.inputBox.layout();
      this.Ab();
    }));
    this.B(this.fb.onDidReset(() => {
      const currentWidth = $xj(this.H);
      if (currentWidth < FIND_WIDGET_INITIAL_WIDTH) {
        return;
      }
      let width2 = FIND_WIDGET_INITIAL_WIDTH;
      if (!this.gb || currentWidth === FIND_WIDGET_INITIAL_WIDTH) {
        const layoutInfo = this.c.getLayoutInfo();
        width2 = layoutInfo.width - 28 - layoutInfo.minimap.minimapWidth - 15;
        this.gb = true;
      } else {
      }
      this.H.style.width = `${width2}px`;
      if (this.X) {
        this.L.width = $xj(this.J.domNode);
      }
      this.J.inputBox.layout();
    }));
  }
  Hb() {
    const value = this.c.getOption(
      2
      /* EditorOption.accessibilitySupport */
    );
    this.J.setFocusInputOnOptionClick(
      value !== 2
      /* AccessibilitySupport.Enabled */
    );
  }
  getViewState() {
    let widgetViewZoneVisible = false;
    if (this.db && this.eb) {
      widgetViewZoneVisible = this.db.heightInPx > this.c.getScrollTop();
    }
    return {
      widgetViewZoneVisible,
      scrollTop: this.c.getScrollTop()
    };
  }
  setViewState(state) {
    if (!state) {
      return;
    }
    if (state.widgetViewZoneVisible) {
      this.vb(state.scrollTop);
    }
  }
};
var $qgb = class extends $qZ {
  constructor(opts, hoverService) {
    super();
    this.a = opts;
    let className = "button";
    if (this.a.className) {
      className = className + " " + this.a.className;
    }
    if (this.a.icon) {
      className = className + " " + ThemeIcon.asClassName(this.a.icon);
    }
    this.c = document.createElement("div");
    this.c.tabIndex = 0;
    this.c.className = className;
    this.c.setAttribute("role", "button");
    this.c.setAttribute("aria-label", this.a.label);
    this.B(hoverService.setupManagedHover(opts.hoverDelegate ?? $JZ("element"), this.c, this.a.label));
    this.b(this.c, (e) => {
      this.a.onTrigger();
      e.preventDefault();
    });
    this.s(this.c, (e) => {
      if (e.equals(
        10
        /* KeyCode.Space */
      ) || e.equals(
        3
        /* KeyCode.Enter */
      )) {
        this.a.onTrigger();
        e.preventDefault();
        return;
      }
      this.a.onKeyDown?.(e);
    });
  }
  get domNode() {
    return this.c;
  }
  isEnabled() {
    return this.c.tabIndex >= 0;
  }
  focus() {
    this.c.focus();
  }
  setEnabled(enabled) {
    this.c.classList.toggle("disabled", !enabled);
    this.c.setAttribute("aria-disabled", String(!enabled));
    this.c.tabIndex = enabled ? 0 : -1;
  }
  setExpanded(expanded2) {
    this.c.setAttribute("aria-expanded", String(!!expanded2));
    if (expanded2) {
      this.c.classList.remove(...ThemeIcon.asClassNameArray(findCollapsedIcon));
      this.c.classList.add(...ThemeIcon.asClassNameArray(findExpandedIcon));
    } else {
      this.c.classList.remove(...ThemeIcon.asClassNameArray(findExpandedIcon));
      this.c.classList.add(...ThemeIcon.asClassNameArray(findCollapsedIcon));
    }
  }
};
$ms((theme, collector) => {
  const findMatchHighlightBorder = theme.getColor($gp);
  if (findMatchHighlightBorder) {
    collector.addRule(`.monaco-editor .findMatch { border: 1px ${$es(theme.type) ? "dotted" : "solid"} ${findMatchHighlightBorder}; box-sizing: border-box; }`);
  }
  const findRangeHighlightBorder = theme.getColor($hp);
  if (findRangeHighlightBorder) {
    collector.addRule(`.monaco-editor .findScope { border: 1px ${$es(theme.type) ? "dashed" : "solid"} ${findRangeHighlightBorder}; }`);
  }
  const hcBorder = theme.getColor($ko);
  if (hcBorder) {
    collector.addRule(`.monaco-editor .find-widget { border: 1px solid ${hcBorder}; }`);
  }
  const findMatchForeground = theme.getColor($bp);
  if (findMatchForeground) {
    collector.addRule(`.monaco-editor .findMatchInline { color: ${findMatchForeground}; }`);
  }
  const findMatchHighlightForeground = theme.getColor($dp);
  if (findMatchHighlightForeground) {
    collector.addRule(`.monaco-editor .currentFindMatchInline { color: ${findMatchHighlightForeground}; }`);
  }
});

// out-build/vs/editor/contrib/find/browser/findWidgetSearchHistory.js
var $rgb_1;
var $rgb = class $rgb2 {
  static {
    $rgb_1 = this;
  }
  static {
    this.FIND_HISTORY_KEY = "workbench.find.history";
  }
  static {
    this.c = null;
  }
  static getOrCreate(storageService) {
    if (!$rgb_1.c) {
      $rgb_1.c = new $rgb_1(storageService);
    }
    return $rgb_1.c;
  }
  constructor(d) {
    this.d = d;
    this.a = /* @__PURE__ */ new Set();
    this.b = new $ze();
    this.onDidChange = this.b.event;
    this.load();
  }
  delete(t) {
    const result = this.a.delete(t);
    this.save();
    return result;
  }
  add(t) {
    this.a.add(t);
    this.save();
    return this;
  }
  has(t) {
    return this.a.has(t);
  }
  clear() {
    this.a.clear();
    this.save();
  }
  forEach(callbackfn, thisArg) {
    this.load();
    return this.a.forEach(callbackfn);
  }
  replace(t) {
    this.a = new Set(t);
    this.save();
  }
  load() {
    let result;
    const raw = this.d.get(
      $rgb_1.FIND_HISTORY_KEY,
      1
      /* StorageScope.WORKSPACE */
    );
    if (raw) {
      try {
        result = JSON.parse(raw);
      } catch (e) {
      }
    }
    this.a = new Set(result || []);
  }
  // Run saves async
  save() {
    const elements = [];
    this.a.forEach((e) => elements.push(e));
    return new Promise((resolve) => {
      this.d.store(
        $rgb_1.FIND_HISTORY_KEY,
        JSON.stringify(elements),
        1,
        0
        /* StorageTarget.USER */
      );
      this.b.fire(elements);
      resolve();
    });
  }
};
$rgb = $rgb_1 = __decorate([
  __param(0, $jv)
], $rgb);

// out-build/vs/editor/contrib/find/browser/findController.js
var $tgb_1;
var SEARCH_STRING_MAX_LENGTH = 524288;
function $sgb(editor, seedSearchStringFromSelection = "single", seedSearchStringFromNonEmptySelection = false) {
  if (!editor.hasModel()) {
    return null;
  }
  const selection = editor.getSelection();
  if (seedSearchStringFromSelection === "single" && selection.startLineNumber === selection.endLineNumber || seedSearchStringFromSelection === "multiple") {
    if (selection.isEmpty()) {
      const wordAtPosition = editor.getConfiguredWordAtPosition(selection.getStartPosition());
      if (wordAtPosition && false === seedSearchStringFromNonEmptySelection) {
        return wordAtPosition.word;
      }
    } else {
      if (editor.getModel().getValueLengthInRange(selection) < SEARCH_STRING_MAX_LENGTH) {
        return editor.getModel().getValueInRange(selection);
      }
    }
  }
  return null;
}
var FindStartFocusAction;
(function(FindStartFocusAction2) {
  FindStartFocusAction2[FindStartFocusAction2["NoFocusChange"] = 0] = "NoFocusChange";
  FindStartFocusAction2[FindStartFocusAction2["FocusFindInput"] = 1] = "FocusFindInput";
  FindStartFocusAction2[FindStartFocusAction2["FocusReplaceInput"] = 2] = "FocusReplaceInput";
})(FindStartFocusAction || (FindStartFocusAction = {}));
var $tgb = class $tgb2 extends $3c {
  static {
    $tgb_1 = this;
  }
  static {
    this.ID = "editor.contrib.findController";
  }
  get editor() {
    return this.a;
  }
  static get(editor) {
    return editor.getContribution($tgb_1.ID);
  }
  constructor(editor, contextKeyService, storageService, clipboardService, notificationService, hoverService) {
    super();
    this.a = editor;
    this.b = $6fb.bindTo(contextKeyService);
    this.m = contextKeyService;
    this.h = storageService;
    this.j = clipboardService;
    this.n = notificationService;
    this.r = hoverService;
    this.f = new $Sh(500);
    this.c = this.B(new $1fb());
    this.w();
    this.B(this.c.onFindReplaceStateChange((e) => this.t(e)));
    this.g = null;
    this.B(this.a.onDidChangeModel(() => {
      const shouldRestartFind = this.a.getModel() && this.c.isRevealed;
      this.s();
      this.c.change({
        searchScope: null,
        matchCase: this.h.getBoolean("editor.matchCase", 1, false),
        wholeWord: this.h.getBoolean("editor.wholeWord", 1, false),
        isRegex: this.h.getBoolean("editor.isRegex", 1, false),
        preserveCase: this.h.getBoolean("editor.preserveCase", 1, false)
      }, false);
      if (shouldRestartFind) {
        this.y({
          forceRevealReplace: false,
          seedSearchStringFromSelection: "none",
          seedSearchStringFromNonEmptySelection: false,
          seedSearchStringFromGlobalClipboard: false,
          shouldFocus: 0,
          shouldAnimate: false,
          updateSearchScope: false,
          loop: this.a.getOption(
            43
            /* EditorOption.find */
          ).loop
        });
      }
    }));
  }
  dispose() {
    this.s();
    super.dispose();
  }
  s() {
    if (this.g) {
      this.g.dispose();
      this.g = null;
    }
  }
  t(e) {
    this.u(e);
    if (e.isRevealed) {
      if (this.c.isRevealed) {
        this.b.set(true);
      } else {
        this.b.reset();
        this.s();
      }
    }
    if (e.searchString) {
      this.setGlobalBufferTerm(this.c.searchString);
    }
  }
  u(e) {
    if (e.isRegex) {
      this.h.store(
        "editor.isRegex",
        this.c.actualIsRegex,
        1,
        1
        /* StorageTarget.MACHINE */
      );
    }
    if (e.wholeWord) {
      this.h.store(
        "editor.wholeWord",
        this.c.actualWholeWord,
        1,
        1
        /* StorageTarget.MACHINE */
      );
    }
    if (e.matchCase) {
      this.h.store(
        "editor.matchCase",
        this.c.actualMatchCase,
        1,
        1
        /* StorageTarget.MACHINE */
      );
    }
    if (e.preserveCase) {
      this.h.store(
        "editor.preserveCase",
        this.c.actualPreserveCase,
        1,
        1
        /* StorageTarget.MACHINE */
      );
    }
  }
  w() {
    this.c.change({
      matchCase: this.h.getBoolean("editor.matchCase", 1, this.c.matchCase),
      wholeWord: this.h.getBoolean("editor.wholeWord", 1, this.c.wholeWord),
      isRegex: this.h.getBoolean("editor.isRegex", 1, this.c.isRegex),
      preserveCase: this.h.getBoolean("editor.preserveCase", 1, this.c.preserveCase)
    }, false);
  }
  isFindInputFocused() {
    return !!$8fb.getValue(this.m);
  }
  getState() {
    return this.c;
  }
  closeFindWidget() {
    this.c.change({
      isRevealed: false,
      searchScope: null
    }, false);
    this.a.focus();
  }
  toggleCaseSensitive() {
    this.c.change({ matchCase: !this.c.matchCase }, false);
    if (!this.c.isRevealed) {
      this.highlightFindOptions();
    }
  }
  toggleWholeWords() {
    this.c.change({ wholeWord: !this.c.wholeWord }, false);
    if (!this.c.isRevealed) {
      this.highlightFindOptions();
    }
  }
  toggleRegex() {
    this.c.change({ isRegex: !this.c.isRegex }, false);
    if (!this.c.isRevealed) {
      this.highlightFindOptions();
    }
  }
  togglePreserveCase() {
    this.c.change({ preserveCase: !this.c.preserveCase }, false);
    if (!this.c.isRevealed) {
      this.highlightFindOptions();
    }
  }
  toggleSearchScope() {
    if (this.c.searchScope) {
      this.c.change({ searchScope: null }, true);
    } else {
      if (this.a.hasModel()) {
        let selections = this.a.getSelections();
        selections = selections.map((selection) => {
          if (selection.endColumn === 1 && selection.endLineNumber > selection.startLineNumber) {
            selection = selection.setEndPosition(selection.endLineNumber - 1, this.a.getModel().getLineMaxColumn(selection.endLineNumber - 1));
          }
          if (!selection.isEmpty()) {
            return selection;
          }
          return null;
        }).filter((element) => !!element);
        if (selections.length) {
          this.c.change({ searchScope: selections }, true);
        }
      }
    }
  }
  setSearchString(searchString) {
    if (this.c.isRegex) {
      searchString = $Af(searchString);
    }
    this.c.change({ searchString }, false);
  }
  highlightFindOptions(ignoreWhenVisible = false) {
  }
  async y(opts, newState) {
    this.s();
    if (!this.a.hasModel()) {
      return;
    }
    const stateChanges = {
      ...newState,
      isRevealed: true
    };
    if (opts.seedSearchStringFromSelection === "single") {
      const selectionSearchString = $sgb(this.a, opts.seedSearchStringFromSelection, opts.seedSearchStringFromNonEmptySelection);
      if (selectionSearchString) {
        if (this.c.isRegex) {
          stateChanges.searchString = $Af(selectionSearchString);
        } else {
          stateChanges.searchString = selectionSearchString;
        }
      }
    } else if (opts.seedSearchStringFromSelection === "multiple" && !opts.updateSearchScope) {
      const selectionSearchString = $sgb(this.a, opts.seedSearchStringFromSelection);
      if (selectionSearchString) {
        stateChanges.searchString = selectionSearchString;
      }
    }
    if (!stateChanges.searchString && opts.seedSearchStringFromGlobalClipboard) {
      const selectionSearchString = await this.getGlobalBufferTerm();
      if (!this.a.hasModel()) {
        return;
      }
      if (selectionSearchString) {
        stateChanges.searchString = selectionSearchString;
      }
    }
    if (opts.forceRevealReplace || stateChanges.isReplaceRevealed) {
      stateChanges.isReplaceRevealed = true;
    } else if (!this.b.get()) {
      stateChanges.isReplaceRevealed = false;
    }
    if (opts.updateSearchScope) {
      const currentSelections = this.a.getSelections();
      if (currentSelections.some((selection) => !selection.isEmpty())) {
        stateChanges.searchScope = currentSelections;
      }
    }
    stateChanges.loop = opts.loop;
    this.c.change(stateChanges, false);
    if (!this.g) {
      this.g = new $egb(this.a, this.c);
    }
  }
  start(opts, newState) {
    return this.y(opts, newState);
  }
  moveToNextMatch() {
    if (this.g) {
      this.g.moveToNextMatch();
      return true;
    }
    return false;
  }
  moveToPrevMatch() {
    if (this.g) {
      this.g.moveToPrevMatch();
      return true;
    }
    return false;
  }
  goToMatch(index) {
    if (this.g) {
      this.g.moveToMatch(index);
      return true;
    }
    return false;
  }
  replace() {
    if (this.g) {
      this.g.replace();
      return true;
    }
    return false;
  }
  replaceAll() {
    if (this.g) {
      if (this.a.getModel()?.isTooLargeForHeapOperation()) {
        this.n.warn(localize(1015, null));
        return false;
      }
      this.g.replaceAll();
      return true;
    }
    return false;
  }
  selectAllMatches() {
    if (this.g) {
      this.g.selectAllMatches();
      this.a.focus();
      return true;
    }
    return false;
  }
  async getGlobalBufferTerm() {
    if (this.a.getOption(
      43
      /* EditorOption.find */
    ).globalFindClipboard && this.a.hasModel() && !this.a.getModel().isTooLargeForSyncing()) {
      return this.j.readFindText();
    }
    return "";
  }
  setGlobalBufferTerm(text2) {
    if (this.a.getOption(
      43
      /* EditorOption.find */
    ).globalFindClipboard && this.a.hasModel() && !this.a.getModel().isTooLargeForSyncing()) {
      this.j.writeFindText(text2);
    }
  }
};
$tgb = $tgb_1 = __decorate([
  __param(1, $on),
  __param(2, $jv),
  __param(3, $30),
  __param(4, $PJ),
  __param(5, $5$)
], $tgb);
var $ugb = class $ugb2 extends $tgb {
  constructor(editor, F, _contextKeyService, G, H, notificationService, _storageService, clipboardService, hoverService) {
    super(editor, _contextKeyService, _storageService, clipboardService, notificationService, hoverService);
    this.F = F;
    this.G = G;
    this.H = H;
    this.z = null;
    this.C = null;
    this.D = $rgb.getOrCreate(_storageService);
  }
  async y(opts, newState) {
    if (!this.z) {
      this.J();
    }
    const selection = this.a.getSelection();
    let updateSearchScope = false;
    switch (this.a.getOption(
      43
      /* EditorOption.find */
    ).autoFindInSelection) {
      case "always":
        updateSearchScope = true;
        break;
      case "never":
        updateSearchScope = false;
        break;
      case "multiline": {
        const isSelectionMultipleLine = !!selection && selection.startLineNumber !== selection.endLineNumber;
        updateSearchScope = isSelectionMultipleLine;
        break;
      }
      default:
        break;
    }
    opts.updateSearchScope = opts.updateSearchScope || updateSearchScope;
    await super.y(opts, newState);
    if (this.z) {
      if (opts.shouldFocus === 2) {
        this.z.focusReplaceInput();
      } else if (opts.shouldFocus === 1) {
        this.z.focusFindInput();
      }
    }
  }
  highlightFindOptions(ignoreWhenVisible = false) {
    if (!this.z) {
      this.J();
    }
    if (this.c.isRevealed && !ignoreWhenVisible) {
      this.z.highlightFindOptions();
    } else {
      this.C.highlightFindOptions();
    }
  }
  J() {
    this.z = this.B(new $pgb(this.a, this, this.c, this.F, this.G, this.m, this.H, this.h, this.n, this.r, this.D));
    this.C = this.B(new $fgb(this.a, this.c, this.G));
  }
  saveViewState() {
    return this.z?.getViewState();
  }
  restoreViewState(state) {
    this.z?.setViewState(state);
  }
};
$ugb = __decorate([
  __param(1, $40),
  __param(2, $on),
  __param(3, $Ty),
  __param(4, $gs),
  __param(5, $PJ),
  __param(6, $jv),
  __param(7, $30),
  __param(8, $5$)
], $ugb);
var $vgb = $65(new $15({
  id: $cgb.StartFindAction,
  label: localize2(1022, "Find"),
  precondition: $7m.or(EditorContextKeys.focus, $7m.has("editorIsOpen")),
  kbOpts: {
    kbExpr: null,
    primary: 2048 | 36,
    weight: 100
    /* KeybindingWeight.EditorContrib */
  },
  menuOpts: {
    menuId: $bJ.MenubarEditMenu,
    group: "3_find",
    title: localize(1016, null),
    order: 1
  }
}));
$vgb.addImplementation(0, (accessor, editor, args2) => {
  const controller = $tgb.get(editor);
  if (!controller) {
    return false;
  }
  return controller.start({
    forceRevealReplace: false,
    seedSearchStringFromSelection: editor.getOption(
      43
      /* EditorOption.find */
    ).seedSearchStringFromSelection !== "never" ? "single" : "none",
    seedSearchStringFromNonEmptySelection: editor.getOption(
      43
      /* EditorOption.find */
    ).seedSearchStringFromSelection === "selection",
    seedSearchStringFromGlobalClipboard: editor.getOption(
      43
      /* EditorOption.find */
    ).globalFindClipboard,
    shouldFocus: 1,
    shouldAnimate: true,
    updateSearchScope: false,
    loop: editor.getOption(
      43
      /* EditorOption.find */
    ).loop
  });
});
var findArgDescription = {
  description: "Open a new In-Editor Find Widget.",
  args: [{
    name: "Open a new In-Editor Find Widget args",
    schema: {
      properties: {
        searchString: { type: "string" },
        replaceString: { type: "string" },
        isRegex: { type: "boolean" },
        matchWholeWord: { type: "boolean" },
        isCaseSensitive: { type: "boolean" },
        preserveCase: { type: "boolean" },
        findInSelection: { type: "boolean" }
      }
    }
  }]
};
var $wgb = class extends $Z5 {
  constructor() {
    super({
      id: $cgb.StartFindWithArgs,
      label: localize2(1023, "Find With Arguments"),
      precondition: void 0,
      kbOpts: {
        kbExpr: null,
        primary: 0,
        weight: 100
        /* KeybindingWeight.EditorContrib */
      },
      metadata: findArgDescription
    });
  }
  async run(accessor, editor, args2) {
    const controller = $tgb.get(editor);
    if (controller) {
      const newState = args2 ? {
        searchString: args2.searchString,
        replaceString: args2.replaceString,
        isReplaceRevealed: args2.replaceString !== void 0,
        isRegex: args2.isRegex,
        // isRegexOverride: args.regexOverride,
        wholeWord: args2.matchWholeWord,
        // wholeWordOverride: args.wholeWordOverride,
        matchCase: args2.isCaseSensitive,
        // matchCaseOverride: args.matchCaseOverride,
        preserveCase: args2.preserveCase
        // preserveCaseOverride: args.preserveCaseOverride,
      } : {};
      await controller.start({
        forceRevealReplace: false,
        seedSearchStringFromSelection: controller.getState().searchString.length === 0 && editor.getOption(
          43
          /* EditorOption.find */
        ).seedSearchStringFromSelection !== "never" ? "single" : "none",
        seedSearchStringFromNonEmptySelection: editor.getOption(
          43
          /* EditorOption.find */
        ).seedSearchStringFromSelection === "selection",
        seedSearchStringFromGlobalClipboard: true,
        shouldFocus: 1,
        shouldAnimate: true,
        updateSearchScope: args2?.findInSelection || false,
        loop: editor.getOption(
          43
          /* EditorOption.find */
        ).loop
      }, newState);
      controller.setGlobalBufferTerm(controller.getState().searchString);
    }
  }
};
var $xgb = class extends $Z5 {
  constructor() {
    super({
      id: $cgb.StartFindWithSelection,
      label: localize2(1024, "Find With Selection"),
      precondition: void 0,
      kbOpts: {
        kbExpr: null,
        primary: 0,
        mac: {
          primary: 2048 | 35
        },
        weight: 100
        /* KeybindingWeight.EditorContrib */
      }
    });
  }
  async run(accessor, editor) {
    const controller = $tgb.get(editor);
    if (controller) {
      await controller.start({
        forceRevealReplace: false,
        seedSearchStringFromSelection: "multiple",
        seedSearchStringFromNonEmptySelection: false,
        seedSearchStringFromGlobalClipboard: false,
        shouldFocus: 0,
        shouldAnimate: true,
        updateSearchScope: false,
        loop: editor.getOption(
          43
          /* EditorOption.find */
        ).loop
      });
      controller.setGlobalBufferTerm(controller.getState().searchString);
    }
  }
};
var $ygb = class extends $Z5 {
  async run(accessor, editor) {
    const controller = $tgb.get(editor);
    if (controller && !this.d(controller)) {
      await controller.start({
        forceRevealReplace: false,
        seedSearchStringFromSelection: controller.getState().searchString.length === 0 && editor.getOption(
          43
          /* EditorOption.find */
        ).seedSearchStringFromSelection !== "never" ? "single" : "none",
        seedSearchStringFromNonEmptySelection: editor.getOption(
          43
          /* EditorOption.find */
        ).seedSearchStringFromSelection === "selection",
        seedSearchStringFromGlobalClipboard: true,
        shouldFocus: 0,
        shouldAnimate: true,
        updateSearchScope: false,
        loop: editor.getOption(
          43
          /* EditorOption.find */
        ).loop
      });
      this.d(controller);
    }
  }
};
var $zgb = class extends $ygb {
  constructor() {
    super({
      id: $cgb.NextMatchFindAction,
      label: localize2(1025, "Find Next"),
      precondition: void 0,
      kbOpts: [{
        kbExpr: EditorContextKeys.focus,
        primary: 61,
        mac: { primary: 2048 | 37, secondary: [
          61
          /* KeyCode.F3 */
        ] },
        weight: 100
        /* KeybindingWeight.EditorContrib */
      }, {
        kbExpr: $7m.and(EditorContextKeys.focus, $8fb),
        primary: 3,
        weight: 100
        /* KeybindingWeight.EditorContrib */
      }]
    });
  }
  d(controller) {
    const result = controller.moveToNextMatch();
    if (result) {
      controller.editor.pushUndoStop();
      return true;
    }
    return false;
  }
};
var $Agb = class extends $ygb {
  constructor() {
    super({
      id: $cgb.PreviousMatchFindAction,
      label: localize2(1026, "Find Previous"),
      precondition: void 0,
      kbOpts: [
        {
          kbExpr: EditorContextKeys.focus,
          primary: 1024 | 61,
          mac: { primary: 2048 | 1024 | 37, secondary: [
            1024 | 61
            /* KeyCode.F3 */
          ] },
          weight: 100
          /* KeybindingWeight.EditorContrib */
        },
        {
          kbExpr: $7m.and(EditorContextKeys.focus, $8fb),
          primary: 1024 | 3,
          weight: 100
          /* KeybindingWeight.EditorContrib */
        }
      ]
    });
  }
  d(controller) {
    return controller.moveToPrevMatch();
  }
};
var $Bgb = class extends $Z5 {
  constructor() {
    super({
      id: $cgb.GoToMatchFindAction,
      label: localize2(1027, "Go to Match..."),
      precondition: $6fb
    });
    this.d = [];
  }
  run(accessor, editor, args2) {
    const controller = $tgb.get(editor);
    if (!controller) {
      return;
    }
    const matchesCount = controller.getState().matchesCount;
    if (matchesCount < 1) {
      const notificationService = accessor.get($PJ);
      notificationService.notify({
        severity: Severity2.Warning,
        message: localize(1017, null)
      });
      return;
    }
    const quickInputService = accessor.get($1M);
    const disposables = new $2c();
    const inputBox = disposables.add(quickInputService.createInputBox());
    inputBox.placeholder = localize(1018, null, matchesCount);
    const toFindMatchIndex = (value) => {
      const index = parseInt(value);
      if (isNaN(index)) {
        return void 0;
      }
      const matchCount = controller.getState().matchesCount;
      if (index > 0 && index <= matchCount) {
        return index - 1;
      } else if (index < 0 && index >= -matchCount) {
        return matchCount + index;
      }
      return void 0;
    };
    const updatePickerAndEditor = (value) => {
      const index = toFindMatchIndex(value);
      if (typeof index === "number") {
        inputBox.validationMessage = void 0;
        controller.goToMatch(index);
        const currentMatch = controller.getState().currentMatch;
        if (currentMatch) {
          this.j(editor, currentMatch);
        }
      } else {
        inputBox.validationMessage = localize(1019, null, controller.getState().matchesCount);
        this.h(editor);
      }
    };
    disposables.add(inputBox.onDidChangeValue((value) => {
      updatePickerAndEditor(value);
    }));
    disposables.add(inputBox.onDidAccept(() => {
      const index = toFindMatchIndex(inputBox.value);
      if (typeof index === "number") {
        controller.goToMatch(index);
        inputBox.hide();
      } else {
        inputBox.validationMessage = localize(1020, null, controller.getState().matchesCount);
      }
    }));
    disposables.add(inputBox.onDidHide(() => {
      this.h(editor);
      disposables.dispose();
    }));
    inputBox.show();
  }
  h(editor) {
    editor.changeDecorations((changeAccessor) => {
      this.d = changeAccessor.deltaDecorations(this.d, []);
    });
  }
  j(editor, range) {
    editor.changeDecorations((changeAccessor) => {
      this.d = changeAccessor.deltaDecorations(this.d, [
        {
          range,
          options: {
            description: "find-match-quick-access-range-highlight",
            className: "rangeHighlight",
            isWholeLine: true
          }
        },
        {
          range,
          options: {
            description: "find-match-quick-access-range-highlight-overview",
            overviewRuler: {
              color: $hs($pH),
              position: OverviewRulerLane.Full
            }
          }
        }
      ]);
    });
  }
};
var $Cgb = class extends $Z5 {
  async run(accessor, editor) {
    const controller = $tgb.get(editor);
    if (!controller) {
      return;
    }
    const selectionSearchString = $sgb(editor, "single", false);
    if (selectionSearchString) {
      controller.setSearchString(selectionSearchString);
    }
    if (!this.d(controller)) {
      await controller.start({
        forceRevealReplace: false,
        seedSearchStringFromSelection: "none",
        seedSearchStringFromNonEmptySelection: false,
        seedSearchStringFromGlobalClipboard: false,
        shouldFocus: 0,
        shouldAnimate: true,
        updateSearchScope: false,
        loop: editor.getOption(
          43
          /* EditorOption.find */
        ).loop
      });
      this.d(controller);
    }
  }
};
var $Dgb = class extends $Cgb {
  constructor() {
    super({
      id: $cgb.NextSelectionMatchFindAction,
      label: localize2(1028, "Find Next Selection"),
      precondition: void 0,
      kbOpts: {
        kbExpr: EditorContextKeys.focus,
        primary: 2048 | 61,
        weight: 100
        /* KeybindingWeight.EditorContrib */
      }
    });
  }
  d(controller) {
    return controller.moveToNextMatch();
  }
};
var $Egb = class extends $Cgb {
  constructor() {
    super({
      id: $cgb.PreviousSelectionMatchFindAction,
      label: localize2(1029, "Find Previous Selection"),
      precondition: void 0,
      kbOpts: {
        kbExpr: EditorContextKeys.focus,
        primary: 2048 | 1024 | 61,
        weight: 100
        /* KeybindingWeight.EditorContrib */
      }
    });
  }
  d(controller) {
    return controller.moveToPrevMatch();
  }
};
var $Fgb = $65(new $15({
  id: $cgb.StartFindReplaceAction,
  label: localize2(1030, "Replace"),
  precondition: $7m.or(EditorContextKeys.focus, $7m.has("editorIsOpen")),
  kbOpts: {
    kbExpr: null,
    primary: 2048 | 38,
    mac: {
      primary: 2048 | 512 | 36
      /* KeyCode.KeyF */
    },
    weight: 100
    /* KeybindingWeight.EditorContrib */
  },
  menuOpts: {
    menuId: $bJ.MenubarEditMenu,
    group: "3_find",
    title: localize(1021, null),
    order: 2
  }
}));
$Fgb.addImplementation(0, (accessor, editor, args2) => {
  if (!editor.hasModel() || editor.getOption(
    96
    /* EditorOption.readOnly */
  )) {
    return false;
  }
  const controller = $tgb.get(editor);
  if (!controller) {
    return false;
  }
  const currentSelection = editor.getSelection();
  const findInputFocused = controller.isFindInputFocused();
  const seedSearchStringFromSelection = !currentSelection.isEmpty() && currentSelection.startLineNumber === currentSelection.endLineNumber && editor.getOption(
    43
    /* EditorOption.find */
  ).seedSearchStringFromSelection !== "never" && !findInputFocused;
  const shouldFocus = findInputFocused || seedSearchStringFromSelection ? 2 : 1;
  return controller.start({
    forceRevealReplace: true,
    seedSearchStringFromSelection: seedSearchStringFromSelection ? "single" : "none",
    seedSearchStringFromNonEmptySelection: editor.getOption(
      43
      /* EditorOption.find */
    ).seedSearchStringFromSelection === "selection",
    seedSearchStringFromGlobalClipboard: editor.getOption(
      43
      /* EditorOption.find */
    ).seedSearchStringFromSelection !== "never",
    shouldFocus,
    shouldAnimate: true,
    updateSearchScope: false,
    loop: editor.getOption(
      43
      /* EditorOption.find */
    ).loop
  });
});
$85(
  $tgb.ID,
  $ugb,
  0
  /* EditorContributionInstantiation.Eager */
);
$55($wgb);
$55($xgb);
$55($zgb);
$55($Agb);
$55($Bgb);
$55($Dgb);
$55($Egb);
var FindCommand = $Y5.bindToContribution($tgb.get);
$45(new FindCommand({
  id: $cgb.CloseFindWidgetCommand,
  precondition: $6fb,
  handler: (x) => x.closeFindWidget(),
  kbOpts: {
    weight: 100 + 5,
    kbExpr: $7m.and(EditorContextKeys.focus, $7m.not("isComposing")),
    primary: 9,
    secondary: [
      1024 | 9
      /* KeyCode.Escape */
    ]
  }
}));
$45(new FindCommand({
  id: $cgb.ToggleCaseSensitiveCommand,
  precondition: void 0,
  handler: (x) => x.toggleCaseSensitive(),
  kbOpts: {
    weight: 100 + 5,
    kbExpr: EditorContextKeys.focus,
    primary: $0fb.primary,
    mac: $0fb.mac,
    win: $0fb.win,
    linux: $0fb.linux
  }
}));
$45(new FindCommand({
  id: $cgb.ToggleWholeWordCommand,
  precondition: void 0,
  handler: (x) => x.toggleWholeWords(),
  kbOpts: {
    weight: 100 + 5,
    kbExpr: EditorContextKeys.focus,
    primary: $$fb.primary,
    mac: $$fb.mac,
    win: $$fb.win,
    linux: $$fb.linux
  }
}));
$45(new FindCommand({
  id: $cgb.ToggleRegexCommand,
  precondition: void 0,
  handler: (x) => x.toggleRegex(),
  kbOpts: {
    weight: 100 + 5,
    kbExpr: EditorContextKeys.focus,
    primary: $_fb.primary,
    mac: $_fb.mac,
    win: $_fb.win,
    linux: $_fb.linux
  }
}));
$45(new FindCommand({
  id: $cgb.ToggleSearchScopeCommand,
  precondition: void 0,
  handler: (x) => x.toggleSearchScope(),
  kbOpts: {
    weight: 100 + 5,
    kbExpr: EditorContextKeys.focus,
    primary: $agb.primary,
    mac: $agb.mac,
    win: $agb.win,
    linux: $agb.linux
  }
}));
$45(new FindCommand({
  id: $cgb.TogglePreserveCaseCommand,
  precondition: void 0,
  handler: (x) => x.togglePreserveCase(),
  kbOpts: {
    weight: 100 + 5,
    kbExpr: EditorContextKeys.focus,
    primary: $bgb.primary,
    mac: $bgb.mac,
    win: $bgb.win,
    linux: $bgb.linux
  }
}));
$45(new FindCommand({
  id: $cgb.ReplaceOneAction,
  precondition: $6fb,
  handler: (x) => x.replace(),
  kbOpts: {
    weight: 100 + 5,
    kbExpr: EditorContextKeys.focus,
    primary: 2048 | 1024 | 22
    /* KeyCode.Digit1 */
  }
}));
$45(new FindCommand({
  id: $cgb.ReplaceOneAction,
  precondition: $6fb,
  handler: (x) => x.replace(),
  kbOpts: {
    weight: 100 + 5,
    kbExpr: $7m.and(EditorContextKeys.focus, $9fb),
    primary: 3
    /* KeyCode.Enter */
  }
}));
$45(new FindCommand({
  id: $cgb.ReplaceAllAction,
  precondition: $6fb,
  handler: (x) => x.replaceAll(),
  kbOpts: {
    weight: 100 + 5,
    kbExpr: EditorContextKeys.focus,
    primary: 2048 | 512 | 3
    /* KeyCode.Enter */
  }
}));
$45(new FindCommand({
  id: $cgb.ReplaceAllAction,
  precondition: $6fb,
  handler: (x) => x.replaceAll(),
  kbOpts: {
    weight: 100 + 5,
    kbExpr: $7m.and(EditorContextKeys.focus, $9fb),
    primary: void 0,
    mac: {
      primary: 2048 | 3
    }
  }
}));
$45(new FindCommand({
  id: $cgb.SelectAllMatchesAction,
  precondition: $6fb,
  handler: (x) => x.selectAllMatches(),
  kbOpts: {
    weight: 100 + 5,
    kbExpr: EditorContextKeys.focus,
    primary: 512 | 3
    /* KeyCode.Enter */
  }
}));

// out-build/vs/editor/contrib/folding/browser/foldingRanges.js
var FoldSource;
(function(FoldSource2) {
  FoldSource2[FoldSource2["provider"] = 0] = "provider";
  FoldSource2[FoldSource2["userDefined"] = 1] = "userDefined";
  FoldSource2[FoldSource2["recovered"] = 2] = "recovered";
})(FoldSource || (FoldSource = {}));
var $Ggb = {
  [
    0
    /* FoldSource.provider */
  ]: " ",
  [
    1
    /* FoldSource.userDefined */
  ]: "u",
  [
    2
    /* FoldSource.recovered */
  ]: "r"
};
var $Hgb = 65535;
var $Igb = 16777215;
var MASK_INDENT = 4278190080;
var BitField = class {
  constructor(size) {
    const numWords = Math.ceil(size / 32);
    this.a = new Uint32Array(numWords);
  }
  get(index) {
    const arrayIndex = index / 32 | 0;
    const bit = index % 32;
    return (this.a[arrayIndex] & 1 << bit) !== 0;
  }
  set(index, newState) {
    const arrayIndex = index / 32 | 0;
    const bit = index % 32;
    const value = this.a[arrayIndex];
    if (newState) {
      this.a[arrayIndex] = value | 1 << bit;
    } else {
      this.a[arrayIndex] = value & ~(1 << bit);
    }
  }
};
var $Jgb = class _$Jgb {
  constructor(startIndexes, endIndexes, types) {
    if (startIndexes.length !== endIndexes.length || startIndexes.length > $Hgb) {
      throw new Error("invalid startIndexes or endIndexes size");
    }
    this.a = startIndexes;
    this.b = endIndexes;
    this.c = new BitField(startIndexes.length);
    this.d = new BitField(startIndexes.length);
    this.e = new BitField(startIndexes.length);
    this.g = types;
    this.f = false;
  }
  h() {
    if (!this.f) {
      this.f = true;
      const parentIndexes = [];
      const isInsideLast = (startLineNumber, endLineNumber) => {
        const index = parentIndexes[parentIndexes.length - 1];
        return this.getStartLineNumber(index) <= startLineNumber && this.getEndLineNumber(index) >= endLineNumber;
      };
      for (let i2 = 0, len = this.a.length; i2 < len; i2++) {
        const startLineNumber = this.a[i2];
        const endLineNumber = this.b[i2];
        if (startLineNumber > $Igb || endLineNumber > $Igb) {
          throw new Error("startLineNumber or endLineNumber must not exceed " + $Igb);
        }
        while (parentIndexes.length > 0 && !isInsideLast(startLineNumber, endLineNumber)) {
          parentIndexes.pop();
        }
        const parentIndex = parentIndexes.length > 0 ? parentIndexes[parentIndexes.length - 1] : -1;
        parentIndexes.push(i2);
        this.a[i2] = startLineNumber + ((parentIndex & 255) << 24);
        this.b[i2] = endLineNumber + ((parentIndex & 65280) << 16);
      }
    }
  }
  get length() {
    return this.a.length;
  }
  getStartLineNumber(index) {
    return this.a[index] & $Igb;
  }
  getEndLineNumber(index) {
    return this.b[index] & $Igb;
  }
  getType(index) {
    return this.g ? this.g[index] : void 0;
  }
  hasTypes() {
    return !!this.g;
  }
  isCollapsed(index) {
    return this.c.get(index);
  }
  setCollapsed(index, newState) {
    this.c.set(index, newState);
  }
  j(index) {
    return this.d.get(index);
  }
  k(index, newState) {
    return this.d.set(index, newState);
  }
  l(index) {
    return this.e.get(index);
  }
  m(index, newState) {
    return this.e.set(index, newState);
  }
  getSource(index) {
    if (this.j(index)) {
      return 1;
    } else if (this.l(index)) {
      return 2;
    }
    return 0;
  }
  setSource(index, source) {
    if (source === 1) {
      this.k(index, true);
      this.m(index, false);
    } else if (source === 2) {
      this.k(index, false);
      this.m(index, true);
    } else {
      this.k(index, false);
      this.m(index, false);
    }
  }
  setCollapsedAllOfType(type, newState) {
    let hasChanged = false;
    if (this.g) {
      for (let i2 = 0; i2 < this.g.length; i2++) {
        if (this.g[i2] === type) {
          this.setCollapsed(i2, newState);
          hasChanged = true;
        }
      }
    }
    return hasChanged;
  }
  toRegion(index) {
    return new $Kgb(this, index);
  }
  getParentIndex(index) {
    this.h();
    const parent = ((this.a[index] & MASK_INDENT) >>> 24) + ((this.b[index] & MASK_INDENT) >>> 16);
    if (parent === $Hgb) {
      return -1;
    }
    return parent;
  }
  contains(index, line) {
    return this.getStartLineNumber(index) <= line && this.getEndLineNumber(index) >= line;
  }
  n(line) {
    let low = 0, high = this.a.length;
    if (high === 0) {
      return -1;
    }
    while (low < high) {
      const mid = Math.floor((low + high) / 2);
      if (line < this.getStartLineNumber(mid)) {
        high = mid;
      } else {
        low = mid + 1;
      }
    }
    return low - 1;
  }
  findRange(line) {
    let index = this.n(line);
    if (index >= 0) {
      const endLineNumber = this.getEndLineNumber(index);
      if (endLineNumber >= line) {
        return index;
      }
      index = this.getParentIndex(index);
      while (index !== -1) {
        if (this.contains(index, line)) {
          return index;
        }
        index = this.getParentIndex(index);
      }
    }
    return -1;
  }
  toString() {
    const res = [];
    for (let i2 = 0; i2 < this.length; i2++) {
      res[i2] = `[${$Ggb[this.getSource(i2)]}${this.isCollapsed(i2) ? "+" : "-"}] ${this.getStartLineNumber(i2)}/${this.getEndLineNumber(i2)}`;
    }
    return res.join(", ");
  }
  toFoldRange(index) {
    return {
      startLineNumber: this.a[index] & $Igb,
      endLineNumber: this.b[index] & $Igb,
      type: this.g ? this.g[index] : void 0,
      isCollapsed: this.isCollapsed(index),
      source: this.getSource(index)
    };
  }
  static fromFoldRanges(ranges) {
    const rangesLength = ranges.length;
    const startIndexes = new Uint32Array(rangesLength);
    const endIndexes = new Uint32Array(rangesLength);
    let types = [];
    let gotTypes = false;
    for (let i2 = 0; i2 < rangesLength; i2++) {
      const range = ranges[i2];
      startIndexes[i2] = range.startLineNumber;
      endIndexes[i2] = range.endLineNumber;
      types.push(range.type);
      if (range.type) {
        gotTypes = true;
      }
    }
    if (!gotTypes) {
      types = void 0;
    }
    const regions = new _$Jgb(startIndexes, endIndexes, types);
    for (let i2 = 0; i2 < rangesLength; i2++) {
      if (ranges[i2].isCollapsed) {
        regions.setCollapsed(i2, true);
      }
      regions.setSource(i2, ranges[i2].source);
    }
    return regions;
  }
  /**
   * Two inputs, each a FoldingRegions or a FoldRange[], are merged.
   * Each input must be pre-sorted on startLineNumber.
   * The first list is assumed to always include all regions currently defined by range providers.
   * The second list only contains the previously collapsed and all manual ranges.
   * If the line position matches, the range of the new range is taken, and the range is no longer manual
   * When an entry in one list overlaps an entry in the other, the second list's entry "wins" and
   * overlapping entries in the first list are discarded.
   * Invalid entries are discarded. An entry is invalid if:
   * 		the start and end line numbers aren't a valid range of line numbers,
   * 		it is out of sequence or has the same start line as a preceding entry,
   * 		it overlaps a preceding entry and is not fully contained by that entry.
   */
  static sanitizeAndMerge(rangesA, rangesB, maxLineNumber, selection) {
    maxLineNumber = maxLineNumber ?? Number.MAX_VALUE;
    const getIndexedFunction = (r2, limit) => {
      return Array.isArray(r2) ? (i2) => {
        return i2 < limit ? r2[i2] : void 0;
      } : (i2) => {
        return i2 < limit ? r2.toFoldRange(i2) : void 0;
      };
    };
    const getA = getIndexedFunction(rangesA, rangesA.length);
    const getB = getIndexedFunction(rangesB, rangesB.length);
    let indexA = 0;
    let indexB = 0;
    let nextA = getA(0);
    let nextB = getB(0);
    const stackedRanges = [];
    let topStackedRange;
    let prevLineNumber = 0;
    const resultRanges = [];
    while (nextA || nextB) {
      let useRange = void 0;
      if (nextB && (!nextA || nextA.startLineNumber >= nextB.startLineNumber)) {
        if (nextA && nextA.startLineNumber === nextB.startLineNumber) {
          if (nextB.source === 1) {
            useRange = nextB;
          } else {
            useRange = nextA;
            useRange.isCollapsed = nextB.isCollapsed && (nextA.endLineNumber === nextB.endLineNumber || !selection?.startsInside(nextA.startLineNumber + 1, nextA.endLineNumber + 1));
            useRange.source = 0;
          }
          nextA = getA(++indexA);
        } else {
          useRange = nextB;
          if (nextB.isCollapsed && nextB.source === 0) {
            useRange.source = 2;
          }
        }
        nextB = getB(++indexB);
      } else {
        let scanIndex = indexB;
        let prescanB = nextB;
        while (true) {
          if (!prescanB || prescanB.startLineNumber > nextA.endLineNumber) {
            useRange = nextA;
            break;
          }
          if (prescanB.source === 1 && prescanB.endLineNumber > nextA.endLineNumber) {
            break;
          }
          prescanB = getB(++scanIndex);
        }
        nextA = getA(++indexA);
      }
      if (useRange) {
        while (topStackedRange && topStackedRange.endLineNumber < useRange.startLineNumber) {
          topStackedRange = stackedRanges.pop();
        }
        if (useRange.endLineNumber > useRange.startLineNumber && useRange.startLineNumber > prevLineNumber && useRange.endLineNumber <= maxLineNumber && (!topStackedRange || topStackedRange.endLineNumber >= useRange.endLineNumber)) {
          resultRanges.push(useRange);
          prevLineNumber = useRange.startLineNumber;
          if (topStackedRange) {
            stackedRanges.push(topStackedRange);
          }
          topStackedRange = useRange;
        }
      }
    }
    return resultRanges;
  }
};
var $Kgb = class {
  constructor(a, b) {
    this.a = a;
    this.b = b;
  }
  get startLineNumber() {
    return this.a.getStartLineNumber(this.b);
  }
  get endLineNumber() {
    return this.a.getEndLineNumber(this.b);
  }
  get regionIndex() {
    return this.b;
  }
  get parentIndex() {
    return this.a.getParentIndex(this.b);
  }
  get isCollapsed() {
    return this.a.isCollapsed(this.b);
  }
  containedBy(range) {
    return range.startLineNumber <= this.startLineNumber && range.endLineNumber >= this.endLineNumber;
  }
  containsLine(lineNumber) {
    return this.startLineNumber <= lineNumber && lineNumber <= this.endLineNumber;
  }
  hidesLine(lineNumber) {
    return this.startLineNumber < lineNumber && lineNumber <= this.endLineNumber;
  }
};

// out-build/vs/editor/contrib/folding/browser/foldingModel.js
var $Lgb = class {
  get regions() {
    return this.c;
  }
  get textModel() {
    return this.a;
  }
  get decorationProvider() {
    return this.b;
  }
  constructor(textModel, decorationProvider) {
    this.e = new $ze();
    this.onDidChange = this.e.event;
    this.a = textModel;
    this.b = decorationProvider;
    this.c = new $Jgb(new Uint32Array(0), new Uint32Array(0));
    this.d = [];
  }
  toggleCollapseState(toggledRegions) {
    if (!toggledRegions.length) {
      return;
    }
    toggledRegions = toggledRegions.sort((r1, r2) => r1.regionIndex - r2.regionIndex);
    const processed = {};
    this.b.changeDecorations((accessor) => {
      let k = 0;
      let dirtyRegionEndLine = -1;
      let lastHiddenLine = -1;
      const updateDecorationsUntil = (index) => {
        while (k < index) {
          const endLineNumber = this.c.getEndLineNumber(k);
          const isCollapsed = this.c.isCollapsed(k);
          if (endLineNumber <= dirtyRegionEndLine) {
            const isManual = this.regions.getSource(k) !== 0;
            accessor.changeDecorationOptions(this.d[k], this.b.getDecorationOption(isCollapsed, endLineNumber <= lastHiddenLine, isManual));
          }
          if (isCollapsed && endLineNumber > lastHiddenLine) {
            lastHiddenLine = endLineNumber;
          }
          k++;
        }
      };
      for (const region of toggledRegions) {
        const index = region.regionIndex;
        const editorDecorationId = this.d[index];
        if (editorDecorationId && !processed[editorDecorationId]) {
          processed[editorDecorationId] = true;
          updateDecorationsUntil(index);
          const newCollapseState = !this.c.isCollapsed(index);
          this.c.setCollapsed(index, newCollapseState);
          dirtyRegionEndLine = Math.max(dirtyRegionEndLine, this.c.getEndLineNumber(index));
        }
      }
      updateDecorationsUntil(this.c.length);
    });
    this.e.fire({ model: this, collapseStateChanged: toggledRegions });
  }
  removeManualRanges(ranges) {
    const newFoldingRanges = new Array();
    const intersects4 = (foldRange) => {
      for (const range of ranges) {
        if (!(range.startLineNumber > foldRange.endLineNumber || foldRange.startLineNumber > range.endLineNumber)) {
          return true;
        }
      }
      return false;
    };
    for (let i2 = 0; i2 < this.c.length; i2++) {
      const foldRange = this.c.toFoldRange(i2);
      if (foldRange.source === 0 || !intersects4(foldRange)) {
        newFoldingRanges.push(foldRange);
      }
    }
    this.updatePost($Jgb.fromFoldRanges(newFoldingRanges));
  }
  update(newRegions, selection) {
    const foldedOrManualRanges = this.f(selection);
    const newRanges = $Jgb.sanitizeAndMerge(newRegions, foldedOrManualRanges, this.a.getLineCount(), selection);
    this.updatePost($Jgb.fromFoldRanges(newRanges));
  }
  updatePost(newRegions) {
    const newEditorDecorations = [];
    let lastHiddenLine = -1;
    for (let index = 0, limit = newRegions.length; index < limit; index++) {
      const startLineNumber = newRegions.getStartLineNumber(index);
      const endLineNumber = newRegions.getEndLineNumber(index);
      const isCollapsed = newRegions.isCollapsed(index);
      const isManual = newRegions.getSource(index) !== 0;
      const decorationRange = {
        startLineNumber,
        startColumn: this.a.getLineMaxColumn(startLineNumber),
        endLineNumber,
        endColumn: this.a.getLineMaxColumn(endLineNumber) + 1
      };
      newEditorDecorations.push({ range: decorationRange, options: this.b.getDecorationOption(isCollapsed, endLineNumber <= lastHiddenLine, isManual) });
      if (isCollapsed && endLineNumber > lastHiddenLine) {
        lastHiddenLine = endLineNumber;
      }
    }
    this.b.changeDecorations((accessor) => this.d = accessor.deltaDecorations(this.d, newEditorDecorations));
    this.c = newRegions;
    this.e.fire({ model: this });
  }
  f(selection) {
    const foldedRanges = [];
    for (let i2 = 0, limit = this.c.length; i2 < limit; i2++) {
      let isCollapsed = this.regions.isCollapsed(i2);
      const source = this.regions.getSource(i2);
      if (isCollapsed || source !== 0) {
        const foldRange = this.c.toFoldRange(i2);
        const decRange = this.a.getDecorationRange(this.d[i2]);
        if (decRange) {
          if (isCollapsed && selection?.startsInside(decRange.startLineNumber + 1, decRange.endLineNumber)) {
            isCollapsed = false;
          }
          foldedRanges.push({
            startLineNumber: decRange.startLineNumber,
            endLineNumber: decRange.endLineNumber,
            type: foldRange.type,
            isCollapsed,
            source
          });
        }
      }
    }
    return foldedRanges;
  }
  /**
   * Collapse state memento, for persistence only
   */
  getMemento() {
    const foldedOrManualRanges = this.f();
    const result = [];
    const maxLineNumber = this.a.getLineCount();
    for (let i2 = 0, limit = foldedOrManualRanges.length; i2 < limit; i2++) {
      const range = foldedOrManualRanges[i2];
      if (range.startLineNumber >= range.endLineNumber || range.startLineNumber < 1 || range.endLineNumber > maxLineNumber) {
        continue;
      }
      const checksum = this.g(range.startLineNumber + 1, range.endLineNumber);
      result.push({
        startLineNumber: range.startLineNumber,
        endLineNumber: range.endLineNumber,
        isCollapsed: range.isCollapsed,
        source: range.source,
        checksum
      });
    }
    return result.length > 0 ? result : void 0;
  }
  /**
   * Apply persisted state, for persistence only
   */
  applyMemento(state) {
    if (!Array.isArray(state)) {
      return;
    }
    const rangesToRestore = [];
    const maxLineNumber = this.a.getLineCount();
    for (const range of state) {
      if (range.startLineNumber >= range.endLineNumber || range.startLineNumber < 1 || range.endLineNumber > maxLineNumber) {
        continue;
      }
      const checksum = this.g(range.startLineNumber + 1, range.endLineNumber);
      if (!range.checksum || checksum === range.checksum) {
        rangesToRestore.push({
          startLineNumber: range.startLineNumber,
          endLineNumber: range.endLineNumber,
          type: void 0,
          isCollapsed: range.isCollapsed ?? true,
          source: range.source ?? 0
          /* FoldSource.provider */
        });
      }
    }
    const newRanges = $Jgb.sanitizeAndMerge(this.c, rangesToRestore, maxLineNumber);
    this.updatePost($Jgb.fromFoldRanges(newRanges));
  }
  g(lineNumber1, lineNumber2) {
    const h3 = $Xi(this.a.getLineContent(lineNumber1) + this.a.getLineContent(lineNumber2));
    return h3 % 1e6;
  }
  dispose() {
    this.b.removeDecorations(this.d);
  }
  getAllRegionsAtLine(lineNumber, filter) {
    const result = [];
    if (this.c) {
      let index = this.c.findRange(lineNumber);
      let level = 1;
      while (index >= 0) {
        const current = this.c.toRegion(index);
        if (!filter || filter(current, level)) {
          result.push(current);
        }
        level++;
        index = current.parentIndex;
      }
    }
    return result;
  }
  getRegionAtLine(lineNumber) {
    if (this.c) {
      const index = this.c.findRange(lineNumber);
      if (index >= 0) {
        return this.c.toRegion(index);
      }
    }
    return null;
  }
  getRegionsInside(region, filter) {
    const result = [];
    const index = region ? region.regionIndex + 1 : 0;
    const endLineNumber = region ? region.endLineNumber : Number.MAX_VALUE;
    if (filter && filter.length === 2) {
      const levelStack = [];
      for (let i2 = index, len = this.c.length; i2 < len; i2++) {
        const current = this.c.toRegion(i2);
        if (this.c.getStartLineNumber(i2) < endLineNumber) {
          while (levelStack.length > 0 && !current.containedBy(levelStack[levelStack.length - 1])) {
            levelStack.pop();
          }
          levelStack.push(current);
          if (filter(current, levelStack.length)) {
            result.push(current);
          }
        } else {
          break;
        }
      }
    } else {
      for (let i2 = index, len = this.c.length; i2 < len; i2++) {
        const current = this.c.toRegion(i2);
        if (this.c.getStartLineNumber(i2) < endLineNumber) {
          if (!filter || filter(current)) {
            result.push(current);
          }
        } else {
          break;
        }
      }
    }
    return result;
  }
};
function $Mgb(foldingModel, levels, lineNumbers) {
  const toToggle = [];
  for (const lineNumber of lineNumbers) {
    const region = foldingModel.getRegionAtLine(lineNumber);
    if (region) {
      const doCollapse = !region.isCollapsed;
      toToggle.push(region);
      if (levels > 1) {
        const regionsInside = foldingModel.getRegionsInside(region, (r2, level) => r2.isCollapsed !== doCollapse && level < levels);
        toToggle.push(...regionsInside);
      }
    }
  }
  foldingModel.toggleCollapseState(toToggle);
}
function $Ngb(foldingModel, doCollapse, levels = Number.MAX_VALUE, lineNumbers) {
  const toToggle = [];
  if (lineNumbers && lineNumbers.length > 0) {
    for (const lineNumber of lineNumbers) {
      const region = foldingModel.getRegionAtLine(lineNumber);
      if (region) {
        if (region.isCollapsed !== doCollapse) {
          toToggle.push(region);
        }
        if (levels > 1) {
          const regionsInside = foldingModel.getRegionsInside(region, (r2, level) => r2.isCollapsed !== doCollapse && level < levels);
          toToggle.push(...regionsInside);
        }
      }
    }
  } else {
    const regionsInside = foldingModel.getRegionsInside(null, (r2, level) => r2.isCollapsed !== doCollapse && level < levels);
    toToggle.push(...regionsInside);
  }
  foldingModel.toggleCollapseState(toToggle);
}
function $Ogb(foldingModel, doCollapse, levels, lineNumbers) {
  const toToggle = [];
  for (const lineNumber of lineNumbers) {
    const regions = foldingModel.getAllRegionsAtLine(lineNumber, (region, level) => region.isCollapsed !== doCollapse && level <= levels);
    toToggle.push(...regions);
  }
  foldingModel.toggleCollapseState(toToggle);
}
function $Pgb(foldingModel, doCollapse, lineNumbers) {
  const toToggle = [];
  for (const lineNumber of lineNumbers) {
    const regions = foldingModel.getAllRegionsAtLine(lineNumber, (region) => region.isCollapsed !== doCollapse);
    if (regions.length > 0) {
      toToggle.push(regions[0]);
    }
  }
  foldingModel.toggleCollapseState(toToggle);
}
function $Qgb(foldingModel, foldLevel, doCollapse, blockedLineNumbers) {
  const filter = (region, level) => level === foldLevel && region.isCollapsed !== doCollapse && !blockedLineNumbers.some((line) => region.containsLine(line));
  const toToggle = foldingModel.getRegionsInside(null, filter);
  foldingModel.toggleCollapseState(toToggle);
}
function $Rgb(foldingModel, doCollapse, blockedLineNumbers) {
  const filteredRegions = [];
  for (const lineNumber of blockedLineNumbers) {
    const regions = foldingModel.getAllRegionsAtLine(lineNumber, void 0);
    if (regions.length > 0) {
      filteredRegions.push(regions[0]);
    }
  }
  const filter = (region) => filteredRegions.every((filteredRegion) => !filteredRegion.containedBy(region) && !region.containedBy(filteredRegion)) && region.isCollapsed !== doCollapse;
  const toToggle = foldingModel.getRegionsInside(null, filter);
  foldingModel.toggleCollapseState(toToggle);
}
function $Sgb(foldingModel, regExp, doCollapse) {
  const editorModel = foldingModel.textModel;
  const regions = foldingModel.regions;
  const toToggle = [];
  for (let i2 = regions.length - 1; i2 >= 0; i2--) {
    if (doCollapse !== regions.isCollapsed(i2)) {
      const startLineNumber = regions.getStartLineNumber(i2);
      if (regExp.test(editorModel.getLineContent(startLineNumber))) {
        toToggle.push(regions.toRegion(i2));
      }
    }
  }
  foldingModel.toggleCollapseState(toToggle);
}
function $Tgb(foldingModel, type, doCollapse) {
  const regions = foldingModel.regions;
  const toToggle = [];
  for (let i2 = regions.length - 1; i2 >= 0; i2--) {
    if (doCollapse !== regions.isCollapsed(i2) && type === regions.getType(i2)) {
      toToggle.push(regions.toRegion(i2));
    }
  }
  foldingModel.toggleCollapseState(toToggle);
}
function $Ugb(lineNumber, foldingModel) {
  let startLineNumber = null;
  const foldingRegion = foldingModel.getRegionAtLine(lineNumber);
  if (foldingRegion !== null) {
    startLineNumber = foldingRegion.startLineNumber;
    if (lineNumber === startLineNumber) {
      const parentFoldingIdx = foldingRegion.parentIndex;
      if (parentFoldingIdx !== -1) {
        startLineNumber = foldingModel.regions.getStartLineNumber(parentFoldingIdx);
      } else {
        startLineNumber = null;
      }
    }
  }
  return startLineNumber;
}
function $Vgb(lineNumber, foldingModel) {
  let foldingRegion = foldingModel.getRegionAtLine(lineNumber);
  if (foldingRegion !== null && foldingRegion.startLineNumber === lineNumber) {
    if (lineNumber !== foldingRegion.startLineNumber) {
      return foldingRegion.startLineNumber;
    } else {
      const expectedParentIndex = foldingRegion.parentIndex;
      let minLineNumber = 0;
      if (expectedParentIndex !== -1) {
        minLineNumber = foldingModel.regions.getStartLineNumber(foldingRegion.parentIndex);
      }
      while (foldingRegion !== null) {
        if (foldingRegion.regionIndex > 0) {
          foldingRegion = foldingModel.regions.toRegion(foldingRegion.regionIndex - 1);
          if (foldingRegion.startLineNumber <= minLineNumber) {
            return null;
          } else if (foldingRegion.parentIndex === expectedParentIndex) {
            return foldingRegion.startLineNumber;
          }
        } else {
          return null;
        }
      }
    }
  } else {
    if (foldingModel.regions.length > 0) {
      foldingRegion = foldingModel.regions.toRegion(foldingModel.regions.length - 1);
      while (foldingRegion !== null) {
        if (foldingRegion.startLineNumber < lineNumber) {
          return foldingRegion.startLineNumber;
        }
        if (foldingRegion.regionIndex > 0) {
          foldingRegion = foldingModel.regions.toRegion(foldingRegion.regionIndex - 1);
        } else {
          foldingRegion = null;
        }
      }
    }
  }
  return null;
}
function $Wgb(lineNumber, foldingModel) {
  let foldingRegion = foldingModel.getRegionAtLine(lineNumber);
  if (foldingRegion !== null && foldingRegion.startLineNumber === lineNumber) {
    const expectedParentIndex = foldingRegion.parentIndex;
    let maxLineNumber = 0;
    if (expectedParentIndex !== -1) {
      maxLineNumber = foldingModel.regions.getEndLineNumber(foldingRegion.parentIndex);
    } else if (foldingModel.regions.length === 0) {
      return null;
    } else {
      maxLineNumber = foldingModel.regions.getEndLineNumber(foldingModel.regions.length - 1);
    }
    while (foldingRegion !== null) {
      if (foldingRegion.regionIndex < foldingModel.regions.length) {
        foldingRegion = foldingModel.regions.toRegion(foldingRegion.regionIndex + 1);
        if (foldingRegion.startLineNumber >= maxLineNumber) {
          return null;
        } else if (foldingRegion.parentIndex === expectedParentIndex) {
          return foldingRegion.startLineNumber;
        }
      } else {
        return null;
      }
    }
  } else {
    if (foldingModel.regions.length > 0) {
      foldingRegion = foldingModel.regions.toRegion(0);
      while (foldingRegion !== null) {
        if (foldingRegion.startLineNumber > lineNumber) {
          return foldingRegion.startLineNumber;
        }
        if (foldingRegion.regionIndex < foldingModel.regions.length) {
          foldingRegion = foldingModel.regions.toRegion(foldingRegion.regionIndex + 1);
        } else {
          foldingRegion = null;
        }
      }
    }
  }
  return null;
}

// out-build/vs/editor/contrib/folding/browser/hiddenRangeModel.js
var $Xgb = class {
  get onDidChange() {
    return this.d.event;
  }
  get hiddenRanges() {
    return this.b;
  }
  constructor(model) {
    this.d = new $ze();
    this.f = false;
    this.a = model;
    this.c = model.onDidChange((_) => this.g());
    this.b = [];
    if (model.regions.length) {
      this.g();
    }
  }
  notifyChangeModelContent(e) {
    if (this.b.length && !this.f) {
      this.f = e.changes.some((change) => {
        return change.range.endLineNumber !== change.range.startLineNumber || $tE(change.text)[0] !== 0;
      });
    }
  }
  g() {
    let updateHiddenAreas = false;
    const newHiddenAreas = [];
    let i2 = 0;
    let k = 0;
    let lastCollapsedStart = Number.MAX_VALUE;
    let lastCollapsedEnd = -1;
    const ranges = this.a.regions;
    for (; i2 < ranges.length; i2++) {
      if (!ranges.isCollapsed(i2)) {
        continue;
      }
      const startLineNumber = ranges.getStartLineNumber(i2) + 1;
      const endLineNumber = ranges.getEndLineNumber(i2);
      if (lastCollapsedStart <= startLineNumber && endLineNumber <= lastCollapsedEnd) {
        continue;
      }
      if (!updateHiddenAreas && k < this.b.length && this.b[k].startLineNumber === startLineNumber && this.b[k].endLineNumber === endLineNumber) {
        newHiddenAreas.push(this.b[k]);
        k++;
      } else {
        updateHiddenAreas = true;
        newHiddenAreas.push(new $9C(startLineNumber, 1, endLineNumber, 1));
      }
      lastCollapsedStart = startLineNumber;
      lastCollapsedEnd = endLineNumber;
    }
    if (this.f || updateHiddenAreas || k < this.b.length) {
      this.h(newHiddenAreas);
    }
  }
  h(newHiddenAreas) {
    this.b = newHiddenAreas;
    this.f = false;
    this.d.fire(newHiddenAreas);
  }
  hasRanges() {
    return this.b.length > 0;
  }
  isHidden(line) {
    return findRange(this.b, line) !== null;
  }
  adjustSelections(selections) {
    let hasChanges = false;
    const editorModel = this.a.textModel;
    let lastRange = null;
    const adjustLine = (line) => {
      if (!lastRange || !isInside(line, lastRange)) {
        lastRange = findRange(this.b, line);
      }
      if (lastRange) {
        return lastRange.startLineNumber - 1;
      }
      return null;
    };
    for (let i2 = 0, len = selections.length; i2 < len; i2++) {
      let selection = selections[i2];
      const adjustedStartLine = adjustLine(selection.startLineNumber);
      if (adjustedStartLine) {
        selection = selection.setStartPosition(adjustedStartLine, editorModel.getLineMaxColumn(adjustedStartLine));
        hasChanges = true;
      }
      const adjustedEndLine = adjustLine(selection.endLineNumber);
      if (adjustedEndLine) {
        selection = selection.setEndPosition(adjustedEndLine, editorModel.getLineMaxColumn(adjustedEndLine));
        hasChanges = true;
      }
      selections[i2] = selection;
    }
    return hasChanges;
  }
  dispose() {
    if (this.hiddenRanges.length > 0) {
      this.b = [];
      this.d.fire(this.b);
    }
    if (this.c) {
      this.c.dispose();
      this.c = null;
    }
  }
};
function isInside(line, range) {
  return line >= range.startLineNumber && line <= range.endLineNumber;
}
function findRange(ranges, line) {
  const i2 = $6(ranges, (r2) => line < r2.startLineNumber) - 1;
  if (i2 >= 0 && ranges[i2].endLineNumber >= line) {
    return ranges[i2];
  }
  return null;
}

// out-build/vs/editor/contrib/folding/browser/indentRangeProvider.js
var MAX_FOLDING_REGIONS_FOR_INDENT_DEFAULT = 5e3;
var ID_INDENT_PROVIDER = "indent";
var $Ygb = class {
  constructor(a, b, c) {
    this.a = a;
    this.b = b;
    this.c = c;
    this.id = ID_INDENT_PROVIDER;
  }
  dispose() {
  }
  compute(cancelationToken) {
    const foldingRules = this.b.getLanguageConfiguration(this.a.getLanguageId()).foldingRules;
    const offSide = foldingRules && !!foldingRules.offSide;
    const markers = foldingRules && foldingRules.markers;
    return Promise.resolve($1gb(this.a, offSide, markers, this.c));
  }
};
var $Zgb = class {
  constructor(foldingRangesLimit) {
    this.a = [];
    this.b = [];
    this.c = [];
    this.d = 0;
    this.e = foldingRangesLimit;
  }
  insertFirst(startLineNumber, endLineNumber, indent) {
    if (startLineNumber > $Igb || endLineNumber > $Igb) {
      return;
    }
    const index = this.d;
    this.a[index] = startLineNumber;
    this.b[index] = endLineNumber;
    this.d++;
    if (indent < 1e3) {
      this.c[indent] = (this.c[indent] || 0) + 1;
    }
  }
  toIndentRanges(model) {
    const limit = this.e.limit;
    if (this.d <= limit) {
      this.e.update(this.d, false);
      const startIndexes = new Uint32Array(this.d);
      const endIndexes = new Uint32Array(this.d);
      for (let i2 = this.d - 1, k = 0; i2 >= 0; i2--, k++) {
        startIndexes[k] = this.a[i2];
        endIndexes[k] = this.b[i2];
      }
      return new $Jgb(startIndexes, endIndexes);
    } else {
      this.e.update(this.d, limit);
      let entries2 = 0;
      let maxIndent = this.c.length;
      for (let i2 = 0; i2 < this.c.length; i2++) {
        const n = this.c[i2];
        if (n) {
          if (n + entries2 > limit) {
            maxIndent = i2;
            break;
          }
          entries2 += n;
        }
      }
      const tabSize = model.getOptions().tabSize;
      const startIndexes = new Uint32Array(limit);
      const endIndexes = new Uint32Array(limit);
      for (let i2 = this.d - 1, k = 0; i2 >= 0; i2--) {
        const startIndex = this.a[i2];
        const lineContent = model.getLineContent(startIndex);
        const indent = $VH(lineContent, tabSize);
        if (indent < maxIndent || indent === maxIndent && entries2++ < limit) {
          startIndexes[k] = startIndex;
          endIndexes[k] = this.b[i2];
          k++;
        }
      }
      return new $Jgb(startIndexes, endIndexes);
    }
  }
};
var foldingRangesLimitDefault = {
  limit: MAX_FOLDING_REGIONS_FOR_INDENT_DEFAULT,
  update: () => {
  }
};
function $1gb(model, offSide, markers, foldingRangesLimit = foldingRangesLimitDefault) {
  const tabSize = model.getOptions().tabSize;
  const result = new $Zgb(foldingRangesLimit);
  let pattern = void 0;
  if (markers) {
    pattern = new RegExp(`(${markers.start.source})|(?:${markers.end.source})`);
  }
  const previousRegions = [];
  const line = model.getLineCount() + 1;
  previousRegions.push({ indent: -1, endAbove: line, line });
  for (let line2 = model.getLineCount(); line2 > 0; line2--) {
    const lineContent = model.getLineContent(line2);
    const indent = $VH(lineContent, tabSize);
    let previous = previousRegions[previousRegions.length - 1];
    if (indent === -1) {
      if (offSide) {
        previous.endAbove = line2;
      }
      continue;
    }
    let m;
    if (pattern && (m = lineContent.match(pattern))) {
      if (m[1]) {
        let i2 = previousRegions.length - 1;
        while (i2 > 0 && previousRegions[i2].indent !== -2) {
          i2--;
        }
        if (i2 > 0) {
          previousRegions.length = i2 + 1;
          previous = previousRegions[i2];
          result.insertFirst(line2, previous.line, indent);
          previous.line = line2;
          previous.indent = indent;
          previous.endAbove = line2;
          continue;
        } else {
        }
      } else {
        previousRegions.push({ indent: -2, endAbove: line2, line: line2 });
        continue;
      }
    }
    if (previous.indent > indent) {
      do {
        previousRegions.pop();
        previous = previousRegions[previousRegions.length - 1];
      } while (previous.indent > indent);
      const endLineNumber = previous.endAbove - 1;
      if (endLineNumber - line2 >= 1) {
        result.insertFirst(line2, endLineNumber, indent);
      }
    }
    if (previous.indent === indent) {
      previous.endAbove = line2;
    } else {
      previousRegions.push({ indent, endAbove: line2, line: line2 });
    }
  }
  return result.toIndentRanges(model);
}

// out-build/vs/editor/contrib/folding/browser/foldingDecorations.js
var foldBackground = $5n("editor.foldBackground", { light: $0n($7o, 0.3), dark: $0n($7o, 0.3), hcDark: null, hcLight: null }, localize(1078, null), true);
$5n("editor.foldPlaceholderForeground", { light: "#808080", dark: "#808080", hcDark: null, hcLight: null }, localize(1079, null));
$5n("editorGutter.foldingControlForeground", $io, localize(1080, null));
var $2gb = $9r("folding-expanded", $6l.chevronDown, localize(1081, null));
var $3gb = $9r("folding-collapsed", $6l.chevronRight, localize(1082, null));
var $4gb = $9r("folding-manual-collapsed", $3gb, localize(1083, null));
var $5gb = $9r("folding-manual-expanded", $2gb, localize(1084, null));
var foldedBackgroundMinimap = {
  color: $hs(foldBackground),
  position: 1
  /* MinimapPosition.Inline */
};
var collapsed = localize(1085, null);
var expanded = localize(1086, null);
var $6gb = class _$6gb {
  static {
    this.a = $WI.register({
      description: "folding-collapsed-visual-decoration",
      stickiness: 0,
      afterContentClassName: "inline-folded",
      isWholeLine: true,
      linesDecorationsTooltip: collapsed,
      firstLineDecorationClassName: ThemeIcon.asClassName($3gb)
    });
  }
  static {
    this.b = $WI.register({
      description: "folding-collapsed-highlighted-visual-decoration",
      stickiness: 0,
      afterContentClassName: "inline-folded",
      className: "folded-background",
      minimap: foldedBackgroundMinimap,
      isWholeLine: true,
      linesDecorationsTooltip: collapsed,
      firstLineDecorationClassName: ThemeIcon.asClassName($3gb)
    });
  }
  static {
    this.c = $WI.register({
      description: "folding-manually-collapsed-visual-decoration",
      stickiness: 0,
      afterContentClassName: "inline-folded",
      isWholeLine: true,
      linesDecorationsTooltip: collapsed,
      firstLineDecorationClassName: ThemeIcon.asClassName($4gb)
    });
  }
  static {
    this.d = $WI.register({
      description: "folding-manually-collapsed-highlighted-visual-decoration",
      stickiness: 0,
      afterContentClassName: "inline-folded",
      className: "folded-background",
      minimap: foldedBackgroundMinimap,
      isWholeLine: true,
      linesDecorationsTooltip: collapsed,
      firstLineDecorationClassName: ThemeIcon.asClassName($4gb)
    });
  }
  static {
    this.e = $WI.register({
      description: "folding-no-controls-range-decoration",
      stickiness: 0,
      afterContentClassName: "inline-folded",
      isWholeLine: true,
      linesDecorationsTooltip: collapsed
    });
  }
  static {
    this.f = $WI.register({
      description: "folding-no-controls-range-decoration",
      stickiness: 0,
      afterContentClassName: "inline-folded",
      className: "folded-background",
      minimap: foldedBackgroundMinimap,
      isWholeLine: true,
      linesDecorationsTooltip: collapsed
    });
  }
  static {
    this.g = $WI.register({
      description: "folding-expanded-visual-decoration",
      stickiness: 1,
      isWholeLine: true,
      firstLineDecorationClassName: "alwaysShowFoldIcons " + ThemeIcon.asClassName($2gb),
      linesDecorationsTooltip: expanded
    });
  }
  static {
    this.h = $WI.register({
      description: "folding-expanded-auto-hide-visual-decoration",
      stickiness: 1,
      isWholeLine: true,
      firstLineDecorationClassName: ThemeIcon.asClassName($2gb),
      linesDecorationsTooltip: expanded
    });
  }
  static {
    this.i = $WI.register({
      description: "folding-manually-expanded-visual-decoration",
      stickiness: 0,
      isWholeLine: true,
      firstLineDecorationClassName: "alwaysShowFoldIcons " + ThemeIcon.asClassName($5gb),
      linesDecorationsTooltip: expanded
    });
  }
  static {
    this.j = $WI.register({
      description: "folding-manually-expanded-auto-hide-visual-decoration",
      stickiness: 0,
      isWholeLine: true,
      firstLineDecorationClassName: ThemeIcon.asClassName($5gb),
      linesDecorationsTooltip: expanded
    });
  }
  static {
    this.k = $WI.register({
      description: "folding-no-controls-range-decoration",
      stickiness: 0,
      isWholeLine: true
    });
  }
  static {
    this.l = $WI.register({
      description: "folding-hidden-range-decoration",
      stickiness: 1
      /* TrackedRangeStickiness.NeverGrowsWhenTypingAtEdges */
    });
  }
  constructor(m) {
    this.m = m;
    this.showFoldingControls = "mouseover";
    this.showFoldingHighlights = true;
  }
  getDecorationOption(isCollapsed, isHidden, isManual) {
    if (isHidden) {
      return _$6gb.l;
    }
    if (this.showFoldingControls === "never") {
      if (isCollapsed) {
        return this.showFoldingHighlights ? _$6gb.f : _$6gb.e;
      }
      return _$6gb.k;
    }
    if (isCollapsed) {
      return isManual ? this.showFoldingHighlights ? _$6gb.d : _$6gb.c : this.showFoldingHighlights ? _$6gb.b : _$6gb.a;
    } else if (this.showFoldingControls === "mouseover") {
      return isManual ? _$6gb.j : _$6gb.h;
    } else {
      return isManual ? _$6gb.i : _$6gb.g;
    }
  }
  changeDecorations(callback) {
    return this.m.changeDecorations(callback);
  }
  removeDecorations(decorationIds) {
    this.m.removeDecorations(decorationIds);
  }
};

// out-build/vs/editor/contrib/folding/browser/syntaxRangeProvider.js
var foldingContext = {};
var ID_SYNTAX_PROVIDER = "syntax";
var $7gb = class {
  constructor(a, b, handleFoldingRangesChange, c, d) {
    this.a = a;
    this.b = b;
    this.handleFoldingRangesChange = handleFoldingRangesChange;
    this.c = c;
    this.d = d;
    this.id = ID_SYNTAX_PROVIDER;
    this.disposables = new $2c();
    if (d) {
      this.disposables.add(d);
    }
    for (const provider of b) {
      if (typeof provider.onDidChange === "function") {
        this.disposables.add(provider.onDidChange(handleFoldingRangesChange));
      }
    }
  }
  compute(cancellationToken) {
    return collectSyntaxRanges(this.b, this.a, cancellationToken).then((ranges) => {
      if (ranges) {
        const res = $8gb(ranges, this.c);
        return res;
      }
      return this.d?.compute(cancellationToken) ?? null;
    });
  }
  dispose() {
    this.disposables.dispose();
  }
};
function collectSyntaxRanges(providers2, model, cancellationToken) {
  let rangeData = null;
  const promises = providers2.map((provider, i2) => {
    return Promise.resolve(provider.provideFoldingRanges(model, foldingContext, cancellationToken)).then((ranges) => {
      if (cancellationToken.isCancellationRequested) {
        return;
      }
      if (Array.isArray(ranges)) {
        if (!Array.isArray(rangeData)) {
          rangeData = [];
        }
        const nLines = model.getLineCount();
        for (const r2 of ranges) {
          if (r2.start > 0 && r2.end > r2.start && r2.end <= nLines) {
            rangeData.push({ start: r2.start, end: r2.end, rank: i2, kind: r2.kind });
          }
        }
      }
    }, $hb);
  });
  return Promise.all(promises).then((_) => {
    return rangeData;
  });
}
var RangesCollector = class {
  constructor(foldingRangesLimit) {
    this.a = [];
    this.b = [];
    this.c = [];
    this.d = [];
    this.e = [];
    this.f = 0;
    this.g = foldingRangesLimit;
  }
  add(startLineNumber, endLineNumber, type, nestingLevel) {
    if (startLineNumber > $Igb || endLineNumber > $Igb) {
      return;
    }
    const index = this.f;
    this.a[index] = startLineNumber;
    this.b[index] = endLineNumber;
    this.c[index] = nestingLevel;
    this.e[index] = type;
    this.f++;
    if (nestingLevel < 30) {
      this.d[nestingLevel] = (this.d[nestingLevel] || 0) + 1;
    }
  }
  toIndentRanges() {
    const limit = this.g.limit;
    if (this.f <= limit) {
      this.g.update(this.f, false);
      const startIndexes = new Uint32Array(this.f);
      const endIndexes = new Uint32Array(this.f);
      for (let i2 = 0; i2 < this.f; i2++) {
        startIndexes[i2] = this.a[i2];
        endIndexes[i2] = this.b[i2];
      }
      return new $Jgb(startIndexes, endIndexes, this.e);
    } else {
      this.g.update(this.f, limit);
      let entries2 = 0;
      let maxLevel = this.d.length;
      for (let i2 = 0; i2 < this.d.length; i2++) {
        const n = this.d[i2];
        if (n) {
          if (n + entries2 > limit) {
            maxLevel = i2;
            break;
          }
          entries2 += n;
        }
      }
      const startIndexes = new Uint32Array(limit);
      const endIndexes = new Uint32Array(limit);
      const types = [];
      for (let i2 = 0, k = 0; i2 < this.f; i2++) {
        const level = this.c[i2];
        if (level < maxLevel || level === maxLevel && entries2++ < limit) {
          startIndexes[k] = this.a[i2];
          endIndexes[k] = this.b[i2];
          types[k] = this.e[i2];
          k++;
        }
      }
      return new $Jgb(startIndexes, endIndexes, types);
    }
  }
};
function $8gb(rangeData, foldingRangesLimit) {
  const sorted = rangeData.sort((d1, d2) => {
    let diff3 = d1.start - d2.start;
    if (diff3 === 0) {
      diff3 = d1.rank - d2.rank;
    }
    return diff3;
  });
  const collector = new RangesCollector(foldingRangesLimit);
  let top2 = void 0;
  const previous = [];
  for (const entry of sorted) {
    if (!top2) {
      top2 = entry;
      collector.add(entry.start, entry.end, entry.kind && entry.kind.value, previous.length);
    } else {
      if (entry.start > top2.start) {
        if (entry.end <= top2.end) {
          previous.push(top2);
          top2 = entry;
          collector.add(entry.start, entry.end, entry.kind && entry.kind.value, previous.length);
        } else {
          if (entry.start > top2.end) {
            do {
              top2 = previous.pop();
            } while (top2 && entry.start > top2.end);
            if (top2) {
              previous.push(top2);
            }
            top2 = entry;
          }
          collector.add(entry.start, entry.end, entry.kind && entry.kind.value, previous.length);
        }
      }
    }
  }
  return collector.toIndentRanges();
}

// out-build/vs/editor/contrib/folding/browser/folding.js
var $9gb_1;
var CONTEXT_FOLDING_ENABLED = new $nn("foldingEnabled", false);
var $9gb = class $9gb2 extends $3c {
  static {
    $9gb_1 = this;
  }
  static {
    this.ID = "editor.contrib.folding";
  }
  static get(editor) {
    return editor.getContribution($9gb_1.ID);
  }
  static getFoldingRangeProviders(languageFeaturesService, model) {
    const foldingRangeProviders = languageFeaturesService.foldingRangeProvider.ordered(model);
    return $9gb_1.c?.(foldingRangeProviders, model) ?? foldingRangeProviders;
  }
  static setFoldingRangeProviderSelector(foldingRangeSelector) {
    $9gb_1.c = foldingRangeSelector;
    return { dispose: () => {
      $9gb_1.c = void 0;
    } };
  }
  constructor(editor, M, N, notificationService, languageFeatureDebounceService, O) {
    super();
    this.M = M;
    this.N = N;
    this.O = O;
    this.J = this.B(new $2c());
    this.f = editor;
    this._foldingLimitReporter = new $0gb(editor);
    const options3 = this.f.getOptions();
    this.g = options3.get(
      45
      /* EditorOption.folding */
    );
    this.h = options3.get(
      46
      /* EditorOption.foldingStrategy */
    ) !== "indentation";
    this.j = options3.get(
      50
      /* EditorOption.unfoldOnClickAfterEndOfLine */
    );
    this.m = false;
    this.t = false;
    this.n = options3.get(
      48
      /* EditorOption.foldingImportsByDefault */
    );
    this.G = languageFeatureDebounceService.for(O.foldingRangeProvider, "Folding", { min: 200 });
    this.w = null;
    this.y = null;
    this.z = null;
    this.C = null;
    this.D = null;
    this.F = null;
    this.I = null;
    this.L = null;
    this.u = new $6gb(editor);
    this.u.showFoldingControls = options3.get(
      115
      /* EditorOption.showFoldingControls */
    );
    this.u.showFoldingHighlights = options3.get(
      47
      /* EditorOption.foldingHighlight */
    );
    this.H = CONTEXT_FOLDING_ENABLED.bindTo(this.M);
    this.H.set(this.g);
    this.B(this.f.onDidChangeModel(() => this.P()));
    this.B(this.f.onDidChangeConfiguration((e) => {
      if (e.hasChanged(
        45
        /* EditorOption.folding */
      )) {
        this.g = this.f.getOptions().get(
          45
          /* EditorOption.folding */
        );
        this.H.set(this.g);
        this.P();
      }
      if (e.hasChanged(
        49
        /* EditorOption.foldingMaximumRegions */
      )) {
        this.P();
      }
      if (e.hasChanged(
        115
        /* EditorOption.showFoldingControls */
      ) || e.hasChanged(
        47
        /* EditorOption.foldingHighlight */
      )) {
        const options4 = this.f.getOptions();
        this.u.showFoldingControls = options4.get(
          115
          /* EditorOption.showFoldingControls */
        );
        this.u.showFoldingHighlights = options4.get(
          47
          /* EditorOption.foldingHighlight */
        );
        this.triggerFoldingModelChanged();
      }
      if (e.hasChanged(
        46
        /* EditorOption.foldingStrategy */
      )) {
        this.h = this.f.getOptions().get(
          46
          /* EditorOption.foldingStrategy */
        ) !== "indentation";
        this.Q();
      }
      if (e.hasChanged(
        50
        /* EditorOption.unfoldOnClickAfterEndOfLine */
      )) {
        this.j = this.f.getOptions().get(
          50
          /* EditorOption.unfoldOnClickAfterEndOfLine */
        );
      }
      if (e.hasChanged(
        48
        /* EditorOption.foldingImportsByDefault */
      )) {
        this.n = this.f.getOptions().get(
          48
          /* EditorOption.foldingImportsByDefault */
        );
      }
    }));
    this.P();
  }
  get limitReporter() {
    return this._foldingLimitReporter;
  }
  /**
   * Store view state.
   */
  saveViewState() {
    const model = this.f.getModel();
    if (!model || !this.g || model.isTooLargeForTokenization()) {
      return {};
    }
    if (this.w) {
      const collapsedRegions = this.w.getMemento();
      const provider = this.z ? this.z.id : void 0;
      return { collapsedRegions, lineCount: model.getLineCount(), provider, foldedImports: this.t };
    }
    return void 0;
  }
  /**
   * Restore view state.
   */
  restoreViewState(state) {
    const model = this.f.getModel();
    if (!model || !this.g || model.isTooLargeForTokenization() || !this.y) {
      return;
    }
    if (!state) {
      return;
    }
    this.t = !!state.foldedImports;
    if (state.collapsedRegions && state.collapsedRegions.length > 0 && this.w) {
      this.m = true;
      try {
        this.w.applyMemento(state.collapsedRegions);
      } finally {
        this.m = false;
      }
    }
  }
  P() {
    this.J.clear();
    const model = this.f.getModel();
    if (!this.g || !model || model.isTooLargeForTokenization()) {
      return;
    }
    this.t = false;
    this.w = new $Lgb(model, this.u);
    this.J.add(this.w);
    this.y = new $Xgb(this.w);
    this.J.add(this.y);
    this.J.add(this.y.onDidChange((hr2) => this.U(hr2)));
    this.F = new $Sh(this.G.get(model));
    this.I = new $8h(() => this.X(), 200);
    this.J.add(this.I);
    this.J.add(this.O.foldingRangeProvider.onDidChange(() => this.Q()));
    this.J.add(this.f.onDidChangeModelLanguageConfiguration(() => this.Q()));
    this.J.add(this.f.onDidChangeModelContent((e) => this.S(e)));
    this.J.add(this.f.onDidChangeCursorPosition(() => this.W()));
    this.J.add(this.f.onMouseDown((e) => this.Y(e)));
    this.J.add(this.f.onMouseUp((e) => this.Z(e)));
    this.J.add({
      dispose: () => {
        if (this.C) {
          this.C.cancel();
          this.C = null;
        }
        this.F?.cancel();
        this.F = null;
        this.w = null;
        this.D = null;
        this.y = null;
        this.I = null;
        this.z?.dispose();
        this.z = null;
      }
    });
    this.triggerFoldingModelChanged();
  }
  Q() {
    this.z?.dispose();
    this.z = null;
    this.triggerFoldingModelChanged();
  }
  R(editorModel) {
    if (this.z) {
      return this.z;
    }
    const indentRangeProvider = new $Ygb(editorModel, this.N, this._foldingLimitReporter);
    this.z = indentRangeProvider;
    if (this.h && this.w) {
      const selectedProviders = $9gb_1.getFoldingRangeProviders(this.O, editorModel);
      if (selectedProviders.length > 0) {
        this.z = new $7gb(editorModel, selectedProviders, () => this.triggerFoldingModelChanged(), this._foldingLimitReporter, indentRangeProvider);
      }
    }
    return this.z;
  }
  getFoldingModel() {
    return this.D;
  }
  S(e) {
    this.y?.notifyChangeModelContent(e);
    this.triggerFoldingModelChanged();
  }
  triggerFoldingModelChanged() {
    if (this.F) {
      if (this.C) {
        this.C.cancel();
        this.C = null;
      }
      this.D = this.F.trigger(() => {
        const foldingModel = this.w;
        if (!foldingModel) {
          return null;
        }
        const sw = new $te();
        const provider = this.R(foldingModel.textModel);
        const foldingRegionPromise = this.C = $Hh((token) => provider.compute(token));
        return foldingRegionPromise.then((foldingRanges) => {
          if (foldingRanges && foldingRegionPromise === this.C) {
            let scrollState;
            if (this.n && !this.t) {
              const hasChanges = foldingRanges.setCollapsedAllOfType($WE.Imports.value, true);
              if (hasChanges) {
                scrollState = $O9.capture(this.f);
                this.t = hasChanges;
              }
            }
            const selections = this.f.getSelections();
            foldingModel.update(foldingRanges, $$gb(selections));
            scrollState?.restore(this.f);
            const newValue = this.G.update(foldingModel.textModel, sw.elapsed());
            if (this.F) {
              this.F.defaultDelay = newValue;
            }
          }
          return foldingModel;
        });
      }).then(void 0, (err) => {
        $gb(err);
        return null;
      });
    }
  }
  U(hiddenRanges) {
    if (this.y && hiddenRanges.length && !this.m) {
      const selections = this.f.getSelections();
      if (selections) {
        if (this.y.adjustSelections(selections)) {
          this.f.setSelections(selections);
        }
      }
    }
    this.f.setHiddenAreas(hiddenRanges, this);
  }
  W() {
    if (this.y && this.y.hasRanges()) {
      this.I.schedule();
    }
  }
  X() {
    const foldingModel = this.getFoldingModel();
    if (!foldingModel) {
      return;
    }
    foldingModel.then((foldingModel2) => {
      if (foldingModel2) {
        const selections = this.f.getSelections();
        if (selections && selections.length > 0) {
          const toToggle = [];
          for (const selection of selections) {
            const lineNumber = selection.selectionStartLineNumber;
            if (this.y && this.y.isHidden(lineNumber)) {
              toToggle.push(...foldingModel2.getAllRegionsAtLine(lineNumber, (r2) => r2.isCollapsed && lineNumber > r2.startLineNumber));
            }
          }
          if (toToggle.length) {
            foldingModel2.toggleCollapseState(toToggle);
            this.reveal(selections[0].getPosition());
          }
        }
      }
    }).then(void 0, $gb);
  }
  Y(e) {
    this.L = null;
    if (!this.y || !e.target || !e.target.range) {
      return;
    }
    if (!e.event.leftButton && !e.event.middleButton) {
      return;
    }
    const range = e.target.range;
    let iconClicked = false;
    switch (e.target.type) {
      case 4: {
        const data = e.target.detail;
        const offsetLeftInGutter = e.target.element.offsetLeft;
        const gutterOffsetX = data.offsetX - offsetLeftInGutter;
        if (gutterOffsetX < 4) {
          return;
        }
        iconClicked = true;
        break;
      }
      case 7: {
        if (this.j && this.y.hasRanges()) {
          const data = e.target.detail;
          if (!data.isAfterLines) {
            break;
          }
        }
        return;
      }
      case 6: {
        if (this.y.hasRanges()) {
          const model = this.f.getModel();
          if (model && range.startColumn === model.getLineMaxColumn(range.startLineNumber)) {
            break;
          }
        }
        return;
      }
      default:
        return;
    }
    this.L = { lineNumber: range.startLineNumber, iconClicked };
  }
  Z(e) {
    const foldingModel = this.w;
    if (!foldingModel || !this.L || !e.target) {
      return;
    }
    const lineNumber = this.L.lineNumber;
    const iconClicked = this.L.iconClicked;
    const range = e.target.range;
    if (!range || range.startLineNumber !== lineNumber) {
      return;
    }
    if (iconClicked) {
      if (e.target.type !== 4) {
        return;
      }
    } else {
      const model = this.f.getModel();
      if (!model || range.startColumn !== model.getLineMaxColumn(lineNumber)) {
        return;
      }
    }
    const region = foldingModel.getRegionAtLine(lineNumber);
    if (region && region.startLineNumber === lineNumber) {
      const isCollapsed = region.isCollapsed;
      if (iconClicked || isCollapsed) {
        const surrounding = e.event.altKey;
        let toToggle = [];
        if (surrounding) {
          const filter = (otherRegion) => !otherRegion.containedBy(region) && !region.containedBy(otherRegion);
          const toMaybeToggle = foldingModel.getRegionsInside(null, filter);
          for (const r2 of toMaybeToggle) {
            if (r2.isCollapsed) {
              toToggle.push(r2);
            }
          }
          if (toToggle.length === 0) {
            toToggle = toMaybeToggle;
          }
        } else {
          const recursive = e.event.middleButton || e.event.shiftKey;
          if (recursive) {
            for (const r2 of foldingModel.getRegionsInside(region)) {
              if (r2.isCollapsed === isCollapsed) {
                toToggle.push(r2);
              }
            }
          }
          if (isCollapsed || !recursive || toToggle.length === 0) {
            toToggle.push(region);
          }
        }
        foldingModel.toggleCollapseState(toToggle);
        this.reveal({ lineNumber, column: 1 });
      }
    }
  }
  reveal(position) {
    this.f.revealPositionInCenterIfOutsideViewport(
      position,
      0
      /* ScrollType.Smooth */
    );
  }
};
$9gb = $9gb_1 = __decorate([
  __param(1, $on),
  __param(2, $NF),
  __param(3, $PJ),
  __param(4, $tbb),
  __param(5, $mP)
], $9gb);
var $0gb = class {
  constructor(c) {
    this.c = c;
    this.d = new $ze();
    this.onDidChange = this.d.event;
    this.f = 0;
    this.g = false;
  }
  get limit() {
    return this.c.getOptions().get(
      49
      /* EditorOption.foldingMaximumRegions */
    );
  }
  get computed() {
    return this.f;
  }
  get limited() {
    return this.g;
  }
  update(computed, limited) {
    if (computed !== this.f || limited !== this.g) {
      this.f = computed;
      this.g = limited;
      this.d.fire();
    }
  }
};
var FoldingAction = class extends $Z5 {
  runEditorCommand(accessor, editor, args2) {
    const languageConfigurationService = accessor.get($NF);
    const foldingController = $9gb.get(editor);
    if (!foldingController) {
      return;
    }
    const foldingModelPromise = foldingController.getFoldingModel();
    if (foldingModelPromise) {
      this.u(accessor, editor);
      return foldingModelPromise.then((foldingModel) => {
        if (foldingModel) {
          this.invoke(foldingController, foldingModel, editor, args2, languageConfigurationService);
          const selection = editor.getSelection();
          if (selection) {
            foldingController.reveal(selection.getStartPosition());
          }
        }
      });
    }
  }
  d(editor) {
    const selections = editor.getSelections();
    return selections ? selections.map((s) => s.startLineNumber) : [];
  }
  h(args2, editor) {
    if (args2 && args2.selectionLines) {
      return args2.selectionLines.map((l) => l + 1);
    }
    return this.d(editor);
  }
  run(_accessor, _editor) {
  }
};
function $$gb(selections) {
  if (!selections || selections.length === 0) {
    return {
      startsInside: () => false
    };
  }
  return {
    startsInside(startLine, endLine) {
      for (const s of selections) {
        const line = s.startLineNumber;
        if (line >= startLine && line <= endLine) {
          return true;
        }
      }
      return false;
    }
  };
}
function foldingArgumentsConstraint(args2) {
  if (!$Gg(args2)) {
    if (!$Bg(args2)) {
      return false;
    }
    const foldingArgs = args2;
    if (!$Gg(foldingArgs.levels) && !$Dg(foldingArgs.levels)) {
      return false;
    }
    if (!$Gg(foldingArgs.direction) && !$zg(foldingArgs.direction)) {
      return false;
    }
    if (!$Gg(foldingArgs.selectionLines) && (!Array.isArray(foldingArgs.selectionLines) || !foldingArgs.selectionLines.every($Dg))) {
      return false;
    }
  }
  return true;
}
var UnfoldAction = class extends FoldingAction {
  constructor() {
    super({
      id: "editor.unfold",
      label: localize2(1058, "Unfold"),
      precondition: CONTEXT_FOLDING_ENABLED,
      kbOpts: {
        kbExpr: EditorContextKeys.editorTextFocus,
        primary: 2048 | 1024 | 94,
        mac: {
          primary: 2048 | 512 | 94
          /* KeyCode.BracketRight */
        },
        weight: 100
        /* KeybindingWeight.EditorContrib */
      },
      metadata: {
        description: "Unfold the content in the editor",
        args: [
          {
            name: "Unfold editor argument",
            description: `Property-value pairs that can be passed through this argument:
						* 'levels': Number of levels to unfold. If not set, defaults to 1.
						* 'direction': If 'up', unfold given number of levels up otherwise unfolds down.
						* 'selectionLines': Array of the start lines (0-based) of the editor selections to apply the unfold action to. If not set, the active selection(s) will be used.
						`,
            constraint: foldingArgumentsConstraint,
            schema: {
              "type": "object",
              "properties": {
                "levels": {
                  "type": "number",
                  "default": 1
                },
                "direction": {
                  "type": "string",
                  "enum": ["up", "down"],
                  "default": "down"
                },
                "selectionLines": {
                  "type": "array",
                  "items": {
                    "type": "number"
                  }
                }
              }
            }
          }
        ]
      }
    });
  }
  invoke(_foldingController, foldingModel, editor, args2) {
    const levels = args2 && args2.levels || 1;
    const lineNumbers = this.h(args2, editor);
    if (args2 && args2.direction === "up") {
      $Ogb(foldingModel, false, levels, lineNumbers);
    } else {
      $Ngb(foldingModel, false, levels, lineNumbers);
    }
  }
};
var UnFoldRecursivelyAction = class extends FoldingAction {
  constructor() {
    super({
      id: "editor.unfoldRecursively",
      label: localize2(1059, "Unfold Recursively"),
      precondition: CONTEXT_FOLDING_ENABLED,
      kbOpts: {
        kbExpr: EditorContextKeys.editorTextFocus,
        primary: $$e(
          2048 | 41,
          2048 | 94
          /* KeyCode.BracketRight */
        ),
        weight: 100
        /* KeybindingWeight.EditorContrib */
      }
    });
  }
  invoke(_foldingController, foldingModel, editor, _args) {
    $Ngb(foldingModel, false, Number.MAX_VALUE, this.d(editor));
  }
};
var FoldAction = class extends FoldingAction {
  constructor() {
    super({
      id: "editor.fold",
      label: localize2(1060, "Fold"),
      precondition: CONTEXT_FOLDING_ENABLED,
      kbOpts: {
        kbExpr: EditorContextKeys.editorTextFocus,
        primary: 2048 | 1024 | 92,
        mac: {
          primary: 2048 | 512 | 92
          /* KeyCode.BracketLeft */
        },
        weight: 100
        /* KeybindingWeight.EditorContrib */
      },
      metadata: {
        description: "Fold the content in the editor",
        args: [
          {
            name: "Fold editor argument",
            description: `Property-value pairs that can be passed through this argument:
							* 'levels': Number of levels to fold.
							* 'direction': If 'up', folds given number of levels up otherwise folds down.
							* 'selectionLines': Array of the start lines (0-based) of the editor selections to apply the fold action to. If not set, the active selection(s) will be used.
							If no levels or direction is set, folds the region at the locations or if already collapsed, the first uncollapsed parent instead.
						`,
            constraint: foldingArgumentsConstraint,
            schema: {
              "type": "object",
              "properties": {
                "levels": {
                  "type": "number"
                },
                "direction": {
                  "type": "string",
                  "enum": ["up", "down"]
                },
                "selectionLines": {
                  "type": "array",
                  "items": {
                    "type": "number"
                  }
                }
              }
            }
          }
        ]
      }
    });
  }
  invoke(_foldingController, foldingModel, editor, args2) {
    const lineNumbers = this.h(args2, editor);
    const levels = args2 && args2.levels;
    const direction = args2 && args2.direction;
    if (typeof levels !== "number" && typeof direction !== "string") {
      $Pgb(foldingModel, true, lineNumbers);
    } else {
      if (direction === "up") {
        $Ogb(foldingModel, true, levels || 1, lineNumbers);
      } else {
        $Ngb(foldingModel, true, levels || 1, lineNumbers);
      }
    }
  }
};
var ToggleFoldAction = class extends FoldingAction {
  constructor() {
    super({
      id: "editor.toggleFold",
      label: localize2(1061, "Toggle Fold"),
      precondition: CONTEXT_FOLDING_ENABLED,
      kbOpts: {
        kbExpr: EditorContextKeys.editorTextFocus,
        primary: $$e(
          2048 | 41,
          2048 | 42
          /* KeyCode.KeyL */
        ),
        weight: 100
        /* KeybindingWeight.EditorContrib */
      }
    });
  }
  invoke(_foldingController, foldingModel, editor) {
    const selectedLines = this.d(editor);
    $Mgb(foldingModel, 1, selectedLines);
  }
};
var FoldRecursivelyAction = class extends FoldingAction {
  constructor() {
    super({
      id: "editor.foldRecursively",
      label: localize2(1062, "Fold Recursively"),
      precondition: CONTEXT_FOLDING_ENABLED,
      kbOpts: {
        kbExpr: EditorContextKeys.editorTextFocus,
        primary: $$e(
          2048 | 41,
          2048 | 92
          /* KeyCode.BracketLeft */
        ),
        weight: 100
        /* KeybindingWeight.EditorContrib */
      }
    });
  }
  invoke(_foldingController, foldingModel, editor) {
    const selectedLines = this.d(editor);
    $Ngb(foldingModel, true, Number.MAX_VALUE, selectedLines);
  }
};
var ToggleFoldRecursivelyAction = class extends FoldingAction {
  constructor() {
    super({
      id: "editor.toggleFoldRecursively",
      label: localize2(1063, "Toggle Fold Recursively"),
      precondition: CONTEXT_FOLDING_ENABLED,
      kbOpts: {
        kbExpr: EditorContextKeys.editorTextFocus,
        primary: $$e(
          2048 | 41,
          2048 | 1024 | 42
          /* KeyCode.KeyL */
        ),
        weight: 100
        /* KeybindingWeight.EditorContrib */
      }
    });
  }
  invoke(_foldingController, foldingModel, editor) {
    const selectedLines = this.d(editor);
    $Mgb(foldingModel, Number.MAX_VALUE, selectedLines);
  }
};
var FoldAllBlockCommentsAction = class extends FoldingAction {
  constructor() {
    super({
      id: "editor.foldAllBlockComments",
      label: localize2(1064, "Fold All Block Comments"),
      precondition: CONTEXT_FOLDING_ENABLED,
      kbOpts: {
        kbExpr: EditorContextKeys.editorTextFocus,
        primary: $$e(
          2048 | 41,
          2048 | 90
          /* KeyCode.Slash */
        ),
        weight: 100
        /* KeybindingWeight.EditorContrib */
      }
    });
  }
  invoke(_foldingController, foldingModel, editor, args2, languageConfigurationService) {
    if (foldingModel.regions.hasTypes()) {
      $Tgb(foldingModel, $WE.Comment.value, true);
    } else {
      const editorModel = editor.getModel();
      if (!editorModel) {
        return;
      }
      const comments = languageConfigurationService.getLanguageConfiguration(editorModel.getLanguageId()).comments;
      if (comments && comments.blockCommentStartToken) {
        const regExp = new RegExp("^\\s*" + $Af(comments.blockCommentStartToken));
        $Sgb(foldingModel, regExp, true);
      }
    }
  }
};
var FoldAllRegionsAction = class extends FoldingAction {
  constructor() {
    super({
      id: "editor.foldAllMarkerRegions",
      label: localize2(1065, "Fold All Regions"),
      precondition: CONTEXT_FOLDING_ENABLED,
      kbOpts: {
        kbExpr: EditorContextKeys.editorTextFocus,
        primary: $$e(
          2048 | 41,
          2048 | 29
          /* KeyCode.Digit8 */
        ),
        weight: 100
        /* KeybindingWeight.EditorContrib */
      }
    });
  }
  invoke(_foldingController, foldingModel, editor, args2, languageConfigurationService) {
    if (foldingModel.regions.hasTypes()) {
      $Tgb(foldingModel, $WE.Region.value, true);
    } else {
      const editorModel = editor.getModel();
      if (!editorModel) {
        return;
      }
      const foldingRules = languageConfigurationService.getLanguageConfiguration(editorModel.getLanguageId()).foldingRules;
      if (foldingRules && foldingRules.markers && foldingRules.markers.start) {
        const regExp = new RegExp(foldingRules.markers.start);
        $Sgb(foldingModel, regExp, true);
      }
    }
  }
};
var UnfoldAllRegionsAction = class extends FoldingAction {
  constructor() {
    super({
      id: "editor.unfoldAllMarkerRegions",
      label: localize2(1066, "Unfold All Regions"),
      precondition: CONTEXT_FOLDING_ENABLED,
      kbOpts: {
        kbExpr: EditorContextKeys.editorTextFocus,
        primary: $$e(
          2048 | 41,
          2048 | 30
          /* KeyCode.Digit9 */
        ),
        weight: 100
        /* KeybindingWeight.EditorContrib */
      }
    });
  }
  invoke(_foldingController, foldingModel, editor, args2, languageConfigurationService) {
    if (foldingModel.regions.hasTypes()) {
      $Tgb(foldingModel, $WE.Region.value, false);
    } else {
      const editorModel = editor.getModel();
      if (!editorModel) {
        return;
      }
      const foldingRules = languageConfigurationService.getLanguageConfiguration(editorModel.getLanguageId()).foldingRules;
      if (foldingRules && foldingRules.markers && foldingRules.markers.start) {
        const regExp = new RegExp(foldingRules.markers.start);
        $Sgb(foldingModel, regExp, false);
      }
    }
  }
};
var FoldAllExceptAction = class extends FoldingAction {
  constructor() {
    super({
      id: "editor.foldAllExcept",
      label: localize2(1067, "Fold All Except Selected"),
      precondition: CONTEXT_FOLDING_ENABLED,
      kbOpts: {
        kbExpr: EditorContextKeys.editorTextFocus,
        primary: $$e(
          2048 | 41,
          2048 | 88
          /* KeyCode.Minus */
        ),
        weight: 100
        /* KeybindingWeight.EditorContrib */
      }
    });
  }
  invoke(_foldingController, foldingModel, editor) {
    const selectedLines = this.d(editor);
    $Rgb(foldingModel, true, selectedLines);
  }
};
var UnfoldAllExceptAction = class extends FoldingAction {
  constructor() {
    super({
      id: "editor.unfoldAllExcept",
      label: localize2(1068, "Unfold All Except Selected"),
      precondition: CONTEXT_FOLDING_ENABLED,
      kbOpts: {
        kbExpr: EditorContextKeys.editorTextFocus,
        primary: $$e(
          2048 | 41,
          2048 | 86
          /* KeyCode.Equal */
        ),
        weight: 100
        /* KeybindingWeight.EditorContrib */
      }
    });
  }
  invoke(_foldingController, foldingModel, editor) {
    const selectedLines = this.d(editor);
    $Rgb(foldingModel, false, selectedLines);
  }
};
var FoldAllAction = class extends FoldingAction {
  constructor() {
    super({
      id: "editor.foldAll",
      label: localize2(1069, "Fold All"),
      precondition: CONTEXT_FOLDING_ENABLED,
      kbOpts: {
        kbExpr: EditorContextKeys.editorTextFocus,
        primary: $$e(
          2048 | 41,
          2048 | 21
          /* KeyCode.Digit0 */
        ),
        weight: 100
        /* KeybindingWeight.EditorContrib */
      }
    });
  }
  invoke(_foldingController, foldingModel, _editor) {
    $Ngb(foldingModel, true);
  }
};
var UnfoldAllAction = class extends FoldingAction {
  constructor() {
    super({
      id: "editor.unfoldAll",
      label: localize2(1070, "Unfold All"),
      precondition: CONTEXT_FOLDING_ENABLED,
      kbOpts: {
        kbExpr: EditorContextKeys.editorTextFocus,
        primary: $$e(
          2048 | 41,
          2048 | 40
          /* KeyCode.KeyJ */
        ),
        weight: 100
        /* KeybindingWeight.EditorContrib */
      }
    });
  }
  invoke(_foldingController, foldingModel, _editor) {
    $Ngb(foldingModel, false);
  }
};
var FoldLevelAction = class _FoldLevelAction extends FoldingAction {
  static {
    this.j = "editor.foldLevel";
  }
  static {
    this.ID = (level) => _FoldLevelAction.j + level;
  }
  k() {
    return parseInt(this.id.substr(_FoldLevelAction.j.length));
  }
  invoke(_foldingController, foldingModel, editor) {
    $Qgb(foldingModel, this.k(), true, this.d(editor));
  }
};
var GotoParentFoldAction = class extends FoldingAction {
  constructor() {
    super({
      id: "editor.gotoParentFold",
      label: localize2(1071, "Go to Parent Fold"),
      precondition: CONTEXT_FOLDING_ENABLED,
      kbOpts: {
        kbExpr: EditorContextKeys.editorTextFocus,
        weight: 100
        /* KeybindingWeight.EditorContrib */
      }
    });
  }
  invoke(_foldingController, foldingModel, editor) {
    const selectedLines = this.d(editor);
    if (selectedLines.length > 0) {
      const startLineNumber = $Ugb(selectedLines[0], foldingModel);
      if (startLineNumber !== null) {
        editor.setSelection({
          startLineNumber,
          startColumn: 1,
          endLineNumber: startLineNumber,
          endColumn: 1
        });
      }
    }
  }
};
var GotoPreviousFoldAction = class extends FoldingAction {
  constructor() {
    super({
      id: "editor.gotoPreviousFold",
      label: localize2(1072, "Go to Previous Folding Range"),
      precondition: CONTEXT_FOLDING_ENABLED,
      kbOpts: {
        kbExpr: EditorContextKeys.editorTextFocus,
        weight: 100
        /* KeybindingWeight.EditorContrib */
      }
    });
  }
  invoke(_foldingController, foldingModel, editor) {
    const selectedLines = this.d(editor);
    if (selectedLines.length > 0) {
      const startLineNumber = $Vgb(selectedLines[0], foldingModel);
      if (startLineNumber !== null) {
        editor.setSelection({
          startLineNumber,
          startColumn: 1,
          endLineNumber: startLineNumber,
          endColumn: 1
        });
      }
    }
  }
};
var GotoNextFoldAction = class extends FoldingAction {
  constructor() {
    super({
      id: "editor.gotoNextFold",
      label: localize2(1073, "Go to Next Folding Range"),
      precondition: CONTEXT_FOLDING_ENABLED,
      kbOpts: {
        kbExpr: EditorContextKeys.editorTextFocus,
        weight: 100
        /* KeybindingWeight.EditorContrib */
      }
    });
  }
  invoke(_foldingController, foldingModel, editor) {
    const selectedLines = this.d(editor);
    if (selectedLines.length > 0) {
      const startLineNumber = $Wgb(selectedLines[0], foldingModel);
      if (startLineNumber !== null) {
        editor.setSelection({
          startLineNumber,
          startColumn: 1,
          endLineNumber: startLineNumber,
          endColumn: 1
        });
      }
    }
  }
};
var FoldRangeFromSelectionAction = class extends FoldingAction {
  constructor() {
    super({
      id: "editor.createFoldingRangeFromSelection",
      label: localize2(1074, "Create Folding Range from Selection"),
      precondition: CONTEXT_FOLDING_ENABLED,
      kbOpts: {
        kbExpr: EditorContextKeys.editorTextFocus,
        primary: $$e(
          2048 | 41,
          2048 | 87
          /* KeyCode.Comma */
        ),
        weight: 100
        /* KeybindingWeight.EditorContrib */
      }
    });
  }
  invoke(_foldingController, foldingModel, editor) {
    const collapseRanges = [];
    const selections = editor.getSelections();
    if (selections) {
      for (const selection of selections) {
        let endLineNumber = selection.endLineNumber;
        if (selection.endColumn === 1) {
          --endLineNumber;
        }
        if (endLineNumber > selection.startLineNumber) {
          collapseRanges.push({
            startLineNumber: selection.startLineNumber,
            endLineNumber,
            type: void 0,
            isCollapsed: true,
            source: 1
            /* FoldSource.userDefined */
          });
          editor.setSelection({
            startLineNumber: selection.startLineNumber,
            startColumn: 1,
            endLineNumber: selection.startLineNumber,
            endColumn: 1
          });
        }
      }
      if (collapseRanges.length > 0) {
        collapseRanges.sort((a, b) => {
          return a.startLineNumber - b.startLineNumber;
        });
        const newRanges = $Jgb.sanitizeAndMerge(foldingModel.regions, collapseRanges, editor.getModel()?.getLineCount());
        foldingModel.updatePost($Jgb.fromFoldRanges(newRanges));
      }
    }
  }
};
var RemoveFoldRangeFromSelectionAction = class extends FoldingAction {
  constructor() {
    super({
      id: "editor.removeManualFoldingRanges",
      label: localize2(1075, "Remove Manual Folding Ranges"),
      precondition: CONTEXT_FOLDING_ENABLED,
      kbOpts: {
        kbExpr: EditorContextKeys.editorTextFocus,
        primary: $$e(
          2048 | 41,
          2048 | 89
          /* KeyCode.Period */
        ),
        weight: 100
        /* KeybindingWeight.EditorContrib */
      }
    });
  }
  invoke(foldingController, foldingModel, editor) {
    const selections = editor.getSelections();
    if (selections) {
      const ranges = [];
      for (const selection of selections) {
        const { startLineNumber, endLineNumber } = selection;
        ranges.push(endLineNumber >= startLineNumber ? { startLineNumber, endLineNumber } : { endLineNumber, startLineNumber });
      }
      foldingModel.removeManualRanges(ranges);
      foldingController.triggerFoldingModelChanged();
    }
  }
};
var ToggleImportFoldAction = class extends FoldingAction {
  constructor() {
    super({
      id: "editor.toggleImportFold",
      label: localize2(1076, "Toggle Import Fold"),
      precondition: CONTEXT_FOLDING_ENABLED,
      kbOpts: {
        kbExpr: EditorContextKeys.editorTextFocus,
        weight: 100
        /* KeybindingWeight.EditorContrib */
      }
    });
  }
  async invoke(foldingController, foldingModel) {
    const regionsToToggle = [];
    const regions = foldingModel.regions;
    for (let i2 = regions.length - 1; i2 >= 0; i2--) {
      if (regions.getType(i2) === $WE.Imports.value) {
        regionsToToggle.push(regions.toRegion(i2));
      }
    }
    foldingModel.toggleCollapseState(regionsToToggle);
    foldingController.triggerFoldingModelChanged();
  }
};
$85(
  $9gb.ID,
  $9gb,
  0
  /* EditorContributionInstantiation.Eager */
);
$55(UnfoldAction);
$55(UnFoldRecursivelyAction);
$55(FoldAction);
$55(FoldRecursivelyAction);
$55(ToggleFoldRecursivelyAction);
$55(FoldAllAction);
$55(UnfoldAllAction);
$55(FoldAllBlockCommentsAction);
$55(FoldAllRegionsAction);
$55(UnfoldAllRegionsAction);
$55(FoldAllExceptAction);
$55(UnfoldAllExceptAction);
$55(ToggleFoldAction);
$55(GotoParentFoldAction);
$55(GotoPreviousFoldAction);
$55(GotoNextFoldAction);
$55(FoldRangeFromSelectionAction);
$55(RemoveFoldRangeFromSelectionAction);
$55(ToggleImportFoldAction);
for (let i2 = 1; i2 <= 7; i2++) {
  $75(new FoldLevelAction({
    id: FoldLevelAction.ID(i2),
    label: localize2(1077, "Fold Level {0}", i2),
    precondition: CONTEXT_FOLDING_ENABLED,
    kbOpts: {
      kbExpr: EditorContextKeys.editorTextFocus,
      primary: $$e(2048 | 41, 2048 | 21 + i2),
      weight: 100
      /* KeybindingWeight.EditorContrib */
    }
  }));
}
$tn.registerCommand("_executeFoldingRangeProvider", async function(accessor, ...args2) {
  const [resource] = args2;
  if (!(resource instanceof URI)) {
    throw $nb();
  }
  const languageFeaturesService = accessor.get($mP);
  const model = accessor.get($sG).getModel(resource);
  if (!model) {
    throw $nb();
  }
  const configurationService = accessor.get($kl);
  if (!configurationService.getValue("editor.folding", { resource })) {
    return [];
  }
  const languageConfigurationService = accessor.get($NF);
  const strategy = configurationService.getValue("editor.foldingStrategy", { resource });
  const foldingLimitReporter = {
    get limit() {
      return configurationService.getValue("editor.foldingMaximumRegions", { resource });
    },
    update: (computed, limited) => {
    }
  };
  const indentRangeProvider = new $Ygb(model, languageConfigurationService, foldingLimitReporter);
  let rangeProvider = indentRangeProvider;
  if (strategy !== "indentation") {
    const providers2 = $9gb.getFoldingRangeProviders(languageFeaturesService, model);
    if (providers2.length) {
      rangeProvider = new $7gb(model, providers2, () => {
      }, foldingLimitReporter, indentRangeProvider);
    }
  }
  const ranges = await rangeProvider.compute(CancellationToken.None);
  const result = [];
  try {
    if (ranges) {
      for (let i2 = 0; i2 < ranges.length; i2++) {
        const type = ranges.getType(i2);
        result.push({ start: ranges.getStartLineNumber(i2), end: ranges.getEndLineNumber(i2), kind: type ? $WE.fromValue(type) : void 0 });
      }
    }
    return result;
  } finally {
    rangeProvider.dispose();
  }
});

// out-build/vs/editor/contrib/fontZoom/browser/fontZoom.js
var EditorFontZoomIn = class extends $Z5 {
  constructor() {
    super({
      id: "editor.action.fontZoomIn",
      label: localize2(1087, "Increase Editor Font Size"),
      precondition: void 0
    });
  }
  run(accessor, editor) {
    EditorZoom.setZoomLevel(EditorZoom.getZoomLevel() + 1);
  }
};
var EditorFontZoomOut = class extends $Z5 {
  constructor() {
    super({
      id: "editor.action.fontZoomOut",
      label: localize2(1088, "Decrease Editor Font Size"),
      precondition: void 0
    });
  }
  run(accessor, editor) {
    EditorZoom.setZoomLevel(EditorZoom.getZoomLevel() - 1);
  }
};
var EditorFontZoomReset = class extends $Z5 {
  constructor() {
    super({
      id: "editor.action.fontZoomReset",
      label: localize2(1089, "Reset Editor Font Size"),
      precondition: void 0
    });
  }
  run(accessor, editor) {
    EditorZoom.setZoomLevel(0);
  }
};
$55(EditorFontZoomIn);
$55(EditorFontZoomOut);
$55(EditorFontZoomReset);

// out-build/vs/editor/contrib/format/browser/formattingEdit.js
var $_gb = class _$_gb {
  static a(editor, edits) {
    let newEol = void 0;
    const singleEdits = [];
    for (const edit3 of edits) {
      if (typeof edit3.eol === "number") {
        newEol = edit3.eol;
      }
      if (edit3.range && typeof edit3.text === "string") {
        singleEdits.push(edit3);
      }
    }
    if (typeof newEol === "number") {
      if (editor.hasModel()) {
        editor.getModel().pushEOL(newEol);
      }
    }
    return singleEdits;
  }
  static b(editor, edit3) {
    if (!editor.hasModel()) {
      return false;
    }
    const model = editor.getModel();
    const editRange = model.validateRange(edit3.range);
    const fullModelRange = model.getFullModelRange();
    return fullModelRange.equalsRange(editRange);
  }
  static execute(editor, _edits, addUndoStops) {
    if (addUndoStops) {
      editor.pushUndoStop();
    }
    const scrollState = $O9.capture(editor);
    const edits = _$_gb.a(editor, _edits);
    if (edits.length === 1 && _$_gb.b(editor, edits[0])) {
      editor.executeEdits("formatEditsCommand", edits.map((edit3) => $bD.replace($9C.lift(edit3.range), edit3.text)));
    } else {
      editor.executeEdits("formatEditsCommand", edits.map((edit3) => $bD.replaceMove($9C.lift(edit3.range), edit3.text)));
    }
    if (addUndoStops) {
      editor.pushUndoStop();
    }
    scrollState.restoreRelativeVerticalPositionOfCursor(editor);
  }
};

// out-build/vs/platform/remote/common/remoteHosts.js
function $8v(uri) {
  return uri.scheme === Schemas.vscodeRemote ? uri.authority : void 0;
}
function $9v(authority) {
  if (!authority) {
    return void 0;
  }
  const pos = authority.indexOf("+");
  if (pos < 0) {
    return authority;
  }
  return authority.substr(0, pos);
}
function $$v(authority, defaultPort) {
  let { host, port } = parseAuthority(authority);
  if (typeof port === "undefined") {
    port = defaultPort;
  }
  return { host, port };
}
function parseAuthority(authority) {
  const m1 = authority.match(/^(\[[0-9a-z:]+\]):(\d+)$/);
  if (m1) {
    return { host: m1[1], port: parseInt(m1[2], 10) };
  }
  const m2 = authority.match(/^(\[[0-9a-z:]+\])$/);
  if (m2) {
    return { host: m2[1], port: void 0 };
  }
  const m3 = authority.match(/(.*):(\d+)$/);
  if (m3) {
    return { host: m3[1], port: parseInt(m3[2], 10) };
  }
  return { host: authority, port: void 0 };
}

// out-build/vs/platform/extensions/common/extensions.js
var $Yz = "extensions.user.cache";
var $Zz = "extensions.builtin.cache";
var $1z = "undefined_publisher";
var $2z = ["ui", "workspace", "web"];
function $3z(supportType) {
  if (typeof supportType === "object" && supportType !== null) {
    if (supportType.supported !== true) {
      return supportType.description;
    }
  }
  return void 0;
}
var $4z = [
  "AI",
  "Azure",
  "Chat",
  "Data Science",
  "Debuggers",
  "Extension Packs",
  "Education",
  "Formatters",
  "Keymaps",
  "Language Packs",
  "Linters",
  "Machine Learning",
  "Notebooks",
  "Programming Languages",
  "SCM Providers",
  "Snippets",
  "Testing",
  "Themes",
  "Visualization",
  "Other"
];
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 $5z = 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 $1f(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 $6z = class {
  get size() {
    return this.c.size;
  }
  constructor(iterable) {
    this.c = /* @__PURE__ */ new Set();
    if (iterable) {
      for (const value of iterable) {
        this.add(value);
      }
    }
  }
  add(id2) {
    this.c.add($5z.toKey(id2));
  }
  delete(extensionId) {
    return this.c.delete($5z.toKey(extensionId));
  }
  has(id2) {
    return this.c.has($5z.toKey(id2));
  }
};
var $7z = class {
  constructor() {
    this.c = /* @__PURE__ */ new Map();
  }
  clear() {
    this.c.clear();
  }
  delete(id2) {
    this.c.delete($5z.toKey(id2));
  }
  get(id2) {
    return this.c.get($5z.toKey(id2));
  }
  has(id2) {
    return this.c.has($5z.toKey(id2));
  }
  set(id2, value) {
    this.c.set($5z.toKey(id2), value);
  }
  values() {
    return this.c.values();
  }
  forEach(callbackfn) {
    this.c.forEach(callbackfn);
  }
  [Symbol.iterator]() {
    return this.c[Symbol.iterator]();
  }
};
function $8z(manifest) {
  return $9z(manifest);
}
function $9z(manifest) {
  return manifest.contributes && manifest.contributes.localizations ? manifest.contributes.localizations.length > 0 : false;
}
function $0z(manifest) {
  return manifest.contributes && manifest.contributes.authentication ? manifest.contributes.authentication.length > 0 : false;
}
function $$z(manifest, remoteAuthority) {
  if (remoteAuthority) {
    const activationEvent = `onResolveRemoteAuthority:${$9v(remoteAuthority)}`;
    return !!manifest.activationEvents?.includes(activationEvent);
  }
  return false;
}
function $_z(enabledApiProposals) {
  return enabledApiProposals.map((proposal) => {
    const [proposalName, version2] = proposal.split("@");
    return { proposalName, version: version2 ? parseInt(version2) : void 0 };
  });
}
function $aA(enabledApiProposals) {
  return enabledApiProposals.map((proposal) => proposal.split("@")[0]);
}
var $bA = $Qk("IBuiltinExtensionsScannerService");

// out-build/vs/editor/contrib/format/browser/format.js
function $ahb(documentFormattingEditProvider, documentRangeFormattingEditProvider, model) {
  const result = [];
  const seen = new $6z();
  const docFormatter = documentFormattingEditProvider.ordered(model);
  for (const formatter of docFormatter) {
    result.push(formatter);
    if (formatter.extensionId) {
      seen.add(formatter.extensionId);
    }
  }
  const rangeFormatter = documentRangeFormattingEditProvider.ordered(model);
  for (const formatter of rangeFormatter) {
    if (formatter.extensionId) {
      if (seen.has(formatter.extensionId)) {
        continue;
      }
      seen.add(formatter.extensionId);
    }
    result.push({
      displayName: formatter.displayName,
      extensionId: formatter.extensionId,
      provideDocumentFormattingEdits(model2, options3, token) {
        return formatter.provideDocumentRangeFormattingEdits(model2, model2.getFullModelRange(), options3, token);
      }
    });
  }
  return result;
}
var FormattingKind;
(function(FormattingKind2) {
  FormattingKind2[FormattingKind2["File"] = 1] = "File";
  FormattingKind2[FormattingKind2["Selection"] = 2] = "Selection";
})(FormattingKind || (FormattingKind = {}));
var FormattingMode;
(function(FormattingMode2) {
  FormattingMode2[FormattingMode2["Explicit"] = 1] = "Explicit";
  FormattingMode2[FormattingMode2["Silent"] = 2] = "Silent";
})(FormattingMode || (FormattingMode = {}));
var $bhb = class _$bhb {
  static {
    this.c = new $cd();
  }
  static setFormatterSelector(selector) {
    const remove = _$bhb.c.unshift(selector);
    return { dispose: remove };
  }
  static async select(formatter, document2, mode, kind) {
    if (formatter.length === 0) {
      return void 0;
    }
    const selector = Iterable.first(_$bhb.c);
    if (selector) {
      return await selector(formatter, document2, mode, kind);
    }
    return void 0;
  }
};
async function $chb(accessor, editorOrModel, rangeOrRanges, mode, progress, token, userGesture) {
  const instaService = accessor.get($Pk);
  const { documentRangeFormattingEditProvider: documentRangeFormattingEditProviderRegistry } = accessor.get($mP);
  const model = $P5(editorOrModel) ? editorOrModel.getModel() : editorOrModel;
  const provider = documentRangeFormattingEditProviderRegistry.ordered(model);
  const selected = await $bhb.select(
    provider,
    model,
    mode,
    2
    /* FormattingKind.Selection */
  );
  if (selected) {
    progress.report(selected);
    await instaService.invokeFunction($dhb, selected, editorOrModel, rangeOrRanges, token, userGesture);
  }
}
async function $dhb(accessor, provider, editorOrModel, rangeOrRanges, token, userGesture) {
  const workerService = accessor.get($I0);
  const logService = accessor.get($wn);
  const accessibilitySignalService = accessor.get($I9);
  let model;
  let cts;
  if ($P5(editorOrModel)) {
    model = editorOrModel.getModel();
    cts = new $N_(editorOrModel, 1 | 4, void 0, token);
  } else {
    model = editorOrModel;
    cts = new $O_(editorOrModel, token);
  }
  const ranges = [];
  let len = 0;
  for (const range of $5b(rangeOrRanges).sort($9C.compareRangesUsingStarts)) {
    if (len > 0 && $9C.areIntersectingOrTouching(ranges[len - 1], range)) {
      ranges[len - 1] = $9C.fromPositions(ranges[len - 1].getStartPosition(), range.getEndPosition());
    } else {
      len = ranges.push(range);
    }
  }
  const computeEdits = async (range) => {
    logService.trace(`[format][provideDocumentRangeFormattingEdits] (request)`, provider.extensionId?.value, range);
    const result = await provider.provideDocumentRangeFormattingEdits(model, range, model.getFormattingOptions(), cts.token) || [];
    logService.trace(`[format][provideDocumentRangeFormattingEdits] (response)`, provider.extensionId?.value, result);
    return result;
  };
  const hasIntersectingEdit = (a, b) => {
    if (!a.length || !b.length) {
      return false;
    }
    const mergedA = a.reduce((acc, val) => {
      return $9C.plusRange(acc, val.range);
    }, a[0].range);
    if (!b.some((x) => {
      return $9C.intersectRanges(mergedA, x.range);
    })) {
      return false;
    }
    for (const edit3 of a) {
      for (const otherEdit of b) {
        if ($9C.intersectRanges(edit3.range, otherEdit.range)) {
          return true;
        }
      }
    }
    return false;
  };
  const allEdits = [];
  const rawEditsList = [];
  try {
    if (typeof provider.provideDocumentRangesFormattingEdits === "function") {
      logService.trace(`[format][provideDocumentRangeFormattingEdits] (request)`, provider.extensionId?.value, ranges);
      const result = await provider.provideDocumentRangesFormattingEdits(model, ranges, model.getFormattingOptions(), cts.token) || [];
      logService.trace(`[format][provideDocumentRangeFormattingEdits] (response)`, provider.extensionId?.value, result);
      rawEditsList.push(result);
    } else {
      for (const range of ranges) {
        if (cts.token.isCancellationRequested) {
          return true;
        }
        rawEditsList.push(await computeEdits(range));
      }
      for (let i2 = 0; i2 < ranges.length; ++i2) {
        for (let j = i2 + 1; j < ranges.length; ++j) {
          if (cts.token.isCancellationRequested) {
            return true;
          }
          if (hasIntersectingEdit(rawEditsList[i2], rawEditsList[j])) {
            const mergedRange = $9C.plusRange(ranges[i2], ranges[j]);
            const edits = await computeEdits(mergedRange);
            ranges.splice(j, 1);
            ranges.splice(i2, 1);
            ranges.push(mergedRange);
            rawEditsList.splice(j, 1);
            rawEditsList.splice(i2, 1);
            rawEditsList.push(edits);
            i2 = 0;
            j = 0;
          }
        }
      }
    }
    for (const rawEdits of rawEditsList) {
      if (cts.token.isCancellationRequested) {
        return true;
      }
      const minimalEdits = await workerService.computeMoreMinimalEdits(model.uri, rawEdits);
      if (minimalEdits) {
        allEdits.push(...minimalEdits);
      }
    }
  } finally {
    cts.dispose();
  }
  if (allEdits.length === 0) {
    return false;
  }
  if ($P5(editorOrModel)) {
    $_gb.execute(editorOrModel, allEdits, true);
    editorOrModel.revealPositionInCenterIfOutsideViewport(
      editorOrModel.getPosition(),
      1
      /* ScrollType.Immediate */
    );
  } else {
    const [{ range }] = allEdits;
    const initialSelection = new $_D(range.startLineNumber, range.startColumn, range.endLineNumber, range.endColumn);
    model.pushEditOperations([initialSelection], allEdits.map((edit3) => {
      return {
        text: edit3.text,
        range: $9C.lift(edit3.range),
        forceMoveMarkers: true
      };
    }), (undoEdits) => {
      for (const { range: range2 } of undoEdits) {
        if ($9C.areIntersectingOrTouching(range2, initialSelection)) {
          return [new $_D(range2.startLineNumber, range2.startColumn, range2.endLineNumber, range2.endColumn)];
        }
      }
      return null;
    });
  }
  accessibilitySignalService.playSignal($N9.format, { userGesture });
  return true;
}
async function $ehb(accessor, editorOrModel, mode, progress, token, userGesture) {
  const instaService = accessor.get($Pk);
  const languageFeaturesService = accessor.get($mP);
  const model = $P5(editorOrModel) ? editorOrModel.getModel() : editorOrModel;
  const provider = $ahb(languageFeaturesService.documentFormattingEditProvider, languageFeaturesService.documentRangeFormattingEditProvider, model);
  const selected = await $bhb.select(
    provider,
    model,
    mode,
    1
    /* FormattingKind.File */
  );
  if (selected) {
    progress.report(selected);
    await instaService.invokeFunction($fhb, selected, editorOrModel, mode, token, userGesture);
  }
}
async function $fhb(accessor, provider, editorOrModel, mode, token, userGesture) {
  const workerService = accessor.get($I0);
  const accessibilitySignalService = accessor.get($I9);
  let model;
  let cts;
  if ($P5(editorOrModel)) {
    model = editorOrModel.getModel();
    cts = new $N_(editorOrModel, 1 | 4, void 0, token);
  } else {
    model = editorOrModel;
    cts = new $O_(editorOrModel, token);
  }
  let edits;
  try {
    const rawEdits = await provider.provideDocumentFormattingEdits(model, model.getFormattingOptions(), cts.token);
    edits = await workerService.computeMoreMinimalEdits(model.uri, rawEdits);
    if (cts.token.isCancellationRequested) {
      return true;
    }
  } finally {
    cts.dispose();
  }
  if (!edits || edits.length === 0) {
    return false;
  }
  if ($P5(editorOrModel)) {
    $_gb.execute(
      editorOrModel,
      edits,
      mode !== 2
      /* FormattingMode.Silent */
    );
    if (mode !== 2) {
      editorOrModel.revealPositionInCenterIfOutsideViewport(
        editorOrModel.getPosition(),
        1
        /* ScrollType.Immediate */
      );
    }
  } else {
    const [{ range }] = edits;
    const initialSelection = new $_D(range.startLineNumber, range.startColumn, range.endLineNumber, range.endColumn);
    model.pushEditOperations([initialSelection], edits.map((edit3) => {
      return {
        text: edit3.text,
        range: $9C.lift(edit3.range),
        forceMoveMarkers: true
      };
    }), (undoEdits) => {
      for (const { range: range2 } of undoEdits) {
        if ($9C.areIntersectingOrTouching(range2, initialSelection)) {
          return [new $_D(range2.startLineNumber, range2.startColumn, range2.endLineNumber, range2.endColumn)];
        }
      }
      return null;
    });
  }
  accessibilitySignalService.playSignal($N9.format, { userGesture });
  return true;
}
async function $ghb(workerService, languageFeaturesService, model, range, options3, token) {
  const providers2 = languageFeaturesService.documentRangeFormattingEditProvider.ordered(model);
  for (const provider of providers2) {
    const rawEdits = await Promise.resolve(provider.provideDocumentRangeFormattingEdits(model, range, options3, token)).catch($hb);
    if ($Qb(rawEdits)) {
      return await workerService.computeMoreMinimalEdits(model.uri, rawEdits);
    }
  }
  return void 0;
}
async function $hhb(workerService, languageFeaturesService, model, options3, token) {
  const providers2 = $ahb(languageFeaturesService.documentFormattingEditProvider, languageFeaturesService.documentRangeFormattingEditProvider, model);
  for (const provider of providers2) {
    const rawEdits = await Promise.resolve(provider.provideDocumentFormattingEdits(model, options3, token)).catch($hb);
    if ($Qb(rawEdits)) {
      return await workerService.computeMoreMinimalEdits(model.uri, rawEdits);
    }
  }
  return void 0;
}
async function $ihb(workerService, languageFeaturesService, editorOrModel, mode, token) {
  const model = $P5(editorOrModel) ? editorOrModel.getModel() : editorOrModel;
  const provider = $ahb(languageFeaturesService.documentFormattingEditProvider, languageFeaturesService.documentRangeFormattingEditProvider, model);
  const selected = await $bhb.select(
    provider,
    model,
    mode,
    1
    /* FormattingKind.File */
  );
  if (selected) {
    const rawEdits = await Promise.resolve(selected.provideDocumentFormattingEdits(model, model.getOptions(), token)).catch($hb);
    return await workerService.computeMoreMinimalEdits(model.uri, rawEdits);
  }
  return void 0;
}
function $jhb(workerService, languageFeaturesService, model, position, ch, options3, token) {
  const providers2 = languageFeaturesService.onTypeFormattingEditProvider.ordered(model);
  if (providers2.length === 0) {
    return Promise.resolve(void 0);
  }
  if (providers2[0].autoFormatTriggerCharacters.indexOf(ch) < 0) {
    return Promise.resolve(void 0);
  }
  return Promise.resolve(providers2[0].provideOnTypeFormattingEdits(model, position, ch, options3, token)).catch($hb).then((edits) => {
    return workerService.computeMoreMinimalEdits(model.uri, edits);
  });
}
$tn.registerCommand("_executeFormatRangeProvider", async function(accessor, ...args2) {
  const [resource, range, options3] = args2;
  $Jg(URI.isUri(resource));
  $Jg($9C.isIRange(range));
  const resolverService = accessor.get($oG);
  const workerService = accessor.get($I0);
  const languageFeaturesService = accessor.get($mP);
  const reference = await resolverService.createModelReference(resource);
  try {
    return $ghb(workerService, languageFeaturesService, reference.object.textEditorModel, $9C.lift(range), options3, CancellationToken.None);
  } finally {
    reference.dispose();
  }
});
$tn.registerCommand("_executeFormatDocumentProvider", async function(accessor, ...args2) {
  const [resource, options3] = args2;
  $Jg(URI.isUri(resource));
  const resolverService = accessor.get($oG);
  const workerService = accessor.get($I0);
  const languageFeaturesService = accessor.get($mP);
  const reference = await resolverService.createModelReference(resource);
  try {
    return $hhb(workerService, languageFeaturesService, reference.object.textEditorModel, options3, CancellationToken.None);
  } finally {
    reference.dispose();
  }
});
$tn.registerCommand("_executeFormatOnTypeProvider", async function(accessor, ...args2) {
  const [resource, position, ch, options3] = args2;
  $Jg(URI.isUri(resource));
  $Jg($8C.isIPosition(position));
  $Jg(typeof ch === "string");
  const resolverService = accessor.get($oG);
  const workerService = accessor.get($I0);
  const languageFeaturesService = accessor.get($mP);
  const reference = await resolverService.createModelReference(resource);
  try {
    return $jhb(workerService, languageFeaturesService, reference.object.textEditorModel, $8C.lift(position), ch, options3, CancellationToken.None);
  } finally {
    reference.dispose();
  }
});

// out-build/vs/editor/contrib/format/browser/formatActions.js
var $khb = class $khb2 {
  static {
    this.ID = "editor.contrib.autoFormat";
  }
  constructor(c, d, f, g) {
    this.c = c;
    this.d = d;
    this.f = f;
    this.g = g;
    this.a = new $2c();
    this.b = new $2c();
    this.a.add(d.onTypeFormattingEditProvider.onDidChange(this.h, this));
    this.a.add(c.onDidChangeModel(() => this.h()));
    this.a.add(c.onDidChangeModelLanguage(() => this.h()));
    this.a.add(c.onDidChangeConfiguration((e) => {
      if (e.hasChanged(
        58
        /* EditorOption.formatOnType */
      )) {
        this.h();
      }
    }));
    this.h();
  }
  dispose() {
    this.a.dispose();
    this.b.dispose();
  }
  h() {
    this.b.clear();
    if (!this.c.getOption(
      58
      /* EditorOption.formatOnType */
    )) {
      return;
    }
    if (!this.c.hasModel()) {
      return;
    }
    const model = this.c.getModel();
    const [support] = this.d.onTypeFormattingEditProvider.ordered(model);
    if (!support || !support.autoFormatTriggerCharacters) {
      return;
    }
    const triggerChars = new $gE();
    for (const ch of support.autoFormatTriggerCharacters) {
      triggerChars.add(ch.charCodeAt(0));
    }
    this.b.add(this.c.onDidType((text2) => {
      const lastCharCode = text2.charCodeAt(text2.length - 1);
      if (triggerChars.has(lastCharCode)) {
        this.j(String.fromCharCode(lastCharCode));
      }
    }));
  }
  j(ch) {
    if (!this.c.hasModel()) {
      return;
    }
    if (this.c.getSelections().length > 1 || !this.c.getSelection().isEmpty()) {
      return;
    }
    const model = this.c.getModel();
    const position = this.c.getPosition();
    const cts = new $ad();
    const unbind = this.c.onDidChangeModelContent((e) => {
      if (e.isFlush) {
        cts.cancel();
        unbind.dispose();
        return;
      }
      for (let i2 = 0, len = e.changes.length; i2 < len; i2++) {
        const change = e.changes[i2];
        if (change.range.endLineNumber <= position.lineNumber) {
          cts.cancel();
          unbind.dispose();
          return;
        }
      }
    });
    $jhb(this.f, this.d, model, position, ch, model.getFormattingOptions(), cts.token).then((edits) => {
      if (cts.token.isCancellationRequested) {
        return;
      }
      if ($Qb(edits)) {
        this.g.playSignal($N9.format, { userGesture: false });
        $_gb.execute(this.c, edits, true);
      }
    }).finally(() => {
      unbind.dispose();
    });
  }
};
$khb = __decorate([
  __param(1, $mP),
  __param(2, $I0),
  __param(3, $I9)
], $khb);
var FormatOnPaste = class FormatOnPaste2 {
  static {
    this.ID = "editor.contrib.formatOnPaste";
  }
  constructor(c, d, f) {
    this.c = c;
    this.d = d;
    this.f = f;
    this.a = new $2c();
    this.b = new $2c();
    this.a.add(c.onDidChangeConfiguration(() => this.g()));
    this.a.add(c.onDidChangeModel(() => this.g()));
    this.a.add(c.onDidChangeModelLanguage(() => this.g()));
    this.a.add(d.documentRangeFormattingEditProvider.onDidChange(this.g, this));
  }
  dispose() {
    this.a.dispose();
    this.b.dispose();
  }
  g() {
    this.b.clear();
    if (!this.c.getOption(
      57
      /* EditorOption.formatOnPaste */
    )) {
      return;
    }
    if (!this.c.hasModel()) {
      return;
    }
    if (!this.d.documentRangeFormattingEditProvider.has(this.c.getModel())) {
      return;
    }
    this.b.add(this.c.onDidPaste(({ range }) => this.h(range)));
  }
  h(range) {
    if (!this.c.hasModel()) {
      return;
    }
    if (this.c.getSelections().length > 1) {
      return;
    }
    this.f.invokeFunction($chb, this.c, range, 2, $VJ.None, CancellationToken.None, false).catch($gb);
  }
};
FormatOnPaste = __decorate([
  __param(1, $mP),
  __param(2, $Pk)
], FormatOnPaste);
var FormatDocumentAction = class extends $Z5 {
  constructor() {
    super({
      id: "editor.action.formatDocument",
      label: localize2(1090, "Format Document"),
      precondition: $7m.and(EditorContextKeys.notInCompositeEditor, EditorContextKeys.writable, EditorContextKeys.hasDocumentFormattingProvider),
      kbOpts: {
        kbExpr: EditorContextKeys.editorTextFocus,
        primary: 1024 | 512 | 36,
        linux: {
          primary: 2048 | 1024 | 39
          /* KeyCode.KeyI */
        },
        weight: 100
        /* KeybindingWeight.EditorContrib */
      },
      contextMenuOpts: {
        group: "1_modification",
        order: 1.3
      }
    });
  }
  async run(accessor, editor) {
    if (editor.hasModel()) {
      const instaService = accessor.get($Pk);
      const progressService = accessor.get($ZJ);
      await progressService.showWhile(instaService.invokeFunction($ehb, editor, 1, $VJ.None, CancellationToken.None, true), 250);
    }
  }
};
var FormatSelectionAction = class extends $Z5 {
  constructor() {
    super({
      id: "editor.action.formatSelection",
      label: localize2(1091, "Format Selection"),
      precondition: $7m.and(EditorContextKeys.writable, EditorContextKeys.hasDocumentSelectionFormattingProvider),
      kbOpts: {
        kbExpr: EditorContextKeys.editorTextFocus,
        primary: $$e(
          2048 | 41,
          2048 | 36
          /* KeyCode.KeyF */
        ),
        weight: 100
        /* KeybindingWeight.EditorContrib */
      },
      contextMenuOpts: {
        when: EditorContextKeys.hasNonEmptySelection,
        group: "1_modification",
        order: 1.31
      }
    });
  }
  async run(accessor, editor) {
    if (!editor.hasModel()) {
      return;
    }
    const instaService = accessor.get($Pk);
    const model = editor.getModel();
    const ranges = editor.getSelections().map((range) => {
      return range.isEmpty() ? new $9C(range.startLineNumber, 1, range.startLineNumber, model.getLineMaxColumn(range.startLineNumber)) : range;
    });
    const progressService = accessor.get($ZJ);
    await progressService.showWhile(instaService.invokeFunction($chb, editor, ranges, 1, $VJ.None, CancellationToken.None, true), 250);
  }
};
$85(
  $khb.ID,
  $khb,
  2
  /* EditorContributionInstantiation.BeforeFirstInteraction */
);
$85(
  FormatOnPaste.ID,
  FormatOnPaste,
  2
  /* EditorContributionInstantiation.BeforeFirstInteraction */
);
$55(FormatDocumentAction);
$55(FormatSelectionAction);
$tn.registerCommand("editor.action.format", async (accessor) => {
  const editor = accessor.get($U5).getFocusedCodeEditor();
  if (!editor || !editor.hasModel()) {
    return;
  }
  const commandService = accessor.get($sn);
  if (editor.getSelection().isEmpty()) {
    await commandService.executeCommand("editor.action.formatDocument");
  } else {
    await commandService.executeCommand("editor.action.formatSelection");
  }
});

// out-build/vs/editor/contrib/documentSymbols/browser/outlineModel.js
var $lhb = class _$lhb {
  remove() {
    this.parent?.children.delete(this.id);
  }
  static findId(candidate, container2) {
    let candidateId;
    if (typeof candidate === "string") {
      candidateId = `${container2.id}/${candidate}`;
    } else {
      candidateId = `${container2.id}/${candidate.name}`;
      if (container2.children.get(candidateId) !== void 0) {
        candidateId = `${container2.id}/${candidate.name}_${candidate.range.startLineNumber}_${candidate.range.startColumn}`;
      }
    }
    let id2 = candidateId;
    for (let i2 = 0; container2.children.get(id2) !== void 0; i2++) {
      id2 = `${candidateId}_${i2}`;
    }
    return id2;
  }
  static getElementById(id2, element) {
    if (!id2) {
      return void 0;
    }
    const len = $3f(id2, element.id);
    if (len === id2.length) {
      return element;
    }
    if (len < element.id.length) {
      return void 0;
    }
    for (const [, child] of element.children) {
      const candidate = _$lhb.getElementById(id2, child);
      if (candidate) {
        return candidate;
      }
    }
    return void 0;
  }
  static size(element) {
    let res = 1;
    for (const [, child] of element.children) {
      res += _$lhb.size(child);
    }
    return res;
  }
  static empty(element) {
    return element.children.size === 0;
  }
};
var $mhb = class extends $lhb {
  constructor(id2, parent, symbol) {
    super();
    this.id = id2;
    this.parent = parent;
    this.symbol = symbol;
    this.children = /* @__PURE__ */ new Map();
  }
};
var $nhb = class extends $lhb {
  constructor(id2, parent, label3, order) {
    super();
    this.id = id2;
    this.parent = parent;
    this.label = label3;
    this.order = order;
    this.children = /* @__PURE__ */ new Map();
  }
  getItemEnclosingPosition(position) {
    return position ? this.c(position, this.children) : void 0;
  }
  c(position, children) {
    for (const [, item] of children) {
      if (!item.symbol.range || !$9C.containsPosition(item.symbol.range, position)) {
        continue;
      }
      return this.c(position, item.children) || item;
    }
    return void 0;
  }
  updateMarker(marker) {
    for (const [, child] of this.children) {
      this.d(marker, child);
    }
  }
  d(markers, item) {
    item.marker = void 0;
    const idx = $Bb(markers, item.symbol.range, $9C.compareRangesUsingStarts);
    let start;
    if (idx < 0) {
      start = ~idx;
      if (start > 0 && $9C.areIntersecting(markers[start - 1], item.symbol.range)) {
        start -= 1;
      }
    } else {
      start = idx;
    }
    const myMarkers = [];
    let myTopSev;
    for (; start < markers.length && $9C.areIntersecting(item.symbol.range, markers[start]); start++) {
      const marker = markers[start];
      myMarkers.push(marker);
      markers[start] = void 0;
      if (!myTopSev || marker.severity > myTopSev) {
        myTopSev = marker.severity;
      }
    }
    for (const [, child] of item.children) {
      this.d(myMarkers, child);
    }
    if (myTopSev) {
      item.marker = {
        count: myMarkers.length,
        topSev: myTopSev
      };
    }
    $Nb(markers);
  }
};
var $ohb = class _$ohb extends $lhb {
  static create(registry4, textModel, token) {
    const cts = new $ad(token);
    const result = new _$ohb(textModel.uri);
    const provider = registry4.ordered(textModel);
    const promises = provider.map((provider2, index) => {
      const id2 = $lhb.findId(`provider_${index}`, result);
      const group2 = new $nhb(id2, result, provider2.displayName ?? "Unknown Outline Provider", index);
      return Promise.resolve(provider2.provideDocumentSymbols(textModel, cts.token)).then((result2) => {
        for (const info of result2 || []) {
          _$ohb.c(info, group2);
        }
        return group2;
      }, (err) => {
        $hb(err);
        return group2;
      }).then((group3) => {
        if (!$lhb.empty(group3)) {
          result.e.set(id2, group3);
        } else {
          group3.remove();
        }
      });
    });
    const listener = registry4.onDidChange(() => {
      const newProvider = registry4.ordered(textModel);
      if (!$zb(newProvider, provider)) {
        cts.cancel();
      }
    });
    return Promise.all(promises).then(() => {
      if (cts.token.isCancellationRequested && !token.isCancellationRequested) {
        return _$ohb.create(registry4, textModel, token);
      } else {
        return result.f();
      }
    }).finally(() => {
      cts.dispose();
      listener.dispose();
      cts.dispose();
    });
  }
  static c(info, container2) {
    const id2 = $lhb.findId(info, container2);
    const res = new $mhb(id2, container2, info);
    if (info.children) {
      for (const childInfo of info.children) {
        _$ohb.c(childInfo, res);
      }
    }
    container2.children.set(res.id, res);
  }
  static get(element) {
    while (element) {
      if (element instanceof _$ohb) {
        return element;
      }
      element = element.parent;
    }
    return void 0;
  }
  constructor(uri) {
    super();
    this.uri = uri;
    this.id = "root";
    this.parent = void 0;
    this.e = /* @__PURE__ */ new Map();
    this.children = /* @__PURE__ */ new Map();
    this.id = "root";
    this.parent = void 0;
  }
  f() {
    let count = 0;
    for (const [key2, group2] of this.e) {
      if (group2.children.size === 0) {
        this.e.delete(key2);
      } else {
        count += 1;
      }
    }
    if (count !== 1) {
      this.children = this.e;
    } else {
      const group2 = Iterable.first(this.e.values());
      for (const [, child] of group2.children) {
        child.parent = this;
        this.children.set(child.id, child);
      }
    }
    return this;
  }
  merge(other) {
    if (this.uri.toString() !== other.uri.toString()) {
      return false;
    }
    if (this.e.size !== other.e.size) {
      return false;
    }
    this.e = other.e;
    this.children = other.children;
    return true;
  }
  getItemEnclosingPosition(position, context) {
    let preferredGroup;
    if (context) {
      let candidate = context.parent;
      while (candidate && !preferredGroup) {
        if (candidate instanceof $nhb) {
          preferredGroup = candidate;
        }
        candidate = candidate.parent;
      }
    }
    let result = void 0;
    for (const [, group2] of this.e) {
      result = group2.getItemEnclosingPosition(position);
      if (result && (!preferredGroup || preferredGroup === group2)) {
        break;
      }
    }
    return result;
  }
  getItemById(id2) {
    return $lhb.getElementById(id2, this);
  }
  updateMarker(marker) {
    marker.sort($9C.compareRangesUsingStarts);
    for (const [, group2] of this.e) {
      group2.updateMarker(marker.slice(0));
    }
  }
  getTopLevelSymbols() {
    const roots = [];
    for (const child of this.children.values()) {
      if (child instanceof $mhb) {
        roots.push(child.symbol);
      } else {
        roots.push(...Iterable.map(child.children.values(), (child2) => child2.symbol));
      }
    }
    return roots.sort((a, b) => $9C.compareRangesUsingStarts(a.range, b.range));
  }
  asListOfDocumentSymbols() {
    const roots = this.getTopLevelSymbols();
    const bucket = [];
    _$ohb.g(bucket, roots, "");
    return bucket.sort((a, b) => $8C.compare($9C.getStartPosition(a.range), $9C.getStartPosition(b.range)) || $8C.compare($9C.getEndPosition(b.range), $9C.getEndPosition(a.range)));
  }
  static g(bucket, entries2, overrideContainerLabel) {
    for (const entry of entries2) {
      bucket.push({
        kind: entry.kind,
        tags: entry.tags,
        name: entry.name,
        detail: entry.detail,
        containerName: entry.containerName || overrideContainerLabel,
        range: entry.range,
        selectionRange: entry.selectionRange,
        children: void 0
        // we flatten it...
      });
      if (entry.children) {
        _$ohb.g(bucket, entry.children, entry.name);
      }
    }
  }
};
var $phb = $Qk("IOutlineModelService");
var $qhb = class $qhb2 {
  constructor(f, debounces, modelService) {
    this.f = f;
    this.c = new $2c();
    this.e = new $Hc(15, 0.7);
    this.d = debounces.for(f.documentSymbolProvider, "DocumentSymbols", { min: 350 });
    this.c.add(modelService.onModelRemoved((textModel) => {
      this.e.delete(textModel.id);
    }));
  }
  dispose() {
    this.c.dispose();
  }
  async getOrCreate(textModel, token) {
    const registry4 = this.f.documentSymbolProvider;
    const provider = registry4.ordered(textModel);
    let data = this.e.get(textModel.id);
    if (!data || data.versionId !== textModel.getVersionId() || !$zb(data.provider, provider)) {
      const source = new $ad();
      data = {
        versionId: textModel.getVersionId(),
        provider,
        promiseCnt: 0,
        source,
        promise: $ohb.create(registry4, textModel, source.token),
        model: void 0
      };
      this.e.set(textModel.id, data);
      const now = Date.now();
      data.promise.then((outlineModel) => {
        data.model = outlineModel;
        this.d.update(textModel, Date.now() - now);
      }).catch((_err) => {
        this.e.delete(textModel.id);
      });
    }
    if (data.model) {
      return data.model;
    }
    data.promiseCnt += 1;
    const listener = token.onCancellationRequested(() => {
      if (--data.promiseCnt === 0) {
        data.source.cancel();
        this.e.delete(textModel.id);
      }
    });
    try {
      return await data.promise;
    } finally {
      listener.dispose();
    }
  }
  getDebounceValue(textModel) {
    return this.d.get(textModel);
  }
  getCachedModels() {
    return Iterable.filter(Iterable.map(this.e.values(), (entry) => entry.model), (model) => model !== void 0);
  }
};
$qhb = __decorate([
  __param(0, $mP),
  __param(1, $tbb),
  __param(2, $sG)
], $qhb);
$SC(
  $phb,
  $qhb,
  1
  /* InstantiationType.Delayed */
);

// out-build/vs/editor/contrib/documentSymbols/browser/documentSymbols.js
$tn.registerCommand("_executeDocumentSymbolProvider", async function(accessor, ...args2) {
  const [resource] = args2;
  $Jg(URI.isUri(resource));
  const outlineService = accessor.get($phb);
  const modelService = accessor.get($oG);
  const reference = await modelService.createModelReference(resource);
  try {
    return (await outlineService.getOrCreate(reference.object.textEditorModel, CancellationToken.None)).getTopLevelSymbols();
  } finally {
    reference.dispose();
  }
});

// out-build/vs/platform/accessibility/browser/accessibleViewRegistry.js
var $vhb = new class AccessibleViewRegistry {
  constructor() {
    this._implementations = [];
  }
  register(implementation) {
    this._implementations.push(implementation);
    return {
      dispose: () => {
        const idx = this._implementations.indexOf(implementation);
        if (idx !== -1) {
          this._implementations.splice(idx, 1);
        }
      }
    };
  }
  getImplementations() {
    return this._implementations;
  }
}();

// out-build/vs/platform/observable/common/wrapInHotClass.js
function $whb(value) {
  if (value instanceof BaseClass) {
    return value._instance;
  }
  return value;
}
var BaseClass = class {
  constructor(instantiationService) {
    this.instantiationService = instantiationService;
  }
  init(...params) {
  }
};
function createWrapper(clazz, B) {
  return class ReloadableWrapper extends B {
    constructor() {
      super(...arguments);
      this.a = void 0;
    }
    init(...params) {
      this.a = $xd((reader, store) => {
        const clazz_ = clazz.read(reader);
        this._instance = store.add(this.instantiationService.createInstance(clazz_, ...params));
      });
    }
    dispose() {
      this.a?.dispose();
    }
  };
}
var BaseClass0 = class BaseClass02 extends BaseClass {
  constructor(i2) {
    super(i2);
    this.init();
  }
};
BaseClass0 = __decorate([
  __param(0, $Pk)
], BaseClass0);
function $yhb(clazz) {
  return !$L3() ? clazz.get() : createWrapper(clazz, BaseClass1);
}
var BaseClass1 = class BaseClass12 extends BaseClass {
  constructor(param1, i2) {
    super(i2);
    this.init(param1);
  }
};
BaseClass1 = __decorate([
  __param(1, $Pk)
], BaseClass1);

// out-build/vs/editor/contrib/suggest/browser/suggest.js
var $_bb = {
  Visible: $7bb,
  HasFocusedSuggestion: new $nn("suggestWidgetHasFocusedSuggestion", false, localize(1493, null)),
  DetailsVisible: new $nn("suggestWidgetDetailsVisible", false, localize(1494, null)),
  MultipleSuggestions: new $nn("suggestWidgetMultipleSuggestions", false, localize(1495, null)),
  MakesTextEdit: new $nn("suggestionMakesTextEdit", true, localize(1496, null)),
  AcceptSuggestionsOnEnter: new $nn("acceptSuggestionOnEnter", true, localize(1497, null)),
  HasInsertAndReplaceRange: new $nn("suggestionHasInsertAndReplaceRange", false, localize(1498, null)),
  InsertMode: new $nn("suggestionInsertMode", void 0, { type: "string", description: localize(1499, null) }),
  CanResolve: new $nn("suggestionCanResolve", false, localize(1500, null))
};
var $acb = new $bJ("suggestWidgetStatusBar");
var $bcb = class {
  constructor(position, completion, container2, provider) {
    this.position = position;
    this.completion = completion;
    this.container = container2;
    this.provider = provider;
    this.isInvalid = false;
    this.score = FuzzyScore.Default;
    this.distance = 0;
    this.textLabel = typeof completion.label === "string" ? completion.label : completion.label?.label;
    this.labelLow = this.textLabel.toLowerCase();
    this.isInvalid = !this.textLabel;
    this.sortTextLow = completion.sortText && completion.sortText.toLowerCase();
    this.filterTextLow = completion.filterText && completion.filterText.toLowerCase();
    this.extensionId = completion.extensionId;
    if ($9C.isIRange(completion.range)) {
      this.editStart = new $8C(completion.range.startLineNumber, completion.range.startColumn);
      this.editInsertEnd = new $8C(completion.range.endLineNumber, completion.range.endColumn);
      this.editReplaceEnd = new $8C(completion.range.endLineNumber, completion.range.endColumn);
      this.isInvalid = this.isInvalid || $9C.spansMultipleLines(completion.range) || completion.range.startLineNumber !== position.lineNumber;
    } else {
      this.editStart = new $8C(completion.range.insert.startLineNumber, completion.range.insert.startColumn);
      this.editInsertEnd = new $8C(completion.range.insert.endLineNumber, completion.range.insert.endColumn);
      this.editReplaceEnd = new $8C(completion.range.replace.endLineNumber, completion.range.replace.endColumn);
      this.isInvalid = this.isInvalid || $9C.spansMultipleLines(completion.range.insert) || $9C.spansMultipleLines(completion.range.replace) || completion.range.insert.startLineNumber !== position.lineNumber || completion.range.replace.startLineNumber !== position.lineNumber || completion.range.insert.startColumn !== completion.range.replace.startColumn;
    }
    if (typeof provider.resolveCompletionItem !== "function") {
      this.d = Promise.resolve();
      this.c = 0;
    }
  }
  // ---- resolving
  get isResolved() {
    return this.c !== void 0;
  }
  get resolveDuration() {
    return this.c !== void 0 ? this.c : -1;
  }
  async resolve(token) {
    if (!this.d) {
      const sub = token.onCancellationRequested(() => {
        this.d = void 0;
        this.c = void 0;
      });
      const sw = new $te(true);
      this.d = Promise.resolve(this.provider.resolveCompletionItem(this.completion, token)).then((value) => {
        Object.assign(this.completion, value);
        this.c = sw.elapsed();
      }, (err) => {
        if ($kb(err)) {
          this.d = void 0;
          this.c = void 0;
        }
      }).finally(() => {
        sub.dispose();
      });
    }
    return this.d;
  }
};
var SnippetSortOrder;
(function(SnippetSortOrder2) {
  SnippetSortOrder2[SnippetSortOrder2["Top"] = 0] = "Top";
  SnippetSortOrder2[SnippetSortOrder2["Inline"] = 1] = "Inline";
  SnippetSortOrder2[SnippetSortOrder2["Bottom"] = 2] = "Bottom";
})(SnippetSortOrder || (SnippetSortOrder = {}));
var $ccb = class _$ccb {
  static {
    this.default = new _$ccb();
  }
  constructor(snippetSortOrder = 2, kindFilter = /* @__PURE__ */ new Set(), providerFilter = /* @__PURE__ */ new Set(), providerItemsToReuse = /* @__PURE__ */ new Map(), showDeprecated = true) {
    this.snippetSortOrder = snippetSortOrder;
    this.kindFilter = kindFilter;
    this.providerFilter = providerFilter;
    this.providerItemsToReuse = providerItemsToReuse;
    this.showDeprecated = showDeprecated;
  }
};
var _snippetSuggestSupport;
function $dcb() {
  return _snippetSuggestSupport;
}
function $ecb(support) {
  const old = _snippetSuggestSupport;
  _snippetSuggestSupport = support;
  return old;
}
var $fcb = class {
  constructor(items, needsClipboard, durations, disposable) {
    this.items = items;
    this.needsClipboard = needsClipboard;
    this.durations = durations;
    this.disposable = disposable;
  }
};
async function $gcb(registry4, model, position, options3 = $ccb.default, context = {
  triggerKind: 0
  /* languages.CompletionTriggerKind.Invoke */
}, token = CancellationToken.None) {
  const sw = new $te();
  position = position.clone();
  const word = model.getWordAtPosition(position);
  const defaultReplaceRange = word ? new $9C(position.lineNumber, word.startColumn, position.lineNumber, word.endColumn) : $9C.fromPositions(position);
  const defaultRange = { replace: defaultReplaceRange, insert: defaultReplaceRange.setEndPosition(position.lineNumber, position.column) };
  const result = [];
  const disposables = new $2c();
  const durations = [];
  let needsClipboard = false;
  const onCompletionList = (provider, container2, sw2) => {
    let didAddResult = false;
    if (!container2) {
      return didAddResult;
    }
    for (const suggestion of container2.suggestions) {
      if (!options3.kindFilter.has(suggestion.kind)) {
        if (!options3.showDeprecated && suggestion?.tags?.includes(
          1
          /* languages.CompletionItemTag.Deprecated */
        )) {
          continue;
        }
        if (!suggestion.range) {
          suggestion.range = defaultRange;
        }
        if (!suggestion.sortText) {
          suggestion.sortText = typeof suggestion.label === "string" ? suggestion.label : suggestion.label.label;
        }
        if (!needsClipboard && suggestion.insertTextRules && suggestion.insertTextRules & 4) {
          needsClipboard = $0_.guessNeedsClipboard(suggestion.insertText);
        }
        result.push(new $bcb(position, suggestion, container2, provider));
        didAddResult = true;
      }
    }
    if ($Wc(container2)) {
      disposables.add(container2);
    }
    durations.push({
      providerName: provider._debugDisplayName ?? "unknown_provider",
      elapsedProvider: container2.duration ?? -1,
      elapsedOverall: sw2.elapsed()
    });
    return didAddResult;
  };
  const snippetCompletions = (async () => {
    if (!_snippetSuggestSupport || options3.kindFilter.has(
      27
      /* languages.CompletionItemKind.Snippet */
    )) {
      return;
    }
    const reuseItems = options3.providerItemsToReuse.get(_snippetSuggestSupport);
    if (reuseItems) {
      reuseItems.forEach((item) => result.push(item));
      return;
    }
    if (options3.providerFilter.size > 0 && !options3.providerFilter.has(_snippetSuggestSupport)) {
      return;
    }
    const sw2 = new $te();
    const list2 = await _snippetSuggestSupport.provideCompletionItems(model, position, context, token);
    onCompletionList(_snippetSuggestSupport, list2, sw2);
  })();
  for (const providerGroup of registry4.orderedGroups(model)) {
    let didAddResult = false;
    await Promise.all(providerGroup.map(async (provider) => {
      if (options3.providerItemsToReuse.has(provider)) {
        const items = options3.providerItemsToReuse.get(provider);
        items.forEach((item) => result.push(item));
        didAddResult = didAddResult || items.length > 0;
        return;
      }
      if (options3.providerFilter.size > 0 && !options3.providerFilter.has(provider)) {
        return;
      }
      try {
        const sw2 = new $te();
        const list2 = await provider.provideCompletionItems(model, position, context, token);
        didAddResult = onCompletionList(provider, list2, sw2) || didAddResult;
      } catch (err) {
        $hb(err);
      }
    }));
    if (didAddResult || token.isCancellationRequested) {
      break;
    }
  }
  await snippetCompletions;
  if (token.isCancellationRequested) {
    disposables.dispose();
    return Promise.reject(new $lb());
  }
  return new $fcb(result.sort($hcb(options3.snippetSortOrder)), needsClipboard, { entries: durations, elapsed: sw.elapsed() }, disposables);
}
function defaultComparator(a, b) {
  if (a.sortTextLow && b.sortTextLow) {
    if (a.sortTextLow < b.sortTextLow) {
      return -1;
    } else if (a.sortTextLow > b.sortTextLow) {
      return 1;
    }
  }
  if (a.textLabel < b.textLabel) {
    return -1;
  } else if (a.textLabel > b.textLabel) {
    return 1;
  }
  return a.completion.kind - b.completion.kind;
}
function snippetUpComparator(a, b) {
  if (a.completion.kind !== b.completion.kind) {
    if (a.completion.kind === 27) {
      return -1;
    } else if (b.completion.kind === 27) {
      return 1;
    }
  }
  return defaultComparator(a, b);
}
function snippetDownComparator(a, b) {
  if (a.completion.kind !== b.completion.kind) {
    if (a.completion.kind === 27) {
      return 1;
    } else if (b.completion.kind === 27) {
      return -1;
    }
  }
  return defaultComparator(a, b);
}
var _snippetComparators = /* @__PURE__ */ new Map();
_snippetComparators.set(0, snippetUpComparator);
_snippetComparators.set(2, snippetDownComparator);
_snippetComparators.set(1, defaultComparator);
function $hcb(snippetConfig) {
  return _snippetComparators.get(snippetConfig);
}
$tn.registerCommand("_executeCompletionItemProvider", async (accessor, ...args2) => {
  const [uri, position, triggerCharacter, maxItemsToResolve] = args2;
  $Jg(URI.isUri(uri));
  $Jg($8C.isIPosition(position));
  $Jg(typeof triggerCharacter === "string" || !triggerCharacter);
  $Jg(typeof maxItemsToResolve === "number" || !maxItemsToResolve);
  const { completionProvider } = accessor.get($mP);
  const ref = await accessor.get($oG).createModelReference(uri);
  try {
    const result = {
      incomplete: false,
      suggestions: []
    };
    const resolving = [];
    const actualPosition = ref.object.textEditorModel.validatePosition(position);
    const completions = await $gcb(completionProvider, ref.object.textEditorModel, actualPosition, void 0, {
      triggerCharacter: triggerCharacter ?? void 0,
      triggerKind: triggerCharacter ? 1 : 0
      /* languages.CompletionTriggerKind.Invoke */
    });
    for (const item of completions.items) {
      if (resolving.length < (maxItemsToResolve ?? 0)) {
        resolving.push(item.resolve(CancellationToken.None));
      }
      result.incomplete = result.incomplete || item.container.incomplete;
      result.suggestions.push(item.completion);
    }
    try {
      await Promise.all(resolving);
      return result;
    } finally {
      setTimeout(() => completions.disposable.dispose(), 100);
    }
  } finally {
    ref.dispose();
  }
});
function $icb(editor, provider) {
  editor.getContribution("editor.contrib.suggestController")?.triggerSuggest((/* @__PURE__ */ new Set()).add(provider), void 0, true);
}
var $jcb = class {
  static isAllOff(config) {
    return config.other === "off" && config.comments === "off" && config.strings === "off";
  }
  static isAllOn(config) {
    return config.other === "on" && config.comments === "on" && config.strings === "on";
  }
  static valueFor(config, tokenType) {
    switch (tokenType) {
      case 1:
        return config.comments;
      case 2:
        return config.strings;
      default:
        return config.other;
    }
  }
};

// out-build/vs/editor/contrib/inlineCompletions/browser/controller/inlineCompletionContextKeys.js
var $ocb = class {
  static {
    this.inlineSuggestionVisible = new $nn("inlineSuggestionVisible", false, localize(1268, null));
  }
  static {
    this.inlineSuggestionHasIndentation = new $nn("inlineSuggestionHasIndentation", false, localize(1269, null));
  }
  static {
    this.inlineSuggestionHasIndentationLessThanTabSize = new $nn("inlineSuggestionHasIndentationLessThanTabSize", true, localize(1270, null));
  }
  static {
    this.suppressSuggestions = new $nn("inlineSuggestionSuppressSuggestions", void 0, localize(1271, null));
  }
  static {
    this.cursorInIndentation = new $nn("cursorInIndentation", false, localize(1272, null));
  }
  static {
    this.hasSelection = new $nn("editor.hasSelection", false, localize(1273, null));
  }
  static {
    this.cursorAtInlineEdit = new $nn("cursorAtInlineEdit", false, localize(1274, null));
  }
  static {
    this.inlineEditVisible = new $nn("inlineEditIsVisible", false, localize(1275, null));
  }
  static {
    this.tabShouldJumpToInlineEdit = new $nn("tabShouldJumpToInlineEdit", false, localize(1276, null));
  }
  static {
    this.tabShouldAcceptInlineEdit = new $nn("tabShouldAcceptInlineEdit", false, localize(1277, null));
  }
};

// out-build/vs/editor/common/model/bracketPairsTextModelPart/fixBrackets.js
function $Ucb(tokens, languageConfigurationService) {
  const denseKeyProvider = new $CF();
  const bracketTokens = new $UF(denseKeyProvider, (languageId) => languageConfigurationService.getLanguageConfiguration(languageId));
  const tokenizer = new $WF(new StaticTokenizerSource([tokens]), bracketTokens);
  const node = $HG(tokenizer, [], void 0, true);
  let str = "";
  const line = tokens.getLineContent();
  function processNode(node2, offset) {
    if (node2.kind === 2) {
      processNode(node2.openingBracket, offset);
      offset = $kF(offset, node2.openingBracket.length);
      if (node2.child) {
        processNode(node2.child, offset);
        offset = $kF(offset, node2.child.length);
      }
      if (node2.closingBracket) {
        processNode(node2.closingBracket, offset);
        offset = $kF(offset, node2.closingBracket.length);
      } else {
        const singleLangBracketTokens = bracketTokens.getSingleLanguageBracketTokens(node2.openingBracket.languageId);
        const closingTokenText = singleLangBracketTokens.findClosingTokenText(node2.openingBracket.bracketIds);
        str += closingTokenText;
      }
    } else if (node2.kind === 3) {
    } else if (node2.kind === 0 || node2.kind === 1) {
      str += line.substring($jF(offset), $jF($kF(offset, node2.length)));
    } else if (node2.kind === 4) {
      for (const child of node2.children) {
        processNode(child, offset);
        offset = $kF(offset, child.length);
      }
    }
  }
  processNode(node, $eF);
  return str;
}
var StaticTokenizerSource = class {
  constructor(a) {
    this.a = a;
    this.tokenization = {
      getLineTokens: (lineNumber) => {
        return this.a[lineNumber - 1];
      }
    };
  }
  getValue() {
    return this.a.map((l) => l.getLineContent()).join("\n");
  }
  getLineCount() {
    return this.a.length;
  }
  getLineLength(lineNumber) {
    return this.a[lineNumber - 1].getLineContent().length;
  }
};

// out-build/vs/editor/common/tokenizationTextModelPart.js
var $$F = class _$$F {
  static replace(range, text2) {
    return new _$$F($cD.replace(range, text2), null);
  }
  constructor(lineEdit, additionalLines) {
    this.lineEdit = lineEdit;
    this.additionalLines = additionalLines;
  }
};
var BackgroundTokenizationState;
(function(BackgroundTokenizationState2) {
  BackgroundTokenizationState2[BackgroundTokenizationState2["InProgress"] = 1] = "InProgress";
  BackgroundTokenizationState2[BackgroundTokenizationState2["Completed"] = 2] = "Completed";
})(BackgroundTokenizationState || (BackgroundTokenizationState = {}));

// out-build/vs/editor/contrib/inlineCompletions/browser/utils.js
var array = [];
function $Ecb() {
  return array;
}
var $Fcb = class {
  constructor(startColumn, endColumnExclusive) {
    this.startColumn = startColumn;
    this.endColumnExclusive = endColumnExclusive;
    if (startColumn > endColumnExclusive) {
      throw new $vb(`startColumn ${startColumn} cannot be after endColumnExclusive ${endColumnExclusive}`);
    }
  }
  toRange(lineNumber) {
    return new $9C(lineNumber, this.startColumn, lineNumber, this.endColumnExclusive);
  }
  equals(other) {
    return this.startColumn === other.startColumn && this.endColumnExclusive === other.endColumnExclusive;
  }
};
function $Gcb(pos1, pos2) {
  return new $8C(pos1.lineNumber + pos2.lineNumber - 1, pos2.lineNumber === 1 ? pos1.column + pos2.column - 1 : pos2.column);
}
function $Hcb(pos1, pos2) {
  return new $8C(pos1.lineNumber - pos2.lineNumber + 1, pos1.lineNumber - pos2.lineNumber === 0 ? pos1.column - pos2.column + 1 : pos1.column);
}
function $Icb(text2, pos) {
  let subtext = "";
  const lines = $Nf(text2);
  for (let i2 = pos.lineNumber - 1; i2 < lines.length; i2++) {
    subtext += lines[i2].substring(i2 === pos.lineNumber - 1 ? pos.column - 1 : 0);
  }
  return subtext;
}
function $Jcb(edits) {
  const sortPerm = $dc.createSortPermutation(edits, $9b((e) => e.range, $9C.compareRangesUsingStarts));
  const edit3 = new $iD(sortPerm.apply(edits));
  const sortedNewRanges = edit3.getNewRanges();
  const newRanges = sortPerm.inverse().apply(sortedNewRanges);
  return newRanges.map((range) => range.getEndPosition());
}
function $Kcb(items, store) {
  const result = $he("result", []);
  const innerObservables = [];
  store.add($td((reader) => {
    const itemsValue = items.read(reader);
    $ce((tx) => {
      if (itemsValue.length !== innerObservables.length) {
        innerObservables.length = itemsValue.length;
        for (let i2 = 0; i2 < innerObservables.length; i2++) {
          if (!innerObservables[i2]) {
            innerObservables[i2] = $he("item", itemsValue[i2]);
          }
        }
        result.set([...innerObservables], tx);
      }
      innerObservables.forEach((o, i2) => o.set(itemsValue[i2], tx));
    });
  }));
  return result;
}
var $Lcb = class {
  constructor(a) {
    this.a = a;
  }
  bind(key2, obs) {
    return $H9(key2, this.a, obs instanceof Function ? obs : (reader) => obs.read(reader));
  }
};

// out-build/vs/editor/contrib/inlineCompletions/browser/model/provideInlineCompletions.js
async function $Vcb(registry4, positionOrRange, model, context, baseToken = CancellationToken.None, languageConfigurationService) {
  const tokenSource = new $ad(baseToken);
  const token = tokenSource.token;
  const defaultReplaceRange = positionOrRange instanceof $8C ? getDefaultRange(positionOrRange, model) : positionOrRange;
  const providers2 = registry4.all(model);
  const multiMap = new $Lc();
  for (const provider of providers2) {
    if (provider.groupId) {
      multiMap.add(provider.groupId, provider);
    }
  }
  function getPreferredProviders(provider) {
    if (!provider.yieldsToGroupIds) {
      return [];
    }
    const result2 = [];
    for (const groupId of provider.yieldsToGroupIds || []) {
      const providers3 = multiMap.get(groupId);
      for (const p of providers3) {
        result2.push(p);
      }
    }
    return result2;
  }
  const states = /* @__PURE__ */ new Map();
  const seen = /* @__PURE__ */ new Set();
  function findPreferredProviderCircle(provider, stack) {
    stack = [...stack, provider];
    if (seen.has(provider)) {
      return stack;
    }
    seen.add(provider);
    try {
      const preferred = getPreferredProviders(provider);
      for (const p of preferred) {
        const c = findPreferredProviderCircle(p, stack);
        if (c) {
          return c;
        }
      }
    } finally {
      seen.delete(provider);
    }
    return void 0;
  }
  function queryProviderOrPreferredProvider(provider) {
    const state = states.get(provider);
    if (state) {
      return state;
    }
    const circle = findPreferredProviderCircle(provider, []);
    if (circle) {
      $hb(new Error(`Inline completions: cyclic yield-to dependency detected. Path: ${circle.map((s) => s.toString ? s.toString() : "" + s).join(" -> ")}`));
    }
    const deferredPromise = new $gi();
    states.set(provider, deferredPromise.p);
    (async () => {
      if (!circle) {
        const preferred = getPreferredProviders(provider);
        for (const p of preferred) {
          const result2 = await queryProviderOrPreferredProvider(p);
          if (result2 && result2.inlineCompletions.items.length > 0) {
            return void 0;
          }
        }
      }
      return query(provider);
    })().then((c) => deferredPromise.complete(c), (e) => deferredPromise.error(e));
    return deferredPromise.p;
  }
  async function query(provider) {
    let result2;
    try {
      if (positionOrRange instanceof $8C) {
        result2 = await provider.provideInlineCompletions(model, positionOrRange, context, token);
      } else {
        result2 = await provider.provideInlineEditsForRange?.(model, positionOrRange, context, token);
      }
    } catch (e) {
      $hb(e);
      return void 0;
    }
    if (!result2) {
      return void 0;
    }
    const list2 = new $Xcb(result2, provider);
    runWhenCancelled(token, () => list2.removeRef());
    return list2;
  }
  const inlineCompletionLists = $ji.fromPromisesResolveOrder(providers2.map(queryProviderOrPreferredProvider));
  if (token.isCancellationRequested) {
    tokenSource.dispose(true);
    return new $Wcb([], /* @__PURE__ */ new Set(), []);
  }
  const result = await addRefAndCreateResult(context, inlineCompletionLists, defaultReplaceRange, model, languageConfigurationService);
  tokenSource.dispose(true);
  return result;
}
function runWhenCancelled(token, callback) {
  if (token.isCancellationRequested) {
    callback();
    return $3c.None;
  } else {
    const listener = token.onCancellationRequested(() => {
      listener.dispose();
      callback();
    });
    return { dispose: () => listener.dispose() };
  }
}
async function addRefAndCreateResult(context, inlineCompletionLists, defaultReplaceRange, model, languageConfigurationService) {
  const itemsByHash = /* @__PURE__ */ new Map();
  let shouldStop = false;
  const lists = [];
  for await (const completions of inlineCompletionLists) {
    if (!completions) {
      continue;
    }
    completions.addRef();
    lists.push(completions);
    for (const item of completions.inlineCompletions.items) {
      if (!context.includeInlineEdits && item.isInlineEdit) {
        continue;
      }
      if (!context.includeInlineCompletions && !item.isInlineEdit) {
        continue;
      }
      const inlineCompletionItem = $Ycb.from(item, completions, defaultReplaceRange, model, languageConfigurationService);
      itemsByHash.set(inlineCompletionItem.hash(), inlineCompletionItem);
      if (!item.isInlineEdit && context.triggerKind === InlineCompletionTriggerKind.Automatic) {
        const minifiedEdit = inlineCompletionItem.toSingleTextEdit().removeCommonPrefix(new $8$(model));
        if (!minifiedEdit.isEmpty) {
          shouldStop = true;
        }
      }
    }
    if (shouldStop) {
      break;
    }
  }
  return new $Wcb(Array.from(itemsByHash.values()), new Set(itemsByHash.keys()), lists);
}
var $Wcb = class {
  constructor(completions, a, b) {
    this.completions = completions;
    this.a = a;
    this.b = b;
  }
  has(item) {
    return this.a.has(item.hash());
  }
  dispose() {
    for (const result of this.b) {
      result.removeRef();
    }
  }
};
var $Xcb = class {
  constructor(inlineCompletions, provider) {
    this.inlineCompletions = inlineCompletions;
    this.provider = provider;
    this.a = 1;
  }
  addRef() {
    this.a++;
  }
  removeRef() {
    this.a--;
    if (this.a === 0) {
      this.provider.freeInlineCompletions(this.inlineCompletions);
    }
  }
};
var $Ycb = class _$Ycb {
  static from(inlineCompletion, source, defaultReplaceRange, textModel, languageConfigurationService) {
    let insertText;
    let snippetInfo;
    let range = inlineCompletion.range ? $9C.lift(inlineCompletion.range) : defaultReplaceRange;
    if (typeof inlineCompletion.insertText === "string") {
      insertText = inlineCompletion.insertText;
      if (languageConfigurationService && inlineCompletion.completeBracketPairs) {
        insertText = closeBrackets(insertText, range.getStartPosition(), textModel, languageConfigurationService);
        const diff3 = insertText.length - inlineCompletion.insertText.length;
        if (diff3 !== 0) {
          range = new $9C(range.startLineNumber, range.startColumn, range.endLineNumber, range.endColumn + diff3);
        }
      }
      snippetInfo = void 0;
    } else if ("snippet" in inlineCompletion.insertText) {
      const preBracketCompletionLength = inlineCompletion.insertText.snippet.length;
      if (languageConfigurationService && inlineCompletion.completeBracketPairs) {
        inlineCompletion.insertText.snippet = closeBrackets(inlineCompletion.insertText.snippet, range.getStartPosition(), textModel, languageConfigurationService);
        const diff3 = inlineCompletion.insertText.snippet.length - preBracketCompletionLength;
        if (diff3 !== 0) {
          range = new $9C(range.startLineNumber, range.startColumn, range.endLineNumber, range.endColumn + diff3);
        }
      }
      const snippet = new $0_().parse(inlineCompletion.insertText.snippet);
      if (snippet.children.length === 1 && snippet.children[0] instanceof $2_) {
        insertText = snippet.children[0].value;
        snippetInfo = void 0;
      } else {
        insertText = snippet.toString();
        snippetInfo = {
          snippet: inlineCompletion.insertText.snippet,
          range
        };
      }
    } else {
      $hd(inlineCompletion.insertText);
    }
    return new _$Ycb(insertText, inlineCompletion.command, inlineCompletion.shownCommand, range, insertText, snippetInfo, inlineCompletion.additionalTextEdits || $Ecb(), inlineCompletion, source);
  }
  constructor(filterText, command4, shownCommand, range, insertText, snippetInfo, additionalTextEdits, sourceInlineCompletion, source) {
    this.filterText = filterText;
    this.command = command4;
    this.shownCommand = shownCommand;
    this.range = range;
    this.insertText = insertText;
    this.snippetInfo = snippetInfo;
    this.additionalTextEdits = additionalTextEdits;
    this.sourceInlineCompletion = sourceInlineCompletion;
    this.source = source;
    this.a = false;
    filterText = filterText.replace(/\r\n|\r/g, "\n");
    insertText = filterText.replace(/\r\n|\r/g, "\n");
  }
  get didShow() {
    return this.a;
  }
  markAsShown() {
    this.a = true;
  }
  withRange(updatedRange) {
    return new _$Ycb(this.filterText, this.command, this.shownCommand, updatedRange, this.insertText, this.snippetInfo, this.additionalTextEdits, this.sourceInlineCompletion, this.source);
  }
  hash() {
    return JSON.stringify({ insertText: this.insertText, range: this.range.toString() });
  }
  toSingleTextEdit() {
    return new $jD(this.range, this.insertText);
  }
};
function getDefaultRange(position, model) {
  const word = model.getWordAtPosition(position);
  const maxColumn = model.getLineMaxColumn(position.lineNumber);
  return word ? new $9C(position.lineNumber, word.startColumn, position.lineNumber, maxColumn) : $9C.fromPositions(position, position.with(void 0, maxColumn));
}
function closeBrackets(text2, position, model, languageConfigurationService) {
  const lineStart = model.getLineContent(position.lineNumber).substring(0, position.column - 1);
  const newLine = lineStart + text2;
  const edit3 = $$F.replace($0C.ofStartAndLength(position.column - 1, newLine.length - (position.column - 1)), text2);
  const newTokens = model.tokenization.tokenizeLineWithEdit(position.lineNumber, edit3);
  const slicedTokens = newTokens?.mainLineTokens?.sliceAndInflate(position.column - 1, newLine.length, 0);
  if (!slicedTokens) {
    return text2;
  }
  const newText = $Ucb(slicedTokens, languageConfigurationService);
  return newText;
}

// out-build/vs/editor/contrib/inlineCompletions/browser/model/singleTextEditHelpers.js
function $Rcb(edit3, model, validModelRange) {
  const modelRange = validModelRange ? edit3.range.intersectRanges(validModelRange) : edit3.range;
  if (!modelRange) {
    return edit3;
  }
  const normalizedText = edit3.text.replaceAll("\r\n", "\n");
  const valueToReplace = model.getValueInRange(
    modelRange,
    1
    /* EndOfLinePreference.LF */
  );
  const commonPrefixLen = $3f(valueToReplace, normalizedText);
  const start = $gD.ofText(valueToReplace.substring(0, commonPrefixLen)).addToPosition(edit3.range.getStartPosition());
  const text2 = normalizedText.substring(commonPrefixLen);
  const range = $9C.fromPositions(start, edit3.range.getEndPosition());
  return new $jD(range, text2);
}
function $Scb(edit3, base) {
  return edit3.text.startsWith(base.text) && rangeExtends(edit3.range, base.range);
}
function rangeExtends(extendingRange, rangeToExtend) {
  return rangeToExtend.getStartPosition().equals(extendingRange.getStartPosition()) && rangeToExtend.getEndPosition().isBeforeOrEqual(extendingRange.getEndPosition());
}

// out-build/vs/editor/contrib/inlineCompletions/browser/model/inlineCompletionsSource.js
var $Zcb_1;
var $4cb_1;
var $Zcb = class $Zcb2 extends $3c {
  static {
    $Zcb_1 = this;
  }
  static {
    this.a = 0;
  }
  constructor(h3, j, m, n, r2, s, t, u) {
    super();
    this.h = h3;
    this.j = j;
    this.m = m;
    this.n = n;
    this.r = r2;
    this.s = s;
    this.t = t;
    this.u = u;
    this.b = this.B(new $4c());
    this.inlineCompletions = $je("inlineCompletions", void 0);
    this.suggestWidgetInlineCompletions = $je("suggestWidgetInlineCompletions", void 0);
    this.f = $G9("editor.inlineSuggest.logFetch", false, this.t).recomputeInitiallyAndOnChange(this.q);
    this.g = this.B(this.u.createInstance($4cb.cast(), "editor.inlineSuggest.logFetch.commandId"));
    this.loading = $he(this, false);
    this.B(this.h.onDidChangeContent(() => {
      this.b.clear();
    }));
  }
  w(entry) {
    if (this.f.get()) {
      this.s.info($3cb(entry));
    }
    this.g.log(entry);
  }
  fetch(position, context, activeInlineCompletion) {
    const request = new UpdateRequest(position, context, this.h.getVersionId());
    const target = context.selectedSuggestionInfo ? this.suggestWidgetInlineCompletions : this.inlineCompletions;
    if (this.b.value?.request.satisfies(request)) {
      return this.b.value.promise;
    } else if (target.get()?.request.satisfies(request)) {
      return Promise.resolve(true);
    }
    this.loading.set(true, void 0);
    const updateOngoing = !!this.b.value;
    this.b.clear();
    const source = new $ad();
    const promise = (async () => {
      const shouldDebounce = updateOngoing || context.triggerKind === InlineCompletionTriggerKind.Automatic;
      if (shouldDebounce) {
        await wait(this.m.get(this.h), source.token);
      }
      if (source.token.isCancellationRequested || this.q.isDisposed || this.h.getVersionId() !== request.versionId) {
        return false;
      }
      const requestId = $Zcb_1.a++;
      if (this.f.get() || this.g.isEnabled.get()) {
        this.w({ sourceId: "InlineCompletions.fetch", kind: "start", requestId, modelUri: this.h.uri.toString(), modelVersion: this.h.getVersionId(), context: { triggerKind: context.triggerKind }, time: Date.now() });
      }
      const startTime = /* @__PURE__ */ new Date();
      let updatedCompletions = void 0;
      let error = void 0;
      try {
        updatedCompletions = await $Vcb(this.n.inlineCompletionsProvider, position, this.h, context, source.token, this.r);
      } catch (e) {
        error = e;
        throw e;
      } finally {
        if (this.f.get() || this.g.isEnabled.get()) {
          if (source.token.isCancellationRequested || this.q.isDisposed || this.h.getVersionId() !== request.versionId) {
            error = "canceled";
          }
          const result = updatedCompletions?.completions.map((c) => ({
            range: c.range.toString(),
            text: c.insertText,
            isInlineEdit: !!c.sourceInlineCompletion.isInlineEdit,
            source: c.source.provider.groupId
          }));
          this.w({ sourceId: "InlineCompletions.fetch", kind: "end", requestId, durationMs: Date.now() - startTime.getTime(), error, result, time: Date.now() });
        }
      }
      if (source.token.isCancellationRequested || this.q.isDisposed || this.h.getVersionId() !== request.versionId) {
        updatedCompletions.dispose();
        return false;
      }
      const endTime = /* @__PURE__ */ new Date();
      this.m.update(this.h, endTime.getTime() - startTime.getTime());
      const completions = new $1cb(updatedCompletions, request, this.h, this.j);
      if (activeInlineCompletion) {
        const asInlineCompletion = activeInlineCompletion.toInlineCompletion(void 0);
        if (activeInlineCompletion.canBeReused(this.h, position) && !updatedCompletions.has(asInlineCompletion)) {
          completions.prepend(activeInlineCompletion.inlineCompletion, asInlineCompletion.range, true);
        }
      }
      this.b.clear();
      $ce((tx) => {
        target.set(completions, tx);
        this.loading.set(false, tx);
      });
      return true;
    })();
    const updateOperation = new UpdateOperation(request, source, promise);
    this.b.value = updateOperation;
    return promise;
  }
  clear(tx) {
    this.b.clear();
    this.inlineCompletions.set(void 0, tx);
    this.suggestWidgetInlineCompletions.set(void 0, tx);
  }
  clearSuggestWidgetInlineCompletions(tx) {
    if (this.b.value?.request.context.selectedSuggestionInfo) {
      this.b.clear();
    }
    this.suggestWidgetInlineCompletions.set(void 0, tx);
  }
  cancelUpdate() {
    this.b.clear();
  }
};
$Zcb = $Zcb_1 = __decorate([
  __param(3, $mP),
  __param(4, $NF),
  __param(5, $wn),
  __param(6, $kl),
  __param(7, $Pk)
], $Zcb);
function wait(ms, cancellationToken) {
  return new Promise((resolve) => {
    let d = void 0;
    const handle2 = setTimeout(() => {
      if (d) {
        d.dispose();
      }
      resolve();
    }, ms);
    if (cancellationToken) {
      d = cancellationToken.onCancellationRequested(() => {
        clearTimeout(handle2);
        if (d) {
          d.dispose();
        }
        resolve();
      });
    }
  });
}
var UpdateRequest = class {
  constructor(position, context, versionId) {
    this.position = position;
    this.context = context;
    this.versionId = versionId;
  }
  satisfies(other) {
    return this.position.equals(other.position) && $qd(this.context.selectedSuggestionInfo, other.context.selectedSuggestionInfo, $pd()) && (other.context.triggerKind === InlineCompletionTriggerKind.Automatic || this.context.triggerKind === InlineCompletionTriggerKind.Explicit) && this.versionId === other.versionId;
  }
  get isExplicitRequest() {
    return this.context.triggerKind === InlineCompletionTriggerKind.Explicit;
  }
};
var UpdateOperation = class {
  constructor(request, cancellationTokenSource, promise) {
    this.request = request;
    this.cancellationTokenSource = cancellationTokenSource;
    this.promise = promise;
  }
  dispose() {
    this.cancellationTokenSource.cancel();
  }
};
var $1cb = class {
  get inlineCompletions() {
    return this.a;
  }
  constructor(g, request, h3, j) {
    this.g = g;
    this.request = request;
    this.h = h3;
    this.j = j;
    this.b = 1;
    this.f = [];
    const ids = h3.deltaDecorations([], g.completions.map((i2) => ({
      range: i2.range,
      options: {
        description: "inline-completion-tracking-range"
      }
    })));
    this.a = g.completions.map((i2, index) => new $2cb(i2, ids[index], this.h, this.j, this.request));
  }
  clone() {
    this.b++;
    return this;
  }
  dispose() {
    this.b--;
    if (this.b === 0) {
      setTimeout(() => {
        if (!this.h.isDisposed()) {
          this.h.deltaDecorations(this.a.map((i2) => i2.decorationId), []);
        }
      }, 0);
      this.g.dispose();
      for (const i2 of this.f) {
        i2.source.removeRef();
      }
    }
  }
  prepend(inlineCompletion, range, addRefToSource) {
    if (addRefToSource) {
      inlineCompletion.source.addRef();
    }
    const id2 = this.h.deltaDecorations([], [{
      range,
      options: {
        description: "inline-completion-tracking-range"
      }
    }])[0];
    this.a.unshift(new $2cb(inlineCompletion, id2, this.h, this.j, this.request));
    this.f.push(inlineCompletion);
  }
};
var $2cb = class {
  get forwardStable() {
    return this.inlineCompletion.source.inlineCompletions.enableForwardStability ?? false;
  }
  constructor(inlineCompletion, decorationId, b, f, request) {
    this.inlineCompletion = inlineCompletion;
    this.decorationId = decorationId;
    this.b = b;
    this.f = f;
    this.request = request;
    this.semanticId = JSON.stringify([
      this.inlineCompletion.filterText,
      this.inlineCompletion.insertText,
      this.inlineCompletion.range.getStartPosition().toString()
    ]);
    this.a = $4d({ owner: this, equalsFn: $9C.equalsRange }, (reader) => {
      this.f.read(reader);
      return this.b.getDecorationRange(this.decorationId);
    });
  }
  toInlineCompletion(reader) {
    return this.inlineCompletion.withRange(this.a.read(reader) ?? emptyRange);
  }
  toSingleTextEdit(reader) {
    return new $jD(this.a.read(reader) ?? emptyRange, this.inlineCompletion.insertText);
  }
  isVisible(model, cursorPosition, reader) {
    const minimizedReplacement = $Rcb(this.g(reader), model);
    const updatedRange = this.a.read(reader);
    if (!updatedRange || !this.inlineCompletion.range.getStartPosition().equals(updatedRange.getStartPosition()) || cursorPosition.lineNumber !== minimizedReplacement.range.startLineNumber || minimizedReplacement.isEmpty) {
      return false;
    }
    const originalValue = model.getValueInRange(
      minimizedReplacement.range,
      1
      /* EndOfLinePreference.LF */
    );
    const filterText = minimizedReplacement.text;
    const cursorPosIndex = Math.max(0, cursorPosition.column - minimizedReplacement.range.startColumn);
    let filterTextBefore = filterText.substring(0, cursorPosIndex);
    let filterTextAfter = filterText.substring(cursorPosIndex);
    let originalValueBefore = originalValue.substring(0, cursorPosIndex);
    let originalValueAfter = originalValue.substring(cursorPosIndex);
    const originalValueIndent = model.getLineIndentColumn(minimizedReplacement.range.startLineNumber);
    if (minimizedReplacement.range.startColumn <= originalValueIndent) {
      originalValueBefore = originalValueBefore.trimStart();
      if (originalValueBefore.length === 0) {
        originalValueAfter = originalValueAfter.trimStart();
      }
      filterTextBefore = filterTextBefore.trimStart();
      if (filterTextBefore.length === 0) {
        filterTextAfter = filterTextAfter.trimStart();
      }
    }
    return filterTextBefore.startsWith(originalValueBefore) && !!$Nl(originalValueAfter, filterTextAfter);
  }
  canBeReused(model, position) {
    const updatedRange = this.a.read(void 0);
    const result = !!updatedRange && updatedRange.containsPosition(position) && this.isVisible(model, position, void 0) && $gD.ofRange(updatedRange).isGreaterThanOrEqualTo($gD.ofRange(this.inlineCompletion.range));
    return result;
  }
  g(reader) {
    return new $jD(this.a.read(reader) ?? emptyRange, this.inlineCompletion.filterText);
  }
};
var emptyRange = new $9C(1, 1, 1, 1);
function $3cb(entry) {
  return entry.sourceId + " @@ " + JSON.stringify({ ...entry, sourceId: void 0 });
}
var $4cb = $4cb_1 = class $4cb2 extends $3c {
  static cast() {
    return this;
  }
  constructor(b, f, g) {
    super();
    this.b = b;
    this.f = f;
    this.g = g;
    this.a = $5cb(this.b, this.f).recomputeInitiallyAndOnChange(this.q);
    this.isEnabled = this.a.map((v) => v !== void 0);
  }
  log(data) {
    const commandId = this.a.get();
    if (!commandId) {
      return false;
    }
    this.g.executeCommand(commandId, data);
    return true;
  }
};
$4cb = $4cb_1 = __decorate([
  __param(1, $on),
  __param(2, $sn)
], $4cb);
function $5cb(key2, contextKeyService) {
  return $Dd(contextKeyService.onDidChangeContext, () => contextKeyService.getContextKeyValue(key2));
}

// out-build/vs/editor/contrib/inlineCompletions/browser/model/changeRecorder.js
var $zhb = class $zhb2 extends $3c {
  constructor(b, c) {
    super();
    this.b = b;
    this.c = c;
    this.a = this.B(this.c.createInstance($4cb.cast(), "editor.inlineSuggest.logChangeReason.commandId"));
    this.B($xd((reader, store) => {
      if (!(this.b instanceof $D9)) {
        return;
      }
      if (!this.a.isEnabled.read(reader)) {
        return;
      }
      const sources = [];
      store.add(this.b.onBeforeExecuteEdit(({ source }) => {
        if (source) {
          sources.push(source);
        }
      }));
      store.add(this.b.onDidChangeModelContent((e) => {
        const tm = this.b.getModel();
        if (!tm) {
          return;
        }
        for (const source of sources) {
          const data = {
            sourceId: "TextModel.setChangeReason",
            source,
            time: Date.now(),
            modelUri: tm.uri.toString(),
            modelVersion: tm.getVersionId()
          };
          this.a.log(data);
        }
        sources.length = 0;
      }));
    }));
  }
};
$zhb = __decorate([
  __param(1, $Pk)
], $zhb);

// out-build/vs/editor/contrib/snippet/browser/snippetVariables.js
var $scb = Object.freeze({
  "CURRENT_YEAR": true,
  "CURRENT_YEAR_SHORT": true,
  "CURRENT_MONTH": true,
  "CURRENT_DATE": true,
  "CURRENT_HOUR": true,
  "CURRENT_MINUTE": true,
  "CURRENT_SECOND": true,
  "CURRENT_DAY_NAME": true,
  "CURRENT_DAY_NAME_SHORT": true,
  "CURRENT_MONTH_NAME": true,
  "CURRENT_MONTH_NAME_SHORT": true,
  "CURRENT_SECONDS_UNIX": true,
  "CURRENT_TIMEZONE_OFFSET": true,
  "SELECTION": true,
  "CLIPBOARD": true,
  "TM_SELECTED_TEXT": true,
  "TM_CURRENT_LINE": true,
  "TM_CURRENT_WORD": true,
  "TM_LINE_INDEX": true,
  "TM_LINE_NUMBER": true,
  "TM_FILENAME": true,
  "TM_FILENAME_BASE": true,
  "TM_DIRECTORY": true,
  "TM_FILEPATH": true,
  "CURSOR_INDEX": true,
  // 0-offset
  "CURSOR_NUMBER": true,
  // 1-offset
  "RELATIVE_FILEPATH": true,
  "BLOCK_COMMENT_START": true,
  "BLOCK_COMMENT_END": true,
  "LINE_COMMENT": true,
  "WORKSPACE_NAME": true,
  "WORKSPACE_FOLDER": true,
  "RANDOM": true,
  "RANDOM_HEX": true,
  "UUID": true
});
var $tcb = class {
  constructor(a) {
    this.a = a;
  }
  resolve(variable) {
    for (const delegate of this.a) {
      const value = delegate.resolve(variable);
      if (value !== void 0) {
        return value;
      }
    }
    return void 0;
  }
};
var $ucb = class {
  constructor(a, b, c, d) {
    this.a = a;
    this.b = b;
    this.c = c;
    this.d = d;
  }
  resolve(variable) {
    const { name } = variable;
    if (name === "SELECTION" || name === "TM_SELECTED_TEXT") {
      let value = this.a.getValueInRange(this.b) || void 0;
      let isMultiline2 = this.b.startLineNumber !== this.b.endLineNumber;
      if (!value && this.d) {
        const info = this.d.getLastOvertypedInfo(this.c);
        if (info) {
          value = info.value;
          isMultiline2 = info.multiline;
        }
      }
      if (value && isMultiline2 && variable.snippet) {
        const line = this.a.getLineContent(this.b.startLineNumber);
        const lineLeadingWhitespace = $Pf(line, 0, this.b.startColumn - 1);
        let varLeadingWhitespace = lineLeadingWhitespace;
        variable.snippet.walk((marker) => {
          if (marker === variable) {
            return false;
          }
          if (marker instanceof $2_) {
            varLeadingWhitespace = $Pf($Mf(marker.value).pop());
          }
          return true;
        });
        const whitespaceCommonLength = $3f(varLeadingWhitespace, lineLeadingWhitespace);
        value = value.replace(/(\r\n|\r|\n)(.*)/g, (m, newline2, rest) => `${newline2}${varLeadingWhitespace.substr(whitespaceCommonLength)}${rest}`);
      }
      return value;
    } else if (name === "TM_CURRENT_LINE") {
      return this.a.getLineContent(this.b.positionLineNumber);
    } else if (name === "TM_CURRENT_WORD") {
      const info = this.a.getWordAtPosition({
        lineNumber: this.b.positionLineNumber,
        column: this.b.positionColumn
      });
      return info && info.word || void 0;
    } else if (name === "TM_LINE_INDEX") {
      return String(this.b.positionLineNumber - 1);
    } else if (name === "TM_LINE_NUMBER") {
      return String(this.b.positionLineNumber);
    } else if (name === "CURSOR_INDEX") {
      return String(this.c);
    } else if (name === "CURSOR_NUMBER") {
      return String(this.c + 1);
    }
    return void 0;
  }
};
var $vcb = class {
  constructor(a, b) {
    this.a = a;
    this.b = b;
  }
  resolve(variable) {
    const { name } = variable;
    if (name === "TM_FILENAME") {
      return $rc(this.b.uri.fsPath);
    } else if (name === "TM_FILENAME_BASE") {
      const name2 = $rc(this.b.uri.fsPath);
      const idx = name2.lastIndexOf(".");
      if (idx <= 0) {
        return name2;
      } else {
        return name2.slice(0, idx);
      }
    } else if (name === "TM_DIRECTORY") {
      if ($qc(this.b.uri.fsPath) === ".") {
        return "";
      }
      return this.a.getUriLabel($uh(this.b.uri));
    } else if (name === "TM_FILEPATH") {
      return this.a.getUriLabel(this.b.uri);
    } else if (name === "RELATIVE_FILEPATH") {
      return this.a.getUriLabel(this.b.uri, { relative: true, noPrefix: true });
    }
    return void 0;
  }
};
var $wcb = class {
  constructor(a, b, c, d) {
    this.a = a;
    this.b = b;
    this.c = c;
    this.d = d;
  }
  resolve(variable) {
    if (variable.name !== "CLIPBOARD") {
      return void 0;
    }
    const clipboardText = this.a();
    if (!clipboardText) {
      return void 0;
    }
    if (this.d) {
      const lines = clipboardText.split(/\r\n|\n|\r/).filter((s) => !$vf(s));
      if (lines.length === this.c) {
        return lines[this.b];
      }
    }
    return clipboardText;
  }
};
var $xcb = class $xcb2 {
  constructor(a, b, c) {
    this.a = a;
    this.b = b;
    this.c = c;
  }
  resolve(variable) {
    const { name } = variable;
    const langId = this.a.getLanguageIdAtPosition(this.b.selectionStartLineNumber, this.b.selectionStartColumn);
    const config = this.c.getLanguageConfiguration(langId).comments;
    if (!config) {
      return void 0;
    }
    if (name === "LINE_COMMENT") {
      return config.lineCommentToken || void 0;
    } else if (name === "BLOCK_COMMENT_START") {
      return config.blockCommentStartToken || void 0;
    } else if (name === "BLOCK_COMMENT_END") {
      return config.blockCommentEndToken || void 0;
    }
    return void 0;
  }
};
$xcb = __decorate([
  __param(2, $NF)
], $xcb);
var $ycb = class _$ycb {
  constructor() {
    this.e = /* @__PURE__ */ new Date();
  }
  static {
    this.a = [localize(1444, null), localize(1445, null), localize(1446, null), localize(1447, null), localize(1448, null), localize(1449, null), localize(1450, null)];
  }
  static {
    this.b = [localize(1451, null), localize(1452, null), localize(1453, null), localize(1454, null), localize(1455, null), localize(1456, null), localize(1457, null)];
  }
  static {
    this.c = [localize(1458, null), localize(1459, null), localize(1460, null), localize(1461, null), localize(1462, null), localize(1463, null), localize(1464, null), localize(1465, null), localize(1466, null), localize(1467, null), localize(1468, null), localize(1469, null)];
  }
  static {
    this.d = [localize(1470, null), localize(1471, null), localize(1472, null), localize(1473, null), localize(1474, null), localize(1475, null), localize(1476, null), localize(1477, null), localize(1478, null), localize(1479, null), localize(1480, null), localize(1481, null)];
  }
  resolve(variable) {
    const { name } = variable;
    if (name === "CURRENT_YEAR") {
      return String(this.e.getFullYear());
    } else if (name === "CURRENT_YEAR_SHORT") {
      return String(this.e.getFullYear()).slice(-2);
    } else if (name === "CURRENT_MONTH") {
      return String(this.e.getMonth().valueOf() + 1).padStart(2, "0");
    } else if (name === "CURRENT_DATE") {
      return String(this.e.getDate().valueOf()).padStart(2, "0");
    } else if (name === "CURRENT_HOUR") {
      return String(this.e.getHours().valueOf()).padStart(2, "0");
    } else if (name === "CURRENT_MINUTE") {
      return String(this.e.getMinutes().valueOf()).padStart(2, "0");
    } else if (name === "CURRENT_SECOND") {
      return String(this.e.getSeconds().valueOf()).padStart(2, "0");
    } else if (name === "CURRENT_DAY_NAME") {
      return _$ycb.a[this.e.getDay()];
    } else if (name === "CURRENT_DAY_NAME_SHORT") {
      return _$ycb.b[this.e.getDay()];
    } else if (name === "CURRENT_MONTH_NAME") {
      return _$ycb.c[this.e.getMonth()];
    } else if (name === "CURRENT_MONTH_NAME_SHORT") {
      return _$ycb.d[this.e.getMonth()];
    } else if (name === "CURRENT_SECONDS_UNIX") {
      return String(Math.floor(this.e.getTime() / 1e3));
    } else if (name === "CURRENT_TIMEZONE_OFFSET") {
      const rawTimeOffset = this.e.getTimezoneOffset();
      const sign = rawTimeOffset > 0 ? "-" : "+";
      const hours = Math.trunc(Math.abs(rawTimeOffset / 60));
      const hoursString = hours < 10 ? "0" + hours : hours;
      const minutes = Math.abs(rawTimeOffset) - hours * 60;
      const minutesString = minutes < 10 ? "0" + minutes : minutes;
      return sign + hoursString + ":" + minutesString;
    }
    return void 0;
  }
};
var $zcb = class {
  constructor(a) {
    this.a = a;
  }
  resolve(variable) {
    if (!this.a) {
      return void 0;
    }
    const workspaceIdentifier = $5k(this.a.getWorkspace());
    if ($2k(workspaceIdentifier)) {
      return void 0;
    }
    if (variable.name === "WORKSPACE_NAME") {
      return this.b(workspaceIdentifier);
    } else if (variable.name === "WORKSPACE_FOLDER") {
      return this.c(workspaceIdentifier);
    }
    return void 0;
  }
  b(workspaceIdentifier) {
    if ($1k(workspaceIdentifier)) {
      return $rc(workspaceIdentifier.uri.path);
    }
    let filename = $rc(workspaceIdentifier.configPath.path);
    if (filename.endsWith($al)) {
      filename = filename.substr(0, filename.length - $al.length - 1);
    }
    return filename;
  }
  c(workspaceIdentifier) {
    if ($1k(workspaceIdentifier)) {
      return $1t(workspaceIdentifier.uri.fsPath);
    }
    const filename = $rc(workspaceIdentifier.configPath.path);
    let folderpath = workspaceIdentifier.configPath.fsPath;
    if (folderpath.endsWith(filename)) {
      folderpath = folderpath.substr(0, folderpath.length - filename.length - 1);
    }
    return folderpath ? $1t(folderpath) : "/";
  }
};
var $Acb = class {
  resolve(variable) {
    const { name } = variable;
    if (name === "RANDOM") {
      return Math.random().toString().slice(-6);
    } else if (name === "RANDOM_HEX") {
      return Math.random().toString(16).slice(-6);
    } else if (name === "UUID") {
      return $ps();
    }
    return void 0;
  }
};

// out-build/vs/editor/contrib/snippet/browser/snippetSession.js
var $Ccb_1;
var $Bcb = class _$Bcb {
  static {
    this.f = {
      active: $WI.register({ description: "snippet-placeholder-1", stickiness: 0, className: "snippet-placeholder" }),
      inactive: $WI.register({ description: "snippet-placeholder-2", stickiness: 1, className: "snippet-placeholder" }),
      activeFinal: $WI.register({ description: "snippet-placeholder-3", stickiness: 1, className: "finish-snippet-placeholder" }),
      inactiveFinal: $WI.register({ description: "snippet-placeholder-4", stickiness: 1, className: "finish-snippet-placeholder" })
    };
  }
  constructor(g, h3, j) {
    this.g = g;
    this.h = h3;
    this.j = j;
    this.e = -1;
    this._nestingLevel = 1;
    this.d = $Eb(h3.placeholders, $4_.compareByIndex);
    this._placeholderGroupsIdx = -1;
  }
  initialize(textChange) {
    this.e = textChange.newPosition;
  }
  dispose() {
    if (this.c) {
      this.g.removeDecorations([...this.c.values()]);
    }
    this.d.length = 0;
  }
  k() {
    if (this.e === -1) {
      throw new Error(`Snippet not initialized!`);
    }
    if (this.c) {
      return;
    }
    this.c = /* @__PURE__ */ new Map();
    const model = this.g.getModel();
    this.g.changeDecorations((accessor) => {
      for (const placeholder of this.h.placeholders) {
        const placeholderOffset = this.h.offset(placeholder);
        const placeholderLen = this.h.fullLen(placeholder);
        const range = $9C.fromPositions(model.getPositionAt(this.e + placeholderOffset), model.getPositionAt(this.e + placeholderOffset + placeholderLen));
        const options3 = placeholder.isFinalTabstop ? _$Bcb.f.inactiveFinal : _$Bcb.f.inactive;
        const handle2 = accessor.addDecoration(range, options3);
        this.c.set(placeholder, handle2);
      }
    });
  }
  move(fwd) {
    if (!this.g.hasModel()) {
      return [];
    }
    this.k();
    if (this._placeholderGroupsIdx >= 0) {
      const operations = [];
      for (const placeholder of this.d[this._placeholderGroupsIdx]) {
        if (placeholder.transform) {
          const id2 = this.c.get(placeholder);
          const range = this.g.getModel().getDecorationRange(id2);
          const currentValue = this.g.getModel().getValueInRange(range);
          const transformedValueLines = placeholder.transform.resolve(currentValue).split(/\r\n|\r|\n/);
          for (let i2 = 1; i2 < transformedValueLines.length; i2++) {
            transformedValueLines[i2] = this.g.getModel().normalizeIndentation(this.j + transformedValueLines[i2]);
          }
          operations.push($bD.replace(range, transformedValueLines.join(this.g.getModel().getEOL())));
        }
      }
      if (operations.length > 0) {
        this.g.executeEdits("snippet.placeholderTransform", operations);
      }
    }
    let couldSkipThisPlaceholder = false;
    if (fwd === true && this._placeholderGroupsIdx < this.d.length - 1) {
      this._placeholderGroupsIdx += 1;
      couldSkipThisPlaceholder = true;
    } else if (fwd === false && this._placeholderGroupsIdx > 0) {
      this._placeholderGroupsIdx -= 1;
      couldSkipThisPlaceholder = true;
    } else {
    }
    const newSelections = this.g.getModel().changeDecorations((accessor) => {
      const activePlaceholders = /* @__PURE__ */ new Set();
      const selections = [];
      for (const placeholder of this.d[this._placeholderGroupsIdx]) {
        const id2 = this.c.get(placeholder);
        const range = this.g.getModel().getDecorationRange(id2);
        selections.push(new $_D(range.startLineNumber, range.startColumn, range.endLineNumber, range.endColumn));
        couldSkipThisPlaceholder = couldSkipThisPlaceholder && this.l(placeholder);
        accessor.changeDecorationOptions(id2, placeholder.isFinalTabstop ? _$Bcb.f.activeFinal : _$Bcb.f.active);
        activePlaceholders.add(placeholder);
        for (const enclosingPlaceholder of this.h.enclosingPlaceholders(placeholder)) {
          const id3 = this.c.get(enclosingPlaceholder);
          accessor.changeDecorationOptions(id3, enclosingPlaceholder.isFinalTabstop ? _$Bcb.f.activeFinal : _$Bcb.f.active);
          activePlaceholders.add(enclosingPlaceholder);
        }
      }
      for (const [placeholder, id2] of this.c) {
        if (!activePlaceholders.has(placeholder)) {
          accessor.changeDecorationOptions(id2, placeholder.isFinalTabstop ? _$Bcb.f.inactiveFinal : _$Bcb.f.inactive);
        }
      }
      return selections;
    });
    return !couldSkipThisPlaceholder ? newSelections ?? [] : this.move(fwd);
  }
  l(placeholder) {
    let marker = placeholder;
    while (marker) {
      if (marker instanceof $4_) {
        const id2 = this.c.get(marker);
        const range = this.g.getModel().getDecorationRange(id2);
        if (range.isEmpty() && marker.toString().length > 0) {
          return true;
        }
      }
      marker = marker.parent;
    }
    return false;
  }
  get isAtFirstPlaceholder() {
    return this._placeholderGroupsIdx <= 0 || this.d.length === 0;
  }
  get isAtLastPlaceholder() {
    return this._placeholderGroupsIdx === this.d.length - 1;
  }
  get hasPlaceholder() {
    return this.h.placeholders.length > 0;
  }
  /**
   * A snippet is trivial when it has no placeholder or only a final placeholder at
   * its very end
   */
  get isTrivialSnippet() {
    if (this.h.placeholders.length === 0) {
      return true;
    }
    if (this.h.placeholders.length === 1) {
      const [placeholder] = this.h.placeholders;
      if (placeholder.isFinalTabstop) {
        if (this.h.rightMostDescendant === placeholder) {
          return true;
        }
      }
    }
    return false;
  }
  computePossibleSelections() {
    const result = /* @__PURE__ */ new Map();
    for (const placeholdersWithEqualIndex of this.d) {
      let ranges;
      for (const placeholder of placeholdersWithEqualIndex) {
        if (placeholder.isFinalTabstop) {
          break;
        }
        if (!ranges) {
          ranges = [];
          result.set(placeholder.index, ranges);
        }
        const id2 = this.c.get(placeholder);
        const range = this.g.getModel().getDecorationRange(id2);
        if (!range) {
          result.delete(placeholder.index);
          break;
        }
        ranges.push(range);
      }
    }
    return result;
  }
  get activeChoice() {
    if (!this.c) {
      return void 0;
    }
    const placeholder = this.d[this._placeholderGroupsIdx][0];
    if (!placeholder?.choice) {
      return void 0;
    }
    const id2 = this.c.get(placeholder);
    if (!id2) {
      return void 0;
    }
    const range = this.g.getModel().getDecorationRange(id2);
    if (!range) {
      return void 0;
    }
    return { range, choice: placeholder.choice };
  }
  get hasChoice() {
    let result = false;
    this.h.walk((marker) => {
      result = marker instanceof $5_;
      return !result;
    });
    return result;
  }
  merge(others) {
    const model = this.g.getModel();
    this._nestingLevel *= 10;
    this.g.changeDecorations((accessor) => {
      for (const placeholder of this.d[this._placeholderGroupsIdx]) {
        const nested = others.shift();
        console.assert(nested.e !== -1);
        console.assert(!nested.c);
        const indexLastPlaceholder = nested.h.placeholderInfo.last.index;
        for (const nestedPlaceholder of nested.h.placeholderInfo.all) {
          if (nestedPlaceholder.isFinalTabstop) {
            nestedPlaceholder.index = placeholder.index + (indexLastPlaceholder + 1) / this._nestingLevel;
          } else {
            nestedPlaceholder.index = placeholder.index + nestedPlaceholder.index / this._nestingLevel;
          }
        }
        this.h.replace(placeholder, nested.h.children);
        const id2 = this.c.get(placeholder);
        accessor.removeDecoration(id2);
        this.c.delete(placeholder);
        for (const placeholder2 of nested.h.placeholders) {
          const placeholderOffset = nested.h.offset(placeholder2);
          const placeholderLen = nested.h.fullLen(placeholder2);
          const range = $9C.fromPositions(model.getPositionAt(nested.e + placeholderOffset), model.getPositionAt(nested.e + placeholderOffset + placeholderLen));
          const handle2 = accessor.addDecoration(range, _$Bcb.f.inactive);
          this.c.set(placeholder2, handle2);
        }
      }
      this.d = $Eb(this.h.placeholders, $4_.compareByIndex);
    });
  }
  getEnclosingRange() {
    let result;
    const model = this.g.getModel();
    for (const decorationId of this.c.values()) {
      const placeholderRange = model.getDecorationRange(decorationId) ?? void 0;
      if (!result) {
        result = placeholderRange;
      } else {
        result = result.plusRange(placeholderRange);
      }
    }
    return result;
  }
};
var _defaultOptions = {
  overwriteBefore: 0,
  overwriteAfter: 0,
  adjustWhitespace: true,
  clipboardText: void 0,
  overtypingCapturer: void 0
};
var $Ccb = $Ccb_1 = class $Ccb2 {
  static adjustWhitespace(model, position, adjustIndentation, snippet, filter) {
    const line = model.getLineContent(position.lineNumber);
    const lineLeadingWhitespace = $Pf(line, 0, position.column - 1);
    let snippetTextString;
    snippet.walk((marker) => {
      if (!(marker instanceof $2_) || marker.parent instanceof $5_) {
        return true;
      }
      if (filter && !filter.has(marker)) {
        return true;
      }
      const lines = marker.value.split(/\r\n|\r|\n/);
      if (adjustIndentation) {
        const offset = snippet.offset(marker);
        if (offset === 0) {
          lines[0] = model.normalizeIndentation(lines[0]);
        } else {
          snippetTextString = snippetTextString ?? snippet.toString();
          const prevChar = snippetTextString.charCodeAt(offset - 1);
          if (prevChar === 10 || prevChar === 13) {
            lines[0] = model.normalizeIndentation(lineLeadingWhitespace + lines[0]);
          }
        }
        for (let i2 = 1; i2 < lines.length; i2++) {
          lines[i2] = model.normalizeIndentation(lineLeadingWhitespace + lines[i2]);
        }
      }
      const newValue = lines.join(model.getEOL());
      if (newValue !== marker.value) {
        marker.parent.replace(marker, [new $2_(newValue)]);
        snippetTextString = void 0;
      }
      return true;
    });
    return lineLeadingWhitespace;
  }
  static adjustSelection(model, selection, overwriteBefore, overwriteAfter) {
    if (overwriteBefore !== 0 || overwriteAfter !== 0) {
      const { positionLineNumber, positionColumn } = selection;
      const positionColumnBefore = positionColumn - overwriteBefore;
      const positionColumnAfter = positionColumn + overwriteAfter;
      const range = model.validateRange({
        startLineNumber: positionLineNumber,
        startColumn: positionColumnBefore,
        endLineNumber: positionLineNumber,
        endColumn: positionColumnAfter
      });
      selection = $_D.createWithDirection(range.startLineNumber, range.startColumn, range.endLineNumber, range.endColumn, selection.getDirection());
    }
    return selection;
  }
  static createEditsAndSnippetsFromSelections(editor, template, overwriteBefore, overwriteAfter, enforceFinalTabstop, adjustWhitespace, clipboardText, overtypingCapturer, languageConfigurationService) {
    const edits = [];
    const snippets = [];
    if (!editor.hasModel()) {
      return { edits, snippets };
    }
    const model = editor.getModel();
    const workspaceService = editor.invokeWithinContext((accessor) => accessor.get($Zk));
    const modelBasedVariableResolver = editor.invokeWithinContext((accessor) => new $vcb(accessor.get($ZI), model));
    const readClipboardText = () => clipboardText;
    const firstBeforeText = model.getValueInRange($Ccb_1.adjustSelection(model, editor.getSelection(), overwriteBefore, 0));
    const firstAfterText = model.getValueInRange($Ccb_1.adjustSelection(model, editor.getSelection(), 0, overwriteAfter));
    const firstLineFirstNonWhitespace = model.getLineFirstNonWhitespaceColumn(editor.getSelection().positionLineNumber);
    const indexedSelections = editor.getSelections().map((selection, idx) => ({ selection, idx })).sort((a, b) => $9C.compareRangesUsingStarts(a.selection, b.selection));
    for (const { selection, idx } of indexedSelections) {
      let extensionBefore = $Ccb_1.adjustSelection(model, selection, overwriteBefore, 0);
      let extensionAfter = $Ccb_1.adjustSelection(model, selection, 0, overwriteAfter);
      if (firstBeforeText !== model.getValueInRange(extensionBefore)) {
        extensionBefore = selection;
      }
      if (firstAfterText !== model.getValueInRange(extensionAfter)) {
        extensionAfter = selection;
      }
      const snippetSelection = selection.setStartPosition(extensionBefore.startLineNumber, extensionBefore.startColumn).setEndPosition(extensionAfter.endLineNumber, extensionAfter.endColumn);
      const snippet = new $0_().parse(template, true, enforceFinalTabstop);
      const start = snippetSelection.getStartPosition();
      const snippetLineLeadingWhitespace = $Ccb_1.adjustWhitespace(model, start, adjustWhitespace || idx > 0 && firstLineFirstNonWhitespace !== model.getLineFirstNonWhitespaceColumn(selection.positionLineNumber), snippet);
      snippet.resolveVariables(new $tcb([
        modelBasedVariableResolver,
        new $wcb(readClipboardText, idx, indexedSelections.length, editor.getOption(
          80
          /* EditorOption.multiCursorPaste */
        ) === "spread"),
        new $ucb(model, selection, idx, overtypingCapturer),
        new $xcb(model, selection, languageConfigurationService),
        new $ycb(),
        new $zcb(workspaceService),
        new $Acb()
      ]));
      edits[idx] = $bD.replace(snippetSelection, snippet.toString());
      edits[idx].identifier = { major: idx, minor: 0 };
      edits[idx]._isTracked = true;
      snippets[idx] = new $Bcb(editor, snippet, snippetLineLeadingWhitespace);
    }
    return { edits, snippets };
  }
  static createEditsAndSnippetsFromEdits(editor, snippetEdits, enforceFinalTabstop, adjustWhitespace, clipboardText, overtypingCapturer, languageConfigurationService) {
    if (!editor.hasModel() || snippetEdits.length === 0) {
      return { edits: [], snippets: [] };
    }
    const edits = [];
    const model = editor.getModel();
    const parser2 = new $0_();
    const snippet = new $9_();
    const resolver = new $tcb([
      editor.invokeWithinContext((accessor) => new $vcb(accessor.get($ZI), model)),
      new $wcb(() => clipboardText, 0, editor.getSelections().length, editor.getOption(
        80
        /* EditorOption.multiCursorPaste */
      ) === "spread"),
      new $ucb(model, editor.getSelection(), 0, overtypingCapturer),
      new $xcb(model, editor.getSelection(), languageConfigurationService),
      new $ycb(),
      new $zcb(editor.invokeWithinContext((accessor) => accessor.get($Zk))),
      new $Acb()
    ]);
    snippetEdits = snippetEdits.sort((a, b) => $9C.compareRangesUsingStarts(a.range, b.range));
    let offset = 0;
    for (let i2 = 0; i2 < snippetEdits.length; i2++) {
      const { range, template } = snippetEdits[i2];
      if (i2 > 0) {
        const lastRange = snippetEdits[i2 - 1].range;
        const textRange = $9C.fromPositions(lastRange.getEndPosition(), range.getStartPosition());
        const textNode = new $2_(model.getValueInRange(textRange));
        snippet.appendChild(textNode);
        offset += textNode.value.length;
      }
      const newNodes = parser2.parseFragment(template, snippet);
      $Ccb_1.adjustWhitespace(model, range.getStartPosition(), true, snippet, new Set(newNodes));
      snippet.resolveVariables(resolver);
      const snippetText = snippet.toString();
      const snippetFragmentText = snippetText.slice(offset);
      offset = snippetText.length;
      const edit3 = $bD.replace(range, snippetFragmentText);
      edit3.identifier = { major: i2, minor: 0 };
      edit3._isTracked = true;
      edits.push(edit3);
    }
    parser2.ensureFinalTabstop(snippet, enforceFinalTabstop, true);
    return {
      edits,
      snippets: [new $Bcb(editor, snippet, "")]
    };
  }
  constructor(e, f, g = _defaultOptions, h3) {
    this.e = e;
    this.f = f;
    this.g = g;
    this.h = h3;
    this.c = [];
    this.d = [];
  }
  dispose() {
    $Xc(this.d);
  }
  _logInfo() {
    return `template="${this.f}", merged_templates="${this.c.join(" -> ")}"`;
  }
  insert() {
    if (!this.e.hasModel()) {
      return;
    }
    const { edits, snippets } = typeof this.f === "string" ? $Ccb_1.createEditsAndSnippetsFromSelections(this.e, this.f, this.g.overwriteBefore, this.g.overwriteAfter, false, this.g.adjustWhitespace, this.g.clipboardText, this.g.overtypingCapturer, this.h) : $Ccb_1.createEditsAndSnippetsFromEdits(this.e, this.f, false, this.g.adjustWhitespace, this.g.clipboardText, this.g.overtypingCapturer, this.h);
    this.d = snippets;
    this.e.executeEdits("snippet", edits, (_undoEdits) => {
      const undoEdits = _undoEdits.filter((edit3) => !!edit3.identifier);
      for (let idx = 0; idx < snippets.length; idx++) {
        snippets[idx].initialize(undoEdits[idx].textChange);
      }
      if (this.d[0].hasPlaceholder) {
        return this.j(true);
      } else {
        return undoEdits.map((edit3) => $_D.fromPositions(edit3.range.getEndPosition()));
      }
    });
    this.e.revealRange(this.e.getSelections()[0]);
  }
  merge(template, options3 = _defaultOptions) {
    if (!this.e.hasModel()) {
      return;
    }
    this.c.push([this.d[0]._nestingLevel, this.d[0]._placeholderGroupsIdx, template]);
    const { edits, snippets } = $Ccb_1.createEditsAndSnippetsFromSelections(this.e, template, options3.overwriteBefore, options3.overwriteAfter, true, options3.adjustWhitespace, options3.clipboardText, options3.overtypingCapturer, this.h);
    this.e.executeEdits("snippet", edits, (_undoEdits) => {
      const undoEdits = _undoEdits.filter((edit3) => !!edit3.identifier);
      for (let idx = 0; idx < snippets.length; idx++) {
        snippets[idx].initialize(undoEdits[idx].textChange);
      }
      const isTrivialSnippet = snippets[0].isTrivialSnippet;
      if (!isTrivialSnippet) {
        for (const snippet of this.d) {
          snippet.merge(snippets);
        }
        console.assert(snippets.length === 0);
      }
      if (this.d[0].hasPlaceholder && !isTrivialSnippet) {
        return this.j(void 0);
      } else {
        return undoEdits.map((edit3) => $_D.fromPositions(edit3.range.getEndPosition()));
      }
    });
  }
  next() {
    const newSelections = this.j(true);
    this.e.setSelections(newSelections);
    this.e.revealPositionInCenterIfOutsideViewport(newSelections[0].getPosition());
  }
  prev() {
    const newSelections = this.j(false);
    this.e.setSelections(newSelections);
    this.e.revealPositionInCenterIfOutsideViewport(newSelections[0].getPosition());
  }
  j(fwd) {
    const selections = [];
    for (const snippet of this.d) {
      const oneSelection = snippet.move(fwd);
      selections.push(...oneSelection);
    }
    return selections;
  }
  get isAtFirstPlaceholder() {
    return this.d[0].isAtFirstPlaceholder;
  }
  get isAtLastPlaceholder() {
    return this.d[0].isAtLastPlaceholder;
  }
  get hasPlaceholder() {
    return this.d[0].hasPlaceholder;
  }
  get hasChoice() {
    return this.d[0].hasChoice;
  }
  get activeChoice() {
    return this.d[0].activeChoice;
  }
  isSelectionWithinPlaceholders() {
    if (!this.hasPlaceholder) {
      return false;
    }
    const selections = this.e.getSelections();
    if (selections.length < this.d.length) {
      return false;
    }
    const allPossibleSelections = /* @__PURE__ */ new Map();
    for (const snippet of this.d) {
      const possibleSelections = snippet.computePossibleSelections();
      if (allPossibleSelections.size === 0) {
        for (const [index, ranges] of possibleSelections) {
          ranges.sort($9C.compareRangesUsingStarts);
          for (const selection of selections) {
            if (ranges[0].containsRange(selection)) {
              allPossibleSelections.set(index, []);
              break;
            }
          }
        }
      }
      if (allPossibleSelections.size === 0) {
        return false;
      }
      allPossibleSelections.forEach((array2, index) => {
        array2.push(...possibleSelections.get(index));
      });
    }
    selections.sort($9C.compareRangesUsingStarts);
    for (const [index, ranges] of allPossibleSelections) {
      if (ranges.length !== selections.length) {
        allPossibleSelections.delete(index);
        continue;
      }
      ranges.sort($9C.compareRangesUsingStarts);
      for (let i2 = 0; i2 < ranges.length; i2++) {
        if (!ranges[i2].containsRange(selections[i2])) {
          allPossibleSelections.delete(index);
          continue;
        }
      }
    }
    return allPossibleSelections.size > 0;
  }
  getEnclosingRange() {
    let result;
    for (const snippet of this.d) {
      const snippetRange = snippet.getEnclosingRange();
      if (!result) {
        result = snippetRange;
      } else {
        result = result.plusRange(snippetRange);
      }
    }
    return result;
  }
};
$Ccb = $Ccb_1 = __decorate([
  __param(3, $NF)
], $Ccb);

// out-build/vs/editor/contrib/snippet/browser/snippetController2.js
var $Dcb_1;
var _defaultOptions2 = {
  overwriteBefore: 0,
  overwriteAfter: 0,
  undoStopBefore: true,
  undoStopAfter: true,
  adjustWhitespace: true,
  clipboardText: void 0,
  overtypingCapturer: void 0
};
var $Dcb = class $Dcb2 {
  static {
    $Dcb_1 = this;
  }
  static {
    this.ID = "snippetController2";
  }
  static get(editor) {
    return editor.getContribution($Dcb_1.ID);
  }
  static {
    this.InSnippetMode = new $nn("inSnippetMode", false, localize(1440, null));
  }
  static {
    this.HasNextTabstop = new $nn("hasNextTabstop", false, localize(1441, null));
  }
  static {
    this.HasPrevTabstop = new $nn("hasPrevTabstop", false, localize(1442, null));
  }
  constructor(k, l, m, contextKeyService, n) {
    this.k = k;
    this.l = l;
    this.m = m;
    this.n = n;
    this.f = new $2c();
    this.g = -1;
    this.a = $Dcb_1.InSnippetMode.bindTo(contextKeyService);
    this.b = $Dcb_1.HasNextTabstop.bindTo(contextKeyService);
    this.c = $Dcb_1.HasPrevTabstop.bindTo(contextKeyService);
  }
  dispose() {
    this.a.reset();
    this.c.reset();
    this.b.reset();
    this.d?.dispose();
    this.f.dispose();
  }
  apply(edits, opts) {
    try {
      this.p(edits, typeof opts === "undefined" ? _defaultOptions2 : { ..._defaultOptions2, ...opts });
    } catch (e) {
      this.cancel();
      this.l.error(e);
      this.l.error("snippet_error");
      this.l.error("insert_edits=", edits);
      this.l.error("existing_template=", this.d ? this.d._logInfo() : "<no_session>");
    }
  }
  insert(template, opts) {
    try {
      this.p(template, typeof opts === "undefined" ? _defaultOptions2 : { ..._defaultOptions2, ...opts });
    } catch (e) {
      this.cancel();
      this.l.error(e);
      this.l.error("snippet_error");
      this.l.error("insert_template=", template);
      this.l.error("existing_template=", this.d ? this.d._logInfo() : "<no_session>");
    }
  }
  p(template, opts) {
    if (!this.k.hasModel()) {
      return;
    }
    this.f.clear();
    if (opts.undoStopBefore) {
      this.k.getModel().pushStackElement();
    }
    if (this.d && typeof template !== "string") {
      this.cancel();
    }
    if (!this.d) {
      this.g = this.k.getModel().getAlternativeVersionId();
      this.d = new $Ccb(this.k, template, opts, this.n);
      this.d.insert();
    } else {
      $Jg(typeof template === "string");
      this.d.merge(template, opts);
    }
    if (opts.undoStopAfter) {
      this.k.getModel().pushStackElement();
    }
    if (this.d?.hasChoice) {
      const provider = {
        _debugDisplayName: "snippetChoiceCompletions",
        provideCompletionItems: (model2, position) => {
          if (!this.d || model2 !== this.k.getModel() || !$8C.equals(this.k.getPosition(), position)) {
            return void 0;
          }
          const { activeChoice } = this.d;
          if (!activeChoice || activeChoice.choice.options.length === 0) {
            return void 0;
          }
          const word = model2.getValueInRange(activeChoice.range);
          const isAnyOfOptions = Boolean(activeChoice.choice.options.find((o) => o.value === word));
          const suggestions = [];
          for (let i2 = 0; i2 < activeChoice.choice.options.length; i2++) {
            const option = activeChoice.choice.options[i2];
            suggestions.push({
              kind: 13,
              label: option.value,
              insertText: option.value,
              sortText: "a".repeat(i2 + 1),
              range: activeChoice.range,
              filterText: isAnyOfOptions ? `${word}_${option.value}` : void 0,
              command: { id: "jumpToNextSnippetPlaceholder", title: localize(1443, null) }
            });
          }
          return { suggestions };
        }
      };
      const model = this.k.getModel();
      let registration;
      let isRegistered = false;
      const disable = () => {
        registration?.dispose();
        isRegistered = false;
      };
      const enable = () => {
        if (!isRegistered) {
          registration = this.m.completionProvider.register({
            language: model.getLanguageId(),
            pattern: model.uri.fsPath,
            scheme: model.uri.scheme,
            exclusive: true
          }, provider);
          this.f.add(registration);
          isRegistered = true;
        }
      };
      this.j = { provider, enable, disable };
    }
    this.q();
    this.f.add(this.k.onDidChangeModelContent((e) => e.isFlush && this.cancel()));
    this.f.add(this.k.onDidChangeModel(() => this.cancel()));
    this.f.add(this.k.onDidChangeCursorSelection(() => this.q()));
  }
  q() {
    if (!this.d || !this.k.hasModel()) {
      return;
    }
    if (this.g === this.k.getModel().getAlternativeVersionId()) {
      return this.cancel();
    }
    if (!this.d.hasPlaceholder) {
      return this.cancel();
    }
    if (this.d.isAtLastPlaceholder || !this.d.isSelectionWithinPlaceholders()) {
      this.k.getModel().pushStackElement();
      return this.cancel();
    }
    this.a.set(true);
    this.c.set(!this.d.isAtFirstPlaceholder);
    this.b.set(!this.d.isAtLastPlaceholder);
    this.r();
  }
  r() {
    if (!this.d || !this.k.hasModel()) {
      this.h = void 0;
      return;
    }
    const { activeChoice } = this.d;
    if (!activeChoice || !this.j) {
      this.j?.disable();
      this.h = void 0;
      return;
    }
    if (this.h !== activeChoice.choice) {
      this.h = activeChoice.choice;
      this.j.enable();
      queueMicrotask(() => {
        $icb(this.k, this.j.provider);
      });
    }
  }
  finish() {
    while (this.a.get()) {
      this.next();
    }
  }
  cancel(resetSelection = false) {
    this.a.reset();
    this.c.reset();
    this.b.reset();
    this.f.clear();
    this.h = void 0;
    this.d?.dispose();
    this.d = void 0;
    this.g = -1;
    if (resetSelection) {
      this.k.setSelections([this.k.getSelection()]);
    }
  }
  prev() {
    this.d?.prev();
    this.q();
  }
  next() {
    this.d?.next();
    this.q();
  }
  isInSnippet() {
    return Boolean(this.a.get());
  }
  getSessionEnclosingRange() {
    if (this.d) {
      return this.d.getEnclosingRange();
    }
    return void 0;
  }
};
$Dcb = $Dcb_1 = __decorate([
  __param(1, $wn),
  __param(2, $mP),
  __param(3, $on),
  __param(4, $NF)
], $Dcb);
$85(
  $Dcb.ID,
  $Dcb,
  4
  /* EditorContributionInstantiation.Lazy */
);
var CommandCtor = $Y5.bindToContribution($Dcb.get);
$45(new CommandCtor({
  id: "jumpToNextSnippetPlaceholder",
  precondition: $7m.and($Dcb.InSnippetMode, $Dcb.HasNextTabstop),
  handler: (ctrl) => ctrl.next(),
  kbOpts: {
    weight: 100 + 30,
    kbExpr: EditorContextKeys.textInputFocus,
    primary: 2
    /* KeyCode.Tab */
  }
}));
$45(new CommandCtor({
  id: "jumpToPrevSnippetPlaceholder",
  precondition: $7m.and($Dcb.InSnippetMode, $Dcb.HasPrevTabstop),
  handler: (ctrl) => ctrl.prev(),
  kbOpts: {
    weight: 100 + 30,
    kbExpr: EditorContextKeys.textInputFocus,
    primary: 1024 | 2
    /* KeyCode.Tab */
  }
}));
$45(new CommandCtor({
  id: "leaveSnippet",
  precondition: $Dcb.InSnippetMode,
  handler: (ctrl) => ctrl.cancel(true),
  kbOpts: {
    weight: 100 + 30,
    kbExpr: EditorContextKeys.textInputFocus,
    primary: 9,
    secondary: [
      1024 | 9
      /* KeyCode.Escape */
    ]
  }
}));
$45(new CommandCtor({
  id: "acceptSnippet",
  precondition: $Dcb.InSnippetMode,
  handler: (ctrl) => ctrl.finish()
  // kbOpts: {
  // 	weight: KeybindingWeight.EditorContrib + 30,
  // 	kbExpr: EditorContextKeys.textFocus,
  // 	primary: KeyCode.Enter,
  // }
}));

// out-build/vs/editor/contrib/inlineCompletions/browser/model/ghostText.js
var $Mcb = class {
  constructor(lineNumber, parts) {
    this.lineNumber = lineNumber;
    this.parts = parts;
  }
  equals(other) {
    return this.lineNumber === other.lineNumber && this.parts.length === other.parts.length && this.parts.every((part, index) => part.equals(other.parts[index]));
  }
  /**
   * Only used for testing/debugging.
  */
  render(documentText, debug = false) {
    return new $iD([
      ...this.parts.map((p) => new $jD($9C.fromPositions(new $8C(this.lineNumber, p.column)), debug ? `[${p.lines.join("\n")}]` : p.lines.join("\n")))
    ]).applyToString(documentText);
  }
  renderForScreenReader(lineText) {
    if (this.parts.length === 0) {
      return "";
    }
    const lastPart = this.parts[this.parts.length - 1];
    const cappedLineText = lineText.substr(0, lastPart.column - 1);
    const text2 = new $iD([
      ...this.parts.map((p) => new $jD($9C.fromPositions(new $8C(1, p.column)), p.lines.join("\n")))
    ]).applyToString(cappedLineText);
    return text2.substring(this.parts[0].column - 1);
  }
  isEmpty() {
    return this.parts.every((p) => p.lines.length === 0);
  }
  get lineCount() {
    return 1 + this.parts.reduce((r2, p) => r2 + p.lines.length - 1, 0);
  }
};
var $Ncb = class {
  constructor(column, text2, preview) {
    this.column = column;
    this.text = text2;
    this.preview = preview;
    this.lines = $Mf(this.text);
  }
  equals(other) {
    return this.column === other.column && this.lines.length === other.lines.length && this.lines.every((line, index) => line === other.lines[index]);
  }
};
var $Ocb = class {
  constructor(lineNumber, columnRange, text2, additionalReservedLineCount = 0) {
    this.lineNumber = lineNumber;
    this.columnRange = columnRange;
    this.text = text2;
    this.additionalReservedLineCount = additionalReservedLineCount;
    this.parts = [
      new $Ncb(this.columnRange.endColumnExclusive, this.text, false)
    ];
    this.newLines = $Mf(this.text);
  }
  renderForScreenReader(_lineText) {
    return this.newLines.join("\n");
  }
  render(documentText, debug = false) {
    const replaceRange = this.columnRange.toRange(this.lineNumber);
    if (debug) {
      return new $iD([
        new $jD($9C.fromPositions(replaceRange.getStartPosition()), "("),
        new $jD($9C.fromPositions(replaceRange.getEndPosition()), `)[${this.newLines.join("\n")}]`)
      ]).applyToString(documentText);
    } else {
      return new $iD([
        new $jD(replaceRange, this.newLines.join("\n"))
      ]).applyToString(documentText);
    }
  }
  get lineCount() {
    return this.newLines.length;
  }
  isEmpty() {
    return this.parts.every((p) => p.lines.length === 0);
  }
  equals(other) {
    return this.lineNumber === other.lineNumber && this.columnRange.equals(other.columnRange) && this.newLines.length === other.newLines.length && this.newLines.every((line, index) => line === other.newLines[index]) && this.additionalReservedLineCount === other.additionalReservedLineCount;
  }
};
function $Pcb(a, b) {
  return $zb(a, b, $Qcb);
}
function $Qcb(a, b) {
  if (a === b) {
    return true;
  }
  if (!a || !b) {
    return false;
  }
  if (a instanceof $Mcb && b instanceof $Mcb) {
    return a.equals(b);
  }
  if (a instanceof $Ocb && b instanceof $Ocb) {
    return a.equals(b);
  }
  return false;
}

// out-build/vs/editor/contrib/inlineCompletions/browser/model/computeGhostText.js
function $Tcb(edit3, model, mode, cursorPosition, previewSuffixLength = 0) {
  let e = $Rcb(edit3, model);
  if (e.range.endLineNumber !== e.range.startLineNumber) {
    return void 0;
  }
  const sourceLine = model.getLineContent(e.range.startLineNumber);
  const sourceIndentationLength = $Pf(sourceLine).length;
  const suggestionTouchesIndentation = e.range.startColumn - 1 <= sourceIndentationLength;
  if (suggestionTouchesIndentation) {
    const suggestionAddedIndentationLength = $Pf(e.text).length;
    const replacedIndentation = sourceLine.substring(e.range.startColumn - 1, sourceIndentationLength);
    const [startPosition, endPosition] = [e.range.getStartPosition(), e.range.getEndPosition()];
    const newStartPosition = startPosition.column + replacedIndentation.length <= endPosition.column ? startPosition.delta(0, replacedIndentation.length) : endPosition;
    const rangeThatDoesNotReplaceIndentation = $9C.fromPositions(newStartPosition, endPosition);
    const suggestionWithoutIndentationChange = e.text.startsWith(replacedIndentation) ? e.text.substring(replacedIndentation.length) : e.text.substring(suggestionAddedIndentationLength);
    e = new $jD(rangeThatDoesNotReplaceIndentation, suggestionWithoutIndentationChange);
  }
  const valueToBeReplaced = model.getValueInRange(e.range);
  const changes = cachingDiff(valueToBeReplaced, e.text);
  if (!changes) {
    return void 0;
  }
  const lineNumber = e.range.startLineNumber;
  const parts = new Array();
  if (mode === "prefix") {
    const filteredChanges = changes.filter((c) => c.originalLength === 0);
    if (filteredChanges.length > 1 || filteredChanges.length === 1 && filteredChanges[0].originalStart !== valueToBeReplaced.length) {
      return void 0;
    }
  }
  const previewStartInCompletionText = e.text.length - previewSuffixLength;
  for (const c of changes) {
    const insertColumn = e.range.startColumn + c.originalStart + c.originalLength;
    if (mode === "subwordSmart" && cursorPosition && cursorPosition.lineNumber === e.range.startLineNumber && insertColumn < cursorPosition.column) {
      return void 0;
    }
    if (c.originalLength > 0) {
      return void 0;
    }
    if (c.modifiedLength === 0) {
      continue;
    }
    const modifiedEnd = c.modifiedStart + c.modifiedLength;
    const nonPreviewTextEnd = Math.max(c.modifiedStart, Math.min(modifiedEnd, previewStartInCompletionText));
    const nonPreviewText = e.text.substring(c.modifiedStart, nonPreviewTextEnd);
    const italicText = e.text.substring(nonPreviewTextEnd, Math.max(c.modifiedStart, modifiedEnd));
    if (nonPreviewText.length > 0) {
      parts.push(new $Ncb(insertColumn, nonPreviewText, false));
    }
    if (italicText.length > 0) {
      parts.push(new $Ncb(insertColumn, italicText, true));
    }
  }
  return new $Mcb(lineNumber, parts);
}
var lastRequest = void 0;
function cachingDiff(originalValue, newValue) {
  if (lastRequest?.originalValue === originalValue && lastRequest?.newValue === newValue) {
    return lastRequest?.changes;
  } else {
    let changes = smartDiff(originalValue, newValue, true);
    if (changes) {
      const deletedChars = deletedCharacters(changes);
      if (deletedChars > 0) {
        const newChanges = smartDiff(originalValue, newValue, false);
        if (newChanges && deletedCharacters(newChanges) < deletedChars) {
          changes = newChanges;
        }
      }
    }
    lastRequest = {
      originalValue,
      newValue,
      changes
    };
    return changes;
  }
}
function deletedCharacters(changes) {
  let sum = 0;
  for (const c of changes) {
    sum += c.originalLength;
  }
  return sum;
}
function smartDiff(originalValue, newValue, smartBracketMatching) {
  if (originalValue.length > 5e3 || newValue.length > 5e3) {
    return void 0;
  }
  function getMaxCharCode(val) {
    let maxCharCode2 = 0;
    for (let i2 = 0, len = val.length; i2 < len; i2++) {
      const charCode = val.charCodeAt(i2);
      if (charCode > maxCharCode2) {
        maxCharCode2 = charCode;
      }
    }
    return maxCharCode2;
  }
  const maxCharCode = Math.max(getMaxCharCode(originalValue), getMaxCharCode(newValue));
  function getUniqueCharCode(id2) {
    if (id2 < 0) {
      throw new Error("unexpected");
    }
    return maxCharCode + id2 + 1;
  }
  function getElements(source) {
    let level = 0;
    let group2 = 0;
    const characters = new Int32Array(source.length);
    for (let i2 = 0, len = source.length; i2 < len; i2++) {
      if (smartBracketMatching && source[i2] === "(") {
        const id2 = group2 * 100 + level;
        characters[i2] = getUniqueCharCode(2 * id2);
        level++;
      } else if (smartBracketMatching && source[i2] === ")") {
        level = Math.max(level - 1, 0);
        const id2 = group2 * 100 + level;
        characters[i2] = getUniqueCharCode(2 * id2 + 1);
        if (level === 0) {
          group2++;
        }
      } else {
        characters[i2] = source.charCodeAt(i2);
      }
    }
    return characters;
  }
  const elements1 = getElements(originalValue);
  const elements2 = getElements(newValue);
  return new $7C({ getElements: () => elements1 }, { getElements: () => elements2 }).ComputeDiff(false).changes;
}

// out-build/vs/editor/contrib/inlineCompletions/browser/model/inlineEdit.js
var $6cb = class {
  constructor(edit3, isCollapsed, renderExplicitly, commands2, inlineCompletion) {
    this.edit = edit3;
    this.isCollapsed = isCollapsed;
    this.renderExplicitly = renderExplicitly;
    this.commands = commands2;
    this.inlineCompletion = inlineCompletion;
  }
  get range() {
    return this.edit.range;
  }
  get text() {
    return this.edit.text;
  }
  equals(other) {
    return this.edit.equals(other.edit) && this.isCollapsed === other.isCollapsed && this.renderExplicitly === other.renderExplicitly && this.inlineCompletion === other.inlineCompletion;
  }
};

// out-build/vs/editor/contrib/inlineCompletions/browser/model/inlineCompletionsModel.js
var $vdb = class $vdb2 extends $3c {
  get isAcceptingPartially() {
    return this.u;
  }
  constructor(textModel, G, _textModelVersionId, H, I, J, L, M, N, O) {
    super();
    this.textModel = textModel;
    this.G = G;
    this._textModelVersionId = _textModelVersionId;
    this.H = H;
    this.I = I;
    this.J = J;
    this.L = L;
    this.M = M;
    this.N = N;
    this.O = O;
    this.f = this.B(this.M.createInstance($Zcb, this.textModel, this._textModelVersionId, this.I));
    this.g = $he(this, false);
    this.h = $Hd(this);
    this.j = $Hd(this);
    this.n = $he(this, void 0);
    this.t = $2d(this, (reader) => this.H.read(reader)[0] ?? new $8C(1, 1));
    this.u = false;
    this.w = $79(this.L);
    this.y = this.w.getOption(
      64
      /* EditorOption.inlineSuggest */
    ).map((v) => !!v.edits.experimental.onlyShowWhenCloseToCursor);
    this.z = this.w.getOption(
      123
      /* EditorOption.suggest */
    ).map((v) => v.preview);
    this.C = this.w.getOption(
      123
      /* EditorOption.suggest */
    ).map((v) => v.previewMode);
    this.D = this.w.getOption(
      64
      /* EditorOption.inlineSuggest */
    ).map((v) => v.mode);
    this.F = this.w.getOption(
      64
      /* EditorOption.inlineSuggest */
    ).map((v) => !!v.edits.experimental?.enabled);
    this.P = /* @__PURE__ */ new Set([
      VersionIdChangeReason.Redo,
      VersionIdChangeReason.Undo,
      VersionIdChangeReason.AcceptWord
    ]);
    this.dontRefetchSignal = $Hd(this);
    this.R = $5d({
      owner: this,
      createEmptyChangeSummary: () => ({
        dontRefetch: false,
        preserveCurrentCompletion: false,
        inlineCompletionTriggerKind: InlineCompletionTriggerKind.Automatic,
        onlyRequestInlineEdits: false
      }),
      handleChange: (ctx, changeSummary) => {
        if (ctx.didChange(this._textModelVersionId) && this.P.has(this.Q(ctx.change))) {
          changeSummary.preserveCurrentCompletion = true;
        } else if (ctx.didChange(this.j)) {
          changeSummary.inlineCompletionTriggerKind = InlineCompletionTriggerKind.Explicit;
        } else if (ctx.didChange(this.dontRefetchSignal)) {
          changeSummary.dontRefetch = true;
        } else if (ctx.didChange(this.h)) {
          changeSummary.onlyRequestInlineEdits = true;
        }
        return true;
      }
    }, (reader, changeSummary) => {
      this.dontRefetchSignal.read(reader);
      this.h.read(reader);
      this.j.read(reader);
      const shouldUpdate = this.J.read(reader) && this.G.read(reader) || this.g.read(reader);
      if (!shouldUpdate) {
        this.f.cancelUpdate();
        return void 0;
      }
      this._textModelVersionId.read(reader);
      const suggestWidgetInlineCompletions = this.f.suggestWidgetInlineCompletions.get();
      const suggestItem = this.G.read(reader);
      if (suggestWidgetInlineCompletions && !suggestItem) {
        const inlineCompletions = this.f.inlineCompletions.get();
        $ce((tx) => {
          if (!inlineCompletions || suggestWidgetInlineCompletions.request.versionId > inlineCompletions.request.versionId) {
            this.f.inlineCompletions.set(suggestWidgetInlineCompletions.clone(), tx);
          }
          this.f.clearSuggestWidgetInlineCompletions(tx);
        });
      }
      const cursorPosition = this.t.get();
      if (changeSummary.dontRefetch) {
        return Promise.resolve(true);
      }
      const context = {
        triggerKind: changeSummary.inlineCompletionTriggerKind,
        selectedSuggestionInfo: suggestItem?.toSelectedSuggestionInfo(),
        includeInlineCompletions: !changeSummary.onlyRequestInlineEdits,
        includeInlineEdits: this.F.read(reader)
      };
      const itemToPreserveCandidate = this.selectedInlineCompletion.get();
      const itemToPreserve = changeSummary.preserveCurrentCompletion || itemToPreserveCandidate?.forwardStable ? itemToPreserveCandidate : void 0;
      return this.f.fetch(cursorPosition, context, itemToPreserve);
    });
    this.S = $he(this, void 0);
    this.U = $4d({ owner: this }, (reader) => {
      const c = this.f.inlineCompletions.read(reader);
      if (!c) {
        return void 0;
      }
      const cursorPosition = this.t.read(reader);
      let inlineEdit = void 0;
      const visibleCompletions = [];
      for (const completion of c.inlineCompletions) {
        if (!completion.inlineCompletion.sourceInlineCompletion.isInlineEdit) {
          if (completion.isVisible(this.textModel, cursorPosition, reader)) {
            visibleCompletions.push(completion);
          }
        } else {
          inlineEdit = completion;
        }
      }
      if (visibleCompletions.length !== 0) {
        inlineEdit = void 0;
      }
      return {
        inlineCompletions: visibleCompletions,
        inlineEdit
      };
    });
    this.W = $4d({ owner: this, equalsFn: $nd() }, (reader) => {
      const c = this.U.read(reader);
      return c?.inlineCompletions ?? [];
    });
    this.selectedInlineCompletionIndex = $2d(this, (reader) => {
      const selectedInlineCompletionId = this.n.read(reader);
      const filteredCompletions = this.W.read(reader);
      const idx = this.n === void 0 ? -1 : filteredCompletions.findIndex((v) => v.semanticId === selectedInlineCompletionId);
      if (idx === -1) {
        this.n.set(void 0, void 0);
        return 0;
      }
      return idx;
    });
    this.selectedInlineCompletion = $2d(this, (reader) => {
      const filteredCompletions = this.W.read(reader);
      const idx = this.selectedInlineCompletionIndex.read(reader);
      return filteredCompletions[idx];
    });
    this.activeCommands = $4d({ owner: this, equalsFn: $nd() }, (r2) => this.selectedInlineCompletion.read(r2)?.inlineCompletion.source.inlineCompletions.commands ?? []);
    this.lastTriggerKind = this.f.inlineCompletions.map(this, (v) => v?.request.context.triggerKind);
    this.inlineCompletionsCount = $2d(this, (reader) => {
      if (this.lastTriggerKind.read(reader) === InlineCompletionTriggerKind.Explicit) {
        return this.W.read(reader).length;
      } else {
        return void 0;
      }
    });
    this.state = $4d({
      owner: this,
      equalsFn: (a, b) => {
        if (!a || !b) {
          return a === b;
        }
        if (a.kind === "ghostText" && b.kind === "ghostText") {
          return $Pcb(a.ghostTexts, b.ghostTexts) && a.inlineCompletion === b.inlineCompletion && a.suggestItem === b.suggestItem;
        } else if (a.kind === "inlineEdit" && b.kind === "inlineEdit") {
          return a.inlineEdit.equals(b.inlineEdit) && a.cursorAtInlineEdit === b.cursorAtInlineEdit;
        }
        return false;
      }
    }, (reader) => {
      const model = this.textModel;
      const item = this.U.read(reader);
      if (item?.inlineEdit) {
        let edit3 = item.inlineEdit.toSingleTextEdit(reader);
        edit3 = $Rcb(edit3, model);
        const cursorPos = this.t.read(reader);
        const cursorAtInlineEdit = $_C.fromRangeInclusive(edit3.range).addMargin(1, 1).contains(cursorPos.lineNumber);
        const cursorDist = $_C.fromRange(edit3.range).distanceToLine(this.t.read(reader).lineNumber);
        if (this.y.read(reader) && cursorDist > 3 && !item.inlineEdit.request.isExplicitRequest && !this.bb.read(reader)) {
          return void 0;
        }
        const disableCollapsing = true;
        const currentItemIsCollapsed = !disableCollapsing && (cursorDist > 1 && this.S.read(reader) === item.inlineEdit.semanticId);
        const commands2 = item.inlineEdit.inlineCompletion.source.inlineCompletions.commands;
        const renderExplicitly = this.ab.read(reader);
        const inlineEdit = new $6cb(edit3, currentItemIsCollapsed, renderExplicitly, commands2 ?? [], item.inlineEdit.inlineCompletion);
        return { kind: "inlineEdit", inlineEdit, inlineCompletion: item.inlineEdit, edits: [edit3], cursorAtInlineEdit };
      }
      this.ab.set(false, void 0);
      const suggestItem = this.G.read(reader);
      if (suggestItem) {
        const suggestCompletionEdit = $Rcb(suggestItem.toSingleTextEdit(), model);
        const augmentation = this.X(suggestCompletionEdit, reader);
        const isSuggestionPreviewEnabled = this.z.read(reader);
        if (!isSuggestionPreviewEnabled && !augmentation) {
          return void 0;
        }
        const fullEdit = augmentation?.edit ?? suggestCompletionEdit;
        const fullEditPreviewLength = augmentation ? augmentation.edit.text.length - suggestCompletionEdit.text.length : 0;
        const mode = this.C.read(reader);
        const positions = this.H.read(reader);
        const edits = [fullEdit, ...$wdb(this.textModel, positions, fullEdit)];
        const ghostTexts = edits.map((edit3, idx) => $Tcb(edit3, model, mode, positions[idx], fullEditPreviewLength)).filter($Hg);
        const primaryGhostText = ghostTexts[0] ?? new $Mcb(fullEdit.range.endLineNumber, []);
        return { kind: "ghostText", edits, primaryGhostText, ghostTexts, inlineCompletion: augmentation?.completion, suggestItem };
      } else {
        if (!this.g.read(reader)) {
          return void 0;
        }
        const inlineCompletion = this.selectedInlineCompletion.read(reader);
        if (!inlineCompletion) {
          return void 0;
        }
        const replacement = inlineCompletion.toSingleTextEdit(reader);
        const mode = this.D.read(reader);
        const positions = this.H.read(reader);
        const edits = [replacement, ...$wdb(this.textModel, positions, replacement)];
        const ghostTexts = edits.map((edit3, idx) => $Tcb(edit3, model, mode, positions[idx], 0)).filter($Hg);
        if (!ghostTexts[0]) {
          return void 0;
        }
        return { kind: "ghostText", edits, primaryGhostText: ghostTexts[0], ghostTexts, inlineCompletion, suggestItem: void 0 };
      }
    });
    this.status = $2d(this, (reader) => {
      if (this.f.loading.read(reader)) {
        return "loading";
      }
      const s = this.state.read(reader);
      if (s?.kind === "ghostText") {
        return "ghostText";
      }
      if (s?.kind === "inlineEdit") {
        return "inlineEdit";
      }
      return "noSuggestion";
    });
    this.inlineCompletionState = $2d((reader) => {
      const s = this.state.read(reader);
      if (!s || s.kind !== "ghostText") {
        return void 0;
      }
      if (this.w.inComposition.read(reader)) {
        return void 0;
      }
      return s;
    });
    this.inlineEditState = $2d((reader) => {
      const s = this.state.read(reader);
      if (!s || s.kind !== "inlineEdit") {
        return void 0;
      }
      return s;
    });
    this.inlineEditAvailable = $2d((reader) => {
      const s = this.inlineEditState.read(reader);
      return !!s;
    });
    this.ghostTexts = $4d({ owner: this, equalsFn: $Pcb }, (reader) => {
      const v = this.inlineCompletionState.read(reader);
      if (!v) {
        return void 0;
      }
      return v.ghostTexts;
    });
    this.primaryGhostText = $4d({ owner: this, equalsFn: $Qcb }, (reader) => {
      const v = this.inlineCompletionState.read(reader);
      if (!v) {
        return void 0;
      }
      return v?.primaryGhostText;
    });
    this.Y = $2d(this, (reader) => {
      function isMultiLine(range) {
        return range.startLineNumber !== range.endLineNumber;
      }
      function getNonIndentationRange(model, lineNumber) {
        const columnStart = model.getLineIndentColumn(lineNumber);
        const lastNonWsColumn = model.getLineLastNonWhitespaceColumn(lineNumber);
        const columnEnd = Math.max(lastNonWsColumn, columnStart);
        return new $9C(lineNumber, columnStart, lineNumber, columnEnd);
      }
      const selections = this.w.selections.read(reader);
      return selections?.some((s) => {
        if (s.isEmpty()) {
          return this.textModel.getLineLength(s.startLineNumber) === 0;
        } else {
          return isMultiLine(s) || s.containsRange(getNonIndentationRange(this.textModel, s.startLineNumber));
        }
      });
    });
    this.tabShouldJumpToInlineEdit = $2d(this, (reader) => {
      if (this.Y.read(reader)) {
        return false;
      }
      const s = this.inlineEditState.read(reader);
      if (!s) {
        return false;
      }
      return !s.cursorAtInlineEdit;
    });
    this.tabShouldAcceptInlineEdit = $2d(this, (reader) => {
      if (this.ab.read(reader)) {
        return true;
      }
      if (this.Y.read(reader)) {
        return false;
      }
      const s = this.inlineEditState.read(reader);
      if (!s) {
        return false;
      }
      return s.cursorAtInlineEdit;
    });
    this.ab = $he(this, false);
    this.bb = $he(this, false);
    this.B($Nd(this.R));
    let lastItem = void 0;
    this.B($td((reader) => {
      const item = this.inlineCompletionState.read(reader);
      const completion = item?.inlineCompletion;
      if (completion?.semanticId !== lastItem?.semanticId) {
        lastItem = completion;
        if (completion) {
          const i2 = completion.inlineCompletion;
          const src = i2.source;
          src.provider.handleItemDidShow?.(src.inlineCompletions, i2.sourceInlineCompletion, i2.insertText);
        }
      }
    }));
    this.B($td((reader) => {
      this.w.versionId.read(reader);
      this.bb.set(false, void 0);
    }));
  }
  debugGetSelectedSuggestItem() {
    return this.G;
  }
  getIndentationInfo(reader) {
    let startsWithIndentation = false;
    let startsWithIndentationLessThanTabSize = true;
    const ghostText = this?.primaryGhostText.read(reader);
    if (!!this?.G && ghostText && ghostText.parts.length > 0) {
      const { column, lines } = ghostText.parts[0];
      const firstLine3 = lines[0];
      const indentationEndColumn = this.textModel.getLineIndentColumn(ghostText.lineNumber);
      const inIndentation = column <= indentationEndColumn;
      if (inIndentation) {
        let firstNonWsIdx = $Of(firstLine3);
        if (firstNonWsIdx === -1) {
          firstNonWsIdx = firstLine3.length - 1;
        }
        startsWithIndentation = firstNonWsIdx > 0;
        const tabSize = this.textModel.getOptions().tabSize;
        const visibleColumnIndentation = $cF.visibleColumnFromColumn(firstLine3, firstNonWsIdx + 1, tabSize);
        startsWithIndentationLessThanTabSize = visibleColumnIndentation < tabSize;
      }
    }
    return {
      startsWithIndentation,
      startsWithIndentationLessThanTabSize
    };
  }
  Q(e) {
    if (e?.isUndoing) {
      return VersionIdChangeReason.Undo;
    }
    if (e?.isRedoing) {
      return VersionIdChangeReason.Redo;
    }
    if (this.isAcceptingPartially) {
      return VersionIdChangeReason.AcceptWord;
    }
    return VersionIdChangeReason.Other;
  }
  async trigger(tx, onlyFetchInlineEdits = false) {
    $fe(tx, (tx2) => {
      if (onlyFetchInlineEdits) {
        this.h.trigger(tx2);
      }
      this.g.set(true, tx2);
    });
    await this.R.get();
  }
  async triggerExplicitly(tx, onlyFetchInlineEdits = false) {
    $fe(tx, (tx2) => {
      if (onlyFetchInlineEdits) {
        this.h.trigger(tx2);
      }
      this.g.set(true, tx2);
      this.j.trigger(tx2);
    });
    await this.R.get();
  }
  stop(stopReason = "automatic", tx) {
    $fe(tx, (tx2) => {
      if (stopReason === "explicitCancel") {
        const completion = this.state.get()?.inlineCompletion?.inlineCompletion;
        if (completion && completion.source.provider.handleRejection) {
          completion.source.provider.handleRejection(completion.source.inlineCompletions, completion.sourceInlineCompletion);
        }
      }
      this.g.set(false, tx2);
      this.f.clear(tx2);
    });
  }
  collapseInlineEdit() {
    const currentInlineEdit = this.inlineEditState.get()?.inlineCompletion;
    if (!currentInlineEdit) {
      return;
    }
    this.S.set(currentInlineEdit.semanticId, void 0);
  }
  X(suggestCompletion, reader) {
    const model = this.textModel;
    const suggestWidgetInlineCompletions = this.f.suggestWidgetInlineCompletions.read(reader);
    const candidateInlineCompletions = suggestWidgetInlineCompletions ? suggestWidgetInlineCompletions.inlineCompletions : [this.selectedInlineCompletion.read(reader)].filter($Hg);
    const augmentedCompletion = $ab(candidateInlineCompletions, (completion) => {
      let r2 = completion.toSingleTextEdit(reader);
      r2 = $Rcb(r2, model, $9C.fromPositions(r2.range.getStartPosition(), suggestCompletion.range.getEndPosition()));
      return $Scb(r2, suggestCompletion) ? { completion, edit: r2 } : void 0;
    });
    return augmentedCompletion;
  }
  async Z(delta) {
    await this.triggerExplicitly();
    const completions = this.W.get() || [];
    if (completions.length > 0) {
      const newIdx = (this.selectedInlineCompletionIndex.get() + delta + completions.length) % completions.length;
      this.n.set(completions[newIdx].semanticId, void 0);
    } else {
      this.n.set(void 0, void 0);
    }
  }
  async next() {
    await this.Z(1);
  }
  async previous() {
    await this.Z(-1);
  }
  async accept(editor) {
    if (editor.getModel() !== this.textModel) {
      throw new $vb();
    }
    let completion;
    const state = this.state.get();
    if (state?.kind === "ghostText") {
      if (!state || state.primaryGhostText.isEmpty() || !state.inlineCompletion) {
        return;
      }
      completion = state.inlineCompletion.toInlineCompletion(void 0);
    } else if (state?.kind === "inlineEdit") {
      completion = state.inlineCompletion.toInlineCompletion(void 0);
    } else {
      return;
    }
    if (completion.command) {
      completion.source.addRef();
    }
    editor.pushUndoStop();
    if (completion.snippetInfo) {
      editor.executeEdits("inlineSuggestion.accept", [
        $bD.replace(completion.range, ""),
        ...completion.additionalTextEdits
      ]);
      editor.setPosition(completion.snippetInfo.range.getStartPosition(), "inlineCompletionAccept");
      $Dcb.get(editor)?.insert(completion.snippetInfo.snippet, { undoStopBefore: false });
    } else {
      const edits = state.edits;
      const selections = $Jcb(edits).map((p) => $_D.fromPositions(p));
      editor.executeEdits("inlineSuggestion.accept", [
        ...edits.map((edit3) => $bD.replace(edit3.range, edit3.text)),
        ...completion.additionalTextEdits
      ]);
      editor.setSelections(selections, "inlineCompletionAccept");
    }
    this.stop();
    if (completion.command) {
      await this.N.executeCommand(completion.command.id, ...completion.command.arguments || []).then(void 0, $hb);
      completion.source.removeRef();
    }
    this.bb.set(true, void 0);
  }
  async acceptNextWord(editor) {
    await this.$(
      editor,
      (pos, text2) => {
        const langId = this.textModel.getLanguageIdAtPosition(pos.lineNumber, pos.column);
        const config = this.O.getLanguageConfiguration(langId);
        const wordRegExp = new RegExp(config.wordDefinition.source, config.wordDefinition.flags.replace("g", ""));
        const m1 = text2.match(wordRegExp);
        let acceptUntilIndexExclusive = 0;
        if (m1 && m1.index !== void 0) {
          if (m1.index === 0) {
            acceptUntilIndexExclusive = m1[0].length;
          } else {
            acceptUntilIndexExclusive = m1.index;
          }
        } else {
          acceptUntilIndexExclusive = text2.length;
        }
        const wsRegExp = /\s+/g;
        const m2 = wsRegExp.exec(text2);
        if (m2 && m2.index !== void 0) {
          if (m2.index + m2[0].length < acceptUntilIndexExclusive) {
            acceptUntilIndexExclusive = m2.index + m2[0].length;
          }
        }
        return acceptUntilIndexExclusive;
      },
      0
      /* PartialAcceptTriggerKind.Word */
    );
  }
  async acceptNextLine(editor) {
    await this.$(
      editor,
      (pos, text2) => {
        const m = text2.match(/\n/);
        if (m && m.index !== void 0) {
          return m.index + 1;
        }
        return text2.length;
      },
      1
      /* PartialAcceptTriggerKind.Line */
    );
  }
  async $(editor, getAcceptUntilIndex, kind) {
    if (editor.getModel() !== this.textModel) {
      throw new $vb();
    }
    const state = this.inlineCompletionState.get();
    if (!state || state.primaryGhostText.isEmpty() || !state.inlineCompletion) {
      return;
    }
    const ghostText = state.primaryGhostText;
    const completion = state.inlineCompletion.toInlineCompletion(void 0);
    if (completion.snippetInfo || completion.filterText !== completion.insertText) {
      await this.accept(editor);
      return;
    }
    const firstPart = ghostText.parts[0];
    const ghostTextPos = new $8C(ghostText.lineNumber, firstPart.column);
    const ghostTextVal = firstPart.text;
    const acceptUntilIndexExclusive = getAcceptUntilIndex(ghostTextPos, ghostTextVal);
    if (acceptUntilIndexExclusive === ghostTextVal.length && ghostText.parts.length === 1) {
      this.accept(editor);
      return;
    }
    const partialGhostTextVal = ghostTextVal.substring(0, acceptUntilIndexExclusive);
    const positions = this.H.get();
    const cursorPosition = positions[0];
    completion.source.addRef();
    try {
      this.u = true;
      try {
        editor.pushUndoStop();
        const replaceRange = $9C.fromPositions(cursorPosition, ghostTextPos);
        const newText = editor.getModel().getValueInRange(replaceRange) + partialGhostTextVal;
        const primaryEdit = new $jD(replaceRange, newText);
        const edits = [primaryEdit, ...$wdb(this.textModel, positions, primaryEdit)];
        const selections = $Jcb(edits).map((p) => $_D.fromPositions(p));
        editor.executeEdits("inlineSuggestion.accept", edits.map((edit3) => $bD.replace(edit3.range, edit3.text)));
        editor.setSelections(selections, "inlineCompletionPartialAccept");
        editor.revealPositionInCenterIfOutsideViewport(
          editor.getPosition(),
          1
          /* ScrollType.Immediate */
        );
      } finally {
        this.u = false;
      }
      if (completion.source.provider.handlePartialAccept) {
        const acceptedRange = $9C.fromPositions(completion.range.getStartPosition(), $gD.ofText(partialGhostTextVal).addToPosition(ghostTextPos));
        const text2 = editor.getModel().getValueInRange(
          acceptedRange,
          1
          /* EndOfLinePreference.LF */
        );
        completion.source.provider.handlePartialAccept(completion.source.inlineCompletions, completion.sourceInlineCompletion, text2.length, { kind });
      }
    } finally {
      completion.source.removeRef();
    }
  }
  handleSuggestAccepted(item) {
    const itemEdit = $Rcb(item.toSingleTextEdit(), this.textModel);
    const augmentedCompletion = this.X(itemEdit, void 0);
    if (!augmentedCompletion) {
      return;
    }
    const inlineCompletion = augmentedCompletion.completion.inlineCompletion;
    inlineCompletion.source.provider.handlePartialAccept?.(inlineCompletion.source.inlineCompletions, inlineCompletion.sourceInlineCompletion, itemEdit.text.length, {
      kind: 2
    });
  }
  extractReproSample() {
    const value = this.textModel.getValue();
    const item = this.state.get()?.inlineCompletion?.toInlineCompletion(void 0);
    return {
      documentValue: value,
      inlineCompletion: item?.sourceInlineCompletion
    };
  }
  jump() {
    const s = this.inlineEditState.get();
    if (!s) {
      return;
    }
    $ce((tx) => {
      this.ab.set(true, tx);
      this.dontRefetchSignal.trigger(tx);
      this.L.setPosition(s.inlineEdit.range.getStartPosition(), "inlineCompletions.jump");
      this.L.revealLine(s.inlineEdit.range.startLineNumber);
      this.L.focus();
    });
  }
  async handleInlineCompletionShown(inlineCompletion) {
    if (!inlineCompletion.shownCommand) {
      return;
    }
    if (inlineCompletion.didShow) {
      return;
    }
    inlineCompletion.markAsShown();
    await this.N.executeCommand(inlineCompletion.shownCommand.id, ...inlineCompletion.shownCommand.arguments || []);
  }
};
$vdb = __decorate([
  __param(7, $Pk),
  __param(8, $sn),
  __param(9, $NF)
], $vdb);
var VersionIdChangeReason;
(function(VersionIdChangeReason2) {
  VersionIdChangeReason2[VersionIdChangeReason2["Undo"] = 0] = "Undo";
  VersionIdChangeReason2[VersionIdChangeReason2["Redo"] = 1] = "Redo";
  VersionIdChangeReason2[VersionIdChangeReason2["AcceptWord"] = 2] = "AcceptWord";
  VersionIdChangeReason2[VersionIdChangeReason2["Other"] = 3] = "Other";
})(VersionIdChangeReason || (VersionIdChangeReason = {}));
function $wdb(textModel, positions, primaryEdit) {
  if (positions.length === 1) {
    return [];
  }
  const primaryPosition = positions[0];
  const secondaryPositions = positions.slice(1);
  const primaryEditStartPosition = primaryEdit.range.getStartPosition();
  const primaryEditEndPosition = primaryEdit.range.getEndPosition();
  const replacedTextAfterPrimaryCursor = textModel.getValueInRange($9C.fromPositions(primaryPosition, primaryEditEndPosition));
  const positionWithinTextEdit = $Hcb(primaryPosition, primaryEditStartPosition);
  if (positionWithinTextEdit.lineNumber < 1) {
    $gb(new $vb(`positionWithinTextEdit line number should be bigger than 0.
			Invalid subtraction between ${primaryPosition.toString()} and ${primaryEditStartPosition.toString()}`));
    return [];
  }
  const secondaryEditText = $Icb(primaryEdit.text, positionWithinTextEdit);
  return secondaryPositions.map((pos) => {
    const posEnd = $Gcb($Hcb(pos, primaryEditStartPosition), primaryEditEndPosition);
    const textAfterSecondaryCursor = textModel.getValueInRange($9C.fromPositions(pos, posEnd));
    const l = $3f(replacedTextAfterPrimaryCursor, textAfterSecondaryCursor);
    const range = $9C.fromPositions(pos, pos.delta(0, l));
    return new $jD(range, secondaryEditText);
  });
}

// out-build/vs/editor/contrib/suggest/browser/suggestMemory.js
var $$cb_1;
var $7cb = class {
  constructor(name) {
    this.name = name;
  }
  select(model, pos, items) {
    if (items.length === 0) {
      return 0;
    }
    const topScore = items[0].score[0];
    for (let i2 = 0; i2 < items.length; i2++) {
      const { score: score2, completion: suggestion } = items[i2];
      if (score2[0] !== topScore) {
        break;
      }
      if (suggestion.preselect) {
        return i2;
      }
    }
    return 0;
  }
};
var $8cb = class extends $7cb {
  constructor() {
    super("first");
  }
  memorize(model, pos, item) {
  }
  toJSON() {
    return void 0;
  }
  fromJSON() {
  }
};
var $9cb = class extends $7cb {
  constructor() {
    super("recentlyUsed");
    this.c = new $Hc(300, 0.66);
    this.d = 0;
  }
  memorize(model, pos, item) {
    const key2 = `${model.getLanguageId()}/${item.textLabel}`;
    this.c.set(key2, {
      touch: this.d++,
      type: item.completion.kind,
      insertText: item.completion.insertText
    });
  }
  select(model, pos, items) {
    if (items.length === 0) {
      return 0;
    }
    const lineSuffix = model.getLineContent(pos.lineNumber).substr(pos.column - 10, pos.column - 1);
    if (/\s$/.test(lineSuffix)) {
      return super.select(model, pos, items);
    }
    const topScore = items[0].score[0];
    let indexPreselect = -1;
    let indexRecency = -1;
    let seq = -1;
    for (let i2 = 0; i2 < items.length; i2++) {
      if (items[i2].score[0] !== topScore) {
        break;
      }
      const key2 = `${model.getLanguageId()}/${items[i2].textLabel}`;
      const item = this.c.peek(key2);
      if (item && item.touch > seq && item.type === items[i2].completion.kind && item.insertText === items[i2].completion.insertText) {
        seq = item.touch;
        indexRecency = i2;
      }
      if (items[i2].completion.preselect && indexPreselect === -1) {
        return indexPreselect = i2;
      }
    }
    if (indexRecency !== -1) {
      return indexRecency;
    } else if (indexPreselect !== -1) {
      return indexPreselect;
    } else {
      return 0;
    }
  }
  toJSON() {
    return this.c.toJSON();
  }
  fromJSON(data) {
    this.c.clear();
    const seq = 0;
    for (const [key2, value] of data) {
      value.touch = seq;
      value.type = typeof value.type === "number" ? value.type : CompletionItemKinds.fromString(value.type);
      this.c.set(key2, value);
    }
    this.d = this.c.size;
  }
};
var $0cb = class extends $7cb {
  constructor() {
    super("recentlyUsedByPrefix");
    this.c = $Wk.forStrings();
    this.d = 0;
  }
  memorize(model, pos, item) {
    const { word } = model.getWordUntilPosition(pos);
    const key2 = `${model.getLanguageId()}/${word}`;
    this.c.set(key2, {
      type: item.completion.kind,
      insertText: item.completion.insertText,
      touch: this.d++
    });
  }
  select(model, pos, items) {
    const { word } = model.getWordUntilPosition(pos);
    if (!word) {
      return super.select(model, pos, items);
    }
    const key2 = `${model.getLanguageId()}/${word}`;
    let item = this.c.get(key2);
    if (!item) {
      item = this.c.findSubstr(key2);
    }
    if (item) {
      for (let i2 = 0; i2 < items.length; i2++) {
        const { kind, insertText } = items[i2].completion;
        if (kind === item.type && insertText === item.insertText) {
          return i2;
        }
      }
    }
    return super.select(model, pos, items);
  }
  toJSON() {
    const entries2 = [];
    this.c.forEach((value, key2) => entries2.push([key2, value]));
    entries2.sort((a, b) => -(a[1].touch - b[1].touch)).forEach((value, i2) => value[1].touch = i2);
    return entries2.slice(0, 200);
  }
  fromJSON(data) {
    this.c.clear();
    if (data.length > 0) {
      this.d = data[0][1].touch + 1;
      for (const [key2, value] of data) {
        value.type = typeof value.type === "number" ? value.type : CompletionItemKinds.fromString(value.type);
        this.c.set(key2, value);
      }
    }
  }
};
var $$cb = class $$cb2 {
  static {
    $$cb_1 = this;
  }
  static {
    this.c = /* @__PURE__ */ new Map([
      ["recentlyUsedByPrefix", $0cb],
      ["recentlyUsed", $9cb],
      ["first", $8cb]
    ]);
  }
  static {
    this.d = "suggest/memories";
  }
  constructor(j, k) {
    this.j = j;
    this.k = k;
    this.g = new $2c();
    this.f = new $8h(() => this.m(), 500);
    this.g.add(j.onWillSaveState((e) => {
      if (e.reason === WillSaveStateReason.SHUTDOWN) {
        this.m();
      }
    }));
  }
  dispose() {
    this.g.dispose();
    this.f.dispose();
  }
  memorize(model, pos, item) {
    this.l(model, pos).memorize(model, pos, item);
    this.f.schedule();
  }
  select(model, pos, items) {
    return this.l(model, pos).select(model, pos, items);
  }
  l(model, pos) {
    const mode = this.k.getValue("editor.suggestSelection", {
      overrideIdentifier: model.getLanguageIdAtPosition(pos.lineNumber, pos.column),
      resource: model.uri
    });
    if (this.h?.name !== mode) {
      this.m();
      const ctor = $$cb_1.c.get(mode) || $8cb;
      this.h = new ctor();
      try {
        const share = this.k.getValue("editor.suggest.shareSuggestSelections");
        const scope = share ? 0 : 1;
        const raw = this.j.get(`${$$cb_1.d}/${mode}`, scope);
        if (raw) {
          this.h.fromJSON(JSON.parse(raw));
        }
      } catch (e) {
      }
    }
    return this.h;
  }
  m() {
    if (this.h) {
      const share = this.k.getValue("editor.suggest.shareSuggestSelections");
      const scope = share ? 0 : 1;
      const raw = JSON.stringify(this.h);
      this.j.store(
        `${$$cb_1.d}/${this.h.name}`,
        raw,
        scope,
        1
        /* StorageTarget.MACHINE */
      );
    }
  }
};
$$cb = $$cb_1 = __decorate([
  __param(0, $jv),
  __param(1, $kl)
], $$cb);
var $_cb = $Qk("ISuggestMemories");
$SC(
  $_cb,
  $$cb,
  1
  /* InstantiationType.Delayed */
);

// out-build/vs/editor/contrib/suggest/browser/wordContextKey.js
var $adb_1;
var $adb = class $adb2 {
  static {
    $adb_1 = this;
  }
  static {
    this.AtEnd = new $nn("atEndOfWord", false);
  }
  constructor(f, contextKeyService) {
    this.f = f;
    this.c = false;
    this.a = $adb_1.AtEnd.bindTo(contextKeyService);
    this.b = this.f.onDidChangeConfiguration((e) => e.hasChanged(
      128
      /* EditorOption.tabCompletion */
    ) && this.g());
    this.g();
  }
  dispose() {
    this.b.dispose();
    this.d?.dispose();
    this.a.reset();
  }
  g() {
    const enabled = this.f.getOption(
      128
      /* EditorOption.tabCompletion */
    ) === "on";
    if (this.c === enabled) {
      return;
    }
    this.c = enabled;
    if (this.c) {
      const checkForWordEnd = () => {
        if (!this.f.hasModel()) {
          this.a.set(false);
          return;
        }
        const model = this.f.getModel();
        const selection = this.f.getSelection();
        const word = model.getWordAtPosition(selection.getStartPosition());
        if (!word) {
          this.a.set(false);
          return;
        }
        this.a.set(word.endColumn === selection.getStartPosition().column);
      };
      this.d = this.f.onDidChangeCursorSelection(checkForWordEnd);
      checkForWordEnd();
    } else if (this.d) {
      this.a.reset();
      this.d.dispose();
      this.d = void 0;
    }
  }
};
$adb = $adb_1 = __decorate([
  __param(1, $on)
], $adb);

// out-build/vs/editor/contrib/suggest/browser/suggestAlternatives.js
var $odb_1;
var $odb = class $odb2 {
  static {
    $odb_1 = this;
  }
  static {
    this.OtherSuggestions = new $nn("hasOtherSuggestions", false);
  }
  constructor(g, contextKeyService) {
    this.g = g;
    this.b = 0;
    this.a = $odb_1.OtherSuggestions.bindTo(contextKeyService);
  }
  dispose() {
    this.reset();
  }
  reset() {
    this.a.reset();
    this.e?.dispose();
    this.c = void 0;
    this.d = void 0;
    this.f = false;
  }
  set({ model, index }, acceptNext) {
    if (model.items.length === 0) {
      this.reset();
      return;
    }
    const nextIndex = $odb_1.h(true, model, index);
    if (nextIndex === index) {
      this.reset();
      return;
    }
    this.d = acceptNext;
    this.c = model;
    this.b = index;
    this.e = this.g.onDidChangeCursorPosition(() => {
      if (!this.f) {
        this.reset();
      }
    });
    this.a.set(true);
  }
  static h(fwd, model, index) {
    let newIndex = index;
    for (let rounds = model.items.length; rounds > 0; rounds--) {
      newIndex = (newIndex + model.items.length + (fwd ? 1 : -1)) % model.items.length;
      if (newIndex === index) {
        break;
      }
      if (!model.items[newIndex].completion.additionalTextEdits) {
        break;
      }
    }
    return newIndex;
  }
  next() {
    this.i(true);
  }
  prev() {
    this.i(false);
  }
  i(fwd) {
    if (!this.c) {
      return;
    }
    try {
      this.f = true;
      this.b = $odb_1.h(fwd, this.c, this.b);
      this.d({ index: this.b, item: this.c.items[this.b], model: this.c });
    } finally {
      this.f = false;
    }
  }
};
$odb = $odb_1 = __decorate([
  __param(1, $on)
], $odb);

// out-build/vs/editor/contrib/suggest/browser/suggestCommitCharacters.js
var $pdb = class {
  constructor(editor, widget, model, accept) {
    this.a = new $2c();
    this.a.add(model.onDidSuggest((e) => {
      if (e.completionModel.items.length === 0) {
        this.reset();
      }
    }));
    this.a.add(model.onDidCancel((e) => {
      this.reset();
    }));
    this.a.add(widget.onDidShow(() => this.c(widget.getFocusedItem())));
    this.a.add(widget.onDidFocus(this.c, this));
    this.a.add(widget.onDidHide(this.reset, this));
    this.a.add(editor.onWillType((text2) => {
      if (this.b && !widget.isFrozen() && model.state !== 0) {
        const ch = text2.charCodeAt(text2.length - 1);
        if (this.b.acceptCharacters.has(ch) && editor.getOption(
          0
          /* EditorOption.acceptSuggestionOnCommitCharacter */
        )) {
          accept(this.b.item);
        }
      }
    }));
  }
  c(selected) {
    if (!selected || !$Qb(selected.item.completion.commitCharacters)) {
      this.reset();
      return;
    }
    if (this.b && this.b.item.item === selected.item) {
      return;
    }
    const acceptCharacters = new $gE();
    for (const ch of selected.item.completion.commitCharacters) {
      if (ch.length > 0) {
        acceptCharacters.add(ch.charCodeAt(0));
      }
    }
    this.b = { acceptCharacters, item: selected };
  }
  reset() {
    this.b = void 0;
  }
  dispose() {
    this.a.dispose();
  }
};

// out-build/vs/editor/contrib/smartSelect/browser/bracketSelections.js
var $kcb = class _$kcb {
  async provideSelectionRanges(model, positions) {
    const result = [];
    for (const position of positions) {
      const bucket = [];
      result.push(bucket);
      const ranges = /* @__PURE__ */ new Map();
      await new Promise((resolve) => _$kcb.b(resolve, 0, model, position, ranges));
      await new Promise((resolve) => _$kcb.c(resolve, 0, model, position, ranges, bucket));
    }
    return result;
  }
  static {
    this._maxDuration = 30;
  }
  static {
    this.a = 2;
  }
  static b(resolve, round, model, pos, ranges) {
    const counts = /* @__PURE__ */ new Map();
    const t1 = Date.now();
    while (true) {
      if (round >= _$kcb.a) {
        resolve();
        break;
      }
      if (!pos) {
        resolve();
        break;
      }
      const bracket = model.bracketPairs.findNextBracket(pos);
      if (!bracket) {
        resolve();
        break;
      }
      const d = Date.now() - t1;
      if (d > _$kcb._maxDuration) {
        setTimeout(() => _$kcb.b(resolve, round + 1, model, pos, ranges));
        break;
      }
      if (bracket.bracketInfo.isOpeningBracket) {
        const key2 = bracket.bracketInfo.bracketText;
        const val = counts.has(key2) ? counts.get(key2) : 0;
        counts.set(key2, val + 1);
      } else {
        const key2 = bracket.bracketInfo.getOpeningBrackets()[0].bracketText;
        let val = counts.has(key2) ? counts.get(key2) : 0;
        val -= 1;
        counts.set(key2, Math.max(0, val));
        if (val < 0) {
          let list2 = ranges.get(key2);
          if (!list2) {
            list2 = new $cd();
            ranges.set(key2, list2);
          }
          list2.push(bracket.range);
        }
      }
      pos = bracket.range.getEndPosition();
    }
  }
  static c(resolve, round, model, pos, ranges, bucket) {
    const counts = /* @__PURE__ */ new Map();
    const t1 = Date.now();
    while (true) {
      if (round >= _$kcb.a && ranges.size === 0) {
        resolve();
        break;
      }
      if (!pos) {
        resolve();
        break;
      }
      const bracket = model.bracketPairs.findPrevBracket(pos);
      if (!bracket) {
        resolve();
        break;
      }
      const d = Date.now() - t1;
      if (d > _$kcb._maxDuration) {
        setTimeout(() => _$kcb.c(resolve, round + 1, model, pos, ranges, bucket));
        break;
      }
      if (!bracket.bracketInfo.isOpeningBracket) {
        const key2 = bracket.bracketInfo.getOpeningBrackets()[0].bracketText;
        const val = counts.has(key2) ? counts.get(key2) : 0;
        counts.set(key2, val + 1);
      } else {
        const key2 = bracket.bracketInfo.bracketText;
        let val = counts.has(key2) ? counts.get(key2) : 0;
        val -= 1;
        counts.set(key2, Math.max(0, val));
        if (val < 0) {
          const list2 = ranges.get(key2);
          if (list2) {
            const closing = list2.shift();
            if (list2.size === 0) {
              ranges.delete(key2);
            }
            const innerBracket = $9C.fromPositions(bracket.range.getEndPosition(), closing.getStartPosition());
            const outerBracket = $9C.fromPositions(bracket.range.getStartPosition(), closing.getEndPosition());
            bucket.push({ range: innerBracket });
            bucket.push({ range: outerBracket });
            _$kcb.e(model, outerBracket, bucket);
          }
        }
      }
      pos = bracket.range.getStartPosition();
    }
  }
  static e(model, bracket, bucket) {
    if (bracket.startLineNumber === bracket.endLineNumber) {
      return;
    }
    const startLine = bracket.startLineNumber;
    const column = model.getLineFirstNonWhitespaceColumn(startLine);
    if (column !== 0 && column !== bracket.startColumn) {
      bucket.push({ range: $9C.fromPositions(new $8C(startLine, column), bracket.getEndPosition()) });
      bucket.push({ range: $9C.fromPositions(new $8C(startLine, 1), bracket.getEndPosition()) });
    }
    const aboveLine = startLine - 1;
    if (aboveLine > 0) {
      const column2 = model.getLineFirstNonWhitespaceColumn(aboveLine);
      if (column2 === bracket.startColumn && column2 !== model.getLineLastNonWhitespaceColumn(aboveLine)) {
        bucket.push({ range: $9C.fromPositions(new $8C(aboveLine, column2), bracket.getEndPosition()) });
        bucket.push({ range: $9C.fromPositions(new $8C(aboveLine, 1), bracket.getEndPosition()) });
      }
    }
  }
};

// out-build/vs/editor/contrib/suggest/browser/wordDistance.js
var $lcb = class _$lcb {
  static {
    this.None = new class extends _$lcb {
      distance() {
        return 0;
      }
    }();
  }
  static async create(service, editor) {
    if (!editor.getOption(
      123
      /* EditorOption.suggest */
    ).localityBonus) {
      return _$lcb.None;
    }
    if (!editor.hasModel()) {
      return _$lcb.None;
    }
    const model = editor.getModel();
    const position = editor.getPosition();
    if (!service.canComputeWordRanges(model.uri)) {
      return _$lcb.None;
    }
    const [ranges] = await new $kcb().provideSelectionRanges(model, [position]);
    if (ranges.length === 0) {
      return _$lcb.None;
    }
    const wordRanges = await service.computeWordRanges(model.uri, ranges[0].range);
    if (!wordRanges) {
      return _$lcb.None;
    }
    const wordUntilPos = model.getWordUntilPosition(position);
    delete wordRanges[wordUntilPos.word];
    return new class extends _$lcb {
      distance(anchor, item) {
        if (!position.equals(editor.getPosition())) {
          return 0;
        }
        if (item.kind === 17) {
          return 2 << 20;
        }
        const word = typeof item.label === "string" ? item.label : item.label.label;
        const wordLines = wordRanges[word];
        if ($Pb(wordLines)) {
          return 2 << 20;
        }
        const idx = $Bb(wordLines, $9C.fromPositions(anchor), $9C.compareRangesUsingStarts);
        const bestWordRange = idx >= 0 ? wordLines[idx] : wordLines[Math.max(0, ~idx - 1)];
        let blockDistance = ranges.length;
        for (const range of ranges) {
          if (!$9C.containsRange(range.range, bestWordRange)) {
            break;
          }
          blockDistance -= 1;
        }
        return blockDistance;
      }
    }();
  }
};

// out-build/vs/editor/contrib/suggest/browser/completionModel.js
var $mcb = class {
  constructor(leadingLineContent, characterCountDelta) {
    this.leadingLineContent = leadingLineContent;
    this.characterCountDelta = characterCountDelta;
  }
};
var Refilter;
(function(Refilter3) {
  Refilter3[Refilter3["Nothing"] = 0] = "Nothing";
  Refilter3[Refilter3["All"] = 1] = "All";
  Refilter3[Refilter3["Incr"] = 2] = "Incr";
})(Refilter || (Refilter = {}));
var $ncb = class _$ncb {
  constructor(items, column, lineContext, wordDistance, options3, snippetSuggestions, fuzzyScoreOptions = $Wl.default, clipboardText = void 0) {
    this.clipboardText = clipboardText;
    this.g = _$ncb.q;
    this.c = items;
    this.d = column;
    this.e = wordDistance;
    this.f = options3;
    this.k = 1;
    this.j = lineContext;
    this.h = fuzzyScoreOptions;
    if (snippetSuggestions === "top") {
      this.g = _$ncb.s;
    } else if (snippetSuggestions === "bottom") {
      this.g = _$ncb.r;
    }
  }
  get lineContext() {
    return this.j;
  }
  set lineContext(value) {
    if (this.j.leadingLineContent !== value.leadingLineContent || this.j.characterCountDelta !== value.characterCountDelta) {
      this.k = this.j.characterCountDelta < value.characterCountDelta && this.l ? 2 : 1;
      this.j = value;
    }
  }
  get items() {
    this.o();
    return this.l;
  }
  getItemsByProvider() {
    this.o();
    return this.m;
  }
  getIncompleteProvider() {
    this.o();
    const result = /* @__PURE__ */ new Set();
    for (const [provider, items] of this.getItemsByProvider()) {
      if (items.length > 0 && items[0].container.incomplete) {
        result.add(provider);
      }
    }
    return result;
  }
  get stats() {
    this.o();
    return this.n;
  }
  o() {
    if (this.k !== 0) {
      this.p();
    }
  }
  p() {
    this.m = /* @__PURE__ */ new Map();
    const labelLengths = [];
    const { leadingLineContent, characterCountDelta } = this.j;
    let word = "";
    let wordLow = "";
    const source = this.k === 1 ? this.c : this.l;
    const target = [];
    const scoreFn = !this.f.filterGraceful || source.length > 2e3 ? $Xl : $Yl;
    for (let i2 = 0; i2 < source.length; i2++) {
      const item = source[i2];
      if (item.isInvalid) {
        continue;
      }
      const arr = this.m.get(item.provider);
      if (arr) {
        arr.push(item);
      } else {
        this.m.set(item.provider, [item]);
      }
      const overwriteBefore = item.position.column - item.editStart.column;
      const wordLen = overwriteBefore + characterCountDelta - (item.position.column - this.d);
      if (word.length !== wordLen) {
        word = wordLen === 0 ? "" : leadingLineContent.slice(-wordLen);
        wordLow = word.toLowerCase();
      }
      item.word = word;
      if (wordLen === 0) {
        item.score = FuzzyScore.Default;
      } else {
        let wordPos = 0;
        while (wordPos < overwriteBefore) {
          const ch = word.charCodeAt(wordPos);
          if (ch === 32 || ch === 9) {
            wordPos += 1;
          } else {
            break;
          }
        }
        if (wordPos >= wordLen) {
          item.score = FuzzyScore.Default;
        } else if (typeof item.completion.filterText === "string") {
          const match = scoreFn(word, wordLow, wordPos, item.completion.filterText, item.filterTextLow, 0, this.h);
          if (!match) {
            continue;
          }
          if ($Vf(item.completion.filterText, item.textLabel) === 0) {
            item.score = match;
          } else {
            item.score = $Tl(word, wordLow, wordPos, item.textLabel, item.labelLow, 0);
            item.score[0] = match[0];
          }
        } else {
          const match = scoreFn(word, wordLow, wordPos, item.textLabel, item.labelLow, 0, this.h);
          if (!match) {
            continue;
          }
          item.score = match;
        }
      }
      item.idx = i2;
      item.distance = this.e.distance(item.position, item.completion);
      target.push(item);
      labelLengths.push(item.textLabel.length);
    }
    this.l = target.sort(this.g);
    this.k = 0;
    this.n = {
      pLabelLen: labelLengths.length ? $Db(labelLengths.length - 0.85, labelLengths, (a, b) => a - b) : 0
    };
  }
  static q(a, b) {
    if (a.score[0] > b.score[0]) {
      return -1;
    } else if (a.score[0] < b.score[0]) {
      return 1;
    } else if (a.distance < b.distance) {
      return -1;
    } else if (a.distance > b.distance) {
      return 1;
    } else if (a.idx < b.idx) {
      return -1;
    } else if (a.idx > b.idx) {
      return 1;
    } else {
      return 0;
    }
  }
  static r(a, b) {
    if (a.completion.kind !== b.completion.kind) {
      if (a.completion.kind === 27) {
        return 1;
      } else if (b.completion.kind === 27) {
        return -1;
      }
    }
    return _$ncb.q(a, b);
  }
  static s(a, b) {
    if (a.completion.kind !== b.completion.kind) {
      if (a.completion.kind === 27) {
        return -1;
      } else if (b.completion.kind === 27) {
        return 1;
      }
    }
    return _$ncb.q(a, b);
  }
};

// out-build/vs/editor/contrib/suggest/browser/suggestModel.js
var $qcb_1;
var $pcb = class {
  static shouldAutoTrigger(editor) {
    if (!editor.hasModel()) {
      return false;
    }
    const model = editor.getModel();
    const pos = editor.getPosition();
    model.tokenization.tokenizeIfCheap(pos.lineNumber);
    const word = model.getWordAtPosition(pos);
    if (!word) {
      return false;
    }
    if (word.endColumn !== pos.column && word.startColumn + 1 !== pos.column) {
      return false;
    }
    if (!isNaN(Number(word.word))) {
      return false;
    }
    return true;
  }
  constructor(model, position, triggerOptions) {
    this.leadingLineContent = model.getLineContent(position.lineNumber).substr(0, position.column - 1);
    this.leadingWord = model.getWordUntilPosition(position);
    this.lineNumber = position.lineNumber;
    this.column = position.column;
    this.triggerOptions = triggerOptions;
  }
};
var State2;
(function(State14) {
  State14[State14["Idle"] = 0] = "Idle";
  State14[State14["Manual"] = 1] = "Manual";
  State14[State14["Auto"] = 2] = "Auto";
})(State2 || (State2 = {}));
function canShowQuickSuggest(editor, contextKeyService, configurationService) {
  if (!Boolean(contextKeyService.getContextKeyValue($ocb.inlineSuggestionVisible.key))) {
    return true;
  }
  const suppressSuggestions = contextKeyService.getContextKeyValue($ocb.suppressSuggestions.key);
  if (suppressSuggestions !== void 0) {
    return !suppressSuggestions;
  }
  return !editor.getOption(
    64
    /* EditorOption.inlineSuggest */
  ).suppressSuggestions;
}
function canShowSuggestOnTriggerCharacters(editor, contextKeyService, configurationService) {
  if (!Boolean(contextKeyService.getContextKeyValue("inlineSuggestionVisible"))) {
    return true;
  }
  const suppressSuggestions = contextKeyService.getContextKeyValue($ocb.suppressSuggestions.key);
  if (suppressSuggestions !== void 0) {
    return !suppressSuggestions;
  }
  return !editor.getOption(
    64
    /* EditorOption.inlineSuggest */
  ).suppressSuggestions;
}
var $qcb = $qcb_1 = class $qcb2 {
  constructor(n, o, p, q, r2, s, t, u, v) {
    this.n = n;
    this.o = o;
    this.p = p;
    this.q = q;
    this.r = r2;
    this.s = s;
    this.t = t;
    this.u = u;
    this.v = v;
    this.a = new $2c();
    this.b = new $2c();
    this.c = new $6h();
    this.d = void 0;
    this.j = new $2c();
    this.k = new $ze();
    this.l = new $ze();
    this.m = new $ze();
    this.onDidCancel = this.k.event;
    this.onDidTrigger = this.l.event;
    this.onDidSuggest = this.m.event;
    this.C = 0;
    this.h = this.n.getSelection() || new $_D(1, 1, 1, 1);
    this.a.add(this.n.onDidChangeModel(() => {
      this.w();
      this.cancel();
    }));
    this.a.add(this.n.onDidChangeModelLanguage(() => {
      this.w();
      this.cancel();
    }));
    this.a.add(this.n.onDidChangeConfiguration(() => {
      this.w();
    }));
    this.a.add(this.u.completionProvider.onDidChange(() => {
      this.w();
      this.x();
    }));
    let editorIsComposing = false;
    this.a.add(this.n.onDidCompositionStart(() => {
      editorIsComposing = true;
    }));
    this.a.add(this.n.onDidCompositionEnd(() => {
      editorIsComposing = false;
      this.z();
    }));
    this.a.add(this.n.onDidChangeCursorSelection((e) => {
      if (!editorIsComposing) {
        this.y(e);
      }
    }));
    this.a.add(this.n.onDidChangeModelContent(() => {
      if (!editorIsComposing && this.d !== void 0) {
        this.B();
      }
    }));
    this.w();
  }
  dispose() {
    $Xc(this.b);
    $Xc([this.k, this.m, this.l, this.c]);
    this.a.dispose();
    this.j.dispose();
    this.cancel();
  }
  w() {
    this.b.clear();
    if (this.n.getOption(
      96
      /* EditorOption.readOnly */
    ) || !this.n.hasModel() || !this.n.getOption(
      126
      /* EditorOption.suggestOnTriggerCharacters */
    )) {
      return;
    }
    const supportsByTriggerCharacter = /* @__PURE__ */ new Map();
    for (const support of this.u.completionProvider.all(this.n.getModel())) {
      for (const ch of support.triggerCharacters || []) {
        let set = supportsByTriggerCharacter.get(ch);
        if (!set) {
          set = /* @__PURE__ */ new Set();
          const suggestSupport = $dcb();
          if (suggestSupport) {
            set.add(suggestSupport);
          }
          supportsByTriggerCharacter.set(ch, set);
        }
        set.add(support);
      }
    }
    const checkTriggerCharacter = (text2) => {
      if (!canShowSuggestOnTriggerCharacters(this.n, this.s, this.t)) {
        return;
      }
      if ($pcb.shouldAutoTrigger(this.n)) {
        return;
      }
      if (!text2) {
        const position = this.n.getPosition();
        const model = this.n.getModel();
        text2 = model.getLineContent(position.lineNumber).substr(0, position.column - 1);
      }
      let lastChar = "";
      if ($6f(text2.charCodeAt(text2.length - 1))) {
        if ($5f(text2.charCodeAt(text2.length - 2))) {
          lastChar = text2.substr(text2.length - 2);
        }
      } else {
        lastChar = text2.charAt(text2.length - 1);
      }
      const supports = supportsByTriggerCharacter.get(lastChar);
      if (supports) {
        const providerItemsToReuse = /* @__PURE__ */ new Map();
        if (this.i) {
          for (const [provider, items] of this.i.getItemsByProvider()) {
            if (!supports.has(provider)) {
              providerItemsToReuse.set(provider, items);
            }
          }
        }
        this.trigger({
          auto: true,
          triggerKind: 1,
          triggerCharacter: lastChar,
          retrigger: Boolean(this.i),
          clipboardText: this.i?.clipboardText,
          completionOptions: { providerFilter: supports, providerItemsToReuse }
        });
      }
    };
    this.b.add(this.n.onDidType(checkTriggerCharacter));
    this.b.add(this.n.onDidCompositionEnd(() => checkTriggerCharacter()));
  }
  // --- trigger/retrigger/cancel suggest
  get state() {
    if (!this.d) {
      return 0;
    } else if (!this.d.auto) {
      return 1;
    } else {
      return 2;
    }
  }
  cancel(retrigger = false) {
    if (this.d !== void 0) {
      this.c.cancel();
      this.f?.cancel();
      this.f = void 0;
      this.d = void 0;
      this.i = void 0;
      this.g = void 0;
      this.k.fire({ retrigger });
    }
  }
  clear() {
    this.j.clear();
  }
  x() {
    if (this.d !== void 0) {
      if (!this.n.hasModel() || !this.u.completionProvider.has(this.n.getModel())) {
        this.cancel();
      } else {
        this.trigger({ auto: this.d.auto, retrigger: true });
      }
    }
  }
  y(e) {
    if (!this.n.hasModel()) {
      return;
    }
    const prevSelection = this.h;
    this.h = this.n.getSelection();
    if (!e.selection.isEmpty() || e.reason !== 0 && e.reason !== 3 || e.source !== "keyboard" && e.source !== "deleteLeft") {
      this.cancel();
      return;
    }
    if (this.d === void 0 && e.reason === 0) {
      if (prevSelection.containsRange(this.h) || prevSelection.getEndPosition().isBeforeOrEqual(this.h.getPosition())) {
        this.A();
      }
    } else if (this.d !== void 0 && e.reason === 3) {
      this.B();
    }
  }
  z() {
    if (this.d === void 0) {
      this.A();
    } else {
      this.B();
    }
  }
  A() {
    if ($jcb.isAllOff(this.n.getOption(
      94
      /* EditorOption.quickSuggestions */
    ))) {
      return;
    }
    if (this.n.getOption(
      123
      /* EditorOption.suggest */
    ).snippetsPreventQuickSuggestions && $Dcb.get(this.n)?.isInSnippet()) {
      return;
    }
    this.cancel();
    this.c.cancelAndSet(() => {
      if (this.d !== void 0) {
        return;
      }
      if (!$pcb.shouldAutoTrigger(this.n)) {
        return;
      }
      if (!this.n.hasModel() || !this.n.hasWidgetFocus()) {
        return;
      }
      const model = this.n.getModel();
      const pos = this.n.getPosition();
      const config = this.n.getOption(
        94
        /* EditorOption.quickSuggestions */
      );
      if ($jcb.isAllOff(config)) {
        return;
      }
      if (!$jcb.isAllOn(config)) {
        model.tokenization.tokenizeIfCheap(pos.lineNumber);
        const lineTokens = model.tokenization.getLineTokens(pos.lineNumber);
        const tokenType = lineTokens.getStandardTokenType(lineTokens.findTokenIndexAtOffset(Math.max(pos.column - 1 - 1, 0)));
        if ($jcb.valueFor(config, tokenType) !== "on") {
          return;
        }
      }
      if (!canShowQuickSuggest(this.n, this.s, this.t)) {
        return;
      }
      if (!this.u.completionProvider.has(model)) {
        return;
      }
      this.trigger({ auto: true });
    }, this.n.getOption(
      95
      /* EditorOption.quickSuggestionsDelay */
    ));
  }
  B() {
    $Jg(this.n.hasModel());
    $Jg(this.d !== void 0);
    const model = this.n.getModel();
    const position = this.n.getPosition();
    const ctx = new $pcb(model, position, { ...this.d, refilter: true });
    this.E(ctx);
  }
  trigger(options3) {
    if (!this.n.hasModel()) {
      return;
    }
    const model = this.n.getModel();
    const ctx = new $pcb(model, this.n.getPosition(), options3);
    this.cancel(options3.retrigger);
    this.d = options3;
    this.l.fire({ auto: options3.auto, shy: options3.shy ?? false, position: this.n.getPosition() });
    this.g = ctx;
    let suggestCtx = {
      triggerKind: options3.triggerKind ?? 0
      /* CompletionTriggerKind.Invoke */
    };
    if (options3.triggerCharacter) {
      suggestCtx = {
        triggerKind: 1,
        triggerCharacter: options3.triggerCharacter
      };
    }
    this.f = new $ad();
    const snippetSuggestions = this.n.getOption(
      117
      /* EditorOption.snippetSuggestions */
    );
    let snippetSortOrder = 1;
    switch (snippetSuggestions) {
      case "top":
        snippetSortOrder = 0;
        break;
      case "bottom":
        snippetSortOrder = 2;
        break;
    }
    const { itemKind: itemKindFilter, showDeprecated } = $qcb_1.createSuggestFilter(this.n);
    const completionOptions = new $ccb(snippetSortOrder, options3.completionOptions?.kindFilter ?? itemKindFilter, options3.completionOptions?.providerFilter, options3.completionOptions?.providerItemsToReuse, showDeprecated);
    const wordDistance = $lcb.create(this.o, this.n);
    const completions = $gcb(this.u.completionProvider, model, this.n.getPosition(), completionOptions, suggestCtx, this.f.token);
    Promise.all([completions, wordDistance]).then(async ([completions2, wordDistance2]) => {
      this.f?.dispose();
      if (!this.n.hasModel()) {
        return;
      }
      let clipboardText = options3?.clipboardText;
      if (!clipboardText && completions2.needsClipboard) {
        clipboardText = await this.p.readText();
      }
      if (this.d === void 0) {
        return;
      }
      const model2 = this.n.getModel();
      const ctx2 = new $pcb(model2, this.n.getPosition(), options3);
      const fuzzySearchOptions = {
        ...$Wl.default,
        firstMatchCanBeWeak: !this.n.getOption(
          123
          /* EditorOption.suggest */
        ).matchOnWordStartOnly
      };
      this.i = new $ncb(completions2.items, this.g.column, {
        leadingLineContent: ctx2.leadingLineContent,
        characterCountDelta: ctx2.column - this.g.column
      }, wordDistance2, this.n.getOption(
        123
        /* EditorOption.suggest */
      ), this.n.getOption(
        117
        /* EditorOption.snippetSuggestions */
      ), fuzzySearchOptions, clipboardText);
      this.j.add(completions2.disposable);
      this.E(ctx2);
      this.D(completions2.durations);
      if (!this.v.isBuilt || this.v.isExtensionDevelopment) {
        for (const item of completions2.items) {
          if (item.isInvalid) {
            this.r.warn(`[suggest] did IGNORE invalid completion item from ${item.provider._debugDisplayName}`, item.completion);
          }
        }
      }
    }).catch($gb);
  }
  D(durations) {
    if (this.C++ % 230 !== 0) {
      return;
    }
    setTimeout(() => {
      this.q.publicLog2("suggest.durations.json", { data: JSON.stringify(durations) });
      this.r.debug("suggest.durations.json", durations);
    });
  }
  static createSuggestFilter(editor) {
    const result = /* @__PURE__ */ new Set();
    const snippetSuggestions = editor.getOption(
      117
      /* EditorOption.snippetSuggestions */
    );
    if (snippetSuggestions === "none") {
      result.add(
        27
        /* CompletionItemKind.Snippet */
      );
    }
    const suggestOptions = editor.getOption(
      123
      /* EditorOption.suggest */
    );
    if (!suggestOptions.showMethods) {
      result.add(
        0
        /* CompletionItemKind.Method */
      );
    }
    if (!suggestOptions.showFunctions) {
      result.add(
        1
        /* CompletionItemKind.Function */
      );
    }
    if (!suggestOptions.showConstructors) {
      result.add(
        2
        /* CompletionItemKind.Constructor */
      );
    }
    if (!suggestOptions.showFields) {
      result.add(
        3
        /* CompletionItemKind.Field */
      );
    }
    if (!suggestOptions.showVariables) {
      result.add(
        4
        /* CompletionItemKind.Variable */
      );
    }
    if (!suggestOptions.showClasses) {
      result.add(
        5
        /* CompletionItemKind.Class */
      );
    }
    if (!suggestOptions.showStructs) {
      result.add(
        6
        /* CompletionItemKind.Struct */
      );
    }
    if (!suggestOptions.showInterfaces) {
      result.add(
        7
        /* CompletionItemKind.Interface */
      );
    }
    if (!suggestOptions.showModules) {
      result.add(
        8
        /* CompletionItemKind.Module */
      );
    }
    if (!suggestOptions.showProperties) {
      result.add(
        9
        /* CompletionItemKind.Property */
      );
    }
    if (!suggestOptions.showEvents) {
      result.add(
        10
        /* CompletionItemKind.Event */
      );
    }
    if (!suggestOptions.showOperators) {
      result.add(
        11
        /* CompletionItemKind.Operator */
      );
    }
    if (!suggestOptions.showUnits) {
      result.add(
        12
        /* CompletionItemKind.Unit */
      );
    }
    if (!suggestOptions.showValues) {
      result.add(
        13
        /* CompletionItemKind.Value */
      );
    }
    if (!suggestOptions.showConstants) {
      result.add(
        14
        /* CompletionItemKind.Constant */
      );
    }
    if (!suggestOptions.showEnums) {
      result.add(
        15
        /* CompletionItemKind.Enum */
      );
    }
    if (!suggestOptions.showEnumMembers) {
      result.add(
        16
        /* CompletionItemKind.EnumMember */
      );
    }
    if (!suggestOptions.showKeywords) {
      result.add(
        17
        /* CompletionItemKind.Keyword */
      );
    }
    if (!suggestOptions.showWords) {
      result.add(
        18
        /* CompletionItemKind.Text */
      );
    }
    if (!suggestOptions.showColors) {
      result.add(
        19
        /* CompletionItemKind.Color */
      );
    }
    if (!suggestOptions.showFiles) {
      result.add(
        20
        /* CompletionItemKind.File */
      );
    }
    if (!suggestOptions.showReferences) {
      result.add(
        21
        /* CompletionItemKind.Reference */
      );
    }
    if (!suggestOptions.showColors) {
      result.add(
        22
        /* CompletionItemKind.Customcolor */
      );
    }
    if (!suggestOptions.showFolders) {
      result.add(
        23
        /* CompletionItemKind.Folder */
      );
    }
    if (!suggestOptions.showTypeParameters) {
      result.add(
        24
        /* CompletionItemKind.TypeParameter */
      );
    }
    if (!suggestOptions.showSnippets) {
      result.add(
        27
        /* CompletionItemKind.Snippet */
      );
    }
    if (!suggestOptions.showUsers) {
      result.add(
        25
        /* CompletionItemKind.User */
      );
    }
    if (!suggestOptions.showIssues) {
      result.add(
        26
        /* CompletionItemKind.Issue */
      );
    }
    return { itemKind: result, showDeprecated: suggestOptions.showDeprecated };
  }
  E(ctx) {
    if (!this.g) {
      return;
    }
    if (ctx.lineNumber !== this.g.lineNumber) {
      this.cancel();
      return;
    }
    if ($Pf(ctx.leadingLineContent) !== $Pf(this.g.leadingLineContent)) {
      this.cancel();
      return;
    }
    if (ctx.column < this.g.column) {
      if (ctx.leadingWord.word) {
        this.trigger({ auto: this.g.triggerOptions.auto, retrigger: true });
      } else {
        this.cancel();
      }
      return;
    }
    if (!this.i) {
      return;
    }
    if (ctx.leadingWord.word.length !== 0 && ctx.leadingWord.startColumn > this.g.leadingWord.startColumn) {
      const shouldAutoTrigger = $pcb.shouldAutoTrigger(this.n);
      if (shouldAutoTrigger && this.g) {
        const map = this.i.getItemsByProvider();
        this.trigger({
          auto: this.g.triggerOptions.auto,
          retrigger: true,
          clipboardText: this.i.clipboardText,
          completionOptions: { providerItemsToReuse: map }
        });
      }
      return;
    }
    if (ctx.column > this.g.column && this.i.getIncompleteProvider().size > 0 && ctx.leadingWord.word.length !== 0) {
      const providerItemsToReuse = /* @__PURE__ */ new Map();
      const providerFilter = /* @__PURE__ */ new Set();
      for (const [provider, items] of this.i.getItemsByProvider()) {
        if (items.length > 0 && items[0].container.incomplete) {
          providerFilter.add(provider);
        } else {
          providerItemsToReuse.set(provider, items);
        }
      }
      this.trigger({
        auto: this.g.triggerOptions.auto,
        triggerKind: 2,
        retrigger: true,
        clipboardText: this.i.clipboardText,
        completionOptions: { providerFilter, providerItemsToReuse }
      });
    } else {
      const oldLineContext = this.i.lineContext;
      let isFrozen2 = false;
      this.i.lineContext = {
        leadingLineContent: ctx.leadingLineContent,
        characterCountDelta: ctx.column - this.g.column
      };
      if (this.i.items.length === 0) {
        const shouldAutoTrigger = $pcb.shouldAutoTrigger(this.n);
        if (!this.g) {
          this.cancel();
          return;
        }
        if (shouldAutoTrigger && this.g.leadingWord.endColumn < ctx.leadingWord.startColumn) {
          this.trigger({ auto: this.g.triggerOptions.auto, retrigger: true });
          return;
        }
        if (!this.g.triggerOptions.auto) {
          this.i.lineContext = oldLineContext;
          isFrozen2 = this.i.items.length > 0;
          if (isFrozen2 && ctx.leadingWord.word.length === 0) {
            this.cancel();
            return;
          }
        } else {
          this.cancel();
          return;
        }
      }
      this.m.fire({
        completionModel: this.i,
        triggerOptions: ctx.triggerOptions,
        isFrozen: isFrozen2
      });
    }
  }
};
$qcb = $qcb_1 = __decorate([
  __param(1, $I0),
  __param(2, $30),
  __param(3, $zv),
  __param(4, $wn),
  __param(5, $on),
  __param(6, $kl),
  __param(7, $mP),
  __param(8, $Xk)
], $qcb);

// out-build/vs/editor/contrib/suggest/browser/suggestOvertypingCapturer.js
var $rcb = class _$rcb {
  static {
    this.a = 51200;
  }
  constructor(editor, suggestModel) {
    this.b = new $2c();
    this.c = [];
    this.d = false;
    this.b.add(editor.onWillType(() => {
      if (this.d || !editor.hasModel()) {
        return;
      }
      const selections = editor.getSelections();
      const selectionsLength = selections.length;
      let willOvertype = false;
      for (let i2 = 0; i2 < selectionsLength; i2++) {
        if (!selections[i2].isEmpty()) {
          willOvertype = true;
          break;
        }
      }
      if (!willOvertype) {
        if (this.c.length !== 0) {
          this.c.length = 0;
        }
        return;
      }
      this.c = [];
      const model = editor.getModel();
      for (let i2 = 0; i2 < selectionsLength; i2++) {
        const selection = selections[i2];
        if (model.getValueLengthInRange(selection) > _$rcb.a) {
          return;
        }
        this.c[i2] = { value: model.getValueInRange(selection), multiline: selection.startLineNumber !== selection.endLineNumber };
      }
    }));
    this.b.add(suggestModel.onDidTrigger((e) => {
      this.d = true;
    }));
    this.b.add(suggestModel.onDidCancel((e) => {
      this.d = false;
    }));
  }
  getLastOvertypedInfo(idx) {
    if (idx >= 0 && idx < this.c.length) {
      return this.c[idx];
    }
    return void 0;
  }
  dispose() {
    this.b.dispose();
  }
};

// out-build/vs/editor/contrib/suggest/browser/suggestWidgetStatus.js
var $cdb = class $cdb2 {
  constructor(container2, d, instantiationService, e, f) {
    this.d = d;
    this.e = e;
    this.f = f;
    this.c = new $2c();
    this.element = $bk(container2, $(".suggest-status-bar"));
    const actionViewItemProvider = (action) => {
      return action instanceof $fJ ? instantiationService.createInstance($U$, action, { useComma: true }) : void 0;
    };
    this.a = new $LZ(this.element, { actionViewItemProvider });
    this.b = new $LZ(this.element, { actionViewItemProvider });
    this.a.domNode.classList.add("left");
    this.b.domNode.classList.add("right");
  }
  dispose() {
    this.c.dispose();
    this.a.dispose();
    this.b.dispose();
    this.element.remove();
  }
  show() {
    const menu = this.e.createMenu(this.d, this.f);
    const renderMenu = () => {
      const left = [];
      const right = [];
      for (const [group2, actions] of menu.getActions()) {
        if (group2 === "left") {
          left.push(...actions);
        } else {
          right.push(...actions);
        }
      }
      this.a.clear();
      this.a.push(left);
      this.b.clear();
      this.b.push(right);
    };
    this.c.add(menu.onDidChange(() => renderMenu()));
    this.c.add(menu);
  }
  hide() {
    this.c.clear();
  }
};
$cdb = __decorate([
  __param(2, $Pk),
  __param(3, $cJ),
  __param(4, $on)
], $cdb);

// out-build/vs/editor/contrib/suggest/browser/suggestWidgetDetails.js
function $ddb(item) {
  return !!item && Boolean(item.completion.documentation || item.completion.detail && item.completion.detail !== item.completion.label);
}
var $edb = class $edb2 {
  constructor(r2, instaService) {
    this.r = r2;
    this.c = new $ze();
    this.onDidClose = this.c.event;
    this.d = new $ze();
    this.onDidChangeContents = this.d.event;
    this.l = new $2c();
    this.n = new $2c();
    this.o = 1;
    this.q = new $rj(330, 0);
    this.domNode = $(".suggest-details");
    this.domNode.classList.add("no-docs");
    this.m = instaService.createInstance($Q_, { editor: r2 });
    this.h = $(".body");
    this.g = new $CZ(this.h, {
      alwaysConsumeMouseWheel: true
    });
    $bk(this.domNode, this.g.getDomNode());
    this.l.add(this.g);
    this.i = $bk(this.h, $(".header"));
    this.f = $bk(this.i, $("span" + ThemeIcon.asCSSSelector($6l.close)));
    this.f.title = localize(1527, null);
    this.f.role = "button";
    this.f.tabIndex = -1;
    this.j = $bk(this.i, $("p.type"));
    this.k = $bk(this.h, $("p.docs"));
    this.s();
    this.l.add(this.r.onDidChangeConfiguration((e) => {
      if (e.hasChanged(
        52
        /* EditorOption.fontInfo */
      )) {
        this.s();
      }
    }));
  }
  dispose() {
    this.l.dispose();
    this.n.dispose();
  }
  s() {
    const options3 = this.r.getOptions();
    const fontInfo = options3.get(
      52
      /* EditorOption.fontInfo */
    );
    const fontFamily = fontInfo.getMassagedFontFamily();
    const fontSize = options3.get(
      124
      /* EditorOption.suggestFontSize */
    ) || fontInfo.fontSize;
    const lineHeight = options3.get(
      125
      /* EditorOption.suggestLineHeight */
    ) || fontInfo.lineHeight;
    const fontWeight = fontInfo.fontWeight;
    const fontSizePx = `${fontSize}px`;
    const lineHeightPx = `${lineHeight}px`;
    this.domNode.style.fontSize = fontSizePx;
    this.domNode.style.lineHeight = `${lineHeight / fontSize}`;
    this.domNode.style.fontWeight = fontWeight;
    this.domNode.style.fontFeatureSettings = fontInfo.fontFeatureSettings;
    this.j.style.fontFamily = fontFamily;
    this.f.style.height = lineHeightPx;
    this.f.style.width = lineHeightPx;
  }
  getLayoutInfo() {
    const lineHeight = this.r.getOption(
      125
      /* EditorOption.suggestLineHeight */
    ) || this.r.getOption(
      52
      /* EditorOption.fontInfo */
    ).lineHeight;
    const borderWidth = this.o;
    const borderHeight = borderWidth * 2;
    return {
      lineHeight,
      borderWidth,
      borderHeight,
      verticalPadding: 22,
      horizontalPadding: 14
    };
  }
  renderLoading() {
    this.j.textContent = localize(1528, null);
    this.k.textContent = "";
    this.domNode.classList.remove("no-docs", "no-type");
    this.layout(this.size.width, this.getLayoutInfo().lineHeight * 2);
    this.d.fire(this);
  }
  renderItem(item, explainMode) {
    this.n.clear();
    let { detail: detail2, documentation } = item.completion;
    if (explainMode) {
      let md = "";
      md += `score: ${item.score[0]}
`;
      md += `prefix: ${item.word ?? "(no prefix)"}
`;
      md += `word: ${item.completion.filterText ? item.completion.filterText + " (filterText)" : item.textLabel}
`;
      md += `distance: ${item.distance} (localityBonus-setting)
`;
      md += `index: ${item.idx}, based on ${item.completion.sortText && `sortText: "${item.completion.sortText}"` || "label"}
`;
      md += `commit_chars: ${item.completion.commitCharacters?.join("")}
`;
      documentation = new $bm().appendCodeblock("empty", md);
      detail2 = `Provider: ${item.provider._debugDisplayName}`;
    }
    if (!explainMode && !$ddb(item)) {
      this.clearContents();
      return;
    }
    this.domNode.classList.remove("no-docs", "no-type");
    if (detail2) {
      const cappedDetail = detail2.length > 1e5 ? `${detail2.substr(0, 1e5)}\u2026` : detail2;
      this.j.textContent = cappedDetail;
      this.j.title = cappedDetail;
      $hk(this.j);
      this.j.classList.toggle("auto-wrap", !/\r?\n^\s+/gmi.test(cappedDetail));
    } else {
      $$i(this.j);
      this.j.title = "";
      $ik(this.j);
      this.domNode.classList.add("no-type");
    }
    $$i(this.k);
    if (typeof documentation === "string") {
      this.k.classList.remove("markdown-docs");
      this.k.textContent = documentation;
    } else if (documentation) {
      this.k.classList.add("markdown-docs");
      $$i(this.k);
      const renderedContents = this.m.render(documentation);
      this.k.appendChild(renderedContents.element);
      this.n.add(renderedContents);
      this.n.add(this.m.onDidRenderAsync(() => {
        this.layout(this.q.width, this.j.clientHeight + this.k.clientHeight);
        this.d.fire(this);
      }));
    }
    this.domNode.style.userSelect = "text";
    this.domNode.tabIndex = -1;
    this.f.onmousedown = (e) => {
      e.preventDefault();
      e.stopPropagation();
    };
    this.f.onclick = (e) => {
      e.preventDefault();
      e.stopPropagation();
      this.c.fire();
    };
    this.h.scrollTop = 0;
    this.layout(this.q.width, this.j.clientHeight + this.k.clientHeight);
    this.d.fire(this);
  }
  clearContents() {
    this.domNode.classList.add("no-docs");
    this.j.textContent = "";
    this.k.textContent = "";
  }
  get isEmpty() {
    return this.domNode.classList.contains("no-docs");
  }
  get size() {
    return this.q;
  }
  layout(width2, height) {
    const newSize = new $rj(width2, height);
    if (!$rj.equals(newSize, this.q)) {
      this.q = newSize;
      $tj(this.domNode, width2, height);
    }
    this.g.scanDomNode();
  }
  scrollDown(much = 8) {
    this.h.scrollTop += much;
  }
  scrollUp(much = 8) {
    this.h.scrollTop -= much;
  }
  scrollTop() {
    this.h.scrollTop = 0;
  }
  scrollBottom() {
    this.h.scrollTop = this.h.scrollHeight;
  }
  pageDown() {
    this.scrollDown(80);
  }
  pageUp() {
    this.scrollUp(80);
  }
  set borderWidth(width2) {
    this.o = width2;
  }
  get borderWidth() {
    return this.o;
  }
  focus() {
    this.domNode.focus();
  }
};
$edb = __decorate([
  __param(1, $Pk)
], $edb);
var $fdb = class {
  constructor(widget, k) {
    this.widget = widget;
    this.k = k;
    this.allowEditorOverflow = true;
    this.c = new $2c();
    this.f = false;
    this.h = true;
    this.d = new $_2();
    this.d.domNode.classList.add("suggest-details-container");
    this.d.domNode.appendChild(widget.domNode);
    this.d.enableSashes(false, true, true, false);
    let topLeftNow;
    let sizeNow;
    let deltaTop = 0;
    let deltaLeft = 0;
    this.c.add(this.d.onDidWillResize(() => {
      topLeftNow = this.j;
      sizeNow = this.d.size;
    }));
    this.c.add(this.d.onDidResize((e) => {
      if (topLeftNow && sizeNow) {
        this.widget.layout(e.dimension.width, e.dimension.height);
        let updateTopLeft = false;
        if (e.west) {
          deltaLeft = sizeNow.width - e.dimension.width;
          updateTopLeft = true;
        }
        if (e.north) {
          deltaTop = sizeNow.height - e.dimension.height;
          updateTopLeft = true;
        }
        if (updateTopLeft) {
          this.l({
            top: topLeftNow.top + deltaTop,
            left: topLeftNow.left + deltaLeft
          });
        }
      }
      if (e.done) {
        topLeftNow = void 0;
        sizeNow = void 0;
        deltaTop = 0;
        deltaLeft = 0;
        this.i = e.dimension;
      }
    }));
    this.c.add(this.widget.onDidChangeContents(() => {
      if (this.g) {
        this._placeAtAnchor(this.g, this.i ?? this.widget.size, this.h);
      }
    }));
  }
  dispose() {
    this.d.dispose();
    this.c.dispose();
    this.hide();
  }
  getId() {
    return "suggest.details";
  }
  getDomNode() {
    return this.d.domNode;
  }
  getPosition() {
    return this.j ? { preference: this.j } : null;
  }
  show() {
    if (!this.f) {
      this.k.addOverlayWidget(this);
      this.f = true;
    }
  }
  hide(sessionEnded = false) {
    this.d.clearSashHoverState();
    if (this.f) {
      this.k.removeOverlayWidget(this);
      this.f = false;
      this.g = void 0;
      this.j = void 0;
    }
    if (sessionEnded) {
      this.i = void 0;
      this.widget.clearContents();
    }
  }
  placeAtAnchor(anchor, preferAlignAtTop) {
    const anchorBox = anchor.getBoundingClientRect();
    this.g = anchorBox;
    this.h = preferAlignAtTop;
    this._placeAtAnchor(this.g, this.i ?? this.widget.size, preferAlignAtTop);
  }
  _placeAtAnchor(anchorBox, size, preferAlignAtTop) {
    const bodyBox = $qj(this.getDomNode().ownerDocument.body);
    const info = this.widget.getLayoutInfo();
    const defaultMinSize = new $rj(220, 2 * info.lineHeight);
    const defaultTop = anchorBox.top;
    const eastPlacement = function() {
      const width2 = bodyBox.width - (anchorBox.left + anchorBox.width + info.borderWidth + info.horizontalPadding);
      const left2 = -info.borderWidth + anchorBox.left + anchorBox.width;
      const maxSizeTop = new $rj(width2, bodyBox.height - anchorBox.top - info.borderHeight - info.verticalPadding);
      const maxSizeBottom = maxSizeTop.with(void 0, anchorBox.top + anchorBox.height - info.borderHeight - info.verticalPadding);
      return { top: defaultTop, left: left2, fit: width2 - size.width, maxSizeTop, maxSizeBottom, minSize: defaultMinSize.with(Math.min(width2, defaultMinSize.width)) };
    }();
    const westPlacement = function() {
      const width2 = anchorBox.left - info.borderWidth - info.horizontalPadding;
      const left2 = Math.max(info.horizontalPadding, anchorBox.left - size.width - info.borderWidth);
      const maxSizeTop = new $rj(width2, bodyBox.height - anchorBox.top - info.borderHeight - info.verticalPadding);
      const maxSizeBottom = maxSizeTop.with(void 0, anchorBox.top + anchorBox.height - info.borderHeight - info.verticalPadding);
      return { top: defaultTop, left: left2, fit: width2 - size.width, maxSizeTop, maxSizeBottom, minSize: defaultMinSize.with(Math.min(width2, defaultMinSize.width)) };
    }();
    const southPacement = function() {
      const left2 = anchorBox.left;
      const top3 = -info.borderWidth + anchorBox.top + anchorBox.height;
      const maxSizeBottom = new $rj(anchorBox.width - info.borderHeight, bodyBox.height - anchorBox.top - anchorBox.height - info.verticalPadding);
      return { top: top3, left: left2, fit: maxSizeBottom.height - size.height, maxSizeBottom, maxSizeTop: maxSizeBottom, minSize: defaultMinSize.with(maxSizeBottom.width) };
    }();
    const placements = [eastPlacement, westPlacement, southPacement];
    const placement = placements.find((p) => p.fit >= 0) ?? placements.sort((a, b) => b.fit - a.fit)[0];
    const bottom = anchorBox.top + anchorBox.height - info.borderHeight;
    let alignAtTop;
    let height = size.height;
    const maxHeight = Math.max(placement.maxSizeTop.height, placement.maxSizeBottom.height);
    if (height > maxHeight) {
      height = maxHeight;
    }
    let maxSize;
    if (preferAlignAtTop) {
      if (height <= placement.maxSizeTop.height) {
        alignAtTop = true;
        maxSize = placement.maxSizeTop;
      } else {
        alignAtTop = false;
        maxSize = placement.maxSizeBottom;
      }
    } else {
      if (height <= placement.maxSizeBottom.height) {
        alignAtTop = false;
        maxSize = placement.maxSizeBottom;
      } else {
        alignAtTop = true;
        maxSize = placement.maxSizeTop;
      }
    }
    let { top: top2, left } = placement;
    if (!alignAtTop && height > anchorBox.height) {
      top2 = bottom - height;
    }
    const editorDomNode = this.k.getDomNode();
    if (editorDomNode) {
      const editorBoundingBox = editorDomNode.getBoundingClientRect();
      top2 -= editorBoundingBox.top;
      left -= editorBoundingBox.left;
    }
    this.l({ left, top: top2 });
    this.d.enableSashes(!alignAtTop, placement === eastPlacement, alignAtTop, placement !== eastPlacement);
    this.d.minSize = placement.minSize;
    this.d.maxSize = maxSize;
    this.d.layout(height, Math.min(maxSize.width, size.width));
    this.widget.layout(this.d.size.width, this.d.size.height);
  }
  l(topLeft) {
    this.j = topLeft;
    this.k.layoutOverlayWidget(this);
  }
};

// out-build/vs/editor/common/services/getIconClasses.js
var fileIconDirectoryRegex = /(?:\/|^)(?:([^\/]+)\/)?([^\/]+)$/;
function $gdb(modelService, languageService, resource, fileKind, icon2) {
  if (ThemeIcon.isThemeIcon(icon2)) {
    return [`codicon-${icon2.id}`, "predefined-file-icon"];
  }
  if (URI.isUri(icon2)) {
    return [];
  }
  const classes2 = fileKind === FileKind.ROOT_FOLDER ? ["rootfolder-icon"] : fileKind === FileKind.FOLDER ? ["folder-icon"] : ["file-icon"];
  if (resource) {
    let name;
    if (resource.scheme === Schemas.data) {
      const metadata = DataUri.parseMetaData(resource);
      name = metadata.get(DataUri.META_DATA_LABEL);
    } else {
      const match = resource.path.match(fileIconDirectoryRegex);
      if (match) {
        name = $idb(match[2].toLowerCase());
        if (match[1]) {
          classes2.push(`${$idb(match[1].toLowerCase())}-name-dir-icon`);
        }
      } else {
        name = $idb(resource.authority.toLowerCase());
      }
    }
    if (fileKind === FileKind.ROOT_FOLDER) {
      classes2.push(`${name}-root-name-folder-icon`);
    } else if (fileKind === FileKind.FOLDER) {
      classes2.push(`${name}-name-folder-icon`);
    } else {
      if (name) {
        classes2.push(`${name}-name-file-icon`);
        classes2.push(`name-file-icon`);
        if (name.length <= 255) {
          const dotSegments = name.split(".");
          for (let i2 = 1; i2 < dotSegments.length; i2++) {
            classes2.push(`${dotSegments.slice(i2).join(".")}-ext-file-icon`);
          }
        }
        classes2.push(`ext-file-icon`);
      }
      const detectedLanguageId = detectLanguageId(modelService, languageService, resource);
      if (detectedLanguageId) {
        classes2.push(`${$idb(detectedLanguageId)}-lang-file-icon`);
      }
    }
  }
  return classes2;
}
function $hdb(languageId) {
  return ["file-icon", `${$idb(languageId)}-lang-file-icon`];
}
function detectLanguageId(modelService, languageService, resource) {
  if (!resource) {
    return null;
  }
  let languageId = null;
  if (resource.scheme === Schemas.data) {
    const metadata = DataUri.parseMetaData(resource);
    const mime = metadata.get(DataUri.META_DATA_MIME);
    if (mime) {
      languageId = languageService.getLanguageIdByMimeType(mime);
    }
  } else {
    const model = modelService.getModel(resource);
    if (model) {
      languageId = model.getLanguageId();
    }
  }
  if (languageId && languageId !== $KF) {
    return languageId;
  }
  return languageService.guessLanguageIdByFilepathOrFirstLine(resource);
}
function $idb(str) {
  return str.replace(/[\s]/g, "/");
}

// out-build/vs/editor/contrib/suggest/browser/suggestWidgetRenderer.js
function $jdb(index) {
  return `suggest-aria-id:${index}`;
}
var suggestMoreInfoIcon = $9r("suggest-more-info", $6l.chevronRight, localize(1529, null));
var _completionItemColor = new class ColorExtractor {
  static {
    this.a = /(#([\da-fA-F]{3}){1,2}|(rgb|hsl)a\(\s*(\d{1,3}%?\s*,\s*){3}(1|0?\.\d+)\)|(rgb|hsl)\(\s*\d{1,3}%?(\s*,\s*\d{1,3}%?){2}\s*\))/;
  }
  static {
    this.b = new RegExp(`^${ColorExtractor.a.source}$`, "i");
  }
  extract(item, out) {
    if (item.textLabel.match(ColorExtractor.b)) {
      out[0] = item.textLabel;
      return true;
    }
    if (item.completion.detail && item.completion.detail.match(ColorExtractor.b)) {
      out[0] = item.completion.detail;
      return true;
    }
    if (item.completion.documentation) {
      const value = typeof item.completion.documentation === "string" ? item.completion.documentation : item.completion.documentation.value;
      const match = ColorExtractor.a.exec(value);
      if (match && (match.index === 0 || match.index + match[0].length === value.length)) {
        out[0] = match[0];
        return true;
      }
    }
    return false;
  }
}();
var $kdb = class $kdb2 {
  constructor(b, c, d, f) {
    this.b = b;
    this.c = c;
    this.d = d;
    this.f = f;
    this.a = new $ze();
    this.onDidToggleDetails = this.a.event;
    this.templateId = "suggestion";
  }
  dispose() {
    this.a.dispose();
  }
  renderTemplate(container2) {
    const disposables = new $2c();
    const root = container2;
    root.classList.add("show-file-icons");
    const icon2 = $bk(container2, $(".icon"));
    const colorspan = $bk(icon2, $("span.colorspan"));
    const text2 = $bk(container2, $(".contents"));
    const main = $bk(text2, $(".main"));
    const iconContainer = $bk(main, $(".icon-label.codicon"));
    const left = $bk(main, $("span.left"));
    const right = $bk(main, $("span.right"));
    const iconLabel = new $T2(left, { supportHighlights: true, supportIcons: true });
    disposables.add(iconLabel);
    const parametersLabel = $bk(left, $("span.signature-label"));
    const qualifierLabel = $bk(left, $("span.qualifier-label"));
    const detailsLabel = $bk(right, $("span.details-label"));
    const readMore = $bk(right, $("span.readMore" + ThemeIcon.asCSSSelector(suggestMoreInfoIcon)));
    readMore.title = localize(1530, null);
    const configureFont = () => {
      const options3 = this.b.getOptions();
      const fontInfo = options3.get(
        52
        /* EditorOption.fontInfo */
      );
      const fontFamily = fontInfo.getMassagedFontFamily();
      const fontFeatureSettings = fontInfo.fontFeatureSettings;
      const fontSize = options3.get(
        124
        /* EditorOption.suggestFontSize */
      ) || fontInfo.fontSize;
      const lineHeight = options3.get(
        125
        /* EditorOption.suggestLineHeight */
      ) || fontInfo.lineHeight;
      const fontWeight = fontInfo.fontWeight;
      const letterSpacing = fontInfo.letterSpacing;
      const fontSizePx = `${fontSize}px`;
      const lineHeightPx = `${lineHeight}px`;
      const letterSpacingPx = `${letterSpacing}px`;
      root.style.fontSize = fontSizePx;
      root.style.fontWeight = fontWeight;
      root.style.letterSpacing = letterSpacingPx;
      main.style.fontFamily = fontFamily;
      main.style.fontFeatureSettings = fontFeatureSettings;
      main.style.lineHeight = lineHeightPx;
      icon2.style.height = lineHeightPx;
      icon2.style.width = lineHeightPx;
      readMore.style.height = lineHeightPx;
      readMore.style.width = lineHeightPx;
    };
    return { root, left, right, icon: icon2, colorspan, iconLabel, iconContainer, parametersLabel, qualifierLabel, detailsLabel, readMore, disposables, configureFont };
  }
  renderElement(element, index, data) {
    data.configureFont();
    const { completion } = element;
    data.root.id = $jdb(index);
    data.colorspan.style.backgroundColor = "";
    const labelOptions = {
      labelEscapeNewLines: true,
      matches: $Ul(element.score)
    };
    const color2 = [];
    if (completion.kind === 19 && _completionItemColor.extract(element, color2)) {
      data.icon.className = "icon customcolor";
      data.iconContainer.className = "icon hide";
      data.colorspan.style.backgroundColor = color2[0];
    } else if (completion.kind === 20 && this.f.getFileIconTheme().hasFileIcons) {
      data.icon.className = "icon hide";
      data.iconContainer.className = "icon hide";
      const labelClasses = $gdb(this.c, this.d, URI.from({ scheme: "fake", path: element.textLabel }), FileKind.FILE);
      const detailClasses = $gdb(this.c, this.d, URI.from({ scheme: "fake", path: completion.detail }), FileKind.FILE);
      labelOptions.extraClasses = labelClasses.length > detailClasses.length ? labelClasses : detailClasses;
    } else if (completion.kind === 23 && this.f.getFileIconTheme().hasFolderIcons) {
      data.icon.className = "icon hide";
      data.iconContainer.className = "icon hide";
      labelOptions.extraClasses = [
        $gdb(this.c, this.d, URI.from({ scheme: "fake", path: element.textLabel }), FileKind.FOLDER),
        $gdb(this.c, this.d, URI.from({ scheme: "fake", path: completion.detail }), FileKind.FOLDER)
      ].flat();
    } else {
      data.icon.className = "icon hide";
      data.iconContainer.className = "";
      data.iconContainer.classList.add("suggest-icon", ...ThemeIcon.asClassNameArray(CompletionItemKinds.toIcon(completion.kind)));
    }
    if (completion.tags && completion.tags.indexOf(
      1
      /* CompletionItemTag.Deprecated */
    ) >= 0) {
      labelOptions.extraClasses = (labelOptions.extraClasses || []).concat(["deprecated"]);
      labelOptions.matches = [];
    }
    data.iconLabel.setLabel(element.textLabel, void 0, labelOptions);
    if (typeof completion.label === "string") {
      data.parametersLabel.textContent = "";
      data.detailsLabel.textContent = stripNewLines(completion.detail || "");
      data.root.classList.add("string-label");
    } else {
      data.parametersLabel.textContent = stripNewLines(completion.label.detail || "");
      data.detailsLabel.textContent = stripNewLines(completion.label.description || "");
      data.root.classList.remove("string-label");
    }
    if (this.b.getOption(
      123
      /* EditorOption.suggest */
    ).showInlineDetails) {
      $hk(data.detailsLabel);
    } else {
      $ik(data.detailsLabel);
    }
    if ($ddb(element)) {
      data.right.classList.add("can-expand-details");
      $hk(data.readMore);
      data.readMore.onmousedown = (e) => {
        e.stopPropagation();
        e.preventDefault();
      };
      data.readMore.onclick = (e) => {
        e.stopPropagation();
        e.preventDefault();
        this.a.fire();
      };
    } else {
      data.right.classList.remove("can-expand-details");
      $ik(data.readMore);
      data.readMore.onmousedown = null;
      data.readMore.onclick = null;
    }
  }
  disposeTemplate(templateData) {
    templateData.disposables.dispose();
  }
};
$kdb = __decorate([
  __param(1, $sG),
  __param(2, $1E),
  __param(3, $gs)
], $kdb);
function stripNewLines(str) {
  return str.replace(/\r\n|\r|\n/g, "");
}

// out-build/vs/editor/contrib/suggest/browser/suggestWidget.js
var $mdb_1;
$5n("editorSuggestWidget.background", $Qo, localize(1511, null));
$5n("editorSuggestWidget.border", $So, localize(1512, null));
var editorSuggestWidgetForeground = $5n("editorSuggestWidget.foreground", $Lo, localize(1513, null));
$5n("editorSuggestWidget.selectedForeground", $2r, localize(1514, null));
$5n("editorSuggestWidget.selectedIconForeground", $3r, localize(1515, null));
var $ldb = $5n("editorSuggestWidget.selectedBackground", $4r, localize(1516, null));
$5n("editorSuggestWidget.highlightForeground", $ur, localize(1517, null));
$5n("editorSuggestWidget.focusHighlightForeground", $vr, localize(1518, null));
$5n("editorSuggestWidgetStatus.foreground", $0n(editorSuggestWidgetForeground, 0.5), localize(1519, null));
var State3;
(function(State14) {
  State14[State14["Hidden"] = 0] = "Hidden";
  State14[State14["Loading"] = 1] = "Loading";
  State14[State14["Empty"] = 2] = "Empty";
  State14[State14["Open"] = 3] = "Open";
  State14[State14["Frozen"] = 4] = "Frozen";
  State14[State14["Details"] = 5] = "Details";
  State14[State14["onDetailsKeyDown"] = 6] = "onDetailsKeyDown";
})(State3 || (State3 = {}));
var PersistedWidgetSize = class {
  constructor(b, editor) {
    this.b = b;
    this.a = `suggestWidget.size/${editor.getEditorType()}/${editor instanceof $bdb}`;
  }
  restore() {
    const raw = this.b.get(
      this.a,
      0
      /* StorageScope.PROFILE */
    ) ?? "";
    try {
      const obj = JSON.parse(raw);
      if ($rj.is(obj)) {
        return $rj.lift(obj);
      }
    } catch {
    }
    return void 0;
  }
  store(size) {
    this.b.store(
      this.a,
      JSON.stringify(size),
      0,
      1
      /* StorageTarget.MACHINE */
    );
  }
  reset() {
    this.b.remove(
      this.a,
      0
      /* StorageScope.PROFILE */
    );
  }
};
var $mdb = class $mdb2 {
  static {
    $mdb_1 = this;
  }
  static {
    this.a = localize(1520, null);
  }
  static {
    this.b = localize(1521, null);
  }
  constructor(I, J, _contextKeyService, _themeService, instantiationService) {
    this.I = I;
    this.J = J;
    this.c = 0;
    this.d = false;
    this.g = new $4c();
    this.h = new $4c();
    this.k = false;
    this.n = false;
    this.o = false;
    this.B = new $6h();
    this.C = new $2c();
    this.D = new $Ce();
    this.E = new $Ce();
    this.F = new $ze();
    this.G = new $ze();
    this.onDidSelect = this.D.event;
    this.onDidFocus = this.E.event;
    this.onDidHide = this.F.event;
    this.onDidShow = this.G.event;
    this.H = new $ze();
    this.onDetailsKeyDown = this.H.event;
    this.element = new $_2();
    this.element.domNode.classList.add("editor-widget", "suggest-widget");
    this.v = new $ndb(this, I);
    this.w = new PersistedWidgetSize(J, I);
    class ResizeState {
      constructor(persistedSize, currentSize, persistHeight = false, persistWidth = false) {
        this.persistedSize = persistedSize;
        this.currentSize = currentSize;
        this.persistHeight = persistHeight;
        this.persistWidth = persistWidth;
      }
    }
    let state;
    this.C.add(this.element.onDidWillResize(() => {
      this.v.lockPreference();
      state = new ResizeState(this.w.restore(), this.element.size);
    }));
    this.C.add(this.element.onDidResize((e) => {
      this.V(e.dimension.width, e.dimension.height);
      if (state) {
        state.persistHeight = state.persistHeight || !!e.north || !!e.south;
        state.persistWidth = state.persistWidth || !!e.east || !!e.west;
      }
      if (!e.done) {
        return;
      }
      if (state) {
        const { itemHeight, defaultSize } = this.getLayoutInfo();
        const threshold = Math.round(itemHeight / 2);
        let { width: width2, height } = this.element.size;
        if (!state.persistHeight || Math.abs(state.currentSize.height - height) <= threshold) {
          height = state.persistedSize?.height ?? defaultSize.height;
        }
        if (!state.persistWidth || Math.abs(state.currentSize.width - width2) <= threshold) {
          width2 = state.persistedSize?.width ?? defaultSize.width;
        }
        this.w.store(new $rj(width2, height));
      }
      this.v.unlockPreference();
      state = void 0;
    }));
    this.p = $bk(this.element.domNode, $(".message"));
    this.q = $bk(this.element.domNode, $(".tree"));
    const details = this.C.add(instantiationService.createInstance($edb, this.I));
    details.onDidClose(() => this.toggleDetails(), this, this.C);
    this.u = new $fdb(details, this.I);
    const applyIconStyle = () => this.element.domNode.classList.toggle("no-icons", !this.I.getOption(
      123
      /* EditorOption.suggest */
    ).showIcons);
    applyIconStyle();
    const renderer = instantiationService.createInstance($kdb, this.I);
    this.C.add(renderer);
    this.C.add(renderer.onDidToggleDetails(() => this.toggleDetails()));
    this.r = new $A1("SuggestWidget", this.q, {
      getHeight: (_element) => this.getLayoutInfo().itemHeight,
      getTemplateId: (_element) => "suggestion"
    }, [renderer], {
      alwaysConsumeMouseWheel: true,
      useShadows: false,
      mouseSupport: false,
      multipleSelectionSupport: false,
      accessibilityProvider: {
        getRole: () => "option",
        getWidgetAriaLabel: () => localize(1522, null),
        getWidgetRole: () => "listbox",
        getAriaLabel: (item) => {
          let label3 = item.textLabel;
          if (typeof item.completion.label !== "string") {
            const { detail: detail3, description } = item.completion.label;
            if (detail3 && description) {
              label3 = localize(1523, null, label3, detail3, description);
            } else if (detail3) {
              label3 = localize(1524, null, label3, detail3);
            } else if (description) {
              label3 = localize(1525, null, label3, description);
            }
          }
          if (!item.isResolved || !this.X()) {
            return label3;
          }
          const { documentation, detail: detail2 } = item.completion;
          const docs = $wf("{0}{1}", detail2 || "", documentation ? typeof documentation === "string" ? documentation : documentation.value : "");
          return localize(1526, null, label3, docs);
        }
      }
    });
    this.r.style($J$({
      listInactiveFocusBackground: $ldb,
      listInactiveFocusOutline: $lo
    }));
    this.s = instantiationService.createInstance($cdb, this.element.domNode, $acb);
    const applyStatusBarStyle = () => this.element.domNode.classList.toggle("with-status-bar", this.I.getOption(
      123
      /* EditorOption.suggest */
    ).showStatusBar);
    applyStatusBarStyle();
    this.C.add(_themeService.onDidColorThemeChange((t) => this.P(t)));
    this.P(_themeService.getColorTheme());
    this.C.add(this.r.onMouseDown((e) => this.M(e)));
    this.C.add(this.r.onTap((e) => this.M(e)));
    this.C.add(this.r.onDidChangeSelection((e) => this.N(e)));
    this.C.add(this.r.onDidChangeFocus((e) => this.Q(e)));
    this.C.add(this.I.onDidChangeCursorSelection(() => this.L()));
    this.C.add(this.I.onDidChangeConfiguration((e) => {
      if (e.hasChanged(
        123
        /* EditorOption.suggest */
      )) {
        applyStatusBarStyle();
        applyIconStyle();
      }
      if (this.l && (e.hasChanged(
        52
        /* EditorOption.fontInfo */
      ) || e.hasChanged(
        124
        /* EditorOption.suggestFontSize */
      ) || e.hasChanged(
        125
        /* EditorOption.suggestLineHeight */
      ))) {
        this.r.splice(0, this.r.length, this.l.items);
      }
    }));
    this.x = $_bb.Visible.bindTo(_contextKeyService);
    this.y = $_bb.DetailsVisible.bindTo(_contextKeyService);
    this.z = $_bb.MultipleSuggestions.bindTo(_contextKeyService);
    this.A = $_bb.HasFocusedSuggestion.bindTo(_contextKeyService);
    this.C.add($aj(this.u.widget.domNode, "keydown", (e) => {
      this.H.fire(e);
    }));
    this.C.add(this.I.onMouseDown((e) => this.K(e)));
  }
  dispose() {
    this.u.widget.dispose();
    this.u.dispose();
    this.r.dispose();
    this.s.dispose();
    this.C.dispose();
    this.f?.dispose();
    this.g.dispose();
    this.h.dispose();
    this.B.dispose();
    this.v.dispose();
    this.element.dispose();
  }
  K(mouseEvent) {
    if (this.u.widget.domNode.contains(mouseEvent.target.element)) {
      this.u.widget.domNode.focus();
    } else {
      if (this.element.domNode.contains(mouseEvent.target.element)) {
        this.I.focus();
      }
    }
  }
  L() {
    if (this.c !== 0) {
      this.v.layout();
    }
  }
  M(e) {
    if (typeof e.element === "undefined" || typeof e.index === "undefined") {
      return;
    }
    e.browserEvent.preventDefault();
    e.browserEvent.stopPropagation();
    this.O(e.element, e.index);
  }
  N(e) {
    if (e.elements.length) {
      this.O(e.elements[0], e.indexes[0]);
    }
  }
  O(item, index) {
    const completionModel = this.l;
    if (completionModel) {
      this.D.fire({ item, index, model: completionModel });
      this.I.focus();
    }
  }
  P(theme) {
    this.u.widget.borderWidth = $es(theme.type) ? 2 : 1;
  }
  Q(e) {
    if (this.k) {
      return;
    }
    if (this.c === 5) {
      this.R(
        3
        /* State.Open */
      );
    }
    if (!e.elements.length) {
      if (this.i) {
        this.i.cancel();
        this.i = void 0;
        this.j = void 0;
      }
      this.I.setAriaOptions({ activeDescendant: void 0 });
      this.A.set(false);
      return;
    }
    if (!this.l) {
      return;
    }
    this.A.set(true);
    const item = e.elements[0];
    const index = e.indexes[0];
    if (item !== this.j) {
      this.i?.cancel();
      this.i = void 0;
      this.j = item;
      this.r.reveal(index);
      this.i = $Hh(async (token) => {
        const loading = $Xh(() => {
          if (this.X()) {
            this.T(true, false);
          }
        }, 250);
        const sub = token.onCancellationRequested(() => loading.dispose());
        try {
          return await item.resolve(token);
        } finally {
          loading.dispose();
          sub.dispose();
        }
      });
      this.i.then(() => {
        if (index >= this.r.length || item !== this.r.element(index)) {
          return;
        }
        this.k = true;
        this.r.splice(index, 1, [item]);
        this.r.setFocus([index]);
        this.k = false;
        if (this.X()) {
          this.T(false, false);
        } else {
          this.element.domNode.classList.remove("docs-side");
        }
        this.I.setAriaOptions({ activeDescendant: $jdb(index) });
      }).catch($gb);
    }
    this.E.fire({ item, index, model: this.l });
  }
  R(state) {
    if (this.c === state) {
      return;
    }
    this.c = state;
    this.element.domNode.classList.toggle(
      "frozen",
      state === 4
      /* State.Frozen */
    );
    this.element.domNode.classList.remove("message");
    switch (state) {
      case 0:
        $ik(this.p, this.q, this.s.element);
        this.u.hide(true);
        this.s.hide();
        this.v.hide();
        this.x.reset();
        this.z.reset();
        this.A.reset();
        this.B.cancel();
        this.element.domNode.classList.remove("visible");
        this.r.splice(0, this.r.length);
        this.j = void 0;
        this.m = void 0;
        this.o = false;
        break;
      case 1:
        this.element.domNode.classList.add("message");
        this.p.textContent = $mdb_1.a;
        $ik(this.q, this.s.element);
        $hk(this.p);
        this.u.hide();
        this.S();
        this.j = void 0;
        $_Z($mdb_1.a);
        break;
      case 2:
        this.element.domNode.classList.add("message");
        this.p.textContent = $mdb_1.b;
        $ik(this.q, this.s.element);
        $hk(this.p);
        this.u.hide();
        this.S();
        this.j = void 0;
        $_Z($mdb_1.b);
        break;
      case 3:
        $ik(this.p);
        $hk(this.q, this.s.element);
        this.S();
        break;
      case 4:
        $ik(this.p);
        $hk(this.q, this.s.element);
        this.S();
        break;
      case 5:
        $ik(this.p);
        $hk(this.q, this.s.element);
        this.u.show();
        this.S();
        this.u.widget.focus();
        break;
    }
  }
  S() {
    this.s.show();
    this.v.show();
    this.U(this.w.restore());
    this.x.set(true);
    this.B.cancelAndSet(() => {
      this.element.domNode.classList.add("visible");
      this.G.fire(this);
    }, 100);
  }
  showTriggered(auto, delay) {
    if (this.c !== 0) {
      return;
    }
    this.v.setPosition(this.I.getPosition());
    this.d = !!auto;
    if (!this.d) {
      this.f = $Xh(() => this.R(
        1
        /* State.Loading */
      ), delay);
    }
  }
  showSuggestions(completionModel, selectionIndex, isFrozen2, isAuto, noFocus) {
    this.v.setPosition(this.I.getPosition());
    this.f?.dispose();
    this.i?.cancel();
    this.i = void 0;
    if (this.l !== completionModel) {
      this.l = completionModel;
    }
    if (isFrozen2 && this.c !== 2 && this.c !== 0) {
      this.R(
        4
        /* State.Frozen */
      );
      return;
    }
    const visibleCount = this.l.items.length;
    const isEmpty = visibleCount === 0;
    this.z.set(visibleCount > 1);
    if (isEmpty) {
      this.R(
        isAuto ? 0 : 2
        /* State.Empty */
      );
      this.l = void 0;
      return;
    }
    this.j = void 0;
    this.E.pause();
    this.D.pause();
    try {
      this.r.splice(0, this.r.length, this.l.items);
      this.R(
        isFrozen2 ? 4 : 3
        /* State.Open */
      );
      this.r.reveal(selectionIndex, 0);
      this.r.setFocus(noFocus ? [] : [selectionIndex]);
    } finally {
      this.E.resume();
      this.D.resume();
    }
    this.g.value = $ij(getWindow(this.element.domNode), () => {
      this.g.clear();
      this.U(this.element.size);
      this.u.widget.domNode.classList.remove("focused");
    });
  }
  focusSelected() {
    if (this.r.length > 0) {
      this.r.setFocus([0]);
    }
  }
  selectNextPage() {
    switch (this.c) {
      case 0:
        return false;
      case 5:
        this.u.widget.pageDown();
        return true;
      case 1:
        return !this.d;
      default:
        this.r.focusNextPage();
        return true;
    }
  }
  selectNext() {
    switch (this.c) {
      case 0:
        return false;
      case 1:
        return !this.d;
      default:
        this.r.focusNext(1, true);
        return true;
    }
  }
  selectLast() {
    switch (this.c) {
      case 0:
        return false;
      case 5:
        this.u.widget.scrollBottom();
        return true;
      case 1:
        return !this.d;
      default:
        this.r.focusLast();
        return true;
    }
  }
  selectPreviousPage() {
    switch (this.c) {
      case 0:
        return false;
      case 5:
        this.u.widget.pageUp();
        return true;
      case 1:
        return !this.d;
      default:
        this.r.focusPreviousPage();
        return true;
    }
  }
  selectPrevious() {
    switch (this.c) {
      case 0:
        return false;
      case 1:
        return !this.d;
      default:
        this.r.focusPrevious(1, true);
        return false;
    }
  }
  selectFirst() {
    switch (this.c) {
      case 0:
        return false;
      case 5:
        this.u.widget.scrollTop();
        return true;
      case 1:
        return !this.d;
      default:
        this.r.focusFirst();
        return true;
    }
  }
  getFocusedItem() {
    if (this.c !== 0 && this.c !== 2 && this.c !== 1 && this.l && this.r.getFocus().length > 0) {
      return {
        item: this.r.getFocusedElements()[0],
        index: this.r.getFocus()[0],
        model: this.l
      };
    }
    return void 0;
  }
  toggleDetailsFocus() {
    if (this.c === 5) {
      this.r.setFocus(this.r.getFocus());
      this.R(
        3
        /* State.Open */
      );
    } else if (this.c === 3) {
      this.R(
        5
        /* State.Details */
      );
      if (!this.X()) {
        this.toggleDetails(true);
      } else {
        this.u.widget.focus();
      }
    }
  }
  toggleDetails(focused = false) {
    if (this.X()) {
      this.h.clear();
      this.y.set(false);
      this.Y(false);
      this.u.hide();
      this.element.domNode.classList.remove("shows-details");
    } else if (($ddb(this.r.getFocusedElements()[0]) || this.o) && (this.c === 3 || this.c === 5 || this.c === 4)) {
      this.y.set(true);
      this.Y(true);
      this.T(false, focused);
    }
  }
  T(loading, focused) {
    this.h.value = $ij(getWindow(this.element.domNode), () => {
      this.h.clear();
      this.u.show();
      let didFocusDetails = false;
      if (loading) {
        this.u.widget.renderLoading();
      } else {
        this.u.widget.renderItem(this.r.getFocusedElements()[0], this.o);
      }
      if (!this.u.widget.isEmpty) {
        this.W();
        this.element.domNode.classList.add("shows-details");
        if (focused) {
          this.u.widget.focus();
          didFocusDetails = true;
        }
      } else {
        this.u.hide();
      }
      if (!didFocusDetails) {
        this.I.focus();
      }
    });
  }
  toggleExplainMode() {
    if (this.r.getFocusedElements()[0]) {
      this.o = !this.o;
      if (!this.X()) {
        this.toggleDetails();
      } else {
        this.T(false, false);
      }
    }
  }
  resetPersistedSize() {
    this.w.reset();
  }
  hideWidget() {
    this.g.clear();
    this.h.clear();
    this.f?.dispose();
    this.R(
      0
      /* State.Hidden */
    );
    this.F.fire(this);
    this.element.clearSashHoverState();
    const dim = this.w.restore();
    const minPersistedHeight = Math.ceil(this.getLayoutInfo().itemHeight * 4.3);
    if (dim && dim.height < minPersistedHeight) {
      this.w.store(dim.with(void 0, minPersistedHeight));
    }
  }
  isFrozen() {
    return this.c === 4;
  }
  _afterRender(position) {
    if (position === null) {
      if (this.X()) {
        this.u.hide();
      }
      return;
    }
    if (this.c === 2 || this.c === 1) {
      return;
    }
    if (this.X() && !this.u.widget.isEmpty) {
      this.u.show();
    }
    this.W();
  }
  U(size) {
    if (!this.I.hasModel()) {
      return;
    }
    if (!this.I.getDomNode()) {
      return;
    }
    const bodyBox = $qj(this.element.domNode.ownerDocument.body);
    const info = this.getLayoutInfo();
    if (!size) {
      size = info.defaultSize;
    }
    let height = size.height;
    let width2 = size.width;
    this.s.element.style.height = `${info.itemHeight}px`;
    if (this.c === 2 || this.c === 1) {
      height = info.itemHeight + info.borderHeight;
      width2 = info.defaultSize.width / 2;
      this.element.enableSashes(false, false, false, false);
      this.element.minSize = this.element.maxSize = new $rj(width2, height);
      this.v.setPreference(
        2
        /* ContentWidgetPositionPreference.BELOW */
      );
    } else {
      const maxWidth = bodyBox.width - info.borderHeight - 2 * info.horizontalPadding;
      if (width2 > maxWidth) {
        width2 = maxWidth;
      }
      const preferredWidth = this.l ? this.l.stats.pLabelLen * info.typicalHalfwidthCharacterWidth : width2;
      const fullHeight = info.statusBarHeight + this.r.contentHeight + info.borderHeight;
      const minHeight = info.itemHeight + info.statusBarHeight;
      const editorBox = $vj(this.I.getDomNode());
      const cursorBox = this.I.getScrolledVisiblePosition(this.I.getPosition());
      const cursorBottom = editorBox.top + cursorBox.top + cursorBox.height;
      const maxHeightBelow = Math.min(bodyBox.height - cursorBottom - info.verticalPadding, fullHeight);
      const availableSpaceAbove = editorBox.top + cursorBox.top - info.verticalPadding;
      const maxHeightAbove = Math.min(availableSpaceAbove, fullHeight);
      let maxHeight = Math.min(Math.max(maxHeightAbove, maxHeightBelow) + info.borderHeight, fullHeight);
      if (height === this.m?.capped) {
        height = this.m.wanted;
      }
      if (height < minHeight) {
        height = minHeight;
      }
      if (height > maxHeight) {
        height = maxHeight;
      }
      const forceRenderingAboveRequiredSpace = 150;
      if (height > maxHeightBelow || this.n && availableSpaceAbove > forceRenderingAboveRequiredSpace) {
        this.v.setPreference(
          1
          /* ContentWidgetPositionPreference.ABOVE */
        );
        this.element.enableSashes(true, true, false, false);
        maxHeight = maxHeightAbove;
      } else {
        this.v.setPreference(
          2
          /* ContentWidgetPositionPreference.BELOW */
        );
        this.element.enableSashes(false, true, true, false);
        maxHeight = maxHeightBelow;
      }
      this.element.preferredSize = new $rj(preferredWidth, info.defaultSize.height);
      this.element.maxSize = new $rj(maxWidth, maxHeight);
      this.element.minSize = new $rj(220, minHeight);
      this.m = height === fullHeight ? { wanted: this.m?.wanted ?? size.height, capped: height } : void 0;
    }
    this.V(width2, height);
  }
  V(width2, height) {
    const { width: maxWidth, height: maxHeight } = this.element.maxSize;
    width2 = Math.min(maxWidth, width2);
    height = Math.min(maxHeight, height);
    const { statusBarHeight } = this.getLayoutInfo();
    this.r.layout(height - statusBarHeight, width2);
    this.q.style.height = `${height - statusBarHeight}px`;
    this.element.layout(height, width2);
    this.v.layout();
    this.W();
  }
  W() {
    if (this.X()) {
      this.u.placeAtAnchor(
        this.element.domNode,
        this.v.getPosition()?.preference[0] === 2
        /* ContentWidgetPositionPreference.BELOW */
      );
    }
  }
  getLayoutInfo() {
    const fontInfo = this.I.getOption(
      52
      /* EditorOption.fontInfo */
    );
    const itemHeight = $4i(this.I.getOption(
      125
      /* EditorOption.suggestLineHeight */
    ) || fontInfo.lineHeight, 8, 1e3);
    const statusBarHeight = !this.I.getOption(
      123
      /* EditorOption.suggest */
    ).showStatusBar || this.c === 2 || this.c === 1 ? 0 : itemHeight;
    const borderWidth = this.u.widget.borderWidth;
    const borderHeight = 2 * borderWidth;
    return {
      itemHeight,
      statusBarHeight,
      borderWidth,
      borderHeight,
      typicalHalfwidthCharacterWidth: fontInfo.typicalHalfwidthCharacterWidth,
      verticalPadding: 22,
      horizontalPadding: 14,
      defaultSize: new $rj(430, statusBarHeight + 12 * itemHeight + borderHeight)
    };
  }
  X() {
    return this.J.getBoolean("expandSuggestionDocs", 0, false);
  }
  Y(value) {
    this.J.store(
      "expandSuggestionDocs",
      value,
      0,
      0
      /* StorageTarget.USER */
    );
  }
  forceRenderingAbove() {
    if (!this.n) {
      this.n = true;
      this.U(this.w.restore());
    }
  }
  stopForceRenderingAbove() {
    this.n = false;
  }
};
$mdb = $mdb_1 = __decorate([
  __param(1, $jv),
  __param(2, $on),
  __param(3, $gs),
  __param(4, $Pk)
], $mdb);
var $ndb = class {
  constructor(g, h3) {
    this.g = g;
    this.h = h3;
    this.allowEditorOverflow = true;
    this.suppressMouseDown = false;
    this.c = false;
    this.d = false;
    this.f = false;
  }
  dispose() {
    if (this.d) {
      this.d = false;
      this.h.removeContentWidget(this);
    }
  }
  getId() {
    return "editor.widget.suggestWidget";
  }
  getDomNode() {
    return this.g.element.domNode;
  }
  show() {
    this.f = false;
    if (!this.d) {
      this.d = true;
      this.h.addContentWidget(this);
    }
  }
  hide() {
    if (!this.f) {
      this.f = true;
      this.layout();
    }
  }
  layout() {
    this.h.layoutContentWidget(this);
  }
  getPosition() {
    if (this.f || !this.a || !this.b) {
      return null;
    }
    return {
      position: this.a,
      preference: [this.b]
    };
  }
  beforeRender() {
    const { height, width: width2 } = this.g.element.size;
    const { borderWidth, horizontalPadding } = this.g.getLayoutInfo();
    return new $rj(width2 + 2 * borderWidth + horizontalPadding, height + 2 * borderWidth);
  }
  afterRender(position) {
    this.g._afterRender(position);
  }
  setPreference(preference) {
    if (!this.c) {
      this.b = preference;
    }
  }
  lockPreference() {
    this.c = true;
  }
  unlockPreference() {
    this.c = false;
  }
  setPosition(position) {
    this.a = position;
  }
};

// out-build/vs/editor/contrib/suggest/browser/suggestController.js
var $qdb_1;
var _sticky2 = false;
var LineSuffix = class {
  constructor(d, f) {
    this.d = d;
    this.f = f;
    this.a = $WI.register({
      description: "suggest-line-suffix",
      stickiness: 1
      /* TrackedRangeStickiness.NeverGrowsWhenTypingAtEdges */
    });
    const maxColumn = d.getLineMaxColumn(f.lineNumber);
    if (maxColumn !== f.column) {
      const offset = d.getOffsetAt(f);
      const end = d.getPositionAt(offset + 1);
      d.changeDecorations((accessor) => {
        if (this.b) {
          accessor.removeDecoration(this.b);
        }
        this.b = accessor.addDecoration($9C.fromPositions(f, end), this.a);
      });
    }
  }
  dispose() {
    if (this.b && !this.d.isDisposed()) {
      this.d.changeDecorations((accessor) => {
        accessor.removeDecoration(this.b);
        this.b = void 0;
      });
    }
  }
  delta(position) {
    if (this.d.isDisposed() || this.f.lineNumber !== position.lineNumber) {
      return 0;
    }
    if (this.b) {
      const range = this.d.getDecorationRange(this.b);
      const end = this.d.getOffsetAt(range.getStartPosition());
      return end - this.d.getOffsetAt(position);
    } else {
      return this.d.getLineMaxColumn(position.lineNumber) - position.column;
    }
  }
};
var InsertFlags;
(function(InsertFlags2) {
  InsertFlags2[InsertFlags2["None"] = 0] = "None";
  InsertFlags2[InsertFlags2["NoBeforeUndoStop"] = 1] = "NoBeforeUndoStop";
  InsertFlags2[InsertFlags2["NoAfterUndoStop"] = 2] = "NoAfterUndoStop";
  InsertFlags2[InsertFlags2["KeepAlternativeSuggestions"] = 4] = "KeepAlternativeSuggestions";
  InsertFlags2[InsertFlags2["AlternativeOverwriteConfig"] = 8] = "AlternativeOverwriteConfig";
})(InsertFlags || (InsertFlags = {}));
var $qdb = class $qdb2 {
  static {
    $qdb_1 = this;
  }
  static {
    this.ID = "editor.contrib.suggestController";
  }
  static get(editor) {
    return editor.getContribution($qdb_1.ID);
  }
  constructor(editor, j, k, l, m, n, o) {
    this.j = j;
    this.k = k;
    this.l = l;
    this.m = m;
    this.n = n;
    this.o = o;
    this.b = new $4c();
    this.d = new $2c();
    this.g = new PriorityRegistry((s) => s.priority);
    this.h = new $ze();
    this.onWillInsertSuggestItem = this.h.event;
    this.editor = editor;
    this.model = m.createInstance($qcb, this.editor);
    this.g.register({
      priority: 0,
      select: (model, pos, items) => this.j.select(model, pos, items)
    });
    const ctxInsertMode = $_bb.InsertMode.bindTo(l);
    ctxInsertMode.set(editor.getOption(
      123
      /* EditorOption.suggest */
    ).insertMode);
    this.d.add(this.model.onDidTrigger(() => ctxInsertMode.set(editor.getOption(
      123
      /* EditorOption.suggest */
    ).insertMode)));
    this.widget = this.d.add(new $hj(getWindow(editor.getDomNode()), () => {
      const widget = this.m.createInstance($mdb, this.editor);
      this.d.add(widget);
      this.d.add(widget.onDidSelect((item) => this.p(
        item,
        0
        /* InsertFlags.None */
      ), this));
      const commitCharacterController = new $pdb(this.editor, widget, this.model, (item) => this.p(
        item,
        2
        /* InsertFlags.NoAfterUndoStop */
      ));
      this.d.add(commitCharacterController);
      const ctxMakesTextEdit = $_bb.MakesTextEdit.bindTo(this.l);
      const ctxHasInsertAndReplace = $_bb.HasInsertAndReplaceRange.bindTo(this.l);
      const ctxCanResolve = $_bb.CanResolve.bindTo(this.l);
      this.d.add($1c(() => {
        ctxMakesTextEdit.reset();
        ctxHasInsertAndReplace.reset();
        ctxCanResolve.reset();
      }));
      this.d.add(widget.onDidFocus(({ item }) => {
        const position = this.editor.getPosition();
        const startColumn = item.editStart.column;
        const endColumn = position.column;
        let value = true;
        if (this.editor.getOption(
          1
          /* EditorOption.acceptSuggestionOnEnter */
        ) === "smart" && this.model.state === 2 && !item.completion.additionalTextEdits && !(item.completion.insertTextRules & 4) && endColumn - startColumn === item.completion.insertText.length) {
          const oldText = this.editor.getModel().getValueInRange({
            startLineNumber: position.lineNumber,
            startColumn,
            endLineNumber: position.lineNumber,
            endColumn
          });
          value = oldText !== item.completion.insertText;
        }
        ctxMakesTextEdit.set(value);
        ctxHasInsertAndReplace.set(!$8C.equals(item.editInsertEnd, item.editReplaceEnd));
        ctxCanResolve.set(Boolean(item.provider.resolveCompletionItem) || Boolean(item.completion.documentation) || item.completion.detail !== item.completion.label);
      }));
      this.d.add(widget.onDetailsKeyDown((e) => {
        if (e.toKeyCodeChord().equals(new $bf(
          true,
          false,
          false,
          false,
          33
          /* KeyCode.KeyC */
        )) || $m && e.toKeyCodeChord().equals(new $bf(
          false,
          false,
          false,
          true,
          33
          /* KeyCode.KeyC */
        ))) {
          e.stopPropagation();
          return;
        }
        if (!e.toKeyCodeChord().isModifierKey()) {
          this.editor.focus();
        }
      }));
      return widget;
    }));
    this.f = this.d.add(new $hj(getWindow(editor.getDomNode()), () => {
      return this.d.add(new $rcb(this.editor, this.model));
    }));
    this.a = this.d.add(new $hj(getWindow(editor.getDomNode()), () => {
      return this.d.add(new $odb(this.editor, this.l));
    }));
    this.d.add(m.createInstance($adb, editor));
    this.d.add(this.model.onDidTrigger((e) => {
      this.widget.value.showTriggered(e.auto, e.shy ? 250 : 50);
      this.b.value = new LineSuffix(this.editor.getModel(), e.position);
    }));
    this.d.add(this.model.onDidSuggest((e) => {
      if (e.triggerOptions.shy) {
        return;
      }
      let index = -1;
      for (const selector of this.g.itemsOrderedByPriorityDesc) {
        index = selector.select(this.editor.getModel(), this.editor.getPosition(), e.completionModel.items);
        if (index !== -1) {
          break;
        }
      }
      if (index === -1) {
        index = 0;
      }
      if (this.model.state === 0) {
        return;
      }
      let noFocus = false;
      if (e.triggerOptions.auto) {
        const options3 = this.editor.getOption(
          123
          /* EditorOption.suggest */
        );
        if (options3.selectionMode === "never" || options3.selectionMode === "always") {
          noFocus = options3.selectionMode === "never";
        } else if (options3.selectionMode === "whenTriggerCharacter") {
          noFocus = e.triggerOptions.triggerKind !== 1;
        } else if (options3.selectionMode === "whenQuickSuggestion") {
          noFocus = e.triggerOptions.triggerKind === 1 && !e.triggerOptions.refilter;
        }
      }
      this.widget.value.showSuggestions(e.completionModel, index, e.isFrozen, e.triggerOptions.auto, noFocus);
    }));
    this.d.add(this.model.onDidCancel((e) => {
      if (!e.retrigger) {
        this.widget.value.hideWidget();
      }
    }));
    this.d.add(this.editor.onDidBlurEditorWidget(() => {
      if (!_sticky2) {
        this.model.cancel();
        this.model.clear();
      }
    }));
    const acceptSuggestionsOnEnter = $_bb.AcceptSuggestionsOnEnter.bindTo(l);
    const updateFromConfig = () => {
      const acceptSuggestionOnEnter = this.editor.getOption(
        1
        /* EditorOption.acceptSuggestionOnEnter */
      );
      acceptSuggestionsOnEnter.set(acceptSuggestionOnEnter === "on" || acceptSuggestionOnEnter === "smart");
    };
    this.d.add(this.editor.onDidChangeConfiguration(() => updateFromConfig()));
    updateFromConfig();
  }
  dispose() {
    this.a.dispose();
    this.d.dispose();
    this.widget.dispose();
    this.model.dispose();
    this.b.dispose();
    this.h.dispose();
  }
  p(event, flags) {
    if (!event || !event.item) {
      this.a.value.reset();
      this.model.cancel();
      this.model.clear();
      return;
    }
    if (!this.editor.hasModel()) {
      return;
    }
    const snippetController = $Dcb.get(this.editor);
    if (!snippetController) {
      return;
    }
    this.h.fire({ item: event.item });
    const model = this.editor.getModel();
    const modelVersionNow = model.getAlternativeVersionId();
    const { item } = event;
    const tasks2 = [];
    const cts = new $ad();
    if (!(flags & 1)) {
      this.editor.pushUndoStop();
    }
    const info = this.getOverwriteInfo(item, Boolean(
      flags & 8
      /* InsertFlags.AlternativeOverwriteConfig */
    ));
    this.j.memorize(model, this.editor.getPosition(), item);
    const isResolved = item.isResolved;
    let _commandExectionDuration = -1;
    let _additionalEditsAppliedAsync = -1;
    if (Array.isArray(item.completion.additionalTextEdits)) {
      this.model.cancel();
      const scrollState = $O9.capture(this.editor);
      this.editor.executeEdits("suggestController.additionalTextEdits.sync", item.completion.additionalTextEdits.map((edit3) => {
        let range = $9C.lift(edit3.range);
        if (range.startLineNumber === item.position.lineNumber && range.startColumn > item.position.column) {
          const columnDelta = this.editor.getPosition().column - item.position.column;
          const startColumnDelta = columnDelta;
          const endColumnDelta = $9C.spansMultipleLines(range) ? 0 : columnDelta;
          range = new $9C(range.startLineNumber, range.startColumn + startColumnDelta, range.endLineNumber, range.endColumn + endColumnDelta);
        }
        return $bD.replaceMove(range, edit3.text);
      }));
      scrollState.restoreRelativeVerticalPositionOfCursor(this.editor);
    } else if (!isResolved) {
      const sw = new $te();
      let position;
      const docListener = model.onDidChangeContent((e) => {
        if (e.isFlush) {
          cts.cancel();
          docListener.dispose();
          return;
        }
        for (const change of e.changes) {
          const thisPosition = $9C.getEndPosition(change.range);
          if (!position || $8C.isBefore(thisPosition, position)) {
            position = thisPosition;
          }
        }
      });
      const oldFlags = flags;
      flags |= 2;
      let didType = false;
      const typeListener = this.editor.onWillType(() => {
        typeListener.dispose();
        didType = true;
        if (!(oldFlags & 2)) {
          this.editor.pushUndoStop();
        }
      });
      tasks2.push(item.resolve(cts.token).then(() => {
        if (!item.completion.additionalTextEdits || cts.token.isCancellationRequested) {
          return void 0;
        }
        if (position && item.completion.additionalTextEdits.some((edit3) => $8C.isBefore(position, $9C.getStartPosition(edit3.range)))) {
          return false;
        }
        if (didType) {
          this.editor.pushUndoStop();
        }
        const scrollState = $O9.capture(this.editor);
        this.editor.executeEdits("suggestController.additionalTextEdits.async", item.completion.additionalTextEdits.map((edit3) => $bD.replaceMove($9C.lift(edit3.range), edit3.text)));
        scrollState.restoreRelativeVerticalPositionOfCursor(this.editor);
        if (didType || !(oldFlags & 2)) {
          this.editor.pushUndoStop();
        }
        return true;
      }).then((applied) => {
        this.n.trace("[suggest] async resolving of edits DONE (ms, applied?)", sw.elapsed(), applied);
        _additionalEditsAppliedAsync = applied === true ? 1 : applied === false ? 0 : -2;
      }).finally(() => {
        docListener.dispose();
        typeListener.dispose();
      }));
    }
    let { insertText } = item.completion;
    if (!(item.completion.insertTextRules & 4)) {
      insertText = $0_.escape(insertText);
    }
    this.model.cancel();
    snippetController.insert(insertText, {
      overwriteBefore: info.overwriteBefore,
      overwriteAfter: info.overwriteAfter,
      undoStopBefore: false,
      undoStopAfter: false,
      adjustWhitespace: !(item.completion.insertTextRules & 1),
      clipboardText: event.model.clipboardText,
      overtypingCapturer: this.f.value
    });
    if (!(flags & 2)) {
      this.editor.pushUndoStop();
    }
    if (item.completion.command) {
      if (item.completion.command.id === $rdb.id) {
        this.model.trigger({ auto: true, retrigger: true });
      } else {
        const sw = new $te();
        tasks2.push(this.k.executeCommand(item.completion.command.id, ...item.completion.command.arguments ? [...item.completion.command.arguments] : []).catch((e) => {
          if (item.completion.extensionId) {
            $hb(e);
          } else {
            $gb(e);
          }
        }).finally(() => {
          _commandExectionDuration = sw.elapsed();
        }));
      }
    }
    if (flags & 4) {
      this.a.value.set(event, (next) => {
        cts.cancel();
        while (model.canUndo()) {
          if (modelVersionNow !== model.getAlternativeVersionId()) {
            model.undo();
          }
          this.p(next, 1 | 2 | (flags & 8 ? 8 : 0));
          break;
        }
      });
    }
    this.r(item);
    Promise.all(tasks2).finally(() => {
      this.q(item, model, isResolved, _commandExectionDuration, _additionalEditsAppliedAsync, event.index, event.model.items);
      this.model.clear();
      cts.dispose();
    });
  }
  q(item, model, itemResolved, commandExectionDuration, additionalEditsAppliedAsync, index, completionItems) {
    if (Math.floor(Math.random() * 100) === 0) {
      return;
    }
    const labelMap = /* @__PURE__ */ new Map();
    for (let i2 = 0; i2 < Math.min(30, completionItems.length); i2++) {
      const label3 = completionItems[i2].textLabel;
      if (labelMap.has(label3)) {
        labelMap.get(label3).push(i2);
      } else {
        labelMap.set(label3, [i2]);
      }
    }
    const firstIndexArray = labelMap.get(item.textLabel);
    const hasDuplicates = firstIndexArray && firstIndexArray.length > 1;
    const firstIndex = hasDuplicates ? firstIndexArray[0] : -1;
    this.o.publicLog2("suggest.acceptedSuggestion", {
      extensionId: item.extensionId?.value ?? "unknown",
      providerId: item.provider._debugDisplayName ?? "unknown",
      kind: item.completion.kind,
      basenameHash: $Xi($sh(model.uri)).toString(16),
      languageId: model.getLanguageId(),
      fileExtension: $th(model.uri),
      resolveInfo: !item.provider.resolveCompletionItem ? -1 : itemResolved ? 1 : 0,
      resolveDuration: item.resolveDuration,
      commandDuration: commandExectionDuration,
      additionalEditsAsync: additionalEditsAppliedAsync,
      index,
      firstIndex
    });
  }
  getOverwriteInfo(item, toggleMode) {
    $Jg(this.editor.hasModel());
    let replace = this.editor.getOption(
      123
      /* EditorOption.suggest */
    ).insertMode === "replace";
    if (toggleMode) {
      replace = !replace;
    }
    const overwriteBefore = item.position.column - item.editStart.column;
    const overwriteAfter = (replace ? item.editReplaceEnd.column : item.editInsertEnd.column) - item.position.column;
    const columnDelta = this.editor.getPosition().column - item.position.column;
    const suffixDelta = this.b.value ? this.b.value.delta(this.editor.getPosition()) : 0;
    return {
      overwriteBefore: overwriteBefore + columnDelta,
      overwriteAfter: overwriteAfter + suffixDelta
    };
  }
  r(item) {
    if ($Qb(item.completion.additionalTextEdits)) {
      const msg = localize(1501, null, item.textLabel, item.completion.additionalTextEdits.length);
      $$Z(msg);
    }
  }
  triggerSuggest(onlyFrom, auto, noFilter) {
    if (this.editor.hasModel()) {
      this.model.trigger({
        auto: auto ?? false,
        completionOptions: { providerFilter: onlyFrom, kindFilter: noFilter ? /* @__PURE__ */ new Set() : void 0 }
      });
      this.editor.revealPosition(
        this.editor.getPosition(),
        0
        /* ScrollType.Smooth */
      );
      this.editor.focus();
    }
  }
  triggerSuggestAndAcceptBest(arg) {
    if (!this.editor.hasModel()) {
      return;
    }
    const positionNow = this.editor.getPosition();
    const fallback2 = () => {
      if (positionNow.equals(this.editor.getPosition())) {
        this.k.executeCommand(arg.fallback);
      }
    };
    const makesTextEdit = (item) => {
      if (item.completion.insertTextRules & 4 || item.completion.additionalTextEdits) {
        return true;
      }
      const position = this.editor.getPosition();
      const startColumn = item.editStart.column;
      const endColumn = position.column;
      if (endColumn - startColumn !== item.completion.insertText.length) {
        return true;
      }
      const textNow = this.editor.getModel().getValueInRange({
        startLineNumber: position.lineNumber,
        startColumn,
        endLineNumber: position.lineNumber,
        endColumn
      });
      return textNow !== item.completion.insertText;
    };
    Event2.once(this.model.onDidTrigger)((_) => {
      const listener = [];
      Event2.any(this.model.onDidTrigger, this.model.onDidCancel)(() => {
        $Xc(listener);
        fallback2();
      }, void 0, listener);
      this.model.onDidSuggest(({ completionModel }) => {
        $Xc(listener);
        if (completionModel.items.length === 0) {
          fallback2();
          return;
        }
        const index = this.j.select(this.editor.getModel(), this.editor.getPosition(), completionModel.items);
        const item = completionModel.items[index];
        if (!makesTextEdit(item)) {
          fallback2();
          return;
        }
        this.editor.pushUndoStop();
        this.p(
          { index, item, model: completionModel },
          4 | 1 | 2
          /* InsertFlags.NoAfterUndoStop */
        );
      }, void 0, listener);
    });
    this.model.trigger({ auto: false, shy: true });
    this.editor.revealPosition(
      positionNow,
      0
      /* ScrollType.Smooth */
    );
    this.editor.focus();
  }
  acceptSelectedSuggestion(keepAlternativeSuggestions, alternativeOverwriteConfig) {
    const item = this.widget.value.getFocusedItem();
    let flags = 0;
    if (keepAlternativeSuggestions) {
      flags |= 4;
    }
    if (alternativeOverwriteConfig) {
      flags |= 8;
    }
    this.p(item, flags);
  }
  acceptNextSuggestion() {
    this.a.value.next();
  }
  acceptPrevSuggestion() {
    this.a.value.prev();
  }
  cancelSuggestWidget() {
    this.model.cancel();
    this.model.clear();
    this.widget.value.hideWidget();
  }
  focusSuggestion() {
    this.widget.value.focusSelected();
  }
  selectNextSuggestion() {
    this.widget.value.selectNext();
  }
  selectNextPageSuggestion() {
    this.widget.value.selectNextPage();
  }
  selectLastSuggestion() {
    this.widget.value.selectLast();
  }
  selectPrevSuggestion() {
    this.widget.value.selectPrevious();
  }
  selectPrevPageSuggestion() {
    this.widget.value.selectPreviousPage();
  }
  selectFirstSuggestion() {
    this.widget.value.selectFirst();
  }
  toggleSuggestionDetails() {
    this.widget.value.toggleDetails();
  }
  toggleExplainMode() {
    this.widget.value.toggleExplainMode();
  }
  toggleSuggestionFocus() {
    this.widget.value.toggleDetailsFocus();
  }
  resetWidgetSize() {
    this.widget.value.resetPersistedSize();
  }
  forceRenderingAbove() {
    this.widget.value.forceRenderingAbove();
  }
  stopForceRenderingAbove() {
    if (!this.widget.isInitialized) {
      return;
    }
    this.widget.value.stopForceRenderingAbove();
  }
  registerSelector(selector) {
    return this.g.register(selector);
  }
};
$qdb = $qdb_1 = __decorate([
  __param(1, $_cb),
  __param(2, $sn),
  __param(3, $on),
  __param(4, $Pk),
  __param(5, $wn),
  __param(6, $zv)
], $qdb);
var PriorityRegistry = class {
  constructor(b) {
    this.b = b;
    this.a = new Array();
  }
  register(value) {
    if (this.a.indexOf(value) !== -1) {
      throw new Error("Value is already registered");
    }
    this.a.push(value);
    this.a.sort((s1, s2) => this.b(s2) - this.b(s1));
    return {
      dispose: () => {
        const idx = this.a.indexOf(value);
        if (idx >= 0) {
          this.a.splice(idx, 1);
        }
      }
    };
  }
  get itemsOrderedByPriorityDesc() {
    return this.a;
  }
};
var $rdb = class _$rdb extends $Z5 {
  static {
    this.id = "editor.action.triggerSuggest";
  }
  constructor() {
    super({
      id: _$rdb.id,
      label: localize2(1509, "Trigger Suggest"),
      precondition: $7m.and(EditorContextKeys.writable, EditorContextKeys.hasCompletionItemProvider, $_bb.Visible.toNegated()),
      kbOpts: {
        kbExpr: EditorContextKeys.textInputFocus,
        primary: 2048 | 10,
        secondary: [
          2048 | 39
          /* KeyCode.KeyI */
        ],
        mac: { primary: 256 | 10, secondary: [
          512 | 9,
          2048 | 39
          /* KeyCode.KeyI */
        ] },
        weight: 100
        /* KeybindingWeight.EditorContrib */
      }
    });
  }
  run(_accessor, editor, args2) {
    const controller = $qdb.get(editor);
    if (!controller) {
      return;
    }
    let auto;
    if (args2 && typeof args2 === "object") {
      if (args2.auto === true) {
        auto = true;
      }
    }
    controller.triggerSuggest(void 0, auto, void 0);
  }
};
$85(
  $qdb.ID,
  $qdb,
  2
  /* EditorContributionInstantiation.BeforeFirstInteraction */
);
$55($rdb);
var weight2 = 100 + 90;
var SuggestCommand = $Y5.bindToContribution($qdb.get);
$45(new SuggestCommand({
  id: "acceptSelectedSuggestion",
  precondition: $7m.and($_bb.Visible, $_bb.HasFocusedSuggestion),
  handler(x) {
    x.acceptSelectedSuggestion(true, false);
  },
  kbOpts: [{
    // normal tab
    primary: 2,
    kbExpr: $7m.and($_bb.Visible, EditorContextKeys.textInputFocus),
    weight: weight2
  }, {
    // accept on enter has special rules
    primary: 3,
    kbExpr: $7m.and($_bb.Visible, EditorContextKeys.textInputFocus, $_bb.AcceptSuggestionsOnEnter, $_bb.MakesTextEdit),
    weight: weight2
  }],
  menuOpts: [{
    menuId: $acb,
    title: localize(1502, null),
    group: "left",
    order: 1,
    when: $_bb.HasInsertAndReplaceRange.toNegated()
  }, {
    menuId: $acb,
    title: localize(1503, null),
    group: "left",
    order: 1,
    when: $7m.and($_bb.HasInsertAndReplaceRange, $_bb.InsertMode.isEqualTo("insert"))
  }, {
    menuId: $acb,
    title: localize(1504, null),
    group: "left",
    order: 1,
    when: $7m.and($_bb.HasInsertAndReplaceRange, $_bb.InsertMode.isEqualTo("replace"))
  }]
}));
$45(new SuggestCommand({
  id: "acceptAlternativeSelectedSuggestion",
  precondition: $7m.and($_bb.Visible, EditorContextKeys.textInputFocus, $_bb.HasFocusedSuggestion),
  kbOpts: {
    weight: weight2,
    kbExpr: EditorContextKeys.textInputFocus,
    primary: 1024 | 3,
    secondary: [
      1024 | 2
      /* KeyCode.Tab */
    ]
  },
  handler(x) {
    x.acceptSelectedSuggestion(false, true);
  },
  menuOpts: [{
    menuId: $acb,
    group: "left",
    order: 2,
    when: $7m.and($_bb.HasInsertAndReplaceRange, $_bb.InsertMode.isEqualTo("insert")),
    title: localize(1505, null)
  }, {
    menuId: $acb,
    group: "left",
    order: 2,
    when: $7m.and($_bb.HasInsertAndReplaceRange, $_bb.InsertMode.isEqualTo("replace")),
    title: localize(1506, null)
  }]
}));
$tn.registerCommandAlias("acceptSelectedSuggestionOnEnter", "acceptSelectedSuggestion");
$45(new SuggestCommand({
  id: "hideSuggestWidget",
  precondition: $_bb.Visible,
  handler: (x) => x.cancelSuggestWidget(),
  kbOpts: {
    weight: weight2,
    kbExpr: EditorContextKeys.textInputFocus,
    primary: 9,
    secondary: [
      1024 | 9
      /* KeyCode.Escape */
    ]
  }
}));
$45(new SuggestCommand({
  id: "selectNextSuggestion",
  precondition: $7m.and($_bb.Visible, $7m.or($_bb.MultipleSuggestions, $_bb.HasFocusedSuggestion.negate())),
  handler: (c) => c.selectNextSuggestion(),
  kbOpts: {
    weight: weight2,
    kbExpr: EditorContextKeys.textInputFocus,
    primary: 18,
    secondary: [
      2048 | 18
      /* KeyCode.DownArrow */
    ],
    mac: { primary: 18, secondary: [
      2048 | 18,
      256 | 44
      /* KeyCode.KeyN */
    ] }
  }
}));
$45(new SuggestCommand({
  id: "selectNextPageSuggestion",
  precondition: $7m.and($_bb.Visible, $7m.or($_bb.MultipleSuggestions, $_bb.HasFocusedSuggestion.negate())),
  handler: (c) => c.selectNextPageSuggestion(),
  kbOpts: {
    weight: weight2,
    kbExpr: EditorContextKeys.textInputFocus,
    primary: 12,
    secondary: [
      2048 | 12
      /* KeyCode.PageDown */
    ]
  }
}));
$45(new SuggestCommand({
  id: "selectLastSuggestion",
  precondition: $7m.and($_bb.Visible, $7m.or($_bb.MultipleSuggestions, $_bb.HasFocusedSuggestion.negate())),
  handler: (c) => c.selectLastSuggestion()
}));
$45(new SuggestCommand({
  id: "selectPrevSuggestion",
  precondition: $7m.and($_bb.Visible, $7m.or($_bb.MultipleSuggestions, $_bb.HasFocusedSuggestion.negate())),
  handler: (c) => c.selectPrevSuggestion(),
  kbOpts: {
    weight: weight2,
    kbExpr: EditorContextKeys.textInputFocus,
    primary: 16,
    secondary: [
      2048 | 16
      /* KeyCode.UpArrow */
    ],
    mac: { primary: 16, secondary: [
      2048 | 16,
      256 | 46
      /* KeyCode.KeyP */
    ] }
  }
}));
$45(new SuggestCommand({
  id: "selectPrevPageSuggestion",
  precondition: $7m.and($_bb.Visible, $7m.or($_bb.MultipleSuggestions, $_bb.HasFocusedSuggestion.negate())),
  handler: (c) => c.selectPrevPageSuggestion(),
  kbOpts: {
    weight: weight2,
    kbExpr: EditorContextKeys.textInputFocus,
    primary: 11,
    secondary: [
      2048 | 11
      /* KeyCode.PageUp */
    ]
  }
}));
$45(new SuggestCommand({
  id: "selectFirstSuggestion",
  precondition: $7m.and($_bb.Visible, $7m.or($_bb.MultipleSuggestions, $_bb.HasFocusedSuggestion.negate())),
  handler: (c) => c.selectFirstSuggestion()
}));
$45(new SuggestCommand({
  id: "focusSuggestion",
  precondition: $7m.and($_bb.Visible, $_bb.HasFocusedSuggestion.negate()),
  handler: (x) => x.focusSuggestion(),
  kbOpts: {
    weight: weight2,
    kbExpr: EditorContextKeys.textInputFocus,
    primary: 2048 | 10,
    secondary: [
      2048 | 39
      /* KeyCode.KeyI */
    ],
    mac: { primary: 256 | 10, secondary: [
      2048 | 39
      /* KeyCode.KeyI */
    ] }
  }
}));
$45(new SuggestCommand({
  id: "focusAndAcceptSuggestion",
  precondition: $7m.and($_bb.Visible, $_bb.HasFocusedSuggestion.negate()),
  handler: (c) => {
    c.focusSuggestion();
    c.acceptSelectedSuggestion(true, false);
  }
}));
$45(new SuggestCommand({
  id: "toggleSuggestionDetails",
  precondition: $7m.and($_bb.Visible, $_bb.HasFocusedSuggestion),
  handler: (x) => x.toggleSuggestionDetails(),
  kbOpts: {
    weight: weight2,
    kbExpr: EditorContextKeys.textInputFocus,
    primary: 2048 | 10,
    secondary: [
      2048 | 39
      /* KeyCode.KeyI */
    ],
    mac: { primary: 256 | 10, secondary: [
      2048 | 39
      /* KeyCode.KeyI */
    ] }
  },
  menuOpts: [{
    menuId: $acb,
    group: "right",
    order: 1,
    when: $7m.and($_bb.DetailsVisible, $_bb.CanResolve),
    title: localize(1507, null)
  }, {
    menuId: $acb,
    group: "right",
    order: 1,
    when: $7m.and($_bb.DetailsVisible.toNegated(), $_bb.CanResolve),
    title: localize(1508, null)
  }]
}));
$45(new SuggestCommand({
  id: "toggleExplainMode",
  precondition: $_bb.Visible,
  handler: (x) => x.toggleExplainMode(),
  kbOpts: {
    weight: 100,
    primary: 2048 | 90
  }
}));
$45(new SuggestCommand({
  id: "toggleSuggestionFocus",
  precondition: $_bb.Visible,
  handler: (x) => x.toggleSuggestionFocus(),
  kbOpts: {
    weight: weight2,
    kbExpr: EditorContextKeys.textInputFocus,
    primary: 2048 | 512 | 10,
    mac: {
      primary: 256 | 512 | 10
      /* KeyCode.Space */
    }
  }
}));
$45(new SuggestCommand({
  id: "insertBestCompletion",
  precondition: $7m.and(EditorContextKeys.textInputFocus, $7m.equals("config.editor.tabCompletion", "on"), $adb.AtEnd, $_bb.Visible.toNegated(), $odb.OtherSuggestions.toNegated(), $Dcb.InSnippetMode.toNegated()),
  handler: (x, arg) => {
    x.triggerSuggestAndAcceptBest($Bg(arg) ? { fallback: "tab", ...arg } : { fallback: "tab" });
  },
  kbOpts: {
    weight: weight2,
    primary: 2
    /* KeyCode.Tab */
  }
}));
$45(new SuggestCommand({
  id: "insertNextSuggestion",
  precondition: $7m.and(EditorContextKeys.textInputFocus, $7m.equals("config.editor.tabCompletion", "on"), $odb.OtherSuggestions, $_bb.Visible.toNegated(), $Dcb.InSnippetMode.toNegated()),
  handler: (x) => x.acceptNextSuggestion(),
  kbOpts: {
    weight: weight2,
    kbExpr: EditorContextKeys.textInputFocus,
    primary: 2
    /* KeyCode.Tab */
  }
}));
$45(new SuggestCommand({
  id: "insertPrevSuggestion",
  precondition: $7m.and(EditorContextKeys.textInputFocus, $7m.equals("config.editor.tabCompletion", "on"), $odb.OtherSuggestions, $_bb.Visible.toNegated(), $Dcb.InSnippetMode.toNegated()),
  handler: (x) => x.acceptPrevSuggestion(),
  kbOpts: {
    weight: weight2,
    kbExpr: EditorContextKeys.textInputFocus,
    primary: 1024 | 2
    /* KeyCode.Tab */
  }
}));
$55(class extends $Z5 {
  constructor() {
    super({
      id: "editor.action.resetSuggestSize",
      label: localize2(1510, "Reset Suggest Widget Size"),
      precondition: void 0
    });
  }
  run(_accessor, editor) {
    $qdb.get(editor)?.resetWidgetSize();
  }
});

// out-build/vs/editor/contrib/inlineCompletions/browser/model/suggestWidgetAdapter.js
var $sdb = class extends $3c {
  get selectedItem() {
    return this.h;
  }
  constructor(m, n, r2) {
    super();
    this.m = m;
    this.n = n;
    this.r = r2;
    this.c = false;
    this.f = false;
    this.g = false;
    this.h = void 0;
    this.j = this.B(new $ze());
    this.onDidSelectedItemChange = this.j.event;
    this.B(m.onKeyDown((e) => {
      if (e.shiftKey && !this.f) {
        this.f = true;
        this.t(this.g);
      }
    }));
    this.B(m.onKeyUp((e) => {
      if (e.shiftKey && this.f) {
        this.f = false;
        this.t(this.g);
      }
    }));
    const suggestController = $qdb.get(this.m);
    if (suggestController) {
      this.B(suggestController.registerSelector({
        priority: 100,
        select: (model, pos, suggestItems) => {
          const textModel = this.m.getModel();
          if (!textModel) {
            return -1;
          }
          const i2 = this.n();
          const itemToPreselect = i2 ? $Rcb(i2, textModel) : void 0;
          if (!itemToPreselect) {
            return -1;
          }
          const position = $8C.lift(pos);
          const candidates = suggestItems.map((suggestItem, index) => {
            const suggestItemInfo = $tdb.fromSuggestion(suggestController, textModel, position, suggestItem, this.f);
            const suggestItemTextEdit = $Rcb(suggestItemInfo.toSingleTextEdit(), textModel);
            const valid2 = $Scb(itemToPreselect, suggestItemTextEdit);
            return { index, valid: valid2, prefixLength: suggestItemTextEdit.text.length, suggestItem };
          }).filter((item) => item && item.valid && item.prefixLength > 0);
          const result = $9(candidates, $9b((s) => s.prefixLength, $$b));
          return result ? result.index : -1;
        }
      }));
      let isBoundToSuggestWidget = false;
      const bindToSuggestWidget = () => {
        if (isBoundToSuggestWidget) {
          return;
        }
        isBoundToSuggestWidget = true;
        this.B(suggestController.widget.value.onDidShow(() => {
          this.c = true;
          this.t(true);
        }));
        this.B(suggestController.widget.value.onDidHide(() => {
          this.c = false;
          this.t(false);
        }));
        this.B(suggestController.widget.value.onDidFocus(() => {
          this.c = true;
          this.t(true);
        }));
      };
      this.B(Event2.once(suggestController.model.onDidTrigger)((e) => {
        bindToSuggestWidget();
      }));
      this.B(suggestController.onWillInsertSuggestItem((e) => {
        const position = this.m.getPosition();
        const model = this.m.getModel();
        if (!position || !model) {
          return void 0;
        }
        const suggestItemInfo = $tdb.fromSuggestion(suggestController, model, position, e.item, this.f);
        this.r(suggestItemInfo);
      }));
    }
    this.t(this.g);
  }
  t(newActive) {
    const newInlineCompletion = this.u();
    if (this.g !== newActive || !suggestItemInfoEquals(this.h, newInlineCompletion)) {
      this.g = newActive;
      this.h = newInlineCompletion;
      this.j.fire();
    }
  }
  u() {
    const suggestController = $qdb.get(this.m);
    if (!suggestController || !this.c) {
      return void 0;
    }
    const focusedItem = suggestController.widget.value.getFocusedItem();
    const position = this.m.getPosition();
    const model = this.m.getModel();
    if (!focusedItem || !position || !model) {
      return void 0;
    }
    return $tdb.fromSuggestion(suggestController, model, position, focusedItem.item, this.f);
  }
  stopForceRenderingAbove() {
    const suggestController = $qdb.get(this.m);
    suggestController?.stopForceRenderingAbove();
  }
  forceRenderingAbove() {
    const suggestController = $qdb.get(this.m);
    suggestController?.forceRenderingAbove();
  }
};
var $tdb = class _$tdb {
  static fromSuggestion(suggestController, model, position, item, toggleMode) {
    let { insertText } = item.completion;
    let isSnippetText = false;
    if (item.completion.insertTextRules & 4) {
      const snippet = new $0_().parse(insertText);
      if (snippet.children.length < 100) {
        $Ccb.adjustWhitespace(model, position, true, snippet);
      }
      insertText = snippet.toString();
      isSnippetText = true;
    }
    const info = suggestController.getOverwriteInfo(item, toggleMode);
    return new _$tdb($9C.fromPositions(position.delta(0, -info.overwriteBefore), position.delta(0, Math.max(info.overwriteAfter, 0))), insertText, item.completion.kind, isSnippetText);
  }
  constructor(range, insertText, completionItemKind, isSnippetText) {
    this.range = range;
    this.insertText = insertText;
    this.completionItemKind = completionItemKind;
    this.isSnippetText = isSnippetText;
  }
  equals(other) {
    return this.range.equalsRange(other.range) && this.insertText === other.insertText && this.completionItemKind === other.completionItemKind && this.isSnippetText === other.isSnippetText;
  }
  toSelectedSuggestionInfo() {
    return new $QE(this.range, this.insertText, this.completionItemKind, this.isSnippetText);
  }
  toSingleTextEdit() {
    return new $jD(this.range, this.insertText);
  }
};
function suggestItemInfoEquals(a, b) {
  if (a === b) {
    return true;
  }
  if (!a || !b) {
    return false;
  }
  return a.equals(b);
}
var $udb = class extends $3c {
  constructor(f, g, h3) {
    super();
    this.f = f;
    this.g = g;
    this.h = h3;
    this.c = this.B(new $sdb(this.f.editor, () => {
      this.f.forceUpdate();
      return this.h();
    }, (item) => this.f.forceUpdate((_tx) => {
      this.g(item);
    })));
    this.selectedItem = $Dd(this, (cb) => this.c.onDidSelectedItemChange(() => {
      this.f.forceUpdate((_tx) => cb(void 0));
    }), () => this.c.selectedItem);
  }
  stopForceRenderingAbove() {
    this.c.stopForceRenderingAbove();
  }
  forceRenderingAbove() {
    this.c.forceRenderingAbove();
  }
};

// out-build/vs/base/browser/domObservable.js
function $81(css) {
  const store = new $2c();
  const w = store.add($UZ());
  store.add($td((reader) => {
    w.setStyle(css.read(reader));
  }));
  return store;
}

// out-build/vs/editor/contrib/inlineCompletions/browser/view/ghostText/ghostTextView.js
var $Ahb = class $Ahb2 extends $3c {
  constructor(c, f, g) {
    super();
    this.c = c;
    this.f = f;
    this.g = g;
    this.a = $he(this, false);
    this.b = $79(this.c);
    this.h = this.b.getOption(
      64
      /* EditorOption.inlineSuggest */
    ).map((v) => v.syntaxHighlightingEnabled);
    this.j = $2d(this, (reader) => {
      if (this.a.read(reader)) {
        return void 0;
      }
      const textModel = this.b.model.read(reader);
      if (textModel !== this.f.targetTextModel.read(reader)) {
        return void 0;
      }
      const ghostText = this.f.ghostText.read(reader);
      if (!ghostText) {
        return void 0;
      }
      const replacedRange = ghostText instanceof $Ocb ? ghostText.columnRange : void 0;
      const syntaxHighlightingEnabled = this.h.read(reader);
      const extraClassName = syntaxHighlightingEnabled ? " syntax-highlighted" : "";
      const { inlineTexts, additionalLines, hiddenRange } = computeGhostTextViewData(ghostText, textModel, "ghost-text" + extraClassName);
      const edit3 = new $cD(inlineTexts.map((t) => $dD.insert(t.column - 1, t.text)));
      const tokens = syntaxHighlightingEnabled ? textModel.tokenization.tokenizeLineWithEdit(ghostText.lineNumber, new $$F(edit3, additionalLines.map((l) => l.content))) : void 0;
      const newRanges = edit3.getNewTextRanges();
      const inlineTextsWithTokens = inlineTexts.map((t, idx) => ({ ...t, tokens: tokens?.mainLineTokens?.getTokensInRange(newRanges[idx]) }));
      const tokenizedAdditionalLines = additionalLines.map((l, idx) => ({
        content: tokens?.additionalLines?.[idx] ?? $xE.createEmpty(l.content, this.g.languageIdCodec),
        decorations: l.decorations
      }));
      return {
        replacedRange,
        inlineTexts: inlineTextsWithTokens,
        additionalLines: tokenizedAdditionalLines,
        hiddenRange,
        lineNumber: ghostText.lineNumber,
        additionalReservedLineCount: this.f.minReservedLineCount.read(reader),
        targetTextModel: textModel,
        syntaxHighlightingEnabled
      };
    });
    this.m = $2d(this, (reader) => {
      const uiState = this.j.read(reader);
      if (!uiState) {
        return [];
      }
      const decorations = [];
      const extraClassName = uiState.syntaxHighlightingEnabled ? " syntax-highlighted" : "";
      if (uiState.replacedRange) {
        decorations.push({
          range: uiState.replacedRange.toRange(uiState.lineNumber),
          options: { inlineClassName: "inline-completion-text-to-replace" + extraClassName, description: "GhostTextReplacement" }
        });
      }
      if (uiState.hiddenRange) {
        decorations.push({
          range: uiState.hiddenRange.toRange(uiState.lineNumber),
          options: { inlineClassName: "ghost-text-hidden", description: "ghost-text-hidden" }
        });
      }
      for (const p of uiState.inlineTexts) {
        decorations.push({
          range: $9C.fromPositions(new $8C(uiState.lineNumber, p.column)),
          options: {
            description: "ghost-text-decoration",
            after: {
              content: p.text,
              tokens: p.tokens,
              inlineClassName: p.preview ? "ghost-text-decoration-preview" : "ghost-text-decoration" + extraClassName,
              cursorStops: InjectedTextCursorStops.Left
            },
            showIfCollapsed: true
          }
        });
      }
      return decorations;
    });
    this.n = this.B(new $Bhb(this.c, $2d((reader) => {
      const uiState = this.j.read(reader);
      return uiState ? {
        lineNumber: uiState.lineNumber,
        additionalLines: uiState.additionalLines,
        minReservedLineCount: uiState.additionalReservedLineCount,
        targetTextModel: uiState.targetTextModel
      } : void 0;
    })));
    this.B($1c(() => {
      this.a.set(true, void 0);
    }));
    this.B(this.b.setDecorations(this.m));
  }
  ownsViewZone(viewZoneId) {
    return this.n.viewZoneId === viewZoneId;
  }
};
$Ahb = __decorate([
  __param(2, $1E)
], $Ahb);
function computeGhostTextViewData(ghostText, textModel, ghostTextClassName) {
  const inlineTexts = [];
  const additionalLines = [];
  function addToAdditionalLines(lines, className) {
    if (additionalLines.length > 0) {
      const lastLine = additionalLines[additionalLines.length - 1];
      if (className) {
        lastLine.decorations.push(new $m7(
          lastLine.content.length + 1,
          lastLine.content.length + 1 + lines[0].length,
          className,
          0
          /* InlineDecorationType.Regular */
        ));
      }
      lastLine.content += lines[0];
      lines = lines.slice(1);
    }
    for (const line of lines) {
      additionalLines.push({
        content: line,
        decorations: className ? [new $m7(
          1,
          line.length + 1,
          className,
          0
          /* InlineDecorationType.Regular */
        )] : []
      });
    }
  }
  const textBufferLine = textModel.getLineContent(ghostText.lineNumber);
  let hiddenTextStartColumn = void 0;
  let lastIdx = 0;
  for (const part of ghostText.parts) {
    let lines = part.lines;
    if (hiddenTextStartColumn === void 0) {
      inlineTexts.push({ column: part.column, text: lines[0], preview: part.preview });
      lines = lines.slice(1);
    } else {
      addToAdditionalLines([textBufferLine.substring(lastIdx, part.column - 1)], void 0);
    }
    if (lines.length > 0) {
      addToAdditionalLines(lines, ghostTextClassName);
      if (hiddenTextStartColumn === void 0 && part.column <= textBufferLine.length) {
        hiddenTextStartColumn = part.column;
      }
    }
    lastIdx = part.column - 1;
  }
  if (hiddenTextStartColumn !== void 0) {
    addToAdditionalLines([textBufferLine.substring(lastIdx)], void 0);
  }
  const hiddenRange = hiddenTextStartColumn !== void 0 ? new $Fcb(hiddenTextStartColumn, textBufferLine.length + 1) : void 0;
  return {
    inlineTexts,
    additionalLines,
    hiddenRange
  };
}
var $Bhb = class extends $3c {
  get viewZoneId() {
    return this.a;
  }
  constructor(c, f) {
    super();
    this.c = c;
    this.f = f;
    this.a = void 0;
    this.b = $Gd("editorOptionChanged", Event2.filter(this.c.onDidChangeConfiguration, (e) => e.hasChanged(
      33
      /* EditorOption.disableMonospaceOptimizations */
    ) || e.hasChanged(
      122
      /* EditorOption.stopRenderingLineAfter */
    ) || e.hasChanged(
      104
      /* EditorOption.renderWhitespace */
    ) || e.hasChanged(
      99
      /* EditorOption.renderControlCharacters */
    ) || e.hasChanged(
      53
      /* EditorOption.fontLigatures */
    ) || e.hasChanged(
      52
      /* EditorOption.fontInfo */
    ) || e.hasChanged(
      68
      /* EditorOption.lineHeight */
    )));
    this.B($td((reader) => {
      const lines = this.f.read(reader);
      this.b.read(reader);
      if (lines) {
        this.h(lines.lineNumber, lines.additionalLines, lines.minReservedLineCount);
      } else {
        this.g();
      }
    }));
  }
  dispose() {
    super.dispose();
    this.g();
  }
  g() {
    this.c.changeViewZones((changeAccessor) => {
      if (this.a) {
        changeAccessor.removeZone(this.a);
        this.a = void 0;
      }
    });
  }
  h(lineNumber, additionalLines, minReservedLineCount) {
    const textModel = this.c.getModel();
    if (!textModel) {
      return;
    }
    const { tabSize } = textModel.getOptions();
    this.c.changeViewZones((changeAccessor) => {
      if (this.a) {
        changeAccessor.removeZone(this.a);
        this.a = void 0;
      }
      const heightInLines = Math.max(additionalLines.length, minReservedLineCount);
      if (heightInLines > 0) {
        const domNode = document.createElement("div");
        renderLines(domNode, tabSize, additionalLines, this.c.getOptions());
        this.a = changeAccessor.addZone({
          afterLineNumber: lineNumber,
          heightInLines,
          domNode,
          afterColumnAffinity: 1
          /* PositionAffinity.Right */
        });
      }
    });
  }
};
function renderLines(domNode, tabSize, lines, opts) {
  const disableMonospaceOptimizations = opts.get(
    33
    /* EditorOption.disableMonospaceOptimizations */
  );
  const stopRenderingLineAfter = opts.get(
    122
    /* EditorOption.stopRenderingLineAfter */
  );
  const renderWhitespace = "none";
  const renderControlCharacters = opts.get(
    99
    /* EditorOption.renderControlCharacters */
  );
  const fontLigatures = opts.get(
    53
    /* EditorOption.fontLigatures */
  );
  const fontInfo = opts.get(
    52
    /* EditorOption.fontInfo */
  );
  const lineHeight = opts.get(
    68
    /* EditorOption.lineHeight */
  );
  const sb = new $cE(1e4);
  sb.appendString('<div class="suggest-preview-text">');
  for (let i2 = 0, len = lines.length; i2 < len; i2++) {
    const lineData = lines[i2];
    const lineTokens = lineData.content;
    sb.appendString('<div class="view-line');
    sb.appendString('" style="top:');
    sb.appendString(String(i2 * lineHeight));
    sb.appendString('px;width:1000000px;">');
    const line = lineTokens.getLineContent();
    const isBasicASCII = $dg(line);
    const containsRTL = $cg(line);
    $u7(new $q7(fontInfo.isMonospace && !disableMonospaceOptimizations, fontInfo.canUseHalfwidthRightwardsArrow, line, false, isBasicASCII, containsRTL, 0, lineTokens, lineData.decorations, tabSize, 0, fontInfo.spaceWidth, fontInfo.middotWidth, fontInfo.wsmiddotWidth, stopRenderingLineAfter, renderWhitespace, renderControlCharacters, fontLigatures !== EditorFontLigatures.OFF, null), sb);
    sb.appendString("</div>");
  }
  sb.appendString("</div>");
  $24(domNode, fontInfo);
  const html3 = sb.build();
  const trustedhtml = $Chb ? $Chb.createHTML(html3) : html3;
  domNode.innerHTML = trustedhtml;
}
var $Chb = $W1("editorGhostText", { createHTML: (value) => value });

// out-build/vs/editor/contrib/inlineCompletions/browser/view/inlineEdits/utils.js
function $Dhb(editor, range, reader) {
  editor.layoutInfo.read(reader);
  editor.value.read(reader);
  const model = editor.model.read(reader);
  if (!model) {
    return 0;
  }
  let maxContentWidth = 0;
  editor.scrollTop.read(reader);
  for (let i2 = range.startLineNumber; i2 < range.endLineNumberExclusive; i2++) {
    const column = model.getLineMaxColumn(i2);
    const lineContentWidth = editor.editor.getOffsetForColumn(i2, column);
    maxContentWidth = Math.max(maxContentWidth, lineContentWidth);
  }
  const lines = range.mapToLineArray((l) => model.getLineContent(l));
  if (maxContentWidth < 5 && lines.some((l) => l.length > 0) && model.uri.scheme !== "file") {
    console.error("unexpected width");
  }
  return maxContentWidth;
}
function $Ehb(editor, pos, reader) {
  editor.layoutInfo.read(reader);
  editor.value.read(reader);
  const model = editor.model.read(reader);
  if (!model) {
    return 0;
  }
  editor.scrollTop.read(reader);
  const lineContentWidth = editor.editor.getOffsetForColumn(pos.lineNumber, pos.column);
  return lineContentWidth;
}
var $Fhb = class extends $T$ {
  constructor() {
    super(...arguments);
    this.b = this.B(this.Z.onDidChangeContext(() => {
      this.C();
    }));
  }
  C() {
    const kb = this.X.lookupKeybinding(this._action.id, this.Z, true);
    if (!kb) {
      return super.C();
    }
    if (this.L) {
      const div = h("div.keybinding").root;
      const keybindingLabel = this.B(new $32(div, OS, { disableTitle: true, ...$22 }));
      keybindingLabel.set(kb);
      this.L.textContent = this._action.label;
      this.L.appendChild(div);
      this.L.classList.add("inlineSuggestionStatusBarItemLabel");
    }
  }
  G() {
  }
};
var $Ghb = class _$Ghb {
  constructor(x, y) {
    this.x = x;
    this.y = y;
  }
  add(other) {
    return new _$Ghb(this.x + other.x, this.y + other.y);
  }
  deltaX(delta) {
    return new _$Ghb(this.x + delta, this.y);
  }
  deltaY(delta) {
    return new _$Ghb(this.x, this.y + delta);
  }
};
var $Hhb = class _$Hhb {
  static {
    this.a = 0;
  }
  constructor(scheme) {
    this.scheme = scheme;
  }
  getUniqueUri() {
    return URI.from({ scheme: this.scheme, path: (/* @__PURE__ */ new Date()).toString() + String(_$Hhb.a++) });
  }
};
function $Ihb(rangeMapping, edit3) {
  const updatedMappings = [];
  for (const m of rangeMapping) {
    const updatedRange = edit3.mapRange(m.modifiedRange);
    updatedMappings.push(new $rD(m.originalRange, updatedRange));
  }
  return updatedMappings;
}
function $Jhb(...classes2) {
  return classes2.filter((c) => typeof c === "string").join(" ");
}
function offsetRangeToRange(columnOffsetRange, startPos) {
  return new $9C(startPos.lineNumber, startPos.column + columnOffsetRange.start, startPos.lineNumber, startPos.column + columnOffsetRange.endExclusive);
}
function $Khb(text2, range) {
  const newLines = $Mf(text2);
  const edits = [];
  const minIndent = $$(range.mapToLineArray((l) => $Rf(newLines[l - 1])), $$b);
  range.forEach((lineNumber) => {
    edits.push(new $jD(offsetRangeToRange(new $0C(0, minIndent), new $8C(lineNumber, 1)), ""));
  });
  return new $iD(edits);
}
var $Lhb = class {
  constructor() {
    this.a = "";
  }
  moveTo(point) {
    this.a += `M ${point.x} ${point.y} `;
    return this;
  }
  lineTo(point) {
    this.a += `L ${point.x} ${point.y} `;
    return this;
  }
  curveTo(cp, to) {
    this.a += `Q ${cp.x} ${cp.y} ${to.x} ${to.y} `;
    return this;
  }
  curveTo2(cp1, cp2, to) {
    this.a += `C ${cp1.x} ${cp1.y} ${cp2.x} ${cp2.y} ${to.x} ${to.y} `;
    return this;
  }
  build() {
    return this.a;
  }
};

// out-build/vs/editor/contrib/inlineCompletions/browser/view/inlineEdits/inlineDiffView.js
var $Mhb = class extends $3c {
  static supportsInlineDiffRendering(mapping2) {
    return allowsTrueInlineDiffRendering(mapping2);
  }
  constructor(a, b, f) {
    super();
    this.a = a;
    this.b = b;
    this.f = f;
    this.g = $2d(this, (reader) => {
      const diff3 = this.b.read(reader);
      if (!diff3) {
        return void 0;
      }
      const modified = diff3.modifiedText;
      const showInline = diff3.mode === "mixedLines";
      const showEmptyDecorations = true;
      const originalDecorations = [];
      const modifiedDecorations = [];
      const diffLineAddDecorationBackground = $WI.register({
        className: "inlineCompletions-line-insert",
        description: "line-insert",
        isWholeLine: true,
        marginClassName: "gutter-insert"
      });
      const diffLineDeleteDecorationBackground = $WI.register({
        className: "inlineCompletions-line-delete",
        description: "line-delete",
        isWholeLine: true,
        marginClassName: "gutter-delete"
      });
      const diffWholeLineDeleteDecoration = $WI.register({
        className: "inlineCompletions-char-delete",
        description: "char-delete",
        isWholeLine: false
      });
      const diffWholeLineAddDecoration = $WI.register({
        className: "inlineCompletions-char-insert",
        description: "char-insert",
        isWholeLine: true
      });
      const diffAddDecoration = $WI.register({
        className: "inlineCompletions-char-insert",
        description: "char-insert",
        shouldFillLineOnLineBreak: true
      });
      const diffAddDecorationEmpty = $WI.register({
        className: "inlineCompletions-char-insert diff-range-empty",
        description: "char-insert diff-range-empty"
      });
      for (const m of diff3.diff) {
        const showFullLineDecorations = true;
        if (showFullLineDecorations) {
          if (!m.original.isEmpty) {
            originalDecorations.push({
              range: m.original.toInclusiveRange(),
              options: diffLineDeleteDecorationBackground
            });
          }
          if (!m.modified.isEmpty) {
            modifiedDecorations.push({
              range: m.modified.toInclusiveRange(),
              options: diffLineAddDecorationBackground
            });
          }
        }
        if (m.modified.isEmpty || m.original.isEmpty) {
          if (!m.original.isEmpty) {
            originalDecorations.push({ range: m.original.toInclusiveRange(), options: diffWholeLineDeleteDecoration });
          }
          if (!m.modified.isEmpty) {
            modifiedDecorations.push({ range: m.modified.toInclusiveRange(), options: diffWholeLineAddDecoration });
          }
        } else {
          const useInlineDiff = showInline && allowsTrueInlineDiffRendering(m);
          for (const i2 of m.innerChanges || []) {
            if (m.original.contains(i2.originalRange.startLineNumber)) {
              originalDecorations.push({
                range: i2.originalRange,
                options: {
                  description: "char-delete",
                  shouldFillLineOnLineBreak: false,
                  className: $Jhb("inlineCompletions-char-delete", i2.originalRange.isEmpty() && showEmptyDecorations && !useInlineDiff && "diff-range-empty"),
                  inlineClassName: useInlineDiff ? "strike-through" : null,
                  zIndex: 1
                }
              });
            }
            if (m.modified.contains(i2.modifiedRange.startLineNumber)) {
              modifiedDecorations.push({
                range: i2.modifiedRange,
                options: i2.modifiedRange.isEmpty() && showEmptyDecorations && !useInlineDiff ? diffAddDecorationEmpty : diffAddDecoration
              });
            }
            if (useInlineDiff) {
              const insertedText = modified.getValueOfRange(i2.modifiedRange);
              originalDecorations.push({
                range: $9C.fromPositions(i2.originalRange.getEndPosition()),
                options: {
                  description: "inserted-text",
                  before: {
                    content: insertedText,
                    inlineClassName: "inlineCompletions-char-insert"
                  },
                  zIndex: 2,
                  showIfCollapsed: true
                }
              });
            }
          }
        }
      }
      return { originalDecorations, modifiedDecorations };
    });
    this.B($79(this.a).setDecorations(this.g.map((d) => d?.originalDecorations ?? [])));
    const modifiedCodeEditor = this.b.map((s) => s?.modifiedCodeEditor);
    this.B($xd((reader, store) => {
      const e = modifiedCodeEditor.read(reader);
      if (e) {
        store.add($79(e).setDecorations(this.g.map((d) => d?.modifiedDecorations ?? [])));
      }
    }));
    const editor = $79(this.a);
    const tokenizationFinished = modelTokenizationFinished(f);
    const originalViewZones = $2d(this, (reader) => {
      const originalModel = editor.model.read(reader);
      if (!originalModel) {
        return [];
      }
      const origViewZones = [];
      const renderOptions = $90.fromEditor(this.a);
      const modLineHeight = editor.getOption(
        68
        /* EditorOption.lineHeight */
      ).read(reader);
      const s = this.b.read(reader);
      if (!s) {
        return origViewZones;
      }
      for (const diff3 of s.diff) {
        if (s.mode !== "interleavedLines") {
          continue;
        }
        tokenizationFinished.read(reader);
        const source = new $80(diff3.modified.mapToLineArray((l) => this.f.tokenization.getLineTokens(l)));
        const decorations = [];
        for (const i2 of diff3.innerChanges || []) {
          decorations.push(new $I5(
            i2.modifiedRange.delta(-(diff3.original.startLineNumber - 1)),
            $W0.className,
            0
            /* InlineDecorationType.Regular */
          ));
        }
        const deletedCodeDomNode = document.createElement("div");
        deletedCodeDomNode.classList.add("view-lines", "line-insert", "monaco-mouse-cursor-text");
        const result = $70(source, renderOptions, decorations, deletedCodeDomNode);
        origViewZones.push({
          afterLineNumber: diff3.original.endLineNumberExclusive - 1,
          domNode: deletedCodeDomNode,
          heightInPx: result.heightInLines * modLineHeight,
          minWidthInPx: result.minWidthInPx,
          showInHiddenAreas: true,
          suppressMouseDown: true
        });
      }
      return origViewZones;
    });
    this.B($29(this.a, originalViewZones));
  }
};
function allowsTrueInlineDiffRendering(mapping2) {
  if (!mapping2.innerChanges) {
    return false;
  }
  return mapping2.innerChanges.every((c) => $_0(c.modifiedRange) && $_0(c.originalRange));
}
var i = 0;
function modelTokenizationFinished(model) {
  return $Dd(model.onDidChangeTokens, () => i++);
}

// out-build/vs/editor/contrib/inlineCompletions/browser/view/inlineEdits/inlineEditsIndicatorView.js
var $Nhb = $5n("inlineEdit.indicator.foreground", $Sq, "");
var $Ohb = $5n("inlineEdit.indicator.background", $Uq, "");
var $Phb = $5n("inlineEdit.indicator.border", $Tq, "");
var $Qhb = class extends $3c {
  constructor(b, c, f) {
    super();
    this.b = b;
    this.c = c;
    this.f = f;
    this.a = h("div.inline-edits-view-indicator", {
      style: {
        position: "absolute",
        overflow: "visible",
        cursor: "pointer"
      }
    }, [
      h("div.icon", {}, [
        $C1($6l.arrowLeft)
      ]),
      h("div.label", {}, [
        " inline edit"
      ])
    ]);
    this.B($_i(this.a.root, "click", () => {
      this.f.get()?.jump();
    }));
    this.B(this.b.createOverlayWidget({
      domNode: this.a.root,
      position: $Bd(null),
      allowEditorOverflow: false,
      minContentWidthInPx: $Bd(0)
    }));
    this.B($td((reader) => {
      const state = this.c.read(reader);
      if (!state) {
        this.a.root.style.visibility = "hidden";
        return;
      }
      this.a.root.style.visibility = "";
      const i2 = this.b.layoutInfo.read(reader);
      const range = new $0C(0, i2.height - 30);
      const topEdit = state.editTopLeft;
      this.a.root.classList.toggle("top", topEdit.y < range.start);
      this.a.root.classList.toggle("bottom", topEdit.y > range.endExclusive);
      const showAnyway = state.showAlways;
      this.a.root.classList.toggle("visible", showAnyway);
      this.a.root.classList.toggle("contained", range.contains(topEdit.y));
      this.a.root.style.top = `${range.clip(topEdit.y)}px`;
      this.a.root.style.right = `${i2.minimap.minimapWidth + i2.verticalScrollbarWidth}px`;
    }));
  }
};

// out-build/vs/editor/contrib/inlineCompletions/browser/view/inlineEdits/inlineEditsView.js
var $Rhb = $5n("inlineEdit.originalBackground", $0n($Dp, 0.4), "", true);
var $Shb = $5n("inlineEdit.modifiedBackground", $0n($Cp, 0.4), "", true);
var $Thb = $5n("inlineEdit.originalChangedLineBackground", $Vn.transparent, "", true);
var $Uhb = $5n("inlineEdit.originalChangedTextBackground", $Dp, "", true);
var $Vhb = $5n("inlineEdit.modifiedChangedLineBackground", $Vn.transparent, "", true);
var $Whb = $5n("inlineEdit.modifiedChangedTextBackground", $Cp, "", true);
var $Xhb = $5n("inlineEdit.border", {
  light: $8n($MG, 0.15),
  dark: $9n($MG, 0.5),
  hcDark: $MG,
  hcLight: $MG
}, "");
var $Yhb = class $Yhb2 extends $3c {
  constructor(n, r2, t, u, w) {
    super();
    this.n = n;
    this.r = r2;
    this.t = t;
    this.u = u;
    this.w = w;
    this.a = $79(this.n);
    this.b = h("div.inline-edits-view", {
      style: {
        position: "absolute",
        overflow: "visible",
        top: "0px",
        left: "0px"
      }
    }, [
      $Ck("svg@svg", { transform: "translate(-0.5 -0.5)", style: { overflow: "visible", pointerEvents: "none", position: "absolute" } }, []),
      h("div.editorContainer@editorContainer", { style: { position: "absolute" } }, [
        h("div.preview@editor", { style: {} }),
        h("div.toolbar@toolbar", { style: {} })
      ]),
      $Ck("svg@svg2", { transform: "translate(-0.5 -0.5)", style: { overflow: "visible", pointerEvents: "none", position: "absolute" } }, [])
    ]);
    this.f = $79(this.n).getOption(
      64
      /* EditorOption.inlineSuggest */
    ).map((s) => s.edits.experimental.useMixedLinesDiff);
    this.j = $79(this.n).getOption(
      64
      /* EditorOption.inlineSuggest */
    ).map((s) => s.edits.experimental.useInterleavedLinesDiff);
    this.z = $2d(this, (reader) => {
      const edit3 = this.r.read(reader);
      if (!edit3) {
        return void 0;
      }
      this.t.get()?.handleInlineCompletionShown(edit3.inlineCompletion);
      let mappings = $rD.fromEdit(edit3.edit);
      let newText = edit3.edit.apply(edit3.originalText);
      let diff3 = $sD(mappings, edit3.originalText, new $nD(newText));
      let state;
      if (edit3.isCollapsed) {
        state = "collapsed";
      } else if (diff3.every((m) => $Mhb.supportsInlineDiffRendering(m)) && (this.f.read(reader) === "whenPossible" || edit3.userJumpedToIt && this.f.read(reader) === "afterJumpWhenPossible")) {
        state = "mixedLines";
      } else if (this.j.read(reader) === "always" || edit3.userJumpedToIt && this.j.read(reader) === "afterJump") {
        state = "interleavedLines";
      } else {
        state = "sideBySide";
      }
      if (state === "sideBySide") {
        const indentationAdjustmentEdit = $Khb(newText, edit3.modifiedLineRange);
        newText = indentationAdjustmentEdit.applyToString(newText);
        mappings = $Ihb(mappings, indentationAdjustmentEdit);
        diff3 = $sD(mappings, edit3.originalText, new $nD(newText));
      }
      const originalDisplayRange = edit3.originalText.lineRange.intersect(edit3.originalLineRange.join($_C.ofLength(edit3.originalLineRange.startLineNumber, edit3.lineEdit.newLines.length)));
      return {
        state,
        diff: diff3,
        edit: edit3,
        newText,
        newTextLineCount: edit3.modifiedLineRange.length,
        originalDisplayRange
      };
    });
    this.C = this.B(this.u.createInstance($zdb, this.b.toolbar, $bJ.InlineEditsActions, {
      menuOptions: { renderShortTitle: true },
      toolbarOptions: {
        primaryGroup: (g) => g.startsWith("primary")
      },
      actionViewItemProvider: (action, options3) => {
        if (action instanceof $fJ) {
          return this.u.createInstance($Fhb, action, void 0);
        }
        if (action.class === void 0) {
          return this.u.createInstance($U1, {}, action, { icon: false });
        }
        return void 0;
      },
      telemetrySource: "inlineEditsToolbar"
    }));
    this.D = $4d({ owner: this, equalsFn: $rd }, (reader) => {
      return this.z.read(reader)?.edit.commands ?? [];
    });
    this.F = this.B($td((reader) => {
      const extraCommands = this.D.read(reader);
      const primaryExtraActions = [];
      const secondaryExtraActions = [];
      for (const c of extraCommands) {
        const action = {
          class: void 0,
          id: c.id,
          enabled: true,
          tooltip: c.tooltip || "",
          label: c.title,
          run: (event) => {
            return this.w.executeCommand(c.id, ...c.arguments ?? []);
          }
        };
        if (c.title.toLowerCase().indexOf("feedback") !== -1) {
          primaryExtraActions.push(action);
        } else {
          secondaryExtraActions.push(action);
        }
      }
      this.C.setAdditionalPrimaryActions(primaryExtraActions);
      this.C.setAdditionalSecondaryActions(secondaryExtraActions);
    }));
    this.G = this.B(this.u.createInstance($QI, "", this.n.getModel().getLanguageId(), { ...$QI.DEFAULT_CREATION_OPTIONS, bracketPairColorizationOptions: { enabled: true, independentColorPoolPerBracketType: false } }, null));
    this.H = this.B(this.u.createInstance($bdb, this.b.editor, {
      glyphMargin: false,
      lineNumbers: "off",
      minimap: { enabled: false },
      guides: {
        indentation: false,
        bracketPairs: false,
        bracketPairsHorizontal: false,
        highlightActiveIndentation: false
      },
      folding: false,
      selectOnLineNumbers: false,
      selectionHighlight: false,
      columnSelection: false,
      overviewRulerBorder: false,
      overviewRulerLanes: 0,
      lineDecorationsWidth: 0,
      lineNumbersMinChars: 0,
      bracketPairColorization: { enabled: true, independentColorPoolPerBracketType: false },
      scrollBeyondLastLine: false,
      scrollbar: {
        vertical: "hidden",
        horizontal: "hidden",
        handleMouseWheel: false
      },
      readOnly: true,
      wordWrap: "off"
    }, { contributions: [] }, this.n));
    this.I = $79(this.H);
    this.J = $2d(this, (reader) => this.z.read(reader)?.state === "sideBySide" ? "block" : "none");
    this.L = $2d((reader) => {
      this.b.root.style.display = this.J.read(reader);
    });
    this.M = $2d((reader) => {
      this.L.read(reader);
      const uiState = this.z.read(reader);
      if (!uiState) {
        return;
      }
      this.G.setLanguage(this.n.getModel().getLanguageId());
      this.G.setValue(uiState.newText);
      const range = uiState.edit.originalLineRange;
      const hiddenAreas = [];
      if (range.startLineNumber > 1) {
        hiddenAreas.push(new $9C(1, 1, range.startLineNumber - 1, 1));
      }
      if (range.startLineNumber + uiState.newTextLineCount < this.G.getLineCount() + 1) {
        hiddenAreas.push(new $9C(range.startLineNumber + uiState.newTextLineCount, 1, this.G.getLineCount() + 1, 1));
      }
      this.H.setHiddenAreas(hiddenAreas, void 0, true);
    }).recomputeInitiallyAndOnChange(this.q);
    this.N = $2d(this, (reader) => {
      const edit3 = this.r.read(reader);
      if (!edit3) {
        return 0;
      }
      this.M.read(reader);
      return $Dhb(this.I, edit3.modifiedLineRange, reader) + 10;
    });
    this.O = $2d(this, (reader) => {
      const cursorPos = this.a.cursorPosition.read(reader);
      const edit3 = this.r.read(reader);
      if (!edit3 || !cursorPos) {
        return void 0;
      }
      return edit3.modifiedLineRange.contains(cursorPos.lineNumber) ? cursorPos : void 0;
    });
    this.P = $2d(this, (reader) => {
      const inlineEdit = this.r.read(reader);
      if (!inlineEdit) {
        return null;
      }
      const state = this.z.read(reader);
      if (!state) {
        return null;
      }
      const range = inlineEdit.originalLineRange;
      const horizontalScrollOffset = this.a.scrollLeft.read(reader);
      const editorContentMaxWidthInRange = $Dhb(this.a, state.originalDisplayRange, reader);
      const editorLayout = this.a.layoutInfo.read(reader);
      const previewWidth = this.N.read(reader);
      const editorContentAreaWidth = editorLayout.width - editorLayout.contentLeft - editorLayout.minimap.minimapWidth - editorLayout.verticalScrollbarWidth;
      const cursorPos = this.O.read(reader);
      const maxPreviewEditorLeft = Math.max(editorContentAreaWidth * 0.65 + horizontalScrollOffset - 10, editorContentAreaWidth - previewWidth - 70 + horizontalScrollOffset - 10, cursorPos ? $Ehb(this.a, cursorPos, reader) + 50 : 0);
      const previewEditorLeftInTextArea = Math.min(editorContentMaxWidthInRange + 20, maxPreviewEditorLeft);
      const previewEditorLeft = editorLayout.contentLeft + previewEditorLeftInTextArea;
      const maxContentWidth = editorContentMaxWidthInRange + 20 + previewWidth + 70;
      const dist = maxPreviewEditorLeft - previewEditorLeftInTextArea;
      const left = Math.max(editorLayout.contentLeft, previewEditorLeft - horizontalScrollOffset);
      const selectionTop = this.n.getTopForLineNumber(range.startLineNumber) - this.a.scrollTop.read(reader);
      const selectionBottom = this.n.getTopForLineNumber(range.endLineNumberExclusive) - this.a.scrollTop.read(reader);
      const codeLeft = editorLayout.contentLeft;
      const code1 = new $Ghb(left, selectionTop);
      const codeStart1 = new $Ghb(codeLeft, selectionTop);
      const code2 = new $Ghb(left, selectionBottom);
      const codeStart2 = new $Ghb(codeLeft, selectionBottom);
      const codeHeight = selectionBottom - selectionTop;
      const codeEditDistRange = inlineEdit.modifiedLineRange.length === inlineEdit.originalLineRange.length ? new $0C(4, 61) : new $0C(60, 61);
      const clipped = dist === 0;
      const codeEditDist = codeEditDistRange.clip(dist);
      const editHeight = this.n.getOption(
        68
        /* EditorOption.lineHeight */
      ) * inlineEdit.modifiedLineRange.length;
      const edit1 = new $Ghb(left + codeEditDist, selectionTop);
      const edit22 = new $Ghb(left + codeEditDist, selectionTop + editHeight);
      return {
        code1,
        codeStart1,
        code2,
        codeStart2,
        codeHeight,
        edit1,
        edit2: edit22,
        editHeight,
        previewEditorLeft,
        maxContentWidth,
        shouldShowShadow: clipped
      };
    });
    this.Q = $2d(this, (reader) => {
      const e = this.z.read(reader);
      if (!e) {
        return void 0;
      }
      return {
        modifiedText: new $nD(e.newText),
        diff: e.diff,
        mode: e.state === "collapsed" ? "sideBySide" : e.state,
        modifiedCodeEditor: this.H
      };
    });
    this.R = this.B(new $Mhb(this.n, this.Q, this.G));
    this.S = this.B(new $Qhb(this.a, $2d((reader) => {
      const state = this.z.read(reader);
      const edit1 = this.P.read(reader)?.edit1;
      if (!edit1 || !state) {
        return void 0;
      }
      return { editTopLeft: edit1, showAlways: state.state !== "sideBySide" };
    }), this.t));
    this.B($S9(this.n.getDomNode(), this.b.root));
    this.B(this.a.createOverlayWidget({
      domNode: this.b.root,
      position: $Bd(null),
      allowEditorOverflow: false,
      minContentWidthInPx: $2d((reader) => {
        const x = this.P.read(reader)?.maxContentWidth;
        if (x === void 0) {
          return 0;
        }
        return x;
      })
    }));
    this.H.setModel(this.G);
    this.B($td((reader) => {
      const layoutInfo = this.P.read(reader);
      if (!layoutInfo) {
        this.b.svg.replaceChildren();
        return;
      }
      const topEdit = layoutInfo.edit1;
      const editHeight = layoutInfo.editHeight;
      const width2 = this.N.read(reader);
      const pathBuilder1 = new $Lhb();
      pathBuilder1.moveTo(layoutInfo.code2);
      pathBuilder1.lineTo(layoutInfo.codeStart2);
      pathBuilder1.lineTo(layoutInfo.codeStart1);
      pathBuilder1.lineTo(layoutInfo.code1);
      const pathBuilder2 = new $Lhb();
      pathBuilder2.moveTo(layoutInfo.code1);
      pathBuilder2.lineTo(layoutInfo.edit1);
      pathBuilder2.lineTo(layoutInfo.edit1.deltaX(width2));
      pathBuilder2.lineTo(layoutInfo.edit2.deltaX(width2));
      pathBuilder2.lineTo(layoutInfo.edit2);
      if (layoutInfo.edit2.y !== layoutInfo.code2.y) {
        pathBuilder2.curveTo2(layoutInfo.edit2.deltaX(-20), layoutInfo.code2.deltaX(20), layoutInfo.code2.deltaX(0));
      }
      pathBuilder2.lineTo(layoutInfo.code2);
      const pathBuilder4 = new $Lhb();
      pathBuilder4.moveTo(layoutInfo.code1);
      pathBuilder4.lineTo(layoutInfo.code1.deltaX(1e3));
      pathBuilder4.lineTo(layoutInfo.code2.deltaX(1e3));
      pathBuilder4.lineTo(layoutInfo.code2);
      const path1 = document.createElementNS("http://www.w3.org/2000/svg", "path");
      path1.setAttribute("d", pathBuilder1.build());
      path1.style.fill = "var(--vscode-inlineEdit-originalBackground, transparent)";
      path1.style.stroke = "var(--vscode-inlineEdit-border)";
      path1.style.strokeWidth = "1px";
      const path2 = document.createElementNS("http://www.w3.org/2000/svg", "path");
      path2.setAttribute("d", pathBuilder2.build());
      path2.style.fill = "var(--vscode-inlineEdit-modifiedBackground, transparent)";
      path2.style.stroke = "var(--vscode-inlineEdit-border)";
      path2.style.strokeWidth = "1px";
      const pathModifiedBackground = document.createElementNS("http://www.w3.org/2000/svg", "path");
      pathModifiedBackground.setAttribute("d", pathBuilder2.build());
      pathModifiedBackground.style.fill = "var(--vscode-editor-background, transparent)";
      pathModifiedBackground.style.strokeWidth = "1px";
      const elements = [];
      if (layoutInfo.shouldShowShadow) {
        const defs = document.createElementNS("http://www.w3.org/2000/svg", "defs");
        const linearGradient = document.createElementNS("http://www.w3.org/2000/svg", "linearGradient");
        linearGradient.setAttribute("id", "gradient");
        linearGradient.setAttribute("x1", "0%");
        linearGradient.setAttribute("x2", "100%");
        const stop1 = document.createElementNS("http://www.w3.org/2000/svg", "stop");
        stop1.setAttribute("offset", "0%");
        stop1.setAttribute("style", "stop-color:var(--vscode-inlineEdit-border);stop-opacity:0");
        const stop2 = document.createElementNS("http://www.w3.org/2000/svg", "stop");
        stop2.setAttribute("offset", "100%");
        stop2.setAttribute("style", "stop-color:var(--vscode-inlineEdit-border);stop-opacity:1");
        linearGradient.appendChild(stop1);
        linearGradient.appendChild(stop2);
        defs.appendChild(linearGradient);
        const width3 = 6;
        const rect = document.createElementNS("http://www.w3.org/2000/svg", "rect");
        rect.setAttribute("x", `${layoutInfo.code1.x - width3}`);
        rect.setAttribute("y", `${layoutInfo.code1.y}`);
        rect.setAttribute("width", `${width3}`);
        rect.setAttribute("height", `${layoutInfo.code2.y - layoutInfo.code1.y}`);
        rect.setAttribute("fill", "url(#gradient)");
        rect.style.strokeWidth = "0";
        rect.style.stroke = "transparent";
        elements.push(defs);
        elements.push(rect);
      } else {
        const pathBuilder3 = new $Lhb();
        pathBuilder3.moveTo(layoutInfo.code1);
        pathBuilder3.lineTo(layoutInfo.code2);
        const path3 = document.createElementNS("http://www.w3.org/2000/svg", "path");
        path3.setAttribute("d", pathBuilder3.build());
        path3.style.stroke = "var(--vscode-inlineEdit-border)";
        path3.style.strokeWidth = "1px";
        elements.push(path3);
      }
      const path4 = document.createElementNS("http://www.w3.org/2000/svg", "path");
      path4.setAttribute("d", pathBuilder4.build());
      path4.style.fill = "var(--vscode-editor-background, transparent)";
      this.b.svg.replaceChildren(path4, pathModifiedBackground);
      this.b.svg2.replaceChildren(path1, path2, ...elements);
      this.b.editorContainer.style.top = `${topEdit.y}px`;
      this.b.editorContainer.style.left = `${topEdit.x}px`;
      this.H.layout({ height: editHeight, width: width2 });
    }));
    const toolbarDropdownVisible = $Dd(this, this.C.onDidChangeDropdownVisibility, (e) => e ?? false);
    this.B($td((reader) => {
      this.b.root.classList.toggle("toolbarDropdownVisible", toolbarDropdownVisible.read(reader));
    }));
  }
};
$Yhb = __decorate([
  __param(3, $Pk),
  __param(4, $sn)
], $Yhb);

// out-build/vs/editor/contrib/inlineCompletions/browser/view/inlineEdits/inlineEditsViewAndDiffProducer.js
var $Zhb_1;
var $Zhb = class $Zhb2 extends $3c {
  static {
    $Zhb_1 = this;
  }
  static {
    this.hot = $P3($Zhb_1);
  }
  constructor(m, n, r2, s, t, u) {
    super();
    this.m = m;
    this.n = n;
    this.r = r2;
    this.s = s;
    this.t = t;
    this.u = u;
    this.a = new $Hhb("inline-edits");
    this.b = $7d(() => this.u.createModel("", null, this.a.getUniqueUri())).keepObserved(this.q);
    this.f = $7d(() => this.u.createModel("", null, this.a.getUniqueUri())).keepObserved(this.q);
    this.g = new $qf({ getCacheKey: JSON.stringify }, (arg) => {
      this.b.get().setValue(arg.original);
      this.f.get().setValue(arg.modified);
      const diffAlgo = this.t.createDiffProvider({ diffAlgorithm: "advanced" });
      return $oe.fromFn(async () => {
        const result = await diffAlgo.computeDiff(this.b.get(), this.f.get(), {
          computeMoves: false,
          ignoreTrimWhitespace: false,
          maxComputationTimeMs: 1e3
        }, CancellationToken.None);
        return result;
      });
    });
    this.h = $2d(this, (reader) => {
      const inlineEdit = this.n.read(reader);
      if (!inlineEdit) {
        return void 0;
      }
      const text2 = new $8$(this.m.getModel());
      const edit3 = inlineEdit.edit.extendToFullLine(text2);
      const diffResult = this.g.get({ original: this.m.getModel().getValueInRange(edit3.range), modified: edit3.text });
      return diffResult.promiseResult.map((p) => {
        if (!p || !p.data) {
          return void 0;
        }
        const result = p.data;
        const rangeStartPos = edit3.range.getStartPosition();
        const innerChanges = result.changes.flatMap((c) => c.innerChanges);
        function addRangeToPos(pos, range) {
          const start = $gD.fromPosition(range.getStartPosition());
          return $gD.ofRange(range).createRange(start.addToPosition(pos));
        }
        const edits = innerChanges.map((c) => new $jD(addRangeToPos(rangeStartPos, c.originalRange), this.f.get().getValueInRange(c.modifiedRange)));
        const diffEdits = new $iD(edits);
        return new $1hb(text2, diffEdits, inlineEdit.isCollapsed, inlineEdit.renderExplicitly, inlineEdit.commands, inlineEdit.inlineCompletion);
      });
    });
    this.j = $4d({ owner: this, equalsFn: $qd($pd()) }, (reader) => this.h.read(reader)?.read(reader));
    this.B(this.s.createInstance($Yhb, this.m, this.j, this.r));
  }
};
$Zhb = $Zhb_1 = __decorate([
  __param(3, $Pk),
  __param(4, $J0),
  __param(5, $sG)
], $Zhb);
var $1hb = class {
  constructor(originalText, edit3, isCollapsed, userJumpedToIt, commands2, inlineCompletion) {
    this.originalText = originalText;
    this.edit = edit3;
    this.isCollapsed = isCollapsed;
    this.userJumpedToIt = userJumpedToIt;
    this.commands = commands2;
    this.inlineCompletion = inlineCompletion;
    this.lineEdit = $fD.fromSingleTextEdit(this.edit.toSingle(this.originalText), this.originalText);
    this.originalLineRange = this.lineEdit.lineRange;
    this.modifiedLineRange = this.lineEdit.toLineEdit().getNewLineRanges()[0];
  }
  equals(other) {
    return this.originalText.getValue() === other.originalText.getValue() && this.edit.equals(other.edit) && this.isCollapsed === other.isCollapsed && this.userJumpedToIt === other.userJumpedToIt && this.commands === other.commands && this.inlineCompletion === other.inlineCompletion;
  }
};

// out-build/vs/editor/contrib/inlineCompletions/browser/view/inlineCompletionsView.js
var $2hb = class $2hb2 extends $3c {
  constructor(n, r2, s) {
    super();
    this.n = n;
    this.r = r2;
    this.s = s;
    this.a = $2d(this, (reader) => {
      const model = this.r.read(reader);
      return model?.ghostTexts.read(reader) ?? [];
    });
    this.b = $Kcb(this.a, this.q);
    this.c = $Rd(this, this.b, (ghostText, store) => $7d((reader) => this.s.createInstance($N3($Ahb, reader), this.n, {
      ghostText,
      minReservedLineCount: $Bd(0),
      targetTextModel: this.r.map((v) => v?.textModel)
    })).recomputeInitiallyAndOnChange(store)).recomputeInitiallyAndOnChange(this.q);
    this.f = $2d(this, (reader) => this.r.read(reader)?.inlineEditState.read(reader)?.inlineEdit);
    this.g = $Pd(this, (reader, last) => last || !!this.f.read(reader));
    this.h = $7d((reader) => {
      if (!this.g.read(reader)) {
        return void 0;
      }
      return this.s.createInstance($Zhb.hot.read(reader), this.n, this.f, this.r);
    }).recomputeInitiallyAndOnChange(this.q);
    this.j = $79(this.n);
    this.m = this.j.getOption(
      64
      /* EditorOption.inlineSuggest */
    ).map((val) => val.fontFamily);
    this.B($81($2d((reader) => {
      const fontFamily = this.m.read(reader);
      if (fontFamily === "" || fontFamily === "default") {
        return "";
      }
      return `
.monaco-editor .ghost-text-decoration,
.monaco-editor .ghost-text-decoration-preview,
.monaco-editor .ghost-text {
	font-family: ${fontFamily};
}`;
    })));
    this.B(new $xdb(this.n, this.r, this.s));
  }
  shouldShowHoverAtViewZone(viewZoneId) {
    return this.c.get()[0]?.get().ownsViewZone(viewZoneId) ?? false;
  }
};
$2hb = __decorate([
  __param(2, $Pk)
], $2hb);

// out-build/vs/editor/contrib/inlineCompletions/browser/controller/inlineCompletionsController.js
var $3hb_1;
var $3hb = class $3hb2 extends $3c {
  static {
    $3hb_1 = this;
  }
  static {
    this.hot = $P3($3hb_1);
  }
  static {
    this.ID = "editor.contrib.inlineCompletionsController";
  }
  static get(editor) {
    return $whb(editor.getContribution($3hb_1.ID));
  }
  constructor(editor, z, C, D, F, G, H, I, J, L) {
    super();
    this.editor = editor;
    this.z = z;
    this.C = C;
    this.D = D;
    this.F = F;
    this.G = G;
    this.H = H;
    this.I = I;
    this.J = J;
    this.L = L;
    this.a = $79(this.editor);
    this.b = $2d(this, (reader) => this.a.selections.read(reader)?.map((s) => s.getEndPosition()) ?? [new $8C(1, 1)]);
    this.c = this.B(new $udb(this.a, (item) => this.model.get()?.handleSuggestAccepted(item), () => this.model.get()?.selectedInlineCompletion.get()?.toSingleTextEdit(void 0)));
    this.f = $Dd(this, this.editor.onDidChangeConfiguration, () => this.editor.getOption(
      64
      /* EditorOption.inlineSuggest */
    ).enabled);
    this.g = $Dd(this, this.L.onDidChangeScreenReaderOptimized, () => this.L.isScreenReaderOptimized());
    this.h = $Dd(this, this.C.onDidChangeContext, () => this.C.getContext(this.editor.getDomNode()).getValue("editorDictation.inProgress") === true);
    this.j = $2d(this, (reader) => this.f.read(reader) && (!this.g.read(reader) || !this.h.read(reader)));
    this.n = this.G.for(this.H.inlineCompletionsProvider, "InlineCompletionsDebounce", { min: 50, max: 50 });
    this.t = $2d(this, (reader) => {
      const cursorPos = this.a.cursorPosition.read(reader);
      if (cursorPos === null) {
        return false;
      }
      const model = this.a.model.read(reader);
      if (!model) {
        return false;
      }
      this.a.versionId.read(reader);
      const indentMaxColumn = model.getLineIndentColumn(cursorPos.lineNumber);
      return cursorPos.column <= indentMaxColumn;
    });
    this.model = $7d(this, (reader) => {
      if (this.a.isReadonly.read(reader)) {
        return void 0;
      }
      const textModel = this.a.model.read(reader);
      if (!textModel) {
        return void 0;
      }
      const model = this.z.createInstance($vdb, textModel, this.c.selectedItem, this.a.versionId, this.b, this.n, this.j, this.editor);
      return model;
    }).recomputeInitiallyAndOnChange(this.q);
    this.u = $Hd(this);
    this.w = this.a.getOption(
      64
      /* EditorOption.inlineSuggest */
    ).map((val) => true);
    this.y = this.B(new $2hb(this.editor, this.model, this.z));
    this.B($Wd(this.a.onDidType, (_value, _changes) => {
      if (this.j.get()) {
        this.model.get()?.trigger();
      }
    }));
    this.B(this.F.onDidExecuteCommand((e) => {
      const commands2 = /* @__PURE__ */ new Set([
        CoreEditingCommands.Tab.id,
        CoreEditingCommands.DeleteLeft.id,
        CoreEditingCommands.DeleteRight.id,
        $4bb,
        "acceptSelectedSuggestion"
      ]);
      if (commands2.has(e.commandId) && editor.hasTextFocus() && this.j.get()) {
        this.a.forceUpdate((tx) => {
          this.model.get()?.trigger(tx);
        });
      }
    }));
    this.B($Wd(this.a.selections, (_value, _, changes) => {
      if (changes.some((e) => e.reason === 3 || e.source === "api")) {
        if (!this.w.get() && this.model.get()?.state.get()?.kind === "inlineEdit") {
          return;
        }
        const m = this.model.get();
        if (!m) {
          return;
        }
        if (m.inlineCompletionState.get()?.primaryGhostText) {
          this.model.get()?.stop();
        } else if (m.state.get()?.inlineCompletion) {
          this.model.get()?.collapseInlineEdit();
        }
      }
    }));
    this.B(this.editor.onDidBlurEditorWidget(() => {
      if (this.C.getContextKeyValue("accessibleViewIsShown") || this.D.getValue("editor.inlineSuggest.keepOnBlur") || editor.getOption(
        64
        /* EditorOption.inlineSuggest */
      ).keepOnBlur || $ydb.dropDownVisible) {
        return;
      }
      if (this.model.get()?.inlineEditAvailable.get()) {
        return;
      }
      $ce((tx) => {
        this.model.get()?.stop("automatic", tx);
      });
    }));
    this.B($td((reader) => {
      const state = this.model.read(reader)?.inlineCompletionState.read(reader);
      if (state?.suggestItem) {
        if (state.primaryGhostText.lineCount >= 2) {
          this.c.forceRenderingAbove();
        }
      } else {
        this.c.stopForceRenderingAbove();
      }
    }));
    this.B($1c(() => {
      this.c.stopForceRenderingAbove();
    }));
    const currentInlineCompletionBySemanticId = $Pd(this, (reader, last) => {
      const model = this.model.read(reader);
      const state = model?.inlineCompletionState.read(reader);
      if (this.c.selectedItem.get()) {
        return last;
      }
      return state?.inlineCompletion?.semanticId;
    });
    this.B($Xd($2d((reader) => {
      this.u.read(reader);
      currentInlineCompletionBySemanticId.read(reader);
      return {};
    }), async (_value, _, _deltas, store) => {
      const model = this.model.get();
      const state = model?.inlineCompletionState.get();
      if (!state || !model) {
        return;
      }
      const lineText = model.textModel.getLineContent(state.primaryGhostText.lineNumber);
      await $Wh(50, $bd(store));
      await $re(this.c.selectedItem, $Gg, () => false, $bd(store));
      await this.I.playSignal($N9.inlineSuggestion);
      if (this.editor.getOption(
        8
        /* EditorOption.screenReaderAnnounceInlineSuggestion */
      )) {
        this.M(state.primaryGhostText.renderForScreenReader(lineText));
      }
    }));
    this.B(this.D.onDidChangeConfiguration((e) => {
      if (e.affectsConfiguration("accessibility.verbosity.inlineCompletions")) {
        this.editor.updateOptions({ inlineCompletionsAccessibilityVerbose: this.D.getValue("accessibility.verbosity.inlineCompletions") });
      }
    }));
    this.editor.updateOptions({ inlineCompletionsAccessibilityVerbose: this.D.getValue("accessibility.verbosity.inlineCompletions") });
    const contextKeySvcObs = new $Lcb(this.C);
    this.B(contextKeySvcObs.bind($ocb.cursorInIndentation, this.t));
    this.B(contextKeySvcObs.bind($ocb.hasSelection, (reader) => !this.a.cursorSelection.read(reader)?.isEmpty()));
    this.B(contextKeySvcObs.bind($ocb.cursorAtInlineEdit, this.model.map((m, reader) => m?.inlineEditState?.read(reader)?.cursorAtInlineEdit)));
    this.B(contextKeySvcObs.bind($ocb.tabShouldAcceptInlineEdit, this.model.map((m, r2) => !!m?.tabShouldAcceptInlineEdit.read(r2))));
    this.B(contextKeySvcObs.bind($ocb.tabShouldJumpToInlineEdit, this.model.map((m, r2) => !!m?.tabShouldJumpToInlineEdit.read(r2))));
    this.B(contextKeySvcObs.bind($ocb.inlineEditVisible, (reader) => this.model.read(reader)?.inlineEditState.read(reader) !== void 0));
    this.B(contextKeySvcObs.bind($ocb.inlineSuggestionHasIndentation, (reader) => this.model.read(reader)?.getIndentationInfo(reader)?.startsWithIndentation));
    this.B(contextKeySvcObs.bind($ocb.inlineSuggestionHasIndentationLessThanTabSize, (reader) => this.model.read(reader)?.getIndentationInfo(reader)?.startsWithIndentationLessThanTabSize));
    this.B(contextKeySvcObs.bind($ocb.suppressSuggestions, (reader) => {
      const model = this.model.read(reader);
      const state = model?.inlineCompletionState.read(reader);
      return state?.primaryGhostText && state?.inlineCompletion ? state.inlineCompletion.inlineCompletion.source.inlineCompletions.suppressSuggestions : void 0;
    }));
    this.B(contextKeySvcObs.bind($ocb.inlineSuggestionVisible, (reader) => {
      const model = this.model.read(reader);
      const state = model?.inlineCompletionState.read(reader);
      return !!state?.inlineCompletion && state?.primaryGhostText !== void 0 && !state?.primaryGhostText.isEmpty();
    }));
    this.B(this.z.createInstance($zhb, this.editor));
  }
  playAccessibilitySignal(tx) {
    this.u.trigger(tx);
  }
  M(content) {
    const accessibleViewShowing = this.C.getContextKeyValue("accessibleViewIsShown");
    const accessibleViewKeybinding = this.J.lookupKeybinding("editor.action.accessibleView");
    let hint;
    if (!accessibleViewShowing && accessibleViewKeybinding && this.editor.getOption(
      155
      /* EditorOption.inlineCompletionsAccessibilityVerbose */
    )) {
      hint = localize(1278, null, accessibleViewKeybinding.getAriaLabel());
    }
    $$Z(hint ? content + ", " + hint : content);
  }
  shouldShowHoverAt(range) {
    const ghostText = this.model.get()?.primaryGhostText.get();
    if (!ghostText) {
      return false;
    }
    return ghostText.parts.some((p) => range.containsPosition(new $8C(ghostText.lineNumber, p.column)));
  }
  shouldShowHoverAtViewZone(viewZoneId) {
    return this.y.shouldShowHoverAtViewZone(viewZoneId);
  }
  reject() {
    $ce((tx) => {
      const m = this.model.get();
      if (m) {
        m.stop("explicitCancel", tx);
      }
    });
  }
  jump() {
    const m = this.model.get();
    if (m) {
      m.jump();
    }
  }
};
$3hb = $3hb_1 = __decorate([
  __param(1, $Pk),
  __param(2, $on),
  __param(3, $kl),
  __param(4, $sn),
  __param(5, $tbb),
  __param(6, $mP),
  __param(7, $I9),
  __param(8, $Ty),
  __param(9, $ND)
], $3hb);

// out-build/vs/editor/contrib/inlineCompletions/browser/controller/commands.js
var $4hb = class _$4hb extends $Z5 {
  static {
    this.ID = $6bb;
  }
  constructor() {
    super({
      id: _$4hb.ID,
      label: localize2(1259, "Show Next Inline Suggestion"),
      precondition: $7m.and(EditorContextKeys.writable, $ocb.inlineSuggestionVisible),
      kbOpts: {
        weight: 100,
        primary: 512 | 94
      }
    });
  }
  async run(accessor, editor) {
    const controller = $3hb.get(editor);
    controller?.model.get()?.next();
  }
};
var $5hb = class _$5hb extends $Z5 {
  static {
    this.ID = $5bb;
  }
  constructor() {
    super({
      id: _$5hb.ID,
      label: localize2(1260, "Show Previous Inline Suggestion"),
      precondition: $7m.and(EditorContextKeys.writable, $ocb.inlineSuggestionVisible),
      kbOpts: {
        weight: 100,
        primary: 512 | 92
      }
    });
  }
  async run(accessor, editor) {
    const controller = $3hb.get(editor);
    controller?.model.get()?.previous();
  }
};
var $6hb = class extends $Z5 {
  constructor() {
    super({
      id: "editor.action.inlineSuggest.trigger",
      label: localize2(1261, "Trigger Inline Suggestion"),
      precondition: EditorContextKeys.writable
    });
  }
  async run(accessor, editor) {
    const controller = $3hb.get(editor);
    await $ee(async (tx) => {
      await controller?.model.get()?.triggerExplicitly(tx);
      controller?.playAccessibilitySignal(tx);
    });
  }
};
var $7hb = class extends $Z5 {
  constructor() {
    super({
      id: "editor.action.inlineSuggest.triggerInlineEditExplicit",
      label: localize2(1262, "Trigger Inline Edit"),
      precondition: EditorContextKeys.writable
    });
  }
  async run(accessor, editor) {
    const notificationService = accessor.get($PJ);
    const controller = $3hb.get(editor);
    await controller?.model.get()?.triggerExplicitly(void 0, true);
    if (!controller?.model.get()?.inlineEditAvailable.get()) {
      notificationService.notify({
        severity: Severity2.Info,
        message: localize(1250, null)
      });
    }
  }
};
var $8hb = class extends $Y5 {
  constructor() {
    super({
      id: "editor.action.inlineSuggest.triggerInlineEdit",
      precondition: EditorContextKeys.writable
    });
  }
  async runEditorCommand(accessor, editor, args2) {
    const controller = $3hb.get(editor);
    await controller?.model.get()?.trigger(void 0, true);
  }
};
var $9hb = class extends $Z5 {
  constructor() {
    super({
      id: "editor.action.inlineSuggest.acceptNextWord",
      label: localize2(1263, "Accept Next Word Of Inline Suggestion"),
      precondition: $7m.and(EditorContextKeys.writable, $ocb.inlineSuggestionVisible),
      kbOpts: {
        weight: 100 + 1,
        primary: 2048 | 17,
        kbExpr: $7m.and(EditorContextKeys.writable, $ocb.inlineSuggestionVisible)
      },
      menuOpts: [{
        menuId: $bJ.InlineSuggestionToolbar,
        title: localize(1251, null),
        group: "primary",
        order: 2
      }]
    });
  }
  async run(accessor, editor) {
    const controller = $3hb.get(editor);
    await controller?.model.get()?.acceptNextWord(controller.editor);
  }
};
var $0hb = class extends $Z5 {
  constructor() {
    super({
      id: "editor.action.inlineSuggest.acceptNextLine",
      label: localize2(1264, "Accept Next Line Of Inline Suggestion"),
      precondition: $7m.and(EditorContextKeys.writable, $ocb.inlineSuggestionVisible),
      kbOpts: {
        weight: 100 + 1
      },
      menuOpts: [{
        menuId: $bJ.InlineSuggestionToolbar,
        title: localize(1252, null),
        group: "secondary",
        order: 2
      }]
    });
  }
  async run(accessor, editor) {
    const controller = $3hb.get(editor);
    await controller?.model.get()?.acceptNextLine(controller.editor);
  }
};
var $$hb = class extends $Z5 {
  constructor() {
    super({
      id: $4bb,
      label: localize2(1265, "Accept Inline Suggestion"),
      precondition: $7m.or($ocb.inlineSuggestionVisible, $ocb.inlineEditVisible),
      menuOpts: [{
        menuId: $bJ.InlineSuggestionToolbar,
        title: localize(1253, null),
        group: "primary",
        order: 2
      }, {
        menuId: $bJ.InlineEditsActions,
        title: localize(1254, null),
        group: "primary",
        order: 2
      }],
      kbOpts: [
        {
          primary: 2,
          weight: 200,
          kbExpr: $7m.or($7m.and($ocb.inlineSuggestionVisible, EditorContextKeys.tabMovesFocus.toNegated(), $_bb.Visible.toNegated(), EditorContextKeys.hoverFocused.toNegated(), $ocb.inlineSuggestionHasIndentationLessThanTabSize), $7m.and($ocb.inlineEditVisible, EditorContextKeys.tabMovesFocus.toNegated(), $_bb.Visible.toNegated(), EditorContextKeys.hoverFocused.toNegated(), $ocb.tabShouldAcceptInlineEdit))
        }
      ]
    });
  }
  async run(accessor, editor) {
    const controller = $3hb.get(editor);
    if (controller) {
      controller.model.get()?.accept(controller.editor);
      controller.editor.focus();
    }
  }
};
var $_hb = class extends $Z5 {
  constructor() {
    super({
      id: "editor.action.inlineSuggest.jump",
      label: localize2(1266, "Jump to next inline edit"),
      precondition: $ocb.inlineEditVisible,
      menuOpts: [{
        menuId: $bJ.InlineEditsActions,
        title: localize(1255, null),
        group: "primary",
        order: 1,
        when: $ocb.cursorAtInlineEdit.toNegated()
      }],
      kbOpts: {
        primary: 2,
        weight: 201,
        kbExpr: $7m.and($ocb.inlineEditVisible, EditorContextKeys.tabMovesFocus.toNegated(), $_bb.Visible.toNegated(), EditorContextKeys.hoverFocused.toNegated(), $ocb.tabShouldJumpToInlineEdit)
      }
    });
  }
  async run(accessor, editor) {
    const controller = $3hb.get(editor);
    if (controller) {
      controller.jump();
    }
  }
};
var $aib = class _$aib extends $Z5 {
  static {
    this.ID = "editor.action.inlineSuggest.hide";
  }
  constructor() {
    super({
      id: _$aib.ID,
      label: localize2(1267, "Hide Inline Suggestion"),
      precondition: $7m.or($ocb.inlineSuggestionVisible, $ocb.inlineEditVisible),
      kbOpts: {
        weight: 100,
        primary: 9
      },
      menuOpts: [{
        menuId: $bJ.InlineEditsActions,
        title: localize(1256, null),
        group: "primary",
        order: 3
      }]
    });
  }
  async run(accessor, editor) {
    const controller = $3hb.get(editor);
    $ce((tx) => {
      controller?.model.get()?.stop("explicitCancel", tx);
    });
  }
};
var $bib = class _$bib extends $gJ {
  static {
    this.ID = "editor.action.inlineSuggest.toggleAlwaysShowToolbar";
  }
  constructor() {
    super({
      id: _$bib.ID,
      title: localize(1257, null),
      f1: false,
      precondition: void 0,
      menu: [{
        id: $bJ.InlineSuggestionToolbar,
        group: "secondary",
        order: 10
      }],
      toggled: $7m.equals("config.editor.inlineSuggest.showToolbar", "always")
    });
  }
  async run(accessor) {
    const configService = accessor.get($kl);
    const currentValue = configService.getValue("editor.inlineSuggest.showToolbar");
    const newValue = currentValue === "always" ? "onHover" : "always";
    configService.updateValue("editor.inlineSuggest.showToolbar", newValue);
  }
};
var $cib = class extends $Z5 {
  constructor() {
    super({
      id: "editor.action.inlineSuggest.dev.extractRepro",
      label: localize(1258, null),
      alias: "Developer: Inline Suggest Extract Repro",
      precondition: $ocb.inlineEditVisible
    });
  }
  async run(accessor, editor) {
    const clipboardService = accessor.get($30);
    const controller = $3hb.get(editor);
    const m = controller?.model.get();
    if (!m) {
      return;
    }
    const repro = m.extractReproSample();
    const inlineCompletionLines = $Mf(JSON.stringify({ inlineCompletion: repro.inlineCompletion }, null, 4));
    const json = inlineCompletionLines.map((l) => "// " + l).join("\n");
    const reproStr = `${repro.documentValue}

// <json>
${json}
// </json>
`;
    await clipboardService.writeText(reproStr);
    return { reproCase: reproStr };
  }
};

// out-build/vs/editor/contrib/inlineCompletions/browser/hintsWidget/hoverParticipant.js
var $dib = class {
  constructor(owner, range, controller) {
    this.owner = owner;
    this.range = range;
    this.controller = controller;
  }
  isValidForHoverAnchor(anchor) {
    return anchor.type === 1 && this.range.startColumn <= anchor.range.startColumn && this.range.endColumn >= anchor.range.endColumn;
  }
};
var $eib = class $eib2 {
  constructor(a, b, c, d, e, f) {
    this.a = a;
    this.b = b;
    this.c = c;
    this.d = d;
    this.e = e;
    this.f = f;
    this.hoverOrdinal = 4;
  }
  suggestHoverAnchor(mouseEvent) {
    const controller = $3hb.get(this.a);
    if (!controller) {
      return null;
    }
    const target = mouseEvent.target;
    if (target.type === 8) {
      const viewZoneData = target.detail;
      if (controller.shouldShowHoverAtViewZone(viewZoneData.viewZoneId)) {
        return new $zbb(1e3, this, $9C.fromPositions(this.a.getModel().validatePosition(viewZoneData.positionBefore || viewZoneData.position)), mouseEvent.event.posx, mouseEvent.event.posy, false);
      }
    }
    if (target.type === 7) {
      if (controller.shouldShowHoverAt(target.range)) {
        return new $zbb(1e3, this, target.range, mouseEvent.event.posx, mouseEvent.event.posy, false);
      }
    }
    if (target.type === 6) {
      const mightBeForeignElement = target.detail.mightBeForeignElement;
      if (mightBeForeignElement && controller.shouldShowHoverAt(target.range)) {
        return new $zbb(1e3, this, target.range, mouseEvent.event.posx, mouseEvent.event.posy, false);
      }
    }
    return null;
  }
  computeSync(anchor, lineDecorations) {
    if (this.a.getOption(
      64
      /* EditorOption.inlineSuggest */
    ).showToolbar !== "onHover") {
      return [];
    }
    const controller = $3hb.get(this.a);
    if (controller && controller.shouldShowHoverAt(anchor.range)) {
      return [new $dib(this, anchor.range, controller)];
    }
    return [];
  }
  renderHoverParts(context, hoverParts) {
    const disposables = new $2c();
    const part = hoverParts[0];
    this.f.publicLog2("inlineCompletionHover.shown");
    if (this.d.isScreenReaderOptimized() && !this.a.getOption(
      8
      /* EditorOption.screenReaderAnnounceInlineSuggestion */
    )) {
      disposables.add(this.g(context, part));
    }
    const model = part.controller.model.get();
    const w = this.e.createInstance($ydb, this.a, false, $Bd(null), model.selectedInlineCompletionIndex, model.inlineCompletionsCount, model.activeCommands);
    const widgetNode = w.getDomNode();
    context.fragment.appendChild(widgetNode);
    model.triggerExplicitly();
    disposables.add(w);
    const renderedHoverPart = {
      hoverPart: part,
      hoverElement: widgetNode,
      dispose() {
        disposables.dispose();
      }
    };
    return new $Abb([renderedHoverPart]);
  }
  getAccessibleContent(hoverPart) {
    return localize(1279, null);
  }
  g(context, part) {
    const disposables = new $2c();
    const $149 = $;
    const markdownHoverElement = $149("div.hover-row.markdown-hover");
    const hoverContentsElement = $bk(markdownHoverElement, $149("div.hover-contents", { ["aria-live"]: "assertive" }));
    const renderer = disposables.add(new $Q_({ editor: this.a }, this.b, this.c));
    const render = (code) => {
      disposables.add(renderer.onDidRenderAsync(() => {
        hoverContentsElement.className = "hover-contents code-hover-contents";
        context.onContentsChanged();
      }));
      const inlineSuggestionAvailable = localize(1280, null);
      const renderedContents = disposables.add(renderer.render(new $bm().appendText(inlineSuggestionAvailable).appendCodeblock("text", code)));
      hoverContentsElement.replaceChildren(renderedContents.element);
    };
    disposables.add($td((reader) => {
      const ghostText = part.controller.model.read(reader)?.primaryGhostText.read(reader);
      if (ghostText) {
        const lineText = this.a.getModel().getLineContent(ghostText.lineNumber);
        render(ghostText.renderForScreenReader(lineText));
      } else {
        $dk(hoverContentsElement);
      }
    }));
    context.fragment.appendChild(markdownHoverElement);
    return disposables;
  }
};
$eib = __decorate([
  __param(1, $1E),
  __param(2, $O4),
  __param(3, $ND),
  __param(4, $Pk),
  __param(5, $zv)
], $eib);

// out-build/vs/editor/contrib/inlineCompletions/browser/inlineCompletionsAccessibleView.js
var $fib = class {
  constructor() {
    this.type = "view";
    this.priority = 95;
    this.name = "inline-completions";
    this.when = $7m.and($ocb.inlineSuggestionVisible);
  }
  getProvider(accessor) {
    const codeEditorService = accessor.get($U5);
    const editor = codeEditorService.getActiveCodeEditor() || codeEditorService.getFocusedCodeEditor();
    if (!editor) {
      return;
    }
    const model = $3hb.get(editor)?.model.get();
    if (!model?.inlineCompletionState.get()) {
      return;
    }
    return new InlineCompletionsAccessibleViewContentProvider(editor, model);
  }
};
var InlineCompletionsAccessibleViewContentProvider = class extends $3c {
  constructor(b, c) {
    super();
    this.b = b;
    this.c = c;
    this.a = this.B(new $ze());
    this.onDidChangeContent = this.a.event;
    this.id = "inlineCompletions";
    this.verbositySettingKey = "accessibility.verbosity.inlineCompletions";
    this.options = {
      language: this.b.getModel()?.getLanguageId() ?? void 0,
      type: "view"
      /* AccessibleViewType.View */
    };
  }
  provideContent() {
    const state = this.c.inlineCompletionState.get();
    if (!state) {
      throw new Error("Inline completion is visible but state is not available");
    }
    const lineText = this.c.textModel.getLineContent(state.primaryGhostText.lineNumber);
    const ghostText = state.primaryGhostText.renderForScreenReader(lineText);
    if (!ghostText) {
      throw new Error("Inline completion is visible but ghost text is not available");
    }
    return lineText + ghostText;
  }
  provideNextContent() {
    this.c.next().then(() => this.a.fire());
    return;
  }
  providePreviousContent() {
    this.c.previous().then(() => this.a.fire());
    return;
  }
  onClose() {
    this.c.stop();
    this.b.focus();
  }
};

// out-build/vs/editor/contrib/inlineCompletions/browser/model/inlineEditsAdapter.js
var $gib_1;
var $gib = class $gib2 extends $3c {
  static {
    $gib_1 = this;
  }
  static {
    this.ID = "editor.contrib.inlineEditsAdapter";
  }
  static {
    this.isFirst = true;
  }
  constructor(_editor, a) {
    super();
    this.a = a;
    if ($gib_1.isFirst) {
      $gib_1.isFirst = false;
      this.a.createInstance($hib);
    }
  }
};
$gib = $gib_1 = __decorate([
  __param(1, $Pk)
], $gib);
var $hib = class $hib2 extends $3c {
  constructor(a, b) {
    super();
    this.a = a;
    this.b = b;
    const didChangeSignal = $Gd("didChangeSignal", this.a.inlineEditProvider.onDidChange);
    this.B($xd((reader, store) => {
      didChangeSignal.read(reader);
      store.add(this.a.inlineCompletionsProvider.register("*", {
        async provideInlineCompletions(model, position, context, token) {
          if (!context.includeInlineEdits) {
            return void 0;
          }
          const allInlineEditProvider = a.inlineEditProvider.all(model);
          const inlineEdits = await Promise.all(allInlineEditProvider.map(async (provider) => {
            const result = await provider.provideInlineEdit(model, {
              triggerKind: InlineEditTriggerKind.Automatic
            }, token);
            if (!result) {
              return void 0;
            }
            return { result, provider };
          }));
          const definedEdits = inlineEdits.filter((e) => !!e);
          return {
            edits: definedEdits,
            items: definedEdits.map((e) => {
              return {
                range: e.result.range,
                insertText: e.result.text,
                command: e.result.accepted,
                shownCommand: e.result.shown,
                isInlineEdit: true,
                edit: e.result
              };
            }),
            commands: definedEdits.flatMap((e) => e.result.commands ?? [])
          };
        },
        handleRejection: (completions, item) => {
          if (item.edit.rejected) {
            this.b.executeCommand(item.edit.rejected.id, ...item.edit.rejected.arguments ?? []);
          }
        },
        freeInlineCompletions(c) {
          for (const e of c.edits) {
            e.provider.freeInlineEdit(e.result);
          }
        },
        toString() {
          return "InlineEditsAdapter";
        }
      }));
    }));
  }
};
$hib = __decorate([
  __param(0, $mP),
  __param(1, $sn)
], $hib);

// out-build/vs/editor/contrib/inlineCompletions/browser/inlineCompletions.contribution.js
$85(
  $gib.ID,
  $gib,
  3
  /* EditorContributionInstantiation.Eventually */
);
$85(
  $3hb.ID,
  $yhb($3hb.hot),
  3
  /* EditorContributionInstantiation.Eventually */
);
$55($6hb);
$55($7hb);
$45(new $8hb());
$55($4hb);
$55($5hb);
$55($9hb);
$55($0hb);
$55($$hb);
$55($aib);
$55($_hb);
$hJ($bib);
$55($cib);
$Bbb.register($eib);
$vhb.register(new $fib());

// out-build/vs/editor/contrib/gotoSymbol/browser/link/goToDefinitionAtPosition.js
var $iib_1;
var $iib = class $iib2 {
  static {
    $iib_1 = this;
  }
  static {
    this.ID = "editor.contrib.gotodefinitionatposition";
  }
  static {
    this.MAX_SOURCE_PREVIEW_LINES = 8;
  }
  constructor(editor, h3, i2, j) {
    this.h = h3;
    this.i = i2;
    this.j = j;
    this.b = new $2c();
    this.c = new $2c();
    this.f = null;
    this.g = null;
    this.a = editor;
    this.d = this.a.createDecorationsCollection();
    const linkGesture = new $6db(editor);
    this.b.add(linkGesture);
    this.b.add(linkGesture.onMouseMoveOrRelevantKeyDown(([mouseEvent, keyboardEvent]) => {
      this.k(mouseEvent, keyboardEvent ?? void 0);
    }));
    this.b.add(linkGesture.onExecute((mouseEvent) => {
      if (this.r(mouseEvent)) {
        this.t(mouseEvent.target.position, mouseEvent.hasSideBySideModifier).catch((error) => {
          $gb(error);
        }).finally(() => {
          this.q();
        });
      }
    }));
    this.b.add(linkGesture.onCancel(() => {
      this.q();
      this.f = null;
    }));
  }
  static get(editor) {
    return editor.getContribution($iib_1.ID);
  }
  async startFindDefinitionFromCursor(position) {
    await this.l(position);
    this.c.add(this.a.onDidChangeCursorPosition(() => {
      this.f = null;
      this.q();
      this.c.clear();
    }));
    this.c.add(this.a.onKeyDown((e) => {
      if (e) {
        this.f = null;
        this.q();
        this.c.clear();
      }
    }));
  }
  k(mouseEvent, withKey) {
    if (mouseEvent.target.type === 9 && this.d.length > 0) {
      return;
    }
    if (!this.a.hasModel() || !this.r(mouseEvent, withKey)) {
      this.f = null;
      this.q();
      return;
    }
    const position = mouseEvent.target.position;
    this.l(position);
  }
  async l(position) {
    this.c.clear();
    const word = position ? this.a.getModel()?.getWordAtPosition(position) : null;
    if (!word) {
      this.f = null;
      this.q();
      return;
    }
    if (this.f && this.f.startColumn === word.startColumn && this.f.endColumn === word.endColumn && this.f.word === word.word) {
      return;
    }
    this.f = word;
    const state = new $M_(
      this.a,
      4 | 1 | 2 | 8
      /* CodeEditorStateFlag.Scroll */
    );
    if (this.g) {
      this.g.cancel();
      this.g = null;
    }
    this.g = $Hh((token) => this.s(position, token));
    let results;
    try {
      results = await this.g;
    } catch (error) {
      $gb(error);
      return;
    }
    if (!results || !results.length || !state.validate(this.a)) {
      this.q();
      return;
    }
    const linkRange = results[0].originSelectionRange ? $9C.lift(results[0].originSelectionRange) : new $9C(position.lineNumber, word.startColumn, position.lineNumber, word.endColumn);
    if (results.length > 1) {
      let combinedRange = linkRange;
      for (const { originSelectionRange } of results) {
        if (originSelectionRange) {
          combinedRange = $9C.plusRange(combinedRange, originSelectionRange);
        }
      }
      this.p(combinedRange, new $bm().appendText(localize(1153, null, results.length)));
    } else {
      const result = results[0];
      if (!result.uri) {
        return;
      }
      this.h.createModelReference(result.uri).then((ref) => {
        if (!ref.object || !ref.object.textEditorModel) {
          ref.dispose();
          return;
        }
        const { object: { textEditorModel } } = ref;
        const { startLineNumber } = result.range;
        if (startLineNumber < 1 || startLineNumber > textEditorModel.getLineCount()) {
          ref.dispose();
          return;
        }
        const previewValue = this.m(textEditorModel, startLineNumber, result);
        const languageId = this.i.guessLanguageIdByFilepathOrFirstLine(textEditorModel.uri);
        this.p(linkRange, previewValue ? new $bm().appendCodeblock(languageId ? languageId : "", previewValue) : void 0);
        ref.dispose();
      });
    }
  }
  m(textEditorModel, startLineNumber, result) {
    let rangeToUse = result.range;
    const numberOfLinesInRange = rangeToUse.endLineNumber - rangeToUse.startLineNumber;
    if (numberOfLinesInRange >= $iib_1.MAX_SOURCE_PREVIEW_LINES) {
      rangeToUse = this.o(textEditorModel, startLineNumber);
    }
    const previewValue = this.n(textEditorModel, startLineNumber, rangeToUse);
    return previewValue;
  }
  n(textEditorModel, startLineNumber, previewRange) {
    const startIndent = textEditorModel.getLineFirstNonWhitespaceColumn(startLineNumber);
    let minIndent = startIndent;
    for (let endLineNumber = startLineNumber + 1; endLineNumber < previewRange.endLineNumber; endLineNumber++) {
      const endIndent = textEditorModel.getLineFirstNonWhitespaceColumn(endLineNumber);
      minIndent = Math.min(minIndent, endIndent);
    }
    const previewValue = textEditorModel.getValueInRange(previewRange).replace(new RegExp(`^\\s{${minIndent - 1}}`, "gm"), "").trim();
    return previewValue;
  }
  o(textEditorModel, startLineNumber) {
    const startIndent = textEditorModel.getLineFirstNonWhitespaceColumn(startLineNumber);
    const maxLineNumber = Math.min(textEditorModel.getLineCount(), startLineNumber + $iib_1.MAX_SOURCE_PREVIEW_LINES);
    let endLineNumber = startLineNumber + 1;
    for (; endLineNumber < maxLineNumber; endLineNumber++) {
      const endIndent = textEditorModel.getLineFirstNonWhitespaceColumn(endLineNumber);
      if (startIndent === endIndent) {
        break;
      }
    }
    return new $9C(startLineNumber, 1, endLineNumber + 1, 1);
  }
  p(range, hoverMessage) {
    const newDecorations = {
      range,
      options: {
        description: "goto-definition-link",
        inlineClassName: "goto-definition-link",
        hoverMessage
      }
    };
    this.d.set([newDecorations]);
  }
  q() {
    this.d.clear();
  }
  r(mouseEvent, withKey) {
    return this.a.hasModel() && mouseEvent.isLeftClick && mouseEvent.isNoneOrSingleMouseDown && mouseEvent.target.type === 6 && !(mouseEvent.target.detail.injectedText?.options instanceof $VI) && (mouseEvent.hasTriggerModifier || (withKey ? withKey.keyCodeIsTriggerKey : false)) && this.j.definitionProvider.has(this.a.getModel());
  }
  s(position, token) {
    const model = this.a.getModel();
    if (!model) {
      return Promise.resolve(null);
    }
    return $kfb(this.j.definitionProvider, model, position, false, token);
  }
  t(position, openToSide) {
    this.a.setPosition(position);
    return this.a.invokeWithinContext((accessor) => {
      const canPeek = !openToSide && this.a.getOption(
        93
        /* EditorOption.definitionLinkOpensInPeek */
      ) && !this.u(accessor);
      const action = new $rfb({ openToSide, openInPeek: canPeek, muteMessage: true }, { title: { value: "", original: "" }, id: "", precondition: void 0 });
      return action.run(accessor);
    });
  }
  u(accessor) {
    const contextKeyService = accessor.get($on);
    return PeekContext.inPeekEditor.getValue(contextKeyService);
  }
  dispose() {
    this.b.dispose();
    this.c.dispose();
  }
};
$iib = $iib_1 = __decorate([
  __param(1, $oG),
  __param(2, $1E),
  __param(3, $mP)
], $iib);
$85(
  $iib.ID,
  $iib,
  2
  /* EditorContributionInstantiation.BeforeFirstInteraction */
);

// out-build/vs/editor/contrib/gotoError/browser/markerNavigationService.js
var $jib = class {
  constructor(marker, index, total) {
    this.marker = marker;
    this.index = index;
    this.total = total;
  }
};
var $kib = class $kib2 {
  constructor(resourceFilter, h3, j) {
    this.h = h3;
    this.j = j;
    this.c = new $ze();
    this.onDidChange = this.c.event;
    this.e = new $2c();
    this.f = [];
    this.g = -1;
    if (URI.isUri(resourceFilter)) {
      this.d = (uri) => uri.toString() === resourceFilter.toString();
    } else if (resourceFilter) {
      this.d = resourceFilter;
    }
    const compareOrder = this.j.getValue("problems.sortOrder");
    const compareMarker = (a, b) => {
      let res = $Tf(a.resource.toString(), b.resource.toString());
      if (res === 0) {
        if (compareOrder === "position") {
          res = $9C.compareRangesUsingStarts(a, b) || MarkerSeverity.compare(a.severity, b.severity);
        } else {
          res = MarkerSeverity.compare(a.severity, b.severity) || $9C.compareRangesUsingStarts(a, b);
        }
      }
      return res;
    };
    const updateMarker = () => {
      this.f = this.h.read({
        resource: URI.isUri(resourceFilter) ? resourceFilter : void 0,
        severities: MarkerSeverity.Error | MarkerSeverity.Warning | MarkerSeverity.Info
      });
      if (typeof resourceFilter === "function") {
        this.f = this.f.filter((m) => this.d(m.resource));
      }
      this.f.sort(compareMarker);
    };
    updateMarker();
    this.e.add(h3.onMarkerChanged((uris) => {
      if (!this.d || uris.some((uri) => this.d(uri))) {
        updateMarker();
        this.g = -1;
        this.c.fire();
      }
    }));
  }
  dispose() {
    this.e.dispose();
    this.c.dispose();
  }
  matches(uri) {
    if (!this.d && !uri) {
      return true;
    }
    if (!this.d || !uri) {
      return false;
    }
    return this.d(uri);
  }
  get selected() {
    const marker = this.f[this.g];
    return marker && new $jib(marker, this.g + 1, this.f.length);
  }
  k(model, position, fwd) {
    let found = false;
    let idx = this.f.findIndex((marker) => marker.resource.toString() === model.uri.toString());
    if (idx < 0) {
      idx = $Bb(this.f, { resource: model.uri }, (a, b) => $Tf(a.resource.toString(), b.resource.toString()));
      if (idx < 0) {
        idx = ~idx;
      }
    }
    for (let i2 = idx; i2 < this.f.length; i2++) {
      let range = $9C.lift(this.f[i2]);
      if (range.isEmpty()) {
        const word = model.getWordAtPosition(range.getStartPosition());
        if (word) {
          range = new $9C(range.startLineNumber, word.startColumn, range.startLineNumber, word.endColumn);
        }
      }
      if (position && (range.containsPosition(position) || position.isBeforeOrEqual(range.getStartPosition()))) {
        this.g = i2;
        found = true;
        break;
      }
      if (this.f[i2].resource.toString() !== model.uri.toString()) {
        break;
      }
    }
    if (!found) {
      this.g = fwd ? 0 : this.f.length - 1;
    }
    if (this.g < 0) {
      this.g = this.f.length - 1;
    }
  }
  resetIndex() {
    this.g = -1;
  }
  move(fwd, model, position) {
    if (this.f.length === 0) {
      return false;
    }
    const oldIdx = this.g;
    if (this.g === -1) {
      this.k(model, position, fwd);
    } else if (fwd) {
      this.g = (this.g + 1) % this.f.length;
    } else if (!fwd) {
      this.g = (this.g - 1 + this.f.length) % this.f.length;
    }
    if (oldIdx !== this.g) {
      return true;
    }
    return false;
  }
  find(uri, position) {
    let idx = this.f.findIndex((marker) => marker.resource.toString() === uri.toString());
    if (idx < 0) {
      return void 0;
    }
    for (; idx < this.f.length; idx++) {
      if ($9C.containsPosition(this.f[idx], position)) {
        return new $jib(this.f[idx], idx + 1, this.f.length);
      }
    }
    return void 0;
  }
};
$kib = __decorate([
  __param(1, $DE),
  __param(2, $kl)
], $kib);
var $lib = $Qk("IMarkerNavigationService");
var MarkerNavigationService = class MarkerNavigationService2 {
  constructor(d, e) {
    this.d = d;
    this.e = e;
    this.c = new $cd();
  }
  registerProvider(provider) {
    const remove = this.c.unshift(provider);
    return $1c(() => remove());
  }
  getMarkerList(resource) {
    for (const provider of this.c) {
      const result = provider.getMarkerList(resource);
      if (result) {
        return result;
      }
    }
    return new $kib(resource, this.d, this.e);
  }
};
MarkerNavigationService = __decorate([
  __param(0, $DE),
  __param(1, $kl)
], MarkerNavigationService);
$SC(
  $lib,
  MarkerNavigationService,
  1
  /* InstantiationType.Delayed */
);

// out-build/vs/platform/severityIcon/browser/severityIcon.js
var SeverityIcon;
(function(SeverityIcon2) {
  function className(severity) {
    switch (severity) {
      case severity_default.Ignore:
        return "severity-ignore " + ThemeIcon.asClassName($6l.info);
      case severity_default.Info:
        return ThemeIcon.asClassName($6l.info);
      case severity_default.Warning:
        return ThemeIcon.asClassName($6l.warning);
      case severity_default.Error:
        return ThemeIcon.asClassName($6l.error);
      default:
        return "";
    }
  }
  SeverityIcon2.className = className;
})(SeverityIcon || (SeverityIcon = {}));

// out-build/vs/editor/contrib/gotoError/browser/gotoErrorWidget.js
var $mib_1;
var MessageWidget2 = class {
  constructor(parent, editor, onRelatedInformation, k, l) {
    this.k = k;
    this.l = l;
    this.a = 0;
    this.b = 0;
    this.h = /* @__PURE__ */ new WeakMap();
    this.i = new $2c();
    this.c = editor;
    const domNode = document.createElement("div");
    domNode.className = "descriptioncontainer";
    this.d = document.createElement("div");
    this.d.classList.add("message");
    this.d.setAttribute("aria-live", "assertive");
    this.d.setAttribute("role", "alert");
    domNode.appendChild(this.d);
    this.f = document.createElement("div");
    domNode.appendChild(this.f);
    this.i.add($aj(this.f, "click", (event) => {
      event.preventDefault();
      const related = this.h.get(event.target);
      if (related) {
        onRelatedInformation(related);
      }
    }));
    this.g = new $AZ(domNode, {
      horizontal: 1,
      vertical: 1,
      useShadows: false,
      horizontalScrollbarSize: 6,
      verticalScrollbarSize: 6
    });
    parent.appendChild(this.g.getDomNode());
    this.i.add(this.g.onScroll((e) => {
      domNode.style.left = `-${e.scrollLeft}px`;
      domNode.style.top = `-${e.scrollTop}px`;
    }));
    this.i.add(this.g);
  }
  dispose() {
    $Xc(this.i);
  }
  update(marker) {
    const { source, message, relatedInformation, code } = marker;
    let sourceAndCodeLength = (source?.length || 0) + "()".length;
    if (code) {
      if (typeof code === "string") {
        sourceAndCodeLength += code.length;
      } else {
        sourceAndCodeLength += code.value.length;
      }
    }
    const lines = $Mf(message);
    this.a = lines.length;
    this.b = 0;
    for (const line of lines) {
      this.b = Math.max(line.length + sourceAndCodeLength, this.b);
    }
    $$i(this.d);
    this.d.setAttribute("aria-label", this.m(marker));
    this.c.applyFontInfo(this.d);
    let lastLineElement = this.d;
    for (const line of lines) {
      lastLineElement = document.createElement("div");
      lastLineElement.innerText = line;
      if (line === "") {
        lastLineElement.style.height = this.d.style.lineHeight;
      }
      this.d.appendChild(lastLineElement);
    }
    if (source || code) {
      const detailsElement = document.createElement("span");
      detailsElement.classList.add("details");
      lastLineElement.appendChild(detailsElement);
      if (source) {
        const sourceElement = document.createElement("span");
        sourceElement.innerText = source;
        sourceElement.classList.add("source");
        detailsElement.appendChild(sourceElement);
      }
      if (code) {
        if (typeof code === "string") {
          const codeElement = document.createElement("span");
          codeElement.innerText = `(${code})`;
          codeElement.classList.add("code");
          detailsElement.appendChild(codeElement);
        } else {
          this.j = $("a.code-link");
          this.j.setAttribute("href", `${code.target.toString()}`);
          this.j.onclick = (e) => {
            this.k.open(code.target, { allowCommands: true });
            e.preventDefault();
            e.stopPropagation();
          };
          const codeElement = $bk(this.j, $("span"));
          codeElement.innerText = code.value;
          detailsElement.appendChild(this.j);
        }
      }
    }
    $$i(this.f);
    this.c.applyFontInfo(this.f);
    if ($Qb(relatedInformation)) {
      const relatedInformationNode = this.f.appendChild(document.createElement("div"));
      relatedInformationNode.style.paddingTop = `${Math.floor(this.c.getOption(
        68
        /* EditorOption.lineHeight */
      ) * 0.66)}px`;
      this.a += 1;
      for (const related of relatedInformation) {
        const container2 = document.createElement("div");
        const relatedResource = document.createElement("a");
        relatedResource.classList.add("filename");
        relatedResource.innerText = `${this.l.getUriBasenameLabel(related.resource)}(${related.startLineNumber}, ${related.startColumn}): `;
        relatedResource.title = this.l.getUriLabel(related.resource);
        this.h.set(relatedResource, related);
        const relatedMessage = document.createElement("span");
        relatedMessage.innerText = related.message;
        container2.appendChild(relatedResource);
        container2.appendChild(relatedMessage);
        this.a += 1;
        relatedInformationNode.appendChild(container2);
      }
    }
    const fontInfo = this.c.getOption(
      52
      /* EditorOption.fontInfo */
    );
    const scrollWidth = Math.ceil(fontInfo.typicalFullwidthCharacterWidth * this.b * 0.75);
    const scrollHeight = fontInfo.lineHeight * this.a;
    this.g.setScrollDimensions({ scrollWidth, scrollHeight });
  }
  layout(height, width2) {
    this.g.getDomNode().style.height = `${height}px`;
    this.g.getDomNode().style.width = `${width2}px`;
    this.g.setScrollDimensions({ width: width2, height });
  }
  getHeightInLines() {
    return Math.min(17, this.a);
  }
  m(marker) {
    let severityLabel = "";
    switch (marker.severity) {
      case MarkerSeverity.Error:
        severityLabel = localize(1100, null);
        break;
      case MarkerSeverity.Warning:
        severityLabel = localize(1101, null);
        break;
      case MarkerSeverity.Info:
        severityLabel = localize(1102, null);
        break;
      case MarkerSeverity.Hint:
        severityLabel = localize(1103, null);
        break;
    }
    let ariaLabel = localize(1104, null, severityLabel, marker.startLineNumber + ":" + marker.startColumn);
    const model = this.c.getModel();
    if (model && marker.startLineNumber <= model.getLineCount() && marker.startLineNumber >= 1) {
      const lineContent = model.getLineContent(marker.startLineNumber);
      ariaLabel = `${lineContent}, ${ariaLabel}`;
    }
    return ariaLabel;
  }
};
var $mib = class $mib2 extends $ceb {
  static {
    $mib_1 = this;
  }
  static {
    this.TitleMenu = new $bJ("gotoErrorTitleMenu");
  }
  constructor(editor, db, eb, fb, instantiationService, gb, hb) {
    super(editor, { showArrow: true, showFrame: true, isAccessible: true, frameWidth: 1 }, instantiationService);
    this.db = db;
    this.eb = eb;
    this.fb = fb;
    this.gb = gb;
    this.hb = hb;
    this.i = new $2c();
    this.bb = new $ze();
    this.onDidSelectRelatedInformation = this.bb.event;
    this.m = MarkerSeverity.Warning;
    this.r = $Vn.white;
    this.ib(db.getColorTheme());
    this.i.add(db.onDidColorThemeChange(this.ib.bind(this)));
    this.create();
  }
  ib(theme) {
    this.r = theme.getColor(editorMarkerNavigationBackground);
    let colorId = editorMarkerNavigationError;
    let headerBackground = editorMarkerNavigationErrorHeader;
    if (this.m === MarkerSeverity.Warning) {
      colorId = editorMarkerNavigationWarning;
      headerBackground = editorMarkerNavigationWarningHeader;
    } else if (this.m === MarkerSeverity.Info) {
      colorId = editorMarkerNavigationInfo;
      headerBackground = editorMarkerNavigationInfoHeader;
    }
    const frameColor = theme.getColor(colorId);
    const headerBg = theme.getColor(headerBackground);
    this.style({
      arrowColor: frameColor,
      frameColor,
      headerBackgroundColor: headerBg,
      primaryHeadingColor: theme.getColor($eeb),
      secondaryHeadingColor: theme.getColor($feb)
    });
  }
  o() {
    if (this.a) {
      this.a.style.backgroundColor = this.r ? this.r.toString() : "";
    }
    super.o();
  }
  dispose() {
    this.i.dispose();
    super.dispose();
  }
  focus() {
    this.a.focus();
  }
  T(container2) {
    super.T(container2);
    this.n.add(this.O.actionRunner.onWillRun((e) => this.editor.focus()));
    const menu = this.fb.getMenuActions($mib_1.TitleMenu, this.gb);
    const actions = $R$(menu);
    this.O.push(actions, { label: false, icon: true, index: 0 });
  }
  U(container2) {
    this.c = $bk(container2, $(""));
  }
  X(container2) {
    this.a = container2;
    container2.classList.add("marker-widget");
    this.a.tabIndex = 0;
    this.a.setAttribute("role", "tooltip");
    this.b = document.createElement("div");
    container2.appendChild(this.b);
    this.d = new MessageWidget2(this.b, this.editor, (related) => this.bb.fire(related), this.eb, this.hb);
    this.n.add(this.d);
  }
  show() {
    throw new Error("call showAtMarker");
  }
  showAtMarker(marker, markerIdx, markerCount) {
    this.b.classList.remove("stale");
    this.d.update(marker);
    this.m = marker.severity;
    this.ib(this.db.getColorTheme());
    const range = $9C.lift(marker);
    const editorPosition = this.editor.getPosition();
    const position = editorPosition && range.containsPosition(editorPosition) ? editorPosition : range.getStartPosition();
    super.show(position, this.qb());
    const model = this.editor.getModel();
    if (model) {
      const detail2 = markerCount > 1 ? localize(1105, null, markerIdx, markerCount) : localize(1106, null, markerIdx, markerCount);
      this.setTitle($sh(model.uri), detail2);
    }
    this.c.className = `codicon ${SeverityIcon.className(MarkerSeverity.toSeverity(this.m))}`;
    this.editor.revealPositionNearTop(
      position,
      0
      /* ScrollType.Smooth */
    );
    this.editor.focus();
  }
  updateMarker(marker) {
    this.b.classList.remove("stale");
    this.d.update(marker);
  }
  showStale() {
    this.b.classList.add("stale");
    this.E();
  }
  ab(heightInPixel, widthInPixel) {
    super.ab(heightInPixel, widthInPixel);
    this.cb = heightInPixel;
    this.d.layout(heightInPixel, widthInPixel);
    this.b.style.height = `${heightInPixel}px`;
  }
  C(widthInPixel) {
    this.d.layout(this.cb, widthInPixel);
  }
  E() {
    super.E(this.qb());
  }
  qb() {
    return 3 + this.d.getHeightInLines();
  }
};
$mib = $mib_1 = __decorate([
  __param(1, $gs),
  __param(2, $O4),
  __param(3, $cJ),
  __param(4, $Pk),
  __param(5, $on),
  __param(6, $ZI)
], $mib);
var errorDefault = $_n($Vo, $Wo);
var warningDefault = $_n($Yo, $Zo);
var infoDefault = $_n($2o, $3o);
var editorMarkerNavigationError = $5n("editorMarkerNavigationError.background", { dark: errorDefault, light: errorDefault, hcDark: $ko, hcLight: $ko }, localize(1107, null));
var editorMarkerNavigationErrorHeader = $5n("editorMarkerNavigationError.headerBackground", { dark: $0n(editorMarkerNavigationError, 0.1), light: $0n(editorMarkerNavigationError, 0.1), hcDark: null, hcLight: null }, localize(1108, null));
var editorMarkerNavigationWarning = $5n("editorMarkerNavigationWarning.background", { dark: warningDefault, light: warningDefault, hcDark: $ko, hcLight: $ko }, localize(1109, null));
var editorMarkerNavigationWarningHeader = $5n("editorMarkerNavigationWarning.headerBackground", { dark: $0n(editorMarkerNavigationWarning, 0.1), light: $0n(editorMarkerNavigationWarning, 0.1), hcDark: "#0C141F", hcLight: $0n(editorMarkerNavigationWarning, 0.2) }, localize(1110, null));
var editorMarkerNavigationInfo = $5n("editorMarkerNavigationInfo.background", { dark: infoDefault, light: infoDefault, hcDark: $ko, hcLight: $ko }, localize(1111, null));
var editorMarkerNavigationInfoHeader = $5n("editorMarkerNavigationInfo.headerBackground", { dark: $0n(editorMarkerNavigationInfo, 0.1), light: $0n(editorMarkerNavigationInfo, 0.1), hcDark: null, hcLight: null }, localize(1112, null));
var editorMarkerNavigationBackground = $5n("editorMarkerNavigation.background", $Ko, localize(1113, null));

// out-build/vs/editor/contrib/gotoError/browser/gotoError.js
var $nib_1;
var $nib = class $nib2 {
  static {
    $nib_1 = this;
  }
  static {
    this.ID = "editor.contrib.markerController";
  }
  static get(editor) {
    return editor.getContribution($nib_1.ID);
  }
  constructor(editor, g, h3, i2, j) {
    this.g = g;
    this.h = h3;
    this.i = i2;
    this.j = j;
    this.c = new $2c();
    this.a = editor;
    this.b = CONTEXT_MARKERS_NAVIGATION_VISIBLE.bindTo(this.h);
  }
  dispose() {
    this.k();
    this.c.dispose();
  }
  k() {
    this.b.reset();
    this.c.clear();
    this.f = void 0;
    this.d = void 0;
  }
  l(uri) {
    if (this.d && this.d.matches(uri)) {
      return this.d;
    }
    let reusePosition = false;
    if (this.d) {
      reusePosition = true;
      this.k();
    }
    this.d = this.g.getMarkerList(uri);
    if (reusePosition) {
      this.d.move(true, this.a.getModel(), this.a.getPosition());
    }
    this.f = this.j.createInstance($mib, this.a);
    this.f.onDidClose(() => this.close(), this, this.c);
    this.b.set(true);
    this.c.add(this.d);
    this.c.add(this.f);
    this.c.add(this.a.onDidChangeCursorPosition((e) => {
      if (!this.d?.selected || !$9C.containsPosition(this.d?.selected.marker, e.position)) {
        this.d?.resetIndex();
      }
    }));
    this.c.add(this.d.onDidChange(() => {
      if (!this.f || !this.f.position || !this.d) {
        return;
      }
      const info = this.d.find(this.a.getModel().uri, this.f.position);
      if (info) {
        this.f.updateMarker(info.marker);
      } else {
        this.f.showStale();
      }
    }));
    this.c.add(this.f.onDidSelectRelatedInformation((related) => {
      this.i.openCodeEditor({
        resource: related.resource,
        options: { pinned: true, revealIfOpened: true, selection: $9C.lift(related).collapseToStart() }
      }, this.a);
      this.close(false);
    }));
    this.c.add(this.a.onDidChangeModel(() => this.k()));
    return this.d;
  }
  close(focusEditor = true) {
    this.k();
    if (focusEditor) {
      this.a.focus();
    }
  }
  showAtMarker(marker) {
    if (this.a.hasModel()) {
      const model = this.l(this.a.getModel().uri);
      model.resetIndex();
      model.move(true, this.a.getModel(), new $8C(marker.startLineNumber, marker.startColumn));
      if (model.selected) {
        this.f.showAtMarker(model.selected.marker, model.selected.index, model.selected.total);
      }
    }
  }
  async nagivate(next, multiFile) {
    if (this.a.hasModel()) {
      const model = this.l(multiFile ? void 0 : this.a.getModel().uri);
      model.move(next, this.a.getModel(), this.a.getPosition());
      if (!model.selected) {
        return;
      }
      if (model.selected.marker.resource.toString() !== this.a.getModel().uri.toString()) {
        this.k();
        const otherEditor = await this.i.openCodeEditor({
          resource: model.selected.marker.resource,
          options: { pinned: false, revealIfOpened: true, selectionRevealType: 2, selection: model.selected.marker }
        }, this.a);
        if (otherEditor) {
          $nib_1.get(otherEditor)?.close();
          $nib_1.get(otherEditor)?.nagivate(next, multiFile);
        }
      } else {
        this.f.showAtMarker(model.selected.marker, model.selected.index, model.selected.total);
      }
    }
  }
};
$nib = $nib_1 = __decorate([
  __param(1, $lib),
  __param(2, $on),
  __param(3, $U5),
  __param(4, $Pk)
], $nib);
var MarkerNavigationAction = class extends $Z5 {
  constructor(d, h3, opts) {
    super(opts);
    this.d = d;
    this.h = h3;
  }
  async run(_accessor, editor) {
    if (editor.hasModel()) {
      $nib.get(editor)?.nagivate(this.d, this.h);
    }
  }
};
var $oib = class _$oib extends MarkerNavigationAction {
  static {
    this.ID = "editor.action.marker.next";
  }
  static {
    this.LABEL = localize2(1096, "Go to Next Problem (Error, Warning, Info)");
  }
  constructor() {
    super(true, false, {
      id: _$oib.ID,
      label: _$oib.LABEL,
      precondition: void 0,
      kbOpts: {
        kbExpr: EditorContextKeys.focus,
        primary: 512 | 66,
        weight: 100
        /* KeybindingWeight.EditorContrib */
      },
      menuOpts: {
        menuId: $mib.TitleMenu,
        title: _$oib.LABEL.value,
        icon: $9r("marker-navigation-next", $6l.arrowDown, localize(1092, null)),
        group: "navigation",
        order: 1
      }
    });
  }
};
var PrevMarkerAction = class _PrevMarkerAction extends MarkerNavigationAction {
  static {
    this.ID = "editor.action.marker.prev";
  }
  static {
    this.LABEL = localize2(1097, "Go to Previous Problem (Error, Warning, Info)");
  }
  constructor() {
    super(false, false, {
      id: _PrevMarkerAction.ID,
      label: _PrevMarkerAction.LABEL,
      precondition: void 0,
      kbOpts: {
        kbExpr: EditorContextKeys.focus,
        primary: 1024 | 512 | 66,
        weight: 100
        /* KeybindingWeight.EditorContrib */
      },
      menuOpts: {
        menuId: $mib.TitleMenu,
        title: _PrevMarkerAction.LABEL.value,
        icon: $9r("marker-navigation-previous", $6l.arrowUp, localize(1093, null)),
        group: "navigation",
        order: 2
      }
    });
  }
};
var NextMarkerInFilesAction = class extends MarkerNavigationAction {
  constructor() {
    super(true, true, {
      id: "editor.action.marker.nextInFiles",
      label: localize2(1098, "Go to Next Problem in Files (Error, Warning, Info)"),
      precondition: void 0,
      kbOpts: {
        kbExpr: EditorContextKeys.focus,
        primary: 66,
        weight: 100
        /* KeybindingWeight.EditorContrib */
      },
      menuOpts: {
        menuId: $bJ.MenubarGoMenu,
        title: localize(1094, null),
        group: "6_problem_nav",
        order: 1
      }
    });
  }
};
var PrevMarkerInFilesAction = class extends MarkerNavigationAction {
  constructor() {
    super(false, true, {
      id: "editor.action.marker.prevInFiles",
      label: localize2(1099, "Go to Previous Problem in Files (Error, Warning, Info)"),
      precondition: void 0,
      kbOpts: {
        kbExpr: EditorContextKeys.focus,
        primary: 1024 | 66,
        weight: 100
        /* KeybindingWeight.EditorContrib */
      },
      menuOpts: {
        menuId: $bJ.MenubarGoMenu,
        title: localize(1095, null),
        group: "6_problem_nav",
        order: 2
      }
    });
  }
};
$85(
  $nib.ID,
  $nib,
  4
  /* EditorContributionInstantiation.Lazy */
);
$55($oib);
$55(PrevMarkerAction);
$55(NextMarkerInFilesAction);
$55(PrevMarkerInFilesAction);
var CONTEXT_MARKERS_NAVIGATION_VISIBLE = new $nn("markersNavigationVisible", false);
var MarkerCommand = $Y5.bindToContribution($nib.get);
$45(new MarkerCommand({
  id: "closeMarkersNavigation",
  precondition: CONTEXT_MARKERS_NAVIGATION_VISIBLE,
  handler: (x) => x.close(),
  kbOpts: {
    weight: 100 + 50,
    kbExpr: EditorContextKeys.focus,
    primary: 9,
    secondary: [
      1024 | 9
      /* KeyCode.Escape */
    ]
  }
}));

// out-build/vs/editor/contrib/gpu/browser/gpuActions.js
var DebugEditorGpuRendererAction = class extends $Z5 {
  constructor() {
    super({
      id: "editor.action.debugEditorGpuRenderer",
      label: localize2(1177, "Developer: Debug Editor GPU Renderer"),
      // TODO: Why doesn't `ContextKeyExpr.equals('config:editor.experimentalGpuAcceleration', 'on')` work?
      precondition: $7m.true()
    });
  }
  async run(accessor, editor) {
    const instantiationService = accessor.get($Pk);
    const quickInputService = accessor.get($1M);
    const choice = await quickInputService.pick([
      {
        label: localize(1174, null),
        id: "logTextureAtlasStats"
      },
      {
        label: localize(1175, null),
        id: "saveTextureAtlas"
      },
      {
        label: localize(1176, null),
        id: "drawGlyph"
      }
    ], { canPickMany: false });
    if (!choice) {
      return;
    }
    switch (choice.id) {
      case "logTextureAtlasStats":
        instantiationService.invokeFunction((accessor2) => {
          const logService = accessor2.get($wn);
          const atlas = $O7.atlas;
          if (!$O7.atlas) {
            logService.error("No texture atlas found");
            return;
          }
          const stats = atlas.getStats();
          logService.info(["Texture atlas stats", ...stats].join("\n\n"));
        });
        break;
      case "saveTextureAtlas":
        instantiationService.invokeFunction(async (accessor2) => {
          const workspaceContextService = accessor2.get($Zk);
          const fileService = accessor2.get($km);
          const folders = workspaceContextService.getWorkspace().folders;
          if (folders.length > 0) {
            const atlas = $O7.atlas;
            const promises = [];
            for (const [layerIndex, page] of atlas.pages.entries()) {
              promises.push(...[
                fileService.writeFile(URI.joinPath(folders[0].uri, `textureAtlasPage${layerIndex}_actual.png`), $Ci.wrap(new Uint8Array(await (await page.source.convertToBlob()).arrayBuffer()))),
                fileService.writeFile(URI.joinPath(folders[0].uri, `textureAtlasPage${layerIndex}_usage.png`), $Ci.wrap(new Uint8Array(await (await page.getUsagePreview()).arrayBuffer())))
              ]);
            }
            await Promise.all(promises);
          }
        });
        break;
      case "drawGlyph":
        instantiationService.invokeFunction(async (accessor2) => {
          const configurationService = accessor2.get($kl);
          const fileService = accessor2.get($km);
          const quickInputService2 = accessor2.get($1M);
          const workspaceContextService = accessor2.get($Zk);
          const folders = workspaceContextService.getWorkspace().folders;
          if (folders.length === 0) {
            return;
          }
          const atlas = $O7.atlas;
          const fontFamily = configurationService.getValue("editor.fontFamily");
          const fontSize = configurationService.getValue("editor.fontSize");
          const rasterizer = new $B7(fontSize, fontFamily, $Qj().devicePixelRatio);
          let chars = await quickInputService2.input({
            prompt: "Enter a character to draw (prefix with 0x for code point))"
          });
          if (!chars) {
            return;
          }
          const codePoint = chars.match(/0x(?<codePoint>[0-9a-f]+)/i)?.groups?.codePoint;
          if (codePoint !== void 0) {
            chars = String.fromCodePoint(parseInt(codePoint, 16));
          }
          const tokenMetadata = 0;
          const charMetadata = 0;
          const rasterizedGlyph = atlas.getGlyph(rasterizer, chars, tokenMetadata, charMetadata);
          if (!rasterizedGlyph) {
            return;
          }
          const imageData = atlas.pages[rasterizedGlyph.pageIndex].source.getContext("2d")?.getImageData(rasterizedGlyph.x, rasterizedGlyph.y, rasterizedGlyph.w, rasterizedGlyph.h);
          if (!imageData) {
            return;
          }
          const canvas = new OffscreenCanvas(imageData.width, imageData.height);
          const ctx = $z7(canvas.getContext("2d"));
          ctx.putImageData(imageData, 0, 0);
          const blob = await canvas.convertToBlob({ type: "image/png" });
          const resource = URI.joinPath(folders[0].uri, `glyph_${chars}_${tokenMetadata}_${fontSize}px_${fontFamily.replaceAll(/[,\\\/\.'\s]/g, "_")}.png`);
          await fileService.writeFile(resource, $Ci.wrap(new Uint8Array(await blob.arrayBuffer())));
        });
        break;
    }
  }
};
$55(DebugEditorGpuRendererAction);

// out-build/vs/editor/contrib/hover/browser/hoverActions.js
var HoverFocusBehavior;
(function(HoverFocusBehavior2) {
  HoverFocusBehavior2["NoAutoFocus"] = "noAutoFocus";
  HoverFocusBehavior2["FocusIfVisible"] = "focusIfVisible";
  HoverFocusBehavior2["AutoFocusImmediately"] = "autoFocusImmediately";
})(HoverFocusBehavior || (HoverFocusBehavior = {}));
var $pib = class extends $Z5 {
  constructor() {
    super({
      id: $Nbb,
      label: localize2(1188, "Show or Focus Hover"),
      metadata: {
        description: localize2(1189, "Show or focus the editor hover which shows documentation, references, and other content for a symbol at the current cursor position."),
        args: [{
          name: "args",
          schema: {
            type: "object",
            properties: {
              "focus": {
                description: "Controls if and when the hover should take focus upon being triggered by this action.",
                enum: [HoverFocusBehavior.NoAutoFocus, HoverFocusBehavior.FocusIfVisible, HoverFocusBehavior.AutoFocusImmediately],
                enumDescriptions: [
                  localize(1185, null),
                  localize(1186, null),
                  localize(1187, null)
                ],
                default: HoverFocusBehavior.FocusIfVisible
              }
            }
          }
        }]
      },
      precondition: void 0,
      kbOpts: {
        kbExpr: EditorContextKeys.editorTextFocus,
        primary: $$e(
          2048 | 41,
          2048 | 39
          /* KeyCode.KeyI */
        ),
        weight: 100
        /* KeybindingWeight.EditorContrib */
      }
    });
  }
  run(accessor, editor, args2) {
    if (!editor.hasModel()) {
      return;
    }
    const controller = $Afb.get(editor);
    if (!controller) {
      return;
    }
    const focusArgument = args2?.focus;
    let focusOption = HoverFocusBehavior.FocusIfVisible;
    if (Object.values(HoverFocusBehavior).includes(focusArgument)) {
      focusOption = focusArgument;
    } else if (typeof focusArgument === "boolean" && focusArgument) {
      focusOption = HoverFocusBehavior.AutoFocusImmediately;
    }
    const showContentHover = (focus) => {
      const position = editor.getPosition();
      const range = new $9C(position.lineNumber, position.column, position.lineNumber, position.column);
      controller.showContentHover(range, 1, 2, focus);
    };
    const accessibilitySupportEnabled = editor.getOption(
      2
      /* EditorOption.accessibilitySupport */
    ) === 2;
    if (controller.isHoverVisible) {
      if (focusOption !== HoverFocusBehavior.NoAutoFocus) {
        controller.focus();
      } else {
        showContentHover(accessibilitySupportEnabled);
      }
    } else {
      showContentHover(accessibilitySupportEnabled || focusOption === HoverFocusBehavior.AutoFocusImmediately);
    }
  }
};
var $qib = class extends $Z5 {
  constructor() {
    super({
      id: $Obb,
      label: localize2(1190, "Show Definition Preview Hover"),
      precondition: void 0,
      metadata: {
        description: localize2(1191, "Show the definition preview hover in the editor.")
      }
    });
  }
  run(accessor, editor) {
    const controller = $Afb.get(editor);
    if (!controller) {
      return;
    }
    const position = editor.getPosition();
    if (!position) {
      return;
    }
    const range = new $9C(position.lineNumber, position.column, position.lineNumber, position.column);
    const goto = $iib.get(editor);
    if (!goto) {
      return;
    }
    const promise = goto.startFindDefinitionFromCursor(position);
    promise.then(() => {
      controller.showContentHover(range, 1, 2, true);
    });
  }
};
var $rib = class extends $Z5 {
  constructor() {
    super({
      id: $Pbb,
      label: localize2(1192, "Scroll Up Hover"),
      precondition: EditorContextKeys.hoverFocused,
      kbOpts: {
        kbExpr: EditorContextKeys.hoverFocused,
        primary: 16,
        weight: 100
        /* KeybindingWeight.EditorContrib */
      },
      metadata: {
        description: localize2(1193, "Scroll up the editor hover.")
      }
    });
  }
  run(accessor, editor) {
    const controller = $Afb.get(editor);
    if (!controller) {
      return;
    }
    controller.scrollUp();
  }
};
var $sib = class extends $Z5 {
  constructor() {
    super({
      id: $Qbb,
      label: localize2(1194, "Scroll Down Hover"),
      precondition: EditorContextKeys.hoverFocused,
      kbOpts: {
        kbExpr: EditorContextKeys.hoverFocused,
        primary: 18,
        weight: 100
        /* KeybindingWeight.EditorContrib */
      },
      metadata: {
        description: localize2(1195, "Scroll down the editor hover.")
      }
    });
  }
  run(accessor, editor) {
    const controller = $Afb.get(editor);
    if (!controller) {
      return;
    }
    controller.scrollDown();
  }
};
var $tib = class extends $Z5 {
  constructor() {
    super({
      id: $Rbb,
      label: localize2(1196, "Scroll Left Hover"),
      precondition: EditorContextKeys.hoverFocused,
      kbOpts: {
        kbExpr: EditorContextKeys.hoverFocused,
        primary: 15,
        weight: 100
        /* KeybindingWeight.EditorContrib */
      },
      metadata: {
        description: localize2(1197, "Scroll left the editor hover.")
      }
    });
  }
  run(accessor, editor) {
    const controller = $Afb.get(editor);
    if (!controller) {
      return;
    }
    controller.scrollLeft();
  }
};
var $uib = class extends $Z5 {
  constructor() {
    super({
      id: $Sbb,
      label: localize2(1198, "Scroll Right Hover"),
      precondition: EditorContextKeys.hoverFocused,
      kbOpts: {
        kbExpr: EditorContextKeys.hoverFocused,
        primary: 17,
        weight: 100
        /* KeybindingWeight.EditorContrib */
      },
      metadata: {
        description: localize2(1199, "Scroll right the editor hover.")
      }
    });
  }
  run(accessor, editor) {
    const controller = $Afb.get(editor);
    if (!controller) {
      return;
    }
    controller.scrollRight();
  }
};
var $vib = class extends $Z5 {
  constructor() {
    super({
      id: $Tbb,
      label: localize2(1200, "Page Up Hover"),
      precondition: EditorContextKeys.hoverFocused,
      kbOpts: {
        kbExpr: EditorContextKeys.hoverFocused,
        primary: 11,
        secondary: [
          512 | 16
          /* KeyCode.UpArrow */
        ],
        weight: 100
        /* KeybindingWeight.EditorContrib */
      },
      metadata: {
        description: localize2(1201, "Page up the editor hover.")
      }
    });
  }
  run(accessor, editor) {
    const controller = $Afb.get(editor);
    if (!controller) {
      return;
    }
    controller.pageUp();
  }
};
var $wib = class extends $Z5 {
  constructor() {
    super({
      id: $Ubb,
      label: localize2(1202, "Page Down Hover"),
      precondition: EditorContextKeys.hoverFocused,
      kbOpts: {
        kbExpr: EditorContextKeys.hoverFocused,
        primary: 12,
        secondary: [
          512 | 18
          /* KeyCode.DownArrow */
        ],
        weight: 100
        /* KeybindingWeight.EditorContrib */
      },
      metadata: {
        description: localize2(1203, "Page down the editor hover.")
      }
    });
  }
  run(accessor, editor) {
    const controller = $Afb.get(editor);
    if (!controller) {
      return;
    }
    controller.pageDown();
  }
};
var $xib = class extends $Z5 {
  constructor() {
    super({
      id: $Vbb,
      label: localize2(1204, "Go To Top Hover"),
      precondition: EditorContextKeys.hoverFocused,
      kbOpts: {
        kbExpr: EditorContextKeys.hoverFocused,
        primary: 14,
        secondary: [
          2048 | 16
          /* KeyCode.UpArrow */
        ],
        weight: 100
        /* KeybindingWeight.EditorContrib */
      },
      metadata: {
        description: localize2(1205, "Go to the top of the editor hover.")
      }
    });
  }
  run(accessor, editor) {
    const controller = $Afb.get(editor);
    if (!controller) {
      return;
    }
    controller.goToTop();
  }
};
var $yib = class extends $Z5 {
  constructor() {
    super({
      id: $Wbb,
      label: localize2(1206, "Go To Bottom Hover"),
      precondition: EditorContextKeys.hoverFocused,
      kbOpts: {
        kbExpr: EditorContextKeys.hoverFocused,
        primary: 13,
        secondary: [
          2048 | 18
          /* KeyCode.DownArrow */
        ],
        weight: 100
        /* KeybindingWeight.EditorContrib */
      },
      metadata: {
        description: localize2(1207, "Go to the bottom of the editor hover.")
      }
    });
  }
  run(accessor, editor) {
    const controller = $Afb.get(editor);
    if (!controller) {
      return;
    }
    controller.goToBottom();
  }
};
var $zib = class extends $Z5 {
  constructor() {
    super({
      id: $Xbb,
      label: $Zbb,
      alias: "Increase Hover Verbosity Level",
      precondition: EditorContextKeys.hoverVisible
    });
  }
  run(accessor, editor, args2) {
    const hoverController = $Afb.get(editor);
    if (!hoverController) {
      return;
    }
    const index = args2?.index !== void 0 ? args2.index : hoverController.focusedHoverPartIndex();
    hoverController.updateHoverVerbosityLevel(HoverVerbosityAction.Increase, index, args2?.focus);
  }
};
var $Aib = class extends $Z5 {
  constructor() {
    super({
      id: $1bb,
      label: $3bb,
      alias: "Decrease Hover Verbosity Level",
      precondition: EditorContextKeys.hoverVisible
    });
  }
  run(accessor, editor, args2) {
    const hoverController = $Afb.get(editor);
    if (!hoverController) {
      return;
    }
    const index = args2?.index !== void 0 ? args2.index : hoverController.focusedHoverPartIndex();
    $Afb.get(editor)?.updateHoverVerbosityLevel(HoverVerbosityAction.Decrease, index, args2?.focus);
  }
};

// out-build/vs/editor/contrib/hover/browser/markerHoverParticipant.js
var $53 = $;
var $Bib = class {
  constructor(owner, range, marker) {
    this.owner = owner;
    this.range = range;
    this.marker = marker;
  }
  isValidForHoverAnchor(anchor) {
    return anchor.type === 1 && this.range.startColumn <= anchor.range.startColumn && this.range.endColumn >= anchor.range.endColumn;
  }
};
var markerCodeActionTrigger = {
  type: 1,
  filter: { include: $pab.QuickFix },
  triggerAction: CodeActionTriggerSource.QuickFixHover
};
var $Cib = class $Cib2 {
  constructor(f, g, h3, i2) {
    this.f = f;
    this.g = g;
    this.h = h3;
    this.i = i2;
    this.hoverOrdinal = 1;
    this.c = void 0;
  }
  computeSync(anchor, lineDecorations) {
    if (!this.f.hasModel() || anchor.type !== 1 && !anchor.supportsMarkerHover) {
      return [];
    }
    const model = this.f.getModel();
    const lineNumber = anchor.range.startLineNumber;
    const maxColumn = model.getLineMaxColumn(lineNumber);
    const result = [];
    for (const d of lineDecorations) {
      const startColumn = d.range.startLineNumber === lineNumber ? d.range.startColumn : 1;
      const endColumn = d.range.endLineNumber === lineNumber ? d.range.endColumn : maxColumn;
      const marker = this.g.getMarker(model.uri, d);
      if (!marker) {
        continue;
      }
      const range = new $9C(anchor.range.startLineNumber, startColumn, anchor.range.startLineNumber, endColumn);
      result.push(new $Bib(this, range, marker));
    }
    return result;
  }
  renderHoverParts(context, hoverParts) {
    if (!hoverParts.length) {
      return new $Abb([]);
    }
    const disposables = new $2c();
    const renderedHoverParts = [];
    hoverParts.forEach((hoverPart) => {
      const renderedMarkerHover = this.j(hoverPart);
      context.fragment.appendChild(renderedMarkerHover.hoverElement);
      renderedHoverParts.push(renderedMarkerHover);
    });
    const markerHoverForStatusbar = hoverParts.length === 1 ? hoverParts[0] : hoverParts.sort((a, b) => MarkerSeverity.compare(a.marker.severity, b.marker.severity))[0];
    this.k(context, markerHoverForStatusbar, disposables);
    return new $Abb(renderedHoverParts);
  }
  getAccessibleContent(hoverPart) {
    return hoverPart.marker.message;
  }
  j(markerHover) {
    const disposables = new $2c();
    const hoverElement = $53("div.hover-row");
    const markerElement = $bk(hoverElement, $53("div.marker.hover-contents"));
    const { source, message, code, relatedInformation } = markerHover.marker;
    this.f.applyFontInfo(markerElement);
    const messageElement = $bk(markerElement, $53("span"));
    messageElement.style.whiteSpace = "pre-wrap";
    messageElement.innerText = message;
    if (source || code) {
      if (code && typeof code !== "string") {
        const sourceAndCodeElement = $53("span");
        if (source) {
          const sourceElement = $bk(sourceAndCodeElement, $53("span"));
          sourceElement.innerText = source;
        }
        const codeLink = $bk(sourceAndCodeElement, $53("a.code-link"));
        codeLink.setAttribute("href", code.target.toString(true));
        disposables.add($_i(codeLink, "click", (e) => {
          this.h.open(code.target, { allowCommands: true });
          e.preventDefault();
          e.stopPropagation();
        }));
        const codeElement = $bk(codeLink, $53("span"));
        codeElement.innerText = code.value;
        const detailsElement = $bk(markerElement, sourceAndCodeElement);
        detailsElement.style.opacity = "0.6";
        detailsElement.style.paddingLeft = "6px";
      } else {
        const detailsElement = $bk(markerElement, $53("span"));
        detailsElement.style.opacity = "0.6";
        detailsElement.style.paddingLeft = "6px";
        detailsElement.innerText = source && code ? `${source}(${code})` : source ? source : `(${code})`;
      }
    }
    if ($Qb(relatedInformation)) {
      for (const { message: message2, resource, startLineNumber, startColumn } of relatedInformation) {
        const relatedInfoContainer = $bk(markerElement, $53("div"));
        relatedInfoContainer.style.marginTop = "8px";
        const a = $bk(relatedInfoContainer, $53("a"));
        a.innerText = `${$sh(resource)}(${startLineNumber}, ${startColumn}): `;
        a.style.cursor = "pointer";
        disposables.add($_i(a, "click", (e) => {
          e.stopPropagation();
          e.preventDefault();
          if (this.h) {
            const editorOptions2 = { selection: { startLineNumber, startColumn } };
            this.h.open(resource, {
              fromUserGesture: true,
              editorOptions: editorOptions2
            }).catch($gb);
          }
        }));
        const messageElement2 = $bk(relatedInfoContainer, $53("span"));
        messageElement2.innerText = message2;
        this.f.applyFontInfo(messageElement2);
      }
    }
    const renderedHoverPart = {
      hoverPart: markerHover,
      hoverElement,
      dispose: () => disposables.dispose()
    };
    return renderedHoverPart;
  }
  k(context, markerHover, disposables) {
    if (markerHover.marker.severity === MarkerSeverity.Error || markerHover.marker.severity === MarkerSeverity.Warning || markerHover.marker.severity === MarkerSeverity.Info) {
      const markerController = $nib.get(this.f);
      if (markerController) {
        context.statusBar.addAction({
          label: localize(1217, null),
          commandId: $oib.ID,
          run: () => {
            context.hide();
            markerController.showAtMarker(markerHover.marker);
            this.f.focus();
          }
        });
      }
    }
    if (!this.f.getOption(
      96
      /* EditorOption.readOnly */
    )) {
      const quickfixPlaceholderElement = context.statusBar.append($53("div"));
      if (this.c) {
        if (IMarkerData.makeKey(this.c.marker) === IMarkerData.makeKey(markerHover.marker)) {
          if (!this.c.hasCodeActions) {
            quickfixPlaceholderElement.textContent = localize(1218, null);
          }
        } else {
          this.c = void 0;
        }
      }
      const updatePlaceholderDisposable = this.c && !this.c.hasCodeActions ? $3c.None : $Xh(() => quickfixPlaceholderElement.textContent = localize(1219, null), 200, disposables);
      if (!quickfixPlaceholderElement.textContent) {
        quickfixPlaceholderElement.textContent = String.fromCharCode(160);
      }
      const codeActionsPromise = this.l(markerHover.marker);
      disposables.add($1c(() => codeActionsPromise.cancel()));
      codeActionsPromise.then((actions) => {
        updatePlaceholderDisposable.dispose();
        this.c = { marker: markerHover.marker, hasCodeActions: actions.validActions.length > 0 };
        if (!this.c.hasCodeActions) {
          actions.dispose();
          quickfixPlaceholderElement.textContent = localize(1220, null);
          return;
        }
        quickfixPlaceholderElement.style.display = "none";
        let showing = false;
        disposables.add($1c(() => {
          if (!showing) {
            actions.dispose();
          }
        }));
        context.statusBar.addAction({
          label: localize(1221, null),
          commandId: $vab,
          run: (target) => {
            showing = true;
            const controller = $fbb.get(this.f);
            const elementPosition = $vj(target);
            context.hide();
            controller?.showCodeActions(markerCodeActionTrigger, actions, {
              x: elementPosition.left,
              y: elementPosition.top,
              width: elementPosition.width,
              height: elementPosition.height
            });
          }
        });
        const aiCodeAction = actions.validActions.find((action) => action.action.isAI);
        if (aiCodeAction) {
          context.statusBar.addAction({
            label: aiCodeAction.action.title,
            commandId: aiCodeAction.action.command?.id ?? "",
            run: () => {
              const controller = $fbb.get(this.f);
              controller?.applyCodeAction(aiCodeAction, false, false, ApplyCodeActionReason.FromProblemsHover);
            }
          });
        }
      }, $gb);
    }
  }
  l(marker) {
    return $Hh((cancellationToken) => {
      return $Cab(this.i.codeActionProvider, this.f.getModel(), new $9C(marker.startLineNumber, marker.startColumn, marker.endLineNumber, marker.endColumn), markerCodeActionTrigger, $VJ.None, cancellationToken);
    });
  }
};
$Cib = __decorate([
  __param(1, $V6),
  __param(2, $O4),
  __param(3, $mP)
], $Cib);

// out-build/vs/editor/contrib/hover/browser/glyphHoverComputer.js
var $Dib = class {
  constructor(a) {
    this.a = a;
  }
  computeSync(opts) {
    const toHoverMessage = (contents) => {
      return {
        value: contents
      };
    };
    const lineDecorations = this.a.getLineDecorations(opts.lineNumber);
    const result = [];
    const isLineHover = opts.laneOrLine === "lineNo";
    if (!lineDecorations) {
      return result;
    }
    for (const d of lineDecorations) {
      const lane = d.options.glyphMargin?.position ?? GlyphMarginLane.Center;
      if (!isLineHover && lane !== opts.laneOrLine) {
        continue;
      }
      const hoverMessage = isLineHover ? d.options.lineNumberHoverMessage : d.options.glyphMarginHoverMessage;
      if (!hoverMessage || $cm(hoverMessage)) {
        continue;
      }
      result.push(...$5b(hoverMessage).map(toHoverMessage));
    }
    return result;
  }
};

// out-build/vs/editor/contrib/hover/browser/glyphHoverWidget.js
var $Eib_1;
var $61 = $;
var $Eib = class $Eib2 extends $3c {
  static {
    $Eib_1 = this;
  }
  static {
    this.ID = "editor.contrib.modesGlyphHoverWidget";
  }
  constructor(editor, languageService, openerService) {
    super();
    this.j = this.B(new $2c());
    this.a = editor;
    this.c = false;
    this.f = [];
    this.b = this.B(new $DZ(true));
    this.b.containerDomNode.classList.toggle("hidden", !this.c);
    this.g = this.B(new $Q_({ editor: this.a }, languageService, openerService));
    this.h = this.B(new $xbb(this.a, new $Dib(this.a)));
    this.B(this.h.onResult((result) => this.t(result)));
    this.B(this.a.onDidChangeModelDecorations(() => this.r()));
    this.B(this.a.onDidChangeConfiguration((e) => {
      if (e.hasChanged(
        52
        /* EditorOption.fontInfo */
      )) {
        this.n();
      }
    }));
    this.B($aj(this.b.containerDomNode, "mouseleave", (e) => {
      this.C(e);
    }));
    this.a.addOverlayWidget(this);
  }
  dispose() {
    this.m = void 0;
    this.a.removeOverlayWidget(this);
    super.dispose();
  }
  getId() {
    return $Eib_1.ID;
  }
  getDomNode() {
    return this.b.containerDomNode;
  }
  getPosition() {
    return null;
  }
  n() {
    const codeClasses = Array.prototype.slice.call(this.b.contentsDomNode.getElementsByClassName("code"));
    codeClasses.forEach((node) => this.a.applyFontInfo(node));
  }
  r() {
    if (this.c && this.m) {
      this.h.cancel();
      this.h.start(0, this.m);
    }
  }
  showsOrWillShow(mouseEvent) {
    const target = mouseEvent.target;
    if (target.type === 2 && target.detail.glyphMarginLane) {
      this.s(target.position.lineNumber, target.detail.glyphMarginLane);
      return true;
    }
    if (target.type === 3) {
      this.s(target.position.lineNumber, "lineNo");
      return true;
    }
    return false;
  }
  s(lineNumber, laneOrLine) {
    if (this.m && this.m.lineNumber === lineNumber && this.m.laneOrLine === laneOrLine) {
      return;
    }
    this.h.cancel();
    this.hide();
    this.m = { lineNumber, laneOrLine };
    this.h.start(0, this.m);
  }
  hide() {
    this.m = void 0;
    this.h.cancel();
    if (!this.c) {
      return;
    }
    this.c = false;
    this.b.containerDomNode.classList.toggle("hidden", !this.c);
  }
  t(result) {
    this.f = result.value;
    if (this.f.length > 0) {
      this.u(result.options.lineNumber, result.options.laneOrLine, this.f);
    } else {
      this.hide();
    }
  }
  u(lineNumber, laneOrLine, messages) {
    this.j.clear();
    const fragment = document.createDocumentFragment();
    for (const msg of messages) {
      const markdownHoverElement = $61("div.hover-row.markdown-hover");
      const hoverContentsElement = $bk(markdownHoverElement, $61("div.hover-contents"));
      const renderedContents = this.j.add(this.g.render(msg.value));
      hoverContentsElement.appendChild(renderedContents.element);
      fragment.appendChild(markdownHoverElement);
    }
    this.w(fragment);
    this.z(lineNumber, laneOrLine);
  }
  w(node) {
    this.b.contentsDomNode.textContent = "";
    this.b.contentsDomNode.appendChild(node);
    this.n();
  }
  z(lineNumber, laneOrLine) {
    if (!this.c) {
      this.c = true;
      this.b.containerDomNode.classList.toggle("hidden", !this.c);
    }
    const editorLayout = this.a.getLayoutInfo();
    const topForLineNumber = this.a.getTopForLineNumber(lineNumber);
    const editorScrollTop = this.a.getScrollTop();
    const lineHeight = this.a.getOption(
      68
      /* EditorOption.lineHeight */
    );
    const nodeHeight = this.b.containerDomNode.clientHeight;
    const top2 = topForLineNumber - editorScrollTop - (nodeHeight - lineHeight) / 2;
    const left = editorLayout.glyphMarginLeft + editorLayout.glyphMarginWidth + (laneOrLine === "lineNo" ? editorLayout.lineNumbersWidth : 0);
    this.b.containerDomNode.style.left = `${left}px`;
    this.b.containerDomNode.style.top = `${Math.max(Math.round(top2), 0)}px`;
  }
  C(e) {
    const editorDomNode = this.a.getDomNode();
    const isMousePositionOutsideOfEditor = !editorDomNode || !$Adb(editorDomNode, e.x, e.y);
    if (isMousePositionOutsideOfEditor) {
      this.hide();
    }
  }
};
$Eib = $Eib_1 = __decorate([
  __param(1, $1E),
  __param(2, $O4)
], $Eib);

// out-build/vs/editor/contrib/hover/browser/glyphHoverController.js
var $Fib_1;
var _sticky3 = false;
var $Fib = class $Fib2 extends $3c {
  static {
    $Fib_1 = this;
  }
  static {
    this.ID = "editor.contrib.marginHover";
  }
  constructor(j, m) {
    super();
    this.j = j;
    this.m = m;
    this.shouldKeepOpenOnEditorMouseMoveOrLeave = false;
    this.a = new $2c();
    this.h = {
      mouseDown: false
    };
    this.f = this.B(new $8h(() => this.F(this.c), 0));
    this.n();
    this.B(this.j.onDidChangeConfiguration((e) => {
      if (e.hasChanged(
        62
        /* EditorOption.hover */
      )) {
        this.r();
        this.n();
      }
    }));
  }
  static get(editor) {
    return editor.getContribution($Fib_1.ID);
  }
  n() {
    const hoverOpts = this.j.getOption(
      62
      /* EditorOption.hover */
    );
    this.g = {
      enabled: hoverOpts.enabled,
      sticky: hoverOpts.sticky,
      hidingDelay: hoverOpts.hidingDelay
    };
    if (hoverOpts.enabled) {
      this.a.add(this.j.onMouseDown((e) => this.u(e)));
      this.a.add(this.j.onMouseUp(() => this.y()));
      this.a.add(this.j.onMouseMove((e) => this.D(e)));
      this.a.add(this.j.onKeyDown((e) => this.H(e)));
    } else {
      this.a.add(this.j.onMouseMove((e) => this.D(e)));
      this.a.add(this.j.onKeyDown((e) => this.H(e)));
    }
    this.a.add(this.j.onMouseLeave((e) => this.z(e)));
    this.a.add(this.j.onDidChangeModel(() => {
      this.s();
      this.I();
    }));
    this.a.add(this.j.onDidChangeModelContent(() => this.s()));
    this.a.add(this.j.onDidScrollChange((e) => this.t(e)));
  }
  r() {
    this.a.clear();
  }
  s() {
    this.c = void 0;
    this.f.cancel();
  }
  t(e) {
    if (e.scrollTopChanged || e.scrollLeftChanged) {
      this.I();
    }
  }
  u(mouseEvent) {
    this.h.mouseDown = true;
    const shouldNotHideCurrentHoverWidget = this.w(mouseEvent);
    if (shouldNotHideCurrentHoverWidget) {
      return;
    }
    this.I();
  }
  w(mouseEvent) {
    const glyphHoverWidgetNode = this.b?.getDomNode();
    if (glyphHoverWidgetNode) {
      return $Adb(glyphHoverWidgetNode, mouseEvent.event.posx, mouseEvent.event.posy);
    }
    return false;
  }
  y() {
    this.h.mouseDown = false;
  }
  z(mouseEvent) {
    if (this.shouldKeepOpenOnEditorMouseMoveOrLeave) {
      return;
    }
    this.s();
    const shouldNotHideCurrentHoverWidget = this.w(mouseEvent);
    if (shouldNotHideCurrentHoverWidget) {
      return;
    }
    if (_sticky3) {
      return;
    }
    this.I();
  }
  C(mouseEvent) {
    const isHoverSticky = this.g.sticky;
    const isMouseOnGlyphHoverWidget = this.w(mouseEvent);
    return isHoverSticky && isMouseOnGlyphHoverWidget;
  }
  D(mouseEvent) {
    if (this.shouldKeepOpenOnEditorMouseMoveOrLeave) {
      return;
    }
    this.c = mouseEvent;
    const shouldNotRecomputeCurrentHoverWidget = this.C(mouseEvent);
    if (shouldNotRecomputeCurrentHoverWidget) {
      this.f.cancel();
      return;
    }
    this.F(mouseEvent);
  }
  F(mouseEvent) {
    if (!mouseEvent) {
      return;
    }
    const glyphWidgetShowsOrWillShow = this.G(mouseEvent);
    if (glyphWidgetShowsOrWillShow) {
      return;
    }
    if (_sticky3) {
      return;
    }
    this.I();
  }
  G(mouseEvent) {
    const glyphWidget = this.J();
    return glyphWidget.showsOrWillShow(mouseEvent);
  }
  H(e) {
    if (!this.j.hasModel()) {
      return;
    }
    if (e.keyCode === 5 || e.keyCode === 6 || e.keyCode === 57 || e.keyCode === 4) {
      return;
    }
    this.I();
  }
  I() {
    if (_sticky3) {
      return;
    }
    this.b?.hide();
  }
  J() {
    if (!this.b) {
      this.b = this.m.createInstance($Eib, this.j);
    }
    return this.b;
  }
  hideContentHover() {
    this.I();
  }
  dispose() {
    super.dispose();
    this.r();
    this.a.dispose();
    this.b?.dispose();
  }
};
$Fib = $Fib_1 = __decorate([
  __param(1, $Pk)
], $Fib);

// out-build/vs/platform/accessibility/browser/accessibleView.js
var $shb = $Qk("accessibleViewService");
var AccessibleViewProviderId;
(function(AccessibleViewProviderId2) {
  AccessibleViewProviderId2["Terminal"] = "terminal";
  AccessibleViewProviderId2["TerminalChat"] = "terminal-chat";
  AccessibleViewProviderId2["TerminalHelp"] = "terminal-help";
  AccessibleViewProviderId2["DiffEditor"] = "diffEditor";
  AccessibleViewProviderId2["PanelChat"] = "panelChat";
  AccessibleViewProviderId2["InlineChat"] = "inlineChat";
  AccessibleViewProviderId2["QuickChat"] = "quickChat";
  AccessibleViewProviderId2["InlineCompletions"] = "inlineCompletions";
  AccessibleViewProviderId2["KeybindingsEditor"] = "keybindingsEditor";
  AccessibleViewProviderId2["Notebook"] = "notebook";
  AccessibleViewProviderId2["ReplEditor"] = "replEditor";
  AccessibleViewProviderId2["Editor"] = "editor";
  AccessibleViewProviderId2["Hover"] = "hover";
  AccessibleViewProviderId2["Notification"] = "notification";
  AccessibleViewProviderId2["EmptyEditorHint"] = "emptyEditorHint";
  AccessibleViewProviderId2["Comments"] = "comments";
  AccessibleViewProviderId2["CommentThread"] = "commentThread";
  AccessibleViewProviderId2["Repl"] = "repl";
  AccessibleViewProviderId2["ReplHelp"] = "replHelp";
  AccessibleViewProviderId2["RunAndDebug"] = "runAndDebug";
  AccessibleViewProviderId2["Walkthrough"] = "walkthrough";
})(AccessibleViewProviderId || (AccessibleViewProviderId = {}));
var AccessibleViewType;
(function(AccessibleViewType2) {
  AccessibleViewType2["Help"] = "help";
  AccessibleViewType2["View"] = "view";
})(AccessibleViewType || (AccessibleViewType = {}));
var NavigationType;
(function(NavigationType2) {
  NavigationType2["Previous"] = "previous";
  NavigationType2["Next"] = "next";
})(NavigationType || (NavigationType = {}));
var $thb = class extends $3c {
  constructor(id2, options3, provideContent, onClose, verbositySettingKey, onOpen, actions, provideNextContent, providePreviousContent, onDidChangeContent, onKeyDown, getSymbols, onDidRequestClearLastProvider) {
    super();
    this.id = id2;
    this.options = options3;
    this.provideContent = provideContent;
    this.onClose = onClose;
    this.verbositySettingKey = verbositySettingKey;
    this.onOpen = onOpen;
    this.actions = actions;
    this.provideNextContent = provideNextContent;
    this.providePreviousContent = providePreviousContent;
    this.onDidChangeContent = onDidChangeContent;
    this.onKeyDown = onKeyDown;
    this.getSymbols = getSymbols;
    this.onDidRequestClearLastProvider = onDidRequestClearLastProvider;
  }
};
var $uhb = class extends $3c {
  constructor(id2, options3, provideContent, onClose, onOpen, provideNextContent, providePreviousContent, actions, onDidChangeContent) {
    super();
    this.id = id2;
    this.options = options3;
    this.provideContent = provideContent;
    this.onClose = onClose;
    this.onOpen = onOpen;
    this.provideNextContent = provideNextContent;
    this.providePreviousContent = providePreviousContent;
    this.actions = actions;
    this.onDidChangeContent = onDidChangeContent;
  }
};

// out-build/vs/editor/contrib/hover/browser/hoverAccessibleViews.js
var HoverAccessibilityHelpNLS;
(function(HoverAccessibilityHelpNLS2) {
  HoverAccessibilityHelpNLS2.increaseVerbosity = localize(1181, null, `<keybinding:${$Xbb}>`);
  HoverAccessibilityHelpNLS2.decreaseVerbosity = localize(1182, null, `<keybinding:${$1bb}>`);
})(HoverAccessibilityHelpNLS || (HoverAccessibilityHelpNLS = {}));
var $Gib = class {
  constructor() {
    this.type = "view";
    this.priority = 95;
    this.name = "hover";
    this.when = EditorContextKeys.hoverFocused;
  }
  getProvider(accessor) {
    const codeEditorService = accessor.get($U5);
    const codeEditor = codeEditorService.getActiveCodeEditor() || codeEditorService.getFocusedCodeEditor();
    if (!codeEditor) {
      throw new Error("No active or focused code editor");
    }
    const hoverController = $Afb.get(codeEditor);
    if (!hoverController) {
      return;
    }
    const keybindingService = accessor.get($Ty);
    return accessor.get($Pk).createInstance($Jib, keybindingService, codeEditor, hoverController);
  }
};
var $Hib = class {
  constructor() {
    this.priority = 100;
    this.name = "hover";
    this.type = "help";
    this.when = EditorContextKeys.hoverVisible;
  }
  getProvider(accessor) {
    const codeEditorService = accessor.get($U5);
    const codeEditor = codeEditorService.getActiveCodeEditor() || codeEditorService.getFocusedCodeEditor();
    if (!codeEditor) {
      throw new Error("No active or focused code editor");
    }
    const hoverController = $Afb.get(codeEditor);
    if (!hoverController) {
      return;
    }
    return accessor.get($Pk).createInstance($Iib, hoverController);
  }
};
var BaseHoverAccessibleViewProvider = class extends $3c {
  constructor(c) {
    super();
    this.c = c;
    this.id = "hover";
    this.verbositySettingKey = "accessibility.verbosity.hover";
    this.a = this.B(new $ze());
    this.onDidChangeContent = this.a.event;
    this.b = -1;
  }
  onOpen() {
    if (!this.c) {
      return;
    }
    this.c.shouldKeepOpenOnEditorMouseMoveOrLeave = true;
    this.b = this.c.focusedHoverPartIndex();
    this.B(this.c.onHoverContentsChanged(() => {
      this.a.fire();
    }));
  }
  onClose() {
    if (!this.c) {
      return;
    }
    if (this.b === -1) {
      this.c.focus();
    } else {
      this.c.focusHoverPartWithIndex(this.b);
    }
    this.b = -1;
    this.c.shouldKeepOpenOnEditorMouseMoveOrLeave = false;
  }
  provideContentAtIndex(focusedHoverIndex, includeVerbosityActions) {
    if (focusedHoverIndex !== -1) {
      const accessibleContent = this.c.getAccessibleWidgetContentAtIndex(focusedHoverIndex);
      if (accessibleContent === void 0) {
        return "";
      }
      const contents = [];
      if (includeVerbosityActions) {
        contents.push(...this.f(focusedHoverIndex));
      }
      contents.push(accessibleContent);
      return contents.join("\n");
    } else {
      const accessibleContent = this.c.getAccessibleWidgetContent();
      if (accessibleContent === void 0) {
        return "";
      }
      const contents = [];
      contents.push(accessibleContent);
      return contents.join("\n");
    }
  }
  f(index) {
    const content = [];
    const descriptionForIncreaseAction = this.g(HoverVerbosityAction.Increase, index);
    if (descriptionForIncreaseAction !== void 0) {
      content.push(descriptionForIncreaseAction);
    }
    const descriptionForDecreaseAction = this.g(HoverVerbosityAction.Decrease, index);
    if (descriptionForDecreaseAction !== void 0) {
      content.push(descriptionForDecreaseAction);
    }
    return content;
  }
  g(action, index) {
    const isActionSupported = this.c.doesHoverAtIndexSupportVerbosityAction(index, action);
    if (!isActionSupported) {
      return;
    }
    switch (action) {
      case HoverVerbosityAction.Increase:
        return HoverAccessibilityHelpNLS.increaseVerbosity;
      case HoverVerbosityAction.Decrease:
        return HoverAccessibilityHelpNLS.decreaseVerbosity;
    }
  }
};
var $Iib = class extends BaseHoverAccessibleViewProvider {
  constructor(hoverController) {
    super(hoverController);
    this.options = {
      type: "help"
      /* AccessibleViewType.Help */
    };
  }
  provideContent() {
    return this.provideContentAtIndex(this.b, true);
  }
};
var $Jib = class extends BaseHoverAccessibleViewProvider {
  constructor(h3, j, hoverController) {
    super(hoverController);
    this.h = h3;
    this.j = j;
    this.options = {
      type: "view"
      /* AccessibleViewType.View */
    };
    this.n(this.j, hoverController);
  }
  provideContent() {
    return this.provideContentAtIndex(this.b, false);
  }
  get actions() {
    const actions = [];
    actions.push(this.m(this.j, HoverVerbosityAction.Increase));
    actions.push(this.m(this.j, HoverVerbosityAction.Decrease));
    return actions;
  }
  m(editor, action) {
    let actionId;
    let accessibleActionId;
    let actionCodicon;
    switch (action) {
      case HoverVerbosityAction.Increase:
        actionId = $Xbb;
        accessibleActionId = $Ybb;
        actionCodicon = $6l.add;
        break;
      case HoverVerbosityAction.Decrease:
        actionId = $1bb;
        accessibleActionId = $2bb;
        actionCodicon = $6l.remove;
        break;
    }
    const actionLabel = $Mdb(this.h, action);
    const actionEnabled = this.c.doesHoverAtIndexSupportVerbosityAction(this.b, action);
    return new $Um(accessibleActionId, actionLabel, ThemeIcon.asClassName(actionCodicon), actionEnabled, () => {
      editor.getAction(actionId)?.run({ index: this.b, focus: false });
    });
  }
  n(editor, hoverController) {
    const helpProvider = this.B(new $Iib(hoverController));
    this.options.language = editor.getModel()?.getLanguageId();
    this.options.customHelp = () => {
      return helpProvider.provideContentAtIndex(this.b, true);
    };
  }
};
var $Kib = class {
  constructor() {
    this.type = "view";
    this.priority = 90;
    this.name = "extension-hover";
  }
  getProvider(accessor) {
    const contextViewService = accessor.get($40);
    const contextViewElement = contextViewService.getContextViewElement();
    const extensionHoverContent = contextViewElement?.textContent ?? void 0;
    const hoverService = accessor.get($5$);
    if (contextViewElement.classList.contains("accessible-view-container") || !extensionHoverContent) {
      return;
    }
    return new $thb("hover", {
      language: "typescript",
      type: "view"
      /* AccessibleViewType.View */
    }, () => {
      return extensionHoverContent;
    }, () => {
      hoverService.showAndFocusLastHover();
    }, "accessibility.verbosity.hover");
  }
};

// out-build/vs/editor/contrib/hover/browser/hoverContribution.js
$85(
  $Afb.ID,
  $Afb,
  2
  /* EditorContributionInstantiation.BeforeFirstInteraction */
);
$85(
  $Fib.ID,
  $Fib,
  2
  /* EditorContributionInstantiation.BeforeFirstInteraction */
);
$55($pib);
$55($qib);
$55($rib);
$55($sib);
$55($tib);
$55($uib);
$55($vib);
$55($wib);
$55($xib);
$55($yib);
$55($zib);
$55($Aib);
$Bbb.register($Kdb);
$Bbb.register($Cib);
$ms((theme, collector) => {
  const hoverBorder = theme.getColor($lp);
  if (hoverBorder) {
    collector.addRule(`.monaco-editor .monaco-hover .hover-row:not(:first-child):not(:empty) { border-top: 1px solid ${hoverBorder.transparent(0.5)}; }`);
    collector.addRule(`.monaco-editor .monaco-hover hr { border-top: 1px solid ${hoverBorder.transparent(0.5)}; }`);
    collector.addRule(`.monaco-editor .monaco-hover hr { border-bottom: 0px solid ${hoverBorder.transparent(0.5)}; }`);
  }
});
$vhb.register(new $Gib());
$vhb.register(new $Hib());
$vhb.register(new $Kib());

// out-build/vs/editor/contrib/indentation/common/indentUtils.js
function $Lib(str, tabSize) {
  let spacesCnt = 0;
  for (let i2 = 0; i2 < str.length; i2++) {
    if (str.charAt(i2) === "	") {
      spacesCnt += tabSize;
    } else {
      spacesCnt++;
    }
  }
  return spacesCnt;
}
function $Mib(spacesCnt, tabSize, insertSpaces) {
  spacesCnt = spacesCnt < 0 ? 0 : spacesCnt;
  let result = "";
  if (!insertSpaces) {
    const tabsCnt = Math.floor(spacesCnt / tabSize);
    spacesCnt = spacesCnt % tabSize;
    for (let i2 = 0; i2 < tabsCnt; i2++) {
      result += "	";
    }
  }
  for (let i2 = 0; i2 < spacesCnt; i2++) {
    result += " ";
  }
  return result;
}

// out-build/vs/editor/contrib/indentation/common/indentation.js
function $Nib(model, languageConfigurationService, startLineNumber, endLineNumber) {
  if (model.getLineCount() === 1 && model.getLineMaxColumn(1) === 1) {
    return [];
  }
  const indentationRulesSupport = languageConfigurationService.getLanguageConfiguration(model.getLanguageId()).indentRulesSupport;
  if (!indentationRulesSupport) {
    return [];
  }
  const processedIndentRulesSupport = new $u6(model, indentationRulesSupport, languageConfigurationService);
  endLineNumber = Math.min(endLineNumber, model.getLineCount());
  while (startLineNumber <= endLineNumber) {
    if (!processedIndentRulesSupport.shouldIgnore(startLineNumber)) {
      break;
    }
    startLineNumber++;
  }
  if (startLineNumber > endLineNumber - 1) {
    return [];
  }
  const { tabSize, indentSize, insertSpaces } = model.getOptions();
  const shiftIndent = (indentation, count) => {
    count = count || 1;
    return $y6.shiftIndent(indentation, indentation.length + count, tabSize, indentSize, insertSpaces);
  };
  const unshiftIndent = (indentation, count) => {
    count = count || 1;
    return $y6.unshiftIndent(indentation, indentation.length + count, tabSize, indentSize, insertSpaces);
  };
  const indentEdits = [];
  const currentLineText = model.getLineContent(startLineNumber);
  let globalIndent = $Pf(currentLineText);
  let idealIndentForNextLine = globalIndent;
  if (processedIndentRulesSupport.shouldIncrease(startLineNumber)) {
    idealIndentForNextLine = shiftIndent(idealIndentForNextLine);
    globalIndent = shiftIndent(globalIndent);
  } else if (processedIndentRulesSupport.shouldIndentNextLine(startLineNumber)) {
    idealIndentForNextLine = shiftIndent(idealIndentForNextLine);
  }
  startLineNumber++;
  for (let lineNumber = startLineNumber; lineNumber <= endLineNumber; lineNumber++) {
    if (doesLineStartWithString(model, lineNumber)) {
      continue;
    }
    const text2 = model.getLineContent(lineNumber);
    const oldIndentation = $Pf(text2);
    const currentIdealIndent = idealIndentForNextLine;
    if (processedIndentRulesSupport.shouldDecrease(lineNumber, currentIdealIndent)) {
      idealIndentForNextLine = unshiftIndent(idealIndentForNextLine);
      globalIndent = unshiftIndent(globalIndent);
    }
    if (oldIndentation !== idealIndentForNextLine) {
      indentEdits.push($bD.replaceMove(new $_D(lineNumber, 1, lineNumber, oldIndentation.length + 1), $BG(idealIndentForNextLine, indentSize, insertSpaces)));
    }
    if (processedIndentRulesSupport.shouldIgnore(lineNumber)) {
      continue;
    } else if (processedIndentRulesSupport.shouldIncrease(lineNumber, currentIdealIndent)) {
      globalIndent = shiftIndent(globalIndent);
      idealIndentForNextLine = globalIndent;
    } else if (processedIndentRulesSupport.shouldIndentNextLine(lineNumber, currentIdealIndent)) {
      idealIndentForNextLine = shiftIndent(idealIndentForNextLine);
    } else {
      idealIndentForNextLine = globalIndent;
    }
  }
  return indentEdits;
}
function doesLineStartWithString(model, lineNumber) {
  if (!model.tokenization.isCheapToTokenize(lineNumber)) {
    return false;
  }
  const lineTokens = model.tokenization.getLineTokens(lineNumber);
  return lineTokens.getStandardTokenType(0) === 2;
}

// out-build/vs/editor/contrib/indentation/browser/indentation.js
var $Oib = class _$Oib extends $Z5 {
  static {
    this.ID = "editor.action.indentationToSpaces";
  }
  constructor() {
    super({
      id: _$Oib.ID,
      label: localize2(1226, "Convert Indentation to Spaces"),
      precondition: EditorContextKeys.writable,
      metadata: {
        description: localize2(1227, "Convert the tab indentation to spaces.")
      }
    });
  }
  run(accessor, editor) {
    const model = editor.getModel();
    if (!model) {
      return;
    }
    const modelOpts = model.getOptions();
    const selection = editor.getSelection();
    if (!selection) {
      return;
    }
    const command4 = new $Zib(selection, modelOpts.tabSize);
    editor.pushUndoStop();
    editor.executeCommands(this.id, [command4]);
    editor.pushUndoStop();
    model.updateOptions({
      insertSpaces: true
    });
  }
};
var $Pib = class _$Pib extends $Z5 {
  static {
    this.ID = "editor.action.indentationToTabs";
  }
  constructor() {
    super({
      id: _$Pib.ID,
      label: localize2(1228, "Convert Indentation to Tabs"),
      precondition: EditorContextKeys.writable,
      metadata: {
        description: localize2(1229, "Convert the spaces indentation to tabs.")
      }
    });
  }
  run(accessor, editor) {
    const model = editor.getModel();
    if (!model) {
      return;
    }
    const modelOpts = model.getOptions();
    const selection = editor.getSelection();
    if (!selection) {
      return;
    }
    const command4 = new $1ib(selection, modelOpts.tabSize);
    editor.pushUndoStop();
    editor.executeCommands(this.id, [command4]);
    editor.pushUndoStop();
    model.updateOptions({
      insertSpaces: false
    });
  }
};
var $Qib = class extends $Z5 {
  constructor(d, e, opts) {
    super(opts);
    this.d = d;
    this.e = e;
  }
  run(accessor, editor) {
    const quickInputService = accessor.get($1M);
    const modelService = accessor.get($sG);
    const model = editor.getModel();
    if (!model) {
      return;
    }
    const creationOpts = modelService.getCreationOptions(model.getLanguageId(), model.uri, model.isForSimpleWidget);
    const modelOpts = model.getOptions();
    const picks = [1, 2, 3, 4, 5, 6, 7, 8].map((n) => ({
      id: n.toString(),
      label: n.toString(),
      // add description for tabSize value set in the configuration
      description: n === creationOpts.tabSize && n === modelOpts.tabSize ? localize(1222, null) : n === creationOpts.tabSize ? localize(1223, null) : n === modelOpts.tabSize ? localize(1224, null) : void 0
    }));
    const autoFocusIndex = Math.min(model.getOptions().tabSize - 1, 7);
    setTimeout(
      () => {
        quickInputService.pick(picks, { placeHolder: localize(1225, null), activeItem: picks[autoFocusIndex] }).then((pick) => {
          if (pick) {
            if (model && !model.isDisposed()) {
              const pickedVal = parseInt(pick.label, 10);
              if (this.e) {
                model.updateOptions({
                  tabSize: pickedVal
                });
              } else {
                model.updateOptions({
                  tabSize: pickedVal,
                  indentSize: pickedVal,
                  insertSpaces: this.d
                });
              }
            }
          }
        });
      },
      50
      /* quick input is sensitive to being opened so soon after another */
    );
  }
};
var $Rib = class _$Rib extends $Qib {
  static {
    this.ID = "editor.action.indentUsingTabs";
  }
  constructor() {
    super(false, false, {
      id: _$Rib.ID,
      label: localize2(1230, "Indent Using Tabs"),
      precondition: void 0,
      metadata: {
        description: localize2(1231, "Use indentation with tabs.")
      }
    });
  }
};
var $Sib = class _$Sib extends $Qib {
  static {
    this.ID = "editor.action.indentUsingSpaces";
  }
  constructor() {
    super(true, false, {
      id: _$Sib.ID,
      label: localize2(1232, "Indent Using Spaces"),
      precondition: void 0,
      metadata: {
        description: localize2(1233, "Use indentation with spaces.")
      }
    });
  }
};
var $Tib = class _$Tib extends $Qib {
  static {
    this.ID = "editor.action.changeTabDisplaySize";
  }
  constructor() {
    super(true, true, {
      id: _$Tib.ID,
      label: localize2(1234, "Change Tab Display Size"),
      precondition: void 0,
      metadata: {
        description: localize2(1235, "Change the space size equivalent of the tab.")
      }
    });
  }
};
var $Uib = class _$Uib extends $Z5 {
  static {
    this.ID = "editor.action.detectIndentation";
  }
  constructor() {
    super({
      id: _$Uib.ID,
      label: localize2(1236, "Detect Indentation from Content"),
      precondition: void 0,
      metadata: {
        description: localize2(1237, "Detect the indentation from content.")
      }
    });
  }
  run(accessor, editor) {
    const modelService = accessor.get($sG);
    const model = editor.getModel();
    if (!model) {
      return;
    }
    const creationOpts = modelService.getCreationOptions(model.getLanguageId(), model.uri, model.isForSimpleWidget);
    model.detectIndentation(creationOpts.insertSpaces, creationOpts.tabSize);
  }
};
var $Vib = class extends $Z5 {
  constructor() {
    super({
      id: "editor.action.reindentlines",
      label: localize2(1238, "Reindent Lines"),
      precondition: EditorContextKeys.writable,
      metadata: {
        description: localize2(1239, "Reindent the lines of the editor.")
      }
    });
  }
  run(accessor, editor) {
    const languageConfigurationService = accessor.get($NF);
    const model = editor.getModel();
    if (!model) {
      return;
    }
    const edits = $Nib(model, languageConfigurationService, 1, model.getLineCount());
    if (edits.length > 0) {
      editor.pushUndoStop();
      editor.executeEdits(this.id, edits);
      editor.pushUndoStop();
    }
  }
};
var $Wib = class extends $Z5 {
  constructor() {
    super({
      id: "editor.action.reindentselectedlines",
      label: localize2(1240, "Reindent Selected Lines"),
      precondition: EditorContextKeys.writable,
      metadata: {
        description: localize2(1241, "Reindent the selected lines of the editor.")
      }
    });
  }
  run(accessor, editor) {
    const languageConfigurationService = accessor.get($NF);
    const model = editor.getModel();
    if (!model) {
      return;
    }
    const selections = editor.getSelections();
    if (selections === null) {
      return;
    }
    const edits = [];
    for (const selection of selections) {
      let startLineNumber = selection.startLineNumber;
      let endLineNumber = selection.endLineNumber;
      if (startLineNumber !== endLineNumber && selection.endColumn === 1) {
        endLineNumber--;
      }
      if (startLineNumber === 1) {
        if (startLineNumber === endLineNumber) {
          continue;
        }
      } else {
        startLineNumber--;
      }
      const editOperations = $Nib(model, languageConfigurationService, startLineNumber, endLineNumber);
      edits.push(...editOperations);
    }
    if (edits.length > 0) {
      editor.pushUndoStop();
      editor.executeEdits(this.id, edits);
      editor.pushUndoStop();
    }
  }
};
var $Xib = class {
  constructor(edits, initialSelection) {
    this.b = initialSelection;
    this.a = [];
    this.c = null;
    for (const edit3 of edits) {
      if (edit3.range && typeof edit3.text === "string") {
        this.a.push(edit3);
      }
    }
  }
  getEditOperations(model, builder) {
    for (const edit3 of this.a) {
      builder.addEditOperation($9C.lift(edit3.range), edit3.text);
    }
    let selectionIsSet = false;
    if (Array.isArray(this.a) && this.a.length === 1 && this.b.isEmpty()) {
      if (this.a[0].range.startColumn === this.b.endColumn && this.a[0].range.startLineNumber === this.b.endLineNumber) {
        selectionIsSet = true;
        this.c = builder.trackSelection(this.b, true);
      } else if (this.a[0].range.endColumn === this.b.startColumn && this.a[0].range.endLineNumber === this.b.startLineNumber) {
        selectionIsSet = true;
        this.c = builder.trackSelection(this.b, false);
      }
    }
    if (!selectionIsSet) {
      this.c = builder.trackSelection(this.b);
    }
  }
  computeCursorState(model, helper) {
    return helper.getTrackedSelection(this.c);
  }
};
var $Yib = class $Yib2 {
  static {
    this.ID = "editor.contrib.autoIndentOnPaste";
  }
  constructor(c, d) {
    this.c = c;
    this.d = d;
    this.a = new $2c();
    this.b = new $2c();
    this.a.add(c.onDidChangeConfiguration(() => this.e()));
    this.a.add(c.onDidChangeModel(() => this.e()));
    this.a.add(c.onDidChangeModelLanguage(() => this.e()));
  }
  e() {
    this.b.clear();
    if (this.c.getOption(
      12
      /* EditorOption.autoIndent */
    ) < 4 || this.c.getOption(
      57
      /* EditorOption.formatOnPaste */
    )) {
      return;
    }
    if (!this.c.hasModel()) {
      return;
    }
    this.b.add(this.c.onDidPaste(({ range }) => {
      this.trigger(range);
    }));
  }
  trigger(range) {
    const selections = this.c.getSelections();
    if (selections === null || selections.length > 1) {
      return;
    }
    const model = this.c.getModel();
    if (!model) {
      return;
    }
    const containsOnlyWhitespace = this.f(model, range);
    if (containsOnlyWhitespace) {
      return;
    }
    if (isStartOrEndInString(model, range)) {
      return;
    }
    if (!model.tokenization.isCheapToTokenize(range.getStartPosition().lineNumber)) {
      return;
    }
    const autoIndent = this.c.getOption(
      12
      /* EditorOption.autoIndent */
    );
    const { tabSize, indentSize, insertSpaces } = model.getOptions();
    const textEdits = [];
    const indentConverter = {
      shiftIndent: (indentation) => {
        return $y6.shiftIndent(indentation, indentation.length + 1, tabSize, indentSize, insertSpaces);
      },
      unshiftIndent: (indentation) => {
        return $y6.unshiftIndent(indentation, indentation.length + 1, tabSize, indentSize, insertSpaces);
      }
    };
    let startLineNumber = range.startLineNumber;
    while (startLineNumber <= range.endLineNumber) {
      if (this.g(model, startLineNumber)) {
        startLineNumber++;
        continue;
      }
      break;
    }
    if (startLineNumber > range.endLineNumber) {
      return;
    }
    let firstLineText = model.getLineContent(startLineNumber);
    if (!/\S/.test(firstLineText.substring(0, range.startColumn - 1))) {
      const indentOfFirstLine = $q6(autoIndent, model, model.getLanguageId(), startLineNumber, indentConverter, this.d);
      if (indentOfFirstLine !== null) {
        const oldIndentation = $Pf(firstLineText);
        const newSpaceCnt = $Lib(indentOfFirstLine, tabSize);
        const oldSpaceCnt = $Lib(oldIndentation, tabSize);
        if (newSpaceCnt !== oldSpaceCnt) {
          const newIndent = $Mib(newSpaceCnt, tabSize, insertSpaces);
          textEdits.push({
            range: new $9C(startLineNumber, 1, startLineNumber, oldIndentation.length + 1),
            text: newIndent
          });
          firstLineText = newIndent + firstLineText.substring(oldIndentation.length);
        } else {
          const indentMetadata = $t6(model, startLineNumber, this.d);
          if (indentMetadata === 0 || indentMetadata === 8) {
            return;
          }
        }
      }
    }
    const firstLineNumber = startLineNumber;
    while (startLineNumber < range.endLineNumber) {
      if (!/\S/.test(model.getLineContent(startLineNumber + 1))) {
        startLineNumber++;
        continue;
      }
      break;
    }
    if (startLineNumber !== range.endLineNumber) {
      const virtualModel = {
        tokenization: {
          getLineTokens: (lineNumber) => {
            return model.tokenization.getLineTokens(lineNumber);
          },
          getLanguageId: () => {
            return model.getLanguageId();
          },
          getLanguageIdAtPosition: (lineNumber, column) => {
            return model.getLanguageIdAtPosition(lineNumber, column);
          }
        },
        getLineContent: (lineNumber) => {
          if (lineNumber === firstLineNumber) {
            return firstLineText;
          } else {
            return model.getLineContent(lineNumber);
          }
        }
      };
      const indentOfSecondLine = $q6(autoIndent, virtualModel, model.getLanguageId(), startLineNumber + 1, indentConverter, this.d);
      if (indentOfSecondLine !== null) {
        const newSpaceCntOfSecondLine = $Lib(indentOfSecondLine, tabSize);
        const oldSpaceCntOfSecondLine = $Lib($Pf(model.getLineContent(startLineNumber + 1)), tabSize);
        if (newSpaceCntOfSecondLine !== oldSpaceCntOfSecondLine) {
          const spaceCntOffset = newSpaceCntOfSecondLine - oldSpaceCntOfSecondLine;
          for (let i2 = startLineNumber + 1; i2 <= range.endLineNumber; i2++) {
            const lineContent = model.getLineContent(i2);
            const originalIndent = $Pf(lineContent);
            const originalSpacesCnt = $Lib(originalIndent, tabSize);
            const newSpacesCnt = originalSpacesCnt + spaceCntOffset;
            const newIndent = $Mib(newSpacesCnt, tabSize, insertSpaces);
            if (newIndent !== originalIndent) {
              textEdits.push({
                range: new $9C(i2, 1, i2, originalIndent.length + 1),
                text: newIndent
              });
            }
          }
        }
      }
    }
    if (textEdits.length > 0) {
      this.c.pushUndoStop();
      const cmd = new $Xib(textEdits, this.c.getSelection());
      this.c.executeCommand("autoIndentOnPaste", cmd);
      this.c.pushUndoStop();
    }
  }
  f(model, range) {
    const lineContainsOnlyWhitespace = (content) => {
      return content.trim().length === 0;
    };
    let containsOnlyWhitespace = true;
    if (range.startLineNumber === range.endLineNumber) {
      const lineContent = model.getLineContent(range.startLineNumber);
      const linePart = lineContent.substring(range.startColumn - 1, range.endColumn - 1);
      containsOnlyWhitespace = lineContainsOnlyWhitespace(linePart);
    } else {
      for (let i2 = range.startLineNumber; i2 <= range.endLineNumber; i2++) {
        const lineContent = model.getLineContent(i2);
        if (i2 === range.startLineNumber) {
          const linePart = lineContent.substring(range.startColumn - 1);
          containsOnlyWhitespace = lineContainsOnlyWhitespace(linePart);
        } else if (i2 === range.endLineNumber) {
          const linePart = lineContent.substring(0, range.endColumn - 1);
          containsOnlyWhitespace = lineContainsOnlyWhitespace(linePart);
        } else {
          containsOnlyWhitespace = model.getLineFirstNonWhitespaceColumn(i2) === 0;
        }
        if (!containsOnlyWhitespace) {
          break;
        }
      }
    }
    return containsOnlyWhitespace;
  }
  g(model, lineNumber) {
    model.tokenization.forceTokenization(lineNumber);
    const nonWhitespaceColumn = model.getLineFirstNonWhitespaceColumn(lineNumber);
    if (nonWhitespaceColumn === 0) {
      return true;
    }
    const tokens = model.tokenization.getLineTokens(lineNumber);
    if (tokens.getCount() > 0) {
      const firstNonWhitespaceTokenIndex = tokens.findTokenIndexAtOffset(nonWhitespaceColumn);
      if (firstNonWhitespaceTokenIndex >= 0 && tokens.getStandardTokenType(firstNonWhitespaceTokenIndex) === 1) {
        return true;
      }
    }
    return false;
  }
  dispose() {
    this.a.dispose();
    this.b.dispose();
  }
};
$Yib = __decorate([
  __param(1, $NF)
], $Yib);
function isStartOrEndInString(model, range) {
  const isPositionInString = (position) => {
    const tokenType = $yE(model, position);
    return tokenType === 2;
  };
  return isPositionInString(range.getStartPosition()) || isPositionInString(range.getEndPosition());
}
function getIndentationEditOperations(model, builder, tabSize, tabsToSpaces) {
  if (model.getLineCount() === 1 && model.getLineMaxColumn(1) === 1) {
    return;
  }
  let spaces2 = "";
  for (let i2 = 0; i2 < tabSize; i2++) {
    spaces2 += " ";
  }
  const spacesRegExp = new RegExp(spaces2, "gi");
  for (let lineNumber = 1, lineCount = model.getLineCount(); lineNumber <= lineCount; lineNumber++) {
    let lastIndentationColumn = model.getLineFirstNonWhitespaceColumn(lineNumber);
    if (lastIndentationColumn === 0) {
      lastIndentationColumn = model.getLineMaxColumn(lineNumber);
    }
    if (lastIndentationColumn === 1) {
      continue;
    }
    const originalIndentationRange = new $9C(lineNumber, 1, lineNumber, lastIndentationColumn);
    const originalIndentation = model.getValueInRange(originalIndentationRange);
    const newIndentation = tabsToSpaces ? originalIndentation.replace(/\t/ig, spaces2) : originalIndentation.replace(spacesRegExp, "	");
    builder.addEditOperation(originalIndentationRange, newIndentation);
  }
}
var $Zib = class {
  constructor(b, c) {
    this.b = b;
    this.c = c;
    this.a = null;
  }
  getEditOperations(model, builder) {
    this.a = builder.trackSelection(this.b);
    getIndentationEditOperations(model, builder, this.c, true);
  }
  computeCursorState(model, helper) {
    return helper.getTrackedSelection(this.a);
  }
};
var $1ib = class {
  constructor(b, c) {
    this.b = b;
    this.c = c;
    this.a = null;
  }
  getEditOperations(model, builder) {
    this.a = builder.trackSelection(this.b);
    getIndentationEditOperations(model, builder, this.c, false);
  }
  computeCursorState(model, helper) {
    return helper.getTrackedSelection(this.a);
  }
};
$85(
  $Yib.ID,
  $Yib,
  2
  /* EditorContributionInstantiation.BeforeFirstInteraction */
);
$55($Oib);
$55($Pib);
$55($Rib);
$55($Sib);
$55($Tib);
$55($Uib);
$55($Vib);
$55($Wib);

// out-build/vs/editor/contrib/inlayHints/browser/inlayHintsContribution.js
$85(
  $vfb.ID,
  $vfb,
  1
  /* EditorContributionInstantiation.AfterFirstRender */
);
$Bbb.register($wfb);

// out-build/vs/editor/contrib/inPlaceReplace/browser/inPlaceReplaceCommand.js
var $2ib = class {
  constructor(editRange, originalSelection, text2) {
    this.a = editRange;
    this.b = originalSelection;
    this.c = text2;
  }
  getEditOperations(model, builder) {
    builder.addTrackedEditOperation(this.a, this.c);
  }
  computeCursorState(model, helper) {
    const inverseEditOperations = helper.getInverseEditOperations();
    const srcRange = inverseEditOperations[0].range;
    if (!this.b.isEmpty()) {
      return new $_D(srcRange.endLineNumber, srcRange.endColumn - this.c.length, srcRange.endLineNumber, srcRange.endColumn);
    }
    return new $_D(srcRange.endLineNumber, Math.min(this.b.positionColumn, srcRange.endColumn), srcRange.endLineNumber, Math.min(this.b.positionColumn, srcRange.endColumn));
  }
};

// out-build/vs/editor/contrib/inPlaceReplace/browser/inPlaceReplace.js
var InPlaceReplaceController_1;
var InPlaceReplaceController = class InPlaceReplaceController2 {
  static {
    InPlaceReplaceController_1 = this;
  }
  static {
    this.ID = "editor.contrib.inPlaceReplaceController";
  }
  static get(editor) {
    return editor.getContribution(InPlaceReplaceController_1.ID);
  }
  static {
    this.a = $WI.register({
      description: "in-place-replace",
      className: "valueSetReplacement"
    });
  }
  constructor(editor, editorWorkerService) {
    this.b = editor;
    this.c = editorWorkerService;
    this.d = this.b.createDecorationsCollection();
  }
  dispose() {
  }
  run(source, up) {
    this.e?.cancel();
    const editorSelection = this.b.getSelection();
    const model = this.b.getModel();
    if (!model || !editorSelection) {
      return void 0;
    }
    let selection = editorSelection;
    if (selection.startLineNumber !== selection.endLineNumber) {
      return void 0;
    }
    const state = new $M_(
      this.b,
      1 | 4
      /* CodeEditorStateFlag.Position */
    );
    const modelURI = model.uri;
    if (!this.c.canNavigateValueSet(modelURI)) {
      return Promise.resolve(void 0);
    }
    this.e = $Hh((token) => this.c.navigateValueSet(modelURI, selection, up));
    return this.e.then((result) => {
      if (!result || !result.range || !result.value) {
        return;
      }
      if (!state.validate(this.b)) {
        return;
      }
      const editRange = $9C.lift(result.range);
      let highlightRange2 = result.range;
      const diff3 = result.value.length - (selection.endColumn - selection.startColumn);
      highlightRange2 = {
        startLineNumber: highlightRange2.startLineNumber,
        startColumn: highlightRange2.startColumn,
        endLineNumber: highlightRange2.endLineNumber,
        endColumn: highlightRange2.startColumn + result.value.length
      };
      if (diff3 > 1) {
        selection = new $_D(selection.startLineNumber, selection.startColumn, selection.endLineNumber, selection.endColumn + diff3 - 1);
      }
      const command4 = new $2ib(editRange, selection, result.value);
      this.b.pushUndoStop();
      this.b.executeCommand(source, command4);
      this.b.pushUndoStop();
      this.d.set([{
        range: highlightRange2,
        options: InPlaceReplaceController_1.a
      }]);
      this.f?.cancel();
      this.f = $Wh(350);
      this.f.then(() => this.d.clear()).catch($gb);
    }).catch($gb);
  }
};
InPlaceReplaceController = InPlaceReplaceController_1 = __decorate([
  __param(1, $I0)
], InPlaceReplaceController);
var InPlaceReplaceUp = class extends $Z5 {
  constructor() {
    super({
      id: "editor.action.inPlaceReplace.up",
      label: localize2(1286, "Replace with Previous Value"),
      precondition: EditorContextKeys.writable,
      kbOpts: {
        kbExpr: EditorContextKeys.editorTextFocus,
        primary: 2048 | 1024 | 87,
        weight: 100
        /* KeybindingWeight.EditorContrib */
      }
    });
  }
  run(accessor, editor) {
    const controller = InPlaceReplaceController.get(editor);
    if (!controller) {
      return Promise.resolve(void 0);
    }
    return controller.run(this.id, false);
  }
};
var InPlaceReplaceDown = class extends $Z5 {
  constructor() {
    super({
      id: "editor.action.inPlaceReplace.down",
      label: localize2(1287, "Replace with Next Value"),
      precondition: EditorContextKeys.writable,
      kbOpts: {
        kbExpr: EditorContextKeys.editorTextFocus,
        primary: 2048 | 1024 | 89,
        weight: 100
        /* KeybindingWeight.EditorContrib */
      }
    });
  }
  run(accessor, editor) {
    const controller = InPlaceReplaceController.get(editor);
    if (!controller) {
      return Promise.resolve(void 0);
    }
    return controller.run(this.id, true);
  }
};
$85(
  InPlaceReplaceController.ID,
  InPlaceReplaceController,
  4
  /* EditorContributionInstantiation.Lazy */
);
$55(InPlaceReplaceUp);
$55(InPlaceReplaceDown);

// out-build/vs/editor/contrib/lineSelection/browser/lineSelection.js
var $3ib = class extends $Z5 {
  constructor() {
    super({
      id: "expandLineSelection",
      label: localize2(1288, "Expand Line Selection"),
      precondition: void 0,
      kbOpts: {
        weight: 0,
        kbExpr: EditorContextKeys.textInputFocus,
        primary: 2048 | 42
        /* KeyCode.KeyL */
      }
    });
  }
  run(_accessor, editor, args2) {
    args2 = args2 || {};
    if (!editor.hasModel()) {
      return;
    }
    const viewModel = editor._getViewModel();
    viewModel.model.pushStackElement();
    viewModel.setCursorStates(args2.source, 3, $o6.expandLineSelection(viewModel, viewModel.getCursorStates()));
    viewModel.revealAllCursors(args2.source, true);
  }
};
$55($3ib);

// out-build/vs/editor/common/commands/trimTrailingWhitespaceCommand.js
var $4ib = class {
  constructor(selection, cursors, trimInRegexesAndStrings) {
    this.c = selection;
    this.e = cursors;
    this.d = null;
    this.f = trimInRegexesAndStrings;
  }
  getEditOperations(model, builder) {
    const ops = $5ib(model, this.e, this.f);
    for (let i2 = 0, len = ops.length; i2 < len; i2++) {
      const op = ops[i2];
      builder.addEditOperation(op.range, op.text);
    }
    this.d = builder.trackSelection(this.c);
  }
  computeCursorState(model, helper) {
    return helper.getTrackedSelection(this.d);
  }
};
function $5ib(model, cursors, trimInRegexesAndStrings) {
  cursors.sort((a, b) => {
    if (a.lineNumber === b.lineNumber) {
      return a.column - b.column;
    }
    return a.lineNumber - b.lineNumber;
  });
  for (let i2 = cursors.length - 2; i2 >= 0; i2--) {
    if (cursors[i2].lineNumber === cursors[i2 + 1].lineNumber) {
      cursors.splice(i2, 1);
    }
  }
  const r2 = [];
  let rLen = 0;
  let cursorIndex = 0;
  const cursorLen = cursors.length;
  for (let lineNumber = 1, lineCount = model.getLineCount(); lineNumber <= lineCount; lineNumber++) {
    const lineContent = model.getLineContent(lineNumber);
    const maxLineColumn = lineContent.length + 1;
    let minEditColumn = 0;
    if (cursorIndex < cursorLen && cursors[cursorIndex].lineNumber === lineNumber) {
      minEditColumn = cursors[cursorIndex].column;
      cursorIndex++;
      if (minEditColumn === maxLineColumn) {
        continue;
      }
    }
    if (lineContent.length === 0) {
      continue;
    }
    const lastNonWhitespaceIndex = $Qf(lineContent);
    let fromColumn = 0;
    if (lastNonWhitespaceIndex === -1) {
      fromColumn = 1;
    } else if (lastNonWhitespaceIndex !== lineContent.length - 1) {
      fromColumn = lastNonWhitespaceIndex + 2;
    } else {
      continue;
    }
    if (!trimInRegexesAndStrings) {
      if (!model.tokenization.hasAccurateTokensForLine(lineNumber)) {
        continue;
      }
      const lineTokens = model.tokenization.getLineTokens(lineNumber);
      const fromColumnType = lineTokens.getStandardTokenType(lineTokens.findTokenIndexAtOffset(fromColumn));
      if (fromColumnType === 2 || fromColumnType === 3) {
        continue;
      }
    }
    fromColumn = Math.max(minEditColumn, fromColumn);
    r2[rLen++] = $bD.delete(new $9C(lineNumber, fromColumn, lineNumber, maxLineColumn));
  }
  return r2;
}

// out-build/vs/editor/contrib/linesOperations/browser/copyLinesCommand.js
var $6ib = class {
  constructor(selection, isCopyingDown, noop2) {
    this.a = selection;
    this.b = isCopyingDown;
    this.c = noop2 || false;
    this.d = 0;
    this.e = null;
    this.f = 0;
    this.g = 0;
  }
  getEditOperations(model, builder) {
    let s = this.a;
    this.f = 0;
    this.g = 0;
    if (s.startLineNumber < s.endLineNumber && s.endColumn === 1) {
      this.g = 1;
      s = s.setEndPosition(s.endLineNumber - 1, model.getLineMaxColumn(s.endLineNumber - 1));
    }
    const sourceLines = [];
    for (let i2 = s.startLineNumber; i2 <= s.endLineNumber; i2++) {
      sourceLines.push(model.getLineContent(i2));
    }
    const sourceText = sourceLines.join("\n");
    if (sourceText === "") {
      if (this.b) {
        this.f++;
        this.g++;
      }
    }
    if (this.c) {
      builder.addEditOperation(new $9C(s.endLineNumber, model.getLineMaxColumn(s.endLineNumber), s.endLineNumber + 1, 1), s.endLineNumber === model.getLineCount() ? "" : "\n");
    } else {
      if (!this.b) {
        builder.addEditOperation(new $9C(s.endLineNumber, model.getLineMaxColumn(s.endLineNumber), s.endLineNumber, model.getLineMaxColumn(s.endLineNumber)), "\n" + sourceText);
      } else {
        builder.addEditOperation(new $9C(s.startLineNumber, 1, s.startLineNumber, 1), sourceText + "\n");
      }
    }
    this.e = builder.trackSelection(s);
    this.d = this.a.getDirection();
  }
  computeCursorState(model, helper) {
    let result = helper.getTrackedSelection(this.e);
    if (this.f !== 0 || this.g !== 0) {
      let startLineNumber = result.startLineNumber;
      let startColumn = result.startColumn;
      let endLineNumber = result.endLineNumber;
      let endColumn = result.endColumn;
      if (this.f !== 0) {
        startLineNumber = startLineNumber + this.f;
        startColumn = 1;
      }
      if (this.g !== 0) {
        endLineNumber = endLineNumber + this.g;
        endColumn = 1;
      }
      result = $_D.createWithDirection(startLineNumber, startColumn, endLineNumber, endColumn, this.d);
    }
    return result;
  }
};

// out-build/vs/editor/contrib/linesOperations/browser/moveLinesCommand.js
var $7ib = class $7ib2 {
  constructor(selection, isMovingDown, autoIndent, g) {
    this.g = g;
    this.a = selection;
    this.b = isMovingDown;
    this.c = autoIndent;
    this.d = null;
    this.f = false;
  }
  getEditOperations(model, builder) {
    const getLanguageId = () => {
      return model.getLanguageId();
    };
    const getLanguageIdAtPosition = (lineNumber, column) => {
      return model.getLanguageIdAtPosition(lineNumber, column);
    };
    const modelLineCount = model.getLineCount();
    if (this.b && this.a.endLineNumber === modelLineCount) {
      this.d = builder.trackSelection(this.a);
      return;
    }
    if (!this.b && this.a.startLineNumber === 1) {
      this.d = builder.trackSelection(this.a);
      return;
    }
    this.e = false;
    let s = this.a;
    if (s.startLineNumber < s.endLineNumber && s.endColumn === 1) {
      this.e = true;
      s = s.setEndPosition(s.endLineNumber - 1, model.getLineMaxColumn(s.endLineNumber - 1));
    }
    const { tabSize, indentSize, insertSpaces } = model.getOptions();
    const indentConverter = this.h(tabSize, indentSize, insertSpaces);
    if (s.startLineNumber === s.endLineNumber && model.getLineMaxColumn(s.startLineNumber) === 1) {
      const lineNumber = s.startLineNumber;
      const otherLineNumber = this.b ? lineNumber + 1 : lineNumber - 1;
      if (model.getLineMaxColumn(otherLineNumber) === 1) {
        builder.addEditOperation(new $9C(1, 1, 1, 1), null);
      } else {
        builder.addEditOperation(new $9C(lineNumber, 1, lineNumber, 1), model.getLineContent(otherLineNumber));
        builder.addEditOperation(new $9C(otherLineNumber, 1, otherLineNumber, model.getLineMaxColumn(otherLineNumber)), null);
      }
      s = new $_D(otherLineNumber, 1, otherLineNumber, 1);
    } else {
      let movingLineNumber;
      let movingLineText;
      if (this.b) {
        movingLineNumber = s.endLineNumber + 1;
        movingLineText = model.getLineContent(movingLineNumber);
        builder.addEditOperation(new $9C(movingLineNumber - 1, model.getLineMaxColumn(movingLineNumber - 1), movingLineNumber, model.getLineMaxColumn(movingLineNumber)), null);
        let insertingText = movingLineText;
        if (this.n(model, s)) {
          const movingLineMatchResult = this.l(model, indentConverter, tabSize, movingLineNumber, s.startLineNumber - 1);
          if (movingLineMatchResult !== null) {
            const oldIndentation = $Pf(model.getLineContent(movingLineNumber));
            const newSpaceCnt = movingLineMatchResult + $Lib(oldIndentation, tabSize);
            const newIndentation = $Mib(newSpaceCnt, tabSize, insertSpaces);
            insertingText = newIndentation + this.m(movingLineText);
          } else {
            const virtualModel = {
              tokenization: {
                getLineTokens: (lineNumber) => {
                  if (lineNumber === s.startLineNumber) {
                    return model.tokenization.getLineTokens(movingLineNumber);
                  } else {
                    return model.tokenization.getLineTokens(lineNumber);
                  }
                },
                getLanguageId,
                getLanguageIdAtPosition
              },
              getLineContent: (lineNumber) => {
                if (lineNumber === s.startLineNumber) {
                  return model.getLineContent(movingLineNumber);
                } else {
                  return model.getLineContent(lineNumber);
                }
              }
            };
            const indentOfMovingLine = $q6(this.c, virtualModel, model.getLanguageIdAtPosition(movingLineNumber, 1), s.startLineNumber, indentConverter, this.g);
            if (indentOfMovingLine !== null) {
              const oldIndentation = $Pf(model.getLineContent(movingLineNumber));
              const newSpaceCnt = $Lib(indentOfMovingLine, tabSize);
              const oldSpaceCnt = $Lib(oldIndentation, tabSize);
              if (newSpaceCnt !== oldSpaceCnt) {
                const newIndentation = $Mib(newSpaceCnt, tabSize, insertSpaces);
                insertingText = newIndentation + this.m(movingLineText);
              }
            }
          }
          builder.addEditOperation(new $9C(s.startLineNumber, 1, s.startLineNumber, 1), insertingText + "\n");
          const ret = this.k(model, indentConverter, tabSize, s.startLineNumber, movingLineNumber, insertingText);
          if (ret !== null) {
            if (ret !== 0) {
              this.o(model, builder, s, tabSize, insertSpaces, ret);
            }
          } else {
            const virtualModel = {
              tokenization: {
                getLineTokens: (lineNumber) => {
                  if (lineNumber === s.startLineNumber) {
                    return model.tokenization.getLineTokens(movingLineNumber);
                  } else if (lineNumber >= s.startLineNumber + 1 && lineNumber <= s.endLineNumber + 1) {
                    return model.tokenization.getLineTokens(lineNumber - 1);
                  } else {
                    return model.tokenization.getLineTokens(lineNumber);
                  }
                },
                getLanguageId,
                getLanguageIdAtPosition
              },
              getLineContent: (lineNumber) => {
                if (lineNumber === s.startLineNumber) {
                  return insertingText;
                } else if (lineNumber >= s.startLineNumber + 1 && lineNumber <= s.endLineNumber + 1) {
                  return model.getLineContent(lineNumber - 1);
                } else {
                  return model.getLineContent(lineNumber);
                }
              }
            };
            const newIndentatOfMovingBlock = $q6(this.c, virtualModel, model.getLanguageIdAtPosition(movingLineNumber, 1), s.startLineNumber + 1, indentConverter, this.g);
            if (newIndentatOfMovingBlock !== null) {
              const oldIndentation = $Pf(model.getLineContent(s.startLineNumber));
              const newSpaceCnt = $Lib(newIndentatOfMovingBlock, tabSize);
              const oldSpaceCnt = $Lib(oldIndentation, tabSize);
              if (newSpaceCnt !== oldSpaceCnt) {
                const spaceCntOffset = newSpaceCnt - oldSpaceCnt;
                this.o(model, builder, s, tabSize, insertSpaces, spaceCntOffset);
              }
            }
          }
        } else {
          builder.addEditOperation(new $9C(s.startLineNumber, 1, s.startLineNumber, 1), insertingText + "\n");
        }
      } else {
        movingLineNumber = s.startLineNumber - 1;
        movingLineText = model.getLineContent(movingLineNumber);
        builder.addEditOperation(new $9C(movingLineNumber, 1, movingLineNumber + 1, 1), null);
        builder.addEditOperation(new $9C(s.endLineNumber, model.getLineMaxColumn(s.endLineNumber), s.endLineNumber, model.getLineMaxColumn(s.endLineNumber)), "\n" + movingLineText);
        if (this.n(model, s)) {
          const virtualModel = {
            tokenization: {
              getLineTokens: (lineNumber) => {
                if (lineNumber === movingLineNumber) {
                  return model.tokenization.getLineTokens(s.startLineNumber);
                } else {
                  return model.tokenization.getLineTokens(lineNumber);
                }
              },
              getLanguageId,
              getLanguageIdAtPosition
            },
            getLineContent: (lineNumber) => {
              if (lineNumber === movingLineNumber) {
                return model.getLineContent(s.startLineNumber);
              } else {
                return model.getLineContent(lineNumber);
              }
            }
          };
          const ret = this.l(model, indentConverter, tabSize, s.startLineNumber, s.startLineNumber - 2);
          if (ret !== null) {
            if (ret !== 0) {
              this.o(model, builder, s, tabSize, insertSpaces, ret);
            }
          } else {
            const indentOfFirstLine = $q6(this.c, virtualModel, model.getLanguageIdAtPosition(s.startLineNumber, 1), movingLineNumber, indentConverter, this.g);
            if (indentOfFirstLine !== null) {
              const oldIndent = $Pf(model.getLineContent(s.startLineNumber));
              const newSpaceCnt = $Lib(indentOfFirstLine, tabSize);
              const oldSpaceCnt = $Lib(oldIndent, tabSize);
              if (newSpaceCnt !== oldSpaceCnt) {
                const spaceCntOffset = newSpaceCnt - oldSpaceCnt;
                this.o(model, builder, s, tabSize, insertSpaces, spaceCntOffset);
              }
            }
          }
        }
      }
    }
    this.d = builder.trackSelection(s);
  }
  h(tabSize, indentSize, insertSpaces) {
    return {
      shiftIndent: (indentation) => {
        return $y6.shiftIndent(indentation, indentation.length + 1, tabSize, indentSize, insertSpaces);
      },
      unshiftIndent: (indentation) => {
        return $y6.unshiftIndent(indentation, indentation.length + 1, tabSize, indentSize, insertSpaces);
      }
    };
  }
  j(model, indentConverter, tabSize, line, enter) {
    if (enter) {
      let enterPrefix = enter.indentation;
      if (enter.indentAction === IndentAction.None) {
        enterPrefix = enter.indentation + enter.appendText;
      } else if (enter.indentAction === IndentAction.Indent) {
        enterPrefix = enter.indentation + enter.appendText;
      } else if (enter.indentAction === IndentAction.IndentOutdent) {
        enterPrefix = enter.indentation;
      } else if (enter.indentAction === IndentAction.Outdent) {
        enterPrefix = indentConverter.unshiftIndent(enter.indentation) + enter.appendText;
      }
      const movingLineText = model.getLineContent(line);
      if (this.m(movingLineText).indexOf(this.m(enterPrefix)) >= 0) {
        const oldIndentation = $Pf(model.getLineContent(line));
        let newIndentation = $Pf(enterPrefix);
        const indentMetadataOfMovelingLine = $t6(model, line, this.g);
        if (indentMetadataOfMovelingLine !== null && indentMetadataOfMovelingLine & 2) {
          newIndentation = indentConverter.unshiftIndent(newIndentation);
        }
        const newSpaceCnt = $Lib(newIndentation, tabSize);
        const oldSpaceCnt = $Lib(oldIndentation, tabSize);
        return newSpaceCnt - oldSpaceCnt;
      }
    }
    return null;
  }
  /**
   *
   * @param model
   * @param indentConverter
   * @param tabSize
   * @param line the line moving down
   * @param futureAboveLineNumber the line which will be at the `line` position
   * @param futureAboveLineText
   */
  k(model, indentConverter, tabSize, line, futureAboveLineNumber, futureAboveLineText) {
    if ($Qf(futureAboveLineText) >= 0) {
      const maxColumn = model.getLineMaxColumn(futureAboveLineNumber);
      const enter = $x6(this.c, model, new $9C(futureAboveLineNumber, maxColumn, futureAboveLineNumber, maxColumn), this.g);
      return this.j(model, indentConverter, tabSize, line, enter);
    } else {
      let validPrecedingLine = line - 1;
      while (validPrecedingLine >= 1) {
        const lineContent = model.getLineContent(validPrecedingLine);
        const nonWhitespaceIdx = $Qf(lineContent);
        if (nonWhitespaceIdx >= 0) {
          break;
        }
        validPrecedingLine--;
      }
      if (validPrecedingLine < 1 || line > model.getLineCount()) {
        return null;
      }
      const maxColumn = model.getLineMaxColumn(validPrecedingLine);
      const enter = $x6(this.c, model, new $9C(validPrecedingLine, maxColumn, validPrecedingLine, maxColumn), this.g);
      return this.j(model, indentConverter, tabSize, line, enter);
    }
  }
  l(model, indentConverter, tabSize, line, oneLineAbove, previousLineText) {
    let validPrecedingLine = oneLineAbove;
    while (validPrecedingLine >= 1) {
      let lineContent;
      if (validPrecedingLine === oneLineAbove && previousLineText !== void 0) {
        lineContent = previousLineText;
      } else {
        lineContent = model.getLineContent(validPrecedingLine);
      }
      const nonWhitespaceIdx = $Qf(lineContent);
      if (nonWhitespaceIdx >= 0) {
        break;
      }
      validPrecedingLine--;
    }
    if (validPrecedingLine < 1 || line > model.getLineCount()) {
      return null;
    }
    const maxColumn = model.getLineMaxColumn(validPrecedingLine);
    const enter = $x6(this.c, model, new $9C(validPrecedingLine, maxColumn, validPrecedingLine, maxColumn), this.g);
    return this.j(model, indentConverter, tabSize, line, enter);
  }
  m(str) {
    return str.replace(/^\s+/, "");
  }
  n(model, selection) {
    if (this.c < 4) {
      return false;
    }
    if (!model.tokenization.isCheapToTokenize(selection.startLineNumber)) {
      return false;
    }
    const languageAtSelectionStart = model.getLanguageIdAtPosition(selection.startLineNumber, 1);
    const languageAtSelectionEnd = model.getLanguageIdAtPosition(selection.endLineNumber, 1);
    if (languageAtSelectionStart !== languageAtSelectionEnd) {
      return false;
    }
    if (this.g.getLanguageConfiguration(languageAtSelectionStart).indentRulesSupport === null) {
      return false;
    }
    return true;
  }
  o(model, builder, s, tabSize, insertSpaces, offset) {
    for (let i2 = s.startLineNumber; i2 <= s.endLineNumber; i2++) {
      const lineContent = model.getLineContent(i2);
      const originalIndent = $Pf(lineContent);
      const originalSpacesCnt = $Lib(originalIndent, tabSize);
      const newSpacesCnt = originalSpacesCnt + offset;
      const newIndent = $Mib(newSpacesCnt, tabSize, insertSpaces);
      if (newIndent !== originalIndent) {
        builder.addEditOperation(new $9C(i2, 1, i2, originalIndent.length + 1), newIndent);
        if (i2 === s.endLineNumber && s.endColumn <= originalIndent.length + 1 && newIndent === "") {
          this.f = true;
        }
      }
    }
  }
  computeCursorState(model, helper) {
    let result = helper.getTrackedSelection(this.d);
    if (this.e) {
      result = result.setEndPosition(result.endLineNumber + 1, 1);
    }
    if (this.f && result.startLineNumber < result.endLineNumber) {
      result = result.setEndPosition(result.endLineNumber, 2);
    }
    return result;
  }
};
$7ib = __decorate([
  __param(3, $NF)
], $7ib);

// out-build/vs/editor/contrib/linesOperations/browser/sortLinesCommand.js
var $8ib = class _$8ib {
  static {
    this.a = null;
  }
  static getCollator() {
    if (!_$8ib.a) {
      _$8ib.a = new Intl.Collator();
    }
    return _$8ib.a;
  }
  constructor(selection, descending) {
    this.b = selection;
    this.c = descending;
    this.d = null;
  }
  getEditOperations(model, builder) {
    const op = sortLines(model, this.b, this.c);
    if (op) {
      builder.addEditOperation(op.range, op.text);
    }
    this.d = builder.trackSelection(this.b);
  }
  computeCursorState(model, helper) {
    return helper.getTrackedSelection(this.d);
  }
  static canRun(model, selection, descending) {
    if (model === null) {
      return false;
    }
    const data = getSortData(model, selection, descending);
    if (!data) {
      return false;
    }
    for (let i2 = 0, len = data.before.length; i2 < len; i2++) {
      if (data.before[i2] !== data.after[i2]) {
        return true;
      }
    }
    return false;
  }
};
function getSortData(model, selection, descending) {
  const startLineNumber = selection.startLineNumber;
  let endLineNumber = selection.endLineNumber;
  if (selection.endColumn === 1) {
    endLineNumber--;
  }
  if (startLineNumber >= endLineNumber) {
    return null;
  }
  const linesToSort = [];
  for (let lineNumber = startLineNumber; lineNumber <= endLineNumber; lineNumber++) {
    linesToSort.push(model.getLineContent(lineNumber));
  }
  let sorted = linesToSort.slice(0);
  sorted.sort($8ib.getCollator().compare);
  if (descending === true) {
    sorted = sorted.reverse();
  }
  return {
    startLineNumber,
    endLineNumber,
    before: linesToSort,
    after: sorted
  };
}
function sortLines(model, selection, descending) {
  const data = getSortData(model, selection, descending);
  if (!data) {
    return null;
  }
  return $bD.replace(new $9C(data.startLineNumber, 1, data.endLineNumber, model.getLineMaxColumn(data.endLineNumber)), data.after.join("\n"));
}

// out-build/vs/editor/contrib/linesOperations/browser/linesOperations.js
var AbstractCopyLinesAction = class extends $Z5 {
  constructor(down, opts) {
    super(opts);
    this.d = down;
  }
  run(_accessor, editor) {
    if (!editor.hasModel()) {
      return;
    }
    const selections = editor.getSelections().map((selection, index) => ({ selection, index, ignore: false }));
    selections.sort((a, b) => $9C.compareRangesUsingStarts(a.selection, b.selection));
    let prev = selections[0];
    for (let i2 = 1; i2 < selections.length; i2++) {
      const curr = selections[i2];
      if (prev.selection.endLineNumber === curr.selection.startLineNumber) {
        if (prev.index < curr.index) {
          curr.ignore = true;
        } else {
          prev.ignore = true;
          prev = curr;
        }
      }
    }
    const commands2 = [];
    for (const selection of selections) {
      commands2.push(new $6ib(selection.selection, this.d, selection.ignore));
    }
    editor.pushUndoStop();
    editor.executeCommands(this.id, commands2);
    editor.pushUndoStop();
  }
};
var CopyLinesUpAction = class extends AbstractCopyLinesAction {
  constructor() {
    super(false, {
      id: "editor.action.copyLinesUpAction",
      label: localize2(1294, "Copy Line Up"),
      precondition: EditorContextKeys.writable,
      kbOpts: {
        kbExpr: EditorContextKeys.editorTextFocus,
        primary: 512 | 1024 | 16,
        linux: {
          primary: 2048 | 512 | 1024 | 16
          /* KeyCode.UpArrow */
        },
        weight: 100
        /* KeybindingWeight.EditorContrib */
      },
      menuOpts: {
        menuId: $bJ.MenubarSelectionMenu,
        group: "2_line",
        title: localize(1289, null),
        order: 1
      }
    });
  }
};
var CopyLinesDownAction = class extends AbstractCopyLinesAction {
  constructor() {
    super(true, {
      id: "editor.action.copyLinesDownAction",
      label: localize2(1295, "Copy Line Down"),
      precondition: EditorContextKeys.writable,
      kbOpts: {
        kbExpr: EditorContextKeys.editorTextFocus,
        primary: 512 | 1024 | 18,
        linux: {
          primary: 2048 | 512 | 1024 | 18
          /* KeyCode.DownArrow */
        },
        weight: 100
        /* KeybindingWeight.EditorContrib */
      },
      menuOpts: {
        menuId: $bJ.MenubarSelectionMenu,
        group: "2_line",
        title: localize(1290, null),
        order: 2
      }
    });
  }
};
var $9ib = class extends $Z5 {
  constructor() {
    super({
      id: "editor.action.duplicateSelection",
      label: localize2(1296, "Duplicate Selection"),
      precondition: EditorContextKeys.writable,
      menuOpts: {
        menuId: $bJ.MenubarSelectionMenu,
        group: "2_line",
        title: localize(1291, null),
        order: 5
      }
    });
  }
  run(accessor, editor, args2) {
    if (!editor.hasModel()) {
      return;
    }
    const commands2 = [];
    const selections = editor.getSelections();
    const model = editor.getModel();
    for (const selection of selections) {
      if (selection.isEmpty()) {
        commands2.push(new $6ib(selection, true));
      } else {
        const insertSelection = new $_D(selection.endLineNumber, selection.endColumn, selection.endLineNumber, selection.endColumn);
        commands2.push(new $d6(insertSelection, model.getValueInRange(selection)));
      }
    }
    editor.pushUndoStop();
    editor.executeCommands(this.id, commands2);
    editor.pushUndoStop();
  }
};
var AbstractMoveLinesAction = class extends $Z5 {
  constructor(down, opts) {
    super(opts);
    this.d = down;
  }
  run(accessor, editor) {
    const languageConfigurationService = accessor.get($NF);
    const commands2 = [];
    const selections = editor.getSelections() || [];
    const autoIndent = editor.getOption(
      12
      /* EditorOption.autoIndent */
    );
    for (const selection of selections) {
      commands2.push(new $7ib(selection, this.d, autoIndent, languageConfigurationService));
    }
    editor.pushUndoStop();
    editor.executeCommands(this.id, commands2);
    editor.pushUndoStop();
  }
};
var MoveLinesUpAction = class extends AbstractMoveLinesAction {
  constructor() {
    super(false, {
      id: "editor.action.moveLinesUpAction",
      label: localize2(1297, "Move Line Up"),
      precondition: EditorContextKeys.writable,
      kbOpts: {
        kbExpr: EditorContextKeys.editorTextFocus,
        primary: 512 | 16,
        linux: {
          primary: 512 | 16
          /* KeyCode.UpArrow */
        },
        weight: 100
        /* KeybindingWeight.EditorContrib */
      },
      menuOpts: {
        menuId: $bJ.MenubarSelectionMenu,
        group: "2_line",
        title: localize(1292, null),
        order: 3
      }
    });
  }
};
var MoveLinesDownAction = class extends AbstractMoveLinesAction {
  constructor() {
    super(true, {
      id: "editor.action.moveLinesDownAction",
      label: localize2(1298, "Move Line Down"),
      precondition: EditorContextKeys.writable,
      kbOpts: {
        kbExpr: EditorContextKeys.editorTextFocus,
        primary: 512 | 18,
        linux: {
          primary: 512 | 18
          /* KeyCode.DownArrow */
        },
        weight: 100
        /* KeybindingWeight.EditorContrib */
      },
      menuOpts: {
        menuId: $bJ.MenubarSelectionMenu,
        group: "2_line",
        title: localize(1293, null),
        order: 4
      }
    });
  }
};
var $0ib = class extends $Z5 {
  constructor(descending, opts) {
    super(opts);
    this.d = descending;
  }
  run(_accessor, editor) {
    if (!editor.hasModel()) {
      return;
    }
    const model = editor.getModel();
    let selections = editor.getSelections();
    if (selections.length === 1 && selections[0].isEmpty()) {
      selections = [new $_D(1, 1, model.getLineCount(), model.getLineMaxColumn(model.getLineCount()))];
    }
    for (const selection of selections) {
      if (!$8ib.canRun(editor.getModel(), selection, this.d)) {
        return;
      }
    }
    const commands2 = [];
    for (let i2 = 0, len = selections.length; i2 < len; i2++) {
      commands2[i2] = new $8ib(selections[i2], this.d);
    }
    editor.pushUndoStop();
    editor.executeCommands(this.id, commands2);
    editor.pushUndoStop();
  }
};
var $$ib = class extends $0ib {
  constructor() {
    super(false, {
      id: "editor.action.sortLinesAscending",
      label: localize2(1299, "Sort Lines Ascending"),
      precondition: EditorContextKeys.writable
    });
  }
};
var $_ib = class extends $0ib {
  constructor() {
    super(true, {
      id: "editor.action.sortLinesDescending",
      label: localize2(1300, "Sort Lines Descending"),
      precondition: EditorContextKeys.writable
    });
  }
};
var $ajb = class extends $Z5 {
  constructor() {
    super({
      id: "editor.action.removeDuplicateLines",
      label: localize2(1301, "Delete Duplicate Lines"),
      precondition: EditorContextKeys.writable
    });
  }
  run(_accessor, editor) {
    if (!editor.hasModel()) {
      return;
    }
    const model = editor.getModel();
    if (model.getLineCount() === 1 && model.getLineMaxColumn(1) === 1) {
      return;
    }
    const edits = [];
    const endCursorState = [];
    let linesDeleted = 0;
    let updateSelection = true;
    let selections = editor.getSelections();
    if (selections.length === 1 && selections[0].isEmpty()) {
      selections = [new $_D(1, 1, model.getLineCount(), model.getLineMaxColumn(model.getLineCount()))];
      updateSelection = false;
    }
    for (const selection of selections) {
      const uniqueLines = /* @__PURE__ */ new Set();
      const lines = [];
      for (let i2 = selection.startLineNumber; i2 <= selection.endLineNumber; i2++) {
        const line = model.getLineContent(i2);
        if (uniqueLines.has(line)) {
          continue;
        }
        lines.push(line);
        uniqueLines.add(line);
      }
      const selectionToReplace = new $_D(selection.startLineNumber, 1, selection.endLineNumber, model.getLineMaxColumn(selection.endLineNumber));
      const adjustedSelectionStart = selection.startLineNumber - linesDeleted;
      const finalSelection = new $_D(adjustedSelectionStart, 1, adjustedSelectionStart + lines.length - 1, lines[lines.length - 1].length);
      edits.push($bD.replace(selectionToReplace, lines.join("\n")));
      endCursorState.push(finalSelection);
      linesDeleted += selection.endLineNumber - selection.startLineNumber + 1 - lines.length;
    }
    editor.pushUndoStop();
    editor.executeEdits(this.id, edits, updateSelection ? endCursorState : void 0);
    editor.pushUndoStop();
  }
};
var $bjb = class _$bjb extends $Z5 {
  static {
    this.ID = "editor.action.trimTrailingWhitespace";
  }
  constructor() {
    super({
      id: _$bjb.ID,
      label: localize2(1302, "Trim Trailing Whitespace"),
      precondition: EditorContextKeys.writable,
      kbOpts: {
        kbExpr: EditorContextKeys.editorTextFocus,
        primary: $$e(
          2048 | 41,
          2048 | 54
          /* KeyCode.KeyX */
        ),
        weight: 100
        /* KeybindingWeight.EditorContrib */
      }
    });
  }
  run(_accessor, editor, args2) {
    let cursors = [];
    if (args2.reason === "auto-save") {
      cursors = (editor.getSelections() || []).map((s) => new $8C(s.positionLineNumber, s.positionColumn));
    }
    const selection = editor.getSelection();
    if (selection === null) {
      return;
    }
    const config = _accessor.get($kl);
    const model = editor.getModel();
    const trimInRegexAndStrings = config.getValue("files.trimTrailingWhitespaceInRegexAndStrings", { overrideIdentifier: model?.getLanguageId(), resource: model?.uri });
    const command4 = new $4ib(selection, cursors, trimInRegexAndStrings);
    editor.pushUndoStop();
    editor.executeCommands(this.id, [command4]);
    editor.pushUndoStop();
  }
};
var $cjb = class extends $Z5 {
  constructor() {
    super({
      id: "editor.action.deleteLines",
      label: localize2(1303, "Delete Line"),
      precondition: EditorContextKeys.writable,
      kbOpts: {
        kbExpr: EditorContextKeys.textInputFocus,
        primary: 2048 | 1024 | 41,
        weight: 100
        /* KeybindingWeight.EditorContrib */
      }
    });
  }
  run(_accessor, editor) {
    if (!editor.hasModel()) {
      return;
    }
    const ops = this.d(editor);
    const model = editor.getModel();
    if (model.getLineCount() === 1 && model.getLineMaxColumn(1) === 1) {
      return;
    }
    let linesDeleted = 0;
    const edits = [];
    const cursorState = [];
    for (let i2 = 0, len = ops.length; i2 < len; i2++) {
      const op = ops[i2];
      let startLineNumber = op.startLineNumber;
      let endLineNumber = op.endLineNumber;
      let startColumn = 1;
      let endColumn = model.getLineMaxColumn(endLineNumber);
      if (endLineNumber < model.getLineCount()) {
        endLineNumber += 1;
        endColumn = 1;
      } else if (startLineNumber > 1) {
        startLineNumber -= 1;
        startColumn = model.getLineMaxColumn(startLineNumber);
      }
      edits.push($bD.replace(new $_D(startLineNumber, startColumn, endLineNumber, endColumn), ""));
      cursorState.push(new $_D(startLineNumber - linesDeleted, op.positionColumn, startLineNumber - linesDeleted, op.positionColumn));
      linesDeleted += op.endLineNumber - op.startLineNumber + 1;
    }
    editor.pushUndoStop();
    editor.executeEdits(this.id, edits, cursorState);
    editor.pushUndoStop();
  }
  d(editor) {
    const operations = editor.getSelections().map((s) => {
      let endLineNumber = s.endLineNumber;
      if (s.startLineNumber < s.endLineNumber && s.endColumn === 1) {
        endLineNumber -= 1;
      }
      return {
        startLineNumber: s.startLineNumber,
        selectionStartColumn: s.selectionStartColumn,
        endLineNumber,
        positionColumn: s.positionColumn
      };
    });
    operations.sort((a, b) => {
      if (a.startLineNumber === b.startLineNumber) {
        return a.endLineNumber - b.endLineNumber;
      }
      return a.startLineNumber - b.startLineNumber;
    });
    const mergedOperations = [];
    let previousOperation = operations[0];
    for (let i2 = 1; i2 < operations.length; i2++) {
      if (previousOperation.endLineNumber + 1 >= operations[i2].startLineNumber) {
        previousOperation.endLineNumber = operations[i2].endLineNumber;
      } else {
        mergedOperations.push(previousOperation);
        previousOperation = operations[i2];
      }
    }
    mergedOperations.push(previousOperation);
    return mergedOperations;
  }
};
var $djb = class extends $Z5 {
  constructor() {
    super({
      id: "editor.action.indentLines",
      label: localize2(1304, "Indent Line"),
      precondition: EditorContextKeys.writable,
      kbOpts: {
        kbExpr: EditorContextKeys.editorTextFocus,
        primary: 2048 | 94,
        weight: 100
        /* KeybindingWeight.EditorContrib */
      }
    });
  }
  run(_accessor, editor) {
    const viewModel = editor._getViewModel();
    if (!viewModel) {
      return;
    }
    editor.pushUndoStop();
    editor.executeCommands(this.id, $S6.indent(viewModel.cursorConfig, editor.getModel(), editor.getSelections()));
    editor.pushUndoStop();
  }
};
var OutdentLinesAction = class extends $Z5 {
  constructor() {
    super({
      id: "editor.action.outdentLines",
      label: localize2(1305, "Outdent Line"),
      precondition: EditorContextKeys.writable,
      kbOpts: {
        kbExpr: EditorContextKeys.editorTextFocus,
        primary: 2048 | 92,
        weight: 100
        /* KeybindingWeight.EditorContrib */
      }
    });
  }
  run(_accessor, editor) {
    CoreEditingCommands.Outdent.runEditorCommand(_accessor, editor, null);
  }
};
var $ejb = class extends $Z5 {
  constructor() {
    super({
      id: "editor.action.insertLineBefore",
      label: localize2(1306, "Insert Line Above"),
      precondition: EditorContextKeys.writable,
      kbOpts: {
        kbExpr: EditorContextKeys.editorTextFocus,
        primary: 2048 | 1024 | 3,
        weight: 100
        /* KeybindingWeight.EditorContrib */
      }
    });
  }
  run(_accessor, editor) {
    const viewModel = editor._getViewModel();
    if (!viewModel) {
      return;
    }
    editor.pushUndoStop();
    editor.executeCommands(this.id, $J6.lineInsertBefore(viewModel.cursorConfig, editor.getModel(), editor.getSelections()));
  }
};
var $fjb = class extends $Z5 {
  constructor() {
    super({
      id: "editor.action.insertLineAfter",
      label: localize2(1307, "Insert Line Below"),
      precondition: EditorContextKeys.writable,
      kbOpts: {
        kbExpr: EditorContextKeys.editorTextFocus,
        primary: 2048 | 3,
        weight: 100
        /* KeybindingWeight.EditorContrib */
      }
    });
  }
  run(_accessor, editor) {
    const viewModel = editor._getViewModel();
    if (!viewModel) {
      return;
    }
    editor.pushUndoStop();
    editor.executeCommands(this.id, $J6.lineInsertAfter(viewModel.cursorConfig, editor.getModel(), editor.getSelections()));
  }
};
var $gjb = class extends $Z5 {
  run(_accessor, editor) {
    if (!editor.hasModel()) {
      return;
    }
    const primaryCursor = editor.getSelection();
    const rangesToDelete = this.e(editor);
    const effectiveRanges = [];
    for (let i2 = 0, count = rangesToDelete.length - 1; i2 < count; i2++) {
      const range = rangesToDelete[i2];
      const nextRange = rangesToDelete[i2 + 1];
      if ($9C.intersectRanges(range, nextRange) === null) {
        effectiveRanges.push(range);
      } else {
        rangesToDelete[i2 + 1] = $9C.plusRange(range, nextRange);
      }
    }
    effectiveRanges.push(rangesToDelete[rangesToDelete.length - 1]);
    const endCursorState = this.d(primaryCursor, effectiveRanges);
    const edits = effectiveRanges.map((range) => {
      return $bD.replace(range, "");
    });
    editor.pushUndoStop();
    editor.executeEdits(this.id, edits, endCursorState);
    editor.pushUndoStop();
  }
};
var $hjb = class extends $gjb {
  constructor() {
    super({
      id: "deleteAllLeft",
      label: localize2(1308, "Delete All Left"),
      precondition: EditorContextKeys.writable,
      kbOpts: {
        kbExpr: EditorContextKeys.textInputFocus,
        primary: 0,
        mac: {
          primary: 2048 | 1
          /* KeyCode.Backspace */
        },
        weight: 100
        /* KeybindingWeight.EditorContrib */
      }
    });
  }
  d(primaryCursor, rangesToDelete) {
    let endPrimaryCursor = null;
    const endCursorState = [];
    let deletedLines = 0;
    rangesToDelete.forEach((range) => {
      let endCursor;
      if (range.endColumn === 1 && deletedLines > 0) {
        const newStartLine = range.startLineNumber - deletedLines;
        endCursor = new $_D(newStartLine, range.startColumn, newStartLine, range.startColumn);
      } else {
        endCursor = new $_D(range.startLineNumber, range.startColumn, range.startLineNumber, range.startColumn);
      }
      deletedLines += range.endLineNumber - range.startLineNumber;
      if (range.intersectRanges(primaryCursor)) {
        endPrimaryCursor = endCursor;
      } else {
        endCursorState.push(endCursor);
      }
    });
    if (endPrimaryCursor) {
      endCursorState.unshift(endPrimaryCursor);
    }
    return endCursorState;
  }
  e(editor) {
    const selections = editor.getSelections();
    if (selections === null) {
      return [];
    }
    let rangesToDelete = selections;
    const model = editor.getModel();
    if (model === null) {
      return [];
    }
    rangesToDelete.sort($9C.compareRangesUsingStarts);
    rangesToDelete = rangesToDelete.map((selection) => {
      if (selection.isEmpty()) {
        if (selection.startColumn === 1) {
          const deleteFromLine = Math.max(1, selection.startLineNumber - 1);
          const deleteFromColumn = selection.startLineNumber === 1 ? 1 : model.getLineLength(deleteFromLine) + 1;
          return new $9C(deleteFromLine, deleteFromColumn, selection.startLineNumber, 1);
        } else {
          return new $9C(selection.startLineNumber, 1, selection.startLineNumber, selection.startColumn);
        }
      } else {
        return new $9C(selection.startLineNumber, 1, selection.endLineNumber, selection.endColumn);
      }
    });
    return rangesToDelete;
  }
};
var $ijb = class extends $gjb {
  constructor() {
    super({
      id: "deleteAllRight",
      label: localize2(1309, "Delete All Right"),
      precondition: EditorContextKeys.writable,
      kbOpts: {
        kbExpr: EditorContextKeys.textInputFocus,
        primary: 0,
        mac: { primary: 256 | 41, secondary: [
          2048 | 20
          /* KeyCode.Delete */
        ] },
        weight: 100
        /* KeybindingWeight.EditorContrib */
      }
    });
  }
  d(primaryCursor, rangesToDelete) {
    let endPrimaryCursor = null;
    const endCursorState = [];
    for (let i2 = 0, len = rangesToDelete.length, offset = 0; i2 < len; i2++) {
      const range = rangesToDelete[i2];
      const endCursor = new $_D(range.startLineNumber - offset, range.startColumn, range.startLineNumber - offset, range.startColumn);
      if (range.intersectRanges(primaryCursor)) {
        endPrimaryCursor = endCursor;
      } else {
        endCursorState.push(endCursor);
      }
    }
    if (endPrimaryCursor) {
      endCursorState.unshift(endPrimaryCursor);
    }
    return endCursorState;
  }
  e(editor) {
    const model = editor.getModel();
    if (model === null) {
      return [];
    }
    const selections = editor.getSelections();
    if (selections === null) {
      return [];
    }
    const rangesToDelete = selections.map((sel) => {
      if (sel.isEmpty()) {
        const maxColumn = model.getLineMaxColumn(sel.startLineNumber);
        if (sel.startColumn === maxColumn) {
          return new $9C(sel.startLineNumber, sel.startColumn, sel.startLineNumber + 1, 1);
        } else {
          return new $9C(sel.startLineNumber, sel.startColumn, sel.startLineNumber, maxColumn);
        }
      }
      return sel;
    });
    rangesToDelete.sort($9C.compareRangesUsingStarts);
    return rangesToDelete;
  }
};
var $jjb = class extends $Z5 {
  constructor() {
    super({
      id: "editor.action.joinLines",
      label: localize2(1310, "Join Lines"),
      precondition: EditorContextKeys.writable,
      kbOpts: {
        kbExpr: EditorContextKeys.editorTextFocus,
        primary: 0,
        mac: {
          primary: 256 | 40
          /* KeyCode.KeyJ */
        },
        weight: 100
        /* KeybindingWeight.EditorContrib */
      }
    });
  }
  run(_accessor, editor) {
    const selections = editor.getSelections();
    if (selections === null) {
      return;
    }
    let primaryCursor = editor.getSelection();
    if (primaryCursor === null) {
      return;
    }
    selections.sort($9C.compareRangesUsingStarts);
    const reducedSelections = [];
    const lastSelection = selections.reduce((previousValue, currentValue) => {
      if (previousValue.isEmpty()) {
        if (previousValue.endLineNumber === currentValue.startLineNumber) {
          if (primaryCursor.equalsSelection(previousValue)) {
            primaryCursor = currentValue;
          }
          return currentValue;
        }
        if (currentValue.startLineNumber > previousValue.endLineNumber + 1) {
          reducedSelections.push(previousValue);
          return currentValue;
        } else {
          return new $_D(previousValue.startLineNumber, previousValue.startColumn, currentValue.endLineNumber, currentValue.endColumn);
        }
      } else {
        if (currentValue.startLineNumber > previousValue.endLineNumber) {
          reducedSelections.push(previousValue);
          return currentValue;
        } else {
          return new $_D(previousValue.startLineNumber, previousValue.startColumn, currentValue.endLineNumber, currentValue.endColumn);
        }
      }
    });
    reducedSelections.push(lastSelection);
    const model = editor.getModel();
    if (model === null) {
      return;
    }
    const edits = [];
    const endCursorState = [];
    let endPrimaryCursor = primaryCursor;
    let lineOffset = 0;
    for (let i2 = 0, len = reducedSelections.length; i2 < len; i2++) {
      const selection = reducedSelections[i2];
      const startLineNumber = selection.startLineNumber;
      const startColumn = 1;
      let columnDeltaOffset = 0;
      let endLineNumber, endColumn;
      const selectionEndPositionOffset = model.getLineLength(selection.endLineNumber) - selection.endColumn;
      if (selection.isEmpty() || selection.startLineNumber === selection.endLineNumber) {
        const position = selection.getStartPosition();
        if (position.lineNumber < model.getLineCount()) {
          endLineNumber = startLineNumber + 1;
          endColumn = model.getLineMaxColumn(endLineNumber);
        } else {
          endLineNumber = position.lineNumber;
          endColumn = model.getLineMaxColumn(position.lineNumber);
        }
      } else {
        endLineNumber = selection.endLineNumber;
        endColumn = model.getLineMaxColumn(endLineNumber);
      }
      let trimmedLinesContent = model.getLineContent(startLineNumber);
      for (let i3 = startLineNumber + 1; i3 <= endLineNumber; i3++) {
        const lineText = model.getLineContent(i3);
        const firstNonWhitespaceIdx = model.getLineFirstNonWhitespaceColumn(i3);
        if (firstNonWhitespaceIdx >= 1) {
          let insertSpace = true;
          if (trimmedLinesContent === "") {
            insertSpace = false;
          }
          if (insertSpace && (trimmedLinesContent.charAt(trimmedLinesContent.length - 1) === " " || trimmedLinesContent.charAt(trimmedLinesContent.length - 1) === "	")) {
            insertSpace = false;
            trimmedLinesContent = trimmedLinesContent.replace(/[\s\uFEFF\xA0]+$/g, " ");
          }
          const lineTextWithoutIndent = lineText.substr(firstNonWhitespaceIdx - 1);
          trimmedLinesContent += (insertSpace ? " " : "") + lineTextWithoutIndent;
          if (insertSpace) {
            columnDeltaOffset = lineTextWithoutIndent.length + 1;
          } else {
            columnDeltaOffset = lineTextWithoutIndent.length;
          }
        } else {
          columnDeltaOffset = 0;
        }
      }
      const deleteSelection = new $9C(startLineNumber, startColumn, endLineNumber, endColumn);
      if (!deleteSelection.isEmpty()) {
        let resultSelection;
        if (selection.isEmpty()) {
          edits.push($bD.replace(deleteSelection, trimmedLinesContent));
          resultSelection = new $_D(deleteSelection.startLineNumber - lineOffset, trimmedLinesContent.length - columnDeltaOffset + 1, startLineNumber - lineOffset, trimmedLinesContent.length - columnDeltaOffset + 1);
        } else {
          if (selection.startLineNumber === selection.endLineNumber) {
            edits.push($bD.replace(deleteSelection, trimmedLinesContent));
            resultSelection = new $_D(selection.startLineNumber - lineOffset, selection.startColumn, selection.endLineNumber - lineOffset, selection.endColumn);
          } else {
            edits.push($bD.replace(deleteSelection, trimmedLinesContent));
            resultSelection = new $_D(selection.startLineNumber - lineOffset, selection.startColumn, selection.startLineNumber - lineOffset, trimmedLinesContent.length - selectionEndPositionOffset);
          }
        }
        if ($9C.intersectRanges(deleteSelection, primaryCursor) !== null) {
          endPrimaryCursor = resultSelection;
        } else {
          endCursorState.push(resultSelection);
        }
      }
      lineOffset += deleteSelection.endLineNumber - deleteSelection.startLineNumber;
    }
    endCursorState.unshift(endPrimaryCursor);
    editor.pushUndoStop();
    editor.executeEdits(this.id, edits, endCursorState);
    editor.pushUndoStop();
  }
};
var $kjb = class extends $Z5 {
  constructor() {
    super({
      id: "editor.action.transpose",
      label: localize2(1311, "Transpose Characters around the Cursor"),
      precondition: EditorContextKeys.writable
    });
  }
  run(_accessor, editor) {
    const selections = editor.getSelections();
    if (selections === null) {
      return;
    }
    const model = editor.getModel();
    if (model === null) {
      return;
    }
    const commands2 = [];
    for (let i2 = 0, len = selections.length; i2 < len; i2++) {
      const selection = selections[i2];
      if (!selection.isEmpty()) {
        continue;
      }
      const cursor = selection.getStartPosition();
      const maxColumn = model.getLineMaxColumn(cursor.lineNumber);
      if (cursor.column >= maxColumn) {
        if (cursor.lineNumber === model.getLineCount()) {
          continue;
        }
        const deleteSelection = new $9C(cursor.lineNumber, Math.max(1, cursor.column - 1), cursor.lineNumber + 1, 1);
        const chars = model.getValueInRange(deleteSelection).split("").reverse().join("");
        commands2.push(new $b6(new $_D(cursor.lineNumber, Math.max(1, cursor.column - 1), cursor.lineNumber + 1, 1), chars));
      } else {
        const deleteSelection = new $9C(cursor.lineNumber, Math.max(1, cursor.column - 1), cursor.lineNumber, cursor.column + 1);
        const chars = model.getValueInRange(deleteSelection).split("").reverse().join("");
        commands2.push(new $h6(deleteSelection, chars, new $_D(cursor.lineNumber, cursor.column + 1, cursor.lineNumber, cursor.column + 1)));
      }
    }
    editor.pushUndoStop();
    editor.executeCommands(this.id, commands2);
    editor.pushUndoStop();
  }
};
var $ljb = class extends $Z5 {
  run(_accessor, editor) {
    const selections = editor.getSelections();
    if (selections === null) {
      return;
    }
    const model = editor.getModel();
    if (model === null) {
      return;
    }
    const wordSeparators2 = editor.getOption(
      136
      /* EditorOption.wordSeparators */
    );
    const textEdits = [];
    for (const selection of selections) {
      if (selection.isEmpty()) {
        const cursor = selection.getStartPosition();
        const word = editor.getConfiguredWordAtPosition(cursor);
        if (!word) {
          continue;
        }
        const wordRange = new $9C(cursor.lineNumber, word.startColumn, cursor.lineNumber, word.endColumn);
        const text2 = model.getValueInRange(wordRange);
        textEdits.push($bD.replace(wordRange, this.d(text2, wordSeparators2)));
      } else {
        const text2 = model.getValueInRange(selection);
        textEdits.push($bD.replace(selection, this.d(text2, wordSeparators2)));
      }
    }
    editor.pushUndoStop();
    editor.executeEdits(this.id, textEdits);
    editor.pushUndoStop();
  }
};
var $mjb = class extends $ljb {
  constructor() {
    super({
      id: "editor.action.transformToUppercase",
      label: localize2(1312, "Transform to Uppercase"),
      precondition: EditorContextKeys.writable
    });
  }
  d(text2, wordSeparators2) {
    return text2.toLocaleUpperCase();
  }
};
var $njb = class extends $ljb {
  constructor() {
    super({
      id: "editor.action.transformToLowercase",
      label: localize2(1313, "Transform to Lowercase"),
      precondition: EditorContextKeys.writable
    });
  }
  d(text2, wordSeparators2) {
    return text2.toLocaleLowerCase();
  }
};
var BackwardsCompatibleRegExp = class {
  constructor(e, f) {
    this.e = e;
    this.f = f;
    this.c = null;
    this.d = false;
  }
  get() {
    if (!this.d) {
      this.d = true;
      try {
        this.c = new RegExp(this.e, this.f);
      } catch (err) {
      }
    }
    return this.c;
  }
  isSupported() {
    return this.get() !== null;
  }
};
var $ojb = class _$ojb extends $ljb {
  static {
    this.titleBoundary = new BackwardsCompatibleRegExp("(^|[^\\p{L}\\p{N}']|((^|\\P{L})'))\\p{L}", "gmu");
  }
  constructor() {
    super({
      id: "editor.action.transformToTitlecase",
      label: localize2(1314, "Transform to Title Case"),
      precondition: EditorContextKeys.writable
    });
  }
  d(text2, wordSeparators2) {
    const titleBoundary = _$ojb.titleBoundary.get();
    if (!titleBoundary) {
      return text2;
    }
    return text2.toLocaleLowerCase().replace(titleBoundary, (b) => b.toLocaleUpperCase());
  }
};
var $pjb = class _$pjb extends $ljb {
  static {
    this.caseBoundary = new BackwardsCompatibleRegExp("(\\p{Ll})(\\p{Lu})", "gmu");
  }
  static {
    this.singleLetters = new BackwardsCompatibleRegExp("(\\p{Lu}|\\p{N})(\\p{Lu})(\\p{Ll})", "gmu");
  }
  constructor() {
    super({
      id: "editor.action.transformToSnakecase",
      label: localize2(1315, "Transform to Snake Case"),
      precondition: EditorContextKeys.writable
    });
  }
  d(text2, wordSeparators2) {
    const caseBoundary = _$pjb.caseBoundary.get();
    const singleLetters = _$pjb.singleLetters.get();
    if (!caseBoundary || !singleLetters) {
      return text2;
    }
    return text2.replace(caseBoundary, "$1_$2").replace(singleLetters, "$1_$2$3").toLocaleLowerCase();
  }
};
var $qjb = class _$qjb extends $ljb {
  static {
    this.wordBoundary = new BackwardsCompatibleRegExp("[_\\s-]", "gm");
  }
  constructor() {
    super({
      id: "editor.action.transformToCamelcase",
      label: localize2(1316, "Transform to Camel Case"),
      precondition: EditorContextKeys.writable
    });
  }
  d(text2, wordSeparators2) {
    const wordBoundary = _$qjb.wordBoundary.get();
    if (!wordBoundary) {
      return text2;
    }
    const words = text2.split(wordBoundary);
    const firstWord = words.shift();
    return firstWord + words.map((word) => word.substring(0, 1).toLocaleUpperCase() + word.substring(1)).join("");
  }
};
var $rjb = class _$rjb extends $ljb {
  static {
    this.wordBoundary = new BackwardsCompatibleRegExp("[_\\s-]", "gm");
  }
  static {
    this.wordBoundaryToMaintain = new BackwardsCompatibleRegExp("(?<=\\.)", "gm");
  }
  constructor() {
    super({
      id: "editor.action.transformToPascalcase",
      label: localize2(1317, "Transform to Pascal Case"),
      precondition: EditorContextKeys.writable
    });
  }
  d(text2, wordSeparators2) {
    const wordBoundary = _$rjb.wordBoundary.get();
    const wordBoundaryToMaintain = _$rjb.wordBoundaryToMaintain.get();
    if (!wordBoundary || !wordBoundaryToMaintain) {
      return text2;
    }
    const wordsWithMaintainBoundaries = text2.split(wordBoundaryToMaintain);
    const words = wordsWithMaintainBoundaries.map((word) => word.split(wordBoundary)).flat();
    return words.map((word) => word.substring(0, 1).toLocaleUpperCase() + word.substring(1)).join("");
  }
};
var $sjb = class _$sjb extends $ljb {
  static isSupported() {
    const areAllRegexpsSupported = [
      this.e,
      this.h,
      this.j
    ].every((regexp) => regexp.isSupported());
    return areAllRegexpsSupported;
  }
  static {
    this.e = new BackwardsCompatibleRegExp("(\\p{Ll})(\\p{Lu})", "gmu");
  }
  static {
    this.h = new BackwardsCompatibleRegExp("(\\p{Lu}|\\p{N})(\\p{Lu}\\p{Ll})", "gmu");
  }
  static {
    this.j = new BackwardsCompatibleRegExp("(\\S)(_)(\\S)", "gm");
  }
  constructor() {
    super({
      id: "editor.action.transformToKebabcase",
      label: localize2(1318, "Transform to Kebab Case"),
      precondition: EditorContextKeys.writable
    });
  }
  d(text2, _) {
    const caseBoundary = _$sjb.e.get();
    const singleLetters = _$sjb.h.get();
    const underscoreBoundary = _$sjb.j.get();
    if (!caseBoundary || !singleLetters || !underscoreBoundary) {
      return text2;
    }
    return text2.replace(underscoreBoundary, "$1-$3").replace(caseBoundary, "$1-$2").replace(singleLetters, "$1-$2").toLocaleLowerCase();
  }
};
$55(CopyLinesUpAction);
$55(CopyLinesDownAction);
$55($9ib);
$55(MoveLinesUpAction);
$55(MoveLinesDownAction);
$55($$ib);
$55($_ib);
$55($ajb);
$55($bjb);
$55($cjb);
$55($djb);
$55(OutdentLinesAction);
$55($ejb);
$55($fjb);
$55($hjb);
$55($ijb);
$55($jjb);
$55($kjb);
$55($mjb);
$55($njb);
if ($pjb.caseBoundary.isSupported() && $pjb.singleLetters.isSupported()) {
  $55($pjb);
}
if ($qjb.wordBoundary.isSupported()) {
  $55($qjb);
}
if ($rjb.wordBoundary.isSupported()) {
  $55($rjb);
}
if ($ojb.titleBoundary.isSupported()) {
  $55($ojb);
}
if ($sjb.isSupported()) {
  $55($sjb);
}

// out-build/vs/editor/contrib/linkedEditing/browser/linkedEditing.js
var $ujb_1;
var $tjb = new $nn("LinkedEditingInputVisible", false);
var DECORATION_CLASS_NAME2 = "linked-editing-decoration";
var $ujb = class $ujb2 extends $3c {
  static {
    $ujb_1 = this;
  }
  static {
    this.ID = "editor.contrib.linkedEditing";
  }
  static {
    this.a = $WI.register({
      description: "linked-editing",
      stickiness: 0,
      className: DECORATION_CLASS_NAME2
    });
  }
  static get(editor) {
    return editor.getContribution($ujb_1.ID);
  }
  constructor(editor, contextKeyService, languageFeaturesService, G, languageFeatureDebounceService) {
    super();
    this.G = G;
    this.y = 0;
    this.F = this.B(new $2c());
    this.f = editor;
    this.g = languageFeaturesService.linkedEditingRangeProvider;
    this.h = false;
    this.j = $tjb.bindTo(contextKeyService);
    this.m = languageFeatureDebounceService.for(this.g, "Linked Editing", { max: 200 });
    this.w = this.f.createDecorationsCollection();
    this.z = null;
    this.C = null;
    this.D = false;
    this.F = this.B(new $2c());
    this.n = null;
    this.r = null;
    this.s = null;
    this.t = null;
    this.u = null;
    this.B(this.f.onDidChangeModel(() => this.H(true)));
    this.B(this.f.onDidChangeConfiguration((e) => {
      if (e.hasChanged(
        71
        /* EditorOption.linkedEditing */
      ) || e.hasChanged(
        98
        /* EditorOption.renameOnType */
      )) {
        this.H(false);
      }
    }));
    this.B(this.g.onDidChange(() => this.H(false)));
    this.B(this.f.onDidChangeModelLanguage(() => this.H(true)));
    this.H(true);
  }
  H(forceRefresh) {
    const model = this.f.getModel();
    const isEnabled = model !== null && (this.f.getOption(
      71
      /* EditorOption.linkedEditing */
    ) || this.f.getOption(
      98
      /* EditorOption.renameOnType */
    )) && this.g.has(model);
    if (isEnabled === this.h && !forceRefresh) {
      return;
    }
    this.h = isEnabled;
    this.clearRanges();
    this.F.clear();
    if (!isEnabled || model === null) {
      return;
    }
    this.F.add(Event2.runAndSubscribe(model.onDidChangeLanguageConfiguration, () => {
      this.z = this.G.getLanguageConfiguration(model.getLanguageId()).getWordDefinition();
    }));
    const rangeUpdateScheduler = new $Sh(this.m.get(model));
    const triggerRangeUpdate = () => {
      this.n = rangeUpdateScheduler.trigger(() => this.updateRanges(), this.b ?? this.m.get(model));
    };
    const rangeSyncScheduler = new $Sh(0);
    const triggerRangeSync = (token) => {
      this.r = rangeSyncScheduler.trigger(() => this.I(token));
    };
    this.F.add(this.f.onDidChangeCursorPosition(() => {
      triggerRangeUpdate();
    }));
    this.F.add(this.f.onDidChangeModelContent((e) => {
      if (!this.D) {
        if (this.w.length > 0) {
          const referenceRange = this.w.getRange(0);
          if (referenceRange && e.changes.every((c) => referenceRange.intersectRanges(c.range))) {
            triggerRangeSync(this.y);
            return;
          }
        }
      }
      triggerRangeUpdate();
    }));
    this.F.add({
      dispose: () => {
        rangeUpdateScheduler.dispose();
        rangeSyncScheduler.dispose();
      }
    });
    this.updateRanges();
  }
  I(token) {
    if (!this.f.hasModel() || token !== this.y || this.w.length === 0) {
      return;
    }
    const model = this.f.getModel();
    const referenceRange = this.w.getRange(0);
    if (!referenceRange || referenceRange.startLineNumber !== referenceRange.endLineNumber) {
      return this.clearRanges();
    }
    const referenceValue = model.getValueInRange(referenceRange);
    if (this.C) {
      const match = referenceValue.match(this.C);
      const matchLength = match ? match[0].length : 0;
      if (matchLength !== referenceValue.length) {
        return this.clearRanges();
      }
    }
    const edits = [];
    for (let i2 = 1, len = this.w.length; i2 < len; i2++) {
      const mirrorRange = this.w.getRange(i2);
      if (!mirrorRange) {
        continue;
      }
      if (mirrorRange.startLineNumber !== mirrorRange.endLineNumber) {
        edits.push({
          range: mirrorRange,
          text: referenceValue
        });
      } else {
        let oldValue = model.getValueInRange(mirrorRange);
        let newValue = referenceValue;
        let rangeStartColumn = mirrorRange.startColumn;
        let rangeEndColumn = mirrorRange.endColumn;
        const commonPrefixLength = $3f(oldValue, newValue);
        rangeStartColumn += commonPrefixLength;
        oldValue = oldValue.substr(commonPrefixLength);
        newValue = newValue.substr(commonPrefixLength);
        const commonSuffixLength = $4f(oldValue, newValue);
        rangeEndColumn -= commonSuffixLength;
        oldValue = oldValue.substr(0, oldValue.length - commonSuffixLength);
        newValue = newValue.substr(0, newValue.length - commonSuffixLength);
        if (rangeStartColumn !== rangeEndColumn || newValue.length !== 0) {
          edits.push({
            range: new $9C(mirrorRange.startLineNumber, rangeStartColumn, mirrorRange.endLineNumber, rangeEndColumn),
            text: newValue
          });
        }
      }
    }
    if (edits.length === 0) {
      return;
    }
    try {
      this.f.popUndoStop();
      this.D = true;
      const prevEditOperationType = this.f._getViewModel().getPrevEditOperationType();
      this.f.executeEdits("linkedEditing", edits);
      this.f._getViewModel().setPrevEditOperationType(prevEditOperationType);
    } finally {
      this.D = false;
    }
  }
  dispose() {
    this.clearRanges();
    super.dispose();
  }
  clearRanges() {
    this.j.set(false);
    this.w.clear();
    if (this.s) {
      this.s.cancel();
      this.s = null;
      this.t = null;
    }
  }
  get currentUpdateTriggerPromise() {
    return this.n || Promise.resolve();
  }
  get currentSyncTriggerPromise() {
    return this.r || Promise.resolve();
  }
  async updateRanges(force = false) {
    if (!this.f.hasModel()) {
      this.clearRanges();
      return;
    }
    const position = this.f.getPosition();
    if (!this.h && !force || this.f.getSelections().length > 1) {
      this.clearRanges();
      return;
    }
    const model = this.f.getModel();
    const modelVersionId = model.getVersionId();
    if (this.t && this.u === modelVersionId) {
      if (position.equals(this.t)) {
        return;
      }
      if (this.w.length > 0) {
        const range = this.w.getRange(0);
        if (range && range.containsPosition(position)) {
          return;
        }
      }
    }
    this.clearRanges();
    this.t = position;
    this.u = modelVersionId;
    const currentRequestCts = this.s = new $ad();
    try {
      const sw = new $te(false);
      const response = await getLinkedEditingRanges(this.g, model, position, currentRequestCts.token);
      this.m.update(model, sw.elapsed());
      if (currentRequestCts !== this.s) {
        return;
      }
      this.s = null;
      if (modelVersionId !== model.getVersionId()) {
        return;
      }
      let ranges = [];
      if (response?.ranges) {
        ranges = response.ranges;
      }
      this.C = response?.wordPattern || this.z;
      let foundReferenceRange = false;
      for (let i2 = 0, len = ranges.length; i2 < len; i2++) {
        if ($9C.containsPosition(ranges[i2], position)) {
          foundReferenceRange = true;
          if (i2 !== 0) {
            const referenceRange = ranges[i2];
            ranges.splice(i2, 1);
            ranges.unshift(referenceRange);
          }
          break;
        }
      }
      if (!foundReferenceRange) {
        this.clearRanges();
        return;
      }
      const decorations = ranges.map((range) => ({ range, options: $ujb_1.a }));
      this.j.set(true);
      this.w.set(decorations);
      this.y++;
    } catch (err) {
      if (!$kb(err)) {
        $gb(err);
      }
      if (this.s === currentRequestCts || !this.s) {
        this.clearRanges();
      }
    }
  }
  // for testing
  setDebounceDuration(timeInMS) {
    this.b = timeInMS;
  }
};
$ujb = $ujb_1 = __decorate([
  __param(1, $on),
  __param(2, $mP),
  __param(3, $NF),
  __param(4, $tbb)
], $ujb);
var $vjb = class extends $Z5 {
  constructor() {
    super({
      id: "editor.action.linkedEditing",
      label: localize2(1320, "Start Linked Editing"),
      precondition: $7m.and(EditorContextKeys.writable, EditorContextKeys.hasRenameProvider),
      kbOpts: {
        kbExpr: EditorContextKeys.editorTextFocus,
        primary: 2048 | 1024 | 60,
        weight: 100
        /* KeybindingWeight.EditorContrib */
      }
    });
  }
  runCommand(accessor, args2) {
    const editorService = accessor.get($U5);
    const [uri, pos] = Array.isArray(args2) && args2 || [void 0, void 0];
    if (URI.isUri(uri) && $8C.isIPosition(pos)) {
      return editorService.openCodeEditor({ resource: uri }, editorService.getActiveCodeEditor()).then((editor) => {
        if (!editor) {
          return;
        }
        editor.setPosition(pos);
        editor.invokeWithinContext((accessor2) => {
          this.u(accessor2, editor);
          return this.run(accessor2, editor);
        });
      }, $gb);
    }
    return super.runCommand(accessor, args2);
  }
  run(_accessor, editor) {
    const controller = $ujb.get(editor);
    if (controller) {
      return Promise.resolve(controller.updateRanges(true));
    }
    return Promise.resolve();
  }
};
var LinkedEditingCommand = $Y5.bindToContribution($ujb.get);
$45(new LinkedEditingCommand({
  id: "cancelLinkedEditingInput",
  precondition: $tjb,
  handler: (x) => x.clearRanges(),
  kbOpts: {
    kbExpr: EditorContextKeys.editorTextFocus,
    weight: 100 + 99,
    primary: 9,
    secondary: [
      1024 | 9
      /* KeyCode.Escape */
    ]
  }
}));
function getLinkedEditingRanges(providers2, model, position, token) {
  const orderedByScore = providers2.ordered(model);
  return $Zh(orderedByScore.map((provider) => async () => {
    try {
      return await provider.provideLinkedEditingRanges(model, position, token);
    } catch (e) {
      $hb(e);
      return void 0;
    }
  }), (result) => !!result && $Qb(result?.ranges));
}
var $wjb = $5n("editor.linkedEditingBackground", { dark: $Vn.fromHex("#f00").transparent(0.3), light: $Vn.fromHex("#f00").transparent(0.3), hcDark: $Vn.fromHex("#f00").transparent(0.3), hcLight: $Vn.white }, localize(1319, null));
$35("_executeLinkedEditingProvider", (_accessor, model, position) => {
  const { linkedEditingRangeProvider } = _accessor.get($mP);
  return getLinkedEditingRanges(linkedEditingRangeProvider, model, position, CancellationToken.None);
});
$85(
  $ujb.ID,
  $ujb,
  1
  /* EditorContributionInstantiation.AfterFirstRender */
);
$55($vjb);

// out-build/vs/editor/contrib/links/browser/getLinks.js
var Link = class {
  constructor(link2, provider) {
    this.a = link2;
    this.b = provider;
  }
  toJSON() {
    return {
      range: this.range,
      url: this.url,
      tooltip: this.tooltip
    };
  }
  get range() {
    return this.a.range;
  }
  get url() {
    return this.a.url;
  }
  get tooltip() {
    return this.a.tooltip;
  }
  async resolve(token) {
    if (this.a.url) {
      return this.a.url;
    }
    if (typeof this.b.resolveLink === "function") {
      return Promise.resolve(this.b.resolveLink(this.a, token)).then((value) => {
        this.a = value || this.a;
        if (this.a.url) {
          return this.resolve(token);
        }
        return Promise.reject(new Error("missing"));
      });
    }
    return Promise.reject(new Error("missing"));
  }
};
var $yjb = class _$yjb {
  constructor(tuples) {
    this.a = new $2c();
    let links = [];
    for (const [list2, provider] of tuples) {
      const newLinks = list2.links.map((link2) => new Link(link2, provider));
      links = _$yjb.b(links, newLinks);
      if ($Wc(list2)) {
        this.a.add(list2);
      }
    }
    this.links = links;
  }
  dispose() {
    this.a.dispose();
    this.links.length = 0;
  }
  static b(oldLinks, newLinks) {
    const result = [];
    let oldIndex;
    let oldLen;
    let newIndex;
    let newLen;
    for (oldIndex = 0, newIndex = 0, oldLen = oldLinks.length, newLen = newLinks.length; oldIndex < oldLen && newIndex < newLen; ) {
      const oldLink = oldLinks[oldIndex];
      const newLink = newLinks[newIndex];
      if ($9C.areIntersectingOrTouching(oldLink.range, newLink.range)) {
        oldIndex++;
        continue;
      }
      const comparisonResult = $9C.compareRangesUsingStarts(oldLink.range, newLink.range);
      if (comparisonResult < 0) {
        result.push(oldLink);
        oldIndex++;
      } else {
        result.push(newLink);
        newIndex++;
      }
    }
    for (; oldIndex < oldLen; oldIndex++) {
      result.push(oldLinks[oldIndex]);
    }
    for (; newIndex < newLen; newIndex++) {
      result.push(newLinks[newIndex]);
    }
    return result;
  }
};
function $zjb(providers2, model, token) {
  const lists = [];
  const promises = providers2.ordered(model).reverse().map((provider, i2) => {
    return Promise.resolve(provider.provideLinks(model, token)).then((result) => {
      if (result) {
        lists[i2] = [result, provider];
      }
    }, $hb);
  });
  return Promise.all(promises).then(() => {
    const result = new $yjb($Mb(lists));
    if (!token.isCancellationRequested) {
      return result;
    }
    result.dispose();
    return new $yjb([]);
  });
}
$tn.registerCommand("_executeLinkProvider", async (accessor, ...args2) => {
  let [uri, resolveCount] = args2;
  $Jg(uri instanceof URI);
  if (typeof resolveCount !== "number") {
    resolveCount = 0;
  }
  const { linkProvider } = accessor.get($mP);
  const model = accessor.get($sG).getModel(uri);
  if (!model) {
    return [];
  }
  const list2 = await $zjb(linkProvider, model, CancellationToken.None);
  if (!list2) {
    return [];
  }
  for (let i2 = 0; i2 < Math.min(resolveCount, list2.links.length); i2++) {
    await list2.links[i2].resolve(CancellationToken.None);
  }
  const result = list2.links.slice(0);
  list2.dispose();
  return result;
});

// out-build/vs/editor/contrib/links/browser/links.js
var $Ajb_1;
var $Ajb = class $Ajb2 extends $3c {
  static {
    $Ajb_1 = this;
  }
  static {
    this.ID = "editor.linkDetector";
  }
  static get(editor) {
    return editor.getContribution($Ajb_1.ID);
  }
  constructor(m, n, r2, s, languageFeatureDebounceService) {
    super();
    this.m = m;
    this.n = n;
    this.r = r2;
    this.s = s;
    this.a = this.s.linkProvider;
    this.b = languageFeatureDebounceService.for(this.a, "Links", { min: 1e3, max: 4e3 });
    this.c = this.B(new $8h(() => this.t(), 1e3));
    this.f = null;
    this.g = null;
    this.j = {};
    this.h = null;
    const clickLinkGesture = this.B(new $6db(m));
    this.B(clickLinkGesture.onMouseMoveOrRelevantKeyDown(([mouseEvent, keyboardEvent]) => {
      this.w(mouseEvent, keyboardEvent);
    }));
    this.B(clickLinkGesture.onExecute((e) => {
      this.z(e);
    }));
    this.B(clickLinkGesture.onCancel((e) => {
      this.y();
    }));
    this.B(m.onDidChangeConfiguration((e) => {
      if (!e.hasChanged(
        72
        /* EditorOption.links */
      )) {
        return;
      }
      this.u([]);
      this.D();
      this.c.schedule(0);
    }));
    this.B(m.onDidChangeModelContent((e) => {
      if (!this.m.hasModel()) {
        return;
      }
      this.c.schedule(this.b.get(this.m.getModel()));
    }));
    this.B(m.onDidChangeModel((e) => {
      this.j = {};
      this.h = null;
      this.D();
      this.c.schedule(0);
    }));
    this.B(m.onDidChangeModelLanguage((e) => {
      this.D();
      this.c.schedule(0);
    }));
    this.B(this.a.onDidChange((e) => {
      this.D();
      this.c.schedule(0);
    }));
    this.c.schedule(0);
  }
  async t() {
    if (!this.m.hasModel() || !this.m.getOption(
      72
      /* EditorOption.links */
    )) {
      return;
    }
    const model = this.m.getModel();
    if (model.isTooLargeForSyncing()) {
      return;
    }
    if (!this.a.has(model)) {
      return;
    }
    if (this.g) {
      this.g.dispose();
      this.g = null;
    }
    this.f = $Hh((token) => $zjb(this.a, model, token));
    try {
      const sw = new $te(false);
      this.g = await this.f;
      this.b.update(model, sw.elapsed());
      if (model.isDisposed()) {
        return;
      }
      this.u(this.g.links);
    } catch (err) {
      $gb(err);
    } finally {
      this.f = null;
    }
  }
  u(links) {
    const useMetaKey = this.m.getOption(
      79
      /* EditorOption.multiCursorModifier */
    ) === "altKey";
    const oldDecorations = [];
    const keys = Object.keys(this.j);
    for (const decorationId of keys) {
      const occurence = this.j[decorationId];
      oldDecorations.push(occurence.decorationId);
    }
    const newDecorations = [];
    if (links) {
      for (const link2 of links) {
        newDecorations.push(LinkOccurrence.decoration(link2, useMetaKey));
      }
    }
    this.m.changeDecorations((changeAccessor) => {
      const decorations = changeAccessor.deltaDecorations(oldDecorations, newDecorations);
      this.j = {};
      this.h = null;
      for (let i2 = 0, len = decorations.length; i2 < len; i2++) {
        const occurence = new LinkOccurrence(links[i2], decorations[i2]);
        this.j[occurence.decorationId] = occurence;
      }
    });
  }
  w(mouseEvent, withKey) {
    const useMetaKey = this.m.getOption(
      79
      /* EditorOption.multiCursorModifier */
    ) === "altKey";
    if (this.C(mouseEvent, withKey)) {
      this.y();
      const occurrence = this.getLinkOccurrence(mouseEvent.target.position);
      if (occurrence) {
        this.m.changeDecorations((changeAccessor) => {
          occurrence.activate(changeAccessor, useMetaKey);
          this.h = occurrence.decorationId;
        });
      }
    } else {
      this.y();
    }
  }
  y() {
    const useMetaKey = this.m.getOption(
      79
      /* EditorOption.multiCursorModifier */
    ) === "altKey";
    if (this.h) {
      const occurrence = this.j[this.h];
      if (occurrence) {
        this.m.changeDecorations((changeAccessor) => {
          occurrence.deactivate(changeAccessor, useMetaKey);
        });
      }
      this.h = null;
    }
  }
  z(mouseEvent) {
    if (!this.C(mouseEvent)) {
      return;
    }
    const occurrence = this.getLinkOccurrence(mouseEvent.target.position);
    if (!occurrence) {
      return;
    }
    this.openLinkOccurrence(
      occurrence,
      mouseEvent.hasSideBySideModifier,
      true
      /* from user gesture */
    );
  }
  openLinkOccurrence(occurrence, openToSide, fromUserGesture = false) {
    if (!this.n) {
      return;
    }
    const { link: link2 } = occurrence;
    link2.resolve(CancellationToken.None).then((uri) => {
      if (typeof uri === "string" && this.m.hasModel()) {
        const modelUri = this.m.getModel().uri;
        if (modelUri.scheme === Schemas.file && uri.startsWith(`${Schemas.file}:`)) {
          const parsedUri = URI.parse(uri);
          if (parsedUri.scheme === Schemas.file) {
            const fsPath = $jh(parsedUri);
            let relativePath = null;
            if (fsPath.startsWith("/./") || fsPath.startsWith("\\.\\")) {
              relativePath = `.${fsPath.substr(1)}`;
            } else if (fsPath.startsWith("//./") || fsPath.startsWith("\\\\.\\")) {
              relativePath = `.${fsPath.substr(2)}`;
            }
            if (relativePath) {
              uri = $vh(modelUri, relativePath);
            }
          }
        }
      }
      return this.n.open(uri, { openToSide, fromUserGesture, allowContributedOpeners: true, allowCommands: true, fromWorkspace: true });
    }, (err) => {
      const messageOrError = err instanceof Error ? err.message : err;
      if (messageOrError === "invalid") {
        this.r.warn(localize(1321, null, link2.url.toString()));
      } else if (messageOrError === "missing") {
        this.r.warn(localize(1322, null));
      } else {
        $gb(err);
      }
    });
  }
  getLinkOccurrence(position) {
    if (!this.m.hasModel() || !position) {
      return null;
    }
    const decorations = this.m.getModel().getDecorationsInRange({
      startLineNumber: position.lineNumber,
      startColumn: position.column,
      endLineNumber: position.lineNumber,
      endColumn: position.column
    }, 0, true);
    for (const decoration3 of decorations) {
      const currentOccurrence = this.j[decoration3.id];
      if (currentOccurrence) {
        return currentOccurrence;
      }
    }
    return null;
  }
  C(mouseEvent, withKey) {
    return Boolean(mouseEvent.target.type === 6 && (mouseEvent.hasTriggerModifier || withKey && withKey.keyCodeIsTriggerKey));
  }
  D() {
    this.c.cancel();
    if (this.g) {
      this.g?.dispose();
      this.g = null;
    }
    if (this.f) {
      this.f.cancel();
      this.f = null;
    }
  }
  dispose() {
    super.dispose();
    this.D();
  }
};
$Ajb = $Ajb_1 = __decorate([
  __param(1, $O4),
  __param(2, $PJ),
  __param(3, $mP),
  __param(4, $tbb)
], $Ajb);
var decoration = {
  general: $WI.register({
    description: "detected-link",
    stickiness: 1,
    collapseOnReplaceEdit: true,
    inlineClassName: "detected-link"
  }),
  active: $WI.register({
    description: "detected-link-active",
    stickiness: 1,
    collapseOnReplaceEdit: true,
    inlineClassName: "detected-link-active"
  })
};
var LinkOccurrence = class _LinkOccurrence {
  static decoration(link2, useMetaKey) {
    return {
      range: link2.range,
      options: _LinkOccurrence.a(link2, useMetaKey, false)
    };
  }
  static a(link2, useMetaKey, isActive2) {
    const options3 = { ...isActive2 ? decoration.active : decoration.general };
    options3.hoverMessage = getHoverMessage(link2, useMetaKey);
    return options3;
  }
  constructor(link2, decorationId) {
    this.link = link2;
    this.decorationId = decorationId;
  }
  activate(changeAccessor, useMetaKey) {
    changeAccessor.changeDecorationOptions(this.decorationId, _LinkOccurrence.a(this.link, useMetaKey, true));
  }
  deactivate(changeAccessor, useMetaKey) {
    changeAccessor.changeDecorationOptions(this.decorationId, _LinkOccurrence.a(this.link, useMetaKey, false));
  }
};
function getHoverMessage(link2, useMetaKey) {
  const executeCmd = link2.url && /^command:/i.test(link2.url.toString());
  const label3 = link2.tooltip ? link2.tooltip : executeCmd ? localize(1323, null) : localize(1324, null);
  const kb = useMetaKey ? $m ? localize(1325, null) : localize(1326, null) : $m ? localize(1327, null) : localize(1328, null);
  if (link2.url) {
    let nativeLabel = "";
    if (/^command:/i.test(link2.url.toString())) {
      const match = link2.url.toString().match(/^command:([^?#]+)/);
      if (match) {
        const commandId = match[1];
        nativeLabel = localize(1329, null, commandId);
      }
    }
    const hoverMessage = new $bm("", true).appendLink(link2.url.toString(true).replace(/ /g, "%20"), label3, nativeLabel).appendMarkdown(` (${kb})`);
    return hoverMessage;
  } else {
    return new $bm().appendText(`${label3} (${kb})`);
  }
}
var OpenLinkAction = class extends $Z5 {
  constructor() {
    super({
      id: "editor.action.openLink",
      label: localize2(1330, "Open Link"),
      precondition: void 0
    });
  }
  run(accessor, editor) {
    const linkDetector = $Ajb.get(editor);
    if (!linkDetector) {
      return;
    }
    if (!editor.hasModel()) {
      return;
    }
    const selections = editor.getSelections();
    for (const sel of selections) {
      const link2 = linkDetector.getLinkOccurrence(sel.getEndPosition());
      if (link2) {
        linkDetector.openLinkOccurrence(link2, false);
      }
    }
  }
};
$85(
  $Ajb.ID,
  $Ajb,
  1
  /* EditorContributionInstantiation.AfterFirstRender */
);
$55(OpenLinkAction);

// out-build/vs/editor/contrib/longLinesHelper/browser/longLinesHelper.js
var LongLinesHelper = class _LongLinesHelper extends $3c {
  static {
    this.ID = "editor.contrib.longLinesHelper";
  }
  static get(editor) {
    return editor.getContribution(_LongLinesHelper.ID);
  }
  constructor(a) {
    super();
    this.a = a;
    this.B(this.a.onMouseDown((e) => {
      const stopRenderingLineAfter = this.a.getOption(
        122
        /* EditorOption.stopRenderingLineAfter */
      );
      if (stopRenderingLineAfter >= 0 && e.target.type === 6 && e.target.position.column >= stopRenderingLineAfter) {
        this.a.updateOptions({
          stopRenderingLineAfter: -1
        });
      }
    }));
  }
};
$85(
  LongLinesHelper.ID,
  LongLinesHelper,
  2
  /* EditorContributionInstantiation.BeforeFirstInteraction */
);

// out-build/vs/editor/contrib/wordHighlighter/browser/highlightDecorations.js
var wordHighlightBackground = $5n("editor.wordHighlightBackground", { dark: "#575757B8", light: "#57575740", hcDark: null, hcLight: null }, localize(1598, null), true);
$5n("editor.wordHighlightStrongBackground", { dark: "#004972B8", light: "#0e639c40", hcDark: null, hcLight: null }, localize(1599, null), true);
$5n("editor.wordHighlightTextBackground", wordHighlightBackground, localize(1600, null), true);
var wordHighlightBorder = $5n("editor.wordHighlightBorder", { light: null, dark: null, hcDark: $lo, hcLight: $lo }, localize(1601, null));
$5n("editor.wordHighlightStrongBorder", { light: null, dark: null, hcDark: $lo, hcLight: $lo }, localize(1602, null));
$5n("editor.wordHighlightTextBorder", wordHighlightBorder, localize(1603, null));
var overviewRulerWordHighlightForeground = $5n("editorOverviewRuler.wordHighlightForeground", "#A0A0A0CC", localize(1604, null), true);
var overviewRulerWordHighlightStrongForeground = $5n("editorOverviewRuler.wordHighlightStrongForeground", "#C0A0C0CC", localize(1605, null), true);
var overviewRulerWordHighlightTextForeground = $5n("editorOverviewRuler.wordHighlightTextForeground", $aq, localize(1606, null), true);
var _WRITE_OPTIONS = $WI.register({
  description: "word-highlight-strong",
  stickiness: 1,
  className: "wordHighlightStrong",
  overviewRuler: {
    color: $hs(overviewRulerWordHighlightStrongForeground),
    position: OverviewRulerLane.Center
  },
  minimap: {
    color: $hs($fq),
    position: 1
    /* MinimapPosition.Inline */
  }
});
var _TEXT_OPTIONS = $WI.register({
  description: "word-highlight-text",
  stickiness: 1,
  className: "wordHighlightText",
  overviewRuler: {
    color: $hs(overviewRulerWordHighlightTextForeground),
    position: OverviewRulerLane.Center
  },
  minimap: {
    color: $hs($fq),
    position: 1
    /* MinimapPosition.Inline */
  }
});
var _SELECTION_HIGHLIGHT_OPTIONS = $WI.register({
  description: "selection-highlight-overview",
  stickiness: 1,
  className: "selectionHighlight",
  overviewRuler: {
    color: $hs($aq),
    position: OverviewRulerLane.Center
  },
  minimap: {
    color: $hs($fq),
    position: 1
    /* MinimapPosition.Inline */
  }
});
var _SELECTION_HIGHLIGHT_OPTIONS_NO_OVERVIEW = $WI.register({
  description: "selection-highlight",
  stickiness: 1,
  className: "selectionHighlight"
});
var _REGULAR_OPTIONS = $WI.register({
  description: "word-highlight",
  stickiness: 1,
  className: "wordHighlight",
  overviewRuler: {
    color: $hs(overviewRulerWordHighlightForeground),
    position: OverviewRulerLane.Center
  },
  minimap: {
    color: $hs($fq),
    position: 1
    /* MinimapPosition.Inline */
  }
});
function $Bjb(kind) {
  if (kind === DocumentHighlightKind.Write) {
    return _WRITE_OPTIONS;
  } else if (kind === DocumentHighlightKind.Text) {
    return _TEXT_OPTIONS;
  } else {
    return _REGULAR_OPTIONS;
  }
}
function $Cjb(hasSemanticHighlights) {
  return hasSemanticHighlights ? _SELECTION_HIGHLIGHT_OPTIONS_NO_OVERVIEW : _SELECTION_HIGHLIGHT_OPTIONS;
}
$ms((theme, collector) => {
  const selectionHighlight = theme.getColor($0o);
  if (selectionHighlight) {
    collector.addRule(`.monaco-editor .selectionHighlight { background-color: ${selectionHighlight.transparent(0.5)}; }`);
  }
});

// out-build/vs/editor/contrib/multicursor/browser/multicursor.js
var $Pjb_1;
function announceCursorChange(previousCursorState, cursorState) {
  const cursorDiff = cursorState.filter((cs) => !previousCursorState.find((pcs) => pcs.equals(cs)));
  if (cursorDiff.length >= 1) {
    const cursorPositions = cursorDiff.map((cs) => `line ${cs.viewState.position.lineNumber} column ${cs.viewState.position.column}`).join(", ");
    const msg = cursorDiff.length === 1 ? localize(1332, null, cursorPositions) : localize(1333, null, cursorPositions);
    $_Z(msg);
  }
}
var $Djb = class extends $Z5 {
  constructor() {
    super({
      id: "editor.action.insertCursorAbove",
      label: localize2(1342, "Add Cursor Above"),
      precondition: void 0,
      kbOpts: {
        kbExpr: EditorContextKeys.editorTextFocus,
        primary: 2048 | 512 | 16,
        linux: {
          primary: 1024 | 512 | 16,
          secondary: [
            2048 | 1024 | 16
            /* KeyCode.UpArrow */
          ]
        },
        weight: 100
        /* KeybindingWeight.EditorContrib */
      },
      menuOpts: {
        menuId: $bJ.MenubarSelectionMenu,
        group: "3_multi",
        title: localize(1334, null),
        order: 2
      }
    });
  }
  run(accessor, editor, args2) {
    if (!editor.hasModel()) {
      return;
    }
    let useLogicalLine = true;
    if (args2 && args2.logicalLine === false) {
      useLogicalLine = false;
    }
    const viewModel = editor._getViewModel();
    if (viewModel.cursorConfig.readOnly) {
      return;
    }
    viewModel.model.pushStackElement();
    const previousCursorState = viewModel.getCursorStates();
    viewModel.setCursorStates(args2.source, 3, $o6.addCursorUp(viewModel, previousCursorState, useLogicalLine));
    viewModel.revealTopMostCursor(args2.source);
    announceCursorChange(previousCursorState, viewModel.getCursorStates());
  }
};
var $Ejb = class extends $Z5 {
  constructor() {
    super({
      id: "editor.action.insertCursorBelow",
      label: localize2(1343, "Add Cursor Below"),
      precondition: void 0,
      kbOpts: {
        kbExpr: EditorContextKeys.editorTextFocus,
        primary: 2048 | 512 | 18,
        linux: {
          primary: 1024 | 512 | 18,
          secondary: [
            2048 | 1024 | 18
            /* KeyCode.DownArrow */
          ]
        },
        weight: 100
        /* KeybindingWeight.EditorContrib */
      },
      menuOpts: {
        menuId: $bJ.MenubarSelectionMenu,
        group: "3_multi",
        title: localize(1335, null),
        order: 3
      }
    });
  }
  run(accessor, editor, args2) {
    if (!editor.hasModel()) {
      return;
    }
    let useLogicalLine = true;
    if (args2 && args2.logicalLine === false) {
      useLogicalLine = false;
    }
    const viewModel = editor._getViewModel();
    if (viewModel.cursorConfig.readOnly) {
      return;
    }
    viewModel.model.pushStackElement();
    const previousCursorState = viewModel.getCursorStates();
    viewModel.setCursorStates(args2.source, 3, $o6.addCursorDown(viewModel, previousCursorState, useLogicalLine));
    viewModel.revealBottomMostCursor(args2.source);
    announceCursorChange(previousCursorState, viewModel.getCursorStates());
  }
};
var InsertCursorAtEndOfEachLineSelected = class extends $Z5 {
  constructor() {
    super({
      id: "editor.action.insertCursorAtEndOfEachLineSelected",
      label: localize2(1344, "Add Cursors to Line Ends"),
      precondition: void 0,
      kbOpts: {
        kbExpr: EditorContextKeys.editorTextFocus,
        primary: 1024 | 512 | 39,
        weight: 100
        /* KeybindingWeight.EditorContrib */
      },
      menuOpts: {
        menuId: $bJ.MenubarSelectionMenu,
        group: "3_multi",
        title: localize(1336, null),
        order: 4
      }
    });
  }
  d(selection, model, result) {
    if (selection.isEmpty()) {
      return;
    }
    for (let i2 = selection.startLineNumber; i2 < selection.endLineNumber; i2++) {
      const currentLineMaxColumn = model.getLineMaxColumn(i2);
      result.push(new $_D(i2, currentLineMaxColumn, i2, currentLineMaxColumn));
    }
    if (selection.endColumn > 1) {
      result.push(new $_D(selection.endLineNumber, selection.endColumn, selection.endLineNumber, selection.endColumn));
    }
  }
  run(accessor, editor) {
    if (!editor.hasModel()) {
      return;
    }
    const model = editor.getModel();
    const selections = editor.getSelections();
    const viewModel = editor._getViewModel();
    const previousCursorState = viewModel.getCursorStates();
    const newSelections = [];
    selections.forEach((sel) => this.d(sel, model, newSelections));
    if (newSelections.length > 0) {
      editor.setSelections(newSelections);
    }
    announceCursorChange(previousCursorState, viewModel.getCursorStates());
  }
};
var InsertCursorAtEndOfLineSelected = class extends $Z5 {
  constructor() {
    super({
      id: "editor.action.addCursorsToBottom",
      label: localize2(1345, "Add Cursors To Bottom"),
      precondition: void 0
    });
  }
  run(accessor, editor) {
    if (!editor.hasModel()) {
      return;
    }
    const selections = editor.getSelections();
    const lineCount = editor.getModel().getLineCount();
    const newSelections = [];
    for (let i2 = selections[0].startLineNumber; i2 <= lineCount; i2++) {
      newSelections.push(new $_D(i2, selections[0].startColumn, i2, selections[0].endColumn));
    }
    const viewModel = editor._getViewModel();
    const previousCursorState = viewModel.getCursorStates();
    if (newSelections.length > 0) {
      editor.setSelections(newSelections);
    }
    announceCursorChange(previousCursorState, viewModel.getCursorStates());
  }
};
var InsertCursorAtTopOfLineSelected = class extends $Z5 {
  constructor() {
    super({
      id: "editor.action.addCursorsToTop",
      label: localize2(1346, "Add Cursors To Top"),
      precondition: void 0
    });
  }
  run(accessor, editor) {
    if (!editor.hasModel()) {
      return;
    }
    const selections = editor.getSelections();
    const newSelections = [];
    for (let i2 = selections[0].startLineNumber; i2 >= 1; i2--) {
      newSelections.push(new $_D(i2, selections[0].startColumn, i2, selections[0].endColumn));
    }
    const viewModel = editor._getViewModel();
    const previousCursorState = viewModel.getCursorStates();
    if (newSelections.length > 0) {
      editor.setSelections(newSelections);
    }
    announceCursorChange(previousCursorState, viewModel.getCursorStates());
  }
};
var $Fjb = class {
  constructor(selections, revealRange, revealScrollType) {
    this.selections = selections;
    this.revealRange = revealRange;
    this.revealScrollType = revealScrollType;
  }
};
var $Gjb = class _$Gjb {
  static create(editor, findController) {
    if (!editor.hasModel()) {
      return null;
    }
    const findState = findController.getState();
    if (!editor.hasTextFocus() && findState.isRevealed && findState.searchString.length > 0) {
      return new _$Gjb(editor, findController, false, findState.searchString, findState.wholeWord, findState.matchCase, null);
    }
    let isDisconnectedFromFindController = false;
    let wholeWord;
    let matchCase;
    const selections = editor.getSelections();
    if (selections.length === 1 && selections[0].isEmpty()) {
      isDisconnectedFromFindController = true;
      wholeWord = true;
      matchCase = true;
    } else {
      wholeWord = findState.wholeWord;
      matchCase = findState.matchCase;
    }
    const s = editor.getSelection();
    let searchText;
    let currentMatch = null;
    if (s.isEmpty()) {
      const word = editor.getConfiguredWordAtPosition(s.getStartPosition());
      if (!word) {
        return null;
      }
      searchText = word.word;
      currentMatch = new $_D(s.startLineNumber, word.startColumn, s.startLineNumber, word.endColumn);
    } else {
      searchText = editor.getModel().getValueInRange(s).replace(/\r\n/g, "\n");
    }
    return new _$Gjb(editor, findController, isDisconnectedFromFindController, searchText, wholeWord, matchCase, currentMatch);
  }
  constructor(a, findController, isDisconnectedFromFindController, searchText, wholeWord, matchCase, currentMatch) {
    this.a = a;
    this.findController = findController;
    this.isDisconnectedFromFindController = isDisconnectedFromFindController;
    this.searchText = searchText;
    this.wholeWord = wholeWord;
    this.matchCase = matchCase;
    this.currentMatch = currentMatch;
  }
  addSelectionToNextFindMatch() {
    if (!this.a.hasModel()) {
      return null;
    }
    const nextMatch = this.b();
    if (!nextMatch) {
      return null;
    }
    const allSelections = this.a.getSelections();
    return new $Fjb(
      allSelections.concat(nextMatch),
      nextMatch,
      0
      /* ScrollType.Smooth */
    );
  }
  moveSelectionToNextFindMatch() {
    if (!this.a.hasModel()) {
      return null;
    }
    const nextMatch = this.b();
    if (!nextMatch) {
      return null;
    }
    const allSelections = this.a.getSelections();
    return new $Fjb(
      allSelections.slice(0, allSelections.length - 1).concat(nextMatch),
      nextMatch,
      0
      /* ScrollType.Smooth */
    );
  }
  b() {
    if (!this.a.hasModel()) {
      return null;
    }
    if (this.currentMatch) {
      const result = this.currentMatch;
      this.currentMatch = null;
      return result;
    }
    this.findController.highlightFindOptions();
    const allSelections = this.a.getSelections();
    const lastAddedSelection = allSelections[allSelections.length - 1];
    const nextMatch = this.a.getModel().findNextMatch(this.searchText, lastAddedSelection.getEndPosition(), false, this.matchCase, this.wholeWord ? this.a.getOption(
      136
      /* EditorOption.wordSeparators */
    ) : null, false);
    if (!nextMatch) {
      return null;
    }
    return new $_D(nextMatch.range.startLineNumber, nextMatch.range.startColumn, nextMatch.range.endLineNumber, nextMatch.range.endColumn);
  }
  addSelectionToPreviousFindMatch() {
    if (!this.a.hasModel()) {
      return null;
    }
    const previousMatch = this.c();
    if (!previousMatch) {
      return null;
    }
    const allSelections = this.a.getSelections();
    return new $Fjb(
      allSelections.concat(previousMatch),
      previousMatch,
      0
      /* ScrollType.Smooth */
    );
  }
  moveSelectionToPreviousFindMatch() {
    if (!this.a.hasModel()) {
      return null;
    }
    const previousMatch = this.c();
    if (!previousMatch) {
      return null;
    }
    const allSelections = this.a.getSelections();
    return new $Fjb(
      allSelections.slice(0, allSelections.length - 1).concat(previousMatch),
      previousMatch,
      0
      /* ScrollType.Smooth */
    );
  }
  c() {
    if (!this.a.hasModel()) {
      return null;
    }
    if (this.currentMatch) {
      const result = this.currentMatch;
      this.currentMatch = null;
      return result;
    }
    this.findController.highlightFindOptions();
    const allSelections = this.a.getSelections();
    const lastAddedSelection = allSelections[allSelections.length - 1];
    const previousMatch = this.a.getModel().findPreviousMatch(this.searchText, lastAddedSelection.getStartPosition(), false, this.matchCase, this.wholeWord ? this.a.getOption(
      136
      /* EditorOption.wordSeparators */
    ) : null, false);
    if (!previousMatch) {
      return null;
    }
    return new $_D(previousMatch.range.startLineNumber, previousMatch.range.startColumn, previousMatch.range.endLineNumber, previousMatch.range.endColumn);
  }
  selectAll(searchScope) {
    if (!this.a.hasModel()) {
      return [];
    }
    this.findController.highlightFindOptions();
    const editorModel = this.a.getModel();
    if (searchScope) {
      return editorModel.findMatches(
        this.searchText,
        searchScope,
        false,
        this.matchCase,
        this.wholeWord ? this.a.getOption(
          136
          /* EditorOption.wordSeparators */
        ) : null,
        false,
        1073741824
        /* Constants.MAX_SAFE_SMALL_INTEGER */
      );
    }
    return editorModel.findMatches(
      this.searchText,
      true,
      false,
      this.matchCase,
      this.wholeWord ? this.a.getOption(
        136
        /* EditorOption.wordSeparators */
      ) : null,
      false,
      1073741824
      /* Constants.MAX_SAFE_SMALL_INTEGER */
    );
  }
};
var $Hjb = class _$Hjb extends $3c {
  static {
    this.ID = "editor.contrib.multiCursorController";
  }
  static get(editor) {
    return editor.getContribution(_$Hjb.ID);
  }
  constructor(editor) {
    super();
    this.f = this.B(new $2c());
    this.a = editor;
    this.b = false;
    this.c = null;
  }
  dispose() {
    this.h();
    super.dispose();
  }
  g(findController) {
    if (!this.c) {
      const session = $Gjb.create(this.a, findController);
      if (!session) {
        return;
      }
      this.c = session;
      const newState = { searchString: this.c.searchText };
      if (this.c.isDisconnectedFromFindController) {
        newState.wholeWordOverride = 1;
        newState.matchCaseOverride = 1;
        newState.isRegexOverride = 2;
      }
      findController.getState().change(newState, false);
      this.f.add(this.a.onDidChangeCursorSelection((e) => {
        if (this.b) {
          return;
        }
        this.h();
      }));
      this.f.add(this.a.onDidBlurEditorText(() => {
        this.h();
      }));
      this.f.add(findController.getState().onFindReplaceStateChange((e) => {
        if (e.matchCase || e.wholeWord) {
          this.h();
        }
      }));
    }
  }
  h() {
    this.f.clear();
    if (this.c && this.c.isDisconnectedFromFindController) {
      const newState = {
        wholeWordOverride: 0,
        matchCaseOverride: 0,
        isRegexOverride: 0
      };
      this.c.findController.getState().change(newState, false);
    }
    this.c = null;
  }
  n(selections) {
    this.b = true;
    this.a.setSelections(selections);
    this.b = false;
  }
  t(model, selection) {
    if (!selection.isEmpty()) {
      return selection;
    }
    const word = this.a.getConfiguredWordAtPosition(selection.getStartPosition());
    if (!word) {
      return selection;
    }
    return new $_D(selection.startLineNumber, word.startColumn, selection.startLineNumber, word.endColumn);
  }
  u(result) {
    if (!result) {
      return;
    }
    this.n(result.selections);
    if (result.revealRange) {
      this.a.revealRangeInCenterIfOutsideViewport(result.revealRange, result.revealScrollType);
    }
  }
  getSession(findController) {
    return this.c;
  }
  addSelectionToNextFindMatch(findController) {
    if (!this.a.hasModel()) {
      return;
    }
    if (!this.c) {
      const allSelections = this.a.getSelections();
      if (allSelections.length > 1) {
        const findState = findController.getState();
        const matchCase = findState.matchCase;
        const selectionsContainSameText = modelRangesContainSameText(this.a.getModel(), allSelections, matchCase);
        if (!selectionsContainSameText) {
          const model = this.a.getModel();
          const resultingSelections = [];
          for (let i2 = 0, len = allSelections.length; i2 < len; i2++) {
            resultingSelections[i2] = this.t(model, allSelections[i2]);
          }
          this.a.setSelections(resultingSelections);
          return;
        }
      }
    }
    this.g(findController);
    if (this.c) {
      this.u(this.c.addSelectionToNextFindMatch());
    }
  }
  addSelectionToPreviousFindMatch(findController) {
    this.g(findController);
    if (this.c) {
      this.u(this.c.addSelectionToPreviousFindMatch());
    }
  }
  moveSelectionToNextFindMatch(findController) {
    this.g(findController);
    if (this.c) {
      this.u(this.c.moveSelectionToNextFindMatch());
    }
  }
  moveSelectionToPreviousFindMatch(findController) {
    this.g(findController);
    if (this.c) {
      this.u(this.c.moveSelectionToPreviousFindMatch());
    }
  }
  selectAll(findController) {
    if (!this.a.hasModel()) {
      return;
    }
    let matches = null;
    const findState = findController.getState();
    if (findState.isRevealed && findState.searchString.length > 0 && findState.isRegex) {
      const editorModel = this.a.getModel();
      if (findState.searchScope) {
        matches = editorModel.findMatches(
          findState.searchString,
          findState.searchScope,
          findState.isRegex,
          findState.matchCase,
          findState.wholeWord ? this.a.getOption(
            136
            /* EditorOption.wordSeparators */
          ) : null,
          false,
          1073741824
          /* Constants.MAX_SAFE_SMALL_INTEGER */
        );
      } else {
        matches = editorModel.findMatches(
          findState.searchString,
          true,
          findState.isRegex,
          findState.matchCase,
          findState.wholeWord ? this.a.getOption(
            136
            /* EditorOption.wordSeparators */
          ) : null,
          false,
          1073741824
          /* Constants.MAX_SAFE_SMALL_INTEGER */
        );
      }
    } else {
      this.g(findController);
      if (!this.c) {
        return;
      }
      matches = this.c.selectAll(findState.searchScope);
    }
    if (matches.length > 0) {
      const editorSelection = this.a.getSelection();
      for (let i2 = 0, len = matches.length; i2 < len; i2++) {
        const match = matches[i2];
        const intersection = match.range.intersectRanges(editorSelection);
        if (intersection) {
          matches[i2] = matches[0];
          matches[0] = match;
          break;
        }
      }
      this.n(matches.map((m) => new $_D(m.range.startLineNumber, m.range.startColumn, m.range.endLineNumber, m.range.endColumn)));
    }
  }
  selectAllUsingSelections(selections) {
    if (selections.length > 0) {
      this.n(selections);
    }
  }
};
var $Ijb = class extends $Z5 {
  run(accessor, editor) {
    const multiCursorController = $Hjb.get(editor);
    if (!multiCursorController) {
      return;
    }
    const viewModel = editor._getViewModel();
    if (viewModel) {
      const previousCursorState = viewModel.getCursorStates();
      const findController = $tgb.get(editor);
      if (findController) {
        this.d(multiCursorController, findController);
      } else {
        const newFindController = accessor.get($Pk).createInstance($tgb, editor);
        this.d(multiCursorController, newFindController);
        newFindController.dispose();
      }
      announceCursorChange(previousCursorState, viewModel.getCursorStates());
    }
  }
};
var $Jjb = class extends $Ijb {
  constructor() {
    super({
      id: "editor.action.addSelectionToNextFindMatch",
      label: localize2(1347, "Add Selection To Next Find Match"),
      precondition: void 0,
      kbOpts: {
        kbExpr: EditorContextKeys.focus,
        primary: 2048 | 34,
        weight: 100
        /* KeybindingWeight.EditorContrib */
      },
      menuOpts: {
        menuId: $bJ.MenubarSelectionMenu,
        group: "3_multi",
        title: localize(1337, null),
        order: 5
      }
    });
  }
  d(multiCursorController, findController) {
    multiCursorController.addSelectionToNextFindMatch(findController);
  }
};
var $Kjb = class extends $Ijb {
  constructor() {
    super({
      id: "editor.action.addSelectionToPreviousFindMatch",
      label: localize2(1348, "Add Selection To Previous Find Match"),
      precondition: void 0,
      menuOpts: {
        menuId: $bJ.MenubarSelectionMenu,
        group: "3_multi",
        title: localize(1338, null),
        order: 6
      }
    });
  }
  d(multiCursorController, findController) {
    multiCursorController.addSelectionToPreviousFindMatch(findController);
  }
};
var $Ljb = class extends $Ijb {
  constructor() {
    super({
      id: "editor.action.moveSelectionToNextFindMatch",
      label: localize2(1349, "Move Last Selection To Next Find Match"),
      precondition: void 0,
      kbOpts: {
        kbExpr: EditorContextKeys.focus,
        primary: $$e(
          2048 | 41,
          2048 | 34
          /* KeyCode.KeyD */
        ),
        weight: 100
        /* KeybindingWeight.EditorContrib */
      }
    });
  }
  d(multiCursorController, findController) {
    multiCursorController.moveSelectionToNextFindMatch(findController);
  }
};
var $Mjb = class extends $Ijb {
  constructor() {
    super({
      id: "editor.action.moveSelectionToPreviousFindMatch",
      label: localize2(1350, "Move Last Selection To Previous Find Match"),
      precondition: void 0
    });
  }
  d(multiCursorController, findController) {
    multiCursorController.moveSelectionToPreviousFindMatch(findController);
  }
};
var $Njb = class extends $Ijb {
  constructor() {
    super({
      id: "editor.action.selectHighlights",
      label: localize2(1351, "Select All Occurrences of Find Match"),
      precondition: void 0,
      kbOpts: {
        kbExpr: EditorContextKeys.focus,
        primary: 2048 | 1024 | 42,
        weight: 100
        /* KeybindingWeight.EditorContrib */
      },
      menuOpts: {
        menuId: $bJ.MenubarSelectionMenu,
        group: "3_multi",
        title: localize(1339, null),
        order: 7
      }
    });
  }
  d(multiCursorController, findController) {
    multiCursorController.selectAll(findController);
  }
};
var $Ojb = class extends $Ijb {
  constructor() {
    super({
      id: "editor.action.changeAll",
      label: localize2(1352, "Change All Occurrences"),
      precondition: $7m.and(EditorContextKeys.writable, EditorContextKeys.editorTextFocus),
      kbOpts: {
        kbExpr: EditorContextKeys.editorTextFocus,
        primary: 2048 | 60,
        weight: 100
        /* KeybindingWeight.EditorContrib */
      },
      contextMenuOpts: {
        group: "1_modification",
        order: 1.2
      }
    });
  }
  d(multiCursorController, findController) {
    multiCursorController.selectAll(findController);
  }
};
var SelectionHighlighterState = class {
  constructor(c, d, f, g, prevState) {
    this.c = c;
    this.d = d;
    this.f = f;
    this.g = g;
    this.a = this.c.getVersionId();
    this.b = null;
    if (prevState && this.c === prevState.c && this.d === prevState.d && this.f === prevState.f && this.g === prevState.g && this.a === prevState.a) {
      this.b = prevState.b;
    }
  }
  findMatches() {
    if (this.b === null) {
      this.b = this.c.findMatches(this.d, true, false, this.f, this.g, false).map((m) => m.range);
      this.b.sort($9C.compareRangesUsingStarts);
    }
    return this.b;
  }
};
var $Pjb = class $Pjb2 extends $3c {
  static {
    $Pjb_1 = this;
  }
  static {
    this.ID = "editor.contrib.selectionHighlighter";
  }
  constructor(editor, h3) {
    super();
    this.h = h3;
    this.a = editor;
    this.b = editor.getOption(
      113
      /* EditorOption.selectionHighlight */
    );
    this.c = editor.createDecorationsCollection();
    this.f = this.B(new $8h(() => this.n(), 300));
    this.g = null;
    this.B(editor.onDidChangeConfiguration((e) => {
      this.b = editor.getOption(
        113
        /* EditorOption.selectionHighlight */
      );
    }));
    this.B(editor.onDidChangeCursorSelection((e) => {
      if (!this.b) {
        return;
      }
      if (e.selection.isEmpty()) {
        if (e.reason === 3) {
          if (this.g) {
            this.u(null);
          }
          this.f.schedule();
        } else {
          this.u(null);
        }
      } else {
        this.n();
      }
    }));
    this.B(editor.onDidChangeModel((e) => {
      this.u(null);
    }));
    this.B(editor.onDidChangeModelContent((e) => {
      if (this.b) {
        this.f.schedule();
      }
    }));
    const findController = $tgb.get(editor);
    if (findController) {
      this.B(findController.getState().onFindReplaceStateChange((e) => {
        this.n();
      }));
    }
    this.f.schedule();
  }
  n() {
    this.u($Pjb_1.t(this.g, this.b, this.a));
  }
  static t(oldState, isEnabled, editor) {
    if (!isEnabled) {
      return null;
    }
    if (!editor.hasModel()) {
      return null;
    }
    const s = editor.getSelection();
    if (s.startLineNumber !== s.endLineNumber) {
      return null;
    }
    const multiCursorController = $Hjb.get(editor);
    if (!multiCursorController) {
      return null;
    }
    const findController = $tgb.get(editor);
    if (!findController) {
      return null;
    }
    let r2 = multiCursorController.getSession(findController);
    if (!r2) {
      const allSelections = editor.getSelections();
      if (allSelections.length > 1) {
        const findState2 = findController.getState();
        const matchCase = findState2.matchCase;
        const selectionsContainSameText = modelRangesContainSameText(editor.getModel(), allSelections, matchCase);
        if (!selectionsContainSameText) {
          return null;
        }
      }
      r2 = $Gjb.create(editor, findController);
    }
    if (!r2) {
      return null;
    }
    if (r2.currentMatch) {
      return null;
    }
    if (/^[ \t]+$/.test(r2.searchText)) {
      return null;
    }
    if (r2.searchText.length > 200) {
      return null;
    }
    const findState = findController.getState();
    const caseSensitive = findState.matchCase;
    if (findState.isRevealed) {
      let findStateSearchString = findState.searchString;
      if (!caseSensitive) {
        findStateSearchString = findStateSearchString.toLowerCase();
      }
      let mySearchString = r2.searchText;
      if (!caseSensitive) {
        mySearchString = mySearchString.toLowerCase();
      }
      if (findStateSearchString === mySearchString && r2.matchCase === findState.matchCase && r2.wholeWord === findState.wholeWord && !findState.isRegex) {
        return null;
      }
    }
    return new SelectionHighlighterState(editor.getModel(), r2.searchText, r2.matchCase, r2.wholeWord ? editor.getOption(
      136
      /* EditorOption.wordSeparators */
    ) : null, oldState);
  }
  u(newState) {
    this.g = newState;
    if (!this.g) {
      this.c.clear();
      return;
    }
    if (!this.a.hasModel()) {
      return;
    }
    const model = this.a.getModel();
    if (model.isTooLargeForTokenization()) {
      return;
    }
    const allMatches = this.g.findMatches();
    const selections = this.a.getSelections();
    selections.sort($9C.compareRangesUsingStarts);
    const matches = [];
    for (let i2 = 0, j = 0, len = allMatches.length, lenJ = selections.length; i2 < len; ) {
      const match = allMatches[i2];
      if (j >= lenJ) {
        matches.push(match);
        i2++;
      } else {
        const cmp4 = $9C.compareRangesUsingStarts(match, selections[j]);
        if (cmp4 < 0) {
          if (selections[j].isEmpty() || !$9C.areIntersecting(match, selections[j])) {
            matches.push(match);
          }
          i2++;
        } else if (cmp4 > 0) {
          j++;
        } else {
          i2++;
          j++;
        }
      }
    }
    const occurrenceHighlighting = this.a.getOption(
      82
      /* EditorOption.occurrencesHighlight */
    ) !== "off";
    const hasSemanticHighlights = this.h.documentHighlightProvider.has(model) && occurrenceHighlighting;
    const decorations = matches.map((r2) => {
      return {
        range: r2,
        options: $Cjb(hasSemanticHighlights)
      };
    });
    this.c.set(decorations);
  }
  dispose() {
    this.u(null);
    super.dispose();
  }
};
$Pjb = $Pjb_1 = __decorate([
  __param(1, $mP)
], $Pjb);
function modelRangesContainSameText(model, ranges, matchCase) {
  const selectedText = getValueInRange(model, ranges[0], !matchCase);
  for (let i2 = 1, len = ranges.length; i2 < len; i2++) {
    const range = ranges[i2];
    if (range.isEmpty()) {
      return false;
    }
    const thisSelectedText = getValueInRange(model, range, !matchCase);
    if (selectedText !== thisSelectedText) {
      return false;
    }
  }
  return true;
}
function getValueInRange(model, range, toLowerCase) {
  const text2 = model.getValueInRange(range);
  return toLowerCase ? text2.toLowerCase() : text2;
}
var $Qjb = class extends $Z5 {
  constructor() {
    super({
      id: "editor.action.focusNextCursor",
      label: localize2(1353, "Focus Next Cursor"),
      metadata: {
        description: localize(1340, null),
        args: []
      },
      precondition: void 0
    });
  }
  run(accessor, editor, args2) {
    if (!editor.hasModel()) {
      return;
    }
    const viewModel = editor._getViewModel();
    if (viewModel.cursorConfig.readOnly) {
      return;
    }
    viewModel.model.pushStackElement();
    const previousCursorState = Array.from(viewModel.getCursorStates());
    const firstCursor = previousCursorState.shift();
    if (!firstCursor) {
      return;
    }
    previousCursorState.push(firstCursor);
    viewModel.setCursorStates(args2.source, 3, previousCursorState);
    viewModel.revealPrimaryCursor(args2.source, true);
    announceCursorChange(previousCursorState, viewModel.getCursorStates());
  }
};
var $Rjb = class extends $Z5 {
  constructor() {
    super({
      id: "editor.action.focusPreviousCursor",
      label: localize2(1354, "Focus Previous Cursor"),
      metadata: {
        description: localize(1341, null),
        args: []
      },
      precondition: void 0
    });
  }
  run(accessor, editor, args2) {
    if (!editor.hasModel()) {
      return;
    }
    const viewModel = editor._getViewModel();
    if (viewModel.cursorConfig.readOnly) {
      return;
    }
    viewModel.model.pushStackElement();
    const previousCursorState = Array.from(viewModel.getCursorStates());
    const firstCursor = previousCursorState.pop();
    if (!firstCursor) {
      return;
    }
    previousCursorState.unshift(firstCursor);
    viewModel.setCursorStates(args2.source, 3, previousCursorState);
    viewModel.revealPrimaryCursor(args2.source, true);
    announceCursorChange(previousCursorState, viewModel.getCursorStates());
  }
};
$85(
  $Hjb.ID,
  $Hjb,
  4
  /* EditorContributionInstantiation.Lazy */
);
$85(
  $Pjb.ID,
  $Pjb,
  1
  /* EditorContributionInstantiation.AfterFirstRender */
);
$55($Djb);
$55($Ejb);
$55(InsertCursorAtEndOfEachLineSelected);
$55($Jjb);
$55($Kjb);
$55($Ljb);
$55($Mjb);
$55($Njb);
$55($Ojb);
$55(InsertCursorAtEndOfLineSelected);
$55(InsertCursorAtTopOfLineSelected);
$55($Qjb);
$55($Rjb);

// out-build/vs/editor/contrib/parameterHints/browser/provideSignatureHelp.js
var $Sjb = {
  Visible: new $nn("parameterHintsVisible", false),
  MultipleSignatures: new $nn("parameterHintsMultipleSignatures", false)
};
async function $Tjb(registry4, model, position, context, token) {
  const supports = registry4.ordered(model);
  for (const support of supports) {
    try {
      const result = await support.provideSignatureHelp(model, position, token, context);
      if (result) {
        return result;
      }
    } catch (err) {
      $hb(err);
    }
  }
  return void 0;
}
$tn.registerCommand("_executeSignatureHelpProvider", async (accessor, ...args2) => {
  const [uri, position, triggerCharacter] = args2;
  $Jg(URI.isUri(uri));
  $Jg($8C.isIPosition(position));
  $Jg(typeof triggerCharacter === "string" || !triggerCharacter);
  const languageFeaturesService = accessor.get($mP);
  const ref = await accessor.get($oG).createModelReference(uri);
  try {
    const result = await $Tjb(languageFeaturesService.signatureHelpProvider, ref.object.textEditorModel, $8C.lift(position), {
      triggerKind: SignatureHelpTriggerKind.Invoke,
      isRetrigger: false,
      triggerCharacter
    }, CancellationToken.None);
    if (!result) {
      return void 0;
    }
    setTimeout(() => result.dispose(), 0);
    return result.value;
  } finally {
    ref.dispose();
  }
});

// out-build/vs/editor/contrib/parameterHints/browser/parameterHintsModel.js
var ParameterHintState;
(function(ParameterHintState2) {
  let Type4;
  (function(Type5) {
    Type5[Type5["Default"] = 0] = "Default";
    Type5[Type5["Active"] = 1] = "Active";
    Type5[Type5["Pending"] = 2] = "Pending";
  })(Type4 = ParameterHintState2.Type || (ParameterHintState2.Type = {}));
  ParameterHintState2.Default = {
    type: 0
    /* Type.Default */
  };
  class Pending {
    constructor(request, previouslyActiveHints) {
      this.request = request;
      this.previouslyActiveHints = previouslyActiveHints;
      this.type = 2;
    }
  }
  ParameterHintState2.Pending = Pending;
  class Active {
    constructor(hints) {
      this.hints = hints;
      this.type = 1;
    }
  }
  ParameterHintState2.Active = Active;
})(ParameterHintState || (ParameterHintState = {}));
var $Ujb = class _$Ujb extends $3c {
  static {
    this.a = 120;
  }
  // ms
  constructor(editor, providers2, delay = _$Ujb.a) {
    super();
    this.b = this.B(new $ze());
    this.onChangedHints = this.b.event;
    this.g = false;
    this.h = ParameterHintState.Default;
    this.j = [];
    this.m = this.B(new $4c());
    this.n = new $gE();
    this.r = new $gE();
    this.t = 0;
    this.c = editor;
    this.f = providers2;
    this.s = new $Sh(delay);
    this.B(this.c.onDidBlurEditorWidget(() => this.cancel()));
    this.B(this.c.onDidChangeConfiguration(() => this.I()));
    this.B(this.c.onDidChangeModel((e) => this.D()));
    this.B(this.c.onDidChangeModelLanguage((_) => this.D()));
    this.B(this.c.onDidChangeCursorSelection((e) => this.G(e)));
    this.B(this.c.onDidChangeModelContent((e) => this.H()));
    this.B(this.f.onDidChange(this.D, this));
    this.B(this.c.onDidType((text2) => this.F(text2)));
    this.I();
    this.D();
  }
  get u() {
    return this.h;
  }
  set u(value) {
    if (this.h.type === 2) {
      this.h.request.cancel();
    }
    this.h = value;
  }
  cancel(silent = false) {
    this.u = ParameterHintState.Default;
    this.s.cancel();
    if (!silent) {
      this.b.fire(void 0);
    }
  }
  trigger(context, delay) {
    const model = this.c.getModel();
    if (!model || !this.f.has(model)) {
      return;
    }
    const triggerId = ++this.t;
    this.j.push(context);
    this.s.trigger(() => {
      return this.y(triggerId);
    }, delay).catch($gb);
  }
  next() {
    if (this.u.type !== 1) {
      return;
    }
    const length = this.u.hints.signatures.length;
    const activeSignature = this.u.hints.activeSignature;
    const last = activeSignature % length === length - 1;
    const cycle = this.c.getOption(
      90
      /* EditorOption.parameterHints */
    ).cycle;
    if ((length < 2 || last) && !cycle) {
      this.cancel();
      return;
    }
    this.w(last && cycle ? 0 : activeSignature + 1);
  }
  previous() {
    if (this.u.type !== 1) {
      return;
    }
    const length = this.u.hints.signatures.length;
    const activeSignature = this.u.hints.activeSignature;
    const first = activeSignature === 0;
    const cycle = this.c.getOption(
      90
      /* EditorOption.parameterHints */
    ).cycle;
    if ((length < 2 || first) && !cycle) {
      this.cancel();
      return;
    }
    this.w(first && cycle ? length - 1 : activeSignature - 1);
  }
  w(activeSignature) {
    if (this.u.type !== 1) {
      return;
    }
    this.u = new ParameterHintState.Active({ ...this.u.hints, activeSignature });
    this.b.fire(this.u.hints);
  }
  async y(triggerId) {
    const isRetrigger = this.u.type === 1 || this.u.type === 2;
    const activeSignatureHelp = this.z();
    this.cancel(true);
    if (this.j.length === 0) {
      return false;
    }
    const context = this.j.reduce(mergeTriggerContexts);
    this.j = [];
    const triggerContext = {
      triggerKind: context.triggerKind,
      triggerCharacter: context.triggerCharacter,
      isRetrigger,
      activeSignatureHelp
    };
    if (!this.c.hasModel()) {
      return false;
    }
    const model = this.c.getModel();
    const position = this.c.getPosition();
    this.u = new ParameterHintState.Pending($Hh((token) => $Tjb(this.f, model, position, triggerContext, token)), activeSignatureHelp);
    try {
      const result = await this.u.request;
      if (triggerId !== this.t) {
        result?.dispose();
        return false;
      }
      if (!result || !result.value.signatures || result.value.signatures.length === 0) {
        result?.dispose();
        this.m.clear();
        this.cancel();
        return false;
      } else {
        this.u = new ParameterHintState.Active(result.value);
        this.m.value = result;
        this.b.fire(this.u.hints);
        return true;
      }
    } catch (error) {
      if (triggerId === this.t) {
        this.u = ParameterHintState.Default;
      }
      $gb(error);
      return false;
    }
  }
  z() {
    switch (this.u.type) {
      case 1:
        return this.u.hints;
      case 2:
        return this.u.previouslyActiveHints;
      default:
        return void 0;
    }
  }
  get C() {
    return this.u.type === 1 || this.u.type === 2 || this.s.isTriggered();
  }
  D() {
    this.cancel();
    this.n.clear();
    this.r.clear();
    const model = this.c.getModel();
    if (!model) {
      return;
    }
    for (const support of this.f.ordered(model)) {
      for (const ch of support.signatureHelpTriggerCharacters || []) {
        if (ch.length) {
          const charCode = ch.charCodeAt(0);
          this.n.add(charCode);
          this.r.add(charCode);
        }
      }
      for (const ch of support.signatureHelpRetriggerCharacters || []) {
        if (ch.length) {
          this.r.add(ch.charCodeAt(0));
        }
      }
    }
  }
  F(text2) {
    if (!this.g) {
      return;
    }
    const lastCharIndex = text2.length - 1;
    const triggerCharCode = text2.charCodeAt(lastCharIndex);
    if (this.n.has(triggerCharCode) || this.C && this.r.has(triggerCharCode)) {
      this.trigger({
        triggerKind: SignatureHelpTriggerKind.TriggerCharacter,
        triggerCharacter: text2.charAt(lastCharIndex)
      });
    }
  }
  G(e) {
    if (e.source === "mouse") {
      this.cancel();
    } else if (this.C) {
      this.trigger({ triggerKind: SignatureHelpTriggerKind.ContentChange });
    }
  }
  H() {
    if (this.C) {
      this.trigger({ triggerKind: SignatureHelpTriggerKind.ContentChange });
    }
  }
  I() {
    this.g = this.c.getOption(
      90
      /* EditorOption.parameterHints */
    ).enabled;
    if (!this.g) {
      this.cancel();
    }
  }
  dispose() {
    this.cancel(true);
    super.dispose();
  }
};
function mergeTriggerContexts(previous, current) {
  switch (current.triggerKind) {
    case SignatureHelpTriggerKind.Invoke:
      return current;
    case SignatureHelpTriggerKind.ContentChange:
      return previous;
    case SignatureHelpTriggerKind.TriggerCharacter:
    default:
      return current;
  }
}

// out-build/vs/editor/contrib/parameterHints/browser/parameterHintsWidget.js
var $Vjb_1;
var $63 = $;
var parameterHintsNextIcon = $9r("parameter-hints-next", $6l.chevronDown, localize(1356, null));
var parameterHintsPreviousIcon = $9r("parameter-hints-previous", $6l.chevronUp, localize(1357, null));
var $Vjb = class $Vjb2 extends $3c {
  static {
    $Vjb_1 = this;
  }
  static {
    this.a = "editor.widget.parameterHintsWidget";
  }
  constructor(n, r2, contextKeyService, openerService, languageService, s) {
    super();
    this.n = n;
    this.r = r2;
    this.s = s;
    this.c = this.B(new $2c());
    this.j = false;
    this.m = null;
    this.allowEditorOverflow = true;
    this.b = this.B(new $Q_({ editor: n }, languageService, openerService));
    this.f = $Sjb.Visible.bindTo(contextKeyService);
    this.g = $Sjb.MultipleSignatures.bindTo(contextKeyService);
  }
  t() {
    const element = $63(".editor-widget.parameter-hints-widget");
    const wrapper = $bk(element, $63(".phwrapper"));
    wrapper.tabIndex = -1;
    const controls = $bk(wrapper, $63(".controls"));
    const previous = $bk(controls, $63(".button" + ThemeIcon.asCSSSelector(parameterHintsPreviousIcon)));
    const overloads = $bk(controls, $63(".overloads"));
    const next = $bk(controls, $63(".button" + ThemeIcon.asCSSSelector(parameterHintsNextIcon)));
    this.B($_i(previous, "click", (e) => {
      $9j.stop(e);
      this.previous();
    }));
    this.B($_i(next, "click", (e) => {
      $9j.stop(e);
      this.next();
    }));
    const body = $63(".body");
    const scrollbar = new $CZ(body, {
      alwaysConsumeMouseWheel: true
    });
    this.B(scrollbar);
    wrapper.appendChild(scrollbar.getDomNode());
    const signature = $bk(body, $63(".signature"));
    const docs = $bk(body, $63(".docs"));
    element.style.userSelect = "text";
    this.h = {
      element,
      signature,
      overloads,
      docs,
      scrollbar
    };
    this.n.addContentWidget(this);
    this.hide();
    this.B(this.n.onDidChangeCursorSelection((e) => {
      if (this.j) {
        this.n.layoutContentWidget(this);
      }
    }));
    const updateFont = () => {
      if (!this.h) {
        return;
      }
      const fontInfo = this.n.getOption(
        52
        /* EditorOption.fontInfo */
      );
      const element2 = this.h.element;
      element2.style.fontSize = `${fontInfo.fontSize}px`;
      element2.style.lineHeight = `${fontInfo.lineHeight / fontInfo.fontSize}`;
      element2.style.setProperty("--vscode-parameterHintsWidget-editorFontFamily", fontInfo.fontFamily);
      element2.style.setProperty("--vscode-parameterHintsWidget-editorFontFamilyDefault", EDITOR_FONT_DEFAULTS.fontFamily);
    };
    updateFont();
    this.B(Event2.chain(this.n.onDidChangeConfiguration.bind(this.n), ($149) => $149.filter((e) => e.hasChanged(
      52
      /* EditorOption.fontInfo */
    )))(updateFont));
    this.B(this.n.onDidLayoutChange((e) => this.C()));
    this.C();
  }
  show() {
    if (this.j) {
      return;
    }
    if (!this.h) {
      this.t();
    }
    this.f.set(true);
    this.j = true;
    setTimeout(() => {
      this.h?.element.classList.add("visible");
    }, 100);
    this.n.layoutContentWidget(this);
  }
  hide() {
    this.c.clear();
    if (!this.j) {
      return;
    }
    this.f.reset();
    this.j = false;
    this.m = null;
    this.h?.element.classList.remove("visible");
    this.n.layoutContentWidget(this);
  }
  getPosition() {
    if (this.j) {
      return {
        position: this.n.getPosition(),
        preference: [
          1,
          2
          /* ContentWidgetPositionPreference.BELOW */
        ]
      };
    }
    return null;
  }
  render(hints) {
    this.c.clear();
    if (!this.h) {
      return;
    }
    const multiple = hints.signatures.length > 1;
    this.h.element.classList.toggle("multiple", multiple);
    this.g.set(multiple);
    this.h.signature.innerText = "";
    this.h.docs.innerText = "";
    const signature = hints.signatures[hints.activeSignature];
    if (!signature) {
      return;
    }
    const code = $bk(this.h.signature, $63(".code"));
    const hasParameters = signature.parameters.length > 0;
    const activeParameterIndex = signature.activeParameter ?? hints.activeParameter;
    if (!hasParameters) {
      const label3 = $bk(code, $63("span"));
      label3.textContent = signature.label;
    } else {
      this.y(code, signature, activeParameterIndex);
    }
    const activeParameter = signature.parameters[activeParameterIndex];
    if (activeParameter?.documentation) {
      const documentation = $63("span.documentation");
      if (typeof activeParameter.documentation === "string") {
        documentation.textContent = activeParameter.documentation;
      } else {
        const renderedContents = this.u(activeParameter.documentation);
        documentation.appendChild(renderedContents.element);
      }
      $bk(this.h.docs, $63("p", {}, documentation));
    }
    if (signature.documentation === void 0) {
    } else if (typeof signature.documentation === "string") {
      $bk(this.h.docs, $63("p", {}, signature.documentation));
    } else {
      const renderedContents = this.u(signature.documentation);
      $bk(this.h.docs, renderedContents.element);
    }
    const hasDocs = this.w(signature, activeParameter);
    this.h.signature.classList.toggle("has-docs", hasDocs);
    this.h.docs.classList.toggle("empty", !hasDocs);
    this.h.overloads.textContent = String(hints.activeSignature + 1).padStart(hints.signatures.length.toString().length, "0") + "/" + hints.signatures.length;
    if (activeParameter) {
      let labelToAnnounce = "";
      const param = signature.parameters[activeParameterIndex];
      if (Array.isArray(param.label)) {
        labelToAnnounce = signature.label.substring(param.label[0], param.label[1]);
      } else {
        labelToAnnounce = param.label;
      }
      if (param.documentation) {
        labelToAnnounce += typeof param.documentation === "string" ? `, ${param.documentation}` : `, ${param.documentation.value}`;
      }
      if (signature.documentation) {
        labelToAnnounce += typeof signature.documentation === "string" ? `, ${signature.documentation}` : `, ${signature.documentation.value}`;
      }
      if (this.m !== labelToAnnounce) {
        $$Z(localize(1358, null, labelToAnnounce));
        this.m = labelToAnnounce;
      }
    }
    this.n.layoutContentWidget(this);
    this.h.scrollbar.scanDomNode();
  }
  u(markdown) {
    const stopWatch = new $te();
    const renderedContents = this.c.add(this.b.render(markdown, {
      asyncRenderCallback: () => {
        this.h?.scrollbar.scanDomNode();
      }
    }));
    renderedContents.element.classList.add("markdown-docs");
    const renderDuration = stopWatch.elapsed();
    if (renderDuration > 300) {
      this.s.publicLog2("parameterHints.parseMarkdown", {
        renderDuration
      });
    }
    return renderedContents;
  }
  w(signature, activeParameter) {
    if (activeParameter && typeof activeParameter.documentation === "string" && $Kg(activeParameter.documentation).length > 0) {
      return true;
    }
    if (activeParameter && typeof activeParameter.documentation === "object" && $Kg(activeParameter.documentation).value.length > 0) {
      return true;
    }
    if (signature.documentation && typeof signature.documentation === "string" && $Kg(signature.documentation).length > 0) {
      return true;
    }
    if (signature.documentation && typeof signature.documentation === "object" && $Kg(signature.documentation.value).length > 0) {
      return true;
    }
    return false;
  }
  y(parent, signature, activeParameterIndex) {
    const [start, end] = this.z(signature, activeParameterIndex);
    const beforeSpan = document.createElement("span");
    beforeSpan.textContent = signature.label.substring(0, start);
    const paramSpan = document.createElement("span");
    paramSpan.textContent = signature.label.substring(start, end);
    paramSpan.className = "parameter active";
    const afterSpan = document.createElement("span");
    afterSpan.textContent = signature.label.substring(end);
    $bk(parent, beforeSpan, paramSpan, afterSpan);
  }
  z(signature, paramIdx) {
    const param = signature.parameters[paramIdx];
    if (!param) {
      return [0, 0];
    } else if (Array.isArray(param.label)) {
      return param.label;
    } else if (!param.label.length) {
      return [0, 0];
    } else {
      const regex = new RegExp(`(\\W|^)${$Af(param.label)}(?=\\W|$)`, "g");
      regex.test(signature.label);
      const idx = regex.lastIndex - param.label.length;
      return idx >= 0 ? [idx, regex.lastIndex] : [0, 0];
    }
  }
  next() {
    this.n.focus();
    this.r.next();
  }
  previous() {
    this.n.focus();
    this.r.previous();
  }
  getDomNode() {
    if (!this.h) {
      this.t();
    }
    return this.h.element;
  }
  getId() {
    return $Vjb_1.a;
  }
  C() {
    if (!this.h) {
      return;
    }
    const height = Math.max(this.n.getLayoutInfo().height / 4, 250);
    const maxHeight = `${height}px`;
    this.h.element.style.maxHeight = maxHeight;
    const wrapper = this.h.element.getElementsByClassName("phwrapper");
    if (wrapper.length) {
      wrapper[0].style.maxHeight = maxHeight;
    }
  }
};
$Vjb = $Vjb_1 = __decorate([
  __param(2, $on),
  __param(3, $O4),
  __param(4, $1E),
  __param(5, $zv)
], $Vjb);
$5n("editorHoverWidget.highlightForeground", $ur, localize(1359, null));

// out-build/vs/editor/contrib/parameterHints/browser/parameterHints.js
var $Wjb_1;
var $Wjb = class $Wjb2 extends $3c {
  static {
    $Wjb_1 = this;
  }
  static {
    this.ID = "editor.controller.parameterHints";
  }
  static get(editor) {
    return editor.getContribution($Wjb_1.ID);
  }
  constructor(editor, instantiationService, languageFeaturesService) {
    super();
    this.a = editor;
    this.b = this.B(new $Ujb(editor, languageFeaturesService.signatureHelpProvider));
    this.B(this.b.onChangedHints((newParameterHints) => {
      if (newParameterHints) {
        this.c.value.show();
        this.c.value.render(newParameterHints);
      } else {
        this.c.rawValue?.hide();
      }
    }));
    this.c = new $sf(() => this.B(instantiationService.createInstance($Vjb, this.a, this.b)));
  }
  cancel() {
    this.b.cancel();
  }
  previous() {
    this.c.rawValue?.previous();
  }
  next() {
    this.c.rawValue?.next();
  }
  trigger(context) {
    this.b.trigger(context, 0);
  }
};
$Wjb = $Wjb_1 = __decorate([
  __param(1, $Pk),
  __param(2, $mP)
], $Wjb);
var $Xjb = class extends $Z5 {
  constructor() {
    super({
      id: "editor.action.triggerParameterHints",
      label: localize2(1355, "Trigger Parameter Hints"),
      precondition: EditorContextKeys.hasSignatureHelpProvider,
      kbOpts: {
        kbExpr: EditorContextKeys.editorTextFocus,
        primary: 2048 | 1024 | 10,
        weight: 100
        /* KeybindingWeight.EditorContrib */
      }
    });
  }
  run(accessor, editor) {
    const controller = $Wjb.get(editor);
    controller?.trigger({
      triggerKind: SignatureHelpTriggerKind.Invoke
    });
  }
};
$85(
  $Wjb.ID,
  $Wjb,
  2
  /* EditorContributionInstantiation.BeforeFirstInteraction */
);
$55($Xjb);
var weight3 = 100 + 75;
var ParameterHintsCommand = $Y5.bindToContribution($Wjb.get);
$45(new ParameterHintsCommand({
  id: "closeParameterHints",
  precondition: $Sjb.Visible,
  handler: (x) => x.cancel(),
  kbOpts: {
    weight: weight3,
    kbExpr: EditorContextKeys.focus,
    primary: 9,
    secondary: [
      1024 | 9
      /* KeyCode.Escape */
    ]
  }
}));
$45(new ParameterHintsCommand({
  id: "showPrevParameterHint",
  precondition: $7m.and($Sjb.Visible, $Sjb.MultipleSignatures),
  handler: (x) => x.previous(),
  kbOpts: {
    weight: weight3,
    kbExpr: EditorContextKeys.focus,
    primary: 16,
    secondary: [
      512 | 16
      /* KeyCode.UpArrow */
    ],
    mac: { primary: 16, secondary: [
      512 | 16,
      256 | 46
      /* KeyCode.KeyP */
    ] }
  }
}));
$45(new ParameterHintsCommand({
  id: "showNextParameterHint",
  precondition: $7m.and($Sjb.Visible, $Sjb.MultipleSignatures),
  handler: (x) => x.next(),
  kbOpts: {
    weight: weight3,
    kbExpr: EditorContextKeys.focus,
    primary: 18,
    secondary: [
      512 | 18
      /* KeyCode.DownArrow */
    ],
    mac: { primary: 18, secondary: [
      512 | 18,
      256 | 44
      /* KeyCode.KeyN */
    ] }
  }
}));

// out-build/vs/editor/contrib/placeholderText/browser/placeholderTextContribution.js
var $Yjb = class _$Yjb extends $3c {
  static get(editor) {
    return editor.getContribution(_$Yjb.ID);
  }
  static {
    this.ID = "editor.contrib.placeholderText";
  }
  constructor(j) {
    super();
    this.j = j;
    this.a = $79(this.j);
    this.b = this.a.getOption(
      92
      /* EditorOption.placeholder */
    );
    this.c = $4d({ owner: this, equalsFn: $rd }, (reader) => {
      const p = this.b.read(reader);
      if (!p) {
        return void 0;
      }
      if (!this.a.valueIsEmpty.read(reader)) {
        return void 0;
      }
      return { placeholder: p };
    });
    this.f = isOrWasTrue(this, (reader) => this.c.read(reader)?.placeholder !== void 0);
    this.g = $6d((reader, store) => {
      if (!this.f.read(reader)) {
        return;
      }
      const element = h("div.editorPlaceholder");
      store.add($td((reader2) => {
        const data = this.c.read(reader2);
        const shouldBeVisibile = data?.placeholder !== void 0;
        element.root.style.display = shouldBeVisibile ? "block" : "none";
        element.root.innerText = data?.placeholder ?? "";
      }));
      store.add($td((reader2) => {
        const info = this.a.layoutInfo.read(reader2);
        element.root.style.left = `${info.contentLeft}px`;
        element.root.style.width = info.contentWidth - info.verticalScrollbarWidth + "px";
        element.root.style.top = `${this.j.getTopForLineNumber(0)}px`;
      }));
      store.add($td((reader2) => {
        element.root.style.fontFamily = this.a.getOption(
          51
          /* EditorOption.fontFamily */
        ).read(reader2);
        element.root.style.fontSize = this.a.getOption(
          54
          /* EditorOption.fontSize */
        ).read(reader2) + "px";
        element.root.style.lineHeight = this.a.getOption(
          68
          /* EditorOption.lineHeight */
        ).read(reader2) + "px";
      }));
      store.add(this.a.createOverlayWidget({
        allowEditorOverflow: false,
        minContentWidthInPx: $Bd(0),
        position: $Bd(null),
        domNode: element.root
      }));
    });
    this.g.recomputeInitiallyAndOnChange(this.q);
  }
};
function isOrWasTrue(owner, fn) {
  return $Pd(owner, (reader, lastValue) => {
    if (lastValue === true) {
      return true;
    }
    return fn(reader);
  });
}

// out-build/vs/platform/observable/common/wrapInReloadableClass.js
function $Zjb(getClass) {
  return !$L3() ? getClass() : createWrapper2(getClass, BaseClass03);
}
var BaseClass2 = class {
  constructor(instantiationService) {
    this.instantiationService = instantiationService;
  }
  init(...params) {
  }
};
function createWrapper2(getClass, B) {
  return class ReloadableWrapper extends B {
    constructor() {
      super(...arguments);
      this.a = void 0;
    }
    init(...params) {
      this.a = $xd((reader, store) => {
        const clazz = $N3(getClass(), reader);
        store.add(this.instantiationService.createInstance(clazz, ...params));
      });
    }
    dispose() {
      this.a?.dispose();
    }
  };
}
var BaseClass03 = class BaseClass04 extends BaseClass2 {
  constructor(i2) {
    super(i2);
    this.init();
  }
};
BaseClass03 = __decorate([
  __param(0, $Pk)
], BaseClass03);
function $1jb(getClass) {
  return !$L3() ? getClass() : createWrapper2(getClass, BaseClass13);
}
var BaseClass13 = class BaseClass14 extends BaseClass2 {
  constructor(param1, i2) {
    super(i2);
    this.init(param1);
  }
};
BaseClass13 = __decorate([
  __param(1, $Pk)
], BaseClass13);

// out-build/vs/editor/contrib/placeholderText/browser/placeholderText.contribution.js
$85(
  $Yjb.ID,
  $1jb(() => $Yjb),
  0
  /* EditorContributionInstantiation.Eager */
);
$5n("editor.placeholder.foreground", $nH, localize(1377, null));

// out-build/vs/editor/common/services/textResourceConfiguration.js
var $zG = $Qk("textResourceConfigurationService");
var $AG = $Qk("textResourcePropertiesService");

// out-build/vs/editor/contrib/rename/browser/renameWidget.js
var _sticky4 = false;
var $2jb = new $nn("renameInputVisible", false, localize(1429, null));
var $3jb = new $nn("renameInputFocused", false, localize(1430, null));
var $4jb = class $4jb2 {
  constructor(z, A, B, C, contextKeyService, D) {
    this.z = z;
    this.A = A;
    this.B = B;
    this.C = C;
    this.D = D;
    this.allowEditorOverflow = true;
    this.y = new $2c();
    this.x = $2jb.bindTo(contextKeyService);
    this.l = false;
    this.s = 0;
    this.t = false;
    this.m = /* @__PURE__ */ new Set();
    this.q = new $te();
    this.b = new InputWithButton();
    this.y.add(this.b);
    this.z.addContentWidget(this);
    this.y.add(this.z.onDidChangeConfiguration((e) => {
      if (e.hasChanged(
        52
        /* EditorOption.fontInfo */
      )) {
        this.F();
      }
    }));
    this.y.add(B.onDidColorThemeChange(this.E, this));
  }
  dispose() {
    this.y.dispose();
    this.z.removeContentWidget(this);
  }
  getId() {
    return "__renameInputWidget";
  }
  getDomNode() {
    if (!this.a) {
      this.a = document.createElement("div");
      this.a.className = "monaco-editor rename-box";
      this.a.appendChild(this.b.domNode);
      this.d = this.y.add(new RenameCandidateListView(this.a, {
        fontInfo: this.z.getOption(
          52
          /* EditorOption.fontInfo */
        ),
        onFocusChange: (newSymbolName) => {
          this.b.input.value = newSymbolName;
          this.l = false;
        },
        onSelectionChange: () => {
          this.l = false;
          this.acceptInput(false);
        }
      }));
      this.y.add(this.b.onDidInputChange(() => {
        if (this.d?.focusedCandidate !== void 0) {
          this.l = true;
        }
        this.r ??= this.q.elapsed();
        if (this.u?.token.isCancellationRequested === false) {
          this.u.cancel();
        }
        this.d?.clearFocus();
      }));
      this.f = document.createElement("div");
      this.f.className = "rename-label";
      this.a.appendChild(this.f);
      this.F();
      this.E(this.B.getColorTheme());
    }
    return this.a;
  }
  E(theme) {
    if (!this.a) {
      return;
    }
    const widgetShadowColor = theme.getColor($Rp);
    const widgetBorderColor = theme.getColor($Sp);
    this.a.style.backgroundColor = String(theme.getColor($Qo) ?? "");
    this.a.style.boxShadow = widgetShadowColor ? ` 0 0 8px 2px ${widgetShadowColor}` : "";
    this.a.style.border = widgetBorderColor ? `1px solid ${widgetBorderColor}` : "";
    this.a.style.color = String(theme.getColor($yq) ?? "");
    const border = theme.getColor($zq);
    this.b.domNode.style.backgroundColor = String(theme.getColor($xq) ?? "");
    this.b.input.style.backgroundColor = String(theme.getColor($xq) ?? "");
    this.b.domNode.style.borderWidth = border ? "1px" : "0px";
    this.b.domNode.style.borderStyle = border ? "solid" : "none";
    this.b.domNode.style.borderColor = border?.toString() ?? "none";
  }
  F() {
    if (this.a === void 0) {
      return;
    }
    $Jg(this.f !== void 0, "RenameWidget#_updateFont: _label must not be undefined given _domNode is defined");
    this.z.applyFontInfo(this.b.input);
    const fontInfo = this.z.getOption(
      52
      /* EditorOption.fontInfo */
    );
    this.f.style.fontSize = `${this.G(fontInfo.fontSize)}px`;
  }
  G(editorFontSize) {
    return editorFontSize * 0.8;
  }
  getPosition() {
    if (!this.o) {
      return null;
    }
    if (!this.z.hasModel() || // @ulugbekna: shouldn't happen
    !this.z.getDomNode()) {
      return null;
    }
    const bodyBox = $qj(this.getDomNode().ownerDocument.body);
    const editorBox = $vj(this.z.getDomNode());
    const cursorBoxTop = this.P();
    this.g = cursorBoxTop + editorBox.top;
    this.h = bodyBox.height - this.g;
    const lineHeight = this.z.getOption(
      68
      /* EditorOption.lineHeight */
    );
    const { totalHeight: candidateViewHeight } = RenameCandidateView.getLayoutInfo({ lineHeight });
    const positionPreference = this.h > candidateViewHeight * 6 ? [
      2,
      1
      /* ContentWidgetPositionPreference.ABOVE */
    ] : [
      1,
      2
      /* ContentWidgetPositionPreference.BELOW */
    ];
    return {
      position: this.i,
      preference: positionPreference
    };
  }
  beforeRender() {
    const [accept, preview] = this.A;
    this.f.innerText = localize(1431, null, this.C.lookupKeybinding(accept)?.getLabel(), this.C.lookupKeybinding(preview)?.getLabel());
    this.a.style.minWidth = `200px`;
    return null;
  }
  afterRender(position) {
    if (position === null) {
      this.cancelInput(true, "afterRender (because position is null)");
      return;
    }
    if (!this.z.hasModel() || // shouldn't happen
    !this.z.getDomNode()) {
      return;
    }
    $Jg(this.d);
    $Jg(this.g !== void 0);
    $Jg(this.h !== void 0);
    const inputBoxHeight = $Bj(this.b.domNode);
    const labelHeight = $Bj(this.f);
    let totalHeightAvailable;
    if (position === 2) {
      totalHeightAvailable = this.h;
    } else {
      totalHeightAvailable = this.g;
    }
    this.d.layout({
      height: totalHeightAvailable - labelHeight - inputBoxHeight,
      width: $xj(this.b.domNode)
    });
  }
  acceptInput(wantsPreview) {
    this.Q(`invoking acceptInput`);
    this.H?.(wantsPreview);
  }
  cancelInput(focusEditor, caller) {
    this.I?.(focusEditor);
  }
  focusNextRenameSuggestion() {
    if (!this.d?.focusNext()) {
      this.b.input.value = this.j;
    }
  }
  focusPreviousRenameSuggestion() {
    if (!this.d?.focusPrevious()) {
      this.b.input.value = this.j;
    }
  }
  /**
   * @param requestRenameCandidates is `undefined` when there are no rename suggestion providers
   */
  getInput(where, currentName, supportPreview, requestRenameCandidates, cts) {
    const { start: selectionStart, end: selectionEnd } = this.L(where, currentName);
    this.w = cts;
    const disposeOnDone = new $2c();
    this.s = 0;
    this.t = false;
    if (requestRenameCandidates === void 0) {
      this.b.button.style.display = "none";
    } else {
      this.b.button.style.display = "flex";
      this.J = requestRenameCandidates;
      this.K(currentName, false);
      disposeOnDone.add($_i(this.b.button, "click", () => this.K(currentName, true)));
      disposeOnDone.add($_i(this.b.button, $7j.KEY_DOWN, (e) => {
        const keyEvent = new $if(e);
        if (keyEvent.equals(
          3
          /* KeyCode.Enter */
        ) || keyEvent.equals(
          10
          /* KeyCode.Space */
        )) {
          keyEvent.stopPropagation();
          keyEvent.preventDefault();
          this.K(currentName, true);
        }
      }));
    }
    this.l = false;
    this.a.classList.toggle("preview", supportPreview);
    this.i = new $8C(where.startLineNumber, where.startColumn);
    this.j = currentName;
    this.b.input.value = currentName;
    this.b.input.setAttribute("selectionStart", selectionStart.toString());
    this.b.input.setAttribute("selectionEnd", selectionEnd.toString());
    this.b.input.size = Math.max((where.endColumn - where.startColumn) * 1.1, 20);
    this.q.reset();
    disposeOnDone.add($1c(() => {
      this.w = void 0;
      cts.dispose(true);
    }));
    disposeOnDone.add($1c(() => {
      if (this.u !== void 0) {
        this.u.dispose(true);
        this.u = void 0;
      }
    }));
    disposeOnDone.add($1c(() => this.m.clear()));
    const inputResult = new $gi();
    inputResult.p.finally(() => {
      disposeOnDone.dispose();
      this.O();
    });
    this.I = (focusEditor) => {
      this.Q("invoking _currentCancelInput");
      this.H = void 0;
      this.I = void 0;
      this.d?.clearCandidates();
      inputResult.complete(focusEditor);
      return true;
    };
    this.H = (wantsPreview) => {
      this.Q("invoking _currentAcceptInput");
      $Jg(this.d !== void 0);
      const nRenameSuggestions = this.d.nCandidates;
      let newName;
      let source;
      const focusedCandidate = this.d.focusedCandidate;
      if (focusedCandidate !== void 0) {
        this.Q("using new name from renameSuggestion");
        newName = focusedCandidate;
        source = { k: "renameSuggestion" };
      } else {
        this.Q("using new name from inputField");
        newName = this.b.input.value;
        source = this.l ? { k: "userEditedRenameSuggestion" } : { k: "inputField" };
      }
      if (newName === currentName || newName.trim().length === 0) {
        this.cancelInput(true, "_currentAcceptInput (because newName === value || newName.trim().length === 0)");
        return;
      }
      this.H = void 0;
      this.I = void 0;
      this.d.clearCandidates();
      inputResult.complete({
        newName,
        wantsPreview: supportPreview && wantsPreview,
        stats: {
          source,
          nRenameSuggestions,
          timeBeforeFirstInputFieldEdit: this.r,
          nRenameSuggestionsInvocations: this.s,
          hadAutomaticRenameSuggestionsInvocation: this.t
        }
      });
    };
    disposeOnDone.add(cts.token.onCancellationRequested(() => this.cancelInput(true, "cts.token.onCancellationRequested")));
    if (!_sticky4) {
      disposeOnDone.add(this.z.onDidBlurEditorWidget(() => this.cancelInput(!this.a?.ownerDocument.hasFocus(), "editor.onDidBlurEditorWidget")));
    }
    this.M();
    return inputResult.p;
  }
  K(currentName, isManuallyTriggered) {
    if (this.J === void 0) {
      return;
    }
    if (this.u !== void 0) {
      this.u.dispose(true);
    }
    $Jg(this.w);
    if (this.b.buttonState !== "stop") {
      this.u = new $ad();
      const triggerKind = isManuallyTriggered ? NewSymbolNameTriggerKind.Invoke : NewSymbolNameTriggerKind.Automatic;
      const candidates = this.J(triggerKind, this.u.token);
      if (candidates.length === 0) {
        this.b.setSparkleButton();
        return;
      }
      if (!isManuallyTriggered) {
        this.t = true;
      }
      this.s += 1;
      this.b.setStopButton();
      this.N(candidates, currentName, this.w.token);
    }
  }
  /**
   * This allows selecting only part of the symbol name in the input field based on the selection in the editor
   */
  L(where, currentName) {
    $Jg(this.z.hasModel());
    const selection = this.z.getSelection();
    let start = 0;
    let end = currentName.length;
    if (!$9C.isEmpty(selection) && !$9C.spansMultipleLines(selection) && $9C.containsRange(where, selection)) {
      start = Math.max(0, selection.startColumn - where.startColumn);
      end = Math.min(where.endColumn, selection.endColumn) - where.startColumn;
    }
    return { start, end };
  }
  M() {
    this.Q("invoking _show");
    this.z.revealLineInCenterIfOutsideViewport(
      this.i.lineNumber,
      0
      /* ScrollType.Smooth */
    );
    this.o = true;
    this.x.set(true);
    this.z.layoutContentWidget(this);
    setTimeout(() => {
      this.b.input.focus();
      this.b.input.setSelectionRange(parseInt(this.b.input.getAttribute("selectionStart")), parseInt(this.b.input.getAttribute("selectionEnd")));
    }, 100);
  }
  async N(candidates, currentName, token) {
    const trace = (...args2) => this.Q("_updateRenameCandidates", ...args2);
    trace("start");
    const namesListResults = await $Ih(Promise.allSettled(candidates), token);
    this.b.setSparkleButton();
    if (namesListResults === void 0) {
      trace("returning early - received updateRenameCandidates results - undefined");
      return;
    }
    const newNames = namesListResults.flatMap((namesListResult) => namesListResult.status === "fulfilled" && $Hg(namesListResult.value) ? namesListResult.value : []);
    trace(`received updateRenameCandidates results - total (unfiltered) ${newNames.length} candidates.`);
    const distinctNames = $Rb(newNames, (v) => v.newSymbolName);
    trace(`distinct candidates - ${distinctNames.length} candidates.`);
    const validDistinctNames = distinctNames.filter(({ newSymbolName }) => newSymbolName.trim().length > 0 && newSymbolName !== this.b.input.value && newSymbolName !== currentName && !this.m.has(newSymbolName));
    trace(`valid distinct candidates - ${newNames.length} candidates.`);
    validDistinctNames.forEach((n) => this.m.add(n.newSymbolName));
    if (validDistinctNames.length < 1) {
      trace("returning early - no valid distinct candidates");
      return;
    }
    trace("setting candidates");
    this.d.setCandidates(validDistinctNames);
    trace("asking editor to re-layout");
    this.z.layoutContentWidget(this);
  }
  O() {
    this.Q("invoked _hide");
    this.o = false;
    this.x.reset();
    this.z.layoutContentWidget(this);
  }
  P() {
    const visibleRanges = this.z.getVisibleRanges();
    let firstLineInViewport;
    if (visibleRanges.length > 0) {
      firstLineInViewport = visibleRanges[0].startLineNumber;
    } else {
      this.D.warn("RenameWidget#_getTopForPosition: this should not happen - visibleRanges is empty");
      firstLineInViewport = Math.max(1, this.i.lineNumber - 5);
    }
    return this.z.getTopForLineNumber(this.i.lineNumber) - this.z.getTopForLineNumber(firstLineInViewport);
  }
  Q(...args2) {
    this.D.trace("RenameWidget", ...args2);
  }
};
$4jb = __decorate([
  __param(2, $gs),
  __param(3, $Ty),
  __param(4, $on),
  __param(5, $wn)
], $4jb);
var RenameCandidateListView = class _RenameCandidateListView {
  // FIXME@ulugbekna: rewrite using event emitters
  constructor(parent, opts) {
    this.i = new $2c();
    this.f = 0;
    this.g = 0;
    this.d = opts.fontInfo.lineHeight;
    this.h = opts.fontInfo.typicalHalfwidthCharacterWidth;
    this.a = document.createElement("div");
    this.a.className = "rename-box rename-candidate-list-container";
    parent.appendChild(this.a);
    this.b = _RenameCandidateListView.o(this.a, this.j, opts.fontInfo);
    this.b.onDidChangeFocus((e) => {
      if (e.elements.length === 1) {
        opts.onFocusChange(e.elements[0].newSymbolName);
      }
    }, this.i);
    this.b.onDidChangeSelection((e) => {
      if (e.elements.length === 1) {
        opts.onSelectionChange();
      }
    }, this.i);
    this.i.add(this.b.onDidBlur((e) => {
      this.b.setFocus([]);
    }));
    this.b.style($J$({
      listInactiveFocusForeground: $2r,
      listInactiveFocusBackground: $4r
    }));
  }
  dispose() {
    this.b.dispose();
    this.i.dispose();
  }
  // height - max height allowed by parent element
  layout({ height, width: width2 }) {
    this.f = height;
    this.g = width2;
  }
  setCandidates(candidates) {
    this.b.splice(0, 0, candidates);
    const height = this.l(this.b.length);
    const width2 = this.m(candidates);
    this.b.layout(height, width2);
    this.a.style.height = `${height}px`;
    this.a.style.width = `${width2}px`;
    $_Z(localize(1432, null, candidates.length));
  }
  clearCandidates() {
    this.a.style.height = "0px";
    this.a.style.width = "0px";
    this.b.splice(0, this.b.length, []);
  }
  get nCandidates() {
    return this.b.length;
  }
  get focusedCandidate() {
    if (this.b.length === 0) {
      return;
    }
    const selectedElement = this.b.getSelectedElements()[0];
    if (selectedElement !== void 0) {
      return selectedElement.newSymbolName;
    }
    const focusedElement = this.b.getFocusedElements()[0];
    if (focusedElement !== void 0) {
      return focusedElement.newSymbolName;
    }
    return;
  }
  focusNext() {
    if (this.b.length === 0) {
      return false;
    }
    const focusedIxs = this.b.getFocus();
    if (focusedIxs.length === 0) {
      this.b.focusFirst();
      this.b.reveal(0);
      return true;
    } else {
      if (focusedIxs[0] === this.b.length - 1) {
        this.b.setFocus([]);
        this.b.reveal(0);
        return false;
      } else {
        this.b.focusNext();
        const focused = this.b.getFocus()[0];
        this.b.reveal(focused);
        return true;
      }
    }
  }
  /**
   * @returns true if focus is moved to previous element
   */
  focusPrevious() {
    if (this.b.length === 0) {
      return false;
    }
    const focusedIxs = this.b.getFocus();
    if (focusedIxs.length === 0) {
      this.b.focusLast();
      const focused = this.b.getFocus()[0];
      this.b.reveal(focused);
      return true;
    } else {
      if (focusedIxs[0] === 0) {
        this.b.setFocus([]);
        return false;
      } else {
        this.b.focusPrevious();
        const focused = this.b.getFocus()[0];
        this.b.reveal(focused);
        return true;
      }
    }
  }
  clearFocus() {
    this.b.setFocus([]);
  }
  get j() {
    const { totalHeight } = RenameCandidateView.getLayoutInfo({ lineHeight: this.d });
    return totalHeight;
  }
  l(nCandidates) {
    const heightToFitAllCandidates = this.j * nCandidates;
    const MAX_N_CANDIDATES = 7;
    const height = Math.min(heightToFitAllCandidates, this.f, this.j * MAX_N_CANDIDATES);
    return height;
  }
  m(candidates) {
    const longestCandidateWidth = Math.ceil(Math.max(...candidates.map((c) => c.newSymbolName.length)) * this.h);
    const width2 = Math.max(
      this.g,
      4 + 16 + 5 + longestCandidateWidth + 10
      /* (possibly visible) scrollbar width */
      // TODO@ulugbekna: approximate calc - clean this up
    );
    return width2;
  }
  static o(container2, candidateViewHeight, fontInfo) {
    const virtualDelegate = new class {
      getTemplateId(element) {
        return "candidate";
      }
      getHeight(element) {
        return candidateViewHeight;
      }
    }();
    const renderer = new class {
      constructor() {
        this.templateId = "candidate";
      }
      renderTemplate(container3) {
        return new RenameCandidateView(container3, fontInfo);
      }
      renderElement(candidate, index, templateData) {
        templateData.populate(candidate);
      }
      disposeTemplate(templateData) {
        templateData.dispose();
      }
    }();
    return new $A1("NewSymbolNameCandidates", container2, virtualDelegate, [renderer], {
      keyboardSupport: false,
      // @ulugbekna: because we handle keyboard events through proper commands & keybinding service, see `rename.ts`
      mouseSupport: true,
      multipleSelectionSupport: false
    });
  }
};
var InputWithButton = class {
  constructor() {
    this.g = "";
    this.m = new $ze();
    this.onDidInputChange = this.m.event;
    this.o = new $2c();
  }
  get domNode() {
    if (!this.b) {
      this.b = document.createElement("div");
      this.b.className = "rename-input-with-button";
      this.b.style.display = "flex";
      this.b.style.flexDirection = "row";
      this.b.style.alignItems = "center";
      this.d = document.createElement("input");
      this.d.className = "rename-input";
      this.d.type = "text";
      this.d.style.border = "none";
      this.d.setAttribute("aria-label", localize(1433, null));
      this.b.appendChild(this.d);
      this.f = document.createElement("div");
      this.f.className = "rename-suggestions-button";
      this.f.setAttribute("tabindex", "0");
      this.h = localize(1434, null);
      this.i = localize(1435, null);
      this.g = this.h;
      this.o.add($J1().setupDelayedHover(this.f, () => ({
        content: this.g,
        appearance: {
          showPointer: true,
          compact: true
        }
      })));
      this.b.appendChild(this.f);
      this.o.add($_i(this.input, $7j.INPUT, () => this.m.fire()));
      this.o.add($_i(this.input, $7j.KEY_DOWN, (e) => {
        const keyEvent = new $if(e);
        if (keyEvent.keyCode === 15 || keyEvent.keyCode === 17) {
          this.m.fire();
        }
      }));
      this.o.add($_i(this.input, $7j.CLICK, () => this.m.fire()));
      this.o.add($_i(this.input, $7j.FOCUS, () => {
        this.domNode.style.outlineWidth = "1px";
        this.domNode.style.outlineStyle = "solid";
        this.domNode.style.outlineOffset = "-1px";
        this.domNode.style.outlineColor = "var(--vscode-focusBorder)";
      }));
      this.o.add($_i(this.input, $7j.BLUR, () => {
        this.domNode.style.outline = "none";
      }));
    }
    return this.b;
  }
  get input() {
    $Jg(this.d);
    return this.d;
  }
  get button() {
    $Jg(this.f);
    return this.f;
  }
  get buttonState() {
    return this.a;
  }
  setSparkleButton() {
    this.a = "sparkle";
    this.j ??= $C1($6l.sparkle);
    $$i(this.button);
    this.button.appendChild(this.j);
    this.button.setAttribute("aria-label", "Generating new name suggestions");
    this.g = this.h;
    this.input.focus();
  }
  setStopButton() {
    this.a = "stop";
    this.l ??= $C1($6l.stopCircle);
    $$i(this.button);
    this.button.appendChild(this.l);
    this.button.setAttribute("aria-label", "Cancel generating new name suggestions");
    this.g = this.i;
    this.input.focus();
  }
  dispose() {
    this.o.dispose();
  }
};
var RenameCandidateView = class _RenameCandidateView {
  static {
    this.a = 2;
  }
  constructor(parent, fontInfo) {
    this.b = document.createElement("div");
    this.b.className = "rename-box rename-candidate";
    this.b.style.display = `flex`;
    this.b.style.columnGap = `5px`;
    this.b.style.alignItems = `center`;
    this.b.style.height = `${fontInfo.lineHeight}px`;
    this.b.style.padding = `${_RenameCandidateView.a}px`;
    const iconContainer = document.createElement("div");
    iconContainer.style.display = `flex`;
    iconContainer.style.alignItems = `center`;
    iconContainer.style.width = iconContainer.style.height = `${fontInfo.lineHeight * 0.8}px`;
    this.b.appendChild(iconContainer);
    this.d = $C1($6l.sparkle);
    this.d.style.display = `none`;
    iconContainer.appendChild(this.d);
    this.f = document.createElement("div");
    $24(this.f, fontInfo);
    this.b.appendChild(this.f);
    parent.appendChild(this.b);
  }
  populate(value) {
    this.g(value);
    this.h(value);
  }
  g(value) {
    const isAIGenerated = !!value.tags?.includes(NewSymbolNameTag.AIGenerated);
    this.d.style.display = isAIGenerated ? "inherit" : "none";
  }
  h(value) {
    this.f.innerText = value.newSymbolName;
  }
  static getLayoutInfo({ lineHeight }) {
    const totalHeight = lineHeight + _RenameCandidateView.a * 2;
    return { totalHeight };
  }
  dispose() {
  }
};

// out-build/vs/editor/contrib/rename/browser/rename.js
var RenameController_1;
var RenameSkeleton = class {
  constructor(c, d, registry4) {
    this.c = c;
    this.d = d;
    this.b = 0;
    this.a = registry4.ordered(c);
  }
  hasProvider() {
    return this.a.length > 0;
  }
  async resolveRenameLocation(token) {
    const rejects = [];
    for (this.b = 0; this.b < this.a.length; this.b++) {
      const provider = this.a[this.b];
      if (!provider.resolveRenameLocation) {
        break;
      }
      const res = await provider.resolveRenameLocation(this.c, this.d, token);
      if (!res) {
        continue;
      }
      if (res.rejectReason) {
        rejects.push(res.rejectReason);
        continue;
      }
      return res;
    }
    this.b = 0;
    const word = this.c.getWordAtPosition(this.d);
    if (!word) {
      return {
        range: $9C.fromPositions(this.d),
        text: "",
        rejectReason: rejects.length > 0 ? rejects.join("\n") : void 0
      };
    }
    return {
      range: new $9C(this.d.lineNumber, word.startColumn, this.d.lineNumber, word.endColumn),
      text: word.word,
      rejectReason: rejects.length > 0 ? rejects.join("\n") : void 0
    };
  }
  async provideRenameEdits(newName, token) {
    return this.f(newName, this.b, [], token);
  }
  async f(newName, i2, rejects, token) {
    const provider = this.a[i2];
    if (!provider) {
      return {
        edits: [],
        rejectReason: rejects.join("\n")
      };
    }
    const result = await provider.provideRenameEdits(this.c, this.d, newName, token);
    if (!result) {
      return this.f(newName, i2 + 1, rejects.concat(localize(1418, null)), token);
    } else if (result.rejectReason) {
      return this.f(newName, i2 + 1, rejects.concat(result.rejectReason), token);
    }
    return result;
  }
};
async function $5jb(registry4, model, position, newName) {
  const skeleton = new RenameSkeleton(model, position, registry4);
  const loc = await skeleton.resolveRenameLocation(CancellationToken.None);
  if (loc?.rejectReason) {
    return { edits: [], rejectReason: loc.rejectReason };
  }
  return skeleton.provideRenameEdits(newName, CancellationToken.None);
}
var RenameController = class RenameController2 {
  static {
    RenameController_1 = this;
  }
  static {
    this.ID = "editor.contrib.renameController";
  }
  static get(editor) {
    return editor.getContribution(RenameController_1.ID);
  }
  constructor(d, f, g, h3, j, l, m, n, o) {
    this.d = d;
    this.f = f;
    this.g = g;
    this.h = h3;
    this.j = j;
    this.l = l;
    this.m = m;
    this.n = n;
    this.o = o;
    this.b = new $2c();
    this.c = new $ad();
    this.a = this.b.add(this.f.createInstance($4jb, this.d, ["acceptRenameInput", "acceptRenameInputWithPreview"]));
  }
  dispose() {
    this.b.dispose();
    this.c.dispose(true);
  }
  async run() {
    const trace = this.l.trace.bind(this.l, "[rename]");
    this.c.dispose(true);
    this.c = new $ad();
    if (!this.d.hasModel()) {
      trace("editor has no model");
      return void 0;
    }
    const position = this.d.getPosition();
    const skeleton = new RenameSkeleton(this.d.getModel(), position, this.n.renameProvider);
    if (!skeleton.hasProvider()) {
      trace("skeleton has no provider");
      return void 0;
    }
    const cts1 = new $N_(this.d, 4 | 1, void 0, this.c.token);
    let loc;
    try {
      trace("resolving rename location");
      const resolveLocationOperation = skeleton.resolveRenameLocation(cts1.token);
      this.j.showWhile(resolveLocationOperation, 250);
      loc = await resolveLocationOperation;
      trace("resolved rename location");
    } catch (e) {
      if (e instanceof $lb) {
        trace("resolve rename location cancelled", JSON.stringify(e, null, "	"));
      } else {
        trace("resolve rename location failed", e instanceof Error ? e : JSON.stringify(e, null, "	"));
        if (typeof e === "string" || $dm(e)) {
          $S_.get(this.d)?.showMessage(e || localize(1419, null), position);
        }
      }
      return void 0;
    } finally {
      cts1.dispose();
    }
    if (!loc) {
      trace("returning early - no loc");
      return void 0;
    }
    if (loc.rejectReason) {
      trace(`returning early - rejected with reason: ${loc.rejectReason}`, loc.rejectReason);
      $S_.get(this.d)?.showMessage(loc.rejectReason, position);
      return void 0;
    }
    if (cts1.token.isCancellationRequested) {
      trace("returning early - cts1 cancelled");
      return void 0;
    }
    const cts2 = new $N_(this.d, 4 | 1, loc.range, this.c.token);
    const model = this.d.getModel();
    const newSymbolNamesProviders = this.n.newSymbolNamesProvider.all(model);
    const resolvedNewSymbolnamesProviders = await Promise.all(newSymbolNamesProviders.map(async (p) => [p, await p.supportsAutomaticNewSymbolNamesTriggerKind ?? false]));
    const requestRenameSuggestions = (triggerKind, cts) => {
      let providers2 = resolvedNewSymbolnamesProviders.slice();
      if (triggerKind === NewSymbolNameTriggerKind.Automatic) {
        providers2 = providers2.filter(([_, supportsAutomatic]) => supportsAutomatic);
      }
      return providers2.map(([p]) => p.provideNewSymbolNames(model, loc.range, triggerKind, cts));
    };
    trace("creating rename input field and awaiting its result");
    const supportPreview = this.h.hasPreviewHandler() && this.m.getValue(this.d.getModel().uri, "editor.rename.enablePreview");
    const inputFieldResult = await this.a.getInput(loc.range, loc.text, supportPreview, newSymbolNamesProviders.length > 0 ? requestRenameSuggestions : void 0, cts2);
    trace("received response from rename input field");
    if (newSymbolNamesProviders.length > 0) {
      this.q(newSymbolNamesProviders.length, model.getLanguageId(), inputFieldResult);
    }
    if (typeof inputFieldResult === "boolean") {
      trace(`returning early - rename input field response - ${inputFieldResult}`);
      if (inputFieldResult) {
        this.d.focus();
      }
      cts2.dispose();
      return void 0;
    }
    this.d.focus();
    trace("requesting rename edits");
    const renameOperation = $Ih(skeleton.provideRenameEdits(inputFieldResult.newName, cts2.token), cts2.token).then(async (renameResult) => {
      if (!renameResult) {
        trace("returning early - no rename edits result");
        return;
      }
      if (!this.d.hasModel()) {
        trace("returning early - no model after rename edits are provided");
        return;
      }
      if (renameResult.rejectReason) {
        trace(`returning early - rejected with reason: ${renameResult.rejectReason}`);
        this.g.info(renameResult.rejectReason);
        return;
      }
      this.d.setSelection($9C.fromPositions(this.d.getSelection().getPosition()));
      trace("applying edits");
      this.h.apply(renameResult, {
        editor: this.d,
        showPreview: inputFieldResult.wantsPreview,
        label: localize(1420, null, loc?.text, inputFieldResult.newName),
        code: "undoredo.rename",
        quotableLabel: localize(1421, null, loc?.text, inputFieldResult.newName),
        respectAutoSaveConfig: true
      }).then((result) => {
        trace("edits applied");
        if (result.ariaSummary) {
          $$Z(localize(1422, null, loc.text, inputFieldResult.newName, result.ariaSummary));
        }
      }).catch((err) => {
        trace(`error when applying edits ${JSON.stringify(err, null, "	")}`);
        this.g.error(localize(1423, null));
        this.l.error(err);
      });
    }, (err) => {
      trace("error when providing rename edits", JSON.stringify(err, null, "	"));
      this.g.error(localize(1424, null));
      this.l.error(err);
    }).finally(() => {
      cts2.dispose();
    });
    trace("returning rename operation");
    this.j.showWhile(renameOperation, 250);
    return renameOperation;
  }
  acceptRenameInput(wantsPreview) {
    this.a.acceptInput(wantsPreview);
  }
  cancelRenameInput() {
    this.a.cancelInput(true, "cancelRenameInput command");
  }
  focusNextRenameSuggestion() {
    this.a.focusNextRenameSuggestion();
  }
  focusPreviousRenameSuggestion() {
    this.a.focusPreviousRenameSuggestion();
  }
  q(nRenameSuggestionProviders, languageId, inputFieldResult) {
    const value = typeof inputFieldResult === "boolean" ? {
      kind: "cancelled",
      languageId,
      nRenameSuggestionProviders
    } : {
      kind: "accepted",
      languageId,
      nRenameSuggestionProviders,
      source: inputFieldResult.stats.source.k,
      nRenameSuggestions: inputFieldResult.stats.nRenameSuggestions,
      timeBeforeFirstInputFieldEdit: inputFieldResult.stats.timeBeforeFirstInputFieldEdit,
      wantsPreview: inputFieldResult.wantsPreview,
      nRenameSuggestionsInvocations: inputFieldResult.stats.nRenameSuggestionsInvocations,
      hadAutomaticRenameSuggestionsInvocation: inputFieldResult.stats.hadAutomaticRenameSuggestionsInvocation
    };
    this.o.publicLog2("renameInvokedEvent", value);
  }
};
RenameController = RenameController_1 = __decorate([
  __param(1, $Pk),
  __param(2, $PJ),
  __param(3, $H_),
  __param(4, $ZJ),
  __param(5, $wn),
  __param(6, $zG),
  __param(7, $mP),
  __param(8, $zv)
], RenameController);
var $6jb = class extends $Z5 {
  constructor() {
    super({
      id: "editor.action.rename",
      label: localize2(1426, "Rename Symbol"),
      precondition: $7m.and(EditorContextKeys.writable, EditorContextKeys.hasRenameProvider),
      kbOpts: {
        kbExpr: EditorContextKeys.editorTextFocus,
        primary: 60,
        weight: 100
        /* KeybindingWeight.EditorContrib */
      },
      contextMenuOpts: {
        group: "1_modification",
        order: 1.1
      }
    });
  }
  runCommand(accessor, args2) {
    const editorService = accessor.get($U5);
    const [uri, pos] = Array.isArray(args2) && args2 || [void 0, void 0];
    if (URI.isUri(uri) && $8C.isIPosition(pos)) {
      return editorService.openCodeEditor({ resource: uri }, editorService.getActiveCodeEditor()).then((editor) => {
        if (!editor) {
          return;
        }
        editor.setPosition(pos);
        editor.invokeWithinContext((accessor2) => {
          this.u(accessor2, editor);
          return this.run(accessor2, editor);
        });
      }, $gb);
    }
    return super.runCommand(accessor, args2);
  }
  run(accessor, editor) {
    const logService = accessor.get($wn);
    const controller = RenameController.get(editor);
    if (controller) {
      logService.trace("[RenameAction] got controller, running...");
      return controller.run();
    }
    logService.trace("[RenameAction] returning early - controller missing");
    return Promise.resolve();
  }
};
$85(
  RenameController.ID,
  RenameController,
  4
  /* EditorContributionInstantiation.Lazy */
);
$55($6jb);
var RenameCommand = $Y5.bindToContribution(RenameController.get);
$45(new RenameCommand({
  id: "acceptRenameInput",
  precondition: $2jb,
  handler: (x) => x.acceptRenameInput(false),
  kbOpts: {
    weight: 100 + 99,
    kbExpr: $7m.and(EditorContextKeys.focus, $7m.not("isComposing")),
    primary: 3
    /* KeyCode.Enter */
  }
}));
$45(new RenameCommand({
  id: "acceptRenameInputWithPreview",
  precondition: $7m.and($2jb, $7m.has("config.editor.rename.enablePreview")),
  handler: (x) => x.acceptRenameInput(true),
  kbOpts: {
    weight: 100 + 99,
    kbExpr: $7m.and(EditorContextKeys.focus, $7m.not("isComposing")),
    primary: 2048 + 3
    /* KeyCode.Enter */
  }
}));
$45(new RenameCommand({
  id: "cancelRenameInput",
  precondition: $2jb,
  handler: (x) => x.cancelRenameInput(),
  kbOpts: {
    weight: 100 + 99,
    kbExpr: EditorContextKeys.focus,
    primary: 9,
    secondary: [
      1024 | 9
      /* KeyCode.Escape */
    ]
  }
}));
$hJ(class FocusNextRenameSuggestion extends $gJ {
  constructor() {
    super({
      id: "focusNextRenameSuggestion",
      title: {
        ...localize2(1427, "Focus Next Rename Suggestion")
      },
      precondition: $2jb,
      keybinding: [
        {
          primary: 18,
          weight: 100 + 99
        }
      ]
    });
  }
  run(accessor) {
    const currentEditor = accessor.get($U5).getFocusedCodeEditor();
    if (!currentEditor) {
      return;
    }
    const controller = RenameController.get(currentEditor);
    if (!controller) {
      return;
    }
    controller.focusNextRenameSuggestion();
  }
});
$hJ(class FocusPreviousRenameSuggestion extends $gJ {
  constructor() {
    super({
      id: "focusPreviousRenameSuggestion",
      title: {
        ...localize2(1428, "Focus Previous Rename Suggestion")
      },
      precondition: $2jb,
      keybinding: [
        {
          primary: 16,
          weight: 100 + 99
        }
      ]
    });
  }
  run(accessor) {
    const currentEditor = accessor.get($U5).getFocusedCodeEditor();
    if (!currentEditor) {
      return;
    }
    const controller = RenameController.get(currentEditor);
    if (!controller) {
      return;
    }
    controller.focusPreviousRenameSuggestion();
  }
});
$35("_executeDocumentRenameProvider", function(accessor, model, position, ...args2) {
  const [newName] = args2;
  $Jg(typeof newName === "string");
  const { renameProvider } = accessor.get($mP);
  return $5jb(renameProvider, model, position, newName);
});
$35("_executePrepareRename", async function(accessor, model, position) {
  const { renameProvider } = accessor.get($mP);
  const skeleton = new RenameSkeleton(model, position, renameProvider);
  const loc = await skeleton.resolveRenameLocation(CancellationToken.None);
  if (loc?.rejectReason) {
    throw new Error(loc.rejectReason);
  }
  return loc;
});
$Wn.as($Ht.Configuration).registerConfiguration({
  id: "editor",
  properties: {
    "editor.rename.enablePreview": {
      scope: 5,
      description: localize(1425, null),
      default: true,
      type: "boolean"
    }
  }
});

// out-build/vs/editor/contrib/sectionHeaders/browser/sectionHeaders.js
var $7jb = class $7jb2 extends $3c {
  static {
    this.ID = "editor.sectionHeaderDetector";
  }
  constructor(h3, j, m) {
    super();
    this.h = h3;
    this.j = j;
    this.m = m;
    this.b = this.h.createDecorationsCollection();
    this.a = this.n(h3.getOption(
      74
      /* EditorOption.minimap */
    ));
    this.f = null;
    this.g = {};
    this.B(h3.onDidChangeModel((e) => {
      this.g = {};
      this.a = this.n(h3.getOption(
        74
        /* EditorOption.minimap */
      ));
      this.t();
      this.c.schedule(0);
    }));
    this.B(h3.onDidChangeModelLanguage((e) => {
      this.g = {};
      this.a = this.n(h3.getOption(
        74
        /* EditorOption.minimap */
      ));
      this.t();
      this.c.schedule(0);
    }));
    this.B(j.onDidChange((e) => {
      const editorLanguageId = this.h.getModel()?.getLanguageId();
      if (editorLanguageId && e.affects(editorLanguageId)) {
        this.g = {};
        this.a = this.n(h3.getOption(
          74
          /* EditorOption.minimap */
        ));
        this.t();
        this.c.schedule(0);
      }
    }));
    this.B(h3.onDidChangeConfiguration((e) => {
      if (this.a && !e.hasChanged(
        74
        /* EditorOption.minimap */
      )) {
        return;
      }
      this.a = this.n(h3.getOption(
        74
        /* EditorOption.minimap */
      ));
      this.s([]);
      this.t();
      this.c.schedule(0);
    }));
    this.B(this.h.onDidChangeModelContent((e) => {
      this.c.schedule();
    }));
    this.B(h3.onDidChangeModelTokens((e) => {
      if (!this.c.isScheduled()) {
        this.c.schedule(1e3);
      }
    }));
    this.c = this.B(new $8h(() => {
      this.r();
    }, 250));
    this.c.schedule(0);
  }
  n(minimap) {
    if (!minimap || !this.h.hasModel()) {
      return void 0;
    }
    const languageId = this.h.getModel().getLanguageId();
    if (!languageId) {
      return void 0;
    }
    const commentsConfiguration = this.j.getLanguageConfiguration(languageId).comments;
    const foldingRules = this.j.getLanguageConfiguration(languageId).foldingRules;
    if (!commentsConfiguration && !foldingRules?.markers) {
      return void 0;
    }
    return {
      foldingRules,
      findMarkSectionHeaders: minimap.showMarkSectionHeaders,
      findRegionSectionHeaders: minimap.showRegionSectionHeaders
    };
  }
  r() {
    if (!this.h.hasModel() || !this.a?.findMarkSectionHeaders && !this.a?.findRegionSectionHeaders) {
      return;
    }
    const model = this.h.getModel();
    if (model.isDisposed() || model.isTooLargeForSyncing()) {
      return;
    }
    const modelVersionId = model.getVersionId();
    this.m.findSectionHeaders(model.uri, this.a).then((sectionHeaders) => {
      if (model.isDisposed() || model.getVersionId() !== modelVersionId) {
        return;
      }
      this.s(sectionHeaders);
    });
  }
  s(sectionHeaders) {
    const model = this.h.getModel();
    if (model) {
      sectionHeaders = sectionHeaders.filter((sectionHeader) => {
        if (!sectionHeader.shouldBeInComments) {
          return true;
        }
        const validRange2 = model.validateRange(sectionHeader.range);
        const tokens = model.tokenization.getLineTokens(validRange2.startLineNumber);
        const idx = tokens.findTokenIndexAtOffset(validRange2.startColumn - 1);
        const tokenType = tokens.getStandardTokenType(idx);
        const languageId = tokens.getLanguageId(idx);
        return languageId === model.getLanguageId() && tokenType === 1;
      });
    }
    const oldDecorations = Object.values(this.g).map((occurrence) => occurrence.decorationId);
    const newDecorations = sectionHeaders.map((sectionHeader) => decoration2(sectionHeader));
    this.h.changeDecorations((changeAccessor) => {
      const decorations = changeAccessor.deltaDecorations(oldDecorations, newDecorations);
      this.g = {};
      for (let i2 = 0, len = decorations.length; i2 < len; i2++) {
        const occurrence = { sectionHeader: sectionHeaders[i2], decorationId: decorations[i2] };
        this.g[occurrence.decorationId] = occurrence;
      }
    });
  }
  t() {
    this.c.cancel();
    if (this.f) {
      this.f.cancel();
      this.f = null;
    }
  }
  dispose() {
    super.dispose();
    this.t();
    this.b.clear();
  }
};
$7jb = __decorate([
  __param(1, $NF),
  __param(2, $I0)
], $7jb);
function decoration2(sectionHeader) {
  return {
    range: sectionHeader.range,
    options: $WI.createDynamic({
      description: "section-header",
      stickiness: 3,
      collapseOnReplaceEdit: true,
      minimap: {
        color: void 0,
        position: 1,
        sectionHeaderStyle: sectionHeader.hasSeparatorLine ? 2 : 1,
        sectionHeaderText: sectionHeader.text
      }
    })
  };
}
$85(
  $7jb.ID,
  $7jb,
  1
  /* EditorContributionInstantiation.AfterFirstRender */
);

// out-build/vs/editor/common/tokens/sparseMultilineTokens.js
var $9F = class _$9F {
  static create(startLineNumber, tokens) {
    return new _$9F(startLineNumber, new SparseMultilineTokensStorage(tokens));
  }
  /**
   * (Inclusive) start line number for these tokens.
   */
  get startLineNumber() {
    return this.c;
  }
  /**
   * (Inclusive) end line number for these tokens.
   */
  get endLineNumber() {
    return this.d;
  }
  constructor(startLineNumber, tokens) {
    this.c = startLineNumber;
    this.e = tokens;
    this.d = this.c + this.e.getMaxDeltaLine();
  }
  toString() {
    return this.e.toString(this.c);
  }
  f() {
    this.d = this.c + this.e.getMaxDeltaLine();
  }
  isEmpty() {
    return this.e.isEmpty();
  }
  getLineTokens(lineNumber) {
    if (this.c <= lineNumber && lineNumber <= this.d) {
      return this.e.getLineTokens(lineNumber - this.c);
    }
    return null;
  }
  getRange() {
    const deltaRange = this.e.getRange();
    if (!deltaRange) {
      return deltaRange;
    }
    return new $9C(this.c + deltaRange.startLineNumber, deltaRange.startColumn, this.c + deltaRange.endLineNumber, deltaRange.endColumn);
  }
  removeTokens(range) {
    const startLineIndex = range.startLineNumber - this.c;
    const endLineIndex = range.endLineNumber - this.c;
    this.c += this.e.removeTokens(startLineIndex, range.startColumn - 1, endLineIndex, range.endColumn - 1);
    this.f();
  }
  split(range) {
    const startLineIndex = range.startLineNumber - this.c;
    const endLineIndex = range.endLineNumber - this.c;
    const [a, b, bDeltaLine] = this.e.split(startLineIndex, range.startColumn - 1, endLineIndex, range.endColumn - 1);
    return [new _$9F(this.c, a), new _$9F(this.c + bDeltaLine, b)];
  }
  applyEdit(range, text2) {
    const [eolCount, firstLineLength, lastLineLength] = $tE(text2);
    this.acceptEdit(
      range,
      eolCount,
      firstLineLength,
      lastLineLength,
      text2.length > 0 ? text2.charCodeAt(0) : 0
      /* CharCode.Null */
    );
  }
  acceptEdit(range, eolCount, firstLineLength, lastLineLength, firstCharCode) {
    this.g(range);
    this.h(new $8C(range.startLineNumber, range.startColumn), eolCount, firstLineLength, lastLineLength, firstCharCode);
    this.f();
  }
  g(range) {
    if (range.startLineNumber === range.endLineNumber && range.startColumn === range.endColumn) {
      return;
    }
    const firstLineIndex = range.startLineNumber - this.c;
    const lastLineIndex = range.endLineNumber - this.c;
    if (lastLineIndex < 0) {
      const deletedLinesCount = lastLineIndex - firstLineIndex;
      this.c -= deletedLinesCount;
      return;
    }
    const tokenMaxDeltaLine = this.e.getMaxDeltaLine();
    if (firstLineIndex >= tokenMaxDeltaLine + 1) {
      return;
    }
    if (firstLineIndex < 0 && lastLineIndex >= tokenMaxDeltaLine + 1) {
      this.c = 0;
      this.e.clear();
      return;
    }
    if (firstLineIndex < 0) {
      const deletedBefore = -firstLineIndex;
      this.c -= deletedBefore;
      this.e.acceptDeleteRange(range.startColumn - 1, 0, 0, lastLineIndex, range.endColumn - 1);
    } else {
      this.e.acceptDeleteRange(0, firstLineIndex, range.startColumn - 1, lastLineIndex, range.endColumn - 1);
    }
  }
  h(position, eolCount, firstLineLength, lastLineLength, firstCharCode) {
    if (eolCount === 0 && firstLineLength === 0) {
      return;
    }
    const lineIndex = position.lineNumber - this.c;
    if (lineIndex < 0) {
      this.c += eolCount;
      return;
    }
    const tokenMaxDeltaLine = this.e.getMaxDeltaLine();
    if (lineIndex >= tokenMaxDeltaLine + 1) {
      return;
    }
    this.e.acceptInsertText(lineIndex, position.column - 1, eolCount, firstLineLength, lastLineLength, firstCharCode);
  }
};
var SparseMultilineTokensStorage = class _SparseMultilineTokensStorage {
  constructor(tokens) {
    this.c = tokens;
    this.d = tokens.length / 4;
  }
  toString(startLineNumber) {
    const pieces = [];
    for (let i2 = 0; i2 < this.d; i2++) {
      pieces.push(`(${this.f(i2) + startLineNumber},${this.g(i2)}-${this.h(i2)})`);
    }
    return `[${pieces.join(",")}]`;
  }
  getMaxDeltaLine() {
    const tokenCount = this.e();
    if (tokenCount === 0) {
      return -1;
    }
    return this.f(tokenCount - 1);
  }
  getRange() {
    const tokenCount = this.e();
    if (tokenCount === 0) {
      return null;
    }
    const startChar = this.g(0);
    const maxDeltaLine = this.f(tokenCount - 1);
    const endChar = this.h(tokenCount - 1);
    return new $9C(0, startChar + 1, maxDeltaLine, endChar + 1);
  }
  e() {
    return this.d;
  }
  f(tokenIndex) {
    return this.c[4 * tokenIndex];
  }
  g(tokenIndex) {
    return this.c[4 * tokenIndex + 1];
  }
  h(tokenIndex) {
    return this.c[4 * tokenIndex + 2];
  }
  isEmpty() {
    return this.e() === 0;
  }
  getLineTokens(deltaLine) {
    let low = 0;
    let high = this.e() - 1;
    while (low < high) {
      const mid = low + Math.floor((high - low) / 2);
      const midDeltaLine = this.f(mid);
      if (midDeltaLine < deltaLine) {
        low = mid + 1;
      } else if (midDeltaLine > deltaLine) {
        high = mid - 1;
      } else {
        let min = mid;
        while (min > low && this.f(min - 1) === deltaLine) {
          min--;
        }
        let max = mid;
        while (max < high && this.f(max + 1) === deltaLine) {
          max++;
        }
        return new $0F(this.c.subarray(4 * min, 4 * max + 4));
      }
    }
    if (this.f(low) === deltaLine) {
      return new $0F(this.c.subarray(4 * low, 4 * low + 4));
    }
    return null;
  }
  clear() {
    this.d = 0;
  }
  removeTokens(startDeltaLine, startChar, endDeltaLine, endChar) {
    const tokens = this.c;
    const tokenCount = this.d;
    let newTokenCount = 0;
    let hasDeletedTokens = false;
    let firstDeltaLine = 0;
    for (let i2 = 0; i2 < tokenCount; i2++) {
      const srcOffset = 4 * i2;
      const tokenDeltaLine = tokens[srcOffset];
      const tokenStartCharacter = tokens[srcOffset + 1];
      const tokenEndCharacter = tokens[srcOffset + 2];
      const tokenMetadata = tokens[srcOffset + 3];
      if ((tokenDeltaLine > startDeltaLine || tokenDeltaLine === startDeltaLine && tokenEndCharacter >= startChar) && (tokenDeltaLine < endDeltaLine || tokenDeltaLine === endDeltaLine && tokenStartCharacter <= endChar)) {
        hasDeletedTokens = true;
      } else {
        if (newTokenCount === 0) {
          firstDeltaLine = tokenDeltaLine;
        }
        if (hasDeletedTokens) {
          const destOffset = 4 * newTokenCount;
          tokens[destOffset] = tokenDeltaLine - firstDeltaLine;
          tokens[destOffset + 1] = tokenStartCharacter;
          tokens[destOffset + 2] = tokenEndCharacter;
          tokens[destOffset + 3] = tokenMetadata;
        }
        newTokenCount++;
      }
    }
    this.d = newTokenCount;
    return firstDeltaLine;
  }
  split(startDeltaLine, startChar, endDeltaLine, endChar) {
    const tokens = this.c;
    const tokenCount = this.d;
    const aTokens = [];
    const bTokens = [];
    let destTokens = aTokens;
    let destOffset = 0;
    let destFirstDeltaLine = 0;
    for (let i2 = 0; i2 < tokenCount; i2++) {
      const srcOffset = 4 * i2;
      const tokenDeltaLine = tokens[srcOffset];
      const tokenStartCharacter = tokens[srcOffset + 1];
      const tokenEndCharacter = tokens[srcOffset + 2];
      const tokenMetadata = tokens[srcOffset + 3];
      if (tokenDeltaLine > startDeltaLine || tokenDeltaLine === startDeltaLine && tokenEndCharacter >= startChar) {
        if (tokenDeltaLine < endDeltaLine || tokenDeltaLine === endDeltaLine && tokenStartCharacter <= endChar) {
          continue;
        } else {
          if (destTokens !== bTokens) {
            destTokens = bTokens;
            destOffset = 0;
            destFirstDeltaLine = tokenDeltaLine;
          }
        }
      }
      destTokens[destOffset++] = tokenDeltaLine - destFirstDeltaLine;
      destTokens[destOffset++] = tokenStartCharacter;
      destTokens[destOffset++] = tokenEndCharacter;
      destTokens[destOffset++] = tokenMetadata;
    }
    return [new _SparseMultilineTokensStorage(new Uint32Array(aTokens)), new _SparseMultilineTokensStorage(new Uint32Array(bTokens)), destFirstDeltaLine];
  }
  acceptDeleteRange(horizontalShiftForFirstLineTokens, startDeltaLine, startCharacter, endDeltaLine, endCharacter) {
    const tokens = this.c;
    const tokenCount = this.d;
    const deletedLineCount = endDeltaLine - startDeltaLine;
    let newTokenCount = 0;
    let hasDeletedTokens = false;
    for (let i2 = 0; i2 < tokenCount; i2++) {
      const srcOffset = 4 * i2;
      let tokenDeltaLine = tokens[srcOffset];
      let tokenStartCharacter = tokens[srcOffset + 1];
      let tokenEndCharacter = tokens[srcOffset + 2];
      const tokenMetadata = tokens[srcOffset + 3];
      if (tokenDeltaLine < startDeltaLine || tokenDeltaLine === startDeltaLine && tokenEndCharacter <= startCharacter) {
        newTokenCount++;
        continue;
      } else if (tokenDeltaLine === startDeltaLine && tokenStartCharacter < startCharacter) {
        if (tokenDeltaLine === endDeltaLine && tokenEndCharacter > endCharacter) {
          tokenEndCharacter -= endCharacter - startCharacter;
        } else {
          tokenEndCharacter = startCharacter;
        }
      } else if (tokenDeltaLine === startDeltaLine && tokenStartCharacter === startCharacter) {
        if (tokenDeltaLine === endDeltaLine && tokenEndCharacter > endCharacter) {
          tokenEndCharacter -= endCharacter - startCharacter;
        } else {
          hasDeletedTokens = true;
          continue;
        }
      } else if (tokenDeltaLine < endDeltaLine || tokenDeltaLine === endDeltaLine && tokenStartCharacter < endCharacter) {
        if (tokenDeltaLine === endDeltaLine && tokenEndCharacter > endCharacter) {
          tokenDeltaLine = startDeltaLine;
          tokenStartCharacter = startCharacter;
          tokenEndCharacter = tokenStartCharacter + (tokenEndCharacter - endCharacter);
        } else {
          hasDeletedTokens = true;
          continue;
        }
      } else if (tokenDeltaLine > endDeltaLine) {
        if (deletedLineCount === 0 && !hasDeletedTokens) {
          newTokenCount = tokenCount;
          break;
        }
        tokenDeltaLine -= deletedLineCount;
      } else if (tokenDeltaLine === endDeltaLine && tokenStartCharacter >= endCharacter) {
        if (horizontalShiftForFirstLineTokens && tokenDeltaLine === 0) {
          tokenStartCharacter += horizontalShiftForFirstLineTokens;
          tokenEndCharacter += horizontalShiftForFirstLineTokens;
        }
        tokenDeltaLine -= deletedLineCount;
        tokenStartCharacter -= endCharacter - startCharacter;
        tokenEndCharacter -= endCharacter - startCharacter;
      } else {
        throw new Error(`Not possible!`);
      }
      const destOffset = 4 * newTokenCount;
      tokens[destOffset] = tokenDeltaLine;
      tokens[destOffset + 1] = tokenStartCharacter;
      tokens[destOffset + 2] = tokenEndCharacter;
      tokens[destOffset + 3] = tokenMetadata;
      newTokenCount++;
    }
    this.d = newTokenCount;
  }
  acceptInsertText(deltaLine, character, eolCount, firstLineLength, lastLineLength, firstCharCode) {
    const isInsertingPreciselyOneWordCharacter = eolCount === 0 && firstLineLength === 1 && (firstCharCode >= 48 && firstCharCode <= 57 || firstCharCode >= 65 && firstCharCode <= 90 || firstCharCode >= 97 && firstCharCode <= 122);
    const tokens = this.c;
    const tokenCount = this.d;
    for (let i2 = 0; i2 < tokenCount; i2++) {
      const offset = 4 * i2;
      let tokenDeltaLine = tokens[offset];
      let tokenStartCharacter = tokens[offset + 1];
      let tokenEndCharacter = tokens[offset + 2];
      if (tokenDeltaLine < deltaLine || tokenDeltaLine === deltaLine && tokenEndCharacter < character) {
        continue;
      } else if (tokenDeltaLine === deltaLine && tokenEndCharacter === character) {
        if (isInsertingPreciselyOneWordCharacter) {
          tokenEndCharacter += 1;
        } else {
          continue;
        }
      } else if (tokenDeltaLine === deltaLine && tokenStartCharacter < character && character < tokenEndCharacter) {
        if (eolCount === 0) {
          tokenEndCharacter += firstLineLength;
        } else {
          tokenEndCharacter = character;
        }
      } else {
        if (tokenDeltaLine === deltaLine && tokenStartCharacter === character) {
          if (isInsertingPreciselyOneWordCharacter) {
            continue;
          }
        }
        if (tokenDeltaLine === deltaLine) {
          tokenDeltaLine += eolCount;
          if (eolCount === 0) {
            tokenStartCharacter += firstLineLength;
            tokenEndCharacter += firstLineLength;
          } else {
            const tokenLength = tokenEndCharacter - tokenStartCharacter;
            tokenStartCharacter = lastLineLength + (tokenStartCharacter - character);
            tokenEndCharacter = tokenStartCharacter + tokenLength;
          }
        } else {
          tokenDeltaLine += eolCount;
        }
      }
      tokens[offset] = tokenDeltaLine;
      tokens[offset + 1] = tokenStartCharacter;
      tokens[offset + 2] = tokenEndCharacter;
    }
  }
};
var $0F = class {
  constructor(tokens) {
    this.c = tokens;
  }
  getCount() {
    return this.c.length / 4;
  }
  getStartCharacter(tokenIndex) {
    return this.c[4 * tokenIndex + 1];
  }
  getEndCharacter(tokenIndex) {
    return this.c[4 * tokenIndex + 2];
  }
  getMetadata(tokenIndex) {
    return this.c[4 * tokenIndex + 3];
  }
};

// out-build/vs/editor/common/services/semanticTokensProviderStyling.js
var SemanticTokensProviderStylingConstants;
(function(SemanticTokensProviderStylingConstants2) {
  SemanticTokensProviderStylingConstants2[SemanticTokensProviderStylingConstants2["NO_STYLING"] = 2147483647] = "NO_STYLING";
})(SemanticTokensProviderStylingConstants || (SemanticTokensProviderStylingConstants = {}));
var ENABLE_TRACE = false;
var $8jb = class $8jb2 {
  constructor(e, f, g, h3) {
    this.e = e;
    this.f = f;
    this.g = g;
    this.h = h3;
    this.b = false;
    this.c = false;
    this.d = false;
    this.a = new HashTable();
  }
  getMetadata(tokenTypeIndex, tokenModifierSet, languageId) {
    const encodedLanguageId = this.g.languageIdCodec.encodeLanguageId(languageId);
    const entry = this.a.get(tokenTypeIndex, tokenModifierSet, encodedLanguageId);
    let metadata;
    if (entry) {
      metadata = entry.metadata;
      if (ENABLE_TRACE && this.h.getLevel() === LogLevel.Trace) {
        this.h.trace(`SemanticTokensProviderStyling [CACHED] ${tokenTypeIndex} / ${tokenModifierSet}: foreground ${$pE.getForeground(metadata)}, fontStyle ${$pE.getFontStyle(metadata).toString(2)}`);
      }
    } else {
      let tokenType = this.e.tokenTypes[tokenTypeIndex];
      const tokenModifiers = [];
      if (tokenType) {
        let modifierSet = tokenModifierSet;
        for (let modifierIndex = 0; modifierSet > 0 && modifierIndex < this.e.tokenModifiers.length; modifierIndex++) {
          if (modifierSet & 1) {
            tokenModifiers.push(this.e.tokenModifiers[modifierIndex]);
          }
          modifierSet = modifierSet >> 1;
        }
        if (ENABLE_TRACE && modifierSet > 0 && this.h.getLevel() === LogLevel.Trace) {
          this.h.trace(`SemanticTokensProviderStyling: unknown token modifier index: ${tokenModifierSet.toString(2)} for legend: ${JSON.stringify(this.e.tokenModifiers)}`);
          tokenModifiers.push("not-in-legend");
        }
        const tokenStyle = this.f.getColorTheme().getTokenStyleMetadata(tokenType, tokenModifiers, languageId);
        if (typeof tokenStyle === "undefined") {
          metadata = 2147483647;
        } else {
          metadata = 0;
          if (typeof tokenStyle.italic !== "undefined") {
            const italicBit = (tokenStyle.italic ? 1 : 0) << 11;
            metadata |= italicBit | 1;
          }
          if (typeof tokenStyle.bold !== "undefined") {
            const boldBit = (tokenStyle.bold ? 2 : 0) << 11;
            metadata |= boldBit | 2;
          }
          if (typeof tokenStyle.underline !== "undefined") {
            const underlineBit = (tokenStyle.underline ? 4 : 0) << 11;
            metadata |= underlineBit | 4;
          }
          if (typeof tokenStyle.strikethrough !== "undefined") {
            const strikethroughBit = (tokenStyle.strikethrough ? 8 : 0) << 11;
            metadata |= strikethroughBit | 8;
          }
          if (tokenStyle.foreground) {
            const foregroundBits = tokenStyle.foreground << 15;
            metadata |= foregroundBits | 16;
          }
          if (metadata === 0) {
            metadata = 2147483647;
          }
        }
      } else {
        if (ENABLE_TRACE && this.h.getLevel() === LogLevel.Trace) {
          this.h.trace(`SemanticTokensProviderStyling: unknown token type index: ${tokenTypeIndex} for legend: ${JSON.stringify(this.e.tokenTypes)}`);
        }
        metadata = 2147483647;
        tokenType = "not-in-legend";
      }
      this.a.add(tokenTypeIndex, tokenModifierSet, encodedLanguageId, metadata);
      if (ENABLE_TRACE && this.h.getLevel() === LogLevel.Trace) {
        this.h.trace(`SemanticTokensProviderStyling ${tokenTypeIndex} (${tokenType}) / ${tokenModifierSet} (${tokenModifiers.join(" ")}): foreground ${$pE.getForeground(metadata)}, fontStyle ${$pE.getFontStyle(metadata).toString(2)}`);
      }
    }
    return metadata;
  }
  warnOverlappingSemanticTokens(lineNumber, startColumn) {
    if (!this.b) {
      this.b = true;
      this.h.warn(`Overlapping semantic tokens detected at lineNumber ${lineNumber}, column ${startColumn}`);
    }
  }
  warnInvalidLengthSemanticTokens(lineNumber, startColumn) {
    if (!this.c) {
      this.c = true;
      this.h.warn(`Semantic token with invalid length detected at lineNumber ${lineNumber}, column ${startColumn}`);
    }
  }
  warnInvalidEditStart(previousResultId, resultId, editIndex, editStart, maxExpectedStart) {
    if (!this.d) {
      this.d = true;
      this.h.warn(`Invalid semantic tokens edit detected (previousResultId: ${previousResultId}, resultId: ${resultId}) at edit #${editIndex}: The provided start offset ${editStart} is outside the previous data (length ${maxExpectedStart}).`);
    }
  }
};
$8jb = __decorate([
  __param(1, $gs),
  __param(2, $1E),
  __param(3, $wn)
], $8jb);
var SemanticColoringConstants;
(function(SemanticColoringConstants2) {
  SemanticColoringConstants2[SemanticColoringConstants2["DesiredTokensPerArea"] = 400] = "DesiredTokensPerArea";
  SemanticColoringConstants2[SemanticColoringConstants2["DesiredMaxAreas"] = 1024] = "DesiredMaxAreas";
})(SemanticColoringConstants || (SemanticColoringConstants = {}));
function $9jb(tokens, styling, languageId) {
  const srcData = tokens.data;
  const tokenCount = tokens.data.length / 5 | 0;
  const tokensPerArea = Math.max(
    Math.ceil(
      tokenCount / 1024
      /* SemanticColoringConstants.DesiredMaxAreas */
    ),
    400
    /* SemanticColoringConstants.DesiredTokensPerArea */
  );
  const result = [];
  let tokenIndex = 0;
  let lastLineNumber = 1;
  let lastStartCharacter = 0;
  while (tokenIndex < tokenCount) {
    const tokenStartIndex = tokenIndex;
    let tokenEndIndex = Math.min(tokenStartIndex + tokensPerArea, tokenCount);
    if (tokenEndIndex < tokenCount) {
      let smallTokenEndIndex = tokenEndIndex;
      while (smallTokenEndIndex - 1 > tokenStartIndex && srcData[5 * smallTokenEndIndex] === 0) {
        smallTokenEndIndex--;
      }
      if (smallTokenEndIndex - 1 === tokenStartIndex) {
        let bigTokenEndIndex = tokenEndIndex;
        while (bigTokenEndIndex + 1 < tokenCount && srcData[5 * bigTokenEndIndex] === 0) {
          bigTokenEndIndex++;
        }
        tokenEndIndex = bigTokenEndIndex;
      } else {
        tokenEndIndex = smallTokenEndIndex;
      }
    }
    let destData = new Uint32Array((tokenEndIndex - tokenStartIndex) * 4);
    let destOffset = 0;
    let areaLine = 0;
    let prevLineNumber = 0;
    let prevEndCharacter = 0;
    while (tokenIndex < tokenEndIndex) {
      const srcOffset = 5 * tokenIndex;
      const deltaLine = srcData[srcOffset];
      const deltaCharacter = srcData[srcOffset + 1];
      const lineNumber = lastLineNumber + deltaLine | 0;
      const startCharacter = deltaLine === 0 ? lastStartCharacter + deltaCharacter | 0 : deltaCharacter;
      const length = srcData[srcOffset + 2];
      const endCharacter = startCharacter + length | 0;
      const tokenTypeIndex = srcData[srcOffset + 3];
      const tokenModifierSet = srcData[srcOffset + 4];
      if (endCharacter <= startCharacter) {
        styling.warnInvalidLengthSemanticTokens(lineNumber, startCharacter + 1);
      } else if (prevLineNumber === lineNumber && prevEndCharacter > startCharacter) {
        styling.warnOverlappingSemanticTokens(lineNumber, startCharacter + 1);
      } else {
        const metadata = styling.getMetadata(tokenTypeIndex, tokenModifierSet, languageId);
        if (metadata !== 2147483647) {
          if (areaLine === 0) {
            areaLine = lineNumber;
          }
          destData[destOffset] = lineNumber - areaLine;
          destData[destOffset + 1] = startCharacter;
          destData[destOffset + 2] = endCharacter;
          destData[destOffset + 3] = metadata;
          destOffset += 4;
          prevLineNumber = lineNumber;
          prevEndCharacter = endCharacter;
        }
      }
      lastLineNumber = lineNumber;
      lastStartCharacter = startCharacter;
      tokenIndex++;
    }
    if (destOffset !== destData.length) {
      destData = destData.subarray(0, destOffset);
    }
    const tokens2 = $9F.create(areaLine, destData);
    result.push(tokens2);
  }
  return result;
}
var HashTableEntry = class {
  constructor(tokenTypeIndex, tokenModifierSet, languageId, metadata) {
    this.tokenTypeIndex = tokenTypeIndex;
    this.tokenModifierSet = tokenModifierSet;
    this.languageId = languageId;
    this.metadata = metadata;
    this.next = null;
  }
};
var HashTable = class _HashTable {
  static {
    this.a = [3, 7, 13, 31, 61, 127, 251, 509, 1021, 2039, 4093, 8191, 16381, 32749, 65521, 131071, 262139, 524287, 1048573, 2097143];
  }
  constructor() {
    this.b = 0;
    this.c = 0;
    this.d = _HashTable.a[this.c];
    this.e = Math.round(this.c + 1 < _HashTable.a.length ? 2 / 3 * this.d : 0);
    this.f = [];
    _HashTable.g(this.f, this.d);
  }
  static g(entries2, length) {
    for (let i2 = 0; i2 < length; i2++) {
      entries2[i2] = null;
    }
  }
  h(n1, n2) {
    return (n1 << 5) - n1 + n2 | 0;
  }
  j(tokenTypeIndex, tokenModifierSet, languageId) {
    return this.h(this.h(tokenTypeIndex, tokenModifierSet), languageId) % this.d;
  }
  get(tokenTypeIndex, tokenModifierSet, languageId) {
    const hash = this.j(tokenTypeIndex, tokenModifierSet, languageId);
    let p = this.f[hash];
    while (p) {
      if (p.tokenTypeIndex === tokenTypeIndex && p.tokenModifierSet === tokenModifierSet && p.languageId === languageId) {
        return p;
      }
      p = p.next;
    }
    return null;
  }
  add(tokenTypeIndex, tokenModifierSet, languageId, metadata) {
    this.b++;
    if (this.e !== 0 && this.b >= this.e) {
      const oldElements = this.f;
      this.c++;
      this.d = _HashTable.a[this.c];
      this.e = Math.round(this.c + 1 < _HashTable.a.length ? 2 / 3 * this.d : 0);
      this.f = [];
      _HashTable.g(this.f, this.d);
      for (const first of oldElements) {
        let p = first;
        while (p) {
          const oldNext = p.next;
          p.next = null;
          this.k(p);
          p = oldNext;
        }
      }
    }
    this.k(new HashTableEntry(tokenTypeIndex, tokenModifierSet, languageId, metadata));
  }
  k(element) {
    const hash = this.j(element.tokenTypeIndex, element.tokenModifierSet, element.languageId);
    element.next = this.f[hash];
    this.f[hash] = element;
  }
};

// out-build/vs/editor/common/services/semanticTokensStyling.js
var $0jb = $Qk("semanticTokensStylingService");

// out-build/vs/editor/common/services/semanticTokensDto.js
var EncodedSemanticTokensType;
(function(EncodedSemanticTokensType2) {
  EncodedSemanticTokensType2[EncodedSemanticTokensType2["Full"] = 1] = "Full";
  EncodedSemanticTokensType2[EncodedSemanticTokensType2["Delta"] = 2] = "Delta";
})(EncodedSemanticTokensType || (EncodedSemanticTokensType = {}));
function reverseEndianness(arr) {
  for (let i2 = 0, len = arr.length; i2 < len; i2 += 4) {
    const b0 = arr[i2 + 0];
    const b1 = arr[i2 + 1];
    const b2 = arr[i2 + 2];
    const b3 = arr[i2 + 3];
    arr[i2 + 0] = b3;
    arr[i2 + 1] = b2;
    arr[i2 + 2] = b1;
    arr[i2 + 3] = b0;
  }
}
function toLittleEndianBuffer(arr) {
  const uint8Arr = new Uint8Array(arr.buffer, arr.byteOffset, arr.length * 4);
  if (!$G()) {
    reverseEndianness(uint8Arr);
  }
  return $Ci.wrap(uint8Arr);
}
function fromLittleEndianBuffer(buff) {
  const uint8Arr = buff.buffer;
  if (!$G()) {
    reverseEndianness(uint8Arr);
  }
  if (uint8Arr.byteOffset % 4 === 0) {
    return new Uint32Array(uint8Arr.buffer, uint8Arr.byteOffset, uint8Arr.length / 4);
  } else {
    const data = new Uint8Array(uint8Arr.byteLength);
    data.set(uint8Arr);
    return new Uint32Array(data.buffer, data.byteOffset, data.length / 4);
  }
}
function $$jb(semanticTokens) {
  const dest = new Uint32Array(encodeSemanticTokensDtoSize(semanticTokens));
  let offset = 0;
  dest[offset++] = semanticTokens.id;
  if (semanticTokens.type === "full") {
    dest[offset++] = 1;
    dest[offset++] = semanticTokens.data.length;
    dest.set(semanticTokens.data, offset);
    offset += semanticTokens.data.length;
  } else {
    dest[offset++] = 2;
    dest[offset++] = semanticTokens.deltas.length;
    for (const delta of semanticTokens.deltas) {
      dest[offset++] = delta.start;
      dest[offset++] = delta.deleteCount;
      if (delta.data) {
        dest[offset++] = delta.data.length;
        dest.set(delta.data, offset);
        offset += delta.data.length;
      } else {
        dest[offset++] = 0;
      }
    }
  }
  return toLittleEndianBuffer(dest);
}
function encodeSemanticTokensDtoSize(semanticTokens) {
  let result = 0;
  result += 1 + 1;
  if (semanticTokens.type === "full") {
    result += 1 + semanticTokens.data.length;
  } else {
    result += 1;
    result += (1 + 1 + 1) * semanticTokens.deltas.length;
    for (const delta of semanticTokens.deltas) {
      if (delta.data) {
        result += delta.data.length;
      }
    }
  }
  return result;
}
function $_jb(_buff) {
  const src = fromLittleEndianBuffer(_buff);
  let offset = 0;
  const id2 = src[offset++];
  const type = src[offset++];
  if (type === 1) {
    const length = src[offset++];
    const data = src.subarray(offset, offset + length);
    offset += length;
    return {
      id: id2,
      type: "full",
      data
    };
  }
  const deltaCount = src[offset++];
  const deltas = [];
  for (let i2 = 0; i2 < deltaCount; i2++) {
    const start = src[offset++];
    const deleteCount = src[offset++];
    const length = src[offset++];
    let data;
    if (length > 0) {
      data = src.subarray(offset, offset + length);
      offset += length;
    }
    deltas[i2] = { start, deleteCount, data };
  }
  return {
    id: id2,
    type: "delta",
    deltas
  };
}

// out-build/vs/editor/contrib/semanticTokens/common/getSemanticTokens.js
function $akb(v) {
  return v && !!v.data;
}
function $bkb(v) {
  return v && Array.isArray(v.edits);
}
var $ckb = class {
  constructor(provider, tokens, error) {
    this.provider = provider;
    this.tokens = tokens;
    this.error = error;
  }
};
function $dkb(registry4, model) {
  return registry4.has(model);
}
function getDocumentSemanticTokensProviders(registry4, model) {
  const groups = registry4.orderedGroups(model);
  return groups.length > 0 ? groups[0] : [];
}
async function $ekb(registry4, model, lastProvider, lastResultId, token) {
  const providers2 = getDocumentSemanticTokensProviders(registry4, model);
  const results = await Promise.all(providers2.map(async (provider) => {
    let result;
    let error = null;
    try {
      result = await provider.provideDocumentSemanticTokens(model, provider === lastProvider ? lastResultId : null, token);
    } catch (err) {
      error = err;
      result = null;
    }
    if (!result || !$akb(result) && !$bkb(result)) {
      result = null;
    }
    return new $ckb(provider, result, error);
  }));
  for (const result of results) {
    if (result.error) {
      throw result.error;
    }
    if (result.tokens) {
      return result;
    }
  }
  if (results.length > 0) {
    return results[0];
  }
  return null;
}
function _getDocumentSemanticTokensProviderHighestGroup(registry4, model) {
  const result = registry4.orderedGroups(model);
  return result.length > 0 ? result[0] : null;
}
var DocumentRangeSemanticTokensResult = class {
  constructor(provider, tokens) {
    this.provider = provider;
    this.tokens = tokens;
  }
};
function $fkb(providers2, model) {
  return providers2.has(model);
}
function getDocumentRangeSemanticTokensProviders(providers2, model) {
  const groups = providers2.orderedGroups(model);
  return groups.length > 0 ? groups[0] : [];
}
async function $gkb(registry4, model, range, token) {
  const providers2 = getDocumentRangeSemanticTokensProviders(registry4, model);
  const results = await Promise.all(providers2.map(async (provider) => {
    let result;
    try {
      result = await provider.provideDocumentRangeSemanticTokens(model, range, token);
    } catch (err) {
      $hb(err);
      result = null;
    }
    if (!result || !$akb(result)) {
      result = null;
    }
    return new DocumentRangeSemanticTokensResult(provider, result);
  }));
  for (const result of results) {
    if (result.tokens) {
      return result;
    }
  }
  if (results.length > 0) {
    return results[0];
  }
  return null;
}
$tn.registerCommand("_provideDocumentSemanticTokensLegend", async (accessor, ...args2) => {
  const [uri] = args2;
  $Jg(uri instanceof URI);
  const model = accessor.get($sG).getModel(uri);
  if (!model) {
    return void 0;
  }
  const { documentSemanticTokensProvider } = accessor.get($mP);
  const providers2 = _getDocumentSemanticTokensProviderHighestGroup(documentSemanticTokensProvider, model);
  if (!providers2) {
    return accessor.get($sn).executeCommand("_provideDocumentRangeSemanticTokensLegend", uri);
  }
  return providers2[0].getLegend();
});
$tn.registerCommand("_provideDocumentSemanticTokens", async (accessor, ...args2) => {
  const [uri] = args2;
  $Jg(uri instanceof URI);
  const model = accessor.get($sG).getModel(uri);
  if (!model) {
    return void 0;
  }
  const { documentSemanticTokensProvider } = accessor.get($mP);
  if (!$dkb(documentSemanticTokensProvider, model)) {
    return accessor.get($sn).executeCommand("_provideDocumentRangeSemanticTokens", uri, model.getFullModelRange());
  }
  const r2 = await $ekb(documentSemanticTokensProvider, model, null, null, CancellationToken.None);
  if (!r2) {
    return void 0;
  }
  const { provider, tokens } = r2;
  if (!tokens || !$akb(tokens)) {
    return void 0;
  }
  const buff = $$jb({
    id: 0,
    type: "full",
    data: tokens.data
  });
  if (tokens.resultId) {
    provider.releaseDocumentSemanticTokens(tokens.resultId);
  }
  return buff;
});
$tn.registerCommand("_provideDocumentRangeSemanticTokensLegend", async (accessor, ...args2) => {
  const [uri, range] = args2;
  $Jg(uri instanceof URI);
  const model = accessor.get($sG).getModel(uri);
  if (!model) {
    return void 0;
  }
  const { documentRangeSemanticTokensProvider } = accessor.get($mP);
  const providers2 = getDocumentRangeSemanticTokensProviders(documentRangeSemanticTokensProvider, model);
  if (providers2.length === 0) {
    return void 0;
  }
  if (providers2.length === 1) {
    return providers2[0].getLegend();
  }
  if (!range || !$9C.isIRange(range)) {
    console.warn(`provideDocumentRangeSemanticTokensLegend might be out-of-sync with provideDocumentRangeSemanticTokens unless a range argument is passed in`);
    return providers2[0].getLegend();
  }
  const result = await $gkb(documentRangeSemanticTokensProvider, model, $9C.lift(range), CancellationToken.None);
  if (!result) {
    return void 0;
  }
  return result.provider.getLegend();
});
$tn.registerCommand("_provideDocumentRangeSemanticTokens", async (accessor, ...args2) => {
  const [uri, range] = args2;
  $Jg(uri instanceof URI);
  $Jg($9C.isIRange(range));
  const model = accessor.get($sG).getModel(uri);
  if (!model) {
    return void 0;
  }
  const { documentRangeSemanticTokensProvider } = accessor.get($mP);
  const result = await $gkb(documentRangeSemanticTokensProvider, model, $9C.lift(range), CancellationToken.None);
  if (!result || !result.tokens) {
    return void 0;
  }
  return $$jb({
    id: 0,
    type: "full",
    data: result.tokens.data
  });
});

// out-build/vs/editor/contrib/semanticTokens/common/semanticTokensConfig.js
var $hkb = "editor.semanticHighlighting";
function $ikb(model, themeService, configurationService) {
  const setting = configurationService.getValue($hkb, { overrideIdentifier: model.getLanguageId(), resource: model.uri })?.enabled;
  if (typeof setting === "boolean") {
    return setting;
  }
  return themeService.getColorTheme().semanticHighlighting;
}

// out-build/vs/editor/contrib/semanticTokens/browser/documentSemanticTokens.js
var ModelSemanticColoring_1;
var $jkb = class $jkb2 extends $3c {
  constructor(semanticTokensStylingService, modelService, themeService, configurationService, languageFeatureDebounceService, languageFeaturesService) {
    super();
    this.a = new $Ec();
    const register2 = (model) => {
      this.a.get(model.uri)?.dispose();
      this.a.set(model.uri, new ModelSemanticColoring(model, semanticTokensStylingService, themeService, languageFeatureDebounceService, languageFeaturesService));
    };
    const deregister = (model, modelSemanticColoring) => {
      modelSemanticColoring.dispose();
      this.a.delete(model.uri);
    };
    const handleSettingOrThemeChange = () => {
      for (const model of modelService.getModels()) {
        const curr = this.a.get(model.uri);
        if ($ikb(model, themeService, configurationService)) {
          if (!curr) {
            register2(model);
          }
        } else {
          if (curr) {
            deregister(model, curr);
          }
        }
      }
    };
    modelService.getModels().forEach((model) => {
      if ($ikb(model, themeService, configurationService)) {
        register2(model);
      }
    });
    this.B(modelService.onModelAdded((model) => {
      if ($ikb(model, themeService, configurationService)) {
        register2(model);
      }
    }));
    this.B(modelService.onModelRemoved((model) => {
      const curr = this.a.get(model.uri);
      if (curr) {
        deregister(model, curr);
      }
    }));
    this.B(configurationService.onDidChangeConfiguration((e) => {
      if (e.affectsConfiguration($hkb)) {
        handleSettingOrThemeChange();
      }
    }));
    this.B(themeService.onDidColorThemeChange(handleSettingOrThemeChange));
  }
  dispose() {
    $Xc(this.a.values());
    this.a.clear();
    super.dispose();
  }
};
$jkb = __decorate([
  __param(0, $0jb),
  __param(1, $sG),
  __param(2, $gs),
  __param(3, $kl),
  __param(4, $tbb),
  __param(5, $mP)
], $jkb);
var ModelSemanticColoring = class ModelSemanticColoring2 extends $3c {
  static {
    ModelSemanticColoring_1 = this;
  }
  static {
    this.REQUEST_MIN_DELAY = 300;
  }
  static {
    this.REQUEST_MAX_DELAY = 2e3;
  }
  constructor(model, r2, themeService, languageFeatureDebounceService, languageFeaturesService) {
    super();
    this.r = r2;
    this.a = false;
    this.b = model;
    this.c = languageFeaturesService.documentSemanticTokensProvider;
    this.f = languageFeatureDebounceService.for(this.c, "DocumentSemanticTokens", { min: ModelSemanticColoring_1.REQUEST_MIN_DELAY, max: ModelSemanticColoring_1.REQUEST_MAX_DELAY });
    this.g = this.B(new $8h(() => this.s(), ModelSemanticColoring_1.REQUEST_MIN_DELAY));
    this.h = null;
    this.j = null;
    this.m = [];
    this.n = false;
    this.B(this.b.onDidChangeContent(() => {
      if (!this.g.isScheduled()) {
        this.g.schedule(this.f.get(this.b));
      }
    }));
    this.B(this.b.onDidChangeAttached(() => {
      if (!this.g.isScheduled()) {
        this.g.schedule(this.f.get(this.b));
      }
    }));
    this.B(this.b.onDidChangeLanguage(() => {
      if (this.h) {
        this.h.dispose();
        this.h = null;
      }
      if (this.j) {
        this.j.cancel();
        this.j = null;
      }
      this.u(null, null, null, []);
      this.g.schedule(0);
    }));
    const bindDocumentChangeListeners = () => {
      $Xc(this.m);
      this.m = [];
      for (const provider of this.c.all(model)) {
        if (typeof provider.onDidChange === "function") {
          this.m.push(provider.onDidChange(() => {
            if (this.j) {
              this.n = true;
              return;
            }
            this.g.schedule(0);
          }));
        }
      }
    };
    bindDocumentChangeListeners();
    this.B(this.c.onDidChange(() => {
      bindDocumentChangeListeners();
      this.g.schedule(this.f.get(this.b));
    }));
    this.B(themeService.onDidColorThemeChange((_) => {
      this.u(null, null, null, []);
      this.g.schedule(this.f.get(this.b));
    }));
    this.g.schedule(0);
  }
  dispose() {
    if (this.h) {
      this.h.dispose();
      this.h = null;
    }
    if (this.j) {
      this.j.cancel();
      this.j = null;
    }
    $Xc(this.m);
    this.m = [];
    this.u(null, null, null, []);
    this.a = true;
    super.dispose();
  }
  s() {
    if (this.j) {
      return;
    }
    if (!$dkb(this.c, this.b)) {
      if (this.h) {
        this.b.tokenization.setSemanticTokens(null, false);
      }
      return;
    }
    if (!this.b.isAttachedToEditor()) {
      return;
    }
    const cancellationTokenSource = new $ad();
    const lastProvider = this.h ? this.h.provider : null;
    const lastResultId = this.h ? this.h.resultId || null : null;
    const request = $ekb(this.c, this.b, lastProvider, lastResultId, cancellationTokenSource.token);
    this.j = cancellationTokenSource;
    this.n = false;
    const pendingChanges = [];
    const contentChangeListener = this.b.onDidChangeContent((e) => {
      pendingChanges.push(e);
    });
    const sw = new $te(false);
    request.then((res) => {
      this.f.update(this.b, sw.elapsed());
      this.j = null;
      contentChangeListener.dispose();
      if (!res) {
        this.u(null, null, null, pendingChanges);
      } else {
        const { provider, tokens } = res;
        const styling = this.r.getStyling(provider);
        this.u(provider, tokens || null, styling, pendingChanges);
      }
    }, (err) => {
      const isExpectedError = err && ($kb(err) || typeof err.message === "string" && err.message.indexOf("busy") !== -1);
      if (!isExpectedError) {
        $gb(err);
      }
      this.j = null;
      contentChangeListener.dispose();
      if (pendingChanges.length > 0 || this.n) {
        if (!this.g.isScheduled()) {
          this.g.schedule(this.f.get(this.b));
        }
      }
    });
  }
  static t(src, srcOffset, dest, destOffset, length) {
    length = Math.min(length, dest.length - destOffset, src.length - srcOffset);
    for (let i2 = 0; i2 < length; i2++) {
      dest[destOffset + i2] = src[srcOffset + i2];
    }
  }
  u(provider, tokens, styling, pendingChanges) {
    const currentResponse = this.h;
    const rescheduleIfNeeded = () => {
      if ((pendingChanges.length > 0 || this.n) && !this.g.isScheduled()) {
        this.g.schedule(this.f.get(this.b));
      }
    };
    if (this.h) {
      this.h.dispose();
      this.h = null;
    }
    if (this.a) {
      if (provider && tokens) {
        provider.releaseDocumentSemanticTokens(tokens.resultId);
      }
      return;
    }
    if (!provider || !styling) {
      this.b.tokenization.setSemanticTokens(null, false);
      return;
    }
    if (!tokens) {
      this.b.tokenization.setSemanticTokens(null, true);
      rescheduleIfNeeded();
      return;
    }
    if ($bkb(tokens)) {
      if (!currentResponse) {
        this.b.tokenization.setSemanticTokens(null, true);
        return;
      }
      if (tokens.edits.length === 0) {
        tokens = {
          resultId: tokens.resultId,
          data: currentResponse.data
        };
      } else {
        let deltaLength = 0;
        for (const edit3 of tokens.edits) {
          deltaLength += (edit3.data ? edit3.data.length : 0) - edit3.deleteCount;
        }
        const srcData = currentResponse.data;
        const destData = new Uint32Array(srcData.length + deltaLength);
        let srcLastStart = srcData.length;
        let destLastStart = destData.length;
        for (let i2 = tokens.edits.length - 1; i2 >= 0; i2--) {
          const edit3 = tokens.edits[i2];
          if (edit3.start > srcData.length) {
            styling.warnInvalidEditStart(currentResponse.resultId, tokens.resultId, i2, edit3.start, srcData.length);
            this.b.tokenization.setSemanticTokens(null, true);
            return;
          }
          const copyCount = srcLastStart - (edit3.start + edit3.deleteCount);
          if (copyCount > 0) {
            ModelSemanticColoring_1.t(srcData, srcLastStart - copyCount, destData, destLastStart - copyCount, copyCount);
            destLastStart -= copyCount;
          }
          if (edit3.data) {
            ModelSemanticColoring_1.t(edit3.data, 0, destData, destLastStart - edit3.data.length, edit3.data.length);
            destLastStart -= edit3.data.length;
          }
          srcLastStart = edit3.start;
        }
        if (srcLastStart > 0) {
          ModelSemanticColoring_1.t(srcData, 0, destData, 0, srcLastStart);
        }
        tokens = {
          resultId: tokens.resultId,
          data: destData
        };
      }
    }
    if ($akb(tokens)) {
      this.h = new SemanticTokensResponse(provider, tokens.resultId, tokens.data);
      const result = $9jb(tokens, styling, this.b.getLanguageId());
      if (pendingChanges.length > 0) {
        for (const change of pendingChanges) {
          for (const area of result) {
            for (const singleChange of change.changes) {
              area.applyEdit(singleChange.range, singleChange.text);
            }
          }
        }
      }
      this.b.tokenization.setSemanticTokens(result, true);
    } else {
      this.b.tokenization.setSemanticTokens(null, true);
    }
    rescheduleIfNeeded();
  }
};
ModelSemanticColoring = ModelSemanticColoring_1 = __decorate([
  __param(1, $0jb),
  __param(2, $gs),
  __param(3, $tbb),
  __param(4, $mP)
], ModelSemanticColoring);
var SemanticTokensResponse = class {
  constructor(provider, resultId, data) {
    this.provider = provider;
    this.resultId = resultId;
    this.data = data;
  }
  dispose() {
    this.provider.releaseDocumentSemanticTokens(this.resultId);
  }
};
$T_($jkb);

// out-build/vs/editor/contrib/semanticTokens/browser/viewportSemanticTokens.js
var $kkb_1;
var $kkb = class $kkb2 extends $3c {
  static {
    $kkb_1 = this;
  }
  static {
    this.ID = "editor.contrib.viewportSemanticTokens";
  }
  static get(editor) {
    return editor.getContribution($kkb_1.ID);
  }
  constructor(editor, h3, j, m, languageFeatureDebounceService, languageFeaturesService) {
    super();
    this.h = h3;
    this.j = j;
    this.m = m;
    this.a = editor;
    this.b = languageFeaturesService.documentRangeSemanticTokensProvider;
    this.c = languageFeatureDebounceService.for(this.b, "DocumentRangeSemanticTokens", { min: 100, max: 500 });
    this.f = this.B(new $8h(() => this.t(), 100));
    this.g = [];
    const scheduleTokenizeViewport = () => {
      if (this.a.hasModel()) {
        this.f.schedule(this.c.get(this.a.getModel()));
      }
    };
    this.B(this.a.onDidScrollChange(() => {
      scheduleTokenizeViewport();
    }));
    this.B(this.a.onDidChangeModel(() => {
      this.n();
      scheduleTokenizeViewport();
    }));
    this.B(this.a.onDidChangeModelContent((e) => {
      this.n();
      scheduleTokenizeViewport();
    }));
    this.B(this.b.onDidChange(() => {
      this.n();
      scheduleTokenizeViewport();
    }));
    this.B(this.m.onDidChangeConfiguration((e) => {
      if (e.affectsConfiguration($hkb)) {
        this.n();
        scheduleTokenizeViewport();
      }
    }));
    this.B(this.j.onDidColorThemeChange(() => {
      this.n();
      scheduleTokenizeViewport();
    }));
    scheduleTokenizeViewport();
  }
  n() {
    for (const request of this.g) {
      request.cancel();
    }
    this.g = [];
  }
  s(req) {
    for (let i2 = 0, len = this.g.length; i2 < len; i2++) {
      if (this.g[i2] === req) {
        this.g.splice(i2, 1);
        return;
      }
    }
  }
  t() {
    if (!this.a.hasModel()) {
      return;
    }
    const model = this.a.getModel();
    if (model.tokenization.hasCompleteSemanticTokens()) {
      return;
    }
    if (!$ikb(model, this.j, this.m)) {
      if (model.tokenization.hasSomeSemanticTokens()) {
        model.tokenization.setSemanticTokens(null, false);
      }
      return;
    }
    if (!$fkb(this.b, model)) {
      if (model.tokenization.hasSomeSemanticTokens()) {
        model.tokenization.setSemanticTokens(null, false);
      }
      return;
    }
    const visibleRanges = this.a.getVisibleRangesPlusViewportAboveBelow();
    this.g = this.g.concat(visibleRanges.map((range) => this.u(model, range)));
  }
  u(model, range) {
    const requestVersionId = model.getVersionId();
    const request = $Hh((token) => Promise.resolve($gkb(this.b, model, range, token)));
    const sw = new $te(false);
    request.then((r2) => {
      this.c.update(model, sw.elapsed());
      if (!r2 || !r2.tokens || model.isDisposed() || model.getVersionId() !== requestVersionId) {
        return;
      }
      const { provider, tokens: result } = r2;
      const styling = this.h.getStyling(provider);
      model.tokenization.setPartialSemanticTokens(range, $9jb(result, styling, model.getLanguageId()));
    }).then(() => this.s(request), () => this.s(request));
    return request;
  }
};
$kkb = $kkb_1 = __decorate([
  __param(1, $0jb),
  __param(2, $gs),
  __param(3, $kl),
  __param(4, $tbb),
  __param(5, $mP)
], $kkb);
$85(
  $kkb.ID,
  $kkb,
  1
  /* EditorContributionInstantiation.AfterFirstRender */
);

// out-build/vs/editor/contrib/smartSelect/browser/wordSelections.js
var $lkb = class {
  constructor(a = true) {
    this.a = a;
  }
  provideSelectionRanges(model, positions) {
    const result = [];
    for (const position of positions) {
      const bucket = [];
      result.push(bucket);
      if (this.a) {
        this.b(bucket, model, position);
      }
      this.c(bucket, model, position);
      this.d(bucket, model, position);
      bucket.push({ range: model.getFullModelRange() });
    }
    return result;
  }
  b(bucket, model, pos) {
    const obj = model.getWordAtPosition(pos);
    if (!obj) {
      return;
    }
    const { word, startColumn } = obj;
    const offset = pos.column - startColumn;
    let start = offset;
    let end = offset;
    let lastCh = 0;
    for (; start >= 0; start--) {
      const ch = word.charCodeAt(start);
      if (start !== offset && (ch === 95 || ch === 45)) {
        break;
      } else if ($Yf(ch) && $Zf(lastCh)) {
        break;
      }
      lastCh = ch;
    }
    start += 1;
    for (; end < word.length; end++) {
      const ch = word.charCodeAt(end);
      if ($Zf(ch) && $Yf(lastCh)) {
        break;
      } else if (ch === 95 || ch === 45) {
        break;
      }
      lastCh = ch;
    }
    if (start < end) {
      bucket.push({ range: new $9C(pos.lineNumber, startColumn + start, pos.lineNumber, startColumn + end) });
    }
  }
  c(bucket, model, pos) {
    const word = model.getWordAtPosition(pos);
    if (word) {
      bucket.push({ range: new $9C(pos.lineNumber, word.startColumn, pos.lineNumber, word.endColumn) });
    }
  }
  d(bucket, model, pos) {
    if (model.getLineLength(pos.lineNumber) > 0 && model.getLineFirstNonWhitespaceColumn(pos.lineNumber) === 0 && model.getLineLastNonWhitespaceColumn(pos.lineNumber) === 0) {
      bucket.push({ range: new $9C(pos.lineNumber, 1, pos.lineNumber, model.getLineMaxColumn(pos.lineNumber)) });
    }
  }
};

// out-build/vs/editor/contrib/smartSelect/browser/smartSelect.js
var $mkb_1;
var SelectionRanges = class _SelectionRanges {
  constructor(index, ranges) {
    this.index = index;
    this.ranges = ranges;
  }
  mov(fwd) {
    const index = this.index + (fwd ? 1 : -1);
    if (index < 0 || index >= this.ranges.length) {
      return this;
    }
    const res = new _SelectionRanges(index, this.ranges);
    if (res.ranges[index].equalsRange(this.ranges[this.index])) {
      return res.mov(fwd);
    }
    return res;
  }
};
var $mkb = class $mkb2 {
  static {
    $mkb_1 = this;
  }
  static {
    this.ID = "editor.contrib.smartSelectController";
  }
  static get(editor) {
    return editor.getContribution($mkb_1.ID);
  }
  constructor(f, g) {
    this.f = f;
    this.g = g;
    this.e = false;
  }
  dispose() {
    this.d?.dispose();
  }
  async run(forward) {
    if (!this.f.hasModel()) {
      return;
    }
    const selections = this.f.getSelections();
    const model = this.f.getModel();
    if (!this.c) {
      await $nkb(this.g.selectionRangeProvider, model, selections.map((s) => s.getPosition()), this.f.getOption(
        118
        /* EditorOption.smartSelect */
      ), CancellationToken.None).then((ranges) => {
        if (!$Qb(ranges) || ranges.length !== selections.length) {
          return;
        }
        if (!this.f.hasModel() || !$zb(this.f.getSelections(), selections, (a, b) => a.equalsSelection(b))) {
          return;
        }
        for (let i2 = 0; i2 < ranges.length; i2++) {
          ranges[i2] = ranges[i2].filter((range) => {
            return range.containsPosition(selections[i2].getStartPosition()) && range.containsPosition(selections[i2].getEndPosition());
          });
          ranges[i2].unshift(selections[i2]);
        }
        this.c = ranges.map((ranges2) => new SelectionRanges(0, ranges2));
        this.d?.dispose();
        this.d = this.f.onDidChangeCursorPosition(() => {
          if (!this.e) {
            this.d?.dispose();
            this.c = void 0;
          }
        });
      });
    }
    if (!this.c) {
      return;
    }
    this.c = this.c.map((state) => state.mov(forward));
    const newSelections = this.c.map((state) => $_D.fromPositions(state.ranges[state.index].getStartPosition(), state.ranges[state.index].getEndPosition()));
    this.e = true;
    try {
      this.f.setSelections(newSelections);
    } finally {
      this.e = false;
    }
  }
};
$mkb = $mkb_1 = __decorate([
  __param(1, $mP)
], $mkb);
var AbstractSmartSelect = class extends $Z5 {
  constructor(forward, opts) {
    super(opts);
    this.d = forward;
  }
  async run(_accessor, editor) {
    const controller = $mkb.get(editor);
    if (controller) {
      await controller.run(this.d);
    }
  }
};
var GrowSelectionAction = class extends AbstractSmartSelect {
  constructor() {
    super(true, {
      id: "editor.action.smartSelect.expand",
      label: localize2(1438, "Expand Selection"),
      precondition: void 0,
      kbOpts: {
        kbExpr: EditorContextKeys.editorTextFocus,
        primary: 1024 | 512 | 17,
        mac: {
          primary: 2048 | 256 | 1024 | 17,
          secondary: [
            256 | 1024 | 17
            /* KeyCode.RightArrow */
          ]
        },
        weight: 100
        /* KeybindingWeight.EditorContrib */
      },
      menuOpts: {
        menuId: $bJ.MenubarSelectionMenu,
        group: "1_basic",
        title: localize(1436, null),
        order: 2
      }
    });
  }
};
$tn.registerCommandAlias("editor.action.smartSelect.grow", "editor.action.smartSelect.expand");
var ShrinkSelectionAction = class extends AbstractSmartSelect {
  constructor() {
    super(false, {
      id: "editor.action.smartSelect.shrink",
      label: localize2(1439, "Shrink Selection"),
      precondition: void 0,
      kbOpts: {
        kbExpr: EditorContextKeys.editorTextFocus,
        primary: 1024 | 512 | 15,
        mac: {
          primary: 2048 | 256 | 1024 | 15,
          secondary: [
            256 | 1024 | 15
            /* KeyCode.LeftArrow */
          ]
        },
        weight: 100
        /* KeybindingWeight.EditorContrib */
      },
      menuOpts: {
        menuId: $bJ.MenubarSelectionMenu,
        group: "1_basic",
        title: localize(1437, null),
        order: 3
      }
    });
  }
};
$85(
  $mkb.ID,
  $mkb,
  4
  /* EditorContributionInstantiation.Lazy */
);
$55(GrowSelectionAction);
$55(ShrinkSelectionAction);
async function $nkb(registry4, model, positions, options3, token) {
  const providers2 = registry4.all(model).concat(new $lkb(options3.selectSubwords));
  if (providers2.length === 1) {
    providers2.unshift(new $kcb());
  }
  const work = [];
  const allRawRanges = [];
  for (const provider of providers2) {
    work.push(Promise.resolve(provider.provideSelectionRanges(model, positions, token)).then((allProviderRanges) => {
      if ($Qb(allProviderRanges) && allProviderRanges.length === positions.length) {
        for (let i2 = 0; i2 < positions.length; i2++) {
          if (!allRawRanges[i2]) {
            allRawRanges[i2] = [];
          }
          for (const oneProviderRanges of allProviderRanges[i2]) {
            if ($9C.isIRange(oneProviderRanges.range) && $9C.containsPosition(oneProviderRanges.range, positions[i2])) {
              allRawRanges[i2].push($9C.lift(oneProviderRanges.range));
            }
          }
        }
      }
    }, $hb));
  }
  await Promise.all(work);
  return allRawRanges.map((oneRawRanges) => {
    if (oneRawRanges.length === 0) {
      return [];
    }
    oneRawRanges.sort((a, b) => {
      if ($8C.isBefore(a.getStartPosition(), b.getStartPosition())) {
        return 1;
      } else if ($8C.isBefore(b.getStartPosition(), a.getStartPosition())) {
        return -1;
      } else if ($8C.isBefore(a.getEndPosition(), b.getEndPosition())) {
        return -1;
      } else if ($8C.isBefore(b.getEndPosition(), a.getEndPosition())) {
        return 1;
      } else {
        return 0;
      }
    });
    const oneRanges = [];
    let last;
    for (const range of oneRawRanges) {
      if (!last || $9C.containsRange(range, last) && !$9C.equalsRange(range, last)) {
        oneRanges.push(range);
        last = range;
      }
    }
    if (!options3.selectLeadingAndTrailingWhitespace) {
      return oneRanges;
    }
    const oneRangesWithTrivia = [oneRanges[0]];
    for (let i2 = 1; i2 < oneRanges.length; i2++) {
      const prev = oneRanges[i2 - 1];
      const cur = oneRanges[i2];
      if (cur.startLineNumber !== prev.startLineNumber || cur.endLineNumber !== prev.endLineNumber) {
        const rangeNoWhitespace = new $9C(prev.startLineNumber, model.getLineFirstNonWhitespaceColumn(prev.startLineNumber), prev.endLineNumber, model.getLineLastNonWhitespaceColumn(prev.endLineNumber));
        if (rangeNoWhitespace.containsRange(prev) && !rangeNoWhitespace.equalsRange(prev) && cur.containsRange(rangeNoWhitespace) && !cur.equalsRange(rangeNoWhitespace)) {
          oneRangesWithTrivia.push(rangeNoWhitespace);
        }
        const rangeFull = new $9C(prev.startLineNumber, 1, prev.endLineNumber, model.getLineMaxColumn(prev.endLineNumber));
        if (rangeFull.containsRange(prev) && !rangeFull.equalsRange(rangeNoWhitespace) && cur.containsRange(rangeFull) && !cur.equalsRange(rangeFull)) {
          oneRangesWithTrivia.push(rangeFull);
        }
      }
      oneRangesWithTrivia.push(cur);
    }
    return oneRangesWithTrivia;
  });
}
$tn.registerCommand("_executeSelectionRangeProvider", async function(accessor, ...args2) {
  const [resource, positions] = args2;
  $Jg(URI.isUri(resource));
  const registry4 = accessor.get($mP).selectionRangeProvider;
  const reference = await accessor.get($oG).createModelReference(resource);
  try {
    return $nkb(registry4, reference.object.textEditorModel, positions, { selectLeadingAndTrailingWhitespace: true, selectSubwords: true }, CancellationToken.None);
  } finally {
    reference.dispose();
  }
});

// out-build/vs/platform/action/common/actionCommonCategories.js
var $qn = Object.freeze({
  View: localize2(1663, "View"),
  Help: localize2(1664, "Help"),
  Test: localize2(1665, "Test"),
  File: localize2(1666, "File"),
  Preferences: localize2(1667, "Preferences"),
  Developer: localize2(1668, "Developer")
});

// out-build/vs/editor/contrib/stickyScroll/browser/stickyScrollWidget.js
var $okb = class _$okb {
  constructor(startLineNumbers, endLineNumbers, lastLineRelativePosition, showEndForLine = null) {
    this.startLineNumbers = startLineNumbers;
    this.endLineNumbers = endLineNumbers;
    this.lastLineRelativePosition = lastLineRelativePosition;
    this.showEndForLine = showEndForLine;
  }
  equals(other) {
    return !!other && this.lastLineRelativePosition === other.lastLineRelativePosition && this.showEndForLine === other.showEndForLine && $zb(this.startLineNumbers, other.startLineNumbers) && $zb(this.endLineNumbers, other.endLineNumbers);
  }
  static get Empty() {
    return new _$okb([], [], 0);
  }
};
var _ttPolicy = $W1("stickyScrollViewLayer", { createHTML: (value) => value });
var STICKY_INDEX_ATTR = "data-sticky-line-index";
var STICKY_IS_LINE_ATTR = "data-sticky-is-line";
var STICKY_IS_LINE_NUMBER_ATTR = "data-sticky-is-line-number";
var STICKY_IS_FOLDING_ICON_ATTR = "data-sticky-is-folding-icon";
var $pkb = class extends $3c {
  constructor(u) {
    super();
    this.u = u;
    this.a = new $2c();
    this.b = document.createElement("div");
    this.c = document.createElement("div");
    this.f = document.createElement("div");
    this.g = document.createElement("div");
    this.j = this.u.getOption(
      68
      /* EditorOption.lineHeight */
    );
    this.m = [];
    this.n = [];
    this.r = 0;
    this.s = 0;
    this.t = false;
    this.c.className = "sticky-widget-line-numbers";
    this.c.setAttribute("role", "none");
    this.g.className = "sticky-widget-lines";
    this.g.setAttribute("role", "list");
    this.f.className = "sticky-widget-lines-scrollable";
    this.f.appendChild(this.g);
    this.b.className = "sticky-widget";
    this.b.classList.toggle("peek", u instanceof $bdb);
    this.b.appendChild(this.c);
    this.b.appendChild(this.f);
    const updateScrollLeftPosition = () => {
      this.g.style.left = this.u.getOption(
        120
        /* EditorOption.stickyScroll */
      ).scrollWithEditor ? `-${this.u.getScrollLeft()}px` : "0px";
    };
    this.B(this.u.onDidChangeConfiguration((e) => {
      if (e.hasChanged(
        120
        /* EditorOption.stickyScroll */
      )) {
        updateScrollLeftPosition();
      }
      if (e.hasChanged(
        68
        /* EditorOption.lineHeight */
      )) {
        this.j = this.u.getOption(
          68
          /* EditorOption.lineHeight */
        );
      }
    }));
    this.B(this.u.onDidScrollChange((e) => {
      if (e.scrollLeftChanged) {
        updateScrollLeftPosition();
      }
      if (e.scrollWidthChanged) {
        this.z();
      }
    }));
    this.B(this.u.onDidChangeModel(() => {
      updateScrollLeftPosition();
      this.z();
    }));
    this.B(this.a);
    updateScrollLeftPosition();
    this.B(this.u.onDidLayoutChange((e) => {
      this.z();
    }));
    this.z();
  }
  get lineNumbers() {
    return this.n;
  }
  get lineNumberCount() {
    return this.n.length;
  }
  getRenderedStickyLine(lineNumber) {
    return this.m.find((stickyLine) => stickyLine.lineNumber === lineNumber);
  }
  getCurrentLines() {
    return this.n;
  }
  setState(_state, foldingModel, _rebuildFromLine) {
    if (_rebuildFromLine === void 0 && (!this.h && !_state || this.h && this.h.equals(_state))) {
      return;
    }
    const isWidgetHeightZero = this.w(_state);
    const state = isWidgetHeightZero ? void 0 : _state;
    const rebuildFromLine = isWidgetHeightZero ? 0 : this.y(_state, _rebuildFromLine);
    this.G(state, foldingModel, rebuildFromLine);
    this.h = _state;
  }
  w(state) {
    if (!state) {
      return true;
    }
    const futureWidgetHeight = state.startLineNumbers.length * this.j + state.lastLineRelativePosition;
    if (futureWidgetHeight > 0) {
      this.r = state.lastLineRelativePosition;
      const lineNumbers = [...state.startLineNumbers];
      if (state.showEndForLine !== null) {
        lineNumbers[state.showEndForLine] = state.endLineNumbers[state.showEndForLine];
      }
      this.n = lineNumbers;
    } else {
      this.r = 0;
      this.n = [];
    }
    return futureWidgetHeight === 0;
  }
  y(state, _rebuildFromLine) {
    if (!state || !this.h) {
      return 0;
    }
    if (_rebuildFromLine !== void 0) {
      return _rebuildFromLine;
    }
    const previousState = this.h;
    const indexOfLinesAlreadyRendered = state.startLineNumbers.findIndex((startLineNumber) => !previousState.startLineNumbers.includes(startLineNumber));
    return indexOfLinesAlreadyRendered === -1 ? 0 : indexOfLinesAlreadyRendered;
  }
  z() {
    const layoutInfo = this.u.getLayoutInfo();
    const lineNumbersWidth = layoutInfo.contentLeft;
    this.c.style.width = `${lineNumbersWidth}px`;
    this.f.style.setProperty("--vscode-editorStickyScroll-scrollableWidth", `${this.u.getScrollWidth() - layoutInfo.verticalScrollbarWidth}px`);
    this.b.style.width = `${layoutInfo.width - layoutInfo.verticalScrollbarWidth}px`;
  }
  C(clearFromLine) {
    this.a.clear();
    for (let i2 = clearFromLine; i2 < this.m.length; i2++) {
      const stickyLine = this.m[i2];
      stickyLine.lineNumberDomNode.remove();
      stickyLine.lineDomNode.remove();
    }
    this.m = this.m.slice(0, clearFromLine);
    this.b.style.display = "none";
  }
  D(requireTransitions) {
    this.c.style.setProperty("--vscode-editorStickyScroll-foldingOpacityTransition", `opacity ${requireTransitions ? 0.5 : 0}s`);
  }
  F(allVisible) {
    for (const line of this.m) {
      const foldingIcon = line.foldingIcon;
      if (!foldingIcon) {
        continue;
      }
      foldingIcon.setVisible(allVisible ? true : foldingIcon.isCollapsed);
    }
  }
  async G(state, foldingModel, rebuildFromLine) {
    this.C(rebuildFromLine);
    if (!state) {
      return;
    }
    for (const stickyLine of this.m) {
      this.J(stickyLine);
    }
    const layoutInfo = this.u.getLayoutInfo();
    const linesToRender = this.n.slice(rebuildFromLine);
    for (const [index, line] of linesToRender.entries()) {
      const stickyLine = this.I(index + rebuildFromLine, line, foldingModel, layoutInfo);
      if (!stickyLine) {
        continue;
      }
      this.g.appendChild(stickyLine.lineDomNode);
      this.c.appendChild(stickyLine.lineNumberDomNode);
      this.m.push(stickyLine);
    }
    if (foldingModel) {
      this.H();
      this.D(!this.t);
    }
    const widgetHeight = this.n.length * this.j + this.r;
    this.b.style.display = "block";
    this.c.style.height = `${widgetHeight}px`;
    this.f.style.height = `${widgetHeight}px`;
    this.b.style.height = `${widgetHeight}px`;
    this.b.style.marginLeft = "0px";
    this.s = Math.max(...this.m.map((l) => l.scrollWidth)) + layoutInfo.verticalScrollbarWidth;
    this.u.layoutOverlayWidget(this);
  }
  H() {
    const showFoldingControls = this.u.getOption(
      115
      /* EditorOption.showFoldingControls */
    );
    if (showFoldingControls !== "mouseover") {
      return;
    }
    this.a.add($_i(this.c, $7j.MOUSE_ENTER, () => {
      this.t = true;
      this.F(true);
    }));
    this.a.add($_i(this.c, $7j.MOUSE_LEAVE, () => {
      this.t = false;
      this.D(true);
      this.F(false);
    }));
  }
  I(index, line, foldingModel, layoutInfo) {
    const viewModel = this.u._getViewModel();
    if (!viewModel) {
      return;
    }
    const viewLineNumber = viewModel.coordinatesConverter.convertModelPositionToViewPosition(new $8C(line, 1)).lineNumber;
    const lineRenderingData = viewModel.getViewLineRenderingData(viewLineNumber);
    const lineNumberOption = this.u.getOption(
      69
      /* EditorOption.lineNumbers */
    );
    let actualInlineDecorations;
    try {
      actualInlineDecorations = $m7.filter(lineRenderingData.inlineDecorations, viewLineNumber, lineRenderingData.minColumn, lineRenderingData.maxColumn);
    } catch (err) {
      actualInlineDecorations = [];
    }
    const renderLineInput = new $q7(true, true, lineRenderingData.content, lineRenderingData.continuesWithWrappedLine, lineRenderingData.isBasicASCII, lineRenderingData.containsRTL, 0, lineRenderingData.tokens, actualInlineDecorations, lineRenderingData.tabSize, lineRenderingData.startVisibleColumn, 1, 1, 1, 500, "none", true, true, null);
    const sb = new $cE(2e3);
    const renderOutput = $u7(renderLineInput, sb);
    let newLine;
    if (_ttPolicy) {
      newLine = _ttPolicy.createHTML(sb.build());
    } else {
      newLine = sb.build();
    }
    const lineHTMLNode = document.createElement("span");
    lineHTMLNode.setAttribute(STICKY_INDEX_ATTR, String(index));
    lineHTMLNode.setAttribute(STICKY_IS_LINE_ATTR, "");
    lineHTMLNode.setAttribute("role", "listitem");
    lineHTMLNode.tabIndex = 0;
    lineHTMLNode.className = "sticky-line-content";
    lineHTMLNode.classList.add(`stickyLine${line}`);
    lineHTMLNode.style.lineHeight = `${this.j}px`;
    lineHTMLNode.innerHTML = newLine;
    const lineNumberHTMLNode = document.createElement("span");
    lineNumberHTMLNode.setAttribute(STICKY_INDEX_ATTR, String(index));
    lineNumberHTMLNode.setAttribute(STICKY_IS_LINE_NUMBER_ATTR, "");
    lineNumberHTMLNode.className = "sticky-line-number";
    lineNumberHTMLNode.style.lineHeight = `${this.j}px`;
    const lineNumbersWidth = layoutInfo.contentLeft;
    lineNumberHTMLNode.style.width = `${lineNumbersWidth}px`;
    const innerLineNumberHTML = document.createElement("span");
    if (lineNumberOption.renderType === 1 || lineNumberOption.renderType === 3 && line % 10 === 0) {
      innerLineNumberHTML.innerText = line.toString();
    } else if (lineNumberOption.renderType === 2) {
      innerLineNumberHTML.innerText = Math.abs(line - this.u.getPosition().lineNumber).toString();
    }
    innerLineNumberHTML.className = "sticky-line-number-inner";
    innerLineNumberHTML.style.lineHeight = `${this.j}px`;
    innerLineNumberHTML.style.width = `${layoutInfo.lineNumbersWidth}px`;
    innerLineNumberHTML.style.paddingLeft = `${layoutInfo.lineNumbersLeft}px`;
    lineNumberHTMLNode.appendChild(innerLineNumberHTML);
    const foldingIcon = this.L(foldingModel, line);
    if (foldingIcon) {
      lineNumberHTMLNode.appendChild(foldingIcon.domNode);
    }
    this.u.applyFontInfo(lineHTMLNode);
    this.u.applyFontInfo(innerLineNumberHTML);
    lineNumberHTMLNode.style.lineHeight = `${this.j}px`;
    lineHTMLNode.style.lineHeight = `${this.j}px`;
    lineNumberHTMLNode.style.height = `${this.j}px`;
    lineHTMLNode.style.height = `${this.j}px`;
    const renderedLine = new RenderedStickyLine(index, line, lineHTMLNode, lineNumberHTMLNode, foldingIcon, renderOutput.characterMapping, lineHTMLNode.scrollWidth);
    return this.J(renderedLine);
  }
  J(stickyLine) {
    const index = stickyLine.index;
    const lineHTMLNode = stickyLine.lineDomNode;
    const lineNumberHTMLNode = stickyLine.lineNumberDomNode;
    const isLastLine = index === this.n.length - 1;
    const lastLineZIndex = "0";
    const intermediateLineZIndex = "1";
    lineHTMLNode.style.zIndex = isLastLine ? lastLineZIndex : intermediateLineZIndex;
    lineNumberHTMLNode.style.zIndex = isLastLine ? lastLineZIndex : intermediateLineZIndex;
    const lastLineTop = `${index * this.j + this.r + (stickyLine.foldingIcon?.isCollapsed ? 1 : 0)}px`;
    const intermediateLineTop = `${index * this.j}px`;
    lineHTMLNode.style.top = isLastLine ? lastLineTop : intermediateLineTop;
    lineNumberHTMLNode.style.top = isLastLine ? lastLineTop : intermediateLineTop;
    return stickyLine;
  }
  L(foldingModel, line) {
    const showFoldingControls = this.u.getOption(
      115
      /* EditorOption.showFoldingControls */
    );
    if (!foldingModel || showFoldingControls === "never") {
      return;
    }
    const foldingRegions = foldingModel.regions;
    const indexOfFoldingRegion = foldingRegions.findRange(line);
    const startLineNumber = foldingRegions.getStartLineNumber(indexOfFoldingRegion);
    const isFoldingScope = line === startLineNumber;
    if (!isFoldingScope) {
      return;
    }
    const isCollapsed = foldingRegions.isCollapsed(indexOfFoldingRegion);
    const foldingIcon = new StickyFoldingIcon(isCollapsed, startLineNumber, foldingRegions.getEndLineNumber(indexOfFoldingRegion), this.j);
    foldingIcon.setVisible(this.t ? true : isCollapsed || showFoldingControls === "always");
    foldingIcon.domNode.setAttribute(STICKY_IS_FOLDING_ICON_ATTR, "");
    return foldingIcon;
  }
  getId() {
    return "editor.contrib.stickyScrollWidget";
  }
  getDomNode() {
    return this.b;
  }
  getPosition() {
    return {
      preference: 2,
      stackOridinal: 10
    };
  }
  getMinContentWidthInPx() {
    return this.s;
  }
  focusLineWithIndex(index) {
    if (0 <= index && index < this.m.length) {
      this.m[index].lineDomNode.focus();
    }
  }
  /**
   * Given a leaf dom node, tries to find the editor position.
   */
  getEditorPositionFromNode(spanDomNode) {
    if (!spanDomNode || spanDomNode.children.length > 0) {
      return null;
    }
    const renderedStickyLine = this.M(spanDomNode);
    if (!renderedStickyLine) {
      return null;
    }
    const column = $Q7(renderedStickyLine.characterMapping, spanDomNode, 0);
    return new $8C(renderedStickyLine.lineNumber, column);
  }
  getLineNumberFromChildDomNode(domNode) {
    return this.M(domNode)?.lineNumber ?? null;
  }
  M(domNode) {
    const index = this.getLineIndexFromChildDomNode(domNode);
    if (index === null || index < 0 || index >= this.m.length) {
      return null;
    }
    return this.m[index];
  }
  /**
   * Given a child dom node, tries to find the line number attribute that was stored in the node.
   * @returns the attribute value or null if none is found.
   */
  getLineIndexFromChildDomNode(domNode) {
    const lineIndex = this.N(domNode, STICKY_INDEX_ATTR);
    return lineIndex ? parseInt(lineIndex, 10) : null;
  }
  /**
   * Given a child dom node, tries to find if it is (contained in) a sticky line.
   * @returns a boolean.
   */
  isInStickyLine(domNode) {
    const isInLine = this.N(domNode, STICKY_IS_LINE_ATTR);
    return isInLine !== void 0;
  }
  /**
   * Given a child dom node, tries to find if this dom node is (contained in) a sticky folding icon.
   * @returns a boolean.
   */
  isInFoldingIconDomNode(domNode) {
    const isInFoldingIcon = this.N(domNode, STICKY_IS_FOLDING_ICON_ATTR);
    return isInFoldingIcon !== void 0;
  }
  /**
   * Given the dom node, finds if it or its parent sequence contains the given attribute.
   * @returns the attribute value or undefined.
   */
  N(domNode, attribute) {
    while (domNode && domNode !== this.b) {
      const line = domNode.getAttribute(attribute);
      if (line !== null) {
        return line;
      }
      domNode = domNode.parentElement;
    }
    return;
  }
};
var RenderedStickyLine = class {
  constructor(index, lineNumber, lineDomNode, lineNumberDomNode, foldingIcon, characterMapping, scrollWidth) {
    this.index = index;
    this.lineNumber = lineNumber;
    this.lineDomNode = lineDomNode;
    this.lineNumberDomNode = lineNumberDomNode;
    this.foldingIcon = foldingIcon;
    this.characterMapping = characterMapping;
    this.scrollWidth = scrollWidth;
  }
};
var StickyFoldingIcon = class {
  constructor(isCollapsed, foldingStartLine, foldingEndLine, dimension) {
    this.isCollapsed = isCollapsed;
    this.foldingStartLine = foldingStartLine;
    this.foldingEndLine = foldingEndLine;
    this.dimension = dimension;
    this.domNode = document.createElement("div");
    this.domNode.style.width = `${dimension}px`;
    this.domNode.style.height = `${dimension}px`;
    this.domNode.className = ThemeIcon.asClassName(isCollapsed ? $3gb : $2gb);
  }
  setVisible(visible) {
    this.domNode.style.cursor = visible ? "pointer" : "default";
    this.domNode.style.opacity = visible ? "1" : "0";
  }
};

// out-build/vs/editor/contrib/stickyScroll/browser/stickyScrollElement.js
var $qkb = class {
  constructor(startLineNumber, endLineNumber) {
    this.startLineNumber = startLineNumber;
    this.endLineNumber = endLineNumber;
  }
};
var $rkb = class {
  constructor(range, children, parent) {
    this.range = range;
    this.children = children;
    this.parent = parent;
  }
};
var $skb = class {
  constructor(uri, version2, element, outlineProviderId) {
    this.uri = uri;
    this.version = version2;
    this.element = element;
    this.outlineProviderId = outlineProviderId;
  }
};

// out-build/vs/editor/contrib/stickyScroll/browser/stickyScrollModelProvider.js
var ModelProvider;
(function(ModelProvider2) {
  ModelProvider2["OUTLINE_MODEL"] = "outlineModel";
  ModelProvider2["FOLDING_PROVIDER_MODEL"] = "foldingProviderModel";
  ModelProvider2["INDENTATION_MODEL"] = "indentationModel";
})(ModelProvider || (ModelProvider = {}));
var Status;
(function(Status2) {
  Status2[Status2["VALID"] = 0] = "VALID";
  Status2[Status2["INVALID"] = 1] = "INVALID";
  Status2[Status2["CANCELED"] = 2] = "CANCELED";
})(Status || (Status = {}));
var $tkb = class $tkb2 extends $3c {
  constructor(g, onProviderUpdate, _languageConfigurationService, _languageFeaturesService) {
    super();
    this.g = g;
    this.a = [];
    this.b = null;
    this.c = this.B(new $Sh(300));
    this.f = this.B(new $2c());
    switch (this.g.getOption(
      120
      /* EditorOption.stickyScroll */
    ).defaultModel) {
      case ModelProvider.OUTLINE_MODEL:
        this.a.push(new StickyModelFromCandidateOutlineProvider(this.g, _languageFeaturesService));
      case ModelProvider.FOLDING_PROVIDER_MODEL:
        this.a.push(new StickyModelFromCandidateSyntaxFoldingProvider(this.g, onProviderUpdate, _languageFeaturesService));
      case ModelProvider.INDENTATION_MODEL:
        this.a.push(new StickyModelFromCandidateIndentationFoldingProvider(this.g, _languageConfigurationService));
        break;
    }
  }
  dispose() {
    this.a.forEach((provider) => provider.dispose());
    this.f.clear();
    this.h();
    super.dispose();
  }
  h() {
    if (this.b) {
      this.b.cancel();
      this.b = null;
    }
  }
  async update(token) {
    this.f.clear();
    this.f.add({
      dispose: () => {
        this.h();
        this.c.cancel();
      }
    });
    this.h();
    return await this.c.trigger(async () => {
      for (const modelProvider of this.a) {
        const { statusPromise, modelPromise } = modelProvider.computeStickyModel(token);
        this.b = modelPromise;
        const status = await statusPromise;
        if (this.b !== modelPromise) {
          return null;
        }
        switch (status) {
          case Status.CANCELED:
            this.f.clear();
            return null;
          case Status.VALID:
            return modelProvider.stickyModel;
        }
      }
      return null;
    }).catch((error) => {
      $gb(error);
      return null;
    });
  }
};
$tkb = __decorate([
  __param(2, $Pk),
  __param(3, $mP)
], $tkb);
var StickyModelCandidateProvider = class extends $3c {
  constructor(b) {
    super();
    this.b = b;
    this.a = null;
  }
  get stickyModel() {
    return this.a;
  }
  c() {
    this.a = null;
    return Status.INVALID;
  }
  computeStickyModel(token) {
    if (token.isCancellationRequested || !this.g()) {
      return { statusPromise: this.c(), modelPromise: null };
    }
    const providerModelPromise = $Hh((token2) => this.h(token2));
    return {
      statusPromise: providerModelPromise.then((providerModel) => {
        if (!this.f(providerModel)) {
          return this.c();
        }
        if (token.isCancellationRequested) {
          return Status.CANCELED;
        }
        this.a = this.j(token, providerModel);
        return Status.VALID;
      }).then(void 0, (err) => {
        $gb(err);
        return Status.CANCELED;
      }),
      modelPromise: providerModelPromise
    };
  }
  /**
   * Method which checks whether the model returned by the provider is valid and can be used to compute a sticky model.
   * This method by default returns true.
   * @param model model returned by the provider
   * @returns boolean indicating whether the model is valid
   */
  f(model) {
    return true;
  }
  /**
   * Method which checks whether the provider is valid before applying it to find the provider model.
   * This method by default returns true.
   * @returns boolean indicating whether the provider is valid
   */
  g() {
    return true;
  }
};
var StickyModelFromCandidateOutlineProvider = class StickyModelFromCandidateOutlineProvider2 extends StickyModelCandidateProvider {
  constructor(_editor, m) {
    super(_editor);
    this.m = m;
  }
  h(token) {
    return $ohb.create(this.m.documentSymbolProvider, this.b.getModel(), token);
  }
  j(token, model) {
    const { stickyOutlineElement, providerID } = this.t(model, this.a?.outlineProviderId);
    const textModel = this.b.getModel();
    return new $skb(textModel.uri, textModel.getVersionId(), stickyOutlineElement, providerID);
  }
  f(model) {
    return model && model.children.size > 0;
  }
  t(outlineModel, preferredProvider) {
    let outlineElements;
    if (Iterable.first(outlineModel.children.values()) instanceof $nhb) {
      const provider = Iterable.find(outlineModel.children.values(), (outlineGroupOfModel) => outlineGroupOfModel.id === preferredProvider);
      if (provider) {
        outlineElements = provider.children;
      } else {
        let tempID = "";
        let maxTotalSumOfRanges = -1;
        let optimalOutlineGroup = void 0;
        for (const [_key, outlineGroup] of outlineModel.children.entries()) {
          const totalSumRanges = this.y(outlineGroup);
          if (totalSumRanges > maxTotalSumOfRanges) {
            optimalOutlineGroup = outlineGroup;
            maxTotalSumOfRanges = totalSumRanges;
            tempID = outlineGroup.id;
          }
        }
        preferredProvider = tempID;
        outlineElements = optimalOutlineGroup.children;
      }
    } else {
      outlineElements = outlineModel.children;
    }
    const stickyChildren = [];
    const outlineElementsArray = Array.from(outlineElements.values()).sort((element1, element2) => {
      const range1 = new $qkb(element1.symbol.range.startLineNumber, element1.symbol.range.endLineNumber);
      const range2 = new $qkb(element2.symbol.range.startLineNumber, element2.symbol.range.endLineNumber);
      return this.w(range1, range2);
    });
    for (const outlineElement of outlineElementsArray) {
      stickyChildren.push(this.u(outlineElement, outlineElement.symbol.selectionRange.startLineNumber));
    }
    const stickyOutlineElement = new $rkb(void 0, stickyChildren, void 0);
    return {
      stickyOutlineElement,
      providerID: preferredProvider
    };
  }
  u(outlineElement, previousStartLine) {
    const children = [];
    for (const child of outlineElement.children.values()) {
      if (child.symbol.selectionRange.startLineNumber !== child.symbol.range.endLineNumber) {
        if (child.symbol.selectionRange.startLineNumber !== previousStartLine) {
          children.push(this.u(child, child.symbol.selectionRange.startLineNumber));
        } else {
          for (const subchild of child.children.values()) {
            children.push(this.u(subchild, child.symbol.selectionRange.startLineNumber));
          }
        }
      }
    }
    children.sort((child1, child2) => this.w(child1.range, child2.range));
    const range = new $qkb(outlineElement.symbol.selectionRange.startLineNumber, outlineElement.symbol.range.endLineNumber);
    return new $rkb(range, children, void 0);
  }
  w(range1, range2) {
    if (range1.startLineNumber !== range2.startLineNumber) {
      return range1.startLineNumber - range2.startLineNumber;
    } else {
      return range2.endLineNumber - range1.endLineNumber;
    }
  }
  y(outline) {
    let res = 0;
    for (const child of outline.children.values()) {
      res += this.y(child);
    }
    if (outline instanceof $mhb) {
      return res + outline.symbol.range.endLineNumber - outline.symbol.selectionRange.startLineNumber;
    } else {
      return res;
    }
  }
};
StickyModelFromCandidateOutlineProvider = __decorate([
  __param(1, $mP)
], StickyModelFromCandidateOutlineProvider);
var StickyModelFromCandidateFoldingProvider = class extends StickyModelCandidateProvider {
  constructor(editor) {
    super(editor);
    this.m = new $0gb(editor);
  }
  j(token, model) {
    const foldingElement = this.s(model);
    const textModel = this.b.getModel();
    return new $skb(textModel.uri, textModel.getVersionId(), foldingElement, void 0);
  }
  f(model) {
    return model !== null;
  }
  s(foldingRegions) {
    const length = foldingRegions.length;
    const orderedStickyElements = [];
    const stickyOutlineElement = new $rkb(void 0, [], void 0);
    for (let i2 = 0; i2 < length; i2++) {
      const parentIndex = foldingRegions.getParentIndex(i2);
      let parentNode;
      if (parentIndex !== -1) {
        parentNode = orderedStickyElements[parentIndex];
      } else {
        parentNode = stickyOutlineElement;
      }
      const child = new $rkb(new $qkb(foldingRegions.getStartLineNumber(i2), foldingRegions.getEndLineNumber(i2) + 1), [], parentNode);
      parentNode.children.push(child);
      orderedStickyElements.push(child);
    }
    return stickyOutlineElement;
  }
};
var StickyModelFromCandidateIndentationFoldingProvider = class StickyModelFromCandidateIndentationFoldingProvider2 extends StickyModelFromCandidateFoldingProvider {
  constructor(editor, u) {
    super(editor);
    this.u = u;
    this.t = this.B(new $Ygb(editor.getModel(), this.u, this.m));
  }
  async h(token) {
    return this.t.compute(token);
  }
};
StickyModelFromCandidateIndentationFoldingProvider = __decorate([
  __param(1, $NF)
], StickyModelFromCandidateIndentationFoldingProvider);
var StickyModelFromCandidateSyntaxFoldingProvider = class StickyModelFromCandidateSyntaxFoldingProvider2 extends StickyModelFromCandidateFoldingProvider {
  constructor(editor, onProviderUpdate, u) {
    super(editor);
    this.u = u;
    const selectedProviders = $9gb.getFoldingRangeProviders(this.u, editor.getModel());
    if (selectedProviders.length > 0) {
      this.t = this.B(new $7gb(editor.getModel(), selectedProviders, onProviderUpdate, this.m, void 0));
    }
  }
  g() {
    return this.t !== void 0;
  }
  async h(token) {
    return this.t?.compute(token) ?? null;
  }
};
StickyModelFromCandidateSyntaxFoldingProvider = __decorate([
  __param(2, $mP)
], StickyModelFromCandidateSyntaxFoldingProvider);

// out-build/vs/editor/contrib/stickyScroll/browser/stickyScrollProvider.js
var $ukb = class {
  constructor(startLineNumber, endLineNumber, nestingDepth) {
    this.startLineNumber = startLineNumber;
    this.endLineNumber = endLineNumber;
    this.nestingDepth = nestingDepth;
  }
};
var $vkb = class $vkb2 extends $3c {
  static {
    this.ID = "store.contrib.stickyScrollController";
  }
  constructor(editor, r2, s) {
    super();
    this.r = r2;
    this.s = s;
    this.c = this.B(new $ze());
    this.onDidChangeStickyScroll = this.c.event;
    this.j = null;
    this.m = null;
    this.n = null;
    this.f = editor;
    this.h = this.B(new $2c());
    this.g = this.B(new $8h(() => this.update(), 50));
    this.B(this.f.onDidChangeConfiguration((e) => {
      if (e.hasChanged(
        120
        /* EditorOption.stickyScroll */
      )) {
        this.t();
      }
    }));
    this.t();
  }
  t() {
    this.h.clear();
    const options3 = this.f.getOption(
      120
      /* EditorOption.stickyScroll */
    );
    if (!options3.enabled) {
      return;
    }
    this.h.add(this.f.onDidChangeModel(() => {
      this.j = null;
      this.u();
      this.c.fire();
      this.update();
    }));
    this.h.add(this.f.onDidChangeHiddenAreas(() => this.update()));
    this.h.add(this.f.onDidChangeModelContent(() => this.g.schedule()));
    this.h.add(this.r.documentSymbolProvider.onDidChange(() => this.update()));
    this.h.add($1c(() => {
      this.n?.dispose();
      this.n = null;
    }));
    this.u();
    this.update();
  }
  getVersionId() {
    return this.j?.version;
  }
  u() {
    this.n?.dispose();
    this.n = null;
    const editor = this.f;
    if (editor.hasModel()) {
      this.n = new $tkb(editor, () => this.g.schedule(), this.s, this.r);
    }
  }
  async update() {
    this.m?.dispose(true);
    this.m = new $ad();
    await this.w(this.m.token);
    this.c.fire();
  }
  async w(token) {
    if (!this.f.hasModel() || !this.n || this.f.getModel().isTooLargeForTokenization()) {
      this.j = null;
      return;
    }
    const model = await this.n.update(token);
    if (token.isCancellationRequested) {
      return;
    }
    this.j = model;
  }
  y(index) {
    if (index === -1) {
      index = 0;
    } else if (index < 0) {
      index = -index - 2;
    }
    return index;
  }
  getCandidateStickyLinesIntersectingFromStickyModel(range, outlineModel, result, depth, lastStartLineNumber) {
    if (outlineModel.children.length === 0) {
      return;
    }
    let lastLine = lastStartLineNumber;
    const childrenStartLines = [];
    for (let i2 = 0; i2 < outlineModel.children.length; i2++) {
      const child = outlineModel.children[i2];
      if (child.range) {
        childrenStartLines.push(child.range.startLineNumber);
      }
    }
    const lowerBound = this.y($Bb(childrenStartLines, range.startLineNumber, (a, b) => {
      return a - b;
    }));
    const upperBound = this.y($Bb(childrenStartLines, range.startLineNumber + depth, (a, b) => {
      return a - b;
    }));
    for (let i2 = lowerBound; i2 <= upperBound; i2++) {
      const child = outlineModel.children[i2];
      if (!child) {
        return;
      }
      if (child.range) {
        const childStartLine = child.range.startLineNumber;
        const childEndLine = child.range.endLineNumber;
        if (range.startLineNumber <= childEndLine + 1 && childStartLine - 1 <= range.endLineNumber && childStartLine !== lastLine) {
          lastLine = childStartLine;
          result.push(new $ukb(childStartLine, childEndLine - 1, depth + 1));
          this.getCandidateStickyLinesIntersectingFromStickyModel(range, child, result, depth + 1, childStartLine);
        }
      } else {
        this.getCandidateStickyLinesIntersectingFromStickyModel(range, child, result, depth, lastStartLineNumber);
      }
    }
  }
  getCandidateStickyLinesIntersecting(range) {
    if (!this.j?.element) {
      return [];
    }
    let stickyLineCandidates = [];
    this.getCandidateStickyLinesIntersectingFromStickyModel(range, this.j.element, stickyLineCandidates, 0, -1);
    const hiddenRanges = this.f._getViewModel()?.getHiddenAreas();
    if (hiddenRanges) {
      for (const hiddenRange of hiddenRanges) {
        stickyLineCandidates = stickyLineCandidates.filter((stickyLine) => !(stickyLine.startLineNumber >= hiddenRange.startLineNumber && stickyLine.endLineNumber <= hiddenRange.endLineNumber + 1));
      }
    }
    return stickyLineCandidates;
  }
};
$vkb = __decorate([
  __param(1, $mP),
  __param(2, $NF)
], $vkb);

// out-build/vs/editor/contrib/stickyScroll/browser/stickyScrollController.js
var $wkb_1;
var $wkb = class $wkb2 extends $3c {
  static {
    $wkb_1 = this;
  }
  static {
    this.ID = "store.contrib.stickyScrollController";
  }
  constructor(G, H, I, J, _languageConfigurationService, _languageFeatureDebounceService, L) {
    super();
    this.G = G;
    this.H = H;
    this.I = I;
    this.J = J;
    this.L = L;
    this.c = new $2c();
    this.h = Number.MAX_SAFE_INTEGER;
    this.m = -1;
    this.t = -1;
    this.u = false;
    this.w = false;
    this.y = false;
    this.z = false;
    this.C = [];
    this.a = new $pkb(this.G);
    this.b = new $vkb(this.G, I, _languageConfigurationService);
    this.B(this.a);
    this.B(this.b);
    this.f = $okb.Empty;
    const stickyScrollDomNode = this.a.getDomNode();
    this.B(this.G.onDidChangeConfiguration((e) => {
      this.X(e);
    }));
    this.B($_i(stickyScrollDomNode, $7j.CONTEXT_MENU, async (event) => {
      this.S(getWindow(stickyScrollDomNode), event);
    }));
    this.n = EditorContextKeys.stickyScrollFocused.bindTo(this.L);
    this.r = EditorContextKeys.stickyScrollVisible.bindTo(this.L);
    const focusTracker = this.B($_j(stickyScrollDomNode));
    this.B(focusTracker.onDidBlur((_) => {
      if (this.y === false && stickyScrollDomNode.clientHeight === 0) {
        this.t = -1;
        this.focus();
      } else {
        this.M();
      }
    }));
    this.B(focusTracker.onDidFocus((_) => {
      this.focus();
    }));
    this.R();
    this.B($_i(stickyScrollDomNode, $7j.MOUSE_DOWN, (e) => {
      this.z = true;
    }));
    this.$();
    this.W();
  }
  get stickyScrollCandidateProvider() {
    return this.b;
  }
  get stickyScrollWidgetState() {
    return this.f;
  }
  static get(editor) {
    return editor.getContribution($wkb_1.ID);
  }
  M() {
    this.n.set(false);
    this.s?.dispose();
    this.w = false;
    this.y = false;
    this.z = false;
  }
  focus() {
    if (this.z) {
      this.z = false;
      this.G.focus();
      return;
    }
    const focusState = this.n.get();
    if (focusState === true) {
      return;
    }
    this.w = true;
    this.s = new $2c();
    this.n.set(true);
    this.t = this.a.lineNumbers.length - 1;
    this.a.focusLineWithIndex(this.t);
  }
  focusNext() {
    if (this.t < this.a.lineNumberCount - 1) {
      this.N(true);
    }
  }
  focusPrevious() {
    if (this.t > 0) {
      this.N(false);
    }
  }
  selectEditor() {
    this.G.focus();
  }
  // True is next, false is previous
  N(direction) {
    this.t = direction ? this.t + 1 : this.t - 1;
    this.a.focusLineWithIndex(this.t);
  }
  goToFocused() {
    const lineNumbers = this.a.lineNumbers;
    this.M();
    this.O({ lineNumber: lineNumbers[this.t], column: 1 });
  }
  O(position) {
    this.Q(position, () => this.G.revealPosition(position));
  }
  P(position) {
    this.Q(position, () => this.G.revealLineInCenterIfOutsideViewport(
      position.lineNumber,
      0
      /* ScrollType.Smooth */
    ));
  }
  Q(position, revealFunction) {
    if (this.w) {
      this.M();
    }
    this.y = true;
    revealFunction();
    this.G.setSelection($9C.fromPositions(position));
    this.G.focus();
  }
  R() {
    const sessionStore = this.B(new $2c());
    const gesture = this.B(new $6db(this.G, {
      extractLineNumberFromMouseEvent: (e) => {
        const position = this.a.getEditorPositionFromNode(e.target.element);
        return position ? position.lineNumber : 0;
      }
    }));
    const getMouseEventTarget = (mouseEvent) => {
      if (!this.G.hasModel()) {
        return null;
      }
      if (mouseEvent.target.type !== 12 || mouseEvent.target.detail !== this.a.getId()) {
        return null;
      }
      const mouseTargetElement = mouseEvent.target.element;
      if (!mouseTargetElement || mouseTargetElement.innerText !== mouseTargetElement.innerHTML) {
        return null;
      }
      const position = this.a.getEditorPositionFromNode(mouseTargetElement);
      if (!position) {
        return null;
      }
      return {
        range: new $9C(position.lineNumber, position.column, position.lineNumber, position.column + mouseTargetElement.innerText.length),
        textElement: mouseTargetElement
      };
    };
    const stickyScrollWidgetDomNode = this.a.getDomNode();
    this.B($aj(stickyScrollWidgetDomNode, $7j.CLICK, (mouseEvent) => {
      if (mouseEvent.ctrlKey || mouseEvent.altKey || mouseEvent.metaKey) {
        return;
      }
      if (!mouseEvent.leftButton) {
        return;
      }
      if (mouseEvent.shiftKey) {
        const lineIndex = this.a.getLineIndexFromChildDomNode(mouseEvent.target);
        if (lineIndex === null) {
          return;
        }
        const position2 = new $8C(this.C[lineIndex], 1);
        this.P(position2);
        return;
      }
      const isInFoldingIconDomNode = this.a.isInFoldingIconDomNode(mouseEvent.target);
      if (isInFoldingIconDomNode) {
        const lineNumber = this.a.getLineNumberFromChildDomNode(mouseEvent.target);
        this.U(lineNumber);
        return;
      }
      const isInStickyLine = this.a.isInStickyLine(mouseEvent.target);
      if (!isInStickyLine) {
        return;
      }
      let position = this.a.getEditorPositionFromNode(mouseEvent.target);
      if (!position) {
        const lineNumber = this.a.getLineNumberFromChildDomNode(mouseEvent.target);
        if (lineNumber === null) {
          return;
        }
        position = new $8C(lineNumber, 1);
      }
      this.O(position);
    }));
    this.B($aj(stickyScrollWidgetDomNode, $7j.MOUSE_MOVE, (mouseEvent) => {
      if (mouseEvent.shiftKey) {
        const currentEndForLineIndex = this.a.getLineIndexFromChildDomNode(mouseEvent.target);
        if (currentEndForLineIndex === null || this.D !== null && this.D === currentEndForLineIndex) {
          return;
        }
        this.D = currentEndForLineIndex;
        this.ab();
        return;
      }
      if (this.D !== void 0) {
        this.D = void 0;
        this.ab();
      }
    }));
    this.B($_i(stickyScrollWidgetDomNode, $7j.MOUSE_LEAVE, (e) => {
      if (this.D !== void 0) {
        this.D = void 0;
        this.ab();
      }
    }));
    this.B(gesture.onMouseMoveOrRelevantKeyDown(([mouseEvent, _keyboardEvent]) => {
      const mouseTarget = getMouseEventTarget(mouseEvent);
      if (!mouseTarget || !mouseEvent.hasTriggerModifier || !this.G.hasModel()) {
        sessionStore.clear();
        return;
      }
      const { range, textElement } = mouseTarget;
      if (!range.equalsRange(this.j)) {
        this.j = range;
        sessionStore.clear();
      } else if (textElement.style.textDecoration === "underline") {
        return;
      }
      const cancellationToken = new $ad();
      sessionStore.add($1c(() => cancellationToken.dispose(true)));
      let currentHTMLChild;
      $kfb(this.I.definitionProvider, this.G.getModel(), new $8C(range.startLineNumber, range.startColumn + 1), false, cancellationToken.token).then((candidateDefinitions) => {
        if (cancellationToken.token.isCancellationRequested) {
          return;
        }
        if (candidateDefinitions.length !== 0) {
          this.m = candidateDefinitions.length;
          const childHTML = textElement;
          if (currentHTMLChild !== childHTML) {
            sessionStore.clear();
            currentHTMLChild = childHTML;
            currentHTMLChild.style.textDecoration = "underline";
            sessionStore.add($1c(() => {
              currentHTMLChild.style.textDecoration = "none";
            }));
          } else if (!currentHTMLChild) {
            currentHTMLChild = childHTML;
            currentHTMLChild.style.textDecoration = "underline";
            sessionStore.add($1c(() => {
              currentHTMLChild.style.textDecoration = "none";
            }));
          }
        } else {
          sessionStore.clear();
        }
      });
    }));
    this.B(gesture.onCancel(() => {
      sessionStore.clear();
    }));
    this.B(gesture.onExecute(async (e) => {
      if (e.target.type !== 12 || e.target.detail !== this.a.getId()) {
        return;
      }
      const position = this.a.getEditorPositionFromNode(e.target.element);
      if (!position) {
        return;
      }
      if (!this.G.hasModel() || !this.j) {
        return;
      }
      if (this.m > 1) {
        if (this.w) {
          this.M();
        }
        this.O({ lineNumber: position.lineNumber, column: 1 });
      }
      this.J.invokeFunction($tfb, e, this.G, { uri: this.G.getModel().uri, range: this.j });
    }));
  }
  S(targetWindow, e) {
    const event = new $lf(targetWindow, e);
    this.H.showContextMenu({
      menuId: $bJ.StickyScrollContext,
      getAnchor: () => event
    });
  }
  U(line) {
    if (!this.g || line === null) {
      return;
    }
    const stickyLine = this.a.getRenderedStickyLine(line);
    const foldingIcon = stickyLine?.foldingIcon;
    if (!foldingIcon) {
      return;
    }
    $Mgb(this.g, Number.MAX_VALUE, [line]);
    foldingIcon.isCollapsed = !foldingIcon.isCollapsed;
    const scrollTop = (foldingIcon.isCollapsed ? this.G.getTopForLineNumber(foldingIcon.foldingEndLine) : this.G.getTopForLineNumber(foldingIcon.foldingStartLine)) - this.G.getOption(
      68
      /* EditorOption.lineHeight */
    ) * stickyLine.index + 1;
    this.G.setScrollTop(scrollTop);
    this.ab(line);
  }
  W() {
    const options3 = this.G.getOption(
      120
      /* EditorOption.stickyScroll */
    );
    if (options3.enabled === false) {
      this.G.removeOverlayWidget(this.a);
      this.c.clear();
      this.u = false;
      return;
    } else if (options3.enabled && !this.u) {
      this.G.addOverlayWidget(this.a);
      this.c.add(this.G.onDidScrollChange((e) => {
        if (e.scrollTopChanged) {
          this.D = void 0;
          this.ab();
        }
      }));
      this.c.add(this.G.onDidLayoutChange(() => this.$()));
      this.c.add(this.G.onDidChangeModelTokens((e) => this.Z(e)));
      this.c.add(this.b.onDidChangeStickyScroll(() => {
        this.D = void 0;
        this.ab();
      }));
      this.u = true;
    }
    const lineNumberOption = this.G.getOption(
      69
      /* EditorOption.lineNumbers */
    );
    if (lineNumberOption.renderType === 2) {
      this.c.add(this.G.onDidChangeCursorPosition(() => {
        this.D = void 0;
        this.ab(0);
      }));
    }
  }
  X(event) {
    if (event.hasChanged(
      120
      /* EditorOption.stickyScroll */
    ) || event.hasChanged(
      74
      /* EditorOption.minimap */
    ) || event.hasChanged(
      68
      /* EditorOption.lineHeight */
    ) || event.hasChanged(
      115
      /* EditorOption.showFoldingControls */
    ) || event.hasChanged(
      69
      /* EditorOption.lineNumbers */
    )) {
      this.W();
    }
    if (event.hasChanged(
      69
      /* EditorOption.lineNumbers */
    )) {
      this.ab(0);
    }
  }
  Y(event) {
    const stickyLineNumbers = this.a.getCurrentLines();
    for (const stickyLineNumber of stickyLineNumbers) {
      for (const range of event.ranges) {
        if (stickyLineNumber >= range.fromLineNumber && stickyLineNumber <= range.toLineNumber) {
          return true;
        }
      }
    }
    return false;
  }
  Z(event) {
    if (this.Y(event)) {
      this.ab(0);
    }
  }
  $() {
    const layoutInfo = this.G.getLayoutInfo();
    const theoreticalLines = layoutInfo.height / this.G.getOption(
      68
      /* EditorOption.lineHeight */
    );
    this.h = Math.round(theoreticalLines * 0.25);
    this.ab(0);
  }
  async ab(rebuildFromLine) {
    const model = this.G.getModel();
    if (!model || model.isTooLargeForTokenization()) {
      this.db();
      return;
    }
    const nextRebuildFromLine = this.bb(rebuildFromLine);
    const stickyWidgetVersion = this.b.getVersionId();
    const shouldUpdateState = stickyWidgetVersion === void 0 || stickyWidgetVersion === model.getVersionId();
    if (shouldUpdateState) {
      if (!this.w) {
        await this.cb(nextRebuildFromLine);
      } else {
        if (this.t === -1) {
          await this.cb(nextRebuildFromLine);
          this.t = this.a.lineNumberCount - 1;
          if (this.t !== -1) {
            this.a.focusLineWithIndex(this.t);
          }
        } else {
          const focusedStickyElementLineNumber = this.a.lineNumbers[this.t];
          await this.cb(nextRebuildFromLine);
          if (this.a.lineNumberCount === 0) {
            this.t = -1;
          } else {
            const previousFocusedLineNumberExists = this.a.lineNumbers.includes(focusedStickyElementLineNumber);
            if (!previousFocusedLineNumberExists) {
              this.t = this.a.lineNumberCount - 1;
            }
            this.a.focusLineWithIndex(this.t);
          }
        }
      }
    }
  }
  bb(rebuildFromLine) {
    if (rebuildFromLine !== void 0) {
      const minRebuildFromLineOrInfinity = this.F !== void 0 ? this.F : Infinity;
      this.F = Math.min(rebuildFromLine, minRebuildFromLineOrInfinity);
    }
    return this.F;
  }
  async cb(rebuildFromLine) {
    this.F = void 0;
    this.g = await $9gb.get(this.G)?.getFoldingModel() ?? void 0;
    this.f = this.findScrollWidgetState();
    const stickyWidgetHasLines = this.f.startLineNumbers.length > 0;
    this.r.set(stickyWidgetHasLines);
    this.a.setState(this.f, this.g, rebuildFromLine);
  }
  async db() {
    this.F = void 0;
    this.g = void 0;
    this.f = $okb.Empty;
    this.r.set(false);
    this.a.setState(void 0, void 0);
  }
  findScrollWidgetState() {
    const lineHeight = this.G.getOption(
      68
      /* EditorOption.lineHeight */
    );
    const maxNumberStickyLines = Math.min(this.h, this.G.getOption(
      120
      /* EditorOption.stickyScroll */
    ).maxLineCount);
    const scrollTop = this.G.getScrollTop();
    let lastLineRelativePosition = 0;
    const startLineNumbers = [];
    const endLineNumbers = [];
    const arrayVisibleRanges = this.G.getVisibleRanges();
    if (arrayVisibleRanges.length !== 0) {
      const fullVisibleRange = new $qkb(arrayVisibleRanges[0].startLineNumber, arrayVisibleRanges[arrayVisibleRanges.length - 1].endLineNumber);
      const candidateRanges = this.b.getCandidateStickyLinesIntersecting(fullVisibleRange);
      for (const range of candidateRanges) {
        const start = range.startLineNumber;
        const end = range.endLineNumber;
        const depth = range.nestingDepth;
        if (end - start > 0) {
          const topOfElementAtDepth = (depth - 1) * lineHeight;
          const bottomOfElementAtDepth = depth * lineHeight;
          const bottomOfBeginningLine = this.G.getBottomForLineNumber(start) - scrollTop;
          const topOfEndLine = this.G.getTopForLineNumber(end) - scrollTop;
          const bottomOfEndLine = this.G.getBottomForLineNumber(end) - scrollTop;
          if (topOfElementAtDepth > topOfEndLine && topOfElementAtDepth <= bottomOfEndLine) {
            startLineNumbers.push(start);
            endLineNumbers.push(end + 1);
            if (topOfElementAtDepth > bottomOfEndLine - lineHeight) {
              lastLineRelativePosition = bottomOfEndLine - bottomOfElementAtDepth;
            }
            break;
          } else if (bottomOfElementAtDepth > bottomOfBeginningLine && bottomOfElementAtDepth <= bottomOfEndLine) {
            startLineNumbers.push(start);
            endLineNumbers.push(end + 1);
          }
          if (startLineNumbers.length === maxNumberStickyLines) {
            break;
          }
        }
      }
    }
    this.C = endLineNumbers;
    return new $okb(startLineNumbers, endLineNumbers, lastLineRelativePosition, this.D);
  }
  dispose() {
    super.dispose();
    this.c.dispose();
  }
};
$wkb = $wkb_1 = __decorate([
  __param(1, $50),
  __param(2, $mP),
  __param(3, $Pk),
  __param(4, $NF),
  __param(5, $tbb),
  __param(6, $on)
], $wkb);

// out-build/vs/editor/contrib/stickyScroll/browser/stickyScrollActions.js
var $xkb = class extends $gJ {
  constructor() {
    super({
      id: "editor.action.toggleStickyScroll",
      title: {
        ...localize2(1486, "Toggle Editor Sticky Scroll"),
        mnemonicTitle: localize(1482, null)
      },
      metadata: {
        description: localize2(1487, "Toggle/enable the editor sticky scroll which shows the nested scopes at the top of the viewport")
      },
      category: $qn.View,
      toggled: {
        condition: $7m.equals("config.editor.stickyScroll.enabled", true),
        title: localize(1483, null),
        mnemonicTitle: localize(1484, null)
      },
      menu: [
        { id: $bJ.CommandPalette },
        { id: $bJ.MenubarAppearanceMenu, group: "4_editor", order: 3 },
        { id: $bJ.StickyScrollContext }
      ]
    });
  }
  async run(accessor) {
    const configurationService = accessor.get($kl);
    const newValue = !configurationService.getValue("editor.stickyScroll.enabled");
    return configurationService.updateValue("editor.stickyScroll.enabled", newValue);
  }
};
var weight4 = 100;
var $ykb = class extends $25 {
  constructor() {
    super({
      id: "editor.action.focusStickyScroll",
      title: {
        ...localize2(1488, "Focus on the editor sticky scroll"),
        mnemonicTitle: localize(1485, null)
      },
      precondition: $7m.and($7m.has("config.editor.stickyScroll.enabled"), EditorContextKeys.stickyScrollVisible),
      menu: [
        { id: $bJ.CommandPalette }
      ]
    });
  }
  runEditorCommand(_accessor, editor) {
    $wkb.get(editor)?.focus();
  }
};
var $zkb = class extends $25 {
  constructor() {
    super({
      id: "editor.action.selectNextStickyScrollLine",
      title: localize2(1489, "Select the next editor sticky scroll line"),
      precondition: EditorContextKeys.stickyScrollFocused.isEqualTo(true),
      keybinding: {
        weight: weight4,
        primary: 18
        /* KeyCode.DownArrow */
      }
    });
  }
  runEditorCommand(_accessor, editor) {
    $wkb.get(editor)?.focusNext();
  }
};
var $Akb = class extends $25 {
  constructor() {
    super({
      id: "editor.action.selectPreviousStickyScrollLine",
      title: localize2(1490, "Select the previous sticky scroll line"),
      precondition: EditorContextKeys.stickyScrollFocused.isEqualTo(true),
      keybinding: {
        weight: weight4,
        primary: 16
        /* KeyCode.UpArrow */
      }
    });
  }
  runEditorCommand(_accessor, editor) {
    $wkb.get(editor)?.focusPrevious();
  }
};
var $Bkb = class extends $25 {
  constructor() {
    super({
      id: "editor.action.goToFocusedStickyScrollLine",
      title: localize2(1491, "Go to the focused sticky scroll line"),
      precondition: EditorContextKeys.stickyScrollFocused.isEqualTo(true),
      keybinding: {
        weight: weight4,
        primary: 3
        /* KeyCode.Enter */
      }
    });
  }
  runEditorCommand(_accessor, editor) {
    $wkb.get(editor)?.goToFocused();
  }
};
var $Ckb = class extends $25 {
  constructor() {
    super({
      id: "editor.action.selectEditor",
      title: localize2(1492, "Select Editor"),
      precondition: EditorContextKeys.stickyScrollFocused.isEqualTo(true),
      keybinding: {
        weight: weight4,
        primary: 9
        /* KeyCode.Escape */
      }
    });
  }
  runEditorCommand(_accessor, editor) {
    $wkb.get(editor)?.selectEditor();
  }
};

// out-build/vs/editor/contrib/stickyScroll/browser/stickyScrollContribution.js
$85(
  $wkb.ID,
  $wkb,
  1
  /* EditorContributionInstantiation.AfterFirstRender */
);
$hJ($xkb);
$hJ($ykb);
$hJ($Akb);
$hJ($zkb);
$hJ($Bkb);
$hJ($Ckb);

// out-build/vs/editor/contrib/suggest/browser/suggestInlineCompletions.js
var SuggestInlineCompletion = class {
  constructor(range, insertText, filterText, additionalTextEdits, command4, completion) {
    this.range = range;
    this.insertText = insertText;
    this.filterText = filterText;
    this.additionalTextEdits = additionalTextEdits;
    this.command = command4;
    this.completion = completion;
  }
};
var InlineCompletionResults = class InlineCompletionResults2 extends $6c {
  constructor(model, line, word, completionModel, completions, c) {
    super(completions.disposable);
    this.model = model;
    this.line = line;
    this.word = word;
    this.completionModel = completionModel;
    this.c = c;
  }
  canBeReused(model, line, word) {
    return this.model === model && this.line === line && this.word.word.length > 0 && this.word.startColumn === word.startColumn && this.word.endColumn < word.endColumn && this.completionModel.getIncompleteProvider().size === 0;
  }
  get items() {
    const result = [];
    const { items } = this.completionModel;
    const selectedIndex = this.c.select(this.model, { lineNumber: this.line, column: this.word.endColumn + this.completionModel.lineContext.characterCountDelta }, items);
    const first = Iterable.slice(items, selectedIndex);
    const second = Iterable.slice(items, 0, selectedIndex);
    let resolveCount = 5;
    for (const item of Iterable.concat(first, second)) {
      if (item.score === FuzzyScore.Default) {
        continue;
      }
      const range = new $9C(
        item.editStart.lineNumber,
        item.editStart.column,
        item.editInsertEnd.lineNumber,
        item.editInsertEnd.column + this.completionModel.lineContext.characterCountDelta
        // end PLUS character delta
      );
      const insertText = item.completion.insertTextRules && item.completion.insertTextRules & 4 ? { snippet: item.completion.insertText } : item.completion.insertText;
      result.push(new SuggestInlineCompletion(range, insertText, item.filterTextLow ?? item.labelLow, item.completion.additionalTextEdits, item.completion.command, item));
      if (resolveCount-- >= 0) {
        item.resolve(CancellationToken.None);
      }
    }
    return result;
  }
};
InlineCompletionResults = __decorate([
  __param(5, $_cb)
], InlineCompletionResults);
var $Dkb = class $Dkb2 extends $3c {
  constructor(b, c, f, g) {
    super();
    this.b = b;
    this.c = c;
    this.f = f;
    this.g = g;
    this.q.add(b.inlineCompletionsProvider.register("*", this));
  }
  async provideInlineCompletions(model, position, context, token) {
    if (context.selectedSuggestionInfo) {
      return;
    }
    let editor;
    for (const candidate of this.g.listCodeEditors()) {
      if (candidate.getModel() === model) {
        editor = candidate;
        break;
      }
    }
    if (!editor) {
      return;
    }
    const config = editor.getOption(
      94
      /* EditorOption.quickSuggestions */
    );
    if ($jcb.isAllOff(config)) {
      return;
    }
    model.tokenization.tokenizeIfCheap(position.lineNumber);
    const lineTokens = model.tokenization.getLineTokens(position.lineNumber);
    const tokenType = lineTokens.getStandardTokenType(lineTokens.findTokenIndexAtOffset(Math.max(position.column - 1 - 1, 0)));
    if ($jcb.valueFor(config, tokenType) !== "inline") {
      return void 0;
    }
    let wordInfo = model.getWordAtPosition(position);
    let triggerCharacterInfo;
    if (!wordInfo?.word) {
      triggerCharacterInfo = this.h(model, position);
    }
    if (!wordInfo?.word && !triggerCharacterInfo) {
      return;
    }
    if (!wordInfo) {
      wordInfo = model.getWordUntilPosition(position);
    }
    if (wordInfo.endColumn !== position.column) {
      return;
    }
    let result;
    const leadingLineContents = model.getValueInRange(new $9C(position.lineNumber, 1, position.lineNumber, position.column));
    if (!triggerCharacterInfo && this.a?.canBeReused(model, position.lineNumber, wordInfo)) {
      const newLineContext = new $mcb(leadingLineContents, position.column - this.a.word.endColumn);
      this.a.completionModel.lineContext = newLineContext;
      this.a.acquire();
      result = this.a;
    } else {
      const completions = await $gcb(this.b.completionProvider, model, position, new $ccb(void 0, $qcb.createSuggestFilter(editor).itemKind, triggerCharacterInfo?.providers), triggerCharacterInfo && { triggerKind: 1, triggerCharacter: triggerCharacterInfo.ch }, token);
      let clipboardText;
      if (completions.needsClipboard) {
        clipboardText = await this.c.readText();
      }
      const completionModel = new $ncb(completions.items, position.column, new $mcb(leadingLineContents, 0), $lcb.None, editor.getOption(
        123
        /* EditorOption.suggest */
      ), editor.getOption(
        117
        /* EditorOption.snippetSuggestions */
      ), { boostFullMatch: false, firstMatchCanBeWeak: false }, clipboardText);
      result = new InlineCompletionResults(model, position.lineNumber, wordInfo, completionModel, completions, this.f);
    }
    this.a = result;
    return result;
  }
  handleItemDidShow(_completions, item) {
    item.completion.resolve(CancellationToken.None);
  }
  freeInlineCompletions(result) {
    result.release();
  }
  h(model, position) {
    const ch = model.getValueInRange($9C.fromPositions({ lineNumber: position.lineNumber, column: position.column - 1 }, position));
    const providers2 = /* @__PURE__ */ new Set();
    for (const provider of this.b.completionProvider.all(model)) {
      if (provider.triggerCharacters?.includes(ch)) {
        providers2.add(provider);
      }
    }
    if (providers2.size === 0) {
      return void 0;
    }
    return { providers: providers2, ch };
  }
};
$Dkb = __decorate([
  __param(0, $mP),
  __param(1, $30),
  __param(2, $_cb),
  __param(3, $U5)
], $Dkb);
$T_($Dkb);

// out-build/vs/editor/contrib/tokenization/browser/tokenization.js
var ForceRetokenizeAction = class extends $Z5 {
  constructor() {
    super({
      id: "editor.action.forceRetokenize",
      label: localize2(1568, "Developer: Force Retokenize"),
      precondition: void 0
    });
  }
  run(accessor, editor) {
    if (!editor.hasModel()) {
      return;
    }
    const model = editor.getModel();
    model.tokenization.resetTokenization();
    const sw = new $te();
    model.tokenization.forceTokenization(model.getLineCount());
    sw.stop();
    console.log(`tokenization took ${sw.elapsed()}`);
  }
};
$55(ForceRetokenizeAction);

// out-build/vs/editor/contrib/toggleTabFocusMode/browser/toggleTabFocusMode.js
var $Ekb = class _$Ekb extends $gJ {
  static {
    this.ID = "editor.action.toggleTabFocusMode";
  }
  constructor() {
    super({
      id: _$Ekb.ID,
      title: localize2(1566, "Toggle Tab Key Moves Focus"),
      precondition: void 0,
      keybinding: {
        primary: 2048 | 43,
        mac: {
          primary: 256 | 1024 | 43
          /* KeyCode.KeyM */
        },
        weight: 100
        /* KeybindingWeight.EditorContrib */
      },
      metadata: {
        description: localize2(1567, "Determines whether the tab key moves focus around the workbench or inserts the tab character in the current editor. This is also called tab trapping, tab navigation, or tab focus mode.")
      },
      f1: true
    });
  }
  run() {
    const oldValue = $94.getTabFocusMode();
    const newValue = !oldValue;
    $94.setTabFocusMode(newValue);
    if (newValue) {
      $$Z(localize(1564, null));
    } else {
      $$Z(localize(1565, null));
    }
  }
};
$hJ($Ekb);

// out-build/vs/editor/common/services/unicodeTextModelHighlighter.js
var $99 = class {
  static computeUnicodeHighlights(model, options3, range) {
    const startLine = range ? range.startLineNumber : 1;
    const endLine = range ? range.endLineNumber : model.getLineCount();
    const codePointHighlighter = new CodePointHighlighter(options3);
    const candidates = codePointHighlighter.getCandidateCodePoints();
    let regex;
    if (candidates === "allNonBasicAscii") {
      regex = new RegExp("[^\\t\\n\\r\\x20-\\x7E]", "g");
    } else {
      regex = new RegExp(`${buildRegExpCharClassExpr(Array.from(candidates))}`, "g");
    }
    const searcher = new $kI(null, regex);
    const ranges = [];
    let hasMore = false;
    let m;
    let ambiguousCharacterCount = 0;
    let invisibleCharacterCount = 0;
    let nonBasicAsciiCharacterCount = 0;
    forLoop: for (let lineNumber = startLine, lineCount = endLine; lineNumber <= lineCount; lineNumber++) {
      const lineContent = model.getLineContent(lineNumber);
      const lineLength = lineContent.length;
      searcher.reset(0);
      do {
        m = searcher.next(lineContent);
        if (m) {
          let startIndex = m.index;
          let endIndex = m.index + m[0].length;
          if (startIndex > 0) {
            const charCodeBefore = lineContent.charCodeAt(startIndex - 1);
            if ($5f(charCodeBefore)) {
              startIndex--;
            }
          }
          if (endIndex + 1 < lineLength) {
            const charCodeBefore = lineContent.charCodeAt(endIndex - 1);
            if ($5f(charCodeBefore)) {
              endIndex++;
            }
          }
          const str = lineContent.substring(startIndex, endIndex);
          let word = $MD(startIndex + 1, $JD, lineContent, 0);
          if (word && word.endColumn <= startIndex + 1) {
            word = null;
          }
          const highlightReason = codePointHighlighter.shouldHighlightNonBasicASCII(str, word ? word.word : null);
          if (highlightReason !== 0) {
            if (highlightReason === 3) {
              ambiguousCharacterCount++;
            } else if (highlightReason === 2) {
              invisibleCharacterCount++;
            } else if (highlightReason === 1) {
              nonBasicAsciiCharacterCount++;
            } else {
              $hd(highlightReason);
            }
            const MAX_RESULT_LENGTH = 1e3;
            if (ranges.length >= MAX_RESULT_LENGTH) {
              hasMore = true;
              break forLoop;
            }
            ranges.push(new $9C(lineNumber, startIndex + 1, lineNumber, endIndex + 1));
          }
        }
      } while (m);
    }
    return {
      ranges,
      hasMore,
      ambiguousCharacterCount,
      invisibleCharacterCount,
      nonBasicAsciiCharacterCount
    };
  }
  static computeUnicodeHighlightReason(char, options3) {
    const codePointHighlighter = new CodePointHighlighter(options3);
    const reason = codePointHighlighter.shouldHighlightNonBasicASCII(char, null);
    switch (reason) {
      case 0:
        return null;
      case 2:
        return {
          kind: 1
          /* UnicodeHighlighterReasonKind.Invisible */
        };
      case 3: {
        const codePoint = char.codePointAt(0);
        const primaryConfusable = codePointHighlighter.ambiguousCharacters.getPrimaryConfusable(codePoint);
        const notAmbiguousInLocales = $xg.getLocales().filter((l) => !$xg.getInstance(/* @__PURE__ */ new Set([...options3.allowedLocales, l])).isAmbiguous(codePoint));
        return { kind: 0, confusableWith: String.fromCodePoint(primaryConfusable), notAmbiguousInLocales };
      }
      case 1:
        return {
          kind: 2
          /* UnicodeHighlighterReasonKind.NonBasicAscii */
        };
    }
  }
};
function buildRegExpCharClassExpr(codePoints, flags) {
  const src = `[${$Af(codePoints.map((i2) => String.fromCodePoint(i2)).join(""))}]`;
  return src;
}
var UnicodeHighlighterReasonKind;
(function(UnicodeHighlighterReasonKind2) {
  UnicodeHighlighterReasonKind2[UnicodeHighlighterReasonKind2["Ambiguous"] = 0] = "Ambiguous";
  UnicodeHighlighterReasonKind2[UnicodeHighlighterReasonKind2["Invisible"] = 1] = "Invisible";
  UnicodeHighlighterReasonKind2[UnicodeHighlighterReasonKind2["NonBasicAscii"] = 2] = "NonBasicAscii";
})(UnicodeHighlighterReasonKind || (UnicodeHighlighterReasonKind = {}));
var CodePointHighlighter = class {
  constructor(b) {
    this.b = b;
    this.a = new Set(b.allowedCodePoints);
    this.ambiguousCharacters = $xg.getInstance(new Set(b.allowedLocales));
  }
  getCandidateCodePoints() {
    if (this.b.nonBasicASCII) {
      return "allNonBasicAscii";
    }
    const set = /* @__PURE__ */ new Set();
    if (this.b.invisibleCharacters) {
      for (const cp of $yg.codePoints) {
        if (!isAllowedInvisibleCharacter(String.fromCodePoint(cp))) {
          set.add(cp);
        }
      }
    }
    if (this.b.ambiguousCharacters) {
      for (const cp of this.ambiguousCharacters.getConfusableCodePoints()) {
        set.add(cp);
      }
    }
    for (const cp of this.a) {
      set.delete(cp);
    }
    return set;
  }
  shouldHighlightNonBasicASCII(character, wordContext) {
    const codePoint = character.codePointAt(0);
    if (this.a.has(codePoint)) {
      return 0;
    }
    if (this.b.nonBasicASCII) {
      return 1;
    }
    let hasBasicASCIICharacters = false;
    let hasNonConfusableNonBasicAsciiCharacter = false;
    if (wordContext) {
      for (const char of wordContext) {
        const codePoint2 = char.codePointAt(0);
        const isBasicASCII = $dg(char);
        hasBasicASCIICharacters = hasBasicASCIICharacters || isBasicASCII;
        if (!isBasicASCII && !this.ambiguousCharacters.isAmbiguous(codePoint2) && !$yg.isInvisibleCharacter(codePoint2)) {
          hasNonConfusableNonBasicAsciiCharacter = true;
        }
      }
    }
    if (
      /* Don't allow mixing weird looking characters with ASCII */
      !hasBasicASCIICharacters && /* Is there an obviously weird looking character? */
      hasNonConfusableNonBasicAsciiCharacter
    ) {
      return 0;
    }
    if (this.b.invisibleCharacters) {
      if (!isAllowedInvisibleCharacter(character) && $yg.isInvisibleCharacter(codePoint)) {
        return 2;
      }
    }
    if (this.b.ambiguousCharacters) {
      if (this.ambiguousCharacters.isAmbiguous(codePoint)) {
        return 3;
      }
    }
    return 0;
  }
};
function isAllowedInvisibleCharacter(character) {
  return character === " " || character === "\n" || character === "	";
}
var SimpleHighlightReason;
(function(SimpleHighlightReason2) {
  SimpleHighlightReason2[SimpleHighlightReason2["None"] = 0] = "None";
  SimpleHighlightReason2[SimpleHighlightReason2["NonBasicASCII"] = 1] = "NonBasicASCII";
  SimpleHighlightReason2[SimpleHighlightReason2["Invisible"] = 2] = "Invisible";
  SimpleHighlightReason2[SimpleHighlightReason2["Ambiguous"] = 3] = "Ambiguous";
})(SimpleHighlightReason || (SimpleHighlightReason = {}));

// out-build/vs/platform/opener/browser/link.js
var Link2 = class Link3 extends $3c {
  get enabled() {
    return this.f;
  }
  set enabled(enabled) {
    if (enabled) {
      this.a.setAttribute("aria-disabled", "false");
      this.a.tabIndex = 0;
      this.a.style.pointerEvents = "auto";
      this.a.style.opacity = "1";
      this.a.style.cursor = "pointer";
      this.f = false;
    } else {
      this.a.setAttribute("aria-disabled", "true");
      this.a.tabIndex = -1;
      this.a.style.pointerEvents = "none";
      this.a.style.opacity = "0.4";
      this.a.style.cursor = "default";
      this.f = true;
    }
    this.f = enabled;
  }
  set link(link2) {
    if (typeof link2.label === "string") {
      this.a.textContent = link2.label;
    } else {
      $$i(this.a);
      this.a.appendChild(link2.label);
    }
    this.a.href = link2.href;
    if (typeof link2.tabIndex !== "undefined") {
      this.a.tabIndex = link2.tabIndex;
    }
    this.j(link2.title);
    this.g = link2;
  }
  constructor(container2, g, options3 = {}, h3, openerService) {
    super();
    this.g = g;
    this.h = h3;
    this.f = true;
    this.a = $bk(container2, $("a.monaco-link", {
      tabIndex: g.tabIndex ?? 0,
      href: g.href
    }, g.label));
    this.c = options3.hoverDelegate ?? $JZ("mouse");
    this.j(g.title);
    this.a.setAttribute("role", "button");
    const onClickEmitter = this.B(new $9Z(this.a, "click"));
    const onKeyPress = this.B(new $9Z(this.a, "keypress"));
    const onEnterPress = Event2.chain(onKeyPress.event, ($149) => $149.map((e) => new $if(e)).filter(
      (e) => e.keyCode === 3
      /* KeyCode.Enter */
    ));
    const onTap = this.B(new $9Z(this.a, EventType.Tap)).event;
    this.B($mZ.addTarget(this.a));
    const onOpen = Event2.any(onClickEmitter.event, onEnterPress, onTap);
    this.B(onOpen((e) => {
      if (!this.enabled) {
        return;
      }
      $9j.stop(e, true);
      if (options3?.opener) {
        options3.opener(this.g.href);
      } else {
        openerService.open(this.g.href, { allowCommands: true });
      }
    }));
    this.enabled = true;
  }
  j(title) {
    if (this.c.showNativeHover) {
      this.a.title = title ?? "";
    } else if (!this.b && title) {
      this.b = this.B(this.h.setupManagedHover(this.c, this.a, title));
    } else if (this.b) {
      this.b.update(title);
    }
  }
};
Link2 = __decorate([
  __param(3, $5$),
  __param(4, $O4)
], Link2);

// out-build/vs/editor/contrib/unicodeHighlighter/browser/bannerController.js
var BANNER_ELEMENT_HEIGHT = 26;
var $Gkb = class $Gkb2 extends $3c {
  constructor(b, c) {
    super();
    this.b = b;
    this.c = c;
    this.a = this.B(this.c.createInstance(Banner));
  }
  hide() {
    this.b.setBanner(null, 0);
    this.a.clear();
  }
  show(item) {
    this.a.show({
      ...item,
      onClose: () => {
        this.hide();
        item.onClose?.();
      }
    });
    this.b.setBanner(this.a.element, BANNER_ELEMENT_HEIGHT);
  }
};
$Gkb = __decorate([
  __param(1, $Pk)
], $Gkb);
var Banner = class Banner2 extends $3c {
  constructor(f) {
    super();
    this.f = f;
    this.a = this.f.createInstance($Q_, {});
    this.element = $("div.editor-banner");
    this.element.tabIndex = 0;
  }
  g(item) {
    if (item.ariaLabel) {
      return item.ariaLabel;
    }
    if (typeof item.message === "string") {
      return item.message;
    }
    return void 0;
  }
  h(message) {
    if (typeof message === "string") {
      const element = $("span");
      element.innerText = message;
      return element;
    }
    return this.a.render(message).element;
  }
  clear() {
    $$i(this.element);
  }
  show(item) {
    $$i(this.element);
    const ariaLabel = this.g(item);
    if (ariaLabel) {
      this.element.setAttribute("aria-label", ariaLabel);
    }
    const iconContainer = $bk(this.element, $("div.icon-container"));
    iconContainer.setAttribute("aria-hidden", "true");
    if (item.icon) {
      iconContainer.appendChild($(`div${ThemeIcon.asCSSSelector(item.icon)}`));
    }
    const messageContainer = $bk(this.element, $("div.message-container"));
    messageContainer.setAttribute("aria-hidden", "true");
    messageContainer.appendChild(this.h(item.message));
    this.b = $bk(this.element, $("div.message-actions-container"));
    if (item.actions) {
      for (const action of item.actions) {
        this.B(this.f.createInstance(Link2, this.b, { ...action, tabIndex: -1 }, {}));
      }
    }
    const actionBarContainer = $bk(this.element, $("div.action-container"));
    this.c = this.B(new $LZ(actionBarContainer));
    this.c.push(this.B(new $Um("banner.close", "Close Banner", ThemeIcon.asClassName($_r), true, () => {
      if (typeof item.onClose === "function") {
        item.onClose();
      }
    })), { icon: true, label: false });
    this.c.setFocusable(false);
  }
};
Banner = __decorate([
  __param(0, $Pk)
], Banner);

// out-build/vs/platform/workspace/common/workspaceTrust.js
var WorkspaceTrustScope;
(function(WorkspaceTrustScope2) {
  WorkspaceTrustScope2[WorkspaceTrustScope2["Local"] = 0] = "Local";
  WorkspaceTrustScope2[WorkspaceTrustScope2["Remote"] = 1] = "Remote";
})(WorkspaceTrustScope || (WorkspaceTrustScope = {}));
var $3M = $Qk("workspaceTrustEnablementService");
var $4M = $Qk("workspaceTrustManagementService");
var WorkspaceTrustUriResponse;
(function(WorkspaceTrustUriResponse2) {
  WorkspaceTrustUriResponse2[WorkspaceTrustUriResponse2["Open"] = 1] = "Open";
  WorkspaceTrustUriResponse2[WorkspaceTrustUriResponse2["OpenInNewWindow"] = 2] = "OpenInNewWindow";
  WorkspaceTrustUriResponse2[WorkspaceTrustUriResponse2["Cancel"] = 3] = "Cancel";
})(WorkspaceTrustUriResponse || (WorkspaceTrustUriResponse = {}));
var $5M = $Qk("workspaceTrustRequestService");

// out-build/vs/editor/contrib/unicodeHighlighter/browser/unicodeHighlighter.js
var $Hkb = $9r("extensions-warning-message", $6l.warning, localize(1569, null));
var $Ikb = class $Ikb2 extends $3c {
  static {
    this.ID = "editor.contrib.unicodeHighlighter";
  }
  constructor(h3, j, m, instantiationService) {
    super();
    this.h = h3;
    this.j = j;
    this.m = m;
    this.a = null;
    this.g = false;
    this.n = (state) => {
      if (state && state.hasMore) {
        if (this.g) {
          return;
        }
        const max = Math.max(state.ambiguousCharacterCount, state.nonBasicAsciiCharacterCount, state.invisibleCharacterCount);
        let data;
        if (state.nonBasicAsciiCharacterCount >= max) {
          data = {
            message: localize(1570, null),
            command: new $Pkb()
          };
        } else if (state.ambiguousCharacterCount >= max) {
          data = {
            message: localize(1571, null),
            command: new $Nkb()
          };
        } else if (state.invisibleCharacterCount >= max) {
          data = {
            message: localize(1572, null),
            command: new $Okb()
          };
        } else {
          throw new Error("Unreachable");
        }
        this.f.show({
          id: "unicodeHighlightBanner",
          message: data.message,
          icon: $Hkb,
          actions: [
            {
              label: data.command.shortLabel,
              href: `command:${data.command.id}`
            }
          ],
          onClose: () => {
            this.g = true;
          }
        });
      } else {
        this.f.hide();
      }
    };
    this.f = this.B(instantiationService.createInstance($Gkb, h3));
    this.B(this.h.onDidChangeModel(() => {
      this.g = false;
      this.s();
    }));
    this.b = h3.getOption(
      130
      /* EditorOption.unicodeHighlighting */
    );
    this.B(m.onDidChangeTrust((e) => {
      this.s();
    }));
    this.B(h3.onDidChangeConfiguration((e) => {
      if (e.hasChanged(
        130
        /* EditorOption.unicodeHighlighting */
      )) {
        this.b = h3.getOption(
          130
          /* EditorOption.unicodeHighlighting */
        );
        this.s();
      }
    }));
    this.s();
  }
  dispose() {
    if (this.a) {
      this.a.dispose();
      this.a = null;
    }
    super.dispose();
  }
  s() {
    this.n(null);
    if (this.a) {
      this.a.dispose();
      this.a = null;
    }
    if (!this.h.hasModel()) {
      return;
    }
    const options3 = resolveOptions2(this.m.isWorkspaceTrusted(), this.b);
    if ([
      options3.nonBasicASCII,
      options3.ambiguousCharacters,
      options3.invisibleCharacters
    ].every((option) => option === false)) {
      return;
    }
    const highlightOptions = {
      nonBasicASCII: options3.nonBasicASCII,
      ambiguousCharacters: options3.ambiguousCharacters,
      invisibleCharacters: options3.invisibleCharacters,
      includeComments: options3.includeComments,
      includeStrings: options3.includeStrings,
      allowedCodePoints: Object.keys(options3.allowedCharacters).map((c) => c.codePointAt(0)),
      allowedLocales: Object.keys(options3.allowedLocales).map((locale) => {
        if (locale === "_os") {
          const osLocale = new Intl.NumberFormat().resolvedOptions().locale;
          return osLocale;
        } else if (locale === "_vscode") {
          return $z;
        }
        return locale;
      })
    };
    if (this.j.canComputeUnicodeHighlights(this.h.getModel().uri)) {
      this.a = new DocumentUnicodeHighlighter(this.h, highlightOptions, this.n, this.j);
    } else {
      this.a = new ViewportUnicodeHighlighter(this.h, highlightOptions, this.n);
    }
  }
  getDecorationInfo(decoration3) {
    if (this.a) {
      return this.a.getDecorationInfo(decoration3);
    }
    return null;
  }
};
$Ikb = __decorate([
  __param(1, $I0),
  __param(2, $4M),
  __param(3, $Pk)
], $Ikb);
function resolveOptions2(trusted, options3) {
  return {
    nonBasicASCII: options3.nonBasicASCII === inUntrustedWorkspace ? !trusted : options3.nonBasicASCII,
    ambiguousCharacters: options3.ambiguousCharacters,
    invisibleCharacters: options3.invisibleCharacters,
    includeComments: options3.includeComments === inUntrustedWorkspace ? !trusted : options3.includeComments,
    includeStrings: options3.includeStrings === inUntrustedWorkspace ? !trusted : options3.includeStrings,
    allowedCharacters: options3.allowedCharacters,
    allowedLocales: options3.allowedLocales
  };
}
var DocumentUnicodeHighlighter = class DocumentUnicodeHighlighter2 extends $3c {
  constructor(g, h3, j, m) {
    super();
    this.g = g;
    this.h = h3;
    this.j = j;
    this.m = m;
    this.a = this.g.getModel();
    this.f = this.g.createDecorationsCollection();
    this.b = this.B(new $8h(() => this.n(), 250));
    this.B(this.g.onDidChangeModelContent(() => {
      this.b.schedule();
    }));
    this.b.schedule();
  }
  dispose() {
    this.f.clear();
    super.dispose();
  }
  n() {
    if (this.a.isDisposed()) {
      return;
    }
    if (!this.a.mightContainNonBasicASCII()) {
      this.f.clear();
      return;
    }
    const modelVersionId = this.a.getVersionId();
    this.m.computedUnicodeHighlights(this.a.uri, this.h).then((info) => {
      if (this.a.isDisposed()) {
        return;
      }
      if (this.a.getVersionId() !== modelVersionId) {
        return;
      }
      this.j(info);
      const decorations = [];
      if (!info.hasMore) {
        for (const range of info.ranges) {
          decorations.push({
            range,
            options: Decorations.instance.getDecorationFromOptions(this.h)
          });
        }
      }
      this.f.set(decorations);
    });
  }
  getDecorationInfo(decoration3) {
    if (!this.f.has(decoration3)) {
      return null;
    }
    const model = this.g.getModel();
    if (!$y9(model, decoration3)) {
      return null;
    }
    const text2 = model.getValueInRange(decoration3.range);
    return {
      reason: computeReason(text2, this.h),
      inComment: $z9(model, decoration3),
      inString: $A9(model, decoration3)
    };
  }
};
DocumentUnicodeHighlighter = __decorate([
  __param(3, $I0)
], DocumentUnicodeHighlighter);
var ViewportUnicodeHighlighter = class extends $3c {
  constructor(g, h3, j) {
    super();
    this.g = g;
    this.h = h3;
    this.j = j;
    this.a = this.g.getModel();
    this.f = this.g.createDecorationsCollection();
    this.b = this.B(new $8h(() => this.m(), 250));
    this.B(this.g.onDidLayoutChange(() => {
      this.b.schedule();
    }));
    this.B(this.g.onDidScrollChange(() => {
      this.b.schedule();
    }));
    this.B(this.g.onDidChangeHiddenAreas(() => {
      this.b.schedule();
    }));
    this.B(this.g.onDidChangeModelContent(() => {
      this.b.schedule();
    }));
    this.b.schedule();
  }
  dispose() {
    this.f.clear();
    super.dispose();
  }
  m() {
    if (this.a.isDisposed()) {
      return;
    }
    if (!this.a.mightContainNonBasicASCII()) {
      this.f.clear();
      return;
    }
    const ranges = this.g.getVisibleRanges();
    const decorations = [];
    const totalResult = {
      ranges: [],
      ambiguousCharacterCount: 0,
      invisibleCharacterCount: 0,
      nonBasicAsciiCharacterCount: 0,
      hasMore: false
    };
    for (const range of ranges) {
      const result = $99.computeUnicodeHighlights(this.a, this.h, range);
      for (const r2 of result.ranges) {
        totalResult.ranges.push(r2);
      }
      totalResult.ambiguousCharacterCount += totalResult.ambiguousCharacterCount;
      totalResult.invisibleCharacterCount += totalResult.invisibleCharacterCount;
      totalResult.nonBasicAsciiCharacterCount += totalResult.nonBasicAsciiCharacterCount;
      totalResult.hasMore = totalResult.hasMore || result.hasMore;
    }
    if (!totalResult.hasMore) {
      for (const range of totalResult.ranges) {
        decorations.push({ range, options: Decorations.instance.getDecorationFromOptions(this.h) });
      }
    }
    this.j(totalResult);
    this.f.set(decorations);
  }
  getDecorationInfo(decoration3) {
    if (!this.f.has(decoration3)) {
      return null;
    }
    const model = this.g.getModel();
    const text2 = model.getValueInRange(decoration3.range);
    if (!$y9(model, decoration3)) {
      return null;
    }
    return {
      reason: computeReason(text2, this.h),
      inComment: $z9(model, decoration3),
      inString: $A9(model, decoration3)
    };
  }
};
var configureUnicodeHighlightOptionsStr = localize(1573, null);
var $Kkb = class $Kkb2 {
  constructor(a, b, f) {
    this.a = a;
    this.b = b;
    this.f = f;
    this.hoverOrdinal = 5;
  }
  computeSync(anchor, lineDecorations) {
    if (!this.a.hasModel() || anchor.type !== 1) {
      return [];
    }
    const model = this.a.getModel();
    const unicodeHighlighter = this.a.getContribution($Ikb.ID);
    if (!unicodeHighlighter) {
      return [];
    }
    const result = [];
    const existedReason = /* @__PURE__ */ new Set();
    let index = 300;
    for (const d of lineDecorations) {
      const highlightInfo = unicodeHighlighter.getDecorationInfo(d);
      if (!highlightInfo) {
        continue;
      }
      const char = model.getValueInRange(d.range);
      const codePoint = char.codePointAt(0);
      const codePointStr = formatCodePointMarkdown(codePoint);
      let reason;
      switch (highlightInfo.reason.kind) {
        case 0: {
          if ($dg(highlightInfo.reason.confusableWith)) {
            reason = localize(1574, null, codePointStr, formatCodePointMarkdown(highlightInfo.reason.confusableWith.codePointAt(0)));
          } else {
            reason = localize(1575, null, codePointStr, formatCodePointMarkdown(highlightInfo.reason.confusableWith.codePointAt(0)));
          }
          break;
        }
        case 1:
          reason = localize(1576, null, codePointStr);
          break;
        case 2:
          reason = localize(1577, null, codePointStr);
          break;
      }
      if (existedReason.has(reason)) {
        continue;
      }
      existedReason.add(reason);
      const adjustSettingsArgs = {
        codePoint,
        reason: highlightInfo.reason,
        inComment: highlightInfo.inComment,
        inString: highlightInfo.inString
      };
      const adjustSettings = localize(1578, null);
      const uri = `command:${$Qkb.ID}?${encodeURIComponent(JSON.stringify(adjustSettingsArgs))}`;
      const markdown = new $bm("", true).appendMarkdown(reason).appendText(" ").appendLink(uri, adjustSettings, configureUnicodeHighlightOptionsStr);
      result.push(new $Jdb(this, d.range, [markdown], false, index++));
    }
    return result;
  }
  renderHoverParts(context, hoverParts) {
    return $Ldb(context, hoverParts, this.a, this.b, this.f);
  }
  getAccessibleContent(hoverPart) {
    return hoverPart.contents.map((c) => c.value).join("\n");
  }
};
$Kkb = __decorate([
  __param(1, $1E),
  __param(2, $O4)
], $Kkb);
function codePointToHex(codePoint) {
  return `U+${codePoint.toString(16).padStart(4, "0")}`;
}
function formatCodePointMarkdown(codePoint) {
  let value = `\`${codePointToHex(codePoint)}\``;
  if (!$yg.isInvisibleCharacter(codePoint)) {
    value += ` "${`${renderCodePointAsInlineCode(codePoint)}`}"`;
  }
  return value;
}
function renderCodePointAsInlineCode(codePoint) {
  if (codePoint === 96) {
    return "`` ` ``";
  }
  return "`" + String.fromCodePoint(codePoint) + "`";
}
function computeReason(char, options3) {
  return $99.computeUnicodeHighlightReason(char, options3);
}
var Decorations = class _Decorations {
  constructor() {
    this.a = /* @__PURE__ */ new Map();
  }
  static {
    this.instance = new _Decorations();
  }
  getDecorationFromOptions(options3) {
    return this.b(!options3.includeComments, !options3.includeStrings);
  }
  b(hideInComments, hideInStrings) {
    const key2 = `${hideInComments}${hideInStrings}`;
    let options3 = this.a.get(key2);
    if (!options3) {
      options3 = $WI.createDynamic({
        description: "unicode-highlight",
        stickiness: 1,
        className: "unicode-highlight",
        showIfCollapsed: true,
        overviewRuler: null,
        minimap: null,
        hideInCommentTokens: hideInComments,
        hideInStringTokens: hideInStrings
      });
      this.a.set(key2, options3);
    }
    return options3;
  }
};
var $Lkb = class extends $Z5 {
  static {
    this.ID = "editor.action.unicodeHighlight.disableHighlightingInComments";
  }
  constructor() {
    super({
      id: $Nkb.ID,
      label: localize2(1587, "Disable highlighting of characters in comments"),
      precondition: void 0
    });
    this.shortLabel = localize(1579, null);
  }
  async run(accessor, editor, args2) {
    const configurationService = accessor?.get($kl);
    if (configurationService) {
      this.runAction(configurationService);
    }
  }
  async runAction(configurationService) {
    await configurationService.updateValue(
      unicodeHighlightConfigKeys.includeComments,
      false,
      2
      /* ConfigurationTarget.USER */
    );
  }
};
var $Mkb = class extends $Z5 {
  static {
    this.ID = "editor.action.unicodeHighlight.disableHighlightingInStrings";
  }
  constructor() {
    super({
      id: $Nkb.ID,
      label: localize2(1588, "Disable highlighting of characters in strings"),
      precondition: void 0
    });
    this.shortLabel = localize(1580, null);
  }
  async run(accessor, editor, args2) {
    const configurationService = accessor?.get($kl);
    if (configurationService) {
      this.runAction(configurationService);
    }
  }
  async runAction(configurationService) {
    await configurationService.updateValue(
      unicodeHighlightConfigKeys.includeStrings,
      false,
      2
      /* ConfigurationTarget.USER */
    );
  }
};
var $Nkb = class _$Nkb extends $Z5 {
  static {
    this.ID = "editor.action.unicodeHighlight.disableHighlightingOfAmbiguousCharacters";
  }
  constructor() {
    super({
      id: _$Nkb.ID,
      label: localize2(1589, "Disable highlighting of ambiguous characters"),
      precondition: void 0
    });
    this.shortLabel = localize(1581, null);
  }
  async run(accessor, editor, args2) {
    const configurationService = accessor?.get($kl);
    if (configurationService) {
      this.runAction(configurationService);
    }
  }
  async runAction(configurationService) {
    await configurationService.updateValue(
      unicodeHighlightConfigKeys.ambiguousCharacters,
      false,
      2
      /* ConfigurationTarget.USER */
    );
  }
};
var $Okb = class _$Okb extends $Z5 {
  static {
    this.ID = "editor.action.unicodeHighlight.disableHighlightingOfInvisibleCharacters";
  }
  constructor() {
    super({
      id: _$Okb.ID,
      label: localize2(1590, "Disable highlighting of invisible characters"),
      precondition: void 0
    });
    this.shortLabel = localize(1582, null);
  }
  async run(accessor, editor, args2) {
    const configurationService = accessor?.get($kl);
    if (configurationService) {
      this.runAction(configurationService);
    }
  }
  async runAction(configurationService) {
    await configurationService.updateValue(
      unicodeHighlightConfigKeys.invisibleCharacters,
      false,
      2
      /* ConfigurationTarget.USER */
    );
  }
};
var $Pkb = class _$Pkb extends $Z5 {
  static {
    this.ID = "editor.action.unicodeHighlight.disableHighlightingOfNonBasicAsciiCharacters";
  }
  constructor() {
    super({
      id: _$Pkb.ID,
      label: localize2(1591, "Disable highlighting of non basic ASCII characters"),
      precondition: void 0
    });
    this.shortLabel = localize(1583, null);
  }
  async run(accessor, editor, args2) {
    const configurationService = accessor?.get($kl);
    if (configurationService) {
      this.runAction(configurationService);
    }
  }
  async runAction(configurationService) {
    await configurationService.updateValue(
      unicodeHighlightConfigKeys.nonBasicASCII,
      false,
      2
      /* ConfigurationTarget.USER */
    );
  }
};
var $Qkb = class _$Qkb extends $Z5 {
  static {
    this.ID = "editor.action.unicodeHighlight.showExcludeOptions";
  }
  constructor() {
    super({
      id: _$Qkb.ID,
      label: localize2(1592, "Show Exclude Options"),
      precondition: void 0
    });
  }
  async run(accessor, editor, args2) {
    const { codePoint, reason, inString, inComment } = args2;
    const char = String.fromCodePoint(codePoint);
    const quickPickService = accessor.get($1M);
    const configurationService = accessor.get($kl);
    function getExcludeCharFromBeingHighlightedLabel(codePoint2) {
      if ($yg.isInvisibleCharacter(codePoint2)) {
        return localize(1584, null, codePointToHex(codePoint2));
      }
      return localize(1585, null, `${codePointToHex(codePoint2)} "${char}"`);
    }
    const options3 = [];
    if (reason.kind === 0) {
      for (const locale of reason.notAmbiguousInLocales) {
        options3.push({
          label: localize(1586, null, locale),
          run: async () => {
            excludeLocaleFromBeingHighlighted(configurationService, [locale]);
          }
        });
      }
    }
    options3.push({
      label: getExcludeCharFromBeingHighlightedLabel(codePoint),
      run: () => excludeCharFromBeingHighlighted(configurationService, [codePoint])
    });
    if (inComment) {
      const action = new $Lkb();
      options3.push({ label: action.label, run: async () => action.runAction(configurationService) });
    } else if (inString) {
      const action = new $Mkb();
      options3.push({ label: action.label, run: async () => action.runAction(configurationService) });
    }
    if (reason.kind === 0) {
      const action = new $Nkb();
      options3.push({ label: action.label, run: async () => action.runAction(configurationService) });
    } else if (reason.kind === 1) {
      const action = new $Okb();
      options3.push({ label: action.label, run: async () => action.runAction(configurationService) });
    } else if (reason.kind === 2) {
      const action = new $Pkb();
      options3.push({ label: action.label, run: async () => action.runAction(configurationService) });
    } else {
      expectNever(reason);
    }
    const result = await quickPickService.pick(options3, { title: configureUnicodeHighlightOptionsStr });
    if (result) {
      await result.run();
    }
  }
};
async function excludeCharFromBeingHighlighted(configurationService, charCodes) {
  const existingValue = configurationService.getValue(unicodeHighlightConfigKeys.allowedCharacters);
  let value;
  if (typeof existingValue === "object" && existingValue) {
    value = existingValue;
  } else {
    value = {};
  }
  for (const charCode of charCodes) {
    value[String.fromCodePoint(charCode)] = true;
  }
  await configurationService.updateValue(
    unicodeHighlightConfigKeys.allowedCharacters,
    value,
    2
    /* ConfigurationTarget.USER */
  );
}
async function excludeLocaleFromBeingHighlighted(configurationService, locales) {
  const existingValue = configurationService.inspect(unicodeHighlightConfigKeys.allowedLocales).user?.value;
  let value;
  if (typeof existingValue === "object" && existingValue) {
    value = Object.assign({}, existingValue);
  } else {
    value = {};
  }
  for (const locale of locales) {
    value[locale] = true;
  }
  await configurationService.updateValue(
    unicodeHighlightConfigKeys.allowedLocales,
    value,
    2
    /* ConfigurationTarget.USER */
  );
}
function expectNever(value) {
  throw new Error(`Unexpected value: ${value}`);
}
$55($Nkb);
$55($Okb);
$55($Pkb);
$55($Qkb);
$85(
  $Ikb.ID,
  $Ikb,
  1
  /* EditorContributionInstantiation.AfterFirstRender */
);
$Bbb.register($Kkb);

// out-build/vs/editor/contrib/unusualLineTerminators/browser/unusualLineTerminators.js
var ignoreUnusualLineTerminators = "ignoreUnusualLineTerminators";
function writeIgnoreState(codeEditorService, model, state) {
  codeEditorService.setModelProperty(model.uri, ignoreUnusualLineTerminators, state);
}
function readIgnoreState(codeEditorService, model) {
  return codeEditorService.getModelProperty(model.uri, ignoreUnusualLineTerminators);
}
var $Rkb = class $Rkb2 extends $3c {
  static {
    this.ID = "editor.contrib.unusualLineTerminatorsDetector";
  }
  constructor(c, f, g) {
    super();
    this.c = c;
    this.f = f;
    this.g = g;
    this.b = false;
    this.a = this.c.getOption(
      131
      /* EditorOption.unusualLineTerminators */
    );
    this.B(this.c.onDidChangeConfiguration((e) => {
      if (e.hasChanged(
        131
        /* EditorOption.unusualLineTerminators */
      )) {
        this.a = this.c.getOption(
          131
          /* EditorOption.unusualLineTerminators */
        );
        this.h();
      }
    }));
    this.B(this.c.onDidChangeModel(() => {
      this.h();
    }));
    this.B(this.c.onDidChangeModelContent((e) => {
      if (e.isUndoing) {
        return;
      }
      this.h();
    }));
    this.h();
  }
  async h() {
    if (this.a === "off") {
      return;
    }
    if (!this.c.hasModel()) {
      return;
    }
    const model = this.c.getModel();
    if (!model.mightContainUnusualLineTerminators()) {
      return;
    }
    const ignoreState = readIgnoreState(this.g, model);
    if (ignoreState === true) {
      return;
    }
    if (this.c.getOption(
      96
      /* EditorOption.readOnly */
    )) {
      return;
    }
    if (this.a === "auto") {
      model.removeUnusualLineTerminators(this.c.getSelections());
      return;
    }
    if (this.b) {
      return;
    }
    let result;
    try {
      this.b = true;
      result = await this.f.confirm({
        title: localize(1593, null),
        message: localize(1594, null),
        detail: localize(1595, null, $sh(model.uri)),
        primaryButton: localize(1596, null),
        cancelButton: localize(1597, null)
      });
    } finally {
      this.b = false;
    }
    if (!result.confirmed) {
      writeIgnoreState(this.g, model, true);
      return;
    }
    model.removeUnusualLineTerminators(this.c.getSelections());
  }
};
$Rkb = __decorate([
  __param(1, $Yv),
  __param(2, $U5)
], $Rkb);
$85(
  $Rkb.ID,
  $Rkb,
  1
  /* EditorContributionInstantiation.AfterFirstRender */
);

// out-build/vs/base/common/glob.js
function $yl() {
  return /* @__PURE__ */ Object.create(null);
}
var $zl = "**";
var $Al = "/";
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 $Bl(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 = $Bl(pattern, $Al);
  if (segments.every((segment) => segment === $zl)) {
    regEx = ".*";
  } else {
    let previousSegmentWasGlobStar = false;
    segments.forEach((segment, index) => {
      if (segment === $zl) {
        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 === $Al) {
              res = "";
            } else {
              res = $Af(char);
            }
            bracketVal += res;
            continue;
          }
          switch (char) {
            case "{":
              inBraces = true;
              continue;
            case "[":
              inBrackets = true;
              continue;
            case "}": {
              const choices = $Bl(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] !== $zl || // next segment is not **, or...
        index + 2 < segments.length)) {
          regEx += PATH_REGEX;
        }
      }
      previousSegmentWasGlobStar = segment === $zl;
    });
  }
  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 $Hc(1e4);
var FALSE = function() {
  return false;
};
var NULL = function() {
  return null;
};
function parsePattern(arg1, options3) {
  if (!arg1) {
    return NULL;
  }
  let pattern;
  if (typeof arg1 !== "string") {
    pattern = arg1.pattern;
  } else {
    pattern = arg1;
  }
  pattern = pattern.trim();
  const patternKey = `${pattern}_${!!options3.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, options3))) {
    parsedPattern = trivia2(match[1], pattern);
  } else if ((options3.trimForExclusions ? T3_2 : T3).test(pattern)) {
    parsedPattern = trivia3(pattern, options3);
  } else if (match = T4.exec(trimForExclusions(pattern, options3))) {
    parsedPattern = trivia4and5(match[1].substr(1), pattern, true);
  } else if (match = T5.exec(trimForExclusions(pattern, options3))) {
    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(path, basename) {
    if (!$Zg(path, arg2.base, !$n)) {
      return null;
    }
    return parsedPattern($Ff(path.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, options3) {
  return options3.trimForExclusions && pattern.endsWith("/**") ? pattern.substr(0, pattern.length - 2) : pattern;
}
function trivia1(base, pattern) {
  return function(path, basename) {
    return typeof path === "string" && path.endsWith(base) ? pattern : null;
  };
}
function trivia2(base, pattern) {
  const slashBase = `/${base}`;
  const backslashBase = `\\${base}`;
  const parsedPattern = function(path, basename) {
    if (typeof path !== "string") {
      return null;
    }
    if (basename) {
      return basename === base ? pattern : null;
    }
    return path === base || path.endsWith(slashBase) || path.endsWith(backslashBase) ? pattern : null;
  };
  const basenames = [base];
  parsedPattern.basenames = basenames;
  parsedPattern.patterns = [pattern];
  parsedPattern.allBasenames = basenames;
  return parsedPattern;
}
function trivia3(pattern, options3) {
  const parsedPatterns = aggregateBasenameMatches(pattern.slice(1, -1).split(",").map((pattern2) => parsePattern(pattern2, options3)).filter((pattern2) => pattern2 !== NULL), pattern);
  const patternsLength = parsedPatterns.length;
  if (!patternsLength) {
    return NULL;
  }
  if (patternsLength === 1) {
    return parsedPatterns[0];
  }
  const parsedPattern = function(path, basename) {
    for (let i2 = 0, n = parsedPatterns.length; i2 < n; i2++) {
      if (parsedPatterns[i2](path, 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 === $kc.sep;
  const nativePath = usingPosixSep ? targetPath : targetPath.replace(ALL_FORWARD_SLASHES, sep);
  const nativePathEnd = sep + nativePath;
  const targetPathEnd = $kc.sep + targetPath;
  let parsedPattern;
  if (matchPathEnds) {
    parsedPattern = function(path, basename) {
      return typeof path === "string" && (path === nativePath || path.endsWith(nativePathEnd) || !usingPosixSep && (path === targetPath || path.endsWith(targetPathEnd))) ? pattern : null;
    };
  } else {
    parsedPattern = function(path, basename) {
      return typeof path === "string" && (path === nativePath || !usingPosixSep && path === targetPath) ? pattern : null;
    };
  }
  parsedPattern.allPaths = [(matchPathEnds ? "*/" : "./") + targetPath];
  return parsedPattern;
}
function toRegExp(pattern) {
  try {
    const regExp = new RegExp(`^${parseRegExp(pattern)}$`);
    return function(path) {
      regExp.lastIndex = 0;
      return typeof path === "string" && regExp.test(path) ? pattern : null;
    };
  } catch (error) {
    return NULL;
  }
}
function $Cl(arg1, path, hasSibling) {
  if (!arg1 || typeof path !== "string") {
    return false;
  }
  return $Dl(arg1)(path, void 0, hasSibling);
}
function $Dl(arg1, options3 = {}) {
  if (!arg1) {
    return FALSE;
  }
  if (typeof arg1 === "string" || $El(arg1)) {
    const parsedPattern = parsePattern(arg1, options3);
    if (parsedPattern === NULL) {
      return FALSE;
    }
    const resultPattern = function(path, basename) {
      return !!parsedPattern(path, basename);
    };
    if (parsedPattern.allBasenames) {
      resultPattern.allBasenames = parsedPattern.allBasenames;
    }
    if (parsedPattern.allPaths) {
      resultPattern.allPaths = parsedPattern.allPaths;
    }
    return resultPattern;
  }
  return parsedExpression(arg1, options3);
}
function $El(obj) {
  const rp = obj;
  if (!rp) {
    return false;
  }
  return typeof rp.base === "string" && typeof rp.pattern === "string";
}
function parsedExpression(expression, options3) {
  const parsedPatterns = aggregateBasenameMatches(Object.getOwnPropertyNames(expression).map((pattern) => parseExpressionPattern(pattern, expression[pattern], options3)).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(path, basename) {
      let resultPromises = void 0;
      for (let i2 = 0, n = parsedPatterns.length; i2 < n; i2++) {
        const result = parsedPatterns[i2](path, basename);
        if (typeof result === "string") {
          return result;
        }
        if ($Gh(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(path, base, hasSibling) {
    let name = void 0;
    let resultPromises = void 0;
    for (let i2 = 0, n = parsedPatterns.length; i2 < n; i2++) {
      const parsedPattern = parsedPatterns[i2];
      if (parsedPattern.requiresSiblings && hasSibling) {
        if (!base) {
          base = $rc(path);
        }
        if (!name) {
          name = base.substr(0, base.length - $sc(path).length);
        }
      }
      const result = parsedPattern(path, base, name, hasSibling);
      if (typeof result === "string") {
        return result;
      }
      if ($Gh(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, options3) {
  if (value === false) {
    return NULL;
  }
  const parsedPattern = parsePattern(pattern, options3);
  if (parsedPattern === NULL) {
    return NULL;
  }
  if (typeof value === "boolean") {
    return parsedPattern;
  }
  if (value) {
    const when = value.when;
    if (typeof when === "string") {
      const result = (path, basename, name, hasSibling) => {
        if (!hasSibling || !parsedPattern(path, basename)) {
          return null;
        }
        const clausePattern = when.replace("$(basename)", () => name);
        const matched = hasSibling(clausePattern);
        return $Gh(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 i2 = 0, n = basenames.length; i2 < n; i2++) {
      patterns.push(result);
    }
  } else {
    patterns = basenamePatterns.reduce((all, current) => {
      const patterns2 = current.patterns;
      return patterns2 ? all.concat(patterns2) : all;
    }, []);
  }
  const aggregate = function(path, basename) {
    if (typeof path !== "string") {
      return null;
    }
    if (!basename) {
      let i2;
      for (i2 = path.length; i2 > 0; i2--) {
        const ch = path.charCodeAt(i2 - 1);
        if (ch === 47 || ch === 92) {
          break;
        }
      }
      basename = path.substr(i2);
    }
    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;
}

// out-build/vs/editor/common/languageSelector.js
function $qE(selector, candidateUri, candidateLanguage, candidateIsSynchronized, candidateNotebookUri, candidateNotebookType) {
  if (Array.isArray(selector)) {
    let ret = 0;
    for (const filter of selector) {
      const value = $qE(filter, candidateUri, candidateLanguage, candidateIsSynchronized, candidateNotebookUri, candidateNotebookType);
      if (value === 10) {
        return value;
      }
      if (value > ret) {
        ret = value;
      }
    }
    return ret;
  } else if (typeof selector === "string") {
    if (!candidateIsSynchronized) {
      return 0;
    }
    if (selector === "*") {
      return 5;
    } else if (selector === candidateLanguage) {
      return 10;
    } else {
      return 0;
    }
  } else if (selector) {
    const { language, pattern, scheme, hasAccessToAllModels, notebookType } = selector;
    if (!candidateIsSynchronized && !hasAccessToAllModels) {
      return 0;
    }
    if (notebookType && candidateNotebookUri) {
      candidateUri = candidateNotebookUri;
    }
    let ret = 0;
    if (scheme) {
      if (scheme === candidateUri.scheme) {
        ret = 10;
      } else if (scheme === "*") {
        ret = 5;
      } else {
        return 0;
      }
    }
    if (language) {
      if (language === candidateLanguage) {
        ret = 10;
      } else if (language === "*") {
        ret = Math.max(ret, 5);
      } else {
        return 0;
      }
    }
    if (notebookType) {
      if (notebookType === candidateNotebookType) {
        ret = 10;
      } else if (notebookType === "*" && candidateNotebookType !== void 0) {
        ret = Math.max(ret, 5);
      } else {
        return 0;
      }
    }
    if (pattern) {
      let normalizedPattern;
      if (typeof pattern === "string") {
        normalizedPattern = pattern;
      } else {
        normalizedPattern = { ...pattern, base: $lc(pattern.base) };
      }
      if (normalizedPattern === candidateUri.fsPath || $Cl(normalizedPattern, candidateUri.fsPath)) {
        ret = 10;
      } else {
        return 0;
      }
    }
    return ret;
  } else {
    return 0;
  }
}

// out-build/vs/editor/contrib/wordHighlighter/browser/textualHighlightProvider.js
var TextualDocumentHighlightProvider = class {
  constructor() {
    this.selector = { language: "*" };
  }
  provideDocumentHighlights(model, position, token) {
    const result = [];
    const word = model.getWordAtPosition({
      lineNumber: position.lineNumber,
      column: position.column
    });
    if (!word) {
      return Promise.resolve(result);
    }
    if (model.isDisposed()) {
      return;
    }
    const matches = model.findMatches(word.word, true, false, true, $ID, false);
    return matches.map((m) => ({
      range: m.range,
      kind: DocumentHighlightKind.Text
    }));
  }
  provideMultiDocumentHighlights(primaryModel, position, otherModels, token) {
    const result = new $Ec();
    const word = primaryModel.getWordAtPosition({
      lineNumber: position.lineNumber,
      column: position.column
    });
    if (!word) {
      return Promise.resolve(result);
    }
    for (const model of [primaryModel, ...otherModels]) {
      if (model.isDisposed()) {
        continue;
      }
      const matches = model.findMatches(word.word, true, false, true, $ID, false);
      const highlights = matches.map((m) => ({
        range: m.range,
        kind: DocumentHighlightKind.Text
      }));
      if (highlights) {
        result.set(model.uri, highlights);
      }
    }
    return result;
  }
};
var $Skb = class $Skb2 extends $3c {
  constructor(languageFeaturesService) {
    super();
    this.B(languageFeaturesService.documentHighlightProvider.register("*", new TextualDocumentHighlightProvider()));
    this.B(languageFeaturesService.multiDocumentHighlightProvider.register("*", new TextualDocumentHighlightProvider()));
  }
};
$Skb = __decorate([
  __param(0, $mP)
], $Skb);

// out-build/vs/editor/contrib/wordHighlighter/browser/wordHighlighter.js
var WordHighlighter_1;
var $Vkb_1;
var ctxHasWordHighlights = new $nn("hasWordHighlights", false);
function $Tkb(registry4, model, position, token) {
  const orderedByScore = registry4.ordered(model);
  return $Zh(orderedByScore.map((provider) => () => {
    return Promise.resolve(provider.provideDocumentHighlights(model, position, token)).then(void 0, $hb);
  }), (result) => result !== void 0 && result !== null).then((result) => {
    if (result) {
      const map = new $Ec();
      map.set(model.uri, result);
      return map;
    }
    return new $Ec();
  });
}
function $Ukb(registry4, model, position, token, otherModels) {
  const orderedByScore = registry4.ordered(model);
  return $Zh(orderedByScore.map((provider) => () => {
    const filteredModels = otherModels.filter((otherModel) => {
      return $kG(otherModel);
    }).filter((otherModel) => {
      return $qE(provider.selector, otherModel.uri, otherModel.getLanguageId(), true, void 0, void 0) > 0;
    });
    return Promise.resolve(provider.provideMultiDocumentHighlights(model, position, filteredModels, token)).then(void 0, $hb);
  }), (result) => result !== void 0 && result !== null);
}
var OccurenceAtPositionRequest = class {
  constructor(c, d, f) {
    this.c = c;
    this.d = d;
    this.f = f;
    this.a = this.h(c, d);
    this.b = null;
  }
  get result() {
    if (!this.b) {
      this.b = $Hh((token) => this.g(this.c, this.d, this.f, token));
    }
    return this.b;
  }
  h(model, selection) {
    const word = model.getWordAtPosition(selection.getPosition());
    if (word) {
      return new $9C(selection.startLineNumber, word.startColumn, selection.startLineNumber, word.endColumn);
    }
    return null;
  }
  isValid(model, selection, decorations) {
    const lineNumber = selection.startLineNumber;
    const startColumn = selection.startColumn;
    const endColumn = selection.endColumn;
    const currentWordRange = this.h(model, selection);
    let requestIsValid = Boolean(this.a && this.a.equalsRange(currentWordRange));
    for (let i2 = 0, len = decorations.length; !requestIsValid && i2 < len; i2++) {
      const range = decorations.getRange(i2);
      if (range && range.startLineNumber === lineNumber) {
        if (range.startColumn <= startColumn && range.endColumn >= endColumn) {
          requestIsValid = true;
        }
      }
    }
    return requestIsValid;
  }
  cancel() {
    this.result.cancel();
  }
};
var SemanticOccurenceAtPositionRequest = class extends OccurenceAtPositionRequest {
  constructor(model, selection, wordSeparators2, providers2) {
    super(model, selection, wordSeparators2);
    this.j = providers2;
  }
  g(model, selection, wordSeparators2, token) {
    return $Tkb(this.j, model, selection.getPosition(), token).then((value) => {
      if (!value) {
        return new $Ec();
      }
      return value;
    });
  }
};
var MultiModelOccurenceRequest = class extends OccurenceAtPositionRequest {
  constructor(model, selection, wordSeparators2, providers2, otherModels) {
    super(model, selection, wordSeparators2);
    this.j = providers2;
    this.k = otherModels;
  }
  g(model, selection, wordSeparators2, token) {
    return $Ukb(this.j, model, selection.getPosition(), token, this.k).then((value) => {
      if (!value) {
        return new $Ec();
      }
      return value;
    });
  }
};
function computeOccurencesAtPosition(registry4, model, selection, wordSeparators2) {
  return new SemanticOccurenceAtPositionRequest(model, selection, wordSeparators2, registry4);
}
function computeOccurencesMultiModel(registry4, model, selection, wordSeparators2, otherModels) {
  return new MultiModelOccurenceRequest(model, selection, wordSeparators2, registry4, otherModels);
}
$35("_executeDocumentHighlights", async (accessor, model, position) => {
  const languageFeaturesService = accessor.get($mP);
  const map = await $Tkb(languageFeaturesService.documentHighlightProvider, model, position, CancellationToken.None);
  return map?.get(model.uri);
});
var WordHighlighter = class WordHighlighter2 {
  static {
    WordHighlighter_1 = this;
  }
  static {
    this.x = new $Ec();
  }
  static {
    this.y = null;
  }
  constructor(editor, providers2, multiProviders, contextKeyService, textModelService, codeEditorService, configurationService, logService) {
    this.g = new $2c();
    this.o = 0;
    this.q = false;
    this.r = new $Ec();
    this.s = 0;
    this.t = -1;
    this.w = this.g.add(new $Sh(50));
    this.a = editor;
    this.b = providers2;
    this.c = multiProviders;
    this.j = codeEditorService;
    this.h = textModelService;
    this.k = configurationService;
    this.l = logService;
    this.u = ctxHasWordHighlights.bindTo(contextKeyService);
    this.v = false;
    this.m = this.a.getOption(
      82
      /* EditorOption.occurrencesHighlight */
    );
    this.n = this.k.getValue("editor.occurrencesHighlightDelay");
    this.d = this.a.getModel();
    this.g.add(editor.onDidChangeCursorPosition((e) => {
      if (this.v) {
        return;
      }
      if (this.m === "off") {
        return;
      }
      this.w.trigger(() => {
        this.E(e);
      });
    }));
    this.g.add(editor.onDidFocusEditorText((e) => {
      if (this.m === "off") {
        return;
      }
      if (!this.p) {
        this.w.trigger(() => {
          this.H();
        });
      }
    }));
    this.g.add(editor.onDidChangeModelContent((e) => {
      if (!$0g(this.d.uri, "output")) {
        this.D();
      }
    }));
    this.g.add(editor.onDidChangeModel((e) => {
      if (!e.newModelUrl && e.oldModelUrl) {
        this.C();
      } else if (WordHighlighter_1.y) {
        this.H();
      }
    }));
    this.g.add(editor.onDidChangeConfiguration((e) => {
      const newEnablement = this.a.getOption(
        82
        /* EditorOption.occurrencesHighlight */
      );
      if (this.m !== newEnablement) {
        this.m = newEnablement;
        switch (newEnablement) {
          case "off":
            this.D();
            break;
          case "singleFile":
            this.D(WordHighlighter_1.y?.modelInfo?.modelURI);
            break;
          case "multiFile":
            if (WordHighlighter_1.y) {
              this.H(true);
            }
            break;
          default:
            console.warn("Unknown occurrencesHighlight setting value:", newEnablement);
            break;
        }
      }
    }));
    this.g.add(this.k.onDidChangeConfiguration((e) => {
      if (e.affectsConfiguration("editor.occurrencesHighlightDelay")) {
        const newDelay = configurationService.getValue("editor.occurrencesHighlightDelay");
        if (this.n !== newDelay) {
          this.n = newDelay;
        }
      }
    }));
    this.g.add(editor.onDidBlurEditorWidget(() => {
      const activeEditor = this.j.getFocusedCodeEditor();
      if (!activeEditor) {
        this.D();
      } else if (activeEditor.getModel()?.uri.scheme === Schemas.vscodeNotebookCell && this.a.getModel()?.uri.scheme !== Schemas.vscodeNotebookCell) {
        this.D();
      }
    }));
    this.f = this.a.createDecorationsCollection();
    this.o = 0;
    this.p = null;
    this.q = false;
    this.s = 0;
    this.t = -1;
    if (WordHighlighter_1.y) {
      this.H();
    }
  }
  hasDecorations() {
    return this.f.length > 0;
  }
  restore() {
    if (this.m === "off") {
      return;
    }
    this.w.cancel();
    this.H();
  }
  trigger() {
    this.w.cancel();
    this.H(false, true);
  }
  stop() {
    if (this.m === "off") {
      return;
    }
    this.D();
  }
  z() {
    return this.f.getRanges().sort($9C.compareRangesUsingStarts);
  }
  moveNext() {
    const highlights = this.z();
    const index = highlights.findIndex((range) => range.containsPosition(this.a.getPosition()));
    const newIndex = (index + 1) % highlights.length;
    const dest = highlights[newIndex];
    try {
      this.v = true;
      this.a.setPosition(dest.getStartPosition());
      this.a.revealRangeInCenterIfOutsideViewport(dest);
      const word = this.F();
      if (word) {
        const lineContent = this.a.getModel().getLineContent(dest.startLineNumber);
        $$Z(`${lineContent}, ${newIndex + 1} of ${highlights.length} for '${word.word}'`);
      }
    } finally {
      this.v = false;
    }
  }
  moveBack() {
    const highlights = this.z();
    const index = highlights.findIndex((range) => range.containsPosition(this.a.getPosition()));
    const newIndex = (index - 1 + highlights.length) % highlights.length;
    const dest = highlights[newIndex];
    try {
      this.v = true;
      this.a.setPosition(dest.getStartPosition());
      this.a.revealRangeInCenterIfOutsideViewport(dest);
      const word = this.F();
      if (word) {
        const lineContent = this.a.getModel().getLineContent(dest.startLineNumber);
        $$Z(`${lineContent}, ${newIndex + 1} of ${highlights.length} for '${word.word}'`);
      }
    } finally {
      this.v = false;
    }
  }
  A() {
    if (!this.a.hasModel()) {
      return;
    }
    const currentDecorationIDs = WordHighlighter_1.x.get(this.a.getModel().uri);
    if (!currentDecorationIDs) {
      return;
    }
    this.a.removeDecorations(currentDecorationIDs);
    WordHighlighter_1.x.delete(this.a.getModel().uri);
    if (this.f.length > 0) {
      this.f.clear();
      this.u.set(false);
    }
  }
  B(preservedModel) {
    const currentEditors = this.j.listCodeEditors();
    const deleteURI = [];
    for (const editor of currentEditors) {
      if (!editor.hasModel() || $oh(editor.getModel().uri, preservedModel)) {
        continue;
      }
      const currentDecorationIDs = WordHighlighter_1.x.get(editor.getModel().uri);
      if (!currentDecorationIDs) {
        continue;
      }
      editor.removeDecorations(currentDecorationIDs);
      deleteURI.push(editor.getModel().uri);
      const editorHighlighterContrib = $Vkb.get(editor);
      if (!editorHighlighterContrib?.wordHighlighter) {
        continue;
      }
      if (editorHighlighterContrib.wordHighlighter.f.length > 0) {
        editorHighlighterContrib.wordHighlighter.f.clear();
        editorHighlighterContrib.wordHighlighter.p = null;
        editorHighlighterContrib.wordHighlighter.u.set(false);
      }
    }
    for (const uri of deleteURI) {
      WordHighlighter_1.x.delete(uri);
    }
  }
  C() {
    this.A();
    if (this.a.hasTextFocus()) {
      if (this.a.getModel()?.uri.scheme !== Schemas.vscodeNotebookCell && WordHighlighter_1.y?.modelInfo?.modelURI.scheme !== Schemas.vscodeNotebookCell) {
        WordHighlighter_1.y = null;
        this.H();
      } else {
        if (WordHighlighter_1.y?.modelInfo) {
          WordHighlighter_1.y.modelInfo = null;
        }
      }
    }
    if (this.t !== -1) {
      clearTimeout(this.t);
      this.t = -1;
    }
    if (this.p !== null) {
      this.p.cancel();
      this.p = null;
    }
    if (!this.q) {
      this.o++;
      this.q = true;
    }
  }
  D(preservedModel) {
    this.B(preservedModel);
    if (this.t !== -1) {
      clearTimeout(this.t);
      this.t = -1;
    }
    if (this.p !== null) {
      this.p.cancel();
      this.p = null;
    }
    if (!this.q) {
      this.o++;
      this.q = true;
    }
  }
  E(e) {
    if (this.m === "off") {
      this.D();
      return;
    }
    if (e.reason !== 3 && this.a.getModel()?.uri.scheme !== Schemas.vscodeNotebookCell) {
      this.D();
      return;
    }
    this.H();
  }
  F() {
    const editorSelection = this.a.getSelection();
    const lineNumber = editorSelection.startLineNumber;
    const startColumn = editorSelection.startColumn;
    if (this.d.isDisposed()) {
      return null;
    }
    return this.d.getWordAtPosition({
      lineNumber,
      column: startColumn
    });
  }
  G(model) {
    if (!model) {
      return [];
    }
    const isNotebookEditor = model.uri.scheme === Schemas.vscodeNotebookCell;
    if (isNotebookEditor) {
      const currentModels2 = [];
      const currentEditors2 = this.j.listCodeEditors();
      for (const editor of currentEditors2) {
        const tempModel = editor.getModel();
        if (tempModel && tempModel !== model && tempModel.uri.scheme === Schemas.vscodeNotebookCell) {
          currentModels2.push(tempModel);
        }
      }
      return currentModels2;
    }
    const currentModels = [];
    const currentEditors = this.j.listCodeEditors();
    for (const editor of currentEditors) {
      if (!$Q5(editor)) {
        continue;
      }
      const diffModel = editor.getModel();
      if (!diffModel) {
        continue;
      }
      if (model === diffModel.modified) {
        currentModels.push(diffModel.modified);
      }
    }
    if (currentModels.length) {
      return currentModels;
    }
    if (this.m === "singleFile") {
      return [];
    }
    for (const editor of currentEditors) {
      const tempModel = editor.getModel();
      const isValidModel = tempModel && tempModel !== model;
      if (isValidModel) {
        currentModels.push(tempModel);
      }
    }
    return currentModels;
  }
  async H(multiFileConfigChange, noDelay) {
    const hasTextFocus = this.a.hasTextFocus();
    if (!hasTextFocus) {
      if (!WordHighlighter_1.y) {
        this.D();
        return;
      }
    } else {
      const editorSelection = this.a.getSelection();
      if (!editorSelection || editorSelection.startLineNumber !== editorSelection.endLineNumber) {
        WordHighlighter_1.y = null;
        this.D();
        return;
      }
      const startColumn = editorSelection.startColumn;
      const endColumn = editorSelection.endColumn;
      const word = this.F();
      if (!word || word.startColumn > startColumn || word.endColumn < endColumn) {
        WordHighlighter_1.y = null;
        this.D();
        return;
      }
      WordHighlighter_1.y = {
        modelInfo: {
          modelURI: this.d.uri,
          selection: editorSelection
        }
      };
    }
    this.s = (/* @__PURE__ */ new Date()).getTime();
    if ($oh(this.a.getModel().uri, WordHighlighter_1.y.modelInfo?.modelURI)) {
      if (!multiFileConfigChange) {
        const currentModelDecorationRanges = this.f.getRanges();
        for (const storedRange of currentModelDecorationRanges) {
          if (storedRange.containsPosition(this.a.getPosition())) {
            return;
          }
        }
      }
      this.D(multiFileConfigChange ? this.d.uri : void 0);
      const myRequestId = ++this.o;
      this.q = false;
      const otherModelsToHighlight = this.G(this.a.getModel());
      if (!WordHighlighter_1.y || !WordHighlighter_1.y.modelInfo) {
        return;
      }
      const queryModelRef = await this.h.createModelReference(WordHighlighter_1.y.modelInfo.modelURI);
      try {
        this.p = this.I(queryModelRef.object.textEditorModel, WordHighlighter_1.y.modelInfo.selection, otherModelsToHighlight);
        this.p?.result.then((data) => {
          if (myRequestId === this.o) {
            this.q = true;
            this.r = data || [];
            this.J();
          }
        }, $gb);
      } catch (e) {
        this.l.error("Unexpected error during occurrence request. Log: ", e);
      } finally {
        queryModelRef.dispose();
      }
    } else if (this.d.uri.scheme === Schemas.vscodeNotebookCell) {
      const myRequestId = ++this.o;
      this.q = false;
      if (!WordHighlighter_1.y || !WordHighlighter_1.y.modelInfo) {
        return;
      }
      const queryModelRef = await this.h.createModelReference(WordHighlighter_1.y.modelInfo.modelURI);
      try {
        this.p = this.I(queryModelRef.object.textEditorModel, WordHighlighter_1.y.modelInfo.selection, [this.d]);
        this.p?.result.then((data) => {
          if (myRequestId === this.o) {
            this.q = true;
            this.r = data || [];
            this.J(noDelay);
          }
        }, $gb);
      } catch (e) {
        this.l.error("Unexpected error during occurrence request. Log: ", e);
      } finally {
        queryModelRef.dispose();
      }
    }
  }
  I(model, selection, otherModels) {
    if (!otherModels.length) {
      return computeOccurencesAtPosition(this.b, model, selection, this.a.getOption(
        136
        /* EditorOption.wordSeparators */
      ));
    } else {
      return computeOccurencesMultiModel(this.c, model, selection, this.a.getOption(
        136
        /* EditorOption.wordSeparators */
      ), otherModels);
    }
  }
  J(noDelay) {
    const currentTime = (/* @__PURE__ */ new Date()).getTime();
    const minimumRenderTime = this.s + (noDelay ? 0 : this.n);
    if (currentTime >= minimumRenderTime) {
      this.t = -1;
      this.K();
    } else {
      this.t = setTimeout(() => {
        this.K();
      }, minimumRenderTime - currentTime);
    }
  }
  K() {
    this.t = -1;
    const currentEditors = this.j.listCodeEditors();
    for (const editor of currentEditors) {
      const editorHighlighterContrib = $Vkb.get(editor);
      if (!editorHighlighterContrib) {
        continue;
      }
      const newDecorations = [];
      const uri = editor.getModel()?.uri;
      if (uri && this.r.has(uri)) {
        const oldDecorationIDs = WordHighlighter_1.x.get(uri);
        const newDocumentHighlights = this.r.get(uri);
        if (newDocumentHighlights) {
          for (const highlight of newDocumentHighlights) {
            if (!highlight.range) {
              continue;
            }
            newDecorations.push({
              range: highlight.range,
              options: $Bjb(highlight.kind)
            });
          }
        }
        let newDecorationIDs = [];
        editor.changeDecorations((changeAccessor) => {
          newDecorationIDs = changeAccessor.deltaDecorations(oldDecorationIDs ?? [], newDecorations);
        });
        WordHighlighter_1.x = WordHighlighter_1.x.set(uri, newDecorationIDs);
        if (newDecorations.length > 0) {
          editorHighlighterContrib.wordHighlighter?.f.set(newDecorations);
          editorHighlighterContrib.wordHighlighter?.u.set(true);
        }
      }
    }
    this.p = null;
  }
  dispose() {
    this.C();
    this.g.dispose();
  }
};
WordHighlighter = WordHighlighter_1 = __decorate([
  __param(4, $oG),
  __param(5, $U5),
  __param(6, $kl),
  __param(7, $wn)
], WordHighlighter);
var $Vkb = class $Vkb2 extends $3c {
  static {
    $Vkb_1 = this;
  }
  static {
    this.ID = "editor.contrib.wordHighlighter";
  }
  static get(editor) {
    return editor.getContribution($Vkb_1.ID);
  }
  constructor(editor, contextKeyService, languageFeaturesService, codeEditorService, textModelService, configurationService, logService) {
    super();
    this.a = null;
    const createWordHighlighterIfPossible = () => {
      if (editor.hasModel() && !editor.getModel().isTooLargeForTokenization() && editor.getModel().uri.scheme !== Schemas.accessibleView) {
        this.a = new WordHighlighter(editor, languageFeaturesService.documentHighlightProvider, languageFeaturesService.multiDocumentHighlightProvider, contextKeyService, textModelService, codeEditorService, configurationService, logService);
      }
    };
    this.B(editor.onDidChangeModel((e) => {
      if (this.a) {
        if (!e.newModelUrl && e.oldModelUrl?.scheme !== Schemas.vscodeNotebookCell) {
          this.wordHighlighter?.stop();
        }
        this.a.dispose();
        this.a = null;
      }
      createWordHighlighterIfPossible();
    }));
    createWordHighlighterIfPossible();
  }
  get wordHighlighter() {
    return this.a;
  }
  saveViewState() {
    if (this.a && this.a.hasDecorations()) {
      return true;
    }
    return false;
  }
  moveNext() {
    this.a?.moveNext();
  }
  moveBack() {
    this.a?.moveBack();
  }
  restoreViewState(state) {
    if (this.a && state) {
      this.a.restore();
    }
  }
  stopHighlighting() {
    this.a?.stop();
  }
  dispose() {
    if (this.a) {
      this.a.dispose();
      this.a = null;
    }
    super.dispose();
  }
};
$Vkb = $Vkb_1 = __decorate([
  __param(1, $on),
  __param(2, $mP),
  __param(3, $U5),
  __param(4, $oG),
  __param(5, $kl),
  __param(6, $wn)
], $Vkb);
var WordHighlightNavigationAction = class extends $Z5 {
  constructor(next, opts) {
    super(opts);
    this.d = next;
  }
  run(accessor, editor) {
    const controller = $Vkb.get(editor);
    if (!controller) {
      return;
    }
    if (this.d) {
      controller.moveNext();
    } else {
      controller.moveBack();
    }
  }
};
var NextWordHighlightAction = class extends WordHighlightNavigationAction {
  constructor() {
    super(true, {
      id: "editor.action.wordHighlight.next",
      label: localize2(1607, "Go to Next Symbol Highlight"),
      precondition: ctxHasWordHighlights,
      kbOpts: {
        kbExpr: EditorContextKeys.editorTextFocus,
        primary: 65,
        weight: 100
        /* KeybindingWeight.EditorContrib */
      }
    });
  }
};
var PrevWordHighlightAction = class extends WordHighlightNavigationAction {
  constructor() {
    super(false, {
      id: "editor.action.wordHighlight.prev",
      label: localize2(1608, "Go to Previous Symbol Highlight"),
      precondition: ctxHasWordHighlights,
      kbOpts: {
        kbExpr: EditorContextKeys.editorTextFocus,
        primary: 1024 | 65,
        weight: 100
        /* KeybindingWeight.EditorContrib */
      }
    });
  }
};
var TriggerWordHighlightAction = class extends $Z5 {
  constructor() {
    super({
      id: "editor.action.wordHighlight.trigger",
      label: localize2(1609, "Trigger Symbol Highlight"),
      precondition: void 0,
      kbOpts: {
        kbExpr: EditorContextKeys.editorTextFocus,
        primary: 0,
        weight: 100
        /* KeybindingWeight.EditorContrib */
      }
    });
  }
  run(accessor, editor, args2) {
    const controller = $Vkb.get(editor);
    if (!controller) {
      return;
    }
    controller.restoreViewState(true);
  }
};
$85(
  $Vkb.ID,
  $Vkb,
  0
  /* EditorContributionInstantiation.Eager */
);
$55(NextWordHighlightAction);
$55(PrevWordHighlightAction);
$55(TriggerWordHighlightAction);
$T_($Skb);

// out-build/vs/editor/contrib/wordOperations/browser/wordOperations.js
var $Wkb = class extends $Y5 {
  constructor(opts) {
    super(opts);
    this.d = opts.inSelectionMode;
    this.e = opts.wordNavigationType;
  }
  runEditorCommand(accessor, editor, args2) {
    if (!editor.hasModel()) {
      return;
    }
    const wordSeparators2 = $iE(editor.getOption(
      136
      /* EditorOption.wordSeparators */
    ), editor.getOption(
      135
      /* EditorOption.wordSegmenterLocales */
    ));
    const model = editor.getModel();
    const selections = editor.getSelections();
    const hasMulticursor = selections.length > 1;
    const result = selections.map((sel) => {
      const inPosition = new $8C(sel.positionLineNumber, sel.positionColumn);
      const outPosition = this.j(wordSeparators2, model, inPosition, this.e, hasMulticursor);
      return this.h(sel, outPosition, this.d);
    });
    model.pushStackElement();
    editor._getViewModel().setCursorStates("moveWordCommand", 3, result.map((r2) => $e5.fromModelSelection(r2)));
    if (result.length === 1) {
      const pos = new $8C(result[0].positionLineNumber, result[0].positionColumn);
      editor.revealPosition(
        pos,
        0
        /* ScrollType.Smooth */
      );
    }
  }
  h(from, to, inSelectionMode) {
    if (inSelectionMode) {
      return new $_D(from.selectionStartLineNumber, from.selectionStartColumn, to.lineNumber, to.column);
    } else {
      return new $_D(to.lineNumber, to.column, to.lineNumber, to.column);
    }
  }
};
var $Xkb = class extends $Wkb {
  j(wordSeparators2, model, position, wordNavigationType, hasMulticursor) {
    return $m6.moveWordLeft(wordSeparators2, model, position, wordNavigationType, hasMulticursor);
  }
};
var $Ykb = class extends $Wkb {
  j(wordSeparators2, model, position, wordNavigationType, hasMulticursor) {
    return $m6.moveWordRight(wordSeparators2, model, position, wordNavigationType);
  }
};
var $Zkb = class extends $Xkb {
  constructor() {
    super({
      inSelectionMode: false,
      wordNavigationType: 0,
      id: "cursorWordStartLeft",
      precondition: void 0
    });
  }
};
var $1kb = class extends $Xkb {
  constructor() {
    super({
      inSelectionMode: false,
      wordNavigationType: 2,
      id: "cursorWordEndLeft",
      precondition: void 0
    });
  }
};
var $2kb = class extends $Xkb {
  constructor() {
    super({
      inSelectionMode: false,
      wordNavigationType: 1,
      id: "cursorWordLeft",
      precondition: void 0,
      kbOpts: {
        kbExpr: $7m.and(EditorContextKeys.textInputFocus, $7m.and($OD, $ueb)?.negate()),
        primary: 2048 | 15,
        mac: {
          primary: 512 | 15
          /* KeyCode.LeftArrow */
        },
        weight: 100
        /* KeybindingWeight.EditorContrib */
      }
    });
  }
};
var $3kb = class extends $Xkb {
  constructor() {
    super({
      inSelectionMode: true,
      wordNavigationType: 0,
      id: "cursorWordStartLeftSelect",
      precondition: void 0
    });
  }
};
var $4kb = class extends $Xkb {
  constructor() {
    super({
      inSelectionMode: true,
      wordNavigationType: 2,
      id: "cursorWordEndLeftSelect",
      precondition: void 0
    });
  }
};
var $5kb = class extends $Xkb {
  constructor() {
    super({
      inSelectionMode: true,
      wordNavigationType: 1,
      id: "cursorWordLeftSelect",
      precondition: void 0,
      kbOpts: {
        kbExpr: $7m.and(EditorContextKeys.textInputFocus, $7m.and($OD, $ueb)?.negate()),
        primary: 2048 | 1024 | 15,
        mac: {
          primary: 512 | 1024 | 15
          /* KeyCode.LeftArrow */
        },
        weight: 100
        /* KeybindingWeight.EditorContrib */
      }
    });
  }
};
var $6kb = class extends $Xkb {
  constructor() {
    super({
      inSelectionMode: false,
      wordNavigationType: 3,
      id: "cursorWordAccessibilityLeft",
      precondition: void 0
    });
  }
  j(wordCharacterClassifier, model, position, wordNavigationType, hasMulticursor) {
    return super.j($iE(EditorOptions.wordSeparators.defaultValue, wordCharacterClassifier.intlSegmenterLocales), model, position, wordNavigationType, hasMulticursor);
  }
};
var $7kb = class extends $Xkb {
  constructor() {
    super({
      inSelectionMode: true,
      wordNavigationType: 3,
      id: "cursorWordAccessibilityLeftSelect",
      precondition: void 0
    });
  }
  j(wordCharacterClassifier, model, position, wordNavigationType, hasMulticursor) {
    return super.j($iE(EditorOptions.wordSeparators.defaultValue, wordCharacterClassifier.intlSegmenterLocales), model, position, wordNavigationType, hasMulticursor);
  }
};
var $8kb = class extends $Ykb {
  constructor() {
    super({
      inSelectionMode: false,
      wordNavigationType: 0,
      id: "cursorWordStartRight",
      precondition: void 0
    });
  }
};
var $9kb = class extends $Ykb {
  constructor() {
    super({
      inSelectionMode: false,
      wordNavigationType: 2,
      id: "cursorWordEndRight",
      precondition: void 0,
      kbOpts: {
        kbExpr: $7m.and(EditorContextKeys.textInputFocus, $7m.and($OD, $ueb)?.negate()),
        primary: 2048 | 17,
        mac: {
          primary: 512 | 17
          /* KeyCode.RightArrow */
        },
        weight: 100
        /* KeybindingWeight.EditorContrib */
      }
    });
  }
};
var $0kb = class extends $Ykb {
  constructor() {
    super({
      inSelectionMode: false,
      wordNavigationType: 2,
      id: "cursorWordRight",
      precondition: void 0
    });
  }
};
var $$kb = class extends $Ykb {
  constructor() {
    super({
      inSelectionMode: true,
      wordNavigationType: 0,
      id: "cursorWordStartRightSelect",
      precondition: void 0
    });
  }
};
var $_kb = class extends $Ykb {
  constructor() {
    super({
      inSelectionMode: true,
      wordNavigationType: 2,
      id: "cursorWordEndRightSelect",
      precondition: void 0,
      kbOpts: {
        kbExpr: $7m.and(EditorContextKeys.textInputFocus, $7m.and($OD, $ueb)?.negate()),
        primary: 2048 | 1024 | 17,
        mac: {
          primary: 512 | 1024 | 17
          /* KeyCode.RightArrow */
        },
        weight: 100
        /* KeybindingWeight.EditorContrib */
      }
    });
  }
};
var $alb = class extends $Ykb {
  constructor() {
    super({
      inSelectionMode: true,
      wordNavigationType: 2,
      id: "cursorWordRightSelect",
      precondition: void 0
    });
  }
};
var $blb = class extends $Ykb {
  constructor() {
    super({
      inSelectionMode: false,
      wordNavigationType: 3,
      id: "cursorWordAccessibilityRight",
      precondition: void 0
    });
  }
  j(wordCharacterClassifier, model, position, wordNavigationType, hasMulticursor) {
    return super.j($iE(EditorOptions.wordSeparators.defaultValue, wordCharacterClassifier.intlSegmenterLocales), model, position, wordNavigationType, hasMulticursor);
  }
};
var $clb = class extends $Ykb {
  constructor() {
    super({
      inSelectionMode: true,
      wordNavigationType: 3,
      id: "cursorWordAccessibilityRightSelect",
      precondition: void 0
    });
  }
  j(wordCharacterClassifier, model, position, wordNavigationType, hasMulticursor) {
    return super.j($iE(EditorOptions.wordSeparators.defaultValue, wordCharacterClassifier.intlSegmenterLocales), model, position, wordNavigationType, hasMulticursor);
  }
};
var $dlb = class extends $Y5 {
  constructor(opts) {
    super(opts);
    this.d = opts.whitespaceHeuristics;
    this.e = opts.wordNavigationType;
  }
  runEditorCommand(accessor, editor, args2) {
    const languageConfigurationService = accessor.get($NF);
    if (!editor.hasModel()) {
      return;
    }
    const wordSeparators2 = $iE(editor.getOption(
      136
      /* EditorOption.wordSeparators */
    ), editor.getOption(
      135
      /* EditorOption.wordSegmenterLocales */
    ));
    const model = editor.getModel();
    const selections = editor.getSelections();
    const autoClosingBrackets = editor.getOption(
      6
      /* EditorOption.autoClosingBrackets */
    );
    const autoClosingQuotes = editor.getOption(
      11
      /* EditorOption.autoClosingQuotes */
    );
    const autoClosingPairs = languageConfigurationService.getLanguageConfiguration(model.getLanguageId()).getAutoClosingPairs();
    const viewModel = editor._getViewModel();
    const commands2 = selections.map((sel) => {
      const deleteRange = this.h({
        wordSeparators: wordSeparators2,
        model,
        selection: sel,
        whitespaceHeuristics: this.d,
        autoClosingDelete: editor.getOption(
          9
          /* EditorOption.autoClosingDelete */
        ),
        autoClosingBrackets,
        autoClosingQuotes,
        autoClosingPairs,
        autoClosedCharacters: viewModel.getCursorAutoClosedCharacters()
      }, this.e);
      return new $b6(deleteRange, "");
    });
    editor.pushUndoStop();
    editor.executeCommands(this.id, commands2);
    editor.pushUndoStop();
  }
};
var $elb = class extends $dlb {
  h(ctx, wordNavigationType) {
    const r2 = $m6.deleteWordLeft(ctx, wordNavigationType);
    if (r2) {
      return r2;
    }
    return new $9C(1, 1, 1, 1);
  }
};
var $flb = class extends $dlb {
  h(ctx, wordNavigationType) {
    const r2 = $m6.deleteWordRight(ctx, wordNavigationType);
    if (r2) {
      return r2;
    }
    const lineCount = ctx.model.getLineCount();
    const maxColumn = ctx.model.getLineMaxColumn(lineCount);
    return new $9C(lineCount, maxColumn, lineCount, maxColumn);
  }
};
var $glb = class extends $elb {
  constructor() {
    super({
      whitespaceHeuristics: false,
      wordNavigationType: 0,
      id: "deleteWordStartLeft",
      precondition: EditorContextKeys.writable
    });
  }
};
var $hlb = class extends $elb {
  constructor() {
    super({
      whitespaceHeuristics: false,
      wordNavigationType: 2,
      id: "deleteWordEndLeft",
      precondition: EditorContextKeys.writable
    });
  }
};
var $ilb = class extends $elb {
  constructor() {
    super({
      whitespaceHeuristics: true,
      wordNavigationType: 0,
      id: "deleteWordLeft",
      precondition: EditorContextKeys.writable,
      kbOpts: {
        kbExpr: EditorContextKeys.textInputFocus,
        primary: 2048 | 1,
        mac: {
          primary: 512 | 1
          /* KeyCode.Backspace */
        },
        weight: 100
        /* KeybindingWeight.EditorContrib */
      }
    });
  }
};
var $jlb = class extends $flb {
  constructor() {
    super({
      whitespaceHeuristics: false,
      wordNavigationType: 0,
      id: "deleteWordStartRight",
      precondition: EditorContextKeys.writable
    });
  }
};
var $klb = class extends $flb {
  constructor() {
    super({
      whitespaceHeuristics: false,
      wordNavigationType: 2,
      id: "deleteWordEndRight",
      precondition: EditorContextKeys.writable
    });
  }
};
var $llb = class extends $flb {
  constructor() {
    super({
      whitespaceHeuristics: true,
      wordNavigationType: 2,
      id: "deleteWordRight",
      precondition: EditorContextKeys.writable,
      kbOpts: {
        kbExpr: EditorContextKeys.textInputFocus,
        primary: 2048 | 20,
        mac: {
          primary: 512 | 20
          /* KeyCode.Delete */
        },
        weight: 100
        /* KeybindingWeight.EditorContrib */
      }
    });
  }
};
var $mlb = class extends $Z5 {
  constructor() {
    super({
      id: "deleteInsideWord",
      precondition: EditorContextKeys.writable,
      label: localize2(1610, "Delete Word")
    });
  }
  run(accessor, editor, args2) {
    if (!editor.hasModel()) {
      return;
    }
    const wordSeparators2 = $iE(editor.getOption(
      136
      /* EditorOption.wordSeparators */
    ), editor.getOption(
      135
      /* EditorOption.wordSegmenterLocales */
    ));
    const model = editor.getModel();
    const selections = editor.getSelections();
    const commands2 = selections.map((sel) => {
      const deleteRange = $m6.deleteInsideWord(wordSeparators2, model, sel);
      return new $b6(deleteRange, "");
    });
    editor.pushUndoStop();
    editor.executeCommands(this.id, commands2);
    editor.pushUndoStop();
  }
};
$45(new $Zkb());
$45(new $1kb());
$45(new $2kb());
$45(new $3kb());
$45(new $4kb());
$45(new $5kb());
$45(new $8kb());
$45(new $9kb());
$45(new $0kb());
$45(new $$kb());
$45(new $_kb());
$45(new $alb());
$45(new $6kb());
$45(new $7kb());
$45(new $blb());
$45(new $clb());
$45(new $glb());
$45(new $hlb());
$45(new $ilb());
$45(new $jlb());
$45(new $klb());
$45(new $llb());
$55($mlb);

// out-build/vs/editor/contrib/wordPartOperations/browser/wordPartOperations.js
var $nlb = class extends $dlb {
  constructor() {
    super({
      whitespaceHeuristics: true,
      wordNavigationType: 0,
      id: "deleteWordPartLeft",
      precondition: EditorContextKeys.writable,
      kbOpts: {
        kbExpr: EditorContextKeys.textInputFocus,
        primary: 0,
        mac: {
          primary: 256 | 512 | 1
          /* KeyCode.Backspace */
        },
        weight: 100
        /* KeybindingWeight.EditorContrib */
      }
    });
  }
  h(ctx, wordNavigationType) {
    const r2 = $n6.deleteWordPartLeft(ctx);
    if (r2) {
      return r2;
    }
    return new $9C(1, 1, 1, 1);
  }
};
var $olb = class extends $dlb {
  constructor() {
    super({
      whitespaceHeuristics: true,
      wordNavigationType: 2,
      id: "deleteWordPartRight",
      precondition: EditorContextKeys.writable,
      kbOpts: {
        kbExpr: EditorContextKeys.textInputFocus,
        primary: 0,
        mac: {
          primary: 256 | 512 | 20
          /* KeyCode.Delete */
        },
        weight: 100
        /* KeybindingWeight.EditorContrib */
      }
    });
  }
  h(ctx, wordNavigationType) {
    const r2 = $n6.deleteWordPartRight(ctx);
    if (r2) {
      return r2;
    }
    const lineCount = ctx.model.getLineCount();
    const maxColumn = ctx.model.getLineMaxColumn(lineCount);
    return new $9C(lineCount, maxColumn, lineCount, maxColumn);
  }
};
var $plb = class extends $Wkb {
  j(wordSeparators2, model, position, wordNavigationType, hasMulticursor) {
    return $n6.moveWordPartLeft(wordSeparators2, model, position, hasMulticursor);
  }
};
var $qlb = class extends $plb {
  constructor() {
    super({
      inSelectionMode: false,
      wordNavigationType: 0,
      id: "cursorWordPartLeft",
      precondition: void 0,
      kbOpts: {
        kbExpr: EditorContextKeys.textInputFocus,
        primary: 0,
        mac: {
          primary: 256 | 512 | 15
          /* KeyCode.LeftArrow */
        },
        weight: 100
        /* KeybindingWeight.EditorContrib */
      }
    });
  }
};
$tn.registerCommandAlias("cursorWordPartStartLeft", "cursorWordPartLeft");
var $rlb = class extends $plb {
  constructor() {
    super({
      inSelectionMode: true,
      wordNavigationType: 0,
      id: "cursorWordPartLeftSelect",
      precondition: void 0,
      kbOpts: {
        kbExpr: EditorContextKeys.textInputFocus,
        primary: 0,
        mac: {
          primary: 256 | 512 | 1024 | 15
          /* KeyCode.LeftArrow */
        },
        weight: 100
        /* KeybindingWeight.EditorContrib */
      }
    });
  }
};
$tn.registerCommandAlias("cursorWordPartStartLeftSelect", "cursorWordPartLeftSelect");
var $slb = class extends $Wkb {
  j(wordSeparators2, model, position, wordNavigationType, hasMulticursor) {
    return $n6.moveWordPartRight(wordSeparators2, model, position);
  }
};
var $tlb = class extends $slb {
  constructor() {
    super({
      inSelectionMode: false,
      wordNavigationType: 2,
      id: "cursorWordPartRight",
      precondition: void 0,
      kbOpts: {
        kbExpr: EditorContextKeys.textInputFocus,
        primary: 0,
        mac: {
          primary: 256 | 512 | 17
          /* KeyCode.RightArrow */
        },
        weight: 100
        /* KeybindingWeight.EditorContrib */
      }
    });
  }
};
var $ulb = class extends $slb {
  constructor() {
    super({
      inSelectionMode: true,
      wordNavigationType: 2,
      id: "cursorWordPartRightSelect",
      precondition: void 0,
      kbOpts: {
        kbExpr: EditorContextKeys.textInputFocus,
        primary: 0,
        mac: {
          primary: 256 | 512 | 1024 | 17
          /* KeyCode.RightArrow */
        },
        weight: 100
        /* KeybindingWeight.EditorContrib */
      }
    });
  }
};
$45(new $nlb());
$45(new $olb());
$45(new $qlb());
$45(new $rlb());
$45(new $tlb());
$45(new $ulb());

// out-build/vs/editor/contrib/readOnlyMessage/browser/contribution.js
var $vlb = class extends $3c {
  static {
    this.ID = "editor.contrib.readOnlyMessageController";
  }
  constructor(a) {
    super();
    this.a = a;
    this.B(this.a.onDidAttemptReadOnlyEdit(() => this.b()));
  }
  b() {
    const messageController = $S_.get(this.a);
    if (messageController && this.a.hasModel()) {
      let message = this.a.getOptions().get(
        97
        /* EditorOption.readOnlyMessage */
      );
      if (!message) {
        if (this.a.isSimpleWidget) {
          message = new $bm(localize(1416, null));
        } else {
          message = new $bm(localize(1417, null));
        }
      }
      messageController.showMessage(message, this.a.getPosition());
    }
  }
};
$85(
  $vlb.ID,
  $vlb,
  2
  /* EditorContributionInstantiation.BeforeFirstInteraction */
);

// out-build/vs/editor/contrib/diffEditorBreadcrumbs/browser/contribution.js
var DiffEditorBreadcrumbsSource = class DiffEditorBreadcrumbsSource2 extends $3c {
  constructor(b, c, f) {
    super();
    this.b = b;
    this.c = c;
    this.f = f;
    this.a = $he(this, void 0);
    const documentSymbolProviderChanged = $Gd("documentSymbolProvider.onDidChange", this.c.documentSymbolProvider.onDidChange);
    const textModelChanged = $Gd("_textModel.onDidChangeContent", Event2.debounce((e) => this.b.onDidChangeContent(e), () => void 0, 100));
    this.B($xd(async (reader, store) => {
      documentSymbolProviderChanged.read(reader);
      textModelChanged.read(reader);
      const src = store.add(new $39());
      const model = await this.f.getOrCreate(this.b, src.token);
      if (store.isDisposed) {
        return;
      }
      this.a.set(model, void 0);
    }));
  }
  getBreadcrumbItems(startRange, reader) {
    const m = this.a.read(reader);
    if (!m) {
      return [];
    }
    const symbols = m.asListOfDocumentSymbols().filter((s) => startRange.contains(s.range.startLineNumber) && !startRange.contains(s.range.endLineNumber));
    symbols.sort($ac($9b((s) => s.range.endLineNumber - s.range.startLineNumber, $$b)));
    return symbols.map((s) => ({ name: s.name, kind: s.kind, startLineNumber: s.range.startLineNumber }));
  }
};
DiffEditorBreadcrumbsSource = __decorate([
  __param(1, $mP),
  __param(2, $phb)
], DiffEditorBreadcrumbsSource);
$_$.setBreadcrumbsSourceFactory((textModel, instantiationService) => {
  return instantiationService.createInstance(DiffEditorBreadcrumbsSource, textModel);
});

// out-build/vs/editor/common/standaloneStrings.js
var AccessibilityHelpNLS;
(function(AccessibilityHelpNLS2) {
  AccessibilityHelpNLS2.accessibilityHelpTitle = localize(833, null);
  AccessibilityHelpNLS2.openingDocs = localize(834, null);
  AccessibilityHelpNLS2.readonlyDiffEditor = localize(835, null);
  AccessibilityHelpNLS2.editableDiffEditor = localize(836, null);
  AccessibilityHelpNLS2.readonlyEditor = localize(837, null);
  AccessibilityHelpNLS2.editableEditor = localize(838, null);
  AccessibilityHelpNLS2.changeConfigToOnMac = localize(839, null);
  AccessibilityHelpNLS2.changeConfigToOnWinLinux = localize(840, null);
  AccessibilityHelpNLS2.auto_on = localize(841, null);
  AccessibilityHelpNLS2.auto_off = localize(842, null);
  AccessibilityHelpNLS2.screenReaderModeEnabled = localize(843, null);
  AccessibilityHelpNLS2.screenReaderModeDisabled = localize(844, null);
  AccessibilityHelpNLS2.tabFocusModeOnMsg = localize(845, null, "<keybinding:editor.action.toggleTabFocusMode>");
  AccessibilityHelpNLS2.tabFocusModeOffMsg = localize(846, null, "<keybinding:editor.action.toggleTabFocusMode>");
  AccessibilityHelpNLS2.stickScroll = localize(847, null, "<keybinding:editor.action.focusStickyDebugConsole>");
  AccessibilityHelpNLS2.codeFolding = localize(848, null, "<keybinding:editor.toggleFold>");
  AccessibilityHelpNLS2.intellisense = localize(849, null, "<keybinding:editor.action.triggerSuggest>");
  AccessibilityHelpNLS2.showOrFocusHover = localize(850, null, "<keybinding:editor.action.showHover>");
  AccessibilityHelpNLS2.goToSymbol = localize(851, null, "<keybinding:workbench.action.gotoSymbol>");
  AccessibilityHelpNLS2.showAccessibilityHelpAction = localize(852, null);
  AccessibilityHelpNLS2.listSignalSounds = localize(853, null);
  AccessibilityHelpNLS2.listAlerts = localize(854, null);
  AccessibilityHelpNLS2.quickChat = localize(855, null, "<keybinding:workbench.action.quickchat.toggle>");
  AccessibilityHelpNLS2.startInlineChat = localize(856, null, "<keybinding:inlineChat.start>");
  AccessibilityHelpNLS2.startDebugging = localize(857, null, "<keybinding:workbench.action.debug.start>");
  AccessibilityHelpNLS2.setBreakpoint = localize(858, null, "<keybinding:editor.debug.action.toggleInlineBreakpoint>");
  AccessibilityHelpNLS2.addToWatch = localize(859, null, "<keybinding:editor.debug.action.selectionToWatch>");
  AccessibilityHelpNLS2.debugExecuteSelection = localize(860, null, "<keybinding:editor.debug.action.selectionToRepl>");
})(AccessibilityHelpNLS || (AccessibilityHelpNLS = {}));
var InspectTokensNLS;
(function(InspectTokensNLS2) {
  InspectTokensNLS2.inspectTokensAction = localize(861, null);
})(InspectTokensNLS || (InspectTokensNLS = {}));
var GoToLineNLS;
(function(GoToLineNLS2) {
  GoToLineNLS2.gotoLineActionLabel = localize(862, null);
})(GoToLineNLS || (GoToLineNLS = {}));
var QuickHelpNLS;
(function(QuickHelpNLS2) {
  QuickHelpNLS2.helpQuickAccessActionLabel = localize(863, null);
})(QuickHelpNLS || (QuickHelpNLS = {}));
var QuickCommandNLS;
(function(QuickCommandNLS2) {
  QuickCommandNLS2.quickCommandActionLabel = localize(864, null);
  QuickCommandNLS2.quickCommandHelp = localize(865, null);
})(QuickCommandNLS || (QuickCommandNLS = {}));
var QuickOutlineNLS;
(function(QuickOutlineNLS2) {
  QuickOutlineNLS2.quickOutlineActionLabel = localize(866, null);
  QuickOutlineNLS2.quickOutlineByCategoryActionLabel = localize(867, null);
})(QuickOutlineNLS || (QuickOutlineNLS = {}));
var StandaloneCodeEditorNLS;
(function(StandaloneCodeEditorNLS2) {
  StandaloneCodeEditorNLS2.editorViewAccessibleLabel = localize(868, null);
})(StandaloneCodeEditorNLS || (StandaloneCodeEditorNLS = {}));
var ToggleHighContrastNLS;
(function(ToggleHighContrastNLS2) {
  ToggleHighContrastNLS2.toggleHighContrast = localize(869, null);
})(ToggleHighContrastNLS || (ToggleHighContrastNLS = {}));
var StandaloneServicesNLS;
(function(StandaloneServicesNLS2) {
  StandaloneServicesNLS2.bulkEditServiceSummary = localize(870, null);
})(StandaloneServicesNLS || (StandaloneServicesNLS = {}));

// out-build/vs/workbench/services/lifecycle/common/lifecycle.js
var $KL = $Qk("lifecycleService");
var WillShutdownJoinerOrder;
(function(WillShutdownJoinerOrder2) {
  WillShutdownJoinerOrder2[WillShutdownJoinerOrder2["Default"] = 1] = "Default";
  WillShutdownJoinerOrder2[WillShutdownJoinerOrder2["Last"] = 2] = "Last";
})(WillShutdownJoinerOrder || (WillShutdownJoinerOrder = {}));
var ShutdownReason;
(function(ShutdownReason2) {
  ShutdownReason2[ShutdownReason2["CLOSE"] = 1] = "CLOSE";
  ShutdownReason2[ShutdownReason2["QUIT"] = 2] = "QUIT";
  ShutdownReason2[ShutdownReason2["RELOAD"] = 3] = "RELOAD";
  ShutdownReason2[ShutdownReason2["LOAD"] = 4] = "LOAD";
})(ShutdownReason || (ShutdownReason = {}));
var StartupKind;
(function(StartupKind2) {
  StartupKind2[StartupKind2["NewWindow"] = 1] = "NewWindow";
  StartupKind2[StartupKind2["ReloadedWindow"] = 3] = "ReloadedWindow";
  StartupKind2[StartupKind2["ReopenedWindow"] = 4] = "ReopenedWindow";
})(StartupKind || (StartupKind = {}));
function $LL(startupKind) {
  switch (startupKind) {
    case 1:
      return "NewWindow";
    case 3:
      return "ReloadedWindow";
    case 4:
      return "ReopenedWindow";
  }
}
var LifecyclePhase;
(function(LifecyclePhase2) {
  LifecyclePhase2[LifecyclePhase2["Starting"] = 1] = "Starting";
  LifecyclePhase2[LifecyclePhase2["Ready"] = 2] = "Ready";
  LifecyclePhase2[LifecyclePhase2["Restored"] = 3] = "Restored";
  LifecyclePhase2[LifecyclePhase2["Eventually"] = 4] = "Eventually";
})(LifecyclePhase || (LifecyclePhase = {}));
function $ML(phase) {
  switch (phase) {
    case 1:
      return "Starting";
    case 2:
      return "Ready";
    case 3:
      return "Restored";
    case 4:
      return "Eventually";
  }
}

// out-build/vs/workbench/services/editor/common/editorPaneService.js
var $NL = $Qk("editorPaneService");

// out-build/vs/workbench/common/contributions.js
var Extensions2;
(function(Extensions9) {
  Extensions9.Workbench = "workbench.contributions.kind";
})(Extensions2 || (Extensions2 = {}));
var WorkbenchPhase;
(function(WorkbenchPhase2) {
  WorkbenchPhase2[WorkbenchPhase2["BlockStartup"] = 1] = "BlockStartup";
  WorkbenchPhase2[WorkbenchPhase2["BlockRestore"] = 2] = "BlockRestore";
  WorkbenchPhase2[WorkbenchPhase2["AfterRestored"] = 3] = "AfterRestored";
  WorkbenchPhase2[WorkbenchPhase2["Eventually"] = 4] = "Eventually";
})(WorkbenchPhase || (WorkbenchPhase = {}));
function isOnEditorWorkbenchContributionInstantiation(obj) {
  const candidate = obj;
  return !!candidate && typeof candidate.editorTypeId === "string";
}
function toWorkbenchPhase(phase) {
  switch (phase) {
    case 3:
      return 3;
    case 4:
      return 4;
  }
}
function toLifecyclePhase(instantiation) {
  switch (instantiation) {
    case 1:
      return 1;
    case 2:
      return 2;
    case 3:
      return 3;
    case 4:
      return 4;
  }
}
var $OL = class _$OL extends $3c {
  constructor() {
    super(...arguments);
    this.m = /* @__PURE__ */ new Map();
    this.n = /* @__PURE__ */ new Map();
    this.r = /* @__PURE__ */ new Map();
    this.s = /* @__PURE__ */ new Map();
    this.t = this.B(new $2c());
    this.u = /* @__PURE__ */ new Map();
    this.w = new $gi();
    this.whenRestored = this.w.p;
  }
  static {
    this.INSTANCE = new _$OL();
  }
  static {
    this.a = 20;
  }
  static {
    this.b = 100;
  }
  get timings() {
    return this.u;
  }
  registerWorkbenchContribution2(id2, ctor, instantiation) {
    const contribution = { id: id2, ctor };
    if (this.c && this.f && this.g && this.h && this.j && (typeof instantiation === "number" && this.f.phase >= instantiation || typeof id2 === "string" && isOnEditorWorkbenchContributionInstantiation(instantiation) && this.j.didInstantiateEditorPane(instantiation.editorTypeId))) {
      this.F(this.c, this.g, this.h, contribution, typeof instantiation === "number" ? toLifecyclePhase(instantiation) : this.f.phase);
    } else {
      if (typeof instantiation === "number") {
        $Bc(this.m, toLifecyclePhase(instantiation), []).push(contribution);
      }
      if (typeof id2 === "string") {
        if (!this.r.has(id2)) {
          this.r.set(id2, contribution);
        } else {
          console.error(`IWorkbenchContributionsRegistry#registerWorkbenchContribution(): Can't register multiple contributions with same id '${id2}'`);
        }
        if (isOnEditorWorkbenchContributionInstantiation(instantiation)) {
          $Bc(this.n, instantiation.editorTypeId, []).push(contribution);
        }
      }
    }
  }
  registerWorkbenchContribution(ctor, phase) {
    this.registerWorkbenchContribution2(void 0, ctor, toWorkbenchPhase(phase));
  }
  getWorkbenchContribution(id2) {
    if (this.s.has(id2)) {
      return this.s.get(id2);
    }
    const instantiationService = this.c;
    const lifecycleService = this.f;
    const logService = this.g;
    const environmentService = this.h;
    if (!instantiationService || !lifecycleService || !logService || !environmentService) {
      throw new Error(`IWorkbenchContributionsRegistry#getContribution('${id2}'): cannot be called before registry started`);
    }
    const contribution = this.r.get(id2);
    if (!contribution) {
      throw new Error(`IWorkbenchContributionsRegistry#getContribution('${id2}'): contribution with that identifier is unknown.`);
    }
    if (lifecycleService.phase < 3) {
      logService.warn(`IWorkbenchContributionsRegistry#getContribution('${id2}'): contribution instantiated before LifecyclePhase.Restored!`);
    }
    this.F(instantiationService, logService, environmentService, contribution, lifecycleService.phase);
    const instance2 = this.s.get(id2);
    if (!instance2) {
      throw new Error(`IWorkbenchContributionsRegistry#getContribution('${id2}'): failed to create contribution.`);
    }
    return instance2;
  }
  start(accessor) {
    const instantiationService = this.c = accessor.get($Pk);
    const lifecycleService = this.f = accessor.get($KL);
    const logService = this.g = accessor.get($wn);
    const environmentService = this.h = accessor.get($Xk);
    const editorPaneService = this.j = accessor.get($NL);
    this.B(lifecycleService.onDidShutdown(() => {
      this.t.clear();
    }));
    for (const phase of [
      1,
      2,
      3,
      4
      /* LifecyclePhase.Eventually */
    ]) {
      this.z(instantiationService, lifecycleService, logService, environmentService, phase);
    }
    for (const editorTypeId of this.n.keys()) {
      if (editorPaneService.didInstantiateEditorPane(editorTypeId)) {
        this.y(editorTypeId, instantiationService, lifecycleService, logService, environmentService);
      }
    }
    this.B(editorPaneService.onWillInstantiateEditorPane((e) => this.y(e.typeId, instantiationService, lifecycleService, logService, environmentService)));
  }
  y(editorTypeId, instantiationService, lifecycleService, logService, environmentService) {
    const contributions = this.n.get(editorTypeId);
    if (contributions) {
      this.n.delete(editorTypeId);
      for (const contribution of contributions) {
        this.F(instantiationService, logService, environmentService, contribution, lifecycleService.phase);
      }
    }
  }
  z(instantiationService, lifecycleService, logService, environmentService, phase) {
    if (lifecycleService.phase >= phase) {
      this.C(instantiationService, logService, environmentService, phase);
    } else {
      lifecycleService.when(phase).then(() => this.C(instantiationService, logService, environmentService, phase));
    }
  }
  async C(instantiationService, logService, environmentService, phase) {
    const contributions = this.m.get(phase);
    if (contributions) {
      this.m.delete(phase);
      switch (phase) {
        case 1:
        case 2: {
          $S(`code/willCreateWorkbenchContributions/${phase}`);
          for (const contribution of contributions) {
            this.F(instantiationService, logService, environmentService, contribution, phase);
          }
          $S(`code/didCreateWorkbenchContributions/${phase}`);
          break;
        }
        case 3:
        case 4: {
          if (phase === 4) {
            await this.w.p;
          }
          this.D(contributions, instantiationService, logService, environmentService, phase);
          break;
        }
      }
    }
  }
  D(contributions, instantiationService, logService, environmentService, phase) {
    $S(`code/willCreateWorkbenchContributions/${phase}`);
    let i2 = 0;
    const forcedTimeout = phase === 4 ? 3e3 : 500;
    const instantiateSome = (idle) => {
      while (i2 < contributions.length) {
        const contribution = contributions[i2++];
        this.F(instantiationService, logService, environmentService, contribution, phase);
        if (idle.timeRemaining() < 1) {
          $_h(instantiateSome, forcedTimeout);
          break;
        }
      }
      if (i2 === contributions.length) {
        $S(`code/didCreateWorkbenchContributions/${phase}`);
        if (phase === 3) {
          this.w.complete();
        }
      }
    };
    $_h(instantiateSome, forcedTimeout);
  }
  F(instantiationService, logService, environmentService, contribution, phase) {
    if (typeof contribution.id === "string" && this.s.has(contribution.id)) {
      return;
    }
    const now = Date.now();
    try {
      if (typeof contribution.id === "string") {
        $S(`code/willCreateWorkbenchContribution/${phase}/${contribution.id}`);
      }
      const instance2 = instantiationService.createInstance(contribution.ctor);
      if (typeof contribution.id === "string") {
        this.s.set(contribution.id, instance2);
        this.r.delete(contribution.id);
      }
      if ($Wc(instance2)) {
        this.t.add(instance2);
      }
    } catch (error) {
      logService.error(`Unable to create workbench contribution '${contribution.id ?? contribution.ctor.name}'.`, error);
    } finally {
      if (typeof contribution.id === "string") {
        $S(`code/didCreateWorkbenchContribution/${phase}/${contribution.id}`);
      }
    }
    if (typeof contribution.id === "string" || !environmentService.isBuilt) {
      const time = Date.now() - now;
      if (time > (phase < 3 ? _$OL.a : _$OL.b)) {
        logService.warn(`Creation of workbench contribution '${contribution.id ?? contribution.ctor.name}' took ${time}ms.`);
      }
      if (typeof contribution.id === "string") {
        let timingsForPhase = this.u.get(phase);
        if (!timingsForPhase) {
          timingsForPhase = [];
          this.u.set(phase, timingsForPhase);
        }
        timingsForPhase.push([contribution.id, time]);
      }
    }
  }
};
var $PL = $OL.INSTANCE.registerWorkbenchContribution2.bind($OL.INSTANCE);
var $QL = $OL.INSTANCE.getWorkbenchContribution.bind($OL.INSTANCE);
$Wn.add(Extensions2.Workbench, $OL.INSTANCE);

// out-build/vs/platform/extensionManagement/common/extensionManagement.js
var $cA = "^([a-z0-9A-Z][a-z0-9-A-Z]*)\\.([a-z0-9A-Z][a-z0-9-A-Z]*)$";
var $dA = new RegExp($cA);
var $eA = "__web_extension";
var $fA = "skipWalkthrough";
var $gA = "extensionInstallSource";
var $hA = "dependecyOrPackExtensionInstall";
var ExtensionInstallSource;
(function(ExtensionInstallSource2) {
  ExtensionInstallSource2["COMMAND"] = "command";
  ExtensionInstallSource2["SETTINGS_SYNC"] = "settingsSync";
})(ExtensionInstallSource || (ExtensionInstallSource = {}));
function $jA(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 $kA(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 $lA(platform, arch) {
  switch (platform) {
    case 3:
      if (arch === "x64") {
        return "win32-x64";
      }
      if (arch === "arm64") {
        return "win32-arm64";
      }
      return "unknown";
    case 2:
      if (arch === "x64") {
        return "linux-x64";
      }
      if (arch === "arm64") {
        return "linux-arm64";
      }
      if (arch === "arm") {
        return "linux-armhf";
      }
      return "unknown";
    case "alpine":
      if (arch === "x64") {
        return "alpine-x64";
      }
      if (arch === "arm64") {
        return "alpine-arm64";
      }
      return "unknown";
    case 1:
      if (arch === "x64") {
        return "darwin-x64";
      }
      if (arch === "arm64") {
        return "darwin-arm64";
      }
      return "unknown";
    case 0:
      return "web";
  }
}
function $mA(allTargetPlatforms, productTargetPlatform) {
  return productTargetPlatform === "web" && !allTargetPlatforms.includes(
    "web"
    /* TargetPlatform.WEB */
  );
}
function $nA(extensionTargetPlatform, allTargetPlatforms, productTargetPlatform) {
  if ($mA(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 $oA(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(SortOrder3) {
  SortOrder3[SortOrder3["Default"] = 0] = "Default";
  SortOrder3[SortOrder3["Ascending"] = 1] = "Ascending";
  SortOrder3[SortOrder3["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 $pA = $Qk("extensionGalleryService");
var ExtensionGalleryErrorCode;
(function(ExtensionGalleryErrorCode2) {
  ExtensionGalleryErrorCode2["Timeout"] = "Timeout";
  ExtensionGalleryErrorCode2["Cancelled"] = "Cancelled";
  ExtensionGalleryErrorCode2["Failed"] = "Failed";
  ExtensionGalleryErrorCode2["DownloadFailedWriting"] = "DownloadFailedWriting";
  ExtensionGalleryErrorCode2["Offline"] = "Offline";
})(ExtensionGalleryErrorCode || (ExtensionGalleryErrorCode = {}));
var $qA = 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["NotSigned"] = "NotSigned";
  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 $rA = class extends Error {
  constructor(message, code) {
    super(message);
    this.code = code;
    this.name = code;
  }
};
var $sA = $Qk("extensionManagementService");
var $tA = "extensionsIdentifiers/disabled";
var $uA = "extensionsIdentifiers/enabled";
var $vA = $Qk("IGlobalExtensionEnablementService");
var $wA = $Qk("IExtensionTipsService");
var $xA = $Qk("IAllowedExtensionsService");
async function $yA(location3, fileService) {
  const stat = await fileService.resolve(location3);
  if (stat.children) {
    const sizes = await Promise.all(stat.children.map((c) => $yA(c.resource, fileService)));
    return sizes.reduce((r2, s) => r2 + s, 0);
  }
  return stat.size ?? 0;
}
var $zA = localize2(1820, "Extensions");
var $AA = localize2(1821, "Preferences");
var $BA = "extensions.gallery.useUnpkgResourceApi";
var $CA = "extensions.allowed";

// out-build/vs/platform/product/common/productService.js
var $Vu = $Qk("productService");
var $Wu = "vscode://schemas/vscode-product";

// out-build/vs/platform/extensionManagement/common/implicitActivationEvents.js
var $eN = class {
  constructor() {
    this.a = /* @__PURE__ */ new Map();
    this.b = /* @__PURE__ */ new WeakMap();
  }
  register(extensionPointName, generator) {
    this.a.set(extensionPointName, generator);
  }
  /**
   * This can run correctly only on the renderer process because that is the only place
   * where all extension points and all implicit activation events generators are known.
   */
  readActivationEvents(extensionDescription) {
    if (!this.b.has(extensionDescription)) {
      this.b.set(extensionDescription, this.c(extensionDescription));
    }
    return this.b.get(extensionDescription);
  }
  /**
   * This can run correctly only on the renderer process because that is the only place
   * where all extension points and all implicit activation events generators are known.
   */
  createActivationEventsMap(extensionDescriptions) {
    const result = /* @__PURE__ */ Object.create(null);
    for (const extensionDescription of extensionDescriptions) {
      const activationEvents = this.readActivationEvents(extensionDescription);
      if (activationEvents.length > 0) {
        result[$5z.toKey(extensionDescription.identifier)] = activationEvents;
      }
    }
    return result;
  }
  c(desc) {
    if (typeof desc.main === "undefined" && typeof desc.browser === "undefined") {
      return [];
    }
    const activationEvents = Array.isArray(desc.activationEvents) ? desc.activationEvents.slice(0) : [];
    for (let i2 = 0; i2 < activationEvents.length; i2++) {
      if (activationEvents[i2] === "onUri") {
        activationEvents[i2] = `onUri:${$5z.toKey(desc.identifier)}`;
      }
    }
    if (!desc.contributes) {
      return activationEvents;
    }
    for (const extPointName in desc.contributes) {
      const generator = this.a.get(extPointName);
      if (!generator) {
        continue;
      }
      const contrib = desc.contributes[extPointName];
      const contribArr = Array.isArray(contrib) ? contrib : [contrib];
      try {
        generator(contribArr, activationEvents);
      } catch (err) {
        $gb(err);
      }
    }
    return activationEvents;
  }
};
var $fN = new $eN();

// 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",
    version: 2
  },
  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"
  },
  chatEditing: {
    proposal: "https://raw.githubusercontent.com/microsoft/vscode/main/src/vscode-dts/vscode.proposed.chatEditing.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"
  },
  chatReferenceBinaryData: {
    proposal: "https://raw.githubusercontent.com/microsoft/vscode/main/src/vscode-dts/vscode.proposed.chatReferenceBinaryData.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"
  },
  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"
  },
  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"
  },
  fileSearchProvider2: {
    proposal: "https://raw.githubusercontent.com/microsoft/vscode/main/src/vscode-dts/vscode.proposed.fileSearchProvider2.d.ts"
  },
  findFiles2: {
    proposal: "https://raw.githubusercontent.com/microsoft/vscode/main/src/vscode-dts/vscode.proposed.findFiles2.d.ts",
    version: 2
  },
  findTextInFiles: {
    proposal: "https://raw.githubusercontent.com/microsoft/vscode/main/src/vscode-dts/vscode.proposed.findTextInFiles.d.ts"
  },
  findTextInFiles2: {
    proposal: "https://raw.githubusercontent.com/microsoft/vscode/main/src/vscode-dts/vscode.proposed.findTextInFiles2.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"
  },
  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"
  },
  nativeWindowHandle: {
    proposal: "https://raw.githubusercontent.com/microsoft/vscode/main/src/vscode-dts/vscode.proposed.nativeWindowHandle.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"
  },
  terminalCompletionProvider: {
    proposal: "https://raw.githubusercontent.com/microsoft/vscode/main/src/vscode-dts/vscode.proposed.terminalCompletionProvider.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"
  },
  textEditorDiffInformation: {
    proposal: "https://raw.githubusercontent.com/microsoft/vscode/main/src/vscode-dts/vscode.proposed.textEditorDiffInformation.d.ts"
  },
  textSearchComplete2: {
    proposal: "https://raw.githubusercontent.com/microsoft/vscode/main/src/vscode-dts/vscode.proposed.textSearchComplete2.d.ts"
  },
  textSearchProvider: {
    proposal: "https://raw.githubusercontent.com/microsoft/vscode/main/src/vscode-dts/vscode.proposed.textSearchProvider.d.ts"
  },
  textSearchProvider2: {
    proposal: "https://raw.githubusercontent.com/microsoft/vscode/main/src/vscode-dts/vscode.proposed.textSearchProvider2.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"
  },
  valueSelectionInQuickPick: {
    proposal: "https://raw.githubusercontent.com/microsoft/vscode/main/src/vscode-dts/vscode.proposed.valueSelectionInQuickPick.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/workbench/services/extensions/common/extensionsRegistry.js
var schemaRegistry3 = $Wn.as($Xn.JSONContribution);
var $oN = class {
  constructor(messageHandler, extension, extensionPointId) {
    this.a = messageHandler;
    this.b = extension;
    this.c = extensionPointId;
  }
  d(type, message) {
    this.a({
      type,
      message,
      extensionId: this.b.identifier,
      extensionPointId: this.c
    });
  }
  error(message) {
    this.d(severity_default.Error, message);
  }
  warn(message) {
    this.d(severity_default.Warning, message);
  }
  info(message) {
    this.d(severity_default.Info, message);
  }
};
var $pN = class _$pN {
  static a(arr) {
    const result = new $6z();
    for (let i2 = 0, len = arr.length; i2 < len; i2++) {
      result.add(arr[i2].description.identifier);
    }
    return result;
  }
  static compute(previous, current) {
    if (!previous || !previous.length) {
      return new _$pN(current, []);
    }
    if (!current || !current.length) {
      return new _$pN([], previous);
    }
    const previousSet = this.a(previous);
    const currentSet = this.a(current);
    const added = current.filter((user) => !previousSet.has(user.description.identifier));
    const removed = previous.filter((user) => !currentSet.has(user.description.identifier));
    return new _$pN(added, removed);
  }
  constructor(added, removed) {
    this.added = added;
    this.removed = removed;
  }
};
var $qN = class {
  constructor(name, defaultExtensionKind, canHandleResolver) {
    this.name = name;
    this.defaultExtensionKind = defaultExtensionKind;
    this.canHandleResolver = canHandleResolver;
    this.a = null;
    this.b = null;
    this.c = null;
  }
  setHandler(handler) {
    if (this.a !== null) {
      throw new Error("Handler already set!");
    }
    this.a = handler;
    this.d();
    return {
      dispose: () => {
        this.a = null;
      }
    };
  }
  acceptUsers(users) {
    this.c = $pN.compute(this.b, users);
    this.b = users;
    this.d();
  }
  d() {
    if (this.a === null || this.b === null || this.c === null) {
      return;
    }
    try {
      this.a(this.b, this.c);
    } catch (err) {
      $gb(err);
    }
  }
};
var extensionKindSchema = {
  type: "string",
  enum: [
    "ui",
    "workspace"
  ],
  enumDescriptions: [
    localize(12808, null),
    localize(12809, null)
  ]
};
var schemaId = "vscode://schemas/vscode-extensions";
var $rN = {
  properties: {
    engines: {
      type: "object",
      description: localize(12810, null),
      properties: {
        "vscode": {
          type: "string",
          description: localize(12811, null),
          default: "^1.22.0"
        }
      }
    },
    publisher: {
      description: localize(12812, null),
      type: "string"
    },
    displayName: {
      description: localize(12813, null),
      type: "string"
    },
    categories: {
      description: localize(12814, null),
      type: "array",
      uniqueItems: true,
      items: {
        oneOf: [
          {
            type: "string",
            enum: $4z
          },
          {
            type: "string",
            const: "Languages",
            deprecationMessage: localize(12815, null)
          }
        ]
      }
    },
    galleryBanner: {
      type: "object",
      description: localize(12816, null),
      properties: {
        color: {
          description: localize(12817, null),
          type: "string"
        },
        theme: {
          description: localize(12818, null),
          type: "string",
          enum: ["dark", "light"]
        }
      }
    },
    contributes: {
      description: localize(12819, null),
      type: "object",
      properties: {
        // extensions will fill in
      },
      default: {}
    },
    preview: {
      type: "boolean",
      description: localize(12820, null)
    },
    enableProposedApi: {
      type: "boolean",
      deprecationMessage: localize(12821, null)
    },
    enabledApiProposals: {
      markdownDescription: localize(12822, null),
      type: "array",
      uniqueItems: true,
      items: {
        type: "string",
        enum: Object.keys(allApiProposals).map((proposalName) => proposalName),
        markdownEnumDescriptions: Object.values(allApiProposals).map((value) => value.proposal)
      }
    },
    api: {
      markdownDescription: localize(12823, null),
      type: "string",
      enum: ["none"],
      enumDescriptions: [
        localize(12824, null)
      ]
    },
    activationEvents: {
      description: localize(12825, null),
      type: "array",
      items: {
        type: "string",
        defaultSnippets: [
          {
            label: "onWebviewPanel",
            description: localize(12826, null),
            body: "onWebviewPanel:viewType"
          },
          {
            label: "onLanguage",
            description: localize(12827, null),
            body: "onLanguage:${1:languageId}"
          },
          {
            label: "onCommand",
            description: localize(12828, null),
            body: "onCommand:${2:commandId}"
          },
          {
            label: "onDebug",
            description: localize(12829, null),
            body: "onDebug"
          },
          {
            label: "onDebugInitialConfigurations",
            description: localize(12830, null),
            body: "onDebugInitialConfigurations"
          },
          {
            label: "onDebugDynamicConfigurations",
            description: localize(12831, null),
            body: "onDebugDynamicConfigurations"
          },
          {
            label: "onDebugResolve",
            description: localize(12832, null),
            body: "onDebugResolve:${6:type}"
          },
          {
            label: "onDebugAdapterProtocolTracker",
            description: localize(12833, null),
            body: "onDebugAdapterProtocolTracker:${6:type}"
          },
          {
            label: "workspaceContains",
            description: localize(12834, null),
            body: "workspaceContains:${4:filePattern}"
          },
          {
            label: "onStartupFinished",
            description: localize(12835, null),
            body: "onStartupFinished"
          },
          {
            label: "onTaskType",
            description: localize(12836, null),
            body: "onTaskType:${1:taskType}"
          },
          {
            label: "onFileSystem",
            description: localize(12837, null),
            body: "onFileSystem:${1:scheme}"
          },
          {
            label: "onEditSession",
            description: localize(12838, null),
            body: "onEditSession:${1:scheme}"
          },
          {
            label: "onSearch",
            description: localize(12839, null),
            body: "onSearch:${7:scheme}"
          },
          {
            label: "onView",
            body: "onView:${5:viewId}",
            description: localize(12840, null)
          },
          {
            label: "onUri",
            body: "onUri",
            description: localize(12841, null)
          },
          {
            label: "onOpenExternalUri",
            body: "onOpenExternalUri",
            description: localize(12842, null)
          },
          {
            label: "onCustomEditor",
            body: "onCustomEditor:${9:viewType}",
            description: localize(12843, null)
          },
          {
            label: "onNotebook",
            body: "onNotebook:${1:type}",
            description: localize(12844, null)
          },
          {
            label: "onAuthenticationRequest",
            body: "onAuthenticationRequest:${11:authenticationProviderId}",
            description: localize(12845, null)
          },
          {
            label: "onRenderer",
            description: localize(12846, null),
            body: "onRenderer:${11:rendererId}"
          },
          {
            label: "onTerminalProfile",
            body: "onTerminalProfile:${1:terminalId}",
            description: localize(12847, null)
          },
          {
            label: "onTerminalQuickFixRequest",
            body: "onTerminalQuickFixRequest:${1:quickFixId}",
            description: localize(12848, null)
          },
          {
            label: "onWalkthrough",
            body: "onWalkthrough:${1:walkthroughID}",
            description: localize(12849, null)
          },
          {
            label: "onIssueReporterOpened",
            body: "onIssueReporterOpened",
            description: localize(12850, null)
          },
          {
            label: "onChatParticipant",
            body: "onChatParticipant:${1:participantId}",
            description: localize(12851, null)
          },
          {
            label: "onLanguageModelTool",
            body: "onLanguageModelTool:${1:toolId}",
            description: localize(12852, null)
          },
          {
            label: "onTerminalCompletionsRequested",
            body: "onTerminalCompletionsRequested",
            description: localize(12853, null)
          },
          {
            label: "*",
            description: localize(12854, null),
            body: "*"
          }
        ]
      }
    },
    badges: {
      type: "array",
      description: localize(12855, null),
      items: {
        type: "object",
        required: ["url", "href", "description"],
        properties: {
          url: {
            type: "string",
            description: localize(12856, null)
          },
          href: {
            type: "string",
            description: localize(12857, null)
          },
          description: {
            type: "string",
            description: localize(12858, null)
          }
        }
      }
    },
    markdown: {
      type: "string",
      description: localize(12859, null),
      enum: ["github", "standard"],
      default: "github"
    },
    qna: {
      default: "marketplace",
      description: localize(12860, null),
      anyOf: [
        {
          type: ["string", "boolean"],
          enum: ["marketplace", false]
        },
        {
          type: "string"
        }
      ]
    },
    extensionDependencies: {
      description: localize(12861, null),
      type: "array",
      uniqueItems: true,
      items: {
        type: "string",
        pattern: $cA
      }
    },
    extensionPack: {
      description: localize(12862, null),
      type: "array",
      uniqueItems: true,
      items: {
        type: "string",
        pattern: $cA
      }
    },
    extensionKind: {
      description: localize(12863, null),
      type: "array",
      items: extensionKindSchema,
      default: ["workspace"],
      defaultSnippets: [
        {
          body: ["ui"],
          description: localize(12864, null)
        },
        {
          body: ["workspace"],
          description: localize(12865, null)
        },
        {
          body: ["ui", "workspace"],
          description: localize(12866, null)
        },
        {
          body: ["workspace", "ui"],
          description: localize(12867, null)
        },
        {
          body: [],
          description: localize(12868, null)
        }
      ]
    },
    capabilities: {
      description: localize(12869, null),
      type: "object",
      properties: {
        virtualWorkspaces: {
          description: localize(12870, null),
          type: ["boolean", "object"],
          defaultSnippets: [
            { label: "limited", body: { supported: "${1:limited}", description: "${2}" } },
            { label: "false", body: { supported: false, description: "${2}" } }
          ],
          default: true.valueOf,
          properties: {
            supported: {
              markdownDescription: localize(12871, null),
              type: ["string", "boolean"],
              enum: ["limited", true, false],
              enumDescriptions: [
                localize(12872, null),
                localize(12873, null),
                localize(12874, null)
              ]
            },
            description: {
              type: "string",
              markdownDescription: localize(12875, null)
            }
          }
        },
        untrustedWorkspaces: {
          description: localize(12876, null),
          type: "object",
          required: ["supported"],
          defaultSnippets: [
            { body: { supported: "${1:limited}", description: "${2}" } }
          ],
          properties: {
            supported: {
              markdownDescription: localize(12877, null),
              type: ["string", "boolean"],
              enum: ["limited", true, false],
              enumDescriptions: [
                localize(12878, null),
                localize(12879, null),
                localize(12880, null)
              ]
            },
            restrictedConfigurations: {
              description: localize(12881, null),
              type: "array",
              items: {
                type: "string"
              }
            },
            description: {
              type: "string",
              markdownDescription: localize(12882, null)
            }
          }
        }
      }
    },
    sponsor: {
      description: localize(12883, null),
      type: "object",
      defaultSnippets: [
        { body: { url: "${1:https:}" } }
      ],
      properties: {
        "url": {
          description: localize(12884, null),
          type: "string"
        }
      }
    },
    scripts: {
      type: "object",
      properties: {
        "vscode:prepublish": {
          description: localize(12885, null),
          type: "string"
        },
        "vscode:uninstall": {
          description: localize(12886, null),
          type: "string"
        }
      }
    },
    icon: {
      type: "string",
      description: localize(12887, null)
    },
    l10n: {
      type: "string",
      description: localize(12888, null)
    },
    pricing: {
      type: "string",
      markdownDescription: localize(12889, null),
      enum: ["Free", "Trial"],
      default: "Free"
    }
  }
};
var $sN = class {
  constructor() {
    this.a = /* @__PURE__ */ new Map();
  }
  registerExtensionPoint(desc) {
    if (this.a.has(desc.extensionPoint)) {
      throw new Error("Duplicate extension point: " + desc.extensionPoint);
    }
    const result = new $qN(desc.extensionPoint, desc.defaultExtensionKind, desc.canHandleResolver);
    this.a.set(desc.extensionPoint, result);
    if (desc.activationEventsGenerator) {
      $fN.register(desc.extensionPoint, desc.activationEventsGenerator);
    }
    $rN.properties["contributes"].properties[desc.extensionPoint] = desc.jsonSchema;
    schemaRegistry3.registerSchema(schemaId, $rN);
    return result;
  }
  getExtensionPoints() {
    return Array.from(this.a.values());
  }
};
var PRExtensions = {
  ExtensionsRegistry: "ExtensionsRegistry"
};
$Wn.add(PRExtensions.ExtensionsRegistry, new $sN());
var $tN = $Wn.as(PRExtensions.ExtensionsRegistry);
schemaRegistry3.registerSchema(schemaId, $rN);
schemaRegistry3.registerSchema($Wu, {
  properties: {
    extensionEnabledApiProposals: {
      description: localize(12890, null),
      type: "object",
      properties: {},
      additionalProperties: {
        anyOf: [{
          type: "array",
          uniqueItems: true,
          items: {
            type: "string",
            enum: Object.keys(allApiProposals),
            markdownEnumDescriptions: Object.values(allApiProposals).map((value) => value.proposal)
          }
        }]
      }
    }
  }
});

// out-build/vs/workbench/services/extensionManagement/common/extensionFeatures.js
var Extensions3;
(function(Extensions9) {
  Extensions9.ExtensionFeaturesRegistry = "workbench.registry.extensionFeatures";
})(Extensions3 || (Extensions3 = {}));
var $wlb = $Qk("IExtensionFeaturesManagementService");
var ExtensionFeaturesRegistry = class {
  constructor() {
    this.a = /* @__PURE__ */ new Map();
  }
  registerExtensionFeature(descriptor) {
    if (this.a.has(descriptor.id)) {
      throw new Error(`Extension feature with id '${descriptor.id}' already exists`);
    }
    this.a.set(descriptor.id, descriptor);
    return {
      dispose: () => this.a.delete(descriptor.id)
    };
  }
  getExtensionFeature(id2) {
    return this.a.get(id2);
  }
  getExtensionFeatures() {
    return Array.from(this.a.values());
  }
};
$Wn.add(Extensions3.ExtensionFeaturesRegistry, new ExtensionFeaturesRegistry());

// out-build/vs/workbench/api/common/jsonValidationExtensionPoint.js
var configurationExtPoint = $tN.registerExtensionPoint({
  extensionPoint: "jsonValidation",
  defaultExtensionKind: ["workspace", "web"],
  jsonSchema: {
    description: localize(2773, null),
    type: "array",
    defaultSnippets: [{ body: [{ fileMatch: "${1:file.json}", url: "${2:url}" }] }],
    items: {
      type: "object",
      defaultSnippets: [{ body: { fileMatch: "${1:file.json}", url: "${2:url}" } }],
      properties: {
        fileMatch: {
          type: ["string", "array"],
          description: localize(2774, null),
          items: {
            type: ["string"]
          }
        },
        url: {
          description: localize(2775, null),
          type: "string"
        }
      }
    }
  }
});
var $xlb = class {
  constructor() {
    configurationExtPoint.setHandler((extensions) => {
      for (const extension of extensions) {
        const extensionValue = extension.value;
        const collector = extension.collector;
        const extensionLocation = extension.description.extensionLocation;
        if (!extensionValue || !Array.isArray(extensionValue)) {
          collector.error(localize(2776, null));
          return;
        }
        extensionValue.forEach((extension2) => {
          if (!$zg(extension2.fileMatch) && !(Array.isArray(extension2.fileMatch) && extension2.fileMatch.every($zg))) {
            collector.error(localize(2777, null));
            return;
          }
          const uri = extension2.url;
          if (!$zg(uri)) {
            collector.error(localize(2778, null));
            return;
          }
          if (uri.startsWith("./")) {
            try {
              const colorThemeLocation = $vh(extensionLocation, uri);
              if (!$ph(colorThemeLocation, extensionLocation)) {
                collector.warn(localize(2779, null, configurationExtPoint.name, colorThemeLocation.toString(), extensionLocation.path));
              }
            } catch (e) {
              collector.error(localize(2780, null, e.message));
            }
          } else if (!/^[^:/?#]+:\/\//.test(uri)) {
            collector.error(localize(2781, null));
            return;
          }
        });
      }
    });
  }
};
var JSONValidationDataRenderer = class extends $3c {
  constructor() {
    super(...arguments);
    this.type = "table";
  }
  shouldRender(manifest) {
    return !!manifest.contributes?.jsonValidation;
  }
  render(manifest) {
    const contrib = manifest.contributes?.jsonValidation || [];
    if (!contrib.length) {
      return { data: { headers: [], rows: [] }, dispose: () => {
      } };
    }
    const headers = [
      localize(2782, null),
      localize(2783, null)
    ];
    const rows = contrib.map((v) => {
      return [
        new $bm().appendMarkdown(`\`${Array.isArray(v.fileMatch) ? v.fileMatch.join(", ") : v.fileMatch}\``),
        v.url
      ];
    });
    return {
      data: {
        headers,
        rows
      },
      dispose: () => {
      }
    };
  }
};
$Wn.as(Extensions3.ExtensionFeaturesRegistry).registerExtensionFeature({
  id: "jsonValidation",
  label: localize(2784, null),
  access: {
    canToggle: false
  },
  renderer: new $Nk(JSONValidationDataRenderer)
});

// out-build/vs/workbench/services/themes/common/colorExtensionPoint.js
var colorRegistry2 = $Wn.as($3n.ColorContribution);
var colorReferenceSchema = colorRegistry2.getColorReferenceSchema();
var colorIdPattern = "^\\w+[.\\w+]*$";
var configurationExtPoint2 = $tN.registerExtensionPoint({
  extensionPoint: "colors",
  jsonSchema: {
    description: localize(13171, null),
    type: "array",
    items: {
      type: "object",
      properties: {
        id: {
          type: "string",
          description: localize(13172, null),
          pattern: colorIdPattern,
          patternErrorMessage: localize(13173, null)
        },
        description: {
          type: "string",
          description: localize(13174, null)
        },
        defaults: {
          type: "object",
          properties: {
            light: {
              description: localize(13175, null),
              type: "string",
              anyOf: [
                colorReferenceSchema,
                { type: "string", format: "color-hex" }
              ]
            },
            dark: {
              description: localize(13176, null),
              type: "string",
              anyOf: [
                colorReferenceSchema,
                { type: "string", format: "color-hex" }
              ]
            },
            highContrast: {
              description: localize(13177, null),
              type: "string",
              anyOf: [
                colorReferenceSchema,
                { type: "string", format: "color-hex" }
              ]
            },
            highContrastLight: {
              description: localize(13178, null),
              type: "string",
              anyOf: [
                colorReferenceSchema,
                { type: "string", format: "color-hex" }
              ]
            }
          },
          required: ["light", "dark"]
        }
      }
    }
  }
});
var $ylb = class {
  constructor() {
    configurationExtPoint2.setHandler((extensions, delta) => {
      for (const extension of delta.added) {
        const extensionValue = extension.value;
        const collector = extension.collector;
        if (!extensionValue || !Array.isArray(extensionValue)) {
          collector.error(localize(13179, null));
          return;
        }
        const parseColorValue = (s, name) => {
          if (s.length > 0) {
            if (s[0] === "#") {
              return $Vn.Format.CSS.parseHex(s);
            } else {
              return s;
            }
          }
          collector.error(localize(13180, null, name));
          return $Vn.red;
        };
        for (const colorContribution of extensionValue) {
          if (typeof colorContribution.id !== "string" || colorContribution.id.length === 0) {
            collector.error(localize(13181, null));
            return;
          }
          if (!colorContribution.id.match(colorIdPattern)) {
            collector.error(localize(13182, null));
            return;
          }
          if (typeof colorContribution.description !== "string" || colorContribution.id.length === 0) {
            collector.error(localize(13183, null));
            return;
          }
          const defaults = colorContribution.defaults;
          if (!defaults || typeof defaults !== "object" || typeof defaults.light !== "string" || typeof defaults.dark !== "string") {
            collector.error(localize(13184, null));
            return;
          }
          if (defaults.highContrast && typeof defaults.highContrast !== "string") {
            collector.error(localize(13185, null));
            return;
          }
          if (defaults.highContrastLight && typeof defaults.highContrastLight !== "string") {
            collector.error(localize(13186, null));
            return;
          }
          colorRegistry2.registerColor(colorContribution.id, {
            light: parseColorValue(defaults.light, "configuration.colors.defaults.light"),
            dark: parseColorValue(defaults.dark, "configuration.colors.defaults.dark"),
            hcDark: parseColorValue(defaults.highContrast ?? defaults.dark, "configuration.colors.defaults.highContrast"),
            hcLight: parseColorValue(defaults.highContrastLight ?? defaults.light, "configuration.colors.defaults.highContrastLight")
          }, colorContribution.description);
        }
      }
      for (const extension of delta.removed) {
        const extensionValue = extension.value;
        for (const colorContribution of extensionValue) {
          colorRegistry2.deregisterColor(colorContribution.id);
        }
      }
    });
  }
};
var ColorDataRenderer = class extends $3c {
  constructor() {
    super(...arguments);
    this.type = "table";
  }
  shouldRender(manifest) {
    return !!manifest.contributes?.colors;
  }
  render(manifest) {
    const colors = manifest.contributes?.colors || [];
    if (!colors.length) {
      return { data: { headers: [], rows: [] }, dispose: () => {
      } };
    }
    const headers = [
      localize(13187, null),
      localize(13188, null),
      localize(13189, null),
      localize(13190, null),
      localize(13191, null)
    ];
    const toColor = (colorReference) => colorReference[0] === "#" ? $Vn.fromHex(colorReference) : void 0;
    const rows = colors.sort((a, b) => a.id.localeCompare(b.id)).map((color2) => {
      return [
        new $bm().appendMarkdown(`\`${color2.id}\``),
        color2.description,
        toColor(color2.defaults.dark) ?? new $bm().appendMarkdown(`\`${color2.defaults.dark}\``),
        toColor(color2.defaults.light) ?? new $bm().appendMarkdown(`\`${color2.defaults.light}\``),
        toColor(color2.defaults.highContrast) ?? new $bm().appendMarkdown(`\`${color2.defaults.highContrast}\``)
      ];
    });
    return {
      data: {
        headers,
        rows
      },
      dispose: () => {
      }
    };
  }
};
$Wn.as(Extensions3.ExtensionFeaturesRegistry).registerExtensionFeature({
  id: "colors",
  label: localize(13192, null),
  access: {
    canToggle: false
  },
  renderer: new $Nk(ColorDataRenderer)
});

// out-build/vs/workbench/services/themes/common/productIconThemeSchema.js
var $zlb = "^([\\w_-]+)$";
var $Alb = "^(normal|italic|(oblique[ \\w\\s-]+))$";
var $Blb = "^(normal|bold|lighter|bolder|(\\d{0-1000}))$";
var $Clb = "^([\\w_.%+-]+)$";
var $Dlb = "^woff|woff2|truetype|opentype|embedded-opentype|svg$";
var $Elb = "^([^\\\\]|\\\\[a-fA-F0-9]+)$";
var $Flb = "^#[0-9a-fA-F]{0,6}$";
var schemaId2 = "vscode://schemas/product-icon-theme";
var schema = {
  type: "object",
  allowComments: true,
  allowTrailingCommas: true,
  properties: {
    fonts: {
      type: "array",
      items: {
        type: "object",
        properties: {
          id: {
            type: "string",
            description: localize(13269, null),
            pattern: $zlb,
            patternErrorMessage: localize(13270, null)
          },
          src: {
            type: "array",
            description: localize(13271, null),
            items: {
              type: "object",
              properties: {
                path: {
                  type: "string",
                  description: localize(13272, null)
                },
                format: {
                  type: "string",
                  description: localize(13273, null),
                  enum: ["woff", "woff2", "truetype", "opentype", "embedded-opentype", "svg"]
                }
              },
              required: [
                "path",
                "format"
              ]
            }
          },
          weight: {
            type: "string",
            description: localize(13274, null),
            anyOf: [
              { enum: ["normal", "bold", "lighter", "bolder"] },
              { type: "string", pattern: $Blb }
            ]
          },
          style: {
            type: "string",
            description: localize(13275, null),
            anyOf: [
              { enum: ["normal", "italic", "oblique"] },
              { type: "string", pattern: $Alb }
            ]
          }
        },
        required: [
          "id",
          "src"
        ]
      }
    },
    iconDefinitions: {
      description: localize(13276, null),
      $ref: $$r
    }
  }
};
function $Glb() {
  const schemaRegistry7 = $Wn.as($Xn.JSONContribution);
  schemaRegistry7.registerSchema(schemaId2, schema);
}

// out-build/vs/workbench/services/themes/common/iconExtensionPoint.js
var iconRegistry2 = $Wn.as($8r.IconContribution);
var iconReferenceSchema = iconRegistry2.getIconReferenceSchema();
var iconIdPattern = `^${ThemeIcon.iconNameSegment}(-${ThemeIcon.iconNameSegment})+$`;
var iconConfigurationExtPoint = $tN.registerExtensionPoint({
  extensionPoint: "icons",
  jsonSchema: {
    description: localize(13254, null),
    type: "object",
    propertyNames: {
      pattern: iconIdPattern,
      description: localize(13255, null),
      patternErrorMessage: localize(13256, null)
    },
    additionalProperties: {
      type: "object",
      properties: {
        description: {
          type: "string",
          description: localize(13257, null)
        },
        default: {
          anyOf: [
            iconReferenceSchema,
            {
              type: "object",
              properties: {
                fontPath: {
                  description: localize(13258, null),
                  type: "string"
                },
                fontCharacter: {
                  description: localize(13259, null),
                  type: "string",
                  pattern: $Elb,
                  patternErrorMessage: localize(13260, null)
                }
              },
              required: ["fontPath", "fontCharacter"],
              defaultSnippets: [{ body: { fontPath: "${1:myiconfont.woff}", fontCharacter: "${2:\\\\E001}" } }]
            }
          ],
          description: localize(13261, null)
        }
      },
      required: ["description", "default"],
      defaultSnippets: [{ body: { description: "${1:my icon}", default: { fontPath: "${2:myiconfont.woff}", fontCharacter: "${3:\\\\E001}" } } }]
    },
    defaultSnippets: [{ body: { "${1:my-icon-id}": { description: "${2:my icon}", default: { fontPath: "${3:myiconfont.woff}", fontCharacter: "${4:\\\\E001}" } } } }]
  }
});
var $Hlb = class {
  constructor() {
    iconConfigurationExtPoint.setHandler((extensions, delta) => {
      for (const extension of delta.added) {
        const extensionValue = extension.value;
        const collector = extension.collector;
        if (!extensionValue || typeof extensionValue !== "object") {
          collector.error(localize(13262, null));
          return;
        }
        for (const id2 in extensionValue) {
          if (!id2.match(iconIdPattern)) {
            collector.error(localize(13263, null));
            return;
          }
          const iconContribution = extensionValue[id2];
          if (typeof iconContribution.description !== "string" || iconContribution.description.length === 0) {
            collector.error(localize(13264, null));
            return;
          }
          const defaultIcon = iconContribution.default;
          if (typeof defaultIcon === "string") {
            iconRegistry2.registerIcon(id2, { id: defaultIcon }, iconContribution.description);
          } else if (typeof defaultIcon === "object" && typeof defaultIcon.fontPath === "string" && typeof defaultIcon.fontCharacter === "string") {
            const fileExt = $sc(defaultIcon.fontPath).substring(1);
            const format2 = formatMap[fileExt];
            if (!format2) {
              collector.warn(localize(13265, null, fileExt));
              return;
            }
            if (!defaultIcon.fontCharacter.match($Elb)) {
              collector.warn(localize(13266, null));
              return;
            }
            const extensionLocation = extension.description.extensionLocation;
            const iconFontLocation = $vh(extensionLocation, defaultIcon.fontPath);
            const fontId = getFontId(extension.description, defaultIcon.fontPath);
            const definition = iconRegistry2.registerIconFont(fontId, { src: [{ location: iconFontLocation, format: format2 }] });
            if (!$ph(iconFontLocation, extensionLocation)) {
              collector.warn(localize(13267, null, iconFontLocation.path, extensionLocation.path));
              return;
            }
            iconRegistry2.registerIcon(id2, {
              fontCharacter: defaultIcon.fontCharacter,
              font: {
                id: fontId,
                definition
              }
            }, iconContribution.description);
          } else {
            collector.error(localize(13268, null));
          }
        }
      }
      for (const extension of delta.removed) {
        const extensionValue = extension.value;
        for (const id2 in extensionValue) {
          iconRegistry2.deregisterIcon(id2);
        }
      }
    });
  }
};
var formatMap = {
  "ttf": "truetype",
  "woff": "woff",
  "woff2": "woff2"
};
function getFontId(description, fontPath) {
  return $kc.join(description.identifier.value, fontPath);
}

// out-build/vs/platform/theme/common/tokenClassificationRegistry.js
var TOKEN_TYPE_WILDCARD = "*";
var TOKEN_CLASSIFIER_LANGUAGE_SEPARATOR = ":";
var CLASSIFIER_MODIFIER_SEPARATOR = ".";
var idPattern = "\\w+[-_\\w+]*";
var $Ilb = `^${idPattern}$`;
var selectorPattern = `^(${idPattern}|\\*)(\\${CLASSIFIER_MODIFIER_SEPARATOR}${idPattern})*(${TOKEN_CLASSIFIER_LANGUAGE_SEPARATOR}${idPattern})?$`;
var fontStylePattern = "^(\\s*(italic|bold|underline|strikethrough))*\\s*$";
var $Jlb = class {
  constructor(foreground, bold, underline, strikethrough, italic) {
    this.foreground = foreground;
    this.bold = bold;
    this.underline = underline;
    this.strikethrough = strikethrough;
    this.italic = italic;
  }
};
(function($Jlb2) {
  function toJSONObject(style) {
    return {
      _foreground: style.foreground === void 0 ? null : $Vn.Format.CSS.formatHexA(style.foreground, true),
      _bold: style.bold === void 0 ? null : style.bold,
      _underline: style.underline === void 0 ? null : style.underline,
      _italic: style.italic === void 0 ? null : style.italic,
      _strikethrough: style.strikethrough === void 0 ? null : style.strikethrough
    };
  }
  $Jlb2.toJSONObject = toJSONObject;
  function fromJSONObject(obj) {
    if (obj) {
      const boolOrUndef = (b) => typeof b === "boolean" ? b : void 0;
      const colorOrUndef = (s) => typeof s === "string" ? $Vn.fromHex(s) : void 0;
      return new $Jlb2(colorOrUndef(obj._foreground), boolOrUndef(obj._bold), boolOrUndef(obj._underline), boolOrUndef(obj._strikethrough), boolOrUndef(obj._italic));
    }
    return void 0;
  }
  $Jlb2.fromJSONObject = fromJSONObject;
  function equals(s1, s2) {
    if (s1 === s2) {
      return true;
    }
    return s1 !== void 0 && s2 !== void 0 && (s1.foreground instanceof $Vn ? s1.foreground.equals(s2.foreground) : s2.foreground === void 0) && s1.bold === s2.bold && s1.underline === s2.underline && s1.strikethrough === s2.strikethrough && s1.italic === s2.italic;
  }
  $Jlb2.equals = equals;
  function is(s) {
    return s instanceof $Jlb2;
  }
  $Jlb2.is = is;
  function fromData(data) {
    return new $Jlb2(data.foreground, data.bold, data.underline, data.strikethrough, data.italic);
  }
  $Jlb2.fromData = fromData;
  function fromSettings(foreground, fontStyle, bold, underline, strikethrough, italic) {
    let foregroundColor = void 0;
    if (foreground !== void 0) {
      foregroundColor = $Vn.fromHex(foreground);
    }
    if (fontStyle !== void 0) {
      bold = italic = underline = strikethrough = false;
      const expression = /italic|bold|underline|strikethrough/g;
      let match;
      while (match = expression.exec(fontStyle)) {
        switch (match[0]) {
          case "bold":
            bold = true;
            break;
          case "italic":
            italic = true;
            break;
          case "underline":
            underline = true;
            break;
          case "strikethrough":
            strikethrough = true;
            break;
        }
      }
    }
    return new $Jlb2(foregroundColor, bold, underline, strikethrough, italic);
  }
  $Jlb2.fromSettings = fromSettings;
})($Jlb || ($Jlb = {}));
var SemanticTokenRule;
(function(SemanticTokenRule2) {
  function fromJSONObject(registry4, o) {
    if (o && typeof o._selector === "string" && o._style) {
      const style = $Jlb.fromJSONObject(o._style);
      if (style) {
        try {
          return { selector: registry4.parseTokenSelector(o._selector), style };
        } catch (_ignore) {
        }
      }
    }
    return void 0;
  }
  SemanticTokenRule2.fromJSONObject = fromJSONObject;
  function toJSONObject(rule) {
    return {
      _selector: rule.selector.id,
      _style: $Jlb.toJSONObject(rule.style)
    };
  }
  SemanticTokenRule2.toJSONObject = toJSONObject;
  function equals(r1, r2) {
    if (r1 === r2) {
      return true;
    }
    return r1 !== void 0 && r2 !== void 0 && r1.selector && r2.selector && r1.selector.id === r2.selector.id && $Jlb.equals(r1.style, r2.style);
  }
  SemanticTokenRule2.equals = equals;
  function is(r2) {
    return r2 && r2.selector && typeof r2.selector.id === "string" && $Jlb.is(r2.style);
  }
  SemanticTokenRule2.is = is;
})(SemanticTokenRule || (SemanticTokenRule = {}));
var Extensions4 = {
  TokenClassificationContribution: "base.contributions.tokenClassification"
};
var TokenClassificationRegistry = class {
  constructor() {
    this.c = new $ze();
    this.onDidChangeSchema = this.c.event;
    this.d = 0;
    this.f = 1;
    this.j = [];
    this.m = {
      type: "object",
      properties: {},
      patternProperties: {
        [selectorPattern]: getStylingSchemeEntry()
      },
      //errorMessage: nls.localize('schema.token.errors', 'Valid token selectors have the form (*|tokenType)(.tokenModifier)*(:tokenLanguage)?.'),
      additionalProperties: false,
      definitions: {
        style: {
          type: "object",
          description: localize(2416, null),
          properties: {
            foreground: {
              type: "string",
              description: localize(2417, null),
              format: "color-hex",
              default: "#ff0000"
            },
            background: {
              type: "string",
              deprecationMessage: localize(2418, null)
            },
            fontStyle: {
              type: "string",
              description: localize(2419, null),
              pattern: fontStylePattern,
              patternErrorMessage: localize(2420, null),
              defaultSnippets: [
                { label: localize(2421, null), bodyText: '""' },
                { body: "italic" },
                { body: "bold" },
                { body: "underline" },
                { body: "strikethrough" },
                { body: "italic bold" },
                { body: "italic underline" },
                { body: "italic strikethrough" },
                { body: "bold underline" },
                { body: "bold strikethrough" },
                { body: "underline strikethrough" },
                { body: "italic bold underline" },
                { body: "italic bold strikethrough" },
                { body: "italic underline strikethrough" },
                { body: "bold underline strikethrough" },
                { body: "italic bold underline strikethrough" }
              ]
            },
            bold: {
              type: "boolean",
              description: localize(2422, null)
            },
            italic: {
              type: "boolean",
              description: localize(2423, null)
            },
            underline: {
              type: "boolean",
              description: localize(2424, null)
            },
            strikethrough: {
              type: "boolean",
              description: localize(2425, null)
            }
          },
          defaultSnippets: [{ body: { foreground: "${1:#FF0000}", fontStyle: "${2:bold}" } }]
        }
      }
    };
    this.g = /* @__PURE__ */ Object.create(null);
    this.h = /* @__PURE__ */ Object.create(null);
    this.l = /* @__PURE__ */ Object.create(null);
  }
  registerTokenType(id2, description, superType, deprecationMessage) {
    if (!id2.match($Ilb)) {
      throw new Error("Invalid token type id.");
    }
    if (superType && !superType.match($Ilb)) {
      throw new Error("Invalid token super type id.");
    }
    const num = this.d++;
    const tokenStyleContribution = { num, id: id2, superType, description, deprecationMessage };
    this.g[id2] = tokenStyleContribution;
    const stylingSchemeEntry = getStylingSchemeEntry(description, deprecationMessage);
    this.m.properties[id2] = stylingSchemeEntry;
    this.l = /* @__PURE__ */ Object.create(null);
  }
  registerTokenModifier(id2, description, deprecationMessage) {
    if (!id2.match($Ilb)) {
      throw new Error("Invalid token modifier id.");
    }
    const num = this.f;
    this.f = this.f * 2;
    const tokenStyleContribution = { num, id: id2, description, deprecationMessage };
    this.h[id2] = tokenStyleContribution;
    this.m.properties[`*.${id2}`] = getStylingSchemeEntry(description, deprecationMessage);
  }
  parseTokenSelector(selectorString, language) {
    const selector = $Klb(selectorString, language);
    if (!selector.type) {
      return {
        match: () => -1,
        id: "$invalid"
      };
    }
    return {
      match: (type, modifiers, language2) => {
        let score2 = 0;
        if (selector.language !== void 0) {
          if (selector.language !== language2) {
            return -1;
          }
          score2 += 10;
        }
        if (selector.type !== TOKEN_TYPE_WILDCARD) {
          const hierarchy = this.n(type);
          const level = hierarchy.indexOf(selector.type);
          if (level === -1) {
            return -1;
          }
          score2 += 100 - level;
        }
        for (const selectorModifier of selector.modifiers) {
          if (modifiers.indexOf(selectorModifier) === -1) {
            return -1;
          }
        }
        return score2 + selector.modifiers.length * 100;
      },
      id: `${[selector.type, ...selector.modifiers.sort()].join(".")}${selector.language !== void 0 ? ":" + selector.language : ""}`
    };
  }
  registerTokenStyleDefault(selector, defaults) {
    this.j.push({ selector, defaults });
  }
  deregisterTokenStyleDefault(selector) {
    const selectorString = selector.id;
    this.j = this.j.filter((r2) => r2.selector.id !== selectorString);
  }
  deregisterTokenType(id2) {
    delete this.g[id2];
    delete this.m.properties[id2];
    this.l = /* @__PURE__ */ Object.create(null);
  }
  deregisterTokenModifier(id2) {
    delete this.h[id2];
    delete this.m.properties[`*.${id2}`];
  }
  getTokenTypes() {
    return Object.keys(this.g).map((id2) => this.g[id2]);
  }
  getTokenModifiers() {
    return Object.keys(this.h).map((id2) => this.h[id2]);
  }
  getTokenStylingSchema() {
    return this.m;
  }
  getTokenStylingDefaultRules() {
    return this.j;
  }
  n(typeId2) {
    let hierarchy = this.l[typeId2];
    if (!hierarchy) {
      this.l[typeId2] = hierarchy = [typeId2];
      let type = this.g[typeId2];
      while (type && type.superType) {
        hierarchy.push(type.superType);
        type = this.g[type.superType];
      }
    }
    return hierarchy;
  }
  toString() {
    const sorter3 = (a, b) => {
      const cat1 = a.indexOf(".") === -1 ? 0 : 1;
      const cat2 = b.indexOf(".") === -1 ? 0 : 1;
      if (cat1 !== cat2) {
        return cat1 - cat2;
      }
      return a.localeCompare(b);
    };
    return Object.keys(this.g).sort(sorter3).map((k) => `- \`${k}\`: ${this.g[k].description}`).join("\n");
  }
};
var CHAR_LANGUAGE = TOKEN_CLASSIFIER_LANGUAGE_SEPARATOR.charCodeAt(0);
var CHAR_MODIFIER = CLASSIFIER_MODIFIER_SEPARATOR.charCodeAt(0);
function $Klb(s, defaultLanguage) {
  let k = s.length;
  let language = defaultLanguage;
  const modifiers = [];
  for (let i2 = k - 1; i2 >= 0; i2--) {
    const ch = s.charCodeAt(i2);
    if (ch === CHAR_LANGUAGE || ch === CHAR_MODIFIER) {
      const segment = s.substring(i2 + 1, k);
      k = i2;
      if (ch === CHAR_LANGUAGE) {
        language = segment;
      } else {
        modifiers.push(segment);
      }
    }
  }
  const type = s.substring(0, k);
  return { type, modifiers, language };
}
var tokenClassificationRegistry = createDefaultTokenClassificationRegistry();
$Wn.add(Extensions4.TokenClassificationContribution, tokenClassificationRegistry);
function createDefaultTokenClassificationRegistry() {
  const registry4 = new TokenClassificationRegistry();
  function registerTokenType(id2, description, scopesToProbe = [], superType, deprecationMessage) {
    registry4.registerTokenType(id2, description, superType, deprecationMessage);
    if (scopesToProbe) {
      registerTokenStyleDefault(id2, scopesToProbe);
    }
    return id2;
  }
  function registerTokenStyleDefault(selectorString, scopesToProbe) {
    try {
      const selector = registry4.parseTokenSelector(selectorString);
      registry4.registerTokenStyleDefault(selector, { scopesToProbe });
    } catch (e) {
      console.log(e);
    }
  }
  registerTokenType("comment", localize(2426, null), [["comment"]]);
  registerTokenType("string", localize(2427, null), [["string"]]);
  registerTokenType("keyword", localize(2428, null), [["keyword.control"]]);
  registerTokenType("number", localize(2429, null), [["constant.numeric"]]);
  registerTokenType("regexp", localize(2430, null), [["constant.regexp"]]);
  registerTokenType("operator", localize(2431, null), [["keyword.operator"]]);
  registerTokenType("namespace", localize(2432, null), [["entity.name.namespace"]]);
  registerTokenType("type", localize(2433, null), [["entity.name.type"], ["support.type"]]);
  registerTokenType("struct", localize(2434, null), [["entity.name.type.struct"]]);
  registerTokenType("class", localize(2435, null), [["entity.name.type.class"], ["support.class"]]);
  registerTokenType("interface", localize(2436, null), [["entity.name.type.interface"]]);
  registerTokenType("enum", localize(2437, null), [["entity.name.type.enum"]]);
  registerTokenType("typeParameter", localize(2438, null), [["entity.name.type.parameter"]]);
  registerTokenType("function", localize(2439, null), [["entity.name.function"], ["support.function"]]);
  registerTokenType("member", localize(2440, null), [], "method", "Deprecated use `method` instead");
  registerTokenType("method", localize(2441, null), [["entity.name.function.member"], ["support.function"]]);
  registerTokenType("macro", localize(2442, null), [["entity.name.function.preprocessor"]]);
  registerTokenType("variable", localize(2443, null), [["variable.other.readwrite"], ["entity.name.variable"]]);
  registerTokenType("parameter", localize(2444, null), [["variable.parameter"]]);
  registerTokenType("property", localize(2445, null), [["variable.other.property"]]);
  registerTokenType("enumMember", localize(2446, null), [["variable.other.enummember"]]);
  registerTokenType("event", localize(2447, null), [["variable.other.event"]]);
  registerTokenType("decorator", localize(2448, null), [["entity.name.decorator"], ["entity.name.function"]]);
  registerTokenType("label", localize(2449, null), void 0);
  registry4.registerTokenModifier("declaration", localize(2450, null), void 0);
  registry4.registerTokenModifier("documentation", localize(2451, null), void 0);
  registry4.registerTokenModifier("static", localize(2452, null), void 0);
  registry4.registerTokenModifier("abstract", localize(2453, null), void 0);
  registry4.registerTokenModifier("deprecated", localize(2454, null), void 0);
  registry4.registerTokenModifier("modification", localize(2455, null), void 0);
  registry4.registerTokenModifier("async", localize(2456, null), void 0);
  registry4.registerTokenModifier("readonly", localize(2457, null), void 0);
  registerTokenStyleDefault("variable.readonly", [["variable.other.constant"]]);
  registerTokenStyleDefault("property.readonly", [["variable.other.constant.property"]]);
  registerTokenStyleDefault("type.defaultLibrary", [["support.type"]]);
  registerTokenStyleDefault("class.defaultLibrary", [["support.class"]]);
  registerTokenStyleDefault("interface.defaultLibrary", [["support.class"]]);
  registerTokenStyleDefault("variable.defaultLibrary", [["support.variable"], ["support.other.variable"]]);
  registerTokenStyleDefault("variable.defaultLibrary.readonly", [["support.constant"]]);
  registerTokenStyleDefault("property.defaultLibrary", [["support.variable.property"]]);
  registerTokenStyleDefault("property.defaultLibrary.readonly", [["support.constant.property"]]);
  registerTokenStyleDefault("function.defaultLibrary", [["support.function"]]);
  registerTokenStyleDefault("member.defaultLibrary", [["support.function"]]);
  return registry4;
}
function $Llb() {
  return tokenClassificationRegistry;
}
function getStylingSchemeEntry(description, deprecationMessage) {
  return {
    description,
    deprecationMessage,
    defaultSnippets: [{ body: "${1:#ff0000}" }],
    anyOf: [
      {
        type: "string",
        format: "color-hex"
      },
      {
        $ref: "#/definitions/style"
      }
    ]
  };
}
var $Mlb = "vscode://schemas/token-styling";
var schemaRegistry4 = $Wn.as($Xn.JSONContribution);
schemaRegistry4.registerSchema($Mlb, tokenClassificationRegistry.getTokenStylingSchema());
var delayer3 = new $8h(() => schemaRegistry4.notifySchemaChanged($Mlb), 200);
tokenClassificationRegistry.onDidChangeSchema(() => {
  if (!delayer3.isScheduled()) {
    delayer3.schedule();
  }
});

// out-build/vs/workbench/services/themes/common/tokenClassificationExtensionPoint.js
var tokenClassificationRegistry2 = $Llb();
var tokenTypeExtPoint = $tN.registerExtensionPoint({
  extensionPoint: "semanticTokenTypes",
  jsonSchema: {
    description: localize(13334, null),
    type: "array",
    items: {
      type: "object",
      properties: {
        id: {
          type: "string",
          description: localize(13335, null),
          pattern: $Ilb,
          patternErrorMessage: localize(13336, null)
        },
        superType: {
          type: "string",
          description: localize(13337, null),
          pattern: $Ilb,
          patternErrorMessage: localize(13338, null)
        },
        description: {
          type: "string",
          description: localize(13339, null)
        }
      }
    }
  }
});
var tokenModifierExtPoint = $tN.registerExtensionPoint({
  extensionPoint: "semanticTokenModifiers",
  jsonSchema: {
    description: localize(13340, null),
    type: "array",
    items: {
      type: "object",
      properties: {
        id: {
          type: "string",
          description: localize(13341, null),
          pattern: $Ilb,
          patternErrorMessage: localize(13342, null)
        },
        description: {
          description: localize(13343, null)
        }
      }
    }
  }
});
var tokenStyleDefaultsExtPoint = $tN.registerExtensionPoint({
  extensionPoint: "semanticTokenScopes",
  jsonSchema: {
    description: localize(13344, null),
    type: "array",
    items: {
      type: "object",
      properties: {
        language: {
          description: localize(13345, null),
          type: "string"
        },
        scopes: {
          description: localize(13346, null),
          type: "object",
          additionalProperties: {
            type: "array",
            items: {
              type: "string"
            }
          }
        }
      }
    }
  }
});
var $Nlb = class {
  constructor() {
    function validateTypeOrModifier(contribution, extensionPoint2, collector) {
      if (typeof contribution.id !== "string" || contribution.id.length === 0) {
        collector.error(localize(13347, null, extensionPoint2));
        return false;
      }
      if (!contribution.id.match($Ilb)) {
        collector.error(localize(13348, null, extensionPoint2));
        return false;
      }
      const superType = contribution.superType;
      if (superType && !superType.match($Ilb)) {
        collector.error(localize(13349, null, extensionPoint2));
        return false;
      }
      if (typeof contribution.description !== "string" || contribution.id.length === 0) {
        collector.error(localize(13350, null, extensionPoint2));
        return false;
      }
      return true;
    }
    tokenTypeExtPoint.setHandler((extensions, delta) => {
      for (const extension of delta.added) {
        const extensionValue = extension.value;
        const collector = extension.collector;
        if (!extensionValue || !Array.isArray(extensionValue)) {
          collector.error(localize(13351, null));
          return;
        }
        for (const contribution of extensionValue) {
          if (validateTypeOrModifier(contribution, "semanticTokenType", collector)) {
            tokenClassificationRegistry2.registerTokenType(contribution.id, contribution.description, contribution.superType);
          }
        }
      }
      for (const extension of delta.removed) {
        const extensionValue = extension.value;
        for (const contribution of extensionValue) {
          tokenClassificationRegistry2.deregisterTokenType(contribution.id);
        }
      }
    });
    tokenModifierExtPoint.setHandler((extensions, delta) => {
      for (const extension of delta.added) {
        const extensionValue = extension.value;
        const collector = extension.collector;
        if (!extensionValue || !Array.isArray(extensionValue)) {
          collector.error(localize(13352, null));
          return;
        }
        for (const contribution of extensionValue) {
          if (validateTypeOrModifier(contribution, "semanticTokenModifier", collector)) {
            tokenClassificationRegistry2.registerTokenModifier(contribution.id, contribution.description);
          }
        }
      }
      for (const extension of delta.removed) {
        const extensionValue = extension.value;
        for (const contribution of extensionValue) {
          tokenClassificationRegistry2.deregisterTokenModifier(contribution.id);
        }
      }
    });
    tokenStyleDefaultsExtPoint.setHandler((extensions, delta) => {
      for (const extension of delta.added) {
        const extensionValue = extension.value;
        const collector = extension.collector;
        if (!extensionValue || !Array.isArray(extensionValue)) {
          collector.error(localize(13353, null));
          return;
        }
        for (const contribution of extensionValue) {
          if (contribution.language && typeof contribution.language !== "string") {
            collector.error(localize(13354, null));
            continue;
          }
          if (!contribution.scopes || typeof contribution.scopes !== "object") {
            collector.error(localize(13355, null));
            continue;
          }
          for (const selectorString in contribution.scopes) {
            const tmScopes = contribution.scopes[selectorString];
            if (!Array.isArray(tmScopes) || tmScopes.some((l) => typeof l !== "string")) {
              collector.error(localize(13356, null));
              continue;
            }
            try {
              const selector = tokenClassificationRegistry2.parseTokenSelector(selectorString, contribution.language);
              tokenClassificationRegistry2.registerTokenStyleDefault(selector, { scopesToProbe: tmScopes.map((s) => s.split(" ")) });
            } catch (e) {
              collector.error(localize(13357, null, selectorString));
            }
          }
        }
      }
      for (const extension of delta.removed) {
        const extensionValue = extension.value;
        for (const contribution of extensionValue) {
          for (const selectorString in contribution.scopes) {
            const tmScopes = contribution.scopes[selectorString];
            try {
              const selector = tokenClassificationRegistry2.parseTokenSelector(selectorString, contribution.language);
              tokenClassificationRegistry2.registerTokenStyleDefault(selector, { scopesToProbe: tmScopes.map((s) => s.split(" ")) });
            } catch (e) {
            }
          }
        }
      }
    });
  }
};

// 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 $ww(text2, ignoreTrivia = false) {
  let pos = 0;
  const len = text2.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 = text2.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 (text2.charCodeAt(pos) === 48) {
      pos++;
    } else {
      pos++;
      while (pos < text2.length && isDigit(text2.charCodeAt(pos))) {
        pos++;
      }
    }
    if (pos < text2.length && text2.charCodeAt(pos) === 46) {
      pos++;
      if (pos < text2.length && isDigit(text2.charCodeAt(pos))) {
        pos++;
        while (pos < text2.length && isDigit(text2.charCodeAt(pos))) {
          pos++;
        }
      } else {
        scanError = 3;
        return text2.substring(start, pos);
      }
    }
    let end = pos;
    if (pos < text2.length && (text2.charCodeAt(pos) === 69 || text2.charCodeAt(pos) === 101)) {
      pos++;
      if (pos < text2.length && text2.charCodeAt(pos) === 43 || text2.charCodeAt(pos) === 45) {
        pos++;
      }
      if (pos < text2.length && isDigit(text2.charCodeAt(pos))) {
        pos++;
        while (pos < text2.length && isDigit(text2.charCodeAt(pos))) {
          pos++;
        }
        end = pos;
      } else {
        scanError = 3;
      }
    }
    return text2.substring(start, end);
  }
  function scanString() {
    let result = "", start = pos;
    while (true) {
      if (pos >= len) {
        result += text2.substring(start, pos);
        scanError = 2;
        break;
      }
      const ch = text2.charCodeAt(pos);
      if (ch === 34) {
        result += text2.substring(start, pos);
        pos++;
        break;
      }
      if (ch === 92) {
        result += text2.substring(start, pos);
        pos++;
        if (pos >= len) {
          scanError = 2;
          break;
        }
        const ch2 = text2.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 += text2.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 = text2.charCodeAt(pos);
    if (isWhitespace2(code)) {
      do {
        pos++;
        value += String.fromCharCode(code);
        code = text2.charCodeAt(pos);
      } while (isWhitespace2(code));
      return token = 15;
    }
    if (isLineBreak(code)) {
      pos++;
      value += String.fromCharCode(code);
      if (code === 13 && text2.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 (text2.charCodeAt(pos + 1) === 47) {
          pos += 2;
          while (pos < len) {
            if (isLineBreak(text2.charCodeAt(pos))) {
              break;
            }
            pos++;
          }
          value = text2.substring(start, pos);
          return token = 12;
        }
        if (text2.charCodeAt(pos + 1) === 42) {
          pos += 2;
          const safeLength = len - 1;
          let commentClosed = false;
          while (pos < safeLength) {
            const ch = text2.charCodeAt(pos);
            if (ch === 42 && text2.charCodeAt(pos + 1) === 47) {
              pos += 2;
              commentClosed = true;
              break;
            }
            pos++;
          }
          if (!commentClosed) {
            pos++;
            scanError = 1;
          }
          value = text2.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(text2.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 = text2.charCodeAt(pos);
        }
        if (tokenOffset !== pos) {
          value = text2.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 (isWhitespace2(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 isWhitespace2(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 $xw(text2, position) {
  const segments = [];
  const earlyReturnException = new Object();
  let previousNode = void 0;
  const previousNodeInst = {
    value: {},
    offset: 0,
    length: 0,
    type: "object",
    parent: void 0
  };
  let isAtPropertyKey = false;
  function setPreviousNode(value, offset, length, type) {
    previousNodeInst.value = value;
    previousNodeInst.offset = offset;
    previousNodeInst.length = length;
    previousNodeInst.type = type;
    previousNodeInst.colonOffset = void 0;
    previousNode = previousNodeInst;
  }
  try {
    $Fw(text2, {
      onObjectBegin: (offset, length) => {
        if (position <= offset) {
          throw earlyReturnException;
        }
        previousNode = void 0;
        isAtPropertyKey = position > offset;
        segments.push("");
      },
      onObjectProperty: (name, offset, length) => {
        if (position < offset) {
          throw earlyReturnException;
        }
        setPreviousNode(name, offset, length, "property");
        segments[segments.length - 1] = name;
        if (position <= offset + length) {
          throw earlyReturnException;
        }
      },
      onObjectEnd: (offset, length) => {
        if (position <= offset) {
          throw earlyReturnException;
        }
        previousNode = void 0;
        segments.pop();
      },
      onArrayBegin: (offset, length) => {
        if (position <= offset) {
          throw earlyReturnException;
        }
        previousNode = void 0;
        segments.push(0);
      },
      onArrayEnd: (offset, length) => {
        if (position <= offset) {
          throw earlyReturnException;
        }
        previousNode = void 0;
        segments.pop();
      },
      onLiteralValue: (value, offset, length) => {
        if (position < offset) {
          throw earlyReturnException;
        }
        setPreviousNode(value, offset, length, $Gw(value));
        if (position <= offset + length) {
          throw earlyReturnException;
        }
      },
      onSeparator: (sep2, offset, length) => {
        if (position <= offset) {
          throw earlyReturnException;
        }
        if (sep2 === ":" && previousNode && previousNode.type === "property") {
          previousNode.colonOffset = offset;
          isAtPropertyKey = false;
          previousNode = void 0;
        } else if (sep2 === ",") {
          const last = segments[segments.length - 1];
          if (typeof last === "number") {
            segments[segments.length - 1] = last + 1;
          } else {
            isAtPropertyKey = true;
            segments[segments.length - 1] = "";
          }
          previousNode = void 0;
        }
      }
    });
  } catch (e) {
    if (e !== earlyReturnException) {
      throw e;
    }
  }
  return {
    path: segments,
    previousNode,
    isAtPropertyKey,
    matches: (pattern) => {
      let k = 0;
      for (let i2 = 0; k < pattern.length && i2 < segments.length; i2++) {
        if (pattern[k] === segments[i2] || pattern[k] === "*") {
          k++;
        } else if (pattern[k] !== "**") {
          return false;
        }
      }
      return k === pattern.length;
    }
  };
}
function $yw(text2, errors = [], options3 = 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 array2 = [];
      onValue(array2);
      previousParents.push(currentParent);
      currentParent = array2;
      currentProperty = null;
    },
    onArrayEnd: () => {
      currentParent = previousParents.pop();
    },
    onLiteralValue: onValue,
    onError: (error, offset, length) => {
      errors.push({ error, offset, length });
    }
  };
  $Fw(text2, visitor, options3);
  return currentParent[0];
}
function $zw(text2, errors = [], options3 = 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: $Gw(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 });
    }
  };
  $Fw(text2, visitor, options3);
  const result = currentParent.children[0];
  if (result) {
    delete result.parent;
  }
  return result;
}
function $Aw(root, path) {
  if (!root) {
    return void 0;
  }
  let node = root;
  for (const segment of path) {
    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 $Fw(text2, visitor, options3 = ParseOptions.DEFAULT) {
  const _scanner = $ww(text2, 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), onError2 = toOneArgVisit(visitor.onError);
  const disallowComments = options3 && options3.disallowComments;
  const allowTrailingComma = options3 && options3.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 = []) {
    onError2(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 (options3.allowEmptyContent) {
      return true;
    }
    handleError(4, [], []);
    return false;
  }
  if (!parseValue()) {
    handleError(4, [], []);
    return false;
  }
  if (_scanner.getToken() !== 17) {
    handleError(9, [], []);
  }
  return true;
}
function $Gw(value) {
  switch (typeof value) {
    case "boolean":
      return "boolean";
    case "number":
      return "number";
    case "string":
      return "string";
    case "object": {
      if (!value) {
        return "null";
      } else if (Array.isArray(value)) {
        return "array";
      }
      return "object";
    }
    default:
      return "null";
  }
}

// out-build/vs/platform/telemetry/common/commonProperties.js
function $aw(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 $bw = class {
  constructor(value) {
    this.value = value;
    this.isTrustedTelemetryValue = true;
  }
};
var $cw = 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 $dw = new $cw();
var $ew = class {
  async publicLog(_endpoint, _eventName, _data) {
  }
  async publicLogError(_endpoint, _errorEventName, _data) {
  }
};
var $fw = "telemetry";
var $gw = "extensionTelemetryLog";
function $iw(productService, environmentService) {
  if (!environmentService.isBuilt && !environmentService.disableTelemetry) {
    return true;
  }
  return !(environmentService.disableTelemetry || !productService.enableTelemetry);
}
function $jw(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 $kw(configurationService) {
  const newConfig = configurationService.getValue($Iv);
  const crashReporterConfig = configurationService.getValue($Jv);
  const oldConfig = configurationService.getValue($Kv);
  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 $lw(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
  };
}
var telemetryAllowedAuthorities = /* @__PURE__ */ new Set(["ssh-remote", "dev-container", "attached-container", "wsl", "tunnel", "codespaces", "amlext"]);
function $mw(remoteAuthority) {
  if (!remoteAuthority) {
    return "none";
  }
  const remoteName = $9v(remoteAuthority);
  return telemetryAllowedAuthorities.has(remoteName) ? remoteName : "other";
}
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] = $Qv(value);
    } else if (value instanceof Date) {
      result[index] = value.toISOString();
    } else if ($Bg(value)) {
      if (order < 2) {
        flatten(value, result, order + 1, index + ".");
      } else {
        result[index] = $Qv(value);
      }
    } else {
      result[index] = value;
    }
  }
}
function $nw(productService, configService) {
  const msftInternalDomains = productService.msftInternalDomains || [];
  const internalTesting = configService.getValue("telemetry.internalTesting");
  return $aw(msftInternalDomains) || internalTesting;
}
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: "Microsoft Entra ID", regex: /eyJ(?:0eXAiOiJKV1Qi|hbGci|[a-zA-Z0-9\-_]+\.[a-zA-Z0-9\-_]+\.)/ },
    { 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 $pw(data, cleanUpPatterns) {
  return $Nv(data, (value) => {
    if (value instanceof $bw || 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 $DA(a, b) {
  if (a.uuid && b.uuid) {
    return a.uuid === b.uuid;
  }
  if (a.id === b.id) {
    return true;
  }
  return $Vf(a.id, b.id) === 0;
}
var ExtensionKeyRegex = /^([^.]+\..+)-(\d+\.\d+\.\d+)(-(.+))?$/;
var $EA = class _$EA {
  static create(extension) {
    const version2 = extension.manifest ? extension.manifest.version : extension.version;
    const targetPlatform = extension.manifest ? extension.targetPlatform : extension.properties.targetPlatform;
    return new _$EA(extension.identifier, version2, targetPlatform);
  }
  static parse(key2) {
    const matches = ExtensionKeyRegex.exec(key2);
    return matches && matches[1] && matches[2] ? new _$EA({ id: matches[1] }, matches[2], matches[4] || void 0) : null;
  }
  constructor(identifier2, version2, targetPlatform = "undefined") {
    this.identifier = identifier2;
    this.version = version2;
    this.targetPlatform = targetPlatform;
    this.id = identifier2.id;
  }
  toString() {
    return `${this.id}-${this.version}${this.targetPlatform !== "undefined" ? `-${this.targetPlatform}` : ""}`;
  }
  equals(o) {
    if (!(o instanceof _$EA)) {
      return false;
    }
    return $DA(this, o) && this.version === o.version && this.targetPlatform === o.targetPlatform;
  }
};
var EXTENSION_IDENTIFIER_WITH_VERSION_REGEX = /^([^.]+\..+)@((prerelease)|(\d+\.\d+\.\d+(-.*)?))$/;
function $FA(id2) {
  const matches = EXTENSION_IDENTIFIER_WITH_VERSION_REGEX.exec(id2);
  if (matches && matches[1]) {
    return [$HA(matches[1]), matches[2]];
  }
  return [$HA(id2), void 0];
}
function $GA(publisher, name) {
  return `${publisher}.${name}`;
}
function $HA(id2) {
  return id2.toLowerCase();
}
function $IA(publisher, name) {
  return $HA($GA(publisher ?? $1z, name));
}
function $JA(extensions, getExtensionIdentifier) {
  const byExtension = [];
  const findGroup = (extension) => {
    for (const group2 of byExtension) {
      if (group2.some((e) => $DA(getExtensionIdentifier(e), getExtensionIdentifier(extension)))) {
        return group2;
      }
    }
    return null;
  };
  for (const extension of extensions) {
    const group2 = findGroup(extension);
    if (group2) {
      group2.push(extension);
    } else {
      byExtension.push([extension]);
    }
  }
  return byExtension;
}
function $KA(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 $LA(extension) {
  return {
    id: new $bw(extension.identifier.id),
    name: new $bw(extension.name),
    extensionVersion: 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 $MA = new $5z("pprice.better-merge");
function $NA(installedExtensions, extension) {
  const dependencies = [];
  const extensions = extension.manifest.extensionDependencies?.slice(0) ?? [];
  while (extensions.length) {
    const id2 = extensions.shift();
    if (id2 && dependencies.every((e) => !$DA(e.identifier, { id: id2 }))) {
      const ext = installedExtensions.filter((e) => $DA(e.identifier, { id: id2 }));
      if (ext.length === 1) {
        dependencies.push(ext[0]);
        extensions.push(...ext[0].manifest.extensionDependencies?.slice(0) ?? []);
      }
    }
  }
  return dependencies;
}
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.`, $qb(error2));
    }
  }
  return !!content && (content.match(/^ID=([^\u001b\r\n]*)/m) || [])[1] === "alpine";
}
async function $OA(fileService, logService) {
  const alpineLinux = await isAlpineLinux(fileService, logService);
  const targetPlatform = $lA(alpineLinux ? "alpine" : $x, $ic);
  logService.debug("ComputeTargetPlatform:", targetPlatform);
  return targetPlatform;
}

// out-build/vs/workbench/services/extensions/common/extensions.js
var $uN = Object.freeze({
  identifier: new $5z("nullExtensionDescription"),
  name: "Null Extension Description",
  version: "0.0.0",
  publisher: "vscode",
  engines: { vscode: "" },
  extensionLocation: URI.parse("void:location"),
  isBuiltin: false,
  targetPlatform: "undefined",
  isUserBuiltin: false,
  isUnderDevelopment: false,
  preRelease: false
});
var $vN = "extensions.webWorker";
var $wN = $Qk("extensionService");
var ExtensionHostStartup;
(function(ExtensionHostStartup2) {
  ExtensionHostStartup2[ExtensionHostStartup2["EagerAutoStart"] = 1] = "EagerAutoStart";
  ExtensionHostStartup2[ExtensionHostStartup2["EagerManualStart"] = 2] = "EagerManualStart";
  ExtensionHostStartup2[ExtensionHostStartup2["Lazy"] = 3] = "Lazy";
})(ExtensionHostStartup || (ExtensionHostStartup = {}));
var $yN = class {
  get versionId() {
    return this.c;
  }
  get allExtensions() {
    return this.d;
  }
  get myExtensions() {
    return this.e;
  }
  constructor(versionId, allExtensions, myExtensions) {
    this.c = versionId;
    this.d = allExtensions.slice(0);
    this.e = myExtensions.slice(0);
    this.f = null;
  }
  toSnapshot() {
    return {
      versionId: this.c,
      allExtensions: this.d,
      myExtensions: this.e,
      activationEvents: $fN.createActivationEventsMap(this.d)
    };
  }
  set(versionId, allExtensions, myExtensions) {
    if (this.c > versionId) {
      throw new Error(`ExtensionHostExtensions: invalid versionId ${versionId} (current: ${this.c})`);
    }
    const toRemove = [];
    const toAdd = [];
    const myToRemove = [];
    const myToAdd = [];
    const oldExtensionsMap = extensionDescriptionArrayToMap(this.d);
    const newExtensionsMap = extensionDescriptionArrayToMap(allExtensions);
    const extensionsAreTheSame = (a, b) => {
      return a.extensionLocation.toString() === b.extensionLocation.toString() || a.isBuiltin === b.isBuiltin || a.isUserBuiltin === b.isUserBuiltin || a.isUnderDevelopment === b.isUnderDevelopment;
    };
    for (const oldExtension of this.d) {
      const newExtension = newExtensionsMap.get(oldExtension.identifier);
      if (!newExtension) {
        toRemove.push(oldExtension.identifier);
        oldExtensionsMap.delete(oldExtension.identifier);
        continue;
      }
      if (!extensionsAreTheSame(oldExtension, newExtension)) {
        toRemove.push(oldExtension.identifier);
        oldExtensionsMap.delete(oldExtension.identifier);
        continue;
      }
    }
    for (const newExtension of allExtensions) {
      const oldExtension = oldExtensionsMap.get(newExtension.identifier);
      if (!oldExtension) {
        toAdd.push(newExtension);
        continue;
      }
      if (!extensionsAreTheSame(oldExtension, newExtension)) {
        toRemove.push(oldExtension.identifier);
        oldExtensionsMap.delete(oldExtension.identifier);
        continue;
      }
    }
    const myOldExtensionsSet = new $6z(this.e);
    const myNewExtensionsSet = new $6z(myExtensions);
    for (const oldExtensionId of this.e) {
      if (!myNewExtensionsSet.has(oldExtensionId)) {
        myToRemove.push(oldExtensionId);
      }
    }
    for (const newExtensionId of myExtensions) {
      if (!myOldExtensionsSet.has(newExtensionId)) {
        myToAdd.push(newExtensionId);
      }
    }
    const addActivationEvents = $fN.createActivationEventsMap(toAdd);
    const delta = { versionId, toRemove, toAdd, addActivationEvents, myToRemove, myToAdd };
    this.delta(delta);
    return delta;
  }
  delta(extensionsDelta) {
    if (this.c >= extensionsDelta.versionId) {
      return null;
    }
    const { toRemove, toAdd, myToRemove, myToAdd } = extensionsDelta;
    const toRemoveSet = new $6z(toRemove);
    const myToRemoveSet = new $6z(myToRemove);
    for (let i2 = 0; i2 < this.d.length; i2++) {
      if (toRemoveSet.has(this.d[i2].identifier)) {
        this.d.splice(i2, 1);
        i2--;
      }
    }
    for (let i2 = 0; i2 < this.e.length; i2++) {
      if (myToRemoveSet.has(this.e[i2])) {
        this.e.splice(i2, 1);
        i2--;
      }
    }
    for (const extension of toAdd) {
      this.d.push(extension);
    }
    for (const extensionId of myToAdd) {
      this.e.push(extensionId);
    }
    this.f = null;
    return extensionsDelta;
  }
  containsExtension(extensionId) {
    for (const myExtensionId of this.e) {
      if ($5z.equals(myExtensionId, extensionId)) {
        return true;
      }
    }
    return false;
  }
  containsActivationEvent(activationEvent) {
    if (!this.f) {
      this.f = this.g();
    }
    return this.f.has(activationEvent);
  }
  g() {
    const result = /* @__PURE__ */ new Set();
    for (const extensionDescription of this.d) {
      if (!this.containsExtension(extensionDescription.identifier)) {
        continue;
      }
      const activationEvents = $fN.readActivationEvents(extensionDescription);
      for (const activationEvent of activationEvents) {
        result.add(activationEvent);
      }
    }
    return result;
  }
};
function extensionDescriptionArrayToMap(extensions) {
  const result = new $7z();
  for (const extension of extensions) {
    result.set(extension.identifier, extension);
  }
  return result;
}
function $zN(extension, proposal) {
  return true;
}
function $AN(extension, proposal) {
  if (!$zN(extension, proposal)) {
    throw new Error(`Extension '${extension.identifier.value}' CANNOT use API proposal: ${proposal}.
Its package.json#enabledApiProposals-property declares: ${extension.enabledApiProposals?.join(", ") ?? "[]"} but NOT ${proposal}.
 The missing proposal MUST be added and you must start in extension development mode or use the following command line switch: --enable-proposed-api ${extension.identifier.value}`);
  }
}
var $BN = class {
  constructor(codeLoadingTime, activateCallTime, activateResolvedTime, activationReason) {
    this.codeLoadingTime = codeLoadingTime;
    this.activateCallTime = activateCallTime;
    this.activateResolvedTime = activateResolvedTime;
    this.activationReason = activationReason;
  }
};
var $CN = class {
  constructor(description, value) {
    this.description = description;
    this.value = value;
  }
};
var ActivationKind;
(function(ActivationKind2) {
  ActivationKind2[ActivationKind2["Normal"] = 0] = "Normal";
  ActivationKind2[ActivationKind2["Immediate"] = 1] = "Immediate";
})(ActivationKind || (ActivationKind = {}));
function $DN(extensionDescription) {
  return {
    type: extensionDescription.isBuiltin ? 0 : 1,
    isBuiltin: extensionDescription.isBuiltin || extensionDescription.isUserBuiltin,
    identifier: { id: $IA(extensionDescription.publisher, extensionDescription.name), uuid: extensionDescription.uuid },
    manifest: extensionDescription,
    location: extensionDescription.extensionLocation,
    targetPlatform: extensionDescription.targetPlatform,
    validations: [],
    isValid: true,
    preRelease: extensionDescription.preRelease
  };
}
function $EN(extension, isUnderDevelopment) {
  const id2 = $GA(extension.manifest.publisher, extension.manifest.name);
  return {
    id: id2,
    identifier: new $5z(id2),
    isBuiltin: extension.type === 0,
    isUserBuiltin: extension.type === 1 && extension.isBuiltin,
    isUnderDevelopment: !!isUnderDevelopment,
    extensionLocation: extension.location,
    uuid: extension.identifier.uuid,
    targetPlatform: extension.targetPlatform,
    publisherDisplayName: extension.publisherDisplayName,
    preRelease: extension.preRelease,
    ...extension.manifest
  };
}

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

// out-build/vs/platform/externalServices/common/serviceMachineId.js
async function $7v(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 = $os(value) ? value : null;
  } catch (e) {
    uuid = null;
  }
  if (!uuid) {
    uuid = $ps();
    try {
      await fileService.writeFile(environmentService.serviceMachineIdResource, $Ci.fromString(uuid));
    } catch (error) {
    }
  }
  storageService?.store(
    "storage.serviceMachineId",
    uuid,
    -1,
    1
    /* StorageTarget.MACHINE */
  );
  return uuid;
}

// out-build/vs/platform/extensionResourceLoader/common/extensionResourceLoader.js
var WEB_EXTENSION_RESOURCE_END_POINT_SEGMENT = "/web-extension-resource/";
var $Olb = $Qk("extensionResourceLoaderService");
function $Plb(resource, targetPlatform) {
  if (resource.query !== `target=${targetPlatform}`) {
    return void 0;
  }
  const paths = resource.path.split("/");
  if (!paths[3]) {
    return void 0;
  }
  paths[3] = `${paths[3]}+${targetPlatform}`;
  return resource.with({ query: null, path: paths.join("/") });
}
var $Qlb = class {
  constructor(c, d, e, f, g) {
    this.c = c;
    this.d = d;
    this.e = e;
    this.f = f;
    this.g = g;
    if (e.extensionsGallery) {
      this.a = e.extensionsGallery.resourceUrlTemplate;
      this.b = this.a ? this.k(URI.parse(this.a)) : void 0;
    }
  }
  get supportsExtensionGalleryResources() {
    return this.a !== void 0;
  }
  getExtensionGalleryResourceURL({ publisher, name, version: version2, targetPlatform }, path) {
    if (this.a) {
      const uri = URI.parse($xf(this.a, {
        publisher,
        name,
        version: targetPlatform !== void 0 && targetPlatform !== "undefined" && targetPlatform !== "unknown" && targetPlatform !== "universal" ? `${version2}+${targetPlatform}` : version2,
        path: "extension"
      }));
      return this.l(uri) ? URI.joinPath(URI.parse(window.location.href), uri.path) : uri;
    }
    return void 0;
  }
  isExtensionGalleryResource(uri) {
    return !!this.b && this.b === this.k(uri);
  }
  async h() {
    const headers = {
      "X-Client-Name": `${this.e.applicationName}${$r ? "-web" : ""}`,
      "X-Client-Version": this.e.version
    };
    if ($iw(this.e, this.f) && $kw(this.g) === 3) {
      headers["X-Machine-Id"] = await this.j();
    }
    if (this.e.commit) {
      headers["X-Client-Commit"] = this.e.commit;
    }
    return headers;
  }
  j() {
    if (!this.i) {
      this.i = $7v(this.f, this.c, this.d);
    }
    return this.i;
  }
  k(uri) {
    if (this.l(uri)) {
      return uri.authority;
    }
    const index = uri.authority.indexOf(".");
    return index !== -1 ? uri.authority.substring(index + 1) : void 0;
  }
  l(uri) {
    const uriPath = uri.path;
    return uriPath.startsWith(WEB_EXTENSION_RESOURCE_END_POINT_SEGMENT);
  }
};

// out-build/vs/workbench/contrib/codeEditor/common/languageConfigurationExtensionPoint.js
var $Rlb_1;
function isStringArr(something) {
  if (!Array.isArray(something)) {
    return false;
  }
  for (let i2 = 0, len = something.length; i2 < len; i2++) {
    if (typeof something[i2] !== "string") {
      return false;
    }
  }
  return true;
}
function isCharacterPair(something) {
  return isStringArr(something) && something.length === 2;
}
var $Rlb = $Rlb_1 = class $Rlb2 extends $3c {
  constructor(b, c, f, g) {
    super();
    this.b = b;
    this.c = c;
    this.f = f;
    this.g = g;
    this.a = /* @__PURE__ */ new Map();
    this.B(this.b.onDidRequestBasicLanguageFeatures(async (languageIdentifier) => {
      this.f.whenInstalledExtensionsRegistered().then(() => {
        this.h(languageIdentifier);
      });
    }));
    this.B(this.b.onDidChange(() => {
      for (const [languageId] of this.a) {
        this.h(languageId);
      }
    }));
  }
  async h(languageId) {
    const configurationFiles = this.b.getConfigurationFiles(languageId);
    const configurationHash = $Xi(configurationFiles.map((uri) => uri.toString()));
    if (this.a.get(languageId) === configurationHash) {
      return;
    }
    this.a.set(languageId, configurationHash);
    const configs = await Promise.all(configurationFiles.map((configFile) => this.j(configFile)));
    for (const config of configs) {
      this.w(languageId, config);
    }
  }
  async j(configFileLocation) {
    try {
      const contents = await this.c.readExtensionResource(configFileLocation);
      const errors = [];
      let configuration2 = $yw(contents, errors);
      if (errors.length) {
        console.error(localize(5242, null, configFileLocation.toString(), errors.map((e) => `[${e.offset}, ${e.length}] ${$SA(e.error)}`).join("\n")));
      }
      if ($Gw(configuration2) !== "object") {
        console.error(localize(5243, null, configFileLocation.toString()));
        configuration2 = {};
      }
      return configuration2;
    } catch (err) {
      console.error(err);
      return {};
    }
  }
  static m(languageId, configuration2) {
    const source = configuration2.comments;
    if (typeof source === "undefined") {
      return void 0;
    }
    if (!$Bg(source)) {
      console.warn(`[${languageId}]: language configuration: expected \`comments\` to be an object.`);
      return void 0;
    }
    let result = void 0;
    if (typeof source.lineComment !== "undefined") {
      if (typeof source.lineComment !== "string") {
        console.warn(`[${languageId}]: language configuration: expected \`comments.lineComment\` to be a string.`);
      } else {
        result = result || {};
        result.lineComment = source.lineComment;
      }
    }
    if (typeof source.blockComment !== "undefined") {
      if (!isCharacterPair(source.blockComment)) {
        console.warn(`[${languageId}]: language configuration: expected \`comments.blockComment\` to be an array of two strings.`);
      } else {
        result = result || {};
        result.blockComment = source.blockComment;
      }
    }
    return result;
  }
  static n(languageId, configuration2) {
    const source = configuration2.brackets;
    if (typeof source === "undefined") {
      return void 0;
    }
    if (!Array.isArray(source)) {
      console.warn(`[${languageId}]: language configuration: expected \`brackets\` to be an array.`);
      return void 0;
    }
    let result = void 0;
    for (let i2 = 0, len = source.length; i2 < len; i2++) {
      const pair = source[i2];
      if (!isCharacterPair(pair)) {
        console.warn(`[${languageId}]: language configuration: expected \`brackets[${i2}]\` to be an array of two strings.`);
        continue;
      }
      result = result || [];
      result.push(pair);
    }
    return result;
  }
  static r(languageId, configuration2) {
    const source = configuration2.autoClosingPairs;
    if (typeof source === "undefined") {
      return void 0;
    }
    if (!Array.isArray(source)) {
      console.warn(`[${languageId}]: language configuration: expected \`autoClosingPairs\` to be an array.`);
      return void 0;
    }
    let result = void 0;
    for (let i2 = 0, len = source.length; i2 < len; i2++) {
      const pair = source[i2];
      if (Array.isArray(pair)) {
        if (!isCharacterPair(pair)) {
          console.warn(`[${languageId}]: language configuration: expected \`autoClosingPairs[${i2}]\` to be an array of two strings or an object.`);
          continue;
        }
        result = result || [];
        result.push({ open: pair[0], close: pair[1] });
      } else {
        if (!$Bg(pair)) {
          console.warn(`[${languageId}]: language configuration: expected \`autoClosingPairs[${i2}]\` to be an array of two strings or an object.`);
          continue;
        }
        if (typeof pair.open !== "string") {
          console.warn(`[${languageId}]: language configuration: expected \`autoClosingPairs[${i2}].open\` to be a string.`);
          continue;
        }
        if (typeof pair.close !== "string") {
          console.warn(`[${languageId}]: language configuration: expected \`autoClosingPairs[${i2}].close\` to be a string.`);
          continue;
        }
        if (typeof pair.notIn !== "undefined") {
          if (!isStringArr(pair.notIn)) {
            console.warn(`[${languageId}]: language configuration: expected \`autoClosingPairs[${i2}].notIn\` to be a string array.`);
            continue;
          }
        }
        result = result || [];
        result.push({ open: pair.open, close: pair.close, notIn: pair.notIn });
      }
    }
    return result;
  }
  static s(languageId, configuration2) {
    const source = configuration2.surroundingPairs;
    if (typeof source === "undefined") {
      return void 0;
    }
    if (!Array.isArray(source)) {
      console.warn(`[${languageId}]: language configuration: expected \`surroundingPairs\` to be an array.`);
      return void 0;
    }
    let result = void 0;
    for (let i2 = 0, len = source.length; i2 < len; i2++) {
      const pair = source[i2];
      if (Array.isArray(pair)) {
        if (!isCharacterPair(pair)) {
          console.warn(`[${languageId}]: language configuration: expected \`surroundingPairs[${i2}]\` to be an array of two strings or an object.`);
          continue;
        }
        result = result || [];
        result.push({ open: pair[0], close: pair[1] });
      } else {
        if (!$Bg(pair)) {
          console.warn(`[${languageId}]: language configuration: expected \`surroundingPairs[${i2}]\` to be an array of two strings or an object.`);
          continue;
        }
        if (typeof pair.open !== "string") {
          console.warn(`[${languageId}]: language configuration: expected \`surroundingPairs[${i2}].open\` to be a string.`);
          continue;
        }
        if (typeof pair.close !== "string") {
          console.warn(`[${languageId}]: language configuration: expected \`surroundingPairs[${i2}].close\` to be a string.`);
          continue;
        }
        result = result || [];
        result.push({ open: pair.open, close: pair.close });
      }
    }
    return result;
  }
  static t(languageId, configuration2) {
    const source = configuration2.colorizedBracketPairs;
    if (typeof source === "undefined") {
      return void 0;
    }
    if (!Array.isArray(source)) {
      console.warn(`[${languageId}]: language configuration: expected \`colorizedBracketPairs\` to be an array.`);
      return void 0;
    }
    const result = [];
    for (let i2 = 0, len = source.length; i2 < len; i2++) {
      const pair = source[i2];
      if (!isCharacterPair(pair)) {
        console.warn(`[${languageId}]: language configuration: expected \`colorizedBracketPairs[${i2}]\` to be an array of two strings.`);
        continue;
      }
      result.push([pair[0], pair[1]]);
    }
    return result;
  }
  static u(languageId, configuration2) {
    const source = configuration2.onEnterRules;
    if (typeof source === "undefined") {
      return void 0;
    }
    if (!Array.isArray(source)) {
      console.warn(`[${languageId}]: language configuration: expected \`onEnterRules\` to be an array.`);
      return void 0;
    }
    let result = void 0;
    for (let i2 = 0, len = source.length; i2 < len; i2++) {
      const onEnterRule = source[i2];
      if (!$Bg(onEnterRule)) {
        console.warn(`[${languageId}]: language configuration: expected \`onEnterRules[${i2}]\` to be an object.`);
        continue;
      }
      if (!$Bg(onEnterRule.action)) {
        console.warn(`[${languageId}]: language configuration: expected \`onEnterRules[${i2}].action\` to be an object.`);
        continue;
      }
      let indentAction;
      if (onEnterRule.action.indent === "none") {
        indentAction = IndentAction.None;
      } else if (onEnterRule.action.indent === "indent") {
        indentAction = IndentAction.Indent;
      } else if (onEnterRule.action.indent === "indentOutdent") {
        indentAction = IndentAction.IndentOutdent;
      } else if (onEnterRule.action.indent === "outdent") {
        indentAction = IndentAction.Outdent;
      } else {
        console.warn(`[${languageId}]: language configuration: expected \`onEnterRules[${i2}].action.indent\` to be 'none', 'indent', 'indentOutdent' or 'outdent'.`);
        continue;
      }
      const action = { indentAction };
      if (onEnterRule.action.appendText) {
        if (typeof onEnterRule.action.appendText === "string") {
          action.appendText = onEnterRule.action.appendText;
        } else {
          console.warn(`[${languageId}]: language configuration: expected \`onEnterRules[${i2}].action.appendText\` to be undefined or a string.`);
        }
      }
      if (onEnterRule.action.removeText) {
        if (typeof onEnterRule.action.removeText === "number") {
          action.removeText = onEnterRule.action.removeText;
        } else {
          console.warn(`[${languageId}]: language configuration: expected \`onEnterRules[${i2}].action.removeText\` to be undefined or a number.`);
        }
      }
      const beforeText = this.y(languageId, `onEnterRules[${i2}].beforeText`, onEnterRule.beforeText);
      if (!beforeText) {
        continue;
      }
      const resultingOnEnterRule = { beforeText, action };
      if (onEnterRule.afterText) {
        const afterText = this.y(languageId, `onEnterRules[${i2}].afterText`, onEnterRule.afterText);
        if (afterText) {
          resultingOnEnterRule.afterText = afterText;
        }
      }
      if (onEnterRule.previousLineText) {
        const previousLineText = this.y(languageId, `onEnterRules[${i2}].previousLineText`, onEnterRule.previousLineText);
        if (previousLineText) {
          resultingOnEnterRule.previousLineText = previousLineText;
        }
      }
      result = result || [];
      result.push(resultingOnEnterRule);
    }
    return result;
  }
  static extractValidConfig(languageId, configuration2) {
    const comments = this.m(languageId, configuration2);
    const brackets = this.n(languageId, configuration2);
    const autoClosingPairs = this.r(languageId, configuration2);
    const surroundingPairs = this.s(languageId, configuration2);
    const colorizedBracketPairs = this.t(languageId, configuration2);
    const autoCloseBefore = typeof configuration2.autoCloseBefore === "string" ? configuration2.autoCloseBefore : void 0;
    const wordPattern = configuration2.wordPattern ? this.y(languageId, `wordPattern`, configuration2.wordPattern) : void 0;
    const indentationRules = configuration2.indentationRules ? this.z(languageId, configuration2.indentationRules) : void 0;
    let folding = void 0;
    if (configuration2.folding) {
      const rawMarkers = configuration2.folding.markers;
      const startMarker = rawMarkers && rawMarkers.start ? this.y(languageId, `folding.markers.start`, rawMarkers.start) : void 0;
      const endMarker = rawMarkers && rawMarkers.end ? this.y(languageId, `folding.markers.end`, rawMarkers.end) : void 0;
      const markers = startMarker && endMarker ? { start: startMarker, end: endMarker } : void 0;
      folding = {
        offSide: configuration2.folding.offSide,
        markers
      };
    }
    const onEnterRules = this.u(languageId, configuration2);
    const richEditConfig = {
      comments,
      brackets,
      wordPattern,
      indentationRules,
      onEnterRules,
      autoClosingPairs,
      surroundingPairs,
      colorizedBracketPairs,
      autoCloseBefore,
      folding,
      __electricCharacterSupport: void 0
    };
    return richEditConfig;
  }
  w(languageId, configuration2) {
    const richEditConfig = $Rlb_1.extractValidConfig(languageId, configuration2);
    this.g.register(languageId, richEditConfig, 50);
  }
  static y(languageId, confPath, value) {
    if (typeof value === "string") {
      try {
        return new RegExp(value, "");
      } catch (err) {
        console.warn(`[${languageId}]: Invalid regular expression in \`${confPath}\`: `, err);
        return void 0;
      }
    }
    if ($Bg(value)) {
      if (typeof value.pattern !== "string") {
        console.warn(`[${languageId}]: language configuration: expected \`${confPath}.pattern\` to be a string.`);
        return void 0;
      }
      if (typeof value.flags !== "undefined" && typeof value.flags !== "string") {
        console.warn(`[${languageId}]: language configuration: expected \`${confPath}.flags\` to be a string.`);
        return void 0;
      }
      try {
        return new RegExp(value.pattern, value.flags);
      } catch (err) {
        console.warn(`[${languageId}]: Invalid regular expression in \`${confPath}\`: `, err);
        return void 0;
      }
    }
    console.warn(`[${languageId}]: language configuration: expected \`${confPath}\` to be a string or an object.`);
    return void 0;
  }
  static z(languageId, indentationRules) {
    const increaseIndentPattern = this.y(languageId, `indentationRules.increaseIndentPattern`, indentationRules.increaseIndentPattern);
    if (!increaseIndentPattern) {
      return void 0;
    }
    const decreaseIndentPattern = this.y(languageId, `indentationRules.decreaseIndentPattern`, indentationRules.decreaseIndentPattern);
    if (!decreaseIndentPattern) {
      return void 0;
    }
    const result = {
      increaseIndentPattern,
      decreaseIndentPattern
    };
    if (indentationRules.indentNextLinePattern) {
      result.indentNextLinePattern = this.y(languageId, `indentationRules.indentNextLinePattern`, indentationRules.indentNextLinePattern);
    }
    if (indentationRules.unIndentedLinePattern) {
      result.unIndentedLinePattern = this.y(languageId, `indentationRules.unIndentedLinePattern`, indentationRules.unIndentedLinePattern);
    }
    return result;
  }
};
$Rlb = $Rlb_1 = __decorate([
  __param(0, $1E),
  __param(1, $Olb),
  __param(2, $wN),
  __param(3, $NF)
], $Rlb);
var schemaId3 = "vscode://schemas/language-configuration";
var schema2 = {
  allowComments: true,
  allowTrailingCommas: true,
  default: {
    comments: {
      blockComment: ["/*", "*/"],
      lineComment: "//"
    },
    brackets: [["(", ")"], ["[", "]"], ["{", "}"]],
    autoClosingPairs: [["(", ")"], ["[", "]"], ["{", "}"]],
    surroundingPairs: [["(", ")"], ["[", "]"], ["{", "}"]]
  },
  definitions: {
    openBracket: {
      type: "string",
      description: localize(5244, null)
    },
    closeBracket: {
      type: "string",
      description: localize(5245, null)
    },
    bracketPair: {
      type: "array",
      items: [{
        $ref: "#/definitions/openBracket"
      }, {
        $ref: "#/definitions/closeBracket"
      }]
    }
  },
  properties: {
    comments: {
      default: {
        blockComment: ["/*", "*/"],
        lineComment: "//"
      },
      description: localize(5246, null),
      type: "object",
      properties: {
        blockComment: {
          type: "array",
          description: localize(5247, null),
          items: [{
            type: "string",
            description: localize(5248, null)
          }, {
            type: "string",
            description: localize(5249, null)
          }]
        },
        lineComment: {
          type: "string",
          description: localize(5250, null)
        }
      }
    },
    brackets: {
      default: [["(", ")"], ["[", "]"], ["{", "}"]],
      markdownDescription: localize(5251, null, "`colorizedBracketPairs`"),
      type: "array",
      items: {
        $ref: "#/definitions/bracketPair"
      }
    },
    colorizedBracketPairs: {
      default: [["(", ")"], ["[", "]"], ["{", "}"]],
      markdownDescription: localize(5252, null, "`brackets`"),
      type: "array",
      items: {
        $ref: "#/definitions/bracketPair"
      }
    },
    autoClosingPairs: {
      default: [["(", ")"], ["[", "]"], ["{", "}"]],
      description: localize(5253, null),
      type: "array",
      items: {
        oneOf: [{
          $ref: "#/definitions/bracketPair"
        }, {
          type: "object",
          properties: {
            open: {
              $ref: "#/definitions/openBracket"
            },
            close: {
              $ref: "#/definitions/closeBracket"
            },
            notIn: {
              type: "array",
              description: localize(5254, null),
              items: {
                enum: ["string", "comment"]
              }
            }
          }
        }]
      }
    },
    autoCloseBefore: {
      default: ";:.,=}])> \n	",
      description: localize(5255, null),
      type: "string"
    },
    surroundingPairs: {
      default: [["(", ")"], ["[", "]"], ["{", "}"]],
      description: localize(5256, null),
      type: "array",
      items: {
        oneOf: [{
          $ref: "#/definitions/bracketPair"
        }, {
          type: "object",
          properties: {
            open: {
              $ref: "#/definitions/openBracket"
            },
            close: {
              $ref: "#/definitions/closeBracket"
            }
          }
        }]
      }
    },
    wordPattern: {
      default: "",
      description: localize(5257, null),
      type: ["string", "object"],
      properties: {
        pattern: {
          type: "string",
          description: localize(5258, null),
          default: ""
        },
        flags: {
          type: "string",
          description: localize(5259, null),
          default: "g",
          pattern: "^([gimuy]+)$",
          patternErrorMessage: localize(5260, null)
        }
      }
    },
    indentationRules: {
      default: {
        increaseIndentPattern: "",
        decreaseIndentPattern: ""
      },
      description: localize(5261, null),
      type: "object",
      properties: {
        increaseIndentPattern: {
          type: ["string", "object"],
          description: localize(5262, null),
          properties: {
            pattern: {
              type: "string",
              description: localize(5263, null),
              default: ""
            },
            flags: {
              type: "string",
              description: localize(5264, null),
              default: "",
              pattern: "^([gimuy]+)$",
              patternErrorMessage: localize(5265, null)
            }
          }
        },
        decreaseIndentPattern: {
          type: ["string", "object"],
          description: localize(5266, null),
          properties: {
            pattern: {
              type: "string",
              description: localize(5267, null),
              default: ""
            },
            flags: {
              type: "string",
              description: localize(5268, null),
              default: "",
              pattern: "^([gimuy]+)$",
              patternErrorMessage: localize(5269, null)
            }
          }
        },
        indentNextLinePattern: {
          type: ["string", "object"],
          description: localize(5270, null),
          properties: {
            pattern: {
              type: "string",
              description: localize(5271, null),
              default: ""
            },
            flags: {
              type: "string",
              description: localize(5272, null),
              default: "",
              pattern: "^([gimuy]+)$",
              patternErrorMessage: localize(5273, null)
            }
          }
        },
        unIndentedLinePattern: {
          type: ["string", "object"],
          description: localize(5274, null),
          properties: {
            pattern: {
              type: "string",
              description: localize(5275, null),
              default: ""
            },
            flags: {
              type: "string",
              description: localize(5276, null),
              default: "",
              pattern: "^([gimuy]+)$",
              patternErrorMessage: localize(5277, null)
            }
          }
        }
      }
    },
    folding: {
      type: "object",
      description: localize(5278, null),
      properties: {
        offSide: {
          type: "boolean",
          description: localize(5279, null)
        },
        markers: {
          type: "object",
          description: localize(5280, null),
          properties: {
            start: {
              type: "string",
              description: localize(5281, null)
            },
            end: {
              type: "string",
              description: localize(5282, null)
            }
          }
        }
      }
    },
    onEnterRules: {
      type: "array",
      description: localize(5283, null),
      items: {
        type: "object",
        description: localize(5284, null),
        required: ["beforeText", "action"],
        properties: {
          beforeText: {
            type: ["string", "object"],
            description: localize(5285, null),
            properties: {
              pattern: {
                type: "string",
                description: localize(5286, null),
                default: ""
              },
              flags: {
                type: "string",
                description: localize(5287, null),
                default: "",
                pattern: "^([gimuy]+)$",
                patternErrorMessage: localize(5288, null)
              }
            }
          },
          afterText: {
            type: ["string", "object"],
            description: localize(5289, null),
            properties: {
              pattern: {
                type: "string",
                description: localize(5290, null),
                default: ""
              },
              flags: {
                type: "string",
                description: localize(5291, null),
                default: "",
                pattern: "^([gimuy]+)$",
                patternErrorMessage: localize(5292, null)
              }
            }
          },
          previousLineText: {
            type: ["string", "object"],
            description: localize(5293, null),
            properties: {
              pattern: {
                type: "string",
                description: localize(5294, null),
                default: ""
              },
              flags: {
                type: "string",
                description: localize(5295, null),
                default: "",
                pattern: "^([gimuy]+)$",
                patternErrorMessage: localize(5296, null)
              }
            }
          },
          action: {
            type: ["string", "object"],
            description: localize(5297, null),
            required: ["indent"],
            default: { "indent": "indent" },
            properties: {
              indent: {
                type: "string",
                description: localize(5298, null),
                default: "indent",
                enum: ["none", "indent", "indentOutdent", "outdent"],
                markdownEnumDescriptions: [
                  localize(5299, null),
                  localize(5300, null),
                  localize(5301, null),
                  localize(5302, null)
                ]
              },
              appendText: {
                type: "string",
                description: localize(5303, null),
                default: ""
              },
              removeText: {
                type: "number",
                description: localize(5304, null),
                default: 0
              }
            }
          }
        }
      }
    }
  }
};
var schemaRegistry5 = $Wn.as($Xn.JSONContribution);
schemaRegistry5.registerSchema(schemaId3, schema2);

// out-build/vs/workbench/services/statusbar/browser/statusbar.js
var $$qb = $Qk("statusbarService");
var StatusbarAlignment;
(function(StatusbarAlignment2) {
  StatusbarAlignment2[StatusbarAlignment2["LEFT"] = 0] = "LEFT";
  StatusbarAlignment2[StatusbarAlignment2["RIGHT"] = 1] = "RIGHT";
})(StatusbarAlignment || (StatusbarAlignment = {}));
function $_qb(thing) {
  const candidate = thing;
  return typeof candidate?.id === "string" && typeof candidate.alignment === "number";
}
function $arb(thing) {
  const candidate = thing;
  return (typeof candidate?.primary === "number" || $_qb(candidate?.primary)) && typeof candidate?.secondary === "number";
}
var $brb = {
  id: "statusBar.entry.showTooltip",
  title: ""
};
var $crb = ["standard", "warning", "error", "prominent", "remote", "offline"];

// out-build/vs/platform/remote/common/remoteAuthorityResolver.js
var $bC = $Qk("remoteAuthorityResolverService");
var RemoteConnectionType;
(function(RemoteConnectionType2) {
  RemoteConnectionType2[RemoteConnectionType2["WebSocket"] = 0] = "WebSocket";
  RemoteConnectionType2[RemoteConnectionType2["Managed"] = 1] = "Managed";
})(RemoteConnectionType || (RemoteConnectionType = {}));
var $cC = class {
  constructor(id2) {
    this.id = id2;
    this.type = 1;
  }
  toString() {
    return `Managed(${this.id})`;
  }
};
var $dC = class {
  constructor(host, port) {
    this.host = host;
    this.port = port;
    this.type = 0;
  }
  toString() {
    return `WebSocket(${this.host}:${this.port})`;
  }
};
var RemoteAuthorityResolverErrorCode;
(function(RemoteAuthorityResolverErrorCode2) {
  RemoteAuthorityResolverErrorCode2["Unknown"] = "Unknown";
  RemoteAuthorityResolverErrorCode2["NotAvailable"] = "NotAvailable";
  RemoteAuthorityResolverErrorCode2["TemporarilyNotAvailable"] = "TemporarilyNotAvailable";
  RemoteAuthorityResolverErrorCode2["NoResolverFound"] = "NoResolverFound";
  RemoteAuthorityResolverErrorCode2["InvalidAuthority"] = "InvalidAuthority";
})(RemoteAuthorityResolverErrorCode || (RemoteAuthorityResolverErrorCode = {}));
var $eC = class _$eC extends $ub {
  static isNotAvailable(err) {
    return err instanceof _$eC && err._code === RemoteAuthorityResolverErrorCode.NotAvailable;
  }
  static isTemporarilyNotAvailable(err) {
    return err instanceof _$eC && err._code === RemoteAuthorityResolverErrorCode.TemporarilyNotAvailable;
  }
  static isNoResolverFound(err) {
    return err instanceof _$eC && err._code === RemoteAuthorityResolverErrorCode.NoResolverFound;
  }
  static isInvalidAuthority(err) {
    return err instanceof _$eC && err._code === RemoteAuthorityResolverErrorCode.InvalidAuthority;
  }
  static isHandled(err) {
    return err instanceof _$eC && err.isHandled;
  }
  constructor(message, code = RemoteAuthorityResolverErrorCode.Unknown, detail2) {
    super(message);
    this._message = message;
    this._code = code;
    this._detail = detail2;
    this.isHandled = code === RemoteAuthorityResolverErrorCode.NotAvailable && detail2 === true;
    Object.setPrototypeOf(this, _$eC.prototype);
  }
};
function $fC(remoteAuthority) {
  const plusIndex = remoteAuthority.indexOf("+");
  if (plusIndex === -1) {
    return remoteAuthority;
  }
  return remoteAuthority.substring(0, plusIndex);
}

// out-build/vs/workbench/services/notebook/common/notebookDocumentService.js
var $8L = $Qk("notebookDocumentService");
var _lengths = ["W", "X", "Y", "Z", "a", "b", "c", "d", "e", "f"];
var _padRegexp = new RegExp(`^[${_lengths.join("")}]+`);
var _radix = 7;
function $9L(cell) {
  if (cell.scheme !== Schemas.vscodeNotebookCell) {
    return void 0;
  }
  const idx = cell.fragment.indexOf("s");
  if (idx < 0) {
    return void 0;
  }
  const handle2 = parseInt(cell.fragment.substring(0, idx).replace(_padRegexp, ""), _radix);
  const _scheme = $Vi(cell.fragment.substring(idx + 1)).toString();
  if (isNaN(handle2)) {
    return void 0;
  }
  return {
    handle: handle2,
    notebook: cell.with({ scheme: _scheme, fragment: null })
  };
}
function $0L(notebook, handle2) {
  const s = handle2.toString(_radix);
  const p = s.length < _lengths.length ? _lengths[s.length - 1] : "z";
  const fragment = `${p}${s}s${$Wi($Ci.fromString(notebook.scheme), true, true)}`;
  return notebook.with({ scheme: Schemas.vscodeNotebookCell, fragment });
}
function $$L(metadata) {
  if (metadata.scheme !== Schemas.vscodeNotebookMetadata) {
    return void 0;
  }
  const _scheme = $Vi(metadata.fragment).toString();
  return metadata.with({ scheme: _scheme, fragment: null });
}
function $_L(notebook) {
  const fragment = `${$Wi($Ci.fromString(notebook.scheme), true, true)}`;
  return notebook.with({ scheme: Schemas.vscodeNotebookMetadata, fragment });
}
var $aM = class {
  constructor() {
    this.a = new $Ec();
  }
  getNotebook(uri) {
    if (uri.scheme === Schemas.vscodeNotebookCell) {
      const cellUri = $9L(uri);
      if (cellUri) {
        const document2 = this.a.get(cellUri.notebook);
        if (document2) {
          return document2;
        }
      }
    }
    return this.a.get(uri);
  }
  addNotebookDocument(document2) {
    this.a.set(document2.uri, document2);
  }
  removeNotebookDocument(document2) {
    this.a.delete(document2.uri);
  }
};
$SC(
  $8L,
  $aM,
  1
  /* InstantiationType.Delayed */
);

// out-build/vs/workbench/contrib/notebook/common/notebookCommon.js
var $bM = "workbench.editor.notebook";
var $cM = "workbench.editor.notebookTextDiffEditor";
var $dM = "workbench.editor.notebookMultiTextDiffEditor";
var $eM = "workbench.editor.interactive";
var $fM = "workbench.editor.repl";
var CellKind;
(function(CellKind2) {
  CellKind2[CellKind2["Markup"] = 1] = "Markup";
  CellKind2[CellKind2["Code"] = 2] = "Code";
})(CellKind || (CellKind = {}));
var $hM = [
  "application/json",
  "application/javascript",
  "text/html",
  "image/svg+xml",
  $YC.latex,
  $YC.markdown,
  "image/png",
  "image/jpeg",
  $YC.text
];
var $iM = [
  $YC.latex,
  $YC.markdown,
  "application/json",
  "text/html",
  "image/svg+xml",
  "image/png",
  "image/jpeg",
  $YC.text
];
var $jM = /* @__PURE__ */ new Map([
  ["ms-toolsai.jupyter", /* @__PURE__ */ new Set(["jupyter-notebook", "interactive"])],
  ["ms-toolsai.jupyter-renderers", /* @__PURE__ */ new Set(["jupyter-notebook", "interactive"])]
]);
var $kM = "_notAvailable";
var NotebookRunState;
(function(NotebookRunState2) {
  NotebookRunState2[NotebookRunState2["Running"] = 1] = "Running";
  NotebookRunState2[NotebookRunState2["Idle"] = 2] = "Idle";
})(NotebookRunState || (NotebookRunState = {}));
var NotebookCellExecutionState;
(function(NotebookCellExecutionState4) {
  NotebookCellExecutionState4[NotebookCellExecutionState4["Unconfirmed"] = 1] = "Unconfirmed";
  NotebookCellExecutionState4[NotebookCellExecutionState4["Pending"] = 2] = "Pending";
  NotebookCellExecutionState4[NotebookCellExecutionState4["Executing"] = 3] = "Executing";
})(NotebookCellExecutionState || (NotebookCellExecutionState = {}));
var NotebookExecutionState;
(function(NotebookExecutionState2) {
  NotebookExecutionState2[NotebookExecutionState2["Unconfirmed"] = 1] = "Unconfirmed";
  NotebookExecutionState2[NotebookExecutionState2["Pending"] = 2] = "Pending";
  NotebookExecutionState2[NotebookExecutionState2["Executing"] = 3] = "Executing";
})(NotebookExecutionState || (NotebookExecutionState = {}));
var NotebookRendererMatch;
(function(NotebookRendererMatch2) {
  NotebookRendererMatch2[NotebookRendererMatch2["WithHardKernelDependency"] = 0] = "WithHardKernelDependency";
  NotebookRendererMatch2[NotebookRendererMatch2["WithOptionalKernelDependency"] = 1] = "WithOptionalKernelDependency";
  NotebookRendererMatch2[NotebookRendererMatch2["Pure"] = 2] = "Pure";
  NotebookRendererMatch2[NotebookRendererMatch2["Never"] = 3] = "Never";
})(NotebookRendererMatch || (NotebookRendererMatch = {}));
var RendererMessagingSpec;
(function(RendererMessagingSpec2) {
  RendererMessagingSpec2["Always"] = "always";
  RendererMessagingSpec2["Never"] = "never";
  RendererMessagingSpec2["Optional"] = "optional";
})(RendererMessagingSpec || (RendererMessagingSpec = {}));
var NotebookCellsChangeType;
(function(NotebookCellsChangeType2) {
  NotebookCellsChangeType2[NotebookCellsChangeType2["ModelChange"] = 1] = "ModelChange";
  NotebookCellsChangeType2[NotebookCellsChangeType2["Move"] = 2] = "Move";
  NotebookCellsChangeType2[NotebookCellsChangeType2["ChangeCellLanguage"] = 5] = "ChangeCellLanguage";
  NotebookCellsChangeType2[NotebookCellsChangeType2["Initialize"] = 6] = "Initialize";
  NotebookCellsChangeType2[NotebookCellsChangeType2["ChangeCellMetadata"] = 7] = "ChangeCellMetadata";
  NotebookCellsChangeType2[NotebookCellsChangeType2["Output"] = 8] = "Output";
  NotebookCellsChangeType2[NotebookCellsChangeType2["OutputItem"] = 9] = "OutputItem";
  NotebookCellsChangeType2[NotebookCellsChangeType2["ChangeCellContent"] = 10] = "ChangeCellContent";
  NotebookCellsChangeType2[NotebookCellsChangeType2["ChangeDocumentMetadata"] = 11] = "ChangeDocumentMetadata";
  NotebookCellsChangeType2[NotebookCellsChangeType2["ChangeCellInternalMetadata"] = 12] = "ChangeCellInternalMetadata";
  NotebookCellsChangeType2[NotebookCellsChangeType2["ChangeCellMime"] = 13] = "ChangeCellMime";
  NotebookCellsChangeType2[NotebookCellsChangeType2["Unknown"] = 100] = "Unknown";
})(NotebookCellsChangeType || (NotebookCellsChangeType = {}));
var SelectionStateType;
(function(SelectionStateType2) {
  SelectionStateType2[SelectionStateType2["Handle"] = 0] = "Handle";
  SelectionStateType2[SelectionStateType2["Index"] = 1] = "Index";
})(SelectionStateType || (SelectionStateType = {}));
var CellEditType;
(function(CellEditType2) {
  CellEditType2[CellEditType2["Replace"] = 1] = "Replace";
  CellEditType2[CellEditType2["Output"] = 2] = "Output";
  CellEditType2[CellEditType2["Metadata"] = 3] = "Metadata";
  CellEditType2[CellEditType2["CellLanguage"] = 4] = "CellLanguage";
  CellEditType2[CellEditType2["DocumentMetadata"] = 5] = "DocumentMetadata";
  CellEditType2[CellEditType2["Move"] = 6] = "Move";
  CellEditType2[CellEditType2["OutputItems"] = 7] = "OutputItems";
  CellEditType2[CellEditType2["PartialMetadata"] = 8] = "PartialMetadata";
  CellEditType2[CellEditType2["PartialInternalMetadata"] = 9] = "PartialInternalMetadata";
})(CellEditType || (CellEditType = {}));
var NotebookMetadataUri;
(function(NotebookMetadataUri2) {
  NotebookMetadataUri2.scheme = Schemas.vscodeNotebookMetadata;
  function generate(notebook) {
    return $_L(notebook);
  }
  NotebookMetadataUri2.generate = generate;
  function parse4(metadata) {
    return $$L(metadata);
  }
  NotebookMetadataUri2.parse = parse4;
})(NotebookMetadataUri || (NotebookMetadataUri = {}));
var CellUri;
(function(CellUri2) {
  CellUri2.scheme = Schemas.vscodeNotebookCell;
  function generate(notebook, handle2) {
    return $0L(notebook, handle2);
  }
  CellUri2.generate = generate;
  function parse4(cell) {
    return $9L(cell);
  }
  CellUri2.parse = parse4;
  function generateCellOutputUri(notebook, outputId) {
    return notebook.with({
      scheme: Schemas.vscodeNotebookCellOutput,
      fragment: `op${outputId ?? ""},${notebook.scheme !== Schemas.file ? notebook.scheme : ""}`
    });
  }
  CellUri2.generateCellOutputUri = generateCellOutputUri;
  function parseCellOutputUri(uri) {
    if (uri.scheme !== Schemas.vscodeNotebookCellOutput) {
      return;
    }
    const match = /^op([0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12})?\,(.*)$/i.exec(uri.fragment);
    if (!match) {
      return void 0;
    }
    const outputId = match[1] && match[1] !== "" ? match[1] : void 0;
    const scheme = match[2];
    return {
      outputId,
      notebook: uri.with({
        scheme: scheme || Schemas.file,
        fragment: null
      })
    };
  }
  CellUri2.parseCellOutputUri = parseCellOutputUri;
  function generateCellPropertyUri(notebook, handle2, scheme) {
    return CellUri2.generate(notebook, handle2).with({ scheme });
  }
  CellUri2.generateCellPropertyUri = generateCellPropertyUri;
  function parseCellPropertyUri(uri, propertyScheme) {
    if (uri.scheme !== propertyScheme) {
      return void 0;
    }
    return CellUri2.parse(uri.with({ scheme: CellUri2.scheme }));
  }
  CellUri2.parseCellPropertyUri = parseCellPropertyUri;
})(CellUri || (CellUri = {}));
var normalizeSlashes = (str) => $l ? str.replace(/\//g, "\\") : str;
var $lM = class {
  constructor(initialValue = [], e = $hM) {
    this.e = e;
    this.d = [...new Set(initialValue)].map((pattern) => ({
      pattern,
      matches: $Dl(normalizeSlashes(pattern))
    }));
  }
  /**
   * Returns a sorted array of the input mimetypes.
   */
  sort(mimetypes) {
    const remaining = new Map(Iterable.map(mimetypes, (m) => [m, normalizeSlashes(m)]));
    let sorted = [];
    for (const { matches } of this.d) {
      for (const [original, normalized] of remaining) {
        if (matches(normalized)) {
          sorted.push(original);
          remaining.delete(original);
          break;
        }
      }
    }
    if (remaining.size) {
      sorted = sorted.concat([...remaining.keys()].sort((a, b) => this.e.indexOf(a) - this.e.indexOf(b)));
    }
    return sorted;
  }
  /**
   * Records that the user selected the given mimetype over the other
   * possible mimetypes, prioritizing it for future reference.
   */
  prioritize(chosenMimetype, otherMimetypes) {
    const chosenIndex = this.f(chosenMimetype);
    if (chosenIndex === -1) {
      this.d.unshift({ pattern: chosenMimetype, matches: $Dl(normalizeSlashes(chosenMimetype)) });
      return;
    }
    const uniqueIndicies = new Set(otherMimetypes.map((m) => this.f(m, chosenIndex)));
    uniqueIndicies.delete(-1);
    const otherIndices = Array.from(uniqueIndicies).sort();
    this.d.splice(chosenIndex + 1, 0, ...otherIndices.map((i2) => this.d[i2]));
    for (let oi = otherIndices.length - 1; oi >= 0; oi--) {
      this.d.splice(otherIndices[oi], 1);
    }
  }
  /**
   * Gets an array of in-order mimetype preferences.
   */
  toArray() {
    return this.d.map((o) => o.pattern);
  }
  f(mimeType, maxIndex = this.d.length) {
    const normalized = normalizeSlashes(mimeType);
    for (let i2 = 0; i2 < maxIndex; i2++) {
      if (this.d[i2].matches(normalized)) {
        return i2;
      }
    }
    return -1;
  }
};
function $mM(before, after, contains, equal = (a, b) => a === b) {
  const result = [];
  function pushSplice(start, deleteCount, toInsert) {
    if (deleteCount === 0 && toInsert.length === 0) {
      return;
    }
    const latest = result[result.length - 1];
    if (latest && latest.start + latest.deleteCount === start) {
      latest.deleteCount += deleteCount;
      latest.toInsert.push(...toInsert);
    } else {
      result.push({ start, deleteCount, toInsert });
    }
  }
  let beforeIdx = 0;
  let afterIdx = 0;
  while (true) {
    if (beforeIdx === before.length) {
      pushSplice(beforeIdx, 0, after.slice(afterIdx));
      break;
    }
    if (afterIdx === after.length) {
      pushSplice(beforeIdx, before.length - beforeIdx, []);
      break;
    }
    const beforeElement = before[beforeIdx];
    const afterElement = after[afterIdx];
    if (equal(beforeElement, afterElement)) {
      beforeIdx += 1;
      afterIdx += 1;
      continue;
    }
    if (contains(afterElement)) {
      pushSplice(beforeIdx, 1, []);
      beforeIdx += 1;
    } else {
      pushSplice(beforeIdx, 0, [afterElement]);
      afterIdx += 1;
    }
  }
  return result;
}
var $nM = new $nn("notebookEditorCursorAtBoundary", "none");
var $oM = new $nn("notebookEditorCursorAtLineBoundary", "none");
var NotebookEditorPriority;
(function(NotebookEditorPriority2) {
  NotebookEditorPriority2["default"] = "default";
  NotebookEditorPriority2["option"] = "option";
})(NotebookEditorPriority || (NotebookEditorPriority = {}));
var NotebookFindScopeType;
(function(NotebookFindScopeType2) {
  NotebookFindScopeType2["Cells"] = "cells";
  NotebookFindScopeType2["Text"] = "text";
  NotebookFindScopeType2["None"] = "none";
})(NotebookFindScopeType || (NotebookFindScopeType = {}));
function $pM(filenamePattern) {
  const arg = filenamePattern;
  if ((typeof arg.include === "string" || $El(arg.include)) && (typeof arg.exclude === "string" || $El(arg.exclude))) {
    return true;
  }
  return false;
}
var $rM = {
  displayOrder: "notebook.displayOrder",
  cellToolbarLocation: "notebook.cellToolbarLocation",
  cellToolbarVisibility: "notebook.cellToolbarVisibility",
  showCellStatusBar: "notebook.showCellStatusBar",
  cellExecutionTimeVerbosity: "notebook.cellExecutionTimeVerbosity",
  textDiffEditorPreview: "notebook.diff.enablePreview",
  diffOverviewRuler: "notebook.diff.overviewRuler",
  experimentalInsertToolbarAlignment: "notebook.experimental.insertToolbarAlignment",
  compactView: "notebook.compactView",
  focusIndicator: "notebook.cellFocusIndicator",
  insertToolbarLocation: "notebook.insertToolbarLocation",
  globalToolbar: "notebook.globalToolbar",
  stickyScrollEnabled: "notebook.stickyScroll.enabled",
  stickyScrollMode: "notebook.stickyScroll.mode",
  undoRedoPerCell: "notebook.undoRedoPerCell",
  consolidatedOutputButton: "notebook.consolidatedOutputButton",
  showFoldingControls: "notebook.showFoldingControls",
  dragAndDropEnabled: "notebook.dragAndDropEnabled",
  cellEditorOptionsCustomizations: "notebook.editorOptionsCustomizations",
  consolidatedRunButton: "notebook.consolidatedRunButton",
  openGettingStarted: "notebook.experimental.openGettingStarted",
  globalToolbarShowLabel: "notebook.globalToolbarShowLabel",
  markupFontSize: "notebook.markup.fontSize",
  markdownLineHeight: "notebook.markdown.lineHeight",
  interactiveWindowCollapseCodeCells: "interactiveWindow.collapseCellInputCode",
  outputScrollingDeprecated: "notebook.experimental.outputScrolling",
  outputScrolling: "notebook.output.scrolling",
  textOutputLineLimit: "notebook.output.textLineLimit",
  LinkifyOutputFilePaths: "notebook.output.linkifyFilePaths",
  minimalErrorRendering: "notebook.output.minimalErrorRendering",
  formatOnSave: "notebook.formatOnSave.enabled",
  insertFinalNewline: "notebook.insertFinalNewline",
  defaultFormatter: "notebook.defaultFormatter",
  formatOnCellExecution: "notebook.formatOnCellExecution",
  codeActionsOnSave: "notebook.codeActionsOnSave",
  outputWordWrap: "notebook.output.wordWrap",
  outputLineHeightDeprecated: "notebook.outputLineHeight",
  outputLineHeight: "notebook.output.lineHeight",
  outputFontSizeDeprecated: "notebook.outputFontSize",
  outputFontSize: "notebook.output.fontSize",
  outputFontFamilyDeprecated: "notebook.outputFontFamily",
  outputFontFamily: "notebook.output.fontFamily",
  findFilters: "notebook.find.filters",
  logging: "notebook.logging",
  confirmDeleteRunningCell: "notebook.confirmDeleteRunningCell",
  remoteSaving: "notebook.experimental.remoteSave",
  gotoSymbolsAllSymbols: "notebook.gotoSymbols.showAllSymbols",
  outlineShowMarkdownHeadersOnly: "notebook.outline.showMarkdownHeadersOnly",
  outlineShowCodeCells: "notebook.outline.showCodeCells",
  outlineShowCodeCellSymbols: "notebook.outline.showCodeCellSymbols",
  breadcrumbsShowCodeCells: "notebook.breadcrumbs.showCodeCells",
  scrollToRevealCell: "notebook.scrolling.revealNextCellOnExecute",
  cellChat: "notebook.experimental.cellChat",
  cellGenerate: "notebook.experimental.generate",
  notebookVariablesView: "notebook.variablesView",
  InteractiveWindowPromptToSave: "interactiveWindow.promptToSaveOnClose",
  cellFailureDiagnostics: "notebook.cellFailureDiagnostics",
  outputBackupSizeLimit: "notebook.backup.sizeLimit",
  multiCursor: "notebook.multiCursor.enabled"
};
var CellStatusbarAlignment;
(function(CellStatusbarAlignment2) {
  CellStatusbarAlignment2[CellStatusbarAlignment2["Left"] = 1] = "Left";
  CellStatusbarAlignment2[CellStatusbarAlignment2["Right"] = 2] = "Right";
})(CellStatusbarAlignment || (CellStatusbarAlignment = {}));
var $sM = class _$sM {
  static {
    this.d = "notebook/";
  }
  static create(notebookType, viewType) {
    return `${_$sM.d}${notebookType}/${viewType ?? notebookType}`;
  }
  static parse(candidate) {
    if (candidate.startsWith(_$sM.d)) {
      const split = candidate.substring(_$sM.d.length).split("/");
      if (split.length === 2) {
        return { notebookType: split[0], viewType: split[1] };
      }
    }
    return void 0;
  }
};
function $tM(mimeType) {
  return ["application/vnd.code.notebook.stdout", "application/vnd.code.notebook.stderr"].includes(mimeType);
}
var textDecoder2 = new TextDecoder();
function $uM(outputs) {
  const buffers = [];
  let startAppending = false;
  for (const output of outputs) {
    if (buffers.length === 0 || startAppending) {
      buffers.push(output);
      startAppending = true;
    }
  }
  let didCompression = compressStreamBuffer(buffers);
  const concatenated = $Ci.concat(buffers.map((buffer) => $Ci.wrap(buffer)));
  const data = formatStreamText(concatenated);
  didCompression = didCompression || data.byteLength !== concatenated.byteLength;
  return { data, didCompression };
}
var $vM = `${String.fromCharCode(27)}[A`;
var MOVE_CURSOR_1_LINE_COMMAND_BYTES = $vM.split("").map((c) => c.charCodeAt(0));
var LINE_FEED = 10;
function compressStreamBuffer(streams) {
  let didCompress = false;
  streams.forEach((stream, index) => {
    if (index === 0 || stream.length < $vM.length) {
      return;
    }
    const previousStream = streams[index - 1];
    const command4 = stream.subarray(0, $vM.length);
    if (command4[0] === MOVE_CURSOR_1_LINE_COMMAND_BYTES[0] && command4[1] === MOVE_CURSOR_1_LINE_COMMAND_BYTES[1] && command4[2] === MOVE_CURSOR_1_LINE_COMMAND_BYTES[2]) {
      const lastIndexOfLineFeed = previousStream.lastIndexOf(LINE_FEED);
      if (lastIndexOfLineFeed === -1) {
        return;
      }
      didCompress = true;
      streams[index - 1] = previousStream.subarray(0, lastIndexOfLineFeed);
      streams[index] = stream.subarray($vM.length);
    }
  });
  return didCompress;
}
function fixBackspace(txt) {
  let tmp = txt;
  do {
    txt = tmp;
    tmp = txt.replace(/[^\n]\x08/gm, "");
  } while (tmp.length < txt.length);
  return txt;
}
function fixCarriageReturn(txt) {
  txt = txt.replace(/\r+\n/gm, "\n");
  while (txt.search(/\r[^$]/g) > -1) {
    const base = txt.match(/^(.*)\r+/m)[1];
    let insert = txt.match(/\r+(.*)$/m)[1];
    insert = insert + base.slice(insert.length, base.length);
    txt = txt.replace(/\r+.*$/m, "\r").replace(/^.*\r/m, insert);
  }
  return txt;
}
var BACKSPACE_CHARACTER = "\b".charCodeAt(0);
var CARRIAGE_RETURN_CHARACTER = "\r".charCodeAt(0);
function formatStreamText(buffer) {
  if (!buffer.buffer.includes(BACKSPACE_CHARACTER) && !buffer.buffer.includes(CARRIAGE_RETURN_CHARACTER)) {
    return buffer;
  }
  return $Ci.fromString(fixCarriageReturn(fixBackspace(textDecoder2.decode(buffer.buffer))));
}

// out-build/vs/workbench/api/common/extHostTypes.js
var $zT_1;
var $AT_1;
var $BT_1;
var $CT_1;
var $IT_1;
var $JT_1;
var $MT_1;
var $NT_1;
var $UT_1;
var $VT_1;
var $XT_1;
var $4T_1;
var $mU_1;
var $qU_1;
var $rU_1;
var $UU_1;
var $hV_1;
function es5ClassCompat(target) {
  const interceptFunctions = {
    apply: function(...args2) {
      if (args2.length === 0) {
        return Reflect.construct(target, []);
      } else {
        const argsList = args2.length === 1 ? [] : args2[1];
        return Reflect.construct(target, argsList, args2[0].constructor);
      }
    },
    call: function(...args2) {
      if (args2.length === 0) {
        return Reflect.construct(target, []);
      } else {
        const [thisArg, ...restArgs] = args2;
        return Reflect.construct(target, restArgs, thisArg.constructor);
      }
    }
  };
  return Object.assign(target, interceptFunctions);
}
var TerminalOutputAnchor;
(function(TerminalOutputAnchor2) {
  TerminalOutputAnchor2[TerminalOutputAnchor2["Top"] = 0] = "Top";
  TerminalOutputAnchor2[TerminalOutputAnchor2["Bottom"] = 1] = "Bottom";
})(TerminalOutputAnchor || (TerminalOutputAnchor = {}));
var TerminalQuickFixType;
(function(TerminalQuickFixType3) {
  TerminalQuickFixType3[TerminalQuickFixType3["TerminalCommand"] = 0] = "TerminalCommand";
  TerminalQuickFixType3[TerminalQuickFixType3["Opener"] = 1] = "Opener";
  TerminalQuickFixType3[TerminalQuickFixType3["Command"] = 3] = "Command";
})(TerminalQuickFixType || (TerminalQuickFixType = {}));
var $zT = $zT_1 = class $zT2 {
  static from(...inDisposables) {
    let disposables = inDisposables;
    return new $zT_1(function() {
      if (disposables) {
        for (const disposable of disposables) {
          if (disposable && typeof disposable.dispose === "function") {
            disposable.dispose();
          }
        }
        disposables = void 0;
      }
    });
  }
  #callOnDispose;
  constructor(callOnDispose) {
    this.#callOnDispose = callOnDispose;
  }
  dispose() {
    if (typeof this.#callOnDispose === "function") {
      this.#callOnDispose();
      this.#callOnDispose = void 0;
    }
  }
};
$zT = $zT_1 = __decorate([
  es5ClassCompat
], $zT);
var $AT = $AT_1 = class $AT2 {
  static Min(...positions) {
    if (positions.length === 0) {
      throw new TypeError();
    }
    let result = positions[0];
    for (let i2 = 1; i2 < positions.length; i2++) {
      const p = positions[i2];
      if (p.isBefore(result)) {
        result = p;
      }
    }
    return result;
  }
  static Max(...positions) {
    if (positions.length === 0) {
      throw new TypeError();
    }
    let result = positions[0];
    for (let i2 = 1; i2 < positions.length; i2++) {
      const p = positions[i2];
      if (p.isAfter(result)) {
        result = p;
      }
    }
    return result;
  }
  static isPosition(other) {
    if (!other) {
      return false;
    }
    if (other instanceof $AT_1) {
      return true;
    }
    const { line, character } = other;
    if (typeof line === "number" && typeof character === "number") {
      return true;
    }
    return false;
  }
  static of(obj) {
    if (obj instanceof $AT_1) {
      return obj;
    } else if (this.isPosition(obj)) {
      return new $AT_1(obj.line, obj.character);
    }
    throw new Error("Invalid argument, is NOT a position-like object");
  }
  get line() {
    return this.c;
  }
  get character() {
    return this.e;
  }
  constructor(line, character) {
    if (line < 0) {
      throw $nb("line must be non-negative");
    }
    if (character < 0) {
      throw $nb("character must be non-negative");
    }
    this.c = line;
    this.e = character;
  }
  isBefore(other) {
    if (this.c < other.c) {
      return true;
    }
    if (other.c < this.c) {
      return false;
    }
    return this.e < other.e;
  }
  isBeforeOrEqual(other) {
    if (this.c < other.c) {
      return true;
    }
    if (other.c < this.c) {
      return false;
    }
    return this.e <= other.e;
  }
  isAfter(other) {
    return !this.isBeforeOrEqual(other);
  }
  isAfterOrEqual(other) {
    return !this.isBefore(other);
  }
  isEqual(other) {
    return this.c === other.c && this.e === other.e;
  }
  compareTo(other) {
    if (this.c < other.c) {
      return -1;
    } else if (this.c > other.line) {
      return 1;
    } else {
      if (this.e < other.e) {
        return -1;
      } else if (this.e > other.e) {
        return 1;
      } else {
        return 0;
      }
    }
  }
  translate(lineDeltaOrChange, characterDelta = 0) {
    if (lineDeltaOrChange === null || characterDelta === null) {
      throw $nb();
    }
    let lineDelta;
    if (typeof lineDeltaOrChange === "undefined") {
      lineDelta = 0;
    } else if (typeof lineDeltaOrChange === "number") {
      lineDelta = lineDeltaOrChange;
    } else {
      lineDelta = typeof lineDeltaOrChange.lineDelta === "number" ? lineDeltaOrChange.lineDelta : 0;
      characterDelta = typeof lineDeltaOrChange.characterDelta === "number" ? lineDeltaOrChange.characterDelta : 0;
    }
    if (lineDelta === 0 && characterDelta === 0) {
      return this;
    }
    return new $AT_1(this.line + lineDelta, this.character + characterDelta);
  }
  with(lineOrChange, character = this.character) {
    if (lineOrChange === null || character === null) {
      throw $nb();
    }
    let line;
    if (typeof lineOrChange === "undefined") {
      line = this.line;
    } else if (typeof lineOrChange === "number") {
      line = lineOrChange;
    } else {
      line = typeof lineOrChange.line === "number" ? lineOrChange.line : this.line;
      character = typeof lineOrChange.character === "number" ? lineOrChange.character : this.character;
    }
    if (line === this.line && character === this.character) {
      return this;
    }
    return new $AT_1(line, character);
  }
  toJSON() {
    return { line: this.line, character: this.character };
  }
  [Symbol.for("debug.description")]() {
    return `(${this.line}:${this.character})`;
  }
};
$AT = $AT_1 = __decorate([
  es5ClassCompat
], $AT);
var $BT = $BT_1 = class $BT2 {
  static isRange(thing) {
    if (thing instanceof $BT_1) {
      return true;
    }
    if (!thing) {
      return false;
    }
    return $AT.isPosition(thing.start) && $AT.isPosition(thing.end);
  }
  static of(obj) {
    if (obj instanceof $BT_1) {
      return obj;
    }
    if (this.isRange(obj)) {
      return new $BT_1(obj.start, obj.end);
    }
    throw new Error("Invalid argument, is NOT a range-like object");
  }
  get start() {
    return this.c;
  }
  get end() {
    return this.e;
  }
  constructor(startLineOrStart, startColumnOrEnd, endLine, endColumn) {
    let start;
    let end;
    if (typeof startLineOrStart === "number" && typeof startColumnOrEnd === "number" && typeof endLine === "number" && typeof endColumn === "number") {
      start = new $AT(startLineOrStart, startColumnOrEnd);
      end = new $AT(endLine, endColumn);
    } else if ($AT.isPosition(startLineOrStart) && $AT.isPosition(startColumnOrEnd)) {
      start = $AT.of(startLineOrStart);
      end = $AT.of(startColumnOrEnd);
    }
    if (!start || !end) {
      throw new Error("Invalid arguments");
    }
    if (start.isBefore(end)) {
      this.c = start;
      this.e = end;
    } else {
      this.c = end;
      this.e = start;
    }
  }
  contains(positionOrRange) {
    if ($BT_1.isRange(positionOrRange)) {
      return this.contains(positionOrRange.start) && this.contains(positionOrRange.end);
    } else if ($AT.isPosition(positionOrRange)) {
      if ($AT.of(positionOrRange).isBefore(this.c)) {
        return false;
      }
      if (this.e.isBefore(positionOrRange)) {
        return false;
      }
      return true;
    }
    return false;
  }
  isEqual(other) {
    return this.c.isEqual(other.c) && this.e.isEqual(other.e);
  }
  intersection(other) {
    const start = $AT.Max(other.start, this.c);
    const end = $AT.Min(other.end, this.e);
    if (start.isAfter(end)) {
      return void 0;
    }
    return new $BT_1(start, end);
  }
  union(other) {
    if (this.contains(other)) {
      return this;
    } else if (other.contains(this)) {
      return other;
    }
    const start = $AT.Min(other.start, this.c);
    const end = $AT.Max(other.end, this.end);
    return new $BT_1(start, end);
  }
  get isEmpty() {
    return this.c.isEqual(this.e);
  }
  get isSingleLine() {
    return this.c.line === this.e.line;
  }
  with(startOrChange, end = this.end) {
    if (startOrChange === null || end === null) {
      throw $nb();
    }
    let start;
    if (!startOrChange) {
      start = this.start;
    } else if ($AT.isPosition(startOrChange)) {
      start = startOrChange;
    } else {
      start = startOrChange.start || this.start;
      end = startOrChange.end || this.end;
    }
    if (start.isEqual(this.c) && end.isEqual(this.end)) {
      return this;
    }
    return new $BT_1(start, end);
  }
  toJSON() {
    return [this.start, this.end];
  }
  [Symbol.for("debug.description")]() {
    return $DT(this);
  }
};
$BT = $BT_1 = __decorate([
  es5ClassCompat
], $BT);
var $CT = $CT_1 = class $CT2 extends $BT {
  static isSelection(thing) {
    if (thing instanceof $CT_1) {
      return true;
    }
    if (!thing) {
      return false;
    }
    return $BT.isRange(thing) && $AT.isPosition(thing.anchor) && $AT.isPosition(thing.active) && typeof thing.isReversed === "boolean";
  }
  get anchor() {
    return this.f;
  }
  get active() {
    return this.g;
  }
  constructor(anchorLineOrAnchor, anchorColumnOrActive, activeLine, activeColumn) {
    let anchor;
    let active;
    if (typeof anchorLineOrAnchor === "number" && typeof anchorColumnOrActive === "number" && typeof activeLine === "number" && typeof activeColumn === "number") {
      anchor = new $AT(anchorLineOrAnchor, anchorColumnOrActive);
      active = new $AT(activeLine, activeColumn);
    } else if ($AT.isPosition(anchorLineOrAnchor) && $AT.isPosition(anchorColumnOrActive)) {
      anchor = $AT.of(anchorLineOrAnchor);
      active = $AT.of(anchorColumnOrActive);
    }
    if (!anchor || !active) {
      throw new Error("Invalid arguments");
    }
    super(anchor, active);
    this.f = anchor;
    this.g = active;
  }
  get isReversed() {
    return this.f === this.e;
  }
  toJSON() {
    return {
      start: this.start,
      end: this.end,
      active: this.active,
      anchor: this.anchor
    };
  }
  [Symbol.for("debug.description")]() {
    return $ET(this);
  }
};
$CT = $CT_1 = __decorate([
  es5ClassCompat
], $CT);
function $DT(range) {
  return range.isEmpty ? `[${range.start.line}:${range.start.character})` : `[${range.start.line}:${range.start.character} -> ${range.end.line}:${range.end.character})`;
}
function $ET(selection) {
  let rangeStr = $DT(selection);
  if (!selection.isEmpty) {
    if (selection.active.isEqual(selection.start)) {
      rangeStr = `|${rangeStr}`;
    } else {
      rangeStr = `${rangeStr}|`;
    }
  }
  return rangeStr;
}
var EndOfLine;
(function(EndOfLine3) {
  EndOfLine3[EndOfLine3["LF"] = 1] = "LF";
  EndOfLine3[EndOfLine3["CRLF"] = 2] = "CRLF";
})(EndOfLine || (EndOfLine = {}));
var EnvironmentVariableMutatorType;
(function(EnvironmentVariableMutatorType3) {
  EnvironmentVariableMutatorType3[EnvironmentVariableMutatorType3["Replace"] = 1] = "Replace";
  EnvironmentVariableMutatorType3[EnvironmentVariableMutatorType3["Append"] = 2] = "Append";
  EnvironmentVariableMutatorType3[EnvironmentVariableMutatorType3["Prepend"] = 3] = "Prepend";
})(EnvironmentVariableMutatorType || (EnvironmentVariableMutatorType = {}));
var $IT = $IT_1 = class $IT2 {
  static isTextEdit(thing) {
    if (thing instanceof $IT_1) {
      return true;
    }
    if (!thing) {
      return false;
    }
    return $BT.isRange(thing) && typeof thing.newText === "string";
  }
  static replace(range, newText) {
    return new $IT_1(range, newText);
  }
  static insert(position, newText) {
    return $IT_1.replace(new $BT(position, position), newText);
  }
  static delete(range) {
    return $IT_1.replace(range, "");
  }
  static setEndOfLine(eol) {
    const ret = new $IT_1(new $BT(new $AT(0, 0), new $AT(0, 0)), "");
    ret.newEol = eol;
    return ret;
  }
  get range() {
    return this.c;
  }
  set range(value) {
    if (value && !$BT.isRange(value)) {
      throw $nb("range");
    }
    this.c = value;
  }
  get newText() {
    return this.e || "";
  }
  set newText(value) {
    if (value && typeof value !== "string") {
      throw $nb("newText");
    }
    this.e = value;
  }
  get newEol() {
    return this.f;
  }
  set newEol(value) {
    if (value && typeof value !== "number") {
      throw $nb("newEol");
    }
    this.f = value;
  }
  constructor(range, newText) {
    this.c = range;
    this.e = newText;
  }
  toJSON() {
    return {
      range: this.range,
      newText: this.newText,
      newEol: this.f
    };
  }
};
$IT = $IT_1 = __decorate([
  es5ClassCompat
], $IT);
var $JT = $JT_1 = class $JT2 {
  static isNotebookCellEdit(thing) {
    if (thing instanceof $JT_1) {
      return true;
    }
    if (!thing) {
      return false;
    }
    return $6U.isNotebookRange(thing) && Array.isArray(thing.newCells);
  }
  static replaceCells(range, newCells) {
    return new $JT_1(range, newCells);
  }
  static insertCells(index, newCells) {
    return new $JT_1(new $6U(index, index), newCells);
  }
  static deleteCells(range) {
    return new $JT_1(range, []);
  }
  static updateCellMetadata(index, newMetadata) {
    const edit3 = new $JT_1(new $6U(index, index), []);
    edit3.newCellMetadata = newMetadata;
    return edit3;
  }
  static updateNotebookMetadata(newMetadata) {
    const edit3 = new $JT_1(new $6U(0, 0), []);
    edit3.newNotebookMetadata = newMetadata;
    return edit3;
  }
  constructor(range, newCells) {
    this.range = range;
    this.newCells = newCells;
  }
};
$JT = $JT_1 = __decorate([
  es5ClassCompat
], $JT);
var $KT = class _$KT {
  static isSnippetTextEdit(thing) {
    if (thing instanceof _$KT) {
      return true;
    }
    if (!thing) {
      return false;
    }
    return $BT.isRange(thing.range) && $MT.isSnippetString(thing.snippet);
  }
  static replace(range, snippet) {
    return new _$KT(range, snippet);
  }
  static insert(position, snippet) {
    return _$KT.replace(new $BT(position, position), snippet);
  }
  constructor(range, snippet) {
    this.range = range;
    this.snippet = snippet;
  }
};
var FileEditType;
(function(FileEditType2) {
  FileEditType2[FileEditType2["File"] = 1] = "File";
  FileEditType2[FileEditType2["Text"] = 2] = "Text";
  FileEditType2[FileEditType2["Cell"] = 3] = "Cell";
  FileEditType2[FileEditType2["CellReplace"] = 5] = "CellReplace";
  FileEditType2[FileEditType2["Snippet"] = 6] = "Snippet";
})(FileEditType || (FileEditType = {}));
var $LT = class $LT2 {
  constructor() {
    this.c = [];
  }
  _allEntries() {
    return this.c;
  }
  // --- file
  renameFile(from, to, options3, metadata) {
    this.c.push({ _type: 1, from, to, options: options3, metadata });
  }
  createFile(uri, options3, metadata) {
    this.c.push({ _type: 1, from: void 0, to: uri, options: options3, metadata });
  }
  deleteFile(uri, options3, metadata) {
    this.c.push({ _type: 1, from: uri, to: void 0, options: options3, metadata });
  }
  // --- notebook
  e(uri, value, metadata) {
    this.c.push({ _type: 3, metadata, uri, edit: { editType: 5, metadata: value } });
  }
  f(uri, startOrRange, cellData, metadata) {
    const start = startOrRange.start;
    const end = startOrRange.end;
    if (start !== end || cellData.length > 0) {
      this.c.push({ _type: 5, uri, index: start, count: end - start, cells: cellData, metadata });
    }
  }
  g(uri, index, cellMetadata, metadata) {
    this.c.push({ _type: 3, metadata, uri, edit: { editType: 3, index, metadata: cellMetadata } });
  }
  // --- text
  replace(uri, range, newText, metadata) {
    this.c.push({ _type: 2, uri, edit: new $IT(range, newText), metadata });
  }
  insert(resource, position, newText, metadata) {
    this.replace(resource, new $BT(position, position), newText, metadata);
  }
  delete(resource, range, metadata) {
    this.replace(resource, range, "", metadata);
  }
  // --- text (Maplike)
  has(uri) {
    return this.c.some((edit3) => edit3._type === 2 && edit3.uri.toString() === uri.toString());
  }
  set(uri, edits) {
    if (!edits) {
      for (let i2 = 0; i2 < this.c.length; i2++) {
        const element = this.c[i2];
        switch (element._type) {
          case 2:
          case 6:
          case 3:
          case 5:
            if (element.uri.toString() === uri.toString()) {
              this.c[i2] = void 0;
            }
            break;
        }
      }
      $Nb(this.c);
    } else {
      for (const editOrTuple of edits) {
        if (!editOrTuple) {
          continue;
        }
        let edit3;
        let metadata;
        if (Array.isArray(editOrTuple)) {
          edit3 = editOrTuple[0];
          metadata = editOrTuple[1];
        } else {
          edit3 = editOrTuple;
        }
        if ($JT.isNotebookCellEdit(edit3)) {
          if (edit3.newCellMetadata) {
            this.g(uri, edit3.range.start, edit3.newCellMetadata, metadata);
          } else if (edit3.newNotebookMetadata) {
            this.e(uri, edit3.newNotebookMetadata, metadata);
          } else {
            this.f(uri, edit3.range, edit3.newCells, metadata);
          }
        } else if ($KT.isSnippetTextEdit(edit3)) {
          this.c.push({ _type: 6, uri, range: edit3.range, edit: edit3.snippet, metadata });
        } else {
          this.c.push({ _type: 2, uri, edit: edit3, metadata });
        }
      }
    }
  }
  get(uri) {
    const res = [];
    for (const candidate of this.c) {
      if (candidate._type === 2 && candidate.uri.toString() === uri.toString()) {
        res.push(candidate.edit);
      }
    }
    return res;
  }
  entries() {
    const textEdits = new $Ec();
    for (const candidate of this.c) {
      if (candidate._type === 2) {
        let textEdit = textEdits.get(candidate.uri);
        if (!textEdit) {
          textEdit = [candidate.uri, []];
          textEdits.set(candidate.uri, textEdit);
        }
        textEdit[1].push(candidate.edit);
      }
    }
    return [...textEdits.values()];
  }
  get size() {
    return this.entries().length;
  }
  toJSON() {
    return this.entries();
  }
};
$LT = __decorate([
  es5ClassCompat
], $LT);
var $MT = $MT_1 = class $MT2 {
  static isSnippetString(thing) {
    if (thing instanceof $MT_1) {
      return true;
    }
    if (!thing) {
      return false;
    }
    return typeof thing.value === "string";
  }
  static c(value) {
    return value.replace(/\$|}|\\/g, "\\$&");
  }
  constructor(value) {
    this.e = 1;
    this.value = value || "";
  }
  appendText(string) {
    this.value += $MT_1.c(string);
    return this;
  }
  appendTabstop(number = this.e++) {
    this.value += "$";
    this.value += number;
    return this;
  }
  appendPlaceholder(value, number = this.e++) {
    if (typeof value === "function") {
      const nested = new $MT_1();
      nested.e = this.e;
      value(nested);
      this.e = nested.e;
      value = nested.value;
    } else {
      value = $MT_1.c(value);
    }
    this.value += "${";
    this.value += number;
    this.value += ":";
    this.value += value;
    this.value += "}";
    return this;
  }
  appendChoice(values, number = this.e++) {
    const value = values.map((s) => s.replaceAll(/[|\\,]/g, "\\$&")).join(",");
    this.value += "${";
    this.value += number;
    this.value += "|";
    this.value += value;
    this.value += "|}";
    return this;
  }
  appendVariable(name, defaultValue) {
    if (typeof defaultValue === "function") {
      const nested = new $MT_1();
      nested.e = this.e;
      defaultValue(nested);
      this.e = nested.e;
      defaultValue = nested.value;
    } else if (typeof defaultValue === "string") {
      defaultValue = defaultValue.replace(/\$|}/g, "\\$&");
    }
    this.value += "${";
    this.value += name;
    if (defaultValue) {
      this.value += ":";
      this.value += defaultValue;
    }
    this.value += "}";
    return this;
  }
};
$MT = $MT_1 = __decorate([
  es5ClassCompat
], $MT);
var DiagnosticTag;
(function(DiagnosticTag3) {
  DiagnosticTag3[DiagnosticTag3["Unnecessary"] = 1] = "Unnecessary";
  DiagnosticTag3[DiagnosticTag3["Deprecated"] = 2] = "Deprecated";
})(DiagnosticTag || (DiagnosticTag = {}));
var DiagnosticSeverity;
(function(DiagnosticSeverity3) {
  DiagnosticSeverity3[DiagnosticSeverity3["Hint"] = 3] = "Hint";
  DiagnosticSeverity3[DiagnosticSeverity3["Information"] = 2] = "Information";
  DiagnosticSeverity3[DiagnosticSeverity3["Warning"] = 1] = "Warning";
  DiagnosticSeverity3[DiagnosticSeverity3["Error"] = 0] = "Error";
})(DiagnosticSeverity || (DiagnosticSeverity = {}));
var $NT = $NT_1 = class $NT2 {
  static isLocation(thing) {
    if (thing instanceof $NT_1) {
      return true;
    }
    if (!thing) {
      return false;
    }
    return $BT.isRange(thing.range) && URI.isUri(thing.uri);
  }
  constructor(uri, rangeOrPosition) {
    this.uri = uri;
    if (!rangeOrPosition) {
    } else if ($BT.isRange(rangeOrPosition)) {
      this.range = $BT.of(rangeOrPosition);
    } else if ($AT.isPosition(rangeOrPosition)) {
      this.range = new $BT(rangeOrPosition, rangeOrPosition);
    } else {
      throw new Error("Illegal argument");
    }
  }
  toJSON() {
    return {
      uri: this.uri,
      range: this.range
    };
  }
};
$NT = $NT_1 = __decorate([
  es5ClassCompat
], $NT);
var $OT = class $OT2 {
  static is(thing) {
    if (!thing) {
      return false;
    }
    return typeof thing.message === "string" && thing.location && $BT.isRange(thing.location.range) && URI.isUri(thing.location.uri);
  }
  constructor(location3, message) {
    this.location = location3;
    this.message = message;
  }
  static isEqual(a, b) {
    if (a === b) {
      return true;
    }
    if (!a || !b) {
      return false;
    }
    return a.message === b.message && a.location.range.isEqual(b.location.range) && a.location.uri.toString() === b.location.uri.toString();
  }
};
$OT = __decorate([
  es5ClassCompat
], $OT);
var $PT = class $PT2 {
  constructor(range, message, severity = DiagnosticSeverity.Error) {
    if (!$BT.isRange(range)) {
      throw new TypeError("range must be set");
    }
    if (!message) {
      throw new TypeError("message must be set");
    }
    this.range = range;
    this.message = message;
    this.severity = severity;
  }
  toJSON() {
    return {
      severity: DiagnosticSeverity[this.severity],
      message: this.message,
      range: this.range,
      source: this.source,
      code: this.code
    };
  }
  static isEqual(a, b) {
    if (a === b) {
      return true;
    }
    if (!a || !b) {
      return false;
    }
    return a.message === b.message && a.severity === b.severity && a.code === b.code && a.severity === b.severity && a.source === b.source && a.range.isEqual(b.range) && $zb(a.tags, b.tags) && $zb(a.relatedInformation, b.relatedInformation, $OT.isEqual);
  }
};
$PT = __decorate([
  es5ClassCompat
], $PT);
var $QT = class $QT2 {
  constructor(contents, range) {
    if (!contents) {
      throw new Error("Illegal argument, contents must be defined");
    }
    if (Array.isArray(contents)) {
      this.contents = contents;
    } else {
      this.contents = [contents];
    }
    this.range = range;
  }
};
$QT = __decorate([
  es5ClassCompat
], $QT);
var $RT = class $RT2 extends $QT {
  constructor(contents, range, canIncreaseVerbosity, canDecreaseVerbosity) {
    super(contents, range);
    this.canIncreaseVerbosity = canIncreaseVerbosity;
    this.canDecreaseVerbosity = canDecreaseVerbosity;
  }
};
$RT = __decorate([
  es5ClassCompat
], $RT);
var HoverVerbosityAction2;
(function(HoverVerbosityAction4) {
  HoverVerbosityAction4[HoverVerbosityAction4["Increase"] = 0] = "Increase";
  HoverVerbosityAction4[HoverVerbosityAction4["Decrease"] = 1] = "Decrease";
})(HoverVerbosityAction2 || (HoverVerbosityAction2 = {}));
var DocumentHighlightKind2;
(function(DocumentHighlightKind4) {
  DocumentHighlightKind4[DocumentHighlightKind4["Text"] = 0] = "Text";
  DocumentHighlightKind4[DocumentHighlightKind4["Read"] = 1] = "Read";
  DocumentHighlightKind4[DocumentHighlightKind4["Write"] = 2] = "Write";
})(DocumentHighlightKind2 || (DocumentHighlightKind2 = {}));
var $ST = class $ST2 {
  constructor(range, kind = DocumentHighlightKind2.Text) {
    this.range = range;
    this.kind = kind;
  }
  toJSON() {
    return {
      range: this.range,
      kind: DocumentHighlightKind2[this.kind]
    };
  }
};
$ST = __decorate([
  es5ClassCompat
], $ST);
var $TT = class $TT2 {
  constructor(uri, highlights) {
    this.uri = uri;
    this.highlights = highlights;
  }
  toJSON() {
    return {
      uri: this.uri,
      highlights: this.highlights.map((h3) => h3.toJSON())
    };
  }
};
$TT = __decorate([
  es5ClassCompat
], $TT);
var SymbolKind2;
(function(SymbolKind5) {
  SymbolKind5[SymbolKind5["File"] = 0] = "File";
  SymbolKind5[SymbolKind5["Module"] = 1] = "Module";
  SymbolKind5[SymbolKind5["Namespace"] = 2] = "Namespace";
  SymbolKind5[SymbolKind5["Package"] = 3] = "Package";
  SymbolKind5[SymbolKind5["Class"] = 4] = "Class";
  SymbolKind5[SymbolKind5["Method"] = 5] = "Method";
  SymbolKind5[SymbolKind5["Property"] = 6] = "Property";
  SymbolKind5[SymbolKind5["Field"] = 7] = "Field";
  SymbolKind5[SymbolKind5["Constructor"] = 8] = "Constructor";
  SymbolKind5[SymbolKind5["Enum"] = 9] = "Enum";
  SymbolKind5[SymbolKind5["Interface"] = 10] = "Interface";
  SymbolKind5[SymbolKind5["Function"] = 11] = "Function";
  SymbolKind5[SymbolKind5["Variable"] = 12] = "Variable";
  SymbolKind5[SymbolKind5["Constant"] = 13] = "Constant";
  SymbolKind5[SymbolKind5["String"] = 14] = "String";
  SymbolKind5[SymbolKind5["Number"] = 15] = "Number";
  SymbolKind5[SymbolKind5["Boolean"] = 16] = "Boolean";
  SymbolKind5[SymbolKind5["Array"] = 17] = "Array";
  SymbolKind5[SymbolKind5["Object"] = 18] = "Object";
  SymbolKind5[SymbolKind5["Key"] = 19] = "Key";
  SymbolKind5[SymbolKind5["Null"] = 20] = "Null";
  SymbolKind5[SymbolKind5["EnumMember"] = 21] = "EnumMember";
  SymbolKind5[SymbolKind5["Struct"] = 22] = "Struct";
  SymbolKind5[SymbolKind5["Event"] = 23] = "Event";
  SymbolKind5[SymbolKind5["Operator"] = 24] = "Operator";
  SymbolKind5[SymbolKind5["TypeParameter"] = 25] = "TypeParameter";
})(SymbolKind2 || (SymbolKind2 = {}));
var SymbolTag2;
(function(SymbolTag5) {
  SymbolTag5[SymbolTag5["Deprecated"] = 1] = "Deprecated";
})(SymbolTag2 || (SymbolTag2 = {}));
var $UT = $UT_1 = class $UT2 {
  static validate(candidate) {
    if (!candidate.name) {
      throw new Error("name must not be falsy");
    }
  }
  constructor(name, kind, rangeOrContainer, locationOrUri, containerName) {
    this.name = name;
    this.kind = kind;
    this.containerName = containerName;
    if (typeof rangeOrContainer === "string") {
      this.containerName = rangeOrContainer;
    }
    if (locationOrUri instanceof $NT) {
      this.location = locationOrUri;
    } else if (rangeOrContainer instanceof $BT) {
      this.location = new $NT(locationOrUri, rangeOrContainer);
    }
    $UT_1.validate(this);
  }
  toJSON() {
    return {
      name: this.name,
      kind: SymbolKind2[this.kind],
      location: this.location,
      containerName: this.containerName
    };
  }
};
$UT = $UT_1 = __decorate([
  es5ClassCompat
], $UT);
var $VT = $VT_1 = class $VT2 {
  static validate(candidate) {
    if (!candidate.name) {
      throw new Error("name must not be falsy");
    }
    if (!candidate.range.contains(candidate.selectionRange)) {
      throw new Error("selectionRange must be contained in fullRange");
    }
    candidate.children?.forEach($VT_1.validate);
  }
  constructor(name, detail2, kind, range, selectionRange) {
    this.name = name;
    this.detail = detail2;
    this.kind = kind;
    this.range = range;
    this.selectionRange = selectionRange;
    this.children = [];
    $VT_1.validate(this);
  }
};
$VT = $VT_1 = __decorate([
  es5ClassCompat
], $VT);
var CodeActionTriggerKind;
(function(CodeActionTriggerKind3) {
  CodeActionTriggerKind3[CodeActionTriggerKind3["Invoke"] = 1] = "Invoke";
  CodeActionTriggerKind3[CodeActionTriggerKind3["Automatic"] = 2] = "Automatic";
})(CodeActionTriggerKind || (CodeActionTriggerKind = {}));
var $WT = class $WT2 {
  constructor(title, kind) {
    this.title = title;
    this.kind = kind;
  }
};
$WT = __decorate([
  es5ClassCompat
], $WT);
var $XT = class $XT2 {
  static {
    $XT_1 = this;
  }
  static {
    this.c = ".";
  }
  constructor(value) {
    this.value = value;
  }
  append(parts) {
    return new $XT_1(this.value ? this.value + $XT_1.c + parts : parts);
  }
  intersects(other) {
    return this.contains(other) || other.contains(this);
  }
  contains(other) {
    return this.value === other.value || other.value.startsWith(this.value + $XT_1.c);
  }
};
$XT = $XT_1 = __decorate([
  es5ClassCompat
], $XT);
$XT.Empty = new $XT("");
$XT.QuickFix = $XT.Empty.append("quickfix");
$XT.Refactor = $XT.Empty.append("refactor");
$XT.RefactorExtract = $XT.Refactor.append("extract");
$XT.RefactorInline = $XT.Refactor.append("inline");
$XT.RefactorMove = $XT.Refactor.append("move");
$XT.RefactorRewrite = $XT.Refactor.append("rewrite");
$XT.Source = $XT.Empty.append("source");
$XT.SourceOrganizeImports = $XT.Source.append("organizeImports");
$XT.SourceFixAll = $XT.Source.append("fixAll");
$XT.Notebook = $XT.Empty.append("notebook");
var $YT = class $YT2 {
  constructor(range, parent) {
    this.range = range;
    this.parent = parent;
    if (parent && !parent.range.contains(this.range)) {
      throw new Error("Invalid argument: parent must contain this range");
    }
  }
};
$YT = __decorate([
  es5ClassCompat
], $YT);
var $ZT = class {
  constructor(kind, name, detail2, uri, range, selectionRange) {
    this.kind = kind;
    this.name = name;
    this.detail = detail2;
    this.uri = uri;
    this.range = range;
    this.selectionRange = selectionRange;
  }
};
var $1T = class {
  constructor(item, fromRanges) {
    this.fromRanges = fromRanges;
    this.from = item;
  }
};
var $2T = class {
  constructor(item, fromRanges) {
    this.fromRanges = fromRanges;
    this.to = item;
  }
};
var LanguageStatusSeverity;
(function(LanguageStatusSeverity2) {
  LanguageStatusSeverity2[LanguageStatusSeverity2["Information"] = 0] = "Information";
  LanguageStatusSeverity2[LanguageStatusSeverity2["Warning"] = 1] = "Warning";
  LanguageStatusSeverity2[LanguageStatusSeverity2["Error"] = 2] = "Error";
})(LanguageStatusSeverity || (LanguageStatusSeverity = {}));
var $3T = class $3T2 {
  constructor(range, command4) {
    this.range = range;
    this.command = command4;
  }
  get isResolved() {
    return !!this.command;
  }
};
$3T = __decorate([
  es5ClassCompat
], $3T);
var $4T = $4T_1 = class $4T2 {
  #delegate;
  static isMarkdownString(thing) {
    if (thing instanceof $4T_1) {
      return true;
    }
    return thing && thing.appendCodeblock && thing.appendMarkdown && thing.appendText && thing.value !== void 0;
  }
  constructor(value, supportThemeIcons = false) {
    this.#delegate = new $bm(value, { supportThemeIcons });
  }
  get value() {
    return this.#delegate.value;
  }
  set value(value) {
    this.#delegate.value = value;
  }
  get isTrusted() {
    return this.#delegate.isTrusted;
  }
  set isTrusted(value) {
    this.#delegate.isTrusted = value;
  }
  get supportThemeIcons() {
    return this.#delegate.supportThemeIcons;
  }
  set supportThemeIcons(value) {
    this.#delegate.supportThemeIcons = value;
  }
  get supportHtml() {
    return this.#delegate.supportHtml;
  }
  set supportHtml(value) {
    this.#delegate.supportHtml = value;
  }
  get baseUri() {
    return this.#delegate.baseUri;
  }
  set baseUri(value) {
    this.#delegate.baseUri = value;
  }
  appendText(value) {
    this.#delegate.appendText(value);
    return this;
  }
  appendMarkdown(value) {
    this.#delegate.appendMarkdown(value);
    return this;
  }
  appendCodeblock(value, language) {
    this.#delegate.appendCodeblock(language ?? "", value);
    return this;
  }
};
$4T = $4T_1 = __decorate([
  es5ClassCompat
], $4T);
var $5T = class $5T2 {
  constructor(label3, documentation) {
    this.label = label3;
    this.documentation = documentation;
  }
};
$5T = __decorate([
  es5ClassCompat
], $5T);
var $6T = class $6T2 {
  constructor(label3, documentation) {
    this.label = label3;
    this.documentation = documentation;
    this.parameters = [];
  }
};
$6T = __decorate([
  es5ClassCompat
], $6T);
var $7T = class $7T2 {
  constructor() {
    this.activeSignature = 0;
    this.activeParameter = 0;
    this.signatures = [];
  }
};
$7T = __decorate([
  es5ClassCompat
], $7T);
var SignatureHelpTriggerKind2;
(function(SignatureHelpTriggerKind4) {
  SignatureHelpTriggerKind4[SignatureHelpTriggerKind4["Invoke"] = 1] = "Invoke";
  SignatureHelpTriggerKind4[SignatureHelpTriggerKind4["TriggerCharacter"] = 2] = "TriggerCharacter";
  SignatureHelpTriggerKind4[SignatureHelpTriggerKind4["ContentChange"] = 3] = "ContentChange";
})(SignatureHelpTriggerKind2 || (SignatureHelpTriggerKind2 = {}));
var InlayHintKind2;
(function(InlayHintKind5) {
  InlayHintKind5[InlayHintKind5["Type"] = 1] = "Type";
  InlayHintKind5[InlayHintKind5["Parameter"] = 2] = "Parameter";
})(InlayHintKind2 || (InlayHintKind2 = {}));
var $8T = class $8T2 {
  constructor(value) {
    this.value = value;
  }
};
$8T = __decorate([
  es5ClassCompat
], $8T);
var $9T = class $9T2 {
  constructor(position, label3, kind) {
    this.position = position;
    this.label = label3;
    this.kind = kind;
  }
};
$9T = __decorate([
  es5ClassCompat
], $9T);
var CompletionTriggerKind2;
(function(CompletionTriggerKind5) {
  CompletionTriggerKind5[CompletionTriggerKind5["Invoke"] = 0] = "Invoke";
  CompletionTriggerKind5[CompletionTriggerKind5["TriggerCharacter"] = 1] = "TriggerCharacter";
  CompletionTriggerKind5[CompletionTriggerKind5["TriggerForIncompleteCompletions"] = 2] = "TriggerForIncompleteCompletions";
})(CompletionTriggerKind2 || (CompletionTriggerKind2 = {}));
var CompletionItemKind2;
(function(CompletionItemKind5) {
  CompletionItemKind5[CompletionItemKind5["Text"] = 0] = "Text";
  CompletionItemKind5[CompletionItemKind5["Method"] = 1] = "Method";
  CompletionItemKind5[CompletionItemKind5["Function"] = 2] = "Function";
  CompletionItemKind5[CompletionItemKind5["Constructor"] = 3] = "Constructor";
  CompletionItemKind5[CompletionItemKind5["Field"] = 4] = "Field";
  CompletionItemKind5[CompletionItemKind5["Variable"] = 5] = "Variable";
  CompletionItemKind5[CompletionItemKind5["Class"] = 6] = "Class";
  CompletionItemKind5[CompletionItemKind5["Interface"] = 7] = "Interface";
  CompletionItemKind5[CompletionItemKind5["Module"] = 8] = "Module";
  CompletionItemKind5[CompletionItemKind5["Property"] = 9] = "Property";
  CompletionItemKind5[CompletionItemKind5["Unit"] = 10] = "Unit";
  CompletionItemKind5[CompletionItemKind5["Value"] = 11] = "Value";
  CompletionItemKind5[CompletionItemKind5["Enum"] = 12] = "Enum";
  CompletionItemKind5[CompletionItemKind5["Keyword"] = 13] = "Keyword";
  CompletionItemKind5[CompletionItemKind5["Snippet"] = 14] = "Snippet";
  CompletionItemKind5[CompletionItemKind5["Color"] = 15] = "Color";
  CompletionItemKind5[CompletionItemKind5["File"] = 16] = "File";
  CompletionItemKind5[CompletionItemKind5["Reference"] = 17] = "Reference";
  CompletionItemKind5[CompletionItemKind5["Folder"] = 18] = "Folder";
  CompletionItemKind5[CompletionItemKind5["EnumMember"] = 19] = "EnumMember";
  CompletionItemKind5[CompletionItemKind5["Constant"] = 20] = "Constant";
  CompletionItemKind5[CompletionItemKind5["Struct"] = 21] = "Struct";
  CompletionItemKind5[CompletionItemKind5["Event"] = 22] = "Event";
  CompletionItemKind5[CompletionItemKind5["Operator"] = 23] = "Operator";
  CompletionItemKind5[CompletionItemKind5["TypeParameter"] = 24] = "TypeParameter";
  CompletionItemKind5[CompletionItemKind5["User"] = 25] = "User";
  CompletionItemKind5[CompletionItemKind5["Issue"] = 26] = "Issue";
})(CompletionItemKind2 || (CompletionItemKind2 = {}));
var CompletionItemTag2;
(function(CompletionItemTag5) {
  CompletionItemTag5[CompletionItemTag5["Deprecated"] = 1] = "Deprecated";
})(CompletionItemTag2 || (CompletionItemTag2 = {}));
var $0T = class $0T2 {
  constructor(label3, kind) {
    this.label = label3;
    this.kind = kind;
  }
  toJSON() {
    return {
      label: this.label,
      kind: this.kind && CompletionItemKind2[this.kind],
      detail: this.detail,
      documentation: this.documentation,
      sortText: this.sortText,
      filterText: this.filterText,
      preselect: this.preselect,
      insertText: this.insertText,
      textEdit: this.textEdit
    };
  }
};
$0T = __decorate([
  es5ClassCompat
], $0T);
var $$T = class $$T2 {
  constructor(items = [], isIncomplete = false) {
    this.items = items;
    this.isIncomplete = isIncomplete;
  }
};
$$T = __decorate([
  es5ClassCompat
], $$T);
var $_T = class $_T2 {
  constructor(insertText, range, command4) {
    this.insertText = insertText;
    this.range = range;
    this.command = command4;
  }
};
$_T = __decorate([
  es5ClassCompat
], $_T);
var $aU = class $aU2 {
  constructor(items) {
    this.commands = void 0;
    this.suppressSuggestions = void 0;
    this.items = items;
  }
};
$aU = __decorate([
  es5ClassCompat
], $aU);
var PartialAcceptTriggerKind2;
(function(PartialAcceptTriggerKind5) {
  PartialAcceptTriggerKind5[PartialAcceptTriggerKind5["Unknown"] = 0] = "Unknown";
  PartialAcceptTriggerKind5[PartialAcceptTriggerKind5["Word"] = 1] = "Word";
  PartialAcceptTriggerKind5[PartialAcceptTriggerKind5["Line"] = 2] = "Line";
  PartialAcceptTriggerKind5[PartialAcceptTriggerKind5["Suggest"] = 3] = "Suggest";
})(PartialAcceptTriggerKind2 || (PartialAcceptTriggerKind2 = {}));
var ViewColumn;
(function(ViewColumn3) {
  ViewColumn3[ViewColumn3["Active"] = -1] = "Active";
  ViewColumn3[ViewColumn3["Beside"] = -2] = "Beside";
  ViewColumn3[ViewColumn3["One"] = 1] = "One";
  ViewColumn3[ViewColumn3["Two"] = 2] = "Two";
  ViewColumn3[ViewColumn3["Three"] = 3] = "Three";
  ViewColumn3[ViewColumn3["Four"] = 4] = "Four";
  ViewColumn3[ViewColumn3["Five"] = 5] = "Five";
  ViewColumn3[ViewColumn3["Six"] = 6] = "Six";
  ViewColumn3[ViewColumn3["Seven"] = 7] = "Seven";
  ViewColumn3[ViewColumn3["Eight"] = 8] = "Eight";
  ViewColumn3[ViewColumn3["Nine"] = 9] = "Nine";
})(ViewColumn || (ViewColumn = {}));
var StatusBarAlignment;
(function(StatusBarAlignment2) {
  StatusBarAlignment2[StatusBarAlignment2["Left"] = 1] = "Left";
  StatusBarAlignment2[StatusBarAlignment2["Right"] = 2] = "Right";
})(StatusBarAlignment || (StatusBarAlignment = {}));
function $bU(extension, id2) {
  return `${$5z.toKey(extension)}.${id2}`;
}
var TextEditorLineNumbersStyle;
(function(TextEditorLineNumbersStyle3) {
  TextEditorLineNumbersStyle3[TextEditorLineNumbersStyle3["Off"] = 0] = "Off";
  TextEditorLineNumbersStyle3[TextEditorLineNumbersStyle3["On"] = 1] = "On";
  TextEditorLineNumbersStyle3[TextEditorLineNumbersStyle3["Relative"] = 2] = "Relative";
  TextEditorLineNumbersStyle3[TextEditorLineNumbersStyle3["Interval"] = 3] = "Interval";
})(TextEditorLineNumbersStyle || (TextEditorLineNumbersStyle = {}));
var TextDocumentSaveReason;
(function(TextDocumentSaveReason3) {
  TextDocumentSaveReason3[TextDocumentSaveReason3["Manual"] = 1] = "Manual";
  TextDocumentSaveReason3[TextDocumentSaveReason3["AfterDelay"] = 2] = "AfterDelay";
  TextDocumentSaveReason3[TextDocumentSaveReason3["FocusOut"] = 3] = "FocusOut";
})(TextDocumentSaveReason || (TextDocumentSaveReason = {}));
var TextEditorRevealType;
(function(TextEditorRevealType3) {
  TextEditorRevealType3[TextEditorRevealType3["Default"] = 0] = "Default";
  TextEditorRevealType3[TextEditorRevealType3["InCenter"] = 1] = "InCenter";
  TextEditorRevealType3[TextEditorRevealType3["InCenterIfOutsideViewport"] = 2] = "InCenterIfOutsideViewport";
  TextEditorRevealType3[TextEditorRevealType3["AtTop"] = 3] = "AtTop";
})(TextEditorRevealType || (TextEditorRevealType = {}));
var TextEditorSelectionChangeKind;
(function(TextEditorSelectionChangeKind2) {
  TextEditorSelectionChangeKind2[TextEditorSelectionChangeKind2["Keyboard"] = 1] = "Keyboard";
  TextEditorSelectionChangeKind2[TextEditorSelectionChangeKind2["Mouse"] = 2] = "Mouse";
  TextEditorSelectionChangeKind2[TextEditorSelectionChangeKind2["Command"] = 3] = "Command";
})(TextEditorSelectionChangeKind || (TextEditorSelectionChangeKind = {}));
var TextEditorChangeKind;
(function(TextEditorChangeKind2) {
  TextEditorChangeKind2[TextEditorChangeKind2["Addition"] = 1] = "Addition";
  TextEditorChangeKind2[TextEditorChangeKind2["Deletion"] = 2] = "Deletion";
  TextEditorChangeKind2[TextEditorChangeKind2["Modification"] = 3] = "Modification";
})(TextEditorChangeKind || (TextEditorChangeKind = {}));
var TextDocumentChangeReason;
(function(TextDocumentChangeReason2) {
  TextDocumentChangeReason2[TextDocumentChangeReason2["Undo"] = 1] = "Undo";
  TextDocumentChangeReason2[TextDocumentChangeReason2["Redo"] = 2] = "Redo";
})(TextDocumentChangeReason || (TextDocumentChangeReason = {}));
var DecorationRangeBehavior;
(function(DecorationRangeBehavior3) {
  DecorationRangeBehavior3[DecorationRangeBehavior3["OpenOpen"] = 0] = "OpenOpen";
  DecorationRangeBehavior3[DecorationRangeBehavior3["ClosedClosed"] = 1] = "ClosedClosed";
  DecorationRangeBehavior3[DecorationRangeBehavior3["OpenClosed"] = 2] = "OpenClosed";
  DecorationRangeBehavior3[DecorationRangeBehavior3["ClosedOpen"] = 3] = "ClosedOpen";
})(DecorationRangeBehavior || (DecorationRangeBehavior = {}));
(function(TextEditorSelectionChangeKind2) {
  function fromValue(s) {
    switch (s) {
      case "keyboard":
        return TextEditorSelectionChangeKind2.Keyboard;
      case "mouse":
        return TextEditorSelectionChangeKind2.Mouse;
      case "api":
        return TextEditorSelectionChangeKind2.Command;
    }
    return void 0;
  }
  TextEditorSelectionChangeKind2.fromValue = fromValue;
})(TextEditorSelectionChangeKind || (TextEditorSelectionChangeKind = {}));
var SyntaxTokenType;
(function(SyntaxTokenType2) {
  SyntaxTokenType2[SyntaxTokenType2["Other"] = 0] = "Other";
  SyntaxTokenType2[SyntaxTokenType2["Comment"] = 1] = "Comment";
  SyntaxTokenType2[SyntaxTokenType2["String"] = 2] = "String";
  SyntaxTokenType2[SyntaxTokenType2["RegEx"] = 3] = "RegEx";
})(SyntaxTokenType || (SyntaxTokenType = {}));
(function(SyntaxTokenType2) {
  function toString(v) {
    switch (v) {
      case SyntaxTokenType2.Other:
        return "other";
      case SyntaxTokenType2.Comment:
        return "comment";
      case SyntaxTokenType2.String:
        return "string";
      case SyntaxTokenType2.RegEx:
        return "regex";
    }
    return "other";
  }
  SyntaxTokenType2.toString = toString;
})(SyntaxTokenType || (SyntaxTokenType = {}));
var $cU = class $cU2 {
  constructor(range, target) {
    if (target && !URI.isUri(target)) {
      throw $nb("target");
    }
    if (!$BT.isRange(range) || range.isEmpty) {
      throw $nb("range");
    }
    this.range = range;
    this.target = target;
  }
};
$cU = __decorate([
  es5ClassCompat
], $cU);
var $dU = class $dU2 {
  constructor(red, green, blue, alpha) {
    this.red = red;
    this.green = green;
    this.blue = blue;
    this.alpha = alpha;
  }
};
$dU = __decorate([
  es5ClassCompat
], $dU);
var $eU = class $eU2 {
  constructor(range, color2) {
    if (color2 && !(color2 instanceof $dU)) {
      throw $nb("color");
    }
    if (!$BT.isRange(range) || range.isEmpty) {
      throw $nb("range");
    }
    this.range = range;
    this.color = color2;
  }
};
$eU = __decorate([
  es5ClassCompat
], $eU);
var $fU = class $fU2 {
  constructor(label3) {
    if (!label3 || typeof label3 !== "string") {
      throw $nb("label");
    }
    this.label = label3;
  }
};
$fU = __decorate([
  es5ClassCompat
], $fU);
var ColorFormat;
(function(ColorFormat2) {
  ColorFormat2[ColorFormat2["RGB"] = 0] = "RGB";
  ColorFormat2[ColorFormat2["HEX"] = 1] = "HEX";
  ColorFormat2[ColorFormat2["HSL"] = 2] = "HSL";
})(ColorFormat || (ColorFormat = {}));
var SourceControlInputBoxValidationType;
(function(SourceControlInputBoxValidationType2) {
  SourceControlInputBoxValidationType2[SourceControlInputBoxValidationType2["Error"] = 0] = "Error";
  SourceControlInputBoxValidationType2[SourceControlInputBoxValidationType2["Warning"] = 1] = "Warning";
  SourceControlInputBoxValidationType2[SourceControlInputBoxValidationType2["Information"] = 2] = "Information";
})(SourceControlInputBoxValidationType || (SourceControlInputBoxValidationType = {}));
var TerminalExitReason;
(function(TerminalExitReason3) {
  TerminalExitReason3[TerminalExitReason3["Unknown"] = 0] = "Unknown";
  TerminalExitReason3[TerminalExitReason3["Shutdown"] = 1] = "Shutdown";
  TerminalExitReason3[TerminalExitReason3["Process"] = 2] = "Process";
  TerminalExitReason3[TerminalExitReason3["User"] = 3] = "User";
  TerminalExitReason3[TerminalExitReason3["Extension"] = 4] = "Extension";
})(TerminalExitReason || (TerminalExitReason = {}));
var TerminalShellExecutionCommandLineConfidence;
(function(TerminalShellExecutionCommandLineConfidence2) {
  TerminalShellExecutionCommandLineConfidence2[TerminalShellExecutionCommandLineConfidence2["Low"] = 0] = "Low";
  TerminalShellExecutionCommandLineConfidence2[TerminalShellExecutionCommandLineConfidence2["Medium"] = 1] = "Medium";
  TerminalShellExecutionCommandLineConfidence2[TerminalShellExecutionCommandLineConfidence2["High"] = 2] = "High";
})(TerminalShellExecutionCommandLineConfidence || (TerminalShellExecutionCommandLineConfidence = {}));
var TerminalLocation;
(function(TerminalLocation3) {
  TerminalLocation3[TerminalLocation3["Panel"] = 1] = "Panel";
  TerminalLocation3[TerminalLocation3["Editor"] = 2] = "Editor";
})(TerminalLocation || (TerminalLocation = {}));
var TerminalCompletionItemKind;
(function(TerminalCompletionItemKind3) {
  TerminalCompletionItemKind3[TerminalCompletionItemKind3["File"] = 0] = "File";
  TerminalCompletionItemKind3[TerminalCompletionItemKind3["Folder"] = 1] = "Folder";
  TerminalCompletionItemKind3[TerminalCompletionItemKind3["Flag"] = 2] = "Flag";
  TerminalCompletionItemKind3[TerminalCompletionItemKind3["Method"] = 3] = "Method";
  TerminalCompletionItemKind3[TerminalCompletionItemKind3["Argument"] = 4] = "Argument";
})(TerminalCompletionItemKind || (TerminalCompletionItemKind = {}));
var TaskRevealKind;
(function(TaskRevealKind2) {
  TaskRevealKind2[TaskRevealKind2["Always"] = 1] = "Always";
  TaskRevealKind2[TaskRevealKind2["Silent"] = 2] = "Silent";
  TaskRevealKind2[TaskRevealKind2["Never"] = 3] = "Never";
})(TaskRevealKind || (TaskRevealKind = {}));
var TaskPanelKind;
(function(TaskPanelKind2) {
  TaskPanelKind2[TaskPanelKind2["Shared"] = 1] = "Shared";
  TaskPanelKind2[TaskPanelKind2["Dedicated"] = 2] = "Dedicated";
  TaskPanelKind2[TaskPanelKind2["New"] = 3] = "New";
})(TaskPanelKind || (TaskPanelKind = {}));
var $mU = class $mU2 {
  static {
    $mU_1 = this;
  }
  static {
    this.Clean = new $mU_1("clean", "Clean");
  }
  static {
    this.Build = new $mU_1("build", "Build");
  }
  static {
    this.Rebuild = new $mU_1("rebuild", "Rebuild");
  }
  static {
    this.Test = new $mU_1("test", "Test");
  }
  static from(value) {
    switch (value) {
      case "clean":
        return $mU_1.Clean;
      case "build":
        return $mU_1.Build;
      case "rebuild":
        return $mU_1.Rebuild;
      case "test":
        return $mU_1.Test;
      default:
        return void 0;
    }
  }
  constructor(id2, label3) {
    this.label = label3;
    if (typeof id2 !== "string") {
      throw $nb("name");
    }
    if (typeof label3 !== "string") {
      throw $nb("name");
    }
    this.c = id2;
  }
  get id() {
    return this.c;
  }
};
$mU = $mU_1 = __decorate([
  es5ClassCompat
], $mU);
function computeTaskExecutionId(values) {
  let id2 = "";
  for (let i2 = 0; i2 < values.length; i2++) {
    id2 += values[i2].replace(/,/g, ",,") + ",";
  }
  return id2;
}
var $nU = class $nU2 {
  constructor(process2, varg1, varg2) {
    if (typeof process2 !== "string") {
      throw $nb("process");
    }
    this.e = [];
    this.c = process2;
    if (varg1 !== void 0) {
      if (Array.isArray(varg1)) {
        this.e = varg1;
        this.f = varg2;
      } else {
        this.f = varg1;
      }
    }
  }
  get process() {
    return this.c;
  }
  set process(value) {
    if (typeof value !== "string") {
      throw $nb("process");
    }
    this.c = value;
  }
  get args() {
    return this.e;
  }
  set args(value) {
    if (!Array.isArray(value)) {
      value = [];
    }
    this.e = value;
  }
  get options() {
    return this.f;
  }
  set options(value) {
    this.f = value;
  }
  computeId() {
    const props = [];
    props.push("process");
    if (this.c !== void 0) {
      props.push(this.c);
    }
    if (this.e && this.e.length > 0) {
      for (const arg of this.e) {
        props.push(arg);
      }
    }
    return computeTaskExecutionId(props);
  }
};
$nU = __decorate([
  es5ClassCompat
], $nU);
var $oU = class $oU2 {
  constructor(arg0, arg1, arg2) {
    this.f = [];
    if (Array.isArray(arg1)) {
      if (!arg0) {
        throw $nb("command can't be undefined or null");
      }
      if (typeof arg0 !== "string" && typeof arg0.value !== "string") {
        throw $nb("command");
      }
      this.e = arg0;
      this.f = arg1;
      this.g = arg2;
    } else {
      if (typeof arg0 !== "string") {
        throw $nb("commandLine");
      }
      this.c = arg0;
      this.g = arg1;
    }
  }
  get commandLine() {
    return this.c;
  }
  set commandLine(value) {
    if (typeof value !== "string") {
      throw $nb("commandLine");
    }
    this.c = value;
  }
  get command() {
    return this.e ? this.e : "";
  }
  set command(value) {
    if (typeof value !== "string" && typeof value.value !== "string") {
      throw $nb("command");
    }
    this.e = value;
  }
  get args() {
    return this.f;
  }
  set args(value) {
    this.f = value || [];
  }
  get options() {
    return this.g;
  }
  set options(value) {
    this.g = value;
  }
  computeId() {
    const props = [];
    props.push("shell");
    if (this.c !== void 0) {
      props.push(this.c);
    }
    if (this.e !== void 0) {
      props.push(typeof this.e === "string" ? this.e : this.e.value);
    }
    if (this.f && this.f.length > 0) {
      for (const arg of this.f) {
        props.push(typeof arg === "string" ? arg : arg.value);
      }
    }
    return computeTaskExecutionId(props);
  }
};
$oU = __decorate([
  es5ClassCompat
], $oU);
var ShellQuoting;
(function(ShellQuoting4) {
  ShellQuoting4[ShellQuoting4["Escape"] = 1] = "Escape";
  ShellQuoting4[ShellQuoting4["Strong"] = 2] = "Strong";
  ShellQuoting4[ShellQuoting4["Weak"] = 3] = "Weak";
})(ShellQuoting || (ShellQuoting = {}));
var TaskScope;
(function(TaskScope3) {
  TaskScope3[TaskScope3["Global"] = 1] = "Global";
  TaskScope3[TaskScope3["Workspace"] = 2] = "Workspace";
})(TaskScope || (TaskScope = {}));
var $pU = class {
  constructor(callback) {
    this.c = callback;
  }
  computeId() {
    return "customExecution" + $ps();
  }
  set callback(value) {
    this.c = value;
  }
  get callback() {
    return this.c;
  }
};
var $qU = class $qU2 {
  static {
    $qU_1 = this;
  }
  static {
    this.c = "customExecution";
  }
  static {
    this.e = "process";
  }
  static {
    this.f = "shell";
  }
  static {
    this.g = "$empty";
  }
  constructor(definition, arg2, arg3, arg4, arg5, arg6) {
    this.k = false;
    this.l = this.definition = definition;
    let problemMatchers;
    if (typeof arg2 === "string") {
      this.o = this.name = arg2;
      this.w = this.source = arg3;
      this.execution = arg4;
      problemMatchers = arg5;
      this.k = true;
    } else if (arg2 === TaskScope.Global || arg2 === TaskScope.Workspace) {
      this.target = arg2;
      this.o = this.name = arg3;
      this.w = this.source = arg4;
      this.execution = arg5;
      problemMatchers = arg6;
    } else {
      this.target = arg2;
      this.o = this.name = arg3;
      this.w = this.source = arg4;
      this.execution = arg5;
      problemMatchers = arg6;
    }
    if (typeof problemMatchers === "string") {
      this.r = [problemMatchers];
      this.t = true;
    } else if (Array.isArray(problemMatchers)) {
      this.r = problemMatchers;
      this.t = true;
    } else {
      this.r = [];
      this.t = false;
    }
    this.u = false;
    this.y = /* @__PURE__ */ Object.create(null);
    this.z = /* @__PURE__ */ Object.create(null);
  }
  get _id() {
    return this.j;
  }
  set _id(value) {
    this.j = value;
  }
  get _deprecated() {
    return this.k;
  }
  B() {
    if (this.j === void 0) {
      return;
    }
    this.j = void 0;
    this.m = void 0;
    this.C();
  }
  C() {
    if (this.q instanceof $nU) {
      this.l = {
        type: $qU_1.e,
        id: this.q.computeId()
      };
    } else if (this.q instanceof $oU) {
      this.l = {
        type: $qU_1.f,
        id: this.q.computeId()
      };
    } else if (this.q instanceof $pU) {
      this.l = {
        type: $qU_1.c,
        id: this.q.computeId()
      };
    } else {
      this.l = {
        type: $qU_1.g,
        id: $ps()
      };
    }
  }
  get definition() {
    return this.l;
  }
  set definition(value) {
    if (value === void 0 || value === null) {
      throw $nb("Kind can't be undefined or null");
    }
    this.B();
    this.l = value;
  }
  get scope() {
    return this.m;
  }
  set target(value) {
    this.B();
    this.m = value;
  }
  get name() {
    return this.o;
  }
  set name(value) {
    if (typeof value !== "string") {
      throw $nb("name");
    }
    this.B();
    this.o = value;
  }
  get execution() {
    return this.q;
  }
  set execution(value) {
    if (value === null) {
      value = void 0;
    }
    this.B();
    this.q = value;
    const type = this.l.type;
    if ($qU_1.g === type || $qU_1.e === type || $qU_1.f === type || $qU_1.c === type) {
      this.C();
    }
  }
  get problemMatchers() {
    return this.r;
  }
  set problemMatchers(value) {
    if (!Array.isArray(value)) {
      this.B();
      this.r = [];
      this.t = false;
      return;
    } else {
      this.B();
      this.r = value;
      this.t = true;
    }
  }
  get hasDefinedMatchers() {
    return this.t;
  }
  get isBackground() {
    return this.u;
  }
  set isBackground(value) {
    if (value !== true && value !== false) {
      value = false;
    }
    this.B();
    this.u = value;
  }
  get source() {
    return this.w;
  }
  set source(value) {
    if (typeof value !== "string" || value.length === 0) {
      throw $nb("source must be a string of length > 0");
    }
    this.B();
    this.w = value;
  }
  get group() {
    return this.x;
  }
  set group(value) {
    if (value === null) {
      value = void 0;
    }
    this.B();
    this.x = value;
  }
  get detail() {
    return this.A;
  }
  set detail(value) {
    if (value === null) {
      value = void 0;
    }
    this.A = value;
  }
  get presentationOptions() {
    return this.y;
  }
  set presentationOptions(value) {
    if (value === null || value === void 0) {
      value = /* @__PURE__ */ Object.create(null);
    }
    this.B();
    this.y = value;
  }
  get runOptions() {
    return this.z;
  }
  set runOptions(value) {
    if (value === null || value === void 0) {
      value = /* @__PURE__ */ Object.create(null);
    }
    this.B();
    this.z = value;
  }
};
$qU = $qU_1 = __decorate([
  es5ClassCompat
], $qU);
var ProgressLocation2;
(function(ProgressLocation4) {
  ProgressLocation4[ProgressLocation4["SourceControl"] = 1] = "SourceControl";
  ProgressLocation4[ProgressLocation4["Window"] = 10] = "Window";
  ProgressLocation4[ProgressLocation4["Notification"] = 15] = "Notification";
})(ProgressLocation2 || (ProgressLocation2 = {}));
var ViewBadge;
(function(ViewBadge3) {
  function isViewBadge(thing) {
    const viewBadgeThing = thing;
    if (!$Dg(viewBadgeThing.value)) {
      console.log("INVALID view badge, invalid value", viewBadgeThing.value);
      return false;
    }
    if (viewBadgeThing.tooltip && !$zg(viewBadgeThing.tooltip)) {
      console.log("INVALID view badge, invalid tooltip", viewBadgeThing.tooltip);
      return false;
    }
    return true;
  }
  ViewBadge3.isViewBadge = isViewBadge;
})(ViewBadge || (ViewBadge = {}));
var $rU = $rU_1 = class $rU2 {
  static isTreeItem(thing, extension) {
    const treeItemThing = thing;
    if (treeItemThing.checkboxState !== void 0) {
      const checkbox = $Dg(treeItemThing.checkboxState) ? treeItemThing.checkboxState : $Bg(treeItemThing.checkboxState) && $Dg(treeItemThing.checkboxState.state) ? treeItemThing.checkboxState.state : void 0;
      const tooltip = !$Dg(treeItemThing.checkboxState) && $Bg(treeItemThing.checkboxState) ? treeItemThing.checkboxState.tooltip : void 0;
      if (checkbox === void 0 || checkbox !== TreeItemCheckboxState.Checked && checkbox !== TreeItemCheckboxState.Unchecked || tooltip !== void 0 && !$zg(tooltip)) {
        console.log("INVALID tree item, invalid checkboxState", treeItemThing.checkboxState);
        return false;
      }
    }
    if (thing instanceof $rU_1) {
      return true;
    }
    if (treeItemThing.label !== void 0 && !$zg(treeItemThing.label) && !treeItemThing.label?.label) {
      console.log("INVALID tree item, invalid label", treeItemThing.label);
      return false;
    }
    if (treeItemThing.id !== void 0 && !$zg(treeItemThing.id)) {
      console.log("INVALID tree item, invalid id", treeItemThing.id);
      return false;
    }
    if (treeItemThing.iconPath !== void 0 && !$zg(treeItemThing.iconPath) && !URI.isUri(treeItemThing.iconPath) && (!treeItemThing.iconPath || !$zg(treeItemThing.iconPath.id))) {
      const asLightAndDarkThing = treeItemThing.iconPath;
      if (!asLightAndDarkThing || !$zg(asLightAndDarkThing.light) && !URI.isUri(asLightAndDarkThing.light) && !$zg(asLightAndDarkThing.dark) && !URI.isUri(asLightAndDarkThing.dark)) {
        console.log("INVALID tree item, invalid iconPath", treeItemThing.iconPath);
        return false;
      }
    }
    if (treeItemThing.description !== void 0 && !$zg(treeItemThing.description) && typeof treeItemThing.description !== "boolean") {
      console.log("INVALID tree item, invalid description", treeItemThing.description);
      return false;
    }
    if (treeItemThing.resourceUri !== void 0 && !URI.isUri(treeItemThing.resourceUri)) {
      console.log("INVALID tree item, invalid resourceUri", treeItemThing.resourceUri);
      return false;
    }
    if (treeItemThing.tooltip !== void 0 && !$zg(treeItemThing.tooltip) && !(treeItemThing.tooltip instanceof $4T)) {
      console.log("INVALID tree item, invalid tooltip", treeItemThing.tooltip);
      return false;
    }
    if (treeItemThing.command !== void 0 && !treeItemThing.command.command) {
      console.log("INVALID tree item, invalid command", treeItemThing.command);
      return false;
    }
    if (treeItemThing.collapsibleState !== void 0 && treeItemThing.collapsibleState < TreeItemCollapsibleState.None && treeItemThing.collapsibleState > TreeItemCollapsibleState.Expanded) {
      console.log("INVALID tree item, invalid collapsibleState", treeItemThing.collapsibleState);
      return false;
    }
    if (treeItemThing.contextValue !== void 0 && !$zg(treeItemThing.contextValue)) {
      console.log("INVALID tree item, invalid contextValue", treeItemThing.contextValue);
      return false;
    }
    if (treeItemThing.accessibilityInformation !== void 0 && !treeItemThing.accessibilityInformation?.label) {
      console.log("INVALID tree item, invalid accessibilityInformation", treeItemThing.accessibilityInformation);
      return false;
    }
    return true;
  }
  constructor(arg1, collapsibleState = TreeItemCollapsibleState.None) {
    this.collapsibleState = collapsibleState;
    if (URI.isUri(arg1)) {
      this.resourceUri = arg1;
    } else {
      this.label = arg1;
    }
  }
};
$rU = $rU_1 = __decorate([
  es5ClassCompat
], $rU);
var TreeItemCollapsibleState;
(function(TreeItemCollapsibleState3) {
  TreeItemCollapsibleState3[TreeItemCollapsibleState3["None"] = 0] = "None";
  TreeItemCollapsibleState3[TreeItemCollapsibleState3["Collapsed"] = 1] = "Collapsed";
  TreeItemCollapsibleState3[TreeItemCollapsibleState3["Expanded"] = 2] = "Expanded";
})(TreeItemCollapsibleState || (TreeItemCollapsibleState = {}));
var TreeItemCheckboxState;
(function(TreeItemCheckboxState2) {
  TreeItemCheckboxState2[TreeItemCheckboxState2["Unchecked"] = 0] = "Unchecked";
  TreeItemCheckboxState2[TreeItemCheckboxState2["Checked"] = 1] = "Checked";
})(TreeItemCheckboxState || (TreeItemCheckboxState = {}));
var $sU = class $sU2 {
  async asString() {
    return typeof this.value === "string" ? this.value : JSON.stringify(this.value);
  }
  asFile() {
    return void 0;
  }
  constructor(value) {
    this.value = value;
  }
};
$sU = __decorate([
  es5ClassCompat
], $sU);
var $tU = class extends $sU {
};
var $uU = class extends $tU {
  #file;
  constructor(file) {
    super("");
    this.#file = file;
  }
  asFile() {
    return this.#file;
  }
};
var $vU = class {
  constructor(name, uri, itemId, getData) {
    this.name = name;
    this.uri = uri;
    this._itemId = itemId;
    this.c = getData;
  }
  data() {
    return this.c();
  }
};
var $wU = class $wU2 {
  #items = /* @__PURE__ */ new Map();
  constructor(init) {
    for (const [mime, item] of init ?? []) {
      const existing = this.#items.get(this.#normalizeMime(mime));
      if (existing) {
        existing.push(item);
      } else {
        this.#items.set(this.#normalizeMime(mime), [item]);
      }
    }
  }
  get(mimeType) {
    return this.#items.get(this.#normalizeMime(mimeType))?.[0];
  }
  set(mimeType, value) {
    this.#items.set(this.#normalizeMime(mimeType), [value]);
  }
  forEach(callbackfn, thisArg) {
    for (const [mime, items] of this.#items) {
      for (const item of items) {
        callbackfn.call(thisArg, item, mime, this);
      }
    }
  }
  *[Symbol.iterator]() {
    for (const [mime, items] of this.#items) {
      for (const item of items) {
        yield [mime, item];
      }
    }
  }
  #normalizeMime(mimeType) {
    return mimeType.toLowerCase();
  }
};
$wU = __decorate([
  es5ClassCompat
], $wU);
var $xU = class $xU2 {
  constructor(insertText, title, kind) {
    this.insertText = insertText;
    this.title = title;
    this.kind = kind;
  }
};
$xU = __decorate([
  es5ClassCompat
], $xU);
var DocumentPasteTriggerKind2;
(function(DocumentPasteTriggerKind3) {
  DocumentPasteTriggerKind3[DocumentPasteTriggerKind3["Automatic"] = 0] = "Automatic";
  DocumentPasteTriggerKind3[DocumentPasteTriggerKind3["PasteAs"] = 1] = "PasteAs";
})(DocumentPasteTriggerKind2 || (DocumentPasteTriggerKind2 = {}));
var $yU = class _$yU {
  static {
    this.c = ".";
  }
  constructor(value) {
    this.value = value;
  }
  append(...parts) {
    return new _$yU((this.value ? [this.value, ...parts] : parts).join(_$yU.c));
  }
  intersects(other) {
    return this.contains(other) || other.contains(this);
  }
  contains(other) {
    return this.value === other.value || other.value.startsWith(this.value + _$yU.c);
  }
};
$yU.Empty = new $yU("");
$yU.Text = new $yU("text");
var $AU = class $AU2 {
  constructor(id2, color2) {
    this.id = id2;
    this.color = color2;
  }
  static isThemeIcon(thing) {
    if (typeof thing.id !== "string") {
      console.log("INVALID ThemeIcon, invalid id", thing.id);
      return false;
    }
    return true;
  }
};
$AU = __decorate([
  es5ClassCompat
], $AU);
$AU.File = new $AU("file");
$AU.Folder = new $AU("folder");
var $BU = class $BU2 {
  constructor(id2) {
    this.id = id2;
  }
};
$BU = __decorate([
  es5ClassCompat
], $BU);
var ConfigurationTarget2;
(function(ConfigurationTarget3) {
  ConfigurationTarget3[ConfigurationTarget3["Global"] = 1] = "Global";
  ConfigurationTarget3[ConfigurationTarget3["Workspace"] = 2] = "Workspace";
  ConfigurationTarget3[ConfigurationTarget3["WorkspaceFolder"] = 3] = "WorkspaceFolder";
})(ConfigurationTarget2 || (ConfigurationTarget2 = {}));
var $CU = class $CU2 {
  get base() {
    return this.c;
  }
  set base(base) {
    this.c = base;
    this.e = URI.file(base);
  }
  get baseUri() {
    return this.e;
  }
  set baseUri(baseUri) {
    this.e = baseUri;
    this.c = baseUri.fsPath;
  }
  constructor(base, pattern) {
    if (typeof base !== "string") {
      if (!base || !URI.isUri(base) && !URI.isUri(base.uri)) {
        throw $nb("base");
      }
    }
    if (typeof pattern !== "string") {
      throw $nb("pattern");
    }
    if (typeof base === "string") {
      this.baseUri = URI.file(base);
    } else if (URI.isUri(base)) {
      this.baseUri = base;
    } else {
      this.baseUri = base.uri;
    }
    this.pattern = pattern;
  }
  toJSON() {
    return {
      pattern: this.pattern,
      base: this.base,
      baseUri: this.baseUri.toJSON()
    };
  }
};
$CU = __decorate([
  es5ClassCompat
], $CU);
var breakpointIds = /* @__PURE__ */ new WeakMap();
var $EU = class $EU2 {
  constructor(enabled, condition, hitCondition, logMessage, mode) {
    this.enabled = typeof enabled === "boolean" ? enabled : true;
    if (typeof condition === "string") {
      this.condition = condition;
    }
    if (typeof hitCondition === "string") {
      this.hitCondition = hitCondition;
    }
    if (typeof logMessage === "string") {
      this.logMessage = logMessage;
    }
    if (typeof mode === "string") {
      this.mode = mode;
    }
  }
  get id() {
    if (!this.c) {
      this.c = breakpointIds.get(this) ?? $ps();
    }
    return this.c;
  }
};
$EU = __decorate([
  es5ClassCompat
], $EU);
var $FU = class $FU2 extends $EU {
  constructor(location3, enabled, condition, hitCondition, logMessage, mode) {
    super(enabled, condition, hitCondition, logMessage, mode);
    if (location3 === null) {
      throw $nb("location");
    }
    this.location = location3;
  }
};
$FU = __decorate([
  es5ClassCompat
], $FU);
var $GU = class $GU2 extends $EU {
  constructor(functionName, enabled, condition, hitCondition, logMessage, mode) {
    super(enabled, condition, hitCondition, logMessage, mode);
    this.functionName = functionName;
  }
};
$GU = __decorate([
  es5ClassCompat
], $GU);
var $HU = class $HU2 extends $EU {
  constructor(label3, dataId, canPersist, enabled, condition, hitCondition, logMessage, mode) {
    super(enabled, condition, hitCondition, logMessage, mode);
    if (!dataId) {
      throw $nb("dataId");
    }
    this.label = label3;
    this.dataId = dataId;
    this.canPersist = canPersist;
  }
};
$HU = __decorate([
  es5ClassCompat
], $HU);
var $IU = class $IU2 {
  constructor(command4, args2, options3) {
    this.command = command4;
    this.args = args2 || [];
    this.options = options3;
  }
};
$IU = __decorate([
  es5ClassCompat
], $IU);
var $JU = class $JU2 {
  constructor(port, host) {
    this.port = port;
    this.host = host;
  }
};
$JU = __decorate([
  es5ClassCompat
], $JU);
var $KU = class $KU2 {
  constructor(path) {
    this.path = path;
  }
};
$KU = __decorate([
  es5ClassCompat
], $KU);
var $LU = class $LU2 {
  constructor(impl) {
    this.implementation = impl;
  }
};
$LU = __decorate([
  es5ClassCompat
], $LU);
var $OU = class $OU2 {
  constructor(range, expression) {
    this.range = range;
    this.expression = expression;
  }
};
$OU = __decorate([
  es5ClassCompat
], $OU);
var InlineCompletionTriggerKind2;
(function(InlineCompletionTriggerKind4) {
  InlineCompletionTriggerKind4[InlineCompletionTriggerKind4["Invoke"] = 0] = "Invoke";
  InlineCompletionTriggerKind4[InlineCompletionTriggerKind4["Automatic"] = 1] = "Automatic";
})(InlineCompletionTriggerKind2 || (InlineCompletionTriggerKind2 = {}));
var $PU = class $PU2 {
  constructor(range, text2) {
    this.range = range;
    this.text = text2;
  }
};
$PU = __decorate([
  es5ClassCompat
], $PU);
var $QU = class $QU2 {
  constructor(range, variableName, caseSensitiveLookup = true) {
    this.range = range;
    this.variableName = variableName;
    this.caseSensitiveLookup = caseSensitiveLookup;
  }
};
$QU = __decorate([
  es5ClassCompat
], $QU);
var $RU = class $RU2 {
  constructor(range, expression) {
    this.range = range;
    this.expression = expression;
  }
};
$RU = __decorate([
  es5ClassCompat
], $RU);
var $SU = class $SU2 {
  constructor(frameId, range) {
    this.frameId = frameId;
    this.stoppedLocation = range;
  }
};
$SU = __decorate([
  es5ClassCompat
], $SU);
var NewSymbolNameTag2;
(function(NewSymbolNameTag4) {
  NewSymbolNameTag4[NewSymbolNameTag4["AIGenerated"] = 1] = "AIGenerated";
})(NewSymbolNameTag2 || (NewSymbolNameTag2 = {}));
var NewSymbolNameTriggerKind2;
(function(NewSymbolNameTriggerKind4) {
  NewSymbolNameTriggerKind4[NewSymbolNameTriggerKind4["Invoke"] = 0] = "Invoke";
  NewSymbolNameTriggerKind4[NewSymbolNameTriggerKind4["Automatic"] = 1] = "Automatic";
})(NewSymbolNameTriggerKind2 || (NewSymbolNameTriggerKind2 = {}));
var FileChangeType2;
(function(FileChangeType3) {
  FileChangeType3[FileChangeType3["Changed"] = 1] = "Changed";
  FileChangeType3[FileChangeType3["Created"] = 2] = "Created";
  FileChangeType3[FileChangeType3["Deleted"] = 3] = "Deleted";
})(FileChangeType2 || (FileChangeType2 = {}));
var $UU = $UU_1 = class $UU2 extends Error {
  static FileExists(messageOrUri) {
    return new $UU_1(messageOrUri, FileSystemProviderErrorCode.FileExists, $UU_1.FileExists);
  }
  static FileNotFound(messageOrUri) {
    return new $UU_1(messageOrUri, FileSystemProviderErrorCode.FileNotFound, $UU_1.FileNotFound);
  }
  static FileNotADirectory(messageOrUri) {
    return new $UU_1(messageOrUri, FileSystemProviderErrorCode.FileNotADirectory, $UU_1.FileNotADirectory);
  }
  static FileIsADirectory(messageOrUri) {
    return new $UU_1(messageOrUri, FileSystemProviderErrorCode.FileIsADirectory, $UU_1.FileIsADirectory);
  }
  static NoPermissions(messageOrUri) {
    return new $UU_1(messageOrUri, FileSystemProviderErrorCode.NoPermissions, $UU_1.NoPermissions);
  }
  static Unavailable(messageOrUri) {
    return new $UU_1(messageOrUri, FileSystemProviderErrorCode.Unavailable, $UU_1.Unavailable);
  }
  constructor(uriOrMessage, code = FileSystemProviderErrorCode.Unknown, terminator) {
    super(URI.isUri(uriOrMessage) ? uriOrMessage.toString(true) : uriOrMessage);
    this.code = terminator?.name ?? "Unknown";
    $zm(this, code);
    Object.setPrototypeOf(this, $UU_1.prototype);
    if (typeof Error.captureStackTrace === "function" && typeof terminator === "function") {
      Error.captureStackTrace(this, terminator);
    }
  }
};
$UU = $UU_1 = __decorate([
  es5ClassCompat
], $UU);
var $VU = class $VU2 {
  constructor(start, end, kind) {
    this.start = start;
    this.end = end;
    this.kind = kind;
  }
};
$VU = __decorate([
  es5ClassCompat
], $VU);
var FoldingRangeKind;
(function(FoldingRangeKind3) {
  FoldingRangeKind3[FoldingRangeKind3["Comment"] = 1] = "Comment";
  FoldingRangeKind3[FoldingRangeKind3["Imports"] = 2] = "Imports";
  FoldingRangeKind3[FoldingRangeKind3["Region"] = 3] = "Region";
})(FoldingRangeKind || (FoldingRangeKind = {}));
var CommentThreadCollapsibleState2;
(function(CommentThreadCollapsibleState3) {
  CommentThreadCollapsibleState3[CommentThreadCollapsibleState3["Collapsed"] = 0] = "Collapsed";
  CommentThreadCollapsibleState3[CommentThreadCollapsibleState3["Expanded"] = 1] = "Expanded";
})(CommentThreadCollapsibleState2 || (CommentThreadCollapsibleState2 = {}));
var CommentMode2;
(function(CommentMode3) {
  CommentMode3[CommentMode3["Editing"] = 0] = "Editing";
  CommentMode3[CommentMode3["Preview"] = 1] = "Preview";
})(CommentMode2 || (CommentMode2 = {}));
var CommentState2;
(function(CommentState3) {
  CommentState3[CommentState3["Published"] = 0] = "Published";
  CommentState3[CommentState3["Draft"] = 1] = "Draft";
})(CommentState2 || (CommentState2 = {}));
var CommentThreadState2;
(function(CommentThreadState3) {
  CommentThreadState3[CommentThreadState3["Unresolved"] = 0] = "Unresolved";
  CommentThreadState3[CommentThreadState3["Resolved"] = 1] = "Resolved";
})(CommentThreadState2 || (CommentThreadState2 = {}));
var CommentThreadApplicability2;
(function(CommentThreadApplicability3) {
  CommentThreadApplicability3[CommentThreadApplicability3["Current"] = 0] = "Current";
  CommentThreadApplicability3[CommentThreadApplicability3["Outdated"] = 1] = "Outdated";
})(CommentThreadApplicability2 || (CommentThreadApplicability2 = {}));
var CommentThreadFocus;
(function(CommentThreadFocus2) {
  CommentThreadFocus2[CommentThreadFocus2["Reply"] = 1] = "Reply";
  CommentThreadFocus2[CommentThreadFocus2["Comment"] = 2] = "Comment";
})(CommentThreadFocus || (CommentThreadFocus = {}));
var DebugConsoleMode;
(function(DebugConsoleMode2) {
  DebugConsoleMode2[DebugConsoleMode2["Separate"] = 0] = "Separate";
  DebugConsoleMode2[DebugConsoleMode2["MergeWithParent"] = 1] = "MergeWithParent";
})(DebugConsoleMode || (DebugConsoleMode = {}));
var QuickInputButtonLocation2;
(function(QuickInputButtonLocation3) {
  QuickInputButtonLocation3[QuickInputButtonLocation3["Title"] = 1] = "Title";
  QuickInputButtonLocation3[QuickInputButtonLocation3["Inline"] = 2] = "Inline";
})(QuickInputButtonLocation2 || (QuickInputButtonLocation2 = {}));
var $3U = class $3U2 {
  static {
    this.Back = { iconPath: new $AU("arrow-left") };
  }
  constructor() {
  }
};
$3U = __decorate([
  es5ClassCompat
], $3U);
var QuickPickItemKind;
(function(QuickPickItemKind2) {
  QuickPickItemKind2[QuickPickItemKind2["Separator"] = -1] = "Separator";
  QuickPickItemKind2[QuickPickItemKind2["Default"] = 0] = "Default";
})(QuickPickItemKind || (QuickPickItemKind = {}));
var InputBoxValidationSeverity;
(function(InputBoxValidationSeverity2) {
  InputBoxValidationSeverity2[InputBoxValidationSeverity2["Info"] = 1] = "Info";
  InputBoxValidationSeverity2[InputBoxValidationSeverity2["Warning"] = 2] = "Warning";
  InputBoxValidationSeverity2[InputBoxValidationSeverity2["Error"] = 3] = "Error";
})(InputBoxValidationSeverity || (InputBoxValidationSeverity = {}));
var ExtensionKind;
(function(ExtensionKind2) {
  ExtensionKind2[ExtensionKind2["UI"] = 1] = "UI";
  ExtensionKind2[ExtensionKind2["Workspace"] = 2] = "Workspace";
})(ExtensionKind || (ExtensionKind = {}));
var $5U = class $5U2 {
  constructor(kind) {
    this.kind = kind;
  }
};
$5U = __decorate([
  es5ClassCompat
], $5U);
var ColorThemeKind;
(function(ColorThemeKind2) {
  ColorThemeKind2[ColorThemeKind2["Light"] = 1] = "Light";
  ColorThemeKind2[ColorThemeKind2["Dark"] = 2] = "Dark";
  ColorThemeKind2[ColorThemeKind2["HighContrast"] = 3] = "HighContrast";
  ColorThemeKind2[ColorThemeKind2["HighContrastLight"] = 4] = "HighContrastLight";
})(ColorThemeKind || (ColorThemeKind = {}));
var $6U = class _$6U {
  static isNotebookRange(thing) {
    if (thing instanceof _$6U) {
      return true;
    }
    if (!thing) {
      return false;
    }
    return typeof thing.start === "number" && typeof thing.end === "number";
  }
  get start() {
    return this.c;
  }
  get end() {
    return this.e;
  }
  get isEmpty() {
    return this.c === this.e;
  }
  constructor(start, end) {
    if (start < 0) {
      throw $nb("start must be positive");
    }
    if (end < 0) {
      throw $nb("end must be positive");
    }
    if (start <= end) {
      this.c = start;
      this.e = end;
    } else {
      this.c = end;
      this.e = start;
    }
  }
  with(change) {
    let start = this.c;
    let end = this.e;
    if (change.start !== void 0) {
      start = change.start;
    }
    if (change.end !== void 0) {
      end = change.end;
    }
    if (start === this.c && end === this.e) {
      return this;
    }
    return new _$6U(start, end);
  }
};
var $7U = class _$7U {
  static validate(data) {
    if (typeof data.kind !== "number") {
      throw new Error("NotebookCellData MUST have 'kind' property");
    }
    if (typeof data.value !== "string") {
      throw new Error("NotebookCellData MUST have 'value' property");
    }
    if (typeof data.languageId !== "string") {
      throw new Error("NotebookCellData MUST have 'languageId' property");
    }
  }
  static isNotebookCellDataArray(value) {
    return Array.isArray(value) && value.every((elem) => _$7U.isNotebookCellData(elem));
  }
  static isNotebookCellData(value) {
    return true;
  }
  constructor(kind, value, languageId, mime, outputs, metadata, executionSummary) {
    this.kind = kind;
    this.value = value;
    this.languageId = languageId;
    this.mime = mime;
    this.outputs = outputs ?? [];
    this.metadata = metadata;
    this.executionSummary = executionSummary;
    _$7U.validate(this);
  }
};
var $8U = class {
  constructor(cells) {
    this.cells = cells;
  }
};
var $9U = class _$9U {
  static isNotebookCellOutputItem(obj) {
    if (obj instanceof _$9U) {
      return true;
    }
    if (!obj) {
      return false;
    }
    return typeof obj.mime === "string" && obj.data instanceof Uint8Array;
  }
  static error(err) {
    const obj = {
      name: err.name,
      message: err.message,
      stack: err.stack
    };
    return _$9U.json(obj, "application/vnd.code.notebook.error");
  }
  static stdout(value) {
    return _$9U.text(value, "application/vnd.code.notebook.stdout");
  }
  static stderr(value) {
    return _$9U.text(value, "application/vnd.code.notebook.stderr");
  }
  static bytes(value, mime = "application/octet-stream") {
    return new _$9U(value, mime);
  }
  static #encoder = new TextEncoder();
  static text(value, mime = $YC.text) {
    const bytes = _$9U.#encoder.encode(String(value));
    return new _$9U(bytes, mime);
  }
  static json(value, mime = "text/x-json") {
    const rawStr = JSON.stringify(value, void 0, "	");
    return _$9U.text(rawStr, mime);
  }
  constructor(data, mime) {
    this.data = data;
    this.mime = mime;
    const mimeNormalized = $3C(mime, true);
    if (!mimeNormalized) {
      throw new Error(`INVALID mime type: ${mime}. Must be in the format "type/subtype[;optionalparameter]"`);
    }
    this.mime = mimeNormalized;
  }
};
var $0U = class _$0U {
  static isNotebookCellOutput(candidate) {
    if (candidate instanceof _$0U) {
      return true;
    }
    if (!candidate || typeof candidate !== "object") {
      return false;
    }
    return typeof candidate.id === "string" && Array.isArray(candidate.items);
  }
  static ensureUniqueMimeTypes(items, warn = false) {
    const seen = /* @__PURE__ */ new Set();
    const removeIdx = /* @__PURE__ */ new Set();
    for (let i2 = 0; i2 < items.length; i2++) {
      const item = items[i2];
      const normalMime = $3C(item.mime);
      if (!seen.has(normalMime) || $tM(normalMime)) {
        seen.add(normalMime);
        continue;
      }
      removeIdx.add(i2);
      if (warn) {
        console.warn(`DUPLICATED mime type '${item.mime}' will be dropped`);
      }
    }
    if (removeIdx.size === 0) {
      return items;
    }
    return items.filter((_item, index) => !removeIdx.has(index));
  }
  constructor(items, idOrMetadata, metadata) {
    this.items = _$0U.ensureUniqueMimeTypes(items, true);
    if (typeof idOrMetadata === "string") {
      this.id = idOrMetadata;
      this.metadata = metadata;
    } else {
      this.id = $ps();
      this.metadata = idOrMetadata ?? metadata;
    }
  }
};
var NotebookCellKind;
(function(NotebookCellKind3) {
  NotebookCellKind3[NotebookCellKind3["Markup"] = 1] = "Markup";
  NotebookCellKind3[NotebookCellKind3["Code"] = 2] = "Code";
})(NotebookCellKind || (NotebookCellKind = {}));
var NotebookCellExecutionState2;
(function(NotebookCellExecutionState4) {
  NotebookCellExecutionState4[NotebookCellExecutionState4["Idle"] = 1] = "Idle";
  NotebookCellExecutionState4[NotebookCellExecutionState4["Pending"] = 2] = "Pending";
  NotebookCellExecutionState4[NotebookCellExecutionState4["Executing"] = 3] = "Executing";
})(NotebookCellExecutionState2 || (NotebookCellExecutionState2 = {}));
var NotebookCellStatusBarAlignment;
(function(NotebookCellStatusBarAlignment2) {
  NotebookCellStatusBarAlignment2[NotebookCellStatusBarAlignment2["Left"] = 1] = "Left";
  NotebookCellStatusBarAlignment2[NotebookCellStatusBarAlignment2["Right"] = 2] = "Right";
})(NotebookCellStatusBarAlignment || (NotebookCellStatusBarAlignment = {}));
var NotebookEditorRevealType;
(function(NotebookEditorRevealType3) {
  NotebookEditorRevealType3[NotebookEditorRevealType3["Default"] = 0] = "Default";
  NotebookEditorRevealType3[NotebookEditorRevealType3["InCenter"] = 1] = "InCenter";
  NotebookEditorRevealType3[NotebookEditorRevealType3["InCenterIfOutsideViewport"] = 2] = "InCenterIfOutsideViewport";
  NotebookEditorRevealType3[NotebookEditorRevealType3["AtTop"] = 3] = "AtTop";
})(NotebookEditorRevealType || (NotebookEditorRevealType = {}));
var NotebookControllerAffinity;
(function(NotebookControllerAffinity3) {
  NotebookControllerAffinity3[NotebookControllerAffinity3["Default"] = 1] = "Default";
  NotebookControllerAffinity3[NotebookControllerAffinity3["Preferred"] = 2] = "Preferred";
})(NotebookControllerAffinity || (NotebookControllerAffinity = {}));
var NotebookControllerAffinity2;
(function(NotebookControllerAffinity22) {
  NotebookControllerAffinity22[NotebookControllerAffinity22["Default"] = 1] = "Default";
  NotebookControllerAffinity22[NotebookControllerAffinity22["Preferred"] = 2] = "Preferred";
  NotebookControllerAffinity22[NotebookControllerAffinity22["Hidden"] = -1] = "Hidden";
})(NotebookControllerAffinity2 || (NotebookControllerAffinity2 = {}));
var $aV = class {
  constructor(uri, provides = []) {
    this.uri = uri;
    this.provides = $5b(provides);
  }
};
var NotebookVariablesRequestKind;
(function(NotebookVariablesRequestKind2) {
  NotebookVariablesRequestKind2[NotebookVariablesRequestKind2["Named"] = 1] = "Named";
  NotebookVariablesRequestKind2[NotebookVariablesRequestKind2["Indexed"] = 2] = "Indexed";
})(NotebookVariablesRequestKind || (NotebookVariablesRequestKind = {}));
var $cV = class $cV2 {
  constructor(label3, timestamp) {
    this.label = label3;
    this.timestamp = timestamp;
  }
};
$cV = __decorate([
  es5ClassCompat
], $cV);
var ExtensionMode;
(function(ExtensionMode2) {
  ExtensionMode2[ExtensionMode2["Production"] = 1] = "Production";
  ExtensionMode2[ExtensionMode2["Development"] = 2] = "Development";
  ExtensionMode2[ExtensionMode2["Test"] = 3] = "Test";
})(ExtensionMode || (ExtensionMode = {}));
var ExtensionRuntime;
(function(ExtensionRuntime2) {
  ExtensionRuntime2[ExtensionRuntime2["Node"] = 1] = "Node";
  ExtensionRuntime2[ExtensionRuntime2["Webworker"] = 2] = "Webworker";
})(ExtensionRuntime || (ExtensionRuntime = {}));
var StandardTokenType2;
(function(StandardTokenType3) {
  StandardTokenType3[StandardTokenType3["Other"] = 0] = "Other";
  StandardTokenType3[StandardTokenType3["Comment"] = 1] = "Comment";
  StandardTokenType3[StandardTokenType3["String"] = 2] = "String";
  StandardTokenType3[StandardTokenType3["RegEx"] = 3] = "RegEx";
})(StandardTokenType2 || (StandardTokenType2 = {}));
var TestResultState;
(function(TestResultState3) {
  TestResultState3[TestResultState3["Queued"] = 1] = "Queued";
  TestResultState3[TestResultState3["Running"] = 2] = "Running";
  TestResultState3[TestResultState3["Passed"] = 3] = "Passed";
  TestResultState3[TestResultState3["Failed"] = 4] = "Failed";
  TestResultState3[TestResultState3["Skipped"] = 5] = "Skipped";
  TestResultState3[TestResultState3["Errored"] = 6] = "Errored";
})(TestResultState || (TestResultState = {}));
var TestRunProfileKind;
(function(TestRunProfileKind3) {
  TestRunProfileKind3[TestRunProfileKind3["Run"] = 1] = "Run";
  TestRunProfileKind3[TestRunProfileKind3["Debug"] = 2] = "Debug";
  TestRunProfileKind3[TestRunProfileKind3["Coverage"] = 3] = "Coverage";
})(TestRunProfileKind || (TestRunProfileKind = {}));
var $gV = class $gV2 {
  constructor(include = void 0, exclude = void 0, profile = void 0, continuous = false, preserveFocus = true) {
    this.include = include;
    this.exclude = exclude;
    this.profile = profile;
    this.continuous = continuous;
    this.preserveFocus = preserveFocus;
  }
};
$gV = __decorate([
  es5ClassCompat
], $gV);
var $hV = $hV_1 = class $hV2 {
  static diff(message, expected, actual) {
    const msg = new $hV_1(message);
    msg.expectedOutput = expected;
    msg.actualOutput = actual;
    return msg;
  }
  constructor(message) {
    this.message = message;
  }
};
$hV = $hV_1 = __decorate([
  es5ClassCompat
], $hV);
var $iV = class $iV2 {
  constructor(id2) {
    this.id = id2;
  }
};
$iV = __decorate([
  es5ClassCompat
], $iV);
var $kV = class {
  constructor(covered, total) {
    this.covered = covered;
    this.total = total;
    $lV(this);
  }
};
function $lV(cc) {
  if (!cc) {
    return;
  }
  if (cc.covered > cc.total) {
    throw new Error(`The total number of covered items (${cc.covered}) cannot be greater than the total (${cc.total})`);
  }
  if (cc.total < 0) {
    throw new Error(`The number of covered items (${cc.total}) cannot be negative`);
  }
}
var $mV = class _$mV {
  static fromDetails(uri, details) {
    const statements = new $kV(0, 0);
    const branches = new $kV(0, 0);
    const decl = new $kV(0, 0);
    for (const detail2 of details) {
      if ("branches" in detail2) {
        statements.total += 1;
        statements.covered += detail2.executed ? 1 : 0;
        for (const branch of detail2.branches) {
          branches.total += 1;
          branches.covered += branch.executed ? 1 : 0;
        }
      } else {
        decl.total += 1;
        decl.covered += detail2.executed ? 1 : 0;
      }
    }
    const coverage = new _$mV(uri, statements, branches.total > 0 ? branches : void 0, decl.total > 0 ? decl : void 0);
    coverage.detailedCoverage = details;
    return coverage;
  }
  constructor(uri, statementCoverage, branchCoverage, declarationCoverage, includesTests = []) {
    this.uri = uri;
    this.statementCoverage = statementCoverage;
    this.branchCoverage = branchCoverage;
    this.declarationCoverage = declarationCoverage;
    this.includesTests = includesTests;
  }
};
var $nV = class {
  // back compat until finalization:
  get executionCount() {
    return +this.executed;
  }
  set executionCount(n) {
    this.executed = n;
  }
  constructor(executed, location3, branches = []) {
    this.executed = executed;
    this.location = location3;
    this.branches = branches;
  }
};
var $oV = class {
  // back compat until finalization:
  get executionCount() {
    return +this.executed;
  }
  set executionCount(n) {
    this.executed = n;
  }
  constructor(executed, location3, label3) {
    this.executed = executed;
    this.location = location3;
    this.label = label3;
  }
};
var $pV = class {
  // back compat until finalization:
  get executionCount() {
    return +this.executed;
  }
  set executionCount(n) {
    this.executed = n;
  }
  constructor(name, executed, location3) {
    this.name = name;
    this.executed = executed;
    this.location = location3;
  }
};
var ExternalUriOpenerPriority2;
(function(ExternalUriOpenerPriority3) {
  ExternalUriOpenerPriority3[ExternalUriOpenerPriority3["None"] = 0] = "None";
  ExternalUriOpenerPriority3[ExternalUriOpenerPriority3["Option"] = 1] = "Option";
  ExternalUriOpenerPriority3[ExternalUriOpenerPriority3["Default"] = 2] = "Default";
  ExternalUriOpenerPriority3[ExternalUriOpenerPriority3["Preferred"] = 3] = "Preferred";
})(ExternalUriOpenerPriority2 || (ExternalUriOpenerPriority2 = {}));
var WorkspaceTrustState;
(function(WorkspaceTrustState2) {
  WorkspaceTrustState2[WorkspaceTrustState2["Untrusted"] = 0] = "Untrusted";
  WorkspaceTrustState2[WorkspaceTrustState2["Trusted"] = 1] = "Trusted";
  WorkspaceTrustState2[WorkspaceTrustState2["Unspecified"] = 2] = "Unspecified";
})(WorkspaceTrustState || (WorkspaceTrustState = {}));
var PortAutoForwardAction;
(function(PortAutoForwardAction2) {
  PortAutoForwardAction2[PortAutoForwardAction2["Notify"] = 1] = "Notify";
  PortAutoForwardAction2[PortAutoForwardAction2["OpenBrowser"] = 2] = "OpenBrowser";
  PortAutoForwardAction2[PortAutoForwardAction2["OpenPreview"] = 3] = "OpenPreview";
  PortAutoForwardAction2[PortAutoForwardAction2["Silent"] = 4] = "Silent";
  PortAutoForwardAction2[PortAutoForwardAction2["Ignore"] = 5] = "Ignore";
  PortAutoForwardAction2[PortAutoForwardAction2["OpenBrowserOnce"] = 6] = "OpenBrowserOnce";
})(PortAutoForwardAction || (PortAutoForwardAction = {}));
var $qV = class {
  constructor(kind, name, detail2, uri, range, selectionRange) {
    this.kind = kind;
    this.name = name;
    this.detail = detail2;
    this.uri = uri;
    this.range = range;
    this.selectionRange = selectionRange;
  }
};
var InteractiveSessionVoteDirection;
(function(InteractiveSessionVoteDirection2) {
  InteractiveSessionVoteDirection2[InteractiveSessionVoteDirection2["Down"] = 0] = "Down";
  InteractiveSessionVoteDirection2[InteractiveSessionVoteDirection2["Up"] = 1] = "Up";
})(InteractiveSessionVoteDirection || (InteractiveSessionVoteDirection = {}));
var ChatCopyKind;
(function(ChatCopyKind3) {
  ChatCopyKind3[ChatCopyKind3["Action"] = 1] = "Action";
  ChatCopyKind3[ChatCopyKind3["Toolbar"] = 2] = "Toolbar";
})(ChatCopyKind || (ChatCopyKind = {}));
var ChatVariableLevel;
(function(ChatVariableLevel2) {
  ChatVariableLevel2[ChatVariableLevel2["Short"] = 1] = "Short";
  ChatVariableLevel2[ChatVariableLevel2["Medium"] = 2] = "Medium";
  ChatVariableLevel2[ChatVariableLevel2["Full"] = 3] = "Full";
})(ChatVariableLevel || (ChatVariableLevel = {}));
var ChatEditingSessionActionOutcome;
(function(ChatEditingSessionActionOutcome2) {
  ChatEditingSessionActionOutcome2[ChatEditingSessionActionOutcome2["Accepted"] = 1] = "Accepted";
  ChatEditingSessionActionOutcome2[ChatEditingSessionActionOutcome2["Rejected"] = 2] = "Rejected";
  ChatEditingSessionActionOutcome2[ChatEditingSessionActionOutcome2["Saved"] = 3] = "Saved";
})(ChatEditingSessionActionOutcome || (ChatEditingSessionActionOutcome = {}));
var InteractiveEditorResponseFeedbackKind;
(function(InteractiveEditorResponseFeedbackKind2) {
  InteractiveEditorResponseFeedbackKind2[InteractiveEditorResponseFeedbackKind2["Unhelpful"] = 0] = "Unhelpful";
  InteractiveEditorResponseFeedbackKind2[InteractiveEditorResponseFeedbackKind2["Helpful"] = 1] = "Helpful";
  InteractiveEditorResponseFeedbackKind2[InteractiveEditorResponseFeedbackKind2["Undone"] = 2] = "Undone";
  InteractiveEditorResponseFeedbackKind2[InteractiveEditorResponseFeedbackKind2["Accepted"] = 3] = "Accepted";
  InteractiveEditorResponseFeedbackKind2[InteractiveEditorResponseFeedbackKind2["Bug"] = 4] = "Bug";
})(InteractiveEditorResponseFeedbackKind || (InteractiveEditorResponseFeedbackKind = {}));
var ChatResultFeedbackKind;
(function(ChatResultFeedbackKind2) {
  ChatResultFeedbackKind2[ChatResultFeedbackKind2["Unhelpful"] = 0] = "Unhelpful";
  ChatResultFeedbackKind2[ChatResultFeedbackKind2["Helpful"] = 1] = "Helpful";
})(ChatResultFeedbackKind || (ChatResultFeedbackKind = {}));
var $DV = class {
  constructor(value) {
    if (typeof value !== "string" && value.isTrusted === true) {
      throw new Error("The boolean form of MarkdownString.isTrusted is NOT supported for chat participants.");
    }
    this.value = typeof value === "string" ? new $4T(value) : value;
  }
};
var $EV = class {
  constructor(value, vulnerabilities) {
    if (typeof value !== "string" && value.isTrusted === true) {
      throw new Error("The boolean form of MarkdownString.isTrusted is NOT supported for chat participants.");
    }
    this.value = typeof value === "string" ? new $4T(value) : value;
    this.vulnerabilities = vulnerabilities;
  }
};
var $FV = class {
  constructor(participant, command4) {
    this.participant = participant;
    this.command = command4;
  }
};
var $GV = class {
  constructor(title, message, data, buttons) {
    this.title = title;
    this.message = message;
    this.data = data;
    this.buttons = buttons;
  }
};
var $HV = class {
  constructor(value, baseUri) {
    this.value = value;
    this.baseUri = baseUri;
  }
};
var $IV = class {
  constructor(value, title) {
    this.value = value;
    this.value2 = value;
    this.title = title;
  }
};
var $JV = class {
  constructor(value) {
    this.value = value;
  }
};
var $LV = class {
  constructor(value) {
    if (typeof value !== "string" && value.isTrusted === true) {
      throw new Error("The boolean form of MarkdownString.isTrusted is NOT supported for chat participants.");
    }
    this.value = typeof value === "string" ? new $4T(value) : value;
  }
};
var $MV = class {
  constructor(value) {
    this.value = value;
  }
};
var $NV = class {
  constructor(value, iconPath, options3) {
    this.value = value;
    this.iconPath = iconPath;
    this.options = options3;
  }
};
var $OV = class {
  constructor(value) {
    this.value = value;
  }
};
var $PV = class {
  constructor(value, license, snippet) {
    this.value = value;
    this.license = license;
    this.snippet = snippet;
  }
};
var $QV = class {
  constructor(uri, range) {
    this.uri = uri;
    this.range = range;
  }
};
var $RV = class {
  constructor(uri, editsOrDone) {
    this.uri = uri;
    if (editsOrDone === true) {
      this.isDone = true;
      this.edits = [];
    } else {
      this.edits = Array.isArray(editsOrDone) ? editsOrDone : [editsOrDone];
    }
  }
};
var ChatLocation;
(function(ChatLocation3) {
  ChatLocation3[ChatLocation3["Panel"] = 1] = "Panel";
  ChatLocation3[ChatLocation3["Terminal"] = 2] = "Terminal";
  ChatLocation3[ChatLocation3["Notebook"] = 3] = "Notebook";
  ChatLocation3[ChatLocation3["Editor"] = 4] = "Editor";
  ChatLocation3[ChatLocation3["EditingSession"] = 5] = "EditingSession";
})(ChatLocation || (ChatLocation = {}));
var ChatResponseReferencePartStatusKind;
(function(ChatResponseReferencePartStatusKind3) {
  ChatResponseReferencePartStatusKind3[ChatResponseReferencePartStatusKind3["Complete"] = 1] = "Complete";
  ChatResponseReferencePartStatusKind3[ChatResponseReferencePartStatusKind3["Partial"] = 2] = "Partial";
  ChatResponseReferencePartStatusKind3[ChatResponseReferencePartStatusKind3["Omitted"] = 3] = "Omitted";
})(ChatResponseReferencePartStatusKind || (ChatResponseReferencePartStatusKind = {}));
var $WV = class {
  constructor(mimeType, data) {
    this.mimeType = mimeType;
    this.data = data;
  }
};
var LanguageModelChatMessageRole;
(function(LanguageModelChatMessageRole3) {
  LanguageModelChatMessageRole3[LanguageModelChatMessageRole3["User"] = 1] = "User";
  LanguageModelChatMessageRole3[LanguageModelChatMessageRole3["Assistant"] = 2] = "Assistant";
  LanguageModelChatMessageRole3[LanguageModelChatMessageRole3["System"] = 3] = "System";
})(LanguageModelChatMessageRole || (LanguageModelChatMessageRole = {}));
var $XV = class {
  constructor(callId, content, isError) {
    this.callId = callId;
    this.content = content;
    this.isError = isError ?? false;
  }
};
var $YV = class _$YV {
  static User(content, name) {
    return new _$YV(LanguageModelChatMessageRole.User, content, name);
  }
  static Assistant(content, name) {
    return new _$YV(LanguageModelChatMessageRole.Assistant, content, name);
  }
  set content(value) {
    if (typeof value === "string") {
      this.c = [new $1V(value)];
    } else {
      this.c = value;
    }
  }
  get content() {
    return this.c;
  }
  // Temp to avoid breaking changes
  set content2(value) {
    if (value) {
      this.content = value.map((part) => {
        if (typeof part === "string") {
          return new $1V(part);
        }
        return part;
      });
    }
  }
  get content2() {
    return this.content.map((part) => {
      if (part instanceof $1V) {
        return part.value;
      }
      return part;
    });
  }
  constructor(role, content, name) {
    this.c = [];
    this.role = role;
    this.content = content;
    this.name = name;
  }
};
var $ZV = class {
  constructor(callId, name, input) {
    this.callId = callId;
    this.name = name;
    this.input = input;
  }
};
var $1V = class {
  constructor(value) {
    this.value = value;
  }
  toJSON() {
    return {
      $mid: 21,
      value: this.value
    };
  }
};
var $2V = class {
  constructor(value) {
    this.value = value;
  }
  toJSON() {
    return {
      $mid: 22,
      value: this.value
    };
  }
};
var $7V = class {
  constructor(content) {
    this.content = content;
  }
  toJSON() {
    return {
      $mid: 20,
      content: this.content
    };
  }
};
var LanguageModelChatToolMode;
(function(LanguageModelChatToolMode2) {
  LanguageModelChatToolMode2[LanguageModelChatToolMode2["Auto"] = 1] = "Auto";
  LanguageModelChatToolMode2[LanguageModelChatToolMode2["Required"] = 2] = "Required";
})(LanguageModelChatToolMode || (LanguageModelChatToolMode = {}));
var RelatedInformationType;
(function(RelatedInformationType3) {
  RelatedInformationType3[RelatedInformationType3["SymbolInformation"] = 1] = "SymbolInformation";
  RelatedInformationType3[RelatedInformationType3["CommandInformation"] = 2] = "CommandInformation";
  RelatedInformationType3[RelatedInformationType3["SearchInformation"] = 3] = "SearchInformation";
  RelatedInformationType3[RelatedInformationType3["SettingInformation"] = 4] = "SettingInformation";
})(RelatedInformationType || (RelatedInformationType = {}));
var SpeechToTextStatus;
(function(SpeechToTextStatus3) {
  SpeechToTextStatus3[SpeechToTextStatus3["Started"] = 1] = "Started";
  SpeechToTextStatus3[SpeechToTextStatus3["Recognizing"] = 2] = "Recognizing";
  SpeechToTextStatus3[SpeechToTextStatus3["Recognized"] = 3] = "Recognized";
  SpeechToTextStatus3[SpeechToTextStatus3["Stopped"] = 4] = "Stopped";
  SpeechToTextStatus3[SpeechToTextStatus3["Error"] = 5] = "Error";
})(SpeechToTextStatus || (SpeechToTextStatus = {}));
var TextToSpeechStatus;
(function(TextToSpeechStatus3) {
  TextToSpeechStatus3[TextToSpeechStatus3["Started"] = 1] = "Started";
  TextToSpeechStatus3[TextToSpeechStatus3["Stopped"] = 2] = "Stopped";
  TextToSpeechStatus3[TextToSpeechStatus3["Error"] = 3] = "Error";
})(TextToSpeechStatus || (TextToSpeechStatus = {}));
var KeywordRecognitionStatus;
(function(KeywordRecognitionStatus3) {
  KeywordRecognitionStatus3[KeywordRecognitionStatus3["Recognized"] = 1] = "Recognized";
  KeywordRecognitionStatus3[KeywordRecognitionStatus3["Stopped"] = 2] = "Stopped";
})(KeywordRecognitionStatus || (KeywordRecognitionStatus = {}));
var InlineEditTriggerKind2;
(function(InlineEditTriggerKind4) {
  InlineEditTriggerKind4[InlineEditTriggerKind4["Invoke"] = 0] = "Invoke";
  InlineEditTriggerKind4[InlineEditTriggerKind4["Automatic"] = 1] = "Automatic";
})(InlineEditTriggerKind2 || (InlineEditTriggerKind2 = {}));

// out-build/vs/workbench/common/theme.js
function $4lb(theme) {
  switch (theme.type) {
    case ColorScheme.LIGHT:
      return $Vn.fromHex("#F3F3F3");
    case ColorScheme.HIGH_CONTRAST_LIGHT:
      return $Vn.fromHex("#FFFFFF");
    case ColorScheme.HIGH_CONTRAST_DARK:
      return $Vn.fromHex("#000000");
    default:
      return $Vn.fromHex("#252526");
  }
}
var $5lb = $5n("tab.activeBackground", $Ko, localize(4140, null));
var $6lb = $5n("tab.unfocusedActiveBackground", $5lb, localize(4141, null));
var $7lb = $5n("tab.inactiveBackground", {
  dark: "#2D2D2D",
  light: "#ECECEC",
  hcDark: null,
  hcLight: null
}, localize(4142, null));
var $8lb = $5n("tab.unfocusedInactiveBackground", $7lb, localize(4143, null));
var $9lb = $5n("tab.activeForeground", {
  dark: $Vn.white,
  light: "#333333",
  hcDark: $Vn.white,
  hcLight: "#292929"
}, localize(4144, null));
var $0lb = $5n("tab.inactiveForeground", {
  dark: $0n($9lb, 0.5),
  light: $0n($9lb, 0.7),
  hcDark: $Vn.white,
  hcLight: "#292929"
}, localize(4145, null));
var $$lb = $5n("tab.unfocusedActiveForeground", {
  dark: $0n($9lb, 0.5),
  light: $0n($9lb, 0.7),
  hcDark: $Vn.white,
  hcLight: "#292929"
}, localize(4146, null));
var $_lb = $5n("tab.unfocusedInactiveForeground", {
  dark: $0n($0lb, 0.5),
  light: $0n($0lb, 0.5),
  hcDark: $Vn.white,
  hcLight: "#292929"
}, localize(4147, null));
var $amb = $5n("tab.hoverBackground", null, localize(4148, null));
var $bmb = $5n("tab.unfocusedHoverBackground", {
  dark: $0n($amb, 0.5),
  light: $0n($amb, 0.7),
  hcDark: null,
  hcLight: null
}, localize(4149, null));
var $cmb = $5n("tab.hoverForeground", null, localize(4150, null));
var $dmb = $5n("tab.unfocusedHoverForeground", {
  dark: $0n($cmb, 0.5),
  light: $0n($cmb, 0.5),
  hcDark: null,
  hcLight: null
}, localize(4151, null));
var $emb = $5n("tab.border", {
  dark: "#252526",
  light: "#F3F3F3",
  hcDark: $ko,
  hcLight: $ko
}, localize(4152, null));
var $fmb = $5n("tab.lastPinnedBorder", {
  dark: $Gr,
  light: $Gr,
  hcDark: $ko,
  hcLight: $ko
}, localize(4153, null));
var $gmb = $5n("tab.activeBorder", null, localize(4154, null));
var $hmb = $5n("tab.unfocusedActiveBorder", {
  dark: $0n($gmb, 0.5),
  light: $0n($gmb, 0.7),
  hcDark: null,
  hcLight: null
}, localize(4155, null));
var $imb = $5n("tab.activeBorderTop", {
  dark: null,
  light: null,
  hcDark: null,
  hcLight: "#B5200D"
}, localize(4156, null));
var $jmb = $5n("tab.unfocusedActiveBorderTop", {
  dark: $0n($imb, 0.5),
  light: $0n($imb, 0.7),
  hcDark: null,
  hcLight: "#B5200D"
}, localize(4157, null));
var $kmb = $5n("tab.selectedBorderTop", $imb, localize(4158, null));
var $lmb = $5n("tab.selectedBackground", $5lb, localize(4159, null));
var $mmb = $5n("tab.selectedForeground", $9lb, localize(4160, null));
var $nmb = $5n("tab.hoverBorder", null, localize(4161, null));
var $omb = $5n("tab.unfocusedHoverBorder", {
  dark: $0n($nmb, 0.5),
  light: $0n($nmb, 0.7),
  hcDark: null,
  hcLight: $ko
}, localize(4162, null));
var $pmb = $5n("tab.dragAndDropBorder", {
  dark: $9lb,
  light: $9lb,
  hcDark: $lo,
  hcLight: $lo
}, localize(4163, null));
var $qmb = $5n("tab.activeModifiedBorder", {
  dark: "#3399CC",
  light: "#33AAEE",
  hcDark: null,
  hcLight: $ko
}, localize(4164, null));
var $rmb = $5n("tab.inactiveModifiedBorder", {
  dark: $0n($qmb, 0.5),
  light: $0n($qmb, 0.5),
  hcDark: $Vn.white,
  hcLight: $ko
}, localize(4165, null));
var $smb = $5n("tab.unfocusedActiveModifiedBorder", {
  dark: $0n($qmb, 0.5),
  light: $0n($qmb, 0.7),
  hcDark: $Vn.white,
  hcLight: $ko
}, localize(4166, null));
var $tmb = $5n("tab.unfocusedInactiveModifiedBorder", {
  dark: $0n($rmb, 0.5),
  light: $0n($rmb, 0.5),
  hcDark: $Vn.white,
  hcLight: $ko
}, localize(4167, null));
var $umb = $5n("editorPane.background", $Ko, localize(4168, null));
var $vmb = $5n("editorGroup.emptyBackground", null, localize(4169, null));
var $wmb = $5n("editorGroup.focusedEmptyBorder", {
  dark: null,
  light: null,
  hcDark: $jo,
  hcLight: $jo
}, localize(4170, null));
var $xmb = $5n("editorGroupHeader.tabsBackground", {
  dark: "#252526",
  light: "#F3F3F3",
  hcDark: null,
  hcLight: null
}, localize(4171, null));
var $ymb = $5n("editorGroupHeader.tabsBorder", null, localize(4172, null));
var $zmb = $5n("editorGroupHeader.noTabsBackground", $Ko, localize(4173, null));
var $Amb = $5n("editorGroupHeader.border", {
  dark: null,
  light: null,
  hcDark: $ko,
  hcLight: $ko
}, localize(4174, null));
var $Bmb = $5n("editorGroup.border", {
  dark: "#444444",
  light: "#E7E7E7",
  hcDark: $ko,
  hcLight: $ko
}, localize(4175, null));
var $Cmb = $5n("editorGroup.dropBackground", {
  dark: $Vn.fromHex("#53595D").transparent(0.5),
  light: $Vn.fromHex("#2677CB").transparent(0.18),
  hcDark: null,
  hcLight: $Vn.fromHex("#0F4A85").transparent(0.5)
}, localize(4176, null));
var $Dmb = $5n("editorGroup.dropIntoPromptForeground", $Ro, localize(4177, null));
var $Emb = $5n("editorGroup.dropIntoPromptBackground", $Qo, localize(4178, null));
var $Fmb = $5n("editorGroup.dropIntoPromptBorder", {
  dark: null,
  light: null,
  hcDark: $ko,
  hcLight: $ko
}, localize(4179, null));
var $Gmb = $5n("sideBySideEditor.horizontalBorder", $Bmb, localize(4180, null));
var $Hmb = $5n("sideBySideEditor.verticalBorder", $Bmb, localize(4181, null));
var $Imb = $5n("panel.background", $Ko, localize(4182, null));
var $Jmb = $5n("panel.border", {
  dark: $Vn.fromHex("#808080").transparent(0.35),
  light: $Vn.fromHex("#808080").transparent(0.35),
  hcDark: $ko,
  hcLight: $ko
}, localize(4183, null));
var $Kmb = $5n("panelTitle.border", {
  dark: null,
  light: null,
  hcDark: $Jmb,
  hcLight: $Jmb
}, localize(4184, null));
var $Lmb = $5n("panelTitle.activeForeground", {
  dark: "#E7E7E7",
  light: "#424242",
  hcDark: $Vn.white,
  hcLight: $Lo
}, localize(4185, null));
var $Mmb = $5n("panelTitle.inactiveForeground", {
  dark: $0n($Lmb, 0.6),
  light: $0n($Lmb, 0.75),
  hcDark: $Vn.white,
  hcLight: $Lo
}, localize(4186, null));
var $Nmb = $5n("panelTitle.activeBorder", {
  dark: $Lmb,
  light: $Lmb,
  hcDark: $ko,
  hcLight: "#B5200D"
}, localize(4187, null));
var $Omb = $5n("panelInput.border", {
  dark: $zq,
  light: $Vn.fromHex("#ddd"),
  hcDark: $zq,
  hcLight: $zq
}, localize(4188, null));
var $Pmb = $5n("panel.dropBorder", $Lmb, localize(4189, null));
var $Qmb = $5n("panelSection.dropBackground", $Cmb, localize(4190, null));
var $Rmb = $5n("panelSectionHeader.background", {
  dark: $Vn.fromHex("#808080").transparent(0.2),
  light: $Vn.fromHex("#808080").transparent(0.2),
  hcDark: null,
  hcLight: null
}, localize(4191, null));
var $Smb = $5n("panelSectionHeader.foreground", null, localize(4192, null));
var $Tmb = $5n("panelSectionHeader.border", $ko, localize(4193, null));
var $Umb = $5n("panelSection.border", $Jmb, localize(4194, null));
var $Vmb = $5n("panelStickyScroll.background", $Imb, localize(4195, null));
var $Wmb = $5n("panelStickyScroll.border", null, localize(4196, null));
var $Xmb = $5n("panelStickyScroll.shadow", $Co, localize(4197, null));
var OUTPUT_VIEW_BACKGROUND = $5n("outputView.background", null, localize(4198, null));
$5n("outputViewStickyScroll.background", OUTPUT_VIEW_BACKGROUND, localize(4199, null));
var $Ymb = $5n("banner.background", {
  dark: $ir,
  light: $8n($ir, 0.3),
  hcDark: $ir,
  hcLight: $ir
}, localize(4200, null));
var $Zmb = $5n("banner.foreground", $jr, localize(4201, null));
var $1mb = $5n("banner.iconForeground", $2o, localize(4202, null));
var $2mb = $5n("statusBar.foreground", {
  dark: "#FFFFFF",
  light: "#FFFFFF",
  hcDark: "#FFFFFF",
  hcLight: $Lo
}, localize(4203, null));
var $3mb = $5n("statusBar.noFolderForeground", $2mb, localize(4204, null));
var $4mb = $5n("statusBar.background", {
  dark: "#007ACC",
  light: "#007ACC",
  hcDark: null,
  hcLight: null
}, localize(4205, null));
var $5mb = $5n("statusBar.noFolderBackground", {
  dark: "#68217A",
  light: "#68217A",
  hcDark: null,
  hcLight: null
}, localize(4206, null));
var $6mb = $5n("statusBar.border", {
  dark: null,
  light: null,
  hcDark: $ko,
  hcLight: $ko
}, localize(4207, null));
var $7mb = $5n("statusBar.focusBorder", {
  dark: $2mb,
  light: $2mb,
  hcDark: null,
  hcLight: $2mb
}, localize(4208, null));
var $8mb = $5n("statusBar.noFolderBorder", $6mb, localize(4209, null));
var $9mb = $5n("statusBarItem.activeBackground", {
  dark: $Vn.white.transparent(0.18),
  light: $Vn.white.transparent(0.18),
  hcDark: $Vn.white.transparent(0.18),
  hcLight: $Vn.black.transparent(0.18)
}, localize(4210, null));
var $0mb = $5n("statusBarItem.focusBorder", {
  dark: $2mb,
  light: $2mb,
  hcDark: null,
  hcLight: $lo
}, localize(4211, null));
var $$mb = $5n("statusBarItem.hoverBackground", {
  dark: $Vn.white.transparent(0.12),
  light: $Vn.white.transparent(0.12),
  hcDark: $Vn.white.transparent(0.12),
  hcLight: $Vn.black.transparent(0.12)
}, localize(4212, null));
var $_mb = $5n("statusBarItem.hoverForeground", $2mb, localize(4213, null));
var $anb = $5n("statusBarItem.compactHoverBackground", {
  dark: $Vn.white.transparent(0.2),
  light: $Vn.white.transparent(0.2),
  hcDark: $Vn.white.transparent(0.2),
  hcLight: $Vn.black.transparent(0.2)
}, localize(4214, null));
var $bnb = $5n("statusBarItem.prominentForeground", $2mb, localize(4215, null));
var $cnb = $5n("statusBarItem.prominentBackground", $Vn.black.transparent(0.5), localize(4216, null));
var $dnb = $5n("statusBarItem.prominentHoverForeground", $_mb, localize(4217, null));
var $enb = $5n("statusBarItem.prominentHoverBackground", {
  dark: $Vn.black.transparent(0.3),
  light: $Vn.black.transparent(0.3),
  hcDark: $Vn.black.transparent(0.3),
  hcLight: null
}, localize(4218, null));
var $fnb = $5n("statusBarItem.errorBackground", {
  dark: $8n($go, 0.4),
  light: $8n($go, 0.4),
  hcDark: null,
  hcLight: "#B5200D"
}, localize(4219, null));
var $gnb = $5n("statusBarItem.errorForeground", $Vn.white, localize(4220, null));
var $hnb = $5n("statusBarItem.errorHoverForeground", $_mb, localize(4221, null));
var $inb = $5n("statusBarItem.errorHoverBackground", $$mb, localize(4222, null));
var $jnb = $5n("statusBarItem.warningBackground", {
  dark: $8n($Yo, 0.4),
  light: $8n($Yo, 0.4),
  hcDark: null,
  hcLight: "#895503"
}, localize(4223, null));
var $knb = $5n("statusBarItem.warningForeground", $Vn.white, localize(4224, null));
var $lnb = $5n("statusBarItem.warningHoverForeground", $_mb, localize(4225, null));
var $mnb = $5n("statusBarItem.warningHoverBackground", $$mb, localize(4226, null));
var $nnb = $5n("activityBar.background", {
  dark: "#333333",
  light: "#2C2C2C",
  hcDark: "#000000",
  hcLight: "#FFFFFF"
}, localize(4227, null));
var $onb = $5n("activityBar.foreground", {
  dark: $Vn.white,
  light: $Vn.white,
  hcDark: $Vn.white,
  hcLight: $Lo
}, localize(4228, null));
var $pnb = $5n("activityBar.inactiveForeground", {
  dark: $0n($onb, 0.4),
  light: $0n($onb, 0.4),
  hcDark: $Vn.white,
  hcLight: $Lo
}, localize(4229, null));
var $qnb = $5n("activityBar.border", {
  dark: null,
  light: null,
  hcDark: $ko,
  hcLight: $ko
}, localize(4230, null));
var $rnb = $5n("activityBar.activeBorder", {
  dark: $onb,
  light: $onb,
  hcDark: $ko,
  hcLight: $ko
}, localize(4231, null));
var $snb = $5n("activityBar.activeFocusBorder", {
  dark: null,
  light: null,
  hcDark: null,
  hcLight: "#B5200D"
}, localize(4232, null));
var $tnb = $5n("activityBar.activeBackground", null, localize(4233, null));
var $unb = $5n("activityBar.dropBorder", {
  dark: $onb,
  light: $onb,
  hcDark: null,
  hcLight: null
}, localize(4234, null));
var $vnb = $5n("activityBarBadge.background", {
  dark: "#007ACC",
  light: "#007ACC",
  hcDark: "#000000",
  hcLight: "#0F4A85"
}, localize(4235, null));
var $wnb = $5n("activityBarBadge.foreground", $Vn.white, localize(4236, null));
var $xnb = $5n("activityBarTop.foreground", {
  dark: "#E7E7E7",
  light: "#424242",
  hcDark: $Vn.white,
  hcLight: $Lo
}, localize(4237, null));
var $ynb = $5n("activityBarTop.activeBorder", {
  dark: $xnb,
  light: $xnb,
  hcDark: $ko,
  hcLight: "#B5200D"
}, localize(4238, null));
var $znb = $5n("activityBarTop.activeBackground", null, localize(4239, null));
var $Anb = $5n("activityBarTop.inactiveForeground", {
  dark: $0n($xnb, 0.6),
  light: $0n($xnb, 0.75),
  hcDark: $Vn.white,
  hcLight: $Lo
}, localize(4240, null));
var $Bnb = $5n("activityBarTop.dropBorder", $xnb, localize(4241, null));
var $Cnb = $5n("activityBarTop.background", null, localize(4242, null));
var $Dnb = $5n("profileBadge.background", {
  dark: "#4D4D4D",
  light: "#C4C4C4",
  hcDark: $Vn.white,
  hcLight: $Vn.black
}, localize(4243, null));
var $Enb = $5n("profileBadge.foreground", {
  dark: $Vn.white,
  light: "#333333",
  hcDark: $Vn.black,
  hcLight: $Vn.white
}, localize(4244, null));
var $Fnb = $5n("statusBarItem.remoteBackground", $vnb, localize(4245, null));
var $Gnb = $5n("statusBarItem.remoteForeground", $wnb, localize(4246, null));
var $Hnb = $5n("statusBarItem.remoteHoverForeground", $_mb, localize(4247, null));
var $Inb = $5n("statusBarItem.remoteHoverBackground", {
  dark: $$mb,
  light: $$mb,
  hcDark: $$mb,
  hcLight: null
}, localize(4248, null));
var $Jnb = $5n("statusBarItem.offlineBackground", "#6c1717", localize(4249, null));
var $Knb = $5n("statusBarItem.offlineForeground", $Gnb, localize(4250, null));
var $Lnb = $5n("statusBarItem.offlineHoverForeground", $_mb, localize(4251, null));
var $Mnb = $5n("statusBarItem.offlineHoverBackground", {
  dark: $$mb,
  light: $$mb,
  hcDark: $$mb,
  hcLight: null
}, localize(4252, null));
var $Nnb = $5n("extensionBadge.remoteBackground", $vnb, localize(4253, null));
var $Onb = $5n("extensionBadge.remoteForeground", $wnb, localize(4254, null));
var $Pnb = $5n("sideBar.background", {
  dark: "#252526",
  light: "#F3F3F3",
  hcDark: "#000000",
  hcLight: "#FFFFFF"
}, localize(4255, null));
var $Qnb = $5n("sideBar.foreground", null, localize(4256, null));
var $Rnb = $5n("sideBar.border", {
  dark: null,
  light: null,
  hcDark: $ko,
  hcLight: $ko
}, localize(4257, null));
var $Snb = $5n("sideBarTitle.background", $Pnb, localize(4258, null));
var $Tnb = $5n("sideBarTitle.foreground", $Qnb, localize(4259, null));
var $Unb = $5n("sideBarTitle.border", {
  dark: null,
  light: null,
  hcDark: $Rnb,
  hcLight: $Rnb
}, localize(4260, null));
var $Vnb = $5n("sideBar.dropBackground", $Cmb, localize(4261, null));
var $Wnb = $5n("sideBarSectionHeader.background", {
  dark: $Vn.fromHex("#808080").transparent(0.2),
  light: $Vn.fromHex("#808080").transparent(0.2),
  hcDark: null,
  hcLight: null
}, localize(4262, null));
var $Xnb = $5n("sideBarSectionHeader.foreground", $Qnb, localize(4263, null));
var $Ynb = $5n("sideBarSectionHeader.border", $ko, localize(4264, null));
var $Znb = $5n("sideBarActivityBarTop.border", $Ynb, localize(4265, null));
var $1nb = $5n("sideBarStickyScroll.background", $Pnb, localize(4266, null));
var $2nb = $5n("sideBarStickyScroll.border", null, localize(4267, null));
var $3nb = $5n("sideBarStickyScroll.shadow", $Co, localize(4268, null));
var $4nb = $5n("titleBar.activeForeground", {
  dark: "#CCCCCC",
  light: "#333333",
  hcDark: "#FFFFFF",
  hcLight: "#292929"
}, localize(4269, null));
var $5nb = $5n("titleBar.inactiveForeground", {
  dark: $0n($4nb, 0.6),
  light: $0n($4nb, 0.6),
  hcDark: null,
  hcLight: "#292929"
}, localize(4270, null));
var $6nb = $5n("titleBar.activeBackground", {
  dark: "#3C3C3C",
  light: "#DDDDDD",
  hcDark: "#000000",
  hcLight: "#FFFFFF"
}, localize(4271, null));
var $7nb = $5n("titleBar.inactiveBackground", {
  dark: $0n($6nb, 0.6),
  light: $0n($6nb, 0.6),
  hcDark: null,
  hcLight: null
}, localize(4272, null));
var $8nb = $5n("titleBar.border", {
  dark: null,
  light: null,
  hcDark: $ko,
  hcLight: $ko
}, localize(4273, null));
var $9nb = $5n("menubar.selectionForeground", $4nb, localize(4274, null));
var $0nb = $5n("menubar.selectionBackground", {
  dark: $Tp,
  light: $Tp,
  hcDark: null,
  hcLight: null
}, localize(4275, null));
var $$nb = $5n("menubar.selectionBorder", {
  dark: null,
  light: null,
  hcDark: $lo,
  hcLight: $lo
}, localize(4276, null));
var $_nb = $5n("commandCenter.foreground", $4nb, localize(4277, null), false);
var $aob = $5n("commandCenter.activeForeground", $9nb, localize(4278, null), false);
var $bob = $5n("commandCenter.inactiveForeground", $5nb, localize(4279, null), false);
var $cob = $5n("commandCenter.background", { dark: $Vn.white.transparent(0.05), hcDark: null, light: $Vn.black.transparent(0.05), hcLight: null }, localize(4280, null), false);
var $dob = $5n("commandCenter.activeBackground", { dark: $Vn.white.transparent(0.08), hcDark: $0nb, light: $Vn.black.transparent(0.08), hcLight: $0nb }, localize(4281, null), false);
var $eob = $5n("commandCenter.border", { dark: $0n($4nb, 0.2), hcDark: $ko, light: $0n($4nb, 0.2), hcLight: $ko }, localize(4282, null), false);
var $fob = $5n("commandCenter.activeBorder", { dark: $0n($4nb, 0.3), hcDark: $4nb, light: $0n($4nb, 0.3), hcLight: $4nb }, localize(4283, null), false);
var $gob = $5n("commandCenter.inactiveBorder", $0n($5nb, 0.25), localize(4284, null), false);
var $hob = $5n("notificationCenter.border", {
  dark: $Sp,
  light: $Sp,
  hcDark: $ko,
  hcLight: $ko
}, localize(4285, null));
var $iob = $5n("notificationToast.border", {
  dark: $Sp,
  light: $Sp,
  hcDark: $ko,
  hcLight: $ko
}, localize(4286, null));
var $job = $5n("notifications.foreground", $Ro, localize(4287, null));
var $kob = $5n("notifications.background", $Qo, localize(4288, null));
var $lob = $5n("notificationLink.foreground", $no, localize(4289, null));
var $mob = $5n("notificationCenterHeader.foreground", null, localize(4290, null));
var $nob = $5n("notificationCenterHeader.background", {
  dark: $9n($kob, 0.3),
  light: $8n($kob, 0.05),
  hcDark: $kob,
  hcLight: $kob
}, localize(4291, null));
var $oob = $5n("notifications.border", $nob, localize(4292, null));
var $pob = $5n("notificationsErrorIcon.foreground", $Vo, localize(4293, null));
var $qob = $5n("notificationsWarningIcon.foreground", $Yo, localize(4294, null));
var $rob = $5n("notificationsInfoIcon.foreground", $2o, localize(4295, null));
var $sob = $5n("window.activeBorder", {
  dark: null,
  light: null,
  hcDark: $ko,
  hcLight: $ko
}, localize(4296, null));
var $tob = $5n("window.inactiveBorder", {
  dark: null,
  light: null,
  hcDark: $ko,
  hcLight: $ko
}, localize(4297, null));

// out-build/vs/workbench/api/browser/statusBarExtensionPoint.js
var $drb = $Qk("IExtensionStatusBarItemService");
var StatusBarUpdateKind;
(function(StatusBarUpdateKind2) {
  StatusBarUpdateKind2[StatusBarUpdateKind2["DidDefine"] = 0] = "DidDefine";
  StatusBarUpdateKind2[StatusBarUpdateKind2["DidUpdate"] = 1] = "DidUpdate";
})(StatusBarUpdateKind || (StatusBarUpdateKind = {}));
var ExtensionStatusBarItemService = class ExtensionStatusBarItemService2 {
  constructor(c) {
    this.c = c;
    this.a = /* @__PURE__ */ new Map();
    this.b = new $ze();
    this.onDidChange = this.b.event;
  }
  dispose() {
    this.a.forEach((entry) => entry.accessor.dispose());
    this.a.clear();
    this.b.dispose();
  }
  setOrUpdateEntry(entryId, id2, extensionId, name, text2, tooltip, command4, color2, backgroundColor, alignLeft, priority, accessibilityInformation) {
    let ariaLabel;
    let role = void 0;
    if (accessibilityInformation) {
      ariaLabel = accessibilityInformation.label;
      role = accessibilityInformation.role;
    } else {
      ariaLabel = $$l(text2);
      if (tooltip) {
        const tooltipString = typeof tooltip === "string" ? tooltip : tooltip.value;
        ariaLabel += `, ${tooltipString}`;
      }
    }
    let kind = void 0;
    switch (backgroundColor?.id) {
      case $fnb:
      case $jnb:
        kind = backgroundColor.id === $fnb ? "error" : "warning";
        color2 = void 0;
        backgroundColor = void 0;
    }
    const entry = { name, text: text2, tooltip, command: command4, color: color2, backgroundColor, ariaLabel, role, kind };
    if (typeof priority === "undefined") {
      priority = 0;
    }
    let alignment = alignLeft ? 0 : 1;
    const existingEntry = this.a.get(entryId);
    if (existingEntry) {
      alignment = existingEntry.alignment;
      priority = existingEntry.priority;
    }
    if (!existingEntry) {
      let entryPriority;
      if (typeof extensionId === "string") {
        entryPriority = { primary: priority, secondary: $Xi(extensionId) };
      } else {
        entryPriority = priority;
      }
      const accessor = this.c.addEntry(entry, id2, alignment, entryPriority);
      this.a.set(entryId, {
        accessor,
        entry,
        alignment,
        priority,
        disposable: $1c(() => {
          accessor.dispose();
          this.a.delete(entryId);
          this.b.fire({ removed: entryId });
        })
      });
      this.b.fire({ added: [entryId, { entry, alignment, priority }] });
      return 0;
    } else {
      existingEntry.accessor.update(entry);
      existingEntry.entry = entry;
      return 1;
    }
  }
  unsetEntry(entryId) {
    this.a.get(entryId)?.disposable.dispose();
    this.a.delete(entryId);
  }
  getEntries() {
    return this.a.entries();
  }
};
ExtensionStatusBarItemService = __decorate([
  __param(0, $$qb)
], ExtensionStatusBarItemService);
$SC(
  $drb,
  ExtensionStatusBarItemService,
  1
  /* InstantiationType.Delayed */
);
function isUserFriendlyStatusItemEntry(candidate) {
  const obj = candidate;
  return typeof obj.id === "string" && obj.id.length > 0 && typeof obj.name === "string" && typeof obj.text === "string" && (obj.alignment === "left" || obj.alignment === "right") && (obj.command === void 0 || typeof obj.command === "string") && (obj.tooltip === void 0 || typeof obj.tooltip === "string") && (obj.priority === void 0 || typeof obj.priority === "number") && (obj.accessibilityInformation === void 0 || $PD(obj.accessibilityInformation));
}
var statusBarItemSchema = {
  type: "object",
  required: ["id", "text", "alignment", "name"],
  properties: {
    id: {
      type: "string",
      markdownDescription: localize(2637, null)
    },
    name: {
      type: "string",
      description: localize(2638, null)
    },
    text: {
      type: "string",
      description: localize(2639, null)
    },
    tooltip: {
      type: "string",
      description: localize(2640, null)
    },
    command: {
      type: "string",
      description: localize(2641, null)
    },
    alignment: {
      type: "string",
      enum: ["left", "right"],
      description: localize(2642, null)
    },
    priority: {
      type: "number",
      description: localize(2643, null)
    },
    accessibilityInformation: {
      type: "object",
      description: localize(2644, null),
      properties: {
        role: {
          type: "string",
          description: localize(2645, null)
        },
        label: {
          type: "string",
          description: localize(2646, null)
        }
      }
    }
  }
};
var statusBarItemsSchema = {
  description: localize(2647, null),
  oneOf: [
    statusBarItemSchema,
    {
      type: "array",
      items: statusBarItemSchema
    }
  ]
};
var statusBarItemsExtensionPoint = $tN.registerExtensionPoint({
  extensionPoint: "statusBarItems",
  jsonSchema: statusBarItemsSchema
});
var $erb = class $erb2 {
  constructor(statusBarItemsService) {
    const contributions = new $2c();
    statusBarItemsExtensionPoint.setHandler((extensions) => {
      contributions.clear();
      for (const entry of extensions) {
        if (!$zN(entry.description, "contribStatusBarItems")) {
          entry.collector.error(`The ${statusBarItemsExtensionPoint.name} is proposed API`);
          continue;
        }
        const { value, collector } = entry;
        for (const candidate of Iterable.wrap(value)) {
          if (!isUserFriendlyStatusItemEntry(candidate)) {
            collector.error(localize(2648, null));
            continue;
          }
          const fullItemId = $bU(entry.description.identifier, candidate.id);
          const kind = statusBarItemsService.setOrUpdateEntry(fullItemId, fullItemId, $5z.toKey(entry.description.identifier), candidate.name ?? entry.description.displayName ?? entry.description.name, candidate.text, candidate.tooltip, candidate.command ? { id: candidate.command, title: candidate.name } : void 0, void 0, void 0, candidate.alignment === "left", candidate.priority, candidate.accessibilityInformation);
          if (kind === 0) {
            contributions.add($1c(() => statusBarItemsService.unsetEntry(fullItemId)));
          }
        }
      }
    });
  }
};
$erb = __decorate([
  __param(0, $drb)
], $erb);

// out-build/vs/workbench/services/extensions/common/proxyIdentifier.js
var $BS = class _$BS {
  static {
    this.count = 0;
  }
  constructor(sid) {
    this._proxyIdentifierBrand = void 0;
    this.sid = sid;
    this.nid = ++_$BS.count;
  }
};
var identifiers = [];
function $CS(identifier2) {
  const result = new $BS(identifier2);
  identifiers[result.nid] = result;
  return result;
}
function $DS(nid) {
  return identifiers[nid].sid;
}
var $ES = class {
  constructor(value) {
    this.value = value;
  }
};

// out-build/vs/workbench/api/common/extHost.protocol.js
var TextEditorRevealType2;
(function(TextEditorRevealType3) {
  TextEditorRevealType3[TextEditorRevealType3["Default"] = 0] = "Default";
  TextEditorRevealType3[TextEditorRevealType3["InCenter"] = 1] = "InCenter";
  TextEditorRevealType3[TextEditorRevealType3["InCenterIfOutsideViewport"] = 2] = "InCenterIfOutsideViewport";
  TextEditorRevealType3[TextEditorRevealType3["AtTop"] = 3] = "AtTop";
})(TextEditorRevealType2 || (TextEditorRevealType2 = {}));
var TabInputKind;
(function(TabInputKind2) {
  TabInputKind2[TabInputKind2["UnknownInput"] = 0] = "UnknownInput";
  TabInputKind2[TabInputKind2["TextInput"] = 1] = "TextInput";
  TabInputKind2[TabInputKind2["TextDiffInput"] = 2] = "TextDiffInput";
  TabInputKind2[TabInputKind2["TextMergeInput"] = 3] = "TextMergeInput";
  TabInputKind2[TabInputKind2["NotebookInput"] = 4] = "NotebookInput";
  TabInputKind2[TabInputKind2["NotebookDiffInput"] = 5] = "NotebookDiffInput";
  TabInputKind2[TabInputKind2["CustomEditorInput"] = 6] = "CustomEditorInput";
  TabInputKind2[TabInputKind2["WebviewEditorInput"] = 7] = "WebviewEditorInput";
  TabInputKind2[TabInputKind2["TerminalEditorInput"] = 8] = "TerminalEditorInput";
  TabInputKind2[TabInputKind2["InteractiveEditorInput"] = 9] = "InteractiveEditorInput";
  TabInputKind2[TabInputKind2["ChatEditorInput"] = 10] = "ChatEditorInput";
  TabInputKind2[TabInputKind2["MultiDiffEditorInput"] = 11] = "MultiDiffEditorInput";
})(TabInputKind || (TabInputKind = {}));
var TabModelOperationKind;
(function(TabModelOperationKind2) {
  TabModelOperationKind2[TabModelOperationKind2["TAB_OPEN"] = 0] = "TAB_OPEN";
  TabModelOperationKind2[TabModelOperationKind2["TAB_CLOSE"] = 1] = "TAB_CLOSE";
  TabModelOperationKind2[TabModelOperationKind2["TAB_UPDATE"] = 2] = "TAB_UPDATE";
  TabModelOperationKind2[TabModelOperationKind2["TAB_MOVE"] = 3] = "TAB_MOVE";
})(TabModelOperationKind || (TabModelOperationKind = {}));
var WebviewEditorCapabilities;
(function(WebviewEditorCapabilities2) {
  WebviewEditorCapabilities2[WebviewEditorCapabilities2["Editable"] = 0] = "Editable";
  WebviewEditorCapabilities2[WebviewEditorCapabilities2["SupportsHotExit"] = 1] = "SupportsHotExit";
})(WebviewEditorCapabilities || (WebviewEditorCapabilities = {}));
var WebviewMessageArrayBufferViewType;
(function(WebviewMessageArrayBufferViewType2) {
  WebviewMessageArrayBufferViewType2[WebviewMessageArrayBufferViewType2["Int8Array"] = 1] = "Int8Array";
  WebviewMessageArrayBufferViewType2[WebviewMessageArrayBufferViewType2["Uint8Array"] = 2] = "Uint8Array";
  WebviewMessageArrayBufferViewType2[WebviewMessageArrayBufferViewType2["Uint8ClampedArray"] = 3] = "Uint8ClampedArray";
  WebviewMessageArrayBufferViewType2[WebviewMessageArrayBufferViewType2["Int16Array"] = 4] = "Int16Array";
  WebviewMessageArrayBufferViewType2[WebviewMessageArrayBufferViewType2["Uint16Array"] = 5] = "Uint16Array";
  WebviewMessageArrayBufferViewType2[WebviewMessageArrayBufferViewType2["Int32Array"] = 6] = "Int32Array";
  WebviewMessageArrayBufferViewType2[WebviewMessageArrayBufferViewType2["Uint32Array"] = 7] = "Uint32Array";
  WebviewMessageArrayBufferViewType2[WebviewMessageArrayBufferViewType2["Float32Array"] = 8] = "Float32Array";
  WebviewMessageArrayBufferViewType2[WebviewMessageArrayBufferViewType2["Float64Array"] = 9] = "Float64Array";
  WebviewMessageArrayBufferViewType2[WebviewMessageArrayBufferViewType2["BigInt64Array"] = 10] = "BigInt64Array";
  WebviewMessageArrayBufferViewType2[WebviewMessageArrayBufferViewType2["BigUint64Array"] = 11] = "BigUint64Array";
})(WebviewMessageArrayBufferViewType || (WebviewMessageArrayBufferViewType = {}));
var CellOutputKind;
(function(CellOutputKind2) {
  CellOutputKind2[CellOutputKind2["Text"] = 1] = "Text";
  CellOutputKind2[CellOutputKind2["Error"] = 2] = "Error";
  CellOutputKind2[CellOutputKind2["Rich"] = 3] = "Rich";
})(CellOutputKind || (CellOutputKind = {}));
var NotebookEditorRevealType2;
(function(NotebookEditorRevealType3) {
  NotebookEditorRevealType3[NotebookEditorRevealType3["Default"] = 0] = "Default";
  NotebookEditorRevealType3[NotebookEditorRevealType3["InCenter"] = 1] = "InCenter";
  NotebookEditorRevealType3[NotebookEditorRevealType3["InCenterIfOutsideViewport"] = 2] = "InCenterIfOutsideViewport";
  NotebookEditorRevealType3[NotebookEditorRevealType3["AtTop"] = 3] = "AtTop";
})(NotebookEditorRevealType2 || (NotebookEditorRevealType2 = {}));
var CandidatePortSource;
(function(CandidatePortSource2) {
  CandidatePortSource2[CandidatePortSource2["None"] = 0] = "None";
  CandidatePortSource2[CandidatePortSource2["Process"] = 1] = "Process";
  CandidatePortSource2[CandidatePortSource2["Output"] = 2] = "Output";
  CandidatePortSource2[CandidatePortSource2["Hybrid"] = 3] = "Hybrid";
})(CandidatePortSource || (CandidatePortSource = {}));
var $wT = class _$wT {
  static {
    this.a = 0;
  }
  static mixin(object) {
    object._id = _$wT.a++;
    return object;
  }
};
var ISuggestDataDtoField;
(function(ISuggestDataDtoField2) {
  ISuggestDataDtoField2["label"] = "a";
  ISuggestDataDtoField2["kind"] = "b";
  ISuggestDataDtoField2["detail"] = "c";
  ISuggestDataDtoField2["documentation"] = "d";
  ISuggestDataDtoField2["sortText"] = "e";
  ISuggestDataDtoField2["filterText"] = "f";
  ISuggestDataDtoField2["preselect"] = "g";
  ISuggestDataDtoField2["insertText"] = "h";
  ISuggestDataDtoField2["insertTextRules"] = "i";
  ISuggestDataDtoField2["range"] = "j";
  ISuggestDataDtoField2["commitCharacters"] = "k";
  ISuggestDataDtoField2["additionalTextEdits"] = "l";
  ISuggestDataDtoField2["kindModifier"] = "m";
  ISuggestDataDtoField2["commandIdent"] = "n";
  ISuggestDataDtoField2["commandId"] = "o";
  ISuggestDataDtoField2["commandArguments"] = "p";
})(ISuggestDataDtoField || (ISuggestDataDtoField = {}));
var ISuggestResultDtoField;
(function(ISuggestResultDtoField2) {
  ISuggestResultDtoField2["defaultRanges"] = "a";
  ISuggestResultDtoField2["completions"] = "b";
  ISuggestResultDtoField2["isIncomplete"] = "c";
  ISuggestResultDtoField2["duration"] = "d";
})(ISuggestResultDtoField || (ISuggestResultDtoField = {}));
var ExtHostTestingResource;
(function(ExtHostTestingResource2) {
  ExtHostTestingResource2[ExtHostTestingResource2["Workspace"] = 0] = "Workspace";
  ExtHostTestingResource2[ExtHostTestingResource2["TextDocument"] = 1] = "TextDocument";
})(ExtHostTestingResource || (ExtHostTestingResource = {}));
var $xT = {
  MainThreadAuthentication: $CS("MainThreadAuthentication"),
  MainThreadBulkEdits: $CS("MainThreadBulkEdits"),
  MainThreadLanguageModels: $CS("MainThreadLanguageModels"),
  MainThreadEmbeddings: $CS("MainThreadEmbeddings"),
  MainThreadChatAgents2: $CS("MainThreadChatAgents2"),
  MainThreadCodeMapper: $CS("MainThreadCodeMapper"),
  MainThreadChatVariables: $CS("MainThreadChatVariables"),
  MainThreadLanguageModelTools: $CS("MainThreadChatSkills"),
  MainThreadClipboard: $CS("MainThreadClipboard"),
  MainThreadCommands: $CS("MainThreadCommands"),
  MainThreadComments: $CS("MainThreadComments"),
  MainThreadConfiguration: $CS("MainThreadConfiguration"),
  MainThreadConsole: $CS("MainThreadConsole"),
  MainThreadDebugService: $CS("MainThreadDebugService"),
  MainThreadDecorations: $CS("MainThreadDecorations"),
  MainThreadDiagnostics: $CS("MainThreadDiagnostics"),
  MainThreadDialogs: $CS("MainThreadDiaglogs"),
  MainThreadDocuments: $CS("MainThreadDocuments"),
  MainThreadDocumentContentProviders: $CS("MainThreadDocumentContentProviders"),
  MainThreadTextEditors: $CS("MainThreadTextEditors"),
  MainThreadEditorInsets: $CS("MainThreadEditorInsets"),
  MainThreadEditorTabs: $CS("MainThreadEditorTabs"),
  MainThreadErrors: $CS("MainThreadErrors"),
  MainThreadTreeViews: $CS("MainThreadTreeViews"),
  MainThreadDownloadService: $CS("MainThreadDownloadService"),
  MainThreadLanguageFeatures: $CS("MainThreadLanguageFeatures"),
  MainThreadLanguages: $CS("MainThreadLanguages"),
  MainThreadLogger: $CS("MainThreadLogger"),
  MainThreadMessageService: $CS("MainThreadMessageService"),
  MainThreadOutputService: $CS("MainThreadOutputService"),
  MainThreadProgress: $CS("MainThreadProgress"),
  MainThreadQuickDiff: $CS("MainThreadQuickDiff"),
  MainThreadQuickOpen: $CS("MainThreadQuickOpen"),
  MainThreadStatusBar: $CS("MainThreadStatusBar"),
  MainThreadSecretState: $CS("MainThreadSecretState"),
  MainThreadStorage: $CS("MainThreadStorage"),
  MainThreadSpeech: $CS("MainThreadSpeechProvider"),
  MainThreadTelemetry: $CS("MainThreadTelemetry"),
  MainThreadTerminalService: $CS("MainThreadTerminalService"),
  MainThreadTerminalShellIntegration: $CS("MainThreadTerminalShellIntegration"),
  MainThreadWebviews: $CS("MainThreadWebviews"),
  MainThreadWebviewPanels: $CS("MainThreadWebviewPanels"),
  MainThreadWebviewViews: $CS("MainThreadWebviewViews"),
  MainThreadCustomEditors: $CS("MainThreadCustomEditors"),
  MainThreadUrls: $CS("MainThreadUrls"),
  MainThreadUriOpeners: $CS("MainThreadUriOpeners"),
  MainThreadProfileContentHandlers: $CS("MainThreadProfileContentHandlers"),
  MainThreadWorkspace: $CS("MainThreadWorkspace"),
  MainThreadFileSystem: $CS("MainThreadFileSystem"),
  MainThreadFileSystemEventService: $CS("MainThreadFileSystemEventService"),
  MainThreadExtensionService: $CS("MainThreadExtensionService"),
  MainThreadSCM: $CS("MainThreadSCM"),
  MainThreadSearch: $CS("MainThreadSearch"),
  MainThreadShare: $CS("MainThreadShare"),
  MainThreadTask: $CS("MainThreadTask"),
  MainThreadWindow: $CS("MainThreadWindow"),
  MainThreadLabelService: $CS("MainThreadLabelService"),
  MainThreadNotebook: $CS("MainThreadNotebook"),
  MainThreadNotebookDocuments: $CS("MainThreadNotebookDocumentsShape"),
  MainThreadNotebookEditors: $CS("MainThreadNotebookEditorsShape"),
  MainThreadNotebookKernels: $CS("MainThreadNotebookKernels"),
  MainThreadNotebookRenderers: $CS("MainThreadNotebookRenderers"),
  MainThreadInteractive: $CS("MainThreadInteractive"),
  MainThreadTheming: $CS("MainThreadTheming"),
  MainThreadTunnelService: $CS("MainThreadTunnelService"),
  MainThreadManagedSockets: $CS("MainThreadManagedSockets"),
  MainThreadTimeline: $CS("MainThreadTimeline"),
  MainThreadTesting: $CS("MainThreadTesting"),
  MainThreadLocalization: $CS("MainThreadLocalizationShape"),
  MainThreadAiRelatedInformation: $CS("MainThreadAiRelatedInformation"),
  MainThreadAiEmbeddingVector: $CS("MainThreadAiEmbeddingVector")
};
var $yT = {
  ExtHostCodeMapper: $CS("ExtHostCodeMapper"),
  ExtHostCommands: $CS("ExtHostCommands"),
  ExtHostConfiguration: $CS("ExtHostConfiguration"),
  ExtHostDiagnostics: $CS("ExtHostDiagnostics"),
  ExtHostDebugService: $CS("ExtHostDebugService"),
  ExtHostDecorations: $CS("ExtHostDecorations"),
  ExtHostDocumentsAndEditors: $CS("ExtHostDocumentsAndEditors"),
  ExtHostDocuments: $CS("ExtHostDocuments"),
  ExtHostDocumentContentProviders: $CS("ExtHostDocumentContentProviders"),
  ExtHostDocumentSaveParticipant: $CS("ExtHostDocumentSaveParticipant"),
  ExtHostEditors: $CS("ExtHostEditors"),
  ExtHostTreeViews: $CS("ExtHostTreeViews"),
  ExtHostFileSystem: $CS("ExtHostFileSystem"),
  ExtHostFileSystemInfo: $CS("ExtHostFileSystemInfo"),
  ExtHostFileSystemEventService: $CS("ExtHostFileSystemEventService"),
  ExtHostLanguages: $CS("ExtHostLanguages"),
  ExtHostLanguageFeatures: $CS("ExtHostLanguageFeatures"),
  ExtHostQuickOpen: $CS("ExtHostQuickOpen"),
  ExtHostQuickDiff: $CS("ExtHostQuickDiff"),
  ExtHostStatusBar: $CS("ExtHostStatusBar"),
  ExtHostShare: $CS("ExtHostShare"),
  ExtHostExtensionService: $CS("ExtHostExtensionService"),
  ExtHostLogLevelServiceShape: $CS("ExtHostLogLevelServiceShape"),
  ExtHostTerminalService: $CS("ExtHostTerminalService"),
  ExtHostTerminalShellIntegration: $CS("ExtHostTerminalShellIntegration"),
  ExtHostSCM: $CS("ExtHostSCM"),
  ExtHostSearch: $CS("ExtHostSearch"),
  ExtHostTask: $CS("ExtHostTask"),
  ExtHostWorkspace: $CS("ExtHostWorkspace"),
  ExtHostWindow: $CS("ExtHostWindow"),
  ExtHostWebviews: $CS("ExtHostWebviews"),
  ExtHostWebviewPanels: $CS("ExtHostWebviewPanels"),
  ExtHostCustomEditors: $CS("ExtHostCustomEditors"),
  ExtHostWebviewViews: $CS("ExtHostWebviewViews"),
  ExtHostEditorInsets: $CS("ExtHostEditorInsets"),
  ExtHostEditorTabs: $CS("ExtHostEditorTabs"),
  ExtHostProgress: $CS("ExtHostProgress"),
  ExtHostComments: $CS("ExtHostComments"),
  ExtHostSecretState: $CS("ExtHostSecretState"),
  ExtHostStorage: $CS("ExtHostStorage"),
  ExtHostUrls: $CS("ExtHostUrls"),
  ExtHostUriOpeners: $CS("ExtHostUriOpeners"),
  ExtHostProfileContentHandlers: $CS("ExtHostProfileContentHandlers"),
  ExtHostOutputService: $CS("ExtHostOutputService"),
  ExtHostLabelService: $CS("ExtHostLabelService"),
  ExtHostNotebook: $CS("ExtHostNotebook"),
  ExtHostNotebookDocuments: $CS("ExtHostNotebookDocuments"),
  ExtHostNotebookEditors: $CS("ExtHostNotebookEditors"),
  ExtHostNotebookKernels: $CS("ExtHostNotebookKernels"),
  ExtHostNotebookRenderers: $CS("ExtHostNotebookRenderers"),
  ExtHostNotebookDocumentSaveParticipant: $CS("ExtHostNotebookDocumentSaveParticipant"),
  ExtHostInteractive: $CS("ExtHostInteractive"),
  ExtHostChatAgents2: $CS("ExtHostChatAgents"),
  ExtHostChatVariables: $CS("ExtHostChatVariables"),
  ExtHostLanguageModelTools: $CS("ExtHostChatSkills"),
  ExtHostChatProvider: $CS("ExtHostChatProvider"),
  ExtHostSpeech: $CS("ExtHostSpeech"),
  ExtHostEmbeddings: $CS("ExtHostEmbeddings"),
  ExtHostAiRelatedInformation: $CS("ExtHostAiRelatedInformation"),
  ExtHostAiEmbeddingVector: $CS("ExtHostAiEmbeddingVector"),
  ExtHostTheming: $CS("ExtHostTheming"),
  ExtHostTunnelService: $CS("ExtHostTunnelService"),
  ExtHostManagedSockets: $CS("ExtHostManagedSockets"),
  ExtHostAuthentication: $CS("ExtHostAuthentication"),
  ExtHostTimeline: $CS("ExtHostTimeline"),
  ExtHostTesting: $CS("ExtHostTesting"),
  ExtHostTelemetry: $CS("ExtHostTelemetry"),
  ExtHostLocalization: $CS("ExtHostLocalization")
};

// out-build/vs/workbench/services/extensions/common/extHostCustomers.js
function $frb(id2) {
  return function(ctor) {
    ExtHostCustomersRegistryImpl.INSTANCE.registerNamedCustomer(id2, ctor);
  };
}
function $grb(ctor) {
  ExtHostCustomersRegistryImpl.INSTANCE.registerCustomer(ctor);
}
var ExtHostCustomersRegistry;
(function(ExtHostCustomersRegistry2) {
  function getNamedCustomers() {
    return ExtHostCustomersRegistryImpl.INSTANCE.getNamedCustomers();
  }
  ExtHostCustomersRegistry2.getNamedCustomers = getNamedCustomers;
  function getCustomers() {
    return ExtHostCustomersRegistryImpl.INSTANCE.getCustomers();
  }
  ExtHostCustomersRegistry2.getCustomers = getCustomers;
})(ExtHostCustomersRegistry || (ExtHostCustomersRegistry = {}));
var ExtHostCustomersRegistryImpl = class _ExtHostCustomersRegistryImpl {
  static {
    this.INSTANCE = new _ExtHostCustomersRegistryImpl();
  }
  constructor() {
    this.a = [];
    this.b = [];
  }
  registerNamedCustomer(id2, ctor) {
    const entry = [id2, ctor];
    this.a.push(entry);
  }
  getNamedCustomers() {
    return this.a;
  }
  registerCustomer(ctor) {
    this.b.push(ctor);
  }
  getCustomers() {
    return this.b;
  }
};

// out-build/vs/platform/languagePacks/common/languagePacks.js
function $xX(extension) {
  return extension.tags.find((t) => t.startsWith("lp-"))?.split("lp-")[1];
}
var $yX = $Qk("languagePackService");
var $zX = class $zX2 extends $3c {
  constructor(c) {
    super();
    this.c = c;
  }
  async getAvailableLanguages() {
    const timeout = new $ad();
    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 = $xX(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 label3 = languageName ?? locale;
    let description;
    if (label3 !== locale) {
      description = `(${locale})`;
    }
    if (locale.toLowerCase() === $z.toLowerCase()) {
      description ??= "";
      description += localize(1961, 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: label3,
      description
    };
  }
};
$zX = __decorate([
  __param(0, $pA)
], $zX);

// out-build/vs/workbench/api/browser/mainThreadLocalization.js
var $hrb = class $hrb2 extends $3c {
  constructor(extHostContext, a, b) {
    super();
    this.a = a;
    this.b = b;
  }
  async $fetchBuiltInBundleUri(id2, language) {
    try {
      const uri = await this.b.getBuiltInExtensionTranslationsUri(id2, language);
      return uri;
    } catch (e) {
      return void 0;
    }
  }
  async $fetchBundleContents(uriComponents) {
    const contents = await this.a.readFile(URI.revive(uriComponents));
    return contents.value.toString();
  }
};
$hrb = __decorate([
  $frb($xT.MainThreadLocalization),
  __param(1, $km),
  __param(2, $yX)
], $hrb);

// out-build/vs/workbench/contrib/notebook/common/notebookService.js
var $mrb = $Qk("notebookService");
var $nrb = class {
  constructor(viewType, serializer, extensionData) {
    this.viewType = viewType;
    this.serializer = serializer;
    this.extensionData = extensionData;
  }
};

// out-build/vs/workbench/contrib/notebook/common/notebookEditorModelResolverService.js
var $orb = $Qk("INotebookModelResolverService");

// out-build/vs/workbench/common/editor.js
var $ZK = {
  EditorPane: "workbench.contributions.editors",
  EditorFactory: "workbench.contributions.editor.inputFactories"
};
var $1K = {
  id: "default",
  displayName: localize(4133, null),
  providerDisplayName: localize(4134, null)
};
var $2K = "workbench.editor.sidebysideEditor";
var $3K = "workbench.editors.textDiffEditor";
var $4K = "workbench.editors.binaryResourceDiffEditor";
var EditorPaneSelectionChangeReason;
(function(EditorPaneSelectionChangeReason2) {
  EditorPaneSelectionChangeReason2[EditorPaneSelectionChangeReason2["PROGRAMMATIC"] = 1] = "PROGRAMMATIC";
  EditorPaneSelectionChangeReason2[EditorPaneSelectionChangeReason2["USER"] = 2] = "USER";
  EditorPaneSelectionChangeReason2[EditorPaneSelectionChangeReason2["EDIT"] = 3] = "EDIT";
  EditorPaneSelectionChangeReason2[EditorPaneSelectionChangeReason2["NAVIGATION"] = 4] = "NAVIGATION";
  EditorPaneSelectionChangeReason2[EditorPaneSelectionChangeReason2["JUMP"] = 5] = "JUMP";
})(EditorPaneSelectionChangeReason || (EditorPaneSelectionChangeReason = {}));
var EditorPaneSelectionCompareResult;
(function(EditorPaneSelectionCompareResult2) {
  EditorPaneSelectionCompareResult2[EditorPaneSelectionCompareResult2["IDENTICAL"] = 1] = "IDENTICAL";
  EditorPaneSelectionCompareResult2[EditorPaneSelectionCompareResult2["SIMILAR"] = 2] = "SIMILAR";
  EditorPaneSelectionCompareResult2[EditorPaneSelectionCompareResult2["DIFFERENT"] = 3] = "DIFFERENT";
})(EditorPaneSelectionCompareResult || (EditorPaneSelectionCompareResult = {}));
function $5K(editorPane) {
  const candidate = editorPane;
  return !!candidate && typeof candidate.getSelection === "function" && !!candidate.onDidChangeSelection;
}
function $6K(editorPane) {
  const candidate = editorPane;
  return !!candidate && typeof candidate.getScrollPosition === "function" && typeof candidate.setScrollPosition === "function" && !!candidate.onDidChangeScroll;
}
function $7K(input, group2, editorService) {
  for (const editorPane of editorService.visibleEditorPanes) {
    if (editorPane.group.id === group2 && input.matches(editorPane.input)) {
      return editorPane.getViewState();
    }
  }
  return void 0;
}
function $8K(editor) {
  if ($dL(editor)) {
    return false;
  }
  const candidate = editor;
  return URI.isUri(candidate?.resource);
}
function $9K(editor) {
  if ($dL(editor)) {
    return false;
  }
  const candidate = editor;
  return candidate?.original !== void 0 && candidate.modified !== void 0;
}
function $0K(editor) {
  if ($dL(editor)) {
    return false;
  }
  const candidate = editor;
  if (!candidate) {
    return false;
  }
  if (candidate.resources && !Array.isArray(candidate.resources)) {
    return false;
  }
  return !!candidate.resources || !!candidate.multiDiffSource;
}
function $$K(editor) {
  if ($dL(editor)) {
    return false;
  }
  if ($9K(editor)) {
    return false;
  }
  const candidate = editor;
  return candidate?.primary !== void 0 && candidate.secondary !== void 0;
}
function $_K(editor) {
  if ($dL(editor)) {
    return false;
  }
  const candidate = editor;
  if (!candidate) {
    return false;
  }
  return candidate.resource === void 0 || candidate.resource.scheme === Schemas.untitled || candidate.forceUntitled === true;
}
function $aL(editor) {
  if ($dL(editor)) {
    return false;
  }
  const candidate = editor;
  return URI.isUri(candidate?.base?.resource) && URI.isUri(candidate?.input1?.resource) && URI.isUri(candidate?.input2?.resource) && URI.isUri(candidate?.result?.resource);
}
var Verbosity2;
(function(Verbosity3) {
  Verbosity3[Verbosity3["SHORT"] = 0] = "SHORT";
  Verbosity3[Verbosity3["MEDIUM"] = 1] = "MEDIUM";
  Verbosity3[Verbosity3["LONG"] = 2] = "LONG";
})(Verbosity2 || (Verbosity2 = {}));
var SaveReason;
(function(SaveReason2) {
  SaveReason2[SaveReason2["EXPLICIT"] = 1] = "EXPLICIT";
  SaveReason2[SaveReason2["AUTO"] = 2] = "AUTO";
  SaveReason2[SaveReason2["FOCUS_CHANGE"] = 3] = "FOCUS_CHANGE";
  SaveReason2[SaveReason2["WINDOW_CHANGE"] = 4] = "WINDOW_CHANGE";
})(SaveReason || (SaveReason = {}));
var SaveSourceFactory = class {
  constructor() {
    this.a = /* @__PURE__ */ new Map();
  }
  /**
   * Registers a `SaveSource` with an identifier and label
   * to the registry so that it can be used in save operations.
   */
  registerSource(id2, label3) {
    let sourceDescriptor = this.a.get(id2);
    if (!sourceDescriptor) {
      sourceDescriptor = { source: id2, label: label3 };
      this.a.set(id2, sourceDescriptor);
    }
    return sourceDescriptor.source;
  }
  getSourceLabel(source) {
    return this.a.get(source)?.label ?? source;
  }
};
var $bL = new SaveSourceFactory();
var EditorInputCapabilities;
(function(EditorInputCapabilities2) {
  EditorInputCapabilities2[EditorInputCapabilities2["None"] = 0] = "None";
  EditorInputCapabilities2[EditorInputCapabilities2["Readonly"] = 2] = "Readonly";
  EditorInputCapabilities2[EditorInputCapabilities2["Untitled"] = 4] = "Untitled";
  EditorInputCapabilities2[EditorInputCapabilities2["Singleton"] = 8] = "Singleton";
  EditorInputCapabilities2[EditorInputCapabilities2["RequiresTrust"] = 16] = "RequiresTrust";
  EditorInputCapabilities2[EditorInputCapabilities2["CanSplitInGroup"] = 32] = "CanSplitInGroup";
  EditorInputCapabilities2[EditorInputCapabilities2["ForceDescription"] = 64] = "ForceDescription";
  EditorInputCapabilities2[EditorInputCapabilities2["CanDropIntoEditor"] = 128] = "CanDropIntoEditor";
  EditorInputCapabilities2[EditorInputCapabilities2["MultipleEditors"] = 256] = "MultipleEditors";
  EditorInputCapabilities2[EditorInputCapabilities2["Scratchpad"] = 512] = "Scratchpad";
})(EditorInputCapabilities || (EditorInputCapabilities = {}));
var $cL = class extends $3c {
};
function $dL(editor) {
  return editor instanceof $cL;
}
function isEditorInputWithPreferredResource(editor) {
  const candidate = editor;
  return URI.isUri(candidate?.preferredResource);
}
function $eL(editor) {
  const candidate = editor;
  return $dL(candidate?.primary) && $dL(candidate?.secondary);
}
function $fL(editor) {
  const candidate = editor;
  return $dL(candidate?.modified) && $dL(candidate?.original);
}
function $gL(group2, input, options3, message, preferencesService) {
  return $qL(message, [
    $Zm({
      id: "workbench.action.openLargeFile",
      label: localize(4135, null),
      run: () => {
        const fileEditorOptions = {
          ...options3,
          limits: {
            size: Number.MAX_VALUE
          }
        };
        group2.openEditor(input, fileEditorOptions);
      }
    }),
    $Zm({
      id: "workbench.action.configureEditorLargeFileConfirmation",
      label: localize(4136, null),
      run: () => {
        return preferencesService.openUserSettings({ query: "workbench.editorLargeFileConfirmation" });
      }
    })
  ], {
    forceMessage: true,
    forceSeverity: severity_default.Warning
  });
}
function $hL(editor) {
  const candidate = editor;
  return $dL(candidate?.editor);
}
function $iL(editor) {
  const candidate = editor;
  return $hL(editor) && candidate?.group !== void 0;
}
function $jL(identifier2) {
  const candidate = identifier2;
  return typeof candidate?.groupId === "number" && $dL(candidate.editor);
}
function $kL(context) {
  const candidate = context;
  return typeof candidate?.groupId === "number";
}
var EditorCloseContext;
(function(EditorCloseContext2) {
  EditorCloseContext2[EditorCloseContext2["UNKNOWN"] = 0] = "UNKNOWN";
  EditorCloseContext2[EditorCloseContext2["REPLACE"] = 1] = "REPLACE";
  EditorCloseContext2[EditorCloseContext2["MOVE"] = 2] = "MOVE";
  EditorCloseContext2[EditorCloseContext2["UNPIN"] = 3] = "UNPIN";
})(EditorCloseContext || (EditorCloseContext = {}));
var GroupModelChangeKind;
(function(GroupModelChangeKind2) {
  GroupModelChangeKind2[GroupModelChangeKind2["GROUP_ACTIVE"] = 0] = "GROUP_ACTIVE";
  GroupModelChangeKind2[GroupModelChangeKind2["GROUP_INDEX"] = 1] = "GROUP_INDEX";
  GroupModelChangeKind2[GroupModelChangeKind2["GROUP_LABEL"] = 2] = "GROUP_LABEL";
  GroupModelChangeKind2[GroupModelChangeKind2["GROUP_LOCKED"] = 3] = "GROUP_LOCKED";
  GroupModelChangeKind2[GroupModelChangeKind2["EDITORS_SELECTION"] = 4] = "EDITORS_SELECTION";
  GroupModelChangeKind2[GroupModelChangeKind2["EDITOR_OPEN"] = 5] = "EDITOR_OPEN";
  GroupModelChangeKind2[GroupModelChangeKind2["EDITOR_CLOSE"] = 6] = "EDITOR_CLOSE";
  GroupModelChangeKind2[GroupModelChangeKind2["EDITOR_MOVE"] = 7] = "EDITOR_MOVE";
  GroupModelChangeKind2[GroupModelChangeKind2["EDITOR_ACTIVE"] = 8] = "EDITOR_ACTIVE";
  GroupModelChangeKind2[GroupModelChangeKind2["EDITOR_LABEL"] = 9] = "EDITOR_LABEL";
  GroupModelChangeKind2[GroupModelChangeKind2["EDITOR_CAPABILITIES"] = 10] = "EDITOR_CAPABILITIES";
  GroupModelChangeKind2[GroupModelChangeKind2["EDITOR_PIN"] = 11] = "EDITOR_PIN";
  GroupModelChangeKind2[GroupModelChangeKind2["EDITOR_TRANSIENT"] = 12] = "EDITOR_TRANSIENT";
  GroupModelChangeKind2[GroupModelChangeKind2["EDITOR_STICKY"] = 13] = "EDITOR_STICKY";
  GroupModelChangeKind2[GroupModelChangeKind2["EDITOR_DIRTY"] = 14] = "EDITOR_DIRTY";
  GroupModelChangeKind2[GroupModelChangeKind2["EDITOR_WILL_DISPOSE"] = 15] = "EDITOR_WILL_DISPOSE";
})(GroupModelChangeKind || (GroupModelChangeKind = {}));
var SideBySideEditor;
(function(SideBySideEditor2) {
  SideBySideEditor2[SideBySideEditor2["PRIMARY"] = 1] = "PRIMARY";
  SideBySideEditor2[SideBySideEditor2["SECONDARY"] = 2] = "SECONDARY";
  SideBySideEditor2[SideBySideEditor2["BOTH"] = 3] = "BOTH";
  SideBySideEditor2[SideBySideEditor2["ANY"] = 4] = "ANY";
})(SideBySideEditor || (SideBySideEditor = {}));
var EditorResourceAccessorImpl = class {
  getOriginalUri(editor, options3) {
    if (!editor) {
      return void 0;
    }
    if ($aL(editor)) {
      return $mL.getOriginalUri(editor.result, options3);
    }
    if (options3?.supportSideBySide) {
      const { primary, secondary } = this.a(editor);
      if (primary && secondary) {
        if (options3?.supportSideBySide === SideBySideEditor.BOTH) {
          return {
            primary: this.getOriginalUri(primary, { filterByScheme: options3.filterByScheme }),
            secondary: this.getOriginalUri(secondary, { filterByScheme: options3.filterByScheme })
          };
        } else if (options3?.supportSideBySide === SideBySideEditor.ANY) {
          return this.getOriginalUri(primary, { filterByScheme: options3.filterByScheme }) ?? this.getOriginalUri(secondary, { filterByScheme: options3.filterByScheme });
        }
        editor = options3.supportSideBySide === SideBySideEditor.PRIMARY ? primary : secondary;
      }
    }
    if ($9K(editor) || $0K(editor) || $$K(editor) || $aL(editor)) {
      return void 0;
    }
    const originalResource = isEditorInputWithPreferredResource(editor) ? editor.preferredResource : editor.resource;
    if (!originalResource || !options3 || !options3.filterByScheme) {
      return originalResource;
    }
    return this.b(originalResource, options3.filterByScheme);
  }
  a(editor) {
    if ($eL(editor) || $$K(editor)) {
      return { primary: editor.primary, secondary: editor.secondary };
    }
    if ($fL(editor) || $9K(editor)) {
      return { primary: editor.modified, secondary: editor.original };
    }
    return { primary: void 0, secondary: void 0 };
  }
  getCanonicalUri(editor, options3) {
    if (!editor) {
      return void 0;
    }
    if ($aL(editor)) {
      return $mL.getCanonicalUri(editor.result, options3);
    }
    if (options3?.supportSideBySide) {
      const { primary, secondary } = this.a(editor);
      if (primary && secondary) {
        if (options3?.supportSideBySide === SideBySideEditor.BOTH) {
          return {
            primary: this.getCanonicalUri(primary, { filterByScheme: options3.filterByScheme }),
            secondary: this.getCanonicalUri(secondary, { filterByScheme: options3.filterByScheme })
          };
        } else if (options3?.supportSideBySide === SideBySideEditor.ANY) {
          return this.getCanonicalUri(primary, { filterByScheme: options3.filterByScheme }) ?? this.getCanonicalUri(secondary, { filterByScheme: options3.filterByScheme });
        }
        editor = options3.supportSideBySide === SideBySideEditor.PRIMARY ? primary : secondary;
      }
    }
    if ($9K(editor) || $0K(editor) || $$K(editor) || $aL(editor)) {
      return void 0;
    }
    const canonicalResource = editor.resource;
    if (!canonicalResource || !options3 || !options3.filterByScheme) {
      return canonicalResource;
    }
    return this.b(canonicalResource, options3.filterByScheme);
  }
  b(resource, filter) {
    if (Array.isArray(filter)) {
      if (filter.some((scheme) => resource.scheme === scheme)) {
        return resource;
      }
    } else {
      if (filter === resource.scheme) {
        return resource;
      }
    }
    return void 0;
  }
};
var EditorCloseMethod;
(function(EditorCloseMethod2) {
  EditorCloseMethod2[EditorCloseMethod2["UNKNOWN"] = 0] = "UNKNOWN";
  EditorCloseMethod2[EditorCloseMethod2["KEYBOARD"] = 1] = "KEYBOARD";
  EditorCloseMethod2[EditorCloseMethod2["MOUSE"] = 2] = "MOUSE";
})(EditorCloseMethod || (EditorCloseMethod = {}));
function $lL(group2, editor, method, configuration2) {
  if (!group2.isSticky(editor)) {
    return false;
  }
  switch (configuration2.preventPinnedEditorClose) {
    case "keyboardAndMouse":
      return method === EditorCloseMethod.MOUSE || method === EditorCloseMethod.KEYBOARD;
    case "mouse":
      return method === EditorCloseMethod.MOUSE;
    case "keyboard":
      return method === EditorCloseMethod.KEYBOARD;
  }
  return false;
}
var $mL = new EditorResourceAccessorImpl();
var CloseDirection;
(function(CloseDirection2) {
  CloseDirection2[CloseDirection2["LEFT"] = 0] = "LEFT";
  CloseDirection2[CloseDirection2["RIGHT"] = 1] = "RIGHT";
})(CloseDirection || (CloseDirection = {}));
var EditorFactoryRegistry = class {
  constructor() {
    this.c = /* @__PURE__ */ new Map();
    this.d = /* @__PURE__ */ new Map();
  }
  start(accessor) {
    const instantiationService = this.a = accessor.get($Pk);
    for (const [key2, ctor] of this.c) {
      this.e(key2, ctor, instantiationService);
    }
    this.c.clear();
  }
  e(editorTypeId, ctor, instantiationService) {
    const instance2 = instantiationService.createInstance(ctor);
    this.d.set(editorTypeId, instance2);
  }
  registerFileEditorFactory(factory) {
    if (this.b) {
      throw new Error("Can only register one file editor factory.");
    }
    this.b = factory;
  }
  getFileEditorFactory() {
    return $Kg(this.b);
  }
  registerEditorSerializer(editorTypeId, ctor) {
    if (this.c.has(editorTypeId) || this.d.has(editorTypeId)) {
      throw new Error(`A editor serializer with type ID '${editorTypeId}' was already registered.`);
    }
    if (!this.a) {
      this.c.set(editorTypeId, ctor);
    } else {
      this.e(editorTypeId, ctor, this.a);
    }
    return $1c(() => {
      this.c.delete(editorTypeId);
      this.d.delete(editorTypeId);
    });
  }
  getEditorSerializer(arg1) {
    return this.d.get(typeof arg1 === "string" ? arg1 : arg1.typeId);
  }
};
$Wn.add($ZK.EditorFactory, new EditorFactoryRegistry());
async function $nL(paths, fileService, logService) {
  if (!paths || !paths.length) {
    return [];
  }
  return await Promise.all(paths.map(async (path) => {
    const resource = URI.revive(path.fileUri);
    if (!resource) {
      logService.info("Cannot resolve the path because it is not valid.", path);
      return void 0;
    }
    const canHandleResource = await fileService.canHandleResource(resource);
    if (!canHandleResource) {
      logService.info("Cannot resolve the path because it cannot be handled", path);
      return void 0;
    }
    let exists = path.exists;
    let type = path.type;
    if (typeof exists !== "boolean" || typeof type !== "number") {
      try {
        type = (await fileService.stat(resource)).isDirectory ? FileType.Directory : FileType.Unknown;
        exists = true;
      } catch (error) {
        logService.error(error);
        exists = false;
      }
    }
    if (!exists && path.openOnlyIfExists) {
      logService.info("Cannot resolve the path because it does not exist", path);
      return void 0;
    }
    if (type === FileType.Directory) {
      logService.info("Cannot resolve the path because it is a directory", path);
      return void 0;
    }
    const options3 = {
      ...path.options,
      pinned: true
    };
    if (!exists) {
      return { resource, options: options3, forceUntitled: true };
    }
    return { resource, options: options3 };
  }));
}
var EditorsOrder;
(function(EditorsOrder2) {
  EditorsOrder2[EditorsOrder2["MOST_RECENTLY_ACTIVE"] = 0] = "MOST_RECENTLY_ACTIVE";
  EditorsOrder2[EditorsOrder2["SEQUENTIAL"] = 1] = "SEQUENTIAL";
})(EditorsOrder || (EditorsOrder = {}));
function $oL(candidate) {
  const viewState = candidate;
  if (!viewState) {
    return false;
  }
  const diffEditorViewState = viewState;
  if (diffEditorViewState.modified) {
    return $oL(diffEditorViewState.modified);
  }
  const codeEditorViewState = viewState;
  return !!(codeEditorViewState.contributionsState && codeEditorViewState.viewState && Array.isArray(codeEditorViewState.cursorState));
}
function $pL(obj) {
  return $2m(obj);
}
function $qL(messageOrError, actions, options3) {
  const error = $3m(messageOrError, actions);
  error.forceMessage = options3?.forceMessage;
  error.forceSeverity = options3?.forceSeverity;
  error.allowDialog = options3?.allowDialog;
  return error;
}

// out-build/vs/workbench/common/editor/editorInput.js
var $nG = class extends $cL {
  constructor() {
    super(...arguments);
    this.f = this.B(new $ze());
    this.g = this.B(new $ze());
    this.j = this.B(new $ze());
    this.n = this.B(new $ze());
    this.onDidChangeDirty = this.f.event;
    this.onDidChangeLabel = this.g.event;
    this.onDidChangeCapabilities = this.j.event;
    this.onWillDispose = this.n.event;
  }
  /**
   * Identifies the type of editor this input represents
   * This ID is registered with the {@link EditorResolverService} to allow
   * for resolving an untyped input to a typed one
   */
  get editorId() {
    return void 0;
  }
  /**
   * The capabilities of the input.
   */
  get capabilities() {
    return 2;
  }
  /**
   * Figure out if the input has the provided capability.
   */
  hasCapability(capability) {
    if (capability === 0) {
      return this.capabilities === 0;
    }
    return (this.capabilities & capability) !== 0;
  }
  isReadonly() {
    return this.hasCapability(
      2
      /* EditorInputCapabilities.Readonly */
    );
  }
  /**
   * Returns the display name of this input.
   */
  getName() {
    return `Editor ${this.typeId}`;
  }
  /**
   * Returns the display description of this input.
   */
  getDescription(verbosity) {
    return void 0;
  }
  /**
   * Returns the display title of this input.
   */
  getTitle(verbosity) {
    return this.getName();
  }
  /**
   * Returns the extra classes to apply to the label of this input.
   */
  getLabelExtraClasses() {
    return [];
  }
  /**
   * Returns the aria label to be read out by a screen reader.
   */
  getAriaLabel() {
    return this.getTitle(
      0
      /* Verbosity.SHORT */
    );
  }
  /**
   * Returns the icon which represents this editor input.
   * If undefined, the default icon will be used.
   */
  getIcon() {
    return void 0;
  }
  /**
   * Returns a descriptor suitable for telemetry events.
   *
   * Subclasses should extend if they can contribute.
   */
  getTelemetryDescriptor() {
    return { typeId: this.typeId };
  }
  /**
   * Returns if this input is dirty or not.
   */
  isDirty() {
    return false;
  }
  /**
   * Returns if the input has unsaved changes.
   */
  isModified() {
    return this.isDirty();
  }
  /**
   * Returns if this input is currently being saved or soon to be
   * saved. Based on this assumption the editor may for example
   * decide to not signal the dirty state to the user assuming that
   * the save is scheduled to happen anyway.
   */
  isSaving() {
    return false;
  }
  /**
   * Returns a type of `IDisposable` that represents the resolved input.
   * Subclasses should override to provide a meaningful model or return
   * `null` if the editor does not require a model.
   *
   * The `options` parameter are passed down from the editor when the
   * input is resolved as part of it.
   */
  async resolve() {
    return null;
  }
  /**
   * Saves the editor. The provided groupId helps implementors
   * to e.g. preserve view state of the editor and re-open it
   * in the correct group after saving.
   *
   * @returns the resulting editor input (typically the same) of
   * this operation or `undefined` to indicate that the operation
   * failed or was canceled.
   */
  async save(group2, options3) {
    return this;
  }
  /**
   * Saves the editor to a different location. The provided `group`
   * helps implementors to e.g. preserve view state of the editor
   * and re-open it in the correct group after saving.
   *
   * @returns the resulting editor input (typically a different one)
   * of this operation or `undefined` to indicate that the operation
   * failed or was canceled.
   */
  async saveAs(group2, options3) {
    return this;
  }
  /**
   * Reverts this input from the provided group.
   */
  async revert(group2, options3) {
  }
  /**
   * Called to determine how to handle a resource that is renamed that matches
   * the editors resource (or is a child of).
   *
   * Implementors are free to not implement this method to signal no intent
   * to participate. If an editor is returned though, it will replace the
   * current one with that editor and optional options.
   */
  async rename(group2, target) {
    return void 0;
  }
  /**
   * Returns a copy of the current editor input. Used when we can't just reuse the input
   */
  copy() {
    return this;
  }
  /**
   * Indicates if this editor can be moved to another group. By default
   * editors can freely be moved around groups. If an editor cannot be
   * moved, a message should be returned to show to the user.
   *
   * @returns `true` if the editor can be moved to the target group, or
   * a string with a message to show to the user if the editor cannot be
   * moved.
   */
  canMove(sourceGroup, targetGroup) {
    return true;
  }
  /**
   * Returns if the other object matches this input.
   */
  matches(otherInput) {
    if ($dL(otherInput)) {
      return this === otherInput;
    }
    const otherInputEditorId = otherInput.options?.override;
    if (this.editorId !== otherInputEditorId && otherInputEditorId !== void 0 && this.editorId !== void 0) {
      return false;
    }
    return $oh(this.resource, $mL.getCanonicalUri(otherInput));
  }
  /**
   * If a editor was registered onto multiple editor panes, this method
   * will be asked to return the preferred one to use.
   *
   * @param editorPanes a list of editor pane descriptors that are candidates
   * for the editor to open in.
   */
  prefersEditorPane(editorPanes) {
    return editorPanes.at(0);
  }
  /**
   * Returns a representation of this typed editor input as untyped
   * resource editor input that e.g. can be used to serialize the
   * editor input into a form that it can be restored.
   *
   * May return `undefined` if an untyped representation is not supported.
   */
  toUntyped(options3) {
    return void 0;
  }
  /**
   * Returns if this editor is disposed.
   */
  isDisposed() {
    return this.q.isDisposed;
  }
  dispose() {
    if (!this.isDisposed()) {
      this.n.fire();
    }
    super.dispose();
  }
};

// out-build/vs/workbench/common/resources.js
var $2J_1;
var $2J = class $2J2 extends $3c {
  static {
    $2J_1 = this;
  }
  static {
    this.a = null;
  }
  constructor(g, h3, j, m) {
    super();
    this.g = g;
    this.h = h3;
    this.j = j;
    this.m = m;
    this.b = this.B(new $ze());
    this.onExpressionChange = this.b.event;
    this.c = /* @__PURE__ */ new Map();
    this.f = /* @__PURE__ */ new Map();
    this.r(false);
    this.n();
  }
  n() {
    this.B(this.m.onDidChangeConfiguration((e) => {
      if (this.h(e)) {
        this.r(true);
      }
    }));
    this.B(this.j.onDidChangeWorkspaceFolders(() => this.r(true)));
  }
  r(fromEvent) {
    let changed = false;
    for (const folder of this.j.getWorkspace().folders) {
      const folderUriStr = folder.uri.toString();
      const newExpression = this.s(folder.uri);
      const currentExpression = this.f.get(folderUriStr);
      if (newExpression) {
        if (!currentExpression || !$Pv(currentExpression.expression, newExpression.expression)) {
          changed = true;
          this.c.set(folderUriStr, $Dl(newExpression.expression));
          this.f.set(folderUriStr, newExpression);
        }
      } else {
        if (currentExpression) {
          changed = true;
          this.c.delete(folderUriStr);
          this.f.delete(folderUriStr);
        }
      }
    }
    const foldersMap = new $Fc(this.j.getWorkspace().folders.map((folder) => folder.uri));
    for (const [folder] of this.f) {
      if (folder === $2J_1.a) {
        continue;
      }
      if (!foldersMap.has(URI.parse(folder))) {
        this.c.delete(folder);
        this.f.delete(folder);
        changed = true;
      }
    }
    const globalNewExpression = this.s(void 0);
    const globalCurrentExpression = this.f.get($2J_1.a);
    if (globalNewExpression) {
      if (!globalCurrentExpression || !$Pv(globalCurrentExpression.expression, globalNewExpression.expression)) {
        changed = true;
        this.c.set($2J_1.a, $Dl(globalNewExpression.expression));
        this.f.set($2J_1.a, globalNewExpression);
      }
    } else {
      if (globalCurrentExpression) {
        changed = true;
        this.c.delete($2J_1.a);
        this.f.delete($2J_1.a);
      }
    }
    if (fromEvent && changed) {
      this.b.fire();
    }
  }
  s(resource) {
    const expression = this.g(resource);
    if (!expression) {
      return void 0;
    }
    const keys = Object.keys(expression);
    if (keys.length === 0) {
      return void 0;
    }
    let hasAbsolutePath = false;
    const massagedExpression = /* @__PURE__ */ Object.create(null);
    for (const key2 of keys) {
      if (!hasAbsolutePath) {
        hasAbsolutePath = $mc(key2);
      }
      let massagedKey = key2;
      const driveLetter = $6g(
        massagedKey,
        true
        /* probe for windows */
      );
      if (driveLetter) {
        const driveLetterLower = driveLetter.toLowerCase();
        if (driveLetter !== driveLetter.toLowerCase()) {
          massagedKey = `${driveLetterLower}${massagedKey.substring(1)}`;
        }
      }
      massagedExpression[massagedKey] = expression[key2];
    }
    return {
      expression: massagedExpression,
      hasAbsolutePath
    };
  }
  matches(resource, hasSibling) {
    if (this.c.size === 0) {
      return false;
    }
    const folder = this.j.getWorkspaceFolder(resource);
    let expressionForFolder;
    let expressionConfigForFolder;
    if (folder && this.c.has(folder.uri.toString())) {
      expressionForFolder = this.c.get(folder.uri.toString());
      expressionConfigForFolder = this.f.get(folder.uri.toString());
    } else {
      expressionForFolder = this.c.get($2J_1.a);
      expressionConfigForFolder = this.f.get($2J_1.a);
    }
    if (!expressionForFolder) {
      return false;
    }
    let resourcePathToMatch;
    if (folder) {
      resourcePathToMatch = $xh(folder.uri, resource);
    } else {
      resourcePathToMatch = this.t(resource);
    }
    if (typeof resourcePathToMatch === "string" && !!expressionForFolder(resourcePathToMatch, void 0, hasSibling)) {
      return true;
    }
    if (resourcePathToMatch !== this.t(resource) && expressionConfigForFolder?.hasAbsolutePath) {
      return !!expressionForFolder(this.t(resource), void 0, hasSibling);
    }
    return false;
  }
  t(uri) {
    if (uri.scheme === Schemas.file) {
      return uri.fsPath;
    }
    return uri.path;
  }
};
$2J = $2J_1 = __decorate([
  __param(2, $Zk),
  __param(3, $kl)
], $2J);

// out-build/vs/workbench/services/filesConfiguration/common/filesConfigurationService.js
var $5J_1;
var $3J = new $nn("autoSaveAfterShortDelayContext", false, true);
var AutoSaveMode;
(function(AutoSaveMode2) {
  AutoSaveMode2[AutoSaveMode2["OFF"] = 0] = "OFF";
  AutoSaveMode2[AutoSaveMode2["AFTER_SHORT_DELAY"] = 1] = "AFTER_SHORT_DELAY";
  AutoSaveMode2[AutoSaveMode2["AFTER_LONG_DELAY"] = 2] = "AFTER_LONG_DELAY";
  AutoSaveMode2[AutoSaveMode2["ON_FOCUS_CHANGE"] = 3] = "ON_FOCUS_CHANGE";
  AutoSaveMode2[AutoSaveMode2["ON_WINDOW_CHANGE"] = 4] = "ON_WINDOW_CHANGE";
})(AutoSaveMode || (AutoSaveMode = {}));
var AutoSaveDisabledReason;
(function(AutoSaveDisabledReason2) {
  AutoSaveDisabledReason2[AutoSaveDisabledReason2["SETTINGS"] = 1] = "SETTINGS";
  AutoSaveDisabledReason2[AutoSaveDisabledReason2["OUT_OF_WORKSPACE"] = 2] = "OUT_OF_WORKSPACE";
  AutoSaveDisabledReason2[AutoSaveDisabledReason2["ERRORS"] = 3] = "ERRORS";
  AutoSaveDisabledReason2[AutoSaveDisabledReason2["DISABLED"] = 4] = "DISABLED";
})(AutoSaveDisabledReason || (AutoSaveDisabledReason = {}));
var $4J = $Qk("filesConfigurationService");
var $5J = class $5J2 extends $3c {
  static {
    $5J_1 = this;
  }
  static {
    this.a = $r ? $Im.AFTER_DELAY : $Im.OFF;
  }
  static {
    this.b = 1e3;
  }
  static {
    this.f = {
      providerReadonly: { value: localize(12921, null), isTrusted: true },
      sessionReadonly: { value: localize(12922, null, "workbench.action.files.setActiveEditorWriteableInSession"), isTrusted: true },
      configuredReadonly: { value: localize(12923, null, `workbench.action.openSettings?${encodeURIComponent('["files.readonly"]')}`, "workbench.action.files.toggleActiveEditorReadonlyInSession"), isTrusted: true },
      fileLocked: { value: localize(12924, null, "workbench.action.files.setActiveEditorWriteableInSession"), isTrusted: true },
      fileReadonly: { value: localize(12925, null), isTrusted: true }
    };
  }
  constructor(F, G, H, I, J, L, M, N) {
    super();
    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.g = this.B(new $ze());
    this.onDidChangeAutoSaveConfiguration = this.g.event;
    this.h = this.B(new $ze());
    this.onDidChangeAutoSaveDisabled = this.h.event;
    this.j = this.B(new $ze());
    this.onDidChangeFilesAssociation = this.j.event;
    this.m = this.B(new $ze());
    this.onDidChangeReadonly = this.m.event;
    this.t = new $Hc(1e3);
    this.u = new $Ec();
    this.w = $3J.bindTo(this.F);
    this.y = this.B(new $ci(() => this.O($Mm)));
    this.z = this.B(new $ci(() => this.O($Nm)));
    this.D = new $Ec((resource) => this.J.extUri.getComparisonKey(resource));
    const configuration2 = G.getValue();
    this.n = this.R(void 0, configuration2.files);
    this.r = configuration2?.files?.associations;
    this.s = configuration2?.files?.hotExit || $Jm.ON_EXIT;
    this.Q(configuration2, false);
    this.P();
  }
  O(config) {
    const matcher = this.B(new $2J((resource) => this.G.getValue(config, { resource }), (event) => event.affectsConfiguration(config), this.H, this.G));
    this.B(matcher.onExpressionChange(() => this.m.fire()));
    return matcher;
  }
  isReadonly(resource, stat) {
    const provider = this.L.getProvider(resource.scheme);
    if (provider && $vm(provider)) {
      return provider.readOnlyMessage ?? $5J_1.f.providerReadonly;
    }
    const sessionReadonlyOverride = this.D.get(resource);
    if (typeof sessionReadonlyOverride === "boolean") {
      return sessionReadonlyOverride === true ? $5J_1.f.sessionReadonly : false;
    }
    if (this.J.extUri.isEqualOrParent(resource, this.I.userRoamingDataHome) || this.J.extUri.isEqual(resource, this.H.getWorkspace().configuration ?? void 0)) {
      return false;
    }
    if (this.y.value.matches(resource)) {
      return !this.z.value.matches(resource) ? $5J_1.f.configuredReadonly : false;
    }
    if (this.C && stat?.locked) {
      return $5J_1.f.fileLocked;
    }
    if (stat?.readonly) {
      return $5J_1.f.fileReadonly;
    }
    return false;
  }
  async updateReadonly(resource, readonly) {
    if (readonly === "toggle") {
      let stat = void 0;
      try {
        stat = await this.L.resolve(resource, { resolveMetadata: true });
      } catch (error) {
      }
      readonly = !this.isReadonly(resource, stat);
    }
    if (readonly === "reset") {
      this.D.delete(resource);
    } else {
      this.D.set(resource, readonly);
    }
    this.m.fire();
  }
  P() {
    this.B(this.G.onDidChangeConfiguration((e) => {
      if (e.affectsConfiguration("files")) {
        this.Q(this.G.getValue(), true);
      }
    }));
  }
  Q(configuration2, fromEvent) {
    this.n = this.R(void 0, configuration2.files);
    this.t.clear();
    this.w.set(
      this.getAutoSaveMode(void 0).mode === 1
      /* AutoSaveMode.AFTER_SHORT_DELAY */
    );
    if (fromEvent) {
      this.g.fire();
    }
    const filesAssociation = configuration2?.files?.associations;
    if (!$Pv(this.r, filesAssociation)) {
      this.r = filesAssociation;
      if (fromEvent) {
        this.j.fire();
      }
    }
    const hotExitMode = configuration2?.files?.hotExit;
    if (hotExitMode === $Jm.OFF || hotExitMode === $Jm.ON_EXIT_AND_WINDOW_CLOSE) {
      this.s = hotExitMode;
    } else {
      this.s = $Jm.ON_EXIT;
    }
    const readonlyFromPermissions = Boolean(configuration2?.files?.readonlyFromPermissions);
    if (readonlyFromPermissions !== Boolean(this.C)) {
      this.C = readonlyFromPermissions;
      if (fromEvent) {
        this.m.fire();
      }
    }
  }
  getAutoSaveConfiguration(resourceOrEditor) {
    const resource = this.S(resourceOrEditor);
    if (resource) {
      let resourceAutoSaveConfiguration = this.t.get(resource);
      if (!resourceAutoSaveConfiguration) {
        resourceAutoSaveConfiguration = this.R(resource, this.N.getValue(resource, "files"));
        this.t.set(resource, resourceAutoSaveConfiguration);
      }
      return resourceAutoSaveConfiguration;
    }
    return this.n;
  }
  R(resource, filesConfiguration) {
    let autoSave;
    let autoSaveDelay;
    let autoSaveWorkspaceFilesOnly;
    let autoSaveWhenNoErrors;
    let isOutOfWorkspace;
    let isShortAutoSaveDelay;
    switch (filesConfiguration?.autoSave ?? $5J_1.a) {
      case $Im.AFTER_DELAY: {
        autoSave = "afterDelay";
        autoSaveDelay = typeof filesConfiguration?.autoSaveDelay === "number" && filesConfiguration.autoSaveDelay >= 0 ? filesConfiguration.autoSaveDelay : $5J_1.b;
        isShortAutoSaveDelay = autoSaveDelay <= $5J_1.b;
        break;
      }
      case $Im.ON_FOCUS_CHANGE:
        autoSave = "onFocusChange";
        break;
      case $Im.ON_WINDOW_CHANGE:
        autoSave = "onWindowChange";
        break;
    }
    if (filesConfiguration?.autoSaveWorkspaceFilesOnly === true) {
      autoSaveWorkspaceFilesOnly = true;
      if (resource && !this.H.isInsideWorkspace(resource)) {
        isOutOfWorkspace = true;
        isShortAutoSaveDelay = void 0;
      }
    }
    if (filesConfiguration?.autoSaveWhenNoErrors === true) {
      autoSaveWhenNoErrors = true;
      isShortAutoSaveDelay = void 0;
    }
    return {
      autoSave,
      autoSaveDelay,
      autoSaveWorkspaceFilesOnly,
      autoSaveWhenNoErrors,
      isOutOfWorkspace,
      isShortAutoSaveDelay
    };
  }
  S(resourceOrEditor) {
    if (resourceOrEditor instanceof $nG) {
      return $mL.getOriginalUri(resourceOrEditor, { supportSideBySide: SideBySideEditor.PRIMARY });
    }
    return resourceOrEditor;
  }
  hasShortAutoSaveDelay(resourceOrEditor) {
    const resource = this.S(resourceOrEditor);
    if (this.getAutoSaveConfiguration(resource).isShortAutoSaveDelay) {
      return !resource || !this.u.has(resource);
    }
    return false;
  }
  getAutoSaveMode(resourceOrEditor, saveReason) {
    const resource = this.S(resourceOrEditor);
    if (resource && this.u.has(resource)) {
      return {
        mode: 0,
        reason: 4
        /* AutoSaveDisabledReason.DISABLED */
      };
    }
    const autoSaveConfiguration = this.getAutoSaveConfiguration(resource);
    if (typeof autoSaveConfiguration.autoSave === "undefined") {
      return {
        mode: 0,
        reason: 1
        /* AutoSaveDisabledReason.SETTINGS */
      };
    }
    if (typeof saveReason === "number") {
      if (autoSaveConfiguration.autoSave === "afterDelay" && saveReason !== 2 || autoSaveConfiguration.autoSave === "onFocusChange" && saveReason !== 3 && saveReason !== 4 || autoSaveConfiguration.autoSave === "onWindowChange" && saveReason !== 4) {
        return {
          mode: 0,
          reason: 1
          /* AutoSaveDisabledReason.SETTINGS */
        };
      }
    }
    if (resource) {
      if (autoSaveConfiguration.autoSaveWorkspaceFilesOnly && autoSaveConfiguration.isOutOfWorkspace) {
        return {
          mode: 0,
          reason: 2
          /* AutoSaveDisabledReason.OUT_OF_WORKSPACE */
        };
      }
      if (autoSaveConfiguration.autoSaveWhenNoErrors && this.M.read({ resource, take: 1, severities: MarkerSeverity.Error }).length > 0) {
        return {
          mode: 0,
          reason: 3
          /* AutoSaveDisabledReason.ERRORS */
        };
      }
    }
    switch (autoSaveConfiguration.autoSave) {
      case "afterDelay":
        if (typeof autoSaveConfiguration.autoSaveDelay === "number" && autoSaveConfiguration.autoSaveDelay <= $5J_1.b) {
          return {
            mode: autoSaveConfiguration.autoSaveWhenNoErrors ? 2 : 1
            /* AutoSaveMode.AFTER_SHORT_DELAY */
          };
        }
        return {
          mode: 2
          /* AutoSaveMode.AFTER_LONG_DELAY */
        };
      case "onFocusChange":
        return {
          mode: 3
          /* AutoSaveMode.ON_FOCUS_CHANGE */
        };
      case "onWindowChange":
        return {
          mode: 4
          /* AutoSaveMode.ON_WINDOW_CHANGE */
        };
    }
  }
  async toggleAutoSave() {
    const currentSetting = this.G.getValue("files.autoSave");
    let newAutoSaveValue;
    if ([$Im.AFTER_DELAY, $Im.ON_FOCUS_CHANGE, $Im.ON_WINDOW_CHANGE].some((setting) => setting === currentSetting)) {
      newAutoSaveValue = $Im.OFF;
    } else {
      newAutoSaveValue = $Im.AFTER_DELAY;
    }
    return this.G.updateValue("files.autoSave", newAutoSaveValue);
  }
  disableAutoSave(resourceOrEditor) {
    const resource = this.S(resourceOrEditor);
    if (!resource) {
      return $3c.None;
    }
    const counter = this.u.get(resource) ?? 0;
    this.u.set(resource, counter + 1);
    if (counter === 0) {
      this.h.fire(resource);
    }
    return $1c(() => {
      const counter2 = this.u.get(resource) ?? 0;
      if (counter2 <= 1) {
        this.u.delete(resource);
        this.h.fire(resource);
      } else {
        this.u.set(resource, counter2 - 1);
      }
    });
  }
  get isHotExitEnabled() {
    if (this.H.getWorkspace().transient) {
      return false;
    }
    return this.s !== $Jm.OFF;
  }
  get hotExitConfiguration() {
    return this.s;
  }
  preventSaveConflicts(resource, language) {
    return this.G.getValue("files.saveConflictResolution", { resource, overrideIdentifier: language }) !== "overwriteFileOnDisk";
  }
};
$5J = $5J_1 = __decorate([
  __param(0, $on),
  __param(1, $kl),
  __param(2, $Zk),
  __param(3, $Xk),
  __param(4, $vl),
  __param(5, $km),
  __param(6, $DE),
  __param(7, $zG)
], $5J);
$SC(
  $4J,
  $5J,
  0
  /* InstantiationType.Eager */
);

// out-build/vs/workbench/services/editor/common/customEditorLabelService.js
var $prb_1;
var $prb = class $prb2 extends $3c {
  static {
    $prb_1 = this;
  }
  static {
    this.SETTING_ID_PATTERNS = "workbench.editor.customLabels.patterns";
  }
  static {
    this.SETTING_ID_ENABLED = "workbench.editor.customLabels.enabled";
  }
  constructor(j, m) {
    super();
    this.j = j;
    this.m = m;
    this.c = this.B(new $ze());
    this.onDidChange = this.c.event;
    this.f = [];
    this.g = true;
    this.h = new $Ic(1e3);
    this.t = /[a-zA-Z0-9]/;
    this.z = /\$\{(dirname|filename|extname|extname\((?<extnameN>[-+]?\d+)\)|dirname\((?<dirnameN>[-+]?\d+)\))\}/g;
    this.C = /(?<filename>^\.*[^.]*)/;
    this.s();
    this.u();
    this.r();
  }
  r() {
    this.B(this.j.onDidChangeConfiguration((e) => {
      if (e.affectsConfiguration($prb_1.SETTING_ID_ENABLED)) {
        const oldEnablement = this.g;
        this.s();
        if (oldEnablement !== this.g && this.f.length > 0) {
          this.c.fire();
        }
      } else if (e.affectsConfiguration($prb_1.SETTING_ID_PATTERNS)) {
        this.h.clear();
        this.u();
        this.c.fire();
      }
    }));
  }
  s() {
    this.g = this.j.getValue($prb_1.SETTING_ID_ENABLED);
  }
  u() {
    this.f = [];
    const customLabelPatterns = this.j.getValue($prb_1.SETTING_ID_PATTERNS);
    for (const pattern in customLabelPatterns) {
      const template = customLabelPatterns[pattern];
      if (!this.t.test(template)) {
        continue;
      }
      const isAbsolutePath = $mc(pattern);
      const parsedPattern = $Dl(pattern);
      this.f.push({ pattern, template, isAbsolutePath, parsedPattern });
    }
    this.f.sort((a, b) => this.w(b.pattern) - this.w(a.pattern));
  }
  w(pattern) {
    let weight5 = 0;
    for (const fragment of pattern.split("/")) {
      if (fragment === "**") {
        weight5 += 1;
      } else if (fragment === "*") {
        weight5 += 10;
      } else if (fragment.includes("*") || fragment.includes("?")) {
        weight5 += 50;
      } else if (fragment !== "") {
        weight5 += 100;
      }
    }
    return weight5;
  }
  getName(resource) {
    if (!this.g || this.f.length === 0) {
      return void 0;
    }
    const key2 = resource.toString();
    const cached = this.h.get(key2);
    if (cached !== void 0) {
      return cached ?? void 0;
    }
    const result = this.y(resource);
    this.h.set(key2, result ?? null);
    return result;
  }
  y(resource) {
    const root = this.m.getWorkspaceFolder(resource);
    let relativePath;
    for (const pattern of this.f) {
      let relevantPath;
      if (root && !pattern.isAbsolutePath) {
        if (!relativePath) {
          relativePath = $xh($uh(root.uri), resource) ?? resource.path;
        }
        relevantPath = relativePath;
      } else {
        relevantPath = resource.path;
      }
      if (pattern.parsedPattern(relevantPath)) {
        return this.D(pattern.template, resource, relevantPath);
      }
    }
    return void 0;
  }
  D(template, resource, relevantPath) {
    let parsedPath;
    return template.replace(this.z, (match, variable, ...args2) => {
      parsedPath = parsedPath ?? $uc(resource.path);
      const { dirnameN = "0", extnameN = "0" } = args2.pop();
      if (variable === "filename") {
        const { filename } = this.C.exec(parsedPath.base)?.groups ?? {};
        if (filename) {
          return filename;
        }
      } else if (variable === "extname") {
        const extension = this.H(parsedPath.base);
        if (extension) {
          return extension;
        }
      } else if (variable.startsWith("extname")) {
        const n = parseInt(extnameN);
        const nthExtname = this.I(parsedPath.base, n);
        if (nthExtname) {
          return nthExtname;
        }
      } else if (variable.startsWith("dirname")) {
        const n = parseInt(dirnameN);
        const nthDir = this.G($qc(relevantPath), n);
        if (nthDir) {
          return nthDir;
        }
      }
      return match;
    });
  }
  F(path) {
    let withoutLeadingDot = path;
    while (withoutLeadingDot.startsWith(".")) {
      withoutLeadingDot = withoutLeadingDot.slice(1);
    }
    return withoutLeadingDot;
  }
  G(path, n) {
    path = path.startsWith("/") ? path.slice(1) : path;
    const pathFragments = path.split("/");
    return this.J(pathFragments, n);
  }
  H(fullFileName) {
    return this.F(fullFileName).split(".").slice(1).join(".");
  }
  I(fullFileName, n) {
    const extensionNameFragments = this.F(fullFileName).split(".");
    extensionNameFragments.shift();
    return this.J(extensionNameFragments, n);
  }
  J(fragments, n) {
    const length = fragments.length;
    let nth;
    if (n < 0) {
      nth = Math.abs(n) - 1;
    } else {
      nth = length - n - 1;
    }
    const nthFragment = fragments[nth];
    if (nthFragment === void 0 || nthFragment === "") {
      return void 0;
    }
    return nthFragment;
  }
};
$prb = $prb_1 = __decorate([
  __param(0, $kl),
  __param(1, $Zk)
], $prb);
var $qrb = $Qk("ICustomEditorLabelService");
$SC(
  $qrb,
  $prb,
  1
  /* InstantiationType.Delayed */
);

// out-build/vs/workbench/common/editor/resourceEditorInput.js
var $rrb = class $rrb2 extends $nG {
  get capabilities() {
    let capabilities = 32;
    if (this.h.hasProvider(this.resource)) {
      if (this.m.isReadonly(this.resource)) {
        capabilities |= 2;
      }
    } else {
      capabilities |= 4;
    }
    if (!(capabilities & 2)) {
      capabilities |= 128;
    }
    return capabilities;
  }
  get preferredResource() {
    return this.a;
  }
  constructor(resource, preferredResource, b, h3, m, r2, s) {
    super();
    this.resource = resource;
    this.b = b;
    this.h = h3;
    this.m = m;
    this.r = r2;
    this.s = s;
    this.y = void 0;
    this.z = void 0;
    this.D = void 0;
    this.G = void 0;
    this.I = void 0;
    this.L = void 0;
    this.N = void 0;
    this.a = preferredResource || resource;
    this.t();
  }
  t() {
    this.B(this.b.onDidChangeFormatters((e) => this.u(e.scheme)));
    this.B(this.h.onDidChangeFileSystemProviderRegistrations((e) => this.u(e.scheme)));
    this.B(this.h.onDidChangeFileSystemProviderCapabilities((e) => this.u(e.scheme)));
    this.B(this.s.onDidChange(() => this.w()));
  }
  u(scheme) {
    if (scheme === this.a.scheme) {
      this.w();
    }
  }
  w() {
    this.y = void 0;
    this.z = void 0;
    this.D = void 0;
    this.G = void 0;
    this.I = void 0;
    this.L = void 0;
    this.N = void 0;
    this.g.fire();
  }
  setPreferredResource(preferredResource) {
    if (!$oh(preferredResource, this.a)) {
      this.a = preferredResource;
      this.w();
    }
  }
  getName() {
    if (typeof this.y !== "string") {
      this.y = this.s.getName(this.a) ?? this.b.getUriBasenameLabel(this.a);
    }
    return this.y;
  }
  getDescription(verbosity = 1) {
    switch (verbosity) {
      case 0:
        return this.C;
      case 2:
        return this.H;
      case 1:
      default:
        return this.F;
    }
  }
  get C() {
    if (typeof this.z !== "string") {
      this.z = this.b.getUriBasenameLabel($uh(this.a));
    }
    return this.z;
  }
  get F() {
    if (typeof this.D !== "string") {
      this.D = this.b.getUriLabel($uh(this.a), { relative: true });
    }
    return this.D;
  }
  get H() {
    if (typeof this.G !== "string") {
      this.G = this.b.getUriLabel($uh(this.a));
    }
    return this.G;
  }
  get J() {
    if (typeof this.I !== "string") {
      this.I = this.getName();
    }
    return this.I;
  }
  get M() {
    if (typeof this.L !== "string") {
      this.L = this.b.getUriLabel(this.a, { relative: true });
    }
    return this.L;
  }
  get O() {
    if (typeof this.N !== "string") {
      this.N = this.b.getUriLabel(this.a);
    }
    return this.N;
  }
  getTitle(verbosity) {
    switch (verbosity) {
      case 0:
        return this.J;
      case 2:
        return this.O;
      default:
      case 1:
        return this.M;
    }
  }
  isReadonly() {
    return this.m.isReadonly(this.resource);
  }
  P(options3) {
    if (options3?.limits) {
      return options3.limits;
    }
    const defaultSizeLimit = $Tm(this.resource);
    let configuredSizeLimit = void 0;
    const configuredSizeLimitMb = this.r.inspect(this.resource, null, "workbench.editorLargeFileConfirmation");
    if ($ol(configuredSizeLimitMb)) {
      configuredSizeLimit = configuredSizeLimitMb.value * $Sm.MB;
    }
    return {
      size: configuredSizeLimit ?? defaultSizeLimit
    };
  }
};
$rrb = __decorate([
  __param(2, $ZI),
  __param(3, $km),
  __param(4, $4J),
  __param(5, $zG),
  __param(6, $qrb)
], $rrb);

// out-build/vs/workbench/services/editor/common/editorGroupsService.js
var $iJ = $Qk("editorGroupsService");
var GroupDirection;
(function(GroupDirection2) {
  GroupDirection2[GroupDirection2["UP"] = 0] = "UP";
  GroupDirection2[GroupDirection2["DOWN"] = 1] = "DOWN";
  GroupDirection2[GroupDirection2["LEFT"] = 2] = "LEFT";
  GroupDirection2[GroupDirection2["RIGHT"] = 3] = "RIGHT";
})(GroupDirection || (GroupDirection = {}));
var GroupOrientation;
(function(GroupOrientation2) {
  GroupOrientation2[GroupOrientation2["HORIZONTAL"] = 0] = "HORIZONTAL";
  GroupOrientation2[GroupOrientation2["VERTICAL"] = 1] = "VERTICAL";
})(GroupOrientation || (GroupOrientation = {}));
var GroupLocation;
(function(GroupLocation2) {
  GroupLocation2[GroupLocation2["FIRST"] = 0] = "FIRST";
  GroupLocation2[GroupLocation2["LAST"] = 1] = "LAST";
  GroupLocation2[GroupLocation2["NEXT"] = 2] = "NEXT";
  GroupLocation2[GroupLocation2["PREVIOUS"] = 3] = "PREVIOUS";
})(GroupLocation || (GroupLocation = {}));
var GroupsArrangement;
(function(GroupsArrangement2) {
  GroupsArrangement2[GroupsArrangement2["MAXIMIZE"] = 0] = "MAXIMIZE";
  GroupsArrangement2[GroupsArrangement2["EXPAND"] = 1] = "EXPAND";
  GroupsArrangement2[GroupsArrangement2["EVEN"] = 2] = "EVEN";
})(GroupsArrangement || (GroupsArrangement = {}));
var MergeGroupMode;
(function(MergeGroupMode2) {
  MergeGroupMode2[MergeGroupMode2["COPY_EDITORS"] = 0] = "COPY_EDITORS";
  MergeGroupMode2[MergeGroupMode2["MOVE_EDITORS"] = 1] = "MOVE_EDITORS";
})(MergeGroupMode || (MergeGroupMode = {}));
function $jJ(replacement) {
  const candidate = replacement;
  return $dL(candidate?.editor) && $dL(candidate?.replacement);
}
var GroupsOrder;
(function(GroupsOrder2) {
  GroupsOrder2[GroupsOrder2["CREATION_TIME"] = 0] = "CREATION_TIME";
  GroupsOrder2[GroupsOrder2["MOST_RECENTLY_ACTIVE"] = 1] = "MOST_RECENTLY_ACTIVE";
  GroupsOrder2[GroupsOrder2["GRID_APPEARANCE"] = 2] = "GRID_APPEARANCE";
})(GroupsOrder || (GroupsOrder = {}));
var OpenEditorContext;
(function(OpenEditorContext2) {
  OpenEditorContext2[OpenEditorContext2["NEW_EDITOR"] = 1] = "NEW_EDITOR";
  OpenEditorContext2[OpenEditorContext2["MOVE_EDITOR"] = 2] = "MOVE_EDITOR";
  OpenEditorContext2[OpenEditorContext2["COPY_EDITOR"] = 3] = "COPY_EDITOR";
})(OpenEditorContext || (OpenEditorContext = {}));
function $kJ(obj) {
  const group2 = obj;
  return !!group2 && typeof group2.id === "number" && Array.isArray(group2.editors);
}
function $lJ(configurationService) {
  const openSideBySideDirection = configurationService.getValue("workbench.editor.openSideBySideDirection");
  if (openSideBySideDirection === "down") {
    return 1;
  }
  return 3;
}

// out-build/vs/workbench/services/editor/common/editorService.js
var $mJ = $Qk("editorService");
var $nJ = -1;
var $oJ = -2;
var $pJ = -3;
function $qJ(obj) {
  const candidate = obj;
  return typeof obj === "number" || $kJ(candidate);
}

// out-build/vs/workbench/contrib/notebook/common/notebookEditorInput.js
var $trb_1;
var $trb = class $trb2 extends $rrb {
  static {
    $trb_1 = this;
  }
  static getOrCreate(instantiationService, resource, preferredResource, viewType, options3 = {}) {
    const editor = instantiationService.createInstance($trb_1, resource, preferredResource, viewType, options3);
    if (preferredResource) {
      editor.setPreferredResource(preferredResource);
    }
    return editor;
  }
  static {
    this.ID = "workbench.input.notebook";
  }
  constructor(resource, preferredResource, viewType, options3, S, U, W, labelService, fileService, filesConfigurationService, extensionService, editorService, textResourceConfigurationService, customEditorLabelService) {
    super(resource, preferredResource, labelService, fileService, filesConfigurationService, textResourceConfigurationService, customEditorLabelService);
    this.viewType = viewType;
    this.options = options3;
    this.S = S;
    this.U = U;
    this.W = W;
    this.c = null;
    this.R = false;
    this.R = !!options3.startDirty;
    this.Q = S.onDidAddNotebookDocument((e) => {
      if (e.viewType === this.viewType && e.uri.toString() === this.resource.toString()) {
        this.resolve().catch($gb);
      }
    });
    this.B(extensionService.onWillStop((e) => {
      if (!e.auto && !this.isDirty()) {
        return;
      }
      const reason = e.auto ? localize(8627, null) : localize(8628, null, this.resource.path);
      e.veto((async () => {
        const editors = editorService.findEditors(this);
        if (e.auto) {
          return true;
        }
        if (editors.length > 0) {
          const result = await editorService.save(editors[0]);
          if (result.success) {
            return false;
          }
        }
        return true;
      })(), reason);
    }));
  }
  dispose() {
    this.Q.dispose();
    this.c?.dispose();
    this.c = null;
    super.dispose();
  }
  get typeId() {
    return $trb_1.ID;
  }
  get editorId() {
    return this.viewType;
  }
  get capabilities() {
    let capabilities = 0;
    if (this.resource.scheme === Schemas.untitled) {
      capabilities |= 4;
    }
    if (this.c) {
      if (this.c.object.isReadonly()) {
        capabilities |= 2;
      }
    } else {
      if (this.m.isReadonly(this.resource)) {
        capabilities |= 2;
      }
    }
    if (!(capabilities & 2)) {
      capabilities |= 128;
    }
    return capabilities;
  }
  getDescription(verbosity = 1) {
    if (!this.hasCapability(
      4
      /* EditorInputCapabilities.Untitled */
    ) || this.c?.object.hasAssociatedFilePath()) {
      return super.getDescription(verbosity);
    }
    return void 0;
  }
  isReadonly() {
    if (!this.c) {
      return this.m.isReadonly(this.resource);
    }
    return this.c.object.isReadonly();
  }
  isDirty() {
    if (!this.c) {
      return this.R;
    }
    return this.c.object.isDirty();
  }
  isSaving() {
    const model = this.c?.object;
    if (!model || !model.isDirty() || model.hasErrorState || this.hasCapability(
      4
      /* EditorInputCapabilities.Untitled */
    )) {
      return false;
    }
    return this.m.hasShortAutoSaveDelay(this);
  }
  async save(group2, options3) {
    if (this.c) {
      if (this.hasCapability(
        4
        /* EditorInputCapabilities.Untitled */
      )) {
        return this.saveAs(group2, options3);
      } else {
        await this.c.object.save(options3);
      }
      return this;
    }
    return void 0;
  }
  async saveAs(group2, options3) {
    if (!this.c) {
      return void 0;
    }
    const provider = this.S.getContributedNotebookType(this.viewType);
    if (!provider) {
      return void 0;
    }
    const pathCandidate = this.hasCapability(
      4
      /* EditorInputCapabilities.Untitled */
    ) ? await this.X(provider, this.b.getUriBasenameLabel(this.resource)) : this.c.object.resource;
    let target;
    if (this.c.object.hasAssociatedFilePath()) {
      target = pathCandidate;
    } else {
      target = await this.W.pickFileToSave(pathCandidate, options3?.availableFileSystems);
      if (!target) {
        return void 0;
      }
    }
    if (!provider.matches(target)) {
      const patterns = provider.selectors.map((pattern) => {
        if (typeof pattern === "string") {
          return pattern;
        }
        if ($El(pattern)) {
          return `${pattern} (base ${pattern.base})`;
        }
        if (pattern.exclude) {
          return `${pattern.include} (exclude: ${pattern.exclude})`;
        } else {
          return `${pattern.include}`;
        }
      }).join(", ");
      throw new Error(`File name ${target} is not supported by ${provider.providerDisplayName}.

Please make sure the file name matches following patterns:
${patterns}`);
    }
    return await this.c.object.saveAs(target);
  }
  async X(provider, suggestedFilename) {
    const firstSelector = provider.selectors[0];
    let selectorStr = firstSelector && typeof firstSelector === "string" ? firstSelector : void 0;
    if (!selectorStr && firstSelector) {
      const include = firstSelector.include;
      if (typeof include === "string") {
        selectorStr = include;
      }
    }
    if (selectorStr) {
      const matches = /^\*\.([A-Za-z_-]*)$/.exec(selectorStr);
      if (matches && matches.length > 1) {
        const fileExt = matches[1];
        if (!suggestedFilename.endsWith(fileExt)) {
          return $vh(await this.W.defaultFilePath(), suggestedFilename + "." + fileExt);
        }
      }
    }
    return $vh(await this.W.defaultFilePath(), suggestedFilename);
  }
  // called when users rename a notebook document
  async rename(group2, target) {
    if (this.c) {
      return { editor: { resource: target }, options: { override: this.viewType } };
    }
    return void 0;
  }
  async revert(_group, options3) {
    if (this.c && this.c.object.isDirty()) {
      await this.c.object.revert(options3);
    }
  }
  async resolve(_options, perf2) {
    if (!await this.S.canResolve(this.viewType)) {
      return null;
    }
    perf2?.mark("extensionActivated");
    this.Q.dispose();
    if (!this.c) {
      const scratchpad = this.capabilities & 512 ? true : false;
      const ref = await this.U.resolve(this.resource, this.viewType, { limits: this.P(_options), scratchpad, viewType: this.editorId });
      if (this.c) {
        ref.dispose();
        return this.c.object;
      }
      this.c = ref;
      if (this.isDisposed()) {
        this.c.dispose();
        this.c = null;
        return null;
      }
      this.B(this.c.object.onDidChangeDirty(() => this.f.fire()));
      this.B(this.c.object.onDidChangeReadonly(() => this.j.fire()));
      this.B(this.c.object.onDidRevertUntitled(() => this.dispose()));
      if (this.c.object.isDirty()) {
        this.f.fire();
      }
    } else {
      this.c.object.load({ limits: this.P(_options) });
    }
    if (this.options._backupId) {
      const info = await this.S.withNotebookDataProvider(this.c.object.notebook.viewType);
      if (!(info instanceof $nrb)) {
        throw new Error("CANNOT open file notebook with this provider");
      }
      const data = await info.serializer.dataToNotebook($Ci.fromString(JSON.stringify({ __webview_backup: this.options._backupId })));
      this.c.object.notebook.applyEdits([
        {
          editType: 1,
          index: 0,
          count: this.c.object.notebook.length,
          cells: data.cells
        }
      ], true, void 0, () => void 0, void 0, false);
      if (this.options._workingCopy) {
        this.options._backupId = void 0;
        this.options._workingCopy = void 0;
        this.options.startDirty = void 0;
      }
    }
    return this.c.object;
  }
  toUntyped() {
    return {
      resource: this.resource,
      options: {
        override: this.viewType
      }
    };
  }
  matches(otherInput) {
    if (super.matches(otherInput)) {
      return true;
    }
    if (otherInput instanceof $trb_1) {
      return this.viewType === otherInput.viewType && $oh(this.resource, otherInput.resource);
    }
    return false;
  }
};
$trb = $trb_1 = __decorate([
  __param(4, $mrb),
  __param(5, $orb),
  __param(6, $1v),
  __param(7, $ZI),
  __param(8, $km),
  __param(9, $4J),
  __param(10, $wN),
  __param(11, $mJ),
  __param(12, $zG),
  __param(13, $qrb)
], $trb);
function $urb(thing) {
  return !!thing && typeof thing === "object" && Array.isArray(thing.editorInputs) && thing.editorInputs.every((input) => input instanceof $trb);
}
function $vrb(thing) {
  return !!thing && typeof thing === "object" && thing.typeId === $trb.ID;
}

// out-build/vs/workbench/contrib/notebook/common/notebookRange.js
function $EL(candidate) {
  if (!candidate || typeof candidate !== "object") {
    return false;
  }
  return typeof candidate.start === "number" && typeof candidate.end === "number";
}
function $FL(indexes) {
  indexes.sort((a, b) => a - b);
  const first = indexes.shift();
  if (first === void 0) {
    return [];
  }
  return indexes.reduce(function(ranges, num) {
    if (num <= ranges[0][1]) {
      ranges[0][1] = num + 1;
    } else {
      ranges.unshift([num, num + 1]);
    }
    return ranges;
  }, [[first, first + 1]]).reverse().map((val) => ({ start: val[0], end: val[1] }));
}
function $GL(ranges) {
  const indexes = ranges.reduce((a, b) => {
    for (let i2 = b.start; i2 < b.end; i2++) {
      a.push(i2);
    }
    return a;
  }, []);
  return indexes;
}
function $HL(ranges) {
  const sorted = ranges.sort((a, b) => a.start - b.start);
  const first = sorted[0];
  if (!first) {
    return [];
  }
  const reduced = sorted.reduce((prev, curr) => {
    const last = prev[prev.length - 1];
    if (last.end >= curr.start) {
      last.end = Math.max(last.end, curr.end);
    } else {
      prev.push(curr);
    }
    return prev;
  }, [first]);
  if (reduced.length > 1) {
    return reduced.filter((range) => !(range.start === range.end && range.start === 0));
  }
  return reduced;
}
function $IL(a, b) {
  a = $HL(a);
  b = $HL(b);
  if (a.length !== b.length) {
    return false;
  }
  for (let i2 = 0; i2 < a.length; i2++) {
    if (a[i2].start !== b[i2].start || a[i2].end !== b[i2].end) {
      return false;
    }
  }
  return true;
}
function $JL(range, other) {
  return other.start >= range.start && other.end <= range.end;
}

// out-build/vs/workbench/contrib/notebook/browser/notebookBrowser.js
var $Grb = "notebook.cell.expandCellInput";
var $Hrb = "notebook.cell.execute";
var $Irb = "notebook.cell.detectLanguage";
var $Jrb = "notebook.cell.changeLanguage";
var $Krb = "notebook.cell.quitEdit";
var $Lrb = "notebook.cell.expandCellOutput";
var $Mrb = "jupyter-notebook";
var $Nrb = "ms-toolsai.jupyter";
var $Orb = /* @__PURE__ */ new Map([
  [$Mrb, $Nrb]
]);
var $Prb = /* @__PURE__ */ new Map();
$Prb.set($Mrb, /* @__PURE__ */ new Map());
$Prb.get($Mrb)?.set("python", {
  extensionIds: [
    "ms-python.python",
    $Nrb
  ],
  displayName: "Python + Jupyter"
});
var RenderOutputType;
(function(RenderOutputType2) {
  RenderOutputType2[RenderOutputType2["Html"] = 0] = "Html";
  RenderOutputType2[RenderOutputType2["Extension"] = 1] = "Extension";
})(RenderOutputType || (RenderOutputType = {}));
var ScrollToRevealBehavior;
(function(ScrollToRevealBehavior2) {
  ScrollToRevealBehavior2[ScrollToRevealBehavior2["fullCell"] = 0] = "fullCell";
  ScrollToRevealBehavior2[ScrollToRevealBehavior2["firstLine"] = 1] = "firstLine";
})(ScrollToRevealBehavior || (ScrollToRevealBehavior = {}));
var CellLayoutState;
(function(CellLayoutState2) {
  CellLayoutState2[CellLayoutState2["Uninitialized"] = 0] = "Uninitialized";
  CellLayoutState2[CellLayoutState2["Estimated"] = 1] = "Estimated";
  CellLayoutState2[CellLayoutState2["FromCache"] = 2] = "FromCache";
  CellLayoutState2[CellLayoutState2["Measured"] = 3] = "Measured";
})(CellLayoutState || (CellLayoutState = {}));
var CellLayoutContext;
(function(CellLayoutContext2) {
  CellLayoutContext2[CellLayoutContext2["Fold"] = 0] = "Fold";
})(CellLayoutContext || (CellLayoutContext = {}));
var NotebookOverviewRulerLane;
(function(NotebookOverviewRulerLane2) {
  NotebookOverviewRulerLane2[NotebookOverviewRulerLane2["Left"] = 1] = "Left";
  NotebookOverviewRulerLane2[NotebookOverviewRulerLane2["Center"] = 2] = "Center";
  NotebookOverviewRulerLane2[NotebookOverviewRulerLane2["Right"] = 4] = "Right";
  NotebookOverviewRulerLane2[NotebookOverviewRulerLane2["Full"] = 7] = "Full";
})(NotebookOverviewRulerLane || (NotebookOverviewRulerLane = {}));
var CellRevealType;
(function(CellRevealType2) {
  CellRevealType2[CellRevealType2["Default"] = 1] = "Default";
  CellRevealType2[CellRevealType2["Top"] = 2] = "Top";
  CellRevealType2[CellRevealType2["Center"] = 3] = "Center";
  CellRevealType2[CellRevealType2["CenterIfOutsideViewport"] = 4] = "CenterIfOutsideViewport";
  CellRevealType2[CellRevealType2["NearTopIfOutsideViewport"] = 5] = "NearTopIfOutsideViewport";
  CellRevealType2[CellRevealType2["FirstLineIfOutsideViewport"] = 6] = "FirstLineIfOutsideViewport";
})(CellRevealType || (CellRevealType = {}));
var CellRevealRangeType;
(function(CellRevealRangeType2) {
  CellRevealRangeType2[CellRevealRangeType2["Default"] = 1] = "Default";
  CellRevealRangeType2[CellRevealRangeType2["Center"] = 2] = "Center";
  CellRevealRangeType2[CellRevealRangeType2["CenterIfOutsideViewport"] = 3] = "CenterIfOutsideViewport";
})(CellRevealRangeType || (CellRevealRangeType = {}));
var CellEditState;
(function(CellEditState2) {
  CellEditState2[CellEditState2["Preview"] = 0] = "Preview";
  CellEditState2[CellEditState2["Editing"] = 1] = "Editing";
})(CellEditState || (CellEditState = {}));
var CellFocusMode;
(function(CellFocusMode2) {
  CellFocusMode2[CellFocusMode2["Container"] = 0] = "Container";
  CellFocusMode2[CellFocusMode2["Editor"] = 1] = "Editor";
  CellFocusMode2[CellFocusMode2["Output"] = 2] = "Output";
  CellFocusMode2[CellFocusMode2["ChatInput"] = 3] = "ChatInput";
})(CellFocusMode || (CellFocusMode = {}));
var CursorAtBoundary;
(function(CursorAtBoundary2) {
  CursorAtBoundary2[CursorAtBoundary2["None"] = 0] = "None";
  CursorAtBoundary2[CursorAtBoundary2["Top"] = 1] = "Top";
  CursorAtBoundary2[CursorAtBoundary2["Bottom"] = 2] = "Bottom";
  CursorAtBoundary2[CursorAtBoundary2["Both"] = 3] = "Both";
})(CursorAtBoundary || (CursorAtBoundary = {}));
var CursorAtLineBoundary;
(function(CursorAtLineBoundary2) {
  CursorAtLineBoundary2[CursorAtLineBoundary2["None"] = 0] = "None";
  CursorAtLineBoundary2[CursorAtLineBoundary2["Start"] = 1] = "Start";
  CursorAtLineBoundary2[CursorAtLineBoundary2["End"] = 2] = "End";
  CursorAtLineBoundary2[CursorAtLineBoundary2["Both"] = 3] = "Both";
})(CursorAtLineBoundary || (CursorAtLineBoundary = {}));
function $Qrb(editorPane) {
  if (!editorPane) {
    return;
  }
  if (editorPane.getId() === $bM) {
    return editorPane.getControl();
  }
  const input = editorPane.input;
  const isCompositeNotebook = input && $urb(input);
  if (isCompositeNotebook) {
    return editorPane.getControl()?.notebookEditor;
  }
  return void 0;
}
function $Rrb(editor, ranges) {
  const indexes = $GL(ranges);
  const modelRanges = [];
  indexes.forEach((index) => {
    const viewCell = editor.cellAt(index);
    if (!viewCell) {
      return;
    }
    const viewIndex = editor.getViewIndexByModelIndex(index);
    if (viewIndex < 0) {
      return;
    }
    const nextViewIndex = viewIndex + 1;
    const range = editor.getCellRangeFromViewRange(viewIndex, nextViewIndex);
    if (range) {
      modelRanges.push(range);
    }
  });
  return $HL(modelRanges);
}
function $Srb(editor, ranges) {
  const cells = [];
  $HL(ranges).forEach((range) => {
    cells.push(...editor.getCellsInRange(range));
  });
  return cells;
}
var CellFoldingState;
(function(CellFoldingState2) {
  CellFoldingState2[CellFoldingState2["None"] = 0] = "None";
  CellFoldingState2[CellFoldingState2["Expanded"] = 1] = "Expanded";
  CellFoldingState2[CellFoldingState2["Collapsed"] = 2] = "Collapsed";
})(CellFoldingState || (CellFoldingState = {}));

// out-build/vs/workbench/contrib/bulkEdit/browser/bulkCellEdits.js
var $Trb = class _$Trb extends $I_ {
  static is(candidate) {
    if (candidate instanceof _$Trb) {
      return true;
    }
    return URI.isUri(candidate.resource) && $Bg(candidate.cellEdit);
  }
  static lift(edit3) {
    if (edit3 instanceof _$Trb) {
      return edit3;
    }
    return new _$Trb(edit3.resource, edit3.cellEdit, edit3.notebookVersionId, edit3.metadata);
  }
  constructor(resource, cellEdit, notebookVersionId = void 0, metadata) {
    super(metadata);
    this.resource = resource;
    this.cellEdit = cellEdit;
    this.notebookVersionId = notebookVersionId;
  }
};
var $Urb = class $Urb2 {
  constructor(c, undoRedoSource, d, f, g, h3, i2) {
    this.c = c;
    this.d = d;
    this.f = f;
    this.g = g;
    this.h = h3;
    this.i = i2;
    this.g = this.g.map((e) => {
      if (e.resource.scheme === CellUri.scheme) {
        const uri = CellUri.parse(e.resource)?.notebook;
        if (!uri) {
          throw new Error(`Invalid notebook URI: ${e.resource}`);
        }
        return new $Trb(uri, e.cellEdit, e.notebookVersionId, e.metadata);
      } else {
        return e;
      }
    });
  }
  async apply() {
    const resources = [];
    const editsByNotebook = $Eb(this.g, (a, b) => $Tf(a.resource.toString(), b.resource.toString()));
    for (const group2 of editsByNotebook) {
      if (this.f.isCancellationRequested) {
        break;
      }
      const [first] = group2;
      const ref = await this.i.resolve(first.resource);
      if (typeof first.notebookVersionId === "number" && ref.object.notebook.versionId !== first.notebookVersionId) {
        ref.dispose();
        throw new Error(`Notebook '${first.resource}' has changed in the meantime`);
      }
      const edits = group2.map((entry) => entry.cellEdit);
      const computeUndo = !ref.object.isReadonly();
      const editor = $Qrb(this.h.activeEditorPane);
      const initialSelectionState = editor?.textModel?.uri.toString() === ref.object.notebook.uri.toString() ? {
        kind: SelectionStateType.Index,
        focus: editor.getFocus(),
        selections: editor.getSelections()
      } : void 0;
      ref.object.notebook.applyEdits(edits, true, initialSelectionState, () => void 0, this.c, computeUndo);
      ref.dispose();
      this.d.report(void 0);
      resources.push(first.resource);
    }
    return resources;
  }
};
$Urb = __decorate([
  __param(5, $mJ),
  __param(6, $orb)
], $Urb);

// out-build/vs/workbench/api/browser/mainThreadBulkEdits.js
var $Vrb = class $Vrb2 {
  constructor(_extHostContext, a, b, c) {
    this.a = a;
    this.b = b;
    this.c = c;
  }
  dispose() {
  }
  $tryApplyWorkspaceEdit(dto, undoRedoGroupId, isRefactoring) {
    const edits = $Wrb(dto.value, this.c);
    return this.a.apply(edits, { undoRedoGroupId, respectAutoSaveConfig: isRefactoring }).then((res) => res.isApplied, (err) => {
      this.b.warn(`IGNORING workspace edit: ${err}`);
      return false;
    });
  }
};
$Vrb = __decorate([
  $frb($xT.MainThreadBulkEdits),
  __param(1, $H_),
  __param(2, $wn),
  __param(3, $vl)
], $Vrb);
function $Wrb(data, uriIdentityService, resolveDataTransferFile) {
  if (!data || !data.edits) {
    return data;
  }
  const result = $cu(data);
  for (const edit3 of result.edits) {
    if ($J_.is(edit3)) {
      edit3.resource = uriIdentityService.asCanonicalUri(edit3.resource);
    }
    if ($K_.is(edit3)) {
      if (edit3.options) {
        const inContents = edit3.options?.contents;
        if (inContents) {
          if (inContents.type === "base64") {
            edit3.options.contents = Promise.resolve($Vi(inContents.value));
          } else {
            if (resolveDataTransferFile) {
              edit3.options.contents = resolveDataTransferFile(inContents.id);
            } else {
              throw new Error("Could not revive data transfer file");
            }
          }
        }
      }
      edit3.newResource = edit3.newResource && uriIdentityService.asCanonicalUri(edit3.newResource);
      edit3.oldResource = edit3.oldResource && uriIdentityService.asCanonicalUri(edit3.oldResource);
    }
    if ($Trb.is(edit3)) {
      edit3.resource = uriIdentityService.asCanonicalUri(edit3.resource);
      const cellEdit = edit3.cellEdit;
      if (cellEdit.editType === 1) {
        edit3.cellEdit = {
          ...cellEdit,
          cells: cellEdit.cells.map((cell) => ({
            ...cell,
            outputs: cell.outputs.map((output) => ({
              ...output,
              outputs: output.items.map((item) => {
                return {
                  mime: item.mime,
                  data: item.valueBytes
                };
              })
            }))
          }))
        };
      }
    }
  }
  return data;
}

// out-build/vs/workbench/contrib/chat/common/ignoredFiles.js
var $Xrb = $Qk("languageModelIgnoredFilesService");
var $Yrb = class {
  constructor() {
    this.a = /* @__PURE__ */ new Set();
  }
  async fileIsIgnored(uri, token) {
    const provider = this.a.values().next().value;
    return provider ? provider.isFileIgnored(uri, token) : false;
  }
  registerIgnoredFileProvider(provider) {
    this.a.add(provider);
    return $1c(() => {
      this.a.delete(provider);
    });
  }
};

// out-build/vs/workbench/contrib/chat/common/languageModelStats.js
var $1rb_1;
var $Zrb = $Qk("ILanguageModelStatsService");
var $1rb = class $1rb2 extends $3c {
  static {
    $1rb_1 = this;
  }
  static {
    this.a = "languageModelStats.";
  }
  static {
    this.b = "languageModelAccess.";
  }
  constructor(g, h3) {
    super();
    this.g = g;
    this.h = h3;
    this.c = this.B(new $ze());
    this.onDidChangeLanguageMoelStats = this.c.event;
    this.f = /* @__PURE__ */ new Map();
    this.B(h3.onDidChangeValue(-1, void 0, this.q)((e) => {
      const model = this.t(e.key);
      if (model) {
        this.c.fire(model);
      }
    }));
  }
  hasAccessedModel(extensionId, model) {
    return this.m(model).includes(extensionId.toLowerCase());
  }
  async update(model, extensionId, agent, tokenCount) {
    await this.g.getAccess(extensionId, $2rb);
    this.j(model, extensionId.value);
    let sessionStats = this.f.get(model);
    if (!sessionStats) {
      sessionStats = { extensions: [] };
      this.f.set(model, sessionStats);
    }
    this.r(sessionStats, extensionId.value, agent, tokenCount);
    this.n(model, extensionId.value, agent, tokenCount);
    this.c.fire(model);
  }
  j(model, extensionId) {
    extensionId = extensionId.toLowerCase();
    const extensions = this.m(model);
    if (!extensions.includes(extensionId)) {
      extensions.push(extensionId);
      this.h.store(
        this.w(model),
        JSON.stringify(extensions),
        -1,
        0
        /* StorageTarget.USER */
      );
    }
  }
  m(model) {
    const key2 = this.w(model);
    const data = this.h.get(
      key2,
      -1
      /* StorageScope.APPLICATION */
    );
    try {
      if (data) {
        const parsed = JSON.parse(data);
        if (Array.isArray(parsed)) {
          return parsed;
        }
      }
    } catch (e) {
    }
    return [];
  }
  async n(model, extensionId, participant, tokenCount) {
    const modelStats = await this.s(model);
    this.r(modelStats, extensionId, participant, tokenCount);
    this.h.store(
      this.u(model),
      JSON.stringify(modelStats),
      -1,
      0
      /* StorageTarget.USER */
    );
  }
  r(modelStats, extensionId, participant, tokenCount) {
    let extensionStats = modelStats.extensions.find((e) => $5z.equals(e.extensionId, extensionId));
    if (!extensionStats) {
      extensionStats = { extensionId, requestCount: 0, tokenCount: 0, participants: [] };
      modelStats.extensions.push(extensionStats);
    }
    if (participant) {
      let participantStats = extensionStats.participants.find((p) => p.id === participant);
      if (!participantStats) {
        participantStats = { id: participant, requestCount: 0, tokenCount: 0 };
        extensionStats.participants.push(participantStats);
      }
      participantStats.requestCount++;
      participantStats.tokenCount += tokenCount ?? 0;
    } else {
      extensionStats.requestCount++;
      extensionStats.tokenCount += tokenCount ?? 0;
    }
  }
  async s(model) {
    try {
      const value = this.h.get(
        this.u(model),
        -1
        /* StorageScope.APPLICATION */
      );
      if (value) {
        return JSON.parse(value);
      }
    } catch (error) {
    }
    return { extensions: [] };
  }
  t(key2) {
    if (key2.startsWith($1rb_1.a)) {
      return key2.substring($1rb_1.a.length);
    }
    return void 0;
  }
  u(model) {
    return `${$1rb_1.a}${model}`;
  }
  w(model) {
    return `${$1rb_1.b}${model}`;
  }
};
$1rb = $1rb_1 = __decorate([
  __param(0, $wlb),
  __param(1, $jv)
], $1rb);
var $2rb = "copilot";
$Wn.as(Extensions3.ExtensionFeaturesRegistry).registerExtensionFeature({
  id: $2rb,
  label: localize(5112, null),
  description: localize(5113, null),
  icon: $6l.copilot,
  access: {
    canToggle: false
  },
  accessDataLabel: localize(5114, null)
});

// out-build/vs/workbench/contrib/chat/common/chatContextKeys.js
var ChatContextKeys;
(function(ChatContextKeys2) {
  ChatContextKeys2.responseVote = new $nn("chatSessionResponseVote", "", { type: "string", description: localize(5076, null) });
  ChatContextKeys2.responseDetectedAgentCommand = new $nn("chatSessionResponseDetectedAgentOrCommand", false, { type: "boolean", description: localize(5077, null) });
  ChatContextKeys2.responseSupportsIssueReporting = new $nn("chatResponseSupportsIssueReporting", false, { type: "boolean", description: localize(5078, null) });
  ChatContextKeys2.responseIsFiltered = new $nn("chatSessionResponseFiltered", false, { type: "boolean", description: localize(5079, null) });
  ChatContextKeys2.responseHasError = new $nn("chatSessionResponseError", false, { type: "boolean", description: localize(5080, null) });
  ChatContextKeys2.requestInProgress = new $nn("chatSessionRequestInProgress", false, { type: "boolean", description: localize(5081, null) });
  ChatContextKeys2.isResponse = new $nn("chatResponse", false, { type: "boolean", description: localize(5082, null) });
  ChatContextKeys2.isRequest = new $nn("chatRequest", false, { type: "boolean", description: localize(5083, null) });
  ChatContextKeys2.itemId = new $nn("chatItemId", "", { type: "string", description: localize(5084, null) });
  ChatContextKeys2.lastItemId = new $nn("chatLastItemId", [], { type: "string", description: localize(5085, null) });
  ChatContextKeys2.editApplied = new $nn("chatEditApplied", false, { type: "boolean", description: localize(5086, null) });
  ChatContextKeys2.inputHasText = new $nn("chatInputHasText", false, { type: "boolean", description: localize(5087, null) });
  ChatContextKeys2.inputHasFocus = new $nn("chatInputHasFocus", false, { type: "boolean", description: localize(5088, null) });
  ChatContextKeys2.inChatInput = new $nn("inChatInput", false, { type: "boolean", description: localize(5089, null) });
  ChatContextKeys2.inChatSession = new $nn("inChat", false, { type: "boolean", description: localize(5090, null) });
  ChatContextKeys2.enabled = new $nn("chatIsEnabled", false, { type: "boolean", description: localize(5091, null) });
  ChatContextKeys2.panelParticipantRegistered = new $nn("chatPanelParticipantRegistered", false, { type: "boolean", description: localize(5092, null) });
  ChatContextKeys2.editingParticipantRegistered = new $nn("chatEditingParticipantRegistered", false, { type: "boolean", description: localize(5093, null) });
  ChatContextKeys2.chatEditingCanUndo = new $nn("chatEditingCanUndo", false, { type: "boolean", description: localize(5094, null) });
  ChatContextKeys2.chatEditingCanRedo = new $nn("chatEditingCanRedo", false, { type: "boolean", description: localize(5095, null) });
  ChatContextKeys2.extensionInvalid = new $nn("chatExtensionInvalid", false, { type: "boolean", description: localize(5096, null) });
  ChatContextKeys2.inputCursorAtTop = new $nn("chatCursorAtTop", false);
  ChatContextKeys2.inputHasAgent = new $nn("chatInputHasAgent", false);
  ChatContextKeys2.location = new $nn("chatLocation", void 0);
  ChatContextKeys2.inQuickChat = new $nn("quickChatHasFocus", false, { type: "boolean", description: localize(5097, null) });
  ChatContextKeys2.hasFileAttachments = new $nn("chatHasFileAttachments", false, { type: "boolean", description: localize(5098, null) });
  ChatContextKeys2.languageModelsAreUserSelectable = new $nn("chatModelsAreUserSelectable", false, { type: "boolean", description: localize(5099, null) });
  ChatContextKeys2.Setup = {
    canSignUp: new $nn("chatSetupCanSignUp", false, true),
    // True when user can sign up to be a chat limited user.
    signedOut: new $nn("chatSetupSignedOut", false, true),
    // True when user is signed out.
    limited: new $nn("chatSetupLimited", false, true),
    // True when user is a chat limited user.
    triggered: new $nn("chatSetupTriggered", false, true),
    // True when chat setup is triggered.
    installed: new $nn("chatSetupInstalled", false, true)
    // True when the chat extension is installed.
  };
  ChatContextKeys2.chatQuotaExceeded = new $nn("chatQuotaExceeded", false, true);
  ChatContextKeys2.completionsQuotaExceeded = new $nn("completionsQuotaExceeded", false, true);
})(ChatContextKeys || (ChatContextKeys = {}));

// out-build/vs/workbench/contrib/chat/common/languageModels.js
var ChatMessageRole;
(function(ChatMessageRole2) {
  ChatMessageRole2[ChatMessageRole2["System"] = 0] = "System";
  ChatMessageRole2[ChatMessageRole2["User"] = 1] = "User";
  ChatMessageRole2[ChatMessageRole2["Assistant"] = 2] = "Assistant";
})(ChatMessageRole || (ChatMessageRole = {}));
var $GN = $Qk("ILanguageModelsService");
var languageModelType = {
  type: "object",
  properties: {
    vendor: {
      type: "string",
      description: localize(5106, null)
    }
  }
};
var $HN = $tN.registerExtensionPoint({
  extensionPoint: "languageModels",
  jsonSchema: {
    description: localize(5107, null),
    oneOf: [
      languageModelType,
      {
        type: "array",
        items: languageModelType
      }
    ]
  },
  activationEventsGenerator: (contribs, result) => {
    for (const contrib of contribs) {
      result.push(`onLanguageModelChat:${contrib.vendor}`);
    }
  }
});
var $IN = class $IN2 {
  constructor(f, g, h3) {
    this.f = f;
    this.g = g;
    this.h = h3;
    this.a = new $2c();
    this.b = /* @__PURE__ */ new Map();
    this.c = /* @__PURE__ */ new Set();
    this.d = this.a.add(new $ze());
    this.onDidChangeLanguageModels = this.d.event;
    this.e = ChatContextKeys.languageModelsAreUserSelectable.bindTo(this.h);
    this.a.add($HN.setHandler((extensions) => {
      this.c.clear();
      for (const extension of extensions) {
        if (!$zN(extension.description, "chatProvider")) {
          extension.collector.error(localize(5108, null));
          continue;
        }
        for (const item of Iterable.wrap(extension.value)) {
          if (this.c.has(item.vendor)) {
            extension.collector.error(localize(5109, null, item.vendor));
            continue;
          }
          if ($vf(item.vendor)) {
            extension.collector.error(localize(5110, null));
            continue;
          }
          if (item.vendor.trim() !== item.vendor) {
            extension.collector.error(localize(5111, null));
            continue;
          }
          this.c.add(item.vendor);
        }
      }
      const removed = [];
      for (const [identifier2, value] of this.b) {
        if (!this.c.has(value.metadata.vendor)) {
          this.b.delete(identifier2);
          removed.push(identifier2);
        }
      }
      if (removed.length > 0) {
        this.d.fire({ removed });
      }
    }));
  }
  dispose() {
    this.a.dispose();
    this.b.clear();
  }
  getLanguageModelIds() {
    return Array.from(this.b.keys());
  }
  lookupLanguageModel(identifier2) {
    return this.b.get(identifier2)?.metadata;
  }
  async selectLanguageModels(selector) {
    if (selector.vendor) {
      await this.f.activateByEvent(`onLanguageModelChat:${selector.vendor}}`);
    } else {
      const all = Array.from(this.c).map((vendor) => this.f.activateByEvent(`onLanguageModelChat:${vendor}`));
      await Promise.all(all);
    }
    const result = [];
    for (const [identifier2, model] of this.b) {
      if ((selector.vendor === void 0 || model.metadata.vendor === selector.vendor) && (selector.family === void 0 || model.metadata.family === selector.family) && (selector.version === void 0 || model.metadata.version === selector.version) && (selector.identifier === void 0 || model.metadata.id === selector.identifier) && (!model.metadata.targetExtensions || model.metadata.targetExtensions.some((candidate) => $5z.equals(candidate, selector.extension)))) {
        result.push(identifier2);
      }
    }
    this.g.trace("[LM] selected language models", selector, result);
    return result;
  }
  registerLanguageModelChat(identifier2, provider) {
    this.g.trace("[LM] registering language model chat", identifier2, provider.metadata);
    if (!this.c.has(provider.metadata.vendor)) {
      throw new Error(`Chat response provider uses UNKNOWN vendor ${provider.metadata.vendor}.`);
    }
    if (this.b.has(identifier2)) {
      throw new Error(`Chat response provider with identifier ${identifier2} is already registered.`);
    }
    this.b.set(identifier2, provider);
    this.d.fire({ added: [{ identifier: identifier2, metadata: provider.metadata }] });
    this.i();
    return $1c(() => {
      this.i();
      if (this.b.delete(identifier2)) {
        this.d.fire({ removed: [identifier2] });
        this.g.trace("[LM] UNregistered language model chat", identifier2, provider.metadata);
      }
    });
  }
  i() {
    const hasUserSelectableModels = Array.from(this.b.values()).some((p) => p.metadata.isUserSelectable && !p.metadata.isDefault);
    const hasDefaultModel = Array.from(this.b.values()).some((p) => p.metadata.isDefault);
    this.e.set(hasUserSelectableModels && hasDefaultModel);
  }
  async sendChatRequest(identifier2, from, messages, options3, token) {
    const provider = this.b.get(identifier2);
    if (!provider) {
      throw new Error(`Chat response provider with identifier ${identifier2} is not registered.`);
    }
    return provider.sendChatRequest(messages, from, options3, token);
  }
  computeTokenLength(identifier2, message, token) {
    const provider = this.b.get(identifier2);
    if (!provider) {
      throw new Error(`Chat response provider with identifier ${identifier2} is not registered.`);
    }
    return provider.provideTokenCount(message, token);
  }
};
$IN = __decorate([
  __param(0, $wN),
  __param(1, $wn),
  __param(2, $on)
], $IN);

// out-build/vs/workbench/services/authentication/browser/authenticationAccessService.js
var $V4 = $Qk("IAuthenticationAccessService");
var $W4 = class $W42 extends $3c {
  constructor(b, c) {
    super();
    this.b = b;
    this.c = c;
    this.a = this.B(new $ze());
    this.onDidChangeExtensionSessionAccess = this.a.event;
  }
  isAccessAllowed(providerId, accountName, extensionId) {
    const trustedExtensionAuthAccess = this.c.trustedExtensionAuthAccess;
    if (Array.isArray(trustedExtensionAuthAccess)) {
      if (trustedExtensionAuthAccess.includes(extensionId)) {
        return true;
      }
    } else if (trustedExtensionAuthAccess?.[providerId]?.includes(extensionId)) {
      return true;
    }
    const allowList = this.readAllowedExtensions(providerId, accountName);
    const extensionData = allowList.find((extension) => extension.id === extensionId);
    if (!extensionData) {
      return void 0;
    }
    return extensionData.allowed !== void 0 ? extensionData.allowed : true;
  }
  readAllowedExtensions(providerId, accountName) {
    let trustedExtensions = [];
    try {
      const trustedExtensionSrc = this.b.get(
        `${providerId}-${accountName}`,
        -1
        /* StorageScope.APPLICATION */
      );
      if (trustedExtensionSrc) {
        trustedExtensions = JSON.parse(trustedExtensionSrc);
      }
    } catch (err) {
    }
    return trustedExtensions;
  }
  updateAllowedExtensions(providerId, accountName, extensions) {
    const allowList = this.readAllowedExtensions(providerId, accountName);
    for (const extension of extensions) {
      const index = allowList.findIndex((e) => e.id === extension.id);
      if (index === -1) {
        allowList.push(extension);
      } else {
        allowList[index].allowed = extension.allowed;
      }
    }
    this.b.store(
      `${providerId}-${accountName}`,
      JSON.stringify(allowList),
      -1,
      0
      /* StorageTarget.USER */
    );
    this.a.fire({ providerId, accountName });
  }
  removeAllowedExtensions(providerId, accountName) {
    this.b.remove(
      `${providerId}-${accountName}`,
      -1
      /* StorageScope.APPLICATION */
    );
    this.a.fire({ providerId, accountName });
  }
};
$W4 = __decorate([
  __param(0, $jv),
  __param(1, $Vu)
], $W4);
$SC(
  $V4,
  $W4,
  1
  /* InstantiationType.Delayed */
);

// out-build/vs/workbench/services/authentication/common/authentication.js
var $wS = "__";
var $xS = $Qk("IAuthenticationService");
var $yS = $Qk("IAuthenticationExtensionsService");

// out-build/vs/workbench/api/browser/mainThreadLanguageModels.js
var $3rb = class $3rb2 {
  constructor(extHostContext, g, h3, i2, j, k, l, m) {
    this.g = g;
    this.h = h3;
    this.i = i2;
    this.j = j;
    this.k = k;
    this.l = l;
    this.m = m;
    this.b = new $2c();
    this.c = new $_c();
    this.d = /* @__PURE__ */ new Map();
    this.f = new $_c();
    this.a = extHostContext.getProxy($yT.ExtHostChatProvider);
    this.a.$acceptChatModelMetadata({ added: g.getLanguageModelIds().map((id2) => ({ identifier: id2, metadata: g.lookupLanguageModel(id2) })) });
    this.b.add(g.onDidChangeLanguageModels(this.a.$acceptChatModelMetadata, this.a));
  }
  dispose() {
    this.c.dispose();
    this.f.dispose();
    this.b.dispose();
  }
  $registerLanguageModelProvider(handle2, identifier2, metadata) {
    const dipsosables = new $2c();
    dipsosables.add(this.g.registerLanguageModelChat(identifier2, {
      metadata,
      sendChatRequest: async (messages, from, options3, token) => {
        const requestId = Math.random() * 1e6 | 0;
        const defer = new $gi();
        const stream = new $mi();
        try {
          this.d.set(requestId, { defer, stream });
          await this.a.$startChatRequest(handle2, requestId, from, messages, options3, token);
        } catch (err) {
          this.d.delete(requestId);
          throw err;
        }
        return {
          result: defer.p,
          stream: stream.asyncIterable
        };
      },
      provideTokenCount: (str, token) => {
        return this.a.$provideTokenLength(handle2, str, token);
      }
    }));
    if (metadata.auth) {
      dipsosables.add(this.n(metadata.extension, metadata.auth));
    }
    this.c.set(handle2, dipsosables);
  }
  async $reportResponsePart(requestId, chunk) {
    const data = this.d.get(requestId);
    this.i.trace("[LM] report response PART", Boolean(data), requestId, chunk);
    if (data) {
      data.stream.emitOne(chunk);
    }
  }
  async $reportResponseDone(requestId, err) {
    const data = this.d.get(requestId);
    this.i.trace("[LM] report response DONE", Boolean(data), requestId, err);
    if (data) {
      this.d.delete(requestId);
      if (err) {
        const error = $jb(err);
        data.stream.reject(error);
        data.defer.error(error);
      } else {
        data.stream.resolve();
        data.defer.complete(void 0);
      }
    }
  }
  $unregisterProvider(handle2) {
    this.c.deleteAndDispose(handle2);
  }
  $selectChatModels(selector) {
    return this.g.selectLanguageModels(selector);
  }
  $whenLanguageModelChatRequestMade(identifier2, extensionId, participant, tokenCount) {
    this.h.update(identifier2, extensionId, participant, tokenCount);
  }
  async $tryStartChatRequest(extension, providerId, requestId, messages, options3, token) {
    this.i.trace("[CHAT] request STARTED", extension.value, requestId);
    const response = await this.g.sendChatRequest(providerId, extension, messages, options3, token);
    const streaming = (async () => {
      try {
        for await (const part of response.stream) {
          this.i.trace("[CHAT] request PART", extension.value, requestId, part);
          await this.a.$acceptResponsePart(requestId, part);
        }
        this.i.trace("[CHAT] request DONE", extension.value, requestId);
      } catch (err) {
        this.i.error("[CHAT] extension request ERRORED in STREAM", err, extension.value, requestId);
        this.a.$acceptResponseDone(requestId, $ib(err));
      }
    })();
    Promise.allSettled([response.result, streaming]).then(() => {
      this.i.debug("[CHAT] extension request DONE", extension.value, requestId);
      this.a.$acceptResponseDone(requestId, void 0);
    }, (err) => {
      this.i.error("[CHAT] extension request ERRORED", err, extension.value, requestId);
      this.a.$acceptResponseDone(requestId, $ib(err));
    });
  }
  $countTokens(provider, value, token) {
    return this.g.computeTokenLength(provider, value, token);
  }
  n(extension, auth) {
    const authProviderId = $wS + extension.value;
    if (this.j.getProviderIds().includes(authProviderId)) {
      return $3c.None;
    }
    const accountLabel = auth.accountLabel ?? localize(2615, null);
    const disposables = new $2c();
    this.j.registerAuthenticationProvider(authProviderId, new LanguageModelAccessAuthProvider(authProviderId, auth.providerLabel, accountLabel));
    disposables.add($1c(() => {
      this.j.unregisterAuthenticationProvider(authProviderId);
    }));
    disposables.add(this.k.onDidChangeExtensionSessionAccess(async (e) => {
      const allowedExtensions = this.k.readAllowedExtensions(authProviderId, accountLabel);
      const accessList = [];
      for (const allowedExtension of allowedExtensions) {
        const from = await this.l.getExtension(allowedExtension.id);
        if (from) {
          accessList.push({
            from: from.identifier,
            to: extension,
            enabled: allowedExtension.allowed ?? true
          });
        }
      }
      this.a.$updateModelAccesslist(accessList);
    }));
    return disposables;
  }
  $fileIsIgnored(uri, token) {
    return this.m.fileIsIgnored(URI.revive(uri), token);
  }
  $registerFileIgnoreProvider(handle2) {
    this.f.set(handle2, this.m.registerIgnoredFileProvider({
      isFileIgnored: async (uri, token) => this.a.$isFileIgnored(handle2, uri, token)
    }));
  }
  $unregisterFileIgnoreProvider(handle2) {
    this.f.deleteAndDispose(handle2);
  }
};
$3rb = __decorate([
  $frb($xT.MainThreadLanguageModels),
  __param(1, $GN),
  __param(2, $Zrb),
  __param(3, $wn),
  __param(4, $xS),
  __param(5, $V4),
  __param(6, $wN),
  __param(7, $Xrb)
], $3rb);
var LanguageModelAccessAuthProvider = class {
  constructor(id2, label3, c) {
    this.id = id2;
    this.label = label3;
    this.c = c;
    this.supportsMultipleAccounts = false;
    this.a = new $ze();
    this.onDidChangeSessions = this.a.event;
  }
  async getSessions(scopes) {
    if (scopes === void 0 && !this.b) {
      return [];
    }
    if (this.b) {
      return [this.b];
    }
    return [await this.createSession(scopes || [])];
  }
  async createSession(scopes) {
    this.b = this.d(scopes);
    this.a.fire({ added: [this.b], changed: [], removed: [] });
    return this.b;
  }
  removeSession(sessionId) {
    if (this.b) {
      this.a.fire({ added: [], changed: [], removed: [this.b] });
      this.b = void 0;
    }
    return Promise.resolve();
  }
  d(scopes) {
    return {
      id: "fake-session",
      account: {
        id: this.id,
        label: this.c
      },
      accessToken: "fake-access-token",
      scopes
    };
  }
};

// out-build/vs/workbench/contrib/chat/common/chatParticipantContribTypes.js
var $XO = "copilot";

// out-build/vs/workbench/contrib/chat/browser/chat.js
var $2Nb = $Qk("chatWidgetService");
async function $3Nb(viewsService) {
  return (await viewsService.openView($9Nb))?.widget;
}
async function $4Nb(viewsService) {
  return (await viewsService.openView($0Nb))?.widget;
}
function $5Nb(width2, viewDescriptorService, layoutService) {
  const location3 = viewDescriptorService.getViewLocationById($9Nb);
  if (location3 === 1) {
    return;
  }
  const viewPart = location3 === 0 ? "workbench.parts.sidebar" : "workbench.parts.auxiliarybar";
  const partSize = layoutService.getSize(viewPart);
  if (partSize.width < width2) {
    layoutService.setSize(viewPart, { width: width2, height: partSize.height });
  }
}
var $6Nb = $Qk("quickChatService");
var $7Nb = $Qk("chatAccessibilityService");
var $8Nb = $Qk("chatCodeBlockContextProviderService");
var $9Nb = `workbench.panel.chat.view.${$XO}`;
var $0Nb = "workbench.panel.chat.view.edits";

// out-build/vs/base/browser/ui/progressbar/progressAccessibilitySignal.js
var nullScopedAccessibilityProgressSignalFactory = () => ({
  msLoopTime: -1,
  msDelayTime: -1,
  dispose: () => {
  }
});
var progressAccessibilitySignalSchedulerFactory = nullScopedAccessibilityProgressSignalFactory;
function $72(progressAccessibilitySignalScheduler) {
  progressAccessibilitySignalSchedulerFactory = progressAccessibilitySignalScheduler;
}
function $82(msDelayTime, msLoopTime) {
  return progressAccessibilitySignalSchedulerFactory(msDelayTime, msLoopTime);
}

// out-build/vs/base/browser/ui/progressbar/progressbar.js
var CSS_DONE = "done";
var CSS_ACTIVE = "active";
var CSS_INFINITE = "infinite";
var CSS_INFINITE_LONG_RUNNING = "infinite-long-running";
var CSS_DISCRETE = "discrete";
var $02 = class _$02 extends $3c {
  static {
    this.a = 1e4;
  }
  static {
    this.b = 3e3;
  }
  constructor(container2, options3) {
    super();
    this.n = this.B(new $4c());
    this.c = 0;
    this.j = this.B(new $8h(() => $hk(this.f), 0));
    this.m = this.B(new $8h(() => this.u(), _$02.a));
    this.r(container2, options3);
  }
  r(container2, options3) {
    this.f = document.createElement("div");
    this.f.classList.add("monaco-progress-container");
    this.f.setAttribute("role", "progressbar");
    this.f.setAttribute("aria-valuemin", "0");
    container2.appendChild(this.f);
    this.g = document.createElement("div");
    this.g.classList.add("progress-bit");
    this.g.style.backgroundColor = options3?.progressBarBackground || "#0E70C0";
    this.f.appendChild(this.g);
  }
  s() {
    this.g.style.width = "inherit";
    this.g.style.opacity = "1";
    this.f.classList.remove(CSS_ACTIVE, CSS_INFINITE, CSS_INFINITE_LONG_RUNNING, CSS_DISCRETE);
    this.c = 0;
    this.h = void 0;
    this.m.cancel();
    this.n.clear();
  }
  /**
   * Indicates to the progress bar that all work is done.
   */
  done() {
    return this.t(true);
  }
  /**
   * Stops the progressbar from showing any progress instantly without fading out.
   */
  stop() {
    return this.t(false);
  }
  t(delayed) {
    this.f.classList.add(CSS_DONE);
    if (!this.f.classList.contains(CSS_INFINITE)) {
      this.g.style.width = "inherit";
      if (delayed) {
        setTimeout(() => this.s(), 200);
      } else {
        this.s();
      }
    } else {
      this.g.style.opacity = "0";
      if (delayed) {
        setTimeout(() => this.s(), 200);
      } else {
        this.s();
      }
    }
    return this;
  }
  /**
   * Use this mode to indicate progress that has no total number of work units.
   */
  infinite() {
    this.g.style.width = "2%";
    this.g.style.opacity = "1";
    this.f.classList.remove(CSS_DISCRETE, CSS_DONE, CSS_INFINITE_LONG_RUNNING);
    this.f.classList.add(CSS_ACTIVE, CSS_INFINITE);
    this.m.schedule();
    return this;
  }
  u() {
    this.f.classList.add(CSS_INFINITE_LONG_RUNNING);
  }
  /**
   * Tells the progress bar the total number of work. Use in combination with workedVal() to let
   * the progress bar show the actual progress based on the work that is done.
   */
  total(value) {
    this.c = 0;
    this.h = value;
    this.f.setAttribute("aria-valuemax", value.toString());
    return this;
  }
  /**
   * Finds out if this progress bar is configured with total work
   */
  hasTotal() {
    return $Dg(this.h);
  }
  /**
   * Tells the progress bar that an increment of work has been completed.
   */
  worked(value) {
    value = Math.max(1, Number(value));
    return this.w(this.c + value);
  }
  /**
   * Tells the progress bar the total amount of work that has been completed.
   */
  setWorked(value) {
    value = Math.max(1, Number(value));
    return this.w(value);
  }
  w(value) {
    const totalWork = this.h || 100;
    this.c = value;
    this.c = Math.min(totalWork, this.c);
    this.f.classList.remove(CSS_INFINITE, CSS_INFINITE_LONG_RUNNING, CSS_DONE);
    this.f.classList.add(CSS_ACTIVE, CSS_DISCRETE);
    this.f.setAttribute("aria-valuenow", value.toString());
    this.g.style.width = 100 * (this.c / totalWork) + "%";
    return this;
  }
  getContainer() {
    return this.f;
  }
  show(delay) {
    this.j.cancel();
    this.n.value = $82(_$02.b);
    if (typeof delay === "number") {
      this.j.schedule(delay);
    } else {
      $hk(this.f);
    }
  }
  hide() {
    $ik(this.f);
    this.j.cancel();
    this.n.clear();
  }
};

// out-build/vs/platform/actions/browser/buttonbar.js
var $gsb = class $gsb2 extends $n2 {
  constructor(container2, k, l, m, telemetryService, n) {
    super(container2);
    this.k = k;
    this.l = l;
    this.m = m;
    this.n = n;
    this.f = new $2c();
    this.g = new $2c();
    this.j = new $ze();
    this.onDidChange = this.j.event;
    this.h = this.f.add(new $Vm());
    if (k?.telemetrySource) {
      this.h.onDidRun((e) => {
        telemetryService.publicLog2("workbenchActionExecuted", { id: e.action.id, from: k.telemetrySource });
      }, void 0, this.f);
    }
  }
  dispose() {
    this.j.dispose();
    this.g.dispose();
    this.f.dispose();
    super.dispose();
  }
  update(actions, secondary) {
    const conifgProvider = this.k?.buttonConfigProvider ?? (() => ({ showLabel: true }));
    this.g.clear();
    this.clear();
    const hoverDelegate = this.g.add($KZ());
    for (let i2 = 0; i2 < actions.length; i2++) {
      const secondary2 = i2 > 0;
      const actionOrSubmenu = actions[i2];
      let action;
      let btn;
      if (actionOrSubmenu instanceof $Xm && actionOrSubmenu.actions.length > 0) {
        const [first, ...rest] = actionOrSubmenu.actions;
        action = first;
        btn = this.addButtonWithDropdown({
          secondary: conifgProvider(action, i2)?.isSecondary ?? secondary2,
          actionRunner: this.h,
          actions: rest,
          contextMenuProvider: this.l,
          ariaLabel: action.label,
          supportIcons: true
        });
      } else {
        action = actionOrSubmenu;
        btn = this.addButton({
          secondary: conifgProvider(action, i2)?.isSecondary ?? secondary2,
          ariaLabel: action.label,
          supportIcons: true
        });
      }
      btn.enabled = action.enabled;
      btn.checked = action.checked ?? false;
      btn.element.classList.add("default-colors");
      const showLabel = conifgProvider(action, i2)?.showLabel ?? true;
      if (showLabel) {
        btn.label = action.label;
      } else {
        btn.element.classList.add("monaco-text-button");
      }
      if (conifgProvider(action, i2)?.showIcon) {
        if (action instanceof $fJ && ThemeIcon.isThemeIcon(action.item.icon)) {
          if (!showLabel) {
            btn.icon = action.item.icon;
          } else {
            btn.label = `$(${action.item.icon.id}) ${action.label}`;
          }
        } else if (action.class) {
          btn.element.classList.add(...action.class.split(" "));
        }
      }
      const kb = this.m.lookupKeybinding(action.id);
      let tooltip;
      if (kb) {
        tooltip = localize(1669, null, action.tooltip || action.label, kb.getLabel());
      } else {
        tooltip = action.tooltip || action.label;
      }
      this.g.add(this.n.setupManagedHover(hoverDelegate, btn.element, tooltip));
      this.g.add(btn.onDidClick(async () => {
        this.h.run(action);
      }));
    }
    if (secondary.length > 0) {
      const btn = this.addButton({
        secondary: true,
        ariaLabel: localize(1670, null)
      });
      btn.icon = $6l.dropDownButton;
      btn.element.classList.add("default-colors", "monaco-text-button");
      btn.enabled = true;
      this.g.add(this.n.setupManagedHover(hoverDelegate, btn.element, localize(1671, null)));
      this.g.add(btn.onDidClick(async () => {
        this.l.showContextMenu({
          getAnchor: () => btn.element,
          getActions: () => secondary,
          actionRunner: this.h,
          onHide: () => btn.element.setAttribute("aria-expanded", "false")
        });
        btn.element.setAttribute("aria-expanded", "true");
      }));
    }
    this.j.fire(this);
  }
};
$gsb = __decorate([
  __param(2, $50),
  __param(3, $Ty),
  __param(4, $zv),
  __param(5, $5$)
], $gsb);
var $hsb = class $hsb2 extends $gsb {
  constructor(container2, menuId, options3, menuService, contextKeyService, contextMenuService, keybindingService, telemetryService, hoverService) {
    super(container2, options3, contextMenuService, keybindingService, telemetryService, hoverService);
    const menu = menuService.createMenu(menuId, contextKeyService);
    this.f.add(menu);
    const update = () => {
      this.clear();
      const actions = $Q$(menu.getActions(options3?.menuOptions), options3?.toolbarOptions?.primaryGroup);
      super.update(actions.primary, actions.secondary);
    };
    this.f.add(menu.onDidChange(update));
    update();
  }
  dispose() {
    super.dispose();
  }
  update(_actions) {
    throw new Error("Use Menu or WorkbenchButtonBar");
  }
};
$hsb = __decorate([
  __param(3, $cJ),
  __param(4, $on),
  __param(5, $50),
  __param(6, $Ty),
  __param(7, $zv),
  __param(8, $5$)
], $hsb);

// out-build/vs/platform/actions/browser/dropdownWithPrimaryActionViewItem.js
var $isb = class $isb2 extends $T1 {
  get onDidChangeDropdownVisibility() {
    return this.g.onDidChangeVisibility;
  }
  constructor(primaryAction, dropdownAction, dropdownMenuActions, className, s, t, _keybindingService, _notificationService, _contextKeyService, _themeService, _accessibilityService) {
    super(null, primaryAction, { hoverDelegate: s?.hoverDelegate });
    this.s = s;
    this.t = t;
    this.n = null;
    this.r = null;
    this.c = new $T$(primaryAction, { hoverDelegate: s?.hoverDelegate }, _keybindingService, _notificationService, _contextKeyService, _themeService, t, _accessibilityService);
    if (s?.actionRunner) {
      this.c.actionRunner = s.actionRunner;
    }
    this.g = new $L2(dropdownAction, dropdownMenuActions, this.t, {
      menuAsChild: s?.menuAsChild ?? true,
      classNames: className ? ["codicon", "codicon-chevron-down", className] : ["codicon", "codicon-chevron-down"],
      actionRunner: this.s?.actionRunner,
      keybindingProvider: this.s?.getKeyBinding ?? ((action) => _keybindingService.lookupKeybinding(action.id)),
      hoverDelegate: s?.hoverDelegate,
      skipTelemetry: s?.skipTelemetry
    });
  }
  set actionRunner(actionRunner) {
    super.actionRunner = actionRunner;
    this.c.actionRunner = actionRunner;
    this.g.actionRunner = actionRunner;
  }
  setActionContext(newContext) {
    super.setActionContext(newContext);
    this.c.setActionContext(newContext);
    this.g.setActionContext(newContext);
  }
  render(container2) {
    this.n = container2;
    super.render(this.n);
    this.n.classList.add("monaco-dropdown-with-primary");
    const primaryContainer = $(".action-container");
    primaryContainer.role = "button";
    this.c.render($bk(this.n, primaryContainer));
    this.r = $(".dropdown-action-container");
    this.g.render($bk(this.n, this.r));
    this.B($_i(primaryContainer, $7j.KEY_DOWN, (e) => {
      const event = new $if(e);
      if (event.equals(
        17
        /* KeyCode.RightArrow */
      )) {
        this.c.element.tabIndex = -1;
        this.g.focus();
        event.stopPropagation();
      }
    }));
    this.B($_i(this.r, $7j.KEY_DOWN, (e) => {
      const event = new $if(e);
      if (event.equals(
        15
        /* KeyCode.LeftArrow */
      )) {
        this.c.element.tabIndex = 0;
        this.g.setFocusable(false);
        this.c.element?.focus();
        event.stopPropagation();
      }
    }));
    this.z();
  }
  focus(fromRight) {
    if (fromRight) {
      this.g.focus();
    } else {
      this.c.element.tabIndex = 0;
      this.c.element.focus();
    }
  }
  blur() {
    this.c.element.tabIndex = -1;
    this.g.blur();
    this.n.blur();
  }
  setFocusable(focusable) {
    if (focusable) {
      this.c.element.tabIndex = 0;
    } else {
      this.c.element.tabIndex = -1;
      this.g.setFocusable(false);
    }
  }
  z() {
    const disabled = !this.action.enabled;
    this.element?.classList.toggle("disabled", disabled);
  }
  update(dropdownAction, dropdownMenuActions, dropdownIcon) {
    this.g.dispose();
    this.g = new $L2(dropdownAction, dropdownMenuActions, this.t, {
      menuAsChild: true,
      classNames: ["codicon", dropdownIcon || "codicon-chevron-down"],
      actionRunner: this.s?.actionRunner,
      hoverDelegate: this.s?.hoverDelegate,
      keybindingProvider: this.s?.getKeyBinding
    });
    if (this.r) {
      this.g.render(this.r);
    }
  }
  showDropdown() {
    this.g.show();
  }
  dispose() {
    this.c.dispose();
    this.g.dispose();
    super.dispose();
  }
};
$isb = __decorate([
  __param(5, $50),
  __param(6, $Ty),
  __param(7, $PJ),
  __param(8, $on),
  __param(9, $gs),
  __param(10, $ND)
], $isb);

// out-build/vs/workbench/services/textfile/common/textfiles.js
var $cK = $Qk("textFileService");
var TextFileOperationResult;
(function(TextFileOperationResult2) {
  TextFileOperationResult2[TextFileOperationResult2["FILE_IS_BINARY"] = 0] = "FILE_IS_BINARY";
})(TextFileOperationResult || (TextFileOperationResult = {}));
var $dK = class extends $Fm {
  static isTextFileOperationError(obj) {
    return obj instanceof Error && !$Ig(obj.textFileOperationResult);
  }
  constructor(message, textFileOperationResult, options3) {
    super(
      message,
      10
      /* FileOperationResult.FILE_OTHER_ERROR */
    );
    this.textFileOperationResult = textFileOperationResult;
    this.options = options3;
  }
};
var TextFileEditorModelState;
(function(TextFileEditorModelState2) {
  TextFileEditorModelState2[TextFileEditorModelState2["SAVED"] = 0] = "SAVED";
  TextFileEditorModelState2[TextFileEditorModelState2["DIRTY"] = 1] = "DIRTY";
  TextFileEditorModelState2[TextFileEditorModelState2["PENDING_SAVE"] = 2] = "PENDING_SAVE";
  TextFileEditorModelState2[TextFileEditorModelState2["CONFLICT"] = 3] = "CONFLICT";
  TextFileEditorModelState2[TextFileEditorModelState2["ORPHAN"] = 4] = "ORPHAN";
  TextFileEditorModelState2[TextFileEditorModelState2["ERROR"] = 5] = "ERROR";
})(TextFileEditorModelState || (TextFileEditorModelState = {}));
var TextFileResolveReason;
(function(TextFileResolveReason2) {
  TextFileResolveReason2[TextFileResolveReason2["EDITOR"] = 1] = "EDITOR";
  TextFileResolveReason2[TextFileResolveReason2["REFERENCE"] = 2] = "REFERENCE";
  TextFileResolveReason2[TextFileResolveReason2["OTHER"] = 3] = "OTHER";
})(TextFileResolveReason || (TextFileResolveReason = {}));
var EncodingMode;
(function(EncodingMode2) {
  EncodingMode2[EncodingMode2["Encode"] = 0] = "Encode";
  EncodingMode2[EncodingMode2["Decode"] = 1] = "Decode";
})(EncodingMode || (EncodingMode = {}));
function $eK(model) {
  const candidate = model;
  return $Og(candidate.setEncoding, candidate.getEncoding, candidate.save, candidate.revert, candidate.isDirty, candidate.getLanguageId);
}
function $gK(value) {
  let done = false;
  return {
    read() {
      if (!done) {
        done = true;
        return value;
      }
      return null;
    }
  };
}
function $hK(value) {
  if (typeof value === "undefined") {
    return void 0;
  }
  if (typeof value === "string") {
    return $Ci.fromString(value);
  }
  return {
    read: () => {
      const chunk = value.read();
      if (typeof chunk === "string") {
        return $Ci.fromString(chunk);
      }
      return null;
    }
  };
}

// out-build/vs/workbench/services/decorations/common/decorations.js
var $jsb = $Qk("IFileDecorationsService");

// out-build/vs/workbench/browser/labels.js
function toResource(props) {
  if (!props || !props.resource) {
    return void 0;
  }
  if (URI.isUri(props.resource)) {
    return props.resource;
  }
  return props.resource.primary;
}
var $ksb = {
  onDidChangeVisibility: Event2.None
};
var $lsb = class $lsb2 extends $3c {
  constructor(container2, f, g, h3, j, m, n, r2, s, t) {
    super();
    this.f = f;
    this.g = g;
    this.h = h3;
    this.j = j;
    this.m = m;
    this.n = n;
    this.r = r2;
    this.s = s;
    this.t = t;
    this.a = this.B(new $ze());
    this.onDidChangeDecorations = this.a.event;
    this.b = [];
    this.c = [];
    this.u(container2);
  }
  u(container2) {
    this.B(container2.onDidChangeVisibility((visible) => {
      this.b.forEach((widget) => widget.notifyVisibilityChanged(visible));
    }));
    this.B(this.m.onDidChange(() => this.b.forEach((widget) => widget.notifyExtensionsRegistered())));
    this.B(this.h.onModelLanguageChanged((e) => {
      if (!e.model.uri) {
        return;
      }
      this.b.forEach((widget) => widget.notifyModelLanguageChanged(e.model));
    }));
    this.B(this.h.onModelAdded((model) => {
      if (!model.uri) {
        return;
      }
      this.b.forEach((widget) => widget.notifyModelAdded(model));
    }));
    this.B(this.j.onDidChangeWorkspaceFolders(() => {
      this.b.forEach((widget) => widget.notifyWorkspaceFoldersChange());
    }));
    this.B(this.n.onDidChangeDecorations((e) => {
      let notifyDidChangeDecorations = false;
      this.b.forEach((widget) => {
        if (widget.notifyFileDecorationsChanges(e)) {
          notifyDidChangeDecorations = true;
        }
      });
      if (notifyDidChangeDecorations) {
        this.a.fire();
      }
    }));
    this.B(this.r.onDidColorThemeChange(() => this.b.forEach((widget) => widget.notifyThemeChange())));
    this.B(this.g.onDidChangeConfiguration((e) => {
      if (e.affectsConfiguration($Km)) {
        this.b.forEach((widget) => widget.notifyFileAssociationsChange());
      }
    }));
    this.B(this.s.onDidChangeFormatters((e) => {
      this.b.forEach((widget) => widget.notifyFormattersChange(e.scheme));
    }));
    this.B(this.t.untitled.onDidChangeLabel((model) => {
      this.b.forEach((widget) => widget.notifyUntitledLabelChange(model.resource));
    }));
  }
  get(index) {
    return this.c[index];
  }
  create(container2, options3) {
    const widget = this.f.createInstance(ResourceLabelWidget, container2, options3);
    const label3 = {
      element: widget.element,
      onDidRender: widget.onDidRender,
      setLabel: (label4, description, options4) => widget.setLabel(label4, description, options4),
      setResource: (label4, options4) => widget.setResource(label4, options4),
      setFile: (resource, options4) => widget.setFile(resource, options4),
      clear: () => widget.clear(),
      dispose: () => this.w(widget)
    };
    this.c.push(label3);
    this.b.push(widget);
    return label3;
  }
  w(widget) {
    const index = this.b.indexOf(widget);
    if (index > -1) {
      this.b.splice(index, 1);
      this.c.splice(index, 1);
    }
    $Xc(widget);
  }
  clear() {
    this.b = $Xc(this.b);
    this.c = [];
  }
  dispose() {
    super.dispose();
    this.clear();
  }
};
$lsb = __decorate([
  __param(1, $Pk),
  __param(2, $kl),
  __param(3, $sG),
  __param(4, $Zk),
  __param(5, $1E),
  __param(6, $jsb),
  __param(7, $gs),
  __param(8, $ZI),
  __param(9, $cK)
], $lsb);
var $msb = class $msb2 extends $lsb {
  get element() {
    return this.y;
  }
  constructor(container2, options3, instantiationService, configurationService, modelService, workspaceService, languageService, decorationsService, themeService, labelService, textFileService) {
    super($ksb, instantiationService, configurationService, modelService, workspaceService, languageService, decorationsService, themeService, labelService, textFileService);
    this.y = this.B(this.create(container2, options3));
  }
};
$msb = __decorate([
  __param(2, $Pk),
  __param(3, $kl),
  __param(4, $sG),
  __param(5, $Zk),
  __param(6, $1E),
  __param(7, $jsb),
  __param(8, $gs),
  __param(9, $ZI),
  __param(10, $cK)
], $msb);
var Redraw;
(function(Redraw2) {
  Redraw2[Redraw2["Basic"] = 1] = "Basic";
  Redraw2[Redraw2["Full"] = 2] = "Full";
})(Redraw || (Redraw = {}));
var ResourceLabelWidget = class ResourceLabelWidget2 extends $T2 {
  constructor(container2, options3, L, M, N, O, P, Q, R) {
    super(container2, options3);
    this.L = L;
    this.M = M;
    this.N = N;
    this.O = O;
    this.P = P;
    this.Q = Q;
    this.R = R;
    this.w = this.B(new $ze());
    this.onDidRender = this.w.event;
    this.y = void 0;
    this.z = this.B(new $4c());
    this.C = void 0;
    this.D = void 0;
    this.F = void 0;
    this.G = void 0;
    this.H = void 0;
    this.I = void 0;
    this.J = false;
  }
  notifyVisibilityChanged(visible) {
    if (visible === this.J) {
      this.J = !visible;
      if (visible && this.I) {
        this.Z({
          updateIcon: this.I === Redraw.Full,
          updateDecoration: this.I === Redraw.Full
        });
        this.I = void 0;
      }
    }
  }
  notifyModelLanguageChanged(model) {
    this.S(model);
  }
  notifyModelAdded(model) {
    this.S(model);
  }
  S(model) {
    const resource = toResource(this.y);
    if (!resource) {
      return;
    }
    if ($oh(model.uri, resource)) {
      if (this.F !== model.getLanguageId()) {
        this.F = model.getLanguageId();
        this.Z({ updateIcon: true, updateDecoration: false });
      }
    }
  }
  notifyFileDecorationsChanges(e) {
    if (!this.C) {
      return false;
    }
    const resource = toResource(this.y);
    if (!resource) {
      return false;
    }
    if (this.C.fileDecorations && e.affectsResource(resource)) {
      return this.Z({ updateIcon: false, updateDecoration: true });
    }
    return false;
  }
  notifyExtensionsRegistered() {
    this.Z({ updateIcon: true, updateDecoration: false });
  }
  notifyThemeChange() {
    this.Z({ updateIcon: false, updateDecoration: false });
  }
  notifyFileAssociationsChange() {
    this.Z({ updateIcon: true, updateDecoration: false });
  }
  notifyFormattersChange(scheme) {
    if (toResource(this.y)?.scheme === scheme) {
      this.Z({ updateIcon: false, updateDecoration: false });
    }
  }
  notifyUntitledLabelChange(resource) {
    if ($oh(resource, toResource(this.y))) {
      this.Z({ updateIcon: false, updateDecoration: false });
    }
  }
  notifyWorkspaceFoldersChange() {
    if (typeof this.H === "string") {
      const resource = toResource(this.y);
      if (URI.isUri(resource) && this.y?.name === this.H) {
        this.setFile(resource, this.C);
      }
    }
  }
  setFile(resource, options3) {
    const hideLabel = options3?.hideLabel;
    let name;
    if (!hideLabel) {
      if (options3?.fileKind === FileKind.ROOT_FOLDER) {
        const workspaceFolder = this.Q.getWorkspaceFolder(resource);
        if (workspaceFolder) {
          name = workspaceFolder.name;
          this.H = name;
        }
      }
      if (!name) {
        name = $1t($rh(resource));
      }
    }
    let description;
    if (!options3?.hidePath) {
      const descriptionCandidate = this.O.getUriLabel($uh(resource), { relative: true });
      if (descriptionCandidate && descriptionCandidate !== ".") {
        description = descriptionCandidate;
      }
    }
    this.setResource({ resource, name, description, range: options3?.range }, options3);
  }
  setResource(label3, options3 = /* @__PURE__ */ Object.create(null)) {
    const resource = toResource(label3);
    const isSideBySideEditor = label3?.resource && !URI.isUri(label3.resource);
    if (!options3.forceLabel && !isSideBySideEditor && resource?.scheme === Schemas.untitled) {
      const untitledModel = this.P.untitled.get(resource);
      if (untitledModel && !untitledModel.hasAssociatedFilePath) {
        if (typeof label3.name === "string") {
          label3.name = untitledModel.name;
        }
        if (typeof label3.description === "string") {
          const untitledDescription = untitledModel.resource.path;
          if (label3.name !== untitledDescription) {
            label3.description = untitledDescription;
          } else {
            label3.description = void 0;
          }
        }
        const untitledTitle = untitledModel.resource.path;
        if (untitledModel.name !== untitledTitle) {
          options3.title = `${untitledModel.name} \u2022 ${untitledTitle}`;
        } else {
          options3.title = untitledTitle;
        }
      }
    }
    if (!options3.forceLabel && !isSideBySideEditor && resource?.scheme === Schemas.vscodeNotebookCell) {
      const notebookDocument = this.R.getNotebook(resource);
      const cellIndex = notebookDocument?.getCellIndex(resource);
      if (notebookDocument && cellIndex !== void 0 && typeof label3.name === "string") {
        options3.title = localize(3047, null, label3.name, `${cellIndex + 1}`);
      }
      if (typeof label3.name === "string" && notebookDocument && cellIndex !== void 0 && typeof label3.name === "string") {
        label3.name = localize(3048, null, label3.name, `${cellIndex + 1}`);
      }
    }
    const hasResourceChanged = this.W(label3);
    const hasPathLabelChanged = hasResourceChanged || this.X(label3);
    const hasFileKindChanged = this.U(options3);
    const hasIconChanged = this.Y(options3);
    this.y = label3;
    this.C = options3;
    if (hasResourceChanged) {
      this.F = void 0;
    }
    if (hasPathLabelChanged) {
      this.G = void 0;
    }
    this.Z({
      updateIcon: hasResourceChanged || hasFileKindChanged || hasIconChanged,
      updateDecoration: hasResourceChanged || hasFileKindChanged
    });
  }
  U(newOptions) {
    const newFileKind = newOptions?.fileKind;
    const oldFileKind = this.C?.fileKind;
    return newFileKind !== oldFileKind;
  }
  W(newLabel) {
    const newResource = toResource(newLabel);
    const oldResource = toResource(this.y);
    if (newResource && oldResource) {
      return newResource.toString() !== oldResource.toString();
    }
    if (!newResource && !oldResource) {
      return false;
    }
    return true;
  }
  X(newLabel) {
    const newResource = toResource(newLabel);
    return !!newResource && this.G !== this.O.getUriLabel(newResource);
  }
  Y(newOptions) {
    return this.C?.icon !== newOptions?.icon;
  }
  clear() {
    this.y = void 0;
    this.C = void 0;
    this.F = void 0;
    this.D = void 0;
    this.G = void 0;
    this.setLabel("");
  }
  Z(options3) {
    if (this.J) {
      if (this.I !== Redraw.Full) {
        this.I = options3.updateIcon || options3.updateDecoration ? Redraw.Full : Redraw.Basic;
      }
      return false;
    }
    if (options3.updateIcon) {
      this.D = void 0;
    }
    if (!this.y) {
      return false;
    }
    const iconLabelOptions = {
      title: "",
      italic: this.C?.italic,
      strikethrough: this.C?.strikethrough,
      matches: this.C?.matches,
      descriptionMatches: this.C?.descriptionMatches,
      extraClasses: [],
      separator: this.C?.separator,
      domId: this.C?.domId,
      disabledCommand: this.C?.disabledCommand,
      labelEscapeNewLines: this.C?.labelEscapeNewLines,
      descriptionTitle: this.C?.descriptionTitle
    };
    const resource = toResource(this.y);
    if (this.C?.title !== void 0) {
      iconLabelOptions.title = this.C.title;
    }
    if (resource && resource.scheme !== Schemas.data && (!this.C?.title || typeof this.C.title !== "string" && !this.C.title.markdownNotSupportedFallback)) {
      if (!this.G) {
        this.G = this.O.getUriLabel(resource);
      }
      if (!iconLabelOptions.title || typeof iconLabelOptions.title === "string") {
        iconLabelOptions.title = this.G;
      } else if (!iconLabelOptions.title.markdownNotSupportedFallback) {
        iconLabelOptions.title.markdownNotSupportedFallback = this.G;
      }
    }
    if (this.C && !this.C.hideIcon) {
      if (!this.D) {
        this.D = $gdb(this.M, this.L, resource, this.C.fileKind, this.C.icon);
      }
      if (URI.isUri(this.C.icon)) {
        iconLabelOptions.iconPath = this.C.icon;
      }
      iconLabelOptions.extraClasses = this.D.slice(0);
    }
    if (this.C?.extraClasses) {
      iconLabelOptions.extraClasses.push(...this.C.extraClasses);
    }
    if (this.C?.fileDecorations && resource) {
      if (options3.updateDecoration) {
        this.z.value = this.N.getDecoration(resource, this.C.fileKind !== FileKind.FILE);
      }
      const decoration3 = this.z.value;
      if (decoration3) {
        if (decoration3.tooltip) {
          if (typeof iconLabelOptions.title === "string") {
            iconLabelOptions.title = `${iconLabelOptions.title} \u2022 ${decoration3.tooltip}`;
          } else if (typeof iconLabelOptions.title?.markdown === "string") {
            const title = `${iconLabelOptions.title.markdown} \u2022 ${decoration3.tooltip}`;
            iconLabelOptions.title = { markdown: title, markdownNotSupportedFallback: title };
          }
        }
        if (decoration3.strikethrough) {
          iconLabelOptions.strikethrough = true;
        }
        if (this.C.fileDecorations.colors) {
          iconLabelOptions.extraClasses.push(decoration3.labelClassName);
        }
        if (this.C.fileDecorations.badges) {
          iconLabelOptions.extraClasses.push(decoration3.badgeClassName);
          iconLabelOptions.extraClasses.push(decoration3.iconClassName);
        }
      }
    }
    if (this.y.range) {
      iconLabelOptions.suffix = this.y.range.startLineNumber !== this.y.range.endLineNumber ? `:${this.y.range.startLineNumber}-${this.y.range.endLineNumber}` : `:${this.y.range.startLineNumber}`;
    }
    this.setLabel(this.y.name ?? "", this.y.description, iconLabelOptions);
    this.w.fire();
    return true;
  }
  dispose() {
    super.dispose();
    this.y = void 0;
    this.C = void 0;
    this.F = void 0;
    this.D = void 0;
    this.G = void 0;
    this.H = void 0;
  }
};
ResourceLabelWidget = __decorate([
  __param(2, $1E),
  __param(3, $sG),
  __param(4, $jsb),
  __param(5, $ZI),
  __param(6, $cK),
  __param(7, $Zk),
  __param(8, $8L)
], ResourceLabelWidget);

// out-build/vs/workbench/contrib/codeEditor/browser/menuPreventer.js
var $Esb = class extends $3c {
  static {
    this.ID = "editor.contrib.menuPreventer";
  }
  constructor(editor) {
    super();
    this.a = editor;
    this.b = false;
    this.c = false;
    this.B(this.a.onMouseDown((e) => {
      if (this.b) {
        this.c = true;
      }
    }));
    this.B(this.a.onKeyDown((e) => {
      if (e.equals(
        512
        /* KeyMod.Alt */
      )) {
        if (!this.b) {
          this.c = false;
        }
        this.b = true;
      }
    }));
    this.B(this.a.onKeyUp((e) => {
      if (e.equals(
        512
        /* KeyMod.Alt */
      )) {
        if (this.c) {
          e.preventDefault();
        }
        this.b = false;
        this.c = false;
      }
    }));
  }
};
$85(
  $Esb.ID,
  $Esb,
  2
  /* EditorContributionInstantiation.BeforeFirstInteraction */
);

// out-build/vs/workbench/contrib/codeEditor/browser/selectionClipboard.js
var $Fsb = "editor.contrib.selectionClipboard";

// out-build/vs/workbench/contrib/snippets/browser/snippets.js
var $Isb = $Qk("snippetService");

// out-build/vs/workbench/contrib/snippets/browser/snippetsFile.js
var SnippetBodyInsights = class {
  constructor(body) {
    this.isBogous = false;
    this.isTrivial = false;
    this.usesClipboardVariable = false;
    this.usesSelectionVariable = false;
    this.codeSnippet = body;
    const textmateSnippet = new $0_().parse(body, false);
    const placeholders = /* @__PURE__ */ new Map();
    let placeholderMax = 0;
    for (const placeholder of textmateSnippet.placeholders) {
      placeholderMax = Math.max(placeholderMax, placeholder.index);
    }
    if (textmateSnippet.placeholders.length === 0) {
      this.isTrivial = true;
    } else if (placeholderMax === 0) {
      const last = textmateSnippet.children.at(-1);
      this.isTrivial = last instanceof $4_ && last.isFinalTabstop;
    }
    const stack = [...textmateSnippet.children];
    while (stack.length > 0) {
      const marker = stack.shift();
      if (marker instanceof $8_) {
        if (marker.children.length === 0 && !$scb[marker.name]) {
          const index = placeholders.has(marker.name) ? placeholders.get(marker.name) : ++placeholderMax;
          placeholders.set(marker.name, index);
          const synthetic = new $4_(index).appendChild(new $2_(marker.name));
          textmateSnippet.replace(marker, [synthetic]);
          this.isBogous = true;
        }
        switch (marker.name) {
          case "CLIPBOARD":
            this.usesClipboardVariable = true;
            break;
          case "SELECTION":
          case "TM_SELECTED_TEXT":
            this.usesSelectionVariable = true;
            break;
        }
      } else {
        stack.push(...marker.children);
      }
    }
    if (this.isBogous) {
      this.codeSnippet = textmateSnippet.toTextmateString();
    }
  }
};
var $Gsb = class {
  constructor(isFileTemplate, scopes, name, prefix, description, body, source, snippetSource, snippetIdentifier, extensionId) {
    this.isFileTemplate = isFileTemplate;
    this.scopes = scopes;
    this.name = name;
    this.prefix = prefix;
    this.description = description;
    this.body = body;
    this.source = source;
    this.snippetSource = snippetSource;
    this.snippetIdentifier = snippetIdentifier;
    this.extensionId = extensionId;
    this.prefixLow = prefix.toLowerCase();
    this.a = new $hj($Qj(), () => new SnippetBodyInsights(this.body));
  }
  get codeSnippet() {
    return this.a.value.codeSnippet;
  }
  get isBogous() {
    return this.a.value.isBogous;
  }
  get isTrivial() {
    return this.a.value.isTrivial;
  }
  get needsClipboard() {
    return this.a.value.usesClipboardVariable;
  }
  get usesSelection() {
    return this.a.value.usesSelectionVariable;
  }
};
function isJsonSerializedSnippet(thing) {
  return $Bg(thing) && Boolean(thing.body);
}
var SnippetSource;
(function(SnippetSource2) {
  SnippetSource2[SnippetSource2["User"] = 1] = "User";
  SnippetSource2[SnippetSource2["Workspace"] = 2] = "Workspace";
  SnippetSource2[SnippetSource2["Extension"] = 3] = "Extension";
})(SnippetSource || (SnippetSource = {}));
var $Hsb = class {
  constructor(source, location3, defaultScopes, b, c, d) {
    this.source = source;
    this.location = location3;
    this.defaultScopes = defaultScopes;
    this.b = b;
    this.c = c;
    this.d = d;
    this.data = [];
    this.isGlobalSnippets = $sc(location3.path) === ".code-snippets";
    this.isUserSnippets = !this.b;
  }
  select(selector, bucket) {
    if (this.isGlobalSnippets || !this.isUserSnippets) {
      this.f(selector, bucket);
    } else {
      this.e(selector, bucket);
    }
  }
  e(selector, bucket) {
    if (selector + ".json" === $rc(this.location.path)) {
      bucket.push(...this.data);
    }
  }
  f(selector, bucket) {
    for (const snippet of this.data) {
      const len = snippet.scopes.length;
      if (len === 0) {
        bucket.push(snippet);
      } else {
        for (let i2 = 0; i2 < len; i2++) {
          if (snippet.scopes[i2] === selector) {
            bucket.push(snippet);
            break;
          }
        }
      }
    }
    const idx = selector.lastIndexOf(".");
    if (idx >= 0) {
      this.f(selector.substring(0, idx), bucket);
    }
  }
  async g() {
    if (this.b) {
      return this.d.readExtensionResource(this.location);
    } else {
      const content = await this.c.readFile(this.location);
      return content.value.toString();
    }
  }
  load() {
    if (!this.a) {
      this.a = Promise.resolve(this.g()).then((content) => {
        const data = $yw(content);
        if ($Gw(data) === "object") {
          for (const [name, scopeOrTemplate] of Object.entries(data)) {
            if (isJsonSerializedSnippet(scopeOrTemplate)) {
              this.h(name, scopeOrTemplate, this.data);
            } else {
              for (const [name2, template] of Object.entries(scopeOrTemplate)) {
                this.h(name2, template, this.data);
              }
            }
          }
        }
        return this;
      });
    }
    return this.a;
  }
  reset() {
    this.a = void 0;
    this.data.length = 0;
  }
  h(name, snippet, bucket) {
    let { isFileTemplate, prefix, body, description } = snippet;
    if (!prefix) {
      prefix = "";
    }
    if (Array.isArray(body)) {
      body = body.join("\n");
    }
    if (typeof body !== "string") {
      return;
    }
    if (Array.isArray(description)) {
      description = description.join("\n");
    }
    let scopes;
    if (this.defaultScopes) {
      scopes = this.defaultScopes;
    } else if (typeof snippet.scope === "string") {
      scopes = snippet.scope.split(",").map((s) => s.trim()).filter(Boolean);
    } else {
      scopes = [];
    }
    let source;
    if (this.b) {
      source = this.b.displayName || this.b.name;
    } else if (this.source === 2) {
      source = localize(9883, null);
    } else {
      if (this.isGlobalSnippets) {
        source = localize(9884, null);
      } else {
        source = localize(9885, null);
      }
    }
    for (const _prefix of Iterable.wrap(prefix)) {
      bucket.push(new $Gsb(Boolean(isFileTemplate), scopes, name, _prefix, description, body, source, this.source, this.b ? `${$xh(this.b.extensionLocation, this.location)}/${name}` : `${$rc(this.location.path)}/${name}`, this.b?.identifier));
    }
  }
};

// out-build/vs/editor/common/services/languagesAssociations.js
var registeredAssociations = [];
var nonUserRegisteredAssociations = [];
var userRegisteredAssociations = [];
function $Jsb(association, warnOnOverwrite = false) {
  _registerLanguageAssociation(association, false, warnOnOverwrite);
}
function $Ksb(association) {
  _registerLanguageAssociation(association, true, false);
}
function _registerLanguageAssociation(association, userConfigured, warnOnOverwrite) {
  const associationItem = toLanguageAssociationItem(association, userConfigured);
  registeredAssociations.push(associationItem);
  if (!associationItem.userConfigured) {
    nonUserRegisteredAssociations.push(associationItem);
  } else {
    userRegisteredAssociations.push(associationItem);
  }
  if (warnOnOverwrite && !associationItem.userConfigured) {
    registeredAssociations.forEach((a) => {
      if (a.mime === associationItem.mime || a.userConfigured) {
        return;
      }
      if (associationItem.extension && a.extension === associationItem.extension) {
        console.warn(`Overwriting extension <<${associationItem.extension}>> to now point to mime <<${associationItem.mime}>>`);
      }
      if (associationItem.filename && a.filename === associationItem.filename) {
        console.warn(`Overwriting filename <<${associationItem.filename}>> to now point to mime <<${associationItem.mime}>>`);
      }
      if (associationItem.filepattern && a.filepattern === associationItem.filepattern) {
        console.warn(`Overwriting filepattern <<${associationItem.filepattern}>> to now point to mime <<${associationItem.mime}>>`);
      }
      if (associationItem.firstline && a.firstline === associationItem.firstline) {
        console.warn(`Overwriting firstline <<${associationItem.firstline}>> to now point to mime <<${associationItem.mime}>>`);
      }
    });
  }
}
function toLanguageAssociationItem(association, userConfigured) {
  return {
    id: association.id,
    mime: association.mime,
    filename: association.filename,
    extension: association.extension,
    filepattern: association.filepattern,
    firstline: association.firstline,
    userConfigured,
    filenameLowercase: association.filename ? association.filename.toLowerCase() : void 0,
    extensionLowercase: association.extension ? association.extension.toLowerCase() : void 0,
    filepatternLowercase: association.filepattern ? $Dl(association.filepattern.toLowerCase()) : void 0,
    filepatternOnPath: association.filepattern ? association.filepattern.indexOf($kc.sep) >= 0 : false
  };
}
function $Lsb() {
  registeredAssociations = registeredAssociations.filter((a) => a.userConfigured);
  nonUserRegisteredAssociations = [];
}
function $Msb() {
  registeredAssociations = registeredAssociations.filter((a) => !a.userConfigured);
  userRegisteredAssociations = [];
}
function $Nsb(resource, firstLine3) {
  return getAssociations(resource, firstLine3).map((item) => item.mime);
}
function $Osb(resource, firstLine3) {
  return getAssociations(resource, firstLine3).map((item) => item.id);
}
function getAssociations(resource, firstLine3) {
  let path;
  if (resource) {
    switch (resource.scheme) {
      case Schemas.file:
        path = resource.fsPath;
        break;
      case Schemas.data: {
        const metadata = DataUri.parseMetaData(resource);
        path = metadata.get(DataUri.META_DATA_LABEL);
        break;
      }
      case Schemas.vscodeNotebookCell:
        path = void 0;
        break;
      default:
        path = resource.path;
    }
  }
  if (!path) {
    return [{ id: "unknown", mime: $YC.unknown }];
  }
  path = path.toLowerCase();
  const filename = $rc(path);
  const configuredLanguage = getAssociationByPath(path, filename, userRegisteredAssociations);
  if (configuredLanguage) {
    return [configuredLanguage, { id: $KF, mime: $YC.text }];
  }
  const registeredLanguage = getAssociationByPath(path, filename, nonUserRegisteredAssociations);
  if (registeredLanguage) {
    return [registeredLanguage, { id: $KF, mime: $YC.text }];
  }
  if (firstLine3) {
    const firstlineLanguage = getAssociationByFirstline(firstLine3);
    if (firstlineLanguage) {
      return [firstlineLanguage, { id: $KF, mime: $YC.text }];
    }
  }
  return [{ id: "unknown", mime: $YC.unknown }];
}
function getAssociationByPath(path, filename, associations) {
  let filenameMatch = void 0;
  let patternMatch = void 0;
  let extensionMatch = void 0;
  for (let i2 = associations.length - 1; i2 >= 0; i2--) {
    const association = associations[i2];
    if (filename === association.filenameLowercase) {
      filenameMatch = association;
      break;
    }
    if (association.filepattern) {
      if (!patternMatch || association.filepattern.length > patternMatch.filepattern.length) {
        const target = association.filepatternOnPath ? path : filename;
        if (association.filepatternLowercase?.(target)) {
          patternMatch = association;
        }
      }
    }
    if (association.extension) {
      if (!extensionMatch || association.extension.length > extensionMatch.extension.length) {
        if (filename.endsWith(association.extensionLowercase)) {
          extensionMatch = association;
        }
      }
    }
  }
  if (filenameMatch) {
    return filenameMatch;
  }
  if (patternMatch) {
    return patternMatch;
  }
  if (extensionMatch) {
    return extensionMatch;
  }
  return void 0;
}
function getAssociationByFirstline(firstLine3) {
  if ($ng(firstLine3)) {
    firstLine3 = firstLine3.substr(1);
  }
  if (firstLine3.length > 0) {
    for (let i2 = registeredAssociations.length - 1; i2 >= 0; i2--) {
      const association = registeredAssociations[i2];
      if (!association.firstline) {
        continue;
      }
      const matches = firstLine3.match(association.firstline);
      if (matches && matches.length > 0) {
        return association;
      }
    }
  }
  return void 0;
}

// out-build/vs/editor/common/services/languagesRegistry.js
var hasOwnProperty3 = Object.prototype.hasOwnProperty;
var NULL_LANGUAGE_ID = "vs.editor.nullLanguage";
var $Psb = class {
  constructor() {
    this.e = [];
    this.f = /* @__PURE__ */ new Map();
    this.g(
      NULL_LANGUAGE_ID,
      0
      /* LanguageId.Null */
    );
    this.g(
      $KF,
      1
      /* LanguageId.PlainText */
    );
    this.c = 2;
  }
  g(language, languageId) {
    this.e[languageId] = language;
    this.f.set(language, languageId);
  }
  register(language) {
    if (this.f.has(language)) {
      return;
    }
    const languageId = this.c++;
    this.g(language, languageId);
  }
  encodeLanguageId(languageId) {
    return this.f.get(languageId) || 0;
  }
  decodeLanguageId(languageId) {
    return this.e[languageId] || NULL_LANGUAGE_ID;
  }
};
var $Qsb = class _$Qsb extends $3c {
  static {
    this.instanceCount = 0;
  }
  constructor(useModesRegistry = true, warnOnOverwrite = false) {
    super();
    this.c = this.B(new $ze());
    this.onDidChange = this.c.event;
    _$Qsb.instanceCount++;
    this.f = warnOnOverwrite;
    this.languageIdCodec = new $Psb();
    this.g = [];
    this.h = {};
    this.j = {};
    this.n = {};
    this.r = {};
    if (useModesRegistry) {
      this.s();
      this.B($JF.onDidChangeLanguages((m) => {
        this.s();
      }));
    }
  }
  dispose() {
    _$Qsb.instanceCount--;
    super.dispose();
  }
  setDynamicLanguages(def2) {
    this.g = def2;
    this.s();
  }
  s() {
    this.h = {};
    this.j = {};
    this.n = {};
    this.r = {};
    $Lsb();
    const desc = [].concat($JF.getLanguages()).concat(this.g);
    this._registerLanguages(desc);
  }
  registerLanguage(desc) {
    return $JF.registerLanguage(desc);
  }
  _registerLanguages(desc) {
    for (const d of desc) {
      this.t(d);
    }
    this.j = {};
    this.n = {};
    this.r = {};
    Object.keys(this.h).forEach((langId) => {
      const language = this.h[langId];
      if (language.name) {
        this.n[language.name] = language.identifier;
      }
      language.aliases.forEach((alias) => {
        this.r[alias.toLowerCase()] = language.identifier;
      });
      language.mimetypes.forEach((mimetype) => {
        this.j[mimetype] = language.identifier;
      });
    });
    $Wn.as($Ht.Configuration).registerOverrideIdentifiers(this.getRegisteredLanguageIds());
    this.c.fire();
  }
  t(lang) {
    const langId = lang.id;
    let resolvedLanguage;
    if (hasOwnProperty3.call(this.h, langId)) {
      resolvedLanguage = this.h[langId];
    } else {
      this.languageIdCodec.register(langId);
      resolvedLanguage = {
        identifier: langId,
        name: null,
        mimetypes: [],
        aliases: [],
        extensions: [],
        filenames: [],
        configurationFiles: [],
        icons: []
      };
      this.h[langId] = resolvedLanguage;
    }
    this.u(resolvedLanguage, lang);
  }
  u(resolvedLanguage, lang) {
    const langId = lang.id;
    let primaryMime = null;
    if (Array.isArray(lang.mimetypes) && lang.mimetypes.length > 0) {
      resolvedLanguage.mimetypes.push(...lang.mimetypes);
      primaryMime = lang.mimetypes[0];
    }
    if (!primaryMime) {
      primaryMime = `text/x-${langId}`;
      resolvedLanguage.mimetypes.push(primaryMime);
    }
    if (Array.isArray(lang.extensions)) {
      if (lang.configuration) {
        resolvedLanguage.extensions = lang.extensions.concat(resolvedLanguage.extensions);
      } else {
        resolvedLanguage.extensions = resolvedLanguage.extensions.concat(lang.extensions);
      }
      for (const extension of lang.extensions) {
        $Jsb({ id: langId, mime: primaryMime, extension }, this.f);
      }
    }
    if (Array.isArray(lang.filenames)) {
      for (const filename of lang.filenames) {
        $Jsb({ id: langId, mime: primaryMime, filename }, this.f);
        resolvedLanguage.filenames.push(filename);
      }
    }
    if (Array.isArray(lang.filenamePatterns)) {
      for (const filenamePattern of lang.filenamePatterns) {
        $Jsb({ id: langId, mime: primaryMime, filepattern: filenamePattern }, this.f);
      }
    }
    if (typeof lang.firstLine === "string" && lang.firstLine.length > 0) {
      let firstLineRegexStr = lang.firstLine;
      if (firstLineRegexStr.charAt(0) !== "^") {
        firstLineRegexStr = "^" + firstLineRegexStr;
      }
      try {
        const firstLineRegex = new RegExp(firstLineRegexStr);
        if (!$Kf(firstLineRegex)) {
          $Jsb({ id: langId, mime: primaryMime, firstline: firstLineRegex }, this.f);
        }
      } catch (err) {
        console.warn(`[${lang.id}]: Invalid regular expression \`${firstLineRegexStr}\`: `, err);
      }
    }
    resolvedLanguage.aliases.push(langId);
    let langAliases = null;
    if (typeof lang.aliases !== "undefined" && Array.isArray(lang.aliases)) {
      if (lang.aliases.length === 0) {
        langAliases = [null];
      } else {
        langAliases = lang.aliases;
      }
    }
    if (langAliases !== null) {
      for (const langAlias of langAliases) {
        if (!langAlias || langAlias.length === 0) {
          continue;
        }
        resolvedLanguage.aliases.push(langAlias);
      }
    }
    const containsAliases = langAliases !== null && langAliases.length > 0;
    if (containsAliases && langAliases[0] === null) {
    } else {
      const bestName = (containsAliases ? langAliases[0] : null) || langId;
      if (containsAliases || !resolvedLanguage.name) {
        resolvedLanguage.name = bestName;
      }
    }
    if (lang.configuration) {
      resolvedLanguage.configurationFiles.push(lang.configuration);
    }
    if (lang.icon) {
      resolvedLanguage.icons.push(lang.icon);
    }
  }
  isRegisteredLanguageId(languageId) {
    if (!languageId) {
      return false;
    }
    return hasOwnProperty3.call(this.h, languageId);
  }
  getRegisteredLanguageIds() {
    return Object.keys(this.h);
  }
  getSortedRegisteredLanguageNames() {
    const result = [];
    for (const languageName in this.n) {
      if (hasOwnProperty3.call(this.n, languageName)) {
        result.push({
          languageName,
          languageId: this.n[languageName]
        });
      }
    }
    result.sort((a, b) => $Vf(a.languageName, b.languageName));
    return result;
  }
  getLanguageName(languageId) {
    if (!hasOwnProperty3.call(this.h, languageId)) {
      return null;
    }
    return this.h[languageId].name;
  }
  getMimeType(languageId) {
    if (!hasOwnProperty3.call(this.h, languageId)) {
      return null;
    }
    const language = this.h[languageId];
    return language.mimetypes[0] || null;
  }
  getExtensions(languageId) {
    if (!hasOwnProperty3.call(this.h, languageId)) {
      return [];
    }
    return this.h[languageId].extensions;
  }
  getFilenames(languageId) {
    if (!hasOwnProperty3.call(this.h, languageId)) {
      return [];
    }
    return this.h[languageId].filenames;
  }
  getIcon(languageId) {
    if (!hasOwnProperty3.call(this.h, languageId)) {
      return null;
    }
    const language = this.h[languageId];
    return language.icons[0] || null;
  }
  getConfigurationFiles(languageId) {
    if (!hasOwnProperty3.call(this.h, languageId)) {
      return [];
    }
    return this.h[languageId].configurationFiles || [];
  }
  getLanguageIdByLanguageName(languageName) {
    const languageNameLower = languageName.toLowerCase();
    if (!hasOwnProperty3.call(this.r, languageNameLower)) {
      return null;
    }
    return this.r[languageNameLower];
  }
  getLanguageIdByMimeType(mimeType) {
    if (!mimeType) {
      return null;
    }
    if (hasOwnProperty3.call(this.j, mimeType)) {
      return this.j[mimeType];
    }
    return null;
  }
  guessLanguageIdByFilepathOrFirstLine(resource, firstLine3) {
    if (!resource && !firstLine3) {
      return [];
    }
    return $Osb(resource, firstLine3);
  }
};

// out-build/vs/editor/common/services/languageService.js
var $Rsb = class _$Rsb extends $3c {
  static {
    this.instanceCount = 0;
  }
  constructor(warnOnOverwrite = false) {
    super();
    this.c = this.B(new $ze());
    this.onDidRequestBasicLanguageFeatures = this.c.event;
    this.f = this.B(new $ze());
    this.onDidRequestRichLanguageFeatures = this.f.event;
    this.g = this.B(new $ze({
      leakWarningThreshold: 200
      /* https://github.com/microsoft/vscode/issues/119968 */
    }));
    this.onDidChange = this.g.event;
    this.h = /* @__PURE__ */ new Set();
    this.m = /* @__PURE__ */ new Set();
    _$Rsb.instanceCount++;
    this.n = this.B(new $Qsb(true, warnOnOverwrite));
    this.languageIdCodec = this.n.languageIdCodec;
    this.B(this.n.onDidChange(() => this.g.fire()));
  }
  dispose() {
    _$Rsb.instanceCount--;
    super.dispose();
  }
  registerLanguage(def2) {
    return this.n.registerLanguage(def2);
  }
  isRegisteredLanguageId(languageId) {
    return this.n.isRegisteredLanguageId(languageId);
  }
  getRegisteredLanguageIds() {
    return this.n.getRegisteredLanguageIds();
  }
  getSortedRegisteredLanguageNames() {
    return this.n.getSortedRegisteredLanguageNames();
  }
  getLanguageName(languageId) {
    return this.n.getLanguageName(languageId);
  }
  getMimeType(languageId) {
    return this.n.getMimeType(languageId);
  }
  getIcon(languageId) {
    return this.n.getIcon(languageId);
  }
  getExtensions(languageId) {
    return this.n.getExtensions(languageId);
  }
  getFilenames(languageId) {
    return this.n.getFilenames(languageId);
  }
  getConfigurationFiles(languageId) {
    return this.n.getConfigurationFiles(languageId);
  }
  getLanguageIdByLanguageName(languageName) {
    return this.n.getLanguageIdByLanguageName(languageName);
  }
  getLanguageIdByMimeType(mimeType) {
    return this.n.getLanguageIdByMimeType(mimeType);
  }
  guessLanguageIdByFilepathOrFirstLine(resource, firstLine3) {
    const languageIds = this.n.guessLanguageIdByFilepathOrFirstLine(resource, firstLine3);
    return languageIds.at(0) ?? null;
  }
  createById(languageId) {
    return new LanguageSelection(this.onDidChange, () => {
      return this.s(languageId);
    });
  }
  createByMimeType(mimeType) {
    return new LanguageSelection(this.onDidChange, () => {
      const languageId = this.getLanguageIdByMimeType(mimeType);
      return this.s(languageId);
    });
  }
  createByFilepathOrFirstLine(resource, firstLine3) {
    return new LanguageSelection(this.onDidChange, () => {
      const languageId = this.guessLanguageIdByFilepathOrFirstLine(resource, firstLine3);
      return this.s(languageId);
    });
  }
  s(languageId) {
    if (!languageId || !this.isRegisteredLanguageId(languageId)) {
      languageId = $KF;
    }
    return languageId;
  }
  requestBasicLanguageFeatures(languageId) {
    if (!this.h.has(languageId)) {
      this.h.add(languageId);
      this.c.fire(languageId);
    }
  }
  requestRichLanguageFeatures(languageId) {
    if (!this.m.has(languageId)) {
      this.m.add(languageId);
      this.requestBasicLanguageFeatures(languageId);
      $YE.getOrCreate(languageId);
      this.f.fire(languageId);
    }
  }
};
var LanguageSelection = class {
  constructor(onDidChangeLanguages, selector) {
    this.a = $Dd(this, onDidChangeLanguages, () => selector());
    this.onDidChange = Event2.fromObservable(this.a);
  }
  get languageId() {
    return this.a.get();
  }
};

// out-build/vs/workbench/services/language/common/languageService.js
var $Ssb = $tN.registerExtensionPoint({
  extensionPoint: "languages",
  jsonSchema: {
    description: localize(12983, null),
    type: "array",
    items: {
      type: "object",
      defaultSnippets: [{ body: { id: "${1:languageId}", aliases: ["${2:label}"], extensions: ["${3:extension}"], configuration: "./language-configuration.json" } }],
      properties: {
        id: {
          description: localize(12984, null),
          type: "string"
        },
        aliases: {
          description: localize(12985, null),
          type: "array",
          items: {
            type: "string"
          }
        },
        extensions: {
          description: localize(12986, null),
          default: [".foo"],
          type: "array",
          items: {
            type: "string"
          }
        },
        filenames: {
          description: localize(12987, null),
          type: "array",
          items: {
            type: "string"
          }
        },
        filenamePatterns: {
          description: localize(12988, null),
          type: "array",
          items: {
            type: "string"
          }
        },
        mimetypes: {
          description: localize(12989, null),
          type: "array",
          items: {
            type: "string"
          }
        },
        firstLine: {
          description: localize(12990, null),
          type: "string"
        },
        configuration: {
          description: localize(12991, null),
          type: "string",
          default: "./language-configuration.json"
        },
        icon: {
          type: "object",
          description: localize(12992, null),
          properties: {
            light: {
              description: localize(12993, null),
              type: "string"
            },
            dark: {
              description: localize(12994, null),
              type: "string"
            }
          }
        }
      }
    }
  },
  activationEventsGenerator: (languageContributions, result) => {
    for (const languageContribution of languageContributions) {
      if (languageContribution.id && languageContribution.configuration) {
        result.push(`onLanguage:${languageContribution.id}`);
      }
    }
  }
});
var LanguageTableRenderer = class extends $3c {
  constructor() {
    super(...arguments);
    this.type = "table";
  }
  shouldRender(manifest) {
    return !!manifest.contributes?.languages;
  }
  render(manifest) {
    const contributes = manifest.contributes;
    const rawLanguages = contributes?.languages || [];
    const languages = [];
    for (const l of rawLanguages) {
      if (isValidLanguageExtensionPoint(l)) {
        languages.push({
          id: l.id,
          name: (l.aliases || [])[0] || l.id,
          extensions: l.extensions || [],
          hasGrammar: false,
          hasSnippets: false
        });
      }
    }
    const byId = $Vb(languages, (l) => l.id);
    const grammars = contributes?.grammars || [];
    grammars.forEach((grammar) => {
      if (!$zg(grammar.language)) {
        return;
      }
      let language = byId[grammar.language];
      if (language) {
        language.hasGrammar = true;
      } else {
        language = { id: grammar.language, name: grammar.language, extensions: [], hasGrammar: true, hasSnippets: false };
        byId[language.id] = language;
        languages.push(language);
      }
    });
    const snippets = contributes?.snippets || [];
    snippets.forEach((snippet) => {
      if (!$zg(snippet.language)) {
        return;
      }
      let language = byId[snippet.language];
      if (language) {
        language.hasSnippets = true;
      } else {
        language = { id: snippet.language, name: snippet.language, extensions: [], hasGrammar: false, hasSnippets: true };
        byId[language.id] = language;
        languages.push(language);
      }
    });
    if (!languages.length) {
      return { data: { headers: [], rows: [] }, dispose: () => {
      } };
    }
    const headers = [
      localize(12995, null),
      localize(12996, null),
      localize(12997, null),
      localize(12998, null),
      localize(12999, null)
    ];
    const rows = languages.sort((a, b) => a.id.localeCompare(b.id)).map((l) => {
      return [
        l.id,
        l.name,
        new $bm().appendMarkdown(`${l.extensions.map((e) => `\`${e}\``).join("&nbsp;")}`),
        l.hasGrammar ? "\u2714\uFE0E" : "\u2014",
        l.hasSnippets ? "\u2714\uFE0E" : "\u2014"
      ];
    });
    return {
      data: {
        headers,
        rows
      },
      dispose: () => {
      }
    };
  }
};
$Wn.as(Extensions3.ExtensionFeaturesRegistry).registerExtensionFeature({
  id: "languages",
  label: localize(13e3, null),
  access: {
    canToggle: false
  },
  renderer: new $Nk(LanguageTableRenderer)
});
var $Tsb = class $Tsb2 extends $Rsb {
  constructor(extensionService, configurationService, environmentService, u) {
    super(environmentService.verbose || environmentService.isExtensionDevelopment || !environmentService.isBuilt);
    this.u = u;
    this.r = configurationService;
    this.t = extensionService;
    $Ssb.setHandler((extensions) => {
      const allValidLanguages = [];
      for (let i2 = 0, len = extensions.length; i2 < len; i2++) {
        const extension = extensions[i2];
        if (!Array.isArray(extension.value)) {
          extension.collector.error(localize(13001, null, $Ssb.name));
          continue;
        }
        for (let j = 0, lenJ = extension.value.length; j < lenJ; j++) {
          const ext = extension.value[j];
          if (isValidLanguageExtensionPoint(ext, extension.collector)) {
            let configuration2 = void 0;
            if (ext.configuration) {
              configuration2 = $vh(extension.description.extensionLocation, ext.configuration);
            }
            allValidLanguages.push({
              id: ext.id,
              extensions: ext.extensions,
              filenames: ext.filenames,
              filenamePatterns: ext.filenamePatterns,
              firstLine: ext.firstLine,
              aliases: ext.aliases,
              mimetypes: ext.mimetypes,
              configuration: configuration2,
              icon: ext.icon && {
                light: $vh(extension.description.extensionLocation, ext.icon.light),
                dark: $vh(extension.description.extensionLocation, ext.icon.dark)
              }
            });
          }
        }
      }
      this.n.setDynamicLanguages(allValidLanguages);
    });
    this.w();
    this.B(this.r.onDidChangeConfiguration((e) => {
      if (e.affectsConfiguration($Km)) {
        this.w();
      }
    }));
    this.t.whenInstalledExtensionsRegistered().then(() => {
      this.w();
    });
    this.B(this.onDidRequestRichLanguageFeatures((languageId) => {
      this.t.activateByEvent(`onLanguage:${languageId}`);
      this.t.activateByEvent(`onLanguage`);
    }));
  }
  w() {
    const configuration2 = this.r.getValue();
    $Msb();
    if (configuration2.files?.associations) {
      Object.keys(configuration2.files.associations).forEach((pattern) => {
        const langId = configuration2.files.associations[pattern];
        if (typeof langId !== "string") {
          this.u.warn(`Ignoring configured 'files.associations' for '${pattern}' because its type is not a string but '${typeof langId}'`);
          return;
        }
        const mimeType = this.getMimeType(langId) || `text/x-${langId}`;
        $Ksb({ id: langId, mime: mimeType, filepattern: pattern });
      });
    }
    this.g.fire();
  }
};
$Tsb = __decorate([
  __param(0, $wN),
  __param(1, $kl),
  __param(2, $Xk),
  __param(3, $wn)
], $Tsb);
function isUndefinedOrStringArray(value) {
  if (typeof value === "undefined") {
    return true;
  }
  if (!Array.isArray(value)) {
    return false;
  }
  return value.every((item) => typeof item === "string");
}
function isValidLanguageExtensionPoint(value, collector) {
  if (!value) {
    collector?.error(localize(13002, null, $Ssb.name));
    return false;
  }
  if (typeof value.id !== "string") {
    collector?.error(localize(13003, null, "id"));
    return false;
  }
  if (!isUndefinedOrStringArray(value.extensions)) {
    collector?.error(localize(13004, null, "extensions"));
    return false;
  }
  if (!isUndefinedOrStringArray(value.filenames)) {
    collector?.error(localize(13005, null, "filenames"));
    return false;
  }
  if (typeof value.firstLine !== "undefined" && typeof value.firstLine !== "string") {
    collector?.error(localize(13006, null, "firstLine"));
    return false;
  }
  if (typeof value.configuration !== "undefined" && typeof value.configuration !== "string") {
    collector?.error(localize(13007, null, "configuration"));
    return false;
  }
  if (!isUndefinedOrStringArray(value.aliases)) {
    collector?.error(localize(13008, null, "aliases"));
    return false;
  }
  if (!isUndefinedOrStringArray(value.mimetypes)) {
    collector?.error(localize(13009, null, "mimetypes"));
    return false;
  }
  if (typeof value.icon !== "undefined") {
    if (typeof value.icon !== "object" || typeof value.icon.light !== "string" || typeof value.icon.dark !== "string") {
      collector?.error(localize(13010, null, "icon", "light", "dark"));
      return false;
    }
  }
  return true;
}
$SC(
  $1E,
  $Tsb,
  0
  /* InstantiationType.Eager */
);

// out-build/vs/workbench/contrib/snippets/browser/snippetCompletionProvider.js
var markSnippetAsUsed = "_snippet.markAsUsed";
$tn.registerCommand(markSnippetAsUsed, (accessor, ...args2) => {
  const snippetsService = accessor.get($Isb);
  const [first] = args2;
  if (first instanceof $Gsb) {
    snippetsService.updateUsageTimestamp(first);
  }
});
var $Usb = class {
  constructor(snippet, range) {
    this.snippet = snippet;
    this.label = { label: snippet.prefix, description: snippet.name };
    this.detail = localize(9863, null, snippet.description || snippet.name, snippet.source);
    this.insertText = snippet.codeSnippet;
    this.extensionId = snippet.extensionId;
    this.range = range;
    this.sortText = `${snippet.snippetSource === 3 ? "z" : "a"}-${snippet.prefix}`;
    this.kind = 27;
    this.insertTextRules = 4;
    this.command = { id: markSnippetAsUsed, title: "", arguments: [snippet] };
  }
  resolve() {
    this.documentation = new $bm().appendCodeblock("", $0_.asInsertText(this.snippet.codeSnippet));
    return this;
  }
  static compareByLabel(a, b) {
    return $Tf(a.label.label, b.label.label);
  }
};
var $Vsb = class $Vsb2 {
  constructor(c, d, e) {
    this.c = c;
    this.d = d;
    this.e = e;
    this._debugDisplayName = "snippetCompletions";
  }
  async provideCompletionItems(model, position, context) {
    const sw = new $te();
    const line = position.lineNumber;
    const word = model.getWordAtPosition(position) ?? { startColumn: position.column, endColumn: position.column, word: "" };
    const lineContentLow = model.getLineContent(position.lineNumber).toLowerCase();
    const lineContentWithWordLow = lineContentLow.substring(0, word.startColumn + word.word.length - 1);
    const anchors = this.g(model, line, word, lineContentWithWordLow);
    const columnOffset = position.column - 1;
    const triggerCharacterLow = context.triggerCharacter?.toLowerCase() ?? "";
    const languageId = this.h(model, position);
    const languageConfig = this.e.getLanguageConfiguration(languageId);
    const snippets = new Set(await this.d.getSnippets(languageId));
    const suggestions = [];
    for (const snippet of snippets) {
      if (context.triggerKind === 1 && !snippet.prefixLow.startsWith(triggerCharacterLow)) {
        continue;
      }
      let candidate;
      for (const anchor of anchors) {
        if (anchor.prefixLow.match(/^\s/) && !snippet.prefixLow.match(/^\s/)) {
          continue;
        }
        if ($Vl(anchor.prefixLow, 0, anchor.prefixLow.length, snippet.prefixLow, 0, snippet.prefixLow.length)) {
          candidate = anchor;
          break;
        }
      }
      if (!candidate) {
        continue;
      }
      const pos = candidate.startColumn - 1;
      const prefixRestLen = snippet.prefixLow.length - (columnOffset - pos);
      const endsWithPrefixRest = $Uf(lineContentLow, snippet.prefixLow, columnOffset, columnOffset + prefixRestLen, columnOffset - pos);
      const startPosition = position.with(void 0, pos + 1);
      let endColumn = endsWithPrefixRest === 0 ? position.column + prefixRestLen : position.column;
      if (columnOffset < lineContentLow.length) {
        const autoClosingPairs = languageConfig.getAutoClosingPairs();
        const standardAutoClosingPairConditionals = autoClosingPairs.autoClosingPairsCloseSingleChar.get(lineContentLow[columnOffset]);
        if (standardAutoClosingPairConditionals?.some((p) => (
          // and the start position is the opening character of an autoclosing pair
          p.open === lineContentLow[startPosition.column - 1] && // and the snippet prefix contains the opening and closing pair at its edges
          snippet.prefix.startsWith(p.open) && snippet.prefix[snippet.prefix.length - 1] === p.close
        ))) {
          endColumn++;
        }
      }
      const replace = $9C.fromPositions({ lineNumber: line, column: candidate.startColumn }, { lineNumber: line, column: endColumn });
      const insert = replace.setEndPosition(line, position.column);
      suggestions.push(new $Usb(snippet, { replace, insert }));
      snippets.delete(snippet);
    }
    if (!triggerCharacterLow && (/\s/.test(lineContentLow[position.column - 2]) || !lineContentLow)) {
      for (const snippet of snippets) {
        const insert = $9C.fromPositions(position);
        const replace = lineContentLow.indexOf(snippet.prefixLow, columnOffset) === columnOffset ? insert.setEndPosition(position.lineNumber, position.column + snippet.prefixLow.length) : insert;
        suggestions.push(new $Usb(snippet, { replace, insert }));
      }
    }
    this.f(suggestions);
    return {
      suggestions,
      duration: sw.elapsed()
    };
  }
  f(suggestions) {
    suggestions.sort($Usb.compareByLabel);
    for (let i2 = 0; i2 < suggestions.length; i2++) {
      const item = suggestions[i2];
      let to = i2 + 1;
      for (; to < suggestions.length && item.label === suggestions[to].label; to++) {
        suggestions[to].label.label = localize(9864, null, suggestions[to].label.label, suggestions[to].snippet.name);
      }
      if (to > i2 + 1) {
        suggestions[i2].label.label = localize(9865, null, suggestions[i2].label.label, suggestions[i2].snippet.name);
        i2 = to;
      }
    }
  }
  resolveCompletionItem(item) {
    return item instanceof $Usb ? item.resolve() : item;
  }
  g(model, line, word, lineContentWithWordLow) {
    const result = [];
    for (let column = 1; column < word.startColumn; column++) {
      const wordInfo = model.getWordAtPosition(new $8C(line, column));
      result.push({
        startColumn: column,
        prefixLow: lineContentWithWordLow.substring(column - 1),
        isWord: Boolean(wordInfo)
      });
      if (wordInfo) {
        column = wordInfo.endColumn;
        result.push({
          startColumn: wordInfo.endColumn,
          prefixLow: lineContentWithWordLow.substring(wordInfo.endColumn - 1),
          isWord: false
        });
      }
    }
    if (word.word.length > 0 || result.length === 0) {
      result.push({
        startColumn: word.startColumn,
        prefixLow: lineContentWithWordLow.substring(word.startColumn - 1),
        isWord: true
      });
    }
    return result;
  }
  h(model, position) {
    model.tokenization.tokenizeIfCheap(position.lineNumber);
    let languageId = model.getLanguageIdAtPosition(position.lineNumber, position.column);
    if (!this.c.getLanguageName(languageId)) {
      languageId = model.getLanguageId();
    }
    return languageId;
  }
};
$Vsb = __decorate([
  __param(0, $1E),
  __param(1, $Isb),
  __param(2, $NF)
], $Vsb);

// out-build/vs/workbench/services/userDataProfile/common/userDataProfile.js
var $gT = $Qk("IUserDataProfileService");
var $hT = $Qk("IUserDataProfileManagementService");
var $jT = "profile";
function $kT(path, productService) {
  return URI.from({
    scheme: productService.urlProtocol,
    authority: $jT,
    path: path.startsWith("/") ? path : `/${path}`
  });
}
var $lT = "profile-";
function $mT(uri) {
  return uri.authority === $jT || new RegExp(`^${$lT}`).test(uri.authority);
}
var $nT = $Qk("IUserDataProfileImportExportService");
var $oT = $9r("defaultProfile-icon", $6l.settings, localize(13422, null));
var $pT = localize2(13424, "Profiles");
var $qT = { ...$pT };
var $rT = "code-profile";
var $sT = [{ name: localize(13423, null), extensions: [$rT] }];
var $tT = new $nn("currentProfile", "");
var $uT = new $nn("isCurrentProfileTransient", false);
var $vT = new $nn("hasProfiles", false);

// out-build/vs/workbench/contrib/snippets/browser/snippetsService.js
var SnippetEnablement_1;
var SnippetUsageTimestamps_1;
var snippetExt;
(function(snippetExt2) {
  function toValidSnippet(extension, snippet, languageService) {
    if ($vf(snippet.path)) {
      extension.collector.error(localize(9886, null, extension.description.name, String(snippet.path)));
      return null;
    }
    if ($vf(snippet.language) && !snippet.path.endsWith(".code-snippets")) {
      extension.collector.error(localize(9887, null, extension.description.name, String(snippet.path)));
      return null;
    }
    if (!$vf(snippet.language) && !languageService.isRegisteredLanguageId(snippet.language)) {
      extension.collector.error(localize(9888, null, extension.description.name, String(snippet.language)));
      return null;
    }
    const extensionLocation = extension.description.extensionLocation;
    const snippetLocation = $vh(extensionLocation, snippet.path);
    if (!$ph(snippetLocation, extensionLocation)) {
      extension.collector.error(localize(9889, null, extension.description.name, snippetLocation.path, extensionLocation.path));
      return null;
    }
    return {
      language: snippet.language,
      location: snippetLocation
    };
  }
  snippetExt2.toValidSnippet = toValidSnippet;
  snippetExt2.snippetsContribution = {
    description: localize(9890, null),
    type: "array",
    defaultSnippets: [{ body: [{ language: "", path: "" }] }],
    items: {
      type: "object",
      defaultSnippets: [{ body: { language: "${1:id}", path: "./snippets/${2:id}.json." } }],
      properties: {
        language: {
          description: localize(9891, null),
          type: "string"
        },
        path: {
          description: localize(9892, null),
          type: "string"
        }
      }
    }
  };
  snippetExt2.point = $tN.registerExtensionPoint({
    extensionPoint: "snippets",
    deps: [$Ssb],
    jsonSchema: snippetExt2.snippetsContribution
  });
})(snippetExt || (snippetExt = {}));
function watch(service, resource, callback) {
  return $Zc(service.watch(resource), service.onDidFilesChange((e) => {
    if (e.affects(resource)) {
      callback();
    }
  }));
}
var SnippetEnablement = class SnippetEnablement2 {
  static {
    SnippetEnablement_1 = this;
  }
  static {
    this.c = "snippets.ignoredSnippets";
  }
  constructor(f) {
    this.f = f;
    const raw = f.get(SnippetEnablement_1.c, 0, "");
    let data;
    try {
      data = JSON.parse(raw);
    } catch {
    }
    this.d = $Ag(data) ? new Set(data) : /* @__PURE__ */ new Set();
  }
  isIgnored(id2) {
    return this.d.has(id2);
  }
  updateIgnored(id2, value) {
    let changed = false;
    if (this.d.has(id2) && !value) {
      this.d.delete(id2);
      changed = true;
    } else if (!this.d.has(id2) && value) {
      this.d.add(id2);
      changed = true;
    }
    if (changed) {
      this.f.store(
        SnippetEnablement_1.c,
        JSON.stringify(Array.from(this.d)),
        0,
        0
        /* StorageTarget.USER */
      );
    }
  }
};
SnippetEnablement = SnippetEnablement_1 = __decorate([
  __param(0, $jv)
], SnippetEnablement);
var SnippetUsageTimestamps = class SnippetUsageTimestamps2 {
  static {
    SnippetUsageTimestamps_1 = this;
  }
  static {
    this.c = "snippets.usageTimestamps";
  }
  constructor(f) {
    this.f = f;
    const raw = f.get(SnippetUsageTimestamps_1.c, 0, "");
    let data;
    try {
      data = JSON.parse(raw);
    } catch {
      data = [];
    }
    this.d = Array.isArray(data) ? new Map(data) : /* @__PURE__ */ new Map();
  }
  getUsageTimestamp(id2) {
    return this.d.get(id2);
  }
  updateUsageTimestamp(id2) {
    this.d.delete(id2);
    this.d.set(id2, Date.now());
    const all = [...this.d].slice(-100);
    this.f.store(
      SnippetUsageTimestamps_1.c,
      JSON.stringify(all),
      0,
      0
      /* StorageTarget.USER */
    );
  }
};
SnippetUsageTimestamps = SnippetUsageTimestamps_1 = __decorate([
  __param(0, $jv)
], SnippetUsageTimestamps);
var $Wsb = class $Wsb2 {
  constructor(i2, j, k, l, m, n, o, p, lifecycleService, instantiationService, languageConfigurationService) {
    this.i = i2;
    this.j = j;
    this.k = k;
    this.l = l;
    this.m = m;
    this.n = n;
    this.o = o;
    this.p = p;
    this.c = new $2c();
    this.d = [];
    this.f = new $Ec();
    this.d.push(Promise.resolve(lifecycleService.when(
      3
      /* LifecyclePhase.Restored */
    ).then(() => {
      this.t();
      this.w();
      this.u();
    })));
    $ecb(new $Vsb(this.l, this, languageConfigurationService));
    this.g = instantiationService.createInstance(SnippetEnablement);
    this.h = instantiationService.createInstance(SnippetUsageTimestamps);
  }
  dispose() {
    this.c.dispose();
  }
  isEnabled(snippet) {
    return !this.g.isIgnored(snippet.snippetIdentifier);
  }
  updateEnablement(snippet, enabled) {
    this.g.updateIgnored(snippet.snippetIdentifier, !enabled);
  }
  updateUsageTimestamp(snippet) {
    this.h.updateUsageTimestamp(snippet.snippetIdentifier);
  }
  q() {
    const promises = this.d.slice(0);
    this.d.length = 0;
    return Promise.all(promises);
  }
  async getSnippetFiles() {
    await this.q();
    return this.f.values();
  }
  async getSnippets(languageId, opts) {
    await this.q();
    const result = [];
    const promises = [];
    if (languageId) {
      if (this.l.isRegisteredLanguageId(languageId)) {
        for (const file of this.f.values()) {
          promises.push(file.load().then((file2) => file2.select(languageId, result)).catch((err) => this.m.error(err, file.location.toString())));
        }
      }
    } else {
      for (const file of this.f.values()) {
        promises.push(file.load().then((file2) => $7b(result, result.length, file2.data)).catch((err) => this.m.error(err, file.location.toString())));
      }
    }
    await Promise.all(promises);
    return this.r(result, opts);
  }
  getSnippetsSync(languageId, opts) {
    const result = [];
    if (this.l.isRegisteredLanguageId(languageId)) {
      for (const file of this.f.values()) {
        file.load().catch((_err) => {
        });
        file.select(languageId, result);
      }
    }
    return this.r(result, opts);
  }
  r(snippets, opts) {
    const result = [];
    for (const snippet of snippets) {
      if (!snippet.prefix && !opts?.includeNoPrefixSnippets) {
        continue;
      }
      if (!this.isEnabled(snippet) && !opts?.includeDisabledSnippets) {
        continue;
      }
      if (typeof opts?.fileTemplateSnippets === "boolean" && opts.fileTemplateSnippets !== snippet.isFileTemplate) {
        continue;
      }
      result.push(snippet);
    }
    return result.sort((a, b) => {
      let result2 = 0;
      if (!opts?.noRecencySort) {
        const val1 = this.h.getUsageTimestamp(a.snippetIdentifier) ?? -1;
        const val2 = this.h.getUsageTimestamp(b.snippetIdentifier) ?? -1;
        result2 = val2 - val1;
      }
      if (result2 === 0) {
        result2 = this.s(a, b);
      }
      return result2;
    });
  }
  s(a, b) {
    if (a.snippetSource < b.snippetSource) {
      return -1;
    } else if (a.snippetSource > b.snippetSource) {
      return 1;
    } else if (a.source < b.source) {
      return -1;
    } else if (a.source > b.source) {
      return 1;
    } else if (a.name > b.name) {
      return 1;
    } else if (a.name < b.name) {
      return -1;
    } else {
      return 0;
    }
  }
  // --- loading, watching
  t() {
    snippetExt.point.setHandler((extensions) => {
      for (const [key2, value] of this.f) {
        if (value.source === 3) {
          this.f.delete(key2);
        }
      }
      for (const extension of extensions) {
        for (const contribution of extension.value) {
          const validContribution = snippetExt.toValidSnippet(extension, contribution, this.l);
          if (!validContribution) {
            continue;
          }
          const file = this.f.get(validContribution.location);
          if (file) {
            if (file.defaultScopes) {
              file.defaultScopes.push(validContribution.language);
            } else {
              file.defaultScopes = [];
            }
          } else {
            const file2 = new $Hsb(3, validContribution.location, validContribution.language ? [validContribution.language] : void 0, extension.description, this.n, this.p);
            this.f.set(file2.location, file2);
            if (this.i.isExtensionDevelopment) {
              file2.load().then((file3) => {
                if (file3.data.some((snippet) => snippet.isBogous)) {
                  extension.collector.warn(localize(9893, null, extension.description.name));
                }
              }, (err) => {
                extension.collector.warn(localize(9894, null, file2.location.toString()));
              });
            }
          }
        }
      }
    });
  }
  u() {
    const disposables = new $2c();
    const updateWorkspaceSnippets = () => {
      disposables.clear();
      this.d.push(this.v(this.k.getWorkspace(), disposables));
    };
    this.c.add(disposables);
    this.c.add(this.k.onDidChangeWorkspaceFolders(updateWorkspaceSnippets));
    this.c.add(this.k.onDidChangeWorkbenchState(updateWorkspaceSnippets));
    updateWorkspaceSnippets();
  }
  async v(workspace2, bucket) {
    const promises = workspace2.folders.map(async (folder) => {
      const snippetFolder = folder.toResource(".vscode");
      const value = await this.n.exists(snippetFolder);
      if (value) {
        this.x(2, snippetFolder, bucket);
      } else {
        bucket.add(this.n.onDidFilesChange((e) => {
          if (e.contains(
            snippetFolder,
            1
            /* FileChangeType.ADDED */
          )) {
            this.x(2, snippetFolder, bucket);
          }
        }));
      }
    });
    await Promise.all(promises);
  }
  async w() {
    const disposables = new $2c();
    const updateUserSnippets = async () => {
      disposables.clear();
      const userSnippetsFolder = this.j.currentProfile.snippetsHome;
      await this.n.createFolder(userSnippetsFolder);
      await this.x(1, userSnippetsFolder, disposables);
    };
    this.c.add(disposables);
    this.c.add(this.j.onDidChangeCurrentProfile((e) => e.join((async () => {
      this.d.push(updateUserSnippets());
    })())));
    await updateUserSnippets();
  }
  x(source, folder, bucket) {
    const disposables = new $2c();
    const addFolderSnippets = async () => {
      disposables.clear();
      if (!await this.n.exists(folder)) {
        return;
      }
      try {
        const stat = await this.n.resolve(folder);
        for (const entry of stat.children || []) {
          disposables.add(this.y(entry.resource, source));
        }
      } catch (err) {
        this.m.error(`Failed snippets from folder '${folder.toString()}'`, err);
      }
    };
    bucket.add(this.o.files.onDidSave((e) => {
      if ($ph(e.model.resource, folder)) {
        addFolderSnippets();
      }
    }));
    bucket.add(watch(this.n, folder, addFolderSnippets));
    bucket.add(disposables);
    return addFolderSnippets();
  }
  y(uri, source) {
    const ext = $th(uri);
    if (source === 1 && ext === ".json") {
      const langName = $sh(uri).replace(/\.json/, "");
      this.f.set(uri, new $Hsb(source, uri, [langName], void 0, this.n, this.p));
    } else if (ext === ".code-snippets") {
      this.f.set(uri, new $Hsb(source, uri, void 0, void 0, this.n, this.p));
    }
    return {
      dispose: () => this.f.delete(uri)
    };
  }
};
$Wsb = __decorate([
  __param(0, $Xk),
  __param(1, $gT),
  __param(2, $Zk),
  __param(3, $1E),
  __param(4, $wn),
  __param(5, $km),
  __param(6, $cK),
  __param(7, $Olb),
  __param(8, $KL),
  __param(9, $Pk),
  __param(10, $NF)
], $Wsb);
function $Xsb(model, position) {
  const MAX_PREFIX_LENGTH = 100;
  const line = model.getLineContent(position.lineNumber).substr(0, position.column - 1);
  const minChIndex = Math.max(0, line.length - MAX_PREFIX_LENGTH);
  for (let chIndex = line.length - 1; chIndex >= minChIndex; chIndex--) {
    const ch = line.charAt(chIndex);
    if (/\s/.test(ch)) {
      return line.substr(chIndex + 1);
    }
  }
  if (minChIndex === 0) {
    return line;
  }
  return "";
}

// out-build/vs/workbench/contrib/snippets/browser/tabCompletion.js
var $Ysb_1;
var $Ysb = class $Ysb2 {
  static {
    $Ysb_1 = this;
  }
  static {
    this.ID = "editor.tabCompletionController";
  }
  static {
    this.ContextKey = new $nn("hasSnippetCompletions", void 0);
  }
  static get(editor) {
    return editor.getContribution($Ysb_1.ID);
  }
  constructor(h3, i2, j, k, contextKeyService) {
    this.h = h3;
    this.i = i2;
    this.j = j;
    this.k = k;
    this.f = [];
    this.a = $Ysb_1.ContextKey.bindTo(contextKeyService);
    this.b = this.h.onDidChangeConfiguration((e) => {
      if (e.hasChanged(
        128
        /* EditorOption.tabCompletion */
      )) {
        this.l();
      }
    });
    this.l();
  }
  dispose() {
    this.b.dispose();
    this.d?.dispose();
  }
  l() {
    const enabled = this.h.getOption(
      128
      /* EditorOption.tabCompletion */
    ) === "onlySnippets";
    if (this.c !== enabled) {
      this.c = enabled;
      if (!this.c) {
        this.d?.dispose();
      } else {
        this.d = this.h.onDidChangeCursorSelection((e) => this.m());
        if (this.h.getModel()) {
          this.m();
        }
      }
    }
  }
  m() {
    this.f = [];
    this.g?.dispose();
    if (!this.h.hasModel()) {
      return;
    }
    const selection = this.h.getSelection();
    const model = this.h.getModel();
    model.tokenization.tokenizeIfCheap(selection.positionLineNumber);
    const id2 = model.getLanguageIdAtPosition(selection.positionLineNumber, selection.positionColumn);
    const snippets = this.i.getSnippetsSync(id2);
    if (!snippets) {
      this.a.set(false);
      return;
    }
    if ($9C.isEmpty(selection)) {
      const prefix = $Xsb(model, selection.getPosition());
      if (prefix) {
        for (const snippet of snippets) {
          if (prefix.endsWith(snippet.prefix)) {
            this.f.push(snippet);
          }
        }
      }
    } else if (!$9C.spansMultipleLines(selection) && model.getValueLengthInRange(selection) <= 100) {
      const selected = model.getValueInRange(selection);
      if (selected) {
        for (const snippet of snippets) {
          if (selected === snippet.prefix) {
            this.f.push(snippet);
          }
        }
      }
    }
    const len = this.f.length;
    if (len === 0) {
      this.a.set(false);
    } else if (len === 1) {
      this.a.set(true);
    } else {
      this.a.set(true);
      this.g = {
        _debugDisplayName: "tabCompletion",
        dispose: () => {
          registration.dispose();
        },
        provideCompletionItems: (_model, position) => {
          if (_model !== model || !selection.containsPosition(position)) {
            return;
          }
          const suggestions = this.f.map((snippet) => {
            const range = $9C.fromPositions(position.delta(0, -snippet.prefix.length), position);
            return new $Usb(snippet, range);
          });
          return { suggestions };
        }
      };
      const registration = this.k.completionProvider.register({ language: model.getLanguageId(), pattern: model.uri.fsPath, scheme: model.uri.scheme }, this.g);
    }
  }
  async performSnippetCompletions() {
    if (!this.h.hasModel()) {
      return;
    }
    if (this.f.length === 1) {
      const [snippet] = this.f;
      let clipboardText;
      if (snippet.needsClipboard) {
        const state = new $M_(
          this.h,
          1 | 4
          /* CodeEditorStateFlag.Position */
        );
        clipboardText = await this.j.readText();
        if (!state.validate(this.h)) {
          return;
        }
      }
      $Dcb.get(this.h)?.insert(snippet.codeSnippet, {
        overwriteBefore: snippet.prefix.length,
        overwriteAfter: 0,
        clipboardText
      });
    } else if (this.f.length > 1) {
      if (this.g) {
        $icb(this.h, this.g);
      }
    }
  }
};
$Ysb = $Ysb_1 = __decorate([
  __param(1, $Isb),
  __param(2, $30),
  __param(3, $mP),
  __param(4, $on)
], $Ysb);
$85(
  $Ysb.ID,
  $Ysb,
  0
  /* EditorContributionInstantiation.Eager */
);
var TabCompletionCommand = $Y5.bindToContribution($Ysb.get);
$45(new TabCompletionCommand({
  id: "insertSnippet",
  precondition: $Ysb.ContextKey,
  handler: (x) => x.performSnippetCompletions(),
  kbOpts: {
    weight: 100,
    kbExpr: $7m.and(EditorContextKeys.editorTextFocus, EditorContextKeys.tabDoesNotMoveFocus, $Dcb.InSnippetMode.toNegated()),
    primary: 2
    /* KeyCode.Tab */
  }
}));

// out-build/vs/workbench/contrib/codeEditor/browser/simpleEditorOptions.js
function $Zsb(configurationService) {
  return {
    wordWrap: "on",
    overviewRulerLanes: 0,
    glyphMargin: false,
    lineNumbers: "off",
    folding: false,
    selectOnLineNumbers: false,
    hideCursorInOverviewRuler: true,
    selectionHighlight: false,
    scrollbar: {
      horizontal: "hidden",
      alwaysConsumeMouseWheel: false
    },
    lineDecorationsWidth: 0,
    overviewRulerBorder: false,
    scrollBeyondLastLine: false,
    renderLineHighlight: "none",
    fixedOverflowWidgets: true,
    acceptSuggestionOnEnter: "smart",
    dragAndDrop: false,
    revealHorizontalRightPadding: 5,
    minimap: {
      enabled: false
    },
    guides: {
      indentation: false
    },
    accessibilitySupport: configurationService.getValue("editor.accessibilitySupport"),
    cursorBlinking: configurationService.getValue("editor.cursorBlinking"),
    experimentalEditContextEnabled: configurationService.getValue("editor.experimentalEditContextEnabled"),
    defaultColorDecorators: "never"
  };
}
function $1sb() {
  return {
    isSimpleWidget: true,
    contributions: EditorExtensionsRegistry.getSomeEditorContributions([
      $Esb.ID,
      $Fsb,
      $Mfb.ID,
      $qdb.ID,
      $Dcb.ID,
      $Ysb.ID
    ])
  };
}
function $2sb(editorContainerSelector) {
  return $ms((theme, collector) => {
    const selectionBackgroundColor = theme.getColor($mo);
    if (selectionBackgroundColor) {
      const inputBackgroundColor = theme.getColor($xq);
      if (inputBackgroundColor) {
        collector.addRule(`${editorContainerSelector} .monaco-editor-background { background-color: ${inputBackgroundColor}; } `);
        collector.addRule(`${editorContainerSelector} .monaco-editor .selected-text { background-color: ${inputBackgroundColor.transparent(0.4)}; }`);
      }
      const inputForegroundColor = theme.getColor($yq);
      if (inputForegroundColor) {
        collector.addRule(`${editorContainerSelector} .monaco-editor .view-line span.inline-selected-text { color: ${inputForegroundColor}; }`);
      }
      collector.addRule(`${editorContainerSelector} .monaco-editor .focused .selected-text { background-color: ${selectionBackgroundColor}; }`);
    } else {
      collector.addRule(`${editorContainerSelector} .monaco-editor .focused .selected-text { background-color: ${theme.getColor($7o)}; }`);
    }
  });
}

// out-build/vs/workbench/contrib/files/common/files.js
var $qtb_1;
var $3sb = "workbench.view.explorer";
var $4sb = "workbench.explorer.fileView";
var $5sb = new $nn("explorerViewletVisible", true, { type: "boolean", description: localize(7411, null) });
var $6sb = new $nn("foldersViewVisible", true, { type: "boolean", description: localize(7412, null) });
var $7sb = new $nn("explorerResourceIsFolder", false, { type: "boolean", description: localize(7413, null) });
var $8sb = new $nn("explorerResourceReadonly", false, { type: "boolean", description: localize(7414, null) });
var $9sb = $8sb.toNegated();
var $0sb = new $nn("explorerResourceParentReadonly", false, { type: "boolean", description: localize(7415, null) });
var $$sb = new $nn("explorerResourceAvailableEditorIds", "");
var $_sb = new $nn("explorerResourceIsRoot", false, { type: "boolean", description: localize(7416, null) });
var $atb = new $nn("explorerResourceCut", false, { type: "boolean", description: localize(7417, null) });
var $btb = new $nn("explorerResourceMoveableToTrash", false, { type: "boolean", description: localize(7418, null) });
var $ctb = new $nn("filesExplorerFocus", true, { type: "boolean", description: localize(7419, null) });
var $dtb = new $nn("openEditorsFocus", true, { type: "boolean", description: localize(7420, null) });
var $etb = new $nn("explorerViewletFocus", true, { type: "boolean", description: localize(7421, null) });
var $ftb = new $nn("explorerFindProviderActive", false, { type: "boolean", description: localize(7422, null) });
var $gtb = new $nn("explorerViewletCompressedFocus", true, { type: "boolean", description: localize(7423, null) });
var $htb = new $nn("explorerViewletCompressedFirstFocus", true, { type: "boolean", description: localize(7424, null) });
var $itb = new $nn("explorerViewletCompressedLastFocus", true, { type: "boolean", description: localize(7425, null) });
var $jtb = new $nn("viewHasSomeCollapsibleItem", false, { type: "boolean", description: localize(7426, null) });
var $ktb = $7m.and($6sb, $ctb, $7m.not($Beb));
var $ltb = $7m.and($6sb, $etb, $7m.not($Beb));
var $mtb = "workbench.editors.files.textFileEditor";
var $ntb = "workbench.editors.files.fileEditorInput";
var $otb = "workbench.editors.files.binaryFileEditor";
var $ptb = "code-text-binary";
var SortOrder2;
(function(SortOrder3) {
  SortOrder3["Default"] = "default";
  SortOrder3["Mixed"] = "mixed";
  SortOrder3["FilesFirst"] = "filesFirst";
  SortOrder3["Type"] = "type";
  SortOrder3["Modified"] = "modified";
  SortOrder3["FoldersNestsFiles"] = "foldersNestsFiles";
})(SortOrder2 || (SortOrder2 = {}));
var UndoConfirmLevel;
(function(UndoConfirmLevel2) {
  UndoConfirmLevel2["Verbose"] = "verbose";
  UndoConfirmLevel2["Default"] = "default";
  UndoConfirmLevel2["Light"] = "light";
})(UndoConfirmLevel || (UndoConfirmLevel = {}));
var LexicographicOptions;
(function(LexicographicOptions2) {
  LexicographicOptions2["Default"] = "default";
  LexicographicOptions2["Upper"] = "upper";
  LexicographicOptions2["Lower"] = "lower";
  LexicographicOptions2["Unicode"] = "unicode";
})(LexicographicOptions || (LexicographicOptions = {}));
var $qtb = $qtb_1 = class $qtb2 extends $3c {
  constructor(b, c, f, g) {
    super();
    this.b = b;
    this.c = c;
    this.f = f;
    this.g = g;
    this.a = this.B(new $4c());
  }
  static async open(resource, scheme, label3, editorService, options3) {
    await editorService.openEditor({
      original: { resource: $qtb_1.h(scheme, resource) },
      modified: { resource },
      label: label3,
      options: options3
    });
  }
  static h(scheme, resource) {
    return resource.with({ scheme, query: JSON.stringify({ scheme: resource.scheme, query: resource.query }) });
  }
  static j(resource) {
    const { scheme, query } = JSON.parse(resource.query);
    return resource.with({ scheme, query });
  }
  async provideTextContent(resource) {
    if (!resource.query) {
      return null;
    }
    const savedFileResource = $qtb_1.j(resource);
    const codeEditorModel = await this.m(resource);
    if (!this.a.value) {
      const disposables = new $2c();
      this.a.value = disposables;
      disposables.add(this.c.onDidFilesChange((changes) => {
        if (changes.contains(
          savedFileResource,
          0
          /* FileChangeType.UPDATED */
        )) {
          this.m(
            resource,
            false
            /* do not create if missing */
          );
        }
      }));
      if (codeEditorModel) {
        disposables.add(Event2.once(codeEditorModel.onWillDispose)(() => this.a.clear()));
      }
    }
    return codeEditorModel;
  }
  async m(resource, createAsNeeded = true) {
    const savedFileResource = $qtb_1.j(resource);
    const content = await this.b.readStream(savedFileResource);
    let codeEditorModel = this.g.getModel(resource);
    if (codeEditorModel) {
      this.g.updateModel(codeEditorModel, content.value);
    } else if (createAsNeeded) {
      const textFileModel = this.g.getModel(savedFileResource);
      let languageSelector;
      if (textFileModel) {
        languageSelector = this.f.createById(textFileModel.getLanguageId());
      } else {
        languageSelector = this.f.createByFilepathOrFirstLine(savedFileResource);
      }
      codeEditorModel = this.g.createModel(content.value, languageSelector, resource);
    }
    return codeEditorModel;
  }
};
$qtb = $qtb_1 = __decorate([
  __param(0, $cK),
  __param(1, $km),
  __param(2, $1E),
  __param(3, $sG)
], $qtb);
var $rtb = class _$rtb {
  static {
    this.b = 0;
  }
  constructor(c, d) {
    this.c = c;
    this.d = d;
    this.a = _$rtb.b++;
  }
  get editor() {
    return this.c;
  }
  get group() {
    return this.d;
  }
  get groupId() {
    return this.d.id;
  }
  getId() {
    return `openeditor:${this.groupId}:${this.a}`;
  }
  isPreview() {
    return !this.d.isPinned(this.editor);
  }
  isSticky() {
    return this.d.isSticky(this.editor);
  }
  getResource() {
    return $mL.getOriginalUri(this.editor, { supportSideBySide: SideBySideEditor.PRIMARY });
  }
};

// out-build/vs/workbench/services/host/browser/host.js
var $S4 = $Qk("hostService");

// out-build/vs/workbench/contrib/files/browser/fileConstants.js
var $stb = "revealInExplorer";
var $ttb = "workbench.action.files.revert";
var $utb = "explorer.openToSide";
var $vtb = "explorer.openWith";
var $wtb = "selectForCompare";
var $xtb = "compareSelected";
var $ytb = "compareFiles";
var $ztb = "workbench.files.action.compareWithSaved";
var $Atb = "copyFilePath";
var $Btb = "copyRelativeFilePath";
var $Ctb = "workbench.action.files.saveAs";
var $Dtb = localize2(7222, "Save As...");
var $Etb = "workbench.action.files.save";
var $Ftb = localize2(7223, "Save");
var $Gtb = "workbench.action.files.saveWithoutFormatting";
var $Htb = localize2(7224, "Save without Formatting");
var $Itb = "saveAll";
var $Jtb = localize2(7225, "Save All");
var $Ktb = "workbench.files.action.saveAllInGroup";
var $Ltb = "workbench.action.files.saveFiles";
var $Mtb = new $nn("groupFocusedInOpenEditors", false);
var $Ntb = new $nn("dirtyEditorFocusedInOpenEditors", false);
var $Otb = new $nn("readonlyEditorFocusedInOpenEditors", false);
var $Ptb = new $nn("openEditorsSelectedFileOrUntitled", true);
var $Qtb = new $nn("resourceSelectedForCompare", false);
var $Rtb = "removeRootFolder";
var $Stb = localize(7221, null);
var $Ttb = "previousCompressedFolder";
var $Utb = "nextCompressedFolder";
var $Vtb = "firstCompressedFolder";
var $Wtb = "lastCompressedFolder";
var $Xtb = "workbench.action.files.newUntitledFile";
var $Ytb = localize2(7226, "New Untitled Text File");
var $Ztb = "workbench.action.files.newFile";

// out-build/vs/platform/editor/common/editor.js
function $wl(model) {
  const candidate = model;
  return typeof candidate?.resolve === "function" && typeof candidate?.isResolved === "function";
}
var EditorActivation;
(function(EditorActivation2) {
  EditorActivation2[EditorActivation2["ACTIVATE"] = 1] = "ACTIVATE";
  EditorActivation2[EditorActivation2["RESTORE"] = 2] = "RESTORE";
  EditorActivation2[EditorActivation2["PRESERVE"] = 3] = "PRESERVE";
})(EditorActivation || (EditorActivation = {}));
var EditorResolution;
(function(EditorResolution2) {
  EditorResolution2[EditorResolution2["PICK"] = 0] = "PICK";
  EditorResolution2[EditorResolution2["EXCLUSIVE_ONLY"] = 1] = "EXCLUSIVE_ONLY";
})(EditorResolution || (EditorResolution = {}));
var EditorOpenSource;
(function(EditorOpenSource2) {
  EditorOpenSource2[EditorOpenSource2["API"] = 0] = "API";
  EditorOpenSource2[EditorOpenSource2["USER"] = 1] = "USER";
})(EditorOpenSource || (EditorOpenSource = {}));
var TextEditorSelectionRevealType;
(function(TextEditorSelectionRevealType2) {
  TextEditorSelectionRevealType2[TextEditorSelectionRevealType2["Center"] = 0] = "Center";
  TextEditorSelectionRevealType2[TextEditorSelectionRevealType2["CenterIfOutsideViewport"] = 1] = "CenterIfOutsideViewport";
  TextEditorSelectionRevealType2[TextEditorSelectionRevealType2["NearTop"] = 2] = "NearTop";
  TextEditorSelectionRevealType2[TextEditorSelectionRevealType2["NearTopIfOutsideViewport"] = 3] = "NearTopIfOutsideViewport";
})(TextEditorSelectionRevealType || (TextEditorSelectionRevealType = {}));
var TextEditorSelectionSource;
(function(TextEditorSelectionSource2) {
  TextEditorSelectionSource2["PROGRAMMATIC"] = "api";
  TextEditorSelectionSource2["NAVIGATION"] = "code.navigation";
  TextEditorSelectionSource2["JUMP"] = "code.jump";
})(TextEditorSelectionSource || (TextEditorSelectionSource = {}));
function $xl(uriIdentityService, diff1, diff22) {
  return diff1?.documentVersion === diff22?.documentVersion && uriIdentityService.extUri.isEqual(diff1?.original, diff22?.original) && uriIdentityService.extUri.isEqual(diff1?.modified, diff22?.modified) && $zb(diff1?.changes, diff22?.changes, (a, b) => {
    return a[0] === b[0] && a[1] === b[1] && a[2] === b[2] && a[3] === b[3];
  });
}

// out-build/vs/platform/quickinput/browser/pickerQuickAccess.js
var TriggerAction;
(function(TriggerAction2) {
  TriggerAction2[TriggerAction2["NO_ACTION"] = 0] = "NO_ACTION";
  TriggerAction2[TriggerAction2["CLOSE_PICKER"] = 1] = "CLOSE_PICKER";
  TriggerAction2[TriggerAction2["REFRESH_PICKER"] = 2] = "REFRESH_PICKER";
  TriggerAction2[TriggerAction2["REMOVE_ITEM"] = 3] = "REMOVE_ITEM";
})(TriggerAction || (TriggerAction = {}));
function isPicksWithActive(obj) {
  const candidate = obj;
  return Array.isArray(candidate.items);
}
function isFastAndSlowPicks(obj) {
  const candidate = obj;
  return !!candidate.picks && candidate.additionalPicks instanceof Promise;
}
var $rhb = class extends $3c {
  constructor(c, f) {
    super();
    this.c = c;
    this.f = f;
  }
  provide(picker, token, runOptions2) {
    const disposables = new $2c();
    picker.canAcceptInBackground = !!this.f?.canAcceptInBackground;
    picker.matchOnLabel = picker.matchOnDescription = picker.matchOnDetail = picker.sortByLabel = false;
    let picksCts = void 0;
    const picksDisposable = disposables.add(new $4c());
    const updatePickerItems = async () => {
      const picksDisposables = picksDisposable.value = new $2c();
      picksCts?.dispose(true);
      picker.busy = false;
      picksCts = new $ad(token);
      const picksToken = picksCts.token;
      let picksFilter = picker.value.substring(this.c.length);
      if (!this.f?.shouldSkipTrimPickFilter) {
        picksFilter = picksFilter.trim();
      }
      const providedPicks = this.g(picksFilter, picksDisposables, picksToken, runOptions2);
      const applyPicks = (picks, skipEmpty) => {
        let items;
        let activeItem = void 0;
        if (isPicksWithActive(picks)) {
          items = picks.items;
          activeItem = picks.active;
        } else {
          items = picks;
        }
        if (items.length === 0) {
          if (skipEmpty) {
            return false;
          }
          if ((picksFilter.length > 0 || picker.hideInput) && this.f?.noResultsPick) {
            if ($Ng(this.f.noResultsPick)) {
              items = [this.f.noResultsPick(picksFilter)];
            } else {
              items = [this.f.noResultsPick];
            }
          }
        }
        picker.items = items;
        if (activeItem) {
          picker.activeItems = [activeItem];
        }
        return true;
      };
      const applyFastAndSlowPicks = async (fastAndSlowPicks) => {
        let fastPicksApplied = false;
        let slowPicksApplied = false;
        await Promise.all([
          // Fast Picks: if `mergeDelay` is configured, in order to reduce
          // amount of flicker, we race against the slow picks over some delay
          // and then set the fast picks.
          // If the slow picks are faster, we reduce the flicker by only
          // setting the items once.
          (async () => {
            if (typeof fastAndSlowPicks.mergeDelay === "number") {
              await $Wh(fastAndSlowPicks.mergeDelay);
              if (picksToken.isCancellationRequested) {
                return;
              }
            }
            if (!slowPicksApplied) {
              fastPicksApplied = applyPicks(
                fastAndSlowPicks.picks,
                true
                /* skip over empty to reduce flicker */
              );
            }
          })(),
          // Slow Picks: we await the slow picks and then set them at
          // once together with the fast picks, but only if we actually
          // have additional results.
          (async () => {
            picker.busy = true;
            try {
              const awaitedAdditionalPicks = await fastAndSlowPicks.additionalPicks;
              if (picksToken.isCancellationRequested) {
                return;
              }
              let picks;
              let activePick = void 0;
              if (isPicksWithActive(fastAndSlowPicks.picks)) {
                picks = fastAndSlowPicks.picks.items;
                activePick = fastAndSlowPicks.picks.active;
              } else {
                picks = fastAndSlowPicks.picks;
              }
              let additionalPicks;
              let additionalActivePick = void 0;
              if (isPicksWithActive(awaitedAdditionalPicks)) {
                additionalPicks = awaitedAdditionalPicks.items;
                additionalActivePick = awaitedAdditionalPicks.active;
              } else {
                additionalPicks = awaitedAdditionalPicks;
              }
              if (additionalPicks.length > 0 || !fastPicksApplied) {
                let fallbackActivePick = void 0;
                if (!activePick && !additionalActivePick) {
                  const fallbackActivePickCandidate = picker.activeItems[0];
                  if (fallbackActivePickCandidate && picks.indexOf(fallbackActivePickCandidate) !== -1) {
                    fallbackActivePick = fallbackActivePickCandidate;
                  }
                }
                applyPicks({
                  items: [...picks, ...additionalPicks],
                  active: activePick || additionalActivePick || fallbackActivePick
                });
              }
            } finally {
              if (!picksToken.isCancellationRequested) {
                picker.busy = false;
              }
              slowPicksApplied = true;
            }
          })()
        ]);
      };
      if (providedPicks === null) {
      } else if (isFastAndSlowPicks(providedPicks)) {
        await applyFastAndSlowPicks(providedPicks);
      } else if (!(providedPicks instanceof Promise)) {
        applyPicks(providedPicks);
      } else {
        picker.busy = true;
        try {
          const awaitedPicks = await providedPicks;
          if (picksToken.isCancellationRequested) {
            return;
          }
          if (isFastAndSlowPicks(awaitedPicks)) {
            await applyFastAndSlowPicks(awaitedPicks);
          } else {
            applyPicks(awaitedPicks);
          }
        } finally {
          if (!picksToken.isCancellationRequested) {
            picker.busy = false;
          }
        }
      }
    };
    disposables.add(picker.onDidChangeValue(() => updatePickerItems()));
    updatePickerItems();
    disposables.add(picker.onDidAccept((event) => {
      if (runOptions2?.handleAccept) {
        if (!event.inBackground) {
          picker.hide();
        }
        runOptions2.handleAccept?.(picker.activeItems[0], event.inBackground);
        return;
      }
      const [item] = picker.selectedItems;
      if (typeof item?.accept === "function") {
        if (!event.inBackground) {
          picker.hide();
        }
        item.accept(picker.keyMods, event);
      }
    }));
    const buttonTrigger = async (button, item) => {
      if (typeof item.trigger !== "function") {
        return;
      }
      const buttonIndex = item.buttons?.indexOf(button) ?? -1;
      if (buttonIndex >= 0) {
        const result = item.trigger(buttonIndex, picker.keyMods);
        const action = typeof result === "number" ? result : await result;
        if (token.isCancellationRequested) {
          return;
        }
        switch (action) {
          case TriggerAction.NO_ACTION:
            break;
          case TriggerAction.CLOSE_PICKER:
            picker.hide();
            break;
          case TriggerAction.REFRESH_PICKER:
            updatePickerItems();
            break;
          case TriggerAction.REMOVE_ITEM: {
            const index = picker.items.indexOf(item);
            if (index !== -1) {
              const items = picker.items.slice();
              const removed = items.splice(index, 1);
              const activeItems = picker.activeItems.filter((activeItem) => activeItem !== removed[0]);
              const keepScrollPositionBefore = picker.keepScrollPosition;
              picker.keepScrollPosition = true;
              picker.items = items;
              if (activeItems) {
                picker.activeItems = activeItems;
              }
              picker.keepScrollPosition = keepScrollPositionBefore;
            }
            break;
          }
        }
      }
    };
    disposables.add(picker.onDidTriggerItemButton(({ button, item }) => buttonTrigger(button, item)));
    disposables.add(picker.onDidTriggerSeparatorButton(({ button, separator }) => buttonTrigger(button, separator)));
    return disposables;
  }
};

// out-build/vs/base/common/comparers.js
var intlFileNameCollatorBaseNumeric = new $sf(() => {
  const collator = new Intl.Collator(void 0, { numeric: true, sensitivity: "base" });
  return {
    collator,
    collatorIsNumeric: collator.resolvedOptions().numeric
  };
});
var intlFileNameCollatorNumeric = new $sf(() => {
  const collator = new Intl.Collator(void 0, { numeric: true });
  return {
    collator
  };
});
var intlFileNameCollatorNumericCaseInsensitive = new $sf(() => {
  const collator = new Intl.Collator(void 0, { numeric: true, sensitivity: "accent" });
  return {
    collator
  };
});
function $EM(one, other, caseSensitive = false) {
  const a = one || "";
  const b = other || "";
  const result = intlFileNameCollatorBaseNumeric.value.collator.compare(a, b);
  if (intlFileNameCollatorBaseNumeric.value.collatorIsNumeric && result === 0 && a !== b) {
    return a < b ? -1 : 1;
  }
  return result;
}
function $FM(one, other) {
  const collatorNumeric = intlFileNameCollatorNumeric.value.collator;
  one = one || "";
  other = other || "";
  return compareAndDisambiguateByLength(collatorNumeric, one, other);
}
function $GM(one, other) {
  const collatorNumeric = intlFileNameCollatorNumeric.value.collator;
  one = one || "";
  other = other || "";
  return compareCaseUpperFirst(one, other) || compareAndDisambiguateByLength(collatorNumeric, one, other);
}
function $HM(one, other) {
  const collatorNumeric = intlFileNameCollatorNumeric.value.collator;
  one = one || "";
  other = other || "";
  return compareCaseLowerFirst(one, other) || compareAndDisambiguateByLength(collatorNumeric, one, other);
}
function $IM(one, other) {
  one = one || "";
  other = other || "";
  if (one === other) {
    return 0;
  }
  return one < other ? -1 : 1;
}
function $JM(one, other) {
  const [oneName, oneExtension] = extractNameAndExtension(one);
  const [otherName, otherExtension] = extractNameAndExtension(other);
  let result = intlFileNameCollatorBaseNumeric.value.collator.compare(oneExtension, otherExtension);
  if (result === 0) {
    if (intlFileNameCollatorBaseNumeric.value.collatorIsNumeric && oneExtension !== otherExtension) {
      return oneExtension < otherExtension ? -1 : 1;
    }
    result = intlFileNameCollatorBaseNumeric.value.collator.compare(oneName, otherName);
    if (intlFileNameCollatorBaseNumeric.value.collatorIsNumeric && result === 0 && oneName !== otherName) {
      return oneName < otherName ? -1 : 1;
    }
  }
  return result;
}
function $KM(one, other) {
  one = one || "";
  other = other || "";
  const oneExtension = extractExtension(one);
  const otherExtension = extractExtension(other);
  const collatorNumeric = intlFileNameCollatorNumeric.value.collator;
  const collatorNumericCaseInsensitive = intlFileNameCollatorNumericCaseInsensitive.value.collator;
  return compareAndDisambiguateByLength(collatorNumericCaseInsensitive, oneExtension, otherExtension) || compareAndDisambiguateByLength(collatorNumeric, one, other);
}
function $LM(one, other) {
  one = one || "";
  other = other || "";
  const oneExtension = extractExtension(one);
  const otherExtension = extractExtension(other);
  const collatorNumeric = intlFileNameCollatorNumeric.value.collator;
  const collatorNumericCaseInsensitive = intlFileNameCollatorNumericCaseInsensitive.value.collator;
  return compareAndDisambiguateByLength(collatorNumericCaseInsensitive, oneExtension, otherExtension) || compareCaseUpperFirst(one, other) || compareAndDisambiguateByLength(collatorNumeric, one, other);
}
function $MM(one, other) {
  one = one || "";
  other = other || "";
  const oneExtension = extractExtension(one);
  const otherExtension = extractExtension(other);
  const collatorNumeric = intlFileNameCollatorNumeric.value.collator;
  const collatorNumericCaseInsensitive = intlFileNameCollatorNumericCaseInsensitive.value.collator;
  return compareAndDisambiguateByLength(collatorNumericCaseInsensitive, oneExtension, otherExtension) || compareCaseLowerFirst(one, other) || compareAndDisambiguateByLength(collatorNumeric, one, other);
}
function $NM(one, other) {
  one = one || "";
  other = other || "";
  const oneExtension = extractExtension(one).toLowerCase();
  const otherExtension = extractExtension(other).toLowerCase();
  if (oneExtension !== otherExtension) {
    return oneExtension < otherExtension ? -1 : 1;
  }
  if (one !== other) {
    return one < other ? -1 : 1;
  }
  return 0;
}
var FileNameMatch = /^(.*?)(\.([^.]*))?$/;
function extractNameAndExtension(str, dotfilesAsNames = false) {
  const match = str ? FileNameMatch.exec(str) : [];
  let result = [match && match[1] || "", match && match[3] || ""];
  if (dotfilesAsNames && (!result[0] && result[1] || result[0] && result[0].charAt(0) === ".")) {
    result = [result[0] + "." + result[1], ""];
  }
  return result;
}
function extractExtension(str) {
  const match = str ? FileNameMatch.exec(str) : [];
  return match && match[1] && match[1].charAt(0) !== "." && match[3] || "";
}
function compareAndDisambiguateByLength(collator, one, other) {
  const result = collator.compare(one, other);
  if (result !== 0) {
    return result;
  }
  if (one.length !== other.length) {
    return one.length < other.length ? -1 : 1;
  }
  return 0;
}
function startsWithLower(string) {
  const character = string.charAt(0);
  return character.toLocaleUpperCase() !== character ? true : false;
}
function startsWithUpper(string) {
  const character = string.charAt(0);
  return character.toLocaleLowerCase() !== character ? true : false;
}
function compareCaseLowerFirst(one, other) {
  if (startsWithLower(one) && startsWithUpper(other)) {
    return -1;
  }
  return startsWithUpper(one) && startsWithLower(other) ? 1 : 0;
}
function compareCaseUpperFirst(one, other) {
  if (startsWithUpper(one) && startsWithLower(other)) {
    return -1;
  }
  return startsWithLower(one) && startsWithUpper(other) ? 1 : 0;
}
function comparePathComponents(one, other, caseSensitive = false) {
  if (!caseSensitive) {
    one = one && one.toLowerCase();
    other = other && other.toLowerCase();
  }
  if (one === other) {
    return 0;
  }
  return one < other ? -1 : 1;
}
function $OM(one, other, caseSensitive = false) {
  const oneParts = one.split(sep);
  const otherParts = other.split(sep);
  const lastOne = oneParts.length - 1;
  const lastOther = otherParts.length - 1;
  let endOne, endOther;
  for (let i2 = 0; ; i2++) {
    endOne = lastOne === i2;
    endOther = lastOther === i2;
    if (endOne && endOther) {
      return $EM(oneParts[i2], otherParts[i2], caseSensitive);
    } else if (endOne) {
      return -1;
    } else if (endOther) {
      return 1;
    }
    const result = comparePathComponents(oneParts[i2], otherParts[i2], caseSensitive);
    if (result !== 0) {
      return result;
    }
  }
}
function $PM(one, other, lookFor) {
  const elementAName = one.toLowerCase();
  const elementBName = other.toLowerCase();
  const prefixCompare = $QM(one, other, lookFor);
  if (prefixCompare) {
    return prefixCompare;
  }
  const elementASuffixMatch = elementAName.endsWith(lookFor);
  const elementBSuffixMatch = elementBName.endsWith(lookFor);
  if (elementASuffixMatch !== elementBSuffixMatch) {
    return elementASuffixMatch ? -1 : 1;
  }
  const r2 = $EM(elementAName, elementBName);
  if (r2 !== 0) {
    return r2;
  }
  return elementAName.localeCompare(elementBName);
}
function $QM(one, other, lookFor) {
  const elementAName = one.toLowerCase();
  const elementBName = other.toLowerCase();
  const elementAPrefixMatch = elementAName.startsWith(lookFor);
  const elementBPrefixMatch = elementBName.startsWith(lookFor);
  if (elementAPrefixMatch !== elementBPrefixMatch) {
    return elementAPrefixMatch ? -1 : 1;
  } else if (elementAPrefixMatch && elementBPrefixMatch) {
    if (elementAName.length < elementBName.length) {
      return -1;
    }
    if (elementAName.length > elementBName.length) {
      return 1;
    }
  }
  return 0;
}

// out-build/vs/base/common/fuzzyScorer.js
var NO_MATCH = 0;
var NO_SCORE = [NO_MATCH, []];
function $RM(target, query, queryLower, allowNonContiguousMatches) {
  if (!target || !query) {
    return NO_SCORE;
  }
  const targetLength = target.length;
  const queryLength = query.length;
  if (targetLength < queryLength) {
    return NO_SCORE;
  }
  const targetLower = target.toLowerCase();
  const res = doScoreFuzzy(query, queryLower, queryLength, target, targetLower, targetLength, allowNonContiguousMatches);
  return res;
}
function doScoreFuzzy(query, queryLower, queryLength, target, targetLower, targetLength, allowNonContiguousMatches) {
  const scores = [];
  const matches = [];
  for (let queryIndex2 = 0; queryIndex2 < queryLength; queryIndex2++) {
    const queryIndexOffset = queryIndex2 * targetLength;
    const queryIndexPreviousOffset = queryIndexOffset - targetLength;
    const queryIndexGtNull = queryIndex2 > 0;
    const queryCharAtIndex = query[queryIndex2];
    const queryLowerCharAtIndex = queryLower[queryIndex2];
    for (let targetIndex2 = 0; targetIndex2 < targetLength; targetIndex2++) {
      const targetIndexGtNull = targetIndex2 > 0;
      const currentIndex = queryIndexOffset + targetIndex2;
      const leftIndex = currentIndex - 1;
      const diagIndex = queryIndexPreviousOffset + targetIndex2 - 1;
      const leftScore = targetIndexGtNull ? scores[leftIndex] : 0;
      const diagScore = queryIndexGtNull && targetIndexGtNull ? scores[diagIndex] : 0;
      const matchesSequenceLength = queryIndexGtNull && targetIndexGtNull ? matches[diagIndex] : 0;
      let score2;
      if (!diagScore && queryIndexGtNull) {
        score2 = 0;
      } else {
        score2 = computeCharScore(queryCharAtIndex, queryLowerCharAtIndex, target, targetLower, targetIndex2, matchesSequenceLength);
      }
      const isValidScore = score2 && diagScore + score2 >= leftScore;
      if (isValidScore && // We don't need to check if it's contiguous if we allow non-contiguous matches
      (allowNonContiguousMatches || // We must be looking for a contiguous match.
      // Looking at an index higher than 0 in the query means we must have already
      // found out this is contiguous otherwise there wouldn't have been a score
      queryIndexGtNull || // lastly check if the query is completely contiguous at this index in the target
      targetLower.startsWith(queryLower, targetIndex2))) {
        matches[currentIndex] = matchesSequenceLength + 1;
        scores[currentIndex] = diagScore + score2;
      } else {
        matches[currentIndex] = NO_MATCH;
        scores[currentIndex] = leftScore;
      }
    }
  }
  const positions = [];
  let queryIndex = queryLength - 1;
  let targetIndex = targetLength - 1;
  while (queryIndex >= 0 && targetIndex >= 0) {
    const currentIndex = queryIndex * targetLength + targetIndex;
    const match = matches[currentIndex];
    if (match === NO_MATCH) {
      targetIndex--;
    } else {
      positions.push(targetIndex);
      queryIndex--;
      targetIndex--;
    }
  }
  return [scores[queryLength * targetLength - 1], positions.reverse()];
}
function computeCharScore(queryCharAtIndex, queryLowerCharAtIndex, target, targetLower, targetIndex, matchesSequenceLength) {
  let score2 = 0;
  if (!considerAsEqual(queryLowerCharAtIndex, targetLower[targetIndex])) {
    return score2;
  }
  score2 += 1;
  if (matchesSequenceLength > 0) {
    score2 += matchesSequenceLength * 5;
  }
  if (queryCharAtIndex === target[targetIndex]) {
    score2 += 1;
  }
  if (targetIndex === 0) {
    score2 += 8;
  } else {
    const separatorBonus = scoreSeparatorAtPos(target.charCodeAt(targetIndex - 1));
    if (separatorBonus) {
      score2 += separatorBonus;
    } else if ($Ol(target.charCodeAt(targetIndex)) && matchesSequenceLength === 0) {
      score2 += 2;
    }
  }
  return score2;
}
function considerAsEqual(a, b) {
  if (a === b) {
    return true;
  }
  if (a === "/" || a === "\\") {
    return b === "/" || b === "\\";
  }
  return false;
}
function scoreSeparatorAtPos(charCode) {
  switch (charCode) {
    case 47:
    case 92:
      return 5;
    case 95:
    case 45:
    case 46:
    case 32:
    case 39:
    case 34:
    case 58:
      return 4;
    default:
      return 0;
  }
}
var NO_SCORE2 = [void 0, []];
function $SM(target, query, patternStart = 0, wordStart = 0) {
  const preparedQuery = query;
  if (preparedQuery.values && preparedQuery.values.length > 1) {
    return doScoreFuzzy2Multiple(target, preparedQuery.values, patternStart, wordStart);
  }
  return doScoreFuzzy2Single(target, query, patternStart, wordStart);
}
function doScoreFuzzy2Multiple(target, query, patternStart, wordStart) {
  let totalScore = 0;
  const totalMatches = [];
  for (const queryPiece of query) {
    const [score2, matches] = doScoreFuzzy2Single(target, queryPiece, patternStart, wordStart);
    if (typeof score2 !== "number") {
      return NO_SCORE2;
    }
    totalScore += score2;
    totalMatches.push(...matches);
  }
  return [totalScore, normalizeMatches(totalMatches)];
}
function doScoreFuzzy2Single(target, query, patternStart, wordStart) {
  const score2 = $Xl(query.original, query.originalLowercase, patternStart, target, target.toLowerCase(), wordStart, { firstMatchCanBeWeak: true, boostFullMatch: true });
  if (!score2) {
    return NO_SCORE2;
  }
  return [score2[0], $Ul(score2)];
}
var NO_ITEM_SCORE = Object.freeze({ score: 0 });
var PATH_IDENTITY_SCORE = 1 << 18;
var LABEL_PREFIX_SCORE_THRESHOLD = 1 << 17;
var LABEL_SCORE_THRESHOLD = 1 << 16;
function getCacheHash(label3, description, allowNonContiguousMatches, query) {
  const values = query.values ? query.values : [query];
  const cacheHash = $Xi({
    [query.normalized]: {
      values: values.map((v) => ({ value: v.normalized, expectContiguousMatch: v.expectContiguousMatch })),
      label: label3,
      description,
      allowNonContiguousMatches
    }
  });
  return cacheHash;
}
function $TM(item, query, allowNonContiguousMatches, accessor, cache2) {
  if (!item || !query.normalized) {
    return NO_ITEM_SCORE;
  }
  const label3 = accessor.getItemLabel(item);
  if (!label3) {
    return NO_ITEM_SCORE;
  }
  const description = accessor.getItemDescription(item);
  const cacheHash = getCacheHash(label3, description, allowNonContiguousMatches, query);
  const cached = cache2[cacheHash];
  if (cached) {
    return cached;
  }
  const itemScore = doScoreItemFuzzy(label3, description, accessor.getItemPath(item), query, allowNonContiguousMatches);
  cache2[cacheHash] = itemScore;
  return itemScore;
}
function doScoreItemFuzzy(label3, description, path, query, allowNonContiguousMatches) {
  const preferLabelMatches = !path || !query.containsPathSeparator;
  if (path && ($n ? query.pathNormalized === path : $1f(query.pathNormalized, path))) {
    return { score: PATH_IDENTITY_SCORE, labelMatch: [{ start: 0, end: label3.length }], descriptionMatch: description ? [{ start: 0, end: description.length }] : void 0 };
  }
  if (query.values && query.values.length > 1) {
    return doScoreItemFuzzyMultiple(label3, description, path, query.values, preferLabelMatches, allowNonContiguousMatches);
  }
  return doScoreItemFuzzySingle(label3, description, path, query, preferLabelMatches, allowNonContiguousMatches);
}
function doScoreItemFuzzyMultiple(label3, description, path, query, preferLabelMatches, allowNonContiguousMatches) {
  let totalScore = 0;
  const totalLabelMatches = [];
  const totalDescriptionMatches = [];
  for (const queryPiece of query) {
    const { score: score2, labelMatch, descriptionMatch } = doScoreItemFuzzySingle(label3, description, path, queryPiece, preferLabelMatches, allowNonContiguousMatches);
    if (score2 === NO_MATCH) {
      return NO_ITEM_SCORE;
    }
    totalScore += score2;
    if (labelMatch) {
      totalLabelMatches.push(...labelMatch);
    }
    if (descriptionMatch) {
      totalDescriptionMatches.push(...descriptionMatch);
    }
  }
  return {
    score: totalScore,
    labelMatch: normalizeMatches(totalLabelMatches),
    descriptionMatch: normalizeMatches(totalDescriptionMatches)
  };
}
function doScoreItemFuzzySingle(label3, description, path, query, preferLabelMatches, allowNonContiguousMatches) {
  if (preferLabelMatches || !description) {
    const [labelScore, labelPositions] = $RM(label3, query.normalized, query.normalizedLowercase, allowNonContiguousMatches && !query.expectContiguousMatch);
    if (labelScore) {
      const labelPrefixMatch = $Ll(query.normalized, label3);
      let baseScore;
      if (labelPrefixMatch) {
        baseScore = LABEL_PREFIX_SCORE_THRESHOLD;
        const prefixLengthBoost = Math.round(query.normalized.length / label3.length * 100);
        baseScore += prefixLengthBoost;
      } else {
        baseScore = LABEL_SCORE_THRESHOLD;
      }
      return { score: baseScore + labelScore, labelMatch: labelPrefixMatch || createMatches(labelPositions) };
    }
  }
  if (description) {
    let descriptionPrefix = description;
    if (!!path) {
      descriptionPrefix = `${description}${sep}`;
    }
    const descriptionPrefixLength = descriptionPrefix.length;
    const descriptionAndLabel = `${descriptionPrefix}${label3}`;
    const [labelDescriptionScore, labelDescriptionPositions] = $RM(descriptionAndLabel, query.normalized, query.normalizedLowercase, allowNonContiguousMatches && !query.expectContiguousMatch);
    if (labelDescriptionScore) {
      const labelDescriptionMatches = createMatches(labelDescriptionPositions);
      const labelMatch = [];
      const descriptionMatch = [];
      labelDescriptionMatches.forEach((h3) => {
        if (h3.start < descriptionPrefixLength && h3.end > descriptionPrefixLength) {
          labelMatch.push({ start: 0, end: h3.end - descriptionPrefixLength });
          descriptionMatch.push({ start: h3.start, end: descriptionPrefixLength });
        } else if (h3.start >= descriptionPrefixLength) {
          labelMatch.push({ start: h3.start - descriptionPrefixLength, end: h3.end - descriptionPrefixLength });
        } else {
          descriptionMatch.push(h3);
        }
      });
      return { score: labelDescriptionScore, labelMatch, descriptionMatch };
    }
  }
  return NO_ITEM_SCORE;
}
function createMatches(offsets) {
  const ret = [];
  if (!offsets) {
    return ret;
  }
  let last;
  for (const pos of offsets) {
    if (last && last.end === pos) {
      last.end += 1;
    } else {
      last = { start: pos, end: pos + 1 };
      ret.push(last);
    }
  }
  return ret;
}
function normalizeMatches(matches) {
  const sortedMatches = matches.sort((matchA, matchB) => {
    return matchA.start - matchB.start;
  });
  const normalizedMatches = [];
  let currentMatch = void 0;
  for (const match of sortedMatches) {
    if (!currentMatch || !matchOverlaps(currentMatch, match)) {
      currentMatch = match;
      normalizedMatches.push(match);
    } else {
      currentMatch.start = Math.min(currentMatch.start, match.start);
      currentMatch.end = Math.max(currentMatch.end, match.end);
    }
  }
  return normalizedMatches;
}
function matchOverlaps(matchA, matchB) {
  if (matchA.end < matchB.start) {
    return false;
  }
  if (matchB.end < matchA.start) {
    return false;
  }
  return true;
}
function $UM(itemA, itemB, query, allowNonContiguousMatches, accessor, cache2) {
  const itemScoreA = $TM(itemA, query, allowNonContiguousMatches, accessor, cache2);
  const itemScoreB = $TM(itemB, query, allowNonContiguousMatches, accessor, cache2);
  const scoreA = itemScoreA.score;
  const scoreB = itemScoreB.score;
  if (scoreA === PATH_IDENTITY_SCORE || scoreB === PATH_IDENTITY_SCORE) {
    if (scoreA !== scoreB) {
      return scoreA === PATH_IDENTITY_SCORE ? -1 : 1;
    }
  }
  if (scoreA > LABEL_SCORE_THRESHOLD || scoreB > LABEL_SCORE_THRESHOLD) {
    if (scoreA !== scoreB) {
      return scoreA > scoreB ? -1 : 1;
    }
    if (scoreA < LABEL_PREFIX_SCORE_THRESHOLD && scoreB < LABEL_PREFIX_SCORE_THRESHOLD) {
      const comparedByMatchLength = compareByMatchLength(itemScoreA.labelMatch, itemScoreB.labelMatch);
      if (comparedByMatchLength !== 0) {
        return comparedByMatchLength;
      }
    }
    const labelA = accessor.getItemLabel(itemA) || "";
    const labelB = accessor.getItemLabel(itemB) || "";
    if (labelA.length !== labelB.length) {
      return labelA.length - labelB.length;
    }
  }
  if (scoreA !== scoreB) {
    return scoreA > scoreB ? -1 : 1;
  }
  const itemAHasLabelMatches = Array.isArray(itemScoreA.labelMatch) && itemScoreA.labelMatch.length > 0;
  const itemBHasLabelMatches = Array.isArray(itemScoreB.labelMatch) && itemScoreB.labelMatch.length > 0;
  if (itemAHasLabelMatches && !itemBHasLabelMatches) {
    return -1;
  } else if (itemBHasLabelMatches && !itemAHasLabelMatches) {
    return 1;
  }
  const itemAMatchDistance = computeLabelAndDescriptionMatchDistance(itemA, itemScoreA, accessor);
  const itemBMatchDistance = computeLabelAndDescriptionMatchDistance(itemB, itemScoreB, accessor);
  if (itemAMatchDistance && itemBMatchDistance && itemAMatchDistance !== itemBMatchDistance) {
    return itemBMatchDistance > itemAMatchDistance ? -1 : 1;
  }
  return fallbackCompare(itemA, itemB, query, accessor);
}
function computeLabelAndDescriptionMatchDistance(item, score2, accessor) {
  let matchStart = -1;
  let matchEnd = -1;
  if (score2.descriptionMatch && score2.descriptionMatch.length) {
    matchStart = score2.descriptionMatch[0].start;
  } else if (score2.labelMatch && score2.labelMatch.length) {
    matchStart = score2.labelMatch[0].start;
  }
  if (score2.labelMatch && score2.labelMatch.length) {
    matchEnd = score2.labelMatch[score2.labelMatch.length - 1].end;
    if (score2.descriptionMatch && score2.descriptionMatch.length) {
      const itemDescription = accessor.getItemDescription(item);
      if (itemDescription) {
        matchEnd += itemDescription.length;
      }
    }
  } else if (score2.descriptionMatch && score2.descriptionMatch.length) {
    matchEnd = score2.descriptionMatch[score2.descriptionMatch.length - 1].end;
  }
  return matchEnd - matchStart;
}
function compareByMatchLength(matchesA, matchesB) {
  if (!matchesA && !matchesB || (!matchesA || !matchesA.length) && (!matchesB || !matchesB.length)) {
    return 0;
  }
  if (!matchesB || !matchesB.length) {
    return -1;
  }
  if (!matchesA || !matchesA.length) {
    return 1;
  }
  const matchStartA = matchesA[0].start;
  const matchEndA = matchesA[matchesA.length - 1].end;
  const matchLengthA = matchEndA - matchStartA;
  const matchStartB = matchesB[0].start;
  const matchEndB = matchesB[matchesB.length - 1].end;
  const matchLengthB = matchEndB - matchStartB;
  return matchLengthA === matchLengthB ? 0 : matchLengthB < matchLengthA ? 1 : -1;
}
function fallbackCompare(itemA, itemB, query, accessor) {
  const labelA = accessor.getItemLabel(itemA) || "";
  const labelB = accessor.getItemLabel(itemB) || "";
  const descriptionA = accessor.getItemDescription(itemA);
  const descriptionB = accessor.getItemDescription(itemB);
  const labelDescriptionALength = labelA.length + (descriptionA ? descriptionA.length : 0);
  const labelDescriptionBLength = labelB.length + (descriptionB ? descriptionB.length : 0);
  if (labelDescriptionALength !== labelDescriptionBLength) {
    return labelDescriptionALength - labelDescriptionBLength;
  }
  const pathA = accessor.getItemPath(itemA);
  const pathB = accessor.getItemPath(itemB);
  if (pathA && pathB && pathA.length !== pathB.length) {
    return pathA.length - pathB.length;
  }
  if (labelA !== labelB) {
    return $PM(labelA, labelB, query.normalized);
  }
  if (descriptionA && descriptionB && descriptionA !== descriptionB) {
    return $PM(descriptionA, descriptionB, query.normalized);
  }
  if (pathA && pathB && pathA !== pathB) {
    return $PM(pathA, pathB, query.normalized);
  }
  return 0;
}
function queryExpectsExactMatch(query) {
  return query.startsWith('"') && query.endsWith('"');
}
var MULTIPLE_QUERY_VALUES_SEPARATOR = " ";
function $VM(original) {
  if (typeof original !== "string") {
    original = "";
  }
  const originalLowercase = original.toLowerCase();
  const { pathNormalized, normalized, normalizedLowercase } = normalizeQuery(original);
  const containsPathSeparator = pathNormalized.indexOf(sep) >= 0;
  const expectExactMatch = queryExpectsExactMatch(original);
  let values = void 0;
  const originalSplit = original.split(MULTIPLE_QUERY_VALUES_SEPARATOR);
  if (originalSplit.length > 1) {
    for (const originalPiece of originalSplit) {
      const expectExactMatchPiece = queryExpectsExactMatch(originalPiece);
      const { pathNormalized: pathNormalizedPiece, normalized: normalizedPiece, normalizedLowercase: normalizedLowercasePiece } = normalizeQuery(originalPiece);
      if (normalizedPiece) {
        if (!values) {
          values = [];
        }
        values.push({
          original: originalPiece,
          originalLowercase: originalPiece.toLowerCase(),
          pathNormalized: pathNormalizedPiece,
          normalized: normalizedPiece,
          normalizedLowercase: normalizedLowercasePiece,
          expectContiguousMatch: expectExactMatchPiece
        });
      }
    }
  }
  return { original, originalLowercase, pathNormalized, normalized, normalizedLowercase, values, containsPathSeparator, expectContiguousMatch: expectExactMatch };
}
function normalizeQuery(original) {
  let pathNormalized;
  if ($l) {
    pathNormalized = original.replace(/\//g, sep);
  } else {
    pathNormalized = original.replace(/\\/g, sep);
  }
  const normalized = $If(pathNormalized).replace(/\s|"/g, "");
  return {
    pathNormalized,
    normalized,
    normalizedLowercase: normalized.toLowerCase()
  };
}
function $WM(arg1) {
  if (Array.isArray(arg1)) {
    return $VM(arg1.map((piece) => piece.original).join(MULTIPLE_QUERY_VALUES_SEPARATOR));
  }
  return $VM(arg1.original);
}

// out-build/vs/workbench/browser/parts/editor/editorQuickAccess.js
var $2tb_1;
var $3tb_1;
var $4tb_1;
var $1tb = class $1tb2 extends $rhb {
  constructor(prefix, b, h3, j, m) {
    super(prefix, {
      canAcceptInBackground: true,
      noResultsPick: {
        label: localize(3522, null),
        groupId: -1
      }
    });
    this.b = b;
    this.h = h3;
    this.j = j;
    this.m = m;
    this.a = new class {
      constructor() {
        this.scorerCache = /* @__PURE__ */ Object.create(null);
        this.isQuickNavigating = void 0;
      }
      reset(isQuickNavigating) {
        if (!isQuickNavigating) {
          this.scorerCache = /* @__PURE__ */ Object.create(null);
        }
        this.isQuickNavigating = isQuickNavigating;
      }
    }();
  }
  provide(picker, token) {
    this.a.reset(!!picker.quickNavigate);
    return super.provide(picker, token);
  }
  g(filter) {
    const query = $VM(filter);
    const filteredEditorEntries = this.r().filter((entry) => {
      if (!query.normalized) {
        return true;
      }
      const itemScore = $TM(entry, query, true, $ZM, this.a.scorerCache);
      if (!itemScore.score) {
        return false;
      }
      entry.highlights = { label: itemScore.labelMatch, description: itemScore.descriptionMatch };
      return true;
    });
    if (query.normalized) {
      const groups = this.b.getGroups(
        2
        /* GroupsOrder.GRID_APPEARANCE */
      ).map((group2) => group2.id);
      filteredEditorEntries.sort((entryA, entryB) => {
        if (entryA.groupId !== entryB.groupId) {
          return groups.indexOf(entryA.groupId) - groups.indexOf(entryB.groupId);
        }
        return $UM(entryA, entryB, query, true, $ZM, this.a.scorerCache);
      });
    }
    const filteredEditorEntriesWithSeparators = [];
    if (this.b.count > 1) {
      let lastGroupId = void 0;
      for (const entry of filteredEditorEntries) {
        if (typeof lastGroupId !== "number" || lastGroupId !== entry.groupId) {
          const group2 = this.b.getGroup(entry.groupId);
          if (group2) {
            filteredEditorEntriesWithSeparators.push({ type: "separator", label: group2.label });
          }
          lastGroupId = entry.groupId;
        }
        filteredEditorEntriesWithSeparators.push(entry);
      }
    } else {
      filteredEditorEntriesWithSeparators.push(...filteredEditorEntries);
    }
    return filteredEditorEntriesWithSeparators;
  }
  r() {
    const editors = this.s();
    const mapGroupIdToGroupAriaLabel = /* @__PURE__ */ new Map();
    for (const { groupId } of editors) {
      if (!mapGroupIdToGroupAriaLabel.has(groupId)) {
        const group2 = this.b.getGroup(groupId);
        if (group2) {
          mapGroupIdToGroupAriaLabel.set(groupId, group2.ariaLabel);
        }
      }
    }
    return this.s().map(({ editor, groupId }) => {
      const resource = $mL.getOriginalUri(editor, { supportSideBySide: SideBySideEditor.PRIMARY });
      const isDirty = editor.isDirty() && !editor.isSaving();
      const description = editor.getDescription();
      const nameAndDescription = description ? `${editor.getName()} ${description}` : editor.getName();
      return {
        groupId,
        resource,
        label: editor.getName(),
        ariaLabel: (() => {
          if (mapGroupIdToGroupAriaLabel.size > 1) {
            return isDirty ? localize(3523, null, nameAndDescription, mapGroupIdToGroupAriaLabel.get(groupId)) : localize(3524, null, nameAndDescription, mapGroupIdToGroupAriaLabel.get(groupId));
          }
          return isDirty ? localize(3525, null, nameAndDescription) : nameAndDescription;
        })(),
        description,
        iconClasses: $gdb(this.j, this.m, resource, void 0, editor.getIcon()).concat(editor.getLabelExtraClasses()),
        italic: !this.b.getGroup(groupId)?.isPinned(editor),
        buttons: (() => {
          return [
            {
              iconClass: isDirty ? "dirty-editor " + ThemeIcon.asClassName($6l.closeDirty) : ThemeIcon.asClassName($6l.close),
              tooltip: localize(3526, null),
              alwaysVisible: isDirty
            }
          ];
        })(),
        trigger: async () => {
          const group2 = this.b.getGroup(groupId);
          if (group2) {
            await group2.closeEditor(editor, { preserveFocus: true });
            if (!group2.contains(editor)) {
              return TriggerAction.REMOVE_ITEM;
            }
          }
          return TriggerAction.NO_ACTION;
        },
        accept: (keyMods, event) => this.b.getGroup(groupId)?.openEditor(editor, { preserveFocus: event.inBackground })
      };
    });
  }
};
$1tb = __decorate([
  __param(1, $iJ),
  __param(2, $mJ),
  __param(3, $sG),
  __param(4, $1E)
], $1tb);
var $2tb = class $2tb2 extends $1tb {
  static {
    $2tb_1 = this;
  }
  static {
    this.PREFIX = "edt active ";
  }
  constructor(editorGroupService, editorService, modelService, languageService) {
    super($2tb_1.PREFIX, editorGroupService, editorService, modelService, languageService);
  }
  s() {
    const group2 = this.b.activeGroup;
    return group2.getEditors(
      0
      /* EditorsOrder.MOST_RECENTLY_ACTIVE */
    ).map((editor) => ({ editor, groupId: group2.id }));
  }
};
$2tb = $2tb_1 = __decorate([
  __param(0, $iJ),
  __param(1, $mJ),
  __param(2, $sG),
  __param(3, $1E)
], $2tb);
var $3tb = class $3tb2 extends $1tb {
  static {
    $3tb_1 = this;
  }
  static {
    this.PREFIX = "edt ";
  }
  constructor(editorGroupService, editorService, modelService, languageService) {
    super($3tb_1.PREFIX, editorGroupService, editorService, modelService, languageService);
  }
  s() {
    const entries2 = [];
    for (const group2 of this.b.getGroups(
      2
      /* GroupsOrder.GRID_APPEARANCE */
    )) {
      for (const editor of group2.getEditors(
        1
        /* EditorsOrder.SEQUENTIAL */
      )) {
        entries2.push({ editor, groupId: group2.id });
      }
    }
    return entries2;
  }
};
$3tb = $3tb_1 = __decorate([
  __param(0, $iJ),
  __param(1, $mJ),
  __param(2, $sG),
  __param(3, $1E)
], $3tb);
var $4tb = class $4tb2 extends $1tb {
  static {
    $4tb_1 = this;
  }
  static {
    this.PREFIX = "edt mru ";
  }
  constructor(editorGroupService, editorService, modelService, languageService) {
    super($4tb_1.PREFIX, editorGroupService, editorService, modelService, languageService);
  }
  s() {
    const entries2 = [];
    for (const editor of this.h.getEditors(
      0
      /* EditorsOrder.MOST_RECENTLY_ACTIVE */
    )) {
      entries2.push(editor);
    }
    return entries2;
  }
};
$4tb = $4tb_1 = __decorate([
  __param(0, $iJ),
  __param(1, $mJ),
  __param(2, $sG),
  __param(3, $1E)
], $4tb);

// out-build/vs/workbench/common/editor/sideBySideEditorInput.js
var $1I_1;
var $1I = class $1I2 extends $nG {
  static {
    $1I_1 = this;
  }
  static {
    this.ID = "workbench.editorinputs.sidebysideEditorInput";
  }
  get typeId() {
    return $1I_1.ID;
  }
  get capabilities() {
    let capabilities = this.primary.capabilities;
    capabilities &= ~32;
    if (this.secondary.hasCapability(
      16
      /* EditorInputCapabilities.RequiresTrust */
    )) {
      capabilities |= 16;
    }
    if (this.secondary.hasCapability(
      8
      /* EditorInputCapabilities.Singleton */
    )) {
      capabilities |= 8;
    }
    capabilities |= 256;
    return capabilities;
  }
  get resource() {
    if (this.a) {
      return this.primary.resource;
    }
    return void 0;
  }
  constructor(b, c, secondary, primary, h3) {
    super();
    this.b = b;
    this.c = c;
    this.secondary = secondary;
    this.primary = primary;
    this.h = h3;
    this.a = this.primary.matches(this.secondary);
    this.m();
  }
  m() {
    this.B(Event2.once(Event2.any(this.primary.onWillDispose, this.secondary.onWillDispose))(() => {
      if (!this.isDisposed()) {
        this.dispose();
      }
    }));
    this.B(this.primary.onDidChangeDirty(() => this.f.fire()));
    this.B(this.primary.onDidChangeCapabilities(() => this.j.fire()));
    this.B(this.secondary.onDidChangeCapabilities(() => this.j.fire()));
    this.B(this.primary.onDidChangeLabel(() => this.g.fire()));
    this.B(this.secondary.onDidChangeLabel(() => this.g.fire()));
  }
  getName() {
    const preferredName = this.getPreferredName();
    if (preferredName) {
      return preferredName;
    }
    if (this.a) {
      return this.primary.getName();
    }
    return localize(4138, null, this.secondary.getName(), this.primary.getName());
  }
  getPreferredName() {
    return this.b;
  }
  getDescription(verbosity) {
    const preferredDescription = this.getPreferredDescription();
    if (preferredDescription) {
      return preferredDescription;
    }
    if (this.a) {
      return this.primary.getDescription(verbosity);
    }
    return super.getDescription(verbosity);
  }
  getPreferredDescription() {
    return this.c;
  }
  getTitle(verbosity) {
    let title;
    if (this.a) {
      title = this.primary.getTitle(verbosity) ?? this.getName();
    } else {
      title = super.getTitle(verbosity);
    }
    const preferredTitle = this.r();
    if (preferredTitle) {
      title = `${preferredTitle} (${title})`;
    }
    return title;
  }
  r() {
    if (this.b && this.c) {
      return `${this.b} ${this.c}`;
    }
    if (this.b || this.c) {
      return this.b ?? this.c;
    }
    return void 0;
  }
  getLabelExtraClasses() {
    if (this.a) {
      return this.primary.getLabelExtraClasses();
    }
    return super.getLabelExtraClasses();
  }
  getAriaLabel() {
    if (this.a) {
      return this.primary.getAriaLabel();
    }
    return super.getAriaLabel();
  }
  getTelemetryDescriptor() {
    const descriptor = this.primary.getTelemetryDescriptor();
    return { ...descriptor, ...super.getTelemetryDescriptor() };
  }
  isDirty() {
    return this.primary.isDirty();
  }
  isSaving() {
    return this.primary.isSaving();
  }
  async save(group2, options3) {
    const primarySaveResult = await this.primary.save(group2, options3);
    return this.s(primarySaveResult);
  }
  async saveAs(group2, options3) {
    const primarySaveResult = await this.primary.saveAs(group2, options3);
    return this.s(primarySaveResult);
  }
  s(primarySaveResult) {
    if (!primarySaveResult || !this.a) {
      return primarySaveResult;
    }
    if (this.primary.matches(primarySaveResult)) {
      return this;
    }
    if (primarySaveResult instanceof $nG) {
      return new $1I_1(this.b, this.c, primarySaveResult, primarySaveResult, this.h);
    }
    if (!$9K(primarySaveResult) && !$0K(primarySaveResult) && !$$K(primarySaveResult) && !$aL(primarySaveResult)) {
      return {
        primary: primarySaveResult,
        secondary: primarySaveResult,
        label: this.b,
        description: this.c
      };
    }
    return void 0;
  }
  revert(group2, options3) {
    return this.primary.revert(group2, options3);
  }
  async rename(group2, target) {
    if (!this.a) {
      return;
    }
    const renameResult = await this.primary.rename(group2, target);
    if (!renameResult) {
      return void 0;
    }
    if ($dL(renameResult.editor)) {
      return {
        editor: new $1I_1(this.b, this.c, renameResult.editor, renameResult.editor, this.h),
        options: {
          ...renameResult.options,
          viewState: $7K(this, group2, this.h)
        }
      };
    }
    if ($8K(renameResult.editor)) {
      return {
        editor: {
          label: this.b,
          description: this.c,
          primary: renameResult.editor,
          secondary: renameResult.editor,
          options: {
            ...renameResult.options,
            viewState: $7K(this, group2, this.h)
          }
        }
      };
    }
    return void 0;
  }
  isReadonly() {
    return this.primary.isReadonly();
  }
  toUntyped(options3) {
    const primaryResourceEditorInput = this.primary.toUntyped(options3);
    const secondaryResourceEditorInput = this.secondary.toUntyped(options3);
    if (primaryResourceEditorInput && secondaryResourceEditorInput && !$9K(primaryResourceEditorInput) && !$9K(secondaryResourceEditorInput) && !$0K(primaryResourceEditorInput) && !$0K(secondaryResourceEditorInput) && !$$K(primaryResourceEditorInput) && !$$K(secondaryResourceEditorInput) && !$aL(primaryResourceEditorInput) && !$aL(secondaryResourceEditorInput)) {
      const untypedInput = {
        label: this.b,
        description: this.c,
        primary: primaryResourceEditorInput,
        secondary: secondaryResourceEditorInput
      };
      if (typeof options3?.preserveViewState === "number") {
        untypedInput.options = {
          viewState: $7K(this, options3.preserveViewState, this.h)
        };
      }
      return untypedInput;
    }
    return void 0;
  }
  matches(otherInput) {
    if (this === otherInput) {
      return true;
    }
    if ($fL(otherInput) || $9K(otherInput)) {
      return false;
    }
    if (otherInput instanceof $1I_1) {
      return this.primary.matches(otherInput.primary) && this.secondary.matches(otherInput.secondary);
    }
    if ($$K(otherInput)) {
      return this.primary.matches(otherInput.primary) && this.secondary.matches(otherInput.secondary);
    }
    return false;
  }
};
$1I = $1I_1 = __decorate([
  __param(4, $mJ)
], $1I);
var $2I = class {
  canSerialize(editorInput) {
    const input = editorInput;
    if (input.primary && input.secondary) {
      const [secondaryInputSerializer, primaryInputSerializer] = this.a(input.secondary.typeId, input.primary.typeId);
      return !!(secondaryInputSerializer?.canSerialize(input.secondary) && primaryInputSerializer?.canSerialize(input.primary));
    }
    return false;
  }
  serialize(editorInput) {
    const input = editorInput;
    if (input.primary && input.secondary) {
      const [secondaryInputSerializer, primaryInputSerializer] = this.a(input.secondary.typeId, input.primary.typeId);
      if (primaryInputSerializer && secondaryInputSerializer) {
        const primarySerialized = primaryInputSerializer.serialize(input.primary);
        const secondarySerialized = secondaryInputSerializer.serialize(input.secondary);
        if (primarySerialized && secondarySerialized) {
          const serializedEditorInput = {
            name: input.getPreferredName(),
            description: input.getPreferredDescription(),
            primarySerialized,
            secondarySerialized,
            primaryTypeId: input.primary.typeId,
            secondaryTypeId: input.secondary.typeId
          };
          return JSON.stringify(serializedEditorInput);
        }
      }
    }
    return void 0;
  }
  deserialize(instantiationService, serializedEditorInput) {
    const deserialized = JSON.parse(serializedEditorInput);
    const [secondaryInputSerializer, primaryInputSerializer] = this.a(deserialized.secondaryTypeId, deserialized.primaryTypeId);
    if (primaryInputSerializer && secondaryInputSerializer) {
      const primaryInput = primaryInputSerializer.deserialize(instantiationService, deserialized.primarySerialized);
      const secondaryInput = secondaryInputSerializer.deserialize(instantiationService, deserialized.secondarySerialized);
      if (primaryInput instanceof $nG && secondaryInput instanceof $nG) {
        return this.b(instantiationService, deserialized.name, deserialized.description, secondaryInput, primaryInput);
      }
    }
    return void 0;
  }
  a(secondaryEditorInputTypeId, primaryEditorInputTypeId) {
    const registry4 = $Wn.as($ZK.EditorFactory);
    return [registry4.getEditorSerializer(secondaryEditorInputTypeId), registry4.getEditorSerializer(primaryEditorInputTypeId)];
  }
};
var $3I = class extends $2I {
  b(instantiationService, name, description, secondaryInput, primaryInput) {
    return instantiationService.createInstance($1I, name, description, secondaryInput, primaryInput);
  }
};

// out-build/vs/base/common/verifier.js
var Verifier = class {
  constructor(a) {
    this.a = a;
  }
  verify(value) {
    if (!this.b(value)) {
      return this.a;
    }
    return value;
  }
};
var $Y3 = class extends Verifier {
  b(value) {
    return typeof value === "boolean";
  }
};
var $Z3 = class extends Verifier {
  b(value) {
    return typeof value === "number";
  }
};
var $132 = class extends Verifier {
  b(value) {
    return value instanceof Set;
  }
};
var $232 = class extends Verifier {
  constructor(defaultValue, allowedValues) {
    super(defaultValue);
    this.c = allowedValues;
  }
  b(value) {
    return this.c.includes(value);
  }
};
var $332 = class extends Verifier {
  constructor(defaultValue, c) {
    super(defaultValue);
    this.c = c;
  }
  verify(value) {
    if (!this.b(value)) {
      return this.a;
    }
    return $432(this.c, value);
  }
  b(value) {
    return $Bg(value);
  }
};
function $432(verifiers, value) {
  const result = /* @__PURE__ */ Object.create(null);
  for (const key2 in verifiers) {
    if (Object.hasOwnProperty.call(verifiers, key2)) {
      const verifier = verifiers[key2];
      result[key2] = verifier.verify(value[key2]);
    }
  }
  return result;
}

// out-build/vs/workbench/browser/parts/editor/editor.js
var $Xob = new $rj(220, 70);
var $Yob = new $rj(Number.POSITIVE_INFINITY, Number.POSITIVE_INFINITY);
var $Zob = {
  showTabs: "multiple",
  highlightModifiedTabs: false,
  tabActionLocation: "right",
  tabActionCloseVisibility: true,
  tabActionUnpinVisibility: true,
  alwaysShowEditorActions: false,
  tabSizing: "fit",
  tabSizingFixedMinWidth: 50,
  tabSizingFixedMaxWidth: 160,
  pinnedTabSizing: "normal",
  pinnedTabsOnSeparateRow: false,
  tabHeight: "default",
  preventPinnedEditorClose: "keyboardAndMouse",
  titleScrollbarSizing: "default",
  focusRecentEditorAfterClose: true,
  showIcons: true,
  hasIcons: true,
  // 'vs-seti' is our default icon theme
  enablePreview: true,
  openPositioning: "right",
  openSideBySideDirection: "right",
  closeEmptyGroups: true,
  labelFormat: "default",
  splitSizing: "auto",
  splitOnDragAndDrop: true,
  dragToOpenWindow: true,
  centeredLayoutFixedWidth: false,
  doubleClickTabToToggleEditorGroupSizes: "expand",
  editorActionsLocation: "default",
  wrapTabs: false,
  enablePreviewFromQuickOpen: false,
  scrollToSwitchTabs: false,
  enablePreviewFromCodeNavigation: false,
  closeOnFileDelete: false,
  mouseBackForwardToNavigate: true,
  restoreViewState: true,
  splitInGroupLayout: "horizontal",
  revealIfOpen: false,
  // Properties that are Objects have to be defined as getters
  // to ensure no consumer modifies the default values
  get limit() {
    return { enabled: false, value: 10, perEditorGroup: false, excludeDirty: false };
  },
  get decorations() {
    return { badges: true, colors: true };
  },
  get autoLockGroups() {
    return /* @__PURE__ */ new Set();
  }
};
function $1ob(event) {
  return event.affectsConfiguration("workbench.editor") || event.affectsConfiguration("workbench.iconTheme") || event.affectsConfiguration("window.density");
}
function $2ob(configurationService, themeService) {
  const options3 = {
    ...$Zob,
    hasIcons: themeService.getFileIconTheme().hasFileIcons
  };
  const config = configurationService.getValue();
  if (config?.workbench?.editor) {
    Object.assign(options3, config.workbench.editor);
    if ($Bg(config.workbench.editor.autoLockGroups)) {
      options3.autoLockGroups = $Zob.autoLockGroups;
      for (const [editorId, enablement] of Object.entries(config.workbench.editor.autoLockGroups)) {
        if (enablement === true) {
          options3.autoLockGroups.add(editorId);
        }
      }
    } else {
      options3.autoLockGroups = $Zob.autoLockGroups;
    }
  }
  const windowConfig = configurationService.getValue();
  if (windowConfig?.window?.density?.editorTabHeight) {
    options3.tabHeight = windowConfig.window.density.editorTabHeight;
  }
  return validateEditorPartOptions(options3);
}
function validateEditorPartOptions(options3) {
  if (typeof options3.showTabs === "boolean") {
    options3.showTabs = options3.showTabs ? "multiple" : "single";
  }
  return $432({
    "wrapTabs": new $Y3($Zob["wrapTabs"]),
    "scrollToSwitchTabs": new $Y3($Zob["scrollToSwitchTabs"]),
    "highlightModifiedTabs": new $Y3($Zob["highlightModifiedTabs"]),
    "tabActionCloseVisibility": new $Y3($Zob["tabActionCloseVisibility"]),
    "tabActionUnpinVisibility": new $Y3($Zob["tabActionUnpinVisibility"]),
    "alwaysShowEditorActions": new $Y3($Zob["alwaysShowEditorActions"]),
    "pinnedTabsOnSeparateRow": new $Y3($Zob["pinnedTabsOnSeparateRow"]),
    "focusRecentEditorAfterClose": new $Y3($Zob["focusRecentEditorAfterClose"]),
    "showIcons": new $Y3($Zob["showIcons"]),
    "enablePreview": new $Y3($Zob["enablePreview"]),
    "enablePreviewFromQuickOpen": new $Y3($Zob["enablePreviewFromQuickOpen"]),
    "enablePreviewFromCodeNavigation": new $Y3($Zob["enablePreviewFromCodeNavigation"]),
    "closeOnFileDelete": new $Y3($Zob["closeOnFileDelete"]),
    "closeEmptyGroups": new $Y3($Zob["closeEmptyGroups"]),
    "revealIfOpen": new $Y3($Zob["revealIfOpen"]),
    "mouseBackForwardToNavigate": new $Y3($Zob["mouseBackForwardToNavigate"]),
    "restoreViewState": new $Y3($Zob["restoreViewState"]),
    "splitOnDragAndDrop": new $Y3($Zob["splitOnDragAndDrop"]),
    "dragToOpenWindow": new $Y3($Zob["dragToOpenWindow"]),
    "centeredLayoutFixedWidth": new $Y3($Zob["centeredLayoutFixedWidth"]),
    "hasIcons": new $Y3($Zob["hasIcons"]),
    "tabSizingFixedMinWidth": new $Z3($Zob["tabSizingFixedMinWidth"]),
    "tabSizingFixedMaxWidth": new $Z3($Zob["tabSizingFixedMaxWidth"]),
    "showTabs": new $232($Zob["showTabs"], ["multiple", "single", "none"]),
    "tabActionLocation": new $232($Zob["tabActionLocation"], ["left", "right"]),
    "tabSizing": new $232($Zob["tabSizing"], ["fit", "shrink", "fixed"]),
    "pinnedTabSizing": new $232($Zob["pinnedTabSizing"], ["normal", "compact", "shrink"]),
    "tabHeight": new $232($Zob["tabHeight"], ["default", "compact"]),
    "preventPinnedEditorClose": new $232($Zob["preventPinnedEditorClose"], ["keyboardAndMouse", "keyboard", "mouse", "never"]),
    "titleScrollbarSizing": new $232($Zob["titleScrollbarSizing"], ["default", "large"]),
    "openPositioning": new $232($Zob["openPositioning"], ["left", "right", "first", "last"]),
    "openSideBySideDirection": new $232($Zob["openSideBySideDirection"], ["right", "down"]),
    "labelFormat": new $232($Zob["labelFormat"], ["default", "short", "medium", "long"]),
    "splitInGroupLayout": new $232($Zob["splitInGroupLayout"], ["vertical", "horizontal"]),
    "splitSizing": new $232($Zob["splitSizing"], ["distribute", "split", "auto"]),
    "doubleClickTabToToggleEditorGroupSizes": new $232($Zob["doubleClickTabToToggleEditorGroupSizes"], ["maximize", "expand", "off"]),
    "editorActionsLocation": new $232($Zob["editorActionsLocation"], ["default", "titleBar", "hidden"]),
    "autoLockGroups": new $132($Zob["autoLockGroups"]),
    "limit": new $332($Zob["limit"], {
      "enabled": new $Y3($Zob["limit"]["enabled"]),
      "value": new $Z3($Zob["limit"]["value"]),
      "perEditorGroup": new $Y3($Zob["limit"]["perEditorGroup"]),
      "excludeDirty": new $Y3($Zob["limit"]["excludeDirty"])
    }),
    "decorations": new $332($Zob["decorations"], {
      "badges": new $Y3($Zob["decorations"]["badges"]),
      "colors": new $Y3($Zob["decorations"]["colors"])
    })
  }, options3);
}
function $3ob(group2, expectedActiveEditor, presetOptions) {
  if (!expectedActiveEditor || !group2.activeEditor || expectedActiveEditor.matches(group2.activeEditor)) {
    const options3 = {
      ...presetOptions,
      viewState: group2.activeEditorPane?.getViewState()
    };
    return options3;
  }
  return presetOptions || /* @__PURE__ */ Object.create(null);
}

// out-build/vs/workbench/common/memento.js
var $Slb = class _$Slb {
  static {
    this.a = /* @__PURE__ */ new Map();
  }
  static {
    this.b = /* @__PURE__ */ new Map();
  }
  static {
    this.c = /* @__PURE__ */ new Map();
  }
  static {
    this.d = "memento/";
  }
  constructor(id2, f) {
    this.f = f;
    this.e = _$Slb.d + id2;
  }
  getMemento(scope, target) {
    switch (scope) {
      case 1: {
        let workspaceMemento = _$Slb.c.get(this.e);
        if (!workspaceMemento) {
          workspaceMemento = new ScopedMemento(this.e, scope, target, this.f);
          _$Slb.c.set(this.e, workspaceMemento);
        }
        return workspaceMemento.getMemento();
      }
      case 0: {
        let profileMemento = _$Slb.b.get(this.e);
        if (!profileMemento) {
          profileMemento = new ScopedMemento(this.e, scope, target, this.f);
          _$Slb.b.set(this.e, profileMemento);
        }
        return profileMemento.getMemento();
      }
      case -1: {
        let applicationMemento = _$Slb.a.get(this.e);
        if (!applicationMemento) {
          applicationMemento = new ScopedMemento(this.e, scope, target, this.f);
          _$Slb.a.set(this.e, applicationMemento);
        }
        return applicationMemento.getMemento();
      }
    }
  }
  onDidChangeValue(scope, disposables) {
    return this.f.onDidChangeValue(scope, this.e, disposables);
  }
  saveMemento() {
    _$Slb.c.get(this.e)?.save();
    _$Slb.b.get(this.e)?.save();
    _$Slb.a.get(this.e)?.save();
  }
  reloadMemento(scope) {
    let memento;
    switch (scope) {
      case -1:
        memento = _$Slb.a.get(this.e);
        break;
      case 0:
        memento = _$Slb.b.get(this.e);
        break;
      case 1:
        memento = _$Slb.c.get(this.e);
        break;
    }
    memento?.reload();
  }
  static clear(scope) {
    switch (scope) {
      case 1:
        _$Slb.c.clear();
        break;
      case 0:
        _$Slb.b.clear();
        break;
      case -1:
        _$Slb.a.clear();
        break;
    }
  }
};
var ScopedMemento = class {
  constructor(b, c, d, e) {
    this.b = b;
    this.c = c;
    this.d = d;
    this.e = e;
    this.a = this.f();
  }
  f() {
    try {
      return this.e.getObject(this.b, this.c, {});
    } catch (error) {
      $gb(`[memento]: failed to parse contents: ${error} (id: ${this.b}, scope: ${this.c}, contents: ${this.e.get(this.b, this.c)})`);
    }
    return {};
  }
  getMemento() {
    return this.a;
  }
  reload() {
    for (const name of Object.getOwnPropertyNames(this.a)) {
      delete this.a[name];
    }
    Object.assign(this.a, this.f());
  }
  save() {
    if (!$Mg(this.a)) {
      this.e.store(this.b, this.a, this.c, this.d);
    } else {
      this.e.remove(this.b, this.c);
    }
  }
};

// out-build/vs/workbench/common/component.js
var $Tlb = class extends $ns {
  constructor(D, themeService, storageService) {
    super(themeService);
    this.D = D;
    this.C = new $Slb(this.D, storageService);
    this.B(storageService.onWillSaveState(() => {
      this.I();
      this.C.saveMemento();
    }));
  }
  getId() {
    return this.D;
  }
  F(scope, target) {
    return this.C.getMemento(scope, target);
  }
  G(scope) {
    return this.C.reloadMemento(scope);
  }
  H(scope, disposables) {
    return this.C.onDidChangeValue(scope, disposables);
  }
  I() {
  }
};

// out-build/vs/workbench/browser/composite.js
var $vob = class extends $Tlb {
  get onDidFocus() {
    if (!this.y) {
      this.y = this.M().onDidFocus;
    }
    return this.y.event;
  }
  get onDidBlur() {
    if (!this.J) {
      this.J = this.M().onDidBlur;
    }
    return this.J.event;
  }
  hasFocus() {
    return this.L;
  }
  M() {
    const container2 = $Kg(this.getContainer());
    const focusTracker = this.B($_j(container2));
    const onDidFocus = this.y = this.B(new $ze());
    this.B(focusTracker.onDidFocus(() => {
      this.L = true;
      onDidFocus.fire();
    }));
    const onDidBlur = this.J = this.B(new $ze());
    this.B(focusTracker.onDidBlur(() => {
      this.L = false;
      onDidBlur.fire();
    }));
    return { onDidFocus, onDidBlur };
  }
  constructor(id2, Q, themeService, storageService) {
    super(id2, themeService, storageService);
    this.Q = Q;
    this.t = this.B(new $ze());
    this.onTitleAreaUpdate = this.t.event;
    this.L = false;
    this.O = false;
  }
  getTitle() {
    return void 0;
  }
  /**
   * Note: Clients should not call this method, the workbench calls this
   * method. Calling it otherwise may result in unexpected behavior.
   *
   * Called to create this composite on the provided parent. This method is only
   * called once during the lifetime of the workbench.
   * Note that DOM-dependent calculations should be performed from the setVisible()
   * call. Only then the composite will be part of the DOM.
   */
  create(parent) {
    this.P = parent;
  }
  /**
   * Returns the container this composite is being build in.
   */
  getContainer() {
    return this.P;
  }
  /**
   * Note: Clients should not call this method, the workbench calls this
   * method. Calling it otherwise may result in unexpected behavior.
   *
   * Called to indicate that the composite has become visible or hidden. This method
   * is called more than once during workbench lifecycle depending on the user interaction.
   * The composite will be on-DOM if visible is set to true and off-DOM otherwise.
   *
   * Typically this operation should be fast though because setVisible might be called many times during a session.
   * If there is a long running operation it is fine to have it running in the background asyncly and return before.
   */
  setVisible(visible) {
    if (this.O !== !!visible) {
      this.O = visible;
    }
  }
  /**
   * Called when this composite should receive keyboard focus.
   */
  focus() {
  }
  /**
   *
   * @returns the action runner for this composite
   */
  getMenuIds() {
    return [];
  }
  /**
   * Returns an array of actions to show in the action bar of the composite.
   */
  getActions() {
    return [];
  }
  /**
   * Returns an array of actions to show in the action bar of the composite
   * in a less prominent way then action from getActions.
   */
  getSecondaryActions() {
    return [];
  }
  /**
   * Returns an array of actions to show in the context menu of the composite
   */
  getContextMenuActions() {
    return [];
  }
  /**
   * For any of the actions returned by this composite, provide an IActionViewItem in
   * cases where the implementor of the composite wants to override the presentation
   * of an action. Returns undefined to indicate that the action is not rendered through
   * an action item.
   */
  getActionViewItem(action, options3) {
    return void 0;
  }
  /**
   * Provide a context to be passed to the toolbar.
   */
  getActionsContext() {
    return null;
  }
  /**
   * Returns the instance of IActionRunner to use with this composite for the
   * composite tool bar.
   */
  getActionRunner() {
    if (!this.N) {
      this.N = this.B(new $Vm());
    }
    return this.N;
  }
  /**
   * Method for composite implementors to indicate to the composite container that the title or the actions
   * of the composite have changed. Calling this method will cause the container to ask for title (getTitle())
   * and actions (getActions(), getSecondaryActions()) if the composite is visible or the next time the composite
   * gets visible.
   */
  R() {
    this.t.fire();
  }
  /**
   * Returns true if this composite is currently visible and false otherwise.
   */
  isVisible() {
    return this.O;
  }
  /**
   * Returns the underlying composite control or `undefined` if it is not accessible.
   */
  getControl() {
    return void 0;
  }
};
var $wob = class {
  constructor(a, id2, name, cssClass, order, requestedIndex) {
    this.a = a;
    this.id = id2;
    this.name = name;
    this.cssClass = cssClass;
    this.order = order;
    this.requestedIndex = requestedIndex;
  }
  instantiate(instantiationService) {
    return instantiationService.createInstance(this.a);
  }
};
var $xob = class extends $3c {
  constructor() {
    super(...arguments);
    this.a = this.B(new $ze());
    this.onDidRegister = this.a.event;
    this.b = this.B(new $ze());
    this.onDidDeregister = this.b.event;
    this.c = [];
  }
  f(descriptor) {
    if (this.j(descriptor.id)) {
      return;
    }
    this.c.push(descriptor);
    this.a.fire(descriptor);
  }
  g(id2) {
    const descriptor = this.j(id2);
    if (!descriptor) {
      return;
    }
    this.c.splice(this.c.indexOf(descriptor), 1);
    this.b.fire(descriptor);
  }
  getComposite(id2) {
    return this.j(id2);
  }
  h() {
    return this.c.slice(0);
  }
  j(id2) {
    return this.c.find((composite) => composite.id === id2);
  }
};

// out-build/vs/workbench/browser/parts/editor/editorPane.js
var $5tb = class _$5tb extends $vob {
  static {
    this.U = /* @__PURE__ */ new Map();
  }
  get minimumWidth() {
    return $Xob.width;
  }
  get maximumWidth() {
    return $Yob.width;
  }
  get minimumHeight() {
    return $Xob.height;
  }
  get maximumHeight() {
    return $Yob.height;
  }
  get input() {
    return this.W;
  }
  get options() {
    return this.X;
  }
  get window() {
    return getWindowById(this.group.windowId, true).window;
  }
  /**
   * Should be overridden by editors that have their own ScopedContextKeyService
   */
  get scopedContextKeyService() {
    return void 0;
  }
  constructor(id2, group2, telemetryService, themeService, storageService) {
    super(id2, telemetryService, themeService, storageService);
    this.group = group2;
    this.onDidChangeSizeConstraints = Event2.None;
    this.S = this.B(new $ze());
    this.onDidChangeControl = this.S.event;
  }
  create(parent) {
    super.create(parent);
    this.Y(parent);
  }
  /**
   * Note: Clients should not call this method, the workbench calls this
   * method. Calling it otherwise may result in unexpected behavior.
   *
   * Sets the given input with the options to the editor. The input is guaranteed
   * to be different from the previous input that was set using the `input.matches()`
   * method.
   *
   * The provided context gives more information around how the editor was opened.
   *
   * The provided cancellation token should be used to test if the operation
   * was cancelled.
   */
  async setInput(input, options3, context, token) {
    this.W = input;
    this.X = options3;
  }
  /**
   * Called to indicate to the editor that the input should be cleared and
   * resources associated with the input should be freed.
   *
   * This method can be called based on different contexts, e.g. when opening
   * a different input or different editor control or when closing all editors
   * in a group.
   *
   * To monitor the lifecycle of editor inputs, you should not rely on this
   * method, rather refer to the listeners on `IEditorGroup` via `IEditorGroupsService`.
   */
  clearInput() {
    this.W = void 0;
    this.X = void 0;
  }
  /**
   * Note: Clients should not call this method, the workbench calls this
   * method. Calling it otherwise may result in unexpected behavior.
   *
   * Sets the given options to the editor. Clients should apply the options
   * to the current input.
   */
  setOptions(options3) {
    this.X = options3;
  }
  setVisible(visible) {
    super.setVisible(visible);
    this.Z(visible);
  }
  /**
   * Indicates that the editor control got visible or hidden.
   *
   * @param visible the state of visibility of this editor
   */
  Z(visible) {
  }
  setBoundarySashes(_sashes) {
  }
  ab(editorGroupService, configurationService, key2, limit = 10) {
    const mementoKey = `${this.getId()}${key2}`;
    let editorMemento = _$5tb.U.get(mementoKey);
    if (!editorMemento) {
      editorMemento = this.B(new $6tb(this.getId(), key2, this.F(
        1,
        1
        /* StorageTarget.MACHINE */
      ), limit, editorGroupService, configurationService));
      _$5tb.U.set(mementoKey, editorMemento);
    }
    return editorMemento;
  }
  getViewState() {
    return void 0;
  }
  I() {
    for (const [, editorMemento] of _$5tb.U) {
      if (editorMemento.id === this.getId()) {
        editorMemento.saveState();
      }
    }
    super.I();
  }
  dispose() {
    this.W = void 0;
    this.X = void 0;
    super.dispose();
  }
};
var $6tb = class _$6tb extends $3c {
  static {
    this.a = -1;
  }
  // pick a number < 0 to be outside group id range
  constructor(id2, h3, j, m, n, r2) {
    super();
    this.id = id2;
    this.h = h3;
    this.j = j;
    this.m = m;
    this.n = n;
    this.r = r2;
    this.c = false;
    this.g = false;
    this.t(void 0);
    this.s();
  }
  s() {
    this.B(this.r.onDidChangeConfiguration((e) => this.t(e)));
  }
  t(e) {
    if (!e || e.affectsConfiguration(void 0, "workbench.editor.sharedViewState")) {
      this.g = this.r.getValue(void 0, "workbench.editor.sharedViewState") === true;
    }
  }
  saveEditorState(group2, resourceOrEditor, state) {
    const resource = this.u(resourceOrEditor);
    if (!resource || !group2) {
      return;
    }
    const cache2 = this.w();
    let mementosForResource = cache2.get(resource.toString());
    if (!mementosForResource) {
      mementosForResource = /* @__PURE__ */ Object.create(null);
      cache2.set(resource.toString(), mementosForResource);
    }
    mementosForResource[group2.id] = state;
    if (this.g) {
      mementosForResource[_$6tb.a] = state;
    }
    if ($dL(resourceOrEditor)) {
      this.clearEditorStateOnDispose(resource, resourceOrEditor);
    }
  }
  loadEditorState(group2, resourceOrEditor) {
    const resource = this.u(resourceOrEditor);
    if (!resource || !group2) {
      return;
    }
    const cache2 = this.w();
    const mementosForResource = cache2.get(resource.toString());
    if (mementosForResource) {
      const mementoForResourceAndGroup = mementosForResource[group2.id];
      if (mementoForResourceAndGroup) {
        return mementoForResourceAndGroup;
      }
      if (this.g) {
        return mementosForResource[_$6tb.a];
      }
    }
    return void 0;
  }
  clearEditorState(resourceOrEditor, group2) {
    if ($dL(resourceOrEditor)) {
      this.f?.delete(resourceOrEditor);
    }
    const resource = this.u(resourceOrEditor);
    if (resource) {
      const cache2 = this.w();
      if (group2) {
        const mementosForResource = cache2.get(resource.toString());
        if (mementosForResource) {
          delete mementosForResource[group2.id];
          if ($Mg(mementosForResource)) {
            cache2.delete(resource.toString());
          }
        }
      } else {
        cache2.delete(resource.toString());
      }
    }
  }
  clearEditorStateOnDispose(resource, editor) {
    if (!this.f) {
      this.f = /* @__PURE__ */ new Map();
    }
    if (!this.f.has(editor)) {
      this.f.set(editor, Event2.once(editor.onWillDispose)(() => {
        this.clearEditorState(resource);
        this.f?.delete(editor);
      }));
    }
  }
  moveEditorState(source, target, comparer) {
    const cache2 = this.w();
    const cacheKeys = [...cache2.keys()];
    for (const cacheKey of cacheKeys) {
      const resource = URI.parse(cacheKey);
      if (!comparer.isEqualOrParent(resource, source)) {
        continue;
      }
      let targetResource;
      if ($oh(source, resource)) {
        targetResource = target;
      } else {
        const index = $7g(resource.path, source.path);
        targetResource = $vh(target, resource.path.substr(index + source.path.length + 1));
      }
      const value = cache2.get(
        cacheKey,
        0
        /* Touch.None */
      );
      if (value) {
        cache2.delete(cacheKey);
        cache2.set(targetResource.toString(), value);
      }
    }
  }
  u(resourceOrEditor) {
    if ($dL(resourceOrEditor)) {
      return resourceOrEditor.resource;
    }
    return resourceOrEditor;
  }
  w() {
    if (!this.b) {
      this.b = new $Hc(this.m);
      const rawEditorMemento = this.j[this.h];
      if (Array.isArray(rawEditorMemento)) {
        this.b.fromJSON(rawEditorMemento);
      }
    }
    return this.b;
  }
  saveState() {
    const cache2 = this.w();
    if (!this.c) {
      this.y();
      this.c = true;
    }
    this.j[this.h] = cache2.toJSON();
  }
  y() {
    const cache2 = this.w();
    const entries2 = [...cache2.entries()];
    for (const [resource, mapGroupToMementos] of entries2) {
      for (const group2 of Object.keys(mapGroupToMementos)) {
        const groupId = Number(group2);
        if (groupId === _$6tb.a && this.g) {
          continue;
        }
        if (!this.n.getGroup(groupId)) {
          delete mapGroupToMementos[groupId];
          if ($Mg(mapGroupToMementos)) {
            cache2.delete(resource);
          }
        }
      }
    }
  }
};

// out-build/vs/workbench/browser/parts/editor/editorWithViewState.js
var $$tb = class $$tb2 extends $5tb {
  constructor(id2, group2, viewStateStorageKey, telemetryService, m, storageService, s, themeService, u, cb) {
    super(id2, group2, telemetryService, themeService, storageService);
    this.m = m;
    this.s = s;
    this.u = u;
    this.cb = cb;
    this.g = this.B(new $4c());
    this.b = this.ab(cb, s, viewStateStorageKey, 100);
  }
  Z(visible) {
    this.g.value = this.group.onWillCloseEditor((e) => this.eb(e));
    super.Z(visible);
  }
  eb(e) {
    const editor = e.editor;
    if (editor === this.input) {
      this.gb(editor);
    }
  }
  clearInput() {
    this.gb(this.input);
    super.clearInput();
  }
  I() {
    this.gb(this.input);
    super.I();
  }
  gb(input) {
    if (!input || !this.nb(input)) {
      return;
    }
    const resource = this.pb(input);
    if (!resource) {
      return;
    }
    if (!this.ob()) {
      if (!this.j) {
        this.j = /* @__PURE__ */ new Map();
      }
      if (!this.j.has(input)) {
        this.j.set(input, Event2.once(input.onWillDispose)(() => {
          this.lb(resource, this.group);
          this.j?.delete(input);
        }));
      }
    }
    if (input.isDisposed() && !this.ob() || !this.hb(input) && !this.group.contains(input)) {
      this.lb(resource, this.group);
    } else if (!input.isDisposed()) {
      this.ib(resource);
    }
  }
  hb(input, context) {
    if (context?.newInGroup) {
      return this.s.getValue($mL.getOriginalUri(input, { supportSideBySide: SideBySideEditor.PRIMARY }), "workbench.editor.restoreViewState") === false ? false : true;
    }
    return true;
  }
  getViewState() {
    const input = this.input;
    if (!input || !this.nb(input)) {
      return;
    }
    const resource = this.pb(input);
    if (!resource) {
      return;
    }
    return this.mb(resource);
  }
  ib(resource) {
    const editorViewState = this.mb(resource);
    if (!editorViewState) {
      return;
    }
    this.b.saveEditorState(this.group, resource, editorViewState);
  }
  jb(input, context) {
    if (!input) {
      return void 0;
    }
    if (!this.nb(input)) {
      return void 0;
    }
    if (!this.hb(input, context)) {
      return void 0;
    }
    const resource = this.pb(input);
    if (!resource) {
      return;
    }
    return this.b.loadEditorState(this.group, resource);
  }
  kb(source, target, comparer) {
    return this.b.moveEditorState(source, target, comparer);
  }
  lb(resource, group2) {
    this.b.clearEditorState(resource, group2);
  }
  dispose() {
    super.dispose();
    if (this.j) {
      for (const [, disposables] of this.j) {
        disposables.dispose();
      }
      this.j = void 0;
    }
  }
  /**
   * Whether view state should be tracked even when the editor is
   * disposed.
   *
   * Subclasses should override this if the input can be restored
   * from the resource at a later point, e.g. if backed by files.
   */
  ob() {
    return false;
  }
};
$$tb = __decorate([
  __param(3, $zv),
  __param(4, $Pk),
  __param(5, $jv),
  __param(6, $zG),
  __param(7, $gs),
  __param(8, $mJ),
  __param(9, $iJ)
], $$tb);

// out-build/vs/workbench/browser/parts/editor/sideBySideEditor.js
var $_tb_1;
function isSideBySideEditorViewState(thing) {
  const candidate = thing;
  return typeof candidate?.primary === "object" && typeof candidate.secondary === "object";
}
var $_tb = class $_tb2 extends $$tb {
  static {
    $_tb_1 = this;
  }
  static {
    this.ID = $2K;
  }
  static {
    this.SIDE_BY_SIDE_LAYOUT_SETTING = "workbench.editor.splitInGroupLayout";
  }
  static {
    this.a = "sideBySideEditorViewState";
  }
  //#region Layout Constraints
  get c() {
    return this.zb ? this.zb.minimumWidth : 0;
  }
  get f() {
    return this.zb ? this.zb.maximumWidth : Number.POSITIVE_INFINITY;
  }
  get r() {
    return this.zb ? this.zb.minimumHeight : 0;
  }
  get qb() {
    return this.zb ? this.zb.maximumHeight : Number.POSITIVE_INFINITY;
  }
  get rb() {
    return this.Ab ? this.Ab.minimumWidth : 0;
  }
  get sb() {
    return this.Ab ? this.Ab.maximumWidth : Number.POSITIVE_INFINITY;
  }
  get tb() {
    return this.Ab ? this.Ab.minimumHeight : 0;
  }
  get ub() {
    return this.Ab ? this.Ab.maximumHeight : Number.POSITIVE_INFINITY;
  }
  set minimumWidth(value) {
  }
  set maximumWidth(value) {
  }
  set minimumHeight(value) {
  }
  set maximumHeight(value) {
  }
  get minimumWidth() {
    return this.c + this.rb;
  }
  get maximumWidth() {
    return this.f + this.sb;
  }
  get minimumHeight() {
    return this.r + this.tb;
  }
  get maximumHeight() {
    return this.qb + this.ub;
  }
  constructor(group2, telemetryService, instantiationService, themeService, storageService, Jb, textResourceConfigurationService, editorService, editorGroupService) {
    super($_tb_1.ID, group2, $_tb_1.a, telemetryService, instantiationService, storageService, textResourceConfigurationService, themeService, editorService, editorGroupService);
    this.Jb = Jb;
    this.wb = this.B(new $ze());
    this.xb = this.B(new $Ie());
    this.onDidChangeSizeConstraints = Event2.any(this.wb.event, this.xb.event);
    this.yb = this.B(new $ze());
    this.onDidChangeSelection = this.yb.event;
    this.zb = void 0;
    this.Ab = void 0;
    this.Eb = this.B(new $2c());
    this.Fb = this.B(new $2c());
    this.Gb = this.Jb.getValue($_tb_1.SIDE_BY_SIDE_LAYOUT_SETTING) === "vertical" ? 0 : 1;
    this.Hb = new $rj(0, 0);
    this.Ib = void 0;
    this.Kb();
  }
  Kb() {
    this.B(this.Jb.onDidChangeConfiguration((e) => this.Lb(e)));
  }
  Lb(event) {
    if (event.affectsConfiguration($_tb_1.SIDE_BY_SIDE_LAYOUT_SETTING)) {
      this.Gb = this.Jb.getValue($_tb_1.SIDE_BY_SIDE_LAYOUT_SETTING) === "vertical" ? 0 : 1;
      if (this.Db) {
        this.Mb();
      }
    }
  }
  Mb() {
    const container2 = $Kg(this.getContainer());
    const ratio = this.Nb();
    if (this.Db) {
      this.Db.el.remove();
      this.Eb.clear();
    }
    this.Pb(container2, ratio);
    this.layout(this.Hb);
  }
  Nb() {
    let ratio = void 0;
    if (this.Db) {
      const leftViewSize = this.Db.getViewSize(0);
      const rightViewSize = this.Db.getViewSize(1);
      if (Math.abs(leftViewSize - rightViewSize) > 1) {
        const totalSize = this.Db.orientation === 1 ? this.Hb.width : this.Hb.height;
        ratio = leftViewSize / totalSize;
      }
    }
    return ratio;
  }
  Y(parent) {
    parent.classList.add("side-by-side-editor");
    this.Cb = $(".side-by-side-editor-container.editor-instance");
    this.Bb = $(".side-by-side-editor-container.editor-instance");
    this.Pb(parent);
  }
  Pb(parent, ratio) {
    this.Db = this.Eb.add(new $r2(parent, { orientation: this.Gb }));
    this.Eb.add(this.Db.onDidSashReset(() => this.Db?.distributeViewSizes()));
    if (this.Gb === 1) {
      this.Db.orthogonalEndSash = this.vb?.bottom;
    } else {
      this.Db.orthogonalStartSash = this.vb?.left;
      this.Db.orthogonalEndSash = this.vb?.right;
    }
    let leftSizing = Sizing.Distribute;
    let rightSizing = Sizing.Distribute;
    if (ratio) {
      const totalSize = this.Db.orientation === 1 ? this.Hb.width : this.Hb.height;
      leftSizing = Math.round(totalSize * ratio);
      rightSizing = totalSize - leftSizing;
      this.Db.layout(this.Gb === 1 ? this.Hb.width : this.Hb.height);
    }
    const secondaryEditorContainer = $Kg(this.Cb);
    this.Db.addView({
      element: secondaryEditorContainer,
      layout: (size) => this.Wb(this.Ab, size),
      minimumSize: this.Gb === 1 ? $Xob.width : $Xob.height,
      maximumSize: Number.POSITIVE_INFINITY,
      onDidChange: Event2.None
    }, leftSizing);
    const primaryEditorContainer = $Kg(this.Bb);
    this.Db.addView({
      element: primaryEditorContainer,
      layout: (size) => this.Wb(this.zb, size),
      minimumSize: this.Gb === 1 ? $Xob.width : $Xob.height,
      maximumSize: Number.POSITIVE_INFINITY,
      onDidChange: Event2.None
    }, rightSizing);
    this.updateStyles();
  }
  getTitle() {
    if (this.input) {
      return this.input.getName();
    }
    return localize(3594, null);
  }
  async setInput(input, options3, context, token) {
    const oldInput = this.input;
    await super.setInput(input, options3, context, token);
    if (!oldInput || !input.matches(oldInput)) {
      if (oldInput) {
        this.$b();
      }
      this.Rb(input);
    }
    const { primary, secondary, viewState } = this.Qb(input, options3, context);
    this.Ib = viewState?.focus;
    if (typeof viewState?.ratio === "number" && this.Db) {
      const totalSize = this.Db.orientation === 1 ? this.Hb.width : this.Hb.height;
      this.Db.resizeView(0, Math.round(totalSize * viewState.ratio));
    } else {
      this.Db?.distributeViewSizes();
    }
    await Promise.all([
      this.Ab?.setInput(input.secondary, secondary, context, token),
      this.zb?.setInput(input.primary, primary, context, token)
    ]);
    if (typeof options3?.target === "number") {
      this.Ib = options3.target;
    }
  }
  Qb(input, options3, context) {
    const viewState = isSideBySideEditorViewState(options3?.viewState) ? options3?.viewState : this.jb(input, context);
    let primaryOptions = /* @__PURE__ */ Object.create(null);
    let secondaryOptions = void 0;
    if (options3?.target === SideBySideEditor.SECONDARY) {
      secondaryOptions = { ...options3 };
    } else {
      primaryOptions = { ...options3 };
    }
    primaryOptions.viewState = viewState?.primary;
    if (viewState?.secondary) {
      if (!secondaryOptions) {
        secondaryOptions = { viewState: viewState.secondary };
      } else {
        secondaryOptions.viewState = viewState?.secondary;
      }
    }
    return { primary: primaryOptions, secondary: secondaryOptions, viewState };
  }
  Rb(newInput) {
    this.Ab = this.Sb(newInput.secondary, $Kg(this.Cb));
    this.zb = this.Sb(newInput.primary, $Kg(this.Bb));
    this.layout(this.Hb);
    this.xb.input = Event2.any(Event2.map(this.Ab.onDidChangeSizeConstraints, () => void 0), Event2.map(this.zb.onDidChangeSizeConstraints, () => void 0));
    this.wb.fire(void 0);
    this.Fb.add(this.zb.onDidFocus(() => this.Tb(SideBySideEditor.PRIMARY)));
    this.Fb.add(this.Ab.onDidFocus(() => this.Tb(SideBySideEditor.SECONDARY)));
  }
  Sb(editorInput, container2) {
    const editorPaneDescriptor = $Wn.as($ZK.EditorPane).getEditorPane(editorInput);
    if (!editorPaneDescriptor) {
      throw new Error("No editor pane descriptor for editor found");
    }
    const editorPane = editorPaneDescriptor.instantiate(this.m, this.group);
    editorPane.create(container2);
    editorPane.setVisible(this.isVisible());
    if ($5K(editorPane)) {
      this.Fb.add(editorPane.onDidChangeSelection((e) => this.yb.fire(e)));
    }
    this.Fb.add(editorPane);
    return editorPane;
  }
  Tb(side) {
    this.Ib = side;
    this.S.fire();
  }
  getSelection() {
    const lastFocusedEditorPane = this.Vb();
    if ($5K(lastFocusedEditorPane)) {
      const selection = lastFocusedEditorPane.getSelection();
      if (selection) {
        return new SideBySideAwareEditorPaneSelection(selection, lastFocusedEditorPane === this.zb ? SideBySideEditor.PRIMARY : SideBySideEditor.SECONDARY);
      }
    }
    return void 0;
  }
  setOptions(options3) {
    super.setOptions(options3);
    if (typeof options3?.target === "number") {
      this.Ib = options3.target;
    }
    this.Vb()?.setOptions(options3);
  }
  Z(visible) {
    this.zb?.setVisible(visible);
    this.Ab?.setVisible(visible);
    super.Z(visible);
  }
  clearInput() {
    super.clearInput();
    this.zb?.clearInput();
    this.Ab?.clearInput();
    this.$b();
  }
  focus() {
    super.focus();
    this.Vb()?.focus();
  }
  Vb() {
    if (this.Ib === SideBySideEditor.SECONDARY) {
      return this.Ab;
    }
    return this.zb;
  }
  layout(dimension) {
    this.Hb = dimension;
    const splitview = $Kg(this.Db);
    splitview.layout(this.Gb === 1 ? dimension.width : dimension.height);
  }
  setBoundarySashes(sashes) {
    this.vb = sashes;
    if (this.Db) {
      this.Db.orthogonalEndSash = sashes.bottom;
    }
  }
  Wb(pane, size) {
    pane?.layout(this.Gb === 1 ? new $rj(size, this.Hb.height) : new $rj(this.Hb.width, size));
  }
  getControl() {
    return this.Vb()?.getControl();
  }
  getPrimaryEditorPane() {
    return this.zb;
  }
  getSecondaryEditorPane() {
    return this.Ab;
  }
  nb(input) {
    return input instanceof $1I;
  }
  mb(resource) {
    if (!this.input || !$oh(resource, this.pb(this.input))) {
      return;
    }
    const primarViewState = this.zb?.getViewState();
    const secondaryViewState = this.Ab?.getViewState();
    if (!primarViewState || !secondaryViewState) {
      return;
    }
    return {
      primary: primarViewState,
      secondary: secondaryViewState,
      focus: this.Ib,
      ratio: this.Nb()
    };
  }
  pb(input) {
    let primary;
    let secondary;
    if (input instanceof $1I) {
      primary = input.primary.resource;
      secondary = input.secondary.resource;
    }
    if (!secondary || !primary) {
      return void 0;
    }
    return URI.from({ scheme: "sideBySide", path: `${$xk(secondary.toString())}${$xk(primary.toString())}` });
  }
  updateStyles() {
    super.updateStyles();
    if (this.Bb) {
      if (this.Gb === 1) {
        this.Bb.style.borderLeftWidth = "1px";
        this.Bb.style.borderLeftStyle = "solid";
        this.Bb.style.borderLeftColor = this.z($Hmb) ?? "";
        this.Bb.style.borderTopWidth = "0";
      } else {
        this.Bb.style.borderTopWidth = "1px";
        this.Bb.style.borderTopStyle = "solid";
        this.Bb.style.borderTopColor = this.z($Gmb) ?? "";
        this.Bb.style.borderLeftWidth = "0";
      }
    }
  }
  dispose() {
    this.$b();
    super.dispose();
  }
  $b() {
    this.Fb.clear();
    this.Ab = void 0;
    this.zb = void 0;
    this.Ib = void 0;
    if (this.Cb) {
      $$i(this.Cb);
    }
    if (this.Bb) {
      $$i(this.Bb);
    }
  }
};
$_tb = $_tb_1 = __decorate([
  __param(1, $zv),
  __param(2, $Pk),
  __param(3, $gs),
  __param(4, $jv),
  __param(5, $kl),
  __param(6, $zG),
  __param(7, $mJ),
  __param(8, $iJ)
], $_tb);
var SideBySideAwareEditorPaneSelection = class _SideBySideAwareEditorPaneSelection {
  constructor(a, b) {
    this.a = a;
    this.b = b;
  }
  compare(other) {
    if (!(other instanceof _SideBySideAwareEditorPaneSelection)) {
      return 3;
    }
    if (this.b !== other.b) {
      return 3;
    }
    return this.a.compare(other.a);
  }
  restore(options3) {
    const sideBySideEditorOptions = {
      ...options3,
      target: this.b
    };
    return this.a.restore(sideBySideEditorOptions);
  }
};

// out-build/vs/workbench/services/workingCopy/common/workingCopyService.js
var $XI = $Qk("workingCopyService");
var $YI = class extends $3c {
  constructor() {
    super(...arguments);
    this.a = this.B(new $ze());
    this.onDidRegister = this.a.event;
    this.b = this.B(new $ze());
    this.onDidUnregister = this.b.event;
    this.f = this.B(new $ze());
    this.onDidChangeDirty = this.f.event;
    this.g = this.B(new $ze());
    this.onDidChangeContent = this.g.event;
    this.h = this.B(new $ze());
    this.onDidSave = this.h.event;
    this.j = /* @__PURE__ */ new Set();
    this.m = new $Ec();
    this.n = this.B(new $_c());
  }
  //#endregion
  //#region Registry
  get workingCopies() {
    return Array.from(this.j.values());
  }
  registerWorkingCopy(workingCopy) {
    let workingCopiesForResource = this.m.get(workingCopy.resource);
    if (workingCopiesForResource?.has(workingCopy.typeId)) {
      throw new Error(`Cannot register more than one working copy with the same resource ${workingCopy.resource.toString()} and type ${workingCopy.typeId}.`);
    }
    this.j.add(workingCopy);
    if (!workingCopiesForResource) {
      workingCopiesForResource = /* @__PURE__ */ new Map();
      this.m.set(workingCopy.resource, workingCopiesForResource);
    }
    workingCopiesForResource.set(workingCopy.typeId, workingCopy);
    const disposables = new $2c();
    disposables.add(workingCopy.onDidChangeContent(() => this.g.fire(workingCopy)));
    disposables.add(workingCopy.onDidChangeDirty(() => this.f.fire(workingCopy)));
    disposables.add(workingCopy.onDidSave((e) => this.h.fire({ workingCopy, ...e })));
    this.n.set(workingCopy, disposables);
    this.a.fire(workingCopy);
    if (workingCopy.isDirty()) {
      this.f.fire(workingCopy);
    }
    return $1c(() => {
      this.r(workingCopy);
      this.b.fire(workingCopy);
    });
  }
  r(workingCopy) {
    this.j.delete(workingCopy);
    const workingCopiesForResource = this.m.get(workingCopy.resource);
    if (workingCopiesForResource?.delete(workingCopy.typeId) && workingCopiesForResource.size === 0) {
      this.m.delete(workingCopy.resource);
    }
    if (workingCopy.isDirty()) {
      this.f.fire(workingCopy);
    }
    this.n.deleteAndDispose(workingCopy);
  }
  has(resourceOrIdentifier) {
    if (URI.isUri(resourceOrIdentifier)) {
      return this.m.has(resourceOrIdentifier);
    }
    return this.m.get(resourceOrIdentifier.resource)?.has(resourceOrIdentifier.typeId) ?? false;
  }
  get(identifier2) {
    return this.m.get(identifier2.resource)?.get(identifier2.typeId);
  }
  getAll(resource) {
    const workingCopies = this.m.get(resource);
    if (!workingCopies) {
      return void 0;
    }
    return Array.from(workingCopies.values());
  }
  //#endregion
  //#region Dirty Tracking
  get hasDirty() {
    for (const workingCopy of this.j) {
      if (workingCopy.isDirty()) {
        return true;
      }
    }
    return false;
  }
  get dirtyCount() {
    let totalDirtyCount = 0;
    for (const workingCopy of this.j) {
      if (workingCopy.isDirty()) {
        totalDirtyCount++;
      }
    }
    return totalDirtyCount;
  }
  get dirtyWorkingCopies() {
    return this.workingCopies.filter((workingCopy) => workingCopy.isDirty());
  }
  get modifiedCount() {
    let totalModifiedCount = 0;
    for (const workingCopy of this.j) {
      if (workingCopy.isModified()) {
        totalModifiedCount++;
      }
    }
    return totalModifiedCount;
  }
  get modifiedWorkingCopies() {
    return this.workingCopies.filter((workingCopy) => workingCopy.isModified());
  }
  isDirty(resource, typeId2) {
    const workingCopies = this.m.get(resource);
    if (workingCopies) {
      if (typeof typeId2 === "string") {
        return workingCopies.get(typeId2)?.isDirty() ?? false;
      } else {
        for (const [, workingCopy] of workingCopies) {
          if (workingCopy.isDirty()) {
            return true;
          }
        }
      }
    }
    return false;
  }
};
$SC(
  $XI,
  $YI,
  1
  /* InstantiationType.Delayed */
);

// out-build/vs/workbench/browser/editor.js
var $7tb = class _$7tb {
  static {
    this.a = /* @__PURE__ */ new Set();
  }
  static didInstantiateEditorPane(typeId2) {
    return _$7tb.a.has(typeId2);
  }
  static {
    this.b = new $ze();
  }
  static {
    this.onWillInstantiateEditorPane = _$7tb.b.event;
  }
  static create(ctor, typeId2, name) {
    return new _$7tb(ctor, typeId2, name);
  }
  constructor(c, typeId2, name) {
    this.c = c;
    this.typeId = typeId2;
    this.name = name;
  }
  instantiate(instantiationService, group2) {
    _$7tb.b.fire({ typeId: this.typeId });
    const pane = instantiationService.createInstance(this.c, group2);
    _$7tb.a.add(this.typeId);
    return pane;
  }
  describes(editorPane) {
    return editorPane.getId() === this.typeId;
  }
};
var $8tb = class {
  constructor() {
    this.a = /* @__PURE__ */ new Map();
  }
  registerEditorPane(editorPaneDescriptor, editorDescriptors) {
    this.a.set(editorPaneDescriptor, editorDescriptors);
    return $1c(() => {
      this.a.delete(editorPaneDescriptor);
    });
  }
  getEditorPane(editor) {
    const descriptors = this.b(editor);
    if (descriptors.length === 0) {
      return void 0;
    }
    if (descriptors.length === 1) {
      return descriptors[0];
    }
    return editor.prefersEditorPane(descriptors);
  }
  b(editor, byInstanceOf) {
    const matchingEditorPaneDescriptors = [];
    for (const editorPane of this.a.keys()) {
      const editorDescriptors = this.a.get(editorPane) || [];
      for (const editorDescriptor of editorDescriptors) {
        const editorClass = editorDescriptor.ctor;
        if (!byInstanceOf && editor.constructor === editorClass) {
          matchingEditorPaneDescriptors.push(editorPane);
          break;
        } else if (byInstanceOf && editor instanceof editorClass) {
          matchingEditorPaneDescriptors.push(editorPane);
          break;
        }
      }
    }
    if (!byInstanceOf && matchingEditorPaneDescriptors.length === 0) {
      return this.b(editor, true);
    }
    return matchingEditorPaneDescriptors;
  }
  //#region Used for tests only
  getEditorPaneByType(typeId2) {
    return Iterable.find(this.a.keys(), (editor) => editor.typeId === typeId2);
  }
  getEditorPanes() {
    return Array.from(this.a.keys());
  }
  getEditors() {
    const editorClasses = [];
    for (const editorPane of this.a.keys()) {
      const editorDescriptors = this.a.get(editorPane);
      if (editorDescriptors) {
        editorClasses.push(...editorDescriptors.map((editorDescriptor) => editorDescriptor.ctor));
      }
    }
    return editorClasses;
  }
};
$Wn.add($ZK.EditorPane, new $8tb());
function $9tb(accessor, resources) {
  const editorService = accessor.get($mJ);
  const uriIdentityService = accessor.get($vl);
  const workingCopyService = accessor.get($XI);
  return new Promise((resolve) => {
    let remainingResources = [...resources];
    const listener = editorService.onDidCloseEditor(async (event) => {
      if (event.context === EditorCloseContext.MOVE) {
        return;
      }
      let primaryResource = $mL.getOriginalUri(event.editor, { supportSideBySide: SideBySideEditor.PRIMARY });
      let secondaryResource = $mL.getOriginalUri(event.editor, { supportSideBySide: SideBySideEditor.SECONDARY });
      if (event.context === EditorCloseContext.REPLACE) {
        const newPrimaryResource = $mL.getOriginalUri(editorService.activeEditor, { supportSideBySide: SideBySideEditor.PRIMARY });
        const newSecondaryResource = $mL.getOriginalUri(editorService.activeEditor, { supportSideBySide: SideBySideEditor.SECONDARY });
        if (uriIdentityService.extUri.isEqual(primaryResource, newPrimaryResource)) {
          primaryResource = void 0;
        }
        if (uriIdentityService.extUri.isEqual(secondaryResource, newSecondaryResource)) {
          secondaryResource = void 0;
        }
      }
      remainingResources = remainingResources.filter((resource) => {
        if (uriIdentityService.extUri.isEqual(resource, primaryResource) || uriIdentityService.extUri.isEqual(resource, secondaryResource)) {
          return false;
        }
        if (event.context !== EditorCloseContext.REPLACE) {
          if (primaryResource?.scheme === Schemas.untitled && uriIdentityService.extUri.isEqual(resource, primaryResource.with({ scheme: resource.scheme })) || secondaryResource?.scheme === Schemas.untitled && uriIdentityService.extUri.isEqual(resource, secondaryResource.with({ scheme: resource.scheme }))) {
            return false;
          }
        }
        return true;
      });
      if (remainingResources.length === 0) {
        const dirtyResources = resources.filter((resource) => workingCopyService.isDirty(resource));
        if (dirtyResources.length > 0) {
          await Promises.settled(dirtyResources.map(async (resource) => await new Promise((resolve2) => {
            if (!workingCopyService.isDirty(resource)) {
              return resolve2();
            }
            const listener2 = workingCopyService.onDidChangeDirty((workingCopy) => {
              if (!workingCopy.isDirty() && uriIdentityService.extUri.isEqual(resource, workingCopy.resource)) {
                listener2.dispose();
                return resolve2();
              }
            });
          })));
        }
        listener.dispose();
        return resolve();
      }
    });
  });
}
function $0tb(input, index, group2, groupCount) {
  let ariaLabel = input.getAriaLabel();
  if (group2 && !group2.isPinned(input)) {
    ariaLabel = localize(3045, null, ariaLabel);
  }
  if (group2?.isSticky(index ?? input)) {
    ariaLabel = localize(3046, null, ariaLabel);
  }
  if (group2 && typeof groupCount === "number" && groupCount > 1) {
    ariaLabel = `${ariaLabel}, ${group2.ariaLabel}`;
  }
  return ariaLabel;
}

// out-build/vs/workbench/browser/parts/editor/textEditor.js
var $aub_1;
var $aub = class $aub2 extends $$tb {
  static {
    $aub_1 = this;
  }
  static {
    this.qb = "textEditorViewState";
  }
  constructor(id2, group2, telemetryService, instantiationService, storageService, textResourceConfigurationService, themeService, editorService, editorGroupService, xb) {
    super(id2, group2, $aub_1.qb, telemetryService, instantiationService, storageService, textResourceConfigurationService, themeService, editorService, editorGroupService);
    this.xb = xb;
    this.rb = this.B(new $ze());
    this.onDidChangeSelection = this.rb.event;
    this.sb = this.B(new $ze());
    this.onDidChangeScroll = this.sb.event;
    this.wb = this.B(new $4c());
    this.B(this.s.onDidChangeConfiguration((e) => this.yb(e)));
    this.B(Event2.any(this.cb.onDidAddGroup, this.cb.onDidRemoveGroup)(() => {
      const ariaLabel = this.Cb();
      this.tb?.setAttribute("aria-label", ariaLabel);
      this.Mb({ ariaLabel });
    }));
    this.B(this.xb.onDidChangeFileSystemProviderCapabilities((e) => this.Db(e.scheme)));
    this.B(this.xb.onDidChangeFileSystemProviderRegistrations((e) => this.Db(e.scheme)));
  }
  yb(e) {
    const resource = this.Rb();
    if (!this.zb(e, resource)) {
      return;
    }
    if (this.isVisible()) {
      this.Qb(resource);
    } else {
      this.ub = true;
    }
  }
  zb(e, resource) {
    return e.affectsConfiguration(resource, "editor") || e.affectsConfiguration(resource, "problems.visibility");
  }
  Ab() {
    if (this.ub) {
      this.Qb();
      this.ub = false;
    }
  }
  Bb(configuration2) {
    const editorConfiguration2 = $Bg(configuration2.editor) ? $Lv(configuration2.editor) : /* @__PURE__ */ Object.create(null);
    Object.assign(editorConfiguration2, this.Hb(configuration2));
    editorConfiguration2.ariaLabel = this.Cb();
    return editorConfiguration2;
  }
  Cb() {
    return this.input ? $0tb(this.input, void 0, this.group, this.cb.count) : localize(3599, null);
  }
  Db(scheme) {
    if (!this.input) {
      return;
    }
    if (this.Rb()?.scheme === scheme) {
      this.Fb(this.input);
    }
  }
  Eb(input) {
    if (this.input === input) {
      this.Fb(input);
    }
  }
  Fb(input) {
    this.Mb({ ...this.Gb(input.isReadonly()) });
  }
  Gb(isReadonly) {
    return {
      readOnly: !!isReadonly,
      readOnlyMessage: typeof isReadonly !== "boolean" ? isReadonly : void 0
    };
  }
  Hb(configuration2) {
    return {
      overviewRulerLanes: 3,
      lineNumbersMinChars: 3,
      fixedOverflowWidgets: true,
      ...this.Gb(this.input?.isReadonly()),
      renderValidationDecorations: configuration2.problems?.visibility !== false ? "on" : "off"
    };
  }
  Y(parent) {
    this.tb = parent;
    this.Lb(parent, this.Bb(this.s.getValue(this.Rb())));
    this.Jb();
  }
  Jb() {
    const mainControl = this.Nb();
    if (mainControl) {
      this.B(mainControl.onDidChangeModelLanguage(() => this.Qb()));
      this.B(mainControl.onDidChangeModel(() => this.Qb()));
      this.B(mainControl.onDidChangeCursorPosition((e) => this.rb.fire({ reason: this.Kb(e) })));
      this.B(mainControl.onDidChangeModelContent(() => this.rb.fire({
        reason: 3
        /* EditorPaneSelectionChangeReason.EDIT */
      })));
      this.B(mainControl.onDidScrollChange(() => this.sb.fire()));
    }
  }
  Kb(e) {
    switch (e.source) {
      case "api":
        return 1;
      case "code.navigation":
        return 4;
      case "code.jump":
        return 5;
      default:
        return 2;
    }
  }
  getSelection() {
    const mainControl = this.Nb();
    if (mainControl) {
      const selection = mainControl.getSelection();
      if (selection) {
        return new $bub(selection);
      }
    }
    return void 0;
  }
  async setInput(input, options3, context, token) {
    await super.setInput(input, options3, context, token);
    this.wb.value = input.onDidChangeCapabilities(() => this.Eb(input));
    this.Qb();
    const editorContainer = $Kg(this.tb);
    editorContainer.setAttribute("aria-label", this.Cb());
  }
  clearInput() {
    this.wb.clear();
    super.clearInput();
  }
  getScrollPosition() {
    const editor = this.Nb();
    if (!editor) {
      throw new Error("Control has not yet been initialized");
    }
    return {
      // The top position can vary depending on the view zones (find widget for example)
      scrollTop: editor.getScrollTop() - editor.getTopForLineNumber(1),
      scrollLeft: editor.getScrollLeft()
    };
  }
  setScrollPosition(scrollPosition) {
    const editor = this.Nb();
    if (!editor) {
      throw new Error("Control has not yet been initialized");
    }
    editor.setScrollTop(scrollPosition.scrollTop);
    if (scrollPosition.scrollLeft) {
      editor.setScrollLeft(scrollPosition.scrollLeft);
    }
  }
  Z(visible) {
    if (visible) {
      this.Ab();
    }
    super.Z(visible);
  }
  pb(input) {
    return input.resource;
  }
  Qb(resource = this.Rb()) {
    let configuration2 = void 0;
    if (resource) {
      configuration2 = this.s.getValue(resource);
    }
    if (!configuration2) {
      return;
    }
    const editorConfiguration2 = this.Bb(configuration2);
    let editorSettingsToApply = editorConfiguration2;
    if (this.vb) {
      editorSettingsToApply = $Rv(this.vb, editorSettingsToApply);
    }
    if (Object.keys(editorSettingsToApply).length > 0) {
      this.vb = editorConfiguration2;
      this.Mb(editorSettingsToApply);
    }
  }
  Rb() {
    const mainControl = this.Nb();
    if (mainControl) {
      const model = mainControl.getModel();
      if (model) {
        return model.uri;
      }
    }
    if (this.input) {
      return this.input.resource;
    }
    return void 0;
  }
  dispose() {
    this.vb = void 0;
    super.dispose();
  }
};
$aub = $aub_1 = __decorate([
  __param(2, $zv),
  __param(3, $Pk),
  __param(4, $jv),
  __param(5, $zG),
  __param(6, $gs),
  __param(7, $mJ),
  __param(8, $iJ),
  __param(9, $km)
], $aub);
var $bub = class _$bub {
  static {
    this.a = 10;
  }
  // number of lines to move in editor to justify for significant change
  constructor(b) {
    this.b = b;
  }
  compare(other) {
    if (!(other instanceof _$bub)) {
      return 3;
    }
    const thisLineNumber = Math.min(this.b.selectionStartLineNumber, this.b.positionLineNumber);
    const otherLineNumber = Math.min(other.b.selectionStartLineNumber, other.b.positionLineNumber);
    if (thisLineNumber === otherLineNumber) {
      return 1;
    }
    if (Math.abs(thisLineNumber - otherLineNumber) < _$bub.a) {
      return 2;
    }
    return 3;
  }
  restore(options3) {
    const textEditorOptions = {
      ...options3,
      selection: this.b,
      selectionRevealType: 1
      /* TextEditorSelectionRevealType.CenterIfOutsideViewport */
    };
    return textEditorOptions;
  }
  log() {
    return `line: ${this.b.startLineNumber}-${this.b.endLineNumber}, col:  ${this.b.startColumn}-${this.b.endColumn}`;
  }
};

// out-build/vs/workbench/common/editor/editorOptions.js
function applyTextEditorOptions(options3, editor, scrollType) {
  let applied = false;
  const viewState = massageEditorViewState(options3);
  if ($oL(viewState)) {
    editor.restoreViewState(viewState);
    applied = true;
  }
  if (options3.selection) {
    const range = {
      startLineNumber: options3.selection.startLineNumber,
      startColumn: options3.selection.startColumn,
      endLineNumber: options3.selection.endLineNumber ?? options3.selection.startLineNumber,
      endColumn: options3.selection.endColumn ?? options3.selection.startColumn
    };
    editor.setSelection(
      range,
      options3.selectionSource ?? "code.navigation"
      /* TextEditorSelectionSource.NAVIGATION */
    );
    if (options3.selectionRevealType === 2) {
      editor.revealRangeNearTop(range, scrollType);
    } else if (options3.selectionRevealType === 3) {
      editor.revealRangeNearTopIfOutsideViewport(range, scrollType);
    } else if (options3.selectionRevealType === 1) {
      editor.revealRangeInCenterIfOutsideViewport(range, scrollType);
    } else {
      editor.revealRangeInCenter(range, scrollType);
    }
    applied = true;
  }
  return applied;
}
function massageEditorViewState(options3) {
  if (!options3.selection || !options3.viewState) {
    return options3.viewState;
  }
  const candidateDiffViewState = options3.viewState;
  if (candidateDiffViewState.modified) {
    candidateDiffViewState.modified.cursorState = [];
    return candidateDiffViewState;
  }
  const candidateEditorViewState = options3.viewState;
  if (candidateEditorViewState.cursorState) {
    candidateEditorViewState.cursorState = [];
  }
  return candidateEditorViewState;
}

// out-build/vs/workbench/common/editor/editorModel.js
var $rG = class extends $3c {
  constructor() {
    super(...arguments);
    this.f = this.B(new $ze());
    this.onWillDispose = this.f.event;
    this.h = false;
  }
  /**
   * Causes this model to resolve returning a promise when loading is completed.
   */
  async resolve() {
    this.h = true;
  }
  /**
   * Returns whether this model was loaded or not.
   */
  isResolved() {
    return this.h;
  }
  /**
   * Find out if this model has been disposed.
   */
  isDisposed() {
    return this.q.isDisposed;
  }
  /**
   * Subclasses should implement to free resources that have been claimed through loading.
   */
  dispose() {
    this.f.fire();
    super.dispose();
  }
};

// out-build/vs/workbench/services/languageDetection/common/languageDetectionWorkerService.js
var $tG = $Qk("ILanguageDetectionService");
var $uG = "languageDetection";
var $vG = "automaticlanguagedetection.likelywrong";
var $wG = "automaticlanguagedetection.stats";

// out-build/vs/workbench/common/editor/textEditorModel.js
var $xG_1;
var $xG = class $xG2 extends $rG {
  static {
    $xG_1 = this;
  }
  static {
    this.a = 600;
  }
  constructor(n, r2, s, t, textEditorModelHandle) {
    super();
    this.n = n;
    this.r = r2;
    this.s = s;
    this.t = t;
    this.b = void 0;
    this.j = this.B(new $4c());
    this.m = this.B(new $Th($xG_1.a));
    this.y = false;
    if (textEditorModelHandle) {
      this.u(textEditorModelHandle);
    }
  }
  u(textEditorModelHandle) {
    const model = this.n.getModel(textEditorModelHandle);
    if (!model) {
      throw new Error(`Document with resource ${textEditorModelHandle.toString(true)} does not exist`);
    }
    this.b = textEditorModelHandle;
    this.w(model);
  }
  w(model) {
    this.j.value = model.onWillDispose(() => {
      this.b = void 0;
      this.dispose();
    });
  }
  get textEditorModel() {
    return this.b ? this.n.getModel(this.b) : null;
  }
  isReadonly() {
    return true;
  }
  get hasLanguageSetExplicitly() {
    return this.y;
  }
  setLanguageId(languageId, source) {
    this.y = true;
    this.z(languageId, source);
  }
  z(languageId, source) {
    if (!this.isResolved()) {
      return;
    }
    if (!languageId || languageId === this.textEditorModel.getLanguageId()) {
      return;
    }
    this.textEditorModel.setLanguage(this.r.createById(languageId), source);
  }
  C(model) {
    const disposable = this.B(model.onDidChangeLanguage((e) => {
      if (e.source === $uG) {
        return;
      }
      this.y = true;
      disposable.dispose();
    }));
  }
  getLanguageId() {
    return this.textEditorModel?.getLanguageId();
  }
  D() {
    return this.m.trigger(() => this.F());
  }
  async F() {
    if (this.hasLanguageSetExplicitly || // skip detection when the user has made an explicit choice on the language
    !this.b || // require a URI to run the detection for
    !this.s.isEnabledForLanguage(this.getLanguageId() ?? $KF)) {
      return;
    }
    const lang = await this.s.detectLanguage(this.b);
    const prevLang = this.getLanguageId();
    if (lang && lang !== prevLang && !this.isDisposed()) {
      this.z(lang, $uG);
      const languageName = this.r.getLanguageName(lang);
      this.t.alert(localize(4139, null, languageName ?? lang));
    }
  }
  /**
   * Creates the text editor model with the provided value, optional preferred language
   * (can be comma separated for multiple values) and optional resource URL.
   */
  G(value, resource, preferredLanguageId) {
    const firstLineText = this.I(value);
    const languageSelection = this.J(resource, this.r, preferredLanguageId, firstLineText);
    return this.H(value, languageSelection, resource);
  }
  H(value, languageSelection, resource) {
    let model = resource && this.n.getModel(resource);
    if (!model) {
      model = this.n.createModel(value, languageSelection, resource);
      this.g = true;
      this.w(model);
    } else {
      this.updateTextEditorModel(value, languageSelection.languageId);
    }
    this.b = model.uri;
    return model;
  }
  I(value) {
    const textBufferFactory = value;
    if (typeof textBufferFactory.getFirstLineText === "function") {
      return textBufferFactory.getFirstLineText(
        1e3
        /* ModelConstants.FIRST_LINE_DETECTION_LENGTH_LIMIT */
      );
    }
    const textSnapshot = value;
    return textSnapshot.getLineContent(1).substr(
      0,
      1e3
      /* ModelConstants.FIRST_LINE_DETECTION_LENGTH_LIMIT */
    );
  }
  /**
   * Gets the language for the given identifier. Subclasses can override to provide their own implementation of this lookup.
   *
   * @param firstLineText optional first line of the text buffer to set the language on. This can be used to guess a language from content.
   */
  J(resource, languageService, preferredLanguage, firstLineText) {
    if (!preferredLanguage || preferredLanguage === $KF) {
      return languageService.createByFilepathOrFirstLine(resource ?? null, firstLineText);
    }
    return languageService.createById(preferredLanguage);
  }
  /**
   * Updates the text editor model with the provided value. If the value is the same as the model has, this is a no-op.
   */
  updateTextEditorModel(newValue, preferredLanguageId) {
    if (!this.isResolved()) {
      return;
    }
    if (newValue) {
      this.n.updateModel(this.textEditorModel, newValue);
    }
    if (preferredLanguageId && preferredLanguageId !== $KF && this.textEditorModel.getLanguageId() !== preferredLanguageId) {
      this.textEditorModel.setLanguage(this.r.createById(preferredLanguageId));
    }
  }
  createSnapshot() {
    if (!this.textEditorModel) {
      return null;
    }
    return this.textEditorModel.createSnapshot(
      true
      /* preserve BOM */
    );
  }
  isResolved() {
    return !!this.b;
  }
  dispose() {
    this.j.dispose();
    if (this.b && this.g) {
      this.n.destroyModel(this.b);
    }
    this.b = void 0;
    this.g = false;
    super.dispose();
  }
};
$xG = $xG_1 = __decorate([
  __param(0, $sG),
  __param(1, $1E),
  __param(2, $tG),
  __param(3, $ND)
], $xG);

// out-build/vs/workbench/common/editor/diffEditorModel.js
var $dub = class extends $rG {
  get originalModel() {
    return this.a;
  }
  get modifiedModel() {
    return this.b;
  }
  constructor(originalModel, modifiedModel) {
    super();
    this.a = originalModel;
    this.b = modifiedModel;
  }
  async resolve() {
    await Promise.all([
      this.a?.resolve(),
      this.b?.resolve()
    ]);
  }
  isResolved() {
    return !!(this.a?.isResolved() && this.b?.isResolved());
  }
  dispose() {
    super.dispose();
  }
};

// out-build/vs/workbench/common/editor/textDiffEditorModel.js
var $eub = class extends $dub {
  get originalModel() {
    return this.a;
  }
  get modifiedModel() {
    return this.b;
  }
  get textDiffEditorModel() {
    return this.j;
  }
  constructor(originalModel, modifiedModel) {
    super(originalModel, modifiedModel);
    this.j = void 0;
    this.a = originalModel;
    this.b = modifiedModel;
    this.m();
  }
  async resolve() {
    await super.resolve();
    this.m();
  }
  m() {
    if (this.originalModel?.isResolved() && this.modifiedModel?.isResolved()) {
      if (!this.j) {
        this.j = {
          original: this.originalModel.textEditorModel,
          modified: this.modifiedModel.textEditorModel
        };
      } else {
        this.j.original = this.originalModel.textEditorModel;
        this.j.modified = this.modifiedModel.textEditorModel;
      }
    }
  }
  isResolved() {
    return !!this.j;
  }
  isReadonly() {
    return !!this.modifiedModel && this.modifiedModel.isReadonly();
  }
  dispose() {
    this.j = void 0;
    super.dispose();
  }
};

// out-build/vs/workbench/common/editor/diffEditorInput.js
var $fub_1;
var $fub = class $fub2 extends $1I {
  static {
    $fub_1 = this;
  }
  static {
    this.ID = "workbench.editors.diffEditorInput";
  }
  get typeId() {
    return $fub_1.ID;
  }
  get editorId() {
    return this.modified.editorId === this.original.editorId ? this.modified.editorId : void 0;
  }
  get capabilities() {
    let capabilities = super.capabilities;
    if (this.u.forceDescription) {
      capabilities |= 64;
    }
    return capabilities;
  }
  constructor(preferredName, preferredDescription, original, modified, w, editorService) {
    super(preferredName, preferredDescription, original, modified, editorService);
    this.original = original;
    this.modified = modified;
    this.w = w;
    this.t = void 0;
    this.u = this.y();
  }
  y() {
    let name;
    let forceDescription = false;
    if (this.b) {
      name = this.b;
    } else {
      const originalName = this.original.getName();
      const modifiedName = this.modified.getName();
      name = localize(4137, null, originalName, modifiedName);
      forceDescription = originalName === modifiedName;
    }
    let shortDescription;
    let mediumDescription;
    let longDescription;
    if (this.c) {
      shortDescription = this.c;
      mediumDescription = this.c;
      longDescription = this.c;
    } else {
      shortDescription = this.z(this.original.getDescription(
        0
        /* Verbosity.SHORT */
      ), this.modified.getDescription(
        0
        /* Verbosity.SHORT */
      ));
      longDescription = this.z(this.original.getDescription(
        2
        /* Verbosity.LONG */
      ), this.modified.getDescription(
        2
        /* Verbosity.LONG */
      ));
      const originalMediumDescription = this.original.getDescription(
        1
        /* Verbosity.MEDIUM */
      );
      const modifiedMediumDescription = this.modified.getDescription(
        1
        /* Verbosity.MEDIUM */
      );
      if (typeof originalMediumDescription === "string" && typeof modifiedMediumDescription === "string" && // we can only `shorten` when both sides are strings...
      (originalMediumDescription || modifiedMediumDescription)) {
        const [shortenedOriginalMediumDescription, shortenedModifiedMediumDescription] = $4t([originalMediumDescription, modifiedMediumDescription]);
        mediumDescription = this.z(shortenedOriginalMediumDescription, shortenedModifiedMediumDescription);
      }
    }
    let shortTitle = this.z(this.original.getTitle(
      0
      /* Verbosity.SHORT */
    ) ?? this.original.getName(), this.modified.getTitle(
      0
      /* Verbosity.SHORT */
    ) ?? this.modified.getName(), " \u2194 ");
    let mediumTitle = this.z(this.original.getTitle(
      1
      /* Verbosity.MEDIUM */
    ) ?? this.original.getName(), this.modified.getTitle(
      1
      /* Verbosity.MEDIUM */
    ) ?? this.modified.getName(), " \u2194 ");
    let longTitle = this.z(this.original.getTitle(
      2
      /* Verbosity.LONG */
    ) ?? this.original.getName(), this.modified.getTitle(
      2
      /* Verbosity.LONG */
    ) ?? this.modified.getName(), " \u2194 ");
    const preferredTitle = this.r();
    if (preferredTitle) {
      shortTitle = `${preferredTitle} (${shortTitle})`;
      mediumTitle = `${preferredTitle} (${mediumTitle})`;
      longTitle = `${preferredTitle} (${longTitle})`;
    }
    return { name, shortDescription, mediumDescription, longDescription, forceDescription, shortTitle, mediumTitle, longTitle };
  }
  z(originalLabel, modifiedLabel, separator = " - ") {
    if (!originalLabel || !modifiedLabel) {
      return void 0;
    }
    if (originalLabel === modifiedLabel) {
      return modifiedLabel;
    }
    return `${originalLabel}${separator}${modifiedLabel}`;
  }
  getName() {
    return this.u.name;
  }
  getDescription(verbosity = 1) {
    switch (verbosity) {
      case 0:
        return this.u.shortDescription;
      case 2:
        return this.u.longDescription;
      case 1:
      default:
        return this.u.mediumDescription;
    }
  }
  getTitle(verbosity) {
    switch (verbosity) {
      case 0:
        return this.u.shortTitle;
      case 2:
        return this.u.longTitle;
      default:
      case 1:
        return this.u.mediumTitle;
    }
  }
  async resolve() {
    const resolvedModel = await this.C();
    this.t?.dispose();
    this.t = resolvedModel;
    return this.t;
  }
  prefersEditorPane(editorPanes) {
    if (this.w) {
      return editorPanes.find((editorPane) => editorPane.typeId === $4K);
    }
    return editorPanes.find((editorPane) => editorPane.typeId === $3K);
  }
  async C() {
    const [originalEditorModel, modifiedEditorModel] = await Promise.all([
      this.original.resolve(),
      this.modified.resolve()
    ]);
    if (modifiedEditorModel instanceof $xG && originalEditorModel instanceof $xG) {
      return new $eub(originalEditorModel, modifiedEditorModel);
    }
    return new $dub($wl(originalEditorModel) ? originalEditorModel : void 0, $wl(modifiedEditorModel) ? modifiedEditorModel : void 0);
  }
  toUntyped(options3) {
    const untyped = super.toUntyped(options3);
    if (untyped) {
      return {
        ...untyped,
        modified: untyped.primary,
        original: untyped.secondary
      };
    }
    return void 0;
  }
  matches(otherInput) {
    if (this === otherInput) {
      return true;
    }
    if (otherInput instanceof $fub_1) {
      return this.modified.matches(otherInput.modified) && this.original.matches(otherInput.original) && otherInput.w === this.w;
    }
    if ($9K(otherInput)) {
      return this.modified.matches(otherInput.modified) && this.original.matches(otherInput.original);
    }
    return false;
  }
  dispose() {
    if (this.t) {
      this.t.dispose();
      this.t = void 0;
    }
    super.dispose();
  }
};
$fub = $fub_1 = __decorate([
  __param(5, $mJ)
], $fub);
var $gub = class extends $2I {
  b(instantiationService, name, description, secondaryInput, primaryInput) {
    return instantiationService.createInstance($fub, name, description, secondaryInput, primaryInput, void 0);
  }
};

// out-build/vs/workbench/services/preferences/common/preferences.js
var SettingValueType;
(function(SettingValueType2) {
  SettingValueType2["Null"] = "null";
  SettingValueType2["Enum"] = "enum";
  SettingValueType2["String"] = "string";
  SettingValueType2["MultilineString"] = "multiline-string";
  SettingValueType2["Integer"] = "integer";
  SettingValueType2["Number"] = "number";
  SettingValueType2["Boolean"] = "boolean";
  SettingValueType2["Array"] = "array";
  SettingValueType2["Exclude"] = "exclude";
  SettingValueType2["Include"] = "include";
  SettingValueType2["Complex"] = "complex";
  SettingValueType2["NullableInteger"] = "nullable-integer";
  SettingValueType2["NullableNumber"] = "nullable-number";
  SettingValueType2["Object"] = "object";
  SettingValueType2["BooleanObject"] = "boolean-object";
  SettingValueType2["LanguageTag"] = "language-tag";
  SettingValueType2["ExtensionToggle"] = "extension-toggle";
  SettingValueType2["ComplexObject"] = "complex-object";
})(SettingValueType || (SettingValueType = {}));
var SettingMatchType;
(function(SettingMatchType2) {
  SettingMatchType2[SettingMatchType2["None"] = 0] = "None";
  SettingMatchType2[SettingMatchType2["LanguageTagSettingMatch"] = 1] = "LanguageTagSettingMatch";
  SettingMatchType2[SettingMatchType2["RemoteMatch"] = 2] = "RemoteMatch";
  SettingMatchType2[SettingMatchType2["DescriptionOrValueMatch"] = 4] = "DescriptionOrValueMatch";
  SettingMatchType2[SettingMatchType2["KeyMatch"] = 8] = "KeyMatch";
})(SettingMatchType || (SettingMatchType = {}));
function $SK(options3) {
  return {
    // Inherit provided options
    ...options3,
    // Enforce some options for settings specifically
    override: $1K.id,
    pinned: true
  };
}
var $TK = $Qk("preferencesService");
var $UK = "editor.contrib.defineKeybinding";
var $VK = ".vscode/settings.json";
var $WK = "workbench.settings.openDefaultSettings";
var $XK = "workbench.settings.useSplitJSON";
var $YK = "settings";

// out-build/vs/workbench/browser/parts/editor/textDiffEditor.js
var $hub_1;
var $hub = class $hub2 extends $aub {
  static {
    $hub_1 = this;
  }
  static {
    this.ID = $3K;
  }
  get scopedContextKeyService() {
    if (!this.a) {
      return void 0;
    }
    const originalEditor = this.a.getOriginalEditor();
    const modifiedEditor = this.a.getModifiedEditor();
    return (originalEditor.hasTextFocus() ? originalEditor : modifiedEditor).invokeWithinContext((accessor) => accessor.get($on));
  }
  constructor(group2, telemetryService, instantiationService, storageService, configurationService, editorService, themeService, editorGroupService, fileService, f) {
    super($hub_1.ID, group2, telemetryService, instantiationService, storageService, configurationService, themeService, editorService, editorGroupService, fileService);
    this.f = f;
    this.a = void 0;
    this.c = void 0;
    this.Tb = null;
  }
  getTitle() {
    if (this.input) {
      return this.input.getName();
    }
    return localize(3596, null);
  }
  Lb(parent, configuration2) {
    this.a = this.B(this.m.createInstance($c_, parent, configuration2, {}));
  }
  Mb(options3) {
    this.a?.updateOptions(options3);
  }
  Nb() {
    return this.a?.getModifiedEditor();
  }
  async setInput(input, options3, context, token) {
    if (this.Tb) {
      this.Tb.dispose();
      this.Tb = null;
    }
    this.c = void 0;
    await super.setInput(input, options3, context, token);
    try {
      const resolvedModel = await input.resolve();
      if (token.isCancellationRequested) {
        return void 0;
      }
      if (!(resolvedModel instanceof $eub)) {
        this.Wb(input, options3);
        return void 0;
      }
      const control = $Kg(this.a);
      const resolvedDiffEditorModel = resolvedModel;
      const vm = resolvedDiffEditorModel.textDiffEditorModel ? control.createViewModel(resolvedDiffEditorModel.textDiffEditorModel) : null;
      this.Tb = vm;
      await vm?.waitForDiff();
      control.setModel(vm);
      let hasPreviousViewState = false;
      if (!$oL(options3?.viewState)) {
        hasPreviousViewState = this.Vb(input, options3, context, control);
      }
      let optionsGotApplied = false;
      if (options3) {
        optionsGotApplied = applyTextEditorOptions(
          options3,
          control,
          1
          /* ScrollType.Immediate */
        );
      }
      if (!optionsGotApplied && !hasPreviousViewState) {
        control.revealFirstDiff();
      }
      control.updateOptions({
        ...this.Gb(resolvedDiffEditorModel.modifiedModel?.isReadonly()),
        originalEditable: !resolvedDiffEditorModel.originalModel?.isReadonly()
      });
      control.handleInitialized();
      this.c = new $te(false);
    } catch (error) {
      await this.Ub(error, input, options3);
    }
  }
  async Ub(error, input, options3) {
    if (this.ac(error)) {
      return this.Wb(input, options3);
    }
    if (error.fileOperationResult === 7) {
      let message;
      if (error instanceof $Gm) {
        message = localize(3597, null, $Sm.formatSize(error.size));
      } else {
        message = localize(3598, null);
      }
      throw $gL(this.group, input, options3, message, this.f);
    }
    throw error;
  }
  Vb(editor, options3, context, control) {
    const editorViewState = this.jb(editor, context);
    if (editorViewState) {
      if (options3?.selection && editorViewState.modified) {
        editorViewState.modified.cursorState = [];
      }
      control.restoreViewState(editorViewState);
      if (options3?.revealIfVisible) {
        control.revealFirstDiff();
      }
      return true;
    }
    return false;
  }
  Wb(input, options3) {
    const original = input.original;
    const modified = input.modified;
    const binaryDiffInput = this.m.createInstance($fub, input.getName(), input.getDescription(), original, modified, true);
    const fileEditorFactory = $Wn.as($ZK.EditorFactory).getFileEditorFactory();
    if (fileEditorFactory.isFileEditor(original)) {
      original.setForceOpenAsBinary();
    }
    if (fileEditorFactory.isFileEditor(modified)) {
      modified.setForceOpenAsBinary();
    }
    this.group.replaceEditors([{
      editor: input,
      replacement: binaryDiffInput,
      options: {
        ...options3,
        // Make sure to not steal away the currently active group
        // because we are triggering another openEditor() call
        // and do not control the initial intent that resulted
        // in us now opening as binary.
        activation: EditorActivation.PRESERVE,
        pinned: this.group.isPinned(input),
        sticky: this.group.isSticky(input)
      }
    }]);
  }
  setOptions(options3) {
    super.setOptions(options3);
    if (options3) {
      applyTextEditorOptions(
        options3,
        $Kg(this.a),
        0
        /* ScrollType.Smooth */
      );
    }
  }
  zb(e, resource) {
    if (super.zb(e, resource)) {
      return true;
    }
    return e.affectsConfiguration(resource, "diffEditor") || e.affectsConfiguration(resource, "accessibility.verbosity.diffEditor");
  }
  Bb(configuration2) {
    const editorConfiguration2 = super.Bb(configuration2);
    if ($Bg(configuration2.diffEditor)) {
      const diffEditorConfiguration = $Lv(configuration2.diffEditor);
      diffEditorConfiguration.diffCodeLens = diffEditorConfiguration.codeLens;
      delete diffEditorConfiguration.codeLens;
      diffEditorConfiguration.diffWordWrap = diffEditorConfiguration.wordWrap;
      delete diffEditorConfiguration.wordWrap;
      Object.assign(editorConfiguration2, diffEditorConfiguration);
    }
    const verbose = configuration2.accessibility?.verbosity?.diffEditor ?? false;
    editorConfiguration2.accessibilityVerbose = verbose;
    return editorConfiguration2;
  }
  Hb(configuration2) {
    return {
      ...super.Hb(configuration2),
      ...this.Gb(this.input?.isReadonly()),
      originalEditable: this.input instanceof $fub && !this.input.original.isReadonly(),
      lineDecorationsWidth: "2ch"
    };
  }
  Fb(input) {
    if (input instanceof $fub) {
      this.a?.updateOptions({
        ...this.Gb(input.isReadonly()),
        originalEditable: !input.original.isReadonly()
      });
    } else {
      super.Fb(input);
    }
  }
  ac(error) {
    if (Array.isArray(error)) {
      const errors = error;
      return errors.some((error2) => this.ac(error2));
    }
    return error.textFileOperationResult === 0;
  }
  clearInput() {
    if (this.Tb) {
      this.Tb.dispose();
      this.Tb = null;
    }
    super.clearInput();
    const inputLifecycleElapsed = this.c?.elapsed();
    this.c = void 0;
    if (typeof inputLifecycleElapsed === "number") {
      this.bc(inputLifecycleElapsed, this.getControl()?.getModel()?.modified?.getLanguageId());
    }
    this.a?.setModel(null);
  }
  bc(duration, languageId) {
    let collapseUnchangedRegions = false;
    if (this.a instanceof $c_) {
      collapseUnchangedRegions = this.a.collapseUnchangedRegions;
    }
    this.Q.publicLog2("diffEditor.editorVisibleTime", {
      editorVisibleTimeMs: duration,
      languageId: languageId ?? "",
      collapseUnchangedRegions
    });
  }
  getControl() {
    return this.a;
  }
  focus() {
    super.focus();
    this.a?.focus();
  }
  hasFocus() {
    return this.a?.hasTextFocus() || super.hasFocus();
  }
  Z(visible) {
    super.Z(visible);
    if (visible) {
      this.a?.onVisible();
    } else {
      this.a?.onHide();
    }
  }
  layout(dimension) {
    this.a?.layout(dimension);
  }
  setBoundarySashes(sashes) {
    this.a?.setBoundarySashes(sashes);
  }
  nb(input) {
    return input instanceof $fub;
  }
  mb(resource) {
    if (!this.a) {
      return void 0;
    }
    const model = this.a.getModel();
    if (!model || !model.modified || !model.original) {
      return void 0;
    }
    const modelUri = this.pb(model);
    if (!modelUri) {
      return void 0;
    }
    if (!$oh(modelUri, resource)) {
      return void 0;
    }
    return this.a.saveViewState() ?? void 0;
  }
  pb(modelOrInput) {
    let original;
    let modified;
    if (modelOrInput instanceof $fub) {
      original = modelOrInput.original.resource;
      modified = modelOrInput.modified.resource;
    } else if (!$dL(modelOrInput)) {
      original = modelOrInput.original.uri;
      modified = modelOrInput.modified.uri;
    }
    if (!original || !modified) {
      return void 0;
    }
    return URI.from({ scheme: "diff", path: `${$xk(original.toString())}${$xk(modified.toString())}` });
  }
};
$hub = $hub_1 = __decorate([
  __param(1, $zv),
  __param(2, $Pk),
  __param(3, $jv),
  __param(4, $zG),
  __param(5, $mJ),
  __param(6, $gs),
  __param(7, $iJ),
  __param(8, $km),
  __param(9, $TK)
], $hub);

// out-build/vs/workbench/common/contextkeys.js
var $lqb_1;
var $epb = new $nn("workbenchState", void 0, { type: "string", description: localize(4063, null) });
var $fpb = new $nn("workspaceFolderCount", 0, localize(4064, null));
var $gpb = new $nn("openFolderWorkspaceSupport", true, true);
var $hpb = new $nn("enterMultiRootWorkspaceSupport", true, true);
var $ipb = new $nn("emptyWorkspaceSupport", true, true);
var $jpb = new $nn("dirtyWorkingCopies", false, localize(4065, null));
var $kpb = new $nn("remoteName", "", localize(4066, null));
var $lpb = new $nn("virtualWorkspace", "", localize(4067, null));
var $mpb = new $nn("temporaryWorkspace", false, localize(4068, null));
var $npb = new $nn("isFullscreen", false, localize(4069, null));
var $opb = new $nn("isAuxiliaryWindowFocusedContext", false, localize(4070, null));
var $ppb = new $nn("hasWebFileSystemAccess", false, true);
var $qpb = new $nn("embedderIdentifier", void 0, localize(4071, null));
var $rpb = new $nn("isEnabledFileDownloads", true, true);
var $spb = new $nn("isEnabledFileUploads", true, true);
var $tpb = new $nn("activeEditorIsDirty", false, localize(4072, null));
var $upb = new $nn("activeEditorIsNotPreview", false, localize(4073, null));
var $vpb = new $nn("activeEditorIsFirstInGroup", false, localize(4074, null));
var $wpb = new $nn("activeEditorIsLastInGroup", false, localize(4075, null));
var $xpb = new $nn("activeEditorIsPinned", false, localize(4076, null));
var $ypb = new $nn("activeEditorIsReadonly", false, localize(4077, null));
var $zpb = new $nn("activeCompareEditorCanSwap", false, localize(4078, null));
var $Apb = new $nn("activeEditorCanToggleReadonly", true, localize(4079, null));
var $Bpb = new $nn("activeEditorCanRevert", false, localize(4080, null));
var $Cpb = new $nn("activeEditorCanSplitInGroup", true);
var $Dpb = new $nn("activeEditor", null, { type: "string", description: localize(4081, null) });
var $Epb = new $nn("activeEditorAvailableEditorIds", "", localize(4082, null));
var $Fpb = new $nn("textCompareEditorVisible", false, localize(4083, null));
var $Gpb = new $nn("textCompareEditorActive", false, localize(4084, null));
var $Hpb = new $nn("sideBySideEditorActive", false, localize(4085, null));
var $Ipb = new $nn("groupEditorsCount", 0, localize(4086, null));
var $Jpb = new $nn("activeEditorGroupEmpty", false, localize(4087, null));
var $Kpb = new $nn("activeEditorGroupIndex", 0, localize(4088, null));
var $Lpb = new $nn("activeEditorGroupLast", false, localize(4089, null));
var $Mpb = new $nn("activeEditorGroupLocked", false, localize(4090, null));
var $Npb = new $nn("multipleEditorGroups", false, localize(4091, null));
var $Opb = $Npb.toNegated();
var $Ppb = new $nn("multipleEditorsSelectedInGroup", false, localize(4092, null));
var $Qpb = new $nn("twoEditorsSelectedInGroup", false, localize(4093, null));
var $Rpb = new $nn("SelectedEditorsInGroupFileOrUntitledResourceContextKey", true, localize(4094, null));
var $Spb = new $nn("editorPartMultipleEditorGroups", false, localize(4095, null));
var $Tpb = $Spb.toNegated();
var $Upb = new $nn("editorPartMaximizedEditorGroup", false, localize(4096, null));
var $Vpb = new $nn("isAuxiliaryEditorPart", false, localize(4097, null));
var $Wpb = new $nn("editorIsOpen", false, localize(4098, null));
var $Xpb = new $nn("inZenMode", false, localize(4099, null));
var $Ypb = new $nn("isCenteredLayout", false, localize(4100, null));
var $Zpb = new $nn("splitEditorsVertically", false, localize(4101, null));
var $1pb = new $nn("mainEditorAreaVisible", true, localize(4102, null));
var $2pb = new $nn("editorTabsVisible", true, localize(4103, null));
var $3pb = new $nn("sideBarVisible", false, localize(4104, null));
var $4pb = new $nn("sideBarFocus", false, localize(4105, null));
var $5pb = new $nn("activeViewlet", "", localize(4106, null));
var $6pb = new $nn("statusBarFocused", false, localize(4107, null));
var $7pb = new $nn("titleBarStyle", $n && product_default.quality === "stable" ? "native" : "custom", localize(4108, null));
var $8pb = new $nn("titleBarVisible", false, localize(4109, null));
var $9pb = new $nn("bannerFocused", false, localize(4110, null));
var $0pb = new $nn("notificationFocus", true, localize(4111, null));
var $$pb = new $nn("notificationCenterVisible", false, localize(4112, null));
var $_pb = new $nn("notificationToastsVisible", false, localize(4113, null));
var $aqb = new $nn("activeAuxiliary", "", localize(4114, null));
var $bqb = new $nn("auxiliaryBarFocus", false, localize(4115, null));
var $cqb = new $nn("auxiliaryBarVisible", false, localize(4116, null));
var $dqb = new $nn("activePanel", "", localize(4117, null));
var $eqb = new $nn("panelFocus", false, localize(4118, null));
var $fqb = new $nn("panelPosition", "bottom", localize(4119, null));
var $gqb = new $nn("panelAlignment", "center", localize(4120, null));
var $hqb = new $nn("panelVisible", false, localize(4121, null));
var $iqb = new $nn("panelMaximized", false, localize(4122, null));
var $jqb = new $nn("focusedView", "", localize(4123, null));
function $kqb(viewId) {
  return `view.${viewId}.visible`;
}
var $lqb = class $lqb2 {
  static {
    $lqb_1 = this;
  }
  static {
    this.Scheme = new $nn("resourceScheme", void 0, { type: "string", description: localize(4124, null) });
  }
  static {
    this.Filename = new $nn("resourceFilename", void 0, { type: "string", description: localize(4125, null) });
  }
  static {
    this.Dirname = new $nn("resourceDirname", void 0, { type: "string", description: localize(4126, null) });
  }
  static {
    this.Path = new $nn("resourcePath", void 0, { type: "string", description: localize(4127, null) });
  }
  static {
    this.LangId = new $nn("resourceLangId", void 0, { type: "string", description: localize(4128, null) });
  }
  static {
    this.Resource = new $nn("resource", void 0, { type: "URI", description: localize(4129, null) });
  }
  static {
    this.Extension = new $nn("resourceExtname", void 0, { type: "string", description: localize(4130, null) });
  }
  static {
    this.HasResource = new $nn("resourceSet", void 0, { type: "boolean", description: localize(4131, null) });
  }
  static {
    this.IsFileSystemResource = new $nn("isFileSystemResource", void 0, { type: "boolean", description: localize(4132, null) });
  }
  constructor(m, n, o, p) {
    this.m = m;
    this.n = n;
    this.o = o;
    this.p = p;
    this.a = new $2c();
    this.d = $lqb_1.Scheme.bindTo(this.m);
    this.f = $lqb_1.Filename.bindTo(this.m);
    this.g = $lqb_1.Dirname.bindTo(this.m);
    this.h = $lqb_1.Path.bindTo(this.m);
    this.i = $lqb_1.LangId.bindTo(this.m);
    this.c = $lqb_1.Resource.bindTo(this.m);
    this.j = $lqb_1.Extension.bindTo(this.m);
    this.k = $lqb_1.HasResource.bindTo(this.m);
    this.l = $lqb_1.IsFileSystemResource.bindTo(this.m);
    this.a.add(n.onDidChangeFileSystemProviderRegistrations(() => {
      const resource = this.get();
      this.l.set(Boolean(resource && n.hasProvider(resource)));
    }));
    this.a.add(p.onModelAdded((model) => {
      if ($oh(model.uri, this.get())) {
        this.q();
      }
    }));
    this.a.add(p.onModelLanguageChanged((e) => {
      if ($oh(e.model.uri, this.get())) {
        this.q();
      }
    }));
  }
  dispose() {
    this.a.dispose();
  }
  q() {
    const value = this.get();
    if (!value) {
      this.i.set(null);
      return;
    }
    const langId = this.p.getModel(value)?.getLanguageId() ?? this.o.guessLanguageIdByFilepathOrFirstLine(value);
    this.i.set(langId);
  }
  set(value) {
    value = value ?? void 0;
    if ($oh(this.b, value)) {
      return;
    }
    this.b = value;
    this.m.bufferChangeEvents(() => {
      this.c.set(value ? value.toString() : null);
      this.d.set(value ? value.scheme : null);
      this.f.set(value ? $sh(value) : null);
      this.g.set(value ? this.r($uh(value)) : null);
      this.h.set(value ? this.r(value) : null);
      this.q();
      this.j.set(value ? $th(value) : null);
      this.k.set(Boolean(value));
      this.l.set(value ? this.n.hasProvider(value) : false);
    });
  }
  r(uri) {
    if (uri.scheme === Schemas.file) {
      return uri.fsPath;
    }
    return uri.path;
  }
  reset() {
    this.b = void 0;
    this.m.bufferChangeEvents(() => {
      this.c.reset();
      this.d.reset();
      this.f.reset();
      this.g.reset();
      this.h.reset();
      this.i.reset();
      this.j.reset();
      this.k.reset();
      this.l.reset();
    });
  }
  get() {
    return this.b;
  }
};
$lqb = $lqb_1 = __decorate([
  __param(0, $on),
  __param(1, $km),
  __param(2, $1E),
  __param(3, $sG)
], $lqb);
function $mqb(contextKey, editor, editorResolverService) {
  if (!editor) {
    contextKey.set("");
    return;
  }
  const editorResource = editor.resource;
  if (editorResource?.scheme === Schemas.untitled && editor.editorId !== $1K.id) {
    contextKey.set("");
  } else {
    const editors = editorResource ? editorResolverService.getEditors(editorResource).map((editor2) => editor2.id) : [];
    contextKey.set(editors.join(","));
  }
}

// out-build/vs/workbench/services/editor/common/editorGroupColumn.js
function $zS(editorGroupService, configurationService, column = $nJ) {
  if (column === $nJ || column === $oJ) {
    return column;
  }
  let groupInColumn = editorGroupService.getGroups(
    2
    /* GroupsOrder.GRID_APPEARANCE */
  )[column];
  if (!groupInColumn && column < 9) {
    for (let i2 = 0; i2 <= column; i2++) {
      const editorGroups = editorGroupService.getGroups(
        2
        /* GroupsOrder.GRID_APPEARANCE */
      );
      if (!editorGroups[i2]) {
        editorGroupService.addGroup(editorGroups[i2 - 1], $lJ(configurationService));
      }
    }
    groupInColumn = editorGroupService.getGroups(
      2
      /* GroupsOrder.GRID_APPEARANCE */
    )[column];
  }
  return groupInColumn?.id ?? $oJ;
}
function $AS(editorGroupService, editorGroup) {
  const group2 = typeof editorGroup === "number" ? editorGroupService.getGroup(editorGroup) : editorGroup;
  return editorGroupService.getGroups(
    2
    /* GroupsOrder.GRID_APPEARANCE */
  ).indexOf(group2 ?? editorGroupService.activeGroup);
}

// out-build/vs/workbench/services/remote/common/remoteAgentService.js
var $RL = $Qk("remoteAgentService");
var $SL = new class {
  constructor() {
    this.maxSampleCount = 5;
    this.sampleDelay = 2e3;
    this.initial = [];
    this.maxInitialCount = 3;
    this.average = [];
    this.maxAverageCount = 100;
    this.highLatencyMultiple = 2;
    this.highLatencyMinThreshold = 500;
    this.highLatencyMaxThreshold = 1500;
    this.lastMeasurement = void 0;
  }
  get latency() {
    return this.lastMeasurement;
  }
  async measure(remoteAgentService) {
    let currentLatency = Infinity;
    for (let i2 = 0; i2 < this.maxSampleCount; i2++) {
      const rtt = await remoteAgentService.getRoundTripTime();
      if (rtt === void 0) {
        return void 0;
      }
      currentLatency = Math.min(
        currentLatency,
        rtt / 2
        /* we want just one way, not round trip time */
      );
      await $Wh(this.sampleDelay);
    }
    this.average.push(currentLatency);
    if (this.average.length > this.maxAverageCount) {
      this.average.shift();
    }
    let initialLatency = void 0;
    if (this.initial.length < this.maxInitialCount) {
      this.initial.push(currentLatency);
    } else {
      initialLatency = this.initial.reduce((sum, value) => sum + value, 0) / this.initial.length;
    }
    this.lastMeasurement = {
      initial: initialLatency,
      current: currentLatency,
      average: this.average.reduce((sum, value) => sum + value, 0) / this.average.length,
      high: (() => {
        if (typeof initialLatency === "undefined") {
          return false;
        }
        if (currentLatency > this.highLatencyMaxThreshold) {
          return true;
        }
        if (currentLatency > this.highLatencyMinThreshold && currentLatency > initialLatency * this.highLatencyMultiple) {
          return true;
        }
        return false;
      })()
    };
    return this.lastMeasurement;
  }
}();

// out-build/vs/workbench/common/configuration.js
var $TL = Object.freeze({
  "id": "application",
  "order": 100,
  "title": localize(4053, null),
  "type": "object"
});
var $UL = Object.freeze({
  "id": "workbench",
  "order": 7,
  "title": localize(4054, null),
  "type": "object"
});
var $VL = Object.freeze({
  "id": "security",
  "scope": 1,
  "title": localize(4055, null),
  "type": "object",
  "order": 7
});
var $WL = Object.freeze({
  "id": "problems",
  "title": localize(4056, null),
  "type": "object",
  "order": 101
});
var $XL = Object.freeze({
  "id": "window",
  "order": 8,
  "title": localize(4057, null),
  "type": "object"
});
var $YL = {
  ConfigurationMigration: "base.contributions.configuration.migration"
};
var ConfigurationMigrationRegistry = class {
  constructor() {
    this.migrations = [];
    this.a = new $ze();
    this.onDidRegisterConfigurationMigration = this.a.event;
  }
  registerConfigurationMigrations(configurationMigrations) {
    this.migrations.push(...configurationMigrations);
  }
};
var configurationMigrationRegistry = new ConfigurationMigrationRegistry();
$Wn.add($YL.ConfigurationMigration, configurationMigrationRegistry);
var $ZL = class $ZL2 extends $3c {
  static {
    this.ID = "workbench.contrib.configurationMigration";
  }
  constructor(a, b) {
    super();
    this.a = a;
    this.b = b;
    this.B(this.b.onDidChangeWorkspaceFolders(async (e) => {
      for (const folder of e.added) {
        await this.f(folder, configurationMigrationRegistry.migrations);
      }
    }));
    this.c(configurationMigrationRegistry.migrations);
    this.B(configurationMigrationRegistry.onDidRegisterConfigurationMigration((migration) => this.c(migration)));
  }
  async c(migrations) {
    await this.f(void 0, migrations);
    for (const folder of this.b.getWorkspace().folders) {
      await this.f(folder, migrations);
    }
  }
  async f(folder, migrations) {
    await Promise.all([migrations.map((migration) => this.g(migration, folder?.uri))]);
  }
  async g(migration, resource) {
    const inspectData = this.a.inspect(migration.key, { resource });
    const targetPairs = this.b.getWorkbenchState() === 3 ? [
      [
        "user",
        2
        /* ConfigurationTarget.USER */
      ],
      [
        "userLocal",
        3
        /* ConfigurationTarget.USER_LOCAL */
      ],
      [
        "userRemote",
        4
        /* ConfigurationTarget.USER_REMOTE */
      ],
      [
        "workspace",
        5
        /* ConfigurationTarget.WORKSPACE */
      ],
      [
        "workspaceFolder",
        6
        /* ConfigurationTarget.WORKSPACE_FOLDER */
      ]
    ] : [
      [
        "user",
        2
        /* ConfigurationTarget.USER */
      ],
      [
        "userLocal",
        3
        /* ConfigurationTarget.USER_LOCAL */
      ],
      [
        "userRemote",
        4
        /* ConfigurationTarget.USER_REMOTE */
      ],
      [
        "workspace",
        5
        /* ConfigurationTarget.WORKSPACE */
      ]
    ];
    for (const [dataKey, target] of targetPairs) {
      const inspectValue = inspectData[dataKey];
      if (!inspectValue) {
        continue;
      }
      const migrationValues = [];
      if (inspectValue.value !== void 0) {
        const keyValuePairs = await this.h(migration, dataKey, inspectValue.value, resource, void 0);
        for (const keyValuePair of keyValuePairs ?? []) {
          migrationValues.push([keyValuePair, []]);
        }
      }
      for (const { identifiers: identifiers2, value } of inspectValue.overrides ?? []) {
        if (value !== void 0) {
          const keyValuePairs = await this.h(migration, dataKey, value, resource, identifiers2);
          for (const keyValuePair of keyValuePairs ?? []) {
            migrationValues.push([keyValuePair, identifiers2]);
          }
        }
      }
      if (migrationValues.length) {
        await Promise.allSettled(migrationValues.map(async ([[key2, value], overrideIdentifiers]) => this.a.updateValue(key2, value.value, { resource, overrideIdentifiers }, target)));
      }
    }
  }
  async h(migration, dataKey, value, resource, overrideIdentifiers) {
    const valueAccessor = (key2) => {
      const inspectData = this.a.inspect(key2, { resource });
      const inspectValue = inspectData[dataKey];
      if (!inspectValue) {
        return void 0;
      }
      if (!overrideIdentifiers) {
        return inspectValue.value;
      }
      return inspectValue.overrides?.find(({ identifiers: identifiers2 }) => $Pv(identifiers2, overrideIdentifiers))?.value;
    };
    const result = await migration.migrateFn(value, valueAccessor);
    return Array.isArray(result) ? result : [[migration.key, result]];
  }
};
$ZL = __decorate([
  __param(0, $kl),
  __param(1, $Zk)
], $ZL);
var $1L = class $1L2 extends $3c {
  static {
    this.ID = "workbench.contrib.dynamicWorkbenchSecurityConfiguration";
  }
  constructor(b) {
    super();
    this.b = b;
    this.a = new $gi();
    this.ready = this.a.p;
    this.c();
  }
  async c() {
    try {
      await this.f();
    } finally {
      this.a.complete();
    }
  }
  async f() {
    if (!$l) {
      const remoteEnvironment = await this.b.getEnvironment();
      if (remoteEnvironment?.os !== 1) {
        return;
      }
    }
    const registry4 = $Wn.as($Ht.Configuration);
    registry4.registerConfiguration({
      ...$VL,
      "properties": {
        "security.allowedUNCHosts": {
          "type": "array",
          "items": {
            "type": "string",
            "pattern": "^[^\\\\]+$",
            "patternErrorMessage": localize(4058, null)
          },
          "default": [],
          "markdownDescription": localize(4059, null),
          "scope": 2
          /* ConfigurationScope.MACHINE */
        },
        "security.restrictUNCAccess": {
          "type": "boolean",
          "default": true,
          "markdownDescription": localize(4060, null),
          "scope": 2
          /* ConfigurationScope.MACHINE */
        }
      }
    });
  }
};
$1L = __decorate([
  __param(0, $RL)
], $1L);
var $2L = "window.newWindowProfile";
var $3L = class $3L2 extends $3c {
  static {
    this.ID = "workbench.contrib.dynamicWindowConfiguration";
  }
  constructor(c, f) {
    super();
    this.c = c;
    this.f = f;
    this.g();
    this.B(this.c.onDidChangeProfiles((e) => this.g()));
    this.h();
    this.j();
    this.B(f.onDidChangeConfiguration((e) => {
      if (e.source !== 7 && e.affectsConfiguration($2L)) {
        this.h();
      }
    }));
    this.B(this.c.onDidChangeProfiles(() => this.j()));
  }
  g() {
    const registry4 = $Wn.as($Ht.Configuration);
    const configurationNode = {
      ...$XL,
      "properties": {
        [$2L]: {
          "type": ["string", "null"],
          "default": null,
          "enum": [...this.c.profiles.map((profile) => profile.name), null],
          "enumItemLabels": [...this.c.profiles.map((p) => ""), localize(4061, null)],
          "description": localize(4062, null),
          "scope": 1
        }
      }
    };
    if (this.a) {
      registry4.updateConfigurations({ add: [configurationNode], remove: [this.a] });
    } else {
      registry4.registerConfiguration(configurationNode);
    }
    this.a = configurationNode;
  }
  h() {
    const newWindowProfileName = this.f.getValue($2L);
    this.b = newWindowProfileName ? this.c.profiles.find((profile) => profile.name === newWindowProfileName) : void 0;
  }
  j() {
    const newWindowProfileName = this.f.getValue($2L);
    if (!newWindowProfileName) {
      return;
    }
    const profile = this.b ? this.c.profiles.find((profile2) => profile2.id === this.b.id) : void 0;
    if (newWindowProfileName === profile?.name) {
      return;
    }
    this.f.updateValue($2L, profile?.name);
  }
};
$3L = __decorate([
  __param(0, $rs),
  __param(1, $kl)
], $3L);

// out-build/vs/workbench/services/editor/common/editorResolverService.js
var $4L = $Qk("editorResolverService");
var $5L = "workbench.editorAssociations";
var configurationRegistry4 = $Wn.as($Ht.Configuration);
var editorAssociationsConfigurationNode = {
  ...$UL,
  properties: {
    "workbench.editorAssociations": {
      type: "object",
      markdownDescription: localize(12702, null),
      additionalProperties: {
        type: "string"
      }
    }
  }
};
configurationRegistry4.registerConfiguration(editorAssociationsConfigurationNode);
var RegisteredEditorPriority;
(function(RegisteredEditorPriority2) {
  RegisteredEditorPriority2["builtin"] = "builtin";
  RegisteredEditorPriority2["option"] = "option";
  RegisteredEditorPriority2["exclusive"] = "exclusive";
  RegisteredEditorPriority2["default"] = "default";
})(RegisteredEditorPriority || (RegisteredEditorPriority = {}));
var ResolvedStatus;
(function(ResolvedStatus2) {
  ResolvedStatus2[ResolvedStatus2["ABORT"] = 1] = "ABORT";
  ResolvedStatus2[ResolvedStatus2["NONE"] = 2] = "NONE";
})(ResolvedStatus || (ResolvedStatus = {}));
function $6L(priority) {
  switch (priority) {
    case RegisteredEditorPriority.exclusive:
      return 5;
    case RegisteredEditorPriority.default:
      return 4;
    case RegisteredEditorPriority.builtin:
      return 3;
    case RegisteredEditorPriority.option:
    default:
      return 1;
  }
}
function $7L(globPattern, resource) {
  const excludedSchemes = /* @__PURE__ */ new Set([
    Schemas.extension,
    Schemas.webviewPanel,
    Schemas.vscodeWorkspaceTrust,
    Schemas.vscodeSettings
  ]);
  if (excludedSchemes.has(resource.scheme)) {
    return false;
  }
  const matchOnPath = typeof globPattern === "string" && globPattern.indexOf($kc.sep) >= 0;
  const target = matchOnPath ? `${resource.scheme}:${resource.path}` : $sh(resource);
  return $Cl(typeof globPattern === "string" ? globPattern.toLowerCase() : globPattern, target.toLowerCase());
}

// out-build/vs/platform/workspace/common/virtualWorkspace.js
function $8S(resource) {
  return resource.scheme !== Schemas.file && resource.scheme !== Schemas.vscodeRemote;
}
function $9S(workspace2) {
  if (workspace2.folders.length) {
    return workspace2.folders.every((f) => $8S(f.uri)) ? workspace2.folders[0].uri : void 0;
  } else if (workspace2.configuration && $8S(workspace2.configuration)) {
    return workspace2.configuration;
  }
  return void 0;
}
function $0S(workspace2) {
  return $9S(workspace2)?.scheme;
}
function $$S(workspace2) {
  return $9S(workspace2)?.authority;
}
function $_S(workspace2) {
  return $9S(workspace2) !== void 0;
}

// out-build/vs/workbench/services/environment/common/environmentService.js
var $US = $Rk($Xk);

// out-build/vs/workbench/services/path/common/pathService.js
var $bT_1;
var $aT = $Qk("pathService");
var $bT = $bT_1 = class $bT2 {
  constructor(d, e, f, g) {
    this.d = d;
    this.e = e;
    this.f = f;
    this.g = g;
    this.a = (async () => {
      const env3 = await this.e.getEnvironment();
      return env3?.os || OS;
    })();
    this.b = (async () => {
      const env3 = await this.e.getEnvironment();
      const userHome = this.c = env3?.userHome ?? d;
      return userHome;
    })();
  }
  hasValidBasename(resource, arg2, basename) {
    if (typeof arg2 === "string" || typeof arg2 === "undefined") {
      return this.a.then((os) => this.h(resource, os, arg2));
    }
    return this.h(resource, arg2, basename);
  }
  h(resource, os, name) {
    if (resource.scheme === Schemas.file || resource.scheme === Schemas.vscodeRemote) {
      return $Xg(
        name ?? $sh(resource),
        os === 1
        /* OperatingSystem.Windows */
      );
    }
    return true;
  }
  get defaultUriScheme() {
    return $bT_1.findDefaultUriScheme(this.f, this.g);
  }
  static findDefaultUriScheme(environmentService, contextService) {
    if (environmentService.remoteAuthority) {
      return Schemas.vscodeRemote;
    }
    const virtualWorkspace = $0S(contextService.getWorkspace());
    if (virtualWorkspace) {
      return virtualWorkspace;
    }
    const firstFolder = contextService.getWorkspace().folders[0];
    if (firstFolder) {
      return firstFolder.uri.scheme;
    }
    const configuration2 = contextService.getWorkspace().configuration;
    if (configuration2) {
      return configuration2.scheme;
    }
    return Schemas.file;
  }
  userHome(options3) {
    return options3?.preferLocal ? this.d : this.b;
  }
  get resolvedUserHome() {
    return this.c;
  }
  get path() {
    return this.a.then((os) => {
      return os === 1 ? $jc : $kc;
    });
  }
  async fileURI(_path) {
    let authority = "";
    const os = await this.a;
    if (os === 1) {
      _path = _path.replace(/\\/g, "/");
    }
    if (_path[0] === "/" && _path[1] === "/") {
      const idx = _path.indexOf("/", 2);
      if (idx === -1) {
        authority = _path.substring(2);
        _path = "/";
      } else {
        authority = _path.substring(2, idx);
        _path = _path.substring(idx) || "/";
      }
    }
    return URI.from({
      scheme: Schemas.file,
      authority,
      path: _path,
      query: "",
      fragment: ""
    });
  }
};
$bT = $bT_1 = __decorate([
  __param(1, $RL),
  __param(2, $US),
  __param(3, $Zk)
], $bT);

// out-build/vs/workbench/services/workingCopy/common/workingCopyBackup.js
var $yG = $Qk("workingCopyBackupService");

// out-build/vs/workbench/services/workingCopy/common/workingCopy.js
var WorkingCopyCapabilities;
(function(WorkingCopyCapabilities2) {
  WorkingCopyCapabilities2[WorkingCopyCapabilities2["None"] = 0] = "None";
  WorkingCopyCapabilities2[WorkingCopyCapabilities2["Untitled"] = 2] = "Untitled";
  WorkingCopyCapabilities2[WorkingCopyCapabilities2["Scratchpad"] = 4] = "Scratchpad";
})(WorkingCopyCapabilities || (WorkingCopyCapabilities = {}));
var $qG = "";

// out-build/vs/amdX.js
var $rJ = false;
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) {
        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}://${$hh}`)) {
            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 = $ps();
        globalThis.define(tmpModuleId, [scriptSrc], function(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);
    }
    await import(scriptSrc);
    return this.c.pop();
  }
  async j(scriptSrc) {
    try {
      const fs = (await import(`${"fs"}`)).default;
      const vm = (await import(`${"vm"}`)).default;
      const module2 = (await import(`${"module"}`)).default;
      const filePath = URI.parse(scriptSrc).fsPath;
      const content = fs.readFileSync(filePath).toString();
      const scriptSource = module2.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 $sJ(nodeModuleName, pathInsideNodeModule, isBuilt) {
  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 = $rJ && isBuilt && !$r;
    const actualNodeModulesPath = useASAR ? $fh : $eh;
    const resourcePath = `${actualNodeModulesPath}/${nodeModulePath}`;
    scriptSrc = $ih.asBrowserUri(resourcePath).toString(true);
  }
  const result = AMDModuleImporter.INSTANCE.load(scriptSrc);
  cache.set(nodeModulePath, result);
  return result;
}
function $tJ(nodeModuleName, pathInsideNodeModule) {
  const product2 = globalThis._VSCODE_PRODUCT_JSON;
  const isBuilt = Boolean((product2 ?? globalThis.vscode?.context?.configuration()?.product)?.commit);
  const useASAR = $rJ && isBuilt && !$r;
  const nodeModulePath = `${nodeModuleName}/${pathInsideNodeModule}`;
  const actualNodeModulesPath = useASAR ? $fh : $eh;
  const resourcePath = `${actualNodeModulesPath}/${nodeModulePath}`;
  return $ih.asBrowserUri(resourcePath).toString(true);
}

// out-build/vs/workbench/services/textfile/common/encoding.js
var $uJ = "utf8";
var $vJ = "utf8bom";
var $wJ = "utf16be";
var $xJ = "utf16le";
var $zJ = [254, 255];
var $AJ = [255, 254];
var $BJ = [239, 187, 191];
var ZERO_BYTE_DETECTION_BUFFER_MAX_LEN = 512;
var NO_ENCODING_GUESS_MIN_BYTES = 512;
var AUTO_ENCODING_GUESS_MIN_BYTES = 512 * 8;
var AUTO_ENCODING_GUESS_MAX_BYTES = 512 * 128;
var DecodeStreamErrorKind;
(function(DecodeStreamErrorKind2) {
  DecodeStreamErrorKind2[DecodeStreamErrorKind2["STREAM_IS_BINARY"] = 1] = "STREAM_IS_BINARY";
})(DecodeStreamErrorKind || (DecodeStreamErrorKind = {}));
var $CJ = class extends Error {
  constructor(message, decodeStreamErrorKind) {
    super(message);
    this.decodeStreamErrorKind = decodeStreamErrorKind;
  }
};
var DecoderStream = class _DecoderStream {
  /**
   * This stream will only load iconv-lite lazily if the encoding
   * is not UTF-8. This ensures that for most common cases we do
   * not pay the price of loading the module from disk.
   *
   * We still need to be careful when converting UTF-8 to a string
   * though because we read the file in chunks of Buffer and thus
   * need to decode it via TextDecoder helper that is available
   * in browser and node.js environments.
   */
  static async create(encoding) {
    let decoder2 = void 0;
    if (encoding !== $uJ) {
      const iconv = await $sJ("@vscode/iconv-lite-umd", "lib/iconv-lite-umd.js");
      decoder2 = iconv.getDecoder($GJ(encoding));
    } else {
      const utf8TextDecoder = new TextDecoder();
      decoder2 = {
        write(buffer) {
          return utf8TextDecoder.decode(buffer, {
            // Signal to TextDecoder that potentially more data is coming
            // and that we are calling `decode` in the end to consume any
            // remainders
            stream: true
          });
        },
        end() {
          return utf8TextDecoder.decode();
        }
      };
    }
    return new _DecoderStream(decoder2);
  }
  constructor(a) {
    this.a = a;
  }
  write(buffer) {
    return this.a.write(buffer);
  }
  end() {
    return this.a.end();
  }
};
function $DJ(source, options3) {
  const minBytesRequiredForDetection = options3.minBytesRequiredForDetection ?? options3.guessEncoding ? AUTO_ENCODING_GUESS_MIN_BYTES : NO_ENCODING_GUESS_MIN_BYTES;
  return new Promise((resolve, reject) => {
    const target = $qi((strings) => strings.join(""));
    const bufferedChunks = [];
    let bytesBuffered = 0;
    let decoder2 = void 0;
    const cts = new $ad();
    const createDecoder = async () => {
      try {
        const detected = await $JJ({
          buffer: $Ci.concat(bufferedChunks),
          bytesRead: bytesBuffered
        }, options3.guessEncoding, options3.candidateGuessEncodings);
        if (detected.seemsBinary && options3.acceptTextOnly) {
          throw new $CJ(
            "Stream is binary but only text is accepted for decoding",
            1
            /* DecodeStreamErrorKind.STREAM_IS_BINARY */
          );
        }
        detected.encoding = await options3.overwriteEncoding(detected.encoding);
        decoder2 = await DecoderStream.create(detected.encoding);
        const decoded = decoder2.write($Ci.concat(bufferedChunks).buffer);
        target.write(decoded);
        bufferedChunks.length = 0;
        bytesBuffered = 0;
        resolve({
          stream: target,
          detected
        });
      } catch (error) {
        cts.cancel();
        target.destroy();
        reject(error);
      }
    };
    $ui(source, {
      onData: async (chunk) => {
        if (decoder2) {
          target.write(decoder2.write(chunk.buffer));
        } else {
          bufferedChunks.push(chunk);
          bytesBuffered += chunk.byteLength;
          if (bytesBuffered >= minBytesRequiredForDetection) {
            source.pause();
            await createDecoder();
            setTimeout(() => source.resume());
          }
        }
      },
      onError: (error) => target.error(error),
      // simply forward to target
      onEnd: async () => {
        if (!decoder2) {
          await createDecoder();
        }
        target.end(decoder2?.end());
      }
    }, cts.token);
  });
}
async function $EJ(readable, encoding, options3) {
  const iconv = await $sJ("@vscode/iconv-lite-umd", "lib/iconv-lite-umd.js");
  const encoder = iconv.getEncoder($GJ(encoding), options3);
  let bytesWritten = false;
  let done = false;
  return {
    read() {
      if (done) {
        return null;
      }
      const chunk = readable.read();
      if (typeof chunk !== "string") {
        done = true;
        if (!bytesWritten && options3?.addBOM) {
          switch (encoding) {
            case $uJ:
            case $vJ:
              return $Ci.wrap(Uint8Array.from($BJ));
            case $wJ:
              return $Ci.wrap(Uint8Array.from($zJ));
            case $xJ:
              return $Ci.wrap(Uint8Array.from($AJ));
          }
        }
        const leftovers = encoder.end();
        if (leftovers && leftovers.length > 0) {
          bytesWritten = true;
          return $Ci.wrap(leftovers);
        }
        return null;
      }
      bytesWritten = true;
      return $Ci.wrap(encoder.write(chunk));
    }
  };
}
async function $FJ(encoding) {
  const iconv = await $sJ("@vscode/iconv-lite-umd", "lib/iconv-lite-umd.js");
  return iconv.encodingExists($GJ(encoding));
}
function $GJ(enc) {
  if (enc === $vJ || enc === null) {
    return $uJ;
  }
  return enc;
}
function $HJ(buffer, bytesRead) {
  if (!buffer || bytesRead < $zJ.length) {
    return null;
  }
  const b0 = buffer.readUInt8(0);
  const b1 = buffer.readUInt8(1);
  if (b0 === $zJ[0] && b1 === $zJ[1]) {
    return $wJ;
  }
  if (b0 === $AJ[0] && b1 === $AJ[1]) {
    return $xJ;
  }
  if (bytesRead < $BJ.length) {
    return null;
  }
  const b2 = buffer.readUInt8(2);
  if (b0 === $BJ[0] && b1 === $BJ[1] && b2 === $BJ[2]) {
    return $vJ;
  }
  return null;
}
var IGNORE_ENCODINGS = ["ascii", "utf-16", "utf-32"];
async function guessEncodingByBuffer(buffer, candidateGuessEncodings) {
  const jschardet = await $sJ("jschardet", "dist/jschardet.min.js");
  const limitedBuffer = buffer.slice(0, AUTO_ENCODING_GUESS_MAX_BYTES);
  const binaryString = encodeLatin1(limitedBuffer.buffer);
  if (candidateGuessEncodings) {
    candidateGuessEncodings = $Mb(candidateGuessEncodings.map((e) => toJschardetEncoding(e)));
    if (candidateGuessEncodings.length === 0) {
      candidateGuessEncodings = void 0;
    }
  }
  const guessed = jschardet.detect(binaryString, candidateGuessEncodings ? { detectEncodings: candidateGuessEncodings } : void 0);
  if (!guessed || !guessed.encoding) {
    return null;
  }
  const enc = guessed.encoding.toLowerCase();
  if (0 <= IGNORE_ENCODINGS.indexOf(enc)) {
    return null;
  }
  return toIconvLiteEncoding(guessed.encoding);
}
var JSCHARDET_TO_ICONV_ENCODINGS = {
  "ibm866": "cp866",
  "big5": "cp950"
};
function normalizeEncoding(encodingName) {
  return encodingName.replace(/[^a-zA-Z0-9]/g, "").toLowerCase();
}
function toIconvLiteEncoding(encodingName) {
  const normalizedEncodingName = normalizeEncoding(encodingName);
  const mapped = JSCHARDET_TO_ICONV_ENCODINGS[normalizedEncodingName];
  return mapped || normalizedEncodingName;
}
function toJschardetEncoding(encodingName) {
  const normalizedEncodingName = normalizeEncoding(encodingName);
  const mapped = $LJ[normalizedEncodingName];
  return mapped.guessableName;
}
function encodeLatin1(buffer) {
  let result = "";
  for (let i2 = 0; i2 < buffer.length; i2++) {
    result += String.fromCharCode(buffer[i2]);
  }
  return result;
}
function $JJ({ buffer, bytesRead }, autoGuessEncoding, candidateGuessEncodings) {
  let encoding = $HJ(buffer, bytesRead);
  let seemsBinary = false;
  if (encoding !== $wJ && encoding !== $xJ && buffer) {
    let couldBeUTF16LE = true;
    let couldBeUTF16BE = true;
    let containsZeroByte = false;
    for (let i2 = 0; i2 < bytesRead && i2 < ZERO_BYTE_DETECTION_BUFFER_MAX_LEN; i2++) {
      const isEndian = i2 % 2 === 1;
      const isZeroByte = buffer.readUInt8(i2) === 0;
      if (isZeroByte) {
        containsZeroByte = true;
      }
      if (couldBeUTF16LE && (isEndian && !isZeroByte || !isEndian && isZeroByte)) {
        couldBeUTF16LE = false;
      }
      if (couldBeUTF16BE && (isEndian && isZeroByte || !isEndian && !isZeroByte)) {
        couldBeUTF16BE = false;
      }
      if (isZeroByte && !couldBeUTF16LE && !couldBeUTF16BE) {
        break;
      }
    }
    if (containsZeroByte) {
      if (couldBeUTF16LE) {
        encoding = $xJ;
      } else if (couldBeUTF16BE) {
        encoding = $wJ;
      } else {
        seemsBinary = true;
      }
    }
  }
  if (autoGuessEncoding && !seemsBinary && !encoding && buffer) {
    return guessEncodingByBuffer(buffer.slice(0, bytesRead), candidateGuessEncodings).then((guessedEncoding) => {
      return {
        seemsBinary: false,
        encoding: guessedEncoding
      };
    });
  }
  return { seemsBinary, encoding };
}
var $KJ = {
  utf8: {
    labelLong: "UTF-8",
    labelShort: "UTF-8",
    order: 1,
    alias: "utf8bom",
    guessableName: "UTF-8"
  },
  utf8bom: {
    labelLong: "UTF-8 with BOM",
    labelShort: "UTF-8 with BOM",
    encodeOnly: true,
    order: 2,
    alias: "utf8"
  },
  utf16le: {
    labelLong: "UTF-16 LE",
    labelShort: "UTF-16 LE",
    order: 3,
    guessableName: "UTF-16LE"
  },
  utf16be: {
    labelLong: "UTF-16 BE",
    labelShort: "UTF-16 BE",
    order: 4,
    guessableName: "UTF-16BE"
  },
  windows1252: {
    labelLong: "Western (Windows 1252)",
    labelShort: "Windows 1252",
    order: 5,
    guessableName: "windows-1252"
  },
  iso88591: {
    labelLong: "Western (ISO 8859-1)",
    labelShort: "ISO 8859-1",
    order: 6
  },
  iso88593: {
    labelLong: "Western (ISO 8859-3)",
    labelShort: "ISO 8859-3",
    order: 7
  },
  iso885915: {
    labelLong: "Western (ISO 8859-15)",
    labelShort: "ISO 8859-15",
    order: 8
  },
  macroman: {
    labelLong: "Western (Mac Roman)",
    labelShort: "Mac Roman",
    order: 9
  },
  cp437: {
    labelLong: "DOS (CP 437)",
    labelShort: "CP437",
    order: 10
  },
  windows1256: {
    labelLong: "Arabic (Windows 1256)",
    labelShort: "Windows 1256",
    order: 11
  },
  iso88596: {
    labelLong: "Arabic (ISO 8859-6)",
    labelShort: "ISO 8859-6",
    order: 12
  },
  windows1257: {
    labelLong: "Baltic (Windows 1257)",
    labelShort: "Windows 1257",
    order: 13
  },
  iso88594: {
    labelLong: "Baltic (ISO 8859-4)",
    labelShort: "ISO 8859-4",
    order: 14
  },
  iso885914: {
    labelLong: "Celtic (ISO 8859-14)",
    labelShort: "ISO 8859-14",
    order: 15
  },
  windows1250: {
    labelLong: "Central European (Windows 1250)",
    labelShort: "Windows 1250",
    order: 16,
    guessableName: "windows-1250"
  },
  iso88592: {
    labelLong: "Central European (ISO 8859-2)",
    labelShort: "ISO 8859-2",
    order: 17,
    guessableName: "ISO-8859-2"
  },
  cp852: {
    labelLong: "Central European (CP 852)",
    labelShort: "CP 852",
    order: 18
  },
  windows1251: {
    labelLong: "Cyrillic (Windows 1251)",
    labelShort: "Windows 1251",
    order: 19,
    guessableName: "windows-1251"
  },
  cp866: {
    labelLong: "Cyrillic (CP 866)",
    labelShort: "CP 866",
    order: 20,
    guessableName: "IBM866"
  },
  iso88595: {
    labelLong: "Cyrillic (ISO 8859-5)",
    labelShort: "ISO 8859-5",
    order: 21,
    guessableName: "ISO-8859-5"
  },
  koi8r: {
    labelLong: "Cyrillic (KOI8-R)",
    labelShort: "KOI8-R",
    order: 22,
    guessableName: "KOI8-R"
  },
  koi8u: {
    labelLong: "Cyrillic (KOI8-U)",
    labelShort: "KOI8-U",
    order: 23
  },
  iso885913: {
    labelLong: "Estonian (ISO 8859-13)",
    labelShort: "ISO 8859-13",
    order: 24
  },
  windows1253: {
    labelLong: "Greek (Windows 1253)",
    labelShort: "Windows 1253",
    order: 25,
    guessableName: "windows-1253"
  },
  iso88597: {
    labelLong: "Greek (ISO 8859-7)",
    labelShort: "ISO 8859-7",
    order: 26,
    guessableName: "ISO-8859-7"
  },
  windows1255: {
    labelLong: "Hebrew (Windows 1255)",
    labelShort: "Windows 1255",
    order: 27,
    guessableName: "windows-1255"
  },
  iso88598: {
    labelLong: "Hebrew (ISO 8859-8)",
    labelShort: "ISO 8859-8",
    order: 28,
    guessableName: "ISO-8859-8"
  },
  iso885910: {
    labelLong: "Nordic (ISO 8859-10)",
    labelShort: "ISO 8859-10",
    order: 29
  },
  iso885916: {
    labelLong: "Romanian (ISO 8859-16)",
    labelShort: "ISO 8859-16",
    order: 30
  },
  windows1254: {
    labelLong: "Turkish (Windows 1254)",
    labelShort: "Windows 1254",
    order: 31
  },
  iso88599: {
    labelLong: "Turkish (ISO 8859-9)",
    labelShort: "ISO 8859-9",
    order: 32
  },
  windows1258: {
    labelLong: "Vietnamese (Windows 1258)",
    labelShort: "Windows 1258",
    order: 33
  },
  gbk: {
    labelLong: "Simplified Chinese (GBK)",
    labelShort: "GBK",
    order: 34
  },
  gb18030: {
    labelLong: "Simplified Chinese (GB18030)",
    labelShort: "GB18030",
    order: 35
  },
  cp950: {
    labelLong: "Traditional Chinese (Big5)",
    labelShort: "Big5",
    order: 36,
    guessableName: "Big5"
  },
  big5hkscs: {
    labelLong: "Traditional Chinese (Big5-HKSCS)",
    labelShort: "Big5-HKSCS",
    order: 37
  },
  shiftjis: {
    labelLong: "Japanese (Shift JIS)",
    labelShort: "Shift JIS",
    order: 38,
    guessableName: "SHIFT_JIS"
  },
  eucjp: {
    labelLong: "Japanese (EUC-JP)",
    labelShort: "EUC-JP",
    order: 39,
    guessableName: "EUC-JP"
  },
  euckr: {
    labelLong: "Korean (EUC-KR)",
    labelShort: "EUC-KR",
    order: 40,
    guessableName: "EUC-KR"
  },
  windows874: {
    labelLong: "Thai (Windows 874)",
    labelShort: "Windows 874",
    order: 41
  },
  iso885911: {
    labelLong: "Latin/Thai (ISO 8859-11)",
    labelShort: "ISO 8859-11",
    order: 42
  },
  koi8ru: {
    labelLong: "Cyrillic (KOI8-RU)",
    labelShort: "KOI8-RU",
    order: 43
  },
  koi8t: {
    labelLong: "Tajik (KOI8-T)",
    labelShort: "KOI8-T",
    order: 44
  },
  gb2312: {
    labelLong: "Simplified Chinese (GB 2312)",
    labelShort: "GB 2312",
    order: 45,
    guessableName: "GB2312"
  },
  cp865: {
    labelLong: "Nordic DOS (CP 865)",
    labelShort: "CP 865",
    order: 46
  },
  cp850: {
    labelLong: "Western European DOS (CP 850)",
    labelShort: "CP 850",
    order: 47
  }
};
var $LJ = (() => {
  const guessableEncodings = {};
  for (const encoding in $KJ) {
    if ($KJ[encoding].guessableName) {
      guessableEncodings[encoding] = $KJ[encoding];
    }
  }
  return guessableEncodings;
})();

// out-build/vs/workbench/services/untitled/common/untitledTextEditorModel.js
var $MJ_1;
var $MJ = class $MJ2 extends $xG {
  static {
    $MJ_1 = this;
  }
  static {
    this.c = 40;
  }
  static {
    this.L = this.c * 10;
  }
  static {
    this.M = "${activeEditorLanguage}";
  }
  get name() {
    if (this.U === "content" && !this.hasAssociatedFilePath && this.W) {
      return this.W;
    }
    return this.db.getUriBasenameLabel(this.resource);
  }
  //#endregion
  constructor(resource, hasAssociatedFilePath, X, Y, Z, languageService, modelService, $149, ab, bb, cb, db, eb, languageDetectionService, accessibilityService) {
    super(modelService, languageService, languageDetectionService, accessibilityService);
    this.resource = resource;
    this.hasAssociatedFilePath = hasAssociatedFilePath;
    this.X = X;
    this.Y = Y;
    this.Z = Z;
    this.$ = $149;
    this.ab = ab;
    this.bb = bb;
    this.cb = cb;
    this.db = db;
    this.eb = eb;
    this.N = this.B(new $ze());
    this.onDidChangeContent = this.N.event;
    this.O = this.B(new $ze());
    this.onDidChangeName = this.O.event;
    this.P = this.B(new $ze());
    this.onDidChangeDirty = this.P.event;
    this.Q = this.B(new $ze());
    this.onDidChangeEncoding = this.Q.event;
    this.R = this.B(new $ze());
    this.onDidSave = this.R.event;
    this.S = this.B(new $ze());
    this.onDidRevert = this.S.event;
    this.typeId = $qG;
    this.capabilities = 2;
    this.U = "content";
    this.W = void 0;
    this.ib = this.hasAssociatedFilePath || !!this.X;
    this.kb = false;
    this.B(this.bb.registerWorkingCopy(this));
    if (Y) {
      this.setLanguageId(Y);
    }
    this.gb(void 0, false);
    this.fb();
  }
  fb() {
    this.B(this.ab.onDidChangeConfiguration((e) => this.gb(e, true)));
  }
  gb(e, fromEvent) {
    if (!e || e.affectsConfiguration(this.resource, "files.encoding")) {
      const configuredEncoding = this.ab.getValue(this.resource, "files.encoding");
      if (this.hb !== configuredEncoding && typeof configuredEncoding === "string") {
        this.hb = configuredEncoding;
        if (fromEvent && !this.Z) {
          this.Q.fire();
        }
      }
    }
    if (!e || e.affectsConfiguration(this.resource, "workbench.editor.untitled.labelFormat")) {
      const configuredLabelFormat = this.ab.getValue(this.resource, "workbench.editor.untitled.labelFormat");
      if (this.U !== configuredLabelFormat && (configuredLabelFormat === "content" || configuredLabelFormat === "name")) {
        this.U = configuredLabelFormat;
        if (fromEvent) {
          this.O.fire();
        }
      }
    }
  }
  //#region Language
  setLanguageId(languageId, source) {
    const actualLanguage = languageId === $MJ_1.M ? this.eb.activeTextEditorLanguageId : languageId;
    this.Y = actualLanguage;
    if (actualLanguage) {
      super.setLanguageId(actualLanguage, source);
    }
  }
  getLanguageId() {
    if (this.textEditorModel) {
      return this.textEditorModel.getLanguageId();
    }
    return this.Y;
  }
  getEncoding() {
    return this.Z || this.hb;
  }
  async setEncoding(encoding) {
    const oldEncoding = this.getEncoding();
    this.Z = encoding;
    if (oldEncoding !== this.Z) {
      this.Q.fire();
    }
  }
  isDirty() {
    return this.ib;
  }
  isModified() {
    return this.isDirty();
  }
  jb(dirty) {
    if (this.ib === dirty) {
      return;
    }
    this.ib = dirty;
    this.P.fire();
  }
  //#endregion
  //#region Save / Revert / Backup
  async save(options3) {
    const target = await this.cb.save(this.resource, options3);
    if (target) {
      this.R.fire({ reason: options3?.reason, source: options3?.source });
    }
    return !!target;
  }
  async revert() {
    this.kb = true;
    try {
      this.updateTextEditorModel($MI(""));
    } finally {
      this.kb = false;
    }
    this.jb(false);
    this.S.fire();
  }
  async backup(token) {
    let content = void 0;
    if (this.isResolved()) {
      content = await this.cb.getEncodedReadable(this.resource, this.createSnapshot() ?? void 0, { encoding: $uJ });
    } else if (typeof this.X === "string") {
      content = $Ni($Ci.fromString(this.X));
    }
    return { content };
  }
  async resolve() {
    let createdUntitledModel = false;
    let hasBackup = false;
    if (!this.textEditorModel) {
      let untitledContents;
      const backup = await this.$.resolve(this);
      if (backup) {
        untitledContents = backup.value;
        hasBackup = true;
      } else {
        untitledContents = $Qi($Ci.fromString(this.X || ""));
      }
      const untitledContentsFactory = await $NI(await this.cb.getDecodedStream(this.resource, untitledContents, { encoding: $uJ }));
      this.G(untitledContentsFactory, this.resource, this.Y);
      createdUntitledModel = true;
    } else {
      this.updateTextEditorModel(void 0, this.Y);
    }
    const textEditorModel = $Kg(this.textEditorModel);
    this.C(textEditorModel);
    if (createdUntitledModel) {
      if (hasBackup || this.X) {
        this.nb(textEditorModel);
      }
      this.jb(this.hasAssociatedFilePath || !!hasBackup || !!this.X);
      if (hasBackup || this.X) {
        this.N.fire();
      }
    }
    return super.resolve();
  }
  C(model) {
    this.B(model.onDidChangeContent((e) => this.mb(model, e)));
    this.B(model.onDidChangeLanguage(() => this.gb(void 0, true)));
    super.C(model);
  }
  mb(textEditorModel, e) {
    if (!this.kb) {
      if (!this.hasAssociatedFilePath && textEditorModel.getLineCount() === 1 && textEditorModel.getLineLength(1) === 0) {
        this.jb(false);
      } else {
        this.jb(true);
      }
    }
    if (e.changes.some((change) => (change.range.startLineNumber === 1 || change.range.endLineNumber === 1) && change.range.startColumn <= $MJ_1.L)) {
      this.nb(textEditorModel);
    }
    this.N.fire();
    this.D();
  }
  nb(textEditorModel) {
    if (this.hasAssociatedFilePath) {
      return;
    }
    let modelFirstWordsCandidate = void 0;
    let firstLineText = textEditorModel.getValueInRange({
      startLineNumber: 1,
      endLineNumber: 1,
      startColumn: 1,
      endColumn: $MJ_1.L + 1
      // first cap at FIRST_LINE_NAME_CANDIDATE_MAX_LENGTH
    }).trim().replace(/\s+/g, " ").replace(/\u202E/g, "");
    firstLineText = firstLineText.substr(0, $ag(
      // finally cap at FIRST_LINE_NAME_MAX_LENGTH (grapheme aware #111235)
      firstLineText,
      $MJ_1.c
    )[0]);
    if (firstLineText && $KD().exec(firstLineText)) {
      modelFirstWordsCandidate = firstLineText;
    }
    if (modelFirstWordsCandidate !== this.W) {
      this.W = modelFirstWordsCandidate;
      this.O.fire();
    }
  }
  //#endregion
  isReadonly() {
    return false;
  }
};
$MJ = $MJ_1 = __decorate([
  __param(5, $1E),
  __param(6, $sG),
  __param(7, $yG),
  __param(8, $zG),
  __param(9, $XI),
  __param(10, $cK),
  __param(11, $ZI),
  __param(12, $mJ),
  __param(13, $tG),
  __param(14, $ND)
], $MJ);

// out-build/vs/workbench/services/untitled/common/untitledTextEditorService.js
var $OJ_1;
var $NJ = $Qk("untitledTextEditorService");
var $OJ = class $OJ2 extends $3c {
  static {
    $OJ_1 = this;
  }
  static {
    this.a = /Untitled-\d+/;
  }
  constructor(m, n) {
    super();
    this.m = m;
    this.n = n;
    this.b = this.B(new $ze());
    this.onDidChangeDirty = this.b.event;
    this.c = this.B(new $ze());
    this.onDidChangeEncoding = this.c.event;
    this.f = this.B(new $ze());
    this.onDidCreate = this.f.event;
    this.g = this.B(new $ze());
    this.onWillDispose = this.g.event;
    this.h = this.B(new $ze());
    this.onDidChangeLabel = this.h.event;
    this.j = new $Ec();
  }
  get(resource) {
    return this.j.get(resource);
  }
  getValue(resource) {
    return this.get(resource)?.textEditorModel?.getValue();
  }
  async resolve(options3) {
    const model = this.r(options3);
    await model.resolve();
    return model;
  }
  create(options3) {
    return this.r(options3);
  }
  r(options3 = /* @__PURE__ */ Object.create(null)) {
    const massagedOptions = this.s(options3);
    if (massagedOptions.untitledResource && this.j.has(massagedOptions.untitledResource)) {
      return this.j.get(massagedOptions.untitledResource);
    }
    return this.t(massagedOptions);
  }
  s(options3) {
    const massagedOptions = /* @__PURE__ */ Object.create(null);
    if (options3.associatedResource) {
      massagedOptions.untitledResource = URI.from({
        scheme: Schemas.untitled,
        authority: options3.associatedResource.authority,
        fragment: options3.associatedResource.fragment,
        path: options3.associatedResource.path,
        query: options3.associatedResource.query
      });
      massagedOptions.associatedResource = options3.associatedResource;
    } else {
      if (options3.untitledResource?.scheme === Schemas.untitled) {
        massagedOptions.untitledResource = options3.untitledResource;
      }
    }
    if (options3.languageId) {
      massagedOptions.languageId = options3.languageId;
    } else if (!massagedOptions.associatedResource) {
      const configuration2 = this.n.getValue();
      if (configuration2.files?.defaultLanguage) {
        massagedOptions.languageId = configuration2.files.defaultLanguage;
      }
    }
    massagedOptions.encoding = options3.encoding;
    massagedOptions.initialValue = options3.initialValue;
    return massagedOptions;
  }
  t(options3) {
    let untitledResource = options3.untitledResource;
    if (!untitledResource) {
      let counter = 1;
      do {
        untitledResource = URI.from({ scheme: Schemas.untitled, path: `Untitled-${counter}` });
        counter++;
      } while (this.j.has(untitledResource));
    }
    const model = this.B(this.m.createInstance($MJ, untitledResource, !!options3.associatedResource, options3.initialValue, options3.languageId, options3.encoding));
    this.u(model);
    return model;
  }
  u(model) {
    const modelListeners = new $2c();
    modelListeners.add(model.onDidChangeDirty(() => this.b.fire(model)));
    modelListeners.add(model.onDidChangeName(() => this.h.fire(model)));
    modelListeners.add(model.onDidChangeEncoding(() => this.c.fire(model)));
    modelListeners.add(model.onWillDispose(() => this.g.fire(model)));
    Event2.once(model.onWillDispose)(() => {
      this.j.delete(model.resource);
      modelListeners.dispose();
    });
    this.j.set(model.resource, model);
    this.f.fire(model);
    if (model.isDirty()) {
      this.b.fire(model);
    }
  }
  isUntitledWithAssociatedResource(resource) {
    return resource.scheme === Schemas.untitled && resource.path.length > 1 && !$OJ_1.a.test(resource.path);
  }
  canDispose(model) {
    if (model.isDisposed()) {
      return true;
    }
    return this.w(model);
  }
  async w(model) {
    if (model.isDirty()) {
      await Event2.toPromise(model.onDidChangeDirty);
      return this.canDispose(model);
    }
    return true;
  }
};
$OJ = $OJ_1 = __decorate([
  __param(0, $Pk),
  __param(1, $kl)
], $OJ);
$SC(
  $NJ,
  $OJ,
  1
  /* InstantiationType.Delayed */
);

// out-build/vs/workbench/browser/parts/editor/diffEditorCommands.js
var $iub = "toggle.diff.renderSideBySide";
var $jub = "workbench.action.compareEditor.nextChange";
var $kub = "workbench.action.compareEditor.previousChange";
var $lub = "workbench.action.compareEditor.focusPrimarySide";
var $mub = "workbench.action.compareEditor.focusSecondarySide";
var $nub = "workbench.action.compareEditor.focusOtherSide";
var $oub = "workbench.action.compareEditor.openSide";
var $pub = "toggle.diff.ignoreTrimWhitespace";
var $qub = "workbench.action.compareEditor.swapSides";
function $rub() {
  $0I.registerCommandAndKeybindingRule({
    id: $jub,
    weight: 200,
    when: $Fpb,
    primary: 512 | 63,
    handler: (accessor, ...args2) => navigateInDiffEditor(accessor, args2, true)
  });
  $dJ.appendMenuItem($bJ.CommandPalette, {
    command: {
      id: $jub,
      title: localize2(3165, "Go to Next Change")
    }
  });
  $0I.registerCommandAndKeybindingRule({
    id: $kub,
    weight: 200,
    when: $Fpb,
    primary: 512 | 1024 | 63,
    handler: (accessor, ...args2) => navigateInDiffEditor(accessor, args2, false)
  });
  $dJ.appendMenuItem($bJ.CommandPalette, {
    command: {
      id: $kub,
      title: localize2(3166, "Go to Previous Change")
    }
  });
  function getActiveTextDiffEditor(accessor, args2) {
    const editorService = accessor.get($mJ);
    const resource = args2.length > 0 && args2[0] instanceof URI ? args2[0] : void 0;
    for (const editor of [editorService.activeEditorPane, ...editorService.visibleEditorPanes]) {
      if (editor instanceof $hub && (!resource || editor.input instanceof $fub && $oh(editor.input.primary.resource, resource))) {
        return editor;
      }
    }
    return void 0;
  }
  function navigateInDiffEditor(accessor, args2, next) {
    const activeTextDiffEditor = getActiveTextDiffEditor(accessor, args2);
    if (activeTextDiffEditor) {
      activeTextDiffEditor.getControl()?.goToDiff(next ? "next" : "previous");
    }
  }
  let FocusTextDiffEditorMode;
  (function(FocusTextDiffEditorMode2) {
    FocusTextDiffEditorMode2[FocusTextDiffEditorMode2["Original"] = 0] = "Original";
    FocusTextDiffEditorMode2[FocusTextDiffEditorMode2["Modified"] = 1] = "Modified";
    FocusTextDiffEditorMode2[FocusTextDiffEditorMode2["Toggle"] = 2] = "Toggle";
  })(FocusTextDiffEditorMode || (FocusTextDiffEditorMode = {}));
  function focusInDiffEditor(accessor, args2, mode) {
    const activeTextDiffEditor = getActiveTextDiffEditor(accessor, args2);
    if (activeTextDiffEditor) {
      switch (mode) {
        case FocusTextDiffEditorMode.Original:
          activeTextDiffEditor.getControl()?.getOriginalEditor().focus();
          break;
        case FocusTextDiffEditorMode.Modified:
          activeTextDiffEditor.getControl()?.getModifiedEditor().focus();
          break;
        case FocusTextDiffEditorMode.Toggle:
          if (activeTextDiffEditor.getControl()?.getModifiedEditor().hasWidgetFocus()) {
            return focusInDiffEditor(accessor, args2, FocusTextDiffEditorMode.Original);
          } else {
            return focusInDiffEditor(accessor, args2, FocusTextDiffEditorMode.Modified);
          }
      }
    }
  }
  function toggleDiffSideBySide(accessor, args2) {
    const configService = accessor.get($zG);
    const activeTextDiffEditor = getActiveTextDiffEditor(accessor, args2);
    const m = activeTextDiffEditor?.getControl()?.getModifiedEditor()?.getModel();
    if (!m) {
      return;
    }
    const key2 = "diffEditor.renderSideBySide";
    const val = configService.getValue(m.uri, key2);
    configService.updateValue(m.uri, key2, !val);
  }
  function toggleDiffIgnoreTrimWhitespace(accessor, args2) {
    const configService = accessor.get($zG);
    const activeTextDiffEditor = getActiveTextDiffEditor(accessor, args2);
    const m = activeTextDiffEditor?.getControl()?.getModifiedEditor()?.getModel();
    if (!m) {
      return;
    }
    const key2 = "diffEditor.ignoreTrimWhitespace";
    const val = configService.getValue(m.uri, key2);
    configService.updateValue(m.uri, key2, !val);
  }
  async function swapDiffSides(accessor, args2) {
    const editorService = accessor.get($mJ);
    const diffEditor = getActiveTextDiffEditor(accessor, args2);
    const activeGroup = diffEditor?.group;
    const diffInput = diffEditor?.input;
    if (!diffEditor || typeof activeGroup === "undefined" || !(diffInput instanceof $fub) || !diffInput.modified.resource) {
      return;
    }
    const untypedDiffInput = diffInput.toUntyped({ preserveViewState: activeGroup.id, preserveResource: true });
    if (!untypedDiffInput) {
      return;
    }
    if (diffInput.modified.isModified() && editorService.findEditors({ resource: diffInput.modified.resource, typeId: diffInput.modified.typeId, editorId: diffInput.modified.editorId }).length === 0) {
      await editorService.openEditor({
        ...untypedDiffInput.modified,
        options: {
          ...untypedDiffInput.modified.options,
          pinned: true,
          inactive: true
        }
      }, activeGroup);
    }
    await editorService.replaceEditors([
      {
        editor: diffInput,
        replacement: {
          ...untypedDiffInput,
          original: untypedDiffInput.modified,
          modified: untypedDiffInput.original,
          options: {
            ...untypedDiffInput.options,
            pinned: true
          }
        }
      }
    ], activeGroup);
  }
  $0I.registerCommandAndKeybindingRule({
    id: $iub,
    weight: 200,
    when: void 0,
    primary: void 0,
    handler: (accessor, ...args2) => toggleDiffSideBySide(accessor, args2)
  });
  $0I.registerCommandAndKeybindingRule({
    id: $lub,
    weight: 200,
    when: void 0,
    primary: void 0,
    handler: (accessor, ...args2) => focusInDiffEditor(accessor, args2, FocusTextDiffEditorMode.Modified)
  });
  $0I.registerCommandAndKeybindingRule({
    id: $mub,
    weight: 200,
    when: void 0,
    primary: void 0,
    handler: (accessor, ...args2) => focusInDiffEditor(accessor, args2, FocusTextDiffEditorMode.Original)
  });
  $0I.registerCommandAndKeybindingRule({
    id: $nub,
    weight: 200,
    when: void 0,
    primary: void 0,
    handler: (accessor, ...args2) => focusInDiffEditor(accessor, args2, FocusTextDiffEditorMode.Toggle)
  });
  $0I.registerCommandAndKeybindingRule({
    id: $pub,
    weight: 200,
    when: void 0,
    primary: void 0,
    handler: (accessor, ...args2) => toggleDiffIgnoreTrimWhitespace(accessor, args2)
  });
  $0I.registerCommandAndKeybindingRule({
    id: $qub,
    weight: 200,
    when: void 0,
    primary: void 0,
    handler: (accessor, ...args2) => swapDiffSides(accessor, args2)
  });
  $dJ.appendMenuItem($bJ.CommandPalette, {
    command: {
      id: $iub,
      title: localize2(3167, "Toggle Inline View"),
      category: localize(3163, null)
    },
    when: $Gpb
  });
  $dJ.appendMenuItem($bJ.CommandPalette, {
    command: {
      id: $qub,
      title: localize2(3168, "Swap Left and Right Editor Side"),
      category: localize(3164, null)
    },
    when: $7m.and($Gpb, $zpb)
  });
}

// out-build/vs/workbench/browser/parts/editor/editorCommandsContext.js
function $sub(commandArgs, editorService, editorGroupsService, listService) {
  const commandContext = getCommandsContext(commandArgs, editorService, editorGroupsService, listService);
  const preserveFocus = commandContext.length ? commandContext[0].preserveFocus || false : false;
  const resolvedContext = { groupedEditors: [], preserveFocus };
  for (const editorContext of commandContext) {
    const groupAndEditor = getEditorAndGroupFromContext(editorContext, editorGroupsService);
    if (!groupAndEditor) {
      continue;
    }
    const { group: group2, editor } = groupAndEditor;
    let groupContext = void 0;
    for (const targetGroupContext of resolvedContext.groupedEditors) {
      if (targetGroupContext.group.id === group2.id) {
        groupContext = targetGroupContext;
        break;
      }
    }
    if (!groupContext) {
      groupContext = { group: group2, editors: [] };
      resolvedContext.groupedEditors.push(groupContext);
    }
    if (editor) {
      groupContext.editors.push(editor);
    }
  }
  return resolvedContext;
}
function getCommandsContext(commandArgs, editorService, editorGroupsService, listService) {
  const list2 = listService.lastFocusedList;
  let isListAction = list2 instanceof $A1 && list2.getHTMLElement() === $Lj();
  let editorContext = getEditorContextFromCommandArgs(commandArgs, isListAction, editorService, editorGroupsService, listService);
  if (!editorContext) {
    const activeGroup = editorGroupsService.activeGroup;
    const activeEditor = activeGroup.activeEditor;
    editorContext = { groupId: activeGroup.id, editorIndex: activeEditor ? activeGroup.getIndexOfEditor(activeEditor) : void 0 };
    isListAction = false;
  }
  const multiEditorContext = getMultiSelectContext(editorContext, isListAction, editorService, editorGroupsService, listService);
  return moveCurrentEditorContextToFront(editorContext, multiEditorContext);
}
function moveCurrentEditorContextToFront(editorContext, multiEditorContext) {
  if (multiEditorContext.length <= 1) {
    return multiEditorContext;
  }
  const editorContextIndex = multiEditorContext.findIndex((context) => context.groupId === editorContext.groupId && context.editorIndex === editorContext.editorIndex);
  if (editorContextIndex !== -1) {
    multiEditorContext.splice(editorContextIndex, 1);
    multiEditorContext.unshift(editorContext);
  } else if (editorContext.editorIndex === void 0) {
    multiEditorContext.unshift(editorContext);
  } else {
    throw new Error("Editor context not found in multi editor context");
  }
  return multiEditorContext;
}
function getEditorContextFromCommandArgs(commandArgs, isListAction, editorService, editorGroupsService, listService) {
  const filteredArgs = commandArgs.filter((arg) => $kL(arg) || URI.isUri(arg));
  for (const arg of filteredArgs) {
    if ($kL(arg)) {
      return arg;
    }
  }
  for (const uri of filteredArgs) {
    const editorIdentifiers = editorService.findEditors(uri);
    if (editorIdentifiers.length) {
      const editorIdentifier = editorIdentifiers[0];
      const group2 = editorGroupsService.getGroup(editorIdentifier.groupId);
      return { groupId: editorIdentifier.groupId, editorIndex: group2?.getIndexOfEditor(editorIdentifier.editor) };
    }
  }
  if (isListAction) {
    const list2 = listService.lastFocusedList;
    for (const focusedElement of list2.getFocusedElements()) {
      if (isGroupOrEditor(focusedElement)) {
        return groupOrEditorToEditorContext(focusedElement, void 0, editorGroupsService);
      }
    }
  }
  return void 0;
}
function getMultiSelectContext(editorContext, isListAction, editorService, editorGroupsService, listService) {
  if (isListAction) {
    const list2 = listService.lastFocusedList;
    const selection = list2.getSelectedElements().filter(isGroupOrEditor);
    if (selection.length > 1) {
      return selection.map((e) => groupOrEditorToEditorContext(e, editorContext.preserveFocus, editorGroupsService));
    }
    if (selection.length === 0) {
      return getMultiSelectContext(editorContext, false, editorService, editorGroupsService, listService);
    }
  } else {
    const group2 = editorGroupsService.getGroup(editorContext.groupId);
    const editor = editorContext.editorIndex !== void 0 ? group2?.getEditorByIndex(editorContext.editorIndex) : group2?.activeEditor;
    if (group2 && editor && group2.isSelected(editor)) {
      return group2.selectedEditors.map((editor2) => groupOrEditorToEditorContext({ editor: editor2, groupId: group2.id }, editorContext.preserveFocus, editorGroupsService));
    }
  }
  return [editorContext];
}
function groupOrEditorToEditorContext(element, preserveFocus, editorGroupsService) {
  if ($kJ(element)) {
    return { groupId: element.id, editorIndex: void 0, preserveFocus };
  }
  const group2 = editorGroupsService.getGroup(element.groupId);
  return { groupId: element.groupId, editorIndex: group2 ? group2.getIndexOfEditor(element.editor) : -1, preserveFocus };
}
function isGroupOrEditor(element) {
  return $kJ(element) || $jL(element);
}
function getEditorAndGroupFromContext(commandContext, editorGroupsService) {
  const group2 = editorGroupsService.getGroup(commandContext.groupId);
  if (!group2) {
    return void 0;
  }
  if (commandContext.editorIndex === void 0) {
    return { group: group2, editor: void 0 };
  }
  const editor = group2.getEditorByIndex(commandContext.editorIndex);
  return { group: group2, editor };
}

// out-build/vs/workbench/browser/parts/editor/editorCommands.js
var $tub = "workbench.action.closeUnmodifiedEditors";
var $uub = "workbench.action.closeEditorsInGroup";
var $vub = "workbench.action.closeEditorsAndGroup";
var $wub = "workbench.action.closeEditorsToTheRight";
var $xub = "workbench.action.closeActiveEditor";
var $yub = "workbench.action.closeActivePinnedEditor";
var $zub = "workbench.action.closeGroup";
var $Aub = "workbench.action.closeOtherEditors";
var $Bub = "moveActiveEditor";
var $Cub = "copyActiveEditor";
var $Dub = "layoutEditorGroups";
var $Eub = "workbench.action.keepEditor";
var $Fub = "workbench.action.toggleKeepEditors";
var $Gub = "workbench.action.toggleEditorGroupLock";
var $Hub = "workbench.action.lockEditorGroup";
var $Iub = "workbench.action.unlockEditorGroup";
var $Jub = "workbench.action.showEditorsInGroup";
var $Kub = "workbench.action.reopenWithEditor";
var $Lub = "workbench.action.pinEditor";
var $Mub = "workbench.action.unpinEditor";
var $Nub = "workbench.action.splitEditor";
var $Oub = "workbench.action.splitEditorUp";
var $Pub = "workbench.action.splitEditorDown";
var $Qub = "workbench.action.splitEditorLeft";
var $Rub = "workbench.action.splitEditorRight";
var $Sub = "workbench.action.toggleMaximizeEditorGroup";
var $Tub = "workbench.action.splitEditorInGroup";
var $Uub = "workbench.action.toggleSplitEditorInGroup";
var $Vub = "workbench.action.joinEditorInGroup";
var $Wub = "workbench.action.toggleSplitEditorInGroupLayout";
var $Xub = "workbench.action.focusFirstSideEditor";
var $Yub = "workbench.action.focusSecondSideEditor";
var $Zub = "workbench.action.focusOtherSideEditor";
var $1ub = "workbench.action.focusLeftGroupWithoutWrap";
var $2ub = "workbench.action.focusRightGroupWithoutWrap";
var $3ub = "workbench.action.focusAboveGroupWithoutWrap";
var $4ub = "workbench.action.focusBelowGroupWithoutWrap";
var $5ub = "workbench.action.openEditorAtIndex";
var $6ub = "workbench.action.moveEditorToNewWindow";
var $7ub = "workbench.action.copyEditorToNewWindow";
var $8ub = "workbench.action.moveEditorGroupToNewWindow";
var $9ub = "workbench.action.copyEditorGroupToNewWindow";
var $0ub = "workbench.action.newEmptyEditorWindow";
var $$ub = "_workbench.open";
var $_ub = "_workbench.diff";
var $avb = "_workbench.openWith";
var $bvb = [
  $Nub,
  $xub,
  $Mub,
  $Iub,
  $Sub
];
var isActiveEditorMoveCopyArg = function(arg) {
  if (!$Bg(arg)) {
    return false;
  }
  if (!$zg(arg.to)) {
    return false;
  }
  if (!$Gg(arg.by) && !$zg(arg.by)) {
    return false;
  }
  if (!$Gg(arg.value) && !$Dg(arg.value)) {
    return false;
  }
  return true;
};
function registerActiveEditorMoveCopyCommand() {
  const moveCopyJSONSchema = {
    "type": "object",
    "required": ["to"],
    "properties": {
      "to": {
        "type": "string",
        "enum": ["left", "right"]
      },
      "by": {
        "type": "string",
        "enum": ["tab", "group"]
      },
      "value": {
        "type": "number"
      }
    }
  };
  $0I.registerCommandAndKeybindingRule({
    id: $Bub,
    weight: 200,
    when: EditorContextKeys.editorTextFocus,
    primary: 0,
    handler: (accessor, args2) => moveCopyActiveEditor(true, args2, accessor),
    metadata: {
      description: localize(3462, null),
      args: [
        {
          name: localize(3463, null),
          description: localize(3464, null),
          constraint: isActiveEditorMoveCopyArg,
          schema: moveCopyJSONSchema
        }
      ]
    }
  });
  $0I.registerCommandAndKeybindingRule({
    id: $Cub,
    weight: 200,
    when: EditorContextKeys.editorTextFocus,
    primary: 0,
    handler: (accessor, args2) => moveCopyActiveEditor(false, args2, accessor),
    metadata: {
      description: localize(3465, null),
      args: [
        {
          name: localize(3466, null),
          description: localize(3467, null),
          constraint: isActiveEditorMoveCopyArg,
          schema: moveCopyJSONSchema
        }
      ]
    }
  });
  function moveCopyActiveEditor(isMove, args2 = /* @__PURE__ */ Object.create(null), accessor) {
    args2.to = args2.to || "right";
    args2.by = args2.by || "tab";
    args2.value = typeof args2.value === "number" ? args2.value : 1;
    const activeEditorPane = accessor.get($mJ).activeEditorPane;
    if (activeEditorPane) {
      switch (args2.by) {
        case "tab":
          if (isMove) {
            return moveActiveTab(args2, activeEditorPane);
          }
          break;
        case "group":
          return moveCopyActiveEditorToGroup(isMove, args2, activeEditorPane, accessor);
      }
    }
  }
  function moveActiveTab(args2, control) {
    const group2 = control.group;
    let index = group2.getIndexOfEditor(control.input);
    switch (args2.to) {
      case "first":
        index = 0;
        break;
      case "last":
        index = group2.count - 1;
        break;
      case "left":
        index = index - (args2.value ?? 1);
        break;
      case "right":
        index = index + (args2.value ?? 1);
        break;
      case "center":
        index = Math.round(group2.count / 2) - 1;
        break;
      case "position":
        index = (args2.value ?? 1) - 1;
        break;
    }
    index = index < 0 ? 0 : index >= group2.count ? group2.count - 1 : index;
    group2.moveEditor(control.input, group2, { index });
  }
  function moveCopyActiveEditorToGroup(isMove, args2, control, accessor) {
    const editorGroupsService = accessor.get($iJ);
    const configurationService = accessor.get($kl);
    const sourceGroup = control.group;
    let targetGroup;
    switch (args2.to) {
      case "left":
        targetGroup = editorGroupsService.findGroup({
          direction: 2
          /* GroupDirection.LEFT */
        }, sourceGroup);
        if (!targetGroup) {
          targetGroup = editorGroupsService.addGroup(
            sourceGroup,
            2
            /* GroupDirection.LEFT */
          );
        }
        break;
      case "right":
        targetGroup = editorGroupsService.findGroup({
          direction: 3
          /* GroupDirection.RIGHT */
        }, sourceGroup);
        if (!targetGroup) {
          targetGroup = editorGroupsService.addGroup(
            sourceGroup,
            3
            /* GroupDirection.RIGHT */
          );
        }
        break;
      case "up":
        targetGroup = editorGroupsService.findGroup({
          direction: 0
          /* GroupDirection.UP */
        }, sourceGroup);
        if (!targetGroup) {
          targetGroup = editorGroupsService.addGroup(
            sourceGroup,
            0
            /* GroupDirection.UP */
          );
        }
        break;
      case "down":
        targetGroup = editorGroupsService.findGroup({
          direction: 1
          /* GroupDirection.DOWN */
        }, sourceGroup);
        if (!targetGroup) {
          targetGroup = editorGroupsService.addGroup(
            sourceGroup,
            1
            /* GroupDirection.DOWN */
          );
        }
        break;
      case "first":
        targetGroup = editorGroupsService.findGroup({
          location: 0
          /* GroupLocation.FIRST */
        }, sourceGroup);
        break;
      case "last":
        targetGroup = editorGroupsService.findGroup({
          location: 1
          /* GroupLocation.LAST */
        }, sourceGroup);
        break;
      case "previous":
        targetGroup = editorGroupsService.findGroup({
          location: 3
          /* GroupLocation.PREVIOUS */
        }, sourceGroup);
        break;
      case "next":
        targetGroup = editorGroupsService.findGroup({
          location: 2
          /* GroupLocation.NEXT */
        }, sourceGroup);
        if (!targetGroup) {
          targetGroup = editorGroupsService.addGroup(sourceGroup, $lJ(configurationService));
        }
        break;
      case "center":
        targetGroup = editorGroupsService.getGroups(
          2
          /* GroupsOrder.GRID_APPEARANCE */
        )[editorGroupsService.count / 2 - 1];
        break;
      case "position":
        targetGroup = editorGroupsService.getGroups(
          2
          /* GroupsOrder.GRID_APPEARANCE */
        )[(args2.value ?? 1) - 1];
        break;
    }
    if (targetGroup) {
      if (isMove) {
        sourceGroup.moveEditor(control.input, targetGroup);
      } else if (sourceGroup.id !== targetGroup.id) {
        sourceGroup.copyEditor(control.input, targetGroup);
      }
      targetGroup.focus();
    }
  }
}
function registerEditorGroupsLayoutCommands() {
  function applyEditorLayout(accessor, layout) {
    if (!layout || typeof layout !== "object") {
      return;
    }
    const editorGroupsService = accessor.get($iJ);
    editorGroupsService.applyLayout(layout);
  }
  $tn.registerCommand($Dub, (accessor, args2) => {
    applyEditorLayout(accessor, args2);
  });
  $tn.registerCommand({
    id: "vscode.setEditorLayout",
    handler: (accessor, args2) => applyEditorLayout(accessor, args2),
    metadata: {
      "description": `Set the editor layout. Editor layout is represented as a tree of groups in which the first group is the root group of the layout.
					The orientation of the first group is 0 (horizontal) by default unless specified otherwise. The other orientations are 1 (vertical).
					The orientation of subsequent groups is the opposite of the orientation of the group that contains it.
					Here are some examples: A layout representing 1 row and 2 columns: { orientation: 0, groups: [{}, {}] }.
					A layout representing 3 rows and 1 column: { orientation: 1, groups: [{}, {}, {}] }.
					A layout representing 3 rows and 1 column in which the second row has 2 columns: { orientation: 1, groups: [{}, { groups: [{}, {}] }, {}] }
					`,
      args: [{
        name: "args",
        schema: {
          "type": "object",
          "required": ["groups"],
          "properties": {
            "orientation": {
              "type": "number",
              "default": 0,
              "description": `The orientation of the root group in the layout. 0 for horizontal, 1 for vertical.`,
              "enum": [0, 1],
              "enumDescriptions": [
                localize(3468, null),
                localize(3469, null)
              ]
            },
            "groups": {
              "$ref": "#/definitions/editorGroupsSchema",
              "default": [{}, {}]
            }
          }
        }
      }]
    }
  });
  $tn.registerCommand({
    id: "vscode.getEditorLayout",
    handler: (accessor) => {
      const editorGroupsService = accessor.get($iJ);
      return editorGroupsService.getLayout();
    },
    metadata: {
      description: "Get Editor Layout",
      args: [],
      returns: "An editor layout object, in the same format as vscode.setEditorLayout"
    }
  });
}
function registerOpenEditorAPICommands() {
  function mixinContext(context, options3, column) {
    if (!context) {
      return [options3, column];
    }
    return [
      { ...context.editorOptions, ...options3 ?? /* @__PURE__ */ Object.create(null) },
      context.sideBySide ? $oJ : column
    ];
  }
  $tn.registerCommand({
    id: "vscode.open",
    handler: (accessor, arg) => {
      accessor.get($sn).executeCommand($$ub, arg);
    },
    metadata: {
      description: "Opens the provided resource in the editor.",
      args: [{ name: "Uri" }]
    }
  });
  $tn.registerCommand($$ub, async function(accessor, resourceArg, columnAndOptions, label3, context) {
    const editorService = accessor.get($mJ);
    const editorGroupsService = accessor.get($iJ);
    const openerService = accessor.get($O4);
    const pathService = accessor.get($aT);
    const configurationService = accessor.get($kl);
    const untitledTextEditorService = accessor.get($NJ);
    const resourceOrString = typeof resourceArg === "string" ? resourceArg : URI.from(resourceArg, true);
    const [columnArg, optionsArg] = columnAndOptions ?? [];
    if (optionsArg || typeof columnArg === "number" || $0g(resourceOrString, Schemas.untitled)) {
      const [options3, column] = mixinContext(context, optionsArg, columnArg);
      const resource = URI.isUri(resourceOrString) ? resourceOrString : URI.parse(resourceOrString);
      let input;
      if (untitledTextEditorService.isUntitledWithAssociatedResource(resource)) {
        input = { resource: resource.with({ scheme: pathService.defaultUriScheme }), forceUntitled: true, options: options3, label: label3 };
      } else {
        input = { resource, options: options3, label: label3 };
      }
      await editorService.openEditor(input, $zS(editorGroupsService, configurationService, column));
    } else if ($0g(resourceOrString, Schemas.command)) {
      return;
    } else {
      await openerService.open(resourceOrString, { openToSide: context?.sideBySide, editorOptions: context?.editorOptions });
    }
  });
  $tn.registerCommand({
    id: "vscode.diff",
    handler: (accessor, left, right, label3) => {
      accessor.get($sn).executeCommand($_ub, left, right, label3);
    },
    metadata: {
      description: "Opens the provided resources in the diff editor to compare their contents.",
      args: [
        { name: "left", description: "Left-hand side resource of the diff editor" },
        { name: "right", description: "Right-hand side resource of the diff editor" },
        { name: "title", description: "Human readable title for the diff editor" }
      ]
    }
  });
  $tn.registerCommand($_ub, async function(accessor, originalResource, modifiedResource, labelAndOrDescription, columnAndOptions, context) {
    const editorService = accessor.get($mJ);
    const editorGroupsService = accessor.get($iJ);
    const configurationService = accessor.get($kl);
    const [columnArg, optionsArg] = columnAndOptions ?? [];
    const [options3, column] = mixinContext(context, optionsArg, columnArg);
    let label3 = void 0;
    let description = void 0;
    if (typeof labelAndOrDescription === "string") {
      label3 = labelAndOrDescription;
    } else if (labelAndOrDescription) {
      label3 = labelAndOrDescription.label;
      description = labelAndOrDescription.description;
    }
    await editorService.openEditor({
      original: { resource: URI.from(originalResource, true) },
      modified: { resource: URI.from(modifiedResource, true) },
      label: label3,
      description,
      options: options3
    }, $zS(editorGroupsService, configurationService, column));
  });
  $tn.registerCommand($avb, async (accessor, resource, id2, columnAndOptions) => {
    const editorService = accessor.get($mJ);
    const editorGroupsService = accessor.get($iJ);
    const configurationService = accessor.get($kl);
    const [columnArg, optionsArg] = columnAndOptions ?? [];
    await editorService.openEditor({ resource: URI.from(resource, true), options: { ...optionsArg, pinned: true, override: id2 } }, $zS(editorGroupsService, configurationService, columnArg));
  });
  $tn.registerCommand({
    id: "vscode.changes",
    handler: (accessor, title, resources) => {
      accessor.get($sn).executeCommand("_workbench.changes", title, resources);
    },
    metadata: {
      description: "Opens a list of resources in the changes editor to compare their contents.",
      args: [
        { name: "title", description: "Human readable title for the diff editor" },
        { name: "resources", description: "List of resources to open in the changes editor" }
      ]
    }
  });
  $tn.registerCommand("_workbench.changes", async (accessor, title, resources) => {
    const editorService = accessor.get($mJ);
    const editor = [];
    for (const [label3, original, modified] of resources) {
      editor.push({
        resource: URI.revive(label3),
        original: { resource: URI.revive(original) },
        modified: { resource: URI.revive(modified) }
      });
    }
    await editorService.openEditor({ resources: editor, label: title });
  });
  $tn.registerCommand("_workbench.openMultiDiffEditor", async (accessor, options3) => {
    const editorService = accessor.get($mJ);
    await editorService.openEditor({
      multiDiffSource: options3.multiDiffSourceUri ? URI.revive(options3.multiDiffSourceUri) : void 0,
      resources: options3.resources?.map((r2) => ({ original: { resource: URI.revive(r2.originalUri) }, modified: { resource: URI.revive(r2.modifiedUri) } })),
      label: options3.title
    });
  });
}
function registerOpenEditorAtIndexCommands() {
  const openEditorAtIndex = (accessor, editorIndex) => {
    const editorService = accessor.get($mJ);
    const activeEditorPane = editorService.activeEditorPane;
    if (activeEditorPane) {
      const editor = activeEditorPane.group.getEditorByIndex(editorIndex);
      if (editor) {
        editorService.openEditor(editor);
      }
    }
  };
  $tn.registerCommand({
    id: $5ub,
    handler: openEditorAtIndex
  });
  for (let i2 = 0; i2 < 9; i2++) {
    const editorIndex = i2;
    const visibleIndex = i2 + 1;
    $0I.registerCommandAndKeybindingRule({
      id: $5ub + visibleIndex,
      weight: 200,
      when: void 0,
      primary: 512 | toKeyCode(visibleIndex),
      mac: { primary: 256 | toKeyCode(visibleIndex) },
      handler: (accessor) => openEditorAtIndex(accessor, editorIndex)
    });
  }
  function toKeyCode(index) {
    switch (index) {
      case 0:
        return 21;
      case 1:
        return 22;
      case 2:
        return 23;
      case 3:
        return 24;
      case 4:
        return 25;
      case 5:
        return 26;
      case 6:
        return 27;
      case 7:
        return 28;
      case 8:
        return 29;
      case 9:
        return 30;
    }
    throw new Error("invalid index");
  }
}
function registerFocusEditorGroupAtIndexCommands() {
  for (let groupIndex = 1; groupIndex < 8; groupIndex++) {
    $0I.registerCommandAndKeybindingRule({
      id: toCommandId(groupIndex),
      weight: 200,
      when: void 0,
      primary: 2048 | toKeyCode(groupIndex),
      handler: (accessor) => {
        const editorGroupsService = accessor.get($iJ);
        const configurationService = accessor.get($kl);
        if (groupIndex > editorGroupsService.count) {
          return;
        }
        const groups = editorGroupsService.getGroups(
          2
          /* GroupsOrder.GRID_APPEARANCE */
        );
        if (groups[groupIndex]) {
          return groups[groupIndex].focus();
        }
        const direction = $lJ(configurationService);
        const lastGroup = editorGroupsService.findGroup({
          location: 1
          /* GroupLocation.LAST */
        });
        if (!lastGroup) {
          return;
        }
        const newGroup = editorGroupsService.addGroup(lastGroup, direction);
        newGroup.focus();
      }
    });
  }
  function toCommandId(index) {
    switch (index) {
      case 1:
        return "workbench.action.focusSecondEditorGroup";
      case 2:
        return "workbench.action.focusThirdEditorGroup";
      case 3:
        return "workbench.action.focusFourthEditorGroup";
      case 4:
        return "workbench.action.focusFifthEditorGroup";
      case 5:
        return "workbench.action.focusSixthEditorGroup";
      case 6:
        return "workbench.action.focusSeventhEditorGroup";
      case 7:
        return "workbench.action.focusEighthEditorGroup";
    }
    throw new Error("Invalid index");
  }
  function toKeyCode(index) {
    switch (index) {
      case 1:
        return 23;
      case 2:
        return 24;
      case 3:
        return 25;
      case 4:
        return 26;
      case 5:
        return 27;
      case 6:
        return 28;
      case 7:
        return 29;
    }
    throw new Error("Invalid index");
  }
}
function $cvb(editorGroupsService, direction, resolvedContext) {
  if (!resolvedContext.groupedEditors.length) {
    return;
  }
  const { group: group2, editors } = resolvedContext.groupedEditors[0];
  const preserveFocus = resolvedContext.preserveFocus;
  const newGroup = editorGroupsService.addGroup(group2, direction);
  for (const editorToCopy of editors) {
    if (editorToCopy && !editorToCopy.hasCapability(
      8
      /* EditorInputCapabilities.Singleton */
    )) {
      group2.copyEditor(editorToCopy, newGroup, { preserveFocus });
    }
  }
  newGroup.focus();
}
function registerSplitEditorCommands() {
  [
    {
      id: $Oub,
      direction: 0
      /* GroupDirection.UP */
    },
    {
      id: $Pub,
      direction: 1
      /* GroupDirection.DOWN */
    },
    {
      id: $Qub,
      direction: 2
      /* GroupDirection.LEFT */
    },
    {
      id: $Rub,
      direction: 3
      /* GroupDirection.RIGHT */
    }
  ].forEach(({ id: id2, direction }) => {
    $tn.registerCommand(id2, function(accessor, ...args2) {
      const resolvedContext = $sub(args2, accessor.get($mJ), accessor.get($iJ), accessor.get($Deb));
      $cvb(accessor.get($iJ), direction, resolvedContext);
    });
  });
}
function registerCloseEditorCommands() {
  function closeEditorHandler(accessor, forceCloseStickyEditors, ...args2) {
    const editorGroupsService = accessor.get($iJ);
    const editorService = accessor.get($mJ);
    let keepStickyEditors = void 0;
    if (forceCloseStickyEditors) {
      keepStickyEditors = false;
    } else if (args2.length) {
      keepStickyEditors = false;
    } else {
      keepStickyEditors = editorGroupsService.partOptions.preventPinnedEditorClose === "keyboard" || editorGroupsService.partOptions.preventPinnedEditorClose === "keyboardAndMouse";
    }
    if (keepStickyEditors) {
      const activeGroup = editorGroupsService.activeGroup;
      const activeEditor = activeGroup.activeEditor;
      if (activeEditor && activeGroup.isSticky(activeEditor)) {
        const nextNonStickyEditorInGroup = activeGroup.getEditors(0, { excludeSticky: true })[0];
        if (nextNonStickyEditorInGroup) {
          return activeGroup.openEditor(nextNonStickyEditorInGroup);
        }
        const nextNonStickyEditorInAllGroups = editorService.getEditors(0, { excludeSticky: true })[0];
        if (nextNonStickyEditorInAllGroups) {
          return Promise.resolve(editorGroupsService.getGroup(nextNonStickyEditorInAllGroups.groupId)?.openEditor(nextNonStickyEditorInAllGroups.editor));
        }
      }
    }
    const resolvedContext = $sub(args2, accessor.get($mJ), accessor.get($iJ), accessor.get($Deb));
    const preserveFocus = resolvedContext.preserveFocus;
    return Promise.all(resolvedContext.groupedEditors.map(async ({ group: group2, editors }) => {
      const editorsToClose = editors.filter((editor) => !keepStickyEditors || !group2.isSticky(editor));
      await group2.closeEditors(editorsToClose, { preserveFocus });
    }));
  }
  $0I.registerCommandAndKeybindingRule({
    id: $xub,
    weight: 200,
    when: void 0,
    primary: 2048 | 53,
    win: { primary: 2048 | 62, secondary: [
      2048 | 53
      /* KeyCode.KeyW */
    ] },
    handler: (accessor, ...args2) => {
      return closeEditorHandler(accessor, false, ...args2);
    }
  });
  $tn.registerCommand($yub, (accessor, ...args2) => {
    return closeEditorHandler(accessor, true, ...args2);
  });
  $0I.registerCommandAndKeybindingRule({
    id: $uub,
    weight: 200,
    when: void 0,
    primary: $$e(
      2048 | 41,
      53
      /* KeyCode.KeyW */
    ),
    handler: (accessor, ...args2) => {
      const resolvedContext = $sub(args2, accessor.get($mJ), accessor.get($iJ), accessor.get($Deb));
      return Promise.all(resolvedContext.groupedEditors.map(async ({ group: group2 }) => {
        await group2.closeAllEditors({ excludeSticky: true });
      }));
    }
  });
  $0I.registerCommandAndKeybindingRule({
    id: $zub,
    weight: 200,
    when: $7m.and($Jpb, $Npb),
    primary: 2048 | 53,
    win: { primary: 2048 | 62, secondary: [
      2048 | 53
      /* KeyCode.KeyW */
    ] },
    handler: (accessor, ...args2) => {
      const editorGroupsService = accessor.get($iJ);
      const commandsContext = $sub(args2, accessor.get($mJ), editorGroupsService, accessor.get($Deb));
      if (commandsContext.groupedEditors.length) {
        editorGroupsService.removeGroup(commandsContext.groupedEditors[0].group);
      }
    }
  });
  $0I.registerCommandAndKeybindingRule({
    id: $tub,
    weight: 200,
    when: void 0,
    primary: $$e(
      2048 | 41,
      51
      /* KeyCode.KeyU */
    ),
    handler: (accessor, ...args2) => {
      const resolvedContext = $sub(args2, accessor.get($mJ), accessor.get($iJ), accessor.get($Deb));
      return Promise.all(resolvedContext.groupedEditors.map(async ({ group: group2 }) => {
        await group2.closeEditors({ savedOnly: true, excludeSticky: true }, { preserveFocus: resolvedContext.preserveFocus });
      }));
    }
  });
  $0I.registerCommandAndKeybindingRule({
    id: $Aub,
    weight: 200,
    when: void 0,
    primary: void 0,
    mac: {
      primary: 2048 | 512 | 50
      /* KeyCode.KeyT */
    },
    handler: (accessor, ...args2) => {
      const resolvedContext = $sub(args2, accessor.get($mJ), accessor.get($iJ), accessor.get($Deb));
      return Promise.all(resolvedContext.groupedEditors.map(async ({ group: group2, editors }) => {
        const editorsToClose = group2.getEditors(1, { excludeSticky: true }).filter((editor) => !editors.includes(editor));
        for (const editorToKeep of editors) {
          if (editorToKeep) {
            group2.pinEditor(editorToKeep);
          }
        }
        await group2.closeEditors(editorsToClose, { preserveFocus: resolvedContext.preserveFocus });
      }));
    }
  });
  $0I.registerCommandAndKeybindingRule({
    id: $wub,
    weight: 200,
    when: void 0,
    primary: void 0,
    handler: async (accessor, ...args2) => {
      const resolvedContext = $sub(args2, accessor.get($mJ), accessor.get($iJ), accessor.get($Deb));
      if (resolvedContext.groupedEditors.length) {
        const { group: group2, editors } = resolvedContext.groupedEditors[0];
        if (group2.activeEditor) {
          group2.pinEditor(group2.activeEditor);
        }
        await group2.closeEditors({ direction: 1, except: editors[0], excludeSticky: true }, { preserveFocus: resolvedContext.preserveFocus });
      }
    }
  });
  $0I.registerCommandAndKeybindingRule({
    id: $Kub,
    weight: 200,
    when: void 0,
    primary: void 0,
    handler: async (accessor, ...args2) => {
      const editorService = accessor.get($mJ);
      const editorResolverService = accessor.get($4L);
      const telemetryService = accessor.get($zv);
      const resolvedContext = $sub(args2, editorService, accessor.get($iJ), accessor.get($Deb));
      const editorReplacements = /* @__PURE__ */ new Map();
      for (const { group: group2, editors } of resolvedContext.groupedEditors) {
        for (const editor of editors) {
          const untypedEditor = editor.toUntyped();
          if (!untypedEditor) {
            return;
          }
          untypedEditor.options = { ...editorService.activeEditorPane?.options, override: EditorResolution.PICK };
          const resolvedEditor = await editorResolverService.resolveEditor(untypedEditor, group2);
          if (!$iL(resolvedEditor)) {
            return;
          }
          let editorReplacementsInGroup = editorReplacements.get(group2);
          if (!editorReplacementsInGroup) {
            editorReplacementsInGroup = [];
            editorReplacements.set(group2, editorReplacementsInGroup);
          }
          editorReplacementsInGroup.push({
            editor,
            replacement: resolvedEditor.editor,
            forceReplaceDirty: editor.resource?.scheme === Schemas.untitled,
            options: resolvedEditor.options
          });
          telemetryService.publicLog2("workbenchEditorReopen", {
            scheme: editor.resource?.scheme ?? "",
            ext: editor.resource ? $th(editor.resource) : "",
            from: editor.editorId ?? "",
            to: resolvedEditor.editor.editorId ?? ""
          });
        }
      }
      for (const [group2, replacements] of editorReplacements) {
        await group2.replaceEditors(replacements);
        await group2.openEditor(replacements[0].replacement);
      }
    }
  });
  $tn.registerCommand($vub, async (accessor, ...args2) => {
    const editorGroupsService = accessor.get($iJ);
    const resolvedContext = $sub(args2, accessor.get($mJ), editorGroupsService, accessor.get($Deb));
    if (resolvedContext.groupedEditors.length) {
      const { group: group2 } = resolvedContext.groupedEditors[0];
      await group2.closeAllEditors();
      if (group2.count === 0 && editorGroupsService.getGroup(group2.id)) {
        editorGroupsService.removeGroup(group2);
      }
    }
  });
}
function registerFocusEditorGroupWihoutWrapCommands() {
  const commands2 = [
    {
      id: $1ub,
      direction: 2
      /* GroupDirection.LEFT */
    },
    {
      id: $2ub,
      direction: 3
      /* GroupDirection.RIGHT */
    },
    {
      id: $3ub,
      direction: 0
    },
    {
      id: $4ub,
      direction: 1
      /* GroupDirection.DOWN */
    }
  ];
  for (const command4 of commands2) {
    $tn.registerCommand(command4.id, async (accessor) => {
      const editorGroupsService = accessor.get($iJ);
      const group2 = editorGroupsService.findGroup({ direction: command4.direction }, editorGroupsService.activeGroup, false);
      group2?.focus();
    });
  }
}
function registerSplitEditorInGroupCommands() {
  async function splitEditorInGroup(accessor, resolvedContext) {
    const instantiationService = accessor.get($Pk);
    if (!resolvedContext.groupedEditors.length) {
      return;
    }
    const { group: group2, editors } = resolvedContext.groupedEditors[0];
    const editor = editors[0];
    if (!editor) {
      return;
    }
    await group2.replaceEditors([{
      editor,
      replacement: instantiationService.createInstance($1I, void 0, void 0, editor, editor),
      forceReplaceDirty: true
    }]);
  }
  $hJ(class extends $gJ {
    constructor() {
      super({
        id: $Tub,
        title: localize2(3470, "Split Editor in Group"),
        category: $qn.View,
        precondition: $Cpb,
        f1: true,
        keybinding: {
          weight: 200,
          when: $Cpb,
          primary: $$e(
            2048 | 41,
            2048 | 1024 | 93
            /* KeyCode.Backslash */
          )
        }
      });
    }
    run(accessor, ...args2) {
      return splitEditorInGroup(accessor, $sub(args2, accessor.get($mJ), accessor.get($iJ), accessor.get($Deb)));
    }
  });
  async function joinEditorInGroup(resolvedContext) {
    if (!resolvedContext.groupedEditors.length) {
      return;
    }
    const { group: group2, editors } = resolvedContext.groupedEditors[0];
    const editor = editors[0];
    if (!editor) {
      return;
    }
    if (!(editor instanceof $1I)) {
      return;
    }
    let options3 = void 0;
    const activeEditorPane = group2.activeEditorPane;
    if (activeEditorPane instanceof $_tb && group2.activeEditor === editor) {
      for (const pane of [activeEditorPane.getPrimaryEditorPane(), activeEditorPane.getSecondaryEditorPane()]) {
        if (pane?.hasFocus()) {
          options3 = { viewState: pane.getViewState() };
          break;
        }
      }
    }
    await group2.replaceEditors([{
      editor,
      replacement: editor.primary,
      options: options3
    }]);
  }
  $hJ(class extends $gJ {
    constructor() {
      super({
        id: $Vub,
        title: localize2(3471, "Join Editor in Group"),
        category: $qn.View,
        precondition: $Hpb,
        f1: true,
        keybinding: {
          weight: 200,
          when: $Hpb,
          primary: $$e(
            2048 | 41,
            2048 | 1024 | 93
            /* KeyCode.Backslash */
          )
        }
      });
    }
    run(accessor, ...args2) {
      return joinEditorInGroup($sub(args2, accessor.get($mJ), accessor.get($iJ), accessor.get($Deb)));
    }
  });
  $hJ(class extends $gJ {
    constructor() {
      super({
        id: $Uub,
        title: localize2(3472, "Toggle Split Editor in Group"),
        category: $qn.View,
        precondition: $7m.or($Cpb, $Hpb),
        f1: true
      });
    }
    async run(accessor, ...args2) {
      const resolvedContext = $sub(args2, accessor.get($mJ), accessor.get($iJ), accessor.get($Deb));
      if (!resolvedContext.groupedEditors.length) {
        return;
      }
      const { editors } = resolvedContext.groupedEditors[0];
      if (editors[0] instanceof $1I) {
        await joinEditorInGroup(resolvedContext);
      } else if (editors[0]) {
        await splitEditorInGroup(accessor, resolvedContext);
      }
    }
  });
  $hJ(class extends $gJ {
    constructor() {
      super({
        id: $Wub,
        title: localize2(3473, "Toggle Layout of Split Editor in Group"),
        category: $qn.View,
        precondition: $Hpb,
        f1: true
      });
    }
    async run(accessor) {
      const configurationService = accessor.get($kl);
      const currentSetting = configurationService.getValue($_tb.SIDE_BY_SIDE_LAYOUT_SETTING);
      let newSetting;
      if (currentSetting !== "horizontal") {
        newSetting = "horizontal";
      } else {
        newSetting = "vertical";
      }
      return configurationService.updateValue($_tb.SIDE_BY_SIDE_LAYOUT_SETTING, newSetting);
    }
  });
}
function registerFocusSideEditorsCommands() {
  $hJ(class extends $gJ {
    constructor() {
      super({
        id: $Xub,
        title: localize2(3474, "Focus First Side in Active Editor"),
        category: $qn.View,
        precondition: $7m.or($Hpb, $Gpb),
        f1: true
      });
    }
    async run(accessor) {
      const editorService = accessor.get($mJ);
      const commandService = accessor.get($sn);
      const activeEditorPane = editorService.activeEditorPane;
      if (activeEditorPane instanceof $_tb) {
        activeEditorPane.getSecondaryEditorPane()?.focus();
      } else if (activeEditorPane instanceof $hub) {
        await commandService.executeCommand($mub);
      }
    }
  });
  $hJ(class extends $gJ {
    constructor() {
      super({
        id: $Yub,
        title: localize2(3475, "Focus Second Side in Active Editor"),
        category: $qn.View,
        precondition: $7m.or($Hpb, $Gpb),
        f1: true
      });
    }
    async run(accessor) {
      const editorService = accessor.get($mJ);
      const commandService = accessor.get($sn);
      const activeEditorPane = editorService.activeEditorPane;
      if (activeEditorPane instanceof $_tb) {
        activeEditorPane.getPrimaryEditorPane()?.focus();
      } else if (activeEditorPane instanceof $hub) {
        await commandService.executeCommand($lub);
      }
    }
  });
  $hJ(class extends $gJ {
    constructor() {
      super({
        id: $Zub,
        title: localize2(3476, "Focus Other Side in Active Editor"),
        category: $qn.View,
        precondition: $7m.or($Hpb, $Gpb),
        f1: true
      });
    }
    async run(accessor) {
      const editorService = accessor.get($mJ);
      const commandService = accessor.get($sn);
      const activeEditorPane = editorService.activeEditorPane;
      if (activeEditorPane instanceof $_tb) {
        if (activeEditorPane.getPrimaryEditorPane()?.hasFocus()) {
          activeEditorPane.getSecondaryEditorPane()?.focus();
        } else {
          activeEditorPane.getPrimaryEditorPane()?.focus();
        }
      } else if (activeEditorPane instanceof $hub) {
        await commandService.executeCommand($nub);
      }
    }
  });
}
function registerOtherEditorCommands() {
  $0I.registerCommandAndKeybindingRule({
    id: $Eub,
    weight: 200,
    when: void 0,
    primary: $$e(
      2048 | 41,
      3
      /* KeyCode.Enter */
    ),
    handler: async (accessor, ...args2) => {
      const resolvedContext = $sub(args2, accessor.get($mJ), accessor.get($iJ), accessor.get($Deb));
      for (const { group: group2, editors } of resolvedContext.groupedEditors) {
        for (const editor of editors) {
          group2.pinEditor(editor);
        }
      }
    }
  });
  $tn.registerCommand({
    id: $Fub,
    handler: (accessor) => {
      const configurationService = accessor.get($kl);
      const currentSetting = configurationService.getValue("workbench.editor.enablePreview");
      const newSetting = currentSetting === true ? false : true;
      configurationService.updateValue("workbench.editor.enablePreview", newSetting);
    }
  });
  function setEditorGroupLock(accessor, locked, ...args2) {
    const resolvedContext = $sub(args2, accessor.get($mJ), accessor.get($iJ), accessor.get($Deb));
    const group2 = resolvedContext.groupedEditors[0]?.group;
    group2?.lock(locked ?? !group2.isLocked);
  }
  $hJ(class extends $gJ {
    constructor() {
      super({
        id: $Gub,
        title: localize2(3477, "Toggle Editor Group Lock"),
        category: $qn.View,
        f1: true
      });
    }
    async run(accessor, ...args2) {
      setEditorGroupLock(accessor, void 0, ...args2);
    }
  });
  $hJ(class extends $gJ {
    constructor() {
      super({
        id: $Hub,
        title: localize2(3478, "Lock Editor Group"),
        category: $qn.View,
        precondition: $Mpb.toNegated(),
        f1: true
      });
    }
    async run(accessor, ...args2) {
      setEditorGroupLock(accessor, true, ...args2);
    }
  });
  $hJ(class extends $gJ {
    constructor() {
      super({
        id: $Iub,
        title: localize2(3479, "Unlock Editor Group"),
        precondition: $Mpb,
        category: $qn.View,
        f1: true
      });
    }
    async run(accessor, ...args2) {
      setEditorGroupLock(accessor, false, ...args2);
    }
  });
  $0I.registerCommandAndKeybindingRule({
    id: $Lub,
    weight: 200,
    when: $xpb.toNegated(),
    primary: $$e(
      2048 | 41,
      1024 | 3
      /* KeyCode.Enter */
    ),
    handler: async (accessor, ...args2) => {
      const resolvedContext = $sub(args2, accessor.get($mJ), accessor.get($iJ), accessor.get($Deb));
      for (const { group: group2, editors } of resolvedContext.groupedEditors) {
        for (const editor of editors) {
          group2.stickEditor(editor);
        }
      }
    }
  });
  $0I.registerCommandAndKeybindingRule({
    id: $oub,
    weight: 200,
    when: EditorContextKeys.inDiffEditor,
    primary: $$e(
      2048 | 41,
      1024 | 45
      /* KeyCode.KeyO */
    ),
    handler: async (accessor) => {
      const editorService = accessor.get($mJ);
      const editorGroupsService = accessor.get($iJ);
      const activeEditor = editorService.activeEditor;
      const activeTextEditorControl = editorService.activeTextEditorControl;
      if (!$Q5(activeTextEditorControl) || !(activeEditor instanceof $fub)) {
        return;
      }
      let editor;
      const originalEditor = activeTextEditorControl.getOriginalEditor();
      if (originalEditor.hasTextFocus()) {
        editor = activeEditor.original;
      } else {
        editor = activeEditor.modified;
      }
      return editorGroupsService.activeGroup.openEditor(editor);
    }
  });
  $0I.registerCommandAndKeybindingRule({
    id: $Mub,
    weight: 200,
    when: $xpb,
    primary: $$e(
      2048 | 41,
      1024 | 3
      /* KeyCode.Enter */
    ),
    handler: async (accessor, ...args2) => {
      const resolvedContext = $sub(args2, accessor.get($mJ), accessor.get($iJ), accessor.get($Deb));
      for (const { group: group2, editors } of resolvedContext.groupedEditors) {
        for (const editor of editors) {
          group2.unstickEditor(editor);
        }
      }
    }
  });
  $0I.registerCommandAndKeybindingRule({
    id: $Jub,
    weight: 200,
    when: void 0,
    primary: void 0,
    handler: (accessor, ...args2) => {
      const editorGroupsService = accessor.get($iJ);
      const quickInputService = accessor.get($1M);
      const commandsContext = $sub(args2, accessor.get($mJ), editorGroupsService, accessor.get($Deb));
      const group2 = commandsContext.groupedEditors[0]?.group;
      if (group2) {
        editorGroupsService.activateGroup(group2);
      }
      return quickInputService.quickAccess.show($2tb.PREFIX);
    }
  });
}
function $dvb() {
  registerActiveEditorMoveCopyCommand();
  registerEditorGroupsLayoutCommands();
  $rub();
  registerOpenEditorAPICommands();
  registerOpenEditorAtIndexCommands();
  registerCloseEditorCommands();
  registerOtherEditorCommands();
  registerSplitEditorInGroupCommands();
  registerFocusSideEditorsCommands();
  registerFocusEditorGroupAtIndexCommands();
  registerSplitEditorCommands();
  registerFocusEditorGroupWihoutWrapCommands();
}

// out-build/vs/workbench/contrib/files/common/explorerFileNestingTrie.js
var $evb = class {
  constructor(config) {
    this.b = new $fvb();
    for (const [parentPattern, childPatterns] of config) {
      for (const childPattern of childPatterns) {
        this.b.add(parentPattern, childPattern);
      }
    }
  }
  toString() {
    return this.b.toString();
  }
  c(filename, dirname) {
    const lastDot = filename.lastIndexOf(".");
    if (lastDot < 1) {
      return {
        dirname,
        basename: filename,
        extname: ""
      };
    } else {
      return {
        dirname,
        basename: filename.substring(0, lastDot),
        extname: filename.substring(lastDot + 1)
      };
    }
  }
  nest(files, dirname) {
    const parentFinder = new $fvb();
    for (const potentialParent of files) {
      const attributes = this.c(potentialParent, dirname);
      const children = this.b.get(potentialParent, attributes);
      for (const child of children) {
        parentFinder.add(child, potentialParent);
      }
    }
    const findAllRootAncestors = (file, seen = /* @__PURE__ */ new Set()) => {
      if (seen.has(file)) {
        return [];
      }
      seen.add(file);
      const attributes = this.c(file, dirname);
      const ancestors = parentFinder.get(file, attributes);
      if (ancestors.length === 0) {
        return [file];
      }
      if (ancestors.length === 1 && ancestors[0] === file) {
        return [file];
      }
      return ancestors.flatMap((a) => findAllRootAncestors(a, seen));
    };
    const result = /* @__PURE__ */ new Map();
    for (const file of files) {
      let ancestors = findAllRootAncestors(file);
      if (ancestors.length === 0) {
        ancestors = [file];
      }
      for (const ancestor of ancestors) {
        let existing = result.get(ancestor);
        if (!existing) {
          result.set(ancestor, existing = /* @__PURE__ */ new Set());
        }
        if (file !== ancestor) {
          existing.add(file);
        }
      }
    }
    return result;
  }
};
var $fvb = class _$fvb {
  constructor() {
    this.b = new $gvb();
    this.c = /* @__PURE__ */ new Map();
  }
  add(key2, value) {
    if (key2 === "") {
      this.b.add(key2, value);
    } else if (key2[0] === "*") {
      this.b.add(key2, value);
    } else {
      const head = key2[0];
      const rest = key2.slice(1);
      let existing = this.c.get(head);
      if (!existing) {
        this.c.set(head, existing = new _$fvb());
      }
      existing.add(rest, value);
    }
  }
  get(key2, attributes) {
    const results = [];
    results.push(...this.b.get(key2, attributes));
    const head = key2[0];
    const rest = key2.slice(1);
    const existing = this.c.get(head);
    if (existing) {
      results.push(...existing.get(rest, attributes));
    }
    return results;
  }
  toString(indentation = "") {
    const lines = [];
    if (this.b.hasItems) {
      lines.push("* => \n" + this.b.toString(indentation + "  "));
    }
    [...this.c.entries()].map(([key2, trie]) => lines.push("^" + key2 + " => \n" + trie.toString(indentation + "  ")));
    return lines.map((l) => indentation + l).join("\n");
  }
};
var $gvb = class _$gvb {
  constructor() {
    this.b = [];
    this.c = [];
    this.d = /* @__PURE__ */ new Map();
    this.hasItems = false;
  }
  add(key2, value) {
    this.hasItems = true;
    if (key2 === "*") {
      this.b.push(new SubstitutionString(value));
    } else if (key2 === "") {
      this.c.push(new SubstitutionString(value));
    } else {
      const tail = key2[key2.length - 1];
      const rest = key2.slice(0, key2.length - 1);
      if (tail === "*") {
        throw Error("Unexpected star in SufTrie key: " + key2);
      } else {
        let existing = this.d.get(tail);
        if (!existing) {
          this.d.set(tail, existing = new _$gvb());
        }
        existing.add(rest, value);
      }
    }
  }
  get(key2, attributes) {
    const results = [];
    if (key2 === "") {
      results.push(...this.c.map((ss) => ss.substitute(attributes)));
    }
    if (this.b.length) {
      results.push(...this.b.map((ss) => ss.substitute(attributes, key2)));
    }
    const tail = key2[key2.length - 1];
    const rest = key2.slice(0, key2.length - 1);
    const existing = this.d.get(tail);
    if (existing) {
      results.push(...existing.get(rest, attributes));
    }
    return results;
  }
  toString(indentation = "") {
    const lines = [];
    if (this.b.length) {
      lines.push("* => " + this.b.join("; "));
    }
    if (this.c.length) {
      lines.push("\u03B5 => " + this.c.join("; "));
    }
    [...this.d.entries()].map(([key2, trie]) => lines.push(key2 + "$ => \n" + trie.toString(indentation + "  ")));
    return lines.map((l) => indentation + l).join("\n");
  }
};
var SubstitutionType;
(function(SubstitutionType2) {
  SubstitutionType2["capture"] = "capture";
  SubstitutionType2["basename"] = "basename";
  SubstitutionType2["dirname"] = "dirname";
  SubstitutionType2["extname"] = "extname";
})(SubstitutionType || (SubstitutionType = {}));
var substitutionStringTokenizer = /\$[({](capture|basename|dirname|extname)[)}]/g;
var SubstitutionString = class {
  constructor(pattern) {
    this.b = [];
    substitutionStringTokenizer.lastIndex = 0;
    let token;
    let lastIndex = 0;
    while (token = substitutionStringTokenizer.exec(pattern)) {
      const prefix = pattern.slice(lastIndex, token.index);
      this.b.push(prefix);
      const type = token[1];
      switch (type) {
        case "basename":
        case "dirname":
        case "extname":
        case "capture":
          this.b.push({ capture: type });
          break;
        default:
          throw Error("unknown substitution type: " + type);
      }
      lastIndex = token.index + token[0].length;
    }
    if (lastIndex !== pattern.length) {
      const suffix = pattern.slice(lastIndex, pattern.length);
      this.b.push(suffix);
    }
  }
  substitute(attributes, capture) {
    return this.b.map((t) => {
      if (typeof t === "string") {
        return t;
      }
      switch (t.capture) {
        case "basename":
          return attributes.basename;
        case "dirname":
          return attributes.dirname;
        case "extname":
          return attributes.extname;
        case "capture":
          return capture || "";
      }
    }).join("");
  }
};

// out-build/vs/workbench/contrib/files/common/explorerModel.js
var $hvb = class {
  constructor(f, g, fileService, configService, filesConfigService) {
    this.f = f;
    this.g = g;
    this.d = new $ze();
    const setRoots = () => this.a = this.f.getWorkspace().folders.map((folder) => new $ivb(folder.uri, fileService, configService, filesConfigService, void 0, true, false, false, false, folder.name));
    setRoots();
    this.b = this.f.onDidChangeWorkspaceFolders(() => {
      setRoots();
      this.d.fire();
    });
  }
  get roots() {
    return this.a;
  }
  get onDidChangeRoots() {
    return this.d.event;
  }
  /**
   * Returns an array of child stat from this stat that matches with the provided path.
   * Starts matching from the first root.
   * Will return empty array in case the FileStat does not exist.
   */
  findAll(resource) {
    return $Mb(this.roots.map((root) => root.find(resource)));
  }
  /**
   * Returns a FileStat that matches the passed resource.
   * In case multiple FileStat are matching the resource (same folder opened multiple times) returns the FileStat that has the closest root.
   * Will return undefined in case the FileStat does not exist.
   */
  findClosest(resource) {
    const folder = this.f.getWorkspaceFolder(resource);
    if (folder) {
      const root = this.roots.find((r2) => this.g.extUri.isEqual(r2.resource, folder.uri));
      if (root) {
        return root.find(resource);
      }
    }
    return null;
  }
  dispose() {
    $Xc(this.b);
  }
};
var $ivb = class _$ivb {
  constructor(resource, b, f, g, h3, j, k, l, m, n = $rh(resource), o, q = false) {
    this.resource = resource;
    this.b = b;
    this.f = f;
    this.g = g;
    this.h = h3;
    this.j = j;
    this.k = k;
    this.l = l;
    this.m = m;
    this.n = n;
    this.o = o;
    this.q = q;
    this.error = void 0;
    this.a = false;
    this.z = false;
    this._isDirectoryResolved = false;
  }
  get isExcluded() {
    if (this.a) {
      return true;
    }
    if (!this.h) {
      return false;
    }
    return this.h.isExcluded;
  }
  set isExcluded(value) {
    this.a = value;
  }
  hasChildren(filter) {
    if (this.hasNests) {
      return this.nestedChildren?.some((c) => filter(c)) ?? false;
    } else {
      return this.isDirectory;
    }
  }
  get hasNests() {
    return !!this.nestedChildren?.length;
  }
  get isDirectoryResolved() {
    return this._isDirectoryResolved;
  }
  get isSymbolicLink() {
    return !!this.k;
  }
  get isDirectory() {
    return !!this.j;
  }
  get isReadonly() {
    return this.g.isReadonly(this.resource, { resource: this.resource, name: this.name, readonly: this.l, locked: this.m });
  }
  get mtime() {
    return this.o;
  }
  get name() {
    return this.n;
  }
  get isUnknown() {
    return this.q;
  }
  get parent() {
    return this.h;
  }
  get root() {
    if (!this.h) {
      return this;
    }
    return this.h.root;
  }
  get children() {
    return /* @__PURE__ */ new Map();
  }
  t(value) {
    this.h?.removeChild(this);
    this.n = value;
    this.h?.addChild(this);
  }
  getId() {
    let id2 = this.root.resource.toString() + "::" + this.resource.toString();
    if (this.isMarkedAsFiltered()) {
      id2 += "::findFilterResult";
    }
    return id2;
  }
  toString() {
    return `ExplorerItem: ${this.name}`;
  }
  get isRoot() {
    return this === this.root;
  }
  static create(fileService, configService, filesConfigService, raw, parent, resolveTo) {
    const stat = new _$ivb(raw.resource, fileService, configService, filesConfigService, parent, raw.isDirectory, raw.isSymbolicLink, raw.readonly, raw.locked, raw.name, raw.mtime, !raw.isFile && !raw.isDirectory);
    if (stat.isDirectory) {
      stat._isDirectoryResolved = !!raw.children || !!resolveTo && resolveTo.some((r2) => {
        return $ph(r2, stat.resource);
      });
      if (raw.children) {
        for (let i2 = 0, len = raw.children.length; i2 < len; i2++) {
          const child = _$ivb.create(fileService, configService, filesConfigService, raw.children[i2], stat, resolveTo);
          stat.addChild(child);
        }
      }
    }
    return stat;
  }
  /**
   * Merges the stat which was resolved from the disk with the local stat by copying over properties
   * and children. The merge will only consider resolved stat elements to avoid overwriting data which
   * exists locally.
   */
  static mergeLocalWithDisk(disk, local) {
    if (disk.resource.toString() !== local.resource.toString()) {
      return;
    }
    const mergingDirectories = disk.isDirectory || local.isDirectory;
    if (mergingDirectories && local._isDirectoryResolved && !disk._isDirectoryResolved) {
      return;
    }
    local.resource = disk.resource;
    if (!local.isRoot) {
      local.t(disk.name);
    }
    local.j = disk.isDirectory;
    local.o = disk.mtime;
    local._isDirectoryResolved = disk._isDirectoryResolved;
    local.k = disk.isSymbolicLink;
    local.error = disk.error;
    if (mergingDirectories && disk._isDirectoryResolved) {
      const oldLocalChildren = new $Ec();
      local.children.forEach((child) => {
        oldLocalChildren.set(child.resource, child);
      });
      local.children.clear();
      disk.children.forEach((diskChild) => {
        const formerLocalChild = oldLocalChildren.get(diskChild.resource);
        if (formerLocalChild) {
          _$ivb.mergeLocalWithDisk(diskChild, formerLocalChild);
          local.addChild(formerLocalChild);
          oldLocalChildren.delete(diskChild.resource);
        } else {
          local.addChild(diskChild);
        }
      });
      oldLocalChildren.forEach((oldChild) => {
        if (oldChild instanceof $jvb) {
          local.addChild(oldChild);
        }
      });
    }
  }
  /**
   * Adds a child element to this folder.
   */
  addChild(child) {
    child.h = this;
    child.x(false);
    this.children.set(this.w(child.name), child);
  }
  getChild(name) {
    return this.children.get(this.w(name));
  }
  fetchChildren(sortOrder) {
    const nestingConfig = this.f.getValue({ resource: this.root.resource }).explorer.fileNesting;
    if (nestingConfig.enabled && this.nestedChildren) {
      return this.nestedChildren;
    }
    return (async () => {
      if (!this._isDirectoryResolved) {
        const resolveMetadata = sortOrder === "modified";
        this.error = void 0;
        try {
          const stat = await this.b.resolve(this.resource, { resolveSingleChildDescendants: true, resolveMetadata });
          const resolved = _$ivb.create(this.b, this.f, this.g, stat, this);
          _$ivb.mergeLocalWithDisk(resolved, this);
        } catch (e) {
          this.error = e;
          throw e;
        }
        this._isDirectoryResolved = true;
      }
      const items = [];
      if (nestingConfig.enabled) {
        const fileChildren = [];
        const dirChildren = [];
        for (const child of this.children.entries()) {
          child[1].nestedParent = void 0;
          if (child[1].isDirectory) {
            dirChildren.push(child);
          } else {
            fileChildren.push(child);
          }
        }
        const nested = this.v.nest(fileChildren.map(([name]) => name), this.w(this.name));
        for (const [fileEntryName, fileEntryItem] of fileChildren) {
          const nestedItems = nested.get(fileEntryName);
          if (nestedItems !== void 0) {
            fileEntryItem.nestedChildren = [];
            for (const name of nestedItems.keys()) {
              const child = $Kg(this.children.get(name));
              fileEntryItem.nestedChildren.push(child);
              child.nestedParent = fileEntryItem;
            }
            items.push(fileEntryItem);
          } else {
            fileEntryItem.nestedChildren = void 0;
          }
        }
        for (const [_, dirEntryItem] of dirChildren.values()) {
          items.push(dirEntryItem);
        }
      } else {
        this.children.forEach((child) => {
          items.push(child);
        });
      }
      return items;
    })();
  }
  get v() {
    if (!this.root.u) {
      const nestingConfig = this.f.getValue({ resource: this.root.resource }).explorer.fileNesting;
      const patterns = Object.entries(nestingConfig.patterns).filter((entry) => typeof entry[0] === "string" && typeof entry[1] === "string" && entry[0] && entry[1]).map(([parentPattern, childrenPatterns]) => [
        this.w(parentPattern.trim()),
        childrenPatterns.split(",").map((p) => this.w(p.trim().replace(/\u200b/g, "").trim())).filter((p) => p !== "")
      ]);
      this.root.u = new $evb(patterns);
    }
    return this.root.u;
  }
  /**
   * Removes a child element from this folder.
   */
  removeChild(child) {
    this.nestedChildren = void 0;
    this.children.delete(this.w(child.name));
  }
  forgetChildren() {
    this.children.clear();
    this.nestedChildren = void 0;
    this._isDirectoryResolved = false;
    this.u = void 0;
  }
  w(name) {
    return this.b.hasCapability(
      this.resource,
      1024
      /* FileSystemProviderCapabilities.PathCaseSensitive */
    ) ? name : name.toLowerCase();
  }
  /**
   * Moves this element under a new parent element.
   */
  move(newParent) {
    this.nestedParent?.removeChild(this);
    this.h?.removeChild(this);
    newParent.removeChild(this);
    newParent.addChild(this);
    this.x(true);
  }
  x(recursive) {
    if (this.h) {
      this.resource = $vh(this.h.resource, this.name);
    }
    if (recursive) {
      if (this.isDirectory) {
        this.children.forEach((child) => {
          child.x(true);
        });
      }
    }
  }
  /**
   * Tells this stat that it was renamed. This requires changes to all children of this stat (if any)
   * so that the path property can be updated properly.
   */
  rename(renamedStat) {
    this.t(renamedStat.name);
    this.o = renamedStat.mtime;
    this.x(true);
  }
  /**
   * Returns a child stat from this stat that matches with the provided path.
   * Will return "null" in case the child does not exist.
   */
  find(resource) {
    const ignoreCase = !this.b.hasCapability(
      resource,
      1024
      /* FileSystemProviderCapabilities.PathCaseSensitive */
    );
    if (resource && this.resource.scheme === resource.scheme && $1f(this.resource.authority, resource.authority) && (ignoreCase ? $2f(resource.path, this.resource.path) : resource.path.startsWith(this.resource.path))) {
      return this.y($Gf(resource.path, $kc.sep), this.resource.path.length, ignoreCase);
    }
    return null;
  }
  y(path, index, ignoreCase) {
    if ($Yg($Gf(this.resource.path, $kc.sep), path, ignoreCase)) {
      return this;
    }
    if (this.isDirectory) {
      while (index < path.length && path[index] === $kc.sep) {
        index++;
      }
      let indexOfNextSep = path.indexOf($kc.sep, index);
      if (indexOfNextSep === -1) {
        indexOfNextSep = path.length;
      }
      const name = path.substring(index, indexOfNextSep);
      const child = this.children.get(this.w(name));
      if (child) {
        return child.y(path, indexOfNextSep, ignoreCase);
      }
    }
    return null;
  }
  isMarkedAsFiltered() {
    return this.z;
  }
  markItemAndParentsAsFiltered() {
    this.z = true;
    this.parent?.markItemAndParentsAsFiltered();
  }
  unmarkItemAndChildren() {
    this.z = false;
    this.children.forEach((child) => child.unmarkItemAndChildren());
  }
};
__decorate([
  $0t
], $ivb.prototype, "children", null);
var $jvb = class extends $ivb {
  constructor(fileService, configService, filesConfigService, parent, isDirectory) {
    super(URI.file(""), fileService, configService, filesConfigService, parent, isDirectory);
    this._isDirectoryResolved = true;
  }
};

// out-build/vs/workbench/services/workingCopy/common/workingCopyFileOperationParticipant.js
var $1J = class $1J2 extends $3c {
  constructor(b, c) {
    super();
    this.b = b;
    this.c = c;
    this.a = new $cd();
  }
  addFileOperationParticipant(participant) {
    const remove = this.a.push(participant);
    return $1c(() => remove());
  }
  async participate(files, operation, undoInfo, token) {
    const timeout = this.c.getValue("files.participants.timeout");
    if (typeof timeout !== "number" || timeout <= 0) {
      return;
    }
    for (const participant of this.a) {
      try {
        await participant.participate(files, operation, undoInfo, timeout, token);
      } catch (err) {
        this.b.warn(err);
      }
    }
  }
  dispose() {
    this.a.clear();
    super.dispose();
  }
};
$1J = __decorate([
  __param(0, $wn),
  __param(1, $kl)
], $1J);

// out-build/vs/workbench/services/workingCopy/common/storedFileWorkingCopySaveParticipant.js
var $_J = class $_J2 extends $3c {
  get length() {
    return this.a.size;
  }
  constructor(b, c) {
    super();
    this.b = b;
    this.c = c;
    this.a = new $cd();
  }
  addSaveParticipant(participant) {
    const remove = this.a.push(participant);
    return $1c(() => remove());
  }
  async participate(workingCopy, context, progress, token) {
    const cts = new $ad(token);
    workingCopy.model?.pushStackElement();
    progress.report({
      message: localize(13614, null)
    });
    let bubbleCancel = false;
    await this.c.withProgress({
      priority: NotificationPriority.URGENT,
      location: 15,
      cancellable: localize(13615, null),
      delay: workingCopy.isDirty() ? 5e3 : 3e3
    }, async (progress2) => {
      for (const saveParticipant of this.a) {
        if (cts.token.isCancellationRequested || workingCopy.isDisposed()) {
          break;
        }
        try {
          const promise = saveParticipant.participate(workingCopy, context, progress2, cts.token);
          await $Ih(promise, cts.token);
        } catch (err) {
          if (!$kb(err)) {
            this.b.error(err);
          } else if (!cts.token.isCancellationRequested) {
            cts.cancel();
            bubbleCancel = true;
          }
        }
      }
    }, () => {
      cts.cancel();
    });
    workingCopy.model?.pushStackElement();
    cts.dispose();
    if (bubbleCancel) {
      throw new $lb();
    }
  }
  dispose() {
    this.a.clear();
    super.dispose();
  }
};
$_J = __decorate([
  __param(0, $wn),
  __param(1, $TJ)
], $_J);

// out-build/vs/workbench/services/workingCopy/common/workingCopyFileService.js
var $aK = $Qk("workingCopyFileService");
var $bK = class $bK2 extends $3c {
  constructor(g, h3, j, m) {
    super();
    this.g = g;
    this.h = h3;
    this.j = j;
    this.m = m;
    this.a = this.B(new $Be());
    this.onWillRunWorkingCopyFileOperation = this.a.event;
    this.b = this.B(new $Be());
    this.onDidFailWorkingCopyFileOperation = this.b.event;
    this.c = this.B(new $Be());
    this.onDidRunWorkingCopyFileOperation = this.c.event;
    this.f = 0;
    this.r = this.B(this.j.createInstance($1J));
    this.t = this.B(this.j.createInstance($_J));
    this.u = [];
    this.B(this.registerWorkingCopyProvider((resource) => {
      return this.h.workingCopies.filter((workingCopy) => {
        if (this.g.hasProvider(resource)) {
          return this.m.extUri.isEqualOrParent(workingCopy.resource, resource);
        }
        return this.m.extUri.isEqual(workingCopy.resource, resource);
      });
    }));
  }
  //#region File operations
  create(operations, token, undoInfo) {
    return this.doCreateFileOrFolder(operations, true, token, undoInfo);
  }
  createFolder(operations, token, undoInfo) {
    return this.doCreateFileOrFolder(operations, false, token, undoInfo);
  }
  async doCreateFileOrFolder(operations, isFile, token, undoInfo) {
    if (operations.length === 0) {
      return [];
    }
    if (isFile) {
      const validateCreates = await Promises.settled(operations.map((operation) => this.g.canCreateFile(operation.resource, { overwrite: operation.overwrite })));
      const error = validateCreates.find((validateCreate) => validateCreate instanceof Error);
      if (error instanceof Error) {
        throw error;
      }
    }
    const files = operations.map((operation) => ({ target: operation.resource }));
    await this.s(files, 0, undoInfo, token);
    const event = { correlationId: this.f++, operation: 0, files };
    await this.a.fireAsync(
      event,
      CancellationToken.None
      /* intentional: we currently only forward cancellation to participants */
    );
    let stats;
    try {
      if (isFile) {
        stats = await Promises.settled(operations.map((operation) => this.g.createFile(operation.resource, operation.contents, { overwrite: operation.overwrite })));
      } else {
        stats = await Promises.settled(operations.map((operation) => this.g.createFolder(operation.resource)));
      }
    } catch (error) {
      await this.b.fireAsync(
        event,
        CancellationToken.None
        /* intentional: we currently only forward cancellation to participants */
      );
      throw error;
    }
    await this.c.fireAsync(
      event,
      CancellationToken.None
      /* intentional: we currently only forward cancellation to participants */
    );
    return stats;
  }
  async move(operations, token, undoInfo) {
    return this.n(operations, true, token, undoInfo);
  }
  async copy(operations, token, undoInfo) {
    return this.n(operations, false, token, undoInfo);
  }
  async n(operations, move, token, undoInfo) {
    const stats = [];
    for (const { file: { source, target }, overwrite } of operations) {
      const validateMoveOrCopy = await (move ? this.g.canMove(source, target, overwrite) : this.g.canCopy(source, target, overwrite));
      if (validateMoveOrCopy instanceof Error) {
        throw validateMoveOrCopy;
      }
    }
    const files = operations.map((o) => o.file);
    await this.s(files, move ? 2 : 3, undoInfo, token);
    const event = { correlationId: this.f++, operation: move ? 2 : 3, files };
    await this.a.fireAsync(
      event,
      CancellationToken.None
      /* intentional: we currently only forward cancellation to participants */
    );
    try {
      for (const { file: { source, target }, overwrite } of operations) {
        if (!this.m.extUri.isEqual(source, target)) {
          const dirtyWorkingCopies = move ? [...this.getDirty(source), ...this.getDirty(target)] : this.getDirty(target);
          await Promises.settled(dirtyWorkingCopies.map((dirtyWorkingCopy) => dirtyWorkingCopy.revert({ soft: true })));
        }
        if (move) {
          stats.push(await this.g.move(source, target, overwrite));
        } else {
          stats.push(await this.g.copy(source, target, overwrite));
        }
      }
    } catch (error) {
      await this.b.fireAsync(
        event,
        CancellationToken.None
        /* intentional: we currently only forward cancellation to participants */
      );
      throw error;
    }
    await this.c.fireAsync(
      event,
      CancellationToken.None
      /* intentional: we currently only forward cancellation to participants */
    );
    return stats;
  }
  async delete(operations, token, undoInfo) {
    for (const operation of operations) {
      const validateDelete = await this.g.canDelete(operation.resource, { recursive: operation.recursive, useTrash: operation.useTrash });
      if (validateDelete instanceof Error) {
        throw validateDelete;
      }
    }
    const files = operations.map((operation) => ({ target: operation.resource }));
    await this.s(files, 1, undoInfo, token);
    const event = { correlationId: this.f++, operation: 1, files };
    await this.a.fireAsync(
      event,
      CancellationToken.None
      /* intentional: we currently only forward cancellation to participants */
    );
    for (const operation of operations) {
      const dirtyWorkingCopies = this.getDirty(operation.resource);
      await Promises.settled(dirtyWorkingCopies.map((dirtyWorkingCopy) => dirtyWorkingCopy.revert({ soft: true })));
    }
    try {
      for (const operation of operations) {
        await this.g.del(operation.resource, { recursive: operation.recursive, useTrash: operation.useTrash });
      }
    } catch (error) {
      await this.b.fireAsync(
        event,
        CancellationToken.None
        /* intentional: we currently only forward cancellation to participants */
      );
      throw error;
    }
    await this.c.fireAsync(
      event,
      CancellationToken.None
      /* intentional: we currently only forward cancellation to participants */
    );
  }
  addFileOperationParticipant(participant) {
    return this.r.addFileOperationParticipant(participant);
  }
  s(files, operation, undoInfo, token) {
    return this.r.participate(files, operation, undoInfo, token);
  }
  get hasSaveParticipants() {
    return this.t.length > 0;
  }
  addSaveParticipant(participant) {
    return this.t.addSaveParticipant(participant);
  }
  runSaveParticipants(workingCopy, context, progress, token) {
    return this.t.participate(workingCopy, context, progress, token);
  }
  registerWorkingCopyProvider(provider) {
    const remove = $Wb(this.u, provider);
    return $1c(remove);
  }
  getDirty(resource) {
    const dirtyWorkingCopies = /* @__PURE__ */ new Set();
    for (const provider of this.u) {
      for (const workingCopy of provider(resource)) {
        if (workingCopy.isDirty()) {
          dirtyWorkingCopies.add(workingCopy);
        }
      }
    }
    return Array.from(dirtyWorkingCopies);
  }
};
$bK = __decorate([
  __param(0, $km),
  __param(1, $XI),
  __param(2, $Pk),
  __param(3, $vl)
], $bK);
$SC(
  $aK,
  $bK,
  1
  /* InstantiationType.Delayed */
);

// out-build/vs/workbench/services/views/common/viewsService.js
var $uob = $Qk("viewsService");

// out-build/vs/workbench/contrib/files/browser/files.js
var $kvb = $Qk("explorerService");
function getFocus(listService) {
  const list2 = listService.lastFocusedList;
  const element = list2?.getHTMLElement();
  if (element && $Mj(element)) {
    let focus;
    if (list2 instanceof $A1) {
      const focused = list2.getFocusedElements();
      if (focused.length) {
        focus = focused[0];
      }
    } else if (list2 instanceof $E3) {
      const focused = list2.getFocus();
      if (focused.length) {
        focus = focused[0];
      }
    }
    return focus;
  }
  return void 0;
}
function $lvb(commandArg, editorService, listService) {
  if (URI.isUri(commandArg)) {
    return commandArg;
  }
  const focus = getFocus(listService);
  if (focus instanceof $ivb) {
    return focus.resource;
  } else if (focus instanceof $rtb) {
    return focus.getResource();
  }
  return $mL.getOriginalUri(editorService.activeEditor, { supportSideBySide: SideBySideEditor.PRIMARY });
}
function $mvb(commandArg, listService, editorSerice, editorGroupService, explorerService) {
  const list2 = listService.lastFocusedList;
  const element = list2?.getHTMLElement();
  if (element && $Mj(element)) {
    if (list2 instanceof $E3 && list2.getFocus().every((item) => item instanceof $ivb)) {
      const context = explorerService.getContext(true, true);
      if (context.length) {
        return context.map((c) => c.resource);
      }
    }
    if (list2 instanceof $A1) {
      const selection2 = $Mb(list2.getSelectedElements().filter((s) => s instanceof $rtb).map((oe) => oe.getResource()));
      const focusedElements = list2.getFocusedElements();
      const focus = focusedElements.length ? focusedElements[0] : void 0;
      let mainUriStr = void 0;
      if (URI.isUri(commandArg)) {
        mainUriStr = commandArg.toString();
      } else if (focus instanceof $rtb) {
        const focusedResource = focus.getResource();
        mainUriStr = focusedResource ? focusedResource.toString() : void 0;
      }
      const mainIndex = selection2.findIndex((s) => s.toString() === mainUriStr);
      if (mainIndex !== -1) {
        const mainResource = selection2[mainIndex];
        selection2.splice(mainIndex, 1);
        selection2.unshift(mainResource);
        return selection2;
      }
    }
  }
  const activeGroup = editorGroupService.activeGroup;
  const selection = activeGroup.selectedEditors;
  if (selection.length > 1 && URI.isUri(commandArg)) {
    const mainEditorSelectionIndex = selection.findIndex((e) => e.matches({ resource: commandArg }));
    if (mainEditorSelectionIndex !== -1) {
      const mainEditor = selection[mainEditorSelectionIndex];
      selection.splice(mainEditorSelectionIndex, 1);
      selection.unshift(mainEditor);
      return selection.map((editor) => $mL.getOriginalUri(editor)).filter((uri) => !!uri);
    }
  }
  const result = $lvb(commandArg, editorSerice, listService);
  return !!result ? [result] : [];
}
function $nvb(accessor) {
  const list2 = accessor.get($Deb).lastFocusedList;
  const element = list2?.getHTMLElement();
  if (element && $Mj(element)) {
    if (list2 instanceof $A1) {
      const selection = $Mb(list2.getSelectedElements().filter((s) => s instanceof $rtb));
      const focusedElements = list2.getFocusedElements();
      const focus = focusedElements.length ? focusedElements[0] : void 0;
      let mainEditor = void 0;
      if (focus instanceof $rtb) {
        mainEditor = focus;
      }
      if (selection.some((s) => s === mainEditor)) {
        return selection;
      }
      return mainEditor ? [mainEditor] : void 0;
    }
  }
  return void 0;
}

// out-build/vs/workbench/services/workspaces/common/workspaceEditing.js
var $zob = $Qk("workspaceEditingService");

// out-build/vs/workbench/contrib/files/browser/fileImportExport.js
var $ovb_1;
var $qvb_1;
var $ovb = class $ovb2 {
  static {
    $ovb_1 = this;
  }
  static {
    this.a = 20;
  }
  constructor(b, c, d, e, f) {
    this.b = b;
    this.c = c;
    this.d = d;
    this.e = e;
    this.f = f;
  }
  upload(target, source) {
    const cts = new $ad();
    const uploadPromise = this.b.withProgress({
      location: 10,
      delay: 800,
      cancellable: true,
      title: localize(7227, null)
    }, async (progress) => this.h(target, this.g(source), progress, cts.token), () => cts.dispose(true));
    this.b.withProgress({ location: $4sb, delay: 500 }, () => uploadPromise);
    return uploadPromise;
  }
  g(source) {
    if ($6j(source)) {
      return source.dataTransfer;
    }
    const transfer = { items: [] };
    for (const file of source) {
      transfer.items.push({
        webkitGetAsEntry: () => {
          return {
            name: file.name,
            isDirectory: false,
            isFile: true,
            createReader: () => {
              throw new Error("Unsupported for files");
            },
            file: (resolve) => resolve(file)
          };
        }
      });
    }
    return transfer;
  }
  async h(target, source, progress, token) {
    const items = source.items;
    const entries2 = [];
    for (const item of items) {
      entries2.push(item.webkitGetAsEntry());
    }
    const results = [];
    const operation = {
      startTime: Date.now(),
      progressScheduler: new $0h((steps) => {
        progress.report(steps[steps.length - 1]);
      }, 1e3),
      filesTotal: entries2.length,
      filesUploaded: 0,
      totalBytesUploaded: 0
    };
    const uploadLimiter = new $2h($ovb_1.a);
    await Promises.settled(entries2.map((entry) => {
      return uploadLimiter.queue(async () => {
        if (token.isCancellationRequested) {
          return;
        }
        if (target && entry.name && target.getChild(entry.name)) {
          const { confirmed } = await this.c.confirm($rvb(entry.name));
          if (!confirmed) {
            return;
          }
          await this.d.applyBulkEdit([new $K_($vh(target.resource, entry.name), void 0, { recursive: true, folder: target.getChild(entry.name)?.isDirectory })], {
            undoLabel: localize(7228, null, entry.name),
            progressLabel: localize(7229, null, entry.name)
          });
          if (token.isCancellationRequested) {
            return;
          }
        }
        const result = await this.i(entry, target.resource, target, progress, operation, token);
        if (result) {
          results.push(result);
        }
      });
    }));
    operation.progressScheduler.dispose();
    const firstUploadedFile = results[0];
    if (!token.isCancellationRequested && firstUploadedFile?.isFile) {
      await this.e.openEditor({ resource: firstUploadedFile.resource, options: { pinned: true } });
    }
  }
  async i(entry, parentResource, target, progress, operation, token) {
    if (token.isCancellationRequested || !entry.name || !entry.isFile && !entry.isDirectory) {
      return void 0;
    }
    let fileBytesUploaded = 0;
    const reportProgress = (fileSize, bytesUploaded) => {
      fileBytesUploaded += bytesUploaded;
      operation.totalBytesUploaded += bytesUploaded;
      const bytesUploadedPerSecond = operation.totalBytesUploaded / ((Date.now() - operation.startTime) / 1e3);
      let message;
      if (fileSize < $Sm.MB) {
        if (operation.filesTotal === 1) {
          message = `${entry.name}`;
        } else {
          message = localize(7230, null, operation.filesUploaded, operation.filesTotal, $Sm.formatSize(bytesUploadedPerSecond));
        }
      } else {
        message = localize(7231, null, entry.name, $Sm.formatSize(fileBytesUploaded), $Sm.formatSize(fileSize), $Sm.formatSize(bytesUploadedPerSecond));
      }
      operation.progressScheduler.work({ message });
    };
    operation.filesUploaded++;
    reportProgress(0, 0);
    const resource = $vh(parentResource, entry.name);
    if (entry.isFile) {
      const file = await new Promise((resolve, reject) => entry.file(resolve, reject));
      if (token.isCancellationRequested) {
        return void 0;
      }
      if (typeof file.stream === "function" && file.size > $Sm.MB) {
        await this.j(resource, file, reportProgress, token);
      } else {
        await this.k(resource, file, reportProgress);
      }
      return { isFile: true, resource };
    } else {
      await this.f.createFolder(resource);
      if (token.isCancellationRequested) {
        return void 0;
      }
      const dirReader = entry.createReader();
      const childEntries = [];
      let done = false;
      do {
        const childEntriesChunk = await new Promise((resolve, reject) => dirReader.readEntries(resolve, reject));
        if (childEntriesChunk.length > 0) {
          childEntries.push(...childEntriesChunk);
        } else {
          done = true;
        }
      } while (!done && !token.isCancellationRequested);
      operation.filesTotal += childEntries.length;
      const folderTarget = target && target.getChild(entry.name) || void 0;
      const fileChildEntries = [];
      const folderChildEntries = [];
      for (const childEntry of childEntries) {
        if (childEntry.isFile) {
          fileChildEntries.push(childEntry);
        } else if (childEntry.isDirectory) {
          folderChildEntries.push(childEntry);
        }
      }
      const fileUploadQueue = new $2h($ovb_1.a);
      await Promises.settled(fileChildEntries.map((fileChildEntry) => {
        return fileUploadQueue.queue(() => this.i(fileChildEntry, resource, folderTarget, progress, operation, token));
      }));
      for (const folderChildEntry of folderChildEntries) {
        await this.i(folderChildEntry, resource, folderTarget, progress, operation, token);
      }
      return { isFile: false, resource };
    }
  }
  async j(resource, file, progressReporter, token) {
    const writeableStream = $Si({
      // Set a highWaterMark to prevent the stream
      // for file upload to produce large buffers
      // in-memory
      highWaterMark: 10
    });
    const writeFilePromise = this.f.writeFile(resource, writeableStream);
    try {
      const reader = file.stream().getReader();
      let res = await reader.read();
      while (!res.done) {
        if (token.isCancellationRequested) {
          break;
        }
        const buffer = $Ci.wrap(res.value);
        await writeableStream.write(buffer);
        if (token.isCancellationRequested) {
          break;
        }
        progressReporter(file.size, buffer.byteLength);
        res = await reader.read();
      }
      writeableStream.end(void 0);
    } catch (error) {
      writeableStream.error(error);
      writeableStream.end();
    }
    if (token.isCancellationRequested) {
      return void 0;
    }
    await writeFilePromise;
  }
  k(resource, file, progressReporter) {
    return new Promise((resolve, reject) => {
      const reader = new FileReader();
      reader.onload = async (event) => {
        try {
          if (event.target?.result instanceof ArrayBuffer) {
            const buffer = $Ci.wrap(new Uint8Array(event.target.result));
            await this.f.writeFile(resource, buffer);
            progressReporter(file.size, buffer.byteLength);
          } else {
            throw new Error("Could not read from dropped file.");
          }
          resolve();
        } catch (error) {
          reject(error);
        }
      };
      reader.readAsArrayBuffer(file);
    });
  }
};
$ovb = $ovb_1 = __decorate([
  __param(0, $TJ),
  __param(1, $Yv),
  __param(2, $kvb),
  __param(3, $mJ),
  __param(4, $km)
], $ovb);
var $pvb = class $pvb2 {
  constructor(a, b, c, d, e, f, g, h3, i2, j, k) {
    this.a = a;
    this.b = b;
    this.c = c;
    this.d = d;
    this.e = e;
    this.f = f;
    this.g = g;
    this.h = h3;
    this.i = i2;
    this.j = j;
    this.k = k;
  }
  async import(target, source, targetWindow) {
    const cts = new $ad();
    const importPromise = this.i.withProgress({
      location: 10,
      delay: 800,
      cancellable: true,
      title: localize(7232, null)
    }, async () => await this.l(target, source, targetWindow, cts.token), () => cts.dispose(true));
    this.i.withProgress({ location: $4sb, delay: 500 }, () => importPromise);
    return importPromise;
  }
  async l(target, source, targetWindow, token) {
    const candidateFiles = $Mb((await this.k.invokeFunction((accessor) => $w_(accessor, source))).map((editor) => editor.resource));
    await Promise.all(candidateFiles.map((resource) => this.a.activateProvider(resource.scheme)));
    const files = $Mb(candidateFiles.filter((resource) => this.a.hasProvider(resource)));
    const resolvedFiles = await this.a.resolveAll(files.map((file) => ({ resource: file })));
    if (token.isCancellationRequested) {
      return;
    }
    this.b.focus(targetWindow);
    const folders = resolvedFiles.filter((resolvedFile) => resolvedFile.success && resolvedFile.stat?.isDirectory).map((resolvedFile) => ({ uri: resolvedFile.stat.resource }));
    if (folders.length > 0 && target.isRoot) {
      let ImportChoice;
      (function(ImportChoice2) {
        ImportChoice2[ImportChoice2["Copy"] = 1] = "Copy";
        ImportChoice2[ImportChoice2["Add"] = 2] = "Add";
      })(ImportChoice || (ImportChoice = {}));
      const buttons = [
        {
          label: folders.length > 1 ? localize(7233, null) : localize(7234, null),
          run: () => ImportChoice.Copy
        }
      ];
      let message;
      const workspaceFolderSchemas = this.c.getWorkspace().folders.map((folder) => folder.uri.scheme);
      if (folders.some((folder) => workspaceFolderSchemas.indexOf(folder.uri.scheme) >= 0)) {
        buttons.unshift({
          label: folders.length > 1 ? localize(7235, null) : localize(7236, null),
          run: () => ImportChoice.Add
        });
        message = folders.length > 1 ? localize(7237, null) : localize(7238, null, $sh(folders[0].uri));
      } else {
        message = folders.length > 1 ? localize(7239, null) : localize(7240, null, $sh(folders[0].uri));
      }
      const { result } = await this.e.prompt({
        type: Severity2.Info,
        message,
        buttons,
        cancelButton: true
      });
      if (result === ImportChoice.Add) {
        return this.f.addFolders(folders);
      }
      if (result === ImportChoice.Copy) {
        return this.m(target, files, token);
      }
    } else if (target instanceof $ivb) {
      return this.m(target, files, token);
    }
  }
  async m(target, resources, token) {
    if (resources && resources.length > 0) {
      const targetStat = await this.a.resolve(target.resource);
      if (token.isCancellationRequested) {
        return;
      }
      const targetNames = /* @__PURE__ */ new Set();
      const caseSensitive = this.a.hasCapability(
        target.resource,
        1024
        /* FileSystemProviderCapabilities.PathCaseSensitive */
      );
      if (targetStat.children) {
        targetStat.children.forEach((child) => {
          targetNames.add(caseSensitive ? child.name : child.name.toLowerCase());
        });
      }
      let inaccessibleFileCount = 0;
      const resourcesFiltered = $Mb(await Promises.settled(resources.map(async (resource) => {
        const fileDoesNotExist = !await this.a.exists(resource);
        if (fileDoesNotExist) {
          inaccessibleFileCount++;
          return void 0;
        }
        if (targetNames.has(caseSensitive ? $sh(resource) : $sh(resource).toLowerCase())) {
          const confirmationResult = await this.e.confirm($rvb($sh(resource)));
          if (!confirmationResult.confirmed) {
            return void 0;
          }
        }
        return resource;
      })));
      if (inaccessibleFileCount > 0) {
        this.j.error(inaccessibleFileCount > 1 ? localize(7241, null) : localize(7242, null));
      }
      const resourceFileEdits = resourcesFiltered.map((resource) => {
        const sourceFileName = $sh(resource);
        const targetFile = $vh(target.resource, sourceFileName);
        return new $K_(resource, targetFile, { overwrite: true, copy: true });
      });
      const undoLevel = this.d.getValue().explorer.confirmUndo;
      await this.g.applyBulkEdit(resourceFileEdits, {
        undoLabel: resourcesFiltered.length === 1 ? localize(7243, null, $sh(resourcesFiltered[0])) : localize(7244, null, resourcesFiltered.length),
        progressLabel: resourcesFiltered.length === 1 ? localize(7245, null, $sh(resourcesFiltered[0])) : localize(7246, null, resourcesFiltered.length),
        progressLocation: 10,
        confirmBeforeUndo: undoLevel === "verbose" || undoLevel === "default"
      });
      const autoOpen = this.d.getValue().explorer.autoOpenDroppedFile;
      if (autoOpen && resourceFileEdits.length === 1) {
        const item = this.g.findClosest(resourceFileEdits[0].newResource);
        if (item && !item.isDirectory) {
          this.h.openEditor({ resource: item.resource, options: { pinned: true } });
        }
      }
    }
  }
};
$pvb = __decorate([
  __param(0, $km),
  __param(1, $S4),
  __param(2, $Zk),
  __param(3, $kl),
  __param(4, $Yv),
  __param(5, $zob),
  __param(6, $kvb),
  __param(7, $mJ),
  __param(8, $TJ),
  __param(9, $PJ),
  __param(10, $Pk)
], $pvb);
var $qvb = class $qvb2 {
  static {
    $qvb_1 = this;
  }
  static {
    this.a = "workbench.explorer.downloadPath";
  }
  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;
  }
  download(source) {
    const cts = new $ad();
    const downloadPromise = this.d.withProgress({
      location: 10,
      delay: 800,
      cancellable: $r,
      title: localize(7247, null)
    }, async (progress) => this.h(source, progress, cts), () => cts.dispose(true));
    this.d.withProgress({ location: $4sb, delay: 500 }, () => downloadPromise);
    return downloadPromise;
  }
  async h(sources, progress, cts) {
    for (const source of sources) {
      if (cts.token.isCancellationRequested) {
        return;
      }
      if ($r) {
        await this.i(source.resource, progress, cts);
      } else {
        await this.o(source, progress, cts);
      }
    }
  }
  async i(resource, progress, cts) {
    const stat = await this.b.resolve(resource, { resolveMetadata: true });
    if (cts.token.isCancellationRequested) {
      return;
    }
    const maxBlobDownloadSize = 32 * $Sm.MB;
    const preferFileSystemAccessWebApis = stat.isDirectory || stat.size > maxBlobDownloadSize;
    const activeWindow = $Qj();
    if (preferFileSystemAccessWebApis && WebFileSystemAccess.supported(activeWindow)) {
      try {
        const parentFolder = await activeWindow.showDirectoryPicker();
        const operation = {
          startTime: Date.now(),
          progressScheduler: new $0h((steps) => {
            progress.report(steps[steps.length - 1]);
          }, 1e3),
          filesTotal: stat.isDirectory ? 0 : 1,
          // folders increment filesTotal within downloadFolder method
          filesDownloaded: 0,
          totalBytesDownloaded: 0,
          fileBytesDownloaded: 0
        };
        if (stat.isDirectory) {
          const targetFolder = await parentFolder.getDirectoryHandle(stat.name, { create: true });
          await this.m(stat, targetFolder, operation, cts.token);
        } else {
          await this.l(parentFolder, stat, operation, cts.token);
        }
        operation.progressScheduler.dispose();
      } catch (error) {
        this.e.warn(error);
        cts.cancel();
      }
    } else if (stat.isFile) {
      let bufferOrUri;
      try {
        bufferOrUri = (await this.b.readFile(stat.resource, { limits: { size: maxBlobDownloadSize } }, cts.token)).value.buffer;
      } catch (error) {
        bufferOrUri = $ih.uriToBrowserUri(stat.resource);
      }
      if (!cts.token.isCancellationRequested) {
        $rk(bufferOrUri, stat.name);
      }
    }
  }
  async j(resource, target, operation, token) {
    const contents = await this.b.readFileStream(resource, void 0, token);
    if (token.isCancellationRequested) {
      target.close();
      return;
    }
    return new Promise((resolve, reject) => {
      const sourceStream = contents.value;
      const disposables = new $2c();
      disposables.add($1c(() => target.close()));
      disposables.add($Qc(token.onCancellationRequested)(() => {
        disposables.dispose();
        reject($mb());
      }));
      $ui(sourceStream, {
        onData: (data) => {
          target.write(data.buffer);
          this.n(contents.name, contents.size, data.byteLength, operation);
        },
        onError: (error) => {
          disposables.dispose();
          reject(error);
        },
        onEnd: () => {
          disposables.dispose();
          resolve();
        }
      }, token);
    });
  }
  async k(resource, target, operation, token) {
    const contents = await this.b.readFile(resource, void 0, token);
    if (!token.isCancellationRequested) {
      target.write(contents.value.buffer);
      this.n(contents.name, contents.size, contents.value.byteLength, operation);
    }
    target.close();
  }
  async l(targetFolder, file, operation, token) {
    operation.filesDownloaded++;
    operation.fileBytesDownloaded = 0;
    this.n(file.name, 0, 0, operation);
    const targetFile = await targetFolder.getFileHandle(file.name, { create: true });
    const targetFileWriter = await targetFile.createWritable();
    if (file.size > $Sm.MB) {
      return this.j(file.resource, targetFileWriter, operation, token);
    }
    return this.k(file.resource, targetFileWriter, operation, token);
  }
  async m(folder, targetFolder, operation, token) {
    if (folder.children) {
      operation.filesTotal += folder.children.map((child) => child.isFile).length;
      for (const child of folder.children) {
        if (token.isCancellationRequested) {
          return;
        }
        if (child.isFile) {
          await this.l(targetFolder, child, operation, token);
        } else {
          const childFolder = await targetFolder.getDirectoryHandle(child.name, { create: true });
          const resolvedChildFolder = await this.b.resolve(child.resource, { resolveMetadata: true });
          await this.m(resolvedChildFolder, childFolder, operation, token);
        }
      }
    }
  }
  n(name, fileSize, bytesDownloaded, operation) {
    operation.fileBytesDownloaded += bytesDownloaded;
    operation.totalBytesDownloaded += bytesDownloaded;
    const bytesDownloadedPerSecond = operation.totalBytesDownloaded / ((Date.now() - operation.startTime) / 1e3);
    let message;
    if (fileSize < $Sm.MB) {
      if (operation.filesTotal === 1) {
        message = name;
      } else {
        message = localize(7248, null, operation.filesDownloaded, operation.filesTotal, $Sm.formatSize(bytesDownloadedPerSecond));
      }
    } else {
      message = localize(7249, null, name, $Sm.formatSize(operation.fileBytesDownloaded), $Sm.formatSize(fileSize), $Sm.formatSize(bytesDownloadedPerSecond));
    }
    operation.progressScheduler.work({ message });
  }
  async o(explorerItem, progress, cts) {
    progress.report({ message: explorerItem.name });
    let defaultUri;
    const lastUsedDownloadPath = this.g.get(
      $qvb_1.a,
      -1
      /* StorageScope.APPLICATION */
    );
    if (lastUsedDownloadPath) {
      defaultUri = $vh(URI.file(lastUsedDownloadPath), explorerItem.name);
    } else {
      defaultUri = $vh(explorerItem.isDirectory ? await this.f.defaultFolderPath(Schemas.file) : await this.f.defaultFilePath(Schemas.file), explorerItem.name);
    }
    const destination = await this.f.showSaveDialog({
      availableFileSystems: [Schemas.file],
      saveLabel: $7t(localize(7250, null)),
      title: localize(7251, null),
      defaultUri
    });
    if (destination) {
      this.g.store(
        $qvb_1.a,
        $uh(destination).fsPath,
        -1,
        1
        /* StorageTarget.MACHINE */
      );
      await this.c.applyBulkEdit([new $K_(explorerItem.resource, destination, { overwrite: true, copy: true })], {
        undoLabel: localize(7252, null, explorerItem.name),
        progressLabel: localize(7253, null, explorerItem.name),
        progressLocation: 10
        /* ProgressLocation.Window */
      });
    } else {
      cts.cancel();
    }
  }
};
$qvb = $qvb_1 = __decorate([
  __param(0, $km),
  __param(1, $kvb),
  __param(2, $TJ),
  __param(3, $wn),
  __param(4, $1v),
  __param(5, $jv)
], $qvb);
function $rvb(name) {
  return {
    message: localize(7254, null, name),
    detail: localize(7255, null),
    primaryButton: localize(7256, null),
    type: "warning"
  };
}
function $svb(files) {
  if (files.length > 1) {
    return {
      message: localize(7257, null, files.length),
      detail: $2v(files) + "\n" + localize(7258, null),
      primaryButton: localize(7259, null),
      type: "warning"
    };
  }
  return $rvb($sh(files[0]));
}

// out-build/vs/workbench/services/panecomposite/browser/panecomposite.js
var $uqb = $Qk("paneCompositePartService");

// out-build/vs/workbench/contrib/files/browser/fileActions.js
var $tvb = "explorer.newFile";
var $uvb = localize2(7194, "New File...");
var $vvb = "explorer.newFolder";
var $wvb = localize2(7195, "New Folder...");
var $xvb = localize(7124, null);
var $yvb = localize(7125, null);
var $zvb = localize(7126, null);
var $Avb = localize(7127, null);
var $Bvb = new $nn("fileCopied", false);
var $Cvb = "explorer.download";
var $Dvb = localize(7128, null);
var $Evb = "explorer.upload";
var $Fvb = localize(7129, null);
var CONFIRM_DELETE_SETTING_KEY = "explorer.confirmDelete";
var MAX_UNDO_FILE_SIZE = 5e6;
function onError(notificationService, error) {
  if (error.message === "string") {
    error = error.message;
  }
  notificationService.error($1m(error, false));
}
async function refreshIfSeparator(value, explorerService) {
  if (value && (value.indexOf("/") >= 0 || value.indexOf("\\") >= 0)) {
    await explorerService.refresh();
  }
}
async function deleteFiles(explorerService, workingCopyFileService, dialogService, configurationService, elements, useTrash, skipConfirm = false, ignoreIfNotExists = false) {
  let primaryButton;
  if (useTrash) {
    primaryButton = $l ? localize(7130, null) : localize(7131, null);
  } else {
    primaryButton = localize(7132, null);
  }
  const distinctElements = $Eh(elements, (e) => e.resource);
  const dirtyWorkingCopies = /* @__PURE__ */ new Set();
  for (const distinctElement of distinctElements) {
    for (const dirtyWorkingCopy of workingCopyFileService.getDirty(distinctElement.resource)) {
      dirtyWorkingCopies.add(dirtyWorkingCopy);
    }
  }
  let confirmed = true;
  if (dirtyWorkingCopies.size) {
    let message;
    if (distinctElements.length > 1) {
      message = localize(7133, null);
    } else if (distinctElements[0].isDirectory) {
      if (dirtyWorkingCopies.size === 1) {
        message = localize(7134, null, distinctElements[0].name);
      } else {
        message = localize(7135, null, distinctElements[0].name, dirtyWorkingCopies.size);
      }
    } else {
      message = localize(7136, null, distinctElements[0].name);
    }
    const response = await dialogService.confirm({
      type: "warning",
      message,
      detail: localize(7137, null),
      primaryButton
    });
    if (!response.confirmed) {
      confirmed = false;
    } else {
      skipConfirm = true;
    }
  }
  if (!confirmed) {
    return;
  }
  let confirmation;
  const deleteDetail = distinctElements.some((e) => e.isDirectory) ? localize(7138, null) : distinctElements.length > 1 ? localize(7139, null) : localize(7140, null);
  if (skipConfirm || useTrash && configurationService.getValue(CONFIRM_DELETE_SETTING_KEY) === false) {
    confirmation = { confirmed: true };
  } else if (useTrash) {
    let { message, detail: detail2 } = getMoveToTrashMessage(distinctElements);
    detail2 += detail2 ? "\n" : "";
    if ($l) {
      detail2 += distinctElements.length > 1 ? localize(7141, null) : localize(7142, null);
    } else {
      detail2 += distinctElements.length > 1 ? localize(7143, null) : localize(7144, null);
    }
    confirmation = await dialogService.confirm({
      message,
      detail: detail2,
      primaryButton,
      checkbox: {
        label: localize(7145, null)
      }
    });
  } else {
    let { message, detail: detail2 } = getDeleteMessage(distinctElements);
    detail2 += detail2 ? "\n" : "";
    detail2 += deleteDetail;
    confirmation = await dialogService.confirm({
      type: "warning",
      message,
      detail: detail2,
      primaryButton
    });
  }
  if (confirmation.confirmed && confirmation.checkboxChecked === true) {
    await configurationService.updateValue(CONFIRM_DELETE_SETTING_KEY, false);
  }
  if (!confirmation.confirmed) {
    return;
  }
  try {
    const resourceFileEdits = distinctElements.map((e) => new $K_(e.resource, void 0, { recursive: true, folder: e.isDirectory, ignoreIfNotExists, skipTrashBin: !useTrash, maxSize: MAX_UNDO_FILE_SIZE }));
    const options3 = {
      undoLabel: distinctElements.length > 1 ? localize(7146, null, distinctElements.length) : localize(7147, null, distinctElements[0].name),
      progressLabel: distinctElements.length > 1 ? localize(7148, null, distinctElements.length) : localize(7149, null, distinctElements[0].name)
    };
    await explorerService.applyBulkEdit(resourceFileEdits, options3);
  } catch (error) {
    let errorMessage;
    let detailMessage;
    let primaryButton2;
    if (useTrash) {
      errorMessage = $l ? localize(7150, null) : localize(7151, null);
      detailMessage = deleteDetail;
      primaryButton2 = localize(7152, null);
    } else {
      errorMessage = $1m(error, false);
      primaryButton2 = localize(7153, null);
    }
    const res = await dialogService.confirm({
      type: "warning",
      message: errorMessage,
      detail: detailMessage,
      primaryButton: primaryButton2
    });
    if (res.confirmed) {
      if (useTrash) {
        useTrash = false;
      }
      skipConfirm = true;
      ignoreIfNotExists = true;
      return deleteFiles(explorerService, workingCopyFileService, dialogService, configurationService, elements, useTrash, skipConfirm, ignoreIfNotExists);
    }
  }
}
function getMoveToTrashMessage(distinctElements) {
  if (containsBothDirectoryAndFile(distinctElements)) {
    return {
      message: localize(7154, null, distinctElements.length),
      detail: $2v(distinctElements.map((e) => e.resource))
    };
  }
  if (distinctElements.length > 1) {
    if (distinctElements[0].isDirectory) {
      return {
        message: localize(7155, null, distinctElements.length),
        detail: $2v(distinctElements.map((e) => e.resource))
      };
    }
    return {
      message: localize(7156, null, distinctElements.length),
      detail: $2v(distinctElements.map((e) => e.resource))
    };
  }
  if (distinctElements[0].isDirectory && !distinctElements[0].isSymbolicLink) {
    return { message: localize(7157, null, distinctElements[0].name), detail: "" };
  }
  return { message: localize(7158, null, distinctElements[0].name), detail: "" };
}
function getDeleteMessage(distinctElements) {
  if (containsBothDirectoryAndFile(distinctElements)) {
    return {
      message: localize(7159, null, distinctElements.length),
      detail: $2v(distinctElements.map((e) => e.resource))
    };
  }
  if (distinctElements.length > 1) {
    if (distinctElements[0].isDirectory) {
      return {
        message: localize(7160, null, distinctElements.length),
        detail: $2v(distinctElements.map((e) => e.resource))
      };
    }
    return {
      message: localize(7161, null, distinctElements.length),
      detail: $2v(distinctElements.map((e) => e.resource))
    };
  }
  if (distinctElements[0].isDirectory) {
    return { message: localize(7162, null, distinctElements[0].name), detail: "" };
  }
  return { message: localize(7163, null, distinctElements[0].name), detail: "" };
}
function containsBothDirectoryAndFile(distinctElements) {
  const directory = distinctElements.find((element) => element.isDirectory);
  const file = distinctElements.find((element) => !element.isDirectory);
  return !!directory && !!file;
}
async function $Gvb(explorerService, fileService, dialogService, targetFolder, fileToPaste, incrementalNaming) {
  let name = typeof fileToPaste.resource === "string" ? fileToPaste.resource : $rh(fileToPaste.resource);
  let candidate = $vh(targetFolder.resource, name);
  if (incrementalNaming === "disabled") {
    const canOverwrite = await askForOverwrite(fileService, dialogService, candidate);
    if (!canOverwrite) {
      return;
    }
  }
  while (!fileToPaste.allowOverwrite) {
    if (!explorerService.findClosest(candidate)) {
      break;
    }
    if (incrementalNaming !== "disabled") {
      name = $Hvb(name, !!fileToPaste.isDirectory, incrementalNaming);
    }
    candidate = $vh(targetFolder.resource, name);
  }
  return candidate;
}
function $Hvb(name, isFolder, incrementalNaming) {
  if (incrementalNaming === "simple") {
    let namePrefix = name;
    let extSuffix = "";
    if (!isFolder) {
      extSuffix = $sc(name);
      namePrefix = $rc(name, extSuffix);
    }
    const suffixRegex = /^(.+ copy)( \d+)?$/;
    if (suffixRegex.test(namePrefix)) {
      return namePrefix.replace(suffixRegex, (match, g1, g2) => {
        const number = g2 ? parseInt(g2) : 1;
        return number === 0 ? `${g1}` : number < 1073741824 ? `${g1} ${number + 1}` : `${g1}${g2} copy`;
      }) + extSuffix;
    }
    return `${namePrefix} copy${extSuffix}`;
  }
  const separators = "[\\.\\-_]";
  const maxNumber = 1073741824;
  const suffixFileRegex = RegExp("(.*" + separators + ")(\\d+)(\\..*)$");
  if (!isFolder && name.match(suffixFileRegex)) {
    return name.replace(suffixFileRegex, (match, g1, g2, g3) => {
      const number = parseInt(g2);
      return number < maxNumber ? g1 + String(number + 1).padStart(g2.length, "0") + g3 : `${g1}${g2}.1${g3}`;
    });
  }
  const prefixFileRegex = RegExp("(\\d+)(" + separators + ".*)(\\..*)$");
  if (!isFolder && name.match(prefixFileRegex)) {
    return name.replace(prefixFileRegex, (match, g1, g2, g3) => {
      const number = parseInt(g1);
      return number < maxNumber ? String(number + 1).padStart(g1.length, "0") + g2 + g3 : `${g1}${g2}.1${g3}`;
    });
  }
  const prefixFileNoNameRegex = RegExp("(\\d+)(\\..*)$");
  if (!isFolder && name.match(prefixFileNoNameRegex)) {
    return name.replace(prefixFileNoNameRegex, (match, g1, g2) => {
      const number = parseInt(g1);
      return number < maxNumber ? String(number + 1).padStart(g1.length, "0") + g2 : `${g1}.1${g2}`;
    });
  }
  const lastIndexOfDot = name.lastIndexOf(".");
  if (!isFolder && lastIndexOfDot >= 0) {
    return `${name.substr(0, lastIndexOfDot)}.1${name.substr(lastIndexOfDot)}`;
  }
  const noNameNoExtensionRegex = RegExp("(\\d+)$");
  if (!isFolder && lastIndexOfDot === -1 && name.match(noNameNoExtensionRegex)) {
    return name.replace(noNameNoExtensionRegex, (match, g1) => {
      const number = parseInt(g1);
      return number < maxNumber ? String(number + 1).padStart(g1.length, "0") : `${g1}.1`;
    });
  }
  const noExtensionRegex = RegExp("(.*)(\\d*)$");
  if (!isFolder && lastIndexOfDot === -1 && name.match(noExtensionRegex)) {
    return name.replace(noExtensionRegex, (match, g1, g2) => {
      let number = parseInt(g2);
      if (isNaN(number)) {
        number = 0;
      }
      return number < maxNumber ? g1 + String(number + 1).padStart(g2.length, "0") : `${g1}${g2}.1`;
    });
  }
  if (isFolder && name.match(/(\d+)$/)) {
    return name.replace(/(\d+)$/, (match, ...groups) => {
      const number = parseInt(groups[0]);
      return number < maxNumber ? String(number + 1).padStart(groups[0].length, "0") : `${groups[0]}.1`;
    });
  }
  if (isFolder && name.match(/^(\d+)/)) {
    return name.replace(/^(\d+)(.*)$/, (match, ...groups) => {
      const number = parseInt(groups[0]);
      return number < maxNumber ? String(number + 1).padStart(groups[0].length, "0") + groups[1] : `${groups[0]}${groups[1]}.1`;
    });
  }
  return `${name}.1`;
}
async function askForOverwrite(fileService, dialogService, targetResource) {
  const exists = await fileService.exists(targetResource);
  if (!exists) {
    return true;
  }
  const { confirmed } = await dialogService.confirm({
    type: Severity2.Warning,
    message: localize(7164, null, $rc(targetResource.path)),
    primaryButton: localize(7165, null)
  });
  return confirmed;
}
var $Ivb = class _$Ivb extends $gJ {
  static {
    this.ID = "workbench.files.action.compareFileWith";
  }
  static {
    this.LABEL = localize2(7196, "Compare Active File With...");
  }
  constructor() {
    super({
      id: _$Ivb.ID,
      title: _$Ivb.LABEL,
      f1: true,
      category: $qn.File,
      precondition: $Dpb,
      metadata: {
        description: localize2(7197, "Opens a picker to select a file to diff with the active editor.")
      }
    });
  }
  async run(accessor) {
    const editorService = accessor.get($mJ);
    const textModelService = accessor.get($oG);
    const quickInputService = accessor.get($1M);
    const activeInput = editorService.activeEditor;
    const activeResource = $mL.getOriginalUri(activeInput);
    if (activeResource && textModelService.canHandleResource(activeResource)) {
      const picks = await quickInputService.quickAccess.pick("", { itemActivation: ItemActivation.SECOND });
      if (picks?.length === 1) {
        const resource = picks[0].resource;
        if (URI.isUri(resource) && textModelService.canHandleResource(resource)) {
          editorService.openEditor({
            original: { resource: activeResource },
            modified: { resource },
            options: { pinned: true }
          });
        }
      }
    }
  }
};
var $Jvb = class _$Jvb extends $gJ {
  static {
    this.ID = "workbench.action.toggleAutoSave";
  }
  constructor() {
    super({
      id: _$Jvb.ID,
      title: localize2(7198, "Toggle Auto Save"),
      f1: true,
      category: $qn.File,
      metadata: { description: localize2(7199, "Toggle the ability to save files automatically after typing") }
    });
  }
  run(accessor) {
    const filesConfigurationService = accessor.get($4J);
    return filesConfigurationService.toggleAutoSave();
  }
};
var BaseSaveAllAction = class BaseSaveAllAction2 extends $Um {
  constructor(id2, label3, b, c, f) {
    super(id2, label3);
    this.b = b;
    this.c = c;
    this.f = f;
    this.a = this.f.hasDirty;
    this.enabled = this.a;
    this.h();
  }
  h() {
    this.B(this.f.onDidChangeDirty((workingCopy) => this.r(workingCopy)));
  }
  r(workingCopy) {
    const hasDirty = workingCopy.isDirty() || this.f.hasDirty;
    if (this.a !== hasDirty) {
      this.enabled = hasDirty;
      this.a = this.enabled;
    }
  }
  async run(context) {
    try {
      await this.g(context);
    } catch (error) {
      onError(this.c, error);
    }
  }
};
BaseSaveAllAction = __decorate([
  __param(2, $sn),
  __param(3, $PJ),
  __param(4, $XI)
], BaseSaveAllAction);
var $Kvb = class extends BaseSaveAllAction {
  static {
    this.ID = "workbench.files.action.saveAllInGroup";
  }
  static {
    this.LABEL = localize(7166, null);
  }
  get class() {
    return "explorer-action " + ThemeIcon.asClassName($6l.saveAll);
  }
  g(context) {
    return this.b.executeCommand($Ktb, {}, context);
  }
};
var $Lvb = class $Lvb2 extends $Um {
  static {
    this.ID = "workbench.files.action.closeGroup";
  }
  static {
    this.LABEL = localize(7167, null);
  }
  constructor(id2, label3, a) {
    super(id2, label3, ThemeIcon.asClassName($6l.closeAll));
    this.a = a;
  }
  run(context) {
    return this.a.executeCommand($vub, {}, context);
  }
};
$Lvb = __decorate([
  __param(2, $sn)
], $Lvb);
var $Mvb = class _$Mvb extends $gJ {
  static {
    this.ID = "workbench.files.action.focusFilesExplorer";
  }
  static {
    this.LABEL = localize2(7200, "Focus on Files Explorer");
  }
  constructor() {
    super({
      id: _$Mvb.ID,
      title: _$Mvb.LABEL,
      f1: true,
      category: $qn.File,
      metadata: {
        description: localize2(7201, "Moves focus to the file explorer view container.")
      }
    });
  }
  async run(accessor) {
    const paneCompositeService = accessor.get($uqb);
    await paneCompositeService.openPaneComposite($3sb, 0, true);
  }
};
var $Nvb = class _$Nvb extends $gJ {
  static {
    this.ID = "workbench.files.action.showActiveFileInExplorer";
  }
  static {
    this.LABEL = localize2(7202, "Reveal Active File in Explorer View");
  }
  constructor() {
    super({
      id: _$Nvb.ID,
      title: _$Nvb.LABEL,
      f1: true,
      category: $qn.File,
      metadata: {
        description: localize2(7203, "Reveals and selects the active file within the explorer view.")
      }
    });
  }
  async run(accessor) {
    const commandService = accessor.get($sn);
    const editorService = accessor.get($mJ);
    const resource = $mL.getOriginalUri(editorService.activeEditor, { supportSideBySide: SideBySideEditor.PRIMARY });
    if (resource) {
      commandService.executeCommand($stb, resource);
    }
  }
};
var $Ovb = class _$Ovb extends $gJ {
  static {
    this.ID = "workbench.action.files.showOpenedFileInNewWindow";
  }
  static {
    this.LABEL = localize2(7204, "Open Active File in New Empty Workspace");
  }
  constructor() {
    super({
      id: _$Ovb.ID,
      title: _$Ovb.LABEL,
      f1: true,
      category: $qn.File,
      precondition: $ipb,
      metadata: {
        description: localize2(7205, "Opens the active file in a new window with no folders open.")
      }
    });
  }
  async run(accessor) {
    const editorService = accessor.get($mJ);
    const hostService = accessor.get($S4);
    const dialogService = accessor.get($Yv);
    const fileService = accessor.get($km);
    const fileResource = $mL.getOriginalUri(editorService.activeEditor, { supportSideBySide: SideBySideEditor.PRIMARY });
    if (fileResource) {
      if (fileService.hasProvider(fileResource)) {
        hostService.openWindow([{ fileUri: fileResource }], { forceNewWindow: true });
      } else {
        dialogService.error(localize(7168, null));
      }
    }
  }
};
function $Pvb(pathService, item, name, os) {
  name = getWellFormedFileName(name);
  if (!name || name.length === 0 || /^\s+$/.test(name)) {
    return {
      content: localize(7169, null),
      severity: Severity2.Error
    };
  }
  if (name[0] === "/" || name[0] === "\\") {
    return {
      content: localize(7170, null),
      severity: Severity2.Error
    };
  }
  const names = $Mb(name.split(/[\\/]/));
  const parent = item.parent;
  if (name !== item.name) {
    const child = parent?.getChild(name);
    if (child && child !== item) {
      return {
        content: localize(7171, null, name),
        severity: Severity2.Error
      };
    }
  }
  if (names.some((folderName) => !pathService.hasValidBasename(item.resource, os, folderName))) {
    const escapedName = name.replace(/\*/g, "\\*");
    return {
      content: localize(7172, null, trimLongName(escapedName)),
      severity: Severity2.Error
    };
  }
  if (names.some((name2) => /^\s|\s$/.test(name2))) {
    return {
      content: localize(7173, null),
      severity: Severity2.Warning
    };
  }
  return null;
}
function trimLongName(name) {
  if (name?.length > 255) {
    return `${name.substr(0, 255)}...`;
  }
  return name;
}
function getWellFormedFileName(filename) {
  if (!filename) {
    return filename;
  }
  filename = $Ef(filename, "	");
  filename = $Gf(filename, "/");
  filename = $Gf(filename, "\\");
  return filename;
}
var $Qvb = class _$Qvb extends $gJ {
  static {
    this.ID = "workbench.files.action.compareNewUntitledTextFiles";
  }
  static {
    this.LABEL = localize2(7206, "Compare New Untitled Text Files");
  }
  constructor() {
    super({
      id: _$Qvb.ID,
      title: _$Qvb.LABEL,
      f1: true,
      category: $qn.File,
      metadata: {
        description: localize2(7207, "Opens a new diff editor with two untitled files.")
      }
    });
  }
  async run(accessor) {
    const editorService = accessor.get($mJ);
    await editorService.openEditor({
      original: { resource: void 0 },
      modified: { resource: void 0 },
      options: { pinned: true }
    });
  }
};
var $Rvb = class _$Rvb extends $gJ {
  static {
    this.ID = "workbench.files.action.compareWithClipboard";
  }
  static {
    this.LABEL = localize2(7208, "Compare Active File with Clipboard");
  }
  static {
    this.b = 0;
  }
  constructor() {
    super({
      id: _$Rvb.ID,
      title: _$Rvb.LABEL,
      f1: true,
      category: $qn.File,
      keybinding: {
        primary: $$e(
          2048 | 41,
          33
          /* KeyCode.KeyC */
        ),
        weight: 200
        /* KeybindingWeight.WorkbenchContrib */
      },
      metadata: {
        description: localize2(7209, "Opens a new diff editor to compare the active file with the contents of the clipboard.")
      }
    });
  }
  async run(accessor) {
    const editorService = accessor.get($mJ);
    const instantiationService = accessor.get($Pk);
    const textModelService = accessor.get($oG);
    const fileService = accessor.get($km);
    const resource = $mL.getOriginalUri(editorService.activeEditor, { supportSideBySide: SideBySideEditor.PRIMARY });
    const scheme = `clipboardCompare${_$Rvb.b++}`;
    if (resource && (fileService.hasProvider(resource) || resource.scheme === Schemas.untitled)) {
      if (!this.a) {
        const provider = instantiationService.createInstance(ClipboardContentProvider);
        this.a = textModelService.registerTextModelContentProvider(scheme, provider);
      }
      const name = $sh(resource);
      const editorLabel = localize(7174, null, name);
      await editorService.openEditor({
        original: { resource: resource.with({ scheme }) },
        modified: { resource },
        label: editorLabel,
        options: { pinned: true }
      }).finally(() => {
        $Xc(this.a);
        this.a = void 0;
      });
    }
  }
  dispose() {
    $Xc(this.a);
    this.a = void 0;
  }
};
var ClipboardContentProvider = class ClipboardContentProvider2 {
  constructor(a, b, c) {
    this.a = a;
    this.b = b;
    this.c = c;
  }
  async provideTextContent(resource) {
    const text2 = await this.a.readText();
    const model = this.c.createModel(text2, this.b.createByFilepathOrFirstLine(resource), resource);
    return model;
  }
};
ClipboardContentProvider = __decorate([
  __param(0, $30),
  __param(1, $1E),
  __param(2, $sG)
], ClipboardContentProvider);
function onErrorWithRetry(notificationService, error, retry) {
  notificationService.prompt(Severity2.Error, $1m(error, false), [{
    label: localize(7175, null),
    run: () => retry()
  }]);
}
async function openExplorerAndCreate(accessor, isFolder) {
  const explorerService = accessor.get($kvb);
  const fileService = accessor.get($km);
  const configService = accessor.get($kl);
  const filesConfigService = accessor.get($4J);
  const editorService = accessor.get($mJ);
  const viewsService = accessor.get($uob);
  const notificationService = accessor.get($PJ);
  const remoteAgentService = accessor.get($RL);
  const commandService = accessor.get($sn);
  const pathService = accessor.get($aT);
  const wasHidden = !viewsService.isViewVisible($4sb);
  const view = await viewsService.openView($4sb, true);
  if (wasHidden) {
    await $Wh(500);
  }
  if (!view) {
    if (isFolder) {
      throw new Error("Open a folder or workspace first.");
    }
    return commandService.executeCommand($Xtb);
  }
  const stats = explorerService.getContext(false);
  const stat = stats.length > 0 ? stats[0] : void 0;
  let folder;
  if (stat) {
    folder = stat.isDirectory ? stat : stat.parent || explorerService.roots[0];
  } else {
    folder = explorerService.roots[0];
  }
  if (folder.isReadonly) {
    throw new Error("Parent folder is readonly.");
  }
  const newStat = new $jvb(fileService, configService, filesConfigService, folder, isFolder);
  folder.addChild(newStat);
  const onSuccess = async (value) => {
    try {
      const resourceToCreate = $vh(folder.resource, value);
      if (value.endsWith("/")) {
        isFolder = true;
      }
      await explorerService.applyBulkEdit([new $K_(void 0, resourceToCreate, { folder: isFolder })], {
        undoLabel: localize(7176, null, value),
        progressLabel: localize(7177, null, value),
        confirmBeforeUndo: true
      });
      await refreshIfSeparator(value, explorerService);
      if (isFolder) {
        await explorerService.select(resourceToCreate, true);
      } else {
        await editorService.openEditor({ resource: resourceToCreate, options: { pinned: true } });
      }
    } catch (error) {
      onErrorWithRetry(notificationService, error, () => onSuccess(value));
    }
  };
  const os = (await remoteAgentService.getEnvironment())?.os ?? OS;
  await explorerService.setEditable(newStat, {
    validationMessage: (value) => $Pvb(pathService, newStat, value, os),
    onFinish: async (value, success) => {
      folder.removeChild(newStat);
      await explorerService.setEditable(newStat, null);
      if (success) {
        onSuccess(value);
      }
    }
  });
}
$tn.registerCommand({
  id: $tvb,
  handler: async (accessor) => {
    await openExplorerAndCreate(accessor, false);
  }
});
$tn.registerCommand({
  id: $vvb,
  handler: async (accessor) => {
    await openExplorerAndCreate(accessor, true);
  }
});
var $Svb = async (accessor) => {
  const explorerService = accessor.get($kvb);
  const notificationService = accessor.get($PJ);
  const remoteAgentService = accessor.get($RL);
  const pathService = accessor.get($aT);
  const configurationService = accessor.get($kl);
  const stats = explorerService.getContext(false);
  const stat = stats.length > 0 ? stats[0] : void 0;
  if (!stat) {
    return;
  }
  const os = (await remoteAgentService.getEnvironment())?.os ?? OS;
  await explorerService.setEditable(stat, {
    validationMessage: (value) => $Pvb(pathService, stat, value, os),
    onFinish: async (value, success) => {
      if (success) {
        const parentResource = stat.parent.resource;
        const targetResource = $vh(parentResource, value);
        if (stat.resource.toString() !== targetResource.toString()) {
          try {
            await explorerService.applyBulkEdit([new $K_(stat.resource, targetResource)], {
              confirmBeforeUndo: configurationService.getValue().explorer.confirmUndo === "verbose",
              undoLabel: localize(7178, null, stat.name, value),
              progressLabel: localize(7179, null, stat.name, value)
            });
            await refreshIfSeparator(value, explorerService);
          } catch (e) {
            notificationService.error(e);
          }
        }
      }
      await explorerService.setEditable(stat, null);
    }
  });
};
var $Tvb = async (accessor) => {
  const explorerService = accessor.get($kvb);
  const stats = explorerService.getContext(true).filter((s) => !s.isRoot);
  if (stats.length) {
    await deleteFiles(accessor.get($kvb), accessor.get($aK), accessor.get($Yv), accessor.get($kl), stats, true);
  }
};
var $Uvb = async (accessor) => {
  const explorerService = accessor.get($kvb);
  const stats = explorerService.getContext(true).filter((s) => !s.isRoot);
  if (stats.length) {
    await deleteFiles(accessor.get($kvb), accessor.get($aK), accessor.get($Yv), accessor.get($kl), stats, false);
  }
};
var pasteShouldMove = false;
var $Vvb = async (accessor) => {
  const explorerService = accessor.get($kvb);
  const stats = explorerService.getContext(true);
  if (stats.length > 0) {
    await explorerService.setToCopy(stats, false);
    pasteShouldMove = false;
  }
};
var $Wvb = async (accessor) => {
  const explorerService = accessor.get($kvb);
  const stats = explorerService.getContext(true);
  if (stats.length > 0) {
    await explorerService.setToCopy(stats, true);
    pasteShouldMove = true;
  }
};
var downloadFileHandler = async (accessor) => {
  const explorerService = accessor.get($kvb);
  const notificationService = accessor.get($PJ);
  const instantiationService = accessor.get($Pk);
  const context = explorerService.getContext(true);
  const explorerItems = context.length ? context : explorerService.roots;
  const downloadHandler = instantiationService.createInstance($qvb);
  try {
    await downloadHandler.download(explorerItems);
  } catch (error) {
    notificationService.error(error);
    throw error;
  }
};
$tn.registerCommand({
  id: $Cvb,
  handler: downloadFileHandler
});
var uploadFileHandler = async (accessor) => {
  const explorerService = accessor.get($kvb);
  const notificationService = accessor.get($PJ);
  const instantiationService = accessor.get($Pk);
  const context = explorerService.getContext(false);
  const element = context.length ? context[0] : explorerService.roots[0];
  try {
    const files = await $sk();
    if (files) {
      const browserUpload = instantiationService.createInstance($ovb);
      await browserUpload.upload(element, files);
    }
  } catch (error) {
    notificationService.error(error);
    throw error;
  }
};
$tn.registerCommand({
  id: $Evb,
  handler: uploadFileHandler
});
var $Xvb = async (accessor, fileList) => {
  const clipboardService = accessor.get($30);
  const explorerService = accessor.get($kvb);
  const fileService = accessor.get($km);
  const notificationService = accessor.get($PJ);
  const editorService = accessor.get($mJ);
  const configurationService = accessor.get($kl);
  const uriIdentityService = accessor.get($vl);
  const dialogService = accessor.get($Yv);
  const hostService = accessor.get($S4);
  const context = explorerService.getContext(false);
  const hasNativeFilesToPaste = fileList && fileList.length > 0;
  const confirmPasteNative = hasNativeFilesToPaste && configurationService.getValue("explorer.confirmPasteNative");
  const toPaste = await getFilesToPaste(fileList, clipboardService, hostService);
  if (confirmPasteNative && toPaste.files.length >= 1) {
    const message = toPaste.files.length > 1 ? localize(7180, null, toPaste.files.length) : localize(7181, null, $rc(toPaste.type === "paths" ? toPaste.files[0].fsPath : toPaste.files[0].name));
    const detail2 = toPaste.files.length > 1 ? $2v(toPaste.files.map((item) => {
      if (URI.isUri(item)) {
        return item.fsPath;
      }
      if (toPaste.type === "paths") {
        const path = $E_(item);
        if (path) {
          return path;
        }
      }
      return item.name;
    })) : void 0;
    const confirmation = await dialogService.confirm({
      message,
      detail: detail2,
      checkbox: {
        label: localize(7182, null)
      },
      primaryButton: localize(7183, null)
    });
    if (!confirmation.confirmed) {
      return;
    }
    if (confirmation.checkboxChecked === true) {
      await configurationService.updateValue("explorer.confirmPasteNative", false);
    }
  }
  const element = context.length ? context[0] : explorerService.roots[0];
  const incrementalNaming = configurationService.getValue().explorer.incrementalNaming;
  const editableItem = explorerService.getEditable();
  if (editableItem) {
    return;
  }
  try {
    let targets = [];
    if (toPaste.type === "paths") {
      const sourceTargetPairs = $Mb(await Promise.all(toPaste.files.map(async (fileToPaste) => {
        if (element.resource.toString() !== fileToPaste.toString() && $ph(element.resource, fileToPaste)) {
          throw new Error(localize(7184, null));
        }
        const fileToPasteStat = await fileService.stat(fileToPaste);
        let target;
        if (uriIdentityService.extUri.isEqual(element.resource, fileToPaste)) {
          target = element.parent;
        } else {
          target = element.isDirectory ? element : element.parent;
        }
        const targetFile = await $Gvb(explorerService, fileService, dialogService, target, { resource: fileToPaste, isDirectory: fileToPasteStat.isDirectory, allowOverwrite: pasteShouldMove || incrementalNaming === "disabled" }, incrementalNaming);
        if (!targetFile) {
          return void 0;
        }
        return { source: fileToPaste, target: targetFile };
      })));
      if (sourceTargetPairs.length >= 1) {
        if (pasteShouldMove) {
          const resourceFileEdits = sourceTargetPairs.map((pair) => new $K_(pair.source, pair.target, { overwrite: incrementalNaming === "disabled" }));
          const options3 = {
            confirmBeforeUndo: configurationService.getValue().explorer.confirmUndo === "verbose",
            progressLabel: sourceTargetPairs.length > 1 ? localize(7185, null, sourceTargetPairs.length) : localize(7186, null, $rh(sourceTargetPairs[0].target)),
            undoLabel: sourceTargetPairs.length > 1 ? localize(7187, null, sourceTargetPairs.length) : localize(7188, null, $rh(sourceTargetPairs[0].target))
          };
          await explorerService.applyBulkEdit(resourceFileEdits, options3);
        } else {
          const resourceFileEdits = sourceTargetPairs.map((pair) => new $K_(pair.source, pair.target, { copy: true, overwrite: incrementalNaming === "disabled" }));
          await applyCopyResourceEdit(sourceTargetPairs.map((pair) => pair.target), resourceFileEdits);
        }
      }
      targets = sourceTargetPairs.map((pair) => pair.target);
    } else {
      const targetAndEdits = $Mb(await Promise.all(toPaste.files.map(async (file) => {
        const target = element.isDirectory ? element : element.parent;
        const targetFile = await $Gvb(explorerService, fileService, dialogService, target, { resource: file.name, isDirectory: false, allowOverwrite: pasteShouldMove || incrementalNaming === "disabled" }, incrementalNaming);
        if (!targetFile) {
          return;
        }
        return {
          target: targetFile,
          edit: new $K_(void 0, targetFile, {
            overwrite: incrementalNaming === "disabled",
            contents: (async () => $Ci.wrap(new Uint8Array(await file.arrayBuffer())))()
          })
        };
      })));
      await applyCopyResourceEdit(targetAndEdits.map((pair) => pair.target), targetAndEdits.map((pair) => pair.edit));
      targets = targetAndEdits.map((pair) => pair.target);
    }
    if (targets.length) {
      const firstTarget = targets[0];
      await explorerService.select(firstTarget);
      if (targets.length === 1) {
        const item = explorerService.findClosest(firstTarget);
        if (item && !item.isDirectory) {
          await editorService.openEditor({ resource: item.resource, options: { pinned: true, preserveFocus: true } });
        }
      }
    }
  } catch (e) {
    onError(notificationService, new Error(localize(7189, null, $qb(e))));
  } finally {
    if (pasteShouldMove) {
      await explorerService.setToCopy([], false);
      pasteShouldMove = false;
    }
  }
  async function applyCopyResourceEdit(targets, resourceFileEdits) {
    const undoLevel = configurationService.getValue().explorer.confirmUndo;
    const options3 = {
      confirmBeforeUndo: undoLevel === "default" || undoLevel === "verbose",
      progressLabel: targets.length > 1 ? localize(7190, null, targets.length) : localize(7191, null, $rh(targets[0])),
      undoLabel: targets.length > 1 ? localize(7192, null, targets.length) : localize(7193, null, $rh(targets[0]))
    };
    await explorerService.applyBulkEdit(resourceFileEdits, options3);
  }
};
async function getFilesToPaste(fileList, clipboardService, hostService) {
  if (fileList && fileList.length > 0) {
    const resources = [...fileList].map((file) => $E_(file)).filter((filePath) => !!filePath && $mc(filePath)).map((filePath) => URI.file(filePath));
    if (resources.length) {
      return { type: "paths", files: resources };
    }
    return { type: "data", files: [...fileList].filter((file) => !$E_(file)) };
  } else {
    return { type: "paths", files: $Eh(await clipboardService.readResources(), (resource) => resource) };
  }
}
var $Yvb = async (accessor) => {
  const editorService = accessor.get($mJ);
  const explorerService = accessor.get($kvb);
  const stats = explorerService.getContext(true);
  await editorService.openEditors(stats.filter((s) => !s.isDirectory).map((s) => ({
    resource: s.resource,
    options: { preserveFocus: true }
  })));
};
var BaseSetActiveEditorReadonlyInSession = class extends $gJ {
  constructor(id2, title, a) {
    super({
      id: id2,
      title,
      f1: true,
      category: $qn.File,
      precondition: $Apb
    });
    this.a = a;
  }
  async run(accessor) {
    const editorService = accessor.get($mJ);
    const filesConfigurationService = accessor.get($4J);
    const fileResource = $mL.getOriginalUri(editorService.activeEditor, { supportSideBySide: SideBySideEditor.PRIMARY });
    if (!fileResource) {
      return;
    }
    await filesConfigurationService.updateReadonly(fileResource, this.a);
  }
};
var $Zvb = class _$Zvb extends BaseSetActiveEditorReadonlyInSession {
  static {
    this.ID = "workbench.action.files.setActiveEditorReadonlyInSession";
  }
  static {
    this.LABEL = localize2(7210, "Set Active Editor Read-only in Session");
  }
  constructor() {
    super(_$Zvb.ID, _$Zvb.LABEL, true);
  }
};
var $1vb = class _$1vb extends BaseSetActiveEditorReadonlyInSession {
  static {
    this.ID = "workbench.action.files.setActiveEditorWriteableInSession";
  }
  static {
    this.LABEL = localize2(7211, "Set Active Editor Writeable in Session");
  }
  constructor() {
    super(_$1vb.ID, _$1vb.LABEL, false);
  }
};
var $2vb = class _$2vb extends BaseSetActiveEditorReadonlyInSession {
  static {
    this.ID = "workbench.action.files.toggleActiveEditorReadonlyInSession";
  }
  static {
    this.LABEL = localize2(7212, "Toggle Active Editor Read-only in Session");
  }
  constructor() {
    super(_$2vb.ID, _$2vb.LABEL, "toggle");
  }
};
var $3vb = class _$3vb extends BaseSetActiveEditorReadonlyInSession {
  static {
    this.ID = "workbench.action.files.resetActiveEditorReadonlyInSession";
  }
  static {
    this.LABEL = localize2(7213, "Reset Active Editor Read-only in Session");
  }
  constructor() {
    super(_$3vb.ID, _$3vb.LABEL, "reset");
  }
};

// out-build/vs/workbench/common/editor/textResourceEditorModel.js
var $4vb = class $4vb2 extends $xG {
  constructor(resource, languageService, modelService, languageDetectionService, accessibilityService) {
    super(modelService, languageService, languageDetectionService, accessibilityService, resource);
  }
  dispose() {
    if (this.b) {
      this.n.destroyModel(this.b);
    }
    super.dispose();
  }
};
$4vb = __decorate([
  __param(1, $1E),
  __param(2, $sG),
  __param(3, $tG),
  __param(4, $ND)
], $4vb);

// out-build/vs/workbench/common/editor/textResourceEditorInput.js
var $6vb_1;
var $5vb = class $5vb2 extends $rrb {
  constructor(resource, preferredResource, Q, R, labelService, fileService, filesConfigurationService, textResourceConfigurationService, customEditorLabelService) {
    super(resource, preferredResource, labelService, fileService, filesConfigurationService, textResourceConfigurationService, customEditorLabelService);
    this.Q = Q;
    this.R = R;
  }
  save(group2, options3) {
    if (this.resource.scheme !== Schemas.untitled && !this.h.hasProvider(this.resource)) {
      return this.saveAs(group2, options3);
    }
    return this.S(options3, false, group2);
  }
  saveAs(group2, options3) {
    return this.S(options3, true, group2);
  }
  async S(options3, saveAs, group2) {
    let target;
    if (saveAs) {
      target = await this.R.saveAs(this.resource, void 0, { ...options3, suggestedTarget: this.preferredResource });
    } else {
      target = await this.R.save(this.resource, options3);
    }
    if (!target) {
      return void 0;
    }
    return { resource: target };
  }
  async revert(group2, options3) {
    await this.R.revert(this.resource, options3);
  }
};
$5vb = __decorate([
  __param(2, $mJ),
  __param(3, $cK),
  __param(4, $ZI),
  __param(5, $km),
  __param(6, $4J),
  __param(7, $zG),
  __param(8, $qrb)
], $5vb);
var $6vb = class $6vb2 extends $5vb {
  static {
    $6vb_1 = this;
  }
  static {
    this.ID = "workbench.editors.resourceEditorInput";
  }
  get typeId() {
    return $6vb_1.ID;
  }
  get editorId() {
    return $1K.id;
  }
  constructor(resource, X, Y, Z, $149, ab, textFileService, editorService, fileService, labelService, filesConfigurationService, textResourceConfigurationService, customEditorLabelService) {
    super(resource, void 0, editorService, textFileService, labelService, fileService, filesConfigurationService, textResourceConfigurationService, customEditorLabelService);
    this.X = X;
    this.Y = Y;
    this.Z = Z;
    this.$ = $149;
    this.ab = ab;
    this.U = void 0;
    this.W = void 0;
  }
  getName() {
    return this.X || super.getName();
  }
  setName(name) {
    if (this.X !== name) {
      this.X = name;
      this.g.fire();
    }
  }
  getDescription() {
    return this.Y;
  }
  setDescription(description) {
    if (this.Y !== description) {
      this.Y = description;
      this.g.fire();
    }
  }
  setLanguageId(languageId, source) {
    this.setPreferredLanguageId(languageId);
    this.U?.setLanguageId(languageId, source);
  }
  setPreferredLanguageId(languageId) {
    this.Z = languageId;
  }
  setPreferredContents(contents) {
    this.$ = contents;
  }
  async resolve() {
    const preferredContents = this.$;
    const preferredLanguageId = this.Z;
    this.$ = void 0;
    this.Z = void 0;
    if (!this.W) {
      this.W = this.ab.createModelReference(this.resource);
    }
    const ref = await this.W;
    const model = ref.object;
    if (!(model instanceof $4vb)) {
      ref.dispose();
      this.W = void 0;
      throw new Error(`Unexpected model for TextResourceEditorInput: ${this.resource}`);
    }
    this.U = model;
    if (typeof preferredContents === "string" || typeof preferredLanguageId === "string") {
      model.updateTextEditorModel(typeof preferredContents === "string" ? $MI(preferredContents) : void 0, preferredLanguageId);
    }
    return model;
  }
  matches(otherInput) {
    if (this === otherInput) {
      return true;
    }
    if (otherInput instanceof $6vb_1) {
      return $oh(otherInput.resource, this.resource);
    }
    if ($8K(otherInput)) {
      return super.matches(otherInput);
    }
    return false;
  }
  dispose() {
    if (this.W) {
      this.W.then((ref) => ref.dispose());
      this.W = void 0;
    }
    this.U = void 0;
    super.dispose();
  }
};
$6vb = $6vb_1 = __decorate([
  __param(5, $oG),
  __param(6, $cK),
  __param(7, $mJ),
  __param(8, $km),
  __param(9, $ZI),
  __param(10, $4J),
  __param(11, $zG),
  __param(12, $qrb)
], $6vb);

// out-build/vs/workbench/common/editor/binaryEditorModel.js
var $7vb = class $7vb2 extends $rG {
  constructor(resource, g, j) {
    super();
    this.resource = resource;
    this.g = g;
    this.j = j;
    this.a = $YC.binary;
  }
  /**
   * The name of the binary resource.
   */
  getName() {
    return this.g;
  }
  /**
   * The size of the binary resource if known.
   */
  getSize() {
    return this.b;
  }
  /**
   * The mime of the binary resource if known.
   */
  getMime() {
    return this.a;
  }
  /**
   * The etag of the binary resource if known.
   */
  getETag() {
    return this.c;
  }
  async resolve() {
    if (this.j.hasProvider(this.resource)) {
      const stat = await this.j.stat(this.resource);
      this.c = stat.etag;
      if (typeof stat.size === "number") {
        this.b = stat.size;
      }
    }
    return super.resolve();
  }
};
$7vb = __decorate([
  __param(2, $km)
], $7vb);

// out-build/vs/workbench/contrib/files/browser/editors/fileEditorInput.js
var $8vb_1;
var ForceOpenAs;
(function(ForceOpenAs2) {
  ForceOpenAs2[ForceOpenAs2["None"] = 0] = "None";
  ForceOpenAs2[ForceOpenAs2["Text"] = 1] = "Text";
  ForceOpenAs2[ForceOpenAs2["Binary"] = 2] = "Binary";
})(ForceOpenAs || (ForceOpenAs = {}));
var $8vb = $8vb_1 = class $8vb2 extends $5vb {
  get typeId() {
    return $ntb;
  }
  get editorId() {
    return $1K.id;
  }
  get capabilities() {
    let capabilities = 32;
    if (this.$) {
      if (this.$.isReadonly()) {
        capabilities |= 2;
      }
    } else {
      if (this.h.hasProvider(this.resource)) {
        if (this.m.isReadonly(this.resource)) {
          capabilities |= 2;
        }
      } else {
        capabilities |= 4;
      }
    }
    if (!(capabilities & 2)) {
      capabilities |= 128;
    }
    return capabilities;
  }
  constructor(resource, preferredResource, preferredName, preferredDescription, preferredEncoding, preferredLanguageId, preferredContents, cb, textFileService, db, labelService, fileService, filesConfigurationService, editorService, eb, textResourceConfigurationService, customEditorLabelService) {
    super(resource, preferredResource, editorService, textFileService, labelService, fileService, filesConfigurationService, textResourceConfigurationService, customEditorLabelService);
    this.cb = cb;
    this.db = db;
    this.eb = eb;
    this.Z = 0;
    this.$ = void 0;
    this.ab = void 0;
    this.bb = this.B(new $2c());
    this.$ = this.R.files.get(resource);
    if (preferredName) {
      this.setPreferredName(preferredName);
    }
    if (preferredDescription) {
      this.setPreferredDescription(preferredDescription);
    }
    if (preferredEncoding) {
      this.setPreferredEncoding(preferredEncoding);
    }
    if (preferredLanguageId) {
      this.setPreferredLanguageId(preferredLanguageId);
    }
    if (typeof preferredContents === "string") {
      this.setPreferredContents(preferredContents);
    }
    this.B(this.R.files.onDidCreate((model) => this.fb(model)));
    if (this.$) {
      this.gb(this.$);
    }
  }
  fb(model) {
    if ($oh(model.resource, this.resource)) {
      this.$ = model;
      this.gb(model);
    }
  }
  gb(model) {
    this.bb.clear();
    this.bb.add(model.onDidChangeDirty(() => this.f.fire()));
    this.bb.add(model.onDidChangeReadonly(() => this.j.fire()));
    this.bb.add(model.onDidSaveError(() => this.f.fire()));
    this.bb.add(Event2.once(model.onWillDispose)(() => {
      this.bb.clear();
      this.$ = void 0;
    }));
  }
  getName() {
    return this.c || super.getName();
  }
  setPreferredName(name) {
    if (!this.hb()) {
      return;
    }
    if (this.c !== name) {
      this.c = name;
      this.g.fire();
    }
  }
  hb() {
    return this.resource.scheme !== this.eb.defaultUriScheme && this.resource.scheme !== Schemas.vscodeUserData && this.resource.scheme !== Schemas.file && this.resource.scheme !== Schemas.vscodeRemote;
  }
  getPreferredName() {
    return this.c;
  }
  isReadonly() {
    return this.$ ? this.$.isReadonly() : this.m.isReadonly(this.resource);
  }
  getDescription(verbosity) {
    return this.U || super.getDescription(verbosity);
  }
  setPreferredDescription(description) {
    if (!this.hb()) {
      return;
    }
    if (this.U !== description) {
      this.U = description;
      this.g.fire();
    }
  }
  getPreferredDescription() {
    return this.U;
  }
  getTitle(verbosity) {
    let title = super.getTitle(verbosity);
    const preferredTitle = this.ib();
    if (preferredTitle) {
      title = `${preferredTitle} (${title})`;
    }
    return title;
  }
  ib() {
    if (this.c && this.U) {
      return `${this.c} ${this.U}`;
    }
    if (this.c || this.U) {
      return this.c ?? this.U;
    }
    return void 0;
  }
  getEncoding() {
    if (this.$) {
      return this.$.getEncoding();
    }
    return this.W;
  }
  getPreferredEncoding() {
    return this.W;
  }
  async setEncoding(encoding, mode) {
    this.setPreferredEncoding(encoding);
    return this.$?.setEncoding(encoding, mode);
  }
  setPreferredEncoding(encoding) {
    this.W = encoding;
    this.setForceOpenAsText();
  }
  getLanguageId() {
    if (this.$) {
      return this.$.getLanguageId();
    }
    return this.X;
  }
  getPreferredLanguageId() {
    return this.X;
  }
  setLanguageId(languageId, source) {
    this.setPreferredLanguageId(languageId);
    this.$?.setLanguageId(languageId, source);
  }
  setPreferredLanguageId(languageId) {
    this.X = languageId;
    this.setForceOpenAsText();
  }
  setPreferredContents(contents) {
    this.Y = contents;
    this.setForceOpenAsText();
  }
  setForceOpenAsText() {
    this.Z = 1;
  }
  setForceOpenAsBinary() {
    this.Z = 2;
  }
  isDirty() {
    return !!this.$?.isDirty();
  }
  isSaving() {
    if (this.$?.hasState(
      0
      /* TextFileEditorModelState.SAVED */
    ) || this.$?.hasState(
      3
      /* TextFileEditorModelState.CONFLICT */
    ) || this.$?.hasState(
      5
      /* TextFileEditorModelState.ERROR */
    )) {
      return false;
    }
    if (this.m.hasShortAutoSaveDelay(this)) {
      return true;
    }
    return super.isSaving();
  }
  prefersEditorPane(editorPanes) {
    if (this.Z === 2) {
      return editorPanes.find((editorPane) => editorPane.typeId === $otb);
    }
    return editorPanes.find((editorPane) => editorPane.typeId === $mtb);
  }
  resolve(options3) {
    if (this.Z === 2) {
      return this.kb();
    }
    return this.jb(options3);
  }
  async jb(options3) {
    try {
      const preferredContents = this.Y;
      this.Y = void 0;
      await this.R.files.resolve(this.resource, {
        languageId: this.X,
        encoding: this.W,
        contents: typeof preferredContents === "string" ? $MI(preferredContents) : void 0,
        reload: { async: true },
        // trigger a reload of the model if it exists already but do not wait to show the model
        allowBinary: this.Z === 1,
        reason: 1,
        limits: this.P(options3)
      });
      if (!this.ab) {
        this.ab = await this.db.createModelReference(this.resource);
      }
      const model = this.ab.object;
      if (this.isDisposed()) {
        this.lb();
      }
      return model;
    } catch (error) {
      if (error.textFileOperationResult === 0) {
        return this.kb();
      }
      throw error;
    }
  }
  async kb() {
    const model = this.cb.createInstance($7vb, this.preferredResource, this.getName());
    await model.resolve();
    return model;
  }
  isResolved() {
    return !!this.$;
  }
  async rename(group2, target) {
    return {
      editor: {
        resource: target,
        encoding: this.getEncoding(),
        options: {
          viewState: $7K(this, group2, this.Q)
        }
      }
    };
  }
  toUntyped(options3) {
    const untypedInput = {
      resource: this.preferredResource,
      forceFile: true,
      options: {
        override: this.editorId
      }
    };
    if (typeof options3?.preserveViewState === "number") {
      untypedInput.encoding = this.getEncoding();
      untypedInput.languageId = this.getLanguageId();
      untypedInput.contents = (() => {
        const model = this.R.files.get(this.resource);
        if (model?.isDirty() && !model.textEditorModel.isTooLargeForHeapOperation()) {
          return model.textEditorModel.getValue();
        }
        return void 0;
      })();
      untypedInput.options = {
        ...untypedInput.options,
        viewState: $7K(this, options3.preserveViewState, this.Q)
      };
    }
    return untypedInput;
  }
  matches(otherInput) {
    if (this === otherInput) {
      return true;
    }
    if (otherInput instanceof $8vb_1) {
      return $oh(otherInput.resource, this.resource);
    }
    if ($8K(otherInput)) {
      return super.matches(otherInput);
    }
    return false;
  }
  dispose() {
    this.$ = void 0;
    this.lb();
    super.dispose();
  }
  lb() {
    $Xc(this.ab);
    this.ab = void 0;
  }
};
$8vb = $8vb_1 = __decorate([
  __param(7, $Pk),
  __param(8, $cK),
  __param(9, $oG),
  __param(10, $ZI),
  __param(11, $km),
  __param(12, $4J),
  __param(13, $mJ),
  __param(14, $aT),
  __param(15, $zG),
  __param(16, $qrb)
], $8vb);

// out-build/vs/workbench/contrib/files/browser/editors/textFileSaveErrorHandler.js
var $9vb = "saveConflictResolutionContext";
var $0vb = "conflictResolution";
var LEARN_MORE_DIRTY_WRITE_IGNORE_KEY = "learnMoreDirtyWriteError";
var conflictEditorHelp = localize(7050, null);
var $$vb = class $$vb2 extends $3c {
  static {
    this.ID = "workbench.contrib.textFileSaveErrorHandler";
  }
  constructor(f, g, h3, j, textModelService, m, n) {
    super();
    this.f = f;
    this.g = g;
    this.h = h3;
    this.j = j;
    this.m = m;
    this.n = n;
    this.a = new $Ec();
    this.b = new $nn($9vb, false, true).bindTo(this.h);
    this.c = void 0;
    const provider = this.B(m.createInstance($qtb));
    this.B(textModelService.registerTextModelContentProvider($0vb, provider));
    this.g.files.saveErrorHandler = this;
    this.r();
  }
  r() {
    this.B(this.g.files.onDidSave((e) => this.t(e.model.resource)));
    this.B(this.g.files.onDidRevert((model) => this.t(model.resource)));
    this.B(this.j.onDidActiveEditorChange(() => this.s()));
  }
  s() {
    let isActiveEditorSaveConflictResolution = false;
    let activeConflictResolutionResource;
    const activeInput = this.j.activeEditor;
    if (activeInput instanceof $fub) {
      const resource = activeInput.original.resource;
      if (resource?.scheme === $0vb) {
        isActiveEditorSaveConflictResolution = true;
        activeConflictResolutionResource = activeInput.modified.resource;
      }
    }
    this.b.set(isActiveEditorSaveConflictResolution);
    this.c = activeConflictResolutionResource;
  }
  t(resource) {
    const messageHandle = this.a.get(resource);
    if (messageHandle) {
      messageHandle.close();
      this.a.delete(resource);
    }
  }
  onSaveError(error, model, options3) {
    const fileOperationError = error;
    const resource = model.resource;
    let message;
    const primaryActions = [];
    const secondaryActions = [];
    if (fileOperationError.fileOperationResult === 3) {
      if (this.c && $oh(this.c, model.resource)) {
        if (this.n.getBoolean(
          LEARN_MORE_DIRTY_WRITE_IGNORE_KEY,
          -1
          /* StorageScope.APPLICATION */
        )) {
          return;
        }
        message = conflictEditorHelp;
        primaryActions.push(this.m.createInstance(ResolveConflictLearnMoreAction));
        secondaryActions.push(this.m.createInstance(DoNotShowResolveConflictLearnMoreAction));
      } else {
        message = localize(7051, null, $sh(resource));
        primaryActions.push(this.m.createInstance(ResolveSaveConflictAction, model));
        primaryActions.push(this.m.createInstance(SaveModelIgnoreModifiedSinceAction, model, options3));
        secondaryActions.push(this.m.createInstance(ConfigureSaveConflictAction));
      }
    } else {
      const isWriteLocked = fileOperationError.fileOperationResult === 5;
      const triedToUnlock = isWriteLocked && fileOperationError.options?.unlock;
      const isPermissionDenied = fileOperationError.fileOperationResult === 6;
      const canSaveElevated = resource.scheme === Schemas.file;
      if (canSaveElevated && (isPermissionDenied || triedToUnlock)) {
        primaryActions.push(this.m.createInstance(SaveModelElevatedAction, model, options3, !!triedToUnlock));
      } else if (isWriteLocked) {
        primaryActions.push(this.m.createInstance(UnlockModelAction, model, options3));
      } else {
        primaryActions.push(this.m.createInstance(RetrySaveModelAction, model, options3));
      }
      primaryActions.push(this.m.createInstance(SaveModelAsAction, model));
      primaryActions.push(this.m.createInstance(RevertModelAction, model));
      if (isWriteLocked) {
        if (triedToUnlock && canSaveElevated) {
          message = $l ? localize(7052, null, $sh(resource)) : localize(7053, null, $sh(resource));
        } else {
          message = localize(7054, null, $sh(resource));
        }
      } else if (canSaveElevated && isPermissionDenied) {
        message = $l ? localize(7055, null, $sh(resource)) : localize(7056, null, $sh(resource));
      } else {
        message = localize(7057, null, $sh(resource), $1m(error, false));
      }
    }
    const actions = { primary: primaryActions, secondary: secondaryActions };
    const handle2 = this.f.notify({
      id: `${$Xi(model.resource.toString())}`,
      // unique per model (https://github.com/microsoft/vscode/issues/121539)
      severity: Severity2.Error,
      message,
      actions
    });
    Event2.once(handle2.onDidClose)(() => {
      $Xc(primaryActions);
      $Xc(secondaryActions);
    });
    this.a.set(model.resource, handle2);
  }
  dispose() {
    super.dispose();
    this.a.clear();
  }
};
$$vb = __decorate([
  __param(0, $PJ),
  __param(1, $cK),
  __param(2, $on),
  __param(3, $mJ),
  __param(4, $oG),
  __param(5, $Pk),
  __param(6, $jv)
], $$vb);
var pendingResolveSaveConflictMessages = [];
function clearPendingResolveSaveConflictMessages() {
  while (pendingResolveSaveConflictMessages.length > 0) {
    const item = pendingResolveSaveConflictMessages.pop();
    item?.close();
  }
}
var ResolveConflictLearnMoreAction = class ResolveConflictLearnMoreAction2 extends $Um {
  constructor(a) {
    super("workbench.files.action.resolveConflictLearnMore", localize(7058, null));
    this.a = a;
  }
  async run() {
    await this.a.open(URI.parse("https://go.microsoft.com/fwlink/?linkid=868264"));
  }
};
ResolveConflictLearnMoreAction = __decorate([
  __param(0, $O4)
], ResolveConflictLearnMoreAction);
var DoNotShowResolveConflictLearnMoreAction = class DoNotShowResolveConflictLearnMoreAction2 extends $Um {
  constructor(a) {
    super("workbench.files.action.resolveConflictLearnMoreDoNotShowAgain", localize(7059, null));
    this.a = a;
  }
  async run(notification) {
    this.a.store(
      LEARN_MORE_DIRTY_WRITE_IGNORE_KEY,
      true,
      -1,
      0
      /* StorageTarget.USER */
    );
    notification.dispose();
  }
};
DoNotShowResolveConflictLearnMoreAction = __decorate([
  __param(0, $jv)
], DoNotShowResolveConflictLearnMoreAction);
var ResolveSaveConflictAction = class ResolveSaveConflictAction2 extends $Um {
  constructor(a, b, c, f, g) {
    super("workbench.files.action.resolveConflict", localize(7060, null));
    this.a = a;
    this.b = b;
    this.c = c;
    this.f = f;
    this.g = g;
  }
  async run() {
    if (!this.a.isDisposed()) {
      const resource = this.a.resource;
      const name = $sh(resource);
      const editorLabel = localize(7061, null, name, name, this.g.nameLong);
      await $qtb.open(resource, $0vb, editorLabel, this.b, { pinned: true });
      const actions = { primary: [this.f.createInstance(ResolveConflictLearnMoreAction)] };
      const handle2 = this.c.notify({
        id: `${$Xi(resource.toString())}`,
        // unique per model
        severity: Severity2.Info,
        message: conflictEditorHelp,
        actions,
        neverShowAgain: { id: LEARN_MORE_DIRTY_WRITE_IGNORE_KEY, isSecondary: true }
      });
      Event2.once(handle2.onDidClose)(() => $Xc(actions.primary));
      pendingResolveSaveConflictMessages.push(handle2);
    }
  }
};
ResolveSaveConflictAction = __decorate([
  __param(1, $mJ),
  __param(2, $PJ),
  __param(3, $Pk),
  __param(4, $Vu)
], ResolveSaveConflictAction);
var SaveModelElevatedAction = class extends $Um {
  constructor(a, b, c) {
    super("workbench.files.action.saveModelElevated", c ? $l ? localize(7062, null) : localize(7063, null) : $l ? localize(7064, null) : localize(7065, null));
    this.a = a;
    this.b = b;
    this.c = c;
  }
  async run() {
    if (!this.a.isDisposed()) {
      await this.a.save({
        ...this.b,
        writeElevated: true,
        writeUnlock: this.c,
        reason: 1
        /* SaveReason.EXPLICIT */
      });
    }
  }
};
var RetrySaveModelAction = class extends $Um {
  constructor(a, b) {
    super("workbench.files.action.saveModel", localize(7066, null));
    this.a = a;
    this.b = b;
  }
  async run() {
    if (!this.a.isDisposed()) {
      await this.a.save({
        ...this.b,
        reason: 1
        /* SaveReason.EXPLICIT */
      });
    }
  }
};
var RevertModelAction = class extends $Um {
  constructor(a) {
    super("workbench.files.action.revertModel", localize(7067, null));
    this.a = a;
  }
  async run() {
    if (!this.a.isDisposed()) {
      await this.a.revert();
    }
  }
};
var SaveModelAsAction = class SaveModelAsAction2 extends $Um {
  constructor(a, b) {
    super("workbench.files.action.saveModelAs", $Dtb.value);
    this.a = a;
    this.b = b;
  }
  async run() {
    if (!this.a.isDisposed()) {
      const editor = this.c();
      if (editor) {
        await this.b.save(editor, {
          saveAs: true,
          reason: 1
          /* SaveReason.EXPLICIT */
        });
      }
    }
  }
  c() {
    let preferredMatchingEditor;
    const editors = this.b.findEditors(this.a.resource, { supportSideBySide: SideBySideEditor.PRIMARY });
    for (const identifier2 of editors) {
      if (identifier2.editor instanceof $8vb) {
        preferredMatchingEditor = identifier2;
        break;
      } else if (!preferredMatchingEditor) {
        preferredMatchingEditor = identifier2;
      }
    }
    return preferredMatchingEditor;
  }
};
SaveModelAsAction = __decorate([
  __param(1, $mJ)
], SaveModelAsAction);
var UnlockModelAction = class extends $Um {
  constructor(a, b) {
    super("workbench.files.action.unlock", localize(7068, null));
    this.a = a;
    this.b = b;
  }
  async run() {
    if (!this.a.isDisposed()) {
      await this.a.save({
        ...this.b,
        writeUnlock: true,
        reason: 1
        /* SaveReason.EXPLICIT */
      });
    }
  }
};
var SaveModelIgnoreModifiedSinceAction = class extends $Um {
  constructor(a, b) {
    super("workbench.files.action.saveIgnoreModifiedSince", localize(7069, null));
    this.a = a;
    this.b = b;
  }
  async run() {
    if (!this.a.isDisposed()) {
      await this.a.save({
        ...this.b,
        ignoreModifiedSince: true,
        reason: 1
        /* SaveReason.EXPLICIT */
      });
    }
  }
};
var ConfigureSaveConflictAction = class ConfigureSaveConflictAction2 extends $Um {
  constructor(a) {
    super("workbench.files.action.configureSaveConflict", localize(7070, null));
    this.a = a;
  }
  async run() {
    this.a.openSettings({ query: "files.saveConflictResolution" });
  }
};
ConfigureSaveConflictAction = __decorate([
  __param(0, $TK)
], ConfigureSaveConflictAction);
var $_vb = (accessor, resource) => {
  return acceptOrRevertLocalChangesCommand(accessor, resource, true);
};
var $awb = (accessor, resource) => {
  return acceptOrRevertLocalChangesCommand(accessor, resource, false);
};
async function acceptOrRevertLocalChangesCommand(accessor, resource, accept) {
  const editorService = accessor.get($mJ);
  const editorPane = editorService.activeEditorPane;
  if (!editorPane) {
    return;
  }
  const editor = editorPane.input;
  const group2 = editorPane.group;
  clearPendingResolveSaveConflictMessages();
  if (accept) {
    const options3 = {
      ignoreModifiedSince: true,
      reason: 1
      /* SaveReason.EXPLICIT */
    };
    await editorService.save({ editor, groupId: group2.id }, options3);
  } else {
    await editorService.revert({ editor, groupId: group2.id });
  }
  await editorService.openEditor({ resource }, group2);
  return group2.closeEditor(editor);
}

// out-build/vs/base/common/jsonFormatter.js
function $Sw(documentText, range, options3) {
  let initialIndentLevel;
  let formatText;
  let formatTextStart;
  let rangeStart;
  let rangeEnd;
  if (range) {
    rangeStart = range.offset;
    rangeEnd = rangeStart + range.length;
    formatTextStart = rangeStart;
    while (formatTextStart > 0 && !$Vw(documentText, formatTextStart - 1)) {
      formatTextStart--;
    }
    let endOffset = rangeEnd;
    while (endOffset < documentText.length && !$Vw(documentText, endOffset)) {
      endOffset++;
    }
    formatText = documentText.substring(formatTextStart, endOffset);
    initialIndentLevel = computeIndentLevel(formatText, options3);
  } else {
    formatText = documentText;
    initialIndentLevel = 0;
    formatTextStart = 0;
    rangeStart = 0;
    rangeEnd = documentText.length;
  }
  const eol = $Uw(options3, documentText);
  let lineBreak = false;
  let indentLevel = 0;
  let indentValue;
  if (options3.insertSpaces) {
    indentValue = repeat2(" ", options3.tabSize || 4);
  } else {
    indentValue = "	";
  }
  const scanner = $ww(formatText, false);
  let hasError = false;
  function newLineAndIndent() {
    return eol + repeat2(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(text2, startOffset, endOffset) {
    if (!hasError && startOffset < rangeEnd && endOffset > rangeStart && documentText.substring(startOffset, endOffset) !== text2) {
      editOperations.push({ offset: startOffset, length: endOffset - startOffset, content: text2 });
    }
  }
  let firstToken = scanNext();
  if (firstToken !== 17) {
    const firstTokenStart = scanner.getTokenOffset() + formatTextStart;
    const initialIndent = repeat2(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 $Tw(obj, options3) {
  const content = JSON.stringify(obj, void 0, options3.insertSpaces ? options3.tabSize || 4 : "	");
  if (options3.eol !== void 0) {
    return content.replace(/\r\n|\r|\n/g, options3.eol);
  }
  return content;
}
function repeat2(s, count) {
  let result = "";
  for (let i2 = 0; i2 < count; i2++) {
    result += s;
  }
  return result;
}
function computeIndentLevel(content, options3) {
  let i2 = 0;
  let nChars = 0;
  const tabSize = options3.tabSize || 4;
  while (i2 < content.length) {
    const ch = content.charAt(i2);
    if (ch === " ") {
      nChars++;
    } else if (ch === "	") {
      nChars += tabSize;
    } else {
      break;
    }
    i2++;
  }
  return Math.floor(nChars / tabSize);
}
function $Uw(options3, text2) {
  for (let i2 = 0; i2 < text2.length; i2++) {
    const ch = text2.charAt(i2);
    if (ch === "\r") {
      if (i2 + 1 < text2.length && text2.charAt(i2 + 1) === "\n") {
        return "\r\n";
      }
      return "\r";
    } else if (ch === "\n") {
      return "\n";
    }
  }
  return options3 && options3.eol || "\n";
}
function $Vw(text2, offset) {
  return "\r\n".indexOf(text2.charAt(offset)) !== -1;
}

// out-build/vs/base/common/jsonEdit.js
function $Ww(text2, path, formattingOptions) {
  return $Xw(text2, path, void 0, formattingOptions);
}
function $Xw(text2, originalPath, value, formattingOptions, getInsertionIndex) {
  const path = originalPath.slice();
  const errors = [];
  const root = $zw(text2, errors);
  let parent = void 0;
  let lastSegment = void 0;
  while (path.length > 0) {
    lastSegment = path.pop();
    parent = $Aw(root, path);
    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 $Yw(text2, { 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 = $Aw(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 $Yw(text2, { offset: removeBegin, length: removeEnd - removeBegin, content: "" }, formattingOptions);
      } else {
        return $Yw(text2, { 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 edit3;
      if (index > 0) {
        const previous = parent.children[index - 1];
        edit3 = { offset: previous.offset + previous.length, length: 0, content: "," + newProperty };
      } else if (parent.children.length === 0) {
        edit3 = { offset: parent.offset + 1, length: 0, content: newProperty };
      } else {
        edit3 = { offset: parent.offset + 1, length: 0, content: newProperty + "," };
      }
      return $Yw(text2, edit3, formattingOptions);
    }
  } else if (parent.type === "array" && typeof lastSegment === "number" && Array.isArray(parent.children)) {
    if (value !== void 0) {
      const newProperty = `${JSON.stringify(value)}`;
      let edit3;
      if (parent.children.length === 0 || lastSegment === 0) {
        edit3 = { 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];
        edit3 = { offset: previous.offset + previous.length, length: 0, content: "," + newProperty };
      }
      return $Yw(text2, edit3, formattingOptions);
    } else {
      const removalIndex = lastSegment;
      const toRemove = parent.children[removalIndex];
      let edit3;
      if (parent.children.length === 1) {
        edit3 = { 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;
        edit3 = { offset, length: parentEndOffset - 2 - offset, content: "" };
      } else {
        edit3 = { offset: toRemove.offset, length: parent.children[removalIndex + 1].offset - toRemove.offset, content: "" };
      }
      return $Yw(text2, edit3, formattingOptions);
    }
  } else {
    throw new Error(`Can not add ${typeof lastSegment !== "number" ? "index" : "property"} to parent of type ${parent.type}`);
  }
}
function $Yw(text2, edit3, formattingOptions) {
  let newText = $Zw(text2, edit3);
  let begin = edit3.offset;
  let end = edit3.offset + edit3.content.length;
  if (edit3.length === 0 || edit3.content.length === 0) {
    while (begin > 0 && !$Vw(newText, begin - 1)) {
      begin--;
    }
    while (end < newText.length && !$Vw(newText, end)) {
      end++;
    }
  }
  const edits = $Sw(newText, { offset: begin, length: end - begin }, formattingOptions);
  for (let i2 = edits.length - 1; i2 >= 0; i2--) {
    const curr = edits[i2];
    newText = $Zw(newText, curr);
    begin = Math.min(begin, curr.offset);
    end = Math.max(end, curr.offset + curr.length);
    end += curr.content.length - curr.length;
  }
  const editLength = text2.length - (newText.length - end) - begin;
  return [{ offset: begin, length: editLength, content: newText.substring(begin, end) }];
}
function $Zw(text2, edit3) {
  return text2.substring(0, edit3.offset) + edit3.content + text2.substring(edit3.offset + edit3.length);
}
function $1w(text2, edits) {
  const sortedEdits = edits.slice(0).sort((a, b) => {
    const diff3 = a.offset - b.offset;
    if (diff3 === 0) {
      return a.length - b.length;
    }
    return diff3;
  });
  let lastModifiedOffset = text2.length;
  for (let i2 = sortedEdits.length - 1; i2 >= 0; i2--) {
    const e = sortedEdits[i2];
    if (e.offset + e.length <= lastModifiedOffset) {
      text2 = $Zw(text2, e);
    } else {
      throw new Error("Overlapping edit");
    }
    lastModifiedOffset = e.offset;
  }
  return text2;
}

// out-build/vs/platform/workspaces/common/workspaces.js
var $2w = $Qk("workspacesService");
function $3w(curr) {
  return curr.hasOwnProperty("workspace");
}
function $4w(curr) {
  return curr.hasOwnProperty("folderUri");
}
function $5w(curr) {
  return curr.hasOwnProperty("fileUri");
}
function $6w(obj) {
  return isRawFileWorkspaceFolder(obj) || isRawUriWorkspaceFolder(obj);
}
function isRawFileWorkspaceFolder(obj) {
  const candidate = obj;
  return typeof candidate?.path === "string" && (!candidate.name || typeof candidate.name === "string");
}
function isRawUriWorkspaceFolder(obj) {
  const candidate = obj;
  return typeof candidate?.uri === "string" && (!candidate.name || typeof candidate.name === "string");
}
function $7w(folderURI, forceAbsolute, folderName, targetConfigFolderURI, extUri) {
  if (folderURI.scheme !== targetConfigFolderURI.scheme) {
    return { name: folderName, uri: folderURI.toString(true) };
  }
  let folderPath = !forceAbsolute ? extUri.relativePath(targetConfigFolderURI, folderURI) : void 0;
  if (folderPath !== void 0) {
    if (folderPath.length === 0) {
      folderPath = ".";
    } else {
      if ($l) {
        folderPath = massagePathForWindows(folderPath);
      }
    }
  } else {
    if (folderURI.scheme === Schemas.file) {
      folderPath = folderURI.fsPath;
      if ($l) {
        folderPath = massagePathForWindows(folderPath);
      }
    } else if (!extUri.isEqualAuthority(folderURI.authority, targetConfigFolderURI.authority)) {
      return { name: folderName, uri: folderURI.toString(true) };
    } else {
      folderPath = folderURI.path;
    }
  }
  return { name: folderName, path: folderPath };
}
function massagePathForWindows(folderPath) {
  folderPath = $1t(folderPath);
  if (!$Wg(folderPath)) {
    folderPath = $Tg(folderPath);
  }
  return folderPath;
}
function $8w(configuredFolders, workspaceConfigFile, extUri) {
  const result = [];
  const seen = /* @__PURE__ */ new Set();
  const relativeTo = extUri.dirname(workspaceConfigFile);
  for (const configuredFolder of configuredFolders) {
    let uri = void 0;
    if (isRawFileWorkspaceFolder(configuredFolder)) {
      if (configuredFolder.path) {
        uri = extUri.resolvePath(relativeTo, configuredFolder.path);
      }
    } else if (isRawUriWorkspaceFolder(configuredFolder)) {
      try {
        uri = URI.parse(configuredFolder.uri);
        if (uri.path[0] !== $kc.sep) {
          uri = uri.with({ path: $kc.sep + uri.path });
        }
      } catch (e) {
        console.warn(e);
      }
    }
    if (uri) {
      const comparisonKey = extUri.getComparisonKey(uri);
      if (!seen.has(comparisonKey)) {
        seen.add(comparisonKey);
        const name = configuredFolder.name || extUri.basenameOrAuthority(uri);
        result.push(new $$k({ uri, name, index: result.length }, configuredFolder));
      }
    }
  }
  return result;
}
function $9w(rawWorkspaceContents, configPathURI, isFromUntitledWorkspace, targetConfigPathURI, extUri) {
  const storedWorkspace = doParseStoredWorkspace(configPathURI, rawWorkspaceContents);
  const sourceConfigFolder = extUri.dirname(configPathURI);
  const targetConfigFolder = extUri.dirname(targetConfigPathURI);
  const rewrittenFolders = [];
  for (const folder of storedWorkspace.folders) {
    const folderURI = isRawFileWorkspaceFolder(folder) ? extUri.resolvePath(sourceConfigFolder, folder.path) : URI.parse(folder.uri);
    let absolute;
    if (isFromUntitledWorkspace) {
      absolute = false;
    } else {
      absolute = !isRawFileWorkspaceFolder(folder) || $mc(folder.path);
    }
    rewrittenFolders.push($7w(folderURI, absolute, folder.name, targetConfigFolder, extUri));
  }
  const formattingOptions = { insertSpaces: false, tabSize: 4, eol: $n || $m ? "\n" : "\r\n" };
  const edits = $Xw(rawWorkspaceContents, ["folders"], rewrittenFolders, formattingOptions);
  let newContent = $1w(rawWorkspaceContents, edits);
  if ($Ah(storedWorkspace.remoteAuthority, $8v(targetConfigPathURI))) {
    newContent = $1w(newContent, $Ww(newContent, ["remoteAuthority"], formattingOptions));
  }
  return newContent;
}
function doParseStoredWorkspace(path, contents) {
  const storedWorkspace = $yw(contents);
  if (storedWorkspace && Array.isArray(storedWorkspace.folders)) {
    storedWorkspace.folders = storedWorkspace.folders.filter((folder) => $6w(folder));
  } else {
    throw new Error(`${path} looks like an invalid workspace file.`);
  }
  return storedWorkspace;
}
function isSerializedRecentWorkspace(data) {
  return data.workspace && typeof data.workspace === "object" && typeof data.workspace.id === "string" && typeof data.workspace.configPath === "string";
}
function isSerializedRecentFolder(data) {
  return typeof data.folderUri === "string";
}
function isSerializedRecentFile(data) {
  return typeof data.fileUri === "string";
}
function $0w(data, logService) {
  const result = { workspaces: [], files: [] };
  if (data) {
    const restoreGracefully = function(entries2, onEntry) {
      for (let i2 = 0; i2 < entries2.length; i2++) {
        try {
          onEntry(entries2[i2], i2);
        } catch (e) {
          logService.warn(`Error restoring recent entry ${JSON.stringify(entries2[i2])}: ${e.toString()}. Skip entry.`);
        }
      }
    };
    const storedRecents = data;
    if (Array.isArray(storedRecents.entries)) {
      restoreGracefully(storedRecents.entries, (entry) => {
        const label3 = entry.label;
        const remoteAuthority = entry.remoteAuthority;
        if (isSerializedRecentWorkspace(entry)) {
          result.workspaces.push({ label: label3, remoteAuthority, workspace: { id: entry.workspace.id, configPath: URI.parse(entry.workspace.configPath) } });
        } else if (isSerializedRecentFolder(entry)) {
          result.workspaces.push({ label: label3, remoteAuthority, folderUri: URI.parse(entry.folderUri) });
        } else if (isSerializedRecentFile(entry)) {
          result.files.push({ label: label3, remoteAuthority, fileUri: URI.parse(entry.fileUri) });
        }
      });
    }
  }
  return result;
}
function $$w(recents) {
  const serialized = { entries: [] };
  for (const recent of recents.workspaces) {
    if ($4w(recent)) {
      serialized.entries.push({ folderUri: recent.folderUri.toString(), label: recent.label, remoteAuthority: recent.remoteAuthority });
    } else {
      serialized.entries.push({ workspace: { id: recent.workspace.id, configPath: recent.workspace.configPath.toString() }, label: recent.label, remoteAuthority: recent.remoteAuthority });
    }
  }
  for (const recent of recents.files) {
    serialized.entries.push({ fileUri: recent.fileUri.toString(), label: recent.label, remoteAuthority: recent.remoteAuthority });
  }
  return serialized;
}

// out-build/vs/workbench/browser/actions/workspaceCommands.js
var $Tyb = "addRootFolder";
var $Uyb = localize2(3044, "Add Folder to Workspace...");
var $Vyb = "setRootFolder";
var $Wyb = "_workbench.pickWorkspaceFolder";
$tn.registerCommand({
  id: "workbench.action.files.openFileFolderInNewWindow",
  handler: (accessor) => accessor.get($1v).pickFileFolderAndOpen({ forceNewWindow: true })
});
$tn.registerCommand({
  id: "_files.pickFolderAndOpen",
  handler: (accessor, options3) => accessor.get($1v).pickFolderAndOpen(options3)
});
$tn.registerCommand({
  id: "workbench.action.files.openFolderInNewWindow",
  handler: (accessor) => accessor.get($1v).pickFolderAndOpen({ forceNewWindow: true })
});
$tn.registerCommand({
  id: "workbench.action.files.openFileInNewWindow",
  handler: (accessor) => accessor.get($1v).pickFileAndOpen({ forceNewWindow: true })
});
$tn.registerCommand({
  id: "workbench.action.openWorkspaceInNewWindow",
  handler: (accessor) => accessor.get($1v).pickWorkspaceAndOpen({ forceNewWindow: true })
});
$tn.registerCommand({
  id: $Tyb,
  handler: async (accessor) => {
    const workspaceEditingService = accessor.get($zob);
    const folders = await selectWorkspaceFolders(accessor);
    if (!folders || !folders.length) {
      return;
    }
    await workspaceEditingService.addFolders(folders.map((folder) => ({ uri: folder })));
  }
});
$tn.registerCommand({
  id: $Vyb,
  handler: async (accessor) => {
    const workspaceEditingService = accessor.get($zob);
    const contextService = accessor.get($Zk);
    const folders = await selectWorkspaceFolders(accessor);
    if (!folders || !folders.length) {
      return;
    }
    await workspaceEditingService.updateFolders(0, contextService.getWorkspace().folders.length, folders.map((folder) => ({ uri: folder })));
  }
});
async function selectWorkspaceFolders(accessor) {
  const dialogsService = accessor.get($1v);
  const pathService = accessor.get($aT);
  const folders = await dialogsService.showOpenDialog({
    openLabel: $7t(localize(3041, null)),
    title: localize(3042, null),
    canSelectFolders: true,
    canSelectMany: true,
    defaultUri: await dialogsService.defaultFolderPath(),
    availableFileSystems: [pathService.defaultUriScheme]
  });
  return folders;
}
$tn.registerCommand($Wyb, async function(accessor, args2) {
  const quickInputService = accessor.get($1M);
  const labelService = accessor.get($ZI);
  const contextService = accessor.get($Zk);
  const modelService = accessor.get($sG);
  const languageService = accessor.get($1E);
  const folders = contextService.getWorkspace().folders;
  if (!folders.length) {
    return;
  }
  const folderPicks = folders.map((folder) => {
    const label3 = folder.name;
    const description = labelService.getUriLabel($uh(folder.uri), { relative: true });
    return {
      label: label3,
      description: description !== label3 ? description : void 0,
      // https://github.com/microsoft/vscode/issues/183418
      folder,
      iconClasses: $gdb(modelService, languageService, folder.uri, FileKind.ROOT_FOLDER)
    };
  });
  const options3 = (args2 ? args2[0] : void 0) || /* @__PURE__ */ Object.create(null);
  if (!options3.activeItem) {
    options3.activeItem = folderPicks[0];
  }
  if (!options3.placeHolder) {
    options3.placeHolder = localize(3043, null);
  }
  if (typeof options3.matchOnDescription !== "boolean") {
    options3.matchOnDescription = true;
  }
  const token = (args2 ? args2[1] : void 0) || CancellationToken.None;
  const pick = await quickInputService.pick(folderPicks, options3, token);
  if (pick) {
    return folders[folderPicks.indexOf(pick)];
  }
  return;
});
$tn.registerCommand({
  id: "vscode.openFolder",
  handler: (accessor, uriComponents, arg) => {
    const commandService = accessor.get($sn);
    if (typeof arg === "boolean") {
      arg = { forceNewWindow: arg };
    }
    if (!uriComponents) {
      const options4 = {
        forceNewWindow: arg?.forceNewWindow
      };
      if (arg?.forceLocalWindow) {
        options4.remoteAuthority = null;
        options4.availableFileSystems = ["file"];
      }
      return commandService.executeCommand("_files.pickFolderAndOpen", options4);
    }
    const uri = URI.from(uriComponents, true);
    const options3 = {
      forceNewWindow: arg?.forceNewWindow,
      forceReuseWindow: arg?.forceReuseWindow,
      noRecentEntry: arg?.noRecentEntry,
      remoteAuthority: arg?.forceLocalWindow ? null : void 0,
      forceProfile: arg?.forceProfile,
      forceTempProfile: arg?.forceTempProfile
    };
    const uriToOpen = $jl(uri) || uri.scheme === Schemas.untitled ? { workspaceUri: uri } : { folderUri: uri };
    return commandService.executeCommand("_files.windowOpen", [uriToOpen], options3);
  },
  metadata: {
    description: "Open a folder or workspace in the current window or new window depending on the newWindow argument. Note that opening in the same window will shutdown the current extension host process and start a new one on the given folder/workspace unless the newWindow parameter is set to true.",
    args: [
      {
        name: "uri",
        description: "(optional) Uri of the folder or workspace file to open. If not provided, a native dialog will ask the user for the folder",
        constraint: (value) => value === void 0 || value === null || value instanceof URI
      },
      {
        name: "options",
        description: "(optional) Options. Object with the following properties: `forceNewWindow`: Whether to open the folder/workspace in a new window or the same. Defaults to opening in the same window. `forceReuseWindow`: Whether to force opening the folder/workspace in the same window.  Defaults to false. `noRecentEntry`: Whether the opened URI will appear in the 'Open Recent' list. Defaults to false. Note, for backward compatibility, options can also be of type boolean, representing the `forceNewWindow` setting.",
        constraint: (value) => value === void 0 || typeof value === "object" || typeof value === "boolean"
      }
    ]
  }
});
$tn.registerCommand({
  id: "vscode.newWindow",
  handler: (accessor, options3) => {
    const commandService = accessor.get($sn);
    const commandOptions = {
      forceReuseWindow: options3 && options3.reuseWindow,
      remoteAuthority: options3 && options3.remoteAuthority
    };
    return commandService.executeCommand("_files.newWindow", commandOptions);
  },
  metadata: {
    description: "Opens an new window depending on the newWindow argument.",
    args: [
      {
        name: "options",
        description: "(optional) Options. Object with the following properties: `reuseWindow`: Whether to open a new window or the same. Defaults to opening in a new window. ",
        constraint: (value) => value === void 0 || typeof value === "object"
      }
    ]
  }
});
$tn.registerCommand("_workbench.removeFromRecentlyOpened", function(accessor, uri) {
  const workspacesService = accessor.get($2w);
  return workspacesService.removeRecentlyOpened([uri]);
});
$tn.registerCommand({
  id: "vscode.removeFromRecentlyOpened",
  handler: (accessor, path) => {
    const workspacesService = accessor.get($2w);
    if (typeof path === "string") {
      path = path.match(/^[^:/?#]+:\/\//) ? URI.parse(path) : URI.file(path);
    } else {
      path = URI.revive(path);
    }
    return workspacesService.removeRecentlyOpened([path]);
  },
  metadata: {
    description: "Removes an entry with the given path from the recently opened list.",
    args: [
      { name: "path", description: "URI or URI string to remove from recently opened.", constraint: (value) => typeof value === "string" || value instanceof URI }
    ]
  }
});
$tn.registerCommand("_workbench.addToRecentlyOpened", async function(accessor, recentEntry) {
  const workspacesService = accessor.get($2w);
  const uri = recentEntry.uri;
  const label3 = recentEntry.label;
  const remoteAuthority = recentEntry.remoteAuthority;
  let recent = void 0;
  if (recentEntry.type === "workspace") {
    const workspace2 = await workspacesService.getWorkspaceIdentifier(uri);
    recent = { workspace: workspace2, label: label3, remoteAuthority };
  } else if (recentEntry.type === "folder") {
    recent = { folderUri: uri, label: label3, remoteAuthority };
  } else {
    recent = { fileUri: uri, label: label3, remoteAuthority };
  }
  return workspacesService.addRecentlyOpened([recent]);
});
$tn.registerCommand("_workbench.getRecentlyOpened", async function(accessor) {
  const workspacesService = accessor.get($2w);
  return workspacesService.getRecentlyOpened();
});

// out-build/vs/workbench/browser/actions/workspaceActions.js
var workspacesCategory = localize2(3030, "Workspaces");
var $Xyb = class _$Xyb extends $gJ {
  static {
    this.ID = "workbench.action.files.openFile";
  }
  constructor() {
    super({
      id: _$Xyb.ID,
      title: localize2(3031, "Open File..."),
      category: $qn.File,
      f1: true,
      keybinding: {
        when: $web.toNegated(),
        weight: 200,
        primary: 2048 | 45
        /* KeyCode.KeyO */
      }
    });
  }
  async run(accessor, data) {
    const fileDialogService = accessor.get($1v);
    return fileDialogService.pickFileAndOpen({ forceNewWindow: false, telemetryExtraData: data });
  }
};
var $Yyb = class _$Yyb extends $gJ {
  static {
    this.ID = "workbench.action.files.openFolder";
  }
  constructor() {
    super({
      id: _$Yyb.ID,
      title: localize2(3032, "Open Folder..."),
      category: $qn.File,
      f1: true,
      precondition: $gpb,
      keybinding: {
        weight: 200,
        primary: void 0,
        linux: {
          primary: $$e(
            2048 | 41,
            2048 | 45
            /* KeyCode.KeyO */
          )
        },
        win: {
          primary: $$e(
            2048 | 41,
            2048 | 45
            /* KeyCode.KeyO */
          )
        }
      }
    });
  }
  async run(accessor, data) {
    const fileDialogService = accessor.get($1v);
    return fileDialogService.pickFolderAndOpen({ forceNewWindow: false, telemetryExtraData: data });
  }
};
var $Zyb = class _$Zyb extends $gJ {
  static {
    this.ID = "workbench.action.files.openFolderViaWorkspace";
  }
  constructor() {
    super({
      id: _$Zyb.ID,
      title: localize2(3033, "Open Folder..."),
      category: $qn.File,
      f1: true,
      precondition: $7m.and($gpb.toNegated(), $epb.isEqualTo("workspace")),
      keybinding: {
        weight: 200,
        primary: 2048 | 45
        /* KeyCode.KeyO */
      }
    });
  }
  run(accessor) {
    const commandService = accessor.get($sn);
    return commandService.executeCommand($Vyb);
  }
};
var $1yb = class _$1yb extends $gJ {
  static {
    this.ID = "workbench.action.files.openFileFolder";
  }
  static {
    this.LABEL = localize2(3034, "Open...");
  }
  constructor() {
    super({
      id: _$1yb.ID,
      title: _$1yb.LABEL,
      category: $qn.File,
      f1: true,
      precondition: $7m.and($web, $gpb),
      keybinding: {
        weight: 200,
        primary: 2048 | 45
        /* KeyCode.KeyO */
      }
    });
  }
  async run(accessor, data) {
    const fileDialogService = accessor.get($1v);
    return fileDialogService.pickFileFolderAndOpen({ forceNewWindow: false, telemetryExtraData: data });
  }
};
var OpenWorkspaceAction = class _OpenWorkspaceAction extends $gJ {
  static {
    this.ID = "workbench.action.openWorkspace";
  }
  constructor() {
    super({
      id: _OpenWorkspaceAction.ID,
      title: localize2(3035, "Open Workspace from File..."),
      category: $qn.File,
      f1: true,
      precondition: $hpb
    });
  }
  async run(accessor, data) {
    const fileDialogService = accessor.get($1v);
    return fileDialogService.pickWorkspaceAndOpen({ telemetryExtraData: data });
  }
};
var CloseWorkspaceAction = class _CloseWorkspaceAction extends $gJ {
  static {
    this.ID = "workbench.action.closeFolder";
  }
  constructor() {
    super({
      id: _CloseWorkspaceAction.ID,
      title: localize2(3036, "Close Workspace"),
      category: workspacesCategory,
      f1: true,
      precondition: $7m.and($epb.notEqualsTo("empty"), $ipb),
      keybinding: {
        weight: 200,
        primary: $$e(
          2048 | 41,
          36
          /* KeyCode.KeyF */
        )
      }
    });
  }
  async run(accessor) {
    const hostService = accessor.get($S4);
    const environmentService = accessor.get($US);
    return hostService.openWindow({ forceReuseWindow: true, remoteAuthority: environmentService.remoteAuthority });
  }
};
var OpenWorkspaceConfigFileAction = class _OpenWorkspaceConfigFileAction extends $gJ {
  static {
    this.ID = "workbench.action.openWorkspaceConfigFile";
  }
  constructor() {
    super({
      id: _OpenWorkspaceConfigFileAction.ID,
      title: localize2(3037, "Open Workspace Configuration File"),
      category: workspacesCategory,
      f1: true,
      precondition: $epb.isEqualTo("workspace")
    });
  }
  async run(accessor) {
    const contextService = accessor.get($Zk);
    const editorService = accessor.get($mJ);
    const configuration2 = contextService.getWorkspace().configuration;
    if (configuration2) {
      await editorService.openEditor({ resource: configuration2, options: { pinned: true } });
    }
  }
};
var $2yb = class _$2yb extends $gJ {
  static {
    this.ID = "workbench.action.addRootFolder";
  }
  constructor() {
    super({
      id: _$2yb.ID,
      title: $Uyb,
      category: workspacesCategory,
      f1: true,
      precondition: $7m.or($hpb, $epb.isEqualTo("workspace"))
    });
  }
  run(accessor) {
    const commandService = accessor.get($sn);
    return commandService.executeCommand($Tyb);
  }
};
var $3yb = class _$3yb extends $gJ {
  static {
    this.ID = "workbench.action.removeRootFolder";
  }
  constructor() {
    super({
      id: _$3yb.ID,
      title: localize2(3038, "Remove Folder from Workspace..."),
      category: workspacesCategory,
      f1: true,
      precondition: $7m.and($fpb.notEqualsTo("0"), $7m.or($hpb, $epb.isEqualTo("workspace")))
    });
  }
  async run(accessor) {
    const commandService = accessor.get($sn);
    const workspaceEditingService = accessor.get($zob);
    const folder = await commandService.executeCommand($Wyb);
    if (folder) {
      await workspaceEditingService.removeFolders([folder.uri]);
    }
  }
};
var SaveWorkspaceAsAction = class _SaveWorkspaceAsAction extends $gJ {
  static {
    this.ID = "workbench.action.saveWorkspaceAs";
  }
  constructor() {
    super({
      id: _SaveWorkspaceAsAction.ID,
      title: localize2(3039, "Save Workspace As..."),
      category: workspacesCategory,
      f1: true,
      precondition: $hpb
    });
  }
  async run(accessor) {
    const workspaceEditingService = accessor.get($zob);
    const contextService = accessor.get($Zk);
    const configPathUri = await workspaceEditingService.pickNewWorkspacePath();
    if (configPathUri && $jl(configPathUri)) {
      switch (contextService.getWorkbenchState()) {
        case 1:
        case 2: {
          const folders = contextService.getWorkspace().folders.map((folder) => ({ uri: folder.uri }));
          return workspaceEditingService.createAndEnterWorkspace(folders, configPathUri);
        }
        case 3:
          return workspaceEditingService.saveAndEnterWorkspace(configPathUri);
      }
    }
  }
};
var DuplicateWorkspaceInNewWindowAction = class _DuplicateWorkspaceInNewWindowAction extends $gJ {
  static {
    this.ID = "workbench.action.duplicateWorkspaceInNewWindow";
  }
  constructor() {
    super({
      id: _DuplicateWorkspaceInNewWindowAction.ID,
      title: localize2(3040, "Duplicate As Workspace in New Window"),
      category: workspacesCategory,
      f1: true,
      precondition: $hpb
    });
  }
  async run(accessor) {
    const workspaceContextService = accessor.get($Zk);
    const workspaceEditingService = accessor.get($zob);
    const hostService = accessor.get($S4);
    const workspacesService = accessor.get($2w);
    const environmentService = accessor.get($US);
    const folders = workspaceContextService.getWorkspace().folders;
    const remoteAuthority = environmentService.remoteAuthority;
    const newWorkspace = await workspacesService.createUntitledWorkspace(folders, remoteAuthority);
    await workspaceEditingService.copyWorkspaceSettings(newWorkspace);
    return hostService.openWindow([{ workspaceUri: newWorkspace.configPath }], { forceNewWindow: true, remoteAuthority });
  }
};
$hJ($2yb);
$hJ($3yb);
$hJ($Xyb);
$hJ($Yyb);
$hJ($Zyb);
$hJ($1yb);
$hJ(OpenWorkspaceAction);
$hJ(OpenWorkspaceConfigFileAction);
$hJ(CloseWorkspaceAction);
$hJ(SaveWorkspaceAsAction);
$hJ(DuplicateWorkspaceInNewWindowAction);
$dJ.appendMenuItem($bJ.MenubarFileMenu, {
  group: "2_open",
  command: {
    id: $Xyb.ID,
    title: localize(3020, null)
  },
  order: 1,
  when: $web.toNegated()
});
$dJ.appendMenuItem($bJ.MenubarFileMenu, {
  group: "2_open",
  command: {
    id: $Yyb.ID,
    title: localize(3021, null)
  },
  order: 2,
  when: $gpb
});
$dJ.appendMenuItem($bJ.MenubarFileMenu, {
  group: "2_open",
  command: {
    id: $Zyb.ID,
    title: localize(3022, null)
  },
  order: 2,
  when: $7m.and($gpb.toNegated(), $epb.isEqualTo("workspace"))
});
$dJ.appendMenuItem($bJ.MenubarFileMenu, {
  group: "2_open",
  command: {
    id: $1yb.ID,
    title: localize(3023, null)
  },
  order: 1,
  when: $7m.and($web, $gpb)
});
$dJ.appendMenuItem($bJ.MenubarFileMenu, {
  group: "2_open",
  command: {
    id: OpenWorkspaceAction.ID,
    title: localize(3024, null)
  },
  order: 3,
  when: $hpb
});
$dJ.appendMenuItem($bJ.MenubarFileMenu, {
  group: "3_workspace",
  command: {
    id: $Tyb,
    title: localize(3025, null)
  },
  when: $7m.or($hpb, $epb.isEqualTo("workspace")),
  order: 1
});
$dJ.appendMenuItem($bJ.MenubarFileMenu, {
  group: "3_workspace",
  command: {
    id: SaveWorkspaceAsAction.ID,
    title: localize(3026, null)
  },
  order: 2,
  when: $hpb
});
$dJ.appendMenuItem($bJ.MenubarFileMenu, {
  group: "3_workspace",
  command: {
    id: DuplicateWorkspaceInNewWindowAction.ID,
    title: localize(3027, null)
  },
  order: 3,
  when: $hpb
});
$dJ.appendMenuItem($bJ.MenubarFileMenu, {
  group: "6_close",
  command: {
    id: CloseWorkspaceAction.ID,
    title: localize(3028, null)
  },
  order: 3,
  when: $7m.and($epb.isEqualTo("folder"), $ipb)
});
$dJ.appendMenuItem($bJ.MenubarFileMenu, {
  group: "6_close",
  command: {
    id: CloseWorkspaceAction.ID,
    title: localize(3029, null)
  },
  order: 3,
  when: $7m.and($epb.isEqualTo("workspace"), $ipb)
});

// out-build/vs/platform/layout/browser/layoutService.js
var $Ulb = $Qk("layoutService");

// out-build/vs/workbench/services/layout/browser/layoutService.js
var $Vlb = $Rk($Ulb);
var Parts;
(function(Parts2) {
  Parts2["TITLEBAR_PART"] = "workbench.parts.titlebar";
  Parts2["BANNER_PART"] = "workbench.parts.banner";
  Parts2["ACTIVITYBAR_PART"] = "workbench.parts.activitybar";
  Parts2["SIDEBAR_PART"] = "workbench.parts.sidebar";
  Parts2["PANEL_PART"] = "workbench.parts.panel";
  Parts2["AUXILIARYBAR_PART"] = "workbench.parts.auxiliarybar";
  Parts2["EDITOR_PART"] = "workbench.parts.editor";
  Parts2["STATUSBAR_PART"] = "workbench.parts.statusbar";
})(Parts || (Parts = {}));
var ZenModeSettings;
(function(ZenModeSettings2) {
  ZenModeSettings2["SHOW_TABS"] = "zenMode.showTabs";
  ZenModeSettings2["HIDE_LINENUMBERS"] = "zenMode.hideLineNumbers";
  ZenModeSettings2["HIDE_STATUSBAR"] = "zenMode.hideStatusBar";
  ZenModeSettings2["HIDE_ACTIVITYBAR"] = "zenMode.hideActivityBar";
  ZenModeSettings2["CENTER_LAYOUT"] = "zenMode.centerLayout";
  ZenModeSettings2["FULLSCREEN"] = "zenMode.fullScreen";
  ZenModeSettings2["RESTORE"] = "zenMode.restore";
  ZenModeSettings2["SILENT_NOTIFICATIONS"] = "zenMode.silentNotifications";
})(ZenModeSettings || (ZenModeSettings = {}));
var LayoutSettings;
(function(LayoutSettings2) {
  LayoutSettings2["ACTIVITY_BAR_LOCATION"] = "workbench.activityBar.location";
  LayoutSettings2["EDITOR_TABS_MODE"] = "workbench.editor.showTabs";
  LayoutSettings2["EDITOR_ACTIONS_LOCATION"] = "workbench.editor.editorActionsLocation";
  LayoutSettings2["COMMAND_CENTER"] = "window.commandCenter";
  LayoutSettings2["LAYOUT_ACTIONS"] = "workbench.layoutControl.enabled";
})(LayoutSettings || (LayoutSettings = {}));
var ActivityBarPosition;
(function(ActivityBarPosition2) {
  ActivityBarPosition2["DEFAULT"] = "default";
  ActivityBarPosition2["TOP"] = "top";
  ActivityBarPosition2["BOTTOM"] = "bottom";
  ActivityBarPosition2["HIDDEN"] = "hidden";
})(ActivityBarPosition || (ActivityBarPosition = {}));
var EditorTabsMode;
(function(EditorTabsMode2) {
  EditorTabsMode2["MULTIPLE"] = "multiple";
  EditorTabsMode2["SINGLE"] = "single";
  EditorTabsMode2["NONE"] = "none";
})(EditorTabsMode || (EditorTabsMode = {}));
var EditorActionsLocation;
(function(EditorActionsLocation2) {
  EditorActionsLocation2["DEFAULT"] = "default";
  EditorActionsLocation2["TITLEBAR"] = "titleBar";
  EditorActionsLocation2["HIDDEN"] = "hidden";
})(EditorActionsLocation || (EditorActionsLocation = {}));
var Position;
(function(Position3) {
  Position3[Position3["LEFT"] = 0] = "LEFT";
  Position3[Position3["RIGHT"] = 1] = "RIGHT";
  Position3[Position3["BOTTOM"] = 2] = "BOTTOM";
  Position3[Position3["TOP"] = 3] = "TOP";
})(Position || (Position = {}));
function $Wlb(position) {
  return position === 2 || position === 3;
}
var PanelOpensMaximizedOptions;
(function(PanelOpensMaximizedOptions2) {
  PanelOpensMaximizedOptions2[PanelOpensMaximizedOptions2["ALWAYS"] = 0] = "ALWAYS";
  PanelOpensMaximizedOptions2[PanelOpensMaximizedOptions2["NEVER"] = 1] = "NEVER";
  PanelOpensMaximizedOptions2[PanelOpensMaximizedOptions2["REMEMBER_LAST"] = 2] = "REMEMBER_LAST";
})(PanelOpensMaximizedOptions || (PanelOpensMaximizedOptions = {}));
function $Xlb(position) {
  switch (position) {
    case 0:
      return "left";
    case 1:
      return "right";
    case 2:
      return "bottom";
    case 3:
      return "top";
    default:
      return "bottom";
  }
}
var positionsByString = {
  [$Xlb(
    0
    /* Position.LEFT */
  )]: 0,
  [$Xlb(
    1
    /* Position.RIGHT */
  )]: 1,
  [$Xlb(
    2
    /* Position.BOTTOM */
  )]: 2,
  [$Xlb(
    3
    /* Position.TOP */
  )]: 3
  /* Position.TOP */
};
function $Ylb(str) {
  return positionsByString[str];
}
function panelOpensMaximizedSettingToString(setting) {
  switch (setting) {
    case 0:
      return "always";
    case 1:
      return "never";
    case 2:
      return "preserve";
    default:
      return "preserve";
  }
}
var panelOpensMaximizedByString = {
  [panelOpensMaximizedSettingToString(
    0
    /* PanelOpensMaximizedOptions.ALWAYS */
  )]: 0,
  [panelOpensMaximizedSettingToString(
    1
    /* PanelOpensMaximizedOptions.NEVER */
  )]: 1,
  [panelOpensMaximizedSettingToString(
    2
    /* PanelOpensMaximizedOptions.REMEMBER_LAST */
  )]: 2
  /* PanelOpensMaximizedOptions.REMEMBER_LAST */
};
function $Zlb(str) {
  return panelOpensMaximizedByString[str];
}
function $1lb(configurationService, window3, menuBarToggled) {
  if (!$Cs(configurationService)) {
    return false;
  }
  const inFullscreen = $Se(window3);
  const nativeTitleBarEnabled = $Ds(configurationService);
  if (!$r) {
    const showCustomTitleBar = configurationService.getValue(
      "window.customTitleBarVisibility"
      /* TitleBarSetting.CUSTOM_TITLE_BAR_VISIBILITY */
    );
    if (showCustomTitleBar === "never" && nativeTitleBarEnabled || showCustomTitleBar === "windowed" && inFullscreen) {
      return false;
    }
  }
  if (!isTitleBarEmpty(configurationService)) {
    return true;
  }
  if (nativeTitleBarEnabled) {
    return false;
  }
  if ($m && $p) {
    return !inFullscreen;
  }
  if ($p && !inFullscreen) {
    return true;
  }
  if ($3e() && !inFullscreen) {
    return true;
  }
  const menuBarVisibility = !$Z(window3) ? $Bs(configurationService) : "hidden";
  switch (menuBarVisibility) {
    case "classic":
      return !inFullscreen || !!menuBarToggled;
    case "compact":
    case "hidden":
      return false;
    case "toggle":
      return !!menuBarToggled;
    case "visible":
      return true;
    default:
      return $r ? false : !inFullscreen || !!menuBarToggled;
  }
}
function isTitleBarEmpty(configurationService) {
  if (configurationService.getValue(
    "window.commandCenter"
    /* LayoutSettings.COMMAND_CENTER */
  )) {
    return false;
  }
  const activityBarPosition = configurationService.getValue(
    "workbench.activityBar.location"
    /* LayoutSettings.ACTIVITY_BAR_LOCATION */
  );
  if (activityBarPosition === "top" || activityBarPosition === "bottom") {
    return false;
  }
  const editorActionsLocation = configurationService.getValue(
    "workbench.editor.editorActionsLocation"
    /* LayoutSettings.EDITOR_ACTIONS_LOCATION */
  );
  const editorTabsMode = configurationService.getValue(
    "workbench.editor.showTabs"
    /* LayoutSettings.EDITOR_TABS_MODE */
  );
  if (editorActionsLocation === "titleBar" || editorActionsLocation === "default" && editorTabsMode === "none") {
    return false;
  }
  if (configurationService.getValue(
    "workbench.layoutControl.enabled"
    /* LayoutSettings.LAYOUT_ACTIONS */
  )) {
    return false;
  }
  return true;
}

// out-build/vs/workbench/services/history/common/history.js
var $tY = $Qk("historyService");
var GoFilter;
(function(GoFilter2) {
  GoFilter2[GoFilter2["NONE"] = 0] = "NONE";
  GoFilter2[GoFilter2["EDITS"] = 1] = "EDITS";
  GoFilter2[GoFilter2["NAVIGATION"] = 2] = "NAVIGATION";
})(GoFilter || (GoFilter = {}));
var GoScope;
(function(GoScope2) {
  GoScope2[GoScope2["DEFAULT"] = 0] = "DEFAULT";
  GoScope2[GoScope2["EDITOR_GROUP"] = 1] = "EDITOR_GROUP";
  GoScope2[GoScope2["EDITOR"] = 2] = "EDITOR";
})(GoScope || (GoScope = {}));

// out-build/vs/workbench/browser/parts/editor/editorActions.js
var ExecuteCommandAction = class extends $gJ {
  constructor(desc, a, b) {
    super(desc);
    this.a = a;
    this.b = b;
  }
  run(accessor) {
    const commandService = accessor.get($sn);
    return commandService.executeCommand(this.a, this.b);
  }
};
var AbstractSplitEditorAction = class extends $gJ {
  a(configurationService) {
    return $lJ(configurationService);
  }
  async run(accessor, ...args2) {
    const editorGroupsService = accessor.get($iJ);
    const configurationService = accessor.get($kl);
    const direction = this.a(configurationService);
    const commandContext = $sub(args2, accessor.get($mJ), editorGroupsService, accessor.get($Deb));
    $cvb(editorGroupsService, direction, commandContext);
  }
};
var $Gwb = class _$Gwb extends AbstractSplitEditorAction {
  static {
    this.ID = $Nub;
  }
  constructor() {
    super({
      id: _$Gwb.ID,
      title: localize2(3352, "Split Editor"),
      f1: true,
      keybinding: {
        weight: 200,
        primary: 2048 | 93
        /* KeyCode.Backslash */
      },
      category: $qn.View
    });
  }
};
var $Hwb = class extends AbstractSplitEditorAction {
  constructor() {
    super({
      id: "workbench.action.splitEditorOrthogonal",
      title: localize2(3353, "Split Editor Orthogonal"),
      f1: true,
      keybinding: {
        weight: 200,
        primary: $$e(
          2048 | 41,
          2048 | 93
          /* KeyCode.Backslash */
        )
      },
      category: $qn.View
    });
  }
  a(configurationService) {
    const direction = $lJ(configurationService);
    return direction === 3 ? 1 : 3;
  }
};
var $Iwb = class extends ExecuteCommandAction {
  constructor() {
    super({
      id: $Qub,
      title: localize2(3354, "Split Editor Left"),
      f1: true,
      keybinding: {
        weight: 200,
        primary: $$e(
          2048 | 41,
          2048 | 93
          /* KeyCode.Backslash */
        )
      },
      category: $qn.View
    }, $Qub);
  }
};
var $Jwb = class extends ExecuteCommandAction {
  constructor() {
    super({
      id: $Rub,
      title: localize2(3355, "Split Editor Right"),
      f1: true,
      keybinding: {
        weight: 200,
        primary: $$e(
          2048 | 41,
          2048 | 93
          /* KeyCode.Backslash */
        )
      },
      category: $qn.View
    }, $Rub);
  }
};
var $Kwb = class extends ExecuteCommandAction {
  static {
    this.LABEL = localize(3328, null);
  }
  constructor() {
    super({
      id: $Oub,
      title: localize2(3356, "Split Editor Up"),
      f1: true,
      keybinding: {
        weight: 200,
        primary: $$e(
          2048 | 41,
          2048 | 93
          /* KeyCode.Backslash */
        )
      },
      category: $qn.View
    }, $Oub);
  }
};
var $Lwb = class extends ExecuteCommandAction {
  static {
    this.LABEL = localize(3329, null);
  }
  constructor() {
    super({
      id: $Pub,
      title: localize2(3357, "Split Editor Down"),
      f1: true,
      keybinding: {
        weight: 200,
        primary: $$e(
          2048 | 41,
          2048 | 93
          /* KeyCode.Backslash */
        )
      },
      category: $qn.View
    }, $Pub);
  }
};
var $Mwb = class extends $gJ {
  constructor() {
    super({
      id: "workbench.action.joinTwoGroups",
      title: localize2(3358, "Join Editor Group with Next Group"),
      f1: true,
      category: $qn.View
    });
  }
  async run(accessor, context) {
    const editorGroupService = accessor.get($iJ);
    let sourceGroup;
    if (context && typeof context.groupId === "number") {
      sourceGroup = editorGroupService.getGroup(context.groupId);
    } else {
      sourceGroup = editorGroupService.activeGroup;
    }
    if (sourceGroup) {
      const targetGroupDirections = [
        3,
        1,
        2,
        0
        /* GroupDirection.UP */
      ];
      for (const targetGroupDirection of targetGroupDirections) {
        const targetGroup = editorGroupService.findGroup({ direction: targetGroupDirection }, sourceGroup);
        if (targetGroup && sourceGroup !== targetGroup) {
          editorGroupService.mergeGroup(sourceGroup, targetGroup);
          break;
        }
      }
    }
  }
};
var $Nwb = class extends $gJ {
  constructor() {
    super({
      id: "workbench.action.joinAllGroups",
      title: localize2(3359, "Join All Editor Groups"),
      f1: true,
      category: $qn.View
    });
  }
  async run(accessor) {
    const editorGroupService = accessor.get($iJ);
    editorGroupService.mergeAllGroups(editorGroupService.activeGroup);
  }
};
var $Owb = class extends $gJ {
  constructor() {
    super({
      id: "workbench.action.navigateEditorGroups",
      title: localize2(3360, "Navigate Between Editor Groups"),
      f1: true,
      category: $qn.View
    });
  }
  async run(accessor) {
    const editorGroupService = accessor.get($iJ);
    const nextGroup = editorGroupService.findGroup({
      location: 2
      /* GroupLocation.NEXT */
    }, editorGroupService.activeGroup, true);
    nextGroup?.focus();
  }
};
var $Pwb = class extends $gJ {
  constructor() {
    super({
      id: "workbench.action.focusActiveEditorGroup",
      title: localize2(3361, "Focus Active Editor Group"),
      f1: true,
      category: $qn.View
    });
  }
  async run(accessor) {
    const editorGroupService = accessor.get($iJ);
    editorGroupService.activeGroup.focus();
  }
};
var AbstractFocusGroupAction = class extends $gJ {
  constructor(desc, a) {
    super(desc);
    this.a = a;
  }
  async run(accessor) {
    const editorGroupService = accessor.get($iJ);
    const group2 = editorGroupService.findGroup(this.a, editorGroupService.activeGroup, true);
    group2?.focus();
  }
};
var $Qwb = class extends AbstractFocusGroupAction {
  constructor() {
    super({
      id: "workbench.action.focusFirstEditorGroup",
      title: localize2(3362, "Focus First Editor Group"),
      f1: true,
      keybinding: {
        weight: 200,
        primary: 2048 | 22
        /* KeyCode.Digit1 */
      },
      category: $qn.View
    }, {
      location: 0
      /* GroupLocation.FIRST */
    });
  }
};
var $Rwb = class extends AbstractFocusGroupAction {
  constructor() {
    super({
      id: "workbench.action.focusLastEditorGroup",
      title: localize2(3363, "Focus Last Editor Group"),
      f1: true,
      category: $qn.View
    }, {
      location: 1
      /* GroupLocation.LAST */
    });
  }
};
var $Swb = class extends AbstractFocusGroupAction {
  constructor() {
    super({
      id: "workbench.action.focusNextGroup",
      title: localize2(3364, "Focus Next Editor Group"),
      f1: true,
      category: $qn.View
    }, {
      location: 2
      /* GroupLocation.NEXT */
    });
  }
};
var $Twb = class extends AbstractFocusGroupAction {
  constructor() {
    super({
      id: "workbench.action.focusPreviousGroup",
      title: localize2(3365, "Focus Previous Editor Group"),
      f1: true,
      category: $qn.View
    }, {
      location: 3
      /* GroupLocation.PREVIOUS */
    });
  }
};
var $Uwb = class extends AbstractFocusGroupAction {
  constructor() {
    super({
      id: "workbench.action.focusLeftGroup",
      title: localize2(3366, "Focus Left Editor Group"),
      f1: true,
      keybinding: {
        weight: 200,
        primary: $$e(
          2048 | 41,
          2048 | 15
          /* KeyCode.LeftArrow */
        )
      },
      category: $qn.View
    }, {
      direction: 2
      /* GroupDirection.LEFT */
    });
  }
};
var $Vwb = class extends AbstractFocusGroupAction {
  constructor() {
    super({
      id: "workbench.action.focusRightGroup",
      title: localize2(3367, "Focus Right Editor Group"),
      f1: true,
      keybinding: {
        weight: 200,
        primary: $$e(
          2048 | 41,
          2048 | 17
          /* KeyCode.RightArrow */
        )
      },
      category: $qn.View
    }, {
      direction: 3
      /* GroupDirection.RIGHT */
    });
  }
};
var $Wwb = class extends AbstractFocusGroupAction {
  constructor() {
    super({
      id: "workbench.action.focusAboveGroup",
      title: localize2(3368, "Focus Editor Group Above"),
      f1: true,
      keybinding: {
        weight: 200,
        primary: $$e(
          2048 | 41,
          2048 | 16
          /* KeyCode.UpArrow */
        )
      },
      category: $qn.View
    }, {
      direction: 0
      /* GroupDirection.UP */
    });
  }
};
var $Xwb = class extends AbstractFocusGroupAction {
  constructor() {
    super({
      id: "workbench.action.focusBelowGroup",
      title: localize2(3369, "Focus Editor Group Below"),
      f1: true,
      keybinding: {
        weight: 200,
        primary: $$e(
          2048 | 41,
          2048 | 18
          /* KeyCode.DownArrow */
        )
      },
      category: $qn.View
    }, {
      direction: 1
      /* GroupDirection.DOWN */
    });
  }
};
var $Ywb = class $Ywb2 extends $Um {
  static {
    this.ID = "workbench.action.closeActiveEditor";
  }
  static {
    this.LABEL = localize(3330, null);
  }
  constructor(id2, label3, a) {
    super(id2, label3, ThemeIcon.asClassName($6l.close));
    this.a = a;
  }
  run(context) {
    return this.a.executeCommand($xub, void 0, context);
  }
};
$Ywb = __decorate([
  __param(2, $sn)
], $Ywb);
var $Zwb = class $Zwb2 extends $Um {
  static {
    this.ID = "workbench.action.unpinActiveEditor";
  }
  static {
    this.LABEL = localize(3331, null);
  }
  constructor(id2, label3, a) {
    super(id2, label3, ThemeIcon.asClassName($6l.pinned));
    this.a = a;
  }
  run(context) {
    return this.a.executeCommand($Mub, void 0, context);
  }
};
$Zwb = __decorate([
  __param(2, $sn)
], $Zwb);
var $1wb = class $1wb2 extends $Um {
  static {
    this.ID = "workbench.action.closeActiveEditor";
  }
  static {
    this.LABEL = localize(3332, null);
  }
  constructor(id2, label3, a) {
    super(id2, label3, ThemeIcon.asClassName($6l.close));
    this.a = a;
  }
  async run(context) {
    const group2 = context ? this.a.getGroup(context.groupId) : this.a.activeGroup;
    if (!group2) {
      return;
    }
    const targetEditor = context?.editorIndex !== void 0 ? group2.getEditorByIndex(context.editorIndex) : group2.activeEditor;
    if (!targetEditor) {
      return;
    }
    const editors = [];
    if (group2.isSelected(targetEditor)) {
      editors.push(...group2.selectedEditors);
    } else {
      editors.push(targetEditor);
    }
    for (const editor of editors) {
      await group2.closeEditor(editor, { preserveFocus: context?.preserveFocus });
    }
  }
};
$1wb = __decorate([
  __param(2, $iJ)
], $1wb);
var $2wb = class extends $gJ {
  constructor() {
    super({
      id: "workbench.action.revertAndCloseActiveEditor",
      title: localize2(3370, "Revert and Close Editor"),
      f1: true,
      category: $qn.View
    });
  }
  async run(accessor) {
    const editorService = accessor.get($mJ);
    const logService = accessor.get($wn);
    const activeEditorPane = editorService.activeEditorPane;
    if (activeEditorPane) {
      const editor = activeEditorPane.input;
      const group2 = activeEditorPane.group;
      try {
        await editorService.revert({ editor, groupId: group2.id });
      } catch (error) {
        logService.error(error);
        await editorService.revert({ editor, groupId: group2.id }, { soft: true });
      }
      await group2.closeEditor(editor);
    }
  }
};
var $3wb = class extends $gJ {
  constructor() {
    super({
      id: "workbench.action.closeEditorsToTheLeft",
      title: localize2(3371, "Close Editors to the Left in Group"),
      f1: true,
      category: $qn.View
    });
  }
  async run(accessor, context) {
    const editorGroupService = accessor.get($iJ);
    const { group: group2, editor } = this.a(editorGroupService, context);
    if (group2 && editor) {
      await group2.closeEditors({ direction: 0, except: editor, excludeSticky: true });
    }
  }
  a(editorGroupService, context) {
    if (context) {
      return { editor: context.editor, group: editorGroupService.getGroup(context.groupId) };
    }
    return { group: editorGroupService.activeGroup, editor: editorGroupService.activeGroup.activeEditor };
  }
};
var AbstractCloseAllAction = class extends $gJ {
  a(editorGroupService) {
    const groupsToClose = [];
    const groups = editorGroupService.getGroups(
      2
      /* GroupsOrder.GRID_APPEARANCE */
    );
    for (let i2 = groups.length - 1; i2 >= 0; i2--) {
      groupsToClose.push(groups[i2]);
    }
    return groupsToClose;
  }
  async run(accessor) {
    const editorService = accessor.get($mJ);
    const logService = accessor.get($wn);
    const progressService = accessor.get($TJ);
    const editorGroupService = accessor.get($iJ);
    const filesConfigurationService = accessor.get($4J);
    const fileDialogService = accessor.get($1v);
    const dirtyEditorsWithDefaultConfirm = /* @__PURE__ */ new Set();
    const dirtyAutoSaveOnFocusChangeEditors = /* @__PURE__ */ new Set();
    const dirtyAutoSaveOnWindowChangeEditors = /* @__PURE__ */ new Set();
    const editorsWithCustomConfirm = /* @__PURE__ */ new Map();
    for (const { editor, groupId } of editorService.getEditors(1, { excludeSticky: this.e })) {
      let confirmClose = false;
      if (editor.closeHandler) {
        confirmClose = editor.closeHandler.showConfirm();
      } else {
        confirmClose = editor.isDirty() && !editor.isSaving();
      }
      if (!confirmClose) {
        continue;
      }
      if (typeof editor.closeHandler?.confirm === "function") {
        let customEditorsToConfirm = editorsWithCustomConfirm.get(editor.typeId);
        if (!customEditorsToConfirm) {
          customEditorsToConfirm = /* @__PURE__ */ new Set();
          editorsWithCustomConfirm.set(editor.typeId, customEditorsToConfirm);
        }
        customEditorsToConfirm.add({ editor, groupId });
      } else if (!editor.hasCapability(
        4
        /* EditorInputCapabilities.Untitled */
      ) && filesConfigurationService.getAutoSaveMode(editor).mode === 3) {
        dirtyAutoSaveOnFocusChangeEditors.add({ editor, groupId });
      } else if ($p && ($l || $n) && !editor.hasCapability(
        4
        /* EditorInputCapabilities.Untitled */
      ) && filesConfigurationService.getAutoSaveMode(editor).mode === 4) {
        dirtyAutoSaveOnWindowChangeEditors.add({ editor, groupId });
      } else {
        dirtyEditorsWithDefaultConfirm.add({ editor, groupId });
      }
    }
    if (dirtyEditorsWithDefaultConfirm.size > 0) {
      const editors = Array.from(dirtyEditorsWithDefaultConfirm.values());
      await this.d(editors, editorGroupService);
      const confirmation = await fileDialogService.showSaveConfirm(editors.map(({ editor }) => {
        if (editor instanceof $1I) {
          return editor.primary.getName();
        }
        return editor.getName();
      }));
      switch (confirmation) {
        case 2:
          return;
        case 1:
          await this.b(editorService, logService, progressService, editors);
          break;
        case 0:
          await editorService.save(editors, {
            reason: 1
            /* SaveReason.EXPLICIT */
          });
          break;
      }
    }
    for (const [, editorIdentifiers] of editorsWithCustomConfirm) {
      const editors = Array.from(editorIdentifiers.values());
      await this.d(editors, editorGroupService);
      const confirmation = await editors.at(0)?.editor.closeHandler?.confirm?.(editors);
      if (typeof confirmation === "number") {
        switch (confirmation) {
          case 2:
            return;
          case 1:
            await this.b(editorService, logService, progressService, editors);
            break;
          case 0:
            await editorService.save(editors, {
              reason: 1
              /* SaveReason.EXPLICIT */
            });
            break;
        }
      }
    }
    if (dirtyAutoSaveOnFocusChangeEditors.size > 0) {
      const editors = Array.from(dirtyAutoSaveOnFocusChangeEditors.values());
      await editorService.save(editors, {
        reason: 3
        /* SaveReason.FOCUS_CHANGE */
      });
    }
    if (dirtyAutoSaveOnWindowChangeEditors.size > 0) {
      const editors = Array.from(dirtyAutoSaveOnWindowChangeEditors.values());
      await editorService.save(editors, {
        reason: 4
        /* SaveReason.WINDOW_CHANGE */
      });
    }
    return this.f(editorGroupService);
  }
  b(editorService, logService, progressService, editors) {
    return progressService.withProgress({
      location: 10,
      // use window progress to not be too annoying about this operation
      delay: 800,
      // delay so that it only appears when operation takes a long time
      title: localize(3333, null)
    }, () => this.c(editorService, logService, editors));
  }
  async c(editorService, logService, editors) {
    try {
      await editorService.revert(editors);
    } catch (error) {
      logService.error(error);
      await editorService.revert(editors, { soft: true });
    }
  }
  async d(editors, editorGroupService) {
    try {
      const handledGroups = /* @__PURE__ */ new Set();
      for (const { editor, groupId } of editors) {
        if (handledGroups.has(groupId)) {
          continue;
        }
        handledGroups.add(groupId);
        const group2 = editorGroupService.getGroup(groupId);
        await group2?.openEditor(editor);
      }
    } catch (error) {
    }
  }
  async f(editorGroupService) {
    await Promise.all(this.a(editorGroupService).map((group2) => group2.closeAllEditors({ excludeSticky: this.e })));
  }
};
var $4wb = class _$4wb extends AbstractCloseAllAction {
  static {
    this.ID = "workbench.action.closeAllEditors";
  }
  static {
    this.LABEL = localize2(3372, "Close All Editors");
  }
  constructor() {
    super({
      id: _$4wb.ID,
      title: _$4wb.LABEL,
      f1: true,
      keybinding: {
        weight: 200,
        primary: $$e(
          2048 | 41,
          2048 | 53
          /* KeyCode.KeyW */
        )
      },
      icon: $6l.closeAll,
      category: $qn.View
    });
  }
  get e() {
    return true;
  }
};
var $5wb = class extends AbstractCloseAllAction {
  constructor() {
    super({
      id: "workbench.action.closeAllGroups",
      title: localize2(3373, "Close All Editor Groups"),
      f1: true,
      keybinding: {
        weight: 200,
        primary: $$e(
          2048 | 41,
          2048 | 1024 | 53
          /* KeyCode.KeyW */
        )
      },
      category: $qn.View
    });
  }
  get e() {
    return false;
  }
  async f(editorGroupService) {
    await super.f(editorGroupService);
    for (const groupToClose of this.a(editorGroupService)) {
      editorGroupService.removeGroup(groupToClose);
    }
  }
};
var $6wb = class extends $gJ {
  constructor() {
    super({
      id: "workbench.action.closeEditorsInOtherGroups",
      title: localize2(3374, "Close Editors in Other Groups"),
      f1: true,
      category: $qn.View
    });
  }
  async run(accessor, context) {
    const editorGroupService = accessor.get($iJ);
    const groupToSkip = context ? editorGroupService.getGroup(context.groupId) : editorGroupService.activeGroup;
    await Promise.all(editorGroupService.getGroups(
      1
      /* GroupsOrder.MOST_RECENTLY_ACTIVE */
    ).map(async (group2) => {
      if (groupToSkip && group2.id === groupToSkip.id) {
        return;
      }
      return group2.closeAllEditors({ excludeSticky: true });
    }));
  }
};
var $7wb = class extends $gJ {
  constructor() {
    super({
      id: "workbench.action.closeEditorInAllGroups",
      title: localize2(3375, "Close Editor in All Groups"),
      f1: true,
      category: $qn.View
    });
  }
  async run(accessor) {
    const editorService = accessor.get($mJ);
    const editorGroupService = accessor.get($iJ);
    const activeEditor = editorService.activeEditor;
    if (activeEditor) {
      await Promise.all(editorGroupService.getGroups(
        1
        /* GroupsOrder.MOST_RECENTLY_ACTIVE */
      ).map((group2) => group2.closeEditor(activeEditor)));
    }
  }
};
var AbstractMoveCopyGroupAction = class extends $gJ {
  constructor(desc, a, b) {
    super(desc);
    this.a = a;
    this.b = b;
  }
  async run(accessor, context) {
    const editorGroupService = accessor.get($iJ);
    let sourceGroup;
    if (context && typeof context.groupId === "number") {
      sourceGroup = editorGroupService.getGroup(context.groupId);
    } else {
      sourceGroup = editorGroupService.activeGroup;
    }
    if (sourceGroup) {
      let resultGroup = void 0;
      if (this.b) {
        const targetGroup = this.c(editorGroupService, sourceGroup);
        if (targetGroup) {
          resultGroup = editorGroupService.moveGroup(sourceGroup, targetGroup, this.a);
        }
      } else {
        resultGroup = editorGroupService.copyGroup(sourceGroup, sourceGroup, this.a);
      }
      if (resultGroup) {
        editorGroupService.activateGroup(resultGroup);
      }
    }
  }
  c(editorGroupService, sourceGroup) {
    const targetNeighbours = [this.a];
    switch (this.a) {
      case 2:
      case 3:
        targetNeighbours.push(
          0,
          1
          /* GroupDirection.DOWN */
        );
        break;
      case 0:
      case 1:
        targetNeighbours.push(
          2,
          3
          /* GroupDirection.RIGHT */
        );
        break;
    }
    for (const targetNeighbour of targetNeighbours) {
      const targetNeighbourGroup = editorGroupService.findGroup({ direction: targetNeighbour }, sourceGroup);
      if (targetNeighbourGroup) {
        return targetNeighbourGroup;
      }
    }
    return void 0;
  }
};
var AbstractMoveGroupAction = class extends AbstractMoveCopyGroupAction {
  constructor(desc, direction) {
    super(desc, direction, true);
  }
};
var $8wb = class extends AbstractMoveGroupAction {
  constructor() {
    super(
      {
        id: "workbench.action.moveActiveEditorGroupLeft",
        title: localize2(3376, "Move Editor Group Left"),
        f1: true,
        keybinding: {
          weight: 200,
          primary: $$e(
            2048 | 41,
            15
            /* KeyCode.LeftArrow */
          )
        },
        category: $qn.View
      },
      2
      /* GroupDirection.LEFT */
    );
  }
};
var $9wb = class extends AbstractMoveGroupAction {
  constructor() {
    super(
      {
        id: "workbench.action.moveActiveEditorGroupRight",
        title: localize2(3377, "Move Editor Group Right"),
        f1: true,
        keybinding: {
          weight: 200,
          primary: $$e(
            2048 | 41,
            17
            /* KeyCode.RightArrow */
          )
        },
        category: $qn.View
      },
      3
      /* GroupDirection.RIGHT */
    );
  }
};
var $0wb = class extends AbstractMoveGroupAction {
  constructor() {
    super(
      {
        id: "workbench.action.moveActiveEditorGroupUp",
        title: localize2(3378, "Move Editor Group Up"),
        f1: true,
        keybinding: {
          weight: 200,
          primary: $$e(
            2048 | 41,
            16
            /* KeyCode.UpArrow */
          )
        },
        category: $qn.View
      },
      0
      /* GroupDirection.UP */
    );
  }
};
var $$wb = class extends AbstractMoveGroupAction {
  constructor() {
    super(
      {
        id: "workbench.action.moveActiveEditorGroupDown",
        title: localize2(3379, "Move Editor Group Down"),
        f1: true,
        keybinding: {
          weight: 200,
          primary: $$e(
            2048 | 41,
            18
            /* KeyCode.DownArrow */
          )
        },
        category: $qn.View
      },
      1
      /* GroupDirection.DOWN */
    );
  }
};
var AbstractDuplicateGroupAction = class extends AbstractMoveCopyGroupAction {
  constructor(desc, direction) {
    super(desc, direction, false);
  }
};
var $_wb = class extends AbstractDuplicateGroupAction {
  constructor() {
    super(
      {
        id: "workbench.action.duplicateActiveEditorGroupLeft",
        title: localize2(3380, "Duplicate Editor Group Left"),
        f1: true,
        category: $qn.View
      },
      2
      /* GroupDirection.LEFT */
    );
  }
};
var $axb = class extends AbstractDuplicateGroupAction {
  constructor() {
    super(
      {
        id: "workbench.action.duplicateActiveEditorGroupRight",
        title: localize2(3381, "Duplicate Editor Group Right"),
        f1: true,
        category: $qn.View
      },
      3
      /* GroupDirection.RIGHT */
    );
  }
};
var $bxb = class extends AbstractDuplicateGroupAction {
  constructor() {
    super(
      {
        id: "workbench.action.duplicateActiveEditorGroupUp",
        title: localize2(3382, "Duplicate Editor Group Up"),
        f1: true,
        category: $qn.View
      },
      0
      /* GroupDirection.UP */
    );
  }
};
var $cxb = class extends AbstractDuplicateGroupAction {
  constructor() {
    super(
      {
        id: "workbench.action.duplicateActiveEditorGroupDown",
        title: localize2(3383, "Duplicate Editor Group Down"),
        f1: true,
        category: $qn.View
      },
      1
      /* GroupDirection.DOWN */
    );
  }
};
var $dxb = class extends $gJ {
  constructor() {
    super({
      id: "workbench.action.minimizeOtherEditors",
      title: localize2(3384, "Expand Editor Group"),
      f1: true,
      category: $qn.View,
      precondition: $Npb
    });
  }
  async run(accessor) {
    const editorGroupService = accessor.get($iJ);
    editorGroupService.arrangeGroups(
      1
      /* GroupsArrangement.EXPAND */
    );
  }
};
var $exb = class extends $gJ {
  constructor() {
    super({
      id: "workbench.action.minimizeOtherEditorsHideSidebar",
      title: localize2(3385, "Expand Editor Group and Hide Side Bars"),
      f1: true,
      category: $qn.View,
      precondition: $7m.or($Npb, $3pb, $cqb)
    });
  }
  async run(accessor) {
    const editorGroupService = accessor.get($iJ);
    const layoutService = accessor.get($Vlb);
    layoutService.setPartHidden(
      true,
      "workbench.parts.sidebar"
      /* Parts.SIDEBAR_PART */
    );
    layoutService.setPartHidden(
      true,
      "workbench.parts.auxiliarybar"
      /* Parts.AUXILIARYBAR_PART */
    );
    editorGroupService.arrangeGroups(
      1
      /* GroupsArrangement.EXPAND */
    );
  }
};
var $fxb = class extends $gJ {
  constructor() {
    super({
      id: "workbench.action.evenEditorWidths",
      title: localize2(3386, "Reset Editor Group Sizes"),
      f1: true,
      category: $qn.View
    });
  }
  async run(accessor) {
    const editorGroupService = accessor.get($iJ);
    editorGroupService.arrangeGroups(
      2
      /* GroupsArrangement.EVEN */
    );
  }
};
var $gxb = class extends $gJ {
  constructor() {
    super({
      id: "workbench.action.toggleEditorWidths",
      title: localize2(3387, "Toggle Editor Group Sizes"),
      f1: true,
      category: $qn.View
    });
  }
  async run(accessor) {
    const editorGroupService = accessor.get($iJ);
    editorGroupService.toggleExpandGroup();
  }
};
var $hxb = class extends $gJ {
  constructor() {
    super({
      id: "workbench.action.maximizeEditorHideSidebar",
      title: localize2(3388, "Maximize Editor Group and Hide Side Bars"),
      f1: true,
      category: $qn.View,
      precondition: $7m.or($7m.and($Upb.negate(), $Spb), $3pb, $cqb)
    });
  }
  async run(accessor) {
    const layoutService = accessor.get($Vlb);
    const editorGroupService = accessor.get($iJ);
    const editorService = accessor.get($mJ);
    if (editorService.activeEditor) {
      layoutService.setPartHidden(
        true,
        "workbench.parts.sidebar"
        /* Parts.SIDEBAR_PART */
      );
      layoutService.setPartHidden(
        true,
        "workbench.parts.auxiliarybar"
        /* Parts.AUXILIARYBAR_PART */
      );
      editorGroupService.arrangeGroups(
        0
        /* GroupsArrangement.MAXIMIZE */
      );
    }
  }
};
var $ixb = class extends $gJ {
  constructor() {
    super({
      id: $Sub,
      title: localize2(3389, "Toggle Maximize Editor Group"),
      f1: true,
      category: $qn.View,
      precondition: $7m.or($Spb, $Upb),
      keybinding: {
        weight: 200,
        primary: $$e(
          2048 | 41,
          2048 | 43
          /* KeyCode.KeyM */
        )
      },
      menu: [
        {
          id: $bJ.EditorTitle,
          order: -1e4,
          // towards the front
          group: "navigation",
          when: $Upb
        },
        {
          id: $bJ.EmptyEditorGroup,
          order: -1e4,
          // towards the front
          group: "navigation",
          when: $Upb
        }
      ],
      icon: $6l.screenFull,
      toggled: $Upb
    });
  }
  async run(accessor, ...args2) {
    const editorGroupsService = accessor.get($iJ);
    const resolvedContext = $sub(args2, accessor.get($mJ), editorGroupsService, accessor.get($Deb));
    if (resolvedContext.groupedEditors.length) {
      editorGroupsService.toggleMaximizeGroup(resolvedContext.groupedEditors[0].group);
    }
  }
};
var AbstractNavigateEditorAction = class extends $gJ {
  async run(accessor) {
    const editorGroupService = accessor.get($iJ);
    const result = this.a(editorGroupService);
    if (!result) {
      return;
    }
    const { groupId, editor } = result;
    if (!editor) {
      return;
    }
    const group2 = editorGroupService.getGroup(groupId);
    if (group2) {
      await group2.openEditor(editor);
    }
  }
};
var $jxb = class extends AbstractNavigateEditorAction {
  constructor() {
    super({
      id: "workbench.action.nextEditor",
      title: localize2(3390, "Open Next Editor"),
      f1: true,
      keybinding: {
        weight: 200,
        primary: 2048 | 12,
        mac: {
          primary: 2048 | 512 | 17,
          secondary: [
            2048 | 1024 | 94
            /* KeyCode.BracketRight */
          ]
        }
      },
      category: $qn.View
    });
  }
  a(editorGroupService) {
    const activeGroup = editorGroupService.activeGroup;
    const activeGroupEditors = activeGroup.getEditors(
      1
      /* EditorsOrder.SEQUENTIAL */
    );
    const activeEditorIndex = activeGroup.activeEditor ? activeGroupEditors.indexOf(activeGroup.activeEditor) : -1;
    if (activeEditorIndex + 1 < activeGroupEditors.length) {
      return { editor: activeGroupEditors[activeEditorIndex + 1], groupId: activeGroup.id };
    }
    const handledGroups = /* @__PURE__ */ new Set();
    let currentGroup = editorGroupService.activeGroup;
    while (currentGroup && !handledGroups.has(currentGroup.id)) {
      currentGroup = editorGroupService.findGroup({
        location: 2
        /* GroupLocation.NEXT */
      }, currentGroup, true);
      if (currentGroup) {
        handledGroups.add(currentGroup.id);
        const groupEditors = currentGroup.getEditors(
          1
          /* EditorsOrder.SEQUENTIAL */
        );
        if (groupEditors.length > 0) {
          return { editor: groupEditors[0], groupId: currentGroup.id };
        }
      }
    }
    return void 0;
  }
};
var $kxb = class extends AbstractNavigateEditorAction {
  constructor() {
    super({
      id: "workbench.action.previousEditor",
      title: localize2(3391, "Open Previous Editor"),
      f1: true,
      keybinding: {
        weight: 200,
        primary: 2048 | 11,
        mac: {
          primary: 2048 | 512 | 15,
          secondary: [
            2048 | 1024 | 92
            /* KeyCode.BracketLeft */
          ]
        }
      },
      category: $qn.View
    });
  }
  a(editorGroupService) {
    const activeGroup = editorGroupService.activeGroup;
    const activeGroupEditors = activeGroup.getEditors(
      1
      /* EditorsOrder.SEQUENTIAL */
    );
    const activeEditorIndex = activeGroup.activeEditor ? activeGroupEditors.indexOf(activeGroup.activeEditor) : -1;
    if (activeEditorIndex > 0) {
      return { editor: activeGroupEditors[activeEditorIndex - 1], groupId: activeGroup.id };
    }
    const handledGroups = /* @__PURE__ */ new Set();
    let currentGroup = editorGroupService.activeGroup;
    while (currentGroup && !handledGroups.has(currentGroup.id)) {
      currentGroup = editorGroupService.findGroup({
        location: 3
        /* GroupLocation.PREVIOUS */
      }, currentGroup, true);
      if (currentGroup) {
        handledGroups.add(currentGroup.id);
        const groupEditors = currentGroup.getEditors(
          1
          /* EditorsOrder.SEQUENTIAL */
        );
        if (groupEditors.length > 0) {
          return { editor: groupEditors[groupEditors.length - 1], groupId: currentGroup.id };
        }
      }
    }
    return void 0;
  }
};
var $lxb = class extends AbstractNavigateEditorAction {
  constructor() {
    super({
      id: "workbench.action.nextEditorInGroup",
      title: localize2(3392, "Open Next Editor in Group"),
      f1: true,
      keybinding: {
        weight: 200,
        primary: $$e(
          2048 | 41,
          2048 | 12
          /* KeyCode.PageDown */
        ),
        mac: {
          primary: $$e(
            2048 | 41,
            2048 | 512 | 17
            /* KeyCode.RightArrow */
          )
        }
      },
      category: $qn.View
    });
  }
  a(editorGroupService) {
    const group2 = editorGroupService.activeGroup;
    const editors = group2.getEditors(
      1
      /* EditorsOrder.SEQUENTIAL */
    );
    const index = group2.activeEditor ? editors.indexOf(group2.activeEditor) : -1;
    return { editor: index + 1 < editors.length ? editors[index + 1] : editors[0], groupId: group2.id };
  }
};
var $mxb = class extends AbstractNavigateEditorAction {
  constructor() {
    super({
      id: "workbench.action.previousEditorInGroup",
      title: localize2(3393, "Open Previous Editor in Group"),
      f1: true,
      keybinding: {
        weight: 200,
        primary: $$e(
          2048 | 41,
          2048 | 11
          /* KeyCode.PageUp */
        ),
        mac: {
          primary: $$e(
            2048 | 41,
            2048 | 512 | 15
            /* KeyCode.LeftArrow */
          )
        }
      },
      category: $qn.View
    });
  }
  a(editorGroupService) {
    const group2 = editorGroupService.activeGroup;
    const editors = group2.getEditors(
      1
      /* EditorsOrder.SEQUENTIAL */
    );
    const index = group2.activeEditor ? editors.indexOf(group2.activeEditor) : -1;
    return { editor: index > 0 ? editors[index - 1] : editors[editors.length - 1], groupId: group2.id };
  }
};
var $nxb = class extends AbstractNavigateEditorAction {
  constructor() {
    super({
      id: "workbench.action.firstEditorInGroup",
      title: localize2(3394, "Open First Editor in Group"),
      f1: true,
      category: $qn.View
    });
  }
  a(editorGroupService) {
    const group2 = editorGroupService.activeGroup;
    const editors = group2.getEditors(
      1
      /* EditorsOrder.SEQUENTIAL */
    );
    return { editor: editors[0], groupId: group2.id };
  }
};
var $oxb = class extends AbstractNavigateEditorAction {
  constructor() {
    super({
      id: "workbench.action.lastEditorInGroup",
      title: localize2(3395, "Open Last Editor in Group"),
      f1: true,
      keybinding: {
        weight: 200,
        primary: 512 | 21,
        secondary: [
          2048 | 30
          /* KeyCode.Digit9 */
        ],
        mac: {
          primary: 256 | 21,
          secondary: [
            2048 | 30
            /* KeyCode.Digit9 */
          ]
        }
      },
      category: $qn.View
    });
  }
  a(editorGroupService) {
    const group2 = editorGroupService.activeGroup;
    const editors = group2.getEditors(
      1
      /* EditorsOrder.SEQUENTIAL */
    );
    return { editor: editors[editors.length - 1], groupId: group2.id };
  }
};
var $pxb = class _$pxb extends $gJ {
  static {
    this.ID = "workbench.action.navigateForward";
  }
  static {
    this.LABEL = localize(3334, null);
  }
  constructor() {
    super({
      id: _$pxb.ID,
      title: {
        ...localize2(3396, "Go Forward"),
        mnemonicTitle: localize(3335, null)
      },
      f1: true,
      icon: $6l.arrowRight,
      precondition: $7m.has("canNavigateForward"),
      keybinding: {
        weight: 200,
        win: {
          primary: 512 | 17
          /* KeyCode.RightArrow */
        },
        mac: {
          primary: 256 | 1024 | 88
          /* KeyCode.Minus */
        },
        linux: {
          primary: 2048 | 1024 | 88
          /* KeyCode.Minus */
        }
      },
      menu: [
        { id: $bJ.MenubarGoMenu, group: "1_history_nav", order: 2 },
        { id: $bJ.CommandCenter, order: 2, when: $7m.has("config.workbench.navigationControl.enabled") }
      ]
    });
  }
  async run(accessor) {
    const historyService = accessor.get($tY);
    await historyService.goForward(
      0
      /* GoFilter.NONE */
    );
  }
};
var $qxb = class _$qxb extends $gJ {
  static {
    this.ID = "workbench.action.navigateBack";
  }
  static {
    this.LABEL = localize(3336, null);
  }
  constructor() {
    super({
      id: _$qxb.ID,
      title: {
        ...localize2(3397, "Go Back"),
        mnemonicTitle: localize(3337, null)
      },
      f1: true,
      precondition: $7m.has("canNavigateBack"),
      icon: $6l.arrowLeft,
      keybinding: {
        weight: 200,
        win: {
          primary: 512 | 15
          /* KeyCode.LeftArrow */
        },
        mac: {
          primary: 256 | 88
          /* KeyCode.Minus */
        },
        linux: {
          primary: 2048 | 512 | 88
          /* KeyCode.Minus */
        }
      },
      menu: [
        { id: $bJ.MenubarGoMenu, group: "1_history_nav", order: 1 },
        { id: $bJ.CommandCenter, order: 1, when: $7m.has("config.workbench.navigationControl.enabled") }
      ]
    });
  }
  async run(accessor) {
    const historyService = accessor.get($tY);
    await historyService.goBack(
      0
      /* GoFilter.NONE */
    );
  }
};
var $rxb = class extends $gJ {
  constructor() {
    super({
      id: "workbench.action.navigateLast",
      title: localize2(3398, "Go Previous"),
      f1: true
    });
  }
  async run(accessor) {
    const historyService = accessor.get($tY);
    await historyService.goPrevious(
      0
      /* GoFilter.NONE */
    );
  }
};
var $sxb = class extends $gJ {
  constructor() {
    super({
      id: "workbench.action.navigateForwardInEditLocations",
      title: localize2(3399, "Go Forward in Edit Locations"),
      f1: true
    });
  }
  async run(accessor) {
    const historyService = accessor.get($tY);
    await historyService.goForward(
      1
      /* GoFilter.EDITS */
    );
  }
};
var $txb = class extends $gJ {
  constructor() {
    super({
      id: "workbench.action.navigateBackInEditLocations",
      title: localize2(3400, "Go Back in Edit Locations"),
      f1: true
    });
  }
  async run(accessor) {
    const historyService = accessor.get($tY);
    await historyService.goBack(
      1
      /* GoFilter.EDITS */
    );
  }
};
var $uxb = class extends $gJ {
  constructor() {
    super({
      id: "workbench.action.navigatePreviousInEditLocations",
      title: localize2(3401, "Go Previous in Edit Locations"),
      f1: true
    });
  }
  async run(accessor) {
    const historyService = accessor.get($tY);
    await historyService.goPrevious(
      1
      /* GoFilter.EDITS */
    );
  }
};
var $vxb = class extends $gJ {
  constructor() {
    super({
      id: "workbench.action.navigateToLastEditLocation",
      title: localize2(3402, "Go to Last Edit Location"),
      f1: true,
      keybinding: {
        weight: 200,
        primary: $$e(
          2048 | 41,
          2048 | 47
          /* KeyCode.KeyQ */
        )
      }
    });
  }
  async run(accessor) {
    const historyService = accessor.get($tY);
    await historyService.goLast(
      1
      /* GoFilter.EDITS */
    );
  }
};
var $wxb = class extends $gJ {
  constructor() {
    super({
      id: "workbench.action.navigateForwardInNavigationLocations",
      title: localize2(3403, "Go Forward in Navigation Locations"),
      f1: true
    });
  }
  async run(accessor) {
    const historyService = accessor.get($tY);
    await historyService.goForward(
      2
      /* GoFilter.NAVIGATION */
    );
  }
};
var $xxb = class extends $gJ {
  constructor() {
    super({
      id: "workbench.action.navigateBackInNavigationLocations",
      title: localize2(3404, "Go Back in Navigation Locations"),
      f1: true
    });
  }
  async run(accessor) {
    const historyService = accessor.get($tY);
    await historyService.goBack(
      2
      /* GoFilter.NAVIGATION */
    );
  }
};
var $yxb = class extends $gJ {
  constructor() {
    super({
      id: "workbench.action.navigatePreviousInNavigationLocations",
      title: localize2(3405, "Go Previous in Navigation Locations"),
      f1: true
    });
  }
  async run(accessor) {
    const historyService = accessor.get($tY);
    await historyService.goPrevious(
      2
      /* GoFilter.NAVIGATION */
    );
  }
};
var $zxb = class extends $gJ {
  constructor() {
    super({
      id: "workbench.action.navigateToLastNavigationLocation",
      title: localize2(3406, "Go to Last Navigation Location"),
      f1: true
    });
  }
  async run(accessor) {
    const historyService = accessor.get($tY);
    await historyService.goLast(
      2
      /* GoFilter.NAVIGATION */
    );
  }
};
var $Axb = class _$Axb extends $gJ {
  static {
    this.ID = "workbench.action.reopenClosedEditor";
  }
  constructor() {
    super({
      id: _$Axb.ID,
      title: localize2(3407, "Reopen Closed Editor"),
      f1: true,
      keybinding: {
        weight: 200,
        primary: 2048 | 1024 | 50
        /* KeyCode.KeyT */
      },
      category: $qn.View
    });
  }
  async run(accessor) {
    const historyService = accessor.get($tY);
    await historyService.reopenLastClosedEditor();
  }
};
var $Bxb = class _$Bxb extends $gJ {
  static {
    this.ID = "workbench.action.clearRecentFiles";
  }
  constructor() {
    super({
      id: _$Bxb.ID,
      title: localize2(3408, "Clear Recently Opened..."),
      f1: true,
      category: $qn.File
    });
  }
  async run(accessor) {
    const dialogService = accessor.get($Yv);
    const workspacesService = accessor.get($2w);
    const historyService = accessor.get($tY);
    const { confirmed } = await dialogService.confirm({
      type: "warning",
      message: localize(3338, null),
      detail: localize(3339, null),
      primaryButton: localize(3340, null)
    });
    if (!confirmed) {
      return;
    }
    workspacesService.clearRecentlyOpened();
    historyService.clearRecentlyOpened();
  }
};
var $Cxb = class _$Cxb extends $gJ {
  static {
    this.ID = "workbench.action.showEditorsInActiveGroup";
  }
  constructor() {
    super({
      id: _$Cxb.ID,
      title: localize2(3409, "Show Editors in Active Group By Most Recently Used"),
      f1: true,
      category: $qn.View
    });
  }
  async run(accessor) {
    const quickInputService = accessor.get($1M);
    quickInputService.quickAccess.show($2tb.PREFIX);
  }
};
var $Dxb = class _$Dxb extends $gJ {
  static {
    this.ID = "workbench.action.showAllEditors";
  }
  constructor() {
    super({
      id: _$Dxb.ID,
      title: localize2(3410, "Show All Editors By Appearance"),
      f1: true,
      keybinding: {
        weight: 200,
        primary: $$e(
          2048 | 41,
          2048 | 46
          /* KeyCode.KeyP */
        ),
        mac: {
          primary: 2048 | 512 | 2
          /* KeyCode.Tab */
        }
      },
      category: $qn.File
    });
  }
  async run(accessor) {
    const quickInputService = accessor.get($1M);
    quickInputService.quickAccess.show($3tb.PREFIX);
  }
};
var $Exb = class _$Exb extends $gJ {
  static {
    this.ID = "workbench.action.showAllEditorsByMostRecentlyUsed";
  }
  constructor() {
    super({
      id: _$Exb.ID,
      title: localize2(3411, "Show All Editors By Most Recently Used"),
      f1: true,
      category: $qn.View
    });
  }
  async run(accessor) {
    const quickInputService = accessor.get($1M);
    quickInputService.quickAccess.show($4tb.PREFIX);
  }
};
var AbstractQuickAccessEditorAction = class extends $gJ {
  constructor(desc, a, b) {
    super(desc);
    this.a = a;
    this.b = b;
  }
  async run(accessor) {
    const keybindingService = accessor.get($Ty);
    const quickInputService = accessor.get($1M);
    const keybindings = keybindingService.lookupKeybindings(this.desc.id);
    quickInputService.quickAccess.show(this.a, {
      quickNavigateConfiguration: { keybindings },
      itemActivation: this.b
    });
  }
};
var $Fxb = class extends AbstractQuickAccessEditorAction {
  constructor() {
    super({
      id: "workbench.action.quickOpenPreviousRecentlyUsedEditor",
      title: localize2(3412, "Quick Open Previous Recently Used Editor"),
      f1: true,
      category: $qn.View
    }, $4tb.PREFIX, void 0);
  }
};
var $Gxb = class extends AbstractQuickAccessEditorAction {
  constructor() {
    super({
      id: "workbench.action.quickOpenLeastRecentlyUsedEditor",
      title: localize2(3413, "Quick Open Least Recently Used Editor"),
      f1: true,
      category: $qn.View
    }, $4tb.PREFIX, void 0);
  }
};
var $Hxb = class extends AbstractQuickAccessEditorAction {
  constructor() {
    super({
      id: "workbench.action.quickOpenPreviousRecentlyUsedEditorInGroup",
      title: localize2(3414, "Quick Open Previous Recently Used Editor in Group"),
      f1: true,
      keybinding: {
        weight: 200,
        primary: 2048 | 2,
        mac: {
          primary: 256 | 2
          /* KeyCode.Tab */
        }
      },
      precondition: $Jpb.toNegated(),
      category: $qn.View
    }, $2tb.PREFIX, void 0);
  }
};
var $Ixb = class extends AbstractQuickAccessEditorAction {
  constructor() {
    super({
      id: "workbench.action.quickOpenLeastRecentlyUsedEditorInGroup",
      title: localize2(3415, "Quick Open Least Recently Used Editor in Group"),
      f1: true,
      keybinding: {
        weight: 200,
        primary: 2048 | 1024 | 2,
        mac: {
          primary: 256 | 1024 | 2
          /* KeyCode.Tab */
        }
      },
      precondition: $Jpb.toNegated(),
      category: $qn.View
    }, $2tb.PREFIX, ItemActivation.LAST);
  }
};
var $Jxb = class _$Jxb extends $gJ {
  static {
    this.a = "workbench.action.openPreviousEditorFromHistory";
  }
  constructor() {
    super({
      id: _$Jxb.a,
      title: localize2(3416, "Quick Open Previous Editor from History"),
      f1: true
    });
  }
  async run(accessor) {
    const keybindingService = accessor.get($Ty);
    const quickInputService = accessor.get($1M);
    const editorGroupService = accessor.get($iJ);
    const keybindings = keybindingService.lookupKeybindings(_$Jxb.a);
    let itemActivation = void 0;
    if (editorGroupService.activeGroup.count === 0) {
      itemActivation = ItemActivation.FIRST;
    }
    quickInputService.quickAccess.show("", { quickNavigateConfiguration: { keybindings }, itemActivation });
  }
};
var $Kxb = class extends $gJ {
  constructor() {
    super({
      id: "workbench.action.openNextRecentlyUsedEditor",
      title: localize2(3417, "Open Next Recently Used Editor"),
      f1: true,
      category: $qn.View
    });
  }
  async run(accessor) {
    const historyService = accessor.get($tY);
    historyService.openNextRecentlyUsedEditor();
  }
};
var $Lxb = class extends $gJ {
  constructor() {
    super({
      id: "workbench.action.openPreviousRecentlyUsedEditor",
      title: localize2(3418, "Open Previous Recently Used Editor"),
      f1: true,
      category: $qn.View
    });
  }
  async run(accessor) {
    const historyService = accessor.get($tY);
    historyService.openPreviouslyUsedEditor();
  }
};
var $Mxb = class extends $gJ {
  constructor() {
    super({
      id: "workbench.action.openNextRecentlyUsedEditorInGroup",
      title: localize2(3419, "Open Next Recently Used Editor In Group"),
      f1: true,
      category: $qn.View
    });
  }
  async run(accessor) {
    const historyService = accessor.get($tY);
    const editorGroupsService = accessor.get($iJ);
    historyService.openNextRecentlyUsedEditor(editorGroupsService.activeGroup.id);
  }
};
var $Nxb = class extends $gJ {
  constructor() {
    super({
      id: "workbench.action.openPreviousRecentlyUsedEditorInGroup",
      title: localize2(3420, "Open Previous Recently Used Editor In Group"),
      f1: true,
      category: $qn.View
    });
  }
  async run(accessor) {
    const historyService = accessor.get($tY);
    const editorGroupsService = accessor.get($iJ);
    historyService.openPreviouslyUsedEditor(editorGroupsService.activeGroup.id);
  }
};
var $Oxb = class extends $gJ {
  constructor() {
    super({
      id: "workbench.action.clearEditorHistory",
      title: localize2(3421, "Clear Editor History"),
      f1: true
    });
  }
  async run(accessor) {
    const dialogService = accessor.get($Yv);
    const historyService = accessor.get($tY);
    const { confirmed } = await dialogService.confirm({
      type: "warning",
      message: localize(3341, null),
      detail: localize(3342, null),
      primaryButton: localize(3343, null)
    });
    if (!confirmed) {
      return;
    }
    historyService.clear();
  }
};
var $Pxb = class extends ExecuteCommandAction {
  constructor() {
    super({
      id: "workbench.action.moveEditorLeftInGroup",
      title: localize2(3422, "Move Editor Left"),
      keybinding: {
        weight: 200,
        primary: 2048 | 1024 | 11,
        mac: {
          primary: $$e(
            2048 | 41,
            2048 | 1024 | 15
            /* KeyCode.LeftArrow */
          )
        }
      },
      f1: true,
      category: $qn.View
    }, $Bub, { to: "left" });
  }
};
var $Qxb = class extends ExecuteCommandAction {
  constructor() {
    super({
      id: "workbench.action.moveEditorRightInGroup",
      title: localize2(3423, "Move Editor Right"),
      keybinding: {
        weight: 200,
        primary: 2048 | 1024 | 12,
        mac: {
          primary: $$e(
            2048 | 41,
            2048 | 1024 | 17
            /* KeyCode.RightArrow */
          )
        }
      },
      f1: true,
      category: $qn.View
    }, $Bub, { to: "right" });
  }
};
var $Rxb = class extends ExecuteCommandAction {
  constructor() {
    super({
      id: "workbench.action.moveEditorToPreviousGroup",
      title: localize2(3424, "Move Editor into Previous Group"),
      keybinding: {
        weight: 200,
        primary: 2048 | 512 | 15,
        mac: {
          primary: 2048 | 256 | 15
          /* KeyCode.LeftArrow */
        }
      },
      f1: true,
      category: $qn.View
    }, $Bub, { to: "previous", by: "group" });
  }
};
var $Sxb = class extends ExecuteCommandAction {
  constructor() {
    super({
      id: "workbench.action.moveEditorToNextGroup",
      title: localize2(3425, "Move Editor into Next Group"),
      f1: true,
      keybinding: {
        weight: 200,
        primary: 2048 | 512 | 17,
        mac: {
          primary: 2048 | 256 | 17
          /* KeyCode.RightArrow */
        }
      },
      category: $qn.View
    }, $Bub, { to: "next", by: "group" });
  }
};
var $Txb = class extends ExecuteCommandAction {
  constructor() {
    super({
      id: "workbench.action.moveEditorToAboveGroup",
      title: localize2(3426, "Move Editor into Group Above"),
      f1: true,
      category: $qn.View
    }, $Bub, { to: "up", by: "group" });
  }
};
var $Uxb = class extends ExecuteCommandAction {
  constructor() {
    super({
      id: "workbench.action.moveEditorToBelowGroup",
      title: localize2(3427, "Move Editor into Group Below"),
      f1: true,
      category: $qn.View
    }, $Bub, { to: "down", by: "group" });
  }
};
var $Vxb = class extends ExecuteCommandAction {
  constructor() {
    super({
      id: "workbench.action.moveEditorToLeftGroup",
      title: localize2(3428, "Move Editor into Left Group"),
      f1: true,
      category: $qn.View
    }, $Bub, { to: "left", by: "group" });
  }
};
var $Wxb = class extends ExecuteCommandAction {
  constructor() {
    super({
      id: "workbench.action.moveEditorToRightGroup",
      title: localize2(3429, "Move Editor into Right Group"),
      f1: true,
      category: $qn.View
    }, $Bub, { to: "right", by: "group" });
  }
};
var $Xxb = class extends ExecuteCommandAction {
  constructor() {
    super({
      id: "workbench.action.moveEditorToFirstGroup",
      title: localize2(3430, "Move Editor into First Group"),
      f1: true,
      keybinding: {
        weight: 200,
        primary: 1024 | 512 | 22,
        mac: {
          primary: 2048 | 256 | 22
          /* KeyCode.Digit1 */
        }
      },
      category: $qn.View
    }, $Bub, { to: "first", by: "group" });
  }
};
var $Yxb = class extends ExecuteCommandAction {
  constructor() {
    super({
      id: "workbench.action.moveEditorToLastGroup",
      title: localize2(3431, "Move Editor into Last Group"),
      f1: true,
      keybinding: {
        weight: 200,
        primary: 1024 | 512 | 30,
        mac: {
          primary: 2048 | 256 | 30
          /* KeyCode.Digit9 */
        }
      },
      category: $qn.View
    }, $Bub, { to: "last", by: "group" });
  }
};
var $Zxb = class extends ExecuteCommandAction {
  constructor() {
    super({
      id: "workbench.action.splitEditorToPreviousGroup",
      title: localize2(3432, "Split Editor into Previous Group"),
      f1: true,
      category: $qn.View
    }, $Cub, { to: "previous", by: "group" });
  }
};
var $1xb = class extends ExecuteCommandAction {
  constructor() {
    super({
      id: "workbench.action.splitEditorToNextGroup",
      title: localize2(3433, "Split Editor into Next Group"),
      f1: true,
      category: $qn.View
    }, $Cub, { to: "next", by: "group" });
  }
};
var $2xb = class extends ExecuteCommandAction {
  constructor() {
    super({
      id: "workbench.action.splitEditorToAboveGroup",
      title: localize2(3434, "Split Editor into Group Above"),
      f1: true,
      category: $qn.View
    }, $Cub, { to: "up", by: "group" });
  }
};
var $3xb = class extends ExecuteCommandAction {
  constructor() {
    super({
      id: "workbench.action.splitEditorToBelowGroup",
      title: localize2(3435, "Split Editor into Group Below"),
      f1: true,
      category: $qn.View
    }, $Cub, { to: "down", by: "group" });
  }
};
var $4xb = class extends ExecuteCommandAction {
  static {
    this.ID = "workbench.action.splitEditorToLeftGroup";
  }
  static {
    this.LABEL = localize(3344, null);
  }
  constructor() {
    super({
      id: "workbench.action.splitEditorToLeftGroup",
      title: localize2(3436, "Split Editor into Left Group"),
      f1: true,
      category: $qn.View
    }, $Cub, { to: "left", by: "group" });
  }
};
var $5xb = class extends ExecuteCommandAction {
  constructor() {
    super({
      id: "workbench.action.splitEditorToRightGroup",
      title: localize2(3437, "Split Editor into Right Group"),
      f1: true,
      category: $qn.View
    }, $Cub, { to: "right", by: "group" });
  }
};
var $6xb = class extends ExecuteCommandAction {
  constructor() {
    super({
      id: "workbench.action.splitEditorToFirstGroup",
      title: localize2(3438, "Split Editor into First Group"),
      f1: true,
      category: $qn.View
    }, $Cub, { to: "first", by: "group" });
  }
};
var $7xb = class extends ExecuteCommandAction {
  constructor() {
    super({
      id: "workbench.action.splitEditorToLastGroup",
      title: localize2(3439, "Split Editor into Last Group"),
      f1: true,
      category: $qn.View
    }, $Cub, { to: "last", by: "group" });
  }
};
var $8xb = class _$8xb extends ExecuteCommandAction {
  static {
    this.ID = "workbench.action.editorLayoutSingle";
  }
  constructor() {
    super({
      id: _$8xb.ID,
      title: localize2(3440, "Single Column Editor Layout"),
      f1: true,
      category: $qn.View
    }, $Dub, {
      groups: [{}],
      orientation: 0
      /* GroupOrientation.HORIZONTAL */
    });
  }
};
var $9xb = class _$9xb extends ExecuteCommandAction {
  static {
    this.ID = "workbench.action.editorLayoutTwoColumns";
  }
  constructor() {
    super({
      id: _$9xb.ID,
      title: localize2(3441, "Two Columns Editor Layout"),
      f1: true,
      category: $qn.View
    }, $Dub, {
      groups: [{}, {}],
      orientation: 0
      /* GroupOrientation.HORIZONTAL */
    });
  }
};
var $0xb = class _$0xb extends ExecuteCommandAction {
  static {
    this.ID = "workbench.action.editorLayoutThreeColumns";
  }
  constructor() {
    super({
      id: _$0xb.ID,
      title: localize2(3442, "Three Columns Editor Layout"),
      f1: true,
      category: $qn.View
    }, $Dub, {
      groups: [{}, {}, {}],
      orientation: 0
      /* GroupOrientation.HORIZONTAL */
    });
  }
};
var $$xb = class _$$xb extends ExecuteCommandAction {
  static {
    this.ID = "workbench.action.editorLayoutTwoRows";
  }
  constructor() {
    super({
      id: _$$xb.ID,
      title: localize2(3443, "Two Rows Editor Layout"),
      f1: true,
      category: $qn.View
    }, $Dub, {
      groups: [{}, {}],
      orientation: 1
      /* GroupOrientation.VERTICAL */
    });
  }
};
var $_xb = class _$_xb extends ExecuteCommandAction {
  static {
    this.ID = "workbench.action.editorLayoutThreeRows";
  }
  constructor() {
    super({
      id: _$_xb.ID,
      title: localize2(3444, "Three Rows Editor Layout"),
      f1: true,
      category: $qn.View
    }, $Dub, {
      groups: [{}, {}, {}],
      orientation: 1
      /* GroupOrientation.VERTICAL */
    });
  }
};
var $ayb = class _$ayb extends ExecuteCommandAction {
  static {
    this.ID = "workbench.action.editorLayoutTwoByTwoGrid";
  }
  constructor() {
    super({
      id: _$ayb.ID,
      title: localize2(3445, "Grid Editor Layout (2x2)"),
      f1: true,
      category: $qn.View
    }, $Dub, {
      groups: [{ groups: [{}, {}] }, { groups: [{}, {}] }],
      orientation: 0
      /* GroupOrientation.HORIZONTAL */
    });
  }
};
var $byb = class _$byb extends ExecuteCommandAction {
  static {
    this.ID = "workbench.action.editorLayoutTwoColumnsBottom";
  }
  constructor() {
    super({
      id: _$byb.ID,
      title: localize2(3446, "Two Columns Bottom Editor Layout"),
      f1: true,
      category: $qn.View
    }, $Dub, {
      groups: [{}, { groups: [{}, {}] }],
      orientation: 1
      /* GroupOrientation.VERTICAL */
    });
  }
};
var $cyb = class _$cyb extends ExecuteCommandAction {
  static {
    this.ID = "workbench.action.editorLayoutTwoRowsRight";
  }
  constructor() {
    super({
      id: _$cyb.ID,
      title: localize2(3447, "Two Rows Right Editor Layout"),
      f1: true,
      category: $qn.View
    }, $Dub, {
      groups: [{}, { groups: [{}, {}] }],
      orientation: 0
      /* GroupOrientation.HORIZONTAL */
    });
  }
};
var AbstractCreateEditorGroupAction = class extends $gJ {
  constructor(desc, a) {
    super(desc);
    this.a = a;
  }
  async run(accessor) {
    const editorGroupService = accessor.get($iJ);
    const layoutService = accessor.get($Vlb);
    const activeDocument = $Pj();
    const focusNewGroup = layoutService.hasFocus(
      "workbench.parts.editor"
      /* Parts.EDITOR_PART */
    ) || activeDocument.activeElement === activeDocument.body;
    const group2 = editorGroupService.addGroup(editorGroupService.activeGroup, this.a);
    editorGroupService.activateGroup(group2);
    if (focusNewGroup) {
      group2.focus();
    }
  }
};
var $dyb = class extends AbstractCreateEditorGroupAction {
  constructor() {
    super(
      {
        id: "workbench.action.newGroupLeft",
        title: localize2(3448, "New Editor Group to the Left"),
        f1: true,
        category: $qn.View
      },
      2
      /* GroupDirection.LEFT */
    );
  }
};
var $eyb = class extends AbstractCreateEditorGroupAction {
  constructor() {
    super(
      {
        id: "workbench.action.newGroupRight",
        title: localize2(3449, "New Editor Group to the Right"),
        f1: true,
        category: $qn.View
      },
      3
      /* GroupDirection.RIGHT */
    );
  }
};
var $fyb = class extends AbstractCreateEditorGroupAction {
  constructor() {
    super(
      {
        id: "workbench.action.newGroupAbove",
        title: localize2(3450, "New Editor Group Above"),
        f1: true,
        category: $qn.View
      },
      0
      /* GroupDirection.UP */
    );
  }
};
var $gyb = class extends AbstractCreateEditorGroupAction {
  constructor() {
    super(
      {
        id: "workbench.action.newGroupBelow",
        title: localize2(3451, "New Editor Group Below"),
        f1: true,
        category: $qn.View
      },
      1
      /* GroupDirection.DOWN */
    );
  }
};
var $hyb = class extends $gJ {
  constructor() {
    super({
      id: "workbench.action.toggleEditorType",
      title: localize2(3452, "Toggle Editor Type"),
      f1: true,
      category: $qn.View,
      precondition: $Epb
    });
  }
  async run(accessor) {
    const editorService = accessor.get($mJ);
    const editorResolverService = accessor.get($4L);
    const activeEditorPane = editorService.activeEditorPane;
    if (!activeEditorPane) {
      return;
    }
    const activeEditorResource = $mL.getCanonicalUri(activeEditorPane.input);
    if (!activeEditorResource) {
      return;
    }
    const editorIds = editorResolverService.getEditors(activeEditorResource).map((editor) => editor.id).filter((id2) => id2 !== activeEditorPane.input.editorId);
    if (editorIds.length === 0) {
      return;
    }
    await editorService.replaceEditors([
      {
        editor: activeEditorPane.input,
        replacement: {
          resource: activeEditorResource,
          options: {
            override: editorIds[0]
          }
        }
      }
    ], activeEditorPane.group);
  }
};
var $iyb = class extends $gJ {
  constructor() {
    super({
      id: "workbench.action.reopenTextEditor",
      title: localize2(3453, "Reopen Editor With Text Editor"),
      f1: true,
      category: $qn.View,
      precondition: $Epb
    });
  }
  async run(accessor) {
    const editorService = accessor.get($mJ);
    const activeEditorPane = editorService.activeEditorPane;
    if (!activeEditorPane) {
      return;
    }
    const activeEditorResource = $mL.getCanonicalUri(activeEditorPane.input);
    if (!activeEditorResource) {
      return;
    }
    await editorService.replaceEditors([
      {
        editor: activeEditorPane.input,
        replacement: {
          resource: activeEditorResource,
          options: {
            override: $1K.id
          }
        }
      }
    ], activeEditorPane.group);
  }
};
var BaseMoveCopyEditorToNewWindowAction = class extends $gJ {
  constructor(id2, title, keybinding, a) {
    super({
      id: id2,
      title,
      category: $qn.View,
      precondition: $Dpb,
      keybinding,
      f1: true
    });
    this.a = a;
  }
  async run(accessor, ...args2) {
    const editorGroupService = accessor.get($iJ);
    const resolvedContext = $sub(args2, accessor.get($mJ), editorGroupService, accessor.get($Deb));
    if (!resolvedContext.groupedEditors.length) {
      return;
    }
    const auxiliaryEditorPart = await editorGroupService.createAuxiliaryEditorPart();
    const { group: group2, editors } = resolvedContext.groupedEditors[0];
    const options3 = { preserveFocus: resolvedContext.preserveFocus };
    const editorsWithOptions = editors.map((editor) => ({ editor, options: options3 }));
    if (this.a) {
      group2.moveEditors(editorsWithOptions, auxiliaryEditorPart.activeGroup);
    } else {
      group2.copyEditors(editorsWithOptions, auxiliaryEditorPart.activeGroup);
    }
    auxiliaryEditorPart.activeGroup.focus();
  }
};
var $jyb = class extends BaseMoveCopyEditorToNewWindowAction {
  constructor() {
    super($6ub, {
      ...localize2(3454, "Move Editor into New Window"),
      mnemonicTitle: localize(3345, null)
    }, void 0, true);
  }
};
var $kyb = class extends BaseMoveCopyEditorToNewWindowAction {
  constructor() {
    super($7ub, {
      ...localize2(3455, "Copy Editor into New Window"),
      mnemonicTitle: localize(3346, null)
    }, {
      primary: $$e(
        2048 | 41,
        45
        /* KeyCode.KeyO */
      ),
      weight: 200
      /* KeybindingWeight.WorkbenchContrib */
    }, false);
  }
};
var BaseMoveCopyEditorGroupToNewWindowAction = class extends $gJ {
  constructor(id2, title, a) {
    super({
      id: id2,
      title,
      category: $qn.View,
      f1: true
    });
    this.a = a;
  }
  async run(accessor) {
    const editorGroupService = accessor.get($iJ);
    const activeGroup = editorGroupService.activeGroup;
    const auxiliaryEditorPart = await editorGroupService.createAuxiliaryEditorPart();
    editorGroupService.mergeGroup(activeGroup, auxiliaryEditorPart.activeGroup, {
      mode: this.a ? 1 : 0
      /* MergeGroupMode.COPY_EDITORS */
    });
    auxiliaryEditorPart.activeGroup.focus();
  }
};
var $lyb = class extends BaseMoveCopyEditorGroupToNewWindowAction {
  constructor() {
    super($8ub, {
      ...localize2(3456, "Move Editor Group into New Window"),
      mnemonicTitle: localize(3347, null)
    }, true);
  }
};
var $myb = class extends BaseMoveCopyEditorGroupToNewWindowAction {
  constructor() {
    super($9ub, {
      ...localize2(3457, "Copy Editor Group into New Window"),
      mnemonicTitle: localize(3348, null)
    }, false);
  }
};
var $nyb = class extends $gJ {
  constructor() {
    super({
      id: "workbench.action.restoreEditorsToMainWindow",
      title: {
        ...localize2(3458, "Restore Editors into Main Window"),
        mnemonicTitle: localize(3349, null)
      },
      f1: true,
      precondition: $opb,
      category: $qn.View
    });
  }
  async run(accessor) {
    const editorGroupService = accessor.get($iJ);
    editorGroupService.mergeAllGroups(editorGroupService.mainPart.activeGroup);
  }
};
var $oyb = class extends $gJ {
  constructor() {
    super({
      id: $0ub,
      title: {
        ...localize2(3459, "New Empty Editor Window"),
        mnemonicTitle: localize(3350, null)
      },
      f1: true,
      category: $qn.View
    });
  }
  async run(accessor) {
    const editorGroupService = accessor.get($iJ);
    const auxiliaryEditorPart = await editorGroupService.createAuxiliaryEditorPart();
    auxiliaryEditorPart.activeGroup.focus();
  }
};
var $pyb = class extends $gJ {
  constructor() {
    super({
      id: "editor.action.toggleOvertypeInsertMode",
      title: {
        ...localize2(3460, "Toggle Overtype/Insert Mode"),
        mnemonicTitle: localize(3351, null)
      },
      metadata: {
        description: localize2(3461, "Toggle between overtype and insert mode")
      },
      keybinding: {
        weight: 200,
        primary: 19,
        mac: {
          primary: 512 | 2048 | 45
          /* KeyCode.KeyO */
        }
      },
      f1: true,
      category: $qn.View
    });
  }
  async run(accessor) {
    const oldInputMode = $04.getInputMode();
    const newInputMode = oldInputMode === "insert" ? "overtype" : "insert";
    $04.setInputMode(newInputMode);
  }
};

// out-build/vs/base/browser/broadcast.js
var $iZ = class extends $3c {
  constructor(c) {
    super();
    this.c = c;
    this.b = this.B(new $ze());
    this.onDidReceiveData = this.b.event;
    if ("BroadcastChannel" in $Y) {
      try {
        this.a = new BroadcastChannel(c);
        const listener = (event) => {
          this.b.fire(event.data);
        };
        this.a.addEventListener("message", listener);
        this.B($1c(() => {
          if (this.a) {
            this.a.removeEventListener("message", listener);
            this.a.close();
          }
        }));
      } catch (error) {
        console.warn("Error while creating broadcast channel. Falling back to localStorage.", $qb(error));
      }
    }
    if (!this.a) {
      this.c = `BroadcastDataChannel.${c}`;
      this.f();
    }
  }
  f() {
    const listener = (event) => {
      if (event.key === this.c && event.newValue) {
        this.b.fire(JSON.parse(event.newValue));
      }
    };
    $Y.addEventListener("storage", listener);
    this.B($1c(() => $Y.removeEventListener("storage", listener)));
  }
  /**
   * Sends the data to other BroadcastChannel objects set up for this channel. Data can be structured objects, e.g. nested objects and arrays.
   * @param data data to broadcast
   */
  postData(data) {
    if (this.a) {
      this.a.postMessage(data);
    } else {
      localStorage.removeItem(this.c);
      localStorage.setItem(this.c, JSON.stringify(data));
    }
  }
};

// out-build/vs/workbench/browser/dnd.js
var $Aob = class {
  constructor(identifier2) {
    this.identifier = identifier2;
  }
};
var $Bob = class {
  constructor(identifier2) {
    this.identifier = identifier2;
  }
};
async function $Cob(dataTransfer) {
  const editors = [];
  const resourcesKey = $YC.uriList.toLowerCase();
  if (dataTransfer.has(resourcesKey)) {
    try {
      const asString = await dataTransfer.get(resourcesKey)?.asString();
      const rawResourcesData = JSON.stringify($nE.parse(asString ?? ""));
      editors.push(...$x_(rawResourcesData));
    } catch (error) {
    }
  }
  return editors;
}
var $Dob = class $Dob2 {
  constructor(a, b, c, d, f, g, h3, i2) {
    this.a = a;
    this.b = b;
    this.c = c;
    this.d = d;
    this.f = f;
    this.g = g;
    this.h = h3;
    this.i = i2;
  }
  async handleDrop(event, targetWindow, resolveTargetGroup, afterDrop, options3) {
    const editors = await this.i.invokeFunction((accessor) => $w_(accessor, event));
    if (!editors.length) {
      return;
    }
    await this.g.focus(targetWindow);
    if (this.a.allowWorkspaceOpen) {
      const localFilesAllowedToOpenAsWorkspace = $Mb(editors.filter((editor) => editor.allowWorkspaceOpen && editor.resource?.scheme === Schemas.file).map((editor) => editor.resource));
      if (localFilesAllowedToOpenAsWorkspace.length > 0) {
        const isWorkspaceOpening = await this.j(localFilesAllowedToOpenAsWorkspace);
        if (isWorkspaceOpening) {
          return;
        }
      }
    }
    const externalLocalFiles = $Mb(editors.filter((editor) => editor.isExternal && editor.resource?.scheme === Schemas.file).map((editor) => editor.resource));
    if (externalLocalFiles.length) {
      this.c.addRecentlyOpened(externalLocalFiles.map((resource) => ({ fileUri: resource })));
    }
    const targetGroup = resolveTargetGroup?.();
    await this.d.openEditors(editors.map((editor) => ({
      ...editor,
      resource: editor.resource,
      options: {
        ...editor.options,
        ...options3,
        pinned: true
      }
    })), targetGroup, { validateTrust: true });
    afterDrop?.(targetGroup);
  }
  async j(resources) {
    const toOpen = [];
    const folderURIs = [];
    await Promise.all(resources.map(async (resource) => {
      if ($jl(resource)) {
        toOpen.push({ workspaceUri: resource });
        return;
      }
      try {
        const stat = await this.b.stat(resource);
        if (stat.isDirectory) {
          toOpen.push({ folderUri: stat.resource });
          folderURIs.push({ uri: stat.resource });
        }
      } catch (error) {
      }
    }));
    if (toOpen.length === 0) {
      return false;
    }
    if (toOpen.length > folderURIs.length || folderURIs.length === 1) {
      await this.g.openWindow(toOpen);
    } else if ($fl(this.h.getWorkspace())) {
      await this.f.addFolders(folderURIs);
    } else {
      await this.f.createAndEnterWorkspace(folderURIs);
    }
    return true;
  }
};
$Dob = __decorate([
  __param(1, $km),
  __param(2, $2w),
  __param(3, $mJ),
  __param(4, $zob),
  __param(5, $S4),
  __param(6, $Zk),
  __param(7, $Pk)
], $Dob);
function $Eob(accessor, resourcesOrEditors, event, options3) {
  if (resourcesOrEditors.length === 0 || !event.dataTransfer) {
    return;
  }
  const textFileService = accessor.get($cK);
  const editorService = accessor.get($mJ);
  const fileService = accessor.get($km);
  const labelService = accessor.get($ZI);
  const resources = $Mb(resourcesOrEditors.map((resourceOrEditor) => {
    if (URI.isUri(resourceOrEditor)) {
      return { resource: resourceOrEditor };
    }
    if ($jL(resourceOrEditor)) {
      if (URI.isUri(resourceOrEditor.editor.resource)) {
        return { resource: resourceOrEditor.editor.resource };
      }
      return void 0;
    }
    return { ...resourceOrEditor, resource: resourceOrEditor.selection ? $P4(resourceOrEditor.resource, resourceOrEditor.selection) : resourceOrEditor.resource };
  }));
  const fileSystemResources = resources.filter(({ resource }) => fileService.hasProvider(resource));
  if (!options3?.disableStandardTransfer) {
    const lineDelimiter2 = $l ? "\r\n" : "\n";
    event.dataTransfer.setData($kZ.TEXT, fileSystemResources.map(({ resource }) => labelService.getUriLabel(resource, { noPrefix: true })).join(lineDelimiter2));
    const firstFile = fileSystemResources.find(({ isDirectory }) => !isDirectory);
    if (firstFile) {
      const firstFileUri = $ih.uriToFileUri(firstFile.resource);
      if (firstFileUri.scheme === Schemas.file) {
        event.dataTransfer.setData($kZ.DOWNLOAD_URL, [$YC.binary, $sh(firstFile.resource), firstFileUri.toString()].join(":"));
      }
    }
  }
  const files = fileSystemResources.filter(({ isDirectory }) => !isDirectory);
  if (files.length) {
    event.dataTransfer.setData($kZ.RESOURCES, JSON.stringify(files.map(({ resource }) => resource.toString())));
  }
  const contributions = $Wn.as($A_.DragAndDropContribution).getAll();
  for (const contribution of contributions) {
    contribution.setData(resources, event);
  }
  const draggedEditors = [];
  for (const resourceOrEditor of resourcesOrEditors) {
    let editor = void 0;
    if ($jL(resourceOrEditor)) {
      const untypedEditor = resourceOrEditor.editor.toUntyped({ preserveViewState: resourceOrEditor.groupId });
      if (untypedEditor) {
        editor = { ...untypedEditor, resource: $mL.getCanonicalUri(untypedEditor) };
      }
    } else if (URI.isUri(resourceOrEditor)) {
      const { selection, uri } = $Q4(resourceOrEditor);
      editor = { resource: uri, options: selection ? { selection } : void 0 };
    } else if (!resourceOrEditor.isDirectory) {
      editor = {
        resource: resourceOrEditor.resource,
        options: {
          selection: resourceOrEditor.selection
        }
      };
    }
    if (!editor) {
      continue;
    }
    {
      const resource = editor.resource;
      if (resource) {
        const textFileModel = textFileService.files.get(resource);
        if (textFileModel) {
          if (typeof editor.languageId !== "string") {
            editor.languageId = textFileModel.getLanguageId();
          }
          if (typeof editor.encoding !== "string") {
            editor.encoding = textFileModel.getEncoding();
          }
          if (typeof editor.contents !== "string" && textFileModel.isDirty() && !textFileModel.textEditorModel.isTooLargeForHeapOperation()) {
            editor.contents = textFileModel.textEditorModel.getValue();
          }
        }
        if (!editor.options?.viewState) {
          editor.options = {
            ...editor.options,
            viewState: (() => {
              for (const visibleEditorPane of editorService.visibleEditorPanes) {
                if ($oh(visibleEditorPane.input.resource, resource)) {
                  const viewState = visibleEditorPane.getViewState();
                  if (viewState) {
                    return viewState;
                  }
                }
              }
              return void 0;
            })()
          };
        }
      }
    }
    draggedEditors.push(editor);
  }
  if (draggedEditors.length) {
    event.dataTransfer.setData($u_.EDITORS, $au(draggedEditors));
    const uriListEntries = [];
    for (const editor of draggedEditors) {
      if (editor.resource) {
        uriListEntries.push(editor.options?.selection ? $P4(editor.resource, editor.options.selection) : editor.resource);
      } else if ($9K(editor)) {
        if (editor.modified.resource) {
          uriListEntries.push(editor.modified.resource);
        }
      } else if ($$K(editor)) {
        if (editor.primary.resource) {
          uriListEntries.push(editor.primary.resource);
        }
      } else if ($aL(editor)) {
        uriListEntries.push(editor.result.resource);
      }
    }
    if (!options3?.disableStandardTransfer) {
      event.dataTransfer.setData($YC.uriList, $nE.create(uriListEntries.slice(0, 1)));
    }
    event.dataTransfer.setData($kZ.INTERNAL_URI_LIST, $nE.create(uriListEntries));
  }
}
var $Fob = class {
  constructor(a, b) {
    this.a = a;
    this.b = b;
  }
  update(dataTransfer) {
  }
  getData() {
    return { type: this.a, id: this.b };
  }
};
var $Gob = class {
  constructor(a) {
    this.a = a;
  }
  get id() {
    return this.a;
  }
};
var $Hob = class {
  constructor(a) {
    this.a = a;
  }
  get id() {
    return this.a;
  }
};
var $Iob = class _$Iob extends $3c {
  static get INSTANCE() {
    if (!_$Iob.a) {
      _$Iob.a = new _$Iob();
      $Vc(_$Iob.a);
    }
    return _$Iob.a;
  }
  constructor() {
    super();
    this.b = $B_.getInstance();
    this.c = this.B(new $ze());
    this.f = this.B(new $ze());
    this.B(this.f.event((e) => {
      const id2 = e.dragAndDropData.getData().id;
      const type = e.dragAndDropData.getData().type;
      const data = this.g(type);
      if (data?.getData().id === id2) {
        this.b.clearData(type === "view" ? $Hob.prototype : $Gob.prototype);
      }
    }));
  }
  g(type) {
    if (this.b.hasData(type === "view" ? $Hob.prototype : $Gob.prototype)) {
      const data = this.b.getData(type === "view" ? $Hob.prototype : $Gob.prototype);
      if (data && data[0]) {
        return new $Fob(type, data[0].id);
      }
    }
    return void 0;
  }
  h(id2, type) {
    this.b.setData([type === "view" ? new $Hob(id2) : new $Gob(id2)], type === "view" ? $Hob.prototype : $Gob.prototype);
  }
  registerTarget(element, callbacks) {
    const disposableStore = new $2c();
    disposableStore.add(new $Ak(element, {
      onDragEnter: (e) => {
        e.preventDefault();
        if (callbacks.onDragEnter) {
          const data = this.g("composite") || this.g("view");
          if (data) {
            callbacks.onDragEnter({ eventData: e, dragAndDropData: data });
          }
        }
      },
      onDragLeave: (e) => {
        const data = this.g("composite") || this.g("view");
        if (callbacks.onDragLeave && data) {
          callbacks.onDragLeave({ eventData: e, dragAndDropData: data });
        }
      },
      onDrop: (e) => {
        if (callbacks.onDrop) {
          const data = this.g("composite") || this.g("view");
          if (!data) {
            return;
          }
          callbacks.onDrop({ eventData: e, dragAndDropData: data });
          this.f.fire({ eventData: e, dragAndDropData: data });
        }
      },
      onDragOver: (e) => {
        e.preventDefault();
        if (callbacks.onDragOver) {
          const data = this.g("composite") || this.g("view");
          if (!data) {
            return;
          }
          callbacks.onDragOver({ eventData: e, dragAndDropData: data });
        }
      }
    }));
    if (callbacks.onDragStart) {
      this.c.event((e) => {
        callbacks.onDragStart(e);
      }, this, disposableStore);
    }
    if (callbacks.onDragEnd) {
      this.f.event((e) => {
        callbacks.onDragEnd(e);
      }, this, disposableStore);
    }
    return this.B(disposableStore);
  }
  registerDraggable(element, draggedItemProvider, callbacks) {
    element.draggable = true;
    const disposableStore = new $2c();
    disposableStore.add(new $Ak(element, {
      onDragStart: (e) => {
        const { id: id2, type } = draggedItemProvider();
        this.h(id2, type);
        e.dataTransfer?.setDragImage(element, 0, 0);
        this.c.fire({ eventData: e, dragAndDropData: this.g(type) });
      },
      onDragEnd: (e) => {
        const { type } = draggedItemProvider();
        const data = this.g(type);
        if (!data) {
          return;
        }
        this.f.fire({ eventData: e, dragAndDropData: data });
      },
      onDragEnter: (e) => {
        if (callbacks.onDragEnter) {
          const data = this.g("composite") || this.g("view");
          if (!data) {
            return;
          }
          if (data) {
            callbacks.onDragEnter({ eventData: e, dragAndDropData: data });
          }
        }
      },
      onDragLeave: (e) => {
        const data = this.g("composite") || this.g("view");
        if (!data) {
          return;
        }
        callbacks.onDragLeave?.({ eventData: e, dragAndDropData: data });
      },
      onDrop: (e) => {
        if (callbacks.onDrop) {
          const data = this.g("composite") || this.g("view");
          if (!data) {
            return;
          }
          callbacks.onDrop({ eventData: e, dragAndDropData: data });
          this.f.fire({ eventData: e, dragAndDropData: data });
        }
      },
      onDragOver: (e) => {
        if (callbacks.onDragOver) {
          const data = this.g("composite") || this.g("view");
          if (!data) {
            return;
          }
          callbacks.onDragOver({ eventData: e, dragAndDropData: data });
        }
      }
    }));
    if (callbacks.onDragStart) {
      this.c.event((e) => {
        callbacks.onDragStart(e);
      }, this, disposableStore);
    }
    if (callbacks.onDragEnd) {
      this.f.event((e) => {
        callbacks.onDragEnd(e);
      }, this, disposableStore);
    }
    return this.B(disposableStore);
  }
};
function $Job(dataTransfer, dropEffect, shouldHaveIt) {
  if (!dataTransfer) {
    return;
  }
  dataTransfer.dropEffect = shouldHaveIt ? dropEffect : "none";
}
var $Kob = class $Kob2 {
  constructor(a, b) {
    this.a = a;
    this.b = b;
  }
  getDragURI(element) {
    const resource = this.a(element);
    return resource ? resource.toString() : null;
  }
  getDragLabel(elements) {
    const resources = $Mb(elements.map(this.a));
    return resources.length === 1 ? $sh(resources[0]) : resources.length > 1 ? String(resources.length) : void 0;
  }
  onDragStart(data, originalEvent) {
    const resources = [];
    for (const element of data.elements) {
      const resource = this.a(element);
      if (resource) {
        resources.push(resource);
      }
    }
    if (resources.length) {
      this.b.invokeFunction((accessor) => $Eob(accessor, resources, originalEvent));
    }
  }
  onDragOver(data, targetElement, targetIndex, targetSector, originalEvent) {
    return false;
  }
  drop(data, targetElement, targetIndex, targetSector, originalEvent) {
  }
  dispose() {
  }
};
$Kob = __decorate([
  __param(1, $Pk)
], $Kob);
var GlobalWindowDraggedOverTracker = class _GlobalWindowDraggedOverTracker extends $3c {
  static {
    this.a = "monaco-workbench-global-dragged-over";
  }
  constructor() {
    super();
    this.b = this.B(new $iZ(_GlobalWindowDraggedOverTracker.a));
    this.f = false;
    this.c();
  }
  c() {
    this.B(Event2.runAndSubscribe(onDidRegisterWindow, ({ window: window3, disposables }) => {
      disposables.add($_i(window3, $7j.DRAG_OVER, () => this.g(false), true));
      disposables.add($_i(window3, $7j.DRAG_LEAVE, () => this.h(false), true));
    }, { window: $Y, disposables: this.q }));
    this.B(this.b.onDidReceiveData((data) => {
      if (data === true) {
        this.g(true);
      } else {
        this.h(true);
      }
    }));
  }
  get isDraggedOver() {
    return this.f;
  }
  g(fromBroadcast) {
    if (this.f === true) {
      return;
    }
    this.f = true;
    if (!fromBroadcast) {
      this.b.postData(true);
    }
  }
  h(fromBroadcast) {
    if (this.f === false) {
      return;
    }
    this.f = false;
    if (!fromBroadcast) {
      this.b.postData(false);
    }
  }
};
var globalDraggedOverTracker = new GlobalWindowDraggedOverTracker();
function $Lob() {
  return globalDraggedOverTracker.isDraggedOver;
}

// out-build/vs/base/browser/ui/splitview/paneview.js
var $a3 = class _$a3 extends $3c {
  static {
    this.u = 22;
  }
  get ariaHeaderLabel() {
    return this.M;
  }
  set ariaHeaderLabel(newLabel) {
    this.M = newLabel;
    this.w.setAttribute("aria-label", this.ariaHeaderLabel);
  }
  get draggableElement() {
    return this.w;
  }
  get dropTargetElement() {
    return this.element;
  }
  get dropBackground() {
    return this.N.dropBackground;
  }
  get minimumBodySize() {
    return this.I;
  }
  set minimumBodySize(size) {
    this.I = size;
    this.P.fire(void 0);
  }
  get maximumBodySize() {
    return this.J;
  }
  set maximumBodySize(size) {
    this.J = size;
    this.P.fire(void 0);
  }
  get R() {
    return this.headerVisible ? _$a3.u : 0;
  }
  get minimumSize() {
    const headerSize = this.R;
    const expanded2 = !this.headerVisible || this.isExpanded();
    const minimumBodySize = expanded2 ? this.minimumBodySize : 0;
    return headerSize + minimumBodySize;
  }
  get maximumSize() {
    const headerSize = this.R;
    const expanded2 = !this.headerVisible || this.isExpanded();
    const maximumBodySize = expanded2 ? this.maximumBodySize : 0;
    return headerSize + maximumBodySize;
  }
  constructor(options3) {
    super();
    this.D = void 0;
    this.F = true;
    this.G = true;
    this.H = false;
    this.N = {
      dropBackground: void 0,
      headerBackground: void 0,
      headerBorder: void 0,
      headerForeground: void 0,
      leftBorder: void 0
    };
    this.O = void 0;
    this.P = this.B(new $ze());
    this.onDidChange = this.P.event;
    this.Q = this.B(new $ze());
    this.onDidChangeExpansionState = this.Q.event;
    this.orthogonalSize = 0;
    this.z = typeof options3.expanded === "undefined" ? true : !!options3.expanded;
    this.C = typeof options3.orientation === "undefined" ? 0 : options3.orientation;
    this.M = localize(29, null, options3.title);
    this.I = typeof options3.minimumBodySize === "number" ? options3.minimumBodySize : this.C === 1 ? 200 : 120;
    this.J = typeof options3.maximumBodySize === "number" ? options3.maximumBodySize : Number.POSITIVE_INFINITY;
    this.element = $(".pane");
  }
  isExpanded() {
    return this.z;
  }
  setExpanded(expanded2) {
    if (!expanded2 && !this.collapsible) {
      return false;
    }
    if (this.z === !!expanded2) {
      return false;
    }
    this.element?.classList.toggle("expanded", expanded2);
    this.z = !!expanded2;
    this.S();
    if (expanded2) {
      if (!this.H) {
        this.W(this.y);
        this.H = true;
      }
      if (typeof this.O === "number") {
        getWindow(this.element).clearTimeout(this.O);
      }
      $bk(this.element, this.y);
    } else {
      this.O = getWindow(this.element).setTimeout(() => {
        this.y.remove();
      }, 200);
    }
    this.Q.fire(expanded2);
    this.P.fire(expanded2 ? this.D : void 0);
    return true;
  }
  get headerVisible() {
    return this.F;
  }
  set headerVisible(visible) {
    if (this.F === !!visible) {
      return;
    }
    this.F = !!visible;
    this.S();
    this.P.fire(void 0);
  }
  get collapsible() {
    return this.G;
  }
  set collapsible(collapsible) {
    if (this.G === !!collapsible) {
      return;
    }
    this.G = !!collapsible;
    this.S();
  }
  get orientation() {
    return this.C;
  }
  set orientation(orientation) {
    if (this.C === orientation) {
      return;
    }
    this.C = orientation;
    if (this.element) {
      this.element.classList.toggle(
        "horizontal",
        this.orientation === 1
        /* Orientation.HORIZONTAL */
      );
      this.element.classList.toggle(
        "vertical",
        this.orientation === 0
        /* Orientation.VERTICAL */
      );
    }
    if (this.w) {
      this.S();
    }
  }
  render() {
    this.element.classList.toggle("expanded", this.isExpanded());
    this.element.classList.toggle(
      "horizontal",
      this.orientation === 1
      /* Orientation.HORIZONTAL */
    );
    this.element.classList.toggle(
      "vertical",
      this.orientation === 0
      /* Orientation.VERTICAL */
    );
    this.w = $(".pane-header");
    $bk(this.element, this.w);
    this.w.setAttribute("tabindex", "0");
    this.w.setAttribute("role", "button");
    this.w.setAttribute("aria-label", this.ariaHeaderLabel);
    this.U(this.w);
    const focusTracker = $_j(this.w);
    this.B(focusTracker);
    this.B(focusTracker.onDidFocus(() => this.w.classList.add("focused"), null));
    this.B(focusTracker.onDidBlur(() => this.w.classList.remove("focused"), null));
    this.S();
    const eventDisposables = this.B(new $2c());
    const onKeyDown = this.B(new $9Z(this.w, "keydown"));
    const onHeaderKeyDown = Event2.map(onKeyDown.event, (e) => new $if(e), eventDisposables);
    this.B(Event2.filter(onHeaderKeyDown, (e) => e.keyCode === 3 || e.keyCode === 10, eventDisposables)(() => this.setExpanded(!this.isExpanded()), null));
    this.B(Event2.filter(onHeaderKeyDown, (e) => e.keyCode === 15, eventDisposables)(() => this.setExpanded(false), null));
    this.B(Event2.filter(onHeaderKeyDown, (e) => e.keyCode === 17, eventDisposables)(() => this.setExpanded(true), null));
    this.B($mZ.addTarget(this.w));
    [$7j.CLICK, EventType.Tap].forEach((eventType) => {
      this.B($_i(this.w, eventType, (e) => {
        if (!e.defaultPrevented) {
          this.setExpanded(!this.isExpanded());
        }
      }));
    });
    this.y = $bk(this.element, $(".pane-body"));
    if (!this.H && this.isExpanded()) {
      this.W(this.y);
      this.H = true;
    }
    if (!this.isExpanded()) {
      this.y.remove();
    }
  }
  layout(size) {
    const headerSize = this.headerVisible ? _$a3.u : 0;
    const width2 = this.C === 0 ? this.orthogonalSize : size;
    const height = this.C === 0 ? size - headerSize : this.orthogonalSize - headerSize;
    if (this.isExpanded()) {
      this.y.classList.toggle("wide", width2 >= 600);
      this.X(height, width2);
      this.D = size;
    }
  }
  style(styles) {
    this.N = styles;
    if (!this.w) {
      return;
    }
    this.S();
  }
  S() {
    const expanded2 = !this.headerVisible || this.isExpanded();
    if (this.collapsible) {
      this.w.setAttribute("tabindex", "0");
      this.w.setAttribute("role", "button");
    } else {
      this.w.removeAttribute("tabindex");
      this.w.removeAttribute("role");
    }
    this.w.style.lineHeight = `${this.R}px`;
    this.w.classList.toggle("hidden", !this.headerVisible);
    this.w.classList.toggle("expanded", expanded2);
    this.w.classList.toggle("not-collapsible", !this.collapsible);
    this.w.setAttribute("aria-expanded", String(expanded2));
    this.w.style.color = this.collapsible ? this.N.headerForeground ?? "" : "";
    this.w.style.backgroundColor = (this.collapsible ? this.N.headerBackground : "transparent") ?? "";
    this.w.style.borderTop = this.N.headerBorder && this.orientation === 0 ? `1px solid ${this.N.headerBorder}` : "";
    this.element.style.borderLeft = this.N.leftBorder && this.orientation === 1 ? `1px solid ${this.N.leftBorder}` : "";
  }
};
var PaneDraggable = class _PaneDraggable extends $3c {
  static {
    this.a = new $Vn(new $Sn(128, 128, 128, 0.5));
  }
  constructor(f, g, h3) {
    super();
    this.f = f;
    this.g = g;
    this.h = h3;
    this.b = 0;
    this.c = this.B(new $ze());
    this.onDidDrop = this.c.event;
    f.draggableElement.draggable = true;
    this.B($_i(f.draggableElement, "dragstart", (e) => this.j(e)));
    this.B($_i(f.dropTargetElement, "dragenter", (e) => this.m(e)));
    this.B($_i(f.dropTargetElement, "dragleave", (e) => this.n(e)));
    this.B($_i(f.dropTargetElement, "dragend", (e) => this.r(e)));
    this.B($_i(f.dropTargetElement, "drop", (e) => this.s(e)));
  }
  j(e) {
    if (!this.g.canDrag(this.f) || !e.dataTransfer) {
      e.preventDefault();
      e.stopPropagation();
      return;
    }
    e.dataTransfer.effectAllowed = "move";
    if ($Ue) {
      e.dataTransfer?.setData($kZ.TEXT, this.f.draggableElement.textContent || "");
    }
    const dragImage = $bk(this.f.element.ownerDocument.body, $(".monaco-drag-image", {}, this.f.draggableElement.textContent || ""));
    e.dataTransfer.setDragImage(dragImage, -10, -10);
    setTimeout(() => dragImage.remove(), 0);
    this.h.draggable = this;
  }
  m(e) {
    if (!this.h.draggable || this.h.draggable === this) {
      return;
    }
    if (!this.g.canDrop(this.h.draggable.f, this.f)) {
      return;
    }
    this.b++;
    this.t();
  }
  n(e) {
    if (!this.h.draggable || this.h.draggable === this) {
      return;
    }
    if (!this.g.canDrop(this.h.draggable.f, this.f)) {
      return;
    }
    this.b--;
    if (this.b === 0) {
      this.t();
    }
  }
  r(e) {
    if (!this.h.draggable) {
      return;
    }
    this.b = 0;
    this.t();
    this.h.draggable = null;
  }
  s(e) {
    if (!this.h.draggable) {
      return;
    }
    $9j.stop(e);
    this.b = 0;
    this.t();
    if (this.g.canDrop(this.h.draggable.f, this.f) && this.h.draggable !== this) {
      this.c.fire({ from: this.h.draggable.f, to: this.f });
    }
    this.h.draggable = null;
  }
  t() {
    let backgroundColor = null;
    if (this.b > 0) {
      backgroundColor = this.f.dropBackground ?? _PaneDraggable.a.toString();
    }
    this.f.dropTargetElement.style.backgroundColor = backgroundColor || "";
  }
};
var $c3 = class extends $3c {
  constructor(container2, options3 = {}) {
    super();
    this.b = { draggable: null };
    this.c = [];
    this.f = 0;
    this.g = 0;
    this.j = void 0;
    this.m = this.B(new $ze());
    this.onDidDrop = this.m.event;
    this.a = options3.dnd;
    this.orientation = options3.orientation ?? 0;
    this.element = $bk(container2, $(".monaco-pane-view"));
    this.h = this.B(new $r2(this.element, { orientation: this.orientation }));
    this.onDidSashReset = this.h.onDidSashReset;
    this.onDidSashChange = this.h.onDidSashChange;
    this.onDidScroll = this.h.onDidScroll;
    const eventDisposables = this.B(new $2c());
    const onKeyDown = this.B(new $9Z(this.element, "keydown"));
    const onHeaderKeyDown = Event2.map(Event2.filter(onKeyDown.event, (e) => $Uj(e.target) && e.target.classList.contains("pane-header"), eventDisposables), (e) => new $if(e), eventDisposables);
    this.B(Event2.filter(onHeaderKeyDown, (e) => e.keyCode === 16, eventDisposables)(() => this.u()));
    this.B(Event2.filter(onHeaderKeyDown, (e) => e.keyCode === 18, eventDisposables)(() => this.w()));
  }
  addPane(pane, size, index = this.h.length) {
    const disposables = new $2c();
    pane.onDidChangeExpansionState(this.s, this, disposables);
    const paneItem = { pane, disposable: disposables };
    this.c.splice(index, 0, paneItem);
    pane.orientation = this.orientation;
    pane.orthogonalSize = this.f;
    this.h.addView(pane, size, index);
    if (this.a) {
      const draggable = new PaneDraggable(pane, this.a, this.b);
      disposables.add(draggable);
      disposables.add(draggable.onDidDrop(this.m.fire, this.m));
    }
  }
  removePane(pane) {
    const index = this.c.findIndex((item) => item.pane === pane);
    if (index === -1) {
      return;
    }
    this.h.removeView(index, pane.isExpanded() ? Sizing.Distribute : void 0);
    const paneItem = this.c.splice(index, 1)[0];
    paneItem.disposable.dispose();
  }
  movePane(from, to) {
    const fromIndex = this.c.findIndex((item) => item.pane === from);
    const toIndex = this.c.findIndex((item) => item.pane === to);
    if (fromIndex === -1 || toIndex === -1) {
      return;
    }
    const [paneItem] = this.c.splice(fromIndex, 1);
    this.c.splice(toIndex, 0, paneItem);
    this.h.moveView(fromIndex, toIndex);
  }
  resizePane(pane, size) {
    const index = this.c.findIndex((item) => item.pane === pane);
    if (index === -1) {
      return;
    }
    this.h.resizeView(index, size);
  }
  getPaneSize(pane) {
    const index = this.c.findIndex((item) => item.pane === pane);
    if (index === -1) {
      return -1;
    }
    return this.h.getViewSize(index);
  }
  layout(height, width2) {
    this.f = this.orientation === 0 ? width2 : height;
    this.g = this.orientation === 1 ? width2 : height;
    for (const paneItem of this.c) {
      paneItem.pane.orthogonalSize = this.f;
    }
    this.h.layout(this.g);
  }
  setBoundarySashes(sashes) {
    this.n = sashes;
    this.r(sashes);
  }
  r(sashes) {
    if (this.orientation === 0) {
      this.h.orthogonalStartSash = sashes?.left;
      this.h.orthogonalEndSash = sashes?.right;
    } else {
      this.h.orthogonalEndSash = sashes?.bottom;
    }
  }
  flipOrientation(height, width2) {
    this.orientation = this.orientation === 0 ? 1 : 0;
    const paneSizes = this.c.map((pane) => this.getPaneSize(pane.pane));
    this.h.dispose();
    $$i(this.element);
    this.h = this.B(new $r2(this.element, { orientation: this.orientation }));
    this.r(this.n);
    const newOrthogonalSize = this.orientation === 0 ? width2 : height;
    const newSize = this.orientation === 1 ? width2 : height;
    this.c.forEach((pane, index) => {
      pane.pane.orthogonalSize = newOrthogonalSize;
      pane.pane.orientation = this.orientation;
      const viewSize = this.g === 0 ? 0 : newSize * paneSizes[index] / this.g;
      this.h.addView(pane.pane, viewSize, index);
    });
    this.g = newSize;
    this.f = newOrthogonalSize;
    this.h.layout(this.g);
  }
  s() {
    if (typeof this.j === "number") {
      getWindow(this.element).clearTimeout(this.j);
    }
    this.element.classList.add("animated");
    this.j = getWindow(this.element).setTimeout(() => {
      this.j = void 0;
      this.element.classList.remove("animated");
    }, 200);
  }
  t() {
    return [...this.element.querySelectorAll(".pane-header")];
  }
  u() {
    const headers = this.t();
    const index = headers.indexOf(this.element.ownerDocument.activeElement);
    if (index === -1) {
      return;
    }
    headers[Math.max(index - 1, 0)].focus();
  }
  w() {
    const headers = this.t();
    const index = headers.indexOf(this.element.ownerDocument.activeElement);
    if (index === -1) {
      return;
    }
    headers[Math.min(index + 1, headers.length - 1)].focus();
  }
  dispose() {
    super.dispose();
    this.c.forEach((i2) => i2.disposable.dispose());
  }
};

// out-build/vs/workbench/common/views.js
var $6M = "views";
var $7M = localize(4298, null);
var $8M = $9r("default-view-icon", $6l.window, localize(4299, null));
var Extensions5;
(function(Extensions9) {
  Extensions9.ViewContainersRegistry = "workbench.registry.view.containers";
  Extensions9.ViewsRegistry = "workbench.registry.view";
})(Extensions5 || (Extensions5 = {}));
var ViewContainerLocation;
(function(ViewContainerLocation2) {
  ViewContainerLocation2[ViewContainerLocation2["Sidebar"] = 0] = "Sidebar";
  ViewContainerLocation2[ViewContainerLocation2["Panel"] = 1] = "Panel";
  ViewContainerLocation2[ViewContainerLocation2["AuxiliaryBar"] = 2] = "AuxiliaryBar";
})(ViewContainerLocation || (ViewContainerLocation = {}));
var $9M = [
  0,
  1,
  2
  /* ViewContainerLocation.AuxiliaryBar */
];
function $0M(viewContainerLocation) {
  switch (viewContainerLocation) {
    case 0:
      return "sidebar";
    case 1:
      return "panel";
    case 2:
      return "auxiliarybar";
  }
}
var ViewContainersRegistryImpl = class extends $3c {
  constructor() {
    super(...arguments);
    this.c = this.B(new $ze());
    this.onDidRegister = this.c.event;
    this.f = this.B(new $ze());
    this.onDidDeregister = this.f.event;
    this.g = /* @__PURE__ */ new Map();
    this.h = [];
  }
  get all() {
    return [...this.g.values()].flat();
  }
  registerViewContainer(viewContainerDescriptor, viewContainerLocation, options3) {
    const existing = this.get(viewContainerDescriptor.id);
    if (existing) {
      return existing;
    }
    const viewContainer5 = viewContainerDescriptor;
    viewContainer5.openCommandActionDescriptor = options3?.doNotRegisterOpenCommand ? void 0 : viewContainer5.openCommandActionDescriptor ?? { id: viewContainer5.id };
    const viewContainers = $Bc(this.g, viewContainerLocation, []);
    viewContainers.push(viewContainer5);
    if (options3?.isDefault) {
      this.h.push(viewContainer5);
    }
    this.c.fire({ viewContainer: viewContainer5, viewContainerLocation });
    return viewContainer5;
  }
  deregisterViewContainer(viewContainer5) {
    for (const viewContainerLocation of this.g.keys()) {
      const viewContainers = this.g.get(viewContainerLocation);
      const index = viewContainers?.indexOf(viewContainer5);
      if (index !== -1) {
        viewContainers?.splice(index, 1);
        if (viewContainers.length === 0) {
          this.g.delete(viewContainerLocation);
        }
        this.f.fire({ viewContainer: viewContainer5, viewContainerLocation });
        return;
      }
    }
  }
  get(id2) {
    return this.all.filter((viewContainer5) => viewContainer5.id === id2)[0];
  }
  getViewContainers(location3) {
    return [...this.g.get(location3) || []];
  }
  getViewContainerLocation(container2) {
    return [...this.g.keys()].filter((location3) => this.getViewContainers(location3).filter((viewContainer5) => viewContainer5?.id === container2.id).length > 0)[0];
  }
  getDefaultViewContainer(location3) {
    return this.h.find((viewContainer5) => this.getViewContainerLocation(viewContainer5) === location3);
  }
};
$Wn.add(Extensions5.ViewContainersRegistry, new ViewContainersRegistryImpl());
var ViewContentGroups;
(function(ViewContentGroups2) {
  ViewContentGroups2["Open"] = "2_open";
  ViewContentGroups2["Debug"] = "4_debug";
  ViewContentGroups2["SCM"] = "5_scm";
  ViewContentGroups2["More"] = "9_more";
})(ViewContentGroups || (ViewContentGroups = {}));
function compareViewContentDescriptors(a, b) {
  const aGroup = a.group ?? ViewContentGroups.More;
  const bGroup = b.group ?? ViewContentGroups.More;
  if (aGroup !== bGroup) {
    return aGroup.localeCompare(bGroup);
  }
  return (a.order ?? 5) - (b.order ?? 5);
}
var ViewsRegistry = class extends $3c {
  constructor() {
    super(...arguments);
    this.c = this.B(new $ze());
    this.onViewsRegistered = this.c.event;
    this.f = this.B(new $ze());
    this.onViewsDeregistered = this.f.event;
    this.g = this.B(new $ze());
    this.onDidChangeContainer = this.g.event;
    this.h = this.B(new $ze());
    this.onDidChangeViewWelcomeContent = this.h.event;
    this.j = [];
    this.m = /* @__PURE__ */ new Map();
    this.n = new $Lc();
  }
  registerViews(views, viewContainer5) {
    this.registerViews2([{ views, viewContainer: viewContainer5 }]);
  }
  registerViews2(views) {
    views.forEach(({ views: views2, viewContainer: viewContainer5 }) => this.r(views2, viewContainer5));
    this.c.fire(views);
  }
  deregisterViews(viewDescriptors, viewContainer5) {
    const views = this.s(viewDescriptors, viewContainer5);
    if (views.length) {
      this.f.fire({ views, viewContainer: viewContainer5 });
    }
  }
  moveViews(viewsToMove, viewContainer5) {
    for (const container2 of this.m.keys()) {
      if (container2 !== viewContainer5) {
        const views = this.s(viewsToMove, container2);
        if (views.length) {
          this.r(views, viewContainer5);
          this.g.fire({ views, from: container2, to: viewContainer5 });
        }
      }
    }
  }
  getViews(loc) {
    return this.m.get(loc) || [];
  }
  getView(id2) {
    for (const viewContainer5 of this.j) {
      const viewDescriptor3 = (this.m.get(viewContainer5) || []).filter((v) => v.id === id2)[0];
      if (viewDescriptor3) {
        return viewDescriptor3;
      }
    }
    return null;
  }
  getViewContainer(viewId) {
    for (const viewContainer5 of this.j) {
      const viewDescriptor3 = (this.m.get(viewContainer5) || []).filter((v) => v.id === viewId)[0];
      if (viewDescriptor3) {
        return viewContainer5;
      }
    }
    return null;
  }
  registerViewWelcomeContent(id2, viewContent) {
    this.n.add(id2, viewContent);
    this.h.fire(id2);
    return $1c(() => {
      this.n.delete(id2, viewContent);
      this.h.fire(id2);
    });
  }
  registerViewWelcomeContent2(id2, viewContentMap) {
    const disposables = /* @__PURE__ */ new Map();
    for (const [key2, content] of viewContentMap) {
      this.n.add(id2, content);
      disposables.set(key2, $1c(() => {
        this.n.delete(id2, content);
        this.h.fire(id2);
      }));
    }
    this.h.fire(id2);
    return disposables;
  }
  getViewWelcomeContent(id2) {
    const result = [];
    this.n.forEach(id2, (descriptor) => result.push(descriptor));
    return result.sort(compareViewContentDescriptors);
  }
  r(viewDescriptors, viewContainer5) {
    let views = this.m.get(viewContainer5);
    if (!views) {
      views = [];
      this.m.set(viewContainer5, views);
      this.j.push(viewContainer5);
    }
    for (const viewDescriptor3 of viewDescriptors) {
      if (this.getView(viewDescriptor3.id) !== null) {
        throw new Error(localize(4300, null, viewDescriptor3.id));
      }
      views.push(viewDescriptor3);
    }
  }
  s(viewDescriptors, viewContainer5) {
    const views = this.m.get(viewContainer5);
    if (!views) {
      return [];
    }
    const viewsToDeregister = [];
    const remaningViews = [];
    for (const view of views) {
      if (!viewDescriptors.includes(view)) {
        remaningViews.push(view);
      } else {
        viewsToDeregister.push(view);
      }
    }
    if (viewsToDeregister.length) {
      if (remaningViews.length) {
        this.m.set(viewContainer5, remaningViews);
      } else {
        this.m.delete(viewContainer5);
        this.j.splice(this.j.indexOf(viewContainer5), 1);
      }
    }
    return viewsToDeregister;
  }
};
$Wn.add(Extensions5.ViewsRegistry, new ViewsRegistry());
var $$M = $Qk("viewDescriptorService");
var ViewVisibilityState;
(function(ViewVisibilityState2) {
  ViewVisibilityState2[ViewVisibilityState2["Default"] = 0] = "Default";
  ViewVisibilityState2[ViewVisibilityState2["Expand"] = 1] = "Expand";
})(ViewVisibilityState || (ViewVisibilityState = {}));
var TreeItemCollapsibleState2;
(function(TreeItemCollapsibleState3) {
  TreeItemCollapsibleState3[TreeItemCollapsibleState3["None"] = 0] = "None";
  TreeItemCollapsibleState3[TreeItemCollapsibleState3["Collapsed"] = 1] = "Collapsed";
  TreeItemCollapsibleState3[TreeItemCollapsibleState3["Expanded"] = 2] = "Expanded";
})(TreeItemCollapsibleState2 || (TreeItemCollapsibleState2 = {}));
var $_M = class {
  constructor(treeItem, resolve) {
    this.c = false;
    this.d = false;
    $Ov(this, treeItem);
    this.d = !!resolve;
    this.resolve = async (token) => {
      if (resolve && !this.c) {
        const resolvedItem = await resolve(token);
        if (resolvedItem) {
          this.tooltip = this.tooltip ?? resolvedItem.tooltip;
          this.command = this.command ?? resolvedItem.command;
        }
      }
      if (!token.isCancellationRequested) {
        this.c = true;
      }
    };
  }
  get hasResolve() {
    return this.d;
  }
  resetResolve() {
    this.c = false;
  }
  asTreeItem() {
    return {
      handle: this.handle,
      parentHandle: this.parentHandle,
      collapsibleState: this.collapsibleState,
      label: this.label,
      description: this.description,
      icon: this.icon,
      iconDark: this.iconDark,
      themeIcon: this.themeIcon,
      resourceUri: this.resourceUri,
      tooltip: this.tooltip,
      contextValue: this.contextValue,
      command: this.command,
      children: this.children,
      accessibilityInformation: this.accessibilityInformation
    };
  }
};
var $aN = class extends Error {
  constructor(treeViewId) {
    super(localize(4301, null, treeViewId));
    this.name = "NoTreeViewError";
  }
  static is(err) {
    return !!err && err.name === "NoTreeViewError";
  }
};

// out-build/vs/base/common/linkedText.js
var $T3 = class {
  constructor(nodes) {
    this.nodes = nodes;
  }
  toString() {
    return this.nodes.map((node) => typeof node === "string" ? node : node.label).join("");
  }
};
__decorate([
  $0t
], $T3.prototype, "toString", null);
var LINK_REGEX = /\[([^\]]+)\]\(((?:https?:\/\/|command:|file:)[^\)\s]+)(?: (["'])(.+?)(\3))?\)/gi;
function $U3(text2) {
  const result = [];
  let index = 0;
  let match;
  while (match = LINK_REGEX.exec(text2)) {
    if (match.index - index > 0) {
      result.push(text2.substring(index, match.index));
    }
    const [, label3, href, , title] = match;
    if (title) {
      result.push({ label: label3, href, title });
    } else {
      result.push({ label: label3, href });
    }
    index = match.index + match[0].length;
  }
  if (index < text2.length) {
    result.push(text2.substring(index));
  }
  return new $T3(result);
}

// out-build/vs/workbench/services/progress/browser/progressIndicator.js
var $4ob = class extends $3c {
  constructor(a, b) {
    super();
    this.a = a;
    this.b = b;
    this.c();
  }
  c() {
    this.B(this.b.onDidModelChange((e) => {
      if (e.kind === 8 || e.kind === 6 && this.b.isEmpty) {
        this.a.stop().hide();
      }
    }));
  }
  show(infiniteOrTotal, delay) {
    if (this.b.isEmpty) {
      return $UJ;
    }
    if (infiniteOrTotal === true) {
      return this.f(true, delay);
    }
    return this.f(infiniteOrTotal, delay);
  }
  f(infiniteOrTotal, delay) {
    if (typeof infiniteOrTotal === "boolean") {
      this.a.infinite().show(delay);
    } else {
      this.a.total(infiniteOrTotal).show(delay);
    }
    return {
      total: (total) => {
        this.a.total(total);
      },
      worked: (worked) => {
        if (this.a.hasTotal()) {
          this.a.worked(worked);
        } else {
          this.a.infinite().show();
        }
      },
      done: () => {
        this.a.stop().hide();
      }
    };
  }
  async showWhile(promise, delay) {
    if (this.b.isEmpty) {
      try {
        await promise;
      } catch (error) {
      }
    }
    return this.g(promise, delay);
  }
  async g(promise, delay) {
    try {
      this.a.infinite().show(delay);
      await promise;
    } catch (error) {
    } finally {
      this.a.stop().hide();
    }
  }
};
var ProgressIndicatorState;
(function(ProgressIndicatorState2) {
  let Type4;
  (function(Type5) {
    Type5[Type5["None"] = 0] = "None";
    Type5[Type5["Done"] = 1] = "Done";
    Type5[Type5["Infinite"] = 2] = "Infinite";
    Type5[Type5["While"] = 3] = "While";
    Type5[Type5["Work"] = 4] = "Work";
  })(Type4 = ProgressIndicatorState2.Type || (ProgressIndicatorState2.Type = {}));
  ProgressIndicatorState2.None = {
    type: 0
    /* Type.None */
  };
  ProgressIndicatorState2.Done = {
    type: 1
    /* Type.Done */
  };
  ProgressIndicatorState2.Infinite = {
    type: 2
    /* Type.Infinite */
  };
  class While {
    constructor(whilePromise, whileStart, whileDelay) {
      this.whilePromise = whilePromise;
      this.whileStart = whileStart;
      this.whileDelay = whileDelay;
      this.type = 3;
    }
  }
  ProgressIndicatorState2.While = While;
  class Work {
    constructor(total, worked) {
      this.total = total;
      this.worked = worked;
      this.type = 4;
    }
  }
  ProgressIndicatorState2.Work = Work;
})(ProgressIndicatorState || (ProgressIndicatorState = {}));
var $5ob = class extends $3c {
  constructor(b, c) {
    super();
    this.b = b;
    this.c = c;
    this.a = ProgressIndicatorState.None;
    this.registerListeners();
  }
  registerListeners() {
    this.B(this.c.onDidChangeActive(() => {
      if (this.c.isActive) {
        this.f();
      } else {
        this.g();
      }
    }));
  }
  f() {
    if (this.a.type === ProgressIndicatorState.Done.type) {
      return;
    }
    if (this.a.type === 3) {
      let delay;
      if (this.a.whileDelay > 0) {
        const remainingDelay = this.a.whileDelay - (Date.now() - this.a.whileStart);
        if (remainingDelay > 0) {
          delay = remainingDelay;
        }
      }
      this.h(delay);
    } else if (this.a.type === 2) {
      this.b.infinite().show();
    } else if (this.a.type === 4) {
      if (this.a.total) {
        this.b.total(this.a.total).show();
      }
      if (this.a.worked) {
        this.b.worked(this.a.worked).show();
      }
    }
  }
  g() {
    this.b.stop().hide();
  }
  show(infiniteOrTotal, delay) {
    if (typeof infiniteOrTotal === "boolean") {
      this.a = ProgressIndicatorState.Infinite;
    } else {
      this.a = new ProgressIndicatorState.Work(infiniteOrTotal, void 0);
    }
    if (this.c.isActive) {
      if (this.a.type === 2) {
        this.b.infinite().show(delay);
      } else if (this.a.type === 4 && typeof this.a.total === "number") {
        this.b.total(this.a.total).show(delay);
      }
    }
    return {
      total: (total) => {
        this.a = new ProgressIndicatorState.Work(total, this.a.type === 4 ? this.a.worked : void 0);
        if (this.c.isActive) {
          this.b.total(total);
        }
      },
      worked: (worked) => {
        if (!this.c.isActive || this.b.hasTotal()) {
          this.a = new ProgressIndicatorState.Work(this.a.type === 4 ? this.a.total : void 0, this.a.type === 4 && typeof this.a.worked === "number" ? this.a.worked + worked : worked);
          if (this.c.isActive) {
            this.b.worked(worked);
          }
        } else {
          this.a = ProgressIndicatorState.Infinite;
          this.b.infinite().show();
        }
      },
      done: () => {
        this.a = ProgressIndicatorState.Done;
        if (this.c.isActive) {
          this.b.stop().hide();
        }
      }
    };
  }
  async showWhile(promise, delay) {
    if (this.a.type === 3) {
      promise = Promise.allSettled([promise, this.a.whilePromise]);
    }
    this.a = new ProgressIndicatorState.While(promise, delay || 0, Date.now());
    try {
      this.h(delay);
      await promise;
    } catch (error) {
    } finally {
      if (this.a.type !== 3 || this.a.whilePromise === promise) {
        this.a = ProgressIndicatorState.None;
        if (this.c.isActive) {
          this.b.stop().hide();
        }
      }
    }
  }
  h(delay) {
    if (this.c.isActive) {
      this.b.infinite().show(delay);
    }
  }
};
var $6ob = class extends $3c {
  get isActive() {
    return this.c;
  }
  constructor(b, c) {
    super();
    this.b = b;
    this.c = c;
    this.a = this.B(new $ze());
    this.onDidChangeActive = this.a.event;
  }
  f(scopeId) {
    if (scopeId === this.b) {
      if (!this.c) {
        this.c = true;
        this.a.fire();
      }
    }
  }
  g(scopeId) {
    if (scopeId === this.b) {
      if (this.c) {
        this.c = false;
        this.a.fire();
      }
    }
  }
};

// out-build/vs/workbench/browser/actions.js
var MenuActions = class extends $3c {
  get primaryActions() {
    return this.b;
  }
  get secondaryActions() {
    return this.c;
  }
  constructor(menuId, h3, j, m) {
    super();
    this.h = h3;
    this.j = j;
    this.m = m;
    this.b = [];
    this.c = [];
    this.f = this.B(new $ze());
    this.onDidChange = this.f.event;
    this.g = this.B(new $2c());
    this.a = this.B(j.createMenu(menuId, m));
    this.B(this.a.onDidChange(() => this.n()));
    this.n();
  }
  n() {
    this.g.clear();
    const newActions = $Q$(this.a.getActions(this.h));
    this.b = newActions.primary;
    this.c = newActions.secondary;
    this.g.add(this.r([...this.b, ...this.c], {}));
    this.f.fire();
  }
  r(actions, submenus) {
    const disposables = new $2c();
    for (const action of actions) {
      if (action instanceof $eJ && !submenus[action.item.submenu.id]) {
        const menu = submenus[action.item.submenu.id] = disposables.add(this.j.createMenu(action.item.submenu, this.m));
        disposables.add(menu.onDidChange(() => this.n()));
        disposables.add(this.r(action.actions, submenus));
      }
    }
    return disposables;
  }
};
var $yob = class $yob2 extends $3c {
  constructor(menuId, g, h3, j, m) {
    super();
    this.menuId = menuId;
    this.g = g;
    this.h = h3;
    this.j = j;
    this.m = m;
    this.f = this.B(new $ze());
    this.onDidChange = this.f.event;
    this.c = this.B(new MenuActions(menuId, this.h, m, j));
    this.B(this.c.onDidChange(() => this.f.fire()));
  }
  getPrimaryActions() {
    return this.c.primaryActions;
  }
  getSecondaryActions() {
    return this.c.secondaryActions;
  }
  getContextMenuActions() {
    if (this.g) {
      const menu = this.m.getMenuActions(this.g, this.j, this.h);
      return $Q$(menu).secondary;
    }
    return [];
  }
};
$yob = __decorate([
  __param(3, $on),
  __param(4, $cJ)
], $yob);

// out-build/vs/workbench/browser/parts/views/viewFilter.js
var viewFilterMenu = new $bJ("menu.view.filter");
var $7ob = new $bJ("submenu.view.filter");
$dJ.appendMenuItem(viewFilterMenu, {
  submenu: $7ob,
  title: localize(3799, null),
  group: "navigation",
  icon: $6l.filter
});
var MoreFiltersActionViewItem = class extends $V$ {
  constructor() {
    super(...arguments);
    this.P = false;
  }
  set checked(checked) {
    if (this.P !== checked) {
      this.P = checked;
      this.J();
    }
  }
  J() {
    if (this.element) {
      this.element.classList.toggle("checked", this.P);
    }
  }
  render(container2) {
    super.render(container2);
    this.J();
  }
};
var $8ob = class $8ob2 extends $qZ {
  get onDidFocus() {
    return this.H.onDidFocus;
  }
  get onDidBlur() {
    return this.H.onDidBlur;
  }
  constructor(I, J, L, contextKeyService, M) {
    super();
    this.I = I;
    this.J = J;
    this.L = L;
    this.M = M;
    this.r = this.B(new $ze());
    this.onDidChangeFilterText = this.r.event;
    this.w = false;
    this.a = new $Sh(400);
    this.B($1c(() => this.a.cancel()));
    if (I.focusContextKey) {
      this.n = new $nn(I.focusContextKey, false).bindTo(contextKeyService);
    }
    this.element = $(".viewpane-filter");
    [this.c, this.H] = this.N(this.element);
    this.B(this.c);
    this.B(this.H);
    const controlsContainer = $bk(this.element, $(".viewpane-filter-controls"));
    this.g = this.O(controlsContainer);
    this.h = this.B(this.P(controlsContainer));
    this.R();
  }
  hasFocus() {
    return this.c.hasFocus();
  }
  focus() {
    this.c.focus();
  }
  blur() {
    this.c.blur();
  }
  updateBadge(message) {
    this.g.classList.toggle("hidden", !message);
    this.g.textContent = message || "";
    this.R();
  }
  setFilterText(filterText) {
    this.c.value = filterText;
  }
  getFilterText() {
    return this.c.value;
  }
  getHistory() {
    return this.c.getHistory();
  }
  layout(width2) {
    this.element.parentElement?.classList.toggle("grow", width2 > 700);
    this.element.classList.toggle("small", width2 < 400);
    this.R();
    this.y = width2;
  }
  relayout() {
    if (this.y) {
      this.layout(this.y);
    }
  }
  checkMoreFilters(checked) {
    this.w = checked;
    if (this.t) {
      this.t.checked = checked;
    }
  }
  N(container2) {
    const history = this.I.history || [];
    const inputBox = this.B(this.J.createInstance($9bb, container2, this.L, {
      placeholder: this.I.placeholder,
      ariaLabel: this.I.ariaLabel,
      history: new Set(history),
      showHistoryHint: () => $ggb(this.M),
      inputBoxStyles: $B$
    }));
    if (this.I.text) {
      inputBox.value = this.I.text;
    }
    this.B(inputBox.onDidChange((filter) => this.a.trigger(() => this.Q(inputBox))));
    this.B($aj(inputBox.inputElement, $7j.KEY_DOWN, (e) => this.U(e, inputBox)));
    this.B($aj(container2, $7j.KEY_DOWN, this.S));
    this.B($aj(container2, $7j.KEY_UP, this.S));
    this.B($aj(inputBox.inputElement, $7j.CLICK, (e) => {
      e.stopPropagation();
      e.preventDefault();
    }));
    const focusTracker = this.B($_j(inputBox.inputElement));
    if (this.n) {
      this.B(focusTracker.onDidFocus(() => this.n.set(true)));
      this.B(focusTracker.onDidBlur(() => this.n.set(false)));
      this.B($1c(() => this.n.reset()));
    }
    return [inputBox, focusTracker];
  }
  O(container2) {
    const filterBadge = $bk(container2, $(".viewpane-filter-badge.hidden"));
    filterBadge.style.backgroundColor = $Zn($wo);
    filterBadge.style.color = $Zn($xo);
    filterBadge.style.border = `1px solid ${$Zn($ko)}`;
    return filterBadge;
  }
  P(container2) {
    return this.J.createInstance($4$, container2, viewFilterMenu, {
      hiddenItemStrategy: -1,
      actionViewItemProvider: (action, options3) => {
        if (action instanceof $eJ && action.item.submenu.id === $7ob.id) {
          this.t = this.J.createInstance(MoreFiltersActionViewItem, action, options3);
          this.t.checked = this.w;
          return this.t;
        }
        return void 0;
      }
    });
  }
  Q(inputbox) {
    inputbox.addToHistory();
    this.r.fire(inputbox.value);
  }
  R() {
    this.c.inputElement.style.paddingRight = this.element.classList.contains("small") || this.g.classList.contains("hidden") ? "25px" : "150px";
  }
  // Action toolbar is swallowing some keys for action items which should not be for an input box
  S(event) {
    if (event.equals(
      10
      /* KeyCode.Space */
    ) || event.equals(
      15
      /* KeyCode.LeftArrow */
    ) || event.equals(
      17
      /* KeyCode.RightArrow */
    ) || event.equals(
      14
      /* KeyCode.Home */
    ) || event.equals(
      13
      /* KeyCode.End */
    )) {
      event.stopPropagation();
    }
  }
  U(event, filterInputBox) {
    let handled = false;
    if (event.equals(
      2
      /* KeyCode.Tab */
    ) && !this.h.isEmpty()) {
      this.h.focus();
      handled = true;
    }
    if (handled) {
      event.stopPropagation();
      event.preventDefault();
    }
  }
};
$8ob = __decorate([
  __param(1, $Pk),
  __param(2, $40),
  __param(3, $on),
  __param(4, $Ty)
], $8ob);

// out-build/vs/workbench/browser/parts/views/viewPane.js
var $_ob_1;
var ViewPaneShowActions;
(function(ViewPaneShowActions2) {
  ViewPaneShowActions2[ViewPaneShowActions2["Default"] = 0] = "Default";
  ViewPaneShowActions2[ViewPaneShowActions2["WhenExpanded"] = 1] = "WhenExpanded";
  ViewPaneShowActions2[ViewPaneShowActions2["Always"] = 2] = "Always";
})(ViewPaneShowActions || (ViewPaneShowActions = {}));
var $$ob = new $Um("viewpane.action.filter");
var viewPaneContainerExpandedIcon = $9r("view-pane-container-expanded", $6l.chevronDown, localize(3800, null));
var viewPaneContainerCollapsedIcon = $9r("view-pane-container-collapsed", $6l.chevronRight, localize(3801, null));
var viewsRegistry = $Wn.as(Extensions5.ViewsRegistry);
var ViewWelcomeController = class ViewWelcomeController2 {
  get enabled() {
    return this.c;
  }
  constructor(j, k, l, m, n, o, lifecycleService) {
    this.j = j;
    this.k = k;
    this.l = l;
    this.m = m;
    this.n = n;
    this.o = o;
    this.b = [];
    this.c = false;
    this.g = new $2c();
    this.h = this.g.add(new $2c());
    this.i = this.g.add(new $2c());
    this.g.add(Event2.runAndSubscribe(this.k.onDidChangeViewWelcomeState, () => this.q()));
    this.g.add(lifecycleService.onWillShutdown(() => this.dispose()));
  }
  layout(height, width2) {
    if (!this.c) {
      return;
    }
    this.d.style.height = `${height}px`;
    this.d.style.width = `${width2}px`;
    this.d.classList.toggle("wide", width2 > 640);
    this.f.scanDomNode();
  }
  focus() {
    if (!this.c) {
      return;
    }
    this.d.focus();
  }
  q() {
    const enabled = this.k.shouldShowWelcome();
    if (this.c === enabled) {
      return;
    }
    this.c = enabled;
    if (!enabled) {
      this.h.clear();
      return;
    }
    this.j.classList.add("welcome");
    const viewWelcomeContainer = $bk(this.j, $(".welcome-view"));
    this.d = $(".welcome-view-content", { tabIndex: 0 });
    this.f = new $CZ(this.d, { alwaysConsumeMouseWheel: true, horizontal: 2, vertical: 3 });
    $bk(viewWelcomeContainer, this.f.getDomNode());
    this.h.add($1c(() => {
      this.j.classList.remove("welcome");
      this.f.dispose();
      viewWelcomeContainer.remove();
      this.f = void 0;
      this.d = void 0;
    }));
    this.o.onDidChangeContext(this.s, this, this.h);
    Event2.chain(viewsRegistry.onDidChangeViewWelcomeContent, ($149) => $149.filter((id2) => id2 === this.k.id))(this.r, this, this.h);
    this.r();
  }
  r() {
    const descriptors = viewsRegistry.getViewWelcomeContent(this.k.id);
    this.b = [];
    for (const descriptor of descriptors) {
      if (descriptor.when === "default") {
        this.a = { descriptor, visible: true };
      } else {
        const visible = descriptor.when ? this.o.contextMatchesRules(descriptor.when) : true;
        this.b.push({ descriptor, visible });
      }
    }
    this.t();
  }
  s() {
    let didChange = false;
    for (const item of this.b) {
      if (!item.descriptor.when || item.descriptor.when === "default") {
        continue;
      }
      const visible = this.o.contextMatchesRules(item.descriptor.when);
      if (item.visible === visible) {
        continue;
      }
      item.visible = visible;
      didChange = true;
    }
    if (didChange) {
      this.t();
    }
  }
  t() {
    this.i.clear();
    this.d.innerText = "";
    const contents = this.u();
    if (contents.length === 0) {
      this.j.classList.remove("welcome");
      this.f.scanDomNode();
      return;
    }
    let buttonsCount = 0;
    for (const { content, precondition: precondition2, renderSecondaryButtons } of contents) {
      const lines = content.split("\n");
      for (let line of lines) {
        line = line.trim();
        if (!line) {
          continue;
        }
        const linkedText = $U3(line);
        if (linkedText.nodes.length === 1 && typeof linkedText.nodes[0] !== "string") {
          const node = linkedText.nodes[0];
          const buttonContainer = $bk(this.d, $(".button-container"));
          const button = new $k2(buttonContainer, { title: node.title, supportIcons: true, secondary: renderSecondaryButtons && buttonsCount > 0 ? true : false, ...$q$ });
          button.label = node.label;
          button.onDidClick((_) => {
            this.n.publicLog2("views.welcomeAction", { viewId: this.k.id, uri: node.href });
            this.m.open(node.href, { allowCommands: true });
          }, null, this.i);
          this.i.add(button);
          buttonsCount++;
          if (precondition2) {
            const updateEnablement = () => button.enabled = this.o.contextMatchesRules(precondition2);
            updateEnablement();
            const keys = new Set(precondition2.keys());
            const onDidChangeContext = Event2.filter(this.o.onDidChangeContext, (e) => e.affectsSome(keys));
            onDidChangeContext(updateEnablement, null, this.i);
          }
        } else {
          const p = $bk(this.d, $("p"));
          for (const node of linkedText.nodes) {
            if (typeof node === "string") {
              $bk(p, ...$B1(node));
            } else {
              const link2 = this.i.add(this.l.createInstance(Link2, p, node, {}));
              if (precondition2 && node.href.startsWith("command:")) {
                const updateEnablement = () => link2.enabled = this.o.contextMatchesRules(precondition2);
                updateEnablement();
                const keys = new Set(precondition2.keys());
                const onDidChangeContext = Event2.filter(this.o.onDidChangeContext, (e) => e.affectsSome(keys));
                onDidChangeContext(updateEnablement, null, this.i);
              }
            }
          }
        }
      }
    }
    this.j.classList.add("welcome");
    this.f.scanDomNode();
  }
  u() {
    const visibleItems = this.b.filter((v) => v.visible);
    if (visibleItems.length === 0 && this.a) {
      return [this.a.descriptor];
    }
    return visibleItems.map((v) => v.descriptor);
  }
  dispose() {
    this.g.dispose();
  }
};
ViewWelcomeController = __decorate([
  __param(2, $Pk),
  __param(3, $O4),
  __param(4, $zv),
  __param(5, $on),
  __param(6, $KL)
], ViewWelcomeController);
var $_ob = class $_ob2 extends $a3 {
  static {
    $_ob_1 = this;
  }
  static {
    this.Y = "workbench.view.alwaysShowHeaderActions";
  }
  get title() {
    return this.gb;
  }
  get titleDescription() {
    return this.hb;
  }
  get singleViewPaneContainerTitle() {
    return this.ib;
  }
  constructor(options3, yb, zb, Ab, Bb, Cb, Db, Eb, Fb, Gb, Hb, Ib) {
    super({ ...options3, ...{
      orientation: Cb.getViewLocationById(options3.id) === 1 ? 1 : 0
      /* Orientation.VERTICAL */
    } });
    this.yb = yb;
    this.zb = zb;
    this.Ab = Ab;
    this.Bb = Bb;
    this.Cb = Cb;
    this.Db = Db;
    this.Eb = Eb;
    this.Fb = Fb;
    this.Gb = Gb;
    this.Hb = Hb;
    this.Ib = Ib;
    this.Z = this.B(new $ze());
    this.onDidFocus = this.Z.event;
    this.bb = this.B(new $ze());
    this.onDidBlur = this.bb.event;
    this.cb = this.B(new $ze());
    this.onDidChangeBodyVisibility = this.cb.event;
    this.db = this.B(new $ze());
    this.onDidChangeTitleArea = this.db.event;
    this.eb = this.B(new $ze());
    this.onDidChangeViewWelcomeState = this.eb.event;
    this.fb = false;
    this.id = options3.id;
    this.gb = options3.title;
    this.hb = options3.titleDescription;
    this.ib = options3.singleViewPaneContainerTitle;
    this.mb = options3.showActions ?? ViewPaneShowActions.Default;
    this.xb = this.B(Bb.createScoped(this.element));
    this.xb.createKey("view", this.id);
    const viewLocationKey = this.xb.createKey("viewLocation", $0M(Cb.getViewLocationById(this.id)));
    this.B(Event2.filter(Cb.onDidChangeLocation, (e) => e.views.some((view) => view.id === this.id))(() => viewLocationKey.set($0M(Cb.getViewLocationById(this.id)))));
    const childInstantiationService = this.B(this.Db.createChild(new $Ok([$on, this.xb])));
    this.menuActions = this.B(childInstantiationService.createInstance($yob, options3.titleMenuId ?? $bJ.ViewTitle, $bJ.ViewTitleContext, { shouldForwardArgs: !options3.donotForwardArgs, renderShortTitle: true }));
    this.B(this.menuActions.onDidChange(() => this.$b()));
  }
  get headerVisible() {
    return super.headerVisible;
  }
  set headerVisible(visible) {
    super.headerVisible = visible;
    this.element.classList.toggle("merged-header", !visible);
  }
  setVisible(visible) {
    if (this.fb !== visible) {
      this.fb = visible;
      if (this.isExpanded()) {
        this.cb.fire(visible);
      }
    }
  }
  isVisible() {
    return this.fb;
  }
  isBodyVisible() {
    return this.fb && this.isExpanded();
  }
  setExpanded(expanded2) {
    const changed = super.setExpanded(expanded2);
    if (changed) {
      this.cb.fire(expanded2);
    }
    this.Lb();
    return changed;
  }
  render() {
    super.render();
    const focusTracker = $_j(this.element);
    this.B(focusTracker);
    this.B(focusTracker.onDidFocus(() => this.Z.fire()));
    this.B(focusTracker.onDidBlur(() => this.bb.fire()));
  }
  U(container2) {
    this.nb = container2;
    this.vb = $bk(container2, $(`.twisty-container${ThemeIcon.asCSSSelector(this.Mb(this.isExpanded()))}`));
    this.Ob(container2, this.title);
    const actions = $bk(container2, $(".actions"));
    actions.classList.toggle("show-always", this.mb === ViewPaneShowActions.Always);
    actions.classList.toggle("show-expanded", this.mb === ViewPaneShowActions.WhenExpanded);
    this.lb = this.Db.createInstance($3$, actions, {
      orientation: 0,
      actionViewItemProvider: (action, options3) => this.getActionViewItem(action, options3),
      ariaLabel: localize(3802, null, this.title),
      getKeyBinding: (action) => this.yb.lookupKeybinding(action.id),
      renderDropdownAsChildElement: true,
      actionRunner: this.getActionRunner(),
      resetMenu: this.menuActions.menuId
    });
    this.B(this.lb);
    this.Yb();
    this.B($_i(actions, $7j.CLICK, (e) => e.preventDefault()));
    const viewContainerModel = this.Cb.getViewContainerByViewId(this.id);
    if (viewContainerModel) {
      this.B(this.Cb.getViewContainerModel(viewContainerModel).onDidChangeContainerInfo(({ title }) => this.Qb(this.title)));
    } else {
      console.error(`View container model not found for view ${this.id}`);
    }
    const onDidRelevantConfigurationChange = Event2.filter(this.Ab.onDidChangeConfiguration, (e) => e.affectsConfiguration($_ob_1.Y));
    this.B(onDidRelevantConfigurationChange(this.Zb, this));
    this.Zb();
  }
  S() {
    super.S();
    this.Lb();
  }
  Lb() {
    if (this.vb) {
      this.vb.classList.remove(...ThemeIcon.asClassNameArray(this.Mb(!this.z)));
      this.vb.classList.add(...ThemeIcon.asClassNameArray(this.Mb(this.z)));
    }
  }
  Mb(expanded2) {
    return expanded2 ? viewPaneContainerExpandedIcon : viewPaneContainerCollapsedIcon;
  }
  style(styles) {
    super.style(styles);
    const icon2 = this.Nb();
    if (this.tb) {
      const fgColor = $ZZ(styles.headerForeground, $Zn($eo));
      if (URI.isUri(icon2)) {
        this.tb.style.backgroundColor = fgColor;
        this.tb.style.color = "";
      } else {
        this.tb.style.color = fgColor;
        this.tb.style.backgroundColor = "";
      }
    }
  }
  Nb() {
    return this.Cb.getViewDescriptorById(this.id)?.containerIcon || $8M;
  }
  Ob(container2, title) {
    this.tb = $bk(container2, $(".icon", void 0));
    const icon2 = this.Nb();
    let cssClass = void 0;
    if (URI.isUri(icon2)) {
      cssClass = `view-${this.id.replace(/[\.\:]/g, "-")}`;
      const iconClass = `.pane-header .icon.${cssClass}`;
      $XZ(iconClass, `
				mask: ${$5Z(icon2)} no-repeat 50% 50%;
				mask-size: 24px;
				-webkit-mask: ${$5Z(icon2)} no-repeat 50% 50%;
				-webkit-mask-size: 16px;
			`);
    } else if (ThemeIcon.isThemeIcon(icon2)) {
      cssClass = ThemeIcon.asClassName(icon2);
    }
    if (cssClass) {
      this.tb.classList.add(...cssClass.split(" "));
    }
    const calculatedTitle = this.Tb(title);
    this.ob = $bk(container2, $("h3.title", {}, calculatedTitle));
    this.pb = this.B(this.Hb.setupManagedHover($JZ("mouse"), this.ob, calculatedTitle));
    if (this.hb) {
      this.Rb(this.hb);
    }
    this.ub = this.B(this.Hb.setupManagedHover($JZ("mouse"), this.tb, calculatedTitle));
    this.tb.setAttribute("aria-label", this.Pb(calculatedTitle));
  }
  Pb(title) {
    const viewHasAccessibilityHelpContent = this.Cb.getViewDescriptorById(this.id)?.accessibilityHelpContent;
    const accessibleViewHasShownForView = this.Ib?.hasShownAccessibleView(this.id);
    if (!viewHasAccessibilityHelpContent || accessibleViewHasShownForView) {
      return title;
    }
    return localize(3803, null, title);
  }
  Qb(title) {
    const calculatedTitle = this.Tb(title);
    if (this.ob) {
      this.ob.textContent = calculatedTitle;
      this.pb?.update(calculatedTitle);
    }
    if (this.tb) {
      this.ub?.update(calculatedTitle);
      this.tb.setAttribute("aria-label", this.Pb(calculatedTitle));
    }
    this.gb = title;
    this.db.fire();
  }
  Rb(description) {
    if (this.qb) {
      this.qb.textContent = description ?? "";
      this.rb?.update(description ?? "");
    } else if (description && this.ob) {
      this.qb = $ak(this.ob, $("span.description", {}, description));
      this.rb = this.B(this.Hb.setupManagedHover($JZ("mouse"), this.qb, description));
    }
  }
  Sb(description) {
    this.Rb(description);
    this.hb = description;
    this.db.fire();
  }
  Tb(title) {
    const viewContainer5 = this.Cb.getViewContainerByViewId(this.id);
    const model = this.Cb.getViewContainerModel(viewContainer5);
    const viewDescriptor3 = this.Cb.getViewDescriptorById(this.id);
    const isDefault = this.Cb.getDefaultContainerById(this.id) === viewContainer5;
    if (!isDefault && viewDescriptor3?.containerTitle && model.title !== viewDescriptor3.containerTitle) {
      return `${viewDescriptor3.containerTitle}: ${title}`;
    }
    return title;
  }
  W(container2) {
    this.wb = this.B(this.Db.createInstance(ViewWelcomeController, container2, this));
  }
  X(height, width2) {
    this.wb.layout(height, width2);
  }
  onDidScrollRoot() {
  }
  getProgressIndicator() {
    if (this.jb === void 0) {
      this.jb = this.B(new $02(this.element, $s$));
      this.jb.hide();
    }
    if (this.kb === void 0) {
      const that = this;
      this.kb = this.B(new $5ob($Kg(this.jb), new class extends $6ob {
        constructor() {
          super(that.id, that.isBodyVisible());
          this.B(that.onDidChangeBodyVisibility((isVisible) => isVisible ? this.f(that.id) : this.g(that.id)));
        }
      }()));
    }
    return this.kb;
  }
  Wb() {
    return this.Cb.getViewContainerByViewId(this.id).id;
  }
  Xb() {
    return $bpb(this.Cb.getViewLocationById(this.id));
  }
  focus() {
    if (this.wb.enabled) {
      this.wb.focus();
    } else if (this.element) {
      this.element.focus();
    }
    if ($Mj(this.element) || $Nj(this.element)) {
      this.Z.fire();
    }
  }
  Yb() {
    if (this.lb) {
      const primaryActions = [...this.menuActions.getPrimaryActions()];
      if (this.shouldShowFilterInHeader()) {
        primaryActions.unshift($$ob);
      }
      this.lb.setActions($MZ(primaryActions), $MZ(this.menuActions.getSecondaryActions()));
      this.lb.context = this.getActionsContext();
    }
  }
  Zb() {
    if (!this.nb) {
      return;
    }
    const shouldAlwaysShowActions = this.Ab.getValue("workbench.view.alwaysShowHeaderActions");
    this.nb.classList.toggle("actions-always-visible", shouldAlwaysShowActions);
  }
  $b() {
    this.Yb();
    this.db.fire();
  }
  getActionViewItem(action, options3) {
    if (action.id === $$ob.id) {
      const that = this;
      return new class extends $T1 {
        constructor() {
          super(null, action);
        }
        setFocusable() {
        }
        get trapsArrowNavigation() {
          return true;
        }
        render(container2) {
          container2.classList.add("viewpane-filter-container");
          const filter = that.getFilterWidget();
          $bk(container2, filter.element);
          filter.relayout();
        }
      }();
    }
    return $X$(this.Db, action, { ...options3, ...{ menuAsChild: action instanceof $eJ } });
  }
  getActionsContext() {
    return void 0;
  }
  getActionRunner() {
    return void 0;
  }
  getOptimalWidth() {
    return 0;
  }
  saveState() {
  }
  shouldShowWelcome() {
    return false;
  }
  getFilterWidget() {
    return void 0;
  }
  shouldShowFilterInHeader() {
    return false;
  }
};
$_ob = $_ob_1 = __decorate([
  __param(1, $Ty),
  __param(2, $50),
  __param(3, $kl),
  __param(4, $on),
  __param(5, $$M),
  __param(6, $Pk),
  __param(7, $O4),
  __param(8, $gs),
  __param(9, $zv),
  __param(10, $5$)
], $_ob);
var $apb = class $apb2 extends $_ob {
  constructor(options3, keybindingService, contextMenuService, configurationService, contextKeyService, viewDescriptorService, instantiationService, openerService, themeService, telemetryService, hoverService, accessibleViewService) {
    super(options3, keybindingService, contextMenuService, configurationService, contextKeyService, viewDescriptorService, instantiationService, openerService, themeService, telemetryService, hoverService, accessibleViewService);
    const childInstantiationService = this.B(instantiationService.createChild(new $Ok([$on, this.xb])));
    this.filterWidget = this.B(childInstantiationService.createInstance($8ob, options3.filterOptions));
  }
  getFilterWidget() {
    return this.filterWidget;
  }
  W(container2) {
    super.W(container2);
    this.j = $bk(container2, $(".viewpane-filter-container"));
  }
  X(height, width2) {
    super.X(height, width2);
    this.g = new $rj(width2, height);
    const wasFilterShownInHeader = !this.j?.hasChildNodes();
    const shouldShowFilterInHeader = this.shouldShowFilterInHeader();
    if (wasFilterShownInHeader !== shouldShowFilterInHeader) {
      if (shouldShowFilterInHeader) {
        $dk(this.j);
      }
      this.$b();
      if (!shouldShowFilterInHeader) {
        $bk(this.j, this.filterWidget.element);
      }
    }
    if (!shouldShowFilterInHeader) {
      height = height - 44;
    }
    this.filterWidget.layout(width2);
    this.L(height, width2);
  }
  shouldShowFilterInHeader() {
    return !(this.g && this.g.width < 600 && this.g.height > 100);
  }
};
$apb = __decorate([
  __param(1, $Ty),
  __param(2, $50),
  __param(3, $kl),
  __param(4, $on),
  __param(5, $$M),
  __param(6, $Pk),
  __param(7, $O4),
  __param(8, $gs),
  __param(9, $zv),
  __param(10, $5$)
], $apb);
function $bpb(location3) {
  let background, overlayBackground, stickyScrollBackground, stickyScrollBorder, stickyScrollShadow;
  switch (location3) {
    case 1:
      background = $Imb;
      overlayBackground = $Qmb;
      stickyScrollBackground = $Vmb;
      stickyScrollBorder = $Wmb;
      stickyScrollShadow = $Xmb;
      break;
    case 0:
    case 2:
    default:
      background = $Pnb;
      overlayBackground = $Vnb;
      stickyScrollBackground = $1nb;
      stickyScrollBorder = $2nb;
      stickyScrollShadow = $3nb;
  }
  return {
    background,
    overlayBackground,
    listOverrideStyles: {
      listBackground: background,
      treeStickyScrollBackground: stickyScrollBackground,
      treeStickyScrollBorder: stickyScrollBorder,
      treeStickyScrollShadow: stickyScrollShadow
    }
  };
}
var $cpb = class extends $gJ {
  constructor(desc) {
    super(desc);
    this.desc = desc;
  }
  run(accessor, ...args2) {
    const view = accessor.get($uob).getActiveViewWithId(this.desc.viewId);
    if (view) {
      return this.runInView(accessor, view, ...args2);
    }
    return void 0;
  }
};

// out-build/vs/workbench/common/editor/editorGroupModel.js
var $9I_1;
var EditorOpenPositioning = {
  LEFT: "left",
  RIGHT: "right",
  FIRST: "first",
  LAST: "last"
};
function $4I(group2) {
  const candidate = group2;
  return !!(candidate && typeof candidate === "object" && Array.isArray(candidate.editors) && Array.isArray(candidate.mru));
}
function $6I(e) {
  const candidate = e;
  return candidate.kind === 5 && candidate.editorIndex !== void 0;
}
function $7I(e) {
  const candidate = e;
  return candidate.kind === 7 && candidate.editorIndex !== void 0 && candidate.oldEditorIndex !== void 0;
}
function $8I(e) {
  const candidate = e;
  return candidate.kind === 6 && candidate.editorIndex !== void 0 && candidate.context !== void 0 && candidate.sticky !== void 0;
}
var $9I = class $9I2 extends $3c {
  static {
    $9I_1 = this;
  }
  static {
    this.a = 0;
  }
  get id() {
    return this.c;
  }
  get n() {
    return this.m[0] ?? null;
  }
  constructor(labelOrSerializedGroup, y, z) {
    super();
    this.y = y;
    this.z = z;
    this.b = this.B(new $ze({
      leakWarningThreshold: 500
      /* increased for users with hundreds of inputs opened */
    }));
    this.onDidModelChange = this.b.event;
    this.f = [];
    this.g = [];
    this.h = /* @__PURE__ */ new Set();
    this.j = false;
    this.m = [];
    this.r = null;
    this.s = -1;
    this.t = /* @__PURE__ */ new Set();
    if ($4I(labelOrSerializedGroup)) {
      this.c = this.W(labelOrSerializedGroup);
    } else {
      this.c = $9I_1.a++;
    }
    this.D();
    this.C();
  }
  C() {
    this.B(this.z.onDidChangeConfiguration((e) => this.D(e)));
  }
  D(e) {
    if (e && !e.affectsConfiguration("workbench.editor.openPositioning") && !e.affectsConfiguration("workbench.editor.focusRecentEditorAfterClose")) {
      return;
    }
    this.u = this.z.getValue("workbench.editor.openPositioning");
    this.w = this.z.getValue("workbench.editor.focusRecentEditorAfterClose");
  }
  get count() {
    return this.f.length;
  }
  get stickyCount() {
    return this.s + 1;
  }
  getEditors(order, options3) {
    const editors = order === 0 ? this.g.slice(0) : this.f.slice(0);
    if (options3?.excludeSticky) {
      if (order === 0) {
        return editors.filter((editor) => !this.isSticky(editor));
      }
      return editors.slice(this.s + 1);
    }
    return editors;
  }
  getEditorByIndex(index) {
    return this.f[index];
  }
  get activeEditor() {
    return this.n;
  }
  isActive(candidate) {
    return this.U(this.n, candidate);
  }
  get previewEditor() {
    return this.r;
  }
  openEditor(candidate, options3) {
    const makeSticky = options3?.sticky || typeof options3?.index === "number" && this.isSticky(options3.index);
    const makePinned = options3?.pinned || options3?.sticky;
    const makeTransient = !!options3?.transient;
    const makeActive = options3?.active || !this.activeEditor || !makePinned && this.r === this.activeEditor;
    const existingEditorAndIndex = this.findEditor(candidate, options3);
    if (!existingEditorAndIndex) {
      const newEditor = candidate;
      const indexOfActive = this.indexOf(this.n);
      let targetIndex;
      if (options3 && typeof options3.index === "number") {
        targetIndex = options3.index;
      } else if (this.u === EditorOpenPositioning.FIRST) {
        targetIndex = 0;
        if (!makeSticky && this.isSticky(targetIndex)) {
          targetIndex = this.s + 1;
        }
      } else if (this.u === EditorOpenPositioning.LAST) {
        targetIndex = this.f.length;
      } else {
        if (this.u === EditorOpenPositioning.LEFT) {
          if (indexOfActive === 0 || !this.f.length) {
            targetIndex = 0;
          } else {
            targetIndex = indexOfActive;
          }
        } else {
          targetIndex = indexOfActive + 1;
        }
        if (!makeSticky && this.isSticky(targetIndex)) {
          targetIndex = this.s + 1;
        }
      }
      if (makeSticky) {
        this.s++;
        if (!this.isSticky(targetIndex)) {
          targetIndex = this.s;
        }
      }
      if (makePinned || !this.r) {
        this.S(targetIndex, false, newEditor);
      }
      if (makeTransient) {
        this.R(newEditor, targetIndex, true);
      }
      if (!makePinned) {
        if (this.r) {
          const indexOfPreview = this.indexOf(this.r);
          if (targetIndex > indexOfPreview) {
            targetIndex--;
          }
          this.G(this.r, newEditor, targetIndex, !makeActive);
        }
        this.r = newEditor;
      }
      this.F(newEditor);
      const event = {
        kind: 5,
        editor: newEditor,
        editorIndex: targetIndex
      };
      this.b.fire(event);
      this.setSelection(makeActive ? newEditor : this.activeEditor, options3?.inactiveSelection ?? []);
      return {
        editor: newEditor,
        isNew: true
      };
    } else {
      const [existingEditor, existingEditorIndex] = existingEditorAndIndex;
      this.R(existingEditor, existingEditorIndex, makeTransient === false ? false : this.isTransient(existingEditor));
      if (makePinned) {
        this.N(existingEditor, existingEditorIndex);
      }
      this.setSelection(makeActive ? existingEditor : this.activeEditor, options3?.inactiveSelection ?? []);
      if (options3 && typeof options3.index === "number") {
        this.moveEditor(existingEditor, options3.index);
      }
      if (makeSticky) {
        this.P(existingEditor, this.indexOf(existingEditor));
      }
      return {
        editor: existingEditor,
        isNew: false
      };
    }
  }
  F(editor) {
    const listeners = new $2c();
    this.h.add(listeners);
    listeners.add(Event2.once(editor.onWillDispose)(() => {
      const editorIndex = this.f.indexOf(editor);
      if (editorIndex >= 0) {
        const event = {
          kind: 15,
          editor,
          editorIndex
        };
        this.b.fire(event);
      }
    }));
    listeners.add(editor.onDidChangeDirty(() => {
      const event = {
        kind: 14,
        editor,
        editorIndex: this.f.indexOf(editor)
      };
      this.b.fire(event);
    }));
    listeners.add(editor.onDidChangeLabel(() => {
      const event = {
        kind: 9,
        editor,
        editorIndex: this.f.indexOf(editor)
      };
      this.b.fire(event);
    }));
    listeners.add(editor.onDidChangeCapabilities(() => {
      const event = {
        kind: 10,
        editor,
        editorIndex: this.f.indexOf(editor)
      };
      this.b.fire(event);
    }));
    listeners.add(this.onDidModelChange((event) => {
      if (event.kind === 6 && event.editor?.matches(editor)) {
        $Xc(listeners);
        this.h.delete(listeners);
      }
    }));
  }
  G(toReplace, replaceWith, replaceIndex, openNext = true) {
    const closeResult = this.H(toReplace, EditorCloseContext.REPLACE, openNext);
    this.S(replaceIndex, false, replaceWith);
    if (closeResult) {
      const event = {
        kind: 6,
        ...closeResult
      };
      this.b.fire(event);
    }
  }
  closeEditor(candidate, context = EditorCloseContext.UNKNOWN, openNext = true) {
    const closeResult = this.H(candidate, context, openNext);
    if (closeResult) {
      const event = {
        kind: 6,
        ...closeResult
      };
      this.b.fire(event);
      return closeResult;
    }
    return void 0;
  }
  H(candidate, context, openNext) {
    const index = this.indexOf(candidate);
    if (index === -1) {
      return void 0;
    }
    const editor = this.f[index];
    const sticky = this.isSticky(index);
    const isActiveEditor = this.n === editor;
    if (openNext && isActiveEditor) {
      if (this.g.length > 1) {
        let newActive;
        if (this.w) {
          newActive = this.g[1];
        } else {
          if (index === this.f.length - 1) {
            newActive = this.f[index - 1];
          } else {
            newActive = this.f[index + 1];
          }
        }
        const newInactiveSelectedEditors = this.m.filter((selected) => selected !== editor && selected !== newActive);
        this.M(newActive, this.f.indexOf(newActive), newInactiveSelectedEditors);
      } else {
        this.M(null, void 0, []);
      }
    } else if (!isActiveEditor) {
      if (this.L(editor)) {
        const newInactiveSelectedEditors = this.m.filter((selected) => selected !== editor && selected !== this.activeEditor);
        this.M(this.activeEditor, this.indexOf(this.activeEditor), newInactiveSelectedEditors);
      }
    }
    if (this.r === editor) {
      this.r = null;
    }
    this.t.delete(editor);
    this.S(index, true);
    return { editor, sticky, editorIndex: index, context };
  }
  moveEditor(candidate, toIndex) {
    if (toIndex >= this.f.length) {
      toIndex = this.f.length - 1;
    } else if (toIndex < 0) {
      toIndex = 0;
    }
    const index = this.indexOf(candidate);
    if (index < 0 || toIndex === index) {
      return;
    }
    const editor = this.f[index];
    const sticky = this.s;
    if (this.isSticky(index) && toIndex > this.s) {
      this.s--;
    } else if (!this.isSticky(index) && toIndex <= this.s) {
      this.s++;
    }
    this.f.splice(index, 1);
    this.f.splice(toIndex, 0, editor);
    const event = {
      kind: 7,
      editor,
      oldEditorIndex: index,
      editorIndex: toIndex
    };
    this.b.fire(event);
    if (sticky !== this.s) {
      const event2 = {
        kind: 13,
        editor,
        editorIndex: toIndex
      };
      this.b.fire(event2);
    }
    return editor;
  }
  setActive(candidate) {
    let result = void 0;
    if (!candidate) {
      this.I();
    } else {
      result = this.J(candidate);
    }
    return result;
  }
  I() {
    this.b.fire({
      kind: 0
      /* GroupModelChangeKind.GROUP_ACTIVE */
    });
  }
  J(candidate) {
    const res = this.findEditor(candidate);
    if (!res) {
      return;
    }
    const [editor, editorIndex] = res;
    this.M(editor, editorIndex, []);
    return editor;
  }
  get selectedEditors() {
    return this.f.filter((editor) => this.L(editor));
  }
  isSelected(editorCandidateOrIndex) {
    let editor;
    if (typeof editorCandidateOrIndex === "number") {
      editor = this.f[editorCandidateOrIndex];
    } else {
      editor = this.findEditor(editorCandidateOrIndex)?.[0];
    }
    return !!editor && this.L(editor);
  }
  L(editor) {
    return this.m.includes(editor);
  }
  setSelection(activeSelectedEditorCandidate, inactiveSelectedEditorCandidates) {
    const res = this.findEditor(activeSelectedEditorCandidate);
    if (!res) {
      return;
    }
    const [activeSelectedEditor, activeSelectedEditorIndex] = res;
    const inactiveSelectedEditors = /* @__PURE__ */ new Set();
    for (const inactiveSelectedEditorCandidate of inactiveSelectedEditorCandidates) {
      const res2 = this.findEditor(inactiveSelectedEditorCandidate);
      if (!res2) {
        return;
      }
      const [inactiveSelectedEditor] = res2;
      if (inactiveSelectedEditor === activeSelectedEditor) {
        continue;
      }
      inactiveSelectedEditors.add(inactiveSelectedEditor);
    }
    this.M(activeSelectedEditor, activeSelectedEditorIndex, Array.from(inactiveSelectedEditors));
  }
  M(activeSelectedEditor, activeSelectedEditorIndex, inactiveSelectedEditors) {
    const previousActiveEditor = this.activeEditor;
    const previousSelection = this.m;
    let newSelection;
    if (activeSelectedEditor) {
      newSelection = [activeSelectedEditor, ...inactiveSelectedEditors];
    } else {
      newSelection = [];
    }
    this.m = newSelection;
    const activeEditorChanged = activeSelectedEditor && typeof activeSelectedEditorIndex === "number" && previousActiveEditor !== activeSelectedEditor;
    if (activeEditorChanged) {
      const mruIndex = this.indexOf(activeSelectedEditor, this.g);
      this.g.splice(mruIndex, 1);
      this.g.unshift(activeSelectedEditor);
      const event = {
        kind: 8,
        editor: activeSelectedEditor,
        editorIndex: activeSelectedEditorIndex
      };
      this.b.fire(event);
    }
    if (activeEditorChanged || previousSelection.length !== newSelection.length || previousSelection.some((editor) => !newSelection.includes(editor))) {
      const event = {
        kind: 4
        /* GroupModelChangeKind.EDITORS_SELECTION */
      };
      this.b.fire(event);
    }
  }
  setIndex(index) {
    this.b.fire({
      kind: 1
      /* GroupModelChangeKind.GROUP_INDEX */
    });
  }
  setLabel(label3) {
    this.b.fire({
      kind: 2
      /* GroupModelChangeKind.GROUP_LABEL */
    });
  }
  pin(candidate) {
    const res = this.findEditor(candidate);
    if (!res) {
      return;
    }
    const [editor, editorIndex] = res;
    this.N(editor, editorIndex);
    return editor;
  }
  N(editor, editorIndex) {
    if (this.isPinned(editor)) {
      return;
    }
    this.setTransient(editor, false);
    this.r = null;
    const event = {
      kind: 11,
      editor,
      editorIndex
    };
    this.b.fire(event);
  }
  unpin(candidate) {
    const res = this.findEditor(candidate);
    if (!res) {
      return;
    }
    const [editor, editorIndex] = res;
    this.O(editor, editorIndex);
    return editor;
  }
  O(editor, editorIndex) {
    if (!this.isPinned(editor)) {
      return;
    }
    const oldPreview = this.r;
    this.r = editor;
    const event = {
      kind: 11,
      editor,
      editorIndex
    };
    this.b.fire(event);
    if (oldPreview) {
      this.closeEditor(oldPreview, EditorCloseContext.UNPIN);
    }
  }
  isPinned(editorCandidateOrIndex) {
    let editor;
    if (typeof editorCandidateOrIndex === "number") {
      editor = this.f[editorCandidateOrIndex];
    } else {
      editor = editorCandidateOrIndex;
    }
    return !this.U(this.r, editor);
  }
  stick(candidate) {
    const res = this.findEditor(candidate);
    if (!res) {
      return;
    }
    const [editor, editorIndex] = res;
    this.P(editor, editorIndex);
    return editor;
  }
  P(editor, editorIndex) {
    if (this.isSticky(editorIndex)) {
      return;
    }
    this.pin(editor);
    const newEditorIndex = this.s + 1;
    this.moveEditor(editor, newEditorIndex);
    this.s++;
    const event = {
      kind: 13,
      editor,
      editorIndex: newEditorIndex
    };
    this.b.fire(event);
  }
  unstick(candidate) {
    const res = this.findEditor(candidate);
    if (!res) {
      return;
    }
    const [editor, editorIndex] = res;
    this.Q(editor, editorIndex);
    return editor;
  }
  Q(editor, editorIndex) {
    if (!this.isSticky(editorIndex)) {
      return;
    }
    const newEditorIndex = this.s;
    this.moveEditor(editor, newEditorIndex);
    this.s--;
    const event = {
      kind: 13,
      editor,
      editorIndex: newEditorIndex
    };
    this.b.fire(event);
  }
  isSticky(candidateOrIndex) {
    if (this.s < 0) {
      return false;
    }
    let index;
    if (typeof candidateOrIndex === "number") {
      index = candidateOrIndex;
    } else {
      index = this.indexOf(candidateOrIndex);
    }
    if (index < 0) {
      return false;
    }
    return index <= this.s;
  }
  setTransient(candidate, transient) {
    if (!transient && this.t.size === 0) {
      return;
    }
    const res = this.findEditor(candidate);
    if (!res) {
      return;
    }
    const [editor, editorIndex] = res;
    this.R(editor, editorIndex, transient);
    return editor;
  }
  R(editor, editorIndex, transient) {
    if (transient) {
      if (this.t.has(editor)) {
        return;
      }
      this.t.add(editor);
    } else {
      if (!this.t.has(editor)) {
        return;
      }
      this.t.delete(editor);
    }
    const event = {
      kind: 12,
      editor,
      editorIndex
    };
    this.b.fire(event);
  }
  isTransient(editorCandidateOrIndex) {
    if (this.t.size === 0) {
      return false;
    }
    let editor;
    if (typeof editorCandidateOrIndex === "number") {
      editor = this.f[editorCandidateOrIndex];
    } else {
      editor = this.findEditor(editorCandidateOrIndex)?.[0];
    }
    return !!editor && this.t.has(editor);
  }
  S(index, del, editor) {
    const editorToDeleteOrReplace = this.f[index];
    if (del && this.isSticky(index)) {
      this.s--;
    }
    if (editor) {
      this.f.splice(index, del ? 1 : 0, editor);
    } else {
      this.f.splice(index, del ? 1 : 0);
    }
    {
      if (!del && editor) {
        if (this.g.length === 0) {
          this.g.push(editor);
        } else {
          this.g.splice(1, 0, editor);
        }
      } else {
        const indexInMRU = this.indexOf(editorToDeleteOrReplace, this.g);
        if (del && !editor) {
          this.g.splice(indexInMRU, 1);
        } else if (del && editor) {
          this.g.splice(indexInMRU, 1, editor);
        }
      }
    }
  }
  indexOf(candidate, editors = this.f, options3) {
    let index = -1;
    if (!candidate) {
      return index;
    }
    for (let i2 = 0; i2 < editors.length; i2++) {
      const editor = editors[i2];
      if (this.U(editor, candidate, options3)) {
        if (options3?.supportSideBySide && editor instanceof $1I && !(candidate instanceof $1I)) {
          index = i2;
        } else {
          index = i2;
          break;
        }
      }
    }
    return index;
  }
  findEditor(candidate, options3) {
    const index = this.indexOf(candidate, this.f, options3);
    if (index === -1) {
      return void 0;
    }
    return [this.f[index], index];
  }
  isFirst(candidate, editors = this.f) {
    return this.U(editors[0], candidate);
  }
  isLast(candidate, editors = this.f) {
    return this.U(editors[editors.length - 1], candidate);
  }
  contains(candidate, options3) {
    return this.indexOf(candidate, this.f, options3) !== -1;
  }
  U(editor, candidate, options3) {
    if (!editor || !candidate) {
      return false;
    }
    if (options3?.supportSideBySide && editor instanceof $1I && !(candidate instanceof $1I)) {
      switch (options3.supportSideBySide) {
        case SideBySideEditor.ANY:
          if (this.U(editor.primary, candidate, options3) || this.U(editor.secondary, candidate, options3)) {
            return true;
          }
          break;
        case SideBySideEditor.BOTH:
          if (this.U(editor.primary, candidate, options3) && this.U(editor.secondary, candidate, options3)) {
            return true;
          }
          break;
      }
    }
    const strictEquals = editor === candidate;
    if (options3?.strictEquals) {
      return strictEquals;
    }
    return strictEquals || editor.matches(candidate);
  }
  get isLocked() {
    return this.j;
  }
  lock(locked) {
    if (this.isLocked !== locked) {
      this.j = locked;
      this.b.fire({
        kind: 3
        /* GroupModelChangeKind.GROUP_LOCKED */
      });
    }
  }
  clone() {
    const clone2 = this.y.createInstance($9I_1, void 0);
    clone2.f = this.f.slice(0);
    clone2.g = this.g.slice(0);
    clone2.r = this.r;
    clone2.m = this.m.slice(0);
    clone2.s = this.s;
    for (const editor of clone2.f) {
      clone2.F(editor);
    }
    return clone2;
  }
  serialize() {
    const registry4 = $Wn.as($ZK.EditorFactory);
    const serializableEditors = [];
    const serializedEditors = [];
    let serializablePreviewIndex;
    let serializableSticky = this.s;
    for (let i2 = 0; i2 < this.f.length; i2++) {
      const editor = this.f[i2];
      let canSerializeEditor = false;
      const editorSerializer = registry4.getEditorSerializer(editor);
      if (editorSerializer) {
        const value = editorSerializer.canSerialize(editor) ? editorSerializer.serialize(editor) : void 0;
        if (typeof value === "string") {
          canSerializeEditor = true;
          serializedEditors.push({ id: editor.typeId, value });
          serializableEditors.push(editor);
          if (this.r === editor) {
            serializablePreviewIndex = serializableEditors.length - 1;
          }
        } else {
          canSerializeEditor = false;
        }
      }
      if (!canSerializeEditor && this.isSticky(i2)) {
        serializableSticky--;
      }
    }
    const serializableMru = this.g.map((editor) => this.indexOf(editor, serializableEditors)).filter((i2) => i2 >= 0);
    return {
      id: this.id,
      locked: this.j ? true : void 0,
      editors: serializedEditors,
      mru: serializableMru,
      preview: serializablePreviewIndex,
      sticky: serializableSticky >= 0 ? serializableSticky : void 0
    };
  }
  W(data) {
    const registry4 = $Wn.as($ZK.EditorFactory);
    if (typeof data.id === "number") {
      this.c = data.id;
      $9I_1.a = Math.max(data.id + 1, $9I_1.a);
    } else {
      this.c = $9I_1.a++;
    }
    if (data.locked) {
      this.j = true;
    }
    this.f = $Mb(data.editors.map((e, index) => {
      let editor = void 0;
      const editorSerializer = registry4.getEditorSerializer(e.id);
      if (editorSerializer) {
        const deserializedEditor = editorSerializer.deserialize(this.y, e.value);
        if (deserializedEditor instanceof $nG) {
          editor = deserializedEditor;
          this.F(editor);
        }
      }
      if (!editor && typeof data.sticky === "number" && index <= data.sticky) {
        data.sticky--;
      }
      return editor;
    }));
    this.g = $Mb(data.mru.map((i2) => this.f[i2]));
    this.m = this.g.length > 0 ? [this.g[0]] : [];
    if (typeof data.preview === "number") {
      this.r = this.f[data.preview];
    }
    if (typeof data.sticky === "number") {
      this.s = data.sticky;
    }
    return this.c;
  }
  dispose() {
    $Xc(Array.from(this.h));
    this.h.clear();
    this.t.clear();
    super.dispose();
  }
};
$9I = $9I_1 = __decorate([
  __param(1, $Pk),
  __param(2, $kl)
], $9I);

// out-build/vs/base/browser/ui/iconLabel/simpleIconLabel.js
var $U2 = class {
  constructor(b) {
    this.b = b;
  }
  set text(text2) {
    $dk(this.b, ...$B1(text2 ?? ""));
  }
  set title(title) {
    if (!this.a && title) {
      this.a = $J1().setupManagedHover($JZ("mouse"), this.b, title);
    } else if (this.a) {
      this.a.update(title);
    }
  }
  dispose() {
    this.a?.dispose();
  }
};

// out-build/vs/workbench/browser/parts/editor/editorPlaceholder.js
var $qyb_1;
var $ryb_1;
var $syb_1;
var $qyb = class $qyb2 extends $5tb {
  static {
    $qyb_1 = this;
  }
  static {
    this.a = 1024;
  }
  constructor(id2, group2, telemetryService, themeService, storageService) {
    super(id2, group2, telemetryService, themeService, storageService);
    this.f = this.B(new $4c());
  }
  Y(parent) {
    this.b = document.createElement("div");
    this.b.className = "monaco-editor-pane-placeholder";
    this.b.style.outline = "none";
    this.b.tabIndex = 0;
    this.c = this.B(new $CZ(this.b, {
      horizontal: 1,
      vertical: 1
      /* ScrollbarVisibility.Auto */
    }));
    parent.appendChild(this.c.getDomNode());
  }
  async setInput(input, options3, context, token) {
    await super.setInput(input, options3, context, token);
    if (token.isCancellationRequested) {
      return;
    }
    this.f.value = await this.j(input, options3);
  }
  async j(input, options3) {
    const [container2, scrollbar] = $Lg(this.b, this.c);
    $$i(container2);
    const disposables = new $2c();
    const { icon: icon2, label: label3, actions } = await this.m(input, options3, disposables);
    const truncatedLabel = $Cf(label3, $qyb_1.a);
    const iconContainer = container2.appendChild($(".editor-placeholder-icon-container"));
    const iconWidget = disposables.add(new $U2(iconContainer));
    iconWidget.text = icon2;
    const labelContainer = container2.appendChild($(".editor-placeholder-label-container"));
    const labelWidget = document.createElement("span");
    labelWidget.textContent = truncatedLabel;
    labelContainer.appendChild(labelWidget);
    container2.setAttribute("aria-label", `${$0tb(input, void 0, this.group, void 0)}, ${truncatedLabel}`);
    if (actions.length) {
      const actionsContainer = container2.appendChild($(".editor-placeholder-buttons-container"));
      const buttons = disposables.add(new $n2(actionsContainer));
      for (let i2 = 0; i2 < actions.length; i2++) {
        const button = disposables.add(buttons.addButton({
          ...$q$,
          secondary: i2 !== 0
        }));
        button.label = actions[i2].label;
        disposables.add(button.onDidClick((e) => {
          if (e) {
            $9j.stop(e, true);
          }
          actions[i2].run();
        }));
      }
    }
    scrollbar.scanDomNode();
    return disposables;
  }
  clearInput() {
    if (this.b) {
      $$i(this.b);
    }
    this.f.clear();
    super.clearInput();
  }
  layout(dimension) {
    const [container2, scrollbar] = $Lg(this.b, this.c);
    $tj(container2, dimension.width, dimension.height);
    scrollbar.scanDomNode();
    container2.classList.toggle("max-height-200px", dimension.height <= 200);
  }
  focus() {
    super.focus();
    this.b?.focus();
  }
  dispose() {
    this.b?.remove();
    super.dispose();
  }
};
$qyb = $qyb_1 = __decorate([
  __param(2, $zv),
  __param(3, $gs),
  __param(4, $jv)
], $qyb);
var $ryb = class $ryb2 extends $qyb {
  static {
    $ryb_1 = this;
  }
  static {
    this.ID = "workbench.editors.workspaceTrustRequiredEditor";
  }
  static {
    this.r = localize(3513, null);
  }
  static {
    this.DESCRIPTOR = $7tb.create($ryb_1, this.ID, this.r);
  }
  constructor(group2, telemetryService, themeService, s, u, storageService) {
    super($ryb_1.ID, group2, telemetryService, themeService, storageService);
    this.s = s;
    this.u = u;
  }
  getTitle() {
    return $ryb_1.r;
  }
  async m() {
    return {
      icon: "$(workspace-untrusted)",
      label: $1k($5k(this.u.getWorkspace())) ? localize(3514, null) : localize(3515, null),
      actions: [
        {
          label: localize(3516, null),
          run: () => this.s.executeCommand("workbench.trust.manage")
        }
      ]
    };
  }
};
$ryb = $ryb_1 = __decorate([
  __param(1, $zv),
  __param(2, $gs),
  __param(3, $sn),
  __param(4, $Zk),
  __param(5, $jv)
], $ryb);
var $syb = class $syb2 extends $qyb {
  static {
    $syb_1 = this;
  }
  static {
    this.r = "workbench.editors.errorEditor";
  }
  static {
    this.s = localize(3517, null);
  }
  static {
    this.DESCRIPTOR = $7tb.create($syb_1, this.r, this.s);
  }
  constructor(group2, telemetryService, themeService, storageService, u, cb) {
    super($syb_1.r, group2, telemetryService, themeService, storageService);
    this.u = u;
    this.cb = cb;
  }
  async m(input, options3, disposables) {
    const resource = input.resource;
    const error = options3.error;
    const isFileNotFound = error?.fileOperationResult === 1;
    let label3;
    if (isFileNotFound) {
      label3 = localize(3518, null);
    } else if ($pL(error) && error.forceMessage) {
      label3 = error.message;
    } else if (error) {
      label3 = localize(3519, null, $Df($1m(error), $qyb.a / 2));
    } else {
      label3 = localize(3520, null);
    }
    let icon2 = "$(error)";
    if ($pL(error)) {
      if (error.forceSeverity === severity_default.Info) {
        icon2 = "$(info)";
      } else if (error.forceSeverity === severity_default.Warning) {
        icon2 = "$(warning)";
      }
    }
    let actions = void 0;
    if ($pL(error) && error.actions.length > 0) {
      actions = error.actions.map((action) => {
        return {
          label: action.label,
          run: () => {
            const result = action.run();
            if (result instanceof Promise) {
              result.catch((error2) => this.cb.error($1m(error2)));
            }
          }
        };
      });
    } else {
      actions = [
        {
          label: localize(3521, null),
          run: () => this.group.openEditor(input, {
            ...options3,
            source: EditorOpenSource.USER
            /* explicit user gesture */
          })
        }
      ];
    }
    if (isFileNotFound && resource && this.u.hasProvider(resource)) {
      disposables.add(this.u.onDidFilesChange((e) => {
        if (e.contains(
          resource,
          1,
          0
          /* FileChangeType.UPDATED */
        )) {
          this.group.openEditor(input, options3);
        }
      }));
    }
    return { icon: icon2, label: label3, actions: actions ?? [] };
  }
};
$syb = $syb_1 = __decorate([
  __param(1, $zv),
  __param(2, $gs),
  __param(3, $jv),
  __param(4, $km),
  __param(5, $Yv)
], $syb);

// out-build/vs/workbench/browser/parts/editor/editorPanes.js
var $tyb = class $tyb2 extends $3c {
  //#endregion
  get minimumWidth() {
    return this.c?.minimumWidth ?? $Xob.width;
  }
  get minimumHeight() {
    return this.c?.minimumHeight ?? $Xob.height;
  }
  get maximumWidth() {
    return this.c?.maximumWidth ?? $Yob.width;
  }
  get maximumHeight() {
    return this.c?.maximumHeight ?? $Yob.height;
  }
  get activeEditorPane() {
    return this.c;
  }
  constructor(s, t, u, w, y, z, C, D, F, G) {
    super();
    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 = G;
    this.a = this.B(new $ze());
    this.onDidFocus = this.a.event;
    this.b = this.B(new $ze());
    this.onDidChangeSizeConstraints = this.b.event;
    this.c = null;
    this.f = [];
    this.g = /* @__PURE__ */ new Map();
    this.h = this.B(new $2c());
    this.n = this.B(new $YJ(this.z));
    this.r = $Wn.as($ZK.EditorPane);
    this.H();
  }
  H() {
    this.B(this.C.onDidChangeTrust(() => this.I()));
  }
  I() {
    const editor = this.c?.input;
    const options3 = this.c?.options;
    if (editor?.hasCapability(
      16
      /* EditorInputCapabilities.RequiresTrust */
    )) {
      this.u.openEditor(editor, options3);
    }
  }
  async openEditor(editor, options3, internalOptions, context = /* @__PURE__ */ Object.create(null)) {
    try {
      return await this.M(this.O(editor), editor, options3, internalOptions, context);
    } catch (error) {
      if (options3?.ignoreError) {
        return { error };
      }
      return this.J(error, editor, options3, internalOptions, context);
    }
  }
  async J(error, editor, options3, internalOptions, context) {
    this.D.error(error);
    let errorHandled = false;
    if (options3?.source === EditorOpenSource.USER && (!$pL(error) || error.allowDialog)) {
      errorHandled = await this.L(error, editor);
    }
    if (errorHandled) {
      return { error };
    }
    const editorPlaceholderOptions = { ...options3 };
    if (!$kb(error)) {
      editorPlaceholderOptions.error = error;
    }
    return {
      ...await this.M($syb.DESCRIPTOR, editor, editorPlaceholderOptions, internalOptions, context),
      error
    };
  }
  async L(error, editor) {
    let severity = severity_default.Error;
    let message = void 0;
    let detail2 = $1m(error);
    let errorActions = void 0;
    if ($pL(error)) {
      errorActions = error.actions;
      severity = error.forceSeverity ?? severity_default.Error;
      if (error.forceMessage) {
        message = error.message;
        detail2 = void 0;
      }
    }
    if (!message) {
      message = localize(3510, null, editor.getName());
    }
    const buttons = [];
    if (errorActions && errorActions.length > 0) {
      for (const errorAction of errorActions) {
        buttons.push({
          label: errorAction.label,
          run: () => errorAction
        });
      }
    } else {
      buttons.push({
        label: localize(3511, null),
        run: () => void 0
      });
    }
    let cancelButton = void 0;
    if (buttons.length === 1) {
      cancelButton = {
        run: () => {
          errorHandled = true;
          return void 0;
        }
      };
    }
    let errorHandled = false;
    const { result } = await this.F.prompt({
      type: severity,
      message,
      detail: detail2,
      buttons,
      cancelButton
    });
    if (result) {
      const errorActionResult = result.run();
      if (errorActionResult instanceof Promise) {
        errorActionResult.catch((error2) => this.F.error($1m(error2)));
      }
      errorHandled = true;
    }
    return errorHandled;
  }
  async M(descriptor, editor, options3, internalOptions, context = /* @__PURE__ */ Object.create(null)) {
    const pane = this.P(descriptor);
    const activeElement = $Lj();
    const { changed, cancelled } = await this.U(pane, editor, options3, context);
    if (!cancelled) {
      const focus = !options3 || !options3.preserveFocus;
      if (focus && this.N(activeElement)) {
        pane.focus();
      } else if (!internalOptions?.preserveWindowOrder) {
        this.G.moveTop(getWindowById(this.u.windowId, true).window);
      }
    }
    return { pane, changed, cancelled };
  }
  N(expectedActiveElement) {
    if (!this.w.isRestored()) {
      return true;
    }
    if (!expectedActiveElement) {
      return true;
    }
    const activeElement = $Lj();
    if (!activeElement || activeElement === expectedActiveElement.ownerDocument.body) {
      return true;
    }
    const same = expectedActiveElement === activeElement;
    if (same) {
      return true;
    }
    if (!$Fk(activeElement)) {
      return true;
    }
    if ($Dj(activeElement, this.s)) {
      return true;
    }
    return false;
  }
  O(editor) {
    if (editor.hasCapability(
      16
      /* EditorInputCapabilities.RequiresTrust */
    ) && !this.C.isWorkspaceTrusted()) {
      return $ryb.DESCRIPTOR;
    }
    return $Kg(this.r.getEditorPane(editor));
  }
  P(descriptor) {
    if (this.c && descriptor.describes(this.c)) {
      return this.c;
    }
    this.W();
    const editorPane = this.Q(descriptor);
    this.S(editorPane);
    const container2 = $Kg(editorPane.getContainer());
    this.t.appendChild(container2);
    $hk(container2);
    editorPane.setVisible(true);
    if (this.j) {
      editorPane.layout(new $rj(this.j.width, this.j.height), { top: this.j.top, left: this.j.left });
    }
    if (this.m) {
      editorPane.setBoundarySashes(this.m);
    }
    return editorPane;
  }
  Q(descriptor) {
    const editorPane = this.R(descriptor);
    if (!editorPane.getContainer()) {
      const editorPaneContainer = document.createElement("div");
      editorPaneContainer.classList.add("editor-instance");
      this.t.appendChild(editorPaneContainer);
      editorPane.create(editorPaneContainer);
    }
    return editorPane;
  }
  R(descriptor) {
    const existingEditorPane = this.f.find((editorPane2) => descriptor.describes(editorPane2));
    if (existingEditorPane) {
      return existingEditorPane;
    }
    const editorPane = this.B(descriptor.instantiate(this.y, this.u));
    this.f.push(editorPane);
    return editorPane;
  }
  S(editorPane) {
    this.c = editorPane;
    this.h.clear();
    if (editorPane) {
      this.h.add(editorPane.onDidChangeSizeConstraints((e) => this.b.fire(e)));
      this.h.add(editorPane.onDidFocus(() => this.a.fire()));
    }
    this.b.fire(void 0);
  }
  async U(editorPane, editor, options3, context) {
    let inputMatches = editorPane.input?.matches(editor);
    if (inputMatches && !options3?.forceReload) {
      if (this.g.has(editorPane)) {
        await this.g.get(editorPane);
      }
      inputMatches = editorPane.input?.matches(editor);
      if (inputMatches) {
        editorPane.setOptions(options3);
      }
      return { changed: false, cancelled: !inputMatches };
    }
    const operation = this.n.start(this.w.isRestored() ? 800 : 3200);
    let cancelled = false;
    try {
      editorPane.clearInput();
      const pendingSetInput = editorPane.setInput(editor, options3, context, operation.token);
      this.g.set(editorPane, pendingSetInput);
      await pendingSetInput;
      if (!operation.isCurrent()) {
        cancelled = true;
      }
    } catch (error) {
      if (!operation.isCurrent()) {
        cancelled = true;
      } else {
        throw error;
      }
    } finally {
      if (operation.isCurrent()) {
        this.g.delete(editorPane);
      }
      operation.stop();
    }
    return { changed: !inputMatches, cancelled };
  }
  W() {
    if (!this.c) {
      return;
    }
    this.n.stop();
    this.X(() => this.c?.clearInput());
    this.X(() => this.c?.setVisible(false));
    this.g.delete(this.c);
    const editorPaneContainer = this.c.getContainer();
    if (editorPaneContainer) {
      editorPaneContainer.remove();
      $ik(editorPaneContainer);
    }
    this.S(null);
  }
  closeEditor(editor) {
    if (this.c?.input && editor.matches(this.c.input)) {
      this.W();
    }
  }
  setVisible(visible) {
    this.X(() => this.c?.setVisible(visible));
  }
  layout(pagePosition) {
    this.j = pagePosition;
    this.X(() => this.c?.layout(new $rj(pagePosition.width, pagePosition.height), pagePosition));
  }
  setBoundarySashes(sashes) {
    this.m = sashes;
    this.X(() => this.c?.setBoundarySashes(sashes));
  }
  X(fn) {
    try {
      fn();
    } catch (error) {
      this.D.error(error);
    }
  }
};
$tyb = __decorate([
  __param(3, $Vlb),
  __param(4, $Pk),
  __param(5, $ZJ),
  __param(6, $4M),
  __param(7, $wn),
  __param(8, $Yv),
  __param(9, $S4)
], $tyb);

// out-build/vs/workbench/browser/parts/editor/editorGroupWatermark.js
var $uyb_1;
var showCommands = { text: localize(3496, null), id: "workbench.action.showCommands" };
var gotoFile = { text: localize(3497, null), id: "workbench.action.quickOpen" };
var openFile = { text: localize(3498, null), id: "workbench.action.files.openFile" };
var openFolder = { text: localize(3499, null), id: "workbench.action.files.openFolder" };
var openFileOrFolder = { text: localize(3500, null), id: "workbench.action.files.openFileFolder" };
var openRecent = { text: localize(3501, null), id: "workbench.action.openRecent" };
var newUntitledFile = { text: localize(3502, null), id: "workbench.action.files.newUntitledFile" };
var findInFiles = { text: localize(3503, null), id: "workbench.action.findInFiles" };
var toggleTerminal = { text: localize(3504, null), id: "workbench.action.terminal.toggleTerminal", when: { web: $7m.equals("terminalProcessSupported", true) } };
var startDebugging = { text: localize(3505, null), id: "workbench.action.debug.start", when: { web: $7m.equals("terminalProcessSupported", true) } };
var openSettings = { text: localize(3506, null), id: "workbench.action.openSettings" };
var openChat = { text: localize(3507, null), id: "workbench.action.chat.open", when: { native: $7m.equals("chatSetupInstalled", true), web: $7m.equals("chatSetupInstalled", true) } };
var openCopilotEdits = { text: localize(3508, null), id: "workbench.action.chat.openEditSession", when: { native: $7m.equals("chatSetupInstalled", true), web: $7m.equals("chatSetupInstalled", true) } };
var emptyWindowEntries = $Mb([
  showCommands,
  ...$m && !$r ? [openFileOrFolder] : [openFile, openFolder],
  openRecent,
  $m && !$r ? newUntitledFile : void 0,
  // fill in one more on macOS to get to 5 entries
  openChat
]);
var randomEmptyWindowEntries = [
  /* Nothing yet */
];
var workspaceEntries = [
  showCommands,
  gotoFile,
  openChat
];
var randomWorkspaceEntries = [
  findInFiles,
  startDebugging,
  toggleTerminal,
  openSettings,
  openCopilotEdits
];
var $uyb = class $uyb2 extends $3c {
  static {
    $uyb_1 = this;
  }
  static {
    this.a = "editorGroupWatermark.whenConditions";
  }
  constructor(container2, n, r2, s, t, u) {
    super();
    this.n = n;
    this.r = r2;
    this.s = s;
    this.t = t;
    this.u = u;
    this.b = this.u.getObject($uyb_1.a, 0, /* @__PURE__ */ Object.create(null));
    this.f = this.B(new $2c());
    this.g = this.B(new $2c());
    this.j = false;
    this.m = this.r.getWorkbenchState();
    const elements = h(".editor-group-watermark", [
      h(".letterpress"),
      h(".shortcuts@shortcuts")
    ]);
    $bk(container2, elements.root);
    this.c = elements.shortcuts;
    this.w();
    this.y();
  }
  w() {
    this.B(this.t.onDidChangeConfiguration((e) => {
      if (e.affectsConfiguration("workbench.tips.enabled") && this.j !== this.t.getValue("workbench.tips.enabled")) {
        this.y();
      }
    }));
    this.B(this.r.onDidChangeWorkbenchState((workbenchState) => {
      if (this.m !== workbenchState) {
        this.m = workbenchState;
        this.y();
      }
    }));
    this.B(this.u.onWillSaveState((e) => {
      if (e.reason === WillSaveStateReason.SHUTDOWN) {
        const entries2 = [...emptyWindowEntries, ...randomEmptyWindowEntries, ...workspaceEntries, ...randomWorkspaceEntries];
        for (const entry of entries2) {
          const when = $r ? entry.when?.web : entry.when?.native;
          if (when) {
            this.b[entry.id] = this.s.contextMatchesRules(when);
          }
        }
        this.u.store(
          $uyb_1.a,
          JSON.stringify(this.b),
          0,
          1
          /* StorageTarget.MACHINE */
        );
      }
    }));
  }
  y() {
    this.j = this.t.getValue("workbench.tips.enabled");
    $$i(this.c);
    this.f.clear();
    if (!this.j) {
      return;
    }
    const fixedEntries = this.z(
      this.m !== 1 ? workspaceEntries : emptyWindowEntries,
      false
      /* not shuffled */
    );
    const randomEntries = this.z(
      this.m !== 1 ? randomWorkspaceEntries : randomEmptyWindowEntries,
      true
      /* shuffled */
    ).slice(0, Math.max(0, 5 - fixedEntries.length));
    const entries2 = [...fixedEntries, ...randomEntries];
    const box = $bk(this.c, $(".watermark-box"));
    const update = () => {
      $$i(box);
      this.g.clear();
      for (const entry of entries2) {
        const keys = this.n.lookupKeybinding(entry.id);
        if (!keys) {
          continue;
        }
        const dl = $bk(box, $("dl"));
        const dt = $bk(dl, $("dt"));
        dt.textContent = entry.text;
        const dd = $bk(dl, $("dd"));
        const label3 = this.g.add(new $32(dd, OS, { renderUnboundKeybindings: true, ...$o$ }));
        label3.set(keys);
      }
    };
    update();
    this.f.add(this.n.onDidUpdateKeybindings(update));
  }
  z(entries2, shuffleEntries) {
    const filteredEntries = entries2.filter((entry) => $r && !entry.when?.web || !$r && !entry.when?.native || this.b[entry.id]).filter((entry) => !!$tn.getCommand(entry.id)).filter((entry) => !!this.n.lookupKeybinding(entry.id));
    if (shuffleEntries) {
      $Zb(filteredEntries);
    }
    return filteredEntries;
  }
};
$uyb = $uyb_1 = __decorate([
  __param(1, $Ty),
  __param(2, $Zk),
  __param(3, $on),
  __param(4, $kl),
  __param(5, $jv)
], $uyb);
$5n("editorWatermark.foreground", { dark: $0n($Lo, 0.6), light: $0n($Lo, 0.68), hcDark: $Lo, hcLight: $Lo }, localize(3509, null));

// out-build/vs/base/browser/ui/breadcrumbs/breadcrumbsWidget.js
var $a2 = class {
};
var $b2 = class {
  constructor(container2, horizontalScrollbarSize, separatorIcon2, styles) {
    this.c = new $2c();
    this.g = new $ze();
    this.h = new $ze();
    this.j = new $ze();
    this.onDidSelectItem = this.g.event;
    this.onDidFocusItem = this.h.event;
    this.onDidChangeFocus = this.j.event;
    this.k = new Array();
    this.l = new Array();
    this.m = new Array();
    this.o = true;
    this.p = -1;
    this.q = -1;
    this.d = document.createElement("div");
    this.d.className = "monaco-breadcrumbs";
    this.d.tabIndex = 0;
    this.d.setAttribute("role", "list");
    this.f = new $CZ(this.d, {
      vertical: 2,
      horizontal: 1,
      horizontalScrollbarSize,
      useShadows: false,
      scrollYToX: true
    });
    this.n = separatorIcon2;
    this.c.add(this.f);
    this.c.add($aj(this.d, "click", (e) => this.C(e)));
    container2.appendChild(this.f.getDomNode());
    const styleElement = $VZ(this.d);
    this.w(styleElement, styles);
    const focusTracker = $_j(this.d);
    this.c.add(focusTracker);
    this.c.add(focusTracker.onDidBlur((_) => this.j.fire(false)));
    this.c.add(focusTracker.onDidFocus((_) => this.j.fire(true)));
  }
  setHorizontalScrollbarSize(size) {
    this.f.updateOptions({
      horizontalScrollbarSize: size
    });
  }
  dispose() {
    this.c.dispose();
    this.s?.dispose();
    this.r?.dispose();
    this.g.dispose();
    this.h.dispose();
    this.j.dispose();
    this.d.remove();
    this.l.length = 0;
    this.m.length = 0;
  }
  layout(dim) {
    if (dim && $rj.equals(dim, this.t)) {
      return;
    }
    if (dim) {
      this.r?.dispose();
      this.r = this.u(dim);
    } else {
      this.s?.dispose();
      this.s = this.v();
    }
  }
  u(dim) {
    const disposables = new $2c();
    disposables.add($nj(getWindow(this.d), () => {
      this.t = dim;
      this.d.style.width = `${dim.width}px`;
      this.d.style.height = `${dim.height}px`;
      disposables.add(this.v());
    }));
    return disposables;
  }
  v() {
    return $mj(getWindow(this.d), () => {
      $mj(getWindow(this.d), () => {
        this.f.setRevealOnScroll(false);
        this.f.scanDomNode();
        this.f.setRevealOnScroll(true);
      });
    });
  }
  w(styleElement, style) {
    let content = "";
    if (style.breadcrumbsBackground) {
      content += `.monaco-breadcrumbs { background-color: ${style.breadcrumbsBackground}}`;
    }
    if (style.breadcrumbsForeground) {
      content += `.monaco-breadcrumbs .monaco-breadcrumb-item { color: ${style.breadcrumbsForeground}}
`;
    }
    if (style.breadcrumbsFocusForeground) {
      content += `.monaco-breadcrumbs .monaco-breadcrumb-item.focused { color: ${style.breadcrumbsFocusForeground}}
`;
    }
    if (style.breadcrumbsFocusAndSelectionForeground) {
      content += `.monaco-breadcrumbs .monaco-breadcrumb-item.focused.selected { color: ${style.breadcrumbsFocusAndSelectionForeground}}
`;
    }
    if (style.breadcrumbsHoverForeground) {
      content += `.monaco-breadcrumbs:not(.disabled	) .monaco-breadcrumb-item:hover:not(.focused):not(.selected) { color: ${style.breadcrumbsHoverForeground}}
`;
    }
    styleElement.innerText = content;
  }
  setEnabled(value) {
    this.o = value;
    this.d.classList.toggle("disabled", !this.o);
  }
  domFocus() {
    const idx = this.p >= 0 ? this.p : this.k.length - 1;
    if (idx >= 0 && idx < this.k.length) {
      this.x(idx, void 0);
    } else {
      this.d.focus();
    }
  }
  isDOMFocused() {
    return $Nj(this.d);
  }
  getFocused() {
    return this.k[this.p];
  }
  setFocused(item, payload) {
    this.x(this.k.indexOf(item), payload);
  }
  focusPrev(payload) {
    if (this.p > 0) {
      this.x(this.p - 1, payload);
    }
  }
  focusNext(payload) {
    if (this.p + 1 < this.l.length) {
      this.x(this.p + 1, payload);
    }
  }
  x(nth, payload) {
    this.p = -1;
    for (let i2 = 0; i2 < this.l.length; i2++) {
      const node = this.l[i2];
      if (i2 !== nth) {
        node.classList.remove("focused");
      } else {
        this.p = i2;
        node.classList.add("focused");
        node.focus();
      }
    }
    this.y(this.p, true);
    this.h.fire({ type: "focus", item: this.k[this.p], node: this.l[this.p], payload });
  }
  reveal(item) {
    const idx = this.k.indexOf(item);
    if (idx >= 0) {
      this.y(idx, false);
    }
  }
  revealLast() {
    this.y(this.k.length - 1, false);
  }
  y(nth, minimal) {
    if (nth < 0 || nth >= this.l.length) {
      return;
    }
    const node = this.l[nth];
    if (!node) {
      return;
    }
    const { width: width2 } = this.f.getScrollDimensions();
    const { scrollLeft } = this.f.getScrollPosition();
    if (!minimal || node.offsetLeft > scrollLeft + width2 || node.offsetLeft < scrollLeft) {
      this.f.setRevealOnScroll(false);
      this.f.setScrollPosition({ scrollLeft: node.offsetLeft });
      this.f.setRevealOnScroll(true);
    }
  }
  getSelection() {
    return this.k[this.q];
  }
  setSelection(item, payload) {
    this.z(this.k.indexOf(item), payload);
  }
  z(nth, payload) {
    this.q = -1;
    for (let i2 = 0; i2 < this.l.length; i2++) {
      const node = this.l[i2];
      if (i2 !== nth) {
        node.classList.remove("selected");
      } else {
        this.q = i2;
        node.classList.add("selected");
      }
    }
    this.g.fire({ type: "select", item: this.k[this.q], node: this.l[this.q], payload });
  }
  getItems() {
    return this.k;
  }
  setItems(items) {
    let prefix;
    let removed = [];
    try {
      prefix = $Tb(this.k, items, (a, b) => a.equals(b));
      removed = this.k.splice(prefix, this.k.length - prefix, ...items.slice(prefix));
      this.A(prefix);
      $Xc(removed);
      this.x(-1, void 0);
    } catch (e) {
      const newError = new Error(`BreadcrumbsItem#setItems: newItems: ${items.length}, prefix: ${prefix}, removed: ${removed.length}`);
      newError.name = e.name;
      newError.stack = e.stack;
      throw newError;
    }
  }
  A(start) {
    let didChange = false;
    for (; start < this.k.length && start < this.l.length; start++) {
      const item = this.k[start];
      const node = this.l[start];
      this.B(item, node);
      didChange = true;
    }
    while (start < this.l.length) {
      const free = this.l.pop();
      if (free) {
        this.m.push(free);
        free.remove();
        didChange = true;
      }
    }
    for (; start < this.k.length; start++) {
      const item = this.k[start];
      const node = this.m.length > 0 ? this.m.pop() : document.createElement("div");
      if (node) {
        this.B(item, node);
        this.d.appendChild(node);
        this.l.push(node);
        didChange = true;
      }
    }
    if (didChange) {
      this.layout(void 0);
    }
  }
  B(item, container2) {
    $$i(container2);
    container2.className = "";
    try {
      item.render(container2);
    } catch (err) {
      container2.innerText = "<<RENDER ERROR>>";
      console.error(err);
    }
    container2.tabIndex = -1;
    container2.setAttribute("role", "listitem");
    container2.classList.add("monaco-breadcrumb-item");
    const iconContainer = $(ThemeIcon.asCSSSelector(this.n));
    container2.appendChild(iconContainer);
  }
  C(event) {
    if (!this.o) {
      return;
    }
    for (let el = event.target; el; el = el.parentElement) {
      const idx = this.l.indexOf(el);
      if (idx >= 0) {
        this.x(idx, event);
        this.z(idx, event);
        break;
      }
    }
  }
};

// out-build/vs/workbench/browser/parts/editor/breadcrumbs.js
var $wyb = $Qk("IEditorBreadcrumbsService");
var $xyb = class {
  constructor() {
    this.a = /* @__PURE__ */ new Map();
  }
  register(group2, widget) {
    if (this.a.has(group2)) {
      throw new Error(`group (${group2}) has already a widget`);
    }
    this.a.set(group2, widget);
    return {
      dispose: () => this.a.delete(group2)
    };
  }
  getWidget(group2) {
    return this.a.get(group2);
  }
};
$SC(
  $wyb,
  $xyb,
  1
  /* InstantiationType.Delayed */
);
var $yyb = class _$yyb {
  constructor() {
  }
  static {
    this.IsEnabled = _$yyb.a("breadcrumbs.enabled");
  }
  static {
    this.UseQuickPick = _$yyb.a("breadcrumbs.useQuickPick");
  }
  static {
    this.FilePath = _$yyb.a("breadcrumbs.filePath");
  }
  static {
    this.SymbolPath = _$yyb.a("breadcrumbs.symbolPath");
  }
  static {
    this.SymbolSortOrder = _$yyb.a("breadcrumbs.symbolSortOrder");
  }
  static {
    this.Icons = _$yyb.a("breadcrumbs.icons");
  }
  static {
    this.TitleScrollbarSizing = _$yyb.a("workbench.editor.titleScrollbarSizing");
  }
  static {
    this.FileExcludes = _$yyb.a("files.exclude");
  }
  static a(name) {
    return {
      bindTo(service) {
        const onDidChange = new $ze();
        const listener = service.onDidChangeConfiguration((e) => {
          if (e.affectsConfiguration(name)) {
            onDidChange.fire(void 0);
          }
        });
        return new class {
          constructor() {
            this.name = name;
            this.onDidChange = onDidChange.event;
          }
          getValue(overrides) {
            if (overrides) {
              return service.getValue(name, overrides);
            } else {
              return service.getValue(name);
            }
          }
          updateValue(newValue, overrides) {
            if (overrides) {
              return service.updateValue(name, newValue, overrides);
            } else {
              return service.updateValue(name, newValue);
            }
          }
          dispose() {
            listener.dispose();
            onDidChange.dispose();
          }
        }();
      }
    };
  }
};
$Wn.as($Ht.Configuration).registerConfiguration({
  id: "breadcrumbs",
  title: localize(3110, null),
  order: 101,
  type: "object",
  properties: {
    "breadcrumbs.enabled": {
      description: localize(3111, null),
      type: "boolean",
      default: true
    },
    "breadcrumbs.filePath": {
      description: localize(3112, null),
      type: "string",
      default: "on",
      enum: ["on", "off", "last"],
      enumDescriptions: [
        localize(3113, null),
        localize(3114, null),
        localize(3115, null)
      ]
    },
    "breadcrumbs.symbolPath": {
      description: localize(3116, null),
      type: "string",
      default: "on",
      enum: ["on", "off", "last"],
      enumDescriptions: [
        localize(3117, null),
        localize(3118, null),
        localize(3119, null)
      ]
    },
    "breadcrumbs.symbolSortOrder": {
      description: localize(3120, null),
      type: "string",
      default: "position",
      scope: 5,
      enum: ["position", "name", "type"],
      enumDescriptions: [
        localize(3121, null),
        localize(3122, null),
        localize(3123, null)
      ]
    },
    "breadcrumbs.icons": {
      description: localize(3124, null),
      type: "boolean",
      default: true
    },
    "breadcrumbs.showFiles": {
      type: "boolean",
      default: true,
      scope: 5,
      markdownDescription: localize(3125, null)
    },
    "breadcrumbs.showModules": {
      type: "boolean",
      default: true,
      scope: 5,
      markdownDescription: localize(3126, null)
    },
    "breadcrumbs.showNamespaces": {
      type: "boolean",
      default: true,
      scope: 5,
      markdownDescription: localize(3127, null)
    },
    "breadcrumbs.showPackages": {
      type: "boolean",
      default: true,
      scope: 5,
      markdownDescription: localize(3128, null)
    },
    "breadcrumbs.showClasses": {
      type: "boolean",
      default: true,
      scope: 5,
      markdownDescription: localize(3129, null)
    },
    "breadcrumbs.showMethods": {
      type: "boolean",
      default: true,
      scope: 5,
      markdownDescription: localize(3130, null)
    },
    "breadcrumbs.showProperties": {
      type: "boolean",
      default: true,
      scope: 5,
      markdownDescription: localize(3131, null)
    },
    "breadcrumbs.showFields": {
      type: "boolean",
      default: true,
      scope: 5,
      markdownDescription: localize(3132, null)
    },
    "breadcrumbs.showConstructors": {
      type: "boolean",
      default: true,
      scope: 5,
      markdownDescription: localize(3133, null)
    },
    "breadcrumbs.showEnums": {
      type: "boolean",
      default: true,
      scope: 5,
      markdownDescription: localize(3134, null)
    },
    "breadcrumbs.showInterfaces": {
      type: "boolean",
      default: true,
      scope: 5,
      markdownDescription: localize(3135, null)
    },
    "breadcrumbs.showFunctions": {
      type: "boolean",
      default: true,
      scope: 5,
      markdownDescription: localize(3136, null)
    },
    "breadcrumbs.showVariables": {
      type: "boolean",
      default: true,
      scope: 5,
      markdownDescription: localize(3137, null)
    },
    "breadcrumbs.showConstants": {
      type: "boolean",
      default: true,
      scope: 5,
      markdownDescription: localize(3138, null)
    },
    "breadcrumbs.showStrings": {
      type: "boolean",
      default: true,
      scope: 5,
      markdownDescription: localize(3139, null)
    },
    "breadcrumbs.showNumbers": {
      type: "boolean",
      default: true,
      scope: 5,
      markdownDescription: localize(3140, null)
    },
    "breadcrumbs.showBooleans": {
      type: "boolean",
      default: true,
      scope: 5,
      markdownDescription: localize(3141, null)
    },
    "breadcrumbs.showArrays": {
      type: "boolean",
      default: true,
      scope: 5,
      markdownDescription: localize(3142, null)
    },
    "breadcrumbs.showObjects": {
      type: "boolean",
      default: true,
      scope: 5,
      markdownDescription: localize(3143, null)
    },
    "breadcrumbs.showKeys": {
      type: "boolean",
      default: true,
      scope: 5,
      markdownDescription: localize(3144, null)
    },
    "breadcrumbs.showNull": {
      type: "boolean",
      default: true,
      scope: 5,
      markdownDescription: localize(3145, null)
    },
    "breadcrumbs.showEnumMembers": {
      type: "boolean",
      default: true,
      scope: 5,
      markdownDescription: localize(3146, null)
    },
    "breadcrumbs.showStructs": {
      type: "boolean",
      default: true,
      scope: 5,
      markdownDescription: localize(3147, null)
    },
    "breadcrumbs.showEvents": {
      type: "boolean",
      default: true,
      scope: 5,
      markdownDescription: localize(3148, null)
    },
    "breadcrumbs.showOperators": {
      type: "boolean",
      default: true,
      scope: 5,
      markdownDescription: localize(3149, null)
    },
    "breadcrumbs.showTypeParameters": {
      type: "boolean",
      default: true,
      scope: 5,
      markdownDescription: localize(3150, null)
    }
  }
});

// out-build/vs/workbench/services/outline/browser/outline.js
var $vyb = $Qk("IOutlineService");
var OutlineTarget;
(function(OutlineTarget2) {
  OutlineTarget2[OutlineTarget2["OutlinePane"] = 1] = "OutlinePane";
  OutlineTarget2[OutlineTarget2["Breadcrumbs"] = 2] = "Breadcrumbs";
  OutlineTarget2[OutlineTarget2["QuickPick"] = 4] = "QuickPick";
})(OutlineTarget || (OutlineTarget = {}));
var OutlineConfigKeys;
(function(OutlineConfigKeys2) {
  OutlineConfigKeys2["icons"] = "outline.icons";
  OutlineConfigKeys2["collapseItems"] = "outline.collapseItems";
  OutlineConfigKeys2["problemsEnabled"] = "outline.problems.enabled";
  OutlineConfigKeys2["problemsColors"] = "outline.problems.colors";
  OutlineConfigKeys2["problemsBadges"] = "outline.problems.badges";
})(OutlineConfigKeys || (OutlineConfigKeys = {}));
var OutlineConfigCollapseItemsValues;
(function(OutlineConfigCollapseItemsValues2) {
  OutlineConfigCollapseItemsValues2["Collapsed"] = "alwaysCollapse";
  OutlineConfigCollapseItemsValues2["Expanded"] = "alwaysExpand";
})(OutlineConfigCollapseItemsValues || (OutlineConfigCollapseItemsValues = {}));

// out-build/vs/workbench/browser/parts/editor/breadcrumbsModel.js
var $zyb = class {
  constructor(uri, kind) {
    this.uri = uri;
    this.kind = kind;
  }
};
var $Ayb = class {
  constructor(element, outline) {
    this.element = element;
    this.outline = outline;
  }
};
var $Byb = class $Byb2 {
  constructor(resource, editor, configurationService, h3, j) {
    this.resource = resource;
    this.h = h3;
    this.j = j;
    this.a = new $2c();
    this.e = new $4c();
    this.f = new $2c();
    this.g = new $ze();
    this.onDidUpdate = this.g.event;
    this.c = $yyb.FilePath.bindTo(configurationService);
    this.d = $yyb.SymbolPath.bindTo(configurationService);
    this.a.add(this.c.onDidChange((_) => this.g.fire(this)));
    this.a.add(this.d.onDidChange((_) => this.g.fire(this)));
    this.h.onDidChangeWorkspaceFolders(this.l, this, this.a);
    this.b = this.k(resource);
    if (editor) {
      this.m(editor);
      this.a.add(j.onDidChange(() => this.m(editor)));
      this.a.add(editor.onDidChangeControl(() => this.m(editor)));
    }
    this.g.fire(this);
  }
  dispose() {
    this.a.dispose();
    this.c.dispose();
    this.d.dispose();
    this.e.dispose();
    this.f.dispose();
    this.g.dispose();
  }
  isRelative() {
    return Boolean(this.b.folder);
  }
  getElements() {
    let result = [];
    if (this.c.getValue() === "on") {
      result = result.concat(this.b.path);
    } else if (this.c.getValue() === "last" && this.b.path.length > 0) {
      result = result.concat(this.b.path.slice(-1));
    }
    if (this.d.getValue() === "off") {
      return result;
    }
    if (!this.e.value) {
      return result;
    }
    const breadcrumbsElements = this.e.value.config.breadcrumbsDataSource.getBreadcrumbElements();
    for (let i2 = this.d.getValue() === "last" && breadcrumbsElements.length > 0 ? breadcrumbsElements.length - 1 : 0; i2 < breadcrumbsElements.length; i2++) {
      result.push(new $Ayb(breadcrumbsElements[i2], this.e.value));
    }
    if (breadcrumbsElements.length === 0 && !this.e.value.isEmpty) {
      result.push(new $Ayb(this.e.value, this.e.value));
    }
    return result;
  }
  k(uri) {
    if ($$g(uri, Schemas.untitled, Schemas.data)) {
      return {
        folder: void 0,
        path: []
      };
    }
    const info = {
      folder: this.h.getWorkspaceFolder(uri) ?? void 0,
      path: []
    };
    let uriPrefix = uri;
    while (uriPrefix && uriPrefix.path !== "/") {
      if (info.folder && $oh(info.folder.uri, uriPrefix)) {
        break;
      }
      info.path.unshift(new $zyb(uriPrefix, info.path.length === 0 ? FileKind.FILE : FileKind.FOLDER));
      const prevPathLength = uriPrefix.path.length;
      uriPrefix = $uh(uriPrefix);
      if (uriPrefix.path.length === prevPathLength) {
        break;
      }
    }
    if (info.folder && this.h.getWorkbenchState() === 3) {
      info.path.unshift(new $zyb(info.folder.uri, FileKind.ROOT_FOLDER));
    }
    return info;
  }
  l() {
    this.b = this.k(this.resource);
    this.g.fire(this);
  }
  m(editor) {
    const newCts = new $ad();
    this.e.clear();
    this.f.clear();
    this.f.add($1c(() => newCts.dispose(true)));
    this.j.createOutline(editor, 2, newCts.token).then((outline) => {
      if (newCts.token.isCancellationRequested) {
        outline?.dispose();
        outline = void 0;
      }
      this.e.value = outline;
      this.g.fire(this);
      if (outline) {
        this.f.add(outline.onDidChange(() => this.g.fire(this)));
      }
    }).catch((err) => {
      this.g.fire(this);
      $gb(err);
    });
  }
};
$Byb = __decorate([
  __param(2, $kl),
  __param(3, $Zk),
  __param(4, $vyb)
], $Byb);

// out-build/vs/workbench/browser/parts/editor/breadcrumbsPicker.js
var $Cyb = class $Cyb2 {
  constructor(parent, m, n, o, p) {
    this.m = m;
    this.n = n;
    this.o = o;
    this.p = p;
    this.c = new $2c();
    this.i = new UIEvent("fakeEvent");
    this.k = new $ze();
    this.onWillPickElement = this.k.event;
    this.l = new $4c();
    this.d = document.createElement("div");
    this.d.className = "monaco-breadcrumbs-picker show-file-icons";
    parent.appendChild(this.d);
  }
  dispose() {
    this.c.dispose();
    this.l.dispose();
    this.k.dispose();
    this.d.remove();
    setTimeout(() => this.h.dispose(), 0);
  }
  async show(input, maxHeight, width2, arrowSize, arrowOffset) {
    const theme = this.o.getColorTheme();
    const color2 = theme.getColor($1p);
    this.f = document.createElement("div");
    this.f.className = "arrow";
    this.f.style.borderColor = `transparent transparent ${color2 ? color2.toString() : ""}`;
    this.d.appendChild(this.f);
    this.g = document.createElement("div");
    this.g.style.background = color2 ? color2.toString() : "";
    this.g.style.paddingTop = "2px";
    this.g.style.borderRadius = "3px";
    this.g.style.boxShadow = `0 0 8px 2px ${this.o.getColorTheme().getColor($Rp)}`;
    this.g.style.border = `1px solid ${this.o.getColorTheme().getColor($Sp)}`;
    this.d.appendChild(this.g);
    this.j = { maxHeight, width: width2, arrowSize, arrowOffset, inputHeight: 0 };
    this.h = this.s(this.g, input);
    this.c.add(this.h.onDidOpen(async (e) => {
      const { element, editorOptions: editorOptions2, sideBySide } = e;
      const didReveal = await this.u(element, { ...editorOptions2, preserveFocus: false }, sideBySide);
      if (!didReveal) {
        return;
      }
    }));
    this.c.add(this.h.onDidChangeFocus((e) => {
      this.l.value = this.t(e.elements[0]);
    }));
    this.c.add(this.h.onDidChangeContentHeight(() => {
      this.q();
    }));
    this.d.focus();
    try {
      await this.r(input);
      this.q();
    } catch (err) {
      $gb(err);
    }
  }
  q() {
    const headerHeight = 2 * this.j.arrowSize;
    const treeHeight = Math.min(this.j.maxHeight - headerHeight, this.h.contentHeight);
    const totalHeight = treeHeight + headerHeight;
    this.d.style.height = `${totalHeight}px`;
    this.d.style.width = `${this.j.width}px`;
    this.f.style.top = `-${2 * this.j.arrowSize}px`;
    this.f.style.borderWidth = `${this.j.arrowSize}px`;
    this.f.style.marginLeft = `${this.j.arrowOffset}px`;
    this.g.style.height = `${treeHeight}px`;
    this.g.style.width = `${this.j.width}px`;
    this.h.layout(treeHeight, this.j.width);
  }
  restoreViewState() {
  }
};
$Cyb = __decorate([
  __param(2, $Pk),
  __param(3, $gs),
  __param(4, $kl)
], $Cyb);
var FileVirtualDelegate = class {
  getHeight(_element) {
    return 22;
  }
  getTemplateId(_element) {
    return "FileStat";
  }
};
var FileIdentityProvider = class {
  getId(element) {
    if (URI.isUri(element)) {
      return element.toString();
    } else if ($8k(element)) {
      return element.id;
    } else if ($9k(element)) {
      return element.uri.toString();
    } else {
      return element.resource.toString();
    }
  }
};
var FileDataSource = class FileDataSource2 {
  constructor(c) {
    this.c = c;
  }
  hasChildren(element) {
    return URI.isUri(element) || $8k(element) || $9k(element) || element.isDirectory;
  }
  async getChildren(element) {
    if ($8k(element)) {
      return element.folders;
    }
    let uri;
    if ($9k(element)) {
      uri = element.uri;
    } else if (URI.isUri(element)) {
      uri = element;
    } else {
      uri = element.resource;
    }
    const stat = await this.c.resolve(uri);
    return stat.children ?? [];
  }
};
FileDataSource = __decorate([
  __param(0, $km)
], FileDataSource);
var FileRenderer = class FileRenderer2 {
  constructor(c, d) {
    this.c = c;
    this.d = d;
    this.templateId = "FileStat";
  }
  renderTemplate(container2) {
    return this.c.create(container2, { supportHighlights: true });
  }
  renderElement(node, index, templateData) {
    const fileDecorations = this.d.getValue("explorer.decorations");
    const { element } = node;
    let resource;
    let fileKind;
    if ($9k(element)) {
      resource = element.uri;
      fileKind = FileKind.ROOT_FOLDER;
    } else {
      resource = element.resource;
      fileKind = element.isDirectory ? FileKind.FOLDER : FileKind.FILE;
    }
    templateData.setFile(resource, {
      fileKind,
      hidePath: true,
      fileDecorations,
      matches: $Ul(node.filterData),
      extraClasses: ["picker-item"]
    });
  }
  disposeTemplate(templateData) {
    templateData.dispose();
  }
};
FileRenderer = __decorate([
  __param(1, $kl)
], FileRenderer);
var FileNavigationLabelProvider = class {
  getKeyboardNavigationLabel(element) {
    return element.name;
  }
};
var FileAccessibilityProvider = class {
  getWidgetAriaLabel() {
    return localize(3162, null);
  }
  getAriaLabel(element) {
    return element.name;
  }
};
var FileFilter = class FileFilter2 {
  constructor(f, configService) {
    this.f = f;
    this.c = /* @__PURE__ */ new Map();
    this.d = new $2c();
    const config = $yyb.FileExcludes.bindTo(configService);
    const update = () => {
      f.getWorkspace().folders.forEach((folder) => {
        const excludesConfig = config.getValue({ resource: folder.uri });
        if (!excludesConfig) {
          return;
        }
        const adjustedConfig = {};
        for (const pattern in excludesConfig) {
          if (typeof excludesConfig[pattern] !== "boolean") {
            continue;
          }
          const patternAbs = pattern.indexOf("**/") !== 0 ? $kc.join(folder.uri.path, pattern) : pattern;
          adjustedConfig[patternAbs] = excludesConfig[pattern];
        }
        this.c.set(folder.uri.toString(), $Dl(adjustedConfig));
      });
    };
    update();
    this.d.add(config);
    this.d.add(config.onDidChange(update));
    this.d.add(f.onDidChangeWorkspaceFolders(update));
  }
  dispose() {
    this.d.dispose();
  }
  filter(element, _parentVisibility) {
    if ($9k(element)) {
      return true;
    }
    const folder = this.f.getWorkspaceFolder(element.resource);
    if (!folder || !this.c.has(folder.uri.toString())) {
      return true;
    }
    const expression = this.c.get(folder.uri.toString());
    return !expression($pc(folder.uri.path, element.resource.path), $sh(element.resource));
  }
};
FileFilter = __decorate([
  __param(0, $Zk),
  __param(1, $kl)
], FileFilter);
var $Dyb = class {
  compare(a, b) {
    if ($9k(a) && $9k(b)) {
      return a.index - b.index;
    }
    if (a.isDirectory === b.isDirectory) {
      return $EM(a.name, b.name);
    } else if (a.isDirectory) {
      return -1;
    } else {
      return 1;
    }
  }
};
var $Eyb = class $Eyb2 extends $Cyb {
  constructor(parent, resource, instantiationService, themeService, configService, v, w) {
    super(parent, resource, instantiationService, themeService, configService);
    this.v = v;
    this.w = w;
  }
  s(container2) {
    this.g.classList.add("file-icon-themable-tree");
    this.g.classList.add("show-file-icons");
    const onFileIconThemeChange = (fileIconTheme) => {
      this.g.classList.toggle("align-icons-and-twisties", fileIconTheme.hasFileIcons && !fileIconTheme.hasFolderIcons);
      this.g.classList.toggle("hide-arrows", fileIconTheme.hidesExplorerArrows === true);
    };
    this.c.add(this.o.onDidFileIconThemeChange(onFileIconThemeChange));
    onFileIconThemeChange(this.o.getFileIconTheme());
    const labels2 = this.n.createInstance(
      $lsb,
      $ksb
      /* TODO@Jo visibility propagation */
    );
    this.c.add(labels2);
    return this.n.createInstance($4eb, "BreadcrumbsFilePicker", container2, new FileVirtualDelegate(), [this.n.createInstance(FileRenderer, labels2)], this.n.createInstance(FileDataSource), {
      multipleSelectionSupport: false,
      sorter: new $Dyb(),
      filter: this.n.createInstance(FileFilter),
      identityProvider: new FileIdentityProvider(),
      keyboardNavigationLabelProvider: new FileNavigationLabelProvider(),
      accessibilityProvider: this.n.createInstance(FileAccessibilityProvider),
      showNotFoundMessage: false,
      overrideStyles: {
        listBackground: $1p
      }
    });
  }
  async r(element) {
    const { uri, kind } = element;
    let input;
    if (kind === FileKind.ROOT_FOLDER) {
      input = this.v.getWorkspace();
    } else {
      input = $uh(uri);
    }
    const tree = this.h;
    await tree.setInput(input);
    let focusElement;
    for (const { element: element2 } of tree.getNode().children) {
      if ($9k(element2) && $oh(element2.uri, uri)) {
        focusElement = element2;
        break;
      } else if ($oh(element2.resource, uri)) {
        focusElement = element2;
        break;
      }
    }
    if (focusElement) {
      tree.reveal(focusElement, 0.5);
      tree.setFocus([focusElement], this.i);
    }
    tree.domFocus();
  }
  t(_element) {
    return $3c.None;
  }
  async u(element, options3, sideBySide) {
    if (!$9k(element) && element.isFile) {
      this.k.fire();
      await this.w.openEditor({ resource: element.resource, options: options3 }, sideBySide ? $oJ : void 0);
      return true;
    }
    return false;
  }
};
$Eyb = __decorate([
  __param(2, $Pk),
  __param(3, $gs),
  __param(4, $kl),
  __param(5, $Zk),
  __param(6, $mJ)
], $Eyb);
var OutlineTreeSorter = class OutlineTreeSorter2 {
  constructor(d, uri, configService) {
    this.d = d;
    this.c = configService.getValue(uri, "breadcrumbs.symbolSortOrder");
  }
  compare(a, b) {
    if (this.c === "name") {
      return this.d.compareByName(a, b);
    } else if (this.c === "type") {
      return this.d.compareByType(a, b);
    } else {
      return this.d.compareByPosition(a, b);
    }
  }
};
OutlineTreeSorter = __decorate([
  __param(2, $zG)
], OutlineTreeSorter);
var $Fyb = class extends $Cyb {
  s(container2, input) {
    const { config } = input.outline;
    return this.n.createInstance($3eb, "BreadcrumbsOutlinePicker", container2, config.delegate, config.renderers, config.treeDataSource, {
      ...config.options,
      sorter: this.n.createInstance(OutlineTreeSorter, config.comparator, void 0),
      collapseByDefault: true,
      expandOnlyOnTwistieClick: true,
      multipleSelectionSupport: false,
      showNotFoundMessage: false
    });
  }
  r(input) {
    const viewState = input.outline.captureViewState();
    this.restoreViewState = () => {
      viewState.dispose();
    };
    const tree = this.h;
    tree.setInput(input.outline);
    if (input.element !== input.outline) {
      tree.reveal(input.element, 0.5);
      tree.setFocus([input.element], this.i);
    }
    tree.domFocus();
    return Promise.resolve();
  }
  t(element) {
    const outline = this.h.getInput();
    return outline.preview(element);
  }
  async u(element, options3, sideBySide) {
    this.k.fire();
    const outline = this.h.getInput();
    await outline.reveal(element, options3, sideBySide, false);
    return true;
  }
};

// out-build/vs/workbench/browser/parts/editor/breadcrumbsControl.js
var OutlineItem_1;
var FileItem_1;
var $Gyb_1;
var OutlineItem = OutlineItem_1 = class OutlineItem2 extends $a2 {
  constructor(model, element, options3, d) {
    super();
    this.model = model;
    this.element = element;
    this.options = options3;
    this.d = d;
    this.c = new $2c();
  }
  dispose() {
    this.c.dispose();
  }
  equals(other) {
    if (!(other instanceof OutlineItem_1)) {
      return false;
    }
    return this.element.element === other.element.element && this.options.showFileIcons === other.options.showFileIcons && this.options.showSymbolIcons === other.options.showSymbolIcons;
  }
  render(container2) {
    const { element, outline } = this.element;
    if (element === outline) {
      const element2 = $("span", void 0, "\u2026");
      container2.appendChild(element2);
      return;
    }
    const templateId = outline.config.delegate.getTemplateId(element);
    const renderer = outline.config.renderers.find((renderer2) => renderer2.templateId === templateId);
    if (!renderer) {
      container2.innerText = "<<NO RENDERER>>";
      return;
    }
    const template = renderer.renderTemplate(container2);
    renderer.renderElement({
      element,
      children: [],
      depth: 0,
      visibleChildrenCount: 0,
      visibleChildIndex: 0,
      collapsible: false,
      collapsed: false,
      visible: true,
      filterData: void 0
    }, 0, template, void 0);
    this.c.add($1c(() => {
      renderer.disposeTemplate(template);
    }));
    if (element instanceof $mhb && outline.uri) {
      this.c.add(this.d.invokeFunction((accessor) => createBreadcrumbDndObserver(accessor, container2, element.symbol.name, { symbol: element.symbol, uri: outline.uri })));
    }
  }
};
OutlineItem = OutlineItem_1 = __decorate([
  __param(3, $Pk)
], OutlineItem);
var FileItem = FileItem_1 = class FileItem2 extends $a2 {
  constructor(model, element, options3, d, f, g) {
    super();
    this.model = model;
    this.element = element;
    this.options = options3;
    this.d = d;
    this.f = f;
    this.g = g;
    this.c = new $2c();
  }
  dispose() {
    this.c.dispose();
  }
  equals(other) {
    if (!(other instanceof FileItem_1)) {
      return false;
    }
    return $lh.isEqual(this.element.uri, other.element.uri) && this.options.showFileIcons === other.options.showFileIcons && this.options.showSymbolIcons === other.options.showSymbolIcons;
  }
  render(container2) {
    const label3 = this.d.create(container2, { hoverDelegate: this.f });
    label3.setFile(this.element.uri, {
      hidePath: true,
      hideIcon: this.element.kind === FileKind.FOLDER || !this.options.showFileIcons,
      fileKind: this.element.kind,
      fileDecorations: { colors: this.options.showDecorationColors, badges: false }
    });
    container2.classList.add(FileKind[this.element.kind].toLowerCase());
    this.c.add(label3);
    this.c.add(this.g.invokeFunction((accessor) => createBreadcrumbDndObserver(accessor, container2, $sh(this.element.uri), this.element.uri)));
  }
};
FileItem = FileItem_1 = __decorate([
  __param(5, $Pk)
], FileItem);
function createBreadcrumbDndObserver(accessor, container2, label3, item) {
  const instantiationService = accessor.get($Pk);
  container2.draggable = true;
  return new $Ak(container2, {
    onDragStart: (event) => {
      if (!event.dataTransfer) {
        return;
      }
      event.dataTransfer.effectAllowed = "copyMove";
      instantiationService.invokeFunction((accessor2) => {
        if (URI.isUri(item)) {
          $Eob(accessor2, [item], event);
        } else {
          $Eob(accessor2, [{ resource: item.uri, selection: item.symbol.range }], event);
          $D_([{
            name: item.symbol.name,
            fsPath: item.uri.fsPath,
            range: item.symbol.range,
            kind: item.symbol.kind
          }], event);
        }
      });
      const dragImage = $(".monaco-drag-image");
      dragImage.textContent = label3;
      const getDragImageContainer = (e) => {
        while (e && !e.classList.contains("monaco-workbench")) {
          e = e.parentElement;
        }
        return e || container2.ownerDocument;
      };
      const dragContainer = getDragImageContainer(container2);
      dragContainer.appendChild(dragImage);
      event.dataTransfer.setDragImage(dragImage, -10, -10);
      setTimeout(() => dragImage.remove(), 0);
    }
  });
}
var separatorIcon = $9r("breadcrumb-separator", $6l.chevronRight, localize(3151, null));
var $Gyb = class $Gyb2 {
  static {
    $Gyb_1 = this;
  }
  static {
    this.HEIGHT = 22;
  }
  static {
    this.a = {
      default: 3,
      large: 8
    };
  }
  static {
    this.Payload_Reveal = {};
  }
  static {
    this.Payload_RevealAside = {};
  }
  static {
    this.Payload_Pick = {};
  }
  static {
    this.CK_BreadcrumbsPossible = new $nn("breadcrumbsPossible", false, localize(3152, null));
  }
  static {
    this.CK_BreadcrumbsVisible = new $nn("breadcrumbsVisible", false, localize(3153, null));
  }
  static {
    this.CK_BreadcrumbsActive = new $nn("breadcrumbsActive", false, localize(3154, null));
  }
  get onDidVisibilityChange() {
    return this.q.event;
  }
  constructor(container2, r2, s, t, u, v, w, z, A, B, configurationService, breadcrumbsService) {
    this.r = r2;
    this.s = s;
    this.t = t;
    this.u = u;
    this.v = v;
    this.w = w;
    this.z = z;
    this.A = A;
    this.B = B;
    this.j = new $2c();
    this.k = new $2c();
    this.m = new $4c();
    this.n = false;
    this.q = this.j.add(new $ze());
    this.domNode = document.createElement("div");
    this.domNode.classList.add("breadcrumbs-control");
    $bk(container2, this.domNode);
    this.f = $yyb.UseQuickPick.bindTo(configurationService);
    this.g = $yyb.Icons.bindTo(configurationService);
    this.h = $yyb.TitleScrollbarSizing.bindTo(configurationService);
    this.l = this.v.createInstance($lsb, $ksb);
    const sizing = this.h.getValue() ?? "default";
    const styles = r2.widgetStyles ?? $G$;
    this.i = new $b2(this.domNode, $Gyb_1.a[sizing], separatorIcon, styles);
    this.i.onDidSelectItem(this.E, this, this.j);
    this.i.onDidFocusItem(this.D, this, this.j);
    this.i.onDidChangeFocus(this.F, this, this.j);
    this.b = $Gyb_1.CK_BreadcrumbsPossible.bindTo(this.t);
    this.c = $Gyb_1.CK_BreadcrumbsVisible.bindTo(this.t);
    this.d = $Gyb_1.CK_BreadcrumbsActive.bindTo(this.t);
    this.p = $JZ("mouse");
    this.j.add(breadcrumbsService.register(this.s.id, this.i));
    this.hide();
  }
  dispose() {
    this.j.dispose();
    this.k.dispose();
    this.b.reset();
    this.c.reset();
    this.d.reset();
    this.f.dispose();
    this.g.dispose();
    this.i.dispose();
    this.l.dispose();
    this.domNode.remove();
  }
  get model() {
    return this.m.value;
  }
  layout(dim) {
    this.i.layout(dim);
  }
  isHidden() {
    return this.domNode.classList.contains("hidden");
  }
  hide() {
    const wasHidden = this.isHidden();
    this.k.clear();
    this.c.set(false);
    this.domNode.classList.toggle("hidden", true);
    if (!wasHidden) {
      this.q.fire();
    }
  }
  C() {
    const wasHidden = this.isHidden();
    this.c.set(true);
    this.domNode.classList.toggle("hidden", false);
    if (wasHidden) {
      this.q.fire();
    }
  }
  revealLast() {
    this.i.revealLast();
  }
  update() {
    this.k.clear();
    const uri = $mL.getCanonicalUri(this.s.activeEditor, { supportSideBySide: SideBySideEditor.PRIMARY });
    const wasHidden = this.isHidden();
    if (!uri || !this.z.hasProvider(uri)) {
      this.b.set(false);
      if (!wasHidden) {
        this.hide();
        return true;
      } else {
        return false;
      }
    }
    const fileInfoUri = $mL.getOriginalUri(this.s.activeEditor, { supportSideBySide: SideBySideEditor.PRIMARY });
    this.C();
    this.b.set(true);
    const model = this.v.createInstance($Byb, fileInfoUri ?? uri, this.s.activeEditorPane);
    this.m.value = model;
    this.domNode.classList.toggle("backslash-path", this.B.getSeparator(uri.scheme, uri.authority) === "\\");
    const updateBreadcrumbs = () => {
      this.domNode.classList.toggle("relative-path", model.isRelative());
      const showIcons = this.g.getValue();
      const options3 = {
        ...this.r,
        showFileIcons: this.r.showFileIcons && showIcons,
        showSymbolIcons: this.r.showSymbolIcons && showIcons
      };
      const items = model.getElements().map((element) => element instanceof $zyb ? this.v.createInstance(FileItem, model, element, options3, this.l, this.p) : this.v.createInstance(OutlineItem, model, element, options3));
      if (items.length === 0) {
        this.i.setEnabled(false);
        this.i.setItems([new class extends $a2 {
          render(container2) {
            container2.innerText = localize(3155, null);
          }
          equals(other) {
            return other === this;
          }
          dispose() {
          }
        }()]);
      } else {
        this.i.setEnabled(true);
        this.i.setItems(items);
        this.i.reveal(items[items.length - 1]);
      }
    };
    const listener = model.onDidUpdate(updateBreadcrumbs);
    const configListener = this.g.onDidChange(updateBreadcrumbs);
    updateBreadcrumbs();
    this.k.clear();
    this.k.add(listener);
    this.k.add($1c(() => this.m.clear()));
    this.k.add(configListener);
    this.k.add($1c(() => this.i.setItems([])));
    const updateScrollbarSizing = () => {
      const sizing = this.h.getValue() ?? "default";
      this.i.setHorizontalScrollbarSize($Gyb_1.a[sizing]);
    };
    updateScrollbarSizing();
    const updateScrollbarSizeListener = this.h.onDidChange(updateScrollbarSizing);
    this.k.add(updateScrollbarSizeListener);
    this.k.add({
      dispose: () => {
        if (this.n) {
          this.u.hideContextView({ source: this });
        }
      }
    });
    return wasHidden !== this.isHidden();
  }
  D(event) {
    if (event.item && this.n) {
      this.o = void 0;
      this.i.setSelection(event.item);
    }
  }
  E(event) {
    if (!event.item) {
      return;
    }
    if (event.item === this.o) {
      this.o = void 0;
      this.i.setFocused(void 0);
      this.i.setSelection(void 0);
      return;
    }
    const { element } = event.item;
    this.s.focus();
    const group2 = this.H(event.payload);
    if (group2 !== void 0) {
      this.i.setFocused(void 0);
      this.i.setSelection(void 0);
      this.G(event, element, group2);
      return;
    }
    if (this.f.getValue()) {
      this.i.setFocused(void 0);
      this.i.setSelection(void 0);
      this.w.quickAccess.show(element instanceof $Ayb ? "@" : "");
      return;
    }
    let picker;
    let pickerAnchor;
    this.u.showContextView({
      render: (parent) => {
        if (event.item instanceof FileItem) {
          picker = this.v.createInstance($Eyb, parent, event.item.model.resource);
        } else if (event.item instanceof OutlineItem) {
          picker = this.v.createInstance($Fyb, parent, event.item.model.resource);
        }
        const selectListener = picker.onWillPickElement(() => this.u.hideContextView({ source: this, didPick: true }));
        const zoomListener = $_1.getInstance(getWindow(this.domNode)).onDidChange(() => this.u.hideContextView({ source: this }));
        const focusTracker = $_j(parent);
        const blurListener = focusTracker.onDidBlur(() => {
          this.o = this.i.isDOMFocused() ? event.item : void 0;
          this.u.hideContextView({ source: this });
        });
        this.n = true;
        this.F();
        return $Zc(picker, selectListener, zoomListener, focusTracker, blurListener);
      },
      getAnchor: () => {
        if (!pickerAnchor) {
          const window3 = getWindow(this.domNode);
          const maxInnerWidth = window3.innerWidth - 8;
          let maxHeight = Math.min(window3.innerHeight * 0.7, 300);
          const pickerWidth = Math.min(maxInnerWidth, Math.max(240, maxInnerWidth / 4.17));
          const pickerArrowSize = 8;
          let pickerArrowOffset;
          const data = $vj(event.node.firstChild);
          const y = data.top + data.height + pickerArrowSize;
          if (y + maxHeight >= window3.innerHeight) {
            maxHeight = window3.innerHeight - y - 30;
          }
          let x = data.left;
          if (x + pickerWidth >= maxInnerWidth) {
            x = maxInnerWidth - pickerWidth;
          }
          if (event.payload instanceof $lf) {
            const maxPickerArrowOffset = pickerWidth - 2 * pickerArrowSize;
            pickerArrowOffset = event.payload.posx - x;
            if (pickerArrowOffset > maxPickerArrowOffset) {
              x = Math.min(maxInnerWidth - pickerWidth, x + pickerArrowOffset - maxPickerArrowOffset);
              pickerArrowOffset = maxPickerArrowOffset;
            }
          } else {
            pickerArrowOffset = data.left + data.width * 0.3 - x;
          }
          picker.show(element, maxHeight, pickerWidth, pickerArrowSize, Math.max(0, pickerArrowOffset));
          pickerAnchor = { x, y };
        }
        return pickerAnchor;
      },
      onHide: (data) => {
        if (!data?.didPick) {
          picker.restoreViewState();
        }
        this.n = false;
        this.F();
        if (data?.source === this) {
          this.i.setFocused(void 0);
          this.i.setSelection(void 0);
        }
        picker.dispose();
      }
    });
  }
  F() {
    const value = this.i.isDOMFocused() || this.n;
    this.d.set(value);
  }
  async G(event, element, group2, pinned = false) {
    if (element instanceof $zyb) {
      if (element.kind === FileKind.FILE) {
        await this.A.openEditor({ resource: element.uri, options: { pinned } }, group2);
      } else {
        const items = this.i.getItems();
        const idx = items.indexOf(event.item);
        this.i.setFocused(items[idx + 1]);
        this.i.setSelection(items[idx + 1], $Gyb_1.Payload_Pick);
      }
    } else {
      element.outline.reveal(element, { pinned }, group2 === $oJ, false);
    }
  }
  H(data) {
    if (data === $Gyb_1.Payload_RevealAside) {
      return $oJ;
    } else if (data === $Gyb_1.Payload_Reveal) {
      return $nJ;
    } else {
      return void 0;
    }
  }
};
$Gyb = $Gyb_1 = __decorate([
  __param(3, $on),
  __param(4, $40),
  __param(5, $Pk),
  __param(6, $1M),
  __param(7, $km),
  __param(8, $mJ),
  __param(9, $ZI),
  __param(10, $kl),
  __param(11, $wyb)
], $Gyb);
var $Hyb = class $Hyb2 {
  get control() {
    return this.c;
  }
  get onDidEnablementChange() {
    return this.d.event;
  }
  get onDidVisibilityChange() {
    return this.f.event;
  }
  constructor(g, h3, i2, configurationService, j, fileService) {
    this.g = g;
    this.h = h3;
    this.i = i2;
    this.j = j;
    this.a = new $2c();
    this.b = new $2c();
    this.d = this.a.add(new $ze());
    this.f = this.a.add(new $ze());
    const config = this.a.add($yyb.IsEnabled.bindTo(configurationService));
    this.a.add(config.onDidChange(() => {
      const value = config.getValue();
      if (!value && this.c) {
        this.b.clear();
        this.c = void 0;
        this.d.fire();
      } else if (value && !this.c) {
        this.c = this.k();
        this.c.update();
        this.d.fire();
      }
    }));
    if (config.getValue()) {
      this.c = this.k();
    }
    this.a.add(fileService.onDidChangeFileSystemProviderRegistrations((e) => {
      if (this.c?.model && this.c.model.resource.scheme !== e.scheme) {
        return;
      }
      if (this.c?.update()) {
        this.d.fire();
      }
    }));
  }
  k() {
    const control = this.b.add(this.j.createInstance($Gyb, this.g, this.i, this.h));
    this.b.add(control.onDidVisibilityChange(() => this.f.fire()));
    return control;
  }
  dispose() {
    this.a.dispose();
    this.b.dispose();
  }
};
$Hyb = __decorate([
  __param(3, $kl),
  __param(4, $Pk),
  __param(5, $km)
], $Hyb);
$hJ(class ToggleBreadcrumb extends $gJ {
  constructor() {
    super({
      id: "breadcrumbs.toggle",
      title: {
        ...localize2(3159, "Toggle Breadcrumbs"),
        mnemonicTitle: localize(3156, null)
      },
      category: $qn.View,
      toggled: {
        condition: $7m.equals("config.breadcrumbs.enabled", true),
        title: localize(3157, null),
        mnemonicTitle: localize(3158, null)
      },
      menu: [
        { id: $bJ.CommandPalette },
        { id: $bJ.MenubarAppearanceMenu, group: "4_editor", order: 2 },
        { id: $bJ.NotebookToolbar, group: "notebookLayout", order: 2 },
        { id: $bJ.StickyScrollContext },
        { id: $bJ.NotebookStickyScrollContext, group: "notebookView", order: 2 }
      ]
    });
  }
  run(accessor) {
    const config = accessor.get($kl);
    const value = $yyb.IsEnabled.bindTo(config).getValue();
    $yyb.IsEnabled.bindTo(config).updateValue(!value);
  }
});
function focusAndSelectHandler(accessor, select) {
  const groups = accessor.get($iJ);
  const breadcrumbs = accessor.get($wyb);
  const widget = breadcrumbs.getWidget(groups.activeGroup.id);
  if (widget) {
    const item = widget.getItems().at(-1);
    widget.setFocused(item);
    if (select) {
      widget.setSelection(item, $Gyb.Payload_Pick);
    }
  }
}
$hJ(class FocusAndSelectBreadcrumbs extends $gJ {
  constructor() {
    super({
      id: "breadcrumbs.focusAndSelect",
      title: localize2(3160, "Focus and Select Breadcrumbs"),
      precondition: $Gyb.CK_BreadcrumbsVisible,
      keybinding: {
        weight: 200,
        primary: 2048 | 1024 | 89,
        when: $Gyb.CK_BreadcrumbsPossible
      },
      f1: true
    });
  }
  run(accessor, ...args2) {
    focusAndSelectHandler(accessor, true);
  }
});
$hJ(class FocusBreadcrumbs extends $gJ {
  constructor() {
    super({
      id: "breadcrumbs.focus",
      title: localize2(3161, "Focus Breadcrumbs"),
      precondition: $Gyb.CK_BreadcrumbsVisible,
      keybinding: {
        weight: 200,
        primary: 2048 | 1024 | 85,
        when: $Gyb.CK_BreadcrumbsPossible
      },
      f1: true
    });
  }
  run(accessor, ...args2) {
    focusAndSelectHandler(accessor, false);
  }
});
$0I.registerCommandAndKeybindingRule({
  id: "breadcrumbs.toggleToOn",
  weight: 200,
  primary: 2048 | 1024 | 89,
  when: $7m.not("config.breadcrumbs.enabled"),
  handler: async (accessor) => {
    const instant = accessor.get($Pk);
    const config = accessor.get($kl);
    const isEnabled = $yyb.IsEnabled.bindTo(config);
    if (!isEnabled.getValue()) {
      await isEnabled.updateValue(true);
      await $Wh(50);
    }
    return instant.invokeFunction(focusAndSelectHandler, true);
  }
});
$0I.registerCommandAndKeybindingRule({
  id: "breadcrumbs.focusNext",
  weight: 200,
  primary: 17,
  secondary: [
    2048 | 17
    /* KeyCode.RightArrow */
  ],
  mac: {
    primary: 17,
    secondary: [
      512 | 17
      /* KeyCode.RightArrow */
    ]
  },
  when: $7m.and($Gyb.CK_BreadcrumbsVisible, $Gyb.CK_BreadcrumbsActive),
  handler(accessor) {
    const groups = accessor.get($iJ);
    const breadcrumbs = accessor.get($wyb);
    const widget = breadcrumbs.getWidget(groups.activeGroup.id);
    if (!widget) {
      return;
    }
    widget.focusNext();
  }
});
$0I.registerCommandAndKeybindingRule({
  id: "breadcrumbs.focusPrevious",
  weight: 200,
  primary: 15,
  secondary: [
    2048 | 15
    /* KeyCode.LeftArrow */
  ],
  mac: {
    primary: 15,
    secondary: [
      512 | 15
      /* KeyCode.LeftArrow */
    ]
  },
  when: $7m.and($Gyb.CK_BreadcrumbsVisible, $Gyb.CK_BreadcrumbsActive),
  handler(accessor) {
    const groups = accessor.get($iJ);
    const breadcrumbs = accessor.get($wyb);
    const widget = breadcrumbs.getWidget(groups.activeGroup.id);
    if (!widget) {
      return;
    }
    widget.focusPrev();
  }
});
$0I.registerCommandAndKeybindingRule({
  id: "breadcrumbs.focusNextWithPicker",
  weight: 200 + 1,
  primary: 2048 | 17,
  mac: {
    primary: 512 | 17
  },
  when: $7m.and($Gyb.CK_BreadcrumbsVisible, $Gyb.CK_BreadcrumbsActive, $Leb),
  handler(accessor) {
    const groups = accessor.get($iJ);
    const breadcrumbs = accessor.get($wyb);
    const widget = breadcrumbs.getWidget(groups.activeGroup.id);
    if (!widget) {
      return;
    }
    widget.focusNext();
  }
});
$0I.registerCommandAndKeybindingRule({
  id: "breadcrumbs.focusPreviousWithPicker",
  weight: 200 + 1,
  primary: 2048 | 15,
  mac: {
    primary: 512 | 15
  },
  when: $7m.and($Gyb.CK_BreadcrumbsVisible, $Gyb.CK_BreadcrumbsActive, $Leb),
  handler(accessor) {
    const groups = accessor.get($iJ);
    const breadcrumbs = accessor.get($wyb);
    const widget = breadcrumbs.getWidget(groups.activeGroup.id);
    if (!widget) {
      return;
    }
    widget.focusPrev();
  }
});
$0I.registerCommandAndKeybindingRule({
  id: "breadcrumbs.selectFocused",
  weight: 200,
  primary: 3,
  secondary: [
    18
    /* KeyCode.DownArrow */
  ],
  when: $7m.and($Gyb.CK_BreadcrumbsVisible, $Gyb.CK_BreadcrumbsActive),
  handler(accessor) {
    const groups = accessor.get($iJ);
    const breadcrumbs = accessor.get($wyb);
    const widget = breadcrumbs.getWidget(groups.activeGroup.id);
    if (!widget) {
      return;
    }
    widget.setSelection(widget.getFocused(), $Gyb.Payload_Pick);
  }
});
$0I.registerCommandAndKeybindingRule({
  id: "breadcrumbs.revealFocused",
  weight: 200,
  primary: 10,
  secondary: [
    2048 | 3
    /* KeyCode.Enter */
  ],
  when: $7m.and($Gyb.CK_BreadcrumbsVisible, $Gyb.CK_BreadcrumbsActive),
  handler(accessor) {
    const groups = accessor.get($iJ);
    const breadcrumbs = accessor.get($wyb);
    const widget = breadcrumbs.getWidget(groups.activeGroup.id);
    if (!widget) {
      return;
    }
    widget.setSelection(widget.getFocused(), $Gyb.Payload_Reveal);
  }
});
$0I.registerCommandAndKeybindingRule({
  id: "breadcrumbs.selectEditor",
  weight: 200 + 1,
  primary: 9,
  when: $7m.and($Gyb.CK_BreadcrumbsVisible, $Gyb.CK_BreadcrumbsActive),
  handler(accessor) {
    const groups = accessor.get($iJ);
    const breadcrumbs = accessor.get($wyb);
    const widget = breadcrumbs.getWidget(groups.activeGroup.id);
    if (!widget) {
      return;
    }
    widget.setFocused(void 0);
    widget.setSelection(void 0);
    groups.activeGroup.activeEditorPane?.focus();
  }
});
$0I.registerCommandAndKeybindingRule({
  id: "breadcrumbs.revealFocusedFromTreeAside",
  weight: 200,
  primary: 2048 | 3,
  when: $7m.and($Gyb.CK_BreadcrumbsVisible, $Gyb.CK_BreadcrumbsActive, $Leb),
  handler(accessor) {
    const editors = accessor.get($mJ);
    const lists = accessor.get($Deb);
    const tree = lists.lastFocusedList;
    if (!(tree instanceof $3eb) && !(tree instanceof $4eb)) {
      return;
    }
    const element = tree.getFocus()[0];
    if (URI.isUri(element?.resource)) {
      return editors.openEditor({
        resource: element.resource,
        options: { pinned: true }
      }, $oJ);
    }
    const input = tree.getInput();
    if (input && typeof input.outlineKind === "string") {
      return input.reveal(element, {
        pinned: true,
        preserveFocus: false
      }, true, false);
    }
  }
});

// out-build/vs/workbench/browser/parts/editor/editorTabsControl.js
var $Jyb_1;
var $Iyb = class extends $Vm {
  constructor(a) {
    super();
    this.a = a;
  }
  run(action, context) {
    let mergedContext = this.a;
    if (context?.preserveFocus) {
      mergedContext = {
        ...this.a,
        preserveFocus: true
      };
    }
    return super.run(action, mergedContext);
  }
};
var $Jyb = class $Jyb2 extends $ns {
  static {
    $Jyb_1 = this;
  }
  static {
    this.f = {
      normal: 35,
      compact: 22
    };
  }
  constructor(M, N, O, P, Q, R, S, U, W, X, Y, themeService, Z, $149) {
    super(themeService);
    this.M = M;
    this.N = N;
    this.O = O;
    this.P = P;
    this.Q = Q;
    this.R = R;
    this.S = S;
    this.U = U;
    this.W = W;
    this.X = X;
    this.Y = Y;
    this.Z = Z;
    this.$ = $149;
    this.a = $B_.getInstance();
    this.b = $B_.getInstance();
    this.c = $B_.getInstance();
    this.m = this.B(new $2c());
    this.r = this.B(new $2c());
    this.L = false;
    const container2 = this.ab(M);
    this.s = this.B(this.U.createScoped(container2));
    const scopedInstantiationService = this.B(this.S.createChild(new $Ok([$on, this.s])));
    this.t = this.B(scopedInstantiationService.createInstance($lqb));
    this.u = $upb.bindTo(this.s);
    this.C = $vpb.bindTo(this.s);
    this.D = $wpb.bindTo(this.s);
    this.F = $xpb.bindTo(this.s);
    this.G = $Epb.bindTo(this.s);
    this.H = $Cpb.bindTo(this.s);
    this.I = $Hpb.bindTo(this.s);
    this.J = $Mpb.bindTo(this.s);
  }
  ab(parent) {
    this.wb();
    return parent;
  }
  get bb() {
    return this.O.partOptions.editorActionsLocation === "default" && this.O.partOptions.showTabs !== "none";
  }
  cb(parent, classes2) {
    this.g = document.createElement("div");
    this.g.classList.add(...classes2);
    parent.appendChild(this.g);
    this.db(this.g);
  }
  db(container2) {
    const editorActionsEnabled = this.bb;
    const editorActionsVisible = !!this.j;
    if (editorActionsEnabled && !editorActionsVisible) {
      this.eb(container2);
    } else if (!editorActionsEnabled && editorActionsVisible) {
      this.j?.getElement().remove();
      this.j = void 0;
      this.m.clear();
      this.r.clear();
    }
    container2.classList.toggle("hidden", !editorActionsEnabled);
  }
  eb(container2) {
    const context = { groupId: this.P.id };
    this.j = this.m.add(this.S.createInstance($3$, container2, {
      actionViewItemProvider: (action, options3) => this.fb(action, options3),
      orientation: 0,
      ariaLabel: localize(3591, null),
      getKeyBinding: (action) => this.sb(action),
      actionRunner: this.m.add(new $Iyb(context)),
      anchorAlignmentProvider: () => 1,
      renderDropdownAsChildElement: this.L,
      telemetrySource: "editorPart",
      resetMenu: $bJ.EditorTitle,
      overflowBehavior: { maxItems: 9, exempted: $bvb },
      highlightToggledItems: true
    }));
    this.j.context = context;
    this.m.add(this.j.actionRunner.onDidRun((e) => {
      if (e.error && !$kb(e.error)) {
        this.X.error(e.error);
      }
    }));
  }
  fb(action, options3) {
    const activeEditorPane = this.P.activeEditorPane;
    if (activeEditorPane instanceof $5tb) {
      const result = activeEditorPane.getActionViewItem(action, options3);
      if (result) {
        return result;
      }
    }
    return $X$(this.S, action, { ...options3, menuAsChild: this.L });
  }
  gb() {
    if (!this.bb) {
      return;
    }
    this.r.clear();
    const editorActions = this.P.createEditorActions(this.r);
    this.r.add(editorActions.onDidChange(() => this.gb()));
    const editorActionsToolbar = $Kg(this.j);
    const { primary, secondary } = this.hb(editorActions.actions);
    editorActionsToolbar.setActions($MZ(primary), $MZ(secondary));
  }
  ib() {
    return this.P.activeEditorPane?.scopedContextKeyService ?? this.U;
  }
  jb() {
    if (!this.bb) {
      return;
    }
    const editorActionsToolbar = $Kg(this.j);
    editorActionsToolbar.setActions([], []);
  }
  lb(e, element) {
    if (e.target !== element) {
      return false;
    }
    const isNewWindowOperation = this.ob(e);
    this.b.setData([new $Bob(this.P.id)], $Bob.prototype);
    if (e.dataTransfer) {
      e.dataTransfer.effectAllowed = "copyMove";
    }
    let hasDataTransfer = false;
    if (this.O.partOptions.showTabs === "multiple") {
      hasDataTransfer = this.qb(this.P.getEditors(
        1
        /* EditorsOrder.SEQUENTIAL */
      ), e, isNewWindowOperation);
    } else {
      if (this.P.activeEditor) {
        hasDataTransfer = this.qb([this.P.activeEditor], e, isNewWindowOperation);
      }
    }
    if (!hasDataTransfer && $Ue) {
      e.dataTransfer?.setData($kZ.TEXT, String(this.P.label));
    }
    if (this.P.activeEditor) {
      let label3 = this.P.activeEditor.getName();
      if (this.O.partOptions.showTabs === "multiple" && this.P.count > 1) {
        label3 = localize(3592, null, label3, this.P.count - 1);
      }
      $lZ(e, label3, "monaco-editor-group-drag-image", this.z($ir), this.z($jr));
    }
    return isNewWindowOperation;
  }
  async mb(e, previousDragEvent, element, isNewWindowOperation) {
    this.b.clearData($Bob.prototype);
    if (e.target !== element || !isNewWindowOperation || $Lob()) {
      return;
    }
    const auxiliaryEditorPart = await this.nb(e, element);
    if (!auxiliaryEditorPart) {
      return;
    }
    const targetGroup = auxiliaryEditorPart.activeGroup;
    this.O.mergeGroup(this.P, targetGroup.id, {
      mode: this.pb(previousDragEvent ?? e, targetGroup.id) ? 1 : 0
      /* MergeGroupMode.COPY_EDITORS */
    });
    targetGroup.focus();
  }
  async nb(e, offsetElement) {
    const { point, display } = await this.$.getCursorScreenPoint() ?? { point: { x: e.screenX, y: e.screenY } };
    const window3 = $Qj();
    if (window3.document.visibilityState === "visible" && window3.document.hasFocus()) {
      if (point.x >= window3.screenX && point.x <= window3.screenX + window3.outerWidth && point.y >= window3.screenY && point.y <= window3.screenY + window3.outerHeight) {
        return;
      }
    }
    const offsetX = offsetElement.offsetWidth / 2;
    const offsetY = 30 + offsetElement.offsetHeight / 2;
    const bounds = {
      x: point.x - offsetX,
      y: point.y - offsetY
    };
    if (display) {
      if (bounds.x < display.x) {
        bounds.x = display.x;
      }
      if (bounds.y < display.y) {
        bounds.y = display.y;
      }
    }
    return this.N.createAuxiliaryEditorPart({ bounds });
  }
  ob(e) {
    if (this.O.partOptions.dragToOpenWindow) {
      return !e.altKey;
    }
    return e.altKey;
  }
  pb(e, sourceGroup, sourceEditor) {
    if (sourceEditor?.hasCapability(
      8
      /* EditorInputCapabilities.Singleton */
    )) {
      return true;
    }
    const isCopy = e.ctrlKey && !$m || e.altKey && $m;
    return !isCopy || sourceGroup === this.P.id;
  }
  qb(editors, e, disableStandardTransfer) {
    if (editors.length) {
      this.S.invokeFunction($Eob, editors.map((editor) => ({ editor, groupId: this.P.id })), e, { disableStandardTransfer });
      return true;
    }
    return false;
  }
  rb(editor, e, node) {
    this.t.set($mL.getOriginalUri(editor, { supportSideBySide: SideBySideEditor.PRIMARY }));
    this.u.set(this.Q.isPinned(editor));
    this.C.set(this.Q.isFirst(editor));
    this.D.set(this.Q.isLast(editor));
    this.F.set(this.Q.isSticky(editor));
    this.J.set(this.Q.isLocked);
    this.H.set(editor.hasCapability(
      32
      /* EditorInputCapabilities.CanSplitInGroup */
    ));
    this.I.set(editor.typeId === $1I.ID);
    $mqb(this.G, editor, this.Z);
    let anchor = node;
    if ($3j(e)) {
      anchor = new $lf(getWindow(node), e);
    }
    this.R.showContextMenu({
      getAnchor: () => anchor,
      menuId: $bJ.EditorTitleContext,
      menuActionOptions: { shouldForwardArgs: true, arg: this.t.get() },
      contextKeyService: this.s,
      getActionsContext: () => ({ groupId: this.P.id, editorIndex: this.P.getIndexOfEditor(editor) }),
      getKeyBinding: (action) => this.W.lookupKeybinding(action.id, this.s),
      onHide: () => this.O.activeGroup.focus()
      // restore focus to active group
    });
  }
  sb(action) {
    return this.W.lookupKeybinding(action.id, this.ib());
  }
  tb(action) {
    const keybinding = this.sb(action);
    return keybinding ? keybinding.getLabel() ?? void 0 : void 0;
  }
  get ub() {
    return this.O.partOptions.tabHeight !== "compact" ? $Jyb_1.f.normal : $Jyb_1.f.compact;
  }
  vb(editor) {
    const title = editor.getTitle(
      2
      /* Verbosity.LONG */
    );
    if (!this.Q.isPinned(editor)) {
      return {
        markdown: new $bm("", { supportThemeIcons: true, isTrusted: true }).appendText(title).appendMarkdown(' (_preview_ [$(gear)](command:workbench.action.openSettings?%5B%22workbench.editor.enablePreview%22%5D "Configure Preview Mode"))'),
        markdownNotSupportedFallback: title + " (preview)"
      };
    }
    return title;
  }
  wb() {
    this.M.style.setProperty("--editor-group-tab-height", `${this.ub}px`);
  }
  updateOptions(oldOptions, newOptions) {
    if (oldOptions.tabHeight !== newOptions.tabHeight) {
      this.wb();
    }
    if (oldOptions.editorActionsLocation !== newOptions.editorActionsLocation || oldOptions.showTabs !== newOptions.showTabs) {
      if (this.g) {
        this.db(this.g);
        this.gb();
      }
    }
  }
};
$Jyb = $Jyb_1 = __decorate([
  __param(5, $50),
  __param(6, $Pk),
  __param(7, $on),
  __param(8, $Ty),
  __param(9, $PJ),
  __param(10, $1M),
  __param(11, $gs),
  __param(12, $4L),
  __param(13, $S4)
], $Jyb);

// out-build/vs/workbench/common/editor/filteredEditorGroupModel.js
var FilteredEditorGroupModel = class extends $3c {
  constructor(b) {
    super();
    this.b = b;
    this.a = this.B(new $ze());
    this.onDidModelChange = this.a.event;
    this.B(this.b.onDidModelChange((e) => {
      const candidateOrIndex = e.editorIndex ?? e.editor;
      if (candidateOrIndex !== void 0) {
        if (!this.c(candidateOrIndex)) {
          return;
        }
      }
      this.a.fire(e);
    }));
  }
  get id() {
    return this.b.id;
  }
  get isLocked() {
    return this.b.isLocked;
  }
  get stickyCount() {
    return this.b.stickyCount;
  }
  get activeEditor() {
    return this.b.activeEditor && this.c(this.b.activeEditor) ? this.b.activeEditor : null;
  }
  get previewEditor() {
    return this.b.previewEditor && this.c(this.b.previewEditor) ? this.b.previewEditor : null;
  }
  get selectedEditors() {
    return this.b.selectedEditors.filter((e) => this.c(e));
  }
  isPinned(editorOrIndex) {
    return this.b.isPinned(editorOrIndex);
  }
  isTransient(editorOrIndex) {
    return this.b.isTransient(editorOrIndex);
  }
  isSticky(editorOrIndex) {
    return this.b.isSticky(editorOrIndex);
  }
  isActive(editor) {
    return this.b.isActive(editor);
  }
  isSelected(editorOrIndex) {
    return this.b.isSelected(editorOrIndex);
  }
  isFirst(editor) {
    return this.b.isFirst(editor, this.getEditors(
      1
      /* EditorsOrder.SEQUENTIAL */
    ));
  }
  isLast(editor) {
    return this.b.isLast(editor, this.getEditors(
      1
      /* EditorsOrder.SEQUENTIAL */
    ));
  }
  getEditors(order, options3) {
    const editors = this.b.getEditors(order, options3);
    return editors.filter((e) => this.c(e));
  }
  findEditor(candidate, options3) {
    const result = this.b.findEditor(candidate, options3);
    if (!result) {
      return void 0;
    }
    return this.c(result[1]) ? result : void 0;
  }
};
var $Kyb = class extends FilteredEditorGroupModel {
  get count() {
    return this.b.stickyCount;
  }
  getEditors(order, options3) {
    if (options3?.excludeSticky) {
      return [];
    }
    if (order === 1) {
      return this.b.getEditors(
        1
        /* EditorsOrder.SEQUENTIAL */
      ).slice(0, this.b.stickyCount);
    }
    return super.getEditors(order, options3);
  }
  isSticky(editorOrIndex) {
    return true;
  }
  getEditorByIndex(index) {
    return index < this.count ? this.b.getEditorByIndex(index) : void 0;
  }
  indexOf(editor, editors, options3) {
    const editorIndex = this.b.indexOf(editor, editors, options3);
    if (editorIndex < 0 || editorIndex >= this.b.stickyCount) {
      return -1;
    }
    return editorIndex;
  }
  contains(candidate, options3) {
    const editorIndex = this.b.indexOf(candidate, void 0, options3);
    return editorIndex >= 0 && editorIndex < this.b.stickyCount;
  }
  c(candidateOrIndex) {
    return this.b.isSticky(candidateOrIndex);
  }
};
var $Lyb = class extends FilteredEditorGroupModel {
  get count() {
    return this.b.count - this.b.stickyCount;
  }
  get stickyCount() {
    return 0;
  }
  isSticky(editorOrIndex) {
    return false;
  }
  getEditors(order, options3) {
    if (order === 1) {
      return this.b.getEditors(
        1
        /* EditorsOrder.SEQUENTIAL */
      ).slice(this.b.stickyCount);
    }
    return super.getEditors(order, options3);
  }
  getEditorByIndex(index) {
    return index >= 0 ? this.b.getEditorByIndex(index + this.b.stickyCount) : void 0;
  }
  indexOf(editor, editors, options3) {
    const editorIndex = this.b.indexOf(editor, editors, options3);
    if (editorIndex < this.b.stickyCount || editorIndex >= this.b.count) {
      return -1;
    }
    return editorIndex - this.b.stickyCount;
  }
  contains(candidate, options3) {
    const editorIndex = this.b.indexOf(candidate, void 0, options3);
    return editorIndex >= this.b.stickyCount && editorIndex < this.b.count;
  }
  c(candidateOrIndex) {
    return !this.b.isSticky(candidateOrIndex);
  }
};

// out-build/vs/workbench/browser/parts/editor/multiEditorTabsControl.js
var $Myb_1;
var $Myb = class $Myb2 extends $Jyb {
  static {
    $Myb_1 = this;
  }
  static {
    this.xb = {
      default: 3,
      large: 10
    };
  }
  static {
    this.yb = {
      compact: 38,
      shrink: 80,
      fit: 120
    };
  }
  static {
    this.zb = 1500;
  }
  static {
    this.Ab = 150;
  }
  static {
    this.Bb = 1.5;
  }
  constructor(parent, editorPartsView, groupsView, groupView, tabsModel, contextMenuService, instantiationService, contextKeyService, keybindingService, notificationService, quickInputService, themeService, Ub, Vb, Wb, editorResolverService, hostService) {
    super(parent, editorPartsView, groupsView, groupView, tabsModel, contextMenuService, instantiationService, contextKeyService, keybindingService, notificationService, quickInputService, themeService, editorResolverService, hostService);
    this.Ub = Ub;
    this.Vb = Vb;
    this.Wb = Wb;
    this.Hb = this.B(this.S.createInstance($1wb, $1wb.ID, $1wb.LABEL));
    this.Ib = this.B(this.S.createInstance($Zwb, $Zwb.ID, $Zwb.LABEL));
    this.Jb = this.B(this.S.createInstance($lsb, $ksb));
    this.Kb = [];
    this.Mb = [];
    this.Nb = [];
    this.Ob = {
      container: $rj.None,
      available: $rj.None
    };
    this.Pb = this.B(new $4c());
    this.Rb = $l ? $jc : $kc;
    this.Sb = 0;
    this.Tb = false;
    this.kc = this.B(new $8h(() => this.lc(), 0));
    (async () => this.Rb = await this.Vb.path)();
    this.B(this.Jb.onDidChangeDecorations(() => this.dc()));
  }
  ab(parent) {
    super.ab(parent);
    this.Cb = parent;
    this.Db = document.createElement("div");
    this.Db.classList.add("tabs-and-actions-container");
    this.Cb.appendChild(this.Db);
    this.Eb = document.createElement("div");
    this.Eb.setAttribute("role", "tablist");
    this.Eb.draggable = true;
    this.Eb.classList.add("tabs-container");
    this.B($mZ.addTarget(this.Eb));
    this.Gb = this.B(new $2c());
    this.$b(false);
    this.Fb = this.Yb(this.Eb);
    this.Db.appendChild(this.Fb.getDomNode());
    this.cc(this.Eb, this.Fb);
    this.cb(this.Db, ["editor-actions"]);
    this.Tc();
    return this.Db;
  }
  Yb(scrollable) {
    const tabsScrollbar = this.B(new $AZ(scrollable, {
      horizontal: 1,
      horizontalScrollbarSize: this.bc(),
      vertical: 2,
      scrollYToX: true,
      useShadows: false
    }));
    this.B(tabsScrollbar.onScroll((e) => {
      if (e.scrollLeftChanged) {
        scrollable.scrollLeft = e.scrollLeft;
      }
    }));
    return tabsScrollbar;
  }
  Zb() {
    this.Fb?.updateOptions({
      horizontalScrollbarSize: this.bc()
    });
  }
  $b(fromEvent) {
    const [tabsContainer, tabSizingFixedDisposables] = $Lg(this.Eb, this.Gb);
    tabSizingFixedDisposables.clear();
    const options3 = this.O.partOptions;
    if (options3.tabSizing === "fixed") {
      tabsContainer.style.setProperty("--tab-sizing-fixed-min-width", `${options3.tabSizingFixedMinWidth}px`);
      tabsContainer.style.setProperty("--tab-sizing-fixed-max-width", `${options3.tabSizingFixedMaxWidth}px`);
      tabSizingFixedDisposables.add($_i(tabsContainer, $7j.MOUSE_ENTER, () => {
        this.Tb = true;
      }));
      tabSizingFixedDisposables.add($_i(tabsContainer, $7j.MOUSE_LEAVE, () => {
        this.Tb = false;
        this.ac(false);
      }));
    } else if (fromEvent) {
      tabsContainer.style.removeProperty("--tab-sizing-fixed-min-width");
      tabsContainer.style.removeProperty("--tab-sizing-fixed-max-width");
      this.ac(false);
    }
  }
  ac(fixed) {
    this.mc((editor, tabIndex, tabContainer) => {
      if (fixed) {
        const { width: width2 } = tabContainer.getBoundingClientRect();
        tabContainer.style.setProperty("--tab-sizing-current-width", `${width2}px`);
      } else {
        tabContainer.style.removeProperty("--tab-sizing-current-width");
      }
    });
  }
  bc() {
    if (this.O.partOptions.titleScrollbarSizing !== "large") {
      return $Myb_1.xb.default;
    }
    return $Myb_1.xb.large;
  }
  cc(tabsContainer, tabsScrollbar) {
    this.B($_i(tabsContainer, $7j.SCROLL, () => {
      if (tabsContainer.classList.contains("scroll")) {
        tabsScrollbar.setScrollPosition({
          scrollLeft: tabsContainer.scrollLeft
          // during DND the container gets scrolled so we need to update the custom scrollbar
        });
      }
    }));
    for (const eventType of [EventType.Tap, $7j.DBLCLICK]) {
      this.B($_i(tabsContainer, eventType, (e) => {
        if (eventType === $7j.DBLCLICK) {
          if (e.target !== tabsContainer) {
            return;
          }
        } else {
          if (e.tapCount !== 2) {
            return;
          }
          if (e.initialTarget !== tabsContainer) {
            return;
          }
        }
        $9j.stop(e);
        this.Ub.openEditor({
          resource: void 0,
          options: {
            pinned: true,
            index: this.P.count,
            // always at the end
            override: $1K.id
          }
        }, this.P.id);
      }));
    }
    this.B($_i(tabsContainer, $7j.MOUSE_DOWN, (e) => {
      if (e.button === 1) {
        e.preventDefault();
      }
    }));
    if ($n) {
      this.B($_i(tabsContainer, $7j.MOUSE_UP, (e) => {
        if (e.button === 1) {
          e.preventDefault();
        }
      }));
    }
    let lastDragEvent = void 0;
    let isNewWindowOperation = false;
    this.B(new $Ak(tabsContainer, {
      onDragStart: (e) => {
        isNewWindowOperation = this.lb(e, tabsContainer);
      },
      onDrag: (e) => {
        lastDragEvent = e;
      },
      onDragEnter: (e) => {
        tabsContainer.classList.add("scroll");
        if (e.target !== tabsContainer) {
          return;
        }
        if (!this.tc(e)) {
          if (e.dataTransfer) {
            e.dataTransfer.dropEffect = "none";
          }
          return;
        }
        if (!this.a.hasData($Aob.prototype)) {
          if (e.dataTransfer) {
            e.dataTransfer.dropEffect = "copy";
          }
        }
        this.uc(tabsContainer, true, e);
      },
      onDragLeave: (e) => {
        this.uc(tabsContainer, false, e);
        tabsContainer.classList.remove("scroll");
      },
      onDragEnd: (e) => {
        this.uc(tabsContainer, false, e);
        tabsContainer.classList.remove("scroll");
        this.mb(e, lastDragEvent, tabsContainer, isNewWindowOperation);
      },
      onDrop: (e) => {
        this.uc(tabsContainer, false, e);
        tabsContainer.classList.remove("scroll");
        if (e.target === tabsContainer) {
          const isGroupTransfer = this.b.hasData($Bob.prototype);
          this.$c(e, isGroupTransfer ? this.P.count : this.Q.count, tabsContainer);
        }
      }
    }));
    this.B($_i(tabsContainer, $7j.MOUSE_WHEEL, (e) => {
      const activeEditor = this.P.activeEditor;
      if (!activeEditor || this.P.count < 2) {
        return;
      }
      if (this.O.partOptions.scrollToSwitchTabs === true) {
        if (e.shiftKey) {
          return;
        }
      } else {
        if (!e.shiftKey) {
          return;
        }
      }
      const now = Date.now();
      if (now - this.Sb < $Myb_1.Ab - 2 * (Math.abs(e.deltaX) + Math.abs(e.deltaY))) {
        return;
      }
      this.Sb = now;
      let tabSwitchDirection;
      if (e.deltaX + e.deltaY < -$Myb_1.Bb) {
        tabSwitchDirection = -1;
      } else if (e.deltaX + e.deltaY > $Myb_1.Bb) {
        tabSwitchDirection = 1;
      } else {
        return;
      }
      const nextEditor = this.P.getEditorByIndex(this.P.getIndexOfEditor(activeEditor) + tabSwitchDirection);
      if (!nextEditor) {
        return;
      }
      this.P.openEditor(nextEditor);
      $9j.stop(e, true);
    }));
    const showContextMenu = (e) => {
      $9j.stop(e);
      let anchor = tabsContainer;
      if ($3j(e)) {
        anchor = new $lf(getWindow(this.M), e);
      }
      this.R.showContextMenu({
        getAnchor: () => anchor,
        menuId: $bJ.EditorTabsBarContext,
        contextKeyService: this.U,
        menuActionOptions: { shouldForwardArgs: true },
        getActionsContext: () => ({ groupId: this.P.id }),
        getKeyBinding: (action) => this.sb(action),
        onHide: () => this.P.focus()
      });
    };
    this.B($_i(tabsContainer, EventType.Contextmenu, (e) => showContextMenu(e)));
    this.B($_i(tabsContainer, $7j.CONTEXT_MENU, (e) => showContextMenu(e)));
  }
  dc() {
    this.layout(this.Ob);
  }
  gb() {
    super.gb();
    this.layout(this.Ob);
  }
  openEditor(editor, options3) {
    const changed = this.fc();
    if (options3?.focusTabControl) {
      this.nc(editor, (editor2, tabIndex, tabContainer) => tabContainer.focus());
    }
    return changed;
  }
  openEditors(editors) {
    return this.fc();
  }
  fc() {
    this.Tc();
    const [tabsContainer, tabsScrollbar] = $Lg(this.Eb, this.Fb);
    for (let i2 = tabsContainer.children.length; i2 < this.Q.count; i2++) {
      tabsContainer.appendChild(this.pc(i2, tabsContainer, tabsScrollbar));
    }
    const activeEditorChanged = this.gc();
    const oldActiveTabLabel = this.Lb;
    const oldTabLabelsLength = this.Kb.length;
    this.Dc();
    let didChange = false;
    if (activeEditorChanged || // active editor changed
    oldTabLabelsLength !== this.Kb.length || // number of tabs changed
    !this.hc(oldActiveTabLabel, this.Lb)) {
      this.Gc({ forceRevealActiveTab: true });
      didChange = true;
    } else {
      this.layout(this.Ob, { forceRevealActiveTab: true });
    }
    return didChange;
  }
  gc() {
    if (!this.Lb?.editor && this.Q.activeEditor || // active editor changed from null => editor
    this.Lb?.editor && !this.Q.activeEditor || // active editor changed from editor => null
    (!this.Lb?.editor || !this.Q.isActive(this.Lb.editor))) {
      return true;
    }
    return false;
  }
  hc(labelA, labelB) {
    if (labelA === labelB) {
      return true;
    }
    if (!labelA || !labelB) {
      return false;
    }
    return labelA.name === labelB.name && labelA.description === labelB.description && labelA.forceDescription === labelB.forceDescription && labelA.title === labelB.title && labelA.ariaLabel === labelB.ariaLabel;
  }
  beforeCloseEditor(editor) {
    if (this.Tb && this.O.partOptions.tabSizing === "fixed") {
      const closingLastTab = this.Q.isLast(editor);
      this.ac(!closingLastTab);
    }
  }
  closeEditor(editor) {
    this.ic();
  }
  closeEditors(editors) {
    this.ic();
  }
  ic() {
    if (this.Q.count) {
      const tabsContainer = $Kg(this.Eb);
      while (tabsContainer.children.length > this.Q.count) {
        tabsContainer.lastChild?.remove();
        $Xc(this.Nb.pop());
      }
      this.Dc();
      this.Gc({ forceRevealActiveTab: true });
    } else {
      if (this.Eb) {
        $$i(this.Eb);
      }
      this.Nb = $Xc(this.Nb);
      this.Jb.clear();
      this.Kb = [];
      this.Lb = void 0;
      this.Mb = [];
      this.jb();
      this.Tc();
    }
  }
  moveEditor(editor, fromTabIndex, targeTabIndex) {
    const editorLabel = this.Kb[fromTabIndex];
    this.Kb.splice(fromTabIndex, 1);
    this.Kb.splice(targeTabIndex, 0, editorLabel);
    this.mc(
      (editor2, tabIndex, tabContainer, tabLabelWidget, tabLabel, tabActionBar) => {
        this.Hc(editor2, tabIndex, tabContainer, tabLabelWidget, tabLabel, tabActionBar);
      },
      Math.min(fromTabIndex, targeTabIndex),
      // from: smallest of fromTabIndex/targeTabIndex
      Math.max(fromTabIndex, targeTabIndex)
      //   to: largest of fromTabIndex/targeTabIndex
    );
    this.layout(this.Ob, { forceRevealActiveTab: true });
  }
  pinEditor(editor) {
    this.nc(editor, (editor2, tabIndex, tabContainer, tabLabelWidget, tabLabel) => this.Ic(editor2, tabIndex, tabContainer, tabLabelWidget, tabLabel));
  }
  stickEditor(editor) {
    this.jc(editor);
  }
  unstickEditor(editor) {
    this.jc(editor);
  }
  jc(editor) {
    this.nc(editor, (editor2, tabIndex, tabContainer, tabLabelWidget, tabLabel, tabActionBar) => this.Hc(editor2, tabIndex, tabContainer, tabLabelWidget, tabLabel, tabActionBar));
    this.mc((editor2, tabIndex, tabContainer, tabLabelWidget, tabLabel) => {
      this.Mc(tabIndex, tabContainer);
    });
    this.layout(this.Ob, { forceRevealActiveTab: true });
  }
  setActive(isGroupActive) {
    this.mc((editor, tabIndex, tabContainer, tabLabelWidget, tabLabel, tabActionBar) => {
      this.Jc(isGroupActive, editor, tabContainer, tabActionBar);
    });
    this.gb();
    this.layout(this.Ob, { forceRevealActiveTab: true });
  }
  updateEditorSelections() {
    this.mc((editor, tabIndex, tabContainer, tabLabelWidget, tabLabel, tabActionBar) => {
      this.Jc(this.O.activeGroup === this.P, editor, tabContainer, tabActionBar);
    });
  }
  updateEditorLabel(editor) {
    this.kc.schedule();
  }
  lc() {
    this.Dc();
    this.mc((editor, tabIndex, tabContainer, tabLabelWidget, tabLabel) => {
      this.Ic(editor, tabIndex, tabContainer, tabLabelWidget, tabLabel);
    });
    this.layout(this.Ob);
  }
  updateEditorDirty(editor) {
    this.nc(editor, (editor2, tabIndex, tabContainer, tabLabelWidget, tabLabel, tabActionBar) => this.Jc(this.O.activeGroup === this.P, editor2, tabContainer, tabActionBar));
  }
  updateOptions(oldOptions, newOptions) {
    super.updateOptions(oldOptions, newOptions);
    if (oldOptions.labelFormat !== newOptions.labelFormat) {
      this.Dc();
    }
    if (oldOptions.titleScrollbarSizing !== newOptions.titleScrollbarSizing) {
      this.Zb();
    }
    if (oldOptions.alwaysShowEditorActions !== newOptions.alwaysShowEditorActions) {
      this.gb();
    }
    if (oldOptions.tabSizingFixedMinWidth !== newOptions.tabSizingFixedMinWidth || oldOptions.tabSizingFixedMaxWidth !== newOptions.tabSizingFixedMaxWidth || oldOptions.tabSizing !== newOptions.tabSizing) {
      this.$b(true);
    }
    if (oldOptions.labelFormat !== newOptions.labelFormat || oldOptions.tabActionLocation !== newOptions.tabActionLocation || oldOptions.tabActionCloseVisibility !== newOptions.tabActionCloseVisibility || oldOptions.tabActionUnpinVisibility !== newOptions.tabActionUnpinVisibility || oldOptions.tabSizing !== newOptions.tabSizing || oldOptions.pinnedTabSizing !== newOptions.pinnedTabSizing || oldOptions.showIcons !== newOptions.showIcons || oldOptions.hasIcons !== newOptions.hasIcons || oldOptions.highlightModifiedTabs !== newOptions.highlightModifiedTabs || oldOptions.wrapTabs !== newOptions.wrapTabs || !$Pv(oldOptions.decorations, newOptions.decorations)) {
      this.Gc();
    }
  }
  updateStyles() {
    this.Gc();
  }
  mc(fn, fromTabIndex, toTabIndex) {
    this.Q.getEditors(
      1
      /* EditorsOrder.SEQUENTIAL */
    ).forEach((editor, tabIndex) => {
      if (typeof fromTabIndex === "number" && fromTabIndex > tabIndex) {
        return;
      }
      if (typeof toTabIndex === "number" && toTabIndex < tabIndex) {
        return;
      }
      this.oc(tabIndex, editor, fn);
    });
  }
  nc(editor, fn) {
    this.oc(this.Q.indexOf(editor), editor, fn);
  }
  oc(tabIndex, editor, fn) {
    const tabsContainer = $Kg(this.Eb);
    const tabContainer = tabsContainer.children[tabIndex];
    const tabResourceLabel = this.Jb.get(tabIndex);
    const tabLabel = this.Kb[tabIndex];
    const tabActionBar = this.Mb[tabIndex];
    if (tabContainer && tabResourceLabel && tabLabel) {
      fn(editor, tabIndex, tabContainer, tabResourceLabel, tabLabel, tabActionBar);
    }
  }
  pc(tabIndex, tabsContainer, tabsScrollbar) {
    const tabContainer = document.createElement("div");
    tabContainer.draggable = true;
    tabContainer.setAttribute("role", "tab");
    tabContainer.classList.add("tab");
    this.B($mZ.addTarget(tabContainer));
    const tabBorderTopContainer = document.createElement("div");
    tabBorderTopContainer.classList.add("tab-border-top-container");
    tabContainer.appendChild(tabBorderTopContainer);
    const editorLabel = this.Jb.create(tabContainer, { hoverTargetOverride: tabContainer });
    const tabActionsContainer = document.createElement("div");
    tabActionsContainer.classList.add("tab-actions");
    tabContainer.appendChild(tabActionsContainer);
    const that = this;
    const tabActionRunner = new $Iyb({
      groupId: this.P.id,
      get editorIndex() {
        return that.qc(tabIndex);
      }
    });
    const tabActionBar = new $LZ(tabActionsContainer, { ariaLabel: localize(3593, null), actionRunner: tabActionRunner });
    const tabActionListener = tabActionBar.onWillRun((e) => {
      if (e.action.id === this.Hb.id) {
        this.Yc();
      }
    });
    const tabActionBarDisposable = $Zc(tabActionBar, tabActionListener, $1c($Wb(this.Mb, tabActionBar)));
    const tabShadowHider = document.createElement("div");
    tabShadowHider.classList.add("tab-fade-hider");
    tabContainer.appendChild(tabShadowHider);
    const tabBorderBottomContainer = document.createElement("div");
    tabBorderBottomContainer.classList.add("tab-border-bottom-container");
    tabContainer.appendChild(tabBorderBottomContainer);
    const eventsDisposable = this.sc(tabContainer, tabIndex, tabsContainer, tabsScrollbar);
    this.Nb.push($Zc(eventsDisposable, tabActionBarDisposable, tabActionRunner, editorLabel));
    return tabContainer;
  }
  qc(tabIndex) {
    const editor = $Kg(this.Q.getEditorByIndex(tabIndex));
    return this.P.getIndexOfEditor(editor);
  }
  sc(tab, tabIndex, tabsContainer, tabsScrollbar) {
    const disposables = new $2c();
    const handleClickOrTouch = async (e, preserveFocus) => {
      tab.blur();
      if ($3j(e) && (e.button !== 0 || $m && e.ctrlKey)) {
        if (e.button === 1) {
          e.preventDefault();
        }
        return;
      }
      if (this.Zc(e)) {
        return;
      }
      const editor = this.Q.getEditorByIndex(tabIndex);
      if (editor) {
        if (e.shiftKey) {
          let anchor;
          if (this.rc && this.Q.isSelected(this.rc)) {
            anchor = this.rc;
          } else {
            const activeEditor = $Kg(this.P.activeEditor);
            this.rc = activeEditor;
            anchor = activeEditor;
          }
          await this.Ac(editor, anchor);
        } else if (e.ctrlKey && !$m || e.metaKey && $m) {
          if (this.Q.isSelected(editor)) {
            await this.Bc(editor);
          } else {
            await this.zc(editor);
            this.rc = editor;
          }
        } else {
          const inactiveSelection = this.Q.isSelected(editor) ? this.P.selectedEditors.filter((e2) => !e2.matches(editor)) : [];
          await this.P.openEditor(editor, { preserveFocus, activation: EditorActivation.ACTIVATE }, { inactiveSelection, focusTabControl: true });
        }
      }
    };
    const showContextMenu = (e) => {
      $9j.stop(e);
      const editor = this.Q.getEditorByIndex(tabIndex);
      if (editor) {
        this.rb(editor, e, tab);
      }
    };
    disposables.add($_i(tab, $7j.MOUSE_DOWN, (e) => handleClickOrTouch(e, false)));
    disposables.add($_i(tab, EventType.Tap, (e) => handleClickOrTouch(e, true)));
    disposables.add($_i(tab, EventType.Change, (e) => {
      tabsScrollbar.setScrollPosition({ scrollLeft: tabsScrollbar.getScrollPosition().scrollLeft - e.translationX });
    }));
    disposables.add($_i(tab, $7j.MOUSE_UP, async (e) => {
      $9j.stop(e);
      tab.blur();
      if ($3j(e) && (e.button !== 0 || $m && e.ctrlKey)) {
        return;
      }
      if (this.Zc(e)) {
        return;
      }
      const isCtrlCmd = e.ctrlKey && !$m || e.metaKey && $m;
      if (!isCtrlCmd && !e.shiftKey && this.P.selectedEditors.length > 1) {
        await this.Cc();
      }
    }));
    disposables.add($_i(tab, $7j.AUXCLICK, (e) => {
      if (e.button === 1) {
        $9j.stop(
          e,
          true
          /* for https://github.com/microsoft/vscode/issues/56715 */
        );
        const editor = this.Q.getEditorByIndex(tabIndex);
        if (editor) {
          if ($lL(this.Q, editor, EditorCloseMethod.MOUSE, this.O.partOptions)) {
            return;
          }
          this.Yc();
          this.Hb.run({ groupId: this.P.id, editorIndex: this.P.getIndexOfEditor(editor) });
        }
      }
    }));
    disposables.add($_i(tab, $7j.KEY_DOWN, (e) => {
      const event = new $if(e);
      if (event.shiftKey && event.keyCode === 68) {
        showContextMenu(e);
      }
    }));
    disposables.add($_i(tab, EventType.Contextmenu, (e) => {
      showContextMenu(e);
    }));
    disposables.add($_i(tab, $7j.KEY_UP, (e) => {
      const event = new $if(e);
      let handled = false;
      if (event.equals(
        3
        /* KeyCode.Enter */
      ) || event.equals(
        10
        /* KeyCode.Space */
      )) {
        handled = true;
        const editor = this.Q.getEditorByIndex(tabIndex);
        if (editor) {
          this.P.openEditor(editor);
        }
      } else if ([
        15,
        17,
        16,
        18,
        14,
        13
        /* KeyCode.End */
      ].some((kb) => event.equals(kb))) {
        let editorIndex = this.qc(tabIndex);
        if (event.equals(
          15
          /* KeyCode.LeftArrow */
        ) || event.equals(
          16
          /* KeyCode.UpArrow */
        )) {
          editorIndex = editorIndex - 1;
        } else if (event.equals(
          17
          /* KeyCode.RightArrow */
        ) || event.equals(
          18
          /* KeyCode.DownArrow */
        )) {
          editorIndex = editorIndex + 1;
        } else if (event.equals(
          14
          /* KeyCode.Home */
        )) {
          editorIndex = 0;
        } else {
          editorIndex = this.P.count - 1;
        }
        const target = this.P.getEditorByIndex(editorIndex);
        if (target) {
          handled = true;
          this.P.openEditor(target, { preserveFocus: true }, { focusTabControl: true });
        }
      }
      if (handled) {
        $9j.stop(e, true);
      }
      tabsScrollbar.setScrollPosition({
        scrollLeft: tabsContainer.scrollLeft
      });
    }));
    for (const eventType of [EventType.Tap, $7j.DBLCLICK]) {
      disposables.add($_i(tab, eventType, (e) => {
        if (eventType === $7j.DBLCLICK) {
          $9j.stop(e);
        } else if (e.tapCount !== 2) {
          return;
        }
        const editor = this.Q.getEditorByIndex(tabIndex);
        if (editor && this.Q.isPinned(editor)) {
          switch (this.O.partOptions.doubleClickTabToToggleEditorGroupSizes) {
            case "maximize":
              this.O.toggleMaximizeGroup(this.P);
              break;
            case "expand":
              this.O.toggleExpandGroup(this.P);
              break;
            case "off":
              break;
          }
        } else {
          this.P.pinEditor(editor);
        }
      }));
    }
    disposables.add($_i(
      tab,
      $7j.CONTEXT_MENU,
      (e) => {
        $9j.stop(e, true);
        const editor = this.Q.getEditorByIndex(tabIndex);
        if (editor) {
          this.rb(editor, e, tab);
        }
      },
      true
      /* use capture to fix https://github.com/microsoft/vscode/issues/19145 */
    ));
    let lastDragEvent = void 0;
    let isNewWindowOperation = false;
    disposables.add(new $Ak(tab, {
      onDragStart: (e) => {
        const editor = this.Q.getEditorByIndex(tabIndex);
        if (!editor) {
          return;
        }
        isNewWindowOperation = this.ob(e);
        const selectedEditors = this.P.selectedEditors;
        this.a.setData(selectedEditors.map((e2) => new $Aob({ editor: e2, groupId: this.P.id })), $Aob.prototype);
        if (e.dataTransfer) {
          e.dataTransfer.effectAllowed = "copyMove";
          if (selectedEditors.length > 1) {
            const label3 = `${editor.getName()} + ${selectedEditors.length - 1}`;
            $lZ(e, label3, "monaco-editor-group-drag-image", this.z($ir), this.z($jr));
          } else {
            e.dataTransfer.setDragImage(tab, 0, 0);
          }
        }
        this.qb(selectedEditors, e, isNewWindowOperation);
        $jj(getWindow(this.M), () => this.uc(tab, false, e, tabIndex));
      },
      onDrag: (e) => {
        lastDragEvent = e;
      },
      onDragEnter: (e) => {
        if (!this.tc(e)) {
          if (e.dataTransfer) {
            e.dataTransfer.dropEffect = "none";
          }
          return;
        }
        if (!this.a.hasData($Aob.prototype)) {
          if (e.dataTransfer) {
            e.dataTransfer.dropEffect = "copy";
          }
        }
        this.uc(tab, true, e, tabIndex);
      },
      onDragOver: (e, dragDuration) => {
        if (dragDuration >= $Myb_1.zb) {
          const draggedOverTab = this.Q.getEditorByIndex(tabIndex);
          if (draggedOverTab && this.Q.activeEditor !== draggedOverTab) {
            this.P.openEditor(draggedOverTab, { preserveFocus: true });
          }
        }
        this.uc(tab, true, e, tabIndex);
      },
      onDragEnd: async (e) => {
        this.uc(tab, false, e, tabIndex);
        const draggedEditors = this.a.getData($Aob.prototype);
        this.a.clearData($Aob.prototype);
        if (!isNewWindowOperation || $Lob() || !draggedEditors || draggedEditors.length === 0) {
          return;
        }
        const auxiliaryEditorPart = await this.nb(e, tab);
        if (!auxiliaryEditorPart) {
          return;
        }
        const targetGroup = auxiliaryEditorPart.activeGroup;
        const editors = draggedEditors.map((de) => ({ editor: de.identifier.editor }));
        if (this.pb(lastDragEvent ?? e, targetGroup.id, draggedEditors[0].identifier.editor)) {
          this.P.moveEditors(editors, targetGroup);
        } else {
          this.P.copyEditors(editors, targetGroup);
        }
        targetGroup.focus();
      },
      onDrop: (e) => {
        this.uc(tab, false, e, tabIndex);
        let targetIndex = tabIndex;
        if (this.xc(e, tab) === "right") {
          targetIndex++;
        }
        this.$c(e, targetIndex, tabsContainer);
      }
    }));
    return disposables;
  }
  tc(e) {
    if (this.b.hasData($Bob.prototype)) {
      const data = this.b.getData($Bob.prototype);
      if (Array.isArray(data) && data.length > 0) {
        const group2 = data[0];
        if (group2.identifier === this.P.id) {
          return false;
        }
      }
      return true;
    }
    if (this.a.hasData($Aob.prototype)) {
      return true;
    }
    if (e.dataTransfer && e.dataTransfer.types.length > 0) {
      return true;
    }
    return false;
  }
  uc(element, isDND, e, tabIndex) {
    const isTab = typeof tabIndex === "number";
    let dropTarget;
    if (isDND) {
      if (isTab) {
        dropTarget = this.yc(e, tabIndex, element);
      } else {
        dropTarget = { leftElement: element.lastElementChild, rightElement: void 0 };
      }
    } else {
      dropTarget = void 0;
    }
    this.wc(dropTarget);
  }
  wc(newTarget) {
    const oldTargets = this.vc;
    if (oldTargets === newTarget || oldTargets && newTarget && oldTargets.leftElement === newTarget.leftElement && oldTargets.rightElement === newTarget.rightElement) {
      return;
    }
    const dropClassLeft = "drop-target-left";
    const dropClassRight = "drop-target-right";
    if (oldTargets) {
      oldTargets.leftElement?.classList.remove(dropClassLeft);
      oldTargets.rightElement?.classList.remove(dropClassRight);
    }
    if (newTarget) {
      newTarget.leftElement?.classList.add(dropClassLeft);
      newTarget.rightElement?.classList.add(dropClassRight);
    }
    this.vc = newTarget;
  }
  xc(e, tab) {
    const rect = tab.getBoundingClientRect();
    const offsetXRelativeToParent = e.clientX - rect.left;
    return offsetXRelativeToParent <= rect.width / 2 ? "left" : "right";
  }
  yc(e, tabIndex, targetTab) {
    const isLeftSideOfTab = this.xc(e, targetTab) === "left";
    const isLastTab = tabIndex === this.Q.count - 1;
    const isFirstTab = tabIndex === 0;
    if (isLeftSideOfTab && isFirstTab) {
      return { leftElement: void 0, rightElement: targetTab };
    }
    if (!isLeftSideOfTab && isLastTab) {
      return { leftElement: targetTab, rightElement: void 0 };
    }
    const tabBefore = isLeftSideOfTab ? targetTab.previousElementSibling : targetTab;
    const tabAfter = isLeftSideOfTab ? targetTab : targetTab.nextElementSibling;
    return { leftElement: tabBefore, rightElement: tabAfter };
  }
  async zc(editor) {
    if (this.P.isActive(editor)) {
      return;
    }
    await this.P.setSelection(editor, this.P.selectedEditors);
  }
  async Ac(target, anchor) {
    const editorIndex = this.P.getIndexOfEditor(target);
    if (editorIndex === -1) {
      throw new $vb();
    }
    const anchorEditorIndex = this.P.getIndexOfEditor(anchor);
    if (anchorEditorIndex === -1) {
      throw new $vb();
    }
    let selection = this.P.selectedEditors;
    let currentEditorIndex = anchorEditorIndex;
    while (currentEditorIndex >= 0 && currentEditorIndex <= this.P.count - 1) {
      currentEditorIndex = anchorEditorIndex < editorIndex ? currentEditorIndex - 1 : currentEditorIndex + 1;
      const currentEditor = this.P.getEditorByIndex(currentEditorIndex);
      if (!currentEditor) {
        break;
      }
      if (!this.P.isSelected(currentEditor)) {
        break;
      }
      selection = selection.filter((editor) => !editor.matches(currentEditor));
    }
    const fromEditorIndex = anchorEditorIndex < editorIndex ? anchorEditorIndex : editorIndex;
    const toEditorIndex = anchorEditorIndex < editorIndex ? editorIndex : anchorEditorIndex;
    const editorsToSelect = this.P.getEditors(
      1
      /* EditorsOrder.SEQUENTIAL */
    ).slice(fromEditorIndex, toEditorIndex + 1);
    for (const editor of editorsToSelect) {
      if (!this.P.isSelected(editor)) {
        selection.push(editor);
      }
    }
    const inactiveSelectedEditors = selection.filter((editor) => !editor.matches(target));
    await this.P.setSelection(target, inactiveSelectedEditors);
  }
  async Bc(editor) {
    const isUnselectingActiveEditor = this.P.isActive(editor);
    if (isUnselectingActiveEditor && this.P.selectedEditors.length === 1) {
      return;
    }
    let newActiveEditor = $Kg(this.P.activeEditor);
    if (isUnselectingActiveEditor) {
      const recentEditors = this.P.getEditors(
        0
        /* EditorsOrder.MOST_RECENTLY_ACTIVE */
      );
      for (let i2 = 1; i2 < recentEditors.length; i2++) {
        const recentEditor = recentEditors[i2];
        if (this.P.isSelected(recentEditor)) {
          newActiveEditor = recentEditor;
          break;
        }
      }
    }
    const inactiveSelectedEditors = this.P.selectedEditors.filter((e) => !e.matches(editor) && !e.matches(newActiveEditor));
    await this.P.setSelection(newActiveEditor, inactiveSelectedEditors);
  }
  async Cc() {
    if (this.P.selectedEditors.length > 1) {
      const activeEditor = $Kg(this.P.activeEditor);
      await this.P.setSelection(activeEditor, []);
    }
  }
  Dc() {
    const { labelFormat } = this.O.partOptions;
    const { verbosity, shortenDuplicates } = this.Fc(labelFormat);
    const labels2 = [];
    let activeEditorTabIndex = -1;
    this.Q.getEditors(
      1
      /* EditorsOrder.SEQUENTIAL */
    ).forEach((editor, tabIndex) => {
      labels2.push({
        editor,
        name: editor.getName(),
        description: editor.getDescription(verbosity),
        forceDescription: editor.hasCapability(
          64
          /* EditorInputCapabilities.ForceDescription */
        ),
        title: editor.getTitle(
          2
          /* Verbosity.LONG */
        ),
        ariaLabel: $0tb(editor, tabIndex, this.P, this.N.count)
      });
      if (editor === this.Q.activeEditor) {
        activeEditorTabIndex = tabIndex;
      }
    });
    if (shortenDuplicates) {
      this.Ec(labels2);
    }
    this.Kb = labels2;
    this.Lb = labels2[activeEditorTabIndex];
  }
  Ec(labels2) {
    const mapNameToDuplicates = /* @__PURE__ */ new Map();
    for (const label3 of labels2) {
      if (typeof label3.description === "string") {
        $Bc(mapNameToDuplicates, label3.name, []).push(label3);
      } else {
        label3.description = "";
      }
    }
    for (const [, duplicateLabels] of mapNameToDuplicates) {
      if (duplicateLabels.length === 1 && !duplicateLabels[0].forceDescription) {
        duplicateLabels[0].description = "";
        continue;
      }
      const mapDescriptionToDuplicates = /* @__PURE__ */ new Map();
      for (const duplicateLabel of duplicateLabels) {
        $Bc(mapDescriptionToDuplicates, duplicateLabel.description, []).push(duplicateLabel);
      }
      let useLongDescriptions = false;
      for (const [, duplicateLabels2] of mapDescriptionToDuplicates) {
        if (!useLongDescriptions && duplicateLabels2.length > 1) {
          const [first, ...rest] = duplicateLabels2.map(({ editor }) => editor.getDescription(
            2
            /* Verbosity.LONG */
          ));
          useLongDescriptions = rest.some((description) => description !== first);
        }
      }
      if (useLongDescriptions) {
        mapDescriptionToDuplicates.clear();
        for (const duplicateLabel of duplicateLabels) {
          duplicateLabel.description = duplicateLabel.editor.getDescription(
            2
            /* Verbosity.LONG */
          );
          $Bc(mapDescriptionToDuplicates, duplicateLabel.description, []).push(duplicateLabel);
        }
      }
      const descriptions = [];
      for (const [description] of mapDescriptionToDuplicates) {
        descriptions.push(description);
      }
      if (descriptions.length === 1) {
        for (const label3 of mapDescriptionToDuplicates.get(descriptions[0]) || []) {
          if (!label3.forceDescription) {
            label3.description = "";
          }
        }
        continue;
      }
      const shortenedDescriptions = $4t(descriptions, this.Rb.sep);
      descriptions.forEach((description, tabIndex) => {
        for (const label3 of mapDescriptionToDuplicates.get(description) || []) {
          label3.description = shortenedDescriptions[tabIndex];
        }
      });
    }
  }
  Fc(value) {
    switch (value) {
      case "short":
        return { verbosity: 0, shortenDuplicates: false };
      case "medium":
        return { verbosity: 1, shortenDuplicates: false };
      case "long":
        return { verbosity: 2, shortenDuplicates: false };
      default:
        return { verbosity: 1, shortenDuplicates: true };
    }
  }
  Gc(options3) {
    if (this.Db) {
      let tabsContainerBorderColor = this.z($ymb);
      if (!tabsContainerBorderColor && $es(this.h.type)) {
        tabsContainerBorderColor = this.z($emb) || this.z($ko);
      }
      if (tabsContainerBorderColor) {
        this.Db.classList.add("tabs-border-bottom");
        this.Db.style.setProperty("--tabs-border-bottom-color", tabsContainerBorderColor.toString());
      } else {
        this.Db.classList.remove("tabs-border-bottom");
        this.Db.style.removeProperty("--tabs-border-bottom-color");
      }
    }
    this.mc((editor, tabIndex, tabContainer, tabLabelWidget, tabLabel, tabActionBar) => {
      this.Hc(editor, tabIndex, tabContainer, tabLabelWidget, tabLabel, tabActionBar);
    });
    this.gb();
    this.layout(this.Ob, options3);
  }
  Hc(editor, tabIndex, tabContainer, tabLabelWidget, tabLabel, tabActionBar) {
    const isTabSticky = this.Q.isSticky(tabIndex);
    const options3 = this.O.partOptions;
    this.Ic(editor, tabIndex, tabContainer, tabLabelWidget, tabLabel);
    const hasUnpinAction = isTabSticky && options3.tabActionUnpinVisibility;
    const hasCloseAction = !hasUnpinAction && options3.tabActionCloseVisibility;
    const hasAction = hasUnpinAction || hasCloseAction;
    let tabAction;
    if (hasAction) {
      tabAction = hasUnpinAction ? this.Ib : this.Hb;
    } else {
      tabAction = isTabSticky ? this.Ib : this.Hb;
    }
    if (!tabActionBar.hasAction(tabAction)) {
      if (!tabActionBar.isEmpty()) {
        tabActionBar.clear();
      }
      tabActionBar.push(tabAction, { icon: true, label: false, keybinding: this.tb(tabAction) });
    }
    tabContainer.classList.toggle(`pinned-action-off`, isTabSticky && !hasUnpinAction);
    tabContainer.classList.toggle(`close-action-off`, !hasUnpinAction && !hasCloseAction);
    for (const option of ["left", "right"]) {
      tabContainer.classList.toggle(`tab-actions-${option}`, hasAction && options3.tabActionLocation === option);
    }
    const tabSizing = isTabSticky && options3.pinnedTabSizing === "shrink" ? "shrink" : options3.tabSizing;
    for (const option of ["fit", "shrink", "fixed"]) {
      tabContainer.classList.toggle(`sizing-${option}`, tabSizing === option);
    }
    tabContainer.classList.toggle("has-icon", options3.showIcons && options3.hasIcons);
    tabContainer.classList.toggle("sticky", isTabSticky);
    for (const option of ["normal", "compact", "shrink"]) {
      tabContainer.classList.toggle(`sticky-${option}`, isTabSticky && options3.pinnedTabSizing === option);
    }
    if (!options3.wrapTabs && isTabSticky && options3.pinnedTabSizing !== "normal") {
      let stickyTabWidth = 0;
      switch (options3.pinnedTabSizing) {
        case "compact":
          stickyTabWidth = $Myb_1.yb.compact;
          break;
        case "shrink":
          stickyTabWidth = $Myb_1.yb.shrink;
          break;
      }
      tabContainer.style.left = `${tabIndex * stickyTabWidth}px`;
    } else {
      tabContainer.style.left = "auto";
    }
    this.Mc(tabIndex, tabContainer);
    this.Jc(this.O.activeGroup === this.P, editor, tabContainer, tabActionBar);
  }
  Ic(editor, tabIndex, tabContainer, tabLabelWidget, tabLabel) {
    const options3 = this.O.partOptions;
    let name;
    let forceLabel = false;
    let fileDecorationBadges = Boolean(options3.decorations?.badges);
    const fileDecorationColors = Boolean(options3.decorations?.colors);
    let description;
    if (options3.pinnedTabSizing === "compact" && this.Q.isSticky(tabIndex)) {
      const isShowingIcons = options3.showIcons && options3.hasIcons;
      name = isShowingIcons ? "" : tabLabel.name?.charAt(0).toUpperCase();
      description = "";
      forceLabel = true;
      fileDecorationBadges = false;
    } else {
      name = tabLabel.name;
      description = tabLabel.description || "";
    }
    if (tabLabel.ariaLabel) {
      tabContainer.setAttribute("aria-label", tabLabel.ariaLabel);
      tabContainer.setAttribute("aria-description", "");
    }
    tabLabelWidget.setResource({ name, description, resource: $mL.getOriginalUri(editor, { supportSideBySide: SideBySideEditor.BOTH }) }, {
      title: this.vb(editor),
      extraClasses: $Mb(["tab-label", fileDecorationBadges ? "tab-label-has-badge" : void 0].concat(editor.getLabelExtraClasses())),
      italic: !this.Q.isPinned(editor),
      forceLabel,
      fileDecorations: {
        colors: fileDecorationColors,
        badges: fileDecorationBadges
      },
      icon: editor.getIcon(),
      hideIcon: options3.showIcons === false
    });
    const resource = $mL.getOriginalUri(editor, { supportSideBySide: SideBySideEditor.PRIMARY });
    if (resource) {
      tabContainer.setAttribute("data-resource-name", $rh(resource));
    } else {
      tabContainer.removeAttribute("data-resource-name");
    }
  }
  Jc(isGroupActive, editor, tabContainer, tabActionBar) {
    const isTabActive = this.Q.isActive(editor);
    const hasModifiedBorderTop = this.Lc(isGroupActive, isTabActive, editor, tabContainer);
    this.Kc(isGroupActive, !hasModifiedBorderTop, editor, tabContainer, tabActionBar);
  }
  Kc(isGroupActive, allowBorderTop, editor, tabContainer, tabActionBar) {
    const isActive2 = this.Q.isActive(editor);
    const isSelected = this.Q.isSelected(editor);
    tabContainer.classList.toggle("active", isActive2);
    tabContainer.classList.toggle("selected", isSelected);
    tabContainer.setAttribute("aria-selected", isActive2 ? "true" : "false");
    tabContainer.tabIndex = isActive2 ? 0 : -1;
    tabActionBar.setFocusable(isActive2);
    if (isActive2) {
      const activeTabBorderColorBottom = this.z(isGroupActive ? $gmb : $hmb);
      tabContainer.classList.toggle("tab-border-bottom", !!activeTabBorderColorBottom);
      tabContainer.style.setProperty("--tab-border-bottom-color", activeTabBorderColorBottom ?? "");
    }
    let tabBorderColorTop = null;
    if (allowBorderTop) {
      if (isActive2) {
        tabBorderColorTop = this.z(isGroupActive ? $imb : $jmb);
      }
      if (tabBorderColorTop === null && isSelected) {
        tabBorderColorTop = this.z($kmb);
      }
    }
    tabContainer.classList.toggle("tab-border-top", !!tabBorderColorTop);
    tabContainer.style.setProperty("--tab-border-top-color", tabBorderColorTop ?? "");
  }
  Lc(isGroupActive, isTabActive, editor, tabContainer) {
    let hasModifiedBorderColor = false;
    if (editor.isDirty() && !editor.isSaving()) {
      tabContainer.classList.add("dirty");
      if (this.O.partOptions.highlightModifiedTabs) {
        let modifiedBorderColor;
        if (isGroupActive && isTabActive) {
          modifiedBorderColor = this.z($qmb);
        } else if (isGroupActive && !isTabActive) {
          modifiedBorderColor = this.z($rmb);
        } else if (!isGroupActive && isTabActive) {
          modifiedBorderColor = this.z($smb);
        } else {
          modifiedBorderColor = this.z($tmb);
        }
        if (modifiedBorderColor) {
          hasModifiedBorderColor = true;
          tabContainer.classList.add("dirty-border-top");
          tabContainer.style.setProperty("--tab-dirty-border-top-color", modifiedBorderColor);
        }
      } else {
        tabContainer.classList.remove("dirty-border-top");
        tabContainer.style.removeProperty("--tab-dirty-border-top-color");
      }
    } else {
      tabContainer.classList.remove("dirty", "dirty-border-top");
      tabContainer.style.removeProperty("--tab-dirty-border-top-color");
    }
    return hasModifiedBorderColor;
  }
  Mc(tabIndex, tabContainer) {
    const isTabSticky = this.Q.isSticky(tabIndex);
    const isTabLastSticky = isTabSticky && this.Q.stickyCount === tabIndex + 1;
    const showLastStickyTabBorderColor = this.Q.stickyCount !== this.Q.count;
    const borderRightColor = (isTabLastSticky && showLastStickyTabBorderColor ? this.z($fmb) : void 0) || this.z($emb) || this.z($ko);
    tabContainer.style.borderRight = borderRightColor ? `1px solid ${borderRightColor}` : "";
    tabContainer.style.outlineColor = this.z($lo) || "";
  }
  hb(editorActions) {
    const isGroupActive = this.O.activeGroup === this.P;
    if (isGroupActive) {
      return editorActions;
    } else {
      return {
        primary: this.O.partOptions.alwaysShowEditorActions ? editorActions.primary : editorActions.primary.filter((action) => action.id === $Iub),
        secondary: editorActions.secondary
      };
    }
  }
  getHeight() {
    if (this.Ob.used) {
      return this.Ob.used.height;
    } else {
      return this.Oc();
    }
  }
  Oc() {
    let height;
    if (!this.Uc) {
      height = 0;
    } else if (this.O.partOptions.wrapTabs && this.Db?.classList.contains("wrapping")) {
      height = this.Db.offsetHeight;
    } else {
      height = this.ub;
    }
    return height;
  }
  layout(dimensions, options3) {
    Object.assign(this.Ob, dimensions);
    if (this.Uc) {
      if (!this.Pb.value) {
        const disposable = $jj(getWindow(this.M), () => {
          this.Pc(
            this.Ob,
            this.Pb.value?.options
            /* ensure to pick up latest options */
          );
          this.Pb.clear();
        });
        this.Pb.value = { options: options3, dispose: () => disposable.dispose() };
      }
      if (options3?.forceRevealActiveTab) {
        this.Pb.value.options = {
          ...this.Pb.value.options,
          forceRevealActiveTab: true
        };
      }
    }
    if (!this.Ob.used) {
      this.Ob.used = new $rj(dimensions.container.width, this.Oc());
    }
    return this.Ob.used;
  }
  Pc(dimensions, options3) {
    if (dimensions.container !== $rj.None && dimensions.available !== $rj.None) {
      this.Qc(dimensions, options3);
    }
    const oldDimension = this.Ob.used;
    const newDimension = this.Ob.used = new $rj(dimensions.container.width, this.Oc());
    if (oldDimension && oldDimension.height !== newDimension.height) {
      this.P.relayout();
    }
  }
  Qc(dimensions, options3) {
    const tabsWrapMultiLine = this.Rc(dimensions);
    if (!tabsWrapMultiLine) {
      this.Sc(options3);
    }
  }
  Rc(dimensions) {
    const [tabsAndActionsContainer, tabsContainer, editorToolbarContainer, tabsScrollbar] = $Lg(this.Db, this.Eb, this.g, this.Fb);
    const didTabsWrapMultiLine = tabsAndActionsContainer.classList.contains("wrapping");
    let tabsWrapMultiLine = didTabsWrapMultiLine;
    function updateTabsWrapping(enabled) {
      tabsWrapMultiLine = enabled;
      tabsAndActionsContainer.classList.toggle("wrapping", tabsWrapMultiLine);
      tabsContainer.style.setProperty("--last-tab-margin-right", tabsWrapMultiLine ? `${editorToolbarContainer.offsetWidth}px` : "0");
      for (const tab of tabsContainer.children) {
        tab.classList.remove("last-in-row");
      }
    }
    if (this.O.partOptions.wrapTabs) {
      const visibleTabsWidth = tabsContainer.offsetWidth;
      const allTabsWidth = tabsContainer.scrollWidth;
      const lastTabFitsWrapped = () => {
        const lastTab = this.Xc();
        if (!lastTab) {
          return true;
        }
        const lastTabOverlapWithToolbarWidth = lastTab.offsetWidth + editorToolbarContainer.offsetWidth - dimensions.available.width;
        if (lastTabOverlapWithToolbarWidth > 1) {
          return false;
        }
        return true;
      };
      if (tabsWrapMultiLine || allTabsWidth > visibleTabsWidth && lastTabFitsWrapped()) {
        updateTabsWrapping(true);
      }
      if (tabsWrapMultiLine) {
        if (tabsContainer.offsetHeight > dimensions.available.height || // if height exceeds available height
        allTabsWidth === visibleTabsWidth && tabsContainer.offsetHeight === this.ub || // if wrapping is not needed anymore
        !lastTabFitsWrapped()) {
          updateTabsWrapping(false);
        }
      }
    } else if (didTabsWrapMultiLine) {
      updateTabsWrapping(false);
    }
    if (tabsWrapMultiLine && !didTabsWrapMultiLine) {
      const visibleTabsWidth = tabsContainer.offsetWidth;
      tabsScrollbar.setScrollDimensions({
        width: visibleTabsWidth,
        scrollWidth: visibleTabsWidth
      });
    }
    if (tabsWrapMultiLine) {
      const tabs = /* @__PURE__ */ new Map();
      let currentTabsPosY = void 0;
      let lastTab = void 0;
      for (const child of tabsContainer.children) {
        const tab = child;
        const tabPosY = tab.offsetTop;
        if (tabPosY !== currentTabsPosY) {
          currentTabsPosY = tabPosY;
          if (lastTab) {
            tabs.set(lastTab, true);
          }
        }
        lastTab = tab;
        tabs.set(tab, false);
      }
      if (lastTab) {
        tabs.set(lastTab, true);
      }
      for (const [tab, lastInRow] of tabs) {
        tab.classList.toggle("last-in-row", lastInRow);
      }
    }
    return tabsWrapMultiLine;
  }
  Sc(options3) {
    const [tabsContainer, tabsScrollbar] = $Lg(this.Eb, this.Fb);
    const visibleTabsWidth = tabsContainer.offsetWidth;
    const allTabsWidth = tabsContainer.scrollWidth;
    let stickyTabsWidth = 0;
    if (this.Q.stickyCount > 0) {
      let stickyTabWidth = 0;
      switch (this.O.partOptions.pinnedTabSizing) {
        case "compact":
          stickyTabWidth = $Myb_1.yb.compact;
          break;
        case "shrink":
          stickyTabWidth = $Myb_1.yb.shrink;
          break;
      }
      stickyTabsWidth = this.Q.stickyCount * stickyTabWidth;
    }
    const activeTabAndIndex = this.Q.activeEditor ? this.Vc(this.Q.activeEditor) : void 0;
    const [activeTab, activeTabIndex] = activeTabAndIndex ?? [void 0, void 0];
    let activeTabPositionStatic = this.O.partOptions.pinnedTabSizing !== "normal" && typeof activeTabIndex === "number" && this.Q.isSticky(activeTabIndex);
    let availableTabsContainerWidth = visibleTabsWidth - stickyTabsWidth;
    if (this.Q.stickyCount > 0 && availableTabsContainerWidth < $Myb_1.yb.fit) {
      tabsContainer.classList.add("disable-sticky-tabs");
      availableTabsContainerWidth = visibleTabsWidth;
      stickyTabsWidth = 0;
      activeTabPositionStatic = false;
    } else {
      tabsContainer.classList.remove("disable-sticky-tabs");
    }
    let activeTabPosX;
    let activeTabWidth;
    if (!this.Qb && activeTab) {
      activeTabPosX = activeTab.offsetLeft;
      activeTabWidth = activeTab.offsetWidth;
    }
    const { width: oldVisibleTabsWidth, scrollWidth: oldAllTabsWidth } = tabsScrollbar.getScrollDimensions();
    tabsScrollbar.setScrollDimensions({
      width: visibleTabsWidth,
      scrollWidth: allTabsWidth
    });
    const dimensionsChanged = oldVisibleTabsWidth !== visibleTabsWidth || oldAllTabsWidth !== allTabsWidth;
    if (this.Qb || // explicitly disabled
    typeof activeTabPosX !== "number" || // invalid dimension
    typeof activeTabWidth !== "number" || // invalid dimension
    activeTabPositionStatic || // static tab (sticky)
    !dimensionsChanged && !options3?.forceRevealActiveTab) {
      this.Qb = false;
      return;
    }
    const tabsContainerScrollPosX = tabsScrollbar.getScrollPosition().scrollLeft;
    const activeTabFits = activeTabWidth <= availableTabsContainerWidth;
    const adjustedActiveTabPosX = activeTabPosX - stickyTabsWidth;
    if (activeTabFits && tabsContainerScrollPosX + availableTabsContainerWidth < adjustedActiveTabPosX + activeTabWidth) {
      tabsScrollbar.setScrollPosition({
        scrollLeft: tabsContainerScrollPosX + (adjustedActiveTabPosX + activeTabWidth - (tabsContainerScrollPosX + availableTabsContainerWidth))
      });
    } else if (tabsContainerScrollPosX > adjustedActiveTabPosX || !activeTabFits) {
      tabsScrollbar.setScrollPosition({
        scrollLeft: adjustedActiveTabPosX
      });
    }
  }
  Tc() {
    const tabsAndActionsContainer = $Kg(this.Db);
    tabsAndActionsContainer.classList.toggle("empty", !this.Uc);
    if (!this.Uc && this.Ob) {
      this.Ob.used = void 0;
    }
  }
  get Uc() {
    return this.Q.count > 0;
  }
  Vc(editor) {
    const tabIndex = this.Q.indexOf(editor);
    const tab = this.Wc(tabIndex);
    if (tab) {
      return [tab, tabIndex];
    }
    return void 0;
  }
  Wc(tabIndex) {
    if (tabIndex >= 0) {
      const tabsContainer = $Kg(this.Eb);
      return tabsContainer.children[tabIndex];
    }
    return void 0;
  }
  Xc() {
    return this.Wc(this.Q.count - 1);
  }
  Yc() {
    this.Qb = true;
  }
  Zc(e) {
    let element;
    if ($3j(e)) {
      element = e.target || e.srcElement;
    } else {
      element = e.initialTarget;
    }
    return !!$Gj(element, "action-item", "tab");
  }
  async $c(e, targetTabIndex, tabsContainer) {
    $9j.stop(e, true);
    this.uc(tabsContainer, false, e, targetTabIndex);
    tabsContainer.classList.remove("scroll");
    let targetEditorIndex = this.Q instanceof $Lyb ? targetTabIndex + this.P.stickyCount : targetTabIndex;
    const options3 = {
      sticky: this.Q instanceof $Kyb && this.Q.stickyCount === targetEditorIndex,
      index: targetEditorIndex
    };
    if (this.b.hasData($Bob.prototype)) {
      const data = this.b.getData($Bob.prototype);
      if (Array.isArray(data) && data.length > 0) {
        const sourceGroup = this.N.getGroup(data[0].identifier);
        if (sourceGroup) {
          const mergeGroupOptions = { index: targetEditorIndex };
          if (!this.pb(e, sourceGroup.id)) {
            mergeGroupOptions.mode = 0;
          }
          this.O.mergeGroup(sourceGroup, this.P, mergeGroupOptions);
        }
        this.P.focus();
        this.b.clearData($Bob.prototype);
      }
    } else if (this.a.hasData($Aob.prototype)) {
      const data = this.a.getData($Aob.prototype);
      if (Array.isArray(data) && data.length > 0) {
        const sourceGroup = this.N.getGroup(data[0].identifier.groupId);
        if (sourceGroup) {
          for (const de of data) {
            const editor = de.identifier.editor;
            if (sourceGroup.id !== de.identifier.groupId) {
              continue;
            }
            const sourceEditorIndex = sourceGroup.getIndexOfEditor(editor);
            if (sourceGroup === this.P && sourceEditorIndex < targetEditorIndex) {
              targetEditorIndex--;
            }
            if (this.pb(e, de.identifier.groupId, editor)) {
              sourceGroup.moveEditor(editor, this.P, { ...options3, index: targetEditorIndex });
            } else {
              sourceGroup.copyEditor(editor, this.P, { ...options3, index: targetEditorIndex });
            }
            targetEditorIndex++;
          }
        }
      }
      this.P.focus();
      this.a.clearData($Aob.prototype);
    } else if (this.c.hasData($Tfb.prototype)) {
      const data = this.c.getData($Tfb.prototype);
      if (Array.isArray(data) && data.length > 0) {
        const editors = [];
        for (const id2 of data) {
          const dataTransferItem = await this.Wb.removeDragOperationTransfer(id2.identifier);
          if (dataTransferItem) {
            const treeDropData = await $Cob(dataTransferItem);
            editors.push(...treeDropData.map((editor) => ({ ...editor, options: { ...editor.options, pinned: true, index: targetEditorIndex } })));
          }
        }
        this.Ub.openEditors(editors, this.P, { validateTrust: true });
      }
      this.c.clearData($Tfb.prototype);
    } else {
      const dropHandler = this.S.createInstance($Dob, { allowWorkspaceOpen: false });
      dropHandler.handleDrop(e, getWindow(this.M), () => this.P, () => this.P.focus(), options3);
    }
  }
  dispose() {
    super.dispose();
    this.Nb = $Xc(this.Nb);
  }
};
$Myb = $Myb_1 = __decorate([
  __param(5, $50),
  __param(6, $Pk),
  __param(7, $on),
  __param(8, $Ty),
  __param(9, $PJ),
  __param(10, $1M),
  __param(11, $gs),
  __param(12, $mJ),
  __param(13, $aT),
  __param(14, $Ufb),
  __param(15, $4L),
  __param(16, $S4)
], $Myb);
$ms((theme, collector) => {
  const borderColor = theme.getColor($emb);
  if (borderColor) {
    collector.addRule(`
			.monaco-workbench .part.editor > .content .editor-group-container > .title > .tabs-and-actions-container.wrapping .tabs-container > .tab {
				border-bottom: 1px solid ${borderColor};
			}
		`);
  }
  const activeContrastBorderColor = theme.getColor($lo);
  if (activeContrastBorderColor) {
    collector.addRule(`
			.monaco-workbench .part.editor > .content .editor-group-container.active > .title .tabs-container > .tab.active,
			.monaco-workbench .part.editor > .content .editor-group-container.active > .title .tabs-container > .tab.active:hover  {
				outline: 1px solid;
				outline-offset: -5px;
			}

			.monaco-workbench .part.editor > .content .editor-group-container > .title .tabs-container > .tab.selected:not(.active):not(:hover)  {
				outline: 1px dotted;
				outline-offset: -5px;
			}

			.monaco-workbench .part.editor > .content .editor-group-container.active > .title .tabs-container > .tab.active:focus {
				outline-style: dashed;
			}

			.monaco-workbench .part.editor > .content .editor-group-container > .title .tabs-container > .tab.active {
				outline: 1px dotted;
				outline-offset: -5px;
			}

			.monaco-workbench .part.editor > .content .editor-group-container > .title .tabs-container > .tab:hover  {
				outline: 1px dashed;
				outline-offset: -5px;
			}

			.monaco-workbench .part.editor > .content .editor-group-container > .title .tabs-container > .tab.active > .tab-actions .action-label,
			.monaco-workbench .part.editor > .content .editor-group-container > .title .tabs-container > .tab.active:hover > .tab-actions .action-label,
			.monaco-workbench .part.editor > .content .editor-group-container > .title .tabs-container > .tab.dirty > .tab-actions .action-label,
			.monaco-workbench .part.editor > .content .editor-group-container > .title .tabs-container > .tab.sticky > .tab-actions .action-label,
			.monaco-workbench .part.editor > .content .editor-group-container > .title .tabs-container > .tab:hover > .tab-actions .action-label {
				opacity: 1 !important;
			}
		`);
  }
  const contrastBorderColor = theme.getColor($ko);
  if (contrastBorderColor) {
    collector.addRule(`
			.monaco-workbench .part.editor > .content .editor-group-container > .title .editor-actions {
				outline: 1px solid ${contrastBorderColor}
			}
		`);
  }
  const tabHoverBackground = theme.getColor($amb);
  if (tabHoverBackground) {
    collector.addRule(`
			.monaco-workbench .part.editor > .content .editor-group-container.active > .title .tabs-container > .tab:not(.selected):hover {
				background-color: ${tabHoverBackground} !important;
			}
		`);
  }
  const tabUnfocusedHoverBackground = theme.getColor($bmb);
  if (tabUnfocusedHoverBackground) {
    collector.addRule(`
			.monaco-workbench .part.editor > .content .editor-group-container > .title .tabs-container > .tab:not(.selected):hover  {
				background-color: ${tabUnfocusedHoverBackground} !important;
			}
		`);
  }
  const tabHoverForeground = theme.getColor($cmb);
  if (tabHoverForeground) {
    collector.addRule(`
			.monaco-workbench .part.editor > .content .editor-group-container.active > .title .tabs-container > .tab:not(.selected):hover  {
				color: ${tabHoverForeground} !important;
			}
		`);
  }
  const tabUnfocusedHoverForeground = theme.getColor($dmb);
  if (tabUnfocusedHoverForeground) {
    collector.addRule(`
			.monaco-workbench .part.editor > .content .editor-group-container > .title .tabs-container > .tab:not(.selected):hover  {
				color: ${tabUnfocusedHoverForeground} !important;
			}
		`);
  }
  const tabHoverBorder = theme.getColor($nmb);
  if (tabHoverBorder) {
    collector.addRule(`
			.monaco-workbench .part.editor > .content .editor-group-container.active > .title .tabs-container > .tab:hover > .tab-border-bottom-container {
				display: block;
				position: absolute;
				left: 0;
				pointer-events: none;
				width: 100%;
				z-index: 10;
				bottom: 0;
				height: 1px;
				background-color: ${tabHoverBorder};
			}
		`);
  }
  const tabUnfocusedHoverBorder = theme.getColor($omb);
  if (tabUnfocusedHoverBorder) {
    collector.addRule(`
			.monaco-workbench .part.editor > .content .editor-group-container > .title .tabs-container > .tab:hover > .tab-border-bottom-container  {
				display: block;
				position: absolute;
				left: 0;
				pointer-events: none;
				width: 100%;
				z-index: 10;
				bottom: 0;
				height: 1px;
				background-color: ${tabUnfocusedHoverBorder};
			}
		`);
  }
  if (!$es(theme.type) && !$Xe && !activeContrastBorderColor) {
    const workbenchBackground = $4lb(theme);
    const editorBackgroundColor = theme.getColor($Ko);
    const editorGroupHeaderTabsBackground = theme.getColor($xmb);
    const editorDragAndDropBackground = theme.getColor($Cmb);
    let adjustedTabBackground;
    if (editorGroupHeaderTabsBackground && editorBackgroundColor) {
      adjustedTabBackground = editorGroupHeaderTabsBackground.flatten(editorBackgroundColor, editorBackgroundColor, workbenchBackground);
    }
    let adjustedTabDragBackground;
    if (editorGroupHeaderTabsBackground && editorBackgroundColor && editorDragAndDropBackground && editorBackgroundColor) {
      adjustedTabDragBackground = editorGroupHeaderTabsBackground.flatten(editorBackgroundColor, editorDragAndDropBackground, editorBackgroundColor, workbenchBackground);
    }
    const makeTabHoverBackgroundRule = (color2, colorDrag, hasFocus = false) => `
			.monaco-workbench .part.editor > .content:not(.dragged-over) .editor-group-container${hasFocus ? ".active" : ""} > .title .tabs-container > .tab.sizing-shrink:not(.dragged):not(.sticky-compact):hover > .tab-label > .monaco-icon-label-container::after,
			.monaco-workbench .part.editor > .content:not(.dragged-over) .editor-group-container${hasFocus ? ".active" : ""} > .title .tabs-container > .tab.sizing-fixed:not(.dragged):not(.sticky-compact):hover > .tab-label > .monaco-icon-label-container::after {
				background: linear-gradient(to left, ${color2}, transparent) !important;
			}

			.monaco-workbench .part.editor > .content.dragged-over .editor-group-container${hasFocus ? ".active" : ""} > .title .tabs-container > .tab.sizing-shrink:not(.dragged):not(.sticky-compact):hover > .tab-label > .monaco-icon-label-container::after,
			.monaco-workbench .part.editor > .content.dragged-over .editor-group-container${hasFocus ? ".active" : ""} > .title .tabs-container > .tab.sizing-fixed:not(.dragged):not(.sticky-compact):hover > .tab-label > .monaco-icon-label-container::after {
				background: linear-gradient(to left, ${colorDrag}, transparent) !important;
			}
		`;
    if (tabHoverBackground && adjustedTabBackground && adjustedTabDragBackground) {
      const adjustedColor = tabHoverBackground.flatten(adjustedTabBackground);
      const adjustedColorDrag = tabHoverBackground.flatten(adjustedTabDragBackground);
      collector.addRule(makeTabHoverBackgroundRule(adjustedColor, adjustedColorDrag, true));
    }
    if (tabUnfocusedHoverBackground && adjustedTabBackground && adjustedTabDragBackground) {
      const adjustedColor = tabUnfocusedHoverBackground.flatten(adjustedTabBackground);
      const adjustedColorDrag = tabUnfocusedHoverBackground.flatten(adjustedTabDragBackground);
      collector.addRule(makeTabHoverBackgroundRule(adjustedColor, adjustedColorDrag));
    }
    if (editorDragAndDropBackground && adjustedTabDragBackground) {
      const adjustedColorDrag = editorDragAndDropBackground.flatten(adjustedTabDragBackground);
      collector.addRule(`
				.monaco-workbench .part.editor > .content.dragged-over .editor-group-container.active > .title .tabs-container > .tab.sizing-shrink.dragged-over:not(.active):not(.dragged):not(.sticky-compact) > .tab-label > .monaco-icon-label-container::after,
				.monaco-workbench .part.editor > .content.dragged-over .editor-group-container:not(.active) > .title .tabs-container > .tab.sizing-shrink.dragged-over:not(.dragged):not(.sticky-compact) > .tab-label > .monaco-icon-label-container::after,
				.monaco-workbench .part.editor > .content.dragged-over .editor-group-container.active > .title .tabs-container > .tab.sizing-fixed.dragged-over:not(.active):not(.dragged):not(.sticky-compact) > .tab-label > .monaco-icon-label-container::after,
				.monaco-workbench .part.editor > .content.dragged-over .editor-group-container:not(.active) > .title .tabs-container > .tab.sizing-fixed.dragged-over:not(.dragged):not(.sticky-compact) > .tab-label > .monaco-icon-label-container::after {
					background: linear-gradient(to left, ${adjustedColorDrag}, transparent) !important;
				}
		`);
    }
    const makeTabBackgroundRule = (color2, colorDrag, focused, active) => `
				.monaco-workbench .part.editor > .content:not(.dragged-over) .editor-group-container${focused ? ".active" : ":not(.active)"} > .title .tabs-container > .tab.sizing-shrink${active ? ".active" : ""}:not(.dragged):not(.sticky-compact) > .tab-label > .monaco-icon-label-container::after,
				.monaco-workbench .part.editor > .content:not(.dragged-over) .editor-group-container${focused ? ".active" : ":not(.active)"} > .title .tabs-container > .tab.sizing-fixed${active ? ".active" : ""}:not(.dragged):not(.sticky-compact) > .tab-label > .monaco-icon-label-container::after {
					background: linear-gradient(to left, ${color2}, transparent);
				}

				.monaco-workbench .part.editor > .content.dragged-over .editor-group-container${focused ? ".active" : ":not(.active)"} > .title .tabs-container > .tab.sizing-shrink${active ? ".active" : ""}:not(.dragged):not(.sticky-compact) > .tab-label > .monaco-icon-label-container::after,
				.monaco-workbench .part.editor > .content.dragged-over .editor-group-container${focused ? ".active" : ":not(.active)"} > .title .tabs-container > .tab.sizing-fixed${active ? ".active" : ""}:not(.dragged):not(.sticky-compact) > .tab-label > .monaco-icon-label-container::after {
					background: linear-gradient(to left, ${colorDrag}, transparent);
				}
		`;
    const tabActiveBackground = theme.getColor($5lb);
    if (tabActiveBackground && adjustedTabBackground && adjustedTabDragBackground) {
      const adjustedColor = tabActiveBackground.flatten(adjustedTabBackground);
      const adjustedColorDrag = tabActiveBackground.flatten(adjustedTabDragBackground);
      collector.addRule(makeTabBackgroundRule(adjustedColor, adjustedColorDrag, true, true));
    }
    const tabUnfocusedActiveBackground = theme.getColor($6lb);
    if (tabUnfocusedActiveBackground && adjustedTabBackground && adjustedTabDragBackground) {
      const adjustedColor = tabUnfocusedActiveBackground.flatten(adjustedTabBackground);
      const adjustedColorDrag = tabUnfocusedActiveBackground.flatten(adjustedTabDragBackground);
      collector.addRule(makeTabBackgroundRule(adjustedColor, adjustedColorDrag, false, true));
    }
    const tabInactiveBackground = theme.getColor($7lb);
    if (tabInactiveBackground && adjustedTabBackground && adjustedTabDragBackground) {
      const adjustedColor = tabInactiveBackground.flatten(adjustedTabBackground);
      const adjustedColorDrag = tabInactiveBackground.flatten(adjustedTabDragBackground);
      collector.addRule(makeTabBackgroundRule(adjustedColor, adjustedColorDrag, true, false));
    }
    const tabUnfocusedInactiveBackground = theme.getColor($8lb);
    if (tabUnfocusedInactiveBackground && adjustedTabBackground && adjustedTabDragBackground) {
      const adjustedColor = tabUnfocusedInactiveBackground.flatten(adjustedTabBackground);
      const adjustedColorDrag = tabUnfocusedInactiveBackground.flatten(adjustedTabDragBackground);
      collector.addRule(makeTabBackgroundRule(adjustedColor, adjustedColorDrag, false, false));
    }
  }
});

// out-build/vs/workbench/browser/parts/editor/singleEditorTabsControl.js
var $Nyb = class extends $Jyb {
  constructor() {
    super(...arguments);
    this.yb = /* @__PURE__ */ Object.create(null);
  }
  get Ab() {
    return this.zb?.control;
  }
  ab(parent) {
    super.ab(parent);
    const titleContainer = this.kb = parent;
    titleContainer.draggable = true;
    this.Cb(titleContainer);
    this.B($mZ.addTarget(titleContainer));
    const labelContainer = document.createElement("div");
    labelContainer.classList.add("label-container");
    titleContainer.appendChild(labelContainer);
    this.xb = this.B(this.S.createInstance($msb, labelContainer, {})).element;
    this.B($_i(this.xb.element, $7j.CLICK, (e) => this.Db(e)));
    this.zb = this.B(this.S.createInstance($Hyb, labelContainer, this.P, {
      showFileIcons: false,
      showSymbolIcons: true,
      showDecorationColors: false,
      widgetStyles: { ...$G$, breadcrumbsBackground: $Vn.transparent.toString() },
      showPlaceholder: false
    }));
    this.B(this.zb.onDidEnablementChange(() => this.Ib()));
    titleContainer.classList.toggle("breadcrumbs", Boolean(this.Ab));
    this.B($1c(() => titleContainer.classList.remove("breadcrumbs")));
    this.cb(titleContainer, ["title-actions"]);
    return titleContainer;
  }
  Cb(titleContainer) {
    let lastDragEvent = void 0;
    let isNewWindowOperation = false;
    this.B(new $Ak(titleContainer, {
      onDragStart: (e) => {
        isNewWindowOperation = this.lb(e, titleContainer);
      },
      onDrag: (e) => {
        lastDragEvent = e;
      },
      onDragEnd: (e) => {
        this.mb(e, lastDragEvent, titleContainer, isNewWindowOperation);
      }
    }));
    this.B($_i(titleContainer, $7j.DBLCLICK, (e) => this.Eb(e)));
    this.B($_i(titleContainer, $7j.AUXCLICK, (e) => this.Fb(e)));
    this.B($_i(titleContainer, EventType.Tap, (e) => this.Gb(e)));
    for (const event of [$7j.CONTEXT_MENU, EventType.Contextmenu]) {
      this.B($_i(titleContainer, event, (e) => {
        if (this.Q.activeEditor) {
          this.rb(this.Q.activeEditor, e, titleContainer);
        }
      }));
    }
  }
  Db(e) {
    $9j.stop(e, false);
    setTimeout(() => this.Y.quickAccess.show());
  }
  Eb(e) {
    $9j.stop(e);
    this.P.pinEditor();
  }
  Fb(e) {
    if (e.button === 1 && this.Q.activeEditor) {
      $9j.stop(
        e,
        true
        /* for https://github.com/microsoft/vscode/issues/56715 */
      );
      if (!$lL(this.Q, this.Q.activeEditor, EditorCloseMethod.MOUSE, this.O.partOptions)) {
        this.P.closeEditor(this.Q.activeEditor);
      }
    }
  }
  Gb(e) {
    const target = e.initialTarget;
    if (!$Uj(target) || !this.xb || !$Dj(target, this.xb.element)) {
      return;
    }
    setTimeout(() => this.Y.quickAccess.show(), 50);
  }
  openEditor(editor) {
    return this.Hb();
  }
  openEditors(editors) {
    return this.Hb();
  }
  Hb() {
    const activeEditorChanged = this.Jb(() => this.Mb());
    if (!activeEditorChanged) {
      this.Kb(() => this.Mb());
    }
    return activeEditorChanged;
  }
  beforeCloseEditor(editor) {
  }
  closeEditor(editor) {
    this.Jb(() => this.Mb());
  }
  closeEditors(editors) {
    this.Jb(() => this.Mb());
  }
  moveEditor(editor, fromIndex, targetIndex) {
    this.Jb(() => this.Mb());
  }
  pinEditor(editor) {
    this.Lb(editor, () => this.Mb());
  }
  stickEditor(editor) {
  }
  unstickEditor(editor) {
  }
  setActive(isActive2) {
    this.Mb();
  }
  updateEditorSelections() {
  }
  updateEditorLabel(editor) {
    this.Lb(editor, () => this.Mb());
  }
  updateEditorDirty(editor) {
    this.Lb(editor, () => {
      const titleContainer = $Kg(this.kb);
      if (editor.isDirty() && !editor.isSaving()) {
        titleContainer.classList.add("dirty");
      } else {
        titleContainer.classList.remove("dirty");
      }
    });
  }
  updateOptions(oldOptions, newOptions) {
    super.updateOptions(oldOptions, newOptions);
    if (oldOptions.labelFormat !== newOptions.labelFormat || !$Pv(oldOptions.decorations, newOptions.decorations)) {
      this.Mb();
    }
  }
  updateStyles() {
    this.Mb();
  }
  Ib() {
    const titleContainer = $Kg(this.kb);
    titleContainer.classList.toggle("breadcrumbs", Boolean(this.Ab));
    this.Mb();
  }
  Jb(fn) {
    if (!this.yb.editor && this.Q.activeEditor || // active editor changed from null => editor
    this.yb.editor && !this.Q.activeEditor || // active editor changed from editor => null
    (!this.yb.editor || !this.Q.isActive(this.yb.editor))) {
      fn();
      return true;
    }
    return false;
  }
  Kb(fn) {
    if (!this.yb.editor || !this.Q.activeEditor) {
      return;
    }
    if (this.yb.pinned !== this.Q.isPinned(this.Q.activeEditor)) {
      fn();
    }
  }
  Lb(editor, fn) {
    if (this.Q.isActive(editor)) {
      fn();
    }
  }
  Mb() {
    const editor = this.Q.activeEditor ?? void 0;
    const options3 = this.O.partOptions;
    const isEditorPinned = editor ? this.Q.isPinned(editor) : false;
    const isGroupActive = this.O.activeGroup === this.P;
    this.yb = { editor, pinned: isEditorPinned };
    if (this.Ab) {
      if (isGroupActive) {
        this.Ab.update();
        this.Ab.domNode.classList.toggle("preview", !isEditorPinned);
      } else {
        this.Ab.hide();
      }
    }
    const [titleContainer, editorLabel] = $Lg(this.kb, this.xb);
    if (!editor) {
      titleContainer.classList.remove("dirty");
      editorLabel.clear();
      this.jb();
    } else {
      this.updateEditorDirty(editor);
      const { labelFormat } = this.O.partOptions;
      let description;
      if (this.Ab && !this.Ab.isHidden()) {
        description = "";
      } else if (labelFormat === "default" && !isGroupActive) {
        description = "";
      } else {
        description = editor.getDescription(this.Nb(labelFormat)) || "";
      }
      editorLabel.setResource({
        resource: $mL.getOriginalUri(editor, { supportSideBySide: SideBySideEditor.BOTH }),
        name: editor.getName(),
        description
      }, {
        title: this.vb(editor),
        italic: !isEditorPinned,
        extraClasses: ["single-tab", "title-label"].concat(editor.getLabelExtraClasses()),
        fileDecorations: {
          colors: Boolean(options3.decorations?.colors),
          badges: Boolean(options3.decorations?.badges)
        },
        icon: editor.getIcon(),
        hideIcon: options3.showIcons === false
      });
      if (isGroupActive) {
        titleContainer.style.color = this.z($9lb) || "";
      } else {
        titleContainer.style.color = this.z($$lb) || "";
      }
      this.gb();
    }
  }
  Nb(style) {
    switch (style) {
      case "short":
        return 0;
      case "long":
        return 2;
      default:
        return 1;
    }
  }
  hb(editorActions) {
    const isGroupActive = this.O.activeGroup === this.P;
    if (isGroupActive) {
      return editorActions;
    } else {
      return {
        primary: this.O.partOptions.alwaysShowEditorActions ? editorActions.primary : editorActions.primary.filter((action) => action.id === $xub || action.id === $Iub),
        secondary: editorActions.secondary
      };
    }
  }
  getHeight() {
    return this.ub;
  }
  layout(dimensions) {
    this.Ab?.layout(void 0);
    return new $rj(dimensions.container.width, this.getHeight());
  }
};

// out-build/vs/workbench/browser/parts/editor/multiRowEditorTabsControl.js
var $Oyb = class $Oyb2 extends $3c {
  constructor(f, editorPartsView, g, h3, j, m) {
    super();
    this.f = f;
    this.g = g;
    this.h = h3;
    this.j = j;
    this.m = m;
    const stickyModel = this.B(new $Kyb(this.j));
    const unstickyModel = this.B(new $Lyb(this.j));
    this.a = this.B(this.m.createInstance($Myb, this.f, editorPartsView, this.g, this.h, stickyModel));
    this.b = this.B(this.m.createInstance($Myb, this.f, editorPartsView, this.g, this.h, unstickyModel));
    this.n();
  }
  n() {
    this.c = this.j.activeEditor ? this.t(this.j.activeEditor) : void 0;
    this.r();
  }
  r() {
    if (this.h.count === 0) {
      return;
    }
    const hadTwoTabBars = this.f.classList.contains("two-tab-bars");
    const hasTwoTabBars = this.h.count !== this.h.stickyCount && this.h.stickyCount > 0;
    this.f.classList.toggle("two-tab-bars", hasTwoTabBars);
    if (hadTwoTabBars !== hasTwoTabBars) {
      this.h.relayout();
    }
  }
  s() {
    return this.c !== (this.j.activeEditor ? this.t(this.j.activeEditor) : void 0);
  }
  t(editor) {
    return this.j.isSticky(editor) ? this.a : this.b;
  }
  openEditor(editor, options3) {
    const didActiveControlChange = this.s();
    const didOpenEditorChange = this.t(editor).openEditor(editor, options3);
    const didChange = didOpenEditorChange || didActiveControlChange;
    if (didChange) {
      this.u();
    }
    return didChange;
  }
  openEditors(editors) {
    const stickyEditors = editors.filter((e) => this.j.isSticky(e));
    const unstickyEditors = editors.filter((e) => !this.j.isSticky(e));
    const didActiveControlChange = this.s();
    const didChangeOpenEditorsSticky = this.a.openEditors(stickyEditors);
    const didChangeOpenEditorsUnSticky = this.b.openEditors(unstickyEditors);
    const didChange = didChangeOpenEditorsSticky || didChangeOpenEditorsUnSticky || didActiveControlChange;
    if (didChange) {
      this.u();
    }
    return didChange;
  }
  u() {
    this.n();
  }
  beforeCloseEditor(editor) {
    this.t(editor).beforeCloseEditor(editor);
  }
  closeEditor(editor) {
    this.a.closeEditor(editor);
    this.b.closeEditor(editor);
    this.w();
  }
  closeEditors(editors) {
    const stickyEditors = editors.filter((e) => this.j.isSticky(e));
    const unstickyEditors = editors.filter((e) => !this.j.isSticky(e));
    this.a.closeEditors(stickyEditors);
    this.b.closeEditors(unstickyEditors);
    this.w();
  }
  w() {
    this.n();
  }
  moveEditor(editor, fromIndex, targetIndex, stickyStateChange) {
    if (stickyStateChange) {
      if (this.j.isSticky(editor)) {
        this.a.openEditor(editor);
        this.b.closeEditor(editor);
      } else {
        this.a.closeEditor(editor);
        this.b.openEditor(editor);
      }
      this.n();
    } else {
      if (this.j.isSticky(editor)) {
        this.a.moveEditor(editor, fromIndex, targetIndex, stickyStateChange);
      } else {
        this.b.moveEditor(editor, fromIndex - this.j.stickyCount, targetIndex - this.j.stickyCount, stickyStateChange);
      }
    }
  }
  pinEditor(editor) {
    this.t(editor).pinEditor(editor);
  }
  stickEditor(editor) {
    this.b.closeEditor(editor);
    this.a.openEditor(editor);
    this.n();
  }
  unstickEditor(editor) {
    this.a.closeEditor(editor);
    this.b.openEditor(editor);
    this.n();
  }
  setActive(isActive2) {
    this.a.setActive(isActive2);
    this.b.setActive(isActive2);
  }
  updateEditorSelections() {
    this.a.updateEditorSelections();
    this.b.updateEditorSelections();
  }
  updateEditorLabel(editor) {
    this.t(editor).updateEditorLabel(editor);
  }
  updateEditorDirty(editor) {
    this.t(editor).updateEditorDirty(editor);
  }
  updateOptions(oldOptions, newOptions) {
    this.a.updateOptions(oldOptions, newOptions);
    this.b.updateOptions(oldOptions, newOptions);
  }
  layout(dimensions) {
    const stickyDimensions = this.a.layout(dimensions);
    const unstickyAvailableDimensions = {
      container: dimensions.container,
      available: new $rj(dimensions.available.width, dimensions.available.height - stickyDimensions.height)
    };
    const unstickyDimensions = this.b.layout(unstickyAvailableDimensions);
    return new $rj(dimensions.container.width, stickyDimensions.height + unstickyDimensions.height);
  }
  getHeight() {
    return this.a.getHeight() + this.b.getHeight();
  }
  dispose() {
    this.f.classList.toggle("two-tab-bars", false);
    super.dispose();
  }
};
$Oyb = __decorate([
  __param(5, $Pk)
], $Oyb);

// out-build/vs/workbench/browser/parts/editor/noEditorTabsControl.js
var $Pyb = class extends $Jyb {
  constructor() {
    super(...arguments);
    this.kb = null;
  }
  hb(editorActions) {
    return {
      primary: [],
      secondary: []
    };
  }
  openEditor(editor) {
    return this.yb();
  }
  openEditors(editors) {
    return this.yb();
  }
  yb() {
    const didChange = this.zb();
    this.kb = this.Q.activeEditor;
    return didChange;
  }
  zb() {
    if (!this.kb && this.Q.activeEditor || // active editor changed from null => editor
    this.kb && !this.Q.activeEditor || // active editor changed from editor => null
    (!this.kb || !this.Q.isActive(this.kb))) {
      return true;
    }
    return false;
  }
  beforeCloseEditor(editor) {
  }
  closeEditor(editor) {
    this.Ab();
  }
  closeEditors(editors) {
    this.Ab();
  }
  Ab() {
    this.kb = this.Q.activeEditor;
  }
  moveEditor(editor, fromIndex, targetIndex) {
  }
  pinEditor(editor) {
  }
  stickEditor(editor) {
  }
  unstickEditor(editor) {
  }
  setActive(isActive2) {
  }
  updateEditorSelections() {
  }
  updateEditorLabel(editor) {
  }
  updateEditorDirty(editor) {
  }
  getHeight() {
    return 0;
  }
  layout(dimensions) {
    return new $rj(dimensions.container.width, this.getHeight());
  }
};

// out-build/vs/workbench/browser/parts/editor/editorTitleControl.js
var $Qyb = class $Qyb2 extends $ns {
  get g() {
    return this.c?.control;
  }
  constructor(j, m, r2, s, t, u, themeService) {
    super(themeService);
    this.j = j;
    this.m = m;
    this.r = r2;
    this.s = s;
    this.t = t;
    this.u = u;
    this.b = this.B(new $2c());
    this.f = this.B(new $2c());
    this.a = this.y();
    this.c = this.C();
  }
  y() {
    let tabsControlType;
    switch (this.r.partOptions.showTabs) {
      case "none":
        tabsControlType = $Pyb;
        break;
      case "single":
        tabsControlType = $Nyb;
        break;
      case "multiple":
      default:
        tabsControlType = this.r.partOptions.pinnedTabsOnSeparateRow ? $Oyb : $Myb;
        break;
    }
    const control = this.u.createInstance(tabsControlType, this.j, this.m, this.r, this.s, this.t);
    return this.b.add(control);
  }
  C() {
    if (this.r.partOptions.showTabs === "single") {
      return void 0;
    }
    const breadcrumbsContainer = document.createElement("div");
    breadcrumbsContainer.classList.add("breadcrumbs-below-tabs");
    this.j.appendChild(breadcrumbsContainer);
    const breadcrumbsControlFactory = this.f.add(this.u.createInstance($Hyb, breadcrumbsContainer, this.s, {
      showFileIcons: true,
      showSymbolIcons: true,
      showDecorationColors: false,
      showPlaceholder: true
    }));
    this.f.add(breadcrumbsControlFactory.onDidEnablementChange(() => this.s.relayout()));
    this.f.add(breadcrumbsControlFactory.onDidVisibilityChange(() => this.s.relayout()));
    return breadcrumbsControlFactory;
  }
  openEditor(editor, options3) {
    const didChange = this.a.openEditor(editor, options3);
    this.D(didChange);
  }
  openEditors(editors) {
    const didChange = this.a.openEditors(editors);
    this.D(didChange);
  }
  D(didChange) {
    if (didChange) {
      this.g?.update();
    } else {
      this.g?.revealLast();
    }
  }
  beforeCloseEditor(editor) {
    return this.a.beforeCloseEditor(editor);
  }
  closeEditor(editor) {
    this.a.closeEditor(editor);
    this.F();
  }
  closeEditors(editors) {
    this.a.closeEditors(editors);
    this.F();
  }
  F() {
    if (!this.s.activeEditor) {
      this.g?.update();
    }
  }
  moveEditor(editor, fromIndex, targetIndex, stickyStateChange) {
    return this.a.moveEditor(editor, fromIndex, targetIndex, stickyStateChange);
  }
  pinEditor(editor) {
    return this.a.pinEditor(editor);
  }
  stickEditor(editor) {
    return this.a.stickEditor(editor);
  }
  unstickEditor(editor) {
    return this.a.unstickEditor(editor);
  }
  setActive(isActive2) {
    return this.a.setActive(isActive2);
  }
  updateEditorSelections() {
    this.a.updateEditorSelections();
  }
  updateEditorLabel(editor) {
    return this.a.updateEditorLabel(editor);
  }
  updateEditorDirty(editor) {
    return this.a.updateEditorDirty(editor);
  }
  updateOptions(oldOptions, newOptions) {
    if (oldOptions.showTabs !== newOptions.showTabs || newOptions.showTabs !== "single" && oldOptions.pinnedTabsOnSeparateRow !== newOptions.pinnedTabsOnSeparateRow) {
      this.b.clear();
      this.f.clear();
      $$i(this.j);
      this.a = this.y();
      this.c = this.C();
    } else {
      this.a.updateOptions(oldOptions, newOptions);
    }
  }
  layout(dimensions) {
    const tabsControlDimension = this.a.layout(dimensions);
    let breadcrumbsControlDimension = void 0;
    if (this.g?.isHidden() === false) {
      breadcrumbsControlDimension = new $rj(dimensions.container.width, $Gyb.HEIGHT);
      this.g.layout(breadcrumbsControlDimension);
    }
    return new $rj(dimensions.container.width, tabsControlDimension.height + (breadcrumbsControlDimension ? breadcrumbsControlDimension.height : 0));
  }
  getHeight() {
    const tabsControlHeight = this.a.getHeight();
    const breadcrumbsControlHeight = this.g?.isHidden() === false ? $Gyb.HEIGHT : 0;
    return {
      total: tabsControlHeight + breadcrumbsControlHeight,
      offset: tabsControlHeight
    };
  }
};
$Qyb = __decorate([
  __param(5, $Pk),
  __param(6, $gs)
], $Qyb);

// out-build/vs/workbench/browser/parts/editor/editorGroupView.js
var $Ryb_1;
var $Ryb = $Ryb_1 = class $Ryb2 extends $ns {
  //#region factory
  static createNew(editorPartsView, groupsView, groupsLabel, groupIndex, instantiationService, options3) {
    return instantiationService.createInstance($Ryb_1, null, editorPartsView, groupsView, groupsLabel, groupIndex, options3);
  }
  static createFromSerialized(serialized, editorPartsView, groupsView, groupsLabel, groupIndex, instantiationService, options3) {
    return instantiationService.createInstance($Ryb_1, serialized, editorPartsView, groupsView, groupsLabel, groupIndex, options3);
  }
  static createCopy(copyFrom, editorPartsView, groupsView, groupsLabel, groupIndex, instantiationService, options3) {
    return instantiationService.createInstance($Ryb_1, copyFrom, editorPartsView, groupsView, groupsLabel, groupIndex, options3);
  }
  constructor(from, P, groupsView, Q, R, options3, S, U, themeService, W, X, Y, Z, $149, ab, bb, cb, db, eb, fb, gb, hb) {
    super(themeService);
    this.P = P;
    this.groupsView = groupsView;
    this.Q = Q;
    this.R = R;
    this.S = S;
    this.U = U;
    this.W = W;
    this.X = X;
    this.Y = Y;
    this.Z = Z;
    this.$ = $149;
    this.ab = ab;
    this.bb = bb;
    this.cb = cb;
    this.db = db;
    this.eb = eb;
    this.fb = fb;
    this.gb = gb;
    this.hb = hb;
    this.a = this.B(new $ze());
    this.onDidFocus = this.a.event;
    this.b = this.B(new $ze());
    this.onWillDispose = this.b.event;
    this.c = this.B(new $ze());
    this.onDidModelChange = this.c.event;
    this.f = this.B(new $ze());
    this.onDidActiveEditorChange = this.f.event;
    this.g = this.B(new $ze());
    this.onDidOpenEditorFail = this.g.event;
    this.j = this.B(new $ze());
    this.onWillCloseEditor = this.j.event;
    this.m = this.B(new $ze());
    this.onDidCloseEditor = this.m.event;
    this.r = this.B(new $ze());
    this.onWillMoveEditor = this.r.event;
    this.s = this.B(new $ze());
    this.onWillOpenEditor = this.s.event;
    this.L = this.B(new $0h((editors) => this.zb(editors), 0));
    this.M = /* @__PURE__ */ new Map();
    this.N = this.B(new $4c());
    this.O = new $gi();
    this.whenRestored = this.O.p;
    this.Hb = false;
    this.element = document.createElement("div");
    this.Yb = this.B(new $Ie());
    this.onDidChange = this.Yb.event;
    if (from instanceof $Ryb_1) {
      this.t = this.B(from.t.clone());
    } else if ($4I(from)) {
      this.t = this.B(S.createInstance($9I, from));
    } else {
      this.t = this.B(S.createInstance($9I, void 0));
    }
    {
      this.scopedContextKeyService = this.B(this.U.createScoped(this.element));
      this.element.classList.add(...$Mb(["editor-group-container", this.t.isLocked ? "locked" : void 0]));
      this.jb();
      this.kb();
      this.lb();
      this.B(this.S.createInstance($uyb, this.element));
      this.H = this.B(new $02(this.element, $s$));
      this.H.hide();
      this.C = this.B(this.S.createChild(new $Ok([$on, this.scopedContextKeyService], [$ZJ, this.B(new $4ob(this.H, this))])));
      this.D = this.B(this.C.createInstance($lqb));
      this.ib();
      this.F = document.createElement("div");
      this.F.classList.add("title");
      this.element.appendChild(this.F);
      this.G = this.B(this.C.createInstance($Qyb, this.F, this.P, this.groupsView, this, this.t));
      this.I = document.createElement("div");
      this.I.classList.add("editor-container");
      this.element.appendChild(this.I);
      this.J = this.B(this.C.createInstance($tyb, this.element, this.I, this));
      this.Yb.input = this.J.onDidChangeSizeConstraints;
      this.nb();
      this.pb();
      this.ob();
      this.updateStyles();
    }
    const restoreEditorsPromise = this.qb(from, options3) ?? Promise.resolve();
    restoreEditorsPromise.finally(() => {
      this.O.complete();
    });
    this.rb();
  }
  ib() {
    const groupActiveEditorDirtyContext = this.P.bind($tpb, this);
    const groupActiveEditorPinnedContext = this.P.bind($upb, this);
    const groupActiveEditorFirstContext = this.P.bind($vpb, this);
    const groupActiveEditorLastContext = this.P.bind($wpb, this);
    const groupActiveEditorStickyContext = this.P.bind($xpb, this);
    const groupEditorsCountContext = this.P.bind($Ipb, this);
    const groupLockedContext = this.P.bind($Mpb, this);
    const multipleEditorsSelectedContext = $Ppb.bindTo(this.scopedContextKeyService);
    const twoEditorsSelectedContext = $Qpb.bindTo(this.scopedContextKeyService);
    const selectedEditorsHaveFileOrUntitledResourceContext = $Rpb.bindTo(this.scopedContextKeyService);
    const groupActiveEditorContext = this.P.bind($Dpb, this);
    const groupActiveEditorIsReadonly = this.P.bind($ypb, this);
    const groupActiveEditorCanRevert = this.P.bind($Bpb, this);
    const groupActiveEditorCanToggleReadonly = this.P.bind($Apb, this);
    const groupActiveCompareEditorCanSwap = this.P.bind($zpb, this);
    const groupTextCompareEditorVisibleContext = this.P.bind($Fpb, this);
    const groupTextCompareEditorActiveContext = this.P.bind($Gpb, this);
    const groupActiveEditorAvailableEditorIds = this.P.bind($Epb, this);
    const groupActiveEditorCanSplitInGroupContext = this.P.bind($Cpb, this);
    const groupActiveEditorIsSideBySideEditorContext = this.P.bind($Hpb, this);
    const activeEditorListener = this.B(new $4c());
    const observeActiveEditor = () => {
      activeEditorListener.clear();
      this.scopedContextKeyService.bufferChangeEvents(() => {
        const activeEditor = this.activeEditor;
        const activeEditorPane = this.activeEditorPane;
        this.D.set($mL.getOriginalUri(activeEditor, { supportSideBySide: SideBySideEditor.PRIMARY }));
        $mqb(groupActiveEditorAvailableEditorIds, activeEditor, this.eb);
        if (activeEditor) {
          groupActiveEditorCanSplitInGroupContext.set(activeEditor.hasCapability(
            32
            /* EditorInputCapabilities.CanSplitInGroup */
          ));
          groupActiveEditorIsSideBySideEditorContext.set(activeEditor.typeId === $1I.ID);
          groupActiveEditorDirtyContext.set(activeEditor.isDirty() && !activeEditor.isSaving());
          activeEditorListener.value = activeEditor.onDidChangeDirty(() => {
            groupActiveEditorDirtyContext.set(activeEditor.isDirty() && !activeEditor.isSaving());
          });
        } else {
          groupActiveEditorCanSplitInGroupContext.set(false);
          groupActiveEditorIsSideBySideEditorContext.set(false);
          groupActiveEditorDirtyContext.set(false);
        }
        if (activeEditorPane) {
          groupActiveEditorContext.set(activeEditorPane.getId());
          groupActiveEditorCanRevert.set(!activeEditorPane.input.hasCapability(
            4
            /* EditorInputCapabilities.Untitled */
          ));
          groupActiveEditorIsReadonly.set(!!activeEditorPane.input.isReadonly());
          const primaryEditorResource = $mL.getOriginalUri(activeEditorPane.input, { supportSideBySide: SideBySideEditor.PRIMARY });
          const secondaryEditorResource = $mL.getOriginalUri(activeEditorPane.input, { supportSideBySide: SideBySideEditor.SECONDARY });
          groupActiveCompareEditorCanSwap.set(activeEditorPane.input instanceof $fub && !activeEditorPane.input.original.isReadonly() && !!primaryEditorResource && (this.hb.hasProvider(primaryEditorResource) || primaryEditorResource.scheme === Schemas.untitled) && !!secondaryEditorResource && (this.hb.hasProvider(secondaryEditorResource) || secondaryEditorResource.scheme === Schemas.untitled));
          groupActiveEditorCanToggleReadonly.set(!!primaryEditorResource && this.hb.hasProvider(primaryEditorResource) && !this.hb.hasCapability(
            primaryEditorResource,
            2048
            /* FileSystemProviderCapabilities.Readonly */
          ));
          const activePaneDiffEditor = activeEditorPane?.getId() === $3K;
          groupTextCompareEditorActiveContext.set(activePaneDiffEditor);
          groupTextCompareEditorVisibleContext.set(activePaneDiffEditor);
        } else {
          groupActiveEditorContext.reset();
          groupActiveEditorCanRevert.reset();
          groupActiveEditorIsReadonly.reset();
          groupActiveCompareEditorCanSwap.reset();
          groupActiveEditorCanToggleReadonly.reset();
        }
      });
    };
    const updateGroupContextKeys = (e) => {
      switch (e.kind) {
        case 3:
          groupLockedContext.set(this.isLocked);
          break;
        case 8:
          groupActiveEditorFirstContext.set(this.t.isFirst(this.t.activeEditor));
          groupActiveEditorLastContext.set(this.t.isLast(this.t.activeEditor));
          groupActiveEditorPinnedContext.set(this.t.activeEditor ? this.t.isPinned(this.t.activeEditor) : false);
          groupActiveEditorStickyContext.set(this.t.activeEditor ? this.t.isSticky(this.t.activeEditor) : false);
          break;
        case 6:
          groupActiveEditorPinnedContext.set(this.t.activeEditor ? this.t.isPinned(this.t.activeEditor) : false);
          groupActiveEditorStickyContext.set(this.t.activeEditor ? this.t.isSticky(this.t.activeEditor) : false);
        case 5:
        case 7:
          groupActiveEditorFirstContext.set(this.t.isFirst(this.t.activeEditor));
          groupActiveEditorLastContext.set(this.t.isLast(this.t.activeEditor));
          break;
        case 11:
          if (e.editor && e.editor === this.t.activeEditor) {
            groupActiveEditorPinnedContext.set(this.t.isPinned(this.t.activeEditor));
          }
          break;
        case 13:
          if (e.editor && e.editor === this.t.activeEditor) {
            groupActiveEditorStickyContext.set(this.t.isSticky(this.t.activeEditor));
          }
          break;
        case 4:
          multipleEditorsSelectedContext.set(this.t.selectedEditors.length > 1);
          twoEditorsSelectedContext.set(this.t.selectedEditors.length === 2);
          selectedEditorsHaveFileOrUntitledResourceContext.set(this.t.selectedEditors.every((e2) => e2.resource && (this.hb.hasProvider(e2.resource) || e2.resource.scheme === Schemas.untitled)));
          break;
      }
      groupEditorsCountContext.set(this.count);
    };
    this.B(this.onDidModelChange((e) => updateGroupContextKeys(e)));
    this.B(this.onDidActiveEditorChange(() => observeActiveEditor()));
    observeActiveEditor();
    updateGroupContextKeys({
      kind: 8
      /* GroupModelChangeKind.EDITOR_ACTIVE */
    });
    updateGroupContextKeys({
      kind: 3
      /* GroupModelChangeKind.GROUP_LOCKED */
    });
  }
  jb() {
    this.B($_i(this.element, $7j.DBLCLICK, (e) => {
      if (this.isEmpty) {
        $9j.stop(e);
        this.ab.openEditor({
          resource: void 0,
          options: {
            pinned: true,
            override: $1K.id
          }
        }, this.id);
      }
    }));
    this.B($_i(this.element, $7j.AUXCLICK, (e) => {
      if (this.isEmpty && e.button === 1) {
        $9j.stop(e, true);
        this.groupsView.removeGroup(this);
      }
    }));
  }
  kb() {
    const toolbarContainer = document.createElement("div");
    toolbarContainer.classList.add("editor-group-container-toolbar");
    this.element.appendChild(toolbarContainer);
    const containerToolbar = this.B(new $LZ(toolbarContainer, {
      ariaLabel: localize(3489, null),
      highlightToggledItems: true
    }));
    const containerToolbarMenu = this.B(this.Y.createMenu($bJ.EmptyEditorGroup, this.scopedContextKeyService));
    const updateContainerToolbar = () => {
      this.N.value = $1c(() => containerToolbar.clear());
      const actions = $Q$(containerToolbarMenu.getActions({ arg: { groupId: this.id }, shouldForwardArgs: true }), "navigation");
      for (const action of [...actions.primary, ...actions.secondary]) {
        const keybinding = this.X.lookupKeybinding(action.id);
        containerToolbar.push(action, { icon: true, label: false, keybinding: keybinding?.getLabel() });
      }
    };
    updateContainerToolbar();
    this.B(containerToolbarMenu.onDidChange(updateContainerToolbar));
  }
  lb() {
    this.B($_i(this.element, $7j.CONTEXT_MENU, (e) => this.mb(e)));
    this.B($_i(this.element, EventType.Contextmenu, () => this.mb()));
  }
  mb(e) {
    if (!this.isEmpty) {
      return;
    }
    let anchor = this.element;
    if (e) {
      anchor = new $lf(getWindow(this.element), e);
    }
    this.Z.showContextMenu({
      menuId: $bJ.EmptyEditorGroupContext,
      contextKeyService: this.U,
      getAnchor: () => anchor,
      onHide: () => {
        this.focus();
      }
    });
  }
  nb() {
    const containerFocusTracker = this.B($_j(this.element));
    this.B(containerFocusTracker.onDidFocus(() => {
      if (this.isEmpty) {
        this.a.fire();
      }
    }));
    const handleTitleClickOrTouch = (e) => {
      let target;
      if ($3j(e)) {
        if (e.button !== 0 || $m && e.ctrlKey) {
          return void 0;
        }
        target = e.target;
      } else {
        target = e.initialTarget;
      }
      if ($Gj(target, "monaco-action-bar", this.F) || $Gj(target, "monaco-breadcrumb-item", this.F)) {
        return;
      }
      setTimeout(() => {
        this.focus();
      });
    };
    this.B($_i(this.F, $7j.MOUSE_DOWN, (e) => handleTitleClickOrTouch(e)));
    this.B($_i(this.F, EventType.Tap, (e) => handleTitleClickOrTouch(e)));
    this.B(this.J.onDidFocus(() => {
      this.a.fire();
    }));
  }
  ob() {
    if (this.isEmpty) {
      this.element.classList.add("empty");
      this.element.tabIndex = 0;
      this.element.setAttribute("aria-label", localize(3490, null, this.ariaLabel));
    } else {
      this.element.classList.remove("empty");
      this.element.removeAttribute("tabIndex");
      this.element.removeAttribute("aria-label");
    }
    this.updateStyles();
  }
  pb() {
    this.F.classList.toggle("tabs", this.groupsView.partOptions.showTabs === "multiple");
    this.F.classList.toggle("show-file-icons", this.groupsView.partOptions.showIcons);
  }
  qb(from, groupViewOptions) {
    if (this.count === 0) {
      return;
    }
    let options3;
    if (from instanceof $Ryb_1) {
      options3 = $3ob(from);
    } else {
      options3 = /* @__PURE__ */ Object.create(null);
    }
    const activeEditor = this.t.activeEditor;
    if (!activeEditor) {
      return;
    }
    options3.pinned = this.t.isPinned(activeEditor);
    options3.sticky = this.t.isSticky(activeEditor);
    options3.preserveFocus = true;
    const internalOptions = {
      preserveWindowOrder: true,
      // handle window order after editor is restored
      skipTitleUpdate: true
      // update the title later for all editors at once
    };
    const activeElement = $Lj();
    const result = this.Kb(activeEditor, {
      active: true,
      isNew: false
      /* restored */
    }, options3, internalOptions).then(() => {
      if (this.groupsView.activeGroup === this && activeElement && $Mj(activeElement) && !groupViewOptions?.preserveFocus) {
        this.focus();
      }
    });
    this.G.openEditors(this.editors);
    return result;
  }
  //#region event handling
  rb() {
    this.B(this.t.onDidModelChange((e) => this.sb(e)));
    this.B(this.groupsView.onDidChangeEditorPartOptions((e) => this.Ab(e)));
    this.B(this.groupsView.onDidVisibilityChange((e) => this.Fb(e)));
    this.B(this.onDidFocus(() => this.Gb()));
  }
  sb(e) {
    this.c.fire(e);
    switch (e.kind) {
      case 3:
        this.element.classList.toggle("locked", this.isLocked);
        break;
      case 4:
        this.Eb();
        break;
    }
    if (!e.editor) {
      return;
    }
    switch (e.kind) {
      case 5:
        if ($6I(e)) {
          this.tb(e.editor, e.editorIndex);
        }
        break;
      case 6:
        if ($8I(e)) {
          this.ub(e.editor, e.editorIndex, e.context, e.sticky);
        }
        break;
      case 15:
        this.yb(e.editor);
        break;
      case 14:
        this.Bb(e.editor);
        break;
      case 12:
        this.Cb(e.editor);
        break;
      case 9:
        this.Db(e.editor);
        break;
    }
  }
  tb(editor, editorIndex) {
    this.W.publicLog("editorOpened", this.xb(editor));
    this.ob();
  }
  ub(editor, editorIndex, context, sticky) {
    this.j.fire({ groupId: this.id, editor, context, index: editorIndex, sticky });
    const editorsToClose = [editor];
    if (editor instanceof $1I) {
      editorsToClose.push(editor.primary, editor.secondary);
    }
    for (const editor2 of editorsToClose) {
      if (this.vb(editor2)) {
        editor2.dispose();
      }
    }
    this.W.publicLog("editorClosed", this.xb(editor));
    this.ob();
    this.m.fire({ groupId: this.id, editor, context, index: editorIndex, sticky });
  }
  vb(editor) {
    for (const groupView of this.P.groups) {
      if (groupView instanceof $Ryb_1 && groupView.t.contains(editor, {
        strictEquals: true,
        // only if this input is not shared across editor groups
        supportSideBySide: SideBySideEditor.ANY
        // include any side of an opened side by side editor
      })) {
        return false;
      }
    }
    return true;
  }
  wb(resource) {
    if (!resource) {
      return void 0;
    }
    const path = resource ? resource.scheme === Schemas.file ? resource.fsPath : resource.path : void 0;
    if (!path) {
      return void 0;
    }
    let resourceExt = $th(resource);
    const queryStringLocation = resourceExt.indexOf("?");
    resourceExt = queryStringLocation !== -1 ? resourceExt.substr(0, queryStringLocation) : resourceExt;
    return {
      mimeType: new $bw($Nsb(resource).join(", ")),
      scheme: resource.scheme,
      ext: resourceExt,
      path: $Xi(path)
    };
  }
  xb(editor) {
    const descriptor = editor.getTelemetryDescriptor();
    const resource = $mL.getOriginalUri(editor, { supportSideBySide: SideBySideEditor.BOTH });
    if (URI.isUri(resource)) {
      descriptor["resource"] = this.wb(resource);
      return descriptor;
    } else if (resource) {
      if (resource.primary) {
        descriptor["resource"] = this.wb(resource.primary);
      }
      if (resource.secondary) {
        descriptor["resourceSecondary"] = this.wb(resource.secondary);
      }
      return descriptor;
    }
    return descriptor;
  }
  yb(editor) {
    this.L.work(editor);
  }
  zb(disposedEditors) {
    let activeEditor;
    const inactiveEditors = [];
    for (const disposedEditor of disposedEditors) {
      const editorFindResult = this.t.findEditor(disposedEditor);
      if (!editorFindResult) {
        continue;
      }
      const editor = editorFindResult[0];
      if (!editor.isDisposed()) {
        continue;
      }
      if (this.t.isActive(editor)) {
        activeEditor = editor;
      } else {
        inactiveEditors.push(editor);
      }
    }
    for (const inactiveEditor of inactiveEditors) {
      this.Ob(inactiveEditor, true);
    }
    if (activeEditor) {
      this.Ob(activeEditor, true);
    }
  }
  Ab(event) {
    this.pb();
    this.G.updateOptions(event.oldPartOptions, event.newPartOptions);
    if (event.oldPartOptions.showTabs !== event.newPartOptions.showTabs || event.oldPartOptions.tabHeight !== event.newPartOptions.tabHeight || event.oldPartOptions.showTabs === "multiple" && event.oldPartOptions.pinnedTabsOnSeparateRow !== event.newPartOptions.pinnedTabsOnSeparateRow) {
      this.relayout();
      if (this.t.activeEditor) {
        this.G.openEditors(this.t.getEditors(
          1
          /* EditorsOrder.SEQUENTIAL */
        ));
      }
    }
    this.updateStyles();
    if (event.oldPartOptions.enablePreview && !event.newPartOptions.enablePreview) {
      if (this.t.previewEditor) {
        this.pinEditor(this.t.previewEditor);
      }
    }
  }
  Bb(editor) {
    this.pinEditor(editor);
    this.G.updateEditorDirty(editor);
  }
  Cb(editor) {
    const transient = this.t.isTransient(editor);
    if (!transient && !this.groupsView.partOptions.enablePreview) {
      this.pinEditor(editor);
    }
  }
  Db(editor) {
    this.G.updateEditorLabel(editor);
  }
  Eb() {
    this.G.updateEditorSelections();
  }
  Fb(visible) {
    this.J.setVisible(visible);
  }
  Gb() {
    if (this.activeEditor) {
      this.t.setTransient(this.activeEditor, false);
    }
  }
  //#endregion
  //#region IEditorGroupView
  get index() {
    return this.R;
  }
  get label() {
    if (this.Q) {
      return localize(3491, null, this.Q, this.R + 1);
    }
    return localize(3492, null, this.R + 1);
  }
  get ariaLabel() {
    if (this.Q) {
      return localize(3493, null, this.Q, this.R + 1);
    }
    return localize(3494, null, this.R + 1);
  }
  get disposed() {
    return this.Hb;
  }
  get isEmpty() {
    return this.count === 0;
  }
  get titleHeight() {
    return this.G.getHeight();
  }
  notifyIndexChanged(newIndex) {
    if (this.R !== newIndex) {
      this.R = newIndex;
      this.t.setIndex(newIndex);
    }
  }
  notifyLabelChanged(newLabel) {
    if (this.Q !== newLabel) {
      this.Q = newLabel;
      this.t.setLabel(newLabel);
    }
  }
  setActive(isActive2) {
    this.u = isActive2;
    if (!isActive2 && this.activeEditor && this.selectedEditors.length > 1) {
      this.setSelection(this.activeEditor, []);
    }
    this.element.classList.toggle("active", isActive2);
    this.element.classList.toggle("inactive", !isActive2);
    this.G.setActive(isActive2);
    this.updateStyles();
    this.t.setActive(
      void 0
      /* entire group got active */
    );
  }
  //#endregion
  //#region basics()
  get id() {
    return this.t.id;
  }
  get windowId() {
    return this.groupsView.windowId;
  }
  get editors() {
    return this.t.getEditors(
      1
      /* EditorsOrder.SEQUENTIAL */
    );
  }
  get count() {
    return this.t.count;
  }
  get stickyCount() {
    return this.t.stickyCount;
  }
  get activeEditorPane() {
    return this.J ? this.J.activeEditorPane ?? void 0 : void 0;
  }
  get activeEditor() {
    return this.t.activeEditor;
  }
  get selectedEditors() {
    return this.t.selectedEditors;
  }
  get previewEditor() {
    return this.t.previewEditor;
  }
  isPinned(editorOrIndex) {
    return this.t.isPinned(editorOrIndex);
  }
  isSticky(editorOrIndex) {
    return this.t.isSticky(editorOrIndex);
  }
  isSelected(editor) {
    return this.t.isSelected(editor);
  }
  isTransient(editorOrIndex) {
    return this.t.isTransient(editorOrIndex);
  }
  isActive(editor) {
    return this.t.isActive(editor);
  }
  async setSelection(activeSelectedEditor, inactiveSelectedEditors) {
    if (!this.isActive(activeSelectedEditor)) {
      await this.openEditor(activeSelectedEditor, { activation: EditorActivation.ACTIVATE }, { inactiveSelection: inactiveSelectedEditors });
    } else {
      this.t.setSelection(activeSelectedEditor, inactiveSelectedEditors);
    }
  }
  contains(candidate, options3) {
    return this.t.contains(candidate, options3);
  }
  getEditors(order, options3) {
    return this.t.getEditors(order, options3);
  }
  findEditors(resource, options3) {
    const canonicalResource = this.cb.asCanonicalUri(resource);
    return this.getEditors(
      1
      /* EditorsOrder.SEQUENTIAL */
    ).filter((editor) => {
      if (editor.resource && $oh(editor.resource, canonicalResource)) {
        return true;
      }
      if (options3?.supportSideBySide === SideBySideEditor.PRIMARY || options3?.supportSideBySide === SideBySideEditor.ANY) {
        const primaryResource = $mL.getCanonicalUri(editor, { supportSideBySide: SideBySideEditor.PRIMARY });
        if (primaryResource && $oh(primaryResource, canonicalResource)) {
          return true;
        }
      }
      if (options3?.supportSideBySide === SideBySideEditor.SECONDARY || options3?.supportSideBySide === SideBySideEditor.ANY) {
        const secondaryResource = $mL.getCanonicalUri(editor, { supportSideBySide: SideBySideEditor.SECONDARY });
        if (secondaryResource && $oh(secondaryResource, canonicalResource)) {
          return true;
        }
      }
      return false;
    });
  }
  getEditorByIndex(index) {
    return this.t.getEditorByIndex(index);
  }
  getIndexOfEditor(editor) {
    return this.t.indexOf(editor);
  }
  isFirst(editor) {
    return this.t.isFirst(editor);
  }
  isLast(editor) {
    return this.t.isLast(editor);
  }
  focus() {
    if (this.activeEditorPane) {
      this.activeEditorPane.focus();
    } else {
      this.element.focus();
    }
    this.a.fire();
  }
  pinEditor(candidate = this.activeEditor || void 0) {
    if (candidate && !this.t.isPinned(candidate)) {
      const editor = this.t.pin(candidate);
      if (editor) {
        this.G.pinEditor(editor);
      }
    }
  }
  stickEditor(candidate = this.activeEditor || void 0) {
    this.Ib(candidate, true);
  }
  unstickEditor(candidate = this.activeEditor || void 0) {
    this.Ib(candidate, false);
  }
  Ib(candidate, sticky) {
    if (candidate && this.t.isSticky(candidate) !== sticky) {
      const oldIndexOfEditor = this.getIndexOfEditor(candidate);
      const editor = sticky ? this.t.stick(candidate) : this.t.unstick(candidate);
      if (!editor) {
        return;
      }
      const newIndexOfEditor = this.getIndexOfEditor(editor);
      if (newIndexOfEditor !== oldIndexOfEditor) {
        this.G.moveEditor(editor, oldIndexOfEditor, newIndexOfEditor, true);
      }
      if (sticky) {
        this.G.stickEditor(editor);
      } else {
        this.G.unstickEditor(editor);
      }
    }
  }
  //#endregion
  //#region openEditor()
  async openEditor(editor, options3, internalOptions) {
    return this.Jb(editor, options3, {
      // Appply given internal open options
      ...internalOptions,
      // Allow to match on a side-by-side editor when same
      // editor is opened on both sides. In that case we
      // do not want to open a new editor but reuse that one.
      supportSideBySide: SideBySideEditor.BOTH
    });
  }
  async Jb(editor, options3, internalOptions) {
    if (!editor || editor.isDisposed()) {
      return;
    }
    this.s.fire({ editor, groupId: this.id });
    const pinned = options3?.sticky || !this.groupsView.partOptions.enablePreview && !options3?.transient || editor.isDirty() || (options3?.pinned ?? typeof options3?.index === "number") || typeof options3?.index === "number" && this.t.isSticky(options3.index) || editor.hasCapability(
      512
      /* EditorInputCapabilities.Scratchpad */
    );
    const openEditorOptions = {
      index: options3 ? options3.index : void 0,
      pinned,
      sticky: options3?.sticky || typeof options3?.index === "number" && this.t.isSticky(options3.index),
      transient: !!options3?.transient,
      inactiveSelection: internalOptions?.inactiveSelection,
      active: this.count === 0 || !options3 || !options3.inactive,
      supportSideBySide: internalOptions?.supportSideBySide
    };
    if (!openEditorOptions.active && !openEditorOptions.pinned && this.t.activeEditor && !this.t.isPinned(this.t.activeEditor)) {
      openEditorOptions.active = true;
    }
    let activateGroup = false;
    let restoreGroup = false;
    if (options3?.activation === EditorActivation.ACTIVATE) {
      activateGroup = true;
    } else if (options3?.activation === EditorActivation.RESTORE) {
      restoreGroup = true;
    } else if (options3?.activation === EditorActivation.PRESERVE) {
      activateGroup = false;
      restoreGroup = false;
    } else if (openEditorOptions.active) {
      activateGroup = !options3 || !options3.preserveFocus;
      restoreGroup = !activateGroup;
    }
    if (typeof openEditorOptions.index === "number") {
      const indexOfEditor = this.t.indexOf(editor);
      if (indexOfEditor !== -1 && indexOfEditor !== openEditorOptions.index) {
        this.Lb(editor, openEditorOptions);
      }
    }
    const { editor: openedEditor, isNew } = this.t.openEditor(editor, openEditorOptions);
    if (isNew && // only if this editor was new for the group
    this.count === 1 && // only when this editor was the first editor in the group
    this.P.groups.length > 1) {
      if (openedEditor.editorId && this.groupsView.partOptions.autoLockGroups?.has(openedEditor.editorId)) {
        this.lock(true);
      }
    }
    const showEditorResult = this.Kb(openedEditor, { active: !!openEditorOptions.active, isNew }, options3, internalOptions);
    if (activateGroup) {
      this.groupsView.activateGroup(this);
    } else if (restoreGroup) {
      this.groupsView.restoreGroup(this);
    }
    return showEditorResult;
  }
  Kb(editor, context, options3, internalOptions) {
    let openEditorPromise;
    if (context.active) {
      openEditorPromise = (async () => {
        const { pane, changed, cancelled, error } = await this.J.openEditor(editor, options3, internalOptions, { newInGroup: context.isNew });
        if (cancelled) {
          return void 0;
        }
        if (changed) {
          this.f.fire({ editor });
        }
        if (error) {
          this.g.fire(editor);
        }
        if (!pane && this.activeEditor === editor) {
          this.Ob(editor, options3?.preserveFocus, { fromError: true });
        }
        return pane;
      })();
    } else {
      openEditorPromise = Promise.resolve(void 0);
    }
    if (!internalOptions?.skipTitleUpdate) {
      this.G.openEditor(editor, internalOptions);
    }
    return openEditorPromise;
  }
  //#endregion
  //#region openEditors()
  async openEditors(editors) {
    const editorsToOpen = $Mb(editors).filter(({ editor }) => !editor.isDisposed());
    const firstEditor = editorsToOpen.at(0);
    if (!firstEditor) {
      return;
    }
    const openEditorsOptions = {
      // Allow to match on a side-by-side editor when same
      // editor is opened on both sides. In that case we
      // do not want to open a new editor but reuse that one.
      supportSideBySide: SideBySideEditor.BOTH
    };
    await this.Jb(firstEditor.editor, firstEditor.options, openEditorsOptions);
    const inactiveEditors = editorsToOpen.slice(1);
    const startingIndex = this.getIndexOfEditor(firstEditor.editor) + 1;
    await Promises.settled(inactiveEditors.map(({ editor, options: options3 }, index) => {
      return this.Jb(editor, {
        ...options3,
        inactive: true,
        pinned: true,
        index: startingIndex + index
      }, {
        ...openEditorsOptions,
        // optimization: update the title control later
        // https://github.com/microsoft/vscode/issues/130634
        skipTitleUpdate: true
      });
    }));
    this.G.openEditors(inactiveEditors.map(({ editor }) => editor));
    return this.J.activeEditorPane ?? void 0;
  }
  //#endregion
  //#region moveEditor()
  moveEditors(editors, target) {
    const internalOptions = {
      skipTitleUpdate: this !== target
    };
    let moveFailed = false;
    const movedEditors = /* @__PURE__ */ new Set();
    for (const { editor, options: options3 } of editors) {
      if (this.moveEditor(editor, target, options3, internalOptions)) {
        movedEditors.add(editor);
      } else {
        moveFailed = true;
      }
    }
    if (internalOptions.skipTitleUpdate) {
      target.G.openEditors(Array.from(movedEditors));
      this.G.closeEditors(Array.from(movedEditors));
    }
    return !moveFailed;
  }
  moveEditor(editor, target, options3, internalOptions) {
    if (this === target) {
      this.Lb(editor, options3);
      return true;
    } else {
      return this.Mb(editor, target, options3, { ...internalOptions, keepCopy: false });
    }
  }
  Lb(candidate, options3) {
    const moveToIndex = options3 ? options3.index : void 0;
    if (typeof moveToIndex !== "number") {
      return;
    }
    const currentIndex = this.t.indexOf(candidate);
    const editor = this.t.getEditorByIndex(currentIndex);
    if (!editor) {
      return;
    }
    if (currentIndex !== moveToIndex) {
      const oldStickyCount = this.t.stickyCount;
      this.t.moveEditor(editor, moveToIndex);
      this.t.pin(editor);
      this.G.moveEditor(editor, currentIndex, moveToIndex, oldStickyCount !== this.t.stickyCount);
      this.G.pinEditor(editor);
    }
    if (options3?.sticky) {
      this.stickEditor(editor);
    }
  }
  Mb(editor, target, openOptions, internalOptions) {
    const keepCopy = internalOptions?.keepCopy;
    if (!keepCopy || editor.hasCapability(
      8
      /* EditorInputCapabilities.Singleton */
    )) {
      const canMoveVeto = editor.canMove(this.id, target.id);
      if (typeof canMoveVeto === "string") {
        this.gb.error(canMoveVeto, localize(3495, null));
        return false;
      }
    }
    const options3 = $3ob(this, editor, {
      ...openOptions,
      pinned: true,
      // always pin moved editor
      sticky: openOptions?.sticky ?? (!keepCopy && this.t.isSticky(editor))
      // preserve sticky state only if editor is moved or eplicitly wanted (https://github.com/microsoft/vscode/issues/99035)
    });
    if (!keepCopy) {
      this.r.fire({
        groupId: this.id,
        editor,
        target: target.id
      });
    }
    target.Jb(keepCopy ? editor.copy() : editor, options3, internalOptions);
    if (!keepCopy) {
      this.Ob(editor, true, { ...internalOptions, context: EditorCloseContext.MOVE });
    }
    return true;
  }
  //#endregion
  //#region copyEditor()
  copyEditors(editors, target) {
    const internalOptions = {
      skipTitleUpdate: this !== target
    };
    for (const { editor, options: options3 } of editors) {
      this.copyEditor(editor, target, options3, internalOptions);
    }
    if (internalOptions.skipTitleUpdate) {
      const copiedEditors = editors.map(({ editor }) => editor);
      target.G.openEditors(copiedEditors);
    }
  }
  copyEditor(editor, target, options3, internalOptions) {
    if (this === target) {
      this.Lb(editor, options3);
    } else {
      this.Mb(editor, target, options3, { ...internalOptions, keepCopy: true });
    }
  }
  //#endregion
  //#region closeEditor()
  async closeEditor(editor = this.activeEditor || void 0, options3) {
    return this.Nb(editor, options3);
  }
  async Nb(editor = this.activeEditor || void 0, options3, internalOptions) {
    if (!editor) {
      return false;
    }
    const veto = await this.Sb([editor]);
    if (veto) {
      return false;
    }
    this.Ob(editor, options3?.preserveFocus, internalOptions);
    return true;
  }
  Ob(editor, preserveFocus = this.groupsView.activeGroup !== this, internalOptions) {
    if (!internalOptions?.skipTitleUpdate) {
      this.G.beforeCloseEditor(editor);
    }
    if (this.t.isActive(editor)) {
      this.Pb(preserveFocus, internalOptions);
    } else {
      this.Rb(editor, internalOptions);
    }
    if (!internalOptions?.skipTitleUpdate) {
      this.G.closeEditor(editor);
    }
  }
  Pb(preserveFocus = this.groupsView.activeGroup !== this, internalOptions) {
    const editorToClose = this.activeEditor;
    const restoreFocus = !preserveFocus && this.Qb(this.element);
    const closeEmptyGroup = this.groupsView.partOptions.closeEmptyGroups;
    if (closeEmptyGroup && this.u && this.count === 1) {
      const mostRecentlyActiveGroups = this.groupsView.getGroups(
        1
        /* GroupsOrder.MOST_RECENTLY_ACTIVE */
      );
      const nextActiveGroup = mostRecentlyActiveGroups[1];
      if (nextActiveGroup) {
        if (restoreFocus) {
          nextActiveGroup.focus();
        } else {
          this.groupsView.activateGroup(nextActiveGroup, true);
        }
      }
    }
    if (editorToClose) {
      this.t.closeEditor(editorToClose, internalOptions?.context);
    }
    const nextActiveEditor = this.t.activeEditor;
    if (nextActiveEditor) {
      let activation = void 0;
      if (preserveFocus && this.groupsView.activeGroup !== this) {
        activation = EditorActivation.PRESERVE;
      }
      const options3 = {
        preserveFocus,
        activation,
        // When closing an editor due to an error we can end up in a loop where we continue closing
        // editors that fail to open (e.g. when the file no longer exists). We do not want to show
        // repeated errors in this case to the user. As such, if we open the next editor and we are
        // in a scope of a previous editor failing, we silence the input errors until the editor is
        // opened by setting ignoreError: true.
        ignoreError: internalOptions?.fromError
      };
      const internalEditorOpenOptions = {
        // When closing an editor, we reveal the next one in the group.
        // However, this can be a result of moving an editor to another
        // window so we explicitly disable window reordering in this case.
        preserveWindowOrder: true
      };
      this.Jb(nextActiveEditor, options3, internalEditorOpenOptions);
    } else {
      if (editorToClose) {
        this.J.closeEditor(editorToClose);
      }
      if (restoreFocus && !closeEmptyGroup) {
        this.focus();
      }
      this.f.fire({ editor: void 0 });
      if (closeEmptyGroup) {
        this.groupsView.removeGroup(this, preserveFocus);
      }
    }
  }
  Qb(target) {
    const activeElement = $Lj();
    if (activeElement === target.ownerDocument.body) {
      return true;
    }
    return $Dj(activeElement, target);
  }
  Rb(editor, internalOptions) {
    this.t.closeEditor(editor, internalOptions?.context);
  }
  async Sb(editors) {
    if (!editors.length) {
      return false;
    }
    const editor = editors.shift();
    let handleCloseConfirmationPromise = this.M.get(editor);
    if (!handleCloseConfirmationPromise) {
      handleCloseConfirmationPromise = this.Tb(editor);
      this.M.set(editor, handleCloseConfirmationPromise);
    }
    let veto;
    try {
      veto = await handleCloseConfirmationPromise;
    } finally {
      this.M.delete(editor);
    }
    if (veto) {
      return veto;
    }
    return this.Sb(editors);
  }
  async Tb(editor, options3) {
    if (!this.Ub(editor)) {
      return false;
    }
    if (editor instanceof $1I && this.t.contains(editor.primary)) {
      return false;
    }
    if (this.P.groups.some((groupView) => {
      if (groupView === this) {
        return false;
      }
      const otherGroup = groupView;
      if (otherGroup.contains(editor, { supportSideBySide: SideBySideEditor.BOTH })) {
        return true;
      }
      if (editor instanceof $1I && otherGroup.contains(editor.primary)) {
        return true;
      }
      return false;
    })) {
      return false;
    }
    let confirmation = 2;
    let saveReason = 1;
    let autoSave = false;
    if (!editor.hasCapability(
      4
      /* EditorInputCapabilities.Untitled */
    ) && !options3?.skipAutoSave && !editor.closeHandler) {
      if (this.bb.getAutoSaveMode(editor).mode === 3) {
        autoSave = true;
        confirmation = 0;
        saveReason = 3;
      } else if ($p && ($l || $n) && this.bb.getAutoSaveMode(editor).mode === 4) {
        autoSave = true;
        confirmation = 0;
        saveReason = 4;
      }
    }
    if (!autoSave) {
      if (!this.activeEditor || !this.activeEditor.matches(editor)) {
        await this.Jb(editor);
      }
      await this.fb.focus(getWindow(this.element));
      if (typeof editor.closeHandler?.confirm === "function") {
        confirmation = await editor.closeHandler.confirm([{ editor, groupId: this.id }]);
      } else {
        let name;
        if (editor instanceof $1I) {
          name = editor.primary.getName();
        } else {
          name = editor.getName();
        }
        confirmation = await this.$.showSaveConfirm([name]);
      }
    }
    if (!editor.closeHandler && !this.Ub(editor)) {
      return confirmation === 2 ? true : false;
    }
    switch (confirmation) {
      case 0: {
        const result = await editor.save(this.id, { reason: saveReason });
        if (!result && autoSave) {
          return this.Tb(editor, { skipAutoSave: true });
        }
        return editor.isDirty();
      }
      case 1:
        try {
          await editor.revert(this.id);
          return editor.isDirty();
        } catch (error) {
          this.db.error(error);
          await editor.revert(this.id, { soft: true });
          return editor.isDirty();
        }
      case 2:
        return true;
    }
  }
  Ub(editor) {
    if (editor.closeHandler) {
      return editor.closeHandler.showConfirm();
    }
    return editor.isDirty() && !editor.isSaving();
  }
  //#endregion
  //#region closeEditors()
  async closeEditors(args2, options3) {
    if (this.isEmpty) {
      return true;
    }
    const editors = this.Vb(args2);
    const veto = await this.Sb(editors.slice(0));
    if (veto) {
      return false;
    }
    this.Wb(editors, options3);
    return true;
  }
  Vb(args2) {
    if (Array.isArray(args2)) {
      return args2;
    }
    const filter = args2;
    const hasDirection = typeof filter.direction === "number";
    let editorsToClose = this.t.getEditors(hasDirection ? 1 : 0, filter);
    if (filter.savedOnly) {
      editorsToClose = editorsToClose.filter((editor) => !editor.isDirty() || editor.isSaving());
    } else if (hasDirection && filter.except) {
      editorsToClose = filter.direction === 0 ? editorsToClose.slice(0, this.t.indexOf(filter.except, editorsToClose)) : editorsToClose.slice(this.t.indexOf(filter.except, editorsToClose) + 1);
    } else if (filter.except) {
      editorsToClose = editorsToClose.filter((editor) => filter.except && !editor.matches(filter.except));
    }
    return editorsToClose;
  }
  Wb(editors, options3) {
    let closeActiveEditor = false;
    for (const editor of editors) {
      if (!this.isActive(editor)) {
        this.Rb(editor);
      } else {
        closeActiveEditor = true;
      }
    }
    if (closeActiveEditor) {
      this.Pb(options3?.preserveFocus);
    }
    if (editors.length) {
      this.G.closeEditors(editors);
    }
  }
  //#endregion
  //#region closeAllEditors()
  async closeAllEditors(options3) {
    if (this.isEmpty) {
      if (this.groupsView.partOptions.closeEmptyGroups) {
        this.groupsView.removeGroup(this);
      }
      return true;
    }
    let editors = this.t.getEditors(0, options3);
    if (options3?.excludeConfirming) {
      editors = editors.filter((editor) => !this.Ub(editor));
    }
    const veto = await this.Sb(editors);
    if (veto) {
      return false;
    }
    this.Xb(options3);
    return true;
  }
  Xb(options3) {
    let editors = this.t.getEditors(1, options3);
    if (options3?.excludeConfirming) {
      editors = editors.filter((editor) => !this.Ub(editor));
    }
    const editorsToClose = [];
    for (const editor of editors) {
      if (!this.isActive(editor)) {
        this.Rb(editor);
      }
      editorsToClose.push(editor);
    }
    if (this.activeEditor && editorsToClose.includes(this.activeEditor)) {
      this.Pb();
    }
    if (editorsToClose.length) {
      this.G.closeEditors(editorsToClose);
    }
  }
  //#endregion
  //#region replaceEditors()
  async replaceEditors(editors) {
    let activeReplacement;
    const inactiveReplacements = [];
    for (let { editor, replacement, forceReplaceDirty, options: options3 } of editors) {
      const index = this.getIndexOfEditor(editor);
      if (index >= 0) {
        const isActiveEditor = this.isActive(editor);
        if (options3) {
          options3.index = index;
        } else {
          options3 = { index };
        }
        options3.inactive = !isActiveEditor;
        options3.pinned = options3.pinned ?? true;
        const editorToReplace = { editor, replacement, forceReplaceDirty, options: options3 };
        if (isActiveEditor) {
          activeReplacement = editorToReplace;
        } else {
          inactiveReplacements.push(editorToReplace);
        }
      }
    }
    for (const { editor, replacement, forceReplaceDirty, options: options3 } of inactiveReplacements) {
      await this.Jb(replacement, options3);
      if (!editor.matches(replacement)) {
        let closed = false;
        if (forceReplaceDirty) {
          this.Ob(editor, true, { context: EditorCloseContext.REPLACE });
          closed = true;
        } else {
          closed = await this.Nb(editor, { preserveFocus: true }, { context: EditorCloseContext.REPLACE });
        }
        if (!closed) {
          return;
        }
      }
    }
    if (activeReplacement) {
      const openEditorResult = this.Jb(activeReplacement.replacement, activeReplacement.options);
      if (!activeReplacement.editor.matches(activeReplacement.replacement)) {
        if (activeReplacement.forceReplaceDirty) {
          this.Ob(activeReplacement.editor, true, { context: EditorCloseContext.REPLACE });
        } else {
          await this.Nb(activeReplacement.editor, { preserveFocus: true }, { context: EditorCloseContext.REPLACE });
        }
      }
      await openEditorResult;
    }
  }
  //#endregion
  //#region Locking
  get isLocked() {
    return this.t.isLocked;
  }
  lock(locked) {
    this.t.lock(locked);
  }
  //#endregion
  //#region Editor Actions
  createEditorActions(disposables) {
    let actions = { primary: [], secondary: [] };
    let onDidChange;
    const activeEditorPane = this.activeEditorPane;
    if (activeEditorPane instanceof $5tb) {
      const editorScopedContextKeyService = activeEditorPane.scopedContextKeyService ?? this.scopedContextKeyService;
      const editorTitleMenu = disposables.add(this.Y.createMenu($bJ.EditorTitle, editorScopedContextKeyService, { emitEventsForSubmenuChanges: true, eventDebounceDelay: 0 }));
      onDidChange = editorTitleMenu.onDidChange;
      const shouldInlineGroup = (action, group2) => group2 === "navigation" && action.actions.length <= 1;
      actions = $Q$(editorTitleMenu.getActions({ arg: this.D.get(), shouldForwardArgs: true }), "navigation", shouldInlineGroup);
    } else {
      const _onDidChange = disposables.add(new $ze());
      onDidChange = _onDidChange.event;
      disposables.add(this.onDidActiveEditorChange(() => _onDidChange.fire()));
    }
    return { actions, onDidChange };
  }
  //#endregion
  //#region Themable
  updateStyles() {
    const isEmpty = this.isEmpty;
    if (isEmpty) {
      this.element.style.backgroundColor = this.z($vmb) || "";
    } else {
      this.element.style.backgroundColor = "";
    }
    const borderColor = this.z($Amb) || this.z($ko);
    if (!isEmpty && borderColor) {
      this.F.classList.add("title-border-bottom");
      this.F.style.setProperty("--title-border-bottom-color", borderColor);
    } else {
      this.F.classList.remove("title-border-bottom");
      this.F.style.removeProperty("--title-border-bottom-color");
    }
    const { showTabs } = this.groupsView.partOptions;
    this.F.style.backgroundColor = this.z(showTabs === "multiple" ? $xmb : $zmb) || "";
    this.I.style.backgroundColor = this.z($Ko) || "";
  }
  get minimumWidth() {
    return this.J.minimumWidth;
  }
  get minimumHeight() {
    return this.J.minimumHeight;
  }
  get maximumWidth() {
    return this.J.maximumWidth;
  }
  get maximumHeight() {
    return this.J.maximumHeight;
  }
  get proportionalLayout() {
    if (!this.y) {
      return true;
    }
    return !(this.y.width === this.minimumWidth || this.y.height === this.minimumHeight);
  }
  layout(width2, height, top2, left) {
    this.y = { width: width2, height, top: top2, left };
    this.element.classList.toggle("max-height-478px", height <= 478);
    const titleControlSize = this.G.layout({
      container: new $rj(width2, height),
      available: new $rj(width2, height - this.J.minimumHeight)
    });
    this.H.getContainer().style.top = `${Math.max(this.titleHeight.offset - 2, 0)}px`;
    const editorHeight = Math.max(0, height - titleControlSize.height);
    this.I.style.height = `${editorHeight}px`;
    this.J.layout({ width: width2, height: editorHeight, top: top2 + titleControlSize.height, left });
  }
  relayout() {
    if (this.y) {
      const { width: width2, height, top: top2, left } = this.y;
      this.layout(width2, height, top2, left);
    }
  }
  setBoundarySashes(sashes) {
    this.J.setBoundarySashes(sashes);
  }
  toJSON() {
    return this.t.serialize();
  }
  //#endregion
  dispose() {
    this.Hb = true;
    this.b.fire();
    super.dispose();
  }
};
$Ryb = $Ryb_1 = __decorate([
  __param(6, $Pk),
  __param(7, $on),
  __param(8, $gs),
  __param(9, $zv),
  __param(10, $Ty),
  __param(11, $cJ),
  __param(12, $50),
  __param(13, $1v),
  __param(14, $mJ),
  __param(15, $4J),
  __param(16, $vl),
  __param(17, $wn),
  __param(18, $4L),
  __param(19, $S4),
  __param(20, $Yv),
  __param(21, $km)
], $Ryb);

// out-build/vs/workbench/contrib/files/browser/views/openEditorsView.js
var $Syb_1;
var $71 = $;
var $Syb = class $Syb2 extends $_ob {
  static {
    $Syb_1 = this;
  }
  static {
    this.a = 9;
  }
  static {
    this.b = 0;
  }
  static {
    this.ID = "workbench.explorer.openEditorsView";
  }
  static {
    this.NAME = localize2(7401, "Open Editors");
  }
  constructor(options3, instantiationService, viewDescriptorService, contextMenuService, ab, configurationService, keybindingService, contextKeyService, themeService, telemetryService, hoverService, sb, ac, openerService, bc) {
    super(options3, keybindingService, contextMenuService, configurationService, contextKeyService, viewDescriptorService, instantiationService, openerService, themeService, telemetryService, hoverService);
    this.ab = ab;
    this.sb = sb;
    this.ac = ac;
    this.bc = bc;
    this.r = false;
    this.s = [];
    this.L = false;
    this.h = 0;
    this.t = configurationService.getValue("explorer.openEditors.sortOrder");
    this.cc();
    this.B(this.Ab.onDidChangeConfiguration((e) => this.oc(e)));
    this.B(this.sb.onDidChangeDirty((workingCopy) => this.qc(workingCopy)));
  }
  cc() {
    const updateWholeList = () => {
      if (!this.isBodyVisible() || !this.m) {
        this.r = true;
        return;
      }
      this.f?.schedule(this.h);
    };
    const groupDisposables = this.B(new $_c());
    const addGroupListener = (group2) => {
      const groupModelChangeListener = group2.onDidModelChange((e) => {
        if (this.f?.isScheduled()) {
          return;
        }
        if (!this.isBodyVisible() || !this.m) {
          this.r = true;
          return;
        }
        const index = this.jc(group2, e.editor);
        switch (e.kind) {
          case 8:
            this.nc();
            break;
          case 1:
          case 2:
            if (index >= 0) {
              this.m.splice(index, 1, [group2]);
            }
            break;
          case 14:
          case 13:
          case 10:
          case 11:
          case 9:
            this.m.splice(index, 1, [new $rtb(e.editor, group2)]);
            this.nc();
            break;
          case 5:
          case 7:
          case 6:
            updateWholeList();
            break;
        }
      });
      groupDisposables.set(group2.id, groupModelChangeListener);
    };
    this.ab.groups.forEach((g) => addGroupListener(g));
    this.B(this.ab.onDidAddGroup((group2) => {
      addGroupListener(group2);
      updateWholeList();
    }));
    this.B(this.ab.onDidMoveGroup(() => updateWholeList()));
    this.B(this.ab.onDidChangeActiveGroup(() => this.nc()));
    this.B(this.ab.onDidRemoveGroup((group2) => {
      groupDisposables.deleteAndDispose(group2.id);
      updateWholeList();
    }));
  }
  Ob(container2) {
    super.Ob(container2, this.title);
    const count = $bk(container2, $71(".open-editors-dirty-count-container"));
    this.c = $bk(count, $71(".dirty-count.monaco-count-badge.long"));
    this.c.style.backgroundColor = $Zn($wo);
    this.c.style.color = $Zn($xo);
    this.c.style.border = `1px solid ${$Zn($ko)}`;
    this.qc();
  }
  W(container2) {
    super.W(container2);
    container2.classList.add("open-editors");
    container2.classList.add("show-file-icons");
    const delegate = new OpenEditorsDelegate();
    if (this.m) {
      this.m.dispose();
    }
    if (this.n) {
      this.n.clear();
    }
    this.j = new OpenEditorsDragAndDrop(this.t, this.Db, this.ab);
    this.n = this.Db.createInstance($lsb, { onDidChangeVisibility: this.onDidChangeBodyVisibility });
    this.m = this.Db.createInstance($Web, "OpenEditors", container2, delegate, [
      new EditorGroupRenderer(this.yb, this.Db),
      new OpenEditorRenderer(this.n, this.Db, this.yb, this.Ab)
    ], {
      identityProvider: { getId: (element) => element instanceof $rtb ? element.getId() : element.id.toString() },
      dnd: this.j,
      overrideStyles: this.Xb().listOverrideStyles,
      accessibilityProvider: new OpenEditorsAccessibilityProvider()
    });
    this.B(this.m);
    this.B(this.n);
    let labelChangeListeners = [];
    this.f = this.B(new $8h(() => {
      if (!this.m) {
        return;
      }
      labelChangeListeners = $Xc(labelChangeListeners);
      const previousLength = this.m.length;
      const elements = this.ic();
      this.m.splice(0, this.m.length, elements);
      this.nc();
      if (previousLength !== this.m.length) {
        this.pc();
      }
      this.r = false;
      if (this.t === "alphabetical" || this.t === "fullPath") {
        elements.forEach((e) => {
          if (e instanceof $rtb) {
            labelChangeListeners.push(e.editor.onDidChangeLabel(() => this.f?.schedule()));
          }
        });
      }
    }, this.h));
    this.pc();
    this.fc();
    this.B(this.m.onContextMenu((e) => this.lc(e)));
    this.B(this.m.onMouseMiddleClick((e) => {
      if (e && e.element instanceof $rtb) {
        if ($lL(e.element.group, e.element.editor, EditorCloseMethod.MOUSE, this.ab.partOptions)) {
          return;
        }
        e.element.group.closeEditor(e.element.editor, { preserveFocus: true });
      }
    }));
    this.B(this.m.onDidOpen((e) => {
      const element = e.element;
      if (!element) {
        return;
      } else if (element instanceof $rtb) {
        if ($3j(e.browserEvent) && e.browserEvent.button === 1) {
          return;
        }
        this.mc(() => {
          this.kc(element, { preserveFocus: e.editorOptions.preserveFocus, pinned: e.editorOptions.pinned, sideBySide: e.sideBySide });
        });
      } else {
        this.mc(() => {
          this.ab.activateGroup(element);
          if (!e.editorOptions.preserveFocus) {
            element.focus();
          }
        });
      }
    }));
    this.f.schedule(0);
    this.B(this.onDidChangeBodyVisibility((visible) => {
      if (visible && this.r) {
        this.f?.schedule(0);
      }
    }));
    const containerModel = this.Cb.getViewContainerModel(this.Cb.getViewContainerByViewId(this.id));
    this.B(containerModel.onDidChangeAllViewDescriptors(() => {
      this.pc();
    }));
  }
  fc() {
    if (!this.m) {
      return;
    }
    $dtb.bindTo(this.m.contextKeyService);
    $etb.bindTo(this.m.contextKeyService);
    const groupFocusedContext = $Mtb.bindTo(this.Bb);
    const dirtyEditorFocusedContext = $Ntb.bindTo(this.Bb);
    const readonlyEditorFocusedContext = $Otb.bindTo(this.Bb);
    const openEditorsSelectedFileOrUntitledContext = $Ptb.bindTo(this.Bb);
    const resourceContext = this.Db.createInstance($lqb);
    this.B(resourceContext);
    this.B(this.m.onDidChangeFocus((e) => {
      resourceContext.reset();
      groupFocusedContext.reset();
      dirtyEditorFocusedContext.reset();
      readonlyEditorFocusedContext.reset();
      const element = e.elements.length ? e.elements[0] : void 0;
      if (element instanceof $rtb) {
        const resource = element.getResource();
        dirtyEditorFocusedContext.set(element.editor.isDirty() && !element.editor.isSaving());
        readonlyEditorFocusedContext.set(!!element.editor.isReadonly());
        resourceContext.set(resource ?? null);
      } else if (!!element) {
        groupFocusedContext.set(true);
      }
    }));
    this.B(this.m.onDidChangeSelection((e) => {
      const selectedAreFileOrUntitled = e.elements.every((e2) => {
        if (e2 instanceof $rtb) {
          const resource = e2.getResource();
          return resource && (resource.scheme === Schemas.untitled || this.bc.hasProvider(resource));
        }
        return false;
      });
      openEditorsSelectedFileOrUntitledContext.set(selectedAreFileOrUntitled);
    }));
  }
  focus() {
    super.focus();
    this.m?.domFocus();
  }
  X(height, width2) {
    super.X(height, width2);
    this.m?.layout(height, width2);
  }
  get hc() {
    return this.ab.groups.length > 1;
  }
  ic() {
    this.s = [];
    this.ab.getGroups(
      2
      /* GroupsOrder.GRID_APPEARANCE */
    ).forEach((g) => {
      if (this.hc) {
        this.s.push(g);
      }
      let editors = g.editors.map((ei) => new $rtb(ei, g));
      if (this.t === "alphabetical") {
        editors = editors.sort((first, second) => $FM(first.editor.getName(), second.editor.getName()));
      } else if (this.t === "fullPath") {
        editors = editors.sort((first, second) => {
          const firstResource = first.editor.resource;
          const secondResource = second.editor.resource;
          if (firstResource === void 0 && secondResource === void 0) {
            return $FM(first.editor.getName(), second.editor.getName());
          } else if (firstResource === void 0) {
            return -1;
          } else if (secondResource === void 0) {
            return 1;
          } else {
            const firstScheme = firstResource.scheme;
            const secondScheme = secondResource.scheme;
            if (firstScheme !== Schemas.file && secondScheme !== Schemas.file) {
              return $nh.compare(firstResource, secondResource);
            } else if (firstScheme !== Schemas.file) {
              return -1;
            } else if (secondScheme !== Schemas.file) {
              return 1;
            } else {
              return $nh.compare(firstResource, secondResource);
            }
          }
        });
      }
      this.s.push(...editors);
    });
    return this.s;
  }
  jc(group2, editor) {
    if (!editor) {
      return this.s.findIndex((e) => !(e instanceof $rtb) && e.id === group2.id);
    }
    return this.s.findIndex((e) => e instanceof $rtb && e.editor === editor && e.group.id === group2.id);
  }
  kc(element, options3) {
    if (element) {
      this.Gb.publicLog2("workbenchActionExecuted", { id: "workbench.files.openFile", from: "openEditors" });
      const preserveActivateGroup = options3.sideBySide && options3.preserveFocus;
      if (!preserveActivateGroup) {
        this.ab.activateGroup(element.group);
      }
      const targetGroup = options3.sideBySide ? this.ab.sideGroup : element.group;
      targetGroup.openEditor(element.editor, options3);
    }
  }
  lc(e) {
    if (!e.element) {
      return;
    }
    const element = e.element;
    this.zb.showContextMenu({
      menuId: $bJ.OpenEditorsContext,
      menuActionOptions: { shouldForwardArgs: true, arg: element instanceof $rtb ? $mL.getOriginalUri(element.editor) : {} },
      contextKeyService: this.m?.contextKeyService,
      getAnchor: () => e.anchor,
      getActionsContext: () => element instanceof $rtb ? { groupId: element.groupId, editorIndex: element.group.getIndexOfEditor(element.editor) } : { groupId: element.id }
    });
  }
  mc(fn) {
    this.L = true;
    try {
      fn();
    } finally {
      this.L = false;
    }
  }
  nc() {
    if (!this.m || this.L) {
      return;
    }
    if (this.m.length && this.ab.activeGroup) {
      const index = this.jc(this.ab.activeGroup, this.ab.activeGroup.activeEditor);
      if (index >= 0) {
        try {
          this.m.setFocus([index]);
          this.m.setSelection([index]);
          this.m.reveal(index);
        } catch (e) {
        }
        return;
      }
    }
    this.m.setFocus([]);
    this.m.setSelection([]);
  }
  oc(event) {
    if (event.affectsConfiguration("explorer.openEditors")) {
      this.pc();
    }
    if (event.affectsConfiguration("explorer.decorations") || event.affectsConfiguration("explorer.openEditors.sortOrder")) {
      this.t = this.Ab.getValue("explorer.openEditors.sortOrder");
      if (this.j) {
        this.j.sortOrder = this.t;
      }
      this.f?.schedule();
    }
  }
  pc() {
    this.minimumBodySize = this.orientation === 0 ? this.tc() : 170;
    this.maximumBodySize = this.orientation === 0 ? this.sc() : Number.POSITIVE_INFINITY;
  }
  qc(workingCopy) {
    if (workingCopy) {
      const gotDirty = workingCopy.isDirty();
      if (gotDirty && !(workingCopy.capabilities & 2) && this.ac.hasShortAutoSaveDelay(workingCopy.resource)) {
        return;
      }
    }
    const dirty = this.sb.dirtyCount;
    if (dirty === 0) {
      this.c.classList.add("hidden");
    } else {
      this.c.textContent = localize(7398, null, dirty);
      this.c.classList.remove("hidden");
    }
  }
  get rc() {
    return this.ab.groups.map((g) => g.count).reduce((first, second) => first + second, this.hc ? this.ab.groups.length : 0);
  }
  sc() {
    let minVisibleOpenEditors = this.Ab.getValue("explorer.openEditors.minVisible");
    if (typeof minVisibleOpenEditors !== "number") {
      minVisibleOpenEditors = $Syb_1.b;
    }
    const containerModel = this.Cb.getViewContainerModel(this.Cb.getViewContainerByViewId(this.id));
    if (containerModel.visibleViewDescriptors.length <= 1) {
      return Number.POSITIVE_INFINITY;
    }
    return Math.max(this.rc, minVisibleOpenEditors) * OpenEditorsDelegate.ITEM_HEIGHT;
  }
  tc() {
    let visibleOpenEditors = this.Ab.getValue("explorer.openEditors.visible");
    if (typeof visibleOpenEditors !== "number") {
      visibleOpenEditors = $Syb_1.a;
    }
    return this.uc(visibleOpenEditors);
  }
  uc(visibleOpenEditors = $Syb_1.a) {
    const itemsToShow = Math.min(Math.max(visibleOpenEditors, 1), this.rc);
    return itemsToShow * OpenEditorsDelegate.ITEM_HEIGHT;
  }
  setStructuralRefreshDelay(delay) {
    this.h = delay;
  }
  getOptimalWidth() {
    if (!this.m) {
      return super.getOptimalWidth();
    }
    const parentNode = this.m.getHTMLElement();
    const childNodes = [].slice.call(parentNode.querySelectorAll(".open-editor > a"));
    return $Cj(parentNode, childNodes);
  }
};
$Syb = $Syb_1 = __decorate([
  __param(1, $Pk),
  __param(2, $$M),
  __param(3, $50),
  __param(4, $iJ),
  __param(5, $kl),
  __param(6, $Ty),
  __param(7, $on),
  __param(8, $gs),
  __param(9, $zv),
  __param(10, $5$),
  __param(11, $XI),
  __param(12, $4J),
  __param(13, $O4),
  __param(14, $km)
], $Syb);
var OpenEditorActionRunner = class extends $Vm {
  async run(action) {
    if (!this.editor) {
      return;
    }
    return super.run(action, { groupId: this.editor.groupId, editorIndex: this.editor.group.getIndexOfEditor(this.editor.editor) });
  }
};
var OpenEditorsDelegate = class _OpenEditorsDelegate {
  static {
    this.ITEM_HEIGHT = 22;
  }
  getHeight(_element) {
    return _OpenEditorsDelegate.ITEM_HEIGHT;
  }
  getTemplateId(element) {
    if (element instanceof $rtb) {
      return OpenEditorRenderer.ID;
    }
    return EditorGroupRenderer.ID;
  }
};
var EditorGroupRenderer = class _EditorGroupRenderer {
  static {
    this.ID = "editorgroup";
  }
  constructor(a, b) {
    this.a = a;
    this.b = b;
  }
  get templateId() {
    return _EditorGroupRenderer.ID;
  }
  renderTemplate(container2) {
    const editorGroupTemplate = /* @__PURE__ */ Object.create(null);
    editorGroupTemplate.root = $bk(container2, $71(".editor-group"));
    editorGroupTemplate.name = $bk(editorGroupTemplate.root, $71("span.name"));
    editorGroupTemplate.actionBar = new $LZ(container2);
    const saveAllInGroupAction = this.b.createInstance($Kvb, $Kvb.ID, $Kvb.LABEL);
    const saveAllInGroupKey = this.a.lookupKeybinding(saveAllInGroupAction.id);
    editorGroupTemplate.actionBar.push(saveAllInGroupAction, { icon: true, label: false, keybinding: saveAllInGroupKey ? saveAllInGroupKey.getLabel() : void 0 });
    const closeGroupAction = this.b.createInstance($Lvb, $Lvb.ID, $Lvb.LABEL);
    const closeGroupActionKey = this.a.lookupKeybinding(closeGroupAction.id);
    editorGroupTemplate.actionBar.push(closeGroupAction, { icon: true, label: false, keybinding: closeGroupActionKey ? closeGroupActionKey.getLabel() : void 0 });
    return editorGroupTemplate;
  }
  renderElement(editorGroup, _index, templateData) {
    templateData.editorGroup = editorGroup;
    templateData.name.textContent = editorGroup.label;
    templateData.actionBar.context = { groupId: editorGroup.id };
  }
  disposeTemplate(templateData) {
    templateData.actionBar.dispose();
  }
};
var OpenEditorRenderer = class _OpenEditorRenderer {
  static {
    this.ID = "openeditor";
  }
  constructor(c, d, f, h3) {
    this.c = c;
    this.d = d;
    this.f = f;
    this.h = h3;
    this.a = this.d.createInstance($Ywb, $Ywb.ID, $Ywb.LABEL);
    this.b = this.d.createInstance($Zwb, $Zwb.ID, $Zwb.LABEL);
  }
  get templateId() {
    return _OpenEditorRenderer.ID;
  }
  renderTemplate(container2) {
    const editorTemplate = /* @__PURE__ */ Object.create(null);
    editorTemplate.container = container2;
    editorTemplate.actionRunner = new OpenEditorActionRunner();
    editorTemplate.actionBar = new $LZ(container2, { actionRunner: editorTemplate.actionRunner });
    editorTemplate.root = this.c.create(container2);
    return editorTemplate;
  }
  renderElement(openedEditor, _index, templateData) {
    const editor = openedEditor.editor;
    templateData.actionRunner.editor = openedEditor;
    templateData.container.classList.toggle("dirty", editor.isDirty() && !editor.isSaving());
    templateData.container.classList.toggle("sticky", openedEditor.isSticky());
    templateData.root.setResource({
      resource: $mL.getOriginalUri(editor, { supportSideBySide: SideBySideEditor.BOTH }),
      name: editor.getName(),
      description: editor.getDescription(
        1
        /* Verbosity.MEDIUM */
      )
    }, {
      italic: openedEditor.isPreview(),
      extraClasses: ["open-editor"].concat(openedEditor.editor.getLabelExtraClasses()),
      fileDecorations: this.h.getValue().explorer.decorations,
      title: editor.getTitle(
        2
        /* Verbosity.LONG */
      ),
      icon: editor.getIcon()
    });
    const editorAction = openedEditor.isSticky() ? this.b : this.a;
    if (!templateData.actionBar.hasAction(editorAction)) {
      if (!templateData.actionBar.isEmpty()) {
        templateData.actionBar.clear();
      }
      templateData.actionBar.push(editorAction, { icon: true, label: false, keybinding: this.f.lookupKeybinding(editorAction.id)?.getLabel() });
    }
  }
  disposeTemplate(templateData) {
    templateData.actionBar.dispose();
    templateData.root.dispose();
    templateData.actionRunner.dispose();
  }
};
var OpenEditorsDragAndDrop = class {
  set sortOrder(value) {
    this.a = value;
  }
  constructor(sortOrder, b, c) {
    this.b = b;
    this.c = c;
    this.a = sortOrder;
  }
  get d() {
    return this.b.createInstance($Dob, { allowWorkspaceOpen: false });
  }
  getDragURI(element) {
    if (element instanceof $rtb) {
      const resource = element.getResource();
      if (resource) {
        return resource.toString();
      }
    }
    return null;
  }
  getDragLabel(elements) {
    if (elements.length > 1) {
      return String(elements.length);
    }
    const element = elements[0];
    return element instanceof $rtb ? element.editor.getName() : element.label;
  }
  onDragStart(data, originalEvent) {
    const items = data.elements;
    const editors = [];
    if (items) {
      for (const item of items) {
        if (item instanceof $rtb) {
          editors.push(item);
        }
      }
    }
    if (editors.length) {
      this.b.invokeFunction($Eob, editors, originalEvent);
    }
  }
  onDragOver(data, _targetElement, _targetIndex, targetSector, originalEvent) {
    if (data instanceof $i1) {
      if (!$z_(originalEvent, $kZ.FILES, $u_.FILES)) {
        return false;
      }
    }
    if (this.a !== "editorOrder") {
      if (data instanceof $g1) {
        return false;
      } else {
        return { accept: true, effect: {
          type: 1
          /* ListDragOverEffectType.Move */
        }, feedback: [-1] };
      }
    }
    let dropEffectPosition = void 0;
    switch (targetSector) {
      case 0:
      case 1:
        dropEffectPosition = _targetIndex === 0 && _targetElement instanceof $Ryb ? "drop-target-after" : "drop-target-before";
        break;
      case 2:
      case 3:
        dropEffectPosition = "drop-target-after";
        break;
    }
    return { accept: true, effect: { type: 1, position: dropEffectPosition }, feedback: [_targetIndex] };
  }
  drop(data, targetElement, _targetIndex, targetSector, originalEvent) {
    let group2 = targetElement instanceof $rtb ? targetElement.group : targetElement || this.c.groups[this.c.count - 1];
    let targetEditorIndex = targetElement instanceof $rtb ? targetElement.group.getIndexOfEditor(targetElement.editor) : 0;
    switch (targetSector) {
      case 0:
      case 1:
        if (targetElement instanceof $Ryb && group2.index !== 0) {
          group2 = this.c.groups[group2.index - 1];
          targetEditorIndex = group2.count;
        }
        break;
      case 3:
      case 2:
        if (targetElement instanceof $rtb) {
          targetEditorIndex++;
        }
        break;
    }
    if (data instanceof $g1) {
      for (const oe of data.elements) {
        const sourceEditorIndex = oe.group.getIndexOfEditor(oe.editor);
        if (oe.group === group2 && sourceEditorIndex < targetEditorIndex) {
          targetEditorIndex--;
        }
        oe.group.moveEditor(oe.editor, group2, { index: targetEditorIndex, preserveFocus: true });
        targetEditorIndex++;
      }
      this.c.activateGroup(group2);
    } else {
      this.d.handleDrop(originalEvent, $Y, () => group2, () => group2.focus(), { index: targetEditorIndex });
    }
  }
  dispose() {
  }
};
__decorate([
  $0t
], OpenEditorsDragAndDrop.prototype, "d", null);
var OpenEditorsAccessibilityProvider = class {
  getWidgetAriaLabel() {
    return localize(7399, null);
  }
  getAriaLabel(element) {
    if (element instanceof $rtb) {
      return `${element.editor.getName()}, ${element.editor.getDescription()}`;
    }
    return element.ariaLabel;
  }
};
var toggleEditorGroupLayoutId = "workbench.action.toggleEditorGroupLayout";
$hJ(class extends $gJ {
  constructor() {
    super({
      id: "workbench.action.toggleEditorGroupLayout",
      title: localize2(7402, "Toggle Vertical/Horizontal Editor Layout"),
      f1: true,
      keybinding: {
        primary: 1024 | 512 | 21,
        mac: {
          primary: 2048 | 512 | 21
          /* KeyCode.Digit0 */
        },
        weight: 200
        /* KeybindingWeight.WorkbenchContrib */
      },
      icon: $6l.editorLayout,
      menu: {
        id: $bJ.ViewTitle,
        group: "navigation",
        when: $7m.and($7m.equals("view", $Syb.ID), $Npb),
        order: 10
      }
    });
  }
  async run(accessor) {
    const editorGroupService = accessor.get($iJ);
    const newOrientation = editorGroupService.orientation === 1 ? 0 : 1;
    editorGroupService.setGroupOrientation(newOrientation);
    editorGroupService.activeGroup.focus();
  }
});
$dJ.appendMenuItem($bJ.MenubarLayoutMenu, {
  group: "5_flip",
  command: {
    id: toggleEditorGroupLayoutId,
    title: {
      ...localize2(7403, "Flip Layout"),
      mnemonicTitle: localize(7400, null)
    }
  },
  order: 1
});
$hJ(class extends $gJ {
  constructor() {
    super({
      id: "workbench.action.files.saveAll",
      title: $Jtb,
      f1: true,
      icon: $6l.saveAll,
      menu: {
        id: $bJ.ViewTitle,
        group: "navigation",
        when: $7m.equals("view", $Syb.ID),
        order: 20
      }
    });
  }
  async run(accessor) {
    const commandService = accessor.get($sn);
    await commandService.executeCommand($Itb);
  }
});
$hJ(class extends $gJ {
  constructor() {
    super({
      id: "openEditors.closeAll",
      title: $4wb.LABEL,
      f1: false,
      icon: $6l.closeAll,
      menu: {
        id: $bJ.ViewTitle,
        group: "navigation",
        when: $7m.equals("view", $Syb.ID),
        order: 30
      }
    });
  }
  async run(accessor) {
    const instantiationService = accessor.get($Pk);
    const closeAll = new $4wb();
    await instantiationService.invokeFunction((accessor2) => closeAll.run(accessor2));
  }
});
$hJ(class extends $gJ {
  constructor() {
    super({
      id: "openEditors.newUntitledFile",
      title: localize2(7404, "New Untitled Text File"),
      f1: false,
      icon: $6l.newFile,
      menu: {
        id: $bJ.ViewTitle,
        group: "navigation",
        when: $7m.equals("view", $Syb.ID),
        order: 5
      }
    });
  }
  async run(accessor) {
    const commandService = accessor.get($sn);
    await commandService.executeCommand($Xtb);
  }
});

// out-build/vs/workbench/contrib/files/browser/fileCommands.js
var $ezb = (accessor, toOpen, options3) => {
  if (Array.isArray(toOpen)) {
    const hostService = accessor.get($S4);
    const environmentService = accessor.get($Xk);
    toOpen = toOpen.map((openable) => {
      if ($ys(openable) && openable.workspaceUri.scheme === Schemas.untitled) {
        return {
          workspaceUri: $vh(environmentService.untitledWorkspacesHome, openable.workspaceUri.path, $dl)
        };
      }
      return openable;
    });
    hostService.openWindow(toOpen, options3);
  }
};
var $fzb = (accessor, options3) => {
  const hostService = accessor.get($S4);
  hostService.openWindow(options3);
};
$0I.registerCommandAndKeybindingRule({
  weight: 200,
  when: $ltb,
  primary: 2048 | 3,
  mac: {
    primary: 256 | 3
    /* KeyCode.Enter */
  },
  id: $utb,
  handler: async (accessor, resource) => {
    const editorService = accessor.get($mJ);
    const fileService = accessor.get($km);
    const explorerService = accessor.get($kvb);
    const resources = $mvb(resource, accessor.get($Deb), editorService, accessor.get($iJ), explorerService);
    if (resources.length) {
      const untitledResources = resources.filter((resource2) => resource2.scheme === Schemas.untitled);
      const fileResources = resources.filter((resource2) => resource2.scheme !== Schemas.untitled);
      const items = await Promise.all(fileResources.map(async (resource2) => {
        const item = explorerService.findClosest(resource2);
        if (item) {
          return item;
        }
        return await fileService.stat(resource2);
      }));
      const files = items.filter((i2) => !i2.isDirectory);
      const editors = files.map((f) => ({
        resource: f.resource,
        options: { pinned: true }
      })).concat(...untitledResources.map((untitledResource) => ({ resource: untitledResource, options: { pinned: true } })));
      await editorService.openEditors(editors, $oJ);
    }
  }
});
$0I.registerCommandAndKeybindingRule({
  weight: 200 + 10,
  when: $7m.and($ktb, $7sb.toNegated()),
  primary: 3,
  mac: {
    primary: 2048 | 18
    /* KeyCode.DownArrow */
  },
  id: "explorer.openAndPassFocus",
  handler: async (accessor, _resource) => {
    const editorService = accessor.get($mJ);
    const explorerService = accessor.get($kvb);
    const resources = explorerService.getContext(true);
    if (resources.length) {
      await editorService.openEditors(resources.map((r2) => ({ resource: r2.resource, options: { preserveFocus: false, pinned: true } })));
    }
  }
});
var COMPARE_WITH_SAVED_SCHEMA = "showModifications";
var providerDisposables = [];
$0I.registerCommandAndKeybindingRule({
  id: $ztb,
  when: void 0,
  weight: 200,
  primary: $$e(
    2048 | 41,
    34
    /* KeyCode.KeyD */
  ),
  handler: async (accessor, resource) => {
    const instantiationService = accessor.get($Pk);
    const textModelService = accessor.get($oG);
    const editorService = accessor.get($mJ);
    const fileService = accessor.get($km);
    const listService = accessor.get($Deb);
    let registerEditorListener = false;
    if (providerDisposables.length === 0) {
      registerEditorListener = true;
      const provider = instantiationService.createInstance($qtb);
      providerDisposables.push(provider);
      providerDisposables.push(textModelService.registerTextModelContentProvider(COMPARE_WITH_SAVED_SCHEMA, provider));
    }
    const uri = $lvb(resource, editorService, listService);
    if (uri && fileService.hasProvider(uri)) {
      const name = $sh(uri);
      const editorLabel = localize(7214, null, name, name);
      try {
        await $qtb.open(uri, COMPARE_WITH_SAVED_SCHEMA, editorLabel, editorService, { pinned: true });
        if (registerEditorListener) {
          providerDisposables.push(editorService.onDidVisibleEditorsChange(() => {
            if (!editorService.editors.some((editor) => !!$mL.getCanonicalUri(editor, { supportSideBySide: SideBySideEditor.SECONDARY, filterByScheme: COMPARE_WITH_SAVED_SCHEMA }))) {
              providerDisposables = $Xc(providerDisposables);
            }
          }));
        }
      } catch {
        providerDisposables = $Xc(providerDisposables);
      }
    }
  }
});
var globalResourceToCompare;
var resourceSelectedForCompareContext;
$tn.registerCommand({
  id: $wtb,
  handler: (accessor, resource) => {
    globalResourceToCompare = $lvb(resource, accessor.get($mJ), accessor.get($Deb));
    if (!resourceSelectedForCompareContext) {
      resourceSelectedForCompareContext = $Qtb.bindTo(accessor.get($on));
    }
    resourceSelectedForCompareContext.set(true);
  }
});
$tn.registerCommand({
  id: $xtb,
  handler: async (accessor, resource) => {
    const editorService = accessor.get($mJ);
    const resources = $mvb(resource, accessor.get($Deb), editorService, accessor.get($iJ), accessor.get($kvb));
    if (resources.length === 2) {
      return editorService.openEditor({
        original: { resource: resources[0] },
        modified: { resource: resources[1] },
        options: { pinned: true }
      });
    }
    return true;
  }
});
$tn.registerCommand({
  id: $ytb,
  handler: (accessor, resource) => {
    const editorService = accessor.get($mJ);
    const rightResource = $lvb(resource, editorService, accessor.get($Deb));
    if (globalResourceToCompare && rightResource) {
      editorService.openEditor({
        original: { resource: globalResourceToCompare },
        modified: { resource: rightResource },
        options: { pinned: true }
      });
    }
  }
});
async function resourcesToClipboard(resources, relative, clipboardService, labelService, configurationService) {
  if (resources.length) {
    const lineDelimiter2 = $l ? "\r\n" : "\n";
    let separator = void 0;
    if (relative) {
      const relativeSeparator = configurationService.getValue("explorer.copyRelativePathSeparator");
      if (relativeSeparator === "/" || relativeSeparator === "\\") {
        separator = relativeSeparator;
      }
    }
    const text2 = resources.map((resource) => labelService.getUriLabel(resource, { relative, noPrefix: true, separator })).join(lineDelimiter2);
    await clipboardService.writeText(text2);
  }
}
var copyPathCommandHandler = async (accessor, resource) => {
  const resources = $mvb(resource, accessor.get($Deb), accessor.get($mJ), accessor.get($iJ), accessor.get($kvb));
  await resourcesToClipboard(resources, false, accessor.get($30), accessor.get($ZI), accessor.get($kl));
};
$0I.registerCommandAndKeybindingRule({
  weight: 200,
  when: EditorContextKeys.focus.toNegated(),
  primary: 2048 | 512 | 33,
  win: {
    primary: 1024 | 512 | 33
    /* KeyCode.KeyC */
  },
  id: $Atb,
  handler: copyPathCommandHandler
});
$0I.registerCommandAndKeybindingRule({
  weight: 200,
  when: EditorContextKeys.focus,
  primary: $$e(
    2048 | 41,
    2048 | 512 | 33
    /* KeyCode.KeyC */
  ),
  win: {
    primary: 1024 | 512 | 33
    /* KeyCode.KeyC */
  },
  id: $Atb,
  handler: copyPathCommandHandler
});
var copyRelativePathCommandHandler = async (accessor, resource) => {
  const resources = $mvb(resource, accessor.get($Deb), accessor.get($mJ), accessor.get($iJ), accessor.get($kvb));
  await resourcesToClipboard(resources, true, accessor.get($30), accessor.get($ZI), accessor.get($kl));
};
$0I.registerCommandAndKeybindingRule({
  weight: 200,
  when: EditorContextKeys.focus.toNegated(),
  primary: 2048 | 1024 | 512 | 33,
  win: {
    primary: $$e(
      2048 | 41,
      2048 | 1024 | 33
      /* KeyCode.KeyC */
    )
  },
  id: $Btb,
  handler: copyRelativePathCommandHandler
});
$0I.registerCommandAndKeybindingRule({
  weight: 200,
  when: EditorContextKeys.focus,
  primary: $$e(
    2048 | 41,
    2048 | 1024 | 512 | 33
    /* KeyCode.KeyC */
  ),
  win: {
    primary: $$e(
      2048 | 41,
      2048 | 1024 | 33
      /* KeyCode.KeyC */
    )
  },
  id: $Btb,
  handler: copyRelativePathCommandHandler
});
$0I.registerCommandAndKeybindingRule({
  weight: 200,
  when: void 0,
  primary: $$e(
    2048 | 41,
    46
    /* KeyCode.KeyP */
  ),
  id: "workbench.action.files.copyPathOfActiveFile",
  handler: async (accessor) => {
    const editorService = accessor.get($mJ);
    const activeInput = editorService.activeEditor;
    const resource = $mL.getOriginalUri(activeInput, { supportSideBySide: SideBySideEditor.PRIMARY });
    const resources = resource ? [resource] : [];
    await resourcesToClipboard(resources, false, accessor.get($30), accessor.get($ZI), accessor.get($kl));
  }
});
$tn.registerCommand({
  id: $stb,
  handler: async (accessor, resource) => {
    const viewService = accessor.get($uob);
    const contextService = accessor.get($Zk);
    const explorerService = accessor.get($kvb);
    const editorService = accessor.get($mJ);
    const listService = accessor.get($Deb);
    const uri = $lvb(resource, editorService, listService);
    if (uri && contextService.isInsideWorkspace(uri)) {
      const explorerView = await viewService.openView($4sb, false);
      if (explorerView) {
        const oldAutoReveal = explorerView.autoReveal;
        explorerView.autoReveal = false;
        explorerView.setExpanded(true);
        await explorerService.select(uri, "force");
        explorerView.focus();
        explorerView.autoReveal = oldAutoReveal;
      }
    } else {
      const openEditorsView = viewService.getViewWithId($Syb.ID);
      if (openEditorsView) {
        openEditorsView.setExpanded(true);
        openEditorsView.focus();
      }
    }
  }
});
$tn.registerCommand({
  id: $vtb,
  handler: async (accessor, resource) => {
    const editorService = accessor.get($mJ);
    const listService = accessor.get($Deb);
    const uri = $lvb(resource, editorService, listService);
    if (uri) {
      return editorService.openEditor({ resource: uri, options: { override: EditorResolution.PICK, source: EditorOpenSource.USER } });
    }
    return void 0;
  }
});
async function saveSelectedEditors(accessor, options3) {
  const editorGroupService = accessor.get($iJ);
  const codeEditorService = accessor.get($U5);
  const textFileService = accessor.get($cK);
  let editors = $nvb(accessor);
  if (!editors) {
    const activeGroup = editorGroupService.activeGroup;
    if (activeGroup.activeEditor) {
      editors = [];
      if (activeGroup.activeEditor instanceof $1I && !options3?.saveAs && !(activeGroup.activeEditor.primary.hasCapability(
        4
        /* EditorInputCapabilities.Untitled */
      ) || activeGroup.activeEditor.secondary.hasCapability(
        4
        /* EditorInputCapabilities.Untitled */
      )) && activeGroup.activeEditor.secondary.isModified()) {
        editors.push({ groupId: activeGroup.id, editor: activeGroup.activeEditor.primary });
        editors.push({ groupId: activeGroup.id, editor: activeGroup.activeEditor.secondary });
      } else {
        editors.push({ groupId: activeGroup.id, editor: activeGroup.activeEditor });
      }
    }
  }
  if (!editors || editors.length === 0) {
    return;
  }
  await doSaveEditors(accessor, editors, options3);
  const focusedCodeEditor = codeEditorService.getFocusedCodeEditor();
  if (focusedCodeEditor instanceof $bdb && !focusedCodeEditor.isSimpleWidget) {
    const resource = focusedCodeEditor.getModel()?.uri;
    if (resource && !editors.some(({ editor }) => $oh($mL.getCanonicalUri(editor, { supportSideBySide: SideBySideEditor.PRIMARY }), resource))) {
      const model = textFileService.files.get(resource);
      if (!model?.isReadonly()) {
        await textFileService.save(resource, options3);
      }
    }
  }
}
function saveDirtyEditorsOfGroups(accessor, groups, options3) {
  const dirtyEditors = [];
  for (const group2 of groups) {
    for (const editor of group2.getEditors(
      0
      /* EditorsOrder.MOST_RECENTLY_ACTIVE */
    )) {
      if (editor.isDirty()) {
        dirtyEditors.push({ groupId: group2.id, editor });
      }
    }
  }
  return doSaveEditors(accessor, dirtyEditors, options3);
}
async function doSaveEditors(accessor, editors, options3) {
  const editorService = accessor.get($mJ);
  const notificationService = accessor.get($PJ);
  const instantiationService = accessor.get($Pk);
  try {
    await editorService.save(editors, options3);
  } catch (error) {
    if (!$kb(error)) {
      const actions = [$Zm({ id: "workbench.action.files.saveEditors", label: localize(7215, null), run: () => instantiationService.invokeFunction((accessor2) => doSaveEditors(accessor2, editors, options3)) })];
      const editorsToRevert = editors.filter(
        ({ editor }) => !editor.hasCapability(
          4
          /* EditorInputCapabilities.Untitled */
        )
        /* all except untitled to prevent unexpected data-loss */
      );
      if (editorsToRevert.length > 0) {
        actions.push($Zm({ id: "workbench.action.files.revertEditors", label: editorsToRevert.length > 1 ? localize(7216, null) : localize(7217, null), run: () => editorService.revert(editorsToRevert) }));
      }
      notificationService.notify({
        id: editors.map(({ editor }) => $Xi(editor.resource?.toString())).join(),
        // ensure unique notification ID per set of editor
        severity: Severity2.Error,
        message: localize(7218, null, editors.map(({ editor }) => editor.getName()).join(", "), $1m(error, false)),
        actions: { primary: actions }
      });
    }
  }
}
$0I.registerCommandAndKeybindingRule({
  when: void 0,
  weight: 200,
  primary: 2048 | 49,
  id: $Etb,
  handler: (accessor) => {
    return saveSelectedEditors(accessor, {
      reason: 1,
      force: true
      /* force save even when non-dirty */
    });
  }
});
$0I.registerCommandAndKeybindingRule({
  when: void 0,
  weight: 200,
  primary: $$e(
    2048 | 41,
    49
    /* KeyCode.KeyS */
  ),
  win: { primary: $$e(
    2048 | 41,
    2048 | 1024 | 49
    /* KeyCode.KeyS */
  ) },
  id: $Gtb,
  handler: (accessor) => {
    return saveSelectedEditors(accessor, { reason: 1, force: true, skipSaveParticipants: true });
  }
});
$0I.registerCommandAndKeybindingRule({
  id: $Ctb,
  weight: 200,
  when: void 0,
  primary: 2048 | 1024 | 49,
  handler: (accessor) => {
    return saveSelectedEditors(accessor, { reason: 1, saveAs: true });
  }
});
$0I.registerCommandAndKeybindingRule({
  when: void 0,
  weight: 200,
  primary: void 0,
  mac: {
    primary: 2048 | 512 | 49
    /* KeyCode.KeyS */
  },
  win: { primary: $$e(
    2048 | 41,
    49
    /* KeyCode.KeyS */
  ) },
  id: $Itb,
  handler: (accessor) => {
    return saveDirtyEditorsOfGroups(accessor, accessor.get($iJ).getGroups(
      1
      /* GroupsOrder.MOST_RECENTLY_ACTIVE */
    ), {
      reason: 1
      /* SaveReason.EXPLICIT */
    });
  }
});
$tn.registerCommand({
  id: $Ktb,
  handler: (accessor, _, editorContext) => {
    const editorGroupsService = accessor.get($iJ);
    const resolvedContext = $sub([editorContext], accessor.get($mJ), editorGroupsService, accessor.get($Deb));
    let groups = void 0;
    if (!resolvedContext.groupedEditors.length) {
      groups = editorGroupsService.getGroups(
        1
        /* GroupsOrder.MOST_RECENTLY_ACTIVE */
      );
    } else {
      groups = resolvedContext.groupedEditors.map(({ group: group2 }) => group2);
    }
    return saveDirtyEditorsOfGroups(accessor, groups, {
      reason: 1
      /* SaveReason.EXPLICIT */
    });
  }
});
$tn.registerCommand({
  id: $Ltb,
  handler: async (accessor) => {
    const editorService = accessor.get($mJ);
    const res = await editorService.saveAll({
      includeUntitled: false,
      reason: 1
      /* SaveReason.EXPLICIT */
    });
    return res.success;
  }
});
$tn.registerCommand({
  id: $ttb,
  handler: async (accessor) => {
    const editorGroupService = accessor.get($iJ);
    const editorService = accessor.get($mJ);
    let editors = $nvb(accessor);
    if (!editors) {
      const activeGroup = editorGroupService.activeGroup;
      if (activeGroup.activeEditor) {
        editors = [{ groupId: activeGroup.id, editor: activeGroup.activeEditor }];
      }
    }
    if (!editors || editors.length === 0) {
      return;
    }
    try {
      await editorService.revert(editors.filter(
        ({ editor }) => !editor.hasCapability(
          4
          /* EditorInputCapabilities.Untitled */
        )
        /* all except untitled */
      ), { force: true });
    } catch (error) {
      const notificationService = accessor.get($PJ);
      notificationService.error(localize(7219, null, editors.map(({ editor }) => editor.getName()).join(", "), $1m(error, false)));
    }
  }
});
$tn.registerCommand({
  id: $Rtb,
  handler: (accessor, resource) => {
    const contextService = accessor.get($Zk);
    const uriIdentityService = accessor.get($vl);
    const workspace2 = contextService.getWorkspace();
    const resources = $mvb(resource, accessor.get($Deb), accessor.get($mJ), accessor.get($iJ), accessor.get($kvb)).filter(
      (resource2) => workspace2.folders.some((folder) => uriIdentityService.extUri.isEqual(folder.uri, resource2))
      // Need to verify resources are workspaces since multi selection can trigger this command on some non workspace resources
    );
    if (resources.length === 0) {
      const commandService = accessor.get($sn);
      return commandService.executeCommand($3yb.ID);
    }
    const workspaceEditingService = accessor.get($zob);
    return workspaceEditingService.removeFolders(resources);
  }
});
$0I.registerCommandAndKeybindingRule({
  weight: 200 + 10,
  when: $7m.and($ktb, $gtb, $htb.negate()),
  primary: 15,
  id: $Ttb,
  handler: (accessor) => {
    const paneCompositeService = accessor.get($uqb);
    const viewlet = paneCompositeService.getActivePaneComposite(
      0
      /* ViewContainerLocation.Sidebar */
    );
    if (viewlet?.getId() !== $3sb) {
      return;
    }
    const explorer = viewlet.getViewPaneContainer();
    const view = explorer.getExplorerView();
    view.previousCompressedStat();
  }
});
$0I.registerCommandAndKeybindingRule({
  weight: 200 + 10,
  when: $7m.and($ktb, $gtb, $itb.negate()),
  primary: 17,
  id: $Utb,
  handler: (accessor) => {
    const paneCompositeService = accessor.get($uqb);
    const viewlet = paneCompositeService.getActivePaneComposite(
      0
      /* ViewContainerLocation.Sidebar */
    );
    if (viewlet?.getId() !== $3sb) {
      return;
    }
    const explorer = viewlet.getViewPaneContainer();
    const view = explorer.getExplorerView();
    view.nextCompressedStat();
  }
});
$0I.registerCommandAndKeybindingRule({
  weight: 200 + 10,
  when: $7m.and($ktb, $gtb, $htb.negate()),
  primary: 14,
  id: $Vtb,
  handler: (accessor) => {
    const paneCompositeService = accessor.get($uqb);
    const viewlet = paneCompositeService.getActivePaneComposite(
      0
      /* ViewContainerLocation.Sidebar */
    );
    if (viewlet?.getId() !== $3sb) {
      return;
    }
    const explorer = viewlet.getViewPaneContainer();
    const view = explorer.getExplorerView();
    view.firstCompressedStat();
  }
});
$0I.registerCommandAndKeybindingRule({
  weight: 200 + 10,
  when: $7m.and($ktb, $gtb, $itb.negate()),
  primary: 13,
  id: $Wtb,
  handler: (accessor) => {
    const paneCompositeService = accessor.get($uqb);
    const viewlet = paneCompositeService.getActivePaneComposite(
      0
      /* ViewContainerLocation.Sidebar */
    );
    if (viewlet?.getId() !== $3sb) {
      return;
    }
    const explorer = viewlet.getViewPaneContainer();
    const view = explorer.getExplorerView();
    view.lastCompressedStat();
  }
});
$0I.registerCommandAndKeybindingRule({
  weight: 200,
  when: null,
  primary: $r ? $l ? $$e(
    2048 | 41,
    44
    /* KeyCode.KeyN */
  ) : 2048 | 512 | 44 : 2048 | 44,
  secondary: $r ? [
    2048 | 44
    /* KeyCode.KeyN */
  ] : void 0,
  id: $Xtb,
  metadata: {
    description: $Ytb,
    args: [
      {
        isOptional: true,
        name: "New Untitled Text File arguments",
        description: "The editor view type or language ID if known",
        schema: {
          "type": "object",
          "properties": {
            "viewType": {
              "type": "string"
            },
            "languageId": {
              "type": "string"
            }
          }
        }
      }
    ]
  },
  handler: async (accessor, args2) => {
    const editorService = accessor.get($mJ);
    await editorService.openEditor({
      resource: void 0,
      options: {
        override: args2?.viewType,
        pinned: true
      },
      languageId: args2?.languageId
    });
  }
});
$tn.registerCommand({
  id: $Ztb,
  handler: async (accessor, args2) => {
    const editorService = accessor.get($mJ);
    const dialogService = accessor.get($1v);
    const fileService = accessor.get($km);
    const createFileLocalized = localize(7220, null);
    const defaultFileUri = $vh(await dialogService.defaultFilePath(), args2?.fileName ?? "Untitled.txt");
    const saveUri = await dialogService.showSaveDialog({ saveLabel: createFileLocalized, title: createFileLocalized, defaultUri: defaultFileUri });
    if (!saveUri) {
      return;
    }
    await fileService.createFile(saveUri, void 0, { overwrite: true });
    await editorService.openEditor({
      resource: saveUri,
      options: {
        override: args2?.viewType,
        pinned: true
      },
      languageId: args2?.languageId
    });
  }
});

// out-build/vs/workbench/contrib/files/browser/fileActions.contribution.js
$hJ($Ivb);
$hJ($Mvb);
$hJ($Nvb);
$hJ($Rvb);
$hJ($Qvb);
$hJ($Jvb);
$hJ($Ovb);
$hJ($Zvb);
$hJ($1vb);
$hJ($2vb);
$hJ($3vb);
$tn.registerCommand("_files.windowOpen", $ezb);
$tn.registerCommand("_files.newWindow", $fzb);
var explorerCommandsWeightBonus = 10;
var RENAME_ID = "renameFile";
$0I.registerCommandAndKeybindingRule({
  id: RENAME_ID,
  weight: 200 + explorerCommandsWeightBonus,
  when: $7m.and($ktb, $_sb.toNegated(), $9sb),
  primary: 60,
  mac: {
    primary: 3
    /* KeyCode.Enter */
  },
  handler: $Svb
});
var MOVE_FILE_TO_TRASH_ID = "moveFileToTrash";
$0I.registerCommandAndKeybindingRule({
  id: MOVE_FILE_TO_TRASH_ID,
  weight: 200 + explorerCommandsWeightBonus,
  when: $7m.and($ktb, $9sb, $btb),
  primary: 20,
  mac: {
    primary: 2048 | 1,
    secondary: [
      20
      /* KeyCode.Delete */
    ]
  },
  handler: $Tvb
});
var DELETE_FILE_ID = "deleteFile";
$0I.registerCommandAndKeybindingRule({
  id: DELETE_FILE_ID,
  weight: 200 + explorerCommandsWeightBonus,
  when: $7m.and($ktb, $9sb),
  primary: 1024 | 20,
  mac: {
    primary: 2048 | 512 | 1
    /* KeyCode.Backspace */
  },
  handler: $Uvb
});
$0I.registerCommandAndKeybindingRule({
  id: DELETE_FILE_ID,
  weight: 200 + explorerCommandsWeightBonus,
  when: $7m.and($ktb, $9sb, $btb.toNegated()),
  primary: 20,
  mac: {
    primary: 2048 | 1
    /* KeyCode.Backspace */
  },
  handler: $Uvb
});
var CUT_FILE_ID = "filesExplorer.cut";
$0I.registerCommandAndKeybindingRule({
  id: CUT_FILE_ID,
  weight: 200 + explorerCommandsWeightBonus,
  when: $7m.and($ktb, $_sb.toNegated(), $9sb),
  primary: 2048 | 54,
  handler: $Wvb
});
var COPY_FILE_ID = "filesExplorer.copy";
$0I.registerCommandAndKeybindingRule({
  id: COPY_FILE_ID,
  weight: 200 + explorerCommandsWeightBonus,
  when: $7m.and($ktb, $_sb.toNegated()),
  primary: 2048 | 33,
  handler: $Vvb
});
var PASTE_FILE_ID = "filesExplorer.paste";
$tn.registerCommand(PASTE_FILE_ID, $Xvb);
$0I.registerKeybindingRule({
  id: `^${PASTE_FILE_ID}`,
  // the `^` enables pasting files into the explorer by preventing default bubble up
  weight: 200 + explorerCommandsWeightBonus,
  when: $7m.and($ktb, $9sb),
  primary: 2048 | 52
});
$0I.registerCommandAndKeybindingRule({
  id: "filesExplorer.cancelCut",
  weight: 200 + explorerCommandsWeightBonus,
  when: $7m.and($ktb, $atb),
  primary: 9,
  handler: async (accessor) => {
    const explorerService = accessor.get($kvb);
    await explorerService.setToCopy([], true);
  }
});
$0I.registerCommandAndKeybindingRule({
  id: "filesExplorer.openFilePreserveFocus",
  weight: 200 + explorerCommandsWeightBonus,
  when: $7m.and($ktb, $7sb.toNegated()),
  primary: 10,
  handler: $Yvb
});
var copyPathCommand = {
  id: $Atb,
  title: localize(7085, null)
};
var copyRelativePathCommand = {
  id: $Btb,
  title: localize(7086, null)
};
var $gzb = {
  id: $stb,
  title: localize(7087, null)
};
$hzb($Atb, copyPathCommand.title, $lqb.IsFileSystemResource, "1_cutcopypaste", true);
$hzb($Btb, copyRelativePathCommand.title, $lqb.IsFileSystemResource, "1_cutcopypaste", true);
$hzb($gzb.id, $gzb.title, $lqb.IsFileSystemResource, "2_files", false, 1);
function $hzb(id2, title, when, group2, supportsMultiSelect, order) {
  const precondition2 = supportsMultiSelect !== true ? $Ppb.negate() : void 0;
  $dJ.appendMenuItem($bJ.EditorTitleContext, {
    command: { id: id2, title, precondition: precondition2 },
    when,
    group: group2,
    order
  });
}
appendSaveConflictEditorTitleAction("workbench.files.action.acceptLocalChanges", localize(7088, null), $6l.check, -10, $_vb);
appendSaveConflictEditorTitleAction("workbench.files.action.revertLocalChanges", localize(7089, null), $6l.discard, -9, $awb);
function appendSaveConflictEditorTitleAction(id2, title, icon2, order, command4) {
  $tn.registerCommand(id2, command4);
  $dJ.appendMenuItem($bJ.EditorTitle, {
    command: { id: id2, title, icon: icon2 },
    when: $7m.equals($9vb, true),
    group: "navigation",
    order
  });
}
function $izb({ id: id2, title, category: category8, metadata }, when) {
  $dJ.appendMenuItem($bJ.CommandPalette, {
    command: {
      id: id2,
      title,
      category: category8,
      metadata
    },
    when
  });
}
$izb({
  id: $Atb,
  title: localize2(7116, "Copy Path of Active File"),
  category: $qn.File
});
$izb({
  id: $Btb,
  title: localize2(7117, "Copy Relative Path of Active File"),
  category: $qn.File
});
$izb({
  id: $Etb,
  title: $Ftb,
  category: $qn.File
});
$izb({
  id: $Gtb,
  title: $Htb,
  category: $qn.File
});
$izb({
  id: $Ktb,
  title: localize2(7118, "Save All in Group"),
  category: $qn.File
});
$izb({
  id: $Ltb,
  title: localize2(7119, "Save All Files"),
  category: $qn.File
});
$izb({
  id: $ttb,
  title: localize2(7120, "Revert File"),
  category: $qn.File
});
$izb({
  id: $ztb,
  title: localize2(7121, "Compare Active File with Saved"),
  category: $qn.File,
  metadata: {
    description: localize2(7122, "Opens a new diff editor to compare the active file with the version on disk.")
  }
});
$izb({
  id: $Ctb,
  title: $Dtb,
  category: $qn.File
});
$izb({
  id: $tvb,
  title: $uvb,
  category: $qn.File
}, $fpb.notEqualsTo("0"));
$izb({
  id: $vvb,
  title: $wvb,
  category: $qn.File,
  metadata: { description: localize2(7123, "Create a new folder or directory") }
}, $fpb.notEqualsTo("0"));
$izb({
  id: $Xtb,
  title: $Ytb,
  category: $qn.File
});
var isFileOrUntitledResourceContextKey = $7m.or($lqb.IsFileSystemResource, $lqb.Scheme.isEqualTo(Schemas.untitled));
var openToSideCommand = {
  id: $utb,
  title: localize(7090, null)
};
$dJ.appendMenuItem($bJ.OpenEditorsContext, {
  group: "navigation",
  order: 10,
  command: openToSideCommand,
  when: isFileOrUntitledResourceContextKey
});
$dJ.appendMenuItem($bJ.OpenEditorsContext, {
  group: "1_open",
  order: 10,
  command: {
    id: $Kub,
    title: localize(7091, null)
  },
  when: $7m.and(
    // Editors with Available Choices to Open With
    $Epb,
    // Not: editor groups
    $Mtb.toNegated()
  )
});
$dJ.appendMenuItem($bJ.OpenEditorsContext, {
  group: "1_cutcopypaste",
  order: 10,
  command: copyPathCommand,
  when: $lqb.IsFileSystemResource
});
$dJ.appendMenuItem($bJ.OpenEditorsContext, {
  group: "1_cutcopypaste",
  order: 20,
  command: copyRelativePathCommand,
  when: $lqb.IsFileSystemResource
});
$dJ.appendMenuItem($bJ.OpenEditorsContext, {
  group: "2_save",
  order: 10,
  command: {
    id: $Etb,
    title: $Ftb,
    precondition: $Ntb
  },
  when: $7m.or(
    // Untitled Editors
    $lqb.Scheme.isEqualTo(Schemas.untitled),
    // Or:
    $7m.and(
      // Not: editor groups
      $Mtb.toNegated(),
      // Not: readonly editors
      $Otb.toNegated(),
      // Not: auto save after short delay
      $3J.toNegated()
    )
  )
});
$dJ.appendMenuItem($bJ.OpenEditorsContext, {
  group: "2_save",
  order: 20,
  command: {
    id: $ttb,
    title: localize(7092, null),
    precondition: $Ntb
  },
  when: $7m.and(
    // Not: editor groups
    $Mtb.toNegated(),
    // Not: readonly editors
    $Otb.toNegated(),
    // Not: untitled editors (revert closes them)
    $lqb.Scheme.notEqualsTo(Schemas.untitled),
    // Not: auto save after short delay
    $3J.toNegated()
  )
});
$dJ.appendMenuItem($bJ.OpenEditorsContext, {
  group: "2_save",
  order: 30,
  command: {
    id: $Ktb,
    title: localize(7093, null),
    precondition: $jpb
  },
  // Editor Group
  when: $Mtb
});
$dJ.appendMenuItem($bJ.OpenEditorsContext, {
  group: "3_compare",
  order: 10,
  command: {
    id: $ztb,
    title: localize(7094, null),
    precondition: $Ntb
  },
  when: $7m.and($lqb.IsFileSystemResource, $3J.toNegated(), $Neb.toNegated())
});
var compareResourceCommand = {
  id: $ytb,
  title: localize(7095, null)
};
$dJ.appendMenuItem($bJ.OpenEditorsContext, {
  group: "3_compare",
  order: 20,
  command: compareResourceCommand,
  when: $7m.and($lqb.HasResource, $Qtb, isFileOrUntitledResourceContextKey, $Neb.toNegated())
});
var selectForCompareCommand = {
  id: $wtb,
  title: localize(7096, null)
};
$dJ.appendMenuItem($bJ.OpenEditorsContext, {
  group: "3_compare",
  order: 30,
  command: selectForCompareCommand,
  when: $7m.and($lqb.HasResource, isFileOrUntitledResourceContextKey, $Neb.toNegated())
});
var compareSelectedCommand = {
  id: $xtb,
  title: localize(7097, null)
};
$dJ.appendMenuItem($bJ.OpenEditorsContext, {
  group: "3_compare",
  order: 30,
  command: compareSelectedCommand,
  when: $7m.and($lqb.HasResource, $Neb, $Ptb)
});
$dJ.appendMenuItem($bJ.EditorTitleContext, {
  group: "1_compare",
  order: 30,
  command: compareSelectedCommand,
  when: $7m.and($lqb.HasResource, $Qpb, $Rpb)
});
$dJ.appendMenuItem($bJ.OpenEditorsContext, {
  group: "4_close",
  order: 10,
  command: {
    id: $xub,
    title: localize(7098, null)
  },
  when: $Mtb.toNegated()
});
$dJ.appendMenuItem($bJ.OpenEditorsContext, {
  group: "4_close",
  order: 20,
  command: {
    id: $Aub,
    title: localize(7099, null)
  },
  when: $Mtb.toNegated()
});
$dJ.appendMenuItem($bJ.OpenEditorsContext, {
  group: "4_close",
  order: 30,
  command: {
    id: $tub,
    title: localize(7100, null)
  }
});
$dJ.appendMenuItem($bJ.OpenEditorsContext, {
  group: "4_close",
  order: 40,
  command: {
    id: $uub,
    title: localize(7101, null)
  }
});
$dJ.appendMenuItem($bJ.ExplorerContext, {
  group: "navigation",
  order: 4,
  command: {
    id: $tvb,
    title: $uvb,
    precondition: $9sb
  },
  when: $7sb
});
$dJ.appendMenuItem($bJ.ExplorerContext, {
  group: "navigation",
  order: 6,
  command: {
    id: $vvb,
    title: $wvb,
    precondition: $9sb
  },
  when: $7sb
});
$dJ.appendMenuItem($bJ.ExplorerContext, {
  group: "navigation",
  order: 10,
  command: openToSideCommand,
  when: $7m.and($7sb.toNegated(), $lqb.HasResource)
});
$dJ.appendMenuItem($bJ.ExplorerContext, {
  group: "navigation",
  order: 20,
  command: {
    id: $vtb,
    title: localize(7102, null)
  },
  when: $7m.and($7sb.toNegated(), $$sb)
});
$dJ.appendMenuItem($bJ.ExplorerContext, {
  group: "3_compare",
  order: 20,
  command: compareResourceCommand,
  when: $7m.and($7sb.toNegated(), $lqb.HasResource, $Qtb, $Neb.toNegated())
});
$dJ.appendMenuItem($bJ.ExplorerContext, {
  group: "3_compare",
  order: 30,
  command: selectForCompareCommand,
  when: $7m.and($7sb.toNegated(), $lqb.HasResource, $Neb.toNegated())
});
$dJ.appendMenuItem($bJ.ExplorerContext, {
  group: "3_compare",
  order: 30,
  command: compareSelectedCommand,
  when: $7m.and($7sb.toNegated(), $lqb.HasResource, $Neb)
});
$dJ.appendMenuItem($bJ.ExplorerContext, {
  group: "5_cutcopypaste",
  order: 8,
  command: {
    id: CUT_FILE_ID,
    title: localize(7103, null)
  },
  when: $7m.and($_sb.toNegated(), $9sb)
});
$dJ.appendMenuItem($bJ.ExplorerContext, {
  group: "5_cutcopypaste",
  order: 10,
  command: {
    id: COPY_FILE_ID,
    title: $zvb
  },
  when: $_sb.toNegated()
});
$dJ.appendMenuItem($bJ.ExplorerContext, {
  group: "5_cutcopypaste",
  order: 20,
  command: {
    id: PASTE_FILE_ID,
    title: $Avb,
    precondition: $7m.and($9sb, $Bvb)
  },
  when: $7sb
});
$dJ.appendMenuItem($bJ.ExplorerContext, {
  group: "5b_importexport",
  order: 10,
  command: {
    id: $Cvb,
    title: $Dvb
  },
  // --- Start PWB: disable file downloads ---
  when: $7m.and(
    $rpb,
    $7m.or(
      // native: for any remote resource
      $7m.and($veb.toNegated(), $lqb.Scheme.notEqualsTo(Schemas.file)),
      // web: for any files
      $7m.and($veb, $7sb.toNegated(), $_sb.toNegated()),
      // web: for any folders if file system API support is provided
      $7m.and($veb, $ppb)
    )
    // --- End PWB ---
  )
});
$dJ.appendMenuItem($bJ.ExplorerContext, {
  group: "5b_importexport",
  order: 20,
  command: {
    id: $Evb,
    title: $Fvb
  },
  when: $7m.and(
    // --- Start PWB: disable file downloads ---
    $spb,
    // --- End PWB ---
    // only in web
    $veb,
    // only on folders
    $7sb,
    // only on editable folders
    $9sb
  )
});
$dJ.appendMenuItem($bJ.ExplorerContext, {
  group: "6_copypath",
  order: 10,
  command: copyPathCommand,
  when: $lqb.IsFileSystemResource
});
$dJ.appendMenuItem($bJ.ExplorerContext, {
  group: "6_copypath",
  order: 20,
  command: copyRelativePathCommand,
  when: $lqb.IsFileSystemResource
});
$dJ.appendMenuItem($bJ.ExplorerContext, {
  group: "2_workspace",
  order: 10,
  command: {
    id: $Tyb,
    title: $Uyb
  },
  when: $7m.and($_sb, $7m.or($hpb, $epb.isEqualTo("workspace")))
});
$dJ.appendMenuItem($bJ.ExplorerContext, {
  group: "2_workspace",
  order: 30,
  command: {
    id: $Rtb,
    title: $Stb
  },
  when: $7m.and($_sb, $7sb, $7m.and($fpb.notEqualsTo("0"), $7m.or($hpb, $epb.isEqualTo("workspace"))))
});
$dJ.appendMenuItem($bJ.ExplorerContext, {
  group: "7_modification",
  order: 10,
  command: {
    id: RENAME_ID,
    title: $xvb,
    precondition: $9sb
  },
  when: $_sb.toNegated()
});
$dJ.appendMenuItem($bJ.ExplorerContext, {
  group: "7_modification",
  order: 20,
  command: {
    id: MOVE_FILE_TO_TRASH_ID,
    title: $yvb,
    precondition: $7m.and($9sb)
  },
  alt: {
    id: DELETE_FILE_ID,
    title: localize(7104, null),
    precondition: $7m.and($9sb)
  },
  when: $7m.and($_sb.toNegated(), $btb)
});
$dJ.appendMenuItem($bJ.ExplorerContext, {
  group: "7_modification",
  order: 20,
  command: {
    id: DELETE_FILE_ID,
    title: localize(7105, null),
    precondition: $9sb
  },
  when: $7m.and($_sb.toNegated(), $btb.toNegated())
});
for (const menuId of [$bJ.EmptyEditorGroupContext, $bJ.EditorTabsBarContext]) {
  $dJ.appendMenuItem(menuId, { command: { id: $Xtb, title: localize(7106, null) }, group: "1_file", order: 10 });
  $dJ.appendMenuItem(menuId, { command: { id: "workbench.action.quickOpen", title: localize(7107, null) }, group: "1_file", order: 20 });
}
$dJ.appendMenuItem($bJ.MenubarFileMenu, {
  group: "1_new",
  command: {
    id: $Xtb,
    title: localize(7108, null)
  },
  order: 1
});
$dJ.appendMenuItem($bJ.MenubarFileMenu, {
  group: "4_save",
  command: {
    id: $Etb,
    title: localize(7109, null),
    precondition: $7m.or($Dpb, $7m.and($6sb, $4pb))
  },
  order: 1
});
$dJ.appendMenuItem($bJ.MenubarFileMenu, {
  group: "4_save",
  command: {
    id: $Ctb,
    title: localize(7110, null),
    precondition: $7m.or($Dpb, $7m.and($6sb, $4pb))
  },
  order: 2
});
$dJ.appendMenuItem($bJ.MenubarFileMenu, {
  group: "4_save",
  command: {
    id: $Itb,
    title: localize(7111, null),
    precondition: $jpb
  },
  order: 3
});
$dJ.appendMenuItem($bJ.MenubarFileMenu, {
  group: "5_autosave",
  command: {
    id: $Jvb.ID,
    title: localize(7112, null),
    toggled: $7m.notEquals("config.files.autoSave", "off")
  },
  order: 1
});
$dJ.appendMenuItem($bJ.MenubarFileMenu, {
  group: "6_close",
  command: {
    id: $ttb,
    title: localize(7113, null),
    precondition: $7m.or(
      // Active editor can revert
      $7m.and($Bpb),
      // Explorer focused but not on untitled
      $7m.and($lqb.Scheme.notEqualsTo(Schemas.untitled), $6sb, $4pb)
    )
  },
  order: 1
});
$dJ.appendMenuItem($bJ.MenubarFileMenu, {
  group: "6_close",
  command: {
    id: $xub,
    title: localize(7114, null),
    precondition: $7m.or($Dpb, $7m.and($6sb, $4pb))
  },
  order: 2
});
$dJ.appendMenuItem($bJ.MenubarGoMenu, {
  group: "3_global_nav",
  command: {
    id: "workbench.action.quickOpen",
    title: localize(7115, null)
  },
  order: 1
});
$dJ.appendMenuItem($bJ.ChatAttachmentsContext, {
  group: "navigation",
  order: 10,
  command: openToSideCommand,
  when: $7m.and($lqb.HasResource, $7sb.toNegated())
});
$dJ.appendMenuItem($bJ.ChatAttachmentsContext, {
  group: "navigation",
  order: 20,
  command: $gzb,
  when: $lqb.IsFileSystemResource
});
$dJ.appendMenuItem($bJ.ChatAttachmentsContext, {
  group: "1_cutcopypaste",
  order: 10,
  command: copyPathCommand,
  when: $lqb.IsFileSystemResource
});
$dJ.appendMenuItem($bJ.ChatAttachmentsContext, {
  group: "1_cutcopypaste",
  order: 20,
  command: copyRelativePathCommand,
  when: $lqb.IsFileSystemResource
});
for (const menuId of [$bJ.ChatInlineResourceAnchorContext, $bJ.ChatInputResourceAttachmentContext]) {
  $dJ.appendMenuItem(menuId, {
    group: "navigation",
    order: 10,
    command: openToSideCommand,
    when: $7m.and($lqb.HasResource, $7sb.toNegated())
  });
  $dJ.appendMenuItem(menuId, {
    group: "navigation",
    order: 20,
    command: $gzb,
    when: $lqb.IsFileSystemResource
  });
  $dJ.appendMenuItem(menuId, {
    group: "1_cutcopypaste",
    order: 10,
    command: copyPathCommand,
    when: $lqb.IsFileSystemResource
  });
  $dJ.appendMenuItem(menuId, {
    group: "1_cutcopypaste",
    order: 20,
    command: copyRelativePathCommand,
    when: $lqb.IsFileSystemResource
  });
}

// out-build/vs/platform/request/common/request.js
var $9u = $Qk("requestService");
var LoggableHeaders = class {
  constructor(b) {
    this.b = b;
  }
  toJSON() {
    if (!this.a) {
      const headers = /* @__PURE__ */ Object.create(null);
      for (const key2 in this.b) {
        if (key2.toLowerCase() === "authorization" || key2.toLowerCase() === "proxy-authorization") {
          headers[key2] = "*****";
        } else {
          headers[key2] = this.b[key2];
        }
      }
      this.a = headers;
    }
    return this.a;
  }
};
var $0u = class extends $3c {
  constructor(b) {
    super();
    this.b = b;
    this.a = 0;
  }
  async c(options3, request) {
    const prefix = `[network] #${++this.a}: ${options3.url}`;
    this.b.trace(`${prefix} - begin`, options3.type, new LoggableHeaders(options3.headers ?? {}));
    try {
      const result = await request();
      this.b.trace(`${prefix} - end`, options3.type, result.res.statusCode, result.res.headers);
      return result;
    } catch (error) {
      this.b.error(`${prefix} - error`, options3.type, $qb(error));
      throw error;
    }
  }
};
function $$u(context) {
  return context.res.statusCode && context.res.statusCode >= 200 && context.res.statusCode < 300 || context.res.statusCode === 1223;
}
function $_u(context) {
  return context.res.statusCode === 204;
}
async function $av(context) {
  if ($_u(context)) {
    return null;
  }
  const buffer = await $Oi(context.stream);
  return buffer.toString();
}
async function $bv(context) {
  if (!$$u(context)) {
    throw new Error("Server returned " + context.res.statusCode);
  }
  return $av(context);
}
async function $cv(context) {
  if (!$$u(context)) {
    throw new Error("Server returned " + context.res.statusCode);
  }
  if ($_u(context)) {
    return null;
  }
  const buffer = await $Oi(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 configurationRegistry22 = $Wn.as($Ht.Configuration);
  const oldProxyConfiguration = proxyConfiguration;
  proxyConfiguration = {
    id: "http",
    order: 15,
    title: localize(2088, null),
    type: "object",
    scope,
    properties: {
      "http.proxy": {
        type: "string",
        pattern: "^(https?|socks|socks4a?|socks5h?)://([^:]*(:[^@]*)?@)?([^:]+|\\[[:0-9a-fA-F]+\\])(:\\d+)?/?$|^$",
        markdownDescription: localize(2089, null),
        restricted: true
      },
      "http.proxyStrictSSL": {
        type: "boolean",
        default: true,
        description: localize(2090, null),
        restricted: true
      },
      "http.proxyKerberosServicePrincipal": {
        type: "string",
        markdownDescription: localize(2091, null),
        restricted: true
      },
      "http.noProxy": {
        type: "array",
        items: { type: "string" },
        markdownDescription: localize(2092, null),
        restricted: true
      },
      "http.proxyAuthorization": {
        type: ["null", "string"],
        default: null,
        markdownDescription: localize(2093, null),
        restricted: true
      },
      "http.proxySupport": {
        type: "string",
        enum: ["off", "on", "fallback", "override"],
        enumDescriptions: [
          localize(2094, null),
          localize(2095, null),
          localize(2096, null),
          localize(2097, null)
        ],
        default: "override",
        description: localize(2098, null),
        restricted: true
      },
      "http.systemCertificates": {
        type: "boolean",
        default: true,
        description: localize(2099, null),
        restricted: true
      },
      "http.experimental.systemCertificatesV2": {
        type: "boolean",
        tags: ["experimental"],
        default: false,
        description: localize(2100, null),
        restricted: true
      },
      "http.electronFetch": {
        type: "boolean",
        default: false,
        description: localize(2101, null),
        restricted: true
      },
      "http.fetchAdditionalSupport": {
        type: "boolean",
        default: true,
        markdownDescription: localize(2102, null, "`#http.proxySupport#`", "`#http.systemCertificates#`"),
        restricted: true
      }
    }
  };
  configurationRegistry22.updateConfigurations({ add: [proxyConfiguration], remove: oldProxyConfiguration ? [oldProxyConfiguration] : [] });
}
registerProxyConfigurations(
  1
  /* ConfigurationScope.APPLICATION */
);

// out-build/vs/workbench/contrib/chat/common/chatAgents.js
var $4O_1;
var ChatAgentLocation;
(function(ChatAgentLocation2) {
  ChatAgentLocation2["Panel"] = "panel";
  ChatAgentLocation2["Terminal"] = "terminal";
  ChatAgentLocation2["Notebook"] = "notebook";
  ChatAgentLocation2["Editor"] = "editor";
  ChatAgentLocation2["EditingSession"] = "editing-session";
})(ChatAgentLocation || (ChatAgentLocation = {}));
(function(ChatAgentLocation2) {
  function fromRaw(value) {
    switch (value) {
      case "panel":
        return ChatAgentLocation2.Panel;
      case "terminal":
        return ChatAgentLocation2.Terminal;
      case "notebook":
        return ChatAgentLocation2.Notebook;
      case "editor":
        return ChatAgentLocation2.Editor;
      case "editing-session":
        return ChatAgentLocation2.EditingSession;
    }
    return ChatAgentLocation2.Panel;
  }
  ChatAgentLocation2.fromRaw = fromRaw;
})(ChatAgentLocation || (ChatAgentLocation = {}));
function $YO(obj) {
  return obj && ThemeIcon.isThemeIcon(obj.icon) && typeof obj.title === "string" && $dm(obj.message);
}
var $ZO = $Qk("chatAgentService");
var $1O = class $1O2 extends $3c {
  static {
    this.AGENT_LEADER = "@";
  }
  constructor(r2) {
    super();
    this.r = r2;
    this.b = /* @__PURE__ */ new Map();
    this.f = new $ze();
    this.onDidChangeAgents = this.f.event;
    this.g = /* @__PURE__ */ new Set();
    this.n = /* @__PURE__ */ new Map();
    this.u = /* @__PURE__ */ new Map();
    this.h = ChatContextKeys.enabled.bindTo(this.r);
    this.j = ChatContextKeys.panelParticipantRegistered.bindTo(this.r);
    this.m = ChatContextKeys.editingParticipantRegistered.bindTo(this.r);
    this.B(r2.onDidChangeContext((e) => {
      if (e.affectsSome(this.g)) {
        this.t();
      }
    }));
  }
  registerAgent(id2, data) {
    const existingAgent = this.getAgent(id2);
    if (existingAgent) {
      throw new Error(`Agent already registered: ${JSON.stringify(id2)}`);
    }
    const that = this;
    const commands2 = data.slashCommands;
    data = {
      ...data,
      get slashCommands() {
        return commands2.filter((c) => !c.when || that.r.contextMatchesRules($7m.deserialize(c.when)));
      }
    };
    const entry = { data };
    this.b.set(id2, entry);
    this.s();
    this.t();
    this.f.fire(void 0);
    return $1c(() => {
      this.b.delete(id2);
      this.s();
      this.t();
      this.f.fire(void 0);
    });
  }
  s() {
    this.g.clear();
    for (const agent of this.b.values()) {
      if (agent.data.when) {
        const expr = $7m.deserialize(agent.data.when);
        for (const key2 of expr?.keys() || []) {
          this.g.add(key2);
        }
      }
    }
  }
  t() {
    let editingAgentRegistered = false;
    let defaultAgentRegistered = false;
    for (const agent of this.getAgents()) {
      if (agent.isDefault && agent.locations.includes(ChatAgentLocation.EditingSession)) {
        editingAgentRegistered = true;
      } else if (agent.isDefault) {
        defaultAgentRegistered = true;
      }
    }
    this.m.set(editingAgentRegistered);
    this.j.set(defaultAgentRegistered);
  }
  registerAgentImplementation(id2, agentImpl) {
    const entry = this.b.get(id2);
    if (!entry) {
      throw new Error(`Unknown agent: ${JSON.stringify(id2)}`);
    }
    if (entry.impl) {
      throw new Error(`Agent already has implementation: ${JSON.stringify(id2)}`);
    }
    if (entry.data.isDefault) {
      this.h.set(true);
    }
    entry.impl = agentImpl;
    this.f.fire(new $2O(entry.data, agentImpl));
    return $1c(() => {
      entry.impl = void 0;
      this.f.fire(void 0);
      if (entry.data.isDefault) {
        this.h.set(false);
      }
    });
  }
  registerDynamicAgent(data, agentImpl) {
    data.isDynamic = true;
    const agent = { data, impl: agentImpl };
    this.b.set(data.id, agent);
    this.f.fire(new $2O(data, agentImpl));
    return $1c(() => {
      this.b.delete(data.id);
      this.f.fire(void 0);
    });
  }
  registerAgentCompletionProvider(id2, provider) {
    this.u.set(id2, provider);
    return {
      dispose: () => {
        this.u.delete(id2);
      }
    };
  }
  async getAgentCompletionItems(id2, query, token) {
    return await this.u.get(id2)?.(query, token) ?? [];
  }
  updateAgent(id2, updateMetadata) {
    const agent = this.b.get(id2);
    if (!agent?.impl) {
      throw new Error(`No activated agent with id ${JSON.stringify(id2)} registered`);
    }
    agent.data.metadata = { ...agent.data.metadata, ...updateMetadata };
    this.f.fire(new $2O(agent.data, agent.impl));
  }
  getDefaultAgent(location3) {
    return $1(this.getActivatedAgents(), (a) => !!a.isDefault && a.locations.includes(location3));
  }
  getContributedDefaultAgent(location3) {
    return this.getAgents().find((a) => !!a.isDefault && a.locations.includes(location3));
  }
  getSecondaryAgent() {
    return Iterable.find(this.b.values(), (a) => !!a.data.metadata.isSecondary)?.data;
  }
  getAgent(id2, includeDisabled = false) {
    if (!this.w(id2) && !includeDisabled) {
      return;
    }
    return this.b.get(id2)?.data;
  }
  w(id2) {
    const entry = this.b.get(id2);
    return !entry?.data.when || this.r.contextMatchesRules($7m.deserialize(entry.data.when));
  }
  getAgentByFullyQualifiedId(id2) {
    const agent = Iterable.find(this.b.values(), (a) => $5O(a.data) === id2)?.data;
    if (agent && !this.w(agent.id)) {
      return;
    }
    return agent;
  }
  /**
   * Returns all agent datas that exist- static registered and dynamic ones.
   */
  getAgents() {
    return Array.from(this.b.values()).map((entry) => entry.data).filter((a) => this.w(a.id));
  }
  getActivatedAgents() {
    return Array.from(this.b.values()).filter((a) => !!a.impl).filter((a) => this.w(a.data.id)).map((a) => new $2O(a.data, a.impl));
  }
  getAgentsByName(name) {
    return this.getAgents().filter((a) => a.name === name);
  }
  agentHasDupeName(id2) {
    const agent = this.getAgent(id2);
    if (!agent) {
      return false;
    }
    return this.getAgentsByName(agent.name).filter((a) => a.extensionId.value !== agent.extensionId.value).length > 0;
  }
  async invokeAgent(id2, request, progress, history, token) {
    const data = this.b.get(id2);
    if (!data?.impl) {
      throw new Error(`No activated agent with id "${id2}"`);
    }
    return await data.impl.invoke(request, progress, history, token);
  }
  async getFollowups(id2, request, result, history, token) {
    const data = this.b.get(id2);
    if (!data?.impl) {
      throw new Error(`No activated agent with id "${id2}"`);
    }
    if (!data.impl?.provideFollowups) {
      return [];
    }
    return data.impl.provideFollowups(request, result, history, token);
  }
  async getChatTitle(id2, history, token) {
    const data = this.b.get(id2);
    if (!data?.impl) {
      throw new Error(`No activated agent with id "${id2}"`);
    }
    if (!data.impl?.provideChatTitle) {
      return void 0;
    }
    return data.impl.provideChatTitle(history, token);
  }
  registerChatParticipantDetectionProvider(handle2, provider) {
    this.n.set(handle2, provider);
    return $1c(() => {
      this.n.delete(handle2);
    });
  }
  hasChatParticipantDetectionProviders() {
    return this.n.size > 0;
  }
  async detectAgentOrCommand(request, history, options3, token) {
    const provider = Iterable.first(this.n.values());
    if (!provider) {
      return;
    }
    const participants = this.getAgents().reduce((acc, a) => {
      if (a.locations.includes(options3.location)) {
        acc.push({ participant: a.id, disambiguation: a.disambiguation ?? [] });
        for (const command5 of a.slashCommands) {
          acc.push({ participant: a.id, command: command5.name, disambiguation: command5.disambiguation ?? [] });
        }
      }
      return acc;
    }, []);
    const result = await provider.provideParticipantDetection(request, history, { ...options3, participants }, token);
    if (!result) {
      return;
    }
    const agent = this.getAgent(result.participant);
    if (!agent) {
      return;
    }
    if (!result.command) {
      return { agent };
    }
    const command4 = agent?.slashCommands.find((c) => c.name === result.command);
    if (!command4) {
      return;
    }
    return { agent, command: command4 };
  }
};
$1O = __decorate([
  __param(0, $on)
], $1O);
var $2O = class {
  constructor(b, d) {
    this.b = b;
    this.d = d;
  }
  get id() {
    return this.b.id;
  }
  get name() {
    return this.b.name ?? "";
  }
  get fullName() {
    return this.b.fullName ?? "";
  }
  get description() {
    return this.b.description ?? "";
  }
  get extensionId() {
    return this.b.extensionId;
  }
  get extensionPublisherId() {
    return this.b.extensionPublisherId;
  }
  get extensionPublisherDisplayName() {
    return this.b.publisherDisplayName;
  }
  get extensionDisplayName() {
    return this.b.extensionDisplayName;
  }
  get isDefault() {
    return this.b.isDefault;
  }
  get metadata() {
    return this.b.metadata;
  }
  get slashCommands() {
    return this.b.slashCommands;
  }
  get locations() {
    return this.b.locations;
  }
  get disambiguation() {
    return this.b.disambiguation;
  }
  async invoke(request, progress, history, token) {
    return this.d.invoke(request, progress, history, token);
  }
  async provideFollowups(request, result, history, token) {
    if (this.d.provideFollowups) {
      return this.d.provideFollowups(request, result, history, token);
    }
    return [];
  }
  provideWelcomeMessage(token) {
    if (this.d.provideWelcomeMessage) {
      return this.d.provideWelcomeMessage(token);
    }
    return void 0;
  }
  provideSampleQuestions(location3, token) {
    if (this.d.provideSampleQuestions) {
      return this.d.provideSampleQuestions(location3, token);
    }
    return void 0;
  }
  toJSON() {
    return this.b;
  }
};
var $3O = $Qk("chatAgentNameService");
var $4O = class $4O2 {
  static {
    $4O_1 = this;
  }
  static {
    this.b = "chat.participantNameRegistry";
  }
  constructor(productService, h3, i2, j) {
    this.h = h3;
    this.i = i2;
    this.j = j;
    this.f = $he(this, /* @__PURE__ */ Object.create(null));
    this.g = false;
    if (!productService.chatParticipantRegistry) {
      return;
    }
    this.d = productService.chatParticipantRegistry;
    const raw = j.get(
      $4O_1.b,
      -1
      /* StorageScope.APPLICATION */
    );
    try {
      this.f.set(JSON.parse(raw ?? "{}"), void 0);
    } catch (err) {
      j.remove(
        $4O_1.b,
        -1
        /* StorageScope.APPLICATION */
      );
    }
    this.k();
  }
  k() {
    if (this.g) {
      return;
    }
    this.l().catch((err) => this.i.warn("Failed to fetch chat participant registry", err)).then(() => $Wh(5 * 60 * 1e3)).then(() => this.k());
  }
  async l() {
    const context = await this.h.request({ type: "GET", url: this.d }, CancellationToken.None);
    if (context.res.statusCode !== 200) {
      throw new Error("Could not get extensions report.");
    }
    const result = await $cv(context);
    if (!result || result.version !== 1) {
      throw new Error("Unexpected chat participant registry response.");
    }
    const registry4 = result.restrictedChatParticipants;
    this.f.set(registry4, void 0);
    this.j.store(
      $4O_1.b,
      JSON.stringify(registry4),
      -1,
      1
      /* StorageTarget.MACHINE */
    );
  }
  /**
   * Returns true if the agent is allowed to use this name
   */
  getAgentNameRestriction(chatAgentData) {
    const nameAllowed = this.m(chatAgentData.name, chatAgentData).get();
    const fullNameAllowed = !chatAgentData.fullName || this.m(chatAgentData.fullName.replace(/\s/g, ""), chatAgentData).get();
    return nameAllowed && fullNameAllowed;
  }
  m(name, chatAgentData) {
    const allowList = this.f.map((registry4) => registry4[name.toLowerCase()]);
    return allowList.map((allowList2) => {
      if (!allowList2) {
        return true;
      }
      return allowList2.some((id2) => $1f(id2, id2.includes(".") ? chatAgentData.extensionId.value : chatAgentData.extensionPublisherId));
    });
  }
  dispose() {
    this.g = true;
  }
};
$4O = $4O_1 = __decorate([
  __param(0, $Vu),
  __param(1, $9u),
  __param(2, $wn),
  __param(3, $jv)
], $4O);
function $5O(chatAgentData) {
  return `${chatAgentData.extensionId.value}.${chatAgentData.id}`;
}
function $6O(raw) {
  const agent = "name" in raw ? raw : {
    ...raw,
    name: raw.id
  };
  if (!("extensionPublisherId" in agent)) {
    agent.extensionPublisherId = agent.extensionPublisher ?? "";
  }
  if (!("extensionDisplayName" in agent)) {
    agent.extensionDisplayName = "";
  }
  if (!("extensionId" in agent)) {
    agent.extensionId = new $5z("");
  }
  return $cu(agent);
}

// out-build/vs/workbench/contrib/chat/common/chatEditingService.js
var $$O = $Qk("chatEditingService");
var WorkingSetEntryRemovalReason;
(function(WorkingSetEntryRemovalReason2) {
  WorkingSetEntryRemovalReason2[WorkingSetEntryRemovalReason2["User"] = 0] = "User";
  WorkingSetEntryRemovalReason2[WorkingSetEntryRemovalReason2["Programmatic"] = 1] = "Programmatic";
})(WorkingSetEntryRemovalReason || (WorkingSetEntryRemovalReason = {}));
var WorkingSetEntryState;
(function(WorkingSetEntryState2) {
  WorkingSetEntryState2[WorkingSetEntryState2["Modified"] = 0] = "Modified";
  WorkingSetEntryState2[WorkingSetEntryState2["Accepted"] = 1] = "Accepted";
  WorkingSetEntryState2[WorkingSetEntryState2["Rejected"] = 2] = "Rejected";
  WorkingSetEntryState2[WorkingSetEntryState2["Transient"] = 3] = "Transient";
  WorkingSetEntryState2[WorkingSetEntryState2["Attached"] = 4] = "Attached";
  WorkingSetEntryState2[WorkingSetEntryState2["Sent"] = 5] = "Sent";
  WorkingSetEntryState2[WorkingSetEntryState2["Suggested"] = 6] = "Suggested";
})(WorkingSetEntryState || (WorkingSetEntryState = {}));
var ChatEditingSessionChangeType;
(function(ChatEditingSessionChangeType2) {
  ChatEditingSessionChangeType2[ChatEditingSessionChangeType2["WorkingSet"] = 0] = "WorkingSet";
  ChatEditingSessionChangeType2[ChatEditingSessionChangeType2["Other"] = 1] = "Other";
})(ChatEditingSessionChangeType || (ChatEditingSessionChangeType = {}));
var ChatEditingSessionState;
(function(ChatEditingSessionState2) {
  ChatEditingSessionState2[ChatEditingSessionState2["Initial"] = 0] = "Initial";
  ChatEditingSessionState2[ChatEditingSessionState2["StreamingEdits"] = 1] = "StreamingEdits";
  ChatEditingSessionState2[ChatEditingSessionState2["Idle"] = 2] = "Idle";
  ChatEditingSessionState2[ChatEditingSessionState2["Disposed"] = 3] = "Disposed";
})(ChatEditingSessionState || (ChatEditingSessionState = {}));
var $_O = "chat-editing-multi-diff-source";
var $aP = new $nn("chatEditingWidgetFileState", void 0, localize(5100, null));
var $bP = new $nn("decidedChatEditingResource", []);
var $cP = new $nn("chatEditingResource", void 0);
var $dP = new $nn("inChatEditingSession", void 0);
var $eP = new $nn("isApplyingChatEdits", void 0);
var $fP = new $nn("hasUndecidedChatEditingResource", false);
var $gP = new $nn("hasAppliedChatEdits", false);
var $hP = new $nn("applyingChatEditsFailed", false);
var $iP = "chatEditingSessionFileLimit";
var $jP = 10;
var ChatEditKind;
(function(ChatEditKind2) {
  ChatEditKind2[ChatEditKind2["Created"] = 0] = "Created";
  ChatEditKind2[ChatEditKind2["Modified"] = 1] = "Modified";
})(ChatEditKind || (ChatEditKind = {}));
function $kP(thing) {
  return typeof thing === "object" && !!thing && "sessionId" in thing;
}

// out-build/vs/workbench/contrib/chat/common/chatParserTypes.js
function $uO(request) {
  const message = request.parts.map((r2) => r2.promptText).join("").trimStart();
  const diff3 = request.text.length - message.length;
  return { message, diff: diff3 };
}
var $vO = class _$vO {
  static {
    this.Kind = "text";
  }
  constructor(range, editorRange, text2) {
    this.range = range;
    this.editorRange = editorRange;
    this.text = text2;
    this.kind = _$vO.Kind;
  }
  get promptText() {
    return this.text;
  }
};
var $wO = "#";
var $xO = "@";
var $yO = "/";
var $zO = class _$zO {
  static {
    this.Kind = "var";
  }
  constructor(range, editorRange, variableName, variableArg, variableId) {
    this.range = range;
    this.editorRange = editorRange;
    this.variableName = variableName;
    this.variableArg = variableArg;
    this.variableId = variableId;
    this.kind = _$zO.Kind;
  }
  get text() {
    const argPart = this.variableArg ? `:${this.variableArg}` : "";
    return `${$wO}${this.variableName}${argPart}`;
  }
  get promptText() {
    return this.text;
  }
};
var $AO = class _$AO {
  static {
    this.Kind = "tool";
  }
  constructor(range, editorRange, toolName, toolId, displayName, icon2) {
    this.range = range;
    this.editorRange = editorRange;
    this.toolName = toolName;
    this.toolId = toolId;
    this.displayName = displayName;
    this.icon = icon2;
    this.kind = _$AO.Kind;
  }
  get text() {
    return `${$wO}${this.toolName}`;
  }
  get promptText() {
    return this.text;
  }
};
var $BO = class _$BO {
  static {
    this.Kind = "agent";
  }
  constructor(range, editorRange, agent) {
    this.range = range;
    this.editorRange = editorRange;
    this.agent = agent;
    this.kind = _$BO.Kind;
  }
  get text() {
    return `${$xO}${this.agent.name}`;
  }
  get promptText() {
    return "";
  }
};
var $CO = class _$CO {
  static {
    this.Kind = "subcommand";
  }
  constructor(range, editorRange, command4) {
    this.range = range;
    this.editorRange = editorRange;
    this.command = command4;
    this.kind = _$CO.Kind;
  }
  get text() {
    return `${$yO}${this.command.name}`;
  }
  get promptText() {
    return "";
  }
};
var $DO = class _$DO {
  static {
    this.Kind = "slash";
  }
  constructor(range, editorRange, slashCommand) {
    this.range = range;
    this.editorRange = editorRange;
    this.slashCommand = slashCommand;
    this.kind = _$DO.Kind;
  }
  get text() {
    return `${$yO}${this.slashCommand.command}`;
  }
  get promptText() {
    return `${$yO}${this.slashCommand.command}`;
  }
};
var $EO = class _$EO {
  static {
    this.Kind = "dynamic";
  }
  constructor(range, editorRange, text2, id2, modelDescription, data, fullName, icon2, isFile) {
    this.range = range;
    this.editorRange = editorRange;
    this.text = text2;
    this.id = id2;
    this.modelDescription = modelDescription;
    this.data = data;
    this.fullName = fullName;
    this.icon = icon2;
    this.isFile = isFile;
    this.kind = _$EO.Kind;
  }
  get referenceText() {
    return this.text.replace($wO, "");
  }
  get promptText() {
    return this.text;
  }
};
function $FO(serialized) {
  return {
    text: serialized.text,
    parts: serialized.parts.map((part) => {
      if (part.kind === $vO.Kind) {
        return new $vO(new $0C(part.range.start, part.range.endExclusive), part.editorRange, part.text);
      } else if (part.kind === $zO.Kind) {
        return new $zO(new $0C(part.range.start, part.range.endExclusive), part.editorRange, part.variableName, part.variableArg, part.variableId || "");
      } else if (part.kind === $AO.Kind) {
        return new $AO(new $0C(part.range.start, part.range.endExclusive), part.editorRange, part.toolName, part.toolId, part.displayName, part.icon);
      } else if (part.kind === $BO.Kind) {
        let agent = part.agent;
        agent = $6O(agent);
        return new $BO(new $0C(part.range.start, part.range.endExclusive), part.editorRange, agent);
      } else if (part.kind === $CO.Kind) {
        return new $CO(new $0C(part.range.start, part.range.endExclusive), part.editorRange, part.command);
      } else if (part.kind === $DO.Kind) {
        return new $DO(new $0C(part.range.start, part.range.endExclusive), part.editorRange, part.slashCommand);
      } else if (part.kind === $EO.Kind) {
        return new $EO(new $0C(part.range.start, part.range.endExclusive), part.editorRange, part.text, part.id, part.modelDescription, $cu(part.data), part.fullName, part.icon, part.isFile);
      } else {
        throw new Error(`Unknown chat request part: ${part.kind}`);
      }
    })
  };
}
function $GO(parsed) {
  const agentPart = parsed.parts.find((r2) => r2 instanceof $BO);
  const commandPart = parsed.parts.find((r2) => r2 instanceof $CO);
  return { agentPart, commandPart };
}
function $HO(chatAgentService, location3, prompt, participant = null, command4 = null) {
  let question = "";
  if (participant && participant !== chatAgentService.getDefaultAgent(location3)?.id) {
    const agent = chatAgentService.getAgent(participant);
    if (!agent) {
      return void 0;
    }
    question += `${$xO}${agent.name} `;
    if (command4) {
      question += `${$yO}${command4} `;
    }
  }
  return question + prompt;
}

// out-build/vs/workbench/contrib/chat/common/chatService.js
function $oO(obj) {
  return !!obj && typeof obj === "object" && "uri" in obj && obj.uri instanceof URI && "version" in obj && typeof obj.version === "number" && "ranges" in obj && Array.isArray(obj.ranges) && obj.ranges.every($9C.isIRange);
}
function $pO(obj) {
  return !!obj && typeof obj === "object" && "documents" in obj && Array.isArray(obj.documents) && obj.documents.every($oO);
}
var ChatResponseReferencePartStatusKind2;
(function(ChatResponseReferencePartStatusKind3) {
  ChatResponseReferencePartStatusKind3[ChatResponseReferencePartStatusKind3["Complete"] = 1] = "Complete";
  ChatResponseReferencePartStatusKind3[ChatResponseReferencePartStatusKind3["Partial"] = 2] = "Partial";
  ChatResponseReferencePartStatusKind3[ChatResponseReferencePartStatusKind3["Omitted"] = 3] = "Omitted";
})(ChatResponseReferencePartStatusKind2 || (ChatResponseReferencePartStatusKind2 = {}));
var ChatAgentVoteDirection;
(function(ChatAgentVoteDirection2) {
  ChatAgentVoteDirection2[ChatAgentVoteDirection2["Down"] = 0] = "Down";
  ChatAgentVoteDirection2[ChatAgentVoteDirection2["Up"] = 1] = "Up";
})(ChatAgentVoteDirection || (ChatAgentVoteDirection = {}));
var ChatAgentVoteDownReason;
(function(ChatAgentVoteDownReason2) {
  ChatAgentVoteDownReason2["IncorrectCode"] = "incorrectCode";
  ChatAgentVoteDownReason2["DidNotFollowInstructions"] = "didNotFollowInstructions";
  ChatAgentVoteDownReason2["IncompleteCode"] = "incompleteCode";
  ChatAgentVoteDownReason2["MissingContext"] = "missingContext";
  ChatAgentVoteDownReason2["PoorlyWrittenOrFormatted"] = "poorlyWrittenOrFormatted";
  ChatAgentVoteDownReason2["RefusedAValidRequest"] = "refusedAValidRequest";
  ChatAgentVoteDownReason2["OffensiveOrUnsafe"] = "offensiveOrUnsafe";
  ChatAgentVoteDownReason2["Other"] = "other";
  ChatAgentVoteDownReason2["WillReportIssue"] = "willReportIssue";
})(ChatAgentVoteDownReason || (ChatAgentVoteDownReason = {}));
var ChatCopyKind2;
(function(ChatCopyKind3) {
  ChatCopyKind3[ChatCopyKind3["Action"] = 1] = "Action";
  ChatCopyKind3[ChatCopyKind3["Toolbar"] = 2] = "Toolbar";
})(ChatCopyKind2 || (ChatCopyKind2 = {}));
var $qO = $Qk("IChatService");
var $rO = "accessibility.voice.keywordActivation";

// out-build/vs/workbench/contrib/chat/common/chatModel.js
var $SO_1;
function $JO(obj) {
  return obj.kind === "paste";
}
var nonHistoryKinds = /* @__PURE__ */ new Set(["toolInvocation", "toolInvocationSerialized"]);
function isChatProgressHistoryResponseContent(content) {
  return !nonHistoryKinds.has(content.kind);
}
function $LO(content) {
  return content.filter(isChatProgressHistoryResponseContent);
}
var $MO = class {
  get session() {
    return this.a;
  }
  get username() {
    return this.session.requesterUsername;
  }
  get avatarIconUri() {
    return this.session.requesterAvatarIconUri;
  }
  get attempt() {
    return this.d;
  }
  get variableData() {
    return this.b;
  }
  set variableData(v) {
    this.b = v;
  }
  get confirmation() {
    return this.e;
  }
  get locationData() {
    return this.f;
  }
  get attachedContext() {
    return this.g;
  }
  get workingSet() {
    return this.h;
  }
  constructor(a, message, b, timestamp, d = 0, e, f, g, h3, isCompleteAddedRequest = false, restoredId) {
    this.a = a;
    this.message = message;
    this.b = b;
    this.timestamp = timestamp;
    this.d = d;
    this.e = e;
    this.f = f;
    this.g = g;
    this.h = h3;
    this.isCompleteAddedRequest = isCompleteAddedRequest;
    this.isHidden = false;
    this.id = restoredId ?? "request_" + $ps();
  }
  adoptTo(session) {
    this.a = session;
  }
};
var $NO = class extends $3c {
  get onDidChangeValue() {
    return this.a.event;
  }
  get value() {
    return this.b;
  }
  constructor(value) {
    super();
    this.a = this.B(new $ze());
    this.f = "";
    this.g = "";
    this.h = [];
    this.b = $5b(value).map((v) => $dm(v) ? { content: v, kind: "markdownContent" } : "kind" in v ? v : { kind: "treeData", treeData: v });
    this.j(true);
  }
  toString() {
    return this.f;
  }
  /**
   * _Just_ the content of markdown parts in the response
   */
  getMarkdown() {
    return this.g;
  }
  clear() {
    this.b = [];
    this.j(true);
  }
  updateContent(progress, quiet) {
    if (progress.kind === "markdownContent") {
      const lastResponsePart = this.b.filter((p) => p.kind !== "textEditGroup").at(-1);
      if (!lastResponsePart || lastResponsePart.kind !== "markdownContent" || !$UO(lastResponsePart.content, progress.content)) {
        this.b.push(progress);
      } else {
        lastResponsePart.content = $VO(lastResponsePart.content, progress.content);
      }
      this.j(quiet);
    } else if (progress.kind === "textEdit") {
      let found = false;
      for (let i2 = 0; !found && i2 < this.b.length; i2++) {
        const candidate = this.b[i2];
        if (candidate.kind === "textEditGroup" && $oh(candidate.uri, progress.uri)) {
          candidate.edits.push(progress.edits);
          candidate.done = progress.done;
          found = true;
        }
      }
      if (!found) {
        this.b.push({
          kind: "textEditGroup",
          uri: progress.uri,
          edits: [progress.edits],
          done: progress.done
        });
      }
      this.j(quiet);
    } else if (progress.kind === "progressTask") {
      const responsePosition = this.b.push(progress) - 1;
      this.j(quiet);
      const disp = progress.onDidAddProgress(() => {
        this.j(false);
      });
      progress.task?.().then((content) => {
        disp.dispose();
        if (typeof content === "string") {
          this.b[responsePosition].content = new $bm(content);
        }
        this.j(false);
      });
    } else {
      this.b.push(progress);
      this.j(quiet);
    }
  }
  addCitation(citation) {
    this.h.push(citation);
    this.j();
  }
  j(quiet) {
    const inlineRefToRepr = (part) => "uri" in part.inlineReference ? $sh(part.inlineReference.uri) : "name" in part.inlineReference ? part.inlineReference.name : $sh(part.inlineReference);
    this.f = this.b.map((part) => {
      if (part.kind === "treeData") {
        return "";
      } else if (part.kind === "inlineReference") {
        return inlineRefToRepr(part);
      } else if (part.kind === "command") {
        return part.command.title;
      } else if (part.kind === "textEditGroup") {
        return localize(5101, null);
      } else if (part.kind === "progressMessage" || part.kind === "codeblockUri" || part.kind === "toolInvocation" || part.kind === "toolInvocationSerialized") {
        return "";
      } else if (part.kind === "confirmation") {
        return `${part.title}
${part.message}`;
      } else {
        return part.content.value;
      }
    }).filter((s) => s.length > 0).join("\n\n");
    this.f += this.h.length ? "\n\n" + $WO(this.h) : "";
    this.g = this.b.map((part) => {
      if (part.kind === "inlineReference") {
        return inlineRefToRepr(part);
      } else if (part.kind === "markdownContent" || part.kind === "markdownVuln") {
        return part.content.value;
      } else {
        return "";
      }
    }).filter((s) => s.length > 0).join("");
    if (!quiet) {
      this.a.fire();
    }
  }
};
var $OO = class extends $3c {
  get session() {
    return this.u;
  }
  get isHidden() {
    return this.H;
  }
  get isComplete() {
    return this.z;
  }
  set isHidden(hidden) {
    this.H = hidden;
    this.a.fire();
  }
  get isCanceled() {
    return this.C;
  }
  get vote() {
    return this.D;
  }
  get voteDownReason() {
    return this.F;
  }
  get followups() {
    return this.f;
  }
  get response() {
    return this.b;
  }
  get result() {
    return this.G;
  }
  get username() {
    return this.session.responderUsername;
  }
  get avatarIcon() {
    return this.session.responderAvatarIcon;
  }
  get agent() {
    return this.w;
  }
  get slashCommand() {
    return this.y;
  }
  get agentOrSlashCommandDetected() {
    return this.g ?? false;
  }
  get usedContext() {
    return this.h;
  }
  get contentReferences() {
    return Array.from(this.j);
  }
  get codeCitations() {
    return this.m;
  }
  get progressMessages() {
    return this.n;
  }
  get isStale() {
    return this.t;
  }
  constructor(_response, u, w, y, requestId, z = false, C = false, D, F, G, followups, isCompleteAddedRequest = false, H = false, restoredId) {
    super();
    this.u = u;
    this.w = w;
    this.y = y;
    this.requestId = requestId;
    this.z = z;
    this.C = C;
    this.D = D;
    this.F = F;
    this.G = G;
    this.isCompleteAddedRequest = isCompleteAddedRequest;
    this.H = H;
    this.a = this.B(new $ze());
    this.onDidChange = this.a.event;
    this.j = [];
    this.m = [];
    this.n = [];
    this.t = false;
    this.t = Array.isArray(_response) && (_response.length !== 0 || $dm(_response) && _response.value.length !== 0);
    this.f = followups ? [...followups] : void 0;
    this.b = this.B(new $NO(_response));
    this.B(this.b.onDidChangeValue(() => this.a.fire()));
    this.id = restoredId ?? "response_" + $ps();
  }
  /**
   * Apply a progress update to the actual response content.
   */
  updateContent(responsePart, quiet) {
    this.b.updateContent(responsePart, quiet);
  }
  /**
   * Apply one of the progress updates that are not part of the actual response content.
   */
  applyReference(progress) {
    if (progress.kind === "usedContext") {
      this.h = progress;
    } else if (progress.kind === "reference") {
      this.j.push(progress);
      this.a.fire();
    }
  }
  applyCodeCitation(progress) {
    this.m.push(progress);
    this.b.addCitation(progress);
    this.a.fire();
  }
  setAgent(agent, slashCommand) {
    this.w = agent;
    this.y = slashCommand;
    this.g = !agent.isDefault || !!slashCommand;
    this.a.fire();
  }
  setResult(result) {
    this.G = result;
    this.a.fire();
  }
  complete() {
    if (this.G?.errorDetails?.responseIsRedacted) {
      this.b.clear();
    }
    this.z = true;
    this.a.fire();
  }
  cancel() {
    this.z = true;
    this.C = true;
    this.a.fire();
  }
  setFollowups(followups) {
    this.f = followups;
    this.a.fire();
  }
  setVote(vote) {
    this.D = vote;
    this.a.fire();
  }
  setVoteDownReason(reason) {
    this.F = reason;
    this.a.fire();
  }
  setEditApplied(edit3, editCount) {
    if (!this.response.value.includes(edit3)) {
      return false;
    }
    if (!edit3.state) {
      return false;
    }
    edit3.state.applied = editCount;
    this.a.fire();
    return true;
  }
  adoptTo(session) {
    this.u = session;
    this.a.fire();
  }
};
function $PO(raw) {
  normalizeOldFields(raw);
  if (!("version" in raw)) {
    return {
      version: 3,
      ...raw,
      lastMessageDate: raw.creationDate,
      customTitle: void 0
    };
  }
  if (raw.version === 2) {
    return {
      ...raw,
      version: 3,
      customTitle: raw.computedTitle
    };
  }
  return raw;
}
function normalizeOldFields(raw) {
  if (!raw.sessionId) {
    raw.sessionId = $ps();
  }
  if (!raw.creationDate) {
    raw.creationDate = getLastYearDate();
  }
  if ("version" in raw && (raw.version === 2 || raw.version === 3)) {
    if (!raw.lastMessageDate) {
      raw.lastMessageDate = getLastYearDate();
    }
  }
}
function getLastYearDate() {
  const lastYearDate = /* @__PURE__ */ new Date();
  lastYearDate.setFullYear(lastYearDate.getFullYear() - 1);
  return lastYearDate.getTime();
}
function $QO(obj) {
  const data = obj;
  return typeof data === "object" && typeof data.requesterUsername === "string";
}
function $RO(obj) {
  const data = obj;
  return $QO(obj) && typeof data.creationDate === "number" && typeof data.sessionId === "string" && obj.requests.every((request) => !request.usedContext || $pO(request.usedContext));
}
var ChatRequestRemovalReason;
(function(ChatRequestRemovalReason2) {
  ChatRequestRemovalReason2[ChatRequestRemovalReason2["Removal"] = 0] = "Removal";
  ChatRequestRemovalReason2[ChatRequestRemovalReason2["Resend"] = 1] = "Resend";
  ChatRequestRemovalReason2[ChatRequestRemovalReason2["Adoption"] = 2] = "Adoption";
})(ChatRequestRemovalReason || (ChatRequestRemovalReason = {}));
var ChatModelInitState;
(function(ChatModelInitState2) {
  ChatModelInitState2[ChatModelInitState2["Created"] = 0] = "Created";
  ChatModelInitState2[ChatModelInitState2["Initializing"] = 1] = "Initializing";
  ChatModelInitState2[ChatModelInitState2["Initialized"] = 2] = "Initialized";
})(ChatModelInitState || (ChatModelInitState = {}));
var $SO = $SO_1 = class $SO2 extends $3c {
  static getDefaultTitle(requests) {
    const firstRequestMessage = requests.at(0)?.message ?? "";
    const message = typeof firstRequestMessage === "string" ? firstRequestMessage : firstRequestMessage.text;
    return message.split("\n")[0].substring(0, 50);
  }
  get welcomeMessage() {
    return this.j;
  }
  get sampleQuestions() {
    return this.m;
  }
  get sessionId() {
    return this.n;
  }
  get requestInProgress() {
    const lastRequest2 = this.lastRequest;
    return !!lastRequest2?.response && !lastRequest2.response.isComplete;
  }
  get hasRequests() {
    return this.f.length > 0;
  }
  get lastRequest() {
    return this.f.at(-1);
  }
  get creationDate() {
    return this.t;
  }
  get lastMessageDate() {
    return this.u;
  }
  get w() {
    return this.I.getDefaultAgent(ChatAgentLocation.Panel);
  }
  get requesterUsername() {
    return this.w?.metadata.requester?.name ?? this.F?.requesterUsername ?? "";
  }
  get responderUsername() {
    return this.w?.fullName ?? this.F?.responderUsername ?? "";
  }
  get requesterAvatarIconUri() {
    return this.w?.metadata.requester?.icon ?? this.y;
  }
  get responderAvatarIcon() {
    return this.w?.metadata.themeIcon ?? this.z;
  }
  get initState() {
    return this.g;
  }
  get isImported() {
    return this.C;
  }
  get customTitle() {
    return this.D;
  }
  get title() {
    return this.D || $SO_1.getDefaultTitle(this.f);
  }
  get initialLocation() {
    return this.G;
  }
  constructor(F, G, H, I) {
    super();
    this.F = F;
    this.G = G;
    this.H = H;
    this.I = I;
    this.a = this.B(new $ze());
    this.onDidDispose = this.a.event;
    this.b = this.B(new $ze());
    this.onDidChange = this.b.event;
    this.g = ChatModelInitState.Created;
    this.h = new $gi();
    this.C = false;
    this.N = void 0;
    this.C = !!F && !$RO(F) || (F?.isImported ?? false);
    this.n = $RO(F) && F.sessionId || $ps();
    this.f = F ? this.J(F) : [];
    this.t = $RO(F) && F.creationDate || Date.now();
    this.u = $RO(F) && F.lastMessageDate || this.t;
    this.D = $RO(F) ? F.customTitle : void 0;
    this.y = F?.requesterAvatarIconUri && URI.revive(F.requesterAvatarIconUri);
    this.z = $zc(F?.responderAvatarIconUri) ? URI.revive(F.responderAvatarIconUri) : F?.responderAvatarIconUri;
  }
  J(obj) {
    const requests = obj.requests;
    if (!Array.isArray(requests)) {
      this.H.error(`Ignoring malformed session data: ${JSON.stringify(obj)}`);
      return [];
    }
    try {
      return requests.map((raw) => {
        const parsedRequest = typeof raw.message === "string" ? this.M(raw.message) : $FO(raw.message);
        const variableData = this.L(raw.variableData);
        const request = new $MO(this, parsedRequest, variableData, raw.timestamp ?? -1, void 0, void 0, void 0, void 0, raw.workingSet?.map((uri) => URI.revive(uri)), void 0, raw.requestId);
        request.isHidden = !!raw.isHidden;
        if (raw.response || raw.result || raw.responseErrorDetails) {
          const agent = raw.agent && "metadata" in raw.agent ? (
            // Check for the new format, ignore entries in the old format
            $6O(raw.agent)
          ) : void 0;
          const result = "responseErrorDetails" in raw ? (
            // eslint-disable-next-line local/code-no-dangerous-type-assertions
            { errorDetails: raw.responseErrorDetails }
          ) : raw.result;
          request.response = new $OO(raw.response ?? [new $bm(raw.response)], this, agent, raw.slashCommand, request.id, true, raw.isCanceled, raw.vote, raw.voteDownReason, result, raw.followups, void 0, void 0, raw.responseId);
          request.response.isHidden = !!raw.isHidden;
          if (raw.usedContext) {
            request.response.applyReference($cu(raw.usedContext));
          }
          raw.contentReferences?.forEach((r2) => request.response.applyReference($cu(r2)));
          raw.codeCitations?.forEach((c) => request.response.applyCodeCitation($cu(c)));
        }
        return request;
      });
    } catch (error) {
      this.H.error("Failed to parse chat data", error);
      return [];
    }
  }
  L(raw) {
    const variableData = raw && Array.isArray(raw.variables) ? raw : { variables: [] };
    variableData.variables = variableData.variables.map((v) => {
      if (v && "values" in v && Array.isArray(v.values)) {
        return {
          id: v.id ?? "",
          name: v.name,
          value: v.values[0]?.value,
          range: v.range,
          modelDescription: v.modelDescription,
          references: v.references
        };
      } else {
        return v;
      }
    });
    return variableData;
  }
  M(message) {
    const parts = [new $vO(new $0C(0, message.length), { startColumn: 1, startLineNumber: 1, endColumn: 1, endLineNumber: 1 }, message)];
    return {
      text: message,
      parts
    };
  }
  startInitialize() {
    if (this.initState !== ChatModelInitState.Created) {
      throw new Error(`ChatModel is in the wrong state for startInitialize: ${ChatModelInitState[this.initState]}`);
    }
    this.g = ChatModelInitState.Initializing;
  }
  deinitialize() {
    this.g = ChatModelInitState.Created;
    this.h = new $gi();
  }
  initialize(welcomeMessage, sampleQuestions) {
    if (this.initState !== ChatModelInitState.Initializing) {
      throw new Error(`ChatModel is in the wrong state for initialize: ${ChatModelInitState[this.initState]}`);
    }
    this.g = ChatModelInitState.Initialized;
    this.j = welcomeMessage;
    this.m = sampleQuestions;
    this.h.complete();
    this.b.fire({ kind: "initialize" });
  }
  setInitializationError(error) {
    if (this.initState !== ChatModelInitState.Initializing) {
      throw new Error(`ChatModel is in the wrong state for setInitializationError: ${ChatModelInitState[this.initState]}`);
    }
    if (!this.h.isSettled) {
      this.h.error(error);
    }
  }
  waitForInitialization() {
    return this.h.p;
  }
  getRequests() {
    return this.f;
  }
  get checkpoint() {
    return this.N;
  }
  disableRequests(requestIds) {
    this.f.forEach((request) => {
      const isHidden = requestIds.includes(request.id);
      request.isHidden = isHidden;
      if (request.response) {
        request.response.isHidden = isHidden;
      }
    });
    this.b.fire({
      kind: "setHidden",
      hiddenRequestIds: new Set(requestIds)
    });
  }
  addRequest(message, variableData, attempt, chatAgent, slashCommand, confirmation, locationData, attachments, workingSet, isCompleteAddedRequest) {
    const request = new $MO(this, message, variableData, Date.now(), attempt, confirmation, locationData, attachments, workingSet, isCompleteAddedRequest);
    request.response = new $OO([], this, chatAgent, slashCommand, request.id, void 0, void 0, void 0, void 0, void 0, void 0, void 0, isCompleteAddedRequest);
    this.f.push(request);
    this.u = Date.now();
    this.b.fire({ kind: "addRequest", request });
    return request;
  }
  setCustomTitle(title) {
    this.D = title;
  }
  updateRequest(request, variableData) {
    request.variableData = variableData;
    this.b.fire({ kind: "changedRequest", request });
  }
  adoptRequest(request) {
    const oldOwner = request.session;
    const index = oldOwner.f.findIndex((candidate) => candidate.id === request.id);
    if (index === -1) {
      return;
    }
    oldOwner.f.splice(index, 1);
    request.adoptTo(this);
    request.response?.adoptTo(this);
    this.f.push(request);
    oldOwner.b.fire({
      kind: "removeRequest",
      requestId: request.id,
      responseId: request.response?.id,
      reason: 2
      /* ChatRequestRemovalReason.Adoption */
    });
    this.b.fire({ kind: "addRequest", request });
  }
  acceptResponseProgress(request, progress, quiet) {
    if (!request.response) {
      request.response = new $OO([], this, void 0, void 0, request.id);
    }
    if (request.response.isComplete) {
      throw new Error("acceptResponseProgress: Adding progress to a completed response");
    }
    if (progress.kind === "markdownContent" || progress.kind === "treeData" || progress.kind === "inlineReference" || progress.kind === "codeblockUri" || progress.kind === "markdownVuln" || progress.kind === "progressMessage" || progress.kind === "command" || progress.kind === "textEdit" || progress.kind === "warning" || progress.kind === "progressTask" || progress.kind === "confirmation" || progress.kind === "toolInvocation") {
      request.response.updateContent(progress, quiet);
    } else if (progress.kind === "usedContext" || progress.kind === "reference") {
      request.response.applyReference(progress);
    } else if (progress.kind === "agentDetection") {
      const agent = this.I.getAgent(progress.agentId);
      if (agent) {
        request.response.setAgent(agent, progress.command);
        this.b.fire({ kind: "setAgent", agent, command: progress.command });
      }
    } else if (progress.kind === "codeCitation") {
      request.response.applyCodeCitation(progress);
    } else if (progress.kind === "move") {
      this.b.fire({ kind: "move", target: progress.uri, range: progress.range });
    } else {
      this.H.error(`Couldn't handle progress: ${JSON.stringify(progress)}`);
    }
  }
  removeRequest(id2, reason = 0) {
    const index = this.f.findIndex((request2) => request2.id === id2);
    const request = this.f[index];
    if (index !== -1) {
      this.b.fire({ kind: "removeRequest", requestId: request.id, responseId: request.response?.id, reason });
      this.f.splice(index, 1);
      request.response?.dispose();
    }
  }
  cancelRequest(request) {
    if (request.response) {
      request.response.cancel();
    }
  }
  setResponse(request, result) {
    if (!request.response) {
      request.response = new $OO([], this, void 0, void 0, request.id);
    }
    request.response.setResult(result);
  }
  completeResponse(request) {
    if (!request.response) {
      throw new Error("Call setResponse before completeResponse");
    }
    request.response.complete();
  }
  setFollowups(request, followups) {
    if (!request.response) {
      return;
    }
    request.response.setFollowups(followups);
  }
  setResponseModel(request, response) {
    request.response = response;
    this.b.fire({ kind: "addResponse", response });
  }
  toExport() {
    return {
      requesterUsername: this.requesterUsername,
      requesterAvatarIconUri: this.requesterAvatarIconUri,
      responderUsername: this.responderUsername,
      responderAvatarIconUri: this.responderAvatarIcon,
      initialLocation: this.initialLocation,
      requests: this.f.map((r2) => {
        const message = {
          ...r2.message,
          parts: r2.message.parts.map((p) => p && "toJSON" in p ? p.toJSON() : p)
        };
        const agent = r2.response?.agent;
        const agentJson = agent && "toJSON" in agent ? agent.toJSON() : agent ? { ...agent } : void 0;
        return {
          requestId: r2.id,
          message,
          variableData: r2.variableData,
          response: r2.response ? r2.response.response.value.map((item) => {
            if (item.kind === "treeData") {
              return item.treeData;
            } else if (item.kind === "markdownContent") {
              return item.content;
            } else {
              return item;
            }
          }) : void 0,
          responseId: r2.response?.id,
          isHidden: r2.isHidden,
          result: r2.response?.result,
          followups: r2.response?.followups,
          isCanceled: r2.response?.isCanceled,
          vote: r2.response?.vote,
          voteDownReason: r2.response?.voteDownReason,
          agent: agentJson,
          workingSet: r2.workingSet,
          slashCommand: r2.response?.slashCommand,
          usedContext: r2.response?.usedContext,
          contentReferences: r2.response?.contentReferences,
          codeCitations: r2.response?.codeCitations,
          timestamp: r2.timestamp
        };
      })
    };
  }
  toJSON() {
    return {
      version: 3,
      ...this.toExport(),
      sessionId: this.sessionId,
      creationDate: this.t,
      isImported: this.C,
      lastMessageDate: this.u,
      customTitle: this.D
    };
  }
  dispose() {
    this.f.forEach((r2) => r2.response?.dispose());
    this.a.fire();
    super.dispose();
  }
};
$SO = $SO_1 = __decorate([
  __param(2, $wn),
  __param(3, $ZO)
], $SO);
function $TO(variableData, diff3) {
  return {
    variables: variableData.variables.map((v) => ({
      ...v,
      range: v.range && {
        start: v.range.start - diff3,
        endExclusive: v.range.endExclusive - diff3
      }
    }))
  };
}
function $UO(md1, md2) {
  if (md1.baseUri && md2.baseUri) {
    const baseUriEquals = md1.baseUri.scheme === md2.baseUri.scheme && md1.baseUri.authority === md2.baseUri.authority && md1.baseUri.path === md2.baseUri.path && md1.baseUri.query === md2.baseUri.query && md1.baseUri.fragment === md2.baseUri.fragment;
    if (!baseUriEquals) {
      return false;
    }
  } else if (md1.baseUri || md2.baseUri) {
    return false;
  }
  return $Pv(md1.isTrusted, md2.isTrusted) && md1.supportHtml === md2.supportHtml && md1.supportThemeIcons === md2.supportThemeIcons;
}
function $VO(md1, md2) {
  const appendedValue = typeof md2 === "string" ? md2 : md2.value;
  return {
    value: md1.value + appendedValue,
    isTrusted: md1.isTrusted,
    supportThemeIcons: md1.supportThemeIcons,
    supportHtml: md1.supportHtml,
    baseUri: md1.baseUri
  };
}
function $WO(citations) {
  if (citations.length === 0) {
    return "";
  }
  const licenseTypes = citations.reduce((set, c) => set.add(c.license), /* @__PURE__ */ new Set());
  const label3 = licenseTypes.size === 1 ? localize(5102, null, licenseTypes.size) : localize(5103, null, licenseTypes.size);
  return label3;
}

// out-build/vs/workbench/contrib/chat/common/chatWidgetHistoryService.js
var $jzb = $Qk("IChatWidgetHistoryService");
var $kzb = class $kzb2 {
  constructor(storageService) {
    this.c = new $ze();
    this.onDidClearHistory = this.c.event;
    this.a = new $Slb("interactive-session", storageService);
    const loadedState = this.a.getMemento(
      1,
      1
      /* StorageTarget.MACHINE */
    );
    for (const provider in loadedState.history) {
      loadedState.history[provider] = loadedState.history[provider].map((entry) => typeof entry === "string" ? { text: entry } : entry);
    }
    this.b = loadedState;
  }
  getHistory(location3) {
    const key2 = this.d(location3);
    return this.b.history?.[key2] ?? [];
  }
  d(location3) {
    return location3 === ChatAgentLocation.Panel ? $XO : location3;
  }
  saveHistory(location3, history) {
    if (!this.b.history) {
      this.b.history = {};
    }
    const key2 = this.d(location3);
    this.b.history[key2] = history;
    this.a.saveMemento();
  }
  clearHistory() {
    this.b.history = {};
    this.a.saveMemento();
    this.c.fire();
  }
};
$kzb = __decorate([
  __param(0, $jv)
], $kzb);

// out-build/vs/workbench/common/activity.js
var $Pzb = "workbench.actions.manage";
var $Qzb = "workbench.actions.accounts";

// out-build/vs/workbench/browser/parts/titlebar/titlebarActions.js
var $Rzb = class extends $gJ {
  constructor(c, title, description, order, mainWindowOnly, when) {
    when = $7m.and(mainWindowOnly ? $opb.toNegated() : $7m.true(), when);
    super({
      id: `toggle.${c}`,
      title,
      metadata: description ? { description } : void 0,
      toggled: $7m.equals(`config.${c}`, true),
      menu: [
        {
          id: $bJ.TitleBarContext,
          when,
          order,
          group: "2_config"
        },
        {
          id: $bJ.TitleBarTitleContext,
          when,
          order,
          group: "2_config"
        }
      ]
    });
    this.c = c;
  }
  run(accessor, ...args2) {
    const configService = accessor.get($kl);
    const value = configService.getValue(this.c);
    configService.updateValue(this.c, !value);
  }
};
$hJ(class ToggleCommandCenter extends $Rzb {
  constructor() {
    super("window.commandCenter", localize(3767, null), localize(3768, null), 1, false);
  }
});
$hJ(class ToggleNavigationControl extends $Rzb {
  constructor() {
    super("workbench.navigationControl.enabled", localize(3769, null), localize(3770, null), 2, false, $7m.has("config.window.commandCenter"));
  }
});
$hJ(class ToggleLayoutControl extends $Rzb {
  constructor() {
    super("workbench.layoutControl.enabled", localize(3771, null), localize(3772, null), 3, true);
  }
});
$hJ(class ToggleCustomTitleBar extends $gJ {
  constructor() {
    super({
      id: `toggle.${"window.customTitleBarVisibility"}`,
      title: localize(3773, null),
      menu: [
        { id: $bJ.TitleBarContext, order: 0, when: $7m.equals(
          $7pb.key,
          "native"
          /* TitlebarStyle.NATIVE */
        ), group: "3_toggle" },
        { id: $bJ.TitleBarTitleContext, order: 0, when: $7m.equals(
          $7pb.key,
          "native"
          /* TitlebarStyle.NATIVE */
        ), group: "3_toggle" }
      ]
    });
  }
  run(accessor, ...args2) {
    const configService = accessor.get($kl);
    configService.updateValue(
      "window.customTitleBarVisibility",
      "never"
      /* CustomTitleBarVisibility.NEVER */
    );
  }
});
$hJ(class ToggleCustomTitleBarWindowed extends $gJ {
  constructor() {
    super({
      id: `toggle.${"window.customTitleBarVisibility"}.windowed`,
      title: localize(3774, null),
      menu: [
        { id: $bJ.TitleBarContext, order: 1, when: $npb, group: "3_toggle" },
        { id: $bJ.TitleBarTitleContext, order: 1, when: $npb, group: "3_toggle" }
      ]
    });
  }
  run(accessor, ...args2) {
    const configService = accessor.get($kl);
    configService.updateValue(
      "window.customTitleBarVisibility",
      "windowed"
      /* CustomTitleBarVisibility.WINDOWED */
    );
  }
});
var ToggleCustomTitleBar2 = class extends $gJ {
  constructor() {
    super({
      id: `toggle.toggleCustomTitleBar`,
      title: localize(3775, null),
      toggled: $8pb,
      menu: [
        {
          id: $bJ.MenubarAppearanceMenu,
          order: 6,
          when: $7m.or($7m.and($7m.equals(
            $7pb.key,
            "native"
            /* TitlebarStyle.NATIVE */
          ), $7m.and($7m.equals("config.workbench.layoutControl.enabled", false), $7m.equals("config.window.commandCenter", false), $7m.notEquals("config.workbench.editor.editorActionsLocation", "titleBar"), $7m.notEquals("config.workbench.activityBar.location", "top"), $7m.notEquals("config.workbench.activityBar.location", "bottom"))?.negate()), $npb),
          group: "2_workbench_layout"
        }
      ]
    });
  }
  run(accessor, ...args2) {
    const configService = accessor.get($kl);
    const contextKeyService = accessor.get($on);
    const titleBarVisibility = configService.getValue(
      "window.customTitleBarVisibility"
      /* TitleBarSetting.CUSTOM_TITLE_BAR_VISIBILITY */
    );
    switch (titleBarVisibility) {
      case "never":
        configService.updateValue(
          "window.customTitleBarVisibility",
          "auto"
          /* CustomTitleBarVisibility.AUTO */
        );
        break;
      case "windowed": {
        const isFullScreen = $npb.evaluate(contextKeyService.getContext(null));
        if (isFullScreen) {
          configService.updateValue(
            "window.customTitleBarVisibility",
            "auto"
            /* CustomTitleBarVisibility.AUTO */
          );
        } else {
          configService.updateValue(
            "window.customTitleBarVisibility",
            "never"
            /* CustomTitleBarVisibility.NEVER */
          );
        }
        break;
      }
      case "auto":
      default:
        configService.updateValue(
          "window.customTitleBarVisibility",
          "never"
          /* CustomTitleBarVisibility.NEVER */
        );
        break;
    }
  }
};
$hJ(ToggleCustomTitleBar2);
$hJ(class ShowCustomTitleBar extends $gJ {
  constructor() {
    super({
      id: `showCustomTitleBar`,
      title: localize2(3782, "Show Custom Title Bar"),
      precondition: $8pb.negate(),
      f1: true
    });
  }
  run(accessor, ...args2) {
    const configService = accessor.get($kl);
    configService.updateValue(
      "window.customTitleBarVisibility",
      "auto"
      /* CustomTitleBarVisibility.AUTO */
    );
  }
});
$hJ(class HideCustomTitleBar extends $gJ {
  constructor() {
    super({
      id: `hideCustomTitleBar`,
      title: localize2(3783, "Hide Custom Title Bar"),
      precondition: $8pb,
      f1: true
    });
  }
  run(accessor, ...args2) {
    const configService = accessor.get($kl);
    configService.updateValue(
      "window.customTitleBarVisibility",
      "never"
      /* CustomTitleBarVisibility.NEVER */
    );
  }
});
$hJ(class HideCustomTitleBar2 extends $gJ {
  constructor() {
    super({
      id: `hideCustomTitleBarInFullScreen`,
      title: localize2(3784, "Hide Custom Title Bar In Full Screen"),
      precondition: $7m.and($8pb, $npb),
      f1: true
    });
  }
  run(accessor, ...args2) {
    const configService = accessor.get($kl);
    configService.updateValue(
      "window.customTitleBarVisibility",
      "windowed"
      /* CustomTitleBarVisibility.WINDOWED */
    );
  }
});
$hJ(class ToggleEditorActions extends $gJ {
  static {
    this.settingsID = `workbench.editor.editorActionsLocation`;
  }
  constructor() {
    const titleBarContextCondition = $7m.and($7m.equals(`config.workbench.editor.showTabs`, "none").negate(), $7m.equals(`config.${ToggleEditorActions.settingsID}`, "default"))?.negate();
    super({
      id: `toggle.${ToggleEditorActions.settingsID}`,
      title: localize(3776, null),
      toggled: $7m.equals(`config.${ToggleEditorActions.settingsID}`, "hidden").negate(),
      menu: [
        { id: $bJ.TitleBarContext, order: 3, when: titleBarContextCondition, group: "2_config" },
        { id: $bJ.TitleBarTitleContext, order: 3, when: titleBarContextCondition, group: "2_config" }
      ]
    });
  }
  run(accessor, ...args2) {
    const configService = accessor.get($kl);
    const storageService = accessor.get($jv);
    const location3 = configService.getValue(ToggleEditorActions.settingsID);
    if (location3 === "hidden") {
      const showTabs = configService.getValue(
        "workbench.editor.showTabs"
        /* LayoutSettings.EDITOR_TABS_MODE */
      );
      if (showTabs !== "none") {
        configService.updateValue(ToggleEditorActions.settingsID, "titleBar");
      } else {
        const storedValue = storageService.get(
          ToggleEditorActions.settingsID,
          0
          /* StorageScope.PROFILE */
        );
        configService.updateValue(ToggleEditorActions.settingsID, storedValue ?? "default");
      }
      storageService.remove(
        ToggleEditorActions.settingsID,
        0
        /* StorageScope.PROFILE */
      );
    } else {
      configService.updateValue(ToggleEditorActions.settingsID, "hidden");
      storageService.store(
        ToggleEditorActions.settingsID,
        location3,
        0,
        0
        /* StorageTarget.USER */
      );
    }
  }
});
if ($n && $p) {
  $hJ(class ToggleCustomTitleBar extends $gJ {
    constructor() {
      super({
        id: `toggle.${"window.titleBarStyle"}`,
        title: localize(3777, null),
        menu: [
          { id: $bJ.TitleBarContext, order: 0, when: $7m.equals(
            $7pb.key,
            "custom"
            /* TitlebarStyle.CUSTOM */
          ), group: "4_restore_native_title" },
          { id: $bJ.TitleBarTitleContext, order: 0, when: $7m.equals(
            $7pb.key,
            "custom"
            /* TitlebarStyle.CUSTOM */
          ), group: "4_restore_native_title" }
        ]
      });
    }
    run(accessor) {
      const configService = accessor.get($kl);
      configService.updateValue(
        "window.titleBarStyle",
        "native"
        /* TitlebarStyle.NATIVE */
      );
    }
  });
}
var $Szb = {
  id: $Qzb,
  label: localize(3778, null),
  tooltip: localize(3779, null),
  class: void 0,
  enabled: true,
  run: function() {
  }
};
var $Tzb = {
  id: $Pzb,
  label: localize(3780, null),
  tooltip: localize(3781, null),
  class: void 0,
  enabled: true,
  run: function() {
  }
};

// out-build/vs/workbench/contrib/extensions/common/extensions.js
var $tzb = "workbench.view.extensions";
var $uzb = localize2(6972, "Extensions");
var ExtensionState;
(function(ExtensionState2) {
  ExtensionState2[ExtensionState2["Installing"] = 0] = "Installing";
  ExtensionState2[ExtensionState2["Installed"] = 1] = "Installed";
  ExtensionState2[ExtensionState2["Uninstalling"] = 2] = "Uninstalling";
  ExtensionState2[ExtensionState2["Uninstalled"] = 3] = "Uninstalled";
})(ExtensionState || (ExtensionState = {}));
var ExtensionRuntimeActionType;
(function(ExtensionRuntimeActionType2) {
  ExtensionRuntimeActionType2["ReloadWindow"] = "reloadWindow";
  ExtensionRuntimeActionType2["RestartExtensions"] = "restartExtensions";
  ExtensionRuntimeActionType2["DownloadUpdate"] = "downloadUpdate";
  ExtensionRuntimeActionType2["ApplyUpdate"] = "applyUpdate";
  ExtensionRuntimeActionType2["QuitAndInstall"] = "quitAndInstall";
})(ExtensionRuntimeActionType || (ExtensionRuntimeActionType = {}));
var $vzb = $Qk("extensionsWorkbenchService");
var ExtensionEditorTab;
(function(ExtensionEditorTab2) {
  ExtensionEditorTab2["Readme"] = "readme";
  ExtensionEditorTab2["Features"] = "features";
  ExtensionEditorTab2["Changelog"] = "changelog";
  ExtensionEditorTab2["Dependencies"] = "dependencies";
  ExtensionEditorTab2["ExtensionPack"] = "extensionPack";
})(ExtensionEditorTab || (ExtensionEditorTab = {}));
var $xzb = "extensions.autoUpdate";
var $yzb = "extensions.autoCheckUpdates";
var $zzb = "extensions.closeExtensionDetailsOnViewChange";
var $Azb = "extensions.autoRestart";
var $Bzb = class $Bzb2 extends $3c {
  constructor(a, extensionsWorkbenchService) {
    super();
    this.a = a;
    this.B(extensionsWorkbenchService.onChange(this.b, this));
  }
  set extension(extension) {
    this.a.forEach((c) => c.extension = extension);
  }
  b(extension) {
    for (const container2 of this.a) {
      if (extension && container2.extension) {
        if ($DA(container2.extension.identifier, extension.identifier)) {
          if (container2.extension.server && extension.server && container2.extension.server !== extension.server) {
            if (container2.updateWhenCounterExtensionChanges) {
              container2.update();
            }
          } else {
            container2.extension = extension;
          }
        }
      } else {
        container2.update();
      }
    }
  }
};
$Bzb = __decorate([
  __param(1, $vzb)
], $Bzb);
var $Czb = "workbench.views.extensions.workspaceRecommendations";
var $Dzb = "workbench.views.extensions.searchOutdated";
var $Ezb = "workbench.extensions.action.toggleIgnoreExtension";
var $Fzb = "workbench.extensions.action.installVSIX";
var $Gzb = "workbench.extensions.command.installFromVSIX";
var $Hzb = "workbench.extensions.action.listWorkspaceUnsupportedExtensions";
var $Izb = new $nn("hasOutdatedExtensions", false);
var $Jzb = new $nn("hasGallery", false);
var $Kzb = new $nn("extensionResultListFocused ", true);
var $Lzb = "_theme_";
var $Mzb = "0_install";
var $Nzb = "0_update";
var $Ozb = new $bJ("extensionsSearchActionsMenu");

// out-build/vs/workbench/contrib/chat/browser/chatQuotasService.js
var $Xzb_1;
var $Uzb = $Qk("chatQuotasService");
var $Vzb = "workbench.action.chat.openQuotaExceededDialog";
var $Wzb = class $Wzb2 extends $3c {
  get quotas() {
    return this.b;
  }
  constructor(h3) {
    super();
    this.h = h3;
    this.a = this.B(new $ze());
    this.onDidChangeQuotas = this.a.event;
    this.b = { chatQuotaExceeded: false, completionsQuotaExceeded: false, quotaResetDate: void 0 };
    this.c = ChatContextKeys.chatQuotaExceeded.bindTo(this.h);
    this.f = ChatContextKeys.completionsQuotaExceeded.bindTo(this.h);
    this.g = {
      chatQuotaExceeded: "github.copilot.chat.quotaExceeded",
      completionsQuotaExceeded: "github.copilot.completions.quotaExceeded"
    };
    this.j();
    this.m();
  }
  j() {
    const chatQuotaExceededSet = /* @__PURE__ */ new Set([this.g.chatQuotaExceeded]);
    const completionsQuotaExceededSet = /* @__PURE__ */ new Set([this.g.completionsQuotaExceeded]);
    this.B(this.h.onDidChangeContext((e) => {
      let changed = false;
      if (e.affectsSome(chatQuotaExceededSet)) {
        const newChatQuotaExceeded = this.h.getContextKeyValue(this.g.chatQuotaExceeded);
        if (typeof newChatQuotaExceeded === "boolean" && newChatQuotaExceeded !== this.b.chatQuotaExceeded) {
          this.b.chatQuotaExceeded = newChatQuotaExceeded;
          changed = true;
        }
      }
      if (e.affectsSome(completionsQuotaExceededSet)) {
        const newCompletionsQuotaExceeded = this.h.getContextKeyValue(this.g.completionsQuotaExceeded);
        if (typeof newCompletionsQuotaExceeded === "boolean" && newCompletionsQuotaExceeded !== this.b.completionsQuotaExceeded) {
          this.b.completionsQuotaExceeded = newCompletionsQuotaExceeded;
          changed = true;
        }
      }
      if (changed) {
        this.n();
        this.a.fire();
      }
    }));
  }
  m() {
    const that = this;
    class ShowLimitReachedDialogAction extends $gJ {
      constructor() {
        super({
          id: $Vzb,
          title: localize(4992, null)
        });
      }
      async run(accessor) {
        const commandService = accessor.get($sn);
        const dialogService = accessor.get($Yv);
        const dateFormatter = $Uu.DateTimeFormat($z, { year: "numeric", month: "long", day: "numeric" });
        let message;
        const { chatQuotaExceeded, completionsQuotaExceeded } = that.quotas;
        if (chatQuotaExceeded && !completionsQuotaExceeded) {
          message = localize(4993, null, dateFormatter.format(that.quotas.quotaResetDate));
        } else if (completionsQuotaExceeded && !chatQuotaExceeded) {
          message = localize(4994, null, dateFormatter.format(that.quotas.quotaResetDate));
        } else {
          message = localize(4995, null, dateFormatter.format(that.quotas.quotaResetDate));
        }
        const upgradeToPro = localize(4996, null);
        await dialogService.prompt({
          type: "none",
          message: localize(4997, null),
          cancelButton: {
            label: localize(4998, null),
            run: () => {
            }
          },
          buttons: [
            {
              label: localize(4999, null),
              run: () => commandService.executeCommand("workbench.action.chat.upgradePlan")
            }
          ],
          custom: {
            closeOnLinkClick: true,
            icon: $6l.copilotWarningLarge,
            markdownDetails: [
              { markdown: new $bm(message, true) },
              { markdown: new $bm(upgradeToPro, true) }
            ]
          }
        });
      }
    }
    class SimulateCopilotQuotaExceeded extends $gJ {
      constructor() {
        super({
          id: "workbench.action.chat.simulateCopilotQuotaExceeded",
          title: localize2(5007, "Simulate Copilot Quota Exceeded"),
          f1: true,
          category: $qn.Developer
        });
      }
      async run(accessor) {
        const inputService = accessor.get($1M);
        const result = await inputService.pick([
          { label: "Chat" },
          { label: "Completions" }
        ], { canPickMany: true, placeHolder: "Pick the quotas to exceed" });
        if (result) {
          const resultSet = new Set(result.map((r2) => r2.label));
          that.acceptQuotas({
            chatQuotaExceeded: resultSet.has("Chat"),
            completionsQuotaExceeded: resultSet.has("Completions"),
            quotaResetDate: /* @__PURE__ */ new Date()
          });
        }
      }
    }
    $hJ(ShowLimitReachedDialogAction);
    if (product_default.quality !== "stable") {
      $hJ(SimulateCopilotQuotaExceeded);
    }
  }
  acceptQuotas(quotas) {
    this.b = quotas;
    this.n();
    this.a.fire();
  }
  clearQuotas() {
    if (this.quotas.chatQuotaExceeded || this.quotas.completionsQuotaExceeded) {
      this.acceptQuotas({ chatQuotaExceeded: false, completionsQuotaExceeded: false, quotaResetDate: void 0 });
    }
  }
  n() {
    this.c.set(this.b.chatQuotaExceeded);
    this.f.set(this.b.completionsQuotaExceeded);
  }
};
$Wzb = __decorate([
  __param(0, $on)
], $Wzb);
var $Xzb = class $Xzb2 extends $3c {
  static {
    $Xzb_1 = this;
  }
  static {
    this.ID = "chat.quotasStatusBarEntry";
  }
  static {
    this.a = "GitHub.copilot.status";
  }
  // TODO@bpasero unify into 1 core indicator
  constructor(c, f) {
    super();
    this.c = c;
    this.f = f;
    this.b = this.B(new $2c());
    this.B(Event2.runAndSubscribe(this.f.onDidChangeQuotas, () => this.g()));
    this.B(this.c.onDidChangeEntryVisibility((e) => {
      if (e.id === $Xzb_1.a) {
        this.g();
      }
    }));
  }
  g() {
    this.b.clear();
    const { chatQuotaExceeded, completionsQuotaExceeded } = this.f.quotas;
    if (chatQuotaExceeded || completionsQuotaExceeded) {
      let text2;
      if (chatQuotaExceeded && !completionsQuotaExceeded) {
        text2 = localize(5e3, null);
      } else if (completionsQuotaExceeded && !chatQuotaExceeded) {
        text2 = localize(5001, null);
      } else {
        text2 = localize(5002, null);
      }
      const isCopilotStatusVisible = this.c.isEntryVisible($Xzb_1.a);
      if (!isCopilotStatusVisible) {
        text2 = `$(copilot-warning) ${text2}`;
      }
      this.b.add(this.c.addEntry({
        name: localize(5003, null),
        text: text2,
        ariaLabel: text2,
        command: $Vzb,
        showInAllWindows: true,
        kind: "prominent",
        tooltip: $Yzb({ chatQuotaExceeded, completionsQuotaExceeded })
      }, $Xzb_1.ID, 1, {
        id: $Xzb_1.a,
        alignment: 1,
        compact: isCopilotStatusVisible
      }));
      this.b.add(this.c.overrideEntry($Xzb_1.a, { kind: "prominent" }));
    }
  }
};
$Xzb = $Xzb_1 = __decorate([
  __param(0, $$qb),
  __param(1, $Uzb)
], $Xzb);
function $Yzb({ chatQuotaExceeded, completionsQuotaExceeded }) {
  if (chatQuotaExceeded && !completionsQuotaExceeded) {
    return localize(5004, null);
  } else if (completionsQuotaExceeded && !chatQuotaExceeded) {
    return localize(5005, null);
  } else {
    return localize(5006, null);
  }
}

// out-build/vs/workbench/contrib/chat/common/chatVariables.js
var $kO = $Qk("IChatVariablesService");

// out-build/vs/workbench/contrib/chat/common/annotations.js
var $4rb = "http://_vscodecontentref_";
function $5rb(response) {
  let refIdPool = 0;
  const result = [];
  for (const item of response) {
    const previousItem = result.filter((p) => p.kind !== "textEditGroup").at(-1);
    const previousItemIndex = result.findIndex((p) => p === previousItem);
    if (item.kind === "inlineReference") {
      let label3 = item.name;
      if (!label3) {
        if (URI.isUri(item.inlineReference)) {
          label3 = $sh(item.inlineReference);
        } else if ("name" in item.inlineReference) {
          label3 = item.inlineReference.name;
        } else {
          label3 = $sh(item.inlineReference.uri);
        }
      }
      const refId = refIdPool++;
      const printUri = URI.parse($4rb).with({ path: String(refId) });
      const markdownText = `[${label3}](${printUri.toString()})`;
      const annotationMetadata = { [refId]: item };
      if (previousItem?.kind === "markdownContent") {
        const merged = $VO(previousItem.content, new $bm(markdownText));
        result[previousItemIndex] = { ...previousItem, content: merged, inlineReferences: { ...annotationMetadata, ...previousItem.inlineReferences || {} } };
      } else {
        result.push({ content: new $bm(markdownText), inlineReferences: annotationMetadata, kind: "markdownContent" });
      }
    } else if (item.kind === "markdownContent" && previousItem?.kind === "markdownContent" && $UO(previousItem.content, item.content)) {
      const merged = $VO(previousItem.content, item.content);
      result[previousItemIndex] = { ...previousItem, content: merged };
    } else if (item.kind === "markdownVuln") {
      const vulnText = encodeURIComponent(JSON.stringify(item.vulnerabilities));
      const markdownText = `<vscode_annotation details='${vulnText}'>${item.content.value}</vscode_annotation>`;
      if (previousItem?.kind === "markdownContent") {
        const merged = $VO(previousItem.content, new $bm(markdownText));
        result[previousItemIndex] = { ...previousItem, content: merged };
      } else {
        result.push({ content: new $bm(markdownText), kind: "markdownContent" });
      }
    } else if (item.kind === "codeblockUri") {
      if (previousItem?.kind === "markdownContent") {
        const markdownText = `<vscode_codeblock_uri>${item.uri.toString()}</vscode_codeblock_uri>`;
        const merged = $VO(previousItem.content, new $bm(markdownText));
        result[previousItemIndex] = { ...previousItem, content: merged };
      }
    } else {
      result.push(item);
    }
  }
  return result;
}
function $6rb(response) {
  const result = [];
  for (const item of response) {
    const previousItem = result[result.length - 1];
    if (item.kind === "markdownContent") {
      if (previousItem?.kind === "markdownContent") {
        result[result.length - 1] = { content: new $bm(previousItem.content.value + item.content.value, { isTrusted: previousItem.content.isTrusted }), kind: "markdownContent" };
      } else {
        result.push(item);
      }
    } else if (item.kind === "markdownVuln") {
      const vulnText = encodeURIComponent(JSON.stringify(item.vulnerabilities));
      const markdownText = `<vscode_annotation details='${vulnText}'>${item.content.value}</vscode_annotation>`;
      if (previousItem?.kind === "markdownContent") {
        result[result.length - 1] = { content: new $bm(previousItem.content.value + markdownText, { isTrusted: previousItem.content.isTrusted }), kind: "markdownContent" };
      } else {
        result.push({ content: new $bm(markdownText), kind: "markdownContent" });
      }
    }
  }
  return result;
}
function $7rb(text2) {
  const match = /<vscode_codeblock_uri>(.*?)<\/vscode_codeblock_uri>/ms.exec(text2);
  if (match && match[1]) {
    const result = URI.parse(match[1]);
    const textWithoutResult = text2.substring(0, match.index) + text2.substring(match.index + match[0].length);
    return { uri: result, textWithoutResult };
  }
  return void 0;
}
function $8rb(text2) {
  const vulnerabilities = [];
  let newText = text2;
  let match;
  while ((match = /<vscode_annotation details='(.*?)'>(.*?)<\/vscode_annotation>/ms.exec(newText)) !== null) {
    const [full, details, content] = match;
    const start = match.index;
    const textBefore = newText.substring(0, start);
    const linesBefore = textBefore.split("\n").length - 1;
    const linesInside = content.split("\n").length - 1;
    const previousNewlineIdx = textBefore.lastIndexOf("\n");
    const startColumn = start - (previousNewlineIdx + 1) + 1;
    const endPreviousNewlineIdx = (textBefore + content).lastIndexOf("\n");
    const endColumn = start + content.length - (endPreviousNewlineIdx + 1) + 1;
    try {
      const vulnDetails = JSON.parse(decodeURIComponent(details));
      vulnDetails.forEach(({ title, description }) => vulnerabilities.push({
        title,
        description,
        range: { startLineNumber: linesBefore + 1, startColumn, endLineNumber: linesBefore + linesInside + 1, endColumn }
      }));
    } catch (err) {
    }
    newText = newText.substring(0, start) + content + newText.substring(start + full.length);
  }
  return { newText, vulnerabilities };
}

// out-build/vs/workbench/contrib/chat/common/chatWordCounter.js
var r = String.raw;
var linkPattern = r`(?<!\\)` + // Must not start with escape
// text
r`(!?\[` + // open prefix match -->
/**/
r`(?:` + /*****/
r`[^\[\]\\]|` + // Non-bracket chars, or...
/*****/
r`\\.|` + // Escaped char, or...
/*****/
r`\[[^\[\]]*\]` + // Matched bracket pair
/**/
r`)*` + r`\])` + // <-- close prefix match
// Destination
r`(\(\s*)` + // Pre href
/**/
r`(` + /*****/
r`[^\s\(\)<](?:[^\s\(\)]|\([^\s\(\)]*?\))*|` + // Link without whitespace, or...
/*****/
r`<(?:\\[<>]|[^<>])+>` + // In angle brackets
/**/
r`)` + // Title
/**/
r`\s*(?:"[^"]*"|'[^']*'|\([^\(\)]*\))?\s*` + r`\)`;
function $9rb(str, numWordsToCount) {
  const allWordMatches = Array.from(str.matchAll(new RegExp(linkPattern + r`|\p{sc=Han}|=+|\++|-+|[^\s\|\p{sc=Han}|=|\+|\-]+`, "gu")));
  const targetWords = allWordMatches.slice(0, numWordsToCount);
  const endIndex = numWordsToCount >= allWordMatches.length ? str.length : targetWords.length ? targetWords.at(-1).index + targetWords.at(-1)[0].length : 0;
  const value = str.substring(0, endIndex);
  return {
    value,
    returnedWordCount: targetWords.length === 0 ? value.length ? 1 : 0 : targetWords.length,
    isFullString: endIndex >= str.length,
    totalWordCount: allWordMatches.length
  };
}
function $0rb(str) {
  const result = $9rb(str, Number.MAX_SAFE_INTEGER);
  return result.returnedWordCount;
}

// out-build/vs/workbench/contrib/chat/common/chatViewModel.js
function $_rb(item) {
  return !!item && typeof item === "object" && "message" in item;
}
function $asb(item) {
  return !!item && typeof item.setVote !== "undefined";
}
var $bsb = class $bsb2 extends $3c {
  get inputPlaceholder() {
    return this.g;
  }
  get model() {
    return this.h;
  }
  setInputPlaceholder(text2) {
    this.g = text2;
    this.b.fire({ kind: "changePlaceholder" });
  }
  resetInputPlaceholder() {
    this.g = void 0;
    this.b.fire({ kind: "changePlaceholder" });
  }
  get sessionId() {
    return this.h.sessionId;
  }
  get requestInProgress() {
    return this.h.requestInProgress;
  }
  get initState() {
    return this.h.initState;
  }
  constructor(h3, codeBlockModelCollection, j) {
    super();
    this.h = h3;
    this.codeBlockModelCollection = codeBlockModelCollection;
    this.j = j;
    this.a = this.B(new $ze());
    this.onDidDisposeModel = this.a.event;
    this.b = this.B(new $ze());
    this.onDidChange = this.b.event;
    this.c = [];
    this.g = void 0;
    h3.getRequests().forEach((request, i2) => {
      const requestModel = this.j.createInstance($csb, request);
      this.c.push(requestModel);
      this.updateCodeBlockTextModels(requestModel);
      if (request.response) {
        this.m(request.response);
      }
    });
    this.B(h3.onDidDispose(() => this.a.fire()));
    this.B(h3.onDidChange((e) => {
      if (e.kind === "addRequest") {
        const requestModel = this.j.createInstance($csb, e.request);
        this.c.push(requestModel);
        this.updateCodeBlockTextModels(requestModel);
        if (e.request.response) {
          this.m(e.request.response);
        }
      } else if (e.kind === "addResponse") {
        this.m(e.response);
      } else if (e.kind === "removeRequest") {
        const requestIdx = this.c.findIndex((item) => $_rb(item) && item.id === e.requestId);
        if (requestIdx >= 0) {
          this.c.splice(requestIdx, 1);
        }
        const responseIdx = e.responseId && this.c.findIndex((item) => $asb(item) && item.id === e.responseId);
        if (typeof responseIdx === "number" && responseIdx >= 0) {
          const items = this.c.splice(responseIdx, 1);
          const item = items[0];
          if (item instanceof $dsb) {
            item.dispose();
          }
        }
      }
      const modelEventToVmEvent = e.kind === "addRequest" ? { kind: "addRequest" } : e.kind === "initialize" ? { kind: "initialize" } : e.kind === "setHidden" ? { kind: "setHidden" } : null;
      this.b.fire(modelEventToVmEvent);
    }));
  }
  m(responseModel) {
    const response = this.j.createInstance($dsb, responseModel, this);
    this.B(response.onDidChange(() => {
      if (response.isComplete) {
        this.updateCodeBlockTextModels(response);
      }
      return this.b.fire(null);
    }));
    this.c.push(response);
    this.updateCodeBlockTextModels(response);
  }
  getItems() {
    return [...this.c].filter((item) => !item.isHidden);
  }
  dispose() {
    super.dispose();
    this.c.filter((item) => item instanceof $dsb).forEach((item) => item.dispose());
  }
  updateCodeBlockTextModels(model) {
    let content;
    if ($_rb(model)) {
      content = model.messageText;
    } else {
      content = $6rb(model.response.value).map((x) => x.content.value).join("");
    }
    let codeBlockIndex = 0;
    walkTokens(lexer(content), (token) => {
      if (token.type === "code") {
        const lang = token.lang || "";
        const text2 = token.text;
        this.codeBlockModelCollection.update(this.h.sessionId, model, codeBlockIndex++, { text: text2, languageId: lang, isComplete: true });
      }
    });
  }
};
$bsb = __decorate([
  __param(2, $Pk)
], $bsb);
var $csb = class {
  get id() {
    return this.a.id;
  }
  get dataId() {
    return this.id + `_${ChatModelInitState[this.a.session.initState]}_${$Xi(this.variables)}_${$Xi(this.isComplete)}`;
  }
  get sessionId() {
    return this.a.session.sessionId;
  }
  get username() {
    return this.a.username;
  }
  get avatarIcon() {
    return this.a.avatarIconUri;
  }
  get message() {
    return this.a.message;
  }
  get messageText() {
    return this.message.text;
  }
  get attempt() {
    return this.a.attempt;
  }
  get variables() {
    return this.a.variableData.variables;
  }
  get contentReferences() {
    return this.a.response?.contentReferences;
  }
  get workingSet() {
    return this.a.workingSet;
  }
  get confirmation() {
    return this.a.confirmation;
  }
  get isComplete() {
    return this.a.response?.isComplete ?? false;
  }
  get isCompleteAddedRequest() {
    return this.a.isCompleteAddedRequest;
  }
  get isHidden() {
    return this.a.isHidden;
  }
  get slashCommand() {
    return this.a.response?.slashCommand;
  }
  get agentOrSlashCommandDetected() {
    return this.a.response?.agentOrSlashCommandDetected ?? false;
  }
  constructor(a) {
    this.a = a;
  }
};
var $dsb = class $dsb2 extends $3c {
  get model() {
    return this.j;
  }
  get id() {
    return this.j.id;
  }
  get dataId() {
    return this.j.id + `_${this.a}_${ChatModelInitState[this.j.session.initState]}` + (this.isLast ? "_last" : "");
  }
  get sessionId() {
    return this.j.session.sessionId;
  }
  get username() {
    if (this.agent) {
      const isAllowed = this.r.getAgentNameRestriction(this.agent);
      if (isAllowed) {
        return this.agent.fullName || this.agent.name;
      } else {
        return $5O(this.agent);
      }
    }
    return this.j.username;
  }
  get avatarIcon() {
    return this.j.avatarIcon;
  }
  get agent() {
    return this.j.agent;
  }
  get slashCommand() {
    return this.j.slashCommand;
  }
  get agentOrSlashCommandDetected() {
    return this.j.agentOrSlashCommandDetected;
  }
  get response() {
    return this.j.response;
  }
  get usedContext() {
    return this.j.usedContext;
  }
  get contentReferences() {
    return this.j.contentReferences;
  }
  get codeCitations() {
    return this.j.codeCitations;
  }
  get progressMessages() {
    return this.j.progressMessages;
  }
  get isComplete() {
    return this.j.isComplete;
  }
  get isCanceled() {
    return this.j.isCanceled;
  }
  get isHidden() {
    return this.j.isHidden;
  }
  get isCompleteAddedRequest() {
    return this.j.isCompleteAddedRequest;
  }
  get replyFollowups() {
    return this.j.followups?.filter((f) => f.kind === "reply");
  }
  get result() {
    return this.j.result;
  }
  get errorDetails() {
    return this.result?.errorDetails;
  }
  get vote() {
    return this.j.vote;
  }
  get voteDownReason() {
    return this.j.voteDownReason;
  }
  get requestId() {
    return this.j.requestId;
  }
  get isStale() {
    return this.j.isStale;
  }
  get isLast() {
    return this.m.getItems().at(-1) === this;
  }
  get usedReferencesExpanded() {
    if (typeof this.c === "boolean") {
      return this.c;
    }
    return this.response.value.length === 0 && !this.errorDetails;
  }
  set usedReferencesExpanded(v) {
    this.c = v;
  }
  get vulnerabilitiesListExpanded() {
    return this.g;
  }
  set vulnerabilitiesListExpanded(v) {
    this.g = v;
  }
  get contentUpdateTimings() {
    return this.h;
  }
  constructor(j, m, n, r2) {
    super();
    this.j = j;
    this.m = m;
    this.n = n;
    this.r = r2;
    this.a = 0;
    this.b = this.B(new $ze());
    this.onDidChange = this.b.event;
    this.renderData = void 0;
    this.g = false;
    this.h = void 0;
    if (!j.isComplete) {
      this.h = {
        firstWordTime: 0,
        lastUpdateTime: Date.now(),
        impliedWordLoadRate: 0,
        lastWordCount: 0
      };
    }
    this.B(j.onDidChange(() => {
      if (this.h) {
        const now = Date.now();
        const wordCount = $0rb(j.response.getMarkdown());
        const timeDiff = Math.max(now - this.h.firstWordTime, 250);
        const impliedWordLoadRate = this.h.lastWordCount / (timeDiff / 1e3);
        this.s("onDidChange", `Update- got ${this.h.lastWordCount} words over last ${timeDiff}ms = ${impliedWordLoadRate} words/s. ${wordCount} words are now available.`);
        this.h = {
          firstWordTime: this.h.firstWordTime === 0 && this.response.value.some((v) => v.kind === "markdownContent") ? now : this.h.firstWordTime,
          lastUpdateTime: now,
          impliedWordLoadRate,
          lastWordCount: wordCount
        };
      } else {
        this.n.warn("ChatResponseViewModel#onDidChange: got model update but contentUpdateTimings is not initialized");
      }
      this.a++;
      this.b.fire();
    }));
  }
  s(tag2, message) {
    this.n.trace(`ChatResponseViewModel#${tag2}: ${message}`);
  }
  setVote(vote) {
    this.a++;
    this.j.setVote(vote);
  }
  setVoteDownReason(reason) {
    this.a++;
    this.j.setVoteDownReason(reason);
  }
  setEditApplied(edit3, editCount) {
    this.a++;
    this.j.setEditApplied(edit3, editCount);
  }
};
$dsb = __decorate([
  __param(2, $wn),
  __param(3, $3O)
], $dsb);

// out-build/vs/workbench/contrib/chat/browser/chatEditorInput.js
var $Zzb_1;
var ChatEditorIcon = $9r("chat-editor-label-icon", $6l.commentDiscussion, localize(4880, null));
var $Zzb = class $Zzb2 extends $nG {
  static {
    $Zzb_1 = this;
  }
  static {
    this.countsInUse = /* @__PURE__ */ new Set();
  }
  static {
    this.TypeID = "workbench.input.chatSession";
  }
  static {
    this.EditorID = "workbench.editor.chatSession";
  }
  static getNewEditorUri() {
    const handle2 = Math.floor(Math.random() * 1e9);
    return ChatUri.generate(handle2);
  }
  static getNextCount() {
    let count = 0;
    while ($Zzb_1.countsInUse.has(count)) {
      count++;
    }
    return count;
  }
  constructor(resource, options3, c) {
    super();
    this.resource = resource;
    this.options = options3;
    this.c = c;
    const parsed = ChatUri.parse(resource);
    if (typeof parsed?.handle !== "number") {
      throw new Error("Invalid chat URI");
    }
    this.sessionId = options3.target && "sessionId" in options3.target ? options3.target.sessionId : void 0;
    this.a = $Zzb_1.getNextCount();
    $Zzb_1.countsInUse.add(this.a);
    this.B($1c(() => $Zzb_1.countsInUse.delete(this.a)));
  }
  get editorId() {
    return $Zzb_1.EditorID;
  }
  get capabilities() {
    return super.capabilities | 8;
  }
  matches(otherInput) {
    return otherInput instanceof $Zzb_1 && otherInput.resource.toString() === this.resource.toString();
  }
  get typeId() {
    return $Zzb_1.TypeID;
  }
  getName() {
    return this.b?.title || localize(4881, null) + (this.a > 0 ? ` ${this.a + 1}` : "");
  }
  getIcon() {
    return ChatEditorIcon;
  }
  async resolve() {
    if (typeof this.sessionId === "string") {
      this.b = this.c.getOrRestoreSession(this.sessionId);
    } else if (!this.options.target) {
      this.b = this.c.startSession(ChatAgentLocation.Panel, CancellationToken.None);
    } else if ("data" in this.options.target) {
      this.b = this.c.loadSessionFromContent(this.options.target.data);
    }
    if (!this.b) {
      return null;
    }
    this.sessionId = this.b.sessionId;
    this.B(this.b.onDidChange(() => this.g.fire()));
    return this.B(new $1zb(this.b));
  }
  dispose() {
    super.dispose();
    if (this.sessionId) {
      this.c.clearSession(this.sessionId);
    }
  }
};
$Zzb = $Zzb_1 = __decorate([
  __param(2, $qO)
], $Zzb);
var $1zb = class extends $3c {
  constructor(model) {
    super();
    this.model = model;
    this.a = this.B(new $ze());
    this.onWillDispose = this.a.event;
    this.b = false;
    this.c = false;
  }
  async resolve() {
    this.c = true;
  }
  isResolved() {
    return this.c;
  }
  isDisposed() {
    return this.b;
  }
  dispose() {
    super.dispose();
    this.b = true;
  }
};
var ChatUri;
(function(ChatUri2) {
  ChatUri2.scheme = Schemas.vscodeChatSesssion;
  function generate(handle2) {
    return URI.from({ scheme: ChatUri2.scheme, path: `chat-${handle2}` });
  }
  ChatUri2.generate = generate;
  function parse4(resource) {
    if (resource.scheme !== ChatUri2.scheme) {
      return void 0;
    }
    const match = resource.path.match(/chat-(\d+)/);
    const handleStr = match?.[1];
    if (typeof handleStr !== "string") {
      return void 0;
    }
    const handle2 = parseInt(handleStr);
    if (isNaN(handle2)) {
      return void 0;
    }
    return { handle: handle2 };
  }
  ChatUri2.parse = parse4;
})(ChatUri || (ChatUri = {}));
var $2zb = class {
  canSerialize(input) {
    return input instanceof $Zzb && typeof input.sessionId === "string";
  }
  serialize(input) {
    if (!this.canSerialize(input)) {
      return void 0;
    }
    const obj = {
      options: input.options,
      sessionId: input.sessionId,
      resource: input.resource
    };
    return JSON.stringify(obj);
  }
  deserialize(instantiationService, serializedEditor) {
    try {
      const parsed = JSON.parse(serializedEditor);
      const resource = URI.revive(parsed.resource);
      return instantiationService.createInstance($Zzb, resource, { ...parsed.options, target: { sessionId: parsed.sessionId } });
    } catch (err) {
      return void 0;
    }
  }
};

// out-build/vs/workbench/contrib/chat/browser/contrib/screenshot.js
var $tNb = "screenshot-focused-window";
function $uNb(buffer) {
  return {
    id: $tNb,
    name: localize(5061, null),
    value: new Uint8Array(buffer),
    isImage: true,
    isDynamic: true
  };
}

// out-build/vs/workbench/contrib/chat/browser/actions/chatClear.js
async function $3zb(accessor, chatEditorInput) {
  const editorService = accessor.get($mJ);
  if (!chatEditorInput) {
    const editorInput = editorService.activeEditor;
    chatEditorInput = editorInput instanceof $Zzb ? editorInput : void 0;
  }
  if (chatEditorInput instanceof $Zzb) {
    const identifier2 = editorService.findEditors(chatEditorInput.resource)[0];
    await editorService.replaceEditors([{
      editor: chatEditorInput,
      replacement: { resource: $Zzb.getNewEditorUri(), options: { pinned: true } }
    }], identifier2.groupId);
  }
}

// out-build/vs/workbench/contrib/chat/browser/actions/chatActions.js
var $vNb = localize2(4636, "Chat");
var $wNb = "workbench.action.chat.open";
var OpenChatGlobalAction = class _OpenChatGlobalAction extends $gJ {
  static {
    this.TITLE = localize2(4637, "Open Chat");
  }
  constructor() {
    super({
      id: $wNb,
      title: _OpenChatGlobalAction.TITLE,
      icon: $6l.copilot,
      f1: true,
      precondition: $7m.or(ChatContextKeys.Setup.installed, ChatContextKeys.panelParticipantRegistered),
      category: $vNb,
      keybinding: {
        weight: 200,
        primary: 2048 | 512 | 39,
        mac: {
          primary: 2048 | 256 | 39
          /* KeyCode.KeyI */
        }
      },
      menu: {
        id: $bJ.ChatCommandCenter,
        group: "a_open",
        order: 1
      }
    });
  }
  async run(accessor, opts) {
    opts = typeof opts === "string" ? { query: opts } : opts;
    const chatService = accessor.get($qO);
    const chatVariablesService = accessor.get($kO);
    const viewsService = accessor.get($uob);
    const hostService = accessor.get($S4);
    const chatWidget = await $3Nb(viewsService);
    if (!chatWidget) {
      return;
    }
    if (opts?.previousRequests?.length && chatWidget.viewModel) {
      for (const { request, response } of opts.previousRequests) {
        chatService.addCompleteRequest(chatWidget.viewModel.sessionId, request, void 0, 0, { message: response });
      }
    }
    if (opts?.attachScreenshot) {
      const screenshot = await hostService.getScreenshot();
      if (screenshot) {
        chatWidget.attachmentModel.addContext($uNb(screenshot));
      }
    }
    if (opts?.query) {
      if (opts.isPartialQuery) {
        chatWidget.setInput(opts.query);
      } else {
        chatWidget.acceptInput(opts.query);
      }
    }
    if (opts?.variableIds && opts.variableIds.length > 0) {
      const actualVariables = chatVariablesService.getVariables(ChatAgentLocation.Panel);
      for (const actualVariable of actualVariables) {
        if (opts.variableIds.includes(actualVariable.id)) {
          chatWidget.attachmentModel.addContext({
            range: void 0,
            id: actualVariable.id ?? "",
            value: void 0,
            fullName: actualVariable.fullName,
            name: actualVariable.name,
            icon: actualVariable.icon
          });
        }
      }
    }
    chatWidget.focusInput();
  }
};
var ChatHistoryAction = class extends $gJ {
  constructor() {
    super({
      id: `workbench.action.chat.history`,
      title: localize2(4638, "Show Chats..."),
      menu: {
        id: $bJ.ViewTitle,
        when: $7m.equals("view", $9Nb),
        group: "navigation",
        order: 2
      },
      category: $vNb,
      icon: $6l.history,
      f1: true,
      precondition: ChatContextKeys.enabled
    });
  }
  async run(accessor) {
    const chatService = accessor.get($qO);
    const quickInputService = accessor.get($1M);
    const viewsService = accessor.get($uob);
    const editorService = accessor.get($mJ);
    const showPicker = () => {
      const openInEditorButton = {
        iconClass: ThemeIcon.asClassName($6l.file),
        tooltip: localize(4624, null)
      };
      const deleteButton = {
        iconClass: ThemeIcon.asClassName($6l.x),
        tooltip: localize(4625, null)
      };
      const renameButton = {
        iconClass: ThemeIcon.asClassName($6l.pencil),
        tooltip: localize(4626, null)
      };
      const getPicks = () => {
        const items = chatService.getHistory();
        items.sort((a, b) => (b.lastMessageDate ?? 0) - (a.lastMessageDate ?? 0));
        let lastDate = void 0;
        const picks2 = items.flatMap((i2) => {
          const timeAgoStr = $Ru(i2.lastMessageDate, true, true);
          const separator = timeAgoStr !== lastDate ? {
            type: "separator",
            label: timeAgoStr
          } : void 0;
          lastDate = timeAgoStr;
          return [
            separator,
            {
              label: i2.title,
              description: i2.isActive ? `(${localize(4627, null)})` : "",
              chat: i2,
              buttons: i2.isActive ? [renameButton] : [
                renameButton,
                openInEditorButton,
                deleteButton
              ]
            }
          ];
        });
        return $Mb(picks2);
      };
      const store = new $2c();
      const picker = store.add(quickInputService.createQuickPick({ useSeparators: true }));
      picker.placeholder = localize(4628, null);
      const picks = getPicks();
      picker.items = picks;
      store.add(picker.onDidTriggerItemButton(async (context) => {
        if (context.button === openInEditorButton) {
          const options3 = { target: { sessionId: context.item.chat.sessionId }, pinned: true };
          editorService.openEditor({ resource: $Zzb.getNewEditorUri(), options: options3 }, $nJ);
          picker.hide();
        } else if (context.button === deleteButton) {
          chatService.removeHistoryEntry(context.item.chat.sessionId);
          picker.items = getPicks();
        } else if (context.button === renameButton) {
          const title = await quickInputService.input({ title: localize(4629, null), value: context.item.chat.title });
          if (title) {
            chatService.setChatSessionTitle(context.item.chat.sessionId, title);
          }
          showPicker();
        }
      }));
      store.add(picker.onDidAccept(async () => {
        try {
          const item = picker.selectedItems[0];
          const sessionId = item.chat.sessionId;
          const view = await viewsService.openView($9Nb);
          view.loadSession(sessionId);
        } finally {
          picker.hide();
        }
      }));
      store.add(picker.onDidHide(() => store.dispose()));
      picker.show();
    };
    showPicker();
  }
};
var OpenChatEditorAction = class extends $gJ {
  constructor() {
    super({
      id: `workbench.action.openChat`,
      title: localize2(4639, "Open Editor"),
      f1: true,
      category: $vNb,
      precondition: ChatContextKeys.enabled
    });
  }
  async run(accessor) {
    const editorService = accessor.get($mJ);
    await editorService.openEditor({ resource: $Zzb.getNewEditorUri(), options: { pinned: true } });
  }
};
var ChatAddAction = class extends $gJ {
  constructor() {
    super({
      id: "workbench.action.chat.addParticipant",
      title: localize2(4640, "Chat with Extension"),
      icon: $6l.mention,
      f1: false,
      category: $vNb,
      menu: {
        id: $bJ.ChatInput,
        when: ChatContextKeys.location.isEqualTo(ChatAgentLocation.Panel),
        group: "navigation",
        order: 1
      }
    });
  }
  async run(accessor, ...args2) {
    const widgetService = accessor.get($2Nb);
    const context = args2[0];
    const widget = context?.widget ?? widgetService.lastFocusedWidget;
    if (!widget) {
      return;
    }
    const hasAgentOrCommand = $GO(widget.parsedInput);
    if (hasAgentOrCommand?.agentPart || hasAgentOrCommand?.commandPart) {
      return;
    }
    const suggestCtrl = $qdb.get(widget.inputEditor);
    if (suggestCtrl) {
      const curText = widget.inputEditor.getValue();
      const newValue = curText ? `@ ${curText}` : "@";
      if (!curText.startsWith("@")) {
        widget.inputEditor.setValue(newValue);
      }
      widget.inputEditor.setPosition(new $8C(1, 2));
      suggestCtrl.triggerSuggest(void 0, true);
    }
  }
};
$dJ.appendMenuItem($bJ.ViewTitle, {
  command: {
    id: "update.showCurrentReleaseNotes",
    title: localize2(4641, "Explore New Features")
  },
  when: $7m.equals("view", $9Nb)
});
function $xNb() {
  $hJ(OpenChatGlobalAction);
  $hJ(ChatHistoryAction);
  $hJ(OpenChatEditorAction);
  $hJ(ChatAddAction);
  $hJ(class ClearChatInputHistoryAction extends $gJ {
    constructor() {
      super({
        id: "workbench.action.chat.clearInputHistory",
        title: localize2(4642, "Clear Input History"),
        precondition: ChatContextKeys.enabled,
        category: $vNb,
        f1: true
      });
    }
    async run(accessor, ...args2) {
      const historyService = accessor.get($jzb);
      historyService.clearHistory();
    }
  });
  $hJ(class ClearChatHistoryAction extends $gJ {
    constructor() {
      super({
        id: "workbench.action.chat.clearHistory",
        title: localize2(4643, "Clear All Workspace Chats"),
        precondition: ChatContextKeys.enabled,
        category: $vNb,
        f1: true
      });
    }
    async run(accessor, ...args2) {
      const editorGroupsService = accessor.get($iJ);
      const viewsService = accessor.get($uob);
      const chatService = accessor.get($qO);
      chatService.clearAllHistoryEntries();
      const chatView = viewsService.getViewWithId($9Nb);
      if (chatView) {
        chatView.widget.clear();
      }
      editorGroupsService.groups.forEach((group2) => {
        group2.editors.forEach((editor) => {
          if (editor instanceof $Zzb) {
            $3zb(accessor, editor);
          }
        });
      });
    }
  });
  $hJ(class FocusChatAction extends $25 {
    constructor() {
      super({
        id: "chat.action.focus",
        title: localize2(4644, "Focus Chat List"),
        precondition: $7m.and(ChatContextKeys.inChatInput),
        category: $vNb,
        keybinding: [
          // On mac, require that the cursor is at the top of the input, to avoid stealing cmd+up to move the cursor to the top
          {
            when: $7m.and(ChatContextKeys.inputCursorAtTop, ChatContextKeys.inQuickChat.negate()),
            primary: 2048 | 16,
            weight: 100
          },
          // On win/linux, ctrl+up can always focus the chat list
          {
            when: $7m.and($7m.or($ueb, $teb), ChatContextKeys.inQuickChat.negate()),
            primary: 2048 | 16,
            weight: 100
          },
          {
            when: $7m.and(ChatContextKeys.inChatSession, ChatContextKeys.inQuickChat),
            primary: 2048 | 18,
            weight: 200
          }
        ]
      });
    }
    runEditorCommand(accessor, editor) {
      const editorUri = editor.getModel()?.uri;
      if (editorUri) {
        const widgetService = accessor.get($2Nb);
        widgetService.getWidgetByInputUri(editorUri)?.focusLastMessage();
      }
    }
  });
  $hJ(class FocusChatInputAction extends $gJ {
    constructor() {
      super({
        id: "workbench.action.chat.focusInput",
        title: localize2(4645, "Focus Chat Input"),
        f1: false,
        keybinding: [
          {
            primary: 2048 | 18,
            weight: 200,
            when: $7m.and(ChatContextKeys.inChatSession, ChatContextKeys.inChatInput.negate(), ChatContextKeys.inQuickChat.negate())
          },
          {
            when: $7m.and(ChatContextKeys.inChatSession, ChatContextKeys.inChatInput.negate(), ChatContextKeys.inQuickChat),
            primary: 2048 | 16,
            weight: 200
          }
        ]
      });
    }
    run(accessor, ...args2) {
      const widgetService = accessor.get($2Nb);
      widgetService.lastFocusedWidget?.focusInput();
    }
  });
  function registerOpenLinkAction(id2, title, url, order) {
    $hJ(class extends $gJ {
      constructor() {
        super({
          id: id2,
          title,
          category: $vNb,
          f1: true,
          precondition: ChatContextKeys.enabled,
          menu: {
            id: $bJ.ChatCommandCenter,
            group: "y_manage",
            order
          }
        });
      }
      async run(accessor) {
        const openerService = accessor.get($O4);
        openerService.open(URI.parse(url));
      }
    });
  }
  registerOpenLinkAction("workbench.action.chat.managePlan", localize2(4646, "Manage Copilot Plan"), defaultChat.managePlanUrl, 1);
  registerOpenLinkAction("workbench.action.chat.manageSettings", localize2(4647, "Manage Copilot Settings"), defaultChat.manageSettingsUrl, 2);
  registerOpenLinkAction("workbench.action.chat.learnMore", localize2(4648, "Learn More"), defaultChat.documentationUrl, 3);
  $hJ(class ShowExtensionsUsingCopilit extends $gJ {
    constructor() {
      super({
        id: "workbench.action.chat.showExtensionsUsingCopilot",
        title: localize2(4649, "Show Extensions using Copilot"),
        f1: true,
        category: $uzb
      });
    }
    async run(accessor) {
      const extensionsWorkbenchService = accessor.get($vzb);
      extensionsWorkbenchService.openSearch(`@feature:${$2rb}`);
    }
  });
}
function $yNb(item, includeName = true) {
  if ($_rb(item)) {
    return (includeName ? `${item.username}: ` : "") + item.messageText;
  } else {
    return (includeName ? `${item.username}: ` : "") + item.response.toString();
  }
}
var defaultChat = {
  documentationUrl: product_default.defaultChatAgent?.documentationUrl ?? "",
  manageSettingsUrl: product_default.defaultChatAgent?.manageSettingsUrl ?? "",
  managePlanUrl: product_default.defaultChatAgent?.managePlanUrl ?? ""
};
$dJ.appendMenuItem($bJ.CommandCenter, {
  submenu: $bJ.ChatCommandCenter,
  title: localize(4630, null),
  icon: $6l.copilot,
  when: $7m.and($7m.has("config.chat.commandCenter.enabled"), $7m.or($7m.has("config.chat.experimental.offerSetup"), ChatContextKeys.Setup.installed, ChatContextKeys.panelParticipantRegistered)),
  order: 10001
});
$hJ(class ToggleCopilotControl extends $Rzb {
  constructor() {
    super("chat.commandCenter.enabled", localize(4631, null), localize(4632, null), 4, false, $7m.and($7m.has("config.window.commandCenter"), $7m.or(ChatContextKeys.Setup.installed, $7m.has("config.chat.experimental.offerSetup"), ChatContextKeys.panelParticipantRegistered)));
  }
});
var $zNb = class $zNb2 extends $3c {
  static {
    this.ID = "chat.commandCenterRendering";
  }
  constructor(actionViewItemService, agentService, chatQuotasService, instantiationService, contextKeyService) {
    super();
    const contextKeySet = /* @__PURE__ */ new Set([ChatContextKeys.Setup.signedOut.key]);
    actionViewItemService.register($bJ.CommandCenter, $bJ.ChatCommandCenter, (action, options3) => {
      if (!(action instanceof $eJ)) {
        return void 0;
      }
      const dropdownAction = $Zm({
        id: "chat.commandCenter.more",
        label: localize(4633, null),
        run() {
        }
      });
      const chatExtensionInstalled = agentService.getAgents().some((agent) => agent.isDefault);
      const { chatQuotaExceeded, completionsQuotaExceeded } = chatQuotasService.quotas;
      const signedOut = contextKeyService.getContextKeyValue(ChatContextKeys.Setup.signedOut.key) ?? false;
      let primaryActionId;
      let primaryActionTitle;
      let primaryActionIcon;
      if (!chatExtensionInstalled) {
        primaryActionId = "workbench.action.chat.triggerSetup";
        primaryActionTitle = localize(4634, null);
        primaryActionIcon = $6l.copilot;
      } else {
        if (signedOut) {
          primaryActionId = $wNb;
          primaryActionTitle = localize(4635, null);
          primaryActionIcon = $6l.copilotWarning;
        } else if (chatQuotaExceeded || completionsQuotaExceeded) {
          primaryActionId = $Vzb;
          primaryActionTitle = $Yzb({ chatQuotaExceeded, completionsQuotaExceeded });
          primaryActionIcon = $6l.copilotWarning;
        } else {
          primaryActionId = $wNb;
          primaryActionTitle = OpenChatGlobalAction.TITLE.value;
          primaryActionIcon = $6l.copilot;
        }
      }
      return instantiationService.createInstance($isb, instantiationService.createInstance($fJ, {
        id: primaryActionId,
        title: primaryActionTitle,
        icon: primaryActionIcon
      }, void 0, void 0, void 0, void 0), dropdownAction, action.actions, "", { ...options3, skipTelemetry: true });
    }, Event2.any(agentService.onDidChangeAgents, chatQuotasService.onDidChangeQuotas, Event2.filter(contextKeyService.onDidChangeContext, (e) => e.affectsSome(contextKeySet))));
  }
};
$zNb = __decorate([
  __param(0, $1$),
  __param(1, $ZO),
  __param(2, $Uzb),
  __param(3, $Pk),
  __param(4, $on)
], $zNb);

// out-build/vs/workbench/contrib/chat/browser/actions/chatExecuteActions.js
var SubmitAction = class extends $gJ {
  run(accessor, ...args2) {
    const context = args2[0];
    const widgetService = accessor.get($2Nb);
    const widget = context?.widget ?? widgetService.lastFocusedWidget;
    widget?.acceptInput(context?.inputValue);
  }
};
var $HNb = class _$HNb extends SubmitAction {
  static {
    this.ID = "workbench.action.chat.submit";
  }
  constructor() {
    super({
      id: _$HNb.ID,
      title: localize2(4697, "Send and Dispatch"),
      f1: false,
      category: $vNb,
      icon: $6l.send,
      precondition: $7m.and(ChatContextKeys.inputHasText, ChatContextKeys.requestInProgress.negate(), ChatContextKeys.location.notEqualsTo(ChatAgentLocation.EditingSession)),
      keybinding: {
        when: ChatContextKeys.inChatInput,
        primary: 3,
        weight: 100
        /* KeybindingWeight.EditorContrib */
      },
      menu: [
        {
          id: $bJ.ChatExecuteSecondary,
          group: "group_1",
          order: 1
        },
        {
          id: $bJ.ChatExecute,
          order: 4,
          when: $7m.and(ChatContextKeys.requestInProgress.negate(), ChatContextKeys.location.notEqualsTo(ChatAgentLocation.EditingSession)),
          group: "navigation"
        }
      ]
    });
  }
};
var $INb = class _$INb extends SubmitAction {
  static {
    this.ID = "workbench.action.edits.submit";
  }
  constructor() {
    super({
      id: _$INb.ID,
      title: localize2(4698, "Send"),
      f1: false,
      category: $vNb,
      icon: $6l.send,
      precondition: $7m.and(ChatContextKeys.inputHasText, ChatContextKeys.requestInProgress.negate(), ChatContextKeys.location.isEqualTo(ChatAgentLocation.EditingSession), $eP.toNegated()),
      keybinding: {
        when: ChatContextKeys.inChatInput,
        primary: 3,
        weight: 100
        /* KeybindingWeight.EditorContrib */
      },
      menu: [
        {
          id: $bJ.ChatExecuteSecondary,
          group: "group_1",
          when: $7m.and(ChatContextKeys.requestInProgress.negate(), ChatContextKeys.location.isEqualTo(ChatAgentLocation.EditingSession), $eP.toNegated()),
          order: 1
        },
        {
          id: $bJ.ChatExecute,
          order: 4,
          when: $7m.and(ChatContextKeys.requestInProgress.negate(), ChatContextKeys.location.isEqualTo(ChatAgentLocation.EditingSession), $eP.toNegated()),
          group: "navigation"
        }
      ]
    });
  }
};
var SubmitWithoutDispatchingAction = class _SubmitWithoutDispatchingAction extends $gJ {
  static {
    this.ID = "workbench.action.chat.submitWithoutDispatching";
  }
  constructor() {
    super({
      id: _SubmitWithoutDispatchingAction.ID,
      title: localize2(4699, "Send"),
      f1: false,
      category: $vNb,
      precondition: $7m.and(ChatContextKeys.inputHasText, ChatContextKeys.requestInProgress.negate(), $7m.and($7m.or(ChatContextKeys.location.isEqualTo(ChatAgentLocation.Panel), ChatContextKeys.location.isEqualTo(ChatAgentLocation.Editor)))),
      keybinding: {
        when: ChatContextKeys.inChatInput,
        primary: 512 | 1024 | 3,
        weight: 100
        /* KeybindingWeight.EditorContrib */
      },
      menu: [
        {
          id: $bJ.ChatExecuteSecondary,
          group: "group_1",
          order: 2
        }
        // need 'when'?
      ]
    });
  }
  run(accessor, ...args2) {
    const context = args2[0];
    const widgetService = accessor.get($2Nb);
    const widget = context?.widget ?? widgetService.lastFocusedWidget;
    widget?.acceptInput(context?.inputValue, { noCommandDetection: true });
  }
};
var $JNb = "workbench.action.chat.pickModel";
$dJ.appendMenuItem($bJ.ChatExecute, {
  command: {
    id: $JNb,
    title: localize2(4700, "Pick Model")
  },
  order: 3,
  group: "navigation",
  when: $7m.and(ChatContextKeys.languageModelsAreUserSelectable, $7m.or($7m.equals(ChatContextKeys.location.key, ChatAgentLocation.Panel), $7m.equals(ChatContextKeys.location.key, ChatAgentLocation.EditingSession), $7m.equals(ChatContextKeys.location.key, ChatAgentLocation.Editor), $7m.equals(ChatContextKeys.location.key, ChatAgentLocation.Notebook), $7m.equals(ChatContextKeys.location.key, ChatAgentLocation.Terminal)))
});
var $KNb = class _$KNb extends $gJ {
  static {
    this.ID = "workbench.action.chat.submitSecondaryAgent";
  }
  constructor() {
    super({
      id: _$KNb.ID,
      title: localize2(4701, "Submit to Secondary Agent"),
      precondition: $7m.and(ChatContextKeys.inputHasText, ChatContextKeys.inputHasAgent.negate(), ChatContextKeys.requestInProgress.negate()),
      menu: {
        id: $bJ.ChatExecuteSecondary,
        group: "group_1",
        order: 3,
        when: $7m.equals(ChatContextKeys.location.key, ChatAgentLocation.Panel)
      },
      keybinding: {
        when: ChatContextKeys.inChatInput,
        primary: 2048 | 3,
        weight: 100
        /* KeybindingWeight.EditorContrib */
      }
    });
  }
  run(accessor, ...args2) {
    const context = args2[0];
    const agentService = accessor.get($ZO);
    const secondaryAgent = agentService.getSecondaryAgent();
    if (!secondaryAgent) {
      return;
    }
    const widgetService = accessor.get($2Nb);
    const widget = context?.widget ?? widgetService.lastFocusedWidget;
    if (!widget) {
      return;
    }
    if ($GO(widget.parsedInput).agentPart) {
      widget.acceptInput();
    } else {
      widget.lastSelectedAgent = secondaryAgent;
      widget.acceptInputWithPrefix(`${$xO}${secondaryAgent.name}`);
    }
  }
};
var SendToChatEditingAction = class extends $gJ {
  constructor() {
    super({
      id: "workbench.action.chat.sendToChatEditing",
      title: localize2(4702, "Send to Copilot Edits"),
      precondition: $7m.and(ChatContextKeys.requestInProgress.negate(), ChatContextKeys.inputHasAgent.negate(), ChatContextKeys.inputHasText),
      category: $vNb,
      f1: false,
      menu: {
        id: $bJ.ChatExecuteSecondary,
        group: "group_1",
        order: 4,
        when: $7m.and(ChatContextKeys.enabled, ChatContextKeys.editingParticipantRegistered, ChatContextKeys.location.notEqualsTo(ChatAgentLocation.EditingSession), ChatContextKeys.location.notEqualsTo(ChatAgentLocation.Editor))
      },
      keybinding: {
        weight: 200,
        primary: 2048 | 512 | 3,
        when: $7m.and(ChatContextKeys.enabled, ChatContextKeys.editingParticipantRegistered, ChatContextKeys.location.notEqualsTo(ChatAgentLocation.EditingSession), ChatContextKeys.location.notEqualsTo(ChatAgentLocation.Editor))
      }
    });
  }
  async run(accessor, ...args2) {
    if (!accessor.get($ZO).getDefaultAgent(ChatAgentLocation.EditingSession)) {
      return;
    }
    const context = args2[0];
    const widgetService = accessor.get($2Nb);
    const widget = context?.widget ?? widgetService.lastFocusedWidget;
    if (!widget || widget.viewModel?.model.initialLocation === ChatAgentLocation.EditingSession) {
      return;
    }
    const viewsService = accessor.get($uob);
    const dialogService = accessor.get($Yv);
    const chatEditingService = accessor.get($$O);
    const currentEditingSession = chatEditingService.currentEditingSessionObs.get();
    const currentEditCount = currentEditingSession?.entries.get().length;
    if (currentEditCount) {
      const result = await dialogService.confirm({
        title: localize(4693, null),
        message: currentEditCount === 1 ? localize(4694, null, currentEditCount) : localize(4695, null, currentEditCount),
        type: "info",
        primaryButton: localize(4696, null)
      });
      if (!result.confirmed) {
        return;
      }
      await currentEditingSession?.stop(true);
    }
    const { widget: editingWidget } = await viewsService.openView($0Nb);
    for (const attachment of widget.attachmentModel.attachments) {
      if (attachment.isFile && URI.isUri(attachment.value)) {
        chatEditingService.currentEditingSessionObs.get()?.addFileToWorkingSet(attachment.value);
      } else {
        editingWidget.attachmentModel.addContext(attachment);
      }
    }
    editingWidget.setInput(widget.getInput());
    widget.setInput("");
    widget.attachmentModel.clear();
    editingWidget.acceptInput();
    editingWidget.focusInput();
  }
};
var SendToNewChatAction = class extends $gJ {
  constructor() {
    super({
      id: "workbench.action.chat.sendToNewChat",
      title: localize2(4703, "Send to New Chat"),
      precondition: $7m.and(ChatContextKeys.requestInProgress.negate(), ChatContextKeys.inputHasText),
      category: $vNb,
      f1: false,
      menu: {
        id: $bJ.ChatExecuteSecondary,
        group: "group_2",
        when: $7m.equals(ChatContextKeys.location.key, ChatAgentLocation.Panel)
      },
      keybinding: {
        weight: 200,
        primary: 2048 | 1024 | 3,
        when: ChatContextKeys.inChatInput
      }
    });
  }
  async run(accessor, ...args2) {
    const context = args2[0];
    const widgetService = accessor.get($2Nb);
    const widget = context?.widget ?? widgetService.lastFocusedWidget;
    if (!widget) {
      return;
    }
    widget.clear();
    widget.acceptInput(context?.inputValue);
  }
};
var $LNb = class _$LNb extends $gJ {
  static {
    this.ID = "workbench.action.chat.cancel";
  }
  constructor() {
    super({
      id: _$LNb.ID,
      title: localize2(4704, "Cancel"),
      f1: false,
      category: $vNb,
      icon: $6l.stopCircle,
      menu: {
        id: $bJ.ChatExecute,
        when: $7m.or(ChatContextKeys.requestInProgress, $7m.and(ChatContextKeys.location.isEqualTo(ChatAgentLocation.EditingSession), $eP)),
        order: 4,
        group: "navigation"
      },
      keybinding: {
        weight: 200,
        primary: 2048 | 9,
        win: {
          primary: 512 | 1
          /* KeyCode.Backspace */
        }
      }
    });
  }
  run(accessor, ...args2) {
    const context = args2[0];
    const widgetService = accessor.get($2Nb);
    const widget = context?.widget ?? widgetService.lastFocusedWidget;
    if (!widget) {
      return;
    }
    const chatService = accessor.get($qO);
    if (widget.viewModel) {
      chatService.cancelCurrentRequestForSession(widget.viewModel.sessionId);
    }
    const chatEditingService = accessor.get($$O);
    const currentEditingSession = chatEditingService.currentEditingSession;
    if (currentEditingSession && currentEditingSession?.chatSessionId === widget.viewModel?.sessionId) {
      chatEditingService.currentAutoApplyOperation?.cancel();
    }
  }
};
function $MNb() {
  $hJ($HNb);
  $hJ($INb);
  $hJ(SubmitWithoutDispatchingAction);
  $hJ($LNb);
  $hJ(SendToNewChatAction);
  $hJ($KNb);
  $hJ(SendToChatEditingAction);
}

// out-build/vs/workbench/contrib/chat/browser/attachments/implicitContextAttachment.js
var $NNb = class $NNb2 extends $3c {
  constructor(b, c, f, g, h3, j, m, n, r2, s) {
    super();
    this.b = b;
    this.c = c;
    this.f = f;
    this.g = g;
    this.h = h3;
    this.j = j;
    this.m = m;
    this.n = n;
    this.r = r2;
    this.s = s;
    this.a = this.B(new $2c());
    this.domNode = $(".chat-attached-context-attachment.show-file-icons.implicit");
    this.t();
  }
  t() {
    $$i(this.domNode);
    this.a.clear();
    this.domNode.classList.toggle("disabled", !this.b.enabled);
    const label3 = this.c.create(this.domNode, { supportIcons: true });
    const file = URI.isUri(this.b.value) ? this.b.value : this.b.value.uri;
    const range = URI.isUri(this.b.value) || !this.b.isSelection ? void 0 : this.b.value.range;
    const fileBasename = $sh(file);
    const fileDirname = $uh(file);
    const friendlyName = `${fileBasename} ${fileDirname}`;
    const ariaLabel = range ? localize(4748, null, friendlyName, range.startLineNumber, range.endLineNumber) : localize(4749, null, friendlyName);
    const uriLabel = this.j.getUriLabel(file, { relative: true });
    const currentFile = localize(4750, null);
    const inactive = localize(4751, null);
    const currentFileHint = currentFile + (this.b.enabled ? "" : ` (${inactive})`);
    const title = `${currentFileHint}
${uriLabel}`;
    label3.setFile(file, {
      fileKind: FileKind.FILE,
      hidePath: true,
      range,
      title
    });
    this.domNode.ariaLabel = ariaLabel;
    this.domNode.tabIndex = 0;
    const hintElement = $bk(this.domNode, $("span.chat-implicit-hint", void 0, "Current file"));
    this.B(this.h.setupManagedHover($JZ("element"), hintElement, title));
    const buttonMsg = this.b.enabled ? localize(4752, null) : localize(4753, null);
    const toggleButton = this.a.add(new $k2(this.domNode, { supportIcons: true, title: buttonMsg }));
    toggleButton.icon = this.b.enabled ? $6l.eye : $6l.eyeClosed;
    this.a.add(toggleButton.onDidClick((e) => {
      e.stopPropagation();
      this.b.enabled = !this.b.enabled;
    }));
    const scopedContextKeyService = this.a.add(this.f.createScoped(this.domNode));
    const resourceContextKey = this.a.add(new $lqb(scopedContextKeyService, this.n, this.r, this.s));
    resourceContextKey.set(file);
    this.a.add($_i(this.domNode, $7j.CONTEXT_MENU, async (domEvent) => {
      const event = new $lf(getWindow(domEvent), domEvent);
      $9j.stop(domEvent, true);
      this.g.showContextMenu({
        contextKeyService: scopedContextKeyService,
        getAnchor: () => event,
        getActions: () => {
          const menu = this.m.getMenuActions($bJ.ChatInputResourceAttachmentContext, scopedContextKeyService, { arg: file });
          return $P$(menu);
        }
      });
    }));
  }
};
$NNb = __decorate([
  __param(2, $on),
  __param(3, $50),
  __param(4, $5$),
  __param(5, $ZI),
  __param(6, $cJ),
  __param(7, $km),
  __param(8, $1E),
  __param(9, $sG)
], $NNb);

// out-build/vs/workbench/contrib/chat/browser/chatAttachmentModel.js
var $esb = class extends $3c {
  constructor() {
    super(...arguments);
    this.a = /* @__PURE__ */ new Map();
    this.b = this.B(new $ze());
    this.onDidChangeContext = this.b.event;
  }
  get attachments() {
    return Array.from(this.a.values());
  }
  get size() {
    return this.a.size;
  }
  getAttachmentIDs() {
    return new Set(this.a.keys());
  }
  clear() {
    this.a.clear();
    this.b.fire();
  }
  delete(...variableEntryIds) {
    for (const variableEntryId of variableEntryIds) {
      this.a.delete(variableEntryId);
    }
    this.b.fire();
  }
  addFile(uri, range) {
    this.addContext(this.asVariableEntry(uri, range));
  }
  asVariableEntry(uri, range) {
    return {
      value: range ? { uri, range } : uri,
      id: uri.toString() + (range?.toString() ?? ""),
      name: $sh(uri),
      isFile: true,
      isDynamic: true
    };
  }
  addContext(...attachments) {
    let hasAdded = false;
    for (const attachment of attachments) {
      if (!this.a.has(attachment.id)) {
        this.a.set(attachment.id, attachment);
        hasAdded = true;
      }
    }
    if (hasAdded) {
      this.b.fire();
    }
  }
  clearAndSetContext(...attachments) {
    this.clear();
    this.addContext(...attachments);
  }
};
var $fsb = class $fsb2 extends $esb {
  get fileAttachments() {
    return this.attachments.filter((attachment) => attachment.isFile);
  }
  get excludedFileAttachments() {
    return this.f;
  }
  constructor(g) {
    super();
    this.g = g;
    this.c = this.B(new $ze());
    this.onFileLimitExceeded = this.c.event;
    this.f = [];
  }
  h(fileAttachmentId) {
    return this.f.some((attachment) => attachment.id === fileAttachmentId);
  }
  addContext(...attachments) {
    const currentAttachmentIds = this.getAttachmentIDs();
    const fileAttachments = attachments.filter((attachment) => attachment.isFile);
    const otherAttachments = attachments.filter((attachment) => !attachment.isFile);
    const newFileAttachments = [];
    const newFileAttachmentIds = /* @__PURE__ */ new Set();
    for (const attachment of fileAttachments) {
      if (newFileAttachmentIds.has(attachment.id) || currentAttachmentIds.has(attachment.id)) {
        continue;
      }
      newFileAttachmentIds.add(attachment.id);
      newFileAttachments.push(attachment);
    }
    const availableFileCount = Math.max(0, this.g.editingSessionFileLimit - this.fileAttachments.length);
    const fileAttachmentsToBeAdded = newFileAttachments.slice(0, availableFileCount);
    if (newFileAttachments.length > availableFileCount) {
      const attachmentsExceedingSize = newFileAttachments.slice(availableFileCount).filter((attachment) => !this.h(attachment.id));
      this.f.push(...attachmentsExceedingSize);
      this.b.fire();
      this.c.fire();
    }
    super.addContext(...otherAttachments, ...fileAttachmentsToBeAdded);
  }
  clear() {
    this.f.splice(0, this.f.length);
    super.clear();
  }
  delete(...variableEntryIds) {
    for (const variableEntryId of variableEntryIds) {
      const excludedFileIndex = this.f.findIndex((attachment) => attachment.id === variableEntryId);
      if (excludedFileIndex !== -1) {
        this.f.splice(excludedFileIndex, 1);
      }
    }
    super.delete(...variableEntryIds);
    if (this.fileAttachments.length < this.g.editingSessionFileLimit) {
      const availableFileCount = Math.max(0, this.g.editingSessionFileLimit - this.fileAttachments.length);
      const reAddAttachments = this.f.splice(0, availableFileCount);
      super.addContext(...reAddAttachments);
    }
  }
};
$fsb = __decorate([
  __param(0, $$O)
], $fsb);

// out-build/vs/workbench/contrib/chat/browser/chatContentParts/chatAttachmentsContentPart.js
var $LDb = new $nn("chatAttachmentResource", void 0, { type: "URI", description: localize(4784, null) });
var $MDb = class $MDb2 extends $3c {
  constructor(f, g = [], h3 = [], domNode = $(".chat-attached-context"), j, m, n, r2, s, t, u, w) {
    super();
    this.f = f;
    this.g = g;
    this.h = h3;
    this.domNode = domNode;
    this.j = j;
    this.m = m;
    this.n = n;
    this.r = r2;
    this.s = s;
    this.t = t;
    this.u = u;
    this.w = w;
    this.a = this.B(new $2c());
    this.b = this.B(new $ze());
    this.c = this.m.createInstance($lsb, { onDidChangeVisibility: this.b.event });
    this.y(domNode);
  }
  y(container2) {
    $$i(container2);
    this.a.clear();
    $gk(Boolean(this.f.length), this.domNode);
    const hoverDelegate = this.a.add($KZ());
    this.f.forEach(async (attachment) => {
      let resource = URI.isUri(attachment.value) ? attachment.value : attachment.value && typeof attachment.value === "object" && "uri" in attachment.value && URI.isUri(attachment.value.uri) ? attachment.value.uri : void 0;
      let range = attachment.value && typeof attachment.value === "object" && "range" in attachment.value && $9C.isIRange(attachment.value.range) ? attachment.value.range : void 0;
      if (resource && attachment.isFile && this.h.find((entry) => entry.toString() === resource?.toString())) {
        return;
      }
      const widget = $bk(container2, $(".chat-attached-context-attachment.show-file-icons"));
      const label3 = this.c.create(widget, { supportIcons: true, hoverDelegate, hoverTargetOverride: widget });
      const correspondingContentReference = this.g.find((ref) => typeof ref.reference === "object" && "variableName" in ref.reference && ref.reference.variableName === attachment.name);
      const isAttachmentOmitted = correspondingContentReference?.options?.status?.kind === ChatResponseReferencePartStatusKind2.Omitted;
      const isAttachmentPartialOrOmitted = isAttachmentOmitted || correspondingContentReference?.options?.status?.kind === ChatResponseReferencePartStatusKind2.Partial;
      let ariaLabel;
      if (resource && (attachment.isFile || attachment.isDirectory)) {
        const fileBasename = $rc(resource.path);
        const fileDirname = $qc(resource.path);
        const friendlyName = `${fileBasename} ${fileDirname}`;
        if (isAttachmentOmitted) {
          ariaLabel = range ? localize(4785, null, friendlyName, range.startLineNumber, range.endLineNumber) : localize(4786, null, friendlyName);
        } else if (isAttachmentPartialOrOmitted) {
          ariaLabel = range ? localize(4787, null, friendlyName, range.startLineNumber, range.endLineNumber) : localize(4788, null, friendlyName);
        } else {
          ariaLabel = range ? localize(4789, null, friendlyName, range.startLineNumber, range.endLineNumber) : localize(4790, null, friendlyName);
        }
        const fileOptions = {
          hidePath: true,
          title: correspondingContentReference?.options?.status?.description
        };
        label3.setFile(resource, attachment.isFile ? {
          ...fileOptions,
          fileKind: FileKind.FILE,
          range
        } : {
          ...fileOptions,
          fileKind: FileKind.FOLDER,
          icon: !this.u.getFileIconTheme().hasFolderIcons ? $js : void 0
        });
        this.m.invokeFunction((accessor) => {
          if (resource) {
            this.a.add($NDb(accessor, widget, resource));
          }
        });
      } else if (attachment.isImage) {
        ariaLabel = localize(4791, null, attachment.name);
        const hoverElement = $("div.chat-attached-context-hover");
        hoverElement.setAttribute("aria-label", ariaLabel);
        const pillIcon = $("div.chat-attached-context-pill", {}, $("span.codicon.codicon-file-media"));
        const textLabel = $("span.chat-attached-context-custom-text", {}, attachment.name);
        widget.appendChild(pillIcon);
        widget.appendChild(textLabel);
        let buffer;
        try {
          if (attachment.value instanceof URI) {
            const readFile = await this.s.readFile(attachment.value);
            buffer = readFile.value.buffer;
          } else {
            buffer = attachment.value;
          }
          await this.C(buffer, widget, hoverElement);
        } catch (error) {
          console.error("Error processing attachment:", error);
        }
        widget.style.position = "relative";
        if (!this.a.isDisposed) {
          this.a.add(this.r.setupManagedHover(hoverDelegate, widget, hoverElement));
        }
      } else if ($JO(attachment)) {
        ariaLabel = localize(4792, null, attachment.name);
        const classNames = ["file-icon", `${attachment.language}-lang-file-icon`];
        if (attachment.copiedFrom) {
          resource = attachment.copiedFrom.uri;
          range = attachment.copiedFrom.range;
          const filename = $rc(resource.path);
          label3.setLabel(filename, void 0, { extraClasses: classNames });
        } else {
          label3.setLabel(attachment.fileName, void 0, { extraClasses: classNames });
        }
        widget.appendChild($("span.attachment-additional-info", {}, `Pasted ${attachment.pastedLines}`));
        widget.style.position = "relative";
        const hoverContent = {
          markdown: {
            value: `**${attachment.copiedFrom ? this.w.getUriLabel(attachment.copiedFrom.uri, { relative: true }) : attachment.fileName}**

---

\`\`\`${attachment.language}
${attachment.code}
\`\`\``
          },
          markdownNotSupportedFallback: attachment.code
        };
        if (!this.a.isDisposed) {
          this.a.add(this.r.setupManagedHover(hoverDelegate, widget, hoverContent, { trapFocus: true }));
          const resource2 = attachment.copiedFrom?.uri;
          if (resource2) {
            this.a.add(this.m.invokeFunction((accessor) => $NDb(accessor, widget, resource2)));
          }
        }
      } else {
        const attachmentLabel = attachment.fullName ?? attachment.name;
        const withIcon = attachment.icon?.id ? `$(${attachment.icon.id}) ${attachmentLabel}` : attachmentLabel;
        label3.setLabel(withIcon, correspondingContentReference?.options?.status?.description);
        ariaLabel = localize(4793, null, attachment.name);
      }
      if (attachment.kind === "symbol") {
        const scopedContextKeyService = this.a.add(this.j.createScoped(widget));
        this.a.add(this.m.invokeFunction((accessor) => $ODb(accessor, widget, scopedContextKeyService, { ...attachment, kind: attachment.symbolKind }, $bJ.ChatInputSymbolAttachmentContext)));
      }
      if (isAttachmentPartialOrOmitted) {
        widget.classList.add("warning");
      }
      const description = correspondingContentReference?.options?.status?.description;
      if (isAttachmentPartialOrOmitted) {
        ariaLabel = `${ariaLabel}${description ? ` ${description}` : ""}`;
        for (const selector of [".monaco-icon-suffix-container", ".monaco-icon-name-container"]) {
          const element = label3.element.querySelector(selector);
          if (element) {
            element.classList.add("warning");
          }
        }
      }
      if (resource) {
        widget.style.cursor = "pointer";
        if (!this.a.isDisposed) {
          this.a.add($_i(widget, $7j.CLICK, async (e) => {
            $9j.stop(e, true);
            if (attachment.isDirectory) {
              this.z(resource, true);
            } else {
              this.z(resource, false, range);
            }
          }));
        }
      }
      widget.ariaLabel = ariaLabel;
      widget.tabIndex = 0;
    });
  }
  z(resource, isDirectory, range) {
    if (isDirectory) {
      this.t.executeCommand($gzb.id, resource);
      return;
    }
    const openTextEditorOptions = range ? { selection: range } : void 0;
    const options3 = {
      fromUserGesture: true,
      editorOptions: openTextEditorOptions
    };
    this.n.open(resource, options3);
  }
  // Helper function to create and replace image
  async C(buffer, widget, hoverElement) {
    const blob = new Blob([buffer], { type: "image/png" });
    const url = URL.createObjectURL(blob);
    const img = $("img.chat-attached-context-image", { src: url, alt: "" });
    const pillImg = $("img.chat-attached-context-pill-image", { src: url, alt: "" });
    const pill = $("div.chat-attached-context-pill", {}, pillImg);
    const existingPill = widget.querySelector(".chat-attached-context-pill");
    if (existingPill) {
      existingPill.replaceWith(pill);
    }
    hoverElement.appendChild(img);
  }
};
$MDb = __decorate([
  __param(4, $on),
  __param(5, $Pk),
  __param(6, $O4),
  __param(7, $5$),
  __param(8, $km),
  __param(9, $sn),
  __param(10, $gs),
  __param(11, $ZI)
], $MDb);
function $NDb(accessor, widget, resource) {
  const contextKeyService = accessor.get($on);
  const instantiationService = accessor.get($Pk);
  const store = new $2c();
  const scopedContextKeyService = store.add(contextKeyService.createScoped(widget));
  store.add(setResourceContext(accessor, scopedContextKeyService, resource));
  widget.draggable = true;
  store.add($_i(widget, "dragstart", (e) => {
    instantiationService.invokeFunction((accessor2) => $Eob(accessor2, [resource], e));
    e.dataTransfer?.setDragImage(widget, 0, 0);
  }));
  store.add(addBasicContextMenu(accessor, widget, scopedContextKeyService, $bJ.ChatInputResourceAttachmentContext, resource));
  return store;
}
function $ODb(accessor, widget, scopedContextKeyService, attachment, contextMenuId) {
  const instantiationService = accessor.get($Pk);
  const languageFeaturesService = accessor.get($mP);
  const textModelService = accessor.get($oG);
  const store = new $2c();
  store.add(setResourceContext(accessor, scopedContextKeyService, attachment.value.uri));
  const chatResourceContext = $LDb.bindTo(scopedContextKeyService);
  chatResourceContext.set(attachment.value.uri.toString());
  widget.draggable = true;
  store.add($_i(widget, "dragstart", (e) => {
    instantiationService.invokeFunction((accessor2) => $Eob(accessor2, [{ resource: attachment.value.uri, selection: attachment.value.range }], e));
    $D_([{
      fsPath: attachment.value.uri.fsPath,
      range: attachment.value.range,
      name: attachment.name,
      kind: attachment.kind
    }], e);
    e.dataTransfer?.setDragImage(widget, 0, 0);
  }));
  const providerContexts = [
    [EditorContextKeys.hasDefinitionProvider.bindTo(scopedContextKeyService), languageFeaturesService.definitionProvider],
    [EditorContextKeys.hasReferenceProvider.bindTo(scopedContextKeyService), languageFeaturesService.referenceProvider],
    [EditorContextKeys.hasImplementationProvider.bindTo(scopedContextKeyService), languageFeaturesService.implementationProvider],
    [EditorContextKeys.hasTypeDefinitionProvider.bindTo(scopedContextKeyService), languageFeaturesService.typeDefinitionProvider]
  ];
  const updateContextKeys = async () => {
    const modelRef = await textModelService.createModelReference(attachment.value.uri);
    try {
      const model = modelRef.object.textEditorModel;
      for (const [contextKey, registry4] of providerContexts) {
        contextKey.set(registry4.has(model));
      }
    } finally {
      modelRef.dispose();
    }
  };
  store.add(addBasicContextMenu(accessor, widget, scopedContextKeyService, contextMenuId, attachment.value, updateContextKeys));
  return store;
}
function setResourceContext(accessor, scopedContextKeyService, resource) {
  const fileService = accessor.get($km);
  const languageService = accessor.get($1E);
  const modelService = accessor.get($sG);
  const resourceContextKey = new $lqb(scopedContextKeyService, fileService, languageService, modelService);
  resourceContextKey.set(resource);
  return resourceContextKey;
}
function addBasicContextMenu(accessor, widget, scopedContextKeyService, menuId, arg, updateContextKeys) {
  const contextMenuService = accessor.get($50);
  const menuService = accessor.get($cJ);
  return $_i(widget, $7j.CONTEXT_MENU, async (domEvent) => {
    const event = new $lf(getWindow(domEvent), domEvent);
    $9j.stop(domEvent, true);
    try {
      await updateContextKeys?.();
    } catch (e) {
      console.error(e);
    }
    contextMenuService.showContextMenu({
      contextKeyService: scopedContextKeyService,
      getAnchor: () => event,
      getActions: () => {
        const menu = menuService.getMenuActions(menuId, scopedContextKeyService, { arg });
        return $P$(menu);
      }
    });
  });
}

// out-build/vs/workbench/browser/web.api.js
var Menu;
(function(Menu2) {
  Menu2[Menu2["CommandPalette"] = 0] = "CommandPalette";
  Menu2[Menu2["StatusBarWindowIndicatorMenu"] = 1] = "StatusBarWindowIndicatorMenu";
})(Menu || (Menu = {}));
var ColorScheme2;
(function(ColorScheme3) {
  ColorScheme3["DARK"] = "dark";
  ColorScheme3["LIGHT"] = "light";
  ColorScheme3["HIGH_CONTRAST_LIGHT"] = "hcLight";
  ColorScheme3["HIGH_CONTRAST_DARK"] = "hcDark";
})(ColorScheme2 || (ColorScheme2 = {}));

// out-build/vs/workbench/services/search/common/ignoreFile.js
var $bwb = class {
  constructor(contents, b, c) {
    this.b = b;
    this.c = c;
    if (b[b.length - 1] === "\\") {
      throw Error("Unexpected path format, do not use trailing backslashes");
    }
    if (b[b.length - 1] !== "/") {
      b += "/";
    }
    this.a = this.e(contents, this.b, this.c);
  }
  /**
   * Updates the contents of the ignorefile. Preservering the location and parent
   * @param contents The new contents of the gitignore file
   */
  updateContents(contents) {
    this.a = this.e(contents, this.b, this.c);
  }
  /**
   * Returns true if a path in a traversable directory has not been ignored.
   *
   * Note: For performance reasons this does not check if the parent directories have been ignored,
   * so it should always be used in tandem with `shouldTraverseDir` when walking a directory.
   *
   * In cases where a path must be tested in isolation, `isArbitraryPathIncluded` should be used.
   */
  isPathIncludedInTraversal(path, isDir) {
    if (path[0] !== "/" || path[path.length - 1] === "/") {
      throw Error("Unexpected path format, expectred to begin with slash and end without. got:" + path);
    }
    const ignored = this.a(path, isDir);
    return !ignored;
  }
  /**
   * Returns true if an arbitrary path has not been ignored.
   * This is an expensive operation and should only be used ouside of traversals.
   */
  isArbitraryPathIgnored(path, isDir) {
    if (path[0] !== "/" || path[path.length - 1] === "/") {
      throw Error("Unexpected path format, expectred to begin with slash and end without. got:" + path);
    }
    const segments = path.split("/").filter((x) => x);
    let ignored = false;
    let walkingPath = "";
    for (let i2 = 0; i2 < segments.length; i2++) {
      const isLast = i2 === segments.length - 1;
      const segment = segments[i2];
      walkingPath = walkingPath + "/" + segment;
      if (!this.isPathIncludedInTraversal(walkingPath, isLast ? isDir : true)) {
        ignored = true;
        break;
      }
    }
    return ignored;
  }
  d(lines, dirPath, trimForExclusions2) {
    const includeLines = lines.map((line) => this.f(line, dirPath));
    const includeExpression = /* @__PURE__ */ Object.create(null);
    for (const line of includeLines) {
      includeExpression[line] = true;
    }
    return $Dl(includeExpression, { trimForExclusions: trimForExclusions2 });
  }
  e(ignoreContents, dirPath, parent) {
    const contentLines = ignoreContents.split("\n").map((line) => line.trim()).filter((line) => line && line[0] !== "#");
    const fileLines = contentLines.filter((line) => !line.endsWith("/"));
    const fileIgnoreLines = fileLines.filter((line) => !line.includes("!"));
    const isFileIgnored = this.d(fileIgnoreLines, dirPath, true);
    const fileIncludeLines = fileLines.filter((line) => line.includes("!")).map((line) => line.replace(/!/g, ""));
    const isFileIncluded = this.d(fileIncludeLines, dirPath, false);
    const dirIgnoreLines = contentLines.filter((line) => !line.includes("!"));
    const isDirIgnored = this.d(dirIgnoreLines, dirPath, true);
    const dirIncludeLines = contentLines.filter((line) => line.includes("!")).map((line) => line.replace(/!/g, ""));
    const isDirIncluded = this.d(dirIncludeLines, dirPath, false);
    const isPathIgnored = (path, isDir) => {
      if (!path.startsWith(dirPath)) {
        return false;
      }
      if (isDir && isDirIgnored(path) && !isDirIncluded(path)) {
        return true;
      }
      if (isFileIgnored(path) && !isFileIncluded(path)) {
        return true;
      }
      if (parent) {
        return parent.a(path, isDir);
      }
      return false;
    };
    return isPathIgnored;
  }
  f(line, dirPath) {
    const firstSep = line.indexOf("/");
    if (firstSep === -1 || firstSep === line.length - 1) {
      line = "**/" + line;
    } else {
      if (firstSep === 0) {
        if (dirPath.slice(-1) === "/") {
          line = line.slice(1);
        }
      } else {
        if (dirPath.slice(-1) !== "/") {
          line = "/" + line;
        }
      }
      line = dirPath + line;
    }
    return line;
  }
};

// out-build/vs/workbench/contrib/files/browser/explorerFileContrib.js
var ExplorerExtensions;
(function(ExplorerExtensions2) {
  ExplorerExtensions2["FileContributionRegistry"] = "workbench.registry.explorer.fileContributions";
})(ExplorerExtensions || (ExplorerExtensions = {}));
var ExplorerFileContributionRegistry = class {
  constructor() {
    this.a = new $ze();
    this.onDidRegisterDescriptor = this.a.event;
    this.b = [];
  }
  /** @inheritdoc */
  register(descriptor) {
    this.b.push(descriptor);
    this.a.fire(descriptor);
  }
  /**
   * Creates a new instance of all registered contributions.
   */
  create(insta, container2, store) {
    return this.b.map((d) => {
      const i2 = d.create(insta, container2);
      store.add(i2);
      return i2;
    });
  }
};
var $cwb = new ExplorerFileContributionRegistry();
$Wn.add("workbench.registry.explorer.fileContributions", $cwb);

// out-build/vs/workbench/services/search/common/searchExtTypes.js
var ExcludeSettingOptions;
(function(ExcludeSettingOptions2) {
  ExcludeSettingOptions2[ExcludeSettingOptions2["None"] = 1] = "None";
  ExcludeSettingOptions2[ExcludeSettingOptions2["FilesExclude"] = 2] = "FilesExclude";
  ExcludeSettingOptions2[ExcludeSettingOptions2["SearchAndFilesExclude"] = 3] = "SearchAndFilesExclude";
})(ExcludeSettingOptions || (ExcludeSettingOptions = {}));
var TextSearchCompleteMessageType;
(function(TextSearchCompleteMessageType2) {
  TextSearchCompleteMessageType2[TextSearchCompleteMessageType2["Information"] = 1] = "Information";
  TextSearchCompleteMessageType2[TextSearchCompleteMessageType2["Warning"] = 2] = "Warning";
})(TextSearchCompleteMessageType || (TextSearchCompleteMessageType = {}));

// out-build/vs/workbench/services/search/common/search.js
var $NN = "workbench.view.search";
var $PN = "workbench.view.search";
var $QN = "search-result";
var $RN = "search.exclude";
var $SN = 2e4;
var SEARCH_ELIDED_PREFIX = "\u27EA ";
var SEARCH_ELIDED_SUFFIX = " characters skipped \u27EB";
var SEARCH_ELIDED_MIN_LEN = (SEARCH_ELIDED_PREFIX.length + SEARCH_ELIDED_SUFFIX.length + 5) * 2;
var $TN = $Qk("searchService");
var SearchProviderType;
(function(SearchProviderType2) {
  SearchProviderType2[SearchProviderType2["file"] = 0] = "file";
  SearchProviderType2[SearchProviderType2["text"] = 1] = "text";
  SearchProviderType2[SearchProviderType2["aiText"] = 2] = "aiText";
})(SearchProviderType || (SearchProviderType = {}));
var QueryType;
(function(QueryType2) {
  QueryType2[QueryType2["File"] = 1] = "File";
  QueryType2[QueryType2["Text"] = 2] = "Text";
  QueryType2[QueryType2["aiText"] = 3] = "aiText";
})(QueryType || (QueryType = {}));
function $UN(result) {
  return !!result.rangeLocations && !!result.previewText;
}
function $VN(p) {
  return !!p.resource;
}
function $WN(p) {
  return !!p.message;
}
var SearchCompletionExitCode;
(function(SearchCompletionExitCode2) {
  SearchCompletionExitCode2[SearchCompletionExitCode2["Normal"] = 0] = "Normal";
  SearchCompletionExitCode2[SearchCompletionExitCode2["NewSearchStarted"] = 1] = "NewSearchStarted";
})(SearchCompletionExitCode || (SearchCompletionExitCode = {}));
var $XN = class {
  constructor(resource) {
    this.resource = resource;
    this.results = [];
  }
};
var $YN = class {
  constructor(text2, ranges, previewOptions, webviewIndex) {
    this.rangeLocations = [];
    this.webviewIndex = webviewIndex;
    const rangesArr = Array.isArray(ranges) ? ranges : [ranges];
    if (previewOptions && previewOptions.matchLines === 1 && isSingleLineRangeList(rangesArr)) {
      text2 = $sg(text2, previewOptions.matchLines);
      let result = "";
      let shift = 0;
      let lastEnd = 0;
      const leadingChars = Math.floor(previewOptions.charsPerLine / 5);
      for (const range of rangesArr) {
        const previewStart = Math.max(range.startColumn - leadingChars, 0);
        const previewEnd = range.startColumn + previewOptions.charsPerLine;
        if (previewStart > lastEnd + leadingChars + SEARCH_ELIDED_MIN_LEN) {
          const elision = SEARCH_ELIDED_PREFIX + (previewStart - lastEnd) + SEARCH_ELIDED_SUFFIX;
          result += elision + text2.slice(previewStart, previewEnd);
          shift += previewStart - (lastEnd + elision.length);
        } else {
          result += text2.slice(lastEnd, previewEnd);
        }
        lastEnd = previewEnd;
        this.rangeLocations.push({
          source: range,
          preview: new $1N(0, range.startColumn - shift, range.endColumn - shift)
        });
      }
      this.previewText = result;
    } else {
      const firstMatchLine = Array.isArray(ranges) ? ranges[0].startLineNumber : ranges.startLineNumber;
      const rangeLocs = $4b(ranges, (r2) => ({
        preview: new $ZN(r2.startLineNumber - firstMatchLine, r2.startColumn, r2.endLineNumber - firstMatchLine, r2.endColumn),
        source: r2
      }));
      this.rangeLocations = Array.isArray(rangeLocs) ? rangeLocs : [rangeLocs];
      this.previewText = text2;
    }
  }
};
function isSingleLineRangeList(ranges) {
  const line = ranges[0].startLineNumber;
  for (const r2 of ranges) {
    if (r2.startLineNumber !== line || r2.endLineNumber !== line) {
      return false;
    }
  }
  return true;
}
var $ZN = class {
  constructor(startLineNumber, startColumn, endLineNumber, endColumn) {
    this.startLineNumber = startLineNumber;
    this.startColumn = startColumn;
    this.endLineNumber = endLineNumber;
    this.endColumn = endColumn;
  }
};
var $1N = class extends $ZN {
  constructor(lineNumber, startColumn, endColumn) {
    super(lineNumber, startColumn, lineNumber, endColumn);
  }
};
var ViewMode;
(function(ViewMode3) {
  ViewMode3["List"] = "list";
  ViewMode3["Tree"] = "tree";
})(ViewMode || (ViewMode = {}));
var SearchSortOrder;
(function(SearchSortOrder2) {
  SearchSortOrder2["Default"] = "default";
  SearchSortOrder2["FileNames"] = "fileNames";
  SearchSortOrder2["Type"] = "type";
  SearchSortOrder2["Modified"] = "modified";
  SearchSortOrder2["CountDescending"] = "countDescending";
  SearchSortOrder2["CountAscending"] = "countAscending";
})(SearchSortOrder || (SearchSortOrder = {}));
function $2N(configuration2, includeSearchExcludes = true) {
  const fileExcludes = configuration2 && configuration2.files && configuration2.files.exclude;
  const searchExcludes = includeSearchExcludes && configuration2 && configuration2.search && configuration2.search.exclude;
  if (!fileExcludes && !searchExcludes) {
    return void 0;
  }
  if (!fileExcludes || !searchExcludes) {
    return fileExcludes || searchExcludes || void 0;
  }
  let allExcludes = /* @__PURE__ */ Object.create(null);
  allExcludes = $Ov(allExcludes, $Lv(fileExcludes));
  allExcludes = $Ov(allExcludes, $Lv(searchExcludes), true);
  return allExcludes;
}
function $3N(queryProps, fsPath) {
  if (queryProps.excludePattern && $Cl(queryProps.excludePattern, fsPath)) {
    return false;
  }
  if (queryProps.includePattern || queryProps.usingSearchPaths) {
    if (queryProps.includePattern && $Cl(queryProps.includePattern, fsPath)) {
      return true;
    }
    if (queryProps.usingSearchPaths) {
      return !!queryProps.folderQueries && queryProps.folderQueries.some((fq) => {
        const searchPath = fq.folder.fsPath;
        if ($Zg(fsPath, searchPath)) {
          const relPath = $pc(searchPath, fsPath);
          return !fq.includePattern || !!$Cl(fq.includePattern, relPath);
        } else {
          return false;
        }
      });
    }
    return false;
  }
  return true;
}
var SearchErrorCode;
(function(SearchErrorCode2) {
  SearchErrorCode2[SearchErrorCode2["unknownEncoding"] = 1] = "unknownEncoding";
  SearchErrorCode2[SearchErrorCode2["regexParseError"] = 2] = "regexParseError";
  SearchErrorCode2[SearchErrorCode2["globParseError"] = 3] = "globParseError";
  SearchErrorCode2[SearchErrorCode2["invalidLiteral"] = 4] = "invalidLiteral";
  SearchErrorCode2[SearchErrorCode2["rgProcessError"] = 5] = "rgProcessError";
  SearchErrorCode2[SearchErrorCode2["other"] = 6] = "other";
  SearchErrorCode2[SearchErrorCode2["canceled"] = 7] = "canceled";
})(SearchErrorCode || (SearchErrorCode = {}));
var $4N = class extends Error {
  constructor(message, code) {
    super(message);
    this.code = code;
  }
};
function $5N(error) {
  const errorMsg = error.message;
  if ($kb(error)) {
    return new $4N(errorMsg, SearchErrorCode.canceled);
  }
  try {
    const details = JSON.parse(errorMsg);
    return new $4N(details.message, details.code);
  } catch (e) {
    return new $4N(errorMsg, SearchErrorCode.other);
  }
}

// out-build/vs/platform/environment/common/environmentService.js
var $Xu = /^([^.]+\..+)[:=](.+)$/;
var $Yu = class {
  get appRoot() {
    return $qc($ih.asFileUri("").fsPath);
  }
  get userHome() {
    return URI.file(this.b.homeDir);
  }
  get userDataPath() {
    return this.b.userDataDir;
  }
  get appSettingsHome() {
    return URI.file($nc(this.userDataPath, "User"));
  }
  get tmpDir() {
    return URI.file(this.b.tmpDir);
  }
  get cacheHome() {
    return URI.file(this.userDataPath);
  }
  get stateResource() {
    return $vh(this.appSettingsHome, "globalStorage", "storage.json");
  }
  get userRoamingDataHome() {
    return this.appSettingsHome.with({ scheme: Schemas.vscodeUserData });
  }
  get userDataSyncHome() {
    return $vh(this.appSettingsHome, "sync");
  }
  get logsHome() {
    if (!this.args.logsPath) {
      const key2 = $Tu(/* @__PURE__ */ new Date()).replace(/-|:|\.\d+Z$/g, "");
      this.args.logsPath = $nc(this.userDataPath, "logs", key2);
    }
    return URI.file(this.args.logsPath);
  }
  get sync() {
    return this.args.sync;
  }
  get machineSettingsResource() {
    return $vh(URI.file($nc(this.userDataPath, "Machine")), "settings.json");
  }
  get workspaceStorageHome() {
    return $vh(this.appSettingsHome, "workspaceStorage");
  }
  get localHistoryHome() {
    return $vh(this.appSettingsHome, "History");
  }
  get keyboardLayoutResource() {
    return $vh(this.userRoamingDataHome, "keyboardLayout.json");
  }
  get argvResource() {
    const vscodePortable = env["VSCODE_PORTABLE"];
    if (vscodePortable) {
      return URI.file($nc(vscodePortable, "argv.json"));
    }
    return $vh(this.userHome, this.c.dataFolderName, "argv.json");
  }
  get isExtensionDevelopment() {
    return !!this.args.extensionDevelopmentPath;
  }
  get untitledWorkspacesHome() {
    return URI.file($nc(this.userDataPath, "Workspaces"));
  }
  get builtinExtensionsPath() {
    const cliBuiltinExtensionsDir = this.args["builtin-extensions-dir"];
    if (cliBuiltinExtensionsDir) {
      return $oc(cliBuiltinExtensionsDir);
    }
    return $lc($nc($ih.asFileUri("").fsPath, "..", "extensions"));
  }
  get extensionsDownloadLocation() {
    const cliExtensionsDownloadDir = this.args["extensions-download-dir"];
    if (cliExtensionsDownloadDir) {
      return URI.file($oc(cliExtensionsDownloadDir));
    }
    return URI.file($nc(this.userDataPath, "CachedExtensionVSIXs"));
  }
  get extensionsPath() {
    const cliExtensionsDir = this.args["extensions-dir"];
    if (cliExtensionsDir) {
      return $oc(cliExtensionsDir);
    }
    const vscodeExtensions = env["VSCODE_EXTENSIONS"];
    if (vscodeExtensions) {
      return vscodeExtensions;
    }
    const vscodePortable = env["VSCODE_PORTABLE"];
    if (vscodePortable) {
      return $nc(vscodePortable, "extensions");
    }
    return $vh(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($lc(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($lc(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 $Zu(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) => !$Xu.test(entry));
  }
  get extensionLogLevel() {
    const result = [];
    for (const entry of this.args.log || []) {
      const matches = $Xu.exec(entry);
      if (matches && matches[1] && matches[2]) {
        result.push([matches[1], matches[2]]);
      }
    }
    return result.length ? result : void 0;
  }
  get serviceMachineIdResource() {
    return $vh(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($nc(vscodePortable, "policy.json"));
      }
      return $vh(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([
  $0t
], $Yu.prototype, "appRoot", null);
__decorate([
  $0t
], $Yu.prototype, "userHome", null);
__decorate([
  $0t
], $Yu.prototype, "userDataPath", null);
__decorate([
  $0t
], $Yu.prototype, "appSettingsHome", null);
__decorate([
  $0t
], $Yu.prototype, "tmpDir", null);
__decorate([
  $0t
], $Yu.prototype, "cacheHome", null);
__decorate([
  $0t
], $Yu.prototype, "stateResource", null);
__decorate([
  $0t
], $Yu.prototype, "userRoamingDataHome", null);
__decorate([
  $0t
], $Yu.prototype, "userDataSyncHome", null);
__decorate([
  $0t
], $Yu.prototype, "sync", null);
__decorate([
  $0t
], $Yu.prototype, "machineSettingsResource", null);
__decorate([
  $0t
], $Yu.prototype, "workspaceStorageHome", null);
__decorate([
  $0t
], $Yu.prototype, "localHistoryHome", null);
__decorate([
  $0t
], $Yu.prototype, "keyboardLayoutResource", null);
__decorate([
  $0t
], $Yu.prototype, "argvResource", null);
__decorate([
  $0t
], $Yu.prototype, "isExtensionDevelopment", null);
__decorate([
  $0t
], $Yu.prototype, "untitledWorkspacesHome", null);
__decorate([
  $0t
], $Yu.prototype, "builtinExtensionsPath", null);
__decorate([
  $0t
], $Yu.prototype, "extensionsPath", null);
__decorate([
  $0t
], $Yu.prototype, "extensionDevelopmentLocationURI", null);
__decorate([
  $0t
], $Yu.prototype, "extensionDevelopmentKind", null);
__decorate([
  $0t
], $Yu.prototype, "extensionTestsLocationURI", null);
__decorate([
  $0t
], $Yu.prototype, "debugExtensionHost", null);
__decorate([
  $0t
], $Yu.prototype, "logLevel", null);
__decorate([
  $0t
], $Yu.prototype, "extensionLogLevel", null);
__decorate([
  $0t
], $Yu.prototype, "serviceMachineIdResource", null);
__decorate([
  $0t
], $Yu.prototype, "disableTelemetry", null);
__decorate([
  $0t
], $Yu.prototype, "disableWorkspaceTrust", null);
__decorate([
  $0t
], $Yu.prototype, "useInMemorySecretStorage", null);
__decorate([
  $0t
], $Yu.prototype, "policyFile", null);
function $Zu(args2, isBuilt) {
  return $1u(args2["inspect-extensions"], args2["inspect-brk-extensions"], 5870, isBuilt, args2.debugId, args2.extensionEnvironment);
}
function $1u(debugArg, debugBrkArg, defaultBuildPort, isBuilt, debugId, environmentString) {
  const portStr = debugBrkArg || debugArg;
  const port = Number(portStr) || (!isBuilt ? defaultBuildPort : null);
  const brk = port ? Boolean(!!debugBrkArg) : false;
  let env3;
  if (environmentString) {
    try {
      env3 = JSON.parse(environmentString);
    } catch {
    }
  }
  return { port, break: brk, debugId, env: env3 };
}

// out-build/vs/workbench/services/environment/browser/environmentService.js
var $M4 = $Rk($Xk);
var $N4 = class {
  get remoteAuthority() {
    return this.options.remoteAuthority;
  }
  get expectsResolverExtension() {
    return !!this.options.remoteAuthority?.includes("+") && !this.options.webSocketFactory;
  }
  get isBuilt() {
    return !!this.f.commit;
  }
  get logLevel() {
    const logLevelFromPayload = this.b?.get("logLevel");
    if (logLevelFromPayload) {
      return logLevelFromPayload.split(",").find((entry) => !$Xu.test(entry));
    }
    return this.options.developmentOptions?.logLevel !== void 0 ? $Ln(this.options.developmentOptions?.logLevel) : void 0;
  }
  get extensionLogLevel() {
    const logLevelFromPayload = this.b?.get("logLevel");
    if (logLevelFromPayload) {
      const result = [];
      for (const entry of logLevelFromPayload.split(",")) {
        const matches = $Xu.exec(entry);
        if (matches && matches[1] && matches[2]) {
          result.push([matches[1], matches[2]]);
        }
      }
      return result.length ? result : void 0;
    }
    return this.options.developmentOptions?.extensionLogLevel !== void 0 ? this.options.developmentOptions?.extensionLogLevel.map(([extension, logLevel]) => [extension, $Ln(logLevel)]) : void 0;
  }
  get profDurationMarkers() {
    const profDurationMarkersFromPayload = this.b?.get("profDurationMarkers");
    if (profDurationMarkersFromPayload) {
      const result = [];
      for (const entry of profDurationMarkersFromPayload.split(",")) {
        result.push(entry);
      }
      return result.length === 2 ? result : void 0;
    }
    return void 0;
  }
  get windowLogsPath() {
    return this.logsHome;
  }
  get logFile() {
    return $vh(this.windowLogsPath, "window.log");
  }
  get userRoamingDataHome() {
    return $vh(URI.file(this.userDataPath).with({ scheme: Schemas.vscodeRemote }), "User");
  }
  get userDataPath() {
    if (!this.options.userDataPath) {
      throw new Error("userDataPath was not provided to the browser");
    }
    return this.options.userDataPath;
  }
  // --- End PWB ---
  // --- Start PWB: disable file downloads ---
  get isEnabledFileDownloads() {
    if (typeof this.options.isEnabledFileDownloads === "undefined") {
      throw new Error("isEnabledFileDownloads was not provided to the browser");
    }
    return this.options.isEnabledFileDownloads;
  }
  get isEnabledFileUploads() {
    if (typeof this.options.isEnabledFileUploads === "undefined") {
      throw new Error("isEnabledFileUploads was not provided to the browser");
    }
    return this.options.isEnabledFileUploads;
  }
  // --- End PWB ---
  get argvResource() {
    return $vh(this.userRoamingDataHome, "argv.json");
  }
  get cacheHome() {
    return $vh(this.userRoamingDataHome, "caches");
  }
  get workspaceStorageHome() {
    return $vh(this.userRoamingDataHome, "workspaceStorage");
  }
  get localHistoryHome() {
    return $vh(this.userRoamingDataHome, "History");
  }
  get stateResource() {
    return $vh(this.userRoamingDataHome, "State", "storage.json");
  }
  /**
   * In Web every workspace can potentially have scoped user-data
   * and/or extensions and if Sync state is shared then it can make
   * Sync error prone - say removing extensions from another workspace.
   * Hence scope Sync state per workspace. Sync scoped to a workspace
   * is capable of handling opening same workspace in multiple windows.
   */
  get userDataSyncHome() {
    return $vh(this.userRoamingDataHome, "sync", this.d);
  }
  get sync() {
    return void 0;
  }
  get keyboardLayoutResource() {
    return $vh(this.userRoamingDataHome, "keyboardLayout.json");
  }
  get untitledWorkspacesHome() {
    return $vh(this.userRoamingDataHome, "Workspaces");
  }
  get serviceMachineIdResource() {
    return $vh(this.userRoamingDataHome, "machineid");
  }
  get extHostLogsPath() {
    return $vh(this.logsHome, "exthost");
  }
  get extHostTelemetryLogFile() {
    return $vh(this.extHostLogsPath, "extensionTelemetry.log");
  }
  get debugExtensionHost() {
    if (!this.a) {
      this.a = this.g();
    }
    return this.a.params;
  }
  get isExtensionDevelopment() {
    if (!this.a) {
      this.a = this.g();
    }
    return this.a.isExtensionDevelopment;
  }
  get extensionDevelopmentLocationURI() {
    if (!this.a) {
      this.a = this.g();
    }
    return this.a.extensionDevelopmentLocationURI;
  }
  get extensionDevelopmentLocationKind() {
    if (!this.a) {
      this.a = this.g();
    }
    return this.a.extensionDevelopmentKind;
  }
  get extensionTestsLocationURI() {
    if (!this.a) {
      this.a = this.g();
    }
    return this.a.extensionTestsLocationURI;
  }
  get extensionEnabledProposedApi() {
    if (!this.a) {
      this.a = this.g();
    }
    return this.a.extensionEnabledProposedApi;
  }
  get debugRenderer() {
    if (!this.a) {
      this.a = this.g();
    }
    return this.a.debugRenderer;
  }
  get enableSmokeTestDriver() {
    return this.options.developmentOptions?.enableSmokeTestDriver;
  }
  get disableExtensions() {
    return this.b?.get("disableExtensions") === "true";
  }
  get enableExtensions() {
    return this.options.enabledExtensions;
  }
  get webviewExternalEndpoint() {
    const endpoint = this.options.webviewEndpoint && new URL(this.options.webviewEndpoint, window.location.toString()).toString() || this.f.webviewContentExternalBaseUrlTemplate || "https://{{uuid}}.vscode-cdn.net/{{quality}}/{{commit}}/out/vs/workbench/contrib/webview/browser/pre/";
    const webviewExternalEndpointCommit = this.b?.get("webviewExternalEndpointCommit");
    return endpoint.replace("{{commit}}", webviewExternalEndpointCommit ?? this.f.commit ?? "ef65ac1ba57f57f2a3961bfe94aa20481caca4c6").replace("{{quality}}", (webviewExternalEndpointCommit ? "insider" : this.f.quality) ?? "insider");
  }
  get extensionTelemetryLogResource() {
    return $vh(this.logsHome, "extensionTelemetry.log");
  }
  get disableTelemetry() {
    return false;
  }
  get verbose() {
    return this.b?.get("verbose") === "true";
  }
  get logExtensionHostCommunication() {
    return this.b?.get("logExtensionHostCommunication") === "true";
  }
  get skipReleaseNotes() {
    return this.b?.get("skipReleaseNotes") === "true";
  }
  get skipWelcome() {
    return this.b?.get("skipWelcome") === "true";
  }
  get disableWorkspaceTrust() {
    return !this.options.enableWorkspaceTrust;
  }
  get profile() {
    return this.b?.get("profile");
  }
  constructor(d, logsHome, options3, f) {
    this.d = d;
    this.logsHome = logsHome;
    this.options = options3;
    this.f = f;
    this.a = void 0;
    this.editSessionId = this.options.editSessionId;
    if (options3.workspaceProvider && Array.isArray(options3.workspaceProvider.payload)) {
      try {
        this.b = new Map(options3.workspaceProvider.payload);
      } catch (error) {
        $gb(error);
      }
    }
  }
  g() {
    const extensionHostDebugEnvironment = {
      params: {
        port: null,
        break: false
      },
      debugRenderer: false,
      isExtensionDevelopment: false,
      extensionDevelopmentLocationURI: void 0,
      extensionDevelopmentKind: void 0
    };
    if (this.b) {
      for (const [key2, value] of this.b) {
        switch (key2) {
          case "extensionDevelopmentPath":
            if (!extensionHostDebugEnvironment.extensionDevelopmentLocationURI) {
              extensionHostDebugEnvironment.extensionDevelopmentLocationURI = [];
            }
            extensionHostDebugEnvironment.extensionDevelopmentLocationURI.push(URI.parse(value));
            extensionHostDebugEnvironment.isExtensionDevelopment = true;
            break;
          case "extensionDevelopmentKind":
            extensionHostDebugEnvironment.extensionDevelopmentKind = [value];
            break;
          case "extensionTestsPath":
            extensionHostDebugEnvironment.extensionTestsLocationURI = URI.parse(value);
            break;
          case "debugRenderer":
            extensionHostDebugEnvironment.debugRenderer = value === "true";
            break;
          case "debugId":
            extensionHostDebugEnvironment.params.debugId = value;
            break;
          case "inspect-brk-extensions":
            extensionHostDebugEnvironment.params.port = parseInt(value);
            extensionHostDebugEnvironment.params.break = true;
            break;
          case "inspect-extensions":
            extensionHostDebugEnvironment.params.port = parseInt(value);
            break;
          case "enableProposedApi":
            extensionHostDebugEnvironment.extensionEnabledProposedApi = [];
            break;
        }
      }
    }
    const developmentOptions = this.options.developmentOptions;
    if (developmentOptions && !extensionHostDebugEnvironment.isExtensionDevelopment) {
      if (developmentOptions.extensions?.length) {
        extensionHostDebugEnvironment.extensionDevelopmentLocationURI = developmentOptions.extensions.map((e) => URI.revive(e));
        extensionHostDebugEnvironment.isExtensionDevelopment = true;
      }
      if (developmentOptions.extensionTestsPath) {
        extensionHostDebugEnvironment.extensionTestsLocationURI = URI.revive(developmentOptions.extensionTestsPath);
      }
    }
    return extensionHostDebugEnvironment;
  }
  get filesToOpenOrCreate() {
    if (this.b) {
      const fileToOpen = this.b.get("openFile");
      if (fileToOpen) {
        const fileUri = URI.parse(fileToOpen);
        if (this.b.has("gotoLineMode")) {
          const pathColumnAware = $8g(fileUri.path);
          return [{
            fileUri: fileUri.with({ path: pathColumnAware.path }),
            options: {
              selection: !$Gg(pathColumnAware.line) ? { startLineNumber: pathColumnAware.line, startColumn: pathColumnAware.column || 1 } : void 0
            }
          }];
        }
        return [{ fileUri }];
      }
    }
    return void 0;
  }
  get filesToDiff() {
    if (this.b) {
      const fileToDiffPrimary = this.b.get("diffFilePrimary");
      const fileToDiffSecondary = this.b.get("diffFileSecondary");
      if (fileToDiffPrimary && fileToDiffSecondary) {
        return [
          { fileUri: URI.parse(fileToDiffSecondary) },
          { fileUri: URI.parse(fileToDiffPrimary) }
        ];
      }
    }
    return void 0;
  }
  get filesToMerge() {
    if (this.b) {
      const fileToMerge1 = this.b.get("mergeFile1");
      const fileToMerge2 = this.b.get("mergeFile2");
      const fileToMergeBase = this.b.get("mergeFileBase");
      const fileToMergeResult = this.b.get("mergeFileResult");
      if (fileToMerge1 && fileToMerge2 && fileToMergeBase && fileToMergeResult) {
        return [
          { fileUri: URI.parse(fileToMerge1) },
          { fileUri: URI.parse(fileToMerge2) },
          { fileUri: URI.parse(fileToMergeBase) },
          { fileUri: URI.parse(fileToMergeResult) }
        ];
      }
    }
    return void 0;
  }
};
__decorate([
  $0t
], $N4.prototype, "remoteAuthority", null);
__decorate([
  $0t
], $N4.prototype, "expectsResolverExtension", null);
__decorate([
  $0t
], $N4.prototype, "isBuilt", null);
__decorate([
  $0t
], $N4.prototype, "logLevel", null);
__decorate([
  $0t
], $N4.prototype, "windowLogsPath", null);
__decorate([
  $0t
], $N4.prototype, "logFile", null);
__decorate([
  $0t
  // -- Start PWB: Local storage ---
], $N4.prototype, "userRoamingDataHome", null);
__decorate([
  $0t
], $N4.prototype, "argvResource", null);
__decorate([
  $0t
], $N4.prototype, "cacheHome", null);
__decorate([
  $0t
], $N4.prototype, "workspaceStorageHome", null);
__decorate([
  $0t
], $N4.prototype, "localHistoryHome", null);
__decorate([
  $0t
], $N4.prototype, "stateResource", null);
__decorate([
  $0t
], $N4.prototype, "userDataSyncHome", null);
__decorate([
  $0t
], $N4.prototype, "sync", null);
__decorate([
  $0t
], $N4.prototype, "keyboardLayoutResource", null);
__decorate([
  $0t
], $N4.prototype, "untitledWorkspacesHome", null);
__decorate([
  $0t
], $N4.prototype, "serviceMachineIdResource", null);
__decorate([
  $0t
], $N4.prototype, "extHostLogsPath", null);
__decorate([
  $0t
], $N4.prototype, "extHostTelemetryLogFile", null);
__decorate([
  $0t
], $N4.prototype, "debugExtensionHost", null);
__decorate([
  $0t
], $N4.prototype, "isExtensionDevelopment", null);
__decorate([
  $0t
], $N4.prototype, "extensionDevelopmentLocationURI", null);
__decorate([
  $0t
], $N4.prototype, "extensionDevelopmentLocationKind", null);
__decorate([
  $0t
], $N4.prototype, "extensionTestsLocationURI", null);
__decorate([
  $0t
], $N4.prototype, "extensionEnabledProposedApi", null);
__decorate([
  $0t
], $N4.prototype, "debugRenderer", null);
__decorate([
  $0t
], $N4.prototype, "enableSmokeTestDriver", null);
__decorate([
  $0t
], $N4.prototype, "disableExtensions", null);
__decorate([
  $0t
], $N4.prototype, "enableExtensions", null);
__decorate([
  $0t
], $N4.prototype, "webviewExternalEndpoint", null);
__decorate([
  $0t
], $N4.prototype, "extensionTelemetryLogResource", null);
__decorate([
  $0t
], $N4.prototype, "disableTelemetry", null);
__decorate([
  $0t
], $N4.prototype, "verbose", null);
__decorate([
  $0t
], $N4.prototype, "logExtensionHostCommunication", null);
__decorate([
  $0t
], $N4.prototype, "skipReleaseNotes", null);
__decorate([
  $0t
], $N4.prototype, "skipWelcome", null);
__decorate([
  $0t
], $N4.prototype, "disableWorkspaceTrust", null);
__decorate([
  $0t
], $N4.prototype, "profile", null);
__decorate([
  $0t
], $N4.prototype, "filesToOpenOrCreate", null);
__decorate([
  $0t
], $N4.prototype, "filesToDiff", null);
__decorate([
  $0t
], $N4.prototype, "filesToMerge", null);

// out-build/vs/workbench/contrib/files/browser/views/explorerViewer.js
var $jwb_1;
var $mwb_1;
var $dwb = class _$dwb {
  static {
    this.ITEM_HEIGHT = 22;
  }
  getHeight(element) {
    return _$dwb.ITEM_HEIGHT;
  }
  getTemplateId(element) {
    return $jwb.ID;
  }
};
var $ewb = new $ze();
var $fwb = class $fwb2 {
  constructor(a, b, f, g, h3, j, k, l, m, n) {
    this.a = a;
    this.b = b;
    this.f = f;
    this.g = g;
    this.h = h3;
    this.j = j;
    this.k = k;
    this.l = l;
    this.m = m;
    this.n = n;
  }
  getParent(element) {
    if (element.parent) {
      return element.parent;
    }
    throw new Error("getParent only supported for cached parents");
  }
  hasChildren(element) {
    return Array.isArray(element) || element.hasChildren((stat) => this.a.filter(
      stat,
      1
      /* TreeVisibility.Visible */
    ));
  }
  getChildren(element) {
    if (Array.isArray(element)) {
      return element;
    }
    if (this.b.isShowingFilterResults()) {
      return Array.from(element.children.values());
    }
    const hasError = element.error;
    const sortOrder = this.l.sortOrderConfiguration.sortOrder;
    const children = element.fetchChildren(sortOrder);
    if (Array.isArray(children)) {
      return children;
    }
    const promise = children.then((children2) => {
      if (element instanceof $ivb && element.isRoot && !element.error && hasError && this.m.getWorkbenchState() !== 2) {
        $ewb.fire(element.resource);
      }
      return children2;
    }, (e) => {
      if (element instanceof $ivb && element.isRoot) {
        if (this.m.getWorkbenchState() === 2) {
          const placeholder = new $ivb(element.resource, this.k, this.g, this.n, void 0, void 0, false);
          placeholder.error = e;
          return [placeholder];
        } else {
          $ewb.fire(element.resource);
        }
      } else {
        this.h.error(e);
      }
      return [];
    });
    this.f.withProgress({
      location: 1,
      delay: this.j.isRestored() ? 800 : 1500
      // reduce progress visibility when still restoring
    }, (_progress) => promise);
    return promise;
  }
};
$fwb = __decorate([
  __param(2, $TJ),
  __param(3, $kl),
  __param(4, $PJ),
  __param(5, $Vlb),
  __param(6, $km),
  __param(7, $kvb),
  __param(8, $Zk),
  __param(9, $4J)
], $fwb);
var $gwb = class extends $ivb {
  constructor(resource, fileService, configService, filesConfigService, _parent, _isDirectory) {
    super(resource, fileService, configService, filesConfigService, _parent, _isDirectory);
  }
};
var ExplorerFindHighlightTree = class {
  constructor() {
    this.a = /* @__PURE__ */ new Map();
    this.b = /* @__PURE__ */ new Map();
  }
  get highlightedItems() {
    return Array.from(this.b.values());
  }
  get(item) {
    const result = this.f(item);
    if (result === void 0) {
      return 0;
    }
    const { treeLayer, relPath } = result;
    this.b.set(relPath, item);
    return treeLayer.childMatches;
  }
  f(item) {
    const rootLayer = this.a.get(item.root.name);
    if (rootLayer === void 0) {
      return void 0;
    }
    const relPath = $xh(item.root.resource, item.resource);
    if (relPath === void 0 || relPath.startsWith("..")) {
      throw new Error("Resource is not a child of the root");
    }
    if (relPath === "") {
      return { treeLayer: rootLayer, relPath };
    }
    let treeLayer = rootLayer;
    for (const segment of relPath.split("/")) {
      if (!treeLayer.stats[segment]) {
        return void 0;
      }
      treeLayer = treeLayer.stats[segment];
    }
    return { treeLayer, relPath };
  }
  add(resource, root) {
    const relPath = $xh(root.resource, resource);
    if (relPath === void 0 || relPath.startsWith("..")) {
      throw new Error("Resource is not a child of the root");
    }
    let rootLayer = this.a.get(root.name);
    if (!rootLayer) {
      rootLayer = { childMatches: 0, stats: {}, isMatch: false };
      this.a.set(root.name, rootLayer);
    }
    rootLayer.childMatches++;
    let treeLayer = rootLayer;
    for (const stat of relPath.split("/")) {
      if (!treeLayer.stats[stat]) {
        treeLayer.stats[stat] = { childMatches: 0, stats: {}, isMatch: false };
      }
      treeLayer = treeLayer.stats[stat];
      treeLayer.childMatches++;
    }
    treeLayer.childMatches--;
    treeLayer.isMatch = true;
  }
  isMatch(item) {
    const result = this.f(item);
    if (result === void 0) {
      return false;
    }
    const { treeLayer } = result;
    return treeLayer.isMatch;
  }
  clear() {
    this.a.clear();
  }
};
var $hwb = class $hwb2 {
  get highlightTree() {
    return this.j;
  }
  constructor(k, l, m, n, o, p, q, t, contextKeyService) {
    this.k = k;
    this.l = l;
    this.m = m;
    this.n = n;
    this.o = o;
    this.p = p;
    this.q = q;
    this.t = t;
    this.a = 0;
    this.h = /* @__PURE__ */ new Set();
    this.j = new ExplorerFindHighlightTree();
    this.g = $ftb.bindTo(contextKeyService);
  }
  isShowingFilterResults() {
    return !!this.b;
  }
  isVisible(element) {
    if (!this.b) {
      return true;
    }
    if (this.t.isEditable(element)) {
      return true;
    }
    return this.b.rootsWithProviders.has(element.root) ? element.isMarkedAsFiltered() : true;
  }
  startSession() {
    this.a++;
  }
  async endSession() {
    if (this.b) {
      await this.endFilterSession();
    }
    if (this.f) {
      this.A();
    }
  }
  async find(pattern, toggles, token) {
    const promise = this.doFind(pattern, toggles, token);
    return await this.q.withProgress({
      location: 1,
      delay: 750
    }, (_progress) => promise);
  }
  async doFind(pattern, toggles, token) {
    if (toggles.findMode === TreeFindMode.Highlight) {
      if (this.b) {
        await this.endFilterSession();
      }
      if (!this.f) {
        this.y();
      }
      return await this.doHighlightFind(pattern, toggles.matchType, token);
    }
    if (this.f) {
      this.A();
    }
    if (!this.b) {
      this.u();
    }
    return await this.doFilterFind(pattern, toggles.matchType, token);
  }
  // Filter
  u() {
    const tree = this.l();
    const input = tree.getInput();
    if (!input) {
      return;
    }
    const roots = this.t.roots.filter((root) => this.C(root.resource.scheme));
    this.b = { viewState: tree.getViewState(), input, rootsWithProviders: new Set(roots) };
    this.g.set(true);
  }
  async doFilterFind(pattern, matchType, token) {
    if (!this.b) {
      throw new Error("ExplorerFindProvider: no session state");
    }
    const roots = Array.from(this.b.rootsWithProviders);
    const searchResults = await this.D(pattern, roots, matchType, token);
    if (token.isCancellationRequested) {
      return void 0;
    }
    this.x();
    for (const { explorerRoot, files, directories } of searchResults) {
      this.v(explorerRoot, files, directories);
    }
    const tree = this.l();
    await tree.setInput(this.b.input);
    const hitMaxResults = searchResults.some(({ hitMaxResults: hitMaxResults2 }) => hitMaxResults2);
    return {
      isMatch: (item) => item.isMarkedAsFiltered(),
      matchCount: searchResults.reduce((acc, { files, directories }) => acc + files.length + directories.length, 0),
      warningMessage: hitMaxResults ? localize(7381, null) : void 0
    };
  }
  v(root, files, directories) {
    const results = [
      ...files.map((file) => ({ resource: file, isDirectory: false })),
      ...directories.map((directory) => ({ resource: directory, isDirectory: true }))
    ];
    for (const { resource, isDirectory } of results) {
      const element = root.find(resource);
      if (element && element.root === root) {
        element.markItemAndParentsAsFiltered();
        continue;
      }
      const phantomElements = this.w(resource, root, isDirectory);
      if (phantomElements.length === 0) {
        throw new Error("Phantom item was not created even though it is not in the model");
      }
      const firstPhantomParent = phantomElements[0].parent;
      if (!(firstPhantomParent instanceof $gwb)) {
        this.h.add(firstPhantomParent);
      }
      const phantomFileElement = phantomElements[phantomElements.length - 1];
      phantomFileElement.markItemAndParentsAsFiltered();
    }
  }
  w(resource, root, resourceIsDirectory) {
    const relativePathToRoot = $xh(root.resource, resource);
    if (!relativePathToRoot) {
      throw new Error("Resource is not a child of the root");
    }
    const phantomElements = [];
    let currentItem = root;
    let currentResource = root.resource;
    const pathSegments = relativePathToRoot.split("/");
    for (const stat of pathSegments) {
      currentResource = currentResource.with({ path: `${currentResource.path}/${stat}` });
      let child = currentItem.getChild(stat);
      if (!child) {
        const isDirectory = pathSegments[pathSegments.length - 1] === stat ? resourceIsDirectory : true;
        child = new $gwb(currentResource, this.n, this.o, this.p, currentItem, isDirectory);
        currentItem.addChild(child);
        phantomElements.push(child);
      }
      currentItem = child;
    }
    return phantomElements;
  }
  async endFilterSession() {
    this.x();
    this.g.set(false);
    if (!this.b) {
      throw new Error("ExplorerFindProvider: no session state to restore");
    }
    const tree = this.l();
    await tree.setInput(this.b.input, this.b.viewState);
    this.b = void 0;
    this.t.refresh();
  }
  x() {
    for (const phantomParent of this.h) {
      phantomParent.forgetChildren();
    }
    this.h.clear();
    this.t.roots.forEach((root) => root.unmarkItemAndChildren());
  }
  // Highlight
  y() {
    const roots = this.t.roots.filter((root) => this.C(root.resource.scheme));
    this.f = { rootsWithProviders: new Set(roots) };
  }
  async doHighlightFind(pattern, matchType, token) {
    if (!this.f) {
      throw new Error("ExplorerFindProvider: no highlight session state");
    }
    const roots = Array.from(this.f.rootsWithProviders);
    const searchResults = await this.D(pattern, roots, matchType, token);
    if (token.isCancellationRequested) {
      return void 0;
    }
    this.B();
    for (const { explorerRoot, files, directories } of searchResults) {
      this.z(explorerRoot, files.concat(directories));
    }
    const hitMaxResults = searchResults.some(({ hitMaxResults: hitMaxResults2 }) => hitMaxResults2);
    return {
      isMatch: (item) => this.j.isMatch(item) || this.j.get(item) > 0 && this.l().isCollapsed(item),
      matchCount: searchResults.reduce((acc, { files, directories }) => acc + files.length + directories.length, 0),
      warningMessage: hitMaxResults ? localize(7382, null) : void 0
    };
  }
  z(root, resources) {
    const highlightedDirectories = /* @__PURE__ */ new Set();
    const storeDirectories = (item) => {
      while (item) {
        highlightedDirectories.add(item);
        item = item.parent;
      }
    };
    for (const resource of resources) {
      const element = root.find(resource);
      if (element && element.root === root) {
        this.j.add(resource, root);
        storeDirectories(element.parent);
        continue;
      }
      const firstParent = findFirstParent(resource, root);
      if (firstParent) {
        this.j.add(resource, root);
        storeDirectories(firstParent.parent);
      }
    }
    const tree = this.l();
    for (const directory of highlightedDirectories) {
      if (tree.hasNode(directory)) {
        tree.rerender(directory);
      }
    }
  }
  A() {
    this.f = void 0;
    this.B();
  }
  B() {
    const tree = this.l();
    for (const item of this.j.highlightedItems) {
      if (tree.hasNode(item)) {
        tree.rerender(item);
      }
    }
    this.j.clear();
  }
  // Search
  C(scheme) {
    if (scheme !== Schemas.file && scheme !== Schemas.vscodeRemote) {
      return false;
    }
    return this.m.schemeHasFileSearchProvider(scheme);
  }
  async D(pattern, roots, matchType, token) {
    const patternLowercase = pattern.toLowerCase();
    const isFuzzyMatch = matchType === TreeFindMatchType.Fuzzy;
    return await Promise.all(roots.map((root, index) => this.E(patternLowercase, root, index, isFuzzyMatch, token)));
  }
  async E(patternLowercase, root, rootIndex, isFuzzyMatch, token) {
    const segmentMatchPattern = caseInsensitiveGlobPattern(isFuzzyMatch ? fuzzyMatchingGlobPattern(patternLowercase) : continousMatchingGlobPattern(patternLowercase));
    const searchExcludePattern = $2N(this.o.getValue({ resource: root.resource })) || {};
    const searchOptions = {
      folderQueries: [{
        folder: root.resource,
        disregardIgnoreFiles: !this.o.getValue("explorer.excludeGitIgnore")
      }],
      type: 1,
      shouldGlobMatchFilePattern: true,
      cacheKey: `explorerfindprovider:${root.name}:${rootIndex}:${this.a}`,
      excludePattern: searchExcludePattern
    };
    let fileResults;
    let folderResults;
    try {
      [fileResults, folderResults] = await Promise.all([
        this.m.fileSearch({ ...searchOptions, filePattern: `**/${segmentMatchPattern}`, maxResults: 512 }, token),
        this.m.fileSearch({ ...searchOptions, filePattern: `**/${segmentMatchPattern}/**` }, token)
      ]);
    } catch (e) {
      if (!$kb(e)) {
        throw e;
      }
    }
    if (!fileResults || !folderResults || token.isCancellationRequested) {
      return { explorerRoot: root, files: [], directories: [], hitMaxResults: false };
    }
    const fileResultResources = fileResults.results.map((result) => result.resource);
    const directoryResources = getMatchingDirectoriesFromFiles(folderResults.results.map((result) => result.resource), root, segmentMatchPattern);
    const filteredFileResources = fileResultResources.filter((resource) => !this.k.isIgnored(resource, root.resource, false));
    const filteredDirectoryResources = directoryResources.filter((resource) => !this.k.isIgnored(resource, root.resource, true));
    return { explorerRoot: root, files: filteredFileResources, directories: filteredDirectoryResources, hitMaxResults: !!fileResults.limitHit || !!folderResults.limitHit };
  }
};
$hwb = __decorate([
  __param(2, $TN),
  __param(3, $km),
  __param(4, $kl),
  __param(5, $4J),
  __param(6, $TJ),
  __param(7, $kvb),
  __param(8, $on)
], $hwb);
function getMatchingDirectoriesFromFiles(resources, root, segmentMatchPattern) {
  const uniqueDirectories = new $Fc();
  for (const resource of resources) {
    const relativePathToRoot = $xh(root.resource, resource);
    if (!relativePathToRoot) {
      throw new Error("Resource is not a child of the root");
    }
    let dirResource = root.resource;
    const stats = relativePathToRoot.split("/").slice(0, -1);
    for (const stat of stats) {
      dirResource = dirResource.with({ path: `${dirResource.path}/${stat}` });
      uniqueDirectories.add(dirResource);
    }
  }
  const matchingDirectories = [];
  for (const dirResource of uniqueDirectories) {
    const stats = dirResource.path.split("/");
    const dirStat = stats[stats.length - 1];
    if (!dirStat || !$Cl(segmentMatchPattern, dirStat)) {
      continue;
    }
    matchingDirectories.push(dirResource);
  }
  return matchingDirectories;
}
function findFirstParent(resource, root) {
  const relativePathToRoot = $xh(root.resource, resource);
  if (!relativePathToRoot) {
    throw new Error("Resource is not a child of the root");
  }
  let currentItem = root;
  let currentResource = root.resource;
  const pathSegments = relativePathToRoot.split("/");
  for (const stat of pathSegments) {
    currentResource = currentResource.with({ path: `${currentResource.path}/${stat}` });
    const child = currentItem.getChild(stat);
    if (!child) {
      return currentItem;
    }
    currentItem = child;
  }
  return void 0;
}
function fuzzyMatchingGlobPattern(pattern) {
  if (!pattern) {
    return "*";
  }
  return "*" + pattern.split("").join("*") + "*";
}
function continousMatchingGlobPattern(pattern) {
  if (!pattern) {
    return "*";
  }
  return "*" + pattern + "*";
}
function caseInsensitiveGlobPattern(pattern) {
  let caseInsensitiveFilePattern = "";
  for (let i2 = 0; i2 < pattern.length; i2++) {
    const char = pattern[i2];
    if (/[a-zA-Z]/.test(char)) {
      caseInsensitiveFilePattern += `[${char.toLowerCase()}${char.toUpperCase()}]`;
    } else {
      caseInsensitiveFilePattern += char;
    }
  }
  return caseInsensitiveFilePattern;
}
var $iwb = class {
  static {
    this.ID = 0;
  }
  get index() {
    return this.a;
  }
  get count() {
    return this.items.length;
  }
  get current() {
    return this.items[this.a];
  }
  get currentId() {
    return `${this.h}_${this.index}`;
  }
  get labels() {
    return this.b;
  }
  constructor(h3, items, templateData, j, k) {
    this.h = h3;
    this.items = items;
    this.j = j;
    this.k = k;
    this.g = new $ze();
    this.onDidChange = this.g.event;
    this.a = items.length - 1;
    this.l(templateData);
    this.f = templateData.label.onDidRender(() => this.l(templateData));
  }
  l(templateData) {
    this.b = Array.from(templateData.container.querySelectorAll(".label-name"));
    let parents = "";
    for (let i2 = 0; i2 < this.labels.length; i2++) {
      const ariaLabel = parents.length ? `${this.items[i2].name}, compact, ${parents}` : this.items[i2].name;
      this.labels[i2].setAttribute("aria-label", ariaLabel);
      this.labels[i2].setAttribute("aria-level", `${this.j + i2}`);
      parents = parents.length ? `${this.items[i2].name} ${parents}` : this.items[i2].name;
    }
    this.updateCollapsed(this.k);
    if (this.a < this.labels.length) {
      this.labels[this.a].classList.add("active");
    }
  }
  previous() {
    if (this.a <= 0) {
      return;
    }
    this.setIndex(this.a - 1);
  }
  next() {
    if (this.a >= this.items.length - 1) {
      return;
    }
    this.setIndex(this.a + 1);
  }
  first() {
    if (this.a === 0) {
      return;
    }
    this.setIndex(0);
  }
  last() {
    if (this.a === this.items.length - 1) {
      return;
    }
    this.setIndex(this.items.length - 1);
  }
  setIndex(index) {
    if (index < 0 || index >= this.items.length) {
      return;
    }
    this.labels[this.a].classList.remove("active");
    this.a = index;
    this.labels[this.a].classList.add("active");
    this.g.fire();
  }
  updateCollapsed(collapsed2) {
    this.k = collapsed2;
    for (let i2 = 0; i2 < this.labels.length; i2++) {
      this.labels[i2].setAttribute("aria-expanded", collapsed2 ? "false" : "true");
    }
  }
  dispose() {
    this.g.dispose();
    this.f.dispose();
  }
};
var $jwb = class $jwb2 {
  static {
    $jwb_1 = this;
  }
  static {
    this.ID = "file";
  }
  constructor(container2, h3, j, k, l, m, n, o, p, q, t, u) {
    this.h = h3;
    this.j = j;
    this.k = k;
    this.l = l;
    this.m = m;
    this.n = n;
    this.o = o;
    this.p = p;
    this.q = q;
    this.t = t;
    this.u = u;
    this.f = /* @__PURE__ */ new Map();
    this.g = new $Fe();
    this.onDidChangeActiveDescendant = this.g.event;
    this.a = this.n.getValue();
    const updateOffsetStyles = () => {
      const indent = this.n.getValue("workbench.tree.indent");
      const offset = Math.max(22 - indent, 0);
      container2.style.setProperty(`--vscode-explorer-align-offset-margin-left`, `${offset}px`);
    };
    this.b = this.n.onDidChangeConfiguration((e) => {
      if (e.affectsConfiguration("explorer")) {
        this.a = this.n.getValue();
      }
      if (e.affectsConfiguration("workbench.tree.indent")) {
        updateOffsetStyles();
      }
    });
    updateOffsetStyles();
  }
  getWidgetAriaLabel() {
    return localize(7383, null);
  }
  get templateId() {
    return $jwb_1.ID;
  }
  renderTemplate(container2) {
    const templateDisposables = new $2c();
    const label3 = templateDisposables.add(this.h.create(container2, { supportHighlights: true }));
    templateDisposables.add(label3.onDidRender(() => {
      try {
        if (templateData.currentContext) {
          this.k(templateData.currentContext);
        }
      } catch (e) {
      }
    }));
    const contribs = $cwb.create(this.u, container2, templateDisposables);
    templateDisposables.add($cwb.onDidRegisterDescriptor((d) => {
      const contr = d.create(this.u, container2);
      contribs.push(templateDisposables.add(contr));
      contr.setResource(templateData.currentContext?.resource);
    }));
    const templateData = { templateDisposables, elementDisposables: templateDisposables.add(new $2c()), label: label3, container: container2, contribs };
    return templateData;
  }
  renderElement(node, index, templateData) {
    const stat = node.element;
    templateData.currentContext = stat;
    const editableData = this.o.getEditableData(stat);
    templateData.label.element.classList.remove("compressed");
    if (!editableData) {
      templateData.label.element.style.display = "flex";
      this.v(stat, stat.name, void 0, node.filterData, templateData);
    } else {
      templateData.label.element.style.display = "none";
      templateData.contribs.forEach((c) => c.setResource(void 0));
      templateData.elementDisposables.add(this.w(templateData.container, stat, editableData));
    }
  }
  renderCompressedElements(node, index, templateData, height) {
    const stat = node.element.elements[node.element.elements.length - 1];
    templateData.currentContext = stat;
    const editable = node.element.elements.filter((e) => this.o.isEditable(e));
    const editableData = editable.length === 0 ? void 0 : this.o.getEditableData(editable[0]);
    if (!editableData) {
      templateData.label.element.classList.add("compressed");
      templateData.label.element.style.display = "flex";
      const id2 = `compressed-explorer_${$iwb.ID++}`;
      const labels2 = node.element.elements.map((e) => e.name);
      let fuzzyScore = node.filterData;
      if (fuzzyScore && fuzzyScore.length > 2) {
        const filterDataOffset = labels2.join("/").length - labels2[labels2.length - 1].length;
        fuzzyScore = [fuzzyScore[0], fuzzyScore[1] + filterDataOffset, ...fuzzyScore.slice(2)];
      }
      this.v(stat, labels2, id2, fuzzyScore, templateData);
      const compressedNavigationController = new $iwb(id2, node.element.elements, templateData, node.depth, node.collapsed);
      templateData.elementDisposables.add(compressedNavigationController);
      const nodeControllers = this.f.get(stat) ?? [];
      this.f.set(stat, [...nodeControllers, compressedNavigationController]);
      templateData.elementDisposables.add(this.g.add(compressedNavigationController.onDidChange));
      templateData.elementDisposables.add($_i(templateData.container, "mousedown", (e) => {
        const result = getIconLabelNameFromHTMLElement(e.target);
        if (result) {
          compressedNavigationController.setIndex(result.index);
        }
      }));
      templateData.elementDisposables.add($1c(() => {
        const nodeControllers2 = this.f.get(stat) ?? [];
        const renderedIndex = nodeControllers2.findIndex((controller) => controller === compressedNavigationController);
        if (renderedIndex < 0) {
          throw new Error("Disposing unknown navigation controller");
        }
        if (nodeControllers2.length === 1) {
          this.f.delete(stat);
        } else {
          nodeControllers2.splice(renderedIndex, 1);
        }
      }));
    } else {
      templateData.label.element.classList.remove("compressed");
      templateData.label.element.style.display = "none";
      templateData.contribs.forEach((c) => c.setResource(void 0));
      templateData.elementDisposables.add(this.w(templateData.container, editable[0], editableData));
    }
  }
  v(stat, label3, domId, filterData, templateData) {
    templateData.label.element.style.display = "flex";
    const extraClasses = ["explorer-item"];
    if (this.o.isCut(stat)) {
      extraClasses.push("cut");
    }
    const theme = this.m.getFileIconTheme();
    const twistieContainer = templateData.container.parentElement?.parentElement?.querySelector(".monaco-tl-twistie");
    twistieContainer?.classList.toggle("force-twistie", stat.hasNests && theme.hidesExplorerArrows);
    const themeIsUnhappyWithNesting = theme.hasFileIcons && (theme.hidesExplorerArrows || !theme.hasFolderIcons);
    const realignNestedChildren = stat.nestedParent && themeIsUnhappyWithNesting;
    templateData.contribs.forEach((c) => c.setResource(stat.resource));
    templateData.label.setResource({ resource: stat.resource, name: label3 }, {
      fileKind: stat.isRoot ? FileKind.ROOT_FOLDER : stat.isDirectory ? FileKind.FOLDER : FileKind.FILE,
      extraClasses: realignNestedChildren ? [...extraClasses, "align-nest-icon-with-parent-icon"] : extraClasses,
      fileDecorations: this.a.explorer.decorations,
      matches: $Ul(filterData),
      separator: this.p.getSeparator(stat.resource.scheme, stat.resource.authority),
      domId
    });
    const highlightResults = stat.isDirectory ? this.j.get(stat) : 0;
    if (highlightResults > 0) {
      const badge = new $D2(templateData.label.element.lastElementChild, {}, { ...$E$, badgeBackground: $Zn($Dr), badgeBorder: $Zn($Er) });
      badge.setCount(highlightResults);
      badge.setTitleFormat(localize(7384, null, highlightResults));
      templateData.elementDisposables.add(badge);
    }
    templateData.label.element.classList.toggle("highlight-badge", highlightResults > 0);
  }
  w(container2, stat, editableData) {
    const label3 = this.h.create(container2);
    const extraClasses = ["explorer-item", "explorer-item-edited"];
    const fileKind = stat.isRoot ? FileKind.ROOT_FOLDER : stat.isDirectory ? FileKind.FOLDER : FileKind.FILE;
    const theme = this.m.getFileIconTheme();
    const themeIsUnhappyWithNesting = theme.hasFileIcons && (theme.hidesExplorerArrows || !theme.hasFolderIcons);
    const realignNestedChildren = stat.nestedParent && themeIsUnhappyWithNesting;
    const labelOptions = {
      hidePath: true,
      hideLabel: true,
      fileKind,
      extraClasses: realignNestedChildren ? [...extraClasses, "align-nest-icon-with-parent-icon"] : extraClasses
    };
    const parent = stat.name ? $uh(stat.resource) : stat.resource;
    const value = stat.name || "";
    label3.setFile($vh(parent, value || " "), labelOptions);
    label3.element.firstElementChild.style.display = "none";
    const inputBox = new $I2(label3.element, this.l, {
      validationOptions: {
        validation: (value2) => {
          const message = editableData.validationMessage(value2);
          if (!message || message.severity !== Severity2.Error) {
            return null;
          }
          return {
            content: message.content,
            formatContent: true,
            type: 3
            /* MessageType.ERROR */
          };
        }
      },
      ariaLabel: localize(7385, null),
      inputBoxStyles: $B$
    });
    const lastDot = value.lastIndexOf(".");
    let currentSelectionState = "prefix";
    inputBox.value = value;
    inputBox.focus();
    inputBox.select({ start: 0, end: lastDot > 0 && !stat.isDirectory ? lastDot : value.length });
    const done = $Qc((success, finishEditing) => {
      label3.element.style.display = "none";
      const value2 = inputBox.value;
      $Xc(toDispose);
      label3.element.remove();
      if (finishEditing) {
        editableData.onFinish(value2, success);
      }
    });
    const showInputBoxNotification = () => {
      if (inputBox.isInputValid()) {
        const message = editableData.validationMessage(inputBox.value);
        if (message) {
          inputBox.showMessage({
            content: message.content,
            formatContent: true,
            type: message.severity === Severity2.Info ? 1 : message.severity === Severity2.Warning ? 2 : 3
            /* MessageType.ERROR */
          });
        } else {
          inputBox.hideMessage();
        }
      }
    };
    showInputBoxNotification();
    const toDispose = [
      inputBox,
      inputBox.onDidChange((value2) => {
        label3.setFile($vh(parent, value2 || " "), labelOptions);
      }),
      $aj(inputBox.inputElement, $7j.KEY_DOWN, (e) => {
        if (e.equals(
          60
          /* KeyCode.F2 */
        )) {
          const dotIndex = inputBox.value.lastIndexOf(".");
          if (stat.isDirectory || dotIndex === -1) {
            return;
          }
          if (currentSelectionState === "prefix") {
            currentSelectionState = "all";
            inputBox.select({ start: 0, end: inputBox.value.length });
          } else if (currentSelectionState === "all") {
            currentSelectionState = "suffix";
            inputBox.select({ start: dotIndex + 1, end: inputBox.value.length });
          } else {
            currentSelectionState = "prefix";
            inputBox.select({ start: 0, end: dotIndex });
          }
        } else if (e.equals(
          3
          /* KeyCode.Enter */
        )) {
          if (!inputBox.validate()) {
            done(true, true);
          }
        } else if (e.equals(
          9
          /* KeyCode.Escape */
        )) {
          done(false, true);
        }
      }),
      $aj(inputBox.inputElement, $7j.KEY_UP, (e) => {
        showInputBoxNotification();
      }),
      $_i(inputBox.inputElement, $7j.BLUR, async () => {
        while (true) {
          await $Wh(0);
          const ownerDocument = inputBox.inputElement.ownerDocument;
          if (!ownerDocument.hasFocus()) {
            break;
          }
          if ($Mj(inputBox.inputElement)) {
            return;
          } else if ($Uj(ownerDocument.activeElement) && $Hj(ownerDocument.activeElement, "context-view")) {
            await Event2.toPromise(this.t.onDidHideContextMenu);
          } else {
            break;
          }
        }
        done(inputBox.isInputValid(), true);
      }),
      label3
    ];
    return $1c(() => {
      done(false, false);
    });
  }
  disposeElement(element, index, templateData) {
    templateData.currentContext = void 0;
    templateData.elementDisposables.clear();
  }
  disposeCompressedElements(node, index, templateData) {
    templateData.currentContext = void 0;
    templateData.elementDisposables.clear();
  }
  disposeTemplate(templateData) {
    templateData.templateDisposables.dispose();
  }
  getCompressedNavigationController(stat) {
    return this.f.get(stat);
  }
  // IAccessibilityProvider
  getAriaLabel(element) {
    return element.name;
  }
  getAriaLevel(element) {
    let depth = 0;
    let parent = element.parent;
    while (parent) {
      parent = parent.parent;
      depth++;
    }
    if (this.q.getWorkbenchState() === 3) {
      depth = depth + 1;
    }
    return depth;
  }
  getActiveDescendantId(stat) {
    return this.f.get(stat)?.[0]?.currentId ?? void 0;
  }
  dispose() {
    this.b.dispose();
  }
};
$jwb = $jwb_1 = __decorate([
  __param(4, $40),
  __param(5, $gs),
  __param(6, $kl),
  __param(7, $kvb),
  __param(8, $ZI),
  __param(9, $Zk),
  __param(10, $50),
  __param(11, $Pk)
], $jwb);
var $kwb = class $kwb2 {
  constructor(k, l, m, n, o, p) {
    this.k = k;
    this.l = l;
    this.m = m;
    this.n = n;
    this.o = o;
    this.p = p;
    this.a = /* @__PURE__ */ new Map();
    this.b = /* @__PURE__ */ new Set();
    this.f = new $ze();
    this.g = [];
    this.h = /* @__PURE__ */ new Map();
    this.j = /* @__PURE__ */ new Map();
    this.g.push(this.k.onDidChangeWorkspaceFolders(() => this.q()));
    this.g.push(this.l.onDidChangeConfiguration((e) => {
      if (e.affectsConfiguration("files.exclude") || e.affectsConfiguration("explorer.excludeGitIgnore")) {
        this.q();
      }
    }));
    this.g.push(this.p.onDidFilesChange((e) => {
      for (const [root, ignoreFileResourceSet] of this.h.entries()) {
        ignoreFileResourceSet.forEach(async (ignoreResource) => {
          if (e.contains(
            ignoreResource,
            0
            /* FileChangeType.UPDATED */
          )) {
            await this.t(root, ignoreResource, true);
          }
          if (e.contains(
            ignoreResource,
            2
            /* FileChangeType.DELETED */
          )) {
            this.j.get(root)?.delete($uh(ignoreResource));
            ignoreFileResourceSet.delete(ignoreResource);
            this.f.fire();
          }
        });
      }
    }));
    this.g.push(this.n.onDidVisibleEditorsChange(() => {
      const editors = this.n.visibleEditors;
      let shouldFire = false;
      for (const e of editors) {
        if (!e.resource) {
          continue;
        }
        const stat = this.m.findClosest(e.resource);
        if (stat && stat.isExcluded) {
          shouldFire = true;
          break;
        }
      }
      for (const e of this.b) {
        if (!editors.includes(e)) {
          shouldFire = true;
          break;
        }
      }
      if (shouldFire) {
        this.b.clear();
        this.f.fire();
      }
    }));
    this.q();
  }
  get onDidChange() {
    return this.f.event;
  }
  q() {
    let shouldFire = false;
    let updatedGitIgnoreSetting = false;
    this.k.getWorkspace().folders.forEach((folder) => {
      const configuration2 = this.l.getValue({ resource: folder.uri });
      const excludesConfig = configuration2?.files?.exclude || /* @__PURE__ */ Object.create(null);
      const parseIgnoreFile = configuration2.explorer.excludeGitIgnore;
      if (parseIgnoreFile && !this.j.has(folder.uri.toString())) {
        updatedGitIgnoreSetting = true;
        this.h.set(folder.uri.toString(), new $Fc());
        this.j.set(folder.uri.toString(), $Wk.forUris((uri) => this.o.extUri.ignorePathCasing(uri)));
      }
      if (!parseIgnoreFile && this.j.has(folder.uri.toString())) {
        updatedGitIgnoreSetting = true;
        this.h.delete(folder.uri.toString());
        this.j.delete(folder.uri.toString());
      }
      if (!shouldFire) {
        const cached = this.a.get(folder.uri.toString());
        shouldFire = !cached || !$Pv(cached.original, excludesConfig);
      }
      const excludesConfigCopy = $Lv(excludesConfig);
      this.a.set(folder.uri.toString(), { original: excludesConfigCopy, parsed: $Dl(excludesConfigCopy) });
    });
    if (shouldFire || updatedGitIgnoreSetting) {
      this.b.clear();
      this.f.fire();
    }
  }
  /**
   * Given a .gitignore file resource, processes the resource and adds it to the ignore tree which hides explorer items
   * @param root The root folder of the workspace as a string. Used for lookup key for ignore tree and resource list
   * @param ignoreFileResource The resource of the .gitignore file
   * @param update Whether or not we're updating an existing ignore file. If true it deletes the old entry
   */
  async t(root, ignoreFileResource, update) {
    const dirUri = $uh(ignoreFileResource);
    const ignoreTree = this.j.get(root);
    if (!ignoreTree) {
      return;
    }
    if (!update && ignoreTree.has(dirUri)) {
      return;
    }
    const content = await this.p.readFile(ignoreFileResource);
    if (update) {
      const ignoreFile = ignoreTree.get(dirUri);
      ignoreFile?.updateContents(content.value.toString());
    } else {
      const ignoreParent = ignoreTree.findSubstr(dirUri);
      const ignoreFile = new $bwb(content.value.toString(), dirUri.path, ignoreParent);
      ignoreTree.set(dirUri, ignoreFile);
      if (!this.h.get(root)?.has(ignoreFileResource)) {
        this.h.get(root)?.add(ignoreFileResource);
      }
    }
    this.f.fire();
  }
  filter(stat, parentVisibility) {
    if (stat.name === ".gitignore" && this.j.has(stat.root.resource.toString())) {
      this.t(stat.root.resource.toString(), stat.resource, false);
      return true;
    }
    return this.u(stat, parentVisibility);
  }
  u(stat, parentVisibility) {
    stat.isExcluded = false;
    if (parentVisibility === 0) {
      stat.isExcluded = true;
      return false;
    }
    if (this.m.getEditableData(stat)) {
      return true;
    }
    const cached = this.a.get(stat.root.resource.toString());
    const globMatch = cached?.parsed($pc(stat.root.resource.path, stat.resource.path), stat.name, (name) => !!(stat.parent && stat.parent.getChild(name)));
    const isHiddenResource = !!globMatch ? true : this.isIgnored(stat.resource, stat.root.resource, stat.isDirectory);
    if (isHiddenResource || stat.parent?.isExcluded) {
      stat.isExcluded = true;
      const editors = this.n.visibleEditors;
      const editor = editors.find((e) => e.resource && this.o.extUri.isEqualOrParent(e.resource, stat.resource));
      if (editor && stat.root === this.m.findClosestRoot(stat.resource)) {
        this.b.add(editor);
        return true;
      }
      return false;
    }
    return true;
  }
  isIgnored(resource, rootResource, isDirectory) {
    const ignoreFile = this.j.get(rootResource.toString())?.findSubstr(resource);
    const isIncludedInTraversal = ignoreFile?.isPathIncludedInTraversal(resource.path, isDirectory);
    return isIncludedInTraversal === void 0 ? false : !isIncludedInTraversal;
  }
  dispose() {
    $Xc(this.g);
  }
};
$kwb = __decorate([
  __param(0, $Zk),
  __param(1, $kl),
  __param(2, $kvb),
  __param(3, $mJ),
  __param(4, $vl),
  __param(5, $km)
], $kwb);
var $lwb = class $lwb2 {
  constructor(a, b) {
    this.a = a;
    this.b = b;
  }
  compare(statA, statB) {
    if (statA.isRoot) {
      if (statB.isRoot) {
        const workspaceA = this.b.getWorkspaceFolder(statA.resource);
        const workspaceB = this.b.getWorkspaceFolder(statB.resource);
        return workspaceA && workspaceB ? workspaceA.index - workspaceB.index : -1;
      }
      return -1;
    }
    if (statB.isRoot) {
      return 1;
    }
    const sortOrder = this.a.sortOrderConfiguration.sortOrder;
    const lexicographicOptions = this.a.sortOrderConfiguration.lexicographicOptions;
    const reverse = this.a.sortOrderConfiguration.reverse;
    if (reverse) {
      [statA, statB] = [statB, statA];
    }
    let compareFileNames;
    let compareFileExtensions;
    switch (lexicographicOptions) {
      case "upper":
        compareFileNames = $GM;
        compareFileExtensions = $LM;
        break;
      case "lower":
        compareFileNames = $HM;
        compareFileExtensions = $MM;
        break;
      case "unicode":
        compareFileNames = $IM;
        compareFileExtensions = $NM;
        break;
      default:
        compareFileNames = $FM;
        compareFileExtensions = $KM;
    }
    switch (sortOrder) {
      case "type":
        if (statA.isDirectory && !statB.isDirectory) {
          return -1;
        }
        if (statB.isDirectory && !statA.isDirectory) {
          return 1;
        }
        if (statA.isDirectory && statB.isDirectory) {
          return compareFileNames(statA.name, statB.name);
        }
        break;
      case "filesFirst":
        if (statA.isDirectory && !statB.isDirectory) {
          return 1;
        }
        if (statB.isDirectory && !statA.isDirectory) {
          return -1;
        }
        break;
      case "foldersNestsFiles":
        if (statA.isDirectory && !statB.isDirectory) {
          return -1;
        }
        if (statB.isDirectory && !statA.isDirectory) {
          return 1;
        }
        if (statA.hasNests && !statB.hasNests) {
          return -1;
        }
        if (statB.hasNests && !statA.hasNests) {
          return 1;
        }
        break;
      case "mixed":
        break;
      default:
        if (statA.isDirectory && !statB.isDirectory) {
          return -1;
        }
        if (statB.isDirectory && !statA.isDirectory) {
          return 1;
        }
        break;
    }
    switch (sortOrder) {
      case "type":
        return compareFileExtensions(statA.name, statB.name);
      case "modified":
        if (statA.mtime !== statB.mtime) {
          return statA.mtime && statB.mtime && statA.mtime < statB.mtime ? 1 : -1;
        }
        return compareFileNames(statA.name, statB.name);
      default:
        return compareFileNames(statA.name, statB.name);
    }
  }
};
$lwb = __decorate([
  __param(0, $kvb),
  __param(1, $Zk)
], $lwb);
var $mwb = class $mwb2 {
  static {
    $mwb_1 = this;
  }
  static {
    this.a = "explorer.confirmDragAndDrop";
  }
  constructor(j, k, l, m, n, o, p, q, t, u, v) {
    this.j = j;
    this.k = k;
    this.l = l;
    this.m = m;
    this.n = n;
    this.o = o;
    this.p = p;
    this.q = q;
    this.t = t;
    this.u = u;
    this.v = v;
    this.f = $3c.None;
    this.g = new $2c();
    this.h = false;
    const updateDropEnablement = (e) => {
      if (!e || e.affectsConfiguration("explorer.enableDragAndDrop")) {
        this.h = this.p.getValue("explorer.enableDragAndDrop");
      }
    };
    updateDropEnablement(void 0);
    this.g.add(this.p.onDidChangeConfiguration((e) => updateDropEnablement(e)));
  }
  onDragOver(data, target, targetIndex, targetSector, originalEvent) {
    if (!this.h) {
      return false;
    }
    if (target) {
      const compressedTarget = $mwb_1.C(target, originalEvent);
      if (compressedTarget) {
        const iconLabelName = getIconLabelNameFromHTMLElement(originalEvent.target);
        if (iconLabelName && iconLabelName.index < iconLabelName.count - 1) {
          const result = this.w(data, compressedTarget, targetIndex, targetSector, originalEvent);
          if (result) {
            if (iconLabelName.element !== this.b) {
              this.b = iconLabelName.element;
              this.f.dispose();
              this.f = $1c(() => {
                iconLabelName.element.classList.remove("drop-target");
                this.b = void 0;
              });
              iconLabelName.element.classList.add("drop-target");
            }
            return typeof result === "boolean" ? result : { ...result, feedback: [] };
          }
          this.f.dispose();
          return false;
        }
      }
    }
    this.f.dispose();
    return this.w(data, target, targetIndex, targetSector, originalEvent);
  }
  w(data, target, targetIndex, targetSector, originalEvent) {
    const isCopy = originalEvent && (originalEvent.ctrlKey && !$m || originalEvent.altKey && $m);
    const isNative = data instanceof $i1;
    const effectType = isNative || isCopy ? 0 : 1;
    const effect = {
      type: effectType,
      position: "drop-target"
      /* ListDragOverEffectPosition.Over */
    };
    if (isNative) {
      if (!$z_(originalEvent, $kZ.FILES, $u_.FILES, $kZ.RESOURCES)) {
        return false;
      }
    } else if (data instanceof $h1) {
      return false;
    } else {
      const items = $mwb_1.B(data);
      const isRootsReorder = items.every((item) => item.isRoot);
      if (!target) {
        if (!isCopy && items.every((i2) => !!i2.parent && i2.parent.isRoot)) {
          return false;
        }
        if (isRootsReorder) {
          return { accept: true, effect: {
            type: 1,
            position: "drop-target-after"
            /* ListDragOverEffectPosition.After */
          } };
        }
        return { accept: true, bubble: 0, effect, autoExpand: false };
      }
      if (!Array.isArray(items)) {
        return false;
      }
      if (!isCopy && items.every((source) => source.isReadonly)) {
        return false;
      }
      if (items.some((source) => {
        if (source.isRoot) {
          return false;
        }
        if (this.u.extUri.isEqual(source.resource, target.resource)) {
          return true;
        }
        if (!isCopy && this.u.extUri.isEqual($uh(source.resource), target.resource)) {
          return true;
        }
        if (this.u.extUri.isEqualOrParent(target.resource, source.resource)) {
          return true;
        }
        return false;
      })) {
        return false;
      }
      if (isRootsReorder) {
        if (!target.isRoot) {
          return false;
        }
        let dropEffectPosition = void 0;
        switch (targetSector) {
          case 0:
          case 1:
            dropEffectPosition = "drop-target-before";
            break;
          case 2:
          case 3:
            dropEffectPosition = "drop-target-after";
            break;
        }
        return { accept: true, effect: { type: 1, position: dropEffectPosition } };
      }
    }
    if (!target) {
      return { accept: true, bubble: 0, effect };
    } else {
      if (target.isDirectory) {
        if (target.isReadonly) {
          return false;
        }
        return { accept: true, bubble: 0, effect, autoExpand: true };
      }
      if (this.n.getWorkspace().folders.every((folder) => folder.uri.toString() !== target.resource.toString())) {
        return { accept: true, bubble: 1, effect };
      }
    }
    return false;
  }
  getDragURI(element) {
    if (this.k.isEditable(element)) {
      return null;
    }
    return element.resource.toString();
  }
  getDragLabel(elements, originalEvent) {
    if (elements.length === 1) {
      const stat = $mwb_1.C(elements[0], originalEvent);
      return stat.name;
    }
    return String(elements.length);
  }
  onDragStart(data, originalEvent) {
    const items = $mwb_1.B(data, originalEvent);
    if (items && items.length && originalEvent.dataTransfer) {
      this.q.invokeFunction((accessor) => $Eob(accessor, items, originalEvent));
      const fileResources = items.filter((s) => s.resource.scheme === Schemas.file).map((r2) => r2.resource.fsPath);
      if (fileResources.length) {
        originalEvent.dataTransfer.setData($u_.FILES, JSON.stringify(fileResources));
      }
    }
  }
  async drop(data, target, targetIndex, targetSector, originalEvent) {
    this.f.dispose();
    if (target) {
      const compressedTarget = $mwb_1.C(target, originalEvent);
      if (compressedTarget) {
        target = compressedTarget;
      }
    }
    if (!target) {
      target = this.k.roots[this.k.roots.length - 1];
      targetSector = 3;
    }
    if (!target.isDirectory && target.parent) {
      target = target.parent;
    }
    if (target.isReadonly) {
      return;
    }
    const resolvedTarget = target;
    if (!resolvedTarget) {
      return;
    }
    try {
      if (data instanceof $i1) {
        if (this.v.isEnabledFileUploads) {
          if (!$r || $fl(this.n.getWorkspace()) && WebFileSystemAccess.supported($Y)) {
            const fileImport = this.q.createInstance($pvb);
            await fileImport.import(resolvedTarget, originalEvent, $Y);
          } else {
            const browserUpload = this.q.createInstance($ovb);
            await browserUpload.upload(target, originalEvent);
          }
        }
      } else {
        await this.x(data, resolvedTarget, targetIndex, targetSector, originalEvent);
      }
    } catch (error) {
      this.m.error($1m(error));
    }
  }
  async x(data, target, targetIndex, targetSector, originalEvent) {
    const elementsData = $mwb_1.B(data);
    const distinctItems = new Map(elementsData.map((element) => [element, this.j(element)]));
    for (const [item, collapsed2] of distinctItems) {
      if (collapsed2) {
        const nestedChildren = item.nestedChildren;
        if (nestedChildren) {
          for (const child of nestedChildren) {
            distinctItems.set(child, true);
          }
        }
      }
    }
    const items = $Eh([...distinctItems.keys()], (s) => s.resource);
    const isCopy = originalEvent.ctrlKey && !$m || originalEvent.altKey && $m;
    const confirmDragAndDrop = !isCopy && this.p.getValue($mwb_1.a);
    if (confirmDragAndDrop) {
      const message = items.length > 1 && items.every((s) => s.isRoot) ? localize(7386, null) : items.length > 1 ? localize(7387, null, items.length, target.name) : items[0].isRoot ? localize(7388, null, items[0].name) : localize(7389, null, items[0].name, target.name);
      const detail2 = items.length > 1 && !items.every((s) => s.isRoot) ? $2v(items.map((i2) => i2.resource)) : void 0;
      const confirmation = await this.m.confirm({
        message,
        detail: detail2,
        checkbox: {
          label: localize(7390, null)
        },
        primaryButton: localize(7391, null)
      });
      if (!confirmation.confirmed) {
        return;
      }
      if (confirmation.checkboxChecked === true) {
        await this.p.updateValue($mwb_1.a, false);
      }
    }
    await this.y(items.filter((s) => s.isRoot), target, targetSector);
    const sources = items.filter((s) => !s.isRoot);
    if (isCopy) {
      return this.z(sources, target);
    }
    return this.A(sources, target);
  }
  async y(roots, target, targetSector) {
    if (roots.length === 0) {
      return;
    }
    const folders = this.n.getWorkspace().folders;
    let targetIndex;
    const sourceIndices = [];
    const workspaceCreationData = [];
    const rootsToMove = [];
    for (let index = 0; index < folders.length; index++) {
      const data = {
        uri: folders[index].uri,
        name: folders[index].name
      };
      if (target instanceof $ivb && this.u.extUri.isEqual(folders[index].uri, target.resource)) {
        targetIndex = index;
      }
      for (const root of roots) {
        if (this.u.extUri.isEqual(folders[index].uri, root.resource)) {
          sourceIndices.push(index);
          break;
        }
      }
      if (roots.every((r2) => r2.resource.toString() !== folders[index].uri.toString())) {
        workspaceCreationData.push(data);
      } else {
        rootsToMove.push(data);
      }
    }
    if (targetIndex === void 0) {
      targetIndex = workspaceCreationData.length;
    } else {
      switch (targetSector) {
        case 3:
        case 2:
          targetIndex++;
          break;
      }
      for (const sourceIndex of sourceIndices) {
        if (sourceIndex < targetIndex) {
          targetIndex--;
        }
      }
    }
    workspaceCreationData.splice(targetIndex, 0, ...rootsToMove);
    return this.t.updateFolders(0, workspaceCreationData.length, workspaceCreationData);
  }
  async z(sources, target) {
    const explorerConfig = this.p.getValue().explorer;
    const resourceFileEdits = [];
    for (const { resource, isDirectory } of sources) {
      const allowOverwrite = explorerConfig.incrementalNaming === "disabled";
      const newResource = await $Gvb(this.k, this.o, this.m, target, { resource, isDirectory, allowOverwrite }, explorerConfig.incrementalNaming);
      if (!newResource) {
        continue;
      }
      const resourceEdit = new $K_(resource, newResource, { copy: true, overwrite: allowOverwrite });
      resourceFileEdits.push(resourceEdit);
    }
    const labelSuffix = getFileOrFolderLabelSuffix(sources);
    await this.k.applyBulkEdit(resourceFileEdits, {
      confirmBeforeUndo: explorerConfig.confirmUndo === "default" || explorerConfig.confirmUndo === "verbose",
      undoLabel: localize(7392, null, labelSuffix),
      progressLabel: localize(7393, null, labelSuffix)
    });
    const editors = resourceFileEdits.filter((edit3) => {
      const item = edit3.newResource ? this.k.findClosest(edit3.newResource) : void 0;
      return item && !item.isDirectory;
    }).map((edit3) => ({ resource: edit3.newResource, options: { pinned: true } }));
    await this.l.openEditors(editors);
  }
  async A(sources, target) {
    const resourceFileEdits = sources.filter((source) => !source.isReadonly).map((source) => new $K_(source.resource, $vh(target.resource, source.name)));
    const labelSuffix = getFileOrFolderLabelSuffix(sources);
    const options3 = {
      confirmBeforeUndo: this.p.getValue().explorer.confirmUndo === "verbose",
      undoLabel: localize(7394, null, labelSuffix),
      progressLabel: localize(7395, null, labelSuffix)
    };
    try {
      await this.k.applyBulkEdit(resourceFileEdits, options3);
    } catch (error) {
      if (error.fileOperationResult === 4) {
        const overwrites = [];
        for (const edit3 of resourceFileEdits) {
          if (edit3.newResource && await this.o.exists(edit3.newResource)) {
            overwrites.push(edit3.newResource);
          }
        }
        const confirm = $svb(overwrites);
        const { confirmed } = await this.m.confirm(confirm);
        if (confirmed) {
          await this.k.applyBulkEdit(resourceFileEdits.map((re) => new $K_(re.oldResource, re.newResource, { overwrite: true })), options3);
        }
      } else {
        throw error;
      }
    }
  }
  static B(data, dragStartEvent) {
    if (data.context) {
      return data.context;
    }
    if (dragStartEvent && data.elements.length === 1) {
      data.context = [$mwb_1.C(data.elements[0], dragStartEvent)];
      return data.context;
    }
    return data.elements;
  }
  static C(stat, dragEvent) {
    const target = getWindow(dragEvent).document.elementFromPoint(dragEvent.clientX, dragEvent.clientY);
    const iconLabelName = getIconLabelNameFromHTMLElement(target);
    if (iconLabelName) {
      const { count, index } = iconLabelName;
      let i2 = count - 1;
      while (i2 > index && stat.parent) {
        stat = stat.parent;
        i2--;
      }
      return stat;
    }
    return stat;
  }
  onDragEnd() {
    this.f.dispose();
  }
  dispose() {
    this.f.dispose();
  }
};
$mwb = $mwb_1 = __decorate([
  __param(1, $kvb),
  __param(2, $mJ),
  __param(3, $Yv),
  __param(4, $Zk),
  __param(5, $km),
  __param(6, $kl),
  __param(7, $Pk),
  __param(8, $zob),
  __param(9, $vl),
  __param(10, $M4)
], $mwb);
function getIconLabelNameFromHTMLElement(target) {
  if (!$Uj(target)) {
    return null;
  }
  let element = target;
  while (element && !element.classList.contains("monaco-list-row")) {
    if (element.classList.contains("label-name") && element.hasAttribute("data-icon-label-count")) {
      const count = Number(element.getAttribute("data-icon-label-count"));
      const index = Number(element.getAttribute("data-icon-label-index"));
      if ($Dg(count) && $Dg(index)) {
        return { element, count, index };
      }
    }
    element = element.parentElement;
  }
  return null;
}
function $nwb(target) {
  return !!getIconLabelNameFromHTMLElement(target);
}
var $owb = class {
  isIncompressible(stat) {
    return stat.isRoot || !stat.isDirectory || stat instanceof $jvb || (!stat.parent || stat.parent.isRoot);
  }
};
function getFileOrFolderLabelSuffix(items) {
  if (items.length === 1) {
    return items[0].name;
  }
  if (items.every((i2) => i2.isDirectory)) {
    return localize(7396, null, items.length);
  }
  if (items.every((i2) => !i2.isDirectory)) {
    return localize(7397, null, items.length);
  }
  return `${items.length} files and folders`;
}

// out-build/vs/workbench/contrib/files/browser/views/explorerDecorationsProvider.js
function $pwb(fileStat) {
  if (fileStat.isRoot && fileStat.error) {
    return {
      tooltip: localize(7370, null, $1m(fileStat.error)),
      letter: "!",
      color: $wr
    };
  }
  if (fileStat.isSymbolicLink) {
    return {
      tooltip: localize(7371, null),
      letter: "\u2937"
    };
  }
  if (fileStat.isUnknown) {
    return {
      tooltip: localize(7372, null),
      letter: "?"
    };
  }
  if (fileStat.isExcluded) {
    return {
      color: $Fr
    };
  }
  return void 0;
}
var $qwb = class $qwb2 {
  constructor(c, contextService) {
    this.c = c;
    this.label = localize(7373, null);
    this.a = new $ze();
    this.b = new $2c();
    this.b.add(this.a);
    this.b.add(contextService.onDidChangeWorkspaceFolders((e) => {
      this.a.fire(e.changed.concat(e.added).map((wf) => wf.uri));
    }));
    this.b.add($ewb.event((resource) => {
      this.a.fire([resource]);
    }));
  }
  get onDidChange() {
    return this.a.event;
  }
  async provideDecorations(resource) {
    const fileStat = this.c.findClosest(resource);
    if (!fileStat) {
      throw new Error("ExplorerItem not found");
    }
    return $pwb(fileStat);
  }
  dispose() {
    this.b.dispose();
  }
};
$qwb = __decorate([
  __param(0, $kvb),
  __param(1, $Zk)
], $qwb);

// out-build/vs/workbench/contrib/files/browser/views/explorerView.js
var $Dwb_1;
function hasExpandedRootChild(tree, treeInput) {
  for (const folder of treeInput) {
    if (tree.hasNode(folder) && !tree.isCollapsed(folder)) {
      for (const [, child] of folder.children.entries()) {
        if (tree.hasNode(child) && tree.isCollapsible(child) && !tree.isCollapsed(child)) {
          return true;
        }
      }
    }
  }
  return false;
}
function hasExpandedNode(tree, treeInput) {
  for (const folder of treeInput) {
    if (tree.hasNode(folder) && !tree.isCollapsed(folder)) {
      return true;
    }
  }
  return false;
}
var identityProvider = {
  getId: (stat) => {
    if (stat instanceof $jvb) {
      return `new:${stat.getId()}`;
    }
    return stat.getId();
  }
};
function $Cwb(focus, selection, respectMultiSelection, compressedNavigationControllerProvider) {
  let focusedStat;
  focusedStat = focus.length ? focus[0] : void 0;
  if (respectMultiSelection && selection.length > 1) {
    focusedStat = void 0;
  }
  const compressedNavigationControllers = focusedStat && compressedNavigationControllerProvider.getCompressedNavigationController(focusedStat);
  const compressedNavigationController = compressedNavigationControllers && compressedNavigationControllers.length ? compressedNavigationControllers[0] : void 0;
  focusedStat = compressedNavigationController ? compressedNavigationController.current : focusedStat;
  const selectedStats = [];
  for (const stat of selection) {
    const controllers = compressedNavigationControllerProvider.getCompressedNavigationController(stat);
    const controller = controllers && controllers.length ? controllers[0] : void 0;
    if (controller && focusedStat && controller === compressedNavigationController) {
      if (stat === focusedStat) {
        selectedStats.push(stat);
      }
      continue;
    }
    if (controller) {
      selectedStats.push(...controller.items);
    } else {
      selectedStats.push(stat);
    }
  }
  if (!focusedStat) {
    if (respectMultiSelection) {
      return selectedStats;
    } else {
      return [];
    }
  }
  if (respectMultiSelection && selectedStats.indexOf(focusedStat) >= 0) {
    return selectedStats;
  }
  return [focusedStat];
}
var $Dwb = class $Dwb2 extends $_ob {
  static {
    $Dwb_1 = this;
  }
  static {
    this.TREE_VIEW_STATE_STORAGE_KEY = "workbench.explorer.treeViewState";
  }
  constructor(options3, contextMenuService, viewDescriptorService, instantiationService, kc, lc, mc, nc, oc, keybindingService, contextKeyService, configurationService, pc, qc, themeService, telemetryService, hoverService, rc, sc, tc, uc, vc, wc, openerService) {
    super(options3, keybindingService, contextMenuService, configurationService, contextKeyService, viewDescriptorService, instantiationService, openerService, themeService, telemetryService, hoverService);
    this.kc = kc;
    this.lc = lc;
    this.mc = mc;
    this.nc = nc;
    this.oc = oc;
    this.pc = pc;
    this.qc = qc;
    this.rc = rc;
    this.sc = sc;
    this.tc = tc;
    this.uc = uc;
    this.vc = vc;
    this.wc = wc;
    this.hc = false;
    this.jc = options3.delegate;
    this.f = instantiationService.createInstance($lqb);
    this.B(this.f);
    this.h = $0sb.bindTo(contextKeyService);
    this.g = $7sb.bindTo(contextKeyService);
    this.j = $8sb.bindTo(contextKeyService);
    this.m = $$sb.bindTo(contextKeyService);
    this.n = $_sb.bindTo(contextKeyService);
    this.r = $btb.bindTo(contextKeyService);
    this.sb = $gtb.bindTo(contextKeyService);
    this.ac = $htb.bindTo(contextKeyService);
    this.bc = $itb.bindTo(contextKeyService);
    this.cc = $jtb.bindTo(contextKeyService);
    this.dc = $6sb.bindTo(contextKeyService);
    this.rc.registerView(this);
  }
  get autoReveal() {
    return this.hc;
  }
  set autoReveal(autoReveal) {
    this.hc = autoReveal;
  }
  get name() {
    return this.qc.getWorkspaceLabel(this.kc.getWorkspace());
  }
  get title() {
    return this.name;
  }
  set title(_) {
  }
  setVisible(visible) {
    this.dc.set(visible);
    super.setVisible(visible);
  }
  get xc() {
    return $Bvb.bindTo(this.Bb);
  }
  get yc() {
    return $atb.bindTo(this.Bb);
  }
  // Split view methods
  U(container2) {
    super.U(container2);
    this.gc = new $jZ(container2, () => this.setExpanded(true));
    const titleElement = container2.querySelector(".title");
    const setHeader = () => {
      titleElement.textContent = this.name;
      this.Qb(this.name);
      this.ariaHeaderLabel = localize(7374, null, this.name);
      titleElement.setAttribute("aria-label", this.ariaHeaderLabel);
    };
    this.B(this.kc.onDidChangeWorkspaceName(setHeader));
    this.B(this.qc.onDidChangeFormatters(setHeader));
    setHeader();
  }
  X(height, width2) {
    super.X(height, width2);
    this.a.layout(height, width2);
  }
  W(container2) {
    super.W(container2);
    this.ab = container2;
    this.L = $bk(container2, $(".explorer-folders-view"));
    this.Dc(this.L);
    this.B(this.qc.onDidChangeFormatters(() => {
      this.db.fire();
    }));
    this.Ec(void 0);
    this.B(this.mc.onDidActiveEditorChange(() => {
      this.Cc();
    }));
    this.B(this.Ab.onDidChangeConfiguration((e) => this.Ec(e)));
    this.B(this.onDidChangeBodyVisibility(async (visible) => {
      if (visible) {
        await this.setTreeInput();
        this.Kc();
        this.Cc(true);
      }
    }));
    this.B($_i(getWindow(this.ab), $7j.PASTE, async (event) => {
      if (!this.hasFocus() || this.j.get()) {
        return;
      }
      if (event.clipboardData?.files?.length) {
        await this.wc.executeCommand("filesExplorer.paste", event.clipboardData?.files);
      }
    }));
  }
  focus() {
    super.focus();
    this.a.domFocus();
    if (this.a.getFocusedPart() === 0) {
      const focused = this.a.getFocus();
      if (focused.length === 1 && this.hc) {
        this.a.reveal(focused[0], 0.5);
      }
    }
  }
  hasFocus() {
    return $Nj(this.ab);
  }
  getFocus() {
    return this.a.getFocus();
  }
  focusNext() {
    this.a.focusNext();
  }
  focusLast() {
    this.a.focusLast();
  }
  getContext(respectMultiSelection) {
    const focusedItems = this.a.getFocusedPart() === 1 ? this.a.getStickyScrollFocus() : this.a.getFocus();
    return $Cwb(focusedItems, this.a.getSelection(), respectMultiSelection, this.t);
  }
  isItemVisible(item) {
    if (!this.b) {
      return false;
    }
    return this.b.filter(
      item,
      1
      /* TreeVisibility.Visible */
    );
  }
  isItemCollapsed(item) {
    return this.a.isCollapsed(item);
  }
  async setEditable(stat, isEditing) {
    if (isEditing) {
      this.fc = this.a.options.horizontalScrolling;
      if (this.fc) {
        this.a.updateOptions({ horizontalScrolling: false });
      }
      await this.a.expand(stat.parent);
    } else {
      if (this.fc !== void 0) {
        this.a.updateOptions({ horizontalScrolling: this.fc });
      }
      this.fc = void 0;
      this.L.classList.remove("highlight");
    }
    await this.refresh(false, stat.parent, false);
    if (isEditing) {
      this.L.classList.add("highlight");
      this.a.reveal(stat);
    } else {
      this.a.domFocus();
    }
  }
  async Cc(reveal = this.hc) {
    if (this.hc) {
      const activeFile = $mL.getCanonicalUri(this.mc.activeEditor, { supportSideBySide: SideBySideEditor.PRIMARY });
      if (activeFile) {
        const focus = this.a.getFocus();
        const selection = this.a.getSelection();
        if (focus.length === 1 && this.vc.extUri.isEqual(focus[0].resource, activeFile) && selection.length === 1 && this.vc.extUri.isEqual(selection[0].resource, activeFile)) {
          return;
        }
        return this.rc.select(activeFile, reveal);
      }
    }
  }
  Dc(container2) {
    this.b = this.Db.createInstance($kwb);
    this.B(this.b);
    this.B(this.b.onDidChange(() => this.refresh(true)));
    const explorerLabels = this.Db.createInstance($lsb, { onDidChangeVisibility: this.onDidChangeBodyVisibility });
    this.B(explorerLabels);
    this.c = this.Db.createInstance($hwb, this.b, () => this.a);
    const updateWidth = (stat) => this.a.updateWidth(stat);
    this.t = this.Db.createInstance($jwb, container2, explorerLabels, this.c.highlightTree, updateWidth);
    this.B(this.t);
    this.B($Ewb(container2, this.Fb));
    const isCompressionEnabled = () => this.Ab.getValue("explorer.compactFolders");
    const getFileNestingSettings = (item) => this.Ab.getValue({ resource: item?.root.resource }).explorer.fileNesting;
    this.a = this.Db.createInstance($5eb, "FileExplorer", container2, new $dwb(), new $owb(), [this.t], this.Db.createInstance($fwb, this.b, this.c), {
      compressionEnabled: isCompressionEnabled(),
      accessibilityProvider: this.t,
      identityProvider,
      keyboardNavigationLabelProvider: {
        getKeyboardNavigationLabel: (stat) => {
          if (this.rc.isEditable(stat)) {
            return void 0;
          }
          return stat.name;
        },
        getCompressedNodeKeyboardNavigationLabel: (stats) => {
          if (stats.some((stat) => this.rc.isEditable(stat))) {
            return void 0;
          }
          return stats.map((stat) => stat.name).join("/");
        }
      },
      multipleSelectionSupport: true,
      filter: this.b,
      sorter: this.Db.createInstance($lwb),
      dnd: this.Db.createInstance($mwb, (item) => this.isItemCollapsed(item)),
      collapseByDefault: (e) => {
        if (e instanceof $ivb) {
          if (e.hasNests && getFileNestingSettings(e).expand) {
            return false;
          }
          if (this.c.isShowingFilterResults()) {
            return false;
          }
        }
        return true;
      },
      autoExpandSingleChildren: true,
      expandOnlyOnTwistieClick: (e) => {
        if (e instanceof $ivb) {
          if (e.hasNests) {
            return true;
          } else if (this.Ab.getValue("workbench.tree.expandMode") === "doubleClick") {
            return true;
          }
        }
        return false;
      },
      paddingBottom: $dwb.ITEM_HEIGHT,
      overrideStyles: this.Xb().listOverrideStyles,
      findProvider: this.c
    });
    this.B(this.a);
    this.B(this.Fb.onDidColorThemeChange(() => this.a.rerender()));
    const onDidChangeCompressionConfiguration = Event2.filter(this.Ab.onDidChangeConfiguration, (e) => e.affectsConfiguration("explorer.compactFolders"));
    this.B(onDidChangeCompressionConfiguration((_) => this.a.updateOptions({ compressionEnabled: isCompressionEnabled() })));
    $ctb.bindTo(this.a.contextKeyService);
    $etb.bindTo(this.a.contextKeyService);
    this.B(this.a.onDidChangeFocus((e) => this.Ic(e.elements)));
    this.Ic([]);
    this.B(this.a.onDidOpen(async (e) => {
      const element = e.element;
      if (!element) {
        return;
      }
      const shiftDown = $4j(e.browserEvent) && e.browserEvent.shiftKey;
      if (!shiftDown) {
        if (element.isDirectory || this.rc.isEditable(void 0)) {
          return;
        }
        this.Gb.publicLog2("workbenchActionExecuted", { id: "workbench.files.openFile", from: "explorer" });
        try {
          this.jc?.willOpenElement(e.browserEvent);
          await this.mc.openEditor({ resource: element.resource, options: { preserveFocus: e.editorOptions.preserveFocus, pinned: e.editorOptions.pinned, source: EditorOpenSource.USER } }, e.sideBySide ? $oJ : $nJ);
        } finally {
          this.jc?.didOpenElement();
        }
      }
    }));
    this.B(this.a.onContextMenu((e) => this.Hc(e)));
    this.B(this.a.onDidScroll(async (e) => {
      const editable = this.rc.getEditable();
      if (e.scrollTopChanged && editable && this.a.getRelativeTop(editable.stat) === null) {
        await editable.data.onFinish("", false);
      }
    }));
    this.B(this.a.onDidChangeCollapseState((e) => {
      const element = e.node.element?.element;
      if (element) {
        const navigationControllers = this.t.getCompressedNavigationController(element instanceof Array ? element[0] : element);
        navigationControllers?.forEach((controller) => controller.updateCollapsed(e.node.collapsed));
      }
      this.Kc();
    }));
    this.Kc();
    this.B(this.a.onMouseDblClick((e) => {
      const scrollingByPage = this.Ab.getValue("workbench.list.scrollByPage");
      if (e.element === null && !scrollingByPage) {
        this.wc.executeCommand($tvb);
      }
    }));
    this.B(this.sc.onWillSaveState(() => {
      this.Fc();
    }));
  }
  // React on events
  Ec(event) {
    if (!event || event.affectsConfiguration("explorer.autoReveal")) {
      const configuration2 = this.Ab.getValue();
      this.hc = configuration2?.explorer?.autoReveal;
    }
    if (event && (event.affectsConfiguration("explorer.decorations.colors") || event.affectsConfiguration("explorer.decorations.badges"))) {
      this.refresh(true);
    }
  }
  Fc() {
    this.sc.store(
      $Dwb_1.TREE_VIEW_STATE_STORAGE_KEY,
      JSON.stringify(this.a.getViewState()),
      1,
      1
      /* StorageTarget.MACHINE */
    );
  }
  Gc(stat) {
    const folders = this.kc.getWorkspace().folders;
    const resource = stat ? stat.resource : folders[folders.length - 1].uri;
    stat = stat || this.rc.findClosest(resource);
    this.f.set(resource);
    this.g.set(!!stat && stat.isDirectory);
    this.j.set(!!stat && !!stat.isReadonly);
    this.h.set(Boolean(stat?.parent?.isReadonly));
    this.n.set(!!stat && stat.isRoot);
    if (resource) {
      const overrides = resource ? this.nc.getEditors(resource).map((editor) => editor.id) : [];
      this.m.set(overrides.join(","));
    } else {
      this.m.reset();
    }
  }
  async Hc(e) {
    if ($Fk(e.browserEvent.target)) {
      return;
    }
    const stat = e.element;
    let anchor = e.anchor;
    if ($Uj(anchor)) {
      if (stat) {
        const controllers = this.t.getCompressedNavigationController(stat);
        if (controllers && controllers.length > 0) {
          if ($4j(e.browserEvent) || $nwb(e.browserEvent.target)) {
            anchor = controllers[0].labels[controllers[0].index];
          } else {
            controllers.forEach((controller) => controller.last());
          }
        }
      }
    }
    this.xc.set(await this.tc.hasResources());
    this.Gc(stat);
    const selection = this.a.getSelection();
    const roots = this.rc.roots;
    let arg;
    if (stat instanceof $ivb) {
      const compressedControllers = this.t.getCompressedNavigationController(stat);
      arg = compressedControllers && compressedControllers.length ? compressedControllers[0].current.resource : stat.resource;
    } else {
      arg = roots.length === 1 ? roots[0].resource : {};
    }
    this.zb.showContextMenu({
      menuId: $bJ.ExplorerContext,
      menuActionOptions: { arg, shouldForwardArgs: true },
      contextKeyService: this.a.contextKeyService,
      getAnchor: () => anchor,
      onHide: (wasCancelled) => {
        if (wasCancelled) {
          this.a.domFocus();
        }
      },
      getActionsContext: () => stat && selection && selection.indexOf(stat) >= 0 ? selection.map((fs) => fs.resource) : stat instanceof $ivb ? [stat.resource] : []
    });
  }
  Ic(elements) {
    const stat = elements && elements.length ? elements[0] : void 0;
    this.Gc(stat);
    if (stat) {
      const enableTrash = Boolean(this.Ab.getValue().files?.enableTrash);
      const hasCapability = this.uc.hasCapability(
        stat.resource,
        4096
        /* FileSystemProviderCapabilities.Trash */
      );
      this.r.set(enableTrash && hasCapability);
    } else {
      this.r.reset();
    }
    const compressedNavigationControllers = stat && this.t.getCompressedNavigationController(stat);
    if (!compressedNavigationControllers) {
      this.sb.set(false);
      return;
    }
    this.sb.set(true);
    compressedNavigationControllers.forEach((controller) => {
      this.Jc(controller);
    });
  }
  // General methods
  /**
   * Refresh the contents of the explorer to get up to date data from the disk about the file structure.
   * If the item is passed we refresh only that level of the tree, otherwise we do a full refresh.
   */
  refresh(recursive, item, cancelEditing = true) {
    if (!this.a || !this.isBodyVisible() || item && !this.a.hasNode(item) || this.c?.isShowingFilterResults() && recursive) {
      return Promise.resolve(void 0);
    }
    if (cancelEditing && this.rc.isEditable(void 0)) {
      this.a.domFocus();
    }
    const toRefresh = item || this.a.getInput();
    return this.a.updateChildren(toRefresh, recursive, !!item);
  }
  getOptimalWidth() {
    const parentNode = this.a.getHTMLElement();
    const childNodes = [].slice.call(parentNode.querySelectorAll(".explorer-item .label-name"));
    return $Cj(parentNode, childNodes);
  }
  async setTreeInput() {
    if (!this.isBodyVisible()) {
      return Promise.resolve(void 0);
    }
    if (this.ec) {
      await this.ec;
    }
    const initialInputSetup = !this.a.getInput();
    if (initialInputSetup) {
      $S("code/willResolveExplorer");
    }
    const roots = this.rc.roots;
    let input = roots[0];
    if (this.kc.getWorkbenchState() !== 2 || roots[0].error) {
      input = roots;
    }
    let viewState;
    if (this.a && this.a.getInput()) {
      viewState = this.a.getViewState();
    } else {
      const rawViewState = this.sc.get(
        $Dwb_1.TREE_VIEW_STATE_STORAGE_KEY,
        1
        /* StorageScope.WORKSPACE */
      );
      if (rawViewState) {
        viewState = JSON.parse(rawViewState);
      }
    }
    const previousInput = this.a.getInput();
    const promise = this.ec = this.a.setInput(input, viewState).then(async () => {
      if (Array.isArray(input)) {
        if (!viewState || previousInput instanceof $ivb) {
          for (let i2 = 0; i2 < Math.min(input.length, 5); i2++) {
            try {
              await this.a.expand(input[i2]);
            } catch (e) {
            }
          }
        }
        if (!previousInput && input.length === 1 && this.Ab.getValue().explorer.expandSingleFolderWorkspaces) {
          await this.a.expand(input[0]).catch(() => {
          });
        }
        if (Array.isArray(previousInput)) {
          const previousRoots = new $Ec();
          previousInput.forEach((previousRoot) => previousRoots.set(previousRoot.resource, true));
          await Promise.all(input.map(async (item) => {
            if (!previousRoots.has(item.resource)) {
              try {
                await this.a.expand(item);
              } catch (e) {
              }
            }
          }));
        }
      }
      if (initialInputSetup) {
        $S("code/didResolveExplorer");
      }
    });
    this.lc.withProgress({
      location: 1,
      delay: this.oc.isRestored() ? 800 : 1500
      // reduce progress visibility when still restoring
    }, (_progress) => promise);
    await promise;
    if (!this.ic) {
      this.ic = new $qwb(this.rc, this.kc);
      this.B(this.pc.registerDecorationsProvider(this.ic));
    }
  }
  async selectResource(resource, reveal = this.hc, retry = 0) {
    if (retry === 2) {
      return;
    }
    if (!resource || !this.isBodyVisible()) {
      return;
    }
    if (this.ec) {
      await this.ec;
    }
    let item = this.rc.findClosestRoot(resource);
    while (item && item.resource.toString() !== resource.toString()) {
      try {
        await this.a.expand(item);
      } catch (e) {
        return this.selectResource(resource, reveal, retry + 1);
      }
      if (!item.children.size) {
        item = null;
      } else {
        for (const child of item.children.values()) {
          if (this.vc.extUri.isEqualOrParent(resource, child.resource)) {
            item = child;
            break;
          }
          item = null;
        }
      }
    }
    if (item) {
      if (item === this.a.getInput()) {
        this.a.setFocus([]);
        this.a.setSelection([]);
        return;
      }
      try {
        if (item.nestedParent) {
          await this.a.expand(item.nestedParent);
        }
        if ((reveal === true || reveal === "force") && this.a.getRelativeTop(item) === null) {
          this.a.reveal(item, 0.5);
        }
        this.a.setFocus([item]);
        this.a.setSelection([item]);
      } catch (e) {
        return this.selectResource(resource, reveal, retry + 1);
      }
    }
  }
  itemsCopied(stats, cut, previousCut) {
    this.xc.set(stats.length > 0);
    this.yc.set(cut && stats.length > 0);
    previousCut?.forEach((item) => this.a.rerender(item));
    if (cut) {
      stats.forEach((s) => this.a.rerender(s));
    }
  }
  expandAll() {
    if (this.rc.isEditable(void 0)) {
      this.a.domFocus();
    }
    this.a.expandAll();
  }
  collapseAll() {
    if (this.rc.isEditable(void 0)) {
      this.a.domFocus();
    }
    const treeInput = this.a.getInput();
    if (Array.isArray(treeInput)) {
      if (hasExpandedRootChild(this.a, treeInput)) {
        treeInput.forEach((folder) => {
          folder.children.forEach((child) => this.a.hasNode(child) && this.a.collapse(child, true));
        });
        return;
      }
    }
    this.a.collapseAll();
  }
  previousCompressedStat() {
    const focused = this.a.getFocus();
    if (!focused.length) {
      return;
    }
    const compressedNavigationControllers = this.t.getCompressedNavigationController(focused[0]);
    compressedNavigationControllers.forEach((controller) => {
      controller.previous();
      this.Jc(controller);
    });
  }
  nextCompressedStat() {
    const focused = this.a.getFocus();
    if (!focused.length) {
      return;
    }
    const compressedNavigationControllers = this.t.getCompressedNavigationController(focused[0]);
    compressedNavigationControllers.forEach((controller) => {
      controller.next();
      this.Jc(controller);
    });
  }
  firstCompressedStat() {
    const focused = this.a.getFocus();
    if (!focused.length) {
      return;
    }
    const compressedNavigationControllers = this.t.getCompressedNavigationController(focused[0]);
    compressedNavigationControllers.forEach((controller) => {
      controller.first();
      this.Jc(controller);
    });
  }
  lastCompressedStat() {
    const focused = this.a.getFocus();
    if (!focused.length) {
      return;
    }
    const compressedNavigationControllers = this.t.getCompressedNavigationController(focused[0]);
    compressedNavigationControllers.forEach((controller) => {
      controller.last();
      this.Jc(controller);
    });
  }
  Jc(controller) {
    this.ac.set(controller.index === 0);
    this.bc.set(controller.index === controller.count - 1);
  }
  Kc() {
    const treeInput = this.a.getInput();
    if (treeInput === void 0) {
      return;
    }
    const treeInputArray = Array.isArray(treeInput) ? treeInput : Array.from(treeInput.children.values());
    this.cc.set(hasExpandedNode(this.a, treeInputArray));
    this.Fc();
  }
  hasPhantomElements() {
    return this.c.isShowingFilterResults();
  }
  dispose() {
    this.gc?.dispose();
    super.dispose();
  }
};
__decorate([
  $0t
], $Dwb.prototype, "xc", null);
__decorate([
  $0t
], $Dwb.prototype, "yc", null);
$Dwb = $Dwb_1 = __decorate([
  __param(1, $50),
  __param(2, $$M),
  __param(3, $Pk),
  __param(4, $Zk),
  __param(5, $TJ),
  __param(6, $mJ),
  __param(7, $4L),
  __param(8, $Vlb),
  __param(9, $Ty),
  __param(10, $on),
  __param(11, $kl),
  __param(12, $jsb),
  __param(13, $ZI),
  __param(14, $gs),
  __param(15, $zv),
  __param(16, $5$),
  __param(17, $kvb),
  __param(18, $jv),
  __param(19, $30),
  __param(20, $km),
  __param(21, $vl),
  __param(22, $sn),
  __param(23, $O4)
], $Dwb);
function $Ewb(container2, themeService) {
  container2.classList.add("file-icon-themable-tree");
  container2.classList.add("show-file-icons");
  const onDidChangeFileIconTheme = (theme) => {
    container2.classList.toggle("align-icons-and-twisties", theme.hasFileIcons && !theme.hasFolderIcons);
    container2.classList.toggle("hide-arrows", theme.hidesExplorerArrows === true);
  };
  onDidChangeFileIconTheme(themeService.getFileIconTheme());
  return themeService.onDidFileIconThemeChange(onDidChangeFileIconTheme);
}
var CanCreateContext = $7m.or(
  // Folder: can create unless readonly
  $7m.and($7sb, $9sb),
  // File: can create unless parent is readonly
  $7m.and($7sb.toNegated(), $0sb.toNegated())
);
$hJ(class extends $gJ {
  constructor() {
    super({
      id: "workbench.files.action.createFileFromExplorer",
      title: localize(7375, null),
      f1: false,
      icon: $6l.newFile,
      precondition: CanCreateContext,
      menu: {
        id: $bJ.ViewTitle,
        group: "navigation",
        when: $7m.equals("view", $4sb),
        order: 10
      }
    });
  }
  run(accessor) {
    const commandService = accessor.get($sn);
    commandService.executeCommand($tvb);
  }
});
$hJ(class extends $gJ {
  constructor() {
    super({
      id: "workbench.files.action.createFolderFromExplorer",
      title: localize(7376, null),
      f1: false,
      icon: $6l.newFolder,
      precondition: CanCreateContext,
      menu: {
        id: $bJ.ViewTitle,
        group: "navigation",
        when: $7m.equals("view", $4sb),
        order: 20
      }
    });
  }
  run(accessor) {
    const commandService = accessor.get($sn);
    commandService.executeCommand($vvb);
  }
});
$hJ(class extends $gJ {
  constructor() {
    super({
      id: "workbench.files.action.refreshFilesExplorer",
      title: localize2(7377, "Refresh Explorer"),
      f1: true,
      icon: $6l.refresh,
      menu: {
        id: $bJ.ViewTitle,
        group: "navigation",
        when: $7m.equals("view", $4sb),
        order: 30
      },
      metadata: {
        description: localize2(7378, "Forces a refresh of the Explorer.")
      },
      precondition: $ftb.negate()
    });
  }
  async run(accessor) {
    const viewsService = accessor.get($uob);
    const explorerService = accessor.get($kvb);
    await viewsService.openView($4sb);
    await explorerService.refresh();
  }
});
$hJ(class extends $gJ {
  constructor() {
    super({
      id: "workbench.files.action.collapseExplorerFolders",
      title: localize2(7379, "Collapse Folders in Explorer"),
      f1: true,
      icon: $6l.collapseAll,
      menu: {
        id: $bJ.ViewTitle,
        group: "navigation",
        when: $7m.equals("view", $4sb),
        order: 40
      },
      metadata: {
        description: localize2(7380, "Folds all folders in the Explorer.")
      }
    });
  }
  run(accessor) {
    const viewsService = accessor.get($uob);
    const view = viewsService.getViewWithId($4sb);
    if (view !== null) {
      const explorerView = view;
      explorerView.collapseAll();
    }
  }
});

// out-build/vs/workbench/contrib/chat/browser/chatContentParts/chatCollections.js
var $WMb = class extends $3c {
  get inUse() {
    return this.b;
  }
  constructor(c) {
    super();
    this.c = c;
    this.a = [];
    this.b = /* @__PURE__ */ new Set();
  }
  get() {
    if (this.a.length > 0) {
      const item2 = this.a.pop();
      this.b.add(item2);
      return item2;
    }
    const item = this.B(this.c());
    this.b.add(item);
    return item;
  }
  release(item) {
    this.b.delete(item);
    this.a.push(item);
  }
};

// out-build/vs/workbench/contrib/chat/browser/chatContentParts/chatReferencesContentPart.js
var CollapsibleListRenderer_1;
var $73 = $;
var $2Mb = class $2Mb2 extends $3c {
  constructor(c, labelOverride, context, contentReferencesListPool, openerService, menuService, f, g) {
    super();
    this.c = c;
    this.f = f;
    this.g = g;
    this.a = this.B(new $ze());
    this.onDidChangeHeight = this.a.event;
    const element = context.element;
    this.b = context.contentIndex + 1 < context.content.length;
    const referencesLabel = labelOverride ?? (c.length > 1 ? localize(4808, null, c.length) : localize(4809, null, 1));
    const iconElement = $73(".chat-used-context-icon");
    const icon2 = (element2) => element2.usedReferencesExpanded ? $6l.chevronDown : $6l.chevronRight;
    iconElement.classList.add(...ThemeIcon.asClassNameArray(icon2(element)));
    const buttonElement = $73(".chat-used-context-label", void 0);
    const collapseButton = this.B(new $k2(buttonElement, {
      buttonBackground: void 0,
      buttonBorder: void 0,
      buttonForeground: void 0,
      buttonHoverBackground: void 0,
      buttonSecondaryBackground: void 0,
      buttonSecondaryForeground: void 0,
      buttonSecondaryHoverBackground: void 0,
      buttonSeparator: void 0
    }));
    this.domNode = $73(".chat-used-context", void 0, buttonElement);
    collapseButton.label = referencesLabel;
    collapseButton.element.prepend(iconElement);
    this.h(collapseButton.element, referencesLabel, element.usedReferencesExpanded);
    this.domNode.classList.toggle("chat-used-context-collapsed", !element.usedReferencesExpanded);
    this.B(collapseButton.onDidClick(() => {
      iconElement.classList.remove(...ThemeIcon.asClassNameArray(icon2(element)));
      element.usedReferencesExpanded = !element.usedReferencesExpanded;
      iconElement.classList.add(...ThemeIcon.asClassNameArray(icon2(element)));
      this.domNode.classList.toggle("chat-used-context-collapsed", !element.usedReferencesExpanded);
      this.a.fire();
      this.h(collapseButton.element, referencesLabel, element.usedReferencesExpanded);
    }));
    const ref = this.B(contentReferencesListPool.get());
    const list2 = ref.object;
    this.domNode.appendChild(list2.getHTMLElement().parentElement);
    this.B(list2.onDidOpen((e) => {
      if (e.element && "reference" in e.element && typeof e.element.reference === "object") {
        const uriOrLocation = "variableName" in e.element.reference ? e.element.reference.value : e.element.reference;
        const uri = URI.isUri(uriOrLocation) ? uriOrLocation : uriOrLocation?.uri;
        if (uri) {
          openerService.open(uri, {
            fromUserGesture: true,
            editorOptions: {
              ...e.editorOptions,
              ...{
                selection: uriOrLocation && "range" in uriOrLocation ? uriOrLocation.range : void 0
              }
            }
          });
        }
      }
    }));
    this.B(list2.onContextMenu((e) => {
      $9j.stop(e.browserEvent, true);
      const uri = e.element && getResourceForElement(e.element);
      if (!uri) {
        return;
      }
      this.g.showContextMenu({
        getAnchor: () => e.anchor,
        getActions: () => {
          const menu = menuService.getMenuActions($bJ.ChatAttachmentsContext, list2.contextKeyService, { shouldForwardArgs: true, arg: uri });
          return $P$(menu);
        }
      });
    }));
    const resourceContextKey = this.B(this.f.createInstance($lqb));
    this.B(list2.onDidChangeFocus((e) => {
      resourceContextKey.reset();
      const element2 = e.elements.length ? e.elements[0] : void 0;
      const uri = element2 && getResourceForElement(element2);
      resourceContextKey.set(uri ?? null);
    }));
    const maxItemsShown = 6;
    const itemsShown = Math.min(c.length, maxItemsShown);
    const height = itemsShown * 22;
    list2.layout(height);
    list2.getHTMLElement().style.height = `${height}px`;
    list2.splice(0, list2.length, c);
  }
  hasSameContent(other, followingContent, element) {
    return other.kind === "references" && other.references.length === this.c.length && !!followingContent.length === this.b;
  }
  h(element, label3, expanded2) {
    element.ariaLabel = expanded2 ? localize(4810, null, label3) : localize(4811, null, label3);
  }
  addDisposable(disposable) {
    this.B(disposable);
  }
};
$2Mb = __decorate([
  __param(4, $O4),
  __param(5, $cJ),
  __param(6, $Pk),
  __param(7, $50)
], $2Mb);
var $3Mb = class $3Mb2 extends $3c {
  get inUse() {
    return this.a.inUse;
  }
  constructor(b, c, f, g, h3) {
    super();
    this.b = b;
    this.c = c;
    this.f = f;
    this.g = g;
    this.h = h3;
    this.a = this.B(new $WMb(() => this.j()));
  }
  j() {
    const resourceLabels = this.B(this.f.createInstance($lsb, { onDidChangeVisibility: this.b }));
    const container2 = $73(".chat-used-context-list");
    this.B($Ewb(container2, this.g));
    const list2 = this.f.createInstance($Web, "ChatListRenderer", container2, new CollapsibleListDelegate(), [this.f.createInstance(CollapsibleListRenderer, resourceLabels, this.c)], {
      alwaysConsumeMouseWheel: false,
      accessibilityProvider: {
        getAriaLabel: (element) => {
          if (element.kind === "warning") {
            return element.content.value;
          }
          const reference = element.reference;
          if (typeof reference === "string") {
            return reference;
          } else if ("variableName" in reference) {
            return reference.variableName;
          } else if (URI.isUri(reference)) {
            return $rc(reference.path);
          } else {
            return $rc(reference.uri.path);
          }
        },
        getWidgetAriaLabel: () => localize(4812, null)
      },
      dnd: {
        getDragURI: (element) => getResourceForElement(element)?.toString() ?? null,
        getDragLabel: (elements, originalEvent) => {
          const uris = $Mb(elements.map(getResourceForElement));
          if (!uris.length) {
            return void 0;
          } else if (uris.length === 1) {
            return this.h.getUriLabel(uris[0], { relative: true });
          } else {
            return `${uris.length}`;
          }
        },
        dispose: () => {
        },
        onDragOver: () => false,
        drop: () => {
        },
        onDragStart: (data, originalEvent) => {
          try {
            const elements = data.getData();
            const uris = $Mb(elements.map(getResourceForElement));
            this.f.invokeFunction((accessor) => $Eob(accessor, uris, originalEvent));
          } catch {
          }
        }
      }
    });
    return list2;
  }
  get() {
    const object = this.a.get();
    let stale = false;
    return {
      object,
      isStale: () => stale,
      dispose: () => {
        stale = true;
        this.a.release(object);
      }
    };
  }
};
$3Mb = __decorate([
  __param(2, $Pk),
  __param(3, $gs),
  __param(4, $ZI)
], $3Mb);
var CollapsibleListDelegate = class {
  getHeight(element) {
    return 22;
  }
  getTemplateId(element) {
    return CollapsibleListRenderer.TEMPLATE_ID;
  }
};
var CollapsibleListRenderer = class CollapsibleListRenderer2 {
  static {
    CollapsibleListRenderer_1 = this;
  }
  static {
    this.TEMPLATE_ID = "chatCollapsibleListRenderer";
  }
  constructor(a, b, c, d, f, g, h3) {
    this.a = a;
    this.b = b;
    this.c = c;
    this.d = d;
    this.f = f;
    this.g = g;
    this.h = h3;
    this.templateId = CollapsibleListRenderer_1.TEMPLATE_ID;
  }
  renderTemplate(container2) {
    const templateDisposables = new $2c();
    const label3 = templateDisposables.add(this.a.create(container2, { supportHighlights: true, supportIcons: true }));
    let toolbar;
    let actionBarContainer;
    let contextKeyService;
    if (this.b) {
      actionBarContainer = $73(".chat-collapsible-list-action-bar");
      contextKeyService = templateDisposables.add(this.h.createScoped(actionBarContainer));
      const scopedInstantiationService = templateDisposables.add(this.g.createChild(new $Ok([$on, contextKeyService])));
      toolbar = templateDisposables.add(scopedInstantiationService.createInstance($4$, actionBarContainer, this.b, { menuOptions: { shouldForwardArgs: true, arg: void 0 } }));
      label3.element.appendChild(actionBarContainer);
    }
    return { templateDisposables, label: label3, toolbar, actionBarContainer, contextKeyService };
  }
  i(data) {
    if (ThemeIcon.isThemeIcon(data.iconPath)) {
      return data.iconPath;
    } else {
      return this.c.getColorTheme().type === ColorScheme2.DARK && data.iconPath?.dark ? data.iconPath?.dark : data.iconPath?.light;
    }
  }
  renderElement(data, index, templateData, height) {
    if (data.kind === "warning") {
      templateData.label.setResource({ name: data.content.value }, { icon: $6l.warning });
      return;
    }
    const reference = data.reference;
    const icon2 = this.i(data);
    templateData.label.element.style.display = "flex";
    let arg;
    if (typeof reference === "object" && "variableName" in reference) {
      if (reference.value) {
        const uri = URI.isUri(reference.value) ? reference.value : reference.value.uri;
        templateData.label.setResource({
          resource: uri,
          name: $rh(uri),
          description: `#${reference.variableName}`,
          range: "range" in reference.value ? reference.value.range : void 0
        }, { icon: icon2, title: data.options?.status?.description ?? data.title });
      } else if (reference.variableName.startsWith("kernelVariable")) {
        const variable = reference.variableName.split(":")[1];
        const asVariableName = `${variable}`;
        const label3 = `Kernel variable`;
        templateData.label.setLabel(label3, asVariableName, { title: data.options?.status?.description });
      } else {
        const variable = this.d.getVariable(reference.variableName);
        const asThemeIcon = variable?.icon ? `$(${variable.icon.id}) ` : "";
        const asVariableName = `#${reference.variableName}`;
        const label3 = `${asThemeIcon}${variable?.fullName ?? asVariableName}`;
        templateData.label.setLabel(label3, asVariableName, { title: data.options?.status?.description ?? variable?.description });
      }
    } else if (typeof reference === "string") {
      templateData.label.setLabel(reference, void 0, { iconPath: URI.isUri(icon2) ? icon2 : void 0, title: data.options?.status?.description ?? data.title });
    } else {
      const uri = "uri" in reference ? reference.uri : reference;
      arg = uri;
      const extraClasses = data.excluded ? ["excluded"] : [];
      if (uri.scheme === "https" && $Ah(uri.authority, "github.com") && uri.path.includes("/tree/")) {
        const label3 = uri.path.split("/").slice(1, 3).join("/");
        const description = uri.path.split("/").slice(5).join("/");
        templateData.label.setResource({ resource: uri, name: label3, description }, { icon: $6l.github, title: data.title, strikethrough: data.excluded, extraClasses });
      } else if (uri.scheme === this.f.urlProtocol && $Ah(uri.authority, $YK)) {
        const settingId = uri.path.substring(1);
        templateData.label.setResource({ resource: uri, name: settingId }, { icon: $6l.settingsGear, title: localize(4813, null, settingId), strikethrough: data.excluded, extraClasses });
      } else if ($$g(uri, Schemas.mailto, Schemas.http, Schemas.https)) {
        templateData.label.setResource({ resource: uri, name: uri.toString() }, { icon: icon2 ?? $6l.globe, title: data.options?.status?.description ?? data.title ?? uri.toString(), strikethrough: data.excluded, extraClasses });
      } else {
        if (data.state === 3 || data.state === 6) {
          templateData.label.setResource({
            resource: uri,
            name: $rh(uri),
            description: data.description ?? localize(4814, null),
            range: "range" in reference ? reference.range : void 0
          }, { icon: icon2, title: data.options?.status?.description ?? data.title, italic: data.state === 6, strikethrough: data.excluded, extraClasses });
        } else {
          templateData.label.setFile(uri, {
            fileKind: FileKind.FILE,
            // Should not have this live-updating data on a historical reference
            fileDecorations: void 0,
            range: "range" in reference ? reference.range : void 0,
            title: data.options?.status?.description ?? data.title,
            strikethrough: data.excluded,
            extraClasses
          });
        }
      }
    }
    for (const selector of [".monaco-icon-suffix-container", ".monaco-icon-name-container"]) {
      const element = templateData.label.element.querySelector(selector);
      if (element) {
        if (data.options?.status?.kind === ChatResponseReferencePartStatusKind2.Omitted || data.options?.status?.kind === ChatResponseReferencePartStatusKind2.Partial) {
          element.classList.add("warning");
        } else {
          element.classList.remove("warning");
        }
      }
    }
    if (data.state !== void 0) {
      if (templateData.actionBarContainer) {
        if (data.state === 0 && !templateData.actionBarContainer.classList.contains("modified")) {
          templateData.actionBarContainer.classList.add("modified");
          templateData.label.element.querySelector(".monaco-icon-name-container")?.classList.add("modified");
        } else if (data.state !== 0) {
          templateData.actionBarContainer.classList.remove("modified");
          templateData.label.element.querySelector(".monaco-icon-name-container")?.classList.remove("modified");
        }
      }
      if (templateData.toolbar) {
        templateData.toolbar.context = arg;
      }
      if (templateData.contextKeyService && data.state !== void 0) {
        $aP.bindTo(templateData.contextKeyService).set(data.state);
      }
    }
  }
  disposeTemplate(templateData) {
    templateData.templateDisposables.dispose();
  }
};
CollapsibleListRenderer = CollapsibleListRenderer_1 = __decorate([
  __param(2, $gs),
  __param(3, $kO),
  __param(4, $Vu),
  __param(5, $Pk),
  __param(6, $on)
], CollapsibleListRenderer);
function getResourceForElement(element) {
  if (element.kind === "warning") {
    return null;
  }
  const { reference } = element;
  if (typeof reference === "string" || "variableName" in reference) {
    return null;
  } else if (URI.isUri(reference)) {
    return reference;
  } else {
    return reference.uri;
  }
}
$hJ(class AddToChatAction extends $gJ {
  static {
    this.id = "workbench.action.chat.addToChatAction";
  }
  constructor() {
    super({
      id: AddToChatAction.id,
      title: {
        ...localize2(4815, "Add File to Chat")
      },
      f1: false,
      menu: [{
        id: $bJ.ChatAttachmentsContext,
        group: "chat",
        order: 1,
        when: $7sb.negate()
      }]
    });
  }
  async run(accessor, resource) {
    const chatWidgetService = accessor.get($2Nb);
    const variablesService = accessor.get($kO);
    if (!resource) {
      return;
    }
    const widget = chatWidgetService.lastFocusedWidget;
    if (!widget) {
      return;
    }
    variablesService.attachContext("file", resource, widget.location);
  }
});

// out-build/vs/workbench/services/untitled/common/untitledTextEditorInput.js
var $0Gb_1;
var $0Gb = class $0Gb2 extends $5vb {
  static {
    $0Gb_1 = this;
  }
  static {
    this.ID = "workbench.editors.untitledEditorInput";
  }
  get typeId() {
    return $0Gb_1.ID;
  }
  get editorId() {
    return $1K.id;
  }
  constructor(X, textFileService, labelService, editorService, fileService, Y, Z, filesConfigurationService, $149, textResourceConfigurationService, customEditorLabelService) {
    super(X.resource, void 0, editorService, textFileService, labelService, fileService, filesConfigurationService, textResourceConfigurationService, customEditorLabelService);
    this.X = X;
    this.Y = Y;
    this.Z = Z;
    this.$ = $149;
    this.c = void 0;
    this.U = this.B(new $2c());
    this.W = void 0;
    this.ab(X);
    this.B(this.R.untitled.onDidCreate((model) => this.bb(model)));
  }
  ab(model) {
    this.U.clear();
    this.U.add(model.onDidChangeDirty(() => this.f.fire()));
    this.U.add(model.onDidChangeName(() => this.g.fire()));
    this.U.add(model.onDidRevert(() => this.dispose()));
  }
  bb(model) {
    if ($oh(model.resource, this.X.resource) && model !== this.X) {
      this.X = model;
      this.ab(model);
    }
  }
  getName() {
    return this.X.name;
  }
  getDescription(verbosity = 1) {
    if (!this.X.hasAssociatedFilePath) {
      const descriptionCandidate = this.resource.path;
      if (descriptionCandidate !== this.getName()) {
        return descriptionCandidate;
      }
      return void 0;
    }
    return super.getDescription(verbosity);
  }
  getTitle(verbosity) {
    if (!this.X.hasAssociatedFilePath) {
      const name = this.getName();
      const description = this.getDescription();
      if (description && description !== name) {
        return `${name} \u2022 ${description}`;
      }
      return name;
    }
    return super.getTitle(verbosity);
  }
  isDirty() {
    return this.X.isDirty();
  }
  getEncoding() {
    return this.X.getEncoding();
  }
  setEncoding(encoding, mode) {
    return this.X.setEncoding(encoding);
  }
  get hasLanguageSetExplicitly() {
    return this.X.hasLanguageSetExplicitly;
  }
  get hasAssociatedFilePath() {
    return this.X.hasAssociatedFilePath;
  }
  setLanguageId(languageId, source) {
    this.X.setLanguageId(languageId, source);
  }
  getLanguageId() {
    return this.X.getLanguageId();
  }
  async resolve() {
    if (!this.c) {
      this.c = (async () => {
        this.W = await this.$.createModelReference(this.resource);
      })();
    }
    await this.c;
    if (this.isDisposed()) {
      this.cb();
    }
    return this.X;
  }
  toUntyped(options3) {
    const untypedInput = {
      resource: this.X.hasAssociatedFilePath ? $Fh(this.X.resource, this.Y.remoteAuthority, this.Z.defaultUriScheme) : this.resource,
      forceUntitled: true,
      options: {
        override: this.editorId
      }
    };
    if (typeof options3?.preserveViewState === "number") {
      untypedInput.encoding = this.getEncoding();
      untypedInput.languageId = this.getLanguageId();
      untypedInput.contents = this.X.isModified() ? this.X.textEditorModel?.getValue() : void 0;
      untypedInput.options.viewState = $7K(this, options3.preserveViewState, this.Q);
      if (typeof untypedInput.contents === "string" && !this.X.hasAssociatedFilePath && !options3.preserveResource) {
        untypedInput.resource = void 0;
      }
    }
    return untypedInput;
  }
  matches(otherInput) {
    if (this === otherInput) {
      return true;
    }
    if (otherInput instanceof $0Gb_1) {
      return $oh(otherInput.resource, this.resource);
    }
    if ($_K(otherInput)) {
      return super.matches(otherInput);
    }
    return false;
  }
  dispose() {
    this.c = void 0;
    this.cb();
    super.dispose();
  }
  cb() {
    $Xc(this.W);
    this.W = void 0;
  }
};
$0Gb = $0Gb_1 = __decorate([
  __param(1, $cK),
  __param(2, $ZI),
  __param(3, $mJ),
  __param(4, $km),
  __param(5, $US),
  __param(6, $aT),
  __param(7, $4J),
  __param(8, $oG),
  __param(9, $zG),
  __param(10, $qrb)
], $0Gb);

// out-build/vs/workbench/contrib/chat/browser/chatDragAndDrop.js
var ChatDragAndDropType;
(function(ChatDragAndDropType2) {
  ChatDragAndDropType2[ChatDragAndDropType2["FILE_INTERNAL"] = 0] = "FILE_INTERNAL";
  ChatDragAndDropType2[ChatDragAndDropType2["FILE_EXTERNAL"] = 1] = "FILE_EXTERNAL";
  ChatDragAndDropType2[ChatDragAndDropType2["FOLDER"] = 2] = "FOLDER";
  ChatDragAndDropType2[ChatDragAndDropType2["IMAGE"] = 3] = "IMAGE";
  ChatDragAndDropType2[ChatDragAndDropType2["SYMBOL"] = 4] = "SYMBOL";
})(ChatDragAndDropType || (ChatDragAndDropType = {}));
var $ONb = class $ONb2 extends $ns {
  constructor(f, g, themeService, j, m, r2) {
    super(themeService);
    this.f = f;
    this.g = g;
    this.j = j;
    this.m = m;
    this.r = r2;
    this.a = /* @__PURE__ */ new Map();
    this.c = "";
    this.s = void 0;
    this.updateStyles();
  }
  addOverlay(target, overlayContainer) {
    this.removeOverlay(target);
    const { overlay, disposable } = this.t(target, overlayContainer);
    this.a.set(target, { overlay, disposable });
  }
  removeOverlay(target) {
    if (this.s === target) {
      this.s = void 0;
    }
    const existingOverlay = this.a.get(target);
    if (existingOverlay) {
      existingOverlay.overlay.remove();
      existingOverlay.disposable.dispose();
      this.a.delete(target);
    }
  }
  t(target, overlayContainer) {
    const overlay = document.createElement("div");
    overlay.classList.add("chat-dnd-overlay");
    this.U(overlay);
    overlayContainer.appendChild(overlay);
    const disposable = new $Ak(target, {
      onDragOver: (e) => {
        e.stopPropagation();
        e.preventDefault();
        if (target === this.s) {
          return;
        }
        if (this.s) {
          this.R(this.s, void 0);
        }
        this.s = target;
        this.u(e, target);
      },
      onDragLeave: (e) => {
        if (target === this.s) {
          this.s = void 0;
        }
        this.y(e, target);
      },
      onDrop: (e) => {
        e.stopPropagation();
        e.preventDefault();
        if (target !== this.s) {
          return;
        }
        this.s = void 0;
        this.C(e, target);
      }
    });
    return { overlay, disposable };
  }
  u(e, target) {
    const estimatedDropType = this.H(e);
    this.G(e, target, estimatedDropType);
  }
  y(e, target) {
    this.G(e, target, void 0);
  }
  C(e, target) {
    this.G(e, target, void 0);
    this.D(e);
  }
  async D(e) {
    const contexts = await this.M(e);
    if (contexts.length === 0) {
      return;
    }
    this.F(contexts);
  }
  F(contexts) {
    this.f.addContext(...contexts);
  }
  G(e, target, dropType) {
    const showOverlay = dropType !== void 0;
    if (e.dataTransfer) {
      e.dataTransfer.dropEffect = showOverlay ? "copy" : "none";
    }
    this.R(target, dropType);
  }
  H(e) {
    if (this.L(e)) {
      return this.j.extensions.some((ext) => $zN(ext, "chatReferenceBinaryData")) ? ChatDragAndDropType.IMAGE : void 0;
    } else if ($z_(e, $u_.SYMBOLS)) {
      return ChatDragAndDropType.SYMBOL;
    } else if ($z_(e, $kZ.FILES)) {
      return ChatDragAndDropType.FILE_EXTERNAL;
    } else if ($z_(e, $kZ.INTERNAL_URI_LIST)) {
      return ChatDragAndDropType.FILE_INTERNAL;
    } else if ($z_(e, $YC.uriList, $u_.FILES)) {
      return ChatDragAndDropType.FOLDER;
    }
    return void 0;
  }
  I(e) {
    const dropType = this.H(e);
    return dropType !== void 0;
  }
  J(type) {
    switch (type) {
      case ChatDragAndDropType.FILE_INTERNAL:
        return localize(4821, null);
      case ChatDragAndDropType.FILE_EXTERNAL:
        return localize(4822, null);
      case ChatDragAndDropType.FOLDER:
        return localize(4823, null);
      case ChatDragAndDropType.IMAGE:
        return localize(4824, null);
      case ChatDragAndDropType.SYMBOL:
        return localize(4825, null);
    }
  }
  L(e) {
    if ($z_(e, "image")) {
      return true;
    }
    if ($z_(e, $kZ.FILES)) {
      const files = e.dataTransfer?.files;
      if (files && files.length > 0) {
        const file = files[0];
        return file.type.startsWith("image/");
      }
      const items = e.dataTransfer?.items;
      if (items && items.length > 0) {
        const item = items[0];
        return item.type.startsWith("image/");
      }
    }
    return false;
  }
  async M(e) {
    if (!this.I(e)) {
      return [];
    }
    if ($z_(e, $u_.SYMBOLS)) {
      const data2 = $C_(e);
      return this.Q(data2);
    }
    const data = $v_(e);
    return $Mb(await Promise.all(data.map((editorInput) => {
      return this.N(editorInput);
    })));
  }
  async N(editorInput) {
    const imageContext = getImageAttachContext(editorInput);
    if (imageContext) {
      return this.j.extensions.some((ext) => $zN(ext, "chatReferenceBinaryData")) ? imageContext : void 0;
    }
    return await this.O(editorInput);
  }
  async O(editor) {
    if ($_K(editor)) {
      return await this.P(editor);
    }
    if (!editor.resource) {
      return void 0;
    }
    let stat;
    try {
      stat = await this.m.stat(editor.resource);
    } catch {
      return void 0;
    }
    if (!stat.isDirectory && !stat.isFile) {
      return void 0;
    }
    return getResourceAttachContext(editor.resource, stat.isDirectory);
  }
  async P(editor) {
    if (editor.resource) {
      return getResourceAttachContext(editor.resource, false);
    }
    const openUntitledEditors = this.r.editors.filter((editor2) => editor2 instanceof $0Gb);
    for (const canidate of openUntitledEditors) {
      const model = await canidate.resolve();
      const contents = model.textEditorModel?.getValue();
      if (contents === editor.contents) {
        return getResourceAttachContext(canidate.resource, false);
      }
    }
    return void 0;
  }
  Q(symbols) {
    return symbols.map((symbol) => {
      const resource = URI.file(symbol.fsPath);
      return {
        kind: "symbol",
        id: symbolId(resource, symbol.range),
        value: { uri: resource, range: symbol.range },
        symbolKind: symbol.kind,
        fullName: `$(${SymbolKinds.toIcon(symbol.kind).id}) ${symbol.name}`,
        name: symbol.name,
        isDynamic: true
      };
    });
  }
  R(target, type) {
    this.b?.remove();
    this.b = void 0;
    const { overlay } = this.a.get(target);
    if (type !== void 0) {
      const iconAndtextElements = $B1(`$(${$6l.attach.id}) ${this.S(type)}`);
      const htmlElements = iconAndtextElements.map((element) => {
        if (typeof element === "string") {
          return $("span.overlay-text", void 0, element);
        }
        return element;
      });
      this.b = $("span.attach-context-overlay-text", void 0, ...htmlElements);
      this.b.style.backgroundColor = this.c;
      overlay.appendChild(this.b);
    }
    overlay.classList.toggle("visible", type !== void 0);
  }
  S(type) {
    const typeName = this.J(type);
    return localize(4826, null, typeName);
  }
  U(overlay) {
    overlay.style.backgroundColor = this.z(this.g.overlayBackground) || "";
    overlay.style.color = this.z(this.g.listForeground) || "";
  }
  updateStyles() {
    this.a.forEach((overlay) => this.U(overlay.overlay));
    this.c = this.z(this.g.listBackground) || "";
  }
};
$ONb = __decorate([
  __param(2, $gs),
  __param(3, $wN),
  __param(4, $km),
  __param(5, $mJ)
], $ONb);
var $PNb = class $PNb2 extends $ONb {
  constructor(attachmentModel, styles, themeService, extensionService, fileService, editorService) {
    super(attachmentModel, styles, themeService, extensionService, fileService, editorService);
  }
  F(context) {
    this.X(context);
  }
  async X(context) {
    const nonDirectoryContext = context.filter((context2) => !context2.isDirectory);
    const directories = context.filter((context2) => context2.isDirectory).map((context2) => context2.value).filter((value) => !!value && URI.isUri(value));
    for (const directory of directories) {
      const fileSystemProvider = this.m.getProvider(directory.scheme);
      if (!fileSystemProvider) {
        continue;
      }
      const resolvedFiles = await resolveFilesInDirectory(directory, fileSystemProvider, true);
      const resolvedFileContext = resolvedFiles.map((file) => getResourceAttachContext(file, false)).filter((context2) => !!context2);
      nonDirectoryContext.push(...resolvedFileContext);
    }
    super.F(nonDirectoryContext);
  }
  S(type) {
    const typeName = this.J(type);
    switch (type) {
      case ChatDragAndDropType.FILE_INTERNAL:
      case ChatDragAndDropType.FILE_EXTERNAL:
        return localize(4827, null, typeName);
      case ChatDragAndDropType.FOLDER:
        return localize(4828, null, localize(4829, null));
      default:
        return super.S(type);
    }
  }
};
$PNb = __decorate([
  __param(2, $gs),
  __param(3, $wN),
  __param(4, $km),
  __param(5, $mJ)
], $PNb);
async function resolveFilesInDirectory(resource, fileSystemProvider, shouldRecurse) {
  const entries2 = await fileSystemProvider.readdir(resource);
  const files = [];
  const folders = [];
  for (const [name, type] of entries2) {
    const entryResource = $vh(resource, name);
    if (type === FileType.File) {
      files.push(entryResource);
    } else if (type === FileType.Directory && shouldRecurse) {
      folders.push(entryResource);
    }
  }
  const subFiles = await Promise.all(folders.map((folder) => resolveFilesInDirectory(folder, fileSystemProvider, shouldRecurse)));
  return [...files, ...subFiles.flat()];
}
function getResourceAttachContext(resource, isDirectory) {
  return {
    value: resource,
    id: resource.toString(),
    name: $sh(resource),
    isFile: !isDirectory,
    isDirectory,
    isDynamic: true
  };
}
function getImageAttachContext(editor) {
  if (!editor.resource) {
    return void 0;
  }
  if (/\.(png|jpg|jpeg|bmp|gif|tiff)$/i.test(editor.resource.path)) {
    const fileName = $sh(editor.resource);
    return {
      id: editor.resource.toString(),
      name: fileName,
      fullName: editor.resource.path,
      value: editor.resource,
      icon: $6l.fileMedia,
      isDynamic: true,
      isImage: true,
      isFile: false
    };
  }
  return void 0;
}
function symbolId(resource, range) {
  let rangePart = "";
  if (range) {
    rangePart = `:${range.startLineNumber}`;
    if (range.startLineNumber !== range.endLineNumber) {
      rangePart += `-${range.endLineNumber}`;
    }
  }
  return resource.fsPath + rangePart;
}

// out-build/vs/workbench/contrib/chat/browser/chatEditing/chatEditingActions.js
var WorkingSetAction = class extends $gJ {
  run(accessor, ...args2) {
    const chatEditingService = accessor.get($$O);
    const currentEditingSession = chatEditingService.currentEditingSession;
    if (!currentEditingSession) {
      return;
    }
    const chatWidget = accessor.get($2Nb).lastFocusedWidget;
    if (chatWidget?.location !== ChatAgentLocation.EditingSession) {
      return;
    }
    const uris = [];
    if (URI.isUri(args2[0])) {
      uris.push(args2[0]);
    } else if (chatWidget) {
      uris.push(...chatWidget.input.selectedElements);
    }
    if (!uris.length) {
      return;
    }
    return this.runWorkingSetAction(accessor, currentEditingSession, chatWidget, ...uris);
  }
};
$hJ(class AddFileToWorkingSet extends WorkingSetAction {
  constructor() {
    super({
      id: "chatEditing.addFileToWorkingSet",
      title: localize2(4851, "Add File"),
      icon: $6l.plus,
      menu: [{
        id: $bJ.ChatEditingWidgetModifiedFilesToolbar,
        when: $7m.or($7m.equals(
          $aP.key,
          3
          /* WorkingSetEntryState.Transient */
        ), $7m.equals(
          $aP.key,
          6
          /* WorkingSetEntryState.Suggested */
        )),
        order: 0,
        group: "navigation"
      }]
    });
  }
  async runWorkingSetAction(_accessor, currentEditingSession, _chatWidget, ...uris) {
    for (const uri of uris) {
      currentEditingSession.addFileToWorkingSet(uri);
    }
  }
});
$hJ(class RemoveFileFromWorkingSet extends WorkingSetAction {
  constructor() {
    super({
      id: "chatEditing.removeFileFromWorkingSet",
      title: localize2(4852, "Remove File"),
      icon: $6l.close,
      menu: [{
        id: $bJ.ChatEditingWidgetModifiedFilesToolbar,
        // when: ContextKeyExpr.or(ContextKeyExpr.equals(chatEditingWidgetFileStateContextKey.key, WorkingSetEntryState.Attached), ContextKeyExpr.equals(chatEditingWidgetFileStateContextKey.key, WorkingSetEntryState.Suggested), ContextKeyExpr.equals(chatEditingWidgetFileStateContextKey.key, WorkingSetEntryState.Transient)),
        order: 5,
        group: "navigation"
      }]
    });
  }
  async runWorkingSetAction(accessor, currentEditingSession, chatWidget, ...uris) {
    currentEditingSession.remove(0, ...uris);
    for (const uri of uris) {
      chatWidget.attachmentModel.delete(uri.toString());
    }
    const entries2 = [...currentEditingSession.workingSet.entries()];
    const suggestedFiles = entries2.filter(
      ([_, state]) => state.state === 6
      /* WorkingSetEntryState.Suggested */
    );
    if (suggestedFiles.length === entries2.length && !chatWidget.attachmentModel.attachments.find((v) => v.isFile && URI.isUri(v.value))) {
      currentEditingSession.remove(1, ...entries2.map(([uri]) => uri));
    }
  }
});
$hJ(class OpenFileInDiffAction extends WorkingSetAction {
  constructor() {
    super({
      id: "chatEditing.openFileInDiff",
      title: localize2(4853, "Open Changes in Diff Editor"),
      icon: $6l.diffSingle,
      menu: [{
        id: $bJ.ChatEditingWidgetModifiedFilesToolbar,
        when: $7m.equals(
          $aP.key,
          0
          /* WorkingSetEntryState.Modified */
        ),
        order: 2,
        group: "navigation"
      }]
    });
  }
  async runWorkingSetAction(accessor, currentEditingSession, _chatWidget, ...uris) {
    const editorService = accessor.get($mJ);
    for (const uri of uris) {
      const editedFile = currentEditingSession.getEntry(uri);
      if (editedFile?.state.get() === 0) {
        await editorService.openEditor({
          original: { resource: URI.from(editedFile.originalURI, true) },
          modified: { resource: URI.from(editedFile.modifiedURI, true) }
        });
      } else {
        await editorService.openEditor({ resource: uri });
      }
    }
  }
});
$hJ(class AcceptAction extends WorkingSetAction {
  constructor() {
    super({
      id: "chatEditing.acceptFile",
      title: localize2(4854, "Accept"),
      icon: $6l.check,
      menu: [{
        when: $7m.and($7m.equals("resourceScheme", $_O), $7m.notIn($cP.key, $bP.key)),
        id: $bJ.MultiDiffEditorFileToolbar,
        order: 0,
        group: "navigation"
      }, {
        id: $bJ.ChatEditingWidgetModifiedFilesToolbar,
        when: $7m.equals(
          $aP.key,
          0
          /* WorkingSetEntryState.Modified */
        ),
        order: 0,
        group: "navigation"
      }]
    });
  }
  async runWorkingSetAction(accessor, currentEditingSession, chatWidget, ...uris) {
    await currentEditingSession.accept(...uris);
  }
});
$hJ(class DiscardAction extends WorkingSetAction {
  constructor() {
    super({
      id: "chatEditing.discardFile",
      title: localize2(4855, "Discard"),
      icon: $6l.discard,
      menu: [{
        when: $7m.and($7m.equals("resourceScheme", $_O), $7m.notIn($cP.key, $bP.key)),
        id: $bJ.MultiDiffEditorFileToolbar,
        order: 2,
        group: "navigation"
      }, {
        id: $bJ.ChatEditingWidgetModifiedFilesToolbar,
        when: $7m.equals(
          $aP.key,
          0
          /* WorkingSetEntryState.Modified */
        ),
        order: 1,
        group: "navigation"
      }]
    });
  }
  async runWorkingSetAction(accessor, currentEditingSession, chatWidget, ...uris) {
    await currentEditingSession.reject(...uris);
  }
});
var $QNb = class extends $gJ {
  constructor() {
    super({
      id: "chatEditing.acceptAllFiles",
      title: localize(4830, null),
      icon: $6l.check,
      tooltip: localize(4831, null),
      precondition: $7m.and(ChatContextKeys.requestInProgress.negate(), $fP),
      keybinding: {
        primary: 2048 | 3,
        when: $7m.and(ChatContextKeys.requestInProgress.negate(), $fP, ChatContextKeys.location.isEqualTo(ChatAgentLocation.EditingSession), ChatContextKeys.inChatInput),
        weight: 200
      },
      menu: [
        {
          when: $7m.equals("resourceScheme", $_O),
          id: $bJ.EditorTitle,
          order: 0,
          group: "navigation"
        },
        {
          id: $bJ.ChatEditingWidgetToolbar,
          group: "navigation",
          order: 0,
          when: $7m.and($hP.negate(), $7m.and($fP, $7m.and(ChatContextKeys.location.isEqualTo(ChatAgentLocation.EditingSession))))
        }
      ]
    });
  }
  async run(accessor, ...args2) {
    const chatEditingService = accessor.get($$O);
    const currentEditingSession = chatEditingService.currentEditingSession;
    if (!currentEditingSession) {
      return;
    }
    await currentEditingSession.accept();
  }
};
$hJ($QNb);
var $RNb = class extends $gJ {
  constructor() {
    super({
      id: "chatEditing.discardAllFiles",
      title: localize(4832, null),
      icon: $6l.discard,
      tooltip: localize(4833, null),
      precondition: $7m.and(ChatContextKeys.requestInProgress.negate(), $fP),
      menu: [
        {
          when: $7m.equals("resourceScheme", $_O),
          id: $bJ.EditorTitle,
          order: 1,
          group: "navigation"
        },
        {
          id: $bJ.ChatEditingWidgetToolbar,
          group: "navigation",
          order: 1,
          when: $7m.and($hP.negate(), $7m.and(ChatContextKeys.location.isEqualTo(ChatAgentLocation.EditingSession), $fP))
        }
      ],
      keybinding: {
        when: $7m.and(ChatContextKeys.requestInProgress.negate(), $fP, ChatContextKeys.location.isEqualTo(ChatAgentLocation.EditingSession), ChatContextKeys.inChatInput, ChatContextKeys.inputHasText.negate()),
        weight: 200,
        primary: 2048 | 1
      }
    });
  }
  async run(accessor, ...args2) {
    const chatEditingService = accessor.get($$O);
    const dialogService = accessor.get($Yv);
    const currentEditingSession = chatEditingService.currentEditingSession;
    if (!currentEditingSession) {
      return;
    }
    const entries2 = currentEditingSession.entries.get();
    if (entries2.length > 0) {
      const confirmation = await dialogService.confirm({
        title: localize(4834, null),
        message: entries2.length === 1 ? localize(4835, null, "Copilot Edits", $sh(entries2[0].modifiedURI)) : localize(4836, null, "Copilot Edits", entries2.length),
        primaryButton: localize(4837, null),
        type: "info"
      });
      if (!confirmation.confirmed) {
        return;
      }
    }
    await currentEditingSession.reject();
  }
};
$hJ($RNb);
var $SNb = class _$SNb extends $gJ {
  static {
    this.ID = "chatEditing.clearWorkingSet";
  }
  constructor() {
    super({
      id: _$SNb.ID,
      title: localize(4838, null),
      icon: $6l.clearAll,
      tooltip: localize(4839, null),
      precondition: $7m.and(ChatContextKeys.requestInProgress.negate()),
      menu: [
        {
          id: $bJ.ChatEditingWidgetToolbar,
          group: "navigation",
          order: 5,
          when: $7m.and($gP.negate(), ChatContextKeys.location.isEqualTo(ChatAgentLocation.EditingSession))
        }
      ]
    });
  }
  async run(accessor, ...args2) {
    const chatEditingService = accessor.get($$O);
    const currentEditingSession = chatEditingService.currentEditingSession;
    if (!currentEditingSession) {
      return;
    }
    const chatWidget = accessor.get($2Nb).getWidgetBySessionId(currentEditingSession.chatSessionId);
    const uris = [...currentEditingSession.workingSet.keys()];
    currentEditingSession.remove(0, ...uris);
    const attachmentModel = chatWidget?.attachmentModel;
    const fileAttachments = attachmentModel ? [...attachmentModel.excludedFileAttachments, ...attachmentModel.fileAttachments] : [];
    const attachmentIdsToRemove = fileAttachments.map((attachment) => attachment.value.toString());
    chatWidget?.attachmentModel.delete(...attachmentIdsToRemove);
  }
};
$hJ($SNb);
var $TNb = class _$TNb extends $gJ {
  static {
    this.ID = "chatEditing.viewChanges";
  }
  static {
    this.LABEL = localize(4840, null);
  }
  constructor() {
    super({
      id: _$TNb.ID,
      title: _$TNb.LABEL,
      tooltip: _$TNb.LABEL,
      f1: false,
      icon: $6l.diffMultiple,
      precondition: $fP,
      menu: [
        {
          id: $bJ.ChatEditingWidgetToolbar,
          group: "navigation",
          order: 4,
          when: $7m.and($hP.negate(), $7m.and($gP, $fP, ChatContextKeys.location.isEqualTo(ChatAgentLocation.EditingSession)))
        }
      ]
    });
  }
  async run(accessor, ...args2) {
    const chatEditingService = accessor.get($$O);
    const currentEditingSession = chatEditingService.currentEditingSession;
    if (!currentEditingSession) {
      return;
    }
    await currentEditingSession.show();
  }
};
$hJ($TNb);
$hJ(class AddFilesToWorkingSetAction extends $gJ {
  constructor() {
    super({
      id: "workbench.action.chat.addSelectedFilesToWorkingSet",
      title: localize2(4856, "Add Selected Files to Working Set"),
      icon: $6l.attach,
      category: $vNb,
      precondition: ChatContextKeys.location.isEqualTo(ChatAgentLocation.EditingSession),
      f1: true
    });
  }
  async run(accessor, ...args2) {
    const listService = accessor.get($Deb);
    const chatEditingService = accessor.get($$O);
    const editorGroupService = accessor.get($iJ);
    const uris = [];
    for (const group2 of editorGroupService.getGroups(
      1
      /* GroupsOrder.MOST_RECENTLY_ACTIVE */
    )) {
      for (const selection of group2.selectedEditors) {
        if (selection.resource) {
          uris.push(selection.resource);
        }
      }
    }
    if (uris.length === 0) {
      const selection = listService.lastFocusedList?.getSelection();
      if (selection?.length) {
        for (const file of selection) {
          if (!!file && typeof file === "object" && "resource" in file && URI.isUri(file.resource)) {
            uris.push(file.resource);
          }
        }
      }
    }
    for (const file of uris) {
      chatEditingService?.currentEditingSessionObs.get()?.addFileToWorkingSet(file);
    }
  }
});
$hJ(class RemoveAction extends $gJ {
  constructor() {
    super({
      id: "workbench.action.chat.undoEdits",
      title: localize2(4857, "Undo Edits"),
      f1: false,
      category: $vNb,
      icon: $6l.x,
      keybinding: {
        primary: 20,
        mac: {
          primary: 2048 | 1
        },
        when: $7m.and(ChatContextKeys.location.isEqualTo(ChatAgentLocation.EditingSession), ChatContextKeys.inChatSession, ChatContextKeys.inChatInput.negate()),
        weight: 200
      },
      menu: [
        {
          id: $bJ.ChatMessageTitle,
          group: "navigation",
          order: 2,
          when: $7m.and(ChatContextKeys.location.isEqualTo(ChatAgentLocation.EditingSession), ChatContextKeys.isRequest)
        }
      ]
    });
  }
  async run(accessor, ...args2) {
    let item = args2[0];
    if (!$asb(item) && !$_rb(item)) {
      const chatWidgetService = accessor.get($2Nb);
      const widget = chatWidgetService.lastFocusedWidget;
      item = widget?.getFocus();
    }
    if (!item) {
      return;
    }
    const configurationService = accessor.get($kl);
    const dialogService = accessor.get($Yv);
    const chatEditingService = accessor.get($$O);
    const chatService = accessor.get($qO);
    const chatModel = chatService.getSession(item.sessionId);
    if (chatModel?.initialLocation !== ChatAgentLocation.EditingSession) {
      return;
    }
    const session = chatEditingService.currentEditingSession;
    if (!session) {
      return;
    }
    const requestId = $_rb(item) ? item.id : $asb(item) ? item.requestId : void 0;
    if (requestId) {
      const chatRequests = chatModel.getRequests();
      const itemIndex = chatRequests.findIndex((request) => request.id === requestId);
      const editsToUndo = chatRequests.length - itemIndex;
      const requestsToRemove = chatRequests.slice(itemIndex);
      const requestIdsToRemove = new Set(requestsToRemove.map((request) => request.id));
      const entriesModifiedInRequestsToRemove = chatEditingService.currentEditingSessionObs.get()?.entries.get().filter((entry) => requestIdsToRemove.has(entry.lastModifyingRequestId)) ?? [];
      const shouldPrompt = entriesModifiedInRequestsToRemove.length > 0 && configurationService.getValue("chat.editing.confirmEditRequestRemoval") === true;
      let message;
      if (editsToUndo === 1) {
        if (entriesModifiedInRequestsToRemove.length === 1) {
          message = localize(4841, null, $sh(entriesModifiedInRequestsToRemove[0].modifiedURI));
        } else {
          message = localize(4842, null, entriesModifiedInRequestsToRemove.length);
        }
      } else {
        if (entriesModifiedInRequestsToRemove.length === 1) {
          message = localize(4843, null, $sh(entriesModifiedInRequestsToRemove[0].modifiedURI));
        } else {
          message = localize(4844, null, entriesModifiedInRequestsToRemove.length);
        }
      }
      const confirmation = shouldPrompt ? await dialogService.confirm({
        title: editsToUndo === 1 ? localize(4845, null) : localize(4846, null, editsToUndo),
        message,
        primaryButton: localize(4847, null),
        checkbox: { label: localize(4848, null), checked: false },
        type: "info"
      }) : { confirmed: true };
      if (!confirmation.confirmed) {
        return;
      }
      if (confirmation.checkboxChecked) {
        await configurationService.updateValue("chat.editing.confirmEditRequestRemoval", false);
      }
      const snapshotRequestId = chatRequests[itemIndex].id;
      await session.restoreSnapshot(snapshotRequestId);
      for (const request of requestsToRemove) {
        await chatService.removeRequest(item.sessionId, request.id);
      }
    }
  }
});
$hJ(class OpenWorkingSetHistoryAction extends $gJ {
  static {
    this.id = "chat.openFileSnapshot";
  }
  constructor() {
    super({
      id: OpenWorkingSetHistoryAction.id,
      title: localize(4849, null),
      precondition: $7m.notIn(ChatContextKeys.itemId.key, ChatContextKeys.lastItemId.key),
      menu: [{
        id: $bJ.ChatEditingCodeBlockContext,
        group: "navigation",
        order: 0
      }]
    });
  }
  async run(accessor, ...args2) {
    const context = args2[0];
    if (!context?.sessionId) {
      return;
    }
    const chatService = accessor.get($qO);
    const chatEditingService = accessor.get($$O);
    const editorService = accessor.get($mJ);
    const chatModel = chatService.getSession(context.sessionId);
    const requests = chatModel?.getRequests();
    if (!requests) {
      return;
    }
    const snapshotRequestIndex = requests?.findIndex((v, i2) => i2 > 0 && requests[i2 - 1]?.id === context.requestId);
    if (snapshotRequestIndex < 1) {
      return;
    }
    const snapshotRequestId = requests[snapshotRequestIndex]?.id;
    if (snapshotRequestId) {
      const snapshot = chatEditingService.currentEditingSession?.getSnapshotUri(snapshotRequestId, context.uri);
      if (snapshot) {
        const editor = await editorService.openEditor({ resource: snapshot, label: localize(4850, null, $sh(context.uri), snapshotRequestIndex - 1), options: { transient: true, activation: EditorActivation.ACTIVATE } });
        if ($P5(editor)) {
          editor.updateOptions({ readOnly: true });
        }
      }
    }
  }
});
$hJ(class ResolveSymbolsContextAction extends $gJ {
  constructor() {
    super({
      id: "workbench.action.edits.addFilesFromReferences",
      title: localize2(4858, "Add Files From References"),
      f1: false,
      category: $vNb,
      menu: {
        id: $bJ.ChatInputSymbolAttachmentContext,
        group: "navigation",
        order: 1,
        when: $7m.and(ChatContextKeys.location.isEqualTo(ChatAgentLocation.EditingSession), EditorContextKeys.hasReferenceProvider)
      }
    });
  }
  async run(accessor, ...args2) {
    const widgetService = accessor.get($2Nb);
    const textModelService = accessor.get($oG);
    const languageFeaturesService = accessor.get($mP);
    const [widget] = widgetService.getWidgetsByLocations(ChatAgentLocation.EditingSession);
    if (!widget || args2.length === 0 || !$SE(args2[0])) {
      return;
    }
    const symbol = args2[0];
    const modelReference = await textModelService.createModelReference(symbol.uri);
    const textModel = modelReference.object.textEditorModel;
    if (!textModel) {
      return;
    }
    const position = new $8C(symbol.range.startLineNumber, symbol.range.startColumn);
    const [references, definitions3, implementations] = await Promise.all([
      this.a(position, textModel, languageFeaturesService),
      this.b(position, textModel, languageFeaturesService),
      this.c(position, textModel, languageFeaturesService)
    ]);
    const attachments = [];
    for (const reference of [...definitions3, ...implementations, ...references]) {
      attachments.push(widget.attachmentModel.asVariableEntry(reference.uri));
    }
    widget.attachmentModel.addContext(...attachments);
  }
  async a(position, textModel, languageFeaturesService) {
    const referenceProviders = languageFeaturesService.referenceProvider.all(textModel);
    const references = await Promise.all(referenceProviders.map(async (referenceProvider) => {
      return await referenceProvider.provideReferences(textModel, position, { includeDeclaration: true }, CancellationToken.None) ?? [];
    }));
    return references.flat();
  }
  async b(position, textModel, languageFeaturesService) {
    const definitionProviders = languageFeaturesService.definitionProvider.all(textModel);
    const definitions3 = await Promise.all(definitionProviders.map(async (definitionProvider) => {
      return await definitionProvider.provideDefinition(textModel, position, CancellationToken.None) ?? [];
    }));
    return definitions3.flat();
  }
  async c(position, textModel, languageFeaturesService) {
    const implementationProviders = languageFeaturesService.implementationProvider.all(textModel);
    const implementations = await Promise.all(implementationProviders.map(async (implementationProvider) => {
      return await implementationProvider.provideImplementation(textModel, position, CancellationToken.None) ?? [];
    }));
    return implementations.flat();
  }
});

// out-build/vs/editor/common/diff/documentDiffProvider.js
var $0O = Object.freeze({
  identical: true,
  quitEarly: false,
  changes: Object.freeze([]),
  moves: Object.freeze([])
});

// out-build/vs/editor/common/model/textModelOffsetEdit.js
var $ZEb = class {
  constructor() {
  }
  static asEditOperations(offsetEdit, doc) {
    const edits = [];
    for (const singleEdit of offsetEdit.edits) {
      const range = $9C.fromPositions(doc.getPositionAt(singleEdit.replaceRange.start), doc.getPositionAt(singleEdit.replaceRange.start + singleEdit.replaceRange.length));
      edits.push($bD.replace(range, singleEdit.newText));
    }
    return edits;
  }
  static fromContentChanges(contentChanges) {
    const editsArr = contentChanges.map((c) => new $dD($0C.ofStartAndLength(c.rangeOffset, c.rangeLength), c.text));
    editsArr.reverse();
    const edits = new $cD(editsArr);
    return edits;
  }
  static fromLineRangeMapping(original, modified, changes) {
    const edits = [];
    for (const c of changes) {
      for (const i2 of c.innerChanges ?? []) {
        const newText = modified.getValueInRange(i2.modifiedRange);
        const startOrig = original.getOffsetAt(i2.originalRange.getStartPosition());
        const endExOrig = original.getOffsetAt(i2.originalRange.getEndPosition());
        const origRange = new $0C(startOrig, endExOrig);
        edits.push(new $dD(origRange, newText));
      }
    }
    return new $cD(edits);
  }
};

// out-build/vs/workbench/contrib/chat/browser/chatEditing/chatEditingTextModelContentProviders.js
var $nFb_1;
var $oFb_1;
var $nFb = class $nFb2 {
  static {
    $nFb_1 = this;
  }
  static {
    this.scheme = "chat-editing-text-model";
  }
  static getEmptyFileURI() {
    return URI.from({
      scheme: $nFb_1.scheme,
      query: JSON.stringify({ kind: "empty" })
    });
  }
  static getFileURI(documentId, path) {
    return URI.from({
      scheme: $nFb_1.scheme,
      path,
      query: JSON.stringify({ kind: "doc", documentId })
    });
  }
  constructor(a, b) {
    this.a = a;
    this.b = b;
  }
  async provideTextContent(resource) {
    const existing = this.b.getModel(resource);
    if (existing && !existing.isDisposed()) {
      return existing;
    }
    const data = JSON.parse(resource.query);
    if (data.kind === "empty") {
      return this.b.createModel("", null, resource, false);
    }
    const session = this.a.get();
    if (!session) {
      return null;
    }
    return session.getVirtualModel(data.documentId);
  }
};
$nFb = $nFb_1 = __decorate([
  __param(1, $sG)
], $nFb);
var $oFb = class $oFb2 {
  static {
    $oFb_1 = this;
  }
  static {
    this.scheme = "chat-editing-snapshot-text-model";
  }
  static getSnapshotFileURI(requestId, path) {
    return URI.from({
      scheme: $oFb_1.scheme,
      path,
      query: JSON.stringify({ requestId: requestId ?? "" })
    });
  }
  constructor(a, b) {
    this.a = a;
    this.b = b;
  }
  async provideTextContent(resource) {
    const existing = this.b.getModel(resource);
    if (existing && !existing.isDisposed()) {
      return existing;
    }
    const data = JSON.parse(resource.query);
    const session = this.a.get();
    if (!session || !data.requestId) {
      return null;
    }
    return session.getSnapshotModel(data.requestId, resource);
  }
};
$oFb = $oFb_1 = __decorate([
  __param(1, $sG)
], $oFb);

// out-build/vs/workbench/contrib/chat/browser/chatEditing/chatEditingModifiedFileEntry.js
var $pFb_1;
var $pFb = class $pFb2 extends $3c {
  static {
    $pFb_1 = this;
  }
  static {
    this.scheme = "modified-file-entry";
  }
  static {
    this.a = 0;
  }
  get onDidDelete() {
    return this.h.event;
  }
  get originalURI() {
    return this.b.uri;
  }
  get originalModel() {
    return this.b;
  }
  get modifiedURI() {
    return this.modifiedModel.uri;
  }
  get modifiedModel() {
    return this.c;
  }
  get state() {
    return this.j;
  }
  get isCurrentlyBeingModified() {
    return this.m;
  }
  get rewriteRatio() {
    return this.n;
  }
  get maxLineNumber() {
    return this.r;
  }
  get diffInfo() {
    return this.z;
  }
  static {
    this.F = $WI.register({
      isWholeLine: true,
      description: "chat-last-edit",
      className: "chat-editing-last-edit-line",
      marginClassName: "chat-editing-last-edit",
      overviewRuler: {
        position: OverviewRulerLane.Full,
        color: $7l($7o)
      }
    });
  }
  static {
    this.G = $WI.register({
      isWholeLine: true,
      description: "chat-pending-edit",
      className: "chat-editing-pending-edit"
    });
  }
  get telemetryInfo() {
    return this.I;
  }
  get lastModifyingRequestId() {
    return this.I.requestId;
  }
  constructor(resourceRef, H, I, kind, initialContent, modelService, textModelService, languageService, J, L, M, N) {
    super();
    this.H = H;
    this.I = I;
    this.J = J;
    this.L = L;
    this.M = M;
    this.N = N;
    this.entryId = `${$pFb_1.scheme}::${++$pFb_1.a}`;
    this.g = true;
    this.h = this.B(new $ze());
    this.j = $he(
      this,
      0
      /* WorkingSetEntryState.Modified */
    );
    this.m = $he(this, false);
    this.n = $he(this, 0);
    this.r = $he(this, 0);
    this.s = true;
    this.t = $cD.empty;
    this.u = false;
    this.y = 0;
    this.z = $he(this, $0O);
    this.C = this.B(new $8h(() => {
      this.D = this.c.deltaDecorations(this.D, []);
    }, 500));
    this.D = [];
    if (kind === 0) {
      this.createdInRequestId = this.I.requestId;
    }
    this.f = this.B(resourceRef).object;
    this.c = resourceRef.object.textEditorModel;
    this.initialContent = initialContent ?? this.c.getValue();
    const docSnapshot = this.b = this.B(modelService.createModel($OI(initialContent ? $gK(initialContent) : this.c.createSnapshot()), languageService.createById(this.c.getLanguageId()), $nFb.getFileURI(this.entryId, this.modifiedURI.path), false));
    (async () => {
      const reference = await textModelService.createModelReference(docSnapshot.uri);
      if (this.q.isDisposed) {
        reference.dispose();
        return;
      }
      this.B(reference);
    })();
    this.B(this.c.onDidChangeContent((e) => this.Q(e)));
    this.B(this.N.watch(this.modifiedURI));
    this.B(this.N.onDidFilesChange((e) => {
      if (e.affects(this.modifiedURI) && kind === 0 && e.gotDeleted()) {
        this.h.fire();
      }
    }));
    this.B($1c(() => {
      this.O();
    }));
  }
  O() {
    this.D = this.c.deltaDecorations(this.D, []);
  }
  updateTelemetryInfo(telemetryInfo) {
    this.I = telemetryInfo;
  }
  createSnapshot(requestId) {
    this.s = true;
    return {
      resource: this.modifiedURI,
      languageId: this.modifiedModel.getLanguageId(),
      snapshotUri: $oFb.getSnapshotFileURI(requestId, this.modifiedURI.path),
      original: this.originalModel.getValue(),
      current: this.modifiedModel.getValue(),
      originalToCurrentEdit: this.t,
      state: this.state.get(),
      telemetryInfo: this.I
    };
  }
  restoreFromSnapshot(snapshot) {
    this.j.set(snapshot.state, void 0);
    this.b.setValue(snapshot.original);
    this.W(snapshot.current);
    this.t = snapshot.originalToCurrentEdit;
    this.S();
  }
  resetToInitialValue() {
    this.W(this.initialContent);
  }
  acceptStreamingEditsStart(tx) {
    this.P(tx);
  }
  acceptStreamingEditsEnd(tx) {
    this.P(tx);
  }
  P(tx) {
    this.m.set(false, tx);
    this.n.set(0, tx);
    this.O();
  }
  Q(event) {
    const edit3 = $ZEb.fromContentChanges(event.changes);
    if (this.u) {
      const e_sum = this.t;
      const e_ai = edit3;
      this.t = e_sum.compose(e_ai);
    } else {
      const e_ai = this.t;
      const e_user = edit3;
      const e_user_r = e_user.tryRebase(e_ai.inverse(this.b.getValue()), true);
      if (e_user_r === void 0) {
        this.t = e_ai.compose(e_user);
      } else {
        const edits = $ZEb.asEditOperations(e_user_r, this.b);
        this.b.applyEdits(edits);
        this.t = e_ai.tryRebase(e_user_r);
      }
      this.g = false;
      this.S();
    }
    if (!this.isCurrentlyBeingModified.get()) {
      const didResetToOriginalContent = this.c.getValue() === this.initialContent;
      const currentState = this.j.get();
      switch (currentState) {
        case 0:
          if (didResetToOriginalContent) {
            this.j.set(2, void 0);
            break;
          }
      }
    }
  }
  acceptAgentEdits(textEdits, isLastEdits) {
    if (this.s) {
      this.s = false;
      const request = this.J.getSession(this.I.sessionId)?.getRequests().at(-1);
      const label3 = request?.message.text ? localize(4859, null, request.message.text) : localize(4860, null);
      this.M.pushElement(new $QH(label3, "chat.edit", this.c, null));
    }
    const ops = textEdits.map($VE.asEditOperation);
    const undoEdits = this.R(ops);
    const maxLineNumber = undoEdits.reduce((max, op) => Math.max(max, op.range.startLineNumber), 0);
    const newDecorations = [
      // decorate pending edit (region)
      {
        options: $pFb_1.G,
        range: new $9C(maxLineNumber + 1, 1, Number.MAX_SAFE_INTEGER, Number.MAX_SAFE_INTEGER)
      }
    ];
    if (maxLineNumber > 0) {
      newDecorations.push({
        options: $pFb_1.F,
        range: new $9C(maxLineNumber, 1, maxLineNumber, Number.MAX_SAFE_INTEGER)
      });
    }
    this.D = this.c.deltaDecorations(this.D, newDecorations);
    $ce((tx) => {
      if (!isLastEdits) {
        this.j.set(0, tx);
        this.m.set(true, tx);
        const lineCount = this.c.getLineCount();
        this.n.set(Math.min(1, maxLineNumber / lineCount), tx);
        this.r.set(maxLineNumber, tx);
      } else {
        this.P(tx);
        this.S();
        this.n.set(1, tx);
        this.C.schedule();
      }
    });
  }
  R(edits) {
    this.u = true;
    try {
      let result = [];
      this.c.pushEditOperations(null, edits, (undoEdits) => {
        result = undoEdits;
        return null;
      });
      return result;
    } finally {
      this.u = false;
    }
  }
  S() {
    const myDiffOperationId = ++this.y;
    Promise.resolve(this.w).then(() => {
      if (this.y === myDiffOperationId) {
        this.w = this.U();
      }
    });
  }
  async U() {
    if (this.b.isDisposed() || this.c.isDisposed()) {
      return;
    }
    const docVersionNow = this.c.getVersionId();
    const snapshotVersionNow = this.b.getVersionId();
    const diff3 = await this.L.computeDiff(this.b.uri, this.c.uri, { computeMoves: true, ignoreTrimWhitespace: false, maxComputationTimeMs: 3e3 }, "advanced");
    if (this.b.isDisposed() || this.c.isDisposed()) {
      return;
    }
    if (this.c.getVersionId() === docVersionNow && this.b.getVersionId() === snapshotVersionNow) {
      const diff22 = diff3 ?? $0O;
      this.z.set(diff22, void 0);
      this.t = $ZEb.fromLineRangeMapping(this.b, this.c, diff22.changes);
    }
  }
  async accept(transaction) {
    if (this.j.get() !== 0) {
      return;
    }
    this.b.setValue(this.c.createSnapshot());
    this.z.set($0O, transaction);
    this.t = $cD.empty;
    this.j.set(1, transaction);
    await this.collapse(transaction);
    this.X("accepted");
  }
  async reject(transaction) {
    if (this.j.get() !== 0) {
      return;
    }
    if (this.createdInRequestId === this.I.requestId) {
      await this.f.revert({ soft: true });
      await this.N.del(this.modifiedURI);
      this.h.fire();
    } else {
      this.W(this.b.getValue());
      if (this.g) {
        await this.f.save({ reason: 1, skipSaveParticipants: true });
      }
      await this.collapse(transaction);
    }
    this.j.set(2, transaction);
    this.X("rejected");
  }
  W(value) {
    if (this.c.getValue() !== value) {
      this.c.pushStackElement();
      const edit3 = $bD.replace(this.c.getFullModelRange(), value);
      this.R([edit3]);
      this.S();
      this.c.pushStackElement();
    }
  }
  async collapse(transaction) {
    this.H.collapse(transaction);
  }
  X(outcome) {
    this.J.notifyUserAction({
      action: { kind: "chatEditingSessionAction", uri: this.modifiedURI, hasRemainingEdits: false, outcome },
      agentId: this.I.agentId,
      command: this.I.command,
      sessionId: this.I.sessionId,
      requestId: this.I.requestId,
      result: this.I.result
    });
  }
};
$pFb = $pFb_1 = __decorate([
  __param(5, $sG),
  __param(6, $oG),
  __param(7, $1E),
  __param(8, $qO),
  __param(9, $I0),
  __param(10, $_F),
  __param(11, $km)
], $pFb);

// out-build/vs/workbench/contrib/chat/browser/chatEditorSaving.js
var $VNb_1;
var STORAGE_KEY_AUTOSAVE_DISABLED = "chat.editing.autosaveDisabled";
var $UNb = class $UNb2 extends $3c {
  static {
    this.ID = "workbench.chat.autoSaveDisabler";
  }
  constructor(configService, chatEditingService, fileConfigService, lifecycleService, storageService) {
    super();
    this.a = [];
    this.q.add(lifecycleService.onWillShutdown((e) => {
      storageService.store(
        STORAGE_KEY_AUTOSAVE_DISABLED,
        this.a,
        1,
        1
        /* StorageTarget.MACHINE */
      );
    }));
    const alwaysSaveConfig = $G9($VNb._config, false, configService);
    if (!alwaysSaveConfig.get()) {
      const autoSaveDisabled = storageService.getObject(STORAGE_KEY_AUTOSAVE_DISABLED, 1, []);
      if (Array.isArray(autoSaveDisabled) && autoSaveDisabled.length > 0) {
        const initializingStore = new $2c();
        for (const uriString of autoSaveDisabled) {
          initializingStore.add(fileConfigService.disableAutoSave(URI.parse(uriString)));
        }
        chatEditingService.getOrRestoreEditingSession().finally(() => {
          initializingStore.dispose();
        });
      }
    }
    const saveConfig = this.q.add(new $4c());
    this.q.add($td((reader) => {
      const store = new $2c();
      const autoSaveDisabled = [];
      try {
        if (alwaysSaveConfig.read(reader)) {
          return;
        }
        const session = chatEditingService.currentEditingSessionObs.read(reader);
        if (session) {
          const entries2 = session.entries.read(reader);
          for (const entry of entries2) {
            if (entry.state.read(reader) === 0) {
              autoSaveDisabled.push(entry.modifiedURI.toString());
              store.add(fileConfigService.disableAutoSave(entry.modifiedURI));
            }
          }
        }
      } finally {
        saveConfig.value = store;
        this.a = autoSaveDisabled;
      }
    }));
  }
};
$UNb = __decorate([
  __param(0, $kl),
  __param(1, $$O),
  __param(2, $4J),
  __param(3, $KL),
  __param(4, $jv)
], $UNb);
var $VNb = class $VNb2 extends $3c {
  static {
    $VNb_1 = this;
  }
  static {
    this.ID = "workbench.chat.editorSaving";
  }
  static {
    this._config = "chat.editing.alwaysSaveWithGeneratedChanges";
  }
  constructor(configService, chatEditingService, chatAgentService, textFileService, labelService, dialogService, a) {
    super();
    this.a = a;
    this.q.add($xd((r2, store2) => {
      const session = chatEditingService.currentEditingSessionObs.read(r2);
      if (!session) {
        return;
      }
      const chatSession = this.a.getSession(session.chatSessionId);
      if (!chatSession) {
        return;
      }
      store2.add(textFileService.files.onDidSave((e) => {
        const entry = session.getEntry(e.model.resource);
        if (entry && entry.state.get() === 0) {
          this.c(chatSession, entry);
        }
      }));
    }));
    const store = this.q.add(new $2c());
    const update = () => {
      store.clear();
      const alwaysSave = configService.getValue($VNb_1._config);
      if (alwaysSave) {
        return;
      }
      const saveJobs = new class {
        constructor() {
          this.b = new $8h(() => this.f(), 0);
          this.c = new $Fc();
        }
        add(uri) {
          this.c.add(uri);
          this.b.schedule();
          this.a ??= new $gi();
          return this.a.p;
        }
        async f() {
          const alwaysSave2 = configService.getValue($VNb_1._config);
          if (alwaysSave2) {
            return;
          }
          const uri = Iterable.first(this.c);
          if (!uri) {
            return;
          }
          const agentName = chatAgentService.getDefaultAgent(ChatAgentLocation.EditingSession)?.fullName ?? localize(4890, null);
          const filelabel = labelService.getUriBasenameLabel(uri);
          const message = this.c.size === 1 ? localize(4891, null, agentName, filelabel) : localize(4892, null, agentName, this.c.size);
          const result = await dialogService.confirm({
            message,
            detail: localize(4893, null, agentName),
            primaryButton: localize(4894, null),
            cancelButton: localize(4895, null),
            checkbox: {
              label: localize(4896, null),
              checked: false
            }
          });
          this.c.clear();
          if (result.confirmed && result.checkboxChecked) {
            await configService.updateValue($VNb_1._config, true);
          }
          if (!result.confirmed) {
            this.a?.error(new $lb());
          } else {
            this.a?.complete();
          }
          this.a = void 0;
        }
      }();
      store.add(textFileService.files.addSaveParticipant({
        participate: async (workingCopy, context, progress, token) => {
          if (context.reason !== 1) {
            return;
          }
          const session = await chatEditingService.getOrRestoreEditingSession();
          if (!session) {
            return;
          }
          const entry = session.getEntry(workingCopy.resource);
          if (!entry || entry.state.get() !== 0) {
            return;
          }
          return saveJobs.add(entry.modifiedURI);
        }
      }));
    };
    configService.onDidChangeConfiguration((e) => {
      if (e.affectsConfiguration($VNb_1._config)) {
        update();
      }
    });
    update();
  }
  b(entry) {
    $Jg(entry instanceof $pFb);
    this.a.notifyUserAction({
      action: { kind: "chatEditingSessionAction", uri: entry.modifiedURI, hasRemainingEdits: false, outcome: "saved" },
      agentId: entry.telemetryInfo.agentId,
      command: entry.telemetryInfo.command,
      sessionId: entry.telemetryInfo.sessionId,
      requestId: entry.telemetryInfo.requestId,
      result: entry.telemetryInfo.result
    });
  }
  c(session, entry) {
    if (!session.requestInProgress) {
      this.b(entry);
      return;
    }
    const d = session.onDidChange((e) => {
      if (!session.requestInProgress) {
        this.b(entry);
        this.q.delete(d);
        d.dispose();
      }
    });
    this.q.add(d);
  }
};
$VNb = $VNb_1 = __decorate([
  __param(0, $kl),
  __param(1, $$O),
  __param(2, $ZO),
  __param(3, $cK),
  __param(4, $ZI),
  __param(5, $Yv),
  __param(6, $qO)
], $VNb);
var $WNb = class _$WNb extends $gJ {
  static {
    this.ID = "chatEditing.saveAllFiles";
  }
  static {
    this.LABEL = localize(4897, null);
  }
  constructor() {
    super({
      id: _$WNb.ID,
      title: _$WNb.LABEL,
      tooltip: _$WNb.LABEL,
      precondition: $7m.and(ChatContextKeys.requestInProgress.negate(), $fP),
      icon: $6l.saveAll,
      menu: [
        {
          when: $7m.equals("resourceScheme", $_O),
          id: $bJ.EditorTitle,
          order: 2,
          group: "navigation"
        },
        {
          id: $bJ.ChatEditingWidgetToolbar,
          group: "navigation",
          order: 2,
          // Show the option to save without accepting if the user hasn't configured the setting to always save with generated changes
          when: $7m.and($hP.negate(), $fP, $7m.equals(`config.${$VNb._config}`, false), ChatContextKeys.location.isEqualTo(ChatAgentLocation.EditingSession))
        }
      ],
      keybinding: {
        primary: 2048 | 49,
        when: $7m.and(ChatContextKeys.requestInProgress.negate(), $fP, ChatContextKeys.location.isEqualTo(ChatAgentLocation.EditingSession), ChatContextKeys.inChatInput),
        weight: 200
      }
    });
  }
  async run(accessor, ...args2) {
    const chatEditingService = accessor.get($$O);
    const editorService = accessor.get($mJ);
    const configService = accessor.get($kl);
    const chatAgentService = accessor.get($ZO);
    const dialogService = accessor.get($Yv);
    const labelService = accessor.get($ZI);
    const currentEditingSession = chatEditingService.currentEditingSession;
    if (!currentEditingSession) {
      return;
    }
    const editors = [];
    for (const modifiedFileEntry of currentEditingSession.entries.get()) {
      if (modifiedFileEntry.state.get() === 0) {
        const modifiedFile = modifiedFileEntry.modifiedURI;
        const matchingEditors = editorService.findEditors(modifiedFile);
        if (matchingEditors.length === 0) {
          continue;
        }
        const matchingEditor = matchingEditors[0];
        if (matchingEditor.editor.isDirty()) {
          editors.push(matchingEditor);
        }
      }
    }
    if (editors.length === 0) {
      return;
    }
    const alwaysSave = configService.getValue($VNb._config);
    if (!alwaysSave) {
      const agentName = chatAgentService.getDefaultAgent(ChatAgentLocation.EditingSession)?.fullName;
      let message;
      if (editors.length === 1) {
        const resource = editors[0].editor.resource;
        if (resource) {
          const filelabel = labelService.getUriBasenameLabel(resource);
          message = agentName ? localize(4898, null, agentName, filelabel) : localize(4899, null, filelabel);
        } else {
          message = agentName ? localize(4900, null, agentName) : localize(4901, null);
        }
      } else {
        message = agentName ? localize(4902, null, agentName, editors.length) : localize(4903, null, editors.length);
      }
      const result = await dialogService.confirm({
        message,
        detail: localize(4904, null, agentName),
        primaryButton: localize(4905, null),
        cancelButton: localize(4906, null),
        checkbox: {
          label: localize(4907, null),
          checked: false
        }
      });
      if (!result.confirmed) {
        return;
      }
      if (result.checkboxChecked) {
        await configService.updateValue($VNb._config, true);
      }
    }
    await editorService.save(editors, { reason: 1, skipSaveParticipants: true });
  }
};
$hJ($WNb);

// out-build/vs/workbench/contrib/chat/browser/chatFollowups.js
var $83 = $;
var $XNb = class $XNb2 extends $3c {
  constructor(container2, followups, a, b, c, f) {
    super();
    this.a = a;
    this.b = b;
    this.c = c;
    this.f = f;
    const followupsContainer = $bk(container2, $83(".interactive-session-followups"));
    followups.forEach((followup) => this.g(followupsContainer, followup));
  }
  g(container2, followup) {
    if (!this.f.getDefaultAgent(this.a)) {
      return;
    }
    const tooltipPrefix = $HO(this.f, this.a, "", followup.agentId, followup.subCommand);
    if (tooltipPrefix === void 0) {
      return;
    }
    const baseTitle = followup.kind === "reply" ? followup.title || followup.message : followup.title;
    const message = followup.kind === "reply" ? followup.message : followup.title;
    const tooltip = (tooltipPrefix + ("tooltip" in followup && followup.tooltip || message)).trim();
    const button = this.B(new $k2(container2, { ...this.b, title: tooltip }));
    if (followup.kind === "reply") {
      button.element.classList.add("interactive-followup-reply");
    } else if (followup.kind === "command") {
      button.element.classList.add("interactive-followup-command");
    }
    button.element.ariaLabel = localize(4908, null, baseTitle);
    button.label = new $bm(baseTitle);
    this.B(button.onDidClick(() => this.c(followup)));
  }
};
$XNb = __decorate([
  __param(5, $ZO)
], $XNb);

// out-build/vs/workbench/contrib/chat/browser/contrib/chatImplicitContext.js
var $YNb = class $YNb2 extends $3c {
  static {
    this.ID = "chat.implicitContext";
  }
  constructor(b, c, f, g) {
    super();
    this.b = b;
    this.c = c;
    this.f = f;
    this.g = g;
    this.a = this.B(new $4c());
    const activeEditorDisposables = this.B(new $2c());
    this.B(Event2.runAndSubscribe(c.onDidVisibleEditorsChange, () => {
      activeEditorDisposables.clear();
      const codeEditor = this.h();
      if (codeEditor) {
        activeEditorDisposables.add(Event2.debounce(Event2.any(codeEditor.onDidChangeModel, codeEditor.onDidChangeCursorSelection, codeEditor.onDidScrollChange), () => void 0, 500)(() => this.j()));
      }
      this.j();
    }));
    this.B(f.onDidAddWidget((widget) => this.j(widget)));
  }
  h() {
    const codeEditor = this.b.getActiveCodeEditor();
    if (codeEditor) {
      const model = codeEditor.getModel();
      if (model) {
        return codeEditor;
      }
    }
    for (const codeOrDiffEditor of this.c.getVisibleTextEditorControls(
      0
      /* EditorsOrder.MOST_RECENTLY_ACTIVE */
    )) {
      let codeEditor2;
      if ($Q5(codeOrDiffEditor)) {
        codeEditor2 = codeOrDiffEditor.getModifiedEditor();
      } else if ($P5(codeOrDiffEditor)) {
        codeEditor2 = codeOrDiffEditor;
      } else {
        continue;
      }
      const model = codeEditor2.getModel();
      if (model) {
        return codeEditor2;
      }
    }
    return void 0;
  }
  async j(updateWidget) {
    const cancelTokenSource = this.a.value = new $ad();
    const codeEditor = this.h();
    const model = codeEditor?.getModel();
    const selection = codeEditor?.getSelection();
    let newValue;
    let isSelection = false;
    if (model) {
      if (selection && !selection.isEmpty()) {
        newValue = { uri: model.uri, range: selection };
        isSelection = true;
      } else {
        const visibleRanges = codeEditor?.getVisibleRanges();
        if (visibleRanges && visibleRanges.length > 0) {
          let range = visibleRanges[0];
          visibleRanges.slice(1).forEach((r2) => {
            range = range.plusRange(r2);
          });
          newValue = { uri: model.uri, range };
        } else {
          newValue = model.uri;
        }
      }
    }
    const uri = newValue instanceof URI ? newValue : newValue?.uri;
    if (uri && await this.g.fileIsIgnored(uri, cancelTokenSource.token)) {
      newValue = void 0;
    }
    if (cancelTokenSource.token.isCancellationRequested) {
      return;
    }
    const widgets2 = updateWidget ? [updateWidget] : [...this.f.getWidgetsByLocations(ChatAgentLocation.Panel), ...this.f.getWidgetsByLocations(ChatAgentLocation.Editor)];
    for (const widget of widgets2) {
      if (widget.input.implicitContext) {
        widget.input.implicitContext.setValue(newValue, isSelection);
      }
    }
  }
};
$YNb = __decorate([
  __param(0, $U5),
  __param(1, $mJ),
  __param(2, $2Nb),
  __param(3, $Xrb)
], $YNb);
var $ZNb = class extends $3c {
  get id() {
    if (URI.isUri(this.value)) {
      return "vscode.implicit.file";
    } else if (this.value) {
      if (this.a) {
        return "vscode.implicit.selection";
      } else {
        return "vscode.implicit.viewport";
      }
    } else {
      return "vscode.implicit";
    }
  }
  get name() {
    if (URI.isUri(this.value)) {
      return `file:${$sh(this.value)}`;
    } else if (this.value) {
      return `file:${$sh(this.value.uri)}`;
    } else {
      return "implicit";
    }
  }
  get modelDescription() {
    if (URI.isUri(this.value)) {
      return `User's active file`;
    } else if (this.a) {
      return `User's active selection`;
    } else {
      return `User's current visible code`;
    }
  }
  get isSelection() {
    return this.a;
  }
  get value() {
    return this.c;
  }
  get enabled() {
    return this.f;
  }
  set enabled(value) {
    this.f = value;
    this.b.fire();
  }
  constructor(value) {
    super();
    this.kind = "implicit";
    this.isDynamic = true;
    this.isFile = true;
    this.a = false;
    this.b = new $ze();
    this.onDidChangeValue = this.b.event;
    this.f = true;
    this.c = value;
  }
  setValue(value, isSelection) {
    this.c = value;
    this.a = isSelection;
    this.b.fire();
  }
  toBaseEntry() {
    return {
      id: this.id,
      name: this.name,
      value: this.value,
      isFile: true,
      isDynamic: true,
      modelDescription: this.modelDescription
    };
  }
};

// out-build/vs/workbench/contrib/chat/browser/chatInputPart.js
var $1Nb_1;
var $92 = $;
var INPUT_EDITOR_MAX_HEIGHT = 250;
var $1Nb = class $1Nb2 extends $3c {
  static {
    $1Nb_1 = this;
  }
  static {
    this.INPUT_SCHEME = "chatSessionInput";
  }
  static {
    this.c = 0;
  }
  get attachmentModel() {
    return this.t;
  }
  getAttachedAndImplicitContext() {
    const contextArr = [...this.attachmentModel.attachments];
    if (this.implicitContext?.enabled && this.implicitContext.value) {
      contextArr.push(this.implicitContext.toBaseEntry());
    }
    return contextArr;
  }
  get implicitContext() {
    return this.w;
  }
  get inputPartHeight() {
    return this.O;
  }
  get followupsHeight() {
    return this.P;
  }
  get inputEditor() {
    return this.Q;
  }
  get currentLanguageModel() {
    return this.gb;
  }
  get selectedElements() {
    const edits = [];
    const editsList = this.pb?.object;
    const selectedElements = editsList?.getSelectedElements() ?? [];
    for (const element of selectedElements) {
      if (element.kind === "reference" && URI.isUri(element.reference)) {
        edits.push(element.reference);
      }
    }
    return edits;
  }
  /**
   * The number of working set entries that the user actually wanted to attach.
   * This is less than or equal to {@link $1Nb.chatEditWorkingSetFiles}.
   */
  get attemptedWorkingSetEntriesCount() {
    return this.qb;
  }
  get chatEditWorkingSetFiles() {
    return this.rb;
  }
  constructor(tb, ub, styles, getContribsInputState, vb, wb, xb, yb, zb, Ab, Bb, Cb, Db, Eb, Fb, Gb, Hb, Ib, Jb, Kb, Lb, Mb, Nb, Ob) {
    super();
    this.tb = tb;
    this.ub = ub;
    this.vb = vb;
    this.wb = wb;
    this.xb = xb;
    this.yb = yb;
    this.zb = zb;
    this.Ab = Ab;
    this.Bb = Bb;
    this.Cb = Cb;
    this.Db = Db;
    this.Eb = Eb;
    this.Fb = Fb;
    this.Gb = Gb;
    this.Hb = Hb;
    this.Ib = Ib;
    this.Jb = Jb;
    this.Kb = Kb;
    this.Lb = Lb;
    this.Mb = Mb;
    this.Nb = Nb;
    this.Ob = Ob;
    this.f = this.B(new $ze());
    this.onDidLoadInputState = this.f.event;
    this.g = this.B(new $ze());
    this.onDidChangeHeight = this.g.event;
    this.j = this.B(new $ze());
    this.onDidFocus = this.j.event;
    this.n = this.B(new $ze());
    this.onDidBlur = this.n.event;
    this.r = this.B(new $ze());
    this.onDidChangeContext = this.r.event;
    this.s = this.B(new $ze());
    this.onDidAcceptFollowup = this.s.event;
    this.u = -1;
    this.z = this.B(new $ze());
    this.C = this.yb.createInstance($lsb, { onDidChangeVisibility: this.z.event });
    this.F = 0;
    this.J = this.B(new $2c());
    this.M = this.B(new $4c());
    this.O = 0;
    this.P = 0;
    this.eb = this.B(new $4c());
    this.fb = this.B(new $ze());
    this.inputUri = URI.parse(`${$1Nb_1.INPUT_SCHEME}:input-${$1Nb_1.c++}`);
    this.kb = this.B(new $2c());
    this.lb = this.B(new $2c());
    this.mb = this.B(new $4c());
    this.qb = 0;
    this.rb = [];
    if (this.tb === ChatAgentLocation.EditingSession) {
      this.t = this.B(this.yb.createInstance($fsb));
      this.W = this.B(this.yb.createInstance($PNb, this.attachmentModel, styles));
    } else {
      this.t = this.B(this.yb.createInstance($esb));
      this.W = this.B(this.yb.createInstance($ONb, this.attachmentModel, styles));
    }
    this.sb = () => {
      return {
        ...getContribsInputState(),
        chatContextAttachments: this.t.attachments
      };
    };
    this.D = this.ub.renderStyle === "compact" ? INPUT_EDITOR_MAX_HEIGHT / 3 : INPUT_EDITOR_MAX_HEIGHT;
    this.bb = ChatContextKeys.inputHasText.bindTo(zb);
    this.cb = ChatContextKeys.inputCursorAtTop.bindTo(zb);
    this.db = ChatContextKeys.inputHasFocus.bindTo(zb);
    this.X = this.Tb();
    this.B(this.vb.onDidClearHistory(() => this.X = new $G2([{ text: "" }], 50, historyKeyFn)));
    this.B(this.Ab.onDidChangeConfiguration((e) => {
      if (e.affectsConfiguration(
        "accessibility.verbosity.panelChat"
        /* AccessibilityVerbositySettingId.Chat */
      )) {
        this.inputEditor.updateOptions({ ariaLabel: this.Ub() });
      }
    }));
    this.ob = this.B(this.yb.createInstance($3Mb, this.z.event, $bJ.ChatEditingWidgetModifiedFilesToolbar));
    this.y = ChatContextKeys.hasFileAttachments.bindTo(zb);
    this.Qb();
  }
  Pb() {
    return `chat.currentLanguageModel.${this.tb}`;
  }
  Qb() {
    const persistedSelection = this.Nb.get(
      this.Pb(),
      -1
      /* StorageScope.APPLICATION */
    );
    if (persistedSelection) {
      const model = this.Db.lookupLanguageModel(persistedSelection);
      if (model) {
        this.gb = persistedSelection;
        this.fb.fire(this.gb);
      } else {
        this.eb.value = this.Db.onDidChangeLanguageModels((e) => {
          const persistedModel = e.added?.find((m) => m.identifier === persistedSelection);
          if (persistedModel) {
            this.eb.clear();
            if (persistedModel.metadata.isUserSelectable) {
              this.gb = persistedSelection;
              this.fb.fire(this.gb);
            }
          }
        });
      }
    }
  }
  Rb() {
    const defaultLanguageModel = this.Db.getLanguageModelIds().find((id2) => this.Db.lookupLanguageModel(id2)?.isDefault);
    const hasUserSelectableLanguageModels = this.Db.getLanguageModelIds().find((id2) => {
      const model = this.Db.lookupLanguageModel(id2);
      return model?.isUserSelectable && !model.isDefault;
    });
    this.gb = hasUserSelectableLanguageModels ? defaultLanguageModel : void 0;
  }
  Sb(modelId) {
    this.gb = modelId;
    this.eb.clear();
    if (this.hb) {
      this.layout(this.hb.height, this.hb.width);
    }
    this.Nb.store(
      this.Pb(),
      modelId,
      -1,
      0
      /* StorageTarget.USER */
    );
  }
  Tb() {
    const history = this.vb.getHistory(this.tb);
    if (history.length === 0) {
      history.push({ text: "" });
    }
    return new $G2(history, 50, historyKeyFn);
  }
  Ub() {
    const verbose = this.Ab.getValue(
      "accessibility.verbosity.panelChat"
      /* AccessibilityVerbositySettingId.Chat */
    );
    if (verbose) {
      const kbLabel = this.Bb.lookupKeybinding(
        "editor.action.accessibilityHelp"
        /* AccessibilityCommandId.OpenAccessibilityHelp */
      )?.getLabel();
      return kbLabel ? localize(4920, null, kbLabel) : localize(4921, null);
    }
    return localize(4922, null);
  }
  initForNewChatModel(state) {
    this.X = this.Tb();
    this.X.add({
      text: state.inputValue ?? this.X.current().text,
      state: state.inputState ?? this.sb()
    });
    const attachments = state.inputState?.chatContextAttachments ?? [];
    this.t.clearAndSetContext(...attachments);
    if (state.inputValue) {
      this.setValue(state.inputValue, false);
    }
  }
  logInputHistory() {
    const historyStr = [...this.X].map((entry) => JSON.stringify(entry)).join("\n");
    this.Eb.info(`[${this.tb}] Chat input history:`, historyStr);
  }
  setVisible(visible) {
    this.z.fire(visible);
  }
  get element() {
    return this.G;
  }
  showPreviousValue() {
    const inputState = this.sb();
    if (this.X.isAtEnd()) {
      this.Wb(inputState);
    } else {
      if (!this.X.has({ text: this.Q.getValue(), state: inputState })) {
        this.Wb(inputState);
        this.X.resetCursor();
      }
    }
    this.Vb(true);
  }
  showNextValue() {
    const inputState = this.sb();
    if (this.X.isAtEnd()) {
      return;
    } else {
      if (!this.X.has({ text: this.Q.getValue(), state: inputState })) {
        this.Wb(inputState);
        this.X.resetCursor();
      }
    }
    this.Vb(false);
  }
  Vb(previous) {
    const historyEntry = previous ? this.X.previous() : this.X.next();
    const historyAttachments = historyEntry.state?.chatContextAttachments ?? [];
    this.t.clearAndSetContext(...historyAttachments);
    $_Z(historyEntry.text);
    this.setValue(historyEntry.text, true);
    this.f.fire(historyEntry.state);
    const model = this.Q.getModel();
    if (!model) {
      return;
    }
    if (previous) {
      const endOfFirstViewLine = this.Q._getViewModel()?.getLineLength(1) ?? 1;
      const endOfFirstModelLine = model.getLineLength(1);
      if (endOfFirstViewLine === endOfFirstModelLine) {
        this.Q.setPosition({ lineNumber: 1, column: endOfFirstViewLine + 1 });
      } else {
        this.Q.setPosition({ lineNumber: 1, column: endOfFirstViewLine });
      }
    } else {
      this.Q.setPosition(getLastPosition(model));
    }
  }
  setValue(value, transient) {
    this.inputEditor.setValue(value);
    this.inputEditor.setPosition({ lineNumber: 1, column: value.length + 1 });
    if (!transient) {
      this.Wb(this.sb());
    }
  }
  Wb(inputState) {
    const newEntry = { text: this.Q.getValue(), state: inputState };
    this.X.replaceLast(newEntry);
  }
  focus() {
    this.Q.focus();
  }
  hasFocus() {
    return this.Q.hasWidgetFocus();
  }
  /**
   * Reset the input and update history.
   * @param userQuery If provided, this will be added to the history. Followups and programmatic queries should not be passed.
   */
  async acceptInput(isUserQuery) {
    if (isUserQuery) {
      const userQuery = this.Q.getValue();
      const entry = { text: userQuery, state: this.sb() };
      this.X.replaceLast(entry);
      this.X.add({ text: "" });
    }
    this.attachmentModel.clear();
    this.f.fire({});
    if (this.Cb.isScreenReaderOptimized() && $m) {
      this.Xb();
    } else {
      this.Q.focus();
      this.Q.setValue("");
    }
  }
  Xb() {
    const domNode = this.Q.getDomNode();
    if (!domNode) {
      return;
    }
    domNode.remove();
    this.Q.setValue("");
    this.R.appendChild(domNode);
    this.Q.focus();
  }
  Yb() {
    this.y.set(Boolean(this.t.attachments.find((a) => a.isFile)));
    this.Zb();
  }
  render(container2, initialValue, widget) {
    let elements;
    if (this.ub.renderStyle === "compact") {
      elements = h(".interactive-input-part", [
        h(".interactive-input-and-edit-session", [
          h(".chat-editing-session@chatEditingSessionWidgetContainer"),
          h(".interactive-input-and-side-toolbar@inputAndSideToolbar", [
            h(".chat-input-container@inputContainer", [
              h(".chat-editor-container@editorContainer"),
              h(".chat-input-toolbars@inputToolbars")
            ])
          ]),
          h(".chat-attached-context@attachedContextContainer"),
          h(".interactive-input-followups@followupsContainer")
        ])
      ]);
    } else {
      elements = h(".interactive-input-part", [
        h(".interactive-input-followups@followupsContainer"),
        h(".chat-editing-session@chatEditingSessionWidgetContainer"),
        h(".interactive-input-and-side-toolbar@inputAndSideToolbar", [
          h(".chat-input-container@inputContainer", [
            h(".chat-editor-container@editorContainer"),
            h(".chat-attached-context@attachedContextContainer"),
            h(".chat-input-toolbars@inputToolbars")
          ])
        ])
      ]);
    }
    this.G = elements.root;
    container2.append(this.G);
    this.G.classList.toggle("compact", this.ub.renderStyle === "compact");
    this.I = elements.followupsContainer;
    const inputAndSideToolbar = elements.inputAndSideToolbar;
    const inputContainer = elements.inputContainer;
    const editorContainer = elements.editorContainer;
    this.L = elements.attachedContextContainer;
    const toolbarsContainer = elements.inputToolbars;
    this.N = elements.chatEditingSessionWidgetContainer;
    this.Zb();
    if (this.ub.enableImplicitContext) {
      this.w = this.B(new $ZNb());
      this.B(this.w.onDidChangeValue(() => this.Yb()));
    }
    this.B(this.t.onDidChangeContext(() => this.Yb()));
    this.renderChatEditingSessionState(null, widget);
    this.W.addOverlay(container2, container2);
    const inputScopedContextKeyService = this.B(this.zb.createScoped(inputContainer));
    ChatContextKeys.inChatInput.bindTo(inputScopedContextKeyService).set(true);
    const scopedInstantiationService = this.B(this.yb.createChild(new $Ok([$on, inputScopedContextKeyService])));
    const { historyNavigationBackwardsEnablement, historyNavigationForwardsEnablement } = this.B($8bb(inputScopedContextKeyService, this));
    this.Y = historyNavigationBackwardsEnablement;
    this.Z = historyNavigationForwardsEnablement;
    const options3 = $Zsb(this.Ab);
    options3.overflowWidgetsDomNode = this.ub.editorOverflowWidgetsDomNode;
    options3.pasteAs = EditorOptions.pasteAs.defaultValue;
    options3.readOnly = false;
    options3.ariaLabel = this.Ub();
    options3.fontFamily = $91;
    options3.fontSize = 13;
    options3.lineHeight = 20;
    options3.padding = this.ub.renderStyle === "compact" ? { top: 2, bottom: 2 } : { top: 8, bottom: 8 };
    options3.cursorWidth = 1;
    options3.wrappingStrategy = "advanced";
    options3.bracketPairColorization = { enabled: false };
    options3.suggest = {
      showIcons: false,
      showSnippets: false,
      showWords: true,
      showStatusBar: false,
      insertMode: "replace"
    };
    options3.scrollbar = { ...options3.scrollbar ?? {}, vertical: "hidden" };
    options3.stickyScroll = { enabled: false };
    this.R = $bk(editorContainer, $92(chatInputEditorContainerSelector));
    const editorOptions2 = $1sb();
    editorOptions2.contributions?.push(...EditorExtensionsRegistry.getSomeEditorContributions([$Afb.ID, $Fib.ID, $iab.ID]));
    this.Q = this.B(scopedInstantiationService.createInstance($D9, this.R, options3, editorOptions2));
    $qdb.get(this.Q)?.forceRenderingAbove();
    this.B(this.Q.onDidChangeModelContent(() => {
      const currentHeight = Math.min(this.Q.getContentHeight(), this.D);
      if (currentHeight !== this.F) {
        this.F = currentHeight;
        this.g.fire();
      }
      const model = this.Q.getModel();
      const inputHasText = !!model && model.getValue().trim().length > 0;
      this.bb.set(inputHasText);
    }));
    this.B(this.Q.onDidContentSizeChange((e) => {
      if (e.contentHeightChanged) {
        this.F = e.contentHeight;
        this.g.fire();
      }
    }));
    this.B(this.Q.onDidFocusEditorText(() => {
      this.db.set(true);
      this.j.fire();
      inputContainer.classList.toggle("focused", true);
    }));
    this.B(this.Q.onDidBlurEditorText(() => {
      this.db.set(false);
      inputContainer.classList.toggle("focused", false);
      this.n.fire();
    }));
    this.B(this.Q.onDidBlurEditorWidget(() => {
      $iab.get(this.Q)?.clearWidgets();
      $Yfb.get(this.Q)?.clearWidgets();
    }));
    const hoverDelegate = this.B($KZ());
    this.B($aj(toolbarsContainer, $7j.CLICK, (e) => this.inputEditor.focus()));
    this.U = this.B(this.yb.createInstance($4$, toolbarsContainer, $bJ.ChatInput, {
      telemetrySource: this.ub.menus.telemetrySource,
      menuOptions: { shouldForwardArgs: true },
      hiddenItemStrategy: 0,
      hoverDelegate
    }));
    this.U.context = { widget };
    this.B(this.U.onDidChangeMenuItems(() => {
      if (this.hb && typeof this.jb === "number" && this.jb !== this.U.getItemsWidth()) {
        this.layout(this.hb.height, this.hb.width);
      }
    }));
    this.S = this.B(this.yb.createInstance($4$, toolbarsContainer, this.ub.menus.executeToolbar, {
      telemetrySource: this.ub.menus.telemetrySource,
      menuOptions: {
        shouldForwardArgs: true
      },
      hoverDelegate,
      hiddenItemStrategy: 0,
      // keep it lean when hiding items and avoid a "..." overflow menu
      actionViewItemProvider: (action, options4) => {
        if (this.tb === ChatAgentLocation.Panel || this.tb === ChatAgentLocation.Editor) {
          if ((action.id === $HNb.ID || action.id === $LNb.ID) && action instanceof $fJ) {
            const dropdownAction = this.yb.createInstance($fJ, { id: "chat.moreExecuteActions", title: localize(4923, null), icon: $6l.chevronDown }, void 0, void 0, void 0, void 0);
            return this.yb.createInstance(ChatSubmitDropdownActionItem, action, dropdownAction, options4);
          }
        }
        if (action.id === $JNb && action instanceof $fJ) {
          if (!this.gb) {
            this.Rb();
          }
          if (this.gb) {
            const itemDelegate = {
              onDidChangeModel: this.fb.event,
              setModel: (modelId) => {
                this.Sb(modelId);
              }
            };
            return this.yb.createInstance(ModelPickerActionViewItem, action, this.gb, itemDelegate, { hoverDelegate: options4.hoverDelegate, keybinding: options4.keybinding ?? void 0 });
          }
        }
        return void 0;
      }
    }));
    this.S.getElement().classList.add("chat-execute-toolbar");
    this.S.context = { widget };
    this.B(this.S.onDidChangeMenuItems(() => {
      if (this.hb && typeof this.ib === "number" && this.ib !== this.S.getItemsWidth()) {
        this.layout(this.hb.height, this.hb.width);
      }
    }));
    if (this.ub.menus.inputSideToolbar) {
      const toolbarSide = this.B(this.yb.createInstance($4$, inputAndSideToolbar, this.ub.menus.inputSideToolbar, {
        telemetrySource: this.ub.menus.telemetrySource,
        menuOptions: {
          shouldForwardArgs: true
        },
        hoverDelegate
      }));
      this.H = toolbarSide.getElement();
      toolbarSide.getElement().classList.add("chat-side-toolbar");
      toolbarSide.context = { widget };
    }
    let inputModel = this.wb.getModel(this.inputUri);
    if (!inputModel) {
      inputModel = this.wb.createModel("", null, this.inputUri, true);
    }
    this.Mb.createModelReference(this.inputUri).then((ref) => {
      if (this.q.isDisposed) {
        ref.dispose();
        return;
      }
      this.B(ref);
    });
    this.ab = inputModel;
    this.ab.updateOptions({ bracketColorizationOptions: { enabled: false, independentColorPoolPerBracketType: false } });
    this.Q.setModel(this.ab);
    if (initialValue) {
      this.ab.setValue(initialValue);
      const lineNumber = this.ab.getLineCount();
      this.Q.setPosition({ lineNumber, column: this.ab.getLineMaxColumn(lineNumber) });
    }
    const onDidChangeCursorPosition = () => {
      const model = this.Q.getModel();
      if (!model) {
        return;
      }
      const position = this.Q.getPosition();
      if (!position) {
        return;
      }
      const atTop = position.lineNumber === 1 && position.column - 1 <= (this.Q._getViewModel()?.getLineLength(1) ?? 0);
      this.cb.set(atTop);
      this.Y.set(atTop);
      this.Z.set(position.equals(getLastPosition(model)));
    };
    this.B(this.Q.onDidChangeCursorPosition((e) => onDidChangeCursorPosition()));
    onDidChangeCursorPosition();
    this.B(this.Lb.onDidFileIconThemeChange(() => {
      this.Zb();
    }));
  }
  async Zb() {
    const container2 = this.L;
    const oldHeight = container2.offsetHeight;
    const store = new $2c();
    this.M.value = store;
    $$i(container2);
    const hoverDelegate = store.add($KZ());
    const attachments = this.tb === ChatAgentLocation.EditingSession ? [...this.attachmentModel.attachments.entries()].filter(([_, attachment]) => !attachment.isFile || attachment.isFile && typeof attachment.value === "object" && !!attachment.value && "range" in attachment.value) : [...this.attachmentModel.attachments.entries()];
    $gk(Boolean(attachments.length) || Boolean(this.implicitContext?.value), this.L);
    if (!attachments.length) {
      this.u = -1;
    }
    if (this.implicitContext?.value) {
      const implicitPart = store.add(this.yb.createInstance($NNb, this.implicitContext, this.C));
      container2.appendChild(implicitPart.domNode);
    }
    const attachmentInitPromises = [];
    for (const [index, attachment] of attachments) {
      const widget = $bk(container2, $92(".chat-attached-context-attachment.show-file-icons"));
      const label3 = this.C.create(widget, { supportIcons: true, hoverDelegate, hoverTargetOverride: widget });
      let ariaLabel;
      let resource = URI.isUri(attachment.value) ? attachment.value : attachment.value && typeof attachment.value === "object" && "uri" in attachment.value && URI.isUri(attachment.value.uri) ? attachment.value.uri : void 0;
      let range = attachment.value && typeof attachment.value === "object" && "range" in attachment.value && $9C.isIRange(attachment.value.range) ? attachment.value.range : void 0;
      if (resource && (attachment.isFile || attachment.isDirectory)) {
        const fileBasename = $rc(resource.path);
        const fileDirname = $qc(resource.path);
        const friendlyName = `${fileBasename} ${fileDirname}`;
        ariaLabel = range ? localize(4924, null, friendlyName, range.startLineNumber, range.endLineNumber) : localize(4925, null, friendlyName);
        const fileOptions = { hidePath: true };
        label3.setFile(resource, attachment.isFile ? {
          ...fileOptions,
          fileKind: FileKind.FILE,
          range
        } : {
          ...fileOptions,
          fileKind: FileKind.FOLDER,
          icon: !this.Lb.getFileIconTheme().hasFolderIcons ? $js : void 0
        });
        this.ac(widget, index, attachment, hoverDelegate);
        this.yb.invokeFunction((accessor) => {
          if (resource) {
            store.add($NDb(accessor, widget, resource));
          }
        });
      } else if (attachment.isImage) {
        ariaLabel = localize(4926, null, attachment.name);
        const hoverElement = $("div.chat-attached-context-hover");
        hoverElement.setAttribute("aria-label", ariaLabel);
        const pillIcon = $("div.chat-attached-context-pill", {}, $("span.codicon.codicon-file-media"));
        const textLabel = $("span.chat-attached-context-custom-text", {}, attachment.name);
        widget.appendChild(pillIcon);
        widget.appendChild(textLabel);
        attachmentInitPromises.push(Promises.withAsyncBody(async (resolve) => {
          let buffer;
          try {
            this.ac(widget, index, attachment, hoverDelegate);
            if (attachment.value instanceof URI) {
              const readFile = await this.Gb.readFile(attachment.value);
              if (store.isDisposed) {
                return;
              }
              buffer = readFile.value.buffer;
            } else {
              buffer = attachment.value;
            }
            this.bc(buffer, widget, hoverElement);
          } catch (error) {
            console.error("Error processing attachment:", error);
          }
          widget.style.position = "relative";
          store.add(this.Fb.setupManagedHover(hoverDelegate, widget, hoverElement, { trapFocus: false }));
          resolve();
        }));
      } else if ($JO(attachment)) {
        ariaLabel = localize(4927, null, attachment.name);
        const classNames = ["file-icon", `${attachment.language}-lang-file-icon`];
        if (attachment.copiedFrom) {
          resource = attachment.copiedFrom.uri;
          range = attachment.copiedFrom.range;
          const filename = $rc(resource.path);
          label3.setLabel(filename, void 0, { extraClasses: classNames });
        } else {
          label3.setLabel(attachment.fileName, void 0, { extraClasses: classNames });
        }
        widget.appendChild($("span.attachment-additional-info", {}, `Pasted ${attachment.pastedLines}`));
        widget.style.position = "relative";
        const hoverContent = {
          markdown: {
            value: `${attachment.copiedFrom ? this.Ob.getUriLabel(attachment.copiedFrom.uri, { relative: true }) : attachment.fileName}

---

\`\`\`${attachment.language}

${attachment.code}
\`\`\``
          },
          markdownNotSupportedFallback: attachment.code
        };
        store.add(this.Fb.setupManagedHover(hoverDelegate, widget, hoverContent, { trapFocus: true }));
        this.ac(widget, index, attachment, hoverDelegate);
        const copiedFromResource = attachment.copiedFrom?.uri;
        if (copiedFromResource) {
          store.add(this.yb.invokeFunction((accessor) => $NDb(accessor, widget, copiedFromResource)));
        }
      } else {
        const attachmentLabel = attachment.fullName ?? attachment.name;
        const withIcon = attachment.icon?.id ? `$(${attachment.icon.id}) ${attachmentLabel}` : attachmentLabel;
        label3.setLabel(withIcon, void 0);
        ariaLabel = localize(4928, null, attachment.name);
        this.ac(widget, index, attachment, hoverDelegate);
      }
      if (attachment.kind === "symbol") {
        const scopedContextKeyService = store.add(this.zb.createScoped(widget));
        store.add(this.yb.invokeFunction((accessor) => $ODb(accessor, widget, scopedContextKeyService, { ...attachment, kind: attachment.symbolKind }, $bJ.ChatInputSymbolAttachmentContext)));
      }
      await Promise.all(attachmentInitPromises);
      if (store.isDisposed) {
        return;
      }
      if (resource) {
        widget.style.cursor = "pointer";
        store.add($_i(widget, $7j.CLICK, (e) => {
          $9j.stop(e, true);
          if (attachment.isDirectory) {
            this.$b(resource, true);
          } else {
            this.$b(resource, false, range);
          }
        }));
        store.add($_i(widget, $7j.KEY_DOWN, (e) => {
          const event = new $if(e);
          if (event.equals(
            3
            /* KeyCode.Enter */
          ) || event.equals(
            10
            /* KeyCode.Space */
          )) {
            $9j.stop(e, true);
            if (attachment.isDirectory) {
              this.$b(resource, true);
            } else {
              this.$b(resource, false, range);
            }
          }
        }));
      }
      widget.tabIndex = 0;
      widget.ariaLabel = ariaLabel;
    }
    if (oldHeight !== container2.offsetHeight) {
      this.g.fire();
    }
  }
  $b(resource, isDirectory, range) {
    if (isDirectory) {
      this.Hb.executeCommand($gzb.id, resource);
      return;
    }
    const openTextEditorOptions = range ? { selection: range } : void 0;
    const options3 = {
      fromUserGesture: true,
      editorOptions: openTextEditorOptions
    };
    this.Jb.open(resource, options3);
  }
  ac(widget, index, attachment, hoverDelegate) {
    const store = this.M.value;
    if (!store) {
      return;
    }
    const clearButton = new $k2(widget, {
      supportIcons: true,
      hoverDelegate,
      title: localize(4929, null)
    });
    if (index === Math.min(this.u, this.attachmentModel.size - 1)) {
      clearButton.focus();
    }
    store.add(clearButton);
    clearButton.icon = $6l.close;
    store.add(Event2.once(clearButton.onDidClick)((e) => {
      this.t.delete(attachment.id);
      if ($4j(e)) {
        const event = new $if(e);
        if (event.equals(
          3
          /* KeyCode.Enter */
        ) || event.equals(
          10
          /* KeyCode.Space */
        )) {
          this.u = index;
        }
      }
      if (this.t.size === 0) {
        this.focus();
      }
      this.r.fire({ removed: [attachment] });
    }));
  }
  // Helper function to create and replace image
  bc(buffer, widget, hoverElement) {
    const blob = new Blob([buffer], { type: "image/png" });
    const url = URL.createObjectURL(blob);
    const pillImg = $("img.chat-attached-context-pill-image", { src: url, alt: "" });
    const pill = $("div.chat-attached-context-pill", {}, pillImg);
    const existingPill = widget.querySelector(".chat-attached-context-pill");
    if (existingPill) {
      existingPill.replaceWith(pill);
    }
    const hoverImage = $("img.chat-attached-context-image", { src: url, alt: "" });
    hoverElement.appendChild(hoverImage);
    hoverImage.onload = () => {
      URL.revokeObjectURL(url);
    };
  }
  async renderChatEditingSessionState(chatEditingSession, chatWidget) {
    $gk(Boolean(chatEditingSession), this.N);
    if (!chatEditingSession) {
      $$i(this.N);
      this.lb.clear();
      this.pb = void 0;
      this.rb = [];
      this.nb?.dispose();
      return;
    }
    const currentChatEditingState = chatEditingSession.state.get();
    if (this.pb && !chatWidget?.viewModel?.requestInProgress && (currentChatEditingState === 2 || currentChatEditingState === 0)) {
      this.nb?.stop();
    }
    const innerContainer = this.N.querySelector(".chat-editing-session-container.show-file-icons") ?? $bk(this.N, $92(".chat-editing-session-container.show-file-icons"));
    const seenEntries = new $Fc();
    let entries2 = chatEditingSession?.entries.get().map((entry) => {
      seenEntries.add(entry.modifiedURI);
      return {
        reference: entry.modifiedURI,
        state: entry.state.get(),
        kind: "reference"
      };
    }) ?? [];
    for (const attachment of this.attachmentModel.fileAttachments) {
      if (URI.isUri(attachment.value) && !seenEntries.has(attachment.value)) {
        entries2.unshift({
          reference: attachment.value,
          state: 4,
          kind: "reference"
        });
        seenEntries.add(attachment.value);
      }
    }
    for (const [file, metadata] of chatEditingSession.workingSet.entries()) {
      if (!seenEntries.has(file) && metadata.state !== 6) {
        entries2.unshift({
          reference: file,
          state: metadata.state,
          description: metadata.description,
          kind: "reference"
        });
        seenEntries.add(file);
      }
    }
    for (const part of chatWidget?.parsedInput.parts ?? []) {
      if (part instanceof $EO && part.isFile && (URI.isUri(part.data) && !seenEntries.has(part.data) || $SE(part.data) && !seenEntries.has(part.data.uri))) {
        entries2.unshift({
          reference: part.data,
          state: 4,
          kind: "reference"
        });
      }
    }
    const excludedEntries = [];
    for (const excludedAttachment of this.attachmentModel.excludedFileAttachments) {
      if (excludedAttachment.isFile && URI.isUri(excludedAttachment.value) && !seenEntries.has(excludedAttachment.value)) {
        excludedEntries.push({
          reference: excludedAttachment.value,
          state: 4,
          kind: "reference",
          excluded: true,
          title: localize(4930, null, $rc(excludedAttachment.value.path))
        });
        seenEntries.add(excludedAttachment.value);
      }
    }
    entries2.sort((a, b) => {
      if (a.kind === "reference" && b.kind === "reference") {
        if (a.state === b.state || a.state === void 0 || b.state === void 0) {
          return a.reference.toString().localeCompare(b.reference.toString());
        }
        return a.state - b.state;
      }
      return 0;
    });
    let remainingFileEntriesBudget = this.Kb.editingSessionFileLimit;
    const overviewRegion = innerContainer.querySelector(".chat-editing-session-overview") ?? $bk(innerContainer, $92(".chat-editing-session-overview"));
    const overviewTitle = overviewRegion.querySelector(".working-set-title") ?? $bk(overviewRegion, $92(".working-set-title"));
    const overviewWorkingSet = overviewTitle.querySelector("span") ?? $bk(overviewTitle, $92("span"));
    const overviewFileCount = overviewTitle.querySelector("span.working-set-count") ?? $bk(overviewTitle, $92("span.working-set-count"));
    overviewWorkingSet.textContent = localize(4931, null);
    this.qb = entries2.length + excludedEntries.length;
    let suggestedFilesInWorkingSetCount = 0;
    overviewFileCount.textContent = "";
    if (entries2.length === 1) {
      overviewFileCount.textContent = " " + localize(4932, null);
      suggestedFilesInWorkingSetCount = entries2[0].kind === "reference" && entries2[0].state === 6 ? 1 : 0;
    } else if (entries2.length >= remainingFileEntriesBudget) {
      const entriesToPreserve = [];
      const newEntries = [];
      const suggestedFiles = [];
      for (let i2 = 0; i2 < entries2.length; i2 += 1) {
        const entry = entries2[i2];
        if (entry.kind !== "reference" || !URI.isUri(entry.reference)) {
          continue;
        }
        const currentEntryUri = entry.reference;
        if (entry.state === 6) {
          suggestedFiles.push(entry);
        } else if (this.rb.find((e) => e.toString() === currentEntryUri?.toString())) {
          if (remainingFileEntriesBudget > 0) {
            entriesToPreserve.push(entry);
            remainingFileEntriesBudget -= 1;
          }
        } else {
          newEntries.push(entry);
        }
      }
      const newEntriesThatFit = remainingFileEntriesBudget > 0 ? newEntries.slice(0, remainingFileEntriesBudget) : [];
      remainingFileEntriesBudget -= newEntriesThatFit.length;
      const suggestedFilesThatFit = remainingFileEntriesBudget > 0 ? suggestedFiles.slice(0, remainingFileEntriesBudget) : [];
      entries2 = [...entriesToPreserve, ...newEntriesThatFit, ...suggestedFilesThatFit];
      suggestedFilesInWorkingSetCount = suggestedFilesThatFit.length;
    } else {
      suggestedFilesInWorkingSetCount = entries2.filter(
        (e) => e.kind === "reference" && e.state === 6
        /* WorkingSetEntryState.Suggested */
      ).length;
    }
    if (excludedEntries.length > 0) {
      overviewFileCount.textContent = " " + localize(4933, null, this.Kb.editingSessionFileLimit + excludedEntries.length, this.Kb.editingSessionFileLimit);
    } else if (entries2.length > 1) {
      const fileCount = entries2.length - suggestedFilesInWorkingSetCount;
      overviewFileCount.textContent = " " + (fileCount === 1 ? localize(4934, null) : localize(4935, null, fileCount));
    }
    const fileLimitReached = remainingFileEntriesBudget <= 0;
    overviewFileCount.classList.toggle("file-limit-reached", fileLimitReached);
    if (fileLimitReached) {
      let title = localize(4936, null);
      title += excludedEntries.length === 1 ? " " + localize(4937, null) : "";
      title += excludedEntries.length > 1 ? " " + localize(4938, null, excludedEntries.length) : "";
      this.mb.value = $J1().setupDelayedHover(overviewFileCount, {
        content: title,
        appearance: { showPointer: true, compact: true },
        position: {
          hoverPosition: 3
          /* HoverPosition.ABOVE */
        }
      });
    } else {
      this.mb.clear();
    }
    this.kb.clear();
    const actionsContainer = overviewRegion.querySelector(".chat-editing-session-actions") ?? $bk(overviewRegion, $92(".chat-editing-session-actions"));
    this.kb.add(this.yb.createInstance($hsb, actionsContainer, $bJ.ChatEditingWidgetToolbar, {
      telemetrySource: this.ub.menus.telemetrySource,
      menuOptions: {
        arg: { sessionId: chatEditingSession.chatSessionId }
      },
      buttonConfigProvider: (action) => {
        if (action.id === $TNb.ID || action.id === $WNb.ID || action.id === $SNb.ID) {
          return { showIcon: true, showLabel: false, isSecondary: true };
        }
        return void 0;
      }
    }));
    if (!chatEditingSession) {
      return;
    }
    if (currentChatEditingState === 1 || chatWidget?.viewModel?.requestInProgress) {
      this.nb ??= new $02(innerContainer);
      this.nb?.infinite().show(500);
    }
    const workingSetContainer = innerContainer.querySelector(".chat-editing-session-list") ?? $bk(innerContainer, $92(".chat-editing-session-list"));
    if (!this.pb) {
      this.pb = this.ob.get();
      const list3 = this.pb.object;
      this.lb.add(this.pb);
      this.lb.add(list3.onDidFocus(() => {
        this.j.fire();
      }));
      this.lb.add(list3.onDidOpen((e) => {
        if (e.element?.kind === "reference" && URI.isUri(e.element.reference)) {
          const modifiedFileUri = e.element.reference;
          const entry = chatEditingSession.getEntry(modifiedFileUri);
          const diffInfo = entry?.diffInfo.get();
          const range = diffInfo?.changes.at(0)?.modified.toExclusiveRange();
          this.Ib.openEditor({
            resource: modifiedFileUri,
            options: {
              ...e.editorOptions,
              selection: range
            }
          }, e.sideBySide ? $oJ : $nJ);
        }
      }));
      this.lb.add($_i(list3.getHTMLElement(), "click", (e) => {
        if (!this.hasFocus()) {
          this.j.fire();
        }
      }, true));
      $bk(workingSetContainer, list3.getHTMLElement());
      $bk(innerContainer, workingSetContainer);
    }
    const maxItemsShown = 6;
    const itemsShown = Math.min(entries2.length + excludedEntries.length, maxItemsShown);
    const height = itemsShown * 22;
    const list2 = this.pb.object;
    list2.layout(height);
    list2.getHTMLElement().style.height = `${height}px`;
    list2.splice(0, list2.length, entries2);
    list2.splice(entries2.length, 0, excludedEntries);
    this.rb = $Mb(entries2.map((e) => e.kind === "reference" && URI.isUri(e.reference) ? e.reference : void 0));
    const addFilesElement = innerContainer.querySelector(".chat-editing-session-toolbar-actions") ?? $bk(innerContainer, $92(".chat-editing-session-toolbar-actions"));
    const hoverDelegate = $JZ("element");
    const button = this.kb.add(new $k2(addFilesElement, {
      supportIcons: true,
      secondary: true,
      hoverDelegate
    }));
    button.enabled = remainingFileEntriesBudget > 0;
    button.label = localize(4939, null, "$(add)");
    button.setTitle(button.enabled ? localize(4940, null) : localize(4941, null));
    this.kb.add(button.onDidClick(() => {
      this.Hb.executeCommand("workbench.action.chat.editing.attachFiles", { widget: chatWidget });
    }));
    $bk(addFilesElement, button.element);
    for (const [uri, metadata] of chatEditingSession.workingSet) {
      if (metadata.state !== 6) {
        continue;
      }
      const addBtn = this.kb.add(new $k2(addFilesElement, {
        supportIcons: true,
        secondary: true,
        hoverDelegate
      }));
      addBtn.enabled = remainingFileEntriesBudget > 0;
      addBtn.label = this.Ob.getUriBasenameLabel(uri);
      addBtn.element.classList.add("monaco-icon-label", ...$gdb(this.wb, this.xb, uri, FileKind.FILE));
      addBtn.setTitle(localize(4942, null, this.Ob.getUriLabel(uri, { relative: true }), metadata.description ?? ""));
      this.kb.add(addBtn.onDidClick(() => {
        group2.remove();
        chatEditingSession.addFileToWorkingSet(uri);
      }));
      const rmBtn = this.kb.add(new $k2(addFilesElement, {
        supportIcons: false,
        secondary: true,
        hoverDelegate
      }));
      rmBtn.icon = $6l.close;
      rmBtn.setTitle(localize(4943, null));
      this.kb.add(rmBtn.onDidClick(() => {
        group2.remove();
        chatEditingSession.remove(0, uri);
      }));
      const sep2 = document.createElement("div");
      sep2.classList.add("separator");
      const group2 = document.createElement("span");
      group2.classList.add("monaco-button-dropdown", "sidebyside-button");
      group2.appendChild(addBtn.element);
      group2.appendChild(sep2);
      group2.appendChild(rmBtn.element);
      $bk(addFilesElement, group2);
      this.kb.add($1c(() => {
        group2.remove();
      }));
    }
  }
  async renderFollowups(items, response) {
    if (!this.ub.renderFollowups) {
      return;
    }
    this.J.clear();
    $$i(this.I);
    if (items && items.length > 0) {
      this.J.add(this.yb.createInstance($XNb, this.I, items, this.tb, void 0, (followup) => this.s.fire({ followup, response })));
    }
    this.g.fire();
  }
  get contentHeight() {
    const data = this.ec();
    return data.followupsHeight + data.inputPartEditorHeight + data.inputPartVerticalPadding + data.inputEditorBorder + data.attachmentsHeight + data.toolbarsHeight + data.chatEditingStateHeight;
  }
  layout(height, width2) {
    this.hb = new $rj(width2, height);
    return this.dc(height, width2);
  }
  dc(height, width2, allowRecurse = true) {
    const data = this.ec();
    const inputEditorHeight = Math.min(data.inputPartEditorHeight, height - data.followupsHeight - data.attachmentsHeight - data.inputPartVerticalPadding - data.toolbarsHeight);
    const followupsWidth = width2 - data.inputPartHorizontalPadding;
    this.I.style.width = `${followupsWidth}px`;
    this.O = data.inputPartVerticalPadding + data.followupsHeight + inputEditorHeight + data.inputEditorBorder + data.attachmentsHeight + data.toolbarsHeight + data.chatEditingStateHeight;
    this.P = data.followupsHeight;
    const initialEditorScrollWidth = this.Q.getScrollWidth();
    const newEditorWidth = width2 - data.inputPartHorizontalPadding - data.editorBorder - data.inputPartHorizontalPaddingInside - data.toolbarsWidth - data.sideToolbarWidth;
    const newDimension = { width: newEditorWidth, height: inputEditorHeight };
    if (!this.cc || (this.cc.width !== newDimension.width || this.cc.height !== newDimension.height)) {
      this.Q.layout(newDimension);
      this.cc = newDimension;
    }
    if (allowRecurse && initialEditorScrollWidth < 10) {
      return this.dc(height, width2, false);
    }
  }
  ec() {
    const executeToolbarWidth = this.ib = this.S.getItemsWidth();
    const inputToolbarWidth = this.jb = this.U.getItemsWidth();
    const executeToolbarPadding = (this.S.getItemsLength() - 1) * 4;
    const inputToolbarPadding = this.U.getItemsLength() ? (this.U.getItemsLength() - 1) * 4 : 0;
    return {
      inputEditorBorder: 2,
      followupsHeight: this.I.offsetHeight,
      inputPartEditorHeight: Math.min(this.Q.getContentHeight(), this.D),
      inputPartHorizontalPadding: this.ub.renderStyle === "compact" ? 16 : 32,
      inputPartVerticalPadding: this.ub.renderStyle === "compact" ? 12 : 28,
      attachmentsHeight: this.L.offsetHeight,
      editorBorder: 2,
      inputPartHorizontalPaddingInside: 12,
      toolbarsWidth: this.ub.renderStyle === "compact" ? executeToolbarWidth + executeToolbarPadding + inputToolbarWidth + inputToolbarPadding : 0,
      toolbarsHeight: this.ub.renderStyle === "compact" ? 0 : 22,
      chatEditingStateHeight: this.N.offsetHeight,
      sideToolbarWidth: this.H ? $xj(this.H) + 4 : 0
    };
  }
  getViewState() {
    return this.sb();
  }
  saveState() {
    this.Wb(this.sb());
    const inputHistory = [...this.X];
    this.vb.saveHistory(this.tb, inputHistory);
  }
};
$1Nb = $1Nb_1 = __decorate([
  __param(4, $jzb),
  __param(5, $sG),
  __param(6, $1E),
  __param(7, $Pk),
  __param(8, $on),
  __param(9, $kl),
  __param(10, $Ty),
  __param(11, $ND),
  __param(12, $GN),
  __param(13, $wn),
  __param(14, $5$),
  __param(15, $km),
  __param(16, $sn),
  __param(17, $mJ),
  __param(18, $O4),
  __param(19, $$O),
  __param(20, $gs),
  __param(21, $oG),
  __param(22, $jv),
  __param(23, $ZI)
], $1Nb);
var historyKeyFn = (entry) => JSON.stringify(entry);
function getLastPosition(model) {
  return { lineNumber: model.getLineCount(), column: model.getLineLength(model.getLineCount()) + 1 };
}
var ChatSubmitDropdownActionItem = class ChatSubmitDropdownActionItem2 extends $isb {
  constructor(action, dropdownAction, options3, menuService, contextMenuService, chatAgentService, contextKeyService, keybindingService, notificationService, themeService, accessibilityService) {
    super(action, dropdownAction, [], "", {
      ...options3,
      getKeyBinding: (action2) => keybindingService.lookupKeybinding(action2.id, contextKeyService)
    }, contextMenuService, keybindingService, notificationService, contextKeyService, themeService, accessibilityService);
    const menu = menuService.createMenu($bJ.ChatExecuteSecondary, contextKeyService);
    const setActions = () => {
      const secondary = $R$(menu.getActions({ shouldForwardArgs: true }));
      const secondaryAgent = chatAgentService.getSecondaryAgent();
      if (secondaryAgent) {
        secondary.forEach((a) => {
          if (a.id === $KNb.ID) {
            a.label = localize(4944, null, secondaryAgent.name);
          }
          return a;
        });
      }
      this.update(dropdownAction, secondary);
    };
    setActions();
    this.B(menu.onDidChange(() => setActions()));
  }
};
ChatSubmitDropdownActionItem = __decorate([
  __param(3, $cJ),
  __param(4, $50),
  __param(5, $ZO),
  __param(6, $on),
  __param(7, $Ty),
  __param(8, $PJ),
  __param(9, $gs),
  __param(10, $ND)
], ChatSubmitDropdownActionItem);
var ModelPickerActionViewItem = class ModelPickerActionViewItem2 extends $T$ {
  constructor(action, c, g, options3, keybindingService, notificationService, contextKeyService, themeService, contextMenuService, y, _accessibilityService) {
    super(action, options3, keybindingService, notificationService, contextKeyService, themeService, contextMenuService, _accessibilityService);
    this.c = c;
    this.g = g;
    this.y = y;
    this.B(g.onDidChangeModel((modelId) => {
      this.c = modelId;
      this.C();
    }));
  }
  async onClick(event) {
    this.lb();
  }
  render(container2) {
    super.render(container2);
    container2.classList.add("chat-modelPicker-item");
    this.B($_i(container2, $7j.KEY_UP, (e) => {
      const event = new $if(e);
      if (event.equals(
        3
        /* KeyCode.Enter */
      ) || event.equals(
        10
        /* KeyCode.Space */
      )) {
        this.lb();
      }
    }));
  }
  C() {
    if (this.L) {
      const model = this.y.lookupLanguageModel(this.c);
      if (model) {
        $dk(this.L, $("span.chat-model-label", void 0, model.name), ...$B1(`$(chevron-down)`));
      }
    }
  }
  lb() {
    const setLanguageModelAction = (id2, modelMetadata) => {
      return {
        id: id2,
        label: modelMetadata.name,
        tooltip: "",
        class: void 0,
        enabled: true,
        checked: id2 === this.c,
        run: () => {
          this.c = id2;
          this.C();
          this.g.setModel(id2);
        }
      };
    };
    const models = this.y.getLanguageModelIds().map((modelId) => ({ id: modelId, model: this.y.lookupLanguageModel(modelId) })).filter((entry) => entry.model?.isUserSelectable);
    models.sort((a, b) => a.model.name.localeCompare(b.model.name));
    this.bb.showContextMenu({
      getAnchor: () => this.element,
      getActions: () => models.map((entry) => setLanguageModelAction(entry.id, entry.model))
    });
  }
};
ModelPickerActionViewItem = __decorate([
  __param(4, $Ty),
  __param(5, $PJ),
  __param(6, $on),
  __param(7, $gs),
  __param(8, $50),
  __param(9, $GN),
  __param(10, $ND)
], ModelPickerActionViewItem);
var chatInputEditorContainerSelector = ".interactive-input-editor";
$2sb(chatInputEditorContainerSelector);

// out-build/vs/workbench/contrib/chat/common/chatSlashCommands.js
var $sO = $Qk("chatSlashCommandService");
var $tO = class $tO2 extends $3c {
  constructor(f) {
    super();
    this.f = f;
    this.a = /* @__PURE__ */ new Map();
    this.b = this.B(new $ze());
    this.onDidChangeCommands = this.b.event;
  }
  dispose() {
    super.dispose();
    this.a.clear();
  }
  registerSlashCommand(data, command4) {
    if (this.a.has(data.command)) {
      throw new Error(`Already registered a command with id ${data.command}}`);
    }
    this.a.set(data.command, { data, command: command4 });
    this.b.fire();
    return $1c(() => {
      if (this.a.delete(data.command)) {
        this.b.fire();
      }
    });
  }
  getCommands(location3) {
    return Array.from(this.a.values(), (v) => v.data).filter((c) => c.locations.includes(location3));
  }
  hasCommand(id2) {
    return this.a.has(id2);
  }
  async executeCommand(id2, prompt, progress, history, location3, token) {
    const data = this.a.get(id2);
    if (!data) {
      throw new Error("No command with id ${id} NOT registered");
    }
    if (!data.command) {
      await this.f.activateByEvent(`onSlash:${id2}`);
    }
    if (!data.command) {
      throw new Error(`No command with id ${id2} NOT resolved`);
    }
    return await data.command(prompt, progress, history, location3, token);
  }
};
$tO = __decorate([
  __param(0, $wN)
], $tO);

// out-build/vs/workbench/contrib/chat/common/languageModelToolsService.js
var $mO = $Qk("ILanguageModelToolsService");

// out-build/vs/workbench/contrib/chat/common/chatRequestParser.js
var agentReg = /^@([\w_\-\.]+)(?=(\s|$|\b))/i;
var variableReg = /^#([\w_\-]+)(:\d+)?(?=(\s|$|\b))/i;
var slashReg = /\/([\w_\-]+)(?=(\s|$|\b))/i;
var $nO = class $nO2 {
  constructor(b, d, e, f) {
    this.b = b;
    this.d = d;
    this.e = e;
    this.f = f;
  }
  parseChatRequest(sessionId, message, location3 = ChatAgentLocation.Panel, context) {
    const parts = [];
    const references = this.d.getDynamicVariables(sessionId);
    let lineNumber = 1;
    let column = 1;
    for (let i2 = 0; i2 < message.length; i2++) {
      const previousChar = message.charAt(i2 - 1);
      const char = message.charAt(i2);
      let newPart;
      if (previousChar.match(/\s/) || i2 === 0) {
        if (char === $wO) {
          newPart = this.h(message.slice(i2), i2, new $8C(lineNumber, column), parts);
        } else if (char === $xO) {
          newPart = this.g(message.slice(i2), message, i2, new $8C(lineNumber, column), parts, location3, context);
        } else if (char === $yO) {
          newPart = this.j(message.slice(i2), message, i2, new $8C(lineNumber, column), parts, location3);
        }
        if (!newPart) {
          newPart = this.k(message.slice(i2), i2, new $8C(lineNumber, column), references);
        }
      }
      if (newPart) {
        if (i2 !== 0) {
          const previousPart = parts.at(-1);
          const previousPartEnd = previousPart?.range.endExclusive ?? 0;
          const previousPartEditorRangeEndLine = previousPart?.editorRange.endLineNumber ?? 1;
          const previousPartEditorRangeEndCol = previousPart?.editorRange.endColumn ?? 1;
          parts.push(new $vO(new $0C(previousPartEnd, i2), new $9C(previousPartEditorRangeEndLine, previousPartEditorRangeEndCol, lineNumber, column), message.slice(previousPartEnd, i2)));
        }
        parts.push(newPart);
      }
      if (char === "\n") {
        lineNumber++;
        column = 1;
      } else {
        column++;
      }
    }
    const lastPart = parts.at(-1);
    const lastPartEnd = lastPart?.range.endExclusive ?? 0;
    if (lastPartEnd < message.length) {
      parts.push(new $vO(new $0C(lastPartEnd, message.length), new $9C(lastPart?.editorRange.endLineNumber ?? 1, lastPart?.editorRange.endColumn ?? 1, lineNumber, column), message.slice(lastPartEnd, message.length)));
    }
    return {
      parts,
      text: message
    };
  }
  g(message, fullMessage, offset, position, parts, location3, context) {
    const nextAgentMatch = message.match(agentReg);
    if (!nextAgentMatch) {
      return;
    }
    const [full, name] = nextAgentMatch;
    const agentRange = new $0C(offset, offset + full.length);
    const agentEditorRange = new $9C(position.lineNumber, position.column, position.lineNumber, position.column + full.length);
    let agents = this.b.getAgentsByName(name);
    if (!agents.length) {
      const fqAgent = this.b.getAgentByFullyQualifiedId(name);
      if (fqAgent) {
        agents = [fqAgent];
      }
    }
    const agent = agents.length > 1 && context?.selectedAgent ? context.selectedAgent : agents.find((a) => a.locations.includes(location3));
    if (!agent) {
      return;
    }
    if (parts.some((p) => p instanceof $BO)) {
      return;
    }
    if (parts.some((p) => p instanceof $vO && p.text.trim() !== "" || !(p instanceof $BO))) {
      return;
    }
    const previousPart = parts.at(-1);
    const previousPartEnd = previousPart?.range.endExclusive ?? 0;
    const textSincePreviousPart = fullMessage.slice(previousPartEnd, offset);
    if (textSincePreviousPart.trim() !== "") {
      return;
    }
    return new $BO(agentRange, agentEditorRange, agent);
  }
  h(message, offset, position, parts) {
    const nextVariableMatch = message.match(variableReg);
    if (!nextVariableMatch) {
      return;
    }
    const [full, name] = nextVariableMatch;
    const variableArg = nextVariableMatch[2] ?? "";
    const varRange = new $0C(offset, offset + full.length);
    const varEditorRange = new $9C(position.lineNumber, position.column, position.lineNumber, position.column + full.length);
    const usedAgent = parts.find((p) => p instanceof $BO);
    const allowSlow = !usedAgent || usedAgent.agent.metadata.supportsSlowVariables;
    const variable = this.d.getVariable(name);
    if (variable && (!variable.isSlow || allowSlow)) {
      return new $zO(varRange, varEditorRange, name, variableArg, variable.id);
    }
    const tool = this.f.getToolByName(name);
    if (tool && tool.canBeReferencedInPrompt) {
      return new $AO(varRange, varEditorRange, name, tool.id, tool.displayName, tool.icon);
    }
    return;
  }
  j(remainingMessage, fullMessage, offset, position, parts, location3) {
    const nextSlashMatch = remainingMessage.match(slashReg);
    if (!nextSlashMatch) {
      return;
    }
    if (parts.some((p) => p instanceof $DO)) {
      return;
    }
    const [full, command4] = nextSlashMatch;
    const slashRange = new $0C(offset, offset + full.length);
    const slashEditorRange = new $9C(position.lineNumber, position.column, position.lineNumber, position.column + full.length);
    const usedAgent = parts.find((p) => p instanceof $BO);
    if (usedAgent) {
      if (parts.some((p) => p instanceof $vO && p.text.trim() !== "" || !(p instanceof $BO) && !(p instanceof $vO))) {
        return;
      }
      const previousPart = parts.at(-1);
      const previousPartEnd = previousPart?.range.endExclusive ?? 0;
      const textSincePreviousPart = fullMessage.slice(previousPartEnd, offset);
      if (textSincePreviousPart.trim() !== "") {
        return;
      }
      const subCommand = usedAgent.agent.slashCommands.find((c) => c.name === command4);
      if (subCommand) {
        return new $CO(slashRange, slashEditorRange, subCommand);
      }
    } else {
      const slashCommands = this.e.getCommands(location3);
      const slashCommand = slashCommands.find((c) => c.command === command4);
      if (slashCommand) {
        return new $DO(slashRange, slashEditorRange, slashCommand);
      } else {
        const defaultAgent = this.b.getDefaultAgent(location3);
        const subCommand = defaultAgent?.slashCommands.find((c) => c.name === command4);
        if (subCommand) {
          return new $CO(slashRange, slashEditorRange, subCommand);
        }
      }
    }
    return;
  }
  k(message, offset, position, references) {
    const refAtThisPosition = references.find((r2) => r2.range.startLineNumber === position.lineNumber && r2.range.startColumn === position.column);
    if (refAtThisPosition) {
      const length = refAtThisPosition.range.endColumn - refAtThisPosition.range.startColumn;
      const text2 = message.substring(0, length);
      const range = new $0C(offset, offset + length);
      return new $EO(range, refAtThisPosition.range, text2, refAtThisPosition.id, refAtThisPosition.modelDescription, refAtThisPosition.data, refAtThisPosition.fullName, refAtThisPosition.icon, refAtThisPosition.isFile);
    }
    return;
  }
};
$nO = __decorate([
  __param(0, $ZO),
  __param(1, $kO),
  __param(2, $sO),
  __param(3, $mO)
], $nO);

// out-build/vs/workbench/contrib/chat/common/codeBlockModelCollection.js
var $$rb = class $$rb2 extends $3c {
  constructor(c, f) {
    super();
    this.c = c;
    this.f = f;
    this.a = /* @__PURE__ */ new Map();
    this.b = 100;
  }
  dispose() {
    super.dispose();
    this.clear();
  }
  get(sessionId, chat, codeBlockIndex) {
    const entry = this.a.get(this.m(sessionId, chat, codeBlockIndex));
    if (!entry) {
      return;
    }
    return {
      model: entry.model.then((ref) => ref.object.textEditorModel),
      vulns: entry.vulns,
      codemapperUri: entry.codemapperUri
    };
  }
  getOrCreate(sessionId, chat, codeBlockIndex) {
    const existing = this.get(sessionId, chat, codeBlockIndex);
    if (existing) {
      return existing;
    }
    const uri = this.n(sessionId, chat, codeBlockIndex);
    const model = this.f.createModelReference(uri);
    this.a.set(this.m(sessionId, chat, codeBlockIndex), {
      model,
      vulns: [],
      codemapperUri: void 0
    });
    while (this.a.size > this.b) {
      const first = Iterable.first(this.a.keys());
      if (!first) {
        break;
      }
      this.g(first);
    }
    return { model: model.then((x) => x.object.textEditorModel), vulns: [], codemapperUri: void 0 };
  }
  g(key2) {
    const entry = this.a.get(key2);
    if (!entry) {
      return;
    }
    entry.model.then((ref) => ref.object.dispose());
    this.a.delete(key2);
  }
  clear() {
    this.a.forEach(async (entry) => (await entry.model).dispose());
    this.a.clear();
  }
  updateSync(sessionId, chat, codeBlockIndex, content) {
    const entry = this.getOrCreate(sessionId, chat, codeBlockIndex);
    const extractedVulns = $8rb(content.text);
    const newText = fixCodeText(extractedVulns.newText, content.languageId);
    this.j(sessionId, chat, codeBlockIndex, extractedVulns.vulnerabilities);
    const codeblockUri = $7rb(newText);
    if (codeblockUri) {
      this.h(sessionId, chat, codeBlockIndex, codeblockUri.uri);
    }
    if (content.isComplete) {
      this.markCodeBlockCompleted(sessionId, chat, codeBlockIndex);
    }
    return this.get(sessionId, chat, codeBlockIndex) ?? entry;
  }
  markCodeBlockCompleted(sessionId, chat, codeBlockIndex) {
    const entry = this.a.get(this.m(sessionId, chat, codeBlockIndex));
    if (!entry) {
      return;
    }
  }
  async update(sessionId, chat, codeBlockIndex, content) {
    const entry = this.getOrCreate(sessionId, chat, codeBlockIndex);
    const extractedVulns = $8rb(content.text);
    let newText = fixCodeText(extractedVulns.newText, content.languageId);
    this.j(sessionId, chat, codeBlockIndex, extractedVulns.vulnerabilities);
    const codeblockUri = $7rb(newText);
    if (codeblockUri) {
      this.h(sessionId, chat, codeBlockIndex, codeblockUri.uri);
      newText = codeblockUri.textWithoutResult;
    }
    if (content.isComplete) {
      this.markCodeBlockCompleted(sessionId, chat, codeBlockIndex);
    }
    const textModel = await entry.model;
    if (textModel.isDisposed()) {
      return entry;
    }
    if (content.languageId) {
      const vscodeLanguageId = this.c.getLanguageIdByLanguageName(content.languageId);
      if (vscodeLanguageId && vscodeLanguageId !== textModel.getLanguageId()) {
        textModel.setLanguage(vscodeLanguageId);
      }
    }
    const currentText = textModel.getValue(
      1
      /* EndOfLinePreference.LF */
    );
    if (newText === currentText) {
      return entry;
    }
    if (newText.startsWith(currentText)) {
      const text2 = newText.slice(currentText.length);
      const lastLine = textModel.getLineCount();
      const lastCol = textModel.getLineMaxColumn(lastLine);
      textModel.applyEdits([{ range: new $9C(lastLine, lastCol, lastLine, lastCol), text: text2 }]);
    } else {
      textModel.setValue(newText);
    }
    return entry;
  }
  h(sessionId, chat, codeBlockIndex, codemapperUri) {
    const entry = this.a.get(this.m(sessionId, chat, codeBlockIndex));
    if (entry) {
      entry.codemapperUri = codemapperUri;
    }
  }
  j(sessionId, chat, codeBlockIndex, vulnerabilities) {
    const entry = this.a.get(this.m(sessionId, chat, codeBlockIndex));
    if (entry) {
      entry.vulns = vulnerabilities;
    }
  }
  m(sessionId, chat, index) {
    return `${sessionId}/${chat.id}/${index}`;
  }
  n(sessionId, chat, index) {
    const metadata = this.r(chat);
    return URI.from({
      scheme: Schemas.vscodeChatCodeBlock,
      authority: sessionId,
      path: `/${chat.id}/${index}`,
      fragment: metadata ? JSON.stringify(metadata) : void 0
    });
  }
  r(chat) {
    if (!$asb(chat)) {
      return void 0;
    }
    return {
      references: chat.contentReferences.map((ref) => {
        if (typeof ref.reference === "string") {
          return;
        }
        const uriOrLocation = "variableName" in ref.reference ? ref.reference.value : ref.reference;
        if (!uriOrLocation) {
          return;
        }
        if (URI.isUri(uriOrLocation)) {
          return {
            uri: uriOrLocation.toJSON()
          };
        }
        return {
          uri: uriOrLocation.uri.toJSON(),
          range: uriOrLocation.range
        };
      })
    };
  }
};
$$rb = __decorate([
  __param(0, $1E),
  __param(1, $oG)
], $$rb);
function fixCodeText(text2, languageId) {
  if (languageId === "php") {
    if (!text2.trim().startsWith("<")) {
      return `<?php
${text2}`;
    }
  }
  return text2;
}

// out-build/vs/workbench/contrib/chat/browser/chatAccessibilityProvider.js
var $4zb = class $4zb2 {
  constructor(a) {
    this.a = a;
  }
  getWidgetRole() {
    return "list";
  }
  getRole(element) {
    return "listitem";
  }
  getWidgetAriaLabel() {
    return localize(4772, null);
  }
  getAriaLabel(element) {
    if ($_rb(element)) {
      return element.messageText;
    }
    if ($asb(element)) {
      return this.b(element);
    }
    return "";
  }
  b(element) {
    const accessibleViewHint = this.a.getOpenAriaHint(
      "accessibility.verbosity.panelChat"
      /* AccessibilityVerbositySettingId.Chat */
    );
    let label3 = "";
    const fileTreeCount = element.response.value.filter((v) => !("value" in v))?.length ?? 0;
    let fileTreeCountHint = "";
    switch (fileTreeCount) {
      case 0:
        break;
      case 1:
        fileTreeCountHint = localize(4773, null);
        break;
      default:
        fileTreeCountHint = localize(4774, null, fileTreeCount);
        break;
    }
    const codeBlockCount = marked.lexer(element.response.toString()).filter((token) => token.type === "code")?.length ?? 0;
    switch (codeBlockCount) {
      case 0:
        label3 = accessibleViewHint ? localize(4775, null, fileTreeCountHint, element.response.toString(), accessibleViewHint) : localize(4776, null, fileTreeCountHint, element.response.toString());
        break;
      case 1:
        label3 = accessibleViewHint ? localize(4777, null, fileTreeCountHint, element.response.toString(), accessibleViewHint) : localize(4778, null, fileTreeCountHint, element.response.toString());
        break;
      default:
        label3 = accessibleViewHint ? localize(4779, null, fileTreeCountHint, codeBlockCount, element.response.toString(), accessibleViewHint) : localize(4780, null, fileTreeCountHint, codeBlockCount, element.response.toString());
        break;
    }
    return label3;
  }
};
$4zb = __decorate([
  __param(0, $shb)
], $4zb);

// out-build/vs/workbench/contrib/issue/common/issue.js
var IssueType;
(function(IssueType2) {
  IssueType2[IssueType2["Bug"] = 0] = "Bug";
  IssueType2[IssueType2["PerformanceIssue"] = 1] = "PerformanceIssue";
  IssueType2[IssueType2["FeatureRequest"] = 2] = "FeatureRequest";
})(IssueType || (IssueType = {}));
var IssueSource;
(function(IssueSource3) {
  IssueSource3["VSCode"] = "vscode";
  IssueSource3["Extension"] = "extension";
  IssueSource3["Marketplace"] = "marketplace";
})(IssueSource || (IssueSource = {}));
var $5zb = $Qk("issueFormService");
var $6zb = $Qk("workbenchIssueService");
var $7zb = $Qk("workbenchProcessService");

// out-build/vs/workbench/contrib/inlineChat/common/inlineChat.js
var InlineChatConfigKeys;
(function(InlineChatConfigKeys2) {
  InlineChatConfigKeys2["Mode"] = "inlineChat.mode";
  InlineChatConfigKeys2["FinishOnType"] = "inlineChat.finishOnType";
  InlineChatConfigKeys2["AcceptedOrDiscardBeforeSave"] = "inlineChat.acceptedOrDiscardBeforeSave";
  InlineChatConfigKeys2["StartWithOverlayWidget"] = "inlineChat.startWithOverlayWidget";
  InlineChatConfigKeys2["HoldToSpeech"] = "inlineChat.holdToSpeech";
  InlineChatConfigKeys2["AccessibleDiffView"] = "inlineChat.accessibleDiffView";
  InlineChatConfigKeys2["LineEmptyHint"] = "inlineChat.lineEmptyHint";
  InlineChatConfigKeys2["LineNLHint"] = "inlineChat.lineNaturalLanguageHint";
})(InlineChatConfigKeys || (InlineChatConfigKeys = {}));
var EditMode;
(function(EditMode2) {
  EditMode2["Live"] = "live";
  EditMode2["Preview"] = "preview";
})(EditMode || (EditMode = {}));
$Wn.as($Ht.Configuration).registerConfiguration({
  id: "editor",
  properties: {
    [
      "inlineChat.mode"
      /* InlineChatConfigKeys.Mode */
    ]: {
      description: localize(7509, null),
      default: "live",
      type: "string",
      enum: [
        "live",
        "preview"
        /* EditMode.Preview */
      ],
      markdownEnumDescriptions: [
        localize(7510, null),
        localize(7511, null)
      ]
    },
    [
      "inlineChat.finishOnType"
      /* InlineChatConfigKeys.FinishOnType */
    ]: {
      description: localize(7512, null),
      default: false,
      type: "boolean"
    },
    [
      "inlineChat.holdToSpeech"
      /* InlineChatConfigKeys.HoldToSpeech */
    ]: {
      description: localize(7513, null),
      default: true,
      type: "boolean"
    },
    [
      "inlineChat.accessibleDiffView"
      /* InlineChatConfigKeys.AccessibleDiffView */
    ]: {
      description: localize(7514, null),
      default: "auto",
      type: "string",
      enum: ["auto", "on", "off"],
      markdownEnumDescriptions: [
        localize(7515, null),
        localize(7516, null),
        localize(7517, null)
      ]
    },
    [
      "inlineChat.lineEmptyHint"
      /* InlineChatConfigKeys.LineEmptyHint */
    ]: {
      description: localize(7518, null),
      default: false,
      type: "boolean",
      tags: ["experimental"]
    },
    [
      "inlineChat.lineNaturalLanguageHint"
      /* InlineChatConfigKeys.LineNLHint */
    ]: {
      markdownDescription: localize(7519, null),
      default: true,
      type: "boolean",
      tags: ["experimental"]
    }
  }
});
var $8zb = "interactiveEditor";
var InlineChatResponseType;
(function(InlineChatResponseType2) {
  InlineChatResponseType2["None"] = "none";
  InlineChatResponseType2["Messages"] = "messages";
  InlineChatResponseType2["MessagesAndEdits"] = "messagesAndEdits";
})(InlineChatResponseType || (InlineChatResponseType = {}));
var $0zb = new $nn("inlineChatPossible", false, localize(7520, null));
var $$zb = new $nn("inlineChatHasProvider", false, localize(7521, null));
var $_zb = new $nn("inlineChatVisible", false, localize(7522, null));
var $aAb = new $nn("inlineChatFocused", false, localize(7523, null));
var $bAb = new $nn("inlineChatEditing", true, localize(7524, null));
var $cAb = new $nn("inlineChatResponseFocused", false, localize(7525, null));
var $dAb = new $nn("inlineChatEmpty", false, localize(7526, null));
var $eAb = new $nn("inlineChatInnerCursorFirst", false, localize(7527, null));
var $fAb = new $nn("inlineChatInnerCursorLast", false, localize(7528, null));
var $gAb = new $nn("inlineChatInnerCursorStart", false, localize(7529, null));
var $hAb = new $nn("inlineChatInnerCursorEnd", false, localize(7530, null));
var $iAb = new $nn("inlineChatOuterCursorPosition", "", localize(7531, null));
var $jAb = new $nn("inlineChatHasStashedSession", false, localize(7532, null));
var $kAb = new $nn("inlineChatUserDidEdit", void 0, localize(7533, null));
var $lAb = new $nn("inlineChatDocumentChanged", false, localize(7534, null));
var $mAb = new $nn("inlineChatChangeHasDiff", false, localize(7535, null));
var $nAb = new $nn("inlineChatChangeShowsDiff", false, localize(7536, null));
var $oAb = new $nn(
  "config.inlineChat.mode",
  "live"
  /* EditMode.Live */
);
var $pAb = new $nn("inlineChatRequestInProgress", false, localize(7537, null));
var $qAb = new $nn("inlineChatResponseType", "none", localize(7538, null));
var $rAb = "inlineChat.start";
var $sAb = "inlineChat.acceptChanges";
var $tAb = "inlineChat.discardHunkChange";
var $uAb = "inlineChat.regenerate";
var $vAb = "inlineChat.viewInChat";
var $wAb = "inlineChat.toggleDiff";
var $xAb = "inlineChat.reportIssue";
var $yAb = $bJ.for("inlineChatWidget.status");
var $zAb = $bJ.for("inlineChatWidget.secondary");
var $AAb = $bJ.for("inlineChatWidget.changesZone");
var $BAb = $5n("inlineChat.foreground", $Ro, localize(7539, null));
var $CAb = $5n("inlineChat.background", $Qo, localize(7540, null));
var $DAb = $5n("inlineChat.border", $So, localize(7541, null));
var $EAb = $5n("inlineChat.shadow", $Rp, localize(7542, null));
var $FAb = $5n("inlineChatInput.border", $So, localize(7543, null));
var $GAb = $5n("inlineChatInput.focusBorder", $jo, localize(7544, null));
var $HAb = $5n("inlineChatInput.placeholderForeground", $Eq, localize(7545, null));
var $IAb = $5n("inlineChatInput.background", $xq, localize(7546, null));
var $JAb = $5n("inlineChatDiff.inserted", $0n($Cp, 0.5), localize(7547, null));
var $KAb = $5n("editorOverviewRuler.inlineChatInserted", { dark: $0n($Cp, 0.6), light: $0n($Cp, 0.8), hcDark: $0n($Cp, 0.6), hcLight: $0n($Cp, 0.8) }, localize(7548, null));
var $LAb = $5n("editorOverviewRuler.inlineChatInserted", { dark: $0n($Cp, 0.6), light: $0n($Cp, 0.8), hcDark: $0n($Cp, 0.6), hcLight: $0n($Cp, 0.8) }, localize(7549, null));
var $MAb = $5n("inlineChatDiff.removed", $0n($Dp, 0.5), localize(7550, null));
var $NAb = $5n("editorOverviewRuler.inlineChatRemoved", { dark: $0n($Dp, 0.6), light: $0n($Dp, 0.8), hcDark: $0n($Dp, 0.6), hcLight: $0n($Dp, 0.8) }, localize(7551, null));

// out-build/vs/workbench/contrib/notebook/common/notebookContextKeys.js
var $OAb = new $nn("userHasOpenedNotebook", false);
var $PAb = new $nn("notebookFindWidgetFocused", false);
var $QAb = new $nn("interactiveWindowOpen", false);
var $RAb = new $nn("mostRecentReplEditor", void 0);
var $SAb = $7m.equals("activeEditor", $bM);
var $TAb = $7m.equals("activeEditor", $eM);
var $UAb = $7m.equals("activeEditor", $fM);
var $VAb = new $nn("isCompositeNotebook", false);
var $WAb = new $nn("notebookEditorFocused", false);
var $XAb = new $nn("notebookCellListFocused", false);
var $YAb = new $nn("notebookOutputFocused", false);
var $ZAb = new $nn("notebookOutputInputFocused", false);
var $1Ab = new $nn("notebookEditable", true);
var $2Ab = new $nn("notebookHasRunningCell", false);
var $3Ab = new $nn("notebookHasSomethingRunning", false);
var $4Ab = new $nn("notebookUseConsolidatedOutputButton", false);
var $5Ab = new $nn("notebookBreakpointMargin", false);
var $6Ab = new $nn("notebookCellToolbarLocation", "left");
var $7Ab = new $nn("notebookCursorNavigationMode", false);
var $8Ab = new $nn("notebookLastCellFailed", false);
var $9Ab = new $nn("notebookType", void 0);
var $0Ab = new $nn("notebookCellType", void 0);
var $$Ab = new $nn("notebookCellEditable", false);
var $_Ab = new $nn("notebookCellFocused", false);
var $aBb = new $nn("notebookCellEditorFocused", false);
var $bBb = new $nn("notebookCellMarkdownEditMode", false);
var $cBb = new $nn("notebookCellLineNumbers", "inherit");
var $dBb = new $nn("notebookCellExecutionState", void 0);
var $eBb = new $nn("notebookCellExecuting", false);
var $fBb = new $nn("notebookCellHasOutputs", false);
var $gBb = new $nn("notebookCellIsFirstOutput", false);
var $hBb = new $nn("hasHiddenOutputs", false);
var $iBb = new $nn("notebookCellInputIsCollapsed", false);
var $jBb = new $nn("notebookCellOutputIsCollapsed", false);
var $kBb = new $nn("notebookCellResource", "");
var $lBb = new $nn("notebookCellGenerateByChat", false);
var $mBb = new $nn("notebookCellHasErrorDiagnostics", false);
var $nBb = new $nn("notebookKernel", void 0);
var $oBb = new $nn("notebookKernelCount", 0);
var $pBb = new $nn("notebookKernelSourceCount", 0);
var $qBb = new $nn("notebookKernelSelected", false);
var $rBb = new $nn("notebookInterruptibleKernel", false);
var $sBb = new $nn("notebookMissingKernelExtension", false);
var $tBb = new $nn("notebookHasOutputs", false);
var $uBb = new $nn("kernelHasVariableProvider", false);

// out-build/vs/workbench/contrib/chat/browser/actions/chatTitleActions.js
var $vBb = "workbench.action.chat.markUnhelpful";
function $wBb() {
  $hJ(class MarkHelpfulAction extends $gJ {
    constructor() {
      super({
        id: "workbench.action.chat.markHelpful",
        title: localize2(4732, "Helpful"),
        f1: false,
        category: $vNb,
        icon: $6l.thumbsup,
        toggled: ChatContextKeys.responseVote.isEqualTo("up"),
        menu: [{
          id: $bJ.ChatMessageFooter,
          group: "navigation",
          order: 1,
          when: $7m.and(ChatContextKeys.isResponse, ChatContextKeys.responseHasError.negate())
        }, {
          id: $zAb,
          group: "navigation",
          order: 1,
          when: $7m.and(ChatContextKeys.isResponse, ChatContextKeys.responseHasError.negate())
        }]
      });
    }
    run(accessor, ...args2) {
      const item = args2[0];
      if (!$asb(item)) {
        return;
      }
      const chatService = accessor.get($qO);
      chatService.notifyUserAction({
        agentId: item.agent?.id,
        command: item.slashCommand?.name,
        sessionId: item.sessionId,
        requestId: item.requestId,
        result: item.result,
        action: {
          kind: "vote",
          direction: ChatAgentVoteDirection.Up,
          reason: void 0
        }
      });
      item.setVote(ChatAgentVoteDirection.Up);
      item.setVoteDownReason(void 0);
    }
  });
  $hJ(class MarkUnhelpfulAction extends $gJ {
    constructor() {
      super({
        id: $vBb,
        title: localize2(4733, "Unhelpful"),
        f1: false,
        category: $vNb,
        icon: $6l.thumbsdown,
        toggled: ChatContextKeys.responseVote.isEqualTo("down"),
        menu: [{
          id: $bJ.ChatMessageFooter,
          group: "navigation",
          order: 2,
          when: $7m.and(ChatContextKeys.isResponse)
        }, {
          id: $zAb,
          group: "navigation",
          order: 2,
          when: $7m.and(ChatContextKeys.isResponse, ChatContextKeys.responseHasError.negate())
        }]
      });
    }
    run(accessor, ...args2) {
      const item = args2[0];
      if (!$asb(item)) {
        return;
      }
      const reason = args2[1];
      if (typeof reason !== "string") {
        return;
      }
      item.setVote(ChatAgentVoteDirection.Down);
      item.setVoteDownReason(reason);
      const chatService = accessor.get($qO);
      chatService.notifyUserAction({
        agentId: item.agent?.id,
        command: item.slashCommand?.name,
        sessionId: item.sessionId,
        requestId: item.requestId,
        result: item.result,
        action: {
          kind: "vote",
          direction: ChatAgentVoteDirection.Down,
          reason: item.voteDownReason
        }
      });
    }
  });
  $hJ(class ReportIssueForBugAction extends $gJ {
    constructor() {
      super({
        id: "workbench.action.chat.reportIssueForBug",
        title: localize2(4734, "Report Issue"),
        f1: false,
        category: $vNb,
        icon: $6l.report,
        menu: [{
          id: $bJ.ChatMessageFooter,
          group: "navigation",
          order: 3,
          when: $7m.and(ChatContextKeys.responseSupportsIssueReporting, ChatContextKeys.isResponse)
        }, {
          id: $zAb,
          group: "navigation",
          order: 3,
          when: $7m.and(ChatContextKeys.responseSupportsIssueReporting, ChatContextKeys.isResponse)
        }]
      });
    }
    run(accessor, ...args2) {
      const item = args2[0];
      if (!$asb(item)) {
        return;
      }
      const chatService = accessor.get($qO);
      chatService.notifyUserAction({
        agentId: item.agent?.id,
        command: item.slashCommand?.name,
        sessionId: item.sessionId,
        requestId: item.requestId,
        result: item.result,
        action: {
          kind: "bug"
        }
      });
    }
  });
  $hJ(class RetryChatAction extends $gJ {
    constructor() {
      super({
        id: "workbench.action.chat.retry",
        title: localize2(4735, "Retry"),
        f1: false,
        category: $vNb,
        icon: $6l.refresh,
        menu: [
          {
            id: $bJ.ChatMessageFooter,
            group: "navigation",
            when: $7m.and(ChatContextKeys.isResponse, $7m.in(ChatContextKeys.itemId.key, ChatContextKeys.lastItemId.key))
          },
          {
            id: $bJ.ChatEditingWidgetToolbar,
            group: "navigation",
            when: $hP,
            order: 0
          }
        ]
      });
    }
    async run(accessor, ...args2) {
      const chatWidgetService = accessor.get($2Nb);
      let item = args2[0];
      if ($kP(item)) {
        item = chatWidgetService.getWidgetBySessionId(item.sessionId)?.viewModel?.getItems().at(-1);
      }
      if (!$asb(item)) {
        return;
      }
      const chatService = accessor.get($qO);
      const chatModel = chatService.getSession(item.sessionId);
      const chatRequests = chatModel?.getRequests();
      if (!chatRequests) {
        return;
      }
      const itemIndex = chatRequests?.findIndex((request2) => request2.id === item.requestId);
      if (chatModel?.initialLocation === ChatAgentLocation.EditingSession) {
        const configurationService = accessor.get($kl);
        const dialogService = accessor.get($Yv);
        const chatEditingService = accessor.get($$O);
        const currentEditingSession = chatEditingService.currentEditingSession;
        if (!currentEditingSession) {
          return;
        }
        const entriesModifiedInLastRequest = currentEditingSession.entries.get().filter((entry) => entry.lastModifyingRequestId === item.requestId);
        const shouldPrompt = entriesModifiedInLastRequest.length > 0 && configurationService.getValue("chat.editing.confirmEditRequestRetry") === true;
        const confirmation = shouldPrompt ? await dialogService.confirm({
          title: localize(4722, null),
          message: entriesModifiedInLastRequest.length === 1 ? localize(4723, null, $sh(entriesModifiedInLastRequest[0].modifiedURI)) : localize(4724, null, entriesModifiedInLastRequest.length),
          primaryButton: localize(4725, null),
          checkbox: { label: localize(4726, null), checked: false },
          type: "info"
        }) : { confirmed: true };
        if (!confirmation.confirmed) {
          return;
        }
        if (confirmation.checkboxChecked) {
          await configurationService.updateValue("chat.editing.confirmEditRequestRetry", false);
        }
        const snapshotRequest = chatRequests[itemIndex];
        if (snapshotRequest) {
          await currentEditingSession.restoreSnapshot(snapshotRequest.id);
        }
      }
      const request = chatModel?.getRequests().find((candidate) => candidate.id === item.requestId);
      const languageModelId = chatWidgetService.getWidgetBySessionId(item.sessionId)?.input.currentLanguageModel;
      chatService.resendRequest(request, { userSelectedModelId: languageModelId });
    }
  });
  $hJ(class InsertToNotebookAction extends $gJ {
    constructor() {
      super({
        id: "workbench.action.chat.insertIntoNotebook",
        title: localize2(4736, "Insert into Notebook"),
        f1: false,
        category: $vNb,
        icon: $6l.insert,
        menu: {
          id: $bJ.ChatMessageFooter,
          group: "navigation",
          isHiddenByDefault: true,
          when: $7m.and($SAb, ChatContextKeys.isResponse, ChatContextKeys.responseIsFiltered.negate())
        }
      });
    }
    async run(accessor, ...args2) {
      const item = args2[0];
      if (!$asb(item)) {
        return;
      }
      const editorService = accessor.get($mJ);
      if (editorService.activeEditorPane?.getId() === $bM) {
        const notebookEditor = editorService.activeEditorPane.getControl();
        if (!notebookEditor.hasModel()) {
          return;
        }
        if (notebookEditor.isReadOnly) {
          return;
        }
        const value = item.response.toString();
        const splitContents = splitMarkdownAndCodeBlocks(value);
        const focusRange = notebookEditor.getFocus();
        const index = Math.max(focusRange.end, 0);
        const bulkEditService = accessor.get($H_);
        await bulkEditService.apply([
          new $Trb(notebookEditor.textModel.uri, {
            editType: 1,
            index,
            count: 0,
            cells: splitContents.map((content) => {
              const kind = content.type === "markdown" ? CellKind.Markup : CellKind.Code;
              const language = content.type === "markdown" ? "markdown" : content.language;
              const mime = content.type === "markdown" ? "text/markdown" : `text/x-${content.language}`;
              return {
                cellKind: kind,
                language,
                mime,
                source: content.content,
                outputs: [],
                metadata: {}
              };
            })
          })
        ], { quotableLabel: "Insert into Notebook" });
      }
    }
  });
  $hJ(class RemoveAction extends $gJ {
    constructor() {
      super({
        id: "workbench.action.chat.remove",
        title: localize2(4737, "Remove Request"),
        f1: false,
        category: $vNb,
        icon: $6l.x,
        precondition: ChatContextKeys.location.notEqualsTo(ChatAgentLocation.EditingSession),
        keybinding: {
          primary: 20,
          mac: {
            primary: 2048 | 1
          },
          when: $7m.and(ChatContextKeys.location.notEqualsTo(ChatAgentLocation.EditingSession), ChatContextKeys.inChatSession, ChatContextKeys.inChatInput.negate()),
          weight: 200
        },
        menu: {
          id: $bJ.ChatMessageTitle,
          group: "navigation",
          order: 2,
          when: $7m.and(ChatContextKeys.location.notEqualsTo(ChatAgentLocation.EditingSession), ChatContextKeys.isRequest)
        }
      });
    }
    run(accessor, ...args2) {
      let item = args2[0];
      if (!$_rb(item)) {
        const chatWidgetService = accessor.get($2Nb);
        const widget = chatWidgetService.lastFocusedWidget;
        item = widget?.getFocus();
      }
      if (!item) {
        return;
      }
      const chatService = accessor.get($qO);
      const chatModel = chatService.getSession(item.sessionId);
      if (chatModel?.initialLocation === ChatAgentLocation.EditingSession) {
        return;
      }
      const requestId = $_rb(item) ? item.id : $asb(item) ? item.requestId : void 0;
      if (requestId) {
        const chatService2 = accessor.get($qO);
        chatService2.removeRequest(item.sessionId, requestId);
      }
    }
  });
  $hJ(class ContinueEditingAction extends $gJ {
    constructor() {
      super({
        id: "workbench.action.chat.startEditing",
        title: localize2(4738, "Edit with Copilot"),
        f1: false,
        category: $vNb,
        icon: $6l.goToEditingSession,
        precondition: $7m.and(ChatContextKeys.editingParticipantRegistered, ChatContextKeys.requestInProgress.toNegated(), ChatContextKeys.location.isEqualTo(ChatAgentLocation.Panel)),
        menu: {
          id: $bJ.ChatMessageFooter,
          group: "navigation",
          order: 4,
          when: $7m.and(ChatContextKeys.enabled, ChatContextKeys.isResponse, ChatContextKeys.editingParticipantRegistered, ChatContextKeys.location.isEqualTo(ChatAgentLocation.Panel))
        }
      });
    }
    async run(accessor, ...args2) {
      const logService = accessor.get($wn);
      const chatWidgetService = accessor.get($2Nb);
      const chatService = accessor.get($qO);
      const chatAgentService = accessor.get($ZO);
      const viewsService = accessor.get($uob);
      const chatEditingService = accessor.get($$O);
      const quickPickService = accessor.get($1M);
      const editAgent = chatAgentService.getDefaultAgent(ChatAgentLocation.EditingSession);
      if (!editAgent) {
        logService.trace("[CHAT_MOVE] No edit agent found");
        return;
      }
      const sourceWidget = chatWidgetService.lastFocusedWidget;
      if (!sourceWidget || !sourceWidget.viewModel) {
        logService.trace("[CHAT_MOVE] NO source model");
        return;
      }
      const sourceModel = sourceWidget.viewModel.model;
      let sourceRequests = sourceModel.getRequests().slice();
      const [first] = args2;
      if ($asb(first)) {
        const idx = sourceRequests.findIndex((candidate) => candidate.id === first.requestId);
        if (idx >= 0) {
          sourceRequests.length = idx + 1;
        }
      }
      if (sourceRequests.length > 1) {
        sourceRequests = await this.b(quickPickService, sourceRequests);
      }
      if (sourceRequests.length === 0) {
        logService.trace("[CHAT_MOVE] NO requests to move");
        return;
      }
      await viewsService.openView($0Nb);
      let editingSession = chatEditingService.currentEditingSessionObs.get();
      if (!editingSession) {
        await Event2.toPromise(chatEditingService.onDidCreateEditingSession);
        editingSession = chatEditingService.currentEditingSessionObs.get();
        return;
      }
      if (!editingSession) {
        return;
      }
      const state = editingSession.state.get();
      if (state === 3) {
        return;
      }
      const workingSetAdditions = new $Fc();
      for (const request of sourceRequests) {
        await chatService.adoptRequest(editingSession.chatSessionId, request);
        this.a(request, workingSetAdditions);
      }
      workingSetAdditions.forEach((uri) => editingSession.addFileToWorkingSet(uri));
      await chatService.sendRequest(editingSession.chatSessionId, "", {
        agentId: editAgent.id,
        acceptedConfirmationData: [{ _type: "toEditTransfer", transferedTurnResults: sourceRequests.map((v) => v.response?.result) }],
        // TODO@jrieken HACKY
        confirmation: typeof this.desc.title === "string" ? this.desc.title : this.desc.title.value
      });
    }
    a(request, bucket) {
      for (const item of request.response?.response.value ?? []) {
        if (item.kind === "inlineReference") {
          bucket.add($SE(item.inlineReference) ? item.inlineReference.uri : URI.isUri(item.inlineReference) ? item.inlineReference : item.inlineReference.location.uri);
        }
      }
    }
    async b(quickPickService, requests) {
      const timeThreshold = 2 * 6e4;
      const lastRequestTimestamp = requests[requests.length - 1].timestamp;
      const relatedRequests = requests.filter((request) => request.timestamp >= 0 && lastRequestTimestamp - request.timestamp <= timeThreshold);
      const lastPick = {
        label: localize(4727, null, relatedRequests.length),
        detail: relatedRequests.map((req) => req.message.text).join(", ")
      };
      const allPick = {
        label: localize(4728, null)
      };
      const customPick = {
        label: localize(4729, null)
      };
      const picks = relatedRequests.length !== 0 ? [lastPick, allPick, customPick] : [allPick, customPick];
      const firstPick = await quickPickService.pick(picks, {
        placeHolder: localize(4730, null)
      });
      if (!firstPick) {
        return [];
      } else if (firstPick === allPick) {
        return requests;
      } else if (firstPick === lastPick) {
        return relatedRequests;
      }
      const customPicks = requests.map((request) => ({
        picked: false,
        request,
        label: request.message.text,
        detail: request.response?.response.toString()
      }));
      return await new Promise((_resolve) => {
        const resolve = (value) => {
          store.dispose();
          _resolve(value);
          qp.hide();
        };
        const store = new $2c();
        const qp = quickPickService.createQuickPick();
        qp.placeholder = localize(4731, null);
        qp.canSelectMany = true;
        qp.items = customPicks;
        let ignore = false;
        store.add(qp.onDidChangeSelection((e) => {
          if (ignore) {
            return;
          }
          ignore = true;
          try {
            const [first] = e;
            const selected = [];
            let disabled = false;
            for (let i2 = 0; i2 < customPicks.length; i2++) {
              const oldItem = customPicks[i2];
              customPicks[i2] = {
                ...oldItem,
                disabled
              };
              disabled = disabled || oldItem === first;
              if (disabled) {
                selected.push(customPicks[i2]);
              }
            }
            qp.items = customPicks;
            qp.selectedItems = selected;
          } finally {
            ignore = false;
          }
        }));
        store.add(qp.onDidAccept((_e) => resolve(qp.selectedItems.map((i2) => i2.request))));
        store.add(qp.onDidHide((_) => resolve([])));
        store.add(qp);
        qp.show();
      });
    }
  });
}
function splitMarkdownAndCodeBlocks(markdown) {
  const lexer2 = new marked.Lexer();
  const tokens = lexer2.lex(markdown);
  const splitContent = [];
  let markdownPart = "";
  tokens.forEach((token) => {
    if (token.type === "code") {
      if (markdownPart.trim()) {
        splitContent.push({ type: "markdown", content: markdownPart });
        markdownPart = "";
      }
      splitContent.push({
        type: "code",
        language: token.lang || "",
        content: token.text
      });
    } else {
      markdownPart += token.raw;
    }
  });
  if (markdownPart.trim()) {
    splitContent.push({ type: "markdown", content: markdownPart });
  }
  return splitContent;
}

// out-build/vs/workbench/contrib/extensions/common/extensionsFileTemplate.js
var $xBb = "vscode://schemas/extensions";
var $yBb = {
  id: $xBb,
  allowComments: true,
  allowTrailingCommas: true,
  type: "object",
  title: localize(6973, null),
  additionalProperties: false,
  properties: {
    recommendations: {
      type: "array",
      description: localize(6974, null),
      items: {
        type: "string",
        pattern: $cA,
        errorMessage: localize(6975, null)
      }
    },
    unwantedRecommendations: {
      type: "array",
      description: localize(6976, null),
      items: {
        type: "string",
        pattern: $cA,
        errorMessage: localize(6977, null)
      }
    }
  }
};
var $zBb = [
  "{",
  "	// See https://go.microsoft.com/fwlink/?LinkId=827846 to learn about workspace recommendations.",
  "	// Extension identifier format: ${publisher}.${name}. Example: vscode.csharp",
  "",
  "	// List of extensions which should be recommended for users of this workspace.",
  '	"recommendations": [',
  "		",
  "	],",
  "	// List of extensions recommended by VS Code that should not be recommended for users of this workspace.",
  '	"unwantedRecommendations": [',
  "		",
  "	]",
  "}"
].join("\n");

// out-build/vs/workbench/services/extensionManagement/common/extensionManagement.js
var $mzb = $Rk($sA);
var ExtensionInstallLocation;
(function(ExtensionInstallLocation2) {
  ExtensionInstallLocation2[ExtensionInstallLocation2["Local"] = 1] = "Local";
  ExtensionInstallLocation2[ExtensionInstallLocation2["Remote"] = 2] = "Remote";
  ExtensionInstallLocation2[ExtensionInstallLocation2["Web"] = 3] = "Web";
})(ExtensionInstallLocation || (ExtensionInstallLocation = {}));
var $nzb = $Qk("extensionManagementServerService");
var $ozb = $ih.asBrowserUri("vs/workbench/services/extensionManagement/common/media/defaultIcon.png").toString(true);
var $pzb = $Rk($mzb);
var EnablementState;
(function(EnablementState2) {
  EnablementState2[EnablementState2["DisabledByTrustRequirement"] = 0] = "DisabledByTrustRequirement";
  EnablementState2[EnablementState2["DisabledByExtensionKind"] = 1] = "DisabledByExtensionKind";
  EnablementState2[EnablementState2["DisabledByEnvironment"] = 2] = "DisabledByEnvironment";
  EnablementState2[EnablementState2["EnabledByEnvironment"] = 3] = "EnabledByEnvironment";
  EnablementState2[EnablementState2["DisabledByVirtualWorkspace"] = 4] = "DisabledByVirtualWorkspace";
  EnablementState2[EnablementState2["DisabledByInvalidExtension"] = 5] = "DisabledByInvalidExtension";
  EnablementState2[EnablementState2["DisabledByAllowlist"] = 6] = "DisabledByAllowlist";
  EnablementState2[EnablementState2["DisabledByExtensionDependency"] = 7] = "DisabledByExtensionDependency";
  EnablementState2[EnablementState2["DisabledGlobally"] = 8] = "DisabledGlobally";
  EnablementState2[EnablementState2["DisabledWorkspace"] = 9] = "DisabledWorkspace";
  EnablementState2[EnablementState2["EnabledGlobally"] = 10] = "EnabledGlobally";
  EnablementState2[EnablementState2["EnabledWorkspace"] = 11] = "EnabledWorkspace";
})(EnablementState || (EnablementState = {}));
var $qzb = $Qk("extensionEnablementService");
var $rzb = $Qk("IWebExtensionsScannerService");

// out-build/vs/workbench/services/extensionRecommendations/common/extensionRecommendations.js
var ExtensionRecommendationReason;
(function(ExtensionRecommendationReason2) {
  ExtensionRecommendationReason2[ExtensionRecommendationReason2["Workspace"] = 0] = "Workspace";
  ExtensionRecommendationReason2[ExtensionRecommendationReason2["File"] = 1] = "File";
  ExtensionRecommendationReason2[ExtensionRecommendationReason2["Executable"] = 2] = "Executable";
  ExtensionRecommendationReason2[ExtensionRecommendationReason2["WorkspaceConfig"] = 3] = "WorkspaceConfig";
  ExtensionRecommendationReason2[ExtensionRecommendationReason2["DynamicWorkspace"] = 4] = "DynamicWorkspace";
  ExtensionRecommendationReason2[ExtensionRecommendationReason2["Experimental"] = 5] = "Experimental";
  ExtensionRecommendationReason2[ExtensionRecommendationReason2["Application"] = 6] = "Application";
})(ExtensionRecommendationReason || (ExtensionRecommendationReason = {}));
var $ABb = $Qk("extensionRecommendationsService");
var $BBb = $Qk("IExtensionIgnoredRecommendationsService");

// out-build/vs/workbench/services/configuration/common/jsonEditing.js
var $CBb = $Qk("jsonEditingService");
var JSONEditingErrorCode;
(function(JSONEditingErrorCode2) {
  JSONEditingErrorCode2[JSONEditingErrorCode2["ERROR_INVALID_FILE"] = 0] = "ERROR_INVALID_FILE";
})(JSONEditingErrorCode || (JSONEditingErrorCode = {}));
var $DBb = class extends Error {
  constructor(message, code) {
    super(message);
    this.code = code;
  }
};

// out-build/vs/workbench/services/themes/common/workbenchThemeService.js
var $rwb = $Rk($gs);
var $swb = "vs";
var $twb = "vs-dark";
var $uwb = "hc-black";
var $vwb = "hc-light";
var $wwb = "[";
var $xwb = "]";
var $ywb = "*";
var $zwb = /\[(.+?)\]/g;
var ThemeSettings;
(function(ThemeSettings2) {
  ThemeSettings2["COLOR_THEME"] = "workbench.colorTheme";
  ThemeSettings2["FILE_ICON_THEME"] = "workbench.iconTheme";
  ThemeSettings2["PRODUCT_ICON_THEME"] = "workbench.productIconTheme";
  ThemeSettings2["COLOR_CUSTOMIZATIONS"] = "workbench.colorCustomizations";
  ThemeSettings2["TOKEN_COLOR_CUSTOMIZATIONS"] = "editor.tokenColorCustomizations";
  ThemeSettings2["SEMANTIC_TOKEN_COLOR_CUSTOMIZATIONS"] = "editor.semanticTokenColorCustomizations";
  ThemeSettings2["PREFERRED_DARK_THEME"] = "workbench.preferredDarkColorTheme";
  ThemeSettings2["PREFERRED_LIGHT_THEME"] = "workbench.preferredLightColorTheme";
  ThemeSettings2["PREFERRED_HC_DARK_THEME"] = "workbench.preferredHighContrastColorTheme";
  ThemeSettings2["PREFERRED_HC_LIGHT_THEME"] = "workbench.preferredHighContrastLightColorTheme";
  ThemeSettings2["DETECT_COLOR_SCHEME"] = "window.autoDetectColorScheme";
  ThemeSettings2["DETECT_HC"] = "window.autoDetectHighContrast";
  ThemeSettings2["SYSTEM_COLOR_THEME"] = "window.systemColorTheme";
})(ThemeSettings || (ThemeSettings = {}));
var ThemeSettingDefaults;
(function(ThemeSettingDefaults2) {
  ThemeSettingDefaults2["COLOR_THEME_DARK"] = "Default Dark Modern";
  ThemeSettingDefaults2["COLOR_THEME_LIGHT"] = "Default Light Modern";
  ThemeSettingDefaults2["COLOR_THEME_HC_DARK"] = "Default High Contrast";
  ThemeSettingDefaults2["COLOR_THEME_HC_LIGHT"] = "Default High Contrast Light";
  ThemeSettingDefaults2["COLOR_THEME_DARK_OLD"] = "Default Dark+";
  ThemeSettingDefaults2["COLOR_THEME_LIGHT_OLD"] = "Default Light+";
  ThemeSettingDefaults2["FILE_ICON_THEME"] = "vs-seti";
  ThemeSettingDefaults2["PRODUCT_ICON_THEME"] = "Default";
})(ThemeSettingDefaults || (ThemeSettingDefaults = {}));
var $Awb = {
  "activityBar.activeBorder": "#0078d4",
  "activityBar.background": "#181818",
  "activityBar.border": "#2b2b2b",
  "activityBar.foreground": "#d7d7d7",
  "activityBar.inactiveForeground": "#868686",
  "editorGroup.border": "#ffffff17",
  "editorGroupHeader.tabsBackground": "#181818",
  "editorGroupHeader.tabsBorder": "#2b2b2b",
  "statusBar.background": "#181818",
  "statusBar.border": "#2b2b2b",
  "statusBar.foreground": "#cccccc",
  "statusBar.noFolderBackground": "#1f1f1f",
  "tab.activeBackground": "#1f1f1f",
  "tab.activeBorder": "#1f1f1f",
  "tab.activeBorderTop": "#0078d4",
  "tab.activeForeground": "#ffffff",
  "tab.border": "#2b2b2b",
  "textLink.foreground": "#4daafc",
  "titleBar.activeBackground": "#181818",
  "titleBar.activeForeground": "#cccccc",
  "titleBar.border": "#2b2b2b",
  "titleBar.inactiveBackground": "#1f1f1f",
  "titleBar.inactiveForeground": "#9d9d9d",
  "welcomePage.tileBackground": "#2b2b2b"
};
var $Bwb = {
  "activityBar.activeBorder": "#005FB8",
  "activityBar.background": "#f8f8f8",
  "activityBar.border": "#e5e5e5",
  "activityBar.foreground": "#1f1f1f",
  "activityBar.inactiveForeground": "#616161",
  "editorGroup.border": "#e5e5e5",
  "editorGroupHeader.tabsBackground": "#f8f8f8",
  "editorGroupHeader.tabsBorder": "#e5e5e5",
  "statusBar.background": "#f8f8f8",
  "statusBar.border": "#e5e5e5",
  "statusBar.foreground": "#3b3b3b",
  "statusBar.noFolderBackground": "#f8f8f8",
  "tab.activeBackground": "#ffffff",
  "tab.activeBorder": "#f8f8f8",
  "tab.activeBorderTop": "#005fb8",
  "tab.activeForeground": "#3b3b3b",
  "tab.border": "#e5e5e5",
  "textLink.foreground": "#005fb8",
  "titleBar.activeBackground": "#f8f8f8",
  "titleBar.activeForeground": "#1e1e1e",
  "titleBar.border": "#E5E5E5",
  "titleBar.inactiveBackground": "#f8f8f8",
  "titleBar.inactiveForeground": "#8b949e",
  "welcomePage.tileBackground": "#f3f3f3"
};
var ExtensionData;
(function(ExtensionData2) {
  function toJSONObject(d) {
    return d && { _extensionId: d.extensionId, _extensionIsBuiltin: d.extensionIsBuiltin, _extensionName: d.extensionName, _extensionPublisher: d.extensionPublisher };
  }
  ExtensionData2.toJSONObject = toJSONObject;
  function fromJSONObject(o) {
    if (o && $zg(o._extensionId) && $Fg(o._extensionIsBuiltin) && $zg(o._extensionName) && $zg(o._extensionPublisher)) {
      return { extensionId: o._extensionId, extensionIsBuiltin: o._extensionIsBuiltin, extensionName: o._extensionName, extensionPublisher: o._extensionPublisher };
    }
    return void 0;
  }
  ExtensionData2.fromJSONObject = fromJSONObject;
  function fromName(publisher, name, isBuiltin = false) {
    return { extensionPublisher: publisher, extensionId: `${publisher}.${name}`, extensionName: name, extensionIsBuiltin: isBuiltin };
  }
  ExtensionData2.fromName = fromName;
})(ExtensionData || (ExtensionData = {}));

// out-build/vs/workbench/services/extensionRecommendations/common/workspaceExtensionsConfig.js
var $EBb = ".vscode/extensions.json";
var $FBb = $Qk("IWorkspaceExtensionsConfigService");
var $GBb = class $GBb2 extends $3c {
  constructor(b, f, g, h3, j, m) {
    super();
    this.b = b;
    this.f = f;
    this.g = g;
    this.h = h3;
    this.j = j;
    this.m = m;
    this.a = this.B(new $ze());
    this.onDidChangeExtensionsConfigs = this.a.event;
    this.B(b.onDidChangeWorkspaceFolders((e) => this.a.fire()));
    this.B(f.onDidFilesChange((e) => {
      const workspace2 = b.getWorkspace();
      if (workspace2.configuration && e.affects(workspace2.configuration) || workspace2.folders.some((folder) => e.affects(folder.toResource($EBb)))) {
        this.a.fire();
      }
    }));
  }
  async getExtensionsConfigs() {
    const workspace2 = this.b.getWorkspace();
    const result = [];
    const workspaceExtensionsConfigContent = workspace2.configuration ? await this.y(workspace2.configuration) : void 0;
    if (workspaceExtensionsConfigContent) {
      result.push(workspaceExtensionsConfigContent);
    }
    result.push(...await Promise.all(workspace2.folders.map((workspaceFolder) => this.z(workspaceFolder))));
    return result;
  }
  async getRecommendations() {
    const configs = await this.getExtensionsConfigs();
    return $Rb(configs.flatMap((c) => c.recommendations ? c.recommendations.map((c2) => c2.toLowerCase()) : []));
  }
  async getUnwantedRecommendations() {
    const configs = await this.getExtensionsConfigs();
    return $Rb(configs.flatMap((c) => c.unwantedRecommendations ? c.unwantedRecommendations.map((c2) => c2.toLowerCase()) : []));
  }
  async toggleRecommendation(extensionId) {
    extensionId = extensionId.toLowerCase();
    const workspace2 = this.b.getWorkspace();
    const workspaceExtensionsConfigContent = workspace2.configuration ? await this.y(workspace2.configuration) : void 0;
    const workspaceFolderExtensionsConfigContents = new $Ec();
    await Promise.all(workspace2.folders.map(async (workspaceFolder) => {
      const extensionsConfigContent = await this.z(workspaceFolder);
      workspaceFolderExtensionsConfigContents.set(workspaceFolder.uri, extensionsConfigContent);
    }));
    const isWorkspaceRecommended = workspaceExtensionsConfigContent && workspaceExtensionsConfigContent.recommendations?.some((r2) => r2.toLowerCase() === extensionId);
    const recommendedWorksapceFolders = workspace2.folders.filter((workspaceFolder) => workspaceFolderExtensionsConfigContents.get(workspaceFolder.uri)?.recommendations?.some((r2) => r2.toLowerCase() === extensionId));
    const isRecommended = isWorkspaceRecommended || recommendedWorksapceFolders.length > 0;
    const workspaceOrFolders = isRecommended ? await this.w(recommendedWorksapceFolders, isWorkspaceRecommended ? workspace2 : void 0, localize(12777, null)) : await this.w(workspace2.folders, workspace2.configuration ? workspace2 : void 0, localize(12778, null));
    for (const workspaceOrWorkspaceFolder of workspaceOrFolders) {
      if ($8k(workspaceOrWorkspaceFolder)) {
        await this.s(extensionId, workspaceOrWorkspaceFolder, workspaceExtensionsConfigContent, !isRecommended);
      } else {
        await this.n(extensionId, workspaceOrWorkspaceFolder, workspaceFolderExtensionsConfigContents.get(workspaceOrWorkspaceFolder.uri), !isRecommended);
      }
    }
  }
  async toggleUnwantedRecommendation(extensionId) {
    const workspace2 = this.b.getWorkspace();
    const workspaceExtensionsConfigContent = workspace2.configuration ? await this.y(workspace2.configuration) : void 0;
    const workspaceFolderExtensionsConfigContents = new $Ec();
    await Promise.all(workspace2.folders.map(async (workspaceFolder) => {
      const extensionsConfigContent = await this.z(workspaceFolder);
      workspaceFolderExtensionsConfigContents.set(workspaceFolder.uri, extensionsConfigContent);
    }));
    const isWorkspaceUnwanted = workspaceExtensionsConfigContent && workspaceExtensionsConfigContent.unwantedRecommendations?.some((r2) => r2 === extensionId);
    const unWantedWorksapceFolders = workspace2.folders.filter((workspaceFolder) => workspaceFolderExtensionsConfigContents.get(workspaceFolder.uri)?.unwantedRecommendations?.some((r2) => r2 === extensionId));
    const isUnwanted = isWorkspaceUnwanted || unWantedWorksapceFolders.length > 0;
    const workspaceOrFolders = isUnwanted ? await this.w(unWantedWorksapceFolders, isWorkspaceUnwanted ? workspace2 : void 0, localize(12779, null)) : await this.w(workspace2.folders, workspace2.configuration ? workspace2 : void 0, localize(12780, null));
    for (const workspaceOrWorkspaceFolder of workspaceOrFolders) {
      if ($8k(workspaceOrWorkspaceFolder)) {
        await this.u(extensionId, workspaceOrWorkspaceFolder, workspaceExtensionsConfigContent, !isUnwanted);
      } else {
        await this.t(extensionId, workspaceOrWorkspaceFolder, workspaceFolderExtensionsConfigContents.get(workspaceOrWorkspaceFolder.uri), !isUnwanted);
      }
    }
  }
  async n(extensionId, workspaceFolder, extensionsConfigContent, add) {
    const values = [];
    if (add) {
      if (Array.isArray(extensionsConfigContent.recommendations)) {
        values.push({ path: ["recommendations", -1], value: extensionId });
      } else {
        values.push({ path: ["recommendations"], value: [extensionId] });
      }
      const unwantedRecommendationEdit = this.D(["unwantedRecommendations"], extensionsConfigContent.unwantedRecommendations, extensionId);
      if (unwantedRecommendationEdit) {
        values.push(unwantedRecommendationEdit);
      }
    } else if (extensionsConfigContent.recommendations) {
      const recommendationEdit = this.D(["recommendations"], extensionsConfigContent.recommendations, extensionId);
      if (recommendationEdit) {
        values.push(recommendationEdit);
      }
    }
    if (values.length) {
      return this.m.write(workspaceFolder.toResource($EBb), values, true);
    }
  }
  async s(extensionId, workspace2, extensionsConfigContent, add) {
    const values = [];
    if (extensionsConfigContent) {
      if (add) {
        const path = ["extensions", "recommendations"];
        if (Array.isArray(extensionsConfigContent.recommendations)) {
          values.push({ path: [...path, -1], value: extensionId });
        } else {
          values.push({ path, value: [extensionId] });
        }
        const unwantedRecommendationEdit = this.D(["extensions", "unwantedRecommendations"], extensionsConfigContent.unwantedRecommendations, extensionId);
        if (unwantedRecommendationEdit) {
          values.push(unwantedRecommendationEdit);
        }
      } else if (extensionsConfigContent.recommendations) {
        const recommendationEdit = this.D(["extensions", "recommendations"], extensionsConfigContent.recommendations, extensionId);
        if (recommendationEdit) {
          values.push(recommendationEdit);
        }
      }
    } else if (add) {
      values.push({ path: ["extensions"], value: { recommendations: [extensionId] } });
    }
    if (values.length) {
      return this.m.write(workspace2.configuration, values, true);
    }
  }
  async t(extensionId, workspaceFolder, extensionsConfigContent, add) {
    const values = [];
    if (add) {
      const path = ["unwantedRecommendations"];
      if (Array.isArray(extensionsConfigContent.unwantedRecommendations)) {
        values.push({ path: [...path, -1], value: extensionId });
      } else {
        values.push({ path, value: [extensionId] });
      }
      const recommendationEdit = this.D(["recommendations"], extensionsConfigContent.recommendations, extensionId);
      if (recommendationEdit) {
        values.push(recommendationEdit);
      }
    } else if (extensionsConfigContent.unwantedRecommendations) {
      const unwantedRecommendationEdit = this.D(["unwantedRecommendations"], extensionsConfigContent.unwantedRecommendations, extensionId);
      if (unwantedRecommendationEdit) {
        values.push(unwantedRecommendationEdit);
      }
    }
    if (values.length) {
      return this.m.write(workspaceFolder.toResource($EBb), values, true);
    }
  }
  async u(extensionId, workspace2, extensionsConfigContent, add) {
    const values = [];
    if (extensionsConfigContent) {
      if (add) {
        const path = ["extensions", "unwantedRecommendations"];
        if (Array.isArray(extensionsConfigContent.recommendations)) {
          values.push({ path: [...path, -1], value: extensionId });
        } else {
          values.push({ path, value: [extensionId] });
        }
        const recommendationEdit = this.D(["extensions", "recommendations"], extensionsConfigContent.recommendations, extensionId);
        if (recommendationEdit) {
          values.push(recommendationEdit);
        }
      } else if (extensionsConfigContent.unwantedRecommendations) {
        const unwantedRecommendationEdit = this.D(["extensions", "unwantedRecommendations"], extensionsConfigContent.unwantedRecommendations, extensionId);
        if (unwantedRecommendationEdit) {
          values.push(unwantedRecommendationEdit);
        }
      }
    } else if (add) {
      values.push({ path: ["extensions"], value: { unwantedRecommendations: [extensionId] } });
    }
    if (values.length) {
      return this.m.write(workspace2.configuration, values, true);
    }
  }
  async w(workspaceFolders, workspace2, placeHolder) {
    const workspaceOrFolders = workspace2 ? [...workspaceFolders, workspace2] : [...workspaceFolders];
    if (workspaceOrFolders.length === 1) {
      return workspaceOrFolders;
    }
    const folderPicks = workspaceFolders.map((workspaceFolder) => {
      return {
        label: workspaceFolder.name,
        description: localize(12781, null),
        workspaceOrFolder: workspaceFolder,
        iconClasses: $gdb(this.h, this.j, workspaceFolder.uri, FileKind.ROOT_FOLDER)
      };
    });
    if (workspace2) {
      folderPicks.push({ type: "separator" });
      folderPicks.push({
        label: localize(12782, null),
        workspaceOrFolder: workspace2
      });
    }
    const result = await this.g.pick(folderPicks, { placeHolder, canPickMany: true }) || [];
    return result.map((r2) => r2.workspaceOrFolder);
  }
  async y(workspaceConfigurationResource) {
    try {
      const content = await this.f.readFile(workspaceConfigurationResource);
      const extensionsConfigContent = $yw(content.value.toString())["extensions"];
      return extensionsConfigContent ? this.C(extensionsConfigContent) : void 0;
    } catch (e) {
    }
    return void 0;
  }
  async z(workspaceFolder) {
    try {
      const content = await this.f.readFile(workspaceFolder.toResource($EBb));
      const extensionsConfigContent = $yw(content.value.toString());
      return this.C(extensionsConfigContent);
    } catch (e) {
    }
    return {};
  }
  C(extensionsConfigContent) {
    return {
      recommendations: $Rb((extensionsConfigContent.recommendations || []).map((e) => e.toLowerCase())),
      unwantedRecommendations: $Rb((extensionsConfigContent.unwantedRecommendations || []).map((e) => e.toLowerCase()))
    };
  }
  D(path, array2, value) {
    const index = array2?.indexOf(value);
    if (index !== void 0 && index !== -1) {
      return { path: [...path, index], value: void 0 };
    }
    return void 0;
  }
};
$GBb = __decorate([
  __param(0, $Zk),
  __param(1, $km),
  __param(2, $1M),
  __param(3, $sG),
  __param(4, $1E),
  __param(5, $CBb)
], $GBb);
$SC(
  $FBb,
  $GBb,
  1
  /* InstantiationType.Delayed */
);

// out-build/vs/platform/userDataSync/common/userDataSync.js
function $KBb() {
  const allSettings = $Wn.as($Ht.Configuration).getConfigurationProperties();
  return Object.keys(allSettings).filter((setting) => !!allSettings[setting].disallowSyncIgnore);
}
function $LBb(excludeExtensions = false) {
  const allSettings = $Wn.as($Ht.Configuration).getConfigurationProperties();
  const ignoredSettings = getIgnoredSettings(allSettings, excludeExtensions);
  const disallowedSettings = $KBb();
  return $Rb([...ignoredSettings, ...disallowedSettings]);
}
function $MBb(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 = $Xt(configurations);
  return getIgnoredSettings(properties, false);
}
function getIgnoredSettings(properties, excludeExtensions) {
  const ignoredSettings = /* @__PURE__ */ new Set();
  for (const key2 in properties) {
    if (excludeExtensions && !!properties[key2].source) {
      continue;
    }
    const scope = $zg(properties[key2].scope) ? $Yt(properties[key2].scope) : properties[key2].scope;
    if (properties[key2].ignoreSync || scope === 2 || scope === 6) {
      ignoredSettings.add(key2);
    }
  }
  return [...ignoredSettings.values()];
}
var $NBb = "settingsSync";
var $OBb = "settingsSync.keybindingsPerPlatform";
function $PBb() {
  const ignoredSettingsSchemaId = "vscode://schemas/ignoredSettings";
  const configurationRegistry22 = $Wn.as($Ht.Configuration);
  configurationRegistry22.registerConfiguration({
    id: "settingsSync",
    order: 30,
    title: localize(2502, null),
    type: "object",
    properties: {
      [$OBb]: {
        type: "boolean",
        description: localize(2503, null),
        default: true,
        scope: 1,
        tags: ["sync", "usesOnlineServices"]
      },
      "settingsSync.ignoredExtensions": {
        "type": "array",
        markdownDescription: localize(2504, null),
        items: [{
          type: "string",
          pattern: $cA,
          errorMessage: localize(2505, null)
        }],
        "default": [],
        "scope": 1,
        uniqueItems: true,
        disallowSyncIgnore: true,
        tags: ["sync", "usesOnlineServices"]
      },
      "settingsSync.ignoredSettings": {
        "type": "array",
        description: localize(2506, null),
        "default": [],
        "scope": 1,
        $ref: ignoredSettingsSchemaId,
        additionalProperties: true,
        uniqueItems: true,
        disallowSyncIgnore: true,
        tags: ["sync", "usesOnlineServices"]
      }
    }
  });
  const jsonRegistry6 = $Wn.as($Xn.JSONContribution);
  const registerIgnoredSettingsSchema = () => {
    const disallowedIgnoredSettings = $KBb();
    const defaultIgnoredSettings = $LBb();
    const settings = Object.keys($It.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}`)]
      }
    };
    jsonRegistry6.registerSchema(ignoredSettingsSchemaId, ignoredSettingsSchema);
  };
  return configurationRegistry22.onDidUpdateConfiguration(() => registerIgnoredSettingsSchema());
}
function $QBb(thing) {
  return thing && $Bg(thing) && $zg(thing.id) && Array.isArray(thing.scopes);
}
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 $RBb = [
  "settings",
  "keybindings",
  "snippets",
  "tasks",
  "extensions",
  "globalState",
  "profiles"
  /* SyncResource.Profiles */
];
function $SBb(collection, ...paths) {
  return collection ? [collection, ...paths] : paths;
}
function $TBb(collection, syncResource, environmentService, extUri) {
  return extUri.joinPath(environmentService.userDataSyncHome, ...$SBb(collection, syncResource, `lastSync${syncResource}.json`));
}
var $UBb = $Qk("IUserDataSyncStoreManagementService");
var $VBb = $Qk("IUserDataSyncStoreService");
var $WBb = $Qk("IUserDataSyncLocalStoreService");
var $XBb = "x-operation-id";
var $YBb = "X-Execution-Id";
function $ZBb(executionId) {
  const headers = {};
  headers[$YBb] = 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 $1Bb = 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 $2Bb = class extends $1Bb {
  constructor(message, url, code, serverCode, operationId) {
    super(message, code, void 0, operationId);
    this.url = url;
    this.serverCode = serverCode;
  }
};
var $3Bb = class extends $1Bb {
  constructor(message, code) {
    super(message, code);
  }
};
(function($1Bb2) {
  function toUserDataSyncError(error) {
    if (error instanceof $1Bb2) {
      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 $1Bb2(error.message, match[1], syncResource, operationId);
    }
    return new $1Bb2(
      error.message,
      "Unknown"
      /* UserDataSyncErrorCode.Unknown */
    );
  }
  $1Bb2.toUserDataSyncError = toUserDataSyncError;
})($1Bb || ($1Bb = {}));
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 $4Bb = "sync.store.url.type";
function $5Bb(resource) {
  return `sync.enable.${resource}`;
}
var $6Bb = $Qk("IUserDataSyncEnablementService");
var $7Bb = $Qk("IUserDataSyncService");
var $8Bb = $Qk("IUserDataSyncResourceProviderService");
var $9Bb = $Qk("IUserDataAutoSyncService");
var $0Bb = $Qk("IUserDataSyncUtilService");
var $$Bb = $Qk("IUserDataSyncLogService");
var $_Bb = "userDataSync";
var $aCb = "vscode-userdata-sync";
var $bCb = "preview";

// out-build/vs/workbench/contrib/extensions/browser/extensionsIcons.js
var $cCb = $9r("extensions-view-icon", $6l.extensions, localize(6785, null));
var $dCb = $9r("extensions-manage", $6l.gear, localize(6786, null));
var $eCb = $9r("extensions-clear-search-results", $6l.clearAll, localize(6787, null));
var $fCb = $9r("extensions-refresh", $6l.refresh, localize(6788, null));
var $gCb = $9r("extensions-filter", $6l.filter, localize(6789, null));
var $hCb = $9r("extensions-install-local-in-remote", $6l.cloudDownload, localize(6790, null));
var $iCb = $9r("extensions-install-workspace-recommended", $6l.cloudDownload, localize(6791, null));
var $jCb = $9r("extensions-configure-recommended", $6l.pencil, localize(6792, null));
var $kCb = $9r("extensions-sync-enabled", $6l.sync, localize(6793, null));
var $lCb = $9r("extensions-sync-ignored", $6l.syncIgnored, localize(6794, null));
var $mCb = $9r("extensions-remote", $6l.remote, localize(6795, null));
var $nCb = $9r("extensions-install-count", $6l.cloudDownload, localize(6796, null));
var $oCb = $9r("extensions-rating", $6l.star, localize(6797, null));
var $pCb = $9r("extensions-verified-publisher", $6l.verifiedFilled, localize(6798, null));
var $qCb = $9r("extensions-pre-release", $6l.versions, localize(6799, null));
var $rCb = $9r("extensions-sponsor", $6l.heartFilled, localize(6800, null));
var $sCb = $9r("extensions-star-full", $6l.starFull, localize(6801, null));
var $tCb = $9r("extensions-star-half", $6l.starHalf, localize(6802, null));
var $uCb = $9r("extensions-star-empty", $6l.starEmpty, localize(6803, null));
var $vCb = $9r("extensions-error-message", $6l.error, localize(6804, null));
var $wCb = $9r("extensions-warning-message", $6l.warning, localize(6805, null));
var $xCb = $9r("extensions-info-message", $6l.info, localize(6806, null));
var $yCb = $9r("extension-workspace-trust", $6l.shield, localize(6807, null));
var $zCb = $9r("extension-activation-time", $6l.history, localize(6808, null));

// out-build/vs/workbench/services/workspaces/common/workspaceTrust.js
var $ACb = "security.workspace.trust.enabled";
var $BCb = "security.workspace.trust.startupPrompt";
var $CCb = "security.workspace.trust.banner";
var $DCb = "security.workspace.trust.untrustedFiles";
var $ECb = "security.workspace.trust.emptyWindow";
var $FCb = "extensions.supportUntrustedWorkspaces";
var $GCb = "content.trust.model.key";
var $HCb = class {
  constructor(a, b, c) {
    this.a = a;
    this.b = b;
    this.c = c;
  }
  get folders() {
    return this.a.folders.map((folder, index) => {
      return {
        index: folder.index,
        name: folder.name,
        toResource: folder.toResource,
        uri: this.b[index]
      };
    });
  }
  get transient() {
    return this.a.transient;
  }
  get configuration() {
    return this.c ?? this.a.configuration;
  }
  get id() {
    return this.a.id;
  }
};
var $ICb = class $ICb2 extends $3c {
  constructor(a, b) {
    super();
    this.a = a;
    this.b = b;
  }
  isWorkspaceTrustEnabled() {
    if (this.b.disableWorkspaceTrust) {
      return false;
    }
    return !!this.a.getValue($ACb);
  }
};
$ICb = __decorate([
  __param(0, $kl),
  __param(1, $US)
], $ICb);
var $JCb = class $JCb2 extends $3c {
  constructor(D, F, G, H, I, J, L, M) {
    super();
    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.a = $GCb;
    this.j = this.B(new $ze());
    this.onDidChangeTrust = this.j.event;
    this.m = this.B(new $ze());
    this.onDidChangeTrustedFolders = this.m.event;
    this.n = [];
    this.s = false;
    this.r = this.J.getWorkspace();
    ({ promise: this.b, resolve: this.c } = $Oh());
    ({ promise: this.g, resolve: this.h } = $Oh());
    this.z = new WorkspaceTrustMemento($r && this.ab() ? void 0 : this.G);
    this.C = this.B(new WorkspaceTrustTransitionManager());
    this.w = this.R();
    this.t = this.W();
    this.N();
    this.O();
  }
  //#region initialize
  N() {
    this.Q().then(async () => {
      this.s = true;
      await this.X();
    }).finally(() => {
      this.c();
      if (!this.I.remoteAuthority) {
        this.h();
      }
    });
    if (this.I.remoteAuthority) {
      this.F.resolveAuthority(this.I.remoteAuthority).then(async (result) => {
        this.y = result;
        await this.M.activateProvider(Schemas.vscodeRemote);
        await this.X();
      }).finally(() => {
        this.h();
      });
    }
    if (this.ab()) {
      this.g.then(() => {
        if (this.z.isEmptyWorkspaceTrusted === void 0) {
          this.z.isEmptyWorkspaceTrusted = this.isWorkspaceTrusted();
        }
      });
    }
  }
  //#endregion
  //#region private interface
  O() {
    this.B(this.J.onDidChangeWorkspaceFolders(async () => await this.X()));
    this.B(this.G.onDidChangeValue(-1, this.a, this.q)(async () => {
      if (JSON.stringify(this.w) !== JSON.stringify(this.R())) {
        this.w = this.R();
        this.m.fire();
        await this.X();
      }
    }));
  }
  async P(uri) {
    let canonicalUri = uri;
    if (this.I.remoteAuthority && uri.scheme === Schemas.vscodeRemote) {
      canonicalUri = await this.F.getCanonicalURI(uri);
    } else if (uri.scheme === "vscode-vfs") {
      const index = uri.authority.indexOf("+");
      if (index !== -1) {
        canonicalUri = uri.with({ authority: uri.authority.substr(0, index) });
      }
    }
    return canonicalUri.with({ query: null, fragment: null });
  }
  async Q() {
    const filesToOpen = [];
    if (this.I.filesToOpenOrCreate) {
      filesToOpen.push(...this.I.filesToOpenOrCreate);
    }
    if (this.I.filesToDiff) {
      filesToOpen.push(...this.I.filesToDiff);
    }
    if (this.I.filesToMerge) {
      filesToOpen.push(...this.I.filesToMerge);
    }
    if (filesToOpen.length) {
      const filesToOpenOrCreateUris = filesToOpen.filter((f) => !!f.fileUri).map((f) => f.fileUri);
      const canonicalFilesToOpen = await Promise.all(filesToOpenOrCreateUris.map((uri) => this.P(uri)));
      this.n.push(...canonicalFilesToOpen.filter((uri) => this.n.every((u) => !this.H.extUri.isEqual(uri, u))));
    }
    const workspaceUris = this.J.getWorkspace().folders.map((f) => f.uri);
    const canonicalWorkspaceFolders = await Promise.all(workspaceUris.map((uri) => this.P(uri)));
    let canonicalWorkspaceConfiguration = this.J.getWorkspace().configuration;
    if (canonicalWorkspaceConfiguration && $il(canonicalWorkspaceConfiguration, this.I)) {
      canonicalWorkspaceConfiguration = await this.P(canonicalWorkspaceConfiguration);
    }
    this.r = new $HCb(this.J.getWorkspace(), canonicalWorkspaceFolders, canonicalWorkspaceConfiguration);
  }
  R() {
    const infoAsString = this.G.get(
      this.a,
      -1
      /* StorageScope.APPLICATION */
    );
    let result;
    try {
      if (infoAsString) {
        result = JSON.parse(infoAsString);
      }
    } catch {
    }
    if (!result) {
      result = {
        uriTrustInfo: []
      };
    }
    if (!result.uriTrustInfo) {
      result.uriTrustInfo = [];
    }
    result.uriTrustInfo = result.uriTrustInfo.map((info) => {
      return { uri: URI.revive(info.uri), trusted: info.trusted };
    });
    result.uriTrustInfo = result.uriTrustInfo.filter((info) => info.trusted);
    return result;
  }
  async S() {
    this.G.store(
      this.a,
      JSON.stringify(this.w),
      -1,
      1
      /* StorageTarget.MACHINE */
    );
    this.m.fire();
    await this.X();
  }
  U() {
    const workspaceUris = this.r.folders.map((f) => f.uri);
    const workspaceConfiguration = this.r.configuration;
    if (workspaceConfiguration && $il(workspaceConfiguration, this.I)) {
      workspaceUris.push(workspaceConfiguration);
    }
    return workspaceUris;
  }
  W() {
    if (!this.L.isWorkspaceTrustEnabled()) {
      return true;
    }
    if (!this.s) {
      return false;
    }
    if (this.I.remoteAuthority && this.y?.options?.isTrusted) {
      return this.y.options.isTrusted;
    }
    if (this.ab()) {
      if (this.z.isEmptyWorkspaceTrusted !== void 0) {
        return this.z.isEmptyWorkspaceTrusted;
      }
      if (this.n.length) {
        return this.Y(this.n);
      }
      return !!this.D.getValue($ECb);
    }
    return this.Y(this.U());
  }
  async X(trusted) {
    if (!this.L.isWorkspaceTrustEnabled()) {
      return;
    }
    if (trusted === void 0) {
      await this.Q();
      trusted = this.W();
    }
    if (this.isWorkspaceTrusted() === trusted) {
      return;
    }
    this.db = trusted;
    await this.C.participate(trusted);
    this.j.fire(trusted);
  }
  Y(uris) {
    let state = true;
    for (const uri of uris) {
      const { trusted } = this.Z(uri);
      if (!trusted) {
        state = trusted;
        return state;
      }
    }
    return state;
  }
  Z(uri) {
    if (!this.L.isWorkspaceTrustEnabled()) {
      return { trusted: true, uri };
    }
    if (this.bb(uri)) {
      return { trusted: true, uri };
    }
    if (this.cb(uri)) {
      return { trusted: true, uri };
    }
    let resultState = false;
    let maxLength = -1;
    let resultUri = uri;
    for (const trustInfo of this.w.uriTrustInfo) {
      if (this.H.extUri.isEqualOrParent(uri, trustInfo.uri)) {
        const fsPath = trustInfo.uri.fsPath;
        if (fsPath.length > maxLength) {
          maxLength = fsPath.length;
          resultState = trustInfo.trusted;
          resultUri = trustInfo.uri;
        }
      }
    }
    return { trusted: resultState, uri: resultUri };
  }
  async $(uris, trusted) {
    let changed = false;
    for (const uri of uris) {
      if (trusted) {
        if (this.bb(uri)) {
          continue;
        }
        if (this.cb(uri)) {
          continue;
        }
        const foundItem = this.w.uriTrustInfo.find((trustInfo) => this.H.extUri.isEqual(trustInfo.uri, uri));
        if (!foundItem) {
          this.w.uriTrustInfo.push({ uri, trusted: true });
          changed = true;
        }
      } else {
        const previousLength = this.w.uriTrustInfo.length;
        this.w.uriTrustInfo = this.w.uriTrustInfo.filter((trustInfo) => !this.H.extUri.isEqual(trustInfo.uri, uri));
        if (previousLength !== this.w.uriTrustInfo.length) {
          changed = true;
        }
      }
    }
    if (changed) {
      await this.S();
    }
  }
  ab() {
    if (this.J.getWorkbenchState() === 1) {
      return true;
    }
    const workspace2 = this.J.getWorkspace();
    if (workspace2) {
      return $fl(this.J.getWorkspace()) && workspace2.folders.length === 0;
    }
    return false;
  }
  bb(uri) {
    return $8S(uri) && uri.scheme !== "vscode-vfs";
  }
  cb(uri) {
    if (!this.I.remoteAuthority) {
      return false;
    }
    if (!this.y) {
      return false;
    }
    return $Ah($8v(uri), this.y.authority.authority) && !!this.y.options?.isTrusted;
  }
  set db(value) {
    this.t = value;
    if (!value) {
      this.z.acceptsOutOfWorkspaceFiles = false;
    }
    if (this.ab()) {
      this.z.isEmptyWorkspaceTrusted = value;
    }
  }
  //#endregion
  //#region public interface
  get workspaceResolved() {
    return this.b;
  }
  get workspaceTrustInitialized() {
    return this.g;
  }
  get acceptsOutOfWorkspaceFiles() {
    return this.z.acceptsOutOfWorkspaceFiles;
  }
  set acceptsOutOfWorkspaceFiles(value) {
    this.z.acceptsOutOfWorkspaceFiles = value;
  }
  isWorkspaceTrusted() {
    return this.t;
  }
  isWorkspaceTrustForced() {
    if (this.I.remoteAuthority && this.y && this.y.options?.isTrusted !== void 0) {
      return true;
    }
    const workspaceUris = this.U().filter((uri) => !this.bb(uri));
    if (workspaceUris.length === 0) {
      return true;
    }
    return false;
  }
  canSetParentFolderTrust() {
    const workspaceIdentifier = $5k(this.r);
    if (!$1k(workspaceIdentifier)) {
      return false;
    }
    if (workspaceIdentifier.uri.scheme !== Schemas.file && workspaceIdentifier.uri.scheme !== Schemas.vscodeRemote) {
      return false;
    }
    const parentFolder = this.H.extUri.dirname(workspaceIdentifier.uri);
    if (this.H.extUri.isEqual(workspaceIdentifier.uri, parentFolder)) {
      return false;
    }
    return true;
  }
  async setParentFolderTrust(trusted) {
    if (this.canSetParentFolderTrust()) {
      const workspaceUri = $5k(this.r).uri;
      const parentFolder = this.H.extUri.dirname(workspaceUri);
      await this.setUrisTrust([parentFolder], trusted);
    }
  }
  canSetWorkspaceTrust() {
    if (this.I.remoteAuthority && (!this.y || this.y.options?.isTrusted !== void 0)) {
      return false;
    }
    if (this.ab()) {
      return true;
    }
    const workspaceUris = this.U().filter((uri) => !this.bb(uri));
    if (workspaceUris.length === 0) {
      return false;
    }
    if (!this.isWorkspaceTrusted()) {
      return true;
    }
    const workspaceIdentifier = $5k(this.r);
    if (!$1k(workspaceIdentifier)) {
      return false;
    }
    if (workspaceIdentifier.uri.scheme !== Schemas.file && workspaceIdentifier.uri.scheme !== "vscode-vfs") {
      return false;
    }
    const trustInfo = this.Z(workspaceIdentifier.uri);
    if (!trustInfo.trusted || !this.H.extUri.isEqual(workspaceIdentifier.uri, trustInfo.uri)) {
      return false;
    }
    if (this.canSetParentFolderTrust()) {
      const parentFolder = this.H.extUri.dirname(workspaceIdentifier.uri);
      const parentPathTrustInfo = this.Z(parentFolder);
      if (parentPathTrustInfo.trusted) {
        return false;
      }
    }
    return true;
  }
  async setWorkspaceTrust(trusted) {
    if (this.ab()) {
      await this.X(trusted);
      return;
    }
    const workspaceFolders = this.U();
    await this.setUrisTrust(workspaceFolders, trusted);
  }
  async getUriTrustInfo(uri) {
    if (!this.L.isWorkspaceTrustEnabled()) {
      return { trusted: true, uri };
    }
    if (this.cb(uri)) {
      return { trusted: true, uri };
    }
    return this.Z(await this.P(uri));
  }
  async setUrisTrust(uris, trusted) {
    this.$(await Promise.all(uris.map((uri) => this.P(uri))), trusted);
  }
  getTrustedUris() {
    return this.w.uriTrustInfo.map((info) => info.uri);
  }
  async setTrustedUris(uris) {
    this.w.uriTrustInfo = [];
    for (const uri of uris) {
      const canonicalUri = await this.P(uri);
      const cleanUri = this.H.extUri.removeTrailingPathSeparator(canonicalUri);
      let added = false;
      for (const addedUri of this.w.uriTrustInfo) {
        if (this.H.extUri.isEqual(addedUri.uri, cleanUri)) {
          added = true;
          break;
        }
      }
      if (added) {
        continue;
      }
      this.w.uriTrustInfo.push({
        trusted: true,
        uri: cleanUri
      });
    }
    await this.S();
  }
  addWorkspaceTrustTransitionParticipant(participant) {
    return this.C.addWorkspaceTrustTransitionParticipant(participant);
  }
};
$JCb = __decorate([
  __param(0, $kl),
  __param(1, $bC),
  __param(2, $jv),
  __param(3, $vl),
  __param(4, $US),
  __param(5, $Zk),
  __param(6, $3M),
  __param(7, $km)
], $JCb);
var $KCb = class $KCb2 extends $3c {
  constructor(n, r2) {
    super();
    this.n = n;
    this.r = r2;
    this.h = this.B(new $ze());
    this.onDidInitiateOpenFilesTrustRequest = this.h.event;
    this.j = this.B(new $ze());
    this.onDidInitiateWorkspaceTrustRequest = this.j.event;
    this.m = this.B(new $ze());
    this.onDidInitiateWorkspaceTrustRequestOnStartup = this.m.event;
  }
  //#region Open file(s) trust request
  get s() {
    return this.n.getValue($DCb);
  }
  set s(value) {
    this.n.updateValue($DCb, value);
  }
  async completeOpenFilesTrustRequest(result, saveResponse) {
    if (!this.b) {
      return;
    }
    if (result === 1) {
      this.r.acceptsOutOfWorkspaceFiles = true;
    }
    if (saveResponse) {
      if (result === 1) {
        this.s = "open";
      }
      if (result === 2) {
        this.s = "newWindow";
      }
    }
    this.b(result);
    this.b = void 0;
    this.a = void 0;
  }
  async requestOpenFilesTrust(uris) {
    if (!this.r.isWorkspaceTrusted()) {
      return 1;
    }
    const openFilesTrustInfo = await Promise.all(uris.map((uri) => this.r.getUriTrustInfo(uri)));
    if (openFilesTrustInfo.map((info) => info.trusted).every((trusted) => trusted)) {
      return 1;
    }
    if (this.s !== "prompt") {
      if (this.s === "newWindow") {
        return 2;
      }
      if (this.s === "open") {
        return 1;
      }
    }
    if (this.r.acceptsOutOfWorkspaceFiles) {
      return 1;
    }
    if (!this.a) {
      this.a = new Promise((resolve) => {
        this.b = resolve;
      });
    } else {
      return this.a;
    }
    this.h.fire();
    return this.a;
  }
  //#endregion
  //#region Workspace trust request
  t(trusted) {
    if (this.g) {
      this.g(trusted ?? this.r.isWorkspaceTrusted());
      this.g = void 0;
      this.c = void 0;
    }
  }
  cancelWorkspaceTrustRequest() {
    if (this.g) {
      this.g(void 0);
      this.g = void 0;
      this.c = void 0;
    }
  }
  async completeWorkspaceTrustRequest(trusted) {
    if (trusted === void 0 || trusted === this.r.isWorkspaceTrusted()) {
      this.t(trusted);
      return;
    }
    Event2.once(this.r.onDidChangeTrust)((trusted2) => this.t(trusted2));
    await this.r.setWorkspaceTrust(trusted);
  }
  async requestWorkspaceTrust(options3) {
    if (this.r.isWorkspaceTrusted()) {
      return this.r.isWorkspaceTrusted();
    }
    if (!this.c) {
      this.c = new Promise((resolve) => {
        this.g = resolve;
      });
    } else {
      return this.c;
    }
    this.j.fire(options3);
    return this.c;
  }
  requestWorkspaceTrustOnStartup() {
    if (!this.c) {
      this.c = new Promise((resolve) => {
        this.g = resolve;
      });
    }
    this.m.fire();
  }
};
$KCb = __decorate([
  __param(0, $kl),
  __param(1, $4M)
], $KCb);
var WorkspaceTrustTransitionManager = class extends $3c {
  constructor() {
    super(...arguments);
    this.a = new $cd();
  }
  addWorkspaceTrustTransitionParticipant(participant) {
    const remove = this.a.push(participant);
    return $1c(() => remove());
  }
  async participate(trusted) {
    for (const participant of this.a) {
      await participant.participate(trusted);
    }
  }
  dispose() {
    this.a.clear();
    super.dispose();
  }
};
var WorkspaceTrustMemento = class {
  constructor(storageService) {
    this.c = "acceptsOutOfWorkspaceFiles";
    this.d = "isEmptyWorkspaceTrusted";
    if (storageService) {
      this.a = new $Slb("workspaceTrust", storageService);
      this.b = this.a.getMemento(
        1,
        1
        /* StorageTarget.MACHINE */
      );
    } else {
      this.b = {};
    }
  }
  get acceptsOutOfWorkspaceFiles() {
    return this.b[this.c] ?? false;
  }
  set acceptsOutOfWorkspaceFiles(value) {
    this.b[this.c] = value;
    this.a?.saveMemento();
  }
  get isEmptyWorkspaceTrusted() {
    return this.b[this.d];
  }
  set isEmptyWorkspaceTrusted(value) {
    this.b[this.d] = value;
    this.a?.saveMemento();
  }
};
$SC(
  $5M,
  $KCb,
  1
  /* InstantiationType.Delayed */
);

// out-build/vs/workbench/services/extensions/common/extensionManifestPropertiesService.js
var $LCb = $Qk("extensionManifestPropertiesService");
var $MCb = class $MCb2 extends $3c {
  constructor(m, n, s, t) {
    super();
    this.m = m;
    this.n = n;
    this.s = s;
    this.t = t;
    this.a = null;
    this.b = null;
    this.c = null;
    this.f = null;
    this.g = null;
    this.h = new $7z();
    const configuredExtensionWorkspaceTrustRequests = n.inspect($FCb).userValue || {};
    for (const id2 of Object.keys(configuredExtensionWorkspaceTrustRequests)) {
      this.h.set(id2, configuredExtensionWorkspaceTrustRequests[id2]);
    }
    this.j = /* @__PURE__ */ new Map();
    if (m.extensionUntrustedWorkspaceSupport) {
      for (const id2 of Object.keys(m.extensionUntrustedWorkspaceSupport)) {
        this.j.set(id2, m.extensionUntrustedWorkspaceSupport[id2]);
      }
    }
  }
  prefersExecuteOnUI(manifest) {
    const extensionKind = this.getExtensionKind(manifest);
    return extensionKind.length > 0 && extensionKind[0] === "ui";
  }
  prefersExecuteOnWorkspace(manifest) {
    const extensionKind = this.getExtensionKind(manifest);
    return extensionKind.length > 0 && extensionKind[0] === "workspace";
  }
  prefersExecuteOnWeb(manifest) {
    const extensionKind = this.getExtensionKind(manifest);
    return extensionKind.length > 0 && extensionKind[0] === "web";
  }
  canExecuteOnUI(manifest) {
    const extensionKind = this.getExtensionKind(manifest);
    return extensionKind.some((kind) => kind === "ui");
  }
  canExecuteOnWorkspace(manifest) {
    const extensionKind = this.getExtensionKind(manifest);
    return extensionKind.some((kind) => kind === "workspace");
  }
  canExecuteOnWeb(manifest) {
    const extensionKind = this.getExtensionKind(manifest);
    return extensionKind.some((kind) => kind === "web");
  }
  getExtensionKind(manifest) {
    const deducedExtensionKind = this.u(manifest);
    const configuredExtensionKind = this.y(manifest);
    if (configuredExtensionKind && configuredExtensionKind.length > 0) {
      const result = [];
      for (const extensionKind of configuredExtensionKind) {
        if (extensionKind !== "-web") {
          result.push(extensionKind);
        }
      }
      if (configuredExtensionKind.includes("-web") && !result.length) {
        result.push("ui");
        result.push("workspace");
      }
      if ($r && !configuredExtensionKind.includes("-web") && !configuredExtensionKind.includes("web") && deducedExtensionKind.includes("web")) {
        result.push("web");
      }
      return result;
    }
    return deducedExtensionKind;
  }
  getUserConfiguredExtensionKind(extensionIdentifier) {
    if (this.c === null) {
      const configuredExtensionKindsMap = new $7z();
      const configuredExtensionKinds = this.n.getValue("remote.extensionKind") || {};
      for (const id2 of Object.keys(configuredExtensionKinds)) {
        configuredExtensionKindsMap.set(id2, configuredExtensionKinds[id2]);
      }
      this.c = configuredExtensionKindsMap;
    }
    const userConfiguredExtensionKind = this.c.get(extensionIdentifier.id);
    return userConfiguredExtensionKind ? this.H(userConfiguredExtensionKind) : void 0;
  }
  getExtensionUntrustedWorkspaceSupportType(manifest) {
    if (!this.s.isWorkspaceTrustEnabled() || !manifest.main) {
      return true;
    }
    const configuredWorkspaceTrustRequest = this.F(manifest);
    const productWorkspaceTrustRequest = this.G(manifest);
    if (configuredWorkspaceTrustRequest !== void 0) {
      return configuredWorkspaceTrustRequest;
    }
    if (productWorkspaceTrustRequest?.override !== void 0) {
      return productWorkspaceTrustRequest.override;
    }
    if (manifest.capabilities?.untrustedWorkspaces?.supported !== void 0) {
      return manifest.capabilities.untrustedWorkspaces.supported;
    }
    if (productWorkspaceTrustRequest?.default !== void 0) {
      return productWorkspaceTrustRequest.default;
    }
    return false;
  }
  getExtensionVirtualWorkspaceSupportType(manifest) {
    const userConfiguredVirtualWorkspaceSupport = this.D(manifest);
    if (userConfiguredVirtualWorkspaceSupport !== void 0) {
      return userConfiguredVirtualWorkspaceSupport;
    }
    const productConfiguredWorkspaceSchemes = this.C(manifest);
    if (productConfiguredWorkspaceSchemes?.override !== void 0) {
      return productConfiguredWorkspaceSchemes.override;
    }
    const virtualWorkspaces = manifest.capabilities?.virtualWorkspaces;
    if ($Fg(virtualWorkspaces)) {
      return virtualWorkspaces;
    } else if (virtualWorkspaces) {
      const supported = virtualWorkspaces.supported;
      if ($Fg(supported) || supported === "limited") {
        return supported;
      }
    }
    if (productConfiguredWorkspaceSchemes?.default !== void 0) {
      return productConfiguredWorkspaceSchemes.default;
    }
    return true;
  }
  u(manifest) {
    if (manifest.main) {
      if (manifest.browser) {
        return $r ? ["workspace", "web"] : ["workspace"];
      }
      return ["workspace"];
    }
    if (manifest.browser) {
      return ["web"];
    }
    let result = [...$2z];
    if ($Qb(manifest.extensionPack) || $Qb(manifest.extensionDependencies)) {
      result = $r ? ["workspace", "web"] : ["workspace"];
    }
    if (manifest.contributes) {
      for (const contribution of Object.keys(manifest.contributes)) {
        const supportedExtensionKinds = this.w(contribution);
        if (supportedExtensionKinds.length) {
          result = result.filter((extensionKind) => supportedExtensionKinds.includes(extensionKind));
        }
      }
    }
    if (!result.length) {
      this.t.warn("Cannot deduce extensionKind for extension", $IA(manifest.publisher, manifest.name));
    }
    return result;
  }
  w(extensionPoint2) {
    if (this.a === null) {
      const extensionPointExtensionKindsMap = /* @__PURE__ */ new Map();
      $tN.getExtensionPoints().forEach((e) => extensionPointExtensionKindsMap.set(
        e.name,
        e.defaultExtensionKind || []
        /* supports all */
      ));
      this.a = extensionPointExtensionKindsMap;
    }
    let extensionPointExtensionKind = this.a.get(extensionPoint2);
    if (extensionPointExtensionKind) {
      return extensionPointExtensionKind;
    }
    extensionPointExtensionKind = this.m.extensionPointExtensionKind ? this.m.extensionPointExtensionKind[extensionPoint2] : void 0;
    if (extensionPointExtensionKind) {
      return extensionPointExtensionKind;
    }
    return $r ? ["workspace", "web"] : ["workspace"];
  }
  y(manifest) {
    const extensionIdentifier = { id: $IA(manifest.publisher, manifest.name) };
    let result = this.getUserConfiguredExtensionKind(extensionIdentifier);
    if (typeof result !== "undefined") {
      return this.H(result);
    }
    result = this.z(manifest);
    if (typeof result !== "undefined") {
      return result;
    }
    result = manifest.extensionKind;
    if (typeof result !== "undefined") {
      result = this.H(result);
      return result.filter((r2) => ["ui", "workspace"].includes(r2));
    }
    return null;
  }
  z(manifest) {
    if (this.b === null) {
      const productExtensionKindsMap = new $7z();
      if (this.m.extensionKind) {
        for (const id2 of Object.keys(this.m.extensionKind)) {
          productExtensionKindsMap.set(id2, this.m.extensionKind[id2]);
        }
      }
      this.b = productExtensionKindsMap;
    }
    const extensionId = $IA(manifest.publisher, manifest.name);
    return this.b.get(extensionId);
  }
  C(manifest) {
    if (this.f === null) {
      const productWorkspaceSchemesMap = new $7z();
      if (this.m.extensionVirtualWorkspacesSupport) {
        for (const id2 of Object.keys(this.m.extensionVirtualWorkspacesSupport)) {
          productWorkspaceSchemesMap.set(id2, this.m.extensionVirtualWorkspacesSupport[id2]);
        }
      }
      this.f = productWorkspaceSchemesMap;
    }
    const extensionId = $IA(manifest.publisher, manifest.name);
    return this.f.get(extensionId);
  }
  D(manifest) {
    if (this.g === null) {
      const configuredWorkspaceSchemesMap = new $7z();
      const configuredWorkspaceSchemes = this.n.getValue("extensions.supportVirtualWorkspaces") || {};
      for (const id2 of Object.keys(configuredWorkspaceSchemes)) {
        if (configuredWorkspaceSchemes[id2] !== void 0) {
          configuredWorkspaceSchemesMap.set(id2, configuredWorkspaceSchemes[id2]);
        }
      }
      this.g = configuredWorkspaceSchemesMap;
    }
    const extensionId = $IA(manifest.publisher, manifest.name);
    return this.g.get(extensionId);
  }
  F(manifest) {
    const extensionId = $IA(manifest.publisher, manifest.name);
    const extensionWorkspaceTrustRequest = this.h.get(extensionId);
    if (extensionWorkspaceTrustRequest && (extensionWorkspaceTrustRequest.version === void 0 || extensionWorkspaceTrustRequest.version === manifest.version)) {
      return extensionWorkspaceTrustRequest.supported;
    }
    return void 0;
  }
  G(manifest) {
    const extensionId = $IA(manifest.publisher, manifest.name);
    return this.j.get(extensionId);
  }
  H(extensionKind) {
    if (Array.isArray(extensionKind)) {
      return extensionKind;
    }
    return extensionKind === "ui" ? ["ui", "workspace"] : [extensionKind];
  }
};
$MCb = __decorate([
  __param(0, $Vu),
  __param(1, $kl),
  __param(2, $3M),
  __param(3, $wn)
], $MCb);
$SC(
  $LCb,
  $MCb,
  1
  /* InstantiationType.Delayed */
);

// out-build/vs/workbench/services/localization/common/locale.js
var $NCb = $Qk("localizationService");
var $OCb = $Qk("activeLanguageService");

// out-build/vs/workbench/services/log/common/logConstants.js
var $PCb = "rendererLog";
var $QCb = "workbench.action.showWindowLog";

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

// out-build/vs/workbench/services/authentication/browser/authenticationUsageService.js
var $RCb = $Qk("IAuthenticationUsageService");
var $SCb = class $SCb2 extends $3c {
  constructor(c, f, g, productService) {
    super();
    this.c = c;
    this.f = f;
    this.g = g;
    this.a = new $3h();
    this.b = /* @__PURE__ */ new Set();
    const trustedExtensionAuthAccess = productService.trustedExtensionAuthAccess;
    if (Array.isArray(trustedExtensionAuthAccess)) {
      for (const extensionId of trustedExtensionAuthAccess) {
        this.b.add(extensionId);
      }
    } else if (trustedExtensionAuthAccess) {
      for (const extensions of Object.values(trustedExtensionAuthAccess)) {
        for (const extensionId of extensions) {
          this.b.add(extensionId);
        }
      }
    }
    this.f.onDidRegisterAuthenticationProvider((provider) => this.a.queue(() => this.h(provider.id)));
  }
  async initializeExtensionUsageCache() {
    await this.a.queue(() => Promise.all(this.f.getProviderIds().map((providerId) => this.h(providerId))));
  }
  async extensionUsesAuth(extensionId) {
    await this.a.whenIdle();
    return this.b.has(extensionId);
  }
  readAccountUsages(providerId, accountName) {
    const accountKey = `${providerId}-${accountName}-usages`;
    const storedUsages = this.c.get(
      accountKey,
      -1
      /* StorageScope.APPLICATION */
    );
    let usages = [];
    if (storedUsages) {
      try {
        usages = JSON.parse(storedUsages);
      } catch (e) {
      }
    }
    return usages;
  }
  removeAccountUsage(providerId, accountName) {
    const accountKey = `${providerId}-${accountName}-usages`;
    this.c.remove(
      accountKey,
      -1
      /* StorageScope.APPLICATION */
    );
  }
  addAccountUsage(providerId, accountName, scopes, extensionId, extensionName) {
    const accountKey = `${providerId}-${accountName}-usages`;
    const usages = this.readAccountUsages(providerId, accountName);
    const existingUsageIndex = usages.findIndex((usage) => usage.extensionId === extensionId);
    if (existingUsageIndex > -1) {
      usages.splice(existingUsageIndex, 1, {
        extensionId,
        extensionName,
        scopes,
        lastUsed: Date.now()
      });
    } else {
      usages.push({
        extensionId,
        extensionName,
        scopes,
        lastUsed: Date.now()
      });
    }
    this.c.store(
      accountKey,
      JSON.stringify(usages),
      -1,
      1
      /* StorageTarget.MACHINE */
    );
    this.b.add(extensionId);
  }
  async h(providerId) {
    try {
      const accounts = await this.f.getAccounts(providerId);
      for (const account of accounts) {
        const usage = this.readAccountUsages(providerId, account.label);
        for (const u of usage) {
          this.b.add(u.extensionId);
        }
      }
    } catch (e) {
      this.g.error(e);
    }
  }
};
$SCb = __decorate([
  __param(0, $jv),
  __param(1, $xS),
  __param(2, $wn),
  __param(3, $Vu)
], $SCb);
$SC(
  $RCb,
  $SCb,
  1
  /* InstantiationType.Delayed */
);

// out-build/vs/workbench/contrib/extensions/browser/extensionsActions.js
var $XCb_1;
var $1Cb_1;
var $5Cb_1;
var $6Cb_1;
var $7Cb_1;
var $8Cb_1;
var $9Cb_1;
var $aDb_1;
var $dDb_1;
var $eDb_1;
var $fDb_1;
var $gDb_1;
var $hDb_1;
var $iDb_1;
var $lDb_1;
var $mDb_1;
var $nDb_1;
var $oDb_1;
var $pDb_1;
var $qDb_1;
var $rDb_1;
var $sDb_1;
var $tDb_1;
var $uDb_1;
var $yDb_1;
var $zDb_1;
var $ADb_1;
var $BDb_1;
var $CDb_1;
var $TCb = class $TCb2 extends $Um {
  constructor(f, g, h3, t, L, M, N, O, P, Q, R, S, U, W, X) {
    super("extension.promptExtensionInstallFailure");
    this.f = f;
    this.g = g;
    this.h = h3;
    this.t = t;
    this.L = L;
    this.M = M;
    this.N = N;
    this.O = O;
    this.P = P;
    this.Q = Q;
    this.R = R;
    this.S = S;
    this.U = U;
    this.W = W;
    this.X = X;
  }
  async run() {
    if ($kb(this.L)) {
      return;
    }
    this.R.error(this.L);
    if (this.L.name === "Unsupported") {
      const productName = $r ? localize(6603, null, this.M.nameLong) : this.M.nameLong;
      const message2 = localize(6604, null, this.f.displayName || this.f.identifier.id, productName);
      const { confirmed } = await this.P.confirm({
        type: Severity2.Info,
        message: message2,
        primaryButton: localize(6605, null),
        cancelButton: localize(6606, null)
      });
      if (confirmed) {
        this.N.open($r ? URI.parse("https://aka.ms/vscode-web-extensions-guide") : URI.parse("https://aka.ms/vscode-remote"));
      }
      return;
    }
    if ("ReleaseVersionNotFound" === this.L.name) {
      await this.P.prompt({
        type: "error",
        message: $qb(this.L),
        buttons: [{
          label: localize(6607, null),
          run: () => {
            const installAction = this.U.createInstance($XCb, { installPreReleaseVersion: true });
            installAction.extension = this.f;
            return installAction.run();
          }
        }],
        cancelButton: localize(6608, null)
      });
      return;
    }
    if ([
      "Incompatible",
      "IncompatibleApi",
      "IncompatibleTargetPlatform",
      "Malicious",
      "Deprecated"
      /* ExtensionManagementErrorCode.Deprecated */
    ].includes(this.L.name)) {
      await this.P.info($qb(this.L));
      return;
    }
    if ("PackageNotSigned" === this.L.name) {
      await this.P.prompt({
        type: "error",
        message: localize(6609, null, this.f.displayName),
        detail: $qb(this.L),
        buttons: [{
          label: localize(6610, null),
          run: () => {
            const installAction = this.U.createInstance($XCb, { ...this.g, donotVerifySignature: true });
            installAction.extension = this.f;
            return installAction.run();
          }
        }],
        cancelButton: true
      });
      return;
    }
    if ("SignatureVerificationFailed" === this.L.name || "SignatureVerificationInternal" === this.L.name) {
      await this.P.prompt({
        type: "error",
        message: localize(6611, null, this.f.displayName, this.M.nameLong),
        detail: $qb(this.L),
        buttons: [{
          label: localize(6612, null),
          run: () => this.N.open("https://code.visualstudio.com/docs/editor/extension-marketplace#_the-extension-signature-cannot-be-verified-by-vs-code")
        }, {
          label: localize(6613, null),
          run: () => {
            const installAction = this.U.createInstance($XCb, { ...this.g, donotVerifySignature: true });
            installAction.extension = this.f;
            return installAction.run();
          }
        }],
        cancelButton: true
      });
      return;
    }
    const operationMessage = this.t === 3 ? localize(6614, null, this.f.displayName || this.f.identifier.id) : localize(6615, null, this.f.displayName || this.f.identifier.id);
    let additionalMessage;
    const promptChoices = [];
    const downloadUrl = await this.Y();
    if (downloadUrl) {
      additionalMessage = localize(6616, null, `command:${$QCb}`);
      promptChoices.push({
        label: localize(6617, null),
        run: () => this.N.open(downloadUrl).then(() => {
          this.O.prompt(Severity2.Info, localize(6618, null, this.f.identifier.id), [{
            label: localize(6619, null),
            run: () => this.Q.executeCommand($Fzb)
          }]);
        })
      });
    }
    const message = `${operationMessage}${additionalMessage ? ` ${additionalMessage}` : ""}`;
    this.O.prompt(Severity2.Error, message, promptChoices);
  }
  async Y() {
    if ($u) {
      return void 0;
    }
    if (!this.f.gallery) {
      return void 0;
    }
    if (!this.M.extensionsGallery) {
      return void 0;
    }
    if (!this.S.localExtensionManagementServer && !this.S.remoteExtensionManagementServer) {
      return void 0;
    }
    let targetPlatform = this.f.gallery.properties.targetPlatform;
    if (targetPlatform !== "universal" && targetPlatform !== "undefined" && this.S.remoteExtensionManagementServer) {
      try {
        const manifest = await this.W.getManifest(this.f.gallery, CancellationToken.None);
        if (manifest && this.X.prefersExecuteOnWorkspace(manifest)) {
          targetPlatform = await this.S.remoteExtensionManagementServer.extensionManagementService.getTargetPlatform();
        }
      } catch (error) {
        this.R.error(error);
        return void 0;
      }
    }
    if (targetPlatform === "unknown") {
      return void 0;
    }
    return URI.parse(`${this.M.extensionsGallery.serviceUrl}/publishers/${this.f.publisher}/vsextensions/${this.f.name}/${this.h}/vspackage${targetPlatform !== "undefined" ? `?targetPlatform=${targetPlatform}` : ""}`);
  }
};
$TCb = __decorate([
  __param(5, $Vu),
  __param(6, $O4),
  __param(7, $PJ),
  __param(8, $Yv),
  __param(9, $sn),
  __param(10, $wn),
  __param(11, $nzb),
  __param(12, $Pk),
  __param(13, $pA),
  __param(14, $LCb)
], $TCb);
var $UCb = class _$UCb extends $Um {
  constructor() {
    super(...arguments);
    this.j = this.B(new $ze());
    this.onDidChange = this.j.event;
    this.g = null;
    this.h = false;
    this.L = true;
  }
  static {
    this.EXTENSION_ACTION_CLASS = "extension-action";
  }
  static {
    this.TEXT_ACTION_CLASS = `${_$UCb.EXTENSION_ACTION_CLASS} text`;
  }
  static {
    this.LABEL_ACTION_CLASS = `${_$UCb.EXTENSION_ACTION_CLASS} label`;
  }
  static {
    this.PROMINENT_LABEL_ACTION_CLASS = `${_$UCb.LABEL_ACTION_CLASS} prominent`;
  }
  static {
    this.ICON_ACTION_CLASS = `${_$UCb.EXTENSION_ACTION_CLASS} icon`;
  }
  get extension() {
    return this.g;
  }
  set extension(extension) {
    this.g = extension;
    this.update();
  }
  get hidden() {
    return this.h;
  }
  set hidden(hidden) {
    if (this.h !== hidden) {
      this.h = hidden;
      this.j.fire({ hidden });
    }
  }
  I(value) {
    super.I(value);
    if (this.L) {
      this.hidden = !value;
    }
  }
};
var $VCb = class extends $UCb {
  get menuActions() {
    return [...this.N];
  }
  get extension() {
    return super.extension;
  }
  set extension(extension) {
    this.O.forEach((a) => a.extension = extension);
    super.extension = extension;
  }
  constructor(id2, clazz, P) {
    clazz = `${clazz} action-dropdown`;
    super(id2, void 0, clazz);
    this.P = P;
    this.menuActionClassNames = [];
    this.N = [];
    this.menuActionClassNames = clazz.split(" ");
    this.L = false;
    this.O = P.flat();
    this.update();
    this.B(Event2.any(...this.O.map((a) => a.onDidChange))(() => this.update(true)));
    this.O.forEach((a) => this.B(a));
  }
  update(donotUpdateActions) {
    if (!donotUpdateActions) {
      this.O.forEach((a) => a.update());
    }
    const actionsGroups = this.P.map((actionsGroup) => actionsGroup.filter((a) => !a.hidden));
    let actions = [];
    for (const visibleActions of actionsGroups) {
      if (visibleActions.length) {
        actions = [...actions, ...visibleActions, new $Wm()];
      }
    }
    actions = actions.length ? actions.slice(0, actions.length - 1) : actions;
    this.M = actions[0];
    this.N = actions.length > 1 ? actions : [];
    this.j.fire({ menuActions: this.N });
    if (this.M) {
      this.hidden = false;
      this.enabled = this.M.enabled;
      this.label = this.Q(this.M);
      this.tooltip = this.M.tooltip;
    } else {
      this.hidden = true;
      this.enabled = false;
    }
  }
  async run() {
    if (this.enabled) {
      await this.M?.run();
    }
  }
  Q(action) {
    return action.label;
  }
};
var $WCb = class extends $M2 {
  constructor(action, options3, contextMenuProvider) {
    super(null, action, options3, contextMenuProvider);
    this.B(action.onDidChange((e) => {
      if (e.hidden !== void 0 || e.menuActions !== void 0) {
        this.I();
      }
    }));
  }
  render(container2) {
    super.render(container2);
    this.I();
  }
  I() {
    super.I();
    if (this.element && this.g?.element) {
      this.element.classList.toggle("hide", this._action.hidden);
      const isMenuEmpty = this._action.menuActions.length === 0;
      this.element.classList.toggle("empty", isMenuEmpty);
      this.g.element.classList.toggle("hide", isMenuEmpty);
    }
  }
};
var $XCb = class $XCb2 extends $UCb {
  static {
    $XCb_1 = this;
  }
  static {
    this.CLASS = `${this.LABEL_ACTION_CLASS} prominent install`;
  }
  static {
    this.M = `${this.CLASS} hide`;
  }
  set manifest(manifest) {
    this.N = manifest;
    this.eb();
  }
  constructor(options3, P, Q, R, S, U, W, X, Y, Z, $149) {
    super("extensions.install", localize(6620, null), $XCb_1.CLASS, false);
    this.P = P;
    this.Q = Q;
    this.R = R;
    this.S = S;
    this.U = U;
    this.W = W;
    this.X = X;
    this.Y = Y;
    this.Z = Z;
    this.$ = $149;
    this.N = null;
    this.O = new $Ph();
    this.L = false;
    this.options = { isMachineScoped: false, ...options3 };
    this.update();
    this.B($149.onDidChangeAllowedExtensions(() => this.update()));
    this.B(this.U.onDidChangeFormatters(() => this.eb(), this));
  }
  update() {
    this.O.queue(() => this.ab());
  }
  async ab() {
    this.enabled = false;
    this.class = $XCb_1.M;
    this.hidden = true;
    if (!this.extension) {
      return;
    }
    if (this.extension.isBuiltin) {
      return;
    }
    if (this.P.canSetLanguage(this.extension)) {
      return;
    }
    if (this.extension.state !== 3) {
      return;
    }
    if (this.options.installPreReleaseVersion && (!this.extension.hasPreReleaseVersion || this.$.isAllowed({ id: this.extension.identifier.id, publisherDisplayName: this.extension.publisherDisplayName, prerelease: true }) !== true)) {
      return;
    }
    if (!this.options.installPreReleaseVersion && !this.extension.hasReleaseVersion) {
      return;
    }
    this.hidden = false;
    this.class = $XCb_1.CLASS;
    if (await this.P.canInstall(this.extension) === true) {
      this.enabled = true;
      this.eb();
    }
  }
  async run() {
    if (!this.extension) {
      return;
    }
    if (this.extension.gallery && !this.extension.gallery.isSigned) {
      const { result } = await this.W.prompt({
        type: Severity2.Warning,
        message: localize(6621, null, this.extension.displayName),
        detail: localize(6622, null),
        buttons: [
          {
            label: localize(6623, null),
            run: () => {
              this.options.donotVerifySignature = true;
              return true;
            }
          }
        ],
        cancelButton: {
          run: () => false
        }
      });
      if (!result) {
        return;
      }
    }
    if (this.extension.deprecationInfo) {
      let detail2 = localize(6624, null);
      let DeprecationChoice;
      (function(DeprecationChoice2) {
        DeprecationChoice2[DeprecationChoice2["InstallAnyway"] = 0] = "InstallAnyway";
        DeprecationChoice2[DeprecationChoice2["ShowAlternateExtension"] = 1] = "ShowAlternateExtension";
        DeprecationChoice2[DeprecationChoice2["ConfigureSettings"] = 2] = "ConfigureSettings";
        DeprecationChoice2[DeprecationChoice2["Cancel"] = 3] = "Cancel";
      })(DeprecationChoice || (DeprecationChoice = {}));
      const buttons = [
        {
          label: localize(6625, null),
          run: () => DeprecationChoice.InstallAnyway
        }
      ];
      if (this.extension.deprecationInfo.extension) {
        detail2 = localize(6626, null, this.extension.deprecationInfo.extension.displayName);
        const alternateExtension = this.extension.deprecationInfo.extension;
        buttons.push({
          label: localize(6627, null, this.extension.deprecationInfo.extension.displayName),
          run: async () => {
            const [extension2] = await this.P.getExtensions([{ id: alternateExtension.id, preRelease: alternateExtension.preRelease }], CancellationToken.None);
            await this.P.open(extension2);
            return DeprecationChoice.ShowAlternateExtension;
          }
        });
      } else if (this.extension.deprecationInfo.settings) {
        detail2 = localize(6628, null);
        const settings = this.extension.deprecationInfo.settings;
        buttons.push({
          label: localize(6629, null),
          run: async () => {
            await this.X.openSettings({ query: settings.map((setting) => `@id:${setting}`).join(" ") });
            return DeprecationChoice.ConfigureSettings;
          }
        });
      } else if (this.extension.deprecationInfo.additionalInfo) {
        detail2 = new $bm(`${detail2} ${this.extension.deprecationInfo.additionalInfo}`);
      }
      const { result } = await this.W.prompt({
        type: Severity2.Warning,
        message: localize(6630, null, this.extension.displayName),
        detail: $zg(detail2) ? detail2 : void 0,
        custom: $zg(detail2) ? void 0 : {
          markdownDetails: [{
            markdown: detail2
          }]
        },
        buttons,
        cancelButton: {
          run: () => DeprecationChoice.Cancel
        }
      });
      if (result !== DeprecationChoice.InstallAnyway) {
        return;
      }
    }
    this.P.open(this.extension, { showPreReleaseVersion: this.options.installPreReleaseVersion });
    $$Z(localize(6631, null, this.extension.displayName));
    this.Y.publicLog("extensions:action:install", { ...this.extension.telemetryData, actionId: this.id });
    const extension = await this.cb(this.extension);
    if (extension?.local) {
      $$Z(localize(6632, null, this.extension.displayName));
      const runningExtension = await this.db(extension.local);
      if (runningExtension && !(runningExtension.activationEvents && runningExtension.activationEvents.some((activationEent) => activationEent.startsWith("onLanguage")))) {
        const action = await this.bb(extension);
        if (action) {
          action.extension = extension;
          try {
            return action.run({ showCurrentTheme: true, ignoreFocusLost: true });
          } finally {
            action.dispose();
          }
        }
      }
    }
  }
  async bb(extension) {
    const colorThemes = await this.S.getColorThemes();
    if (colorThemes.some((theme) => isThemeFromExtension(theme, extension))) {
      return this.Q.createInstance($mDb);
    }
    const fileIconThemes = await this.S.getFileIconThemes();
    if (fileIconThemes.some((theme) => isThemeFromExtension(theme, extension))) {
      return this.Q.createInstance($nDb);
    }
    const productIconThemes = await this.S.getProductIconThemes();
    if (productIconThemes.some((theme) => isThemeFromExtension(theme, extension))) {
      return this.Q.createInstance($oDb);
    }
    return void 0;
  }
  async cb(extension) {
    try {
      return await this.P.install(extension, this.options);
    } catch (error) {
      await this.Q.createInstance($TCb, extension, this.options, extension.latestVersion, 2, error).run();
      return void 0;
    }
  }
  async db(extension) {
    const runningExtension = await this.R.getExtension(extension.identifier.id);
    if (runningExtension) {
      return runningExtension;
    }
    if (this.R.canAddExtension($EN(extension))) {
      return new Promise((c, e) => {
        const disposable = this.R.onDidChangeExtensions(async () => {
          const runningExtension2 = await this.R.getExtension(extension.identifier.id);
          if (runningExtension2) {
            disposable.dispose();
            c(runningExtension2);
          }
        });
      });
    }
    return null;
  }
  eb() {
    this.label = this.getLabel();
  }
  getLabel(primary) {
    if (this.extension?.isWorkspaceScoped && this.extension.resourceExtension && this.Z.isInsideWorkspace(this.extension.resourceExtension.location)) {
      return localize(6633, null);
    }
    if (this.options.installPreReleaseVersion && this.extension?.hasPreReleaseVersion) {
      return primary ? localize(6634, null) : localize(6635, null);
    }
    if (this.extension?.hasPreReleaseVersion) {
      return primary ? localize(6636, null) : localize(6637, null);
    }
    return localize(6638, null);
  }
};
$XCb = $XCb_1 = __decorate([
  __param(1, $vzb),
  __param(2, $Pk),
  __param(3, $wN),
  __param(4, $rwb),
  __param(5, $ZI),
  __param(6, $Yv),
  __param(7, $TK),
  __param(8, $zv),
  __param(9, $Zk),
  __param(10, $xA)
], $XCb);
var $YCb = class $YCb2 extends $VCb {
  set manifest(manifest) {
    this.O.forEach((a) => a.manifest = manifest);
    this.update();
  }
  constructor(instantiationService, extensionsWorkbenchService) {
    super(`extensions.installActions`, $XCb.CLASS, [
      [
        instantiationService.createInstance($XCb, { installPreReleaseVersion: extensionsWorkbenchService.preferPreReleases }),
        instantiationService.createInstance($XCb, { installPreReleaseVersion: !extensionsWorkbenchService.preferPreReleases })
      ]
    ]);
  }
  Q(action) {
    return action.getLabel(true);
  }
};
$YCb = __decorate([
  __param(0, $Pk),
  __param(1, $vzb)
], $YCb);
var $ZCb = class _$ZCb extends $UCb {
  static {
    this.M = localize(6639, null);
  }
  static {
    this.N = `${$UCb.LABEL_ACTION_CLASS} install installing`;
  }
  constructor() {
    super("extension.installing", _$ZCb.M, _$ZCb.N, false);
  }
  update() {
    this.class = `${_$ZCb.N}${this.extension && this.extension.state === 0 ? "" : " hide"}`;
  }
};
var $1Cb = class $1Cb2 extends $UCb {
  static {
    $1Cb_1 = this;
  }
  static {
    this.M = localize(6640, null);
  }
  static {
    this.N = localize(6641, null);
  }
  static {
    this.O = `${$UCb.LABEL_ACTION_CLASS} prominent install-other-server`;
  }
  static {
    this.P = `${$UCb.LABEL_ACTION_CLASS} install-other-server installing`;
  }
  constructor(id2, Q, R, S, U, W) {
    super(id2, $1Cb_1.M, $1Cb_1.O, false);
    this.Q = Q;
    this.R = R;
    this.S = S;
    this.U = U;
    this.W = W;
    this.updateWhenCounterExtensionChanges = true;
    this.update();
  }
  update() {
    this.enabled = false;
    this.class = $1Cb_1.O;
    if (this.X()) {
      const extensionInOtherServer = this.S.installed.filter((e) => $DA(e.identifier, this.extension.identifier) && e.server === this.Q)[0];
      if (extensionInOtherServer) {
        if (extensionInOtherServer.state === 0 && !extensionInOtherServer.local) {
          this.enabled = true;
          this.label = $1Cb_1.N;
          this.class = $1Cb_1.P;
        }
      } else {
        this.enabled = true;
        this.label = this.Y();
      }
    }
  }
  X() {
    if (!this.extension || !this.Q || !this.extension.local || this.extension.state !== 1 || this.extension.type !== 1 || this.extension.enablementState === 2 || this.extension.enablementState === 0 || this.extension.enablementState === 4) {
      return false;
    }
    if ($9z(this.extension.local.manifest)) {
      return true;
    }
    if (this.Q === this.U.localExtensionManagementServer && this.W.prefersExecuteOnUI(this.extension.local.manifest)) {
      return true;
    }
    if (this.Q === this.U.remoteExtensionManagementServer && this.W.prefersExecuteOnWorkspace(this.extension.local.manifest)) {
      return true;
    }
    if (this.Q === this.U.webExtensionManagementServer && this.W.prefersExecuteOnWeb(this.extension.local.manifest)) {
      return true;
    }
    if (this.R) {
      if (this.Q === this.U.localExtensionManagementServer && this.W.canExecuteOnUI(this.extension.local.manifest)) {
        return true;
      }
      if (this.Q === this.U.remoteExtensionManagementServer && this.W.canExecuteOnWorkspace(this.extension.local.manifest)) {
        return true;
      }
    }
    return false;
  }
  async run() {
    if (!this.extension?.local) {
      return;
    }
    if (!this.extension?.server) {
      return;
    }
    if (!this.Q) {
      return;
    }
    this.S.open(this.extension);
    $$Z(localize(6642, null, this.extension.displayName));
    return this.S.installInServer(this.extension, this.Q);
  }
};
$1Cb = $1Cb_1 = __decorate([
  __param(3, $vzb),
  __param(4, $nzb),
  __param(5, $LCb)
], $1Cb);
var $2Cb = class $2Cb2 extends $1Cb {
  constructor(canInstallAnyWhere, extensionsWorkbenchService, extensionManagementServerService, extensionManifestPropertiesService) {
    super(`extensions.remoteinstall`, extensionManagementServerService.remoteExtensionManagementServer, canInstallAnyWhere, extensionsWorkbenchService, extensionManagementServerService, extensionManifestPropertiesService);
  }
  Y() {
    return this.U.remoteExtensionManagementServer ? localize(6643, null, this.U.remoteExtensionManagementServer.label) : $1Cb.M;
  }
};
$2Cb = __decorate([
  __param(1, $vzb),
  __param(2, $nzb),
  __param(3, $LCb)
], $2Cb);
var $3Cb = class $3Cb2 extends $1Cb {
  constructor(extensionsWorkbenchService, extensionManagementServerService, extensionManifestPropertiesService) {
    super(`extensions.localinstall`, extensionManagementServerService.localExtensionManagementServer, false, extensionsWorkbenchService, extensionManagementServerService, extensionManifestPropertiesService);
  }
  Y() {
    return localize(6644, null);
  }
};
$3Cb = __decorate([
  __param(0, $vzb),
  __param(1, $nzb),
  __param(2, $LCb)
], $3Cb);
var $4Cb = class $4Cb2 extends $1Cb {
  constructor(extensionsWorkbenchService, extensionManagementServerService, extensionManifestPropertiesService) {
    super(`extensions.webInstall`, extensionManagementServerService.webExtensionManagementServer, false, extensionsWorkbenchService, extensionManagementServerService, extensionManifestPropertiesService);
  }
  Y() {
    return localize(6645, null);
  }
};
$4Cb = __decorate([
  __param(0, $vzb),
  __param(1, $nzb),
  __param(2, $LCb)
], $4Cb);
var $5Cb = class $5Cb2 extends $UCb {
  static {
    $5Cb_1 = this;
  }
  static {
    this.UninstallLabel = localize(6646, null);
  }
  static {
    this.M = localize(6647, null);
  }
  static {
    this.UninstallClass = `${$UCb.LABEL_ACTION_CLASS} uninstall`;
  }
  static {
    this.N = `${$UCb.LABEL_ACTION_CLASS} uninstall uninstalling`;
  }
  constructor(O, P) {
    super("extensions.uninstall", $5Cb_1.UninstallLabel, $5Cb_1.UninstallClass, false);
    this.O = O;
    this.P = P;
    this.update();
  }
  update() {
    if (!this.extension) {
      this.enabled = false;
      return;
    }
    const state = this.extension.state;
    if (state === 2) {
      this.label = $5Cb_1.M;
      this.class = $5Cb_1.N;
      this.enabled = false;
      return;
    }
    this.label = $5Cb_1.UninstallLabel;
    this.class = $5Cb_1.UninstallClass;
    this.tooltip = $5Cb_1.UninstallLabel;
    if (state !== 1) {
      this.enabled = false;
      return;
    }
    if (this.extension.isBuiltin) {
      this.enabled = false;
      return;
    }
    this.enabled = true;
  }
  async run() {
    if (!this.extension) {
      return;
    }
    $$Z(localize(6648, null, this.extension.displayName));
    try {
      await this.O.uninstall(this.extension);
      $$Z(localize(6649, null, this.extension.displayName));
    } catch (error) {
      if (!$kb(error)) {
        this.P.error($qb(error));
      }
    }
  }
};
$5Cb = $5Cb_1 = __decorate([
  __param(0, $vzb),
  __param(1, $Yv)
], $5Cb);
var $6Cb = class $6Cb2 extends $UCb {
  static {
    $6Cb_1 = this;
  }
  static {
    this.M = `${this.LABEL_ACTION_CLASS} prominent update`;
  }
  static {
    this.N = `${this.M} disabled`;
  }
  constructor(P, Q, R, S, U) {
    super(`extensions.update`, localize(6650, null), $6Cb_1.N, false);
    this.P = P;
    this.Q = Q;
    this.R = R;
    this.S = S;
    this.U = U;
    this.O = new $Ph();
    this.update();
  }
  update() {
    this.O.queue(() => this.W());
    if (this.extension) {
      this.label = this.P ? localize(6651, null, this.extension.latestVersion) : localize(6652, null);
    }
  }
  async W() {
    this.enabled = false;
    this.class = $6Cb_1.N;
    if (!this.extension) {
      return;
    }
    if (this.extension.deprecationInfo) {
      return;
    }
    const canInstall = await this.Q.canInstall(this.extension);
    const isInstalled = this.extension.state === 1;
    this.enabled = canInstall === true && isInstalled && this.extension.outdated;
    this.class = this.enabled ? $6Cb_1.M : $6Cb_1.N;
  }
  async run() {
    if (!this.extension) {
      return;
    }
    const consent = await this.Q.shouldRequireConsentToUpdate(this.extension);
    if (consent) {
      const { result } = await this.R.prompt({
        type: "warning",
        title: localize(6653, null, this.extension.displayName),
        message: localize(6654, null, consent),
        buttons: [{
          label: localize(6655, null),
          run: () => "update"
        }, {
          label: localize(6656, null),
          run: () => "review"
        }, {
          label: localize(6657, null),
          run: () => "cancel"
        }]
      });
      if (result === "cancel") {
        return;
      }
      if (result === "review") {
        if (this.extension.hasChangelog()) {
          return this.Q.open(this.extension, {
            tab: "changelog"
            /* ExtensionEditorTab.Changelog */
          });
        }
        if (this.extension.repository) {
          return this.S.open(this.extension.repository);
        }
        return this.Q.open(this.extension);
      }
    }
    $$Z(localize(6658, null, this.extension.displayName, this.extension.latestVersion));
    return this.X(this.extension);
  }
  async X(extension) {
    const options3 = extension.local?.preRelease ? { installPreReleaseVersion: true } : void 0;
    try {
      await this.Q.install(extension, options3);
      $$Z(localize(6659, null, extension.displayName, extension.latestVersion));
    } catch (err) {
      this.U.createInstance($TCb, extension, options3, extension.latestVersion, 3, err).run();
    }
  }
};
$6Cb = $6Cb_1 = __decorate([
  __param(1, $vzb),
  __param(2, $Yv),
  __param(3, $O4),
  __param(4, $Pk)
], $6Cb);
var $7Cb = class $7Cb2 extends $UCb {
  static {
    $7Cb_1 = this;
  }
  static {
    this.ID = "workbench.extensions.action.toggleAutoUpdateForExtension";
  }
  static {
    this.LABEL = localize2(6772, "Auto Update");
  }
  static {
    this.M = `${$UCb.EXTENSION_ACTION_CLASS} auto-update`;
  }
  static {
    this.N = `${this.M} hide`;
  }
  constructor(O, P, Q, configurationService) {
    super($7Cb_1.ID, $7Cb_1.LABEL.value, $7Cb_1.N);
    this.O = O;
    this.P = P;
    this.Q = Q;
    this.B(configurationService.onDidChangeConfiguration((e) => {
      if (e.affectsConfiguration($xzb)) {
        this.update();
      }
    }));
    this.B(Q.onDidChangeAllowedExtensions((e) => this.update()));
    this.update();
  }
  update() {
    this.enabled = false;
    this.class = $7Cb_1.N;
    if (!this.extension) {
      return;
    }
    if (this.extension.isBuiltin) {
      return;
    }
    if (this.extension.deprecationInfo?.disallowInstall) {
      return;
    }
    const extension = this.extension.local ?? this.extension.gallery;
    if (extension && this.Q.isAllowed(extension) !== true) {
      return;
    }
    if (this.O.getAutoUpdateValue() === "onlyEnabledExtensions" && !this.P.isEnabledEnablementState(this.extension.enablementState)) {
      return;
    }
    this.enabled = true;
    this.class = $7Cb_1.M;
    this.checked = this.O.isAutoUpdateEnabledFor(this.extension);
  }
  async run() {
    if (!this.extension) {
      return;
    }
    const enableAutoUpdate = !this.O.isAutoUpdateEnabledFor(this.extension);
    await this.O.updateAutoUpdateEnablementFor(this.extension, enableAutoUpdate);
    if (enableAutoUpdate) {
      $$Z(localize(6660, null, this.extension.displayName));
    } else {
      $$Z(localize(6661, null, this.extension.displayName));
    }
  }
};
$7Cb = $7Cb_1 = __decorate([
  __param(0, $vzb),
  __param(1, $qzb),
  __param(2, $xA),
  __param(3, $kl)
], $7Cb);
var $8Cb = class $8Cb2 extends $UCb {
  static {
    $8Cb_1 = this;
  }
  static {
    this.ID = "workbench.extensions.action.toggleAutoUpdatesForPublisher";
  }
  static {
    this.LABEL = localize(6662, null);
  }
  constructor(M) {
    super($8Cb_1.ID, $8Cb_1.LABEL);
    this.M = M;
  }
  update() {
  }
  async run() {
    if (!this.extension) {
      return;
    }
    $$Z(localize(6663, null, this.extension.publisherDisplayName));
    const enableAutoUpdate = !this.M.isAutoUpdateEnabledFor(this.extension.publisher);
    await this.M.updateAutoUpdateEnablementFor(this.extension.publisher, enableAutoUpdate);
    if (enableAutoUpdate) {
      $$Z(localize(6664, null, this.extension.displayName));
    } else {
      $$Z(localize(6665, null, this.extension.displayName));
    }
  }
};
$8Cb = $8Cb_1 = __decorate([
  __param(0, $vzb)
], $8Cb);
var $9Cb = class $9Cb2 extends $UCb {
  static {
    $9Cb_1 = this;
  }
  static {
    this.M = `${$UCb.LABEL_ACTION_CLASS} migrate`;
  }
  static {
    this.N = `${this.M} disabled`;
  }
  constructor(O, P) {
    super("extensionsAction.migrateDeprecatedExtension", localize(6666, null), $9Cb_1.N, false);
    this.O = O;
    this.P = P;
    this.update();
  }
  update() {
    this.enabled = false;
    this.class = $9Cb_1.N;
    if (!this.extension?.local) {
      return;
    }
    if (this.extension.state !== 1) {
      return;
    }
    if (!this.extension.deprecationInfo?.extension) {
      return;
    }
    const id2 = this.extension.deprecationInfo.extension.id;
    if (this.P.local.some((e) => $DA(e.identifier, { id: id2 }))) {
      return;
    }
    this.enabled = true;
    this.class = $9Cb_1.M;
    this.tooltip = localize(6667, null, this.extension.deprecationInfo.extension.displayName);
    this.label = this.O ? localize(6668, null) : this.tooltip;
  }
  async run() {
    if (!this.extension?.deprecationInfo?.extension) {
      return;
    }
    const local = this.extension.local;
    await this.P.uninstall(this.extension);
    const [extension] = await this.P.getExtensions([{ id: this.extension.deprecationInfo.extension.id, preRelease: this.extension.deprecationInfo?.extension?.preRelease }], CancellationToken.None);
    await this.P.install(extension, { isMachineScoped: local?.isMachineScoped });
  }
};
$9Cb = $9Cb_1 = __decorate([
  __param(1, $vzb)
], $9Cb);
var $0Cb = class $0Cb2 extends $UCb {
  constructor(id2, label3, cssClass, enabled, M) {
    super(id2, label3, cssClass, enabled);
    this.M = M;
    this.N = null;
  }
  createActionViewItem(options3) {
    this.N = this.M.createInstance($$Cb, this, options3);
    return this.N;
  }
  run({ actionGroups, disposeActionsOnHide }) {
    this.N?.showMenu(actionGroups, disposeActionsOnHide);
    return Promise.resolve();
  }
};
$0Cb = __decorate([
  __param(4, $Pk)
], $0Cb);
var $$Cb = class $$Cb2 extends $U1 {
  constructor(action, options3, g) {
    super(null, action, { ...options3, icon: true, label: true });
    this.g = g;
  }
  showMenu(menuActionGroups, disposeActionsOnHide) {
    if (this.element) {
      const actions = this.h(menuActionGroups);
      const elementPosition = $vj(this.element);
      const anchor = { x: elementPosition.left, y: elementPosition.top + elementPosition.height + 10 };
      this.g.showContextMenu({
        getAnchor: () => anchor,
        getActions: () => actions,
        actionRunner: this.actionRunner,
        onHide: () => {
          if (disposeActionsOnHide) {
            $Yc(actions);
          }
        }
      });
    }
  }
  h(menuActionGroups) {
    let actions = [];
    for (const menuActions of menuActionGroups) {
      actions = [...actions, ...menuActions, new $Wm()];
    }
    return actions.length ? actions.slice(0, actions.length - 1) : actions;
  }
};
$$Cb = __decorate([
  __param(2, $50)
], $$Cb);
async function getContextMenuActionsGroups(extension, contextKeyService, instantiationService) {
  return instantiationService.invokeFunction(async (accessor) => {
    const extensionsWorkbenchService = accessor.get($vzb);
    const extensionEnablementService = accessor.get($qzb);
    const menuService = accessor.get($cJ);
    const extensionRecommendationsService = accessor.get($ABb);
    const extensionIgnoredRecommendationsService = accessor.get($BBb);
    const workbenchThemeService = accessor.get($rwb);
    const authenticationUsageService = accessor.get($RCb);
    const allowedExtensionsService = accessor.get($xA);
    const cksOverlay = [];
    if (extension) {
      cksOverlay.push(["extension", extension.identifier.id]);
      cksOverlay.push(["isBuiltinExtension", extension.isBuiltin]);
      cksOverlay.push(["isDefaultApplicationScopedExtension", extension.local && $8z(extension.local.manifest)]);
      cksOverlay.push(["isApplicationScopedExtension", extension.local && extension.local.isApplicationScoped]);
      cksOverlay.push(["isWorkspaceScopedExtension", extension.isWorkspaceScoped]);
      cksOverlay.push(["isGalleryExtension", !!extension.identifier.uuid]);
      if (extension.local) {
        cksOverlay.push(["extensionSource", extension.local.source]);
      }
      cksOverlay.push(["extensionHasConfiguration", extension.local && !!extension.local.manifest.contributes && !!extension.local.manifest.contributes.configuration]);
      cksOverlay.push(["extensionHasKeybindings", extension.local && !!extension.local.manifest.contributes && !!extension.local.manifest.contributes.keybindings]);
      cksOverlay.push(["extensionHasCommands", extension.local && !!extension.local.manifest.contributes && !!extension.local.manifest.contributes?.commands]);
      cksOverlay.push(["isExtensionRecommended", !!extensionRecommendationsService.getAllRecommendationsWithReason()[extension.identifier.id.toLowerCase()]]);
      cksOverlay.push([
        "isExtensionWorkspaceRecommended",
        extensionRecommendationsService.getAllRecommendationsWithReason()[extension.identifier.id.toLowerCase()]?.reasonId === 0
        /* ExtensionRecommendationReason.Workspace */
      ]);
      cksOverlay.push(["isUserIgnoredRecommendation", extensionIgnoredRecommendationsService.globalIgnoredRecommendations.some((e) => e === extension.identifier.id.toLowerCase())]);
      cksOverlay.push(["isExtensionPinned", extension.pinned]);
      cksOverlay.push(["isExtensionEnabled", extensionEnablementService.isEnabledEnablementState(extension.enablementState)]);
      switch (extension.state) {
        case 0:
          cksOverlay.push(["extensionStatus", "installing"]);
          break;
        case 1:
          cksOverlay.push(["extensionStatus", "installed"]);
          break;
        case 2:
          cksOverlay.push(["extensionStatus", "uninstalling"]);
          break;
        case 3:
          cksOverlay.push(["extensionStatus", "uninstalled"]);
          break;
      }
      cksOverlay.push(["installedExtensionIsPreReleaseVersion", !!extension.local?.isPreReleaseVersion]);
      cksOverlay.push(["installedExtensionIsOptedToPreRelease", !!extension.local?.preRelease]);
      cksOverlay.push(["galleryExtensionIsPreReleaseVersion", !!extension.gallery?.properties.isPreReleaseVersion]);
      cksOverlay.push(["galleryExtensionHasPreReleaseVersion", extension.gallery?.hasPreReleaseVersion]);
      cksOverlay.push(["extensionHasPreReleaseVersion", extension.hasPreReleaseVersion]);
      cksOverlay.push(["extensionHasReleaseVersion", extension.hasReleaseVersion]);
      cksOverlay.push(["extensionDisallowInstall", !!extension.deprecationInfo?.disallowInstall]);
      cksOverlay.push(["isExtensionAllowed", allowedExtensionsService.isAllowed({ id: extension.identifier.id, publisherDisplayName: extension.publisherDisplayName }) === true]);
      cksOverlay.push(["isPreReleaseExtensionAllowed", allowedExtensionsService.isAllowed({ id: extension.identifier.id, publisherDisplayName: extension.publisherDisplayName, prerelease: true }) === true]);
      cksOverlay.push(["extensionIsUnsigned", extension.gallery && !extension.gallery.isSigned]);
      const [colorThemes, fileIconThemes, productIconThemes, extensionUsesAuth] = await Promise.all([workbenchThemeService.getColorThemes(), workbenchThemeService.getFileIconThemes(), workbenchThemeService.getProductIconThemes(), authenticationUsageService.extensionUsesAuth(extension.identifier.id.toLowerCase())]);
      cksOverlay.push(["extensionHasColorThemes", colorThemes.some((theme) => isThemeFromExtension(theme, extension))]);
      cksOverlay.push(["extensionHasFileIconThemes", fileIconThemes.some((theme) => isThemeFromExtension(theme, extension))]);
      cksOverlay.push(["extensionHasProductIconThemes", productIconThemes.some((theme) => isThemeFromExtension(theme, extension))]);
      cksOverlay.push(["extensionHasAccountPreferences", extensionUsesAuth]);
      cksOverlay.push(["canSetLanguage", extensionsWorkbenchService.canSetLanguage(extension)]);
      cksOverlay.push(["isActiveLanguagePackExtension", extension.gallery && $z === $xX(extension.gallery)]);
    }
    const actionsGroups = menuService.getMenuActions($bJ.ExtensionContext, contextKeyService.createOverlay(cksOverlay), { shouldForwardArgs: true });
    return actionsGroups;
  });
}
function toActions(actionsGroups, instantiationService) {
  const result = [];
  for (const [, actions] of actionsGroups) {
    result.push(actions.map((action) => {
      if (action instanceof $Xm) {
        return action;
      }
      return instantiationService.createInstance($cDb, action);
    }));
  }
  return result;
}
async function $_Cb(extension, contextKeyService, instantiationService) {
  const actionsGroups = await getContextMenuActionsGroups(extension, contextKeyService, instantiationService);
  return toActions(actionsGroups, instantiationService);
}
var $aDb = class $aDb2 extends $0Cb {
  static {
    $aDb_1 = this;
  }
  static {
    this.ID = "extensions.manage";
  }
  static {
    this.O = `${$UCb.ICON_ACTION_CLASS} manage ` + ThemeIcon.asClassName($dCb);
  }
  static {
    this.P = `${this.O} hide`;
  }
  constructor(instantiationService, Q, R) {
    super($aDb_1.ID, "", "", true, instantiationService);
    this.Q = Q;
    this.R = R;
    this.tooltip = localize(6669, null);
    this.update();
  }
  async getActionGroups() {
    const groups = [];
    const contextMenuActionsGroups = await getContextMenuActionsGroups(this.extension, this.R, this.M);
    const themeActions = [], installActions = [], updateActions = [], otherActionGroups = [];
    for (const [group2, actions] of contextMenuActionsGroups) {
      if (group2 === $Mzb) {
        installActions.push(...toActions([[group2, actions]], this.M)[0]);
      } else if (group2 === $Nzb) {
        updateActions.push(...toActions([[group2, actions]], this.M)[0]);
      } else if (group2 === $Lzb) {
        themeActions.push(...toActions([[group2, actions]], this.M)[0]);
      } else {
        otherActionGroups.push(...toActions([[group2, actions]], this.M));
      }
    }
    if (themeActions.length) {
      groups.push(themeActions);
    }
    groups.push([
      this.M.createInstance($gDb),
      this.M.createInstance($fDb)
    ]);
    groups.push([
      this.M.createInstance($iDb),
      this.M.createInstance($hDb)
    ]);
    if (updateActions.length) {
      groups.push(updateActions);
    }
    groups.push([
      ...installActions.length ? installActions : [],
      this.M.createInstance($eDb, this.extension, false),
      this.M.createInstance($5Cb)
    ]);
    otherActionGroups.forEach((actions) => groups.push(actions));
    groups.forEach((group2) => group2.forEach((extensionAction) => {
      if (extensionAction instanceof $UCb) {
        extensionAction.extension = this.extension;
      }
    }));
    return groups;
  }
  async run() {
    await this.Q.whenInstalledExtensionsRegistered();
    return super.run({ actionGroups: await this.getActionGroups(), disposeActionsOnHide: true });
  }
  update() {
    this.class = $aDb_1.P;
    this.enabled = false;
    if (this.extension) {
      const state = this.extension.state;
      this.enabled = state === 1;
      this.class = this.enabled || state === 2 ? $aDb_1.O : $aDb_1.P;
    }
  }
};
$aDb = $aDb_1 = __decorate([
  __param(0, $Pk),
  __param(1, $wN),
  __param(2, $on)
], $aDb);
var $bDb = class extends $0Cb {
  constructor(O, instantiationService) {
    super("extensionEditor.manageExtension", "", `${$UCb.ICON_ACTION_CLASS} manage ${ThemeIcon.asClassName($dCb)}`, true, instantiationService);
    this.O = O;
    this.tooltip = localize(6670, null);
  }
  update() {
  }
  async run() {
    const actionGroups = [];
    (await $_Cb(this.extension, this.O, this.M)).forEach((actions) => actionGroups.push(actions));
    actionGroups.forEach((group2) => group2.forEach((extensionAction) => {
      if (extensionAction instanceof $UCb) {
        extensionAction.extension = this.extension;
      }
    }));
    return super.run({ actionGroups, disposeActionsOnHide: true });
  }
};
var $cDb = class $cDb2 extends $UCb {
  constructor(M, N) {
    super(M.id, M.label);
    this.M = M;
    this.N = N;
  }
  get enabled() {
    return this.M.enabled;
  }
  set enabled(value) {
    this.M.enabled = value;
  }
  update() {
    if (!this.extension) {
      return;
    }
    if (this.M.id === $Ezb) {
      this.checked = !this.N.isExtensionIgnoredToSync(this.extension);
    } else if (this.M.id === $7Cb.ID) {
      this.checked = this.N.isAutoUpdateEnabledFor(this.extension);
    } else if (this.M.id === $8Cb.ID) {
      this.checked = this.N.isAutoUpdateEnabledFor(this.extension.publisher);
    } else {
      this.checked = this.M.checked;
    }
  }
  async run() {
    if (this.extension) {
      const id2 = this.extension.local ? $GA(this.extension.local.manifest.publisher, this.extension.local.manifest.name) : this.extension.gallery ? $GA(this.extension.gallery.publisher, this.extension.gallery.name) : this.extension.identifier.id;
      const extensionArg = {
        id: this.extension.identifier.id,
        version: this.extension.version,
        location: this.extension.local?.location
      };
      await this.M.run(id2, extensionArg);
    }
  }
};
$cDb = __decorate([
  __param(1, $vzb)
], $cDb);
var $dDb = class $dDb2 extends $UCb {
  static {
    $dDb_1 = this;
  }
  static {
    this.ID = "workbench.extensions.action.togglePreRlease";
  }
  static {
    this.LABEL = localize(6671, null);
  }
  static {
    this.M = `${$UCb.LABEL_ACTION_CLASS} pre-release`;
  }
  static {
    this.N = `${this.M} hide`;
  }
  constructor(O, P) {
    super($dDb_1.ID, $dDb_1.LABEL, $dDb_1.N);
    this.O = O;
    this.P = P;
    this.B(P.onDidChangeAllowedExtensions(() => this.update()));
    this.update();
  }
  update() {
    this.enabled = false;
    this.class = $dDb_1.N;
    if (!this.extension) {
      return;
    }
    if (this.extension.isBuiltin) {
      return;
    }
    if (this.extension.state !== 1) {
      return;
    }
    if (!this.extension.hasPreReleaseVersion) {
      return;
    }
    if (!this.extension.gallery) {
      return;
    }
    if (this.extension.preRelease) {
      if (!this.extension.isPreReleaseVersion) {
        return;
      }
      if (this.P.isAllowed({ id: this.extension.identifier.id, publisherDisplayName: this.extension.publisherDisplayName }) !== true) {
        return;
      }
    }
    if (!this.extension.preRelease) {
      if (!this.extension.gallery.hasPreReleaseVersion) {
        return;
      }
      if (this.P.isAllowed(this.extension.gallery) !== true) {
        return;
      }
    }
    this.enabled = true;
    this.class = $dDb_1.M;
    if (this.extension.preRelease) {
      this.label = localize(6672, null);
      this.tooltip = localize(6673, null);
    } else {
      this.label = localize(6674, null);
      this.tooltip = localize(6675, null);
    }
  }
  async run() {
    if (!this.extension) {
      return;
    }
    this.O.open(this.extension, { showPreReleaseVersion: !this.extension.preRelease });
    await this.O.togglePreRelease(this.extension);
  }
};
$dDb = $dDb_1 = __decorate([
  __param(0, $vzb),
  __param(1, $xA)
], $dDb);
var $eDb = class $eDb2 extends $UCb {
  static {
    $eDb_1 = this;
  }
  static {
    this.ID = "workbench.extensions.action.install.anotherVersion";
  }
  static {
    this.LABEL = localize(6676, null);
  }
  constructor(extension, M, N, O, P, Q, R, S, U) {
    super($eDb_1.ID, $eDb_1.LABEL, $UCb.LABEL_ACTION_CLASS);
    this.M = M;
    this.N = N;
    this.O = O;
    this.P = P;
    this.Q = Q;
    this.R = R;
    this.S = S;
    this.U = U;
    this.B(U.onDidChangeAllowedExtensions(() => this.update()));
    this.extension = extension;
    this.update();
  }
  update() {
    this.enabled = !!this.extension && !this.extension.isBuiltin && !!this.extension.identifier.uuid && !this.extension.deprecationInfo && this.U.isAllowed({ id: this.extension.identifier.id, publisherDisplayName: this.extension.publisherDisplayName }) === true;
    if (this.enabled && this.M) {
      this.enabled = !!this.extension?.local && !!this.extension.server && this.extension.state === 1;
    }
  }
  async run() {
    if (!this.enabled) {
      return;
    }
    if (!this.extension) {
      return;
    }
    const targetPlatform = this.extension.server ? await this.extension.server.extensionManagementService.getTargetPlatform() : await this.O.getTargetPlatform();
    const allVersions = await this.P.getAllCompatibleVersions(this.extension.identifier, this.extension.local?.preRelease ?? this.extension.gallery?.properties.isPreReleaseVersion ?? false, targetPlatform);
    if (!allVersions.length) {
      await this.S.info(localize(6677, null));
      return;
    }
    const picks = allVersions.map((v, i2) => {
      return {
        id: v.version,
        label: v.version,
        description: `${$Qu(new Date(Date.parse(v.date)), true)}${v.isPreReleaseVersion ? ` (${localize(6678, null)})` : ""}${v.version === this.extension?.local?.manifest.version ? ` (${localize(6679, null)})` : ""}`,
        ariaLabel: `${v.isPreReleaseVersion ? "Pre-Release version" : "Release version"} ${v.version}`,
        isPreReleaseVersion: v.isPreReleaseVersion
      };
    });
    const pick = await this.Q.pick(picks, {
      placeHolder: localize(6680, null),
      matchOnDetail: true
    });
    if (pick) {
      if (this.extension.local?.manifest.version === pick.id) {
        return;
      }
      const options3 = { installPreReleaseVersion: pick.isPreReleaseVersion, version: pick.id };
      try {
        await this.N.install(this.extension, options3);
      } catch (error) {
        this.R.createInstance($TCb, this.extension, options3, pick.id, 2, error).run();
      }
    }
    return null;
  }
};
$eDb = $eDb_1 = __decorate([
  __param(2, $vzb),
  __param(3, $pzb),
  __param(4, $pA),
  __param(5, $1M),
  __param(6, $Pk),
  __param(7, $Yv),
  __param(8, $xA)
], $eDb);
var $fDb = class $fDb2 extends $UCb {
  static {
    $fDb_1 = this;
  }
  static {
    this.ID = "extensions.enableForWorkspace";
  }
  static {
    this.LABEL = localize(6681, null);
  }
  constructor(M, N) {
    super($fDb_1.ID, $fDb_1.LABEL, $UCb.LABEL_ACTION_CLASS);
    this.M = M;
    this.N = N;
    this.tooltip = localize(6682, null);
    this.update();
  }
  update() {
    this.enabled = false;
    if (this.extension && this.extension.local && !this.extension.isWorkspaceScoped) {
      this.enabled = this.extension.state === 1 && !this.N.isEnabled(this.extension.local) && this.N.canChangeWorkspaceEnablement(this.extension.local);
    }
  }
  async run() {
    if (!this.extension) {
      return;
    }
    return this.M.setEnablement(
      this.extension,
      11
      /* EnablementState.EnabledWorkspace */
    );
  }
};
$fDb = $fDb_1 = __decorate([
  __param(0, $vzb),
  __param(1, $qzb)
], $fDb);
var $gDb = class $gDb2 extends $UCb {
  static {
    $gDb_1 = this;
  }
  static {
    this.ID = "extensions.enableGlobally";
  }
  static {
    this.LABEL = localize(6683, null);
  }
  constructor(M, N) {
    super($gDb_1.ID, $gDb_1.LABEL, $UCb.LABEL_ACTION_CLASS);
    this.M = M;
    this.N = N;
    this.tooltip = localize(6684, null);
    this.update();
  }
  update() {
    this.enabled = false;
    if (this.extension && this.extension.local && !this.extension.isWorkspaceScoped) {
      this.enabled = this.extension.state === 1 && this.N.isDisabledGlobally(this.extension.local) && this.N.canChangeEnablement(this.extension.local);
    }
  }
  async run() {
    if (!this.extension) {
      return;
    }
    return this.M.setEnablement(
      this.extension,
      10
      /* EnablementState.EnabledGlobally */
    );
  }
};
$gDb = $gDb_1 = __decorate([
  __param(0, $vzb),
  __param(1, $qzb)
], $gDb);
var $hDb = class $hDb2 extends $UCb {
  static {
    $hDb_1 = this;
  }
  static {
    this.ID = "extensions.disableForWorkspace";
  }
  static {
    this.LABEL = localize(6685, null);
  }
  constructor(M, N, O, P) {
    super($hDb_1.ID, $hDb_1.LABEL, $UCb.LABEL_ACTION_CLASS);
    this.M = M;
    this.N = N;
    this.O = O;
    this.P = P;
    this.tooltip = localize(6686, null);
    this.update();
    this.B(this.P.onDidChangeExtensions(() => this.update()));
  }
  update() {
    this.enabled = false;
    if (this.extension && this.extension.local && !this.extension.isWorkspaceScoped && this.P.extensions.some(
      (e) => $DA({ id: e.identifier.value, uuid: e.uuid }, this.extension.identifier) && this.M.getWorkbenchState() !== 1
      /* WorkbenchState.EMPTY */
    )) {
      this.enabled = this.extension.state === 1 && (this.extension.enablementState === 10 || this.extension.enablementState === 11) && this.O.canChangeWorkspaceEnablement(this.extension.local);
    }
  }
  async run() {
    if (!this.extension) {
      return;
    }
    return this.N.setEnablement(
      this.extension,
      9
      /* EnablementState.DisabledWorkspace */
    );
  }
};
$hDb = $hDb_1 = __decorate([
  __param(0, $Zk),
  __param(1, $vzb),
  __param(2, $qzb),
  __param(3, $wN)
], $hDb);
var $iDb = class $iDb2 extends $UCb {
  static {
    $iDb_1 = this;
  }
  static {
    this.ID = "extensions.disableGlobally";
  }
  static {
    this.LABEL = localize(6687, null);
  }
  constructor(M, N, O) {
    super($iDb_1.ID, $iDb_1.LABEL, $UCb.LABEL_ACTION_CLASS);
    this.M = M;
    this.N = N;
    this.O = O;
    this.tooltip = localize(6688, null);
    this.update();
    this.B(this.O.onDidChangeExtensions(() => this.update()));
  }
  update() {
    this.enabled = false;
    if (this.extension && this.extension.local && !this.extension.isWorkspaceScoped && this.O.extensions.some((e) => $DA({ id: e.identifier.value, uuid: e.uuid }, this.extension.identifier))) {
      this.enabled = this.extension.state === 1 && (this.extension.enablementState === 10 || this.extension.enablementState === 11) && this.N.canChangeEnablement(this.extension.local);
    }
  }
  async run() {
    if (!this.extension) {
      return;
    }
    return this.M.setEnablement(
      this.extension,
      8
      /* EnablementState.DisabledGlobally */
    );
  }
};
$iDb = $iDb_1 = __decorate([
  __param(0, $vzb),
  __param(1, $qzb),
  __param(2, $wN)
], $iDb);
var $jDb = class $jDb2 extends $VCb {
  constructor(instantiationService) {
    super("extensions.enable", $UCb.LABEL_ACTION_CLASS, [
      [
        instantiationService.createInstance($gDb),
        instantiationService.createInstance($fDb)
      ]
    ]);
  }
};
$jDb = __decorate([
  __param(0, $Pk)
], $jDb);
var $kDb = class $kDb2 extends $VCb {
  constructor(instantiationService) {
    super("extensions.disable", $UCb.LABEL_ACTION_CLASS, [[
      instantiationService.createInstance($iDb),
      instantiationService.createInstance($hDb)
    ]]);
  }
};
$kDb = __decorate([
  __param(0, $Pk)
], $kDb);
var $lDb = class $lDb2 extends $UCb {
  static {
    $lDb_1 = this;
  }
  static {
    this.M = `${$UCb.LABEL_ACTION_CLASS} reload`;
  }
  static {
    this.N = `${this.M} disabled`;
  }
  constructor(O, P, Q, R, S, U) {
    super("extensions.runtimeState", "", $lDb_1.N, false);
    this.O = O;
    this.P = P;
    this.Q = Q;
    this.R = R;
    this.S = S;
    this.U = U;
    this.updateWhenCounterExtensionChanges = true;
    this.B(this.R.onDidChangeExtensions(() => this.update()));
    this.update();
  }
  update() {
    this.enabled = false;
    this.tooltip = "";
    this.class = $lDb_1.N;
    if (!this.extension) {
      return;
    }
    const state = this.extension.state;
    if (state === 0 || state === 2) {
      return;
    }
    if (this.extension.local && this.extension.local.manifest && this.extension.local.manifest.contributes && this.extension.local.manifest.contributes.localizations && this.extension.local.manifest.contributes.localizations.length > 0) {
      return;
    }
    const runtimeState = this.extension.runtimeState;
    if (!runtimeState) {
      return;
    }
    this.enabled = true;
    this.class = $lDb_1.M;
    this.tooltip = runtimeState.reason;
    this.label = runtimeState.action === "reloadWindow" ? localize(6689, null) : runtimeState.action === "restartExtensions" ? localize(6690, null) : runtimeState.action === "quitAndInstall" ? localize(6691, null) : runtimeState.action === "applyUpdate" || runtimeState.action === "downloadUpdate" ? localize(6692, null, this.S.nameShort) : "";
  }
  async run() {
    const runtimeState = this.extension?.runtimeState;
    if (!runtimeState?.action) {
      return;
    }
    this.U.publicLog2("extensions:runtimestate:action", {
      action: runtimeState.action
    });
    if (runtimeState?.action === "reloadWindow") {
      return this.O.reload();
    } else if (runtimeState?.action === "restartExtensions") {
      return this.P.updateRunningExtensions();
    } else if (runtimeState?.action === "downloadUpdate") {
      return this.Q.downloadUpdate();
    } else if (runtimeState?.action === "applyUpdate") {
      return this.Q.applyUpdate();
    } else if (runtimeState?.action === "quitAndInstall") {
      return this.Q.quitAndInstall();
    }
  }
};
$lDb = $lDb_1 = __decorate([
  __param(0, $S4),
  __param(1, $vzb),
  __param(2, $az),
  __param(3, $wN),
  __param(4, $Vu),
  __param(5, $zv)
], $lDb);
function isThemeFromExtension(theme, extension) {
  return !!(extension && theme.extensionData && $5z.equals(theme.extensionData.extensionId, extension.identifier.id));
}
function getQuickPickEntries(themes, currentTheme, extension, showCurrentTheme) {
  const picks = [];
  for (const theme of themes) {
    if (isThemeFromExtension(theme, extension) && !(showCurrentTheme && theme === currentTheme)) {
      picks.push({ label: theme.label, id: theme.id });
    }
  }
  if (showCurrentTheme) {
    picks.push({ type: "separator", label: localize(6693, null) });
    picks.push({ label: currentTheme.label, id: currentTheme.id });
  }
  return picks;
}
var $mDb = class $mDb2 extends $UCb {
  static {
    $mDb_1 = this;
  }
  static {
    this.ID = "workbench.extensions.action.setColorTheme";
  }
  static {
    this.TITLE = localize2(6773, "Set Color Theme");
  }
  static {
    this.M = `${$UCb.LABEL_ACTION_CLASS} theme`;
  }
  static {
    this.N = `${this.M} disabled`;
  }
  constructor(extensionService, O, P, Q) {
    super($mDb_1.ID, $mDb_1.TITLE.value, $mDb_1.N, false);
    this.O = O;
    this.P = P;
    this.Q = Q;
    this.B(Event2.any(extensionService.onDidChangeExtensions, O.onDidColorThemeChange)(() => this.update(), this));
    this.update();
  }
  update() {
    this.O.getColorThemes().then((colorThemes) => {
      this.enabled = this.R(colorThemes);
      this.class = this.enabled ? $mDb_1.M : $mDb_1.N;
    });
  }
  R(colorThemes) {
    return !!this.extension && this.extension.state === 1 && this.Q.isEnabledEnablementState(this.extension.enablementState) && colorThemes.some((th) => isThemeFromExtension(th, this.extension));
  }
  async run({ showCurrentTheme, ignoreFocusLost } = { showCurrentTheme: false, ignoreFocusLost: false }) {
    const colorThemes = await this.O.getColorThemes();
    if (!this.R(colorThemes)) {
      return;
    }
    const currentTheme = this.O.getColorTheme();
    const delayer4 = new $Sh(100);
    const picks = getQuickPickEntries(colorThemes, currentTheme, this.extension, showCurrentTheme);
    const pickedTheme = await this.P.pick(picks, {
      placeHolder: localize(6694, null),
      onDidFocus: (item) => delayer4.trigger(() => this.O.setColorTheme(item.id, void 0)),
      ignoreFocusLost
    });
    return this.O.setColorTheme(pickedTheme ? pickedTheme.id : currentTheme.id, "auto");
  }
};
$mDb = $mDb_1 = __decorate([
  __param(0, $wN),
  __param(1, $rwb),
  __param(2, $1M),
  __param(3, $qzb)
], $mDb);
var $nDb = class $nDb2 extends $UCb {
  static {
    $nDb_1 = this;
  }
  static {
    this.ID = "workbench.extensions.action.setFileIconTheme";
  }
  static {
    this.TITLE = localize2(6774, "Set File Icon Theme");
  }
  static {
    this.M = `${$UCb.LABEL_ACTION_CLASS} theme`;
  }
  static {
    this.N = `${this.M} disabled`;
  }
  constructor(extensionService, O, P, Q) {
    super($nDb_1.ID, $nDb_1.TITLE.value, $nDb_1.N, false);
    this.O = O;
    this.P = P;
    this.Q = Q;
    this.B(Event2.any(extensionService.onDidChangeExtensions, O.onDidFileIconThemeChange)(() => this.update(), this));
    this.update();
  }
  update() {
    this.O.getFileIconThemes().then((fileIconThemes) => {
      this.enabled = this.R(fileIconThemes);
      this.class = this.enabled ? $nDb_1.M : $nDb_1.N;
    });
  }
  R(colorThemfileIconThemess) {
    return !!this.extension && this.extension.state === 1 && this.Q.isEnabledEnablementState(this.extension.enablementState) && colorThemfileIconThemess.some((th) => isThemeFromExtension(th, this.extension));
  }
  async run({ showCurrentTheme, ignoreFocusLost } = { showCurrentTheme: false, ignoreFocusLost: false }) {
    const fileIconThemes = await this.O.getFileIconThemes();
    if (!this.R(fileIconThemes)) {
      return;
    }
    const currentTheme = this.O.getFileIconTheme();
    const delayer4 = new $Sh(100);
    const picks = getQuickPickEntries(fileIconThemes, currentTheme, this.extension, showCurrentTheme);
    const pickedTheme = await this.P.pick(picks, {
      placeHolder: localize(6695, null),
      onDidFocus: (item) => delayer4.trigger(() => this.O.setFileIconTheme(item.id, void 0)),
      ignoreFocusLost
    });
    return this.O.setFileIconTheme(pickedTheme ? pickedTheme.id : currentTheme.id, "auto");
  }
};
$nDb = $nDb_1 = __decorate([
  __param(0, $wN),
  __param(1, $rwb),
  __param(2, $1M),
  __param(3, $qzb)
], $nDb);
var $oDb = class $oDb2 extends $UCb {
  static {
    $oDb_1 = this;
  }
  static {
    this.ID = "workbench.extensions.action.setProductIconTheme";
  }
  static {
    this.TITLE = localize2(6775, "Set Product Icon Theme");
  }
  static {
    this.M = `${$UCb.LABEL_ACTION_CLASS} theme`;
  }
  static {
    this.N = `${this.M} disabled`;
  }
  constructor(extensionService, O, P, Q) {
    super($oDb_1.ID, $oDb_1.TITLE.value, $oDb_1.N, false);
    this.O = O;
    this.P = P;
    this.Q = Q;
    this.B(Event2.any(extensionService.onDidChangeExtensions, O.onDidProductIconThemeChange)(() => this.update(), this));
    this.update();
  }
  update() {
    this.O.getProductIconThemes().then((productIconThemes) => {
      this.enabled = this.R(productIconThemes);
      this.class = this.enabled ? $oDb_1.M : $oDb_1.N;
    });
  }
  R(productIconThemes) {
    return !!this.extension && this.extension.state === 1 && this.Q.isEnabledEnablementState(this.extension.enablementState) && productIconThemes.some((th) => isThemeFromExtension(th, this.extension));
  }
  async run({ showCurrentTheme, ignoreFocusLost } = { showCurrentTheme: false, ignoreFocusLost: false }) {
    const productIconThemes = await this.O.getProductIconThemes();
    if (!this.R(productIconThemes)) {
      return;
    }
    const currentTheme = this.O.getProductIconTheme();
    const delayer4 = new $Sh(100);
    const picks = getQuickPickEntries(productIconThemes, currentTheme, this.extension, showCurrentTheme);
    const pickedTheme = await this.P.pick(picks, {
      placeHolder: localize(6696, null),
      onDidFocus: (item) => delayer4.trigger(() => this.O.setProductIconTheme(item.id, void 0)),
      ignoreFocusLost
    });
    return this.O.setProductIconTheme(pickedTheme ? pickedTheme.id : currentTheme.id, "auto");
  }
};
$oDb = $oDb_1 = __decorate([
  __param(0, $wN),
  __param(1, $rwb),
  __param(2, $1M),
  __param(3, $qzb)
], $oDb);
var $pDb = class $pDb2 extends $UCb {
  static {
    $pDb_1 = this;
  }
  static {
    this.ID = "workbench.extensions.action.setDisplayLanguage";
  }
  static {
    this.TITLE = localize2(6776, "Set Display Language");
  }
  static {
    this.M = `${$UCb.LABEL_ACTION_CLASS} language`;
  }
  static {
    this.N = `${this.M} disabled`;
  }
  constructor(O) {
    super($pDb_1.ID, $pDb_1.TITLE.value, $pDb_1.N, false);
    this.O = O;
    this.update();
  }
  update() {
    this.enabled = false;
    this.class = $pDb_1.N;
    if (!this.extension) {
      return;
    }
    if (!this.O.canSetLanguage(this.extension)) {
      return;
    }
    if (this.extension.gallery && $z === $xX(this.extension.gallery)) {
      return;
    }
    this.enabled = true;
    this.class = $pDb_1.M;
  }
  async run() {
    return this.extension && this.O.setLanguage(this.extension);
  }
};
$pDb = $pDb_1 = __decorate([
  __param(0, $vzb)
], $pDb);
var $qDb = class $qDb2 extends $UCb {
  static {
    $qDb_1 = this;
  }
  static {
    this.ID = "workbench.extensions.action.clearLanguage";
  }
  static {
    this.TITLE = localize2(6777, "Clear Display Language");
  }
  static {
    this.M = `${$UCb.LABEL_ACTION_CLASS} language`;
  }
  static {
    this.N = `${this.M} disabled`;
  }
  constructor(O, P) {
    super($qDb_1.ID, $qDb_1.TITLE.value, $qDb_1.N, false);
    this.O = O;
    this.P = P;
    this.update();
  }
  update() {
    this.enabled = false;
    this.class = $qDb_1.N;
    if (!this.extension) {
      return;
    }
    if (!this.O.canSetLanguage(this.extension)) {
      return;
    }
    if (this.extension.gallery && $z !== $xX(this.extension.gallery)) {
      return;
    }
    this.enabled = true;
    this.class = $qDb_1.M;
  }
  async run() {
    return this.extension && this.P.clearLocalePreference();
  }
};
$qDb = $qDb_1 = __decorate([
  __param(0, $vzb),
  __param(1, $NCb)
], $qDb);
var $rDb = class $rDb2 extends $Um {
  static {
    $rDb_1 = this;
  }
  static {
    this.ID = "workbench.extensions.action.showRecommendedExtension";
  }
  static {
    this.LABEL = localize(6697, null);
  }
  constructor(extensionId, g) {
    super($rDb_1.ID, $rDb_1.LABEL, void 0, false);
    this.g = g;
    this.f = extensionId;
  }
  async run() {
    await this.g.openSearch(`@id:${this.f}`);
    const [extension] = await this.g.getExtensions([{ id: this.f }], { source: "install-recommendation" }, CancellationToken.None);
    if (extension) {
      return this.g.open(extension);
    }
    return null;
  }
};
$rDb = $rDb_1 = __decorate([
  __param(1, $vzb)
], $rDb);
var $sDb = class $sDb2 extends $Um {
  static {
    $sDb_1 = this;
  }
  static {
    this.ID = "workbench.extensions.action.installRecommendedExtension";
  }
  static {
    this.LABEL = localize(6698, null);
  }
  constructor(extensionId, g, h3) {
    super($sDb_1.ID, $sDb_1.LABEL, void 0, false);
    this.g = g;
    this.h = h3;
    this.f = extensionId;
  }
  async run() {
    await this.h.openSearch(`@id:${this.f}`);
    const [extension] = await this.h.getExtensions([{ id: this.f }], { source: "install-recommendation" }, CancellationToken.None);
    if (extension) {
      await this.h.open(extension);
      try {
        await this.h.install(extension);
      } catch (err) {
        this.g.createInstance($TCb, extension, void 0, extension.latestVersion, 2, err).run();
      }
    }
  }
};
$sDb = $sDb_1 = __decorate([
  __param(1, $Pk),
  __param(2, $vzb)
], $sDb);
var $tDb = class $tDb2 extends $Um {
  static {
    $tDb_1 = this;
  }
  static {
    this.ID = "extensions.ignore";
  }
  static {
    this.f = `${$UCb.LABEL_ACTION_CLASS} ignore`;
  }
  constructor(g, h3) {
    super($tDb_1.ID, "Ignore Recommendation");
    this.g = g;
    this.h = h3;
    this.class = $tDb_1.f;
    this.tooltip = localize(6699, null);
    this.enabled = true;
  }
  run() {
    this.h.toggleGlobalIgnoredRecommendation(this.g.identifier.id, true);
    return Promise.resolve();
  }
};
$tDb = $tDb_1 = __decorate([
  __param(1, $BBb)
], $tDb);
var $uDb = class $uDb2 extends $Um {
  static {
    $uDb_1 = this;
  }
  static {
    this.ID = "extensions.ignore";
  }
  static {
    this.f = `${$UCb.LABEL_ACTION_CLASS} undo-ignore`;
  }
  constructor(g, h3) {
    super($uDb_1.ID, "Undo");
    this.g = g;
    this.h = h3;
    this.class = $uDb_1.f;
    this.tooltip = localize(6700, null);
    this.enabled = true;
  }
  run() {
    this.h.toggleGlobalIgnoredRecommendation(this.g.identifier.id, false);
    return Promise.resolve();
  }
};
$uDb = $uDb_1 = __decorate([
  __param(1, $BBb)
], $uDb);
var $vDb = class $vDb2 extends $Um {
  constructor(id2, label3, f, g, h3, t, L, M) {
    super(id2, label3);
    this.f = f;
    this.g = g;
    this.h = h3;
    this.t = t;
    this.L = L;
    this.M = M;
  }
  N(extensionsFileResource) {
    return this.R(extensionsFileResource).then(({ created: created2, content }) => this.Q(content, extensionsFileResource, ["recommendations"]).then((selection) => this.t.openEditor({
      resource: extensionsFileResource,
      options: {
        pinned: created2,
        selection
      }
    })), (error) => Promise.reject(new Error(localize(6701, null, error))));
  }
  O(workspaceConfigurationFile) {
    return this.P(workspaceConfigurationFile).then((content) => this.Q(content.value.toString(), content.resource, ["extensions", "recommendations"])).then((selection) => this.t.openEditor({
      resource: workspaceConfigurationFile,
      options: {
        selection,
        forceReload: true
        // because content has changed
      }
    }));
  }
  P(workspaceConfigurationFile) {
    return Promise.resolve(this.g.readFile(workspaceConfigurationFile)).then((content) => {
      const workspaceRecommendations = $yw(content.value.toString())["extensions"];
      if (!workspaceRecommendations || !workspaceRecommendations.recommendations) {
        return this.L.write(workspaceConfigurationFile, [{ path: ["extensions"], value: { recommendations: [] } }], true).then(() => this.g.readFile(workspaceConfigurationFile));
      }
      return content;
    });
  }
  Q(content, resource, path) {
    const tree = $zw(content);
    const node = $Aw(tree, path);
    if (node && node.parent && node.parent.children) {
      const recommendationsValueNode = node.parent.children[1];
      const lastExtensionNode = recommendationsValueNode.children && recommendationsValueNode.children.length ? recommendationsValueNode.children[recommendationsValueNode.children.length - 1] : null;
      const offset = lastExtensionNode ? lastExtensionNode.offset + lastExtensionNode.length : recommendationsValueNode.offset + 1;
      return Promise.resolve(this.M.createModelReference(resource)).then((reference) => {
        const position = reference.object.textEditorModel.getPositionAt(offset);
        reference.dispose();
        return {
          startLineNumber: position.lineNumber,
          startColumn: position.column,
          endLineNumber: position.lineNumber,
          endColumn: position.column
        };
      });
    }
    return Promise.resolve(void 0);
  }
  R(extensionsFileResource) {
    return Promise.resolve(this.g.readFile(extensionsFileResource)).then((content) => {
      return { created: false, extensionsFileResource, content: content.value.toString() };
    }, (err) => {
      return this.h.write(extensionsFileResource, $zBb).then(() => {
        return { created: true, extensionsFileResource, content: $zBb };
      });
    });
  }
};
$vDb = __decorate([
  __param(2, $Zk),
  __param(3, $km),
  __param(4, $cK),
  __param(5, $mJ),
  __param(6, $CBb),
  __param(7, $oG)
], $vDb);
var $wDb = class $wDb2 extends $vDb {
  static {
    this.ID = "workbench.extensions.action.configureWorkspaceRecommendedExtensions";
  }
  static {
    this.LABEL = localize(6702, null);
  }
  constructor(id2, label3, fileService, textFileService, contextService, editorService, jsonEditingService, textModelResolverService) {
    super(id2, label3, contextService, fileService, textFileService, editorService, jsonEditingService, textModelResolverService);
    this.B(this.f.onDidChangeWorkbenchState(() => this.S(), this));
    this.S();
  }
  S() {
    this.enabled = this.f.getWorkbenchState() !== 1;
  }
  run() {
    switch (this.f.getWorkbenchState()) {
      case 2:
        return this.N(this.f.getWorkspace().folders[0].toResource($EBb));
      case 3:
        return this.O(this.f.getWorkspace().configuration);
    }
    return Promise.resolve();
  }
};
$wDb = __decorate([
  __param(2, $km),
  __param(3, $cK),
  __param(4, $Zk),
  __param(5, $mJ),
  __param(6, $CBb),
  __param(7, $oG)
], $wDb);
var $xDb = class $xDb2 extends $vDb {
  static {
    this.ID = "workbench.extensions.action.configureWorkspaceFolderRecommendedExtensions";
  }
  static {
    this.LABEL = localize(6703, null);
  }
  constructor(id2, label3, fileService, textFileService, contextService, editorService, jsonEditingService, textModelResolverService, S) {
    super(id2, label3, contextService, fileService, textFileService, editorService, jsonEditingService, textModelResolverService);
    this.S = S;
  }
  run() {
    const folderCount = this.f.getWorkspace().folders.length;
    const pickFolderPromise = folderCount === 1 ? Promise.resolve(this.f.getWorkspace().folders[0]) : this.S.executeCommand($Wyb);
    return Promise.resolve(pickFolderPromise).then((workspaceFolder) => {
      if (workspaceFolder) {
        return this.N(workspaceFolder.toResource($EBb));
      }
      return null;
    });
  }
};
$xDb = __decorate([
  __param(2, $km),
  __param(3, $cK),
  __param(4, $Zk),
  __param(5, $mJ),
  __param(6, $CBb),
  __param(7, $oG),
  __param(8, $sn)
], $xDb);
var $yDb = class $yDb2 extends $Um {
  static {
    $yDb_1 = this;
  }
  static {
    this.f = `${$UCb.TEXT_ACTION_CLASS} extension-status-label`;
  }
  static {
    this.g = `${this.f} hide`;
  }
  get extension() {
    return this.N;
  }
  set extension(extension) {
    if (!(this.N && extension && $DA(this.N.identifier, extension.identifier))) {
      this.h = null;
      this.t = null;
      this.M = null;
    }
    this.N = extension;
    this.update();
  }
  constructor(O, P, Q) {
    super("extensions.action.statusLabel", "", $yDb_1.g, false);
    this.O = O;
    this.P = P;
    this.Q = Q;
    this.h = null;
    this.t = null;
    this.L = null;
    this.M = null;
    this.N = null;
  }
  update() {
    const label3 = this.R();
    this.label = label3 || "";
    this.class = label3 ? $yDb_1.f : $yDb_1.g;
  }
  R() {
    if (!this.extension) {
      return null;
    }
    const currentStatus = this.t;
    const currentVersion = this.L;
    const currentEnablementState = this.M;
    this.t = this.extension.state;
    this.L = this.extension.version;
    if (this.h === null) {
      this.h = this.t;
    }
    this.M = this.extension.enablementState;
    const canAddExtension = () => {
      const runningExtension = this.O.extensions.filter((e) => $DA({ id: e.identifier.value, uuid: e.uuid }, this.extension.identifier))[0];
      if (this.extension.local) {
        if (runningExtension && this.extension.version === runningExtension.version) {
          return true;
        }
        return this.O.canAddExtension($EN(this.extension.local));
      }
      return false;
    };
    const canRemoveExtension = () => {
      if (this.extension.local) {
        if (this.O.extensions.every((e) => !($DA({ id: e.identifier.value, uuid: e.uuid }, this.extension.identifier) && this.extension.server === this.P.getExtensionManagementServer($DN(e))))) {
          return true;
        }
        return this.O.canRemoveExtension($EN(this.extension.local));
      }
      return false;
    };
    if (currentStatus !== null) {
      if (currentStatus === 0 && this.t === 1) {
        if (this.h === 3 && canAddExtension()) {
          return localize(6704, null);
        }
        if (this.h === 1 && this.L !== currentVersion && canAddExtension()) {
          return localize(6705, null);
        }
        return null;
      }
      if (currentStatus === 2 && this.t === 3) {
        this.h = this.t;
        return canRemoveExtension() ? localize(6706, null) : null;
      }
    }
    if (currentEnablementState !== null) {
      const currentlyEnabled = this.Q.isEnabledEnablementState(currentEnablementState);
      const enabled = this.Q.isEnabledEnablementState(this.M);
      if (!currentlyEnabled && enabled) {
        return canAddExtension() ? localize(6707, null) : null;
      }
      if (currentlyEnabled && !enabled) {
        return canRemoveExtension() ? localize(6708, null) : null;
      }
    }
    return null;
  }
  run() {
    return Promise.resolve();
  }
};
$yDb = $yDb_1 = __decorate([
  __param(0, $wN),
  __param(1, $nzb),
  __param(2, $qzb)
], $yDb);
var $zDb = class $zDb2 extends $0Cb {
  static {
    $zDb_1 = this;
  }
  static {
    this.O = `${$UCb.ICON_ACTION_CLASS} extension-sync ${ThemeIcon.asClassName($lCb)}`;
  }
  static {
    this.P = `${this.ICON_ACTION_CLASS} extension-sync ${ThemeIcon.asClassName($kCb)}`;
  }
  constructor(Q, R, S, instantiationService) {
    super("extensions.sync", "", $zDb_1.P, false, instantiationService);
    this.Q = Q;
    this.R = R;
    this.S = S;
    this.B(Event2.filter(this.Q.onDidChangeConfiguration, (e) => e.affectsConfiguration("settingsSync.ignoredExtensions"))(() => this.update()));
    this.B(S.onDidChangeEnablement(() => this.update()));
    this.update();
  }
  update() {
    this.enabled = !!this.extension && this.S.isEnabled() && this.extension.state === 1;
    if (this.extension) {
      const isIgnored = this.R.isExtensionIgnoredToSync(this.extension);
      this.class = isIgnored ? $zDb_1.O : $zDb_1.P;
      this.tooltip = isIgnored ? localize(6709, null) : localize(6710, null);
    }
  }
  async run() {
    return super.run({
      actionGroups: [
        [
          new $Um("extensions.syncignore", this.R.isExtensionIgnoredToSync(this.extension) ? localize(6711, null) : localize(6712, null), void 0, true, () => this.R.toggleExtensionIgnoredToSync(this.extension))
        ]
      ],
      disposeActionsOnHide: true
    });
  }
};
$zDb = $zDb_1 = __decorate([
  __param(0, $kl),
  __param(1, $vzb),
  __param(2, $6Bb),
  __param(3, $Pk)
], $zDb);
var $ADb = class $ADb2 extends $UCb {
  static {
    $ADb_1 = this;
  }
  static {
    this.M = `${$UCb.ICON_ACTION_CLASS} extension-status`;
  }
  get status() {
    return this.N;
  }
  constructor(Q, R, S, U, W, X, Y, Z, $149, ab, bb, cb, db) {
    super("extensions.status", "", `${$ADb_1.M} hide`, false);
    this.Q = Q;
    this.R = R;
    this.S = S;
    this.U = U;
    this.W = W;
    this.X = X;
    this.Y = Y;
    this.Z = Z;
    this.$ = $149;
    this.ab = ab;
    this.bb = bb;
    this.cb = cb;
    this.db = db;
    this.updateWhenCounterExtensionChanges = true;
    this.N = [];
    this.O = this.B(new $ze());
    this.onDidChangeStatus = this.O.event;
    this.P = new $Ph();
    this.B(this.R.onDidChangeFormatters(() => this.update(), this));
    this.B(this.Y.onDidChangeExtensions(() => this.update()));
    this.B(this.db.onDidChangeAccessData(() => this.update()));
    this.B(bb.onDidChangeAllowedExtensions(() => this.update()));
    this.update();
  }
  update() {
    this.P.queue(() => this.eb());
  }
  async eb() {
    this.fb(void 0, true);
    this.enabled = false;
    if (!this.extension) {
      return;
    }
    if (this.extension.isMalicious) {
      this.fb({ icon: $wCb, message: new $bm(localize(6713, null)) }, true);
      return;
    }
    if (this.extension.state === 3 && this.extension.gallery && !this.extension.gallery.isSigned) {
      this.fb({ icon: $wCb, message: new $bm(localize(6714, null)) }, true);
      return;
    }
    if (this.extension.deprecationInfo) {
      if (this.extension.deprecationInfo.extension) {
        const link2 = `[${this.extension.deprecationInfo.extension.displayName}](${URI.parse(`command:extension.open?${encodeURIComponent(JSON.stringify([this.extension.deprecationInfo.extension.id]))}`)})`;
        this.fb({ icon: $wCb, message: new $bm(localize(6715, null, link2)) }, true);
      } else if (this.extension.deprecationInfo.settings) {
        const link2 = `[${localize(6716, null)}](${URI.parse(`command:workbench.action.openSettings?${encodeURIComponent(JSON.stringify([this.extension.deprecationInfo.settings.map((setting) => `@id:${setting}`).join(" ")]))}`)})`;
        this.fb({ icon: $wCb, message: new $bm(localize(6717, null, link2)) }, true);
      } else {
        const message = new $bm(localize(6718, null));
        if (this.extension.deprecationInfo.additionalInfo) {
          message.appendMarkdown(` ${this.extension.deprecationInfo.additionalInfo}`);
        }
        this.fb({ icon: $wCb, message }, true);
      }
      return;
    }
    if (this.X.canSetLanguage(this.extension)) {
      return;
    }
    if (this.extension.outdated && this.X.isAutoUpdateEnabledFor(this.extension)) {
      const message = await this.X.shouldRequireConsentToUpdate(this.extension);
      if (message) {
        const markdown = new $bm();
        markdown.appendMarkdown(`${message} `);
        markdown.appendMarkdown(localize(6719, null, this.extension.hasChangelog() ? URI.parse(`command:extension.open?${encodeURIComponent(JSON.stringify([
          this.extension.identifier.id,
          "changelog"
          /* ExtensionEditorTab.Changelog */
        ]))}`).toString() : this.extension.repository ? this.extension.repository : URI.parse(`command:extension.open?${encodeURIComponent(JSON.stringify([this.extension.identifier.id]))}`).toString()));
        this.fb({ icon: $wCb, message: markdown }, true);
      }
    }
    if (this.extension.gallery && this.extension.state === 3) {
      const result2 = await this.X.canInstall(this.extension);
      if (result2 !== true) {
        this.fb({ icon: $wCb, message: result2 }, true);
        return;
      }
    }
    if (!this.extension.local || !this.extension.server || this.extension.state !== 1) {
      return;
    }
    const result = this.bb.isAllowed(this.extension.local);
    if (result !== true) {
      this.fb({ icon: $wCb, message: new $bm(localize(6720, null, result.value)) }, true);
      return;
    }
    if (this.extension.enablementState === 2) {
      this.fb({ message: new $bm(localize(6721, null)) }, true);
      return;
    }
    if (this.extension.enablementState === 3) {
      this.fb({ message: new $bm(localize(6722, null)) }, true);
      return;
    }
    if (this.extension.enablementState === 4) {
      const details = $3z(this.extension.local.manifest.capabilities?.virtualWorkspaces);
      this.fb({ icon: $xCb, message: new $bm(details ? $fm(details) : localize(6723, null)) }, true);
      return;
    }
    if ($_S(this.$.getWorkspace())) {
      const virtualSupportType = this.Z.getExtensionVirtualWorkspaceSupportType(this.extension.local.manifest);
      const details = $3z(this.extension.local.manifest.capabilities?.virtualWorkspaces);
      if (virtualSupportType === "limited" || details) {
        this.fb({ icon: $wCb, message: new $bm(details ? $fm(details) : localize(6724, null)) }, true);
        return;
      }
    }
    if (!this.W.isWorkspaceTrusted() && // Extension is disabled by untrusted workspace
    (this.extension.enablementState === 0 || // All disabled dependencies of the extension are disabled by untrusted workspace
    this.extension.enablementState === 7 && this.cb.getDependenciesEnablementStates(this.extension.local).every(
      ([, enablementState]) => this.cb.isEnabledEnablementState(enablementState) || enablementState === 0
      /* EnablementState.DisabledByTrustRequirement */
    ))) {
      this.enabled = true;
      const untrustedDetails = $3z(this.extension.local.manifest.capabilities?.untrustedWorkspaces);
      this.fb({ icon: $yCb, message: new $bm(untrustedDetails ? $fm(untrustedDetails) : localize(6725, null)) }, true);
      return;
    }
    if (this.U.isWorkspaceTrustEnabled() && !this.W.isWorkspaceTrusted()) {
      const untrustedSupportType = this.Z.getExtensionUntrustedWorkspaceSupportType(this.extension.local.manifest);
      const untrustedDetails = $3z(this.extension.local.manifest.capabilities?.untrustedWorkspaces);
      if (untrustedSupportType === "limited" || untrustedDetails) {
        this.enabled = true;
        this.fb({ icon: $yCb, message: new $bm(untrustedDetails ? $fm(untrustedDetails) : localize(6726, null)) }, true);
        return;
      }
    }
    if (this.extension.enablementState === 1) {
      if (!this.X.installed.some((e) => $DA(e.identifier, this.extension.identifier) && e.server !== this.extension.server)) {
        let message;
        if (this.Q.localExtensionManagementServer === this.extension.server) {
          if (this.Z.prefersExecuteOnWorkspace(this.extension.local.manifest)) {
            if (this.Q.remoteExtensionManagementServer) {
              message = new $bm(`${localize(6727, null, this.Q.remoteExtensionManagementServer.label)} [${localize(6728, null)}](https://code.visualstudio.com/api/advanced-topics/remote-extensions#architecture-and-extension-kinds)`);
            }
          }
        } else if (this.Q.remoteExtensionManagementServer === this.extension.server) {
          if (this.Z.prefersExecuteOnUI(this.extension.local.manifest)) {
            if (this.Q.localExtensionManagementServer) {
              message = new $bm(`${localize(6729, null, this.Q.remoteExtensionManagementServer.label)} [${localize(6730, null)}](https://code.visualstudio.com/api/advanced-topics/remote-extensions#architecture-and-extension-kinds)`);
            } else if ($r) {
              message = new $bm(`${localize(6731, null, this.ab.nameLong)} [${localize(6732, null)}](https://code.visualstudio.com/api/advanced-topics/remote-extensions#architecture-and-extension-kinds)`);
            }
          }
        } else if (this.Q.webExtensionManagementServer === this.extension.server) {
          message = new $bm(`${localize(6733, null, this.ab.nameLong)} [${localize(6734, null)}](https://code.visualstudio.com/api/advanced-topics/remote-extensions#architecture-and-extension-kinds)`);
        }
        if (message) {
          this.fb({ icon: $wCb, message }, true);
        }
        return;
      }
    }
    const extensionId = new $5z(this.extension.identifier.id);
    const features = $Wn.as(Extensions3.ExtensionFeaturesRegistry).getExtensionFeatures();
    for (const feature of features) {
      const status = this.db.getAccessData(extensionId, feature.id)?.current?.status;
      const manageAccessLink = `[${localize(6735, null)}](${URI.parse(`command:extension.open?${encodeURIComponent(JSON.stringify([this.extension.identifier.id, "features", false, feature.id]))}`)})`;
      if (status?.severity === Severity2.Error) {
        this.fb({ icon: $vCb, message: new $bm().appendText(status.message).appendMarkdown(` ${manageAccessLink}`) }, true);
        return;
      }
      if (status?.severity === Severity2.Warning) {
        this.fb({ icon: $wCb, message: new $bm().appendText(status.message).appendMarkdown(` ${manageAccessLink}`) }, true);
        return;
      }
    }
    if (this.Q.remoteExtensionManagementServer) {
      if ($9z(this.extension.local.manifest)) {
        if (!this.X.installed.some((e) => $DA(e.identifier, this.extension.identifier) && e.server !== this.extension.server)) {
          const message = this.extension.server === this.Q.localExtensionManagementServer ? new $bm(localize(6736, null, this.Q.remoteExtensionManagementServer.label)) : new $bm(localize(6737, null));
          this.fb({ icon: $xCb, message }, true);
        }
        return;
      }
      const runningExtension = this.Y.extensions.filter((e) => $DA({ id: e.identifier.value, uuid: e.uuid }, this.extension.identifier))[0];
      const runningExtensionServer = runningExtension ? this.Q.getExtensionManagementServer($DN(runningExtension)) : null;
      if (this.extension.server === this.Q.localExtensionManagementServer && runningExtensionServer === this.Q.remoteExtensionManagementServer) {
        if (this.Z.prefersExecuteOnWorkspace(this.extension.local.manifest)) {
          this.fb({ icon: $xCb, message: new $bm(`${localize(6738, null)} [${localize(6739, null)}](https://code.visualstudio.com/api/advanced-topics/remote-extensions#architecture-and-extension-kinds)`) }, true);
        }
        return;
      }
      if (this.extension.server === this.Q.remoteExtensionManagementServer && runningExtensionServer === this.Q.localExtensionManagementServer) {
        if (this.Z.prefersExecuteOnUI(this.extension.local.manifest)) {
          this.fb({ icon: $xCb, message: new $bm(`${localize(6740, null)} [${localize(6741, null)}](https://code.visualstudio.com/api/advanced-topics/remote-extensions#architecture-and-extension-kinds)`) }, true);
        }
        return;
      }
      if (this.extension.server === this.Q.remoteExtensionManagementServer && runningExtensionServer === this.Q.webExtensionManagementServer) {
        if (this.Z.canExecuteOnWeb(this.extension.local.manifest)) {
          this.fb({ icon: $xCb, message: new $bm(`${localize(6742, null)} [${localize(6743, null)}](https://code.visualstudio.com/api/advanced-topics/remote-extensions#architecture-and-extension-kinds)`) }, true);
        }
        return;
      }
    }
    if (this.extension.enablementState === 7) {
      this.fb({
        icon: $wCb,
        message: new $bm(localize(6744, null)).appendMarkdown(`&nbsp;[${localize(6745, null)}](${URI.parse(`command:extension.open?${encodeURIComponent(JSON.stringify([
          this.extension.identifier.id,
          "dependencies"
          /* ExtensionEditorTab.Dependencies */
        ]))}`)})`)
      }, true);
      return;
    }
    if (!this.extension.local.isValid) {
      const errors = this.extension.local.validations.filter(([severity]) => severity === Severity2.Error).map(([, message]) => message);
      this.fb({ icon: $wCb, message: new $bm(errors.join(" ").trim()) }, true);
      return;
    }
    const isEnabled = this.cb.isEnabled(this.extension.local);
    const isRunning = this.Y.extensions.some((e) => $DA({ id: e.identifier.value, uuid: e.uuid }, this.extension.identifier));
    if (!this.extension.isWorkspaceScoped && isEnabled && isRunning) {
      if (this.extension.enablementState === 11) {
        this.fb({ message: new $bm(localize(6746, null)) }, true);
        return;
      }
      if (this.Q.localExtensionManagementServer && this.Q.remoteExtensionManagementServer) {
        if (this.extension.server === this.Q.remoteExtensionManagementServer) {
          this.fb({ message: new $bm(localize(6747, null, this.extension.server.label)) }, true);
          return;
        }
      }
      if (this.extension.enablementState === 10) {
        return;
      }
    }
    if (!isEnabled && !isRunning) {
      if (this.extension.enablementState === 8) {
        this.fb({ message: new $bm(localize(6748, null)) }, true);
        return;
      }
      if (this.extension.enablementState === 9) {
        this.fb({ message: new $bm(localize(6749, null)) }, true);
        return;
      }
    }
  }
  fb(status, updateClass) {
    if (status) {
      if (this.N.some((s) => s.message.value === status.message.value && s.icon?.id === status.icon?.id)) {
        return;
      }
    } else {
      if (this.N.length === 0) {
        return;
      }
      this.N = [];
    }
    if (status) {
      this.N.push(status);
      this.N.sort((a, b) => b.icon === $yCb ? -1 : a.icon === $yCb ? 1 : b.icon === $vCb ? -1 : a.icon === $vCb ? 1 : b.icon === $wCb ? -1 : a.icon === $wCb ? 1 : b.icon === $xCb ? -1 : a.icon === $xCb ? 1 : 0);
    }
    if (updateClass) {
      if (status?.icon === $vCb) {
        this.class = `${$ADb_1.M} extension-status-error ${ThemeIcon.asClassName($vCb)}`;
      } else if (status?.icon === $wCb) {
        this.class = `${$ADb_1.M} extension-status-warning ${ThemeIcon.asClassName($wCb)}`;
      } else if (status?.icon === $xCb) {
        this.class = `${$ADb_1.M} extension-status-info ${ThemeIcon.asClassName($xCb)}`;
      } else if (status?.icon === $yCb) {
        this.class = `${$ADb_1.M} ${ThemeIcon.asClassName($yCb)}`;
      } else {
        this.class = `${$ADb_1.M} hide`;
      }
    }
    this.O.fire();
  }
  async run() {
    if (this.N[0]?.icon === $yCb) {
      return this.S.executeCommand("workbench.trust.manage");
    }
  }
};
$ADb = $ADb_1 = __decorate([
  __param(0, $nzb),
  __param(1, $ZI),
  __param(2, $sn),
  __param(3, $3M),
  __param(4, $4M),
  __param(5, $vzb),
  __param(6, $wN),
  __param(7, $LCb),
  __param(8, $Zk),
  __param(9, $Vu),
  __param(10, $xA),
  __param(11, $qzb),
  __param(12, $wlb)
], $ADb);
var $BDb = class $BDb2 extends $Um {
  static {
    $BDb_1 = this;
  }
  static {
    this.ID = "workbench.extensions.action.reinstall";
  }
  static {
    this.LABEL = localize(6750, null);
  }
  constructor(id2 = $BDb_1.ID, label3 = $BDb_1.LABEL, f, g, h3, t, L, M) {
    super(id2, label3);
    this.f = f;
    this.g = g;
    this.h = h3;
    this.t = t;
    this.L = L;
    this.M = M;
  }
  get enabled() {
    return this.f.local.filter((l) => !l.isBuiltin && l.local).length > 0;
  }
  run() {
    return this.h.pick(this.N(), { placeHolder: localize(6751, null) }).then((pick) => pick && this.O(pick.extension));
  }
  N() {
    return this.f.queryLocal().then((local) => {
      const entries2 = local.filter((extension) => !extension.isBuiltin && extension.server !== this.g.webExtensionManagementServer).map((extension) => {
        return {
          id: extension.identifier.id,
          label: extension.displayName,
          description: extension.identifier.id,
          extension
        };
      });
      return entries2;
    });
  }
  O(extension) {
    return this.f.openSearch("@installed ").then(() => {
      return this.f.reinstall(extension).then((extension2) => {
        const requireReload = !(extension2.local && this.M.canAddExtension($EN(extension2.local)));
        const message = requireReload ? localize(6752, null, extension2.identifier.id) : localize(6753, null, extension2.identifier.id);
        const actions = requireReload ? [{
          label: localize(6754, null),
          run: () => this.L.reload()
        }] : [];
        this.t.prompt(Severity2.Info, message, actions, { sticky: true });
      }, (error) => this.t.error(error));
    });
  }
};
$BDb = $BDb_1 = __decorate([
  __param(2, $vzb),
  __param(3, $nzb),
  __param(4, $1M),
  __param(5, $PJ),
  __param(6, $S4),
  __param(7, $wN)
], $BDb);
var $CDb = class $CDb2 extends $Um {
  static {
    $CDb_1 = this;
  }
  static {
    this.ID = "workbench.extensions.action.install.specificVersion";
  }
  static {
    this.LABEL = localize(6755, null);
  }
  constructor(id2 = $CDb_1.ID, label3 = $CDb_1.LABEL, f, g, h3, t) {
    super(id2, label3);
    this.f = f;
    this.g = g;
    this.h = h3;
    this.t = t;
  }
  get enabled() {
    return this.f.local.some((l) => this.L(l));
  }
  async run() {
    const extensionPick = await this.g.pick(this.M(), { placeHolder: localize(6756, null), matchOnDetail: true });
    if (extensionPick && extensionPick.extension) {
      const action = this.h.createInstance($eDb, extensionPick.extension, true);
      await action.run();
      await this.f.openSearch(extensionPick.extension.identifier.id);
    }
  }
  L(extension) {
    const action = this.h.createInstance($eDb, extension, true);
    return action.enabled && !!extension.local && this.t.isEnabled(extension.local);
  }
  async M() {
    const installed = await this.f.queryLocal();
    const entries2 = [];
    for (const extension of installed) {
      if (this.L(extension)) {
        entries2.push({
          id: extension.identifier.id,
          label: extension.displayName || extension.identifier.id,
          description: extension.identifier.id,
          extension
        });
      }
    }
    return entries2.sort((e1, e2) => e1.extension.displayName.localeCompare(e2.extension.displayName));
  }
};
$CDb = $CDb_1 = __decorate([
  __param(2, $vzb),
  __param(3, $1M),
  __param(4, $Pk),
  __param(5, $qzb)
], $CDb);
var $DDb = class $DDb2 extends $Um {
  constructor(id2, g, h3, t, L) {
    super(id2);
    this.g = g;
    this.h = h3;
    this.t = t;
    this.L = L;
    this.f = void 0;
    this.N();
    this.g.queryLocal().then(() => this.M());
    this.B(this.g.onChange(() => {
      if (this.f) {
        this.M();
      }
    }));
  }
  M() {
    this.f = this.g.local;
    this.N();
  }
  N() {
    this.enabled = !!this.f && this.S(this.f).length > 0;
    this.tooltip = this.label;
  }
  async run() {
    return this.P();
  }
  async O() {
    const local = await this.g.queryLocal();
    return this.S(local);
  }
  async P() {
    const quickPick = this.h.createQuickPick();
    quickPick.busy = true;
    const disposable = quickPick.onDidAccept(() => {
      disposable.dispose();
      quickPick.hide();
      quickPick.dispose();
      this.Q(quickPick.selectedItems);
    });
    quickPick.show();
    const localExtensionsToInstall = await this.O();
    quickPick.busy = false;
    if (localExtensionsToInstall.length) {
      quickPick.title = this.R();
      quickPick.placeholder = localize(6757, null);
      quickPick.canSelectMany = true;
      localExtensionsToInstall.sort((e1, e2) => e1.displayName.localeCompare(e2.displayName));
      quickPick.items = localExtensionsToInstall.map((extension) => ({ extension, label: extension.displayName, description: extension.version }));
    } else {
      quickPick.hide();
      quickPick.dispose();
      this.t.notify({
        severity: Severity2.Info,
        message: localize(6758, null)
      });
    }
  }
  async Q(selectedItems) {
    if (selectedItems.length) {
      const localExtensionsToInstall = selectedItems.filter((r2) => !!r2.extension).map((r2) => r2.extension);
      if (localExtensionsToInstall.length) {
        await this.L.withProgress({
          location: 15,
          title: localize(6759, null)
        }, () => this.U(localExtensionsToInstall));
        this.t.info(localize(6760, null));
      }
    }
  }
};
$DDb = __decorate([
  __param(1, $vzb),
  __param(2, $1M),
  __param(3, $PJ),
  __param(4, $TJ)
], $DDb);
var $EDb = class $EDb2 extends $DDb {
  constructor(extensionsWorkbenchService, quickInputService, progressService, notificationService, W, X, Y, Z, $149) {
    super("workbench.extensions.actions.installLocalExtensionsInRemote", extensionsWorkbenchService, quickInputService, notificationService, progressService);
    this.W = W;
    this.X = X;
    this.Y = Y;
    this.Z = Z;
    this.$ = $149;
  }
  get label() {
    if (this.W && this.W.remoteExtensionManagementServer) {
      return localize(6761, null, this.W.remoteExtensionManagementServer.label);
    }
    return "";
  }
  R() {
    return localize(6762, null, this.W.remoteExtensionManagementServer.label);
  }
  S(local) {
    return local.filter((extension) => {
      const action = this.Y.createInstance($2Cb, true);
      action.extension = extension;
      return action.enabled;
    });
  }
  async U(localExtensionsToInstall) {
    const galleryExtensions = [];
    const vsixs = [];
    const targetPlatform = await this.W.remoteExtensionManagementServer.extensionManagementService.getTargetPlatform();
    await Promises.settled(localExtensionsToInstall.map(async (extension) => {
      if (this.X.isEnabled()) {
        const gallery = (await this.X.getExtensions([{ ...extension.identifier, preRelease: !!extension.local?.preRelease }], { targetPlatform, compatible: true }, CancellationToken.None))[0];
        if (gallery) {
          galleryExtensions.push(gallery);
          return;
        }
      }
      const vsix = await this.W.localExtensionManagementServer.extensionManagementService.zip(extension.local);
      vsixs.push(vsix);
    }));
    await Promises.settled(galleryExtensions.map((gallery) => this.W.remoteExtensionManagementServer.extensionManagementService.installFromGallery(gallery)));
    try {
      await Promises.settled(vsixs.map((vsix) => this.W.remoteExtensionManagementServer.extensionManagementService.install(vsix)));
    } finally {
      try {
        await Promise.allSettled(vsixs.map((vsix) => this.Z.del(vsix)));
      } catch (error) {
        this.$.error(error);
      }
    }
  }
};
$EDb = __decorate([
  __param(0, $vzb),
  __param(1, $1M),
  __param(2, $TJ),
  __param(3, $PJ),
  __param(4, $nzb),
  __param(5, $pA),
  __param(6, $Pk),
  __param(7, $km),
  __param(8, $wn)
], $EDb);
var $FDb = class $FDb2 extends $DDb {
  constructor(id2, extensionsWorkbenchService, quickInputService, progressService, notificationService, W, X, Y, Z) {
    super(id2, extensionsWorkbenchService, quickInputService, notificationService, progressService);
    this.W = W;
    this.X = X;
    this.Y = Y;
    this.Z = Z;
  }
  get label() {
    return localize(6763, null);
  }
  R() {
    return localize(6764, null);
  }
  S(local) {
    return local.filter((extension) => extension.type === 1 && extension.server !== this.W.localExtensionManagementServer && !this.g.installed.some((e) => e.server === this.W.localExtensionManagementServer && $DA(e.identifier, extension.identifier)));
  }
  async U(extensions) {
    const galleryExtensions = [];
    const vsixs = [];
    const targetPlatform = await this.W.localExtensionManagementServer.extensionManagementService.getTargetPlatform();
    await Promises.settled(extensions.map(async (extension) => {
      if (this.X.isEnabled()) {
        const gallery = (await this.X.getExtensions([{ ...extension.identifier, preRelease: !!extension.local?.preRelease }], { targetPlatform, compatible: true }, CancellationToken.None))[0];
        if (gallery) {
          galleryExtensions.push(gallery);
          return;
        }
      }
      const vsix = await this.W.remoteExtensionManagementServer.extensionManagementService.zip(extension.local);
      vsixs.push(vsix);
    }));
    await Promises.settled(galleryExtensions.map((gallery) => this.W.localExtensionManagementServer.extensionManagementService.installFromGallery(gallery)));
    try {
      await Promises.settled(vsixs.map((vsix) => this.W.localExtensionManagementServer.extensionManagementService.install(vsix)));
    } finally {
      try {
        await Promise.allSettled(vsixs.map((vsix) => this.Y.del(vsix)));
      } catch (error) {
        this.Z.error(error);
      }
    }
  }
};
$FDb = __decorate([
  __param(1, $vzb),
  __param(2, $1M),
  __param(3, $TJ),
  __param(4, $PJ),
  __param(5, $nzb),
  __param(6, $pA),
  __param(7, $km),
  __param(8, $wn)
], $FDb);
$tn.registerCommand("workbench.extensions.action.showExtensionsForLanguage", function(accessor, fileExtension) {
  const extensionsWorkbenchService = accessor.get($vzb);
  return extensionsWorkbenchService.openSearch(`ext:${fileExtension.replace(/^\./, "")}`);
});
var $GDb = "workbench.extensions.action.showExtensionsWithIds";
$tn.registerCommand($GDb, function(accessor, extensionIds) {
  const extensionsWorkbenchService = accessor.get($vzb);
  return extensionsWorkbenchService.openSearch(extensionIds.map((id2) => `@id:${id2}`).join(" "));
});
$5n("extensionButton.background", {
  dark: $Uq,
  light: $Uq,
  hcDark: null,
  hcLight: null
}, localize(6765, null));
$5n("extensionButton.foreground", {
  dark: $Sq,
  light: $Sq,
  hcDark: null,
  hcLight: null
}, localize(6766, null));
$5n("extensionButton.hoverBackground", {
  dark: $Vq,
  light: $Vq,
  hcDark: null,
  hcLight: null
}, localize(6767, null));
$5n("extensionButton.separator", $Tq, localize(6768, null));
var $HDb = $5n("extensionButton.prominentBackground", {
  dark: $Uq,
  light: $Uq,
  hcDark: null,
  hcLight: null
}, localize(6769, null));
$5n("extensionButton.prominentForeground", {
  dark: $Sq,
  light: $Sq,
  hcDark: null,
  hcLight: null
}, localize(6770, null));
$5n("extensionButton.prominentHoverBackground", {
  dark: $Vq,
  light: $Vq,
  hcDark: null,
  hcLight: null
}, localize(6771, null));
$ms((theme, collector) => {
  const errorColor = theme.getColor($Vo);
  if (errorColor) {
    collector.addRule(`.extension-editor .header .actions-status-container > .status ${ThemeIcon.asCSSSelector($vCb)} { color: ${errorColor}; }`);
    collector.addRule(`.extension-editor .body .subcontent .runtime-status ${ThemeIcon.asCSSSelector($vCb)} { color: ${errorColor}; }`);
    collector.addRule(`.monaco-hover.extension-hover .markdown-hover .hover-contents ${ThemeIcon.asCSSSelector($vCb)} { color: ${errorColor}; }`);
  }
  const warningColor = theme.getColor($Yo);
  if (warningColor) {
    collector.addRule(`.extension-editor .header .actions-status-container > .status ${ThemeIcon.asCSSSelector($wCb)} { color: ${warningColor}; }`);
    collector.addRule(`.extension-editor .body .subcontent .runtime-status ${ThemeIcon.asCSSSelector($wCb)} { color: ${warningColor}; }`);
    collector.addRule(`.monaco-hover.extension-hover .markdown-hover .hover-contents ${ThemeIcon.asCSSSelector($wCb)} { color: ${warningColor}; }`);
  }
  const infoColor = theme.getColor($2o);
  if (infoColor) {
    collector.addRule(`.extension-editor .header .actions-status-container > .status ${ThemeIcon.asCSSSelector($xCb)} { color: ${infoColor}; }`);
    collector.addRule(`.extension-editor .body .subcontent .runtime-status ${ThemeIcon.asCSSSelector($xCb)} { color: ${infoColor}; }`);
    collector.addRule(`.monaco-hover.extension-hover .markdown-hover .hover-contents ${ThemeIcon.asCSSSelector($xCb)} { color: ${infoColor}; }`);
  }
});

// out-build/vs/workbench/contrib/chat/browser/chatAgentHover.js
var $IDb = class $IDb2 extends $3c {
  constructor(m, n, r2) {
    super();
    this.m = m;
    this.n = n;
    this.r = r2;
    this.j = this.B(new $ze());
    this.onDidChangeContents = this.j.event;
    const hoverElement = h(".chat-agent-hover@root", [
      h(".chat-agent-hover-header", [
        h(".chat-agent-hover-icon@icon"),
        h(".chat-agent-hover-details", [
          h(".chat-agent-hover-name@name"),
          h(".chat-agent-hover-extension", [
            h(".chat-agent-hover-extension-name@extensionName"),
            h(".chat-agent-hover-separator@separator"),
            h(".chat-agent-hover-publisher@publisher")
          ])
        ])
      ]),
      h(".chat-agent-hover-warning@warning"),
      h("span.chat-agent-hover-description@description")
    ]);
    this.domNode = hoverElement.root;
    this.a = hoverElement.icon;
    this.b = hoverElement.name;
    this.c = hoverElement.extensionName;
    this.g = hoverElement.description;
    hoverElement.separator.textContent = "|";
    const verifiedBadge = $("span.extension-verified-publisher", void 0, $C1($pCb));
    this.f = $("span.chat-agent-hover-publisher-name");
    $bk(hoverElement.publisher, verifiedBadge, this.f);
    hoverElement.warning.appendChild($C1($6l.warning));
    hoverElement.warning.appendChild($("span", void 0, localize(4781, null)));
  }
  setAgent(id2) {
    const agent = this.m.getAgent(id2);
    if (agent.metadata.icon instanceof URI) {
      const avatarIcon = $("img.icon");
      avatarIcon.src = $ih.uriToBrowserUri(agent.metadata.icon).toString(true);
      this.a.replaceChildren($(".avatar", void 0, avatarIcon));
    } else if (agent.metadata.themeIcon) {
      const avatarIcon = $(ThemeIcon.asCSSSelector(agent.metadata.themeIcon));
      this.a.replaceChildren($(".avatar.codicon-avatar", void 0, avatarIcon));
    }
    this.domNode.classList.toggle("noExtensionName", !!agent.isDynamic);
    const isAllowed = this.r.getAgentNameRestriction(agent);
    this.b.textContent = isAllowed ? `@${agent.name}` : $5O(agent);
    this.c.textContent = agent.extensionDisplayName;
    this.f.textContent = agent.publisherDisplayName ?? agent.extensionPublisherId;
    let description = agent.description ?? "";
    if (description) {
      if (!description.match(/[\.\?\!] *$/)) {
        description += ".";
      }
    }
    this.g.textContent = description;
    this.domNode.classList.toggle("allowedName", isAllowed);
    this.domNode.classList.toggle("verifiedPublisher", false);
    if (!agent.isDynamic) {
      const cancel = this.B(new $ad());
      this.n.getExtensions([{ id: agent.extensionId.value }], cancel.token).then((extensions) => {
        cancel.dispose();
        const extension = extensions[0];
        if (extension?.publisherDomain?.verified) {
          this.domNode.classList.toggle("verifiedPublisher", true);
          this.j.fire();
        }
      });
    }
  }
};
$IDb = __decorate([
  __param(0, $ZO),
  __param(1, $vzb),
  __param(2, $3O)
], $IDb);
function $JDb(getAgent, commandService) {
  return {
    actions: [
      {
        commandId: $GDb,
        label: localize(4782, null),
        run: () => {
          const agent = getAgent();
          if (agent) {
            commandService.executeCommand($GDb, [agent.extensionId.value]);
          }
        }
      }
    ]
  };
}

// out-build/vs/workbench/contrib/chat/browser/chatContentParts/chatAgentCommandContentPart.js
var $KDb = class $KDb2 extends $3c {
  constructor(cmd, onClick2, a) {
    super();
    this.a = a;
    this.domNode = document.createElement("span");
    this.domNode.classList.add("chat-agent-command");
    this.domNode.setAttribute("aria-label", cmd.name);
    this.domNode.setAttribute("role", "button");
    const groupId = $ps();
    const commandSpan = document.createElement("span");
    this.domNode.appendChild(commandSpan);
    commandSpan.innerText = $yO + cmd.name;
    this.q.add(this.a.setupDelayedHover(commandSpan, { content: cmd.description, appearance: { showPointer: true } }, { groupId }));
    const rerun = localize(4783, null, $yO, cmd.name);
    const btn = new $k2(this.domNode, { ariaLabel: rerun });
    btn.icon = $6l.close;
    this.q.add(btn.onDidClick(() => onClick2()));
    this.q.add(btn);
    this.q.add(this.a.setupDelayedHover(btn.element, { content: rerun, appearance: { showPointer: true } }, { groupId }));
  }
  hasSameContent(other, followingContent, element) {
    return false;
  }
};
$KDb = __decorate([
  __param(2, $5$)
], $KDb);

// out-build/vs/workbench/contrib/chat/browser/chatContentParts/chatCodeCitationContentPart.js
var $PDb = class $PDb2 extends $3c {
  constructor(citations, context, a, b) {
    super();
    this.a = a;
    this.b = b;
    const label3 = $WO(citations.citations);
    const elements = h(".chat-code-citation-message@root", [
      h("span.chat-code-citation-label@label"),
      h(".chat-code-citation-button-container@button")
    ]);
    elements.label.textContent = label3 + " - ";
    const button = this.B(new $k2(elements.button, {
      buttonBackground: void 0,
      buttonBorder: void 0,
      buttonForeground: void 0,
      buttonHoverBackground: void 0,
      buttonSecondaryBackground: void 0,
      buttonSecondaryForeground: void 0,
      buttonSecondaryHoverBackground: void 0,
      buttonSeparator: void 0
    }));
    button.label = localize(4794, null);
    this.B(button.onDidClick(() => {
      const citationText = `# Code Citations

` + citations.citations.map((c) => `## License: ${c.license}
${c.value.toString()}

\`\`\`
${c.snippet}
\`\`\`

`).join("\n");
      this.a.openEditor({ resource: void 0, contents: citationText, languageId: "markdown" });
      this.b.publicLog2("openedChatCodeCitations");
    }));
    this.domNode = elements.root;
  }
  hasSameContent(other, followingContent, element) {
    return other.kind === "codeCitations";
  }
};
$PDb = __decorate([
  __param(2, $mJ),
  __param(3, $zv)
], $PDb);

// out-build/vs/workbench/contrib/chat/browser/chatContentParts/chatCommandContentPart.js
var $93 = $;
var $QDb = class $QDb2 extends $3c {
  constructor(commandButton, context, a) {
    super();
    this.a = a;
    this.domNode = $93(".chat-command-button");
    const enabled = !$asb(context.element) || !context.element.isStale;
    const tooltip = enabled ? commandButton.command.tooltip : localize(4795, null);
    const button = this.B(new $k2(this.domNode, { ...$q$, supportIcons: true, title: tooltip }));
    button.label = commandButton.command.title;
    button.enabled = enabled;
    this.B(button.onDidClick(() => this.a.executeCommand(commandButton.command.id, ...commandButton.command.arguments ?? [])));
  }
  hasSameContent(other) {
    return other.kind === "command";
  }
};
$QDb = __decorate([
  __param(2, $sn)
], $QDb);

// out-build/vs/workbench/contrib/chat/browser/chatContentParts/chatConfirmationWidget.js
var $RDb = class $RDb2 extends $3c {
  get onDidClick() {
    return this.a.event;
  }
  get domNode() {
    return this.b;
  }
  setShowButtons(showButton) {
    this.domNode.classList.toggle("hideButtons", !showButton);
  }
  constructor(title, message, buttons, c) {
    super();
    this.c = c;
    this.a = this.B(new $ze());
    const elements = h(".chat-confirmation-widget@root", [
      h(".chat-confirmation-widget-title@title"),
      h(".chat-confirmation-widget-message@message"),
      h(".chat-confirmation-buttons-container@buttonsContainer")
    ]);
    this.b = elements.root;
    const renderer = this.B(this.c.createInstance($Q_, {}));
    const renderedTitle = this.B(renderer.render(new $bm(title)));
    elements.title.appendChild(renderedTitle.element);
    const renderedMessage = this.B(renderer.render(typeof message === "string" ? new $bm(message) : message));
    elements.message.appendChild(renderedMessage.element);
    buttons.forEach((buttonData) => {
      const button = new $k2(elements.buttonsContainer, { ...$q$, secondary: buttonData.isSecondary });
      button.label = buttonData.label;
      this.B(button.onDidClick(() => this.a.fire(buttonData)));
    });
  }
};
$RDb = __decorate([
  __param(3, $Pk)
], $RDb);

// out-build/vs/workbench/contrib/chat/browser/chatContentParts/chatConfirmationContentPart.js
var $SDb = class $SDb2 extends $3c {
  constructor(confirmation, context, b, c, chatWidgetService) {
    super();
    this.b = b;
    this.c = c;
    this.a = this.B(new $ze());
    this.onDidChangeHeight = this.a.event;
    const element = context.element;
    const buttons = confirmation.buttons ? confirmation.buttons.map((button) => ({
      label: button,
      data: confirmation.data
    })) : [
      { label: localize(4796, null), data: confirmation.data },
      { label: localize(4797, null), data: confirmation.data, isSecondary: true }
    ];
    const confirmationWidget = this.B(this.b.createInstance($RDb, confirmation.title, confirmation.message, buttons));
    confirmationWidget.setShowButtons(!confirmation.isUsed);
    this.B(confirmationWidget.onDidClick(async (e) => {
      if ($asb(element)) {
        const prompt = `${e.label}: "${confirmation.title}"`;
        const options3 = e.isSecondary ? { rejectedConfirmationData: [e.data] } : { acceptedConfirmationData: [e.data] };
        options3.agentId = element.agent?.id;
        options3.slashCommand = element.slashCommand?.name;
        options3.confirmation = e.label;
        options3.userSelectedModelId = chatWidgetService.getWidgetBySessionId(element.sessionId)?.input.currentLanguageModel;
        if (await this.c.sendRequest(element.sessionId, prompt, options3)) {
          confirmation.isUsed = true;
          confirmationWidget.setShowButtons(false);
          this.a.fire();
        }
      }
    }));
    this.domNode = confirmationWidget.domNode;
  }
  hasSameContent(other) {
    return other.kind === "confirmation";
  }
  addDisposable(disposable) {
    this.B(disposable);
  }
};
$SDb = __decorate([
  __param(2, $Pk),
  __param(3, $qO),
  __param(4, $2Nb)
], $SDb);

// out-build/vs/workbench/contrib/scm/common/scm.js
var $_R = "workbench.view.scm";
var $aS = "workbench.scm";
var $bS = "workbench.scm.repositories";
var $cS = "workbench.scm.history";
var $dS = $Qk("scm");
var InputValidationType;
(function(InputValidationType2) {
  InputValidationType2[InputValidationType2["Error"] = 0] = "Error";
  InputValidationType2[InputValidationType2["Warning"] = 1] = "Warning";
  InputValidationType2[InputValidationType2["Information"] = 2] = "Information";
})(InputValidationType || (InputValidationType = {}));
var SCMInputChangeReason;
(function(SCMInputChangeReason2) {
  SCMInputChangeReason2[SCMInputChangeReason2["HistoryPrevious"] = 0] = "HistoryPrevious";
  SCMInputChangeReason2[SCMInputChangeReason2["HistoryNext"] = 1] = "HistoryNext";
})(SCMInputChangeReason || (SCMInputChangeReason = {}));
var ISCMRepositorySortKey;
(function(ISCMRepositorySortKey2) {
  ISCMRepositorySortKey2["DiscoveryTime"] = "discoveryTime";
  ISCMRepositorySortKey2["Name"] = "name";
  ISCMRepositorySortKey2["Path"] = "path";
})(ISCMRepositorySortKey || (ISCMRepositorySortKey = {}));
var $eS = $Qk("scmView");

// out-build/vs/editor/browser/widget/diffEditor/embeddedDiffEditorWidget.js
var $zEb = class $zEb2 extends $c_ {
  constructor(domElement, options3, codeEditorWidgetOptions, parentEditor, contextKeyService, instantiationService, codeEditorService, accessibilitySignalService, editorProgressService) {
    super(domElement, parentEditor.getRawOptions(), codeEditorWidgetOptions, contextKeyService, instantiationService, codeEditorService, accessibilitySignalService, editorProgressService);
    this.cb = parentEditor;
    this.db = options3;
    super.updateOptions(this.db);
    this.B(parentEditor.onDidChangeConfiguration((e) => this.eb(e)));
  }
  getParentEditor() {
    return this.cb;
  }
  eb(e) {
    super.updateOptions(this.cb.getRawOptions());
    super.updateOptions(this.db);
  }
  updateOptions(newOptions) {
    $Ov(this.db, newOptions, true);
    super.updateOptions(this.db);
  }
};
$zEb = __decorate([
  __param(4, $on),
  __param(5, $Pk),
  __param(6, $U5),
  __param(7, $I9),
  __param(8, $ZJ)
], $zEb);

// out-build/vs/workbench/contrib/scm/common/quickDiff.js
var $AEb = $Qk("quickDiff");

// out-build/vs/workbench/contrib/scm/browser/dirtyDiffSwitcher.js
var $BEb = class $BEb2 extends $V1 {
  constructor(action, providers2, selected, contextViewService, themeService) {
    const items = providers2.map((provider) => ({ provider, text: provider }));
    let startingSelection = providers2.indexOf(selected);
    if (startingSelection === -1) {
      startingSelection = 0;
    }
    const styles = { ...$K$ };
    const theme = themeService.getColorTheme();
    const editorBackgroundColor = theme.getColor($Ko);
    const peekTitleColor = theme.getColor($deb);
    const opaqueTitleColor = peekTitleColor?.makeOpaque(editorBackgroundColor) ?? editorBackgroundColor;
    styles.selectBackground = opaqueTitleColor.lighten(0.6).toString();
    super(null, action, items, startingSelection, contextViewService, styles, { ariaLabel: localize(9394, null) });
    this.a = items;
  }
  setSelection(provider) {
    const index = this.a.findIndex((item) => item.provider === provider);
    this.select(index);
  }
  n(_, index) {
    return this.a[index];
  }
  render(container2) {
    super.render(container2);
    this.setFocusable(true);
  }
};
$BEb = __decorate([
  __param(3, $40),
  __param(4, $gs)
], $BEb);
var $CEb = class _$CEb extends $Um {
  static {
    this.ID = "quickDiff.base.switch";
  }
  static {
    this.LABEL = localize(9395, null);
  }
  constructor(a) {
    super(_$CEb.ID, _$CEb.LABEL, void 0, void 0);
    this.a = a;
  }
  async run(event) {
    return this.a(event);
  }
};

// out-build/vs/workbench/contrib/scm/browser/dirtydiffDecorator.js
var $IEb_1;
var DirtyDiffDecorator_1;
var DiffActionRunner = class extends $Vm {
  u(action, context) {
    if (action instanceof $fJ) {
      return action.run(...context);
    }
    return super.u(action, context);
  }
};
var $DEb = new $nn("dirtyDiffVisible", false);
function getChangeHeight(change) {
  const modified = change.modifiedEndLineNumber - change.modifiedStartLineNumber + 1;
  const original = change.originalEndLineNumber - change.originalStartLineNumber + 1;
  if (change.originalEndLineNumber === 0) {
    return modified;
  } else if (change.modifiedEndLineNumber === 0) {
    return original;
  } else {
    return modified + original;
  }
}
function getModifiedEndLineNumber(change) {
  if (change.modifiedEndLineNumber === 0) {
    return change.modifiedStartLineNumber === 0 ? 1 : change.modifiedStartLineNumber;
  } else {
    return change.modifiedEndLineNumber;
  }
}
function lineIntersectsChange(lineNumber, change) {
  if (lineNumber === 1 && change.modifiedStartLineNumber === 0 && change.modifiedEndLineNumber === 0) {
    return true;
  }
  return lineNumber >= change.modifiedStartLineNumber && lineNumber <= (change.modifiedEndLineNumber || change.modifiedStartLineNumber);
}
var UIEditorAction = class UIEditorAction2 extends $Um {
  constructor(editor, action, cssClass, keybindingService, instantiationService) {
    const keybinding = keybindingService.lookupKeybinding(action.id);
    const label3 = action.label + (keybinding ? ` (${keybinding.getLabel()})` : "");
    super(action.id, label3, cssClass);
    this.g = instantiationService;
    this.f = action;
    this.c = editor;
  }
  run() {
    return Promise.resolve(this.g.invokeFunction((accessor) => this.f.run(accessor, this.c, null)));
  }
};
UIEditorAction = __decorate([
  __param(3, $Ty),
  __param(4, $Pk)
], UIEditorAction);
var ChangeType;
(function(ChangeType3) {
  ChangeType3[ChangeType3["Modify"] = 0] = "Modify";
  ChangeType3[ChangeType3["Add"] = 1] = "Add";
  ChangeType3[ChangeType3["Delete"] = 2] = "Delete";
})(ChangeType || (ChangeType = {}));
function getChangeType(change) {
  if (change.originalEndLineNumber === 0) {
    return ChangeType.Add;
  } else if (change.modifiedEndLineNumber === 0) {
    return ChangeType.Delete;
  } else {
    return ChangeType.Modify;
  }
}
function getChangeTypeColor(theme, changeType) {
  switch (changeType) {
    case ChangeType.Modify:
      return theme.getColor(editorGutterModifiedBackground);
    case ChangeType.Add:
      return theme.getColor(editorGutterAddedBackground);
    case ChangeType.Delete:
      return theme.getColor(editorGutterDeletedBackground);
  }
}
function getOuterEditorFromDiffEditor(accessor) {
  const diffEditors = accessor.get($U5).listDiffEditors();
  for (const diffEditor of diffEditors) {
    if (diffEditor.hasTextFocus() && diffEditor instanceof $zEb) {
      return diffEditor.getParentEditor();
    }
  }
  return $beb(accessor);
}
var DirtyDiffWidget = class DirtyDiffWidget2 extends $ceb {
  constructor(editor, ib, jb, instantiationService, kb, lb) {
    super(editor, { isResizeable: true, frameWidth: 1, keepEditorSelection: true, className: "dirty-diff" }, instantiationService);
    this.ib = ib;
    this.jb = jb;
    this.kb = kb;
    this.lb = lb;
    this.cb = 0;
    this.db = "";
    this.fb = void 0;
    this.n.add(jb.onDidColorThemeChange(this.wb, this));
    this.wb(jb.getColorTheme());
    if (this.ib.original.length > 0) {
      lb = lb.createOverlay([["originalResourceScheme", this.ib.original[0].uri.scheme], ["originalResourceSchemes", this.ib.original.map((original) => original.uri.scheme)]]);
    }
    this.create();
    if (editor.hasModel()) {
      this.m = $sh(editor.getModel().uri);
    } else {
      this.m = "";
    }
    this.setTitle(this.m);
  }
  get provider() {
    return this.db;
  }
  get index() {
    return this.cb;
  }
  get visibleRange() {
    const visibleRanges = this.c.getModifiedEditor().getVisibleRanges();
    return visibleRanges.length >= 0 ? visibleRanges[0] : void 0;
  }
  showChange(index, usePosition = true) {
    const labeledChange = this.ib.changes[index];
    const change = labeledChange.change;
    this.cb = index;
    this.lb.createKey("originalResourceScheme", this.ib.changes[index].uri.scheme);
    this.pb();
    this.db = labeledChange.label;
    this.eb = change;
    const originalModel = this.ib.original;
    if (!originalModel) {
      return;
    }
    const onFirstDiffUpdate = Event2.once(this.c.onDidUpdateDiff);
    onFirstDiffUpdate(() => setTimeout(() => this.vb(change), 0));
    const diffEditorModel = this.ib.getDiffEditorModel(labeledChange.uri.toString());
    if (!diffEditorModel) {
      return;
    }
    this.c.setModel(diffEditorModel);
    this.gb?.setSelection(labeledChange.label);
    const position = new $8C(getModifiedEndLineNumber(change), 1);
    const lineHeight = this.editor.getOption(
      68
      /* EditorOption.lineHeight */
    );
    const editorHeight = this.editor.getLayoutInfo().height;
    const editorHeightInLines = Math.floor(editorHeight / lineHeight);
    const height = Math.min(getChangeHeight(change) + /* padding */
    8, Math.floor(editorHeightInLines / 3));
    this.mb(labeledChange.label);
    const changeType = getChangeType(change);
    const changeTypeColor = getChangeTypeColor(this.jb.getColorTheme(), changeType);
    this.style({ frameColor: changeTypeColor, arrowColor: changeTypeColor });
    const providerSpecificChanges = [];
    let contextIndex = index;
    for (const change2 of this.ib.changes) {
      if (change2.label === this.ib.changes[this.cb].label) {
        providerSpecificChanges.push(change2.change);
        if (labeledChange === change2) {
          contextIndex = providerSpecificChanges.length - 1;
        }
      }
    }
    this.O.context = [diffEditorModel.modified.uri, providerSpecificChanges, contextIndex];
    if (usePosition) {
      this.show(position, height);
      this.editor.setPosition(position);
      this.editor.focus();
    }
  }
  mb(label3) {
    const providerChanges = this.ib.mapChanges.get(label3);
    const providerIndex = providerChanges.indexOf(this.cb);
    let detail2;
    if (!this.ob()) {
      detail2 = this.ib.changes.length > 1 ? localize(9371, null, label3, providerIndex + 1, providerChanges.length) : localize(9372, null, label3, providerIndex + 1, providerChanges.length);
      this.hb.style.display = "none";
    } else {
      detail2 = this.ib.changes.length > 1 ? localize(9373, null, providerIndex + 1, providerChanges.length) : localize(9374, null, providerIndex + 1, providerChanges.length);
      this.hb.style.display = "inherit";
    }
    this.setTitle(this.m, detail2);
  }
  nb(event) {
    const newProvider = event?.provider;
    if (newProvider === this.ib.changes[this.cb].label) {
      return;
    }
    let closestGreaterIndex = this.cb < this.ib.changes.length - 1 ? this.cb + 1 : 0;
    for (let i2 = closestGreaterIndex; i2 !== this.cb; i2 < this.ib.changes.length - 1 ? i2++ : i2 = 0) {
      if (this.ib.changes[i2].label === newProvider) {
        closestGreaterIndex = i2;
        break;
      }
    }
    let closestLesserIndex = this.cb > 0 ? this.cb - 1 : this.ib.changes.length - 1;
    for (let i2 = closestLesserIndex; i2 !== this.cb; i2 >= 0 ? i2-- : i2 = this.ib.changes.length - 1) {
      if (this.ib.changes[i2].label === newProvider) {
        closestLesserIndex = i2;
        break;
      }
    }
    const closestIndex = Math.abs(this.ib.changes[closestGreaterIndex].change.modifiedEndLineNumber - this.ib.changes[this.cb].change.modifiedEndLineNumber) < Math.abs(this.ib.changes[closestLesserIndex].change.modifiedEndLineNumber - this.ib.changes[this.cb].change.modifiedEndLineNumber) ? closestGreaterIndex : closestLesserIndex;
    this.showChange(closestIndex, false);
  }
  ob() {
    let providersWithChangesCount = 0;
    if (this.ib.mapChanges.size > 1) {
      const keys = Array.from(this.ib.mapChanges.keys());
      for (let i2 = 0; i2 < keys.length && providersWithChangesCount <= 1; i2++) {
        if (this.ib.mapChanges.get(keys[i2]).length > 0) {
          providersWithChangesCount++;
        }
      }
    }
    return providersWithChangesCount >= 2;
  }
  pb() {
    if (!this.O) {
      return;
    }
    const previous = this.Q.createInstance(UIEditorAction, this.editor, new $EEb(this.editor), ThemeIcon.asClassName($as));
    const next = this.Q.createInstance(UIEditorAction, this.editor, new $FEb(this.editor), ThemeIcon.asClassName($bs));
    this.n.add(previous);
    this.n.add(next);
    if (this.bb) {
      this.bb.dispose();
    }
    this.bb = this.kb.createMenu($bJ.SCMChangeContext, this.lb);
    const actions = $R$(this.bb.getActions({ shouldForwardArgs: true }));
    this.O.clear();
    this.O.push(actions.reverse(), { label: false, icon: true });
    this.O.push([next, previous], { label: false, icon: true });
    this.O.push(new $Um("peekview.close", localize(9375, null), ThemeIcon.asClassName($6l.close), true, () => this.dispose()), { label: false, icon: true });
  }
  T(container2) {
    super.T(container2, true);
    this.hb = $ck(this.K, $(".dropdown"));
    this.gb = this.Q.createInstance($BEb, new $CEb((event) => this.nb(event)), this.ib.quickDiffs.map((quickDiffer) => quickDiffer.label), this.ib.changes[this.cb].label);
    this.gb.render(this.hb);
    this.pb();
  }
  V() {
    const actionRunner = new DiffActionRunner();
    actionRunner.onDidRun((e) => {
      if (!(e.action instanceof UIEditorAction) && !e.error) {
        this.dispose();
      }
    });
    return {
      ...super.V(),
      actionRunner
    };
  }
  X(container2) {
    const options3 = {
      scrollBeyondLastLine: true,
      scrollbar: {
        verticalScrollbarSize: 14,
        horizontal: "auto",
        useShadows: true,
        verticalHasArrows: false,
        horizontalHasArrows: false
      },
      overviewRulerLanes: 2,
      fixedOverflowWidgets: true,
      minimap: { enabled: false },
      renderSideBySide: false,
      readOnly: false,
      renderIndicators: false,
      diffAlgorithm: "advanced",
      ignoreTrimWhitespace: false,
      stickyScroll: { enabled: false }
    };
    this.c = this.Q.createInstance($zEb, container2, options3, {}, this.editor);
    this.n.add(this.c);
  }
  C(width2) {
    if (typeof this.fb === "undefined") {
      return;
    }
    this.c.layout({ height: this.fb, width: width2 });
  }
  ab(height, width2) {
    super.ab(height, width2);
    this.c.layout({ height, width: width2 });
    if (typeof this.fb === "undefined" && this.eb) {
      this.vb(this.eb);
    }
    this.fb = height;
  }
  vb(change) {
    let start, end;
    if (change.modifiedEndLineNumber === 0) {
      start = change.modifiedStartLineNumber;
      end = change.modifiedStartLineNumber + 1;
    } else if (change.originalEndLineNumber > 0) {
      start = change.modifiedStartLineNumber - 1;
      end = change.modifiedEndLineNumber + 1;
    } else {
      start = change.modifiedStartLineNumber;
      end = change.modifiedEndLineNumber;
    }
    this.c.revealLinesInCenter(
      start,
      end,
      1
      /* ScrollType.Immediate */
    );
  }
  wb(theme) {
    const borderColor = theme.getColor($geb) || $Vn.transparent;
    this.style({
      arrowColor: borderColor,
      frameColor: borderColor,
      headerBackgroundColor: theme.getColor($deb) || $Vn.transparent,
      primaryHeadingColor: theme.getColor($eeb),
      secondaryHeadingColor: theme.getColor($feb)
    });
  }
  z(range) {
    this.editor.revealLineInCenterIfOutsideViewport(
      range.endLineNumber,
      0
      /* ScrollType.Smooth */
    );
  }
  hasFocus() {
    return this.c.hasTextFocus();
  }
  dispose() {
    super.dispose();
    this.bb?.dispose();
  }
};
DirtyDiffWidget = __decorate([
  __param(2, $gs),
  __param(3, $Pk),
  __param(4, $cJ),
  __param(5, $on)
], DirtyDiffWidget);
var $EEb = class extends $Z5 {
  constructor(h3) {
    super({
      id: "editor.action.dirtydiff.previous",
      label: localize2(9390, "Show Previous Change"),
      precondition: $Gpb.toNegated(),
      kbOpts: {
        kbExpr: EditorContextKeys.editorTextFocus,
        primary: 1024 | 512 | 61,
        weight: 100
        /* KeybindingWeight.EditorContrib */
      }
    });
    this.h = h3;
  }
  run(accessor) {
    const outerEditor = this.h ?? getOuterEditorFromDiffEditor(accessor);
    if (!outerEditor) {
      return;
    }
    const controller = $IEb.get(outerEditor);
    if (!controller) {
      return;
    }
    if (!controller.canNavigate()) {
      return;
    }
    controller.previous();
  }
};
$55($EEb);
var $FEb = class extends $Z5 {
  constructor(h3) {
    super({
      id: "editor.action.dirtydiff.next",
      label: localize2(9391, "Show Next Change"),
      precondition: $Gpb.toNegated(),
      kbOpts: {
        kbExpr: EditorContextKeys.editorTextFocus,
        primary: 512 | 61,
        weight: 100
        /* KeybindingWeight.EditorContrib */
      }
    });
    this.h = h3;
  }
  run(accessor) {
    const outerEditor = this.h ?? getOuterEditorFromDiffEditor(accessor);
    if (!outerEditor) {
      return;
    }
    const controller = $IEb.get(outerEditor);
    if (!controller) {
      return;
    }
    if (!controller.canNavigate()) {
      return;
    }
    controller.next();
  }
};
$55($FEb);
$dJ.appendMenuItem($bJ.MenubarGoMenu, {
  group: "7_change_nav",
  command: {
    id: "editor.action.dirtydiff.next",
    title: localize(9376, null)
  },
  order: 1
});
$dJ.appendMenuItem($bJ.MenubarGoMenu, {
  group: "7_change_nav",
  command: {
    id: "editor.action.dirtydiff.previous",
    title: localize(9377, null)
  },
  order: 2
});
var $GEb = class extends $Z5 {
  constructor() {
    super({
      id: "workbench.action.editor.previousChange",
      label: localize2(9392, "Go to Previous Change"),
      precondition: $Gpb.toNegated(),
      kbOpts: {
        kbExpr: EditorContextKeys.editorTextFocus,
        primary: 1024 | 512 | 63,
        weight: 100
        /* KeybindingWeight.EditorContrib */
      }
    });
  }
  async run(accessor) {
    const outerEditor = getOuterEditorFromDiffEditor(accessor);
    const accessibilitySignalService = accessor.get($I9);
    const accessibilityService = accessor.get($ND);
    const codeEditorService = accessor.get($U5);
    if (!outerEditor || !outerEditor.hasModel()) {
      return;
    }
    const controller = $IEb.get(outerEditor);
    if (!controller || !controller.modelRegistry) {
      return;
    }
    const lineNumber = outerEditor.getPosition().lineNumber;
    const model = controller.modelRegistry.getModel(outerEditor.getModel(), outerEditor);
    if (!model || model.changes.length === 0) {
      return;
    }
    const index = model.findPreviousClosestChange(lineNumber, false);
    const change = model.changes[index];
    await playAccessibilitySymbolForChange(change.change, accessibilitySignalService);
    setPositionAndSelection(change.change, outerEditor, accessibilityService, codeEditorService);
  }
};
$55($GEb);
var $HEb = class extends $Z5 {
  constructor() {
    super({
      id: "workbench.action.editor.nextChange",
      label: localize2(9393, "Go to Next Change"),
      precondition: $Gpb.toNegated(),
      kbOpts: {
        kbExpr: EditorContextKeys.editorTextFocus,
        primary: 512 | 63,
        weight: 100
        /* KeybindingWeight.EditorContrib */
      }
    });
  }
  async run(accessor) {
    const accessibilitySignalService = accessor.get($I9);
    const outerEditor = getOuterEditorFromDiffEditor(accessor);
    const accessibilityService = accessor.get($ND);
    const codeEditorService = accessor.get($U5);
    if (!outerEditor || !outerEditor.hasModel()) {
      return;
    }
    const controller = $IEb.get(outerEditor);
    if (!controller || !controller.modelRegistry) {
      return;
    }
    const lineNumber = outerEditor.getPosition().lineNumber;
    const model = controller.modelRegistry.getModel(outerEditor.getModel(), outerEditor);
    if (!model || model.changes.length === 0) {
      return;
    }
    const index = model.findNextClosestChange(lineNumber, false);
    const change = model.changes[index].change;
    await playAccessibilitySymbolForChange(change, accessibilitySignalService);
    setPositionAndSelection(change, outerEditor, accessibilityService, codeEditorService);
  }
};
function setPositionAndSelection(change, editor, accessibilityService, codeEditorService) {
  const position = new $8C(change.modifiedStartLineNumber, 1);
  editor.setPosition(position);
  editor.revealPositionInCenter(position);
  if (accessibilityService.isScreenReaderOptimized()) {
    editor.setSelection({ startLineNumber: change.modifiedStartLineNumber, startColumn: 0, endLineNumber: change.modifiedStartLineNumber, endColumn: Number.MAX_VALUE });
    codeEditorService.getActiveCodeEditor()?.writeScreenReaderContent("diff-navigation");
  }
}
async function playAccessibilitySymbolForChange(change, accessibilitySignalService) {
  const changeType = getChangeType(change);
  switch (changeType) {
    case ChangeType.Add:
      accessibilitySignalService.playSignal($N9.diffLineInserted, { allowManyInParallel: true, source: "dirtyDiffDecoration" });
      break;
    case ChangeType.Delete:
      accessibilitySignalService.playSignal($N9.diffLineDeleted, { allowManyInParallel: true, source: "dirtyDiffDecoration" });
      break;
    case ChangeType.Modify:
      accessibilitySignalService.playSignal($N9.diffLineModified, { allowManyInParallel: true, source: "dirtyDiffDecoration" });
      break;
  }
}
$55($HEb);
$0I.registerCommandAndKeybindingRule({
  id: "closeDirtyDiff",
  weight: 100 + 50,
  primary: 9,
  secondary: [
    1024 | 9
    /* KeyCode.Escape */
  ],
  when: $7m.and($DEb),
  handler: (accessor) => {
    const outerEditor = getOuterEditorFromDiffEditor(accessor);
    if (!outerEditor) {
      return;
    }
    const controller = $IEb.get(outerEditor);
    if (!controller) {
      return;
    }
    controller.close();
  }
});
var $IEb = class $IEb2 extends $3c {
  static {
    $IEb_1 = this;
  }
  static {
    this.ID = "editor.contrib.dirtydiff";
  }
  static get(editor) {
    return editor.getContribution($IEb_1.ID);
  }
  constructor(t, contextKeyService, u, w) {
    super();
    this.t = t;
    this.u = u;
    this.w = w;
    this.modelRegistry = null;
    this.c = null;
    this.f = null;
    this.h = $3c.None;
    this.j = null;
    this.m = false;
    this.n = new $2c();
    this.m = !contextKeyService.getContextKeyValue("isInDiffEditor");
    this.s = $VZ(void 0, void 0, this.q);
    if (this.m) {
      this.g = $DEb.bindTo(contextKeyService);
      this.B(t.onDidChangeModel(() => this.close()));
      const onDidChangeGutterAction = Event2.filter(u.onDidChangeConfiguration, (e) => e.affectsConfiguration("scm.diffDecorationsGutterAction"));
      this.B(onDidChangeGutterAction(this.y, this));
      this.y();
    }
  }
  y() {
    const gutterAction = this.u.getValue("scm.diffDecorationsGutterAction");
    this.n.clear();
    if (gutterAction === "diff") {
      this.n.add(this.t.onMouseDown((e) => this.D(e)));
      this.n.add(this.t.onMouseUp((e) => this.F(e)));
      this.s.textContent = `
				.monaco-editor .dirty-diff-glyph {
					cursor: pointer;
				}

				.monaco-editor .margin-view-overlays .dirty-diff-glyph:hover::before {
					height: 100%;
					width: 6px;
					left: -6px;
				}

				.monaco-editor .margin-view-overlays .dirty-diff-deleted:hover::after {
					bottom: 0;
					border-top-width: 0;
					border-bottom-width: 0;
				}
			`;
    } else {
      this.s.textContent = ``;
    }
  }
  canNavigate() {
    return !this.f || this.f?.index === -1 || !!this.c && this.c.changes.length > 1;
  }
  refresh() {
    this.f?.showChange(this.f.index, false);
  }
  next(lineNumber) {
    if (!this.z()) {
      return;
    }
    if (!this.f || !this.c) {
      return;
    }
    let index;
    if (this.t.hasModel() && (typeof lineNumber === "number" || !this.f.provider)) {
      index = this.c.findNextClosestChange(typeof lineNumber === "number" ? lineNumber : this.t.getPosition().lineNumber, true, this.f.provider);
    } else {
      const providerChanges = this.c.mapChanges.get(this.f.provider) ?? this.c.mapChanges.values().next().value;
      const mapIndex = providerChanges.findIndex((value) => value === this.f.index);
      index = providerChanges[rot(mapIndex + 1, providerChanges.length)];
    }
    this.f.showChange(index);
  }
  previous(lineNumber) {
    if (!this.z()) {
      return;
    }
    if (!this.f || !this.c) {
      return;
    }
    let index;
    if (this.t.hasModel() && typeof lineNumber === "number") {
      index = this.c.findPreviousClosestChange(typeof lineNumber === "number" ? lineNumber : this.t.getPosition().lineNumber, true, this.f.provider);
    } else {
      const providerChanges = this.c.mapChanges.get(this.f.provider) ?? this.c.mapChanges.values().next().value;
      const mapIndex = providerChanges.findIndex((value) => value === this.f.index);
      index = providerChanges[rot(mapIndex - 1, providerChanges.length)];
    }
    this.f.showChange(index);
  }
  close() {
    this.h.dispose();
    this.h = $3c.None;
  }
  z() {
    if (!this.m) {
      return false;
    }
    if (this.f) {
      if (!this.c || this.c.changes.length === 0) {
        this.close();
        return false;
      }
      return true;
    }
    if (!this.modelRegistry) {
      return false;
    }
    const editorModel = this.t.getModel();
    if (!editorModel) {
      return false;
    }
    const model = this.modelRegistry.getModel(editorModel, this.t);
    if (!model) {
      return false;
    }
    if (model.changes.length === 0) {
      return false;
    }
    this.c = model;
    this.f = this.w.createInstance(DirtyDiffWidget, this.t, model);
    this.g.set(true);
    const disposables = new $2c();
    disposables.add(Event2.once(this.f.onDidClose)(this.close, this));
    const onDidModelChange = Event2.chain(model.onDidChange, ($149) => $149.filter((e) => e.diff.length > 0).map((e) => e.diff));
    onDidModelChange(this.C, this, disposables);
    disposables.add(this.f);
    disposables.add($1c(() => {
      this.c = null;
      this.f = null;
      this.g.set(false);
      this.t.focus();
    }));
    this.h = disposables;
    return true;
  }
  C(splices) {
    if (!this.c || !this.f || this.f.hasFocus()) {
      return;
    }
    for (const splice2 of splices) {
      if (splice2.start <= this.f.index) {
        this.next();
        return;
      }
    }
    this.refresh();
  }
  D(e) {
    this.j = null;
    const range = e.target.range;
    if (!range) {
      return;
    }
    if (!e.event.leftButton) {
      return;
    }
    if (e.target.type !== 4) {
      return;
    }
    if (!e.target.element) {
      return;
    }
    if (e.target.element.className.indexOf("dirty-diff-glyph") < 0) {
      return;
    }
    const data = e.target.detail;
    const offsetLeftInGutter = e.target.element.offsetLeft;
    const gutterOffsetX = data.offsetX - offsetLeftInGutter;
    if (gutterOffsetX < -3 || gutterOffsetX > 3) {
      return;
    }
    this.j = { lineNumber: range.startLineNumber };
  }
  F(e) {
    if (!this.j) {
      return;
    }
    const { lineNumber } = this.j;
    this.j = null;
    const range = e.target.range;
    if (!range || range.startLineNumber !== lineNumber) {
      return;
    }
    if (e.target.type !== 4) {
      return;
    }
    if (!this.modelRegistry) {
      return;
    }
    const editorModel = this.t.getModel();
    if (!editorModel) {
      return;
    }
    const model = this.modelRegistry.getModel(editorModel, this.t);
    if (!model) {
      return;
    }
    const index = model.changes.findIndex((change) => lineIntersectsChange(lineNumber, change.change));
    if (index < 0) {
      return;
    }
    if (index === this.f?.index) {
      this.close();
    } else {
      this.next(lineNumber);
    }
  }
  getChanges() {
    if (!this.modelRegistry) {
      return [];
    }
    if (!this.t.hasModel()) {
      return [];
    }
    const model = this.modelRegistry.getModel(this.t.getModel(), this.t);
    if (!model) {
      return [];
    }
    return model.changes.map((change) => change.change);
  }
  dispose() {
    this.n.dispose();
    super.dispose();
  }
};
$IEb = $IEb_1 = __decorate([
  __param(1, $on),
  __param(2, $kl),
  __param(3, $Pk)
], $IEb);
var editorGutterModifiedBackground = $5n("editorGutter.modifiedBackground", {
  dark: "#1B81A8",
  light: "#2090D3",
  hcDark: "#1B81A8",
  hcLight: "#2090D3"
}, localize(9378, null));
var editorGutterAddedBackground = $5n("editorGutter.addedBackground", {
  dark: "#487E02",
  light: "#48985D",
  hcDark: "#487E02",
  hcLight: "#48985D"
}, localize(9379, null));
var editorGutterDeletedBackground = $5n("editorGutter.deletedBackground", $Vo, localize(9380, null));
var $JEb = $5n("minimapGutter.modifiedBackground", editorGutterModifiedBackground, localize(9381, null));
var $KEb = $5n("minimapGutter.addedBackground", editorGutterAddedBackground, localize(9382, null));
var $LEb = $5n("minimapGutter.deletedBackground", editorGutterDeletedBackground, localize(9383, null));
var $MEb = $5n("editorOverviewRuler.modifiedForeground", $0n(editorGutterModifiedBackground, 0.6), localize(9384, null));
var $NEb = $5n("editorOverviewRuler.addedForeground", $0n(editorGutterAddedBackground, 0.6), localize(9385, null));
var $OEb = $5n("editorOverviewRuler.deletedForeground", $0n(editorGutterDeletedBackground, 0.6), localize(9386, null));
var DirtyDiffDecorator = DirtyDiffDecorator_1 = class DirtyDiffDecorator2 extends $3c {
  static createDecoration(className, tooltip, options3) {
    const decorationOptions = {
      description: "dirty-diff-decoration",
      isWholeLine: options3.isWholeLine
    };
    if (options3.gutter) {
      decorationOptions.linesDecorationsClassName = `dirty-diff-glyph ${className}`;
      decorationOptions.linesDecorationsTooltip = tooltip;
    }
    if (options3.overview.active) {
      decorationOptions.overviewRuler = {
        color: $hs(options3.overview.color),
        position: OverviewRulerLane.Left
      };
    }
    if (options3.minimap.active) {
      decorationOptions.minimap = {
        color: $hs(options3.minimap.color),
        position: 2
        /* MinimapPosition.Gutter */
      };
    }
    return $WI.createDynamic(decorationOptions);
  }
  constructor(editorModel, s, t, u) {
    super();
    this.s = s;
    this.t = t;
    this.u = u;
    this.n = editorModel;
    const decorations = u.getValue("scm.diffDecorations");
    const gutter = decorations === "all" || decorations === "gutter";
    const overview = decorations === "all" || decorations === "overview";
    const minimap = decorations === "all" || decorations === "minimap";
    const diffAdded = localize(9387, null);
    this.c = DirtyDiffDecorator_1.createDecoration("dirty-diff-added", diffAdded, {
      gutter,
      overview: { active: overview, color: $NEb },
      minimap: { active: minimap, color: $KEb },
      isWholeLine: true
    });
    this.f = DirtyDiffDecorator_1.createDecoration("dirty-diff-added-pattern", diffAdded, {
      gutter,
      overview: { active: overview, color: $NEb },
      minimap: { active: minimap, color: $KEb },
      isWholeLine: true
    });
    const diffModified = localize(9388, null);
    this.g = DirtyDiffDecorator_1.createDecoration("dirty-diff-modified", diffModified, {
      gutter,
      overview: { active: overview, color: $MEb },
      minimap: { active: minimap, color: $JEb },
      isWholeLine: true
    });
    this.h = DirtyDiffDecorator_1.createDecoration("dirty-diff-modified-pattern", diffModified, {
      gutter,
      overview: { active: overview, color: $MEb },
      minimap: { active: minimap, color: $JEb },
      isWholeLine: true
    });
    this.j = DirtyDiffDecorator_1.createDecoration("dirty-diff-deleted", localize(9389, null), {
      gutter,
      overview: { active: overview, color: $OEb },
      minimap: { active: minimap, color: $LEb },
      isWholeLine: false
    });
    this.B(u.onDidChangeConfiguration((e) => {
      if (e.affectsConfiguration("scm.diffDecorationsGutterPattern")) {
        this.w();
      }
    }));
    this.B(t.onDidChange(this.w, this));
  }
  w() {
    if (!this.n) {
      return;
    }
    const visibleQuickDiffs = this.t.quickDiffs.filter((quickDiff) => quickDiff.visible);
    const pattern = this.u.getValue("scm.diffDecorationsGutterPattern");
    const decorations = this.t.changes.filter((labeledChange) => visibleQuickDiffs.some((quickDiff) => quickDiff.label === labeledChange.label)).map((labeledChange) => {
      const change = labeledChange.change;
      const changeType = getChangeType(change);
      const startLineNumber = change.modifiedStartLineNumber;
      const endLineNumber = change.modifiedEndLineNumber || startLineNumber;
      switch (changeType) {
        case ChangeType.Add:
          return {
            range: {
              startLineNumber,
              startColumn: 1,
              endLineNumber,
              endColumn: 1
            },
            options: pattern.added ? this.f : this.c
          };
        case ChangeType.Delete:
          return {
            range: {
              startLineNumber,
              startColumn: Number.MAX_VALUE,
              endLineNumber: startLineNumber,
              endColumn: Number.MAX_VALUE
            },
            options: this.j
          };
        case ChangeType.Modify:
          return {
            range: {
              startLineNumber,
              startColumn: 1,
              endLineNumber,
              endColumn: 1
            },
            options: pattern.modified ? this.h : this.g
          };
      }
    });
    if (!this.m) {
      this.m = this.s.createDecorationsCollection(decorations);
    } else {
      this.m.set(decorations);
    }
  }
  dispose() {
    super.dispose();
    if (this.m) {
      this.m?.clear();
    }
    this.n = null;
    this.m = void 0;
  }
};
DirtyDiffDecorator = DirtyDiffDecorator_1 = __decorate([
  __param(3, $kl)
], DirtyDiffDecorator);
function compareChanges(a, b) {
  let result = a.modifiedStartLineNumber - b.modifiedStartLineNumber;
  if (result !== 0) {
    return result;
  }
  result = a.modifiedEndLineNumber - b.modifiedEndLineNumber;
  if (result !== 0) {
    return result;
  }
  result = a.originalStartLineNumber - b.originalStartLineNumber;
  if (result !== 0) {
    return result;
  }
  return a.originalEndLineNumber - b.originalEndLineNumber;
}
async function $PEb(quickDiffService, uri, language, isSynchronized) {
  const quickDiffs = await quickDiffService.getQuickDiffs(uri, language, isSynchronized);
  return quickDiffs.length > 0 ? quickDiffs[0].originalResource : null;
}
var $QEb = class $QEb2 extends $3c {
  get original() {
    return this.g;
  }
  get changes() {
    return this.w;
  }
  get mapChanges() {
    return this.y;
  }
  constructor(textFileModel, z, C, D, F, G, H, I, J) {
    super();
    this.z = z;
    this.C = C;
    this.D = D;
    this.F = F;
    this.G = G;
    this.H = H;
    this.I = I;
    this.J = J;
    this.c = [];
    this.f = /* @__PURE__ */ new Map();
    this.g = [];
    this.j = new $Th(200);
    this.n = /* @__PURE__ */ new Set();
    this.s = this.B(new $2c());
    this.t = false;
    this.u = new $ze();
    this.onDidChange = this.u.event;
    this.w = [];
    this.y = /* @__PURE__ */ new Map();
    this.h = textFileModel;
    this.B(textFileModel.textEditorModel.onDidChangeContent(() => this.M()));
    this.B(Event2.filter(G.onDidChangeConfiguration, (e) => e.affectsConfiguration("scm.diffDecorationsIgnoreTrimWhitespace") || e.affectsConfiguration("diffEditor.ignoreTrimWhitespace"))(this.M, this));
    this.B(C.onDidAddRepository(this.L, this));
    for (const r2 of C.repositories) {
      this.L(r2);
    }
    this.B(this.h.onDidChangeEncoding(() => {
      this.j.cancel();
      this.c = [];
      this.f.clear();
      this.g = [];
      this.m = void 0;
      this.N([], /* @__PURE__ */ new Map());
      this.M();
    }));
    this.B(this.D.onDidChangeQuickDiffProviders(() => this.M()));
    this.B(this.I.onDidChangeEditingSession(() => this.M()));
    this.M();
  }
  get quickDiffs() {
    return this.c;
  }
  getQuickDiffResults() {
    return this.c.map((quickDiff) => {
      const changes = this.w.filter((change) => change.label === quickDiff.label).map((change) => change.change);
      const lineRangeMappings = $uD(changes);
      return {
        original: quickDiff.originalResource,
        modified: this.h.resource,
        changes: lineRangeMappings
      };
    });
  }
  getDiffEditorModel(originalUri) {
    if (!this.f.has(originalUri)) {
      return;
    }
    const original = this.f.get(originalUri);
    return {
      modified: this.h.textEditorModel,
      original: original.textEditorModel
    };
  }
  L(repository) {
    const disposables = new $2c();
    this.n.add(disposables);
    disposables.add($1c(() => this.n.delete(disposables)));
    disposables.add(repository.provider.onDidChangeResources(this.M, this));
    const onDidRemoveThis = Event2.filter(this.C.onDidRemoveRepository, (r2) => r2 === repository);
    disposables.add(onDidRemoveThis(() => $Xc(disposables), null));
    this.M();
  }
  M() {
    if (!this.j) {
      return;
    }
    this.j.trigger(async () => {
      const result = await this.O();
      const originalModels = Array.from(this.f.values());
      if (!result || this.t || this.h.isDisposed() || originalModels.some((originalModel) => originalModel.isDisposed())) {
        return;
      }
      if (originalModels.every((originalModel) => originalModel.textEditorModel.getValueLength() === 0)) {
        result.changes = [];
      }
      if (!result.changes) {
        result.changes = [];
      }
      this.N(result.changes, result.mapChanges);
    }).catch((err) => $gb(err));
  }
  N(changes, mapChanges) {
    const diff3 = $Ib(this.w, changes, (a, b) => compareChanges(a.change, b.change));
    this.w = changes;
    this.y = mapChanges;
    this.u.fire({ changes, diff: diff3 });
  }
  O() {
    return this.J.withProgress({ location: 3, delay: 250 }, async () => {
      const originalURIs = await this.Q();
      if (this.t || this.h.isDisposed() || originalURIs.length === 0) {
        return Promise.resolve({ changes: [], mapChanges: /* @__PURE__ */ new Map() });
      }
      const filteredToDiffable = originalURIs.filter((quickDiff) => this.F.canComputeDirtyDiff(quickDiff.originalResource, this.h.resource));
      if (filteredToDiffable.length === 0) {
        return Promise.resolve({ changes: [], mapChanges: /* @__PURE__ */ new Map() });
      }
      const ignoreTrimWhitespaceSetting = this.G.getValue("scm.diffDecorationsIgnoreTrimWhitespace");
      const ignoreTrimWhitespace = ignoreTrimWhitespaceSetting === "inherit" ? this.G.getValue("diffEditor.ignoreTrimWhitespace") : ignoreTrimWhitespaceSetting !== "false";
      const allDiffs = [];
      for (const quickDiff of filteredToDiffable) {
        const dirtyDiff = await this.P(quickDiff.originalResource, this.h.resource, ignoreTrimWhitespace);
        if (dirtyDiff) {
          for (const diff3 of dirtyDiff) {
            if (diff3) {
              allDiffs.push({ change: diff3, label: quickDiff.label, uri: quickDiff.originalResource });
            }
          }
        }
      }
      const sorted = allDiffs.sort((a, b) => compareChanges(a.change, b.change));
      const map = /* @__PURE__ */ new Map();
      for (let i2 = 0; i2 < sorted.length; i2++) {
        const label3 = sorted[i2].label;
        if (!map.has(label3)) {
          map.set(label3, []);
        }
        map.get(label3).push(i2);
      }
      return { changes: sorted, mapChanges: map };
    });
  }
  async P(original, modified, ignoreTrimWhitespace) {
    if (this.z === void 0) {
      return this.F.computeDirtyDiff(original, modified, ignoreTrimWhitespace);
    }
    const diffResult = await this.F.computeDiff(original, modified, {
      computeMoves: false,
      ignoreTrimWhitespace,
      maxComputationTimeMs: Number.MAX_SAFE_INTEGER
    }, this.z);
    if (!diffResult) {
      return null;
    }
    return $d_($c$.fromDiffResult(diffResult));
  }
  Q() {
    if (this.m) {
      return this.m;
    }
    this.m = this.R().then(async (quickDiffs) => {
      if (this.t) {
        return [];
      }
      if (quickDiffs.length === 0) {
        this.c = [];
        this.f.clear();
        this.g = [];
        return [];
      }
      if ($zb(this.c, quickDiffs, (a, b) => a.originalResource.toString() === b.originalResource.toString() && a.label === b.label)) {
        return quickDiffs;
      }
      this.s.clear();
      this.f.clear();
      this.g = [];
      this.c = quickDiffs;
      return (await Promise.all(quickDiffs.map(async (quickDiff) => {
        try {
          const ref = await this.H.createModelReference(quickDiff.originalResource);
          if (this.t) {
            ref.dispose();
            return [];
          }
          this.f.set(quickDiff.originalResource.toString(), ref.object);
          this.g.push(ref.object.textEditorModel);
          if ($eK(ref.object)) {
            const encoding = this.h.getEncoding();
            if (encoding) {
              ref.object.setEncoding(
                encoding,
                1
                /* EncodingMode.Decode */
              );
            }
          }
          this.s.add(ref);
          this.s.add(ref.object.textEditorModel.onDidChangeContent(() => this.M()));
          return quickDiff;
        } catch (error) {
          return [];
        }
      }))).flat();
    });
    return this.m.finally(() => {
      this.m = void 0;
    });
  }
  async R() {
    if (this.t) {
      return Promise.resolve([]);
    }
    const uri = this.h.resource;
    const session = this.I.currentEditingSession;
    if (session && session.getEntry(uri)?.state.get() === 0) {
      return Promise.resolve([]);
    }
    const isSynchronized = this.h.textEditorModel ? $kG(this.h.textEditorModel) : void 0;
    const quickDiffs = await this.D.getQuickDiffs(uri, this.h.getLanguageId(), isSynchronized);
    return this.z !== void 0 ? quickDiffs.filter((quickDiff) => !quickDiff.isSCM) : quickDiffs;
  }
  findNextClosestChange(lineNumber, inclusive = true, provider) {
    let preferredProvider;
    if (!provider && inclusive) {
      preferredProvider = this.quickDiffs.find((value) => value.isSCM)?.label;
    }
    const possibleChanges = [];
    for (let i2 = 0; i2 < this.changes.length; i2++) {
      if (provider && this.changes[i2].label !== provider) {
        continue;
      }
      const change = this.changes[i2];
      const possibleChangesLength = possibleChanges.length;
      if (inclusive) {
        if (getModifiedEndLineNumber(change.change) >= lineNumber) {
          if (preferredProvider && change.label !== preferredProvider) {
            possibleChanges.push(i2);
          } else {
            return i2;
          }
        }
      } else {
        if (change.change.modifiedStartLineNumber > lineNumber) {
          return i2;
        }
      }
      if (possibleChanges.length > 0 && possibleChanges.length === possibleChangesLength) {
        return possibleChanges[0];
      }
    }
    return possibleChanges.length > 0 ? possibleChanges[0] : 0;
  }
  findPreviousClosestChange(lineNumber, inclusive = true, provider) {
    for (let i2 = this.changes.length - 1; i2 >= 0; i2--) {
      if (provider && this.changes[i2].label !== provider) {
        continue;
      }
      const change = this.changes[i2].change;
      if (inclusive) {
        if (change.modifiedStartLineNumber <= lineNumber) {
          return i2;
        }
      } else {
        if (getModifiedEndLineNumber(change) < lineNumber) {
          return i2;
        }
      }
    }
    return this.changes.length - 1;
  }
  dispose() {
    super.dispose();
    this.t = true;
    this.c = [];
    this.f.clear();
    this.g = [];
    this.j.cancel();
    this.n.forEach((d) => $Xc(d));
    this.n.clear();
  }
};
$QEb = __decorate([
  __param(2, $dS),
  __param(3, $AEb),
  __param(4, $I0),
  __param(5, $kl),
  __param(6, $oG),
  __param(7, $$O),
  __param(8, $TJ)
], $QEb);
var DirtyDiffItem = class {
  constructor(model, decorator) {
    this.model = model;
    this.decorator = decorator;
  }
  dispose() {
    this.decorator.dispose();
    this.model.dispose();
  }
};
var $REb = class $REb2 extends $3c {
  constructor(m, n, s, t) {
    super();
    this.m = m;
    this.n = n;
    this.s = s;
    this.t = t;
    this.c = false;
    this.f = { width: 3, visibility: "always" };
    this.g = new $Ec();
    this.h = this.B(new $2c());
    this.j = $VZ(void 0, void 0, this.q);
    const onDidChangeConfiguration = Event2.filter(s.onDidChangeConfiguration, (e) => e.affectsConfiguration("scm.diffDecorations"));
    this.B(onDidChangeConfiguration(this.u, this));
    this.u();
    const onDidChangeDiffWidthConfiguration = Event2.filter(s.onDidChangeConfiguration, (e) => e.affectsConfiguration("scm.diffDecorationsGutterWidth"));
    this.B(onDidChangeDiffWidthConfiguration(this.w, this));
    this.w();
    const onDidChangeDiffVisibilityConfiguration = Event2.filter(s.onDidChangeConfiguration, (e) => e.affectsConfiguration("scm.diffDecorationsGutterVisibility"));
    this.B(onDidChangeDiffVisibilityConfiguration(this.y, this));
    this.y();
  }
  u() {
    const enabled = this.s.getValue("scm.diffDecorations") !== "none";
    if (enabled) {
      this.C();
    } else {
      this.D();
    }
  }
  w() {
    let width2 = this.s.getValue("scm.diffDecorationsGutterWidth");
    if (isNaN(width2) || width2 <= 0 || width2 > 5) {
      width2 = 3;
    }
    this.z({ ...this.f, width: width2 });
  }
  y() {
    const visibility = this.s.getValue("scm.diffDecorationsGutterVisibility");
    this.z({ ...this.f, visibility });
  }
  z(state) {
    this.f = state;
    this.j.textContent = `
			.monaco-editor .dirty-diff-added,
			.monaco-editor .dirty-diff-modified {
				border-left-width:${state.width}px;
			}
			.monaco-editor .dirty-diff-added-pattern,
			.monaco-editor .dirty-diff-added-pattern:before,
			.monaco-editor .dirty-diff-modified-pattern,
			.monaco-editor .dirty-diff-modified-pattern:before {
				background-size: ${state.width}px ${state.width}px;
			}
			.monaco-editor .dirty-diff-added,
			.monaco-editor .dirty-diff-added-pattern,
			.monaco-editor .dirty-diff-modified,
			.monaco-editor .dirty-diff-modified-pattern,
			.monaco-editor .dirty-diff-deleted {
				opacity: ${state.visibility === "always" ? 1 : 0};
			}
		`;
  }
  C() {
    if (this.c) {
      this.D();
    }
    this.h.add(Event2.any(this.m.onDidCloseEditor, this.m.onDidVisibleEditorsChange)(() => this.F()));
    this.F();
    this.c = true;
  }
  D() {
    if (!this.c) {
      return;
    }
    this.h.clear();
    for (const [, dirtyDiff] of this.g) {
      $Xc(dirtyDiff.values());
    }
    this.g.clear();
    this.c = false;
  }
  F() {
    for (const editor of this.m.visibleTextEditorControls) {
      if ($P5(editor)) {
        const textModel = editor.getModel();
        const controller = $IEb.get(editor);
        if (controller) {
          controller.modelRegistry = this;
        }
        if (textModel && (!this.g.has(textModel.uri) || !this.g.get(textModel.uri).has(editor.getId()))) {
          const textFileModel = this.t.files.get(textModel.uri);
          if (textFileModel?.isResolved()) {
            const dirtyDiffModel = this.n.createInstance($QEb, textFileModel, void 0);
            const decorator = new DirtyDiffDecorator(textFileModel.textEditorModel, editor, dirtyDiffModel, this.s);
            if (!this.g.has(textModel.uri)) {
              this.g.set(textModel.uri, /* @__PURE__ */ new Map());
            }
            this.g.get(textModel.uri)?.set(editor.getId(), new DirtyDiffItem(dirtyDiffModel, decorator));
          }
        }
      }
    }
    for (const [uri, item] of this.g) {
      for (const editorId of item.keys()) {
        if (!this.m.visibleTextEditorControls.find((editor) => $P5(editor) && editor.getModel()?.uri.toString() === uri.toString() && editor.getId() === editorId)) {
          if (item.has(editorId)) {
            const dirtyDiffItem = item.get(editorId);
            dirtyDiffItem?.dispose();
            item.delete(editorId);
            if (item.size === 0) {
              this.g.delete(uri);
            }
          }
        }
      }
    }
  }
  getModel(editorModel, codeEditor) {
    return this.g.get(editorModel.uri)?.get(codeEditor.getId())?.model;
  }
  dispose() {
    this.D();
    super.dispose();
  }
};
$REb = __decorate([
  __param(0, $mJ),
  __param(1, $Pk),
  __param(2, $kl),
  __param(3, $cK)
], $REb);
$85(
  $IEb.ID,
  $IEb,
  1
  /* EditorContributionInstantiation.AfterFirstRender */
);

// out-build/vs/workbench/contrib/notebook/browser/diff/diffCellEditorOptions.js
var fixedEditorPaddingSingleLineCells = {
  top: 24,
  bottom: 24
};
var fixedEditorPadding = {
  top: 12,
  bottom: 12
};
function $WDb(lineCount) {
  return lineCount === 1 ? fixedEditorPaddingSingleLineCells : fixedEditorPadding;
}
var $XDb = {
  padding: fixedEditorPadding,
  scrollBeyondLastLine: false,
  scrollbar: {
    verticalScrollbarSize: 14,
    horizontal: "auto",
    vertical: "auto",
    useShadows: true,
    verticalHasArrows: false,
    horizontalHasArrows: false,
    alwaysConsumeMouseWheel: false
  },
  renderLineHighlightOnlyWhenFocus: true,
  overviewRulerLanes: 0,
  overviewRulerBorder: false,
  selectOnLineNumbers: false,
  wordWrap: "off",
  lineNumbers: "off",
  glyphMargin: true,
  fixedOverflowWidgets: true,
  minimap: { enabled: false },
  renderValidationDecorations: "on",
  renderLineHighlight: "none",
  readOnly: true
};
var $YDb = {
  ...$XDb,
  glyphMargin: true,
  enableSplitViewResizing: false,
  renderIndicators: true,
  renderMarginRevertIcon: false,
  readOnly: false,
  isInEmbeddedEditor: true,
  renderOverviewRuler: false,
  wordWrap: "off",
  diffWordWrap: "off",
  diffAlgorithm: "advanced",
  renderSideBySide: true,
  useInlineViewWhenSpaceIsLimited: false
};

// out-build/vs/workbench/contrib/notebook/browser/viewModel/cellOutputViewModel.js
var handle = 0;
var $_Db = class extends $3c {
  setVisible(visible = true, force = false) {
    if (!visible && this.b) {
      return;
    }
    if (force && visible) {
      this.b = true;
    }
    this.visible.set(visible, void 0);
  }
  get model() {
    return this.f;
  }
  get pickedMimeType() {
    return this.c;
  }
  set pickedMimeType(value) {
    this.c = value;
  }
  constructor(cellViewModel, f, g) {
    super();
    this.cellViewModel = cellViewModel;
    this.f = f;
    this.g = g;
    this.a = this.B(new $ze());
    this.onDidResetRenderer = this.a.event;
    this.b = false;
    this.visible = $he("outputVisible", false);
    this.outputHandle = handle++;
  }
  hasMultiMimeType() {
    if (this.f.outputs.length < 2) {
      return false;
    }
    const firstMimeType = this.f.outputs[0].mime;
    return this.f.outputs.some((output) => output.mime !== firstMimeType);
  }
  resolveMimeTypes(textModel, kernelProvides) {
    const mimeTypes = this.g.getOutputMimeTypeInfo(textModel, kernelProvides, this.model);
    const index = mimeTypes.findIndex((mimeType) => mimeType.rendererId !== $kM && mimeType.isTrusted);
    return [mimeTypes, Math.max(index, 0)];
  }
  resetRenderer() {
    this.c = void 0;
    this.model.bumpVersion();
    this.a.fire();
  }
  toRawJSON() {
    return {
      outputs: this.f.outputs
      // TODO@rebronix, no id, right?
    };
  }
};

// out-build/vs/workbench/contrib/notebook/browser/diff/diffNestedCellViewModel.js
var $aEb = class $aEb2 extends $3c {
  get id() {
    return this.a;
  }
  get outputs() {
    return this.textModel.outputs;
  }
  get language() {
    return this.textModel.language;
  }
  get metadata() {
    return this.textModel.metadata;
  }
  get uri() {
    return this.textModel.uri;
  }
  get handle() {
    return this.textModel.handle;
  }
  get outputIsHovered() {
    return this.c;
  }
  set outputIsHovered(v) {
    this.c = v;
    this.b.fire({ outputIsHoveredChanged: true });
  }
  get outputIsFocused() {
    return this.f;
  }
  set outputIsFocused(v) {
    this.f = v;
    this.b.fire({ outputIsFocusedChanged: true });
  }
  get inputInOutputIsFocused() {
    return this.g;
  }
  set inputInOutputIsFocused(v) {
    this.g = v;
  }
  get outputsViewModels() {
    return this.h;
  }
  constructor(textModel, r2) {
    super();
    this.textModel = textModel;
    this.r = r2;
    this.b = this.B(new $ze());
    this.c = false;
    this.f = false;
    this.g = false;
    this.j = [];
    this.m = null;
    this.n = this.B(new $ze());
    this.onDidChangeOutputLayout = this.n.event;
    this.a = $ps();
    this.h = this.textModel.outputs.map((output) => new $_Db(this, output, this.r));
    this.B(this.textModel.onDidChangeOutputs((splice2) => {
      this.j.splice(splice2.start, splice2.deleteCount, ...splice2.newOutputs.map(() => 0));
      const removed = this.h.splice(splice2.start, splice2.deleteCount, ...splice2.newOutputs.map((output) => new $_Db(this, output, this.r)));
      removed.forEach((vm) => vm.dispose());
      this.m = null;
      this.n.fire();
    }));
    this.j = new Array(this.textModel.outputs.length);
  }
  s() {
    if (!this.m) {
      const values = new Uint32Array(this.j.length);
      for (let i2 = 0; i2 < this.j.length; i2++) {
        values[i2] = this.j[i2];
      }
      this.m = new $wM(values);
    }
  }
  getOutputOffset(index) {
    this.s();
    if (index >= this.j.length) {
      throw new Error("Output index out of range!");
    }
    return this.m.getPrefixSum(index - 1);
  }
  updateOutputHeight(index, height) {
    if (index >= this.j.length) {
      throw new Error("Output index out of range!");
    }
    this.s();
    this.j[index] = height;
    if (this.m.setValue(index, height)) {
      this.n.fire();
    }
  }
  getOutputTotalHeight() {
    this.s();
    return this.m?.getTotalSum() ?? 0;
  }
  dispose() {
    super.dispose();
    this.h.forEach((output) => {
      output.dispose();
    });
  }
};
$aEb = __decorate([
  __param(1, $mrb)
], $aEb);

// out-build/vs/workbench/contrib/notebook/browser/diff/eventDispatcher.js
var NotebookDiffViewEventType;
(function(NotebookDiffViewEventType2) {
  NotebookDiffViewEventType2[NotebookDiffViewEventType2["LayoutChanged"] = 1] = "LayoutChanged";
  NotebookDiffViewEventType2[NotebookDiffViewEventType2["CellLayoutChanged"] = 2] = "CellLayoutChanged";
})(NotebookDiffViewEventType || (NotebookDiffViewEventType = {}));
var $bEb = class {
  constructor(source, value) {
    this.source = source;
    this.value = value;
    this.type = NotebookDiffViewEventType.LayoutChanged;
  }
};
var $dEb = class extends $3c {
  constructor() {
    super(...arguments);
    this.a = this.B(new $ze());
    this.onDidChangeLayout = this.a.event;
    this.b = this.B(new $ze());
    this.onDidChangeCellLayout = this.b.event;
  }
  emit(events) {
    for (let i2 = 0, len = events.length; i2 < len; i2++) {
      const e = events[i2];
      switch (e.type) {
        case NotebookDiffViewEventType.LayoutChanged:
          this.a.fire(e);
          break;
        case NotebookDiffViewEventType.CellLayoutChanged:
          this.b.fire(e);
          break;
      }
    }
  }
};

// out-build/vs/workbench/contrib/notebook/browser/diff/notebookDiffEditorBrowser.js
var DiffSide;
(function(DiffSide2) {
  DiffSide2[DiffSide2["Original"] = 0] = "Original";
  DiffSide2[DiffSide2["Modified"] = 1] = "Modified";
})(DiffSide || (DiffSide = {}));
var $ZDb = 16;
var $1Db = new $nn("notebook.diffEditor.cell.inputChanged", false);
var $2Db = new $nn("notebook.diffEditor.metadataChanged", false);
var $3Db = "notebook.diffEditor.cell.ignoreWhitespace";
var $4Db = new $nn($3Db, false);
var $5Db = new $nn("notebook.diffEditor.cell.property.changed", false);
var $6Db = new $nn("notebook.diffEditor.cell.property.expanded", false);
var $7Db = new $nn("notebook.diffEditor.allCollapsed", void 0, localize(8391, null));
var $8Db = new $nn("notebook.diffEditor.hasUnchangedCells", void 0, localize(8392, null));
var $9Db = new $nn("notebook.diffEditor.unchangedCellsAreHidden", void 0, localize(8393, null));
var $0Db = new $nn("notebook.diffEditor.item.kind", void 0, localize(8394, null));
var $$Db = new $nn("notebook.diffEditor.item.state", void 0, localize(8395, null));

// out-build/vs/workbench/contrib/notebook/common/model/notebookCellOutputTextModel.js
var $rL = class extends $3c {
  get outputs() {
    return this.f.outputs || [];
  }
  get metadata() {
    return this.f.metadata;
  }
  get outputId() {
    return this.f.outputId;
  }
  get alternativeOutputId() {
    return this.b;
  }
  get versionId() {
    return this.c;
  }
  constructor(f) {
    super();
    this.f = f;
    this.a = this.B(new $ze());
    this.onDidChangeData = this.a.event;
    this.c = 0;
    this.h = {};
    this.b = this.f.outputId;
  }
  replaceData(rawData) {
    this.h = {};
    this.f = rawData;
    this.j();
    this.c = this.c + 1;
    this.a.fire();
  }
  appendData(items) {
    this.g();
    this.f.outputs.push(...items);
    this.j();
    this.c = this.c + 1;
    this.a.fire();
  }
  g() {
    this.outputs.forEach((output) => {
      if ($tM(output.mime)) {
        if (!this.h[output.mime]) {
          this.h[output.mime] = {};
        }
        this.h[output.mime][this.versionId] = output.data.byteLength;
      }
    });
  }
  appendedSinceVersion(versionId, mime) {
    const bufferLength = this.h[mime]?.[versionId];
    const output = this.outputs.find((output2) => output2.mime === mime);
    if (bufferLength && output) {
      return output.data.slice(bufferLength);
    }
    return void 0;
  }
  j() {
    if (this.outputs.length > 1 && this.outputs.every((item) => $tM(item.mime))) {
      const mimeOutputs = /* @__PURE__ */ new Map();
      const mimeTypes = [];
      this.outputs.forEach((item) => {
        let items;
        if (mimeOutputs.has(item.mime)) {
          items = mimeOutputs.get(item.mime);
        } else {
          items = [];
          mimeOutputs.set(item.mime, items);
          mimeTypes.push(item.mime);
        }
        items.push(item.data.buffer);
      });
      this.outputs.length = 0;
      mimeTypes.forEach((mime) => {
        const compressionResult = $uM(mimeOutputs.get(mime));
        this.outputs.push({
          mime,
          data: compressionResult.data
        });
        if (compressionResult.didCompression) {
          this.h = {};
        }
      });
    }
  }
  asDto() {
    return {
      // data: this._data,
      metadata: this.f.metadata,
      outputs: this.f.outputs,
      outputId: this.f.outputId
    };
  }
  bumpVersion() {
    this.c = this.c + 1;
  }
};

// out-build/vs/workbench/contrib/notebook/common/model/notebookCellTextModel.js
var $sL = class _$sL extends $3c {
  get outputs() {
    return this.n;
  }
  get metadata() {
    return this.s;
  }
  set metadata(newMetadata) {
    this.s = newMetadata;
    this.y = null;
    this.g.fire();
  }
  get internalMetadata() {
    return this.t;
  }
  set internalMetadata(newInternalMetadata) {
    const lastRunSuccessChanged = this.t.lastRunSuccess !== newInternalMetadata.lastRunSuccess;
    newInternalMetadata = {
      ...newInternalMetadata,
      ...{ runStartTimeAdjustment: computeRunStartTimeAdjustment(this.t, newInternalMetadata) }
    };
    this.t = newInternalMetadata;
    this.y = null;
    this.h.fire({ lastRunSuccessChanged });
  }
  get language() {
    return this.N;
  }
  set language(newLanguage) {
    if (this.F && this.F.getLanguageId() === this.P.getLanguageIdByLanguageName(newLanguage) && this.F.getLanguageId() === this.P.getLanguageIdByLanguageName(this.language)) {
      return;
    }
    this.L = true;
    this.U(newLanguage);
  }
  get mime() {
    return this.O;
  }
  set mime(newMime) {
    if (this.O === newMime) {
      return;
    }
    this.O = newMime;
    this.y = null;
    this.f.fire("mime");
  }
  get textBuffer() {
    if (this.u) {
      return this.u;
    }
    this.u = this.B($PI(
      this.M,
      1
      /* model.DefaultEndOfLine.LF */
    ).textBuffer);
    this.B(this.u.onDidChangeContent(() => {
      this.y = null;
      if (!this.F) {
        this.f.fire("content");
      }
      this.autoDetectLanguage();
    }));
    return this.u;
  }
  get alternativeId() {
    return this.C;
  }
  get textModel() {
    return this.F;
  }
  set textModel(m) {
    if (this.F === m) {
      return;
    }
    this.D.clear();
    this.F = m;
    if (this.F) {
      this.G(this.P, this.F.getLanguageId(), this.language);
      this.D.add(this.F.onDidChangeLanguage((e) => this.G(this.P, e.newLanguage, this.language)));
      this.D.add(this.F.onWillDispose(() => this.textModel = void 0));
      this.D.add(this.F.onDidChangeContent((e) => {
        if (this.F) {
          this.z = this.F.getVersionId();
          this.C = this.F.getAlternativeVersionId();
        }
        this.w = null;
        this.f.fire("content");
        this.f.fire({ type: "model", event: e });
      }));
      this.F._overwriteVersionId(this.z);
      this.F._overwriteAlternativeVersionId(this.z);
    }
  }
  G(languageService, newLanguage, currentLanguage) {
    const isFallBackLanguage = newLanguage === $KF || newLanguage === "jupyter";
    if (!languageService.isRegisteredLanguageId(currentLanguage) && isFallBackLanguage) {
      this.j.fire(currentLanguage);
    } else {
      this.language = newLanguage;
    }
  }
  static {
    this.H = 600;
  }
  get hasLanguageSetExplicitly() {
    return this.L;
  }
  constructor(uri, handle2, M, N, O, cellKind, outputs, metadata, internalMetadata, collapseState, transientOptions, P, Q = void 0) {
    super();
    this.uri = uri;
    this.handle = handle2;
    this.M = M;
    this.N = N;
    this.O = O;
    this.cellKind = cellKind;
    this.collapseState = collapseState;
    this.transientOptions = transientOptions;
    this.P = P;
    this.Q = Q;
    this.a = this.B(new $ze());
    this.onDidChangeOutputs = this.a.event;
    this.c = this.B(new $ze());
    this.onDidChangeOutputItems = this.c.event;
    this.f = this.B(new $ze());
    this.onDidChangeContent = this.f.event;
    this.g = this.B(new $ze());
    this.onDidChangeMetadata = this.g.event;
    this.h = this.B(new $ze());
    this.onDidChangeInternalMetadata = this.h.event;
    this.j = this.B(new $ze());
    this.onDidChangeLanguage = this.j.event;
    this.w = null;
    this.y = null;
    this.z = 1;
    this.C = 1;
    this.D = this.B(new $2c());
    this.F = void 0;
    this.I = this.B(new $Th(_$sL.H));
    this.J = false;
    this.L = false;
    this.n = outputs.map((op) => new $rL(op));
    this.s = metadata ?? {};
    this.t = internalMetadata ?? {};
  }
  enableAutoLanguageDetection() {
    this.J = true;
    this.autoDetectLanguage();
  }
  async autoDetectLanguage() {
    if (this.J) {
      this.I.trigger(() => this.S());
    }
  }
  async S() {
    if (this.hasLanguageSetExplicitly) {
      return;
    }
    const newLanguage = await this.Q?.detectLanguage(this.uri);
    if (!newLanguage) {
      return;
    }
    if (this.F && this.F.getLanguageId() === this.P.getLanguageIdByLanguageName(newLanguage) && this.F.getLanguageId() === this.P.getLanguageIdByLanguageName(this.language)) {
      return;
    }
    this.U(newLanguage);
  }
  U(newLanguage) {
    const newLanguageId = this.P.getLanguageIdByLanguageName(newLanguage);
    if (newLanguageId === null) {
      return;
    }
    if (this.F) {
      const languageId = this.P.createById(newLanguageId);
      this.F.setLanguage(languageId.languageId);
    }
    if (this.N === newLanguage) {
      return;
    }
    this.N = newLanguage;
    this.y = null;
    this.j.fire(newLanguage);
    this.f.fire("language");
  }
  resetTextBuffer(textBuffer) {
    this.u = textBuffer;
  }
  getValue() {
    const fullRange = this.getFullModelRange();
    const eol = this.textBuffer.getEOL();
    if (eol === "\n") {
      return this.textBuffer.getValueInRange(
        fullRange,
        1
        /* model.EndOfLinePreference.LF */
      );
    } else {
      return this.textBuffer.getValueInRange(
        fullRange,
        2
        /* model.EndOfLinePreference.CRLF */
      );
    }
  }
  getTextBufferHash() {
    if (this.w !== null) {
      return this.w;
    }
    const shaComputer = new $3i();
    const snapshot = this.textBuffer.createSnapshot(false);
    let text2;
    while (text2 = snapshot.read()) {
      shaComputer.update(text2);
    }
    this.w = shaComputer.digest();
    return this.w;
  }
  getHashValue() {
    if (this.y !== null) {
      return this.y;
    }
    this.y = $Xi([$Xi(this.language), this.getTextBufferHash(), this.W(), this.transientOptions.transientOutputs ? [] : this.n.map((op) => ({
      outputs: op.outputs.map((output) => ({
        mime: output.mime,
        data: Array.from(output.data.buffer)
      })),
      metadata: op.metadata
    }))]);
    return this.y;
  }
  W() {
    return $uL(this.transientOptions.transientCellMetadata, this.metadata, this.language);
  }
  getTextLength() {
    return this.textBuffer.getLength();
  }
  getFullModelRange() {
    const lineCount = this.textBuffer.getLineCount();
    return new $9C(1, 1, lineCount, this.textBuffer.getLineLength(lineCount) + 1);
  }
  spliceNotebookCellOutputs(splice2) {
    if (splice2.deleteCount > 0 && splice2.newOutputs.length > 0) {
      const commonLen = Math.min(splice2.deleteCount, splice2.newOutputs.length);
      for (let i2 = 0; i2 < commonLen; i2++) {
        const currentOutput = this.outputs[splice2.start + i2];
        const newOutput = splice2.newOutputs[i2];
        this.replaceOutput(currentOutput.outputId, newOutput);
      }
      const removed = this.outputs.splice(splice2.start + commonLen, splice2.deleteCount - commonLen, ...splice2.newOutputs.slice(commonLen));
      removed.forEach((output) => output.dispose());
      this.a.fire({ start: splice2.start + commonLen, deleteCount: splice2.deleteCount - commonLen, newOutputs: splice2.newOutputs.slice(commonLen) });
    } else {
      const removed = this.outputs.splice(splice2.start, splice2.deleteCount, ...splice2.newOutputs);
      removed.forEach((output) => output.dispose());
      this.a.fire(splice2);
    }
  }
  replaceOutput(outputId, newOutputItem) {
    const outputIndex = this.outputs.findIndex((output2) => output2.outputId === outputId);
    if (outputIndex < 0) {
      return false;
    }
    const output = this.outputs[outputIndex];
    output.replaceData({
      outputs: newOutputItem.outputs,
      outputId: newOutputItem.outputId,
      metadata: newOutputItem.metadata
    });
    newOutputItem.dispose();
    this.c.fire();
    return true;
  }
  changeOutputItems(outputId, append2, items) {
    const outputIndex = this.outputs.findIndex((output2) => output2.outputId === outputId);
    if (outputIndex < 0) {
      return false;
    }
    const output = this.outputs[outputIndex];
    if (append2) {
      output.appendData(items);
    } else {
      output.replaceData({ outputId, outputs: items, metadata: output.metadata });
    }
    this.c.fire();
    return true;
  }
  X(left, right) {
    if (left.length !== right.length) {
      return false;
    }
    for (let i2 = 0; i2 < this.outputs.length; i2++) {
      const l = left[i2];
      const r2 = right[i2];
      if (l.outputs.length !== r2.outputs.length) {
        return false;
      }
      for (let k = 0; k < l.outputs.length; k++) {
        if (l.outputs[k].mime !== r2.outputs[k].mime) {
          return false;
        }
        if (l.outputs[k].data.byteLength !== r2.outputs[k].data.byteLength) {
          return false;
        }
      }
    }
    return true;
  }
  equal(b) {
    if (this.language !== b.language) {
      return false;
    }
    if (this.outputs.length !== b.outputs.length) {
      return false;
    }
    if (this.getTextLength() !== b.getTextLength()) {
      return false;
    }
    if (!this.transientOptions.transientOutputs) {
      if (!this.X(this.outputs, b.outputs)) {
        return false;
      }
    }
    return this.getHashValue() === b.getHashValue();
  }
  /**
   * Only compares
   * - language
   * - mime
   * - cellKind
   * - internal metadata (conditionally)
   * - source
   */
  fastEqual(b, ignoreMetadata) {
    if (this.language !== b.language) {
      return false;
    }
    if (this.mime !== b.mime) {
      return false;
    }
    if (this.cellKind !== b.cellKind) {
      return false;
    }
    if (!ignoreMetadata) {
      if (this.internalMetadata?.executionOrder !== b.internalMetadata?.executionOrder || this.internalMetadata?.lastRunSuccess !== b.internalMetadata?.lastRunSuccess || this.internalMetadata?.runStartTime !== b.internalMetadata?.runStartTime || this.internalMetadata?.runStartTimeAdjustment !== b.internalMetadata?.runStartTimeAdjustment || this.internalMetadata?.runEndTime !== b.internalMetadata?.runEndTime) {
        return false;
      }
    }
    if (this.u) {
      if (!_$sL.Y(this.textBuffer.getLinesContent(), b.source)) {
        return false;
      }
    } else if (this.M !== b.source) {
      return false;
    }
    return true;
  }
  static Y(aLines, b) {
    const bLines = $Mf(b);
    if (aLines.length !== bLines.length) {
      return false;
    }
    for (let i2 = 0; i2 < aLines.length; i2++) {
      if (aLines[i2] !== bLines[i2]) {
        return false;
      }
    }
    return true;
  }
  dispose() {
    $Xc(this.n);
    const emptyDisposedTextBuffer = new $qI([], "", "\n", false, false, true, true);
    emptyDisposedTextBuffer.dispose();
    this.u = emptyDisposedTextBuffer;
    super.dispose();
  }
};
function $tL(cell) {
  return {
    source: cell.getValue(),
    language: cell.language,
    mime: cell.mime,
    cellKind: cell.cellKind,
    outputs: cell.outputs.map((output) => ({
      outputs: output.outputs,
      /* paste should generate new outputId */
      outputId: $ps()
    })),
    metadata: {}
  };
}
function computeRunStartTimeAdjustment(oldMetadata, newMetadata) {
  if (oldMetadata.runStartTime !== newMetadata.runStartTime && typeof newMetadata.runStartTime === "number") {
    const offset = Date.now() - newMetadata.runStartTime;
    return offset < 0 ? Math.abs(offset) : 0;
  } else {
    return newMetadata.runStartTimeAdjustment;
  }
}
function $uL(transientCellMetadata, metadata, language) {
  let filteredMetadata = {};
  if (transientCellMetadata) {
    const keys = /* @__PURE__ */ new Set([...Object.keys(metadata)]);
    for (const key2 of keys) {
      if (!transientCellMetadata[key2]) {
        filteredMetadata[key2] = metadata[key2];
      }
    }
  } else {
    filteredMetadata = metadata;
  }
  const obj = {
    language,
    ...filteredMetadata
  };
  if (language) {
    obj.language = language;
  }
  const metadataSource = $Tw(obj, {});
  return metadataSource;
}

// out-build/vs/workbench/contrib/notebook/common/model/notebookMetadataTextModel.js
function $fEb(transientMetadata, metadata) {
  let filteredMetadata = {};
  if (transientMetadata) {
    const keys = /* @__PURE__ */ new Set([...Object.keys(metadata)]);
    for (const key2 of keys) {
      if (!transientMetadata[key2]) {
        filteredMetadata[key2] = metadata[key2];
      }
    }
  } else {
    filteredMetadata = metadata;
  }
  const metadataSource = $Tw(filteredMetadata, {});
  return metadataSource;
}
var $gEb = class extends $3c {
  get metadata() {
    return this.notebookModel.metadata;
  }
  get textBuffer() {
    if (this.c) {
      return this.c;
    }
    const source = $fEb(this.notebookModel.transientOptions.transientDocumentMetadata, this.metadata);
    this.c = this.B($PI(
      source,
      1
      /* DefaultEndOfLine.LF */
    ).textBuffer);
    this.B(this.c.onDidChangeContent(() => {
      this.a.fire();
    }));
    return this.c;
  }
  constructor(notebookModel) {
    super();
    this.notebookModel = notebookModel;
    this.a = this.B(new $ze());
    this.onDidChange = this.a.event;
    this.b = null;
    this.uri = NotebookMetadataUri.generate(this.notebookModel.uri);
    this.B(this.notebookModel.onDidChangeContent((e) => {
      if (e.rawEvents.some((event) => event.kind === NotebookCellsChangeType.ChangeDocumentMetadata || event.kind === NotebookCellsChangeType.ModelChange)) {
        this.c?.dispose();
        this.c = void 0;
        this.b = null;
        this.a.fire();
      }
    }));
  }
  getHash() {
    if (this.b !== null) {
      return this.b;
    }
    const shaComputer = new $3i();
    const snapshot = this.textBuffer.createSnapshot(false);
    let text2;
    while (text2 = snapshot.read()) {
      shaComputer.update(text2);
    }
    this.b = shaComputer.digest();
    return this.b;
  }
  getValue() {
    const fullRange = this.f();
    const eol = this.textBuffer.getEOL();
    if (eol === "\n") {
      return this.textBuffer.getValueInRange(
        fullRange,
        1
        /* EndOfLinePreference.LF */
      );
    } else {
      return this.textBuffer.getValueInRange(
        fullRange,
        2
        /* EndOfLinePreference.CRLF */
      );
    }
  }
  f() {
    const lineCount = this.textBuffer.getLineCount();
    return new $9C(1, 1, lineCount, this.textBuffer.getLineLength(lineCount) + 1);
  }
};

// out-build/vs/workbench/contrib/notebook/browser/diff/diffElementViewModel.js
var PropertyHeaderHeight = 25;
var $hEb = 24;
var $iEb = 17;
var PropertyFoldingState;
(function(PropertyFoldingState2) {
  PropertyFoldingState2[PropertyFoldingState2["Expanded"] = 0] = "Expanded";
  PropertyFoldingState2[PropertyFoldingState2["Collapsed"] = 1] = "Collapsed";
})(PropertyFoldingState || (PropertyFoldingState = {}));
var $jEb = 1440;
var $kEb = class extends $3c {
  constructor(mainDocumentTextModel, editorEventDispatcher, initData) {
    super();
    this.mainDocumentTextModel = mainDocumentTextModel;
    this.editorEventDispatcher = editorEventDispatcher;
    this.initData = initData;
    this.c = this.B(new $ze());
    this.onDidLayoutChange = this.c.event;
    this.B(this.editorEventDispatcher.onDidChangeLayout((e) => this.c.fire({ outerWidth: true })));
  }
};
var $lEb = class extends $kEb {
  constructor(mainDocumentTextModel, editorEventDispatcher, initData) {
    super(mainDocumentTextModel, editorEventDispatcher, initData);
    this.type = "placeholder";
    this.hiddenCells = [];
    this.f = this.B(new $ze());
    this.onUnfoldHiddenCells = this.f.event;
    this.renderOutput = false;
  }
  get totalHeight() {
    return 24 + 2 * $ZDb;
  }
  getHeight(_) {
    return this.totalHeight;
  }
  layoutChange() {
  }
  showHiddenCells() {
    this.f.fire();
  }
};
var $mEb = class extends $kEb {
  set editorHeight(height) {
    this.m({ editorHeight: height });
  }
  get editorHeight() {
    throw new Error("Use Cell.layoutInfo.editorHeight");
  }
  set editorMargin(margin) {
    this.m({ editorMargin: margin });
  }
  get editorMargin() {
    throw new Error("Use Cell.layoutInfo.editorMargin");
  }
  get layoutInfo() {
    return this.f;
  }
  get totalHeight() {
    return this.layoutInfo.totalHeight;
  }
  constructor(originalDocumentTextModel, modifiedDocumentTextModel, type, editorEventDispatcher, initData, notebookService, h3) {
    super(originalDocumentTextModel, editorEventDispatcher, initData);
    this.originalDocumentTextModel = originalDocumentTextModel;
    this.modifiedDocumentTextModel = modifiedDocumentTextModel;
    this.type = type;
    this.h = h3;
    this.renderOutput = false;
    this.g = null;
    const cellStatusHeight = PropertyHeaderHeight;
    this.f = {
      width: 0,
      editorHeight: 0,
      editorMargin: 0,
      metadataHeight: 0,
      cellStatusHeight,
      metadataStatusHeight: 0,
      rawOutputHeight: 0,
      outputTotalHeight: 0,
      outputStatusHeight: 0,
      outputMetadataHeight: 0,
      bodyMargin: 32,
      totalHeight: 82 + cellStatusHeight + 0,
      layoutState: CellLayoutState.Uninitialized
    };
    this.cellFoldingState = type === "modifiedMetadata" ? PropertyFoldingState.Expanded : PropertyFoldingState.Collapsed;
    this.originalMetadata = this.B(new $gEb(originalDocumentTextModel));
    this.modifiedMetadata = this.B(new $gEb(modifiedDocumentTextModel));
  }
  async computeHeights() {
    if (this.type === "unchangedMetadata") {
      this.editorHeight = this.h.computeHeightFromLines(this.originalMetadata.textBuffer.getLineCount());
    } else {
      const original = this.originalMetadata.uri;
      const modified = this.modifiedMetadata.uri;
      this.editorHeight = await this.h.diffAndComputeHeight(original, modified);
    }
  }
  layoutChange() {
    this.m({ recomputeOutput: true });
  }
  m(delta) {
    const width2 = delta.width !== void 0 ? delta.width : this.f.width;
    const editorHeight = delta.editorHeight !== void 0 ? delta.editorHeight : this.f.editorHeight;
    const editorMargin = delta.editorMargin !== void 0 ? delta.editorMargin : this.f.editorMargin;
    const cellStatusHeight = delta.cellStatusHeight !== void 0 ? delta.cellStatusHeight : this.f.cellStatusHeight;
    const bodyMargin = delta.bodyMargin !== void 0 ? delta.bodyMargin : this.f.bodyMargin;
    const totalHeight = editorHeight + editorMargin + cellStatusHeight + bodyMargin;
    const newLayout = {
      width: width2,
      editorHeight,
      editorMargin,
      metadataHeight: 0,
      cellStatusHeight,
      metadataStatusHeight: 0,
      outputTotalHeight: 0,
      outputStatusHeight: 0,
      bodyMargin,
      rawOutputHeight: 0,
      outputMetadataHeight: 0,
      totalHeight,
      layoutState: CellLayoutState.Measured
    };
    let somethingChanged = false;
    const changeEvent = {};
    if (newLayout.width !== this.f.width) {
      changeEvent.width = true;
      somethingChanged = true;
    }
    if (newLayout.editorHeight !== this.f.editorHeight) {
      changeEvent.editorHeight = true;
      somethingChanged = true;
    }
    if (newLayout.editorMargin !== this.f.editorMargin) {
      changeEvent.editorMargin = true;
      somethingChanged = true;
    }
    if (newLayout.cellStatusHeight !== this.f.cellStatusHeight) {
      changeEvent.cellStatusHeight = true;
      somethingChanged = true;
    }
    if (newLayout.bodyMargin !== this.f.bodyMargin) {
      changeEvent.bodyMargin = true;
      somethingChanged = true;
    }
    if (newLayout.totalHeight !== this.f.totalHeight) {
      changeEvent.totalHeight = true;
      somethingChanged = true;
    }
    if (somethingChanged) {
      this.f = newLayout;
      this.r(changeEvent);
    }
  }
  getHeight(lineHeight) {
    if (this.f.layoutState === CellLayoutState.Uninitialized) {
      const editorHeight = this.cellFoldingState === PropertyFoldingState.Collapsed ? 0 : this.computeInputEditorHeight(lineHeight);
      return this.n(editorHeight);
    } else {
      return this.f.totalHeight;
    }
  }
  n(editorHeight) {
    const totalHeight = editorHeight + this.f.editorMargin + this.f.metadataHeight + this.f.cellStatusHeight + this.f.metadataStatusHeight + this.f.outputTotalHeight + this.f.outputStatusHeight + this.f.outputMetadataHeight + this.f.bodyMargin;
    return totalHeight;
  }
  computeInputEditorHeight(_lineHeight) {
    return this.h.computeHeightFromLines(Math.max(this.originalMetadata.textBuffer.getLineCount(), this.modifiedMetadata.textBuffer.getLineCount()));
  }
  r(state) {
    this.c.fire(state);
    this.editorEventDispatcher.emit([{ type: NotebookDiffViewEventType.CellLayoutChanged, source: this.f }]);
  }
  getComputedCellContainerWidth(layoutInfo, diffEditor, fullWidth) {
    if (fullWidth) {
      return layoutInfo.width - 2 * $ZDb + (diffEditor ? $c_.ENTIRE_DIFF_OVERVIEW_WIDTH : 0) - 2;
    }
    return (layoutInfo.width - 2 * $ZDb + (diffEditor ? $c_.ENTIRE_DIFF_OVERVIEW_WIDTH : 0)) / 2 - 18 - 2;
  }
  getSourceEditorViewState() {
    return this.g;
  }
  saveSpirceEditorViewState(viewState) {
    this.g = viewState;
  }
};
var $nEb = class extends $kEb {
  hideUnchangedCells() {
    this.h.fire();
  }
  set rawOutputHeight(height) {
    this.z({ rawOutputHeight: Math.min($jEb, height) });
  }
  get rawOutputHeight() {
    throw new Error("Use Cell.layoutInfo.rawOutputHeight");
  }
  set outputStatusHeight(height) {
    this.z({ outputStatusHeight: height });
  }
  get outputStatusHeight() {
    throw new Error("Use Cell.layoutInfo.outputStatusHeight");
  }
  set outputMetadataHeight(height) {
    this.z({ outputMetadataHeight: height });
  }
  get outputMetadataHeight() {
    throw new Error("Use Cell.layoutInfo.outputStatusHeight");
  }
  set editorHeight(height) {
    this.z({ editorHeight: height });
  }
  get editorHeight() {
    throw new Error("Use Cell.layoutInfo.editorHeight");
  }
  set editorMargin(margin) {
    this.z({ editorMargin: margin });
  }
  get editorMargin() {
    throw new Error("Use Cell.layoutInfo.editorMargin");
  }
  set metadataStatusHeight(height) {
    this.z({ metadataStatusHeight: height });
  }
  get metadataStatusHeight() {
    throw new Error("Use Cell.layoutInfo.outputStatusHeight");
  }
  set metadataHeight(height) {
    this.z({ metadataHeight: height });
  }
  get metadataHeight() {
    throw new Error("Use Cell.layoutInfo.metadataHeight");
  }
  set renderOutput(value) {
    this.m = value;
    this.z({ recomputeOutput: true });
    this.f.fire({ renderOutput: this.m });
  }
  get renderOutput() {
    return this.m;
  }
  get layoutInfo() {
    return this.g;
  }
  get totalHeight() {
    return this.layoutInfo.totalHeight;
  }
  get n() {
    return this.w.getValue("notebook.diff.ignoreOutputs") || !!this.mainDocumentTextModel?.transientOptions.transientOutputs;
  }
  get r() {
    return this.w.getValue("notebook.diff.ignoreMetadata");
  }
  constructor(mainDocumentTextModel, original, modified, type, editorEventDispatcher, initData, notebookService, index, w, diffEditorHeightCalculator) {
    super(mainDocumentTextModel, editorEventDispatcher, initData);
    this.type = type;
    this.index = index;
    this.w = w;
    this.diffEditorHeightCalculator = diffEditorHeightCalculator;
    this.f = this.B(new $ze());
    this.onDidStateChange = this.f.event;
    this.h = this.B(new $ze());
    this.onHideUnchangedCells = this.h.event;
    this.m = true;
    this.s = null;
    this.t = null;
    this.u = null;
    this.original = original ? this.B(new $aEb(original, notebookService)) : void 0;
    this.modified = modified ? this.B(new $aEb(modified, notebookService)) : void 0;
    const editorHeight = this.y(initData.fontInfo);
    const cellStatusHeight = PropertyHeaderHeight;
    this.g = {
      width: 0,
      editorHeight,
      editorMargin: 0,
      metadataHeight: 0,
      cellStatusHeight,
      metadataStatusHeight: this.r ? 0 : PropertyHeaderHeight,
      rawOutputHeight: 0,
      outputTotalHeight: 0,
      outputStatusHeight: this.n ? 0 : PropertyHeaderHeight,
      outputMetadataHeight: 0,
      bodyMargin: 32,
      totalHeight: 82 + cellStatusHeight + editorHeight,
      layoutState: CellLayoutState.Uninitialized
    };
    this.cellFoldingState = modified?.getTextBufferHash() !== original?.getTextBufferHash() ? PropertyFoldingState.Expanded : PropertyFoldingState.Collapsed;
    this.metadataFoldingState = PropertyFoldingState.Collapsed;
    this.outputFoldingState = PropertyFoldingState.Collapsed;
  }
  layoutChange() {
    this.z({ recomputeOutput: true });
  }
  y(fontInfo) {
    const lineHeight = fontInfo?.lineHeight ?? 17;
    switch (this.type) {
      case "unchanged":
      case "insert": {
        const lineCount = this.modified.textModel.textBuffer.getLineCount();
        const editorHeight = lineCount * lineHeight + $WDb(lineCount).top + $WDb(lineCount).bottom;
        return editorHeight;
      }
      case "delete":
      case "modified": {
        const lineCount = this.original.textModel.textBuffer.getLineCount();
        const editorHeight = lineCount * lineHeight + $WDb(lineCount).top + $WDb(lineCount).bottom;
        return editorHeight;
      }
    }
  }
  z(delta) {
    const width2 = delta.width !== void 0 ? delta.width : this.g.width;
    const editorHeight = delta.editorHeight !== void 0 ? delta.editorHeight : this.g.editorHeight;
    const editorMargin = delta.editorMargin !== void 0 ? delta.editorMargin : this.g.editorMargin;
    const metadataHeight = delta.metadataHeight !== void 0 ? delta.metadataHeight : this.g.metadataHeight;
    const cellStatusHeight = delta.cellStatusHeight !== void 0 ? delta.cellStatusHeight : this.g.cellStatusHeight;
    const metadataStatusHeight = delta.metadataStatusHeight !== void 0 ? delta.metadataStatusHeight : this.g.metadataStatusHeight;
    const rawOutputHeight = delta.rawOutputHeight !== void 0 ? delta.rawOutputHeight : this.g.rawOutputHeight;
    const outputStatusHeight = delta.outputStatusHeight !== void 0 ? delta.outputStatusHeight : this.g.outputStatusHeight;
    const bodyMargin = delta.bodyMargin !== void 0 ? delta.bodyMargin : this.g.bodyMargin;
    const outputMetadataHeight = delta.outputMetadataHeight !== void 0 ? delta.outputMetadataHeight : this.g.outputMetadataHeight;
    const outputHeight = this.n ? 0 : delta.recomputeOutput || delta.rawOutputHeight !== void 0 || delta.outputMetadataHeight !== void 0 ? this.D(rawOutputHeight, outputMetadataHeight) : this.g.outputTotalHeight;
    const totalHeight = editorHeight + editorMargin + cellStatusHeight + metadataHeight + metadataStatusHeight + outputHeight + outputStatusHeight + bodyMargin;
    const newLayout = {
      width: width2,
      editorHeight,
      editorMargin,
      metadataHeight,
      cellStatusHeight,
      metadataStatusHeight,
      outputTotalHeight: outputHeight,
      outputStatusHeight,
      bodyMargin,
      rawOutputHeight,
      outputMetadataHeight,
      totalHeight,
      layoutState: CellLayoutState.Measured
    };
    let somethingChanged = false;
    const changeEvent = {};
    if (newLayout.width !== this.g.width) {
      changeEvent.width = true;
      somethingChanged = true;
    }
    if (newLayout.editorHeight !== this.g.editorHeight) {
      changeEvent.editorHeight = true;
      somethingChanged = true;
    }
    if (newLayout.editorMargin !== this.g.editorMargin) {
      changeEvent.editorMargin = true;
      somethingChanged = true;
    }
    if (newLayout.metadataHeight !== this.g.metadataHeight) {
      changeEvent.metadataHeight = true;
      somethingChanged = true;
    }
    if (newLayout.cellStatusHeight !== this.g.cellStatusHeight) {
      changeEvent.cellStatusHeight = true;
      somethingChanged = true;
    }
    if (newLayout.metadataStatusHeight !== this.g.metadataStatusHeight) {
      changeEvent.metadataStatusHeight = true;
      somethingChanged = true;
    }
    if (newLayout.outputTotalHeight !== this.g.outputTotalHeight) {
      changeEvent.outputTotalHeight = true;
      somethingChanged = true;
    }
    if (newLayout.outputStatusHeight !== this.g.outputStatusHeight) {
      changeEvent.outputStatusHeight = true;
      somethingChanged = true;
    }
    if (newLayout.bodyMargin !== this.g.bodyMargin) {
      changeEvent.bodyMargin = true;
      somethingChanged = true;
    }
    if (newLayout.outputMetadataHeight !== this.g.outputMetadataHeight) {
      changeEvent.outputMetadataHeight = true;
      somethingChanged = true;
    }
    if (newLayout.totalHeight !== this.g.totalHeight) {
      changeEvent.totalHeight = true;
      somethingChanged = true;
    }
    if (somethingChanged) {
      this.g = newLayout;
      this.F(changeEvent);
    }
  }
  getHeight(lineHeight) {
    if (this.g.layoutState === CellLayoutState.Uninitialized) {
      const editorHeight = this.cellFoldingState === PropertyFoldingState.Collapsed ? 0 : this.computeInputEditorHeight(lineHeight);
      return this.C(editorHeight);
    } else {
      return this.g.totalHeight;
    }
  }
  C(editorHeight) {
    const totalHeight = editorHeight + this.g.editorMargin + this.g.metadataHeight + this.g.cellStatusHeight + this.g.metadataStatusHeight + this.g.outputTotalHeight + this.g.outputStatusHeight + this.g.outputMetadataHeight + this.g.bodyMargin;
    return totalHeight;
  }
  computeInputEditorHeight(lineHeight) {
    const lineCount = Math.max(this.original?.textModel.textBuffer.getLineCount() ?? 1, this.modified?.textModel.textBuffer.getLineCount() ?? 1);
    return this.diffEditorHeightCalculator.computeHeightFromLines(lineCount);
  }
  D(rawOutputHeight, metadataHeight) {
    if (this.outputFoldingState === PropertyFoldingState.Collapsed) {
      return 0;
    }
    if (this.renderOutput) {
      if (this.isOutputEmpty()) {
        return 24;
      }
      return this.getRichOutputTotalHeight() + metadataHeight;
    } else {
      return rawOutputHeight;
    }
  }
  F(state) {
    this.c.fire(state);
    this.editorEventDispatcher.emit([{ type: NotebookDiffViewEventType.CellLayoutChanged, source: this.g }]);
  }
  getComputedCellContainerWidth(layoutInfo, diffEditor, fullWidth) {
    if (fullWidth) {
      return layoutInfo.width - 2 * $ZDb + (diffEditor ? $c_.ENTIRE_DIFF_OVERVIEW_WIDTH : 0) - 2;
    }
    return (layoutInfo.width - 2 * $ZDb + (diffEditor ? $c_.ENTIRE_DIFF_OVERVIEW_WIDTH : 0)) / 2 - 18 - 2;
  }
  getOutputEditorViewState() {
    return this.t;
  }
  saveOutputEditorViewState(viewState) {
    this.t = viewState;
  }
  getMetadataEditorViewState() {
    return this.u;
  }
  saveMetadataEditorViewState(viewState) {
    this.u = viewState;
  }
  getSourceEditorViewState() {
    return this.s;
  }
  saveSpirceEditorViewState(viewState) {
    this.s = viewState;
  }
};
var $oEb = class extends $nEb {
  get originalDocument() {
    return this.otherDocumentTextModel;
  }
  get modifiedDocument() {
    return this.mainDocumentTextModel;
  }
  constructor(mainDocumentTextModel, otherDocumentTextModel, original, modified, type, editorEventDispatcher, initData, notebookService, configurationService, index, diffEditorHeightCalculator) {
    super(mainDocumentTextModel, original, modified, type, editorEventDispatcher, initData, notebookService, index, configurationService, diffEditorHeightCalculator);
    this.otherDocumentTextModel = otherDocumentTextModel;
    this.type = type;
    this.cellFoldingState = this.modified.textModel.getValue() !== this.original.textModel.getValue() ? PropertyFoldingState.Expanded : PropertyFoldingState.Collapsed;
    this.metadataFoldingState = PropertyFoldingState.Collapsed;
    this.outputFoldingState = PropertyFoldingState.Collapsed;
    if (this.checkMetadataIfModified()) {
      this.metadataFoldingState = PropertyFoldingState.Expanded;
    }
    if (this.checkIfOutputsModified()) {
      this.outputFoldingState = PropertyFoldingState.Expanded;
    }
    this.B(this.original.onDidChangeOutputLayout(() => {
      this.z({ recomputeOutput: true });
    }));
    this.B(this.modified.onDidChangeOutputLayout(() => {
      this.z({ recomputeOutput: true });
    }));
    this.B(this.modified.textModel.onDidChangeContent(() => {
      if (mainDocumentTextModel.transientOptions.cellContentMetadata) {
        const cellMetadataKeys = [...Object.keys(mainDocumentTextModel.transientOptions.cellContentMetadata)];
        const modifiedMedataRaw = Object.assign({}, this.modified.metadata);
        const originalCellMetadata = this.original.metadata;
        for (const key2 of cellMetadataKeys) {
          if (key2 in originalCellMetadata) {
            modifiedMedataRaw[key2] = originalCellMetadata[key2];
          }
        }
        this.modified.textModel.metadata = modifiedMedataRaw;
      }
    }));
  }
  checkIfInputModified() {
    if (this.original.textModel.getTextBufferHash() === this.modified.textModel.getTextBufferHash()) {
      return false;
    }
    return {
      reason: "Cell content has changed"
    };
  }
  checkIfOutputsModified() {
    if (this.mainDocumentTextModel.transientOptions.transientOutputs || this.n) {
      return false;
    }
    const ret = outputsEqual(this.original?.outputs ?? [], this.modified?.outputs ?? []);
    if (ret === 0) {
      return false;
    }
    return {
      reason: ret === 1 ? "Output metadata has changed" : void 0,
      kind: ret
    };
  }
  checkMetadataIfModified() {
    if (this.r) {
      return false;
    }
    const modified = $Xi($uL(this.mainDocumentTextModel.transientOptions.transientCellMetadata, this.original?.metadata || {}, this.original?.language)) !== $Xi($uL(this.mainDocumentTextModel.transientOptions.transientCellMetadata, this.modified?.metadata ?? {}, this.modified?.language));
    if (modified) {
      return { reason: void 0 };
    } else {
      return false;
    }
  }
  updateOutputHeight(diffSide, index, height) {
    if (diffSide === DiffSide.Original) {
      this.original.updateOutputHeight(index, height);
    } else {
      this.modified.updateOutputHeight(index, height);
    }
  }
  getOutputOffsetInContainer(diffSide, index) {
    if (diffSide === DiffSide.Original) {
      return this.original.getOutputOffset(index);
    } else {
      return this.modified.getOutputOffset(index);
    }
  }
  getOutputOffsetInCell(diffSide, index) {
    const offsetInOutputsContainer = this.getOutputOffsetInContainer(diffSide, index);
    return this.g.editorHeight + this.g.editorMargin + this.g.metadataHeight + this.g.cellStatusHeight + this.g.metadataStatusHeight + this.g.outputStatusHeight + this.g.bodyMargin / 2 + offsetInOutputsContainer;
  }
  isOutputEmpty() {
    if (this.mainDocumentTextModel.transientOptions.transientOutputs) {
      return true;
    }
    if (this.checkIfOutputsModified()) {
      return false;
    }
    return (this.original?.outputs || []).length === 0;
  }
  getRichOutputTotalHeight() {
    return Math.max(this.original.getOutputTotalHeight(), this.modified.getOutputTotalHeight());
  }
  getNestedCellViewModel(diffSide) {
    return diffSide === DiffSide.Original ? this.original : this.modified;
  }
  getCellByUri(cellUri) {
    if (cellUri.toString() === this.original.uri.toString()) {
      return this.original;
    } else {
      return this.modified;
    }
  }
  computeInputEditorHeight(lineHeight) {
    if (this.type === "modified" && typeof this.G === "number" && this.checkIfInputModified()) {
      return this.G;
    }
    return super.computeInputEditorHeight(lineHeight);
  }
  async H() {
    if (this.checkIfInputModified()) {
      this.G = this.g.editorHeight = await this.diffEditorHeightCalculator.diffAndComputeHeight(this.original.uri, this.modified.uri);
    }
  }
  async I() {
    if (this.checkMetadataIfModified()) {
      const originalMetadataUri = CellUri.generateCellPropertyUri(this.originalDocument.uri, this.original.handle, Schemas.vscodeNotebookCellMetadata);
      const modifiedMetadataUri = CellUri.generateCellPropertyUri(this.modifiedDocument.uri, this.modified.handle, Schemas.vscodeNotebookCellMetadata);
      this.g.metadataHeight = await this.diffEditorHeightCalculator.diffAndComputeHeight(originalMetadataUri, modifiedMetadataUri);
    }
  }
  async computeEditorHeights() {
    if (this.type === "unchanged") {
      return;
    }
    await Promise.all([this.H(), this.I()]);
  }
};
var $pEb = class extends $nEb {
  get cellViewModel() {
    return this.type === "insert" ? this.modified : this.original;
  }
  get originalDocument() {
    if (this.type === "insert") {
      return this.otherDocumentTextModel;
    } else {
      return this.mainDocumentTextModel;
    }
  }
  get modifiedDocument() {
    if (this.type === "insert") {
      return this.mainDocumentTextModel;
    } else {
      return this.otherDocumentTextModel;
    }
  }
  constructor(mainDocumentTextModel, otherDocumentTextModel, original, modified, type, editorEventDispatcher, initData, notebookService, configurationService, diffEditorHeightCalculator, index) {
    super(mainDocumentTextModel, original, modified, type, editorEventDispatcher, initData, notebookService, index, configurationService, diffEditorHeightCalculator);
    this.otherDocumentTextModel = otherDocumentTextModel;
    this.type = type;
    this.B(this.cellViewModel.onDidChangeOutputLayout(() => {
      this.z({ recomputeOutput: true });
    }));
  }
  checkIfInputModified() {
    return {
      reason: "Cell content has changed"
    };
  }
  getNestedCellViewModel(diffSide) {
    return this.type === "insert" ? this.modified : this.original;
  }
  checkIfOutputsModified() {
    return false;
  }
  checkMetadataIfModified() {
    return false;
  }
  updateOutputHeight(diffSide, index, height) {
    this.cellViewModel?.updateOutputHeight(index, height);
  }
  getOutputOffsetInContainer(diffSide, index) {
    return this.cellViewModel.getOutputOffset(index);
  }
  getOutputOffsetInCell(diffSide, index) {
    const offsetInOutputsContainer = this.cellViewModel.getOutputOffset(index);
    return this.g.editorHeight + this.g.editorMargin + this.g.metadataHeight + this.g.cellStatusHeight + this.g.metadataStatusHeight + this.g.outputStatusHeight + this.g.bodyMargin / 2 + offsetInOutputsContainer;
  }
  isOutputEmpty() {
    if (this.mainDocumentTextModel.transientOptions.transientOutputs) {
      return true;
    }
    return (this.original?.outputs || this.modified?.outputs || []).length === 0;
  }
  getRichOutputTotalHeight() {
    return this.cellViewModel?.getOutputTotalHeight() ?? 0;
  }
  getCellByUri(cellUri) {
    return this.cellViewModel;
  }
};
var OutputComparison;
(function(OutputComparison2) {
  OutputComparison2[OutputComparison2["Unchanged"] = 0] = "Unchanged";
  OutputComparison2[OutputComparison2["Metadata"] = 1] = "Metadata";
  OutputComparison2[OutputComparison2["Other"] = 2] = "Other";
})(OutputComparison || (OutputComparison = {}));
function $qEb(a, b) {
  if ($Xi(a.metadata) === $Xi(b.metadata)) {
    return 2;
  }
  for (let j = 0; j < a.outputs.length; j++) {
    const aOutputItem = a.outputs[j];
    const bOutputItem = b.outputs[j];
    if (aOutputItem.mime !== bOutputItem.mime) {
      return 2;
    }
    if (aOutputItem.data.buffer.length !== bOutputItem.data.buffer.length) {
      return 2;
    }
    for (let k = 0; k < aOutputItem.data.buffer.length; k++) {
      if (aOutputItem.data.buffer[k] !== bOutputItem.data.buffer[k]) {
        return 2;
      }
    }
  }
  return 1;
}
function outputsEqual(original, modified) {
  if (original.length !== modified.length) {
    return 2;
  }
  const len = original.length;
  for (let i2 = 0; i2 < len; i2++) {
    const a = original[i2];
    const b = modified[i2];
    if ($Xi(a.metadata) !== $Xi(b.metadata)) {
      return 1;
    }
    if (a.outputs.length !== b.outputs.length) {
      return 2;
    }
    for (let j = 0; j < a.outputs.length; j++) {
      const aOutputItem = a.outputs[j];
      const bOutputItem = b.outputs[j];
      if (aOutputItem.mime !== bOutputItem.mime) {
        return 2;
      }
      if (aOutputItem.data.buffer.length !== bOutputItem.data.buffer.length) {
        return 2;
      }
      for (let k = 0; k < aOutputItem.data.buffer.length; k++) {
        if (aOutputItem.data.buffer[k] !== bOutputItem.data.buffer[k]) {
          return 2;
        }
      }
    }
  }
  return 0;
}
function $rEb(outputs) {
  if (!outputs.length) {
    return null;
  }
  const first = outputs[0];
  const mime = first.mime;
  const sameStream = !outputs.find((op) => op.mime !== mime);
  if (sameStream) {
    return outputs.map((opit) => opit.data.toString()).join("");
  } else {
    return null;
  }
}
function $sEb(outputs) {
  if (outputs.length === 1) {
    const streamOutputData = $rEb(outputs[0].outputs);
    if (streamOutputData) {
      return streamOutputData;
    }
  }
  return JSON.stringify(outputs.map((output) => {
    return {
      metadata: output.metadata,
      outputItems: output.outputs.map((opit) => ({
        mimeType: opit.mime,
        data: opit.data.toString()
      }))
    };
  }), void 0, "	");
}

// out-build/vs/workbench/contrib/notebook/browser/contrib/chatEdit/notebookOriginalCellModelFactory.js
var $SEb = $Qk("INotebookOriginalCellModelFactory");
var $TEb = class $TEb2 extends $8c {
  constructor(f, g) {
    super();
    this.f = f;
    this.g = g;
  }
  b(_key, uri, cellValue, language, cellKind) {
    const scheme = `${uri.scheme}-chat-edit`;
    const originalCellUri = URI.from({ scheme, fragment: uri.fragment, path: uri.path });
    const languageSelection = this.g.getLanguageIdByLanguageName(language) ? this.g.createById(language) : cellKind === CellKind.Markup ? this.g.createById("markdown") : null;
    return this.f.createModel(cellValue, languageSelection, originalCellUri);
  }
  c(_key, model) {
    model.dispose();
  }
};
$TEb = __decorate([
  __param(0, $sG),
  __param(1, $1E)
], $TEb);
var $UEb = class $UEb2 {
  constructor(instantiationService) {
    this.a = instantiationService.createInstance($TEb);
  }
  getOrCreate(uri, cellValue, language, cellKind) {
    return this.a.acquire(uri.toString(), uri, cellValue, language, cellKind);
  }
};
$UEb = __decorate([
  __param(0, $Pk)
], $UEb);

// out-build/vs/workbench/contrib/notebook/browser/contrib/chatEdit/notebookCellDecorators.js
var $VEb = class $VEb2 extends $2c {
  constructor(notebookEditor, modifiedCell, originalCell, q, s, t) {
    super();
    this.modifiedCell = modifiedCell;
    this.originalCell = originalCell;
    this.q = q;
    this.s = s;
    this.t = t;
    this.h = [];
    this.j = new $Th(50);
    this.n = this.add(new $2c());
    const onDidChangeVisibleRanges = $Dd(notebookEditor.onDidChangeVisibleRanges, () => notebookEditor.visibleRanges);
    const editorObs = $2d((r2) => {
      const visibleRanges = onDidChangeVisibleRanges.read(r2);
      const visibleCellHandles = visibleRanges.map((range) => notebookEditor.getCellsInRange(range)).flat().map((c) => c.handle);
      if (!visibleCellHandles.includes(modifiedCell.handle)) {
        return;
      }
      const editor = notebookEditor.codeEditors.find((item) => item[0].handle === modifiedCell.handle)?.[1];
      if (editor?.getModel() !== this.modifiedCell.textModel) {
        return;
      }
      return editor;
    });
    this.add($xd((r2, store) => {
      const editor = editorObs.read(r2);
      this.n.clear();
      if (editor) {
        store.add(editor.onDidChangeModel(() => {
          this.n.clear();
        }));
        store.add(editor.onDidChangeModelContent(() => {
          this.update(editor);
        }));
        store.add(editor.onDidChangeConfiguration((e) => {
          if (e.hasChanged(
            52
            /* EditorOption.fontInfo */
          ) || e.hasChanged(
            68
            /* EditorOption.lineHeight */
          )) {
            this.update(editor);
          }
        }));
        this.update(editor);
      }
    }));
    const shouldBeReadOnly = $2d(this, (r2) => {
      const editor = editorObs.read(r2);
      if (!editor) {
        return false;
      }
      const value = this.q.currentEditingSessionObs.read(r2);
      if (!value || value.state.read(r2) !== 1) {
        return false;
      }
      return value.entries.read(r2).some((e) => $oh(e.modifiedURI, editor.getModel()?.uri));
    });
    let actualReadonly;
    let actualDeco;
    this.add($td((r2) => {
      const editor = editorObs.read(r2);
      if (!editor) {
        return;
      }
      const value = shouldBeReadOnly.read(r2);
      if (value) {
        actualReadonly ??= editor.getOption(
          96
          /* EditorOption.readOnly */
        );
        actualDeco ??= editor.getOption(
          103
          /* EditorOption.renderValidationDecorations */
        );
        editor.updateOptions({
          readOnly: true,
          renderValidationDecorations: "off"
        });
      } else {
        if (actualReadonly !== void 0 && actualDeco !== void 0) {
          editor.updateOptions({
            readOnly: actualReadonly,
            renderValidationDecorations: actualDeco
          });
          actualReadonly = void 0;
          actualDeco = void 0;
        }
      }
    }));
  }
  update(editor) {
    this.j.trigger(() => this.u(editor));
  }
  async u(editor) {
    if (this.isDisposed) {
      return;
    }
    if (editor.getOption(
      63
      /* EditorOption.inDiffEditor */
    )) {
      this.n.clear();
      return;
    }
    const model = editor.getModel();
    if (!model || model !== this.modifiedCell.textModel) {
      this.n.clear();
      return;
    }
    const originalModel = this.y(editor);
    if (!originalModel) {
      this.n.clear();
      return;
    }
    const version2 = model.getVersionId();
    const diff3 = await this.s.computeDiff(originalModel.uri, model.uri, { computeMoves: true, ignoreTrimWhitespace: false, maxComputationTimeMs: Number.MAX_SAFE_INTEGER }, "advanced");
    if (this.isDisposed) {
      return;
    }
    if (diff3 && !diff3.identical && originalModel && model === editor.getModel() && editor.getModel()?.getVersionId() === version2) {
      this.z(editor, originalModel, diff3);
    } else {
      this.n.clear();
    }
  }
  y(editor) {
    if (!this.w) {
      const model = editor.getModel();
      if (!model) {
        return;
      }
      this.w = this.add(this.t.getOrCreate(model.uri, this.originalCell.getValue(), model.getLanguageId(), this.modifiedCell.cellKind)).object;
    }
    return this.w;
  }
  z(editor, originalModel, diff3) {
    if (areDiffsEqual(diff3, this.m)) {
      return;
    }
    this.n.clear();
    const decorations = editor.createDecorationsCollection();
    this.n.add($1c(() => {
      editor.changeViewZones((viewZoneChangeAccessor) => {
        for (const id2 of this.h) {
          viewZoneChangeAccessor.removeZone(id2);
        }
      });
      this.h = [];
      decorations.clear();
      this.m = void 0;
    }));
    this.m = diff3;
    const chatDiffAddDecoration = $WI.createDynamic({
      ...$W0,
      stickiness: 1
      /* TrackedRangeStickiness.NeverGrowsWhenTypingAtEdges */
    });
    const chatDiffWholeLineAddDecoration = $WI.createDynamic({
      ...$X0,
      stickiness: 1
    });
    const createOverviewDecoration = (overviewRulerColor, minimapColor) => {
      return $WI.createDynamic({
        description: "chat-editing-decoration",
        overviewRuler: { color: $7l(overviewRulerColor), position: OverviewRulerLane.Left },
        minimap: {
          color: $7l(minimapColor),
          position: 2
          /* MinimapPosition.Gutter */
        }
      });
    };
    const modifiedDecoration = createOverviewDecoration($MEb, $JEb);
    const addedDecoration = createOverviewDecoration($NEb, $KEb);
    const deletedDecoration = createOverviewDecoration($OEb, $LEb);
    editor.changeViewZones((viewZoneChangeAccessor) => {
      for (const id2 of this.h) {
        viewZoneChangeAccessor.removeZone(id2);
      }
      this.h = [];
      const modifiedDecorations = [];
      const mightContainNonBasicASCII = originalModel?.mightContainNonBasicASCII();
      const mightContainRTL = originalModel?.mightContainRTL();
      const renderOptions = $90.fromEditor(editor);
      for (const diffEntry of diff3.changes) {
        const originalRange = diffEntry.original;
        if (originalModel) {
          originalModel.tokenization.forceTokenization(Math.max(1, originalRange.endLineNumberExclusive - 1));
        }
        const source = new $80(originalRange.length && originalModel ? originalRange.mapToLineArray((l) => originalModel.tokenization.getLineTokens(l)) : [], [], mightContainNonBasicASCII, mightContainRTL);
        const decorations2 = [];
        for (const i2 of diffEntry.innerChanges || []) {
          decorations2.push(new $I5(
            i2.originalRange.delta(-(diffEntry.original.startLineNumber - 1)),
            $Z0.className,
            0
            /* InlineDecorationType.Regular */
          ));
          modifiedDecorations.push({
            range: i2.modifiedRange,
            options: chatDiffAddDecoration
          });
        }
        if (!diffEntry.modified.isEmpty) {
          modifiedDecorations.push({
            range: diffEntry.modified.toInclusiveRange(),
            options: chatDiffWholeLineAddDecoration
          });
        }
        if (diffEntry.original.isEmpty) {
          modifiedDecorations.push({
            range: diffEntry.modified.toInclusiveRange(),
            options: addedDecoration
          });
        } else if (diffEntry.modified.isEmpty) {
          modifiedDecorations.push({
            range: new $9C(diffEntry.modified.startLineNumber - 1, 1, diffEntry.modified.startLineNumber, 1),
            options: deletedDecoration
          });
        } else {
          modifiedDecorations.push({
            range: diffEntry.modified.toInclusiveRange(),
            options: modifiedDecoration
          });
        }
        const domNode = document.createElement("div");
        domNode.className = "chat-editing-original-zone view-lines line-delete monaco-mouse-cursor-text";
        const result = $70(source, renderOptions, decorations2, domNode);
        const isCreatedContent = decorations2.length === 1 && decorations2[0].range.isEmpty() && decorations2[0].range.startLineNumber === 1;
        if (!isCreatedContent) {
          const viewZoneData = {
            afterLineNumber: diffEntry.modified.startLineNumber - 1,
            heightInLines: result.heightInLines,
            domNode,
            ordinal: 5e4 + 2
            // more than https://github.com/microsoft/vscode/blob/bf52a5cfb2c75a7327c9adeaefbddc06d529dcad/src/vs/workbench/contrib/inlineChat/browser/inlineChatZoneWidget.ts#L42
          };
          this.h.push(viewZoneChangeAccessor.addZone(viewZoneData));
        }
      }
      decorations.set(modifiedDecorations);
    });
  }
};
$VEb = __decorate([
  __param(3, $$O),
  __param(4, $I0),
  __param(5, $SEb)
], $VEb);
var $WEb = class extends $3c {
  constructor(g) {
    super();
    this.g = g;
    this.f = this.B(new $2c());
  }
  apply(diffInfo) {
    const model = this.g.textModel;
    if (!model) {
      return;
    }
    const cells = diffInfo.filter((diff3) => diff3.type === "insert").map((diff3) => model.cells[diff3.modifiedCellIndex]);
    const ids = this.g.deltaCellDecorations([], cells.map((cell) => ({
      handle: cell.handle,
      options: { className: "nb-insertHighlight", outputClassName: "nb-insertHighlight" }
    })));
    this.clear();
    this.f.add($1c(() => {
      if (!this.g.isDisposed) {
        this.g.deltaCellDecorations(ids, []);
      }
    }));
  }
  clear() {
    this.f.clear();
  }
};
var ttPolicy3 = $W1("notebookChatEditController", { createHTML: (value) => value });
var $XEb = class $XEb2 extends $3c {
  constructor(j, m) {
    super();
    this.j = j;
    this.m = m;
    this.f = this.B(new $2c());
    this.g = /* @__PURE__ */ new Map();
    this.h = /* @__PURE__ */ new Map();
  }
  getTop(deletedIndex) {
    const info = this.h.get(deletedIndex);
    if (!info) {
      return;
    }
    const cells = this.j.getCellsInRange({ start: info.previousIndex, end: info.previousIndex + 1 });
    if (!cells.length) {
      return;
    }
    const cell = cells[0];
    const cellHeight = this.j.getHeightOfElement(cell);
    const top2 = this.j.getAbsoluteTopOfElement(cell);
    return top2 + cellHeight + info.offset;
  }
  apply(diffInfo, original) {
    this.clear();
    let currentIndex = 0;
    const deletedCellsToRender = { cells: [], index: 0 };
    diffInfo.forEach((diff3) => {
      if (diff3.type === "delete") {
        const deletedCell = original.cells[diff3.originalCellIndex];
        if (deletedCell) {
          deletedCellsToRender.cells.push({ cell: deletedCell, originalIndex: diff3.originalCellIndex, previousIndex: currentIndex });
          deletedCellsToRender.index = currentIndex;
        }
      } else {
        if (deletedCellsToRender.cells.length) {
          this.n(deletedCellsToRender.index + 1, deletedCellsToRender.cells);
          deletedCellsToRender.cells.length = 0;
        }
        currentIndex = diff3.modifiedCellIndex;
      }
    });
    if (deletedCellsToRender.cells.length) {
      this.n(deletedCellsToRender.index + 1, deletedCellsToRender.cells);
    }
  }
  clear() {
    this.h.clear();
    this.f.clear();
  }
  n(index, cells) {
    this.s(index, cells);
  }
  async s(index, cells) {
    const rootContainer = document.createElement("div");
    const widgets2 = [];
    const heights = await Promise.all(cells.map(async (cell) => {
      const widget = new $YEb(this.j, cell.cell.getValue(), cell.cell.language, rootContainer, cell.originalIndex, this.m);
      widgets2.push(widget);
      const height = await widget.render();
      this.h.set(cell.originalIndex, { height, previousIndex: cell.previousIndex, offset: 0 });
      return height;
    }));
    Array.from(this.h.keys()).sort((a, b) => a - b).forEach((originalIndex) => {
      const previousDeletedCell = this.h.get(originalIndex - 1);
      if (previousDeletedCell) {
        const deletedCell = this.h.get(originalIndex);
        if (deletedCell) {
          deletedCell.offset = previousDeletedCell.height + previousDeletedCell.offset;
        }
      }
    });
    const totalHeight = heights.reduce((prev, curr) => prev + curr, 0);
    this.j.changeViewZones((accessor) => {
      const notebookViewZone = {
        afterModelPosition: index,
        heightInPx: totalHeight + 4,
        domNode: rootContainer
      };
      const id2 = accessor.addZone(notebookViewZone);
      accessor.layoutZone(id2);
      this.g.set(index, id2);
      this.f.add($1c(() => {
        if (this.g.get(index) === id2) {
          this.g.delete(index);
        }
        if (!this.j.isDisposed) {
          this.j.changeViewZones((accessor2) => {
            accessor2.removeZone(id2);
            $Xc(widgets2);
          });
        }
      }));
    });
  }
};
$XEb = __decorate([
  __param(1, $1E)
], $XEb);
var $YEb = class $YEb2 extends $3c {
  constructor(g, h3, j, container2, originalIndex, m) {
    super();
    this.g = g;
    this.h = h3;
    this.j = j;
    this.originalIndex = originalIndex;
    this.m = m;
    this.f = $bk(container2, document.createElement("div"));
    this.B($1c(() => {
      container2.removeChild(this.f);
    }));
  }
  async render() {
    const code = this.h;
    const languageId = this.j;
    const codeHtml = await $o9(this.m, code, languageId);
    const fontInfo = this.g.getBaseCellEditorOptions(languageId).value;
    const fontFamilyVar = "--notebook-editor-font-family";
    const fontSizeVar = "--notebook-editor-font-size";
    const fontWeightVar = "--notebook-editor-font-weight";
    const editor = this.g.codeEditors.map((c) => c[1]).find((c) => c);
    const layoutInfo = editor?.getOptions().get(
      151
      /* EditorOption.layoutInfo */
    );
    const style = `font-family: var(${fontFamilyVar});font-weight: var(${fontWeightVar});font-size: var(${fontSizeVar});` + fontInfo.lineHeight ? `line-height: ${fontInfo.lineHeight}px;` : "" + layoutInfo?.contentLeft ? `margin-left: ${layoutInfo}px;` : `white-space: pre;`;
    const rootContainer = this.f;
    rootContainer.classList.add("code-cell-row");
    const container2 = $bk(rootContainer, $(".cell-inner-container"));
    const focusIndicatorLeft = $bk(container2, $(".cell-focus-indicator.cell-focus-indicator-side.cell-focus-indicator-left"));
    const cellContainer = $bk(container2, $(".cell.code"));
    $bk(focusIndicatorLeft, $("div.execution-count-label"));
    const editorPart = $bk(cellContainer, $(".cell-editor-part"));
    let editorContainer = $bk(editorPart, $(".cell-editor-container"));
    editorContainer = $bk(editorContainer, $(".code", { style }));
    if (fontInfo.fontFamily) {
      editorContainer.style.setProperty(fontFamilyVar, fontInfo.fontFamily);
    }
    if (fontInfo.fontSize) {
      editorContainer.style.setProperty(fontSizeVar, `${fontInfo.fontSize}px`);
    }
    if (fontInfo.fontWeight) {
      editorContainer.style.setProperty(fontWeightVar, fontInfo.fontWeight);
    }
    editorContainer.innerHTML = ttPolicy3?.createHTML(codeHtml) || codeHtml;
    const lineCount = $Mf(code).length;
    const height = lineCount * (fontInfo.lineHeight || $iEb) + 12 + 12;
    const totalHeight = height + 16 + 16;
    return totalHeight;
  }
};
$YEb = __decorate([
  __param(5, $1E)
], $YEb);
function areDiffsEqual(a, b) {
  if (a && b) {
    if (a.changes.length !== b.changes.length) {
      return false;
    }
    if (a.moves.length !== b.moves.length) {
      return false;
    }
    if (!areLineRangeMappinsEqual(a.changes, b.changes)) {
      return false;
    }
    if (!a.moves.some((move, i2) => {
      const bMove = b.moves[i2];
      if (!areLineRangeMappinsEqual(move.changes, bMove.changes)) {
        return true;
      }
      if (move.lineRangeMapping.changedLineCount !== bMove.lineRangeMapping.changedLineCount) {
        return true;
      }
      if (!move.lineRangeMapping.modified.equals(bMove.lineRangeMapping.modified)) {
        return true;
      }
      if (!move.lineRangeMapping.original.equals(bMove.lineRangeMapping.original)) {
        return true;
      }
      return false;
    })) {
      return false;
    }
    return true;
  } else if (!a && !b) {
    return true;
  } else {
    return false;
  }
}
function areLineRangeMappinsEqual(a, b) {
  if (a.length !== b.length) {
    return false;
  }
  if (a.some((c, i2) => {
    const bChange = b[i2];
    if (c.changedLineCount !== bChange.changedLineCount) {
      return true;
    }
    if ((c.innerChanges || []).length !== (bChange.innerChanges || []).length) {
      return true;
    }
    if ((c.innerChanges || []).some((innerC, innerIdx) => {
      const bInnerC = bChange.innerChanges[innerIdx];
      if (!innerC.modifiedRange.equalsRange(bInnerC.modifiedRange)) {
        return true;
      }
      if (!innerC.originalRange.equalsRange(bInnerC.originalRange)) {
        return true;
      }
      return false;
    })) {
      return true;
    }
    return false;
  })) {
    return false;
  }
  return true;
}

// out-build/vs/workbench/contrib/multiDiffEditor/browser/multiDiffSourceResolverService.js
var $TDb = $Qk("multiDiffSourceResolverService");
var $UDb = class {
  constructor(originalUri, modifiedUri, goToFileUri, contextKeys) {
    this.originalUri = originalUri;
    this.modifiedUri = modifiedUri;
    this.goToFileUri = goToFileUri;
    this.contextKeys = contextKeys;
    if (!originalUri && !modifiedUri) {
      throw new $vb("Invalid arguments");
    }
  }
  getKey() {
    return JSON.stringify([this.modifiedUri?.toString(), this.originalUri?.toString()]);
  }
};
var $VDb = class {
  constructor() {
    this.a = /* @__PURE__ */ new Set();
  }
  registerResolver(resolver) {
    if (this.a.has(resolver)) {
      throw new $vb("Duplicate resolver");
    }
    this.a.add(resolver);
    return $1c(() => this.a.delete(resolver));
  }
  resolve(uri) {
    for (const resolver of this.a) {
      if (resolver.canHandleUri(uri)) {
        return resolver.resolveDiffSource(uri);
      }
    }
    return Promise.resolve(void 0);
  }
};

// out-build/vs/workbench/contrib/notebook/browser/diff/notebookDiffViewModel.js
var $vEb = class extends $3c {
  get items() {
    return this.f;
  }
  get value() {
    return this.n.filter((item) => item.type !== "placeholder").filter((item) => {
      if (this.t) {
        return true;
      }
      if (item instanceof NotebookMultiDiffEditorCellItem) {
        return item.type === "unchanged" && item.containerType === "unchanged" ? false : true;
      }
      if (item instanceof NotebookMultiDiffEditorMetadataItem) {
        return item.type === "unchanged" && item.containerType === "unchanged" ? false : true;
      }
      if (item instanceof NotebookMultiDiffEditorOutputItem) {
        return item.type === "unchanged" && item.containerType === "unchanged" ? false : true;
      }
      return true;
    }).filter((item) => item instanceof NotebookMultiDiffEditorOutputItem ? !this.u : true).filter((item) => item instanceof NotebookMultiDiffEditorMetadataItem ? !this.w : true);
  }
  get hasUnchangedCells() {
    return this.s === true;
  }
  get includeUnchanged() {
    return this.t === true;
  }
  set includeUnchanged(value) {
    this.t = value;
    this.m.fire();
  }
  constructor(C, D, F, G, H, I, J, L) {
    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.c = /* @__PURE__ */ new Map();
    this.f = [];
    this.g = this.B(new $ze());
    this.onDidChangeItems = this.g.event;
    this.h = this.B(new $2c());
    this.m = this.B(new $ze());
    this.n = [];
    this.onDidChange = this.m.event;
    this.z = [];
    this.u = this.C.modified.notebook.transientOptions.transientOutputs || this.F.getValue("notebook.diff.ignoreOutputs");
    this.w = this.F.getValue("notebook.diff.ignoreMetadata");
    this.B(this.F.onDidChangeConfiguration((e) => {
      let triggerChange = false;
      let metadataChanged = false;
      if (e.affectsConfiguration("notebook.diff.ignoreMetadata")) {
        const newValue = this.F.getValue("notebook.diff.ignoreMetadata");
        if (newValue !== void 0 && this.w !== newValue) {
          this.w = newValue;
          triggerChange = true;
          metadataChanged = true;
        }
      }
      if (e.affectsConfiguration("notebook.diff.ignoreOutputs")) {
        const newValue = this.F.getValue("notebook.diff.ignoreOutputs");
        if (newValue !== void 0 && this.u !== (newValue || this.C.modified.notebook.transientOptions.transientOutputs)) {
          this.u = newValue || !!this.C.modified.notebook.transientOptions.transientOutputs;
          triggerChange = true;
        }
      }
      if (metadataChanged) {
        this.N();
      }
      if (triggerChange) {
        this.m.fire();
      }
    }));
  }
  dispose() {
    this.M();
    super.dispose();
  }
  M() {
    this.h.clear();
    $Xc(Array.from(this.c.keys()));
    this.c.clear();
    $Xc(this.z);
    this.z = [];
    $Xc(this.f);
    this.f.splice(0, this.f.length);
  }
  async computeDiff(token) {
    const diffResult = await $Ih(this.D.computeDiff(this.C.original.resource, this.C.modified.resource), token);
    if (!diffResult || token.isCancellationRequested) {
      return;
    }
    $wEb(this.C.original.notebook, this.C.modified.notebook, diffResult.cellsDiff);
    const { cellDiffInfo, firstChangeIndex } = $xEb(this.C.original.notebook, this.C.modified.notebook, diffResult);
    if (isEqual(cellDiffInfo, this.z, this.C)) {
      return;
    } else {
      await $Ih(this.P(cellDiffInfo, diffResult.metadataChanged, firstChangeIndex), token);
      if (token.isCancellationRequested) {
        return;
      }
      this.O();
    }
  }
  N() {
    if (!this.r) {
      return;
    }
    if (this.w) {
      if (this.f.length && this.f[0] === this.r) {
        this.f.splice(0, 1);
        this.g.fire({ start: 0, deleteCount: 1, elements: [] });
      }
    } else {
      if (!this.f.length || this.f[0] !== this.r) {
        this.f.splice(0, 0, this.r);
        this.g.fire({ start: 0, deleteCount: 0, elements: [this.r] });
      }
    }
  }
  O() {
    this.n = [];
    const originalSourceUri = this.C.original.resource;
    const modifiedSourceUri = this.C.modified.resource;
    this.s = false;
    this.items.forEach((item) => {
      switch (item.type) {
        case "delete": {
          this.n.push(new NotebookMultiDiffEditorCellItem(item.original.uri, void 0, item.type, item.type));
          const originalMetadata = CellUri.generateCellPropertyUri(originalSourceUri, item.original.handle, Schemas.vscodeNotebookCellMetadata);
          this.n.push(new NotebookMultiDiffEditorMetadataItem(originalMetadata, void 0, item.type, item.type));
          const originalOutput = CellUri.generateCellPropertyUri(originalSourceUri, item.original.handle, Schemas.vscodeNotebookCellOutput);
          this.n.push(new NotebookMultiDiffEditorOutputItem(originalOutput, void 0, item.type, item.type));
          break;
        }
        case "insert": {
          this.n.push(new NotebookMultiDiffEditorCellItem(void 0, item.modified.uri, item.type, item.type));
          const modifiedMetadata = CellUri.generateCellPropertyUri(modifiedSourceUri, item.modified.handle, Schemas.vscodeNotebookCellMetadata);
          this.n.push(new NotebookMultiDiffEditorMetadataItem(void 0, modifiedMetadata, item.type, item.type));
          const modifiedOutput = CellUri.generateCellPropertyUri(modifiedSourceUri, item.modified.handle, Schemas.vscodeNotebookCellOutput);
          this.n.push(new NotebookMultiDiffEditorOutputItem(void 0, modifiedOutput, item.type, item.type));
          break;
        }
        case "modified": {
          const cellType = item.checkIfInputModified() ? item.type : "unchanged";
          const containerChanged = item.checkIfInputModified() || item.checkMetadataIfModified() || item.checkIfOutputsModified() ? item.type : "unchanged";
          this.n.push(new NotebookMultiDiffEditorCellItem(item.original.uri, item.modified.uri, cellType, containerChanged));
          const originalMetadata = CellUri.generateCellPropertyUri(originalSourceUri, item.original.handle, Schemas.vscodeNotebookCellMetadata);
          const modifiedMetadata = CellUri.generateCellPropertyUri(modifiedSourceUri, item.modified.handle, Schemas.vscodeNotebookCellMetadata);
          this.n.push(new NotebookMultiDiffEditorMetadataItem(originalMetadata, modifiedMetadata, item.checkMetadataIfModified() ? item.type : "unchanged", containerChanged));
          const originalOutput = CellUri.generateCellPropertyUri(originalSourceUri, item.original.handle, Schemas.vscodeNotebookCellOutput);
          const modifiedOutput = CellUri.generateCellPropertyUri(modifiedSourceUri, item.modified.handle, Schemas.vscodeNotebookCellOutput);
          this.n.push(new NotebookMultiDiffEditorOutputItem(originalOutput, modifiedOutput, item.checkIfOutputsModified() ? item.type : "unchanged", containerChanged));
          break;
        }
        case "unchanged": {
          this.s = true;
          this.n.push(new NotebookMultiDiffEditorCellItem(item.original.uri, item.modified.uri, item.type, item.type));
          const originalMetadata = CellUri.generateCellPropertyUri(originalSourceUri, item.original.handle, Schemas.vscodeNotebookCellMetadata);
          const modifiedMetadata = CellUri.generateCellPropertyUri(modifiedSourceUri, item.modified.handle, Schemas.vscodeNotebookCellMetadata);
          this.n.push(new NotebookMultiDiffEditorMetadataItem(originalMetadata, modifiedMetadata, item.type, item.type));
          const originalOutput = CellUri.generateCellPropertyUri(originalSourceUri, item.original.handle, Schemas.vscodeNotebookCellOutput);
          const modifiedOutput = CellUri.generateCellPropertyUri(modifiedSourceUri, item.modified.handle, Schemas.vscodeNotebookCellOutput);
          this.n.push(new NotebookMultiDiffEditorOutputItem(originalOutput, modifiedOutput, item.type, item.type));
          break;
        }
      }
    });
    this.m.fire();
  }
  async P(cellDiffInfo, metadataChanged, firstChangeIndex) {
    const cellViewModels = await this.Q(cellDiffInfo, metadataChanged);
    const oldLength = this.f.length;
    this.M();
    this.f.splice(0, oldLength);
    let placeholder = void 0;
    this.z = cellViewModels;
    cellViewModels.forEach((vm, index) => {
      if (vm.type === "unchanged" && !this.L) {
        if (!placeholder) {
          vm.displayIconToHideUnmodifiedCells = true;
          placeholder = new $lEb(vm.mainDocumentTextModel, vm.editorEventDispatcher, vm.initData);
          this.f.push(placeholder);
          const placeholderItem = placeholder;
          this.h.add(placeholderItem.onUnfoldHiddenCells(() => {
            const hiddenCellViewModels2 = this.c.get(placeholderItem);
            if (!Array.isArray(hiddenCellViewModels2)) {
              return;
            }
            const start = this.f.indexOf(placeholderItem);
            this.f.splice(start, 1, ...hiddenCellViewModels2);
            this.g.fire({ start, deleteCount: 1, elements: hiddenCellViewModels2 });
          }));
          this.h.add(vm.onHideUnchangedCells(() => {
            const hiddenCellViewModels2 = this.c.get(placeholderItem);
            if (!Array.isArray(hiddenCellViewModels2)) {
              return;
            }
            const start = this.f.indexOf(vm);
            this.f.splice(start, hiddenCellViewModels2.length, placeholderItem);
            this.g.fire({ start, deleteCount: hiddenCellViewModels2.length, elements: [placeholderItem] });
          }));
        }
        const hiddenCellViewModels = this.c.get(placeholder) || [];
        hiddenCellViewModels.push(vm);
        this.c.set(placeholder, hiddenCellViewModels);
        placeholder.hiddenCells.push(vm);
      } else {
        placeholder = void 0;
        this.f.push(vm);
      }
    });
    this.g.fire({ start: 0, deleteCount: oldLength, elements: this.f, firstChangeIndex });
  }
  async Q(computedCellDiffs, metadataChanged) {
    const originalModel = this.C.original.notebook;
    const modifiedModel = this.C.modified.notebook;
    const initData = {
      metadataStatusHeight: this.F.getValue("notebook.diff.ignoreMetadata") ? 0 : 25,
      outputStatusHeight: this.F.getValue("notebook.diff.ignoreOutputs") || !!modifiedModel.transientOptions.transientOutputs ? 0 : 25,
      fontInfo: this.J
    };
    const viewModels = [];
    this.r = this.B(new $mEb(this.C.original.notebook, this.C.modified.notebook, metadataChanged ? "modifiedMetadata" : "unchangedMetadata", this.G, initData, this.H, this.I));
    if (!this.w) {
      if (metadataChanged) {
        await this.r.computeHeights();
      }
      viewModels.push(this.r);
    }
    const cellViewModels = await Promise.all(computedCellDiffs.map(async (diff3) => {
      switch (diff3.type) {
        case "delete": {
          return new $pEb(originalModel, modifiedModel, originalModel.cells[diff3.originalCellIndex], void 0, "delete", this.G, initData, this.H, this.F, this.I, diff3.originalCellIndex);
        }
        case "insert": {
          return new $pEb(modifiedModel, originalModel, void 0, modifiedModel.cells[diff3.modifiedCellIndex], "insert", this.G, initData, this.H, this.F, this.I, diff3.modifiedCellIndex);
        }
        case "modified": {
          const viewModel = new $oEb(this.C.modified.notebook, this.C.original.notebook, originalModel.cells[diff3.originalCellIndex], modifiedModel.cells[diff3.modifiedCellIndex], "modified", this.G, initData, this.H, this.F, diff3.originalCellIndex, this.I);
          await viewModel.computeEditorHeights();
          return viewModel;
        }
        case "unchanged": {
          return new $oEb(this.C.modified.notebook, this.C.original.notebook, originalModel.cells[diff3.originalCellIndex], modifiedModel.cells[diff3.modifiedCellIndex], "unchanged", this.G, initData, this.H, this.F, diff3.originalCellIndex, this.I);
        }
      }
    }));
    cellViewModels.forEach((vm) => viewModels.push(vm));
    return viewModels;
  }
};
function $wEb(original, modified, diffResult) {
  const changes = diffResult.changes;
  for (let i2 = 0; i2 < diffResult.changes.length - 1; i2++) {
    const curr = changes[i2];
    const next = changes[i2 + 1];
    const x = curr.originalStart;
    const y = curr.modifiedStart;
    if (curr.originalLength === 1 && curr.modifiedLength === 0 && next.originalStart === x + 2 && next.originalLength === 0 && next.modifiedStart === y + 1 && next.modifiedLength === 1 && original.cells[x].getHashValue() === modified.cells[y + 1].getHashValue() && original.cells[x + 1].getHashValue() === modified.cells[y].getHashValue()) {
      curr.originalStart = x;
      curr.originalLength = 0;
      curr.modifiedStart = y;
      curr.modifiedLength = 1;
      next.originalStart = x + 1;
      next.originalLength = 1;
      next.modifiedStart = y + 2;
      next.modifiedLength = 0;
      i2++;
    }
  }
}
function $xEb(originalModel, modifiedModel, diffResult) {
  const cellChanges = diffResult.cellsDiff.changes;
  const cellDiffInfo = [];
  let originalCellIndex = 0;
  let modifiedCellIndex = 0;
  let firstChangeIndex = -1;
  for (let i2 = 0; i2 < cellChanges.length; i2++) {
    const change = cellChanges[i2];
    for (let j = 0; j < change.originalStart - originalCellIndex; j++) {
      const originalCell = originalModel.cells[originalCellIndex + j];
      const modifiedCell = modifiedModel.cells[modifiedCellIndex + j];
      if (originalCell.getHashValue() === modifiedCell.getHashValue()) {
        cellDiffInfo.push({
          originalCellIndex: originalCellIndex + j,
          modifiedCellIndex: modifiedCellIndex + j,
          type: "unchanged"
        });
      } else {
        if (firstChangeIndex === -1) {
          firstChangeIndex = cellDiffInfo.length;
        }
        cellDiffInfo.push({
          originalCellIndex: originalCellIndex + j,
          modifiedCellIndex: modifiedCellIndex + j,
          type: "modified"
        });
      }
    }
    const modifiedLCS = computeModifiedLCS(change, originalModel, modifiedModel);
    if (modifiedLCS.length && firstChangeIndex === -1) {
      firstChangeIndex = cellDiffInfo.length;
    }
    cellDiffInfo.push(...modifiedLCS);
    originalCellIndex = change.originalStart + change.originalLength;
    modifiedCellIndex = change.modifiedStart + change.modifiedLength;
  }
  for (let i2 = originalCellIndex; i2 < originalModel.cells.length; i2++) {
    cellDiffInfo.push({
      originalCellIndex: i2,
      modifiedCellIndex: i2 - originalCellIndex + modifiedCellIndex,
      type: "unchanged"
    });
  }
  return {
    cellDiffInfo,
    firstChangeIndex
  };
}
function isEqual(cellDiffInfo, viewModels, model) {
  if (cellDiffInfo.length !== viewModels.length) {
    return false;
  }
  const originalModel = model.original.notebook;
  const modifiedModel = model.modified.notebook;
  for (let i2 = 0; i2 < viewModels.length; i2++) {
    const a = cellDiffInfo[i2];
    const b = viewModels[i2];
    if (a.type !== b.type) {
      return false;
    }
    switch (a.type) {
      case "delete": {
        if (originalModel.cells[a.originalCellIndex].handle !== b.original?.handle) {
          return false;
        }
        continue;
      }
      case "insert": {
        if (modifiedModel.cells[a.modifiedCellIndex].handle !== b.modified?.handle) {
          return false;
        }
        continue;
      }
      default: {
        if (originalModel.cells[a.originalCellIndex].handle !== b.original?.handle) {
          return false;
        }
        if (modifiedModel.cells[a.modifiedCellIndex].handle !== b.modified?.handle) {
          return false;
        }
        continue;
      }
    }
  }
  return true;
}
function computeModifiedLCS(change, originalModel, modifiedModel) {
  const result = [];
  const modifiedLen = Math.min(change.originalLength, change.modifiedLength);
  for (let j = 0; j < modifiedLen; j++) {
    const isTheSame = originalModel.cells[change.originalStart + j].equal(modifiedModel.cells[change.modifiedStart + j]);
    result.push({
      originalCellIndex: change.originalStart + j,
      modifiedCellIndex: change.modifiedStart + j,
      type: isTheSame ? "unchanged" : "modified"
    });
  }
  for (let j = modifiedLen; j < change.originalLength; j++) {
    result.push({
      originalCellIndex: change.originalStart + j,
      type: "delete"
    });
  }
  for (let j = modifiedLen; j < change.modifiedLength; j++) {
    result.push({
      modifiedCellIndex: change.modifiedStart + j,
      type: "insert"
    });
  }
  return result;
}
var $yEb = class extends $UDb {
  constructor(originalUri, modifiedUri, goToFileUri, type, containerType, kind, contextKeys) {
    super(originalUri, modifiedUri, goToFileUri, contextKeys);
    this.type = type;
    this.containerType = containerType;
    this.kind = kind;
  }
};
var NotebookMultiDiffEditorCellItem = class extends $yEb {
  constructor(originalUri, modifiedUri, type, containerType) {
    super(originalUri, modifiedUri, modifiedUri || originalUri, type, containerType, "Cell", {
      [$0Db.key]: "Cell",
      [$$Db.key]: type
    });
  }
};
var NotebookMultiDiffEditorMetadataItem = class extends $yEb {
  constructor(originalUri, modifiedUri, type, containerType) {
    super(originalUri, modifiedUri, modifiedUri || originalUri, type, containerType, "Metadata", {
      [$0Db.key]: "Metadata",
      [$$Db.key]: type
    });
  }
};
var NotebookMultiDiffEditorOutputItem = class extends $yEb {
  constructor(originalUri, modifiedUri, type, containerType) {
    super(originalUri, modifiedUri, modifiedUri || originalUri, type, containerType, "Output", {
      [$0Db.key]: "Output",
      [$$Db.key]: type
    });
  }
};

// out-build/vs/workbench/contrib/notebook/common/services/notebookWorkerService.js
var $tEb = "notebookEditorWorkerService";
var $uEb = $Qk($tEb);

// out-build/vs/workbench/contrib/notebook/common/notebookLoggingService.js
var $qFb = $Qk("INotebookLoggingService");

// out-build/vs/workbench/contrib/notebook/browser/contrib/chatEdit/notebookOriginalModelRefFactory.js
var $rFb = $Qk("INotebookOriginalModelReferenceFactory");
var $sFb = class $sFb2 extends $8c {
  constructor(g) {
    super();
    this.g = g;
    this.f = /* @__PURE__ */ new Set();
  }
  async b(key2, fileEntry, viewType) {
    this.f.delete(key2);
    const uri = fileEntry.originalURI;
    const model = this.g.getNotebookTextModel(uri);
    if (model) {
      return model;
    }
    const bytes = $Ci.fromString(fileEntry.originalModel.getValue());
    const stream = $Qi(bytes);
    return this.g.createNotebookTextModel(viewType, uri, stream);
  }
  c(key2, modelPromise) {
    this.f.add(key2);
    (async () => {
      try {
        const model = await modelPromise;
        if (!this.f.has(key2)) {
          return;
        }
        model.dispose();
      } catch (error) {
      } finally {
        this.f.delete(key2);
      }
    })();
  }
};
$sFb = __decorate([
  __param(0, $mrb)
], $sFb);
var $tFb = class $tFb2 {
  get b() {
    if (!this.a) {
      this.a = this.e.createInstance($sFb);
    }
    return this.a;
  }
  get d() {
    if (!this.c) {
      this.c = new $9c(this.b);
    }
    return this.c;
  }
  constructor(e) {
    this.e = e;
    this.a = void 0;
    this.c = void 0;
  }
  getOrCreate(fileEntry, viewType) {
    return this.d.acquire(fileEntry.originalURI.toString(), fileEntry, viewType);
  }
};
$tFb = __decorate([
  __param(0, $Pk)
], $tFb);

// out-build/vs/workbench/contrib/notebook/browser/services/notebookEditorService.js
var $yMb = $Qk("INotebookEditorWidgetService");

// out-build/vs/workbench/contrib/notebook/browser/contrib/chatEdit/notebookSynchronizer.js
var $zMb = $Qk("INotebookModelSynchronizerFactory");
var NotebookModelSynchronizerReferenceCollection = class NotebookModelSynchronizerReferenceCollection2 extends $8c {
  constructor(f) {
    super();
    this.f = f;
  }
  b(_key, model) {
    return this.f.createInstance($BMb, model);
  }
  c(_key, object) {
    object.dispose();
  }
};
NotebookModelSynchronizerReferenceCollection = __decorate([
  __param(0, $Pk)
], NotebookModelSynchronizerReferenceCollection);
var $AMb = class $AMb2 {
  constructor(instantiationService) {
    this.a = instantiationService.createInstance(NotebookModelSynchronizerReferenceCollection);
  }
  getOrCreate(model) {
    return this.a.acquire(model.uri.toString(), model);
  }
};
$AMb = __decorate([
  __param(0, $Pk)
], $AMb);
var $BMb = class $BMb2 extends $3c {
  get diffInfo() {
    return this.b;
  }
  constructor(m, _chatEditingService, n, s, chatService, t, u, w, y, z, C) {
    super();
    this.m = m;
    this.n = n;
    this.s = s;
    this.t = t;
    this.u = u;
    this.w = w;
    this.y = y;
    this.z = z;
    this.C = C;
    this.a = new $Th(200);
    this.b = $he("diffInfo", void 0);
    this.f = false;
    this.g = false;
    this.h = false;
    this.j = new $Th(100);
    const entryObs = $2d((r2) => {
      const session = _chatEditingService.currentEditingSessionObs.read(r2);
      if (!session) {
        return;
      }
      return session.readEntry(m.uri, r2);
    }).recomputeInitiallyAndOnChange(this.q);
    this.B(chatService.onDidPerformUserAction(async (e) => {
      const entry = entryObs.read(void 0);
      if (!entry) {
        return;
      }
      if (e.action.kind === "chatEditingSessionAction" && !e.action.hasRemainingEdits && $oh(e.action.uri, entry.modifiedURI)) {
        if (e.action.outcome === "accepted") {
          await this.H(entry);
          await this.D();
          this.b.set(void 0, void 0);
        } else if (e.action.outcome === "rejected") {
          await this.F();
        }
      }
    }));
    const updateNotebookModel = (entry, token) => {
      this.a.trigger(() => this.M(entry, token));
    };
    let snapshotCreated = false;
    this.B($xd((r2, store) => {
      const entry = entryObs.read(r2);
      if (!entry) {
        return;
      }
      if (!snapshotCreated) {
        this.D();
        snapshotCreated = true;
      }
      const modifiedModel = entry.modifiedModel;
      let cancellationToken = store.add(new $ad());
      store.add(modifiedModel.onDidChangeContent(async () => {
        if (!this.g && !modifiedModel.isDisposed() && !entry.originalModel.isDisposed() && modifiedModel.getValue() !== entry.originalModel.getValue()) {
          cancellationToken = store.add(new $ad());
          updateNotebookModel(entry, cancellationToken.token);
        }
      }));
      updateNotebookModel(entry, cancellationToken.token);
    }));
    this.B(m.onDidChangeContent(() => {
      if (!this.f && this.c) {
        this.c.dirty = true;
        const entry = entryObs.get();
        if (entry) {
          this.j.trigger(() => this.I(entry));
        }
      }
    }));
  }
  async D() {
    const [serializer, ref] = await Promise.all([
      this.getNotebookSerializer(),
      this.z.resolve(this.m.uri)
    ]);
    try {
      const data = {
        metadata: $Tv(this.m.metadata, (key2) => !serializer.options.transientDocumentMetadata[key2]),
        cells: []
      };
      const indentAmount = this.m.metadata.indentAmount || ref.object.notebook.metadata.indentAmount || void 0;
      if (typeof indentAmount === "string" && indentAmount) {
        data.metadata.indentAmount = indentAmount;
      }
      let outputSize = 0;
      for (const cell of this.m.cells) {
        const cellData = {
          cellKind: cell.cellKind,
          language: cell.language,
          mime: cell.mime,
          source: cell.getValue(),
          outputs: [],
          internalMetadata: cell.internalMetadata
        };
        const outputSizeLimit = this.w.getValue($rM.outputBackupSizeLimit) * 1024;
        if (outputSizeLimit > 0) {
          cell.outputs.forEach((output) => {
            output.outputs.forEach((item) => {
              outputSize += item.data.byteLength;
            });
          });
          if (outputSize > outputSizeLimit) {
            return;
          }
        }
        cellData.outputs = !serializer.options.transientOutputs ? cell.outputs : [];
        cellData.metadata = $Tv(cell.metadata, (key2) => !serializer.options.transientCellMetadata[key2]);
        data.cells.push(cellData);
      }
      const bytes = await serializer.notebookToData(data);
      this.c = { bytes, dirty: ref.object.isDirty() };
    } finally {
      ref.dispose();
    }
  }
  async revert() {
    await this.F();
  }
  async F() {
    if (!this.c || this.h) {
      return;
    }
    this.h = true;
    try {
      await this.G(this.c.bytes, !this.c.dirty);
    } finally {
      this.h = false;
      this.b.set(void 0, void 0);
    }
  }
  async G(bytes, saveForRevert) {
    const oldEditIsFromus = this.f;
    this.f = true;
    const ref = await this.z.resolve(this.m.uri);
    try {
      const serializer = await this.getNotebookSerializer();
      const data = await serializer.dataToNotebook(bytes);
      this.m.reset(data.cells, data.metadata, serializer.options);
      if (saveForRevert) {
        await ref.object.save({ reason: 1, force: true, ignoreModifiedSince: true });
      }
    } finally {
      ref.dispose();
      this.f = oldEditIsFromus;
    }
  }
  async H(entry) {
    const modifiedModel = entry.modifiedModel;
    const content = modifiedModel.getValue();
    await this.G($Ci.fromString(content), false);
    this.b.set(void 0, void 0);
    const stream = await this.n.createNotebookTextDocumentSnapshot(this.m.uri, 1, CancellationToken.None);
    const originalModel = await this.L(entry);
    await this.n.restoreNotebookTextModelFromSnapshot(originalModel.uri, originalModel.viewType, stream);
  }
  async I(entry) {
    const modifiedModel = entry.modifiedModel;
    const stream = await this.n.createNotebookTextDocumentSnapshot(this.m.uri, 1, CancellationToken.None);
    const buffer = await $Oi(stream);
    const text2 = new TextDecoder().decode(buffer.buffer);
    this.g = true;
    modifiedModel.pushEditOperations(null, [{ range: modifiedModel.getFullModelRange(), text: text2 }], () => null);
    this.g = false;
  }
  async getNotebookSerializer() {
    const info = await this.n.withNotebookDataProvider(this.m.viewType);
    return info.serializer;
  }
  async L(entry) {
    if (!this.J) {
      this.J = this.C.getOrCreate(entry, this.m.viewType).then((ref) => {
        if (this.q.isDisposed) {
          ref.dispose();
          return ref.object;
        } else {
          return this.B(ref).object;
        }
      });
    }
    return this.J;
  }
  async M(entry, token) {
    const modifiedModelVersion = entry.modifiedModel.getVersionId();
    const currentModel = this.m;
    const modelVersion = currentModel?.versionId ?? 0;
    const modelWithChatEdits = await this.O(entry, token);
    if (!modelWithChatEdits || token.isCancellationRequested || !currentModel) {
      return;
    }
    const originalModel = await this.L(entry);
    const cellDiffInfo = (await this.computeDiff(originalModel, modelWithChatEdits, token))?.cellDiffInfo;
    const cellDiffInfoToApplyEdits = (await this.computeDiff(currentModel, modelWithChatEdits, token))?.cellDiffInfo;
    const currentVersion = entry.modifiedModel.getVersionId();
    if (!cellDiffInfo || !cellDiffInfoToApplyEdits || token.isCancellationRequested || currentVersion !== modifiedModelVersion || modelVersion !== currentModel.versionId) {
      return;
    }
    if (cellDiffInfoToApplyEdits.every((d) => d.type === "unchanged")) {
      return;
    }
    this.f = true;
    try {
      const edits = [];
      const mappings = /* @__PURE__ */ new Map();
      const deletedIndexes = [];
      await Promise.all(cellDiffInfoToApplyEdits.reverse().map(async (diff3) => {
        if (diff3.type === "delete") {
          deletedIndexes.push(diff3.originalCellIndex);
          edits.push({
            editType: 1,
            index: diff3.originalCellIndex,
            cells: [],
            count: 1
          });
        }
      }));
      if (edits.length) {
        currentModel.applyEdits(edits, true, void 0, () => void 0, void 0, false);
        edits.length = 0;
      }
      const notebookEditor = this.s.retrieveExistingWidgetFromURI(this.m.uri)?.value;
      cellDiffInfoToApplyEdits.reverse().forEach((diff3) => {
        if (diff3.type === "modified" || diff3.type === "unchanged") {
          mappings.set(diff3.modifiedCellIndex, diff3.originalCellIndex);
        }
        if (diff3.type === "insert") {
          const originalIndex = mappings.get(diff3.modifiedCellIndex - 1) ?? 0;
          mappings.set(diff3.modifiedCellIndex, originalIndex);
          const index = currentModel.cells.length ? originalIndex + 1 : originalIndex;
          const cell = modelWithChatEdits.cells[diff3.modifiedCellIndex];
          const newCell = {
            source: cell.getValue(),
            cellKind: cell.cellKind,
            language: cell.language,
            outputs: cell.outputs.map((output) => output.asDto()),
            mime: cell.mime,
            metadata: cell.metadata,
            collapseState: cell.collapseState,
            internalMetadata: cell.internalMetadata
          };
          edits.push({
            editType: 1,
            index,
            cells: [newCell],
            count: 0
          });
        }
      });
      if (edits.length) {
        currentModel.applyEdits(edits, true, void 0, () => void 0, void 0, false);
        for (const edit3 of edits.filter(
          (e) => e.editType === 1
          /* CellEditType.Replace */
        )) {
          const cell = currentModel.cells[edit3.index];
          if (cell) {
            const cellViewModel = notebookEditor?.getCellByHandle(cell.handle);
            cellViewModel?.updateEditState(CellEditState.Editing, "chatEdit");
          }
        }
        edits.length = 0;
      }
      await Promise.all(cellDiffInfoToApplyEdits.map(async (diff3) => {
        if (diff3.type === "modified") {
          const cell = currentModel.cells[diff3.originalCellIndex];
          const cellModelRef = await this.t.createModelReference(cell.uri);
          try {
            const modifiedCell = modelWithChatEdits.cells[diff3.modifiedCellIndex];
            if (modifiedCell.cellKind === cell.cellKind) {
              const cellViewModel = notebookEditor?.getCellByHandle(cell.handle);
              cellViewModel?.updateEditState(CellEditState.Editing, "chatEdit");
              const textModel = cellModelRef.object.textEditorModel;
              textModel.pushEditOperations(null, [
                $bD.replace(textModel.getFullModelRange(), modifiedCell.getValue())
              ], () => null);
            } else {
              const newCellDto = {
                source: modifiedCell.getValue(),
                cellKind: modifiedCell.cellKind,
                language: modifiedCell.language,
                outputs: modifiedCell.outputs.map((output) => output.asDto()),
                mime: modifiedCell.mime,
                metadata: modifiedCell.metadata,
                collapseState: modifiedCell.collapseState,
                internalMetadata: modifiedCell.internalMetadata
              };
              const edit3 = {
                editType: 1,
                index: diff3.originalCellIndex,
                cells: [newCellDto],
                count: 1
              };
              currentModel.applyEdits([edit3], true, void 0, () => void 0, void 0, false);
              const newCell = currentModel.cells[diff3.originalCellIndex];
              const cellViewModel = notebookEditor?.getCellByHandle(newCell.handle);
              cellViewModel?.updateEditState(CellEditState.Editing, "chatEdit");
            }
          } finally {
            cellModelRef.dispose();
          }
        }
      }));
      if (edits.length) {
        currentModel.applyEdits(edits, true, void 0, () => void 0, void 0, false);
      }
      this.b.set({ cellDiff: cellDiffInfo, modelVersion: currentModel.versionId }, void 0);
    } finally {
      this.f = false;
    }
  }
  async O(entry, token) {
    const text2 = entry.modifiedModel.getValue();
    const bytes = $Ci.fromString(text2);
    const uri = entry.modifiedURI.with({ scheme: `NotebookChatEditorController.modifiedScheme${Date.now().toString()}` });
    const stream = $Qi(bytes);
    if (this.N) {
      this.n.getNotebookTextModel(this.N)?.dispose();
    }
    this.N = uri;
    try {
      const model = await this.n.createNotebookTextModel(this.m.viewType, uri, stream);
      if (token.isCancellationRequested) {
        model.dispose();
        return;
      }
      this.B(model);
      return model;
    } catch (ex) {
      this.u.warn("NotebookChatEdit", `Failed to deserialize Notebook for ${uri.toString}, ${ex.message}`);
      this.u.debug("NotebookChatEdit", ex.toString());
      return;
    }
  }
  async computeDiff(original, modified, token) {
    const diffResult = await $Ih(this.y.computeDiff(original.uri, modified.uri), token);
    if (!diffResult || token.isCancellationRequested) {
      return;
    }
    $wEb(original, modified, diffResult.cellsDiff);
    return $xEb(original, modified, diffResult);
  }
};
$BMb = __decorate([
  __param(1, $$O),
  __param(2, $mrb),
  __param(3, $yMb),
  __param(4, $qO),
  __param(5, $oG),
  __param(6, $qFb),
  __param(7, $kl),
  __param(8, $uEb),
  __param(9, $orb),
  __param(10, $rFb)
], $BMb);

// out-build/vs/workbench/contrib/chat/browser/chatEditorController.js
var $EMb_1;
var DiffHunkWidget_1;
var $CMb = new $nn("chat.hasEditorModifications", void 0, localize(4878, null));
var $DMb = new $nn("chat.ctxHasRequestInProgress", false, localize(4879, null));
var $EMb = class $EMb2 extends $3c {
  static {
    $EMb_1 = this;
  }
  static {
    this.ID = "editor.contrib.chatEditorController";
  }
  static {
    this.f = $WI.register({ description: "diff-line-decoration" });
  }
  static get(editor) {
    const controller = editor.getContribution($EMb_1.ID);
    return controller;
  }
  constructor(z, C, D, F, contextKeyService) {
    super();
    this.z = z;
    this.C = C;
    this.D = D;
    this.F = F;
    this.g = this.z.createDecorationsCollection();
    this.h = this.z.createDecorationsCollection();
    this.j = this.B(new $2c());
    this.m = [];
    this.n = [];
    this.u = $he(this, void 0);
    this.currentChange = this.u;
    this.y = false;
    this.s = $CMb.bindTo(contextKeyService);
    this.t = $DMb.bindTo(contextKeyService);
    const fontInfoObs = $79(this.z).getOption(
      52
      /* EditorOption.fontInfo */
    );
    const lineHeightObs = $79(this.z).getOption(
      68
      /* EditorOption.lineHeight */
    );
    const modelObs = $79(this.z).model;
    let ignoreScrollEvent = false;
    this.q.add(this.z.onDidScrollChange((e) => {
      if (e.scrollTopChanged && !ignoreScrollEvent) {
      }
    }));
    this.q.add($td((r2) => {
      const session = this.D.currentEditingSessionObs.read(r2);
      this.t.set(
        session?.state.read(r2) === 1
        /* ChatEditingSessionState.StreamingEdits */
      );
    }));
    let didReveal = false;
    this.B($xd((r2, store) => {
      if (this.z.getOption(
        63
        /* EditorOption.inDiffEditor */
      )) {
        this.G();
        return;
      }
      fontInfoObs.read(r2);
      lineHeightObs.read(r2);
      const model = modelObs.read(r2);
      const session = this.D.currentEditingSessionObs.read(r2);
      const entry = model?.uri ? session?.readEntry(model.uri, r2) : void 0;
      if (!entry || entry.state.read(r2) !== 0) {
        this.G();
        didReveal = false;
        return;
      }
      if (entry.isCurrentlyBeingModified.read(r2)) {
        const domNode = this.z.getDomNode();
        if (domNode) {
          store.add($aj(domNode, "wheel", () => {
            this.y = true;
          }));
        }
      }
      try {
        ignoreScrollEvent = true;
        if (!this.y && !didReveal) {
          const maxLineNumber = entry.maxLineNumber.read(r2);
          this.z.revealLineNearTop(
            maxLineNumber,
            0
            /* ScrollType.Smooth */
          );
        }
        const diff3 = entry?.diffInfo.read(r2);
        this.H(entry, diff3);
        if (!entry.isCurrentlyBeingModified.read(r2)) {
          this.initNavigation();
          if (!this.y && !didReveal) {
            const currentPosition = this.u.read(r2);
            if (currentPosition) {
              this.z.revealLine(
                currentPosition.lineNumber,
                0
                /* ScrollType.Smooth */
              );
              didReveal = true;
            } else {
              didReveal = this.revealNext();
            }
          }
        }
      } finally {
        ignoreScrollEvent = false;
      }
    }));
    const shouldBeReadOnly = $2d(this, (r2) => {
      const value = this.D.currentEditingSessionObs.read(r2);
      if (!value || value.state.read(r2) !== 1) {
        return false;
      }
      const model = modelObs.read(r2);
      return model ? value.readEntry(model.uri, r2) : void 0;
    });
    let actualReadonly;
    let actualDeco;
    this.B($td((r2) => {
      const value = shouldBeReadOnly.read(r2);
      if (value) {
        actualReadonly ??= this.z.getOption(
          96
          /* EditorOption.readOnly */
        );
        actualDeco ??= this.z.getOption(
          103
          /* EditorOption.renderValidationDecorations */
        );
        this.z.updateOptions({
          readOnly: true,
          renderValidationDecorations: "off"
        });
      } else {
        if (actualReadonly !== void 0 && actualDeco !== void 0) {
          this.z.updateOptions({
            readOnly: actualReadonly,
            renderValidationDecorations: actualDeco
          });
          actualReadonly = void 0;
          actualDeco = void 0;
        }
      }
    }));
  }
  dispose() {
    this.G();
    super.dispose();
  }
  G() {
    this.z.changeViewZones((viewZoneChangeAccessor) => {
      for (const id2 of this.n) {
        viewZoneChangeAccessor.removeZone(id2);
      }
    });
    this.n = [];
    this.j.clear();
    this.h.clear();
    this.g.clear();
    this.s.reset();
    this.u.set(void 0, void 0);
    this.y = false;
  }
  H(entry, diff3) {
    this.s.set(!diff3.identical);
    const originalModel = entry.originalModel;
    const chatDiffAddDecoration = $WI.createDynamic({
      ...$W0,
      stickiness: 1
      /* TrackedRangeStickiness.NeverGrowsWhenTypingAtEdges */
    });
    const chatDiffWholeLineAddDecoration = $WI.createDynamic({
      ...$X0,
      stickiness: 1
    });
    const createOverviewDecoration = (overviewRulerColor, minimapColor) => {
      return $WI.createDynamic({
        description: "chat-editing-decoration",
        overviewRuler: { color: $7l(overviewRulerColor), position: OverviewRulerLane.Left },
        minimap: {
          color: $7l(minimapColor),
          position: 2
          /* MinimapPosition.Gutter */
        }
      });
    };
    const modifiedDecoration = createOverviewDecoration($MEb, $JEb);
    const addedDecoration = createOverviewDecoration($NEb, $KEb);
    const deletedDecoration = createOverviewDecoration($OEb, $LEb);
    this.j.clear();
    this.m.length = 0;
    const diffHunkDecorations = [];
    this.z.changeViewZones((viewZoneChangeAccessor) => {
      for (const id2 of this.n) {
        viewZoneChangeAccessor.removeZone(id2);
      }
      this.n = [];
      const modifiedVisualDecorations = [];
      const modifiedLineDecorations = [];
      const mightContainNonBasicASCII = originalModel.mightContainNonBasicASCII();
      const mightContainRTL = originalModel.mightContainRTL();
      const renderOptions = $90.fromEditor(this.z);
      const editorLineCount = this.z.getModel()?.getLineCount();
      for (const diffEntry of diff3.changes) {
        const originalRange = diffEntry.original;
        originalModel.tokenization.forceTokenization(Math.max(1, originalRange.endLineNumberExclusive - 1));
        const source = new $80(originalRange.mapToLineArray((l) => originalModel.tokenization.getLineTokens(l)), [], mightContainNonBasicASCII, mightContainRTL);
        const decorations = [];
        for (const i2 of diffEntry.innerChanges || []) {
          decorations.push(new $I5(
            i2.originalRange.delta(-(diffEntry.original.startLineNumber - 1)),
            $Z0.className,
            0
            /* InlineDecorationType.Regular */
          ));
          if (!(i2.originalRange.isEmpty() && i2.originalRange.startLineNumber === 1 && i2.modifiedRange.endLineNumber === editorLineCount) && !i2.modifiedRange.isEmpty()) {
            modifiedVisualDecorations.push({
              range: i2.modifiedRange,
              options: chatDiffAddDecoration
            });
          }
        }
        const isCreatedContent = decorations.length === 1 && decorations[0].range.isEmpty() && diffEntry.original.startLineNumber === 1;
        if (!diffEntry.modified.isEmpty && !(isCreatedContent && diffEntry.modified.endLineNumberExclusive - 1 === editorLineCount)) {
          modifiedVisualDecorations.push({
            range: diffEntry.modified.toInclusiveRange(),
            options: chatDiffWholeLineAddDecoration
          });
        }
        if (diffEntry.original.isEmpty) {
          modifiedVisualDecorations.push({
            range: diffEntry.modified.toInclusiveRange(),
            options: addedDecoration
          });
        } else if (diffEntry.modified.isEmpty) {
          modifiedVisualDecorations.push({
            range: new $9C(diffEntry.modified.startLineNumber - 1, 1, diffEntry.modified.startLineNumber, 1),
            options: deletedDecoration
          });
        } else {
          modifiedVisualDecorations.push({
            range: diffEntry.modified.toInclusiveRange(),
            options: modifiedDecoration
          });
        }
        const domNode = document.createElement("div");
        domNode.className = "chat-editing-original-zone view-lines line-delete monaco-mouse-cursor-text";
        const result = $70(source, renderOptions, decorations, domNode);
        if (!isCreatedContent) {
          const viewZoneData = {
            afterLineNumber: diffEntry.modified.startLineNumber - 1,
            heightInLines: result.heightInLines,
            domNode,
            ordinal: 5e4 + 2
            // more than https://github.com/microsoft/vscode/blob/bf52a5cfb2c75a7327c9adeaefbddc06d529dcad/src/vs/workbench/contrib/inlineChat/browser/inlineChatZoneWidget.ts#L42
          };
          this.n.push(viewZoneChangeAccessor.addZone(viewZoneData));
        }
        const undoEdits = [];
        for (const c of diffEntry.innerChanges ?? []) {
          const oldText = originalModel.getValueInRange(c.originalRange);
          undoEdits.push($bD.replace(c.modifiedRange, oldText));
        }
        const widget = this.C.createInstance(DiffHunkWidget, entry, undoEdits, this.z.getModel().getVersionId(), this.z, isCreatedContent ? 0 : result.heightInLines);
        widget.layout(diffEntry.modified.startLineNumber);
        this.m.push(widget);
        diffHunkDecorations.push({
          range: diffEntry.modified.toInclusiveRange() ?? new $9C(diffEntry.modified.startLineNumber, 1, diffEntry.modified.startLineNumber, Number.MAX_SAFE_INTEGER),
          options: {
            description: "diff-hunk-widget",
            stickiness: 0
            /* TrackedRangeStickiness.AlwaysGrowsWhenTypingAtEdges */
          }
        });
        modifiedLineDecorations.push({
          range: diffEntry.modified.toInclusiveRange() ?? new $9C(diffEntry.modified.startLineNumber, 1, diffEntry.modified.startLineNumber, Number.MAX_SAFE_INTEGER),
          options: $EMb_1.f
        });
      }
      this.h.set(modifiedVisualDecorations);
      this.g.set(modifiedLineDecorations);
    });
    const diffHunkDecoCollection = this.z.createDecorationsCollection(diffHunkDecorations);
    this.j.add($1c(() => {
      $Xc(this.m);
      this.m.length = 0;
      diffHunkDecoCollection.clear();
    }));
    const positionObs = $Dd(this.z.onDidChangeCursorPosition, (_) => this.z.getPosition());
    const activeWidgetIdx = $2d((r2) => {
      const position = positionObs.read(r2);
      if (!position) {
        return -1;
      }
      const idx = diffHunkDecoCollection.getRanges().findIndex((r3) => r3.containsPosition(position));
      return idx;
    });
    const toggleWidget = (activeWidget) => {
      const positionIdx = activeWidgetIdx.get();
      for (let i2 = 0; i2 < this.m.length; i2++) {
        const widget = this.m[i2];
        widget.toggle(widget === activeWidget || i2 === positionIdx);
      }
    };
    this.j.add($td((r2) => {
      const idx = activeWidgetIdx.read(r2);
      const widget = this.m[idx];
      toggleWidget(widget);
    }));
    this.j.add(this.z.onMouseMove((e) => {
      if (e.target.type === 12) {
        const id2 = e.target.detail;
        const widget = this.m.find((w) => w.getId() === id2);
        toggleWidget(widget);
      } else if (e.target.type === 8) {
        const zone = e.target.detail;
        const idx = this.n.findIndex((id2) => id2 === zone.viewZoneId);
        toggleWidget(this.m[idx]);
      } else if (e.target.position) {
        const { position } = e.target;
        const idx = diffHunkDecoCollection.getRanges().findIndex((r2) => r2.containsPosition(position));
        toggleWidget(this.m[idx]);
      } else {
        toggleWidget(void 0);
      }
    }));
    this.j.add(Event2.any(this.z.onDidScrollChange, this.z.onDidLayoutChange)(() => {
      for (let i2 = 0; i2 < this.m.length; i2++) {
        const widget = this.m[i2];
        const range = diffHunkDecoCollection.getRange(i2);
        if (range) {
          widget.layout(range?.startLineNumber);
        } else {
          widget.dispose();
        }
      }
    }));
  }
  unlockScroll() {
    this.y = false;
  }
  initNavigation() {
    const position = this.z.getPosition();
    const range = position && this.g.getRanges().find((r2) => r2.containsPosition(position));
    if (range) {
      this.u.set(position, void 0);
    }
  }
  revealNext(strict = false) {
    return this.I(true, strict);
  }
  revealPrevious(strict = false) {
    return this.I(false, strict);
  }
  I(next, strict) {
    const position = this.z.getPosition();
    if (!position) {
      return false;
    }
    const decorations = this.g.getRanges().sort((a, b) => $9C.compareRangesUsingStarts(a, b));
    if (decorations.length === 0) {
      return false;
    }
    let target = -1;
    for (let i2 = 0; i2 < decorations.length; i2++) {
      const range = decorations[i2];
      if (range.containsPosition(position)) {
        target = i2 + (next ? 1 : -1);
        break;
      } else if ($8C.isBefore(position, range.getStartPosition())) {
        target = next ? i2 : i2 - 1;
        break;
      }
    }
    if (strict && (target < 0 || target >= decorations.length)) {
      return false;
    }
    target = (target + decorations.length) % decorations.length;
    const targetPosition = next ? decorations[target].getStartPosition() : decorations[target].getEndPosition();
    this.u.set(targetPosition, void 0);
    this.z.setPosition(targetPosition);
    this.z.revealPositionInCenter(
      targetPosition,
      0
      /* ScrollType.Smooth */
    );
    this.z.focus();
    return true;
  }
  undoNearestChange(closestWidget) {
    if (!this.z.hasModel()) {
      return;
    }
    const lineRelativeTop = this.z.getTopForLineNumber(this.z.getPosition().lineNumber) - this.z.getScrollTop();
    let closestDistance = Number.MAX_VALUE;
    if (!(closestWidget instanceof DiffHunkWidget)) {
      for (const widget of this.m) {
        const widgetTop = widget.getPosition()?.preference?.top;
        if (widgetTop !== void 0) {
          const distance = Math.abs(widgetTop - lineRelativeTop);
          if (distance < closestDistance) {
            closestDistance = distance;
            closestWidget = widget;
          }
        }
      }
    }
    if (closestWidget instanceof DiffHunkWidget) {
      closestWidget.undo();
    }
  }
  async openDiff(widget) {
    if (!this.z.hasModel()) {
      return;
    }
    const lineRelativeTop = this.z.getTopForLineNumber(this.z.getPosition().lineNumber) - this.z.getScrollTop();
    let closestDistance = Number.MAX_VALUE;
    if (!(widget instanceof DiffHunkWidget)) {
      for (const candidate of this.m) {
        const widgetTop = candidate.getPosition()?.preference?.top;
        if (widgetTop !== void 0) {
          const distance = Math.abs(widgetTop - lineRelativeTop);
          if (distance < closestDistance) {
            closestDistance = distance;
            widget = candidate;
          }
        }
      }
    }
    if (widget instanceof DiffHunkWidget) {
      const lineNumber = widget.getStartLineNumber();
      const position = lineNumber ? new $8C(lineNumber, 1) : void 0;
      let selection = this.z.getSelection();
      if (position && !selection.containsPosition(position)) {
        selection = $_D.fromPositions(position);
      }
      const diffEditor = await this.F.openEditor({
        original: { resource: widget.entry.originalURI, options: { selection: void 0 } },
        modified: { resource: widget.entry.modifiedURI, options: { selection } }
      });
      diffEditor?.getControl()?.setSelection(selection);
    }
  }
};
$EMb = $EMb_1 = __decorate([
  __param(1, $Pk),
  __param(2, $$O),
  __param(3, $mJ),
  __param(4, $on)
], $EMb);
var DiffHunkWidget = class DiffHunkWidget2 {
  static {
    DiffHunkWidget_1 = this;
  }
  static {
    this.d = 0;
  }
  constructor(entry, m, n, o, p, instaService) {
    this.entry = entry;
    this.m = m;
    this.n = n;
    this.o = o;
    this.p = p;
    this.f = `diff-change-widget-${DiffHunkWidget_1.d++}`;
    this.h = new $2c();
    this.g = document.createElement("div");
    this.g.className = "chat-diff-change-content-widget";
    const toolbar = instaService.createInstance($4$, this.g, $bJ.ChatEditingEditorHunk, {
      telemetrySource: "chatEditingEditorHunk",
      hiddenItemStrategy: -1,
      toolbarOptions: { primaryGroup: () => true },
      menuOptions: {
        renderShortTitle: true,
        arg: this
      }
    });
    this.h.add(toolbar);
    this.o.addOverlayWidget(this);
  }
  dispose() {
    this.h.dispose();
    this.o.removeOverlayWidget(this);
  }
  getId() {
    return this.f;
  }
  layout(startLineNumber) {
    const lineHeight = this.o.getOption(
      68
      /* EditorOption.lineHeight */
    );
    const { contentLeft, contentWidth, verticalScrollbarWidth } = this.o.getLayoutInfo();
    const scrollTop = this.o.getScrollTop();
    this.j = {
      stackOridinal: 1,
      preference: {
        top: this.o.getTopForLineNumber(startLineNumber) - scrollTop - lineHeight * this.p,
        left: contentLeft + contentWidth - (2 * verticalScrollbarWidth + $xj(this.g))
      }
    };
    this.o.layoutOverlayWidget(this);
    this.k = startLineNumber;
  }
  toggle(show2) {
    this.g.classList.toggle("hover", show2);
    if (this.k) {
      this.layout(this.k);
    }
  }
  getDomNode() {
    return this.g;
  }
  getPosition() {
    return this.j ?? null;
  }
  getStartLineNumber() {
    return this.k;
  }
  // ---
  undo() {
    if (this.n === this.o.getModel()?.getVersionId()) {
      this.o.executeEdits("chatEdits.undo", this.m);
    }
  }
};
DiffHunkWidget = DiffHunkWidget_1 = __decorate([
  __param(5, $Pk)
], DiffHunkWidget);

// out-build/vs/workbench/contrib/chat/browser/chatEditorActions.js
var NavigateAction = class extends $gJ {
  constructor(next) {
    super({
      id: next ? "chatEditor.action.navigateNext" : "chatEditor.action.navigatePrevious",
      title: next ? localize2(4869, "Go to Next Chat Edit") : localize2(4870, "Go to Previous Chat Edit"),
      category: $vNb,
      icon: next ? $6l.arrowDown : $6l.arrowUp,
      keybinding: {
        primary: next ? 512 | 63 : 512 | 1024 | 63,
        weight: 100,
        when: $7m.and($7m.or($CMb, $KMb), EditorContextKeys.focus)
      },
      f1: true,
      menu: {
        id: $bJ.ChatEditingEditorContent,
        group: "navigate",
        order: !next ? 2 : 3
      }
    });
    this.next = next;
  }
  async run(accessor) {
    const chatEditingService = accessor.get($$O);
    const editorService = accessor.get($mJ);
    const editor = editorService.activeTextEditorControl;
    if (!$P5(editor) || !editor.hasModel()) {
      return;
    }
    const session = chatEditingService.currentEditingSession;
    if (!session) {
      return;
    }
    const ctrl = $EMb.get(editor);
    if (!ctrl) {
      return;
    }
    const done = this.next ? ctrl.revealNext(true) : ctrl.revealPrevious(true);
    if (done) {
      return;
    }
    const entries2 = session.entries.get();
    const idx = entries2.findIndex((e) => $oh(e.modifiedURI, editor.getModel().uri));
    if (idx < 0) {
      return;
    }
    const newIdx = (idx + (this.next ? 1 : -1) + entries2.length) % entries2.length;
    if (idx === newIdx) {
      if (this.next) {
        ctrl.revealNext(false);
      } else {
        ctrl.revealPrevious(false);
      }
      return;
    }
    const entry = entries2[newIdx];
    const change = entry.diffInfo.get().changes.at(this.next ? 0 : -1);
    const newEditorPane = await editorService.openEditor({
      resource: entry.modifiedURI,
      options: {
        selection: change && $9C.fromPositions({ lineNumber: change.modified.startLineNumber, column: 1 }),
        revealIfOpened: false,
        revealIfVisible: false
      }
    }, $nJ);
    const newEditor = newEditorPane?.getControl();
    if ($P5(newEditor)) {
      $EMb.get(newEditor)?.initNavigation();
    }
  }
};
var AcceptDiscardAction = class extends $gJ {
  constructor(id2, accept) {
    super({
      id: id2,
      title: accept ? localize2(4871, "Accept Chat Edit") : localize2(4872, "Discard Chat Edit"),
      shortTitle: accept ? localize2(4873, "Accept") : localize2(4874, "Discard"),
      category: $vNb,
      precondition: $7m.and($DMb.negate(), $fP, $7m.or($CMb, $KMb)),
      icon: accept ? $6l.check : $6l.discard,
      f1: true,
      keybinding: {
        when: EditorContextKeys.focus,
        weight: 200,
        primary: accept ? 2048 | 3 : 2048 | 1
        /* KeyCode.Backspace */
      },
      menu: {
        id: $bJ.ChatEditingEditorContent,
        group: "a_resolve",
        order: accept ? 0 : 1
      }
    });
    this.accept = accept;
  }
  run(accessor) {
    const chatEditingService = accessor.get($$O);
    const editorService = accessor.get($mJ);
    let uri = $Qrb(editorService.activeEditorPane)?.textModel?.uri;
    if (!uri) {
      const editor = editorService.activeTextEditorControl;
      uri = $P5(editor) && editor.hasModel() ? editor.getModel().uri : void 0;
    }
    if (!uri) {
      return;
    }
    const session = chatEditingService.currentEditingSession;
    if (!session) {
      return;
    }
    if (this.accept) {
      session.accept(uri);
    } else {
      session.reject(uri);
    }
  }
};
var $FMb = class _$FMb extends AcceptDiscardAction {
  static {
    this.ID = "chatEditor.action.accept";
  }
  constructor() {
    super(_$FMb.ID, true);
  }
};
var $GMb = class _$GMb extends AcceptDiscardAction {
  static {
    this.ID = "chatEditor.action.reject";
  }
  constructor() {
    super(_$GMb.ID, false);
  }
};
var UndoHunkAction = class extends $25 {
  constructor() {
    super({
      id: "chatEditor.action.undoHunk",
      title: localize2(4875, "Undo this Change"),
      shortTitle: localize2(4876, "Undo"),
      category: $vNb,
      precondition: $7m.and(ChatContextKeys.requestInProgress.negate(), $fP),
      icon: $6l.discard,
      f1: true,
      keybinding: {
        when: EditorContextKeys.focus,
        weight: 200,
        primary: 2048 | 1024 | 1
        /* KeyCode.Backspace */
      },
      menu: {
        id: $bJ.ChatEditingEditorHunk,
        order: 1
      }
    });
  }
  runEditorCommand(_accessor, editor, ...args2) {
    $EMb.get(editor)?.undoNearestChange(args2[0]);
  }
};
var OpenDiffFromHunkAction = class extends $25 {
  constructor() {
    super({
      id: "chatEditor.action.diffHunk",
      title: localize2(4877, "Open Diff"),
      category: $vNb,
      precondition: $7m.and(ChatContextKeys.requestInProgress.negate(), $fP),
      icon: $6l.diffSingle,
      menu: {
        id: $bJ.ChatEditingEditorHunk,
        order: 10
      }
    });
  }
  runEditorCommand(_accessor, editor, ...args2) {
    $EMb.get(editor)?.openDiff(args2[0]);
  }
};
function $HMb() {
  $hJ(class NextAction extends NavigateAction {
    constructor() {
      super(true);
    }
  });
  $hJ(class PrevAction extends NavigateAction {
    constructor() {
      super(false);
    }
  });
  $hJ($FMb);
  $hJ($GMb);
  $hJ(UndoHunkAction);
  $hJ(OpenDiffFromHunkAction);
}

// out-build/vs/workbench/contrib/notebook/browser/contrib/chatEdit/notebookChatActionsOverlay.js
var $IMb = class $IMb2 extends $3c {
  constructor(a, cellDiffInfo, deletedCellDecorator, b, instantiationService) {
    super();
    this.a = a;
    this.b = b;
    const notebookModel = $Dd(this.a.onDidChangeModel, (e) => e);
    this.B($xd((r2, store) => {
      const session = this.b.currentEditingSessionObs.read(r2);
      const model = notebookModel.read(r2);
      if (!model || !session) {
        return;
      }
      const entries2 = session.entries.read(r2);
      const idx = entries2.findIndex((e) => $oh(e.modifiedURI, model.uri));
      if (idx >= 0) {
        const entry = entries2[idx];
        const nextEntry = entries2[(idx + 1) % entries2.length];
        const previousEntry = entries2[(idx - 1 + entries2.length) % entries2.length];
        store.add(instantiationService.createInstance($JMb, a, entry, cellDiffInfo, nextEntry, previousEntry, deletedCellDecorator));
      }
    }));
  }
};
$IMb = __decorate([
  __param(3, $$O),
  __param(4, $Pk)
], $IMb);
var $JMb = class $JMb2 extends $3c {
  constructor(g, entry, cellDiffInfo, nextEntry, previousEntry, deletedCellDecorator, h3, instaService) {
    super();
    this.g = g;
    this.h = h3;
    this.a = $he("focusedDiff", void 0);
    this.f = false;
    this.B(g.onDidBlurWidget(() => {
      if ($Qrb(h3.activeEditorPane) !== g) {
        this.a.set(void 0, void 0);
      }
    }));
    this.B(g.onDidChangeActiveEditor((e) => {
      if (e !== g) {
        this.a.set(void 0, void 0);
      }
    }));
    this.b = $("div");
    this.b.classList.add("notebook-chat-editor-overlay-widget");
    this.B($1c(() => this.m()));
    this.B($td((r2) => {
      const diffs = cellDiffInfo.read(r2);
      if (diffs?.some((d) => d.type !== "unchanged")) {
        this.j();
      } else {
        this.m();
      }
    }));
    const focusedDiff = this.a;
    const _toolbar = instaService.createInstance($4$, this.b, $bJ.ChatEditingEditorContent, {
      telemetrySource: "chatEditor.overlayToolbar",
      hiddenItemStrategy: 0,
      toolbarOptions: {
        primaryGroup: () => true,
        useSeparatorsInPrimaryActions: true
      },
      menuOptions: { renderShortTitle: true },
      actionViewItemProvider: (action, options3) => {
        const that = this;
        if (action.id === $MMb) {
          return new class extends $U1 {
            constructor() {
              super(void 0, action, { ...options3, icon: false, label: false, keybindingNotRenderedWithLabel: true });
            }
          }();
        }
        if (action.id === $FMb.ID || action.id === $GMb.ID) {
          return new class extends $U1 {
            constructor() {
              super(void 0, action, { ...options3, icon: false, label: true, keybindingNotRenderedWithLabel: true });
              this.a = this.q.add(new $4c());
            }
            set actionRunner(actionRunner) {
              super.actionRunner = actionRunner;
              const store = new $2c();
              store.add(actionRunner.onWillRun((_e) => {
                g.focus();
              }));
              store.add(actionRunner.onDidRun((e) => {
                if (e.action !== this.action) {
                  return;
                }
                if (entry === nextEntry) {
                  return;
                }
                const change = nextEntry.diffInfo.get().changes.at(0);
                return that.h.openEditor({
                  resource: nextEntry.modifiedURI,
                  options: {
                    selection: change && $9C.fromPositions({ lineNumber: change.original.startLineNumber, column: 1 }),
                    revealIfOpened: false,
                    revealIfVisible: false
                  }
                }, $nJ);
              }));
              this.a.value = store;
            }
            get actionRunner() {
              return super.actionRunner;
            }
          }();
        }
        if (action.id === "chatEditor.action.navigateNext" || action.id === "chatEditor.action.navigatePrevious") {
          return new class extends $U1 {
            constructor() {
              super(void 0, action, { ...options3, icon: true, label: false, keybindingNotRenderedWithLabel: true });
            }
            set actionRunner(_) {
              const next = action.id === "chatEditor.action.navigateNext" ? nextEntry : previousEntry;
              const direction = action.id === "chatEditor.action.navigateNext" ? "next" : "previous";
              super.actionRunner = new NextPreviousChangeActionRunner(g, cellDiffInfo, entry, next, direction, h3, deletedCellDecorator, focusedDiff);
            }
            get actionRunner() {
              return super.actionRunner;
            }
          }();
        }
        return void 0;
      }
    });
    this.B(_toolbar);
  }
  j() {
    if (!this.f) {
      this.g.getDomNode().appendChild(this.b);
      this.f = true;
    }
  }
  m() {
    if (this.f) {
      this.g.getDomNode().removeChild(this.b);
      this.f = false;
    }
  }
};
$JMb = __decorate([
  __param(6, $mJ),
  __param(7, $Pk)
], $JMb);
var NextPreviousChangeActionRunner = class extends $Vm {
  constructor(a, b, g, h3, j, n, s, t) {
    super();
    this.a = a;
    this.b = b;
    this.g = g;
    this.h = h3;
    this.j = j;
    this.n = n;
    this.s = s;
    this.t = t;
  }
  async u(_action, _context) {
    const viewModel = this.a.getViewModel();
    const activeCell = this.a.activeCellAndCodeEditor;
    const cellDiff = this.b.read(void 0);
    if (!viewModel || !cellDiff?.length || !activeCell && this.t.read(void 0)) {
      return this.D();
    }
    const nextDiff = this.z(cellDiff, viewModel);
    if (nextDiff && await this.y(nextDiff, viewModel)) {
      return;
    }
    return this.D();
  }
  /**
   * @returns `true` if focused to the next diff
   */
  async y(diff3, viewModel) {
    if (diff3.type === "delete") {
      const top2 = this.s.getTop(diff3.originalCellIndex);
      if (typeof top2 === "number") {
        this.t.set(diff3, void 0);
        this.a.setScrollTop(top2);
        return true;
      }
    } else {
      const index = diff3.modifiedCellIndex;
      this.t.set(diff3, void 0);
      await this.a.focusNotebookCell(viewModel.viewCells[index], "container");
      this.a.revealInViewAtTop(viewModel.viewCells[index]);
      viewModel.viewCells[index].updateEditState(CellEditState.Editing, "chatEdit");
      return true;
    }
    return false;
  }
  z(cellDiffInfo, viewModel) {
    const activeCell = this.a.activeCellAndCodeEditor;
    const currentCellIndex = activeCell ? viewModel.viewCells.findIndex((c) => c.handle === activeCell[0].handle) : this.j === "next" ? 0 : viewModel.viewCells.length - 1;
    if (this.t.read(void 0)) {
      const changes = cellDiffInfo.filter((d) => d.type !== "unchanged");
      const idx = changes.findIndex((d) => d === this.t.read(void 0));
      if (idx >= 0) {
        const next = this.j === "next" ? idx + 1 : idx - 1;
        if (next >= 0 && next < changes.length) {
          return changes[next];
        }
      }
    } else if (this.j === "next") {
      let currentIndex = 0;
      let next;
      cellDiffInfo.forEach((d, i2) => {
        if (next) {
          return;
        }
        if (d.type === "insert" || d.type === "modified") {
          if (d.modifiedCellIndex > currentCellIndex) {
            next = d;
          }
          currentIndex = d.modifiedCellIndex;
        } else if (d.type === "unchanged") {
          currentIndex = d.modifiedCellIndex;
        } else if (currentIndex >= currentCellIndex) {
          next = d;
        }
      });
      if (next) {
        return next;
      }
    } else {
      let currentIndex = 0;
      let previous;
      cellDiffInfo.forEach((d, i2) => {
        if (d.type === "insert" || d.type === "modified") {
          if (d.modifiedCellIndex < currentCellIndex) {
            previous = d;
          }
          currentIndex = d.modifiedCellIndex;
        } else if (d.type === "unchanged") {
          currentIndex = d.modifiedCellIndex;
        } else if (currentIndex <= currentCellIndex) {
          previous = d;
        }
      });
      if (previous) {
        return previous;
      }
    }
    if (this.C()) {
      return;
    }
    return this.j === "next" ? cellDiffInfo[0] : cellDiffInfo[cellDiffInfo.length - 1];
  }
  C() {
    return this.g !== this.h;
  }
  async D() {
    if (!this.C()) {
      return;
    }
    const change = this.h.diffInfo.get().changes.at(0);
    this.t.set(void 0, void 0);
    await this.n.openEditor({
      resource: this.h.modifiedURI,
      options: {
        selection: change && $9C.fromPositions({ lineNumber: change.original.startLineNumber, column: 1 }),
        revealIfOpened: false,
        revealIfVisible: false
      }
    }, $nJ);
  }
};

// out-build/vs/workbench/contrib/notebook/browser/notebookEditorExtensions.js
var EditorContributionRegistry2 = class _EditorContributionRegistry {
  static {
    this.INSTANCE = new _EditorContributionRegistry();
  }
  constructor() {
    this.a = [];
  }
  registerEditorContribution(id2, ctor) {
    this.a.push({ id: id2, ctor });
  }
  getEditorContributions() {
    return this.a.slice(0);
  }
};
function $iGb(id2, ctor) {
  EditorContributionRegistry2.INSTANCE.registerEditorContribution(id2, ctor);
}
var NotebookEditorExtensionsRegistry;
(function(NotebookEditorExtensionsRegistry2) {
  function getEditorContributions() {
    return EditorContributionRegistry2.INSTANCE.getEditorContributions();
  }
  NotebookEditorExtensionsRegistry2.getEditorContributions = getEditorContributions;
  function getSomeEditorContributions(ids) {
    return EditorContributionRegistry2.INSTANCE.getEditorContributions().filter((c) => ids.indexOf(c.id) >= 0);
  }
  NotebookEditorExtensionsRegistry2.getSomeEditorContributions = getSomeEditorContributions;
})(NotebookEditorExtensionsRegistry || (NotebookEditorExtensionsRegistry = {}));

// out-build/vs/workbench/contrib/notebook/browser/contrib/chatEdit/notebookChatEditController.js
var $KMb = new $nn("chat.hasNotebookEditorModifications", void 0, localize(8110, null));
var $LMb = class $LMb2 extends $3c {
  static {
    this.ID = "workbench.notebook.chatEditorController";
  }
  constructor(notebookEditor, instantiationService, configurationService) {
    super();
    this.B(instantiationService.createInstance(NotebookChatEditorController, notebookEditor));
  }
};
$LMb = __decorate([
  __param(1, $Pk),
  __param(2, $kl)
], $LMb);
var NotebookChatEditorController = class NotebookChatEditorController2 extends $3c {
  constructor(f, g, h3, j, m, contextKeyService) {
    super();
    this.f = f;
    this.g = g;
    this.h = h3;
    this.j = j;
    this.m = m;
    this.c = $KMb.bindTo(contextKeyService);
    this.a = this.B(m.createInstance($XEb, f));
    this.b = this.B(m.createInstance($WEb, f));
    const notebookModel = $Dd(this.f.onDidChangeModel, (e) => e);
    const originalModel = $he("originalModel", void 0);
    const readyToRenderViewzones = $he("viewModelAttached", false);
    this.B(Event2.once(this.f.onDidAttachViewModel)(() => readyToRenderViewzones.set(true, void 0)));
    const onDidChangeVisibleRanges = $Kd($Dd(this.f.onDidChangeVisibleRanges, () => this.f.visibleRanges), 50);
    const decorators = /* @__PURE__ */ new Map();
    let updatedCellDecoratorsOnceBefore = false;
    let updatedDeletedInsertedDecoratorsOnceBefore = false;
    const clearDecorators = () => {
      $Xc(Array.from(decorators.values()));
      decorators.clear();
      this.a.clear();
      this.b.clear();
    };
    this.B($1c(() => clearDecorators()));
    let notebookSynchronizer;
    const entryObs = $2d((r2) => {
      const session = this.g.currentEditingSessionObs.read(r2);
      const model = notebookModel.read(r2);
      if (!model || !session) {
        return;
      }
      return session.readEntry(model.uri, r2);
    }).recomputeInitiallyAndOnChange(this.q);
    this.B($td((r2) => {
      const entry = entryObs.read(r2);
      const model = notebookModel.read(r2);
      if (!entry || !model || entry.state.read(r2) !== 0) {
        clearDecorators();
      }
    }));
    const notebookDiffInfo = $6d(this, (r2, store) => {
      const entry = entryObs.read(r2);
      const model = notebookModel.read(r2);
      if (!entry || !model) {
        if (notebookSynchronizer && model) {
          notebookSynchronizer.object.revert();
        }
        return $he("DefaultDiffIno", void 0);
      }
      notebookSynchronizer = notebookSynchronizer || this.B(this.j.getOrCreate(model));
      this.h.getOrCreate(entry, model.viewType).then((ref) => originalModel.set(this.B(ref).object, void 0));
      return notebookSynchronizer.object.diffInfo;
    }).recomputeInitiallyAndOnChange(this.q).flatten();
    const notebookCellDiffInfo = notebookDiffInfo.map((d) => d?.cellDiff);
    this.B(m.createInstance($IMb, f, notebookCellDiffInfo, this.a));
    this.B($td((r2) => {
      entryObs.read(r2);
      clearDecorators();
    }));
    this.B($td((r2) => {
      const diffs = notebookDiffInfo.read(r2);
      if (!diffs || !diffs.cellDiff.length) {
        clearDecorators();
        this.c.reset();
      } else {
        this.c.set(true);
      }
    }));
    this.B($td((r2) => {
      const entry = entryObs.read(r2);
      const diffInfo = notebookDiffInfo.read(r2);
      const modified = notebookModel.read(r2);
      const original = originalModel.read(r2);
      onDidChangeVisibleRanges.read(r2);
      if (!entry || !modified || !original || !diffInfo) {
        return;
      }
      if (diffInfo && updatedCellDecoratorsOnceBefore && diffInfo.modelVersion !== modified.versionId) {
        return;
      }
      updatedCellDecoratorsOnceBefore = true;
      const validDiffDecorators = /* @__PURE__ */ new Set();
      diffInfo.cellDiff.forEach((diff3) => {
        if (diff3.type === "modified") {
          const modifiedCell = modified.cells[diff3.modifiedCellIndex];
          const originalCell = original.cells[diff3.originalCellIndex];
          const editor = this.f.codeEditors.find(([vm]) => vm.handle === modifiedCell.handle)?.[1];
          if (editor) {
            const currentDecorator = decorators.get(modifiedCell);
            if (currentDecorator?.modifiedCell !== modifiedCell || currentDecorator?.originalCell !== originalCell) {
              currentDecorator?.dispose();
              const decorator = this.m.createInstance($VEb, f, modifiedCell, originalCell);
              decorators.set(modifiedCell, decorator);
              validDiffDecorators.add(decorator);
              this.B(editor.onDidDispose(() => {
                decorator.dispose();
                if (decorators.get(modifiedCell) === decorator) {
                  decorators.delete(modifiedCell);
                }
              }));
            } else if (currentDecorator) {
              validDiffDecorators.add(currentDecorator);
            }
          }
        }
      });
      decorators.forEach((v, cell) => {
        if (!validDiffDecorators.has(v)) {
          v.dispose();
          decorators.delete(cell);
        }
      });
    }));
    this.B($td((r2) => {
      const entry = entryObs.read(r2);
      const diffInfo = notebookDiffInfo.read(r2);
      const modified = notebookModel.read(r2);
      const original = originalModel.read(r2);
      const ready = readyToRenderViewzones.read(r2);
      if (!ready || !entry || !modified || !original || !diffInfo) {
        return;
      }
      if (diffInfo && updatedDeletedInsertedDecoratorsOnceBefore && diffInfo.modelVersion !== modified.versionId) {
        return;
      }
      updatedDeletedInsertedDecoratorsOnceBefore = true;
      this.b.apply(diffInfo.cellDiff);
      this.a.apply(diffInfo.cellDiff, original);
    }));
  }
};
NotebookChatEditorController = __decorate([
  __param(1, $$O),
  __param(2, $rFb),
  __param(3, $zMb),
  __param(4, $Pk),
  __param(5, $on)
], NotebookChatEditorController);
$iGb($LMb.ID, $LMb);
$SC(
  $rFb,
  $tFb,
  1
  /* InstantiationType.Delayed */
);
$SC(
  $zMb,
  $AMb,
  1
  /* InstantiationType.Delayed */
);
$SC(
  $SEb,
  $UEb,
  1
  /* InstantiationType.Delayed */
);

// out-build/vs/workbench/contrib/chat/browser/chatEditorOverlay.js
var $PMb_1;
var ChatEditorOverlayWidget = class ChatEditorOverlayWidget2 {
  constructor(j, editorService, instaService) {
    this.j = j;
    this.allowEditorOverflow = false;
    this.f = false;
    this.g = new $2c();
    this.h = $he(this, void 0);
    this.i = $he(this, { changeCount: -1, activeIdx: -1, entriesCount: -1 });
    this.a = document.createElement("div");
    this.a.classList.add("chat-editor-overlay-widget");
    const progressNode = document.createElement("div");
    progressNode.classList.add("chat-editor-overlay-progress");
    $bk(progressNode, $C1(ThemeIcon.modify($6l.loading, "spin")));
    this.b = $bk(progressNode, $("SPAN.busy-label"));
    this.a.appendChild(progressNode);
    const toolbarNode = document.createElement("div");
    toolbarNode.classList.add("chat-editor-overlay-toolbar");
    this.a.appendChild(toolbarNode);
    this.c = instaService.createInstance($4$, toolbarNode, $bJ.ChatEditingEditorContent, {
      telemetrySource: "chatEditor.overlayToolbar",
      hiddenItemStrategy: 0,
      toolbarOptions: {
        primaryGroup: () => true,
        useSeparatorsInPrimaryActions: true
      },
      menuOptions: { renderShortTitle: true },
      actionViewItemProvider: (action, options3) => {
        const that = this;
        if (action.id === $MMb) {
          return new class extends $U1 {
            constructor() {
              super(void 0, action, { ...options3, icon: false, label: true, keybindingNotRenderedWithLabel: true });
            }
            render(container2) {
              super.render(container2);
              container2.classList.add("label-item");
              this.q.add($td((r2) => {
                $Jg(this.L);
                const { changeCount, activeIdx } = that.i.read(r2);
                const n = activeIdx === -1 ? "?" : `${activeIdx + 1}`;
                const m = changeCount === -1 ? "?" : `${changeCount}`;
                this.L.innerText = localize(4882, null, n, m);
                this.G();
              }));
            }
            F() {
              const { changeCount, entriesCount } = that.i.get();
              if (changeCount === -1 || entriesCount === -1) {
                return void 0;
              } else if (changeCount === 1 && entriesCount === 1) {
                return localize(4883, null);
              } else if (changeCount === 1) {
                return localize(4884, null, entriesCount);
              } else if (entriesCount === 1) {
                return localize(4885, null, changeCount);
              } else {
                return localize(4886, null, changeCount, entriesCount);
              }
            }
            onClick(event, preserveFocus) {
              $EMb.get(that.j)?.unlockScroll();
            }
          }();
        }
        if (action.id === $FMb.ID || action.id === $GMb.ID) {
          return new class extends $U1 {
            constructor() {
              super(void 0, action, { ...options3, icon: false, label: true, keybindingNotRenderedWithLabel: true });
              this.a = this.q.add(new $4c());
            }
            set actionRunner(actionRunner) {
              super.actionRunner = actionRunner;
              const store = new $2c();
              store.add(actionRunner.onWillRun((_e) => {
                that.j.focus();
              }));
              store.add(actionRunner.onDidRun((e) => {
                if (e.action !== this.action) {
                  return;
                }
                const d = that.h.get();
                if (!d || d.entry === d.next) {
                  return;
                }
                const change = d.next.diffInfo.get().changes.at(0);
                return editorService.openEditor({
                  resource: d.next.modifiedURI,
                  options: {
                    selection: change && $9C.fromPositions({ lineNumber: change.original.startLineNumber, column: 1 }),
                    revealIfOpened: false,
                    revealIfVisible: false
                  }
                }, $nJ);
              }));
              this.a.value = store;
            }
            get actionRunner() {
              return super.actionRunner;
            }
          }();
        }
        return void 0;
      }
    });
  }
  dispose() {
    this.hide();
    this.g.dispose();
    this.c.dispose();
  }
  getId() {
    return "chatEditorOverlayWidget";
  }
  getDomNode() {
    return this.a;
  }
  getPosition() {
    return {
      preference: 1
      /* OverlayWidgetPositionPreference.BOTTOM_RIGHT_CORNER */
    };
  }
  show(session, activeEntry, next) {
    this.g.clear();
    this.h.set({ entry: activeEntry, next }, void 0);
    this.g.add($td((r2) => {
      const busy = activeEntry.isCurrentlyBeingModified.read(r2);
      this.a.classList.toggle("busy", busy);
    }));
    const slickRatio = $NMb.const(0);
    let t = Date.now();
    this.g.add($td((r2) => {
      const value = activeEntry.rewriteRatio.read(r2);
      slickRatio.changeAnimation((prev) => {
        const result = new $OMb(prev.getValue(), value, Date.now() - t);
        t = Date.now();
        return result;
      }, void 0);
      const value2 = slickRatio.getValue(r2);
      $dk(this.b, value === 0 ? localize(4887, null) : localize(4888, null, Math.round(value2 * 100)));
    }));
    this.g.add($td((r2) => {
      const position = $EMb.get(this.j)?.currentChange.read(r2);
      const entries2 = session.entries.read(r2);
      let changes = 0;
      let activeIdx = -1;
      for (const entry of entries2) {
        const diffInfo = entry.diffInfo.read(r2);
        if (activeIdx !== -1 || entry !== activeEntry) {
          changes += diffInfo.changes.length;
        } else {
          for (const change of diffInfo.changes) {
            if (position && change.modified.includes(position.lineNumber)) {
              activeIdx = changes;
            }
            changes += 1;
          }
        }
      }
      this.i.set({ changeCount: changes, activeIdx, entriesCount: entries2.length }, void 0);
    }));
    if (!this.f) {
      this.j.addOverlayWidget(this);
      this.f = true;
    }
  }
  hide() {
    $ce((tx) => {
      this.h.set(void 0, tx);
      this.i.set({ changeCount: -1, activeIdx: -1, entriesCount: -1 }, tx);
    });
    if (this.f) {
      this.j.removeOverlayWidget(this);
      this.f = false;
      this.g.clear();
    }
  }
};
ChatEditorOverlayWidget = __decorate([
  __param(1, $mJ),
  __param(2, $Pk)
], ChatEditorOverlayWidget);
var $MMb = "chatEditor.navigation.bearings";
$dJ.appendMenuItem($bJ.ChatEditingEditorContent, {
  command: {
    id: $MMb,
    title: localize(4889, null),
    precondition: $7m.false()
  },
  when: $KMb.negate(),
  group: "navigate",
  order: -1
});
var $NMb = class _$NMb {
  static const(value) {
    return new _$NMb($OMb.const(value));
  }
  constructor(initialValue) {
    this.a = $he(this, initialValue);
  }
  setAnimation(value, tx) {
    this.a.set(value, tx);
  }
  changeAnimation(fn, tx) {
    const value = fn(this.a.get());
    this.a.set(value, tx);
  }
  getValue(reader) {
    const value = this.a.read(reader);
    if (!value.isFinished()) {
      Scheduler.instance.invalidateOnNextAnimationFrame(reader);
    }
    return value.getValue();
  }
};
var Scheduler = class _Scheduler {
  constructor() {
    this.a = $Hd(this);
    this.b = false;
  }
  static {
    this.instance = new _Scheduler();
  }
  invalidateOnNextAnimationFrame(reader) {
    this.a.read(reader);
    if (!this.b) {
      this.b = true;
      $jj(getWindow(void 0), () => {
        this.b = false;
        this.a.trigger(void 0);
      });
    }
  }
};
var $OMb = class _$OMb {
  static const(value) {
    return new _$OMb(value, value, 0);
  }
  constructor(startValue, endValue, durationMs) {
    this.startValue = startValue;
    this.endValue = endValue;
    this.durationMs = durationMs;
    this.startTimeMs = Date.now();
    if (startValue === endValue) {
      this.durationMs = 0;
    }
  }
  isFinished() {
    return Date.now() >= this.startTimeMs + this.durationMs;
  }
  getValue() {
    const timePassed = Date.now() - this.startTimeMs;
    if (timePassed >= this.durationMs) {
      return this.endValue;
    }
    const value = easeOutExpo2(timePassed, this.startValue, this.endValue - this.startValue, this.durationMs);
    return value;
  }
};
function easeOutExpo2(passedTime, start, length, totalDuration) {
  return passedTime === totalDuration ? start + length : length * (-Math.pow(2, -10 * passedTime / totalDuration) + 1) + start;
}
var $PMb = class $PMb2 {
  static {
    $PMb_1 = this;
  }
  static {
    this.ID = "editor.contrib.chatOverlayController";
  }
  static get(editor) {
    return editor.getContribution($PMb_1.ID);
  }
  constructor(b, chatEditingService, instaService) {
    this.b = b;
    this.a = new $2c();
    const modelObs = $Dd(this.b.onDidChangeModel, () => this.b.getModel());
    const widget = this.a.add(instaService.createInstance(ChatEditorOverlayWidget, this.b));
    if (this.b.getOption(
      63
      /* EditorOption.inDiffEditor */
    )) {
      return;
    }
    this.a.add($td((r2) => {
      const model = modelObs.read(r2);
      const session = chatEditingService.currentEditingSessionObs.read(r2);
      if (!session || !model) {
        widget.hide();
        return;
      }
      const state = session.state.read(r2);
      if (state === 3) {
        widget.hide();
        return;
      }
      const entries2 = session.entries.read(r2);
      const idx = entries2.findIndex((e) => $oh(e.modifiedURI, model.uri));
      if (idx < 0) {
        widget.hide();
        return;
      }
      const isModifyingOrModified = entries2.some((e) => e.state.read(r2) === 0 || e.isCurrentlyBeingModified.read(r2));
      if (!isModifyingOrModified) {
        widget.hide();
        return;
      }
      const entry = entries2[idx];
      widget.show(session, entry, entries2[(idx + 1) % entries2.length]);
    }));
  }
  dispose() {
    this.a.dispose();
  }
};
$PMb = $PMb_1 = __decorate([
  __param(1, $$O),
  __param(2, $Pk)
], $PMb);

// out-build/vs/workbench/contrib/chat/common/chatColors.js
var $pGb = $5n("chat.requestBorder", { dark: new $Vn(new $Sn(255, 255, 255, 0.1)), light: new $Vn(new $Sn(0, 0, 0, 0.1)), hcDark: $ko, hcLight: $ko }, localize(5069, null));
var $qGb = $5n("chat.requestBackground", { dark: $0n($Ko, 0.62), light: $0n($Ko, 0.62), hcDark: $Qo, hcLight: null }, localize(5070, null));
var $rGb = $5n("chat.slashCommandBackground", { dark: "#34414b8f", light: "#d2ecff99", hcDark: $Vn.white, hcLight: $wo }, localize(5071, null));
var $sGb = $5n("chat.slashCommandForeground", { dark: "#40A6FF", light: "#306CA2", hcDark: $Vn.black, hcLight: $xo }, localize(5072, null));
var $tGb = $5n("chat.avatarBackground", { dark: "#1f1f1f", light: "#f2f2f2", hcDark: $Vn.black, hcLight: $Vn.white }, localize(5073, null));
var $uGb = $5n("chat.avatarForeground", $eo, localize(5074, null));
var $vGb = $5n("chat.editedFileForeground", {
  light: "#895503",
  dark: "#E2C08D",
  hcDark: "#E2C08D",
  hcLight: "#895503"
}, localize(5075, null));

// out-build/vs/workbench/contrib/chat/browser/chatContentParts/chatMarkdownAnchorService.js
var $RMb = $Qk("chatMarkdownAnchorService");
var $SMb = class extends $3c {
  constructor() {
    super(...arguments);
    this.a = [];
    this.b = void 0;
  }
  get lastFocusedAnchor() {
    return this.b;
  }
  c(widget) {
    this.b = widget;
  }
  register(widget) {
    if (this.a.some((other) => other === widget)) {
      throw new Error("Cannot register the same widget multiple times");
    }
    this.a.push(widget);
    const element = widget.getHTMLElement();
    if ($Mj(element)) {
      this.c(widget);
    }
    return $Zc($_i(element, "focus", () => this.c(widget)), $1c(() => this.a.splice(this.a.indexOf(widget), 1)), $_i(element, "blur", () => {
      if (this.b === widget) {
        this.c(void 0);
      }
    }));
  }
};

// out-build/vs/workbench/contrib/chat/browser/chatInlineAnchorWidget.js
var $QMb_1;
var $QMb = class $QMb2 extends $3c {
  static {
    $QMb_1 = this;
  }
  static {
    this.className = "chat-inline-anchor-widget";
  }
  constructor(c, inlineReference, originalContextKeyService, contextMenuService, fileService, hoverService, instantiationService, labelService, languageFeaturesService, languageService, menuService, modelService, textModelService, telemetryService) {
    super();
    this.c = c;
    this.inlineReference = inlineReference;
    this.b = false;
    this.data = "uri" in inlineReference.inlineReference ? inlineReference.inlineReference : "name" in inlineReference.inlineReference ? { kind: "symbol", symbol: inlineReference.inlineReference } : { uri: inlineReference.inlineReference };
    const contextKeyService = this.B(originalContextKeyService.createScoped(c));
    this.a = $LDb.bindTo(contextKeyService);
    const anchorId = new $sf($ps);
    c.classList.add($QMb_1.className, "show-file-icons");
    let iconText;
    let iconClasses;
    let location3;
    let updateContextKeys;
    if (this.data.kind === "symbol") {
      const symbol = this.data.symbol;
      location3 = this.data.symbol.location;
      iconText = this.data.symbol.name;
      iconClasses = ["codicon", ...$gdb(modelService, languageService, void 0, void 0, SymbolKinds.toIcon(symbol.kind))];
      this.B($_i(c, "click", () => {
        telemetryService.publicLog2("chat.inlineAnchor.openSymbol", {
          anchorId: anchorId.value
        });
      }));
      this.q.add(instantiationService.invokeFunction((accessor) => $ODb(accessor, c, contextKeyService, { value: symbol.location, name: symbol.name, kind: symbol.kind }, $bJ.ChatInlineSymbolAnchorContext)));
    } else {
      location3 = this.data;
      const label3 = labelService.getUriBasenameLabel(location3.uri);
      iconText = location3.range && this.data.kind !== "symbol" ? `${label3}#${location3.range.startLineNumber}-${location3.range.endLineNumber}` : label3;
      const fileKind = location3.uri.path.endsWith("/") ? FileKind.FOLDER : FileKind.FILE;
      iconClasses = $gdb(modelService, languageService, location3.uri, fileKind);
      const isFolderContext = $7sb.bindTo(contextKeyService);
      fileService.stat(location3.uri).then((stat) => {
        isFolderContext.set(stat.isDirectory);
      }).catch(() => {
      });
      this.B($_i(c, "click", () => {
        telemetryService.publicLog2("chat.inlineAnchor.openResource", {
          anchorId: anchorId.value
        });
      }));
      this.B($_i(c, $7j.CONTEXT_MENU, async (domEvent) => {
        const event = new $lf(getWindow(domEvent), domEvent);
        $9j.stop(domEvent, true);
        try {
          await updateContextKeys?.();
        } catch (e) {
          console.error(e);
        }
        if (this.b) {
          return;
        }
        contextMenuService.showContextMenu({
          contextKeyService,
          getAnchor: () => event,
          getActions: () => {
            const menu = menuService.getMenuActions($bJ.ChatInlineResourceAnchorContext, contextKeyService, { arg: location3.uri });
            return $P$(menu);
          }
        });
      }));
    }
    const resourceContextKey = this.B(new $lqb(contextKeyService, fileService, languageService, modelService));
    resourceContextKey.set(location3.uri);
    this.a.set(location3.uri.toString());
    const iconEl = $("span.icon");
    iconEl.classList.add(...iconClasses);
    c.replaceChildren(iconEl, $("span.icon-label", {}, iconText));
    const fragment = location3.range ? `${location3.range.startLineNumber},${location3.range.startColumn}` : "";
    c.setAttribute("data-href", (fragment ? location3.uri.with({ fragment }) : location3.uri).toString());
    const relativeLabel = labelService.getUriLabel(location3.uri, { relative: true });
    this.B(hoverService.setupManagedHover($JZ("element"), c, relativeLabel));
    if (this.data.kind !== "symbol") {
      c.draggable = true;
      this.B($_i(c, "dragstart", (e) => {
        const stat = {
          resource: location3.uri,
          selection: location3.range
        };
        instantiationService.invokeFunction((accessor) => $Eob(accessor, [stat], e));
        e.dataTransfer?.setDragImage(c, 0, 0);
      }));
    }
  }
  dispose() {
    this.b = true;
    super.dispose();
  }
  getHTMLElement() {
    return this.c;
  }
};
$QMb = $QMb_1 = __decorate([
  __param(2, $on),
  __param(3, $50),
  __param(4, $km),
  __param(5, $5$),
  __param(6, $Pk),
  __param(7, $ZI),
  __param(8, $mP),
  __param(9, $1E),
  __param(10, $cJ),
  __param(11, $sG),
  __param(12, $oG),
  __param(13, $zv)
], $QMb);
$hJ(class AddFileToChatAction extends $gJ {
  static {
    this.id = "chat.inlineResourceAnchor.addFileToChat";
  }
  constructor() {
    super({
      id: AddFileToChatAction.id,
      title: localize2(4913, "Add File to Chat"),
      menu: [{
        id: $bJ.ChatInlineResourceAnchorContext,
        group: "chat",
        order: 1,
        when: $7sb.negate()
      }]
    });
  }
  async run(accessor, resource) {
    const chatWidgetService = accessor.get($2Nb);
    const variablesService = accessor.get($kO);
    const widget = chatWidgetService.lastFocusedWidget;
    if (!widget) {
      return;
    }
    variablesService.attachContext("file", resource, widget.location);
  }
});
$hJ(class CopyResourceAction extends $gJ {
  static {
    this.id = "chat.inlineResourceAnchor.copyResource";
  }
  constructor() {
    super({
      id: CopyResourceAction.id,
      title: localize2(4914, "Copy"),
      f1: false,
      precondition: $LDb,
      keybinding: {
        weight: 200,
        primary: 2048 | 33
      }
    });
  }
  async run(accessor) {
    const chatWidgetService = accessor.get($RMb);
    const clipboardService = accessor.get($30);
    const anchor = chatWidgetService.lastFocusedAnchor;
    if (!anchor) {
      return;
    }
    const resource = anchor.data.kind === "symbol" ? anchor.data.symbol.location.uri : anchor.data.uri;
    clipboardService.writeResources([resource]);
  }
});
$hJ(class OpenToSideResourceAction extends $gJ {
  static {
    this.id = "chat.inlineResourceAnchor.openToSide";
  }
  constructor() {
    super({
      id: OpenToSideResourceAction.id,
      title: localize2(4915, "Open to the Side"),
      f1: false,
      precondition: $LDb,
      keybinding: {
        weight: 400 + 2,
        primary: 2048 | 3,
        mac: {
          primary: 256 | 3
          /* KeyCode.Enter */
        }
      },
      menu: [$bJ.ChatInlineSymbolAnchorContext, $bJ.ChatInputSymbolAttachmentContext].map((id2) => ({
        id: id2,
        group: "navigation",
        order: 1
      }))
    });
  }
  async run(accessor, arg) {
    const editorService = accessor.get($mJ);
    const target = this.a(accessor, arg);
    if (!target) {
      return;
    }
    const input = URI.isUri(target) ? { resource: target } : {
      resource: target.uri,
      options: {
        selection: {
          startColumn: target.range.startColumn,
          startLineNumber: target.range.startLineNumber
        }
      }
    };
    await editorService.openEditors([input], $oJ);
  }
  a(accessor, arg) {
    const chatWidgetService = accessor.get($RMb);
    if (arg) {
      return arg;
    }
    const anchor = chatWidgetService.lastFocusedAnchor;
    if (!anchor) {
      return void 0;
    }
    return anchor.data.kind === "symbol" ? anchor.data.symbol.location : anchor.data.uri;
  }
});
$hJ(class GoToDefinitionAction2 extends $gJ {
  static {
    this.id = "chat.inlineSymbolAnchor.goToDefinition";
  }
  constructor() {
    super({
      id: GoToDefinitionAction2.id,
      title: {
        ...localize2(4916, "Go to Definition"),
        mnemonicTitle: localize(4909, null)
      },
      menu: [$bJ.ChatInlineSymbolAnchorContext, $bJ.ChatInputSymbolAttachmentContext].map((id2) => ({
        id: id2,
        group: "4_symbol_nav",
        order: 1.1,
        when: EditorContextKeys.hasDefinitionProvider
      }))
    });
  }
  async run(accessor, location3) {
    const editorService = accessor.get($U5);
    await openEditorWithSelection(editorService, location3);
    const action = new $rfb({ openToSide: false, openInPeek: false, muteMessage: true }, { title: { value: "", original: "" }, id: "", precondition: void 0 });
    return action.run(accessor);
  }
});
async function openEditorWithSelection(editorService, location3) {
  await editorService.openCodeEditor({
    resource: location3.uri,
    options: {
      selection: {
        startColumn: location3.range.startColumn,
        startLineNumber: location3.range.startLineNumber
      }
    }
  }, null);
}
async function runGoToCommand(accessor, command4, location3) {
  const editorService = accessor.get($U5);
  const commandService = accessor.get($sn);
  await openEditorWithSelection(editorService, location3);
  return commandService.executeCommand(command4);
}
$hJ(class GoToTypeDefinitionsAction extends $gJ {
  static {
    this.id = "chat.inlineSymbolAnchor.goToTypeDefinitions";
  }
  constructor() {
    super({
      id: GoToTypeDefinitionsAction.id,
      title: {
        ...localize2(4917, "Go to Type Definitions"),
        mnemonicTitle: localize(4910, null)
      },
      menu: [$bJ.ChatInlineSymbolAnchorContext, $bJ.ChatInputSymbolAttachmentContext].map((id2) => ({
        id: id2,
        group: "4_symbol_nav",
        order: 1.1,
        when: EditorContextKeys.hasTypeDefinitionProvider
      }))
    });
  }
  async run(accessor, location3) {
    return runGoToCommand(accessor, "editor.action.goToTypeDefinition", location3);
  }
});
$hJ(class GoToImplementations extends $gJ {
  static {
    this.id = "chat.inlineSymbolAnchor.goToImplementations";
  }
  constructor() {
    super({
      id: GoToImplementations.id,
      title: {
        ...localize2(4918, "Go to Implementations"),
        mnemonicTitle: localize(4911, null)
      },
      menu: [$bJ.ChatInlineSymbolAnchorContext, $bJ.ChatInputSymbolAttachmentContext].map((id2) => ({
        id: id2,
        group: "4_symbol_nav",
        order: 1.2,
        when: EditorContextKeys.hasImplementationProvider
      }))
    });
  }
  async run(accessor, location3) {
    return runGoToCommand(accessor, "editor.action.goToImplementation", location3);
  }
});
$hJ(class GoToReferencesAction2 extends $gJ {
  static {
    this.id = "chat.inlineSymbolAnchor.goToReferences";
  }
  constructor() {
    super({
      id: GoToReferencesAction2.id,
      title: {
        ...localize2(4919, "Go to References"),
        mnemonicTitle: localize(4912, null)
      },
      menu: [$bJ.ChatInlineSymbolAnchorContext, $bJ.ChatInputSymbolAttachmentContext].map((id2) => ({
        id: id2,
        group: "4_symbol_nav",
        order: 1.3,
        when: EditorContextKeys.hasReferenceProvider
      }))
    });
  }
  async run(accessor, location3) {
    return runGoToCommand(accessor, "editor.action.goToReferences", location3);
  }
});

// out-build/vs/workbench/contrib/chat/browser/chatMarkdownDecorationsRenderer.js
var decorationRefUrl = `http://_vscodedecoration_`;
var agentRefUrl = `http://_chatagent_`;
var agentSlashRefUrl = `http://_chatslash_`;
function $TMb(agent, isClickable, accessor) {
  const chatAgentNameService = accessor.get($3O);
  const chatAgentService = accessor.get($ZO);
  const isAllowed = chatAgentNameService.getAgentNameRestriction(agent);
  let name = `${isAllowed ? agent.name : $5O(agent)}`;
  const isDupe = isAllowed && chatAgentService.agentHasDupeName(agent.id);
  if (isDupe) {
    name += ` (${agent.publisherDisplayName})`;
  }
  const args2 = { agentId: agent.id, name, isClickable };
  return `[${agent.name}](${agentRefUrl}?${encodeURIComponent(JSON.stringify(args2))})`;
}
function $UMb(agent, command4) {
  const text2 = `${$yO}${command4.name}`;
  const args2 = { agentId: agent.id, command: command4.name };
  return `[${text2}](${agentSlashRefUrl}?${encodeURIComponent(JSON.stringify(args2))})`;
}
var $VMb = class $VMb2 {
  constructor(b, d, f, g, h3, i2, j, k, l, m, n, o) {
    this.b = b;
    this.d = d;
    this.f = f;
    this.g = g;
    this.h = h3;
    this.i = i2;
    this.j = j;
    this.k = k;
    this.l = l;
    this.m = m;
    this.n = n;
    this.o = o;
  }
  convertParsedRequestToMarkdown(parsedRequest) {
    let result = "";
    for (const part of parsedRequest.parts) {
      if (part instanceof $vO) {
        result += part.text;
      } else if (part instanceof $BO) {
        result += this.g.invokeFunction((accessor) => $TMb(part.agent, false, accessor));
      } else {
        result += this.p(part);
      }
    }
    return result;
  }
  p(part) {
    const uri = part instanceof $EO && part.data instanceof URI ? part.data : void 0;
    const title = uri ? this.m.getUriLabel(uri, { relative: true }) : part instanceof $DO ? part.slashCommand.detail : part instanceof $CO ? part.command.description : part instanceof $zO ? this.l.getVariable(part.variableName)?.description : part instanceof $AO ? this.n.getTool(part.toolId)?.userDescription : "";
    const args2 = { title };
    const text2 = part.text;
    return `[${text2}](${decorationRefUrl}?${encodeURIComponent(JSON.stringify(args2))})`;
  }
  walkTreeAndAnnotateReferenceLinks(content, element) {
    const store = new $2c();
    element.querySelectorAll("a").forEach((a) => {
      const href = a.getAttribute("data-href");
      if (href) {
        if (href.startsWith(agentRefUrl)) {
          let args2;
          try {
            args2 = JSON.parse(decodeURIComponent(href.slice(agentRefUrl.length + 1)));
          } catch (e) {
            this.d.error("Invalid chat widget render data JSON", $1m(e));
          }
          if (args2) {
            a.parentElement.replaceChild(this.q(args2, store), a);
          }
        } else if (href.startsWith(agentSlashRefUrl)) {
          let args2;
          try {
            args2 = JSON.parse(decodeURIComponent(href.slice(agentRefUrl.length + 1)));
          } catch (e) {
            this.d.error("Invalid chat slash command render data JSON", $1m(e));
          }
          if (args2) {
            a.parentElement.replaceChild(this.r(a.textContent, args2, store), a);
          }
        } else if (href.startsWith(decorationRefUrl)) {
          let args2;
          try {
            args2 = JSON.parse(decodeURIComponent(href.slice(decorationRefUrl.length + 1)));
          } catch (e) {
          }
          a.parentElement.replaceChild(this.t(a.textContent, args2, store), a);
        } else if (href.startsWith($4rb)) {
          this.s(content, href, a, store);
        } else if (href.startsWith("command:")) {
          this.u(a, href, this.b);
        }
      }
    });
    return store;
  }
  q(args2, store) {
    const nameWithLeader = `${$xO}${args2.name}`;
    let container2;
    if (args2.isClickable) {
      container2 = $("span.chat-agent-widget");
      const button = store.add(new $k2(container2, {
        buttonBackground: $Zn($rGb),
        buttonForeground: $Zn($sGb),
        buttonHoverBackground: void 0
      }));
      button.label = nameWithLeader;
      store.add(button.onDidClick(() => {
        const agent2 = this.f.getAgent(args2.agentId);
        const widget = this.j.lastFocusedWidget;
        if (!widget || !agent2) {
          return;
        }
        this.i.sendRequest(widget.viewModel.sessionId, agent2.metadata.sampleRequest ?? "", {
          location: widget.location,
          agentId: agent2.id,
          userSelectedModelId: widget.input.currentLanguageModel
        });
      }));
    } else {
      container2 = this.t(nameWithLeader, void 0, store);
    }
    const agent = this.f.getAgent(args2.agentId);
    const hover = new $sf(() => store.add(this.g.createInstance($IDb)));
    store.add(this.h.setupManagedHover($JZ("element"), container2, () => {
      hover.value.setAgent(args2.agentId);
      return hover.value.domNode;
    }, agent && $JDb(() => agent, this.k)));
    return container2;
  }
  r(name, args2, store) {
    const container2 = $("span.chat-agent-widget.chat-command-widget");
    const agent = this.f.getAgent(args2.agentId);
    const button = store.add(new $k2(container2, {
      buttonBackground: $Zn($rGb),
      buttonForeground: $Zn($sGb),
      buttonHoverBackground: void 0
    }));
    button.label = name;
    store.add(button.onDidClick(() => {
      const widget = this.j.lastFocusedWidget;
      if (!widget || !agent) {
        return;
      }
      const command4 = agent.slashCommands.find((c) => c.name === args2.command);
      this.i.sendRequest(widget.viewModel.sessionId, command4?.sampleRequest ?? "", {
        location: widget.location,
        agentId: agent.id,
        slashCommand: args2.command,
        userSelectedModelId: widget.input.currentLanguageModel
      });
    }));
    return container2;
  }
  s(content, href, a, store) {
    const fullUri = URI.parse(href);
    const data = content.inlineReferences?.[fullUri.path.slice(1)];
    if (!data) {
      this.d.error("Invalid chat widget render data JSON");
      return;
    }
    const inlineAnchor = store.add(this.g.createInstance($QMb, a, data));
    this.o.register(inlineAnchor);
  }
  t(name, args2, store) {
    const container2 = $("span.chat-resource-widget");
    const alias = $("span", void 0, name);
    if (args2?.title) {
      store.add(this.h.setupManagedHover($JZ("element"), container2, args2.title));
    }
    container2.appendChild(alias);
    return container2;
  }
  u(a, href, keybindingService) {
    const command4 = href.match(/command:([^\)]+)/)?.[1];
    if (command4) {
      const kb = keybindingService.lookupKeybinding(command4);
      if (kb) {
        const keybinding = kb.getLabel();
        if (keybinding) {
          a.textContent = `${a.textContent} (${keybinding})`;
        }
      }
    }
  }
};
$VMb = __decorate([
  __param(0, $Ty),
  __param(1, $wn),
  __param(2, $ZO),
  __param(3, $Pk),
  __param(4, $5$),
  __param(5, $qO),
  __param(6, $2Nb),
  __param(7, $sn),
  __param(8, $kO),
  __param(9, $ZI),
  __param(10, $mO),
  __param(11, $RMb)
], $VMb);

// out-build/vs/editor/common/services/modelService.js
var $BGb_1;
function MODEL_ID2(resource) {
  return resource.toString();
}
var ModelData2 = class {
  constructor(model, onWillDispose, onDidChangeLanguage) {
    this.model = model;
    this.c = new $2c();
    this.model = model;
    this.c.add(model.onWillDispose(() => onWillDispose(model)));
    this.c.add(model.onDidChangeLanguage((e) => onDidChangeLanguage(model, e)));
  }
  dispose() {
    this.c.dispose();
  }
};
var DEFAULT_EOL = $n || $m ? 1 : 2;
var DisposedModelInfo = class {
  constructor(uri, initialUndoRedoSnapshot, time, sharesUndoRedoStack, heapSize, sha1, versionId, alternativeVersionId) {
    this.uri = uri;
    this.initialUndoRedoSnapshot = initialUndoRedoSnapshot;
    this.time = time;
    this.sharesUndoRedoStack = sharesUndoRedoStack;
    this.heapSize = heapSize;
    this.sha1 = sha1;
    this.versionId = versionId;
    this.alternativeVersionId = alternativeVersionId;
  }
};
var $BGb = class $BGb2 extends $3c {
  static {
    $BGb_1 = this;
  }
  static {
    this.MAX_MEMORY_FOR_CLOSED_FILES_UNDO_STACK = 20 * 1024 * 1024;
  }
  constructor(r2, s, t, u) {
    super();
    this.r = r2;
    this.s = s;
    this.t = t;
    this.u = u;
    this.c = this.B(new $ze());
    this.onModelAdded = this.c.event;
    this.f = this.B(new $ze());
    this.onModelRemoved = this.f.event;
    this.g = this.B(new $ze());
    this.onModelLanguageChanged = this.g.event;
    this.h = /* @__PURE__ */ Object.create(null);
    this.j = {};
    this.m = /* @__PURE__ */ new Map();
    this.n = 0;
    this.B(this.r.onDidChangeConfiguration((e) => this.C(e)));
    this.C(void 0);
  }
  static w(config, isForSimpleWidget) {
    let tabSize = $HD.tabSize;
    if (config.editor && typeof config.editor.tabSize !== "undefined") {
      const parsedTabSize = parseInt(config.editor.tabSize, 10);
      if (!isNaN(parsedTabSize)) {
        tabSize = parsedTabSize;
      }
      if (tabSize < 1) {
        tabSize = 1;
      }
    }
    let indentSize = "tabSize";
    if (config.editor && typeof config.editor.indentSize !== "undefined" && config.editor.indentSize !== "tabSize") {
      const parsedIndentSize = parseInt(config.editor.indentSize, 10);
      if (!isNaN(parsedIndentSize)) {
        indentSize = Math.max(parsedIndentSize, 1);
      }
    }
    let insertSpaces = $HD.insertSpaces;
    if (config.editor && typeof config.editor.insertSpaces !== "undefined") {
      insertSpaces = config.editor.insertSpaces === "false" ? false : Boolean(config.editor.insertSpaces);
    }
    let newDefaultEOL = DEFAULT_EOL;
    const eol = config.eol;
    if (eol === "\r\n") {
      newDefaultEOL = 2;
    } else if (eol === "\n") {
      newDefaultEOL = 1;
    }
    let trimAutoWhitespace = $HD.trimAutoWhitespace;
    if (config.editor && typeof config.editor.trimAutoWhitespace !== "undefined") {
      trimAutoWhitespace = config.editor.trimAutoWhitespace === "false" ? false : Boolean(config.editor.trimAutoWhitespace);
    }
    let detectIndentation = $HD.detectIndentation;
    if (config.editor && typeof config.editor.detectIndentation !== "undefined") {
      detectIndentation = config.editor.detectIndentation === "false" ? false : Boolean(config.editor.detectIndentation);
    }
    let largeFileOptimizations = $HD.largeFileOptimizations;
    if (config.editor && typeof config.editor.largeFileOptimizations !== "undefined") {
      largeFileOptimizations = config.editor.largeFileOptimizations === "false" ? false : Boolean(config.editor.largeFileOptimizations);
    }
    let bracketPairColorizationOptions = $HD.bracketPairColorizationOptions;
    if (config.editor?.bracketPairColorization && typeof config.editor.bracketPairColorization === "object") {
      bracketPairColorizationOptions = {
        enabled: !!config.editor.bracketPairColorization.enabled,
        independentColorPoolPerBracketType: !!config.editor.bracketPairColorization.independentColorPoolPerBracketType
      };
    }
    return {
      isForSimpleWidget,
      tabSize,
      indentSize,
      insertSpaces,
      detectIndentation,
      defaultEOL: newDefaultEOL,
      trimAutoWhitespace,
      largeFileOptimizations,
      bracketPairColorizationOptions
    };
  }
  y(resource, language) {
    if (resource) {
      return this.s.getEOL(resource, language);
    }
    const eol = this.r.getValue("files.eol", { overrideIdentifier: language });
    if (eol && typeof eol === "string" && eol !== "auto") {
      return eol;
    }
    return OS === 3 || OS === 2 ? "\n" : "\r\n";
  }
  z() {
    const result = this.r.getValue("files.restoreUndoStack");
    if (typeof result === "boolean") {
      return result;
    }
    return true;
  }
  getCreationOptions(languageIdOrSelection, resource, isForSimpleWidget) {
    const language = typeof languageIdOrSelection === "string" ? languageIdOrSelection : languageIdOrSelection.languageId;
    let creationOptions = this.h[language + resource];
    if (!creationOptions) {
      const editor = this.r.getValue("editor", { overrideIdentifier: language, resource });
      const eol = this.y(resource, language);
      creationOptions = $BGb_1.w({ editor, eol }, isForSimpleWidget);
      this.h[language + resource] = creationOptions;
    }
    return creationOptions;
  }
  C(e) {
    const oldOptionsByLanguageAndResource = this.h;
    this.h = /* @__PURE__ */ Object.create(null);
    const keys = Object.keys(this.j);
    for (let i2 = 0, len = keys.length; i2 < len; i2++) {
      const modelId = keys[i2];
      const modelData = this.j[modelId];
      const language = modelData.model.getLanguageId();
      const uri = modelData.model.uri;
      if (e && !e.affectsConfiguration("editor", { overrideIdentifier: language, resource: uri }) && !e.affectsConfiguration("files.eol", { overrideIdentifier: language, resource: uri })) {
        continue;
      }
      const oldOptions = oldOptionsByLanguageAndResource[language + uri];
      const newOptions = this.getCreationOptions(language, uri, modelData.model.isForSimpleWidget);
      $BGb_1.D(modelData.model, newOptions, oldOptions);
    }
  }
  static D(model, newOptions, currentOptions) {
    if (currentOptions && currentOptions.defaultEOL !== newOptions.defaultEOL && model.getLineCount() === 1) {
      model.setEOL(
        newOptions.defaultEOL === 1 ? 0 : 1
        /* EndOfLineSequence.CRLF */
      );
    }
    if (currentOptions && currentOptions.detectIndentation === newOptions.detectIndentation && currentOptions.insertSpaces === newOptions.insertSpaces && currentOptions.tabSize === newOptions.tabSize && currentOptions.indentSize === newOptions.indentSize && currentOptions.trimAutoWhitespace === newOptions.trimAutoWhitespace && $Pv(currentOptions.bracketPairColorizationOptions, newOptions.bracketPairColorizationOptions)) {
      return;
    }
    if (newOptions.detectIndentation) {
      model.detectIndentation(newOptions.insertSpaces, newOptions.tabSize);
      model.updateOptions({
        trimAutoWhitespace: newOptions.trimAutoWhitespace,
        bracketColorizationOptions: newOptions.bracketPairColorizationOptions
      });
    } else {
      model.updateOptions({
        insertSpaces: newOptions.insertSpaces,
        tabSize: newOptions.tabSize,
        indentSize: newOptions.indentSize,
        trimAutoWhitespace: newOptions.trimAutoWhitespace,
        bracketColorizationOptions: newOptions.bracketPairColorizationOptions
      });
    }
  }
  // --- begin IModelService
  F(disposedModelData) {
    this.m.set(MODEL_ID2(disposedModelData.uri), disposedModelData);
    this.n += disposedModelData.heapSize;
  }
  G(resource) {
    const disposedModelData = this.m.get(MODEL_ID2(resource));
    if (disposedModelData) {
      this.n -= disposedModelData.heapSize;
    }
    this.m.delete(MODEL_ID2(resource));
    return disposedModelData;
  }
  H(maxModelsHeapSize) {
    if (this.n > maxModelsHeapSize) {
      const disposedModels = [];
      this.m.forEach((entry) => {
        if (!entry.sharesUndoRedoStack) {
          disposedModels.push(entry);
        }
      });
      disposedModels.sort((a, b) => a.time - b.time);
      while (disposedModels.length > 0 && this.n > maxModelsHeapSize) {
        const disposedModel = disposedModels.shift();
        this.G(disposedModel.uri);
        if (disposedModel.initialUndoRedoSnapshot !== null) {
          this.t.restoreSnapshot(disposedModel.initialUndoRedoSnapshot);
        }
      }
    }
  }
  I(value, languageIdOrSelection, resource, isForSimpleWidget) {
    const options3 = this.getCreationOptions(languageIdOrSelection, resource, isForSimpleWidget);
    const model = this.u.createInstance($QI, value, languageIdOrSelection, options3, resource);
    if (resource && this.m.has(MODEL_ID2(resource))) {
      const disposedModelData = this.G(resource);
      const elements = this.t.getElements(resource);
      const sha1Computer = this.P();
      const sha1IsEqual = sha1Computer.canComputeSHA1(model) ? sha1Computer.computeSHA1(model) === disposedModelData.sha1 : false;
      if (sha1IsEqual || disposedModelData.sharesUndoRedoStack) {
        for (const element of elements.past) {
          if ($SH(element) && element.matchesResource(resource)) {
            element.setModel(model);
          }
        }
        for (const element of elements.future) {
          if ($SH(element) && element.matchesResource(resource)) {
            element.setModel(model);
          }
        }
        this.t.setElementsValidFlag(resource, true, (element) => $SH(element) && element.matchesResource(resource));
        if (sha1IsEqual) {
          model._overwriteVersionId(disposedModelData.versionId);
          model._overwriteAlternativeVersionId(disposedModelData.alternativeVersionId);
          model._overwriteInitialUndoRedoSnapshot(disposedModelData.initialUndoRedoSnapshot);
        }
      } else {
        if (disposedModelData.initialUndoRedoSnapshot !== null) {
          this.t.restoreSnapshot(disposedModelData.initialUndoRedoSnapshot);
        }
      }
    }
    const modelId = MODEL_ID2(model.uri);
    if (this.j[modelId]) {
      throw new Error("ModelService: Cannot add model because it already exists!");
    }
    const modelData = new ModelData2(model, (model2) => this.N(model2), (model2, e) => this.O(model2, e));
    this.j[modelId] = modelData;
    return modelData;
  }
  updateModel(model, value) {
    const options3 = this.getCreationOptions(model.getLanguageId(), model.uri, model.isForSimpleWidget);
    const { textBuffer, disposable } = $PI(value, options3.defaultEOL);
    if (model.equalsTextBuffer(textBuffer)) {
      disposable.dispose();
      return;
    }
    model.pushStackElement();
    model.pushEOL(
      textBuffer.getEOL() === "\r\n" ? 1 : 0
      /* EndOfLineSequence.LF */
    );
    model.pushEditOperations([], $BGb_1._computeEdits(model, textBuffer), () => []);
    model.pushStackElement();
    disposable.dispose();
  }
  static J(a, aLen, aDelta, b, bLen, bDelta) {
    const maxResult = Math.min(aLen, bLen);
    let result = 0;
    for (let i2 = 0; i2 < maxResult && a.getLineContent(aDelta + i2) === b.getLineContent(bDelta + i2); i2++) {
      result++;
    }
    return result;
  }
  static L(a, aLen, aDelta, b, bLen, bDelta) {
    const maxResult = Math.min(aLen, bLen);
    let result = 0;
    for (let i2 = 0; i2 < maxResult && a.getLineContent(aDelta + aLen - i2) === b.getLineContent(bDelta + bLen - i2); i2++) {
      result++;
    }
    return result;
  }
  /**
   * Compute edits to bring `model` to the state of `textSource`.
   */
  static _computeEdits(model, textBuffer) {
    const modelLineCount = model.getLineCount();
    const textBufferLineCount = textBuffer.getLineCount();
    const commonPrefix = this.J(model, modelLineCount, 1, textBuffer, textBufferLineCount, 1);
    if (modelLineCount === textBufferLineCount && commonPrefix === modelLineCount) {
      return [];
    }
    const commonSuffix = this.L(model, modelLineCount - commonPrefix, commonPrefix, textBuffer, textBufferLineCount - commonPrefix, commonPrefix);
    let oldRange;
    let newRange;
    if (commonSuffix > 0) {
      oldRange = new $9C(commonPrefix + 1, 1, modelLineCount - commonSuffix + 1, 1);
      newRange = new $9C(commonPrefix + 1, 1, textBufferLineCount - commonSuffix + 1, 1);
    } else if (commonPrefix > 0) {
      oldRange = new $9C(commonPrefix, model.getLineMaxColumn(commonPrefix), modelLineCount, model.getLineMaxColumn(modelLineCount));
      newRange = new $9C(commonPrefix, 1 + textBuffer.getLineLength(commonPrefix), textBufferLineCount, 1 + textBuffer.getLineLength(textBufferLineCount));
    } else {
      oldRange = new $9C(1, 1, modelLineCount, model.getLineMaxColumn(modelLineCount));
      newRange = new $9C(1, 1, textBufferLineCount, 1 + textBuffer.getLineLength(textBufferLineCount));
    }
    return [$bD.replaceMove(oldRange, textBuffer.getValueInRange(
      newRange,
      0
      /* EndOfLinePreference.TextDefined */
    ))];
  }
  createModel(value, languageSelection, resource, isForSimpleWidget = false) {
    let modelData;
    if (languageSelection) {
      modelData = this.I(value, languageSelection, resource, isForSimpleWidget);
    } else {
      modelData = this.I(value, $KF, resource, isForSimpleWidget);
    }
    this.c.fire(modelData.model);
    return modelData.model;
  }
  destroyModel(resource) {
    const modelData = this.j[MODEL_ID2(resource)];
    if (!modelData) {
      return;
    }
    modelData.model.dispose();
  }
  getModels() {
    const ret = [];
    const keys = Object.keys(this.j);
    for (let i2 = 0, len = keys.length; i2 < len; i2++) {
      const modelId = keys[i2];
      ret.push(this.j[modelId].model);
    }
    return ret;
  }
  getModel(resource) {
    const modelId = MODEL_ID2(resource);
    const modelData = this.j[modelId];
    if (!modelData) {
      return null;
    }
    return modelData.model;
  }
  // --- end IModelService
  M(resource) {
    return resource.scheme === Schemas.file || resource.scheme === Schemas.vscodeRemote || resource.scheme === Schemas.vscodeUserData || resource.scheme === Schemas.vscodeNotebookCell || resource.scheme === "fake-fs";
  }
  N(model) {
    const modelId = MODEL_ID2(model.uri);
    const modelData = this.j[modelId];
    const sharesUndoRedoStack = this.t.getUriComparisonKey(model.uri) !== model.uri.toString();
    let maintainUndoRedoStack = false;
    let heapSize = 0;
    if (sharesUndoRedoStack || this.z() && this.M(model.uri)) {
      const elements = this.t.getElements(model.uri);
      if (elements.past.length > 0 || elements.future.length > 0) {
        for (const element of elements.past) {
          if ($SH(element) && element.matchesResource(model.uri)) {
            maintainUndoRedoStack = true;
            heapSize += element.heapSize(model.uri);
            element.setModel(model.uri);
          }
        }
        for (const element of elements.future) {
          if ($SH(element) && element.matchesResource(model.uri)) {
            maintainUndoRedoStack = true;
            heapSize += element.heapSize(model.uri);
            element.setModel(model.uri);
          }
        }
      }
    }
    const maxMemory = $BGb_1.MAX_MEMORY_FOR_CLOSED_FILES_UNDO_STACK;
    const sha1Computer = this.P();
    if (!maintainUndoRedoStack) {
      if (!sharesUndoRedoStack) {
        const initialUndoRedoSnapshot = modelData.model.getInitialUndoRedoSnapshot();
        if (initialUndoRedoSnapshot !== null) {
          this.t.restoreSnapshot(initialUndoRedoSnapshot);
        }
      }
    } else if (!sharesUndoRedoStack && (heapSize > maxMemory || !sha1Computer.canComputeSHA1(model))) {
      const initialUndoRedoSnapshot = modelData.model.getInitialUndoRedoSnapshot();
      if (initialUndoRedoSnapshot !== null) {
        this.t.restoreSnapshot(initialUndoRedoSnapshot);
      }
    } else {
      this.H(maxMemory - heapSize);
      this.t.setElementsValidFlag(model.uri, false, (element) => $SH(element) && element.matchesResource(model.uri));
      this.F(new DisposedModelInfo(model.uri, modelData.model.getInitialUndoRedoSnapshot(), Date.now(), sharesUndoRedoStack, heapSize, sha1Computer.computeSHA1(model), model.getVersionId(), model.getAlternativeVersionId()));
    }
    delete this.j[modelId];
    modelData.dispose();
    delete this.h[model.getLanguageId() + model.uri];
    this.f.fire(model);
  }
  O(model, e) {
    const oldLanguageId = e.oldLanguage;
    const newLanguageId = model.getLanguageId();
    const oldOptions = this.getCreationOptions(oldLanguageId, model.uri, model.isForSimpleWidget);
    const newOptions = this.getCreationOptions(newLanguageId, model.uri, model.isForSimpleWidget);
    $BGb_1.D(model, newOptions, oldOptions);
    this.g.fire({ model, oldLanguageId });
  }
  P() {
    return new $CGb();
  }
};
$BGb = $BGb_1 = __decorate([
  __param(0, $kl),
  __param(1, $AG),
  __param(2, $_F),
  __param(3, $Pk)
], $BGb);
var $CGb = class _$CGb {
  static {
    this.MAX_MODEL_SIZE = 10 * 1024 * 1024;
  }
  // takes 200ms to compute a sha1 on a 10MB model on a new machine
  canComputeSHA1(model) {
    return model.getValueLength() <= _$CGb.MAX_MODEL_SIZE;
  }
  computeSHA1(model) {
    const shaComputer = new $3i();
    const snapshot = model.createSnapshot();
    let text2;
    while (text2 = snapshot.read()) {
      shaComputer.update(text2);
    }
    return shaComputer.digest();
  }
};

// out-build/vs/workbench/services/textMate/common/TMHelper.js
function $DGb(theme, scopes, onlyColorRules = true) {
  for (let i2 = scopes.length - 1; i2 >= 0; i2--) {
    const parentScopes = scopes.slice(0, i2);
    const scope = scopes[i2];
    const r2 = findMatchingThemeRule2(theme, scope, parentScopes, onlyColorRules);
    if (r2) {
      return r2;
    }
  }
  return null;
}
function findMatchingThemeRule2(theme, scope, parentScopes, onlyColorRules) {
  let result = null;
  for (let i2 = theme.tokenColors.length - 1; i2 >= 0; i2--) {
    const rule = theme.tokenColors[i2];
    if (onlyColorRules && !rule.settings.foreground) {
      continue;
    }
    let selectors;
    if (typeof rule.scope === "string") {
      selectors = rule.scope.split(/,/).map((scope2) => scope2.trim());
    } else if (Array.isArray(rule.scope)) {
      selectors = rule.scope;
    } else {
      continue;
    }
    for (let j = 0, lenJ = selectors.length; j < lenJ; j++) {
      const rawSelector = selectors[j];
      const themeRule = new $EGb(rawSelector, rule.settings);
      if (themeRule.matches(scope, parentScopes)) {
        if (themeRule.isMoreSpecific(result)) {
          result = themeRule;
        }
      }
    }
  }
  return result;
}
var $EGb = class _$EGb {
  constructor(rawSelector, settings) {
    this.rawSelector = rawSelector;
    this.settings = settings;
    const rawSelectorPieces = this.rawSelector.split(/ /);
    this.scope = rawSelectorPieces[rawSelectorPieces.length - 1];
    this.parentScopes = rawSelectorPieces.slice(0, rawSelectorPieces.length - 1);
  }
  matches(scope, parentScopes) {
    return _$EGb.e(this.scope, this.parentScopes, scope, parentScopes);
  }
  static c(a, b) {
    if (a === null && b === null) {
      return 0;
    }
    if (a === null) {
      return -1;
    }
    if (b === null) {
      return 1;
    }
    if (a.scope.length !== b.scope.length) {
      return a.scope.length - b.scope.length;
    }
    const aParentScopesLen = a.parentScopes.length;
    const bParentScopesLen = b.parentScopes.length;
    if (aParentScopesLen !== bParentScopesLen) {
      return aParentScopesLen - bParentScopesLen;
    }
    for (let i2 = 0; i2 < aParentScopesLen; i2++) {
      const aLen = a.parentScopes[i2].length;
      const bLen = b.parentScopes[i2].length;
      if (aLen !== bLen) {
        return aLen - bLen;
      }
    }
    return 0;
  }
  isMoreSpecific(other) {
    return _$EGb.c(this, other) > 0;
  }
  static d(selectorScope, scope) {
    const selectorPrefix = selectorScope + ".";
    if (selectorScope === scope || scope.substring(0, selectorPrefix.length) === selectorPrefix) {
      return true;
    }
    return false;
  }
  static e(selectorScope, selectorParentScopes, scope, parentScopes) {
    if (!this.d(selectorScope, scope)) {
      return false;
    }
    let selectorParentIndex = selectorParentScopes.length - 1;
    let parentIndex = parentScopes.length - 1;
    while (selectorParentIndex >= 0 && parentIndex >= 0) {
      if (this.d(selectorParentScopes[selectorParentIndex], parentScopes[parentIndex])) {
        selectorParentIndex--;
      }
      parentIndex--;
    }
    if (selectorParentIndex === -1) {
      return true;
    }
    return false;
  }
};

// out-build/vs/workbench/services/textMate/browser/textMateTokenizationFeature.js
var $FGb = $Qk("textMateTokenizationFeature");

// out-build/vs/workbench/contrib/codeEditor/browser/inspectEditorTokens/inspectEditorTokens.js
var $7Gb_1;
var $100 = $;
var $7Gb = class $7Gb2 extends $3c {
  static {
    $7Gb_1 = this;
  }
  static {
    this.ID = "editor.contrib.inspectEditorTokens";
  }
  static get(editor) {
    return editor.getContribution($7Gb_1.ID);
  }
  constructor(editor, textMateService, treeSitterService, languageService, themeService, notificationService, configurationService, languageFeaturesService) {
    super();
    this.a = editor;
    this.b = textMateService;
    this.c = treeSitterService;
    this.f = themeService;
    this.g = languageService;
    this.h = notificationService;
    this.j = configurationService;
    this.m = languageFeaturesService;
    this.n = null;
    this.B(this.a.onDidChangeModel((e) => this.stop()));
    this.B(this.a.onDidChangeModelLanguage((e) => this.stop()));
    this.B(this.a.onKeyUp((e) => e.keyCode === 9 && this.stop()));
  }
  dispose() {
    this.stop();
    super.dispose();
  }
  launch() {
    if (this.n) {
      return;
    }
    if (!this.a.hasModel()) {
      return;
    }
    if (this.a.getModel().uri.scheme === Schemas.vscodeNotebookCell) {
      return;
    }
    this.n = new InspectEditorTokensWidget(this.a, this.b, this.c, this.g, this.f, this.h, this.j, this.m);
  }
  stop() {
    if (this.n) {
      this.n.dispose();
      this.n = null;
    }
  }
  toggle() {
    if (!this.n) {
      this.launch();
    } else {
      this.stop();
    }
  }
};
$7Gb = $7Gb_1 = __decorate([
  __param(1, $FGb),
  __param(2, $HI),
  __param(3, $1E),
  __param(4, $rwb),
  __param(5, $PJ),
  __param(6, $kl),
  __param(7, $mP)
], $7Gb);
var InspectEditorTokens = class extends $Z5 {
  constructor() {
    super({
      id: "editor.action.inspectTMScopes",
      label: localize2(5201, "Developer: Inspect Editor Tokens and Scopes"),
      precondition: void 0
    });
  }
  run(accessor, editor) {
    const controller = $7Gb.get(editor);
    controller?.toggle();
  }
};
function renderTokenText(tokenText) {
  if (tokenText.length > 40) {
    tokenText = tokenText.substr(0, 20) + "\u2026" + tokenText.substr(tokenText.length - 20);
  }
  let result = "";
  for (let charIndex = 0, len = tokenText.length; charIndex < len; charIndex++) {
    const charCode = tokenText.charCodeAt(charIndex);
    switch (charCode) {
      case 9:
        result += "\u2192";
        break;
      case 32:
        result += "\xB7";
        break;
      default:
        result += String.fromCharCode(charCode);
    }
  }
  return result;
}
var InspectEditorTokensWidget = class _InspectEditorTokensWidget extends $3c {
  static {
    this.a = "editor.contrib.inspectEditorTokensWidget";
  }
  constructor(editor, textMateService, treeSitterService, languageService, themeService, notificationService, configurationService, languageFeaturesService) {
    super();
    this.allowEditorOverflow = true;
    this.b = false;
    this.c = editor;
    this.f = languageService;
    this.g = themeService;
    this.h = textMateService;
    this.j = treeSitterService;
    this.m = notificationService;
    this.n = configurationService;
    this.r = languageFeaturesService;
    this.s = this.c.getModel();
    this.u = document.createElement("div");
    this.u.className = "token-inspect-widget";
    this.w = new $ad();
    this.y(this.c.getPosition());
    this.B(this.c.onDidChangeCursorPosition((e) => this.y(this.c.getPosition())));
    this.B(themeService.onDidColorThemeChange((_) => this.y(this.c.getPosition())));
    this.B(configurationService.onDidChangeConfiguration((e) => e.affectsConfiguration("editor.semanticHighlighting.enabled") && this.y(this.c.getPosition())));
    this.c.addContentWidget(this);
  }
  dispose() {
    this.b = true;
    this.c.removeContentWidget(this);
    this.w.cancel();
    super.dispose();
  }
  getId() {
    return _InspectEditorTokensWidget.a;
  }
  y(position) {
    const grammar = this.h.createTokenizer(this.s.getLanguageId());
    const semanticTokens = this.L(position);
    const tree = this.j.getParseResult(this.s);
    $$i(this.u);
    this.u.appendChild(document.createTextNode(localize(5200, null)));
    Promise.all([grammar, semanticTokens]).then(([grammar2, semanticTokens2]) => {
      if (this.b) {
        return;
      }
      this.C(grammar2, semanticTokens2, tree?.f, position);
      this.u.style.maxWidth = `${Math.max(this.c.getLayoutInfo().width * 0.66, 500)}px`;
      this.c.layoutContentWidget(this);
    }, (err) => {
      this.m.warn(err);
      setTimeout(() => {
        $7Gb.get(this.c)?.stop();
      });
    });
  }
  z() {
    const setting = this.n.getValue($hkb, { overrideIdentifier: this.s.getLanguageId(), resource: this.s.uri })?.enabled;
    if (typeof setting === "boolean") {
      return setting;
    }
    return this.g.getColorTheme().semanticHighlighting;
  }
  C(grammar, semanticTokens, tree, position) {
    const textMateTokenInfo = grammar && this.H(grammar, position);
    const semanticTokenInfo = semanticTokens && this.M(semanticTokens, position);
    const treeSitterTokenInfo = tree && this.O(tree, position);
    if (!textMateTokenInfo && !semanticTokenInfo && !treeSitterTokenInfo) {
      $dk(this.u, "No grammar or semantic tokens available.");
      return;
    }
    const tmMetadata = textMateTokenInfo?.metadata;
    const semMetadata = semanticTokenInfo?.metadata;
    const semTokenText = semanticTokenInfo && renderTokenText(this.s.getValueInRange(semanticTokenInfo.range));
    const tmTokenText = textMateTokenInfo && renderTokenText(this.s.getLineContent(position.lineNumber).substring(textMateTokenInfo.token.startIndex, textMateTokenInfo.token.endIndex));
    const tokenText = semTokenText || tmTokenText || "";
    $dk(this.u, $100("h2.tiw-token", void 0, tokenText, $100("span.tiw-token-length", void 0, `${tokenText.length} ${tokenText.length === 1 ? "char" : "chars"}`)));
    $bk(this.u, $100("hr.tiw-metadata-separator", { "style": "clear:both" }));
    $bk(this.u, $100("table.tiw-metadata-table", void 0, $100("tbody", void 0, $100("tr", void 0, $100("td.tiw-metadata-key", void 0, "language"), $100("td.tiw-metadata-value", void 0, tmMetadata?.languageId || "")), $100("tr", void 0, $100("td.tiw-metadata-key", void 0, "standard token type"), $100("td.tiw-metadata-value", void 0, this.G(
      tmMetadata?.tokenType || 0
      /* StandardTokenType.Other */
    ))), ...this.D(semMetadata, tmMetadata))));
    if (semanticTokenInfo) {
      $bk(this.u, $100("hr.tiw-metadata-separator"));
      const table = $bk(this.u, $100("table.tiw-metadata-table", void 0));
      const tbody = $bk(table, $100("tbody", void 0, $100("tr", void 0, $100("td.tiw-metadata-key", void 0, "semantic token type"), $100("td.tiw-metadata-value", void 0, semanticTokenInfo.type))));
      if (semanticTokenInfo.modifiers.length) {
        $bk(tbody, $100("tr", void 0, $100("td.tiw-metadata-key", void 0, "modifiers"), $100("td.tiw-metadata-value", void 0, semanticTokenInfo.modifiers.join(" "))));
      }
      if (semanticTokenInfo.metadata) {
        const properties = ["foreground", "bold", "italic", "underline", "strikethrough"];
        const propertiesByDefValue = {};
        const allDefValues = new Array();
        for (const property of properties) {
          if (semanticTokenInfo.metadata[property] !== void 0) {
            const definition = semanticTokenInfo.definitions[property];
            const defValue = this.P(definition, property);
            const defValueStr = defValue.map((el) => $Uj(el) ? el.outerHTML : el).join();
            let properties2 = propertiesByDefValue[defValueStr];
            if (!properties2) {
              propertiesByDefValue[defValueStr] = properties2 = [];
              allDefValues.push([defValue, defValueStr]);
            }
            properties2.push(property);
          }
        }
        for (const [defValue, defValueStr] of allDefValues) {
          $bk(tbody, $100("tr", void 0, $100("td.tiw-metadata-key", void 0, propertiesByDefValue[defValueStr].join(", ")), $100("td.tiw-metadata-value", void 0, ...defValue)));
        }
      }
    }
    if (textMateTokenInfo) {
      const theme = this.g.getColorTheme();
      $bk(this.u, $100("hr.tiw-metadata-separator"));
      const table = $bk(this.u, $100("table.tiw-metadata-table"));
      const tbody = $bk(table, $100("tbody"));
      if (tmTokenText && tmTokenText !== tokenText) {
        $bk(tbody, $100("tr", void 0, $100("td.tiw-metadata-key", void 0, "textmate token"), $100("td.tiw-metadata-value", void 0, `${tmTokenText} (${tmTokenText.length})`)));
      }
      const scopes = new Array();
      for (let i2 = textMateTokenInfo.token.scopes.length - 1; i2 >= 0; i2--) {
        scopes.push(textMateTokenInfo.token.scopes[i2]);
        if (i2 > 0) {
          scopes.push($100("br"));
        }
      }
      $bk(tbody, $100("tr", void 0, $100("td.tiw-metadata-key", void 0, "textmate scopes"), $100("td.tiw-metadata-value.tiw-metadata-scopes", void 0, ...scopes)));
      const matchingRule = $DGb(theme, textMateTokenInfo.token.scopes, false);
      const semForeground = semanticTokenInfo?.metadata?.foreground;
      if (matchingRule) {
        if (semForeground !== textMateTokenInfo.metadata.foreground) {
          let defValue = $100("code.tiw-theme-selector", void 0, matchingRule.rawSelector, $100("br"), JSON.stringify(matchingRule.settings, null, "	"));
          if (semForeground) {
            defValue = $100("s", void 0, defValue);
          }
          $bk(tbody, $100("tr", void 0, $100("td.tiw-metadata-key", void 0, "foreground"), $100("td.tiw-metadata-value", void 0, defValue)));
        }
      } else if (!semForeground) {
        $bk(tbody, $100("tr", void 0, $100("td.tiw-metadata-key", void 0, "foreground"), $100("td.tiw-metadata-value", void 0, "No theme selector")));
      }
    }
    if (treeSitterTokenInfo) {
      $bk(this.u, $100("hr.tiw-metadata-separator"));
      const table = $bk(this.u, $100("table.tiw-metadata-table"));
      const tbody = $bk(table, $100("tbody"));
      $bk(tbody, $100("tr", void 0, $100("td.tiw-metadata-key", void 0, "tree-sitter token"), $100("td.tiw-metadata-value", void 0, `${treeSitterTokenInfo.text}`)));
      const scopes = new Array();
      let node = treeSitterTokenInfo;
      while (node.parent) {
        scopes.push(node.type);
        node = node.parent;
        if (node) {
          scopes.push($100("br"));
        }
      }
      $bk(tbody, $100("tr", void 0, $100("td.tiw-metadata-key", void 0, "tree-sitter scopes"), $100("td.tiw-metadata-value.tiw-metadata-scopes", void 0, ...scopes)));
      const tokenizationSupport = $ZE.get(this.s.getLanguageId());
      const captures = tokenizationSupport?.captureAtPosition(position.lineNumber, position.column, this.s);
      if (captures && captures.length > 0) {
        $bk(tbody, $100("tr", void 0, $100("td.tiw-metadata-key", void 0, "foreground"), $100("td.tiw-metadata-value", void 0, captures[captures.length - 1].name)));
      }
    }
  }
  D(semantic, tm) {
    const elements = new Array();
    function render(property) {
      const value = semantic?.[property] || tm?.[property];
      if (value !== void 0) {
        const semanticStyle = semantic?.[property] ? "tiw-metadata-semantic" : "";
        elements.push($100("tr", void 0, $100("td.tiw-metadata-key", void 0, property), $100(`td.tiw-metadata-value.${semanticStyle}`, void 0, value)));
      }
      return value;
    }
    const foreground = render("foreground");
    const background = render("background");
    if (foreground && background) {
      const backgroundColor = $Vn.fromHex(background), foregroundColor = $Vn.fromHex(foreground);
      if (backgroundColor.isOpaque()) {
        elements.push($100("tr", void 0, $100("td.tiw-metadata-key", void 0, "contrast ratio"), $100("td.tiw-metadata-value", void 0, backgroundColor.getContrastRatio(foregroundColor.makeOpaque(backgroundColor)).toFixed(2))));
      } else {
        elements.push($100("tr", void 0, $100("td.tiw-metadata-key", void 0, "Contrast ratio cannot be precise for background colors that use transparency"), $100("td.tiw-metadata-value")));
      }
    }
    const fontStyleLabels = new Array();
    function addStyle(key2) {
      let label3;
      if (semantic && semantic[key2]) {
        label3 = $100("span.tiw-metadata-semantic", void 0, key2);
      } else if (tm && tm[key2]) {
        label3 = key2;
      }
      if (label3) {
        if (fontStyleLabels.length) {
          fontStyleLabels.push(" ");
        }
        fontStyleLabels.push(label3);
      }
    }
    addStyle("bold");
    addStyle("italic");
    addStyle("underline");
    addStyle("strikethrough");
    if (fontStyleLabels.length) {
      elements.push($100("tr", void 0, $100("td.tiw-metadata-key", void 0, "font style"), $100("td.tiw-metadata-value", void 0, ...fontStyleLabels)));
    }
    return elements;
  }
  F(metadata) {
    const colorMap = this.g.getColorTheme().tokenColorMap;
    const languageId = $pE.getLanguageId(metadata);
    const tokenType = $pE.getTokenType(metadata);
    const fontStyle = $pE.getFontStyle(metadata);
    const foreground = $pE.getForeground(metadata);
    const background = $pE.getBackground(metadata);
    return {
      languageId: this.f.languageIdCodec.decodeLanguageId(languageId),
      tokenType,
      bold: fontStyle & 2 ? true : void 0,
      italic: fontStyle & 1 ? true : void 0,
      underline: fontStyle & 4 ? true : void 0,
      strikethrough: fontStyle & 8 ? true : void 0,
      foreground: colorMap[foreground],
      background: colorMap[background]
    };
  }
  G(tokenType) {
    switch (tokenType) {
      case 0:
        return "Other";
      case 1:
        return "Comment";
      case 2:
        return "String";
      case 3:
        return "RegEx";
      default:
        return "??";
    }
  }
  H(grammar, position) {
    const lineNumber = position.lineNumber;
    const stateBeforeLine = this.I(grammar, lineNumber);
    const tokenizationResult1 = grammar.tokenizeLine(this.s.getLineContent(lineNumber), stateBeforeLine);
    const tokenizationResult2 = grammar.tokenizeLine2(this.s.getLineContent(lineNumber), stateBeforeLine);
    let token1Index = 0;
    for (let i2 = tokenizationResult1.tokens.length - 1; i2 >= 0; i2--) {
      const t = tokenizationResult1.tokens[i2];
      if (position.column - 1 >= t.startIndex) {
        token1Index = i2;
        break;
      }
    }
    let token2Index = 0;
    for (let i2 = tokenizationResult2.tokens.length >>> 1; i2 >= 0; i2--) {
      if (position.column - 1 >= tokenizationResult2.tokens[i2 << 1]) {
        token2Index = i2;
        break;
      }
    }
    return {
      token: tokenizationResult1.tokens[token1Index],
      metadata: this.F(tokenizationResult2.tokens[(token2Index << 1) + 1])
    };
  }
  I(grammar, lineNumber) {
    let state = null;
    for (let i2 = 1; i2 < lineNumber; i2++) {
      const tokenizationResult = grammar.tokenizeLine(this.s.getLineContent(i2), state);
      state = tokenizationResult.ruleStack;
    }
    return state;
  }
  J(token) {
    return token && token.data;
  }
  async L(position) {
    if (!this.z()) {
      return null;
    }
    const tokenProviders = this.r.documentSemanticTokensProvider.ordered(this.s);
    if (tokenProviders.length) {
      const provider = tokenProviders[0];
      const tokens = await Promise.resolve(provider.provideDocumentSemanticTokens(this.s, null, this.w.token));
      if (this.J(tokens)) {
        return { tokens, legend: provider.getLegend() };
      }
    }
    const rangeTokenProviders = this.r.documentRangeSemanticTokensProvider.ordered(this.s);
    if (rangeTokenProviders.length) {
      const provider = rangeTokenProviders[0];
      const lineNumber = position.lineNumber;
      const range = new $9C(lineNumber, 1, lineNumber, this.s.getLineMaxColumn(lineNumber));
      const tokens = await Promise.resolve(provider.provideDocumentRangeSemanticTokens(this.s, range, this.w.token));
      if (this.J(tokens)) {
        return { tokens, legend: provider.getLegend() };
      }
    }
    return null;
  }
  M(semanticTokens, pos) {
    const tokenData = semanticTokens.tokens.data;
    const defaultLanguage = this.s.getLanguageId();
    let lastLine = 0;
    let lastCharacter = 0;
    const posLine = pos.lineNumber - 1, posCharacter = pos.column - 1;
    for (let i2 = 0; i2 < tokenData.length; i2 += 5) {
      const lineDelta = tokenData[i2], charDelta = tokenData[i2 + 1], len = tokenData[i2 + 2], typeIdx = tokenData[i2 + 3], modSet = tokenData[i2 + 4];
      const line = lastLine + lineDelta;
      const character = lineDelta === 0 ? lastCharacter + charDelta : charDelta;
      if (posLine === line && character <= posCharacter && posCharacter < character + len) {
        const type = semanticTokens.legend.tokenTypes[typeIdx] || "not in legend (ignored)";
        const modifiers = [];
        let modifierSet = modSet;
        for (let modifierIndex = 0; modifierSet > 0 && modifierIndex < semanticTokens.legend.tokenModifiers.length; modifierIndex++) {
          if (modifierSet & 1) {
            modifiers.push(semanticTokens.legend.tokenModifiers[modifierIndex]);
          }
          modifierSet = modifierSet >> 1;
        }
        if (modifierSet > 0) {
          modifiers.push("not in legend (ignored)");
        }
        const range = new $9C(line + 1, character + 1, line + 1, character + 1 + len);
        const definitions3 = {};
        const colorMap = this.g.getColorTheme().tokenColorMap;
        const theme = this.g.getColorTheme();
        const tokenStyle = theme.getTokenStyleMetadata(type, modifiers, defaultLanguage, true, definitions3);
        let metadata = void 0;
        if (tokenStyle) {
          metadata = {
            languageId: void 0,
            tokenType: 0,
            bold: tokenStyle?.bold,
            italic: tokenStyle?.italic,
            underline: tokenStyle?.underline,
            strikethrough: tokenStyle?.strikethrough,
            foreground: colorMap[
              tokenStyle?.foreground || 0
              /* ColorId.None */
            ],
            background: void 0
          };
        }
        return { type, modifiers, range, metadata, definitions: definitions3 };
      }
      lastLine = line;
      lastCharacter = character;
    }
    return null;
  }
  N(cursor, pos) {
    const offset = this.s.getOffsetAt(pos);
    cursor.gotoFirstChild();
    let goChild = false;
    let lastGoodNode = null;
    do {
      if (cursor.currentNode.startIndex <= offset && offset < cursor.currentNode.endIndex) {
        goChild = true;
        lastGoodNode = cursor.currentNode;
      } else {
        goChild = false;
      }
    } while (goChild ? cursor.gotoFirstChild() : cursor.gotoNextSibling());
    return lastGoodNode;
  }
  O(tree, pos) {
    const cursor = tree.walk();
    return this.N(cursor, pos);
  }
  P(definition, property) {
    const elements = new Array();
    if (definition === void 0) {
      return elements;
    }
    const theme = this.g.getColorTheme();
    if (Array.isArray(definition)) {
      const scopesDefinition = {};
      theme.resolveScopes(definition, scopesDefinition);
      const matchingRule = scopesDefinition[property];
      if (matchingRule && scopesDefinition.scope) {
        const scopes = $100("ul.tiw-metadata-values");
        const strScopes = Array.isArray(matchingRule.scope) ? matchingRule.scope : [String(matchingRule.scope)];
        for (const strScope of strScopes) {
          scopes.appendChild($100("li.tiw-metadata-value.tiw-metadata-scopes", void 0, strScope));
        }
        elements.push(scopesDefinition.scope.join(" "), scopes, $100("code.tiw-theme-selector", void 0, JSON.stringify(matchingRule.settings, null, "	")));
        return elements;
      }
      return elements;
    } else if (SemanticTokenRule.is(definition)) {
      const scope = theme.getTokenStylingRuleScope(definition);
      if (scope === "setting") {
        elements.push(`User settings: ${definition.selector.id} - ${this.Q(definition.style, property)}`);
        return elements;
      } else if (scope === "theme") {
        elements.push(`Color theme: ${definition.selector.id} - ${this.Q(definition.style, property)}`);
        return elements;
      }
      return elements;
    } else {
      const style = theme.resolveTokenStyleValue(definition);
      elements.push(`Default: ${style ? this.Q(style, property) : ""}`);
      return elements;
    }
  }
  Q(style, property) {
    switch (property) {
      case "foreground":
        return style.foreground ? $Vn.Format.CSS.formatHexA(style.foreground, true) : "";
      default:
        return style[property] !== void 0 ? String(style[property]) : "";
    }
  }
  getDomNode() {
    return this.u;
  }
  getPosition() {
    return {
      position: this.c.getPosition(),
      preference: [
        2,
        1
        /* ContentWidgetPositionPreference.ABOVE */
      ]
    };
  }
};
$85(
  $7Gb.ID,
  $7Gb,
  4
  /* EditorContributionInstantiation.Lazy */
);
$55(InspectEditorTokens);

// out-build/vs/workbench/contrib/inlineChat/browser/inlineChatSavingService.js
var $9Gb = $Qk("IInlineChatSavingService	");

// out-build/vs/workbench/contrib/inlineChat/browser/inlineChatSessionService.js
var $kGb = $Qk("IInlineChatSessionService");

// out-build/vs/workbench/contrib/inlineChat/browser/inlineChatSession.js
var $oGb_1;
var $lGb = class _$lGb {
  static {
    this.c = $WI.register({ description: "inlineChat/session/wholeRange" });
  }
  constructor(g, wholeRange) {
    this.g = g;
    this.d = new $ze();
    this.onDidChange = this.d.event;
    this.f = [];
    this.f = g.deltaDecorations([], [{ range: wholeRange, options: _$lGb.c }]);
  }
  dispose() {
    this.d.dispose();
    if (!this.g.isDisposed()) {
      this.g.deltaDecorations(this.f, []);
    }
  }
  fixup(changes) {
    const newDeco = [];
    for (const { modified } of changes) {
      const modifiedRange = this.g.validateRange(modified.isEmpty ? new $9C(modified.startLineNumber, 1, modified.startLineNumber, Number.MAX_SAFE_INTEGER) : new $9C(modified.startLineNumber, 1, modified.endLineNumberExclusive - 1, Number.MAX_SAFE_INTEGER));
      newDeco.push({ range: modifiedRange, options: _$lGb.c });
    }
    const [first, ...rest] = this.f;
    const newIds = this.g.deltaDecorations(rest, newDeco);
    this.f = [first].concat(newIds);
    this.d.fire(this);
  }
  get trackedInitialRange() {
    const [first] = this.f;
    return this.g.getDecorationRange(first) ?? new $9C(1, 1, 1, 1);
  }
  get value() {
    let result;
    for (const id2 of this.f) {
      const range = this.g.getDecorationRange(id2);
      if (range) {
        if (!result) {
          result = range;
        } else {
          result = $9C.plusRange(result, range);
        }
      }
    }
    return result;
  }
};
var $mGb = class {
  constructor(editMode, headless, targetUri, textModel0, textModelN, agent, wholeRange, hunkData, chatModel, versionsByRequest) {
    this.editMode = editMode;
    this.headless = headless;
    this.targetUri = targetUri;
    this.textModel0 = textModel0;
    this.textModelN = textModelN;
    this.agent = agent;
    this.wholeRange = wholeRange;
    this.hunkData = hunkData;
    this.chatModel = chatModel;
    this.c = false;
    this.d = /* @__PURE__ */ new Date();
    this.g = /* @__PURE__ */ new Map();
    this.f = {
      extension: $5z.toKey(agent.extensionId),
      startTime: this.d.toISOString(),
      endTime: this.d.toISOString(),
      edits: 0,
      finishedByEdit: false,
      rounds: "",
      undos: "",
      editMode,
      unstashed: 0,
      acceptedHunks: 0,
      discardedHunks: 0,
      responseTypes: ""
    };
    if (versionsByRequest) {
      this.g = new Map(versionsByRequest);
    }
  }
  get isUnstashed() {
    return this.c;
  }
  markUnstashed() {
    this.f.unstashed += 1;
    this.c = true;
  }
  markModelVersion(request) {
    this.g.set(request.id, this.textModelN.getAlternativeVersionId());
  }
  get versionsByRequest() {
    return Array.from(this.g);
  }
  async undoChangesUntil(requestId) {
    const targetAltVersion = this.g.get(requestId);
    if (targetAltVersion === void 0) {
      return false;
    }
    this.hunkData.ignoreTextModelNChanges = true;
    try {
      while (targetAltVersion < this.textModelN.getAlternativeVersionId() && this.textModelN.canUndo()) {
        await this.textModelN.undo();
      }
    } finally {
      this.hunkData.ignoreTextModelNChanges = false;
    }
    return true;
  }
  get hasChangedText() {
    return !this.textModel0.equalsTextBuffer(this.textModelN.getTextBuffer());
  }
  asChangedText(changes) {
    if (changes.length === 0) {
      return void 0;
    }
    let startLine = Number.MAX_VALUE;
    let endLine = Number.MIN_VALUE;
    for (const change of changes) {
      startLine = Math.min(startLine, change.modified.startLineNumber);
      endLine = Math.max(endLine, change.modified.endLineNumberExclusive);
    }
    return this.textModelN.getValueInRange(new $9C(startLine, 1, endLine, Number.MAX_VALUE));
  }
  recordExternalEditOccurred(didFinish) {
    this.f.edits += 1;
    this.f.finishedByEdit = didFinish;
  }
  asTelemetryData() {
    for (const item of this.hunkData.getInfo()) {
      switch (item.getState()) {
        case 1:
          this.f.acceptedHunks += 1;
          break;
        case 2:
          this.f.discardedHunks += 1;
          break;
      }
    }
    this.f.endTime = (/* @__PURE__ */ new Date()).toISOString();
    return this.f;
  }
};
var $nGb = class $nGb2 {
  constructor(editor, session, g, contextKeyService, h3, j) {
    this.g = g;
    this.h = h3;
    this.j = j;
    this.d = $jAb.bindTo(contextKeyService);
    this.f = session;
    this.d.set(true);
    this.c = Event2.once(Event2.any(editor.onDidChangeCursorSelection, editor.onDidChangeModelContent, editor.onDidChangeModel, editor.onDidBlurEditorWidget))(() => {
      this.f = void 0;
      this.h.releaseSession(session);
      this.d.reset();
    });
  }
  dispose() {
    this.c.dispose();
    this.d.reset();
    if (this.f) {
      this.h.releaseSession(this.f);
    }
  }
  unstash() {
    if (!this.f) {
      return void 0;
    }
    this.c.dispose();
    const result = this.f;
    result.markUnstashed();
    result.hunkData.ignoreTextModelNChanges = true;
    result.textModelN.pushEditOperations(null, this.g, () => null);
    result.hunkData.ignoreTextModelNChanges = false;
    this.f = void 0;
    this.j.debug("[IE] Unstashed session");
    return result;
  }
};
$nGb = __decorate([
  __param(3, $on),
  __param(4, $kGb),
  __param(5, $wn)
], $nGb);
function lineRangeAsRange(lineRange, model) {
  return lineRange.isEmpty ? new $9C(lineRange.startLineNumber, 1, lineRange.startLineNumber, Number.MAX_SAFE_INTEGER) : new $9C(lineRange.startLineNumber, 1, lineRange.endLineNumberExclusive - 1, Number.MAX_SAFE_INTEGER);
}
var $oGb = class $oGb2 {
  static {
    $oGb_1 = this;
  }
  static {
    this.c = $WI.register({
      description: "inline-chat-hunk-tracked-range",
      stickiness: 0
      /* TrackedRangeStickiness.AlwaysGrowsWhenTypingAtEdges */
    });
  }
  static {
    this.d = 8;
  }
  constructor(j, k, l) {
    this.j = j;
    this.k = k;
    this.l = l;
    this.f = new $2c();
    this.g = /* @__PURE__ */ new Map();
    this.h = false;
    this.f.add(l.onDidChangeContent((e) => {
      if (!this.h) {
        this.m(e);
      }
    }));
  }
  dispose() {
    if (!this.l.isDisposed()) {
      this.l.changeDecorations((accessor) => {
        for (const { textModelNDecorations } of this.g.values()) {
          textModelNDecorations.forEach(accessor.removeDecoration, accessor);
        }
      });
    }
    if (!this.k.isDisposed()) {
      this.k.changeDecorations((accessor) => {
        for (const { textModel0Decorations } of this.g.values()) {
          textModel0Decorations.forEach(accessor.removeDecoration, accessor);
        }
      });
    }
    this.g.clear();
    this.f.dispose();
  }
  set ignoreTextModelNChanges(value) {
    this.h = value;
  }
  get ignoreTextModelNChanges() {
    return this.h;
  }
  m(event) {
    const hunkRanges = [];
    const ranges0 = [];
    for (const entry of this.g.values()) {
      if (entry.state === 0) {
        for (let i2 = 1; i2 < entry.textModelNDecorations.length; i2++) {
          const rangeN = this.l.getDecorationRange(entry.textModelNDecorations[i2]);
          const range0 = this.k.getDecorationRange(entry.textModel0Decorations[i2]);
          if (rangeN && range0) {
            hunkRanges.push({
              rangeN,
              range0,
              markAccepted: () => entry.state = 1
              /* HunkState.Accepted */
            });
          }
        }
      } else if (entry.state === 1) {
        for (let i2 = 1; i2 < entry.textModel0Decorations.length; i2++) {
          const range = this.k.getDecorationRange(entry.textModel0Decorations[i2]);
          if (range) {
            ranges0.push(range);
          }
        }
      }
    }
    hunkRanges.sort((a, b) => $9C.compareRangesUsingStarts(a.rangeN, b.rangeN));
    ranges0.sort($9C.compareRangesUsingStarts);
    const edits = [];
    for (const change of event.changes) {
      let isOverlapping = false;
      let pendingChangesLen = 0;
      for (const entry of hunkRanges) {
        if (entry.rangeN.getEndPosition().isBefore($9C.getStartPosition(change.range))) {
          pendingChangesLen += this.l.getValueLengthInRange(entry.rangeN);
          pendingChangesLen -= this.k.getValueLengthInRange(entry.range0);
        } else if ($9C.areIntersectingOrTouching(entry.rangeN, change.range)) {
          entry.markAccepted();
          isOverlapping = true;
          break;
        } else {
          break;
        }
      }
      if (isOverlapping) {
        continue;
      }
      const offset0 = change.rangeOffset - pendingChangesLen;
      const start0 = this.k.getPositionAt(offset0);
      let acceptedChangesLen = 0;
      for (const range of ranges0) {
        if (range.getEndPosition().isBefore(start0)) {
          acceptedChangesLen += this.k.getValueLengthInRange(range);
        }
      }
      const start = this.k.getPositionAt(offset0 + acceptedChangesLen);
      const end = this.k.getPositionAt(offset0 + acceptedChangesLen + change.rangeLength);
      edits.push($bD.replace($9C.fromPositions(start, end), change.text));
    }
    this.k.pushEditOperations(null, edits, () => null);
  }
  async recompute(editState, diff3) {
    diff3 ??= await this.j.computeDiff(this.k.uri, this.l.uri, { ignoreTrimWhitespace: false, maxComputationTimeMs: Number.MAX_SAFE_INTEGER, computeMoves: false }, "advanced");
    let mergedChanges = [];
    if (diff3 && diff3.changes.length > 0) {
      mergedChanges = [diff3.changes[0]];
      for (let i2 = 1; i2 < diff3.changes.length; i2++) {
        const lastChange = mergedChanges[mergedChanges.length - 1];
        const thisChange = diff3.changes[i2];
        if (thisChange.modified.startLineNumber - lastChange.modified.endLineNumberExclusive <= $oGb_1.d) {
          mergedChanges[mergedChanges.length - 1] = new $qD(lastChange.original.join(thisChange.original), lastChange.modified.join(thisChange.modified), (lastChange.innerChanges ?? []).concat(thisChange.innerChanges ?? []));
        } else {
          mergedChanges.push(thisChange);
        }
      }
    }
    const hunks = mergedChanges.map((change) => new RawHunk(change.original, change.modified, change.innerChanges ?? []));
    editState.applied = hunks.length;
    this.l.changeDecorations((accessorN) => {
      this.k.changeDecorations((accessor0) => {
        for (const { textModelNDecorations, textModel0Decorations } of this.g.values()) {
          textModelNDecorations.forEach(accessorN.removeDecoration, accessorN);
          textModel0Decorations.forEach(accessor0.removeDecoration, accessor0);
        }
        this.g.clear();
        for (const hunk of hunks) {
          const textModelNDecorations = [];
          const textModel0Decorations = [];
          textModelNDecorations.push(accessorN.addDecoration(lineRangeAsRange(hunk.modified, this.l), $oGb_1.c));
          textModel0Decorations.push(accessor0.addDecoration(lineRangeAsRange(hunk.original, this.k), $oGb_1.c));
          for (const change of hunk.changes) {
            textModelNDecorations.push(accessorN.addDecoration(change.modifiedRange, $oGb_1.c));
            textModel0Decorations.push(accessor0.addDecoration(change.originalRange, $oGb_1.c));
          }
          this.g.set(hunk, {
            editState,
            textModelNDecorations,
            textModel0Decorations,
            state: 0
            /* HunkState.Pending */
          });
        }
      });
    });
  }
  get size() {
    return this.g.size;
  }
  get pending() {
    return Iterable.reduce(this.g.values(), (r2, { state }) => r2 + (state === 0 ? 1 : 0), 0);
  }
  n(item) {
    const edits = [];
    const rangesN = item.getRangesN();
    const ranges0 = item.getRanges0();
    for (let i2 = 1; i2 < rangesN.length; i2++) {
      const modifiedRange = rangesN[i2];
      const originalValue = this.k.getValueInRange(ranges0[i2]);
      edits.push($bD.replace(modifiedRange, originalValue));
    }
    return edits;
  }
  discardAll() {
    const edits = [];
    for (const item of this.getInfo()) {
      if (item.getState() === 0) {
        edits.push(this.n(item));
      }
    }
    const undoEdits = [];
    this.l.pushEditOperations(null, edits.flat(), (_undoEdits) => {
      undoEdits.push(_undoEdits);
      return null;
    });
    return undoEdits.flat();
  }
  getInfo() {
    const result = [];
    for (const [hunk, data] of this.g.entries()) {
      const item = {
        getState: () => {
          return data.state;
        },
        isInsertion: () => {
          return hunk.original.isEmpty;
        },
        getRangesN: () => {
          const ranges = data.textModelNDecorations.map((id2) => this.l.getDecorationRange(id2));
          $Nb(ranges);
          return ranges;
        },
        getRanges0: () => {
          const ranges = data.textModel0Decorations.map((id2) => this.k.getDecorationRange(id2));
          $Nb(ranges);
          return ranges;
        },
        discardChanges: () => {
          if (data.state === 0) {
            const edits = this.n(item);
            this.l.pushEditOperations(null, edits, () => null);
            data.state = 2;
            if (data.editState.applied > 0) {
              data.editState.applied -= 1;
            }
          }
        },
        acceptChanges: () => {
          if (data.state === 0) {
            const edits = [];
            const rangesN = item.getRangesN();
            const ranges0 = item.getRanges0();
            for (let i2 = 1; i2 < ranges0.length; i2++) {
              const originalRange = ranges0[i2];
              const modifiedValue = this.l.getValueInRange(rangesN[i2]);
              edits.push($bD.replace(originalRange, modifiedValue));
            }
            this.k.pushEditOperations(null, edits, () => null);
            data.state = 1;
          }
        }
      };
      result.push(item);
    }
    return result;
  }
};
$oGb = $oGb_1 = __decorate([
  __param(0, $I0)
], $oGb);
var RawHunk = class {
  constructor(original, modified, changes) {
    this.original = original;
    this.modified = modified;
    this.changes = changes;
  }
};
var HunkState;
(function(HunkState2) {
  HunkState2[HunkState2["Pending"] = 0] = "Pending";
  HunkState2[HunkState2["Accepted"] = 1] = "Accepted";
  HunkState2[HunkState2["Rejected"] = 2] = "Rejected";
})(HunkState || (HunkState = {}));

// out-build/vs/workbench/contrib/inlineChat/browser/inlineChatSessionServiceImpl.js
var $$Gb = class _$$Gb extends Error {
  static {
    this.code = "InlineChatError";
  }
  constructor(message) {
    super(message);
    this.name = _$$Gb.code;
  }
};
var $_Gb = class $_Gb2 {
  constructor(i2, j, k, l, m, n, o, p, q, r2, s) {
    this.i = i2;
    this.j = j;
    this.k = k;
    this.l = l;
    this.m = m;
    this.n = n;
    this.o = o;
    this.p = p;
    this.q = q;
    this.r = r2;
    this.s = s;
    this.a = new $2c();
    this.b = this.a.add(new $ze());
    this.onWillStartSession = this.b.event;
    this.c = this.a.add(new $ze());
    this.onDidMoveSession = this.c.event;
    this.d = this.a.add(new $ze());
    this.onDidEndSession = this.d.event;
    this.f = this.a.add(new $ze());
    this.onDidStashSession = this.f.event;
    this.g = /* @__PURE__ */ new Map();
    this.h = /* @__PURE__ */ new Map();
  }
  dispose() {
    this.a.dispose();
    this.g.forEach((x) => x.store.dispose());
    this.g.clear();
  }
  async createSession(editor, options3, token) {
    const agent = this.s.getDefaultAgent(ChatAgentLocation.Editor);
    if (!agent) {
      this.m.trace("[IE] NO agent found");
      return void 0;
    }
    this.b.fire(editor);
    const textModel = editor.getModel();
    const selection = editor.getSelection();
    const store = new $2c();
    this.m.trace(`[IE] creating NEW session for ${editor.getId()}, ${agent.extensionId}`);
    const chatModel = options3.session?.chatModel ?? this.r.startSession(ChatAgentLocation.Editor, token);
    if (!chatModel) {
      this.m.trace("[IE] NO chatModel found");
      return void 0;
    }
    store.add($1c(() => {
      const doesOtherSessionUseChatModel = [...this.g.values()].some((data) => data.session !== session && data.session.chatModel === chatModel);
      if (!doesOtherSessionUseChatModel) {
        this.r.clearSession(chatModel.sessionId);
        chatModel.dispose();
      }
    }));
    const lastResponseListener = store.add(new $4c());
    store.add(chatModel.onDidChange((e) => {
      if (e.kind !== "addRequest" || !e.request.response) {
        return;
      }
      const { response } = e.request;
      session.markModelVersion(e.request);
      lastResponseListener.value = response.onDidChange(() => {
        if (!response.isComplete) {
          return;
        }
        lastResponseListener.clear();
        for (const part of response.response.value) {
          if (part.kind !== "textEditGroup" || part.uri.scheme !== Schemas.untitled || $oh(part.uri, session.textModelN.uri)) {
            continue;
          }
          const langSelection = this.q.createByFilepathOrFirstLine(part.uri, void 0);
          const untitledTextModel = this.p.untitled.create({
            associatedResource: part.uri,
            languageId: langSelection.languageId
          });
          untitledTextModel.resolve();
          this.k.createModelReference(part.uri).then((ref) => {
            store.add(ref);
          });
        }
      });
    }));
    store.add(this.s.onDidChangeAgents((e) => {
      if (e === void 0 && (!this.s.getAgent(agent.id) || !this.s.getActivatedAgents().includes(agent))) {
        this.m.trace(`[IE] provider GONE for ${editor.getId()}, ${agent.extensionId}`);
        this.t(session, true);
      }
    }));
    const id2 = $ps();
    const targetUri = textModel.uri;
    store.add(await this.k.createModelReference(textModel.uri));
    const textModelN = textModel;
    const textModel0 = store.add(this.j.createModel($OI(textModel.createSnapshot()), { languageId: textModel.getLanguageId(), onDidChange: Event2.None }, targetUri.with({ scheme: Schemas.vscode, authority: "inline-chat", path: "", query: new URLSearchParams({ id: id2, "textModel0": "" }).toString() }), true));
    if (targetUri.scheme === Schemas.untitled) {
      store.add(this.o.onDidCloseEditor(() => {
        if (!this.o.isOpened({ resource: targetUri, typeId: $0Gb.ID, editorId: $1K.id })) {
          this.t(session, true);
        }
      }));
    }
    let wholeRange = options3.wholeRange;
    if (!wholeRange) {
      wholeRange = new $9C(selection.selectionStartLineNumber, selection.selectionStartColumn, selection.positionLineNumber, selection.positionColumn);
    }
    if (token.isCancellationRequested) {
      store.dispose();
      return void 0;
    }
    const session = new $mGb(options3.editMode, options3.headless ?? false, targetUri, textModel0, textModelN, agent, store.add(new $lGb(textModelN, wholeRange)), store.add(new $oGb(this.l, textModel0, textModelN)), chatModel, options3.session?.versionsByRequest);
    const key2 = this.u(editor, session.targetUri);
    if (this.g.has(key2)) {
      store.dispose();
      throw new Error(`Session already stored for ${key2}`);
    }
    this.g.set(key2, { session, editor, store });
    return session;
  }
  moveSession(session, target) {
    const newKey = this.u(target, session.targetUri);
    const existing = this.g.get(newKey);
    if (existing) {
      if (existing.session !== session) {
        throw new Error(`Cannot move session because the target editor already/still has one`);
      } else {
        return;
      }
    }
    let found = false;
    for (const [oldKey, data] of this.g) {
      if (data.session === session) {
        found = true;
        this.g.delete(oldKey);
        this.g.set(newKey, { ...data, editor: target });
        this.m.trace(`[IE] did MOVE session for ${data.editor.getId()} to NEW EDITOR ${target.getId()}, ${session.agent.extensionId}`);
        this.c.fire({ session, editor: target });
        break;
      }
    }
    if (!found) {
      throw new Error(`Cannot move session because it is not stored`);
    }
  }
  releaseSession(session) {
    this.t(session, false);
  }
  t(session, byServer) {
    let tuple;
    for (const candidate of this.g) {
      if (candidate[1].session === session) {
        tuple = candidate;
        break;
      }
    }
    if (!tuple) {
      return;
    }
    this.i.publicLog2("interactiveEditor/session", session.asTelemetryData());
    const [key2, value] = tuple;
    this.g.delete(key2);
    this.m.trace(`[IE] did RELEASED session for ${value.editor.getId()}, ${session.agent.extensionId}`);
    this.d.fire({ editor: value.editor, session, endedByExternalCause: byServer });
    value.store.dispose();
  }
  stashSession(session, editor, undoCancelEdits) {
    const result = this.n.createInstance($nGb, editor, session, undoCancelEdits);
    this.f.fire({ editor, session });
    this.m.trace(`[IE] did STASH session for ${editor.getId()}, ${session.agent.extensionId}`);
    return result;
  }
  getCodeEditor(session) {
    for (const [, data] of this.g) {
      if (data.session === session) {
        return data.editor;
      }
    }
    throw new Error("session not found");
  }
  getSession(editor, uri) {
    const key2 = this.u(editor, uri);
    return this.g.get(key2)?.session;
  }
  u(editor, uri) {
    const item = this.h.get(uri.scheme);
    return item ? item.getComparisonKey(editor, uri) : `${editor.getId()}@${uri.toString()}`;
  }
  registerSessionKeyComputer(scheme, value) {
    this.h.set(scheme, value);
    return $1c(() => this.h.delete(scheme));
  }
};
$_Gb = __decorate([
  __param(0, $zv),
  __param(1, $sG),
  __param(2, $oG),
  __param(3, $I0),
  __param(4, $wn),
  __param(5, $Pk),
  __param(6, $mJ),
  __param(7, $cK),
  __param(8, $1E),
  __param(9, $qO),
  __param(10, $ZO)
], $_Gb);
var $aHb = class $aHb2 {
  static {
    this.Id = "inlineChat.enabler";
  }
  constructor(contextKeyService, chatAgentService, editorService) {
    this.c = new $2c();
    this.a = $$zb.bindTo(contextKeyService);
    this.b = $0zb.bindTo(contextKeyService);
    const updateAgent = () => {
      const hasEditorAgent = Boolean(chatAgentService.getDefaultAgent(ChatAgentLocation.Editor));
      this.a.set(hasEditorAgent);
    };
    this.c.add(chatAgentService.onDidChangeAgents(updateAgent));
    updateAgent();
    const updateEditor = () => {
      const ctrl = editorService.activeEditorPane?.getControl();
      const isCodeEditorLike = $P5(ctrl) || $Q5(ctrl) || $R5(ctrl);
      this.b.set(isCodeEditorLike);
    };
    this.c.add(editorService.onDidActiveEditorChange(updateEditor));
    updateEditor();
  }
  dispose() {
    this.b.reset();
    this.a.reset();
    this.c.dispose();
  }
};
$aHb = __decorate([
  __param(0, $on),
  __param(1, $ZO),
  __param(2, $mJ)
], $aHb);

// out-build/vs/workbench/contrib/inlineChat/browser/utils.js
async function $zGb(model, edit3, progress, obs) {
  const [id2] = model.deltaDecorations([], [{
    range: edit3.range,
    options: {
      description: "asyncTextEdit",
      stickiness: 0
      /* TrackedRangeStickiness.AlwaysGrowsWhenTypingAtEdges */
    }
  }]);
  let first = true;
  for await (const part of edit3.newText) {
    if (model.isDisposed()) {
      break;
    }
    const range = model.getDecorationRange(id2);
    if (!range) {
      throw new Error("FAILED to perform async replace edit because the anchor decoration was removed");
    }
    const edit4 = first ? $bD.replace(range, part) : $bD.insert(range.getEndPosition(), part);
    obs?.start();
    model.pushEditOperations(null, [edit4], (undoEdits) => {
      progress?.report(undoEdits);
      return null;
    });
    obs?.stop();
    first = false;
  }
}
function $AGb(interval, edit3, wordsPerSec, token) {
  wordsPerSec = Math.max(30, wordsPerSec);
  const stream = new $mi();
  let newText = edit3.text ?? "";
  interval.cancelAndSet(() => {
    if (token.isCancellationRequested) {
      return;
    }
    const r2 = $9rb(newText, 1);
    stream.emitOne(r2.value);
    newText = newText.substring(r2.value.length);
    if (r2.isFullString) {
      interval.cancel();
      stream.resolve();
      d.dispose();
    }
  }, 1e3 / wordsPerSec);
  const d = token.onCancellationRequested(() => {
    interval.cancel();
    stream.resolve();
    d.dispose();
  });
  return {
    range: edit3.range,
    newText: stream.asyncIterable
  };
}

// out-build/vs/workbench/contrib/mergeEditor/browser/model/editing.js
var $kHb = class {
  constructor(range, newLines) {
    this.range = range;
    this.newLines = newLines;
  }
  equals(other) {
    return this.range.equals(other.range) && $zb(this.newLines, other.newLines);
  }
  toEdits(modelLineCount) {
    return new $mHb([this]).toEdits(modelLineCount);
  }
};
var $lHb = class {
  constructor(range, newText) {
    this.range = range;
    this.newText = newText;
  }
  equals(other) {
    return $9C.equalsRange(this.range, other.range) && this.newText === other.newText;
  }
};
var $mHb = class {
  constructor(edits) {
    this.edits = edits;
  }
  toEdits(modelLineCount) {
    return this.edits.map((e) => {
      if (e.range.endLineNumberExclusive <= modelLineCount) {
        return {
          range: new $9C(e.range.startLineNumber, 1, e.range.endLineNumberExclusive, 1),
          text: e.newLines.map((s) => s + "\n").join("")
        };
      }
      if (e.range.startLineNumber === 1) {
        return {
          range: new $9C(1, 1, modelLineCount, Number.MAX_SAFE_INTEGER),
          text: e.newLines.join("\n")
        };
      }
      return {
        range: new $9C(e.range.startLineNumber - 1, Number.MAX_SAFE_INTEGER, modelLineCount, Number.MAX_SAFE_INTEGER),
        text: e.newLines.map((s) => "\n" + s).join("")
      };
    });
  }
};

// out-build/vs/workbench/contrib/mergeEditor/browser/utils.js
function $nHb(element, style) {
  Object.entries(style).forEach(([key2, value]) => {
    element.style.setProperty(key2, toSize(value));
  });
}
function toSize(value) {
  return typeof value === "number" ? `${value}px` : value;
}
function $oHb(editor, decorations) {
  const d = new $2c();
  let decorationIds = [];
  d.add($ud({ debugName: () => `Apply decorations from ${decorations.debugName}` }, (reader) => {
    const d2 = decorations.read(reader);
    editor.changeDecorations((a) => {
      decorationIds = a.deltaDecorations(decorationIds, d2);
    });
  }));
  d.add({
    dispose: () => {
      editor.changeDecorations((a) => {
        decorationIds = a.deltaDecorations(decorationIds, []);
      });
    }
  });
  return d;
}
function* $pHb(left, right, compare8) {
  const rightQueue = new $bc(right);
  for (const leftElement of left) {
    rightQueue.takeWhile((rightElement) => CompareResult.isGreaterThan(compare8(leftElement, rightElement)));
    const equals = rightQueue.takeWhile((rightElement) => CompareResult.isNeitherLessOrGreaterThan(compare8(leftElement, rightElement)));
    yield { left: leftElement, rights: equals || [] };
  }
}
function* join2(left, right, compare8) {
  const rightQueue = new $bc(right);
  for (const leftElement of left) {
    const skipped = rightQueue.takeWhile((rightElement) => CompareResult.isGreaterThan(compare8(leftElement, rightElement)));
    if (skipped) {
      yield { rights: skipped };
    }
    const equals = rightQueue.takeWhile((rightElement) => CompareResult.isNeitherLessOrGreaterThan(compare8(leftElement, rightElement)));
    yield { left: leftElement, rights: equals || [] };
  }
}
function $rHb(...arrays) {
  return [].concat(...arrays);
}
function $tHb(promise, then) {
  let disposed = false;
  promise.then(() => {
    if (disposed) {
      return;
    }
    then();
  });
  return $1c(() => {
    disposed = true;
  });
}
function $uHb(obj, fields) {
  return Object.assign(obj, fields);
}
function $vHb(source1, source2) {
  const result = {};
  for (const key2 in source1) {
    result[key2] = source1[key2];
  }
  for (const key2 in source2) {
    const source2Value = source2[key2];
    if (typeof result[key2] === "object" && source2Value && typeof source2Value === "object") {
      result[key2] = $vHb(result[key2], source2Value);
    } else {
      result[key2] = source2Value;
    }
  }
  return result;
}
var $wHb = class $wHb2 {
  constructor(f, g) {
    this.f = f;
    this.g = g;
    this.b = false;
    this.c = void 0;
  }
  get() {
    if (!this.b) {
      const value = this.g.get(
        this.f,
        0
        /* StorageScope.PROFILE */
      );
      if (value !== void 0) {
        try {
          this.c = JSON.parse(value);
        } catch (e) {
          $gb(e);
        }
      }
      this.b = true;
    }
    return this.c;
  }
  set(newValue) {
    this.c = newValue;
    this.g.store(
      this.f,
      JSON.stringify(this.c),
      0,
      0
      /* StorageTarget.USER */
    );
  }
};
$wHb = __decorate([
  __param(1, $jv)
], $wHb);

// out-build/vs/workbench/contrib/mergeEditor/browser/model/lineRange.js
var $jHb = class _$jHb {
  static {
    this.compareByStart = $9b((l) => l.startLineNumber, $$b);
  }
  static join(ranges) {
    if (ranges.length === 0) {
      return void 0;
    }
    let startLineNumber = Number.MAX_SAFE_INTEGER;
    let endLineNumber = 0;
    for (const range of ranges) {
      startLineNumber = Math.min(startLineNumber, range.startLineNumber);
      endLineNumber = Math.max(endLineNumber, range.startLineNumber + range.lineCount);
    }
    return new _$jHb(startLineNumber, endLineNumber - startLineNumber);
  }
  static fromLineNumbers(startLineNumber, endExclusiveLineNumber) {
    return new _$jHb(startLineNumber, endExclusiveLineNumber - startLineNumber);
  }
  constructor(startLineNumber, lineCount) {
    this.startLineNumber = startLineNumber;
    this.lineCount = lineCount;
    if (lineCount < 0) {
      throw new $vb();
    }
  }
  join(other) {
    return new _$jHb(Math.min(this.startLineNumber, other.startLineNumber), Math.max(this.endLineNumberExclusive, other.endLineNumberExclusive) - this.startLineNumber);
  }
  get endLineNumberExclusive() {
    return this.startLineNumber + this.lineCount;
  }
  get isEmpty() {
    return this.lineCount === 0;
  }
  /**
   * Returns false if there is at least one line between `this` and `other`.
  */
  touches(other) {
    return this.endLineNumberExclusive >= other.startLineNumber && other.endLineNumberExclusive >= this.startLineNumber;
  }
  isAfter(range) {
    return this.startLineNumber >= range.endLineNumberExclusive;
  }
  isBefore(range) {
    return range.startLineNumber >= this.endLineNumberExclusive;
  }
  delta(lineDelta) {
    return new _$jHb(this.startLineNumber + lineDelta, this.lineCount);
  }
  toString() {
    return `[${this.startLineNumber},${this.endLineNumberExclusive})`;
  }
  equals(originalRange) {
    return this.startLineNumber === originalRange.startLineNumber && this.lineCount === originalRange.lineCount;
  }
  contains(lineNumber) {
    return this.startLineNumber <= lineNumber && lineNumber < this.endLineNumberExclusive;
  }
  deltaEnd(delta) {
    return new _$jHb(this.startLineNumber, this.lineCount + delta);
  }
  deltaStart(lineDelta) {
    return new _$jHb(this.startLineNumber + lineDelta, this.lineCount - lineDelta);
  }
  getLines(model) {
    const result = new Array(this.lineCount);
    for (let i2 = 0; i2 < this.lineCount; i2++) {
      result[i2] = model.getLineContent(this.startLineNumber + i2);
    }
    return result;
  }
  containsRange(range) {
    return this.startLineNumber <= range.startLineNumber && range.endLineNumberExclusive <= this.endLineNumberExclusive;
  }
  toRange() {
    return new $9C(this.startLineNumber, 1, this.endLineNumberExclusive, 1);
  }
  toInclusiveRange() {
    if (this.isEmpty) {
      return void 0;
    }
    return new $9C(
      this.startLineNumber,
      1,
      this.endLineNumberExclusive - 1,
      1073741824
      /* Constants.MAX_SAFE_SMALL_INTEGER */
    );
  }
  toInclusiveRangeOrEmpty() {
    if (this.isEmpty) {
      return new $9C(this.startLineNumber, 1, this.startLineNumber, 1);
    }
    return new $9C(
      this.startLineNumber,
      1,
      this.endLineNumberExclusive - 1,
      1073741824
      /* Constants.MAX_SAFE_SMALL_INTEGER */
    );
  }
  intersects(lineRange) {
    return this.startLineNumber <= lineRange.endLineNumberExclusive && lineRange.startLineNumber <= this.endLineNumberExclusive;
  }
};

// out-build/vs/workbench/contrib/mergeEditor/browser/model/rangeUtils.js
function $xHb(range, position) {
  if (position.lineNumber < range.startLineNumber || position.lineNumber > range.endLineNumber) {
    return false;
  }
  if (position.lineNumber === range.startLineNumber && position.column < range.startColumn) {
    return false;
  }
  if (position.lineNumber === range.endLineNumber && position.column >= range.endColumn) {
    return false;
  }
  return true;
}
function $yHb(range) {
  if (range.startLineNumber === range.endLineNumber) {
    return new $gD(0, range.endColumn - range.startColumn);
  } else {
    return new $gD(range.endLineNumber - range.startLineNumber, range.endColumn - 1);
  }
}
function $zHb(position1, position2) {
  if (position1.lineNumber === position2.lineNumber) {
    return new $gD(0, position2.column - position1.column);
  } else {
    return new $gD(position2.lineNumber - position1.lineNumber, position2.column - 1);
  }
}
function $AHb(position, length) {
  if (length.lineCount === 0) {
    return new $8C(position.lineNumber, position.column + length.columnCount);
  } else {
    return new $8C(position.lineNumber + length.lineCount, length.columnCount + 1);
  }
}
function $BHb(range, other) {
  return range.endLineNumber < other.startLineNumber || range.endLineNumber === other.startLineNumber && range.endColumn <= other.startColumn;
}

// out-build/vs/workbench/contrib/mergeEditor/browser/model/mapping.js
var $CHb = class _$CHb {
  static join(mappings) {
    return mappings.reduce((acc, cur) => acc ? acc.join(cur) : cur, void 0);
  }
  constructor(inputRange, outputRange) {
    this.inputRange = inputRange;
    this.outputRange = outputRange;
  }
  extendInputRange(extendedInputRange) {
    if (!extendedInputRange.containsRange(this.inputRange)) {
      throw new $vb();
    }
    const startDelta = extendedInputRange.startLineNumber - this.inputRange.startLineNumber;
    const endDelta = extendedInputRange.endLineNumberExclusive - this.inputRange.endLineNumberExclusive;
    return new _$CHb(extendedInputRange, new $jHb(this.outputRange.startLineNumber + startDelta, this.outputRange.lineCount - startDelta + endDelta));
  }
  join(other) {
    return new _$CHb(this.inputRange.join(other.inputRange), this.outputRange.join(other.outputRange));
  }
  get resultingDeltaFromOriginalToModified() {
    return this.outputRange.endLineNumberExclusive - this.inputRange.endLineNumberExclusive;
  }
  toString() {
    return `${this.inputRange.toString()} -> ${this.outputRange.toString()}`;
  }
  addOutputLineDelta(delta) {
    return new _$CHb(this.inputRange, this.outputRange.delta(delta));
  }
  addInputLineDelta(delta) {
    return new _$CHb(this.inputRange.delta(delta), this.outputRange);
  }
  reverse() {
    return new _$CHb(this.outputRange, this.inputRange);
  }
};
var $DHb = class _$DHb {
  static betweenOutputs(inputToOutput1, inputToOutput2, inputLineCount) {
    const alignments = $EHb.compute(inputToOutput1, inputToOutput2);
    const mappings = alignments.map((m) => new $CHb(m.output1Range, m.output2Range));
    return new _$DHb(mappings, inputLineCount);
  }
  constructor(lineRangeMappings, inputLineCount) {
    this.lineRangeMappings = lineRangeMappings;
    this.inputLineCount = inputLineCount;
    $kd(() => {
      return $ld(lineRangeMappings, (m1, m2) => m1.inputRange.isBefore(m2.inputRange) && m1.outputRange.isBefore(m2.outputRange) && m2.inputRange.startLineNumber - m1.inputRange.endLineNumberExclusive === m2.outputRange.startLineNumber - m1.outputRange.endLineNumberExclusive);
    });
  }
  project(lineNumber) {
    const lastBefore = $1(this.lineRangeMappings, (r2) => r2.inputRange.startLineNumber <= lineNumber);
    if (!lastBefore) {
      return new $CHb(new $jHb(lineNumber, 1), new $jHb(lineNumber, 1));
    }
    if (lastBefore.inputRange.contains(lineNumber)) {
      return lastBefore;
    }
    const containingRange = new $jHb(lineNumber, 1);
    const mappedRange = new $jHb(lineNumber + lastBefore.outputRange.endLineNumberExclusive - lastBefore.inputRange.endLineNumberExclusive, 1);
    return new $CHb(containingRange, mappedRange);
  }
  get outputLineCount() {
    const last = this.lineRangeMappings.at(-1);
    const diff3 = last ? last.outputRange.endLineNumberExclusive - last.inputRange.endLineNumberExclusive : 0;
    return this.inputLineCount + diff3;
  }
  reverse() {
    return new _$DHb(this.lineRangeMappings.map((r2) => r2.reverse()), this.outputLineCount);
  }
};
var $EHb = class _$EHb {
  static compute(fromInputToOutput1, fromInputToOutput2) {
    const compareByStartLineNumber = $9b((d) => d.inputRange.startLineNumber, $$b);
    const combinedDiffs = $rHb(fromInputToOutput1.map((diff3) => ({ source: 0, diff: diff3 })), fromInputToOutput2.map((diff3) => ({ source: 1, diff: diff3 }))).sort($9b((d) => d.diff, compareByStartLineNumber));
    const currentDiffs = [new Array(), new Array()];
    const deltaFromBaseToInput = [0, 0];
    const alignments = new Array();
    function pushAndReset(inputRange) {
      const mapping1 = $CHb.join(currentDiffs[0]) || new $CHb(inputRange, inputRange.delta(deltaFromBaseToInput[0]));
      const mapping2 = $CHb.join(currentDiffs[1]) || new $CHb(inputRange, inputRange.delta(deltaFromBaseToInput[1]));
      alignments.push(new _$EHb(currentInputRange, mapping1.extendInputRange(currentInputRange).outputRange, currentDiffs[0], mapping2.extendInputRange(currentInputRange).outputRange, currentDiffs[1]));
      currentDiffs[0] = [];
      currentDiffs[1] = [];
    }
    let currentInputRange;
    for (const diff3 of combinedDiffs) {
      const range = diff3.diff.inputRange;
      if (currentInputRange && !currentInputRange.touches(range)) {
        pushAndReset(currentInputRange);
        currentInputRange = void 0;
      }
      deltaFromBaseToInput[diff3.source] = diff3.diff.resultingDeltaFromOriginalToModified;
      currentInputRange = currentInputRange ? currentInputRange.join(range) : range;
      currentDiffs[diff3.source].push(diff3.diff);
    }
    if (currentInputRange) {
      pushAndReset(currentInputRange);
    }
    return alignments;
  }
  constructor(inputRange, output1Range, output1LineMappings, output2Range, output2LineMappings) {
    this.inputRange = inputRange;
    this.output1Range = output1Range;
    this.output1LineMappings = output1LineMappings;
    this.output2Range = output2Range;
    this.output2LineMappings = output2LineMappings;
  }
  toString() {
    return `${this.output1Range} <- ${this.inputRange} -> ${this.output2Range}`;
  }
};
var $FHb = class _$FHb extends $CHb {
  static join(mappings) {
    return mappings.reduce((acc, cur) => acc ? acc.join(cur) : cur, void 0);
  }
  constructor(inputRange, inputTextModel, outputRange, outputTextModel, rangeMappings) {
    super(inputRange, outputRange);
    this.inputTextModel = inputTextModel;
    this.outputTextModel = outputTextModel;
    this.rangeMappings = rangeMappings || [new $GHb(this.inputRange.toRange(), this.outputRange.toRange())];
  }
  addOutputLineDelta(delta) {
    return new _$FHb(this.inputRange, this.inputTextModel, this.outputRange.delta(delta), this.outputTextModel, this.rangeMappings.map((d) => d.addOutputLineDelta(delta)));
  }
  addInputLineDelta(delta) {
    return new _$FHb(this.inputRange.delta(delta), this.inputTextModel, this.outputRange, this.outputTextModel, this.rangeMappings.map((d) => d.addInputLineDelta(delta)));
  }
  join(other) {
    return new _$FHb(this.inputRange.join(other.inputRange), this.inputTextModel, this.outputRange.join(other.outputRange), this.outputTextModel);
  }
  getLineEdit() {
    return new $kHb(this.inputRange, this.a());
  }
  getReverseLineEdit() {
    return new $kHb(this.outputRange, this.b());
  }
  a() {
    return this.outputRange.getLines(this.outputTextModel);
  }
  b() {
    return this.inputRange.getLines(this.inputTextModel);
  }
};
var $GHb = class _$GHb {
  constructor(inputRange, outputRange) {
    this.inputRange = inputRange;
    this.outputRange = outputRange;
  }
  toString() {
    function rangeToString(range) {
      return `[${range.startLineNumber}:${range.startColumn}, ${range.endLineNumber}:${range.endColumn})`;
    }
    return `${rangeToString(this.inputRange)} -> ${rangeToString(this.outputRange)}`;
  }
  addOutputLineDelta(deltaLines) {
    return new _$GHb(this.inputRange, new $9C(this.outputRange.startLineNumber + deltaLines, this.outputRange.startColumn, this.outputRange.endLineNumber + deltaLines, this.outputRange.endColumn));
  }
  addInputLineDelta(deltaLines) {
    return new _$GHb(new $9C(this.inputRange.startLineNumber + deltaLines, this.inputRange.startColumn, this.inputRange.endLineNumber + deltaLines, this.inputRange.endColumn), this.outputRange);
  }
  reverse() {
    return new _$GHb(this.outputRange, this.inputRange);
  }
};
var $HHb = class _$HHb {
  constructor(rangeMappings, inputLineCount) {
    this.rangeMappings = rangeMappings;
    this.inputLineCount = inputLineCount;
    $kd(() => $ld(
      rangeMappings,
      (m1, m2) => $BHb(m1.inputRange, m2.inputRange) && $BHb(m1.outputRange, m2.outputRange)
      /*&&
      lengthBetweenPositions(m1.inputRange.getEndPosition(), m2.inputRange.getStartPosition()).equals(
          lengthBetweenPositions(m1.outputRange.getEndPosition(), m2.outputRange.getStartPosition())
      )*/
    ));
  }
  project(position) {
    const lastBefore = $1(this.rangeMappings, (r2) => r2.inputRange.getStartPosition().isBeforeOrEqual(position));
    if (!lastBefore) {
      return new $GHb($9C.fromPositions(position, position), $9C.fromPositions(position, position));
    }
    if ($xHb(lastBefore.inputRange, position)) {
      return lastBefore;
    }
    const dist = $zHb(lastBefore.inputRange.getEndPosition(), position);
    const outputPos = $AHb(lastBefore.outputRange.getEndPosition(), dist);
    return new $GHb($9C.fromPositions(position), $9C.fromPositions(outputPos));
  }
  projectRange(range) {
    const start = this.project(range.getStartPosition());
    const end = this.project(range.getEndPosition());
    return new $GHb(start.inputRange.plusRange(end.inputRange), start.outputRange.plusRange(end.outputRange));
  }
  get outputLineCount() {
    const last = this.rangeMappings.at(-1);
    const diff3 = last ? last.outputRange.endLineNumber - last.inputRange.endLineNumber : 0;
    return this.inputLineCount + diff3;
  }
  reverse() {
    return new _$HHb(this.rangeMappings.map((m) => m.reverse()), this.outputLineCount);
  }
};

// out-build/vs/workbench/contrib/mergeEditor/browser/model/modifiedBaseRange.js
var $IHb = class _$IHb {
  static fromDiffs(diffs1, diffs2, baseTextModel, input1TextModel, input2TextModel) {
    const alignments = $EHb.compute(diffs1, diffs2);
    return alignments.map((a) => new _$IHb(a.inputRange, baseTextModel, a.output1Range, input1TextModel, a.output1LineMappings, a.output2Range, input2TextModel, a.output2LineMappings));
  }
  constructor(baseRange, baseTextModel, input1Range, input1TextModel, input1Diffs, input2Range, input2TextModel, input2Diffs) {
    this.baseRange = baseRange;
    this.baseTextModel = baseTextModel;
    this.input1Range = input1Range;
    this.input1TextModel = input1TextModel;
    this.input1Diffs = input1Diffs;
    this.input2Range = input2Range;
    this.input2TextModel = input2TextModel;
    this.input2Diffs = input2Diffs;
    this.input1CombinedDiff = $FHb.join(this.input1Diffs);
    this.input2CombinedDiff = $FHb.join(this.input2Diffs);
    this.isEqualChange = $zb(this.input1Diffs, this.input2Diffs, (a, b) => a.getLineEdit().equals(b.getLineEdit()));
    this.c = null;
    this.e = null;
    this.g = null;
    this.h = null;
    if (this.input1Diffs.length === 0 && this.input2Diffs.length === 0) {
      throw new $vb("must have at least one diff");
    }
  }
  getInputRange(inputNumber) {
    return inputNumber === 1 ? this.input1Range : this.input2Range;
  }
  getInputCombinedDiff(inputNumber) {
    return inputNumber === 1 ? this.input1CombinedDiff : this.input2CombinedDiff;
  }
  getInputDiffs(inputNumber) {
    return inputNumber === 1 ? this.input1Diffs : this.input2Diffs;
  }
  get isConflicting() {
    return this.input1Diffs.length > 0 && this.input2Diffs.length > 0;
  }
  get canBeCombined() {
    return this.f(1) !== void 0;
  }
  get isOrderRelevant() {
    const input1 = this.f(1);
    const input2 = this.f(2);
    if (!input1 || !input2) {
      return false;
    }
    return !input1.equals(input2);
  }
  getEditForBase(state) {
    const diffs = [];
    if (state.includesInput1 && this.input1CombinedDiff) {
      diffs.push({ diff: this.input1CombinedDiff, inputNumber: 1 });
    }
    if (state.includesInput2 && this.input2CombinedDiff) {
      diffs.push({ diff: this.input2CombinedDiff, inputNumber: 2 });
    }
    if (diffs.length === 0) {
      return { edit: void 0, effectiveState: ModifiedBaseRangeState.base };
    }
    if (diffs.length === 1) {
      return { edit: diffs[0].diff.getLineEdit(), effectiveState: ModifiedBaseRangeState.base.withInputValue(diffs[0].inputNumber, true, false) };
    }
    if (state.kind !== ModifiedBaseRangeStateKind.both) {
      throw new $vb();
    }
    const smartCombinedEdit = state.smartCombination ? this.f(state.firstInput) : this.i(state.firstInput);
    if (smartCombinedEdit) {
      return { edit: smartCombinedEdit, effectiveState: state };
    }
    return {
      edit: diffs[$JHb(state.firstInput) - 1].diff.getLineEdit(),
      effectiveState: ModifiedBaseRangeState.base.withInputValue($JHb(state.firstInput), true, false)
    };
  }
  f(firstInput) {
    if (firstInput === 1 && this.c !== null) {
      return this.c;
    } else if (firstInput === 2 && this.e !== null) {
      return this.e;
    }
    const combinedDiffs = $rHb(this.input1Diffs.flatMap((diffs) => diffs.rangeMappings.map((diff3) => ({ diff: diff3, input: 1 }))), this.input2Diffs.flatMap((diffs) => diffs.rangeMappings.map((diff3) => ({ diff: diff3, input: 2 })))).sort($0b($9b((d) => d.diff.inputRange, $9C.compareRangesUsingStarts), $9b((d) => d.input === firstInput ? 1 : 2, $$b)));
    const sortedEdits = combinedDiffs.map((d) => {
      const sourceTextModel = d.input === 1 ? this.input1TextModel : this.input2TextModel;
      return new $lHb(d.diff.inputRange, sourceTextModel.getValueInRange(d.diff.outputRange));
    });
    const result = editsToLineRangeEdit(this.baseRange, sortedEdits, this.baseTextModel);
    if (firstInput === 1) {
      this.c = result;
    } else {
      this.e = result;
    }
    return result;
  }
  i(firstInput) {
    if (firstInput === 1 && this.g !== null) {
      return this.g;
    } else if (firstInput === 2 && this.h !== null) {
      return this.h;
    }
    let input1Lines = this.input1Range.getLines(this.input1TextModel);
    let input2Lines = this.input2Range.getLines(this.input2TextModel);
    if (firstInput === 2) {
      [input1Lines, input2Lines] = [input2Lines, input1Lines];
    }
    const result = new $kHb(this.baseRange, input1Lines.concat(input2Lines));
    if (firstInput === 1) {
      this.g = result;
    } else {
      this.h = result;
    }
    return result;
  }
};
function editsToLineRangeEdit(range, sortedEdits, textModel) {
  let text2 = "";
  const startsLineBefore = range.startLineNumber > 1;
  let currentPosition = startsLineBefore ? new $8C(range.startLineNumber - 1, textModel.getLineMaxColumn(range.startLineNumber - 1)) : new $8C(range.startLineNumber, 1);
  for (const edit3 of sortedEdits) {
    const diffStart = edit3.range.getStartPosition();
    if (!currentPosition.isBeforeOrEqual(diffStart)) {
      return void 0;
    }
    let originalText2 = textModel.getValueInRange($9C.fromPositions(currentPosition, diffStart));
    if (diffStart.lineNumber > textModel.getLineCount()) {
      originalText2 += "\n";
    }
    text2 += originalText2;
    text2 += edit3.newText;
    currentPosition = edit3.range.getEndPosition();
  }
  const endsLineAfter = range.endLineNumberExclusive <= textModel.getLineCount();
  const end = endsLineAfter ? new $8C(range.endLineNumberExclusive, 1) : new $8C(
    range.endLineNumberExclusive - 1,
    1073741824
    /* Constants.MAX_SAFE_SMALL_INTEGER */
  );
  const originalText = textModel.getValueInRange($9C.fromPositions(currentPosition, end));
  text2 += originalText;
  const lines = $Mf(text2);
  if (startsLineBefore) {
    if (lines[0] !== "") {
      return void 0;
    }
    lines.shift();
  }
  if (endsLineAfter) {
    if (lines[lines.length - 1] !== "") {
      return void 0;
    }
    lines.pop();
  }
  return new $kHb(range, lines);
}
var ModifiedBaseRangeStateKind;
(function(ModifiedBaseRangeStateKind2) {
  ModifiedBaseRangeStateKind2[ModifiedBaseRangeStateKind2["base"] = 0] = "base";
  ModifiedBaseRangeStateKind2[ModifiedBaseRangeStateKind2["input1"] = 1] = "input1";
  ModifiedBaseRangeStateKind2[ModifiedBaseRangeStateKind2["input2"] = 2] = "input2";
  ModifiedBaseRangeStateKind2[ModifiedBaseRangeStateKind2["both"] = 3] = "both";
  ModifiedBaseRangeStateKind2[ModifiedBaseRangeStateKind2["unrecognized"] = 4] = "unrecognized";
})(ModifiedBaseRangeStateKind || (ModifiedBaseRangeStateKind = {}));
function $JHb(inputNumber) {
  return inputNumber === 1 ? 2 : 1;
}
var $KHb = class {
  constructor() {
  }
  get includesInput1() {
    return false;
  }
  get includesInput2() {
    return false;
  }
  includesInput(inputNumber) {
    return inputNumber === 1 ? this.includesInput1 : this.includesInput2;
  }
  isInputIncluded(inputNumber) {
    return inputNumber === 1 ? this.includesInput1 : this.includesInput2;
  }
  toggle(inputNumber) {
    return this.withInputValue(inputNumber, !this.includesInput(inputNumber), true);
  }
  getInput(inputNumber) {
    if (!this.isInputIncluded(inputNumber)) {
      return 0;
    }
    return 1;
  }
};
var $LHb = class extends $KHb {
  get kind() {
    return ModifiedBaseRangeStateKind.base;
  }
  toString() {
    return "base";
  }
  swap() {
    return this;
  }
  withInputValue(inputNumber, value, smartCombination = false) {
    if (inputNumber === 1) {
      return value ? new $MHb() : this;
    } else {
      return value ? new $NHb() : this;
    }
  }
  equals(other) {
    return other.kind === ModifiedBaseRangeStateKind.base;
  }
};
var $MHb = class extends $KHb {
  get kind() {
    return ModifiedBaseRangeStateKind.input1;
  }
  get includesInput1() {
    return true;
  }
  toString() {
    return "1\u2713";
  }
  swap() {
    return new $NHb();
  }
  withInputValue(inputNumber, value, smartCombination = false) {
    if (inputNumber === 1) {
      return value ? this : new $LHb();
    } else {
      return value ? new $OHb(1, smartCombination) : new $NHb();
    }
  }
  equals(other) {
    return other.kind === ModifiedBaseRangeStateKind.input1;
  }
};
var $NHb = class _$NHb extends $KHb {
  get kind() {
    return ModifiedBaseRangeStateKind.input2;
  }
  get includesInput2() {
    return true;
  }
  toString() {
    return "2\u2713";
  }
  swap() {
    return new $MHb();
  }
  withInputValue(inputNumber, value, smartCombination = false) {
    if (inputNumber === 2) {
      return value ? this : new $LHb();
    } else {
      return value ? new $OHb(2, smartCombination) : new _$NHb();
    }
  }
  equals(other) {
    return other.kind === ModifiedBaseRangeStateKind.input2;
  }
};
var $OHb = class _$OHb extends $KHb {
  constructor(firstInput, smartCombination) {
    super();
    this.firstInput = firstInput;
    this.smartCombination = smartCombination;
  }
  get kind() {
    return ModifiedBaseRangeStateKind.both;
  }
  get includesInput1() {
    return true;
  }
  get includesInput2() {
    return true;
  }
  toString() {
    return "2\u2713";
  }
  swap() {
    return new _$OHb($JHb(this.firstInput), this.smartCombination);
  }
  withInputValue(inputNumber, value, smartCombination = false) {
    if (value) {
      return this;
    }
    return inputNumber === 1 ? new $NHb() : new $MHb();
  }
  equals(other) {
    return other.kind === ModifiedBaseRangeStateKind.both && this.firstInput === other.firstInput && this.smartCombination === other.smartCombination;
  }
  getInput(inputNumber) {
    return inputNumber === this.firstInput ? 1 : 2;
  }
};
var $PHb = class extends $KHb {
  get kind() {
    return ModifiedBaseRangeStateKind.unrecognized;
  }
  toString() {
    return "unrecognized";
  }
  swap() {
    return this;
  }
  withInputValue(inputNumber, value, smartCombination = false) {
    if (!value) {
      return this;
    }
    return inputNumber === 1 ? new $MHb() : new $NHb();
  }
  equals(other) {
    return other.kind === ModifiedBaseRangeStateKind.unrecognized;
  }
};
var ModifiedBaseRangeState;
(function(ModifiedBaseRangeState2) {
  ModifiedBaseRangeState2.base = new $LHb();
  ModifiedBaseRangeState2.unrecognized = new $PHb();
})(ModifiedBaseRangeState || (ModifiedBaseRangeState = {}));
var InputState;
(function(InputState2) {
  InputState2[InputState2["excluded"] = 0] = "excluded";
  InputState2[InputState2["first"] = 1] = "first";
  InputState2[InputState2["second"] = 2] = "second";
  InputState2[InputState2["unrecognized"] = 3] = "unrecognized";
})(InputState || (InputState = {}));

// out-build/vs/workbench/contrib/mergeEditor/browser/view/fixedZoneWidget.js
var $QHb = class _$QHb extends $3c {
  static {
    this.a = 0;
  }
  constructor(j, viewZoneAccessor, afterLineNumber, height, viewZoneIdsToCleanUp) {
    super();
    this.j = j;
    this.b = `fixedZoneWidget-${_$QHb.a++}`;
    this.f = h("div.fixed-zone-widget").root;
    this.g = {
      getId: () => this.b,
      getDomNode: () => this.f,
      getPosition: () => null
    };
    this.c = viewZoneAccessor.addZone({
      domNode: document.createElement("div"),
      afterLineNumber,
      heightInPx: height,
      ordinal: 5e4 + 1,
      onComputedHeight: (height2) => {
        this.f.style.height = `${height2}px`;
      },
      onDomNodeTop: (top2) => {
        this.f.style.top = `${top2}px`;
      }
    });
    viewZoneIdsToCleanUp.push(this.c);
    this.B(Event2.runAndSubscribe(this.j.onDidLayoutChange, () => {
      this.f.style.left = this.j.getLayoutInfo().contentLeft + "px";
    }));
    this.j.addOverlayWidget(this.g);
    this.B({
      dispose: () => {
        this.j.removeOverlayWidget(this.g);
      }
    });
  }
};

// out-build/vs/workbench/contrib/mergeEditor/browser/view/conflictActions.js
var $rIb = class extends $3c {
  constructor(c) {
    super();
    this.c = c;
    this.B(this.c.onDidChangeConfiguration((e) => {
      if (e.hasChanged(
        52
        /* EditorOption.fontInfo */
      ) || e.hasChanged(
        19
        /* EditorOption.codeLensFontSize */
      ) || e.hasChanged(
        18
        /* EditorOption.codeLensFontFamily */
      )) {
        this.f();
      }
    }));
    this.a = "_conflictActionsFactory_" + $Xi(this.c.getId()).toString(16);
    this.b = $VZ($Jj(this.c.getContainerDomNode()) ? this.c.getContainerDomNode() : void 0, void 0, this.q);
    this.f();
  }
  f() {
    const { codeLensHeight, fontSize } = this.g();
    const fontFamily = this.c.getOption(
      18
      /* EditorOption.codeLensFontFamily */
    );
    const editorFontInfo = this.c.getOption(
      52
      /* EditorOption.fontInfo */
    );
    const fontFamilyVar = `--codelens-font-family${this.a}`;
    const fontFeaturesVar = `--codelens-font-features${this.a}`;
    let newStyle = `
		.${this.a} { line-height: ${codeLensHeight}px; font-size: ${fontSize}px; padding-right: ${Math.round(fontSize * 0.5)}px; font-feature-settings: var(${fontFeaturesVar}) }
		.monaco-workbench .${this.a} span.codicon { line-height: ${codeLensHeight}px; font-size: ${fontSize}px; }
		`;
    if (fontFamily) {
      newStyle += `${this.a} { font-family: var(${fontFamilyVar}), ${EDITOR_FONT_DEFAULTS.fontFamily}}`;
    }
    this.b.textContent = newStyle;
    this.c.getContainerDomNode().style?.setProperty(fontFamilyVar, fontFamily ?? "inherit");
    this.c.getContainerDomNode().style?.setProperty(fontFeaturesVar, editorFontInfo.fontFeatureSettings);
  }
  g() {
    const lineHeightFactor = Math.max(1.3, this.c.getOption(
      68
      /* EditorOption.lineHeight */
    ) / this.c.getOption(
      54
      /* EditorOption.fontSize */
    ));
    let fontSize = this.c.getOption(
      19
      /* EditorOption.codeLensFontSize */
    );
    if (!fontSize || fontSize < 5) {
      fontSize = this.c.getOption(
        54
        /* EditorOption.fontSize */
      ) * 0.9 | 0;
    }
    return {
      fontSize,
      codeLensHeight: fontSize * lineHeightFactor | 0
    };
  }
  createWidget(viewZoneChangeAccessor, lineNumber, items, viewZoneIdsToCleanUp) {
    const layoutInfo = this.g();
    return new ActionsContentWidget(this.c, viewZoneChangeAccessor, lineNumber, layoutInfo.codeLensHeight + 2, this.a, items, viewZoneIdsToCleanUp);
  }
};
var $sIb = class {
  constructor(a, b) {
    this.a = a;
    this.b = b;
    this.itemsInput1 = this.c(1);
    this.itemsInput2 = this.c(2);
    this.resultItems = $2d(this, (reader) => {
      const viewModel = this.a;
      const modifiedBaseRange = this.b;
      const state = viewModel.model.getState(modifiedBaseRange).read(reader);
      const model = viewModel.model;
      const result = [];
      if (state.kind === ModifiedBaseRangeStateKind.unrecognized) {
        result.push({
          text: localize(8023, null),
          tooltip: localize(8024, null)
        });
      } else if (state.kind === ModifiedBaseRangeStateKind.base) {
        result.push({
          text: localize(8025, null),
          tooltip: localize(8026, null)
        });
      } else {
        const labels2 = [];
        if (state.includesInput1) {
          labels2.push(model.input1.title);
        }
        if (state.includesInput2) {
          labels2.push(model.input2.title);
        }
        if (state.kind === ModifiedBaseRangeStateKind.both && state.firstInput === 2) {
          labels2.reverse();
        }
        result.push({
          text: `${labels2.join(" + ")}`
        });
      }
      const stateToggles = [];
      if (state.includesInput1) {
        stateToggles.push(command(localize(8027, null, model.input1.title), async () => {
          $ce((tx) => {
            model.setState(modifiedBaseRange, state.withInputValue(1, false), true, tx);
            model.telemetry.reportRemoveInvoked(1, state.includesInput(2));
          });
        }, localize(8028, null, model.input1.title)));
      }
      if (state.includesInput2) {
        stateToggles.push(command(localize(8029, null, model.input2.title), async () => {
          $ce((tx) => {
            model.setState(modifiedBaseRange, state.withInputValue(2, false), true, tx);
            model.telemetry.reportRemoveInvoked(2, state.includesInput(1));
          });
        }, localize(8030, null, model.input2.title)));
      }
      if (state.kind === ModifiedBaseRangeStateKind.both && state.firstInput === 2) {
        stateToggles.reverse();
      }
      result.push(...stateToggles);
      if (state.kind === ModifiedBaseRangeStateKind.unrecognized) {
        result.push(command(localize(8031, null), async () => {
          $ce((tx) => {
            model.setState(modifiedBaseRange, ModifiedBaseRangeState.base, true, tx);
            model.telemetry.reportResetToBaseInvoked();
          });
        }, localize(8032, null)));
      }
      return result;
    });
    this.isEmpty = $2d(this, (reader) => {
      return this.itemsInput1.read(reader).length + this.itemsInput2.read(reader).length + this.resultItems.read(reader).length === 0;
    });
    this.inputIsEmpty = $2d(this, (reader) => {
      return this.itemsInput1.read(reader).length + this.itemsInput2.read(reader).length === 0;
    });
  }
  c(inputNumber) {
    return $2d((reader) => {
      const viewModel = this.a;
      const modifiedBaseRange = this.b;
      if (!viewModel.model.hasBaseRange(modifiedBaseRange)) {
        return [];
      }
      const state = viewModel.model.getState(modifiedBaseRange).read(reader);
      const handled = viewModel.model.isHandled(modifiedBaseRange).read(reader);
      const model = viewModel.model;
      const result = [];
      const inputData = inputNumber === 1 ? viewModel.model.input1 : viewModel.model.input2;
      const showNonConflictingChanges = viewModel.showNonConflictingChanges.read(reader);
      if (!modifiedBaseRange.isConflicting && handled && !showNonConflictingChanges) {
        return [];
      }
      const otherInputNumber = inputNumber === 1 ? 2 : 1;
      if (state.kind !== ModifiedBaseRangeStateKind.unrecognized && !state.isInputIncluded(inputNumber)) {
        if (!state.isInputIncluded(otherInputNumber) || !this.a.shouldUseAppendInsteadOfAccept.read(reader)) {
          result.push(command(localize(8012, null, inputData.title), async () => {
            $ce((tx) => {
              model.setState(modifiedBaseRange, state.withInputValue(inputNumber, true, false), inputNumber, tx);
              model.telemetry.reportAcceptInvoked(inputNumber, state.includesInput(otherInputNumber));
            });
          }, localize(8013, null, inputData.title)));
          if (modifiedBaseRange.canBeCombined) {
            const commandName = modifiedBaseRange.isOrderRelevant ? localize(8014, null, inputData.title) : localize(8015, null);
            result.push(command(commandName, async () => {
              $ce((tx) => {
                model.setState(modifiedBaseRange, ModifiedBaseRangeState.base.withInputValue(inputNumber, true).withInputValue(otherInputNumber, true, true), true, tx);
                model.telemetry.reportSmartCombinationInvoked(state.includesInput(otherInputNumber));
              });
            }, localize(8016, null)));
          }
        } else {
          result.push(command(localize(8017, null, inputData.title), async () => {
            $ce((tx) => {
              model.setState(modifiedBaseRange, state.withInputValue(inputNumber, true, false), inputNumber, tx);
              model.telemetry.reportAcceptInvoked(inputNumber, state.includesInput(otherInputNumber));
            });
          }, localize(8018, null, inputData.title)));
          if (modifiedBaseRange.canBeCombined) {
            result.push(command(localize(8019, null, inputData.title), async () => {
              $ce((tx) => {
                model.setState(modifiedBaseRange, state.withInputValue(inputNumber, true, true), inputNumber, tx);
                model.telemetry.reportSmartCombinationInvoked(state.includesInput(otherInputNumber));
              });
            }, localize(8020, null)));
          }
        }
        if (!model.isInputHandled(modifiedBaseRange, inputNumber).read(reader)) {
          result.push(command(localize(8021, null), async () => {
            $ce((tx) => {
              model.setInputHandled(modifiedBaseRange, inputNumber, true, tx);
            });
          }, localize(8022, null)));
        }
      }
      return result;
    });
  }
};
function command(title, action, tooltip) {
  return {
    text: title,
    action,
    tooltip
  };
}
var ActionsContentWidget = class extends $QHb {
  constructor(editor, viewZoneAccessor, afterLineNumber, height, className, items, viewZoneIdsToCleanUp) {
    super(editor, viewZoneAccessor, afterLineNumber, height, viewZoneIdsToCleanUp);
    this.m = h("div.merge-editor-conflict-actions").root;
    this.f.appendChild(this.m);
    this.m.classList.add(className);
    this.B($td((reader) => {
      const i2 = items.read(reader);
      this.n(i2);
    }));
  }
  n(items) {
    const children = [];
    let isFirst = true;
    for (const item of items) {
      if (isFirst) {
        isFirst = false;
      } else {
        children.push($("span", void 0, "\xA0|\xA0"));
      }
      const title = $B1(item.text);
      if (item.action) {
        children.push($("a", { title: item.tooltip, role: "button", onclick: () => item.action() }, ...title));
      } else {
        children.push($("span", { title: item.tooltip }, ...title));
      }
    }
    $dk(this.m, ...children);
  }
};

// out-build/vs/workbench/contrib/inlineChat/browser/inlineChatStrategies.js
var $tIb_1;
var HunkAction;
(function(HunkAction2) {
  HunkAction2[HunkAction2["Accept"] = 0] = "Accept";
  HunkAction2[HunkAction2["Discard"] = 1] = "Discard";
  HunkAction2[HunkAction2["MoveNext"] = 2] = "MoveNext";
  HunkAction2[HunkAction2["MovePrev"] = 3] = "MovePrev";
  HunkAction2[HunkAction2["ToggleDiff"] = 4] = "ToggleDiff";
})(HunkAction || (HunkAction = {}));
var $tIb = class $tIb2 {
  static {
    $tIb_1 = this;
  }
  static {
    this.a = $WI.register({
      description: "inline-chat",
      showIfCollapsed: false,
      isWholeLine: true
    });
  }
  constructor(e, f, g, h3, j) {
    this.e = e;
    this.f = f;
    this.g = g;
    this.h = h3;
    this.j = j;
    this.b = new $2c();
    this.c = this.b.add(new $ze());
    this.d = this.b.add(new $ze());
    this.onDidAccept = this.c.event;
    this.onDidDiscard = this.d.event;
  }
  dispose() {
    this.b.dispose();
  }
  performHunkAction(_hunk, action) {
    if (action === 0) {
      this.c.fire();
    } else if (action === 1) {
      this.d.fire();
    }
  }
  async k(ignoreLocal) {
    const untitledModels = [];
    const editor = this.j.createInstance($iHb);
    for (const request of this.e.chatModel.getRequests()) {
      if (!request.response?.response) {
        continue;
      }
      for (const item of request.response.response.value) {
        if (item.kind !== "textEditGroup") {
          continue;
        }
        if (ignoreLocal && $oh(item.uri, this.e.textModelN.uri)) {
          continue;
        }
        await editor.apply(request.response, item, void 0);
        if (item.uri.scheme === Schemas.untitled) {
          const untitled = this.h.untitled.get(item.uri);
          if (untitled) {
            untitledModels.push(untitled);
          }
        }
      }
    }
    for (const untitledModel of untitledModels) {
      if (!untitledModel.isDisposed()) {
        await untitledModel.resolve();
        await untitledModel.save({
          reason: 1
          /* SaveReason.EXPLICIT */
        });
      }
    }
  }
  cancel() {
    return this.e.hunkData.discardAll();
  }
  getWholeRangeDecoration() {
    const ranges = [this.e.wholeRange.value];
    const newDecorations = ranges.map((range) => range.isEmpty() ? void 0 : { range, options: $tIb_1.a });
    $Nb(newDecorations);
    return newDecorations;
  }
};
$tIb = $tIb_1 = __decorate([
  __param(3, $cK),
  __param(4, $Pk)
], $tIb);
var $uIb = class $uIb2 extends $tIb {
  constructor(session, editor, zone, modelService, contextKeyService, textFileService, instaService) {
    super(session, editor, zone, textFileService, instaService);
    this.m = $lAb.bindTo(contextKeyService);
    const baseModel = modelService.getModel(session.targetUri);
    Event2.debounce(baseModel.onDidChangeContent.bind(baseModel), () => {
    }, 350)((_) => {
      if (!baseModel.isDisposed() && !session.textModel0.isDisposed()) {
        this.m.set(session.hasChangedText);
      }
    }, void 0, this.b);
  }
  dispose() {
    this.m.reset();
    super.dispose();
  }
  async apply() {
    await super.k(false);
  }
  async makeChanges() {
  }
  async makeProgressiveChanges() {
  }
  async renderChanges() {
  }
  hasFocus() {
    return this.g.widget.hasFocus();
  }
};
$uIb = __decorate([
  __param(3, $sG),
  __param(4, $on),
  __param(5, $cK),
  __param(6, $Pk)
], $uIb);
var $vIb = class $vIb2 extends $tIb {
  constructor(session, editor, zone, t, contextKeyService, u, v, w, x, y, textFileService, instaService) {
    super(session, editor, zone, textFileService, instaService);
    this.t = t;
    this.u = u;
    this.v = v;
    this.w = w;
    this.x = x;
    this.y = y;
    this.m = $WI.register({
      description: "inline-modified-line",
      className: "inline-chat-inserted-range-linehighlight",
      isWholeLine: true,
      overviewRuler: {
        position: OverviewRulerLane.Full,
        color: $7l($KAb)
      },
      minimap: {
        position: 1,
        color: $7l($LAb)
      }
    });
    this.n = $WI.register({
      description: "inline-chat-inserted-range-linehighlight",
      className: "inline-chat-inserted-range",
      stickiness: 1
    });
    this.s = 0;
    this.C = /* @__PURE__ */ new Map();
    this.o = $mAb.bindTo(contextKeyService);
    this.p = $nAb.bindTo(contextKeyService);
    this.q = this.f.createDecorationsCollection();
    this.r = this.b.add(new $rIb(this.f));
  }
  dispose() {
    this.z();
    super.dispose();
  }
  z() {
    this.o.reset();
    this.p.reset();
    this.g.widget.updateStatus("");
    this.q.clear();
    for (const data of this.C.values()) {
      data.remove();
    }
  }
  async apply() {
    this.z();
    if (this.s > 0) {
      this.f.pushUndoStop();
    }
    await super.k(true);
  }
  cancel() {
    this.z();
    return super.cancel();
  }
  async makeChanges(edits, obs, undoStopBefore) {
    return this.A(edits, obs, void 0, void 0, undoStopBefore);
  }
  async makeProgressiveChanges(edits, obs, opts, undoStopBefore) {
    const progress = new $VJ((edits2) => {
      const newLines = /* @__PURE__ */ new Set();
      for (const edit3 of edits2) {
        $_C.fromRange(edit3.range).forEach((line) => newLines.add(line));
      }
      const existingRanges = this.q.getRanges().map($_C.fromRange);
      for (const existingRange of existingRanges) {
        existingRange.forEach((line) => newLines.delete(line));
      }
      const newDecorations = [];
      for (const line of newLines) {
        newDecorations.push({ range: new $9C(line, 1, line, Number.MAX_VALUE), options: this.m });
      }
      this.q.append(newDecorations);
    });
    return this.A(edits, obs, opts, progress, undoStopBefore);
  }
  async A(edits, obs, opts, progress, undoStopBefore) {
    if (undoStopBefore) {
      this.f.pushUndoStop();
    }
    this.s++;
    if (opts) {
      const durationInSec = opts.duration / 1e3;
      for (const edit3 of edits) {
        const wordCount = $0rb(edit3.text ?? "");
        const speed = wordCount / durationInSec;
        const asyncEdit = $AGb(new $lj(this.g.domNode), edit3, speed, opts.token);
        await $zGb(this.e.textModelN, asyncEdit, progress, obs);
      }
    } else {
      obs.start();
      this.e.textModelN.pushEditOperations(null, edits, (undoEdits) => {
        progress?.report(undoEdits);
        return null;
      });
      obs.stop();
    }
  }
  performHunkAction(hunk, action) {
    const displayData = this.B(hunk);
    if (!displayData) {
      if (action === 0) {
        this.c.fire();
      } else if (action === 1) {
        this.d.fire();
      }
      return;
    }
    if (action === 0) {
      displayData.acceptHunk();
    } else if (action === 1) {
      displayData.discardHunk();
    } else if (action === 2) {
      displayData.move(true);
    } else if (action === 3) {
      displayData.move(false);
    } else if (action === 4) {
      displayData.toggleDiff?.();
    }
  }
  B(hunkInfo) {
    let result;
    if (hunkInfo) {
      result = this.C.get(hunkInfo);
    }
    if (!result && this.g.position) {
      const zoneLine = this.g.position.lineNumber;
      let distance = Number.MAX_SAFE_INTEGER;
      for (const candidate of this.C.values()) {
        if (candidate.hunk.getState() !== 0) {
          continue;
        }
        const hunkRanges = candidate.hunk.getRangesN();
        const myDistance = zoneLine <= hunkRanges[0].startLineNumber ? hunkRanges[0].startLineNumber - zoneLine : zoneLine - hunkRanges[0].endLineNumber;
        if (myDistance < distance) {
          distance = myDistance;
          result = candidate;
        }
      }
    }
    if (!result) {
      result = Iterable.first(Iterable.filter(
        this.C.values(),
        (candidate) => candidate.hunk.getState() === 0
        /* HunkState.Pending */
      ));
    }
    return result;
  }
  async renderChanges() {
    this.q.clear();
    const renderHunks = () => {
      let widgetData;
      changeDecorationsAndViewZones(this.f, (decorationsAccessor, viewZoneAccessor) => {
        const keysNow = new Set(this.C.keys());
        widgetData = void 0;
        for (const hunkData of this.e.hunkData.getInfo()) {
          keysNow.delete(hunkData);
          const hunkRanges = hunkData.getRangesN();
          let data = this.C.get(hunkData);
          if (!data) {
            const decorationIds = [];
            for (let i2 = 0; i2 < hunkRanges.length; i2++) {
              decorationIds.push(decorationsAccessor.addDecoration(hunkRanges[i2], i2 === 0 ? this.m : this.n));
            }
            const acceptHunk = () => {
              hunkData.acceptChanges();
              renderHunks();
            };
            const discardHunk = () => {
              hunkData.discardChanges();
              renderHunks();
            };
            const mightContainNonBasicASCII = this.e.textModel0.mightContainNonBasicASCII();
            const mightContainRTL = this.e.textModel0.mightContainRTL();
            const renderOptions = $90.fromEditor(this.f);
            const originalRange = hunkData.getRanges0()[0];
            const source = new $80($_C.fromRangeInclusive(originalRange).mapToLineArray((l) => this.e.textModel0.tokenization.getLineTokens(l)), [], mightContainNonBasicASCII, mightContainRTL);
            const domNode = document.createElement("div");
            domNode.className = "inline-chat-original-zone2";
            const result = $70(source, renderOptions, [new $I5(
              new $9C(originalRange.startLineNumber, 1, originalRange.startLineNumber, 1),
              "",
              0
              /* InlineDecorationType.Regular */
            )], domNode);
            const viewZoneData = {
              afterLineNumber: -1,
              heightInLines: result.heightInLines,
              domNode,
              ordinal: 5e4 + 2
              // more than https://github.com/microsoft/vscode/blob/bf52a5cfb2c75a7327c9adeaefbddc06d529dcad/src/vs/workbench/contrib/inlineChat/browser/inlineChatZoneWidget.ts#L42
            };
            const toggleDiff = () => {
              const scrollState = $O9.capture(this.f);
              changeDecorationsAndViewZones(this.f, (_decorationsAccessor, viewZoneAccessor2) => {
                $Jg(data);
                if (!data.diffViewZoneId) {
                  const [hunkRange] = hunkData.getRangesN();
                  viewZoneData.afterLineNumber = hunkRange.startLineNumber - 1;
                  data.diffViewZoneId = viewZoneAccessor2.addZone(viewZoneData);
                } else {
                  viewZoneAccessor2.removeZone(data.diffViewZoneId);
                  data.diffViewZoneId = void 0;
                }
              });
              this.p.set(typeof data?.diffViewZoneId === "string");
              scrollState.restore(this.f);
            };
            let lensActions;
            const lensActionsViewZoneIds = [];
            if (this.t && hunkData.getState() === 0) {
              lensActions = new $2c();
              const menu = this.x.createMenu($AAb, this.y);
              const makeActions = () => {
                const actions = [];
                const tuples = menu.getActions({ arg: hunkData });
                for (const [, group2] of tuples) {
                  for (const item of group2) {
                    if (item instanceof $fJ) {
                      let text2 = item.label;
                      if (item.id === $wAb) {
                        text2 = item.checked ? "Hide Changes" : "Show Changes";
                      } else if (ThemeIcon.isThemeIcon(item.item.icon)) {
                        text2 = `$(${item.item.icon.id}) ${text2}`;
                      }
                      actions.push({
                        text: text2,
                        tooltip: item.tooltip,
                        action: async () => item.run()
                      });
                    }
                  }
                }
                return actions;
              };
              const obs = $he(this, makeActions());
              lensActions.add(menu.onDidChange(() => obs.set(makeActions(), void 0)));
              lensActions.add(menu);
              lensActions.add(this.r.createWidget(viewZoneAccessor, hunkRanges[0].startLineNumber - 1, obs, lensActionsViewZoneIds));
            }
            const remove = () => {
              changeDecorationsAndViewZones(this.f, (decorationsAccessor2, viewZoneAccessor2) => {
                $Jg(data);
                for (const decorationId of data.decorationIds) {
                  decorationsAccessor2.removeDecoration(decorationId);
                }
                if (data.diffViewZoneId) {
                  viewZoneAccessor2.removeZone(data.diffViewZoneId);
                }
                data.decorationIds = [];
                data.diffViewZoneId = void 0;
                data.lensActionsViewZoneIds?.forEach(viewZoneAccessor2.removeZone);
                data.lensActionsViewZoneIds = void 0;
              });
              lensActions?.dispose();
            };
            const move = (next) => {
              const keys = Array.from(this.C.keys());
              const idx = keys.indexOf(hunkData);
              const nextIdx = (idx + (next ? 1 : -1) + keys.length) % keys.length;
              if (nextIdx !== idx) {
                const nextData = this.C.get(keys[nextIdx]);
                this.g.updatePositionAndHeight(nextData?.position);
                renderHunks();
              }
            };
            const zoneLineNumber = this.g.position?.lineNumber ?? this.f.getPosition().lineNumber;
            const myDistance = zoneLineNumber <= hunkRanges[0].startLineNumber ? hunkRanges[0].startLineNumber - zoneLineNumber : zoneLineNumber - hunkRanges[0].endLineNumber;
            data = {
              hunk: hunkData,
              decorationIds,
              diffViewZoneId: "",
              diffViewZone: viewZoneData,
              lensActionsViewZoneIds,
              distance: myDistance,
              position: hunkRanges[0].getStartPosition().delta(-1),
              acceptHunk,
              discardHunk,
              toggleDiff: !hunkData.isInsertion() ? toggleDiff : void 0,
              remove,
              move
            };
            this.C.set(hunkData, data);
          } else if (hunkData.getState() !== 0) {
            data.remove();
          } else {
            const zoneLineNumber = this.g.position?.lineNumber ?? this.f.getPosition().lineNumber;
            const modifiedRangeNow = hunkRanges[0];
            data.position = modifiedRangeNow.getStartPosition().delta(-1);
            data.distance = zoneLineNumber <= modifiedRangeNow.startLineNumber ? modifiedRangeNow.startLineNumber - zoneLineNumber : zoneLineNumber - modifiedRangeNow.endLineNumber;
          }
          if (hunkData.getState() === 0 && (!widgetData || data.distance < widgetData.distance)) {
            widgetData = data;
          }
        }
        for (const key2 of keysNow) {
          const data = this.C.get(key2);
          if (data) {
            this.C.delete(key2);
            data.remove();
          }
        }
      });
      if (widgetData) {
        this.g.reveal(widgetData.position);
        const mode = this.w.getValue(
          "inlineChat.accessibleDiffView"
          /* InlineChatConfigKeys.AccessibleDiffView */
        );
        if (mode === "on" || mode === "auto" && this.v.isScreenReaderOptimized()) {
          this.g.widget.showAccessibleHunk(this.e, widgetData.hunk);
        }
        this.o.set(Boolean(widgetData.toggleDiff));
      } else if (this.C.size > 0) {
        let oneAccepted = false;
        for (const hunkData of this.e.hunkData.getInfo()) {
          if (hunkData.getState() === 1) {
            oneAccepted = true;
            break;
          }
        }
        if (oneAccepted) {
          this.c.fire();
        } else {
          this.d.fire();
        }
      }
      return widgetData;
    };
    return renderHunks()?.position;
  }
  hasFocus() {
    return this.g.widget.hasFocus();
  }
  getWholeRangeDecoration() {
    return [];
  }
};
$vIb = __decorate([
  __param(4, $on),
  __param(5, $I0),
  __param(6, $ND),
  __param(7, $kl),
  __param(8, $cJ),
  __param(9, $on),
  __param(10, $cK),
  __param(11, $Pk)
], $vIb);
function changeDecorationsAndViewZones(editor, callback) {
  editor.changeDecorations((decorationsAccessor) => {
    editor.changeViewZones((viewZoneAccessor) => {
      callback(decorationsAccessor, viewZoneAccessor);
    });
  });
}

// out-build/vs/workbench/contrib/inlineChat/browser/inlineChatWidget.js
var HunkAccessibleDiffViewer_1;
var $wGb = class $wGb2 {
  constructor(location3, l, m, n, o, p, q, s, t, u, v) {
    this.l = l;
    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.v = v;
    this.a = h("div.inline-chat@root", [
      h("div.chat-widget@chatWidget"),
      h("div.accessibleViewer@accessibleViewer"),
      h("div.status@status", [
        h("div.label.info.hidden@infoLabel"),
        h("div.actions.hidden@toolbar1"),
        h("div.label.status.hidden@statusLabel"),
        h("div.actions.secondary.hidden@toolbar2")
      ])
    ]);
    this.b = new $2c();
    this.g = this.b.add(new $ze());
    this.onDidChangeHeight = Event2.filter(this.g.event, (_) => !this.k);
    this.j = $he(this, false);
    this.requestInProgress = this.j;
    this.k = false;
    this.scopedContextKeyService = this.b.add(n.createScoped(this.a.chatWidget));
    const scopedInstaService = m.createChild(new $Ok([
      $on,
      this.scopedContextKeyService
    ]), this.b);
    this.f = scopedInstaService.createInstance($qNb, location3, void 0, {
      autoScroll: true,
      defaultElementHeight: 32,
      renderStyle: "minimal",
      renderInputOnTop: false,
      renderFollowups: true,
      supportsFileReferences: true,
      filter: (item) => {
        if (!$asb(item) || item.errorDetails) {
          return true;
        }
        const emptyResponse = item.response.value.length === 0;
        if (emptyResponse) {
          return false;
        }
        if (item.response.value.every((item2) => item2.kind === "textEditGroup" && l.chatWidgetViewOptions?.rendererOptions?.renderTextEditsAsSummary?.(item2.uri))) {
          return false;
        }
        return true;
      },
      ...l.chatWidgetViewOptions
    }, {
      listForeground: $BAb,
      listBackground: $CAb,
      overlayBackground: $Cmb,
      inputEditorBackground: $xq,
      resultEditorBackground: $Ko
    });
    this.a.root.classList.toggle("in-zone-widget", !!l.inZoneWidget);
    this.f.render(this.a.chatWidget);
    this.a.chatWidget.style.setProperty($Yn($qGb), $Zn($CAb));
    this.f.setVisible(true);
    this.b.add(this.f);
    const ctxResponse = ChatContextKeys.isResponse.bindTo(this.scopedContextKeyService);
    const ctxResponseVote = ChatContextKeys.responseVote.bindTo(this.scopedContextKeyService);
    const ctxResponseSupportIssues = ChatContextKeys.responseSupportsIssueReporting.bindTo(this.scopedContextKeyService);
    const ctxResponseError = ChatContextKeys.responseHasError.bindTo(this.scopedContextKeyService);
    const ctxResponseErrorFiltered = ChatContextKeys.responseIsFiltered.bindTo(this.scopedContextKeyService);
    const viewModelStore = this.b.add(new $2c());
    this.b.add(this.f.onDidChangeViewModel(() => {
      viewModelStore.clear();
      const viewModel = this.f.viewModel;
      if (!viewModel) {
        return;
      }
      viewModelStore.add($1c(() => {
        toolbar2.context = void 0;
        ctxResponse.reset();
        ctxResponseVote.reset();
        ctxResponseError.reset();
        ctxResponseErrorFiltered.reset();
        ctxResponseSupportIssues.reset();
      }));
      viewModelStore.add(viewModel.onDidChange(() => {
        this.j.set(viewModel.requestInProgress, void 0);
        const last = viewModel.getItems().at(-1);
        toolbar2.context = last;
        ctxResponse.set($asb(last));
        ctxResponseVote.set($asb(last) ? last.vote === ChatAgentVoteDirection.Down ? "down" : last.vote === ChatAgentVoteDirection.Up ? "up" : "" : "");
        ctxResponseError.set($asb(last) && last.errorDetails !== void 0);
        ctxResponseErrorFiltered.set(!!($asb(last) && last.errorDetails?.responseIsFiltered));
        ctxResponseSupportIssues.set($asb(last) && (last.agent?.metadata.supportIssueReporting ?? false));
        this.g.fire();
      }));
      this.g.fire();
    }));
    this.b.add(this.chatWidget.onDidChangeContentHeight(() => {
      this.g.fire();
    }));
    this.d = $cAb.bindTo(this.n);
    const tracker2 = this.b.add($_j(this.domNode));
    this.b.add(tracker2.onDidBlur(() => this.d.set(false)));
    this.b.add(tracker2.onDidFocus(() => this.d.set(true)));
    this.c = $aAb.bindTo(n);
    this.b.add(this.f.inputEditor.onDidFocusEditorWidget(() => this.c.set(true)));
    this.b.add(this.f.inputEditor.onDidBlurEditorWidget(() => this.c.set(false)));
    const statusMenuId = l.statusMenuId instanceof $bJ ? l.statusMenuId : l.statusMenuId.menu;
    const statusMenuOptions = l.statusMenuId instanceof $bJ ? void 0 : l.statusMenuId.options;
    const statusButtonBar = scopedInstaService.createInstance($hsb, this.a.toolbar1, statusMenuId, {
      toolbarOptions: { primaryGroup: "0_main" },
      telemetrySource: l.chatWidgetViewOptions?.menus?.telemetrySource,
      menuOptions: { renderShortTitle: true },
      ...statusMenuOptions
    });
    this.b.add(statusButtonBar.onDidChange(() => this.g.fire()));
    this.b.add(statusButtonBar);
    const toolbar2 = scopedInstaService.createInstance($4$, this.a.toolbar2, l.secondaryMenuId ?? $bJ.for(""), {
      telemetrySource: l.chatWidgetViewOptions?.menus?.telemetrySource,
      menuOptions: { renderShortTitle: true, shouldForwardArgs: true },
      actionViewItemProvider: (action, options3) => {
        if (action instanceof $fJ && action.item.id === $vBb) {
          return scopedInstaService.createInstance($lNb, action, options3);
        }
        return $X$(scopedInstaService, action, options3);
      }
    });
    this.b.add(toolbar2.onDidChangeMenuItems(() => this.g.fire()));
    this.b.add(toolbar2);
    this.b.add(this.q.onDidChangeConfiguration((e) => {
      if (e.affectsConfiguration(
        "accessibility.verbosity.inlineChat"
        /* AccessibilityVerbositySettingId.InlineChat */
      )) {
        this.w();
      }
    }));
    this.a.root.tabIndex = 0;
    this.a.statusLabel.tabIndex = 0;
    this.w();
    this.b.add(this.v.setupManagedHover($JZ("element"), this.a.statusLabel, () => {
      return this.a.statusLabel.dataset["title"];
    }));
    this.b.add(this.u.onDidPerformUserAction((e) => {
      if (e.sessionId === this.f.viewModel?.model.sessionId && e.action.kind === "vote") {
        this.updateStatus("Thank you for your feedback!", { resetAfter: 1250 });
      }
    }));
  }
  w() {
    this.a.root.ariaLabel = this.s.getOpenAriaHint(
      "accessibility.verbosity.inlineChat"
      /* AccessibilityVerbositySettingId.InlineChat */
    );
    if (this.p.isScreenReaderOptimized()) {
      let label3 = defaultAriaLabel;
      if (this.q.getValue(
        "accessibility.verbosity.inlineChat"
        /* AccessibilityVerbositySettingId.InlineChat */
      )) {
        const kbLabel = this.o.lookupKeybinding(
          "editor.action.accessibilityHelp"
          /* AccessibilityCommandId.OpenAccessibilityHelp */
        )?.getLabel();
        label3 = kbLabel ? localize(7505, null, kbLabel) : localize(7506, null);
      }
      this.f.inputEditor.updateOptions({ ariaLabel: label3 });
    }
  }
  dispose() {
    this.b.dispose();
  }
  get domNode() {
    return this.a.root;
  }
  get chatWidget() {
    return this.f;
  }
  saveState() {
    this.f.saveState();
  }
  layout(widgetDim) {
    const contentHeight = this.contentHeight;
    this.k = true;
    try {
      this.x(widgetDim);
    } finally {
      this.k = false;
      if (this.contentHeight !== contentHeight) {
        this.g.fire();
      }
    }
  }
  x(dimension) {
    const extraHeight = this.y();
    const statusHeight = $Bj(this.a.status);
    this.a.root.style.height = `${dimension.height - extraHeight}px`;
    this.a.root.style.width = `${dimension.width}px`;
    this.f.layout(dimension.height - statusHeight - extraHeight, dimension.width);
  }
  /**
   * The content height of this widget is the size that would require no scrolling
   */
  get contentHeight() {
    const data = {
      chatWidgetContentHeight: this.f.contentHeight,
      statusHeight: $Bj(this.a.status),
      extraHeight: this.y()
    };
    const result = data.chatWidgetContentHeight + data.statusHeight + data.extraHeight;
    return result;
  }
  get minHeight() {
    let maxWidgetOutputHeight = 100;
    for (const item of this.f.viewModel?.getItems() ?? []) {
      if ($asb(item) && item.response.value.some((r2) => r2.kind === "textEditGroup" && !r2.state?.applied)) {
        maxWidgetOutputHeight = 270;
        break;
      }
    }
    let value = this.contentHeight;
    value -= this.f.contentHeight;
    value += Math.min(this.f.input.contentHeight + maxWidgetOutputHeight, this.f.contentHeight);
    return value;
  }
  y() {
    return this.l.inZoneWidget ? 1 : 2 + 4;
  }
  get value() {
    return this.f.getInput();
  }
  set value(value) {
    this.f.setInput(value);
  }
  selectAll() {
    this.f.inputEditor.setSelection(new $_D(1, 1, Number.MAX_SAFE_INTEGER, 1));
  }
  set placeholder(value) {
    this.f.setInputPlaceholder(value);
  }
  toggleStatus(show2) {
    this.a.toolbar1.classList.toggle("hidden", !show2);
    this.a.toolbar2.classList.toggle("hidden", !show2);
    this.a.status.classList.toggle("hidden", !show2);
    this.a.infoLabel.classList.toggle("hidden", !show2);
    this.g.fire();
  }
  updateToolbar(show2) {
    this.a.root.classList.toggle("toolbar", show2);
    this.a.toolbar1.classList.toggle("hidden", !show2);
    this.a.toolbar2.classList.toggle("hidden", !show2);
    this.a.status.classList.toggle("actions", show2);
    this.a.infoLabel.classList.toggle("hidden", show2);
    this.g.fire();
  }
  async getCodeBlockInfo(codeBlockIndex) {
    const { viewModel } = this.f;
    if (!viewModel) {
      return void 0;
    }
    const items = viewModel.getItems().filter((i2) => $asb(i2));
    const item = items.at(-1);
    if (!item) {
      return;
    }
    return viewModel.codeBlockModelCollection.get(viewModel.sessionId, item, codeBlockIndex)?.model;
  }
  get responseContent() {
    const requests = this.f.viewModel?.model.getRequests();
    if (!$Qb(requests)) {
      return void 0;
    }
    return requests.at(-1)?.response?.response.toString();
  }
  getChatModel() {
    return this.f.viewModel?.model;
  }
  setChatModel(chatModel, state) {
    this.f.setModel(chatModel, { ...state, inputValue: void 0 });
  }
  updateInfo(message) {
    this.a.infoLabel.classList.toggle("hidden", !message);
    const renderedMessage = $B1(message);
    $dk(this.a.infoLabel, ...renderedMessage);
    this.g.fire();
  }
  updateStatus(message, ops = {}) {
    const isTempMessage = typeof ops.resetAfter === "number";
    if (isTempMessage && !this.a.statusLabel.dataset["state"]) {
      const statusLabel = this.a.statusLabel.innerText;
      const title = this.a.statusLabel.dataset["title"];
      const classes2 = Array.from(this.a.statusLabel.classList.values());
      setTimeout(() => {
        this.updateStatus(statusLabel, { classes: classes2, keepMessage: true, title });
      }, ops.resetAfter);
    }
    const renderedMessage = $B1(message);
    $dk(this.a.statusLabel, ...renderedMessage);
    this.a.statusLabel.className = `label status ${(ops.classes ?? []).join(" ")}`;
    this.a.statusLabel.classList.toggle("hidden", !message);
    if (isTempMessage) {
      this.a.statusLabel.dataset["state"] = "temp";
    } else {
      delete this.a.statusLabel.dataset["state"];
    }
    if (ops.title) {
      this.a.statusLabel.dataset["title"] = ops.title;
    } else {
      delete this.a.statusLabel.dataset["title"];
    }
    this.g.fire();
  }
  reset() {
    this.f.attachmentModel.clear();
    this.f.saveState();
    $dk(this.a.statusLabel);
    this.a.statusLabel.classList.toggle("hidden", true);
    this.a.toolbar1.classList.add("hidden");
    this.a.toolbar2.classList.add("hidden");
    this.updateInfo("");
    this.a.accessibleViewer.classList.toggle("hidden", true);
    this.g.fire();
  }
  focus() {
    this.f.focusInput();
  }
  hasFocus() {
    return this.domNode.contains($Lj());
  }
};
$wGb = __decorate([
  __param(2, $Pk),
  __param(3, $on),
  __param(4, $Ty),
  __param(5, $ND),
  __param(6, $kl),
  __param(7, $shb),
  __param(8, $oG),
  __param(9, $qO),
  __param(10, $5$)
], $wGb);
var defaultAriaLabel = localize(7507, null);
var $xGb = class $xGb2 extends $wGb {
  constructor(location3, A, options3, contextKeyService, keybindingService, instantiationService, accessibilityService, configurationService, accessibleViewService, textModelResolverService, chatService, hoverService, layoutService) {
    const overflowWidgetsNode = layoutService.getContainer(getWindow(A.getContainerDomNode())).appendChild($(".inline-chat-overflow.monaco-editor"));
    super(location3, {
      ...options3,
      chatWidgetViewOptions: {
        ...options3.chatWidgetViewOptions,
        editorOverflowWidgetsDomNode: overflowWidgetsNode
      }
    }, instantiationService, contextKeyService, keybindingService, accessibilityService, configurationService, accessibleViewService, textModelResolverService, chatService, hoverService);
    this.A = A;
    this.z = this.b.add(new $4c());
    this.b.add($1c(() => {
      overflowWidgetsNode.remove();
    }));
  }
  // --- layout
  get contentHeight() {
    let result = super.contentHeight;
    if (this.z.value) {
      result += this.z.value.height + 8;
    }
    return result;
  }
  x(dimension) {
    let newHeight = dimension.height;
    if (this.z.value) {
      this.z.value.width = dimension.width - 12;
      newHeight -= this.z.value.height + 8;
    }
    super.x(dimension.with(void 0, newHeight));
    this.a.root.style.height = `${dimension.height - this.y()}px`;
  }
  reset() {
    this.z.clear();
    super.reset();
  }
  // --- accessible viewer
  showAccessibleHunk(session, hunkData) {
    this.a.accessibleViewer.classList.remove("hidden");
    this.z.clear();
    this.z.value = this.m.createInstance(HunkAccessibleDiffViewer, this.a.accessibleViewer, session, hunkData, new AccessibleHunk(this.A, session, hunkData));
    this.g.fire();
  }
};
$xGb = __decorate([
  __param(3, $on),
  __param(4, $Ty),
  __param(5, $Pk),
  __param(6, $ND),
  __param(7, $kl),
  __param(8, $shb),
  __param(9, $oG),
  __param(10, $qO),
  __param(11, $5$),
  __param(12, $Ulb)
], $xGb);
var HunkAccessibleDiffViewer = HunkAccessibleDiffViewer_1 = class HunkAccessibleDiffViewer2 extends $h$ {
  set width(value) {
    this.z.set(value, void 0);
  }
  constructor(parentNode, session, hunk, models, instantiationService) {
    const width2 = $he("width", 0);
    const diff3 = $he("diff", HunkAccessibleDiffViewer_1.C(hunk));
    const diffs = $2d((r2) => [diff3.read(r2)]);
    const lines = Math.min(10, 8 + diff3.get().changedLineCount);
    const height = models.getModifiedOptions().get(
      68
      /* EditorOption.lineHeight */
    ) * lines;
    super(parentNode, $Bd(true), () => {
    }, $Bd(false), width2, $Bd(height), diffs, models, instantiationService);
    this.height = height;
    this.z = width2;
    this.q.add(session.textModelN.onDidChangeContent(() => {
      diff3.set(HunkAccessibleDiffViewer_1.C(hunk), void 0);
    }));
  }
  static C(hunk) {
    const ranges0 = hunk.getRanges0();
    const rangesN = hunk.getRangesN();
    const originalLineRange = $_C.fromRangeInclusive(ranges0[0]);
    const modifiedLineRange = $_C.fromRangeInclusive(rangesN[0]);
    const innerChanges = [];
    for (let i2 = 1; i2 < ranges0.length; i2++) {
      innerChanges.push(new $rD(ranges0[i2], rangesN[i2]));
    }
    return new $qD(originalLineRange, modifiedLineRange, innerChanges);
  }
};
HunkAccessibleDiffViewer = HunkAccessibleDiffViewer_1 = __decorate([
  __param(4, $Pk)
], HunkAccessibleDiffViewer);
var AccessibleHunk = class {
  constructor(a, b, c) {
    this.a = a;
    this.b = b;
    this.c = c;
  }
  getOriginalModel() {
    return this.b.textModel0;
  }
  getModifiedModel() {
    return this.b.textModelN;
  }
  getOriginalOptions() {
    return this.a.getOptions();
  }
  getModifiedOptions() {
    return this.a.getOptions();
  }
  originalReveal(range) {
  }
  modifiedReveal(range) {
    this.a.revealRangeInCenterIfOutsideViewport(
      range || this.c.getRangesN()[0],
      0
      /* ScrollType.Smooth */
    );
  }
  modifiedSetSelection(range) {
  }
  modifiedFocus() {
    this.a.focus();
  }
  getModifiedPosition() {
    return this.c.getRangesN()[0].getStartPosition();
  }
};

// out-build/vs/workbench/contrib/inlineChat/browser/inlineChatZoneWidget.js
var $yGb_1;
var $yGb = class $yGb2 extends $_db {
  static {
    $yGb_1 = this;
  }
  static {
    this.a = {
      showFrame: true,
      frameWidth: 1,
      // frameColor: 'var(--vscode-inlineChat-border)',
      isResizeable: true,
      showArrow: false,
      isAccessible: true,
      className: "inline-chat-widget",
      keepEditorSelection: true,
      showInHiddenAreas: true,
      ordinal: 5e4
    };
  }
  constructor(location3, editor, i2, m, contextKeyService, configurationService) {
    super(editor, $yGb_1.a);
    this.i = i2;
    this.m = m;
    this.b = this.n.add(new ScrollUpState(this.editor));
    this.c = $iAb.bindTo(contextKeyService);
    this.n.add($1c(() => {
      this.c.reset();
    }));
    this.widget = this.i.createInstance($xGb, location3, this.editor, {
      statusMenuId: {
        menu: $yAb,
        options: {
          buttonConfigProvider: (action, index) => {
            const isSecondary = index > 0;
            if ((/* @__PURE__ */ new Set([$uAb, $wAb, $xAb])).has(action.id)) {
              return { isSecondary, showIcon: true, showLabel: false };
            } else {
              return { isSecondary };
            }
          }
        }
      },
      secondaryMenuId: $zAb,
      inZoneWidget: true,
      chatWidgetViewOptions: {
        menus: {
          telemetrySource: "interactiveEditorWidget-toolbar"
        },
        rendererOptions: {
          renderTextEditsAsSummary: (uri) => {
            return $oh(uri, editor.getModel()?.uri) && configurationService.getValue(
              "inlineChat.mode"
              /* InlineChatConfigKeys.Mode */
            ) === "live";
          },
          renderDetectedCommandsWithRequest: true
        }
      }
    });
    this.n.add(this.widget);
    let revealFn;
    this.n.add(this.widget.chatWidget.onWillMaybeChangeHeight(() => {
      if (this.position) {
        revealFn = this.N(this.position);
      }
    }));
    this.n.add(this.widget.onDidChangeHeight(() => {
      if (this.position && !this.H) {
        revealFn ??= this.N(this.position);
        const height = this.J();
        this.E(height.linesValue);
        revealFn?.();
        revealFn = void 0;
      }
    }));
    this.create();
    this.n.add($td((r2) => {
      const isBusy = this.widget.requestInProgress.read(r2);
      this.domNode.firstElementChild?.classList.toggle("busy", isBusy);
    }));
    this.n.add($_i(this.domNode, "click", (e) => {
      if (!this.editor.hasWidgetFocus() && !this.widget.hasFocus()) {
        this.editor.focus();
      }
    }, true));
    const updateCursorIsAboveContextKey = () => {
      if (!this.position || !this.editor.hasModel()) {
        this.c.reset();
      } else if (this.position.lineNumber === this.editor.getPosition().lineNumber) {
        this.c.set("above");
      } else if (this.position.lineNumber + 1 === this.editor.getPosition().lineNumber) {
        this.c.set("below");
      } else {
        this.c.reset();
      }
    };
    this.n.add(this.editor.onDidChangeCursorPosition((e) => updateCursorIsAboveContextKey()));
    this.n.add(this.editor.onDidFocusEditorText((e) => updateCursorIsAboveContextKey()));
    updateCursorIsAboveContextKey();
  }
  B(container2) {
    container2.style.setProperty("--vscode-inlineChat-background", "var(--vscode-editor-background)");
    container2.appendChild(this.widget.domNode);
  }
  D(heightInPixel) {
    this.M();
    const info = this.editor.getLayoutInfo();
    const width2 = info.contentWidth - info.verticalScrollbarWidth;
    this.d = new $rj(width2, heightInPixel);
    this.widget.layout(this.d);
  }
  J() {
    const chatContentHeight = this.widget.contentHeight;
    const editorHeight = this.editor.getLayoutInfo().height;
    const contentHeight = this.x() + Math.min(chatContentHeight, Math.max(this.widget.minHeight, editorHeight * 0.42));
    const heightInLines = contentHeight / this.editor.getOption(
      68
      /* EditorOption.lineHeight */
    );
    return { linesValue: heightInLines, pixelsValue: contentHeight };
  }
  I() {
    const lineHeight = this.editor.getOption(
      68
      /* EditorOption.lineHeight */
    );
    const decoHeight = this.x();
    const minHeightPx = decoHeight + this.widget.minHeight;
    const maxHeightPx = decoHeight + this.widget.contentHeight;
    return {
      minLines: minHeightPx / lineHeight,
      maxLines: maxHeightPx / lineHeight
    };
  }
  C(_widthInPixel) {
    if (this.d) {
      this.D(this.d.height);
    }
  }
  show(position) {
    $Jg(this.container);
    this.M();
    const revealZone = this.N(position);
    super.show(position, this.J().linesValue);
    this.widget.chatWidget.setVisible(true);
    this.widget.focus();
    revealZone();
    this.b.enable();
  }
  M() {
    $Jg(this.container);
    const info = this.editor.getLayoutInfo();
    const marginWithoutIndentation = info.glyphMarginWidth + info.lineNumbersWidth + info.decorationsWidth;
    this.container.style.paddingLeft = `${marginWithoutIndentation}px`;
  }
  reveal(position) {
    const stickyScroll = this.editor.getOption(
      120
      /* EditorOption.stickyScroll */
    );
    const magicValue = stickyScroll.enabled ? stickyScroll.maxLineCount : 0;
    this.editor.revealLines(
      position.lineNumber + magicValue,
      position.lineNumber + magicValue,
      1
      /* ScrollType.Immediate */
    );
    this.b.reset();
    this.updatePositionAndHeight(position);
  }
  updatePositionAndHeight(position) {
    const revealZone = this.N(position);
    super.updatePositionAndHeight(position, !this.H ? this.J().linesValue : void 0);
    revealZone();
  }
  N(position) {
    const scrollState = $P9.capture(this.editor);
    const lineNumber = position.lineNumber <= 1 ? 1 : 1 + position.lineNumber;
    const scrollTop = this.editor.getScrollTop();
    const lineTop = this.editor.getTopForLineNumber(lineNumber);
    const zoneTop = lineTop - this.J().pixelsValue;
    const hasResponse = this.widget.chatWidget.viewModel?.getItems().find((candidate) => {
      return $asb(candidate) && candidate.response.value.length > 0;
    });
    if (hasResponse && zoneTop < scrollTop || this.b.didScrollUpOrDown) {
      return this.b.runIgnored(() => {
        scrollState.restore(this.editor);
      });
    }
    return this.b.runIgnored(() => {
      scrollState.restore(this.editor);
      const scrollTop2 = this.editor.getScrollTop();
      const lineTop2 = this.editor.getTopForLineNumber(lineNumber);
      const zoneTop2 = lineTop2 - this.J().pixelsValue;
      const editorHeight = this.editor.getLayoutInfo().height;
      const lineBottom = this.editor.getBottomForLineNumber(lineNumber);
      let newScrollTop = zoneTop2;
      let forceScrollTop = false;
      if (lineBottom >= scrollTop2 + editorHeight) {
        newScrollTop = lineBottom - editorHeight;
        forceScrollTop = true;
      }
      if (newScrollTop < scrollTop2 || forceScrollTop) {
        this.m.trace("[IE] REVEAL zone", { zoneTop: zoneTop2, lineTop: lineTop2, lineBottom, scrollTop: scrollTop2, newScrollTop, forceScrollTop });
        this.editor.setScrollTop(
          newScrollTop,
          1
          /* ScrollType.Immediate */
        );
      }
    });
  }
  z(range, isLastLine) {
  }
  hide() {
    const scrollState = $P9.capture(this.editor);
    this.b.disable();
    this.c.reset();
    this.widget.reset();
    this.widget.chatWidget.setVisible(false);
    super.hide();
    $_Z(localize(7508, null));
    scrollState.restore(this.editor);
  }
};
$yGb = $yGb_1 = __decorate([
  __param(2, $Pk),
  __param(3, $wn),
  __param(4, $on),
  __param(5, $kl)
], $yGb);
var ScrollUpState = class {
  constructor(d) {
    this.d = d;
    this.b = false;
    this.c = new $4c();
  }
  dispose() {
    this.c.dispose();
  }
  reset() {
    this.a = void 0;
  }
  enable() {
    this.a = void 0;
    this.c.value = this.d.onDidScrollChange((e) => {
      if (!e.scrollTopChanged || this.b) {
        return;
      }
      this.c.clear();
      this.a = true;
    });
  }
  disable() {
    this.c.clear();
    this.a = void 0;
  }
  runIgnored(callback) {
    return () => {
      this.b = true;
      try {
        return callback();
      } finally {
        this.b = false;
      }
    };
  }
  get didScrollUpOrDown() {
    return this.a;
  }
};

// out-build/vs/workbench/contrib/inlineChat/browser/inlineChatController.js
var $cHb_1;
var State4;
(function(State14) {
  State14["CREATE_SESSION"] = "CREATE_SESSION";
  State14["INIT_UI"] = "INIT_UI";
  State14["WAIT_FOR_INPUT"] = "WAIT_FOR_INPUT";
  State14["SHOW_REQUEST"] = "SHOW_REQUEST";
  State14["PAUSE"] = "PAUSE";
  State14["CANCEL"] = "CANCEL";
  State14["ACCEPT"] = "DONE";
})(State4 || (State4 = {}));
var Message;
(function(Message3) {
  Message3[Message3["NONE"] = 0] = "NONE";
  Message3[Message3["ACCEPT_SESSION"] = 1] = "ACCEPT_SESSION";
  Message3[Message3["CANCEL_SESSION"] = 2] = "CANCEL_SESSION";
  Message3[Message3["PAUSE_SESSION"] = 4] = "PAUSE_SESSION";
  Message3[Message3["CANCEL_REQUEST"] = 8] = "CANCEL_REQUEST";
  Message3[Message3["CANCEL_INPUT"] = 16] = "CANCEL_INPUT";
  Message3[Message3["ACCEPT_INPUT"] = 32] = "ACCEPT_INPUT";
})(Message || (Message = {}));
var $bHb = class {
  static isInlineChatRunOptions(options3) {
    const { initialSelection, initialRange, message, autoSend, position, existingSession } = options3;
    if (typeof message !== "undefined" && typeof message !== "string" || typeof autoSend !== "undefined" && typeof autoSend !== "boolean" || typeof initialRange !== "undefined" && !$9C.isIRange(initialRange) || typeof initialSelection !== "undefined" && !$_D.isISelection(initialSelection) || typeof position !== "undefined" && !$8C.isIPosition(position) || typeof existingSession !== "undefined" && !(existingSession instanceof $mGb)) {
      return false;
    }
    return true;
  }
};
var $cHb = $cHb_1 = class $cHb2 {
  static get(editor) {
    return editor.getContribution($8zb);
  }
  get chatWidget() {
    return this.c.value.widget.chatWidget;
  }
  constructor(v, w, x, y, z, A, B, C, contextKeyService, D, E, notebookEditorService) {
    this.v = v;
    this.w = w;
    this.x = x;
    this.y = y;
    this.z = z;
    this.A = A;
    this.B = B;
    this.C = C;
    this.D = D;
    this.E = E;
    this.a = false;
    this.b = new $2c();
    this.l = this.b.add(new $ze());
    this.n = this.b.add(new $ze());
    this.onDidEnterState = this.n.event;
    this.o = this.b.add(new $ze());
    this.onWillStartSession = this.o.event;
    this.q = this.b.add(new $2c());
    this.s = this.b.add(new $4c());
    this.f = $_zb.bindTo(contextKeyService);
    this.g = $bAb.bindTo(contextKeyService);
    this.i = $kAb.bindTo(contextKeyService);
    this.h = $qAb.bindTo(contextKeyService);
    this.j = $pAb.bindTo(contextKeyService);
    this.k = ChatContextKeys.isResponse.bindTo(contextKeyService);
    ChatContextKeys.responseHasError.bindTo(contextKeyService);
    this.c = new $sf(() => {
      const location3 = {
        location: ChatAgentLocation.Editor,
        resolveData: () => {
          $Jg(this.v.hasModel());
          $Jg(this.t);
          return {
            type: ChatAgentLocation.Editor,
            selection: this.v.getSelection(),
            document: this.t.textModelN.uri,
            wholeRange: this.t?.wholeRange.trackedInitialRange
          };
        }
      };
      for (const notebookEditor of notebookEditorService.listNotebookEditors()) {
        for (const [, codeEditor] of notebookEditor.codeEditors) {
          if (codeEditor === this.v) {
            location3.location = ChatAgentLocation.Notebook;
            break;
          }
        }
      }
      const zone = w.createInstance($yGb, location3, this.v);
      this.b.add(zone);
      this.b.add(zone.widget.chatWidget.onDidClear(async () => {
        const r2 = this.joinCurrentRun();
        this.cancelSession();
        await r2;
        this.run();
      }));
      return zone;
    });
    this.b.add(this.v.onDidChangeModel(async (e) => {
      if (this.t || !e.newModelUrl) {
        return;
      }
      const existingSession = this.x.getSession(this.v, e.newModelUrl);
      if (!existingSession) {
        return;
      }
      this.F("session RESUMING after model change", e);
      await this.run({ existingSession });
    }));
    this.b.add(this.x.onDidEndSession((e) => {
      if (e.session === this.t && e.endedByExternalCause) {
        this.F("session ENDED by external cause");
        this.finishExistingSession();
      }
    }));
    this.b.add(this.x.onDidMoveSession(async (e) => {
      if (e.editor === this.v) {
        this.F("session RESUMING after move", e);
        await this.run({ existingSession: e.session });
      }
    }));
    this.F(`NEW controller`);
  }
  dispose() {
    if (this.H) {
      this.l.fire(
        this.t?.chatModel.hasRequests ? 4 : 2
        /* Message.CANCEL_SESSION */
      );
    }
    this.b.dispose();
    this.a = true;
    this.F("DISPOSED controller");
  }
  F(message, ...more) {
    if (message instanceof Error) {
      this.A.error(message, ...more);
    } else {
      this.A.trace(`[IE] (editor:${this.v.getId()}) ${message}`, ...more);
    }
  }
  getMessage() {
    return this.c.value.widget.responseContent;
  }
  getId() {
    return $8zb;
  }
  G() {
    return this.B.getValue(
      "inlineChat.mode"
      /* InlineChatConfigKeys.Mode */
    );
  }
  getWidgetPosition() {
    return this.c.value.position;
  }
  async run(options3 = {}) {
    try {
      this.finishExistingSession();
      if (this.H) {
        await this.H;
      }
      if (options3.initialSelection) {
        this.v.setSelection(options3.initialSelection);
      }
      this.s.clear();
      this.o.fire();
      this.H = this.I("CREATE_SESSION", options3);
      await this.H;
    } catch (error) {
      this.F("error during run", error);
      $gb(error);
      if (this.t) {
        this.x.releaseSession(this.t);
      }
      this[
        "PAUSE"
        /* State.PAUSE */
      ]();
    } finally {
      this.H = void 0;
    }
  }
  // ---- state machine
  async I(state, options3) {
    let nextState = state;
    while (nextState && !this.a) {
      this.F("setState to ", nextState);
      const p = this[nextState](options3);
      this.n.fire(nextState);
      nextState = await p;
    }
  }
  async [
    "CREATE_SESSION"
    /* State.CREATE_SESSION */
  ](options3) {
    $Jg(this.t === void 0);
    $Jg(this.v.hasModel());
    let session = options3.existingSession;
    let initPosition;
    if (options3.position) {
      initPosition = $8C.lift(options3.position).delta(-1);
      delete options3.position;
    }
    const widgetPosition = this.J(options3.headless ?? session?.headless, true, initPosition);
    let errorMessage = localize(7486, null);
    if (!session) {
      const createSessionCts = new $ad();
      const msgListener = Event2.once(this.l.event)((m) => {
        this.F("state=_createSession) message received", m);
        if (m === 32) {
          options3.autoSend = true;
          this.c.value.widget.updateInfo(localize(7487, null));
        } else {
          createSessionCts.cancel();
        }
      });
      try {
        session = await this.x.createSession(this.v, { editMode: this.G(), wholeRange: options3.initialRange }, createSessionCts.token);
      } catch (error) {
        if (error instanceof $$Gb || error?.name === $$Gb.code) {
          errorMessage = error.message;
        }
      }
      createSessionCts.dispose();
      msgListener.dispose();
      if (createSessionCts.token.isCancellationRequested) {
        if (session) {
          this.x.releaseSession(session);
        }
        return "CANCEL";
      }
    }
    delete options3.initialRange;
    delete options3.existingSession;
    if (!session) {
      $S_.get(this.v)?.showMessage(errorMessage, widgetPosition);
      this.F("Failed to start editor chat");
      return "CANCEL";
    }
    await session.chatModel.waitForInitialization();
    switch (session.editMode) {
      case "preview":
        this.u = this.w.createInstance($uIb, session, this.v, this.c.value);
        break;
      case "live":
      default:
        this.u = this.w.createInstance($vIb, session, this.v, this.c.value, session.headless);
        break;
    }
    this.t = session;
    return "INIT_UI";
  }
  async [
    "INIT_UI"
    /* State.INIT_UI */
  ](options3) {
    $Jg(this.t);
    $Jg(this.u);
    $3hb.get(this.v)?.reject();
    this.q.clear();
    const wholeRangeDecoration = this.v.createDecorationsCollection();
    const handleWholeRangeChange = () => {
      const newDecorations = this.u?.getWholeRangeDecoration() ?? [];
      wholeRangeDecoration.set(newDecorations);
      this.g.set(!this.t?.wholeRange.trackedInitialRange.isEmpty());
    };
    this.q.add($1c(() => {
      wholeRangeDecoration.clear();
      this.g.reset();
    }));
    this.q.add(this.t.wholeRange.onDidChange(handleWholeRangeChange));
    handleWholeRangeChange();
    this.c.value.widget.setChatModel(this.t.chatModel);
    this.O();
    const isModelEmpty = !this.t.chatModel.hasRequests;
    this.c.value.widget.updateToolbar(true);
    this.c.value.widget.toggleStatus(!isModelEmpty);
    this.J(this.t.headless, isModelEmpty);
    this.q.add(this.v.onDidChangeModel((e) => {
      const msg = this.t?.chatModel.hasRequests ? 4 : 2;
      this.F("model changed, pause or cancel session", msg, e);
      this.l.fire(msg);
    }));
    const altVersionNow = this.v.getModel()?.getAlternativeVersionId();
    this.q.add(this.v.onDidChangeModelContent((e) => {
      if (!this.t?.hunkData.ignoreTextModelNChanges) {
        this.i.set(altVersionNow !== this.v.getModel()?.getAlternativeVersionId());
      }
      if (this.t?.hunkData.ignoreTextModelNChanges || this.u?.hasFocus()) {
        return;
      }
      const wholeRange = this.t.wholeRange;
      let shouldFinishSession = false;
      if (this.B.getValue(
        "inlineChat.finishOnType"
        /* InlineChatConfigKeys.FinishOnType */
      )) {
        for (const { range } of e.changes) {
          shouldFinishSession = !$9C.areIntersectingOrTouching(range, wholeRange.value);
        }
      }
      this.t.recordExternalEditOccurred(shouldFinishSession);
      if (shouldFinishSession) {
        this.F("text changed outside of whole range, FINISH session");
        this.finishExistingSession();
      }
    }));
    this.q.add(this.t.chatModel.onDidChange(async (e) => {
      if (e.kind === "removeRequest") {
        await this.t.undoChangesUntil(e.requestId);
      }
    }));
    const editState = this.M();
    let didEdit = false;
    for (const request of this.t.chatModel.getRequests()) {
      if (!request.response || request.response.result?.errorDetails) {
        break;
      }
      for (const part of request.response.response.value) {
        if (part.kind !== "textEditGroup" || !$oh(part.uri, this.t.textModelN.uri)) {
          continue;
        }
        if (part.state?.applied) {
          continue;
        }
        for (const edit3 of part.edits) {
          this.N(edit3, void 0, !didEdit);
          didEdit = true;
        }
        part.state ??= editState;
      }
    }
    if (didEdit) {
      const diff3 = await this.z.computeDiff(this.t.textModel0.uri, this.t.textModelN.uri, { computeMoves: false, maxComputationTimeMs: Number.MAX_SAFE_INTEGER, ignoreTrimWhitespace: false }, "advanced");
      this.t.wholeRange.fixup(diff3?.changes ?? []);
      await this.t.hunkData.recompute(editState, diff3);
      this.L();
    }
    options3.position = await this.u.renderChanges();
    if (this.t.chatModel.requestInProgress) {
      return "SHOW_REQUEST";
    } else {
      return "WAIT_FOR_INPUT";
    }
  }
  async [
    "WAIT_FOR_INPUT"
    /* State.WAIT_FOR_INPUT */
  ](options3) {
    $Jg(this.t);
    $Jg(this.u);
    this.O();
    if (options3.message) {
      this.updateInput(options3.message);
      $$Z(options3.message);
      delete options3.message;
      this.J(this.t.headless, false);
    }
    let message = 0;
    let request;
    const barrier = new $Uh();
    const store = new $2c();
    store.add(this.t.chatModel.onDidChange((e) => {
      if (e.kind === "addRequest") {
        request = e.request;
        message = 32;
        barrier.open();
      }
    }));
    store.add(this.u.onDidAccept(() => this.acceptSession()));
    store.add(this.u.onDidDiscard(() => this.cancelSession()));
    store.add(Event2.once(this.l.event)((m) => {
      this.F("state=_waitForInput) message received", m);
      message = m;
      barrier.open();
    }));
    if (options3.autoSend) {
      delete options3.autoSend;
      this.J(this.t.headless, false);
      this.c.value.widget.chatWidget.acceptInput();
    }
    await barrier.wait();
    store.dispose();
    if (message & (16 | 2)) {
      return "CANCEL";
    }
    if (message & 4) {
      return "PAUSE";
    }
    if (message & 1) {
      this.c.value.widget.selectAll();
      return "DONE";
    }
    if (!request?.message.text) {
      return "WAIT_FOR_INPUT";
    }
    return "SHOW_REQUEST";
  }
  async [
    "SHOW_REQUEST"
    /* State.SHOW_REQUEST */
  ](options3) {
    $Jg(this.t);
    $Jg(this.u);
    $Jg(this.t.chatModel.requestInProgress);
    this.j.set(true);
    const { chatModel } = this.t;
    const request = chatModel.lastRequest;
    $Jg(request);
    $Jg(request.response);
    this.J(this.t.headless, false);
    this.c.value.widget.selectAll();
    this.c.value.widget.updateInfo("");
    this.c.value.widget.toggleStatus(true);
    const { response } = request;
    const responsePromise = new $gi();
    const store = new $2c();
    const progressiveEditsCts = store.add(new $ad());
    const progressiveEditsAvgDuration = new $7i();
    const progressiveEditsClock = $te.create();
    const progressiveEditsQueue = new $3h();
    const origDeco = this.v.getOption(
      103
      /* EditorOption.renderValidationDecorations */
    );
    this.v.updateOptions({
      renderValidationDecorations: "off"
    });
    store.add($1c(() => {
      this.v.updateOptions({
        renderValidationDecorations: origDeco
      });
    }));
    let next = "WAIT_FOR_INPUT";
    store.add(Event2.once(this.l.event)((message) => {
      this.F("state=_makeRequest) message received", message);
      this.D.cancelCurrentRequestForSession(chatModel.sessionId);
      if (message & 2) {
        next = "CANCEL";
      } else if (message & 4) {
        next = "PAUSE";
      } else if (message & 1) {
        next = "DONE";
      }
    }));
    store.add(chatModel.onDidChange(async (e) => {
      if (e.kind === "removeRequest" && e.requestId === request.id) {
        progressiveEditsCts.cancel();
        responsePromise.complete();
        if (e.reason === 1) {
          next = "SHOW_REQUEST";
        } else {
          next = "CANCEL";
        }
        return;
      }
      if (e.kind === "move") {
        $Jg(this.t);
        const log4 = (msg, ...args2) => this.F("state=_showRequest) moving inline chat", msg, ...args2);
        log4("move was requested", e.target, e.range);
        const initialSelection = $_D.fromRange(
          $9C.lift(e.range),
          0
          /* SelectionDirection.LTR */
        );
        const editorPane = await this.E.openEditor({ resource: e.target, options: { selection: initialSelection } }, $oJ);
        if (!editorPane) {
          log4("opening editor failed");
          return;
        }
        const newEditor = editorPane.getControl();
        if (!$P5(newEditor) || !newEditor.hasModel()) {
          log4("new editor is either missing or not a code editor or does not have a model");
          return;
        }
        if (this.x.getSession(newEditor, e.target)) {
          log4("new editor ALREADY has a session");
          return;
        }
        const newSession = await this.x.createSession(newEditor, {
          editMode: this.G(),
          session: this.t
        }, CancellationToken.None);
        $cHb_1.get(newEditor)?.run({ existingSession: newSession });
        next = "CANCEL";
        responsePromise.complete();
        return;
      }
    }));
    store.add(this.c.value.widget.chatWidget.inputEditor.onDidChangeModelContent(() => {
      this.D.cancelCurrentRequestForSession(chatModel.sessionId);
    }));
    let lastLength = 0;
    let isFirstChange = true;
    const editState = this.M();
    let localEditGroup;
    const handleResponse = () => {
      this.L();
      if (!localEditGroup) {
        localEditGroup = response.response.value.find((part) => part.kind === "textEditGroup" && $oh(part.uri, this.t?.textModelN.uri));
      }
      if (localEditGroup) {
        localEditGroup.state ??= editState;
        const edits = localEditGroup.edits;
        const newEdits = edits.slice(lastLength);
        if (newEdits.length > 0) {
          this.F(`${this.t?.textModelN.uri.toString()} received ${newEdits.length} edits`);
          lastLength = edits.length;
          progressiveEditsAvgDuration.update(progressiveEditsClock.elapsed());
          progressiveEditsClock.reset();
          progressiveEditsQueue.queue(async () => {
            const startThen = this.t.wholeRange.value.getStartPosition();
            for (const edits2 of newEdits) {
              await this.N(edits2, {
                duration: progressiveEditsAvgDuration.value,
                token: progressiveEditsCts.token
              }, isFirstChange);
              isFirstChange = false;
            }
            const startNow = this.t.wholeRange.value.getStartPosition();
            if (!startNow.equals(startThen) || !this.c.value.position?.equals(startNow)) {
              this.J(this.t.headless, false, startNow.delta(-1));
            }
          });
        }
      }
      if (response.isCanceled) {
        progressiveEditsCts.cancel();
        responsePromise.complete();
      } else if (response.isComplete) {
        responsePromise.complete();
      }
    };
    store.add(response.onDidChange(handleResponse));
    handleResponse();
    await responsePromise.p;
    await progressiveEditsQueue.whenIdle();
    if (response.result?.errorDetails && !response.result.errorDetails.responseIsFiltered) {
      await this.t.undoChangesUntil(response.requestId);
    }
    store.dispose();
    const diff3 = await this.z.computeDiff(this.t.textModel0.uri, this.t.textModelN.uri, { computeMoves: false, maxComputationTimeMs: Number.MAX_SAFE_INTEGER, ignoreTrimWhitespace: false }, "advanced");
    this.t.wholeRange.fixup(diff3?.changes ?? []);
    await this.t.hunkData.recompute(editState, diff3);
    this.j.set(false);
    let newPosition;
    if (response.result?.errorDetails) {
    } else if (response.response.value.length === 0) {
      const status = localize(7488, null);
      this.c.value.widget.updateStatus(status, { classes: ["warn"] });
    } else {
      this.c.value.widget.updateStatus("");
    }
    const position = await this.u.renderChanges();
    if (position) {
      const selection = this.v.getSelection();
      if (selection?.containsPosition(position)) {
        if (position.lineNumber - selection.startLineNumber > 8) {
          newPosition = position;
        }
      } else {
        newPosition = position;
      }
    }
    this.J(this.t.headless, false, newPosition);
    return next;
  }
  async [
    "PAUSE"
    /* State.PAUSE */
  ]() {
    this.K();
    this.u?.dispose?.();
    this.t = void 0;
  }
  async [
    "DONE"
    /* State.ACCEPT */
  ]() {
    $Jg(this.t);
    $Jg(this.u);
    this.q.clear();
    try {
      await this.u.apply();
    } catch (err) {
      this.C.error(localize(7489, null, $1m(err)));
      this.F("FAILED to apply changes");
      this.F(err);
    }
    this.K();
    this.x.releaseSession(this.t);
    this.u?.dispose();
    this.u = void 0;
    this.t = void 0;
  }
  async [
    "CANCEL"
    /* State.CANCEL */
  ]() {
    this.K();
    if (this.t) {
      $Jg(this.u);
      this.q.clear();
      const shouldStash = !this.t.isUnstashed && this.t.chatModel.hasRequests && this.t.hunkData.size === this.t.hunkData.pending;
      let undoCancelEdits = [];
      try {
        undoCancelEdits = this.u.cancel();
      } catch (err) {
        this.C.error(localize(7490, null, $1m(err)));
        this.F("FAILED to discard changes");
        this.F(err);
      }
      this.s.clear();
      if (shouldStash) {
        this.s.value = this.x.stashSession(this.t, this.v, undoCancelEdits);
      } else {
        this.x.releaseSession(this.t);
      }
    }
    this.u?.dispose();
    this.u = void 0;
    this.t = void 0;
  }
  // ----
  J(headless = false, initialRender = false, position) {
    $Jg(this.v.hasModel());
    this.f.set(true);
    let widgetPosition;
    if (position) {
      widgetPosition = position;
    } else if (this.c.rawValue?.position) {
      if (this.c.rawValue?.position.lineNumber === 1) {
        widgetPosition = this.c.rawValue?.position.delta(-1);
      } else {
        widgetPosition = this.c.rawValue?.position;
      }
    } else {
      widgetPosition = this.v.getSelection().getStartPosition().delta(-1);
    }
    if (this.t && !position && (this.t.hasChangedText || this.t.chatModel.hasRequests)) {
      widgetPosition = this.t.wholeRange.trackedInitialRange.getStartPosition().delta(-1);
    }
    if (initialRender && this.v.getOption(
      120
      /* EditorOption.stickyScroll */
    ).enabled) {
      this.v.revealLine(widgetPosition.lineNumber);
    }
    if (!headless) {
      if (this.c.rawValue?.position) {
        this.c.value.updatePositionAndHeight(widgetPosition);
      } else {
        this.c.value.show(widgetPosition);
      }
    }
    return widgetPosition;
  }
  K() {
    this.q.clear();
    this.f.reset();
    this.i.reset();
    this.c.rawValue?.hide();
    if (this.v.hasWidgetFocus()) {
      this.v.focus();
    }
  }
  L() {
    if (!this.t) {
      this.h.set(
        "none"
        /* InlineChatResponseType.None */
      );
      return;
    }
    const hasLocalEdit = (response) => {
      return response.value.some((part) => part.kind === "textEditGroup" && $oh(part.uri, this.t?.textModelN.uri));
    };
    let responseType = "none";
    for (const request of this.t.chatModel.getRequests()) {
      if (!request.response) {
        continue;
      }
      responseType = "messages";
      if (hasLocalEdit(request.response.response)) {
        responseType = "messagesAndEdits";
        break;
      }
    }
    this.h.set(responseType);
    this.k.set(
      responseType !== "none"
      /* InlineChatResponseType.None */
    );
  }
  M() {
    $Jg(this.t);
    const sha1 = new $CGb();
    const textModel0Sha1 = sha1.canComputeSHA1(this.t.textModel0) ? sha1.computeSHA1(this.t.textModel0) : $ps();
    return {
      sha1: textModel0Sha1,
      applied: 0
    };
  }
  async N(edits, opts, undoStopBefore) {
    $Jg(this.t);
    $Jg(this.u);
    const moreMinimalEdits = await this.z.computeMoreMinimalEdits(this.t.textModelN.uri, edits);
    this.F("edits from PROVIDER and after making them MORE MINIMAL", this.t.agent.extensionId, edits, moreMinimalEdits);
    if (moreMinimalEdits?.length === 0) {
      return;
    }
    const actualEdits = !opts && moreMinimalEdits ? moreMinimalEdits : edits;
    const editOperations = actualEdits.map($VE.asEditOperation);
    const editsObserver = {
      start: () => this.t.hunkData.ignoreTextModelNChanges = true,
      stop: () => this.t.hunkData.ignoreTextModelNChanges = false
    };
    this.y.markChanged(this.t);
    if (opts) {
      await this.u.makeProgressiveChanges(editOperations, editsObserver, opts, undoStopBefore);
    } else {
      await this.u.makeChanges(editOperations, editsObserver, undoStopBefore);
    }
  }
  O() {
    this.c.value.widget.placeholder = this.t?.agent.description ?? "";
  }
  // ---- controller API
  acceptInput() {
    return this.chatWidget.acceptInput();
  }
  updateInput(text2, selectAll = true) {
    this.c.value.widget.chatWidget.setInput(text2);
    if (selectAll) {
      const newSelection = new $_D(1, 1, Number.MAX_SAFE_INTEGER, 1);
      this.c.value.widget.chatWidget.inputEditor.setSelection(newSelection);
    }
  }
  cancelCurrentRequest() {
    this.l.fire(
      16 | 8
      /* Message.CANCEL_REQUEST */
    );
  }
  arrowOut(up) {
    if (this.c.value.position && this.v.hasModel()) {
      const { column } = this.v.getPosition();
      const { lineNumber } = this.c.value.position;
      const newLine = up ? lineNumber : lineNumber + 1;
      this.v.setPosition({ lineNumber: newLine, column });
      this.v.focus();
    }
  }
  focus() {
    this.c.value.widget.focus();
  }
  hasFocus() {
    return this.c.value.widget.hasFocus();
  }
  async viewInChat() {
    if (!this.u || !this.t) {
      return;
    }
    let someApplied = false;
    let lastEdit;
    const uri = this.v.getModel()?.uri;
    const requests = this.t.chatModel.getRequests();
    for (const request of requests) {
      if (!request.response) {
        continue;
      }
      for (const part of request.response.response.value) {
        if (part.kind === "textEditGroup" && $oh(part.uri, uri)) {
          someApplied = someApplied || Boolean(part.state?.applied);
          lastEdit = part;
        }
      }
    }
    const doEdits = this.u.cancel();
    if (someApplied) {
      $Jg(lastEdit);
      lastEdit.edits = [doEdits];
      lastEdit.state.applied = 0;
    }
    await this.w.invokeFunction(moveToPanelChat, this.t?.chatModel);
    this.cancelSession();
  }
  acceptSession() {
    const response = this.t?.chatModel.getRequests().at(-1)?.response;
    if (response) {
      this.D.notifyUserAction({
        sessionId: response.session.sessionId,
        requestId: response.requestId,
        agentId: response.agent?.id,
        command: response.slashCommand?.name,
        result: response.result,
        action: {
          kind: "inlineChat",
          action: "accepted"
        }
      });
    }
    this.l.fire(
      1
      /* Message.ACCEPT_SESSION */
    );
  }
  acceptHunk(hunkInfo) {
    return this.u?.performHunkAction(
      hunkInfo,
      0
      /* HunkAction.Accept */
    );
  }
  discardHunk(hunkInfo) {
    return this.u?.performHunkAction(
      hunkInfo,
      1
      /* HunkAction.Discard */
    );
  }
  toggleDiff(hunkInfo) {
    return this.u?.performHunkAction(
      hunkInfo,
      4
      /* HunkAction.ToggleDiff */
    );
  }
  moveHunk(next) {
    this.focus();
    this.u?.performHunkAction(
      void 0,
      next ? 2 : 3
      /* HunkAction.MovePrev */
    );
  }
  async cancelSession() {
    const response = this.t?.chatModel.lastRequest?.response;
    if (response) {
      this.D.notifyUserAction({
        sessionId: response.session.sessionId,
        requestId: response.requestId,
        agentId: response.agent?.id,
        command: response.slashCommand?.name,
        result: response.result,
        action: {
          kind: "inlineChat",
          action: "discarded"
        }
      });
    }
    this.l.fire(
      2
      /* Message.CANCEL_SESSION */
    );
  }
  finishExistingSession() {
    if (this.t) {
      if (this.t.editMode === "preview") {
        this.F("finishing existing session, using CANCEL", this.t.editMode);
        this.cancelSession();
      } else {
        this.F("finishing existing session, using APPLY", this.t.editMode);
        this.acceptSession();
      }
    }
  }
  reportIssue() {
    const response = this.t?.chatModel.lastRequest?.response;
    if (response) {
      this.D.notifyUserAction({
        sessionId: response.session.sessionId,
        requestId: response.requestId,
        agentId: response.agent?.id,
        command: response.slashCommand?.name,
        result: response.result,
        action: { kind: "bug" }
      });
    }
  }
  unstashLastSession() {
    const result = this.s.value?.unstash();
    if (result) {
      this.y.markChanged(result);
    }
    return result;
  }
  joinCurrentRun() {
    return this.H;
  }
  async reviewEdits(anchor, stream, token) {
    if (!this.v.hasModel()) {
      return false;
    }
    const session = await this.x.createSession(this.v, { editMode: "live", wholeRange: anchor, headless: true }, token);
    if (!session) {
      return false;
    }
    const request = session.chatModel.addRequest({ text: "DUMMY", parts: [] }, { variables: [] }, 0);
    const run = this.run({
      existingSession: session,
      headless: true
    });
    await Event2.toPromise(Event2.filter(
      this.n.event,
      (candidate) => candidate === "SHOW_REQUEST"
      /* State.SHOW_REQUEST */
    ));
    for await (const chunk of stream) {
      session.chatModel.acceptResponseProgress(request, { kind: "textEdit", uri: this.v.getModel().uri, edits: chunk });
    }
    if (token.isCancellationRequested) {
      session.chatModel.cancelRequest(request);
    } else {
      session.chatModel.completeResponse(request);
    }
    await Event2.toPromise(Event2.filter(
      this.n.event,
      (candidate) => candidate === "WAIT_FOR_INPUT"
      /* State.WAIT_FOR_INPUT */
    ));
    if (session.hunkData.pending === 0) {
      this.cancelSession();
    }
    await run;
    return true;
  }
};
$cHb = $cHb_1 = __decorate([
  __param(1, $Pk),
  __param(2, $kGb),
  __param(3, $9Gb),
  __param(4, $I0),
  __param(5, $wn),
  __param(6, $kl),
  __param(7, $Yv),
  __param(8, $on),
  __param(9, $qO),
  __param(10, $mJ),
  __param(11, $yMb)
], $cHb);
async function moveToPanelChat(accessor, model) {
  const viewsService = accessor.get($uob);
  const chatService = accessor.get($qO);
  const widget = await $3Nb(viewsService);
  if (widget && widget.viewModel && model) {
    for (const request of model.getRequests().slice()) {
      await chatService.adoptRequest(widget.viewModel.model.sessionId, request);
    }
    widget.focusLastMessage();
  }
}

// out-build/vs/workbench/contrib/chat/browser/codeBlockPart.js
var $101 = $;
var $dHb = "vscode-local-file";
function $eHb(text2) {
  let data;
  try {
    data = JSON.parse(text2);
  } catch (e) {
    throw new Error("Could not parse code block local file data");
  }
  let uri;
  try {
    uri = URI.revive(data?.uri);
  } catch (e) {
    throw new Error("Invalid code block local file data URI");
  }
  let range;
  if (data.range) {
    range = new $9C(data.range.startLineNumber + 1, data.range.startColumn + 1, data.range.endLineNumber + 1, data.range.endColumn + 1);
  }
  return { uri, range };
}
var defaultCodeblockPadding = 10;
var $fHb = class $fHb2 extends $3c {
  constructor(r2, menuId, delegate, overflowWidgetsDomNode, instantiationService, contextKeyService, s, t, u) {
    super();
    this.r = r2;
    this.menuId = menuId;
    this.s = s;
    this.t = t;
    this.u = u;
    this.a = this.B(new $ze());
    this.onDidChangeContentHeight = this.a.event;
    this.j = 0;
    this.m = false;
    this.element = $101(".interactive-result-code-block");
    this.n = this.B(instantiationService.createInstance($lqb));
    this.c = this.B(contextKeyService.createScoped(this.element));
    const scopedInstantiationService = this.B(instantiationService.createChild(new $Ok([$on, this.c])));
    const editorElement = $bk(this.element, $101(".interactive-result-editor"));
    this.editor = this.w(scopedInstantiationService, editorElement, {
      ...$Zsb(this.t),
      readOnly: true,
      lineNumbers: "off",
      selectOnLineNumbers: true,
      scrollBeyondLastLine: false,
      lineDecorationsWidth: 8,
      dragAndDrop: false,
      padding: { top: defaultCodeblockPadding, bottom: defaultCodeblockPadding },
      mouseWheelZoom: false,
      scrollbar: {
        vertical: "hidden",
        alwaysConsumeMouseWheel: false
      },
      definitionLinkOpensInPeek: false,
      gotoLocation: {
        multiple: "goto",
        multipleDeclarations: "goto",
        multipleDefinitions: "goto",
        multipleImplementations: "goto"
      },
      ariaLabel: localize(5036, null),
      overflowWidgetsDomNode,
      ...this.C()
    });
    const toolbarElement = $bk(this.element, $101(".interactive-result-code-block-toolbar"));
    const editorScopedService = this.editor.contextKeyService.createScoped(toolbarElement);
    const editorScopedInstantiationService = this.B(scopedInstantiationService.createChild(new $Ok([$on, editorScopedService])));
    this.b = this.B(editorScopedInstantiationService.createInstance($4$, toolbarElement, menuId, {
      menuOptions: {
        shouldForwardArgs: true
      }
    }));
    const vulnsContainer = $bk(this.element, $101(".interactive-result-vulns"));
    const vulnsHeaderElement = $bk(vulnsContainer, $101(".interactive-result-vulns-header", void 0));
    this.f = this.B(new $k2(vulnsHeaderElement, {
      buttonBackground: void 0,
      buttonBorder: void 0,
      buttonForeground: void 0,
      buttonHoverBackground: void 0,
      buttonSecondaryBackground: void 0,
      buttonSecondaryForeground: void 0,
      buttonSecondaryHoverBackground: void 0,
      buttonSeparator: void 0,
      supportIcons: true
    }));
    this.g = $bk(vulnsContainer, $101("ul.interactive-result-vulns-list"));
    this.B(this.f.onDidClick(() => {
      const element = this.h.element;
      element.vulnerabilitiesListExpanded = !element.vulnerabilitiesListExpanded;
      this.f.label = this.H();
      this.element.classList.toggle("chat-vulnerabilities-collapsed", !element.vulnerabilitiesListExpanded);
      this.a.fire();
    }));
    this.B(this.b.onDidChangeDropdownVisibility((e) => {
      toolbarElement.classList.toggle("force-visibility", e);
    }));
    this.z();
    this.B(this.u.onDidChangeScreenReaderOptimized(() => this.z()));
    this.B(this.t.onDidChangeConfiguration((e) => {
      if (e.affectedKeys.has(
        "accessibility.verbosity.panelChat"
        /* AccessibilityVerbositySettingId.Chat */
      )) {
        this.z();
      }
    }));
    this.B(this.r.onDidChange(() => {
      this.editor.updateOptions(this.C());
    }));
    this.B(this.editor.onDidScrollChange((e) => {
      this.j = e.scrollWidth;
    }));
    this.B(this.editor.onDidContentSizeChange((e) => {
      if (e.contentHeightChanged) {
        this.a.fire();
      }
    }));
    this.B(this.editor.onDidBlurEditorWidget(() => {
      this.element.classList.remove("focused");
      $Vkb.get(this.editor)?.stopHighlighting();
      this.F();
    }));
    this.B(this.editor.onDidFocusEditorWidget(() => {
      this.element.classList.add("focused");
      $Vkb.get(this.editor)?.restoreViewState(true);
    }));
    if (delegate.onDidScroll) {
      this.B(delegate.onDidScroll((e) => {
        this.F();
      }));
    }
  }
  dispose() {
    this.m = true;
    super.dispose();
  }
  get uri() {
    return this.editor.getModel()?.uri;
  }
  w(instantiationService, parent, options3) {
    return this.B(instantiationService.createInstance($D9, parent, options3, {
      isSimpleWidget: false,
      contributions: EditorExtensionsRegistry.getSomeEditorContributions([
        $Esb.ID,
        $Fsb,
        $Mfb.ID,
        $Vkb.ID,
        $kkb.ID,
        $r_.ID,
        $mkb.ID,
        $Afb.ID,
        $Fib.ID,
        $S_.ID,
        $iib.ID,
        $Lbb.ID,
        $Ajb.ID,
        $7Gb.ID
      ])
    }));
  }
  focus() {
    this.editor.focus();
  }
  y() {
    const horizontalScrollbarVisible = this.j > this.editor.getLayoutInfo().contentWidth;
    const scrollbarHeight = this.editor.getLayoutInfo().horizontalScrollbarHeight;
    const bottomPadding = horizontalScrollbarVisible ? Math.max(defaultCodeblockPadding - scrollbarHeight, 2) : defaultCodeblockPadding;
    this.editor.updateOptions({ padding: { top: defaultCodeblockPadding, bottom: bottomPadding } });
  }
  z() {
    const toolbarElt = this.b.getElement();
    if (this.u.isScreenReaderOptimized()) {
      toolbarElt.style.display = "block";
      toolbarElt.ariaLabel = this.t.getValue(
        "accessibility.verbosity.panelChat"
        /* AccessibilityVerbositySettingId.Chat */
      ) ? localize(5037, null) : localize(5038, null);
    } else {
      toolbarElt.style.display = "";
    }
  }
  C() {
    return {
      wordWrap: this.r.configuration.resultEditor.wordWrap,
      fontLigatures: this.r.configuration.resultEditor.fontLigatures,
      bracketPairColorization: this.r.configuration.resultEditor.bracketPairColorization,
      fontFamily: this.r.configuration.resultEditor.fontFamily === "default" ? EDITOR_FONT_DEFAULTS.fontFamily : this.r.configuration.resultEditor.fontFamily,
      fontSize: this.r.configuration.resultEditor.fontSize,
      fontWeight: this.r.configuration.resultEditor.fontWeight,
      lineHeight: this.r.configuration.resultEditor.lineHeight
    };
  }
  layout(width2) {
    const contentHeight = this.D();
    const editorBorder = 2;
    this.editor.layout({ width: width2 - editorBorder, height: contentHeight });
    this.y();
  }
  D() {
    if (this.h?.range) {
      const lineCount = this.h.range.endLineNumber - this.h.range.startLineNumber + 1;
      const lineHeight = this.editor.getOption(
        68
        /* EditorOption.lineHeight */
      );
      return lineCount * lineHeight;
    }
    return this.editor.getContentHeight();
  }
  async render(data, width2) {
    this.h = data;
    if (data.parentContextKeyService) {
      this.c.updateParent(data.parentContextKeyService);
    }
    if (this.r.configuration.resultEditor.wordWrap === "on") {
      this.layout(width2);
    }
    await this.G(data);
    if (this.m) {
      return;
    }
    this.layout(width2);
    this.editor.updateOptions({ ariaLabel: localize(5039, null, data.codeBlockIndex + 1) });
    if (data.hideToolbar) {
      $ik(this.b.getElement());
    } else {
      $hk(this.b.getElement());
    }
    if (data.vulns?.length && $asb(data.element)) {
      $$i(this.g);
      this.element.classList.remove("no-vulns");
      this.element.classList.toggle("chat-vulnerabilities-collapsed", !data.element.vulnerabilitiesListExpanded);
      $bk(this.g, ...data.vulns.map((v) => $101("li", void 0, $101("span.chat-vuln-title", void 0, v.title), " " + v.description)));
      this.f.label = this.H();
    } else {
      this.element.classList.add("no-vulns");
    }
  }
  reset() {
    this.F();
  }
  F() {
    $Afb.get(this.editor)?.hideContentHover();
    $Fib.get(this.editor)?.hideContentHover();
  }
  async G(data) {
    const textModel = await data.textModel;
    this.editor.setModel(textModel);
    if (data.range) {
      this.editor.setSelection(data.range);
      this.editor.revealRangeInCenter(
        data.range,
        1
        /* ScrollType.Immediate */
      );
    }
    this.b.context = {
      code: textModel.getTextBuffer().getValueInRange(
        data.range ?? textModel.getFullModelRange(),
        0
        /* EndOfLinePreference.TextDefined */
      ),
      codeBlockIndex: data.codeBlockIndex,
      element: data.element,
      languageId: textModel.getLanguageId(),
      codemapperUri: data.codemapperUri
    };
    this.n.set(textModel.uri);
  }
  H() {
    if (!this.h || !this.h.vulns) {
      return "";
    }
    const referencesLabel = this.h.vulns.length > 1 ? localize(5040, null, this.h.vulns.length) : localize(5041, null, 1);
    const icon2 = (element) => element.vulnerabilitiesListExpanded ? $6l.chevronDown : $6l.chevronRight;
    return `${referencesLabel} $(${icon2(this.h.element).id})`;
  }
};
$fHb = __decorate([
  __param(4, $Pk),
  __param(5, $on),
  __param(6, $sG),
  __param(7, $kl),
  __param(8, $ND)
], $fHb);
var $gHb = class $gHb2 extends $3c {
  constructor(textModelService, a) {
    super();
    this.a = a;
    this.B(textModelService.registerTextModelContentProvider(Schemas.vscodeChatCodeBlock, this));
  }
  async provideTextContent(resource) {
    const existing = this.a.getModel(resource);
    if (existing) {
      return existing;
    }
    return this.a.createModel("", null, resource);
  }
};
$gHb = __decorate([
  __param(0, $oG),
  __param(1, $sG)
], $gHb);
var $hHb = class $hHb2 extends $3c {
  constructor(n, menuId, delegate, overflowWidgetsDomNode, instantiationService, contextKeyService, r2, s, t, u, w) {
    super();
    this.n = n;
    this.menuId = menuId;
    this.r = r2;
    this.s = s;
    this.t = t;
    this.u = u;
    this.w = w;
    this.a = this.B(new $ze());
    this.onDidChangeContentHeight = this.a.event;
    this.j = this.q.add(new $4c());
    this.m = 0;
    this.element = $101(".interactive-result-code-block");
    this.element.classList.add("compare");
    this.h = $bk(this.element, $101(".message"));
    this.h.setAttribute("role", "status");
    this.h.tabIndex = 0;
    this.b = this.B(contextKeyService.createScoped(this.element));
    const scopedInstantiationService = this.B(instantiationService.createChild(new $Ok([$on, this.b], [$ZJ, new class {
      show(_total, _delay) {
        return $UJ;
      }
      async showWhile(promise, _delay) {
        await promise;
      }
    }()])));
    const editorHeader = $bk(this.element, $101(".interactive-result-header.show-file-icons"));
    const editorElement = $bk(this.element, $101(".interactive-result-editor"));
    this.c = this.y(scopedInstantiationService, editorElement, {
      ...$Zsb(this.s),
      lineNumbers: "on",
      selectOnLineNumbers: true,
      scrollBeyondLastLine: false,
      lineDecorationsWidth: 12,
      dragAndDrop: false,
      padding: { top: defaultCodeblockPadding, bottom: defaultCodeblockPadding },
      mouseWheelZoom: false,
      scrollbar: {
        vertical: "hidden",
        alwaysConsumeMouseWheel: false
      },
      definitionLinkOpensInPeek: false,
      gotoLocation: {
        multiple: "goto",
        multipleDeclarations: "goto",
        multipleDefinitions: "goto",
        multipleImplementations: "goto"
      },
      ariaLabel: localize(5042, null),
      overflowWidgetsDomNode,
      ...this.D()
    });
    this.f = this.B(scopedInstantiationService.createInstance($msb, editorHeader, { supportIcons: true }));
    const editorScopedService = this.c.getModifiedEditor().contextKeyService.createScoped(editorHeader);
    const editorScopedInstantiationService = this.B(scopedInstantiationService.createChild(new $Ok([$on, editorScopedService])));
    this.g = this.B(editorScopedInstantiationService.createInstance($4$, editorHeader, menuId, {
      menuOptions: {
        shouldForwardArgs: true
      }
    }));
    this.C();
    this.B(this.t.onDidChangeScreenReaderOptimized(() => this.C()));
    this.B(this.s.onDidChangeConfiguration((e) => {
      if (e.affectedKeys.has(
        "accessibility.verbosity.panelChat"
        /* AccessibilityVerbositySettingId.Chat */
      )) {
        this.C();
      }
    }));
    this.B(this.n.onDidChange(() => {
      this.c.updateOptions(this.D());
    }));
    this.B(this.c.getModifiedEditor().onDidScrollChange((e) => {
      this.m = e.scrollWidth;
    }));
    this.B(this.c.onDidContentSizeChange((e) => {
      if (e.contentHeightChanged) {
        this.a.fire();
      }
    }));
    this.B(this.c.getModifiedEditor().onDidBlurEditorWidget(() => {
      this.element.classList.remove("focused");
      $Vkb.get(this.c.getModifiedEditor())?.stopHighlighting();
      this.F();
    }));
    this.B(this.c.getModifiedEditor().onDidFocusEditorWidget(() => {
      this.element.classList.add("focused");
      $Vkb.get(this.c.getModifiedEditor())?.restoreViewState(true);
    }));
    if (delegate.onDidScroll) {
      this.B(delegate.onDidScroll((e) => {
        this.F();
      }));
    }
  }
  get uri() {
    return this.c.getModifiedEditor().getModel()?.uri;
  }
  y(instantiationService, parent, options3) {
    const widgetOptions = {
      isSimpleWidget: false,
      contributions: EditorExtensionsRegistry.getSomeEditorContributions([
        $Esb.ID,
        $Fsb,
        $Mfb.ID,
        $Vkb.ID,
        $kkb.ID,
        $r_.ID,
        $mkb.ID,
        $Afb.ID,
        $Fib.ID,
        $iib.ID
      ])
    };
    return this.B(instantiationService.createInstance($c_, parent, {
      scrollbar: { useShadows: false, alwaysConsumeMouseWheel: false, ignoreHorizontalScrollbarInContentHeight: true },
      renderMarginRevertIcon: false,
      diffCodeLens: false,
      scrollBeyondLastLine: false,
      stickyScroll: { enabled: false },
      originalAriaLabel: localize(5043, null),
      modifiedAriaLabel: localize(5044, null),
      diffAlgorithm: "advanced",
      readOnly: false,
      isInEmbeddedEditor: true,
      useInlineViewWhenSpaceIsLimited: true,
      experimental: {
        useTrueInlineView: true
      },
      renderSideBySideInlineBreakpoint: 300,
      renderOverviewRuler: false,
      compactMode: true,
      hideUnchangedRegions: { enabled: true, contextLineCount: 1 },
      renderGutterMenu: false,
      lineNumbersMinChars: 1,
      ...options3
    }, { originalEditor: widgetOptions, modifiedEditor: widgetOptions }));
  }
  focus() {
    this.c.focus();
  }
  z() {
    const horizontalScrollbarVisible = this.m > this.c.getModifiedEditor().getLayoutInfo().contentWidth;
    const scrollbarHeight = this.c.getModifiedEditor().getLayoutInfo().horizontalScrollbarHeight;
    const bottomPadding = horizontalScrollbarVisible ? Math.max(defaultCodeblockPadding - scrollbarHeight, 2) : defaultCodeblockPadding;
    this.c.updateOptions({ padding: { top: defaultCodeblockPadding, bottom: bottomPadding } });
  }
  C() {
    const toolbarElt = this.g.getElement();
    if (this.t.isScreenReaderOptimized()) {
      toolbarElt.style.display = "block";
      toolbarElt.ariaLabel = this.s.getValue(
        "accessibility.verbosity.panelChat"
        /* AccessibilityVerbositySettingId.Chat */
      ) ? localize(5045, null) : localize(5046, null);
    } else {
      toolbarElt.style.display = "";
    }
  }
  D() {
    return {
      wordWrap: this.n.configuration.resultEditor.wordWrap,
      fontLigatures: this.n.configuration.resultEditor.fontLigatures,
      bracketPairColorization: this.n.configuration.resultEditor.bracketPairColorization,
      fontFamily: this.n.configuration.resultEditor.fontFamily === "default" ? EDITOR_FONT_DEFAULTS.fontFamily : this.n.configuration.resultEditor.fontFamily,
      fontSize: this.n.configuration.resultEditor.fontSize,
      fontWeight: this.n.configuration.resultEditor.fontWeight,
      lineHeight: this.n.configuration.resultEditor.lineHeight
    };
  }
  layout(width2) {
    const editorBorder = 2;
    const toolbar = $Bj(this.g.getElement());
    const content = this.c.getModel() ? this.c.getContentHeight() : $Bj(this.h);
    const dimension = new $rj(width2 - editorBorder, toolbar + content);
    this.element.style.height = `${dimension.height}px`;
    this.element.style.width = `${dimension.width}px`;
    this.c.layout(dimension.with(void 0, content - editorBorder));
    this.z();
  }
  async render(data, width2, token) {
    if (data.parentContextKeyService) {
      this.b.updateParent(data.parentContextKeyService);
    }
    if (this.n.configuration.resultEditor.wordWrap === "on") {
      this.layout(width2);
    }
    await this.G(data, token);
    this.layout(width2);
    this.c.updateOptions({ ariaLabel: localize(5047, null) });
    this.f.element.setFile(data.edit.uri, {
      fileKind: FileKind.FILE,
      fileDecorations: { colors: true, badges: false }
    });
  }
  reset() {
    this.F();
  }
  F() {
    $Afb.get(this.c.getOriginalEditor())?.hideContentHover();
    $Afb.get(this.c.getModifiedEditor())?.hideContentHover();
    $Fib.get(this.c.getOriginalEditor())?.hideContentHover();
    $Fib.get(this.c.getModifiedEditor())?.hideContentHover();
  }
  async G(data, token) {
    if (!$asb(data.element)) {
      return;
    }
    const isEditApplied = Boolean(data.edit.state?.applied ?? 0);
    ChatContextKeys.editApplied.bindTo(this.b).set(isEditApplied);
    this.element.classList.toggle("no-diff", isEditApplied);
    if (isEditApplied) {
      $Jg(data.edit.state?.applied);
      const uriLabel = this.u.getUriLabel(data.edit.uri, { relative: true, noPrefix: true });
      let template;
      if (data.edit.state.applied === 1) {
        template = localize(5048, null, uriLabel);
      } else if (data.edit.state.applied < 0) {
        template = localize(5049, null, uriLabel);
      } else {
        template = localize(5050, null, data.edit.state.applied, uriLabel);
      }
      const message = $RZ(template, {
        renderCodeSegments: true,
        actionHandler: {
          callback: () => {
            this.w.open(data.edit.uri, { fromUserGesture: true, allowCommands: false });
          },
          disposables: this.q
        }
      });
      $dk(this.h, message);
    }
    const diffData = await data.diffData;
    if (!isEditApplied && diffData) {
      const viewModel = this.c.createViewModel({
        original: diffData.original,
        modified: diffData.modified
      });
      await viewModel.waitForDiff();
      if (token.isCancellationRequested) {
        return;
      }
      const listener = Event2.any(diffData.original.onWillDispose, diffData.modified.onWillDispose)(() => {
        this.c.setModel(null);
      });
      this.c.setModel(viewModel);
      this.j.value = $Zc(listener, viewModel);
    } else {
      this.c.setModel(null);
      this.j.value = void 0;
      this.a.fire();
    }
    this.g.context = {
      edit: data.edit,
      element: data.element,
      diffEditor: this.c
    };
  }
};
$hHb = __decorate([
  __param(4, $Pk),
  __param(5, $on),
  __param(6, $sG),
  __param(7, $kl),
  __param(8, $ND),
  __param(9, $ZI),
  __param(10, $O4)
], $hHb);
var $iHb = class $iHb2 {
  constructor(b, c, d) {
    this.b = b;
    this.c = c;
    this.d = d;
    this.a = new $CGb();
  }
  async apply(response, item, diffEditor) {
    if (!response.response.value.includes(item)) {
      return;
    }
    if (item.state?.applied) {
      return;
    }
    if (!diffEditor) {
      for (const candidate of this.c.listDiffEditors()) {
        if (!candidate.getContainerDomNode().isConnected) {
          continue;
        }
        const model = candidate.getModel();
        if (!model || !$oh(model.original.uri, item.uri) || model.modified.uri.scheme !== Schemas.vscodeChatCodeCompareBlock) {
          diffEditor = candidate;
          break;
        }
      }
    }
    const edits = diffEditor ? await this.f(diffEditor, item) : await this.g(item);
    response.setEditApplied(item, edits);
  }
  async f(diffEditor, item) {
    const model = diffEditor.getModel();
    if (!model) {
      return 0;
    }
    const diff3 = diffEditor.getDiffComputationResult();
    if (!diff3 || diff3.identical) {
      return 0;
    }
    if (!await this.h(model.original, item)) {
      return 0;
    }
    const modified = new $8$(model.modified);
    const edits = diff3.changes2.map((i2) => i2.toRangeMapping().toTextEdit(modified).toSingleEditOperation());
    model.original.pushStackElement();
    model.original.pushEditOperations(null, edits, () => null);
    model.original.pushStackElement();
    return edits.length;
  }
  async g(item) {
    const ref = await this.b.createModelReference(item.uri);
    try {
      if (!await this.h(ref.object.textEditorModel, item)) {
        return 0;
      }
      ref.object.textEditorModel.pushStackElement();
      let total = 0;
      for (const group2 of item.edits) {
        const edits = group2.map($VE.asEditOperation);
        ref.object.textEditorModel.pushEditOperations(null, edits, () => null);
        total += edits.length;
      }
      ref.object.textEditorModel.pushStackElement();
      return total;
    } finally {
      ref.dispose();
    }
  }
  async h(model, item) {
    if (item.state?.sha1 && this.a.computeSHA1(model) && this.a.computeSHA1(model) !== item.state.sha1) {
      const result = await this.d.confirm({
        message: localize(5051, null),
        detail: localize(5052, null)
      });
      if (!result.confirmed) {
        return false;
      }
    }
    return true;
  }
  discard(response, item) {
    if (!response.response.value.includes(item)) {
      return;
    }
    if (item.state?.applied) {
      return;
    }
    response.setEditApplied(item, -1);
  }
  async preview(response, item) {
    if (item.state?.applied) {
      return false;
    }
    if (!response.response.value.includes(item)) {
      return false;
    }
    const firstEdit = item.edits[0]?.[0];
    if (!firstEdit) {
      return false;
    }
    const textEdits = $ji.fromArray(item.edits);
    const editorToApply = await this.c.openCodeEditor({ resource: item.uri }, null);
    if (editorToApply) {
      const inlineChatController = $cHb.get(editorToApply);
      if (inlineChatController) {
        const tokenSource = new $ad();
        editorToApply.revealLineInCenterIfOutsideViewport(firstEdit.range.startLineNumber);
        const promise = inlineChatController.reviewEdits(firstEdit.range, textEdits, tokenSource.token);
        response.setEditApplied(item, 1);
        promise.finally(() => {
          tokenSource.dispose();
        });
        return true;
      }
    }
    return false;
  }
};
$iHb = __decorate([
  __param(0, $oG),
  __param(1, $U5),
  __param(2, $Yv)
], $iHb);

// out-build/vs/workbench/contrib/chat/browser/chatContentParts/chatMarkdownContentPart.js
var $XMb_1;
var $102 = $;
var $XMb = class $XMb2 extends $3c {
  static {
    $XMb_1 = this;
  }
  static {
    this.a = 0;
  }
  constructor(f, context, g, fillInIncompleteTokens = false, codeBlockStartIndex = 0, renderer, currentWidth, h3, j, contextKeyService, m, n) {
    super();
    this.f = f;
    this.g = g;
    this.h = h3;
    this.j = j;
    this.m = m;
    this.n = n;
    this.id = String(++$XMb_1.a);
    this.b = [];
    this.c = this.B(new $ze());
    this.onDidChangeHeight = this.c.event;
    this.codeblocks = [];
    const element = context.element;
    const orderedDisposablesList = [];
    let codeBlockIndex = codeBlockStartIndex;
    const result = this.B(renderer.render(f.content, {
      fillInIncompleteTokens,
      codeBlockRendererSync: (languageId, text2, raw) => {
        const isCodeBlockComplete = !$asb(context.element) || context.element.isComplete || !raw || raw?.endsWith("```");
        if ((!text2 || text2.startsWith("<vscode_codeblock_uri>") && !text2.includes("\n")) && !isCodeBlockComplete && j.renderCodeBlockPills) {
          const hideEmptyCodeblock = $102("div");
          hideEmptyCodeblock.style.display = "none";
          return hideEmptyCodeblock;
        }
        const index = codeBlockIndex++;
        let textModel;
        let range;
        let vulns;
        let codemapperUri;
        if ($1f(languageId, $dHb)) {
          try {
            const parsedBody = $eHb(text2);
            range = parsedBody.range && $9C.lift(parsedBody.range);
            textModel = this.m.createModelReference(parsedBody.uri).then((ref) => ref.object.textEditorModel);
          } catch (e) {
            return $102("div");
          }
        } else {
          const sessionId = $asb(element) || $_rb(element) ? element.sessionId : "";
          const modelEntry = this.h.getOrCreate(sessionId, element, index);
          const fastUpdateModelEntry = this.h.updateSync(sessionId, element, index, { text: text2, languageId, isComplete: isCodeBlockComplete });
          vulns = modelEntry.vulns;
          codemapperUri = fastUpdateModelEntry.codemapperUri;
          textModel = modelEntry.model;
        }
        const hideToolbar = $asb(element) && element.errorDetails?.responseIsFiltered;
        const codeBlockInfo = { languageId, textModel, codeBlockIndex: index, element, range, hideToolbar, parentContextKeyService: contextKeyService, vulns, codemapperUri };
        if (!j.renderCodeBlockPills || element.isCompleteAddedRequest || !codemapperUri) {
          const ref = this.u(codeBlockInfo, text2, isCodeBlockComplete, currentWidth);
          this.b.push(ref);
          this.B(ref.object.onDidChangeContentHeight(() => this.c.fire()));
          const ownerMarkdownPartId = this.id;
          const info = new class {
            constructor() {
              this.ownerMarkdownPartId = ownerMarkdownPartId;
              this.codeBlockIndex = index;
              this.element = element;
              this.isStreaming = !j.renderCodeBlockPills;
              this.codemapperUri = void 0;
              this.uriPromise = textModel.then((model) => model.uri);
            }
            get uri() {
              return ref.object.uri;
            }
            focus() {
              ref.object.focus();
            }
            getContent() {
              return ref.object.editor.getValue();
            }
          }();
          this.codeblocks.push(info);
          orderedDisposablesList.push(ref);
          return ref.object.element;
        } else {
          const requestId = $_rb(element) ? element.id : element.requestId;
          const ref = this.s(element.sessionId, requestId, codeBlockInfo.codemapperUri, !isCodeBlockComplete);
          if ($asb(codeBlockInfo.element)) {
            this.h.update(codeBlockInfo.element.sessionId, codeBlockInfo.element, codeBlockInfo.codeBlockIndex, { text: text2, languageId: codeBlockInfo.languageId, isComplete: isCodeBlockComplete }).then((e) => {
              this.codeblocks[codeBlockInfo.codeBlockIndex].codemapperUri = e.codemapperUri;
              this.c.fire();
            });
          }
          this.b.push(ref);
          const ownerMarkdownPartId = this.id;
          const info = new class {
            constructor() {
              this.ownerMarkdownPartId = ownerMarkdownPartId;
              this.codeBlockIndex = index;
              this.element = element;
              this.isStreaming = !isCodeBlockComplete;
              this.codemapperUri = codemapperUri;
              this.uriPromise = Promise.resolve(void 0);
            }
            get uri() {
              return void 0;
            }
            focus() {
              return ref.object.element.focus();
            }
            getContent() {
              return "";
            }
          }();
          this.codeblocks.push(info);
          orderedDisposablesList.push(ref);
          return ref.object.element;
        }
      },
      asyncRenderCallback: () => this.c.fire()
    }));
    const markdownDecorationsRenderer = n.createInstance($VMb);
    this.B(markdownDecorationsRenderer.walkTreeAndAnnotateReferenceLinks(f, result.element));
    orderedDisposablesList.reverse().forEach((d) => this.B(d));
    this.domNode = result.element;
  }
  s(sessionId, requestId, codemapperUri, isStreaming) {
    const codeBlock = this.n.createInstance(CollapsedCodeBlock, sessionId, requestId);
    if (codemapperUri) {
      codeBlock.render(codemapperUri, isStreaming);
    }
    return {
      object: codeBlock,
      isStale: () => false,
      dispose: () => codeBlock.dispose()
    };
  }
  u(data, text2, isComplete, currentWidth) {
    const ref = this.g.get();
    const editorInfo = ref.object;
    if ($asb(data.element)) {
      this.h.update(data.element.sessionId, data.element, data.codeBlockIndex, { text: text2, languageId: data.languageId, isComplete }).then((e) => {
        this.codeblocks[data.codeBlockIndex].codemapperUri = e.codemapperUri;
        this.c.fire();
      });
    }
    editorInfo.render(data, currentWidth);
    return ref;
  }
  hasSameContent(other) {
    return other.kind === "markdownContent" && !!(other.content.value === this.f.content.value || this.j.renderCodeBlockPills && this.codeblocks.at(-1)?.isStreaming && this.codeblocks.at(-1)?.codemapperUri !== void 0 && other.content.value.lastIndexOf("```") === this.f.content.value.lastIndexOf("```"));
  }
  layout(width2) {
    this.b.forEach((ref, index) => {
      if (ref.object instanceof $fHb) {
        ref.object.layout(width2);
      } else if (ref.object instanceof CollapsedCodeBlock) {
        const codeblockModel = this.codeblocks[index];
        if (codeblockModel.codemapperUri && ref.object.uri?.toString() !== codeblockModel.codemapperUri.toString()) {
          ref.object.render(codeblockModel.codemapperUri, codeblockModel.isStreaming);
        }
      }
    });
  }
  addDisposable(disposable) {
    this.B(disposable);
  }
};
$XMb = $XMb_1 = __decorate([
  __param(9, $on),
  __param(10, $oG),
  __param(11, $Pk)
], $XMb);
var $YMb = class $YMb2 extends $3c {
  inUse() {
    return this.a.inUse;
  }
  constructor(options3, delegate, overflowWidgetsDomNode, instantiationService) {
    super();
    this.a = this.B(new $WMb(() => {
      return instantiationService.createInstance($fHb, options3, $bJ.ChatCodeBlock, delegate, overflowWidgetsDomNode);
    }));
  }
  get() {
    const codeBlock = this.a.get();
    let stale = false;
    return {
      object: codeBlock,
      isStale: () => stale,
      dispose: () => {
        codeBlock.reset();
        stale = true;
        this.a.release(codeBlock);
      }
    };
  }
};
$YMb = __decorate([
  __param(3, $Pk)
], $YMb);
var CollapsedCodeBlock = class CollapsedCodeBlock2 extends $3c {
  get uri() {
    return this.a;
  }
  constructor(sessionId, requestId, c, f, g, h3, j, m, n, s) {
    super();
    this.c = c;
    this.f = f;
    this.g = g;
    this.h = h3;
    this.j = j;
    this.m = m;
    this.n = n;
    this.s = s;
    this.b = new $2c();
    this.element = $102(".chat-codeblock-pill-widget");
    this.element.classList.add("show-file-icons");
    this.B($_i(this.element, "click", async () => {
      if (this.uri) {
        this.f.openEditor({ resource: this.uri });
      }
    }));
    this.B($_i(this.element, $7j.CONTEXT_MENU, (domEvent) => {
      const event = new $lf(getWindow(domEvent), domEvent);
      $9j.stop(domEvent, true);
      this.j.showContextMenu({
        contextKeyService: this.m,
        getAnchor: () => event,
        getActions: () => {
          const menu = this.n.getMenuActions($bJ.ChatEditingCodeBlockContext, this.m, { arg: { sessionId, requestId, uri: this.uri } });
          return $P$(menu);
        }
      });
    }));
  }
  render(uri, isStreaming) {
    this.b.clear();
    this.a = uri;
    const iconText = this.c.getUriBasenameLabel(uri);
    const modifiedEntry = this.s.currentEditingSession?.getEntry(uri);
    const isComplete = !modifiedEntry?.isCurrentlyBeingModified.get();
    let iconClasses = [];
    if (isStreaming || !isComplete) {
      const codicon = ThemeIcon.modify($6l.loading, "spin");
      iconClasses = ThemeIcon.asClassNameArray(codicon);
    } else {
      const fileKind = uri.path.endsWith("/") ? FileKind.FOLDER : FileKind.FILE;
      iconClasses = $gdb(this.g, this.h, uri, fileKind);
    }
    const iconEl = $("span.icon");
    iconEl.classList.add(...iconClasses);
    const children = [$("span.icon-label", {}, iconText)];
    if (isStreaming) {
      children.push($("span.label-detail", {}, localize(4798, null)));
    } else if (!isComplete) {
      children.push($("span.label-detail", {}, ""));
    }
    this.element.replaceChildren(iconEl, ...children);
    this.element.title = this.c.getUriLabel(uri, { relative: false });
    const slickRatio = $NMb.const(0);
    let t = Date.now();
    this.b.add($td((r2) => {
      const rewriteRatio = modifiedEntry?.rewriteRatio.read(r2);
      if (rewriteRatio) {
        slickRatio.changeAnimation((prev) => {
          const result = new $OMb(prev.getValue(), rewriteRatio, Date.now() - t);
          t = Date.now();
          return result;
        }, void 0);
      }
      const labelDetail = this.element.querySelector(".label-detail");
      const isComplete2 = !modifiedEntry?.isCurrentlyBeingModified.read(r2);
      if (labelDetail && !isStreaming && !isComplete2) {
        const value = slickRatio.getValue(void 0);
        labelDetail.textContent = value === 0 ? localize(4799, null) : localize(4800, null, Math.round(value * 100));
      } else if (labelDetail && !isStreaming && isComplete2) {
        iconEl.classList.remove(...iconClasses);
        const fileKind = uri.path.endsWith("/") ? FileKind.FOLDER : FileKind.FILE;
        iconEl.classList.add(...$gdb(this.g, this.h, uri, fileKind));
        labelDetail.textContent = "";
      }
      if (!isStreaming && isComplete2) {
        const labelAdded = this.element.querySelector(".label-added") ?? this.element.appendChild($("span.label-added"));
        const labelRemoved = this.element.querySelector(".label-removed") ?? this.element.appendChild($("span.label-removed"));
        const changes = modifiedEntry?.diffInfo.read(r2);
        if (changes && !changes?.identical && !changes?.quitEarly) {
          let removedLines = 0;
          let addedLines = 0;
          for (const change of changes.changes) {
            removedLines += change.original.endLineNumberExclusive - change.original.startLineNumber;
            addedLines += change.modified.endLineNumberExclusive - change.modified.startLineNumber;
          }
          labelAdded.textContent = `+${addedLines}`;
          labelRemoved.textContent = `-${removedLines}`;
          const insertionsFragment = addedLines === 1 ? localize(4801, null) : localize(4802, null, addedLines);
          const deletionsFragment = removedLines === 1 ? localize(4803, null) : localize(4804, null, removedLines);
          this.element.ariaLabel = this.element.title = localize(4805, null, iconText, insertionsFragment, deletionsFragment);
        }
      }
    }));
  }
};
CollapsedCodeBlock = __decorate([
  __param(2, $ZI),
  __param(3, $mJ),
  __param(4, $sG),
  __param(5, $1E),
  __param(6, $50),
  __param(7, $on),
  __param(8, $cJ),
  __param(9, $$O)
], CollapsedCodeBlock);

// out-build/vs/workbench/contrib/chat/browser/chatContentParts/chatProgressContentPart.js
var $ZMb = class extends $3c {
  constructor(progress, renderer, context, forceShowSpinner, forceShowMessage, icon2) {
    super();
    const followingContent = context.content.slice(context.contentIndex + 1);
    this.a = forceShowSpinner ?? shouldShowSpinner(followingContent, context.element);
    this.b = forceShowMessage !== true && followingContent.some((part) => part.kind !== "progressMessage");
    if (this.b) {
      this.domNode = $("");
      return;
    }
    if (this.a) {
      $$Z(progress.content.value);
    }
    const codicon = icon2 ? icon2 : this.a ? ThemeIcon.modify($6l.loading, "spin") : $6l.check;
    const markdown = new $bm(progress.content.value, {
      supportThemeIcons: true
    });
    const result = this.B(renderer.render(markdown));
    result.element.classList.add("progress-step");
    this.domNode = $(".progress-container");
    const iconElement = $("div");
    iconElement.classList.add(...ThemeIcon.asClassNameArray(codicon));
    $bk(this.domNode, iconElement);
    $bk(this.domNode, result.element);
  }
  hasSameContent(other, followingContent, element) {
    if (followingContent.some((part) => part.kind !== "progressMessage") && !this.b) {
      return false;
    }
    const showSpinner = shouldShowSpinner(followingContent, element);
    return other.kind === "progressMessage" && this.a === showSpinner;
  }
};
function shouldShowSpinner(followingContent, element) {
  return $asb(element) && !element.isComplete && followingContent.length === 0;
}

// out-build/vs/workbench/contrib/chat/browser/chatContentParts/chatQuotaExceededPart.js
var $103 = $;
var $1Mb = class $1Mb2 extends $3c {
  constructor(element, renderer, chatWidgetService, commandService) {
    super();
    this.a = this.B(new $ze());
    this.onDidChangeHeight = this.a.event;
    const errorDetails = element.errorDetails;
    $Jg(!!errorDetails, "errorDetails");
    this.domNode = $103(".chat-quota-error-widget");
    const icon2 = $bk(this.domNode, $103("span"));
    icon2.classList.add(...ThemeIcon.asClassNameArray($6l.warning));
    const messageContainer = $bk(this.domNode, $103(".chat-quota-error-message"));
    const markdownContent = renderer.render(new $bm(errorDetails.message));
    $bk(messageContainer, markdownContent.element);
    const button1 = this.B(new $k2(messageContainer, { ...$q$, supportIcons: true }));
    button1.label = localize(4806, null);
    button1.element.classList.add("chat-quota-error-button");
    let didAddSecondary = false;
    this.B(button1.onDidClick(async () => {
      await commandService.executeCommand("workbench.action.chat.upgradePlan");
      if (!didAddSecondary) {
        didAddSecondary = true;
        const button2 = this.B(new $k2(messageContainer, {
          buttonBackground: void 0,
          buttonForeground: $Zn($no)
        }));
        button2.element.classList.add("chat-quota-error-secondary-button");
        button2.label = localize(4807, null);
        this.a.fire();
        this.B(button2.onDidClick(() => {
          const widget = chatWidgetService.getWidgetBySessionId(element.sessionId);
          if (!widget) {
            return;
          }
          widget.rerunLastRequest();
        }));
      }
    }));
  }
  hasSameContent(other) {
    return true;
  }
};
$1Mb = __decorate([
  __param(2, $2Nb),
  __param(3, $sn)
], $1Mb);

// out-build/vs/workbench/contrib/chat/browser/chatContentParts/chatTaskContentPart.js
var $4Mb = class $4Mb2 extends $3c {
  constructor(a, contentReferencesListPool, renderer, context, instantiationService) {
    super();
    this.a = a;
    if (a.progress.length) {
      const refsPart = this.B(instantiationService.createInstance($2Mb, a.progress, a.content.value, context, contentReferencesListPool));
      this.domNode = $(".chat-progress-task");
      this.domNode.appendChild(refsPart.domNode);
      this.onDidChangeHeight = refsPart.onDidChangeHeight;
    } else {
      const isSettled = a.isSettled?.() ?? true;
      const showSpinner = !isSettled && !context.element.isComplete;
      const progressPart = this.B(instantiationService.createInstance($ZMb, a, renderer, context, showSpinner, true));
      this.domNode = progressPart.domNode;
      this.onDidChangeHeight = Event2.None;
    }
  }
  hasSameContent(other) {
    return other.kind === "progressTask" && other.progress.length === this.a.progress.length && other.isSettled() === this.a.isSettled();
  }
  addDisposable(disposable) {
    this.B(disposable);
  }
};
$4Mb = __decorate([
  __param(4, $Pk)
], $4Mb);

// out-build/vs/workbench/contrib/chat/browser/chatContentParts/chatTextEditContentPart.js
var $104 = $;
var ICodeCompareModelService = $Qk("ICodeCompareModelService");
var $5Mb = class $5Mb2 extends $3c {
  constructor(chatTextEdit, context, rendererOptions, diffEditorPool, currentWidth, c) {
    super();
    this.c = c;
    this.b = this.B(new $ze());
    this.onDidChangeHeight = this.b.event;
    const element = context.element;
    $Jg($asb(element));
    if (rendererOptions.renderTextEditsAsSummary?.(chatTextEdit.uri)) {
      if (element.response.value.every((item) => item.kind === "textEditGroup")) {
        this.domNode = $104(".interactive-edits-summary", void 0, !element.isComplete ? "" : element.isCanceled ? localize(4816, null) : localize(4817, null));
      } else {
        this.domNode = $104("div");
      }
    } else {
      const cts = new $ad();
      let isDisposed = false;
      this.B($1c(() => {
        isDisposed = true;
        cts.dispose(true);
      }));
      this.a = this.B(diffEditorPool.get());
      this.B(this.a.object.onDidChangeContentHeight(() => {
        this.b.fire();
      }));
      const data = {
        element,
        edit: chatTextEdit,
        diffData: (async () => {
          const ref = await this.c.createModel(element, chatTextEdit);
          if (isDisposed) {
            ref.dispose();
            return;
          }
          this.B(ref);
          return {
            modified: ref.object.modified.textEditorModel,
            original: ref.object.original.textEditorModel,
            originalSha1: ref.object.originalSha1
          };
        })()
      };
      this.a.object.render(data, currentWidth, cts.token);
      this.domNode = this.a.object.element;
    }
  }
  layout(width2) {
    this.a?.object.layout(width2);
  }
  hasSameContent(other) {
    return other.kind === "textEditGroup";
  }
  addDisposable(disposable) {
    this.B(disposable);
  }
};
$5Mb = __decorate([
  __param(5, ICodeCompareModelService)
], $5Mb);
var $6Mb = class $6Mb2 extends $3c {
  inUse() {
    return this.a.inUse;
  }
  constructor(options3, delegate, overflowWidgetsDomNode, instantiationService) {
    super();
    this.a = this.B(new $WMb(() => {
      return instantiationService.createInstance($hHb, options3, $bJ.ChatCompareBlock, delegate, overflowWidgetsDomNode);
    }));
  }
  get() {
    const codeBlock = this.a.get();
    let stale = false;
    return {
      object: codeBlock,
      isStale: () => stale,
      dispose: () => {
        codeBlock.reset();
        stale = true;
        this.a.release(codeBlock);
      }
    };
  }
};
$6Mb = __decorate([
  __param(3, $Pk)
], $6Mb);
var CodeCompareModelService = class CodeCompareModelService2 {
  constructor(a, b, c) {
    this.a = a;
    this.b = b;
    this.c = c;
  }
  async createModel(element, chatTextEdit) {
    const original = await this.a.createModelReference(chatTextEdit.uri);
    const modified = await this.a.createModelReference(this.b.createModel($OI(original.object.textEditorModel.createSnapshot()), { languageId: original.object.textEditorModel.getLanguageId(), onDidChange: Event2.None }, URI.from({ scheme: Schemas.vscodeChatCodeBlock, path: chatTextEdit.uri.path, query: $ps() }), false).uri);
    const d = new $6c($1c(() => {
      original.dispose();
      modified.dispose();
    }));
    let originalSha1 = "";
    if (chatTextEdit.state) {
      originalSha1 = chatTextEdit.state.sha1;
    } else {
      const sha1 = new $CGb();
      if (sha1.canComputeSHA1(original.object.textEditorModel)) {
        originalSha1 = sha1.computeSHA1(original.object.textEditorModel);
        chatTextEdit.state = { sha1: originalSha1, applied: 0 };
      }
    }
    const chatModel = this.c.getSession(element.sessionId);
    const editGroups = [];
    for (const request of chatModel.getRequests()) {
      if (!request.response) {
        continue;
      }
      for (const item of request.response.response.value) {
        if (item.kind !== "textEditGroup" || item.state?.applied || !$oh(item.uri, chatTextEdit.uri)) {
          continue;
        }
        for (const group2 of item.edits) {
          const edits = group2.map($VE.asEditOperation);
          editGroups.push(edits);
        }
      }
      if (request.response === element.model) {
        break;
      }
    }
    for (const edits of editGroups) {
      modified.object.textEditorModel.pushEditOperations(null, edits, () => null);
    }
    d.acquire();
    setTimeout(() => d.release(), 5e3);
    return {
      object: {
        originalSha1,
        original: original.object,
        modified: modified.object
      },
      dispose() {
        d.release();
      }
    };
  }
};
CodeCompareModelService = __decorate([
  __param(0, $oG),
  __param(1, $sG),
  __param(2, $qO)
], CodeCompareModelService);
$SC(
  ICodeCompareModelService,
  CodeCompareModelService,
  1
  /* InstantiationType.Delayed */
);

// out-build/vs/workbench/contrib/chat/browser/chatContentParts/chatToolInvocationPart.js
var $7Mb = class $7Mb2 extends $3c {
  constructor(toolInvocation, context, renderer, instantiationService) {
    super();
    this.a = this.B(new $ze());
    this.onDidChangeHeight = this.a.event;
    this.domNode = $(".chat-tool-invocation-part");
    const partStore = this.B(new $2c());
    const render = () => {
      $$i(this.domNode);
      const subPart = partStore.add(instantiationService.createInstance(ChatToolInvocationSubPart, toolInvocation, context, renderer));
      this.domNode.appendChild(subPart.domNode);
      partStore.add(subPart.onNeedsRerender(() => {
        render();
        this.a.fire();
      }));
    };
    render();
  }
  hasSameContent(other, followingContent, element) {
    return other.kind === "toolInvocation" || other.kind === "toolInvocationSerialized";
  }
  addDisposable(disposable) {
    this.B(disposable);
  }
};
$7Mb = __decorate([
  __param(3, $Pk)
], $7Mb);
var ChatToolInvocationSubPart = class ChatToolInvocationSubPart2 extends $3c {
  constructor(toolInvocation, context, renderer, instantiationService) {
    super();
    this.a = this.B(new $ze());
    this.onNeedsRerender = this.a.event;
    if (toolInvocation.kind === "toolInvocation" && toolInvocation.confirmationMessages) {
      const title = toolInvocation.confirmationMessages.title;
      const message = toolInvocation.confirmationMessages.message;
      const confirmWidget = this.B(instantiationService.createInstance($RDb, title, message, [{ label: localize(4818, null), data: true }, { label: localize(4819, null), data: false, isSecondary: true }]));
      this.domNode = confirmWidget.domNode;
      this.B(confirmWidget.onDidClick((button) => {
        toolInvocation.confirmed.complete(button.data);
      }));
      toolInvocation.confirmed.p.then(() => this.a.fire());
    } else {
      const content = typeof toolInvocation.invocationMessage === "string" ? new $bm().appendText(toolInvocation.invocationMessage + "\u2026") : new $bm(toolInvocation.invocationMessage.value + "\u2026");
      const progressMessage = {
        kind: "progressMessage",
        content
      };
      const iconOverride = toolInvocation.isConfirmed === false ? $6l.error : toolInvocation.isComplete ? $6l.check : void 0;
      const progressPart = this.B(instantiationService.createInstance($ZMb, progressMessage, renderer, context, void 0, true, iconOverride));
      this.domNode = progressPart.domNode;
    }
    if (toolInvocation.kind === "toolInvocation" && !toolInvocation.isComplete) {
      toolInvocation.isCompleteDeferred.p.then(() => this.a.fire());
    }
  }
};
ChatToolInvocationSubPart = __decorate([
  __param(3, $Pk)
], ChatToolInvocationSubPart);

// out-build/vs/workbench/contrib/chat/browser/chatContentParts/chatTreeContentPart.js
var $105 = $;
var $8Mb = class $8Mb2 extends $3c {
  constructor(data, element, treePool, treeDataIndex, c) {
    super();
    this.c = c;
    this.a = this.B(new $ze());
    this.onDidChangeHeight = this.a.event;
    const ref = this.B(treePool.get());
    this.b = ref.object;
    this.onDidFocus = this.b.onDidFocus;
    this.B(this.b.onDidOpen((e) => {
      if (e.element && !("children" in e.element)) {
        this.c.open(e.element.uri);
      }
    }));
    this.B(this.b.onDidChangeCollapseState(() => {
      this.a.fire();
    }));
    this.B(this.b.onContextMenu((e) => {
      e.browserEvent.preventDefault();
      e.browserEvent.stopPropagation();
    }));
    this.b.setInput(data).then(() => {
      if (!ref.isStale()) {
        this.b.layout();
        this.a.fire();
      }
    });
    this.domNode = this.b.getHTMLElement().parentElement;
  }
  domFocus() {
    this.b.domFocus();
  }
  hasSameContent(other) {
    return other.kind === "treeData";
  }
  addDisposable(disposable) {
    this.B(disposable);
  }
};
$8Mb = __decorate([
  __param(4, $O4)
], $8Mb);
var $9Mb = class $9Mb2 extends $3c {
  get inUse() {
    return this.a.inUse;
  }
  constructor(b, c, f, g) {
    super();
    this.b = b;
    this.c = c;
    this.f = f;
    this.g = g;
    this.a = this.B(new $WMb(() => this.h()));
  }
  h() {
    const resourceLabels = this.B(this.c.createInstance($lsb, { onDidChangeVisibility: this.b }));
    const container2 = $105(".interactive-response-progress-tree");
    this.B($Ewb(container2, this.g));
    const tree = this.c.createInstance($5eb, "ChatListRenderer", container2, new ChatListTreeDelegate(), new ChatListTreeCompressionDelegate(), [new ChatListTreeRenderer(resourceLabels, this.f.getValue("explorer.decorations"))], new ChatListTreeDataSource(), {
      collapseByDefault: () => false,
      expandOnlyOnTwistieClick: () => false,
      identityProvider: {
        getId: (e) => e.uri.toString()
      },
      accessibilityProvider: {
        getAriaLabel: (element) => element.label,
        getWidgetAriaLabel: () => localize(4820, null)
      },
      alwaysConsumeMouseWheel: false
    });
    return tree;
  }
  get() {
    const object = this.a.get();
    let stale = false;
    return {
      object,
      isStale: () => stale,
      dispose: () => {
        stale = true;
        this.a.release(object);
      }
    };
  }
};
$9Mb = __decorate([
  __param(1, $Pk),
  __param(2, $kl),
  __param(3, $gs)
], $9Mb);
var ChatListTreeDelegate = class _ChatListTreeDelegate {
  static {
    this.ITEM_HEIGHT = 22;
  }
  getHeight(element) {
    return _ChatListTreeDelegate.ITEM_HEIGHT;
  }
  getTemplateId(element) {
    return "chatListTreeTemplate";
  }
};
var ChatListTreeCompressionDelegate = class {
  isIncompressible(element) {
    return !element.children;
  }
};
var ChatListTreeRenderer = class {
  constructor(a, b) {
    this.a = a;
    this.b = b;
    this.templateId = "chatListTreeTemplate";
  }
  renderCompressedElements(element, index, templateData, height) {
    templateData.label.element.style.display = "flex";
    const label3 = element.element.elements.map((e) => e.label);
    templateData.label.setResource({ resource: element.element.elements[0].uri, name: label3 }, {
      title: element.element.elements[0].label,
      fileKind: element.children ? FileKind.FOLDER : FileKind.FILE,
      extraClasses: ["explorer-item"],
      fileDecorations: this.b
    });
  }
  renderTemplate(container2) {
    const templateDisposables = new $2c();
    const label3 = templateDisposables.add(this.a.create(container2, { supportHighlights: true }));
    return { templateDisposables, label: label3 };
  }
  renderElement(element, index, templateData, height) {
    templateData.label.element.style.display = "flex";
    if (!element.children.length && element.element.type !== FileType.Directory) {
      templateData.label.setFile(element.element.uri, {
        fileKind: FileKind.FILE,
        hidePath: true,
        fileDecorations: this.b
      });
    } else {
      templateData.label.setResource({ resource: element.element.uri, name: element.element.label }, {
        title: element.element.label,
        fileKind: FileKind.FOLDER,
        fileDecorations: this.b
      });
    }
  }
  disposeTemplate(templateData) {
    templateData.templateDisposables.dispose();
  }
};
var ChatListTreeDataSource = class {
  hasChildren(element) {
    return !!element.children;
  }
  async getChildren(element) {
    return element.children ?? [];
  }
};

// out-build/vs/workbench/contrib/chat/browser/chatContentParts/chatWarningContentPart.js
var $106 = $;
var $0Mb = class extends $3c {
  constructor(kind, content, renderer) {
    super();
    this.domNode = $106(".chat-notification-widget");
    let icon2;
    let iconClass;
    switch (kind) {
      case "warning":
        icon2 = $6l.warning;
        iconClass = ".chat-warning-codicon";
        break;
      case "error":
        icon2 = $6l.error;
        iconClass = ".chat-error-codicon";
        break;
      case "info":
        icon2 = $6l.info;
        iconClass = ".chat-info-codicon";
        break;
    }
    this.domNode.appendChild($106(iconClass, void 0, $C1(icon2)));
    const markdownContent = renderer.render(content);
    this.domNode.appendChild(markdownContent.element);
  }
  hasSameContent(other) {
    return other.kind === "warning";
  }
};

// out-build/vs/workbench/contrib/url/browser/trustedDomains.js
var TRUSTED_DOMAINS_URI = URI.parse("trustedDomains:/Trusted Domains");
var $$Mb = "http.linkProtectionTrustedDomains";
var $_Mb = "http.linkProtectionTrustedDomainsContent";
var $aNb = {
  id: "workbench.action.manageTrustedDomain",
  description: {
    description: localize2(11523, "Manage Trusted Domains"),
    args: []
  },
  handler: async (accessor) => {
    const editorService = accessor.get($mJ);
    editorService.openEditor({ resource: TRUSTED_DOMAINS_URI, languageId: "jsonc", options: { pinned: true } });
    return;
  }
};
async function $bNb(trustedDomains, domainToConfigure, resource, quickInputService, storageService, editorService, telemetryService) {
  const parsedDomainToConfigure = URI.parse(domainToConfigure);
  const toplevelDomainSegements = parsedDomainToConfigure.authority.split(".");
  const domainEnd = toplevelDomainSegements.slice(toplevelDomainSegements.length - 2).join(".");
  const topLevelDomain = "*." + domainEnd;
  const options3 = [];
  options3.push({
    type: "item",
    label: localize(11518, null, domainToConfigure),
    id: "trust",
    toTrust: domainToConfigure,
    picked: true
  });
  const isIP = toplevelDomainSegements.length === 4 && toplevelDomainSegements.every((segment) => Number.isInteger(+segment) || Number.isInteger(+segment.split(":")[0]));
  if (isIP) {
    if (parsedDomainToConfigure.authority.includes(":")) {
      const base = parsedDomainToConfigure.authority.split(":")[0];
      options3.push({
        type: "item",
        label: localize(11519, null, base),
        toTrust: base + ":*",
        id: "trust"
      });
    }
  } else {
    options3.push({
      type: "item",
      label: localize(11520, null, domainEnd),
      toTrust: topLevelDomain,
      id: "trust"
    });
  }
  options3.push({
    type: "item",
    label: localize(11521, null),
    toTrust: "*",
    id: "trust"
  });
  options3.push({
    type: "item",
    label: localize(11522, null),
    id: "manage"
  });
  const pickedResult = await quickInputService.pick(options3, { activeItem: options3[0] });
  if (pickedResult && pickedResult.id) {
    switch (pickedResult.id) {
      case "manage":
        await editorService.openEditor({
          resource: TRUSTED_DOMAINS_URI.with({ fragment: resource.toString() }),
          languageId: "jsonc",
          options: { pinned: true }
        });
        return trustedDomains;
      case "trust": {
        const itemToTrust = pickedResult.toTrust;
        if (trustedDomains.indexOf(itemToTrust) === -1) {
          storageService.remove(
            $_Mb,
            -1
            /* StorageScope.APPLICATION */
          );
          storageService.store(
            $$Mb,
            JSON.stringify([...trustedDomains, itemToTrust]),
            -1,
            0
            /* StorageTarget.USER */
          );
          return [...trustedDomains, itemToTrust];
        }
      }
    }
  }
  return [];
}
async function $cNb(accessor) {
  const { defaultTrustedDomains, trustedDomains } = $dNb(accessor);
  return {
    defaultTrustedDomains,
    trustedDomains
  };
}
function $dNb(accessor) {
  const storageService = accessor.get($jv);
  const productService = accessor.get($Vu);
  const environmentService = accessor.get($M4);
  const defaultTrustedDomains = [
    ...productService.linkProtectionTrustedDomains ?? [],
    ...environmentService.options?.additionalTrustedDomains ?? []
  ];
  let trustedDomains = [];
  try {
    const trustedDomainsSrc = storageService.get(
      $$Mb,
      -1
      /* StorageScope.APPLICATION */
    );
    if (trustedDomainsSrc) {
      trustedDomains = JSON.parse(trustedDomainsSrc);
    }
  } catch (err) {
  }
  return {
    defaultTrustedDomains,
    trustedDomains
  };
}

// out-build/vs/workbench/contrib/url/common/urlGlob.js
var $eNb = (uri, globUrl) => {
  let url = uri.with({ query: null, fragment: null }).toString(true);
  const normalize = (url2) => url2.replace(/\/+$/, "");
  globUrl = normalize(globUrl);
  url = normalize(url);
  const memo = Array.from({ length: url.length + 1 }).map(() => Array.from({ length: globUrl.length + 1 }).map(() => void 0));
  if (/^[^./:]*:\/\//.test(globUrl)) {
    return doUrlMatch(memo, url, globUrl, 0, 0);
  }
  const scheme = /^(https?):\/\//.exec(url)?.[1];
  if (scheme) {
    return doUrlMatch(memo, url, `${scheme}://${globUrl}`, 0, 0);
  }
  return false;
};
var doUrlMatch = (memo, url, globUrl, urlOffset, globUrlOffset) => {
  if (memo[urlOffset]?.[globUrlOffset] !== void 0) {
    return memo[urlOffset][globUrlOffset];
  }
  const options3 = [];
  if (urlOffset === url.length) {
    return globUrlOffset === globUrl.length;
  }
  if (globUrlOffset === globUrl.length) {
    const remaining = url.slice(urlOffset);
    return remaining[0] === "/";
  }
  if (url[urlOffset] === globUrl[globUrlOffset]) {
    options3.push(doUrlMatch(memo, url, globUrl, urlOffset + 1, globUrlOffset + 1));
  }
  if (globUrl[globUrlOffset] + globUrl[globUrlOffset + 1] === "*.") {
    if (!["/", ":"].includes(url[urlOffset])) {
      options3.push(doUrlMatch(memo, url, globUrl, urlOffset + 1, globUrlOffset));
    }
    options3.push(doUrlMatch(memo, url, globUrl, urlOffset, globUrlOffset + 2));
  }
  if (globUrl[globUrlOffset] === "*") {
    if (urlOffset + 1 === url.length) {
      options3.push(doUrlMatch(memo, url, globUrl, urlOffset + 1, globUrlOffset + 1));
    } else {
      options3.push(doUrlMatch(memo, url, globUrl, urlOffset + 1, globUrlOffset));
    }
    options3.push(doUrlMatch(memo, url, globUrl, urlOffset, globUrlOffset + 1));
  }
  if (globUrl[globUrlOffset] + globUrl[globUrlOffset + 1] === ":*") {
    if (url[urlOffset] === ":") {
      let endPortIndex = urlOffset + 1;
      do {
        endPortIndex++;
      } while (/[0-9]/.test(url[endPortIndex]));
      options3.push(doUrlMatch(memo, url, globUrl, endPortIndex, globUrlOffset + 2));
    } else {
      options3.push(doUrlMatch(memo, url, globUrl, urlOffset, globUrlOffset + 2));
    }
  }
  return memo[urlOffset][globUrlOffset] = options3.some((a) => a === true);
};

// out-build/vs/workbench/contrib/url/browser/trustedDomainService.js
var $fNb = $Qk("ITrustedDomainService");
var $gNb = class $gNb2 extends $3c {
  constructor(b, c) {
    super();
    this.b = b;
    this.c = c;
    const initStaticDomainsResult = () => {
      return new $hj($Y, () => {
        const { defaultTrustedDomains, trustedDomains } = this.b.invokeFunction($dNb);
        return [
          ...defaultTrustedDomains,
          ...trustedDomains
        ];
      });
    };
    this.a = initStaticDomainsResult();
    this.B(this.c.onDidChangeValue(-1, $$Mb, this.q)(() => {
      this.a?.dispose();
      this.a = initStaticDomainsResult();
    }));
  }
  isValid(resource) {
    const { defaultTrustedDomains, trustedDomains } = this.b.invokeFunction($dNb);
    const allTrustedDomains = [...defaultTrustedDomains, ...trustedDomains];
    return $hNb(resource, allTrustedDomains);
  }
};
$gNb = __decorate([
  __param(0, $Pk),
  __param(1, $jv)
], $gNb);
var rLocalhost = /^localhost(:\d+)?$/i;
var r127 = /^127.0.0.1(:\d+)?$/;
function isLocalhostAuthority(authority) {
  return rLocalhost.test(authority) || r127.test(authority);
}
function normalizeURL(url) {
  const caseInsensitiveAuthorities = ["github.com"];
  try {
    const parsed = typeof url === "string" ? URI.parse(url, true) : url;
    if (caseInsensitiveAuthorities.includes(parsed.authority)) {
      return parsed.with({ path: parsed.path.toLowerCase() }).toString(true);
    } else {
      return parsed.toString(true);
    }
  } catch {
    return url.toString();
  }
}
function $hNb(url, trustedDomains) {
  url = URI.parse(normalizeURL(url));
  trustedDomains = trustedDomains.map(normalizeURL);
  if (isLocalhostAuthority(url.authority)) {
    return true;
  }
  for (let i2 = 0; i2 < trustedDomains.length; i2++) {
    if (trustedDomains[i2] === "*") {
      return true;
    }
    if ($eNb(url, trustedDomains[i2])) {
      return true;
    }
  }
  return false;
}

// out-build/vs/workbench/contrib/chat/browser/chatMarkdownRenderer.js
var allowedHtmlTags = [
  "b",
  "blockquote",
  "br",
  "code",
  "em",
  "h1",
  "h2",
  "h3",
  "h4",
  "h5",
  "h6",
  "hr",
  "i",
  "li",
  "ol",
  "p",
  "pre",
  "strong",
  "sub",
  "sup",
  "table",
  "tbody",
  "td",
  "th",
  "thead",
  "tr",
  "ul",
  "a",
  "img",
  // TODO@roblourens when we sanitize attributes in markdown source, we can ban these elements at that step. microsoft/vscode-copilot#5091
  // Not in the official list, but used for codicons and other vscode markdown extensions
  "span",
  "div"
];
var $iNb = class $iNb2 extends $Q_ {
  constructor(options3, languageService, openerService, i2, j, k, l) {
    super(options3 ?? {}, languageService, openerService);
    this.i = i2;
    this.j = j;
    this.k = k;
    this.l = l;
  }
  render(markdown, options3, markedOptions) {
    options3 = {
      ...options3,
      remoteImageIsAllowed: (uri) => this.i.isValid(uri),
      sanitizerOptions: {
        replaceWithPlaintext: true,
        allowedTags: allowedHtmlTags
      }
    };
    const mdWithBody = markdown && markdown.supportHtml ? {
      ...markdown,
      // dompurify uses DOMParser, which strips leading comments. Wrapping it all in 'body' prevents this.
      // The \n\n prevents marked.js from parsing the body contents as just text in an 'html' token, instead of actual markdown.
      value: `<body>

${markdown.value}</body>`
    } : markdown;
    const result = super.render(mdWithBody, options3, markedOptions);
    return this.m(result);
  }
  m(result) {
    const store = new $2c();
    result.element.querySelectorAll("a").forEach((element) => {
      if (element.title) {
        const title = element.title;
        element.title = "";
        store.add(this.j.setupManagedHover($JZ("element"), element, title));
      }
    });
    return {
      element: result.element,
      dispose: () => {
        result.dispose();
        store.dispose();
      }
    };
  }
  async h(link2, markdown) {
    try {
      const uri = URI.parse(link2);
      if ((await this.k.stat(uri)).isDirectory) {
        return this.l.executeCommand($stb, uri);
      }
    } catch {
    }
    return super.h(link2, markdown);
  }
};
$iNb = __decorate([
  __param(1, $1E),
  __param(2, $O4),
  __param(3, $fNb),
  __param(4, $5$),
  __param(5, $km),
  __param(6, $sn)
], $iNb);

// out-build/vs/workbench/contrib/chat/browser/chatListRenderer.js
var $jNb_1;
var $107 = $;
var forceVerboseLayoutTracing = false;
var mostRecentResponseClassName = "chat-most-recent-response";
var $jNb = class $jNb2 extends $3c {
  static {
    $jNb_1 = this;
  }
  static {
    this.ID = "item";
  }
  constructor(editorOptions2, C, D, F, overflowWidgetsDomNode, G, configService, H, I, J, L, M, N) {
    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.a = /* @__PURE__ */ new Map();
    this.b = new $Ec();
    this.c = /* @__PURE__ */ new Map();
    this.f = /* @__PURE__ */ new Map();
    this.j = this.B(new $ze());
    this.onDidClickFollowup = this.j.event;
    this.m = new $ze();
    this.onDidClickRerunWithAgentOrCommandDetection = this.m.event;
    this.n = this.B(new $ze());
    this.onDidChangeItemHeight = this.n.event;
    this.w = 0;
    this.y = true;
    this.z = this.B(new $ze());
    this.g = this.B(this.G.createInstance($iNb, void 0));
    this.h = this.G.createInstance($VMb);
    this.r = this.B(this.G.createInstance($YMb, editorOptions2, D, overflowWidgetsDomNode));
    this.s = this.B(this.G.createInstance($6Mb, editorOptions2, D, overflowWidgetsDomNode));
    this.t = this.B(this.G.createInstance($9Mb, this.z.event));
    this.u = this.B(this.G.createInstance($3Mb, this.z.event, void 0));
    this.B(this.G.createInstance($gHb));
  }
  get templateId() {
    return $jNb_1.ID;
  }
  editorsInUse() {
    return this.r.inUse();
  }
  O(method, message) {
    if (forceVerboseLayoutTracing) {
      this.H.info(`ChatListItemRenderer#${method}: ${message}`);
    } else {
      this.H.trace(`ChatListItemRenderer#${method}: ${message}`);
    }
  }
  /**
   * Compute a rate to render at in words/s.
   */
  P(element) {
    if (element.isComplete) {
      return 80;
    }
    if (element.contentUpdateTimings && element.contentUpdateTimings.impliedWordLoadRate) {
      const minRate = 5;
      const maxRate = 80;
      const rate = element.contentUpdateTimings.impliedWordLoadRate;
      return $4i(rate, minRate, maxRate);
    }
    return 8;
  }
  getCodeBlockInfosForResponse(response) {
    const codeBlocks = this.a.get(response.id);
    return codeBlocks ?? [];
  }
  getCodeBlockInfoForEditor(uri) {
    return this.b.get(uri);
  }
  getFileTreeInfosForResponse(response) {
    const fileTrees = this.c.get(response.id);
    return fileTrees ?? [];
  }
  getLastFocusedFileTreeForResponse(response) {
    const fileTrees = this.c.get(response.id);
    const lastFocusedFileTreeIndex = this.f.get(response.id);
    if (fileTrees?.length && lastFocusedFileTreeIndex !== void 0 && lastFocusedFileTreeIndex < fileTrees.length) {
      return fileTrees[lastFocusedFileTreeIndex];
    }
    return void 0;
  }
  setVisible(visible) {
    this.y = visible;
    this.z.fire(visible);
  }
  layout(width2) {
    this.w = width2 - (this.C.noPadding ? 0 : 40);
    for (const editor of this.r.inUse()) {
      editor.layout(this.w);
    }
    for (const diffEditor of this.s.inUse()) {
      diffEditor.layout(this.w);
    }
  }
  renderTemplate(container2) {
    const templateDisposables = new $2c();
    const rowContainer = $bk(container2, $107(".interactive-item-container"));
    if (this.C.renderStyle === "compact") {
      rowContainer.classList.add("interactive-item-compact");
    }
    if (this.C.noPadding) {
      rowContainer.classList.add("no-padding");
    }
    let headerParent = rowContainer;
    let valueParent = rowContainer;
    let detailContainerParent;
    let toolbarParent;
    if (this.C.renderStyle === "minimal") {
      rowContainer.classList.add("interactive-item-compact");
      rowContainer.classList.add("minimal");
      const lhsContainer = $bk(rowContainer, $107(".column.left"));
      const rhsContainer = $bk(rowContainer, $107(".column.right"));
      headerParent = lhsContainer;
      detailContainerParent = rhsContainer;
      valueParent = rhsContainer;
      toolbarParent = $bk(rowContainer, $107(".header"));
    }
    const header = $bk(headerParent, $107(".header"));
    const user = $bk(header, $107(".user"));
    const avatarContainer = $bk(user, $107(".avatar-container"));
    const username = $bk(user, $107("h3.username"));
    username.tabIndex = 0;
    const detailContainer = $bk(detailContainerParent ?? user, $107("span.detail-container"));
    const detail2 = $bk(detailContainer, $107("span.detail"));
    $bk(detailContainer, $107("span.chat-animated-ellipsis"));
    const value = $bk(valueParent, $107(".value"));
    const elementDisposables = new $2c();
    const contextKeyService = templateDisposables.add(this.I.createScoped(rowContainer));
    const scopedInstantiationService = templateDisposables.add(this.G.createChild(new $Ok([$on, contextKeyService])));
    let titleToolbar;
    if (this.C.noHeader) {
      header.classList.add("hidden");
    } else {
      titleToolbar = templateDisposables.add(scopedInstantiationService.createInstance($4$, toolbarParent ?? header, $bJ.ChatMessageTitle, {
        menuOptions: {
          shouldForwardArgs: true
        },
        toolbarOptions: {
          shouldInlineSubmenu: (submenu) => submenu.actions.length <= 1
        }
      }));
    }
    const footerToolbarContainer = $bk(rowContainer, $107(".chat-footer-toolbar"));
    const footerToolbar = templateDisposables.add(scopedInstantiationService.createInstance($4$, footerToolbarContainer, $bJ.ChatMessageFooter, {
      eventDebounceDelay: 0,
      menuOptions: { shouldForwardArgs: true, renderShortTitle: true },
      toolbarOptions: { shouldInlineSubmenu: (submenu) => submenu.actions.length <= 1 },
      actionViewItemProvider: (action, options3) => {
        if (action instanceof $fJ && action.item.id === $vBb) {
          return scopedInstantiationService.createInstance($lNb, action, options3);
        }
        return $X$(scopedInstantiationService, action, options3);
      }
    }));
    const agentHover = templateDisposables.add(this.G.createInstance($IDb));
    const hoverContent = () => {
      if ($asb(template.currentElement) && template.currentElement.agent && !template.currentElement.agent.isDefault) {
        agentHover.setAgent(template.currentElement.agent.id);
        return agentHover.domNode;
      }
      return void 0;
    };
    const hoverOptions = $JDb(() => $asb(template.currentElement) ? template.currentElement.agent : void 0, this.L);
    templateDisposables.add(this.M.setupManagedHover($JZ("element"), user, hoverContent, hoverOptions));
    templateDisposables.add($_i(user, $7j.KEY_DOWN, (e) => {
      const ev = new $if(e);
      if (ev.equals(
        10
        /* KeyCode.Space */
      ) || ev.equals(
        3
        /* KeyCode.Enter */
      )) {
        const content = hoverContent();
        if (content) {
          this.M.showHover({ content, target: user, trapFocus: true, actions: hoverOptions.actions }, true);
        }
      } else if (ev.equals(
        9
        /* KeyCode.Escape */
      )) {
        this.M.hideHover();
      }
    }));
    const template = { avatarContainer, username, detail: detail2, value, rowContainer, elementDisposables, templateDisposables, contextKeyService, instantiationService: scopedInstantiationService, agentHover, titleToolbar, footerToolbar };
    return template;
  }
  renderElement(node, index, templateData) {
    this.renderChatTreeItem(node.element, index, templateData);
  }
  Q(templateData) {
    if (templateData.renderedParts) {
      $Xc($Mb(templateData.renderedParts));
      templateData.renderedParts = void 0;
      $$i(templateData.value);
    }
  }
  renderChatTreeItem(element, index, templateData) {
    if (templateData.currentElement && templateData.currentElement.id !== element.id) {
      this.O("renderChatTreeItem", `Rendering a different element into the template, index=${index}`);
      this.Q(templateData);
    }
    templateData.currentElement = element;
    const kind = $_rb(element) ? "request" : $asb(element) ? "response" : "welcome";
    this.O("renderElement", `${kind}, index=${index}`);
    ChatContextKeys.isResponse.bindTo(templateData.contextKeyService).set($asb(element));
    ChatContextKeys.itemId.bindTo(templateData.contextKeyService).set(element.id);
    ChatContextKeys.isRequest.bindTo(templateData.contextKeyService).set($_rb(element));
    ChatContextKeys.responseDetectedAgentCommand.bindTo(templateData.contextKeyService).set($asb(element) && element.agentOrSlashCommandDetected);
    if ($asb(element)) {
      ChatContextKeys.responseSupportsIssueReporting.bindTo(templateData.contextKeyService).set(!!element.agent?.metadata.supportIssueReporting);
      ChatContextKeys.responseVote.bindTo(templateData.contextKeyService).set(element.vote === ChatAgentVoteDirection.Up ? "up" : element.vote === ChatAgentVoteDirection.Down ? "down" : "");
    } else {
      ChatContextKeys.responseVote.bindTo(templateData.contextKeyService).set("");
    }
    if (templateData.titleToolbar) {
      templateData.titleToolbar.context = element;
    }
    templateData.footerToolbar.context = element;
    ChatContextKeys.responseHasError.bindTo(templateData.contextKeyService).set($asb(element) && !!element.errorDetails);
    const isFiltered = !!($asb(element) && element.errorDetails?.responseIsFiltered);
    ChatContextKeys.responseIsFiltered.bindTo(templateData.contextKeyService).set(isFiltered);
    templateData.rowContainer.classList.toggle("editing-session", this.N.getWidgetBySessionId(element.sessionId)?.location === ChatAgentLocation.EditingSession);
    templateData.rowContainer.classList.toggle("interactive-request", $_rb(element));
    templateData.rowContainer.classList.toggle("interactive-response", $asb(element));
    templateData.rowContainer.classList.toggle("show-detail-progress", $asb(element) && !element.isComplete && !element.progressMessages.length);
    templateData.username.textContent = element.username;
    if (!this.C.noHeader) {
      this.W(element, templateData);
    }
    $$i(templateData.detail);
    if ($asb(element)) {
      this.R(element, templateData);
    }
    templateData.rowContainer.classList.toggle(mostRecentResponseClassName, index === this.D.getListLength() - 1);
    if ($_rb(element) && element.confirmation) {
      this.U(element, templateData);
    }
    if ($asb(element) && index === this.D.getListLength() - 1 && (!element.isComplete || element.renderData)) {
      this.O("renderElement", `start progressive render, index=${index}`);
      const timer = templateData.elementDisposables.add(new $lj());
      const runProgressiveRender = (initial) => {
        try {
          if (this.ab(element, index, templateData, !!initial)) {
            timer.cancel();
          }
        } catch (err) {
          timer.cancel();
          this.H.error(err);
        }
      };
      timer.cancelAndSet(runProgressiveRender, 50, getWindow(templateData.rowContainer));
      runProgressiveRender(true);
    } else {
      if ($asb(element)) {
        this.Y(element, index, templateData);
      } else if ($_rb(element)) {
        this.Y(element, index, templateData);
      }
    }
  }
  R(element, templateData) {
    templateData.elementDisposables.add($td((reader) => {
      this.S(element, templateData);
    }));
  }
  S(element, templateData) {
    $$i(templateData.detail);
    if (element.agentOrSlashCommandDetected) {
      const msg = element.slashCommand ? localize(4945, null, `${$yO}${element.slashCommand.name}`) : localize(4946, null);
      $dk(templateData.detail, $RZ(msg, {
        className: "agentOrSlashCommandDetected",
        inline: true,
        actionHandler: {
          disposables: templateData.elementDisposables,
          callback: (content) => {
            this.m.fire(element);
          }
        }
      }));
    } else if (!element.isComplete && this.C.renderStyle !== "minimal") {
      templateData.detail.textContent = localize(4947, null);
    }
  }
  U(element, templateData) {
    $$i(templateData.detail);
    if (element.confirmation) {
      templateData.detail.textContent = localize(4948, null, element.confirmation);
    }
  }
  W(element, templateData) {
    const icon2 = $asb(element) ? this.X(element.agent?.metadata) : element.avatarIcon ?? $6l.account;
    if (icon2 instanceof URI) {
      const avatarIcon = $("img.icon");
      avatarIcon.src = $ih.uriToBrowserUri(icon2).toString(true);
      templateData.avatarContainer.replaceChildren($(".avatar", void 0, avatarIcon));
    } else {
      const avatarIcon = $(ThemeIcon.asCSSSelector(icon2));
      templateData.avatarContainer.replaceChildren($(".avatar.codicon-avatar", void 0, avatarIcon));
    }
  }
  X(agent) {
    if (agent?.themeIcon) {
      return agent.themeIcon;
    } else if (agent?.iconDark && this.J.getColorTheme().type === ColorScheme.DARK) {
      return agent.iconDark;
    } else if (agent?.icon) {
      return agent.icon;
    } else {
      return $6l.copilot;
    }
  }
  Y(element, index, templateData) {
    templateData.rowContainer.classList.toggle("chat-response-loading", $asb(element) && !element.isComplete);
    let value = [];
    if ($_rb(element) && !element.confirmation) {
      const markdown = "message" in element.message ? element.message.message : this.h.convertParsedRequestToMarkdown(element.message);
      value = [{ content: new $bm(markdown), kind: "markdownContent" }];
    } else if ($asb(element)) {
      if (element.contentReferences.length) {
        value.push({ kind: "references", references: element.contentReferences });
      }
      value.push(...$5rb(element.response.value));
      if (element.codeCitations.length) {
        value.push({ kind: "codeCitations", citations: element.codeCitations });
      }
    }
    $$i(templateData.value);
    if ($asb(element)) {
      this.R(element, templateData);
    }
    const isFiltered = !!($asb(element) && element.errorDetails?.responseIsFiltered);
    const parts = [];
    if (!isFiltered) {
      value.forEach((data, index2) => {
        const context = {
          element,
          contentIndex: index2,
          content: value,
          preceedingContentParts: parts
        };
        const newPart = this.fb(data, templateData, context);
        if (newPart) {
          if (this.C.renderDetectedCommandsWithRequest && $_rb(element) && element.agentOrSlashCommandDetected && element.slashCommand && data.kind === "markdownContent") {
            newPart.domNode.style.display = "inline-flex";
            const cmdPart = this.G.createInstance($KDb, element.slashCommand, () => this.m.fire({ sessionId: element.sessionId, requestId: element.id }));
            templateData.value.appendChild(cmdPart.domNode);
            parts.push(cmdPart);
          }
          templateData.value.appendChild(newPart.domNode);
          parts.push(newPart);
        }
      });
    }
    if (templateData.renderedParts) {
      $Xc(templateData.renderedParts);
    }
    templateData.renderedParts = parts;
    if (!isFiltered) {
      if ($_rb(element) && element.variables.length) {
        const newPart = this.mb(element.variables, element.contentReferences, element.workingSet, templateData);
        if (newPart) {
          templateData.value.appendChild(newPart.domNode);
          templateData.elementDisposables.add(newPart);
        }
      }
    }
    if ($asb(element) && element.errorDetails?.message) {
      if (element.errorDetails.isQuotaExceeded) {
        const renderedError = this.G.createInstance($1Mb, element, this.g);
        templateData.elementDisposables.add(renderedError);
        templateData.value.appendChild(renderedError.domNode);
        templateData.elementDisposables.add(renderedError.onDidChangeHeight(() => this.Z(templateData)));
      } else {
        const renderedError = this.G.createInstance($0Mb, element.errorDetails.responseIsFiltered ? "info" : "error", new $bm(element.errorDetails.message), this.g);
        templateData.elementDisposables.add(renderedError);
        templateData.value.appendChild(renderedError.domNode);
      }
    }
    if (this.C.renderStyle === "minimal" && $_rb(element) && !element.isComplete) {
      const element2 = $107("span.chat-animated-ellipsis");
      templateData.value.lastChild?.lastChild?.appendChild(element2);
    }
    const newHeight = templateData.rowContainer.offsetHeight;
    const fireEvent = !element.currentRenderedHeight || element.currentRenderedHeight !== newHeight;
    element.currentRenderedHeight = newHeight;
    if (fireEvent) {
      const disposable = templateData.elementDisposables.add($jj(getWindow(templateData.value), () => {
        element.currentRenderedHeight = templateData.rowContainer.offsetHeight;
        disposable.dispose();
        this.n.fire({ element, height: element.currentRenderedHeight });
      }));
    }
  }
  Z(templateData) {
    if (!templateData.currentElement) {
      return;
    }
    const newHeight = Math.max(templateData.rowContainer.offsetHeight, 1);
    templateData.currentElement.currentRenderedHeight = newHeight;
    this.n.fire({ element: templateData.currentElement, height: newHeight });
  }
  /**
   *	@returns true if progressive rendering should be considered complete- the element's data is fully rendered or the view is not visible
   */
  ab(element, index, templateData, isInRenderElement) {
    if (!this.y) {
      return true;
    }
    if (element.isCanceled) {
      this.O("doNextProgressiveRender", `canceled, index=${index}`);
      element.renderData = void 0;
      this.Y(element, index, templateData);
      return true;
    }
    templateData.rowContainer.classList.toggle("chat-response-loading", true);
    this.O("doNextProgressiveRender", `START progressive render, index=${index}, renderData=${JSON.stringify(element.renderData)}`);
    const contentForThisTurn = this.cb(element);
    const partsToRender = this.eb(templateData.renderedParts ?? [], contentForThisTurn.content, element);
    const contentIsAlreadyRendered = partsToRender.every((part) => part === null);
    if (contentIsAlreadyRendered) {
      if (contentForThisTurn.moreContentAvailable) {
        this.O("doNextProgressiveRender", "not rendering any new content this tick, but more available");
        return false;
      } else if (element.isComplete) {
        this.O("doNextProgressiveRender", `END progressive render, index=${index} and clearing renderData, response is complete`);
        element.renderData = void 0;
        this.Y(element, index, templateData);
        return true;
      } else {
        this.O("doNextProgressiveRender", "caught up with the stream- no new content to render");
        if (!templateData.renderedParts) {
          const height2 = templateData.rowContainer.offsetHeight;
          element.currentRenderedHeight = height2;
        }
        return true;
      }
    }
    this.O("doNextProgressiveRender", `doing progressive render, ${partsToRender.length} parts to render`);
    this.bb(partsToRender, contentForThisTurn.content, element, templateData);
    const height = templateData.rowContainer.offsetHeight;
    element.currentRenderedHeight = height;
    if (!isInRenderElement) {
      this.n.fire({ element, height });
    }
    return false;
  }
  bb(partsToRender, contentForThisTurn, element, templateData) {
    const renderedParts = templateData.renderedParts ?? [];
    templateData.renderedParts = renderedParts;
    partsToRender.forEach((partToRender, index) => {
      if (!partToRender) {
        return;
      }
      const alreadyRenderedPart = templateData.renderedParts?.[index];
      if (alreadyRenderedPart) {
        alreadyRenderedPart.dispose();
      }
      const preceedingContentParts = renderedParts.slice(0, index);
      const context = {
        element,
        content: contentForThisTurn,
        preceedingContentParts,
        contentIndex: index
      };
      const newPart = this.fb(partToRender, templateData, context);
      if (newPart) {
        if (alreadyRenderedPart) {
          try {
            alreadyRenderedPart.domNode.replaceWith(newPart.domNode);
          } catch (err) {
            this.H.error("ChatListItemRenderer#renderChatContentDiff: error replacing part", err);
          }
        } else {
          templateData.value.appendChild(newPart.domNode);
        }
        renderedParts[index] = newPart;
      } else if (alreadyRenderedPart) {
        alreadyRenderedPart.domNode.remove();
      }
    });
  }
  /**
   * Returns all content parts that should be rendered, and trimmed markdown content. We will diff this with the current rendered set.
   */
  cb(element) {
    const data = this.db(element);
    const renderableResponse = $5rb(element.response.value);
    this.O("getNextProgressiveRenderContent", `Want to render ${data.numWordsToRender} at ${data.rate} words/s, counting...`);
    let numNeededWords = data.numWordsToRender;
    const partsToRender = [];
    if (element.contentReferences.length) {
      partsToRender.push({ kind: "references", references: element.contentReferences });
    }
    let moreContentAvailable = false;
    for (let i2 = 0; i2 < renderableResponse.length; i2++) {
      const part = renderableResponse[i2];
      if (part.kind === "markdownContent") {
        const wordCountResult = $9rb(part.content.value, numNeededWords);
        this.O("getNextProgressiveRenderContent", `  Chunk ${i2}: Want to render ${numNeededWords} words and found ${wordCountResult.returnedWordCount} words. Total words in chunk: ${wordCountResult.totalWordCount}`);
        numNeededWords -= wordCountResult.returnedWordCount;
        if (wordCountResult.isFullString) {
          partsToRender.push(part);
          for (const nextPart of renderableResponse.slice(i2 + 1)) {
            if (nextPart.kind !== "markdownContent") {
              i2++;
              partsToRender.push(nextPart);
            } else {
              break;
            }
          }
        } else {
          moreContentAvailable = true;
          partsToRender.push({ ...part, content: new $bm(wordCountResult.value, part.content) });
        }
        if (numNeededWords <= 0) {
          if (renderableResponse.slice(i2 + 1).some((part2) => part2.kind === "markdownContent")) {
            moreContentAvailable = true;
          }
          break;
        }
      } else {
        partsToRender.push(part);
      }
    }
    const lastWordCount = element.contentUpdateTimings?.lastWordCount ?? 0;
    const newRenderedWordCount = data.numWordsToRender - numNeededWords;
    const bufferWords = lastWordCount - newRenderedWordCount;
    this.O("getNextProgressiveRenderContent", `Want to render ${data.numWordsToRender} words. Rendering ${newRenderedWordCount} words. Buffer: ${bufferWords} words`);
    if (newRenderedWordCount > 0 && newRenderedWordCount !== element.renderData?.renderedWordCount) {
      element.renderData = { lastRenderTime: Date.now(), renderedWordCount: newRenderedWordCount, renderedParts: partsToRender };
    }
    return { content: partsToRender, moreContentAvailable };
  }
  db(element) {
    const renderData = element.renderData ?? { lastRenderTime: 0, renderedWordCount: 0 };
    const rate = this.P(element);
    const numWordsToRender = renderData.lastRenderTime === 0 ? 1 : renderData.renderedWordCount + // Additional words to render beyond what's already rendered
    Math.floor((Date.now() - renderData.lastRenderTime) / 1e3 * rate);
    return {
      numWordsToRender,
      rate
    };
  }
  eb(renderedParts, contentToRender, element) {
    const diff3 = [];
    for (let i2 = 0; i2 < contentToRender.length; i2++) {
      const content = contentToRender[i2];
      const renderedPart = renderedParts[i2];
      if (!renderedPart || !renderedPart.hasSameContent(content, contentToRender.slice(i2 + 1), element)) {
        diff3.push(content);
      } else {
        diff3.push(null);
      }
    }
    return diff3;
  }
  fb(content, templateData, context) {
    if (content.kind === "treeData") {
      return this.gb(content, templateData, context);
    } else if (content.kind === "progressMessage") {
      return this.G.createInstance($ZMb, content, this.g, context);
    } else if (content.kind === "progressTask") {
      return this.kb(content, templateData, context);
    } else if (content.kind === "command") {
      return this.G.createInstance($QDb, content, context);
    } else if (content.kind === "textEditGroup") {
      return this.nb(context, content, templateData);
    } else if (content.kind === "confirmation") {
      return this.lb(context, content, templateData);
    } else if (content.kind === "warning") {
      return this.G.createInstance($0Mb, "warning", content.content, this.g);
    } else if (content.kind === "markdownContent") {
      return this.ob(content, templateData, context);
    } else if (content.kind === "references") {
      return this.hb(content, void 0, context, templateData);
    } else if (content.kind === "codeCitations") {
      return this.ib(content, context, templateData);
    } else if (content.kind === "toolInvocation" || content.kind === "toolInvocationSerialized") {
      return this.jb(content, context, templateData);
    }
    return void 0;
  }
  gb(content, templateData, context) {
    const data = content.treeData;
    const treeDataIndex = context.preceedingContentParts.filter((part) => part instanceof $8Mb).length;
    const treePart = this.G.createInstance($8Mb, data, context.element, this.t, treeDataIndex);
    treePart.addDisposable(treePart.onDidChangeHeight(() => {
      this.Z(templateData);
    }));
    if ($asb(context.element)) {
      const fileTreeFocusInfo = {
        treeDataId: data.uri.toString(),
        treeIndex: treeDataIndex,
        focus() {
          treePart.domFocus();
        }
      };
      treePart.addDisposable(treePart.onDidFocus(() => {
        this.f.set(context.element.id, fileTreeFocusInfo.treeIndex);
      }));
      const fileTrees = this.c.get(context.element.id) ?? [];
      fileTrees.push(fileTreeFocusInfo);
      this.c.set(context.element.id, $Rb(fileTrees, (v) => v.treeDataId));
      treePart.addDisposable($1c(() => this.c.set(context.element.id, fileTrees.filter((v) => v.treeDataId !== data.uri.toString()))));
    }
    return treePart;
  }
  hb(references, labelOverride, context, templateData) {
    const referencesPart = this.G.createInstance($2Mb, references.references, labelOverride, context, this.u);
    referencesPart.addDisposable(referencesPart.onDidChangeHeight(() => {
      this.Z(templateData);
    }));
    return referencesPart;
  }
  ib(citations, context, templateData) {
    const citationsPart = this.G.createInstance($PDb, citations, context);
    return citationsPart;
  }
  jb(toolInvocation, context, templateData) {
    const part = this.G.createInstance($7Mb, toolInvocation, context, this.g);
    part.addDisposable(part.onDidChangeHeight(() => {
      this.Z(templateData);
    }));
    return part;
  }
  kb(task, templateData, context) {
    if (!$asb(context.element)) {
      return;
    }
    const taskPart = this.G.createInstance($4Mb, task, this.u, this.g, context);
    taskPart.addDisposable(taskPart.onDidChangeHeight(() => {
      this.Z(templateData);
    }));
    return taskPart;
  }
  lb(context, confirmation, templateData) {
    const part = this.G.createInstance($SDb, confirmation, context);
    part.addDisposable(part.onDidChangeHeight(() => this.Z(templateData)));
    return part;
  }
  mb(variables, contentReferences, workingSet, templateData) {
    return this.G.createInstance($MDb, variables, contentReferences, workingSet, void 0);
  }
  nb(context, chatTextEdit, templateData) {
    const textEditPart = this.G.createInstance($5Mb, chatTextEdit, context, this.C, this.s, this.w);
    textEditPart.addDisposable(textEditPart.onDidChangeHeight(() => {
      textEditPart.layout(this.w);
      this.Z(templateData);
    }));
    return textEditPart;
  }
  ob(markdown, templateData, context) {
    const element = context.element;
    const fillInIncompleteTokens = $asb(element) && (!element.isComplete || element.isCanceled || element.errorDetails?.responseIsFiltered || element.errorDetails?.responseIsIncomplete || !!element.renderData);
    const codeBlockStartIndex = context.preceedingContentParts.reduce((acc, part) => acc + (part instanceof $XMb ? part.codeblocks.length : 0), 0);
    const markdownPart = templateData.instantiationService.createInstance($XMb, markdown, context, this.r, fillInIncompleteTokens, codeBlockStartIndex, this.g, this.w, this.F, this.C);
    const markdownPartId = markdownPart.id;
    markdownPart.addDisposable(markdownPart.onDidChangeHeight(() => {
      markdownPart.layout(this.w);
      this.Z(templateData);
    }));
    const codeBlocksByResponseId = this.a.get(element.id) ?? [];
    this.a.set(element.id, codeBlocksByResponseId);
    markdownPart.addDisposable($1c(() => {
      const codeBlocksByResponseId2 = this.a.get(element.id);
      if (codeBlocksByResponseId2) {
        markdownPart.codeblocks.forEach((info, i2) => {
          const codeblock = codeBlocksByResponseId2[codeBlockStartIndex + i2];
          if (codeblock?.ownerMarkdownPartId === markdownPartId) {
            delete codeBlocksByResponseId2[codeBlockStartIndex + i2];
          }
        });
      }
    }));
    markdownPart.codeblocks.forEach((info, i2) => {
      codeBlocksByResponseId[codeBlockStartIndex + i2] = info;
      info.uriPromise.then((uri) => {
        if (!uri) {
          return;
        }
        this.b.set(uri, info);
        markdownPart.addDisposable($1c(() => {
          const codeblock = this.b.get(uri);
          if (codeblock?.ownerMarkdownPartId === markdownPartId) {
            this.b.delete(uri);
          }
        }));
      });
    });
    return markdownPart;
  }
  disposeElement(node, index, templateData) {
    this.O("disposeElement", `Disposing element, index=${index}`);
    templateData.elementDisposables.clear();
  }
  disposeTemplate(templateData) {
    templateData.templateDisposables.dispose();
  }
};
$jNb = $jNb_1 = __decorate([
  __param(5, $Pk),
  __param(6, $kl),
  __param(7, $wn),
  __param(8, $on),
  __param(9, $gs),
  __param(10, $sn),
  __param(11, $5$),
  __param(12, $2Nb)
], $jNb);
var $kNb = class $kNb2 {
  constructor(a, b) {
    this.a = a;
    this.b = b;
  }
  c(method, message) {
    if (forceVerboseLayoutTracing) {
      this.b.info(`ChatListDelegate#${method}: ${message}`);
    } else {
      this.b.trace(`ChatListDelegate#${method}: ${message}`);
    }
  }
  getHeight(element) {
    const kind = $_rb(element) ? "request" : "response";
    const height = ("currentRenderedHeight" in element ? element.currentRenderedHeight : void 0) ?? this.a;
    this.c("getHeight", `${kind}, height=${height}`);
    return height;
  }
  getTemplateId(element) {
    return $jNb.ID;
  }
  hasDynamicHeight(element) {
    return true;
  }
};
$kNb = __decorate([
  __param(1, $wn)
], $kNb);
var voteDownDetailLabels = {
  [ChatAgentVoteDownReason.IncorrectCode]: localize(4949, null),
  [ChatAgentVoteDownReason.DidNotFollowInstructions]: localize(4950, null),
  [ChatAgentVoteDownReason.MissingContext]: localize(4951, null),
  [ChatAgentVoteDownReason.OffensiveOrUnsafe]: localize(4952, null),
  [ChatAgentVoteDownReason.PoorlyWrittenOrFormatted]: localize(4953, null),
  [ChatAgentVoteDownReason.RefusedAValidRequest]: localize(4954, null),
  [ChatAgentVoteDownReason.IncompleteCode]: localize(4955, null),
  [ChatAgentVoteDownReason.WillReportIssue]: localize(4956, null),
  [ChatAgentVoteDownReason.Other]: localize(4957, null)
};
var $lNb = class $lNb2 extends $L2 {
  constructor(action, options3, a, g, r2, contextMenuService) {
    super(action, { getActions: () => this.getActions() }, contextMenuService, {
      ...options3,
      classNames: ThemeIcon.asClassNameArray($6l.thumbsdown)
    });
    this.a = a;
    this.g = g;
    this.r = r2;
  }
  getActions() {
    return [
      this.O(ChatAgentVoteDownReason.IncorrectCode),
      this.O(ChatAgentVoteDownReason.DidNotFollowInstructions),
      this.O(ChatAgentVoteDownReason.IncompleteCode),
      this.O(ChatAgentVoteDownReason.MissingContext),
      this.O(ChatAgentVoteDownReason.PoorlyWrittenOrFormatted),
      this.O(ChatAgentVoteDownReason.RefusedAValidRequest),
      this.O(ChatAgentVoteDownReason.OffensiveOrUnsafe),
      this.O(ChatAgentVoteDownReason.Other),
      {
        id: "reportIssue",
        label: voteDownDetailLabels[ChatAgentVoteDownReason.WillReportIssue],
        tooltip: "",
        enabled: true,
        class: void 0,
        run: async (context) => {
          if (!$asb(context)) {
            this.r.error("ChatVoteDownButton#run: invalid context");
            return;
          }
          await this.a.executeCommand($vBb, context, ChatAgentVoteDownReason.WillReportIssue);
          await this.g.openReporter({ extensionId: context.agent?.extensionId.value });
        }
      }
    ];
  }
  render(container2) {
    super.render(container2);
    this.element?.classList.toggle("checked", this.action.checked);
  }
  O(reason) {
    const label3 = voteDownDetailLabels[reason];
    return {
      id: $vBb,
      label: label3,
      tooltip: "",
      enabled: true,
      checked: this._context.voteDownReason === reason,
      class: void 0,
      run: async (context) => {
        if (!$asb(context)) {
          this.r.error("ChatVoteDownButton#getVoteDownDetailAction: invalid context");
          return;
        }
        await this.a.executeCommand($vBb, context, reason);
      }
    };
  }
};
$lNb = __decorate([
  __param(2, $sn),
  __param(3, $6zb),
  __param(4, $wn),
  __param(5, $50)
], $lNb);

// out-build/vs/workbench/contrib/chat/browser/chatOptions.js
var $8Gb_1;
var $8Gb = class $8Gb2 extends $3c {
  static {
    $8Gb_1 = this;
  }
  static {
    this.a = 1.4;
  }
  get configuration() {
    return this.c;
  }
  static {
    this.f = [
      "chat.editor.lineHeight",
      "chat.editor.fontSize",
      "chat.editor.fontFamily",
      "chat.editor.fontWeight",
      "chat.editor.wordWrap",
      "editor.cursorBlinking",
      "editor.fontLigatures",
      "editor.accessibilitySupport",
      "editor.bracketPairColorization.enabled",
      "editor.bracketPairColorization.independentColorPoolPerBracketType"
    ];
  }
  constructor(viewId, g, h3, j, m, n, r2) {
    super();
    this.g = g;
    this.h = h3;
    this.j = j;
    this.m = m;
    this.n = n;
    this.r = r2;
    this.b = this.B(new $ze());
    this.onDidChange = this.b.event;
    this.B(this.n.onDidColorThemeChange((e) => this.s()));
    this.B(this.r.onDidChangeLocation((e) => {
      if (e.views.some((v) => v.id === viewId)) {
        this.s();
      }
    }));
    this.B(this.m.onDidChangeConfiguration((e) => {
      if ($8Gb_1.f.some((id2) => e.affectsConfiguration(id2))) {
        this.s();
      }
    }));
    this.s();
  }
  s() {
    const editorConfig = this.m.getValue("editor");
    const chatEditorConfig = this.m.getValue("chat")?.editor;
    const accessibilitySupport = this.m.getValue("editor.accessibilitySupport");
    this.c = {
      foreground: this.n.getColorTheme().getColor(this.g),
      inputEditor: {
        backgroundColor: this.n.getColorTheme().getColor(this.h),
        accessibilitySupport
      },
      resultEditor: {
        backgroundColor: this.n.getColorTheme().getColor(this.j),
        fontSize: chatEditorConfig.fontSize,
        fontFamily: chatEditorConfig.fontFamily === "default" ? editorConfig.fontFamily : chatEditorConfig.fontFamily,
        fontWeight: chatEditorConfig.fontWeight,
        lineHeight: chatEditorConfig.lineHeight ? chatEditorConfig.lineHeight : $8Gb_1.a * chatEditorConfig.fontSize,
        bracketPairColorization: {
          enabled: this.m.getValue("editor.bracketPairColorization.enabled"),
          independentColorPoolPerBracketType: this.m.getValue("editor.bracketPairColorization.independentColorPoolPerBracketType")
        },
        wordWrap: chatEditorConfig.wordWrap,
        fontLigatures: editorConfig.fontLigatures
      }
    };
    this.b.fire();
  }
};
$8Gb = $8Gb_1 = __decorate([
  __param(4, $kl),
  __param(5, $gs),
  __param(6, $$M)
], $8Gb);

// out-build/vs/workbench/contrib/chat/browser/viewsWelcome/chatViewsWelcome.js
var ChatViewsWelcomeExtensions;
(function(ChatViewsWelcomeExtensions2) {
  ChatViewsWelcomeExtensions2["ChatViewsWelcomeRegistry"] = "workbench.registry.chat.viewsWelcome";
})(ChatViewsWelcomeExtensions || (ChatViewsWelcomeExtensions = {}));
var ChatViewsWelcomeContributionRegistry = class {
  constructor() {
    this.a = [];
    this.b = new $ze();
    this.onDidChange = this.b.event;
  }
  register(descriptor) {
    this.a.push(descriptor);
    this.b.fire();
  }
  get() {
    return this.a;
  }
};
var $mNb = new ChatViewsWelcomeContributionRegistry();
$Wn.add("workbench.registry.chat.viewsWelcome", $mNb);

// out-build/vs/workbench/contrib/chat/browser/viewsWelcome/chatViewWelcomeController.js
var $108 = $;
var $nNb = class $nNb2 extends $3c {
  constructor(g, h3, j, m, n) {
    super();
    this.g = g;
    this.h = h3;
    this.j = j;
    this.m = m;
    this.n = n;
    this.b = false;
    this.c = this.B(new $2c());
    this.f = this.B(new $2c());
    this.a = $bk(this.g, $(".chat-view-welcome"));
    this.B(Event2.runAndSubscribe(h3.onDidChangeViewWelcomeState, () => this.r()));
    this.B($mNb.onDidChange(() => this.r(true)));
  }
  r(force) {
    const enabled = this.h.shouldShowWelcome();
    if (this.b === enabled && !force) {
      return;
    }
    this.b = enabled;
    this.c.clear();
    if (!enabled) {
      this.g.classList.toggle("chat-view-welcome-visible", false);
      this.f.clear();
      return;
    }
    const descriptors = $mNb.get();
    if (descriptors.length) {
      this.s(descriptors);
      const descriptorKeys = new Set(descriptors.flatMap((d) => d.when.keys()));
      this.c.add(this.m.onDidChangeContext((e) => {
        if (e.affectsSome(descriptorKeys)) {
          this.s(descriptors);
        }
      }));
    }
  }
  s(descriptors) {
    this.f.clear();
    $$i(this.a);
    const matchingDescriptors = descriptors.filter((descriptor) => this.m.contextMatchesRules(descriptor.when));
    let enabledDescriptor;
    for (const descriptor of matchingDescriptors) {
      if (typeof descriptor.content === "function") {
        enabledDescriptor = descriptor;
        break;
      }
    }
    enabledDescriptor = enabledDescriptor ?? matchingDescriptors.at(0);
    if (enabledDescriptor) {
      const content = {
        icon: enabledDescriptor.icon,
        title: enabledDescriptor.title,
        message: enabledDescriptor.content
      };
      const welcomeView = this.f.add(this.n.createInstance($oNb, content, { firstLinkToButton: true, location: this.j }));
      this.a.appendChild(welcomeView.element);
      this.g.classList.toggle("chat-view-welcome-visible", true);
    } else {
      this.g.classList.toggle("chat-view-welcome-visible", false);
    }
  }
};
$nNb = __decorate([
  __param(3, $on),
  __param(4, $Pk)
], $nNb);
var $oNb = class $oNb2 extends $3c {
  constructor(content, options3, a, b, c) {
    super();
    this.a = a;
    this.b = b;
    this.c = c;
    this.element = $(".chat-welcome-view");
    try {
      const renderer = this.B(this.b.createInstance($Q_, {}));
      const icon2 = $bk(this.element, $108(".chat-welcome-view-icon"));
      if (content.icon) {
        icon2.appendChild($C1(content.icon));
      }
      const title = $bk(this.element, $108(".chat-welcome-view-title"));
      title.textContent = content.title;
      if (options3?.location === ChatAgentLocation.EditingSession && typeof content.message !== "function") {
        const featureIndicator = $bk(this.element, $108(".chat-welcome-view-indicator"));
        featureIndicator.textContent = localize(5068, null);
      }
      const message = $bk(this.element, $108(".chat-welcome-view-message"));
      if (typeof content.message === "function") {
        $bk(message, content.message(this.B(new $2c())));
      } else {
        const messageResult = this.B(renderer.render(content.message));
        const firstLink = options3?.firstLinkToButton ? messageResult.element.querySelector("a") : void 0;
        if (firstLink) {
          const target = firstLink.getAttribute("data-href");
          const button = this.B(new $k2(firstLink.parentElement, $q$));
          button.label = firstLink.textContent ?? "";
          if (target) {
            this.B(button.onDidClick(() => {
              this.a.open(target, { allowCommands: true });
            }));
          }
          firstLink.replaceWith(button.element);
        }
        $bk(message, messageResult.element);
      }
      if (content.tips) {
        const tips = $bk(this.element, $108(".chat-welcome-view-tips"));
        const tipsResult = this.B(renderer.render(content.tips));
        tips.appendChild(tipsResult.element);
      }
    } catch (err) {
      this.c.error("Failed to render chat view welcome content", err);
    }
  }
};
$oNb = __decorate([
  __param(2, $O4),
  __param(3, $Pk),
  __param(4, $wn)
], $oNb);

// out-build/vs/workbench/contrib/chat/browser/chatWidget.js
var $qNb_1;
var $109 = $;
function $pNb(widget) {
  return "viewContext" in widget && "isQuickChat" in widget.viewContext && Boolean(widget.viewContext.isQuickChat);
}
var PersistWelcomeMessageContentKey = "chat.welcomeMessageContent";
var $qNb = class $qNb2 extends $3c {
  static {
    $qNb_1 = this;
  }
  static {
    this.CONTRIBS = [];
  }
  get visible() {
    return this.U;
  }
  set viewModel(viewModel) {
    if (this.Z === viewModel) {
      return;
    }
    this.Y.clear();
    this.Z = viewModel;
    if (viewModel) {
      this.Y.add(viewModel);
    }
    this.g.fire();
  }
  get viewModel() {
    return this.Z;
  }
  get parsedInput() {
    if (this.ab === void 0) {
      if (!this.viewModel) {
        return { text: "", parts: [] };
      }
      this.ab = this.fb.createInstance($nO).parseChatRequest(this.viewModel.sessionId, this.getInput(), this.location, { selectedAgent: this.rb });
    }
    return this.ab;
  }
  get scopedContextKeyService() {
    return this.eb;
  }
  get location() {
    return this.bb.location;
  }
  constructor(location3, _viewContext, cb, db, codeEditorService, eb, fb, gb, hb, ib, jb, kb, lb, mb, nb, ob, pb, qb) {
    super();
    this.cb = cb;
    this.db = db;
    this.eb = eb;
    this.fb = fb;
    this.gb = gb;
    this.hb = hb;
    this.ib = ib;
    this.jb = jb;
    this.kb = kb;
    this.lb = lb;
    this.mb = mb;
    this.nb = nb;
    this.ob = ob;
    this.pb = pb;
    this.qb = qb;
    this.a = this.B(new $ze());
    this.onDidSubmitAgent = this.a.event;
    this.b = this.B(new $ze());
    this.onDidChangeAgent = this.b.event;
    this.f = this.B(new $ze());
    this.onDidFocus = this.f.event;
    this.g = this.B(new $ze());
    this.onDidChangeViewModel = this.g.event;
    this.h = this.B(new $ze());
    this.onDidScroll = this.h.event;
    this.j = this.B(new $ze());
    this.onDidClear = this.j.event;
    this.n = this.B(new $ze());
    this.onDidAcceptInput = this.n.event;
    this.r = this.B(new $ze());
    this.onDidHide = this.r.event;
    this.t = this.B(new $ze());
    this.onDidChangeParsedInput = this.t.event;
    this.u = new $ze();
    this.onWillMaybeChangeHeight = this.u.event;
    this.y = this.B(new $ze());
    this.onDidChangeHeight = this.y.event;
    this.z = new $ze();
    this.onDidChangeContentHeight = this.z.event;
    this.C = [];
    this.Q = 0;
    this.U = false;
    this.W = 0;
    this.X = true;
    this.Y = this.B(new $2c());
    this.viewContext = _viewContext ?? {};
    if (typeof location3 === "object") {
      this.bb = location3;
    } else {
      this.bb = { location: location3 };
    }
    ChatContextKeys.inChatSession.bindTo(eb).set(true);
    ChatContextKeys.location.bindTo(eb).set(this.bb.location);
    ChatContextKeys.inQuickChat.bindTo(eb).set($pNb(this));
    this.S = ChatContextKeys.inputHasAgent.bindTo(eb);
    this.R = ChatContextKeys.requestInProgress.bindTo(eb);
    this.G = this.B(fb.createInstance($$rb));
    const chatEditingSessionDisposables = this.B(new $2c());
    this.B(this.ob.onDidCreateEditingSession((session) => {
      if (session.chatSessionId !== this.viewModel?.sessionId) {
        return;
      }
      chatEditingSessionDisposables.clear();
      this.vb(null);
      chatEditingSessionDisposables.add(session.onDidChange(() => {
        this.vb(session);
      }));
      chatEditingSessionDisposables.add(session.onDidDispose(() => {
        chatEditingSessionDisposables.clear();
        this.vb(null);
      }));
      chatEditingSessionDisposables.add(this.onDidChangeParsedInput(() => {
        this.vb(session);
      }));
      chatEditingSessionDisposables.add(this.inputEditor.onDidChangeModelContent(() => {
        if (this.getInput() === "") {
          this.refreshParsedInput();
          this.vb(session);
        }
      }));
      this.vb(session);
    }));
    if (this.bb.location === ChatAgentLocation.EditingSession) {
      let currentEditSession = void 0;
      this.B(this.onDidChangeViewModel(async () => {
        const sessionId = this.Z?.sessionId;
        if (sessionId) {
          if (sessionId !== currentEditSession?.chatSessionId) {
            currentEditSession = await this.ob.startOrContinueEditingSession(sessionId);
          }
        } else {
          if (currentEditSession) {
            const session = currentEditSession;
            currentEditSession = void 0;
            await session.stop();
          }
        }
      }));
    }
    this.B(codeEditorService.registerCodeEditorOpenHandler(async (input, _source, _sideBySide) => {
      const resource = input.resource;
      if (resource.scheme !== Schemas.vscodeChatCodeBlock) {
        return null;
      }
      const responseId = resource.path.split("/").at(1);
      if (!responseId) {
        return null;
      }
      const item = this.viewModel?.getItems().find((item2) => item2.id === responseId);
      if (!item) {
        return null;
      }
      this.reveal(item);
      await $Wh(0);
      for (const codeBlockPart of this.F.editorsInUse()) {
        if ($lh.isEqual(codeBlockPart.uri, resource, true)) {
          const editor = codeBlockPart.editor;
          let relativeTop = 0;
          const editorDomNode = editor.getDomNode();
          if (editorDomNode) {
            const row = $Gj(editorDomNode, "monaco-list-row");
            if (row) {
              relativeTop = $sj(editorDomNode).top - $sj(row).top;
            }
          }
          if (input.options?.selection) {
            const editorSelectionTopOffset = editor.getTopForPosition(input.options.selection.startLineNumber, input.options.selection.startColumn);
            relativeTop += editorSelectionTopOffset;
            editor.focus();
            editor.setSelection({
              startLineNumber: input.options.selection.startLineNumber,
              startColumn: input.options.selection.startColumn,
              endLineNumber: input.options.selection.endLineNumber ?? input.options.selection.startLineNumber,
              endColumn: input.options.selection.endColumn ?? input.options.selection.startColumn
            });
          }
          this.reveal(item, relativeTop);
          return editor;
        }
      }
      return null;
    }));
    const loadedWelcomeContent = pb.getObject(
      `${PersistWelcomeMessageContentKey}.${this.location}`,
      -1
      /* StorageScope.APPLICATION */
    );
    if ($YO(loadedWelcomeContent)) {
      this.O = loadedWelcomeContent;
    }
    this.B(this.onDidChangeParsedInput(() => this.Fb()));
  }
  set lastSelectedAgent(agent) {
    this.ab = void 0;
    this.rb = agent;
    this.t.fire();
  }
  get lastSelectedAgent() {
    return this.rb;
  }
  get supportsFileReferences() {
    return !!this.cb.supportsFileReferences;
  }
  get input() {
    return this.I;
  }
  get inputEditor() {
    return this.I.inputEditor;
  }
  get inputUri() {
    return this.I.inputUri;
  }
  get contentHeight() {
    return this.I.contentHeight + this.D.contentHeight;
  }
  get attachmentModel() {
    return this.I.attachmentModel;
  }
  render(parent) {
    const viewId = "viewId" in this.viewContext ? this.viewContext.viewId : void 0;
    this.J = this.B(this.fb.createInstance($8Gb, viewId, this.db.listForeground, this.db.inputEditorBackground, this.db.resultEditorBackground));
    const renderInputOnTop = this.cb.renderInputOnTop ?? false;
    const renderFollowups = this.cb.renderFollowups ?? !renderInputOnTop;
    const renderStyle = this.cb.renderStyle;
    this.M = $bk(parent, $109(".interactive-session"));
    this.N = $bk(this.M, $109(".chat-welcome-view-container", { style: "display: none" }));
    this.ub();
    if (renderInputOnTop) {
      this.Ab(this.M, { renderFollowups, renderStyle });
      this.L = $bk(this.M, $109(`.interactive-list`));
    } else {
      this.L = $bk(this.M, $109(`.interactive-list`));
      this.Ab(this.M, { renderFollowups, renderStyle });
    }
    this.xb(this.L, { ...this.cb.rendererOptions, renderStyle });
    const scrollDownButton = this.B(new $k2(this.L, {
      supportIcons: true,
      buttonBackground: $Zn($Yq),
      buttonForeground: $Zn($Xq),
      buttonHoverBackground: $Zn($Zq)
    }));
    scrollDownButton.element.classList.add("chat-scroll-down");
    scrollDownButton.label = `$(${$6l.chevronDown.id})`;
    scrollDownButton.setTitle(localize(5033, null));
    this.B(scrollDownButton.onDidClick(() => {
      this.X = true;
      this.sb();
    }));
    this.B(this.J.onDidChange(() => this.Bb()));
    this.Bb();
    if (this.viewModel) {
      this.tb();
      this.sb();
    }
    this.C = $qNb_1.CONTRIBS.map((contrib) => {
      try {
        return this.B(this.fb.createInstance(contrib, this));
      } catch (err) {
        this.lb.error("Failed to instantiate chat widget contrib", $1m(err));
        return void 0;
      }
    }).filter($Hg);
    this.B(this.ib.register(this));
  }
  sb() {
    if (this.H) {
      const offset = Math.max(this.H.currentRenderedHeight ?? 0, 1e6);
      this.D.reveal(this.H, offset);
    }
  }
  getContrib(id2) {
    return this.C.find((c) => c.id === id2);
  }
  focusInput() {
    this.I.focus();
  }
  hasInputFocus() {
    return this.I.hasFocus();
  }
  refreshParsedInput() {
    if (!this.viewModel) {
      return;
    }
    this.ab = this.fb.createInstance($nO).parseChatRequest(this.viewModel.sessionId, this.getInput(), this.location, { selectedAgent: this.rb });
    this.t.fire();
  }
  getSibling(item, type) {
    if (!$asb(item)) {
      return;
    }
    const items = this.viewModel?.getItems();
    if (!items) {
      return;
    }
    const responseItems = items.filter((i2) => $asb(i2));
    const targetIndex = responseItems.indexOf(item);
    if (targetIndex === void 0) {
      return;
    }
    const indexToFocus = type === "next" ? targetIndex + 1 : targetIndex - 1;
    if (indexToFocus < 0 || indexToFocus > responseItems.length - 1) {
      return;
    }
    return responseItems[indexToFocus];
  }
  clear() {
    if (this.Eb) {
      this.Eb.enabled = true;
    }
    this.j.fire();
  }
  tb(skipDynamicLayout) {
    if (this.U || !this.viewModel) {
      const treeItems = (this.viewModel?.getItems() ?? []).map((item) => {
        return {
          element: item,
          collapsed: false,
          collapsible: false
        };
      });
      this.ub();
      this.u.fire();
      this.H = treeItems.at(-1)?.element;
      ChatContextKeys.lastItemId.bindTo(this.eb).set(this.H ? [this.H.id] : []);
      this.D.setChildren(null, treeItems, {
        diffIdentityProvider: {
          getId: (element) => {
            return element.dataId + // Ensure re-rendering an element once slash commands are loaded, so the colorization can be applied.
            `${$_rb(element)}${$asb(element) && element.renderData ? `_${this.Q}` : ""}` + // Re-render once content references are loaded
            ($asb(element) ? `_${element.contentReferences.length}` : "") + // Re-render if element becomes hidden due to undo/redo
            `_${element.isHidden ? "1" : "0"}` + // Rerender request if we got new content references in the response
            // since this may change how we render the corresponding attachments in the request
            ($_rb(element) && element.contentReferences ? `_${element.contentReferences?.length}` : "");
          }
        }
      });
      if (!skipDynamicLayout && this.Eb) {
        this.layoutDynamicChatTreeItemMode();
      }
      if (this.H && $asb(this.H) && this.H.isComplete) {
        this.wb(this.H.replyFollowups, this.H);
      } else if (!treeItems.length && this.viewModel) {
        this.wb(this.viewModel.model.sampleQuestions);
      } else {
        this.wb(void 0);
      }
    }
  }
  ub() {
    const welcomeContent = this.viewModel?.model.welcomeMessage ?? this.O;
    if (welcomeContent && this.N.children.length === 0 && !this.cb.renderStyle) {
      const tips = this.cb.supportsAdditionalParticipants ? new $bm(localize(5034, null, "$(attach)", "#", "$(mention)", "/"), { supportThemeIcons: true }) : new $bm(localize(5035, null, "$(attach)", "#"), { supportThemeIcons: true });
      const welcomePart = this.B(this.fb.createInstance($oNb, { ...welcomeContent, tips }, { location: this.location }));
      $bk(this.N, welcomePart.element);
    }
    if (!this.cb.renderStyle && this.viewModel) {
      const treeItems = this.viewModel.getItems();
      $gk(treeItems.length === 0, this.N);
      $gk(treeItems.length !== 0, this.L);
    }
  }
  async vb(session) {
    this.I.renderChatEditingSessionState(session, this);
    if (this.P) {
      this.layout(this.P.height, this.P.width);
    }
  }
  async wb(items, response) {
    this.I.renderFollowups(items, response);
    if (this.P) {
      this.layout(this.P.height, this.P.width);
    }
  }
  setVisible(visible) {
    const wasVisible = this.U;
    this.U = visible;
    this.Q++;
    this.F.setVisible(visible);
    this.input.setVisible(visible);
    if (visible) {
      this.B($Xh(() => {
        if (this.U) {
          this.tb(true);
        }
      }, 0));
    } else if (wasVisible) {
      this.r.fire();
    }
  }
  xb(listContainer, options3) {
    const scopedInstantiationService = this.B(this.fb.createChild(new $Ok([$on, this.eb])));
    const delegate = scopedInstantiationService.createInstance($kNb, this.cb.defaultElementHeight ?? 200);
    const rendererDelegate = {
      getListLength: () => this.D.getNode(null).visibleChildrenCount,
      onDidScroll: this.onDidScroll,
      container: listContainer
    };
    const overflowWidgetsContainer = document.createElement("div");
    overflowWidgetsContainer.classList.add("chat-overflow-widget-container", "monaco-editor");
    listContainer.append(overflowWidgetsContainer);
    this.F = this.B(scopedInstantiationService.createInstance($jNb, this.J, options3, rendererDelegate, this.G, overflowWidgetsContainer));
    this.B(this.F.onDidClickFollowup((item) => {
      this.acceptInput(item.message);
    }));
    this.B(this.F.onDidClickRerunWithAgentOrCommandDetection((item) => {
      const request = this.gb.getSession(item.sessionId)?.getRequests().find((candidate) => candidate.id === item.requestId);
      if (request) {
        const options4 = {
          noCommandDetection: true,
          attempt: request.attempt + 1,
          location: this.location,
          userSelectedModelId: this.input.currentLanguageModel
        };
        this.gb.resendRequest(request, options4).catch((e) => this.lb.error("FAILED to rerun request", e));
      }
    }));
    this.D = this.B(scopedInstantiationService.createInstance($1eb, "Chat", listContainer, delegate, [this.F], {
      identityProvider: { getId: (e) => e.id },
      horizontalScrolling: false,
      alwaysConsumeMouseWheel: false,
      supportDynamicHeights: true,
      hideTwistiesOfChildlessElements: true,
      accessibilityProvider: this.fb.createInstance($4zb),
      keyboardNavigationLabelProvider: { getKeyboardNavigationLabel: (e) => $_rb(e) ? e.message : $asb(e) ? e.response.value : "" },
      // TODO
      setRowLineHeight: false,
      filter: this.cb.filter ? { filter: this.cb.filter.bind(this.cb) } : void 0,
      overrideStyles: {
        listFocusBackground: this.db.listBackground,
        listInactiveFocusBackground: this.db.listBackground,
        listActiveSelectionBackground: this.db.listBackground,
        listFocusAndSelectionBackground: this.db.listBackground,
        listInactiveSelectionBackground: this.db.listBackground,
        listHoverBackground: this.db.listBackground,
        listBackground: this.db.listBackground,
        listFocusForeground: this.db.listForeground,
        listHoverForeground: this.db.listForeground,
        listInactiveFocusForeground: this.db.listForeground,
        listInactiveSelectionForeground: this.db.listForeground,
        listActiveSelectionForeground: this.db.listForeground,
        listFocusAndSelectionForeground: this.db.listForeground,
        listActiveSelectionIconForeground: void 0,
        listInactiveSelectionIconForeground: void 0
      }
    }));
    this.B(this.D.onContextMenu((e) => this.yb(e)));
    this.B(this.D.onDidChangeContentHeight(() => {
      this.zb();
    }));
    this.B(this.F.onDidChangeItemHeight((e) => {
      this.D.updateElementHeight(e.element, e.height);
    }));
    this.B(this.D.onDidFocus(() => {
      this.f.fire();
    }));
    this.B(this.D.onDidScroll(() => {
      this.h.fire();
      const isScrolledDown = this.D.scrollTop >= this.D.scrollHeight - this.D.renderHeight - 2;
      this.M.classList.toggle("show-scroll-down", !isScrolledDown && !this.X);
    }));
  }
  yb(e) {
    e.browserEvent.preventDefault();
    e.browserEvent.stopPropagation();
    const selected = e.element;
    const scopedContextKeyService = this.eb.createOverlay([
      [ChatContextKeys.responseIsFiltered.key, $asb(selected) && !!selected.errorDetails?.responseIsFiltered]
    ]);
    this.jb.showContextMenu({
      menuId: $bJ.ChatContext,
      menuActionOptions: { shouldForwardArgs: true },
      contextKeyService: scopedContextKeyService,
      getAnchor: () => e.anchor,
      getActionsContext: () => selected
    });
  }
  zb() {
    if (this.D.scrollHeight !== this.W) {
      const lastItem = this.viewModel?.getItems().at(-1);
      const lastResponseIsRendering = $asb(lastItem) && lastItem.renderData;
      if (!lastResponseIsRendering || this.X) {
        const lastElementWasVisible = this.D.scrollTop + this.D.renderHeight >= this.W - 2;
        if (lastElementWasVisible) {
          $jj(getWindow(this.L), () => {
            this.sb();
          }, 0);
        }
      }
    }
    this.W = this.D.scrollHeight;
    this.z.fire();
  }
  Ab(container2, options3) {
    this.I = this.B(this.fb.createInstance($1Nb, this.location, {
      renderFollowups: options3?.renderFollowups ?? true,
      renderStyle: options3?.renderStyle === "minimal" ? "compact" : options3?.renderStyle,
      menus: { executeToolbar: $bJ.ChatExecute, ...this.cb.menus },
      editorOverflowWidgetsDomNode: this.cb.editorOverflowWidgetsDomNode,
      enableImplicitContext: this.cb.enableImplicitContext
    }, this.db, () => this.Cb()));
    this.I.render(container2, "", this);
    this.B(this.I.onDidLoadInputState((state) => {
      this.C.forEach((c) => {
        if (c.setInputState) {
          const contribState = (typeof state === "object" && state?.[c.id]) ?? {};
          c.setInputState(contribState);
        }
      });
      this.refreshParsedInput();
    }));
    this.B(this.I.onDidFocus(() => this.f.fire()));
    this.B(this.I.onDidAcceptFollowup((e) => {
      if (!this.viewModel) {
        return;
      }
      let msg = "";
      if (e.followup.agentId && e.followup.agentId !== this.hb.getDefaultAgent(this.location)?.id) {
        const agent = this.hb.getAgent(e.followup.agentId);
        if (!agent) {
          return;
        }
        this.lastSelectedAgent = agent;
        msg = `${$xO}${agent.name} `;
        if (e.followup.subCommand) {
          msg += `${$yO}${e.followup.subCommand} `;
        }
      } else if (!e.followup.agentId && e.followup.subCommand && this.nb.hasCommand(e.followup.subCommand)) {
        msg = `${$yO}${e.followup.subCommand} `;
      }
      msg += e.followup.message;
      this.acceptInput(msg);
      if (!e.response) {
        return;
      }
      this.gb.notifyUserAction({
        sessionId: this.viewModel.sessionId,
        requestId: e.response.requestId,
        agentId: e.response.agent?.id,
        command: e.response.slashCommand?.name,
        result: e.response.result,
        action: {
          kind: "followUp",
          followup: e.followup
        }
      });
    }));
    this.B(this.I.onDidChangeHeight(() => {
      if (this.P) {
        this.layout(this.P.height, this.P.width);
      }
      this.z.fire();
    }));
    this.B(this.I.attachmentModel.onDidChangeContext(() => {
      if (this.ob.currentEditingSession && this.ob.currentEditingSession?.chatSessionId === this.viewModel?.sessionId) {
        this.vb(this.ob.currentEditingSession);
      }
    }));
    this.B(this.inputEditor.onDidChangeModelContent(() => {
      this.ab = void 0;
      this.Fb();
    }));
    this.B(this.hb.onDidChangeAgents(() => this.ab = void 0));
  }
  Bb() {
    this.M.style.setProperty("--vscode-interactive-result-editor-background-color", this.J.configuration.resultEditor.backgroundColor?.toString() ?? "");
    this.M.style.setProperty("--vscode-interactive-session-foreground", this.J.configuration.foreground?.toString() ?? "");
    this.M.style.setProperty("--vscode-chat-list-background", this.mb.getColorTheme().getColor(this.db.listBackground)?.toString() ?? "");
  }
  setModel(model, viewState) {
    if (!this.M) {
      throw new Error("Call render() before setModel()");
    }
    if (model.sessionId === this.viewModel?.sessionId) {
      return;
    }
    this.G.clear();
    this.M.setAttribute("data-session-id", model.sessionId);
    this.viewModel = this.fb.createInstance($bsb, model, this.G);
    this.Y.add(Event2.accumulate(this.viewModel.onDidChange, 0)((events) => {
      if (!this.viewModel) {
        return;
      }
      this.R.set(this.viewModel.requestInProgress);
      this.tb();
      if (events.some((e) => e?.kind === "addRequest") && this.visible) {
        this.sb();
      }
      if (this.ob.currentEditingSession && this.ob.currentEditingSession?.chatSessionId === this.viewModel?.sessionId) {
        this.vb(this.ob.currentEditingSession);
      }
    }));
    this.Y.add(this.viewModel.onDidDisposeModel(() => {
      this.I.saveState();
      this.viewModel = void 0;
      this.tb();
    }));
    this.I.initForNewChatModel(viewState);
    this.C.forEach((c) => {
      if (c.setInputState && viewState.inputState?.[c.id]) {
        c.setInputState(viewState.inputState?.[c.id]);
      }
    });
    this.refreshParsedInput();
    this.Y.add(model.onDidChange((e) => {
      if (e.kind === "setAgent") {
        this.b.fire({ agent: e.agent, slashCommand: e.command });
      }
    }));
    if (this.D && this.visible) {
      this.tb();
      this.sb();
    }
    this.Fb();
  }
  getFocus() {
    return this.D.getFocus()[0] ?? void 0;
  }
  reveal(item, relativeTop) {
    this.D.reveal(item, relativeTop);
  }
  focus(item) {
    const items = this.D.getNode(null).children;
    const node = items.find((i2) => i2.element?.id === item.id);
    if (!node) {
      return;
    }
    this.D.setFocus([node.element]);
    this.D.domFocus();
  }
  refilter() {
    this.D.refilter();
  }
  setInputPlaceholder(placeholder) {
    this.viewModel?.setInputPlaceholder(placeholder);
  }
  resetInputPlaceholder() {
    this.viewModel?.resetInputPlaceholder();
  }
  setInput(value = "") {
    this.I.setValue(value, false);
    this.refreshParsedInput();
  }
  getInput() {
    return this.I.inputEditor.getValue();
  }
  logInputHistory() {
    this.I.logInputHistory();
  }
  async acceptInput(query, options3) {
    return this.Db(query ? { query } : void 0, options3);
  }
  async rerunLastRequest() {
    if (!this.viewModel) {
      return;
    }
    const sessionId = this.viewModel.sessionId;
    const lastRequest2 = this.gb.getSession(sessionId)?.getRequests().at(-1);
    if (!lastRequest2) {
      return;
    }
    const options3 = {
      attempt: lastRequest2.attempt + 1,
      location: this.location,
      userSelectedModelId: this.input.currentLanguageModel
    };
    return await this.gb.resendRequest(lastRequest2, options3);
  }
  async acceptInputWithPrefix(prefix) {
    this.Db({ prefix });
  }
  Cb() {
    const inputState = {};
    this.C.forEach((c) => {
      if (c.getInputState) {
        inputState[c.id] = c.getInputState();
      }
    });
    return inputState;
  }
  async Db(query, options3) {
    if (this.viewModel) {
      this.n.fire();
      if (!this.cb.autoScroll) {
        this.X = false;
      }
      const editorValue = this.getInput();
      const requestId = this.kb.acceptRequest();
      const input = !query ? editorValue : "query" in query ? query.query : `${query.prefix} ${editorValue}`;
      const isUserQuery = !query || "prefix" in query;
      const requests = this.viewModel.model.getRequests();
      for (let i2 = requests.length - 1; i2 >= 0; i2 -= 1) {
        const request = requests[i2];
        if (request.isHidden) {
          this.gb.removeRequest(this.viewModel.sessionId, request.id);
        }
      }
      let attachedContext = this.I.getAttachedAndImplicitContext();
      let workingSet;
      if (this.location === ChatAgentLocation.EditingSession) {
        const currentEditingSession = this.ob.currentEditingSessionObs.get();
        const unconfirmedSuggestions = new $Fc();
        const uniqueWorkingSetEntries = new $Fc();
        const editingSessionAttachedContext = [];
        for (const v of this.I.chatEditWorkingSetFiles) {
          if (currentEditingSession?.workingSet.get(v)?.state === 6) {
            unconfirmedSuggestions.add(v);
          } else {
            uniqueWorkingSetEntries.add(v);
            editingSessionAttachedContext.push(this.attachmentModel.asVariableEntry(v));
          }
        }
        let maximumFileEntries = this.ob.editingSessionFileLimit - editingSessionAttachedContext.length;
        for (const attachment of this.attachmentModel.attachments) {
          if (!URI.isUri(attachment.value)) {
            editingSessionAttachedContext.push(attachment);
          }
        }
        for (const file of uniqueWorkingSetEntries) {
          currentEditingSession?.addFileToWorkingSet(file);
        }
        const previousRequests = this.viewModel.model.getRequests();
        for (const request of previousRequests) {
          for (const variable of request.variableData.variables) {
            if (URI.isUri(variable.value) && variable.isFile && maximumFileEntries > 0) {
              const uri = variable.value;
              if (!uniqueWorkingSetEntries.has(uri)) {
                editingSessionAttachedContext.push(variable);
                uniqueWorkingSetEntries.add(variable.value);
                maximumFileEntries -= 1;
              }
            }
          }
        }
        workingSet = [...uniqueWorkingSetEntries.values()];
        attachedContext = editingSessionAttachedContext;
        this.qb.publicLog2("chatEditing/workingSetSize", { originalSize: this.I.attemptedWorkingSetEntriesCount, actualSize: uniqueWorkingSetEntries.size });
        currentEditingSession?.remove(0, ...unconfirmedSuggestions);
      }
      const result = await this.gb.sendRequest(this.viewModel.sessionId, input, {
        userSelectedModelId: this.I.currentLanguageModel,
        location: this.location,
        locationData: this.bb.resolveData?.(),
        parserContext: { selectedAgent: this.rb },
        attachedContext,
        workingSet,
        noCommandDetection: options3?.noCommandDetection
      });
      if (result) {
        this.I.acceptInput(isUserQuery);
        this.a.fire({ agent: result.agent, slashCommand: result.slashCommand });
        result.responseCompletePromise.then(() => {
          const responses = this.viewModel?.getItems().filter($asb);
          const lastResponse = responses?.[responses.length - 1];
          this.kb.acceptResponse(lastResponse, requestId, options3?.isVoiceInput);
          if (lastResponse?.result?.nextQuestion) {
            const { prompt, participant, command: command4 } = lastResponse.result.nextQuestion;
            const question = $HO(this.hb, this.location, prompt, participant, command4);
            if (question) {
              this.input.setValue(question, false);
            }
          }
        });
        return result.responseCreatedPromise;
      }
    }
    return void 0;
  }
  getCodeBlockInfosForResponse(response) {
    return this.F.getCodeBlockInfosForResponse(response);
  }
  getCodeBlockInfoForEditor(uri) {
    return this.F.getCodeBlockInfoForEditor(uri);
  }
  getFileTreeInfosForResponse(response) {
    return this.F.getFileTreeInfosForResponse(response);
  }
  getLastFocusedFileTreeForResponse(response) {
    return this.F.getLastFocusedFileTreeForResponse(response);
  }
  focusLastMessage() {
    if (!this.viewModel) {
      return;
    }
    const items = this.D.getNode(null).children;
    const lastItem = items[items.length - 1];
    if (!lastItem) {
      return;
    }
    this.D.setFocus([lastItem.element]);
    this.D.domFocus();
  }
  layout(height, width2) {
    width2 = Math.min(width2, 850);
    this.P = new $rj(width2, height);
    const inputPartMaxHeight = this.Eb?.enabled ? this.Eb.maxHeight : height;
    this.I.layout(inputPartMaxHeight, width2);
    const inputPartHeight = this.I.inputPartHeight;
    const lastElementVisible = this.D.scrollTop + this.D.renderHeight >= this.D.scrollHeight - 2;
    const listHeight = Math.max(0, height - inputPartHeight);
    if (!this.cb.autoScroll) {
      this.L.style.setProperty("--chat-current-response-min-height", listHeight * 0.75 + "px");
    }
    this.D.layout(listHeight, width2);
    this.D.getHTMLElement().style.height = `${listHeight}px`;
    const followupsOffset = this.cb.renderFollowups ? Math.max(100 - this.I.followupsHeight, 0) : 0;
    this.N.style.height = `${listHeight - followupsOffset}px`;
    this.N.style.paddingBottom = `${followupsOffset}px`;
    this.F.layout(width2);
    const lastItem = this.viewModel?.getItems().at(-1);
    const lastResponseIsRendering = $asb(lastItem) && lastItem.renderData;
    if (lastElementVisible && (!lastResponseIsRendering || this.cb.autoScroll)) {
      this.sb();
    }
    this.L.style.height = `${listHeight}px`;
    this.y.fire(height);
  }
  // An alternative to layout, this allows you to specify the number of ChatTreeItems
  // you want to show, and the max height of the container. It will then layout the
  // tree to show that many items.
  // TODO@TylerLeonhardt: This could use some refactoring to make it clear which layout strategy is being used
  setDynamicChatTreeItemLayout(numOfChatTreeItems, maxHeight) {
    this.Eb = { numOfMessages: numOfChatTreeItems, maxHeight, enabled: true };
    this.B(this.F.onDidChangeItemHeight(() => this.layoutDynamicChatTreeItemMode()));
    const mutableDisposable = this.B(new $4c());
    this.B(this.D.onDidScroll((e) => {
      if (!this.Eb?.enabled) {
        return;
      }
      mutableDisposable.value = $jj(getWindow(this.L), () => {
        if (!e.scrollTopChanged || e.heightChanged || e.scrollHeightChanged) {
          return;
        }
        const renderHeight = e.height;
        const diff3 = e.scrollHeight - renderHeight - e.scrollTop;
        if (diff3 === 0) {
          return;
        }
        const possibleMaxHeight = this.Eb?.maxHeight ?? maxHeight;
        const width2 = this.P?.width ?? this.M.offsetWidth;
        this.I.layout(possibleMaxHeight, width2);
        const inputPartHeight = this.I.inputPartHeight;
        const newHeight = Math.min(renderHeight + diff3, possibleMaxHeight - inputPartHeight);
        this.layout(newHeight + inputPartHeight, width2);
      });
    }));
  }
  updateDynamicChatTreeItemLayout(numOfChatTreeItems, maxHeight) {
    this.Eb = { numOfMessages: numOfChatTreeItems, maxHeight, enabled: true };
    let hasChanged = false;
    let height = this.P.height;
    let width2 = this.P.width;
    if (maxHeight < this.P.height) {
      height = maxHeight;
      hasChanged = true;
    }
    const containerWidth = this.M.offsetWidth;
    if (this.P?.width !== containerWidth) {
      width2 = containerWidth;
      hasChanged = true;
    }
    if (hasChanged) {
      this.layout(height, width2);
    }
  }
  get isDynamicChatTreeItemLayoutEnabled() {
    return this.Eb?.enabled ?? false;
  }
  set isDynamicChatTreeItemLayoutEnabled(value) {
    if (!this.Eb) {
      return;
    }
    this.Eb.enabled = value;
  }
  layoutDynamicChatTreeItemMode() {
    if (!this.viewModel || !this.Eb?.enabled) {
      return;
    }
    const width2 = this.P?.width ?? this.M.offsetWidth;
    this.I.layout(this.Eb.maxHeight, width2);
    const inputHeight = this.I.inputPartHeight;
    const totalMessages = this.viewModel.getItems();
    const messages = totalMessages.slice(-this.Eb.numOfMessages);
    const needsRerender = messages.some((m) => m.currentRenderedHeight === void 0);
    const listHeight = needsRerender ? this.Eb.maxHeight : messages.reduce((acc, message) => acc + message.currentRenderedHeight, 0);
    this.layout(Math.min(
      // we add an additional 18px in order to show that there is scrollable content
      inputHeight + listHeight + (totalMessages.length > 2 ? 18 : 0),
      this.Eb.maxHeight
    ), width2);
    if (needsRerender || !listHeight) {
      this.sb();
    }
  }
  saveState() {
    this.I.saveState();
    if (this.viewModel?.model.welcomeMessage) {
      this.pb.store(
        `${PersistWelcomeMessageContentKey}.${this.location}`,
        this.viewModel?.model.welcomeMessage,
        -1,
        1
        /* StorageTarget.MACHINE */
      );
    }
  }
  getViewState() {
    return {
      inputValue: this.getInput(),
      inputState: this.I.getViewState()
    };
  }
  Fb() {
    const currentAgent = this.parsedInput.parts.find((part) => part instanceof $BO);
    this.S.set(!!currentAgent);
  }
};
$qNb = $qNb_1 = __decorate([
  __param(4, $U5),
  __param(5, $on),
  __param(6, $Pk),
  __param(7, $qO),
  __param(8, $ZO),
  __param(9, $2Nb),
  __param(10, $50),
  __param(11, $7Nb),
  __param(12, $wn),
  __param(13, $gs),
  __param(14, $sO),
  __param(15, $$O),
  __param(16, $jv),
  __param(17, $zv)
], $qNb);
var $rNb = class extends $3c {
  constructor() {
    super(...arguments);
    this.a = [];
    this.b = void 0;
    this.f = this.B(new $ze());
    this.onDidAddWidget = this.f.event;
  }
  get lastFocusedWidget() {
    return this.b;
  }
  getWidgetsByLocations(location3) {
    return this.a.filter((w) => w.location === location3);
  }
  getWidgetByInputUri(uri) {
    return this.a.find((w) => $oh(w.inputUri, uri));
  }
  getWidgetBySessionId(sessionId) {
    return this.a.find((w) => w.viewModel?.sessionId === sessionId);
  }
  g(widget) {
    if (widget === this.b) {
      return;
    }
    this.b = widget;
  }
  register(newWidget) {
    if (this.a.some((widget) => widget === newWidget)) {
      throw new Error("Cannot register the same widget multiple times");
    }
    this.a.push(newWidget);
    this.f.fire(newWidget);
    return $Zc(newWidget.onDidFocus(() => this.g(newWidget)), $1c(() => this.a.splice(this.a.indexOf(newWidget), 1)));
  }
};

// out-build/vs/workbench/contrib/chat/browser/contrib/chatDynamicVariables.js
var $aOb_1;
var $_Nb = "chat-dynamic-variable";
var $aOb = class $aOb2 extends $3c {
  static {
    $aOb_1 = this;
  }
  static {
    this.ID = "chatDynamicVariableModel";
  }
  get variables() {
    return [...this.a];
  }
  get id() {
    return $aOb_1.ID;
  }
  constructor(b, f) {
    super();
    this.b = b;
    this.f = f;
    this.a = [];
    this.B(b.inputEditor.onDidChangeModelContent((e) => {
      e.changes.forEach((c) => {
        this.a = $Mb(this.a.map((ref) => {
          const intersection = $9C.intersectRanges(ref.range, c.range);
          if (intersection && !intersection.isEmpty()) {
            if (!$9C.containsRange(c.range, ref.range)) {
              const rangeToDelete = new $9C(ref.range.startLineNumber, ref.range.startColumn, ref.range.endLineNumber, ref.range.endColumn - 1);
              this.b.inputEditor.executeEdits(this.id, [{
                range: rangeToDelete,
                text: ""
              }]);
              this.b.refreshParsedInput();
            }
            return null;
          } else if ($9C.compareRangesUsingStarts(ref.range, c.range) > 0) {
            const delta = c.text.length - c.rangeLength;
            return {
              ...ref,
              range: {
                startLineNumber: ref.range.startLineNumber,
                startColumn: ref.range.startColumn + delta,
                endLineNumber: ref.range.endLineNumber,
                endColumn: ref.range.endColumn + delta
              }
            };
          }
          return ref;
        }));
      });
      this.g();
    }));
  }
  getInputState() {
    return this.variables;
  }
  setInputState(s) {
    if (!Array.isArray(s)) {
      s = [];
    }
    this.a = s.filter(isDynamicVariable);
    this.g();
  }
  addReference(ref) {
    this.a.push(ref);
    this.g();
    this.b.refreshParsedInput();
  }
  g() {
    this.b.inputEditor.setDecorationsByType("chat", $_Nb, this.a.map((r2) => ({
      range: r2.range,
      hoverMessage: this.h(r2)
    })));
  }
  h(ref) {
    const value = ref.data;
    if (URI.isUri(value)) {
      return new $bm(this.f.getUriLabel(value, { relative: true }));
    } else if ($SE(value)) {
      const prefix = ref.fullName ? ` ${ref.fullName}` : "";
      const rangeString = `#${value.range.startLineNumber}-${value.range.endLineNumber}`;
      return new $bm(prefix + this.f.getUriLabel(value.uri, { relative: true }) + rangeString);
    } else {
      return void 0;
    }
  }
};
$aOb = $aOb_1 = __decorate([
  __param(1, $ZI)
], $aOb);
function isDynamicVariable(obj) {
  return obj && typeof obj.id === "string" && $9C.isIRange(obj.range) && "data" in obj;
}
$qNb.CONTRIBS.push($aOb);
function isSelectAndInsertActionContext(context) {
  return "widget" in context && "range" in context;
}
var $bOb = class _$bOb extends $gJ {
  static {
    this.Name = "files";
  }
  static {
    this.Item = {
      label: localize(5053, null),
      description: localize(5054, null)
    };
  }
  static {
    this.ID = "workbench.action.chat.selectAndInsertFile";
  }
  constructor() {
    super({
      id: _$bOb.ID,
      title: ""
      // not displayed
    });
  }
  async run(accessor, ...args2) {
    const textModelService = accessor.get($oG);
    const logService = accessor.get($wn);
    const quickInputService = accessor.get($1M);
    const chatVariablesService = accessor.get($kO);
    const context = args2[0];
    if (!isSelectAndInsertActionContext(context)) {
      return;
    }
    const doCleanup = () => {
      context.widget.inputEditor.executeEdits("chatInsertFile", [{ range: context.range, text: `` }]);
    };
    let options3;
    if (chatVariablesService.hasVariable(_$bOb.Name)) {
      const providerOptions = {
        additionPicks: [_$bOb.Item, { type: "separator" }]
      };
      options3 = { providerOptions };
    }
    const picks = await quickInputService.quickAccess.pick("", options3);
    if (!picks?.length) {
      logService.trace("SelectAndInsertFileAction: no file selected");
      doCleanup();
      return;
    }
    const editor = context.widget.inputEditor;
    const range = context.range;
    if (picks[0] === _$bOb.Item) {
      const text3 = `#${_$bOb.Name}`;
      const success2 = editor.executeEdits("chatInsertFile", [{ range, text: text3 + " " }]);
      if (!success2) {
        logService.trace(`SelectAndInsertFileAction: failed to insert "${text3}"`);
        doCleanup();
      }
      return;
    }
    const resource = picks[0].resource;
    if (!textModelService.canHandleResource(resource)) {
      logService.trace("SelectAndInsertFileAction: non-text resource selected");
      doCleanup();
      return;
    }
    const fileName = $sh(resource);
    const text2 = `#file:${fileName}`;
    const success = editor.executeEdits("chatInsertFile", [{ range, text: text2 + " " }]);
    if (!success) {
      logService.trace(`SelectAndInsertFileAction: failed to insert "${text2}"`);
      doCleanup();
      return;
    }
    context.widget.getContrib($aOb.ID)?.addReference({
      id: "vscode.file",
      isFile: true,
      prefix: "file",
      range: { startLineNumber: range.startLineNumber, startColumn: range.startColumn, endLineNumber: range.endLineNumber, endColumn: range.startColumn + text2.length },
      data: resource
    });
  }
};
$hJ($bOb);
var $cOb = class _$cOb extends $gJ {
  static {
    this.Name = "symbols";
  }
  static {
    this.ID = "workbench.action.chat.selectAndInsertSym";
  }
  constructor() {
    super({
      id: _$cOb.ID,
      title: ""
      // not displayed
    });
  }
  async run(accessor, ...args2) {
    const textModelService = accessor.get($oG);
    const logService = accessor.get($wn);
    const quickInputService = accessor.get($1M);
    const context = args2[0];
    if (!isSelectAndInsertActionContext(context)) {
      return;
    }
    const doCleanup = () => {
      context.widget.inputEditor.executeEdits("chatInsertSym", [{ range: context.range, text: `` }]);
    };
    const picks = await quickInputService.quickAccess.pick("#", { enabledProviderPrefixes: ["#"] });
    if (!picks?.length) {
      logService.trace("SelectAndInsertSymAction: no symbol selected");
      doCleanup();
      return;
    }
    const editor = context.widget.inputEditor;
    const range = context.range;
    const symbol = picks[0].symbol;
    if (!symbol || !textModelService.canHandleResource(symbol.location.uri)) {
      logService.trace("SelectAndInsertSymAction: non-text resource selected");
      doCleanup();
      return;
    }
    const text2 = `#sym:${symbol.name}`;
    const success = editor.executeEdits("chatInsertSym", [{ range, text: text2 + " " }]);
    if (!success) {
      logService.trace(`SelectAndInsertSymAction: failed to insert "${text2}"`);
      doCleanup();
      return;
    }
    context.widget.getContrib($aOb.ID)?.addReference({
      id: "vscode.symbol",
      prefix: "symbol",
      range: { startLineNumber: range.startLineNumber, startColumn: range.startColumn, endLineNumber: range.endLineNumber, endColumn: range.startColumn + text2.length },
      data: symbol.location
    });
  }
};
$hJ($cOb);
function isAddDynamicVariableContext(context) {
  return "widget" in context && "range" in context && "variableData" in context;
}
var $dOb = class _$dOb extends $gJ {
  static {
    this.ID = "workbench.action.chat.addDynamicVariable";
  }
  constructor() {
    super({
      id: _$dOb.ID,
      title: ""
      // not displayed
    });
  }
  async run(accessor, ...args2) {
    const context = args2[0];
    if (!isAddDynamicVariableContext(context)) {
      return;
    }
    let range = context.range;
    const variableData = context.variableData;
    const doCleanup = () => {
      context.widget.inputEditor.executeEdits("chatInsertDynamicVariableWithArguments", [{ range: context.range, text: `` }]);
    };
    if (context.command) {
      const commandService = accessor.get($sn);
      const selection = await commandService.executeCommand(context.command.id, ...context.command.arguments ?? []);
      if (!selection) {
        doCleanup();
        return;
      }
      const insertText = ":" + selection;
      const insertRange = new $9C(range.startLineNumber, range.endColumn, range.endLineNumber, range.endColumn + insertText.length);
      range = new $9C(range.startLineNumber, range.startColumn, range.endLineNumber, range.endColumn + insertText.length);
      const editor = context.widget.inputEditor;
      const success = editor.executeEdits("chatInsertDynamicVariableWithArguments", [{ range: insertRange, text: insertText + " " }]);
      if (!success) {
        doCleanup();
        return;
      }
    }
    context.widget.getContrib($aOb.ID)?.addReference({
      id: context.id,
      range,
      isFile: true,
      prefix: "file",
      data: variableData
    });
  }
};
$hJ($dOb);

// out-build/vs/workbench/api/browser/mainThreadChatAgents2.js
var $eOb = class {
  get onDidAddProgress() {
    return this.a.event;
  }
  constructor(content) {
    this.content = content;
    this.kind = "progressTask";
    this.deferred = new $gi();
    this.a = new $ze();
    this.progress = [];
  }
  task() {
    return this.deferred.p;
  }
  isSettled() {
    return this.deferred.isSettled;
  }
  complete(v) {
    this.deferred.complete(v);
  }
  add(progress) {
    this.progress.push(progress);
    this.a.fire(progress);
  }
};
var $fOb = class $fOb2 extends $3c {
  constructor(extHostContext, t, u, w, y, z, C, D, F) {
    super();
    this.t = t;
    this.u = u;
    this.w = w;
    this.y = y;
    this.z = z;
    this.C = C;
    this.D = D;
    this.F = F;
    this.a = this.B(new $_c());
    this.b = this.B(new $_c());
    this.f = this.B(new $_c());
    this.g = this.B(new $_c());
    this.h = this.B(new $_c());
    this.j = /* @__PURE__ */ new Map();
    this.n = 0;
    this.r = /* @__PURE__ */ new Map();
    this.s = /* @__PURE__ */ new Map();
    this.m = extHostContext.getProxy($yT.ExtHostChatAgents2);
    this.B(this.u.onDidDisposeSession((e) => {
      this.m.$releaseSession(e.sessionId);
    }));
    this.B(this.u.onDidPerformUserAction((e) => {
      if (typeof e.agentId === "string") {
        for (const [handle2, agent] of this.a) {
          if (agent.id === e.agentId) {
            if (e.action.kind === "vote") {
              this.m.$acceptFeedback(handle2, e.result ?? {}, e.action);
            } else {
              this.m.$acceptAction(handle2, e.result || {}, e);
            }
            break;
          }
        }
      }
    }));
  }
  $unregisterAgent(handle2) {
    this.a.deleteAndDispose(handle2);
  }
  $transferActiveChatSession(toWorkspace) {
    const widget = this.z.lastFocusedWidget;
    const sessionId = widget?.viewModel?.model.sessionId;
    if (!sessionId) {
      this.D.error(`MainThreadChat#$transferActiveChatSession: No active chat session found`);
      return;
    }
    const inputValue = widget?.inputEditor.getValue() ?? "";
    this.u.transferChatSession({ sessionId, inputValue }, URI.revive(toWorkspace));
  }
  async $registerAgent(handle2, extension, id2, metadata, dynamicProps) {
    await this.F.whenInstalledExtensionsRegistered();
    const staticAgentRegistration = this.t.getAgent(id2, true);
    if (!staticAgentRegistration && !dynamicProps) {
      if (this.t.getAgentsByName(id2).length) {
        throw new Error(`chatParticipant must be declared with an ID in package.json. The "id" property may be missing! "${id2}"`);
      }
      throw new Error(`chatParticipant must be declared in package.json: ${id2}`);
    }
    const impl = {
      invoke: async (request, progress, history, token) => {
        this.j.set(request.requestId, progress);
        try {
          return await this.m.$invokeAgent(handle2, request, { history }, token) ?? {};
        } finally {
          this.j.delete(request.requestId);
        }
      },
      provideFollowups: async (request, result, history, token) => {
        if (!this.a.get(handle2)?.hasFollowups) {
          return [];
        }
        return this.m.$provideFollowups(request, handle2, result, { history }, token);
      },
      provideWelcomeMessage: (token) => {
        return this.m.$provideWelcomeMessage(handle2, token);
      },
      provideChatTitle: (history, token) => {
        return this.m.$provideChatTitle(handle2, history, token);
      },
      provideSampleQuestions: (location3, token) => {
        return this.m.$provideSampleQuestions(handle2, location3, token);
      }
    };
    let disposable;
    if (!staticAgentRegistration && dynamicProps) {
      const extensionDescription = this.F.extensions.find((e) => $5z.equals(e.identifier, extension));
      disposable = this.t.registerDynamicAgent({
        id: id2,
        name: dynamicProps.name,
        description: dynamicProps.description,
        extensionId: extension,
        extensionDisplayName: extensionDescription?.displayName ?? extension.value,
        extensionPublisherId: extensionDescription?.publisher ?? "",
        publisherDisplayName: dynamicProps.publisherName,
        fullName: dynamicProps.fullName,
        metadata: $cu(metadata),
        slashCommands: [],
        disambiguation: [],
        locations: [ChatAgentLocation.Panel]
        // TODO all dynamic participants are panel only?
      }, impl);
    } else {
      disposable = this.t.registerAgentImplementation(id2, impl);
    }
    this.a.set(handle2, {
      id: id2,
      extensionId: extension,
      dispose: disposable.dispose,
      hasFollowups: metadata.hasFollowups
    });
  }
  async $updateAgent(handle2, metadataUpdate) {
    await this.F.whenInstalledExtensionsRegistered();
    const data = this.a.get(handle2);
    if (!data) {
      this.D.error(`MainThreadChatAgents2#$updateAgent: No agent with handle ${handle2} registered`);
      return;
    }
    data.hasFollowups = metadataUpdate.hasFollowups;
    this.t.updateAgent(data.id, $cu(metadataUpdate));
  }
  async $handleProgressChunk(requestId, progress, responsePartHandle) {
    const revivedProgress = $cu(progress);
    if (revivedProgress.kind === "progressTask") {
      const handle2 = ++this.n;
      const responsePartId = `${requestId}_${handle2}`;
      const task = new $eOb(revivedProgress.content);
      this.r.set(responsePartId, task);
      this.j.get(requestId)?.(task);
      return handle2;
    } else if (responsePartHandle !== void 0) {
      const responsePartId = `${requestId}_${responsePartHandle}`;
      const task = this.r.get(responsePartId);
      switch (revivedProgress.kind) {
        case "progressTaskResult":
          if (task && revivedProgress.content) {
            task.complete(revivedProgress.content.value);
            this.r.delete(responsePartId);
          } else {
            task?.complete(void 0);
          }
          return responsePartHandle;
        case "warning":
        case "reference":
          task?.add(revivedProgress);
          return;
      }
    }
    if (revivedProgress.kind === "inlineReference" && revivedProgress.resolveId) {
      if (!this.s.has(requestId)) {
        this.s.set(requestId, /* @__PURE__ */ new Map());
      }
      this.s.get(requestId)?.set(revivedProgress.resolveId, revivedProgress);
    }
    this.j.get(requestId)?.(revivedProgress);
  }
  $handleAnchorResolve(requestId, handle2, resolveAnchor) {
    const anchor = this.s.get(requestId)?.get(handle2);
    if (!anchor) {
      return;
    }
    this.s.get(requestId)?.delete(handle2);
    if (resolveAnchor) {
      const revivedAnchor = $cu(resolveAnchor);
      anchor.inlineReference = revivedAnchor.inlineReference;
    }
  }
  $registerAgentCompletionsProvider(handle2, id2, triggerCharacters) {
    const provide = async (query, token) => {
      const completions = await this.m.$invokeCompletionProvider(handle2, query, token);
      return completions.map((c) => ({ ...c, icon: c.icon ? ThemeIcon.fromId(c.icon) : void 0 }));
    };
    this.f.set(id2, this.t.registerAgentCompletionProvider(id2, provide));
    this.b.set(handle2, this.y.completionProvider.register({ scheme: $1Nb.INPUT_SCHEME, hasAccessToAllModels: true }, {
      _debugDisplayName: "chatAgentCompletions:" + handle2,
      triggerCharacters,
      provideCompletionItems: async (model, position, _context, token) => {
        const widget = this.z.getWidgetByInputUri(model.uri);
        if (!widget || !widget.viewModel) {
          return;
        }
        const triggerCharsPart = triggerCharacters.map((c) => $Af(c)).join("");
        const wordRegex = new RegExp(`[${triggerCharsPart}]\\S*`, "g");
        const query = $MD(position.column, wordRegex, model.getLineContent(position.lineNumber), 0)?.word ?? "";
        if (query && !triggerCharacters.some((c) => query.startsWith(c))) {
          return;
        }
        const parsedRequest = this.C.createInstance($nO).parseChatRequest(widget.viewModel.sessionId, model.getValue()).parts;
        const agentPart = parsedRequest.find((part) => part instanceof $BO);
        const thisAgentId = this.a.get(handle2)?.id;
        if (agentPart?.agent.id !== thisAgentId) {
          return;
        }
        const range = computeCompletionRanges(model, position, wordRegex);
        if (!range) {
          return null;
        }
        const result = await provide(query, token);
        const variableItems = result.map((v) => {
          const insertText = v.insertText ?? (typeof v.label === "string" ? v.label : v.label.label);
          const rangeAfterInsert = new $9C(range.insert.startLineNumber, range.insert.startColumn, range.insert.endLineNumber, range.insert.startColumn + insertText.length);
          return {
            label: v.label,
            range,
            insertText: insertText + " ",
            kind: 18,
            detail: v.detail,
            documentation: v.documentation,
            command: { id: $dOb.ID, title: "", arguments: [{ id: v.id, widget, range: rangeAfterInsert, variableData: $cu(v.value), command: v.command }] }
          };
        });
        return {
          suggestions: variableItems
        };
      }
    }));
  }
  $unregisterAgentCompletionsProvider(handle2, id2) {
    this.b.deleteAndDispose(handle2);
    this.f.deleteAndDispose(id2);
  }
  $registerChatParticipantDetectionProvider(handle2) {
    this.g.set(handle2, this.t.registerChatParticipantDetectionProvider(handle2, {
      provideParticipantDetection: async (request, history, options3, token) => {
        return await this.m.$detectChatParticipant(handle2, request, { history }, options3, token);
      }
    }));
  }
  $unregisterChatParticipantDetectionProvider(handle2) {
    this.g.deleteAndDispose(handle2);
  }
  $registerRelatedFilesProvider(handle2, metadata) {
    this.h.set(handle2, this.w.registerRelatedFilesProvider(handle2, {
      description: metadata.description,
      provideRelatedFiles: async (request, token) => {
        return (await this.m.$provideRelatedFiles(handle2, request, token))?.map((v) => ({ uri: URI.from(v.uri), description: v.description })) ?? [];
      }
    }));
  }
  $unregisterRelatedFilesProvider(handle2) {
    this.h.deleteAndDispose(handle2);
  }
};
$fOb = __decorate([
  $frb($xT.MainThreadChatAgents2),
  __param(1, $ZO),
  __param(2, $qO),
  __param(3, $$O),
  __param(4, $mP),
  __param(5, $2Nb),
  __param(6, $Pk),
  __param(7, $wn),
  __param(8, $wN)
], $fOb);
function computeCompletionRanges(model, position, reg2) {
  const varWord = $MD(position.column, reg2, model.getLineContent(position.lineNumber), 0);
  if (!varWord && model.getWordUntilPosition(position).word) {
    return;
  }
  let insert;
  let replace;
  if (!varWord) {
    insert = replace = $9C.fromPositions(position);
  } else {
    insert = new $9C(position.lineNumber, varWord.startColumn, position.lineNumber, position.column);
    replace = new $9C(position.lineNumber, varWord.startColumn, position.lineNumber, varWord.endColumn);
  }
  return { insert, replace };
}

// out-build/vs/workbench/api/browser/mainThreadChatVariables.js
var $gOb = class $gOb2 {
  constructor(extHostContext, d) {
    this.d = d;
    this.b = new $_c();
    this.c = /* @__PURE__ */ new Map();
    this.a = extHostContext.getProxy($yT.ExtHostChatVariables);
  }
  dispose() {
    this.b.clearAndDisposeAll();
  }
  $registerVariable(handle2, data) {
    const registration = this.d.registerVariable(data, async (messageText, _arg, model, progress, token) => {
      const varRequestId = `${model.sessionId}-${handle2}`;
      this.c.set(varRequestId, progress);
      const result = $cu(await this.a.$resolveVariable(handle2, varRequestId, messageText, token));
      this.c.delete(varRequestId);
      return result;
    });
    this.b.set(handle2, registration);
  }
  async $handleProgressChunk(requestId, progress) {
    const revivedProgress = $cu(progress);
    this.c.get(requestId)?.(revivedProgress);
  }
  $unregisterVariable(handle2) {
    this.b.deleteAndDispose(handle2);
  }
};
$gOb = __decorate([
  $frb($xT.MainThreadChatVariables),
  __param(1, $kO)
], $gOb);

// out-build/vs/workbench/contrib/chat/common/chatCodeMapperService.js
var $7O = $Qk("codeMapperService");
var $8O = class {
  constructor() {
    this.a = [];
  }
  registerCodeMapperProvider(handle2, provider) {
    this.a.push(provider);
    return {
      dispose: () => {
        const index = this.a.indexOf(provider);
        if (index >= 0) {
          this.a.splice(index, 1);
        }
      }
    };
  }
  async mapCode(request, response, token) {
    for (const provider of this.a) {
      const result = await provider.mapCode(request, response, token);
      if (result) {
        return result;
      }
    }
    return void 0;
  }
  async mapCodeFromResponse(responseModel, response, token) {
    const fenceLanguageRegex = /^`{3,}/;
    const codeBlocks = [];
    const currentBlock = [];
    const markdownBeforeBlock = [];
    let currentBlockUri = void 0;
    let fence = void 0;
    for (const lineOrUri of iterateLinesOrUris(responseModel)) {
      if ($zg(lineOrUri)) {
        const fenceLanguageIdMatch = lineOrUri.match(fenceLanguageRegex);
        if (fenceLanguageIdMatch) {
          if (fence !== void 0 && fenceLanguageIdMatch[0] === fence) {
            fence = void 0;
            if (currentBlockUri) {
              codeBlocks.push({ code: currentBlock.join(""), resource: currentBlockUri, markdownBeforeBlock: markdownBeforeBlock.join("") });
              currentBlock.length = 0;
              markdownBeforeBlock.length = 0;
              currentBlockUri = void 0;
            }
          } else {
            fence = fenceLanguageIdMatch[0];
          }
        } else {
          if (fence !== void 0) {
            currentBlock.push(lineOrUri);
          } else {
            markdownBeforeBlock.push(lineOrUri);
          }
        }
      } else {
        currentBlockUri = lineOrUri;
      }
    }
    const conversation = [];
    for (const request of responseModel.session.getRequests()) {
      const response2 = request.response;
      if (!response2 || response2 === responseModel) {
        break;
      }
      conversation.push({
        type: "request",
        message: request.message.text
      });
      conversation.push({
        type: "response",
        message: response2.response.getMarkdown(),
        result: response2.result,
        references: $9O(response2.contentReferences)
      });
    }
    return this.mapCode({ codeBlocks, conversation }, response, token);
  }
};
function iterateLinesOrUris(responseModel) {
  return {
    *[Symbol.iterator]() {
      let lastIncompleteLine = void 0;
      for (const part of responseModel.response.value) {
        if (part.kind === "markdownContent" || part.kind === "markdownVuln") {
          const lines = $Nf(part.content.value);
          if (lines.length > 0) {
            if (lastIncompleteLine !== void 0) {
              lines[0] = lastIncompleteLine + lines[0];
            }
            lastIncompleteLine = isLineIncomplete(lines[lines.length - 1]) ? lines.pop() : void 0;
            for (const line of lines) {
              yield line;
            }
          }
        } else if (part.kind === "codeblockUri") {
          yield part.uri;
        }
      }
      if (lastIncompleteLine !== void 0) {
        yield lastIncompleteLine;
      }
    }
  };
}
function isLineIncomplete(line) {
  const lastChar = line.charCodeAt(line.length - 1);
  return lastChar !== 10 && lastChar !== 13;
}
function $9O(res) {
  const map = new $Ec();
  for (const r2 of res) {
    let uri;
    let range;
    if (URI.isUri(r2.reference)) {
      uri = r2.reference;
    } else if ($SE(r2.reference)) {
      uri = r2.reference.uri;
      range = r2.reference.range;
    }
    if (uri) {
      const item = map.get(uri);
      if (item) {
        if (range) {
          item.ranges.push(range);
        }
      } else {
        map.set(uri, { uri, version: -1, ranges: range ? [range] : [] });
      }
    }
  }
  return [...map.values()];
}

// out-build/vs/workbench/api/browser/mainThreadChatCodeMapper.js
var $hOb_1;
var $hOb = class $hOb2 extends $3c {
  static {
    $hOb_1 = this;
  }
  static {
    this.c = 0;
  }
  constructor(extHostContext, g) {
    super();
    this.g = g;
    this.a = this.B(new $_c());
    this.f = /* @__PURE__ */ new Map();
    this.b = extHostContext.getProxy($yT.ExtHostCodeMapper);
  }
  $registerCodeMapperProvider(handle2) {
    const impl = {
      mapCode: async (uiRequest, response, token) => {
        const requestId = String($hOb_1.c++);
        this.f.set(requestId, response);
        const extHostRequest = {
          requestId,
          codeBlocks: uiRequest.codeBlocks,
          conversation: uiRequest.conversation
        };
        try {
          return await this.b.$mapCode(handle2, extHostRequest, token).then((result) => result ?? void 0);
        } finally {
          this.f.delete(requestId);
        }
      }
    };
    const disposable = this.g.registerCodeMapperProvider(handle2, impl);
    this.a.set(handle2, disposable);
  }
  $unregisterCodeMapperProvider(handle2) {
    this.a.deleteAndDispose(handle2);
  }
  $handleProgress(requestId, data) {
    const response = this.f.get(requestId);
    if (response) {
      const resource = URI.revive(data.uri);
      response.textEdit(resource, data.edits);
    }
    return Promise.resolve();
  }
};
$hOb = $hOb_1 = __decorate([
  $frb($xT.MainThreadCodeMapper),
  __param(1, $7O)
], $hOb);

// out-build/vs/workbench/api/browser/mainThreadLanguageModelTools.js
var $iOb = class $iOb2 extends $3c {
  constructor(extHostContext, f) {
    super();
    this.f = f;
    this.b = this.B(new $_c());
    this.c = /* @__PURE__ */ new Map();
    this.a = extHostContext.getProxy($yT.ExtHostLanguageModelTools);
    this.B(this.f.onDidChangeTools((e) => this.a.$onDidChangeTools([...this.f.getTools()])));
  }
  async $getTools() {
    return Array.from(this.f.getTools());
  }
  async $invokeTool(dto, token) {
    return await this.f.invokeTool(dto, (input, token2) => this.a.$countTokensForInvocation(dto.callId, input, token2), token ?? CancellationToken.None);
  }
  $countTokensForInvocation(callId, input, token) {
    const fn = this.c.get(callId);
    if (!fn) {
      throw new Error(`Tool invocation call ${callId} not found`);
    }
    return fn(input, token);
  }
  $registerTool(id2) {
    const disposable = this.f.registerToolImplementation(id2, {
      invoke: async (dto, countTokens, token) => {
        try {
          this.c.set(dto.callId, countTokens);
          return await this.a.$invokeTool(dto, token);
        } finally {
          this.c.delete(dto.callId);
        }
      },
      prepareToolInvocation: (parameters, token) => this.a.$prepareToolInvocation(id2, parameters, token)
    });
    this.b.set(id2, disposable);
  }
  $unregisterTool(name) {
    this.b.deleteAndDispose(name);
  }
};
$iOb = __decorate([
  $frb($xT.MainThreadLanguageModelTools),
  __param(1, $mO)
], $iOb);

// out-build/vs/workbench/api/browser/mainThreadEmbeddings.js
var IEmbeddingsService = $Qk("embeddingsService");
var EmbeddingsService = class {
  constructor() {
    this.b = new $ze();
    this.onDidChange = this.b.event;
    this.a = /* @__PURE__ */ new Map();
  }
  get allProviders() {
    return this.a.keys();
  }
  registerProvider(id2, provider) {
    this.a.set(id2, provider);
    this.b.fire();
    return {
      dispose: () => {
        this.a.delete(id2);
        this.b.fire();
      }
    };
  }
  computeEmbeddings(id2, input, token) {
    const provider = this.a.get(id2);
    if (provider) {
      return provider.provideEmbeddings(input, token);
    } else {
      return Promise.reject(new Error(`No embeddings provider registered with id: ${id2}`));
    }
  }
};
$SC(
  IEmbeddingsService,
  EmbeddingsService,
  1
  /* InstantiationType.Delayed */
);
var $jOb = class $jOb2 {
  constructor(context, d) {
    this.d = d;
    this.a = new $2c();
    this.b = this.a.add(new $_c());
    this.c = context.getProxy($yT.ExtHostEmbeddings);
    this.a.add(d.onDidChange(() => {
      this.c.$acceptEmbeddingModels(Array.from(d.allProviders));
    }));
  }
  dispose() {
    this.a.dispose();
  }
  $registerEmbeddingProvider(handle2, identifier2) {
    const registration = this.d.registerProvider(identifier2, {
      provideEmbeddings: (input, token) => {
        return this.c.$provideEmbeddings(handle2, input, token);
      }
    });
    this.b.set(handle2, registration);
  }
  $unregisterEmbeddingProvider(handle2) {
    this.b.deleteAndDispose(handle2);
  }
  $computeEmbeddings(embeddingsModel, input, token) {
    return this.d.computeEmbeddings(embeddingsModel, input, token);
  }
};
$jOb = __decorate([
  $frb($xT.MainThreadEmbeddings),
  __param(1, IEmbeddingsService)
], $jOb);

// out-build/vs/workbench/api/common/extHostWebviewMessaging.js
var ArrayBufferSet = class {
  constructor() {
    this.buffers = [];
  }
  add(buffer) {
    let index = this.buffers.indexOf(buffer);
    if (index < 0) {
      index = this.buffers.length;
      this.buffers.push(buffer);
    }
    return index;
  }
};
function $kOb(message, options3) {
  if (options3.serializeBuffersForPostMessage) {
    const arrayBuffers = new ArrayBufferSet();
    const replacer2 = (_key, value) => {
      if (value instanceof ArrayBuffer) {
        const index = arrayBuffers.add(value);
        return {
          $$vscode_array_buffer_reference$$: true,
          index
        };
      } else if (ArrayBuffer.isView(value)) {
        const type = getTypedArrayType(value);
        if (type) {
          const index = arrayBuffers.add(value.buffer);
          return {
            $$vscode_array_buffer_reference$$: true,
            index,
            view: {
              type,
              byteLength: value.byteLength,
              byteOffset: value.byteOffset
            }
          };
        }
      }
      return value;
    };
    const serializedMessage = JSON.stringify(message, replacer2);
    const buffers = arrayBuffers.buffers.map((arrayBuffer) => {
      const bytes = new Uint8Array(arrayBuffer);
      return $Ci.wrap(bytes);
    });
    return { message: serializedMessage, buffers };
  } else {
    return { message: JSON.stringify(message), buffers: [] };
  }
}
function getTypedArrayType(value) {
  switch (value.constructor.name) {
    case "Int8Array":
      return 1;
    case "Uint8Array":
      return 2;
    case "Uint8ClampedArray":
      return 3;
    case "Int16Array":
      return 4;
    case "Uint16Array":
      return 5;
    case "Int32Array":
      return 6;
    case "Uint32Array":
      return 7;
    case "Float32Array":
      return 8;
    case "Float64Array":
      return 9;
    case "BigInt64Array":
      return 10;
    case "BigUint64Array":
      return 11;
  }
  return void 0;
}
function $lOb(jsonMessage, buffers) {
  const arrayBuffers = buffers.map((buffer) => {
    const arrayBuffer = new ArrayBuffer(buffer.byteLength);
    const uint8Array = new Uint8Array(arrayBuffer);
    uint8Array.set(buffer.buffer);
    return arrayBuffer;
  });
  const reviver = !buffers.length ? void 0 : (_key, value) => {
    if (value && typeof value === "object" && value.$$vscode_array_buffer_reference$$) {
      const ref = value;
      const { index } = ref;
      const arrayBuffer = arrayBuffers[index];
      if (ref.view) {
        switch (ref.view.type) {
          case 1:
            return new Int8Array(arrayBuffer, ref.view.byteOffset, ref.view.byteLength / Int8Array.BYTES_PER_ELEMENT);
          case 2:
            return new Uint8Array(arrayBuffer, ref.view.byteOffset, ref.view.byteLength / Uint8Array.BYTES_PER_ELEMENT);
          case 3:
            return new Uint8ClampedArray(arrayBuffer, ref.view.byteOffset, ref.view.byteLength / Uint8ClampedArray.BYTES_PER_ELEMENT);
          case 4:
            return new Int16Array(arrayBuffer, ref.view.byteOffset, ref.view.byteLength / Int16Array.BYTES_PER_ELEMENT);
          case 5:
            return new Uint16Array(arrayBuffer, ref.view.byteOffset, ref.view.byteLength / Uint16Array.BYTES_PER_ELEMENT);
          case 6:
            return new Int32Array(arrayBuffer, ref.view.byteOffset, ref.view.byteLength / Int32Array.BYTES_PER_ELEMENT);
          case 7:
            return new Uint32Array(arrayBuffer, ref.view.byteOffset, ref.view.byteLength / Uint32Array.BYTES_PER_ELEMENT);
          case 8:
            return new Float32Array(arrayBuffer, ref.view.byteOffset, ref.view.byteLength / Float32Array.BYTES_PER_ELEMENT);
          case 9:
            return new Float64Array(arrayBuffer, ref.view.byteOffset, ref.view.byteLength / Float64Array.BYTES_PER_ELEMENT);
          case 10:
            return new BigInt64Array(arrayBuffer, ref.view.byteOffset, ref.view.byteLength / BigInt64Array.BYTES_PER_ELEMENT);
          case 11:
            return new BigUint64Array(arrayBuffer, ref.view.byteOffset, ref.view.byteLength / BigUint64Array.BYTES_PER_ELEMENT);
          default:
            throw new Error("Unknown array buffer view type");
        }
      }
      return arrayBuffer;
    }
    return value;
  };
  const message = JSON.parse(jsonMessage, reviver);
  return { message, arrayBuffers };
}

// out-build/vs/workbench/api/browser/mainThreadWebviews.js
var $mOb_1;
var $mOb = class $mOb2 extends $3c {
  static {
    $mOb_1 = this;
  }
  static {
    this.a = /* @__PURE__ */ new Set([
      Schemas.http,
      Schemas.https,
      Schemas.mailto,
      Schemas.vscode,
      "vscode-insider"
    ]);
  }
  constructor(context, f, g) {
    super();
    this.f = f;
    this.g = g;
    this.c = /* @__PURE__ */ new Map();
    this.b = context.getProxy($yT.ExtHostWebviews);
  }
  addWebview(handle2, webview, options3) {
    if (this.c.has(handle2)) {
      throw new Error("Webview already registered");
    }
    this.c.set(handle2, webview);
    this.h(handle2, webview, options3);
  }
  $setHtml(handle2, value) {
    this.n(handle2)?.setHtml(value);
  }
  $setOptions(handle2, options3) {
    const webview = this.n(handle2);
    if (webview) {
      webview.contentOptions = $oOb(options3);
    }
  }
  async $postMessage(handle2, jsonMessage, ...buffers) {
    const webview = this.n(handle2);
    if (!webview) {
      return false;
    }
    const { message, arrayBuffers } = $lOb(jsonMessage, buffers);
    return webview.postMessage(message, arrayBuffers);
  }
  h(handle2, webview, options3) {
    const disposables = new $2c();
    disposables.add(webview.onDidClickLink((uri) => this.j(handle2, uri)));
    disposables.add(webview.onMessage((message) => {
      const serialized = $kOb(message.message, options3);
      this.b.$onMessage(handle2, serialized.message, new $ES(serialized.buffers));
    }));
    disposables.add(webview.onMissingCsp((extension) => this.b.$onMissingCsp(handle2, extension.value)));
    disposables.add(webview.onDidDispose(() => {
      disposables.dispose();
      this.c.delete(handle2);
    }));
  }
  j(handle2, link2) {
    const webview = this.s(handle2);
    if (this.m(webview, URI.parse(link2))) {
      this.f.open(link2, { fromUserGesture: true, allowContributedOpeners: true, allowCommands: Array.isArray(webview.contentOptions.enableCommandUris) || webview.contentOptions.enableCommandUris === true, fromWorkspace: true });
    }
  }
  m(webview, link2) {
    if ($mOb_1.a.has(link2.scheme)) {
      return true;
    }
    if (!$r && this.g.urlProtocol === link2.scheme) {
      return true;
    }
    if (link2.scheme === Schemas.command) {
      if (Array.isArray(webview.contentOptions.enableCommandUris)) {
        return webview.contentOptions.enableCommandUris.includes(link2.path);
      }
      return webview.contentOptions.enableCommandUris === true;
    }
    return false;
  }
  n(handle2) {
    return this.c.get(handle2);
  }
  s(handle2) {
    const webview = this.n(handle2);
    if (!webview) {
      throw new Error(`Unknown webview handle:${handle2}`);
    }
    return webview;
  }
  getWebviewResolvedFailedContent(viewType) {
    return `<!DOCTYPE html>
		<html>
			<head>
				<meta http-equiv="Content-type" content="text/html;charset=UTF-8">
				<meta http-equiv="Content-Security-Policy" content="default-src 'none';">
			</head>
			<body>${localize(2631, null, $zf(viewType))}</body>
		</html>`;
  }
};
$mOb = $mOb_1 = __decorate([
  __param(1, $O4),
  __param(2, $Vu)
], $mOb);
function $nOb(extensionData) {
  return {
    id: extensionData.id,
    location: URI.revive(extensionData.location)
  };
}
function $oOb(webviewOptions) {
  return {
    allowScripts: webviewOptions.enableScripts,
    allowForms: webviewOptions.enableForms,
    enableCommandUris: webviewOptions.enableCommandUris,
    localResourceRoots: Array.isArray(webviewOptions.localResourceRoots) ? webviewOptions.localResourceRoots.map((r2) => URI.revive(r2)) : void 0,
    portMapping: webviewOptions.portMapping
  };
}

// out-build/vs/workbench/contrib/webview/browser/webview.js
var $zrb = new $nn("webviewFindWidgetVisible", false);
var $Arb = new $nn("webviewFindWidgetFocused", false);
var $Brb = new $nn("webviewFindWidgetEnabled", false);
var $Crb = $Qk("webviewService");
var WebviewContentPurpose;
(function(WebviewContentPurpose2) {
  WebviewContentPurpose2["NotebookRenderer"] = "notebookRenderer";
  WebviewContentPurpose2["CustomEditor"] = "customEditor";
  WebviewContentPurpose2["WebviewView"] = "webviewView";
})(WebviewContentPurpose || (WebviewContentPurpose = {}));
function $Drb(a, b) {
  return a.allowMultipleAPIAcquire === b.allowMultipleAPIAcquire && a.allowScripts === b.allowScripts && a.allowForms === b.allowForms && $zb(a.localResourceRoots, b.localResourceRoots, $oh) && $zb(a.portMapping, b.portMapping, (a2, b2) => a2.extensionHostPort === b2.extensionHostPort && a2.webviewPort === b2.webviewPort) && areEnableCommandUrisEqual(a, b);
}
function areEnableCommandUrisEqual(a, b) {
  if (a.enableCommandUris === b.enableCommandUris) {
    return true;
  }
  if (Array.isArray(a.enableCommandUris) && Array.isArray(b.enableCommandUris)) {
    return $zb(a.enableCommandUris, b.enableCommandUris);
  }
  return false;
}
var $Erb = class $Erb2 {
  constructor(rootStorageKey, storageService) {
    this.c = new $Slb(rootStorageKey, storageService);
    this.d = this.c.getMemento(
      -1,
      1
      /* StorageTarget.MACHINE */
    );
  }
  getOrigin(viewType, additionalKey) {
    const key2 = this.e(viewType, additionalKey);
    const existing = this.d[key2];
    if (existing && typeof existing === "string") {
      return existing;
    }
    const newOrigin = $ps();
    this.d[key2] = newOrigin;
    this.c.saveMemento();
    return newOrigin;
  }
  e(viewType, additionalKey) {
    return JSON.stringify({ viewType, key: additionalKey });
  }
};
$Erb = __decorate([
  __param(1, $jv)
], $Erb);
var $Frb = class $Frb2 {
  constructor(rootStorageKey, storageService) {
    this.c = new $Erb(rootStorageKey, storageService);
  }
  getOrigin(viewType, extId) {
    return this.c.getOrigin(viewType, extId.value);
  }
};
$Frb = __decorate([
  __param(1, $jv)
], $Frb);

// out-build/vs/workbench/api/browser/mainThreadCodeInsets.js
var EditorWebviewZone = class {
  // suppressMouseDown?: boolean | undefined;
  // heightInPx?: number | undefined;
  // minWidthInPx?: number | undefined;
  // marginDomNode?: HTMLElement | null | undefined;
  // onDomNodeTop?: ((top: number) => void) | undefined;
  // onComputedHeight?: ((height: number) => void) | undefined;
  constructor(editor, line, height, webview) {
    this.editor = editor;
    this.line = line;
    this.height = height;
    this.webview = webview;
    this.domNode = document.createElement("div");
    this.domNode.style.zIndex = "10";
    this.afterLineNumber = line;
    this.afterColumn = 1;
    this.heightInLines = height;
    editor.changeViewZones((accessor) => this.a = accessor.addZone(this));
    webview.mountTo(this.domNode, getWindow(editor.getDomNode()));
  }
  dispose() {
    this.editor.changeViewZones((accessor) => this.a && accessor.removeZone(this.a));
  }
};
var $pOb = class $pOb2 {
  constructor(context, d, e) {
    this.d = d;
    this.e = e;
    this.b = new $2c();
    this.c = /* @__PURE__ */ new Map();
    this.a = context.getProxy($yT.ExtHostEditorInsets);
  }
  dispose() {
    this.b.dispose();
  }
  async $createEditorInset(handle2, id2, uri, line, height, options3, extensionId, extensionLocation) {
    let editor;
    id2 = id2.substr(0, id2.indexOf(","));
    for (const candidate of this.d.listCodeEditors()) {
      if (candidate.getId() === id2 && candidate.hasModel() && $oh(candidate.getModel().uri, URI.revive(uri))) {
        editor = candidate;
        break;
      }
    }
    if (!editor) {
      setTimeout(() => this.a.$onDidDispose(handle2));
      return;
    }
    const disposables = new $2c();
    const webview = this.e.createWebviewElement({
      title: void 0,
      options: {
        enableFindWidget: false
      },
      contentOptions: $oOb(options3),
      extension: { id: extensionId, location: URI.revive(extensionLocation) }
    });
    const webviewZone = new EditorWebviewZone(editor, line, height, webview);
    const remove = () => {
      disposables.dispose();
      this.a.$onDidDispose(handle2);
      this.c.delete(handle2);
    };
    disposables.add(editor.onDidChangeModel(remove));
    disposables.add(editor.onDidDispose(remove));
    disposables.add(webviewZone);
    disposables.add(webview);
    disposables.add(webview.onMessage((msg) => this.a.$onDidReceiveMessage(handle2, msg.message)));
    this.c.set(handle2, webviewZone);
  }
  $disposeEditorInset(handle2) {
    const inset = this.f(handle2);
    this.c.delete(handle2);
    inset.dispose();
  }
  $setHtml(handle2, value) {
    const inset = this.f(handle2);
    inset.webview.setHtml(value);
  }
  $setOptions(handle2, options3) {
    const inset = this.f(handle2);
    inset.webview.contentOptions = $oOb(options3);
  }
  async $postMessage(handle2, value) {
    const inset = this.f(handle2);
    inset.webview.postMessage(value);
    return true;
  }
  f(handle2) {
    const inset = this.c.get(handle2);
    if (!inset) {
      throw new Error("Unknown inset");
    }
    return inset;
  }
};
$pOb = __decorate([
  $frb($xT.MainThreadEditorInsets),
  __param(1, $U5),
  __param(2, $Crb)
], $pOb);

// out-build/vs/base/common/semver/semver.js
var exports = {};
var module = { exports };
!function(e, r2) {
  if ("object" == typeof exports && "object" == typeof module) module.exports = r2();
  else if ("function" == typeof define && define.amd) define([], r2);
  else {
    var t = r2();
    for (var n in t) ("object" == typeof exports ? exports : e)[n] = t[n];
  }
}("undefined" != typeof self ? self : void 0, function() {
  return function(e) {
    var r2 = {};
    function t(n) {
      if (r2[n]) return r2[n].exports;
      var o = r2[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 = r2, t.d = function(e2, r3, n) {
      t.o(e2, r3) || Object.defineProperty(e2, r3, { 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, r3) {
      if (1 & r3 && (e2 = t(e2)), 8 & r3) return e2;
      if (4 & r3 && "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 & r3 && "string" != typeof e2) for (var o in e2) t.d(n, o, function(r4) {
        return e2[r4];
      }.bind(null, o));
      return n;
    }, t.n = function(e2) {
      var r3 = e2 && e2.__esModule ? function() {
        return e2.default;
      } : function() {
        return e2;
      };
      return t.d(r3, "a", r3), r3;
    }, t.o = function(e2, r3) {
      return Object.prototype.hasOwnProperty.call(e2, r3);
    }, t.p = "", t(t.s = 0);
  }([function(e, r2, t) {
    (function(t2) {
      var n;
      r2 = 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() {
      }, r2.SEMVER_SPEC_VERSION = "2.0.0";
      var o = 256, i2 = Number.MAX_SAFE_INTEGER || 9007199254740991, s = r2.re = [], a = r2.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 h3 = u++;
      a[h3] = "(" + 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[h3] + a[g] + "?" + a[d] + "?", T = u++;
      a[T] = "^" + E + "$";
      var x = u++;
      a[x] = "((?:<|>)?=?)";
      var $149 = u++;
      a[$149] = 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[$149] + ")(?:\\.(" + a[$149] + ")(?:\\.(" + a[$149] + ")(?:" + 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, r3) {
        if (e2 instanceof H) return e2;
        if ("string" != typeof e2) return null;
        if (e2.length > o) return null;
        if (!(r3 ? s[T] : s[b]).test(e2)) return null;
        try {
          return new H(e2, r3);
        } catch (e3) {
          return null;
        }
      }
      function H(e2, r3) {
        if (e2 instanceof H) {
          if (e2.loose === r3) 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, r3);
        n("SemVer", e2, r3), this.loose = r3;
        var t3 = e2.trim().match(r3 ? 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 > i2 || this.major < 0) throw new TypeError("Invalid major version");
        if (this.minor > i2 || this.minor < 0) throw new TypeError("Invalid minor version");
        if (this.patch > i2 || 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 r4 = +e3;
            if (r4 >= 0 && r4 < i2) return r4;
          }
          return e3;
        }) : this.prerelease = [], this.build = t3[5] ? t3[5].split(".") : [], this.format();
      }
      r2.parse = F, r2.valid = function(e2, r3) {
        var t3 = F(e2, r3);
        return t3 ? t3.version : null;
      }, r2.clean = function(e2, r3) {
        var t3 = F(e2.trim().replace(/^[=v]+/, ""), r3);
        return t3 ? t3.version : null;
      }, r2.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 r3 = 0;
        do {
          var t3 = this.prerelease[r3], o2 = e2.prerelease[r3];
          if (n("prerelease compare", r3, 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 (++r3);
      }, H.prototype.inc = function(e2, r3) {
        switch (e2) {
          case "premajor":
            this.prerelease.length = 0, this.patch = 0, this.minor = 0, this.major++, this.inc("pre", r3);
            break;
          case "preminor":
            this.prerelease.length = 0, this.patch = 0, this.minor++, this.inc("pre", r3);
            break;
          case "prepatch":
            this.prerelease.length = 0, this.inc("patch", r3), this.inc("pre", r3);
            break;
          case "prerelease":
            0 === this.prerelease.length && this.inc("patch", r3), this.inc("pre", r3);
            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);
            }
            r3 && (this.prerelease[0] === r3 ? isNaN(this.prerelease[1]) && (this.prerelease = [r3, 0]) : this.prerelease = [r3, 0]);
            break;
          default:
            throw new Error("invalid increment argument: " + e2);
        }
        return this.format(), this.raw = this.version, this;
      }, r2.inc = function(e2, r3, t3, n2) {
        "string" == typeof t3 && (n2 = t3, t3 = void 0);
        try {
          return new H(e2, t3).inc(r3, n2).version;
        } catch (e3) {
          return null;
        }
      }, r2.diff = function(e2, r3) {
        if (ee(e2, r3)) return null;
        var t3 = F(e2), n2 = F(r3);
        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;
      }, r2.compareIdentifiers = K;
      var J = /^[0-9]+$/;
      function K(e2, r3) {
        var t3 = J.test(e2), n2 = J.test(r3);
        return t3 && n2 && (e2 = +e2, r3 = +r3), t3 && !n2 ? -1 : n2 && !t3 ? 1 : e2 < r3 ? -1 : e2 > r3 ? 1 : 0;
      }
      function Q(e2, r3, t3) {
        return new H(e2, t3).compare(new H(r3, t3));
      }
      function W(e2, r3, t3) {
        return Q(e2, r3, t3) > 0;
      }
      function Y(e2, r3, t3) {
        return Q(e2, r3, t3) < 0;
      }
      function ee(e2, r3, t3) {
        return 0 === Q(e2, r3, t3);
      }
      function re(e2, r3, t3) {
        return 0 !== Q(e2, r3, t3);
      }
      function te(e2, r3, t3) {
        return Q(e2, r3, t3) >= 0;
      }
      function ne(e2, r3, t3) {
        return Q(e2, r3, t3) <= 0;
      }
      function oe(e2, r3, t3, n2) {
        var o2;
        switch (r3) {
          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: " + r3);
        }
        return o2;
      }
      function ie(e2, r3) {
        if (e2 instanceof ie) {
          if (e2.loose === r3) return e2;
          e2 = e2.value;
        }
        if (!(this instanceof ie)) return new ie(e2, r3);
        n("comparator", e2, r3), this.loose = r3, this.parse(e2), this.semver === se ? this.value = "" : this.value = this.operator + this.semver.version, n("comp", this);
      }
      r2.rcompareIdentifiers = function(e2, r3) {
        return K(r3, e2);
      }, r2.major = function(e2, r3) {
        return new H(e2, r3).major;
      }, r2.minor = function(e2, r3) {
        return new H(e2, r3).minor;
      }, r2.patch = function(e2, r3) {
        return new H(e2, r3).patch;
      }, r2.compare = Q, r2.compareLoose = function(e2, r3) {
        return Q(e2, r3, true);
      }, r2.rcompare = function(e2, r3, t3) {
        return Q(r3, e2, t3);
      }, r2.sort = function(e2, t3) {
        return e2.sort(function(e3, n2) {
          return r2.compare(e3, n2, t3);
        });
      }, r2.rsort = function(e2, t3) {
        return e2.sort(function(e3, n2) {
          return r2.rcompare(e3, n2, t3);
        });
      }, r2.gt = W, r2.lt = Y, r2.eq = ee, r2.neq = re, r2.gte = te, r2.lte = ne, r2.cmp = oe, r2.Comparator = ie;
      var se = {};
      function ae(e2, r3) {
        if (e2 instanceof ae) return e2.loose === r3 ? e2 : new ae(e2.raw, r3);
        if (e2 instanceof ie) return new ae(e2.value, r3);
        if (!(this instanceof ae)) return new ae(e2, r3);
        if (this.loose = r3, 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, r3, t3, n2, o2, i3, s2, a2, u2, c2, p2, f2, l2) {
        return ((r3 = ue(t3) ? "" : ue(n2) ? ">=" + t3 + ".0.0" : ue(o2) ? ">=" + t3 + "." + n2 + ".0" : ">=" + r3) + " " + (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, r3) {
        for (var t3 = 0; t3 < e2.length; t3++) if (!e2[t3].test(r3)) return false;
        if (r3.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 === r3.major && o2.minor === r3.minor && o2.patch === r3.patch) return true;
          }
          return false;
        }
        return true;
      }
      function fe(e2, r3, t3) {
        try {
          r3 = new ae(r3, t3);
        } catch (e3) {
          return false;
        }
        return r3.test(e2);
      }
      function le(e2, r3, t3, n2) {
        var o2, i3, s2, a2, u2;
        switch (e2 = new H(e2, n2), r3 = new ae(r3, n2), t3) {
          case ">":
            o2 = W, i3 = ne, s2 = Y, a2 = ">", u2 = ">=";
            break;
          case "<":
            o2 = Y, i3 = te, s2 = W, a2 = "<", u2 = "<=";
            break;
          default:
            throw new TypeError('Must provide a hilo val of "<" or ">"');
        }
        if (fe(e2, r3, n2)) return false;
        for (var c2 = 0; c2 < r3.set.length; ++c2) {
          var p2 = r3.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) && i3(e2, l2.semver)) return false;
          if (l2.operator === u2 && s2(e2, l2.semver)) return false;
        }
        return true;
      }
      ie.prototype.parse = function(e2) {
        var r3 = this.loose ? s[D] : s[X], t3 = e2.match(r3);
        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, r3) {
        if (!(e2 instanceof ie)) throw new TypeError("a Comparator is required");
        var t3;
        if ("" === this.operator) return t3 = new ae(e2.value, r3), fe(this.value, t3, r3);
        if ("" === e2.operator) return t3 = new ae(this.value, r3), fe(e2.semver, t3, r3);
        var n2 = !(">=" !== this.operator && ">" !== this.operator || ">=" !== e2.operator && ">" !== e2.operator), o2 = !("<=" !== this.operator && "<" !== this.operator || "<=" !== e2.operator && "<" !== e2.operator), i3 = this.semver.version === e2.semver.version, s2 = !(">=" !== this.operator && "<=" !== this.operator || ">=" !== e2.operator && "<=" !== e2.operator), a2 = oe(this.semver, "<", e2.semver, r3) && (">=" === this.operator || ">" === this.operator) && ("<=" === e2.operator || "<" === e2.operator), u2 = oe(this.semver, ">", e2.semver, r3) && ("<=" === this.operator || "<" === this.operator) && (">=" === e2.operator || ">" === e2.operator);
        return n2 || o2 || i3 && s2 || a2 || u2;
      }, r2.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 r3 = this.loose;
        e2 = e2.trim(), n("range", e2, r3);
        var t3 = r3 ? 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 = r3 ? s[D] : s[X], i3 = e2.split(" ").map(function(e3) {
          return function(e4, r4) {
            return n("comp", e4), e4 = function(e5, r5) {
              return e5.trim().split(/\s+/).map(function(e6) {
                return function(e7, r6) {
                  n("caret", e7, r6);
                  var t4 = r6 ? s[q] : s[N];
                  return e7.replace(t4, function(r7, t5, o3, i4, s2) {
                    var a2;
                    return n("caret", e7, r7, t5, o3, i4, s2), ue(t5) ? a2 = "" : ue(o3) ? a2 = ">=" + t5 + ".0.0 <" + (+t5 + 1) + ".0.0" : ue(i4) ? 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 + "." + i4 + s2 + " <" + t5 + "." + o3 + "." + (+i4 + 1) : ">=" + t5 + "." + o3 + "." + i4 + s2 + " <" + t5 + "." + (+o3 + 1) + ".0" : ">=" + t5 + "." + o3 + "." + i4 + s2 + " <" + (+t5 + 1) + ".0.0") : (n("no pr"), a2 = "0" === t5 ? "0" === o3 ? ">=" + t5 + "." + o3 + "." + i4 + " <" + t5 + "." + o3 + "." + (+i4 + 1) : ">=" + t5 + "." + o3 + "." + i4 + " <" + t5 + "." + (+o3 + 1) + ".0" : ">=" + t5 + "." + o3 + "." + i4 + " <" + (+t5 + 1) + ".0.0"), n("caret return", a2), a2;
                  });
                }(e6, r5);
              }).join(" ");
            }(e4, r4), n("caret", e4), e4 = function(e5, r5) {
              return e5.trim().split(/\s+/).map(function(e6) {
                return function(e7, r6) {
                  var t4 = r6 ? s[P] : s[V];
                  return e7.replace(t4, function(r7, t5, o3, i4, s2) {
                    var a2;
                    return n("tilde", e7, r7, t5, o3, i4, s2), ue(t5) ? a2 = "" : ue(o3) ? a2 = ">=" + t5 + ".0.0 <" + (+t5 + 1) + ".0.0" : ue(i4) ? a2 = ">=" + t5 + "." + o3 + ".0 <" + t5 + "." + (+o3 + 1) + ".0" : s2 ? (n("replaceTilde pr", s2), "-" !== s2.charAt(0) && (s2 = "-" + s2), a2 = ">=" + t5 + "." + o3 + "." + i4 + s2 + " <" + t5 + "." + (+o3 + 1) + ".0") : a2 = ">=" + t5 + "." + o3 + "." + i4 + " <" + t5 + "." + (+o3 + 1) + ".0", n("tilde return", a2), a2;
                  });
                }(e6, r5);
              }).join(" ");
            }(e4, r4), n("tildes", e4), e4 = function(e5, r5) {
              return n("replaceXRanges", e5, r5), e5.split(/\s+/).map(function(e6) {
                return function(e7, r6) {
                  e7 = e7.trim();
                  var t4 = r6 ? s[_] : s[I];
                  return e7.replace(t4, function(r7, t5, o3, i4, s2, a2) {
                    n("xRange", e7, r7, t5, o3, i4, s2, a2);
                    var u2 = ue(o3), c2 = u2 || ue(i4), p2 = c2 || ue(s2);
                    return "=" === t5 && p2 && (t5 = ""), u2 ? r7 = ">" === t5 || "<" === t5 ? "<0.0.0" : "*" : t5 && p2 ? (c2 && (i4 = 0), p2 && (s2 = 0), ">" === t5 ? (t5 = ">=", c2 ? (o3 = +o3 + 1, i4 = 0, s2 = 0) : p2 && (i4 = +i4 + 1, s2 = 0)) : "<=" === t5 && (t5 = "<", c2 ? o3 = +o3 + 1 : i4 = +i4 + 1), r7 = t5 + o3 + "." + i4 + "." + s2) : c2 ? r7 = ">=" + o3 + ".0.0 <" + (+o3 + 1) + ".0.0" : p2 && (r7 = ">=" + o3 + "." + i4 + ".0 <" + o3 + "." + (+i4 + 1) + ".0"), n("xRange return", r7), r7;
                  });
                }(e6, r5);
              }).join(" ");
            }(e4, r4), n("xrange", e4), e4 = function(e5, r5) {
              return n("replaceStars", e5, r5), e5.trim().replace(s[B], "");
            }(e4, r4), n("stars", e4), e4;
          }(e3, r3);
        }).join(" ").split(/\s+/);
        return this.loose && (i3 = i3.filter(function(e3) {
          return !!e3.match(o2);
        })), i3 = i3.map(function(e3) {
          return new ie(e3, r3);
        });
      }, ae.prototype.intersects = function(e2, r3) {
        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, r3);
              });
            });
          });
        });
      }, r2.toComparators = function(e2, r3) {
        return new ae(e2, r3).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 r3 = 0; r3 < this.set.length; r3++) if (pe(this.set[r3], e2)) return true;
        return false;
      }, r2.satisfies = fe, r2.maxSatisfying = function(e2, r3, t3) {
        var n2 = null, o2 = null;
        try {
          var i3 = new ae(r3, t3);
        } catch (e3) {
          return null;
        }
        return e2.forEach(function(e3) {
          i3.test(e3) && (n2 && -1 !== o2.compare(e3) || (o2 = new H(n2 = e3, t3)));
        }), n2;
      }, r2.minSatisfying = function(e2, r3, t3) {
        var n2 = null, o2 = null;
        try {
          var i3 = new ae(r3, t3);
        } catch (e3) {
          return null;
        }
        return e2.forEach(function(e3) {
          i3.test(e3) && (n2 && 1 !== o2.compare(e3) || (o2 = new H(n2 = e3, t3)));
        }), n2;
      }, r2.validRange = function(e2, r3) {
        try {
          return new ae(e2, r3).range || "*";
        } catch (e3) {
          return null;
        }
      }, r2.ltr = function(e2, r3, t3) {
        return le(e2, r3, "<", t3);
      }, r2.gtr = function(e2, r3, t3) {
        return le(e2, r3, ">", t3);
      }, r2.outside = le, r2.prerelease = function(e2, r3) {
        var t3 = F(e2, r3);
        return t3 && t3.prerelease.length ? t3.prerelease : null;
      }, r2.intersects = function(e2, r3, t3) {
        return e2 = new ae(e2, t3), r3 = new ae(r3, t3), e2.intersects(r3);
      }, r2.coerce = function(e2) {
        if (e2 instanceof H) return e2;
        if ("string" != typeof e2) return null;
        var r3 = e2.match(s[O]);
        return null == r3 ? null : F((r3[1] || "0") + "." + (r3[2] || "0") + "." + (r3[3] || "0"));
      };
    }).call(this, t(1));
  }, function(e, r2) {
    var t, n, o = e.exports = {};
    function i2() {
      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 === i2 || !t) && setTimeout) return t = setTimeout, setTimeout(e2, 0);
      try {
        return t(e2, 0);
      } catch (r3) {
        try {
          return t.call(null, e2, 0);
        } catch (r4) {
          return t.call(this, e2, 0);
        }
      }
    }
    !function() {
      try {
        t = "function" == typeof setTimeout ? setTimeout : i2;
      } catch (e2) {
        t = i2;
      }
      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 && h3());
    }
    function h3() {
      if (!p) {
        var e2 = a(l);
        p = true;
        for (var r3 = c.length; r3; ) {
          for (u = c, c = []; ++f < r3; ) u && u[f].run();
          f = -1, r3 = 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 (r4) {
            try {
              return n.call(null, e3);
            } catch (r5) {
              return n.call(this, e3);
            }
          }
        }(e2);
      }
    }
    function v(e2, r3) {
      this.fun = e2, this.array = r3;
    }
    function m() {
    }
    o.nextTick = function(e2) {
      var r3 = new Array(arguments.length - 1);
      if (arguments.length > 1) for (var t2 = 1; t2 < arguments.length; t2++) r3[t2 - 1] = arguments[t2];
      c.push(new v(e2, r3)), 1 !== c.length || p || a(h3);
    }, 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 = module.exports.SEMVER_SPEC_VERSION;
var parse2 = module.exports.parse;
var valid = module.exports.valid;
var coerce = module.exports.coerce;
var clean = module.exports.clean;
var inc = module.exports.inc;
var major = module.exports.major;
var minor = module.exports.minor;
var patch = module.exports.patch;
var prerelease = module.exports.prerelease;
var gt = module.exports.gt;
var gte = module.exports.gte;
var lt = module.exports.lt;
var lte = module.exports.lte;
var eq = module.exports.eq;
var neq = module.exports.neq;
var cmp3 = module.exports.cmp;
var compare = module.exports.compare;
var rcompare = module.exports.rcompare;
var compareIdentifiers = module.exports.compareIdentifiers;
var rcompareIdentifiers = module.exports.rcompareIdentifiers;
var compareBuild = module.exports.compareBuild;
var sort = module.exports.sort;
var rsort = module.exports.rsort;
var diff = module.exports.diff;
var validRange = module.exports.validRange;
var satisfies = module.exports.satisfies;
var maxSatisfying = module.exports.maxSatisfying;
var minSatisfying = module.exports.minSatisfying;
var minVersion = module.exports.minVersion;
var gtr = module.exports.gtr;
var ltr = module.exports.ltr;
var outside = module.exports.outside;
var intersects2 = module.exports.intersects;
var SemVer = module.exports.SemVer;
var Comparator = module.exports.Comparator;
var Range3 = module.exports.Range;

// out-build/vs/platform/extensionManagement/common/extensionManagementCLI.js
var notFound = (id2) => localize(1822, null, id2);
var useId = localize(1823, null, "ms-dotnettools.csharp");
var $bX = class $bX2 {
  constructor(a, b, d) {
    this.a = a;
    this.b = b;
    this.d = d;
  }
  get f() {
    return void 0;
  }
  async listExtensions(showVersions, category8, profileLocation) {
    let extensions = await this.b.getInstalled(1, profileLocation);
    const categories = $4z.map((c) => c.toLowerCase());
    if (category8 && category8 !== "") {
      if (categories.indexOf(category8.toLowerCase()) < 0) {
        this.a.info("Invalid category please enter a valid category. To list valid categories run --category without a category specified");
        return;
      }
      extensions = extensions.filter((e) => {
        if (e.manifest.categories) {
          const lowerCaseCategories = e.manifest.categories.map((c) => c.toLowerCase());
          return lowerCaseCategories.indexOf(category8.toLowerCase()) > -1;
        }
        return false;
      });
    } else if (category8 === "") {
      this.a.info("Possible Categories: ");
      categories.forEach((category9) => {
        this.a.info(category9);
      });
      return;
    }
    if (this.f) {
      this.a.info(localize(1824, null, this.f));
    }
    extensions = extensions.sort((e1, e2) => e1.identifier.id.localeCompare(e2.identifier.id));
    let lastId = void 0;
    for (const extension of extensions) {
      if (lastId !== extension.identifier.id) {
        lastId = extension.identifier.id;
        this.a.info(showVersions ? `${lastId}@${extension.manifest.version}` : lastId);
      }
    }
  }
  async installExtensions(extensions, builtinExtensions, installOptions, force) {
    const failed = [];
    try {
      if (extensions.length) {
        this.a.info(this.f ? localize(1825, null, this.f) : localize(1826, null));
      }
      const installVSIXInfos = [];
      const installExtensionInfos = [];
      const addInstallExtensionInfo = (id2, version2, isBuiltin) => {
        installExtensionInfos.push({ id: id2, version: version2 !== "prerelease" ? version2 : void 0, installOptions: { ...installOptions, isBuiltin, installPreReleaseVersion: version2 === "prerelease" || installOptions.installPreReleaseVersion } });
      };
      for (const extension of extensions) {
        if (extension instanceof URI) {
          installVSIXInfos.push({ vsix: extension, installOptions });
        } else {
          const [id2, version2] = $FA(extension);
          addInstallExtensionInfo(id2, version2, false);
        }
      }
      for (const extension of builtinExtensions) {
        if (extension instanceof URI) {
          installVSIXInfos.push({ vsix: extension, installOptions: { ...installOptions, isBuiltin: true, donotIncludePackAndDependencies: true } });
        } else {
          const [id2, version2] = $FA(extension);
          addInstallExtensionInfo(id2, version2, true);
        }
      }
      const installed = await this.b.getInstalled(void 0, installOptions.profileLocation);
      if (installVSIXInfos.length) {
        await Promise.all(installVSIXInfos.map(async ({ vsix, installOptions: installOptions2 }) => {
          try {
            await this.h(vsix, installOptions2, force, installed);
          } catch (err) {
            this.a.error(err);
            failed.push(vsix.toString());
          }
        }));
      }
      if (installExtensionInfos.length) {
        const failedGalleryExtensions = await this.g(installExtensionInfos, installed, force);
        failed.push(...failedGalleryExtensions);
      }
    } catch (error) {
      this.a.error(localize(1827, null, $qb(error)));
      throw error;
    }
    if (failed.length) {
      throw new Error(localize(1828, null, failed.join(", ")));
    }
  }
  async updateExtensions(profileLocation) {
    const installedExtensions = await this.b.getInstalled(1, profileLocation);
    const installedExtensionsQuery = [];
    for (const extension of installedExtensions) {
      if (!!extension.identifier.uuid) {
        installedExtensionsQuery.push({ ...extension.identifier, preRelease: extension.preRelease });
      }
    }
    this.a.trace(localize(1829, null, installedExtensionsQuery.length));
    const availableVersions = await this.d.getExtensions(installedExtensionsQuery, { compatible: true }, CancellationToken.None);
    const extensionsToUpdate = [];
    for (const newVersion of availableVersions) {
      for (const oldVersion of installedExtensions) {
        if ($DA(oldVersion.identifier, newVersion.identifier) && gt(newVersion.version, oldVersion.manifest.version)) {
          extensionsToUpdate.push({
            extension: newVersion,
            options: { operation: 3, installPreReleaseVersion: oldVersion.preRelease, profileLocation, isApplicationScoped: oldVersion.isApplicationScoped }
          });
        }
      }
    }
    if (!extensionsToUpdate.length) {
      this.a.info(localize(1830, null));
      return;
    }
    this.a.info(localize(1831, null, extensionsToUpdate.map((ext) => ext.extension.identifier.id).join(", ")));
    const installationResult = await this.b.installGalleryExtensions(extensionsToUpdate);
    for (const extensionResult of installationResult) {
      if (extensionResult.error) {
        this.a.error(localize(1832, null, extensionResult.identifier.id, $qb(extensionResult.error)));
      } else {
        this.a.info(localize(1833, null, extensionResult.identifier.id, extensionResult.local?.manifest.version));
      }
    }
  }
  async g(installExtensionInfos, installed, force) {
    installExtensionInfos = installExtensionInfos.filter(({ id: id2, version: version2 }) => {
      const installedExtension = installed.find((i2) => $DA(i2.identifier, { id: id2 }));
      if (installedExtension) {
        if (!force && (!version2 || version2 === "prerelease" && installedExtension.preRelease)) {
          this.a.info(localize(1834, null, id2, installedExtension.manifest.version, id2));
          return false;
        }
        if (version2 && installedExtension.manifest.version === version2) {
          this.a.info(localize(1835, null, `${id2}@${version2}`));
          return false;
        }
      }
      return true;
    });
    if (!installExtensionInfos.length) {
      return [];
    }
    const failed = [];
    const extensionsToInstall = [];
    const galleryExtensions = await this.j(installExtensionInfos);
    await Promise.all(installExtensionInfos.map(async ({ id: id2, version: version2, installOptions }) => {
      const gallery = galleryExtensions.get(id2.toLowerCase());
      if (!gallery) {
        this.a.error(`${notFound(version2 ? `${id2}@${version2}` : id2)}
${useId}`);
        failed.push(id2);
        return;
      }
      try {
        const manifest = await this.d.getManifest(gallery, CancellationToken.None);
        if (manifest && !this.k(manifest)) {
          return;
        }
      } catch (err) {
        this.a.error(err.message || err.stack || err);
        failed.push(id2);
        return;
      }
      const installedExtension = installed.find((e) => $DA(e.identifier, gallery.identifier));
      if (installedExtension) {
        if (gallery.version === installedExtension.manifest.version) {
          this.a.info(localize(1836, null, version2 ? `${id2}@${version2}` : id2));
          return;
        }
        this.a.info(localize(1837, null, id2, gallery.version));
      }
      if (installOptions.isBuiltin) {
        this.a.info(version2 ? localize(1838, null, id2, version2) : localize(1839, null, id2));
      } else {
        this.a.info(version2 ? localize(1840, null, id2, version2) : localize(1841, null, id2));
      }
      extensionsToInstall.push({
        extension: gallery,
        options: { ...installOptions, installGivenVersion: !!version2, isApplicationScoped: installOptions.isApplicationScoped || installedExtension?.isApplicationScoped }
      });
    }));
    if (extensionsToInstall.length) {
      const installationResult = await this.b.installGalleryExtensions(extensionsToInstall);
      for (const extensionResult of installationResult) {
        if (extensionResult.error) {
          this.a.error(localize(1842, null, extensionResult.identifier.id, $qb(extensionResult.error)));
          failed.push(extensionResult.identifier.id);
        } else {
          this.a.info(localize(1843, null, extensionResult.identifier.id, extensionResult.local?.manifest.version));
        }
      }
    }
    return failed;
  }
  async h(vsix, installOptions, force, installedExtensions) {
    const manifest = await this.b.getManifest(vsix);
    if (!manifest) {
      throw new Error("Invalid vsix");
    }
    const valid2 = await this.l(manifest, force, installOptions.profileLocation, installedExtensions);
    if (valid2) {
      try {
        await this.b.install(vsix, { ...installOptions, installGivenVersion: true });
        this.a.info(localize(1844, null, $sh(vsix)));
      } catch (error) {
        if ($kb(error)) {
          this.a.info(localize(1845, null, $sh(vsix)));
        } else {
          throw error;
        }
      }
    }
  }
  async j(extensions) {
    const galleryExtensions = /* @__PURE__ */ new Map();
    const preRelease = extensions.some((e) => e.installOptions.installPreReleaseVersion);
    const targetPlatform = await this.b.getTargetPlatform();
    const extensionInfos = [];
    for (const extension of extensions) {
      if ($dA.test(extension.id)) {
        extensionInfos.push({ ...extension, preRelease });
      }
    }
    if (extensionInfos.length) {
      const result = await this.d.getExtensions(extensionInfos, { targetPlatform }, CancellationToken.None);
      for (const extension of result) {
        galleryExtensions.set(extension.identifier.id.toLowerCase(), extension);
      }
    }
    return galleryExtensions;
  }
  k(_manifest) {
    return true;
  }
  async l(manifest, force, profileLocation, installedExtensions) {
    if (!force) {
      const extensionIdentifier = { id: $IA(manifest.publisher, manifest.name) };
      const newer = installedExtensions.find((local) => $DA(extensionIdentifier, local.identifier) && gt(local.manifest.version, manifest.version));
      if (newer) {
        this.a.info(localize(1846, null, newer.identifier.id, newer.manifest.version, manifest.version));
        return false;
      }
    }
    return this.k(manifest);
  }
  async uninstallExtensions(extensions, force, profileLocation) {
    const getId2 = async (extensionDescription) => {
      if (extensionDescription instanceof URI) {
        const manifest = await this.b.getManifest(extensionDescription);
        return $GA(manifest.publisher, manifest.name);
      }
      return extensionDescription;
    };
    const uninstalledExtensions = [];
    for (const extension of extensions) {
      const id2 = await getId2(extension);
      const installed = await this.b.getInstalled(void 0, profileLocation);
      const extensionsToUninstall = installed.filter((e) => $DA(e.identifier, { id: id2 }));
      if (!extensionsToUninstall.length) {
        throw new Error(`${this.m(id2)}
${useId}`);
      }
      if (extensionsToUninstall.some(
        (e) => e.type === 0
        /* ExtensionType.System */
      )) {
        this.a.info(localize(1847, null, id2));
        return;
      }
      if (!force && extensionsToUninstall.some((e) => e.isBuiltin)) {
        this.a.info(localize(1848, null, id2));
        return;
      }
      this.a.info(localize(1849, null, id2));
      for (const extensionToUninstall of extensionsToUninstall) {
        await this.b.uninstall(extensionToUninstall, { profileLocation });
        uninstalledExtensions.push(extensionToUninstall);
      }
      if (this.f) {
        this.a.info(localize(1850, null, id2, this.f));
      } else {
        this.a.info(localize(1851, null, id2));
      }
    }
  }
  async locateExtension(extensions) {
    const installed = await this.b.getInstalled();
    extensions.forEach((e) => {
      installed.forEach((i2) => {
        if (i2.identifier.id === e) {
          if (i2.location.scheme === Schemas.file) {
            this.a.info(i2.location.fsPath);
            return;
          }
        }
      });
    });
  }
  m(id2) {
    return this.f ? localize(1852, null, id2, this.f) : localize(1853, null, id2);
  }
};
$bX = __decorate([
  __param(1, $sA),
  __param(2, $pA)
], $bX);

// out-build/vs/workbench/api/browser/mainThreadCLICommands.js
$tn.registerCommand("_remoteCLI.openExternal", function(accessor, uri) {
  const openerService = accessor.get($O4);
  return openerService.open($zg(uri) ? uri : URI.revive(uri), { openExternal: true, allowTunneling: true });
});
$tn.registerCommand("_remoteCLI.windowOpen", function(accessor, toOpen, options3) {
  const commandService = accessor.get($sn);
  if (!toOpen.length) {
    return commandService.executeCommand("_files.newWindow", options3);
  }
  return commandService.executeCommand("_files.windowOpen", toOpen, options3);
});
$tn.registerCommand("_remoteCLI.getSystemStatus", function(accessor) {
  const commandService = accessor.get($sn);
  return commandService.executeCommand("_issues.getSystemStatus");
});
$tn.registerCommand("_remoteCLI.manageExtensions", async function(accessor, args2) {
  const instantiationService = accessor.get($Pk);
  const extensionManagementServerService = accessor.get($nzb);
  const remoteExtensionManagementService = extensionManagementServerService.remoteExtensionManagementServer?.extensionManagementService;
  if (!remoteExtensionManagementService) {
    return;
  }
  const lines = [];
  const logger2 = new class extends $Cn {
    m(level, message) {
      lines.push(message);
    }
  }();
  const childInstantiationService = instantiationService.createChild(new $Ok([$sA, remoteExtensionManagementService]));
  try {
    const cliService = childInstantiationService.createInstance(RemoteExtensionManagementCLI, logger2);
    if (args2.list) {
      await cliService.listExtensions(!!args2.list.showVersions, args2.list.category, void 0);
    } else {
      const revive = (inputs) => inputs.map((input) => $zg(input) ? input : URI.revive(input));
      if (Array.isArray(args2.install) && args2.install.length) {
        try {
          await cliService.installExtensions(revive(args2.install), [], { isMachineScoped: true }, !!args2.force);
        } catch (e) {
          lines.push(e.message);
        }
      }
      if (Array.isArray(args2.uninstall) && args2.uninstall.length) {
        try {
          await cliService.uninstallExtensions(revive(args2.uninstall), !!args2.force, void 0);
        } catch (e) {
          lines.push(e.message);
        }
      }
    }
    return lines.join("\n");
  } finally {
    childInstantiationService.dispose();
  }
});
var RemoteExtensionManagementCLI = class RemoteExtensionManagementCLI2 extends $bX {
  constructor(logger2, extensionManagementService, extensionGalleryService, labelService, envService, o) {
    super(logger2, extensionManagementService, extensionGalleryService);
    this.o = o;
    const remoteAuthority = envService.remoteAuthority;
    this.n = remoteAuthority ? labelService.getHostLabel(Schemas.vscodeRemote, remoteAuthority) : void 0;
  }
  get f() {
    return this.n;
  }
  k(manifest) {
    if (!this.o.canExecuteOnWorkspace(manifest) && !($r && this.o.canExecuteOnWeb(manifest))) {
      this.a.info(localize(2579, null, $GA(manifest.publisher, manifest.name)));
      return false;
    }
    return true;
  }
};
RemoteExtensionManagementCLI = __decorate([
  __param(1, $sA),
  __param(2, $pA),
  __param(3, $ZI),
  __param(4, $US),
  __param(5, $LCb)
], RemoteExtensionManagementCLI);

// out-build/vs/workbench/api/browser/mainThreadClipboard.js
var $qOb = class $qOb2 {
  constructor(_context, a) {
    this.a = a;
  }
  dispose() {
  }
  $readText() {
    return this.a.readText();
  }
  $writeText(value) {
    return this.a.writeText(value);
  }
};
$qOb = __decorate([
  $frb($xT.MainThreadClipboard),
  __param(1, $30)
], $qOb);

// out-build/vs/workbench/api/browser/mainThreadCommands.js
var $rOb = class $rOb2 {
  constructor(extHostContext, d, e) {
    this.d = d;
    this.e = e;
    this.a = new $_c();
    this.c = extHostContext.getProxy($yT.ExtHostCommands);
    this.b = $tn.registerCommand("_generateCommandsDocumentation", () => this.f());
  }
  dispose() {
    this.a.dispose();
    this.b.dispose();
  }
  async f() {
    const result = await this.c.$getContributedCommandMetadata();
    const commands2 = $tn.getCommands();
    for (const [id2, command4] of commands2) {
      if (command4.metadata) {
        result[id2] = command4.metadata;
      }
    }
    const all = [];
    for (const id2 in result) {
      all.push("`" + id2 + "` - " + _generateMarkdown(result[id2]));
    }
    console.log(all.join("\n"));
  }
  $registerCommand(id2) {
    this.a.set(id2, $tn.registerCommand(id2, (accessor, ...args2) => {
      return this.c.$executeContributedCommand(id2, ...args2).then((result) => {
        return $cu(result);
      });
    }));
  }
  $unregisterCommand(id2) {
    this.a.deleteAndDispose(id2);
  }
  $fireCommandActivationEvent(id2) {
    const activationEvent = `onCommand:${id2}`;
    if (!this.e.activationEventIsDone(activationEvent)) {
      this.e.activateByEvent(activationEvent);
    }
  }
  async $executeCommand(id2, args2, retry) {
    if (args2 instanceof $ES) {
      args2 = args2.value;
    }
    for (let i2 = 0; i2 < args2.length; i2++) {
      args2[i2] = $cu(args2[i2]);
    }
    if (retry && args2.length > 0 && !$tn.getCommand(id2)) {
      await this.e.activateByEvent(`onCommand:${id2}`);
      throw new Error("$executeCommand:retry");
    }
    return this.d.executeCommand(id2, ...args2);
  }
  $getCommands() {
    return Promise.resolve([...$tn.getCommands().keys()]);
  }
};
$rOb = __decorate([
  $frb($xT.MainThreadCommands),
  __param(1, $sn),
  __param(2, $wN)
], $rOb);
function _generateMarkdown(description) {
  if (typeof description === "string") {
    return description;
  } else {
    const descriptionString = $zg(description.description) ? description.description : description.description.original;
    const parts = [descriptionString];
    parts.push("\n\n");
    if (description.args) {
      for (const arg of description.args) {
        parts.push(`* _${arg.name}_ - ${arg.description || ""}
`);
      }
    }
    if (description.returns) {
      parts.push(`* _(returns)_ - ${description.returns}`);
    }
    parts.push("\n\n");
    return parts.join("");
  }
}

// out-build/vs/workbench/api/browser/mainThreadConfiguration.js
var $sOb = class $sOb2 {
  constructor(extHostContext, b, c, d) {
    this.b = b;
    this.c = c;
    this.d = d;
    const proxy = extHostContext.getProxy($yT.ExtHostConfiguration);
    proxy.$initializeConfiguration(this.f());
    this.a = c.onDidChangeConfiguration((e) => {
      proxy.$acceptConfigurationChanged(this.f(), e.change);
    });
  }
  f() {
    const configurationData = { ...this.c.getConfigurationData(), configurationScopes: [] };
    if (!this.d.isBuilt || this.d.isExtensionDevelopment) {
      configurationData.configurationScopes = $Wt();
    }
    return configurationData;
  }
  dispose() {
    this.a.dispose();
  }
  $updateConfigurationOption(target, key2, value, overrides, scopeToLanguage) {
    overrides = { resource: overrides?.resource ? URI.revive(overrides.resource) : void 0, overrideIdentifier: overrides?.overrideIdentifier };
    return this.g(target, key2, value, overrides, scopeToLanguage);
  }
  $removeConfigurationOption(target, key2, overrides, scopeToLanguage) {
    overrides = { resource: overrides?.resource ? URI.revive(overrides.resource) : void 0, overrideIdentifier: overrides?.overrideIdentifier };
    return this.g(target, key2, void 0, overrides, scopeToLanguage);
  }
  g(target, key2, value, overrides, scopeToLanguage) {
    target = target !== null && target !== void 0 ? target : this.i(key2, overrides);
    const configurationValue = this.c.inspect(key2, overrides);
    switch (target) {
      case 8:
        return this.h(key2, value, target, configurationValue?.memory?.override, overrides, scopeToLanguage);
      case 6:
        return this.h(key2, value, target, configurationValue?.workspaceFolder?.override, overrides, scopeToLanguage);
      case 5:
        return this.h(key2, value, target, configurationValue?.workspace?.override, overrides, scopeToLanguage);
      case 4:
        return this.h(key2, value, target, configurationValue?.userRemote?.override, overrides, scopeToLanguage);
      default:
        return this.h(key2, value, target, configurationValue?.userLocal?.override, overrides, scopeToLanguage);
    }
  }
  h(key2, value, configurationTarget, overriddenValue, overrides, scopeToLanguage) {
    overrides = scopeToLanguage === true ? overrides : scopeToLanguage === false ? { resource: overrides.resource } : overrides.overrideIdentifier && overriddenValue !== void 0 ? overrides : { resource: overrides.resource };
    return this.c.updateValue(key2, value, overrides, configurationTarget, { donotNotifyError: true });
  }
  i(key2, overrides) {
    if (overrides.resource && this.b.getWorkbenchState() === 3) {
      const configurationProperties = $Wn.as($Ht.Configuration).getConfigurationProperties();
      if (configurationProperties[key2] && (configurationProperties[key2].scope === 4 || configurationProperties[key2].scope === 5)) {
        return 6;
      }
    }
    return 5;
  }
};
$sOb = __decorate([
  $frb($xT.MainThreadConfiguration),
  __param(1, $Zk),
  __param(2, $kl),
  __param(3, $Xk)
], $sOb);

// out-build/vs/base/common/console.js
function $hy(entry) {
  const args2 = [];
  let stack;
  try {
    const parsedArguments = JSON.parse(entry.arguments);
    const stackArgument = parsedArguments[parsedArguments.length - 1];
    if (stackArgument && stackArgument.__$stack) {
      parsedArguments.pop();
      stack = stackArgument.__$stack;
    }
    args2.push(...parsedArguments);
  } catch (error) {
    args2.push("Unable to log remote console arguments", entry.arguments);
  }
  return { args: args2, stack };
}
function findFirstFrame(stack) {
  if (!stack) {
    return stack;
  }
  const newlineIndex = stack.indexOf("\n");
  if (newlineIndex === -1) {
    return stack;
  }
  return stack.substring(0, newlineIndex);
}
function log2(entry, label3) {
  const { args: args2, stack } = $hy(entry);
  const isOneStringArg = typeof args2[0] === "string" && args2.length === 1;
  let topFrame = findFirstFrame(stack);
  if (topFrame) {
    topFrame = `(${topFrame.trim()})`;
  }
  let consoleArgs = [];
  if (typeof args2[0] === "string") {
    if (topFrame && isOneStringArg) {
      consoleArgs = [`%c[${label3}] %c${args2[0]} %c${topFrame}`, color("blue"), color(""), color("grey")];
    } else {
      consoleArgs = [`%c[${label3}] %c${args2[0]}`, color("blue"), color(""), ...args2.slice(1)];
    }
  } else {
    consoleArgs = [`%c[${label3}]%`, color("blue"), ...args2];
  }
  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/workbench/services/extensions/common/remoteConsoleUtil.js
function $tOb(logService, entry, label3 = null) {
  const args2 = $hy(entry).args;
  let firstArg = args2.shift();
  if (typeof firstArg !== "string") {
    return;
  }
  if (!entry.severity) {
    entry.severity = "info";
  }
  if (label3) {
    if (!/^\[/.test(label3)) {
      label3 = `[${label3}]`;
    }
    if (!/ $/.test(label3)) {
      label3 = `${label3} `;
    }
    firstArg = label3 + firstArg;
  }
  switch (entry.severity) {
    case "log":
    case "info":
      logService.info(firstArg, ...args2);
      break;
    case "warn":
      logService.warn(firstArg, ...args2);
      break;
    case "error":
      logService.error(firstArg, ...args2);
      break;
  }
}
function $uOb(logService, entry, label3) {
  const args2 = $hy(entry).args;
  const firstArg = args2.shift();
  if (typeof firstArg !== "string" || entry.severity !== "error") {
    return;
  }
  if (!/^\[/.test(label3)) {
    label3 = `[${label3}]`;
  }
  if (!/ $/.test(label3)) {
    label3 = `${label3} `;
  }
  logService.error(label3 + firstArg, ...args2);
}

// out-build/vs/workbench/services/extensions/common/extensionDevOptions.js
function $vOb(environmentService) {
  const isExtensionDevHost = environmentService.isExtensionDevelopment;
  let debugOk = true;
  const extDevLocs = environmentService.extensionDevelopmentLocationURI;
  if (extDevLocs) {
    for (const x of extDevLocs) {
      if (x.scheme !== Schemas.file) {
        debugOk = false;
      }
    }
  }
  const isExtensionDevDebug = debugOk && typeof environmentService.debugExtensionHost.port === "number";
  const isExtensionDevDebugBrk = debugOk && !!environmentService.debugExtensionHost.break;
  const isExtensionDevTestFromCli = isExtensionDevHost && !!environmentService.extensionTestsLocationURI && !environmentService.debugExtensionHost.debugId;
  return {
    isExtensionDevHost,
    isExtensionDevDebug,
    isExtensionDevDebugBrk,
    isExtensionDevTestFromCli
  };
}

// out-build/vs/workbench/api/browser/mainThreadConsole.js
var $wOb = class $wOb2 {
  constructor(_extHostContext, b, c) {
    this.b = b;
    this.c = c;
    const devOpts = $vOb(this.b);
    this.a = devOpts.isExtensionDevTestFromCli;
  }
  dispose() {
  }
  $logExtensionHostMessage(entry) {
    if (this.a) {
      $tOb(this.c, entry);
    } else {
      $uOb(this.c, entry, "Extension Host");
      log2(entry, "Extension Host");
    }
  }
};
$wOb = __decorate([
  $frb($xT.MainThreadConsole),
  __param(1, $Xk),
  __param(2, $wn)
], $wOb);

// out-build/vs/workbench/contrib/debug/common/debug.js
var $TQ = "workbench.view.debug";
var $UQ = "workbench.debug.variablesView";
var $VQ = "workbench.debug.watchExpressionsView";
var $WQ = "workbench.debug.callStackView";
var $XQ = "workbench.debug.loadedScriptsView";
var $YQ = "workbench.debug.breakPointsView";
var $ZQ = "workbench.debug.disassemblyView";
var $1Q = "workbench.panel.repl";
var $2Q = "workbench.panel.repl.view";
var $3Q = new $nn("debugType", void 0, { type: "string", description: localize(6103, null) });
var $4Q = new $nn("debugConfigurationType", void 0, { type: "string", description: localize(6104, null) });
var $5Q = new $nn("debugState", "inactive", { type: "string", description: localize(6105, null) });
var $6Q = "debugUx";
var $7Q = new $nn($6Q, "default", { type: "string", description: localize(6106, null) });
var $8Q = new $nn("hasDebugged", false, { type: "boolean", description: localize(6107, null) });
var $9Q = new $nn("inDebugMode", false, { type: "boolean", description: localize(6108, null) });
var $0Q = new $nn("inDebugRepl", false, { type: "boolean", description: localize(6109, null) });
var $$Q = new $nn("breakpointWidgetVisible", false, { type: "boolean", description: localize(6110, null) });
var $_Q = new $nn("inBreakpointWidget", false, { type: "boolean", description: localize(6111, null) });
var $aR = new $nn("breakpointsFocused", true, { type: "boolean", description: localize(6112, null) });
var $bR = new $nn("watchExpressionsFocused", true, { type: "boolean", description: localize(6113, null) });
var $cR = new $nn("watchExpressionsExist", false, { type: "boolean", description: localize(6114, null) });
var $dR = new $nn("variablesFocused", true, { type: "boolean", description: localize(6115, null) });
var $eR = new $nn("expressionSelected", false, { type: "boolean", description: localize(6116, null) });
var $fR = new $nn("breakpointInputFocused", false, { type: "boolean", description: localize(6117, null) });
var $gR = new $nn("callStackItemType", void 0, { type: "string", description: localize(6118, null) });
var $hR = new $nn("callStackSessionIsAttach", false, { type: "boolean", description: localize(6119, null) });
var $iR = new $nn("callStackItemStopped", false, { type: "boolean", description: localize(6120, null) });
var $jR = new $nn("callStackSessionHasOneThread", false, { type: "boolean", description: localize(6121, null) });
var $kR = new $nn("callStackFocused", true, { type: "boolean", description: localize(6122, null) });
var $lR = new $nn("watchItemType", void 0, { type: "string", description: localize(6123, null) });
var $mR = new $nn("canViewMemory", void 0, { type: "boolean", description: localize(6124, null) });
var $nR = new $nn("breakpointItemType", void 0, { type: "string", description: localize(6125, null) });
var $oR = new $nn("breakpointItemBytes", void 0, { type: "boolean", description: localize(6126, null) });
var $pR = new $nn("breakpointHasModes", false, { type: "boolean", description: localize(6127, null) });
var $qR = new $nn("breakpointSupportsCondition", false, { type: "boolean", description: localize(6128, null) });
var $rR = new $nn("loadedScriptsSupported", false, { type: "boolean", description: localize(6129, null) });
var $sR = new $nn("loadedScriptsItemType", void 0, { type: "string", description: localize(6130, null) });
var $tR = new $nn("focusedSessionIsAttach", false, { type: "boolean", description: localize(6131, null) });
var $uR = new $nn("focusedSessionIsNoDebug", false, { type: "boolean", description: localize(6132, null) });
var $vR = new $nn("stepBackSupported", false, { type: "boolean", description: localize(6133, null) });
var $wR = new $nn("restartFrameSupported", false, { type: "boolean", description: localize(6134, null) });
var $xR = new $nn("stackFrameSupportsRestart", false, { type: "boolean", description: localize(6135, null) });
var $yR = new $nn("jumpToCursorSupported", false, { type: "boolean", description: localize(6136, null) });
var $zR = new $nn("stepIntoTargetsSupported", false, { type: "boolean", description: localize(6137, null) });
var $AR = new $nn("breakpointsExist", false, { type: "boolean", description: localize(6138, null) });
var $BR = new $nn("debuggersAvailable", false, { type: "boolean", description: localize(6139, null) });
var $CR = new $nn("debugExtensionAvailable", true, { type: "boolean", description: localize(6140, null) });
var $DR = new $nn("debugProtocolVariableMenuContext", void 0, { type: "string", description: localize(6141, null) });
var $ER = new $nn("debugSetVariableSupported", false, { type: "boolean", description: localize(6142, null) });
var $FR = new $nn("debugSetDataBreakpointAddressSupported", false, { type: "boolean", description: localize(6143, null) });
var $GR = new $nn("debugSetExpressionSupported", false, { type: "boolean", description: localize(6144, null) });
var $HR = new $nn("breakWhenValueChangesSupported", false, { type: "boolean", description: localize(6145, null) });
var $IR = new $nn("breakWhenValueIsAccessedSupported", false, { type: "boolean", description: localize(6146, null) });
var $JR = new $nn("breakWhenValueIsReadSupported", false, { type: "boolean", description: localize(6147, null) });
var $KR = new $nn("terminateDebuggeeSupported", false, { type: "boolean", description: localize(6148, null) });
var $LR = new $nn("suspendDebuggeeSupported", false, { type: "boolean", description: localize(6149, null) });
var $MR = new $nn("variableEvaluateNamePresent", false, { type: "boolean", description: localize(6150, null) });
var $NR = new $nn("variableIsReadonly", false, { type: "boolean", description: localize(6151, null) });
var $OR = new $nn("variableValue", false, { type: "string", description: localize(6152, null) });
var $PR = new $nn("variableType", false, { type: "string", description: localize(6153, null) });
var $QR = new $nn("variableInterfaces", false, { type: "array", description: localize(6154, null) });
var $RR = new $nn("variableName", false, { type: "string", description: localize(6155, null) });
var $SR = new $nn("variableLanguage", false, { type: "string", description: localize(6156, null) });
var $TR = new $nn("variableExtensionId", false, { type: "string", description: localize(6157, null) });
var $UR = new $nn("exceptionWidgetVisible", false, { type: "boolean", description: localize(6158, null) });
var $VR = new $nn("multiSessionRepl", false, { type: "boolean", description: localize(6159, null) });
var $WR = new $nn("multiSessionDebug", false, { type: "boolean", description: localize(6160, null) });
var $XR = new $nn("disassembleRequestSupported", false, { type: "boolean", description: localize(6161, null) });
var $YR = new $nn("disassemblyViewFocus", false, { type: "boolean", description: localize(6162, null) });
var $ZR = new $nn("languageSupportsDisassembleRequest", false, { type: "boolean", description: localize(6163, null) });
var $1R = new $nn("focusedStackFrameHasInstructionReference", false, { type: "boolean", description: localize(6164, null) });
var $2R = (debugType) => localize(6165, null, debugType);
var $3R = "editor.contrib.debug";
var $4R = "editor.contrib.breakpoint";
var $5R = "debug";
var $6R = {
  enum: ["neverOpen", "openOnSessionStart", "openOnFirstSessionStart"],
  default: "openOnFirstSessionStart",
  description: localize(6166, null)
};
var State5;
(function(State14) {
  State14[State14["Inactive"] = 0] = "Inactive";
  State14[State14["Initializing"] = 1] = "Initializing";
  State14[State14["Stopped"] = 2] = "Stopped";
  State14[State14["Running"] = 3] = "Running";
})(State5 || (State5 = {}));
function $7R(state) {
  switch (state) {
    case 1:
      return "initializing";
    case 2:
      return "stopped";
    case 3:
      return "running";
    default:
      return "inactive";
  }
}
var MemoryRangeType;
(function(MemoryRangeType2) {
  MemoryRangeType2[MemoryRangeType2["Valid"] = 0] = "Valid";
  MemoryRangeType2[MemoryRangeType2["Unreadable"] = 1] = "Unreadable";
  MemoryRangeType2[MemoryRangeType2["Error"] = 2] = "Error";
})(MemoryRangeType || (MemoryRangeType = {}));
var $8R = "vscode-debug-memory";
function $9R(frame) {
  const hint = frame.presentationHint ?? frame.source.presentationHint;
  return hint === "deemphasize" || hint === "subtle";
}
var DataBreakpointSetType;
(function(DataBreakpointSetType2) {
  DataBreakpointSetType2[DataBreakpointSetType2["Variable"] = 0] = "Variable";
  DataBreakpointSetType2[DataBreakpointSetType2["Address"] = 1] = "Address";
})(DataBreakpointSetType || (DataBreakpointSetType = {}));
var DebugConfigurationProviderTriggerKind;
(function(DebugConfigurationProviderTriggerKind2) {
  DebugConfigurationProviderTriggerKind2[DebugConfigurationProviderTriggerKind2["Initial"] = 1] = "Initial";
  DebugConfigurationProviderTriggerKind2[DebugConfigurationProviderTriggerKind2["Dynamic"] = 2] = "Dynamic";
})(DebugConfigurationProviderTriggerKind || (DebugConfigurationProviderTriggerKind = {}));
var DebuggerString;
(function(DebuggerString2) {
  DebuggerString2["UnverifiedBreakpoints"] = "unverifiedBreakpoints";
})(DebuggerString || (DebuggerString = {}));
var $0R = $Qk("debugService");
var BreakpointWidgetContext;
(function(BreakpointWidgetContext2) {
  BreakpointWidgetContext2[BreakpointWidgetContext2["CONDITION"] = 0] = "CONDITION";
  BreakpointWidgetContext2[BreakpointWidgetContext2["HIT_COUNT"] = 1] = "HIT_COUNT";
  BreakpointWidgetContext2[BreakpointWidgetContext2["LOG_MESSAGE"] = 2] = "LOG_MESSAGE";
  BreakpointWidgetContext2[BreakpointWidgetContext2["TRIGGER_POINT"] = 3] = "TRIGGER_POINT";
})(BreakpointWidgetContext || (BreakpointWidgetContext = {}));
var DebugVisualizationType;
(function(DebugVisualizationType2) {
  DebugVisualizationType2[DebugVisualizationType2["Command"] = 0] = "Command";
  DebugVisualizationType2[DebugVisualizationType2["Tree"] = 1] = "Tree";
})(DebugVisualizationType || (DebugVisualizationType = {}));
var DebugTreeItemCollapsibleState;
(function(DebugTreeItemCollapsibleState2) {
  DebugTreeItemCollapsibleState2[DebugTreeItemCollapsibleState2["None"] = 0] = "None";
  DebugTreeItemCollapsibleState2[DebugTreeItemCollapsibleState2["Collapsed"] = 1] = "Collapsed";
  DebugTreeItemCollapsibleState2[DebugTreeItemCollapsibleState2["Expanded"] = 2] = "Expanded";
})(DebugTreeItemCollapsibleState || (DebugTreeItemCollapsibleState = {}));
var IDebugVisualizationTreeItem;
(function(IDebugVisualizationTreeItem2) {
  IDebugVisualizationTreeItem2.deserialize = (v) => v;
  IDebugVisualizationTreeItem2.serialize = (item) => item;
})(IDebugVisualizationTreeItem || (IDebugVisualizationTreeItem = {}));
var IDebugVisualization;
(function(IDebugVisualization2) {
  IDebugVisualization2.deserialize = (v) => ({
    id: v.id,
    name: v.name,
    iconPath: v.iconPath && { light: URI.revive(v.iconPath.light), dark: URI.revive(v.iconPath.dark) },
    iconClass: v.iconClass,
    visualization: v.visualization
  });
  IDebugVisualization2.serialize = (visualizer) => visualizer;
})(IDebugVisualization || (IDebugVisualization = {}));

// out-build/vs/workbench/contrib/debug/common/abstractDebugAdapter.js
var $xOb = class {
  constructor() {
    this.f = /* @__PURE__ */ new Map();
    this.m = [];
    this.n = new $ze();
    this.o = new $ze();
    this.d = 1;
  }
  get onError() {
    return this.n.event;
  }
  get onExit() {
    return this.o.event;
  }
  onMessage(callback) {
    if (this.k) {
      this.n.fire(new Error(`attempt to set more than one 'Message' callback`));
    }
    this.k = callback;
  }
  onEvent(callback) {
    if (this.j) {
      this.n.fire(new Error(`attempt to set more than one 'Event' callback`));
    }
    this.j = callback;
  }
  onRequest(callback) {
    if (this.g) {
      this.n.fire(new Error(`attempt to set more than one 'Request' callback`));
    }
    this.g = callback;
  }
  sendResponse(response) {
    if (response.seq > 0) {
      this.n.fire(new Error(`attempt to send more than one response for command ${response.command}`));
    } else {
      this.u("response", response);
    }
  }
  sendRequest(command4, args2, clb, timeout) {
    const request = {
      command: command4
    };
    if (args2 && Object.keys(args2).length > 0) {
      request.arguments = args2;
    }
    this.u("request", request);
    if (typeof timeout === "number") {
      const timer = setTimeout(() => {
        clearTimeout(timer);
        const clb2 = this.f.get(request.seq);
        if (clb2) {
          this.f.delete(request.seq);
          const err = {
            type: "response",
            seq: 0,
            request_seq: request.seq,
            success: false,
            command: command4,
            message: localize(6102, null, timeout, command4)
          };
          clb2(err);
        }
      }, timeout);
    }
    if (clb) {
      this.f.set(request.seq, clb);
    }
    return request.seq;
  }
  acceptMessage(message) {
    if (this.k) {
      this.k(message);
    } else {
      this.m.push(message);
      if (this.m.length === 1) {
        this.s();
      }
    }
  }
  /**
   * Returns whether we should insert a timeout between processing messageA
   * and messageB. Artificially queueing protocol messages guarantees that any
   * microtasks for previous message finish before next message is processed.
   * This is essential ordering when using promises anywhere along the call path.
   *
   * For example, take the following, where `chooseAndSendGreeting` returns
   * a person name and then emits a greeting event:
   *
   * ```
   * let person: string;
   * adapter.onGreeting(() => console.log('hello', person));
   * person = await adapter.chooseAndSendGreeting();
   * ```
   *
   * Because the event is dispatched synchronously, it may fire before person
   * is assigned if they're processed in the same task. Inserting a task
   * boundary avoids this issue.
   */
  q(messageA, messageB) {
    return messageA.type !== "event" || messageB.type !== "event";
  }
  /**
   * Reads and dispatches items from the queue until it is empty.
   */
  async s() {
    let message;
    while (this.m.length) {
      if (!message || this.q(this.m[0], message)) {
        await $Wh(0);
      }
      message = this.m.shift();
      if (!message) {
        return;
      }
      switch (message.type) {
        case "event":
          this.j?.(message);
          break;
        case "request":
          this.g?.(message);
          break;
        case "response": {
          const response = message;
          const clb = this.f.get(response.request_seq);
          if (clb) {
            this.f.delete(response.request_seq);
            clb(response);
          }
          break;
        }
      }
    }
  }
  u(typ, message) {
    message.type = typ;
    message.seq = this.d++;
    this.sendMessage(message);
  }
  async w() {
    if (this.f.size === 0) {
      return Promise.resolve();
    }
    const pending = /* @__PURE__ */ new Map();
    this.f.forEach((value, key2) => pending.set(key2, value));
    await $Wh(500);
    pending.forEach((callback, request_seq) => {
      const err = {
        type: "response",
        seq: 0,
        request_seq,
        success: false,
        command: "canceled",
        message: "canceled"
      };
      callback(err);
      this.f.delete(request_seq);
    });
  }
  getPendingRequestIds() {
    return Array.from(this.f.keys());
  }
  dispose() {
    this.m = [];
  }
};

// out-build/vs/workbench/contrib/debug/common/debugUtils.js
var _formatPIIRegexp = /{([^}]+)}/g;
function $nP(value, excludePII, args2) {
  return value.replace(_formatPIIRegexp, function(match, group2) {
    if (excludePII && group2.length > 0 && group2[0] !== "_") {
      return match;
    }
    return args2 && args2.hasOwnProperty(group2) ? args2[group2] : match;
  });
}
function $oP(data) {
  const output = {};
  for (const key2 of Object.keys(data)) {
    if (!key2.startsWith("!")) {
      output[key2] = data[key2];
    }
  }
  return output;
}
function $pP(session) {
  return session.configuration.request === "attach" && !$qP(session) && (!session.parentSession || $pP(session.parentSession));
}
function $qP(session) {
  let type = session.configuration.type;
  if (!type) {
    return;
  }
  if (type === "vslsShare") {
    type = session.configuration.adapterProxy.configuration.type;
  }
  if ($1f(type, "extensionhost") || $1f(type, "pwa-extensionhost")) {
    return session;
  }
  return session.parentSession ? $qP(session.parentSession) : void 0;
}
function $rP(dbg) {
  return dbg.type && (dbg.label || dbg.program || dbg.runtime);
}
function $sP(lineContent, looseStart, looseEnd) {
  let matchingExpression = void 0;
  let startOffset = 0;
  const expression = /([^()\[\]{}<>\s+\-/%~#^;=|,`!]|\->)+/g;
  let result = null;
  while (result = expression.exec(lineContent)) {
    const start = result.index + 1;
    const end = start + result[0].length;
    if (start <= looseStart && end >= looseEnd) {
      matchingExpression = result[0];
      startOffset = start;
      break;
    }
  }
  if (matchingExpression) {
    const subExpression = /(\w|\p{L})+/gu;
    let subExpressionResult = null;
    while (subExpressionResult = subExpression.exec(matchingExpression)) {
      const subEnd = subExpressionResult.index + 1 + startOffset + subExpressionResult[0].length;
      if (subEnd >= looseEnd) {
        break;
      }
    }
    if (subExpressionResult) {
      matchingExpression = matchingExpression.substring(0, subExpression.lastIndex);
    }
  }
  return matchingExpression ? { start: startOffset, end: startOffset + matchingExpression.length - 1 } : { start: 0, end: 0 };
}
async function $tP(languageFeaturesService, model, position, token) {
  if (languageFeaturesService.evaluatableExpressionProvider.has(model)) {
    const supports = languageFeaturesService.evaluatableExpressionProvider.ordered(model);
    const results = $Mb(await Promise.all(supports.map(async (support) => {
      try {
        return await support.provideEvaluatableExpression(model, position, token ?? CancellationToken.None);
      } catch (err) {
        return void 0;
      }
    })));
    if (results.length > 0) {
      let matchingExpression = results[0].expression;
      const range = results[0].range;
      if (!matchingExpression) {
        const lineContent = model.getLineContent(position.lineNumber);
        matchingExpression = lineContent.substring(range.startColumn - 1, range.endColumn - 1);
      }
      return { range, matchingExpression };
    }
  } else {
    const lineContent = model.getLineContent(position.lineNumber);
    const { start, end } = $sP(lineContent, position.column, position.column);
    const matchingExpression = lineContent.substring(start - 1, end);
    return {
      matchingExpression,
      range: new $9C(position.lineNumber, start, position.lineNumber, start + matchingExpression.length)
    };
  }
  return null;
}
var _schemePattern2 = /^[a-zA-Z][a-zA-Z0-9\+\-\.]+:/;
function $uP(s) {
  return !!(s && s.match(_schemePattern2));
}
function stringToUri(source) {
  if (typeof source.path === "string") {
    if (typeof source.sourceReference === "number" && source.sourceReference > 0) {
    } else {
      if ($uP(source.path)) {
        return URI.parse(source.path);
      } else {
        if ($mc(source.path)) {
          return URI.file(source.path);
        } else {
        }
      }
    }
  }
  return source.path;
}
function uriToString(source) {
  if (typeof source.path === "object") {
    const u = URI.revive(source.path);
    if (u) {
      if (u.scheme === Schemas.file) {
        return u.fsPath;
      } else {
        return u.toString();
      }
    }
  }
  return source.path;
}
function $vP(message, toUri) {
  const fixPath = toUri ? stringToUri : uriToString;
  const msg = $Lv(message);
  convertPaths(msg, (toDA, source) => {
    if (toDA && source) {
      source.path = fixPath(source);
    }
  });
  return msg;
}
function $wP(message, toUri) {
  const fixPath = toUri ? stringToUri : uriToString;
  const msg = $Lv(message);
  convertPaths(msg, (toDA, source) => {
    if (!toDA && source) {
      source.path = fixPath(source);
    }
  });
  return msg;
}
function convertPaths(msg, fixSourcePath) {
  switch (msg.type) {
    case "event": {
      const event = msg;
      switch (event.event) {
        case "output":
          fixSourcePath(false, event.body.source);
          break;
        case "loadedSource":
          fixSourcePath(false, event.body.source);
          break;
        case "breakpoint":
          fixSourcePath(false, event.body.breakpoint.source);
          break;
        default:
          break;
      }
      break;
    }
    case "request": {
      const request = msg;
      switch (request.command) {
        case "setBreakpoints":
          fixSourcePath(true, request.arguments.source);
          break;
        case "breakpointLocations":
          fixSourcePath(true, request.arguments.source);
          break;
        case "source":
          fixSourcePath(true, request.arguments.source);
          break;
        case "gotoTargets":
          fixSourcePath(true, request.arguments.source);
          break;
        case "launchVSCode":
          request.arguments.args.forEach((arg) => fixSourcePath(false, arg));
          break;
        default:
          break;
      }
      break;
    }
    case "response": {
      const response = msg;
      if (response.success && response.body) {
        switch (response.command) {
          case "stackTrace":
            response.body.stackFrames.forEach((frame) => fixSourcePath(false, frame.source));
            break;
          case "loadedSources":
            response.body.sources.forEach((source) => fixSourcePath(false, source));
            break;
          case "scopes":
            response.body.scopes.forEach((scope) => fixSourcePath(false, scope.source));
            break;
          case "setFunctionBreakpoints":
            response.body.breakpoints.forEach((bp) => fixSourcePath(false, bp.source));
            break;
          case "setBreakpoints":
            response.body.breakpoints.forEach((bp) => fixSourcePath(false, bp.source));
            break;
          case "disassemble":
            {
              const di = response;
              di.body?.instructions.forEach((di2) => fixSourcePath(false, di2.location));
            }
            break;
          case "locations":
            fixSourcePath(false, response.body?.source);
            break;
          default:
            break;
        }
      }
      break;
    }
  }
}
function $xP(array2) {
  return array2.filter((config) => !config.presentation?.hidden).sort((first, second) => {
    if (!first.presentation) {
      if (!second.presentation) {
        return 0;
      }
      return 1;
    }
    if (!second.presentation) {
      return -1;
    }
    if (!first.presentation.group) {
      if (!second.presentation.group) {
        return compareOrders(first.presentation.order, second.presentation.order);
      }
      return 1;
    }
    if (!second.presentation.group) {
      return -1;
    }
    if (first.presentation.group !== second.presentation.group) {
      return first.presentation.group.localeCompare(second.presentation.group);
    }
    return compareOrders(first.presentation.order, second.presentation.order);
  });
}
function compareOrders(first, second) {
  if (typeof first !== "number") {
    if (typeof second !== "number") {
      return 0;
    }
    return 1;
  }
  if (typeof second !== "number") {
    return -1;
  }
  return first - second;
}
async function $yP(configurationService, editorService) {
  const saveBeforeStartConfig = configurationService.getValue("debug.saveBeforeStart", { overrideIdentifier: editorService.activeTextEditorLanguageId });
  if (saveBeforeStartConfig !== "none") {
    await editorService.saveAll();
    if (saveBeforeStartConfig === "allEditorsInActiveGroup") {
      const activeEditor = editorService.activeEditorPane;
      if (activeEditor && activeEditor.input.resource?.scheme === Schemas.untitled) {
        await editorService.save({ editor: activeEditor.input, groupId: activeEditor.group.id });
      }
    }
  }
  await configurationService.reloadConfiguration();
}
var $zP = (a, b) => !a || !b ? a === b : a.name === b.name && a.path === b.path && a.sourceReference === b.sourceReference;

// out-build/vs/workbench/contrib/debug/common/debugContext.js
function $EP(parentContext, variable, additionalContext = []) {
  const session = variable.getSession();
  const contextKeys = [
    [$DR.key, variable.variableMenuContext || ""],
    [$MR.key, !!variable.evaluateName],
    [$mR.key, !!session?.capabilities.supportsReadMemoryRequest && variable.memoryReference !== void 0],
    [$NR.key, !!variable.presentationHint?.attributes?.includes("readOnly") || variable.presentationHint?.lazy],
    [$3Q.key, session?.configuration.type],
    ...additionalContext
  ];
  return parentContext.createOverlay(contextKeys);
}

// out-build/vs/workbench/contrib/debug/common/debugSource.js
var $AP = localize(6235, null);
var $BP = class {
  constructor(raw_, sessionId, uriIdentityService, logService) {
    let path;
    if (raw_) {
      this.raw = raw_;
      path = this.raw.path || this.raw.name || "";
      this.available = true;
    } else {
      this.raw = { name: $AP };
      this.available = false;
      path = `${$5R}:${$AP}`;
    }
    this.uri = $CP(this.raw, path, sessionId, uriIdentityService, logService);
  }
  get name() {
    return this.raw.name || $rh(this.uri);
  }
  get origin() {
    return this.raw.origin;
  }
  get presentationHint() {
    return this.raw.presentationHint;
  }
  get reference() {
    return this.raw.sourceReference;
  }
  get inMemory() {
    return this.uri.scheme === $5R;
  }
  openInEditor(editorService, selection, preserveFocus, sideBySide, pinned) {
    return !this.available ? Promise.resolve(void 0) : editorService.openEditor({
      resource: this.uri,
      description: this.origin,
      options: {
        preserveFocus,
        selection,
        revealIfOpened: true,
        selectionRevealType: 1,
        pinned
      }
    }, sideBySide ? $oJ : $nJ);
  }
  static getEncodedDebugData(modelUri) {
    let path;
    let sourceReference;
    let sessionId;
    switch (modelUri.scheme) {
      case Schemas.file:
        path = $lc(modelUri.fsPath);
        break;
      case $5R:
        path = modelUri.path;
        if (modelUri.query) {
          const keyvalues = modelUri.query.split("&");
          for (const keyvalue of keyvalues) {
            const pair = keyvalue.split("=");
            if (pair.length === 2) {
              switch (pair[0]) {
                case "session":
                  sessionId = pair[1];
                  break;
                case "ref":
                  sourceReference = parseInt(pair[1]);
                  break;
              }
            }
          }
        }
        break;
      default:
        path = modelUri.toString();
        break;
    }
    return {
      name: $rh(modelUri),
      path,
      sourceReference,
      sessionId
    };
  }
};
function $CP(raw, path, sessionId, uriIdentityService, logService) {
  const _getUriFromSource = (path2) => {
    if (typeof raw.sourceReference === "number" && raw.sourceReference > 0) {
      return URI.from({
        scheme: $5R,
        path: path2?.replace(/^\/+/g, "/"),
        // #174054
        query: `session=${sessionId}&ref=${raw.sourceReference}`
      });
    }
    if (path2 && $uP(path2)) {
      return uriIdentityService.asCanonicalUri(URI.parse(path2));
    }
    if (path2 && $mc(path2)) {
      return uriIdentityService.asCanonicalUri(URI.file(path2));
    }
    return uriIdentityService.asCanonicalUri(URI.from({
      scheme: $5R,
      path: path2,
      query: `session=${sessionId}`
    }));
  };
  try {
    return _getUriFromSource(path);
  } catch (err) {
    logService.error("Invalid path from debug adapter: " + path);
    return _getUriFromSource("/invalidDebugSource");
  }
}

// out-build/vs/workbench/contrib/debug/common/disassemblyViewInput.js
var DisassemblyEditorIcon = $9r("disassembly-editor-label-icon", $6l.debug, localize(6236, null));
var $IP = class _$IP extends $nG {
  constructor() {
    super(...arguments);
    this.resource = void 0;
  }
  static {
    this.ID = "debug.disassemblyView.input";
  }
  get typeId() {
    return _$IP.ID;
  }
  static get instance() {
    if (!_$IP._instance || _$IP._instance.isDisposed()) {
      _$IP._instance = new _$IP();
    }
    return _$IP._instance;
  }
  getName() {
    return localize(6237, null);
  }
  getIcon() {
    return DisassemblyEditorIcon;
  }
  matches(other) {
    return other instanceof _$IP;
  }
};

// out-build/vs/workbench/contrib/debug/common/debugModel.js
var $JP = class _$JP {
  static {
    this.allValues = /* @__PURE__ */ new Map();
  }
  static {
    this.a = 100;
  }
  constructor(g, h3, j, k, namedVariables = 0, indexedVariables = 0, memoryReference = void 0, l = 0, presentationHint = void 0, valueLocationReference = void 0) {
    this.g = g;
    this.h = h3;
    this.j = j;
    this.k = k;
    this.namedVariables = namedVariables;
    this.indexedVariables = indexedVariables;
    this.memoryReference = memoryReference;
    this.l = l;
    this.presentationHint = presentationHint;
    this.valueLocationReference = valueLocationReference;
    this.valueChanged = false;
    this.b = "";
  }
  get reference() {
    return this.j;
  }
  set reference(value) {
    this.j = value;
    this.f = void 0;
  }
  async evaluateLazy() {
    if (typeof this.reference === "undefined") {
      return;
    }
    const response = await this.g.variables(this.reference, this.h, void 0, void 0, void 0);
    if (!response || !response.body || !response.body.variables || response.body.variables.length !== 1) {
      return;
    }
    const dummyVar = response.body.variables[0];
    this.reference = dummyVar.variablesReference;
    this.b = dummyVar.value;
    this.namedVariables = dummyVar.namedVariables;
    this.indexedVariables = dummyVar.indexedVariables;
    this.memoryReference = dummyVar.memoryReference;
    this.presentationHint = dummyVar.presentationHint;
    this.valueLocationReference = dummyVar.valueLocationReference;
    this.m(dummyVar);
  }
  m(response) {
  }
  getChildren() {
    if (!this.f) {
      this.f = this.n();
    }
    return this.f;
  }
  async n() {
    if (!this.hasChildren) {
      return [];
    }
    if (!this.q) {
      return this.o(void 0, void 0, void 0);
    }
    const children = this.namedVariables ? await this.o(void 0, void 0, "named") : [];
    let chunkSize = _$JP.a;
    while (!!this.indexedVariables && this.indexedVariables > chunkSize * _$JP.a) {
      chunkSize *= _$JP.a;
    }
    if (!!this.indexedVariables && this.indexedVariables > chunkSize) {
      const numberOfChunks = Math.ceil(this.indexedVariables / chunkSize);
      for (let i2 = 0; i2 < numberOfChunks; i2++) {
        const start = (this.l || 0) + i2 * chunkSize;
        const count = Math.min(chunkSize, this.indexedVariables - i2 * chunkSize);
        children.push(new $MP(this.g, this.h, this, this.reference, `[${start}..${start + count - 1}]`, "", "", void 0, count, void 0, { kind: "virtual" }, void 0, void 0, true, start));
      }
      return children;
    }
    const variables = await this.o(this.l, this.indexedVariables, "indexed");
    return children.concat(variables);
  }
  getId() {
    return this.k;
  }
  getSession() {
    return this.g;
  }
  get value() {
    return this.b;
  }
  get hasChildren() {
    return !!this.reference && this.reference > 0 && !this.presentationHint?.lazy;
  }
  async o(start, count, filter) {
    try {
      const response = await this.g.variables(this.reference || 0, this.h, filter, start, count);
      if (!response || !response.body || !response.body.variables) {
        return [];
      }
      const nameCount = /* @__PURE__ */ new Map();
      const vars = response.body.variables.filter((v) => !!v).map((v) => {
        if ($zg(v.value) && $zg(v.name) && typeof v.variablesReference === "number") {
          const count2 = nameCount.get(v.name) || 0;
          const idDuplicationIndex = count2 > 0 ? count2.toString() : "";
          nameCount.set(v.name, count2 + 1);
          return new $MP(this.g, this.h, this, v.variablesReference, v.name, v.evaluateName, v.value, v.namedVariables, v.indexedVariables, v.memoryReference, v.presentationHint, v.type, v.__vscodeVariableMenuContext, true, 0, idDuplicationIndex, v.declarationLocationReference, v.valueLocationReference);
        }
        return new $MP(this.g, this.h, this, 0, "", void 0, localize(6184, null), 0, 0, void 0, { kind: "virtual" }, void 0, void 0, false);
      });
      if (this.g.autoExpandLazyVariables) {
        await Promise.all(vars.map((v) => v.presentationHint?.lazy && v.evaluateLazy()));
      }
      return vars;
    } catch (e) {
      return [new $MP(this.g, this.h, this, 0, "", void 0, e.message, 0, 0, void 0, { kind: "virtual" }, void 0, void 0, false)];
    }
  }
  // The adapter explicitly sents the children count of an expression only if there are lots of children which should be chunked.
  get q() {
    return !!this.indexedVariables;
  }
  set value(value) {
    this.b = value;
    this.valueChanged = !!_$JP.allValues.get(this.getId()) && _$JP.allValues.get(this.getId()) !== $LP.DEFAULT_VALUE && _$JP.allValues.get(this.getId()) !== value;
    _$JP.allValues.set(this.getId(), value);
  }
  toString() {
    return this.value;
  }
  async evaluateExpression(expression, session, stackFrame, context, keepLazyVars = false, location3) {
    if (!session || !stackFrame && context !== "repl") {
      this.value = context === "repl" ? localize(6185, null) : $LP.DEFAULT_VALUE;
      this.reference = 0;
      return false;
    }
    this.g = session;
    try {
      const response = await session.evaluate(expression, stackFrame ? stackFrame.frameId : void 0, context, location3);
      if (response && response.body) {
        this.value = response.body.result || "";
        this.reference = response.body.variablesReference;
        this.namedVariables = response.body.namedVariables;
        this.indexedVariables = response.body.indexedVariables;
        this.memoryReference = response.body.memoryReference;
        this.type = response.body.type || this.type;
        this.presentationHint = response.body.presentationHint;
        this.valueLocationReference = response.body.valueLocationReference;
        if (!keepLazyVars && response.body.presentationHint?.lazy) {
          await this.evaluateLazy();
        }
        return true;
      }
      return false;
    } catch (e) {
      this.value = e.message || "";
      this.reference = 0;
      return false;
    }
  }
};
function handleSetResponse(expression, response) {
  if (response && response.body) {
    expression.value = response.body.value || "";
    expression.type = response.body.type || expression.type;
    expression.reference = response.body.variablesReference;
    expression.namedVariables = response.body.namedVariables;
    expression.indexedVariables = response.body.indexedVariables;
  }
}
var $KP = class {
  evaluateLazy() {
    return Promise.resolve();
  }
  getChildren() {
    return this.f.getVisualizedChildren(this.b, this.treeId, this.treeItem.id);
  }
  getId() {
    return this.a;
  }
  get name() {
    return this.treeItem.label;
  }
  get value() {
    return this.treeItem.description || "";
  }
  get hasChildren() {
    return this.treeItem.collapsibleState !== 0;
  }
  constructor(b, f, treeId, treeItem, original) {
    this.b = b;
    this.f = f;
    this.treeId = treeId;
    this.treeItem = treeItem;
    this.original = original;
    this.a = $ps();
  }
  getSession() {
    return this.b;
  }
  /** Edits the value, sets the {@link errorMessage} and returns false if unsuccessful */
  async edit(newValue) {
    try {
      await this.f.editTreeItem(this.treeId, this.treeItem, newValue);
      return true;
    } catch (e) {
      this.errorMessage = e.message;
      return false;
    }
  }
};
var $LP = class _$LP extends $JP {
  static {
    this.DEFAULT_VALUE = localize(6186, null);
  }
  constructor(name, id2 = $ps()) {
    super(void 0, void 0, 0, id2);
    this.name = name;
    this.t = new $ze();
    this.onDidChangeValue = this.t.event;
    this.available = false;
    if (name) {
      this.value = _$LP.DEFAULT_VALUE;
    }
  }
  async evaluate(session, stackFrame, context, keepLazyVars, location3) {
    const hadDefaultValue = this.value === _$LP.DEFAULT_VALUE;
    this.available = await this.evaluateExpression(this.name, session, stackFrame, context, keepLazyVars, location3);
    if (hadDefaultValue || this.valueChanged) {
      this.t.fire(this);
    }
  }
  toString() {
    return `${this.name}
${this.value}`;
  }
  async setExpression(value, stackFrame) {
    if (!this.g) {
      return;
    }
    const response = await this.g.setExpression(stackFrame.frameId, this.name, value);
    handleSetResponse(this, response);
  }
};
var $MP = class extends $JP {
  constructor(session, threadId, parent, reference, name, evaluateName, value, namedVariables, indexedVariables, memoryReference, presentationHint, type = void 0, variableMenuContext = void 0, available = true, startOfVariables = 0, idDuplicationIndex = "", declarationLocationReference = void 0, valueLocationReference = void 0) {
    super(session, threadId, reference, `variable:${parent.getId()}:${name}:${idDuplicationIndex}`, namedVariables, indexedVariables, memoryReference, startOfVariables, presentationHint, valueLocationReference);
    this.parent = parent;
    this.name = name;
    this.evaluateName = evaluateName;
    this.variableMenuContext = variableMenuContext;
    this.available = available;
    this.declarationLocationReference = declarationLocationReference;
    this.value = value || "";
    this.type = type;
  }
  getThreadId() {
    return this.h;
  }
  async setVariable(value, stackFrame) {
    if (!this.g) {
      return;
    }
    try {
      if (this.g.capabilities.supportsSetExpression && !this.g.capabilities.supportsSetVariable && this.evaluateName) {
        return this.setExpression(value, stackFrame);
      }
      const response = await this.g.setVariable(this.parent.reference, this.name, value);
      handleSetResponse(this, response);
    } catch (err) {
      this.errorMessage = err.message;
    }
  }
  async setExpression(value, stackFrame) {
    if (!this.g || !this.evaluateName) {
      return;
    }
    const response = await this.g.setExpression(stackFrame.frameId, this.evaluateName, value);
    handleSetResponse(this, response);
  }
  toString() {
    return this.name ? `${this.name}: ${this.value}` : this.value;
  }
  m(response) {
    this.evaluateName = response.evaluateName;
  }
  toDebugProtocolObject() {
    return {
      name: this.name,
      variablesReference: this.reference || 0,
      memoryReference: this.memoryReference,
      value: this.value,
      evaluateName: this.evaluateName
    };
  }
};
var $NP = class extends $JP {
  constructor(stackFrame, id2, name, reference, expensive, namedVariables, indexedVariables, range) {
    super(stackFrame.thread.session, stackFrame.thread.threadId, reference, `scope:${name}:${id2}`, namedVariables, indexedVariables);
    this.stackFrame = stackFrame;
    this.name = name;
    this.expensive = expensive;
    this.range = range;
  }
  toString() {
    return this.name;
  }
  toDebugProtocolObject() {
    return {
      name: this.name,
      variablesReference: this.reference || 0,
      expensive: this.expensive
    };
  }
};
var $OP = class extends $NP {
  constructor(stackFrame, index, message) {
    super(stackFrame, index, message, 0, false);
  }
  toString() {
    return this.name;
  }
};
var $PP = class {
  constructor(thread, frameId, source, name, presentationHint, range, b, canRestart, instructionPointerReference) {
    this.thread = thread;
    this.frameId = frameId;
    this.source = source;
    this.name = name;
    this.presentationHint = presentationHint;
    this.range = range;
    this.b = b;
    this.canRestart = canRestart;
    this.instructionPointerReference = instructionPointerReference;
  }
  getId() {
    return `stackframe:${this.thread.getId()}:${this.b}:${this.source.name}`;
  }
  getScopes() {
    if (!this.a) {
      this.a = this.thread.session.scopes(this.frameId, this.thread.threadId).then((response) => {
        if (!response || !response.body || !response.body.scopes) {
          return [];
        }
        const usedIds = /* @__PURE__ */ new Set();
        return response.body.scopes.map((rs) => {
          let id2 = 0;
          do {
            id2 = $1i(`${rs.name}:${rs.line}:${rs.column}`, id2);
          } while (usedIds.has(id2));
          usedIds.add(id2);
          return new $NP(this, id2, rs.name, rs.variablesReference, rs.expensive, rs.namedVariables, rs.indexedVariables, rs.line && rs.column && rs.endLine && rs.endColumn ? new $9C(rs.line, rs.column, rs.endLine, rs.endColumn) : void 0);
        });
      }, (err) => [new $OP(this, 0, err.message)]);
    }
    return this.a;
  }
  async getMostSpecificScopes(range) {
    const scopes = await this.getScopes();
    const nonExpensiveScopes = scopes.filter((s) => !s.expensive);
    const haveRangeInfo = nonExpensiveScopes.some((s) => !!s.range);
    if (!haveRangeInfo) {
      return nonExpensiveScopes;
    }
    const scopesContainingRange = nonExpensiveScopes.filter((scope) => scope.range && $9C.containsRange(scope.range, range)).sort((first, second) => first.range.endLineNumber - first.range.startLineNumber - (second.range.endLineNumber - second.range.startLineNumber));
    return scopesContainingRange.length ? scopesContainingRange : nonExpensiveScopes;
  }
  restart() {
    return this.thread.session.restartFrame(this.frameId, this.thread.threadId);
  }
  forgetScopes() {
    this.a = void 0;
  }
  toString() {
    const lineNumberToString = typeof this.range.startLineNumber === "number" ? `:${this.range.startLineNumber}` : "";
    const sourceToString = `${this.source.inMemory ? this.source.name : this.source.uri.fsPath}${lineNumberToString}`;
    return sourceToString === $AP ? this.name : `${this.name} (${sourceToString})`;
  }
  async openInEditor(editorService, preserveFocus, sideBySide, pinned) {
    const threadStopReason = this.thread.stoppedDetails?.reason;
    if (this.instructionPointerReference && (threadStopReason === "instruction breakpoint" || threadStopReason === "step" && this.thread.lastSteppingGranularity === "instruction" || editorService.activeEditor instanceof $IP)) {
      return editorService.openEditor($IP.instance, { pinned: true, revealIfOpened: true });
    }
    if (this.source.available) {
      return this.source.openInEditor(editorService, this.range, preserveFocus, sideBySide, pinned);
    }
    return void 0;
  }
  equals(other) {
    return this.name === other.name && other.thread === this.thread && this.frameId === other.frameId && other.source === this.source && $9C.equalsRange(this.range, other.range);
  }
};
var KEEP_SUBTLE_FRAME_AT_TOP_REASONS = ["breakpoint", "step", "function breakpoint"];
var $QP = class {
  constructor(session, name, threadId) {
    this.session = session;
    this.name = name;
    this.threadId = threadId;
    this.f = [];
    this.reachedEndOfCallStack = false;
    this.a = [];
    this.b = [];
    this.stopped = false;
  }
  getId() {
    return `thread:${this.session.getId()}:${this.threadId}`;
  }
  clearCallStack() {
    if (this.a.length) {
      this.b = this.a;
    }
    this.a = [];
    this.f.forEach((c) => c.dispose(true));
    this.f = [];
  }
  getCallStack() {
    return this.a;
  }
  getStaleCallStack() {
    return this.b;
  }
  getTopStackFrame() {
    const callStack = this.getCallStack();
    const stopReason = this.stoppedDetails?.reason;
    const firstAvailableStackFrame = callStack.find((sf) => !!((stopReason === "instruction breakpoint" || stopReason === "step" && this.lastSteppingGranularity === "instruction") && sf.instructionPointerReference || sf.source && sf.source.available && (KEEP_SUBTLE_FRAME_AT_TOP_REASONS.includes(stopReason) || !$9R(sf))));
    return firstAvailableStackFrame;
  }
  get stateLabel() {
    if (this.stoppedDetails) {
      return this.stoppedDetails.description || (this.stoppedDetails.reason ? localize(6187, null, this.stoppedDetails.reason) : localize(6188, null));
    }
    return localize(6189, null);
  }
  /**
   * Queries the debug adapter for the callstack and returns a promise
   * which completes once the call stack has been retrieved.
   * If the thread is not stopped, it returns a promise to an empty array.
   * Only fetches the first stack frame for performance reasons. Calling this method consecutive times
   * gets the remainder of the call stack.
   */
  async fetchCallStack(levels = 20) {
    if (this.stopped) {
      const start = this.a.length;
      const callStack = await this.g(start, levels);
      this.reachedEndOfCallStack = callStack.length < levels;
      if (start < this.a.length) {
        this.a.splice(start, this.a.length - start);
      }
      this.a = this.a.concat(callStack || []);
      if (typeof this.stoppedDetails?.totalFrames === "number" && this.stoppedDetails.totalFrames === this.a.length) {
        this.reachedEndOfCallStack = true;
      }
    }
  }
  async g(startFrame, levels) {
    try {
      const tokenSource = new $ad();
      this.f.push(tokenSource);
      const response = await this.session.stackTrace(this.threadId, startFrame, levels, tokenSource.token);
      if (!response || !response.body || tokenSource.token.isCancellationRequested) {
        return [];
      }
      if (this.stoppedDetails) {
        this.stoppedDetails.totalFrames = response.body.totalFrames;
      }
      return response.body.stackFrames.map((rsf, index) => {
        const source = this.session.getSource(rsf.source);
        return new $PP(this, rsf.id, source, rsf.name, rsf.presentationHint, new $9C(rsf.line, rsf.column, rsf.endLine || rsf.line, rsf.endColumn || rsf.column), startFrame + index, typeof rsf.canRestart === "boolean" ? rsf.canRestart : true, rsf.instructionPointerReference);
      });
    } catch (err) {
      if (this.stoppedDetails) {
        this.stoppedDetails.framesErrorMessage = err.message;
      }
      return [];
    }
  }
  /**
   * Returns exception info promise if the exception was thrown, otherwise undefined
   */
  get exceptionInfo() {
    if (this.stoppedDetails && this.stoppedDetails.reason === "exception") {
      if (this.session.capabilities.supportsExceptionInfoRequest) {
        return this.session.exceptionInfo(this.threadId);
      }
      return Promise.resolve({
        description: this.stoppedDetails.text,
        breakMode: null
      });
    }
    return Promise.resolve(void 0);
  }
  next(granularity) {
    return this.session.next(this.threadId, granularity);
  }
  stepIn(granularity) {
    return this.session.stepIn(this.threadId, void 0, granularity);
  }
  stepOut(granularity) {
    return this.session.stepOut(this.threadId, granularity);
  }
  stepBack(granularity) {
    return this.session.stepBack(this.threadId, granularity);
  }
  continue() {
    return this.session.continue(this.threadId);
  }
  pause() {
    return this.session.pause(this.threadId);
  }
  terminate() {
    return this.session.terminateThreads([this.threadId]);
  }
  reverseContinue() {
    return this.session.reverseContinue(this.threadId);
  }
};
var $RP = (sessionId, memoryReference, range, displayName = "memory") => {
  return URI.from({
    scheme: $8R,
    authority: sessionId,
    path: "/" + encodeURIComponent(memoryReference) + `/${encodeURIComponent(displayName)}.bin`,
    query: range ? `?range=${range.fromOffset}:${range.toOffset}` : void 0
  });
};
var $SP = class extends $3c {
  constructor(b, f) {
    super();
    this.b = b;
    this.f = f;
    this.a = this.B(new $ze());
    this.onDidInvalidate = this.a.event;
    this.writable = !!this.f.capabilities.supportsWriteMemoryRequest;
    this.B(f.onDidInvalidateMemory((e) => {
      if (e.body.memoryReference === b) {
        this.g(e.body.offset, e.body.count - e.body.offset);
      }
    }));
  }
  async read(fromOffset, toOffset) {
    const length = toOffset - fromOffset;
    const offset = fromOffset;
    const result = await this.f.readMemory(this.b, offset, length);
    if (result === void 0 || !result.body?.data) {
      return [{ type: 1, offset, length }];
    }
    let data;
    try {
      data = $Vi(result.body.data);
    } catch {
      return [{ type: 2, offset, length, error: "Invalid base64 data from debug adapter" }];
    }
    const unreadable = result.body.unreadableBytes || 0;
    const dataLength = length - unreadable;
    if (data.byteLength < dataLength) {
      const pad = $Ci.alloc(dataLength - data.byteLength);
      pad.buffer.fill(0);
      data = $Ci.concat([data, pad], dataLength);
    } else if (data.byteLength > dataLength) {
      data = data.slice(0, dataLength);
    }
    if (!unreadable) {
      return [{ type: 0, offset, length, data }];
    }
    return [
      { type: 0, offset, length: dataLength, data },
      { type: 1, offset: offset + dataLength, length: unreadable }
    ];
  }
  async write(offset, data) {
    const result = await this.f.writeMemory(this.b, offset, $Wi(data), true);
    const written = result?.body?.bytesWritten ?? data.byteLength;
    this.g(offset, offset + written);
    return written;
  }
  dispose() {
    super.dispose();
  }
  g(fromOffset, toOffset) {
    this.a.fire({ fromOffset, toOffset });
  }
};
var $TP = class {
  constructor(enabled, a) {
    this.enabled = enabled;
    this.a = a;
  }
  getId() {
    return this.a;
  }
};
function toBreakpointSessionData(data, capabilities) {
  return $Ov({
    supportsConditionalBreakpoints: !!capabilities.supportsConditionalBreakpoints,
    supportsHitConditionalBreakpoints: !!capabilities.supportsHitConditionalBreakpoints,
    supportsLogPoints: !!capabilities.supportsLogPoints,
    supportsFunctionBreakpoints: !!capabilities.supportsFunctionBreakpoints,
    supportsDataBreakpoints: !!capabilities.supportsDataBreakpoints,
    supportsInstructionBreakpoints: !!capabilities.supportsInstructionBreakpoints
  }, data);
}
var $UP = class extends $TP {
  constructor(id2, opts) {
    super(opts.enabled ?? true, id2);
    this.b = /* @__PURE__ */ new Map();
    this.condition = opts.condition;
    this.hitCondition = opts.hitCondition;
    this.logMessage = opts.logMessage;
    this.mode = opts.mode;
    this.modeLabel = opts.modeLabel;
  }
  setSessionData(sessionId, data) {
    if (!data) {
      this.b.delete(sessionId);
    } else {
      data.sessionId = sessionId;
      this.b.set(sessionId, data);
    }
    const allData = Array.from(this.b.values());
    const verifiedData = $Rb(allData.filter((d) => d.verified), (d) => `${d.line}:${d.column}`);
    if (verifiedData.length) {
      this.f = verifiedData.length === 1 ? verifiedData[0] : void 0;
    } else {
      this.f = allData.length ? allData[0] : void 0;
    }
  }
  get message() {
    if (!this.f) {
      return void 0;
    }
    return this.f.message;
  }
  get verified() {
    return this.f ? this.f.verified : true;
  }
  get sessionsThatVerified() {
    const sessionIds = [];
    for (const [sessionId, data] of this.b) {
      if (data.verified) {
        sessionIds.push(sessionId);
      }
    }
    return sessionIds;
  }
  getIdFromAdapter(sessionId) {
    const data = this.b.get(sessionId);
    return data ? data.id : void 0;
  }
  getDebugProtocolBreakpoint(sessionId) {
    const data = this.b.get(sessionId);
    if (data) {
      const bp = {
        id: data.id,
        verified: data.verified,
        message: data.message,
        source: data.source,
        line: data.line,
        column: data.column,
        endLine: data.endLine,
        endColumn: data.endColumn,
        instructionReference: data.instructionReference,
        offset: data.offset
      };
      return bp;
    }
    return void 0;
  }
  toJSON() {
    return {
      id: this.getId(),
      enabled: this.enabled,
      condition: this.condition,
      hitCondition: this.hitCondition,
      logMessage: this.logMessage,
      mode: this.mode,
      modeLabel: this.modeLabel
    };
  }
};
var $VP = class extends $UP {
  constructor(opts, m, n, o, id2 = $ps()) {
    super(id2, opts);
    this.m = m;
    this.n = n;
    this.o = o;
    this.h = opts.uri;
    this.k = opts.lineNumber;
    this.l = opts.column;
    this.j = opts.adapterData;
    this.triggeredBy = opts.triggeredBy;
  }
  toDAP() {
    return {
      line: this.sessionAgnosticData.lineNumber,
      column: this.sessionAgnosticData.column,
      condition: this.condition,
      hitCondition: this.hitCondition,
      logMessage: this.logMessage,
      mode: this.mode
    };
  }
  get originalUri() {
    return this.h;
  }
  get lineNumber() {
    return this.verified && this.f && typeof this.f.line === "number" ? this.f.line : this.k;
  }
  get verified() {
    if (this.f) {
      return this.f.verified && !this.m.isDirty(this.h);
    }
    return true;
  }
  get pending() {
    if (this.f) {
      return false;
    }
    return this.triggeredBy !== void 0;
  }
  get uri() {
    return this.verified && this.f && this.f.source ? $CP(this.f.source, this.f.source.path, this.f.sessionId, this.n, this.o) : this.h;
  }
  get column() {
    return this.verified && this.f && typeof this.f.column === "number" ? this.f.column : this.l;
  }
  get message() {
    if (this.m.isDirty(this.uri)) {
      return localize(6190, null);
    }
    return super.message;
  }
  get adapterData() {
    return this.f && this.f.source && this.f.source.adapterData ? this.f.source.adapterData : this.j;
  }
  get endLineNumber() {
    return this.verified && this.f ? this.f.endLine : void 0;
  }
  get endColumn() {
    return this.verified && this.f ? this.f.endColumn : void 0;
  }
  get sessionAgnosticData() {
    return {
      lineNumber: this.k,
      column: this.l
    };
  }
  get supported() {
    if (!this.f) {
      return true;
    }
    if (this.logMessage && !this.f.supportsLogPoints) {
      return false;
    }
    if (this.condition && !this.f.supportsConditionalBreakpoints) {
      return false;
    }
    if (this.hitCondition && !this.f.supportsHitConditionalBreakpoints) {
      return false;
    }
    return true;
  }
  setSessionData(sessionId, data) {
    super.setSessionData(sessionId, data);
    if (!this.j) {
      this.j = this.adapterData;
    }
  }
  toJSON() {
    return {
      ...super.toJSON(),
      uri: this.h,
      lineNumber: this.k,
      column: this.l,
      adapterData: this.adapterData,
      triggeredBy: this.triggeredBy
    };
  }
  toString() {
    return `${$rh(this.uri)} ${this.lineNumber}`;
  }
  setSessionDidTrigger(sessionId, didTrigger = true) {
    if (didTrigger) {
      this.g ??= /* @__PURE__ */ new Set();
      this.g.add(sessionId);
    } else {
      this.g?.delete(sessionId);
    }
  }
  getSessionDidTrigger(sessionId) {
    return !!this.g?.has(sessionId);
  }
  update(data) {
    if (data.hasOwnProperty("lineNumber") && !$Ig(data.lineNumber)) {
      this.k = data.lineNumber;
    }
    if (data.hasOwnProperty("column")) {
      this.l = data.column;
    }
    if (data.hasOwnProperty("condition")) {
      this.condition = data.condition;
    }
    if (data.hasOwnProperty("hitCondition")) {
      this.hitCondition = data.hitCondition;
    }
    if (data.hasOwnProperty("logMessage")) {
      this.logMessage = data.logMessage;
    }
    if (data.hasOwnProperty("mode")) {
      this.mode = data.mode;
      this.modeLabel = data.modeLabel;
    }
    if (data.hasOwnProperty("triggeredBy")) {
      this.triggeredBy = data.triggeredBy;
      this.g = void 0;
    }
  }
};
var $WP = class extends $UP {
  constructor(opts, id2 = $ps()) {
    super(id2, opts);
    this.name = opts.name;
  }
  toDAP() {
    return {
      name: this.name,
      condition: this.condition,
      hitCondition: this.hitCondition
    };
  }
  toJSON() {
    return {
      ...super.toJSON(),
      name: this.name
    };
  }
  get supported() {
    if (!this.f) {
      return true;
    }
    return this.f.supportsFunctionBreakpoints;
  }
  toString() {
    return this.name;
  }
};
var $XP = class extends $UP {
  constructor(opts, id2 = $ps()) {
    super(id2, opts);
    this.g = /* @__PURE__ */ new WeakMap();
    this.description = opts.description;
    if ("dataId" in opts) {
      opts.src = { type: 0, dataId: opts.dataId };
    }
    this.src = opts.src;
    this.canPersist = opts.canPersist;
    this.accessTypes = opts.accessTypes;
    this.accessType = opts.accessType;
    if (opts.initialSessionData) {
      this.g.set(opts.initialSessionData.session, opts.initialSessionData.dataId);
    }
  }
  async toDAP(session) {
    let dataId;
    if (this.src.type === 0) {
      dataId = this.src.dataId;
    } else {
      let sessionDataId = this.g.get(session);
      if (!sessionDataId) {
        sessionDataId = (await session.dataBytesBreakpointInfo(this.src.address, this.src.bytes))?.dataId;
        if (!sessionDataId) {
          return void 0;
        }
        this.g.set(session, sessionDataId);
      }
      dataId = sessionDataId;
    }
    return {
      dataId,
      accessType: this.accessType,
      condition: this.condition,
      hitCondition: this.hitCondition
    };
  }
  toJSON() {
    return {
      ...super.toJSON(),
      description: this.description,
      src: this.src,
      accessTypes: this.accessTypes,
      accessType: this.accessType,
      canPersist: this.canPersist
    };
  }
  get supported() {
    if (!this.f) {
      return true;
    }
    return this.f.supportsDataBreakpoints;
  }
  toString() {
    return this.description;
  }
};
var $YP = class extends $UP {
  constructor(opts, id2 = $ps()) {
    super(id2, opts);
    this.g = /* @__PURE__ */ new Set();
    this.h = false;
    this.filter = opts.filter;
    this.label = opts.label;
    this.supportsCondition = opts.supportsCondition;
    this.description = opts.description;
    this.conditionDescription = opts.conditionDescription;
    this.h = opts.fallback || false;
  }
  toJSON() {
    return {
      ...super.toJSON(),
      filter: this.filter,
      label: this.label,
      enabled: this.enabled,
      supportsCondition: this.supportsCondition,
      conditionDescription: this.conditionDescription,
      condition: this.condition,
      fallback: this.h,
      description: this.description
    };
  }
  setSupportedSession(sessionId, supported) {
    if (supported) {
      this.g.add(sessionId);
    } else {
      this.g.delete(sessionId);
    }
  }
  /**
   * Used to specify which breakpoints to show when no session is specified.
   * Useful when no session is active and we want to show the exception breakpoints from the last session.
   */
  setFallback(isFallback) {
    this.h = isFallback;
  }
  get supported() {
    return true;
  }
  /**
   * Checks if the breakpoint is applicable for the specified session.
   * If sessionId is undefined, returns true if this breakpoint is a fallback breakpoint.
   */
  isSupportedSession(sessionId) {
    return sessionId ? this.g.has(sessionId) : this.h;
  }
  matches(filter) {
    return this.filter === filter.filter && this.label === filter.label && this.supportsCondition === !!filter.supportsCondition && this.conditionDescription === filter.conditionDescription && this.description === filter.description;
  }
  toString() {
    return this.label;
  }
};
var $ZP = class extends $UP {
  constructor(opts, id2 = $ps()) {
    super(id2, opts);
    this.instructionReference = opts.instructionReference;
    this.offset = opts.offset;
    this.canPersist = opts.canPersist;
    this.address = opts.address;
  }
  toDAP() {
    return {
      instructionReference: this.instructionReference,
      condition: this.condition,
      hitCondition: this.hitCondition,
      mode: this.mode,
      offset: this.offset
    };
  }
  toJSON() {
    return {
      ...super.toJSON(),
      instructionReference: this.instructionReference,
      offset: this.offset,
      canPersist: this.canPersist,
      address: this.address
    };
  }
  get supported() {
    if (!this.f) {
      return true;
    }
    return this.f.supportsInstructionBreakpoints;
  }
  toString() {
    return this.instructionReference;
  }
};
var $1P = class {
  constructor(sessionId, threadId) {
    this.sessionId = sessionId;
    this.threadId = threadId;
  }
  getId() {
    return `${this.sessionId}:${this.threadId}`;
  }
};
var $2P = class $2P2 extends $3c {
  constructor(debugStorage, D, F, G) {
    super();
    this.D = D;
    this.F = F;
    this.G = G;
    this.b = /* @__PURE__ */ new Map();
    this.f = true;
    this.g = this.B(new $ze());
    this.h = this.B(new $ze());
    this.j = this.B(new $ze());
    this.m = this.B(new $ze());
    this.n = /* @__PURE__ */ new Map();
    this.B($td((reader) => {
      this.t = debugStorage.breakpoints.read(reader);
      this.u = debugStorage.functionBreakpoints.read(reader);
      this.w = debugStorage.exceptionBreakpoints.read(reader);
      this.y = debugStorage.dataBreakpoints.read(reader);
      this.g.fire(void 0);
    }));
    this.B($td((reader) => {
      this.z = debugStorage.watchExpressions.read(reader);
      this.j.fire(void 0);
    }));
    this.B($Ke(() => new Set(this.z), this.onDidChangeWatchExpressions, (we) => we.onDidChangeValue((e) => this.m.fire(e))));
    this.C = [];
    this.a = [];
  }
  getId() {
    return "root";
  }
  getSession(sessionId, includeInactive = false) {
    if (sessionId) {
      return this.getSessions(includeInactive).find((s) => s.getId() === sessionId);
    }
    return void 0;
  }
  getSessions(includeInactive = false) {
    return this.a.filter(
      (s) => includeInactive || s.state !== 0
      /* State.Inactive */
    );
  }
  addSession(session) {
    this.a = this.a.filter((s) => {
      if (s.getId() === session.getId()) {
        return false;
      }
      if (s.state === 0 && s.configuration.name === session.configuration.name) {
        return false;
      }
      return true;
    });
    let i2 = 1;
    while (this.a.some((s) => s.getLabel() === session.getLabel())) {
      session.setName(`${session.configuration.name} ${++i2}`);
    }
    let index = -1;
    if (session.parentSession) {
      index = $2(this.a, (s) => s.parentSession === session.parentSession || s === session.parentSession);
    }
    if (index >= 0) {
      this.a.splice(index + 1, 0, session);
    } else {
      this.a.push(session);
    }
    this.h.fire(void 0);
  }
  get onDidChangeBreakpoints() {
    return this.g.event;
  }
  get onDidChangeCallStack() {
    return this.h.event;
  }
  get onDidChangeWatchExpressions() {
    return this.j.event;
  }
  get onDidChangeWatchExpressionValue() {
    return this.m.event;
  }
  rawUpdate(data) {
    const session = this.a.find((p) => p.getId() === data.sessionId);
    if (session) {
      session.rawUpdate(data);
      this.h.fire(void 0);
    }
  }
  clearThreads(id2, removeThreads, reference = void 0) {
    const session = this.a.find((p) => p.getId() === id2);
    this.b.forEach((entry) => {
      entry.scheduler.dispose();
      entry.completeDeferred.complete();
    });
    this.b.clear();
    if (session) {
      session.clearThreads(removeThreads, reference);
      this.h.fire(void 0);
    }
  }
  /**
   * Update the call stack and notify the call stack view that changes have occurred.
   */
  async fetchCallstack(thread, levels) {
    if (thread.reachedEndOfCallStack) {
      return;
    }
    const totalFrames = thread.stoppedDetails?.totalFrames;
    const remainingFrames = typeof totalFrames === "number" ? totalFrames - thread.getCallStack().length : void 0;
    if (!levels || remainingFrames && levels > remainingFrames) {
      levels = remainingFrames;
    }
    if (levels && levels > 0) {
      await thread.fetchCallStack(levels);
      this.h.fire();
    }
    return;
  }
  refreshTopOfCallstack(thread, fetchFullStack = true) {
    if (thread.session.capabilities.supportsDelayedStackTraceLoading) {
      let topCallStack = Promise.resolve();
      const wholeCallStack2 = new Promise((c, e) => {
        topCallStack = thread.fetchCallStack(1).then(() => {
          if (!fetchFullStack) {
            c();
            this.h.fire();
            return;
          }
          if (!this.b.has(thread.getId())) {
            const deferred = new $gi();
            this.b.set(thread.getId(), {
              completeDeferred: deferred,
              scheduler: new $8h(() => {
                thread.fetchCallStack(19).then(() => {
                  const stale = thread.getStaleCallStack();
                  const current = thread.getCallStack();
                  let bottomOfCallStackChanged = stale.length !== current.length;
                  for (let i2 = 1; i2 < stale.length && !bottomOfCallStackChanged; i2++) {
                    bottomOfCallStackChanged = !stale[i2].equals(current[i2]);
                  }
                  if (bottomOfCallStackChanged) {
                    this.h.fire();
                  }
                }).finally(() => {
                  deferred.complete();
                  this.b.delete(thread.getId());
                });
              }, 420)
            });
          }
          const entry = this.b.get(thread.getId());
          entry.scheduler.schedule();
          entry.completeDeferred.p.then(c, e);
          this.h.fire();
        });
      });
      return { topCallStack, wholeCallStack: wholeCallStack2 };
    }
    const wholeCallStack = thread.fetchCallStack();
    return { wholeCallStack, topCallStack: wholeCallStack };
  }
  getBreakpoints(filter) {
    if (filter) {
      const uriStr = filter.uri?.toString();
      const originalUriStr = filter.originalUri?.toString();
      return this.t.filter((bp) => {
        if (uriStr && bp.uri.toString() !== uriStr) {
          return false;
        }
        if (originalUriStr && bp.originalUri.toString() !== originalUriStr) {
          return false;
        }
        if (filter.lineNumber && bp.lineNumber !== filter.lineNumber) {
          return false;
        }
        if (filter.column && bp.column !== filter.column) {
          return false;
        }
        if (filter.enabledOnly && (!this.f || !bp.enabled)) {
          return false;
        }
        if (filter.triggeredOnly && bp.triggeredBy === void 0) {
          return false;
        }
        return true;
      });
    }
    return this.t;
  }
  getFunctionBreakpoints() {
    return this.u;
  }
  getDataBreakpoints() {
    return this.y;
  }
  getExceptionBreakpoints() {
    return this.w;
  }
  getExceptionBreakpointsForSession(sessionId) {
    return this.w.filter((ebp) => ebp.isSupportedSession(sessionId));
  }
  getInstructionBreakpoints() {
    return this.C;
  }
  setExceptionBreakpointsForSession(sessionId, filters2) {
    if (!filters2) {
      return;
    }
    let didChangeBreakpoints = false;
    filters2.forEach((d) => {
      let ebp = this.w.filter((exbp) => exbp.matches(d)).pop();
      if (!ebp) {
        didChangeBreakpoints = true;
        ebp = new $YP({
          filter: d.filter,
          label: d.label,
          enabled: !!d.default,
          supportsCondition: !!d.supportsCondition,
          description: d.description,
          conditionDescription: d.conditionDescription
        });
        this.w.push(ebp);
      }
      ebp.setSupportedSession(sessionId, true);
    });
    if (didChangeBreakpoints) {
      this.g.fire(void 0);
    }
  }
  removeExceptionBreakpointsForSession(sessionId) {
    this.w.forEach((ebp) => ebp.setSupportedSession(sessionId, false));
  }
  // Set last focused session as fallback session.
  // This is done to keep track of the exception breakpoints to show when no session is active.
  setExceptionBreakpointFallbackSession(sessionId) {
    this.w.forEach((ebp) => ebp.setFallback(ebp.isSupportedSession(sessionId)));
  }
  setExceptionBreakpointCondition(exceptionBreakpoint, condition) {
    exceptionBreakpoint.condition = condition;
    this.g.fire(void 0);
  }
  areBreakpointsActivated() {
    return this.f;
  }
  setBreakpointsActivated(activated) {
    this.f = activated;
    this.g.fire(void 0);
  }
  addBreakpoints(uri, rawData, fireEvent = true) {
    const newBreakpoints = rawData.map((rawBp) => {
      return new $VP({
        uri,
        lineNumber: rawBp.lineNumber,
        column: rawBp.column,
        enabled: rawBp.enabled ?? true,
        condition: rawBp.condition,
        hitCondition: rawBp.hitCondition,
        logMessage: rawBp.logMessage,
        triggeredBy: rawBp.triggeredBy,
        adapterData: void 0,
        mode: rawBp.mode,
        modeLabel: rawBp.modeLabel
      }, this.D, this.F, this.G, rawBp.id);
    });
    this.t = this.t.concat(newBreakpoints);
    this.f = true;
    this.H();
    if (fireEvent) {
      this.g.fire({ added: newBreakpoints, sessionOnly: false });
    }
    return newBreakpoints;
  }
  removeBreakpoints(toRemove) {
    this.t = this.t.filter((bp) => !toRemove.some((toRemove2) => toRemove2.getId() === bp.getId()));
    this.g.fire({ removed: toRemove, sessionOnly: false });
  }
  updateBreakpoints(data) {
    const updated = [];
    this.t.forEach((bp) => {
      const bpData = data.get(bp.getId());
      if (bpData) {
        bp.update(bpData);
        updated.push(bp);
      }
    });
    this.H();
    this.g.fire({ changed: updated, sessionOnly: false });
  }
  setBreakpointSessionData(sessionId, capabilites, data) {
    this.t.forEach((bp) => {
      if (!data) {
        bp.setSessionData(sessionId, void 0);
      } else {
        const bpData = data.get(bp.getId());
        if (bpData) {
          bp.setSessionData(sessionId, toBreakpointSessionData(bpData, capabilites));
        }
      }
    });
    this.u.forEach((fbp) => {
      if (!data) {
        fbp.setSessionData(sessionId, void 0);
      } else {
        const fbpData = data.get(fbp.getId());
        if (fbpData) {
          fbp.setSessionData(sessionId, toBreakpointSessionData(fbpData, capabilites));
        }
      }
    });
    this.y.forEach((dbp) => {
      if (!data) {
        dbp.setSessionData(sessionId, void 0);
      } else {
        const dbpData = data.get(dbp.getId());
        if (dbpData) {
          dbp.setSessionData(sessionId, toBreakpointSessionData(dbpData, capabilites));
        }
      }
    });
    this.w.forEach((ebp) => {
      if (!data) {
        ebp.setSessionData(sessionId, void 0);
      } else {
        const ebpData = data.get(ebp.getId());
        if (ebpData) {
          ebp.setSessionData(sessionId, toBreakpointSessionData(ebpData, capabilites));
        }
      }
    });
    this.C.forEach((ibp) => {
      if (!data) {
        ibp.setSessionData(sessionId, void 0);
      } else {
        const ibpData = data.get(ibp.getId());
        if (ibpData) {
          ibp.setSessionData(sessionId, toBreakpointSessionData(ibpData, capabilites));
        }
      }
    });
    this.g.fire({
      sessionOnly: true
    });
  }
  getDebugProtocolBreakpoint(breakpointId, sessionId) {
    const bp = this.t.find((bp2) => bp2.getId() === breakpointId);
    if (bp) {
      return bp.getDebugProtocolBreakpoint(sessionId);
    }
    return void 0;
  }
  getBreakpointModes(forBreakpointType) {
    return [...this.n.values()].filter((mode) => mode.appliesTo.includes(forBreakpointType));
  }
  registerBreakpointModes(debugType, modes) {
    for (const mode of modes) {
      const key2 = `${mode.mode}/${mode.label}`;
      const rec = this.n.get(key2);
      if (rec) {
        for (const target of mode.appliesTo) {
          if (!rec.appliesTo.includes(target)) {
            rec.appliesTo.push(target);
          }
        }
      } else {
        const duplicate = [...this.n.values()].find((r2) => r2 !== rec && r2.label === mode.label);
        if (duplicate) {
          duplicate.label = `${duplicate.label} (${duplicate.firstFromDebugType})`;
        }
        this.n.set(key2, {
          mode: mode.mode,
          label: duplicate ? `${mode.label} (${debugType})` : mode.label,
          firstFromDebugType: debugType,
          description: mode.description,
          appliesTo: mode.appliesTo.slice()
          // avoid later mutations
        });
      }
    }
  }
  H() {
    this.t = this.t.sort((first, second) => {
      if (first.uri.toString() !== second.uri.toString()) {
        return $rh(first.uri).localeCompare($rh(second.uri));
      }
      if (first.lineNumber === second.lineNumber) {
        if (first.column && second.column) {
          return first.column - second.column;
        }
        return 1;
      }
      return first.lineNumber - second.lineNumber;
    });
    this.t = $Rb(this.t, (bp) => `${bp.uri.toString()}:${bp.lineNumber}:${bp.column}`);
  }
  setEnablement(element, enable) {
    if (element instanceof $VP || element instanceof $WP || element instanceof $YP || element instanceof $XP || element instanceof $ZP) {
      const changed = [];
      if (element.enabled !== enable && (element instanceof $VP || element instanceof $WP || element instanceof $XP || element instanceof $ZP)) {
        changed.push(element);
      }
      element.enabled = enable;
      if (enable) {
        this.f = true;
      }
      this.g.fire({ changed, sessionOnly: false });
    }
  }
  enableOrDisableAllBreakpoints(enable) {
    const changed = [];
    this.t.forEach((bp) => {
      if (bp.enabled !== enable) {
        changed.push(bp);
      }
      bp.enabled = enable;
    });
    this.u.forEach((fbp) => {
      if (fbp.enabled !== enable) {
        changed.push(fbp);
      }
      fbp.enabled = enable;
    });
    this.y.forEach((dbp) => {
      if (dbp.enabled !== enable) {
        changed.push(dbp);
      }
      dbp.enabled = enable;
    });
    this.C.forEach((ibp) => {
      if (ibp.enabled !== enable) {
        changed.push(ibp);
      }
      ibp.enabled = enable;
    });
    if (enable) {
      this.f = true;
    }
    this.g.fire({ changed, sessionOnly: false });
  }
  addFunctionBreakpoint(opts, id2) {
    const newFunctionBreakpoint = new $WP(opts, id2);
    this.u.push(newFunctionBreakpoint);
    this.g.fire({ added: [newFunctionBreakpoint], sessionOnly: false });
    return newFunctionBreakpoint;
  }
  updateFunctionBreakpoint(id2, update) {
    const functionBreakpoint = this.u.find((fbp) => fbp.getId() === id2);
    if (functionBreakpoint) {
      if (typeof update.name === "string") {
        functionBreakpoint.name = update.name;
      }
      if (typeof update.condition === "string") {
        functionBreakpoint.condition = update.condition;
      }
      if (typeof update.hitCondition === "string") {
        functionBreakpoint.hitCondition = update.hitCondition;
      }
      this.g.fire({ changed: [functionBreakpoint], sessionOnly: false });
    }
  }
  removeFunctionBreakpoints(id2) {
    let removed;
    if (id2) {
      removed = this.u.filter((fbp) => fbp.getId() === id2);
      this.u = this.u.filter((fbp) => fbp.getId() !== id2);
    } else {
      removed = this.u;
      this.u = [];
    }
    this.g.fire({ removed, sessionOnly: false });
  }
  addDataBreakpoint(opts, id2) {
    const newDataBreakpoint = new $XP(opts, id2);
    this.y.push(newDataBreakpoint);
    this.g.fire({ added: [newDataBreakpoint], sessionOnly: false });
  }
  updateDataBreakpoint(id2, update) {
    const dataBreakpoint = this.y.find((fbp) => fbp.getId() === id2);
    if (dataBreakpoint) {
      if (typeof update.condition === "string") {
        dataBreakpoint.condition = update.condition;
      }
      if (typeof update.hitCondition === "string") {
        dataBreakpoint.hitCondition = update.hitCondition;
      }
      this.g.fire({ changed: [dataBreakpoint], sessionOnly: false });
    }
  }
  removeDataBreakpoints(id2) {
    let removed;
    if (id2) {
      removed = this.y.filter((fbp) => fbp.getId() === id2);
      this.y = this.y.filter((fbp) => fbp.getId() !== id2);
    } else {
      removed = this.y;
      this.y = [];
    }
    this.g.fire({ removed, sessionOnly: false });
  }
  addInstructionBreakpoint(opts) {
    const newInstructionBreakpoint = new $ZP(opts);
    this.C.push(newInstructionBreakpoint);
    this.g.fire({ added: [newInstructionBreakpoint], sessionOnly: true });
  }
  removeInstructionBreakpoints(instructionReference, offset) {
    let removed = [];
    if (instructionReference) {
      for (let i2 = 0; i2 < this.C.length; i2++) {
        const ibp = this.C[i2];
        if (ibp.instructionReference === instructionReference && (offset === void 0 || ibp.offset === offset)) {
          removed.push(ibp);
          this.C.splice(i2--, 1);
        }
      }
    } else {
      removed = this.C;
      this.C = [];
    }
    this.g.fire({ removed, sessionOnly: false });
  }
  getWatchExpressions() {
    return this.z;
  }
  addWatchExpression(name) {
    const we = new $LP(name || "");
    this.z.push(we);
    this.j.fire(we);
    return we;
  }
  renameWatchExpression(id2, newName) {
    const filtered = this.z.filter((we) => we.getId() === id2);
    if (filtered.length === 1) {
      filtered[0].name = newName;
      this.j.fire(filtered[0]);
    }
  }
  removeWatchExpressions(id2 = null) {
    this.z = id2 ? this.z.filter((we) => we.getId() !== id2) : [];
    this.j.fire(void 0);
  }
  moveWatchExpression(id2, position) {
    const we = this.z.find((we2) => we2.getId() === id2);
    if (we) {
      this.z = this.z.filter((we2) => we2.getId() !== id2);
      this.z = this.z.slice(0, position).concat(we, this.z.slice(position));
      this.j.fire(void 0);
    }
  }
  sourceIsNotAvailable(uri) {
    this.a.forEach((s) => {
      const source = s.getSourceForUri(uri);
      if (source) {
        source.available = false;
      }
    });
    this.h.fire(void 0);
  }
};
$2P = __decorate([
  __param(1, $cK),
  __param(2, $vl),
  __param(3, $wn)
], $2P);

// out-build/vs/workbench/contrib/debug/common/debugVisualizers.js
var $FP = $Qk("debugVisualizerService");
var $GP = class {
  get name() {
    return this.b.name;
  }
  get iconPath() {
    return this.b.iconPath;
  }
  get iconClass() {
    return this.b.iconClass;
  }
  constructor(a, b) {
    this.a = a;
    this.b = b;
  }
  async resolve(token) {
    return this.b.visualization ??= await this.a.resolveDebugVisualizer(this.b, token);
  }
  async execute() {
    await this.a.executeDebugVisualizerCommand(this.b.id);
  }
};
var emptyRef = { object: [], dispose: () => {
} };
var $HP = class $HP2 {
  constructor(g, h3, i2) {
    this.g = g;
    this.h = h3;
    this.i = i2;
    this.a = /* @__PURE__ */ new Map();
    this.b = /* @__PURE__ */ new Map();
    this.d = /* @__PURE__ */ new Map();
    this.f = [];
    visualizersExtensionPoint.setHandler((_, { added, removed }) => {
      this.f = this.f.filter((r2) => !removed.some((e) => $5z.equals(e.description.identifier, r2.extensionId)));
      added.forEach((e) => this.k(e.description));
    });
  }
  /** @inheritdoc */
  async getApplicableFor(variable, token) {
    if (!(variable instanceof $MP)) {
      return emptyRef;
    }
    const threadId = variable.getThreadId();
    if (threadId === void 0) {
      return emptyRef;
    }
    const context = this.j(threadId, variable);
    const overlay = $EP(this.g, variable, [
      [$RR.key, variable.name],
      [$OR.key, variable.value],
      [$PR.key, variable.type]
    ]);
    const maybeVisualizers = await Promise.all(this.f.map(async (registration) => {
      if (!overlay.contextMatchesRules(registration.expr)) {
        return;
      }
      let prom = this.d.get(registration.id);
      if (!prom) {
        prom = this.h.activateByEvent(`onDebugVisualizer:${registration.id}`);
        this.d.set(registration.id, prom);
      }
      await prom;
      if (token.isCancellationRequested) {
        return;
      }
      const handle2 = this.a.get(toKey(registration.extensionId, registration.id));
      return handle2 && { handle: handle2, result: await handle2.provideDebugVisualizers(context, token) };
    }));
    const ref = {
      object: maybeVisualizers.filter($Hg).flatMap((v) => v.result.map((r2) => new $GP(v.handle, r2))),
      dispose: () => {
        for (const viz of maybeVisualizers) {
          viz?.handle.disposeDebugVisualizers(viz.result.map((r2) => r2.id));
        }
      }
    };
    if (token.isCancellationRequested) {
      ref.dispose();
    }
    return ref;
  }
  /** @inheritdoc */
  register(handle2) {
    const key2 = toKey(handle2.extensionId, handle2.id);
    this.a.set(key2, handle2);
    return $1c(() => this.a.delete(key2));
  }
  /** @inheritdoc */
  registerTree(treeId, handle2) {
    this.b.set(treeId, handle2);
    return $1c(() => this.b.delete(treeId));
  }
  /** @inheritdoc */
  async getVisualizedNodeFor(treeId, expr) {
    if (!(expr instanceof $MP)) {
      return;
    }
    const threadId = expr.getThreadId();
    if (threadId === void 0) {
      return;
    }
    const tree = this.b.get(treeId);
    if (!tree) {
      return;
    }
    try {
      const treeItem = await tree.getTreeItem(this.j(threadId, expr));
      if (!treeItem) {
        return;
      }
      return new $KP(expr.getSession(), this, treeId, treeItem, expr);
    } catch (e) {
      this.i.warn("Failed to get visualized node", e);
      return;
    }
  }
  /** @inheritdoc */
  async getVisualizedChildren(session, treeId, treeElementId) {
    const node = this.b.get(treeId);
    const children = await node?.getChildren(treeElementId) || [];
    return children.map((c) => new $KP(session, this, treeId, c, void 0));
  }
  /** @inheritdoc */
  async editTreeItem(treeId, treeItem, newValue) {
    const newItem = await this.b.get(treeId)?.editItem?.(treeItem.id, newValue);
    if (newItem) {
      Object.assign(treeItem, newItem);
    }
  }
  j(threadId, variable) {
    const context = {
      sessionId: variable.getSession()?.getId() || "",
      containerId: variable.parent instanceof $MP ? variable.reference : void 0,
      threadId,
      variable: {
        name: variable.name,
        value: variable.value,
        type: variable.type,
        evaluateName: variable.evaluateName,
        variablesReference: variable.reference || 0,
        indexedVariables: variable.indexedVariables,
        memoryReference: variable.memoryReference,
        namedVariables: variable.namedVariables,
        presentationHint: variable.presentationHint
      }
    };
    for (let p = variable; p instanceof $MP; p = p.parent) {
      if (p.parent instanceof $NP) {
        context.frameId = p.parent.stackFrame.frameId;
      }
    }
    return context;
  }
  k(ext) {
    const viz = ext.contributes?.debugVisualizers;
    if (!(viz instanceof Array)) {
      return;
    }
    for (const { when, id: id2 } of viz) {
      try {
        const expr = $7m.deserialize(when);
        if (expr) {
          this.f.push({ expr, id: id2, extensionId: ext.identifier });
        }
      } catch (e) {
        this.i.error(`Error processing debug visualizer registration from extension '${ext.identifier.value}'`, e);
      }
    }
  }
};
$HP = __decorate([
  __param(0, $on),
  __param(1, $wN),
  __param(2, $wn)
], $HP);
var toKey = (extensionId, id2) => `${$5z.toKey(extensionId)}\0${id2}`;
var visualizersExtensionPoint = $tN.registerExtensionPoint({
  extensionPoint: "debugVisualizers",
  jsonSchema: {
    type: "array",
    items: {
      type: "object",
      properties: {
        id: {
          type: "string",
          description: "Name of the debug visualizer"
        },
        when: {
          type: "string",
          description: "Condition when the debug visualizer is applicable"
        }
      },
      required: ["id", "when"]
    }
  },
  activationEventsGenerator: (contribs, result) => {
    for (const contrib of contribs) {
      if (contrib.id) {
        result.push(`onDebugVisualizer:${contrib.id}`);
      }
    }
  }
});

// out-build/vs/workbench/api/browser/mainThreadDebugService.js
var $yOb = class $yOb2 {
  constructor(extHostContext, k, m) {
    this.k = k;
    this.m = m;
    this.b = new $2c();
    this.d = 1;
    this.i = /* @__PURE__ */ new Map();
    this.j = /* @__PURE__ */ new Map();
    this.a = extHostContext.getProxy($yT.ExtHostDebugService);
    const sessionListeners = new $_c();
    this.b.add(sessionListeners);
    this.b.add(k.onDidNewSession((session) => {
      this.a.$acceptDebugSessionStarted(this.getSessionDto(session));
      const store = sessionListeners.get(session);
      store?.add(session.onDidChangeName((name) => {
        this.a.$acceptDebugSessionNameChanged(this.getSessionDto(session), name);
      }));
    }));
    this.b.add(k.onWillNewSession((session) => {
      let store = sessionListeners.get(session);
      if (!store) {
        store = new $2c();
        sessionListeners.set(session, store);
      }
      store.add(session.onDidCustomEvent((event) => this.a.$acceptDebugSessionCustomEvent(this.getSessionDto(session), event)));
    }));
    this.b.add(k.onDidEndSession(({ session, restart }) => {
      this.a.$acceptDebugSessionTerminated(this.getSessionDto(session));
      this.h.delete(session.getId());
      if (!restart) {
        sessionListeners.deleteAndDispose(session);
      }
      for (const [handle2, value] of this.c) {
        if (value.session === session) {
          this.c.delete(handle2);
        }
      }
    }));
    this.b.add(k.getViewModel().onDidFocusSession((session) => {
      this.a.$acceptDebugSessionActiveChanged(this.getSessionDto(session));
    }));
    this.b.add($1c(() => {
      for (const [handle2, da] of this.c) {
        da.fireError(handle2, new Error("Extension host shut down"));
      }
    }));
    this.c = /* @__PURE__ */ new Map();
    this.f = /* @__PURE__ */ new Map();
    this.g = /* @__PURE__ */ new Map();
    this.h = /* @__PURE__ */ new Set();
    const viewModel = this.k.getViewModel();
    this.b.add(Event2.any(viewModel.onDidFocusStackFrame, viewModel.onDidFocusThread)(() => {
      const stackFrame = viewModel.focusedStackFrame;
      const thread = viewModel.focusedThread;
      if (stackFrame) {
        this.a.$acceptStackFrameFocus({
          kind: "stackFrame",
          threadId: stackFrame.thread.threadId,
          frameId: stackFrame.frameId,
          sessionId: stackFrame.thread.session.getId()
        });
      } else if (thread) {
        this.a.$acceptStackFrameFocus({
          kind: "thread",
          threadId: thread.threadId,
          sessionId: thread.session.getId()
        });
      } else {
        this.a.$acceptStackFrameFocus(void 0);
      }
    }));
    this.n();
  }
  $registerDebugVisualizerTree(treeId, canEdit) {
    this.m.registerTree(treeId, {
      disposeItem: (id2) => this.a.$disposeVisualizedTree(id2),
      getChildren: (e) => this.a.$getVisualizerTreeItemChildren(treeId, e),
      getTreeItem: (e) => this.a.$getVisualizerTreeItem(treeId, e),
      editItem: canEdit ? (e, v) => this.a.$editVisualizerTreeItem(e, v) : void 0
    });
  }
  $unregisterDebugVisualizerTree(treeId) {
    this.j.get(treeId)?.dispose();
    this.j.delete(treeId);
  }
  $registerDebugVisualizer(extensionId, id2) {
    const handle2 = this.m.register({
      extensionId: new $5z(extensionId),
      id: id2,
      disposeDebugVisualizers: (ids) => this.a.$disposeDebugVisualizers(ids),
      executeDebugVisualizerCommand: (id3) => this.a.$executeDebugVisualizerCommand(id3),
      provideDebugVisualizers: (context, token) => this.a.$provideDebugVisualizers(extensionId, id2, context, token).then((r2) => r2.map(IDebugVisualization.deserialize)),
      resolveDebugVisualizer: (viz, token) => this.a.$resolveDebugVisualizer(viz.id, token)
    });
    this.i.set(`${extensionId}/${id2}`, handle2);
  }
  $unregisterDebugVisualizer(extensionId, id2) {
    const key2 = `${extensionId}/${id2}`;
    this.i.get(key2)?.dispose();
    this.i.delete(key2);
  }
  n() {
    this.b.add(this.k.getModel().onDidChangeBreakpoints((e) => {
      if (e && !e.sessionOnly) {
        const delta = {};
        if (e.added) {
          delta.added = this.q(e.added);
        }
        if (e.removed) {
          delta.removed = e.removed.map((x) => x.getId());
        }
        if (e.changed) {
          delta.changed = this.q(e.changed);
        }
        if (delta.added || delta.removed || delta.changed) {
          this.a.$acceptBreakpointsDelta(delta);
        }
      }
    }));
    const bps = this.k.getModel().getBreakpoints();
    const fbps = this.k.getModel().getFunctionBreakpoints();
    const dbps = this.k.getModel().getDataBreakpoints();
    if (bps.length > 0 || fbps.length > 0) {
      this.a.$acceptBreakpointsDelta({
        added: this.q(bps).concat(this.q(fbps)).concat(this.q(dbps))
      });
    }
  }
  dispose() {
    this.b.dispose();
  }
  // interface IDebugAdapterProvider
  createDebugAdapter(session) {
    const handle2 = this.d++;
    const da = new ExtensionHostDebugAdapter(this, handle2, this.a, session);
    this.c.set(handle2, da);
    return da;
  }
  substituteVariables(folder, config) {
    return Promise.resolve(this.a.$substituteVariables(folder ? folder.uri : void 0, config));
  }
  runInTerminal(args2, sessionId) {
    return this.a.$runInTerminal(args2, sessionId);
  }
  // RPC methods (MainThreadDebugServiceShape)
  $registerDebugTypes(debugTypes) {
    this.b.add(this.k.getAdapterManager().registerDebugAdapterFactory(debugTypes, this));
  }
  $registerBreakpoints(DTOs) {
    for (const dto of DTOs) {
      if (dto.type === "sourceMulti") {
        const rawbps = dto.lines.map((l) => ({
          id: l.id,
          enabled: l.enabled,
          lineNumber: l.line + 1,
          column: l.character > 0 ? l.character + 1 : void 0,
          // a column value of 0 results in an omitted column attribute; see #46784
          condition: l.condition,
          hitCondition: l.hitCondition,
          logMessage: l.logMessage,
          mode: l.mode
        }));
        this.k.addBreakpoints(URI.revive(dto.uri), rawbps);
      } else if (dto.type === "function") {
        this.k.addFunctionBreakpoint({
          name: dto.functionName,
          mode: dto.mode,
          condition: dto.condition,
          hitCondition: dto.hitCondition,
          enabled: dto.enabled,
          logMessage: dto.logMessage
        }, dto.id);
      } else if (dto.type === "data") {
        this.k.addDataBreakpoint({
          description: dto.label,
          src: { type: 0, dataId: dto.dataId },
          canPersist: dto.canPersist,
          accessTypes: dto.accessTypes,
          accessType: dto.accessType,
          mode: dto.mode
        });
      }
    }
    return Promise.resolve();
  }
  $unregisterBreakpoints(breakpointIds2, functionBreakpointIds, dataBreakpointIds) {
    breakpointIds2.forEach((id2) => this.k.removeBreakpoints(id2));
    functionBreakpointIds.forEach((id2) => this.k.removeFunctionBreakpoints(id2));
    dataBreakpointIds.forEach((id2) => this.k.removeDataBreakpoints(id2));
    return Promise.resolve();
  }
  $registerDebugConfigurationProvider(debugType, providerTriggerKind, hasProvide, hasResolve, hasResolve2, handle2) {
    const provider = {
      type: debugType,
      triggerKind: providerTriggerKind
    };
    if (hasProvide) {
      provider.provideDebugConfigurations = (folder, token) => {
        return this.a.$provideDebugConfigurations(handle2, folder, token);
      };
    }
    if (hasResolve) {
      provider.resolveDebugConfiguration = (folder, config, token) => {
        return this.a.$resolveDebugConfiguration(handle2, folder, config, token);
      };
    }
    if (hasResolve2) {
      provider.resolveDebugConfigurationWithSubstitutedVariables = (folder, config, token) => {
        return this.a.$resolveDebugConfigurationWithSubstitutedVariables(handle2, folder, config, token);
      };
    }
    this.f.set(handle2, provider);
    this.b.add(this.k.getConfigurationManager().registerDebugConfigurationProvider(provider));
    return Promise.resolve(void 0);
  }
  $unregisterDebugConfigurationProvider(handle2) {
    const provider = this.f.get(handle2);
    if (provider) {
      this.f.delete(handle2);
      this.k.getConfigurationManager().unregisterDebugConfigurationProvider(provider);
    }
  }
  $registerDebugAdapterDescriptorFactory(debugType, handle2) {
    const provider = {
      type: debugType,
      createDebugAdapterDescriptor: (session) => {
        return Promise.resolve(this.a.$provideDebugAdapter(handle2, this.getSessionDto(session)));
      }
    };
    this.g.set(handle2, provider);
    this.b.add(this.k.getAdapterManager().registerDebugAdapterDescriptorFactory(provider));
    return Promise.resolve(void 0);
  }
  $unregisterDebugAdapterDescriptorFactory(handle2) {
    const provider = this.g.get(handle2);
    if (provider) {
      this.g.delete(handle2);
      this.k.getAdapterManager().unregisterDebugAdapterDescriptorFactory(provider);
    }
  }
  o(sessionId) {
    if (sessionId) {
      return this.k.getModel().getSession(sessionId, true);
    }
    return void 0;
  }
  async $startDebugging(folder, nameOrConfig, options3) {
    const folderUri = folder ? URI.revive(folder) : void 0;
    const launch = this.k.getConfigurationManager().getLaunch(folderUri);
    const parentSession = this.o(options3.parentSessionID);
    const saveBeforeStart = typeof options3.suppressSaveBeforeStart === "boolean" ? !options3.suppressSaveBeforeStart : void 0;
    const debugOptions = {
      noDebug: options3.noDebug,
      parentSession,
      lifecycleManagedByParent: options3.lifecycleManagedByParent,
      repl: options3.repl,
      compact: options3.compact,
      compoundRoot: parentSession?.compoundRoot,
      saveBeforeRestart: saveBeforeStart,
      testRun: options3.testRun,
      suppressDebugStatusbar: options3.suppressDebugStatusbar,
      suppressDebugToolbar: options3.suppressDebugToolbar,
      suppressDebugView: options3.suppressDebugView
    };
    try {
      return this.k.startDebugging(launch, nameOrConfig, debugOptions, saveBeforeStart);
    } catch (err) {
      throw new $ub(err && err.message ? err.message : "cannot start debugging");
    }
  }
  $setDebugSessionName(sessionId, name) {
    const session = this.k.getModel().getSession(sessionId);
    session?.setName(name);
  }
  $customDebugAdapterRequest(sessionId, request, args2) {
    const session = this.k.getModel().getSession(sessionId, true);
    if (session) {
      return session.customRequest(request, args2).then((response) => {
        if (response && response.success) {
          return response.body;
        } else {
          return Promise.reject(new $ub(response ? response.message : "custom request failed"));
        }
      });
    }
    return Promise.reject(new $ub("debug session not found"));
  }
  $getDebugProtocolBreakpoint(sessionId, breakpoinId) {
    const session = this.k.getModel().getSession(sessionId, true);
    if (session) {
      return Promise.resolve(session.getDebugProtocolBreakpoint(breakpoinId));
    }
    return Promise.reject(new $ub("debug session not found"));
  }
  $stopDebugging(sessionId) {
    if (sessionId) {
      const session = this.k.getModel().getSession(sessionId, true);
      if (session) {
        return this.k.stopSession(session, $pP(session));
      }
    } else {
      return this.k.stopSession(void 0);
    }
    return Promise.reject(new $ub("debug session not found"));
  }
  $appendDebugConsole(value) {
    const session = this.k.getViewModel().focusedSession;
    session?.appendToRepl({ output: value, sev: severity_default.Warning });
  }
  $acceptDAMessage(handle2, message) {
    this.p(handle2).acceptMessage($wP(message, false));
  }
  $acceptDAError(handle2, name, message, stack) {
    this.c.get(handle2)?.fireError(handle2, new Error(`${name}: ${message}
${stack}`));
  }
  $acceptDAExit(handle2, code, signal) {
    this.p(handle2).fireExit(handle2, code, signal);
  }
  p(handle2) {
    const adapter = this.c.get(handle2);
    if (!adapter) {
      throw new Error("Invalid debug adapter");
    }
    return adapter;
  }
  // dto helpers
  $sessionCached(sessionID) {
    this.h.add(sessionID);
  }
  getSessionDto(session) {
    if (session) {
      const sessionID = session.getId();
      if (this.h.has(sessionID)) {
        return sessionID;
      } else {
        return {
          id: sessionID,
          type: session.configuration.type,
          name: session.name,
          folderUri: session.root ? session.root.uri : void 0,
          configuration: session.configuration,
          parent: session.parentSession?.getId()
        };
      }
    }
    return void 0;
  }
  q(bps) {
    return bps.map((bp) => {
      if ("name" in bp) {
        const fbp = bp;
        return {
          type: "function",
          id: fbp.getId(),
          enabled: fbp.enabled,
          condition: fbp.condition,
          hitCondition: fbp.hitCondition,
          logMessage: fbp.logMessage,
          functionName: fbp.name
        };
      } else if ("src" in bp) {
        const dbp = bp;
        return {
          type: "data",
          id: dbp.getId(),
          dataId: dbp.src.type === 0 ? dbp.src.dataId : dbp.src.address,
          enabled: dbp.enabled,
          condition: dbp.condition,
          hitCondition: dbp.hitCondition,
          logMessage: dbp.logMessage,
          accessType: dbp.accessType,
          label: dbp.description,
          canPersist: dbp.canPersist
        };
      } else if ("uri" in bp) {
        const sbp = bp;
        return {
          type: "source",
          id: sbp.getId(),
          enabled: sbp.enabled,
          condition: sbp.condition,
          hitCondition: sbp.hitCondition,
          logMessage: sbp.logMessage,
          uri: sbp.uri,
          line: sbp.lineNumber > 0 ? sbp.lineNumber - 1 : 0,
          character: typeof sbp.column === "number" && sbp.column > 0 ? sbp.column - 1 : 0
        };
      } else {
        return void 0;
      }
    }).filter($Hg);
  }
};
$yOb = __decorate([
  $frb($xT.MainThreadDebugService),
  __param(1, $0R),
  __param(2, $FP)
], $yOb);
var ExtensionHostDebugAdapter = class extends $xOb {
  constructor(a, b, c, session) {
    super();
    this.a = a;
    this.b = b;
    this.c = c;
    this.session = session;
  }
  fireError(handle2, err) {
    this.n.fire(err);
  }
  fireExit(handle2, code, signal) {
    this.o.fire(code);
  }
  startSession() {
    return Promise.resolve(this.c.$startDASession(this.b, this.a.getSessionDto(this.session)));
  }
  sendMessage(message) {
    this.c.$sendDAMessage(this.b, $vP(message, true));
  }
  async stopSession() {
    await this.w();
    return Promise.resolve(this.c.$stopDASession(this.b));
  }
};

// out-build/vs/workbench/api/browser/mainThreadDecorations.js
var DecorationRequestsQueue = class {
  constructor(e, f) {
    this.e = e;
    this.f = f;
    this.a = 0;
    this.b = /* @__PURE__ */ new Map();
    this.c = /* @__PURE__ */ new Map();
  }
  enqueue(uri, token) {
    const id2 = ++this.a;
    const result = new Promise((resolve) => {
      this.b.set(id2, { id: id2, uri });
      this.c.set(id2, resolve);
      this.g();
    });
    const sub = token.onCancellationRequested(() => {
      this.b.delete(id2);
      this.c.delete(id2);
    });
    return result.finally(() => sub.dispose());
  }
  g() {
    if (typeof this.d === "number") {
      return;
    }
    this.d = setTimeout(() => {
      const requests = this.b;
      const resolver = this.c;
      this.e.$provideDecorations(this.f, [...requests.values()], CancellationToken.None).then((data) => {
        for (const [id2, resolve] of resolver) {
          resolve(data[id2]);
        }
      });
      this.b = /* @__PURE__ */ new Map();
      this.c = /* @__PURE__ */ new Map();
      this.d = void 0;
    }, 0);
  }
};
var $zOb = class $zOb2 {
  constructor(context, c) {
    this.c = c;
    this.a = /* @__PURE__ */ new Map();
    this.b = context.getProxy($yT.ExtHostDecorations);
  }
  dispose() {
    this.a.forEach((value) => $Xc(value));
    this.a.clear();
  }
  $registerDecorationProvider(handle2, label3) {
    const emitter = new $ze();
    const queue = new DecorationRequestsQueue(this.b, handle2);
    const registration = this.c.registerDecorationsProvider({
      label: label3,
      onDidChange: emitter.event,
      provideDecorations: async (uri, token) => {
        const data = await queue.enqueue(uri, token);
        if (!data) {
          return void 0;
        }
        const [bubble, tooltip, letter, themeColor] = data;
        return {
          weight: 10,
          bubble: bubble ?? false,
          color: themeColor?.id,
          tooltip,
          letter
        };
      }
    });
    this.a.set(handle2, [emitter, registration]);
  }
  $onDidChange(handle2, resources) {
    const provider = this.a.get(handle2);
    if (provider) {
      const [emitter] = provider;
      emitter.fire(resources && resources.map((r2) => URI.revive(r2)));
    }
  }
  $unregisterDecorationProvider(handle2) {
    const provider = this.a.get(handle2);
    if (provider) {
      $Xc(provider);
      this.a.delete(handle2);
    }
  }
};
$zOb = __decorate([
  $frb($xT.MainThreadDecorations),
  __param(1, $jsb)
], $zOb);

// out-build/vs/workbench/api/browser/mainThreadDiagnostics.js
var $AOb = class $AOb2 {
  constructor(extHostContext, d, e) {
    this.d = d;
    this.e = e;
    this.a = /* @__PURE__ */ new Set();
    this.b = extHostContext.getProxy($yT.ExtHostDiagnostics);
    this.c = this.d.onMarkerChanged(this.f, this);
  }
  dispose() {
    this.c.dispose();
    this.a.forEach((owner) => this.d.changeAll(owner, []));
    this.a.clear();
  }
  f(resources) {
    const data = [];
    for (const resource of resources) {
      const allMarkerData = this.d.read({ resource });
      if (allMarkerData.length === 0) {
        data.push([resource, []]);
      } else {
        const forgeinMarkerData = allMarkerData.filter((marker) => !this.a.has(marker.owner));
        if (forgeinMarkerData.length > 0) {
          data.push([resource, forgeinMarkerData]);
        }
      }
    }
    if (data.length > 0) {
      this.b.$acceptMarkersChange(data);
    }
  }
  $changeMany(owner, entries2) {
    for (const entry of entries2) {
      const [uri, markers] = entry;
      if (markers) {
        for (const marker of markers) {
          if (marker.relatedInformation) {
            for (const relatedInformation of marker.relatedInformation) {
              relatedInformation.resource = URI.revive(relatedInformation.resource);
            }
          }
          if (marker.code && typeof marker.code !== "string") {
            marker.code.target = URI.revive(marker.code.target);
          }
        }
      }
      this.d.changeOne(owner, this.e.asCanonicalUri(URI.revive(uri)), markers);
    }
    this.a.add(owner);
  }
  $clear(owner) {
    this.d.changeAll(owner, []);
    this.a.delete(owner);
  }
};
$AOb = __decorate([
  $frb($xT.MainThreadDiagnostics),
  __param(1, $DE),
  __param(2, $vl)
], $AOb);

// out-build/vs/workbench/api/browser/mainThreadDialogs.js
var $BOb_1;
var $BOb = $BOb_1 = class $BOb2 {
  constructor(context, a) {
    this.a = a;
  }
  dispose() {
  }
  async $showOpenDialog(options3) {
    const convertedOptions = $BOb_1.b(options3);
    if (!convertedOptions.defaultUri) {
      convertedOptions.defaultUri = await this.a.defaultFilePath();
    }
    return Promise.resolve(this.a.showOpenDialog(convertedOptions));
  }
  async $showSaveDialog(options3) {
    const convertedOptions = $BOb_1.c(options3);
    if (!convertedOptions.defaultUri) {
      convertedOptions.defaultUri = await this.a.defaultFilePath();
    }
    return Promise.resolve(this.a.showSaveDialog(convertedOptions));
  }
  static b(options3) {
    const result = {
      openLabel: options3?.openLabel || void 0,
      canSelectFiles: options3?.canSelectFiles || !options3?.canSelectFiles && !options3?.canSelectFolders,
      canSelectFolders: options3?.canSelectFolders,
      canSelectMany: options3?.canSelectMany,
      defaultUri: options3?.defaultUri ? URI.revive(options3.defaultUri) : void 0,
      title: options3?.title || void 0,
      availableFileSystems: options3?.allowUIResources ? [Schemas.vscodeRemote, Schemas.file] : []
    };
    if (options3?.filters) {
      result.filters = [];
      for (const [key2, value] of Object.entries(options3.filters)) {
        result.filters.push({ name: key2, extensions: value });
      }
    }
    return result;
  }
  static c(options3) {
    const result = {
      defaultUri: options3?.defaultUri ? URI.revive(options3.defaultUri) : void 0,
      saveLabel: options3?.saveLabel || void 0,
      title: options3?.title || void 0
    };
    if (options3?.filters) {
      result.filters = [];
      for (const [key2, value] of Object.entries(options3.filters)) {
        result.filters.push({ name: key2, extensions: value });
      }
    }
    return result;
  }
};
$BOb = $BOb_1 = __decorate([
  $frb($xT.MainThreadDialogs),
  __param(1, $1v)
], $BOb);

// out-build/vs/workbench/api/browser/mainThreadDocumentContentProviders.js
var $COb = class $COb2 {
  constructor(extHostContext, d, e, f, g) {
    this.d = d;
    this.e = e;
    this.f = f;
    this.g = g;
    this.a = new $_c();
    this.b = /* @__PURE__ */ new Map();
    this.c = extHostContext.getProxy($yT.ExtHostDocumentContentProviders);
  }
  dispose() {
    this.a.dispose();
    $Xc(this.b.values());
  }
  $registerTextContentProvider(handle2, scheme) {
    const registration = this.d.registerTextModelContentProvider(scheme, {
      provideTextContent: (uri) => {
        return this.c.$provideTextDocumentContent(handle2, uri).then((value) => {
          if (typeof value === "string") {
            const firstLineText = value.substr(0, 1 + value.search(/\r?\n/));
            const languageSelection = this.e.createByFilepathOrFirstLine(uri, firstLineText);
            return this.f.createModel(value, languageSelection, uri);
          }
          return null;
        });
      }
    });
    this.a.set(handle2, registration);
  }
  $unregisterTextContentProvider(handle2) {
    this.a.deleteAndDispose(handle2);
  }
  async $onVirtualDocumentChange(uri, value) {
    const model = this.f.getModel(URI.revive(uri));
    if (!model) {
      return;
    }
    const pending = this.b.get(model.id);
    pending?.cancel();
    const myToken = new $ad();
    this.b.set(model.id, myToken);
    try {
      const edits = await this.g.computeMoreMinimalEdits(model.uri, [{ text: value, range: model.getFullModelRange() }]);
      this.b.delete(model.id);
      if (myToken.token.isCancellationRequested) {
        return;
      }
      if (edits && edits.length > 0) {
        model.applyEdits(edits.map((edit3) => $bD.replace($9C.lift(edit3.range), edit3.text)));
      }
    } catch (error) {
      $gb(error);
    }
  }
};
$COb = __decorate([
  $frb($xT.MainThreadDocumentContentProviders),
  __param(1, $oG),
  __param(2, $1E),
  __param(3, $sG),
  __param(4, $I0)
], $COb);

// out-build/vs/workbench/api/browser/mainThreadDocuments.js
var $DOb = class {
  constructor(c, d = 1e3 * 60 * 3, f = 1024 * 1024 * 80, g = 50) {
    this.c = c;
    this.d = d;
    this.f = f;
    this.g = g;
    this.a = new Array();
    this.b = 0;
  }
  dispose() {
    this.a = $Xc(this.a);
  }
  remove(uri) {
    for (const entry of [...this.a]) {
      if (this.c.isEqualOrParent(entry.uri, uri)) {
        entry.dispose();
      }
    }
  }
  add(uri, ref, length = 0) {
    const dispose = () => {
      const idx = this.a.indexOf(entry);
      if (idx >= 0) {
        this.b -= length;
        ref.dispose();
        clearTimeout(handle2);
        this.a.splice(idx, 1);
      }
    };
    const handle2 = setTimeout(dispose, this.d);
    const entry = { uri, length, dispose };
    this.a.push(entry);
    this.b += length;
    this.h();
  }
  h() {
    while (this.b > this.f) {
      this.a[0].dispose();
    }
    const extraSize = Math.ceil(this.g * 1.2);
    if (this.a.length >= extraSize) {
      $Xc(this.a.slice(0, extraSize - this.g));
    }
  }
};
var ModelTracker = class extends $3c {
  constructor(b, c, f, g) {
    super();
    this.b = b;
    this.c = c;
    this.f = f;
    this.g = g;
    this.a = this.b.getVersionId();
    this.q.add(this.b.onDidChangeContent((e) => {
      this.a = e.versionId;
      this.f.$acceptModelChanged(this.b.uri, e, this.g.isDirty(this.b.uri));
      if (this.isCaughtUpWithContentChanges()) {
        this.c.fire(this.b.uri);
      }
    }));
  }
  isCaughtUpWithContentChanges() {
    return this.b.getVersionId() === this.a;
  }
};
var $EOb = class $EOb2 extends $3c {
  constructor(extHostContext, g, h3, j, n, r2, s, workingCopyFileService, t) {
    super();
    this.g = g;
    this.h = h3;
    this.j = j;
    this.n = n;
    this.r = r2;
    this.s = s;
    this.t = t;
    this.a = this.q.add(new $ze());
    this.onIsCaughtUpWithContentChanges = this.a.event;
    this.c = new $Ec();
    this.f = this.q.add(new $DOb(s.extUri));
    this.b = extHostContext.getProxy($yT.ExtHostDocuments);
    this.q.add(g.onModelLanguageChanged(this.w, this));
    this.q.add(h3.files.onDidSave((e) => {
      if (this.u(e.model.resource)) {
        this.b.$acceptModelSaved(e.model.resource);
      }
    }));
    this.q.add(h3.files.onDidChangeDirty((m) => {
      if (this.u(m.resource)) {
        this.b.$acceptDirtyStateChanged(m.resource, m.isDirty());
      }
    }));
    this.q.add(workingCopyFileService.onDidRunWorkingCopyFileOperation((e) => {
      const isMove = e.operation === 2;
      if (isMove || e.operation === 1) {
        for (const pair of e.files) {
          const removed = isMove ? pair.source : pair.target;
          if (removed) {
            this.f.remove(removed);
          }
        }
      }
    }));
  }
  dispose() {
    $Xc(this.c.values());
    this.c.clear();
    super.dispose();
  }
  isCaughtUpWithContentChanges(resource) {
    const tracker2 = this.c.get(resource);
    if (tracker2) {
      return tracker2.isCaughtUpWithContentChanges();
    }
    return true;
  }
  u(resource) {
    const model = this.g.getModel(resource);
    return !!model && $kG(model);
  }
  handleModelAdded(model) {
    if (!$kG(model)) {
      return;
    }
    this.c.set(model.uri, new ModelTracker(model, this.a, this.b, this.h));
  }
  w(event) {
    const { model } = event;
    if (!this.c.has(model.uri)) {
      return;
    }
    this.b.$acceptModelLanguageChanged(model.uri, model.getLanguageId());
  }
  handleModelRemoved(modelUrl) {
    if (!this.c.has(modelUrl)) {
      return;
    }
    this.c.get(modelUrl).dispose();
    this.c.delete(modelUrl);
  }
  // --- from extension host process
  async $trySaveDocument(uri) {
    const target = await this.h.save(URI.revive(uri));
    return Boolean(target);
  }
  async $tryOpenDocument(uriData) {
    const inputUri = URI.revive(uriData);
    if (!inputUri.scheme || !(inputUri.fsPath || inputUri.authority)) {
      throw new $ub(`Invalid uri. Scheme and authority or path must be set.`);
    }
    const canonicalUri = this.s.asCanonicalUri(inputUri);
    let promise;
    switch (canonicalUri.scheme) {
      case Schemas.untitled:
        promise = this.z(canonicalUri);
        break;
      case Schemas.file:
      default:
        promise = this.y(canonicalUri);
        break;
    }
    let documentUri;
    try {
      documentUri = await promise;
    } catch (err) {
      throw new $ub(`cannot open ${canonicalUri.toString()}. Detail: ${$1m(err)}`);
    }
    if (!documentUri) {
      throw new $ub(`cannot open ${canonicalUri.toString()}`);
    } else if (!$lh.isEqual(documentUri, canonicalUri)) {
      throw new $ub(`cannot open ${canonicalUri.toString()}. Detail: Actual document opened as ${documentUri.toString()}`);
    } else if (!this.c.has(canonicalUri)) {
      throw new $ub(`cannot open ${canonicalUri.toString()}. Detail: Files above 50MB cannot be synchronized with extensions.`);
    } else {
      return canonicalUri;
    }
  }
  $tryCreateDocument(options3) {
    return this.C(void 0, options3 ? options3.language : void 0, options3 ? options3.content : void 0);
  }
  async y(uri) {
    const ref = await this.n.createModelReference(uri);
    this.f.add(uri, ref, ref.object.textEditorModel.getValueLength());
    return ref.object.textEditorModel.uri;
  }
  async z(uri) {
    const asLocalUri = $Fh(uri, this.r.remoteAuthority, this.t.defaultUriScheme);
    const exists = await this.j.exists(asLocalUri);
    if (exists) {
      return Promise.reject(new Error("file already exists"));
    }
    return await this.C(Boolean(uri.path) ? uri : void 0);
  }
  async C(associatedResource, languageId, initialValue) {
    const model = this.h.untitled.create({
      associatedResource,
      languageId,
      initialValue
    });
    const resource = model.resource;
    const ref = await this.n.createModelReference(resource);
    if (!this.c.has(resource)) {
      ref.dispose();
      throw new Error(`expected URI ${resource.toString()} to have come to LIFE`);
    }
    this.f.add(resource, ref, ref.object.textEditorModel.getValueLength());
    Event2.once(model.onDidRevert)(() => this.f.remove(resource));
    this.b.$acceptDirtyStateChanged(resource, true);
    return resource;
  }
};
$EOb = __decorate([
  __param(1, $sG),
  __param(2, $cK),
  __param(3, $km),
  __param(4, $oG),
  __param(5, $US),
  __param(6, $vl),
  __param(7, $aK),
  __param(8, $aT)
], $EOb);

// out-build/vs/workbench/api/browser/mainThreadEditor.js
var $FOb = class _$FOb {
  static readFromEditor(previousProperties, model, codeEditor) {
    const selections = _$FOb.c(previousProperties, codeEditor);
    const options3 = _$FOb.d(previousProperties, model, codeEditor);
    const visibleRanges = _$FOb.f(previousProperties, codeEditor);
    return new _$FOb(selections, options3, visibleRanges);
  }
  static c(previousProperties, codeEditor) {
    let result = null;
    if (codeEditor) {
      result = codeEditor.getSelections();
    }
    if (!result && previousProperties) {
      result = previousProperties.selections;
    }
    if (!result) {
      result = [new $_D(1, 1, 1, 1)];
    }
    return result;
  }
  static d(previousProperties, model, codeEditor) {
    if (model.isDisposed()) {
      if (previousProperties) {
        return previousProperties.options;
      } else {
        throw new Error("No valid properties");
      }
    }
    let cursorStyle;
    let lineNumbers;
    if (codeEditor) {
      const options3 = codeEditor.getOptions();
      const lineNumbersOpts = options3.get(
        69
        /* EditorOption.lineNumbers */
      );
      cursorStyle = options3.get(
        28
        /* EditorOption.cursorStyle */
      );
      lineNumbers = lineNumbersOpts.renderType;
    } else if (previousProperties) {
      cursorStyle = previousProperties.options.cursorStyle;
      lineNumbers = previousProperties.options.lineNumbers;
    } else {
      cursorStyle = TextEditorCursorStyle.Line;
      lineNumbers = 1;
    }
    const modelOptions = model.getOptions();
    return {
      insertSpaces: modelOptions.insertSpaces,
      tabSize: modelOptions.tabSize,
      indentSize: modelOptions.indentSize,
      originalIndentSize: modelOptions.originalIndentSize,
      cursorStyle,
      lineNumbers
    };
  }
  static f(previousProperties, codeEditor) {
    if (codeEditor) {
      return codeEditor.getVisibleRanges();
    }
    return [];
  }
  constructor(selections, options3, visibleRanges) {
    this.selections = selections;
    this.options = options3;
    this.visibleRanges = visibleRanges;
  }
  generateDelta(oldProps, selectionChangeSource) {
    const delta = {
      options: null,
      selections: null,
      visibleRanges: null
    };
    if (!oldProps || !_$FOb.g(oldProps.selections, this.selections)) {
      delta.selections = {
        selections: this.selections,
        source: selectionChangeSource ?? void 0
      };
    }
    if (!oldProps || !_$FOb.j(oldProps.options, this.options)) {
      delta.options = this.options;
    }
    if (!oldProps || !_$FOb.h(oldProps.visibleRanges, this.visibleRanges)) {
      delta.visibleRanges = this.visibleRanges;
    }
    if (delta.selections || delta.options || delta.visibleRanges) {
      return delta;
    }
    return null;
  }
  static g(a, b) {
    return $zb(a, b, (aValue, bValue) => aValue.equalsSelection(bValue));
  }
  static h(a, b) {
    return $zb(a, b, (aValue, bValue) => aValue.equalsRange(bValue));
  }
  static j(a, b) {
    if (a && !b || !a && b) {
      return false;
    }
    if (!a && !b) {
      return true;
    }
    return a.tabSize === b.tabSize && a.indentSize === b.indentSize && a.insertSpaces === b.insertSpaces && a.cursorStyle === b.cursorStyle && a.lineNumbers === b.lineNumbers;
  }
};
var $GOb = class {
  constructor(id2, model, codeEditor, focusTracker, mainThreadDocuments, modelService, clipboardService) {
    this.j = new $2c();
    this.m = new $2c();
    this.c = id2;
    this.d = model;
    this.k = null;
    this.n = null;
    this.l = focusTracker;
    this.f = mainThreadDocuments;
    this.g = modelService;
    this.h = clipboardService;
    this.o = new $ze();
    this.j.add(this.d.onDidChangeOptions((e) => {
      this.p(null);
    }));
    this.setCodeEditor(codeEditor);
    this.p(null);
  }
  dispose() {
    this.j.dispose();
    this.k = null;
    this.m.dispose();
  }
  p(selectionChangeSource) {
    this.q($FOb.readFromEditor(this.n, this.d, this.k), selectionChangeSource);
  }
  q(newProperties, selectionChangeSource) {
    const delta = newProperties.generateDelta(this.n, selectionChangeSource);
    this.n = newProperties;
    if (delta) {
      this.o.fire(delta);
    }
  }
  getId() {
    return this.c;
  }
  getModel() {
    return this.d;
  }
  getCodeEditor() {
    return this.k;
  }
  hasCodeEditor(codeEditor) {
    return this.k === codeEditor;
  }
  setCodeEditor(codeEditor) {
    if (this.hasCodeEditor(codeEditor)) {
      return;
    }
    this.m.clear();
    this.k = codeEditor;
    if (this.k) {
      this.m.add(this.k.onDidChangeModel(() => {
        this.setCodeEditor(null);
      }));
      this.m.add(this.k.onDidFocusEditorWidget(() => {
        this.l.onGainedFocus();
      }));
      this.m.add(this.k.onDidBlurEditorWidget(() => {
        this.l.onLostFocus();
      }));
      let nextSelectionChangeSource = null;
      this.m.add(this.f.onIsCaughtUpWithContentChanges((uri) => {
        if (uri.toString() === this.d.uri.toString()) {
          const selectionChangeSource = nextSelectionChangeSource;
          nextSelectionChangeSource = null;
          this.p(selectionChangeSource);
        }
      }));
      const isValidCodeEditor = () => {
        return this.k && this.k.getModel() === this.d;
      };
      const updateProperties = (selectionChangeSource) => {
        if (this.f.isCaughtUpWithContentChanges(this.d.uri)) {
          nextSelectionChangeSource = null;
          this.p(selectionChangeSource);
        } else {
          nextSelectionChangeSource = selectionChangeSource;
        }
      };
      this.m.add(this.k.onDidChangeCursorSelection((e) => {
        if (!isValidCodeEditor()) {
          return;
        }
        updateProperties(e.source);
      }));
      this.m.add(this.k.onDidChangeConfiguration((e) => {
        if (!isValidCodeEditor()) {
          return;
        }
        updateProperties(null);
      }));
      this.m.add(this.k.onDidLayoutChange(() => {
        if (!isValidCodeEditor()) {
          return;
        }
        updateProperties(null);
      }));
      this.m.add(this.k.onDidScrollChange(() => {
        if (!isValidCodeEditor()) {
          return;
        }
        updateProperties(null);
      }));
      this.p(null);
    }
  }
  isVisible() {
    return !!this.k;
  }
  getProperties() {
    return this.n;
  }
  get onPropertiesChanged() {
    return this.o.event;
  }
  setSelections(selections) {
    if (this.k) {
      this.k.setSelections(selections);
      return;
    }
    const newSelections = selections.map($_D.liftSelection);
    this.q(new $FOb(newSelections, this.n.options, this.n.visibleRanges), null);
  }
  r(newConfiguration) {
    const creationOpts = this.g.getCreationOptions(this.d.getLanguageId(), this.d.uri, this.d.isForSimpleWidget);
    if (newConfiguration.tabSize === "auto" || newConfiguration.insertSpaces === "auto") {
      let insertSpaces = creationOpts.insertSpaces;
      let tabSize = creationOpts.tabSize;
      if (newConfiguration.insertSpaces !== "auto" && typeof newConfiguration.insertSpaces !== "undefined") {
        insertSpaces = newConfiguration.insertSpaces;
      }
      if (newConfiguration.tabSize !== "auto" && typeof newConfiguration.tabSize !== "undefined") {
        tabSize = newConfiguration.tabSize;
      }
      this.d.detectIndentation(insertSpaces, tabSize);
      return;
    }
    const newOpts = {};
    if (typeof newConfiguration.insertSpaces !== "undefined") {
      newOpts.insertSpaces = newConfiguration.insertSpaces;
    }
    if (typeof newConfiguration.tabSize !== "undefined") {
      newOpts.tabSize = newConfiguration.tabSize;
    }
    if (typeof newConfiguration.indentSize !== "undefined") {
      newOpts.indentSize = newConfiguration.indentSize;
    }
    this.d.updateOptions(newOpts);
  }
  setConfiguration(newConfiguration) {
    this.r(newConfiguration);
    if (!this.k) {
      return;
    }
    if (newConfiguration.cursorStyle) {
      const newCursorStyle = cursorStyleToString(newConfiguration.cursorStyle);
      this.k.updateOptions({
        cursorStyle: newCursorStyle
      });
    }
    if (typeof newConfiguration.lineNumbers !== "undefined") {
      let lineNumbers;
      switch (newConfiguration.lineNumbers) {
        case 1:
          lineNumbers = "on";
          break;
        case 2:
          lineNumbers = "relative";
          break;
        case 3:
          lineNumbers = "interval";
          break;
        default:
          lineNumbers = "off";
      }
      this.k.updateOptions({
        lineNumbers
      });
    }
  }
  setDecorations(key2, ranges) {
    if (!this.k) {
      return;
    }
    this.k.setDecorationsByType("exthost-api", key2, ranges);
  }
  setDecorationsFast(key2, _ranges) {
    if (!this.k) {
      return;
    }
    const ranges = [];
    for (let i2 = 0, len = Math.floor(_ranges.length / 4); i2 < len; i2++) {
      ranges[i2] = new $9C(_ranges[4 * i2], _ranges[4 * i2 + 1], _ranges[4 * i2 + 2], _ranges[4 * i2 + 3]);
    }
    this.k.setDecorationsByTypeFast(key2, ranges);
  }
  revealRange(range, revealType) {
    if (!this.k) {
      return;
    }
    switch (revealType) {
      case TextEditorRevealType2.Default:
        this.k.revealRange(
          range,
          0
          /* ScrollType.Smooth */
        );
        break;
      case TextEditorRevealType2.InCenter:
        this.k.revealRangeInCenter(
          range,
          0
          /* ScrollType.Smooth */
        );
        break;
      case TextEditorRevealType2.InCenterIfOutsideViewport:
        this.k.revealRangeInCenterIfOutsideViewport(
          range,
          0
          /* ScrollType.Smooth */
        );
        break;
      case TextEditorRevealType2.AtTop:
        this.k.revealRangeAtTop(
          range,
          0
          /* ScrollType.Smooth */
        );
        break;
      default:
        console.warn(`Unknown revealType: ${revealType}`);
        break;
    }
  }
  isFocused() {
    if (this.k) {
      return this.k.hasTextFocus();
    }
    return false;
  }
  matches(editor) {
    if (!editor) {
      return false;
    }
    return editor.getControl() === this.k;
  }
  applyEdits(versionIdCheck, edits, opts) {
    if (this.d.getVersionId() !== versionIdCheck) {
      return false;
    }
    if (!this.k) {
      return false;
    }
    if (typeof opts.setEndOfLine !== "undefined") {
      this.d.pushEOL(opts.setEndOfLine);
    }
    const transformedEdits = edits.map((edit3) => {
      return {
        range: $9C.lift(edit3.range),
        text: edit3.text,
        forceMoveMarkers: edit3.forceMoveMarkers
      };
    });
    if (opts.undoStopBefore) {
      this.k.pushUndoStop();
    }
    this.k.executeEdits("MainThreadTextEditor", transformedEdits);
    if (opts.undoStopAfter) {
      this.k.pushUndoStop();
    }
    return true;
  }
  async insertSnippet(modelVersionId, template, ranges, opts) {
    if (!this.k || !this.k.hasModel()) {
      return false;
    }
    let clipboardText;
    const needsTemplate = $0_.guessNeedsClipboard(template);
    if (needsTemplate) {
      const state = new $M_(
        this.k,
        1 | 4
        /* CodeEditorStateFlag.Position */
      );
      clipboardText = await this.h.readText();
      if (!state.validate(this.k)) {
        return false;
      }
    }
    if (this.k.getModel().getVersionId() !== modelVersionId) {
      return false;
    }
    const snippetController = $Dcb.get(this.k);
    if (!snippetController) {
      return false;
    }
    this.k.focus();
    const edits = ranges.map((range) => ({ range: $9C.lift(range), template }));
    snippetController.apply(edits, {
      overwriteBefore: 0,
      overwriteAfter: 0,
      undoStopBefore: opts.undoStopBefore,
      undoStopAfter: opts.undoStopAfter,
      clipboardText
    });
    return true;
  }
};

// out-build/vs/workbench/contrib/scm/browser/diff.js
var $HOb = $Qk("IDirtyDiffModelService");
var $IOb = class $IOb2 extends $3c {
  constructor(f, g, h3, j) {
    super();
    this.f = f;
    this.g = g;
    this.h = h3;
    this.j = j;
    this.a = new $Ec();
    this.b = new $Ec();
    this.c = $Dd(this.f.onDidVisibleEditorsChange, () => this.f.visibleTextEditorControls);
    this.B($td((reader) => {
      const visibleTextEditorControls = this.c.read(reader);
      for (const [uri, dirtyDiffModel] of this.a) {
        const textEditorControl = visibleTextEditorControls.find((editor) => $P5(editor) && this.j.extUri.isEqual(editor.getModel()?.uri, uri));
        if (textEditorControl) {
          continue;
        }
        dirtyDiffModel.dispose();
        this.a.delete(uri);
      }
      for (const [uri, dirtyDiffModel] of this.b) {
        const diffEditorControl = visibleTextEditorControls.find((editor) => $Q5(editor) && this.j.extUri.isEqual(editor.getModel()?.modified.uri, uri));
        if (diffEditorControl) {
          continue;
        }
        for (const algorithm of dirtyDiffModel.keys()) {
          dirtyDiffModel.get(algorithm)?.dispose();
          dirtyDiffModel.delete(algorithm);
        }
        this.b.delete(uri);
      }
    }));
  }
  getDirtyDiffModel(uri) {
    let model = this.a.get(uri);
    if (model) {
      return model;
    }
    const textFileModel = this.h.files.get(uri);
    if (!textFileModel?.isResolved()) {
      return void 0;
    }
    model = this.g.createInstance($QEb, textFileModel, void 0);
    this.a.set(uri, model);
    return model;
  }
  getDiffModel(uri, algorithm) {
    let model = this.b.get(uri)?.get(algorithm);
    if (model) {
      return model;
    }
    const textFileModel = this.h.files.get(uri);
    if (!textFileModel?.isResolved()) {
      return void 0;
    }
    model = this.g.createInstance($QEb, textFileModel, algorithm);
    if (!this.b.has(uri)) {
      this.b.set(uri, /* @__PURE__ */ new Map());
    }
    this.b.get(uri).set(algorithm, model);
    return model;
  }
};
$IOb = __decorate([
  __param(0, $mJ),
  __param(1, $Pk),
  __param(2, $cK),
  __param(3, $vl)
], $IOb);
$SC(
  $HOb,
  $IOb,
  1
  /* InstantiationType.Delayed */
);

// out-build/vs/workbench/api/browser/mainThreadEditors.js
var $JOb_1;
var $JOb = class $JOb2 {
  static {
    $JOb_1 = this;
  }
  static {
    this.c = 0;
  }
  constructor(k, extHostContext, l, m, n, o, p, q) {
    this.k = k;
    this.l = l;
    this.m = m;
    this.n = n;
    this.o = o;
    this.p = p;
    this.q = q;
    this.g = new $2c();
    this.e = String(++$JOb_1.c);
    this.f = extHostContext.getProxy($yT.ExtHostEditors);
    this.h = /* @__PURE__ */ Object.create(null);
    this.i = null;
    this.g.add(this.m.onDidVisibleEditorsChange(() => this.r()));
    this.g.add(this.n.onDidRemoveGroup(() => this.r()));
    this.g.add(this.n.onDidMoveGroup(() => this.r()));
    this.j = /* @__PURE__ */ Object.create(null);
  }
  dispose() {
    Object.keys(this.h).forEach((editorId) => {
      $Xc(this.h[editorId]);
    });
    this.h = /* @__PURE__ */ Object.create(null);
    this.g.dispose();
    for (const decorationType in this.j) {
      this.l.removeDecorationType(decorationType);
    }
    this.j = /* @__PURE__ */ Object.create(null);
  }
  handleTextEditorAdded(textEditor) {
    const id2 = textEditor.getId();
    const toDispose = [];
    toDispose.push(textEditor.onPropertiesChanged((data) => {
      this.f.$acceptEditorPropertiesChanged(id2, data);
    }));
    const diffInformationObs = this.t(textEditor);
    toDispose.push($td((reader) => {
      const diffInformation = diffInformationObs.read(reader);
      this.f.$acceptEditorDiffInformation(id2, diffInformation);
    }));
    this.h[id2] = toDispose;
  }
  handleTextEditorRemoved(id2) {
    $Xc(this.h[id2]);
    delete this.h[id2];
  }
  r() {
    const editorPositionData = this.s();
    if (!$Pv(this.i, editorPositionData)) {
      this.i = editorPositionData;
      this.f.$acceptEditorPositionData(this.i);
    }
  }
  s() {
    const result = /* @__PURE__ */ Object.create(null);
    for (const editorPane of this.m.visibleEditorPanes) {
      const id2 = this.k.findTextEditorIdFor(editorPane);
      if (id2) {
        result[id2] = $AS(this.n, editorPane.group);
      }
    }
    return result;
  }
  t(textEditor) {
    const codeEditor = textEditor.getCodeEditor();
    if (!codeEditor) {
      return $Bd(void 0);
    }
    const diffEditors = this.l.listDiffEditors();
    const [diffEditor] = diffEditors.filter((d) => d.getOriginalEditor().getId() === codeEditor.getId() || d.getModifiedEditor().getId() === codeEditor.getId());
    const editorModelObs = diffEditor ? $Dd(this, diffEditor.onDidChangeModel, () => diffEditor.getModel()) : $Dd(this, codeEditor.onDidChangeModel, () => codeEditor.getModel());
    const editorChangesObs = $2d((reader) => {
      const editorModel = editorModelObs.read(reader);
      if (!editorModel) {
        return $Bd(void 0);
      }
      const editorModelUri = $gG(editorModel) ? editorModel.uri : editorModel.modified.uri;
      if ($gG(editorModel)) {
        const dirtyDiffModel2 = this.p.getDirtyDiffModel(editorModelUri);
        if (!dirtyDiffModel2) {
          return $Bd(void 0);
        }
        return $Dd(this, dirtyDiffModel2.onDidChange, () => {
          return dirtyDiffModel2.getQuickDiffResults();
        });
      }
      const diffAlgorithm = this.o.getValue("diffEditor.diffAlgorithm");
      const dirtyDiffModel = this.p.getDiffModel(editorModelUri, diffAlgorithm);
      if (!dirtyDiffModel) {
        return $Bd(void 0);
      }
      return $Dd(Event2.any(dirtyDiffModel.onDidChange, diffEditor.onDidUpdateDiff), () => {
        const dirtyDiffInformation = dirtyDiffModel.getQuickDiffResults();
        const diffChanges = diffEditor.getDiffComputationResult()?.changes2 ?? [];
        const diffInformation = [{
          original: editorModel.original.uri,
          modified: editorModel.modified.uri,
          changes: diffChanges.map((change) => change)
        }];
        return [...dirtyDiffInformation, ...diffInformation];
      });
    });
    return $4d({
      owner: this,
      equalsFn: (diff1, diff22) => $zb(diff1, diff22, (a, b) => $xl(this.q, a, b))
    }, (reader) => {
      const editorModel = editorModelObs.read(reader);
      const editorChanges = editorChangesObs.read(reader).read(reader);
      if (!editorModel || !editorChanges) {
        return void 0;
      }
      const documentVersion = $gG(editorModel) ? editorModel.getVersionId() : editorModel.modified.getVersionId();
      return editorChanges.map((change) => {
        const changes = change.changes.map((change2) => [
          change2.original.startLineNumber,
          change2.original.endLineNumberExclusive,
          change2.modified.startLineNumber,
          change2.modified.endLineNumberExclusive
        ]);
        return {
          documentVersion,
          original: change.original,
          modified: change.modified,
          changes
        };
      });
    });
  }
  // --- from extension host process
  async $tryShowTextDocument(resource, options3) {
    const uri = URI.revive(resource);
    const editorOptions2 = {
      preserveFocus: options3.preserveFocus,
      pinned: options3.pinned,
      selection: options3.selection,
      // preserve pre 1.38 behaviour to not make group active when preserveFocus: true
      // but make sure to restore the editor to fix https://github.com/microsoft/vscode/issues/79633
      activation: options3.preserveFocus ? EditorActivation.RESTORE : void 0,
      override: EditorResolution.EXCLUSIVE_ONLY
    };
    const input = {
      resource: uri,
      options: editorOptions2
    };
    const editor = await this.m.openEditor(input, $zS(this.n, this.o, options3.position));
    if (!editor) {
      return void 0;
    }
    const editorControl = editor.getControl();
    const codeEditor = $S5(editorControl);
    return codeEditor ? this.k.getIdOfCodeEditor(codeEditor) : void 0;
  }
  async $tryShowEditor(id2, position) {
    const mainThreadEditor = this.k.getEditor(id2);
    if (mainThreadEditor) {
      const model = mainThreadEditor.getModel();
      await this.m.openEditor({
        resource: model.uri,
        options: { preserveFocus: false }
      }, $zS(this.n, this.o, position));
      return;
    }
  }
  async $tryHideEditor(id2) {
    const mainThreadEditor = this.k.getEditor(id2);
    if (mainThreadEditor) {
      const editorPanes = this.m.visibleEditorPanes;
      for (const editorPane of editorPanes) {
        if (mainThreadEditor.matches(editorPane)) {
          await editorPane.group.closeEditor(editorPane.input);
          return;
        }
      }
    }
  }
  $trySetSelections(id2, selections) {
    const editor = this.k.getEditor(id2);
    if (!editor) {
      return Promise.reject($nb(`TextEditor(${id2})`));
    }
    editor.setSelections(selections);
    return Promise.resolve(void 0);
  }
  $trySetDecorations(id2, key2, ranges) {
    key2 = `${this.e}-${key2}`;
    const editor = this.k.getEditor(id2);
    if (!editor) {
      return Promise.reject($nb(`TextEditor(${id2})`));
    }
    editor.setDecorations(key2, ranges);
    return Promise.resolve(void 0);
  }
  $trySetDecorationsFast(id2, key2, ranges) {
    key2 = `${this.e}-${key2}`;
    const editor = this.k.getEditor(id2);
    if (!editor) {
      return Promise.reject($nb(`TextEditor(${id2})`));
    }
    editor.setDecorationsFast(key2, ranges);
    return Promise.resolve(void 0);
  }
  $tryRevealRange(id2, range, revealType) {
    const editor = this.k.getEditor(id2);
    if (!editor) {
      return Promise.reject($nb(`TextEditor(${id2})`));
    }
    editor.revealRange(range, revealType);
    return Promise.resolve();
  }
  $trySetOptions(id2, options3) {
    const editor = this.k.getEditor(id2);
    if (!editor) {
      return Promise.reject($nb(`TextEditor(${id2})`));
    }
    editor.setConfiguration(options3);
    return Promise.resolve(void 0);
  }
  $tryApplyEdits(id2, modelVersionId, edits, opts) {
    const editor = this.k.getEditor(id2);
    if (!editor) {
      return Promise.reject($nb(`TextEditor(${id2})`));
    }
    return Promise.resolve(editor.applyEdits(modelVersionId, edits, opts));
  }
  $tryInsertSnippet(id2, modelVersionId, template, ranges, opts) {
    const editor = this.k.getEditor(id2);
    if (!editor) {
      return Promise.reject($nb(`TextEditor(${id2})`));
    }
    return Promise.resolve(editor.insertSnippet(modelVersionId, template, ranges, opts));
  }
  $registerTextEditorDecorationType(extensionId, key2, options3) {
    key2 = `${this.e}-${key2}`;
    this.j[key2] = true;
    this.l.registerDecorationType(`exthost-api-${extensionId}`, key2, options3);
  }
  $removeTextEditorDecorationType(key2) {
    key2 = `${this.e}-${key2}`;
    delete this.j[key2];
    this.l.removeDecorationType(key2);
  }
  $getDiffInformation(id2) {
    const editor = this.k.getEditor(id2);
    if (!editor) {
      return Promise.reject(new Error("No such TextEditor"));
    }
    const codeEditor = editor.getCodeEditor();
    if (!codeEditor) {
      return Promise.reject(new Error("No such CodeEditor"));
    }
    const codeEditorId = codeEditor.getId();
    const diffEditors = this.l.listDiffEditors();
    const [diffEditor] = diffEditors.filter((d) => d.getOriginalEditor().getId() === codeEditorId || d.getModifiedEditor().getId() === codeEditorId);
    if (diffEditor) {
      return Promise.resolve(diffEditor.getLineChanges() || []);
    }
    const dirtyDiffContribution = codeEditor.getContribution("editor.contrib.dirtydiff");
    if (dirtyDiffContribution) {
      return Promise.resolve(dirtyDiffContribution.getChanges());
    }
    return Promise.resolve([]);
  }
};
$JOb = $JOb_1 = __decorate([
  __param(2, $U5),
  __param(3, $mJ),
  __param(4, $iJ),
  __param(5, $kl),
  __param(6, $HOb),
  __param(7, $vl)
], $JOb);
$tn.registerCommand("_workbench.revertAllDirty", async function(accessor) {
  const environmentService = accessor.get($Xk);
  if (!environmentService.extensionTestsLocationURI) {
    throw new Error("Command is only available when running extension tests.");
  }
  const workingCopyService = accessor.get($XI);
  for (const workingCopy of workingCopyService.dirtyWorkingCopies) {
    await workingCopy.revert({ soft: true });
  }
});

// out-build/vs/workbench/api/browser/mainThreadDocumentsAndEditors.js
var TextEditorSnapshot = class {
  constructor(editor) {
    this.editor = editor;
    this.id = `${editor.getId()},${editor.getModel().id}`;
  }
};
var DocumentAndEditorStateDelta = class {
  constructor(removedDocuments, addedDocuments, removedEditors, addedEditors, oldActiveEditor, newActiveEditor) {
    this.removedDocuments = removedDocuments;
    this.addedDocuments = addedDocuments;
    this.removedEditors = removedEditors;
    this.addedEditors = addedEditors;
    this.oldActiveEditor = oldActiveEditor;
    this.newActiveEditor = newActiveEditor;
    this.isEmpty = this.removedDocuments.length === 0 && this.addedDocuments.length === 0 && this.removedEditors.length === 0 && this.addedEditors.length === 0 && oldActiveEditor === newActiveEditor;
  }
  toString() {
    let ret = "DocumentAndEditorStateDelta\n";
    ret += `	Removed Documents: [${this.removedDocuments.map((d) => d.uri.toString(true)).join(", ")}]
`;
    ret += `	Added Documents: [${this.addedDocuments.map((d) => d.uri.toString(true)).join(", ")}]
`;
    ret += `	Removed Editors: [${this.removedEditors.map((e) => e.id).join(", ")}]
`;
    ret += `	Added Editors: [${this.addedEditors.map((e) => e.id).join(", ")}]
`;
    ret += `	New Active Editor: ${this.newActiveEditor}
`;
    return ret;
  }
};
var DocumentAndEditorState = class {
  static compute(before, after) {
    if (!before) {
      return new DocumentAndEditorStateDelta([], [...after.documents.values()], [], [...after.textEditors.values()], void 0, after.activeEditor);
    }
    const documentDelta = $b(before.documents, after.documents);
    const editorDelta = $c(before.textEditors, after.textEditors);
    const oldActiveEditor = before.activeEditor !== after.activeEditor ? before.activeEditor : void 0;
    const newActiveEditor = before.activeEditor !== after.activeEditor ? after.activeEditor : void 0;
    return new DocumentAndEditorStateDelta(documentDelta.removed, documentDelta.added, editorDelta.removed, editorDelta.added, oldActiveEditor, newActiveEditor);
  }
  constructor(documents, textEditors, activeEditor) {
    this.documents = documents;
    this.textEditors = textEditors;
    this.activeEditor = activeEditor;
  }
};
var ActiveEditorOrder;
(function(ActiveEditorOrder2) {
  ActiveEditorOrder2[ActiveEditorOrder2["Editor"] = 0] = "Editor";
  ActiveEditorOrder2[ActiveEditorOrder2["Panel"] = 1] = "Panel";
})(ActiveEditorOrder || (ActiveEditorOrder = {}));
var MainThreadDocumentAndEditorStateComputer = class MainThreadDocumentAndEditorStateComputer2 {
  constructor(g, h3, i2, j, k) {
    this.g = g;
    this.h = h3;
    this.i = i2;
    this.j = j;
    this.k = k;
    this.a = new $2c();
    this.b = new $_c();
    this.f = 0;
    this.h.onModelAdded(this.o, this, this.a);
    this.h.onModelRemoved((_) => this.p(), this, this.a);
    this.j.onDidActiveEditorChange((_) => this.p(), this, this.a);
    this.i.onCodeEditorAdd(this.l, this, this.a);
    this.i.onCodeEditorRemove(this.n, this, this.a);
    this.i.listCodeEditors().forEach(this.l, this);
    Event2.filter(
      this.k.onDidPaneCompositeOpen,
      (event) => event.viewContainerLocation === 1
      /* ViewContainerLocation.Panel */
    )((_) => this.f = 1, void 0, this.a);
    Event2.filter(
      this.k.onDidPaneCompositeClose,
      (event) => event.viewContainerLocation === 1
      /* ViewContainerLocation.Panel */
    )((_) => this.f = 0, void 0, this.a);
    this.j.onDidVisibleEditorsChange((_) => this.f = 0, void 0, this.a);
    this.p();
  }
  dispose() {
    this.a.dispose();
    this.b.dispose();
  }
  l(e) {
    this.b.set(e.getId(), $Zc(e.onDidChangeModel(() => this.p()), e.onDidFocusEditorText(() => this.p()), e.onDidFocusEditorWidget(() => this.p(e))));
    this.p();
  }
  n(e) {
    const id2 = e.getId();
    if (this.b.has(id2)) {
      this.b.deleteAndDispose(id2);
      this.p();
    }
  }
  o(model) {
    if (!$kG(model)) {
      return;
    }
    if (!this.c) {
      this.p();
      return;
    }
    this.c = new DocumentAndEditorState(this.c.documents.add(model), this.c.textEditors, this.c.activeEditor);
    this.g(new DocumentAndEditorStateDelta([], [model], [], [], void 0, void 0));
  }
  p(widgetFocusCandidate) {
    const models = /* @__PURE__ */ new Set();
    for (const model of this.h.getModels()) {
      if ($kG(model)) {
        models.add(model);
      }
    }
    const editors = /* @__PURE__ */ new Map();
    let activeEditor = null;
    for (const editor of this.i.listCodeEditors()) {
      if (editor.isSimpleWidget) {
        continue;
      }
      const model = editor.getModel();
      if (editor.hasModel() && model && $kG(model) && !model.isDisposed() && Boolean(this.h.getModel(model.uri))) {
        const apiEditor = new TextEditorSnapshot(editor);
        editors.set(apiEditor.id, apiEditor);
        if (editor.hasTextFocus() || widgetFocusCandidate === editor && editor.hasWidgetFocus()) {
          activeEditor = apiEditor.id;
        }
      }
    }
    if (!activeEditor) {
      let candidate;
      if (this.f === 0) {
        candidate = this.r() || this.q();
      } else {
        candidate = this.q() || this.r();
      }
      if (candidate) {
        for (const snapshot of editors.values()) {
          if (candidate === snapshot.editor) {
            activeEditor = snapshot.id;
          }
        }
      }
    }
    const newState = new DocumentAndEditorState(models, editors, activeEditor);
    const delta = DocumentAndEditorState.compute(this.c, newState);
    if (!delta.isEmpty) {
      this.c = newState;
      this.g(delta);
    }
  }
  q() {
    const panel = this.k.getActivePaneComposite(
      1
      /* ViewContainerLocation.Panel */
    );
    if (panel instanceof $aub) {
      const control = panel.getControl();
      if ($P5(control)) {
        return control;
      }
    }
    return void 0;
  }
  r() {
    let activeTextEditorControl = this.j.activeTextEditorControl;
    if ($Q5(activeTextEditorControl)) {
      activeTextEditorControl = activeTextEditorControl.getModifiedEditor();
    }
    return activeTextEditorControl;
  }
};
MainThreadDocumentAndEditorStateComputer = __decorate([
  __param(1, $sG),
  __param(2, $U5),
  __param(3, $mJ),
  __param(4, $uqb)
], MainThreadDocumentAndEditorStateComputer);
var $KOb = class $KOb2 {
  constructor(extHostContext, h3, i2, j, codeEditorService, fileService, textModelResolverService, k, paneCompositeService, environmentService, workingCopyFileService, uriIdentityService, l, pathService, configurationService, dirtyDiffModelService) {
    this.h = h3;
    this.i = i2;
    this.j = j;
    this.k = k;
    this.l = l;
    this.a = new $2c();
    this.g = /* @__PURE__ */ new Map();
    this.b = extHostContext.getProxy($yT.ExtHostDocumentsAndEditors);
    this.c = this.a.add(new $EOb(extHostContext, this.h, this.i, fileService, textModelResolverService, environmentService, uriIdentityService, workingCopyFileService, pathService));
    extHostContext.set($xT.MainThreadDocuments, this.c);
    this.f = this.a.add(new $JOb(this, extHostContext, codeEditorService, this.j, this.k, configurationService, dirtyDiffModelService, uriIdentityService));
    extHostContext.set($xT.MainThreadTextEditors, this.f);
    this.a.add(new MainThreadDocumentAndEditorStateComputer((delta) => this.n(delta), h3, codeEditorService, this.j, paneCompositeService));
  }
  dispose() {
    this.a.dispose();
  }
  n(delta) {
    const removedEditors = [];
    const addedEditors = [];
    const removedDocuments = delta.removedDocuments.map((m) => m.uri);
    for (const apiEditor of delta.addedEditors) {
      const mainThreadEditor = new $GOb(apiEditor.id, apiEditor.editor.getModel(), apiEditor.editor, { onGainedFocus() {
      }, onLostFocus() {
      } }, this.c, this.h, this.l);
      this.g.set(apiEditor.id, mainThreadEditor);
      addedEditors.push(mainThreadEditor);
    }
    for (const { id: id2 } of delta.removedEditors) {
      const mainThreadEditor = this.g.get(id2);
      if (mainThreadEditor) {
        mainThreadEditor.dispose();
        this.g.delete(id2);
        removedEditors.push(id2);
      }
    }
    const extHostDelta = /* @__PURE__ */ Object.create(null);
    let empty = true;
    if (delta.newActiveEditor !== void 0) {
      empty = false;
      extHostDelta.newActiveEditor = delta.newActiveEditor;
    }
    if (removedDocuments.length > 0) {
      empty = false;
      extHostDelta.removedDocuments = removedDocuments;
    }
    if (removedEditors.length > 0) {
      empty = false;
      extHostDelta.removedEditors = removedEditors;
    }
    if (delta.addedDocuments.length > 0) {
      empty = false;
      extHostDelta.addedDocuments = delta.addedDocuments.map((m) => this.o(m));
    }
    if (delta.addedEditors.length > 0) {
      empty = false;
      extHostDelta.addedEditors = addedEditors.map((e) => this.p(e));
    }
    if (!empty) {
      this.b.$acceptDocumentsAndEditorsDelta(extHostDelta);
      removedDocuments.forEach(this.c.handleModelRemoved, this.c);
      delta.addedDocuments.forEach(this.c.handleModelAdded, this.c);
      removedEditors.forEach(this.f.handleTextEditorRemoved, this.f);
      addedEditors.forEach(this.f.handleTextEditorAdded, this.f);
    }
  }
  o(model) {
    return {
      uri: model.uri,
      versionId: model.getVersionId(),
      lines: model.getLinesContent(),
      EOL: model.getEOL(),
      languageId: model.getLanguageId(),
      isDirty: this.i.isDirty(model.uri)
    };
  }
  p(textEditor) {
    const props = textEditor.getProperties();
    return {
      id: textEditor.getId(),
      documentUri: textEditor.getModel().uri,
      options: props.options,
      selections: props.selections,
      visibleRanges: props.visibleRanges,
      editorPosition: this.q(textEditor)
    };
  }
  q(editor) {
    for (const editorPane of this.j.visibleEditorPanes) {
      if (editor.matches(editorPane)) {
        return $AS(this.k, editorPane.group);
      }
    }
    return void 0;
  }
  findTextEditorIdFor(editorPane) {
    for (const [id2, editor] of this.g) {
      if (editor.matches(editorPane)) {
        return id2;
      }
    }
    return void 0;
  }
  getIdOfCodeEditor(codeEditor) {
    for (const [id2, editor] of this.g) {
      if (editor.getCodeEditor() === codeEditor) {
        return id2;
      }
    }
    return void 0;
  }
  getEditor(id2) {
    return this.g.get(id2);
  }
};
$KOb = __decorate([
  $grb,
  __param(1, $sG),
  __param(2, $cK),
  __param(3, $mJ),
  __param(4, $U5),
  __param(5, $km),
  __param(6, $oG),
  __param(7, $iJ),
  __param(8, $uqb),
  __param(9, $US),
  __param(10, $aK),
  __param(11, $vl),
  __param(12, $30),
  __param(13, $aT),
  __param(14, $kl),
  __param(15, $HOb)
], $KOb);

// out-build/vs/workbench/contrib/customEditor/common/customEditor.js
var $LOb = $Qk("customEditorService");
var $MOb = new $nn("activeCustomEditorId", "", {
  type: "string",
  description: localize(5462, null)
});
var $NOb = new $nn("focusedCustomEditorIsEditable", false);
var CustomEditorPriority;
(function(CustomEditorPriority2) {
  CustomEditorPriority2["default"] = "default";
  CustomEditorPriority2["builtin"] = "builtin";
  CustomEditorPriority2["option"] = "option";
})(CustomEditorPriority || (CustomEditorPriority = {}));
var $OOb = class {
  constructor(descriptor) {
    this.id = descriptor.id;
    this.displayName = descriptor.displayName;
    this.providerDisplayName = descriptor.providerDisplayName;
    this.priority = descriptor.priority;
    this.selector = descriptor.selector;
  }
  matches(resource) {
    return this.selector.some((selector) => selector.filenamePattern && $7L(selector.filenamePattern, resource));
  }
};
var $POb = class {
  constructor(editors) {
    this.allEditors = $Rb(editors, (editor) => editor.id);
  }
  get length() {
    return this.allEditors.length;
  }
  /**
   * Find the single default editor to use (if any) by looking at the editor's priority and the
   * other contributed editors.
   */
  get defaultEditor() {
    return this.allEditors.find((editor) => {
      switch (editor.priority) {
        case RegisteredEditorPriority.default:
        case RegisteredEditorPriority.builtin:
          return this.allEditors.every((otherEditor) => otherEditor === editor || isLowerPriority(otherEditor, editor));
        default:
          return false;
      }
    });
  }
  /**
   * Find the best available editor to use.
   *
   * Unlike the `defaultEditor`, a bestAvailableEditor can exist even if there are other editors with
   * the same priority.
   */
  get bestAvailableEditor() {
    const editors = Array.from(this.allEditors).sort((a, b) => {
      return $6L(a.priority) - $6L(b.priority);
    });
    return editors[0];
  }
};
function isLowerPriority(otherEditor, editor) {
  return $6L(otherEditor.priority) < $6L(editor.priority);
}

// out-build/vs/workbench/contrib/webview/browser/webviewWindowDragMonitor.js
var $DJb = class extends $3c {
  constructor(targetWindow, getWebview) {
    super();
    const onDragStart = () => {
      getWebview()?.windowDidDragStart();
    };
    const onDragEnd = () => {
      getWebview()?.windowDidDragEnd();
    };
    this.B($_i(targetWindow, $7j.DRAG_START, () => {
      onDragStart();
    }));
    this.B($_i(targetWindow, $7j.DRAG_END, onDragEnd));
    this.B($_i(targetWindow, $7j.MOUSE_MOVE, (currentEvent) => {
      if (currentEvent.buttons === 0) {
        onDragEnd();
      }
    }));
    this.B($_i(targetWindow, $7j.DRAG, (event) => {
      if (event.shiftKey) {
        onDragEnd();
      } else {
        onDragStart();
      }
    }));
    this.B($_i(targetWindow, $7j.DRAG_OVER, (event) => {
      if (event.shiftKey) {
        onDragEnd();
      } else {
        onDragStart();
      }
    }));
  }
};

// out-build/vs/workbench/contrib/webviewPanel/browser/webviewEditorInput.js
var $8Lb = class _$8Lb extends $nG {
  static {
    this.typeId = "workbench.editors.webviewInput";
  }
  get typeId() {
    return _$8Lb.typeId;
  }
  get editorId() {
    return this.viewType;
  }
  get capabilities() {
    return 2 | 8 | 128;
  }
  get resource() {
    return URI.from({
      scheme: Schemas.webviewPanel,
      path: `webview-panel/webview-${this.a}`
    });
  }
  constructor(init, webview, s) {
    super();
    this.s = s;
    this.a = $ps();
    this.r = false;
    this.viewType = init.viewType;
    this.providedId = init.providedId;
    this.b = init.name;
    this.m = webview;
  }
  dispose() {
    if (!this.isDisposed()) {
      if (!this.r) {
        this.m?.dispose();
      }
    }
    super.dispose();
  }
  getName() {
    return this.b;
  }
  getTitle(_verbosity) {
    return this.getName();
  }
  getDescription() {
    return void 0;
  }
  setName(value) {
    this.b = value;
    this.webview.setTitle(value);
    this.g.fire();
  }
  get webview() {
    return this.m;
  }
  get extension() {
    return this.webview.extension;
  }
  get iconPath() {
    return this.c;
  }
  set iconPath(value) {
    this.c = value;
    this.s.setIcons(this.a, value);
  }
  matches(other) {
    return super.matches(other) || other === this;
  }
  get group() {
    return this.h;
  }
  updateGroup(group2) {
    this.h = group2;
  }
  t(other) {
    if (this.r) {
      return void 0;
    }
    this.r = true;
    other.m = this.m;
    return other;
  }
  claim(claimant, targetWindow, scopedContextKeyService) {
    return this.m.claim(claimant, targetWindow, scopedContextKeyService);
  }
};

// out-build/vs/workbench/contrib/webviewPanel/browser/webviewEditor.js
var $ROb_1;
var $QOb = new $nn("activeWebviewPanelId", "", {
  type: "string",
  description: localize(11806, null)
});
var $ROb = class $ROb2 extends $5tb {
  static {
    $ROb_1 = this;
  }
  static {
    this.ID = "WebviewEditor";
  }
  get onDidFocus() {
    return this.m.event;
  }
  constructor(group2, telemetryService, themeService, storageService, s, u, $149, cb, db) {
    super($ROb_1.ID, group2, telemetryService, themeService, storageService);
    this.s = s;
    this.u = u;
    this.$ = $149;
    this.cb = cb;
    this.db = db;
    this.c = false;
    this.f = false;
    this.g = this.B(new $2c());
    this.j = this.B(new $4c());
    this.m = this.B(new $ze());
    this.r = this.B(new $4c());
    const part = s.getPart(group2);
    this.B(Event2.any(part.onDidScroll, part.onDidAddGroup, part.onDidRemoveGroup, part.onDidMoveGroup)(() => {
      if (this.eb && this.c) {
        this.ib(this.eb);
      }
    }));
  }
  get eb() {
    return this.input instanceof $8Lb ? this.input.webview : void 0;
  }
  get scopedContextKeyService() {
    return this.r.value;
  }
  Y(parent) {
    const element = document.createElement("div");
    this.a = element;
    this.a.id = `webview-editor-element-${$ps()}`;
    parent.appendChild(element);
    this.r.value = this.B(this.db.createScoped(element));
  }
  dispose() {
    this.f = true;
    this.a?.remove();
    this.a = void 0;
    super.dispose();
  }
  layout(dimension) {
    this.b = dimension;
    if (this.eb && this.c) {
      this.ib(this.eb, dimension);
    }
  }
  focus() {
    super.focus();
    if (!this.j.value && !$r) {
      this.j.value = this.cb.onDidChangeFocus((focused) => {
        if (focused && this.u.activeEditorPane === this && this.$.hasFocus(
          "workbench.parts.editor"
          /* Parts.EDITOR_PART */
        )) {
          this.focus();
        }
      });
    }
    this.eb?.focus();
  }
  Z(visible) {
    this.c = visible;
    if (this.input instanceof $8Lb && this.eb) {
      if (visible) {
        this.hb(this.input);
      } else {
        this.eb.release(this);
      }
    }
    super.Z(visible);
  }
  clearInput() {
    if (this.eb) {
      this.eb.release(this);
      this.g.clear();
    }
    super.clearInput();
  }
  async setInput(input, options3, context, token) {
    if (this.input && input.matches(this.input)) {
      return;
    }
    const alreadyOwnsWebview = input instanceof $8Lb && input.webview === this.eb;
    if (this.eb && !alreadyOwnsWebview) {
      this.eb.release(this);
    }
    await super.setInput(input, options3, context, token);
    await input.resolve();
    if (token.isCancellationRequested || this.f) {
      return;
    }
    if (input instanceof $8Lb) {
      input.updateGroup(this.group.id);
      if (!alreadyOwnsWebview) {
        this.hb(input);
      }
      if (this.b) {
        this.layout(this.b);
      }
    }
  }
  hb(input) {
    input.claim(this, this.window, this.scopedContextKeyService);
    if (this.a) {
      this.a.setAttribute("aria-flowto", input.webview.container.id);
      $Ej(input.webview.container, this.a);
    }
    this.g.clear();
    this.g.add(this.s.createEditorDropTarget(input.webview.container, {
      containsGroup: (group2) => this.group.id === group2.id
    }));
    this.g.add(new $DJb(this.window, () => this.eb));
    this.ib(input.webview);
    this.g.add(this.jb(input.webview));
  }
  ib(webview, dimension) {
    if (!this.a?.isConnected) {
      return;
    }
    const rootContainer = this.$.getContainer(
      this.window,
      "workbench.parts.editor"
      /* Parts.EDITOR_PART */
    );
    webview.layoutWebviewOverElement(this.a.parentElement, dimension, rootContainer);
  }
  jb(webview) {
    const store = new $2c();
    const webviewContentFocusTracker = $_j(webview.container);
    store.add(webviewContentFocusTracker);
    store.add(webviewContentFocusTracker.onDidFocus(() => this.m.fire()));
    store.add(webview.onDidFocus(() => this.m.fire()));
    return store;
  }
};
$ROb = $ROb_1 = __decorate([
  __param(1, $zv),
  __param(2, $gs),
  __param(3, $jv),
  __param(4, $iJ),
  __param(5, $mJ),
  __param(6, $Vlb),
  __param(7, $S4),
  __param(8, $on)
], $ROb);

// out-build/vs/workbench/contrib/webviewPanel/browser/webviewIconManager.js
var $7Lb = class $7Lb2 extends $3c {
  constructor(c, f) {
    super();
    this.c = c;
    this.f = f;
    this.a = /* @__PURE__ */ new Map();
    this.B(this.f.onDidChangeConfiguration((e) => {
      if (e.affectsConfiguration("workbench.iconTheme")) {
        this.h();
      }
    }));
  }
  dispose() {
    super.dispose();
    this.b = void 0;
  }
  get g() {
    if (!this.b) {
      this.b = $VZ(void 0, void 0, this.q);
      this.b.className = "webview-icons";
    }
    return this.b;
  }
  setIcons(webviewId, iconPath) {
    if (iconPath) {
      this.a.set(webviewId, iconPath);
    } else {
      this.a.delete(webviewId);
    }
    this.h();
  }
  async h() {
    await this.c.when(
      1
      /* LifecyclePhase.Starting */
    );
    const cssRules = [];
    if (this.f.getValue("workbench.iconTheme") !== null) {
      for (const [key2, value] of this.a) {
        const webviewSelector = `.show-file-icons .webview-${key2}-name-file-icon::before`;
        try {
          cssRules.push(`.monaco-workbench.vs ${webviewSelector}, .monaco-workbench.hc-light ${webviewSelector} { content: ""; background-image: ${$5Z(value.light)}; }`, `.monaco-workbench.vs-dark ${webviewSelector}, .monaco-workbench.hc-black ${webviewSelector} { content: ""; background-image: ${$5Z(value.dark)}; }`);
        } catch {
        }
      }
    }
    this.g.textContent = cssRules.join("\n");
  }
};
$7Lb = __decorate([
  __param(0, $KL),
  __param(1, $kl)
], $7Lb);

// out-build/vs/workbench/contrib/webviewPanel/browser/webviewWorkbenchService.js
var $SOb = $Qk("webviewEditorService");
function canRevive(reviver, webview) {
  return reviver.canResolve(webview);
}
var $TOb = class $TOb2 extends $8Lb {
  constructor(init, webview, y) {
    super(init, webview, y.iconManager);
    this.y = y;
    this.u = false;
  }
  dispose() {
    super.dispose();
    this.w?.cancel();
    this.w = void 0;
  }
  async resolve() {
    if (!this.u) {
      this.u = true;
      this.w = $Hh((token) => this.y.resolveWebview(this, token));
      try {
        await this.w;
      } catch (e) {
        if (!$kb(e)) {
          throw e;
        }
      }
    }
    return super.resolve();
  }
  t(other) {
    if (!super.t(other)) {
      return;
    }
    other.u = this.u;
    return other;
  }
};
__decorate([
  $0t
], $TOb.prototype, "resolve", null);
$TOb = __decorate([
  __param(2, $SOb)
], $TOb);
var RevivalPool = class {
  constructor() {
    this.a = [];
  }
  enqueueForRestoration(input, token) {
    const promise = new $gi();
    const remove = () => {
      const index = this.a.findIndex((entry) => input === entry.input);
      if (index >= 0) {
        this.a.splice(index, 1);
      }
    };
    const disposable = $Zc(input.webview.onDidDispose(remove), token.onCancellationRequested(() => {
      remove();
      promise.cancel();
    }));
    this.a.push({ input, promise, disposable });
    return promise.p;
  }
  reviveFor(reviver, token) {
    const toRevive = this.a.filter(({ input }) => canRevive(reviver, input));
    this.a = this.a.filter(({ input }) => !canRevive(reviver, input));
    for (const { input, promise: resolve, disposable } of toRevive) {
      reviver.resolveWebview(input, token).then((x) => resolve.complete(x), (err) => resolve.error(err)).finally(() => {
        disposable.dispose();
      });
    }
  }
};
var $UOb = class $UOb2 extends $3c {
  constructor(editorGroupsService, f, g, h3) {
    super();
    this.f = f;
    this.g = g;
    this.h = h3;
    this.a = /* @__PURE__ */ new Set();
    this.b = new RevivalPool();
    this.m = this.B(new $ze());
    this.onDidChangeActiveWebviewEditor = this.m.event;
    this.c = this.B(this.g.createInstance($7Lb));
    this.B(editorGroupsService.registerContextKeyProvider({
      contextKey: $QOb,
      getGroupContextKeyValue: (group2) => this.n(group2.activeEditor)
    }));
    this.B(f.onDidActiveEditorChange(() => {
      this.r();
    }));
    this.B(h3.onDidChangeActiveWebview(() => {
      this.r();
    }));
    this.r();
  }
  get iconManager() {
    return this.c;
  }
  n(input) {
    let webviewInput;
    if (input instanceof $8Lb) {
      webviewInput = input;
    } else if (input instanceof $fub) {
      if (input.primary instanceof $8Lb) {
        webviewInput = input.primary;
      } else if (input.secondary instanceof $8Lb) {
        webviewInput = input.secondary;
      }
    }
    return webviewInput?.webview.providedViewType ?? "";
  }
  r() {
    const activeInput = this.f.activeEditor;
    let newActiveWebview;
    if (activeInput instanceof $8Lb) {
      newActiveWebview = activeInput;
    } else if (activeInput instanceof $fub) {
      if (activeInput.primary instanceof $8Lb && activeInput.primary.webview === this.h.activeWebview) {
        newActiveWebview = activeInput.primary;
      } else if (activeInput.secondary instanceof $8Lb && activeInput.secondary.webview === this.h.activeWebview) {
        newActiveWebview = activeInput.secondary;
      }
    }
    if (newActiveWebview !== this.j) {
      this.j = newActiveWebview;
      this.m.fire(newActiveWebview);
    }
  }
  openWebview(webviewInitInfo, viewType, title, showOptions) {
    const webview = this.h.createWebviewOverlay(webviewInitInfo);
    const webviewInput = this.g.createInstance($8Lb, { viewType, name: title, providedId: webviewInitInfo.providedViewType }, webview, this.iconManager);
    this.f.openEditor(webviewInput, {
      pinned: true,
      preserveFocus: showOptions.preserveFocus,
      // preserve pre 1.38 behaviour to not make group active when preserveFocus: true
      // but make sure to restore the editor to fix https://github.com/microsoft/vscode/issues/79633
      activation: showOptions.preserveFocus ? EditorActivation.RESTORE : void 0
    }, showOptions.group);
    return webviewInput;
  }
  revealWebview(webview, group2, preserveFocus) {
    const topLevelEditor = this.s(webview);
    this.f.openEditor(topLevelEditor, {
      preserveFocus,
      // preserve pre 1.38 behaviour to not make group active when preserveFocus: true
      // but make sure to restore the editor to fix https://github.com/microsoft/vscode/issues/79633
      activation: preserveFocus ? EditorActivation.RESTORE : void 0
    }, group2);
  }
  s(webview) {
    for (const editor of this.f.editors) {
      if (editor === webview) {
        return editor;
      }
      if (editor instanceof $fub) {
        if (webview === editor.primary || webview === editor.secondary) {
          return editor;
        }
      }
    }
    return webview;
  }
  openRevivedWebview(options3) {
    const webview = this.h.createWebviewOverlay(options3.webviewInitInfo);
    webview.state = options3.state;
    const webviewInput = this.g.createInstance($TOb, { viewType: options3.viewType, providedId: options3.webviewInitInfo.providedViewType, name: options3.title }, webview);
    webviewInput.iconPath = options3.iconPath;
    if (typeof options3.group === "number") {
      webviewInput.updateGroup(options3.group);
    }
    return webviewInput;
  }
  registerResolver(reviver) {
    this.a.add(reviver);
    const cts = new $ad();
    this.b.reviveFor(reviver, cts.token);
    return $1c(() => {
      this.a.delete(reviver);
      cts.dispose(true);
    });
  }
  shouldPersist(webview) {
    if (webview instanceof $TOb) {
      return true;
    }
    return Iterable.some(this.a.values(), (reviver) => canRevive(reviver, webview));
  }
  async t(webview, token) {
    for (const reviver of this.a.values()) {
      if (canRevive(reviver, webview)) {
        await reviver.resolveWebview(webview, token);
        return true;
      }
    }
    return false;
  }
  async resolveWebview(webview, token) {
    const didRevive = await this.t(webview, token);
    if (!didRevive && !token.isCancellationRequested) {
      return this.b.enqueueForRestoration(webview, token);
    }
  }
  setIcons(id2, iconPath) {
    this.c.setIcons(id2, iconPath);
  }
};
$UOb = __decorate([
  __param(0, $iJ),
  __param(1, $mJ),
  __param(2, $Pk),
  __param(3, $Crb)
], $UOb);

// out-build/vs/workbench/contrib/customEditor/browser/customEditorInput.js
var $VOb_1;
var $VOb = class $VOb2 extends $TOb {
  static {
    $VOb_1 = this;
  }
  static create(instantiationService, resource, viewType, group2, options3) {
    return instantiationService.invokeFunction((accessor) => {
      const untitledString = accessor.get($NJ).getValue(resource);
      const untitledDocumentData = untitledString ? $Ci.fromString(untitledString) : void 0;
      const webview = accessor.get($Crb).createWebviewOverlay({
        providedViewType: viewType,
        title: void 0,
        options: { customClasses: options3?.customClasses },
        contentOptions: {},
        extension: void 0
      });
      const input = instantiationService.createInstance($VOb_1, { resource, viewType }, webview, { untitledDocumentData, oldResource: options3?.oldResource });
      if (typeof group2 !== "undefined") {
        input.updateGroup(group2);
      }
      return input;
    });
  }
  static {
    this.typeId = "workbench.editors.webviewEditor";
  }
  get resource() {
    return this.C;
  }
  constructor(init, webview, options3, webviewWorkbenchService, I, J, L, M, N, O, P, Q, R, S) {
    super({ providedId: init.viewType, viewType: init.viewType, name: "" }, webview, webviewWorkbenchService);
    this.I = I;
    this.J = J;
    this.L = L;
    this.M = M;
    this.N = N;
    this.O = O;
    this.P = P;
    this.Q = Q;
    this.R = R;
    this.S = S;
    this.Y = void 0;
    this.Z = void 0;
    this.ab = void 0;
    this.cb = void 0;
    this.eb = void 0;
    this.gb = void 0;
    this.ib = void 0;
    this.C = init.resource;
    this.oldResource = options3.oldResource;
    this.D = options3.startsDirty;
    this.F = options3.backupId;
    this.G = options3.untitledDocumentData;
    this.U();
  }
  U() {
    this.B(this.J.onDidChangeFormatters((e) => this.W(e.scheme)));
    this.B(this.O.onDidChangeFileSystemProviderRegistrations((e) => this.W(e.scheme)));
    this.B(this.O.onDidChangeFileSystemProviderCapabilities((e) => this.W(e.scheme)));
    this.B(this.S.onDidChange(() => this.X()));
  }
  W(scheme) {
    if (scheme === this.resource.scheme) {
      this.X();
    }
  }
  X() {
    this.Y = void 0;
    this.Z = void 0;
    this.ab = void 0;
    this.cb = void 0;
    this.eb = void 0;
    this.gb = void 0;
    this.ib = void 0;
    this.g.fire();
  }
  get typeId() {
    return $VOb_1.typeId;
  }
  get editorId() {
    return this.viewType;
  }
  get capabilities() {
    let capabilities = 0;
    capabilities |= 128;
    if (!this.L.getCustomEditorCapabilities(this.viewType)?.supportsMultipleEditorsPerDocument) {
      capabilities |= 8;
    }
    if (this.H) {
      if (this.H.object.isReadonly()) {
        capabilities |= 2;
      }
    } else {
      if (this.P.isReadonly(this.resource)) {
        capabilities |= 2;
      }
    }
    if (this.resource.scheme === Schemas.untitled) {
      capabilities |= 4;
    }
    return capabilities;
  }
  getName() {
    if (typeof this.Y !== "string") {
      this.Y = this.S.getName(this.resource) ?? $rc(this.J.getUriLabel(this.resource));
    }
    return this.Y;
  }
  getDescription(verbosity = 1) {
    switch (verbosity) {
      case 0:
        return this.$;
      case 2:
        return this.db;
      case 1:
      default:
        return this.bb;
    }
  }
  get $() {
    if (typeof this.Z !== "string") {
      this.Z = this.J.getUriBasenameLabel($uh(this.resource));
    }
    return this.Z;
  }
  get bb() {
    if (typeof this.ab !== "string") {
      this.ab = this.J.getUriLabel($uh(this.resource), { relative: true });
    }
    return this.ab;
  }
  get db() {
    if (typeof this.cb !== "string") {
      this.cb = this.J.getUriLabel($uh(this.resource));
    }
    return this.cb;
  }
  get fb() {
    if (typeof this.eb !== "string") {
      this.eb = this.getName();
    }
    return this.eb;
  }
  get hb() {
    if (typeof this.gb !== "string") {
      this.gb = this.J.getUriLabel(this.resource, { relative: true });
    }
    return this.gb;
  }
  get jb() {
    if (typeof this.ib !== "string") {
      this.ib = this.J.getUriLabel(this.resource);
    }
    return this.ib;
  }
  getTitle(verbosity) {
    switch (verbosity) {
      case 0:
        return this.fb;
      case 2:
        return this.jb;
      default:
      case 1:
        return this.hb;
    }
  }
  matches(other) {
    if (super.matches(other)) {
      return true;
    }
    return this === other || other instanceof $VOb_1 && this.viewType === other.viewType && $oh(this.resource, other.resource);
  }
  copy() {
    return $VOb_1.create(this.I, this.resource, this.viewType, this.group, this.webview.options);
  }
  isReadonly() {
    if (!this.H) {
      return this.P.isReadonly(this.resource);
    }
    return this.H.object.isReadonly();
  }
  isDirty() {
    if (!this.H) {
      return !!this.D;
    }
    return this.H.object.isDirty();
  }
  async save(groupId, options3) {
    if (!this.H) {
      return void 0;
    }
    const target = await this.H.object.saveCustomEditor(options3);
    if (!target) {
      return void 0;
    }
    if (!$oh(target, this.resource)) {
      return { resource: target };
    }
    return this;
  }
  async saveAs(groupId, options3) {
    if (!this.H) {
      return void 0;
    }
    const dialogPath = this.C;
    const target = await this.M.pickFileToSave(dialogPath, options3?.availableFileSystems);
    if (!target) {
      return void 0;
    }
    if (!await this.H.object.saveCustomEditorAs(this.C, target, options3)) {
      return void 0;
    }
    return (await this.rename(groupId, target))?.editor;
  }
  async revert(group2, options3) {
    if (this.H) {
      return this.H.object.revert(options3);
    }
    this.D = false;
    this.f.fire();
  }
  async resolve() {
    await super.resolve();
    if (this.isDisposed()) {
      return null;
    }
    if (!this.H) {
      const oldCapabilities = this.capabilities;
      this.H = this.B($Kg(await this.L.models.tryRetain(this.resource, this.viewType)));
      this.B(this.H.object.onDidChangeDirty(() => this.f.fire()));
      this.B(this.H.object.onDidChangeReadonly(() => this.j.fire()));
      if (this.G) {
        this.D = true;
      }
      if (this.isDirty()) {
        this.f.fire();
      }
      if (this.capabilities !== oldCapabilities) {
        this.j.fire();
      }
    }
    return null;
  }
  async rename(group2, newResource) {
    return { editor: { resource: newResource } };
  }
  undo() {
    $Kg(this.H);
    return this.N.undo(this.resource);
  }
  redo() {
    $Kg(this.H);
    return this.N.redo(this.resource);
  }
  onMove(handler) {
    this.kb = handler;
  }
  t(other) {
    if (!super.t(other)) {
      return;
    }
    other.kb = this.kb;
    this.kb = void 0;
    return other;
  }
  get backupId() {
    if (this.H) {
      return this.H.object.backupId;
    }
    return this.F;
  }
  get untitledDocumentData() {
    return this.G;
  }
  toUntyped() {
    return {
      resource: this.resource,
      options: {
        override: this.viewType
      }
    };
  }
  claim(claimant, targetWindow, scopedContextKeyService) {
    if (this.mb(targetWindow.vscodeWindowId) !== true) {
      throw $qL(localize(5458, null), [
        $Zm({
          id: "openInOriginalWindow",
          label: localize(5459, null),
          run: async () => {
            const originalPart = this.Q.getPart(this.R.getContainer(getWindow(this.webview.container).window));
            const currentPart = this.Q.getPart(this.R.getContainer(targetWindow.window));
            currentPart.activeGroup.moveEditor(this, originalPart.activeGroup);
          }
        })
      ], { forceMessage: true });
    }
    return super.claim(claimant, targetWindow, scopedContextKeyService);
  }
  canMove(sourceGroup, targetGroup) {
    const resolvedTargetGroup = this.Q.getGroup(targetGroup);
    if (resolvedTargetGroup) {
      const canMove = this.mb(resolvedTargetGroup.windowId);
      if (typeof canMove === "string") {
        return canMove;
      }
    }
    return super.canMove(sourceGroup, targetGroup);
  }
  mb(targetWindowId) {
    if (this.isModified() && this.H?.object.canHotExit === false) {
      const sourceWindowId = getWindow(this.webview.container).vscodeWindowId;
      if (sourceWindowId !== targetWindowId) {
        return localize(5460, null, this.getName());
      }
    }
    return true;
  }
};
$VOb = $VOb_1 = __decorate([
  __param(3, $SOb),
  __param(4, $Pk),
  __param(5, $ZI),
  __param(6, $LOb),
  __param(7, $1v),
  __param(8, $_F),
  __param(9, $km),
  __param(10, $4J),
  __param(11, $iJ),
  __param(12, $Vlb),
  __param(13, $qrb)
], $VOb);

// out-build/vs/workbench/contrib/interactive/browser/interactiveDocumentService.js
var $WOb = $Qk("IInteractiveDocumentService");
var $XOb = class extends $3c {
  constructor() {
    super();
    this.a = this.B(new $ze());
    this.onWillAddInteractiveDocument = this.a.event;
    this.b = this.B(new $ze());
    this.onWillRemoveInteractiveDocument = this.b.event;
  }
  willCreateInteractiveDocument(notebookUri, inputUri, languageId) {
    this.a.fire({
      notebookUri,
      inputUri,
      languageId
    });
  }
  willRemoveInteractiveDocument(notebookUri, inputUri) {
    this.b.fire({
      notebookUri,
      inputUri
    });
  }
};

// out-build/vs/workbench/contrib/interactive/browser/interactiveHistoryService.js
var $YOb = $Qk("IInteractiveHistoryService");
var $ZOb = class extends $3c {
  constructor() {
    super();
    this._history = new $Ec();
  }
  matchesCurrent(uri, value) {
    const history = this._history.get(uri);
    if (!history) {
      return false;
    }
    return history.current() === value;
  }
  addToHistory(uri, value) {
    const history = this._history.get(uri);
    if (!history) {
      this._history.set(uri, new $G2([value], 50));
      return;
    }
    history.resetCursor();
    history.add(value);
  }
  getPreviousValue(uri) {
    const history = this._history.get(uri);
    return history?.previous() ?? null;
  }
  getNextValue(uri) {
    const history = this._history.get(uri);
    return history?.next() ?? null;
  }
  replaceLast(uri, value) {
    const history = this._history.get(uri);
    if (!history) {
      this._history.set(uri, new $G2([value], 50));
      return;
    } else {
      history.replaceLast(value);
      history.resetCursor();
    }
  }
  clearHistory(uri) {
    this._history.delete(uri);
  }
  has(uri) {
    return this._history.has(uri) ? true : false;
  }
};

// out-build/vs/workbench/contrib/interactive/browser/interactiveEditorInput.js
var $1Ob_1;
var $1Ob = class $1Ob2 extends $nG {
  static {
    $1Ob_1 = this;
  }
  static create(instantiationService, resource, inputResource, title, language) {
    return instantiationService.createInstance($1Ob_1, resource, inputResource, title, language);
  }
  static {
    this.a = {};
  }
  static setName(notebookUri, title) {
    if (title) {
      this.a[notebookUri.path] = title;
    }
  }
  static {
    this.ID = "workbench.input.interactive";
  }
  get editorId() {
    return "interactive";
  }
  get typeId() {
    return $1Ob_1.ID;
  }
  get language() {
    return this.w?.object.textEditorModel.getLanguageId() ?? this.h;
  }
  get notebookEditorInput() {
    return this.m;
  }
  get editorInputs() {
    return [this.m];
  }
  get resource() {
    return this.r;
  }
  get inputResource() {
    return this.s;
  }
  get primary() {
    return this.m;
  }
  constructor(resource, inputResource, title, languageId, instantiationService, textModelService, interactiveDocumentService, historyService, D, F, configurationService) {
    const input = $trb.getOrCreate(instantiationService, resource, void 0, "interactive", {});
    super();
    this.D = D;
    this.F = F;
    this.c = configurationService.getValue($rM.InteractiveWindowPromptToSave) !== true;
    this.m = input;
    this.B(this.m);
    this.b = title ?? $1Ob_1.a[resource.path] ?? $rc(resource.path, $sc(resource.path));
    this.h = languageId;
    this.r = resource;
    this.s = inputResource;
    this.t = null;
    this.u = null;
    this.w = null;
    this.y = textModelService;
    this.z = interactiveDocumentService;
    this.C = historyService;
    this.G();
  }
  G() {
    const oncePrimaryDisposed = Event2.once(this.primary.onWillDispose);
    this.B(oncePrimaryDisposed(() => {
      if (!this.isDisposed()) {
        this.dispose();
      }
    }));
    this.B(this.primary.onDidChangeDirty(() => this.f.fire()));
    this.B(this.primary.onDidChangeLabel(() => this.g.fire()));
    this.B(this.primary.onDidChangeCapabilities(() => this.j.fire()));
  }
  get capabilities() {
    const scratchPad = this.c ? 512 : 0;
    return 4 | 2 | scratchPad;
  }
  async H() {
    if (!this.u) {
      this.u = await this.m.resolve();
    }
    return this.u;
  }
  async resolve() {
    if (this.u) {
      return this.u;
    }
    if (this.t) {
      return this.t;
    }
    this.t = this.H();
    return this.t;
  }
  async resolveInput(language) {
    if (this.w) {
      return this.w.object.textEditorModel;
    }
    const resolvedLanguage = language ?? this.h ?? $KF;
    this.z.willCreateInteractiveDocument(this.resource, this.inputResource, resolvedLanguage);
    this.w = await this.y.createModelReference(this.inputResource);
    return this.w.object.textEditorModel;
  }
  async save(group2, options3) {
    if (this.u) {
      if (this.hasCapability(
        4
        /* EditorInputCapabilities.Untitled */
      )) {
        return this.saveAs(group2, options3);
      } else {
        await this.u.save(options3);
      }
      return this;
    }
    return void 0;
  }
  async saveAs(group2, options3) {
    if (!this.u) {
      return void 0;
    }
    const provider = this.D.getContributedNotebookType("interactive");
    if (!provider) {
      return void 0;
    }
    const filename = this.getName() + ".ipynb";
    const pathCandidate = $vh(await this.F.defaultFilePath(), filename);
    const target = await this.F.pickFileToSave(pathCandidate, options3?.availableFileSystems);
    if (!target) {
      return void 0;
    }
    const saved = await this.u.saveAs(target);
    if (saved && "resource" in saved && saved.resource) {
      this.D.getNotebookTextModel(saved.resource)?.dispose();
    }
    return saved;
  }
  matches(otherInput) {
    if (super.matches(otherInput)) {
      return true;
    }
    if (otherInput instanceof $1Ob_1) {
      return $oh(this.resource, otherInput.resource) && $oh(this.inputResource, otherInput.inputResource);
    }
    return false;
  }
  getName() {
    return this.b;
  }
  isDirty() {
    if (this.c) {
      return false;
    }
    return this.u?.isDirty() ?? false;
  }
  isModified() {
    return this.u?.isModified() ?? false;
  }
  async revert(_group, options3) {
    if (this.u && this.u.isDirty()) {
      await this.u.revert(options3);
    }
  }
  dispose() {
    this.u?.revert({ soft: true });
    this.m?.dispose();
    this.u?.dispose();
    this.u = null;
    this.z.willRemoveInteractiveDocument(this.resource, this.inputResource);
    this.w?.dispose();
    this.w = null;
    super.dispose();
  }
  get historyService() {
    return this.C;
  }
};
$1Ob = $1Ob_1 = __decorate([
  __param(4, $Pk),
  __param(5, $oG),
  __param(6, $WOb),
  __param(7, $YOb),
  __param(8, $mrb),
  __param(9, $1v),
  __param(10, $kl)
], $1Ob);

// out-build/vs/workbench/contrib/mergeEditor/browser/mergeMarkers/mergeMarkersController.js
var $2Ob = {
  start: "<<<<<<<",
  end: ">>>>>>>"
};

// out-build/vs/workbench/contrib/mergeEditor/browser/model/diffComputer.js
var $RHb = class $RHb2 {
  constructor(b, d) {
    this.b = b;
    this.d = d;
    this.a = $G9("mergeEditor.diffAlgorithm", "advanced", this.d).map((v) => v === "smart" ? "legacy" : v === "experimental" ? "advanced" : v);
  }
  async computeDiff(textModel1, textModel2, reader) {
    const diffAlgorithm = this.a.read(reader);
    const inputVersion = textModel1.getVersionId();
    const outputVersion = textModel2.getVersionId();
    const result = await this.b.computeDiff(textModel1.uri, textModel2.uri, {
      ignoreTrimWhitespace: false,
      maxComputationTimeMs: 0,
      computeMoves: false
    }, diffAlgorithm);
    if (!result) {
      throw new Error("Diff computation failed");
    }
    if (textModel1.isDisposed() || textModel2.isDisposed()) {
      return { diffs: null };
    }
    const changes = result.changes.map((c) => new $FHb($SHb(c.original), textModel1, $SHb(c.modified), textModel2, c.innerChanges?.map((ic) => $THb(ic))));
    const newInputVersion = textModel1.getVersionId();
    const newOutputVersion = textModel2.getVersionId();
    if (inputVersion !== newInputVersion || outputVersion !== newOutputVersion) {
      return { diffs: null };
    }
    $kd(() => {
      for (const c of changes) {
        const inputRange = c.inputRange;
        const outputRange = c.outputRange;
        const inputTextModel = c.inputTextModel;
        const outputTextModel = c.outputTextModel;
        for (const map of c.rangeMappings) {
          let inputRangesValid = inputRange.startLineNumber - 1 <= map.inputRange.startLineNumber && map.inputRange.endLineNumber <= inputRange.endLineNumberExclusive;
          if (inputRangesValid && map.inputRange.startLineNumber === inputRange.startLineNumber - 1) {
            inputRangesValid = map.inputRange.endColumn >= inputTextModel.getLineMaxColumn(map.inputRange.startLineNumber);
          }
          if (inputRangesValid && map.inputRange.endLineNumber === inputRange.endLineNumberExclusive) {
            inputRangesValid = map.inputRange.endColumn === 1;
          }
          let outputRangesValid = outputRange.startLineNumber - 1 <= map.outputRange.startLineNumber && map.outputRange.endLineNumber <= outputRange.endLineNumberExclusive;
          if (outputRangesValid && map.outputRange.startLineNumber === outputRange.startLineNumber - 1) {
            outputRangesValid = map.outputRange.endColumn >= outputTextModel.getLineMaxColumn(map.outputRange.endLineNumber);
          }
          if (outputRangesValid && map.outputRange.endLineNumber === outputRange.endLineNumberExclusive) {
            outputRangesValid = map.outputRange.endColumn === 1;
          }
          if (!inputRangesValid || !outputRangesValid) {
            return false;
          }
        }
      }
      return changes.length === 0 || changes[0].inputRange.startLineNumber === changes[0].outputRange.startLineNumber && $ld(changes, (m1, m2) => m2.inputRange.startLineNumber - m1.inputRange.endLineNumberExclusive === m2.outputRange.startLineNumber - m1.outputRange.endLineNumberExclusive && // There has to be an unchanged line in between (otherwise both diffs should have been joined)
      m1.inputRange.endLineNumberExclusive < m2.inputRange.startLineNumber && m1.outputRange.endLineNumberExclusive < m2.outputRange.startLineNumber);
    });
    return {
      diffs: changes
    };
  }
};
$RHb = __decorate([
  __param(0, $I0),
  __param(1, $kl)
], $RHb);
function $SHb(range) {
  return new $jHb(range.startLineNumber, range.length);
}
function $THb(mapping2) {
  return new $GHb(mapping2.originalRange, mapping2.modifiedRange);
}

// out-build/vs/base/common/controlFlow.js
var $J3 = class {
  constructor() {
    this.a = false;
  }
  /**
   * Calls `runner` if the barrier is not occupied.
   * During the call, the barrier becomes occupied.
   */
  runExclusivelyOrSkip(runner) {
    if (this.a) {
      return;
    }
    this.a = true;
    try {
      runner();
    } finally {
      this.a = false;
    }
  }
  /**
   * Calls `runner`. If the barrier is occupied, throws an error.
   * During the call, the barrier becomes active.
   */
  runExclusivelyOrThrow(runner) {
    if (this.a) {
      throw new $vb(`ReentrancyBarrier: reentrant call detected!`);
    }
    this.a = true;
    try {
      runner();
    } finally {
      this.a = false;
    }
  }
  /**
   * Indicates if some runner occupies this barrier.
  */
  get isOccupied() {
    return this.a;
  }
  makeExclusiveOrSkip(fn) {
    return (...args2) => {
      if (this.a) {
        return;
      }
      this.a = true;
      try {
        return fn(...args2);
      } finally {
        this.a = false;
      }
    };
  }
};

// out-build/vs/workbench/contrib/mergeEditor/browser/model/textModelDiffs.js
var $UHb = class extends $3c {
  get isApplyingChange() {
    return this.f.isOccupied;
  }
  constructor(h3, j, m) {
    super();
    this.h = h3;
    this.j = j;
    this.m = m;
    this.a = 0;
    this.b = $he(
      this,
      1
      /* TextModelDiffState.initializing */
    );
    this.c = $he(this, []);
    this.f = new $J3();
    this.g = false;
    this.n = true;
    const recomputeSignal = $Hd("recompute");
    this.B($td((reader) => {
      recomputeSignal.read(reader);
      this.r(reader);
    }));
    this.B(h3.onDidChangeContent(this.f.makeExclusiveOrSkip(() => {
      recomputeSignal.trigger(void 0);
    })));
    this.B(j.onDidChangeContent(this.f.makeExclusiveOrSkip(() => {
      recomputeSignal.trigger(void 0);
    })));
    this.B($1c(() => {
      this.g = true;
    }));
  }
  get state() {
    return this.b;
  }
  /**
   * Diffs from base to input.
  */
  get diffs() {
    return this.c;
  }
  r(reader) {
    this.a++;
    const currentRecomputeIdx = this.a;
    if (this.b.get() === 1) {
      this.n = true;
    }
    $ce((tx) => {
      this.b.set(
        this.n ? 1 : 3,
        tx,
        0
        /* TextModelDiffChangeReason.other */
      );
    });
    const result = this.m.computeDiff(this.h, this.j, reader);
    result.then((result2) => {
      if (this.g) {
        return;
      }
      if (currentRecomputeIdx !== this.a) {
        return;
      }
      $ce((tx) => {
        if (result2.diffs) {
          this.b.set(
            2,
            tx,
            1
            /* TextModelDiffChangeReason.textChange */
          );
          this.c.set(
            result2.diffs,
            tx,
            1
            /* TextModelDiffChangeReason.textChange */
          );
        } else {
          this.b.set(
            4,
            tx,
            1
            /* TextModelDiffChangeReason.textChange */
          );
        }
        this.n = false;
      });
    });
  }
  s() {
    if (this.state.get() !== 2) {
      throw new $vb("Cannot remove diffs when the model is not up to date");
    }
  }
  removeDiffs(diffToRemoves, transaction, group2) {
    this.s();
    diffToRemoves.sort($9b((d) => d.inputRange.startLineNumber, $$b));
    diffToRemoves.reverse();
    let diffs = this.c.get();
    for (const diffToRemove of diffToRemoves) {
      const len = diffs.length;
      diffs = diffs.filter((d) => d !== diffToRemove);
      if (len === diffs.length) {
        throw new $vb();
      }
      this.f.runExclusivelyOrThrow(() => {
        const edits = diffToRemove.getReverseLineEdit().toEdits(this.j.getLineCount());
        this.j.pushEditOperations(null, edits, () => null, group2);
      });
      diffs = diffs.map((d) => d.outputRange.isAfter(diffToRemove.outputRange) ? d.addOutputLineDelta(diffToRemove.inputRange.lineCount - diffToRemove.outputRange.lineCount) : d);
    }
    this.c.set(
      diffs,
      transaction,
      0
      /* TextModelDiffChangeReason.other */
    );
  }
  /**
   * Edit must be conflict free.
   */
  applyEditRelativeToOriginal(edit3, transaction, group2) {
    this.s();
    const editMapping = new $FHb(edit3.range, this.h, new $jHb(edit3.range.startLineNumber, edit3.newLines.length), this.j);
    let firstAfter = false;
    let delta = 0;
    const newDiffs = new Array();
    for (const diff3 of this.diffs.get()) {
      if (diff3.inputRange.touches(edit3.range)) {
        throw new $vb("Edit must be conflict free.");
      } else if (diff3.inputRange.isAfter(edit3.range)) {
        if (!firstAfter) {
          firstAfter = true;
          newDiffs.push(editMapping.addOutputLineDelta(delta));
        }
        newDiffs.push(diff3.addOutputLineDelta(edit3.newLines.length - edit3.range.lineCount));
      } else {
        newDiffs.push(diff3);
      }
      if (!firstAfter) {
        delta += diff3.outputRange.lineCount - diff3.inputRange.lineCount;
      }
    }
    if (!firstAfter) {
      firstAfter = true;
      newDiffs.push(editMapping.addOutputLineDelta(delta));
    }
    this.f.runExclusivelyOrThrow(() => {
      const edits = new $kHb(edit3.range.delta(delta), edit3.newLines).toEdits(this.j.getLineCount());
      this.j.pushEditOperations(null, edits, () => null, group2);
    });
    this.c.set(
      newDiffs,
      transaction,
      0
      /* TextModelDiffChangeReason.other */
    );
  }
  findTouchingDiffs(baseRange) {
    return this.diffs.get().filter((d) => d.inputRange.touches(baseRange));
  }
  t(lineNumber, reader) {
    let offset = 0;
    const diffs = reader ? this.diffs.read(reader) : this.diffs.get();
    for (const diff3 of diffs) {
      if (diff3.inputRange.contains(lineNumber) || diff3.inputRange.endLineNumberExclusive === lineNumber) {
        return diff3;
      } else if (diff3.inputRange.endLineNumberExclusive < lineNumber) {
        offset = diff3.resultingDeltaFromOriginalToModified;
      } else {
        break;
      }
    }
    return lineNumber + offset;
  }
  getResultLineRange(baseRange, reader) {
    let start = this.t(baseRange.startLineNumber, reader);
    if (typeof start !== "number") {
      start = start.outputRange.startLineNumber;
    }
    let endExclusive = this.t(baseRange.endLineNumberExclusive, reader);
    if (typeof endExclusive !== "number") {
      endExclusive = endExclusive.outputRange.endLineNumberExclusive;
    }
    return $jHb.fromLineNumbers(start, endExclusive);
  }
};
var TextModelDiffChangeReason;
(function(TextModelDiffChangeReason2) {
  TextModelDiffChangeReason2[TextModelDiffChangeReason2["other"] = 0] = "other";
  TextModelDiffChangeReason2[TextModelDiffChangeReason2["textChange"] = 1] = "textChange";
})(TextModelDiffChangeReason || (TextModelDiffChangeReason = {}));
var TextModelDiffState;
(function(TextModelDiffState2) {
  TextModelDiffState2[TextModelDiffState2["initializing"] = 1] = "initializing";
  TextModelDiffState2[TextModelDiffState2["upToDate"] = 2] = "upToDate";
  TextModelDiffState2[TextModelDiffState2["updating"] = 3] = "updating";
  TextModelDiffState2[TextModelDiffState2["error"] = 4] = "error";
})(TextModelDiffState || (TextModelDiffState = {}));

// out-build/vs/workbench/contrib/mergeEditor/browser/model/mergeEditorModel.js
var $WHb = class $WHb2 extends $rG {
  constructor(base, input1, input2, resultTextModel, u, w, telemetry, y, z) {
    super();
    this.base = base;
    this.input1 = input1;
    this.input2 = input2;
    this.resultTextModel = resultTextModel;
    this.u = u;
    this.w = w;
    this.telemetry = telemetry;
    this.y = y;
    this.z = z;
    this.c = this.B(new $UHb(this.base, this.input1.textModel, this.u));
    this.g = this.B(new $UHb(this.base, this.input2.textModel, this.u));
    this.j = this.B(new $UHb(this.base, this.resultTextModel, this.u));
    this.modifiedBaseRanges = $2d(this, (reader) => {
      const input1Diffs = this.c.diffs.read(reader);
      const input2Diffs = this.g.diffs.read(reader);
      return $IHb.fromDiffs(input1Diffs, input2Diffs, this.base, this.input1.textModel, this.input2.textModel);
    });
    this.n = $2d(this, (reader) => {
      const map = new Map(this.modifiedBaseRanges.read(reader).map((s) => [
        s,
        new ModifiedBaseRangeData(s)
      ]));
      return map;
    });
    this.t = this.resultTextModel.createSnapshot();
    this.baseInput1Diffs = this.c.diffs;
    this.baseInput2Diffs = this.g.diffs;
    this.baseResultDiffs = this.j.diffs;
    this.input1ResultMapping = $2d(this, (reader) => {
      return this.F(this.baseInput1Diffs.read(reader), this.baseResultDiffs.read(reader), this.input1.textModel.getLineCount());
    });
    this.resultInput1Mapping = $2d(this, (reader) => this.input1ResultMapping.read(reader).reverse());
    this.input2ResultMapping = $2d(this, (reader) => {
      return this.F(this.baseInput2Diffs.read(reader), this.baseResultDiffs.read(reader), this.input2.textModel.getLineCount());
    });
    this.resultInput2Mapping = $2d(this, (reader) => this.input2ResultMapping.read(reader).reverse());
    this.baseResultMapping = $2d(this, (reader) => {
      const map = new $DHb(this.baseResultDiffs.read(reader), -1);
      return new $DHb(map.lineRangeMappings.map((m) => m.inputRange.isEmpty || m.outputRange.isEmpty ? new $CHb(
        // We can do this because two adjacent diffs have one line in between.
        m.inputRange.deltaStart(-1),
        m.outputRange.deltaStart(-1)
      ) : m), map.inputLineCount);
    });
    this.resultBaseMapping = $2d(this, (reader) => this.baseResultMapping.read(reader).reverse());
    this.diffComputingState = $2d(this, (reader) => {
      const states = [
        this.c,
        this.g,
        this.j
      ].map((s) => s.state.read(reader));
      if (states.some(
        (s) => s === 1
        /* TextModelDiffState.initializing */
      )) {
        return 1;
      }
      if (states.some(
        (s) => s === 3
        /* TextModelDiffState.updating */
      )) {
        return 3;
      }
      return 2;
    });
    this.inputDiffComputingState = $2d(this, (reader) => {
      const states = [
        this.c,
        this.g
      ].map((s) => s.state.read(reader));
      if (states.some(
        (s) => s === 1
        /* TextModelDiffState.initializing */
      )) {
        return 1;
      }
      if (states.some(
        (s) => s === 3
        /* TextModelDiffState.updating */
      )) {
        return 3;
      }
      return 2;
    });
    this.isUpToDate = $2d(
      this,
      (reader) => this.diffComputingState.read(reader) === 2
      /* MergeEditorModelState.upToDate */
    );
    this.onInitialized = $re(
      this.diffComputingState,
      (state) => state === 2
      /* MergeEditorModelState.upToDate */
    ).then(() => {
    });
    this.G = true;
    this.unhandledConflictsCount = $2d(this, (reader) => {
      const map = this.n.read(reader);
      let unhandledCount = 0;
      for (const [_key, value] of map) {
        if (!value.handled.read(reader)) {
          unhandledCount++;
        }
      }
      return unhandledCount;
    });
    this.hasUnhandledConflicts = this.unhandledConflictsCount.map((value) => (
      /** @description hasUnhandledConflicts */
      value > 0
    ));
    this.B($Md(this.n));
    this.B($Md(this.input1ResultMapping));
    this.B($Md(this.input2ResultMapping));
    const initializePromise = this.C();
    this.onInitialized = this.onInitialized.then(async () => {
      await initializePromise;
    });
    initializePromise.then(() => {
      let shouldRecomputeHandledFromAccepted = true;
      this.B($vd({
        handleChange: (ctx) => {
          if (ctx.didChange(this.n)) {
            shouldRecomputeHandledFromAccepted = true;
          }
          return ctx.didChange(this.j.diffs) ? ctx.change === 1 : true;
        }
      }, (reader) => {
        const states = this.n.read(reader);
        if (!this.isUpToDate.read(reader)) {
          return;
        }
        const resultDiffs = this.j.diffs.read(reader);
        $ce((tx) => {
          this.H(resultDiffs, states, tx);
          if (shouldRecomputeHandledFromAccepted) {
            shouldRecomputeHandledFromAccepted = false;
            for (const [_range, observableState] of states) {
              const state = observableState.accepted.get();
              const handled = !(state.kind === ModifiedBaseRangeStateKind.base || state.kind === ModifiedBaseRangeStateKind.unrecognized);
              observableState.handledInput1.set(handled, tx);
              observableState.handledInput2.set(handled, tx);
            }
          }
        });
      }));
    });
  }
  async C() {
    if (this.w.resetResult) {
      await this.reset();
    }
  }
  async reset() {
    await $re(
      this.inputDiffComputingState,
      (state) => state === 2
      /* MergeEditorModelState.upToDate */
    );
    const states = this.n.get();
    $ce((tx) => {
      for (const [range, state] of states) {
        let newState;
        let handled = false;
        if (range.input1Diffs.length === 0) {
          newState = ModifiedBaseRangeState.base.withInputValue(2, true);
          handled = true;
        } else if (range.input2Diffs.length === 0) {
          newState = ModifiedBaseRangeState.base.withInputValue(1, true);
          handled = true;
        } else if (range.isEqualChange) {
          newState = ModifiedBaseRangeState.base.withInputValue(1, true);
          handled = true;
        } else {
          newState = ModifiedBaseRangeState.base;
          handled = false;
        }
        state.accepted.set(newState, tx);
        state.computedFromDiffing = false;
        state.previousNonDiffingState = void 0;
        state.handledInput1.set(handled, tx);
        state.handledInput2.set(handled, tx);
      }
      this.resultTextModel.pushEditOperations(null, [{
        range: new $9C(1, 1, Number.MAX_SAFE_INTEGER, 1),
        text: this.D()
      }], () => null);
    });
  }
  D() {
    const baseRanges = this.modifiedBaseRanges.get();
    const baseLines = this.base.getLinesContent();
    const input1Lines = this.input1.textModel.getLinesContent();
    const input2Lines = this.input2.textModel.getLinesContent();
    const resultLines = [];
    function appendLinesToResult(source, lineRange) {
      for (let i2 = lineRange.startLineNumber; i2 < lineRange.endLineNumberExclusive; i2++) {
        resultLines.push(source[i2 - 1]);
      }
    }
    let baseStartLineNumber = 1;
    for (const baseRange of baseRanges) {
      appendLinesToResult(baseLines, $jHb.fromLineNumbers(baseStartLineNumber, baseRange.baseRange.startLineNumber));
      baseStartLineNumber = baseRange.baseRange.endLineNumberExclusive;
      if (baseRange.input1Diffs.length === 0) {
        appendLinesToResult(input2Lines, baseRange.input2Range);
      } else if (baseRange.input2Diffs.length === 0) {
        appendLinesToResult(input1Lines, baseRange.input1Range);
      } else if (baseRange.isEqualChange) {
        appendLinesToResult(input1Lines, baseRange.input1Range);
      } else {
        appendLinesToResult(baseLines, baseRange.baseRange);
      }
    }
    appendLinesToResult(baseLines, $jHb.fromLineNumbers(baseStartLineNumber, baseLines.length + 1));
    return resultLines.join(this.resultTextModel.getEOL());
  }
  hasBaseRange(baseRange) {
    return this.n.get().has(baseRange);
  }
  get isApplyingEditInResult() {
    return this.j.isApplyingChange;
  }
  F(inputLinesDiffs, resultDiffs, inputLineCount) {
    const map = $DHb.betweenOutputs(inputLinesDiffs, resultDiffs, inputLineCount);
    return new $DHb(map.lineRangeMappings.map((m) => m.inputRange.isEmpty || m.outputRange.isEmpty ? new $CHb(
      // We can do this because two adjacent diffs have one line in between.
      m.inputRange.deltaStart(-1),
      m.outputRange.deltaStart(-1)
    ) : m), map.inputLineCount);
  }
  translateInputRangeToBase(input, range) {
    const baseInputDiffs = input === 1 ? this.baseInput1Diffs.get() : this.baseInput2Diffs.get();
    const map = new $HHb(baseInputDiffs.flatMap((d) => d.rangeMappings), 0).reverse();
    return map.projectRange(range).outputRange;
  }
  translateBaseRangeToInput(input, range) {
    const baseInputDiffs = input === 1 ? this.baseInput1Diffs.get() : this.baseInput2Diffs.get();
    const map = new $HHb(baseInputDiffs.flatMap((d) => d.rangeMappings), 0);
    return map.projectRange(range).outputRange;
  }
  getLineRangeInResult(baseRange, reader) {
    return this.j.getResultLineRange(baseRange, reader);
  }
  translateResultRangeToBase(range) {
    const map = new $HHb(this.baseResultDiffs.get().flatMap((d) => d.rangeMappings), 0).reverse();
    return map.projectRange(range).outputRange;
  }
  translateBaseRangeToResult(range) {
    const map = new $HHb(this.baseResultDiffs.get().flatMap((d) => d.rangeMappings), 0);
    return map.projectRange(range).outputRange;
  }
  findModifiedBaseRangesInRange(rangeInBase) {
    return this.modifiedBaseRanges.get().filter((r2) => r2.baseRange.intersects(rangeInBase));
  }
  H(resultDiffs, states, tx) {
    const baseRangeWithStoreAndTouchingDiffs = $pHb(states, resultDiffs, (baseRange, diff3) => baseRange[0].baseRange.touches(diff3.inputRange) ? CompareResult.neitherLessOrGreaterThan : $jHb.compareByStart(baseRange[0].baseRange, diff3.inputRange));
    for (const row of baseRangeWithStoreAndTouchingDiffs) {
      const newState = this.I(row.left[0], row.rights);
      const data = row.left[1];
      const oldState = data.accepted.get();
      if (!oldState.equals(newState)) {
        if (!this.G && !data.computedFromDiffing) {
          data.computedFromDiffing = true;
          data.previousNonDiffingState = oldState;
        }
        data.accepted.set(newState, tx);
      }
    }
    if (this.G) {
      this.G = false;
    }
  }
  I(baseRange, conflictingDiffs) {
    if (conflictingDiffs.length === 0) {
      return ModifiedBaseRangeState.base;
    }
    const conflictingEdits = conflictingDiffs.map((d) => d.getLineEdit());
    function editsAgreeWithDiffs(diffs) {
      return $zb(conflictingEdits, diffs.map((d) => d.getLineEdit()), (a, b) => a.equals(b));
    }
    if (editsAgreeWithDiffs(baseRange.input1Diffs)) {
      return ModifiedBaseRangeState.base.withInputValue(1, true);
    }
    if (editsAgreeWithDiffs(baseRange.input2Diffs)) {
      return ModifiedBaseRangeState.base.withInputValue(2, true);
    }
    const states = [
      ModifiedBaseRangeState.base.withInputValue(1, true).withInputValue(2, true, true),
      ModifiedBaseRangeState.base.withInputValue(2, true).withInputValue(1, true, true),
      ModifiedBaseRangeState.base.withInputValue(1, true).withInputValue(2, true, false),
      ModifiedBaseRangeState.base.withInputValue(2, true).withInputValue(1, true, false)
    ];
    for (const s of states) {
      const { edit: edit3 } = baseRange.getEditForBase(s);
      if (edit3) {
        const resultRange = this.j.getResultLineRange(baseRange.baseRange);
        const existingLines = resultRange.getLines(this.resultTextModel);
        if ($zb(edit3.newLines, existingLines, (a, b) => a === b)) {
          return s;
        }
      }
    }
    return ModifiedBaseRangeState.unrecognized;
  }
  getState(baseRange) {
    const existingState = this.n.get().get(baseRange);
    if (!existingState) {
      throw new $vb("object must be from this instance");
    }
    return existingState.accepted;
  }
  setState(baseRange, state, _markInputAsHandled, tx, _pushStackElement = false) {
    if (!this.isUpToDate.get()) {
      throw new $vb("Cannot set state while updating");
    }
    const existingState = this.n.get().get(baseRange);
    if (!existingState) {
      throw new $vb("object must be from this instance");
    }
    const conflictingDiffs = this.j.findTouchingDiffs(baseRange.baseRange);
    const group2 = new $bG();
    if (conflictingDiffs) {
      this.j.removeDiffs(conflictingDiffs, tx, group2);
    }
    const { edit: edit3, effectiveState } = baseRange.getEditForBase(state);
    existingState.accepted.set(effectiveState, tx);
    existingState.previousNonDiffingState = void 0;
    existingState.computedFromDiffing = false;
    const input1Handled = existingState.handledInput1.get();
    const input2Handled = existingState.handledInput2.get();
    if (!input1Handled || !input2Handled) {
      this.z.pushElement(new MarkAsHandledUndoRedoElement(this.resultTextModel.uri, new WeakRef(this), new WeakRef(existingState), input1Handled, input2Handled), group2);
    }
    if (edit3) {
      this.resultTextModel.pushStackElement();
      this.j.applyEditRelativeToOriginal(edit3, tx, group2);
      this.resultTextModel.pushStackElement();
    }
    existingState.handledInput1.set(true, tx);
    existingState.handledInput2.set(true, tx);
  }
  resetDirtyConflictsToBase() {
    $ce((tx) => {
      this.resultTextModel.pushStackElement();
      for (const range of this.modifiedBaseRanges.get()) {
        if (this.getState(range).get().kind === ModifiedBaseRangeStateKind.unrecognized) {
          this.setState(range, ModifiedBaseRangeState.base, false, tx, false);
        }
      }
      this.resultTextModel.pushStackElement();
    });
  }
  isHandled(baseRange) {
    return this.n.get().get(baseRange).handled;
  }
  isInputHandled(baseRange, inputNumber) {
    const state = this.n.get().get(baseRange);
    return inputNumber === 1 ? state.handledInput1 : state.handledInput2;
  }
  setInputHandled(baseRange, inputNumber, handled, tx) {
    const state = this.n.get().get(baseRange);
    if (state.handled.get() === handled) {
      return;
    }
    const dataRef = new WeakRef(ModifiedBaseRangeData);
    const modelRef = new WeakRef(this);
    this.z.pushElement({
      type: 0,
      resource: this.resultTextModel.uri,
      code: "setInputHandled",
      label: localize(7997, null),
      redo() {
        const model = modelRef.deref();
        const data = dataRef.deref();
        if (model && !model.isDisposed() && data) {
          $ce((tx2) => {
            if (inputNumber === 1) {
              state.handledInput1.set(handled, tx2);
            } else {
              state.handledInput2.set(handled, tx2);
            }
          });
        }
      },
      undo() {
        const model = modelRef.deref();
        const data = dataRef.deref();
        if (model && !model.isDisposed() && data) {
          $ce((tx2) => {
            if (inputNumber === 1) {
              state.handledInput1.set(!handled, tx2);
            } else {
              state.handledInput2.set(!handled, tx2);
            }
          });
        }
      }
    });
    if (inputNumber === 1) {
      state.handledInput1.set(handled, tx);
    } else {
      state.handledInput2.set(handled, tx);
    }
  }
  setHandled(baseRange, handled, tx) {
    const state = this.n.get().get(baseRange);
    if (state.handled.get() === handled) {
      return;
    }
    state.handledInput1.set(handled, tx);
    state.handledInput2.set(handled, tx);
  }
  setLanguageId(languageId, source) {
    const language = this.y.createById(languageId);
    this.base.setLanguage(language, source);
    this.input1.textModel.setLanguage(language, source);
    this.input2.textModel.setLanguage(language, source);
    this.resultTextModel.setLanguage(language, source);
  }
  getInitialResultValue() {
    const chunks = [];
    while (true) {
      const chunk = this.t.read();
      if (chunk === null) {
        break;
      }
      chunks.push(chunk);
    }
    return chunks.join();
  }
  async getResultValueWithConflictMarkers() {
    await $re(
      this.diffComputingState,
      (state) => state === 2
      /* MergeEditorModelState.upToDate */
    );
    if (this.unhandledConflictsCount.get() === 0) {
      return this.resultTextModel.getValue();
    }
    const resultLines = this.resultTextModel.getLinesContent();
    const input1Lines = this.input1.textModel.getLinesContent();
    const input2Lines = this.input2.textModel.getLinesContent();
    const states = this.n.get();
    const outputLines = [];
    function appendLinesToResult(source, lineRange) {
      for (let i2 = lineRange.startLineNumber; i2 < lineRange.endLineNumberExclusive; i2++) {
        outputLines.push(source[i2 - 1]);
      }
    }
    let resultStartLineNumber = 1;
    for (const [range, state] of states) {
      if (state.handled.get()) {
        continue;
      }
      const resultRange = this.j.getResultLineRange(range.baseRange);
      appendLinesToResult(resultLines, $jHb.fromLineNumbers(resultStartLineNumber, Math.max(resultStartLineNumber, resultRange.startLineNumber)));
      resultStartLineNumber = resultRange.endLineNumberExclusive;
      outputLines.push("<<<<<<<");
      if (state.accepted.get().kind === ModifiedBaseRangeStateKind.unrecognized) {
        appendLinesToResult(resultLines, resultRange);
      } else {
        appendLinesToResult(input1Lines, range.input1Range);
      }
      outputLines.push("=======");
      appendLinesToResult(input2Lines, range.input2Range);
      outputLines.push(">>>>>>>");
    }
    appendLinesToResult(resultLines, $jHb.fromLineNumbers(resultStartLineNumber, resultLines.length + 1));
    return outputLines.join("\n");
  }
  get conflictCount() {
    return arrayCount(this.modifiedBaseRanges.get(), (r2) => r2.isConflicting);
  }
  get combinableConflictCount() {
    return arrayCount(this.modifiedBaseRanges.get(), (r2) => r2.isConflicting && r2.canBeCombined);
  }
  get conflictsResolvedWithBase() {
    return arrayCount(this.n.get().entries(), ([r2, s]) => r2.isConflicting && s.accepted.get().kind === ModifiedBaseRangeStateKind.base);
  }
  get conflictsResolvedWithInput1() {
    return arrayCount(this.n.get().entries(), ([r2, s]) => r2.isConflicting && s.accepted.get().kind === ModifiedBaseRangeStateKind.input1);
  }
  get conflictsResolvedWithInput2() {
    return arrayCount(this.n.get().entries(), ([r2, s]) => r2.isConflicting && s.accepted.get().kind === ModifiedBaseRangeStateKind.input2);
  }
  get conflictsResolvedWithSmartCombination() {
    return arrayCount(this.n.get().entries(), ([r2, s]) => {
      const state = s.accepted.get();
      return r2.isConflicting && state.kind === ModifiedBaseRangeStateKind.both && state.smartCombination;
    });
  }
  get manuallySolvedConflictCountThatEqualNone() {
    return arrayCount(this.n.get().entries(), ([r2, s]) => r2.isConflicting && s.accepted.get().kind === ModifiedBaseRangeStateKind.unrecognized);
  }
  get manuallySolvedConflictCountThatEqualSmartCombine() {
    return arrayCount(this.n.get().entries(), ([r2, s]) => {
      const state = s.accepted.get();
      return r2.isConflicting && s.computedFromDiffing && state.kind === ModifiedBaseRangeStateKind.both && state.smartCombination;
    });
  }
  get manuallySolvedConflictCountThatEqualInput1() {
    return arrayCount(this.n.get().entries(), ([r2, s]) => {
      const state = s.accepted.get();
      return r2.isConflicting && s.computedFromDiffing && state.kind === ModifiedBaseRangeStateKind.input1;
    });
  }
  get manuallySolvedConflictCountThatEqualInput2() {
    return arrayCount(this.n.get().entries(), ([r2, s]) => {
      const state = s.accepted.get();
      return r2.isConflicting && s.computedFromDiffing && state.kind === ModifiedBaseRangeStateKind.input2;
    });
  }
  get manuallySolvedConflictCountThatEqualNoneAndStartedWithBase() {
    return arrayCount(this.n.get().entries(), ([r2, s]) => {
      const state = s.accepted.get();
      return r2.isConflicting && state.kind === ModifiedBaseRangeStateKind.unrecognized && s.previousNonDiffingState?.kind === ModifiedBaseRangeStateKind.base;
    });
  }
  get manuallySolvedConflictCountThatEqualNoneAndStartedWithInput1() {
    return arrayCount(this.n.get().entries(), ([r2, s]) => {
      const state = s.accepted.get();
      return r2.isConflicting && state.kind === ModifiedBaseRangeStateKind.unrecognized && s.previousNonDiffingState?.kind === ModifiedBaseRangeStateKind.input1;
    });
  }
  get manuallySolvedConflictCountThatEqualNoneAndStartedWithInput2() {
    return arrayCount(this.n.get().entries(), ([r2, s]) => {
      const state = s.accepted.get();
      return r2.isConflicting && state.kind === ModifiedBaseRangeStateKind.unrecognized && s.previousNonDiffingState?.kind === ModifiedBaseRangeStateKind.input2;
    });
  }
  get manuallySolvedConflictCountThatEqualNoneAndStartedWithBothNonSmart() {
    return arrayCount(this.n.get().entries(), ([r2, s]) => {
      const state = s.accepted.get();
      return r2.isConflicting && state.kind === ModifiedBaseRangeStateKind.unrecognized && s.previousNonDiffingState?.kind === ModifiedBaseRangeStateKind.both && !s.previousNonDiffingState?.smartCombination;
    });
  }
  get manuallySolvedConflictCountThatEqualNoneAndStartedWithBothSmart() {
    return arrayCount(this.n.get().entries(), ([r2, s]) => {
      const state = s.accepted.get();
      return r2.isConflicting && state.kind === ModifiedBaseRangeStateKind.unrecognized && s.previousNonDiffingState?.kind === ModifiedBaseRangeStateKind.both && s.previousNonDiffingState?.smartCombination;
    });
  }
};
$WHb = __decorate([
  __param(7, $1E),
  __param(8, $_F)
], $WHb);
function arrayCount(array2, predicate) {
  let count = 0;
  for (const value of array2) {
    if (predicate(value)) {
      count++;
    }
  }
  return count;
}
var ModifiedBaseRangeData = class {
  constructor(c) {
    this.c = c;
    this.accepted = $he(`BaseRangeState${this.c.baseRange}`, ModifiedBaseRangeState.base);
    this.handledInput1 = $he(`BaseRangeHandledState${this.c.baseRange}.Input1`, false);
    this.handledInput2 = $he(`BaseRangeHandledState${this.c.baseRange}.Input2`, false);
    this.computedFromDiffing = false;
    this.previousNonDiffingState = void 0;
    this.handled = $2d(this, (reader) => this.handledInput1.read(reader) && this.handledInput2.read(reader));
  }
};
var MergeEditorModelState;
(function(MergeEditorModelState2) {
  MergeEditorModelState2[MergeEditorModelState2["initializing"] = 1] = "initializing";
  MergeEditorModelState2[MergeEditorModelState2["upToDate"] = 2] = "upToDate";
  MergeEditorModelState2[MergeEditorModelState2["updating"] = 3] = "updating";
})(MergeEditorModelState || (MergeEditorModelState = {}));
var MarkAsHandledUndoRedoElement = class {
  constructor(resource, c, e, f, g) {
    this.resource = resource;
    this.c = c;
    this.e = e;
    this.f = f;
    this.g = g;
    this.code = "undoMarkAsHandled";
    this.label = localize(7998, null);
    this.type = 0;
  }
  redo() {
    const mergeEditorModel = this.c.deref();
    if (!mergeEditorModel || mergeEditorModel.isDisposed()) {
      return;
    }
    const state = this.e.deref();
    if (!state) {
      return;
    }
    $ce((tx) => {
      state.handledInput1.set(true, tx);
      state.handledInput2.set(true, tx);
    });
  }
  undo() {
    const mergeEditorModel = this.c.deref();
    if (!mergeEditorModel || mergeEditorModel.isDisposed()) {
      return;
    }
    const state = this.e.deref();
    if (!state) {
      return;
    }
    $ce((tx) => {
      state.handledInput1.set(this.f, tx);
      state.handledInput2.set(this.g, tx);
    });
  }
};

// out-build/vs/workbench/contrib/mergeEditor/common/mergeEditor.js
var $gIb = new $nn("isMergeEditor", false, { type: "boolean", description: localize(8054, null) });
var $hIb = new $nn("isMergeResultEditor", false, { type: "boolean", description: localize(8055, null) });
var $iIb = new $nn("mergeEditorLayout", "mixed", { type: "string", description: localize(8056, null) });
var $jIb = new $nn("mergeEditorShowBase", false, { type: "boolean", description: localize(8057, null) });
var $kIb = new $nn("mergeEditorShowBaseAtTop", false, { type: "boolean", description: localize(8058, null) });
var $lIb = new $nn("mergeEditorShowNonConflictingChanges", false, { type: "boolean", description: localize(8059, null) });
var $mIb = new $nn("mergeEditorBaseUri", "", { type: "string", description: localize(8060, null) });
var $nIb = new $nn("mergeEditorResultUri", "", { type: "string", description: localize(8061, null) });
var $oIb = "mergeEditorCloseWithConflicts";

// out-build/vs/workbench/contrib/mergeEditor/browser/mergeEditorInputModel.js
var $5Ob_1;
var $4Ob = class $4Ob2 {
  constructor(a, b, c, d) {
    this.a = a;
    this.b = b;
    this.c = c;
    this.d = d;
  }
  async createInputModel(args2) {
    const store = new $2c();
    const [base, result, input1Data, input2Data] = await Promise.all([
      this.c.createModelReference(args2.base),
      this.c.createModelReference(args2.result),
      toInputData(args2.input1, this.c, store),
      toInputData(args2.input2, this.c, store)
    ]);
    store.add(base);
    store.add(result);
    const tempResultUri = result.object.textEditorModel.uri.with({ scheme: "merge-result" });
    const temporaryResultModel = this.d.createModel("", {
      languageId: result.object.textEditorModel.getLanguageId(),
      onDidChange: Event2.None
    }, tempResultUri);
    store.add(temporaryResultModel);
    const mergeDiffComputer = this.b.createInstance($RHb);
    const model = this.b.createInstance($WHb, base.object.textEditorModel, input1Data, input2Data, temporaryResultModel, mergeDiffComputer, {
      resetResult: true
    }, this.a);
    store.add(model);
    await model.onInitialized;
    return this.b.createInstance(TempFileMergeEditorInputModel, model, store, result.object, args2.result);
  }
};
$4Ob = __decorate([
  __param(1, $Pk),
  __param(2, $oG),
  __param(3, $sG)
], $4Ob);
var TempFileMergeEditorInputModel = class TempFileMergeEditorInputModel2 extends $rG {
  constructor(model, g, j, resultUri, n, r2, s) {
    super();
    this.model = model;
    this.g = g;
    this.j = j;
    this.resultUri = resultUri;
    this.n = n;
    this.r = r2;
    this.s = s;
    this.a = $he(this, this.model.resultTextModel.getAlternativeVersionId());
    this.b = $Dd(this, (e) => this.model.resultTextModel.onDidChangeContent(e), () => (
      /** @description getAlternativeVersionId */
      this.model.resultTextModel.getAlternativeVersionId()
    ));
    this.isDirty = $2d(this, (reader) => this.b.read(reader) !== this.a.read(reader));
    this.c = false;
  }
  dispose() {
    this.g.dispose();
    super.dispose();
  }
  async accept() {
    const value = await this.model.resultTextModel.getValue();
    this.j.textEditorModel.setValue(value);
    this.a.set(this.model.resultTextModel.getAlternativeVersionId(), void 0);
    await this.n.save(this.j.textEditorModel.uri);
    this.c = true;
  }
  async t() {
    await this.n.revert(this.model.resultTextModel.uri);
    this.a.set(this.model.resultTextModel.getAlternativeVersionId(), void 0);
    this.c = true;
  }
  shouldConfirmClose() {
    return true;
  }
  async confirmClose(inputModels) {
    $kd(() => inputModels.some((m) => m === this));
    const someDirty = inputModels.some((m) => m.isDirty.get());
    let choice;
    if (someDirty) {
      const isMany = inputModels.length > 1;
      const message = isMany ? localize(7966, null, inputModels.length) : localize(7967, null, $sh(inputModels[0].model.resultTextModel.uri));
      const hasUnhandledConflicts = inputModels.some((m) => m.model.hasUnhandledConflicts.get());
      const buttons = [
        {
          label: hasUnhandledConflicts ? localize(7968, null) : localize(7969, null),
          run: () => 0
          /* ConfirmResult.SAVE */
        },
        {
          label: localize(7970, null),
          run: () => 1
          /* ConfirmResult.DONT_SAVE */
        }
      ];
      choice = (await this.r.prompt({
        type: severity_default.Info,
        message,
        detail: hasUnhandledConflicts ? isMany ? localize(7971, null) : localize(7972, null) : isMany ? localize(7973, null) : localize(7974, null),
        buttons,
        cancelButton: {
          run: () => 2
          /* ConfirmResult.CANCEL */
        }
      })).result;
    } else {
      choice = 1;
    }
    if (choice === 0) {
      await Promise.all(inputModels.map((m) => m.accept()));
    } else if (choice === 1) {
      await Promise.all(inputModels.map((m) => m.t()));
    } else {
    }
    return choice;
  }
  async save(options3) {
    if (this.c) {
      return;
    }
    (async () => {
      const { confirmed } = await this.r.confirm({
        message: localize(7975, null),
        detail: localize(7976, null),
        primaryButton: localize(7977, null)
      });
      if (confirmed) {
        await this.accept();
        const editors = this.s.findEditors(this.resultUri).filter((e) => e.editor.typeId === "mergeEditor.Input");
        await this.s.closeEditors(editors);
      }
    })();
  }
  async revert(options3) {
  }
};
TempFileMergeEditorInputModel = __decorate([
  __param(4, $cK),
  __param(5, $Yv),
  __param(6, $mJ)
], TempFileMergeEditorInputModel);
var $5Ob = class $5Ob2 {
  static {
    $5Ob_1 = this;
  }
  constructor(a, b, c, d) {
    this.a = a;
    this.b = b;
    this.c = c;
    this.d = d;
  }
  static {
    this.f = $bL.registerSource("merge-editor.source", localize(7978, null));
  }
  async createInputModel(args2) {
    const store = new $2c();
    let resultTextFileModel = void 0;
    const modelListener = store.add(new $2c());
    const handleDidCreate = (model2) => {
      if ($oh(args2.result, model2.resource)) {
        modelListener.clear();
        resultTextFileModel = model2;
      }
    };
    modelListener.add(this.d.files.onDidCreate(handleDidCreate));
    this.d.files.models.forEach(handleDidCreate);
    const [base, result, input1Data, input2Data] = await Promise.all([
      this.c.createModelReference(args2.base),
      this.c.createModelReference(args2.result),
      toInputData(args2.input1, this.c, store),
      toInputData(args2.input2, this.c, store)
    ]);
    store.add(base);
    store.add(result);
    if (!resultTextFileModel) {
      throw new $vb();
    }
    await resultTextFileModel.save({ source: $5Ob_1.f });
    const lines = resultTextFileModel.textEditorModel.getLinesContent();
    const hasConflictMarkers = lines.some((l) => l.startsWith($2Ob.start));
    const resetResult = hasConflictMarkers;
    const mergeDiffComputer = this.b.createInstance($RHb);
    const model = this.b.createInstance($WHb, base.object.textEditorModel, input1Data, input2Data, result.object.textEditorModel, mergeDiffComputer, {
      resetResult
    }, this.a);
    store.add(model);
    await model.onInitialized;
    return this.b.createInstance(WorkspaceMergeEditorInputModel, model, store, resultTextFileModel, this.a);
  }
};
$5Ob = $5Ob_1 = __decorate([
  __param(1, $Pk),
  __param(2, $oG),
  __param(3, $cK)
], $5Ob);
var WorkspaceMergeEditorInputModel = class WorkspaceMergeEditorInputModel2 extends $rG {
  constructor(model, c, g, j, n, r2) {
    super();
    this.model = model;
    this.c = c;
    this.g = g;
    this.j = j;
    this.n = n;
    this.r = r2;
    this.isDirty = $Dd(this, Event2.any(this.g.onDidChangeDirty, this.g.onDidSaveError), () => (
      /** @description isDirty */
      this.g.isDirty()
    ));
    this.a = false;
    this.b = /* @__PURE__ */ new Date();
  }
  dispose() {
    this.c.dispose();
    super.dispose();
    this.s(false);
  }
  s(accepted) {
    if (!this.a) {
      const remainingConflictCount = this.model.unhandledConflictsCount.get();
      const durationOpenedMs = (/* @__PURE__ */ new Date()).getTime() - this.b.getTime();
      this.j.reportMergeEditorClosed({
        durationOpenedSecs: durationOpenedMs / 1e3,
        remainingConflictCount,
        accepted,
        conflictCount: this.model.conflictCount,
        combinableConflictCount: this.model.combinableConflictCount,
        conflictsResolvedWithBase: this.model.conflictsResolvedWithBase,
        conflictsResolvedWithInput1: this.model.conflictsResolvedWithInput1,
        conflictsResolvedWithInput2: this.model.conflictsResolvedWithInput2,
        conflictsResolvedWithSmartCombination: this.model.conflictsResolvedWithSmartCombination,
        manuallySolvedConflictCountThatEqualNone: this.model.manuallySolvedConflictCountThatEqualNone,
        manuallySolvedConflictCountThatEqualSmartCombine: this.model.manuallySolvedConflictCountThatEqualSmartCombine,
        manuallySolvedConflictCountThatEqualInput1: this.model.manuallySolvedConflictCountThatEqualInput1,
        manuallySolvedConflictCountThatEqualInput2: this.model.manuallySolvedConflictCountThatEqualInput2,
        manuallySolvedConflictCountThatEqualNoneAndStartedWithBase: this.model.manuallySolvedConflictCountThatEqualNoneAndStartedWithBase,
        manuallySolvedConflictCountThatEqualNoneAndStartedWithInput1: this.model.manuallySolvedConflictCountThatEqualNoneAndStartedWithInput1,
        manuallySolvedConflictCountThatEqualNoneAndStartedWithInput2: this.model.manuallySolvedConflictCountThatEqualNoneAndStartedWithInput2,
        manuallySolvedConflictCountThatEqualNoneAndStartedWithBothNonSmart: this.model.manuallySolvedConflictCountThatEqualNoneAndStartedWithBothNonSmart,
        manuallySolvedConflictCountThatEqualNoneAndStartedWithBothSmart: this.model.manuallySolvedConflictCountThatEqualNoneAndStartedWithBothSmart
      });
      this.a = true;
    }
  }
  async accept() {
    this.s(true);
    await this.g.save();
  }
  get resultUri() {
    return this.g.resource;
  }
  async save(options3) {
    await this.g.save(options3);
  }
  /**
   * If save resets the dirty state, revert must do so too.
  */
  async revert(options3) {
    await this.g.revert(options3);
  }
  shouldConfirmClose() {
    return true;
  }
  async confirmClose(inputModels) {
    const isMany = inputModels.length > 1;
    const someDirty = inputModels.some((m) => m.isDirty.get());
    const someUnhandledConflicts = inputModels.some((m) => m.model.hasUnhandledConflicts.get());
    if (someDirty) {
      const message = isMany ? localize(7979, null, inputModels.length) : localize(7980, null, $sh(inputModels[0].resultUri));
      const { result } = await this.n.prompt({
        type: severity_default.Info,
        message,
        detail: someUnhandledConflicts ? isMany ? localize(7981, null) : localize(7982, null) : isMany ? localize(7983, null) : localize(7984, null),
        buttons: [
          {
            label: someUnhandledConflicts ? localize(7985, null) : localize(7986, null),
            run: () => 0
            /* ConfirmResult.SAVE */
          },
          {
            label: localize(7987, null),
            run: () => 1
            /* ConfirmResult.DONT_SAVE */
          }
        ],
        cancelButton: {
          run: () => 2
          /* ConfirmResult.CANCEL */
        }
      });
      return result;
    } else if (someUnhandledConflicts && !this.r.getBoolean($oIb, 0, false)) {
      const { confirmed, checkboxChecked } = await this.n.confirm({
        message: isMany ? localize(7988, null, inputModels.length) : localize(7989, null, $sh(inputModels[0].resultUri)),
        detail: someUnhandledConflicts ? isMany ? localize(7990, null) : localize(7991, null) : void 0,
        primaryButton: someUnhandledConflicts ? localize(7992, null) : localize(7993, null),
        checkbox: { label: localize(7994, null) }
      });
      if (checkboxChecked) {
        this.r.store(
          $oIb,
          true,
          0,
          0
          /* StorageTarget.USER */
        );
      }
      return confirmed ? 0 : 2;
    } else {
      return 0;
    }
  }
};
WorkspaceMergeEditorInputModel = __decorate([
  __param(4, $Yv),
  __param(5, $jv)
], WorkspaceMergeEditorInputModel);
async function toInputData(data, textModelService, store) {
  const ref = await textModelService.createModelReference(data.uri);
  store.add(ref);
  return {
    textModel: ref.object.textEditorModel,
    title: data.title,
    description: data.description,
    detail: data.detail
  };
}

// out-build/vs/workbench/contrib/mergeEditor/browser/telemetry.js
var $VHb = class $VHb2 {
  constructor(a) {
    this.a = a;
  }
  reportMergeEditorOpened(args2) {
    this.a.publicLog2("mergeEditor.opened", {
      conflictCount: args2.conflictCount,
      combinableConflictCount: args2.combinableConflictCount,
      baseVisible: args2.baseVisible,
      isColumnView: args2.isColumnView,
      baseTop: args2.baseTop
    });
  }
  reportLayoutChange(args2) {
    this.a.publicLog2("mergeEditor.layoutChanged", {
      baseVisible: args2.baseVisible,
      isColumnView: args2.isColumnView,
      baseTop: args2.baseTop
    });
  }
  reportMergeEditorClosed(args2) {
    this.a.publicLog2("mergeEditor.closed", {
      conflictCount: args2.conflictCount,
      combinableConflictCount: args2.combinableConflictCount,
      durationOpenedSecs: args2.durationOpenedSecs,
      remainingConflictCount: args2.remainingConflictCount,
      accepted: args2.accepted,
      conflictsResolvedWithBase: args2.conflictsResolvedWithBase,
      conflictsResolvedWithInput1: args2.conflictsResolvedWithInput1,
      conflictsResolvedWithInput2: args2.conflictsResolvedWithInput2,
      conflictsResolvedWithSmartCombination: args2.conflictsResolvedWithSmartCombination,
      manuallySolvedConflictCountThatEqualNone: args2.manuallySolvedConflictCountThatEqualNone,
      manuallySolvedConflictCountThatEqualSmartCombine: args2.manuallySolvedConflictCountThatEqualSmartCombine,
      manuallySolvedConflictCountThatEqualInput1: args2.manuallySolvedConflictCountThatEqualInput1,
      manuallySolvedConflictCountThatEqualInput2: args2.manuallySolvedConflictCountThatEqualInput2,
      manuallySolvedConflictCountThatEqualNoneAndStartedWithBase: args2.manuallySolvedConflictCountThatEqualNoneAndStartedWithBase,
      manuallySolvedConflictCountThatEqualNoneAndStartedWithInput1: args2.manuallySolvedConflictCountThatEqualNoneAndStartedWithInput1,
      manuallySolvedConflictCountThatEqualNoneAndStartedWithInput2: args2.manuallySolvedConflictCountThatEqualNoneAndStartedWithInput2,
      manuallySolvedConflictCountThatEqualNoneAndStartedWithBothNonSmart: args2.manuallySolvedConflictCountThatEqualNoneAndStartedWithBothNonSmart,
      manuallySolvedConflictCountThatEqualNoneAndStartedWithBothSmart: args2.manuallySolvedConflictCountThatEqualNoneAndStartedWithBothSmart
    });
  }
  reportAcceptInvoked(inputNumber, otherAccepted) {
    this.a.publicLog2("mergeEditor.action.accept", {
      otherAccepted,
      isInput1: inputNumber === 1
    });
  }
  reportSmartCombinationInvoked(otherAccepted) {
    this.a.publicLog2("mergeEditor.action.smartCombination", {
      otherAccepted
    });
  }
  reportRemoveInvoked(inputNumber, otherAccepted) {
    this.a.publicLog2("mergeEditor.action.remove", {
      otherAccepted,
      isInput1: inputNumber === 1
    });
  }
  reportResetToBaseInvoked() {
    this.a.publicLog2("mergeEditor.action.resetToBase", {});
  }
  reportNavigationToNextConflict() {
    this.a.publicLog2("mergeEditor.action.goToNextConflict", {});
  }
  reportNavigationToPreviousConflict() {
    this.a.publicLog2("mergeEditor.action.goToPreviousConflict", {});
  }
  reportConflictCounterClicked() {
    this.a.publicLog2("mergeEditor.action.conflictCounterClicked", {});
  }
};
$VHb = __decorate([
  __param(0, $zv)
], $VHb);

// out-build/vs/workbench/contrib/mergeEditor/browser/mergeEditorInput.js
var $7Ob_1;
var $6Ob = class {
  constructor(uri, title, detail2, description) {
    this.uri = uri;
    this.title = title;
    this.detail = detail2;
    this.description = description;
  }
};
var $7Ob = class $7Ob2 extends $5vb {
  static {
    $7Ob_1 = this;
  }
  static {
    this.ID = "mergeEditor.Input";
  }
  get U() {
    return this.X.getValue("mergeEditor.useWorkingCopy") ?? false;
  }
  constructor(base, input1, input2, result, W, editorService, textFileService, labelService, fileService, X, filesConfigurationService, textResourceConfigurationService, customEditorLabelService) {
    super(result, void 0, editorService, textFileService, labelService, fileService, filesConfigurationService, textResourceConfigurationService, customEditorLabelService);
    this.base = base;
    this.input1 = input1;
    this.input2 = input2;
    this.result = result;
    this.W = W;
    this.X = X;
    this.closeHandler = {
      showConfirm: () => this.c?.shouldConfirmClose() ?? false,
      confirm: async (editors) => {
        $kd(() => editors.every((e) => e.editor instanceof $7Ob_1));
        const inputModels = editors.map((e) => e.editor.c).filter($Hg);
        return await this.c.confirmClose(inputModels);
      }
    };
    this.Y = this.W.createInstance(this.U ? $4Ob : $5Ob, this.W.createInstance($VHb));
  }
  dispose() {
    super.dispose();
  }
  get typeId() {
    return $7Ob_1.ID;
  }
  get editorId() {
    return $1K.id;
  }
  get capabilities() {
    let capabilities = super.capabilities | 256;
    if (this.U) {
      capabilities |= 4;
    }
    return capabilities;
  }
  getName() {
    return localize(7965, null, super.getName());
  }
  async resolve() {
    if (!this.c) {
      const inputModel = this.B(await this.Y.createInputModel({
        base: this.base,
        input1: this.input1,
        input2: this.input2,
        result: this.result
      }));
      this.c = inputModel;
      this.B($td((reader) => {
        inputModel.isDirty.read(reader);
        this.f.fire();
      }));
      await this.c.model.onInitialized;
    }
    return this.c;
  }
  async accept() {
    await this.c?.accept();
  }
  async save(group2, options3) {
    await this.c?.save(options3);
    return void 0;
  }
  toUntyped() {
    return {
      input1: { resource: this.input1.uri, label: this.input1.title, description: this.input1.description, detail: this.input1.detail },
      input2: { resource: this.input2.uri, label: this.input2.title, description: this.input2.description, detail: this.input2.detail },
      base: { resource: this.base },
      result: { resource: this.result },
      options: {
        override: this.typeId
      }
    };
  }
  matches(otherInput) {
    if (this === otherInput) {
      return true;
    }
    if (otherInput instanceof $7Ob_1) {
      return $oh(this.base, otherInput.base) && $oh(this.input1.uri, otherInput.input1.uri) && $oh(this.input2.uri, otherInput.input2.uri) && $oh(this.result, otherInput.result);
    }
    if ($aL(otherInput)) {
      return (this.editorId === otherInput.options?.override || otherInput.options?.override === void 0) && $oh(this.base, otherInput.base.resource) && $oh(this.input1.uri, otherInput.input1.resource) && $oh(this.input2.uri, otherInput.input2.resource) && $oh(this.result, otherInput.result.resource);
    }
    return false;
  }
  async revert(group2, options3) {
    return this.c?.revert(options3);
  }
  // ---- FileEditorInput
  isDirty() {
    return this.c?.isDirty.get() ?? false;
  }
  setLanguageId(languageId, source) {
    this.c?.model.setLanguageId(languageId, source);
  }
};
$7Ob = $7Ob_1 = __decorate([
  __param(4, $Pk),
  __param(5, $mJ),
  __param(6, $cK),
  __param(7, $ZI),
  __param(8, $km),
  __param(9, $kl),
  __param(10, $4J),
  __param(11, $zG),
  __param(12, $qrb)
], $7Ob);

// out-build/vs/editor/browser/widget/multiDiffEditor/multiDiffEditorViewModel.js
var $4Eb = class extends $3c {
  async waitForDiffs() {
    for (const d of this.items.get()) {
      await d.diffEditorViewModel.waitForDiff();
    }
  }
  collapseAll() {
    $ce((tx) => {
      for (const d of this.items.get()) {
        d.collapsed.set(true, tx);
      }
    });
  }
  expandAll() {
    $ce((tx) => {
      for (const d of this.items.get()) {
        d.collapsed.set(false, tx);
      }
    });
  }
  get contextKeys() {
    return this.model.contextKeys;
  }
  constructor(model, c) {
    super();
    this.model = model;
    this.c = c;
    this.a = $Td(this.model, this.model.documents);
    this.b = $2d(this, (reader) => {
      const result = this.a.read(reader);
      if (result === "loading") {
        return [];
      }
      return result;
    });
    this.isLoading = $2d(this, (reader) => this.a.read(reader) === "loading");
    this.items = $Rd(this, this.b, (d, store) => store.add(this.c.createInstance($5Eb, d, this))).recomputeInitiallyAndOnChange(this.q);
    this.focusedDiffItem = $2d(this, (reader) => this.items.read(reader).find((i2) => i2.isFocused.read(reader)));
    this.activeDiffItem = $Qd(this, (reader, lastValue) => this.focusedDiffItem.read(reader) ?? (lastValue && this.items.read(reader).indexOf(lastValue) !== -1) ? lastValue : void 0);
  }
};
var $5Eb = class $5Eb2 extends $3c {
  get diffEditorViewModel() {
    return this.diffEditorViewModelRef.object;
  }
  get originalUri() {
    return this.documentDiffItem.original?.uri;
  }
  get modifiedUri() {
    return this.documentDiffItem.modified?.uri;
  }
  setIsFocused(source, tx) {
    this.a.set(source, tx);
  }
  get documentDiffItem() {
    return this.b.object;
  }
  constructor(documentDiffItem, c, f, g) {
    super();
    this.c = c;
    this.f = f;
    this.g = g;
    this.collapsed = $he(this, false);
    this.lastTemplateData = $he(this, { contentHeight: 500, selections: void 0 });
    this.isActive = $2d(this, (reader) => this.c.activeDiffItem.read(reader) === this);
    this.a = $he(this, $Bd(false));
    this.isFocused = $2d(this, (reader) => this.a.read(reader).read(reader));
    this.isAlive = $he(this, true);
    this.B($1c(() => {
      this.isAlive.set(false, void 0);
    }));
    this.b = this.B(documentDiffItem.createNewRef(this));
    function updateOptions(options4) {
      return {
        ...options4,
        hideUnchangedRegions: {
          enabled: true
        }
      };
    }
    const options3 = this.f.createInstance($a$, updateOptions(this.documentDiffItem.options || {}));
    if (this.documentDiffItem.onOptionsDidChange) {
      this.B(this.documentDiffItem.onOptionsDidChange(() => {
        options3.updateOptions(updateOptions(this.documentDiffItem.options || {}));
      }));
    }
    const diffEditorViewModelStore = new $2c();
    const originalTextModel = this.documentDiffItem.original ?? diffEditorViewModelStore.add(this.g.createModel("", null));
    const modifiedTextModel = this.documentDiffItem.modified ?? diffEditorViewModelStore.add(this.g.createModel("", null));
    diffEditorViewModelStore.add(this.b.createNewRef(this));
    this.diffEditorViewModelRef = this.B($69.createWithDisposable(this.f.createInstance($b$, {
      original: originalTextModel,
      modified: modifiedTextModel
    }, options3), diffEditorViewModelStore, this));
  }
  getKey() {
    return JSON.stringify([
      this.originalUri?.toString(),
      this.modifiedUri?.toString()
    ]);
  }
};
$5Eb = __decorate([
  __param(2, $Pk),
  __param(3, $sG)
], $5Eb);

// out-build/vs/workbench/contrib/multiDiffEditor/browser/icons.contribution.js
var $$Eb = $9r("multi-diff-editor-label-icon", $6l.diffMultiple, localize(8069, null));

// out-build/vs/workbench/contrib/multiDiffEditor/browser/multiDiffEditorInput.js
var $_Eb_1;
var $_Eb = class $_Eb2 extends $nG {
  static {
    $_Eb_1 = this;
  }
  static fromResourceMultiDiffEditorInput(input, instantiationService) {
    if (!input.multiDiffSource && !input.resources) {
      throw new $vb("MultiDiffEditorInput requires either multiDiffSource or resources");
    }
    const multiDiffSource = input.multiDiffSource ?? URI.parse(`multi-diff-editor:${(/* @__PURE__ */ new Date()).getMilliseconds().toString() + Math.random().toString()}`);
    return instantiationService.createInstance($_Eb_1, multiDiffSource, input.label, input.resources?.map((resource) => {
      return new $UDb(resource.original.resource, resource.modified.resource, resource.goToFileResource);
    }), input.isTransient ?? false);
  }
  static fromSerialized(data, instantiationService) {
    return instantiationService.createInstance($_Eb_1, URI.parse(data.multiDiffSourceUri), data.label, data.resources?.map((resource) => new $UDb(resource.originalUri ? URI.parse(resource.originalUri) : void 0, resource.modifiedUri ? URI.parse(resource.modifiedUri) : void 0, resource.goToFileUri ? URI.parse(resource.goToFileUri) : void 0)), false);
  }
  static {
    this.ID = "workbench.input.multiDiffEditor";
  }
  get resource() {
    return this.multiDiffSource;
  }
  get capabilities() {
    return 2;
  }
  get typeId() {
    return $_Eb_1.ID;
  }
  getName() {
    return this.b;
  }
  get editorId() {
    return $1K.id;
  }
  getIcon() {
    return $$Eb;
  }
  constructor(multiDiffSource, label3, initialResources, isTransient = false, c, m, s, t, u) {
    super();
    this.multiDiffSource = multiDiffSource;
    this.label = label3;
    this.initialResources = initialResources;
    this.isTransient = isTransient;
    this.c = c;
    this.m = m;
    this.s = s;
    this.t = t;
    this.u = u;
    this.b = "";
    this.w = new $ii(async () => {
      const model = await this.y();
      this.B(model);
      const vm = new $4Eb(model, this.s);
      this.B(vm);
      await $Lh(vm.waitForDiffs(), 1e3);
      return vm;
    });
    this.z = new $qe(async () => {
      const source = this.initialResources ? { resources: $Je.const(this.initialResources) } : await this.t.resolve(this.multiDiffSource);
      return {
        source,
        resources: source ? $Td(this, source.resources) : $Bd([])
      };
    });
    this.resources = $2d(this, (reader) => this.z.cachedPromiseResult.read(reader)?.data?.resources.read(reader));
    this.C = new FastEventDispatcher(this.u.files.onDidChangeDirty, (item) => item.resource.toString(), (uri) => uri.toString());
    this.D = $Rd(this, this.resources.map((r2) => r2 ?? []), (res) => {
      const isModifiedDirty = res.modifiedUri ? isUriDirty(this.C, this.u, res.modifiedUri) : $Bd(false);
      const isOriginalDirty = res.originalUri ? isUriDirty(this.C, this.u, res.originalUri) : $Bd(false);
      return $2d((reader) => (
        /** @description modifiedDirty||originalDirty */
        isModifiedDirty.read(reader) || isOriginalDirty.read(reader)
      ));
    }, (i2) => i2.getKey());
    this.F = $2d(this, (reader) => this.D.read(reader).some((isDirty) => isDirty.read(reader))).keepObserved(this.q);
    this.onDidChangeDirty = Event2.fromObservableLight(this.F);
    this.closeHandler = {
      // TODO@bpasero TODO@hediet this is a workaround for
      // not having a better way to figure out if the
      // editors this input wraps around are opened or not
      async confirm() {
        return 1;
      },
      showConfirm() {
        return false;
      }
    };
    this.B($td((reader) => {
      const resources = this.resources.read(reader);
      const label4 = this.label ?? localize(8071, null);
      if (resources) {
        this.b = label4 + localize(8072, null, resources.length);
      } else {
        this.b = label4;
      }
      this.g.fire();
    }));
  }
  serialize() {
    return {
      label: this.label,
      multiDiffSourceUri: this.multiDiffSource.toString(),
      resources: this.initialResources?.map((resource) => ({
        originalUri: resource.originalUri?.toString(),
        modifiedUri: resource.modifiedUri?.toString(),
        goToFileUri: resource.goToFileUri?.toString()
      }))
    };
  }
  setLanguageId(languageId, source) {
    const activeDiffItem = this.w.requireValue().activeDiffItem.get();
    const value = activeDiffItem?.documentDiffItem;
    if (!value) {
      return;
    }
    const target = value.modified ?? value.original;
    if (!target) {
      return;
    }
    target.setLanguage(languageId, source);
  }
  async getViewModel() {
    return this.w.getPromise();
  }
  async y() {
    const source = await this.z.getPromise();
    const textResourceConfigurationService = this.m;
    const documentsWithPromises = $Rd(this, source.resources, async (r2, store) => {
      let original;
      let modified;
      const multiDiffItemStore = new $2c();
      try {
        [original, modified] = await Promise.all([
          r2.originalUri ? this.c.createModelReference(r2.originalUri) : void 0,
          r2.modifiedUri ? this.c.createModelReference(r2.modifiedUri) : void 0
        ]);
        if (original) {
          multiDiffItemStore.add(original);
        }
        if (modified) {
          multiDiffItemStore.add(modified);
        }
      } catch (e) {
        console.error(e);
        $gb(e);
        return void 0;
      }
      const uri = r2.modifiedUri ?? r2.originalUri;
      const result2 = {
        multiDiffEditorItem: r2,
        original: original?.object.textEditorModel,
        modified: modified?.object.textEditorModel,
        contextKeys: r2.contextKeys,
        get options() {
          return {
            ...getReadonlyConfiguration(modified?.object.isReadonly() ?? true),
            ...computeOptions(textResourceConfigurationService.getValue(uri))
          };
        },
        onOptionsDidChange: (h3) => this.m.onDidChangeConfiguration((e) => {
          if (e.affectsConfiguration(uri, "editor") || e.affectsConfiguration(uri, "diffEditor")) {
            h3();
          }
        })
      };
      return store.add($69.createOfNonDisposable(result2, multiDiffItemStore, this));
    }, (i2) => JSON.stringify([i2.modifiedUri?.toString(), i2.originalUri?.toString()]));
    const documents = $he("documents", "loading");
    const updateDocuments = $2d(async (reader) => {
      const docsPromises = documentsWithPromises.read(reader);
      const docs = await Promise.all(docsPromises);
      const newDocuments = docs.filter($Hg);
      documents.set(newDocuments, void 0);
    });
    const a = $Nd(updateDocuments);
    await updateDocuments.get();
    const result = {
      dispose: () => a.dispose(),
      documents: new $Sd(documents),
      contextKeys: source.source?.contextKeys
    };
    return result;
  }
  matches(otherInput) {
    if (super.matches(otherInput)) {
      return true;
    }
    if (otherInput instanceof $_Eb_1) {
      return this.multiDiffSource.toString() === otherInput.multiDiffSource.toString();
    }
    return false;
  }
  isDirty() {
    return this.F.get();
  }
  async save(group2, options3) {
    await this.G("save", group2, options3);
    return this;
  }
  revert(group2, options3) {
    return this.G("revert", group2, options3);
  }
  async G(mode, group2, options3) {
    const items = this.w.currentValue?.items.get();
    if (items) {
      await Promise.all(items.map(async (item) => {
        const model = item.diffEditorViewModel.model;
        const handleOriginal = model.original.uri.scheme !== Schemas.untitled && this.u.isDirty(model.original.uri);
        await Promise.all([
          handleOriginal ? mode === "save" ? this.u.save(model.original.uri, options3) : this.u.revert(model.original.uri, options3) : Promise.resolve(),
          mode === "save" ? this.u.save(model.modified.uri, options3) : this.u.revert(model.modified.uri, options3)
        ]);
      }));
    }
    return void 0;
  }
};
$_Eb = $_Eb_1 = __decorate([
  __param(4, $oG),
  __param(5, $zG),
  __param(6, $Pk),
  __param(7, $TDb),
  __param(8, $cK)
], $_Eb);
var FastEventDispatcher = class {
  constructor(f, g, j) {
    this.f = f;
    this.g = g;
    this.j = j;
    this.b = 0;
    this.c = /* @__PURE__ */ new Map();
    this.k = (e) => {
      const key2 = this.g(e);
      const bucket = this.c.get(key2);
      if (bucket) {
        for (const listener of bucket) {
          listener(e);
        }
      }
    };
  }
  filteredEvent(filter) {
    return (listener) => {
      const key2 = this.j(filter);
      let bucket = this.c.get(key2);
      if (!bucket) {
        bucket = /* @__PURE__ */ new Set();
        this.c.set(key2, bucket);
      }
      bucket.add(listener);
      this.b++;
      if (this.b === 1) {
        this.d = this.f(this.k);
      }
      return {
        dispose: () => {
          bucket.delete(listener);
          if (bucket.size === 0) {
            this.c.delete(key2);
          }
          this.b--;
          if (this.b === 0) {
            this.d?.dispose();
            this.d = void 0;
          }
        }
      };
    };
  }
};
function isUriDirty(onDidChangeDirty, textFileService, uri) {
  return $Dd(onDidChangeDirty.filteredEvent(uri), () => textFileService.isDirty(uri));
}
function getReadonlyConfiguration(isReadonly) {
  return {
    readOnly: !!isReadonly,
    readOnlyMessage: typeof isReadonly !== "boolean" ? isReadonly : void 0
  };
}
function computeOptions(configuration2) {
  const editorConfiguration2 = $Lv(configuration2.editor);
  if ($Bg(configuration2.diffEditor)) {
    const diffEditorConfiguration = $Lv(configuration2.diffEditor);
    diffEditorConfiguration.diffCodeLens = diffEditorConfiguration.codeLens;
    delete diffEditorConfiguration.codeLens;
    diffEditorConfiguration.diffWordWrap = diffEditorConfiguration.wordWrap;
    delete diffEditorConfiguration.wordWrap;
    Object.assign(editorConfiguration2, diffEditorConfiguration);
  }
  return editorConfiguration2;
}
var $aFb = class $aFb2 extends $3c {
  static {
    this.ID = "workbench.contrib.multiDiffEditorResolver";
  }
  constructor(editorResolverService, instantiationService) {
    super();
    this.B(editorResolverService.registerEditor(`*`, {
      id: $1K.id,
      label: $1K.displayName,
      detail: $1K.providerDisplayName,
      priority: RegisteredEditorPriority.builtin
    }, {}, {
      createMultiDiffEditorInput: (multiDiffEditor) => {
        return {
          editor: $_Eb.fromResourceMultiDiffEditorInput(multiDiffEditor, instantiationService)
        };
      }
    }));
  }
};
$aFb = __decorate([
  __param(0, $4L),
  __param(1, $Pk)
], $aFb);
var $bFb = class {
  canSerialize(editor) {
    return editor instanceof $_Eb && !editor.isTransient;
  }
  serialize(editor) {
    if (!this.canSerialize(editor)) {
      return void 0;
    }
    return JSON.stringify(editor.serialize());
  }
  deserialize(instantiationService, serializedEditor) {
    try {
      const data = $bu(serializedEditor);
      return $_Eb.fromSerialized(data, instantiationService);
    } catch (err) {
      $gb(err);
      return void 0;
    }
  }
};

// out-build/vs/workbench/contrib/terminal/browser/terminal.js
var $4Pb = $Qk("terminalService");
var $5Pb = $Qk("terminalConfigurationService");
var $6Pb = $Qk("terminalEditorService");
var $7Pb = $Qk("terminalGroupService");
var $8Pb = $Qk("terminalInstanceService");
var Direction2;
(function(Direction4) {
  Direction4[Direction4["Left"] = 0] = "Left";
  Direction4[Direction4["Right"] = 1] = "Right";
  Direction4[Direction4["Up"] = 2] = "Up";
  Direction4[Direction4["Down"] = 3] = "Down";
})(Direction2 || (Direction2 = {}));
var TerminalConnectionState;
(function(TerminalConnectionState2) {
  TerminalConnectionState2[TerminalConnectionState2["Connecting"] = 0] = "Connecting";
  TerminalConnectionState2[TerminalConnectionState2["Connected"] = 1] = "Connected";
})(TerminalConnectionState || (TerminalConnectionState = {}));
var $9Pb = (t) => typeof t.instanceId !== "number";
var $0Pb = class extends MouseEvent {
};
var $$Pb = "terminalEditor";
var XtermTerminalConstants;
(function(XtermTerminalConstants2) {
  XtermTerminalConstants2[XtermTerminalConstants2["SearchHighlightLimit"] = 2e4] = "SearchHighlightLimit";
})(XtermTerminalConstants || (XtermTerminalConstants = {}));
var LinuxDistro;
(function(LinuxDistro2) {
  LinuxDistro2[LinuxDistro2["Unknown"] = 1] = "Unknown";
  LinuxDistro2[LinuxDistro2["Fedora"] = 2] = "Fedora";
  LinuxDistro2[LinuxDistro2["Ubuntu"] = 3] = "Ubuntu";
})(LinuxDistro || (LinuxDistro = {}));
var TerminalDataTransfers;
(function(TerminalDataTransfers2) {
  TerminalDataTransfers2["Terminals"] = "Terminals";
})(TerminalDataTransfers || (TerminalDataTransfers = {}));

// out-build/vs/workbench/contrib/terminalContrib/accessibility/common/terminal.accessibility.js
var TerminalAccessibilityCommandId;
(function(TerminalAccessibilityCommandId2) {
  TerminalAccessibilityCommandId2["FocusAccessibleBuffer"] = "workbench.action.terminal.focusAccessibleBuffer";
  TerminalAccessibilityCommandId2["AccessibleBufferGoToNextCommand"] = "workbench.action.terminal.accessibleBufferGoToNextCommand";
  TerminalAccessibilityCommandId2["AccessibleBufferGoToPreviousCommand"] = "workbench.action.terminal.accessibleBufferGoToPreviousCommand";
  TerminalAccessibilityCommandId2["ScrollToBottomAccessibleView"] = "workbench.action.terminal.scrollToBottomAccessibleView";
  TerminalAccessibilityCommandId2["ScrollToTopAccessibleView"] = "workbench.action.terminal.scrollToTopAccessibleView";
})(TerminalAccessibilityCommandId || (TerminalAccessibilityCommandId = {}));
var $OX = [
  "workbench.action.terminal.focusAccessibleBuffer"
  /* TerminalAccessibilityCommandId.FocusAccessibleBuffer */
];

// out-build/vs/workbench/contrib/terminalContrib/accessibility/common/terminalAccessibilityConfiguration.js
var TerminalAccessibilitySettingId;
(function(TerminalAccessibilitySettingId2) {
  TerminalAccessibilitySettingId2["AccessibleViewPreserveCursorPosition"] = "terminal.integrated.accessibleViewPreserveCursorPosition";
  TerminalAccessibilitySettingId2["AccessibleViewFocusOnCommandExecution"] = "terminal.integrated.accessibleViewFocusOnCommandExecution";
})(TerminalAccessibilitySettingId || (TerminalAccessibilitySettingId = {}));
var $PX = {
  [
    "terminal.integrated.accessibleViewPreserveCursorPosition"
    /* TerminalAccessibilitySettingId.AccessibleViewPreserveCursorPosition */
  ]: {
    markdownDescription: localize(10824, null),
    type: "boolean",
    default: false
  },
  [
    "terminal.integrated.accessibleViewFocusOnCommandExecution"
    /* TerminalAccessibilitySettingId.AccessibleViewFocusOnCommandExecution */
  ]: {
    markdownDescription: localize(10825, null),
    type: "boolean",
    default: false
  }
};

// out-build/vs/workbench/contrib/terminalContrib/autoReplies/common/terminalAutoRepliesConfiguration.js
var TerminalAutoRepliesSettingId;
(function(TerminalAutoRepliesSettingId2) {
  TerminalAutoRepliesSettingId2["AutoReplies"] = "terminal.integrated.autoReplies";
})(TerminalAutoRepliesSettingId || (TerminalAutoRepliesSettingId = {}));
var $QX = {
  [
    "terminal.integrated.autoReplies"
    /* TerminalAutoRepliesSettingId.AutoReplies */
  ]: {
    markdownDescription: localize(10826, null, '`"Terminate batch job (Y/N)": "Y\\r"`', '`"\\r"`'),
    type: "object",
    additionalProperties: {
      oneOf: [
        {
          type: "string",
          description: localize(10827, null)
        },
        { type: "null" }
      ]
    },
    default: {}
  }
};

// out-build/vs/workbench/contrib/terminalContrib/chat/common/terminalInitialHintConfiguration.js
var TerminalInitialHintSettingId;
(function(TerminalInitialHintSettingId2) {
  TerminalInitialHintSettingId2["Enabled"] = "terminal.integrated.initialHint";
})(TerminalInitialHintSettingId || (TerminalInitialHintSettingId = {}));
var $RX = {
  [
    "terminal.integrated.initialHint"
    /* TerminalInitialHintSettingId.Enabled */
  ]: {
    restricted: true,
    markdownDescription: localize(10869, null),
    type: "boolean",
    default: true
  }
};

// out-build/vs/workbench/contrib/terminalContrib/commandGuide/common/terminalCommandGuideConfiguration.js
var TerminalCommandGuideSettingId;
(function(TerminalCommandGuideSettingId2) {
  TerminalCommandGuideSettingId2["ShowCommandGuide"] = "terminal.integrated.shellIntegration.showCommandGuide";
})(TerminalCommandGuideSettingId || (TerminalCommandGuideSettingId = {}));
var $SX = "terminal.integrated.shellIntegration";
var $TX = {
  [
    "terminal.integrated.shellIntegration.showCommandGuide"
    /* TerminalCommandGuideSettingId.ShowCommandGuide */
  ]: {
    restricted: true,
    markdownDescription: localize(10884, null),
    type: "boolean",
    default: true
  }
};

// out-build/vs/workbench/contrib/terminalContrib/find/common/terminal.find.js
var TerminalFindCommandId;
(function(TerminalFindCommandId2) {
  TerminalFindCommandId2["FindFocus"] = "workbench.action.terminal.focusFind";
  TerminalFindCommandId2["FindHide"] = "workbench.action.terminal.hideFind";
  TerminalFindCommandId2["FindNext"] = "workbench.action.terminal.findNext";
  TerminalFindCommandId2["FindPrevious"] = "workbench.action.terminal.findPrevious";
  TerminalFindCommandId2["ToggleFindRegex"] = "workbench.action.terminal.toggleFindRegex";
  TerminalFindCommandId2["ToggleFindWholeWord"] = "workbench.action.terminal.toggleFindWholeWord";
  TerminalFindCommandId2["ToggleFindCaseSensitive"] = "workbench.action.terminal.toggleFindCaseSensitive";
  TerminalFindCommandId2["SearchWorkspace"] = "workbench.action.terminal.searchWorkspace";
})(TerminalFindCommandId || (TerminalFindCommandId = {}));
var $UX = [
  "workbench.action.terminal.focusFind",
  "workbench.action.terminal.hideFind",
  "workbench.action.terminal.findNext",
  "workbench.action.terminal.findPrevious",
  "workbench.action.terminal.toggleFindRegex",
  "workbench.action.terminal.toggleFindWholeWord",
  "workbench.action.terminal.toggleFindCaseSensitive",
  "workbench.action.terminal.searchWorkspace"
];

// out-build/vs/workbench/contrib/terminalContrib/history/common/terminal.history.js
var TerminalHistoryCommandId;
(function(TerminalHistoryCommandId2) {
  TerminalHistoryCommandId2["ClearPreviousSessionHistory"] = "workbench.action.terminal.clearPreviousSessionHistory";
  TerminalHistoryCommandId2["GoToRecentDirectory"] = "workbench.action.terminal.goToRecentDirectory";
  TerminalHistoryCommandId2["RunRecentCommand"] = "workbench.action.terminal.runRecentCommand";
})(TerminalHistoryCommandId || (TerminalHistoryCommandId = {}));
var $VX = [
  "workbench.action.terminal.goToRecentDirectory",
  "workbench.action.terminal.runRecentCommand"
  /* TerminalHistoryCommandId.RunRecentCommand */
];
var TerminalHistorySettingId;
(function(TerminalHistorySettingId2) {
  TerminalHistorySettingId2["ShellIntegrationCommandHistory"] = "terminal.integrated.shellIntegration.history";
})(TerminalHistorySettingId || (TerminalHistorySettingId = {}));
var $WX = {
  [
    "terminal.integrated.shellIntegration.history"
    /* TerminalHistorySettingId.ShellIntegrationCommandHistory */
  ]: {
    restricted: true,
    markdownDescription: localize(10921, null),
    type: "number",
    default: 100
  }
};

// out-build/vs/workbench/contrib/terminalContrib/stickyScroll/common/terminalStickyScrollConfiguration.js
var TerminalStickyScrollSettingId;
(function(TerminalStickyScrollSettingId2) {
  TerminalStickyScrollSettingId2["Enabled"] = "terminal.integrated.stickyScroll.enabled";
  TerminalStickyScrollSettingId2["MaxLineCount"] = "terminal.integrated.stickyScroll.maxLineCount";
})(TerminalStickyScrollSettingId || (TerminalStickyScrollSettingId = {}));
var $XX = {
  [
    "terminal.integrated.stickyScroll.enabled"
    /* TerminalStickyScrollSettingId.Enabled */
  ]: {
    markdownDescription: localize(10976, null),
    type: "boolean",
    default: product_default.quality !== "stable"
  },
  [
    "terminal.integrated.stickyScroll.maxLineCount"
    /* TerminalStickyScrollSettingId.MaxLineCount */
  ]: {
    markdownDescription: localize(10977, null),
    type: "number",
    default: 5,
    minimum: 1,
    maximum: 10
  }
};

// out-build/vs/workbench/contrib/terminalContrib/suggest/common/terminal.suggest.js
var TerminalSuggestCommandId;
(function(TerminalSuggestCommandId2) {
  TerminalSuggestCommandId2["SelectPrevSuggestion"] = "workbench.action.terminal.selectPrevSuggestion";
  TerminalSuggestCommandId2["SelectPrevPageSuggestion"] = "workbench.action.terminal.selectPrevPageSuggestion";
  TerminalSuggestCommandId2["SelectNextSuggestion"] = "workbench.action.terminal.selectNextSuggestion";
  TerminalSuggestCommandId2["SelectNextPageSuggestion"] = "workbench.action.terminal.selectNextPageSuggestion";
  TerminalSuggestCommandId2["AcceptSelectedSuggestion"] = "workbench.action.terminal.acceptSelectedSuggestion";
  TerminalSuggestCommandId2["AcceptSelectedSuggestionEnter"] = "workbench.action.terminal.acceptSelectedSuggestionEnter";
  TerminalSuggestCommandId2["HideSuggestWidget"] = "workbench.action.terminal.hideSuggestWidget";
  TerminalSuggestCommandId2["ClearSuggestCache"] = "workbench.action.terminal.clearSuggestCache";
  TerminalSuggestCommandId2["RequestCompletions"] = "workbench.action.terminal.requestCompletions";
})(TerminalSuggestCommandId || (TerminalSuggestCommandId = {}));
var $YX = [
  "workbench.action.terminal.selectPrevSuggestion",
  "workbench.action.terminal.selectPrevPageSuggestion",
  "workbench.action.terminal.selectNextSuggestion",
  "workbench.action.terminal.selectNextPageSuggestion",
  "workbench.action.terminal.acceptSelectedSuggestion",
  "workbench.action.terminal.acceptSelectedSuggestionEnter",
  "workbench.action.terminal.hideSuggestWidget",
  "workbench.action.terminal.clearSuggestCache",
  "workbench.action.terminal.requestCompletions"
];

// out-build/vs/workbench/contrib/terminalContrib/suggest/common/terminalSuggestConfiguration.js
var TerminalSuggestSettingId;
(function(TerminalSuggestSettingId2) {
  TerminalSuggestSettingId2["Enabled"] = "terminal.integrated.suggest.enabled";
  TerminalSuggestSettingId2["QuickSuggestions"] = "terminal.integrated.suggest.quickSuggestions";
  TerminalSuggestSettingId2["SuggestOnTriggerCharacters"] = "terminal.integrated.suggest.suggestOnTriggerCharacters";
  TerminalSuggestSettingId2["RunOnEnter"] = "terminal.integrated.suggest.runOnEnter";
  TerminalSuggestSettingId2["BuiltinCompletions"] = "terminal.integrated.suggest.builtinCompletions";
  TerminalSuggestSettingId2["EnableExtensionCompletions"] = "terminal.integrated.suggest.enableExtensionCompletions";
})(TerminalSuggestSettingId || (TerminalSuggestSettingId = {}));
var $ZX = "terminal.integrated.suggest";
var $1X = {
  [
    "terminal.integrated.suggest.enabled"
    /* TerminalSuggestSettingId.Enabled */
  ]: {
    restricted: true,
    markdownDescription: localize(10987, null, "PowerShell v7+, zsh, bash, fish", `\`#${"terminal.integrated.shellIntegration.enabled"}#\``, "`true`", "`VSCODE_SUGGEST`", "`1`", `\`#${"terminal.integrated.suggest.enableExtensionCompletions"}#\``),
    type: "boolean",
    default: false,
    tags: ["experimental"]
  },
  [
    "terminal.integrated.suggest.quickSuggestions"
    /* TerminalSuggestSettingId.QuickSuggestions */
  ]: {
    restricted: true,
    markdownDescription: localize(10988, null, `\`#${"terminal.integrated.suggest.suggestOnTriggerCharacters"}#\``),
    type: "boolean",
    default: true
  },
  [
    "terminal.integrated.suggest.suggestOnTriggerCharacters"
    /* TerminalSuggestSettingId.SuggestOnTriggerCharacters */
  ]: {
    restricted: true,
    markdownDescription: localize(10989, null),
    type: "boolean",
    default: true
  },
  [
    "terminal.integrated.suggest.runOnEnter"
    /* TerminalSuggestSettingId.RunOnEnter */
  ]: {
    restricted: true,
    markdownDescription: localize(10990, null),
    enum: ["ignore", "never", "exactMatch", "exactMatchIgnoreExtension", "always"],
    markdownEnumDescriptions: [
      localize(10991, null),
      localize(10992, null),
      localize(10993, null),
      localize(10994, null),
      localize(10995, null)
    ],
    default: "ignore"
  },
  [
    "terminal.integrated.suggest.builtinCompletions"
    /* TerminalSuggestSettingId.BuiltinCompletions */
  ]: {
    restricted: true,
    markdownDescription: localize(10996, null),
    type: "object",
    properties: {
      "pwshCode": {
        description: localize(10997, null),
        type: "boolean"
      },
      "pwshGit": {
        description: localize(10998, null),
        type: "boolean"
      }
    },
    default: {
      pwshCode: true,
      pwshGit: true
    }
  },
  [
    "terminal.integrated.suggest.enableExtensionCompletions"
    /* TerminalSuggestSettingId.EnableExtensionCompletions */
  ]: {
    restricted: true,
    markdownDescription: localize(10999, null),
    type: "boolean",
    default: false,
    tags: ["experimental"]
  }
};

// out-build/vs/workbench/contrib/terminalContrib/typeAhead/common/terminalTypeAheadConfiguration.js
var $2X = ["vim", "vi", "nano", "tmux"];
var TerminalTypeAheadSettingId;
(function(TerminalTypeAheadSettingId2) {
  TerminalTypeAheadSettingId2["LocalEchoLatencyThreshold"] = "terminal.integrated.localEchoLatencyThreshold";
  TerminalTypeAheadSettingId2["LocalEchoEnabled"] = "terminal.integrated.localEchoEnabled";
  TerminalTypeAheadSettingId2["LocalEchoExcludePrograms"] = "terminal.integrated.localEchoExcludePrograms";
  TerminalTypeAheadSettingId2["LocalEchoStyle"] = "terminal.integrated.localEchoStyle";
})(TerminalTypeAheadSettingId || (TerminalTypeAheadSettingId = {}));
var $3X = {
  [
    "terminal.integrated.localEchoLatencyThreshold"
    /* TerminalTypeAheadSettingId.LocalEchoLatencyThreshold */
  ]: {
    description: localize(11e3, null),
    type: "integer",
    minimum: -1,
    default: 30
  },
  [
    "terminal.integrated.localEchoEnabled"
    /* TerminalTypeAheadSettingId.LocalEchoEnabled */
  ]: {
    markdownDescription: localize(11001, null, "`#terminal.integrated.localEchoLatencyThreshold#`"),
    type: "string",
    enum: ["on", "off", "auto"],
    enumDescriptions: [
      localize(11002, null),
      localize(11003, null),
      localize(11004, null)
    ],
    default: "auto"
  },
  [
    "terminal.integrated.localEchoExcludePrograms"
    /* TerminalTypeAheadSettingId.LocalEchoExcludePrograms */
  ]: {
    description: localize(11005, null),
    type: "array",
    items: {
      type: "string",
      uniqueItems: true
    },
    default: $2X
  },
  [
    "terminal.integrated.localEchoStyle"
    /* TerminalTypeAheadSettingId.LocalEchoStyle */
  ]: {
    description: localize(11006, null),
    default: "dim",
    anyOf: [
      {
        enum: ["bold", "dim", "italic", "underlined", "inverted", "#ff0000"]
      },
      {
        type: "string",
        format: "color-hex"
      }
    ]
  }
};

// out-build/vs/workbench/contrib/terminalContrib/zoom/common/terminal.zoom.js
var TerminalZoomCommandId;
(function(TerminalZoomCommandId2) {
  TerminalZoomCommandId2["FontZoomIn"] = "workbench.action.terminal.fontZoomIn";
  TerminalZoomCommandId2["FontZoomOut"] = "workbench.action.terminal.fontZoomOut";
  TerminalZoomCommandId2["FontZoomReset"] = "workbench.action.terminal.fontZoomReset";
})(TerminalZoomCommandId || (TerminalZoomCommandId = {}));
var TerminalZoomSettingId;
(function(TerminalZoomSettingId2) {
  TerminalZoomSettingId2["MouseWheelZoom"] = "terminal.integrated.mouseWheelZoom";
})(TerminalZoomSettingId || (TerminalZoomSettingId = {}));
var $4X = {
  [
    "terminal.integrated.mouseWheelZoom"
    /* TerminalZoomSettingId.MouseWheelZoom */
  ]: {
    markdownDescription: $m ? localize(11012, null) : localize(11013, null),
    type: "boolean",
    default: false
  }
};

// out-build/vs/workbench/contrib/terminal/terminalContribExports.js
var TerminalContribCommandId;
(function(TerminalContribCommandId2) {
  TerminalContribCommandId2["A11yFocusAccessibleBuffer"] = "workbench.action.terminal.focusAccessibleBuffer";
  TerminalContribCommandId2["DeveloperRestartPtyHost"] = "workbench.action.terminal.restartPtyHost";
})(TerminalContribCommandId || (TerminalContribCommandId = {}));
var TerminalContribSettingId;
(function(TerminalContribSettingId2) {
  TerminalContribSettingId2["SuggestEnabled"] = "terminal.integrated.suggest.enabled";
  TerminalContribSettingId2["StickyScrollEnabled"] = "terminal.integrated.stickyScroll.enabled";
})(TerminalContribSettingId || (TerminalContribSettingId = {}));
var $5X = {
  ...$PX,
  ...$QX,
  ...$RX,
  ...$TX,
  ...$WX,
  ...$XX,
  ...$1X,
  ...$3X,
  ...$4X
};
var $6X = [
  ...$OX,
  ...$UX,
  ...$VX,
  ...$YX
];

// out-build/vs/workbench/contrib/terminal/common/terminal.js
var $7X = "terminal";
var $8X = ["workbench.action.terminal.toggleTerminal", "workbench.action.terminal.new", "workbench.action.togglePanel", "workbench.action.terminal.focus"];
var $9X = "terminal.integrated";
var $0X = 0;
var $$X = -5;
var $_X = $n ? 1.1 : 1;
var $aY = 1;
var $bY = 1e3;
var $cY = "normal";
var $dY = "bold";
var $eY = ["normal", "bold", "100", "200", "300", "400", "500", "600", "700", "800", "900"];
var $fY = $Qk("terminalProfileResolverService");
var $hY = $Qk("terminalProfileService");
var $iY = (t) => typeof t.write === "function";
var ProcessState;
(function(ProcessState2) {
  ProcessState2[ProcessState2["Uninitialized"] = 1] = "Uninitialized";
  ProcessState2[ProcessState2["Launching"] = 2] = "Launching";
  ProcessState2[ProcessState2["Running"] = 3] = "Running";
  ProcessState2[ProcessState2["KilledDuringLaunch"] = 4] = "KilledDuringLaunch";
  ProcessState2[ProcessState2["KilledByUser"] = 5] = "KilledByUser";
  ProcessState2[ProcessState2["KilledByProcess"] = 6] = "KilledByProcess";
})(ProcessState || (ProcessState = {}));
var TerminalCommandId;
(function(TerminalCommandId2) {
  TerminalCommandId2["Toggle"] = "workbench.action.terminal.toggleTerminal";
  TerminalCommandId2["Kill"] = "workbench.action.terminal.kill";
  TerminalCommandId2["KillViewOrEditor"] = "workbench.action.terminal.killViewOrEditor";
  TerminalCommandId2["KillEditor"] = "workbench.action.terminal.killEditor";
  TerminalCommandId2["KillActiveTab"] = "workbench.action.terminal.killActiveTab";
  TerminalCommandId2["KillAll"] = "workbench.action.terminal.killAll";
  TerminalCommandId2["QuickKill"] = "workbench.action.terminal.quickKill";
  TerminalCommandId2["ConfigureTerminalSettings"] = "workbench.action.terminal.openSettings";
  TerminalCommandId2["ShellIntegrationLearnMore"] = "workbench.action.terminal.learnMore";
  TerminalCommandId2["CopyLastCommand"] = "workbench.action.terminal.copyLastCommand";
  TerminalCommandId2["CopyLastCommandOutput"] = "workbench.action.terminal.copyLastCommandOutput";
  TerminalCommandId2["CopyLastCommandAndLastCommandOutput"] = "workbench.action.terminal.copyLastCommandAndLastCommandOutput";
  TerminalCommandId2["CopyAndClearSelection"] = "workbench.action.terminal.copyAndClearSelection";
  TerminalCommandId2["CopySelection"] = "workbench.action.terminal.copySelection";
  TerminalCommandId2["CopySelectionAsHtml"] = "workbench.action.terminal.copySelectionAsHtml";
  TerminalCommandId2["SelectAll"] = "workbench.action.terminal.selectAll";
  TerminalCommandId2["DeleteWordLeft"] = "workbench.action.terminal.deleteWordLeft";
  TerminalCommandId2["DeleteWordRight"] = "workbench.action.terminal.deleteWordRight";
  TerminalCommandId2["DeleteToLineStart"] = "workbench.action.terminal.deleteToLineStart";
  TerminalCommandId2["MoveToLineStart"] = "workbench.action.terminal.moveToLineStart";
  TerminalCommandId2["MoveToLineEnd"] = "workbench.action.terminal.moveToLineEnd";
  TerminalCommandId2["New"] = "workbench.action.terminal.new";
  TerminalCommandId2["NewWithCwd"] = "workbench.action.terminal.newWithCwd";
  TerminalCommandId2["NewLocal"] = "workbench.action.terminal.newLocal";
  TerminalCommandId2["NewInActiveWorkspace"] = "workbench.action.terminal.newInActiveWorkspace";
  TerminalCommandId2["NewWithProfile"] = "workbench.action.terminal.newWithProfile";
  TerminalCommandId2["Split"] = "workbench.action.terminal.split";
  TerminalCommandId2["SplitActiveTab"] = "workbench.action.terminal.splitActiveTab";
  TerminalCommandId2["SplitInActiveWorkspace"] = "workbench.action.terminal.splitInActiveWorkspace";
  TerminalCommandId2["Unsplit"] = "workbench.action.terminal.unsplit";
  TerminalCommandId2["JoinActiveTab"] = "workbench.action.terminal.joinActiveTab";
  TerminalCommandId2["Join"] = "workbench.action.terminal.join";
  TerminalCommandId2["Relaunch"] = "workbench.action.terminal.relaunch";
  TerminalCommandId2["FocusPreviousPane"] = "workbench.action.terminal.focusPreviousPane";
  TerminalCommandId2["CreateTerminalEditor"] = "workbench.action.createTerminalEditor";
  TerminalCommandId2["CreateTerminalEditorSameGroup"] = "workbench.action.createTerminalEditorSameGroup";
  TerminalCommandId2["CreateTerminalEditorSide"] = "workbench.action.createTerminalEditorSide";
  TerminalCommandId2["FocusTabs"] = "workbench.action.terminal.focusTabs";
  TerminalCommandId2["FocusNextPane"] = "workbench.action.terminal.focusNextPane";
  TerminalCommandId2["ResizePaneLeft"] = "workbench.action.terminal.resizePaneLeft";
  TerminalCommandId2["ResizePaneRight"] = "workbench.action.terminal.resizePaneRight";
  TerminalCommandId2["ResizePaneUp"] = "workbench.action.terminal.resizePaneUp";
  TerminalCommandId2["SizeToContentWidth"] = "workbench.action.terminal.sizeToContentWidth";
  TerminalCommandId2["SizeToContentWidthActiveTab"] = "workbench.action.terminal.sizeToContentWidthActiveTab";
  TerminalCommandId2["ResizePaneDown"] = "workbench.action.terminal.resizePaneDown";
  TerminalCommandId2["Focus"] = "workbench.action.terminal.focus";
  TerminalCommandId2["FocusNext"] = "workbench.action.terminal.focusNext";
  TerminalCommandId2["FocusPrevious"] = "workbench.action.terminal.focusPrevious";
  TerminalCommandId2["Paste"] = "workbench.action.terminal.paste";
  TerminalCommandId2["PasteSelection"] = "workbench.action.terminal.pasteSelection";
  TerminalCommandId2["SelectDefaultProfile"] = "workbench.action.terminal.selectDefaultShell";
  TerminalCommandId2["RunSelectedText"] = "workbench.action.terminal.runSelectedText";
  TerminalCommandId2["RunActiveFile"] = "workbench.action.terminal.runActiveFile";
  TerminalCommandId2["SwitchTerminal"] = "workbench.action.terminal.switchTerminal";
  TerminalCommandId2["ScrollDownLine"] = "workbench.action.terminal.scrollDown";
  TerminalCommandId2["ScrollDownPage"] = "workbench.action.terminal.scrollDownPage";
  TerminalCommandId2["ScrollToBottom"] = "workbench.action.terminal.scrollToBottom";
  TerminalCommandId2["ScrollUpLine"] = "workbench.action.terminal.scrollUp";
  TerminalCommandId2["ScrollUpPage"] = "workbench.action.terminal.scrollUpPage";
  TerminalCommandId2["ScrollToTop"] = "workbench.action.terminal.scrollToTop";
  TerminalCommandId2["Clear"] = "workbench.action.terminal.clear";
  TerminalCommandId2["ClearSelection"] = "workbench.action.terminal.clearSelection";
  TerminalCommandId2["ChangeIcon"] = "workbench.action.terminal.changeIcon";
  TerminalCommandId2["ChangeIconActiveTab"] = "workbench.action.terminal.changeIconActiveTab";
  TerminalCommandId2["ChangeColor"] = "workbench.action.terminal.changeColor";
  TerminalCommandId2["ChangeColorActiveTab"] = "workbench.action.terminal.changeColorActiveTab";
  TerminalCommandId2["Rename"] = "workbench.action.terminal.rename";
  TerminalCommandId2["RenameActiveTab"] = "workbench.action.terminal.renameActiveTab";
  TerminalCommandId2["RenameWithArgs"] = "workbench.action.terminal.renameWithArg";
  TerminalCommandId2["ScrollToPreviousCommand"] = "workbench.action.terminal.scrollToPreviousCommand";
  TerminalCommandId2["ScrollToNextCommand"] = "workbench.action.terminal.scrollToNextCommand";
  TerminalCommandId2["SelectToPreviousCommand"] = "workbench.action.terminal.selectToPreviousCommand";
  TerminalCommandId2["SelectToNextCommand"] = "workbench.action.terminal.selectToNextCommand";
  TerminalCommandId2["SelectToPreviousLine"] = "workbench.action.terminal.selectToPreviousLine";
  TerminalCommandId2["SelectToNextLine"] = "workbench.action.terminal.selectToNextLine";
  TerminalCommandId2["SendSequence"] = "workbench.action.terminal.sendSequence";
  TerminalCommandId2["AttachToSession"] = "workbench.action.terminal.attachToSession";
  TerminalCommandId2["DetachSession"] = "workbench.action.terminal.detachSession";
  TerminalCommandId2["MoveToEditor"] = "workbench.action.terminal.moveToEditor";
  TerminalCommandId2["MoveToTerminalPanel"] = "workbench.action.terminal.moveToTerminalPanel";
  TerminalCommandId2["MoveIntoNewWindow"] = "workbench.action.terminal.moveIntoNewWindow";
  TerminalCommandId2["SetDimensions"] = "workbench.action.terminal.setDimensions";
  TerminalCommandId2["FocusHover"] = "workbench.action.terminal.focusHover";
  TerminalCommandId2["ShowEnvironmentContributions"] = "workbench.action.terminal.showEnvironmentContributions";
  TerminalCommandId2["StartVoice"] = "workbench.action.terminal.startVoice";
  TerminalCommandId2["StopVoice"] = "workbench.action.terminal.stopVoice";
})(TerminalCommandId || (TerminalCommandId = {}));
var $kY = [
  "workbench.action.terminal.clearSelection",
  "workbench.action.terminal.clear",
  "workbench.action.terminal.copyAndClearSelection",
  "workbench.action.terminal.copySelection",
  "workbench.action.terminal.copySelectionAsHtml",
  "workbench.action.terminal.copyLastCommand",
  "workbench.action.terminal.copyLastCommandOutput",
  "workbench.action.terminal.copyLastCommandAndLastCommandOutput",
  "workbench.action.terminal.deleteToLineStart",
  "workbench.action.terminal.deleteWordLeft",
  "workbench.action.terminal.deleteWordRight",
  "workbench.action.terminal.focusNextPane",
  "workbench.action.terminal.focusNext",
  "workbench.action.terminal.focusPreviousPane",
  "workbench.action.terminal.focusPrevious",
  "workbench.action.terminal.focus",
  "workbench.action.terminal.sizeToContentWidth",
  "workbench.action.terminal.kill",
  "workbench.action.terminal.killEditor",
  "workbench.action.terminal.moveToEditor",
  "workbench.action.terminal.moveToLineEnd",
  "workbench.action.terminal.moveToLineStart",
  "workbench.action.terminal.moveToTerminalPanel",
  "workbench.action.terminal.newInActiveWorkspace",
  "workbench.action.terminal.new",
  "workbench.action.terminal.paste",
  "workbench.action.terminal.pasteSelection",
  "workbench.action.terminal.resizePaneDown",
  "workbench.action.terminal.resizePaneLeft",
  "workbench.action.terminal.resizePaneRight",
  "workbench.action.terminal.resizePaneUp",
  "workbench.action.terminal.runActiveFile",
  "workbench.action.terminal.runSelectedText",
  "workbench.action.terminal.scrollDown",
  "workbench.action.terminal.scrollDownPage",
  "workbench.action.terminal.scrollToBottom",
  "workbench.action.terminal.scrollToNextCommand",
  "workbench.action.terminal.scrollToPreviousCommand",
  "workbench.action.terminal.scrollToTop",
  "workbench.action.terminal.scrollUp",
  "workbench.action.terminal.scrollUpPage",
  "workbench.action.terminal.sendSequence",
  "workbench.action.terminal.selectAll",
  "workbench.action.terminal.selectToNextCommand",
  "workbench.action.terminal.selectToNextLine",
  "workbench.action.terminal.selectToPreviousCommand",
  "workbench.action.terminal.selectToPreviousLine",
  "workbench.action.terminal.splitInActiveWorkspace",
  "workbench.action.terminal.split",
  "workbench.action.terminal.toggleTerminal",
  "workbench.action.terminal.focusHover",
  "editor.action.accessibilityHelp",
  "editor.action.toggleTabFocusMode",
  "notifications.hideList",
  "notifications.hideToasts",
  "workbench.action.closeQuickOpen",
  "workbench.action.quickOpen",
  "workbench.action.quickOpenPreviousEditor",
  "workbench.action.showCommands",
  "workbench.action.tasks.build",
  "workbench.action.tasks.restartTask",
  "workbench.action.tasks.runTask",
  "workbench.action.tasks.reRunTask",
  "workbench.action.tasks.showLog",
  "workbench.action.tasks.showTasks",
  "workbench.action.tasks.terminate",
  "workbench.action.tasks.test",
  "workbench.action.toggleFullScreen",
  "workbench.action.terminal.focusAtIndex1",
  "workbench.action.terminal.focusAtIndex2",
  "workbench.action.terminal.focusAtIndex3",
  "workbench.action.terminal.focusAtIndex4",
  "workbench.action.terminal.focusAtIndex5",
  "workbench.action.terminal.focusAtIndex6",
  "workbench.action.terminal.focusAtIndex7",
  "workbench.action.terminal.focusAtIndex8",
  "workbench.action.terminal.focusAtIndex9",
  "workbench.action.focusSecondEditorGroup",
  "workbench.action.focusThirdEditorGroup",
  "workbench.action.focusFourthEditorGroup",
  "workbench.action.focusFifthEditorGroup",
  "workbench.action.focusSixthEditorGroup",
  "workbench.action.focusSeventhEditorGroup",
  "workbench.action.focusEighthEditorGroup",
  "workbench.action.focusNextPart",
  "workbench.action.focusPreviousPart",
  "workbench.action.nextPanelView",
  "workbench.action.previousPanelView",
  "workbench.action.nextSideBarView",
  "workbench.action.previousSideBarView",
  "workbench.action.debug.start",
  "workbench.action.debug.stop",
  "workbench.action.debug.run",
  "workbench.action.debug.restart",
  "workbench.action.debug.continue",
  "workbench.action.debug.pause",
  "workbench.action.debug.stepInto",
  "workbench.action.debug.stepOut",
  "workbench.action.debug.stepOver",
  "workbench.action.nextEditor",
  "workbench.action.previousEditor",
  "workbench.action.nextEditorInGroup",
  "workbench.action.previousEditorInGroup",
  "workbench.action.openNextRecentlyUsedEditor",
  "workbench.action.openPreviousRecentlyUsedEditor",
  "workbench.action.openNextRecentlyUsedEditorInGroup",
  "workbench.action.openPreviousRecentlyUsedEditorInGroup",
  "workbench.action.quickOpenPreviousRecentlyUsedEditor",
  "workbench.action.quickOpenLeastRecentlyUsedEditor",
  "workbench.action.quickOpenPreviousRecentlyUsedEditorInGroup",
  "workbench.action.quickOpenLeastRecentlyUsedEditorInGroup",
  "workbench.action.focusActiveEditorGroup",
  "workbench.action.focusFirstEditorGroup",
  "workbench.action.focusLastEditorGroup",
  "workbench.action.firstEditorInGroup",
  "workbench.action.lastEditorInGroup",
  "workbench.action.navigateUp",
  "workbench.action.navigateDown",
  "workbench.action.navigateRight",
  "workbench.action.navigateLeft",
  "workbench.action.togglePanel",
  "workbench.action.quickOpenView",
  "workbench.action.toggleMaximizedPanel",
  "notification.acceptPrimaryAction",
  "runCommands",
  "workbench.action.terminal.chat.start",
  "workbench.action.terminal.chat.close",
  "workbench.action.terminal.chat.discard",
  "workbench.action.terminal.chat.makeRequest",
  "workbench.action.terminal.chat.cancel",
  "workbench.action.terminal.chat.feedbackHelpful",
  "workbench.action.terminal.chat.feedbackUnhelpful",
  "workbench.action.terminal.chat.feedbackReportIssue",
  "workbench.action.terminal.chat.runCommand",
  "workbench.action.terminal.chat.insertCommand",
  "workbench.action.terminal.chat.viewInChat",
  ...$6X
];
var $lY = {
  extensionPoint: "terminal",
  defaultExtensionKind: ["workspace"],
  activationEventsGenerator: (contribs, result) => {
    for (const contrib of contribs) {
      for (const profileContrib of contrib.profiles ?? []) {
        result.push(`onTerminalProfile:${profileContrib.id}`);
      }
    }
  },
  jsonSchema: {
    description: localize(10576, null),
    type: "object",
    properties: {
      profiles: {
        type: "array",
        description: localize(10577, null),
        items: {
          type: "object",
          required: ["id", "title"],
          defaultSnippets: [{
            body: {
              id: "$1",
              title: "$2"
            }
          }],
          properties: {
            id: {
              description: localize(10578, null),
              type: "string"
            },
            title: {
              description: localize(10579, null),
              type: "string"
            },
            icon: {
              description: localize(10580, null),
              anyOf: [
                {
                  type: "string"
                },
                {
                  type: "object",
                  properties: {
                    light: {
                      description: localize(10581, null),
                      type: "string"
                    },
                    dark: {
                      description: localize(10582, null),
                      type: "string"
                    }
                  }
                }
              ]
            }
          }
        }
      }
    }
  }
};

// out-build/vs/workbench/contrib/terminal/common/terminalColorRegistry.js
var $0Ob = [];
var $$Ob = $5n("terminal.background", null, localize(10583, null));
var $_Ob = $5n("terminal.foreground", {
  light: "#333333",
  dark: "#CCCCCC",
  hcDark: "#FFFFFF",
  hcLight: "#292929"
}, localize(10584, null));
var $aPb = $5n("terminalCursor.foreground", null, localize(10585, null));
var $bPb = $5n("terminalCursor.background", null, localize(10586, null));
var $cPb = $5n("terminal.selectionBackground", $7o, localize(10587, null));
var $dPb = $5n("terminal.inactiveSelectionBackground", {
  light: $0n($cPb, 0.5),
  dark: $0n($cPb, 0.5),
  hcDark: $0n($cPb, 0.7),
  hcLight: $0n($cPb, 0.5)
}, localize(10588, null));
var $ePb = $5n("terminal.selectionForeground", {
  light: null,
  dark: null,
  hcDark: "#000000",
  hcLight: "#ffffff"
}, localize(10589, null));
var $fPb = $5n("terminalCommandDecoration.defaultBackground", {
  light: "#00000040",
  dark: "#ffffff40",
  hcDark: "#ffffff80",
  hcLight: "#00000040"
}, localize(10590, null));
var $gPb = $5n("terminalCommandDecoration.successBackground", {
  dark: "#1B81A8",
  light: "#2090D3",
  hcDark: "#1B81A8",
  hcLight: "#007100"
}, localize(10591, null));
var $hPb = $5n("terminalCommandDecoration.errorBackground", {
  dark: "#F14C4C",
  light: "#E51400",
  hcDark: "#F14C4C",
  hcLight: "#B5200D"
}, localize(10592, null));
var $iPb = $5n("terminalOverviewRuler.cursorForeground", "#A0A0A0CC", localize(10593, null));
var $jPb = $5n("terminal.border", $Jmb, localize(10594, null));
var $kPb = $5n("terminalOverviewRuler.border", $hH, localize(10595, null));
var $lPb = $5n("terminal.findMatchBackground", {
  dark: $ap,
  light: $ap,
  // Use regular selection background in high contrast with a thick border
  hcDark: null,
  hcLight: "#0F4A85"
}, localize(10596, null), true);
var $mPb = $5n("terminal.hoverHighlightBackground", $0n($ip, 0.5), localize(10597, null));
var $nPb = $5n("terminal.findMatchBorder", {
  dark: null,
  light: null,
  hcDark: "#f38518",
  hcLight: "#0F4A85"
}, localize(10598, null));
var $oPb = $5n("terminal.findMatchHighlightBackground", {
  dark: $cp,
  light: $cp,
  hcDark: null,
  hcLight: null
}, localize(10599, null), true);
var $pPb = $5n("terminal.findMatchHighlightBorder", {
  dark: null,
  light: null,
  hcDark: "#f38518",
  hcLight: "#0F4A85"
}, localize(10600, null));
var $qPb = $5n("terminalOverviewRuler.findMatchForeground", {
  dark: $_p,
  light: $_p,
  hcDark: "#f38518",
  hcLight: "#0F4A85"
}, localize(10601, null));
var $rPb = $5n("terminal.dropBackground", $Cmb, localize(10602, null), true);
var $sPb = $5n("terminal.tab.activeBorder", $gmb, localize(10603, null));
var $tPb = $5n("terminal.initialHintForeground", {
  dark: "#ffffff56",
  light: "#0007",
  hcDark: null,
  hcLight: null
}, localize(10604, null));
var $uPb = {
  "terminal.ansiBlack": {
    index: 0,
    defaults: {
      light: "#000000",
      dark: "#000000",
      hcDark: "#000000",
      hcLight: "#292929"
    }
  },
  "terminal.ansiRed": {
    index: 1,
    defaults: {
      light: "#cd3131",
      dark: "#cd3131",
      hcDark: "#cd0000",
      hcLight: "#cd3131"
    }
  },
  "terminal.ansiGreen": {
    index: 2,
    defaults: {
      light: "#107C10",
      dark: "#0DBC79",
      hcDark: "#00cd00",
      hcLight: "#136C13"
    }
  },
  "terminal.ansiYellow": {
    index: 3,
    defaults: {
      light: "#949800",
      dark: "#e5e510",
      hcDark: "#cdcd00",
      hcLight: "#949800"
    }
  },
  "terminal.ansiBlue": {
    index: 4,
    defaults: {
      light: "#0451a5",
      dark: "#2472c8",
      hcDark: "#0000ee",
      hcLight: "#0451a5"
    }
  },
  "terminal.ansiMagenta": {
    index: 5,
    defaults: {
      light: "#bc05bc",
      dark: "#bc3fbc",
      hcDark: "#cd00cd",
      hcLight: "#bc05bc"
    }
  },
  "terminal.ansiCyan": {
    index: 6,
    defaults: {
      light: "#0598bc",
      dark: "#11a8cd",
      hcDark: "#00cdcd",
      hcLight: "#0598bc"
    }
  },
  "terminal.ansiWhite": {
    index: 7,
    defaults: {
      light: "#555555",
      dark: "#e5e5e5",
      hcDark: "#e5e5e5",
      hcLight: "#555555"
    }
  },
  "terminal.ansiBrightBlack": {
    index: 8,
    defaults: {
      light: "#666666",
      dark: "#666666",
      hcDark: "#7f7f7f",
      hcLight: "#666666"
    }
  },
  "terminal.ansiBrightRed": {
    index: 9,
    defaults: {
      light: "#cd3131",
      dark: "#f14c4c",
      hcDark: "#ff0000",
      hcLight: "#cd3131"
    }
  },
  "terminal.ansiBrightGreen": {
    index: 10,
    defaults: {
      light: "#14CE14",
      dark: "#23d18b",
      hcDark: "#00ff00",
      hcLight: "#00bc00"
    }
  },
  "terminal.ansiBrightYellow": {
    index: 11,
    defaults: {
      light: "#b5ba00",
      dark: "#f5f543",
      hcDark: "#ffff00",
      hcLight: "#b5ba00"
    }
  },
  "terminal.ansiBrightBlue": {
    index: 12,
    defaults: {
      light: "#0451a5",
      dark: "#3b8eea",
      hcDark: "#5c5cff",
      hcLight: "#0451a5"
    }
  },
  "terminal.ansiBrightMagenta": {
    index: 13,
    defaults: {
      light: "#bc05bc",
      dark: "#d670d6",
      hcDark: "#ff00ff",
      hcLight: "#bc05bc"
    }
  },
  "terminal.ansiBrightCyan": {
    index: 14,
    defaults: {
      light: "#0598bc",
      dark: "#29b8db",
      hcDark: "#00ffff",
      hcLight: "#0598bc"
    }
  },
  "terminal.ansiBrightWhite": {
    index: 15,
    defaults: {
      light: "#a5a5a5",
      dark: "#e5e5e5",
      hcDark: "#ffffff",
      hcLight: "#a5a5a5"
    }
  }
};
function $vPb() {
  for (const id2 in $uPb) {
    const entry = $uPb[id2];
    const colorName = id2.substring(13);
    $0Ob[entry.index] = $5n(id2, entry.defaults, localize(10605, null, colorName));
  }
}

// out-build/vs/workbench/contrib/terminal/browser/terminalIcon.js
function $_Pb(terminalOrColorKey) {
  let color2 = void 0;
  if (typeof terminalOrColorKey === "string") {
    color2 = terminalOrColorKey;
  } else if (terminalOrColorKey.color) {
    color2 = terminalOrColorKey.color.replace(/\./g, "_");
  } else if (ThemeIcon.isThemeIcon(terminalOrColorKey.icon) && terminalOrColorKey.icon.color) {
    color2 = terminalOrColorKey.icon.color.id.replace(/\./g, "_");
  }
  if (color2) {
    return `terminal-icon-${color2.replace(/\./g, "_")}`;
  }
  return void 0;
}
function $aQb(colorTheme) {
  const standardColors = [];
  for (const colorKey in $uPb) {
    const color2 = colorTheme.getColor(colorKey);
    if (color2 && !colorKey.toLowerCase().includes("bright")) {
      standardColors.push(colorKey);
    }
  }
  return standardColors;
}
function $bQb(colorTheme) {
  const disposable = new $2c();
  const standardColors = $aQb(colorTheme);
  const styleElement = $VZ(void 0, void 0, disposable);
  let css = "";
  for (const colorKey of standardColors) {
    const colorClass = $_Pb(colorKey);
    const color2 = colorTheme.getColor(colorKey);
    if (color2) {
      css += `.monaco-workbench .${colorClass} .codicon:first-child:not(.codicon-split-horizontal):not(.codicon-trashcan):not(.file-icon){ color: ${color2} !important; }`;
    }
  }
  styleElement.textContent = css;
  return disposable;
}
function $cQb(colorTheme, editor) {
  const standardColors = $aQb(colorTheme);
  let css = "";
  for (const colorKey of standardColors) {
    const colorClass = $_Pb(colorKey);
    const color2 = colorTheme.getColor(colorKey);
    if (color2) {
      if (editor) {
        css += `.monaco-workbench .show-file-icons .predefined-file-icon.terminal-tab.${colorClass}::before,.monaco-workbench .show-file-icons .file-icon.terminal-tab.${colorClass}::before{ color: ${color2} !important; }`;
      } else {
        css += `.monaco-workbench .${colorClass} .codicon:first-child:not(.codicon-split-horizontal):not(.codicon-trashcan):not(.file-icon){ color: ${color2} !important; }`;
      }
    }
  }
  return css;
}
function $dQb(terminal2, colorScheme, extensionContributed) {
  const icon2 = terminal2.icon;
  if (!icon2) {
    return void 0;
  }
  const iconClasses = [];
  let uri = void 0;
  if (extensionContributed) {
    if (typeof icon2 === "string" && (icon2.startsWith("$(") || $0r().getIcon(icon2))) {
      return iconClasses;
    } else if (typeof icon2 === "string") {
      uri = URI.parse(icon2);
    }
  }
  if (icon2 instanceof URI) {
    uri = icon2;
  } else if (icon2 instanceof Object && "light" in icon2 && "dark" in icon2) {
    uri = colorScheme === ColorScheme.LIGHT ? icon2.light : icon2.dark;
  }
  if (uri instanceof URI) {
    const uriIconKey = $Xi(uri.path).toString(36);
    const className = `terminal-uri-icon-${uriIconKey}`;
    iconClasses.push(className);
    iconClasses.push(`terminal-uri-icon`);
  }
  return iconClasses;
}
function $eQb(accessor, terminal2) {
  if (!terminal2.icon || terminal2.icon instanceof Object && !("id" in terminal2.icon)) {
    return accessor.get($fY).getDefaultIcon().id;
  }
  return typeof terminal2.icon === "string" ? terminal2.icon : terminal2.icon.id;
}

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

// out-build/vs/workbench/contrib/terminal/common/terminalContextKey.js
var TerminalContextKeyStrings;
(function(TerminalContextKeyStrings2) {
  TerminalContextKeyStrings2["IsOpen"] = "terminalIsOpen";
  TerminalContextKeyStrings2["Count"] = "terminalCount";
  TerminalContextKeyStrings2["GroupCount"] = "terminalGroupCount";
  TerminalContextKeyStrings2["TabsNarrow"] = "isTerminalTabsNarrow";
  TerminalContextKeyStrings2["HasFixedWidth"] = "terminalHasFixedWidth";
  TerminalContextKeyStrings2["ProcessSupported"] = "terminalProcessSupported";
  TerminalContextKeyStrings2["Focus"] = "terminalFocus";
  TerminalContextKeyStrings2["FocusInAny"] = "terminalFocusInAny";
  TerminalContextKeyStrings2["AccessibleBufferFocus"] = "terminalAccessibleBufferFocus";
  TerminalContextKeyStrings2["AccessibleBufferOnLastLine"] = "terminalAccessibleBufferOnLastLine";
  TerminalContextKeyStrings2["EditorFocus"] = "terminalEditorFocus";
  TerminalContextKeyStrings2["TabsFocus"] = "terminalTabsFocus";
  TerminalContextKeyStrings2["WebExtensionContributedProfile"] = "terminalWebExtensionContributedProfile";
  TerminalContextKeyStrings2["TerminalHasBeenCreated"] = "terminalHasBeenCreated";
  TerminalContextKeyStrings2["TerminalEditorActive"] = "terminalEditorActive";
  TerminalContextKeyStrings2["TabsMouse"] = "terminalTabsMouse";
  TerminalContextKeyStrings2["AltBufferActive"] = "terminalAltBufferActive";
  TerminalContextKeyStrings2["SuggestWidgetVisible"] = "terminalSuggestWidgetVisible";
  TerminalContextKeyStrings2["A11yTreeFocus"] = "terminalA11yTreeFocus";
  TerminalContextKeyStrings2["ViewShowing"] = "terminalViewShowing";
  TerminalContextKeyStrings2["TextSelected"] = "terminalTextSelected";
  TerminalContextKeyStrings2["TextSelectedInFocused"] = "terminalTextSelectedInFocused";
  TerminalContextKeyStrings2["FindVisible"] = "terminalFindVisible";
  TerminalContextKeyStrings2["FindInputFocused"] = "terminalFindInputFocused";
  TerminalContextKeyStrings2["FindFocused"] = "terminalFindFocused";
  TerminalContextKeyStrings2["TabsSingularSelection"] = "terminalTabsSingularSelection";
  TerminalContextKeyStrings2["SplitTerminal"] = "terminalSplitTerminal";
  TerminalContextKeyStrings2["ShellType"] = "terminalShellType";
  TerminalContextKeyStrings2["InTerminalRunCommandPicker"] = "inTerminalRunCommandPicker";
  TerminalContextKeyStrings2["TerminalShellIntegrationEnabled"] = "terminalShellIntegrationEnabled";
})(TerminalContextKeyStrings || (TerminalContextKeyStrings = {}));
var TerminalContextKeys;
(function(TerminalContextKeys2) {
  TerminalContextKeys2.isOpen = new $nn("terminalIsOpen", false, true);
  TerminalContextKeys2.focus = new $nn("terminalFocus", false, localize(10760, null));
  TerminalContextKeys2.focusInAny = new $nn("terminalFocusInAny", false, localize(10761, null));
  TerminalContextKeys2.editorFocus = new $nn("terminalEditorFocus", false, localize(10762, null));
  TerminalContextKeys2.count = new $nn("terminalCount", 0, localize(10763, null));
  TerminalContextKeys2.groupCount = new $nn("terminalGroupCount", 0, true);
  TerminalContextKeys2.tabsNarrow = new $nn("isTerminalTabsNarrow", false, true);
  TerminalContextKeys2.terminalHasFixedWidth = new $nn("terminalHasFixedWidth", false, true);
  TerminalContextKeys2.tabsFocus = new $nn("terminalTabsFocus", false, localize(10764, null));
  TerminalContextKeys2.webExtensionContributedProfile = new $nn("terminalWebExtensionContributedProfile", false, true);
  TerminalContextKeys2.terminalHasBeenCreated = new $nn("terminalHasBeenCreated", false, true);
  TerminalContextKeys2.terminalEditorActive = new $nn("terminalEditorActive", false, true);
  TerminalContextKeys2.tabsMouse = new $nn("terminalTabsMouse", false, true);
  TerminalContextKeys2.shellType = new $nn("terminalShellType", void 0, { type: "string", description: localize(10765, null) });
  TerminalContextKeys2.altBufferActive = new $nn("terminalAltBufferActive", false, localize(10766, null));
  TerminalContextKeys2.suggestWidgetVisible = new $nn("terminalSuggestWidgetVisible", false, localize(10767, null));
  TerminalContextKeys2.notFocus = TerminalContextKeys2.focus.toNegated();
  TerminalContextKeys2.viewShowing = new $nn("terminalViewShowing", false, localize(10768, null));
  TerminalContextKeys2.textSelected = new $nn("terminalTextSelected", false, localize(10769, null));
  TerminalContextKeys2.textSelectedInFocused = new $nn("terminalTextSelectedInFocused", false, localize(10770, null));
  TerminalContextKeys2.notTextSelected = TerminalContextKeys2.textSelected.toNegated();
  TerminalContextKeys2.findVisible = new $nn("terminalFindVisible", false, true);
  TerminalContextKeys2.notFindVisible = TerminalContextKeys2.findVisible.toNegated();
  TerminalContextKeys2.findInputFocus = new $nn("terminalFindInputFocused", false, true);
  TerminalContextKeys2.findFocus = new $nn("terminalFindFocused", false, true);
  TerminalContextKeys2.notFindFocus = TerminalContextKeys2.findInputFocus.toNegated();
  TerminalContextKeys2.processSupported = new $nn("terminalProcessSupported", false, localize(10771, null));
  TerminalContextKeys2.tabsSingularSelection = new $nn("terminalTabsSingularSelection", false, localize(10772, null));
  TerminalContextKeys2.splitTerminal = new $nn("terminalSplitTerminal", false, localize(10773, null));
  TerminalContextKeys2.inTerminalRunCommandPicker = new $nn("inTerminalRunCommandPicker", false, localize(10774, null));
  TerminalContextKeys2.terminalShellIntegrationEnabled = new $nn("terminalShellIntegrationEnabled", false, localize(10775, null));
  TerminalContextKeys2.shouldShowViewInlineActions = $7m.and($7m.equals("view", $7X), $7m.notEquals(`config.${"terminal.integrated.tabs.hideCondition"}`, "never"), $7m.or($7m.not(`config.${"terminal.integrated.tabs.enabled"}`), $7m.and($7m.equals(`config.${"terminal.integrated.tabs.showActions"}`, "singleTerminal"), $7m.equals("terminalGroupCount", 1)), $7m.and($7m.equals(`config.${"terminal.integrated.tabs.showActions"}`, "singleTerminalOrNarrow"), $7m.or($7m.equals("terminalGroupCount", 1), $7m.has(
    "isTerminalTabsNarrow"
    /* TerminalContextKeyStrings.TabsNarrow */
  ))), $7m.and($7m.equals(`config.${"terminal.integrated.tabs.showActions"}`, "singleGroup"), $7m.equals("terminalGroupCount", 1)), $7m.equals(`config.${"terminal.integrated.tabs.showActions"}`, "always")));
})(TerminalContextKeys || (TerminalContextKeys = {}));

// out-build/vs/workbench/contrib/terminal/browser/terminalEditorInput.js
var $fQb_1;
var $fQb = class $fQb2 extends $nG {
  static {
    $fQb_1 = this;
  }
  static {
    this.ID = "workbench.editors.terminal";
  }
  setGroup(group2) {
    this.r = group2;
    if (group2?.scopedContextKeyService) {
      this.t?.setParentContextKeyService(group2.scopedContextKeyService);
    }
  }
  get group() {
    return this.r;
  }
  get typeId() {
    return $fQb_1.ID;
  }
  get editorId() {
    return $$Pb;
  }
  get capabilities() {
    return 2 | 8 | 128 | 64;
  }
  setTerminalInstance(instance2) {
    if (this.t) {
      throw new Error("cannot set instance that has already been set");
    }
    this.t = instance2;
    this.G();
  }
  copy() {
    const instance2 = this.w.createInstance(this.h || {}, TerminalLocation2.Editor);
    instance2.focusWhenReady();
    this.h = void 0;
    return this.y.createInstance($fQb_1, instance2.resource, instance2);
  }
  /**
   * Sets the launch config to use for the next call to EditorInput.copy, which will be used when
   * the editor's split command is run.
   */
  setCopyLaunchConfig(launchConfig) {
    this.h = launchConfig;
  }
  /**
   * Returns the terminal instance for this input if it has not yet been detached from the input.
   */
  get terminalInstance() {
    return this.a ? void 0 : this.t;
  }
  showConfirm() {
    if (this.c) {
      return false;
    }
    const confirmOnKill = this.z.getValue(
      "terminal.integrated.confirmOnKill"
      /* TerminalSettingId.ConfirmOnKill */
    );
    if (confirmOnKill === "editor" || confirmOnKill === "always") {
      return this.t?.hasChildProcesses || false;
    }
    return false;
  }
  async confirm(terminals) {
    const { confirmed } = await this.F.confirm({
      type: severity_default.Warning,
      message: localize(10443, null),
      primaryButton: localize(10444, null),
      detail: terminals.length > 1 ? terminals.map((terminal2) => terminal2.editor.getName()).join("\n") + "\n\n" + localize(10445, null) : localize(10446, null)
    });
    return confirmed ? 1 : 2;
  }
  async revert() {
    this.c = true;
  }
  constructor(resource, t, u, w, y, z, C, D, F) {
    super();
    this.resource = resource;
    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.closeHandler = this;
    this.a = false;
    this.b = false;
    this.c = false;
    this.s = this.B(new $ze());
    this.onDidRequestAttach = this.s.event;
    this.m = TerminalContextKeys.editorFocus.bindTo(D);
    if (t) {
      this.G();
    }
  }
  G() {
    const instance2 = this.t;
    if (!instance2) {
      return;
    }
    const instanceOnDidFocusListener = instance2.onDidFocus(() => this.m.set(true));
    const instanceOnDidBlurListener = instance2.onDidBlur(() => this.m.reset());
    this.B($1c(() => {
      if (!this.a && !this.b) {
        instance2.dispose(TerminalExitReason2.User);
      }
      $Xc([instanceOnDidFocusListener, instanceOnDidBlurListener]);
    }));
    const disposeListeners = [
      instance2.onExit((e) => {
        if (!instance2.waitOnExit) {
          this.dispose();
        }
      }),
      instance2.onDisposed(() => this.dispose()),
      instance2.onTitleChanged(() => this.g.fire()),
      instance2.onIconChanged(() => this.g.fire()),
      instanceOnDidFocusListener,
      instanceOnDidBlurListener,
      instance2.statusList.onDidChangePrimaryStatus(() => this.g.fire())
    ];
    this.C.onWillShutdown((e) => {
      this.b = true;
      $Xc(disposeListeners);
      const shouldPersistTerminals = this.z.getValue(
        "terminal.integrated.enablePersistentSessions"
        /* TerminalSettingId.EnablePersistentSessions */
      ) && e.reason === 3;
      if (shouldPersistTerminals) {
        instance2.detachProcessAndDispose(TerminalExitReason2.Shutdown);
      } else {
        instance2.dispose(TerminalExitReason2.Shutdown);
      }
    });
  }
  getName() {
    return this.t?.title || this.resource.fragment;
  }
  getIcon() {
    if (!this.t || !ThemeIcon.isThemeIcon(this.t.icon)) {
      return void 0;
    }
    return this.t.icon;
  }
  getLabelExtraClasses() {
    if (!this.t) {
      return [];
    }
    const extraClasses = ["terminal-tab", "predefined-file-icon"];
    const colorClass = $_Pb(this.t);
    if (colorClass) {
      extraClasses.push(colorClass);
    }
    const uriClasses = $dQb(this.t, this.u.getColorTheme().type);
    if (uriClasses) {
      extraClasses.push(...uriClasses);
    }
    return extraClasses;
  }
  /**
   * Detach the instance from the input such that when the input is disposed it will not dispose
   * of the terminal instance/process.
   */
  detachInstance() {
    if (!this.b) {
      this.t?.detachFromElement();
      this.t?.setParentContextKeyService(this.D);
      this.a = true;
    }
  }
  getDescription() {
    return this.t?.description;
  }
  toUntyped() {
    return {
      resource: this.resource,
      options: {
        override: $$Pb,
        pinned: true,
        forceReload: true
      }
    };
  }
};
$fQb = $fQb_1 = __decorate([
  __param(2, $gs),
  __param(3, $8Pb),
  __param(4, $Pk),
  __param(5, $kl),
  __param(6, $KL),
  __param(7, $on),
  __param(8, $Yv)
], $fQb);

// out-build/vs/workbench/api/browser/mainThreadEditorTabs.js
var $gQb = class $gQb2 {
  constructor(extHostContext, g, h3, i2, editorService) {
    this.g = g;
    this.h = h3;
    this.i = i2;
    this.a = new $2c();
    this.c = [];
    this.d = /* @__PURE__ */ new Map();
    this.e = /* @__PURE__ */ new Map();
    this.f = new $_c();
    this.b = extHostContext.getProxy($yT.ExtHostEditorTabs);
    this.a.add(editorService.onDidEditorsChange((event) => {
      try {
        this.w(event);
      } catch {
        this.i.error("Failed to update model, rebuilding");
        this.v();
      }
    }));
    this.a.add(this.f);
    this.a.add(this.g.onDidAddGroup(() => this.v()));
    this.a.add(this.g.onDidRemoveGroup(() => this.v()));
    this.g.whenReady.then(() => this.v());
  }
  dispose() {
    this.d.clear();
    this.e.clear();
    this.a.dispose();
  }
  /**
   * Creates a tab object with the correct properties
   * @param editor The editor input represented by the tab
   * @param group The group the tab is in
   * @returns A tab object
   */
  j(group2, editor, editorIndex) {
    const editorId = editor.editorId;
    const tab = {
      id: this.l(editor, group2.id),
      label: editor.getName(),
      editorId,
      input: this.k(editor),
      isPinned: group2.isSticky(editorIndex),
      isPreview: !group2.isPinned(editorIndex),
      isActive: group2.isActive(editor),
      isDirty: editor.isDirty()
    };
    return tab;
  }
  k(editor) {
    if (editor instanceof $7Ob) {
      return {
        kind: 3,
        base: editor.base,
        input1: editor.input1.uri,
        input2: editor.input2.uri,
        result: editor.resource
      };
    }
    if (editor instanceof $5vb) {
      return {
        kind: 1,
        uri: editor.resource
      };
    }
    if (editor instanceof $1I && !(editor instanceof $fub)) {
      const primaryResource = editor.primary.resource;
      const secondaryResource = editor.secondary.resource;
      if (editor.primary instanceof $5vb && editor.secondary instanceof $5vb && $oh(primaryResource, secondaryResource) && primaryResource && secondaryResource) {
        return {
          kind: 1,
          uri: primaryResource
        };
      }
      return {
        kind: 0
        /* TabInputKind.UnknownInput */
      };
    }
    if (editor instanceof $trb) {
      return {
        kind: 4,
        notebookType: editor.viewType,
        uri: editor.resource
      };
    }
    if (editor instanceof $VOb) {
      return {
        kind: 6,
        viewType: editor.viewType,
        uri: editor.resource
      };
    }
    if (editor instanceof $8Lb) {
      return {
        kind: 7,
        viewType: editor.viewType
      };
    }
    if (editor instanceof $fQb) {
      return {
        kind: 8
        /* TabInputKind.TerminalEditorInput */
      };
    }
    if (editor instanceof $fub) {
      if (editor.modified instanceof $5vb && editor.original instanceof $5vb) {
        return {
          kind: 2,
          modified: editor.modified.resource,
          original: editor.original.resource
        };
      }
      if (editor.modified instanceof $trb && editor.original instanceof $trb) {
        return {
          kind: 5,
          notebookType: editor.original.viewType,
          modified: editor.modified.resource,
          original: editor.original.resource
        };
      }
    }
    if (editor instanceof $1Ob) {
      return {
        kind: 9,
        uri: editor.resource,
        inputBoxUri: editor.inputResource
      };
    }
    if (editor instanceof $Zzb) {
      return {
        kind: 10
      };
    }
    if (editor instanceof $_Eb) {
      const diffEditors = [];
      for (const resource of editor?.resources.get() ?? []) {
        if (resource.originalUri && resource.modifiedUri) {
          diffEditors.push({
            kind: 2,
            original: resource.originalUri,
            modified: resource.modifiedUri
          });
        }
      }
      return {
        kind: 11,
        diffEditors
      };
    }
    return {
      kind: 0
      /* TabInputKind.UnknownInput */
    };
  }
  /**
   * Generates a unique id for a tab
   * @param editor The editor input
   * @param groupId The group id
   * @returns A unique identifier for a specific tab
   */
  l(editor, groupId) {
    let resourceString;
    const resource = $mL.getCanonicalUri(editor, { supportSideBySide: SideBySideEditor.BOTH });
    if (resource instanceof URI) {
      resourceString = resource.toString();
    } else {
      resourceString = `${resource?.primary?.toString()}-${resource?.secondary?.toString()}`;
    }
    return `${groupId}~${editor.editorId}-${editor.typeId}-${resourceString} `;
  }
  /**
   * Called whenever a group activates, updates the model by marking the group as active an notifies the extension host
   */
  m() {
    const activeGroupId = this.g.activeGroup.id;
    const activeGroup = this.d.get(activeGroupId);
    if (activeGroup) {
      activeGroup.isActive = true;
      this.b.$acceptTabGroupUpdate(activeGroup);
    }
  }
  /**
   * Called when the tab label changes
   * @param groupId The id of the group the tab exists in
   * @param editorInput The editor input represented by the tab
   */
  n(groupId, editorInput, editorIndex) {
    const tabId = this.l(editorInput, groupId);
    const tabInfo = this.e.get(tabId);
    if (tabInfo) {
      tabInfo.tab.label = editorInput.getName();
      this.b.$acceptTabOperation({
        groupId,
        index: editorIndex,
        tabDto: tabInfo.tab,
        kind: 2
        /* TabModelOperationKind.TAB_UPDATE */
      });
    } else {
      this.i.error("Invalid model for label change, rebuilding");
      this.v();
    }
  }
  /**
   * Called when a new tab is opened
   * @param groupId The id of the group the tab is being created in
   * @param editorInput The editor input being opened
   * @param editorIndex The index of the editor within that group
   */
  o(groupId, editorInput, editorIndex) {
    const group2 = this.g.getGroup(groupId);
    const groupInModel = this.d.get(groupId) !== void 0;
    if (!group2 || !groupInModel) {
      this.v();
      return;
    }
    const tabs = this.d.get(groupId)?.tabs;
    if (!tabs) {
      return;
    }
    const tabObject = this.j(group2, editorInput, editorIndex);
    tabs.splice(editorIndex, 0, tabObject);
    const tabId = this.l(editorInput, groupId);
    this.e.set(tabId, { group: group2, editorInput, tab: tabObject });
    if (editorInput instanceof $_Eb) {
      this.f.set(editorInput, Event2.fromObservableLight(editorInput.resources)(() => {
        const tabInfo = this.e.get(tabId);
        if (!tabInfo) {
          return;
        }
        tabInfo.tab = this.j(group2, editorInput, editorIndex);
        this.b.$acceptTabOperation({
          groupId,
          index: editorIndex,
          tabDto: tabInfo.tab,
          kind: 2
          /* TabModelOperationKind.TAB_UPDATE */
        });
      }));
    }
    this.b.$acceptTabOperation({
      groupId,
      index: editorIndex,
      tabDto: tabObject,
      kind: 0
      /* TabModelOperationKind.TAB_OPEN */
    });
  }
  /**
   * Called when a tab is closed
   * @param groupId The id of the group the tab is being removed from
   * @param editorIndex The index of the editor within that group
   */
  p(groupId, editorIndex) {
    const group2 = this.g.getGroup(groupId);
    const tabs = this.d.get(groupId)?.tabs;
    if (!group2 || !tabs) {
      this.v();
      return;
    }
    const removedTab = tabs.splice(editorIndex, 1);
    if (removedTab.length === 0) {
      return;
    }
    this.e.delete(removedTab[0]?.id ?? "");
    if (removedTab[0]?.input instanceof $_Eb) {
      this.f.deleteAndDispose(removedTab[0]?.input);
    }
    this.b.$acceptTabOperation({
      groupId,
      index: editorIndex,
      tabDto: removedTab[0],
      kind: 1
      /* TabModelOperationKind.TAB_CLOSE */
    });
  }
  /**
   * Called when the active tab changes
   * @param groupId The id of the group the tab is contained in
   * @param editorIndex The index of the tab
   */
  q(groupId, editorIndex) {
    const tabs = this.d.get(groupId)?.tabs;
    if (!tabs) {
      return;
    }
    const activeTab = tabs[editorIndex];
    activeTab.isActive = true;
    this.b.$acceptTabOperation({
      groupId,
      index: editorIndex,
      tabDto: activeTab,
      kind: 2
      /* TabModelOperationKind.TAB_UPDATE */
    });
  }
  /**
   * Called when the dirty indicator on the tab changes
   * @param groupId The id of the group the tab is in
   * @param editorIndex The index of the tab
   * @param editor The editor input represented by the tab
   */
  r(groupId, editorIndex, editor) {
    const tabId = this.l(editor, groupId);
    const tabInfo = this.e.get(tabId);
    if (!tabInfo) {
      this.i.error("Invalid model for dirty change, rebuilding");
      this.v();
      return;
    }
    tabInfo.tab.isDirty = editor.isDirty();
    this.b.$acceptTabOperation({
      groupId,
      index: editorIndex,
      tabDto: tabInfo.tab,
      kind: 2
      /* TabModelOperationKind.TAB_UPDATE */
    });
  }
  /**
   * Called when the tab is pinned/unpinned
   * @param groupId The id of the group the tab is in
   * @param editorIndex The index of the tab
   * @param editor The editor input represented by the tab
   */
  s(groupId, editorIndex, editor) {
    const tabId = this.l(editor, groupId);
    const tabInfo = this.e.get(tabId);
    const group2 = tabInfo?.group;
    const tab = tabInfo?.tab;
    if (!group2 || !tab) {
      this.i.error("Invalid model for sticky change, rebuilding");
      this.v();
      return;
    }
    tab.isPinned = group2.isSticky(editorIndex);
    this.b.$acceptTabOperation({
      groupId,
      index: editorIndex,
      tabDto: tab,
      kind: 2
      /* TabModelOperationKind.TAB_UPDATE */
    });
  }
  /**
  * Called when the tab is preview / unpreviewed
  * @param groupId The id of the group the tab is in
  * @param editorIndex The index of the tab
  * @param editor The editor input represented by the tab
  */
  t(groupId, editorIndex, editor) {
    const tabId = this.l(editor, groupId);
    const tabInfo = this.e.get(tabId);
    const group2 = tabInfo?.group;
    const tab = tabInfo?.tab;
    if (!group2 || !tab) {
      this.i.error("Invalid model for sticky change, rebuilding");
      this.v();
      return;
    }
    tab.isPreview = !group2.isPinned(editorIndex);
    this.b.$acceptTabOperation({
      kind: 2,
      groupId,
      tabDto: tab,
      index: editorIndex
    });
  }
  u(groupId, editorIndex, oldEditorIndex, editor) {
    const tabs = this.d.get(groupId)?.tabs;
    if (!tabs) {
      this.i.error("Invalid model for move change, rebuilding");
      this.v();
      return;
    }
    const removedTab = tabs.splice(oldEditorIndex, 1);
    if (removedTab.length === 0) {
      return;
    }
    tabs.splice(editorIndex, 0, removedTab[0]);
    this.b.$acceptTabOperation({
      kind: 3,
      groupId,
      tabDto: removedTab[0],
      index: editorIndex,
      oldIndex: oldEditorIndex
    });
  }
  /**
   * Builds the model from scratch based on the current state of the editor service.
   */
  v() {
    if (this.g.groups.length === 0) {
      return;
    }
    this.c = [];
    this.d.clear();
    this.e.clear();
    let tabs = [];
    for (const group2 of this.g.groups) {
      const currentTabGroupModel = {
        groupId: group2.id,
        isActive: group2.id === this.g.activeGroup.id,
        viewColumn: $AS(this.g, group2),
        tabs: []
      };
      group2.editors.forEach((editor, editorIndex) => {
        const tab = this.j(group2, editor, editorIndex);
        tabs.push(tab);
        this.e.set(this.l(editor, group2.id), {
          group: group2,
          tab,
          editorInput: editor
        });
      });
      currentTabGroupModel.tabs = tabs;
      this.c.push(currentTabGroupModel);
      this.d.set(group2.id, currentTabGroupModel);
      tabs = [];
    }
    this.b.$acceptEditorTabModel(this.c);
  }
  // TODOD @lramos15 Remove this after done finishing the tab model code
  // private _eventToString(event: IEditorsChangeEvent | IEditorsMoveEvent): string {
  // 	let eventString = '';
  // 	switch (event.kind) {
  // 		case GroupModelChangeKind.GROUP_INDEX: eventString += 'GROUP_INDEX'; break;
  // 		case GroupModelChangeKind.EDITOR_ACTIVE: eventString += 'EDITOR_ACTIVE'; break;
  // 		case GroupModelChangeKind.EDITOR_PIN: eventString += 'EDITOR_PIN'; break;
  // 		case GroupModelChangeKind.EDITOR_OPEN: eventString += 'EDITOR_OPEN'; break;
  // 		case GroupModelChangeKind.EDITOR_CLOSE: eventString += 'EDITOR_CLOSE'; break;
  // 		case GroupModelChangeKind.EDITOR_MOVE: eventString += 'EDITOR_MOVE'; break;
  // 		case GroupModelChangeKind.EDITOR_LABEL: eventString += 'EDITOR_LABEL'; break;
  // 		case GroupModelChangeKind.GROUP_ACTIVE: eventString += 'GROUP_ACTIVE'; break;
  // 		case GroupModelChangeKind.GROUP_LOCKED: eventString += 'GROUP_LOCKED'; break;
  // 		case GroupModelChangeKind.EDITOR_DIRTY: eventString += 'EDITOR_DIRTY'; break;
  // 		case GroupModelChangeKind.EDITOR_STICKY: eventString += 'EDITOR_STICKY'; break;
  // 		default: eventString += `UNKNOWN: ${event.kind}`; break;
  // 	}
  // 	return eventString;
  // }
  /**
   * The main handler for the tab events
   * @param events The list of events to process
   */
  w(changeEvent) {
    const event = changeEvent.event;
    const groupId = changeEvent.groupId;
    switch (event.kind) {
      case 0:
        if (groupId === this.g.activeGroup.id) {
          this.m();
          break;
        } else {
          return;
        }
      case 9:
        if (event.editor !== void 0 && event.editorIndex !== void 0) {
          this.n(groupId, event.editor, event.editorIndex);
          break;
        }
      case 5:
        if (event.editor !== void 0 && event.editorIndex !== void 0) {
          this.o(groupId, event.editor, event.editorIndex);
          break;
        }
      case 6:
        if (event.editorIndex !== void 0) {
          this.p(groupId, event.editorIndex);
          break;
        }
      case 8:
        if (event.editorIndex !== void 0) {
          this.q(groupId, event.editorIndex);
          break;
        }
      case 14:
        if (event.editorIndex !== void 0 && event.editor !== void 0) {
          this.r(groupId, event.editorIndex, event.editor);
          break;
        }
      case 13:
        if (event.editorIndex !== void 0 && event.editor !== void 0) {
          this.s(groupId, event.editorIndex, event.editor);
          break;
        }
      case 11:
        if (event.editorIndex !== void 0 && event.editor !== void 0) {
          this.t(groupId, event.editorIndex, event.editor);
          break;
        }
      case 12:
        break;
      case 7:
        if ($7I(event) && event.editor && event.editorIndex !== void 0 && event.oldEditorIndex !== void 0) {
          this.u(groupId, event.editorIndex, event.oldEditorIndex, event.editor);
          break;
        }
      default:
        this.v();
    }
  }
  //#region Messages received from Ext Host
  $moveTab(tabId, index, viewColumn, preserveFocus) {
    const groupId = $zS(this.g, this.h, viewColumn);
    const tabInfo = this.e.get(tabId);
    const tab = tabInfo?.tab;
    if (!tab) {
      throw new Error(`Attempted to close tab with id ${tabId} which does not exist`);
    }
    let targetGroup;
    const sourceGroup = this.g.getGroup(tabInfo.group.id);
    if (!sourceGroup) {
      return;
    }
    if (this.d.get(groupId) === void 0) {
      let direction = 3;
      if (viewColumn === $oJ) {
        direction = $lJ(this.h);
      }
      targetGroup = this.g.addGroup(this.g.groups[this.g.groups.length - 1], direction);
    } else {
      targetGroup = this.g.getGroup(groupId);
    }
    if (!targetGroup) {
      return;
    }
    if (index < 0 || index > targetGroup.editors.length) {
      index = targetGroup.editors.length;
    }
    const editorInput = tabInfo?.editorInput;
    if (!editorInput) {
      return;
    }
    sourceGroup.moveEditor(editorInput, targetGroup, { index, preserveFocus });
    return;
  }
  async $closeTab(tabIds, preserveFocus) {
    const groups = /* @__PURE__ */ new Map();
    for (const tabId of tabIds) {
      const tabInfo = this.e.get(tabId);
      const tab = tabInfo?.tab;
      const group2 = tabInfo?.group;
      const editorTab = tabInfo?.editorInput;
      if (!group2 || !tab || !tabInfo || !editorTab) {
        continue;
      }
      const groupEditors = groups.get(group2);
      if (!groupEditors) {
        groups.set(group2, [editorTab]);
      } else {
        groupEditors.push(editorTab);
      }
    }
    const results = [];
    for (const [group2, editors] of groups) {
      results.push(await group2.closeEditors(editors, { preserveFocus }));
    }
    return results.every((result) => result);
  }
  async $closeGroup(groupIds, preserveFocus) {
    const groupCloseResults = [];
    for (const groupId of groupIds) {
      const group2 = this.g.getGroup(groupId);
      if (group2) {
        groupCloseResults.push(await group2.closeAllEditors());
        if (group2.count === 0 && this.g.getGroup(group2.id)) {
          this.g.removeGroup(group2);
        }
      }
    }
    return groupCloseResults.every((result) => result);
  }
};
$gQb = __decorate([
  $frb($xT.MainThreadEditorTabs),
  __param(1, $iJ),
  __param(2, $kl),
  __param(3, $wn),
  __param(4, $mJ)
], $gQb);

// out-build/vs/workbench/api/browser/mainThreadErrors.js
var $hQb = class $hQb2 {
  dispose() {
  }
  $onUnexpectedError(err) {
    if (err && err.$isError) {
      err = $jb(err);
    }
    $gb(err);
  }
};
$hQb = __decorate([
  $frb($xT.MainThreadErrors)
], $hQb);

// out-build/vs/base/common/worker/simpleWorker.js
var DEFAULT_CHANNEL = "default";
var INITIALIZE = "$initialize";
var webWorkerWarningLogged = false;
function $X1(err) {
  if (!$r) {
    return;
  }
  if (!webWorkerWarningLogged) {
    webWorkerWarningLogged = true;
    console.warn("Could not create web worker(s). Falling back to loading web worker code in main thread, which might cause UI freezes. Please see https://github.com/microsoft/monaco-editor#faq");
  }
  console.warn(err.message);
}
var MessageType2;
(function(MessageType5) {
  MessageType5[MessageType5["Request"] = 0] = "Request";
  MessageType5[MessageType5["Reply"] = 1] = "Reply";
  MessageType5[MessageType5["SubscribeEvent"] = 2] = "SubscribeEvent";
  MessageType5[MessageType5["Event"] = 3] = "Event";
  MessageType5[MessageType5["UnsubscribeEvent"] = 4] = "UnsubscribeEvent";
})(MessageType2 || (MessageType2 = {}));
var RequestMessage = class {
  constructor(vsWorker, req, channel, method, args2) {
    this.vsWorker = vsWorker;
    this.req = req;
    this.channel = channel;
    this.method = method;
    this.args = args2;
    this.type = 0;
  }
};
var ReplyMessage = class {
  constructor(vsWorker, seq, res, err) {
    this.vsWorker = vsWorker;
    this.seq = seq;
    this.res = res;
    this.err = err;
    this.type = 1;
  }
};
var SubscribeEventMessage = class {
  constructor(vsWorker, req, channel, eventName, arg) {
    this.vsWorker = vsWorker;
    this.req = req;
    this.channel = channel;
    this.eventName = eventName;
    this.arg = arg;
    this.type = 2;
  }
};
var EventMessage = class {
  constructor(vsWorker, req, event) {
    this.vsWorker = vsWorker;
    this.req = req;
    this.event = event;
    this.type = 3;
  }
};
var UnsubscribeEventMessage = class {
  constructor(vsWorker, req) {
    this.vsWorker = vsWorker;
    this.req = req;
    this.type = 4;
  }
};
var SimpleWorkerProtocol = class {
  constructor(handler) {
    this.a = -1;
    this.g = handler;
    this.b = 0;
    this.c = /* @__PURE__ */ Object.create(null);
    this.d = /* @__PURE__ */ new Map();
    this.f = /* @__PURE__ */ new Map();
  }
  setWorkerId(workerId) {
    this.a = workerId;
  }
  sendMessage(channel, method, args2) {
    const req = String(++this.b);
    return new Promise((resolve, reject) => {
      this.c[req] = {
        resolve,
        reject
      };
      this.o(new RequestMessage(this.a, req, channel, method, args2));
    });
  }
  listen(channel, eventName, arg) {
    let req = null;
    const emitter = new $ze({
      onWillAddFirstListener: () => {
        req = String(++this.b);
        this.d.set(req, emitter);
        this.o(new SubscribeEventMessage(this.a, req, channel, eventName, arg));
      },
      onDidRemoveLastListener: () => {
        this.d.delete(req);
        this.o(new UnsubscribeEventMessage(this.a, req));
        req = null;
      }
    });
    return emitter.event;
  }
  handleMessage(message) {
    if (!message || !message.vsWorker) {
      return;
    }
    if (this.a !== -1 && message.vsWorker !== this.a) {
      return;
    }
    this.h(message);
  }
  createProxyToRemoteChannel(channel, sendMessageBarrier) {
    const handler = {
      get: (target, name) => {
        if (typeof name === "string" && !target[name]) {
          if (propertyIsDynamicEvent(name)) {
            target[name] = (arg) => {
              return this.listen(channel, name, arg);
            };
          } else if (propertyIsEvent(name)) {
            target[name] = this.listen(channel, name, void 0);
          } else if (name.charCodeAt(0) === 36) {
            target[name] = async (...myArgs) => {
              await sendMessageBarrier?.();
              return this.sendMessage(channel, name, myArgs);
            };
          }
        }
        return target[name];
      }
    };
    return new Proxy(/* @__PURE__ */ Object.create(null), handler);
  }
  h(msg) {
    switch (msg.type) {
      case 1:
        return this.j(msg);
      case 0:
        return this.k(msg);
      case 2:
        return this.l(msg);
      case 3:
        return this.m(msg);
      case 4:
        return this.n(msg);
    }
  }
  j(replyMessage) {
    if (!this.c[replyMessage.seq]) {
      console.warn("Got reply to unknown seq");
      return;
    }
    const reply = this.c[replyMessage.seq];
    delete this.c[replyMessage.seq];
    if (replyMessage.err) {
      let err = replyMessage.err;
      if (replyMessage.err.$isError) {
        err = new Error();
        err.name = replyMessage.err.name;
        err.message = replyMessage.err.message;
        err.stack = replyMessage.err.stack;
      }
      reply.reject(err);
      return;
    }
    reply.resolve(replyMessage.res);
  }
  k(requestMessage) {
    const req = requestMessage.req;
    const result = this.g.handleMessage(requestMessage.channel, requestMessage.method, requestMessage.args);
    result.then((r2) => {
      this.o(new ReplyMessage(this.a, req, r2, void 0));
    }, (e) => {
      if (e.detail instanceof Error) {
        e.detail = $ib(e.detail);
      }
      this.o(new ReplyMessage(this.a, req, void 0, $ib(e)));
    });
  }
  l(msg) {
    const req = msg.req;
    const disposable = this.g.handleEvent(msg.channel, msg.eventName, msg.arg)((event) => {
      this.o(new EventMessage(this.a, req, event));
    });
    this.f.set(req, disposable);
  }
  m(msg) {
    if (!this.d.has(msg.req)) {
      console.warn("Got event for unknown req");
      return;
    }
    this.d.get(msg.req).fire(msg.event);
  }
  n(msg) {
    if (!this.f.has(msg.req)) {
      console.warn("Got unsubscribe for unknown req");
      return;
    }
    this.f.get(msg.req).dispose();
    this.f.delete(msg.req);
  }
  o(msg) {
    const transfer = [];
    if (msg.type === 0) {
      for (let i2 = 0; i2 < msg.args.length; i2++) {
        if (msg.args[i2] instanceof ArrayBuffer) {
          transfer.push(msg.args[i2]);
        }
      }
    } else if (msg.type === 1) {
      if (msg.res instanceof ArrayBuffer) {
        transfer.push(msg.res);
      }
    }
    this.g.sendMessage(msg, transfer);
  }
};
var $Y1 = class extends $3c {
  constructor(workerFactory, workerDescriptor) {
    super();
    this.f = /* @__PURE__ */ new Map();
    this.g = /* @__PURE__ */ new Map();
    this.a = this.B(workerFactory.create({
      moduleId: "vs/base/common/worker/simpleWorker",
      esmModuleLocation: workerDescriptor.esmModuleLocation,
      label: workerDescriptor.label
    }, (msg) => {
      this.c.handleMessage(msg);
    }, (err) => {
      $gb(err);
    }));
    this.c = new SimpleWorkerProtocol({
      sendMessage: (msg, transfer) => {
        this.a.postMessage(msg, transfer);
      },
      handleMessage: (channel, method, args2) => {
        return this.h(channel, method, args2);
      },
      handleEvent: (channel, eventName, arg) => {
        return this.j(channel, eventName, arg);
      }
    });
    this.c.setWorkerId(this.a.getId());
    let loaderConfiguration = null;
    const globalRequire = globalThis.require;
    if (typeof globalRequire !== "undefined" && typeof globalRequire.getConfig === "function") {
      loaderConfiguration = globalRequire.getConfig();
    } else if (typeof globalThis.requirejs !== "undefined") {
      loaderConfiguration = globalThis.requirejs.s.contexts._.config;
    }
    this.b = this.c.sendMessage(DEFAULT_CHANNEL, INITIALIZE, [
      this.a.getId(),
      JSON.parse(JSON.stringify(loaderConfiguration)),
      workerDescriptor.moduleId
    ]);
    this.proxy = this.c.createProxyToRemoteChannel(DEFAULT_CHANNEL, async () => {
      await this.b;
    });
    this.b.catch((e) => {
      this.m("Worker failed to load " + workerDescriptor.moduleId, e);
    });
  }
  h(channelName, method, args2) {
    const channel = this.f.get(channelName);
    if (!channel) {
      return Promise.reject(new Error(`Missing channel ${channelName} on main thread`));
    }
    if (typeof channel[method] !== "function") {
      return Promise.reject(new Error(`Missing method ${method} on main thread channel ${channelName}`));
    }
    try {
      return Promise.resolve(channel[method].apply(channel, args2));
    } catch (e) {
      return Promise.reject(e);
    }
  }
  j(channelName, eventName, arg) {
    const channel = this.f.get(channelName);
    if (!channel) {
      throw new Error(`Missing channel ${channelName} on main thread`);
    }
    if (propertyIsDynamicEvent(eventName)) {
      const event = channel[eventName].call(channel, arg);
      if (typeof event !== "function") {
        throw new Error(`Missing dynamic event ${eventName} on main thread channel ${channelName}.`);
      }
      return event;
    }
    if (propertyIsEvent(eventName)) {
      const event = channel[eventName];
      if (typeof event !== "function") {
        throw new Error(`Missing event ${eventName} on main thread channel ${channelName}.`);
      }
      return event;
    }
    throw new Error(`Malformed event name ${eventName}`);
  }
  setChannel(channel, handler) {
    this.f.set(channel, handler);
  }
  getChannel(channel) {
    if (!this.g.has(channel)) {
      const inst = this.c.createProxyToRemoteChannel(channel, async () => {
        await this.b;
      });
      this.g.set(channel, inst);
    }
    return this.g.get(channel);
  }
  m(message, error) {
    console.error(message);
    console.info(error);
  }
};
function propertyIsEvent(name) {
  return name[0] === "o" && name[1] === "n" && $Zf(name.charCodeAt(2));
}
function propertyIsDynamicEvent(name) {
  return /^onDynamic/.test(name) && $Zf(name.charCodeAt(9));
}

// out-build/vs/base/browser/defaultWorkerFactory.js
var ttPolicy4;
if (typeof self === "object" && self.constructor && self.constructor.name === "DedicatedWorkerGlobalScope" && globalThis.workerttPolicy !== void 0) {
  ttPolicy4 = globalThis.workerttPolicy;
} else {
  ttPolicy4 = $W1("defaultWorkerFactory", { createScriptURL: (value) => value });
}
function $212(blobUrl, options3) {
  if (!blobUrl.startsWith("blob:")) {
    throw new URIError("Not a blob-url: " + blobUrl);
  }
  return new Worker(ttPolicy4 ? ttPolicy4.createScriptURL(blobUrl) : blobUrl, { ...options3, type: "module" });
}
function getWorker(esmWorkerLocation, label3) {
  const monacoEnvironment = globalThis.MonacoEnvironment;
  if (monacoEnvironment) {
    if (typeof monacoEnvironment.getWorker === "function") {
      return monacoEnvironment.getWorker("workerMain.js", label3);
    }
    if (typeof monacoEnvironment.getWorkerUrl === "function") {
      const workerUrl = monacoEnvironment.getWorkerUrl("workerMain.js", label3);
      return new Worker(ttPolicy4 ? ttPolicy4.createScriptURL(workerUrl) : workerUrl, { name: label3, type: "module" });
    }
  }
  if (esmWorkerLocation) {
    const workerUrl = getWorkerBootstrapUrl(label3, esmWorkerLocation.toString(true));
    const worker = new Worker(ttPolicy4 ? ttPolicy4.createScriptURL(workerUrl) : workerUrl, { name: label3, type: "module" });
    return whenESMWorkerReady(worker);
  }
  throw new Error(`You must define a function MonacoEnvironment.getWorkerUrl or MonacoEnvironment.getWorker`);
}
function getWorkerBootstrapUrl(label3, workerScriptUrl) {
  if (/^((http:)|(https:)|(file:))/.test(workerScriptUrl) && workerScriptUrl.substring(0, globalThis.origin.length) !== globalThis.origin) {
  } else {
    const start = workerScriptUrl.lastIndexOf("?");
    const end = workerScriptUrl.lastIndexOf("#", start);
    const params = start > 0 ? new URLSearchParams(workerScriptUrl.substring(start + 1, ~end ? end : void 0)) : new URLSearchParams();
    COI.addSearchParam(params, true, true);
    const search2 = params.toString();
    if (!search2) {
      workerScriptUrl = `${workerScriptUrl}#${label3}`;
    } else {
      workerScriptUrl = `${workerScriptUrl}?${params.toString()}#${label3}`;
    }
  }
  const blob = new Blob([$Mb([
    `/*${label3}*/`,
    `globalThis._VSCODE_NLS_MESSAGES = ${JSON.stringify($f())};`,
    `globalThis._VSCODE_NLS_LANGUAGE = ${JSON.stringify($g())};`,
    `globalThis._VSCODE_FILE_ROOT = ${JSON.stringify(globalThis._VSCODE_FILE_ROOT)};`,
    `const ttPolicy = globalThis.trustedTypes?.createPolicy('defaultWorkerFactory', { createScriptURL: value => value });`,
    `globalThis.workerttPolicy = ttPolicy;`,
    `await import(ttPolicy?.createScriptURL(${JSON.stringify(workerScriptUrl)}) ?? ${JSON.stringify(workerScriptUrl)});`,
    `globalThis.postMessage({ type: 'vscode-worker-ready' });`,
    `/*${label3}*/`
  ]).join("")], { type: "application/javascript" });
  return URL.createObjectURL(blob);
}
function whenESMWorkerReady(worker) {
  return new Promise((resolve, reject) => {
    worker.onmessage = function(e) {
      if (e.data.type === "vscode-worker-ready") {
        worker.onmessage = null;
        resolve(worker);
      }
    };
    worker.onerror = reject;
  });
}
function isPromiseLike(obj) {
  if (typeof obj.then === "function") {
    return true;
  }
  return false;
}
var WebWorker = class extends $3c {
  constructor(esmWorkerLocation, moduleId, id2, label3, onMessageCallback, onErrorCallback) {
    super();
    this.a = id2;
    this.b = label3;
    const workerOrPromise = getWorker(esmWorkerLocation, label3);
    if (isPromiseLike(workerOrPromise)) {
      this.c = workerOrPromise;
    } else {
      this.c = Promise.resolve(workerOrPromise);
    }
    this.postMessage(moduleId, []);
    this.c.then((w) => {
      w.onmessage = function(ev) {
        onMessageCallback(ev.data);
      };
      w.onmessageerror = onErrorCallback;
      if (typeof w.addEventListener === "function") {
        w.addEventListener("error", onErrorCallback);
      }
    });
    this.B($1c(() => {
      this.c?.then((w) => {
        w.onmessage = null;
        w.onmessageerror = null;
        w.removeEventListener("error", onErrorCallback);
        w.terminate();
      });
      this.c = null;
    }));
  }
  getId() {
    return this.a;
  }
  postMessage(message, transfer) {
    this.c?.then((w) => {
      try {
        w.postMessage(message, transfer);
      } catch (err) {
        $gb(err);
        $gb(new Error(`FAILED to post message to '${this.b}'-worker`, { cause: err }));
      }
    });
  }
};
var $312 = class {
  constructor(moduleId, label3) {
    this.moduleId = moduleId;
    this.label = label3;
    this.esmModuleLocation = $ih.asBrowserUri(`${moduleId}Main.js`);
  }
};
var DefaultWorkerFactory = class _DefaultWorkerFactory {
  static {
    this.a = 0;
  }
  constructor() {
    this.b = false;
  }
  create(desc, onMessageCallback, onErrorCallback) {
    const workerId = ++_DefaultWorkerFactory.a;
    if (this.b) {
      throw this.b;
    }
    return new WebWorker(desc.esmModuleLocation, desc.moduleId, workerId, desc.label || "anonymous" + workerId, onMessageCallback, (err) => {
      $X1(err);
      this.b = err;
      onErrorCallback(err);
    });
  }
};
function $412(arg0, arg1) {
  const workerDescriptor = typeof arg0 === "string" ? new $312(arg0, arg1) : arg0;
  return new $Y1(new DefaultWorkerFactory(), workerDescriptor);
}

// out-build/vs/workbench/services/timer/browser/timerService.js
var $iQb = $Qk("timerService");
var PerfMarks = class {
  constructor() {
    this.a = [];
  }
  setMarks(source, entries2) {
    this.a.push([source, entries2]);
  }
  getDuration(from, to) {
    const fromEntry = this.b(from);
    if (!fromEntry) {
      return 0;
    }
    const toEntry2 = this.b(to);
    if (!toEntry2) {
      return 0;
    }
    return toEntry2.startTime - fromEntry.startTime;
  }
  getStartTime(mark) {
    const entry = this.b(mark);
    return entry ? entry.startTime : -1;
  }
  b(name) {
    for (const [, marks] of this.a) {
      for (let i2 = marks.length - 1; i2 >= 0; i2--) {
        if (marks[i2].name === name) {
          return marks[i2];
        }
      }
    }
  }
  getEntries() {
    return this.a.slice(0);
  }
};
var $jQb = class $jQb2 {
  constructor(f, g, h3, j, k, l, m, o, layoutService) {
    this.f = f;
    this.g = g;
    this.h = h3;
    this.j = j;
    this.k = k;
    this.l = l;
    this.m = m;
    this.o = o;
    this.a = new $Uh();
    this.b = new PerfMarks();
    this.c = Math.random() < 0.05;
    Promise.all([
      this.h.whenInstalledExtensionsRegistered(),
      // extensions registered
      f.when(
        3
        /* LifecyclePhase.Restored */
      ),
      // workbench created and parts restored
      layoutService.whenRestored,
      // layout restored (including visible editors resolved)
      Promise.all(Array.from($Wn.as($6x.Backend).backends.values()).map((e) => e.whenReady))
    ]).then(() => {
      this.setPerformanceMarks("renderer", $T());
      return this.s();
    }).then((metrics) => {
      this.d = metrics;
      this.p(metrics);
      this.a.open();
    });
    this.perfBaseline = this.a.wait().then(() => this.f.when(
      4
      /* LifecyclePhase.Eventually */
    )).then(() => $Wh(this.d.timers.ellapsedRequire)).then(() => {
      const jsSrc = function() {
        let tooSlow = false;
        function fib(n) {
          if (tooSlow) {
            return 0;
          }
          if (performance.now() - t1 >= 1e3) {
            tooSlow = true;
          }
          if (n <= 2) {
            return n;
          }
          return fib(n - 1) + fib(n - 2);
        }
        const t1 = performance.now();
        fib(24);
        const value = Math.round(performance.now() - t1);
        self.postMessage({ value: tooSlow ? -1 : value });
      }.toString();
      const blob = new Blob([`(${jsSrc})();`], { type: "application/javascript" });
      const blobUrl = URL.createObjectURL(blob);
      const worker = $212(blobUrl, { name: "perfBaseline" });
      return new Promise((resolve) => {
        worker.onmessage = (e) => resolve(e.data.value);
      }).finally(() => {
        worker.terminate();
        URL.revokeObjectURL(blobUrl);
      });
    });
  }
  whenReady() {
    return this.a.wait();
  }
  get startupMetrics() {
    if (!this.d) {
      throw new Error("illegal state, MUST NOT access startupMetrics before whenReady has resolved");
    }
    return this.d;
  }
  setPerformanceMarks(source, marks) {
    const codeMarks = marks.filter((mark) => mark.name.startsWith("code/"));
    this.b.setMarks(source, codeMarks);
    this.r(source, codeMarks);
  }
  getPerformanceMarks() {
    return this.b.getEntries();
  }
  getDuration(from, to) {
    return this.b.getDuration(from, to);
  }
  getStartTime(mark) {
    return this.b.getStartTime(mark);
  }
  p(metrics) {
    this.o.publicLog("startupTimeVaried", metrics);
  }
  q() {
    return this.c;
  }
  r(source, marks) {
    if (!this.q()) {
      return;
    }
    for (const mark of marks) {
      this.o.publicLog2("startup.timer.mark", {
        source,
        name: new $bw(mark.name),
        startTime: mark.startTime
      });
    }
  }
  async s() {
    const initialStartup = this.t();
    let startMark;
    if ($r) {
      startMark = "code/timeOrigin";
    } else {
      startMark = initialStartup ? "code/didStartMain" : "code/willOpenNewWindow";
    }
    const activeViewlet = this.k.getActivePaneComposite(
      0
      /* ViewContainerLocation.Sidebar */
    );
    const activePanel = this.k.getActivePaneComposite(
      1
      /* ViewContainerLocation.Panel */
    );
    const info = {
      version: 2,
      ellapsed: this.b.getDuration(startMark, "code/didStartWorkbench"),
      // reflections
      isLatestVersion: Boolean(await this.j.isLatestVersion()),
      didUseCachedData: this.u(),
      windowKind: this.f.startupKind,
      windowCount: await this.v(),
      viewletId: activeViewlet?.getId(),
      editorIds: this.l.visibleEditors.map((input) => input.typeId),
      panelId: activePanel ? activePanel.getId() : void 0,
      // timers
      timers: {
        ellapsedAppReady: initialStartup ? this.b.getDuration("code/didStartMain", "code/mainAppReady") : void 0,
        ellapsedNlsGeneration: initialStartup ? this.b.getDuration("code/willGenerateNls", "code/didGenerateNls") : void 0,
        ellapsedLoadMainBundle: initialStartup ? this.b.getDuration("code/willLoadMainBundle", "code/didLoadMainBundle") : void 0,
        ellapsedRunMainBundle: initialStartup ? this.b.getDuration("code/didStartMain", "code/didRunMainBundle") : void 0,
        ellapsedCrashReporter: initialStartup ? this.b.getDuration("code/willStartCrashReporter", "code/didStartCrashReporter") : void 0,
        ellapsedMainServer: initialStartup ? this.b.getDuration("code/willStartMainServer", "code/didStartMainServer") : void 0,
        ellapsedWindowCreate: initialStartup ? this.b.getDuration("code/willCreateCodeWindow", "code/didCreateCodeWindow") : void 0,
        ellapsedWindowRestoreState: initialStartup ? this.b.getDuration("code/willRestoreCodeWindowState", "code/didRestoreCodeWindowState") : void 0,
        ellapsedBrowserWindowCreate: initialStartup ? this.b.getDuration("code/willCreateCodeBrowserWindow", "code/didCreateCodeBrowserWindow") : void 0,
        ellapsedWindowMaximize: initialStartup ? this.b.getDuration("code/willMaximizeCodeWindow", "code/didMaximizeCodeWindow") : void 0,
        ellapsedWindowLoad: initialStartup ? this.b.getDuration("code/mainAppReady", "code/willOpenNewWindow") : void 0,
        ellapsedWindowLoadToRequire: this.b.getDuration("code/willOpenNewWindow", "code/willLoadWorkbenchMain"),
        ellapsedRequire: this.b.getDuration("code/willLoadWorkbenchMain", "code/didLoadWorkbenchMain"),
        ellapsedWaitForWindowConfig: this.b.getDuration("code/willWaitForWindowConfig", "code/didWaitForWindowConfig"),
        ellapsedStorageInit: this.b.getDuration("code/willInitStorage", "code/didInitStorage"),
        ellapsedSharedProcesConnected: this.b.getDuration("code/willConnectSharedProcess", "code/didConnectSharedProcess"),
        ellapsedWorkspaceServiceInit: this.b.getDuration("code/willInitWorkspaceService", "code/didInitWorkspaceService"),
        ellapsedRequiredUserDataInit: this.b.getDuration("code/willInitRequiredUserData", "code/didInitRequiredUserData"),
        ellapsedOtherUserDataInit: this.b.getDuration("code/willInitOtherUserData", "code/didInitOtherUserData"),
        ellapsedExtensions: this.b.getDuration("code/willLoadExtensions", "code/didLoadExtensions"),
        ellapsedEditorRestore: this.b.getDuration("code/willRestoreEditors", "code/didRestoreEditors"),
        ellapsedViewletRestore: this.b.getDuration("code/willRestoreViewlet", "code/didRestoreViewlet"),
        ellapsedPanelRestore: this.b.getDuration("code/willRestorePanel", "code/didRestorePanel"),
        ellapsedWorkbenchContributions: this.b.getDuration("code/willCreateWorkbenchContributions/1", "code/didCreateWorkbenchContributions/2"),
        ellapsedWorkbench: this.b.getDuration("code/willStartWorkbench", "code/didStartWorkbench"),
        ellapsedExtensionsReady: this.b.getDuration(startMark, "code/didLoadExtensions"),
        ellapsedRenderer: this.b.getDuration("code/didStartRenderer", "code/didStartWorkbench")
      },
      // system info
      platform: void 0,
      release: void 0,
      arch: void 0,
      totalmem: void 0,
      freemem: void 0,
      meminfo: void 0,
      cpus: void 0,
      loadavg: void 0,
      isVMLikelyhood: void 0,
      initialStartup,
      hasAccessibilitySupport: this.m.isScreenReaderOptimized(),
      emptyWorkbench: this.g.getWorkbenchState() === 1
      /* WorkbenchState.EMPTY */
    };
    await this.w(info);
    return info;
  }
};
$jQb = __decorate([
  __param(0, $KL),
  __param(1, $Zk),
  __param(2, $wN),
  __param(3, $az),
  __param(4, $uqb),
  __param(5, $mJ),
  __param(6, $ND),
  __param(7, $zv),
  __param(8, $Vlb)
], $jQb);
var $kQb = class extends $jQb {
  t() {
    return false;
  }
  u() {
    return false;
  }
  async v() {
    return 1;
  }
  async w(info) {
    info.isVMLikelyhood = 0;
    info.isARM64Emulated = false;
    info.platform = navigator.userAgent;
    info.release = navigator.appVersion;
  }
};

// out-build/vs/workbench/api/browser/mainThreadExtensionService.js
var $lQb = class $lQb2 {
  constructor(extHostContext, d, f, g, h3, j, k, l, m) {
    this.d = d;
    this.f = f;
    this.g = g;
    this.h = h3;
    this.j = j;
    this.k = k;
    this.l = l;
    this.m = m;
    this.a = extHostContext.extensionHostKind;
    const internalExtHostContext = extHostContext;
    this.c = internalExtHostContext.internalExtensionService;
    internalExtHostContext._setExtensionHostProxy(new ExtensionHostProxy(extHostContext.getProxy($yT.ExtHostExtensionService)));
    internalExtHostContext._setAllMainProxyIdentifiers(Object.keys($xT).map((key2) => $xT[key2]));
  }
  dispose() {
  }
  $getExtension(extensionId) {
    return this.d.getExtension(extensionId);
  }
  $activateExtension(extensionId, reason) {
    return this.c._activateById(extensionId, reason);
  }
  async $onWillActivateExtension(extensionId) {
    this.c._onWillActivateExtension(extensionId);
  }
  $onDidActivateExtension(extensionId, codeLoadingTime, activateCallTime, activateResolvedTime, activationReason) {
    this.c._onDidActivateExtension(extensionId, codeLoadingTime, activateCallTime, activateResolvedTime, activationReason);
  }
  $onExtensionRuntimeError(extensionId, data) {
    const error = $jb(data);
    this.c._onExtensionRuntimeError(extensionId, error);
    console.error(`[${extensionId.value}]${error.message}`);
    console.error(error.stack);
  }
  async $onExtensionActivationError(extensionId, data, missingExtensionDependency) {
    const error = $jb(data);
    this.c._onDidActivateExtensionError(extensionId, error);
    if (missingExtensionDependency) {
      const extension = await this.d.getExtension(extensionId.value);
      if (extension) {
        const local = await this.g.queryLocal();
        const installedDependency = local.find((i2) => $DA(i2.identifier, { id: missingExtensionDependency.dependency }));
        if (installedDependency?.local) {
          await this.o(extension, installedDependency.local);
          return;
        } else {
          await this.p(extension, missingExtensionDependency.dependency);
          return;
        }
      }
    }
    const isDev = !this.m.isBuilt || this.m.isExtensionDevelopment;
    if (isDev) {
      this.f.error(error);
      return;
    }
    console.error(error.message);
  }
  async o(extension, missingInstalledDependency) {
    const extName = extension.displayName || extension.name;
    if (this.j.isEnabled(missingInstalledDependency)) {
      this.f.notify({
        severity: severity_default.Error,
        message: localize(2584, null, extName, missingInstalledDependency.manifest.displayName || missingInstalledDependency.manifest.name),
        actions: {
          primary: [new $Um("reload", localize(2585, null), "", true, () => this.h.reload())]
        }
      });
    } else {
      const enablementState = this.j.getEnablementState(missingInstalledDependency);
      if (enablementState === 4) {
        this.f.notify({
          severity: severity_default.Error,
          message: localize(2586, null, extName, missingInstalledDependency.manifest.displayName || missingInstalledDependency.manifest.name)
        });
      } else if (enablementState === 0) {
        this.f.notify({
          severity: severity_default.Error,
          message: localize(2587, null, extName, missingInstalledDependency.manifest.displayName || missingInstalledDependency.manifest.name),
          actions: {
            primary: [new $Um("manageWorkspaceTrust", localize(2588, null), "", true, () => this.l.executeCommand("workbench.trust.manage"))]
          }
        });
      } else if (this.j.canChangeEnablement(missingInstalledDependency)) {
        this.f.notify({
          severity: severity_default.Error,
          message: localize(2589, null, extName, missingInstalledDependency.manifest.displayName || missingInstalledDependency.manifest.name),
          actions: {
            primary: [new $Um("enable", localize(2590, null), "", true, () => this.j.setEnablement(
              [missingInstalledDependency],
              enablementState === 8 ? 10 : 11
              /* EnablementState.EnabledWorkspace */
            ).then(() => this.h.reload(), (e) => this.f.error(e)))]
          }
        });
      } else {
        this.f.notify({
          severity: severity_default.Error,
          message: localize(2591, null, extName, missingInstalledDependency.manifest.displayName || missingInstalledDependency.manifest.name)
        });
      }
    }
  }
  async p(extension, missingDependency) {
    const extName = extension.displayName || extension.name;
    let dependencyExtension = null;
    try {
      dependencyExtension = (await this.g.getExtensions([{ id: missingDependency }], CancellationToken.None))[0];
    } catch (err) {
    }
    if (dependencyExtension) {
      this.f.notify({
        severity: severity_default.Error,
        message: localize(2592, null, extName, dependencyExtension.displayName, dependencyExtension.publisherDisplayName),
        actions: {
          primary: [new $Um("install", localize(2593, null), "", true, () => this.g.install(dependencyExtension).then(() => this.h.reload(), (e) => this.f.error(e)))]
        }
      });
    } else {
      this.f.error(localize(2594, null, extName, missingDependency));
    }
  }
  async $setPerformanceMarks(marks) {
    if (this.a === 1) {
      this.k.setPerformanceMarks("localExtHost", marks);
    } else if (this.a === 2) {
      this.k.setPerformanceMarks("workerExtHost", marks);
    } else {
      this.k.setPerformanceMarks("remoteExtHost", marks);
    }
  }
  async $asBrowserUri(uri) {
    return $ih.uriToBrowserUri(URI.revive(uri));
  }
};
$lQb = __decorate([
  $frb($xT.MainThreadExtensionService),
  __param(1, $wN),
  __param(2, $PJ),
  __param(3, $vzb),
  __param(4, $S4),
  __param(5, $qzb),
  __param(6, $iQb),
  __param(7, $sn),
  __param(8, $US)
], $lQb);
var ExtensionHostProxy = class {
  constructor(a) {
    this.a = a;
  }
  async resolveAuthority(remoteAuthority, resolveAttempt) {
    const resolved = reviveResolveAuthorityResult(await this.a.$resolveAuthority(remoteAuthority, resolveAttempt));
    return resolved;
  }
  async getCanonicalURI(remoteAuthority, uri) {
    const uriComponents = await this.a.$getCanonicalURI(remoteAuthority, uri);
    return uriComponents ? URI.revive(uriComponents) : uriComponents;
  }
  startExtensionHost(extensionsDelta) {
    return this.a.$startExtensionHost(extensionsDelta);
  }
  extensionTestsExecute() {
    return this.a.$extensionTestsExecute();
  }
  activateByEvent(activationEvent, activationKind) {
    return this.a.$activateByEvent(activationEvent, activationKind);
  }
  activate(extensionId, reason) {
    return this.a.$activate(extensionId, reason);
  }
  setRemoteEnvironment(env3) {
    return this.a.$setRemoteEnvironment(env3);
  }
  updateRemoteConnectionData(connectionData) {
    return this.a.$updateRemoteConnectionData(connectionData);
  }
  deltaExtensions(extensionsDelta) {
    return this.a.$deltaExtensions(extensionsDelta);
  }
  test_latency(n) {
    return this.a.$test_latency(n);
  }
  test_up(b) {
    return this.a.$test_up(b);
  }
  test_down(size) {
    return this.a.$test_down(size);
  }
};
function reviveResolveAuthorityResult(result) {
  if (result.type === "ok") {
    return {
      type: "ok",
      value: {
        ...result.value,
        authority: reviveResolvedAuthority(result.value.authority)
      }
    };
  } else {
    return result;
  }
}
function reviveResolvedAuthority(resolvedAuthority) {
  return {
    ...resolvedAuthority,
    connectTo: reviveConnection(resolvedAuthority.connectTo)
  };
}
function reviveConnection(connection) {
  if (connection.type === 0) {
    return new $dC(connection.host, connection.port);
  }
  return new $cC(connection.id);
}

// out-build/vs/workbench/api/browser/mainThreadFileSystem.js
var $mQb_1;
var $mQb = $mQb_1 = class $mQb2 {
  constructor(extHostContext, d) {
    this.d = d;
    this.b = new $_c();
    this.c = new $2c();
    this.a = extHostContext.getProxy($yT.ExtHostFileSystem);
    const infoProxy = extHostContext.getProxy($yT.ExtHostFileSystemInfo);
    for (const entry of d.listCapabilities()) {
      infoProxy.$acceptProviderInfos(URI.from({ scheme: entry.scheme, path: "/dummy" }), entry.capabilities);
    }
    this.c.add(d.onDidChangeFileSystemProviderRegistrations((e) => infoProxy.$acceptProviderInfos(URI.from({ scheme: e.scheme, path: "/dummy" }), e.provider?.capabilities ?? null)));
    this.c.add(d.onDidChangeFileSystemProviderCapabilities((e) => infoProxy.$acceptProviderInfos(URI.from({ scheme: e.scheme, path: "/dummy" }), e.provider.capabilities)));
  }
  dispose() {
    this.c.dispose();
    this.b.dispose();
  }
  async $registerFileSystemProvider(handle2, scheme, capabilities, readonlyMessage) {
    this.b.set(handle2, new RemoteFileSystemProvider(this.d, scheme, capabilities, readonlyMessage, handle2, this.a));
  }
  $unregisterProvider(handle2) {
    this.b.deleteAndDispose(handle2);
  }
  $onFileSystemChange(handle2, changes) {
    const fileProvider = this.b.get(handle2);
    if (!fileProvider) {
      throw new Error("Unknown file provider");
    }
    fileProvider.$onFileSystemChange(changes);
  }
  // --- consumer fs, vscode.workspace.fs
  $stat(uri) {
    return this.d.stat(URI.revive(uri)).then((stat) => {
      return {
        ctime: stat.ctime,
        mtime: stat.mtime,
        size: stat.size,
        permissions: stat.readonly ? FilePermission.Readonly : void 0,
        type: $mQb_1.f(stat)
      };
    }).catch($mQb_1.g);
  }
  $readdir(uri) {
    return this.d.resolve(URI.revive(uri), { resolveMetadata: false }).then((stat) => {
      if (!stat.isDirectory) {
        const err = new Error(stat.name);
        err.name = FileSystemProviderErrorCode.FileNotADirectory;
        throw err;
      }
      return !stat.children ? [] : stat.children.map((child) => [child.name, $mQb_1.f(child)]);
    }).catch($mQb_1.g);
  }
  static f(stat) {
    let res = 0;
    if (stat.isFile) {
      res += FileType.File;
    } else if (stat.isDirectory) {
      res += FileType.Directory;
    }
    if (stat.isSymbolicLink) {
      res += FileType.SymbolicLink;
    }
    return res;
  }
  $readFile(uri) {
    return this.d.readFile(URI.revive(uri)).then((file) => file.value).catch($mQb_1.g);
  }
  $writeFile(uri, content) {
    return this.d.writeFile(URI.revive(uri), content).then(() => void 0).catch($mQb_1.g);
  }
  $rename(source, target, opts) {
    return this.d.move(URI.revive(source), URI.revive(target), opts.overwrite).then(() => void 0).catch($mQb_1.g);
  }
  $copy(source, target, opts) {
    return this.d.copy(URI.revive(source), URI.revive(target), opts.overwrite).then(() => void 0).catch($mQb_1.g);
  }
  $mkdir(uri) {
    return this.d.createFolder(URI.revive(uri)).then(() => void 0).catch($mQb_1.g);
  }
  $delete(uri, opts) {
    return this.d.del(URI.revive(uri), opts).catch($mQb_1.g);
  }
  static g(err) {
    if (err instanceof $Fm) {
      switch (err.fileOperationResult) {
        case 1:
          err.name = FileSystemProviderErrorCode.FileNotFound;
          break;
        case 0:
          err.name = FileSystemProviderErrorCode.FileIsADirectory;
          break;
        case 6:
          err.name = FileSystemProviderErrorCode.NoPermissions;
          break;
        case 4:
          err.name = FileSystemProviderErrorCode.FileExists;
          break;
      }
    } else if (err instanceof Error) {
      const code = $Am(err);
      if (code !== FileSystemProviderErrorCode.Unknown) {
        err.name = code;
      }
    }
    throw err;
  }
  $ensureActivation(scheme) {
    return this.d.activateProvider(scheme);
  }
};
$mQb = $mQb_1 = __decorate([
  $frb($xT.MainThreadFileSystem),
  __param(1, $km)
], $mQb);
var RemoteFileSystemProvider = class _RemoteFileSystemProvider {
  constructor(fileService, scheme, capabilities, readOnlyMessage, c, d) {
    this.readOnlyMessage = readOnlyMessage;
    this.c = c;
    this.d = d;
    this.a = new $ze();
    this.onDidChangeFile = this.a.event;
    this.onDidChangeCapabilities = Event2.None;
    this.capabilities = capabilities;
    this.b = fileService.registerProvider(scheme, this);
  }
  dispose() {
    this.b.dispose();
    this.a.dispose();
  }
  watch(resource, opts) {
    const session = Math.random();
    this.d.$watch(this.c, session, resource, opts);
    return $1c(() => {
      this.d.$unwatch(this.c, session);
    });
  }
  $onFileSystemChange(changes) {
    this.a.fire(changes.map(_RemoteFileSystemProvider.f));
  }
  static f(dto) {
    return { resource: URI.revive(dto.resource), type: dto.type };
  }
  // --- forwarding calls
  stat(resource) {
    return this.d.$stat(this.c, resource).then(void 0, (err) => {
      throw err;
    });
  }
  readFile(resource) {
    return this.d.$readFile(this.c, resource).then((buffer) => buffer.buffer);
  }
  writeFile(resource, content, opts) {
    return this.d.$writeFile(this.c, resource, $Ci.wrap(content), opts);
  }
  delete(resource, opts) {
    return this.d.$delete(this.c, resource, opts);
  }
  mkdir(resource) {
    return this.d.$mkdir(this.c, resource);
  }
  readdir(resource) {
    return this.d.$readdir(this.c, resource);
  }
  rename(resource, target, opts) {
    return this.d.$rename(this.c, resource, target, opts);
  }
  copy(resource, target, opts) {
    return this.d.$copy(this.c, resource, target, opts);
  }
  open(resource, opts) {
    return this.d.$open(this.c, resource, opts);
  }
  close(fd) {
    return this.d.$close(this.c, fd);
  }
  read(fd, pos, data, offset, length) {
    return this.d.$read(this.c, fd, pos, length).then((readData) => {
      data.set(readData.buffer, offset);
      return readData.byteLength;
    });
  }
  write(fd, pos, data, offset, length) {
    return this.d.$write(this.c, fd, pos, $Ci.wrap(data).slice(offset, offset + length));
  }
};

// out-build/vs/workbench/api/browser/mainThreadFileSystemEventService.js
var $nQb_1;
var $nQb = class $nQb2 {
  static {
    $nQb_1 = this;
  }
  static {
    this.MementoKeyAdditionalEdits = `file.particpants.additionalEdits`;
  }
  constructor(extHostContext, d, workingCopyFileService, bulkEditService, progressService, dialogService, storageService, logService, envService, uriIdentService, f) {
    this.d = d;
    this.f = f;
    this.b = new $2c();
    this.c = new $_c();
    this.a = extHostContext.getProxy($yT.ExtHostFileSystemEventService);
    this.b.add(d.onDidFilesChange((event) => {
      this.a.$onFileEvent({
        created: event.rawAdded,
        changed: event.rawUpdated,
        deleted: event.rawDeleted
      });
    }));
    const that = this;
    const fileOperationParticipant = new class {
      async participate(files, operation, undoInfo, timeout, token) {
        if (undoInfo?.isUndoing) {
          return;
        }
        const cts = new $ad(token);
        const timer = setTimeout(() => cts.cancel(), timeout);
        const data = await progressService.withProgress({
          location: 15,
          title: this.a(operation),
          cancellable: true,
          delay: Math.min(timeout / 2, 3e3)
        }, () => {
          const onWillEvent = that.a.$onWillRunFileOperation(operation, files, timeout, cts.token);
          return $Ih(onWillEvent, cts.token);
        }, () => {
          cts.cancel();
        }).finally(() => {
          cts.dispose();
          clearTimeout(timer);
        });
        if (!data || data.edit.edits.length === 0) {
          return;
        }
        const needsConfirmation = data.edit.edits.some((edit3) => edit3.metadata?.needsConfirmation);
        let showPreview = storageService.getBoolean(
          $nQb_1.MementoKeyAdditionalEdits,
          0
          /* StorageScope.PROFILE */
        );
        if (envService.extensionTestsLocationURI) {
          showPreview = false;
        }
        if (showPreview === void 0) {
          let message;
          if (data.extensionNames.length === 1) {
            if (operation === 0) {
              message = localize(2595, null, data.extensionNames[0]);
            } else if (operation === 3) {
              message = localize(2596, null, data.extensionNames[0]);
            } else if (operation === 2) {
              message = localize(2597, null, data.extensionNames[0]);
            } else {
              message = localize(2598, null, data.extensionNames[0]);
            }
          } else {
            if (operation === 0) {
              message = localize(2599, null, data.extensionNames.length);
            } else if (operation === 3) {
              message = localize(2600, null, data.extensionNames.length);
            } else if (operation === 2) {
              message = localize(2601, null, data.extensionNames.length);
            } else {
              message = localize(2602, null, data.extensionNames.length);
            }
          }
          if (needsConfirmation) {
            const { confirmed } = await dialogService.confirm({
              type: severity_default.Info,
              message,
              primaryButton: localize(2603, null),
              cancelButton: localize(2604, null)
            });
            showPreview = true;
            if (!confirmed) {
              return;
            }
          } else {
            let Choice;
            (function(Choice2) {
              Choice2[Choice2["OK"] = 0] = "OK";
              Choice2[Choice2["Preview"] = 1] = "Preview";
              Choice2[Choice2["Cancel"] = 2] = "Cancel";
            })(Choice || (Choice = {}));
            const { result, checkboxChecked } = await dialogService.prompt({
              type: severity_default.Info,
              message,
              buttons: [
                {
                  label: localize(2605, null),
                  run: () => Choice.OK
                },
                {
                  label: localize(2606, null),
                  run: () => Choice.Preview
                }
              ],
              cancelButton: {
                label: localize(2607, null),
                run: () => Choice.Cancel
              },
              checkbox: { label: localize(2608, null) }
            });
            if (result === Choice.Cancel) {
              return;
            }
            showPreview = result === Choice.Preview;
            if (checkboxChecked) {
              storageService.store(
                $nQb_1.MementoKeyAdditionalEdits,
                showPreview,
                0,
                0
                /* StorageTarget.USER */
              );
            }
          }
        }
        logService.info("[onWill-handler] applying additional workspace edit from extensions", data.extensionNames);
        await bulkEditService.apply($Wrb(data.edit, uriIdentService), { undoRedoGroupId: undoInfo?.undoRedoGroupId, showPreview });
      }
      a(operation) {
        switch (operation) {
          case 0:
            return localize(2609, null);
          case 2:
            return localize(2610, null);
          case 3:
            return localize(2611, null);
          case 1:
            return localize(2612, null);
          case 4:
            return localize(2613, null);
        }
      }
    }();
    this.b.add(workingCopyFileService.addFileOperationParticipant(fileOperationParticipant));
    this.b.add(workingCopyFileService.onDidRunWorkingCopyFileOperation((e) => this.a.$onDidRunFileOperation(e.operation, e.files)));
  }
  async $watch(extensionId, session, resource, unvalidatedOpts, correlate) {
    const uri = URI.revive(resource);
    const opts = {
      ...unvalidatedOpts
    };
    if (opts.recursive) {
      try {
        const stat = await this.d.stat(uri);
        if (!stat.isDirectory) {
          opts.recursive = false;
        }
      } catch (error) {
      }
    }
    if (correlate) {
      this.f.trace(`MainThreadFileSystemEventService#$watch(): request to start watching correlated (extension: ${extensionId}, path: ${uri.toString(true)}, recursive: ${opts.recursive}, session: ${session}, excludes: ${JSON.stringify(opts.excludes)}, includes: ${JSON.stringify(opts.includes)})`);
      const watcherDisposables = new $2c();
      const subscription = watcherDisposables.add(this.d.createWatcher(uri, opts));
      watcherDisposables.add(subscription.onDidChange((event) => {
        this.a.$onFileEvent({
          session,
          created: event.rawAdded,
          changed: event.rawUpdated,
          deleted: event.rawDeleted
        });
      }));
      this.c.set(session, watcherDisposables);
    } else {
      this.f.trace(`MainThreadFileSystemEventService#$watch(): request to start watching uncorrelated (extension: ${extensionId}, path: ${uri.toString(true)}, recursive: ${opts.recursive}, session: ${session}, excludes: ${JSON.stringify(opts.excludes)}, includes: ${JSON.stringify(opts.includes)})`);
      const subscription = this.d.watch(uri, opts);
      this.c.set(session, subscription);
    }
  }
  $unwatch(session) {
    if (this.c.has(session)) {
      this.f.trace(`MainThreadFileSystemEventService#$unwatch(): request to stop watching (session: ${session})`);
      this.c.deleteAndDispose(session);
    }
  }
  dispose() {
    this.b.dispose();
    this.c.dispose();
  }
};
$nQb = $nQb_1 = __decorate([
  $frb($xT.MainThreadFileSystemEventService),
  __param(1, $km),
  __param(2, $aK),
  __param(3, $H_),
  __param(4, $TJ),
  __param(5, $Yv),
  __param(6, $jv),
  __param(7, $wn),
  __param(8, $Xk),
  __param(9, $vl),
  __param(10, $wn)
], $nQb);
$hJ(class ResetMemento extends $gJ {
  constructor() {
    super({
      id: "files.participants.resetChoice",
      title: {
        value: localize(2614, null),
        original: `Reset choice for 'File operation needs preview'`
      },
      f1: true
    });
  }
  run(accessor) {
    accessor.get($jv).remove(
      $nQb.MementoKeyAdditionalEdits,
      0
      /* StorageScope.PROFILE */
    );
  }
});

// out-build/vs/base/common/prefixTree.js
var unset = Symbol("unset");
var $lQ = class {
  constructor() {
    this.root = new Node3();
    this.a = 0;
  }
  /** Tree size, not including the root. */
  get size() {
    return this.a;
  }
  /** Gets the top-level nodes of the tree */
  get nodes() {
    return this.root.children?.values() || Iterable.empty();
  }
  /** Gets the top-level nodes of the tree */
  get entries() {
    return this.root.children?.entries() || Iterable.empty();
  }
  /**
   * Inserts a new value in the prefix tree.
   * @param onNode - called for each node as we descend to the insertion point,
   * including the insertion point itself.
   */
  insert(key2, value, onNode) {
    this.c(key2, (n) => n._value = value, onNode);
  }
  /** Mutates a value in the prefix tree. */
  mutate(key2, mutate) {
    this.c(key2, (n) => n._value = mutate(n._value === unset ? void 0 : n._value));
  }
  /** Mutates nodes along the path in the prefix tree. */
  mutatePath(key2, mutate) {
    this.c(key2, () => {
    }, (n) => mutate(n));
  }
  /** Deletes a node from the prefix tree, returning the value it contained. */
  delete(key2) {
    const path = this.b(key2);
    if (!path) {
      return;
    }
    let i2 = path.length - 1;
    const value = path[i2].node._value;
    if (value === unset) {
      return;
    }
    this.a--;
    path[i2].node._value = unset;
    for (; i2 > 0; i2--) {
      const { node, part } = path[i2];
      if (node.children?.size || node._value !== unset) {
        break;
      }
      path[i2 - 1].node.children.delete(part);
    }
    return value;
  }
  /** Deletes a subtree from the prefix tree, returning the values they contained. */
  *deleteRecursive(key2) {
    const path = this.b(key2);
    if (!path) {
      return;
    }
    const subtree = path[path.length - 1].node;
    for (let i2 = path.length - 1; i2 > 0; i2--) {
      const parent = path[i2 - 1];
      parent.node.children.delete(path[i2].part);
      if (parent.node.children.size > 0 || parent.node._value !== unset) {
        break;
      }
    }
    for (const node of bfsIterate(subtree)) {
      if (node._value !== unset) {
        this.a--;
        yield node._value;
      }
    }
    if (subtree === this.root) {
      this.root._value = unset;
      this.root.children = void 0;
    }
  }
  /** Gets a value from the tree. */
  find(key2) {
    let node = this.root;
    for (const segment of key2) {
      const next = node.children?.get(segment);
      if (!next) {
        return void 0;
      }
      node = next;
    }
    return node._value === unset ? void 0 : node._value;
  }
  /** Gets whether the tree has the key, or a parent of the key, already inserted. */
  hasKeyOrParent(key2) {
    let node = this.root;
    for (const segment of key2) {
      const next = node.children?.get(segment);
      if (!next) {
        return false;
      }
      if (next._value !== unset) {
        return true;
      }
      node = next;
    }
    return false;
  }
  /** Gets whether the tree has the given key or any children. */
  hasKeyOrChildren(key2) {
    let node = this.root;
    for (const segment of key2) {
      const next = node.children?.get(segment);
      if (!next) {
        return false;
      }
      node = next;
    }
    return true;
  }
  /** Gets whether the tree has the given key. */
  hasKey(key2) {
    let node = this.root;
    for (const segment of key2) {
      const next = node.children?.get(segment);
      if (!next) {
        return false;
      }
      node = next;
    }
    return node._value !== unset;
  }
  b(key2) {
    const path = [{ part: "", node: this.root }];
    let i2 = 0;
    for (const part of key2) {
      const node = path[i2].node.children?.get(part);
      if (!node) {
        return;
      }
      path.push({ part, node });
      i2++;
    }
    return path;
  }
  c(key2, fn, onDescend) {
    let node = this.root;
    for (const part of key2) {
      if (!node.children) {
        const next = new Node3();
        node.children = /* @__PURE__ */ new Map([[part, next]]);
        node = next;
      } else if (!node.children.has(part)) {
        const next = new Node3();
        node.children.set(part, next);
        node = next;
      } else {
        node = node.children.get(part);
      }
      onDescend?.(node);
    }
    const sizeBefore = node._value === unset ? 0 : 1;
    fn(node);
    const sizeAfter = node._value === unset ? 0 : 1;
    this.a += sizeAfter - sizeBefore;
  }
  /** Returns an iterable of the tree values in no defined order. */
  *values() {
    for (const { _value } of bfsIterate(this.root)) {
      if (_value !== unset) {
        yield _value;
      }
    }
  }
};
function* bfsIterate(root) {
  const stack = [root];
  while (stack.length > 0) {
    const node = stack.pop();
    yield node;
    if (node.children) {
      for (const child of node.children.values()) {
        stack.push(child);
      }
    }
  }
}
var Node3 = class {
  constructor() {
    this._value = unset;
  }
  get value() {
    return this._value === unset ? void 0 : this._value;
  }
  set value(value) {
    this._value = value === void 0 ? unset : value;
  }
};

// out-build/vs/workbench/contrib/testing/common/testId.js
var TestIdPathParts;
(function(TestIdPathParts2) {
  TestIdPathParts2["Delimiter"] = "\0";
})(TestIdPathParts || (TestIdPathParts = {}));
var TestPosition;
(function(TestPosition2) {
  TestPosition2[TestPosition2["IsSame"] = 0] = "IsSame";
  TestPosition2[TestPosition2["Disconnected"] = 1] = "Disconnected";
  TestPosition2[TestPosition2["IsChild"] = 2] = "IsChild";
  TestPosition2[TestPosition2["IsParent"] = 3] = "IsParent";
})(TestPosition || (TestPosition = {}));
var $mQ = class _$mQ {
  /**
   * Creates a test ID from an ext host test item.
   */
  static fromExtHostTestItem(item, rootId, parent = item.parent) {
    if (item._isRoot) {
      return new _$mQ([rootId]);
    }
    const path = [item.id];
    for (let i2 = parent; i2 && i2.id !== rootId; i2 = i2.parent) {
      path.push(i2.id);
    }
    path.push(rootId);
    return new _$mQ(path.reverse());
  }
  /**
   * Cheaply ets whether the ID refers to the root .
   */
  static isRoot(idString) {
    return !idString.includes(
      "\0"
      /* TestIdPathParts.Delimiter */
    );
  }
  /**
   * Cheaply gets whether the ID refers to the root .
   */
  static root(idString) {
    const idx = idString.indexOf(
      "\0"
      /* TestIdPathParts.Delimiter */
    );
    return idx === -1 ? idString : idString.slice(0, idx);
  }
  /**
   * Creates a test ID from a serialized TestId instance.
   */
  static fromString(idString) {
    return new _$mQ(idString.split(
      "\0"
      /* TestIdPathParts.Delimiter */
    ));
  }
  /**
   * Gets the ID resulting from adding b to the base ID.
   */
  static join(base, b) {
    return new _$mQ([...base.path, b]);
  }
  /**
   * Gets the string ID resulting from adding b to the base ID.
   */
  static joinToString(base, b) {
    return base.toString() + "\0" + b;
  }
  /**
   * Cheaply gets the parent ID of a test identified with the string.
   */
  static parentId(idString) {
    const idx = idString.lastIndexOf(
      "\0"
      /* TestIdPathParts.Delimiter */
    );
    return idx === -1 ? void 0 : idString.slice(0, idx);
  }
  /**
   * Cheaply gets the local ID of a test identified with the string.
   */
  static localId(idString) {
    const idx = idString.lastIndexOf(
      "\0"
      /* TestIdPathParts.Delimiter */
    );
    return idx === -1 ? idString : idString.slice(idx + "\0".length);
  }
  /**
   * Gets whether maybeChild is a child of maybeParent.
   * todo@connor4312: review usages of this to see if using the WellDefinedPrefixTree is better
   */
  static isChild(maybeParent, maybeChild) {
    return maybeChild[maybeParent.length] === "\0" && maybeChild.startsWith(maybeParent);
  }
  /**
   * Compares the position of the two ID strings.
   * todo@connor4312: review usages of this to see if using the WellDefinedPrefixTree is better
   */
  static compare(a, b) {
    if (a === b) {
      return 0;
    }
    if (_$mQ.isChild(a, b)) {
      return 2;
    }
    if (_$mQ.isChild(b, a)) {
      return 3;
    }
    return 1;
  }
  static getLengthOfCommonPrefix(length, getId2) {
    if (length === 0) {
      return 0;
    }
    let commonPrefix = 0;
    while (commonPrefix < length - 1) {
      for (let i2 = 1; i2 < length; i2++) {
        const a = getId2(i2 - 1);
        const b = getId2(i2);
        if (a.path[commonPrefix] !== b.path[commonPrefix]) {
          return commonPrefix;
        }
      }
      commonPrefix++;
    }
    return commonPrefix;
  }
  constructor(path, d = path.length) {
    this.path = path;
    this.d = d;
    if (path.length === 0 || d < 1) {
      throw new Error("cannot create test with empty path");
    }
  }
  /**
   * Gets the ID of the parent test.
   */
  get rootId() {
    return new _$mQ(this.path, 1);
  }
  /**
   * Gets the ID of the parent test.
   */
  get parentId() {
    return this.d > 1 ? new _$mQ(this.path, this.d - 1) : void 0;
  }
  /**
   * Gets the local ID of the current full test ID.
   */
  get localId() {
    return this.path[this.d - 1];
  }
  /**
   * Gets whether this ID refers to the root.
   */
  get controllerId() {
    return this.path[0];
  }
  /**
   * Gets whether this ID refers to the root.
   */
  get isRoot() {
    return this.d === 1;
  }
  /**
   * Returns an iterable that yields IDs of all parent items down to and
   * including the current item.
   */
  *idsFromRoot() {
    for (let i2 = 1; i2 <= this.d; i2++) {
      yield new _$mQ(this.path, i2);
    }
  }
  /**
   * Returns an iterable that yields IDs of the current item up to the root
   * item.
   */
  *idsToRoot() {
    for (let i2 = this.d; i2 > 0; i2--) {
      yield new _$mQ(this.path, i2);
    }
  }
  /**
   * Compares the other test ID with this one.
   */
  compare(other) {
    if (typeof other === "string") {
      return _$mQ.compare(this.toString(), other);
    }
    for (let i2 = 0; i2 < other.d && i2 < this.d; i2++) {
      if (other.path[i2] !== this.path[i2]) {
        return 1;
      }
    }
    if (other.d > this.d) {
      return 2;
    }
    if (other.d < this.d) {
      return 3;
    }
    return 0;
  }
  /**
   * Serializes the ID.
   */
  toJSON() {
    return this.toString();
  }
  /**
   * Serializes the ID to a string.
   */
  toString() {
    if (!this.c) {
      this.c = this.path[0];
      for (let i2 = 1; i2 < this.d; i2++) {
        this.c += "\0";
        this.c += this.path[i2];
      }
    }
    return this.c;
  }
};

// out-build/vs/workbench/contrib/testing/common/testTypes.js
var TestResultState2;
(function(TestResultState3) {
  TestResultState3[TestResultState3["Unset"] = 0] = "Unset";
  TestResultState3[TestResultState3["Queued"] = 1] = "Queued";
  TestResultState3[TestResultState3["Running"] = 2] = "Running";
  TestResultState3[TestResultState3["Passed"] = 3] = "Passed";
  TestResultState3[TestResultState3["Failed"] = 4] = "Failed";
  TestResultState3[TestResultState3["Skipped"] = 5] = "Skipped";
  TestResultState3[TestResultState3["Errored"] = 6] = "Errored";
})(TestResultState2 || (TestResultState2 = {}));
var $nQ = {
  [
    0
    /* TestResultState.Unset */
  ]: "unset",
  [
    1
    /* TestResultState.Queued */
  ]: "queued",
  [
    2
    /* TestResultState.Running */
  ]: "running",
  [
    3
    /* TestResultState.Passed */
  ]: "passed",
  [
    4
    /* TestResultState.Failed */
  ]: "failed",
  [
    5
    /* TestResultState.Skipped */
  ]: "skipped",
  [
    6
    /* TestResultState.Errored */
  ]: "errored"
};
var ExtTestRunProfileKind;
(function(ExtTestRunProfileKind2) {
  ExtTestRunProfileKind2[ExtTestRunProfileKind2["Run"] = 1] = "Run";
  ExtTestRunProfileKind2[ExtTestRunProfileKind2["Debug"] = 2] = "Debug";
  ExtTestRunProfileKind2[ExtTestRunProfileKind2["Coverage"] = 3] = "Coverage";
})(ExtTestRunProfileKind || (ExtTestRunProfileKind = {}));
var TestControllerCapability;
(function(TestControllerCapability2) {
  TestControllerCapability2[TestControllerCapability2["Refresh"] = 2] = "Refresh";
  TestControllerCapability2[TestControllerCapability2["CodeRelatedToTest"] = 4] = "CodeRelatedToTest";
  TestControllerCapability2[TestControllerCapability2["TestRelatedToCode"] = 8] = "TestRelatedToCode";
})(TestControllerCapability || (TestControllerCapability = {}));
var TestRunProfileBitset;
(function(TestRunProfileBitset2) {
  TestRunProfileBitset2[TestRunProfileBitset2["Run"] = 2] = "Run";
  TestRunProfileBitset2[TestRunProfileBitset2["Debug"] = 4] = "Debug";
  TestRunProfileBitset2[TestRunProfileBitset2["Coverage"] = 8] = "Coverage";
  TestRunProfileBitset2[TestRunProfileBitset2["HasNonDefaultProfile"] = 16] = "HasNonDefaultProfile";
  TestRunProfileBitset2[TestRunProfileBitset2["HasConfigurable"] = 32] = "HasConfigurable";
  TestRunProfileBitset2[TestRunProfileBitset2["SupportsContinuousRun"] = 64] = "SupportsContinuousRun";
})(TestRunProfileBitset || (TestRunProfileBitset = {}));
var $oQ = {
  [
    2
    /* TestRunProfileBitset.Run */
  ]: localize(11359, null),
  [
    4
    /* TestRunProfileBitset.Debug */
  ]: localize(11360, null),
  [
    8
    /* TestRunProfileBitset.Coverage */
  ]: localize(11361, null)
};
var $pQ = [
  2,
  4,
  8,
  16,
  32,
  64
];
var IRichLocation;
(function(IRichLocation2) {
  IRichLocation2.serialize = (location3) => ({
    range: location3.range.toJSON(),
    uri: location3.uri.toJSON()
  });
  IRichLocation2.deserialize = (uriIdentity, location3) => ({
    range: $9C.lift(location3.range),
    uri: uriIdentity.asCanonicalUri(URI.revive(location3.uri))
  });
})(IRichLocation || (IRichLocation = {}));
var TestMessageType;
(function(TestMessageType2) {
  TestMessageType2[TestMessageType2["Error"] = 0] = "Error";
  TestMessageType2[TestMessageType2["Output"] = 1] = "Output";
})(TestMessageType || (TestMessageType = {}));
var ITestMessageStackFrame;
(function(ITestMessageStackFrame2) {
  ITestMessageStackFrame2.serialize = (stack) => ({
    label: stack.label,
    uri: stack.uri?.toJSON(),
    position: stack.position?.toJSON()
  });
  ITestMessageStackFrame2.deserialize = (uriIdentity, stack) => ({
    label: stack.label,
    uri: stack.uri ? uriIdentity.asCanonicalUri(URI.revive(stack.uri)) : void 0,
    position: stack.position ? $8C.lift(stack.position) : void 0
  });
})(ITestMessageStackFrame || (ITestMessageStackFrame = {}));
var ITestErrorMessage;
(function(ITestErrorMessage2) {
  ITestErrorMessage2.serialize = (message) => ({
    message: message.message,
    type: 0,
    expected: message.expected,
    actual: message.actual,
    contextValue: message.contextValue,
    location: message.location && IRichLocation.serialize(message.location),
    stackTrace: message.stackTrace?.map(ITestMessageStackFrame.serialize)
  });
  ITestErrorMessage2.deserialize = (uriIdentity, message) => ({
    message: message.message,
    type: 0,
    expected: message.expected,
    actual: message.actual,
    contextValue: message.contextValue,
    location: message.location && IRichLocation.deserialize(uriIdentity, message.location),
    stackTrace: message.stackTrace && message.stackTrace.map((s) => ITestMessageStackFrame.deserialize(uriIdentity, s))
  });
})(ITestErrorMessage || (ITestErrorMessage = {}));
var $rQ = (marker, start) => `${start ? "s" : "e"}${marker}`;
var ITestOutputMessage;
(function(ITestOutputMessage2) {
  ITestOutputMessage2.serialize = (message) => ({
    message: message.message,
    type: 1,
    offset: message.offset,
    length: message.length,
    location: message.location && IRichLocation.serialize(message.location)
  });
  ITestOutputMessage2.deserialize = (uriIdentity, message) => ({
    message: message.message,
    type: 1,
    offset: message.offset,
    length: message.length,
    location: message.location && IRichLocation.deserialize(uriIdentity, message.location)
  });
})(ITestOutputMessage || (ITestOutputMessage = {}));
var ITestMessage;
(function(ITestMessage2) {
  ITestMessage2.serialize = (message) => message.type === 0 ? ITestErrorMessage.serialize(message) : ITestOutputMessage.serialize(message);
  ITestMessage2.deserialize = (uriIdentity, message) => message.type === 0 ? ITestErrorMessage.deserialize(uriIdentity, message) : ITestOutputMessage.deserialize(uriIdentity, message);
  ITestMessage2.isDiffable = (message) => message.type === 0 && message.actual !== void 0 && message.expected !== void 0;
})(ITestMessage || (ITestMessage = {}));
var ITestTaskState;
(function(ITestTaskState2) {
  ITestTaskState2.serializeWithoutMessages = (state) => ({
    state: state.state,
    duration: state.duration,
    messages: []
  });
  ITestTaskState2.serialize = (state) => ({
    state: state.state,
    duration: state.duration,
    messages: state.messages.map(ITestMessage.serialize)
  });
  ITestTaskState2.deserialize = (uriIdentity, state) => ({
    state: state.state,
    duration: state.duration,
    messages: state.messages.map((m) => ITestMessage.deserialize(uriIdentity, m))
  });
})(ITestTaskState || (ITestTaskState = {}));
var testTagDelimiter = "\0";
var $sQ = (ctrlId, tagId) => ctrlId + testTagDelimiter + tagId;
var $tQ = (namespaced) => {
  const index = namespaced.indexOf(testTagDelimiter);
  return { ctrlId: namespaced.slice(0, index), tagId: namespaced.slice(index + 1) };
};
var ITestItem;
(function(ITestItem2) {
  ITestItem2.serialize = (item) => ({
    extId: item.extId,
    label: item.label,
    tags: item.tags,
    busy: item.busy,
    children: void 0,
    uri: item.uri?.toJSON(),
    range: item.range?.toJSON() || null,
    description: item.description,
    error: item.error,
    sortText: item.sortText
  });
  ITestItem2.deserialize = (uriIdentity, serialized) => ({
    extId: serialized.extId,
    label: serialized.label,
    tags: serialized.tags,
    busy: serialized.busy,
    children: void 0,
    uri: serialized.uri ? uriIdentity.asCanonicalUri(URI.revive(serialized.uri)) : void 0,
    range: serialized.range ? $9C.lift(serialized.range) : null,
    description: serialized.description,
    error: serialized.error,
    sortText: serialized.sortText
  });
})(ITestItem || (ITestItem = {}));
var TestItemExpandState;
(function(TestItemExpandState2) {
  TestItemExpandState2[TestItemExpandState2["NotExpandable"] = 0] = "NotExpandable";
  TestItemExpandState2[TestItemExpandState2["Expandable"] = 1] = "Expandable";
  TestItemExpandState2[TestItemExpandState2["BusyExpanding"] = 2] = "BusyExpanding";
  TestItemExpandState2[TestItemExpandState2["Expanded"] = 3] = "Expanded";
})(TestItemExpandState || (TestItemExpandState = {}));
var InternalTestItem;
(function(InternalTestItem2) {
  InternalTestItem2.serialize = (item) => ({
    expand: item.expand,
    item: ITestItem.serialize(item.item)
  });
  InternalTestItem2.deserialize = (uriIdentity, serialized) => ({
    // the `controllerId` is derived from the test.item.extId. It's redundant
    // in the non-serialized InternalTestItem too, but there just because it's
    // checked against in many hot paths.
    controllerId: $mQ.root(serialized.item.extId),
    expand: serialized.expand,
    item: ITestItem.deserialize(uriIdentity, serialized.item)
  });
})(InternalTestItem || (InternalTestItem = {}));
var ITestItemUpdate;
(function(ITestItemUpdate2) {
  ITestItemUpdate2.serialize = (u) => {
    let item;
    if (u.item) {
      item = {};
      if (u.item.label !== void 0) {
        item.label = u.item.label;
      }
      if (u.item.tags !== void 0) {
        item.tags = u.item.tags;
      }
      if (u.item.busy !== void 0) {
        item.busy = u.item.busy;
      }
      if (u.item.uri !== void 0) {
        item.uri = u.item.uri?.toJSON();
      }
      if (u.item.range !== void 0) {
        item.range = u.item.range?.toJSON();
      }
      if (u.item.description !== void 0) {
        item.description = u.item.description;
      }
      if (u.item.error !== void 0) {
        item.error = u.item.error;
      }
      if (u.item.sortText !== void 0) {
        item.sortText = u.item.sortText;
      }
    }
    return { extId: u.extId, expand: u.expand, item };
  };
  ITestItemUpdate2.deserialize = (u) => {
    let item;
    if (u.item) {
      item = {};
      if (u.item.label !== void 0) {
        item.label = u.item.label;
      }
      if (u.item.tags !== void 0) {
        item.tags = u.item.tags;
      }
      if (u.item.busy !== void 0) {
        item.busy = u.item.busy;
      }
      if (u.item.range !== void 0) {
        item.range = u.item.range ? $9C.lift(u.item.range) : null;
      }
      if (u.item.description !== void 0) {
        item.description = u.item.description;
      }
      if (u.item.error !== void 0) {
        item.error = u.item.error;
      }
      if (u.item.sortText !== void 0) {
        item.sortText = u.item.sortText;
      }
    }
    return { extId: u.extId, expand: u.expand, item };
  };
})(ITestItemUpdate || (ITestItemUpdate = {}));
var $uQ = (internal, patch2) => {
  if (patch2.expand !== void 0) {
    internal.expand = patch2.expand;
  }
  if (patch2.item !== void 0) {
    internal.item = internal.item ? Object.assign(internal.item, patch2.item) : patch2.item;
  }
};
var TestResultItem;
(function(TestResultItem2) {
  TestResultItem2.serializeWithoutMessages = (original) => ({
    ...InternalTestItem.serialize(original),
    ownComputedState: original.ownComputedState,
    computedState: original.computedState,
    tasks: original.tasks.map(ITestTaskState.serializeWithoutMessages)
  });
  TestResultItem2.serialize = (original) => ({
    ...InternalTestItem.serialize(original),
    ownComputedState: original.ownComputedState,
    computedState: original.computedState,
    tasks: original.tasks.map(ITestTaskState.serialize)
  });
  TestResultItem2.deserialize = (uriIdentity, serialized) => ({
    ...InternalTestItem.deserialize(uriIdentity, serialized),
    ownComputedState: serialized.ownComputedState,
    computedState: serialized.computedState,
    tasks: serialized.tasks.map((m) => ITestTaskState.deserialize(uriIdentity, m)),
    retired: true
  });
})(TestResultItem || (TestResultItem = {}));
var ICoverageCount;
(function(ICoverageCount2) {
  ICoverageCount2.empty = () => ({ covered: 0, total: 0 });
  ICoverageCount2.sum = (target, src) => {
    target.covered += src.covered;
    target.total += src.total;
  };
})(ICoverageCount || (ICoverageCount = {}));
var IFileCoverage;
(function(IFileCoverage2) {
  IFileCoverage2.serialize = (original) => ({
    id: original.id,
    statement: original.statement,
    branch: original.branch,
    declaration: original.declaration,
    testIds: original.testIds,
    uri: original.uri.toJSON()
  });
  IFileCoverage2.deserialize = (uriIdentity, serialized) => ({
    id: serialized.id,
    statement: serialized.statement,
    branch: serialized.branch,
    declaration: serialized.declaration,
    testIds: serialized.testIds,
    uri: uriIdentity.asCanonicalUri(URI.revive(serialized.uri))
  });
  IFileCoverage2.empty = (id2, uri) => ({
    id: id2,
    uri,
    statement: ICoverageCount.empty()
  });
})(IFileCoverage || (IFileCoverage = {}));
function serializeThingWithLocation(serialized) {
  return {
    ...serialized,
    location: serialized.location?.toJSON()
  };
}
function deserializeThingWithLocation(serialized) {
  serialized.location = serialized.location ? $8C.isIPosition(serialized.location) ? $8C.lift(serialized.location) : $9C.lift(serialized.location) : void 0;
  return serialized;
}
var DetailType;
(function(DetailType2) {
  DetailType2[DetailType2["Declaration"] = 0] = "Declaration";
  DetailType2[DetailType2["Statement"] = 1] = "Statement";
  DetailType2[DetailType2["Branch"] = 2] = "Branch";
})(DetailType || (DetailType = {}));
var CoverageDetails;
(function(CoverageDetails2) {
  CoverageDetails2.serialize = (original) => original.type === 0 ? IDeclarationCoverage.serialize(original) : IStatementCoverage.serialize(original);
  CoverageDetails2.deserialize = (serialized) => serialized.type === 0 ? IDeclarationCoverage.deserialize(serialized) : IStatementCoverage.deserialize(serialized);
})(CoverageDetails || (CoverageDetails = {}));
var IBranchCoverage;
(function(IBranchCoverage2) {
  IBranchCoverage2.serialize = serializeThingWithLocation;
  IBranchCoverage2.deserialize = deserializeThingWithLocation;
})(IBranchCoverage || (IBranchCoverage = {}));
var IDeclarationCoverage;
(function(IDeclarationCoverage2) {
  IDeclarationCoverage2.serialize = serializeThingWithLocation;
  IDeclarationCoverage2.deserialize = deserializeThingWithLocation;
})(IDeclarationCoverage || (IDeclarationCoverage = {}));
var IStatementCoverage;
(function(IStatementCoverage2) {
  IStatementCoverage2.serialize = (original) => ({
    ...serializeThingWithLocation(original),
    branches: original.branches?.map(IBranchCoverage.serialize)
  });
  IStatementCoverage2.deserialize = (serialized) => ({
    ...deserializeThingWithLocation(serialized),
    branches: serialized.branches?.map(IBranchCoverage.deserialize)
  });
})(IStatementCoverage || (IStatementCoverage = {}));
var TestDiffOpType;
(function(TestDiffOpType2) {
  TestDiffOpType2[TestDiffOpType2["Add"] = 0] = "Add";
  TestDiffOpType2[TestDiffOpType2["Update"] = 1] = "Update";
  TestDiffOpType2[TestDiffOpType2["DocumentSynced"] = 2] = "DocumentSynced";
  TestDiffOpType2[TestDiffOpType2["Remove"] = 3] = "Remove";
  TestDiffOpType2[TestDiffOpType2["IncrementPendingExtHosts"] = 4] = "IncrementPendingExtHosts";
  TestDiffOpType2[TestDiffOpType2["Retire"] = 5] = "Retire";
  TestDiffOpType2[TestDiffOpType2["AddTag"] = 6] = "AddTag";
  TestDiffOpType2[TestDiffOpType2["RemoveTag"] = 7] = "RemoveTag";
})(TestDiffOpType || (TestDiffOpType = {}));
var TestsDiffOp;
(function(TestsDiffOp2) {
  TestsDiffOp2.deserialize = (uriIdentity, u) => {
    if (u.op === 0) {
      return { op: u.op, item: InternalTestItem.deserialize(uriIdentity, u.item) };
    } else if (u.op === 1) {
      return { op: u.op, item: ITestItemUpdate.deserialize(u.item) };
    } else if (u.op === 2) {
      return { op: u.op, uri: uriIdentity.asCanonicalUri(URI.revive(u.uri)), docv: u.docv };
    } else {
      return u;
    }
  };
  TestsDiffOp2.serialize = (u) => {
    if (u.op === 0) {
      return { op: u.op, item: InternalTestItem.serialize(u.item) };
    } else if (u.op === 1) {
      return { op: u.op, item: ITestItemUpdate.serialize(u.item) };
    } else {
      return u;
    }
  };
})(TestsDiffOp || (TestsDiffOp = {}));
var $wQ = class {
  constructor(l) {
    this.l = l;
    this.f = /* @__PURE__ */ new Map();
    this.g = /* @__PURE__ */ new Map();
    this.h = /* @__PURE__ */ new Set();
    this.j = 0;
    this.k = 0;
    this.tags = this.f;
  }
  /**
   * Applies the diff to the collection.
   */
  apply(diff3) {
    const changes = this.x();
    for (const op of diff3) {
      switch (op.op) {
        case 0:
          this.p(InternalTestItem.deserialize(this.l, op.item), changes);
          break;
        case 1:
          this.q(ITestItemUpdate.deserialize(op.item), changes);
          break;
        case 3:
          this.v(op.itemId, changes);
          break;
        case 5:
          this.w(op.itemId);
          break;
        case 4:
          this.updatePendingRoots(op.amount);
          break;
        case 6:
          this.f.set(op.tag.id, op.tag);
          break;
        case 7:
          this.f.delete(op.id);
          break;
      }
    }
    changes.complete?.();
  }
  p(item, changes) {
    const parentId = $mQ.parentId(item.item.extId)?.toString();
    let created2;
    if (!parentId) {
      created2 = this.y(item);
      this.h.add(created2);
      this.g.set(item.item.extId, created2);
    } else if (this.g.has(parentId)) {
      const parent = this.g.get(parentId);
      parent.children.add(item.item.extId);
      created2 = this.y(item, parent);
      this.g.set(item.item.extId, created2);
    } else {
      console.error(`Test with unknown parent ID: ${JSON.stringify(item)}`);
      return;
    }
    changes.add?.(created2);
    if (item.expand === 2) {
      this.j++;
    }
    return created2;
  }
  q(patch2, changes) {
    const existing = this.g.get(patch2.extId);
    if (!existing) {
      return;
    }
    if (patch2.expand !== void 0) {
      if (existing.expand === 2) {
        this.j--;
      }
      if (patch2.expand === 2) {
        this.j++;
      }
    }
    $uQ(existing, patch2);
    changes.update?.(existing);
    return existing;
  }
  v(itemId, changes) {
    const toRemove = this.g.get(itemId);
    if (!toRemove) {
      return;
    }
    const parentId = $mQ.parentId(toRemove.item.extId)?.toString();
    if (parentId) {
      const parent = this.g.get(parentId);
      parent.children.delete(toRemove.item.extId);
    } else {
      this.h.delete(toRemove);
    }
    const queue = [[itemId]];
    while (queue.length) {
      for (const itemId2 of queue.pop()) {
        const existing = this.g.get(itemId2);
        if (existing) {
          queue.push(existing.children);
          this.g.delete(itemId2);
          changes.remove?.(existing, existing !== toRemove);
          if (existing.expand === 2) {
            this.j--;
          }
        }
      }
    }
  }
  /**
   * Called when the extension signals a test result should be retired.
   */
  w(testId) {
  }
  /**
   * Updates the number of test root sources who are yet to report. When
   * the total pending test roots reaches 0, the roots for all controllers
   * will exist in the collection.
   */
  updatePendingRoots(delta) {
    this.k += delta;
  }
  /**
   * Called before a diff is applied to create a new change collector.
   */
  x() {
    return {};
  }
};

// out-build/vs/workbench/contrib/testing/common/testItemCollection.js
var TestItemEventOp;
(function(TestItemEventOp2) {
  TestItemEventOp2[TestItemEventOp2["Upsert"] = 0] = "Upsert";
  TestItemEventOp2[TestItemEventOp2["SetTags"] = 1] = "SetTags";
  TestItemEventOp2[TestItemEventOp2["UpdateCanResolveChildren"] = 2] = "UpdateCanResolveChildren";
  TestItemEventOp2[TestItemEventOp2["RemoveChild"] = 3] = "RemoveChild";
  TestItemEventOp2[TestItemEventOp2["SetProp"] = 4] = "SetProp";
  TestItemEventOp2[TestItemEventOp2["Bulk"] = 5] = "Bulk";
  TestItemEventOp2[TestItemEventOp2["DocumentSynced"] = 6] = "DocumentSynced";
})(TestItemEventOp || (TestItemEventOp = {}));
var strictEqualComparator = (a, b) => a === b;
var diffableProps = {
  range: (a, b) => {
    if (a === b) {
      return true;
    }
    if (!a || !b) {
      return false;
    }
    return a.equalsRange(b);
  },
  busy: strictEqualComparator,
  label: strictEqualComparator,
  description: strictEqualComparator,
  error: strictEqualComparator,
  sortText: strictEqualComparator,
  tags: (a, b) => {
    if (a.length !== b.length) {
      return false;
    }
    if (a.some((t1) => !b.includes(t1))) {
      return false;
    }
    return true;
  }
};
var diffableEntries = Object.entries(diffableProps);
var $$V = class extends Error {
  constructor(id2) {
    super(`TestItem with ID "${id2}" is invalid. Make sure to create it from the createTestItem method.`);
  }
};

// out-build/vs/workbench/api/common/extHostTestingPrivateApi.js
var eventPrivateApis = /* @__PURE__ */ new WeakMap();
var $cW = (impl) => {
  const api = eventPrivateApis.get(impl);
  if (!api) {
    throw new $$V(impl?.id || "<unknown>");
  }
  return api;
};

// out-build/vs/workbench/api/common/extHostTypeConverters.js
var Selection;
(function(Selection2) {
  function to(selection) {
    const { selectionStartLineNumber, selectionStartColumn, positionLineNumber, positionColumn } = selection;
    const start = new $AT(selectionStartLineNumber - 1, selectionStartColumn - 1);
    const end = new $AT(positionLineNumber - 1, positionColumn - 1);
    return new $CT(start, end);
  }
  Selection2.to = to;
  function from(selection) {
    const { anchor, active } = selection;
    return {
      selectionStartLineNumber: anchor.line + 1,
      selectionStartColumn: anchor.character + 1,
      positionLineNumber: active.line + 1,
      positionColumn: active.character + 1
    };
  }
  Selection2.from = from;
})(Selection || (Selection = {}));
var Range4;
(function(Range5) {
  function from(range) {
    if (!range) {
      return void 0;
    }
    const { start, end } = range;
    return {
      startLineNumber: start.line + 1,
      startColumn: start.character + 1,
      endLineNumber: end.line + 1,
      endColumn: end.character + 1
    };
  }
  Range5.from = from;
  function to(range) {
    if (!range) {
      return void 0;
    }
    const { startLineNumber, startColumn, endLineNumber, endColumn } = range;
    return new $BT(startLineNumber - 1, startColumn - 1, endLineNumber - 1, endColumn - 1);
  }
  Range5.to = to;
})(Range4 || (Range4 = {}));
var Location;
(function(Location2) {
  function from(location3) {
    return {
      uri: location3.uri,
      range: Range4.from(location3.range)
    };
  }
  Location2.from = from;
  function to(location3) {
    return new $NT(URI.revive(location3.uri), Range4.to(location3.range));
  }
  Location2.to = to;
})(Location || (Location = {}));
var TokenType3;
(function(TokenType4) {
  function to(type) {
    switch (type) {
      case 1:
        return StandardTokenType2.Comment;
      case 0:
        return StandardTokenType2.Other;
      case 3:
        return StandardTokenType2.RegEx;
      case 2:
        return StandardTokenType2.String;
    }
  }
  TokenType4.to = to;
})(TokenType3 || (TokenType3 = {}));
var Position2;
(function(Position3) {
  function to(position) {
    return new $AT(position.lineNumber - 1, position.column - 1);
  }
  Position3.to = to;
  function from(position) {
    return { lineNumber: position.line + 1, column: position.character + 1 };
  }
  Position3.from = from;
})(Position2 || (Position2 = {}));
var DocumentSelector;
(function(DocumentSelector2) {
  function from(value, uriTransformer, extension) {
    return $Mb($5b(value).map((sel) => _doTransformDocumentSelector(sel, uriTransformer, extension)));
  }
  DocumentSelector2.from = from;
  function _doTransformDocumentSelector(selector, uriTransformer, extension) {
    if (typeof selector === "string") {
      return {
        $serialized: true,
        language: selector,
        isBuiltin: extension?.isBuiltin
      };
    }
    if (selector) {
      return {
        $serialized: true,
        language: selector.language,
        scheme: _transformScheme(selector.scheme, uriTransformer),
        pattern: GlobPattern.from(selector.pattern) ?? void 0,
        exclusive: selector.exclusive,
        notebookType: selector.notebookType,
        isBuiltin: extension?.isBuiltin
      };
    }
    return void 0;
  }
  function _transformScheme(scheme, uriTransformer) {
    if (uriTransformer && typeof scheme === "string") {
      return uriTransformer.transformOutgoingScheme(scheme);
    }
    return scheme;
  }
})(DocumentSelector || (DocumentSelector = {}));
var DiagnosticTag2;
(function(DiagnosticTag3) {
  function from(value) {
    switch (value) {
      case DiagnosticTag.Unnecessary:
        return 1;
      case DiagnosticTag.Deprecated:
        return 2;
    }
    return void 0;
  }
  DiagnosticTag3.from = from;
  function to(value) {
    switch (value) {
      case 1:
        return DiagnosticTag.Unnecessary;
      case 2:
        return DiagnosticTag.Deprecated;
      default:
        return void 0;
    }
  }
  DiagnosticTag3.to = to;
})(DiagnosticTag2 || (DiagnosticTag2 = {}));
var Diagnostic;
(function(Diagnostic2) {
  function from(value) {
    let code;
    if (value.code) {
      if ($zg(value.code) || $Dg(value.code)) {
        code = String(value.code);
      } else {
        code = {
          value: String(value.code.value),
          target: value.code.target
        };
      }
    }
    return {
      ...Range4.from(value.range),
      message: value.message,
      source: value.source,
      code,
      severity: DiagnosticSeverity2.from(value.severity),
      relatedInformation: value.relatedInformation && value.relatedInformation.map(DiagnosticRelatedInformation.from),
      tags: Array.isArray(value.tags) ? $Mb(value.tags.map(DiagnosticTag2.from)) : void 0
    };
  }
  Diagnostic2.from = from;
  function to(value) {
    const res = new $PT(Range4.to(value), value.message, DiagnosticSeverity2.to(value.severity));
    res.source = value.source;
    res.code = $zg(value.code) ? value.code : value.code?.value;
    res.relatedInformation = value.relatedInformation && value.relatedInformation.map(DiagnosticRelatedInformation.to);
    res.tags = value.tags && $Mb(value.tags.map(DiagnosticTag2.to));
    return res;
  }
  Diagnostic2.to = to;
})(Diagnostic || (Diagnostic = {}));
var DiagnosticRelatedInformation;
(function(DiagnosticRelatedInformation2) {
  function from(value) {
    return {
      ...Range4.from(value.location.range),
      message: value.message,
      resource: value.location.uri
    };
  }
  DiagnosticRelatedInformation2.from = from;
  function to(value) {
    return new $OT(new $NT(value.resource, Range4.to(value)), value.message);
  }
  DiagnosticRelatedInformation2.to = to;
})(DiagnosticRelatedInformation || (DiagnosticRelatedInformation = {}));
var DiagnosticSeverity2;
(function(DiagnosticSeverity3) {
  function from(value) {
    switch (value) {
      case DiagnosticSeverity.Error:
        return MarkerSeverity.Error;
      case DiagnosticSeverity.Warning:
        return MarkerSeverity.Warning;
      case DiagnosticSeverity.Information:
        return MarkerSeverity.Info;
      case DiagnosticSeverity.Hint:
        return MarkerSeverity.Hint;
    }
    return MarkerSeverity.Error;
  }
  DiagnosticSeverity3.from = from;
  function to(value) {
    switch (value) {
      case MarkerSeverity.Info:
        return DiagnosticSeverity.Information;
      case MarkerSeverity.Warning:
        return DiagnosticSeverity.Warning;
      case MarkerSeverity.Error:
        return DiagnosticSeverity.Error;
      case MarkerSeverity.Hint:
        return DiagnosticSeverity.Hint;
      default:
        return DiagnosticSeverity.Error;
    }
  }
  DiagnosticSeverity3.to = to;
})(DiagnosticSeverity2 || (DiagnosticSeverity2 = {}));
var ViewColumn2;
(function(ViewColumn3) {
  function from(column) {
    if (typeof column === "number" && column >= ViewColumn.One) {
      return column - 1;
    }
    if (column === ViewColumn.Beside) {
      return $oJ;
    }
    return $nJ;
  }
  ViewColumn3.from = from;
  function to(position) {
    if (typeof position === "number" && position >= 0) {
      return position + 1;
    }
    throw new Error(`invalid 'EditorGroupColumn'`);
  }
  ViewColumn3.to = to;
})(ViewColumn2 || (ViewColumn2 = {}));
var MarkdownString;
(function(MarkdownString2) {
  function fromMany(markup) {
    return markup.map(MarkdownString2.from);
  }
  MarkdownString2.fromMany = fromMany;
  function isCodeblock(thing) {
    return thing && typeof thing === "object" && typeof thing.language === "string" && typeof thing.value === "string";
  }
  function from(markup) {
    let res;
    if (isCodeblock(markup)) {
      const { language, value } = markup;
      res = { value: "```" + language + "\n" + value + "\n```\n" };
    } else if ($4T.isMarkdownString(markup)) {
      res = { value: markup.value, isTrusted: markup.isTrusted, supportThemeIcons: markup.supportThemeIcons, supportHtml: markup.supportHtml, baseUri: markup.baseUri };
    } else if (typeof markup === "string") {
      res = { value: markup };
    } else {
      res = { value: "" };
    }
    const resUris = /* @__PURE__ */ Object.create(null);
    res.uris = resUris;
    const collectUri = ({ href }) => {
      try {
        let uri = URI.parse(href, true);
        uri = uri.with({ query: _uriMassage(uri.query, resUris) });
        resUris[href] = uri;
      } catch (e) {
      }
      return "";
    };
    marked.walkTokens(marked.lexer(res.value), (token) => {
      if (token.type === "link") {
        collectUri({ href: token.href });
      } else if (token.type === "image") {
        if (typeof token.href === "string") {
          collectUri($jm(token.href));
        }
      }
    });
    return res;
  }
  MarkdownString2.from = from;
  function _uriMassage(part, bucket) {
    if (!part) {
      return part;
    }
    let data;
    try {
      data = $bu(part);
    } catch (e) {
    }
    if (!data) {
      return part;
    }
    let changed = false;
    data = $Nv(data, (value) => {
      if (URI.isUri(value)) {
        const key2 = `__uri_${Math.random().toString(16).slice(2, 8)}`;
        bucket[key2] = value;
        changed = true;
        return key2;
      } else {
        return void 0;
      }
    });
    if (!changed) {
      return part;
    }
    return JSON.stringify(data);
  }
  function to(value) {
    const result = new $4T(value.value, value.supportThemeIcons);
    result.isTrusted = value.isTrusted;
    result.supportHtml = value.supportHtml;
    result.baseUri = value.baseUri ? URI.from(value.baseUri) : void 0;
    return result;
  }
  MarkdownString2.to = to;
  function fromStrict(value) {
    if (!value) {
      return void 0;
    }
    return typeof value === "string" ? value : MarkdownString2.from(value);
  }
  MarkdownString2.fromStrict = fromStrict;
})(MarkdownString || (MarkdownString = {}));
function $fW(value) {
  if (typeof value === "undefined") {
    return value;
  }
  if (typeof value === "string") {
    return URI.file(value);
  } else {
    return value;
  }
}
var ThemableDecorationAttachmentRenderOptions;
(function(ThemableDecorationAttachmentRenderOptions2) {
  function from(options3) {
    if (typeof options3 === "undefined") {
      return options3;
    }
    return {
      contentText: options3.contentText,
      contentIconPath: options3.contentIconPath ? $fW(options3.contentIconPath) : void 0,
      border: options3.border,
      borderColor: options3.borderColor,
      fontStyle: options3.fontStyle,
      fontWeight: options3.fontWeight,
      textDecoration: options3.textDecoration,
      color: options3.color,
      backgroundColor: options3.backgroundColor,
      margin: options3.margin,
      width: options3.width,
      height: options3.height
    };
  }
  ThemableDecorationAttachmentRenderOptions2.from = from;
})(ThemableDecorationAttachmentRenderOptions || (ThemableDecorationAttachmentRenderOptions = {}));
var ThemableDecorationRenderOptions;
(function(ThemableDecorationRenderOptions2) {
  function from(options3) {
    if (typeof options3 === "undefined") {
      return options3;
    }
    return {
      backgroundColor: options3.backgroundColor,
      outline: options3.outline,
      outlineColor: options3.outlineColor,
      outlineStyle: options3.outlineStyle,
      outlineWidth: options3.outlineWidth,
      border: options3.border,
      borderColor: options3.borderColor,
      borderRadius: options3.borderRadius,
      borderSpacing: options3.borderSpacing,
      borderStyle: options3.borderStyle,
      borderWidth: options3.borderWidth,
      fontStyle: options3.fontStyle,
      fontWeight: options3.fontWeight,
      textDecoration: options3.textDecoration,
      cursor: options3.cursor,
      color: options3.color,
      opacity: options3.opacity,
      letterSpacing: options3.letterSpacing,
      gutterIconPath: options3.gutterIconPath ? $fW(options3.gutterIconPath) : void 0,
      gutterIconSize: options3.gutterIconSize,
      overviewRulerColor: options3.overviewRulerColor,
      before: options3.before ? ThemableDecorationAttachmentRenderOptions.from(options3.before) : void 0,
      after: options3.after ? ThemableDecorationAttachmentRenderOptions.from(options3.after) : void 0
    };
  }
  ThemableDecorationRenderOptions2.from = from;
})(ThemableDecorationRenderOptions || (ThemableDecorationRenderOptions = {}));
var DecorationRangeBehavior2;
(function(DecorationRangeBehavior3) {
  function from(value) {
    if (typeof value === "undefined") {
      return value;
    }
    switch (value) {
      case DecorationRangeBehavior.OpenOpen:
        return 0;
      case DecorationRangeBehavior.ClosedClosed:
        return 1;
      case DecorationRangeBehavior.OpenClosed:
        return 2;
      case DecorationRangeBehavior.ClosedOpen:
        return 3;
    }
  }
  DecorationRangeBehavior3.from = from;
})(DecorationRangeBehavior2 || (DecorationRangeBehavior2 = {}));
var DecorationRenderOptions;
(function(DecorationRenderOptions2) {
  function from(options3) {
    return {
      isWholeLine: options3.isWholeLine,
      rangeBehavior: options3.rangeBehavior ? DecorationRangeBehavior2.from(options3.rangeBehavior) : void 0,
      overviewRulerLane: options3.overviewRulerLane,
      light: options3.light ? ThemableDecorationRenderOptions.from(options3.light) : void 0,
      dark: options3.dark ? ThemableDecorationRenderOptions.from(options3.dark) : void 0,
      backgroundColor: options3.backgroundColor,
      outline: options3.outline,
      outlineColor: options3.outlineColor,
      outlineStyle: options3.outlineStyle,
      outlineWidth: options3.outlineWidth,
      border: options3.border,
      borderColor: options3.borderColor,
      borderRadius: options3.borderRadius,
      borderSpacing: options3.borderSpacing,
      borderStyle: options3.borderStyle,
      borderWidth: options3.borderWidth,
      fontStyle: options3.fontStyle,
      fontWeight: options3.fontWeight,
      textDecoration: options3.textDecoration,
      cursor: options3.cursor,
      color: options3.color,
      opacity: options3.opacity,
      letterSpacing: options3.letterSpacing,
      gutterIconPath: options3.gutterIconPath ? $fW(options3.gutterIconPath) : void 0,
      gutterIconSize: options3.gutterIconSize,
      overviewRulerColor: options3.overviewRulerColor,
      before: options3.before ? ThemableDecorationAttachmentRenderOptions.from(options3.before) : void 0,
      after: options3.after ? ThemableDecorationAttachmentRenderOptions.from(options3.after) : void 0
    };
  }
  DecorationRenderOptions2.from = from;
})(DecorationRenderOptions || (DecorationRenderOptions = {}));
var TextEdit;
(function(TextEdit2) {
  function from(edit3) {
    return {
      text: edit3.newText,
      eol: edit3.newEol && EndOfLine2.from(edit3.newEol),
      range: Range4.from(edit3.range)
    };
  }
  TextEdit2.from = from;
  function to(edit3) {
    const result = new $IT(Range4.to(edit3.range), edit3.text);
    result.newEol = typeof edit3.eol === "undefined" ? void 0 : EndOfLine2.to(edit3.eol);
    return result;
  }
  TextEdit2.to = to;
})(TextEdit || (TextEdit = {}));
var WorkspaceEdit;
(function(WorkspaceEdit2) {
  function from(value, versionInfo) {
    const result = {
      edits: []
    };
    if (value instanceof $LT) {
      const toCreate = new $Fc();
      for (const entry of value._allEntries()) {
        if (entry._type === 1 && URI.isUri(entry.to) && entry.from === void 0) {
          toCreate.add(entry.to);
        }
      }
      for (const entry of value._allEntries()) {
        if (entry._type === 1) {
          let contents;
          if (entry.options?.contents) {
            if (ArrayBuffer.isView(entry.options.contents)) {
              contents = { type: "base64", value: $Wi($Ci.wrap(entry.options.contents)) };
            } else {
              contents = { type: "dataTransferItem", id: entry.options.contents._itemId };
            }
          }
          result.edits.push({
            oldResource: entry.from,
            newResource: entry.to,
            options: { ...entry.options, contents },
            metadata: entry.metadata
          });
        } else if (entry._type === 2) {
          result.edits.push({
            resource: entry.uri,
            textEdit: TextEdit.from(entry.edit),
            versionId: !toCreate.has(entry.uri) ? versionInfo?.getTextDocumentVersion(entry.uri) : void 0,
            metadata: entry.metadata
          });
        } else if (entry._type === 6) {
          result.edits.push({
            resource: entry.uri,
            textEdit: {
              range: Range4.from(entry.range),
              text: entry.edit.value,
              insertAsSnippet: true
            },
            versionId: !toCreate.has(entry.uri) ? versionInfo?.getTextDocumentVersion(entry.uri) : void 0,
            metadata: entry.metadata
          });
        } else if (entry._type === 3) {
          result.edits.push({
            metadata: entry.metadata,
            resource: entry.uri,
            cellEdit: entry.edit,
            notebookVersionId: versionInfo?.getNotebookDocumentVersion(entry.uri)
          });
        } else if (entry._type === 5) {
          result.edits.push({
            metadata: entry.metadata,
            resource: entry.uri,
            notebookVersionId: versionInfo?.getNotebookDocumentVersion(entry.uri),
            cellEdit: {
              editType: 1,
              index: entry.index,
              count: entry.count,
              cells: entry.cells.map(NotebookCellData.from)
            }
          });
        }
      }
    }
    return result;
  }
  WorkspaceEdit2.from = from;
  function to(value) {
    const result = new $LT();
    const edits = new $Ec();
    for (const edit3 of value.edits) {
      if (edit3.textEdit) {
        const item = edit3;
        const uri = URI.revive(item.resource);
        const range = Range4.to(item.textEdit.range);
        const text2 = item.textEdit.text;
        const isSnippet = item.textEdit.insertAsSnippet;
        let editOrSnippetTest;
        if (isSnippet) {
          editOrSnippetTest = $KT.replace(range, new $MT(text2));
        } else {
          editOrSnippetTest = $IT.replace(range, text2);
        }
        const array2 = edits.get(uri);
        if (!array2) {
          edits.set(uri, [editOrSnippetTest]);
        } else {
          array2.push(editOrSnippetTest);
        }
      } else {
        result.renameFile(URI.revive(edit3.oldResource), URI.revive(edit3.newResource), edit3.options);
      }
    }
    for (const [uri, array2] of edits) {
      result.set(uri, array2);
    }
    return result;
  }
  WorkspaceEdit2.to = to;
})(WorkspaceEdit || (WorkspaceEdit = {}));
var SymbolKind3;
(function(SymbolKind5) {
  const _fromMapping = /* @__PURE__ */ Object.create(null);
  _fromMapping[SymbolKind2.File] = 0;
  _fromMapping[SymbolKind2.Module] = 1;
  _fromMapping[SymbolKind2.Namespace] = 2;
  _fromMapping[SymbolKind2.Package] = 3;
  _fromMapping[SymbolKind2.Class] = 4;
  _fromMapping[SymbolKind2.Method] = 5;
  _fromMapping[SymbolKind2.Property] = 6;
  _fromMapping[SymbolKind2.Field] = 7;
  _fromMapping[SymbolKind2.Constructor] = 8;
  _fromMapping[SymbolKind2.Enum] = 9;
  _fromMapping[SymbolKind2.Interface] = 10;
  _fromMapping[SymbolKind2.Function] = 11;
  _fromMapping[SymbolKind2.Variable] = 12;
  _fromMapping[SymbolKind2.Constant] = 13;
  _fromMapping[SymbolKind2.String] = 14;
  _fromMapping[SymbolKind2.Number] = 15;
  _fromMapping[SymbolKind2.Boolean] = 16;
  _fromMapping[SymbolKind2.Array] = 17;
  _fromMapping[SymbolKind2.Object] = 18;
  _fromMapping[SymbolKind2.Key] = 19;
  _fromMapping[SymbolKind2.Null] = 20;
  _fromMapping[SymbolKind2.EnumMember] = 21;
  _fromMapping[SymbolKind2.Struct] = 22;
  _fromMapping[SymbolKind2.Event] = 23;
  _fromMapping[SymbolKind2.Operator] = 24;
  _fromMapping[SymbolKind2.TypeParameter] = 25;
  function from(kind) {
    return typeof _fromMapping[kind] === "number" ? _fromMapping[kind] : 6;
  }
  SymbolKind5.from = from;
  function to(kind) {
    for (const k in _fromMapping) {
      if (_fromMapping[k] === kind) {
        return Number(k);
      }
    }
    return SymbolKind2.Property;
  }
  SymbolKind5.to = to;
})(SymbolKind3 || (SymbolKind3 = {}));
var SymbolTag3;
(function(SymbolTag5) {
  function from(kind) {
    switch (kind) {
      case SymbolTag2.Deprecated:
        return 1;
    }
  }
  SymbolTag5.from = from;
  function to(kind) {
    switch (kind) {
      case 1:
        return SymbolTag2.Deprecated;
    }
  }
  SymbolTag5.to = to;
})(SymbolTag3 || (SymbolTag3 = {}));
var WorkspaceSymbol;
(function(WorkspaceSymbol2) {
  function from(info) {
    return {
      name: info.name,
      kind: SymbolKind3.from(info.kind),
      tags: info.tags && info.tags.map(SymbolTag3.from),
      containerName: info.containerName,
      location: location2.from(info.location)
    };
  }
  WorkspaceSymbol2.from = from;
  function to(info) {
    const result = new $UT(info.name, SymbolKind3.to(info.kind), info.containerName, location2.to(info.location));
    result.tags = info.tags && info.tags.map(SymbolTag3.to);
    return result;
  }
  WorkspaceSymbol2.to = to;
})(WorkspaceSymbol || (WorkspaceSymbol = {}));
var DocumentSymbol;
(function(DocumentSymbol2) {
  function from(info) {
    const result = {
      name: info.name || "!!MISSING: name!!",
      detail: info.detail,
      range: Range4.from(info.range),
      selectionRange: Range4.from(info.selectionRange),
      kind: SymbolKind3.from(info.kind),
      tags: info.tags?.map(SymbolTag3.from) ?? []
    };
    if (info.children) {
      result.children = info.children.map(from);
    }
    return result;
  }
  DocumentSymbol2.from = from;
  function to(info) {
    const result = new $VT(info.name, info.detail, SymbolKind3.to(info.kind), Range4.to(info.range), Range4.to(info.selectionRange));
    if ($Qb(info.tags)) {
      result.tags = info.tags.map(SymbolTag3.to);
    }
    if (info.children) {
      result.children = info.children.map(to);
    }
    return result;
  }
  DocumentSymbol2.to = to;
})(DocumentSymbol || (DocumentSymbol = {}));
var CallHierarchyItem;
(function(CallHierarchyItem2) {
  function to(item) {
    const result = new $ZT(SymbolKind3.to(item.kind), item.name, item.detail || "", URI.revive(item.uri), Range4.to(item.range), Range4.to(item.selectionRange));
    result._sessionId = item._sessionId;
    result._itemId = item._itemId;
    return result;
  }
  CallHierarchyItem2.to = to;
  function from(item, sessionId, itemId) {
    sessionId = sessionId ?? item._sessionId;
    itemId = itemId ?? item._itemId;
    if (sessionId === void 0 || itemId === void 0) {
      throw new Error("invalid item");
    }
    return {
      _sessionId: sessionId,
      _itemId: itemId,
      name: item.name,
      detail: item.detail,
      kind: SymbolKind3.from(item.kind),
      uri: item.uri,
      range: Range4.from(item.range),
      selectionRange: Range4.from(item.selectionRange),
      tags: item.tags?.map(SymbolTag3.from)
    };
  }
  CallHierarchyItem2.from = from;
})(CallHierarchyItem || (CallHierarchyItem = {}));
var CallHierarchyIncomingCall;
(function(CallHierarchyIncomingCall2) {
  function to(item) {
    return new $1T(CallHierarchyItem.to(item.from), item.fromRanges.map((r2) => Range4.to(r2)));
  }
  CallHierarchyIncomingCall2.to = to;
})(CallHierarchyIncomingCall || (CallHierarchyIncomingCall = {}));
var CallHierarchyOutgoingCall;
(function(CallHierarchyOutgoingCall2) {
  function to(item) {
    return new $2T(CallHierarchyItem.to(item.to), item.fromRanges.map((r2) => Range4.to(r2)));
  }
  CallHierarchyOutgoingCall2.to = to;
})(CallHierarchyOutgoingCall || (CallHierarchyOutgoingCall = {}));
var location2;
(function(location3) {
  function from(value) {
    return {
      range: value.range && Range4.from(value.range),
      uri: value.uri
    };
  }
  location3.from = from;
  function to(value) {
    return new $NT(URI.revive(value.uri), Range4.to(value.range));
  }
  location3.to = to;
})(location2 || (location2 = {}));
var DefinitionLink;
(function(DefinitionLink2) {
  function from(value) {
    const definitionLink = value;
    const location3 = value;
    return {
      originSelectionRange: definitionLink.originSelectionRange ? Range4.from(definitionLink.originSelectionRange) : void 0,
      uri: definitionLink.targetUri ? definitionLink.targetUri : location3.uri,
      range: Range4.from(definitionLink.targetRange ? definitionLink.targetRange : location3.range),
      targetSelectionRange: definitionLink.targetSelectionRange ? Range4.from(definitionLink.targetSelectionRange) : void 0
    };
  }
  DefinitionLink2.from = from;
  function to(value) {
    return {
      targetUri: URI.revive(value.uri),
      targetRange: Range4.to(value.range),
      targetSelectionRange: value.targetSelectionRange ? Range4.to(value.targetSelectionRange) : void 0,
      originSelectionRange: value.originSelectionRange ? Range4.to(value.originSelectionRange) : void 0
    };
  }
  DefinitionLink2.to = to;
})(DefinitionLink || (DefinitionLink = {}));
var Hover;
(function(Hover2) {
  function from(hover) {
    const convertedHover = {
      range: Range4.from(hover.range),
      contents: MarkdownString.fromMany(hover.contents),
      canIncreaseVerbosity: hover.canIncreaseVerbosity,
      canDecreaseVerbosity: hover.canDecreaseVerbosity
    };
    return convertedHover;
  }
  Hover2.from = from;
  function to(info) {
    const contents = info.contents.map(MarkdownString.to);
    const range = Range4.to(info.range);
    const canIncreaseVerbosity = info.canIncreaseVerbosity;
    const canDecreaseVerbosity = info.canDecreaseVerbosity;
    return new $RT(contents, range, canIncreaseVerbosity, canDecreaseVerbosity);
  }
  Hover2.to = to;
})(Hover || (Hover = {}));
var EvaluatableExpression;
(function(EvaluatableExpression2) {
  function from(expression) {
    return {
      range: Range4.from(expression.range),
      expression: expression.expression
    };
  }
  EvaluatableExpression2.from = from;
  function to(info) {
    return new $OU(Range4.to(info.range), info.expression);
  }
  EvaluatableExpression2.to = to;
})(EvaluatableExpression || (EvaluatableExpression = {}));
var InlineValue;
(function(InlineValue2) {
  function from(inlineValue) {
    if (inlineValue instanceof $PU) {
      return {
        type: "text",
        range: Range4.from(inlineValue.range),
        text: inlineValue.text
      };
    } else if (inlineValue instanceof $QU) {
      return {
        type: "variable",
        range: Range4.from(inlineValue.range),
        variableName: inlineValue.variableName,
        caseSensitiveLookup: inlineValue.caseSensitiveLookup
      };
    } else if (inlineValue instanceof $RU) {
      return {
        type: "expression",
        range: Range4.from(inlineValue.range),
        expression: inlineValue.expression
      };
    } else {
      throw new Error(`Unknown 'InlineValue' type`);
    }
  }
  InlineValue2.from = from;
  function to(inlineValue) {
    switch (inlineValue.type) {
      case "text":
        return {
          range: Range4.to(inlineValue.range),
          text: inlineValue.text
        };
      case "variable":
        return {
          range: Range4.to(inlineValue.range),
          variableName: inlineValue.variableName,
          caseSensitiveLookup: inlineValue.caseSensitiveLookup
        };
      case "expression":
        return {
          range: Range4.to(inlineValue.range),
          expression: inlineValue.expression
        };
    }
  }
  InlineValue2.to = to;
})(InlineValue || (InlineValue = {}));
var InlineValueContext;
(function(InlineValueContext2) {
  function from(inlineValueContext) {
    return {
      frameId: inlineValueContext.frameId,
      stoppedLocation: Range4.from(inlineValueContext.stoppedLocation)
    };
  }
  InlineValueContext2.from = from;
  function to(inlineValueContext) {
    return new $SU(inlineValueContext.frameId, Range4.to(inlineValueContext.stoppedLocation));
  }
  InlineValueContext2.to = to;
})(InlineValueContext || (InlineValueContext = {}));
var DocumentHighlight;
(function(DocumentHighlight2) {
  function from(documentHighlight) {
    return {
      range: Range4.from(documentHighlight.range),
      kind: documentHighlight.kind
    };
  }
  DocumentHighlight2.from = from;
  function to(occurrence) {
    return new $ST(Range4.to(occurrence.range), occurrence.kind);
  }
  DocumentHighlight2.to = to;
})(DocumentHighlight || (DocumentHighlight = {}));
var MultiDocumentHighlight;
(function(MultiDocumentHighlight2) {
  function from(multiDocumentHighlight) {
    return {
      uri: multiDocumentHighlight.uri,
      highlights: multiDocumentHighlight.highlights.map(DocumentHighlight.from)
    };
  }
  MultiDocumentHighlight2.from = from;
  function to(multiDocumentHighlight) {
    return new $TT(URI.revive(multiDocumentHighlight.uri), multiDocumentHighlight.highlights.map(DocumentHighlight.to));
  }
  MultiDocumentHighlight2.to = to;
})(MultiDocumentHighlight || (MultiDocumentHighlight = {}));
var CompletionTriggerKind3;
(function(CompletionTriggerKind5) {
  function to(kind) {
    switch (kind) {
      case 1:
        return CompletionTriggerKind2.TriggerCharacter;
      case 2:
        return CompletionTriggerKind2.TriggerForIncompleteCompletions;
      case 0:
      default:
        return CompletionTriggerKind2.Invoke;
    }
  }
  CompletionTriggerKind5.to = to;
})(CompletionTriggerKind3 || (CompletionTriggerKind3 = {}));
var CompletionContext;
(function(CompletionContext2) {
  function to(context) {
    return {
      triggerKind: CompletionTriggerKind3.to(context.triggerKind),
      triggerCharacter: context.triggerCharacter
    };
  }
  CompletionContext2.to = to;
})(CompletionContext || (CompletionContext = {}));
var CompletionItemTag3;
(function(CompletionItemTag5) {
  function from(kind) {
    switch (kind) {
      case CompletionItemTag2.Deprecated:
        return 1;
    }
  }
  CompletionItemTag5.from = from;
  function to(kind) {
    switch (kind) {
      case 1:
        return CompletionItemTag2.Deprecated;
    }
  }
  CompletionItemTag5.to = to;
})(CompletionItemTag3 || (CompletionItemTag3 = {}));
var CompletionItemKind3;
(function(CompletionItemKind5) {
  const _from = /* @__PURE__ */ new Map([
    [
      CompletionItemKind2.Method,
      0
      /* languages.CompletionItemKind.Method */
    ],
    [
      CompletionItemKind2.Function,
      1
      /* languages.CompletionItemKind.Function */
    ],
    [
      CompletionItemKind2.Constructor,
      2
      /* languages.CompletionItemKind.Constructor */
    ],
    [
      CompletionItemKind2.Field,
      3
      /* languages.CompletionItemKind.Field */
    ],
    [
      CompletionItemKind2.Variable,
      4
      /* languages.CompletionItemKind.Variable */
    ],
    [
      CompletionItemKind2.Class,
      5
      /* languages.CompletionItemKind.Class */
    ],
    [
      CompletionItemKind2.Interface,
      7
      /* languages.CompletionItemKind.Interface */
    ],
    [
      CompletionItemKind2.Struct,
      6
      /* languages.CompletionItemKind.Struct */
    ],
    [
      CompletionItemKind2.Module,
      8
      /* languages.CompletionItemKind.Module */
    ],
    [
      CompletionItemKind2.Property,
      9
      /* languages.CompletionItemKind.Property */
    ],
    [
      CompletionItemKind2.Unit,
      12
      /* languages.CompletionItemKind.Unit */
    ],
    [
      CompletionItemKind2.Value,
      13
      /* languages.CompletionItemKind.Value */
    ],
    [
      CompletionItemKind2.Constant,
      14
      /* languages.CompletionItemKind.Constant */
    ],
    [
      CompletionItemKind2.Enum,
      15
      /* languages.CompletionItemKind.Enum */
    ],
    [
      CompletionItemKind2.EnumMember,
      16
      /* languages.CompletionItemKind.EnumMember */
    ],
    [
      CompletionItemKind2.Keyword,
      17
      /* languages.CompletionItemKind.Keyword */
    ],
    [
      CompletionItemKind2.Snippet,
      27
      /* languages.CompletionItemKind.Snippet */
    ],
    [
      CompletionItemKind2.Text,
      18
      /* languages.CompletionItemKind.Text */
    ],
    [
      CompletionItemKind2.Color,
      19
      /* languages.CompletionItemKind.Color */
    ],
    [
      CompletionItemKind2.File,
      20
      /* languages.CompletionItemKind.File */
    ],
    [
      CompletionItemKind2.Reference,
      21
      /* languages.CompletionItemKind.Reference */
    ],
    [
      CompletionItemKind2.Folder,
      23
      /* languages.CompletionItemKind.Folder */
    ],
    [
      CompletionItemKind2.Event,
      10
      /* languages.CompletionItemKind.Event */
    ],
    [
      CompletionItemKind2.Operator,
      11
      /* languages.CompletionItemKind.Operator */
    ],
    [
      CompletionItemKind2.TypeParameter,
      24
      /* languages.CompletionItemKind.TypeParameter */
    ],
    [
      CompletionItemKind2.Issue,
      26
      /* languages.CompletionItemKind.Issue */
    ],
    [
      CompletionItemKind2.User,
      25
      /* languages.CompletionItemKind.User */
    ]
  ]);
  function from(kind) {
    return _from.get(kind) ?? 9;
  }
  CompletionItemKind5.from = from;
  const _to = /* @__PURE__ */ new Map([
    [0, CompletionItemKind2.Method],
    [1, CompletionItemKind2.Function],
    [2, CompletionItemKind2.Constructor],
    [3, CompletionItemKind2.Field],
    [4, CompletionItemKind2.Variable],
    [5, CompletionItemKind2.Class],
    [7, CompletionItemKind2.Interface],
    [6, CompletionItemKind2.Struct],
    [8, CompletionItemKind2.Module],
    [9, CompletionItemKind2.Property],
    [12, CompletionItemKind2.Unit],
    [13, CompletionItemKind2.Value],
    [14, CompletionItemKind2.Constant],
    [15, CompletionItemKind2.Enum],
    [16, CompletionItemKind2.EnumMember],
    [17, CompletionItemKind2.Keyword],
    [27, CompletionItemKind2.Snippet],
    [18, CompletionItemKind2.Text],
    [19, CompletionItemKind2.Color],
    [20, CompletionItemKind2.File],
    [21, CompletionItemKind2.Reference],
    [23, CompletionItemKind2.Folder],
    [10, CompletionItemKind2.Event],
    [11, CompletionItemKind2.Operator],
    [24, CompletionItemKind2.TypeParameter],
    [25, CompletionItemKind2.User],
    [26, CompletionItemKind2.Issue]
  ]);
  function to(kind) {
    return _to.get(kind) ?? CompletionItemKind2.Property;
  }
  CompletionItemKind5.to = to;
})(CompletionItemKind3 || (CompletionItemKind3 = {}));
var CompletionItem;
(function(CompletionItem2) {
  function to(suggestion, converter) {
    const result = new $0T(suggestion.label);
    result.insertText = suggestion.insertText;
    result.kind = CompletionItemKind3.to(suggestion.kind);
    result.tags = suggestion.tags?.map(CompletionItemTag3.to);
    result.detail = suggestion.detail;
    result.documentation = $dm(suggestion.documentation) ? MarkdownString.to(suggestion.documentation) : suggestion.documentation;
    result.sortText = suggestion.sortText;
    result.filterText = suggestion.filterText;
    result.preselect = suggestion.preselect;
    result.commitCharacters = suggestion.commitCharacters;
    if ($9C.isIRange(suggestion.range)) {
      result.range = Range4.to(suggestion.range);
    } else if (typeof suggestion.range === "object") {
      result.range = { inserting: Range4.to(suggestion.range.insert), replacing: Range4.to(suggestion.range.replace) };
    }
    result.keepWhitespace = typeof suggestion.insertTextRules === "undefined" ? false : Boolean(
      suggestion.insertTextRules & 1
      /* languages.CompletionItemInsertTextRule.KeepWhitespace */
    );
    if (typeof suggestion.insertTextRules !== "undefined" && suggestion.insertTextRules & 4) {
      result.insertText = new $MT(suggestion.insertText);
    } else {
      result.insertText = suggestion.insertText;
      result.textEdit = result.range instanceof $BT ? new $IT(result.range, result.insertText) : void 0;
    }
    if (suggestion.additionalTextEdits && suggestion.additionalTextEdits.length > 0) {
      result.additionalTextEdits = suggestion.additionalTextEdits.map((e) => TextEdit.to(e));
    }
    result.command = converter && suggestion.command ? converter.fromInternal(suggestion.command) : void 0;
    return result;
  }
  CompletionItem2.to = to;
})(CompletionItem || (CompletionItem = {}));
var ParameterInformation;
(function(ParameterInformation2) {
  function from(info) {
    if (typeof info.label !== "string" && !Array.isArray(info.label)) {
      throw new TypeError("Invalid label");
    }
    return {
      label: info.label,
      documentation: MarkdownString.fromStrict(info.documentation)
    };
  }
  ParameterInformation2.from = from;
  function to(info) {
    return {
      label: info.label,
      documentation: $dm(info.documentation) ? MarkdownString.to(info.documentation) : info.documentation
    };
  }
  ParameterInformation2.to = to;
})(ParameterInformation || (ParameterInformation = {}));
var SignatureInformation;
(function(SignatureInformation2) {
  function from(info) {
    return {
      label: info.label,
      documentation: MarkdownString.fromStrict(info.documentation),
      parameters: Array.isArray(info.parameters) ? info.parameters.map(ParameterInformation.from) : [],
      activeParameter: info.activeParameter
    };
  }
  SignatureInformation2.from = from;
  function to(info) {
    return {
      label: info.label,
      documentation: $dm(info.documentation) ? MarkdownString.to(info.documentation) : info.documentation,
      parameters: Array.isArray(info.parameters) ? info.parameters.map(ParameterInformation.to) : [],
      activeParameter: info.activeParameter
    };
  }
  SignatureInformation2.to = to;
})(SignatureInformation || (SignatureInformation = {}));
var SignatureHelp;
(function(SignatureHelp2) {
  function from(help) {
    return {
      activeSignature: help.activeSignature,
      activeParameter: help.activeParameter,
      signatures: Array.isArray(help.signatures) ? help.signatures.map(SignatureInformation.from) : []
    };
  }
  SignatureHelp2.from = from;
  function to(help) {
    return {
      activeSignature: help.activeSignature,
      activeParameter: help.activeParameter,
      signatures: Array.isArray(help.signatures) ? help.signatures.map(SignatureInformation.to) : []
    };
  }
  SignatureHelp2.to = to;
})(SignatureHelp || (SignatureHelp = {}));
var InlayHint;
(function(InlayHint2) {
  function to(converter, hint) {
    const res = new $9T(Position2.to(hint.position), typeof hint.label === "string" ? hint.label : hint.label.map(InlayHintLabelPart.to.bind(void 0, converter)), hint.kind && InlayHintKind3.to(hint.kind));
    res.textEdits = hint.textEdits && hint.textEdits.map(TextEdit.to);
    res.tooltip = $dm(hint.tooltip) ? MarkdownString.to(hint.tooltip) : hint.tooltip;
    res.paddingLeft = hint.paddingLeft;
    res.paddingRight = hint.paddingRight;
    return res;
  }
  InlayHint2.to = to;
})(InlayHint || (InlayHint = {}));
var InlayHintLabelPart;
(function(InlayHintLabelPart2) {
  function to(converter, part) {
    const result = new $8T(part.label);
    result.tooltip = $dm(part.tooltip) ? MarkdownString.to(part.tooltip) : part.tooltip;
    if (Command.is(part.command)) {
      result.command = converter.fromInternal(part.command);
    }
    if (part.location) {
      result.location = location2.to(part.location);
    }
    return result;
  }
  InlayHintLabelPart2.to = to;
})(InlayHintLabelPart || (InlayHintLabelPart = {}));
var InlayHintKind3;
(function(InlayHintKind5) {
  function from(kind) {
    return kind;
  }
  InlayHintKind5.from = from;
  function to(kind) {
    return kind;
  }
  InlayHintKind5.to = to;
})(InlayHintKind3 || (InlayHintKind3 = {}));
var DocumentLink;
(function(DocumentLink2) {
  function from(link2) {
    return {
      range: Range4.from(link2.range),
      url: link2.target,
      tooltip: link2.tooltip
    };
  }
  DocumentLink2.from = from;
  function to(link2) {
    let target = void 0;
    if (link2.url) {
      try {
        target = typeof link2.url === "string" ? URI.parse(link2.url, true) : URI.revive(link2.url);
      } catch (err) {
      }
    }
    const result = new $cU(Range4.to(link2.range), target);
    result.tooltip = link2.tooltip;
    return result;
  }
  DocumentLink2.to = to;
})(DocumentLink || (DocumentLink = {}));
var ColorPresentation;
(function(ColorPresentation2) {
  function to(colorPresentation) {
    const cp = new $fU(colorPresentation.label);
    if (colorPresentation.textEdit) {
      cp.textEdit = TextEdit.to(colorPresentation.textEdit);
    }
    if (colorPresentation.additionalTextEdits) {
      cp.additionalTextEdits = colorPresentation.additionalTextEdits.map((value) => TextEdit.to(value));
    }
    return cp;
  }
  ColorPresentation2.to = to;
  function from(colorPresentation) {
    return {
      label: colorPresentation.label,
      textEdit: colorPresentation.textEdit ? TextEdit.from(colorPresentation.textEdit) : void 0,
      additionalTextEdits: colorPresentation.additionalTextEdits ? colorPresentation.additionalTextEdits.map((value) => TextEdit.from(value)) : void 0
    };
  }
  ColorPresentation2.from = from;
})(ColorPresentation || (ColorPresentation = {}));
var Color;
(function(Color2) {
  function to(c) {
    return new $dU(c[0], c[1], c[2], c[3]);
  }
  Color2.to = to;
  function from(color2) {
    return [color2.red, color2.green, color2.blue, color2.alpha];
  }
  Color2.from = from;
})(Color || (Color = {}));
var SelectionRange;
(function(SelectionRange2) {
  function from(obj) {
    return { range: Range4.from(obj.range) };
  }
  SelectionRange2.from = from;
  function to(obj) {
    return new $YT(Range4.to(obj.range));
  }
  SelectionRange2.to = to;
})(SelectionRange || (SelectionRange = {}));
var TextDocumentSaveReason2;
(function(TextDocumentSaveReason3) {
  function to(reason) {
    switch (reason) {
      case 2:
        return TextDocumentSaveReason.AfterDelay;
      case 1:
        return TextDocumentSaveReason.Manual;
      case 3:
      case 4:
        return TextDocumentSaveReason.FocusOut;
    }
  }
  TextDocumentSaveReason3.to = to;
})(TextDocumentSaveReason2 || (TextDocumentSaveReason2 = {}));
var TextEditorLineNumbersStyle2;
(function(TextEditorLineNumbersStyle3) {
  function from(style) {
    switch (style) {
      case TextEditorLineNumbersStyle.Off:
        return 0;
      case TextEditorLineNumbersStyle.Relative:
        return 2;
      case TextEditorLineNumbersStyle.Interval:
        return 3;
      case TextEditorLineNumbersStyle.On:
      default:
        return 1;
    }
  }
  TextEditorLineNumbersStyle3.from = from;
  function to(style) {
    switch (style) {
      case 0:
        return TextEditorLineNumbersStyle.Off;
      case 2:
        return TextEditorLineNumbersStyle.Relative;
      case 3:
        return TextEditorLineNumbersStyle.Interval;
      case 1:
      default:
        return TextEditorLineNumbersStyle.On;
    }
  }
  TextEditorLineNumbersStyle3.to = to;
})(TextEditorLineNumbersStyle2 || (TextEditorLineNumbersStyle2 = {}));
var EndOfLine2;
(function(EndOfLine3) {
  function from(eol) {
    if (eol === EndOfLine.CRLF) {
      return 1;
    } else if (eol === EndOfLine.LF) {
      return 0;
    }
    return void 0;
  }
  EndOfLine3.from = from;
  function to(eol) {
    if (eol === 1) {
      return EndOfLine.CRLF;
    } else if (eol === 0) {
      return EndOfLine.LF;
    }
    return void 0;
  }
  EndOfLine3.to = to;
})(EndOfLine2 || (EndOfLine2 = {}));
var ProgressLocation3;
(function(ProgressLocation4) {
  function from(loc) {
    if (typeof loc === "object") {
      return loc.viewId;
    }
    switch (loc) {
      case ProgressLocation2.SourceControl:
        return 3;
      case ProgressLocation2.Window:
        return 10;
      case ProgressLocation2.Notification:
        return 15;
    }
    throw new Error(`Unknown 'ProgressLocation'`);
  }
  ProgressLocation4.from = from;
})(ProgressLocation3 || (ProgressLocation3 = {}));
var FoldingRange;
(function(FoldingRange2) {
  function from(r2) {
    const range = { start: r2.start + 1, end: r2.end + 1 };
    if (r2.kind) {
      range.kind = FoldingRangeKind2.from(r2.kind);
    }
    return range;
  }
  FoldingRange2.from = from;
  function to(r2) {
    const range = { start: r2.start - 1, end: r2.end - 1 };
    if (r2.kind) {
      range.kind = FoldingRangeKind2.to(r2.kind);
    }
    return range;
  }
  FoldingRange2.to = to;
})(FoldingRange || (FoldingRange = {}));
var FoldingRangeKind2;
(function(FoldingRangeKind3) {
  function from(kind) {
    if (kind) {
      switch (kind) {
        case FoldingRangeKind.Comment:
          return $WE.Comment;
        case FoldingRangeKind.Imports:
          return $WE.Imports;
        case FoldingRangeKind.Region:
          return $WE.Region;
      }
    }
    return void 0;
  }
  FoldingRangeKind3.from = from;
  function to(kind) {
    if (kind) {
      switch (kind.value) {
        case $WE.Comment.value:
          return FoldingRangeKind.Comment;
        case $WE.Imports.value:
          return FoldingRangeKind.Imports;
        case $WE.Region.value:
          return FoldingRangeKind.Region;
      }
    }
    return void 0;
  }
  FoldingRangeKind3.to = to;
})(FoldingRangeKind2 || (FoldingRangeKind2 = {}));
var TextEditorOpenOptions;
(function(TextEditorOpenOptions2) {
  function from(options3) {
    if (options3) {
      return {
        pinned: typeof options3.preview === "boolean" ? !options3.preview : void 0,
        inactive: options3.background,
        preserveFocus: options3.preserveFocus,
        selection: typeof options3.selection === "object" ? Range4.from(options3.selection) : void 0,
        override: typeof options3.override === "boolean" ? $1K.id : void 0
      };
    }
    return void 0;
  }
  TextEditorOpenOptions2.from = from;
})(TextEditorOpenOptions || (TextEditorOpenOptions = {}));
var GlobPattern;
(function(GlobPattern2) {
  function from(pattern) {
    if (pattern instanceof $CU) {
      return pattern.toJSON();
    }
    if (typeof pattern === "string") {
      return pattern;
    }
    if (isRelativePatternShape(pattern) || isLegacyRelativePatternShape(pattern)) {
      return new $CU(pattern.baseUri ?? pattern.base, pattern.pattern).toJSON();
    }
    return pattern;
  }
  GlobPattern2.from = from;
  function isRelativePatternShape(obj) {
    const rp = obj;
    if (!rp) {
      return false;
    }
    return URI.isUri(rp.baseUri) && typeof rp.pattern === "string";
  }
  function isLegacyRelativePatternShape(obj) {
    const rp = obj;
    if (!rp) {
      return false;
    }
    return typeof rp.base === "string" && typeof rp.pattern === "string";
  }
  function to(pattern) {
    if (typeof pattern === "string") {
      return pattern;
    }
    return new $CU(URI.revive(pattern.baseUri), pattern.pattern);
  }
  GlobPattern2.to = to;
})(GlobPattern || (GlobPattern = {}));
var LanguageSelector;
(function(LanguageSelector2) {
  function from(selector) {
    if (!selector) {
      return void 0;
    } else if (Array.isArray(selector)) {
      return selector.map(from);
    } else if (typeof selector === "string") {
      return selector;
    } else {
      const filter = selector;
      return {
        language: filter.language,
        scheme: filter.scheme,
        pattern: GlobPattern.from(filter.pattern) ?? void 0,
        exclusive: filter.exclusive,
        notebookType: filter.notebookType
      };
    }
  }
  LanguageSelector2.from = from;
})(LanguageSelector || (LanguageSelector = {}));
var MappedEditsContext;
(function(MappedEditsContext2) {
  function is(v) {
    return !!v && typeof v === "object" && "documents" in v && Array.isArray(v.documents) && v.documents.every((subArr) => Array.isArray(subArr) && subArr.every(DocumentContextItem.is));
  }
  MappedEditsContext2.is = is;
  function from(extContext) {
    return {
      documents: extContext.documents.map((subArray) => subArray.map(DocumentContextItem.from)),
      conversation: extContext.conversation?.map((item) => item.type === "request" ? {
        type: "request",
        message: item.message
      } : {
        type: "response",
        message: item.message,
        result: item.result ? ChatAgentResult.from(item.result) : void 0,
        references: item.references?.map(DocumentContextItem.from)
      })
    };
  }
  MappedEditsContext2.from = from;
})(MappedEditsContext || (MappedEditsContext = {}));
var DocumentContextItem;
(function(DocumentContextItem2) {
  function is(item) {
    return typeof item === "object" && item !== null && "uri" in item && URI.isUri(item.uri) && "version" in item && typeof item.version === "number" && "ranges" in item && Array.isArray(item.ranges) && item.ranges.every((r2) => r2 instanceof $BT);
  }
  DocumentContextItem2.is = is;
  function from(item) {
    return {
      uri: item.uri,
      version: item.version,
      ranges: item.ranges.map((r2) => Range4.from(r2))
    };
  }
  DocumentContextItem2.from = from;
  function to(item) {
    return {
      uri: URI.revive(item.uri),
      version: item.version,
      ranges: item.ranges.map((r2) => Range4.to(r2))
    };
  }
  DocumentContextItem2.to = to;
})(DocumentContextItem || (DocumentContextItem = {}));
var NotebookRange;
(function(NotebookRange2) {
  function from(range) {
    return { start: range.start, end: range.end };
  }
  NotebookRange2.from = from;
  function to(range) {
    return new $6U(range.start, range.end);
  }
  NotebookRange2.to = to;
})(NotebookRange || (NotebookRange = {}));
var NotebookCellExecutionSummary;
(function(NotebookCellExecutionSummary2) {
  function to(data) {
    return {
      timing: typeof data.runStartTime === "number" && typeof data.runEndTime === "number" ? { startTime: data.runStartTime, endTime: data.runEndTime } : void 0,
      executionOrder: data.executionOrder,
      success: data.lastRunSuccess
    };
  }
  NotebookCellExecutionSummary2.to = to;
  function from(data) {
    return {
      lastRunSuccess: data.success,
      runStartTime: data.timing?.startTime,
      runEndTime: data.timing?.endTime,
      executionOrder: data.executionOrder
    };
  }
  NotebookCellExecutionSummary2.from = from;
})(NotebookCellExecutionSummary || (NotebookCellExecutionSummary = {}));
var NotebookCellExecutionState3;
(function(NotebookCellExecutionState4) {
  function to(state) {
    if (state === NotebookCellExecutionState.Unconfirmed) {
      return NotebookCellExecutionState2.Pending;
    } else if (state === NotebookCellExecutionState.Pending) {
      return void 0;
    } else if (state === NotebookCellExecutionState.Executing) {
      return NotebookCellExecutionState2.Executing;
    } else {
      throw new Error(`Unknown state: ${state}`);
    }
  }
  NotebookCellExecutionState4.to = to;
})(NotebookCellExecutionState3 || (NotebookCellExecutionState3 = {}));
var NotebookCellKind2;
(function(NotebookCellKind3) {
  function from(data) {
    switch (data) {
      case NotebookCellKind.Markup:
        return CellKind.Markup;
      case NotebookCellKind.Code:
      default:
        return CellKind.Code;
    }
  }
  NotebookCellKind3.from = from;
  function to(data) {
    switch (data) {
      case CellKind.Markup:
        return NotebookCellKind.Markup;
      case CellKind.Code:
      default:
        return NotebookCellKind.Code;
    }
  }
  NotebookCellKind3.to = to;
})(NotebookCellKind2 || (NotebookCellKind2 = {}));
var NotebookData;
(function(NotebookData2) {
  function from(data) {
    const res = {
      metadata: data.metadata ?? /* @__PURE__ */ Object.create(null),
      cells: []
    };
    for (const cell of data.cells) {
      $7U.validate(cell);
      res.cells.push(NotebookCellData.from(cell));
    }
    return res;
  }
  NotebookData2.from = from;
  function to(data) {
    const res = new $8U(data.cells.map(NotebookCellData.to));
    if (!$Mg(data.metadata)) {
      res.metadata = data.metadata;
    }
    return res;
  }
  NotebookData2.to = to;
})(NotebookData || (NotebookData = {}));
var NotebookCellData;
(function(NotebookCellData2) {
  function from(data) {
    return {
      cellKind: NotebookCellKind2.from(data.kind),
      language: data.languageId,
      mime: data.mime,
      source: data.value,
      metadata: data.metadata,
      internalMetadata: NotebookCellExecutionSummary.from(data.executionSummary ?? {}),
      outputs: data.outputs ? data.outputs.map(NotebookCellOutput.from) : []
    };
  }
  NotebookCellData2.from = from;
  function to(data) {
    return new $7U(NotebookCellKind2.to(data.cellKind), data.source, data.language, data.mime, data.outputs ? data.outputs.map(NotebookCellOutput.to) : void 0, data.metadata, data.internalMetadata ? NotebookCellExecutionSummary.to(data.internalMetadata) : void 0);
  }
  NotebookCellData2.to = to;
})(NotebookCellData || (NotebookCellData = {}));
var NotebookCellOutputItem;
(function(NotebookCellOutputItem2) {
  function from(item) {
    return {
      mime: item.mime,
      valueBytes: $Ci.wrap(item.data)
    };
  }
  NotebookCellOutputItem2.from = from;
  function to(item) {
    return new $9U(item.valueBytes.buffer, item.mime);
  }
  NotebookCellOutputItem2.to = to;
})(NotebookCellOutputItem || (NotebookCellOutputItem = {}));
var NotebookCellOutput;
(function(NotebookCellOutput2) {
  function from(output) {
    return {
      outputId: output.id,
      items: output.items.map(NotebookCellOutputItem.from),
      metadata: output.metadata
    };
  }
  NotebookCellOutput2.from = from;
  function to(output) {
    const items = output.items.map(NotebookCellOutputItem.to);
    return new $0U(items, output.outputId, output.metadata);
  }
  NotebookCellOutput2.to = to;
})(NotebookCellOutput || (NotebookCellOutput = {}));
var NotebookExclusiveDocumentPattern;
(function(NotebookExclusiveDocumentPattern2) {
  function from(pattern) {
    if (isExclusivePattern(pattern)) {
      return {
        include: GlobPattern.from(pattern.include) ?? void 0,
        exclude: GlobPattern.from(pattern.exclude) ?? void 0
      };
    }
    return GlobPattern.from(pattern) ?? void 0;
  }
  NotebookExclusiveDocumentPattern2.from = from;
  function to(pattern) {
    if (isExclusivePattern(pattern)) {
      return {
        include: GlobPattern.to(pattern.include),
        exclude: GlobPattern.to(pattern.exclude)
      };
    }
    return GlobPattern.to(pattern);
  }
  NotebookExclusiveDocumentPattern2.to = to;
  function isExclusivePattern(obj) {
    const ep = obj;
    if (!ep) {
      return false;
    }
    return !$Ig(ep.include) && !$Ig(ep.exclude);
  }
})(NotebookExclusiveDocumentPattern || (NotebookExclusiveDocumentPattern = {}));
var NotebookStatusBarItem;
(function(NotebookStatusBarItem2) {
  function from(item, commandsConverter, disposables) {
    const command4 = typeof item.command === "string" ? { title: "", command: item.command } : item.command;
    return {
      alignment: item.alignment === NotebookCellStatusBarAlignment.Left ? 1 : 2,
      command: commandsConverter.toInternal(command4, disposables),
      // TODO@roblou
      text: item.text,
      tooltip: item.tooltip,
      accessibilityInformation: item.accessibilityInformation,
      priority: item.priority
    };
  }
  NotebookStatusBarItem2.from = from;
})(NotebookStatusBarItem || (NotebookStatusBarItem = {}));
var NotebookKernelSourceAction;
(function(NotebookKernelSourceAction2) {
  function from(item, commandsConverter, disposables) {
    const command4 = typeof item.command === "string" ? { title: "", command: item.command } : item.command;
    return {
      command: commandsConverter.toInternal(command4, disposables),
      label: item.label,
      description: item.description,
      detail: item.detail,
      documentation: item.documentation
    };
  }
  NotebookKernelSourceAction2.from = from;
})(NotebookKernelSourceAction || (NotebookKernelSourceAction = {}));
var NotebookDocumentContentOptions;
(function(NotebookDocumentContentOptions2) {
  function from(options3) {
    return {
      transientOutputs: options3?.transientOutputs ?? false,
      transientCellMetadata: options3?.transientCellMetadata ?? {},
      transientDocumentMetadata: options3?.transientDocumentMetadata ?? {},
      cellContentMetadata: options3?.cellContentMetadata ?? {}
    };
  }
  NotebookDocumentContentOptions2.from = from;
})(NotebookDocumentContentOptions || (NotebookDocumentContentOptions = {}));
var NotebookRendererScript;
(function(NotebookRendererScript2) {
  function from(preload) {
    return {
      uri: preload.uri,
      provides: preload.provides
    };
  }
  NotebookRendererScript2.from = from;
  function to(preload) {
    return new $aV(URI.revive(preload.uri), preload.provides);
  }
  NotebookRendererScript2.to = to;
})(NotebookRendererScript || (NotebookRendererScript = {}));
var TestMessage;
(function(TestMessage2) {
  function from(message) {
    return {
      message: MarkdownString.fromStrict(message.message) || "",
      type: 0,
      expected: message.expectedOutput,
      actual: message.actualOutput,
      contextValue: message.contextValue,
      location: message.location && { range: Range4.from(message.location.range), uri: message.location.uri },
      stackTrace: message.stackTrace?.map((s) => ({
        label: s.label,
        position: s.position && Position2.from(s.position),
        uri: s.uri && URI.revive(s.uri).toJSON()
      }))
    };
  }
  TestMessage2.from = from;
  function to(item) {
    const message = new $hV(typeof item.message === "string" ? item.message : MarkdownString.to(item.message));
    message.actualOutput = item.actual;
    message.expectedOutput = item.expected;
    message.contextValue = item.contextValue;
    message.location = item.location ? location2.to(item.location) : void 0;
    return message;
  }
  TestMessage2.to = to;
})(TestMessage || (TestMessage = {}));
var TestTag;
(function(TestTag2) {
  TestTag2.namespace = $sQ;
  TestTag2.denamespace = $tQ;
})(TestTag || (TestTag = {}));
var TestRunProfile;
(function(TestRunProfile2) {
  function from(item) {
    return {
      controllerId: item.controllerId,
      profileId: item.profileId,
      group: TestRunProfileKind2.from(item.kind)
    };
  }
  TestRunProfile2.from = from;
})(TestRunProfile || (TestRunProfile = {}));
var TestRunProfileKind2;
(function(TestRunProfileKind3) {
  const profileGroupToBitset = {
    [TestRunProfileKind.Coverage]: 8,
    [TestRunProfileKind.Debug]: 4,
    [TestRunProfileKind.Run]: 2
  };
  function from(kind) {
    return profileGroupToBitset.hasOwnProperty(kind) ? profileGroupToBitset[kind] : 2;
  }
  TestRunProfileKind3.from = from;
})(TestRunProfileKind2 || (TestRunProfileKind2 = {}));
var TestItem;
(function(TestItem2) {
  function from(item) {
    const ctrlId = $cW(item).controllerId;
    return {
      extId: $mQ.fromExtHostTestItem(item, ctrlId).toString(),
      label: item.label,
      uri: URI.revive(item.uri),
      busy: item.busy,
      tags: item.tags.map((t) => TestTag.namespace(ctrlId, t.id)),
      range: $9C.lift(Range4.from(item.range)),
      description: item.description || null,
      sortText: item.sortText || null,
      error: item.error ? MarkdownString.fromStrict(item.error) || null : null
    };
  }
  TestItem2.from = from;
  function toPlain(item) {
    return {
      parent: void 0,
      error: void 0,
      id: $mQ.fromString(item.extId).localId,
      label: item.label,
      uri: URI.revive(item.uri),
      tags: (item.tags || []).map((t) => {
        const { tagId } = TestTag.denamespace(t);
        return new $iV(tagId);
      }),
      children: {
        add: () => {
        },
        delete: () => {
        },
        forEach: () => {
        },
        *[Symbol.iterator]() {
        },
        get: () => void 0,
        replace: () => {
        },
        size: 0
      },
      range: Range4.to(item.range || void 0),
      canResolveChildren: false,
      busy: item.busy,
      description: item.description || void 0,
      sortText: item.sortText || void 0
    };
  }
  TestItem2.toPlain = toPlain;
})(TestItem || (TestItem = {}));
(function(TestTag2) {
  function from(tag2) {
    return { id: tag2.id };
  }
  TestTag2.from = from;
  function to(tag2) {
    return new $iV(tag2.id);
  }
  TestTag2.to = to;
})(TestTag || (TestTag = {}));
var TestResults;
(function(TestResults2) {
  const convertTestResultItem = (node, parent) => {
    const item = node.value;
    if (!item) {
      return void 0;
    }
    const snapshot = {
      ...TestItem.toPlain(item.item),
      parent,
      taskStates: item.tasks.map((t) => ({
        state: t.state,
        duration: t.duration,
        messages: t.messages.filter(
          (m) => m.type === 0
          /* TestMessageType.Error */
        ).map(TestMessage.to)
      })),
      children: []
    };
    if (node.children) {
      for (const child of node.children.values()) {
        const c = convertTestResultItem(child, snapshot);
        if (c) {
          snapshot.children.push(c);
        }
      }
    }
    return snapshot;
  };
  function to(serialized) {
    const tree = new $lQ();
    for (const item of serialized.items) {
      tree.insert($mQ.fromString(item.item.extId).path, item);
    }
    const queue = [tree.nodes];
    const roots = [];
    while (queue.length) {
      for (const node of queue.pop()) {
        if (node.value) {
          roots.push(node);
        } else if (node.children) {
          queue.push(node.children.values());
        }
      }
    }
    return {
      completedAt: serialized.completedAt,
      results: roots.map((r2) => convertTestResultItem(r2)).filter($Hg)
    };
  }
  TestResults2.to = to;
})(TestResults || (TestResults = {}));
var TestCoverage;
(function(TestCoverage2) {
  function fromCoverageCount(count) {
    return { covered: count.covered, total: count.total };
  }
  function fromLocation(location3) {
    return "line" in location3 ? Position2.from(location3) : Range4.from(location3);
  }
  function toLocation(location3) {
    if (!location3) {
      return void 0;
    }
    return "endLineNumber" in location3 ? Range4.to(location3) : Position2.to(location3);
  }
  function to(serialized) {
    if (serialized.type === 1) {
      const branches = [];
      if (serialized.branches) {
        for (const branch of serialized.branches) {
          branches.push({
            executed: branch.count,
            location: toLocation(branch.location),
            label: branch.label
          });
        }
      }
      return new $nV(serialized.count, toLocation(serialized.location), serialized.branches?.map((b) => new $oV(b.count, toLocation(b.location), b.label)));
    } else {
      return new $pV(serialized.name, serialized.count, toLocation(serialized.location));
    }
  }
  TestCoverage2.to = to;
  function fromDetails(coverage) {
    if (typeof coverage.executed === "number" && coverage.executed < 0) {
      throw new Error(`Invalid coverage count ${coverage.executed}`);
    }
    if ("branches" in coverage) {
      return {
        count: coverage.executed,
        location: fromLocation(coverage.location),
        type: 1,
        branches: coverage.branches.length ? coverage.branches.map((b) => ({ count: b.executed, location: b.location && fromLocation(b.location), label: b.label })) : void 0
      };
    } else {
      return {
        type: 0,
        name: coverage.name,
        count: coverage.executed,
        location: fromLocation(coverage.location)
      };
    }
  }
  TestCoverage2.fromDetails = fromDetails;
  function fromFile(controllerId, id2, coverage) {
    $lV(coverage.statementCoverage);
    $lV(coverage.branchCoverage);
    $lV(coverage.declarationCoverage);
    return {
      id: id2,
      uri: coverage.uri,
      statement: fromCoverageCount(coverage.statementCoverage),
      branch: coverage.branchCoverage && fromCoverageCount(coverage.branchCoverage),
      declaration: coverage.declarationCoverage && fromCoverageCount(coverage.declarationCoverage),
      testIds: coverage instanceof $mV && coverage.includesTests.length ? coverage.includesTests.map((t) => $mQ.fromExtHostTestItem(t, controllerId).toString()) : void 0
    };
  }
  TestCoverage2.fromFile = fromFile;
})(TestCoverage || (TestCoverage = {}));
var CodeActionTriggerKind2;
(function(CodeActionTriggerKind3) {
  function to(value) {
    switch (value) {
      case 1:
        return CodeActionTriggerKind.Invoke;
      case 2:
        return CodeActionTriggerKind.Automatic;
    }
  }
  CodeActionTriggerKind3.to = to;
})(CodeActionTriggerKind2 || (CodeActionTriggerKind2 = {}));
var TypeHierarchyItem;
(function(TypeHierarchyItem2) {
  function to(item) {
    const result = new $qV(SymbolKind3.to(item.kind), item.name, item.detail || "", URI.revive(item.uri), Range4.to(item.range), Range4.to(item.selectionRange));
    result._sessionId = item._sessionId;
    result._itemId = item._itemId;
    return result;
  }
  TypeHierarchyItem2.to = to;
  function from(item, sessionId, itemId) {
    sessionId = sessionId ?? item._sessionId;
    itemId = itemId ?? item._itemId;
    if (sessionId === void 0 || itemId === void 0) {
      throw new Error("invalid item");
    }
    return {
      _sessionId: sessionId,
      _itemId: itemId,
      kind: SymbolKind3.from(item.kind),
      name: item.name,
      detail: item.detail ?? "",
      uri: item.uri,
      range: Range4.from(item.range),
      selectionRange: Range4.from(item.selectionRange),
      tags: item.tags?.map(SymbolTag3.from)
    };
  }
  TypeHierarchyItem2.from = from;
})(TypeHierarchyItem || (TypeHierarchyItem = {}));
var ViewBadge2;
(function(ViewBadge3) {
  function from(badge) {
    if (!badge) {
      return void 0;
    }
    return {
      value: badge.value,
      tooltip: badge.tooltip
    };
  }
  ViewBadge3.from = from;
})(ViewBadge2 || (ViewBadge2 = {}));
var DataTransferItem;
(function(DataTransferItem2) {
  function to(mime, item, resolveFileData) {
    const file = item.fileData;
    if (file) {
      return new $uU(new $vU(file.name, URI.revive(file.uri), file.id, $Qc(() => resolveFileData(file.id))));
    }
    if (mime === $YC.uriList && item.uriListData) {
      return new $tU(reviveUriList(item.uriListData));
    }
    return new $tU(item.asString);
  }
  DataTransferItem2.to = to;
  async function from(mime, item) {
    const stringValue = await item.asString();
    if (mime === $YC.uriList) {
      return {
        asString: stringValue,
        fileData: void 0,
        uriListData: serializeUriList(stringValue)
      };
    }
    const fileValue = item.asFile();
    return {
      asString: stringValue,
      fileData: fileValue ? {
        name: fileValue.name,
        uri: fileValue.uri,
        id: fileValue._itemId ?? fileValue.id
      } : void 0
    };
  }
  DataTransferItem2.from = from;
  function serializeUriList(stringValue) {
    return $nE.split(stringValue).map((part) => {
      if (part.startsWith("#")) {
        return part;
      }
      try {
        return URI.parse(part);
      } catch {
      }
      return part;
    });
  }
  function reviveUriList(parts) {
    return $nE.create(parts.map((part) => {
      return typeof part === "string" ? part : URI.revive(part);
    }));
  }
})(DataTransferItem || (DataTransferItem = {}));
var DataTransfer;
(function(DataTransfer2) {
  function toDataTransfer(value, resolveFileData) {
    const init = value.items.map(([type, item]) => {
      return [type, DataTransferItem.to(type, item, resolveFileData)];
    });
    return new $wU(init);
  }
  DataTransfer2.toDataTransfer = toDataTransfer;
  async function from(dataTransfer) {
    const newDTO = { items: [] };
    const promises = [];
    for (const [mime, value] of dataTransfer) {
      promises.push((async () => {
        newDTO.items.push([mime, await DataTransferItem.from(mime, value)]);
      })());
    }
    await Promise.all(promises);
    return newDTO;
  }
  DataTransfer2.from = from;
})(DataTransfer || (DataTransfer = {}));
var ChatFollowup;
(function(ChatFollowup2) {
  function from(followup, request) {
    return {
      kind: "reply",
      agentId: followup.participant ?? request?.agentId ?? "",
      subCommand: followup.command ?? request?.command,
      message: followup.prompt,
      title: followup.label
    };
  }
  ChatFollowup2.from = from;
  function to(followup) {
    return {
      prompt: followup.message,
      label: followup.title,
      participant: followup.agentId,
      command: followup.subCommand
    };
  }
  ChatFollowup2.to = to;
})(ChatFollowup || (ChatFollowup = {}));
var LanguageModelChatMessageRole2;
(function(LanguageModelChatMessageRole3) {
  function to(role) {
    switch (role) {
      case 0:
        return LanguageModelChatMessageRole.System;
      case 1:
        return LanguageModelChatMessageRole.User;
      case 2:
        return LanguageModelChatMessageRole.Assistant;
    }
  }
  LanguageModelChatMessageRole3.to = to;
  function from(role) {
    switch (role) {
      case LanguageModelChatMessageRole.System:
        return 0;
      case LanguageModelChatMessageRole.User:
        return 1;
      case LanguageModelChatMessageRole.Assistant:
        return 2;
    }
    return 1;
  }
  LanguageModelChatMessageRole3.from = from;
})(LanguageModelChatMessageRole2 || (LanguageModelChatMessageRole2 = {}));
var LanguageModelChatMessage;
(function(LanguageModelChatMessage2) {
  function to(message) {
    const content = message.content.map((c) => {
      if (c.type === "text") {
        return new $1V(c.value);
      } else if (c.type === "tool_result") {
        const content2 = c.value.map((part) => {
          if (part.type === "text") {
            return new $1V(part.value);
          } else {
            return new $2V(part.value);
          }
        });
        return new $XV(c.toolCallId, content2, c.isError);
      } else {
        return new $ZV(c.toolCallId, c.name, c.parameters);
      }
    });
    const role = LanguageModelChatMessageRole2.to(message.role);
    const result = new $YV(role, content, message.name);
    return result;
  }
  LanguageModelChatMessage2.to = to;
  function from(message) {
    const role = LanguageModelChatMessageRole2.from(message.role);
    const name = message.name;
    let messageContent = message.content;
    if (typeof messageContent === "string") {
      messageContent = [new $1V(messageContent)];
    }
    const content = messageContent.map((c) => {
      if (c instanceof $XV) {
        return {
          type: "tool_result",
          toolCallId: c.callId,
          value: $Mb(c.content.map((part) => {
            if (part instanceof $1V) {
              return {
                type: "text",
                value: part.value
              };
            } else if (part instanceof $2V) {
              return {
                type: "prompt_tsx",
                value: part.value
              };
            } else {
              return void 0;
            }
          })),
          isError: c.isError
        };
      } else if (c instanceof $ZV) {
        return {
          type: "tool_use",
          toolCallId: c.callId,
          name: c.name,
          parameters: c.input
        };
      } else if (c instanceof $1V) {
        return {
          type: "text",
          value: c.value
        };
      } else {
        if (typeof c !== "string") {
          throw new Error("Unexpected chat message content type");
        }
        return {
          type: "text",
          value: c
        };
      }
    });
    return {
      role,
      name,
      content
    };
  }
  LanguageModelChatMessage2.from = from;
})(LanguageModelChatMessage || (LanguageModelChatMessage = {}));
var ChatResponseMarkdownPart;
(function(ChatResponseMarkdownPart2) {
  function from(part) {
    return {
      kind: "markdownContent",
      content: MarkdownString.from(part.value)
    };
  }
  ChatResponseMarkdownPart2.from = from;
  function to(part) {
    return new $DV(MarkdownString.to(part.content));
  }
  ChatResponseMarkdownPart2.to = to;
})(ChatResponseMarkdownPart || (ChatResponseMarkdownPart = {}));
var ChatResponseCodeblockUriPart;
(function(ChatResponseCodeblockUriPart2) {
  function from(part) {
    return {
      kind: "codeblockUri",
      uri: part.value
    };
  }
  ChatResponseCodeblockUriPart2.from = from;
  function to(part) {
    return new $OV(URI.revive(part.uri));
  }
  ChatResponseCodeblockUriPart2.to = to;
})(ChatResponseCodeblockUriPart || (ChatResponseCodeblockUriPart = {}));
var ChatResponseMarkdownWithVulnerabilitiesPart;
(function(ChatResponseMarkdownWithVulnerabilitiesPart2) {
  function from(part) {
    return {
      kind: "markdownVuln",
      content: MarkdownString.from(part.value),
      vulnerabilities: part.vulnerabilities
    };
  }
  ChatResponseMarkdownWithVulnerabilitiesPart2.from = from;
  function to(part) {
    return new $EV(MarkdownString.to(part.content), part.vulnerabilities);
  }
  ChatResponseMarkdownWithVulnerabilitiesPart2.to = to;
})(ChatResponseMarkdownWithVulnerabilitiesPart || (ChatResponseMarkdownWithVulnerabilitiesPart = {}));
var ChatResponseDetectedParticipantPart;
(function(ChatResponseDetectedParticipantPart2) {
  function from(part) {
    return {
      kind: "agentDetection",
      agentId: part.participant,
      command: part.command
    };
  }
  ChatResponseDetectedParticipantPart2.from = from;
  function to(part) {
    return new $FV(part.agentId, part.command);
  }
  ChatResponseDetectedParticipantPart2.to = to;
})(ChatResponseDetectedParticipantPart || (ChatResponseDetectedParticipantPart = {}));
var ChatResponseConfirmationPart;
(function(ChatResponseConfirmationPart2) {
  function from(part) {
    return {
      kind: "confirmation",
      title: part.title,
      message: part.message,
      data: part.data,
      buttons: part.buttons
    };
  }
  ChatResponseConfirmationPart2.from = from;
})(ChatResponseConfirmationPart || (ChatResponseConfirmationPart = {}));
var ChatResponseFilesPart;
(function(ChatResponseFilesPart2) {
  function from(part) {
    const { value, baseUri } = part;
    function convert(items, baseUri2) {
      return items.map((item) => {
        const myUri = URI.joinPath(baseUri2, item.name);
        return {
          label: item.name,
          uri: myUri,
          children: item.children && convert(item.children, myUri)
        };
      });
    }
    return {
      kind: "treeData",
      treeData: {
        label: $sh(baseUri),
        uri: baseUri,
        children: convert(value, baseUri)
      }
    };
  }
  ChatResponseFilesPart2.from = from;
  function to(part) {
    const treeData = $cu(part.treeData);
    function convert(items2) {
      return items2.map((item) => {
        return {
          name: item.label,
          children: item.children && convert(item.children)
        };
      });
    }
    const baseUri = treeData.uri;
    const items = treeData.children ? convert(treeData.children) : [];
    return new $HV(items, baseUri);
  }
  ChatResponseFilesPart2.to = to;
})(ChatResponseFilesPart || (ChatResponseFilesPart = {}));
var ChatResponseAnchorPart;
(function(ChatResponseAnchorPart2) {
  function from(part) {
    const isUri = (thing) => URI.isUri(thing);
    const isSymbolInformation = (thing) => "name" in thing;
    return {
      kind: "inlineReference",
      name: part.title,
      inlineReference: isUri(part.value) ? part.value : isSymbolInformation(part.value) ? WorkspaceSymbol.from(part.value) : Location.from(part.value)
    };
  }
  ChatResponseAnchorPart2.from = from;
  function to(part) {
    const value = $cu(part);
    return new $IV(URI.isUri(value.inlineReference) ? value.inlineReference : "location" in value.inlineReference ? WorkspaceSymbol.to(value.inlineReference) : Location.to(value.inlineReference), part.name);
  }
  ChatResponseAnchorPart2.to = to;
})(ChatResponseAnchorPart || (ChatResponseAnchorPart = {}));
var ChatResponseProgressPart;
(function(ChatResponseProgressPart2) {
  function from(part) {
    return {
      kind: "progressMessage",
      content: MarkdownString.from(part.value)
    };
  }
  ChatResponseProgressPart2.from = from;
  function to(part) {
    return new $JV(part.content.value);
  }
  ChatResponseProgressPart2.to = to;
})(ChatResponseProgressPart || (ChatResponseProgressPart = {}));
var ChatResponseWarningPart;
(function(ChatResponseWarningPart2) {
  function from(part) {
    return {
      kind: "warning",
      content: MarkdownString.from(part.value)
    };
  }
  ChatResponseWarningPart2.from = from;
  function to(part) {
    return new $LV(part.content.value);
  }
  ChatResponseWarningPart2.to = to;
})(ChatResponseWarningPart || (ChatResponseWarningPart = {}));
var ChatResponseMovePart;
(function(ChatResponseMovePart2) {
  function from(part) {
    return {
      kind: "move",
      uri: part.uri,
      range: Range4.from(part.range)
    };
  }
  ChatResponseMovePart2.from = from;
  function to(part) {
    return new $QV(URI.revive(part.uri), Range4.to(part.range));
  }
  ChatResponseMovePart2.to = to;
})(ChatResponseMovePart || (ChatResponseMovePart = {}));
var ChatTask;
(function(ChatTask2) {
  function from(part) {
    return {
      kind: "progressTask",
      content: MarkdownString.from(part.value)
    };
  }
  ChatTask2.from = from;
})(ChatTask || (ChatTask = {}));
var ChatTaskResult;
(function(ChatTaskResult2) {
  function from(part) {
    return {
      kind: "progressTaskResult",
      content: typeof part === "string" ? MarkdownString.from(part) : void 0
    };
  }
  ChatTaskResult2.from = from;
})(ChatTaskResult || (ChatTaskResult = {}));
var ChatResponseCommandButtonPart;
(function(ChatResponseCommandButtonPart2) {
  function from(part, commandsConverter, commandDisposables) {
    const command4 = commandsConverter.toInternal(part.value, commandDisposables) ?? { command: part.value.command, title: part.value.title };
    return {
      kind: "command",
      command: command4
    };
  }
  ChatResponseCommandButtonPart2.from = from;
  function to(part, commandsConverter) {
    return new $MV(commandsConverter.fromInternal(part.command) ?? { command: part.command.id, title: part.command.title });
  }
  ChatResponseCommandButtonPart2.to = to;
})(ChatResponseCommandButtonPart || (ChatResponseCommandButtonPart = {}));
var ChatResponseTextEditPart;
(function(ChatResponseTextEditPart2) {
  function from(part) {
    return {
      kind: "textEdit",
      uri: part.uri,
      edits: part.edits.map((e) => TextEdit.from(e)),
      done: part.isDone
    };
  }
  ChatResponseTextEditPart2.from = from;
  function to(part) {
    const result = new $RV(URI.revive(part.uri), part.edits.map((e) => TextEdit.to(e)));
    result.isDone = part.done;
    return result;
  }
  ChatResponseTextEditPart2.to = to;
})(ChatResponseTextEditPart || (ChatResponseTextEditPart = {}));
var ChatResponseReferencePart;
(function(ChatResponseReferencePart2) {
  function from(part) {
    const iconPath = ThemeIcon.isThemeIcon(part.iconPath) ? part.iconPath : URI.isUri(part.iconPath) ? { light: URI.revive(part.iconPath) } : part.iconPath && "light" in part.iconPath && "dark" in part.iconPath && URI.isUri(part.iconPath.light) && URI.isUri(part.iconPath.dark) ? { light: URI.revive(part.iconPath.light), dark: URI.revive(part.iconPath.dark) } : void 0;
    if (typeof part.value === "object" && "variableName" in part.value) {
      return {
        kind: "reference",
        reference: {
          variableName: part.value.variableName,
          value: URI.isUri(part.value.value) || !part.value.value ? part.value.value : Location.from(part.value.value)
        },
        iconPath,
        options: part.options
      };
    }
    return {
      kind: "reference",
      reference: URI.isUri(part.value) || typeof part.value === "string" ? part.value : Location.from(part.value),
      iconPath,
      options: part.options
    };
  }
  ChatResponseReferencePart2.from = from;
  function to(part) {
    const value = $cu(part);
    const mapValue = (value2) => URI.isUri(value2) ? value2 : Location.to(value2);
    return new $NV(typeof value.reference === "string" ? value.reference : "variableName" in value.reference ? {
      variableName: value.reference.variableName,
      value: value.reference.value && mapValue(value.reference.value)
    } : mapValue(value.reference));
  }
  ChatResponseReferencePart2.to = to;
})(ChatResponseReferencePart || (ChatResponseReferencePart = {}));
var ChatResponseCodeCitationPart;
(function(ChatResponseCodeCitationPart2) {
  function from(part) {
    return {
      kind: "codeCitation",
      value: part.value,
      license: part.license,
      snippet: part.snippet
    };
  }
  ChatResponseCodeCitationPart2.from = from;
})(ChatResponseCodeCitationPart || (ChatResponseCodeCitationPart = {}));
var ChatResponsePart;
(function(ChatResponsePart2) {
  function from(part, commandsConverter, commandDisposables) {
    if (part instanceof $DV) {
      return ChatResponseMarkdownPart.from(part);
    } else if (part instanceof $IV) {
      return ChatResponseAnchorPart.from(part);
    } else if (part instanceof $NV) {
      return ChatResponseReferencePart.from(part);
    } else if (part instanceof $JV) {
      return ChatResponseProgressPart.from(part);
    } else if (part instanceof $HV) {
      return ChatResponseFilesPart.from(part);
    } else if (part instanceof $MV) {
      return ChatResponseCommandButtonPart.from(part, commandsConverter, commandDisposables);
    } else if (part instanceof $RV) {
      return ChatResponseTextEditPart.from(part);
    } else if (part instanceof $EV) {
      return ChatResponseMarkdownWithVulnerabilitiesPart.from(part);
    } else if (part instanceof $OV) {
      return ChatResponseCodeblockUriPart.from(part);
    } else if (part instanceof $FV) {
      return ChatResponseDetectedParticipantPart.from(part);
    } else if (part instanceof $LV) {
      return ChatResponseWarningPart.from(part);
    } else if (part instanceof $GV) {
      return ChatResponseConfirmationPart.from(part);
    } else if (part instanceof $PV) {
      return ChatResponseCodeCitationPart.from(part);
    } else if (part instanceof $QV) {
      return ChatResponseMovePart.from(part);
    }
    return {
      kind: "markdownContent",
      content: MarkdownString.from("")
    };
  }
  ChatResponsePart2.from = from;
  function to(part, commandsConverter) {
    switch (part.kind) {
      case "reference":
        return ChatResponseReferencePart.to(part);
      case "markdownContent":
      case "inlineReference":
      case "progressMessage":
      case "treeData":
      case "command":
        return toContent(part, commandsConverter);
    }
    return void 0;
  }
  ChatResponsePart2.to = to;
  function toContent(part, commandsConverter) {
    switch (part.kind) {
      case "markdownContent":
        return ChatResponseMarkdownPart.to(part);
      case "inlineReference":
        return ChatResponseAnchorPart.to(part);
      case "progressMessage":
        return void 0;
      case "treeData":
        return ChatResponseFilesPart.to(part);
      case "command":
        return ChatResponseCommandButtonPart.to(part, commandsConverter);
    }
    return void 0;
  }
  ChatResponsePart2.toContent = toContent;
})(ChatResponsePart || (ChatResponsePart = {}));
var ChatAgentRequest;
(function(ChatAgentRequest2) {
  function to(request, location22, model) {
    const toolReferences = request.variables.variables.filter((v) => v.isTool);
    const variableReferences = request.variables.variables.filter((v) => !v.isTool);
    return {
      prompt: request.message,
      command: request.command,
      attempt: request.attempt ?? 0,
      enableCommandDetection: request.enableCommandDetection ?? true,
      isParticipantDetected: request.isParticipantDetected ?? false,
      references: variableReferences.map(ChatPromptReference.to),
      toolReferences: toolReferences.map(ChatLanguageModelToolReference.to),
      location: ChatLocation2.to(request.location),
      acceptedConfirmationData: request.acceptedConfirmationData,
      rejectedConfirmationData: request.rejectedConfirmationData,
      location2: location22,
      toolInvocationToken: Object.freeze({ sessionId: request.sessionId }),
      model
    };
  }
  ChatAgentRequest2.to = to;
})(ChatAgentRequest || (ChatAgentRequest = {}));
var ChatRequestDraft;
(function(ChatRequestDraft2) {
  function to(request) {
    return {
      prompt: request.prompt,
      files: request.files.map((uri) => URI.revive(uri))
    };
  }
  ChatRequestDraft2.to = to;
})(ChatRequestDraft || (ChatRequestDraft = {}));
var ChatLocation2;
(function(ChatLocation3) {
  function to(loc) {
    switch (loc) {
      case ChatAgentLocation.Notebook:
        return ChatLocation.Notebook;
      case ChatAgentLocation.Terminal:
        return ChatLocation.Terminal;
      case ChatAgentLocation.Panel:
        return ChatLocation.Panel;
      case ChatAgentLocation.Editor:
        return ChatLocation.Editor;
      case ChatAgentLocation.EditingSession:
        return ChatLocation.EditingSession;
    }
  }
  ChatLocation3.to = to;
  function from(loc) {
    switch (loc) {
      case ChatLocation.Notebook:
        return ChatAgentLocation.Notebook;
      case ChatLocation.Terminal:
        return ChatAgentLocation.Terminal;
      case ChatLocation.Panel:
        return ChatAgentLocation.Panel;
      case ChatLocation.Editor:
        return ChatAgentLocation.Editor;
      case ChatLocation.EditingSession:
        return ChatAgentLocation.EditingSession;
    }
  }
  ChatLocation3.from = from;
})(ChatLocation2 || (ChatLocation2 = {}));
var ChatPromptReference;
(function(ChatPromptReference2) {
  function to(variable) {
    const value = variable.value;
    if (!value) {
      throw new Error("Invalid value reference");
    }
    return {
      id: variable.id,
      name: variable.name,
      range: variable.range && [variable.range.start, variable.range.endExclusive],
      value: $zc(value) ? URI.revive(value) : value && typeof value === "object" && "uri" in value && "range" in value && $zc(value.uri) ? Location.to($cu(value)) : variable.isImage ? new $WV(variable.mimeType ?? "image/png", () => Promise.resolve(new Uint8Array(Object.values(value)))) : value,
      modelDescription: variable.modelDescription
    };
  }
  ChatPromptReference2.to = to;
})(ChatPromptReference || (ChatPromptReference = {}));
var ChatLanguageModelToolReference;
(function(ChatLanguageModelToolReference2) {
  function to(variable) {
    const value = variable.value;
    if (value) {
      throw new Error("Invalid tool reference");
    }
    return {
      name: variable.id,
      range: variable.range && [variable.range.start, variable.range.endExclusive]
    };
  }
  ChatLanguageModelToolReference2.to = to;
})(ChatLanguageModelToolReference || (ChatLanguageModelToolReference = {}));
var ChatAgentCompletionItem;
(function(ChatAgentCompletionItem2) {
  function from(item, commandsConverter, disposables) {
    return {
      id: item.id,
      label: item.label,
      fullName: item.fullName,
      icon: item.icon?.id,
      value: item.values[0].value,
      insertText: item.insertText,
      detail: item.detail,
      documentation: item.documentation,
      command: commandsConverter.toInternal(item.command, disposables)
    };
  }
  ChatAgentCompletionItem2.from = from;
})(ChatAgentCompletionItem || (ChatAgentCompletionItem = {}));
var ChatAgentResult;
(function(ChatAgentResult2) {
  function to(result) {
    return {
      errorDetails: result.errorDetails,
      metadata: reviveMetadata(result.metadata),
      nextQuestion: result.nextQuestion
    };
  }
  ChatAgentResult2.to = to;
  function from(result) {
    return {
      errorDetails: result.errorDetails,
      metadata: result.metadata,
      nextQuestion: result.nextQuestion
    };
  }
  ChatAgentResult2.from = from;
  function reviveMetadata(metadata) {
    return $Nv(metadata, (value) => {
      if (value.$mid === 20) {
        return new $7V($Nv(value.content, reviveMetadata));
      } else if (value.$mid === 21) {
        return new $1V(value.value);
      } else if (value.$mid === 22) {
        return new $2V(value.value);
      }
      return void 0;
    });
  }
})(ChatAgentResult || (ChatAgentResult = {}));
var ChatAgentUserActionEvent;
(function(ChatAgentUserActionEvent2) {
  function to(result, event, commandsConverter) {
    if (event.action.kind === "vote") {
      return;
    }
    const ehResult = ChatAgentResult.to(result);
    if (event.action.kind === "command") {
      const command4 = event.action.commandButton.command;
      const commandButton = {
        command: commandsConverter.fromInternal(command4) ?? { command: command4.id, title: command4.title }
      };
      const commandAction = { kind: "command", commandButton };
      return { action: commandAction, result: ehResult };
    } else if (event.action.kind === "followUp") {
      const followupAction = { kind: "followUp", followup: ChatFollowup.to(event.action.followup) };
      return { action: followupAction, result: ehResult };
    } else if (event.action.kind === "inlineChat") {
      return { action: { kind: "editor", accepted: event.action.action === "accepted" }, result: ehResult };
    } else if (event.action.kind === "chatEditingSessionAction") {
      const outcomes = /* @__PURE__ */ new Map([
        ["accepted", ChatEditingSessionActionOutcome.Accepted],
        ["rejected", ChatEditingSessionActionOutcome.Rejected],
        ["saved", ChatEditingSessionActionOutcome.Saved]
      ]);
      return {
        action: {
          kind: "chatEditingSessionAction",
          outcome: outcomes.get(event.action.outcome) ?? ChatEditingSessionActionOutcome.Rejected,
          uri: URI.revive(event.action.uri),
          hasRemainingEdits: event.action.hasRemainingEdits
        },
        result: ehResult
      };
    } else {
      return { action: event.action, result: ehResult };
    }
  }
  ChatAgentUserActionEvent2.to = to;
})(ChatAgentUserActionEvent || (ChatAgentUserActionEvent = {}));
var TerminalQuickFix;
(function(TerminalQuickFix2) {
  function from(quickFix, converter, disposables) {
    if ("terminalCommand" in quickFix) {
      return { terminalCommand: quickFix.terminalCommand, shouldExecute: quickFix.shouldExecute };
    }
    if ("uri" in quickFix) {
      return { uri: quickFix.uri };
    }
    return converter.toInternal(quickFix, disposables);
  }
  TerminalQuickFix2.from = from;
})(TerminalQuickFix || (TerminalQuickFix = {}));
var PartialAcceptInfo;
(function(PartialAcceptInfo2) {
  function to(info) {
    return {
      kind: PartialAcceptTriggerKind3.to(info.kind)
    };
  }
  PartialAcceptInfo2.to = to;
})(PartialAcceptInfo || (PartialAcceptInfo = {}));
var PartialAcceptTriggerKind3;
(function(PartialAcceptTriggerKind5) {
  function to(kind) {
    switch (kind) {
      case 0:
        return PartialAcceptTriggerKind2.Word;
      case 1:
        return PartialAcceptTriggerKind2.Line;
      case 2:
        return PartialAcceptTriggerKind2.Suggest;
      default:
        return PartialAcceptTriggerKind2.Unknown;
    }
  }
  PartialAcceptTriggerKind5.to = to;
})(PartialAcceptTriggerKind3 || (PartialAcceptTriggerKind3 = {}));
var DebugTreeItem;
(function(DebugTreeItem2) {
  function from(item, id2) {
    return {
      id: id2,
      label: item.label,
      description: item.description,
      canEdit: item.canEdit,
      collapsibleState: item.collapsibleState || 0,
      contextValue: item.contextValue
    };
  }
  DebugTreeItem2.from = from;
})(DebugTreeItem || (DebugTreeItem = {}));
var LanguageModelToolDescription;
(function(LanguageModelToolDescription2) {
  function to(item) {
    return {
      // Note- the reason this is a unique 'name' is just to avoid confusion with the toolCallId
      name: item.id,
      description: item.modelDescription,
      inputSchema: item.inputSchema,
      tags: item.tags ?? []
    };
  }
  LanguageModelToolDescription2.to = to;
})(LanguageModelToolDescription || (LanguageModelToolDescription = {}));
var LanguageModelToolResult;
(function(LanguageModelToolResult2) {
  function to(result) {
    return new $7V(result.content.map((item) => {
      if (item.kind === "text") {
        return new $1V(item.value);
      } else {
        return new $2V(item.value);
      }
    }));
  }
  LanguageModelToolResult2.to = to;
  function from(result) {
    return {
      content: result.content.map((item) => {
        if (item instanceof $1V) {
          return {
            kind: "text",
            value: item.value
          };
        } else if (item instanceof $2V) {
          return {
            kind: "promptTsx",
            value: item.value
          };
        } else {
          throw new Error("Unknown LanguageModelToolResult part type");
        }
      })
    };
  }
  LanguageModelToolResult2.from = from;
})(LanguageModelToolResult || (LanguageModelToolResult = {}));

// out-build/vs/workbench/api/common/shared/dataTransferCache.js
var $oQb = class {
  constructor() {
    this.a = 0;
    this.b = /* @__PURE__ */ new Map();
  }
  add(dataTransfer) {
    const requestId = this.a++;
    this.b.set(requestId, $Mb(Array.from(dataTransfer, ([, item]) => item.asFile())));
    return {
      id: requestId,
      dispose: () => {
        this.b.delete(requestId);
      }
    };
  }
  async resolveFileData(requestId, dataItemId) {
    const files = this.b.get(requestId);
    if (!files) {
      throw new Error("No data transfer found");
    }
    const file = files.find((file2) => file2.id === dataItemId);
    if (!file) {
      throw new Error("No matching file found in data transfer");
    }
    return $Ci.wrap(await file.data());
  }
  dispose() {
    this.b.clear();
  }
};

// out-build/vs/editor/common/languageFeatureRegistry.js
function isExclusive(selector) {
  if (typeof selector === "string") {
    return false;
  } else if (Array.isArray(selector)) {
    return selector.every(isExclusive);
  } else {
    return !!selector.exclusive;
  }
}
var MatchCandidate = class {
  constructor(uri, languageId, notebookUri, notebookType, recursive) {
    this.uri = uri;
    this.languageId = languageId;
    this.notebookUri = notebookUri;
    this.notebookType = notebookType;
    this.recursive = recursive;
  }
  equals(other) {
    return this.notebookType === other.notebookType && this.languageId === other.languageId && this.uri.toString() === other.uri.toString() && this.notebookUri?.toString() === other.notebookUri?.toString() && this.recursive === other.recursive;
  }
};
var $bN = class _$bN {
  constructor(f) {
    this.f = f;
    this.c = 0;
    this.d = [];
    this.e = new $ze();
    this.onDidChange = this.e.event;
  }
  register(selector, provider) {
    let entry = {
      selector,
      provider,
      _score: -1,
      _time: this.c++
    };
    this.d.push(entry);
    this.h = void 0;
    this.e.fire(this.d.length);
    return $1c(() => {
      if (entry) {
        const idx = this.d.indexOf(entry);
        if (idx >= 0) {
          this.d.splice(idx, 1);
          this.h = void 0;
          this.e.fire(this.d.length);
          entry = void 0;
        }
      }
    });
  }
  has(model) {
    return this.all(model).length > 0;
  }
  all(model) {
    if (!model) {
      return [];
    }
    this.i(model, false);
    const result = [];
    for (const entry of this.d) {
      if (entry._score > 0) {
        result.push(entry.provider);
      }
    }
    return result;
  }
  allNoModel() {
    return this.d.map((entry) => entry.provider);
  }
  ordered(model, recursive = false) {
    const result = [];
    this.g(model, recursive, (entry) => result.push(entry.provider));
    return result;
  }
  orderedGroups(model) {
    const result = [];
    let lastBucket;
    let lastBucketScore;
    this.g(model, false, (entry) => {
      if (lastBucket && lastBucketScore === entry._score) {
        lastBucket.push(entry.provider);
      } else {
        lastBucketScore = entry._score;
        lastBucket = [entry.provider];
        result.push(lastBucket);
      }
    });
    return result;
  }
  g(model, recursive, callback) {
    this.i(model, recursive);
    for (const entry of this.d) {
      if (entry._score > 0) {
        callback(entry);
      }
    }
  }
  i(model, recursive) {
    const notebookInfo = this.f?.(model.uri);
    const candidate = notebookInfo ? new MatchCandidate(model.uri, model.getLanguageId(), notebookInfo.uri, notebookInfo.type, recursive) : new MatchCandidate(model.uri, model.getLanguageId(), void 0, void 0, recursive);
    if (this.h?.equals(candidate)) {
      return;
    }
    this.h = candidate;
    for (const entry of this.d) {
      entry._score = $qE(entry.selector, candidate.uri, candidate.languageId, $kG(model), candidate.notebookUri, candidate.notebookType);
      if (isExclusive(entry.selector) && entry._score > 0) {
        if (recursive) {
          entry._score = 0;
        } else {
          for (const entry2 of this.d) {
            entry2._score = 0;
          }
          entry._score = 1e3;
          break;
        }
      }
    }
    this.d.sort(_$bN.j);
  }
  static j(a, b) {
    if (a._score < b._score) {
      return 1;
    } else if (a._score > b._score) {
      return -1;
    }
    if (isBuiltinSelector(a.selector) && !isBuiltinSelector(b.selector)) {
      return 1;
    } else if (!isBuiltinSelector(a.selector) && isBuiltinSelector(b.selector)) {
      return -1;
    }
    if (a._time < b._time) {
      return 1;
    } else if (a._time > b._time) {
      return -1;
    } else {
      return 0;
    }
  }
};
function isBuiltinSelector(selector) {
  if (typeof selector === "string") {
    return false;
  }
  if (Array.isArray(selector)) {
    return selector.some(isBuiltinSelector);
  }
  return Boolean(selector.isBuiltin);
}

// out-build/vs/workbench/contrib/callHierarchy/common/callHierarchy.js
var CallHierarchyDirection;
(function(CallHierarchyDirection2) {
  CallHierarchyDirection2["CallsTo"] = "incomingCalls";
  CallHierarchyDirection2["CallsFrom"] = "outgoingCalls";
})(CallHierarchyDirection || (CallHierarchyDirection = {}));
var $cN = new $bN();
var $dN = class _$dN {
  static async create(model, position, token) {
    const [provider] = $cN.ordered(model);
    if (!provider) {
      return void 0;
    }
    const session = await provider.prepareCallHierarchy(model, position, token);
    if (!session) {
      return void 0;
    }
    return new _$dN(session.roots.reduce((p, c) => p + c._sessionId, ""), provider, session.roots, new $6c(session));
  }
  constructor(id2, provider, roots, ref) {
    this.id = id2;
    this.provider = provider;
    this.roots = roots;
    this.ref = ref;
    this.root = roots[0];
  }
  dispose() {
    this.ref.release();
  }
  fork(item) {
    const that = this;
    return new class extends _$dN {
      constructor() {
        super(that.id, that.provider, [item], that.ref.acquire());
      }
    }();
  }
  async resolveIncomingCalls(item, token) {
    try {
      const result = await this.provider.provideIncomingCalls(item, token);
      if ($Qb(result)) {
        return result;
      }
    } catch (e) {
      $hb(e);
    }
    return [];
  }
  async resolveOutgoingCalls(item, token) {
    try {
      const result = await this.provider.provideOutgoingCalls(item, token);
      if ($Qb(result)) {
        return result;
      }
    } catch (e) {
      $hb(e);
    }
    return [];
  }
};
var _models = /* @__PURE__ */ new Map();
$tn.registerCommand("_executePrepareCallHierarchy", async (accessor, ...args2) => {
  const [resource, position] = args2;
  $Jg(URI.isUri(resource));
  $Jg($8C.isIPosition(position));
  const modelService = accessor.get($sG);
  let textModel = modelService.getModel(resource);
  let textModelReference;
  if (!textModel) {
    const textModelService = accessor.get($oG);
    const result = await textModelService.createModelReference(resource);
    textModel = result.object.textEditorModel;
    textModelReference = result;
  }
  try {
    const model = await $dN.create(textModel, position, CancellationToken.None);
    if (!model) {
      return [];
    }
    _models.set(model.id, model);
    _models.forEach((value, key2, map) => {
      if (map.size > 10) {
        value.dispose();
        _models.delete(key2);
      }
    });
    return [model.root];
  } finally {
    textModelReference?.dispose();
  }
});
function isCallHierarchyItemDto(obj) {
  return true;
}
$tn.registerCommand("_executeProvideIncomingCalls", async (_accessor, ...args2) => {
  const [item] = args2;
  $Jg(isCallHierarchyItemDto(item));
  const model = _models.get(item._sessionId);
  if (!model) {
    return void 0;
  }
  return model.resolveIncomingCalls(item, CancellationToken.None);
});
$tn.registerCommand("_executeProvideOutgoingCalls", async (_accessor, ...args2) => {
  const [item] = args2;
  $Jg(isCallHierarchyItemDto(item));
  const model = _models.get(item._sessionId);
  if (!model) {
    return void 0;
  }
  return model.resolveOutgoingCalls(item, CancellationToken.None);
});

// out-build/vs/workbench/contrib/search/common/search.js
var WorkspaceSymbolProviderRegistry;
(function(WorkspaceSymbolProviderRegistry2) {
  const _supports = [];
  function register2(provider) {
    let support = provider;
    if (support) {
      _supports.push(support);
    }
    return {
      dispose() {
        if (support) {
          const idx = _supports.indexOf(support);
          if (idx >= 0) {
            _supports.splice(idx, 1);
            support = void 0;
          }
        }
      }
    };
  }
  WorkspaceSymbolProviderRegistry2.register = register2;
  function all() {
    return _supports.slice(0);
  }
  WorkspaceSymbolProviderRegistry2.all = all;
})(WorkspaceSymbolProviderRegistry || (WorkspaceSymbolProviderRegistry = {}));
var $fO = class {
  constructor(symbol, provider) {
    this.symbol = symbol;
    this.provider = provider;
  }
};
async function $gO(query, token = CancellationToken.None) {
  const all = [];
  const promises = WorkspaceSymbolProviderRegistry.all().map(async (provider) => {
    try {
      const value = await provider.provideWorkspaceSymbols(query, token);
      if (!value) {
        return;
      }
      for (const symbol of value) {
        all.push(new $fO(symbol, provider));
      }
    } catch (err) {
      $hb(err);
    }
  });
  await Promise.all(promises);
  if (token.isCancellationRequested) {
    return [];
  }
  function compareItems(a, b) {
    let res = $Tf(a.symbol.name, b.symbol.name);
    if (res === 0) {
      res = a.symbol.kind - b.symbol.kind;
    }
    if (res === 0) {
      res = $Tf(a.symbol.location.uri.toString(), b.symbol.location.uri.toString());
    }
    if (res === 0) {
      if (a.symbol.location.range && b.symbol.location.range) {
        if (!$9C.areIntersecting(a.symbol.location.range, b.symbol.location.range)) {
          res = $9C.compareRangesUsingStarts(a.symbol.location.range, b.symbol.location.range);
        }
      } else if (a.provider.resolveWorkspaceSymbol && !b.provider.resolveWorkspaceSymbol) {
        res = -1;
      } else if (!a.provider.resolveWorkspaceSymbol && b.provider.resolveWorkspaceSymbol) {
        res = 1;
      }
    }
    if (res === 0) {
      res = $Tf(a.symbol.containerName ?? "", b.symbol.containerName ?? "");
    }
    return res;
  }
  return $Eb(all, compareItems).map((group2) => group2[0]).flat();
}
function $hO(accessor) {
  const editorService = accessor.get($mJ);
  const contextService = accessor.get($Zk);
  const fileService = accessor.get($km);
  const resources = editorService.editors.map((editor) => $mL.getOriginalUri(editor, { supportSideBySide: SideBySideEditor.PRIMARY })).filter((resource) => !!resource && !contextService.isInsideWorkspace(resource) && fileService.hasProvider(resource));
  return resources;
}
var LINE_COLON_PATTERN = /\s?[#:\(](?:line )?(\d*)(?:[#:,](\d*))?\)?:?\s*$/;
function $iO(filter, unless) {
  if (!filter || unless?.some((value) => {
    const unlessCharPos = filter.indexOf(value);
    return unlessCharPos === 0 || unlessCharPos > 0 && !LINE_COLON_PATTERN.test(filter.substring(unlessCharPos + 1));
  })) {
    return void 0;
  }
  let range = void 0;
  const patternMatch = LINE_COLON_PATTERN.exec(filter);
  if (patternMatch) {
    const startLineNumber = parseInt(patternMatch[1] ?? "", 10);
    if ($Dg(startLineNumber)) {
      range = {
        startLineNumber,
        startColumn: 1,
        endLineNumber: startLineNumber,
        endColumn: 1
      };
      const startColumn = parseInt(patternMatch[2] ?? "", 10);
      if ($Dg(startColumn)) {
        range = {
          startLineNumber: range.startLineNumber,
          startColumn,
          endLineNumber: range.endLineNumber,
          endColumn: startColumn
        };
      }
    } else if (patternMatch[1] === "") {
      range = {
        startLineNumber: 1,
        startColumn: 1,
        endLineNumber: 1,
        endColumn: 1
      };
    }
  }
  if (patternMatch && range) {
    return {
      filter: filter.substr(0, patternMatch.index),
      // clear range suffix from search value
      range
    };
  }
  return void 0;
}
var SearchUIState;
(function(SearchUIState2) {
  SearchUIState2[SearchUIState2["Idle"] = 0] = "Idle";
  SearchUIState2[SearchUIState2["Searching"] = 1] = "Searching";
  SearchUIState2[SearchUIState2["SlowSearch"] = 2] = "SlowSearch";
})(SearchUIState || (SearchUIState = {}));
var $jO = new $nn("searchState", SearchUIState.Idle);

// out-build/vs/workbench/contrib/typeHierarchy/common/typeHierarchy.js
var TypeHierarchyDirection;
(function(TypeHierarchyDirection2) {
  TypeHierarchyDirection2["Subtypes"] = "subtypes";
  TypeHierarchyDirection2["Supertypes"] = "supertypes";
})(TypeHierarchyDirection || (TypeHierarchyDirection = {}));
var $tS = new $bN();
var $uS = class _$uS {
  static async create(model, position, token) {
    const [provider] = $tS.ordered(model);
    if (!provider) {
      return void 0;
    }
    const session = await provider.prepareTypeHierarchy(model, position, token);
    if (!session) {
      return void 0;
    }
    return new _$uS(session.roots.reduce((p, c) => p + c._sessionId, ""), provider, session.roots, new $6c(session));
  }
  constructor(id2, provider, roots, ref) {
    this.id = id2;
    this.provider = provider;
    this.roots = roots;
    this.ref = ref;
    this.root = roots[0];
  }
  dispose() {
    this.ref.release();
  }
  fork(item) {
    const that = this;
    return new class extends _$uS {
      constructor() {
        super(that.id, that.provider, [item], that.ref.acquire());
      }
    }();
  }
  async provideSupertypes(item, token) {
    try {
      const result = await this.provider.provideSupertypes(item, token);
      if ($Qb(result)) {
        return result;
      }
    } catch (e) {
      $hb(e);
    }
    return [];
  }
  async provideSubtypes(item, token) {
    try {
      const result = await this.provider.provideSubtypes(item, token);
      if ($Qb(result)) {
        return result;
      }
    } catch (e) {
      $hb(e);
    }
    return [];
  }
};
var _models2 = /* @__PURE__ */ new Map();
$tn.registerCommand("_executePrepareTypeHierarchy", async (accessor, ...args2) => {
  const [resource, position] = args2;
  $Jg(URI.isUri(resource));
  $Jg($8C.isIPosition(position));
  const modelService = accessor.get($sG);
  let textModel = modelService.getModel(resource);
  let textModelReference;
  if (!textModel) {
    const textModelService = accessor.get($oG);
    const result = await textModelService.createModelReference(resource);
    textModel = result.object.textEditorModel;
    textModelReference = result;
  }
  try {
    const model = await $uS.create(textModel, position, CancellationToken.None);
    if (!model) {
      return [];
    }
    _models2.set(model.id, model);
    _models2.forEach((value, key2, map) => {
      if (map.size > 10) {
        value.dispose();
        _models2.delete(key2);
      }
    });
    return [model.root];
  } finally {
    textModelReference?.dispose();
  }
});
function isTypeHierarchyItemDto(obj) {
  const item = obj;
  return typeof obj === "object" && typeof item.name === "string" && typeof item.kind === "number" && URI.isUri(item.uri) && $9C.isIRange(item.range) && $9C.isIRange(item.selectionRange);
}
$tn.registerCommand("_executeProvideSupertypes", async (_accessor, ...args2) => {
  const [item] = args2;
  $Jg(isTypeHierarchyItemDto(item));
  const model = _models2.get(item._sessionId);
  if (!model) {
    return void 0;
  }
  return model.provideSupertypes(item, CancellationToken.None);
});
$tn.registerCommand("_executeProvideSubtypes", async (_accessor, ...args2) => {
  const [item] = args2;
  $Jg(isTypeHierarchyItemDto(item));
  const model = _models2.get(item._sessionId);
  if (!model) {
    return void 0;
  }
  return model.provideSubtypes(item, CancellationToken.None);
});

// out-build/vs/workbench/api/browser/mainThreadLanguageFeatures.js
var $pQb_1;
var $pQb = $pQb_1 = class $pQb2 extends $3c {
  constructor(extHostContext, c, f, g, h3) {
    super();
    this.c = c;
    this.f = f;
    this.g = g;
    this.h = h3;
    this.b = this.B(new $_c());
    this.w = /* @__PURE__ */ new Map();
    this.G = /* @__PURE__ */ new Map();
    this.a = extHostContext.getProxy($yT.ExtHostLanguageFeatures);
    if (this.c) {
      const updateAllWordDefinitions = () => {
        const wordDefinitionDtos = [];
        for (const languageId of c.getRegisteredLanguageIds()) {
          const wordDefinition = this.f.getLanguageConfiguration(languageId).getWordDefinition();
          wordDefinitionDtos.push({
            languageId,
            regexSource: wordDefinition.source,
            regexFlags: wordDefinition.flags
          });
        }
        this.a.$setWordDefinitions(wordDefinitionDtos);
      };
      this.B(this.f.onDidChange((e) => {
        if (!e.languageId) {
          updateAllWordDefinitions();
        } else {
          const wordDefinition = this.f.getLanguageConfiguration(e.languageId).getWordDefinition();
          this.a.$setWordDefinitions([{
            languageId: e.languageId,
            regexSource: wordDefinition.source,
            regexFlags: wordDefinition.flags
          }]);
        }
      }));
      updateAllWordDefinitions();
    }
  }
  $unregister(handle2) {
    this.b.deleteAndDispose(handle2);
  }
  static j(data) {
    if (!data) {
      return data;
    } else if (Array.isArray(data)) {
      data.forEach((l) => $pQb_1.j(l));
      return data;
    } else {
      data.uri = URI.revive(data.uri);
      return data;
    }
  }
  static m(data) {
    if (!data) {
      return data;
    } else if (Array.isArray(data)) {
      data.forEach((l) => $pQb_1.m(l));
      return data;
    } else {
      data.uri = URI.revive(data.uri);
      return data;
    }
  }
  static n(data) {
    if (!data) {
      return data;
    } else if (Array.isArray(data)) {
      data.forEach($pQb_1.n);
      return data;
    } else {
      data.location = $pQb_1.j(data.location);
      return data;
    }
  }
  static r(data, uriIdentService) {
    data?.forEach((code) => $Wrb(code.edit, uriIdentService));
    return data;
  }
  static s(data) {
    if (data.url && typeof data.url !== "string") {
      data.url = URI.revive(data.url);
    }
    return data;
  }
  static t(data) {
    if (data) {
      data.uri = URI.revive(data.uri);
    }
    return data;
  }
  static u(data) {
    if (data) {
      data.uri = URI.revive(data.uri);
    }
    return data;
  }
  //#endregion
  // --- outline
  $registerDocumentSymbolProvider(handle2, selector, displayName) {
    this.b.set(handle2, this.g.documentSymbolProvider.register(selector, {
      displayName,
      provideDocumentSymbols: (model, token) => {
        return this.a.$provideDocumentSymbols(handle2, model.uri, token);
      }
    }));
  }
  // --- code lens
  $registerCodeLensSupport(handle2, selector, eventHandle) {
    const provider = {
      provideCodeLenses: async (model, token) => {
        const listDto = await this.a.$provideCodeLenses(handle2, model.uri, token);
        if (!listDto) {
          return void 0;
        }
        return {
          lenses: listDto.lenses,
          dispose: () => listDto.cacheId && this.a.$releaseCodeLenses(handle2, listDto.cacheId)
        };
      },
      resolveCodeLens: async (model, codeLens, token) => {
        const result = await this.a.$resolveCodeLens(handle2, codeLens, token);
        if (!result) {
          return void 0;
        }
        return {
          ...result,
          range: model.validateRange(result.range)
        };
      }
    };
    if (typeof eventHandle === "number") {
      const emitter = new $ze();
      this.b.set(eventHandle, emitter);
      provider.onDidChange = emitter.event;
    }
    this.b.set(handle2, this.g.codeLensProvider.register(selector, provider));
  }
  $emitCodeLensEvent(eventHandle, event) {
    const obj = this.b.get(eventHandle);
    if (obj instanceof $ze) {
      obj.fire(event);
    }
  }
  // --- declaration
  $registerDefinitionSupport(handle2, selector) {
    this.b.set(handle2, this.g.definitionProvider.register(selector, {
      provideDefinition: (model, position, token) => {
        return this.a.$provideDefinition(handle2, model.uri, position, token).then($pQb_1.m);
      }
    }));
  }
  $registerDeclarationSupport(handle2, selector) {
    this.b.set(handle2, this.g.declarationProvider.register(selector, {
      provideDeclaration: (model, position, token) => {
        return this.a.$provideDeclaration(handle2, model.uri, position, token).then($pQb_1.m);
      }
    }));
  }
  $registerImplementationSupport(handle2, selector) {
    this.b.set(handle2, this.g.implementationProvider.register(selector, {
      provideImplementation: (model, position, token) => {
        return this.a.$provideImplementation(handle2, model.uri, position, token).then($pQb_1.m);
      }
    }));
  }
  $registerTypeDefinitionSupport(handle2, selector) {
    this.b.set(handle2, this.g.typeDefinitionProvider.register(selector, {
      provideTypeDefinition: (model, position, token) => {
        return this.a.$provideTypeDefinition(handle2, model.uri, position, token).then($pQb_1.m);
      }
    }));
  }
  // --- extra info
  $registerHoverProvider(handle2, selector) {
    this.b.set(handle2, this.g.hoverProvider.register(selector, {
      provideHover: async (model, position, token, context) => {
        const serializedContext = {
          verbosityRequest: context?.verbosityRequest ? {
            verbosityDelta: context.verbosityRequest.verbosityDelta,
            previousHover: { id: context.verbosityRequest.previousHover.id }
          } : void 0
        };
        const hover = await this.a.$provideHover(handle2, model.uri, position, serializedContext, token);
        return hover;
      }
    }));
  }
  // --- debug hover
  $registerEvaluatableExpressionProvider(handle2, selector) {
    this.b.set(handle2, this.g.evaluatableExpressionProvider.register(selector, {
      provideEvaluatableExpression: (model, position, token) => {
        return this.a.$provideEvaluatableExpression(handle2, model.uri, position, token);
      }
    }));
  }
  // --- inline values
  $registerInlineValuesProvider(handle2, selector, eventHandle) {
    const provider = {
      provideInlineValues: (model, viewPort, context, token) => {
        return this.a.$provideInlineValues(handle2, model.uri, viewPort, context, token);
      }
    };
    if (typeof eventHandle === "number") {
      const emitter = new $ze();
      this.b.set(eventHandle, emitter);
      provider.onDidChangeInlineValues = emitter.event;
    }
    this.b.set(handle2, this.g.inlineValuesProvider.register(selector, provider));
  }
  $emitInlineValuesEvent(eventHandle, event) {
    const obj = this.b.get(eventHandle);
    if (obj instanceof $ze) {
      obj.fire(event);
    }
  }
  // --- occurrences
  $registerDocumentHighlightProvider(handle2, selector) {
    this.b.set(handle2, this.g.documentHighlightProvider.register(selector, {
      provideDocumentHighlights: (model, position, token) => {
        return this.a.$provideDocumentHighlights(handle2, model.uri, position, token);
      }
    }));
  }
  $registerMultiDocumentHighlightProvider(handle2, selector) {
    this.b.set(handle2, this.g.multiDocumentHighlightProvider.register(selector, {
      selector,
      provideMultiDocumentHighlights: (model, position, otherModels, token) => {
        return this.a.$provideMultiDocumentHighlights(handle2, model.uri, position, otherModels.map((model2) => model2.uri), token).then((dto) => {
          if (dto === void 0 || dto === null) {
            return void 0;
          }
          const result = new $Ec();
          dto?.forEach((value) => {
            const uri = URI.revive(value.uri);
            if (result.has(uri)) {
              result.get(uri).push(...value.highlights);
            } else {
              result.set(uri, value.highlights);
            }
          });
          return result;
        });
      }
    }));
  }
  // --- linked editing
  $registerLinkedEditingRangeProvider(handle2, selector) {
    this.b.set(handle2, this.g.linkedEditingRangeProvider.register(selector, {
      provideLinkedEditingRanges: async (model, position, token) => {
        const res = await this.a.$provideLinkedEditingRanges(handle2, model.uri, position, token);
        if (res) {
          return {
            ranges: res.ranges,
            wordPattern: res.wordPattern ? $pQb_1.z(res.wordPattern) : void 0
          };
        }
        return void 0;
      }
    }));
  }
  // --- references
  $registerReferenceSupport(handle2, selector) {
    this.b.set(handle2, this.g.referenceProvider.register(selector, {
      provideReferences: (model, position, context, token) => {
        return this.a.$provideReferences(handle2, model.uri, position, context, token).then($pQb_1.j);
      }
    }));
  }
  // --- code actions
  $registerCodeActionSupport(handle2, selector, metadata, displayName, extensionId, supportsResolve) {
    const provider = {
      provideCodeActions: async (model, rangeOrSelection, context, token) => {
        const listDto = await this.a.$provideCodeActions(handle2, model.uri, rangeOrSelection, context, token);
        if (!listDto) {
          return void 0;
        }
        return {
          actions: $pQb_1.r(listDto.actions, this.h),
          dispose: () => {
            if (typeof listDto.cacheId === "number") {
              this.a.$releaseCodeActions(handle2, listDto.cacheId);
            }
          }
        };
      },
      providedCodeActionKinds: metadata.providedKinds,
      documentation: metadata.documentation,
      displayName,
      extensionId
    };
    if (supportsResolve) {
      provider.resolveCodeAction = async (codeAction, token) => {
        const resolved = await this.a.$resolveCodeAction(handle2, codeAction.cacheId, token);
        if (resolved.edit) {
          codeAction.edit = $Wrb(resolved.edit, this.h);
        }
        if (resolved.command) {
          codeAction.command = resolved.command;
        }
        return codeAction;
      };
    }
    this.b.set(handle2, this.g.codeActionProvider.register(selector, provider));
  }
  $registerPasteEditProvider(handle2, selector, metadata) {
    const provider = new MainThreadPasteEditProvider(handle2, this.a, metadata, this.h);
    this.w.set(handle2, provider);
    this.b.set(handle2, $Zc(this.g.documentPasteEditProvider.register(selector, provider), $1c(() => this.w.delete(handle2))));
  }
  $resolvePasteFileData(handle2, requestId, dataId) {
    const provider = this.w.get(handle2);
    if (!provider) {
      throw new Error("Could not find provider");
    }
    return provider.resolveFileData(requestId, dataId);
  }
  // --- formatting
  $registerDocumentFormattingSupport(handle2, selector, extensionId, displayName) {
    this.b.set(handle2, this.g.documentFormattingEditProvider.register(selector, {
      extensionId,
      displayName,
      provideDocumentFormattingEdits: (model, options3, token) => {
        return this.a.$provideDocumentFormattingEdits(handle2, model.uri, options3, token);
      }
    }));
  }
  $registerRangeFormattingSupport(handle2, selector, extensionId, displayName, supportsRanges) {
    this.b.set(handle2, this.g.documentRangeFormattingEditProvider.register(selector, {
      extensionId,
      displayName,
      provideDocumentRangeFormattingEdits: (model, range, options3, token) => {
        return this.a.$provideDocumentRangeFormattingEdits(handle2, model.uri, range, options3, token);
      },
      provideDocumentRangesFormattingEdits: !supportsRanges ? void 0 : (model, ranges, options3, token) => {
        return this.a.$provideDocumentRangesFormattingEdits(handle2, model.uri, ranges, options3, token);
      }
    }));
  }
  $registerOnTypeFormattingSupport(handle2, selector, autoFormatTriggerCharacters, extensionId) {
    this.b.set(handle2, this.g.onTypeFormattingEditProvider.register(selector, {
      extensionId,
      autoFormatTriggerCharacters,
      provideOnTypeFormattingEdits: (model, position, ch, options3, token) => {
        return this.a.$provideOnTypeFormattingEdits(handle2, model.uri, position, ch, options3, token);
      }
    }));
  }
  // --- navigate type
  $registerNavigateTypeSupport(handle2, supportsResolve) {
    let lastResultId;
    const provider = {
      provideWorkspaceSymbols: async (search2, token) => {
        const result = await this.a.$provideWorkspaceSymbols(handle2, search2, token);
        if (lastResultId !== void 0) {
          this.a.$releaseWorkspaceSymbols(handle2, lastResultId);
        }
        lastResultId = result.cacheId;
        return $pQb_1.n(result.symbols);
      }
    };
    if (supportsResolve) {
      provider.resolveWorkspaceSymbol = async (item, token) => {
        const resolvedItem = await this.a.$resolveWorkspaceSymbol(handle2, item, token);
        return resolvedItem && $pQb_1.n(resolvedItem);
      };
    }
    this.b.set(handle2, WorkspaceSymbolProviderRegistry.register(provider));
  }
  // --- rename
  $registerRenameSupport(handle2, selector, supportResolveLocation) {
    this.b.set(handle2, this.g.renameProvider.register(selector, {
      provideRenameEdits: (model, position, newName, token) => {
        return this.a.$provideRenameEdits(handle2, model.uri, position, newName, token).then((data) => $Wrb(data, this.h));
      },
      resolveRenameLocation: supportResolveLocation ? (model, position, token) => this.a.$resolveRenameLocation(handle2, model.uri, position, token) : void 0
    }));
  }
  $registerNewSymbolNamesProvider(handle2, selector) {
    this.b.set(handle2, this.g.newSymbolNamesProvider.register(selector, {
      supportsAutomaticNewSymbolNamesTriggerKind: this.a.$supportsAutomaticNewSymbolNamesTriggerKind(handle2),
      provideNewSymbolNames: (model, range, triggerKind, token) => {
        return this.a.$provideNewSymbolNames(handle2, model.uri, range, triggerKind, token);
      }
    }));
  }
  // --- semantic tokens
  $registerDocumentSemanticTokensProvider(handle2, selector, legend, eventHandle) {
    let event = void 0;
    if (typeof eventHandle === "number") {
      const emitter = new $ze();
      this.b.set(eventHandle, emitter);
      event = emitter.event;
    }
    this.b.set(handle2, this.g.documentSemanticTokensProvider.register(selector, new $qQb(this.a, handle2, legend, event)));
  }
  $emitDocumentSemanticTokensEvent(eventHandle) {
    const obj = this.b.get(eventHandle);
    if (obj instanceof $ze) {
      obj.fire(void 0);
    }
  }
  $registerDocumentRangeSemanticTokensProvider(handle2, selector, legend) {
    this.b.set(handle2, this.g.documentRangeSemanticTokensProvider.register(selector, new $rQb(this.a, handle2, legend)));
  }
  // --- suggest
  static y(defaultRange, data, extensionId) {
    const label3 = data[
      "a"
      /* ISuggestDataDtoField.label */
    ];
    const commandId = data[
      "o"
      /* ISuggestDataDtoField.commandId */
    ];
    const commandIdent = data[
      "n"
      /* ISuggestDataDtoField.commandIdent */
    ];
    const commitChars = data[
      "k"
      /* ISuggestDataDtoField.commitCharacters */
    ];
    let command4;
    if (commandId) {
      command4 = {
        $ident: commandIdent,
        id: commandId,
        title: "",
        arguments: commandIdent ? [commandIdent] : data[
          "p"
          /* ISuggestDataDtoField.commandArguments */
        ]
        // Automatically fill in ident as first argument
      };
    }
    return {
      label: label3,
      extensionId,
      kind: data[
        "b"
        /* ISuggestDataDtoField.kind */
      ] ?? 9,
      tags: data[
        "m"
        /* ISuggestDataDtoField.kindModifier */
      ],
      detail: data[
        "c"
        /* ISuggestDataDtoField.detail */
      ],
      documentation: data[
        "d"
        /* ISuggestDataDtoField.documentation */
      ],
      sortText: data[
        "e"
        /* ISuggestDataDtoField.sortText */
      ],
      filterText: data[
        "f"
        /* ISuggestDataDtoField.filterText */
      ],
      preselect: data[
        "g"
        /* ISuggestDataDtoField.preselect */
      ],
      insertText: data[
        "h"
        /* ISuggestDataDtoField.insertText */
      ] ?? (typeof label3 === "string" ? label3 : label3.label),
      range: data[
        "j"
        /* ISuggestDataDtoField.range */
      ] ?? defaultRange,
      insertTextRules: data[
        "i"
        /* ISuggestDataDtoField.insertTextRules */
      ],
      commitCharacters: commitChars ? Array.from(commitChars) : void 0,
      additionalTextEdits: data[
        "l"
        /* ISuggestDataDtoField.additionalTextEdits */
      ],
      command: command4,
      // not-standard
      _id: data.x
    };
  }
  $registerCompletionsProvider(handle2, selector, triggerCharacters, supportsResolveDetails, extensionId) {
    const provider = {
      triggerCharacters,
      _debugDisplayName: `${extensionId.value}(${triggerCharacters.join("")})`,
      provideCompletionItems: async (model, position, context, token) => {
        const result = await this.a.$provideCompletionItems(handle2, model.uri, position, context, token);
        if (!result) {
          return result;
        }
        return {
          suggestions: result[
            "b"
            /* ISuggestResultDtoField.completions */
          ].map((d) => $pQb_1.y(result[
            "a"
            /* ISuggestResultDtoField.defaultRanges */
          ], d, extensionId)),
          incomplete: result[
            "c"
            /* ISuggestResultDtoField.isIncomplete */
          ] || false,
          duration: result[
            "d"
            /* ISuggestResultDtoField.duration */
          ],
          dispose: () => {
            if (typeof result.x === "number") {
              this.a.$releaseCompletionItems(handle2, result.x);
            }
          }
        };
      }
    };
    if (supportsResolveDetails) {
      provider.resolveCompletionItem = (suggestion, token) => {
        return this.a.$resolveCompletionItem(handle2, suggestion._id, token).then((result) => {
          if (!result) {
            return suggestion;
          }
          const newSuggestion = $pQb_1.y(suggestion.range, result, extensionId);
          return $Ov(suggestion, newSuggestion, true);
        });
      };
    }
    this.b.set(handle2, this.g.completionProvider.register(selector, provider));
  }
  $registerInlineCompletionsSupport(handle2, selector, supportsHandleEvents, extensionId, yieldsToExtensionIds) {
    const provider = {
      provideInlineCompletions: async (model, position, context, token) => {
        return this.a.$provideInlineCompletions(handle2, model.uri, position, context, token);
      },
      provideInlineEditsForRange: async (model, range, context, token) => {
        return this.a.$provideInlineEditsForRange(handle2, model.uri, range, context, token);
      },
      handleItemDidShow: async (completions, item, updatedInsertText) => {
        if (supportsHandleEvents) {
          await this.a.$handleInlineCompletionDidShow(handle2, completions.pid, item.idx, updatedInsertText);
        }
      },
      handlePartialAccept: async (completions, item, acceptedCharacters, info) => {
        if (supportsHandleEvents) {
          await this.a.$handleInlineCompletionPartialAccept(handle2, completions.pid, item.idx, acceptedCharacters, info);
        }
      },
      freeInlineCompletions: (completions) => {
        this.a.$freeInlineCompletionsList(handle2, completions.pid);
      },
      groupId: extensionId,
      yieldsToGroupIds: yieldsToExtensionIds,
      toString() {
        return `InlineCompletionsProvider(${extensionId})`;
      }
    };
    this.b.set(handle2, this.g.inlineCompletionsProvider.register(selector, provider));
  }
  $registerInlineEditProvider(handle2, selector, extensionId) {
    const provider = {
      provideInlineEdit: async (model, context, token) => {
        return this.a.$provideInlineEdit(handle2, model.uri, context, token);
      },
      freeInlineEdit: (edit3) => {
        this.a.$freeInlineEdit(handle2, edit3.pid);
      }
    };
    this.b.set(handle2, this.g.inlineEditProvider.register(selector, provider));
  }
  // --- parameter hints
  $registerSignatureHelpProvider(handle2, selector, metadata) {
    this.b.set(handle2, this.g.signatureHelpProvider.register(selector, {
      signatureHelpTriggerCharacters: metadata.triggerCharacters,
      signatureHelpRetriggerCharacters: metadata.retriggerCharacters,
      provideSignatureHelp: async (model, position, token, context) => {
        const result = await this.a.$provideSignatureHelp(handle2, model.uri, position, context, token);
        if (!result) {
          return void 0;
        }
        return {
          value: result,
          dispose: () => {
            this.a.$releaseSignatureHelp(handle2, result.id);
          }
        };
      }
    }));
  }
  // --- inline hints
  $registerInlayHintsProvider(handle2, selector, supportsResolve, eventHandle, displayName) {
    const provider = {
      displayName,
      provideInlayHints: async (model, range, token) => {
        const result = await this.a.$provideInlayHints(handle2, model.uri, range, token);
        if (!result) {
          return;
        }
        return {
          hints: $cu(result.hints),
          dispose: () => {
            if (result.cacheId) {
              this.a.$releaseInlayHints(handle2, result.cacheId);
            }
          }
        };
      }
    };
    if (supportsResolve) {
      provider.resolveInlayHint = async (hint, token) => {
        const dto = hint;
        if (!dto.cacheId) {
          return hint;
        }
        const result = await this.a.$resolveInlayHint(handle2, dto.cacheId, token);
        if (token.isCancellationRequested) {
          throw new $lb();
        }
        if (!result) {
          return hint;
        }
        return {
          ...hint,
          tooltip: result.tooltip,
          label: $cu(result.label),
          textEdits: result.textEdits
        };
      };
    }
    if (typeof eventHandle === "number") {
      const emitter = new $ze();
      this.b.set(eventHandle, emitter);
      provider.onDidChangeInlayHints = emitter.event;
    }
    this.b.set(handle2, this.g.inlayHintsProvider.register(selector, provider));
  }
  $emitInlayHintsEvent(eventHandle) {
    const obj = this.b.get(eventHandle);
    if (obj instanceof $ze) {
      obj.fire(void 0);
    }
  }
  // --- links
  $registerDocumentLinkProvider(handle2, selector, supportsResolve) {
    const provider = {
      provideLinks: (model, token) => {
        return this.a.$provideDocumentLinks(handle2, model.uri, token).then((dto) => {
          if (!dto) {
            return void 0;
          }
          return {
            links: dto.links.map($pQb_1.s),
            dispose: () => {
              if (typeof dto.cacheId === "number") {
                this.a.$releaseDocumentLinks(handle2, dto.cacheId);
              }
            }
          };
        });
      }
    };
    if (supportsResolve) {
      provider.resolveLink = (link2, token) => {
        const dto = link2;
        if (!dto.cacheId) {
          return link2;
        }
        return this.a.$resolveDocumentLink(handle2, dto.cacheId, token).then((obj) => {
          return obj && $pQb_1.s(obj);
        });
      };
    }
    this.b.set(handle2, this.g.linkProvider.register(selector, provider));
  }
  // --- colors
  $registerDocumentColorProvider(handle2, selector) {
    const proxy = this.a;
    this.b.set(handle2, this.g.colorProvider.register(selector, {
      provideDocumentColors: (model, token) => {
        return proxy.$provideDocumentColors(handle2, model.uri, token).then((documentColors) => {
          return documentColors.map((documentColor) => {
            const [red, green, blue, alpha] = documentColor.color;
            const color2 = {
              red,
              green,
              blue,
              alpha
            };
            return {
              color: color2,
              range: documentColor.range
            };
          });
        });
      },
      provideColorPresentations: (model, colorInfo, token) => {
        return proxy.$provideColorPresentations(handle2, model.uri, {
          color: [colorInfo.color.red, colorInfo.color.green, colorInfo.color.blue, colorInfo.color.alpha],
          range: colorInfo.range
        }, token);
      }
    }));
  }
  // --- folding
  $registerFoldingRangeProvider(handle2, selector, extensionId, eventHandle) {
    const provider = {
      id: extensionId.value,
      provideFoldingRanges: (model, context, token) => {
        return this.a.$provideFoldingRanges(handle2, model.uri, context, token);
      }
    };
    if (typeof eventHandle === "number") {
      const emitter = new $ze();
      this.b.set(eventHandle, emitter);
      provider.onDidChange = emitter.event;
    }
    this.b.set(handle2, this.g.foldingRangeProvider.register(selector, provider));
  }
  $emitFoldingRangeEvent(eventHandle, event) {
    const obj = this.b.get(eventHandle);
    if (obj instanceof $ze) {
      obj.fire(event);
    }
  }
  // -- smart select
  $registerSelectionRangeProvider(handle2, selector) {
    this.b.set(handle2, this.g.selectionRangeProvider.register(selector, {
      provideSelectionRanges: (model, positions, token) => {
        return this.a.$provideSelectionRanges(handle2, model.uri, positions, token);
      }
    }));
  }
  // --- call hierarchy
  $registerCallHierarchyProvider(handle2, selector) {
    this.b.set(handle2, $cN.register(selector, {
      prepareCallHierarchy: async (document2, position, token) => {
        const items = await this.a.$prepareCallHierarchy(handle2, document2.uri, position, token);
        if (!items || items.length === 0) {
          return void 0;
        }
        return {
          dispose: () => {
            for (const item of items) {
              this.a.$releaseCallHierarchy(handle2, item._sessionId);
            }
          },
          roots: items.map($pQb_1.t)
        };
      },
      provideOutgoingCalls: async (item, token) => {
        const outgoing = await this.a.$provideCallHierarchyOutgoingCalls(handle2, item._sessionId, item._itemId, token);
        if (!outgoing) {
          return outgoing;
        }
        outgoing.forEach((value) => {
          value.to = $pQb_1.t(value.to);
        });
        return outgoing;
      },
      provideIncomingCalls: async (item, token) => {
        const incoming = await this.a.$provideCallHierarchyIncomingCalls(handle2, item._sessionId, item._itemId, token);
        if (!incoming) {
          return incoming;
        }
        incoming.forEach((value) => {
          value.from = $pQb_1.t(value.from);
        });
        return incoming;
      }
    }));
  }
  // --- configuration
  static z(regExp) {
    return new RegExp(regExp.pattern, regExp.flags);
  }
  static C(indentationRule) {
    return {
      decreaseIndentPattern: $pQb_1.z(indentationRule.decreaseIndentPattern),
      increaseIndentPattern: $pQb_1.z(indentationRule.increaseIndentPattern),
      indentNextLinePattern: indentationRule.indentNextLinePattern ? $pQb_1.z(indentationRule.indentNextLinePattern) : void 0,
      unIndentedLinePattern: indentationRule.unIndentedLinePattern ? $pQb_1.z(indentationRule.unIndentedLinePattern) : void 0
    };
  }
  static D(onEnterRule) {
    return {
      beforeText: $pQb_1.z(onEnterRule.beforeText),
      afterText: onEnterRule.afterText ? $pQb_1.z(onEnterRule.afterText) : void 0,
      previousLineText: onEnterRule.previousLineText ? $pQb_1.z(onEnterRule.previousLineText) : void 0,
      action: onEnterRule.action
    };
  }
  static F(onEnterRules) {
    return onEnterRules.map($pQb_1.D);
  }
  $setLanguageConfiguration(handle2, languageId, _configuration) {
    const configuration2 = {
      comments: _configuration.comments,
      brackets: _configuration.brackets,
      wordPattern: _configuration.wordPattern ? $pQb_1.z(_configuration.wordPattern) : void 0,
      indentationRules: _configuration.indentationRules ? $pQb_1.C(_configuration.indentationRules) : void 0,
      onEnterRules: _configuration.onEnterRules ? $pQb_1.F(_configuration.onEnterRules) : void 0,
      autoClosingPairs: void 0,
      surroundingPairs: void 0,
      __electricCharacterSupport: void 0
    };
    if (_configuration.autoClosingPairs) {
      configuration2.autoClosingPairs = _configuration.autoClosingPairs;
    } else if (_configuration.__characterPairSupport) {
      configuration2.autoClosingPairs = _configuration.__characterPairSupport.autoClosingPairs;
    }
    if (_configuration.__electricCharacterSupport && _configuration.__electricCharacterSupport.docComment) {
      configuration2.__electricCharacterSupport = {
        docComment: {
          open: _configuration.__electricCharacterSupport.docComment.open,
          close: _configuration.__electricCharacterSupport.docComment.close
        }
      };
    }
    if (this.c.isRegisteredLanguageId(languageId)) {
      this.b.set(handle2, this.f.register(languageId, configuration2, 100));
    }
  }
  // --- type hierarchy
  $registerTypeHierarchyProvider(handle2, selector) {
    this.b.set(handle2, $tS.register(selector, {
      prepareTypeHierarchy: async (document2, position, token) => {
        const items = await this.a.$prepareTypeHierarchy(handle2, document2.uri, position, token);
        if (!items) {
          return void 0;
        }
        return {
          dispose: () => {
            for (const item of items) {
              this.a.$releaseTypeHierarchy(handle2, item._sessionId);
            }
          },
          roots: items.map($pQb_1.u)
        };
      },
      provideSupertypes: async (item, token) => {
        const supertypes = await this.a.$provideTypeHierarchySupertypes(handle2, item._sessionId, item._itemId, token);
        if (!supertypes) {
          return supertypes;
        }
        return supertypes.map($pQb_1.u);
      },
      provideSubtypes: async (item, token) => {
        const subtypes = await this.a.$provideTypeHierarchySubtypes(handle2, item._sessionId, item._itemId, token);
        if (!subtypes) {
          return subtypes;
        }
        return subtypes.map($pQb_1.u);
      }
    }));
  }
  $registerDocumentOnDropEditProvider(handle2, selector, metadata) {
    const provider = new MainThreadDocumentOnDropEditProvider(handle2, this.a, metadata, this.h);
    this.G.set(handle2, provider);
    this.b.set(handle2, $Zc(this.g.documentDropEditProvider.register(selector, provider), $1c(() => this.G.delete(handle2))));
  }
  async $resolveDocumentOnDropFileData(handle2, requestId, dataId) {
    const provider = this.G.get(handle2);
    if (!provider) {
      throw new Error("Could not find provider");
    }
    return provider.resolveDocumentOnDropFileData(requestId, dataId);
  }
  // --- mapped edits
  $registerMappedEditsProvider(handle2, selector, displayName) {
    const provider = new $sQb(displayName, handle2, this.a, this.h);
    this.b.set(handle2, this.g.mappedEditsProvider.register(selector, provider));
  }
};
$pQb = $pQb_1 = __decorate([
  $frb($xT.MainThreadLanguageFeatures),
  __param(1, $1E),
  __param(2, $NF),
  __param(3, $mP),
  __param(4, $vl)
], $pQb);
var MainThreadPasteEditProvider = class MainThreadPasteEditProvider2 {
  constructor(b, c, metadata, f) {
    this.b = b;
    this.c = c;
    this.f = f;
    this.a = new $oQb();
    this.copyMimeTypes = metadata.copyMimeTypes ?? [];
    this.pasteMimeTypes = metadata.pasteMimeTypes ?? [];
    this.providedPasteEditKinds = metadata.providedPasteEditKinds?.map((kind) => new $oE(kind)) ?? [];
    if (metadata.supportsCopy) {
      this.prepareDocumentPaste = async (model, selections, dataTransfer, token) => {
        const dataTransferDto = await DataTransfer.from(dataTransfer);
        if (token.isCancellationRequested) {
          return void 0;
        }
        const newDataTransfer = await this.c.$prepareDocumentPaste(b, model.uri, selections, dataTransferDto, token);
        if (!newDataTransfer) {
          return void 0;
        }
        const dataTransferOut = new $lE();
        for (const [type, item] of newDataTransfer.items) {
          dataTransferOut.replace(type, $jE(item.asString));
        }
        return dataTransferOut;
      };
    }
    if (metadata.supportsPaste) {
      this.provideDocumentPasteEdits = async (model, selections, dataTransfer, context, token) => {
        const request = this.a.add(dataTransfer);
        try {
          const dataTransferDto = await DataTransfer.from(dataTransfer);
          if (token.isCancellationRequested) {
            return;
          }
          const edits = await this.c.$providePasteEdits(this.b, request.id, model.uri, selections, dataTransferDto, {
            only: context.only?.value,
            triggerKind: context.triggerKind
          }, token);
          if (!edits) {
            return;
          }
          return {
            edits: edits.map((edit3) => {
              return {
                ...edit3,
                kind: edit3.kind ? new $oE(edit3.kind.value) : new $oE(""),
                yieldTo: edit3.yieldTo?.map((x) => ({ kind: new $oE(x) })),
                additionalEdit: edit3.additionalEdit ? $Wrb(edit3.additionalEdit, this.f, (dataId) => this.resolveFileData(request.id, dataId)) : void 0
              };
            }),
            dispose: () => {
              this.c.$releasePasteEdits(this.b, request.id);
            }
          };
        } finally {
          request.dispose();
        }
      };
    }
    if (metadata.supportsResolve) {
      this.resolveDocumentPasteEdit = async (edit3, token) => {
        const resolved = await this.c.$resolvePasteEdit(this.b, edit3._cacheId, token);
        if (resolved.additionalEdit) {
          edit3.additionalEdit = $Wrb(resolved.additionalEdit, this.f);
        }
        return edit3;
      };
    }
  }
  resolveFileData(requestId, dataId) {
    return this.a.resolveFileData(requestId, dataId);
  }
};
MainThreadPasteEditProvider = __decorate([
  __param(3, $vl)
], MainThreadPasteEditProvider);
var MainThreadDocumentOnDropEditProvider = class MainThreadDocumentOnDropEditProvider2 {
  constructor(b, c, metadata, f) {
    this.b = b;
    this.c = c;
    this.f = f;
    this.a = new $oQb();
    this.dropMimeTypes = metadata?.dropMimeTypes ?? ["*/*"];
    this.providedDropEditKinds = metadata?.providedDropKinds?.map((kind) => new $oE(kind));
    if (metadata?.supportsResolve) {
      this.resolveDocumentDropEdit = async (edit3, token) => {
        const resolved = await this.c.$resolvePasteEdit(this.b, edit3._cacheId, token);
        if (resolved.additionalEdit) {
          edit3.additionalEdit = $Wrb(resolved.additionalEdit, this.f);
        }
        return edit3;
      };
    }
  }
  async provideDocumentDropEdits(model, position, dataTransfer, token) {
    const request = this.a.add(dataTransfer);
    try {
      const dataTransferDto = await DataTransfer.from(dataTransfer);
      if (token.isCancellationRequested) {
        return;
      }
      const edits = await this.c.$provideDocumentOnDropEdits(this.b, request.id, model.uri, position, dataTransferDto, token);
      if (!edits) {
        return;
      }
      return {
        edits: edits.map((edit3) => {
          return {
            ...edit3,
            yieldTo: edit3.yieldTo?.map((x) => ({ kind: new $oE(x) })),
            kind: edit3.kind ? new $oE(edit3.kind) : void 0,
            additionalEdit: $Wrb(edit3.additionalEdit, this.f, (dataId) => this.resolveDocumentOnDropFileData(request.id, dataId))
          };
        }),
        dispose: () => {
          this.c.$releaseDocumentOnDropEdits(this.b, request.id);
        }
      };
    } finally {
      request.dispose();
    }
  }
  resolveDocumentOnDropFileData(requestId, dataId) {
    return this.a.resolveFileData(requestId, dataId);
  }
};
MainThreadDocumentOnDropEditProvider = __decorate([
  __param(3, $vl)
], MainThreadDocumentOnDropEditProvider);
var $qQb = class {
  constructor(a, b, c, onDidChange) {
    this.a = a;
    this.b = b;
    this.c = c;
    this.onDidChange = onDidChange;
  }
  releaseDocumentSemanticTokens(resultId) {
    if (resultId) {
      this.a.$releaseDocumentSemanticTokens(this.b, parseInt(resultId, 10));
    }
  }
  getLegend() {
    return this.c;
  }
  async provideDocumentSemanticTokens(model, lastResultId, token) {
    const nLastResultId = lastResultId ? parseInt(lastResultId, 10) : 0;
    const encodedDto = await this.a.$provideDocumentSemanticTokens(this.b, model.uri, nLastResultId, token);
    if (!encodedDto) {
      return null;
    }
    if (token.isCancellationRequested) {
      return null;
    }
    const dto = $_jb(encodedDto);
    if (dto.type === "full") {
      return {
        resultId: String(dto.id),
        data: dto.data
      };
    }
    return {
      resultId: String(dto.id),
      edits: dto.deltas
    };
  }
};
var $rQb = class {
  constructor(a, b, c) {
    this.a = a;
    this.b = b;
    this.c = c;
  }
  getLegend() {
    return this.c;
  }
  async provideDocumentRangeSemanticTokens(model, range, token) {
    const encodedDto = await this.a.$provideDocumentRangeSemanticTokens(this.b, model.uri, range, token);
    if (!encodedDto) {
      return null;
    }
    if (token.isCancellationRequested) {
      return null;
    }
    const dto = $_jb(encodedDto);
    if (dto.type === "full") {
      return {
        resultId: String(dto.id),
        data: dto.data
      };
    }
    throw new Error(`Unexpected`);
  }
};
var $sQb = class {
  constructor(displayName, a, b, c) {
    this.displayName = displayName;
    this.a = a;
    this.b = b;
    this.c = c;
  }
  async provideMappedEdits(document2, codeBlocks, context, token) {
    const res = await this.b.$provideMappedEdits(this.a, document2.uri, codeBlocks, context, token);
    return res ? $Wrb(res, this.c) : null;
  }
};

// out-build/vs/workbench/services/languageStatus/common/languageStatusService.js
var $FS = $Qk("ILanguageStatusService");
var LanguageStatusServiceImpl = class {
  constructor() {
    this.c = new $bN();
    this.onDidChange = this.c.onDidChange;
  }
  addStatus(status) {
    return this.c.register(status.selector, status);
  }
  getLanguageStatus(model) {
    return this.c.ordered(model).sort((a, b) => {
      let res = b.severity - a.severity;
      if (res === 0) {
        res = $Tf(a.source, b.source);
      }
      if (res === 0) {
        res = $Tf(a.id, b.id);
      }
      return res;
    });
  }
};
$SC(
  $FS,
  LanguageStatusServiceImpl,
  1
  /* InstantiationType.Delayed */
);

// out-build/vs/workbench/api/browser/mainThreadLanguages.js
var $tQb = class $tQb2 {
  constructor(_extHostContext, d, e, f, g) {
    this.d = d;
    this.e = e;
    this.f = f;
    this.g = g;
    this.a = new $2c();
    this.c = new $_c();
    this.b = _extHostContext.getProxy($yT.ExtHostLanguages);
    this.b.$acceptLanguageIds(d.getRegisteredLanguageIds());
    this.a.add(d.onDidChange((_) => {
      this.b.$acceptLanguageIds(d.getRegisteredLanguageIds());
    }));
  }
  dispose() {
    this.a.dispose();
    this.c.dispose();
  }
  async $changeLanguage(resource, languageId) {
    if (!this.d.isRegisteredLanguageId(languageId)) {
      return Promise.reject(new Error(`Unknown language id: ${languageId}`));
    }
    const uri = URI.revive(resource);
    const ref = await this.f.createModelReference(uri);
    try {
      ref.object.textEditorModel.setLanguage(this.d.createById(languageId));
    } finally {
      ref.dispose();
    }
  }
  async $tokensAtPosition(resource, position) {
    const uri = URI.revive(resource);
    const model = this.e.getModel(uri);
    if (!model) {
      return void 0;
    }
    model.tokenization.tokenizeIfCheap(position.lineNumber);
    const tokens = model.tokenization.getLineTokens(position.lineNumber);
    const idx = tokens.findTokenIndexAtOffset(position.column - 1);
    return {
      type: tokens.getStandardTokenType(idx),
      range: new $9C(position.lineNumber, 1 + tokens.getStartOffset(idx), position.lineNumber, 1 + tokens.getEndOffset(idx))
    };
  }
  // --- language status
  $setLanguageStatus(handle2, status) {
    this.c.get(handle2)?.dispose();
    this.c.set(handle2, this.g.addStatus(status));
  }
  $removeLanguageStatus(handle2) {
    this.c.get(handle2)?.dispose();
  }
};
$tQb = __decorate([
  $frb($xT.MainThreadLanguages),
  __param(1, $1E),
  __param(2, $sG),
  __param(3, $oG),
  __param(4, $FS)
], $tQb);

// out-build/vs/workbench/api/browser/mainThreadLogService.js
var $uQb = class $uQb2 {
  constructor(extHostContext, b) {
    this.b = b;
    this.a = new $2c();
    const proxy = extHostContext.getProxy($yT.ExtHostLogLevelServiceShape);
    this.a.add(b.onDidChangeLogLevel((arg) => {
      if ($yn(arg)) {
        proxy.$setLogLevel(arg);
      } else {
        proxy.$setLogLevel(arg[1], arg[0]);
      }
    }));
  }
  $log(file, messages) {
    const logger2 = this.b.getLogger(URI.revive(file));
    if (!logger2) {
      throw new Error("Create the logger before logging");
    }
    for (const [level, message] of messages) {
      log(logger2, level, message);
    }
  }
  async $createLogger(file, options3) {
    this.b.createLogger(URI.revive(file), options3);
  }
  async $registerLogger(logResource) {
    this.b.registerLogger({
      ...logResource,
      resource: URI.revive(logResource.resource)
    });
  }
  async $deregisterLogger(resource) {
    this.b.deregisterLogger(URI.revive(resource));
  }
  async $setVisibility(resource, visible) {
    this.b.setVisibility(URI.revive(resource), visible);
  }
  $flush(file) {
    const logger2 = this.b.getLogger(URI.revive(file));
    if (!logger2) {
      throw new Error("Create the logger before flushing");
    }
    logger2.flush();
  }
  dispose() {
    this.a.dispose();
  }
};
$uQb = __decorate([
  $frb($xT.MainThreadLogger),
  __param(1, $xn)
], $uQb);
$tn.registerCommand("_extensionTests.setLogLevel", function(accessor, level) {
  const loggerService = accessor.get($xn);
  const environmentService = accessor.get($Xk);
  if (environmentService.isExtensionDevelopment && !!environmentService.extensionTestsLocationURI) {
    const logLevel = $Nn(level);
    if (logLevel !== void 0) {
      loggerService.setLogLevel(logLevel);
    }
  }
});
$tn.registerCommand("_extensionTests.getLogLevel", function(accessor) {
  const logService = accessor.get($wn);
  return $Ln(logService.getLevel());
});

// out-build/vs/workbench/api/browser/mainThreadMessageService.js
var $vQb = class $vQb2 {
  constructor(extHostContext, b, c, d, extensionService) {
    this.b = b;
    this.c = c;
    this.d = d;
    this.a = extensionService.onDidChangeExtensions((e) => {
      for (const extension of e.removed) {
        this.b.removeFilter(extension.identifier.value);
      }
    });
  }
  dispose() {
    this.a.dispose();
  }
  $showMessage(severity, message, options3, commands2) {
    if (options3.modal) {
      return this.g(severity, message, options3.detail, commands2, options3.useCustom);
    } else {
      return this.f(severity, message, commands2, options3);
    }
  }
  f(severity, message, commands2, options3) {
    return new Promise((resolve) => {
      const primaryActions = commands2.map((command4) => $Zm({
        id: `_extension_message_handle_${command4.handle}`,
        label: command4.title,
        enabled: true,
        run: () => {
          resolve(command4.handle);
          return Promise.resolve();
        }
      }));
      let source;
      if (options3.source) {
        source = {
          label: options3.source.label,
          id: options3.source.identifier.value
        };
      }
      if (!source) {
        source = localize(2616, null);
      }
      const secondaryActions = [];
      if (options3.source) {
        secondaryActions.push($Zm({
          id: options3.source.identifier.value,
          label: localize(2617, null),
          run: () => {
            return this.c.executeCommand("_extensions.manage", options3.source.identifier.value);
          }
        }));
      }
      const messageHandle = this.b.notify({
        severity,
        message,
        actions: { primary: primaryActions, secondary: secondaryActions },
        source
      });
      Event2.once(messageHandle.onDidClose)(() => {
        resolve(void 0);
      });
    });
  }
  async g(severity, message, detail2, commands2, useCustom) {
    const buttons = [];
    let cancelButton = void 0;
    for (const command4 of commands2) {
      const button = {
        label: command4.title,
        run: () => command4.handle
      };
      if (command4.isCloseAffordance) {
        cancelButton = button;
      } else {
        buttons.push(button);
      }
    }
    if (!cancelButton) {
      if (buttons.length > 0) {
        cancelButton = {
          label: localize(2618, null),
          run: () => void 0
        };
      } else {
        cancelButton = {
          label: localize(2619, null),
          run: () => void 0
        };
      }
    }
    const { result } = await this.d.prompt({
      type: severity,
      message,
      detail: detail2,
      buttons,
      cancelButton,
      custom: useCustom
    });
    return result;
  }
};
$vQb = __decorate([
  $frb($xT.MainThreadMessageService),
  __param(1, $PJ),
  __param(2, $sn),
  __param(3, $Yv),
  __param(4, $wN)
], $vQb);

// 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(type) {
  switch (type) {
    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(type) {
  switch (type) {
    case 200:
      return `init`;
    case 201:
      return `reply:`;
    case 202:
    case 203:
      return `replyErr:`;
    case 204:
      return `event:`;
  }
}
var State6;
(function(State14) {
  State14[State14["Uninitialized"] = 0] = "Uninitialized";
  State14[State14["Idle"] = 1] = "Idle";
})(State6 || (State6 = {}));
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 = $Ci.alloc(len);
  for (let i2 = 0; value !== 0; i2++) {
    scratch.buffer[i2] = value & 127;
    value = value >>> 7;
    if (value > 0) {
      scratch.buffer[i2] |= 128;
    }
  }
  writer.write(scratch);
}
var $du = 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 $eu = class {
  constructor() {
    this.a = [];
  }
  get buffer() {
    return $Ci.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 = $Ci.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 $fu(writer, data) {
  if (typeof data === "undefined") {
    writer.write(BufferPresets.Undefined);
  } else if (typeof data === "string") {
    const buffer = $Ci.fromString(data);
    writer.write(BufferPresets.String);
    writeInt32VQL(writer, buffer.byteLength);
    writer.write(buffer);
  } else if (hasBuffer2 && Buffer.isBuffer(data)) {
    const buffer = $Ci.wrap(data);
    writer.write(BufferPresets.Buffer);
    writeInt32VQL(writer, buffer.byteLength);
    writer.write(buffer);
  } else if (data instanceof $Ci) {
    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) {
      $fu(writer, el);
    }
  } else if (typeof data === "number" && (data | 0) === data) {
    writer.write(BufferPresets.Uint);
    writeInt32VQL(writer, data);
  } else {
    const buffer = $Ci.fromString(JSON.stringify(data));
    writer.write(BufferPresets.Object);
    writeInt32VQL(writer, buffer.byteLength);
    writer.write(buffer);
  }
}
function $gu(reader) {
  const type = reader.read(1).readUInt8(0);
  switch (type) {
    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 i2 = 0; i2 < length; i2++) {
        result.push($gu(reader));
      }
      return result;
    }
    case DataType.Object:
      return JSON.parse(reader.read(readIntVQL(reader)).toString());
    case DataType.Int:
      return readIntVQL(reader);
  }
}
var $hu = class {
  constructor(h3, j, k = null, l = 1e3) {
    this.h = h3;
    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 $eu();
    $fu(writer, header);
    $fu(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 $du(message);
    const header = $gu(reader);
    const body = $gu(reader);
    const type = header[0];
    switch (type) {
      case 100:
        this.k?.logIncoming(message.byteLength, header[1], 1, `${requestTypeToStr(type)}: ${header[2]}.${header[3]}`, body);
        return this.s({ type, id: header[1], channelName: header[2], name: header[3], arg: body });
      case 102:
        this.k?.logIncoming(message.byteLength, header[1], 1, `${requestTypeToStr(type)}: ${header[2]}.${header[3]}`, body);
        return this.t({ type, id: header[1], channelName: header[2], name: header[3], arg: body });
      case 101:
        this.k?.logIncoming(message.byteLength, header[1], 1, `${requestTypeToStr(type)}`);
        return this.u({ type, id: header[1] });
      case 103:
        this.k?.logIncoming(message.byteLength, header[1], 1, `${requestTypeToStr(type)}`);
        return this.u({ type, id: header[1] });
    }
  }
  s(request) {
    const channel = this.b.get(request.channelName);
    if (!channel) {
      this.v(request);
      return;
    }
    const cancellationTokenSource = new $ad();
    let promise;
    try {
      promise = channel.call(this.j, request.name, request.arg, cancellationTokenSource.token);
    } catch (err) {
      promise = Promise.reject(err);
    }
    const id2 = request.id;
    promise.then((data) => {
      this.m({
        id: id2,
        data,
        type: 201
        /* ResponseType.PromiseSuccess */
      });
    }, (err) => {
      if (err instanceof Error) {
        this.m({
          id: id2,
          data: {
            message: err.message,
            name: err.name,
            stack: err.stack ? err.stack.split("\n") : void 0
          },
          type: 202
          /* ResponseType.PromiseError */
        });
      } else {
        this.m({
          id: id2,
          data: err,
          type: 203
          /* ResponseType.PromiseErrorObj */
        });
      }
    }).finally(() => {
      disposable.dispose();
      this.d.delete(request.id);
    });
    const disposable = $1c(() => cancellationTokenSource.cancel());
    this.d.set(request.id, disposable);
  }
  t(request) {
    const channel = this.b.get(request.channelName);
    if (!channel) {
      this.v(request);
      return;
    }
    const id2 = request.id;
    const event = channel.listen(this.j, request.name, request.arg);
    const disposable = event((data) => this.m({
      id: id2,
      data,
      type: 204
      /* ResponseType.EventFire */
    }));
    this.d.set(request.id, disposable);
  }
  u(request) {
    const disposable = this.d.get(request.id);
    if (disposable) {
      disposable.dispose();
      this.d.delete(request.id);
    }
  }
  v(request) {
    let pendingRequests = this.g.get(request.channelName);
    if (!pendingRequests) {
      pendingRequests = [];
      this.g.set(request.channelName, pendingRequests);
    }
    const timer = setTimeout(() => {
      console.error(`Unknown channel: ${request.channelName}`);
      if (request.type === 100) {
        this.m({
          id: request.id,
          data: { name: "Unknown channel", message: `Channel name '${request.channelName}' timed out after ${this.l}ms`, stack: void 0 },
          type: 202
          /* ResponseType.PromiseError */
        });
      }
    }, this.l);
    pendingRequests.push({ request, timeoutTimer: timer });
  }
  w(channelName) {
    const requests = this.g.get(channelName);
    if (requests) {
      for (const request of requests) {
        clearTimeout(request.timeoutTimer);
        switch (request.request.type) {
          case 100:
            this.s(request.request);
            break;
          case 102:
            this.t(request.request);
            break;
        }
      }
      this.g.delete(channelName);
    }
  }
  dispose() {
    if (this.f) {
      this.f.dispose();
      this.f = null;
    }
    $Xc(this.d.values());
    this.d.clear();
  }
};
var RequestInitiator;
(function(RequestInitiator3) {
  RequestInitiator3[RequestInitiator3["LocalSide"] = 0] = "LocalSide";
  RequestInitiator3[RequestInitiator3["OtherSide"] = 1] = "OtherSide";
})(RequestInitiator || (RequestInitiator = {}));
var $iu = class {
  constructor(l, logger2 = null) {
    this.l = l;
    this.a = false;
    this.b = State6.Uninitialized;
    this.d = /* @__PURE__ */ new Set();
    this.f = /* @__PURE__ */ new Map();
    this.g = 0;
    this.k = new $ze();
    this.onDidInitialize = this.k.event;
    this.h = this.l.onMessage((msg) => this.s(msg));
    this.j = logger2;
  }
  getChannel(channelName) {
    const that = this;
    return {
      call(command4, arg, cancellationToken) {
        if (that.a) {
          return Promise.reject(new $lb());
        }
        return that.m(channelName, command4, arg, cancellationToken);
      },
      listen(event, arg) {
        if (that.a) {
          return Event2.None;
        }
        return that.o(channelName, event, arg);
      }
    };
  }
  m(channelName, name, arg, cancellationToken = CancellationToken.None) {
    const id2 = this.g++;
    const type = 100;
    const request = { id: id2, type, channelName, name, arg };
    if (cancellationToken.isCancellationRequested) {
      return Promise.reject(new $lb());
    }
    let disposable;
    let disposableWithRequestCancel;
    const result = new Promise((c, e) => {
      if (cancellationToken.isCancellationRequested) {
        return e(new $lb());
      }
      const doRequest = () => {
        const handler = (response) => {
          switch (response.type) {
            case 201:
              this.f.delete(id2);
              c(response.data);
              break;
            case 202: {
              this.f.delete(id2);
              const error = new Error(response.data.message);
              error.stack = Array.isArray(response.data.stack) ? response.data.stack.join("\n") : response.data.stack;
              error.name = response.data.name;
              e(error);
              break;
            }
            case 203:
              this.f.delete(id2);
              e(response.data);
              break;
          }
        };
        this.f.set(id2, handler);
        this.p(request);
      };
      let uninitializedPromise = null;
      if (this.b === State6.Idle) {
        doRequest();
      } else {
        uninitializedPromise = $Hh((_) => 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 $lb());
      };
      disposable = cancellationToken.onCancellationRequested(cancel);
      disposableWithRequestCancel = {
        dispose: $Qc(() => {
          cancel();
          disposable.dispose();
        })
      };
      this.d.add(disposableWithRequestCancel);
    });
    return result.finally(() => {
      disposable.dispose();
      this.d.delete(disposableWithRequestCancel);
    });
  }
  o(channelName, name, arg) {
    const id2 = this.g++;
    const type = 102;
    const request = { id: id2, type, channelName, name, arg };
    let uninitializedPromise = null;
    const emitter = new $ze({
      onWillAddFirstListener: () => {
        const doRequest = () => {
          this.d.add(emitter);
          this.p(request);
        };
        if (this.b === State6.Idle) {
          doRequest();
        } else {
          uninitializedPromise = $Hh((_) => this.u());
          uninitializedPromise.then(() => {
            uninitializedPromise = null;
            doRequest();
          });
        }
      },
      onDidRemoveLastListener: () => {
        if (uninitializedPromise) {
          uninitializedPromise.cancel();
          uninitializedPromise = null;
        } else {
          this.d.delete(emitter);
          this.p({
            id: id2,
            type: 103
            /* RequestType.EventDispose */
          });
        }
      }
    });
    const handler = (res) => emitter.fire(res.data);
    this.f.set(id2, handler);
    return emitter.event;
  }
  p(request) {
    switch (request.type) {
      case 100:
      case 102: {
        const msgLength = this.q([request.type, request.id, request.channelName, request.name], request.arg);
        this.j?.logOutgoing(msgLength, request.id, 0, `${requestTypeToStr(request.type)}: ${request.channelName}.${request.name}`, request.arg);
        return;
      }
      case 101:
      case 103: {
        const msgLength = this.q([request.type, request.id]);
        this.j?.logOutgoing(msgLength, request.id, 0, requestTypeToStr(request.type));
        return;
      }
    }
  }
  q(header, body = void 0) {
    const writer = new $eu();
    $fu(writer, header);
    $fu(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 $du(message);
    const header = $gu(reader);
    const body = $gu(reader);
    const type = header[0];
    switch (type) {
      case 200:
        this.j?.logIncoming(message.byteLength, 0, 0, responseTypeToStr(type));
        return this.t({ type: header[0] });
      case 201:
      case 202:
      case 204:
      case 203:
        this.j?.logIncoming(message.byteLength, header[1], 0, responseTypeToStr(type), body);
        return this.t({ type: header[0], id: header[1], data: body });
    }
  }
  t(response) {
    if (response.type === 200) {
      this.b = State6.Idle;
      this.k.fire();
      return;
    }
    const handler = this.f.get(response.id);
    handler?.(response);
  }
  get onDidInitializePromise() {
    return Event2.toPromise(this.onDidInitialize);
  }
  u() {
    if (this.b === State6.Idle) {
      return Promise.resolve();
    } else {
      return this.onDidInitializePromise;
    }
  }
  dispose() {
    this.a = true;
    if (this.h) {
      this.h.dispose();
      this.h = null;
    }
    $Xc(this.d.values());
    this.d.clear();
  }
};
__decorate([
  $0t
], $iu.prototype, "onDidInitializePromise", null);
var $ku = class {
  constructor(protocol, ctx, ipcLogger = null) {
    const writer = new $eu();
    $fu(writer, ctx);
    protocol.send(writer.buffer);
    this.a = new $iu(protocol, ipcLogger);
    this.d = new $hu(protocol, ctx, ipcLogger);
  }
  getChannel(channelName) {
    return this.a.getChannel(channelName);
  }
  registerChannel(channelName, channel) {
    this.d.registerChannel(channelName, channel);
  }
  dispose() {
    this.a.dispose();
    this.d.dispose();
  }
};
function $lu(promise) {
  return {
    call(command4, arg, cancellationToken) {
      return promise.then((c) => c.call(command4, arg, cancellationToken));
    },
    listen(event, arg) {
      const relay = new $Ie();
      promise.then((c) => relay.input = c.listen(event, arg));
      return relay.event;
    }
  };
}
var ProxyChannel;
(function(ProxyChannel2) {
  function fromService(service, disposables, options3) {
    const handler = service;
    const disableMarshalling = options3 && options3.disableMarshalling;
    const mapEventNameToEvent = /* @__PURE__ */ new Map();
    for (const key2 in handler) {
      if (propertyIsEvent2(key2)) {
        mapEventNameToEvent.set(key2, Event2.buffer(handler[key2], 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 (propertyIsDynamicEvent2(event)) {
            return target.call(handler, arg);
          }
          if (propertyIsEvent2(event)) {
            mapEventNameToEvent.set(event, Event2.buffer(handler[event], true, void 0, disposables));
            return mapEventNameToEvent.get(event);
          }
        }
        throw new $ub(`Event not found: ${event}`);
      }
      call(_, command4, args2) {
        const target = handler[command4];
        if (typeof target === "function") {
          if (!disableMarshalling && Array.isArray(args2)) {
            for (let i2 = 0; i2 < args2.length; i2++) {
              args2[i2] = $cu(args2[i2]);
            }
          }
          let res = target.apply(handler, args2);
          if (!(res instanceof Promise)) {
            res = Promise.resolve(res);
          }
          return res;
        }
        throw new $ub(`Method not found: ${command4}`);
      }
    }();
  }
  ProxyChannel2.fromService = fromService;
  function toService(channel, options3) {
    const disableMarshalling = options3 && options3.disableMarshalling;
    return new Proxy({}, {
      get(_target, propKey) {
        if (typeof propKey === "string") {
          if (options3?.properties?.has(propKey)) {
            return options3.properties.get(propKey);
          }
          if (propertyIsDynamicEvent2(propKey)) {
            return function(arg) {
              return channel.listen(propKey, arg);
            };
          }
          if (propertyIsEvent2(propKey)) {
            return channel.listen(propKey);
          }
          return async function(...args2) {
            let methodArgs;
            if (options3 && !$Ig(options3.context)) {
              methodArgs = [options3.context, ...args2];
            } else {
              methodArgs = args2;
            }
            const result = await channel.call(propKey, methodArgs);
            if (!disableMarshalling) {
              return $cu(result);
            }
            return result;
          };
        }
        throw new $ub(`Property not found: ${String(propKey)}`);
      }
    });
  }
  ProxyChannel2.toService = toService;
  function propertyIsEvent2(name) {
    return name[0] === "o" && name[1] === "n" && $Zf(name.charCodeAt(2));
  }
  function propertyIsDynamicEvent2(name) {
    return /^onDynamic/.test(name) && $Zf(name.charCodeAt(9));
  }
})(ProxyChannel || (ProxyChannel = {}));

// 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, label3) {
    if (!socketIds.has(nativeObject)) {
      const id2 = String(++lastUsedSocketId);
      socketIds.set(nativeObject, id2);
    }
    return socketIds.get(nativeObject);
  }
  function traceSocketEvent(nativeObject, socketDebugLabel, type, data) {
    if (!SocketDiagnostics2.enableDiagnostics) {
      return;
    }
    const id2 = getSocketId(nativeObject, socketDebugLabel);
    if (data instanceof $Ci || data instanceof Uint8Array || data instanceof ArrayBuffer || ArrayBuffer.isView(data)) {
      const copiedData = $Ci.alloc(data.byteLength);
      copiedData.set(data);
      SocketDiagnostics2.records.push({ timestamp: Date.now(), id: id2, label: socketDebugLabel, type, buff: copiedData });
    } else {
      SocketDiagnostics2.records.push({ timestamp: Date.now(), id: id2, label: socketDebugLabel, type, 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 = $Ci.alloc(0);
  }
  return emptyBuffer;
}
var $pu = 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 = $Ci.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(type, id2, ack, data) {
    this.type = type;
    this.id = id2;
    this.ack = ack;
    this.data = data;
    this.writtenTime = 0;
  }
  get size() {
    return this.data.byteLength;
  }
};
var ProtocolReader = class extends $3c {
  constructor(socket) {
    super();
    this.f = this.B(new $ze());
    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 $pu();
    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 = $Ci.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 = $Ci.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 $qu = class extends $3c {
  constructor(socket) {
    super();
    this.f = new $ze();
    this.onMessage = this.f.event;
    this.g = new $ze();
    this.onDidDispose = this.g.event;
    this.a = socket;
    this.b = this.B(new ProtocolWriter(this.a));
    this.c = this.B(new ProtocolReader(this.a));
    this.B(this.c.onMessage((msg) => {
      if (msg.type === 1) {
        this.f.fire(msg.data);
      }
    }));
    this.B(this.a.onClose(() => this.g.fire()));
  }
  drain() {
    return this.b.drain();
  }
  getSocket() {
    return this.a;
  }
  sendDisconnect() {
  }
  send(buffer) {
    this.b.write(new ProtocolMessage(1, 0, 0, buffer));
  }
};
var $ru = class _$ru extends $ku {
  static fromSocket(socket, id2) {
    return new _$ru(new $qu(socket), id2);
  }
  get onDidDispose() {
    return this.b.onDidDispose;
  }
  constructor(b, id2, ipcLogger = null) {
    super(b, id2, ipcLogger);
    this.b = b;
  }
  dispose() {
    super.dispose();
    const socket = this.b.getSocket();
    this.b.sendDisconnect();
    this.b.dispose();
    socket.end();
  }
};
var $su = class {
  constructor() {
    this.b = false;
    this.c = false;
    this.d = [];
    this.a = new $ze({
      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 i2 = 0; i2 < _LoadEstimator.a; i2++) {
      this.c[i2] = now - 1e3 * i2;
    }
    setInterval(() => {
      for (let i2 = _LoadEstimator.a; i2 >= 1; i2--) {
        this.c[i2] = this.c[i2 - 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 score2 = 0;
    for (let i2 = 0; i2 < _LoadEstimator.a; i2++) {
      if (now - this.c[i2] <= historyLimit) {
        score2++;
      }
    }
    return 1 - score2 / _LoadEstimator.a;
  }
  hasHighLoad() {
    return this.d() >= 0.5;
  }
};
var $tu = class {
  get unacknowledgedCount() {
    return this.d - this.f;
  }
  constructor(opts) {
    this.v = new $su();
    this.onControlMessage = this.v.event;
    this.w = new $su();
    this.onMessage = this.w.event;
    this.x = new $su();
    this.onDidDispose = this.x.event;
    this.y = new $su();
    this.onSocketClose = this.y.event;
    this.z = new $su();
    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 $2c();
    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 $2c();
    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 i2 = 0, len = toSend.length; i2 < len; i2++) {
      this.q.write(toSend[i2]);
    }
    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 i2 = 0, len = toSend.length; i2 < len; i2++) {
          this.q.write(toSend[i2]);
        }
        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/platform/remote/common/managedSocket.js
var $wQb = (path, query, deubgLabel) => {
  const buffer = new Uint8Array(16);
  for (let i2 = 0; i2 < 16; i2++) {
    buffer[i2] = Math.round(Math.random() * 256);
  }
  const nonce = $Wi($Ci.wrap(buffer));
  const headers = [
    `GET ws://localhost${path}?${query}&skipWebSocketFrames=true HTTP/1.1`,
    `Connection: Upgrade`,
    `Upgrade: websocket`,
    `Sec-WebSocket-Key: ${nonce}`
  ];
  return headers.join("\r\n") + "\r\n\r\n";
};
var $xQb = $Ci.fromString("\r\n\r\n");
async function $yQb(socket, path, query, debugLabel, half) {
  socket.write($Ci.fromString($wQb(path, query, debugLabel)));
  const d = new $2c();
  try {
    return await new Promise((resolve, reject) => {
      let dataSoFar;
      d.add(socket.onData((d_1) => {
        if (!dataSoFar) {
          dataSoFar = d_1;
        } else {
          dataSoFar = $Ci.concat([dataSoFar, d_1], dataSoFar.byteLength + d_1.byteLength);
        }
        const index = dataSoFar.indexOf($xQb);
        if (index === -1) {
          return;
        }
        resolve(socket);
        socket.pauseData();
        const rest = dataSoFar.slice(index + $xQb.byteLength);
        if (rest.byteLength) {
          half.onData.fire(rest);
        }
      }));
      d.add(socket.onClose((err) => reject(err ?? new Error("socket closed"))));
      d.add(socket.onEnd(() => reject(new Error("socket ended"))));
    });
  } catch (e) {
    socket.dispose();
    throw e;
  } finally {
    d.dispose();
  }
}
var $zQb = class extends $3c {
  constructor(g, half) {
    super();
    this.g = g;
    this.a = this.B(new $Ce());
    this.onData = (...args2) => {
      if (this.a.isPaused) {
        queueMicrotask(() => this.a.resume());
      }
      return this.a.event(...args2);
    };
    this.b = this.B(new $ze());
    this.onDidDispose = this.b.event;
    this.f = false;
    this.B(half.onData);
    this.B(half.onData.event((data) => this.a.fire(data)));
    this.onClose = this.B(half.onClose).event;
    this.onEnd = this.B(half.onEnd).event;
  }
  /** Pauses data events until a new listener comes in onData() */
  pauseData() {
    this.a.pause();
  }
  /** Flushes data to the socket. */
  drain() {
    return Promise.resolve();
  }
  /** Ends the remote socket. */
  end() {
    this.f = true;
    this.h();
  }
  traceSocketEvent(type, data) {
    SocketDiagnostics.traceSocketEvent(this, this.g, type, data);
  }
  dispose() {
    if (!this.f) {
      this.h();
    }
    this.b.fire();
    super.dispose();
  }
};

// out-build/vs/platform/remote/common/remoteSocketFactoryService.js
var $gC = $Qk("remoteSocketFactoryService");
var $hC = class {
  constructor() {
    this.a = {};
  }
  register(type, factory) {
    this.a[type] ??= [];
    this.a[type].push(factory);
    return $1c(() => {
      const idx = this.a[type]?.indexOf(factory);
      if (typeof idx === "number" && idx >= 0) {
        this.a[type]?.splice(idx, 1);
      }
    });
  }
  b(messagePassing) {
    const factories = this.a[messagePassing.type] || [];
    return factories.find((factory) => factory.supports(messagePassing));
  }
  connect(connectTo, path, query, debugLabel) {
    const socketFactory = this.b(connectTo);
    if (!socketFactory) {
      throw new Error(`No socket factory found for ${connectTo}`);
    }
    return socketFactory.connect(connectTo, path, query, debugLabel);
  }
};

// out-build/vs/workbench/api/browser/mainThreadManagedSockets.js
var $AQb = class $AQb2 extends $3c {
  constructor(extHostContext, f) {
    super();
    this.f = f;
    this.b = /* @__PURE__ */ new Map();
    this.c = /* @__PURE__ */ new Map();
    this.a = extHostContext.getProxy($yT.ExtHostManagedSockets);
  }
  async $registerSocketFactory(socketFactoryId) {
    const that = this;
    const socketFactory = new class {
      supports(connectTo) {
        return connectTo.id === socketFactoryId;
      }
      connect(connectTo, path, query, debugLabel) {
        return new Promise((resolve, reject) => {
          if (connectTo.id !== socketFactoryId) {
            return reject(new Error("Invalid connectTo"));
          }
          const factoryId = connectTo.id;
          that.a.$openRemoteSocket(factoryId).then((socketId) => {
            const half = {
              onClose: new $ze(),
              onData: new $ze(),
              onEnd: new $ze()
            };
            that.c.set(socketId, half);
            $BQb.connect(socketId, that.a, path, query, debugLabel, half).then((socket) => {
              socket.onDidDispose(() => that.c.delete(socketId));
              resolve(socket);
            }, (err) => {
              that.c.delete(socketId);
              reject(err);
            });
          }).catch(reject);
        });
      }
    }();
    this.b.set(socketFactoryId, this.f.register(1, socketFactory));
  }
  async $unregisterSocketFactory(socketFactoryId) {
    this.b.get(socketFactoryId)?.dispose();
  }
  $onDidManagedSocketHaveData(socketId, data) {
    this.c.get(socketId)?.onData.fire(data);
  }
  $onDidManagedSocketClose(socketId, error) {
    this.c.get(socketId)?.onClose.fire({
      type: 0,
      error: error ? new Error(error) : void 0,
      hadError: !!error
    });
    this.c.delete(socketId);
  }
  $onDidManagedSocketEnd(socketId) {
    this.c.get(socketId)?.onEnd.fire();
  }
};
$AQb = __decorate([
  $frb($xT.MainThreadManagedSockets),
  __param(1, $gC)
], $AQb);
var $BQb = class _$BQb extends $zQb {
  static connect(socketId, proxy, path, query, debugLabel, half) {
    const socket = new _$BQb(socketId, proxy, debugLabel, half);
    return $yQb(socket, path, query, debugLabel, half);
  }
  constructor(c, j, debugLabel, half) {
    super(debugLabel, half);
    this.c = c;
    this.j = j;
  }
  write(buffer) {
    this.j.$remoteSocketWrite(this.c, buffer);
  }
  h() {
    this.j.$remoteSocketEnd(this.c);
  }
  drain() {
    return this.j.$remoteSocketDrain(this.c);
  }
};

// out-build/vs/workbench/services/output/common/output.js
var $GS = "text/x-code-output";
var $HS = "Log";
var $IS = "text/x-code-log-output";
var $JS = "log";
var $KS = "workbench.panel.output";
var $LS = new $nn("inOutput", false);
var $MS = new $nn("activeLogOutput", false);
var $NS = new $nn("activeLogOutput.levelSettable", false);
var $OS = new $nn("activeLogOutput.level", "");
var $PS = new $nn("activeLogOutput.levelIsDefault", false);
var $QS = new $nn(`outputView.scrollLock`, false);
var $RS = $Qk("outputService");
var OutputChannelUpdateMode;
(function(OutputChannelUpdateMode2) {
  OutputChannelUpdateMode2[OutputChannelUpdateMode2["Append"] = 1] = "Append";
  OutputChannelUpdateMode2[OutputChannelUpdateMode2["Replace"] = 2] = "Replace";
  OutputChannelUpdateMode2[OutputChannelUpdateMode2["Clear"] = 3] = "Clear";
})(OutputChannelUpdateMode || (OutputChannelUpdateMode = {}));
var $SS = {
  OutputChannels: "workbench.contributions.outputChannels"
};
var OutputChannelRegistry = class {
  constructor() {
    this.a = /* @__PURE__ */ new Map();
    this.b = new $ze();
    this.onDidRegisterChannel = this.b.event;
    this.c = new $ze();
    this.onDidRemoveChannel = this.c.event;
  }
  registerChannel(descriptor) {
    if (!this.a.has(descriptor.id)) {
      this.a.set(descriptor.id, descriptor);
      this.b.fire(descriptor.id);
    }
  }
  getChannels() {
    const result = [];
    this.a.forEach((value) => result.push(value));
    return result;
  }
  getChannel(id2) {
    return this.a.get(id2);
  }
  removeChannel(id2) {
    this.a.delete(id2);
    this.c.fire(id2);
  }
};
$Wn.add($SS.OutputChannels, new OutputChannelRegistry());
var $TS = new $nn("activeOutputChannel", "");

// out-build/vs/workbench/api/browser/mainThreadOutputService.js
var $CQb_1;
var $CQb = class $CQb2 extends $3c {
  static {
    $CQb_1 = this;
  }
  static {
    this.a = /* @__PURE__ */ new Map();
  }
  constructor(extHostContext, outputService, viewsService, configurationService, statusbarService) {
    super();
    this.j = this.B(new $4c());
    this.c = outputService;
    this.f = viewsService;
    this.g = configurationService;
    this.h = statusbarService;
    this.b = extHostContext.getProxy($yT.ExtHostOutputService);
    const setVisibleChannel = () => {
      const visibleChannel = this.f.isViewVisible($KS) ? this.c.getActiveChannel() : void 0;
      this.b.$setVisibleChannel(visibleChannel ? visibleChannel.id : null);
      this.j.value = void 0;
    };
    this.B(Event2.any(this.c.onActiveOutputChannel, Event2.filter(this.f.onDidChangeViewVisibility, ({ id: id2 }) => id2 === $KS))(() => setVisibleChannel()));
    setVisibleChannel();
  }
  async $register(label3, file, languageId, extensionId) {
    const idCounter2 = ($CQb_1.a.get(extensionId) || 0) + 1;
    $CQb_1.a.set(extensionId, idCounter2);
    const id2 = `extension-output-${extensionId}-#${idCounter2}-${label3}`;
    const resource = URI.revive(file);
    $Wn.as($SS.OutputChannels).registerChannel({ id: id2, label: label3, file: resource, log: false, languageId, extensionId });
    this.B($1c(() => this.$dispose(id2)));
    return id2;
  }
  async $update(channelId, mode, till) {
    const channel = this.n(channelId);
    if (channel) {
      if (mode === OutputChannelUpdateMode.Append) {
        channel.update(mode);
      } else if ($Dg(till)) {
        channel.update(mode, till);
      }
    }
  }
  async $reveal(channelId, preserveFocus) {
    const channel = this.n(channelId);
    if (!channel) {
      return;
    }
    const viewsToShowQuietly = this.g.getValue("workbench.view.showQuietly") ?? {};
    if (!this.f.isViewVisible($KS) && viewsToShowQuietly[$KS]) {
      this.m(channel);
      return;
    }
    this.c.showChannel(channel.id, preserveFocus);
  }
  // Show status bar indicator
  m(channel) {
    const statusProperties = {
      name: localize(2621, null),
      text: "$(output)",
      ariaLabel: localize(2622, null, channel.label),
      command: `workbench.action.output.show.${channel.id}`,
      tooltip: localize(2623, null, channel.label),
      kind: "prominent"
    };
    if (!this.j.value) {
      this.j.value = this.h.addEntry(statusProperties, "status.view.showQuietly", 1, {
        id: "status.notifications",
        alignment: 0
        /* StatusbarAlignment.LEFT */
      });
    } else {
      this.j.value.update(statusProperties);
    }
  }
  async $close(channelId) {
    if (this.f.isViewVisible($KS)) {
      const activeChannel = this.c.getActiveChannel();
      if (activeChannel && channelId === activeChannel.id) {
        this.f.closeView($KS);
      }
    }
  }
  async $dispose(channelId) {
    const channel = this.n(channelId);
    channel?.dispose();
  }
  n(channelId) {
    return this.c.getChannel(channelId);
  }
};
$CQb = $CQb_1 = __decorate([
  $frb($xT.MainThreadOutputService),
  __param(1, $RS),
  __param(2, $uob),
  __param(3, $kl),
  __param(4, $$qb)
], $CQb);

// out-build/vs/workbench/api/browser/mainThreadProgress.js
var ManageExtensionAction = class extends $Um {
  constructor(extensionId, label3, commandService) {
    super(extensionId, label3, void 0, true, () => {
      return commandService.executeCommand("_extensions.manage", extensionId);
    });
  }
};
var $DQb = class $DQb2 {
  constructor(extHostContext, progressService, d) {
    this.d = d;
    this.b = /* @__PURE__ */ new Map();
    this.c = extHostContext.getProxy($yT.ExtHostProgress);
    this.a = progressService;
  }
  dispose() {
    this.b.forEach((handle2) => handle2.resolve());
    this.b.clear();
  }
  async $startProgress(handle2, options3, extensionId) {
    const task = this.e(handle2);
    if (options3.location === 15 && extensionId) {
      const notificationOptions = {
        ...options3,
        location: 15,
        secondaryActions: [new ManageExtensionAction(extensionId, localize(2624, null), this.d)]
      };
      options3 = notificationOptions;
    }
    this.a.withProgress(options3, task, () => this.c.$acceptProgressCanceled(handle2));
  }
  $progressReport(handle2, message) {
    const entry = this.b.get(handle2);
    entry?.progress.report(message);
  }
  $progressEnd(handle2) {
    const entry = this.b.get(handle2);
    if (entry) {
      entry.resolve();
      this.b.delete(handle2);
    }
  }
  e(handle2) {
    return (progress) => {
      return new Promise((resolve) => {
        this.b.set(handle2, { resolve, progress });
      });
    };
  }
};
$DQb = __decorate([
  $frb($xT.MainThreadProgress),
  __param(1, $TJ),
  __param(2, $sn)
], $DQb);

// out-build/vs/workbench/api/browser/mainThreadQuickDiff.js
var $EQb = class $EQb2 {
  constructor(extHostContext, c) {
    this.c = c;
    this.b = new $_c();
    this.a = extHostContext.getProxy($yT.ExtHostQuickDiff);
  }
  async $registerQuickDiffProvider(handle2, selector, label3, rootUri, visible) {
    const provider = {
      label: label3,
      rootUri: URI.revive(rootUri),
      selector,
      isSCM: false,
      visible,
      getOriginalResource: async (uri) => {
        return URI.revive(await this.a.$provideOriginalResource(handle2, uri, CancellationToken.None));
      }
    };
    const disposable = this.c.addQuickDiffProvider(provider);
    this.b.set(handle2, disposable);
  }
  async $unregisterQuickDiffProvider(handle2) {
    if (this.b.has(handle2)) {
      this.b.deleteAndDispose(handle2);
    }
  }
  dispose() {
    this.b.dispose();
  }
};
$EQb = __decorate([
  $frb($xT.MainThreadQuickDiff),
  __param(1, $AEb)
], $EQb);

// out-build/vs/workbench/api/browser/mainThreadQuickOpen.js
function reviveIconPathUris(iconPath) {
  iconPath.dark = URI.revive(iconPath.dark);
  if (iconPath.light) {
    iconPath.light = URI.revive(iconPath.light);
  }
}
var $FQb = class $FQb2 {
  constructor(extHostContext, quickInputService) {
    this.c = {};
    this.d = /* @__PURE__ */ new Map();
    this.a = extHostContext.getProxy($yT.ExtHostQuickOpen);
    this.b = quickInputService;
  }
  dispose() {
    for (const [_id, session] of this.d) {
      session.store.dispose();
    }
  }
  $show(instance2, options3, token) {
    const contents = new Promise((resolve, reject) => {
      this.c[instance2] = { resolve, reject };
    });
    options3 = {
      ...options3,
      onDidFocus: (el) => {
        if (el) {
          this.a.$onItemSelected(el.handle);
        }
      }
    };
    if (options3.canPickMany) {
      return this.b.pick(contents, options3, token).then((items) => {
        if (items) {
          return items.map((item) => item.handle);
        }
        return void 0;
      });
    } else {
      return this.b.pick(contents, options3, token).then((item) => {
        if (item) {
          return item.handle;
        }
        return void 0;
      });
    }
  }
  $setItems(instance2, items) {
    if (this.c[instance2]) {
      this.c[instance2].resolve(items);
      delete this.c[instance2];
    }
    return Promise.resolve();
  }
  $setError(instance2, error) {
    if (this.c[instance2]) {
      this.c[instance2].reject(error);
      delete this.c[instance2];
    }
    return Promise.resolve();
  }
  // ---- input
  $input(options3, validateInput, token) {
    const inputOptions2 = /* @__PURE__ */ Object.create(null);
    if (options3) {
      inputOptions2.title = options3.title;
      inputOptions2.password = options3.password;
      inputOptions2.placeHolder = options3.placeHolder;
      inputOptions2.valueSelection = options3.valueSelection;
      inputOptions2.prompt = options3.prompt;
      inputOptions2.value = options3.value;
      inputOptions2.ignoreFocusLost = options3.ignoreFocusOut;
    }
    if (validateInput) {
      inputOptions2.validateInput = (value) => {
        return this.a.$validateInput(value);
      };
    }
    return this.b.input(inputOptions2, token);
  }
  $createOrUpdate(params) {
    const sessionId = params.id;
    let session = this.d.get(sessionId);
    if (!session) {
      const store = new $2c();
      const input2 = params.type === "quickPick" ? this.b.createQuickPick() : this.b.createInputBox();
      store.add(input2);
      store.add(input2.onDidAccept(() => {
        this.a.$onDidAccept(sessionId);
      }));
      store.add(input2.onDidTriggerButton((button) => {
        this.a.$onDidTriggerButton(sessionId, button.handle);
      }));
      store.add(input2.onDidChangeValue((value) => {
        this.a.$onDidChangeValue(sessionId, value);
      }));
      store.add(input2.onDidHide(() => {
        this.a.$onDidHide(sessionId);
      }));
      if (params.type === "quickPick") {
        const quickpick = input2;
        store.add(quickpick.onDidChangeActive((items) => {
          this.a.$onDidChangeActive(sessionId, items.map((item) => item.handle));
        }));
        store.add(quickpick.onDidChangeSelection((items) => {
          this.a.$onDidChangeSelection(sessionId, items.map((item) => item.handle));
        }));
        store.add(quickpick.onDidTriggerItemButton((e) => {
          this.a.$onDidTriggerItemButton(sessionId, e.item.handle, e.button.handle);
        }));
      }
      session = {
        input: input2,
        handlesToItems: /* @__PURE__ */ new Map(),
        store
      };
      this.d.set(sessionId, session);
    }
    const { input, handlesToItems } = session;
    for (const param in params) {
      if (param === "id" || param === "type") {
        continue;
      }
      if (param === "visible") {
        if (params.visible) {
          input.show();
        } else {
          input.hide();
        }
      } else if (param === "items") {
        handlesToItems.clear();
        params[param].forEach((item) => {
          if (item.type === "separator") {
            return;
          }
          if (item.buttons) {
            item.buttons = item.buttons.map((button) => {
              if (button.iconPath) {
                reviveIconPathUris(button.iconPath);
              }
              return button;
            });
          }
          handlesToItems.set(item.handle, item);
        });
        input[param] = params[param];
      } else if (param === "activeItems" || param === "selectedItems") {
        input[param] = params[param].filter((handle2) => handlesToItems.has(handle2)).map((handle2) => handlesToItems.get(handle2));
      } else if (param === "buttons") {
        input[param] = params.buttons.map((button) => {
          if (button.handle === -1) {
            return this.b.backButton;
          }
          if (button.iconPath) {
            reviveIconPathUris(button.iconPath);
          }
          return button;
        });
      } else {
        input[param] = params[param];
      }
    }
    return Promise.resolve(void 0);
  }
  $dispose(sessionId) {
    const session = this.d.get(sessionId);
    if (session) {
      session.store.dispose();
      this.d.delete(sessionId);
    }
    return Promise.resolve(void 0);
  }
};
$FQb = __decorate([
  $frb($xT.MainThreadQuickOpen),
  __param(1, $1M)
], $FQb);

// out-build/vs/workbench/api/browser/mainThreadRemoteConnectionData.js
var $GQb = class $GQb2 extends $3c {
  constructor(extHostContext, b, remoteAuthorityResolverService) {
    super();
    this.b = b;
    this.a = extHostContext.getProxy($yT.ExtHostExtensionService);
    const remoteAuthority = this.b.remoteAuthority;
    if (remoteAuthority) {
      this.B(remoteAuthorityResolverService.onDidChangeConnectionData(() => {
        const connectionData = remoteAuthorityResolverService.getConnectionData(remoteAuthority);
        if (connectionData) {
          this.a.$updateRemoteConnectionData(connectionData);
        }
      }));
    }
  }
};
$GQb = __decorate([
  $grb,
  __param(1, $US),
  __param(2, $bC)
], $GQb);

// out-build/vs/workbench/api/browser/mainThreadSaveParticipant.js
var ExtHostSaveParticipant = class {
  constructor(extHostContext) {
    this.a = extHostContext.getProxy($yT.ExtHostDocumentSaveParticipant);
  }
  async participate(editorModel, context, _progress, token) {
    if (!editorModel.textEditorModel || !$kG(editorModel.textEditorModel)) {
      return void 0;
    }
    const p = new Promise((resolve, reject) => {
      setTimeout(() => reject(new Error(localize(2625, null))), 1750);
      this.a.$participateInSave(editorModel.resource, context.reason).then((values) => {
        if (!values.every((success) => success)) {
          return Promise.reject(new Error("listener failed"));
        }
        return void 0;
      }).then(resolve, reject);
    });
    return $Jh(p, token);
  }
};
var $HQb = class $HQb2 {
  constructor(extHostContext, instantiationService, b) {
    this.b = b;
    this.a = this.b.files.addSaveParticipant(instantiationService.createInstance(ExtHostSaveParticipant, extHostContext));
  }
  dispose() {
    this.a.dispose();
  }
};
$HQb = __decorate([
  $grb,
  __param(1, $Pk),
  __param(2, $cK)
], $HQb);

// out-build/vs/workbench/contrib/speech/common/speechService.js
var $jS = $Qk("speechService");
var $kS = new $nn("hasSpeechProvider", false, { type: "boolean", description: localize(9898, null) });
var $lS = new $nn("speechToTextInProgress", false, { type: "boolean", description: localize(9899, null) });
var $mS = new $nn("textToSpeechInProgress", false, { type: "boolean", description: localize(9900, null) });
var SpeechToTextStatus2;
(function(SpeechToTextStatus3) {
  SpeechToTextStatus3[SpeechToTextStatus3["Started"] = 1] = "Started";
  SpeechToTextStatus3[SpeechToTextStatus3["Recognizing"] = 2] = "Recognizing";
  SpeechToTextStatus3[SpeechToTextStatus3["Recognized"] = 3] = "Recognized";
  SpeechToTextStatus3[SpeechToTextStatus3["Stopped"] = 4] = "Stopped";
  SpeechToTextStatus3[SpeechToTextStatus3["Error"] = 5] = "Error";
})(SpeechToTextStatus2 || (SpeechToTextStatus2 = {}));
var TextToSpeechStatus2;
(function(TextToSpeechStatus3) {
  TextToSpeechStatus3[TextToSpeechStatus3["Started"] = 1] = "Started";
  TextToSpeechStatus3[TextToSpeechStatus3["Stopped"] = 2] = "Stopped";
  TextToSpeechStatus3[TextToSpeechStatus3["Error"] = 3] = "Error";
})(TextToSpeechStatus2 || (TextToSpeechStatus2 = {}));
var KeywordRecognitionStatus2;
(function(KeywordRecognitionStatus3) {
  KeywordRecognitionStatus3[KeywordRecognitionStatus3["Recognized"] = 1] = "Recognized";
  KeywordRecognitionStatus3[KeywordRecognitionStatus3["Stopped"] = 2] = "Stopped";
  KeywordRecognitionStatus3[KeywordRecognitionStatus3["Canceled"] = 3] = "Canceled";
})(KeywordRecognitionStatus2 || (KeywordRecognitionStatus2 = {}));
var AccessibilityVoiceSettingId;
(function(AccessibilityVoiceSettingId2) {
  AccessibilityVoiceSettingId2["SpeechTimeout"] = "accessibility.voice.speechTimeout";
  AccessibilityVoiceSettingId2["AutoSynthesize"] = "accessibility.voice.autoSynthesize";
  AccessibilityVoiceSettingId2["SpeechLanguage"] = "accessibility.voice.speechLanguage";
})(AccessibilityVoiceSettingId || (AccessibilityVoiceSettingId = {}));
var $nS = "accessibility.voice.speechLanguage";
var $oS = {
  ["da-DK"]: {
    name: localize(9901, null)
  },
  ["de-DE"]: {
    name: localize(9902, null)
  },
  ["en-AU"]: {
    name: localize(9903, null)
  },
  ["en-CA"]: {
    name: localize(9904, null)
  },
  ["en-GB"]: {
    name: localize(9905, null)
  },
  ["en-IE"]: {
    name: localize(9906, null)
  },
  ["en-IN"]: {
    name: localize(9907, null)
  },
  ["en-NZ"]: {
    name: localize(9908, null)
  },
  ["en-US"]: {
    name: localize(9909, null)
  },
  ["es-ES"]: {
    name: localize(9910, null)
  },
  ["es-MX"]: {
    name: localize(9911, null)
  },
  ["fr-CA"]: {
    name: localize(9912, null)
  },
  ["fr-FR"]: {
    name: localize(9913, null)
  },
  ["hi-IN"]: {
    name: localize(9914, null)
  },
  ["it-IT"]: {
    name: localize(9915, null)
  },
  ["ja-JP"]: {
    name: localize(9916, null)
  },
  ["ko-KR"]: {
    name: localize(9917, null)
  },
  ["nl-NL"]: {
    name: localize(9918, null)
  },
  ["pt-PT"]: {
    name: localize(9919, null)
  },
  ["pt-BR"]: {
    name: localize(9920, null)
  },
  ["ru-RU"]: {
    name: localize(9921, null)
  },
  ["sv-SE"]: {
    name: localize(9922, null)
  },
  ["tr-TR"]: {
    // allow-any-unicode-next-line
    name: localize(9923, null)
  },
  ["zh-CN"]: {
    name: localize(9924, null)
  },
  ["zh-HK"]: {
    name: localize(9925, null)
  },
  ["zh-TW"]: {
    name: localize(9926, null)
  }
};
function $pS(config, lang = $z) {
  if (typeof config === "string") {
    if (config === "auto") {
      if (lang !== "en") {
        const langParts = lang.split("-");
        return $pS(`${langParts[0]}-${(langParts[1] ?? langParts[0]).toUpperCase()}`);
      }
    } else {
      if ($oS[config]) {
        return config;
      }
    }
  }
  return "en-US";
}

// out-build/vs/workbench/api/browser/mainThreadSpeech.js
var $IQb = class $IQb2 {
  constructor(extHostContext, g, h3) {
    this.g = g;
    this.h = h3;
    this.b = /* @__PURE__ */ new Map();
    this.c = /* @__PURE__ */ new Map();
    this.d = /* @__PURE__ */ new Map();
    this.f = /* @__PURE__ */ new Map();
    this.a = extHostContext.getProxy($yT.ExtHostSpeech);
  }
  $registerProvider(handle2, identifier2, metadata) {
    this.h.trace("[Speech] extension registered provider", metadata.extension.value);
    const registration = this.g.registerSpeechProvider(identifier2, {
      metadata,
      createSpeechToTextSession: (token, options3) => {
        if (token.isCancellationRequested) {
          return {
            onDidChange: Event2.None
          };
        }
        const disposables = new $2c();
        const session = Math.random();
        this.a.$createSpeechToTextSession(handle2, session, options3?.language);
        const onDidChange = disposables.add(new $ze());
        this.c.set(session, { onDidChange });
        disposables.add(token.onCancellationRequested(() => {
          this.a.$cancelSpeechToTextSession(session);
          this.c.delete(session);
          disposables.dispose();
        }));
        return {
          onDidChange: onDidChange.event
        };
      },
      createTextToSpeechSession: (token, options3) => {
        if (token.isCancellationRequested) {
          return {
            onDidChange: Event2.None,
            synthesize: async () => {
            }
          };
        }
        const disposables = new $2c();
        const session = Math.random();
        this.a.$createTextToSpeechSession(handle2, session, options3?.language);
        const onDidChange = disposables.add(new $ze());
        this.d.set(session, { onDidChange });
        disposables.add(token.onCancellationRequested(() => {
          this.a.$cancelTextToSpeechSession(session);
          this.d.delete(session);
          disposables.dispose();
        }));
        return {
          onDidChange: onDidChange.event,
          synthesize: async (text2) => {
            await this.a.$synthesizeSpeech(session, text2);
            await $Ih(Event2.toPromise(Event2.filter(onDidChange.event, (e) => e.status === TextToSpeechStatus2.Stopped)), token);
          }
        };
      },
      createKeywordRecognitionSession: (token) => {
        if (token.isCancellationRequested) {
          return {
            onDidChange: Event2.None
          };
        }
        const disposables = new $2c();
        const session = Math.random();
        this.a.$createKeywordRecognitionSession(handle2, session);
        const onDidChange = disposables.add(new $ze());
        this.f.set(session, { onDidChange });
        disposables.add(token.onCancellationRequested(() => {
          this.a.$cancelKeywordRecognitionSession(session);
          this.f.delete(session);
          disposables.dispose();
        }));
        return {
          onDidChange: onDidChange.event
        };
      }
    });
    this.b.set(handle2, {
      dispose: () => {
        registration.dispose();
      }
    });
  }
  $unregisterProvider(handle2) {
    const registration = this.b.get(handle2);
    if (registration) {
      registration.dispose();
      this.b.delete(handle2);
    }
  }
  $emitSpeechToTextEvent(session, event) {
    const providerSession = this.c.get(session);
    providerSession?.onDidChange.fire(event);
  }
  $emitTextToSpeechEvent(session, event) {
    const providerSession = this.d.get(session);
    providerSession?.onDidChange.fire(event);
  }
  $emitKeywordRecognitionEvent(session, event) {
    const providerSession = this.f.get(session);
    providerSession?.onDidChange.fire(event);
  }
  dispose() {
    this.b.forEach((disposable) => disposable.dispose());
    this.b.clear();
    this.c.forEach((session) => session.onDidChange.dispose());
    this.c.clear();
    this.d.forEach((session) => session.onDidChange.dispose());
    this.d.clear();
    this.f.forEach((session) => session.onDidChange.dispose());
    this.f.clear();
  }
};
$IQb = __decorate([
  $frb($xT.MainThreadSpeech),
  __param(1, $jS),
  __param(2, $wn)
], $IQb);

// out-build/vs/platform/workspace/common/editSessions.js
var $2M = $Qk("editSessionIdentityService");
var EditSessionIdentityMatch;
(function(EditSessionIdentityMatch2) {
  EditSessionIdentityMatch2[EditSessionIdentityMatch2["Complete"] = 100] = "Complete";
  EditSessionIdentityMatch2[EditSessionIdentityMatch2["Partial"] = 50] = "Partial";
  EditSessionIdentityMatch2[EditSessionIdentityMatch2["None"] = 0] = "None";
})(EditSessionIdentityMatch || (EditSessionIdentityMatch = {}));

// out-build/vs/workbench/api/browser/mainThreadEditSessionIdentityParticipant.js
var ExtHostEditSessionIdentityCreateParticipant = class {
  constructor(extHostContext) {
    this.b = 1e4;
    this.a = extHostContext.getProxy($yT.ExtHostWorkspace);
  }
  async participate(workspaceFolder, token) {
    const p = new Promise((resolve, reject) => {
      setTimeout(() => reject(new Error(localize(2583, null))), this.b);
      this.a.$onWillCreateEditSessionIdentity(workspaceFolder.uri, token, this.b).then(resolve, reject);
    });
    return $Jh(p, token);
  }
};
var $JQb = class $JQb2 {
  constructor(extHostContext, instantiationService, b) {
    this.b = b;
    this.a = this.b.addEditSessionIdentityCreateParticipant(instantiationService.createInstance(ExtHostEditSessionIdentityCreateParticipant, extHostContext));
  }
  dispose() {
    this.a.dispose();
  }
};
$JQb = __decorate([
  $grb,
  __param(1, $Pk),
  __param(2, $2M)
], $JQb);

// out-build/vs/base/common/resourceTree.js
var Node4 = class {
  get childrenCount() {
    return this.a.size;
  }
  get children() {
    return this.a.values();
  }
  get name() {
    return $kc.basename(this.relativePath);
  }
  constructor(uri, relativePath, context, element = void 0, parent = void 0) {
    this.uri = uri;
    this.relativePath = relativePath;
    this.context = context;
    this.element = element;
    this.parent = parent;
    this.a = /* @__PURE__ */ new Map();
  }
  get(path) {
    return this.a.get(path);
  }
  set(path, child) {
    this.a.set(path, child);
  }
  delete(path) {
    this.a.delete(path);
  }
  clear() {
    this.a.clear();
  }
};
__decorate([
  $0t
], Node4.prototype, "name", null);
function collect(node, result) {
  if (typeof node.element !== "undefined") {
    result.push(node.element);
  }
  for (const child of node.children) {
    collect(child, result);
  }
  return result;
}
var $$R = class {
  static getRoot(node) {
    while (node.parent) {
      node = node.parent;
    }
    return node;
  }
  static collect(node) {
    return collect(node, []);
  }
  static isResourceNode(obj) {
    return obj instanceof Node4;
  }
  constructor(context, rootURI = URI.file("/"), a = $lh) {
    this.a = a;
    this.root = new Node4(rootURI, "", context);
  }
  add(uri, element) {
    const key2 = this.a.relativePath(this.root.uri, uri) || uri.path;
    const iterator = new $Uk(false).reset(key2);
    let node = this.root;
    let path = "";
    while (true) {
      const name = iterator.value();
      path = path + "/" + name;
      let child = node.get(name);
      if (!child) {
        child = new Node4(this.a.joinPath(this.root.uri, path), path, this.root.context, iterator.hasNext() ? void 0 : element, node);
        node.set(name, child);
      } else if (!iterator.hasNext()) {
        child.element = element;
      }
      node = child;
      if (!iterator.hasNext()) {
        return;
      }
      iterator.next();
    }
  }
  delete(uri) {
    const key2 = this.a.relativePath(this.root.uri, uri) || uri.path;
    const iterator = new $Uk(false).reset(key2);
    return this.b(this.root, iterator);
  }
  b(node, iterator) {
    const name = iterator.value();
    const child = node.get(name);
    if (!child) {
      return void 0;
    }
    if (iterator.hasNext()) {
      const result = this.b(child, iterator.next());
      if (typeof result !== "undefined" && child.childrenCount === 0) {
        node.delete(name);
      }
      return result;
    }
    node.delete(name);
    return child.element;
  }
  clear() {
    this.root.clear();
  }
  getNode(uri) {
    const key2 = this.a.relativePath(this.root.uri, uri) || uri.path;
    const iterator = new $Uk(false).reset(key2);
    let node = this.root;
    while (true) {
      const name = iterator.value();
      const child = node.get(name);
      if (!child || !iterator.hasNext()) {
        return child;
      }
      node = child;
      iterator.next();
    }
  }
};

// out-build/vs/workbench/contrib/scm/browser/util.js
function $KQb(element) {
  return Array.isArray(element.repositories) && Array.isArray(element.visibleRepositories);
}
function $LQb(element) {
  return !!element.provider && !!element.input;
}
function $MQb(element) {
  return !!element.validateInput && typeof element.value === "string";
}
function $NQb(element) {
  return element.type === "actionButton";
}
function $OQb(element) {
  return !!element.provider && !!element.resources;
}
function $PQb(element) {
  return !!element.sourceUri && $OQb(element.resourceGroup);
}
function $QQb(element) {
  return $$R.isResourceNode(element) && $OQb(element.context);
}
function $RQb(element) {
  return element.type === "historyItemViewModel";
}
function $SQb(element) {
  return element.type === "historyItemLoadMore";
}
var compareActions = (a, b) => {
  if (a instanceof $fJ && b instanceof $fJ) {
    return a.id === b.id && a.enabled === b.enabled && a.hideActions?.isHidden === b.hideActions?.isHidden;
  }
  return a.id === b.id && a.enabled === b.enabled;
};
function $TQb(menu, callback, primaryGroup) {
  let cachedPrimary = [];
  let cachedSecondary = [];
  const updateActions = () => {
    const { primary, secondary } = $Q$(menu.getActions({ shouldForwardArgs: true }), primaryGroup);
    if ($zb(cachedPrimary, primary, compareActions) && $zb(cachedSecondary, secondary, compareActions)) {
      return;
    }
    cachedPrimary = primary;
    cachedSecondary = secondary;
    callback(primary, secondary);
  };
  updateActions();
  return menu.onDidChange(updateActions);
}
function $UQb(menu) {
  return $O$(menu.getActions({ shouldForwardArgs: true }), "inline").secondary;
}
var $VQb = class extends $Um {
  constructor(c, f) {
    super(`statusbaraction{${c.id}}`, c.title, "", true);
    this.c = c;
    this.f = f;
    this.tooltip = c.tooltip || "";
  }
  run() {
    return this.f.executeCommand(this.c.id, ...this.c.arguments || []);
  }
};
var StatusBarActionViewItem = class extends $U1 {
  constructor(action, options3) {
    super(null, action, { ...options3, icon: false, label: true });
  }
  C() {
    if (this.u.label && this.L) {
      $dk(this.L, ...$B1(this.action.label));
    }
  }
};
function $WQb(instaService) {
  return (action, options3) => {
    if (action instanceof $VQb) {
      return new StatusBarActionViewItem(action, options3);
    }
    return $X$(instaService, action, options3);
  };
}
function $XQb(provider) {
  return `${provider.contextValue}:${provider.label}${provider.rootUri ? `:${provider.rootUri.toString()}` : ""}`;
}
function $YQb(provider) {
  return provider.groups.reduce((r2, g) => r2 + g.resources.length, 0);
}
function $ZQb(historyItem, maxLength = 20) {
  const title = historyItem.subject.length <= maxLength ? historyItem.subject : `${historyItem.subject.substring(0, maxLength)}\u2026`;
  return `${historyItem.displayId ?? historyItem.id} - ${title}`;
}
function $1Qb(ref1, ref2, currentHistoryItemRef, currentHistoryItemRemoteRef, currentHistoryItemBaseRef) {
  const getHistoryItemRefOrder = (ref) => {
    if (ref.id === currentHistoryItemRef?.id) {
      return 1;
    } else if (ref.id === currentHistoryItemRemoteRef?.id) {
      return 2;
    } else if (ref.id === currentHistoryItemBaseRef?.id) {
      return 3;
    } else if (ref.color !== void 0) {
      return 4;
    }
    return 99;
  };
  const ref1Order = getHistoryItemRefOrder(ref1);
  const ref2Order = getHistoryItemRefOrder(ref2);
  return ref1Order - ref2Order;
}

// out-build/vs/workbench/contrib/scm/browser/scmHistory.js
var $2Qb = 22;
var $3Qb = 11;
var SWIMLANE_CURVE_RADIUS = 5;
var CIRCLE_RADIUS = 4;
var CIRCLE_STROKE_WIDTH = 2;
var $4Qb = $5n("scmGraph.historyItemRefColor", $sq, localize(9472, null));
var $5Qb = $5n("scmGraph.historyItemRemoteRefColor", $wq, localize(9473, null));
var $6Qb = $5n("scmGraph.historyItemBaseRefColor", "#EA5C00", localize(9474, null));
var $7Qb = $5n("scmGraph.historyItemHoverDefaultLabelForeground", $eo, localize(9475, null));
var $8Qb = $5n("scmGraph.historyItemHoverDefaultLabelBackground", $wo, localize(9476, null));
var $9Qb = $5n("scmGraph.historyItemHoverLabelForeground", $Sq, localize(9477, null));
var $0Qb = $5n("scmGraph.historyItemHoverAdditionsForeground", { light: "#587C0C", dark: "#81B88B", hcDark: "#A1E3AD", hcLight: "#374E06" }, localize(9478, null));
var $$Qb = $5n("scmGraph.historyItemHoverDeletionsForeground", { light: "#AD0707", dark: "#C74E39", hcDark: "#C74E39", hcLight: "#AD0707" }, localize(9479, null));
var $_Qb = [
  $5n("scmGraph.foreground1", "#FFB000", localize(9480, null)),
  $5n("scmGraph.foreground2", "#DC267F", localize(9481, null)),
  $5n("scmGraph.foreground3", "#994F00", localize(9482, null)),
  $5n("scmGraph.foreground4", "#40B0A6", localize(9483, null)),
  $5n("scmGraph.foreground5", "#B66DFF", localize(9484, null))
];
function getLabelColorIdentifier(historyItem, colorMap) {
  for (const ref of historyItem.references ?? []) {
    const colorIdentifier = colorMap.get(ref.id);
    if (colorIdentifier !== void 0) {
      return colorIdentifier;
    }
  }
  return void 0;
}
function createPath(colorIdentifier) {
  const path = document.createElementNS("http://www.w3.org/2000/svg", "path");
  path.setAttribute("fill", "none");
  path.setAttribute("stroke-width", "1px");
  path.setAttribute("stroke-linecap", "round");
  path.style.stroke = $Zn(colorIdentifier);
  return path;
}
function drawCircle(index, radius, strokeWidth, colorIdentifier) {
  const circle = document.createElementNS("http://www.w3.org/2000/svg", "circle");
  circle.setAttribute("cx", `${$3Qb * (index + 1)}`);
  circle.setAttribute("cy", `${$3Qb}`);
  circle.setAttribute("r", `${radius}`);
  circle.style.strokeWidth = `${strokeWidth}px`;
  if (colorIdentifier) {
    circle.style.fill = $Zn(colorIdentifier);
  }
  return circle;
}
function drawVerticalLine(x1, y1, y2, color2) {
  const path = createPath(color2);
  path.setAttribute("d", `M ${x1} ${y1} V ${y2}`);
  return path;
}
function findLastIndex(nodes, id2) {
  for (let i2 = nodes.length - 1; i2 >= 0; i2--) {
    if (nodes[i2].id === id2) {
      return i2;
    }
  }
  return -1;
}
function $aRb(historyItemViewModel) {
  const svg2 = document.createElementNS("http://www.w3.org/2000/svg", "svg");
  svg2.classList.add("graph");
  const historyItem = historyItemViewModel.historyItem;
  const inputSwimlanes = historyItemViewModel.inputSwimlanes;
  const outputSwimlanes = historyItemViewModel.outputSwimlanes;
  const inputIndex = inputSwimlanes.findIndex((node) => node.id === historyItem.id);
  const circleIndex = inputIndex !== -1 ? inputIndex : inputSwimlanes.length;
  const circleColor = circleIndex < outputSwimlanes.length ? outputSwimlanes[circleIndex].color : circleIndex < inputSwimlanes.length ? inputSwimlanes[circleIndex].color : $4Qb;
  let outputSwimlaneIndex = 0;
  for (let index = 0; index < inputSwimlanes.length; index++) {
    const color2 = inputSwimlanes[index].color;
    if (inputSwimlanes[index].id === historyItem.id) {
      if (index !== circleIndex) {
        const d = [];
        const path = createPath(color2);
        d.push(`M ${$3Qb * (index + 1)} 0`);
        d.push(`A ${$3Qb} ${$3Qb} 0 0 1 ${$3Qb * index} ${$3Qb}`);
        d.push(`H ${$3Qb * (circleIndex + 1)}`);
        path.setAttribute("d", d.join(" "));
        svg2.append(path);
      } else {
        outputSwimlaneIndex++;
      }
    } else {
      if (outputSwimlaneIndex < outputSwimlanes.length && inputSwimlanes[index].id === outputSwimlanes[outputSwimlaneIndex].id) {
        if (index === outputSwimlaneIndex) {
          const path = drawVerticalLine($3Qb * (index + 1), 0, $2Qb, color2);
          svg2.append(path);
        } else {
          const d = [];
          const path = createPath(color2);
          d.push(`M ${$3Qb * (index + 1)} 0`);
          d.push(`V 6`);
          d.push(`A ${SWIMLANE_CURVE_RADIUS} ${SWIMLANE_CURVE_RADIUS} 0 0 1 ${$3Qb * (index + 1) - SWIMLANE_CURVE_RADIUS} ${$2Qb / 2}`);
          d.push(`H ${$3Qb * (outputSwimlaneIndex + 1) + SWIMLANE_CURVE_RADIUS}`);
          d.push(`A ${SWIMLANE_CURVE_RADIUS} ${SWIMLANE_CURVE_RADIUS} 0 0 0 ${$3Qb * (outputSwimlaneIndex + 1)} ${$2Qb / 2 + SWIMLANE_CURVE_RADIUS}`);
          d.push(`V ${$2Qb}`);
          path.setAttribute("d", d.join(" "));
          svg2.append(path);
        }
        outputSwimlaneIndex++;
      }
    }
  }
  for (let i2 = 1; i2 < historyItem.parentIds.length; i2++) {
    const parentOutputIndex = findLastIndex(outputSwimlanes, historyItem.parentIds[i2]);
    if (parentOutputIndex === -1) {
      continue;
    }
    const d = [];
    const path = createPath(outputSwimlanes[parentOutputIndex].color);
    d.push(`M ${$3Qb * parentOutputIndex} ${$2Qb / 2}`);
    d.push(`A ${$3Qb} ${$3Qb} 0 0 1 ${$3Qb * (parentOutputIndex + 1)} ${$2Qb}`);
    d.push(`M ${$3Qb * parentOutputIndex} ${$2Qb / 2}`);
    d.push(`H ${$3Qb * (circleIndex + 1)} `);
    path.setAttribute("d", d.join(" "));
    svg2.append(path);
  }
  if (inputIndex !== -1) {
    const path = drawVerticalLine($3Qb * (circleIndex + 1), 0, $2Qb / 2, inputSwimlanes[inputIndex].color);
    svg2.append(path);
  }
  if (historyItem.parentIds.length > 0) {
    const path = drawVerticalLine($3Qb * (circleIndex + 1), $2Qb / 2, $2Qb, circleColor);
    svg2.append(path);
  }
  if (historyItemViewModel.isCurrent) {
    const outerCircle = drawCircle(circleIndex, CIRCLE_RADIUS + 3, CIRCLE_STROKE_WIDTH, circleColor);
    svg2.append(outerCircle);
    const innerCircle = drawCircle(circleIndex, CIRCLE_STROKE_WIDTH, CIRCLE_RADIUS);
    svg2.append(innerCircle);
  } else {
    if (historyItem.parentIds.length > 1) {
      const circleOuter = drawCircle(circleIndex, CIRCLE_RADIUS + 2, CIRCLE_STROKE_WIDTH, circleColor);
      svg2.append(circleOuter);
      const circleInner = drawCircle(circleIndex, CIRCLE_RADIUS - 1, CIRCLE_STROKE_WIDTH, circleColor);
      svg2.append(circleInner);
    } else {
      const circle = drawCircle(circleIndex, CIRCLE_RADIUS + 1, CIRCLE_STROKE_WIDTH, circleColor);
      svg2.append(circle);
    }
  }
  svg2.style.height = `${$2Qb}px`;
  svg2.style.width = `${$3Qb * (Math.max(inputSwimlanes.length, outputSwimlanes.length, 1) + 1)}px`;
  return svg2;
}
function $bRb(columns) {
  const elements = $Ck("svg", {
    style: { height: `${$2Qb}px`, width: `${$3Qb * (columns.length + 1)}px` }
  });
  for (let index = 0; index < columns.length; index++) {
    const path = drawVerticalLine($3Qb * (index + 1), 0, $2Qb, columns[index].color);
    elements.root.append(path);
  }
  return elements.root;
}
function $cRb(historyItems, colorMap = /* @__PURE__ */ new Map(), currentHistoryItemRef, currentHistoryItemRemoteRef, currentHistoryItemBaseRef) {
  let colorIndex = -1;
  const viewModels = [];
  for (let index = 0; index < historyItems.length; index++) {
    const historyItem = historyItems[index];
    const isCurrent = historyItem.id === currentHistoryItemRef?.revision;
    const outputSwimlanesFromPreviousItem = viewModels.at(-1)?.outputSwimlanes ?? [];
    const inputSwimlanes = outputSwimlanesFromPreviousItem.map((i2) => $Lv(i2));
    const outputSwimlanes = [];
    let firstParentAdded = false;
    if (historyItem.parentIds.length > 0) {
      for (const node of inputSwimlanes) {
        if (node.id === historyItem.id) {
          if (!firstParentAdded) {
            outputSwimlanes.push({
              id: historyItem.parentIds[0],
              color: getLabelColorIdentifier(historyItem, colorMap) ?? node.color
            });
            firstParentAdded = true;
          }
          continue;
        }
        outputSwimlanes.push($Lv(node));
      }
    }
    for (let i2 = firstParentAdded ? 1 : 0; i2 < historyItem.parentIds.length; i2++) {
      let colorIdentifier;
      if (i2 === 0) {
        colorIdentifier = getLabelColorIdentifier(historyItem, colorMap);
      } else {
        const historyItemParent = historyItems.find((h3) => h3.id === historyItem.parentIds[i2]);
        colorIdentifier = historyItemParent ? getLabelColorIdentifier(historyItemParent, colorMap) : void 0;
      }
      if (!colorIdentifier) {
        colorIndex = rot(colorIndex + 1, $_Qb.length);
        colorIdentifier = $_Qb[colorIndex];
      }
      outputSwimlanes.push({
        id: historyItem.parentIds[i2],
        color: colorIdentifier
      });
    }
    const references = (historyItem.references ?? []).map((ref) => {
      let color2 = colorMap.get(ref.id);
      if (colorMap.has(ref.id) && color2 === void 0) {
        const inputIndex = inputSwimlanes.findIndex((node) => node.id === historyItem.id);
        const circleIndex = inputIndex !== -1 ? inputIndex : inputSwimlanes.length;
        color2 = circleIndex < outputSwimlanes.length ? outputSwimlanes[circleIndex].color : circleIndex < inputSwimlanes.length ? inputSwimlanes[circleIndex].color : $4Qb;
      }
      return { ...ref, color: color2 };
    });
    references.sort((ref1, ref2) => $1Qb(ref1, ref2, currentHistoryItemRef, currentHistoryItemRemoteRef, currentHistoryItemBaseRef));
    viewModels.push({
      historyItem: {
        ...historyItem,
        references
      },
      isCurrent,
      inputSwimlanes,
      outputSwimlanes
    });
  }
  return viewModels;
}

// out-build/vs/workbench/api/browser/mainThreadSCM.js
function getIconFromIconDto(iconDto) {
  if (iconDto === void 0) {
    return void 0;
  } else if (URI.isUri(iconDto)) {
    return URI.revive(iconDto);
  } else if (ThemeIcon.isThemeIcon(iconDto)) {
    return iconDto;
  } else {
    const icon2 = iconDto;
    return { light: URI.revive(icon2.light), dark: URI.revive(icon2.dark) };
  }
}
function toISCMHistoryItem(historyItemDto) {
  const references = historyItemDto.references?.map((r2) => ({
    ...r2,
    icon: getIconFromIconDto(r2.icon)
  }));
  const newLineIndex = historyItemDto.message.indexOf("\n");
  const subject = newLineIndex === -1 ? historyItemDto.message : `${historyItemDto.message.substring(0, newLineIndex)}\u2026`;
  return { ...historyItemDto, subject, references };
}
function toISCMHistoryItemRef(historyItemRefDto, color2) {
  return historyItemRefDto ? { ...historyItemRefDto, icon: getIconFromIconDto(historyItemRefDto.icon), color: color2 } : void 0;
}
var SCMInputBoxContentProvider = class extends $3c {
  constructor(textModelService, a, b) {
    super();
    this.a = a;
    this.b = b;
    this.B(textModelService.registerTextModelContentProvider(Schemas.vscodeSourceControl, this));
  }
  async provideTextContent(resource) {
    const existing = this.a.getModel(resource);
    if (existing) {
      return existing;
    }
    return this.a.createModel("", this.b.createById("scminput"), resource);
  }
};
var MainThreadSCMResourceGroup = class {
  get resourceTree() {
    if (!this.a) {
      const rootUri = this.provider.rootUri ?? URI.file("/");
      this.a = new $$R(this, rootUri, this.f.extUri);
      for (const resource of this.resources) {
        this.a.add(resource.sourceUri, resource);
      }
    }
    return this.a;
  }
  get hideWhenEmpty() {
    return !!this.features.hideWhenEmpty;
  }
  constructor(d, e, provider, features, label3, id2, multiDiffEditorEnableViewChanges, f) {
    this.d = d;
    this.e = e;
    this.provider = provider;
    this.features = features;
    this.label = label3;
    this.id = id2;
    this.multiDiffEditorEnableViewChanges = multiDiffEditorEnableViewChanges;
    this.f = f;
    this.resources = [];
    this.b = new $ze();
    this.onDidChange = this.b.event;
    this.c = new $ze();
    this.onDidChangeResources = this.c.event;
  }
  toJSON() {
    return {
      $mid: 4,
      sourceControlHandle: this.d,
      groupHandle: this.e
    };
  }
  splice(start, deleteCount, toInsert) {
    this.resources.splice(start, deleteCount, ...toInsert);
    this.a = void 0;
    this.c.fire();
  }
  $updateGroup(features) {
    this.features = { ...this.features, ...features };
    this.b.fire();
  }
  $updateGroupLabel(label3) {
    this.label = label3;
    this.b.fire();
  }
};
var MainThreadSCMResource = class {
  constructor(a, b, c, d, sourceUri, resourceGroup, decorations, contextValue, command4, multiDiffEditorOriginalUri, multiDiffEditorModifiedUri) {
    this.a = a;
    this.b = b;
    this.c = c;
    this.d = d;
    this.sourceUri = sourceUri;
    this.resourceGroup = resourceGroup;
    this.decorations = decorations;
    this.contextValue = contextValue;
    this.command = command4;
    this.multiDiffEditorOriginalUri = multiDiffEditorOriginalUri;
    this.multiDiffEditorModifiedUri = multiDiffEditorModifiedUri;
  }
  open(preserveFocus) {
    return this.a.$executeResourceCommand(this.b, this.c, this.d, preserveFocus);
  }
  toJSON() {
    return {
      $mid: 3,
      sourceControlHandle: this.b,
      groupHandle: this.c,
      handle: this.d
    };
  }
};
var MainThreadSCMHistoryProvider = class {
  get historyItemRef() {
    return this.a;
  }
  get historyItemRemoteRef() {
    return this.b;
  }
  get historyItemBaseRef() {
    return this.c;
  }
  get historyItemRefChanges() {
    return this.d;
  }
  constructor(e, f) {
    this.e = e;
    this.f = f;
    this.a = $me({
      owner: this,
      equalsFn: $rd
    }, void 0);
    this.b = $me({
      owner: this,
      equalsFn: $rd
    }, void 0);
    this.c = $me({
      owner: this,
      equalsFn: $rd
    }, void 0);
    this.d = $he(this, { added: [], modified: [], removed: [], silent: false });
  }
  async resolveHistoryItemRefsCommonAncestor(historyItemRefs) {
    return this.e.$resolveHistoryItemRefsCommonAncestor(this.f, historyItemRefs, CancellationToken.None);
  }
  async provideHistoryItemRefs(historyItemsRefs) {
    const historyItemRefs = await this.e.$provideHistoryItemRefs(this.f, historyItemsRefs, CancellationToken.None);
    return historyItemRefs?.map((ref) => ({ ...ref, icon: getIconFromIconDto(ref.icon) }));
  }
  async provideHistoryItems(options3) {
    const historyItems = await this.e.$provideHistoryItems(this.f, options3, CancellationToken.None);
    return historyItems?.map((historyItem) => toISCMHistoryItem(historyItem));
  }
  async provideHistoryItemChanges(historyItemId, historyItemParentId) {
    const changes = await this.e.$provideHistoryItemChanges(this.f, historyItemId, historyItemParentId, CancellationToken.None);
    return changes?.map((change) => ({
      uri: URI.revive(change.uri),
      originalUri: change.originalUri && URI.revive(change.originalUri),
      modifiedUri: change.modifiedUri && URI.revive(change.modifiedUri),
      renameUri: change.renameUri && URI.revive(change.renameUri)
    }));
  }
  $onDidChangeCurrentHistoryItemRefs(historyItemRef, historyItemRemoteRef, historyItemBaseRef) {
    $ce((tx) => {
      this.a.set(toISCMHistoryItemRef(historyItemRef, $4Qb), tx);
      this.b.set(toISCMHistoryItemRef(historyItemRemoteRef, $5Qb), tx);
      this.c.set(toISCMHistoryItemRef(historyItemBaseRef, $6Qb), tx);
    });
  }
  $onDidChangeHistoryItemRefs(historyItemRefs) {
    const added = historyItemRefs.added.map((ref) => toISCMHistoryItemRef(ref));
    const modified = historyItemRefs.modified.map((ref) => toISCMHistoryItemRef(ref));
    const removed = historyItemRefs.removed.map((ref) => toISCMHistoryItemRef(ref));
    this.d.set({ added, modified, removed, silent: historyItemRefs.silent }, void 0);
  }
};
var MainThreadSCMProvider = class _MainThreadSCMProvider {
  static {
    this.a = 0;
  }
  get id() {
    return this.b;
  }
  get handle() {
    return this.o;
  }
  get label() {
    return this.q;
  }
  get rootUri() {
    return this.s;
  }
  get inputBoxTextModel() {
    return this.t;
  }
  get contextValue() {
    return this.p;
  }
  get acceptInputCommand() {
    return this.f.acceptInputCommand;
  }
  get count() {
    return this.g;
  }
  get statusBarCommands() {
    return this.h;
  }
  get name() {
    return this.i ?? this.q;
  }
  get commitTemplate() {
    return this.j;
  }
  get actionButton() {
    return this.k;
  }
  get historyProvider() {
    return this.m;
  }
  constructor(n, o, p, q, s, t, u, v, w) {
    this.n = n;
    this.o = o;
    this.p = p;
    this.q = q;
    this.s = s;
    this.t = t;
    this.u = u;
    this.v = v;
    this.w = w;
    this.b = `scm${_MainThreadSCMProvider.a++}`;
    this.groups = [];
    this.c = new $ze();
    this.onDidChangeResourceGroups = this.c.event;
    this.d = new $ze();
    this.onDidChangeResources = this.d.event;
    this.e = /* @__PURE__ */ Object.create(null);
    this.f = {};
    this.g = $he(this, void 0);
    this.h = $he(this, void 0);
    this.j = $he(this, "");
    this.k = $he(this, void 0);
    this.isSCM = true;
    this.visible = true;
    this.m = $he(this, void 0);
    if (s) {
      const folder = this.w.getWorkspaceFolder(s);
      if (folder?.uri.toString() === s.toString()) {
        this.i = folder.name;
      } else if (s.path !== "/") {
        this.i = $sh(s);
      }
    }
  }
  $updateSourceControl(features) {
    this.f = { ...this.f, ...features };
    if (typeof features.commitTemplate !== "undefined") {
      this.j.set(features.commitTemplate, void 0);
    }
    if (typeof features.actionButton !== "undefined") {
      this.k.set(features.actionButton ?? void 0, void 0);
    }
    if (typeof features.count !== "undefined") {
      this.g.set(features.count, void 0);
    }
    if (typeof features.statusBarCommands !== "undefined") {
      this.h.set(features.statusBarCommands, void 0);
    }
    if (features.hasQuickDiffProvider && !this.l) {
      this.l = this.u.addQuickDiffProvider({
        label: features.quickDiffLabel ?? this.label,
        rootUri: this.rootUri,
        isSCM: this.isSCM,
        visible: this.visible,
        getOriginalResource: (uri) => this.getOriginalResource(uri)
      });
    } else if (features.hasQuickDiffProvider === false && this.l) {
      this.l.dispose();
      this.l = void 0;
    }
    if (features.hasHistoryProvider && !this.historyProvider.get()) {
      const historyProvider = new MainThreadSCMHistoryProvider(this.n, this.handle);
      this.m.set(historyProvider, void 0);
    } else if (features.hasHistoryProvider === false && this.historyProvider.get()) {
      this.m.set(void 0, void 0);
    }
  }
  $registerGroups(_groups) {
    const groups = _groups.map(([handle2, id2, label3, features, multiDiffEditorEnableViewChanges]) => {
      const group2 = new MainThreadSCMResourceGroup(this.handle, handle2, this, features, label3, id2, multiDiffEditorEnableViewChanges, this.v);
      this.e[handle2] = group2;
      return group2;
    });
    this.groups.splice(this.groups.length, 0, ...groups);
    this.c.fire();
  }
  $updateGroup(handle2, features) {
    const group2 = this.e[handle2];
    if (!group2) {
      return;
    }
    group2.$updateGroup(features);
  }
  $updateGroupLabel(handle2, label3) {
    const group2 = this.e[handle2];
    if (!group2) {
      return;
    }
    group2.$updateGroupLabel(label3);
  }
  $spliceGroupResourceStates(splices) {
    for (const [groupHandle, groupSlices] of splices) {
      const group2 = this.e[groupHandle];
      if (!group2) {
        console.warn(`SCM group ${groupHandle} not found in provider ${this.label}`);
        continue;
      }
      groupSlices.reverse();
      for (const [start, deleteCount, rawResources] of groupSlices) {
        const resources = rawResources.map((rawResource) => {
          const [handle2, sourceUri, icons2, tooltip, strikeThrough, faded, contextValue, command4, multiDiffEditorOriginalUri, multiDiffEditorModifiedUri] = rawResource;
          const [light, dark] = icons2;
          const icon2 = ThemeIcon.isThemeIcon(light) ? light : URI.revive(light);
          const iconDark = (ThemeIcon.isThemeIcon(dark) ? dark : URI.revive(dark)) || icon2;
          const decorations = {
            icon: icon2,
            iconDark,
            tooltip,
            strikeThrough,
            faded
          };
          return new MainThreadSCMResource(this.n, this.handle, groupHandle, handle2, URI.revive(sourceUri), group2, decorations, contextValue || void 0, command4, URI.revive(multiDiffEditorOriginalUri), URI.revive(multiDiffEditorModifiedUri));
        });
        group2.splice(start, deleteCount, resources);
      }
    }
    this.d.fire();
  }
  $unregisterGroup(handle2) {
    const group2 = this.e[handle2];
    if (!group2) {
      return;
    }
    delete this.e[handle2];
    this.groups.splice(this.groups.indexOf(group2), 1);
    this.c.fire();
  }
  async getOriginalResource(uri) {
    if (!this.f.hasQuickDiffProvider) {
      return null;
    }
    const result = await this.n.$provideOriginalResource(this.handle, uri, CancellationToken.None);
    return result && URI.revive(result);
  }
  $onDidChangeHistoryProviderCurrentHistoryItemRefs(historyItemRef, historyItemRemoteRef, historyItemBaseRef) {
    if (!this.historyProvider.get()) {
      return;
    }
    this.m.get()?.$onDidChangeCurrentHistoryItemRefs(historyItemRef, historyItemRemoteRef, historyItemBaseRef);
  }
  $onDidChangeHistoryProviderHistoryItemRefs(historyItemRefs) {
    if (!this.historyProvider.get()) {
      return;
    }
    this.m.get()?.$onDidChangeHistoryItemRefs(historyItemRefs);
  }
  toJSON() {
    return {
      $mid: 5,
      handle: this.handle
    };
  }
  dispose() {
    this.l?.dispose();
  }
};
var $dRb = class $dRb2 {
  constructor(extHostContext, f, g, h3, i2, j, k, l, m) {
    this.f = f;
    this.g = g;
    this.h = h3;
    this.i = i2;
    this.j = j;
    this.k = k;
    this.l = l;
    this.m = m;
    this.b = /* @__PURE__ */ new Map();
    this.c = /* @__PURE__ */ new Map();
    this.d = /* @__PURE__ */ new Map();
    this.e = new $2c();
    this.a = extHostContext.getProxy($yT.ExtHostSCM);
    this.e.add(new SCMInputBoxContentProvider(this.j, this.i, this.h));
  }
  dispose() {
    $Xc(this.b.values());
    this.b.clear();
    $Xc(this.d.values());
    this.d.clear();
    this.e.dispose();
  }
  async $registerSourceControl(handle2, id2, label3, rootUri, inputBoxDocumentUri) {
    this.c.set(handle2, new $Uh());
    const inputBoxTextModelRef = await this.j.createModelReference(URI.revive(inputBoxDocumentUri));
    const provider = new MainThreadSCMProvider(this.a, handle2, id2, label3, rootUri ? URI.revive(rootUri) : void 0, inputBoxTextModelRef.object.textEditorModel, this.k, this.l, this.m);
    const repository = this.f.registerSCMProvider(provider);
    this.b.set(handle2, repository);
    const disposable = $Zc(inputBoxTextModelRef, Event2.filter(this.g.onDidFocusRepository, (r2) => r2 === repository)((_) => this.a.$setSelectedSourceControl(handle2)), repository.input.onDidChange(({ value }) => this.a.$onInputBoxValueChange(handle2, value)));
    this.d.set(handle2, disposable);
    if (this.g.focusedRepository === repository) {
      setTimeout(() => this.a.$setSelectedSourceControl(handle2), 0);
    }
    if (repository.input.value) {
      setTimeout(() => this.a.$onInputBoxValueChange(handle2, repository.input.value), 0);
    }
    this.c.get(handle2)?.open();
  }
  async $updateSourceControl(handle2, features) {
    await this.c.get(handle2)?.wait();
    const repository = this.b.get(handle2);
    if (!repository) {
      return;
    }
    const provider = repository.provider;
    provider.$updateSourceControl(features);
  }
  async $unregisterSourceControl(handle2) {
    await this.c.get(handle2)?.wait();
    const repository = this.b.get(handle2);
    if (!repository) {
      return;
    }
    this.d.get(handle2).dispose();
    this.d.delete(handle2);
    repository.dispose();
    this.b.delete(handle2);
  }
  async $registerGroups(sourceControlHandle, groups, splices) {
    await this.c.get(sourceControlHandle)?.wait();
    const repository = this.b.get(sourceControlHandle);
    if (!repository) {
      return;
    }
    const provider = repository.provider;
    provider.$registerGroups(groups);
    provider.$spliceGroupResourceStates(splices);
  }
  async $updateGroup(sourceControlHandle, groupHandle, features) {
    await this.c.get(sourceControlHandle)?.wait();
    const repository = this.b.get(sourceControlHandle);
    if (!repository) {
      return;
    }
    const provider = repository.provider;
    provider.$updateGroup(groupHandle, features);
  }
  async $updateGroupLabel(sourceControlHandle, groupHandle, label3) {
    await this.c.get(sourceControlHandle)?.wait();
    const repository = this.b.get(sourceControlHandle);
    if (!repository) {
      return;
    }
    const provider = repository.provider;
    provider.$updateGroupLabel(groupHandle, label3);
  }
  async $spliceResourceStates(sourceControlHandle, splices) {
    await this.c.get(sourceControlHandle)?.wait();
    const repository = this.b.get(sourceControlHandle);
    if (!repository) {
      return;
    }
    const provider = repository.provider;
    provider.$spliceGroupResourceStates(splices);
  }
  async $unregisterGroup(sourceControlHandle, handle2) {
    await this.c.get(sourceControlHandle)?.wait();
    const repository = this.b.get(sourceControlHandle);
    if (!repository) {
      return;
    }
    const provider = repository.provider;
    provider.$unregisterGroup(handle2);
  }
  async $setInputBoxValue(sourceControlHandle, value) {
    await this.c.get(sourceControlHandle)?.wait();
    const repository = this.b.get(sourceControlHandle);
    if (!repository) {
      return;
    }
    repository.input.setValue(value, false);
  }
  async $setInputBoxPlaceholder(sourceControlHandle, placeholder) {
    await this.c.get(sourceControlHandle)?.wait();
    const repository = this.b.get(sourceControlHandle);
    if (!repository) {
      return;
    }
    repository.input.placeholder = placeholder;
  }
  async $setInputBoxEnablement(sourceControlHandle, enabled) {
    await this.c.get(sourceControlHandle)?.wait();
    const repository = this.b.get(sourceControlHandle);
    if (!repository) {
      return;
    }
    repository.input.enabled = enabled;
  }
  async $setInputBoxVisibility(sourceControlHandle, visible) {
    await this.c.get(sourceControlHandle)?.wait();
    const repository = this.b.get(sourceControlHandle);
    if (!repository) {
      return;
    }
    repository.input.visible = visible;
  }
  async $showValidationMessage(sourceControlHandle, message, type) {
    await this.c.get(sourceControlHandle)?.wait();
    const repository = this.b.get(sourceControlHandle);
    if (!repository) {
      return;
    }
    repository.input.showValidationMessage(message, type);
  }
  async $setValidationProviderIsEnabled(sourceControlHandle, enabled) {
    await this.c.get(sourceControlHandle)?.wait();
    const repository = this.b.get(sourceControlHandle);
    if (!repository) {
      return;
    }
    if (enabled) {
      repository.input.validateInput = async (value, pos) => {
        const result = await this.a.$validateInput(sourceControlHandle, value, pos);
        return result && { message: result[0], type: result[1] };
      };
    } else {
      repository.input.validateInput = async () => void 0;
    }
  }
  async $onDidChangeHistoryProviderCurrentHistoryItemRefs(sourceControlHandle, historyItemRef, historyItemRemoteRef, historyItemBaseRef) {
    await this.c.get(sourceControlHandle)?.wait();
    const repository = this.b.get(sourceControlHandle);
    if (!repository) {
      return;
    }
    const provider = repository.provider;
    provider.$onDidChangeHistoryProviderCurrentHistoryItemRefs(historyItemRef, historyItemRemoteRef, historyItemBaseRef);
  }
  async $onDidChangeHistoryProviderHistoryItemRefs(sourceControlHandle, historyItemRefs) {
    await this.c.get(sourceControlHandle)?.wait();
    const repository = this.b.get(sourceControlHandle);
    if (!repository) {
      return;
    }
    const provider = repository.provider;
    provider.$onDidChangeHistoryProviderHistoryItemRefs(historyItemRefs);
  }
};
$dRb = __decorate([
  $frb($xT.MainThreadSCM),
  __param(1, $dS),
  __param(2, $eS),
  __param(3, $1E),
  __param(4, $sG),
  __param(5, $oG),
  __param(6, $AEb),
  __param(7, $vl),
  __param(8, $Zk)
], $dRb);

// out-build/vs/workbench/contrib/search/common/constants.js
var SearchCommandIds;
(function(SearchCommandIds2) {
  SearchCommandIds2["FindInFilesActionId"] = "workbench.action.findInFiles";
  SearchCommandIds2["FocusActiveEditorCommandId"] = "search.action.focusActiveEditor";
  SearchCommandIds2["FocusSearchFromResults"] = "search.action.focusSearchFromResults";
  SearchCommandIds2["OpenMatch"] = "search.action.openResult";
  SearchCommandIds2["OpenMatchToSide"] = "search.action.openResultToSide";
  SearchCommandIds2["RemoveActionId"] = "search.action.remove";
  SearchCommandIds2["CopyPathCommandId"] = "search.action.copyPath";
  SearchCommandIds2["CopyMatchCommandId"] = "search.action.copyMatch";
  SearchCommandIds2["CopyAllCommandId"] = "search.action.copyAll";
  SearchCommandIds2["OpenInEditorCommandId"] = "search.action.openInEditor";
  SearchCommandIds2["ClearSearchHistoryCommandId"] = "search.action.clearHistory";
  SearchCommandIds2["FocusSearchListCommandID"] = "search.action.focusSearchList";
  SearchCommandIds2["ReplaceActionId"] = "search.action.replace";
  SearchCommandIds2["ReplaceAllInFileActionId"] = "search.action.replaceAllInFile";
  SearchCommandIds2["ReplaceAllInFolderActionId"] = "search.action.replaceAllInFolder";
  SearchCommandIds2["CloseReplaceWidgetActionId"] = "closeReplaceInFilesWidget";
  SearchCommandIds2["ToggleCaseSensitiveCommandId"] = "toggleSearchCaseSensitive";
  SearchCommandIds2["ToggleWholeWordCommandId"] = "toggleSearchWholeWord";
  SearchCommandIds2["ToggleRegexCommandId"] = "toggleSearchRegex";
  SearchCommandIds2["TogglePreserveCaseId"] = "toggleSearchPreserveCase";
  SearchCommandIds2["AddCursorsAtSearchResults"] = "addCursorsAtSearchResults";
  SearchCommandIds2["RevealInSideBarForSearchResults"] = "search.action.revealInSideBar";
  SearchCommandIds2["ReplaceInFilesActionId"] = "workbench.action.replaceInFiles";
  SearchCommandIds2["ShowAllSymbolsActionId"] = "workbench.action.showAllSymbols";
  SearchCommandIds2["QuickTextSearchActionId"] = "workbench.action.quickTextSearch";
  SearchCommandIds2["CancelSearchActionId"] = "search.action.cancel";
  SearchCommandIds2["RefreshSearchResultsActionId"] = "search.action.refreshSearchResults";
  SearchCommandIds2["FocusNextSearchResultActionId"] = "search.action.focusNextSearchResult";
  SearchCommandIds2["FocusPreviousSearchResultActionId"] = "search.action.focusPreviousSearchResult";
  SearchCommandIds2["ToggleSearchOnTypeActionId"] = "workbench.action.toggleSearchOnType";
  SearchCommandIds2["CollapseSearchResultsActionId"] = "search.action.collapseSearchResults";
  SearchCommandIds2["ExpandSearchResultsActionId"] = "search.action.expandSearchResults";
  SearchCommandIds2["ExpandRecursivelyCommandId"] = "search.action.expandRecursively";
  SearchCommandIds2["ClearSearchResultsActionId"] = "search.action.clearSearchResults";
  SearchCommandIds2["ViewAsTreeActionId"] = "search.action.viewAsTree";
  SearchCommandIds2["ViewAsListActionId"] = "search.action.viewAsList";
  SearchCommandIds2["ShowAIResultsActionId"] = "search.action.showAIResults";
  SearchCommandIds2["HideAIResultsActionId"] = "search.action.hideAIResults";
  SearchCommandIds2["ToggleQueryDetailsActionId"] = "workbench.action.search.toggleQueryDetails";
  SearchCommandIds2["ExcludeFolderFromSearchId"] = "search.action.excludeFromSearch";
  SearchCommandIds2["FocusNextInputActionId"] = "search.focus.nextInputBox";
  SearchCommandIds2["FocusPreviousInputActionId"] = "search.focus.previousInputBox";
  SearchCommandIds2["RestrictSearchToFolderId"] = "search.action.restrictSearchToFolder";
  SearchCommandIds2["FindInFolderId"] = "filesExplorer.findInFolder";
  SearchCommandIds2["FindInWorkspaceId"] = "filesExplorer.findInWorkspace";
})(SearchCommandIds || (SearchCommandIds = {}));
var $eRb = {
  SearchViewVisibleKey: new $nn("searchViewletVisible", true),
  SearchViewFocusedKey: new $nn("searchViewletFocus", false),
  SearchResultListFocusedKey: new $nn("searchResultListFocused", true),
  InputBoxFocusedKey: new $nn("inputBoxFocus", false),
  SearchInputBoxFocusedKey: new $nn("searchInputBoxFocus", false),
  ReplaceInputBoxFocusedKey: new $nn("replaceInputBoxFocus", false),
  PatternIncludesFocusedKey: new $nn("patternIncludesInputBoxFocus", false),
  PatternExcludesFocusedKey: new $nn("patternExcludesInputBoxFocus", false),
  ReplaceActiveKey: new $nn("replaceActive", false),
  HasSearchResults: new $nn("hasSearchResult", false),
  FirstMatchFocusKey: new $nn("firstMatchFocus", false),
  FileMatchOrMatchFocusKey: new $nn("fileMatchOrMatchFocus", false),
  // This is actually, Match or File or Folder
  FileMatchOrFolderMatchFocusKey: new $nn("fileMatchOrFolderMatchFocus", false),
  FileMatchOrFolderMatchWithResourceFocusKey: new $nn("fileMatchOrFolderMatchWithResourceFocus", false),
  // Excludes "Other files"
  FileFocusKey: new $nn("fileMatchFocus", false),
  FolderFocusKey: new $nn("folderMatchFocus", false),
  ResourceFolderFocusKey: new $nn("folderMatchWithResourceFocus", false),
  IsEditableItemKey: new $nn("isEditableItem", true),
  MatchFocusKey: new $nn("matchFocus", false),
  ViewHasSearchPatternKey: new $nn("viewHasSearchPattern", false),
  ViewHasReplacePatternKey: new $nn("viewHasReplacePattern", false),
  ViewHasFilePatternKey: new $nn("viewHasFilePattern", false),
  ViewHasSomeCollapsibleKey: new $nn("viewHasSomeCollapsibleResult", false),
  InTreeViewKey: new $nn("inTreeView", false),
  hasAIResultProvider: new $nn("hasAIResultProviderKey", false)
};

// out-build/vs/workbench/api/browser/mainThreadSearch.js
var $fRb = class $fRb2 {
  constructor(extHostContext, c, d, _configurationService, e) {
    this.c = c;
    this.d = d;
    this.e = e;
    this.b = /* @__PURE__ */ new Map();
    this.a = extHostContext.getProxy($yT.ExtHostSearch);
    this.a.$enableExtensionHostSearch();
  }
  dispose() {
    this.b.forEach((value) => value.dispose());
    this.b.clear();
  }
  $registerTextSearchProvider(handle2, scheme) {
    this.b.set(handle2, new RemoteSearchProvider(this.c, 1, scheme, handle2, this.a));
  }
  $registerAITextSearchProvider(handle2, scheme) {
    $eRb.hasAIResultProvider.bindTo(this.e).set(true);
    this.b.set(handle2, new RemoteSearchProvider(this.c, 2, scheme, handle2, this.a));
  }
  $registerFileSearchProvider(handle2, scheme) {
    this.b.set(handle2, new RemoteSearchProvider(this.c, 0, scheme, handle2, this.a));
  }
  $unregisterProvider(handle2) {
    $Xc(this.b.get(handle2));
    this.b.delete(handle2);
  }
  $handleFileMatch(handle2, session, data) {
    const provider = this.b.get(handle2);
    if (!provider) {
      throw new Error("Got result for unknown provider");
    }
    provider.handleFindMatch(session, data);
  }
  $handleTextMatch(handle2, session, data) {
    const provider = this.b.get(handle2);
    if (!provider) {
      throw new Error("Got result for unknown provider");
    }
    provider.handleFindMatch(session, data);
  }
  $handleTelemetry(eventName, data) {
    this.d.publicLog(eventName, data);
  }
};
$fRb = __decorate([
  $frb($xT.MainThreadSearch),
  __param(1, $TN),
  __param(2, $zv),
  __param(3, $kl),
  __param(4, $on)
], $fRb);
var SearchOperation = class _SearchOperation {
  static {
    this.a = 0;
  }
  constructor(progress, id2 = ++_SearchOperation.a, matches = /* @__PURE__ */ new Map()) {
    this.progress = progress;
    this.id = id2;
    this.matches = matches;
  }
  addMatch(match) {
    const existingMatch = this.matches.get(match.resource.toString());
    if (existingMatch) {
      if (existingMatch.results && match.results) {
        existingMatch.results.push(...match.results);
      }
    } else {
      this.matches.set(match.resource.toString(), match);
    }
    this.progress?.(match);
  }
};
var RemoteSearchProvider = class {
  constructor(searchService, type, d, e, f) {
    this.d = d;
    this.e = e;
    this.f = f;
    this.a = new $2c();
    this.b = /* @__PURE__ */ new Map();
    this.a.add(searchService.registerSearchResultProvider(this.d, type, this));
  }
  async getAIName() {
    if (this.c === void 0) {
      this.c = await this.f.$getAIName(this.e);
    }
    return this.c;
  }
  dispose() {
    this.a.dispose();
  }
  fileSearch(query, token = CancellationToken.None) {
    return this.doSearch(query, void 0, token);
  }
  textSearch(query, onProgress, token = CancellationToken.None) {
    return this.doSearch(query, onProgress, token);
  }
  doSearch(query, onProgress, token = CancellationToken.None) {
    if (!query.folderQueries.length) {
      throw new Error("Empty folderQueries");
    }
    const search2 = new SearchOperation(onProgress);
    this.b.set(search2.id, search2);
    const searchP = this.g(query, search2.id, token);
    return Promise.resolve(searchP).then((result) => {
      this.b.delete(search2.id);
      return { results: Array.from(search2.matches.values()), stats: result.stats, limitHit: result.limitHit, messages: result.messages };
    }, (err) => {
      this.b.delete(search2.id);
      return Promise.reject(err);
    });
  }
  clearCache(cacheKey) {
    return Promise.resolve(this.f.$clearCache(cacheKey));
  }
  handleFindMatch(session, dataOrUri) {
    const searchOp = this.b.get(session);
    if (!searchOp) {
      return;
    }
    dataOrUri.forEach((result) => {
      if (result.results) {
        searchOp.addMatch($cu(result));
      } else {
        searchOp.addMatch({
          resource: URI.revive(result)
        });
      }
    });
  }
  g(query, session, token) {
    switch (query.type) {
      case 1:
        return this.f.$provideFileSearchResults(this.e, session, query, token);
      case 2:
        return this.f.$provideTextSearchResults(this.e, session, query, token);
      default:
        return this.f.$provideAITextSearchResults(this.e, session, query, token);
    }
  }
};

// out-build/vs/workbench/api/browser/mainThreadStatusBar.js
var $gRb = class $gRb2 {
  constructor(extHostContext, b) {
    this.b = b;
    this.a = new $2c();
    const proxy = extHostContext.getProxy($yT.ExtHostStatusBar);
    const entries2 = [];
    for (const [entryId, item] of b.getEntries()) {
      entries2.push(asDto(entryId, item));
    }
    proxy.$acceptStaticEntries(entries2);
    this.a.add(b.onDidChange((e) => {
      if (e.added) {
        proxy.$acceptStaticEntries([asDto(e.added[0], e.added[1])]);
      }
    }));
    function asDto(entryId, item) {
      return {
        entryId,
        name: item.entry.name,
        text: item.entry.text,
        tooltip: item.entry.tooltip,
        command: typeof item.entry.command === "string" ? item.entry.command : typeof item.entry.command === "object" ? item.entry.command.id : void 0,
        priority: item.priority,
        alignLeft: item.alignment === 0,
        accessibilityInformation: item.entry.ariaLabel ? { label: item.entry.ariaLabel, role: item.entry.role } : void 0
      };
    }
  }
  dispose() {
    this.a.dispose();
  }
  $setEntry(entryId, id2, extensionId, name, text2, tooltip, command4, color2, backgroundColor, alignLeft, priority, accessibilityInformation) {
    const kind = this.b.setOrUpdateEntry(entryId, id2, extensionId, name, text2, tooltip, command4, color2, backgroundColor, alignLeft, priority, accessibilityInformation);
    if (kind === 0) {
      this.a.add($1c(() => this.b.unsetEntry(entryId)));
    }
  }
  $disposeEntry(entryId) {
    this.b.unsetEntry(entryId);
  }
};
$gRb = __decorate([
  $frb($xT.MainThreadStatusBar),
  __param(1, $drb)
], $gRb);

// out-build/vs/platform/extensionManagement/common/extensionStorage.js
var $BM_1;
var $AM = $Qk("IExtensionStorageService");
var EXTENSION_KEYS_ID_VERSION_REGEX = /^extensionKeys\/([^.]+\..+)@(\d+\.\d+\.\d+(-.*)?)$/;
var $BM = class $BM2 extends $3c {
  static {
    $BM_1 = this;
  }
  static {
    this.a = 512 * 1024;
  }
  static b(extension) {
    return `extensionKeys/${$HA(extension.id)}@${extension.version}`;
  }
  static c(key2) {
    const matches = EXTENSION_KEYS_ID_VERSION_REGEX.exec(key2);
    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 $BM_1.f(storageService)) {
      const extensionVersion = extensions.find((e) => $DA(e.identifier, { id: id2 }))?.manifest.version;
      for (const version2 of versions) {
        if (extensionVersion !== version2) {
          extensionVersionsToRemove.push($BM_1.b({ id: id2, version: version2 }));
        }
      }
    }
    for (const key2 of extensionVersionsToRemove) {
      storageService.remove(
        key2,
        0
        /* StorageScope.PROFILE */
      );
    }
  }
  static f(storageService) {
    const extensionsWithKeysForSync = /* @__PURE__ */ new Map();
    const keys = storageService.keys(
      0,
      1
      /* StorageTarget.MACHINE */
    );
    for (const key2 of keys) {
      const extensionIdWithVersion = $BM_1.c(key2);
      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 $ze());
    this.onDidChangeExtensionStorageToSync = this.g.event;
    this.h = $BM_1.f(j);
    this.B(this.j.onDidChangeValue(0, void 0, this.q)((e) => this.r(e)));
  }
  r(e) {
    if (this.h.has(e.key.toLowerCase())) {
      this.g.fire();
      return;
    }
    const extensionIdWithVersion = $BM_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 ($zg(extension)) {
      return extension;
    }
    const publisher = extension.manifest ? extension.manifest.publisher : extension.publisher;
    const name = extension.manifest ? extension.manifest.name : extension.name;
    return $GA(publisher, name);
  }
  getExtensionState(extension, global) {
    const extensionId = this.s(extension);
    const jsonValue = this.getExtensionStateRaw(extension, global);
    if (jsonValue) {
      try {
        return JSON.parse(jsonValue);
      } catch (error) {
        this.n.error(`[mainThreadStorage] unexpected error parsing storage contents (extensionId: ${extensionId}, global: ${global}): ${error}`);
      }
    }
    return void 0;
  }
  getExtensionStateRaw(extension, global) {
    const extensionId = this.s(extension);
    const rawState = this.j.get(
      extensionId,
      global ? 0 : 1
      /* StorageScope.WORKSPACE */
    );
    if (rawState && rawState?.length > $BM_1.a) {
      this.n.warn(`[mainThreadStorage] large extension state detected (extensionId: ${extensionId}, global: ${global}): ${rawState.length / 1024}kb. Consider to use 'storageUri' or 'globalStorageUri' to store this data on disk instead.`);
    }
    return rawState;
  }
  setExtensionState(extension, state, global) {
    const extensionId = this.s(extension);
    if (state === void 0) {
      this.j.remove(
        extensionId,
        global ? 0 : 1
        /* StorageScope.WORKSPACE */
      );
    } else {
      this.j.store(
        extensionId,
        JSON.stringify(state),
        global ? 0 : 1,
        1
        /* StorageTarget.MACHINE */
      );
    }
  }
  setKeysForSync(extensionIdWithVersion, keys) {
    this.j.store(
      $BM_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(
      $BM_1.b(extensionIdWithVersion),
      0
      /* StorageScope.PROFILE */
    );
    const extensionKeysForSyncFromStorage = extensionKeysForSyncFromStorageValue ? JSON.parse(extensionKeysForSyncFromStorageValue) : void 0;
    return extensionKeysForSyncFromStorage && extensionKeysForSyncFromProduct ? $Rb([...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 */
      );
    }
  }
};
$BM = $BM_1 = __decorate([
  __param(0, $jv),
  __param(1, $Vu),
  __param(2, $wn)
], $BM);

// out-build/vs/workbench/services/extensions/common/extensionStorageMigration.js
async function $hRb(fromExtensionId, toExtensionId, global, instantionService) {
  return instantionService.invokeFunction(async (serviceAccessor) => {
    const environmentService = serviceAccessor.get($Xk);
    const userDataProfilesService = serviceAccessor.get($rs);
    const extensionStorageService = serviceAccessor.get($AM);
    const storageService = serviceAccessor.get($jv);
    const uriIdentityService = serviceAccessor.get($vl);
    const fileService = serviceAccessor.get($km);
    const workspaceContextService = serviceAccessor.get($Zk);
    const logService = serviceAccessor.get($wn);
    const storageMigratedKey = `extensionStorage.migrate.${fromExtensionId}-${toExtensionId}`;
    const migrateLowerCaseStorageKey = fromExtensionId.toLowerCase() === toExtensionId.toLowerCase() ? `extension.storage.migrateFromLowerCaseKey.${fromExtensionId.toLowerCase()}` : void 0;
    if (fromExtensionId === toExtensionId) {
      return;
    }
    const getExtensionStorageLocation = (extensionId, global2) => {
      if (global2) {
        return uriIdentityService.extUri.joinPath(
          userDataProfilesService.defaultProfile.globalStorageHome,
          extensionId.toLowerCase()
          /* Extension id is lower cased for global storage */
        );
      }
      return uriIdentityService.extUri.joinPath(environmentService.workspaceStorageHome, workspaceContextService.getWorkspace().id, extensionId);
    };
    const storageScope = global ? 0 : 1;
    if (!storageService.getBoolean(storageMigratedKey, storageScope, false) && !(migrateLowerCaseStorageKey && storageService.getBoolean(migrateLowerCaseStorageKey, storageScope, false))) {
      logService.info(`Migrating ${global ? "global" : "workspace"} extension storage from ${fromExtensionId} to ${toExtensionId}...`);
      const value = extensionStorageService.getExtensionState(fromExtensionId, global);
      if (value) {
        extensionStorageService.setExtensionState(toExtensionId, value, global);
        extensionStorageService.setExtensionState(fromExtensionId, void 0, global);
      }
      const fromPath = getExtensionStorageLocation(fromExtensionId, global);
      const toPath = getExtensionStorageLocation(toExtensionId, global);
      if (!uriIdentityService.extUri.isEqual(fromPath, toPath)) {
        try {
          await fileService.move(fromPath, toPath, true);
        } catch (error) {
          if (error.code !== FileSystemProviderErrorCode.FileNotFound) {
            logService.info(`Error while migrating ${global ? "global" : "workspace"} file storage from '${fromExtensionId}' to '${toExtensionId}'`, $qb(error));
          }
        }
      }
      logService.info(`Migrated ${global ? "global" : "workspace"} extension storage from ${fromExtensionId} to ${toExtensionId}`);
      storageService.store(
        storageMigratedKey,
        true,
        storageScope,
        1
        /* StorageTarget.MACHINE */
      );
    }
  });
}

// out-build/vs/workbench/api/browser/mainThreadStorage.js
var $iRb = class $iRb2 {
  constructor(extHostContext, d, f, g, h3) {
    this.d = d;
    this.f = f;
    this.g = g;
    this.h = h3;
    this.b = new $2c();
    this.c = /* @__PURE__ */ new Map();
    this.a = extHostContext.getProxy($yT.ExtHostStorage);
    this.b.add(this.f.onDidChangeValue(0, void 0, this.b)((e) => {
      if (this.c.has(e.key)) {
        const rawState = this.d.getExtensionStateRaw(e.key, true);
        if (typeof rawState === "string") {
          this.a.$acceptValue(true, e.key, rawState);
        }
      }
    }));
  }
  dispose() {
    this.b.dispose();
  }
  async $initializeExtensionStorage(shared, extensionId) {
    await this.i(extensionId, shared);
    if (shared) {
      this.c.set(extensionId, true);
    }
    return this.d.getExtensionStateRaw(extensionId, shared);
  }
  async $setValue(shared, key2, value) {
    this.d.setExtensionState(key2, value, shared);
  }
  $registerExtensionStorageKeysToSync(extension, keys) {
    this.d.setKeysForSync(extension, keys);
  }
  async i(extensionId, shared) {
    try {
      let sourceExtensionId = this.d.getSourceExtensionToMigrate(extensionId);
      if (!sourceExtensionId && $r && extensionId !== extensionId.toLowerCase()) {
        sourceExtensionId = extensionId.toLowerCase();
      }
      if (sourceExtensionId) {
        if ($r && sourceExtensionId !== sourceExtensionId.toLowerCase() && this.d.getExtensionState(sourceExtensionId.toLowerCase(), shared) && !this.d.getExtensionState(sourceExtensionId, shared)) {
          sourceExtensionId = sourceExtensionId.toLowerCase();
        }
        await $hRb(sourceExtensionId, extensionId, shared, this.g);
      }
    } catch (error) {
      this.h.error(error);
    }
  }
};
$iRb = __decorate([
  $frb($xT.MainThreadStorage),
  __param(1, $AM),
  __param(2, $jv),
  __param(3, $Pk),
  __param(4, $wn)
], $iRb);

// out-build/vs/workbench/api/browser/mainThreadTelemetry.js
var $jRb_1;
var $jRb = class $jRb2 extends $3c {
  static {
    $jRb_1 = this;
  }
  static {
    this.b = "pluginHostTelemetry";
  }
  constructor(extHostContext, c, f, g, h3) {
    super();
    this.c = c;
    this.f = f;
    this.g = g;
    this.h = h3;
    this.a = extHostContext.getProxy($yT.ExtHostTelemetry);
    if ($iw(this.h, this.g)) {
      this.B(this.f.onDidChangeConfiguration((e) => {
        if (e.affectsConfiguration($Iv) || e.affectsConfiguration($Kv)) {
          this.a.$onDidChangeTelemetryLevel(this.j);
        }
      }));
    }
    this.a.$initializeTelemetryLevel(this.j, $iw(this.h, this.g), this.h.enabledTelemetryLevels);
  }
  get j() {
    if (!$iw(this.h, this.g)) {
      return 0;
    }
    return this.c.telemetryLevel;
  }
  $publicLog(eventName, data = /* @__PURE__ */ Object.create(null)) {
    data[$jRb_1.b] = true;
    this.c.publicLog(eventName, data);
  }
  $publicLog2(eventName, data) {
    this.$publicLog(eventName, data);
  }
};
$jRb = $jRb_1 = __decorate([
  $frb($xT.MainThreadTelemetry),
  __param(1, $zv),
  __param(2, $kl),
  __param(3, $Xk),
  __param(4, $Vu)
], $jRb);

// out-build/vs/platform/terminal/common/terminalDataBuffering.js
var $kRb = class {
  constructor(b) {
    this.b = b;
    this.a = /* @__PURE__ */ new Map();
  }
  dispose() {
    for (const buffer of this.a.values()) {
      buffer.dispose();
    }
  }
  startBuffering(id2, event, throttleBy = 5) {
    const disposable = event((e) => {
      const data = typeof e === "string" ? e : e.data;
      let buffer = this.a.get(id2);
      if (buffer) {
        buffer.data.push(data);
        return;
      }
      const timeoutId = setTimeout(() => this.flushBuffer(id2), throttleBy);
      buffer = {
        data: [data],
        timeoutId,
        dispose: () => {
          clearTimeout(timeoutId);
          this.flushBuffer(id2);
          disposable.dispose();
        }
      };
      this.a.set(id2, buffer);
    });
    return disposable;
  }
  stopBuffering(id2) {
    const buffer = this.a.get(id2);
    buffer?.dispose();
  }
  flushBuffer(id2) {
    const buffer = this.a.get(id2);
    if (buffer) {
      this.a.delete(id2);
      this.b(id2, buffer.data.join(""));
    }
  }
};

// out-build/vs/workbench/contrib/terminal/browser/terminalProcessExtHostProxy.js
var $lRb = class $lRb2 extends $3c {
  get onProcessReady() {
    return this.b.event;
  }
  constructor(instanceId, y, z, C) {
    super();
    this.instanceId = instanceId;
    this.y = y;
    this.z = z;
    this.C = C;
    this.id = 0;
    this.shouldPersist = false;
    this.a = this.B(new $ze());
    this.onProcessData = this.a.event;
    this.b = this.B(new $ze());
    this.c = this.B(new $ze());
    this.onStart = this.c.event;
    this.f = this.B(new $ze());
    this.onInput = this.f.event;
    this.g = this.B(new $ze());
    this.onBinary = this.g.event;
    this.h = this.B(new $ze());
    this.onResize = this.h.event;
    this.j = this.B(new $ze());
    this.onAcknowledgeDataEvent = this.j.event;
    this.m = this.B(new $ze());
    this.onShutdown = this.m.event;
    this.n = this.B(new $ze());
    this.onRequestInitialCwd = this.n.event;
    this.r = this.B(new $ze());
    this.onRequestCwd = this.r.event;
    this.s = this.B(new $ze());
    this.onDidChangeProperty = this.s.event;
    this.t = this.B(new $ze());
    this.onProcessExit = this.t.event;
    this.u = [];
    this.w = [];
  }
  emitData(data) {
    this.a.fire(data);
  }
  emitTitle(title) {
    this.s.fire({ type: "title", value: title });
  }
  emitReady(pid, cwd2) {
    this.b.fire({ pid, cwd: cwd2, windowsPty: void 0 });
  }
  emitProcessProperty({ type, value }) {
    switch (type) {
      case "cwd":
        this.emitCwd(value);
        break;
      case "initialCwd":
        this.emitInitialCwd(value);
        break;
      case "title":
        this.emitTitle(value);
        break;
      case "overrideDimensions":
        this.emitOverrideDimensions(value);
        break;
      case "resolvedShellLaunchConfig":
        this.emitResolvedShellLaunchConfig(value);
        break;
    }
  }
  emitExit(exitCode) {
    this.t.fire(exitCode);
    this.dispose();
  }
  emitOverrideDimensions(dimensions) {
    this.s.fire({ type: "overrideDimensions", value: dimensions });
  }
  emitResolvedShellLaunchConfig(shellLaunchConfig) {
    this.s.fire({ type: "resolvedShellLaunchConfig", value: shellLaunchConfig });
  }
  emitInitialCwd(initialCwd) {
    while (this.u.length > 0) {
      this.u.pop()(initialCwd);
    }
  }
  emitCwd(cwd2) {
    while (this.w.length > 0) {
      this.w.pop()(cwd2);
    }
  }
  async start() {
    return this.C.requestStartExtensionTerminal(this, this.y, this.z);
  }
  shutdown(immediate) {
    this.m.fire(immediate);
  }
  input(data) {
    this.f.fire(data);
  }
  resize(cols, rows) {
    this.h.fire({ cols, rows });
  }
  clearBuffer() {
  }
  acknowledgeDataEvent() {
  }
  async setUnicodeVersion(version2) {
  }
  async processBinary(data) {
    this.g.fire(data);
  }
  getInitialCwd() {
    return new Promise((resolve) => {
      this.n.fire();
      this.u.push(resolve);
    });
  }
  getCwd() {
    return new Promise((resolve) => {
      this.r.fire();
      this.w.push(resolve);
    });
  }
  async refreshProperty(type) {
  }
  async updateProperty(type, value) {
  }
};
$lRb = __decorate([
  __param(3, $4Pb)
], $lRb);

// out-build/vs/workbench/contrib/terminal/common/environmentVariable.js
var $NX = $Qk("environmentVariableService");

// out-build/vs/platform/terminal/common/environmentVariableShared.js
function $BB(collection) {
  return [...collection.entries()];
}
function $CB(descriptionMap) {
  return descriptionMap ? [...descriptionMap.entries()] : [];
}
function $DB(serializedCollection) {
  return new Map(serializedCollection);
}
function $EB(serializableEnvironmentDescription) {
  return new Map(serializableEnvironmentDescription ?? []);
}
function $FB(collections) {
  return Array.from(collections.entries()).map((e) => {
    return [e[0], $BB(e[1].map), $CB(e[1].descriptionMap)];
  });
}
function $GB(serializedCollection) {
  return new Map(serializedCollection.map((e) => {
    return [e[0], { map: $DB(e[1]), descriptionMap: $EB(e[2]) }];
  }));
}

// out-build/vs/workbench/contrib/terminalContrib/links/browser/links.js
var $tRb = $Qk("terminalLinkProviderService");
var TerminalBuiltinLinkType;
(function(TerminalBuiltinLinkType2) {
  TerminalBuiltinLinkType2["LocalFile"] = "LocalFile";
  TerminalBuiltinLinkType2["LocalFolderOutsideWorkspace"] = "LocalFolderOutsideWorkspace";
  TerminalBuiltinLinkType2["LocalFolderInWorkspace"] = "LocalFolderInWorkspace";
  TerminalBuiltinLinkType2["Search"] = "Search";
  TerminalBuiltinLinkType2["Url"] = "Url";
})(TerminalBuiltinLinkType || (TerminalBuiltinLinkType = {}));

// out-build/vs/workbench/contrib/terminalContrib/quickFix/browser/quickFix.js
var $uRb = $Qk("terminalQuickFixService");
var TerminalQuickFixType2;
(function(TerminalQuickFixType3) {
  TerminalQuickFixType3[TerminalQuickFixType3["TerminalCommand"] = 0] = "TerminalCommand";
  TerminalQuickFixType3[TerminalQuickFixType3["Opener"] = 1] = "Opener";
  TerminalQuickFixType3[TerminalQuickFixType3["Port"] = 2] = "Port";
  TerminalQuickFixType3[TerminalQuickFixType3["VscodeCommand"] = 3] = "VscodeCommand";
})(TerminalQuickFixType2 || (TerminalQuickFixType2 = {}));

// out-build/vs/workbench/contrib/terminalContrib/suggest/browser/terminalCompletionService.js
var $wRb = $Qk("terminalCompletionService");
var TerminalCompletionItemKind2;
(function(TerminalCompletionItemKind3) {
  TerminalCompletionItemKind3[TerminalCompletionItemKind3["File"] = 0] = "File";
  TerminalCompletionItemKind3[TerminalCompletionItemKind3["Folder"] = 1] = "Folder";
  TerminalCompletionItemKind3[TerminalCompletionItemKind3["Flag"] = 2] = "Flag";
  TerminalCompletionItemKind3[TerminalCompletionItemKind3["Method"] = 3] = "Method";
  TerminalCompletionItemKind3[TerminalCompletionItemKind3["Argument"] = 4] = "Argument";
})(TerminalCompletionItemKind2 || (TerminalCompletionItemKind2 = {}));
var $yRb = class $yRb2 extends $3c {
  get providers() {
    return this.b();
  }
  *b() {
    for (const providerMap of this.a.values()) {
      for (const provider of providerMap.values()) {
        yield provider;
      }
    }
  }
  constructor(c, f) {
    super();
    this.c = c;
    this.f = f;
    this.a = /* @__PURE__ */ new Map();
  }
  registerTerminalCompletionProvider(extensionIdentifier, id2, provider, ...triggerCharacters) {
    let extMap = this.a.get(extensionIdentifier);
    if (!extMap) {
      extMap = /* @__PURE__ */ new Map();
      this.a.set(extensionIdentifier, extMap);
    }
    provider.triggerCharacters = triggerCharacters;
    provider.id = id2;
    extMap.set(id2, provider);
    return $1c(() => {
      const extMap2 = this.a.get(extensionIdentifier);
      if (extMap2) {
        extMap2.delete(id2);
        if (extMap2.size === 0) {
          this.a.delete(extensionIdentifier);
        }
      }
    });
  }
  async provideCompletions(promptValue, cursorPosition, shellType, token, triggerCharacter, skipExtensionCompletions) {
    if (!this.a || !this.a.values) {
      return void 0;
    }
    const extensionCompletionsEnabled = this.c.getValue($ZX).enableExtensionCompletions;
    let providers2;
    if (triggerCharacter) {
      const providersToRequest = [];
      for (const provider of this.providers) {
        if (!provider.triggerCharacters) {
          continue;
        }
        for (const char of provider.triggerCharacters) {
          if (promptValue.substring(0, cursorPosition)?.endsWith(char)) {
            providersToRequest.push(provider);
            break;
          }
        }
      }
      providers2 = providersToRequest;
    } else {
      providers2 = [...this.a.values()].flatMap((providerMap) => [...providerMap.values()]);
    }
    if (!extensionCompletionsEnabled || skipExtensionCompletions) {
      providers2 = providers2.filter((p) => p.isBuiltin);
    }
    return this.g(providers2, shellType, promptValue, cursorPosition, token);
  }
  async g(providers2, shellType, promptValue, cursorPosition, token) {
    const completionPromises = providers2.map(async (provider) => {
      if (provider.shellTypes && !provider.shellTypes.includes(shellType)) {
        return void 0;
      }
      const completions = await provider.provideCompletions(promptValue, cursorPosition, token);
      if (!completions) {
        return void 0;
      }
      const completionItems = Array.isArray(completions) ? completions : completions.items ?? [];
      const itemsWithModifiedLabels = this.h(completionItems, provider.id);
      if (Array.isArray(completions)) {
        return itemsWithModifiedLabels;
      }
      if (completions.resourceRequestConfig) {
        const resourceCompletions = await this.resolveResources(completions.resourceRequestConfig, promptValue, cursorPosition);
        if (resourceCompletions) {
          itemsWithModifiedLabels.push(...this.h(resourceCompletions, provider.id));
        }
        return itemsWithModifiedLabels;
      }
      return;
    });
    const results = await Promise.all(completionPromises);
    return results.filter((result) => !!result).flat();
  }
  h(completions, providerId) {
    const devModeEnabled = this.c.getValue(
      "terminal.integrated.developer.devMode"
      /* TerminalSettingId.DevMode */
    );
    return completions.map((completion) => {
      if (devModeEnabled && !completion.detail?.includes(providerId)) {
        completion.detail = `(${providerId}) ${completion.detail ?? ""}`;
      }
      return completion;
    });
  }
  async resolveResources(resourceRequestConfig, promptValue, cursorPosition) {
    const cwd2 = URI.revive(resourceRequestConfig.cwd);
    const foldersRequested = resourceRequestConfig.foldersRequested ?? false;
    const filesRequested = resourceRequestConfig.filesRequested ?? false;
    if (!cwd2 || !foldersRequested && !filesRequested) {
      return;
    }
    const fileStat = await this.f.resolve(cwd2, { resolveSingleChildDescendants: true });
    if (!fileStat || !fileStat?.children) {
      return;
    }
    const resourceCompletions = [];
    const endsWithSpace = promptValue.substring(0, cursorPosition).endsWith(" ");
    let lastWord;
    if (endsWithSpace) {
      lastWord = "";
    } else {
      lastWord = promptValue.substring(0, cursorPosition).trim().split(" ").at(-1) ?? "";
    }
    for (const stat of fileStat.children) {
      let kind;
      if (foldersRequested && stat.isDirectory) {
        kind = TerminalCompletionItemKind2.Folder;
      }
      if (filesRequested && !stat.isDirectory && (stat.isFile || stat.resource.scheme === Schemas.file)) {
        kind = TerminalCompletionItemKind2.File;
      }
      if (kind === void 0) {
        continue;
      }
      const isDirectory = kind === TerminalCompletionItemKind2.Folder;
      const pathToResource = stat.resource.fsPath.replace(cwd2.fsPath, "");
      let label3 = pathToResource;
      if (isDirectory && !label3.endsWith(resourceRequestConfig.pathSeparator)) {
        label3 = label3 + resourceRequestConfig.pathSeparator;
      }
      const startsWithDot = lastWord && lastWord.startsWith(".");
      if (!startsWithDot) {
        label3 = "." + label3;
      }
      resourceCompletions.push({
        label: label3,
        kind,
        isDirectory,
        isFile: kind === TerminalCompletionItemKind2.File,
        replacementIndex: promptValue[cursorPosition - 1] === " " ? cursorPosition : cursorPosition - 1,
        replacementLength: label3.length - lastWord.length > 0 ? label3.length - lastWord.length : label3.length
      });
    }
    return resourceCompletions.length ? resourceCompletions : void 0;
  }
};
$yRb = __decorate([
  __param(0, $kl),
  __param(1, $km)
], $yRb);

// out-build/vs/workbench/api/browser/mainThreadTerminalService.js
var $zRb = class $zRb2 {
  constructor(m, n, o, p, q, s, t, u, remoteAgentService, v, w, x, y) {
    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.v = v;
    this.w = w;
    this.x = x;
    this.y = y;
    this.a = new $2c();
    this.c = /* @__PURE__ */ new Map();
    this.d = /* @__PURE__ */ new Map();
    this.f = /* @__PURE__ */ new Map();
    this.g = /* @__PURE__ */ new Map();
    this.h = /* @__PURE__ */ new Map();
    this.i = new $4c();
    this.j = new $4c();
    this.k = this.a.add(new $4c());
    this.l = OS;
    this.b = m.getProxy($yT.ExtHostTerminalService);
    this.a.add(n.onDidCreateInstance((instance2) => {
      this.H(instance2);
      this.J(instance2);
    }));
    this.a.add(n.onDidDisposeInstance((instance2) => this.G(instance2)));
    this.a.add(n.onAnyInstanceProcessIdReady((instance2) => this.I(instance2)));
    this.a.add(n.onDidChangeInstanceDimensions((instance2) => this.J(instance2)));
    this.a.add(n.onAnyInstanceMaximumDimensionsChange((instance2) => this.K(instance2)));
    this.a.add(n.onDidRequestStartExtensionTerminal((e) => this.L(e)));
    this.a.add(n.onDidChangeActiveInstance((instance2) => this.C(instance2 ? instance2.instanceId : null)));
    this.a.add(n.onAnyInstanceTitleChange((instance2) => instance2 && this.F(instance2.instanceId, instance2.title)));
    this.a.add(n.onAnyInstanceDataInput((instance2) => this.b.$acceptTerminalInteraction(instance2.instanceId)));
    this.a.add(n.onAnyInstanceSelectionChange((instance2) => this.b.$acceptTerminalSelection(instance2.instanceId, instance2.selection)));
    for (const instance2 of this.n.instances) {
      this.H(instance2);
      instance2.processReady.then(() => this.I(instance2));
    }
    const activeInstance = this.n.activeInstance;
    if (activeInstance) {
      this.b.$acceptActiveTerminalChanged(activeInstance.instanceId);
    }
    if (this.s.collections.size > 0) {
      const collectionAsArray = [...this.s.collections.entries()];
      const serializedCollections = collectionAsArray.map((e) => {
        return [e[0], $BB(e[1].map)];
      });
      this.b.$initEnvironmentVariableCollections(serializedCollections);
    }
    remoteAgentService.getEnvironment().then(async (env3) => {
      this.l = env3?.os || OS;
      this.z();
    });
    this.a.add(this.x.onDidChangeAvailableProfiles(() => this.z()));
  }
  dispose() {
    this.a.dispose();
    for (const provider of this.f.values()) {
      provider.dispose();
    }
    for (const provider of this.h.values()) {
      provider.dispose();
    }
  }
  async z() {
    const remoteAuthority = this.m.remoteAuthority ?? void 0;
    const defaultProfile = this.u.getDefaultProfile({ remoteAuthority, os: this.l });
    const defaultAutomationProfile = this.u.getDefaultProfile({ remoteAuthority, os: this.l, allowAutomationShell: true });
    this.b.$acceptDefaultProfile(...await Promise.all([defaultProfile, defaultAutomationProfile]));
  }
  async A(id2) {
    if (typeof id2 === "string") {
      return this.c.get(id2);
    }
    return this.n.getInstanceFromId(id2);
  }
  async $createTerminal(extHostTerminalId, launchConfig) {
    const shellLaunchConfig = {
      name: launchConfig.name,
      executable: launchConfig.shellPath,
      args: launchConfig.shellArgs,
      cwd: typeof launchConfig.cwd === "string" ? launchConfig.cwd : URI.revive(launchConfig.cwd),
      icon: launchConfig.icon,
      color: launchConfig.color,
      initialText: launchConfig.initialText,
      waitOnExit: launchConfig.waitOnExit,
      ignoreConfigurationCwd: true,
      env: launchConfig.env,
      strictEnv: launchConfig.strictEnv,
      hideFromUser: launchConfig.hideFromUser,
      customPtyImplementation: launchConfig.isExtensionCustomPtyTerminal ? (id2, cols, rows) => new $lRb(id2, cols, rows, this.n) : void 0,
      extHostTerminalId,
      forceShellIntegration: launchConfig.forceShellIntegration,
      isFeatureTerminal: launchConfig.isFeatureTerminal,
      isExtensionOwnedTerminal: launchConfig.isExtensionOwnedTerminal,
      useShellEnvironment: launchConfig.useShellEnvironment,
      isTransient: launchConfig.isTransient
    };
    const terminal2 = Promises.withAsyncBody(async (r2) => {
      const terminal3 = await this.n.createTerminal({
        config: shellLaunchConfig,
        location: await this.B(launchConfig.location)
      });
      r2(terminal3);
    });
    this.c.set(extHostTerminalId, terminal2);
    const terminalInstance = await terminal2;
    this.a.add(terminalInstance.onDisposed(() => {
      this.c.delete(extHostTerminalId);
    }));
  }
  async B(location3) {
    if (typeof location3 === "object" && "parentTerminal" in location3) {
      const parentTerminal = await this.c.get(location3.parentTerminal.toString());
      return parentTerminal ? { parentTerminal } : void 0;
    }
    return location3;
  }
  async $show(id2, preserveFocus) {
    const terminalInstance = await this.A(id2);
    if (terminalInstance) {
      this.n.setActiveInstance(terminalInstance);
      if (terminalInstance.target === TerminalLocation2.Editor) {
        await this.w.revealActiveEditor(preserveFocus);
      } else {
        await this.v.showPanel(!preserveFocus);
      }
    }
  }
  async $hide(id2) {
    const instanceToHide = await this.A(id2);
    const activeInstance = this.n.activeInstance;
    if (activeInstance && activeInstance.instanceId === instanceToHide?.instanceId && activeInstance.target !== TerminalLocation2.Editor) {
      this.v.hidePanel();
    }
  }
  async $dispose(id2) {
    (await this.A(id2))?.dispose(TerminalExitReason2.Extension);
  }
  async $sendText(id2, text2, shouldExecute) {
    const instance2 = await this.A(id2);
    await instance2?.sendText(text2, shouldExecute);
  }
  $sendProcessExit(terminalId, exitCode) {
    this.d.get(terminalId)?.emitExit(exitCode);
  }
  $startSendingDataEvents() {
    if (!this.i.value) {
      this.i.value = this.q.createInstance(TerminalDataEventTracker, (id2, data) => {
        this.D(id2, data);
      });
      for (const instance2 of this.n.instances) {
        for (const data of instance2.initialDataEvents || []) {
          this.D(instance2.instanceId, data);
        }
      }
    }
  }
  $stopSendingDataEvents() {
    this.i.clear();
  }
  $startSendingCommandEvents() {
    if (this.j.value) {
      return;
    }
    const multiplexer = this.n.createOnInstanceCapabilityEvent(2, (capability) => capability.onCommandFinished);
    const sub = multiplexer.event((e) => {
      this.E(e.instance.instanceId, {
        commandLine: e.data.command,
        // TODO: Convert to URI if possible
        cwd: e.data.cwd,
        exitCode: e.data.exitCode,
        output: e.data.getOutput()
      });
    });
    this.j.value = $Zc(multiplexer, sub);
  }
  $stopSendingCommandEvents() {
    this.j.clear();
  }
  $startLinkProvider() {
    this.k.value = this.o.registerLinkProvider(new ExtensionTerminalLinkProvider(this.b));
  }
  $stopLinkProvider() {
    this.k.clear();
  }
  $registerProcessSupport(isSupported) {
    this.n.registerProcessSupport(isSupported);
  }
  $registerCompletionProvider(id2, extensionIdentifier, ...triggerCharacters) {
    this.g.set(id2, this.y.registerTerminalCompletionProvider(extensionIdentifier, id2, {
      id: id2,
      provideCompletions: async (commandLine, cursorPosition, token) => {
        return await this.b.$provideTerminalCompletions(id2, { commandLine, cursorPosition }, token);
      }
    }, ...triggerCharacters));
  }
  $unregisterCompletionProvider(id2) {
    this.g.get(id2)?.dispose();
    this.g.delete(id2);
  }
  $registerProfileProvider(id2, extensionIdentifier) {
    this.f.set(id2, this.x.registerTerminalProfileProvider(extensionIdentifier, id2, {
      createContributedTerminalProfile: async (options3) => {
        return this.b.$createContributedProfileTerminal(id2, options3);
      }
    }));
  }
  $unregisterProfileProvider(id2) {
    this.f.get(id2)?.dispose();
    this.f.delete(id2);
  }
  async $registerQuickFixProvider(id2, extensionId) {
    this.h.set(id2, this.p.registerQuickFixProvider(id2, {
      provideTerminalQuickFixes: async (terminalCommand, lines, options3, token) => {
        if (token.isCancellationRequested) {
          return;
        }
        if (options3.outputMatcher?.length && options3.outputMatcher.length > 40) {
          options3.outputMatcher.length = 40;
          this.t.warn("Cannot exceed output matcher length of 40");
        }
        const commandLineMatch = terminalCommand.command.match(options3.commandLineMatcher);
        if (!commandLineMatch || !lines) {
          return;
        }
        const outputMatcher = options3.outputMatcher;
        let outputMatch;
        if (outputMatcher) {
          outputMatch = $ARb(lines, outputMatcher);
        }
        if (!outputMatch) {
          return;
        }
        const matchResult = { commandLineMatch, outputMatch, commandLine: terminalCommand.command };
        if (matchResult) {
          const result = await this.b.$provideTerminalQuickFixes(id2, matchResult, token);
          if (result && Array.isArray(result)) {
            return result.map((r2) => parseQuickFix(id2, extensionId, r2));
          } else if (result) {
            return parseQuickFix(id2, extensionId, result);
          }
        }
        return;
      }
    }));
  }
  $unregisterQuickFixProvider(id2) {
    this.h.get(id2)?.dispose();
    this.h.delete(id2);
  }
  C(terminalId) {
    this.b.$acceptActiveTerminalChanged(terminalId);
  }
  D(terminalId, data) {
    this.b.$acceptTerminalProcessData(terminalId, data);
  }
  E(terminalId, command4) {
    this.b.$acceptDidExecuteCommand(terminalId, command4);
  }
  F(terminalId, name) {
    this.b.$acceptTerminalTitleChange(terminalId, name);
  }
  G(terminalInstance) {
    this.b.$acceptTerminalClosed(terminalInstance.instanceId, terminalInstance.exitCode, terminalInstance.exitReason ?? TerminalExitReason2.Unknown);
  }
  H(terminalInstance) {
    const extHostTerminalId = terminalInstance.shellLaunchConfig.extHostTerminalId;
    const shellLaunchConfigDto = {
      name: terminalInstance.shellLaunchConfig.name,
      executable: terminalInstance.shellLaunchConfig.executable,
      args: terminalInstance.shellLaunchConfig.args,
      cwd: terminalInstance.shellLaunchConfig.cwd,
      env: terminalInstance.shellLaunchConfig.env,
      hideFromUser: terminalInstance.shellLaunchConfig.hideFromUser
    };
    this.b.$acceptTerminalOpened(terminalInstance.instanceId, extHostTerminalId, terminalInstance.title, shellLaunchConfigDto);
  }
  I(terminalInstance) {
    if (terminalInstance.processId === void 0) {
      return;
    }
    this.b.$acceptTerminalProcessId(terminalInstance.instanceId, terminalInstance.processId);
  }
  J(instance2) {
    this.b.$acceptTerminalDimensions(instance2.instanceId, instance2.cols, instance2.rows);
  }
  K(instance2) {
    this.b.$acceptTerminalMaximumDimensions(instance2.instanceId, instance2.maxCols, instance2.maxRows);
  }
  L(request) {
    const proxy = request.proxy;
    this.d.set(proxy.instanceId, proxy);
    const initialDimensions = request.cols && request.rows ? {
      columns: request.cols,
      rows: request.rows
    } : void 0;
    this.b.$startExtensionTerminal(proxy.instanceId, initialDimensions).then(request.callback);
    proxy.onInput((data) => this.b.$acceptProcessInput(proxy.instanceId, data));
    proxy.onShutdown((immediate) => this.b.$acceptProcessShutdown(proxy.instanceId, immediate));
    proxy.onRequestCwd(() => this.b.$acceptProcessRequestCwd(proxy.instanceId));
    proxy.onRequestInitialCwd(() => this.b.$acceptProcessRequestInitialCwd(proxy.instanceId));
  }
  $sendProcessData(terminalId, data) {
    this.d.get(terminalId)?.emitData(data);
  }
  $sendProcessReady(terminalId, pid, cwd2, windowsPty) {
    this.d.get(terminalId)?.emitReady(pid, cwd2, windowsPty);
  }
  $sendProcessProperty(terminalId, property) {
    if (property.type === "title") {
      const instance2 = this.n.getInstanceFromId(terminalId);
      instance2?.rename(property.value);
    }
    this.d.get(terminalId)?.emitProcessProperty(property);
  }
  $setEnvironmentVariableCollection(extensionIdentifier, persistent, collection, descriptionMap) {
    if (collection) {
      const translatedCollection = {
        persistent,
        map: $DB(collection),
        descriptionMap: $EB(descriptionMap)
      };
      this.s.set(extensionIdentifier, translatedCollection);
    } else {
      this.s.delete(extensionIdentifier);
    }
  }
};
$zRb = __decorate([
  $frb($xT.MainThreadTerminalService),
  __param(1, $4Pb),
  __param(2, $tRb),
  __param(3, $uRb),
  __param(4, $Pk),
  __param(5, $NX),
  __param(6, $wn),
  __param(7, $fY),
  __param(8, $RL),
  __param(9, $7Pb),
  __param(10, $6Pb),
  __param(11, $hY),
  __param(12, $wRb)
], $zRb);
var TerminalDataEventTracker = class TerminalDataEventTracker2 extends $3c {
  constructor(b, c) {
    super();
    this.b = b;
    this.c = c;
    this.B(this.a = new $kRb(this.b));
    for (const instance2 of this.c.instances) {
      this.f(instance2);
    }
    this.B(this.c.onDidCreateInstance((instance2) => this.f(instance2)));
    this.B(this.c.onDidDisposeInstance((instance2) => this.a.stopBuffering(instance2.instanceId)));
  }
  f(instance2) {
    this.B(this.a.startBuffering(instance2.instanceId, instance2.onData));
  }
};
TerminalDataEventTracker = __decorate([
  __param(1, $4Pb)
], TerminalDataEventTracker);
var ExtensionTerminalLinkProvider = class {
  constructor(a) {
    this.a = a;
  }
  async provideLinks(instance2, line) {
    const proxy = this.a;
    const extHostLinks = await proxy.$provideLinks(instance2.instanceId, line);
    return extHostLinks.map((dto) => ({
      id: dto.id,
      startIndex: dto.startIndex,
      length: dto.length,
      label: dto.label,
      activate: () => proxy.$activateLink(instance2.instanceId, dto.id)
    }));
  }
};
function $ARb(lines, outputMatcher) {
  const match = lines.join("\n").match(outputMatcher.lineMatcher);
  return match ? { regexMatch: match, outputLines: lines } : void 0;
}
function parseQuickFix(id2, source, fix) {
  let type = TerminalQuickFixType2.TerminalCommand;
  if ("uri" in fix) {
    fix.uri = URI.revive(fix.uri);
    type = TerminalQuickFixType2.Opener;
  } else if ("id" in fix) {
    type = TerminalQuickFixType2.VscodeCommand;
  }
  return { id: id2, type, source, ...fix };
}

// out-build/vs/workbench/api/browser/mainThreadTerminalShellIntegration.js
var $BRb = class $BRb2 extends $3c {
  constructor(extHostContext, b, workbenchEnvironmentService) {
    super();
    this.b = b;
    this.a = extHostContext.getProxy($yT.ExtHostTerminalShellIntegration);
    const instanceDataListeners = /* @__PURE__ */ new Map();
    this.B($1c(() => {
      for (const listener of instanceDataListeners.values()) {
        listener.dispose();
      }
    }));
    const onDidAddCommandDetection = this.q.add(this.b.createOnInstanceEvent((instance2) => {
      return Event2.map(Event2.filter(instance2.capabilities.onDidAddCapabilityType, (e) => {
        return e === 2 || e === 0;
      }), () => instance2);
    })).event;
    this.q.add(onDidAddCommandDetection((e) => this.a.$shellIntegrationChange(e.instanceId)));
    const commandDetectionStartEvent = this.q.add(this.b.createOnInstanceCapabilityEvent(2, (e) => e.onCommandExecuted));
    let currentCommand;
    this.q.add(commandDetectionStartEvent.event((e) => {
      if (e.data === currentCommand) {
        return;
      }
      currentCommand = e.data;
      const instanceId = e.instance.instanceId;
      this.a.$shellExecutionStart(instanceId, e.data.command, convertToExtHostCommandLineConfidence(e.data), e.data.isTrusted, this.c(e.data.cwd));
      instanceDataListeners.get(instanceId)?.dispose();
      instanceDataListeners.set(instanceId, Event2.accumulate(e.instance.onData, 50, this.q)((events) => this.a.$shellExecutionData(instanceId, events.join(""))));
    }));
    const commandDetectionEndEvent = this.q.add(this.b.createOnInstanceCapabilityEvent(2, (e) => e.onCommandFinished));
    this.q.add(commandDetectionEndEvent.event((e) => {
      currentCommand = void 0;
      const instanceId = e.instance.instanceId;
      instanceDataListeners.get(instanceId)?.dispose();
      setTimeout(() => {
        this.a.$shellExecutionEnd(instanceId, e.data.command, convertToExtHostCommandLineConfidence(e.data), e.data.isTrusted, e.data.exitCode);
      });
    }));
    const cwdChangeEvent = this.q.add(this.b.createOnInstanceCapabilityEvent(0, (e) => e.onDidChangeCwd));
    this.q.add(cwdChangeEvent.event((e) => {
      this.a.$cwdChange(e.instance.instanceId, this.c(e.data));
    }));
    this.q.add(this.b.onDidDisposeInstance((e) => this.a.$closeTerminal(e.instanceId)));
  }
  $executeCommand(terminalId, commandLine) {
    this.b.getInstanceFromId(terminalId)?.runCommand(commandLine, true);
  }
  c(cwd2) {
    return cwd2 ? URI.file(cwd2) : void 0;
  }
};
$BRb = __decorate([
  $frb($xT.MainThreadTerminalShellIntegration),
  __param(1, $4Pb),
  __param(2, $US)
], $BRb);
function convertToExtHostCommandLineConfidence(command4) {
  switch (command4.commandLineConfidence) {
    case "high":
      return TerminalShellExecutionCommandLineConfidence.High;
    case "medium":
      return TerminalShellExecutionCommandLineConfidence.Medium;
    case "low":
    default:
      return TerminalShellExecutionCommandLineConfidence.Low;
  }
}

// out-build/vs/workbench/api/browser/mainThreadTheming.js
var $CRb = class $CRb2 {
  constructor(extHostContext, themeService) {
    this.a = themeService;
    this.b = extHostContext.getProxy($yT.ExtHostTheming);
    this.c = this.a.onDidColorThemeChange((e) => {
      this.b.$onColorThemeChange(this.a.getColorTheme().type);
    });
    this.b.$onColorThemeChange(this.a.getColorTheme().type);
  }
  dispose() {
    this.c.dispose();
  }
};
$CRb = __decorate([
  $frb($xT.MainThreadTheming),
  __param(1, $gs)
], $CRb);

// out-build/vs/workbench/api/browser/mainThreadTreeViews.js
var $DRb = class $DRb2 extends $3c {
  constructor(extHostContext, f, g, h3, j) {
    super();
    this.f = f;
    this.g = g;
    this.h = h3;
    this.j = j;
    this.b = this.B(new $_c());
    this.c = /* @__PURE__ */ new Map();
    this.a = extHostContext.getProxy($yT.ExtHostTreeViews);
  }
  async $registerTreeViewDataProvider(treeViewId, options3) {
    this.j.trace("MainThreadTreeViews#$registerTreeViewDataProvider", treeViewId, options3);
    this.h.whenInstalledExtensionsRegistered().then(() => {
      const dataProvider = new TreeViewDataProvider(treeViewId, this.a, this.g);
      const disposables = new $2c();
      this.b.set(treeViewId, { dataProvider, dispose: () => disposables.dispose() });
      const dndController = options3.hasHandleDrag || options3.hasHandleDrop ? new TreeViewDragAndDropController(treeViewId, options3.dropMimeTypes, options3.dragMimeTypes, options3.hasHandleDrag, this.a) : void 0;
      const viewer = this.r(treeViewId);
      if (viewer) {
        viewer.showCollapseAllAction = options3.showCollapseAll;
        viewer.canSelectMany = options3.canSelectMany;
        viewer.manuallyManageCheckboxes = options3.manuallyManageCheckboxes;
        viewer.dragAndDropController = dndController;
        if (dndController) {
          this.c.set(treeViewId, dndController);
        }
        viewer.dataProvider = dataProvider;
        this.n(treeViewId, viewer, disposables);
        this.a.$setVisible(treeViewId, viewer.visible);
      } else {
        this.g.error("No view is registered with id: " + treeViewId);
      }
    });
  }
  $reveal(treeViewId, itemInfo, options3) {
    this.j.trace("MainThreadTreeViews#$reveal", treeViewId, itemInfo?.item, itemInfo?.parentChain, options3);
    return this.f.openView(treeViewId, options3.focus).then(() => {
      const viewer = this.r(treeViewId);
      if (viewer && itemInfo) {
        return this.m(viewer, this.b.get(treeViewId).dataProvider, itemInfo.item, itemInfo.parentChain, options3);
      }
      return void 0;
    });
  }
  $refresh(treeViewId, itemsToRefreshByHandle) {
    this.j.trace("MainThreadTreeViews#$refresh", treeViewId, itemsToRefreshByHandle);
    const viewer = this.r(treeViewId);
    const dataProvider = this.b.get(treeViewId);
    if (viewer && dataProvider) {
      const itemsToRefresh = dataProvider.dataProvider.getItemsToRefresh(itemsToRefreshByHandle);
      return viewer.refresh(itemsToRefresh.items.length ? itemsToRefresh.items : void 0, itemsToRefresh.checkboxes.length ? itemsToRefresh.checkboxes : void 0);
    }
    return Promise.resolve();
  }
  $setMessage(treeViewId, message) {
    this.j.trace("MainThreadTreeViews#$setMessage", treeViewId, message.toString());
    const viewer = this.r(treeViewId);
    if (viewer) {
      viewer.message = message;
    }
  }
  $setTitle(treeViewId, title, description) {
    this.j.trace("MainThreadTreeViews#$setTitle", treeViewId, title, description);
    const viewer = this.r(treeViewId);
    if (viewer) {
      viewer.title = title;
      viewer.description = description;
    }
  }
  $setBadge(treeViewId, badge) {
    this.j.trace("MainThreadTreeViews#$setBadge", treeViewId, badge?.value, badge?.tooltip);
    const viewer = this.r(treeViewId);
    if (viewer) {
      viewer.badge = badge;
    }
  }
  $resolveDropFileData(destinationViewId, requestId, dataItemId) {
    const controller = this.c.get(destinationViewId);
    if (!controller) {
      throw new Error("Unknown tree");
    }
    return controller.resolveDropFileData(requestId, dataItemId);
  }
  async $disposeTree(treeViewId) {
    const viewer = this.r(treeViewId);
    if (viewer) {
      viewer.dataProvider = void 0;
    }
    this.b.deleteAndDispose(treeViewId);
  }
  async m(treeView, dataProvider, itemIn, parentChain, options3) {
    options3 = options3 ? options3 : { select: false, focus: false };
    const select = $Ig(options3.select) ? false : options3.select;
    const focus = $Ig(options3.focus) ? false : options3.focus;
    let expand = Math.min($Dg(options3.expand) ? options3.expand : options3.expand === true ? 1 : 0, 3);
    if (dataProvider.isEmpty()) {
      await treeView.refresh();
    }
    for (const parent of parentChain) {
      const parentItem = dataProvider.getItem(parent.handle);
      if (parentItem) {
        await treeView.expand(parentItem);
      }
    }
    const item = dataProvider.getItem(itemIn.handle);
    if (item) {
      await treeView.reveal(item);
      if (select) {
        treeView.setSelection([item]);
      }
      if (focus === false) {
        treeView.setFocus();
      } else if (focus) {
        treeView.setFocus(item);
      }
      let itemsToExpand = [item];
      for (; itemsToExpand.length > 0 && expand > 0; expand--) {
        await treeView.expand(itemsToExpand);
        itemsToExpand = itemsToExpand.reduce((result, itemValue) => {
          const item2 = dataProvider.getItem(itemValue.handle);
          if (item2 && item2.children && item2.children.length) {
            result.push(...item2.children);
          }
          return result;
        }, []);
      }
    }
  }
  n(treeViewId, treeView, disposables) {
    disposables.add(treeView.onDidExpandItem((item) => this.a.$setExpanded(treeViewId, item.handle, true)));
    disposables.add(treeView.onDidCollapseItem((item) => this.a.$setExpanded(treeViewId, item.handle, false)));
    disposables.add(treeView.onDidChangeSelectionAndFocus((items) => this.a.$setSelectionAndFocus(treeViewId, items.selection.map(({ handle: handle2 }) => handle2), items.focus.handle)));
    disposables.add(treeView.onDidChangeVisibility((isVisible) => this.a.$setVisible(treeViewId, isVisible)));
    disposables.add(treeView.onDidChangeCheckboxState((items) => {
      this.a.$changeCheckboxState(treeViewId, items.map((item) => {
        return { treeItemHandle: item.handle, newState: item.checkbox?.isChecked ?? false };
      }));
    }));
  }
  r(treeViewId) {
    const viewDescriptor3 = $Wn.as(Extensions5.ViewsRegistry).getView(treeViewId);
    return viewDescriptor3 ? viewDescriptor3.treeView : null;
  }
  dispose() {
    for (const dataprovider of this.b) {
      const treeView = this.r(dataprovider[0]);
      if (treeView) {
        treeView.dataProvider = void 0;
      }
    }
    this.b.dispose();
    this.c.clear();
    super.dispose();
  }
};
$DRb = __decorate([
  $frb($xT.MainThreadTreeViews),
  __param(1, $uob),
  __param(2, $PJ),
  __param(3, $wN),
  __param(4, $wn)
], $DRb);
var TreeViewDragAndDropController = class {
  constructor(b, dropMimeTypes, dragMimeTypes, hasWillDrop, c) {
    this.b = b;
    this.dropMimeTypes = dropMimeTypes;
    this.dragMimeTypes = dragMimeTypes;
    this.hasWillDrop = hasWillDrop;
    this.c = c;
    this.a = new $oQb();
  }
  async handleDrop(dataTransfer, targetTreeItem, token, operationUuid, sourceTreeId, sourceTreeItemHandles) {
    const request = this.a.add(dataTransfer);
    try {
      const dataTransferDto = await DataTransfer.from(dataTransfer);
      if (token.isCancellationRequested) {
        return;
      }
      return await this.c.$handleDrop(this.b, request.id, dataTransferDto, targetTreeItem?.handle, token, operationUuid, sourceTreeId, sourceTreeItemHandles);
    } finally {
      request.dispose();
    }
  }
  async handleDrag(sourceTreeItemHandles, operationUuid, token) {
    if (!this.hasWillDrop) {
      return;
    }
    const additionalDataTransferDTO = await this.c.$handleDrag(this.b, sourceTreeItemHandles, operationUuid, token);
    if (!additionalDataTransferDTO) {
      return;
    }
    const additionalDataTransfer = new $lE();
    additionalDataTransferDTO.items.forEach(([type, item]) => {
      additionalDataTransfer.replace(type, $jE(item.asString));
    });
    return additionalDataTransfer;
  }
  resolveDropFileData(requestId, dataItemId) {
    return this.a.resolveFileData(requestId, dataItemId);
  }
};
var TreeViewDataProvider = class {
  constructor(c, d, e) {
    this.c = c;
    this.d = d;
    this.e = e;
    this.a = /* @__PURE__ */ new Map();
    this.b = this.d.$hasResolve(this.c);
  }
  async getChildren(treeItem) {
    const batches = await this.getChildrenBatch(treeItem ? [treeItem] : void 0);
    return batches?.[0];
  }
  getChildrenBatch(treeItems) {
    if (!treeItems) {
      this.a.clear();
    }
    return this.d.$getChildren(this.c, treeItems ? treeItems.map((item) => item.handle) : void 0).then((children) => {
      const convertedChildren = this.f(treeItems ?? [], children);
      return this.g(convertedChildren);
    }, (err) => {
      if (!$aN.is(err)) {
        this.e.error(err);
      }
      return [];
    });
  }
  f(parents, children) {
    const convertedChildren = Array(parents.length);
    if (children) {
      for (const childGroup of children) {
        const childGroupIndex = childGroup[0];
        convertedChildren[childGroupIndex] = childGroup.slice(1);
      }
    }
    return convertedChildren;
  }
  getItemsToRefresh(itemsToRefreshByHandle) {
    const itemsToRefresh = [];
    const checkboxesToRefresh = [];
    if (itemsToRefreshByHandle) {
      for (const newTreeItemHandle of Object.keys(itemsToRefreshByHandle)) {
        const currentTreeItem = this.getItem(newTreeItemHandle);
        if (currentTreeItem) {
          const newTreeItem = itemsToRefreshByHandle[newTreeItemHandle];
          if (currentTreeItem.checkbox?.isChecked !== newTreeItem.checkbox?.isChecked) {
            checkboxesToRefresh.push(currentTreeItem);
          }
          this.h(currentTreeItem, newTreeItem);
          if (newTreeItemHandle === newTreeItem.handle) {
            itemsToRefresh.push(currentTreeItem);
          } else {
            this.a.delete(newTreeItemHandle);
            this.a.set(currentTreeItem.handle, currentTreeItem);
            const parent = newTreeItem.parentHandle ? this.a.get(newTreeItem.parentHandle) : null;
            if (parent) {
              itemsToRefresh.push(parent);
            }
          }
        }
      }
    }
    return { items: itemsToRefresh, checkboxes: checkboxesToRefresh };
  }
  getItem(treeItemHandle) {
    return this.a.get(treeItemHandle);
  }
  isEmpty() {
    return this.a.size === 0;
  }
  async g(elementGroups) {
    if (elementGroups === void 0) {
      return void 0;
    }
    const resultGroups = [];
    const hasResolve = await this.b;
    if (elementGroups) {
      for (const elements of elementGroups) {
        const result = [];
        resultGroups.push(result);
        if (!elements) {
          continue;
        }
        for (const element of elements) {
          const resolvable = new $_M(element, hasResolve ? (token) => {
            return this.d.$resolve(this.c, element.handle, token);
          } : void 0);
          this.a.set(element.handle, resolvable);
          result.push(resolvable);
        }
      }
    }
    return resultGroups;
  }
  h(current, treeItem) {
    treeItem.children = treeItem.children ? treeItem.children : void 0;
    if (current) {
      const properties = $Rb([
        ...Object.keys(current instanceof $_M ? current.asTreeItem() : current),
        ...Object.keys(treeItem)
      ]);
      for (const property of properties) {
        current[property] = treeItem[property];
      }
      if (current instanceof $_M) {
        current.resetResolve();
      }
    }
  }
};

// out-build/vs/platform/download/common/download.js
var $6W = $Qk("downloadService");

// out-build/vs/workbench/api/browser/mainThreadDownloadService.js
var $ERb = class $ERb2 extends $3c {
  constructor(extHostContext, a) {
    super();
    this.a = a;
  }
  $download(uri, to) {
    return this.a.download(URI.revive(uri), URI.revive(to));
  }
};
$ERb = __decorate([
  $frb($xT.MainThreadDownloadService),
  __param(1, $6W)
], $ERb);

// out-build/vs/platform/url/common/url.js
var $4y = $Qk("urlService");

// out-build/vs/workbench/services/extensions/browser/extensionUrlHandler.js
var ExtensionUrlBootstrapHandler_1;
var FIVE_MINUTES = 5 * 60 * 1e3;
var THIRTY_SECONDS = 30 * 1e3;
var URL_TO_HANDLE = "extensionUrlHandler.urlToHandle";
var USER_TRUSTED_EXTENSIONS_CONFIGURATION_KEY = "extensions.confirmedUriHandlerExtensionIds";
var USER_TRUSTED_EXTENSIONS_STORAGE_KEY = "extensionUrlHandler.confirmedExtensions";
function isExtensionId(value) {
  return /^[a-z0-9][a-z0-9\-]*\.[a-z0-9][a-z0-9\-]*$/i.test(value);
}
var UserTrustedExtensionIdStorage = class {
  get extensions() {
    const userTrustedExtensionIdsJson = this.a.get(USER_TRUSTED_EXTENSIONS_STORAGE_KEY, 0, "[]");
    try {
      return JSON.parse(userTrustedExtensionIdsJson);
    } catch {
      return [];
    }
  }
  constructor(a) {
    this.a = a;
  }
  has(id2) {
    return this.extensions.indexOf(id2) > -1;
  }
  add(id2) {
    this.set([...this.extensions, id2]);
  }
  set(ids) {
    this.a.store(
      USER_TRUSTED_EXTENSIONS_STORAGE_KEY,
      JSON.stringify(ids),
      0,
      1
      /* StorageTarget.MACHINE */
    );
  }
};
var $FRb = $Qk("extensionUrlHandler");
var ExtensionUrlHandler = class ExtensionUrlHandler2 {
  constructor(urlService, e, f, g, h3, i2, j, k, l, m, n) {
    this.e = e;
    this.f = f;
    this.g = g;
    this.h = h3;
    this.i = i2;
    this.j = j;
    this.k = k;
    this.l = l;
    this.m = m;
    this.n = n;
    this.a = /* @__PURE__ */ new Map();
    this.b = /* @__PURE__ */ new Map();
    this.c = new UserTrustedExtensionIdStorage(i2);
    const interval = $kj($Y, () => this.q(), THIRTY_SECONDS);
    const urlToHandleValue = this.i.get(
      URL_TO_HANDLE,
      1
      /* StorageScope.WORKSPACE */
    );
    if (urlToHandleValue) {
      this.i.remove(
        URL_TO_HANDLE,
        1
        /* StorageScope.WORKSPACE */
      );
      this.handleURL(URI.revive(JSON.parse(urlToHandleValue)), { trusted: true });
    }
    this.d = $Zc(urlService.registerHandler(this), interval);
    const cache2 = ExtensionUrlBootstrapHandler.cache;
    setTimeout(() => cache2.forEach(([uri, option]) => this.handleURL(uri, option)));
  }
  async handleURL(uri, options3) {
    if (!isExtensionId(uri.authority)) {
      return false;
    }
    const extensionId = uri.authority;
    this.k.publicLog2("uri_invoked/start", { extensionId });
    const initialHandler = this.a.get($5z.toKey(extensionId));
    let extensionDisplayName;
    if (!initialHandler) {
      const extension = await this.e.getExtension(extensionId);
      if (!extension) {
        await this.p(uri, extensionId, options3);
        return true;
      } else {
        extensionDisplayName = extension.displayName ?? "";
      }
    } else {
      extensionDisplayName = initialHandler.extensionDisplayName;
    }
    const trusted = options3?.trusted || this.m.trustedExtensionProtocolHandlers?.includes(extensionId) || this.r($5z.toKey(extensionId));
    if (!trusted) {
      let uriString = uri.toString(false);
      if (uriString.length > 40) {
        uriString = `${uriString.substring(0, 30)}...${uriString.substring(uriString.length - 5)}`;
      }
      const result = await this.f.confirm({
        message: localize(12783, null, extensionDisplayName),
        checkbox: {
          label: localize(12784, null)
        },
        detail: uriString,
        primaryButton: localize(12785, null)
      });
      if (!result.confirmed) {
        this.k.publicLog2("uri_invoked/cancel", { extensionId });
        return true;
      }
      if (result.checkboxChecked) {
        this.c.add($5z.toKey(extensionId));
      }
    }
    const handler = this.a.get($5z.toKey(extensionId));
    if (handler) {
      if (!initialHandler) {
        return await this.o(extensionId, handler, uri, options3);
      }
      return false;
    }
    const timestamp = (/* @__PURE__ */ new Date()).getTime();
    let uris = this.b.get($5z.toKey(extensionId));
    if (!uris) {
      uris = [];
      this.b.set($5z.toKey(extensionId), uris);
    }
    uris.push({ timestamp, uri });
    await this.e.activateByEvent(
      `onUri:${$5z.toKey(extensionId)}`,
      1
      /* ActivationKind.Immediate */
    );
    return true;
  }
  registerExtensionHandler(extensionId, handler) {
    this.a.set($5z.toKey(extensionId), handler);
    const uris = this.b.get($5z.toKey(extensionId)) || [];
    for (const { uri } of uris) {
      this.o(extensionId, handler, uri);
    }
    this.b.delete($5z.toKey(extensionId));
  }
  unregisterExtensionHandler(extensionId) {
    this.a.delete($5z.toKey(extensionId));
  }
  async o(extensionId, handler, uri, options3) {
    this.k.publicLog2("uri_invoked/end", { extensionId: $5z.toKey(extensionId) });
    return await handler.handleURL(uri, options3);
  }
  async p(uri, extensionId, options3) {
    this.k.publicLog2("uri_invoked/install_extension/start", { extensionId });
    try {
      await this.g.executeCommand("workbench.extensions.installExtension", extensionId, {
        justification: {
          reason: `${localize(12786, null)}
${uri.toString()}`,
          action: localize(12787, null)
        },
        enable: true
      });
      this.k.publicLog2("uri_invoked/install_extension/accept", { extensionId });
    } catch (error) {
      if ($kb(error)) {
        this.k.publicLog2("uri_invoked/install_extension/cancel", { extensionId });
      } else {
        this.k.publicLog2("uri_invoked/install_extension/error", { extensionId });
        this.l.error(error);
      }
      return;
    }
    const extension = await this.e.getExtension(extensionId);
    if (extension) {
      await this.handleURL(uri, { ...options3, trusted: true });
    } else {
      this.k.publicLog2("uri_invoked/install_extension/reload", { extensionId, isRemote: !!this.n.remoteAuthority });
      const result = await this.f.confirm({
        message: localize(12788, null, extensionId),
        primaryButton: localize(12789, null)
      });
      if (!result.confirmed) {
        return;
      }
      this.i.store(
        URL_TO_HANDLE,
        JSON.stringify(uri.toJSON()),
        1,
        1
        /* StorageTarget.MACHINE */
      );
      await this.h.reload();
    }
  }
  // forget about all uris buffered more than 5 minutes ago
  q() {
    const now = (/* @__PURE__ */ new Date()).getTime();
    const uriBuffer = /* @__PURE__ */ new Map();
    this.b.forEach((uris, extensionId) => {
      uris = uris.filter(({ timestamp }) => now - timestamp < FIVE_MINUTES);
      if (uris.length > 0) {
        uriBuffer.set(extensionId, uris);
      }
    });
    this.b = uriBuffer;
  }
  r(id2) {
    if (this.c.has(id2)) {
      return true;
    }
    return this.s().indexOf(id2) > -1;
  }
  s() {
    const trustedExtensionIds = this.j.getValue(USER_TRUSTED_EXTENSIONS_CONFIGURATION_KEY);
    if (!Array.isArray(trustedExtensionIds)) {
      return [];
    }
    return trustedExtensionIds;
  }
  dispose() {
    this.d.dispose();
    this.a.clear();
    this.b.clear();
  }
};
ExtensionUrlHandler = __decorate([
  __param(0, $4y),
  __param(1, $wN),
  __param(2, $Yv),
  __param(3, $sn),
  __param(4, $S4),
  __param(5, $jv),
  __param(6, $kl),
  __param(7, $zv),
  __param(8, $PJ),
  __param(9, $Vu),
  __param(10, $US)
], ExtensionUrlHandler);
$SC(
  $FRb,
  ExtensionUrlHandler,
  0
  /* InstantiationType.Eager */
);
var ExtensionUrlBootstrapHandler = class ExtensionUrlBootstrapHandler2 {
  static {
    ExtensionUrlBootstrapHandler_1 = this;
  }
  static {
    this.ID = "workbench.contrib.extensionUrlBootstrapHandler";
  }
  static {
    this.a = [];
  }
  static get cache() {
    ExtensionUrlBootstrapHandler_1.b.dispose();
    const result = ExtensionUrlBootstrapHandler_1.a;
    ExtensionUrlBootstrapHandler_1.a = [];
    return result;
  }
  constructor(urlService) {
    ExtensionUrlBootstrapHandler_1.b = urlService.registerHandler(this);
  }
  async handleURL(uri, options3) {
    if (!isExtensionId(uri.authority)) {
      return false;
    }
    ExtensionUrlBootstrapHandler_1.a.push([uri, options3]);
    return true;
  }
};
ExtensionUrlBootstrapHandler = ExtensionUrlBootstrapHandler_1 = __decorate([
  __param(0, $4y)
], ExtensionUrlBootstrapHandler);
$PL(
  ExtensionUrlBootstrapHandler.ID,
  ExtensionUrlBootstrapHandler,
  2
  /* WorkbenchPhase.BlockRestore */
);
var ManageAuthorizedExtensionURIsAction = class extends $gJ {
  constructor() {
    super({
      id: "workbench.extensions.action.manageAuthorizedExtensionURIs",
      title: localize2(12791, "Manage Authorized Extension URIs..."),
      category: localize2(12792, "Extensions"),
      menu: {
        id: $bJ.CommandPalette,
        when: $veb.toNegated()
      }
    });
  }
  async run(accessor) {
    const storageService = accessor.get($jv);
    const quickInputService = accessor.get($1M);
    const storage = new UserTrustedExtensionIdStorage(storageService);
    const items = storage.extensions.map((label3) => ({ label: label3, picked: true }));
    if (items.length === 0) {
      await quickInputService.pick([{ label: localize(12790, null) }]);
      return;
    }
    const result = await quickInputService.pick(items, { canPickMany: true });
    if (!result) {
      return;
    }
    storage.set(result.map((item) => item.label));
  }
};
$hJ(ManageAuthorizedExtensionURIsAction);

// out-build/vs/workbench/api/browser/mainThreadUrls.js
var ExtensionUrlHandler3 = class {
  constructor(a, b, extensionId, extensionDisplayName) {
    this.a = a;
    this.b = b;
    this.extensionId = extensionId;
    this.extensionDisplayName = extensionDisplayName;
  }
  handleURL(uri, options3) {
    if (!$5z.equals(this.extensionId, uri.authority)) {
      return Promise.resolve(false);
    }
    return Promise.resolve(this.a.$handleExternalUri(this.b, uri)).then(() => true);
  }
};
var $GRb = class $GRb2 {
  constructor(context, c, d) {
    this.c = c;
    this.d = d;
    this.b = /* @__PURE__ */ new Map();
    this.a = context.getProxy($yT.ExtHostUrls);
  }
  $registerUriHandler(handle2, extensionId, extensionDisplayName) {
    const handler = new ExtensionUrlHandler3(this.a, handle2, extensionId, extensionDisplayName);
    const disposable = this.c.registerHandler(handler);
    this.b.set(handle2, { extensionId, disposable });
    this.d.registerExtensionHandler(extensionId, handler);
    return Promise.resolve(void 0);
  }
  $unregisterUriHandler(handle2) {
    const tuple = this.b.get(handle2);
    if (!tuple) {
      return Promise.resolve(void 0);
    }
    const { extensionId, disposable } = tuple;
    this.d.unregisterExtensionHandler(extensionId);
    this.b.delete(handle2);
    disposable.dispose();
    return Promise.resolve(void 0);
  }
  async $createAppUri(uri) {
    return this.c.create(uri);
  }
  dispose() {
    this.b.forEach(({ disposable }) => disposable.dispose());
    this.b.clear();
  }
};
$GRb = __decorate([
  $frb($xT.MainThreadUrls),
  __param(1, $4y),
  __param(2, $FRb)
], $GRb);

// out-build/vs/workbench/contrib/externalUriOpener/common/configuration.js
var $HRb = "default";
var $IRb = "workbench.externalUriOpeners";
var externalUriOpenerIdSchemaAddition = {
  type: "string",
  enum: []
};
var exampleUriPatterns = `
- \`https://microsoft.com\`: Matches this specific domain using https
- \`https://microsoft.com:8080\`: Matches this specific domain on this port using https
- \`https://microsoft.com:*\`: Matches this specific domain on any port using https
- \`https://microsoft.com/foo\`: Matches \`https://microsoft.com/foo\` and \`https://microsoft.com/foo/bar\`, but not \`https://microsoft.com/foobar\` or \`https://microsoft.com/bar\`
- \`https://*.microsoft.com\`: Match all domains ending in \`microsoft.com\` using https
- \`microsoft.com\`: Match this specific domain using either http or https
- \`*.microsoft.com\`: Match all domains ending in \`microsoft.com\` using either http or https
- \`http://192.168.0.1\`: Matches this specific IP using http
- \`http://192.168.0.*\`: Matches all IP's with this prefix using http
- \`*\`: Match all domains using either http or https`;
var $JRb = {
  ...$UL,
  properties: {
    [$IRb]: {
      type: "object",
      markdownDescription: localize(7033, null),
      defaultSnippets: [{
        body: {
          "example.com": "$1"
        }
      }],
      additionalProperties: {
        anyOf: [
          {
            type: "string",
            markdownDescription: localize(7034, null, exampleUriPatterns)
          },
          {
            type: "string",
            markdownDescription: localize(7035, null, exampleUriPatterns),
            enum: [$HRb],
            enumDescriptions: [localize(7036, null)]
          },
          externalUriOpenerIdSchemaAddition
        ]
      }
    }
  }
};
function $KRb(enumValues, enumDescriptions) {
  externalUriOpenerIdSchemaAddition.enum = enumValues;
  externalUriOpenerIdSchemaAddition.enumDescriptions = enumDescriptions;
  $Wn.as($Ht.Configuration).notifyConfigurationSchemaUpdated($JRb);
}

// out-build/vs/workbench/contrib/externalUriOpener/common/contributedOpeners.js
var $LRb_1;
var $LRb = class $LRb2 extends $3c {
  static {
    $LRb_1 = this;
  }
  static {
    this.a = "externalUriOpeners";
  }
  constructor(storageService, g) {
    super();
    this.g = g;
    this.b = /* @__PURE__ */ new Map();
    this.c = new $Slb($LRb_1.a, storageService);
    this.f = this.c.getMemento(
      0,
      1
      /* StorageTarget.MACHINE */
    );
    for (const [id2, value] of Object.entries(this.f || {})) {
      this.h(id2, value.extensionId, { isCurrentlyRegistered: false });
    }
    this.j();
    this.B(this.g.onDidChangeExtensions(() => this.j()));
    this.B(this.g.onDidChangeExtensionsStatus(() => this.j()));
  }
  didRegisterOpener(id2, extensionId) {
    this.h(id2, extensionId, {
      isCurrentlyRegistered: true
    });
  }
  h(id2, extensionId, options3) {
    const existing = this.b.get(id2);
    if (existing) {
      existing.isCurrentlyRegistered = existing.isCurrentlyRegistered || options3.isCurrentlyRegistered;
      return;
    }
    const entry = {
      extensionId,
      isCurrentlyRegistered: options3.isCurrentlyRegistered
    };
    this.b.set(id2, entry);
    this.f[id2] = entry;
    this.c.saveMemento();
    this.m();
  }
  delete(id2) {
    this.b.delete(id2);
    delete this.f[id2];
    this.c.saveMemento();
    this.m();
  }
  async j() {
    await this.g.whenInstalledExtensionsRegistered();
    const registeredExtensions = this.g.extensions;
    for (const [id2, entry] of this.b) {
      const extension = registeredExtensions.find((r2) => r2.identifier.value === entry.extensionId);
      if (extension) {
        if (!this.g.canRemoveExtension(extension)) {
          if (!entry.isCurrentlyRegistered) {
            this.delete(id2);
          }
        }
      } else {
        this.delete(id2);
      }
    }
  }
  m() {
    const ids = [];
    const descriptions = [];
    for (const [id2, entry] of this.b) {
      ids.push(id2);
      descriptions.push(entry.extensionId);
    }
    $KRb(ids, descriptions);
  }
};
$LRb = $LRb_1 = __decorate([
  __param(0, $jv),
  __param(1, $wN)
], $LRb);

// out-build/vs/workbench/contrib/externalUriOpener/common/externalUriOpenerService.js
var $MRb = $Qk("externalUriOpenerService");
var $NRb = class $NRb2 extends $3c {
  constructor(openerService, b, c, f, g) {
    super();
    this.b = b;
    this.c = c;
    this.f = f;
    this.g = g;
    this.a = new $cd();
    this.B(openerService.registerExternalOpener(this));
  }
  registerExternalOpenerProvider(provider) {
    const remove = this.a.push(provider);
    return { dispose: remove };
  }
  async h(targetUri, allowOptional, ctx, token) {
    const allOpeners = await this.j(targetUri);
    if (allOpeners.size === 0) {
      return [];
    }
    if (ctx.preferredOpenerId) {
      if (ctx.preferredOpenerId === $HRb) {
        return [];
      }
      const preferredOpener = allOpeners.get(ctx.preferredOpenerId);
      if (preferredOpener) {
        return [preferredOpener];
      }
    }
    const configuredOpener = this.m(allOpeners, targetUri);
    if (configuredOpener) {
      return configuredOpener === $HRb ? [] : [configuredOpener];
    }
    const validOpeners = [];
    await Promise.all(Array.from(allOpeners.values()).map(async (opener) => {
      let priority;
      try {
        priority = await opener.canOpen(ctx.sourceUri, token);
      } catch (e) {
        this.c.error(e);
        return;
      }
      switch (priority) {
        case ExternalUriOpenerPriority.Option:
        case ExternalUriOpenerPriority.Default:
        case ExternalUriOpenerPriority.Preferred:
          validOpeners.push({ opener, priority });
          break;
      }
    }));
    if (validOpeners.length === 0) {
      return [];
    }
    const preferred = validOpeners.filter((x) => x.priority === ExternalUriOpenerPriority.Preferred).at(0);
    if (preferred) {
      return [preferred.opener];
    }
    if (!allowOptional && validOpeners.every((x) => x.priority === ExternalUriOpenerPriority.Option)) {
      return [];
    }
    return validOpeners.map((value) => value.opener);
  }
  async openExternal(href, ctx, token) {
    const targetUri = typeof href === "string" ? URI.parse(href) : href;
    const allOpeners = await this.h(targetUri, false, ctx, token);
    if (allOpeners.length === 0) {
      return false;
    } else if (allOpeners.length === 1) {
      return allOpeners[0].openExternalUri(targetUri, ctx, token);
    }
    return this.n(allOpeners, targetUri, ctx, token);
  }
  async getOpener(targetUri, ctx, token) {
    const allOpeners = await this.h(targetUri, true, ctx, token);
    if (allOpeners.length >= 1) {
      return allOpeners[0];
    }
    return void 0;
  }
  async j(targetUri) {
    const allOpeners = /* @__PURE__ */ new Map();
    await Promise.all(Iterable.map(this.a, async (provider) => {
      for await (const opener of provider.getOpeners(targetUri)) {
        allOpeners.set(opener.id, opener);
      }
    }));
    return allOpeners;
  }
  m(openers, targetUri) {
    const config = this.b.getValue($IRb) || {};
    for (const [uriGlob, id2] of Object.entries(config)) {
      if ($eNb(targetUri, uriGlob)) {
        if (id2 === $HRb) {
          return "default";
        }
        const entry = openers.get(id2);
        if (entry) {
          return entry;
        }
      }
    }
    return void 0;
  }
  async n(openers, targetUri, ctx, token) {
    const items = openers.map((opener) => {
      return {
        label: opener.label,
        opener
      };
    });
    items.push({
      label: $r ? localize(7037, null) : localize(7038, null),
      opener: void 0
    }, { type: "separator" }, {
      label: localize(7039, null),
      opener: "configureDefault"
    });
    const picked = await this.g.pick(items, {
      placeHolder: localize(7040, null, targetUri.toString())
    });
    if (!picked) {
      return true;
    }
    if (typeof picked.opener === "undefined") {
      return false;
    } else if (picked.opener === "configureDefault") {
      await this.f.openUserSettings({
        jsonEditor: true,
        revealSetting: { key: $IRb, edit: true }
      });
      return true;
    } else {
      return picked.opener.openExternalUri(targetUri, ctx, token);
    }
  }
};
$NRb = __decorate([
  __param(0, $O4),
  __param(1, $kl),
  __param(2, $wn),
  __param(3, $TK),
  __param(4, $1M)
], $NRb);

// out-build/vs/workbench/api/browser/mainThreadUriOpeners.js
var $ORb = class $ORb2 extends $3c {
  constructor(context, storageService, externalUriOpenerService, f, g, h3) {
    super();
    this.f = f;
    this.g = g;
    this.h = h3;
    this.b = /* @__PURE__ */ new Map();
    this.a = context.getProxy($yT.ExtHostUriOpeners);
    this.B(externalUriOpenerService.registerExternalOpenerProvider(this));
    this.c = this.B(new $LRb(storageService, f));
  }
  async *getOpeners(targetUri) {
    if (targetUri.scheme !== Schemas.http && targetUri.scheme !== Schemas.https) {
      return;
    }
    await this.f.activateByEvent(`onOpenExternalUri:${targetUri.scheme}`);
    for (const [id2, openerMetadata] of this.b) {
      if (openerMetadata.schemes.has(targetUri.scheme)) {
        yield this.j(id2, openerMetadata);
      }
    }
  }
  j(id2, metadata) {
    return {
      id: id2,
      label: metadata.label,
      canOpen: (uri, token) => {
        return this.a.$canOpenUri(id2, uri, token);
      },
      openExternalUri: async (uri, ctx, token) => {
        try {
          await this.a.$openUri(id2, { resolvedUri: uri, sourceUri: ctx.sourceUri }, token);
        } catch (e) {
          if (!$kb(e)) {
            const openDefaultAction = new $Um("default", localize(2629, null), void 0, void 0, async () => {
              await this.g.open(uri, {
                allowTunneling: false,
                allowContributedOpeners: $HRb
              });
            });
            openDefaultAction.tooltip = uri.toString();
            this.h.notify({
              severity: Severity2.Error,
              message: localize(2630, null, id2, e.toString()),
              actions: {
                primary: [
                  openDefaultAction
                ]
              }
            });
          }
        }
        return true;
      }
    };
  }
  async $registerUriOpener(id2, schemes, extensionId, label3) {
    if (this.b.has(id2)) {
      throw new Error(`Opener with id '${id2}' already registered`);
    }
    this.b.set(id2, {
      schemes: new Set(schemes),
      label: label3,
      extensionId
    });
    this.c.didRegisterOpener(id2, extensionId.value);
  }
  async $unregisterUriOpener(id2) {
    this.b.delete(id2);
    this.c.delete(id2);
  }
  dispose() {
    super.dispose();
    this.b.clear();
  }
};
$ORb = __decorate([
  $frb($xT.MainThreadUriOpeners),
  __param(1, $jv),
  __param(2, $MRb),
  __param(3, $wN),
  __param(4, $O4),
  __param(5, $PJ)
], $ORb);

// out-build/vs/workbench/services/userActivity/common/userActivityRegistry.js
var UserActivityRegistry = class {
  constructor() {
    this.a = [];
    this.add = (ctor) => {
      this.a.push(ctor);
    };
  }
  take(userActivityService, instantiation) {
    this.add = (ctor) => instantiation.createInstance(ctor, userActivityService);
    this.a.forEach(this.add);
    this.a = [];
  }
};
var $PRb = new UserActivityRegistry();

// out-build/vs/workbench/services/userActivity/common/userActivityService.js
var MARK_INACTIVE_DEBOUNCE = 1e4;
var $QRb = $Qk("IUserActivityService");
var $RRb = class $RRb2 extends $3c {
  constructor(instantiationService) {
    super();
    this.a = this.B(new $8h(() => {
      this.isActive = false;
      this.b.fire(false);
    }, MARK_INACTIVE_DEBOUNCE));
    this.b = this.B(new $ze());
    this.c = 0;
    this.isActive = true;
    this.onDidChangeIsActive = this.b.event;
    this.B($_h(() => $PRb.take(this, instantiationService)));
  }
  /** @inheritdoc */
  markActive(opts) {
    if (opts?.whenHeldFor) {
      const store = new $2c();
      store.add($Xh(() => store.add(this.markActive()), opts.whenHeldFor));
      return store;
    }
    if (++this.c === 1) {
      this.isActive = true;
      this.b.fire(true);
      this.a.cancel();
    }
    return $1c(() => {
      if (--this.c === 0) {
        this.a.schedule();
      }
    });
  }
};
$RRb = __decorate([
  __param(0, $Pk)
], $RRb);
$SC(
  $QRb,
  $RRb,
  1
  /* InstantiationType.Delayed */
);

// out-build/vs/workbench/api/browser/mainThreadWindow.js
var $SRb = class $SRb2 {
  constructor(extHostContext, c, d, e) {
    this.c = c;
    this.d = d;
    this.e = e;
    this.b = new $2c();
    this.a = extHostContext.getProxy($yT.ExtHostWindow);
    Event2.latch(c.onDidChangeFocus)(this.a.$onDidChangeWindowFocus, this.a, this.b);
    e.onDidChangeIsActive(this.a.$onDidChangeWindowActive, this.a, this.b);
    this.registerNativeHandle();
  }
  dispose() {
    this.b.dispose();
  }
  registerNativeHandle() {
    Event2.latch(this.c.onDidChangeActiveWindow)(async (windowId) => {
      const handle2 = await this.c.getNativeWindowHandle(windowId);
      this.a.$onDidChangeActiveNativeWindowHandle(handle2 ? $Wi(handle2) : void 0);
    }, this, this.b);
  }
  $getInitialState() {
    return Promise.resolve({
      isFocused: this.c.hasFocus,
      isActive: this.e.isActive
    });
  }
  async $openUri(uriComponents, uriString, options3) {
    const uri = URI.from(uriComponents);
    let target;
    if (uriString && URI.parse(uriString).toString() === uri.toString()) {
      target = uriString;
    } else {
      target = uri;
    }
    return this.d.open(target, {
      openExternal: true,
      allowTunneling: options3.allowTunneling,
      allowContributedOpeners: options3.allowContributedOpeners
    });
  }
  async $asExternalUri(uriComponents, options3) {
    const result = await this.d.resolveExternalUri(URI.revive(uriComponents), options3);
    return result.resolved;
  }
};
$SRb = __decorate([
  $frb($xT.MainThreadWindow),
  __param(1, $S4),
  __param(2, $O4),
  __param(3, $QRb)
], $SRb);

// out-build/vs/workbench/contrib/customEditor/common/customTextEditorModel.js
var $1Rb_1;
var $1Rb = $1Rb_1 = class $1Rb2 extends $3c {
  static async create(instantiationService, viewType, resource) {
    return instantiationService.invokeFunction(async (accessor) => {
      const textModelResolverService = accessor.get($oG);
      const model = await textModelResolverService.createModelReference(resource);
      return instantiationService.createInstance($1Rb_1, viewType, resource, model);
    });
  }
  constructor(viewType, f, g, h3, j, extensionService) {
    super();
    this.viewType = viewType;
    this.f = f;
    this.g = g;
    this.h = h3;
    this.j = j;
    this.b = this.B(new $ze());
    this.onDidChangeOrphaned = this.b.event;
    this.c = this.B(new $ze());
    this.onDidChangeReadonly = this.c.event;
    this.m = this.B(new $ze());
    this.onDidChangeDirty = this.m.event;
    this.n = this.B(new $ze());
    this.onDidChangeContent = this.n.event;
    this.B(g);
    this.a = this.h.files.get(f);
    if (this.a) {
      this.B(this.a.onDidChangeOrphaned(() => this.b.fire()));
      this.B(this.a.onDidChangeReadonly(() => this.c.fire()));
    }
    this.B(this.h.files.onDidChangeDirty((e) => {
      if ($oh(this.resource, e.resource)) {
        this.m.fire();
        this.n.fire();
      }
    }));
    this.B(extensionService.onWillStop((e) => {
      e.veto(true, localize(5463, null, this.resource.path));
    }));
  }
  get resource() {
    return this.f;
  }
  get name() {
    return $rc(this.j.getUriLabel(this.f));
  }
  isReadonly() {
    return this.g.object.isReadonly();
  }
  get backupId() {
    return void 0;
  }
  get canHotExit() {
    return true;
  }
  isDirty() {
    return this.h.isDirty(this.resource);
  }
  isOrphaned() {
    return !!this.a?.hasState(
      4
      /* TextFileEditorModelState.ORPHAN */
    );
  }
  async revert(options3) {
    return this.h.revert(this.resource, options3);
  }
  saveCustomEditor(options3) {
    return this.h.save(this.resource, options3);
  }
  async saveCustomEditorAs(resource, targetResource, options3) {
    return !!await this.h.saveAs(resource, targetResource, options3);
  }
};
$1Rb = $1Rb_1 = __decorate([
  __param(3, $cK),
  __param(4, $ZI),
  __param(5, $wN)
], $1Rb);

// out-build/vs/workbench/services/workingCopy/common/resourceWorkingCopy.js
var $9J = class $9J2 extends $3c {
  constructor(resource, a) {
    super();
    this.resource = resource;
    this.a = a;
    this.b = this.B(new $ze());
    this.onDidChangeOrphaned = this.b.event;
    this.c = false;
    this.h = this.B(new $ze());
    this.onWillDispose = this.h.event;
    this.B(this.a.onDidFilesChange((e) => this.f(e)));
  }
  isOrphaned() {
    return this.c;
  }
  async f(e) {
    let fileEventImpactsUs = false;
    let newInOrphanModeGuess;
    if (this.c) {
      const fileWorkingCopyResourceAdded = e.contains(
        this.resource,
        1
        /* FileChangeType.ADDED */
      );
      if (fileWorkingCopyResourceAdded) {
        newInOrphanModeGuess = false;
        fileEventImpactsUs = true;
      }
    } else {
      const fileWorkingCopyResourceDeleted = e.contains(
        this.resource,
        2
        /* FileChangeType.DELETED */
      );
      if (fileWorkingCopyResourceDeleted) {
        newInOrphanModeGuess = true;
        fileEventImpactsUs = true;
      }
    }
    if (fileEventImpactsUs && this.c !== newInOrphanModeGuess) {
      let newInOrphanModeValidated = false;
      if (newInOrphanModeGuess) {
        await $Wh(100, CancellationToken.None);
        if (this.isDisposed()) {
          newInOrphanModeValidated = true;
        } else {
          const exists = await this.a.exists(this.resource);
          newInOrphanModeValidated = !exists;
        }
      }
      if (this.c !== newInOrphanModeValidated && !this.isDisposed()) {
        this.g(newInOrphanModeValidated);
      }
    }
  }
  g(orphaned) {
    if (this.c !== orphaned) {
      this.c = orphaned;
      this.b.fire();
    }
  }
  isDisposed() {
    return this.q.isDisposed;
  }
  dispose() {
    this.c = false;
    this.h.fire();
    super.dispose();
  }
  //#endregion
  //#region Modified Tracking
  isModified() {
    return this.isDirty();
  }
};
$9J = __decorate([
  __param(1, $km)
], $9J);

// out-build/vs/workbench/api/browser/mainThreadCustomEditors.js
var MainThreadCustomEditorModel_1;
var CustomEditorModelType;
(function(CustomEditorModelType2) {
  CustomEditorModelType2[CustomEditorModelType2["Custom"] = 0] = "Custom";
  CustomEditorModelType2[CustomEditorModelType2["Text"] = 1] = "Text";
})(CustomEditorModelType || (CustomEditorModelType = {}));
var $2Rb = class $2Rb2 extends $3c {
  constructor(context, g, h3, extensionService, storageService, workingCopyService, workingCopyFileService, j, m, n, r2, s) {
    super();
    this.g = g;
    this.h = h3;
    this.j = j;
    this.m = m;
    this.n = n;
    this.r = r2;
    this.s = s;
    this.b = this.B(new $_c());
    this.c = /* @__PURE__ */ new Map();
    this.f = new $Frb("mainThreadCustomEditors.origins", storageService);
    this.a = context.getProxy($yT.ExtHostCustomEditors);
    this.B(workingCopyFileService.registerWorkingCopyProvider((editorResource) => {
      const matchedWorkingCopies = [];
      for (const workingCopy of workingCopyService.workingCopies) {
        if (workingCopy instanceof MainThreadCustomEditorModel) {
          if ($ph(editorResource, workingCopy.editorResource)) {
            matchedWorkingCopies.push(workingCopy);
          }
        }
      }
      return matchedWorkingCopies;
    }));
    this.B(s.registerResolver({
      canResolve: (webview) => {
        if (webview instanceof $VOb) {
          extensionService.activateByEvent(`onCustomEditor:${webview.viewType}`);
        }
        return false;
      },
      resolveWebview: () => {
        throw new Error("not implemented");
      }
    }));
    this.B(workingCopyFileService.onWillRunWorkingCopyFileOperation(async (e) => this.y(e)));
  }
  $registerTextEditorProvider(extensionData, viewType, options3, capabilities, serializeBuffersForPostMessage) {
    this.t(1, $nOb(extensionData), viewType, options3, capabilities, true, serializeBuffersForPostMessage);
  }
  $registerCustomEditorProvider(extensionData, viewType, options3, supportsMultipleEditorsPerDocument, serializeBuffersForPostMessage) {
    this.t(0, $nOb(extensionData), viewType, options3, {}, supportsMultipleEditorsPerDocument, serializeBuffersForPostMessage);
  }
  t(modelType, extension, viewType, options3, capabilities, supportsMultipleEditorsPerDocument, serializeBuffersForPostMessage) {
    if (this.b.has(viewType)) {
      throw new Error(`Provider for ${viewType} already registered`);
    }
    const disposables = new $2c();
    disposables.add(this.j.registerCustomEditorCapabilities(viewType, {
      supportsMultipleEditorsPerDocument
    }));
    disposables.add(this.s.registerResolver({
      canResolve: (webviewInput) => {
        return webviewInput instanceof $VOb && webviewInput.viewType === viewType;
      },
      resolveWebview: async (webviewInput, cancellation) => {
        const handle2 = $ps();
        const resource = webviewInput.resource;
        webviewInput.webview.origin = this.f.getOrigin(viewType, extension.id);
        this.h.addWebviewInput(handle2, webviewInput, { serializeBuffersForPostMessage });
        webviewInput.webview.options = options3;
        webviewInput.webview.extension = extension;
        let backupId = webviewInput.backupId;
        if (webviewInput.oldResource && !webviewInput.backupId) {
          const backup = this.c.get(webviewInput.oldResource.toString());
          backupId = backup?.backupId;
          this.c.delete(webviewInput.oldResource.toString());
        }
        let modelRef;
        try {
          modelRef = await this.u(modelType, resource, viewType, { backupId }, cancellation);
        } catch (error) {
          $gb(error);
          webviewInput.webview.setHtml(this.g.getWebviewResolvedFailedContent(viewType));
          return;
        }
        if (cancellation.isCancellationRequested) {
          modelRef.dispose();
          return;
        }
        webviewInput.webview.onDidDispose(() => {
          if (modelRef.object.isDirty()) {
            const sub = modelRef.object.onDidChangeDirty(() => {
              if (!modelRef.object.isDirty()) {
                sub.dispose();
                modelRef.dispose();
              }
            });
            return;
          }
          modelRef.dispose();
        });
        if (capabilities.supportsMove) {
          webviewInput.onMove(async (newResource) => {
            const oldModel = modelRef;
            modelRef = await this.u(modelType, newResource, viewType, {}, CancellationToken.None);
            this.a.$onMoveCustomEditor(handle2, newResource, viewType);
            oldModel.dispose();
          });
        }
        try {
          await this.a.$resolveCustomEditor(resource, handle2, viewType, {
            title: webviewInput.getTitle(),
            contentOptions: webviewInput.webview.contentOptions,
            options: webviewInput.webview.options,
            active: webviewInput === this.n.activeEditor
          }, $AS(this.m, webviewInput.group || 0), cancellation);
        } catch (error) {
          $gb(error);
          webviewInput.webview.setHtml(this.g.getWebviewResolvedFailedContent(viewType));
          modelRef.dispose();
          return;
        }
      }
    }));
    this.b.set(viewType, disposables);
  }
  $unregisterEditorProvider(viewType) {
    if (!this.b.has(viewType)) {
      throw new Error(`No provider for ${viewType} registered`);
    }
    this.b.deleteAndDispose(viewType);
    this.j.models.disposeAllModelsForView(viewType);
  }
  async u(modelType, resource, viewType, options3, cancellation) {
    const existingModel = this.j.models.tryRetain(resource, viewType);
    if (existingModel) {
      return existingModel;
    }
    switch (modelType) {
      case 1: {
        const model = $1Rb.create(this.r, viewType, resource);
        return this.j.models.add(resource, viewType, model);
      }
      case 0: {
        const model = MainThreadCustomEditorModel.create(this.r, this.a, viewType, resource, options3, () => {
          return Array.from(this.h.webviewInputs).filter((editor) => editor instanceof $VOb && $oh(editor.resource, resource));
        }, cancellation);
        return this.j.models.add(resource, viewType, model);
      }
    }
  }
  async $onDidEdit(resourceComponents, viewType, editId, label3) {
    const model = await this.w(resourceComponents, viewType);
    model.pushEdit(editId, label3);
  }
  async $onContentChange(resourceComponents, viewType) {
    const model = await this.w(resourceComponents, viewType);
    model.changeContent();
  }
  async w(resourceComponents, viewType) {
    const resource = URI.revive(resourceComponents);
    const model = await this.j.models.get(resource, viewType);
    if (!model || !(model instanceof MainThreadCustomEditorModel)) {
      throw new Error("Could not find model for webview editor");
    }
    return model;
  }
  //#region Working Copy
  async y(e) {
    if (e.operation !== 2) {
      return;
    }
    e.waitUntil((async () => {
      const models = [];
      for (const file of e.files) {
        if (file.source) {
          models.push(...await this.j.models.getAllModels(file.source));
        }
      }
      for (const model of models) {
        if (model instanceof MainThreadCustomEditorModel && model.isDirty()) {
          const workingCopy = await model.backup(CancellationToken.None);
          if (workingCopy.meta) {
            this.c.set(model.editorResource.toString(), workingCopy.meta);
          }
        }
      }
    })());
  }
};
$2Rb = __decorate([
  __param(3, $wN),
  __param(4, $jv),
  __param(5, $XI),
  __param(6, $aK),
  __param(7, $LOb),
  __param(8, $iJ),
  __param(9, $mJ),
  __param(10, $Pk),
  __param(11, $SOb)
], $2Rb);
var HotExitState;
(function(HotExitState2) {
  let Type4;
  (function(Type5) {
    Type5[Type5["Allowed"] = 0] = "Allowed";
    Type5[Type5["NotAllowed"] = 1] = "NotAllowed";
    Type5[Type5["Pending"] = 2] = "Pending";
  })(Type4 = HotExitState2.Type || (HotExitState2.Type = {}));
  HotExitState2.Allowed = Object.freeze({
    type: 0
    /* Type.Allowed */
  });
  HotExitState2.NotAllowed = Object.freeze({
    type: 1
    /* Type.NotAllowed */
  });
  class Pending {
    constructor(operation) {
      this.operation = operation;
      this.type = 2;
    }
  }
  HotExitState2.Pending = Pending;
})(HotExitState || (HotExitState = {}));
var MainThreadCustomEditorModel = MainThreadCustomEditorModel_1 = class MainThreadCustomEditorModel2 extends $9J {
  static async create(instantiationService, proxy, viewType, resource, options3, getEditors, cancellation) {
    const editors = getEditors();
    let untitledDocumentData;
    if (editors.length !== 0) {
      untitledDocumentData = editors[0].untitledDocumentData;
    }
    const { editable } = await proxy.$createCustomDocument(resource, viewType, options3.backupId, untitledDocumentData, cancellation);
    return instantiationService.createInstance(MainThreadCustomEditorModel_1, proxy, viewType, resource, !!options3.backupId, editable, !!untitledDocumentData, getEditors);
  }
  constructor(y, z, C, fromBackup, D, startDirty, F, G, fileService, H, I, J, workingCopyService, L, extensionService) {
    super(MainThreadCustomEditorModel_1.M(z, C), fileService);
    this.y = y;
    this.z = z;
    this.C = C;
    this.D = D;
    this.F = F;
    this.G = G;
    this.H = H;
    this.I = I;
    this.J = J;
    this.L = L;
    this.j = false;
    this.m = HotExitState.Allowed;
    this.r = -1;
    this.s = -1;
    this.t = [];
    this.u = false;
    this.typeId = $qG;
    this.O = this.B(new $ze());
    this.onDidChangeDirty = this.O.event;
    this.P = this.B(new $ze());
    this.onDidChangeContent = this.P.event;
    this.Q = this.B(new $ze());
    this.onDidSave = this.Q.event;
    this.onDidChangeReadonly = Event2.None;
    this.j = fromBackup;
    if (D) {
      this.B(workingCopyService.registerWorkingCopy(this));
      this.B(extensionService.onWillStop((e) => {
        e.veto(true, localize(2581, null, this.name));
      }));
    }
    if (startDirty) {
      this.u = true;
    }
  }
  get editorResource() {
    return this.C;
  }
  dispose() {
    if (this.D) {
      this.I.removeElements(this.C);
    }
    this.y.$disposeCustomDocument(this.C, this.z);
    super.dispose();
  }
  //#region IWorkingCopy
  // Make sure each custom editor has a unique resource for backup and edits
  static M(viewType, resource) {
    const authority = viewType.replace(/[^a-z0-9\-_]/gi, "-");
    const path = `/${$xk(resource.with({ query: null, fragment: null }).toString(true))}`;
    return URI.from({
      scheme: Schemas.vscodeCustomEditor,
      authority,
      path,
      query: JSON.stringify(resource.toJSON())
    });
  }
  get name() {
    return $rc(this.H.getUriLabel(this.C));
  }
  get capabilities() {
    return this.N() ? 2 : 0;
  }
  isDirty() {
    if (this.u) {
      return true;
    }
    if (this.t.length > 0) {
      return this.s !== this.r;
    }
    return this.j;
  }
  N() {
    return this.C.scheme === Schemas.untitled;
  }
  //#endregion
  isReadonly() {
    return !this.D;
  }
  get viewType() {
    return this.z;
  }
  get backupId() {
    return this.n;
  }
  pushEdit(editId, label3) {
    if (!this.D) {
      throw new Error("Document is not editable");
    }
    this.W(() => {
      this.U(editId);
      this.r = this.t.length - 1;
    });
    this.I.pushElement({
      type: 0,
      resource: this.C,
      label: label3 ?? localize(2582, null),
      code: "undoredo.customEditorEdit",
      undo: () => this.R(),
      redo: () => this.S()
    });
  }
  changeContent() {
    this.W(() => {
      this.u = true;
    });
  }
  async R() {
    if (!this.D) {
      return;
    }
    if (this.r < 0) {
      return;
    }
    const undoneEdit = this.t[this.r];
    this.W(() => {
      --this.r;
    });
    await this.y.$undo(this.C, this.viewType, undoneEdit, this.isDirty());
  }
  async S() {
    if (!this.D) {
      return;
    }
    if (this.r >= this.t.length - 1) {
      return;
    }
    const redoneEdit = this.t[this.r + 1];
    this.W(() => {
      ++this.r;
    });
    await this.y.$redo(this.C, this.viewType, redoneEdit, this.isDirty());
  }
  U(editToInsert) {
    const start = this.r + 1;
    const toRemove = this.t.length - this.r;
    const removedEdits = typeof editToInsert === "number" ? this.t.splice(start, toRemove, editToInsert) : this.t.splice(start, toRemove);
    if (removedEdits.length) {
      this.y.$disposeEdits(this.C, this.z, removedEdits);
    }
  }
  W(makeEdit) {
    const wasDirty = this.isDirty();
    makeEdit();
    this.P.fire();
    if (this.isDirty() !== wasDirty) {
      this.O.fire();
    }
  }
  async revert(options3) {
    if (!this.D) {
      return;
    }
    if (this.r === this.s && !this.u && !this.j) {
      return;
    }
    if (!options3?.soft) {
      this.y.$revert(this.C, this.viewType, CancellationToken.None);
    }
    this.W(() => {
      this.u = false;
      this.j = false;
      this.r = this.s;
      this.U();
    });
  }
  async save(options3) {
    const result = !!await this.saveCustomEditor(options3);
    if (result) {
      this.Q.fire({ reason: options3?.reason, source: options3?.source });
    }
    return result;
  }
  async saveCustomEditor(options3) {
    if (!this.D) {
      return void 0;
    }
    if (this.N()) {
      const targetUri = await this.X(options3);
      if (!targetUri) {
        return void 0;
      }
      await this.saveCustomEditorAs(this.C, targetUri, options3);
      return targetUri;
    }
    const savePromise = $Hh((token) => this.y.$onSave(this.C, this.viewType, token));
    this.w?.cancel();
    this.w = savePromise;
    try {
      await savePromise;
      if (this.w === savePromise) {
        this.W(() => {
          this.u = false;
          this.s = this.r;
          this.j = false;
        });
      }
    } finally {
      if (this.w === savePromise) {
        this.w = void 0;
      }
    }
    return this.C;
  }
  X(options3) {
    if (!this.N()) {
      throw new Error("Resource is not untitled");
    }
    const remoteAuthority = this.J.remoteAuthority;
    const localResource = $Fh(this.C, remoteAuthority, this.L.defaultUriScheme);
    return this.G.pickFileToSave(localResource, options3?.availableFileSystems);
  }
  async saveCustomEditorAs(resource, targetResource, _options) {
    if (this.D) {
      await $Hh((token) => this.y.$onSaveAs(this.C, this.viewType, targetResource, token));
      this.W(() => {
        this.s = this.r;
      });
      return true;
    } else {
      await this.a.copy(
        resource,
        targetResource,
        false
        /* overwrite */
      );
      return true;
    }
  }
  get canHotExit() {
    return typeof this.n === "string" && this.m.type === 0;
  }
  async backup(token) {
    const editors = this.F();
    if (!editors.length) {
      throw new Error("No editors found for resource, cannot back up");
    }
    const primaryEditor = editors[0];
    const backupMeta = {
      viewType: this.viewType,
      editorResource: this.C,
      backupId: "",
      extension: primaryEditor.extension ? {
        id: primaryEditor.extension.id.value,
        location: primaryEditor.extension.location
      } : void 0,
      webview: {
        origin: primaryEditor.webview.origin,
        options: primaryEditor.webview.options,
        state: primaryEditor.webview.state
      }
    };
    const backupData = {
      meta: backupMeta
    };
    if (!this.D) {
      return backupData;
    }
    if (this.m.type === 2) {
      this.m.operation.cancel();
    }
    const pendingState = new HotExitState.Pending($Hh((token2) => this.y.$backup(this.C.toJSON(), this.viewType, token2)));
    this.m = pendingState;
    token.onCancellationRequested(() => {
      pendingState.operation.cancel();
    });
    let errorMessage = "";
    try {
      const backupId = await pendingState.operation;
      if (this.m === pendingState) {
        this.m = HotExitState.Allowed;
        backupData.meta.backupId = backupId;
        this.n = backupId;
      }
    } catch (e) {
      if ($kb(e)) {
        throw e;
      }
      if (this.m === pendingState) {
        this.m = HotExitState.NotAllowed;
      }
      if (e.message) {
        errorMessage = e.message;
      }
    }
    if (this.m === HotExitState.Allowed) {
      return backupData;
    }
    throw new Error(`Cannot backup in this state: ${errorMessage}`);
  }
};
MainThreadCustomEditorModel = MainThreadCustomEditorModel_1 = __decorate([
  __param(7, $1v),
  __param(8, $km),
  __param(9, $ZI),
  __param(10, $_F),
  __param(11, $US),
  __param(12, $XI),
  __param(13, $aT),
  __param(14, $wN)
], MainThreadCustomEditorModel);

// out-build/vs/workbench/api/browser/mainThreadWebviewPanels.js
var WebviewInputStore = class {
  constructor() {
    this.a = /* @__PURE__ */ new Map();
    this.b = /* @__PURE__ */ new Map();
  }
  add(handle2, input) {
    this.a.set(handle2, input);
    this.b.set(input, handle2);
  }
  getHandleForInput(input) {
    return this.b.get(input);
  }
  getInputForHandle(handle2) {
    return this.a.get(handle2);
  }
  delete(handle2) {
    const input = this.getInputForHandle(handle2);
    this.a.delete(handle2);
    if (input) {
      this.b.delete(input);
    }
  }
  get size() {
    return this.a.size;
  }
  [Symbol.iterator]() {
    return this.a.values();
  }
};
var WebviewViewTypeTransformer = class {
  constructor(prefix) {
    this.prefix = prefix;
  }
  fromExternal(viewType) {
    return this.prefix + viewType;
  }
  toExternal(viewType) {
    return viewType.startsWith(this.prefix) ? viewType.substr(this.prefix.length) : void 0;
  }
};
var $TRb = class $TRb2 extends $3c {
  constructor(context, h3, j, m, n, extensionService, storageService, r2, s) {
    super();
    this.h = h3;
    this.j = j;
    this.m = m;
    this.n = n;
    this.r = r2;
    this.s = s;
    this.a = new WebviewViewTypeTransformer("mainThreadWebview-");
    this.c = new WebviewInputStore();
    this.f = this.B(new $_c());
    this.g = new $Frb("mainThreadWebviewPanel.origins", storageService);
    this.b = context.getProxy($yT.ExtHostWebviewPanels);
    this.B(Event2.any(n.onDidActiveEditorChange, n.onDidVisibleEditorsChange, m.onDidAddGroup, m.onDidRemoveGroup, m.onDidMoveGroup)(() => {
      this.u(this.n.activeEditor);
    }));
    this.B(s.onDidChangeActiveWebviewEditor((input) => {
      this.u(input);
    }));
    this.B(s.registerResolver({
      canResolve: (webview) => {
        const viewType = this.a.toExternal(webview.viewType);
        if (typeof viewType === "string") {
          extensionService.activateByEvent(`onWebviewPanel:${viewType}`);
        }
        return false;
      },
      resolveWebview: () => {
        throw new Error("not implemented");
      }
    }));
  }
  get webviewInputs() {
    return this.c;
  }
  addWebviewInput(handle2, input, options3) {
    this.c.add(handle2, input);
    this.h.addWebview(handle2, input.webview, options3);
    input.webview.onDidDispose(() => {
      this.b.$onDidDisposeWebviewPanel(handle2).finally(() => {
        this.c.delete(handle2);
      });
    });
  }
  $createWebviewPanel(extensionData, handle2, viewType, initData, showOptions) {
    const targetGroup = this.t(showOptions);
    const mainThreadShowOptions = showOptions ? {
      preserveFocus: !!showOptions.preserveFocus,
      group: targetGroup
    } : {};
    const extension = $nOb(extensionData);
    const origin = this.g.getOrigin(viewType, extension.id);
    const webview = this.s.openWebview({
      origin,
      providedViewType: viewType,
      title: initData.title,
      options: reviveWebviewOptions(initData.panelOptions),
      contentOptions: $oOb(initData.webviewOptions),
      extension
    }, this.a.fromExternal(viewType), initData.title, mainThreadShowOptions);
    this.addWebviewInput(handle2, webview, { serializeBuffersForPostMessage: initData.serializeBuffersForPostMessage });
    const payload = {
      extensionId: extension.id.value,
      viewType
    };
    this.r.publicLog2("webviews:createWebviewPanel", payload);
  }
  $disposeWebview(handle2) {
    const webview = this.w(handle2);
    if (!webview) {
      return;
    }
    webview.dispose();
  }
  $setTitle(handle2, value) {
    this.w(handle2)?.setName(value);
  }
  $setIconPath(handle2, value) {
    const webview = this.w(handle2);
    if (webview) {
      webview.iconPath = reviveWebviewIcon(value);
    }
  }
  $reveal(handle2, showOptions) {
    const webview = this.w(handle2);
    if (!webview || webview.isDisposed()) {
      return;
    }
    const targetGroup = this.t(showOptions);
    this.s.revealWebview(webview, targetGroup, !!showOptions.preserveFocus);
  }
  t(showOptions) {
    if (typeof showOptions.viewColumn === "undefined" || showOptions.viewColumn === $nJ || this.m.count === 1 && this.m.activeGroup.isEmpty) {
      return $nJ;
    }
    if (showOptions.viewColumn === $oJ) {
      return $oJ;
    }
    if (showOptions.viewColumn >= 0) {
      const groupInColumn = this.m.getGroups(
        2
        /* GroupsOrder.GRID_APPEARANCE */
      )[showOptions.viewColumn];
      if (groupInColumn) {
        return groupInColumn.id;
      }
      const newGroup = this.m.findGroup({
        location: 1
        /* GroupLocation.LAST */
      });
      if (newGroup) {
        const direction = $lJ(this.j);
        return this.m.addGroup(newGroup, direction);
      }
    }
    return $nJ;
  }
  $registerSerializer(viewType, options3) {
    if (this.f.has(viewType)) {
      throw new Error(`Reviver for ${viewType} already registered`);
    }
    this.f.set(viewType, this.s.registerResolver({
      canResolve: (webviewInput) => {
        return webviewInput.viewType === this.a.fromExternal(viewType);
      },
      resolveWebview: async (webviewInput) => {
        const viewType2 = this.a.toExternal(webviewInput.viewType);
        if (!viewType2) {
          webviewInput.webview.setHtml(this.h.getWebviewResolvedFailedContent(webviewInput.viewType));
          return;
        }
        const handle2 = $ps();
        this.addWebviewInput(handle2, webviewInput, options3);
        let state = void 0;
        if (webviewInput.webview.state) {
          try {
            state = JSON.parse(webviewInput.webview.state);
          } catch (e) {
            console.error("Could not load webview state", e, webviewInput.webview.state);
          }
        }
        try {
          await this.b.$deserializeWebviewPanel(handle2, viewType2, {
            title: webviewInput.getTitle(),
            state,
            panelOptions: webviewInput.webview.options,
            webviewOptions: webviewInput.webview.contentOptions,
            active: webviewInput === this.n.activeEditor
          }, $AS(this.m, webviewInput.group || 0));
        } catch (error) {
          $gb(error);
          webviewInput.webview.setHtml(this.h.getWebviewResolvedFailedContent(viewType2));
        }
      }
    }));
  }
  $unregisterSerializer(viewType) {
    if (!this.f.has(viewType)) {
      throw new Error(`No reviver for ${viewType} registered`);
    }
    this.f.deleteAndDispose(viewType);
  }
  u(activeEditorInput) {
    if (!this.c.size) {
      return;
    }
    const viewStates = {};
    const updateViewStatesForInput = (group2, topLevelInput, editorInput) => {
      if (!(editorInput instanceof $8Lb)) {
        return;
      }
      editorInput.updateGroup(group2.id);
      const handle2 = this.c.getHandleForInput(editorInput);
      if (handle2) {
        viewStates[handle2] = {
          visible: topLevelInput === group2.activeEditor,
          active: editorInput === activeEditorInput,
          position: $AS(this.m, group2.id)
        };
      }
    };
    for (const group2 of this.m.groups) {
      for (const input of group2.editors) {
        if (input instanceof $fub) {
          updateViewStatesForInput(group2, input, input.primary);
          updateViewStatesForInput(group2, input, input.secondary);
        } else {
          updateViewStatesForInput(group2, input, input);
        }
      }
    }
    if (Object.keys(viewStates).length) {
      this.b.$onDidChangeWebviewPanelViewStates(viewStates);
    }
  }
  w(handle2) {
    return this.c.getInputForHandle(handle2);
  }
};
$TRb = __decorate([
  __param(2, $kl),
  __param(3, $iJ),
  __param(4, $mJ),
  __param(5, $wN),
  __param(6, $jv),
  __param(7, $zv),
  __param(8, $SOb)
], $TRb);
function reviveWebviewIcon(value) {
  if (!value) {
    return void 0;
  }
  return {
    light: URI.revive(value.light),
    dark: URI.revive(value.dark)
  };
}
function reviveWebviewOptions(panelOptions) {
  return {
    enableFindWidget: panelOptions.enableFindWidget,
    retainContextWhenHidden: panelOptions.retainContextWhenHidden
  };
}

// out-build/vs/workbench/contrib/webviewView/browser/webviewViewService.js
var $3Rb = $Qk("webviewViewService");
var $4Rb = class extends $3c {
  constructor() {
    super(...arguments);
    this.a = /* @__PURE__ */ new Map();
    this.b = /* @__PURE__ */ new Map();
    this.c = this.B(new $ze());
    this.onNewResolverRegistered = this.c.event;
  }
  register(viewType, resolver) {
    if (this.a.has(viewType)) {
      throw new Error(`View resolver already registered for ${viewType}`);
    }
    this.a.set(viewType, resolver);
    this.c.fire({ viewType });
    const pending = this.b.get(viewType);
    if (pending) {
      resolver.resolve(pending.webview, CancellationToken.None).then(() => {
        this.b.delete(viewType);
        pending.resolve();
      });
    }
    return $1c(() => {
      this.a.delete(viewType);
    });
  }
  resolve(viewType, webview, cancellation) {
    const resolver = this.a.get(viewType);
    if (!resolver) {
      if (this.b.has(viewType)) {
        throw new Error("View already awaiting revival");
      }
      const { promise, resolve } = $Oh();
      this.b.set(viewType, { webview, resolve });
      return promise;
    }
    return resolver.resolve(webview, cancellation);
  }
};

// out-build/vs/workbench/api/browser/mainThreadWebviewViews.js
var $5Rb = class $5Rb2 extends $3c {
  constructor(context, f, g, h3) {
    super();
    this.f = f;
    this.g = g;
    this.h = h3;
    this.b = this.B(new $_c());
    this.c = this.B(new $_c());
    this.a = context.getProxy($yT.ExtHostWebviewViews);
  }
  $setWebviewViewTitle(handle2, value) {
    const webviewView = this.j(handle2);
    webviewView.title = value;
  }
  $setWebviewViewDescription(handle2, value) {
    const webviewView = this.j(handle2);
    webviewView.description = value;
  }
  $setWebviewViewBadge(handle2, badge) {
    const webviewView = this.j(handle2);
    webviewView.badge = badge;
  }
  $show(handle2, preserveFocus) {
    const webviewView = this.j(handle2);
    webviewView.show(preserveFocus);
  }
  $registerWebviewViewProvider(extensionData, viewType, options3) {
    if (this.c.has(viewType)) {
      throw new Error(`View provider for ${viewType} already registered`);
    }
    const extension = $nOb(extensionData);
    const registration = this.h.register(viewType, {
      resolve: async (webviewView, cancellation) => {
        const handle2 = $ps();
        this.b.set(handle2, webviewView);
        this.f.addWebview(handle2, webviewView.webview, { serializeBuffersForPostMessage: options3.serializeBuffersForPostMessage });
        let state = void 0;
        if (webviewView.webview.state) {
          try {
            state = JSON.parse(webviewView.webview.state);
          } catch (e) {
            console.error("Could not load webview state", e, webviewView.webview.state);
          }
        }
        webviewView.webview.extension = extension;
        if (options3) {
          webviewView.webview.options = options3;
        }
        webviewView.onDidChangeVisibility((visible) => {
          this.a.$onDidChangeWebviewViewVisibility(handle2, visible);
        });
        webviewView.onDispose(() => {
          this.a.$disposeWebviewView(handle2);
          this.b.deleteAndDispose(handle2);
        });
        this.g.publicLog2("webviews:createWebviewView", {
          extensionId: extension.id.value,
          id: viewType
        });
        try {
          await this.a.$resolveWebviewView(handle2, viewType, webviewView.title, state, cancellation);
        } catch (error) {
          $gb(error);
          webviewView.webview.setHtml(this.f.getWebviewResolvedFailedContent(viewType));
        }
      }
    });
    this.c.set(viewType, registration);
  }
  $unregisterWebviewViewProvider(viewType) {
    if (!this.c.has(viewType)) {
      throw new Error(`No view provider for ${viewType} registered`);
    }
    this.c.deleteAndDispose(viewType);
  }
  j(handle2) {
    const webviewView = this.b.get(handle2);
    if (!webviewView) {
      throw new Error("unknown webview view");
    }
    return webviewView;
  }
};
$5Rb = __decorate([
  __param(2, $zv),
  __param(3, $3Rb)
], $5Rb);

// out-build/vs/workbench/api/browser/mainThreadWebviewManager.js
var $6Rb = class $6Rb2 extends $3c {
  constructor(context, instantiationService) {
    super();
    const webviews = this.B(instantiationService.createInstance($mOb, context));
    context.set($xT.MainThreadWebviews, webviews);
    const webviewPanels = this.B(instantiationService.createInstance($TRb, context, webviews));
    context.set($xT.MainThreadWebviewPanels, webviewPanels);
    const customEditors = this.B(instantiationService.createInstance($2Rb, context, webviews, webviewPanels));
    context.set($xT.MainThreadCustomEditors, customEditors);
    const webviewViews = this.B(instantiationService.createInstance($5Rb, context, webviews));
    context.set($xT.MainThreadWebviewViews, webviewViews);
  }
};
$6Rb = __decorate([
  $grb,
  __param(1, $Pk)
], $6Rb);

// out-build/vs/workbench/services/search/common/queryBuilder.js
function $cT(object) {
  return typeof object === "object" && "uri" in object && "pattern" in object;
}
var $eT = class $eT2 {
  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;
  }
  aiText(contentPattern, folderResources, options3 = {}) {
    const commonQuery = this.j(folderResources?.map($_k), options3);
    return {
      ...commonQuery,
      type: 3,
      contentPattern
    };
  }
  text(contentPattern, folderResources, options3 = {}) {
    contentPattern = this.h(contentPattern, options3);
    const searchConfig = this.a.getValue();
    const fallbackToPCRE = folderResources && folderResources.some((folder) => {
      const folderConfig = this.a.getValue({ resource: folder });
      return !folderConfig.search.useRipgrep;
    });
    const commonQuery = this.j(folderResources?.map($_k), options3);
    return {
      ...commonQuery,
      type: 2,
      contentPattern,
      previewOptions: options3.previewOptions,
      maxFileSize: options3.maxFileSize,
      usePCRE2: searchConfig.search.usePCRE2 || fallbackToPCRE || false,
      surroundingContext: options3.surroundingContext,
      userDisabledExcludesAndIgnoreFiles: options3.disregardExcludeSettings && options3.disregardIgnoreFiles
    };
  }
  /**
   * Adjusts input pattern for config
   */
  h(inputPattern, options3) {
    const searchConfig = this.a.getValue();
    if (inputPattern.isRegExp) {
      inputPattern.pattern = inputPattern.pattern.replace(/\r?\n/g, "\\n");
    }
    const newPattern = {
      ...inputPattern,
      wordSeparators: searchConfig.editor.wordSeparators
    };
    if (this.l(inputPattern, options3)) {
      newPattern.isCaseSensitive = true;
    }
    if (this.m(inputPattern)) {
      newPattern.isMultiline = true;
    }
    if (options3.notebookSearchConfig?.includeMarkupInput) {
      if (!newPattern.notebookInfo) {
        newPattern.notebookInfo = {};
      }
      newPattern.notebookInfo.isInNotebookMarkdownInput = options3.notebookSearchConfig.includeMarkupInput;
    }
    if (options3.notebookSearchConfig?.includeMarkupPreview) {
      if (!newPattern.notebookInfo) {
        newPattern.notebookInfo = {};
      }
      newPattern.notebookInfo.isInNotebookMarkdownPreview = options3.notebookSearchConfig.includeMarkupPreview;
    }
    if (options3.notebookSearchConfig?.includeCodeInput) {
      if (!newPattern.notebookInfo) {
        newPattern.notebookInfo = {};
      }
      newPattern.notebookInfo.isInNotebookCellInput = options3.notebookSearchConfig.includeCodeInput;
    }
    if (options3.notebookSearchConfig?.includeOutput) {
      if (!newPattern.notebookInfo) {
        newPattern.notebookInfo = {};
      }
      newPattern.notebookInfo.isInNotebookCellOutput = options3.notebookSearchConfig.includeOutput;
    }
    return newPattern;
  }
  file(folders, options3 = {}) {
    const commonQuery = this.j(folders, options3);
    return {
      ...commonQuery,
      type: 1,
      filePattern: options3.filePattern ? options3.filePattern.trim() : options3.filePattern,
      exists: options3.exists,
      sortByScore: options3.sortByScore,
      cacheKey: options3.cacheKey,
      shouldGlobMatchFilePattern: options3.shouldGlobSearch
    };
  }
  i(pattern, expandPatterns) {
    if (!pattern) {
      return {};
    }
    if (Array.isArray(pattern)) {
      pattern = pattern.filter((p) => p.length > 0).map(normalizeSlashes2);
      if (!pattern.length) {
        return {};
      }
    } else {
      pattern = normalizeSlashes2(pattern);
    }
    return expandPatterns ? this.parseSearchPaths(pattern) : { pattern: patternListToIExpression(...Array.isArray(pattern) ? pattern : [pattern]) };
  }
  j(folderResources = [], options3 = {}) {
    let excludePatterns = Array.isArray(options3.excludePattern) ? options3.excludePattern.map((p) => p.pattern).flat() : options3.excludePattern;
    excludePatterns = excludePatterns?.length === 1 ? excludePatterns[0] : excludePatterns;
    const includeSearchPathsInfo = this.i(options3.includePattern, options3.expandPatterns);
    const excludeSearchPathsInfo = this.i(excludePatterns, options3.expandPatterns);
    const includeFolderName = folderResources.length > 1;
    const folderQueries = (includeSearchPathsInfo.searchPaths && includeSearchPathsInfo.searchPaths.length ? includeSearchPathsInfo.searchPaths.map((searchPath) => this.t(searchPath, options3, excludeSearchPathsInfo)) : folderResources.map((folder) => this.u(folder, options3, excludeSearchPathsInfo, includeFolderName))).filter((query) => !!query);
    const queryProps = {
      _reason: options3._reason,
      folderQueries,
      usingSearchPaths: !!(includeSearchPathsInfo.searchPaths && includeSearchPathsInfo.searchPaths.length),
      extraFileResources: options3.extraFileResources,
      excludePattern: excludeSearchPathsInfo.pattern,
      includePattern: includeSearchPathsInfo.pattern,
      onlyOpenEditors: options3.onlyOpenEditors,
      maxResults: options3.maxResults,
      onlyFileScheme: options3.onlyFileScheme
    };
    if (options3.onlyOpenEditors) {
      const openEditors = $Mb(this.c.groups.flatMap((group2) => group2.editors.map((editor) => editor.resource)));
      this.d.trace("QueryBuilder#commonQuery - openEditor URIs", JSON.stringify(openEditors));
      const openEditorsInQuery = openEditors.filter((editor) => $3N(queryProps, editor.fsPath));
      const openEditorsQueryProps = this.k(openEditorsInQuery);
      this.d.trace("QueryBuilder#commonQuery - openEditor Query", JSON.stringify(openEditorsQueryProps));
      return { ...queryProps, ...openEditorsQueryProps };
    }
    const extraFileResources = options3.extraFileResources && options3.extraFileResources.filter((extraFile) => $3N(queryProps, extraFile.fsPath));
    queryProps.extraFileResources = extraFileResources && extraFileResources.length ? extraFileResources : void 0;
    return queryProps;
  }
  k(files) {
    const folderQueries = [];
    const foldersToSearch = new $Ec();
    const includePattern = {};
    let hasIncludedFile = false;
    files.forEach((file) => {
      if (file.scheme === Schemas.walkThrough) {
        return;
      }
      const providerExists = $zh(file);
      if (providerExists) {
        const searchRoot = this.b.getWorkspaceFolder(file)?.uri ?? this.g.extUri.dirname(file);
        let folderQuery = foldersToSearch.get(searchRoot);
        if (!folderQuery) {
          hasIncludedFile = true;
          folderQuery = { folder: searchRoot, includePattern: {} };
          folderQueries.push(folderQuery);
          foldersToSearch.set(searchRoot, folderQuery);
        }
        const relPath = $pc(searchRoot.fsPath, file.fsPath);
        $Kg(folderQuery.includePattern)[relPath.replace(/\\/g, "/")] = true;
      } else {
        if (file.fsPath) {
          hasIncludedFile = true;
          includePattern[file.fsPath] = true;
        }
      }
    });
    return {
      folderQueries,
      includePattern,
      usingSearchPaths: true,
      excludePattern: hasIncludedFile ? void 0 : { "**/*": true }
    };
  }
  /**
   * Resolve isCaseSensitive flag based on the query and the isSmartCase flag, for search providers that don't support smart case natively.
   */
  l(contentPattern, options3) {
    if (options3.isSmartCase) {
      if (contentPattern.isRegExp) {
        if ($qg(contentPattern.pattern, true)) {
          return true;
        }
      } else if ($qg(contentPattern.pattern)) {
        return true;
      }
    }
    return !!contentPattern.isCaseSensitive;
  }
  m(contentPattern) {
    if (contentPattern.isMultiline) {
      return true;
    }
    if (contentPattern.isRegExp && $gI(contentPattern.pattern)) {
      return true;
    }
    if (contentPattern.pattern.indexOf("\n") >= 0) {
      return true;
    }
    return !!contentPattern.isMultiline;
  }
  /**
   * Take the includePattern as seen in the search viewlet, and split into components that look like searchPaths, and
   * glob patterns. Glob patterns are expanded from 'foo/bar' to '{foo/bar/**, **\/foo/bar}.
   *
   * Public for test.
   */
  parseSearchPaths(pattern) {
    const isSearchPath = (segment) => {
      return $mc(segment) || /^\.\.?([\/\\]|$)/.test(segment);
    };
    const patterns = Array.isArray(pattern) ? pattern : splitGlobPattern(pattern);
    const segments = patterns.map((segment) => {
      const userHome = this.f.resolvedUserHome;
      if (userHome) {
        return $3t(segment, userHome.scheme === Schemas.file ? userHome.fsPath : userHome.path);
      }
      return segment;
    });
    const groups = $a(segments, (segment) => isSearchPath(segment) ? "searchPaths" : "exprSegments");
    const expandedExprSegments = (groups.exprSegments || []).map((s) => $Gf(s, "/")).map((s) => $Gf(s, "\\")).map((p) => {
      if (p[0] === ".") {
        p = "*" + p;
      }
      return expandGlobalGlob(p);
    });
    const result = {};
    const searchPaths = this.o(groups.searchPaths || []);
    if (searchPaths && searchPaths.length) {
      result.searchPaths = searchPaths;
    }
    const exprSegments = expandedExprSegments.flat();
    const includePattern = patternListToIExpression(...exprSegments);
    if (includePattern) {
      result.pattern = includePattern;
    }
    return result;
  }
  n(folderConfig, options3) {
    return options3.disregardExcludeSettings ? void 0 : $2N(folderConfig, !options3.disregardSearchExcludeSettings);
  }
  /**
   * Split search paths (./ or ../ or absolute paths in the includePatterns) into absolute paths and globs applied to those paths
   */
  o(searchPaths) {
    if (!searchPaths || !searchPaths.length) {
      return [];
    }
    const expandedSearchPaths = searchPaths.flatMap((searchPath) => {
      let { pathPortion, globPortion } = splitGlobFromPath(searchPath);
      if (globPortion) {
        globPortion = normalizeGlobPattern(globPortion);
      }
      const oneExpanded = this.q(pathPortion);
      return oneExpanded.flatMap((oneExpandedResult) => this.r(oneExpandedResult, globPortion));
    });
    const searchPathPatternMap = /* @__PURE__ */ new Map();
    expandedSearchPaths.forEach((oneSearchPathPattern) => {
      const key2 = oneSearchPathPattern.searchPath.toString();
      const existing = searchPathPatternMap.get(key2);
      if (existing) {
        if (oneSearchPathPattern.pattern) {
          existing.pattern = existing.pattern || {};
          existing.pattern[oneSearchPathPattern.pattern] = true;
        }
      } else {
        searchPathPatternMap.set(key2, {
          searchPath: oneSearchPathPattern.searchPath,
          pattern: oneSearchPathPattern.pattern ? patternListToIExpression(oneSearchPathPattern.pattern) : void 0
        });
      }
    });
    return Array.from(searchPathPatternMap.values());
  }
  /**
   * Takes a searchPath like `./a/foo` or `../a/foo` and expands it to absolute paths for all the workspaces it matches.
   */
  q(searchPath) {
    if ($mc(searchPath)) {
      const workspaceFolders = this.b.getWorkspace().folders;
      if (workspaceFolders[0] && workspaceFolders[0].uri.scheme !== Schemas.file) {
        return [{
          searchPath: workspaceFolders[0].uri.with({ path: searchPath })
        }];
      }
      return [{
        searchPath: URI.file($lc(searchPath))
      }];
    }
    if (this.b.getWorkbenchState() === 2) {
      const workspaceUri = this.b.getWorkspace().folders[0].uri;
      searchPath = normalizeSlashes2(searchPath);
      if (searchPath.startsWith("../") || searchPath === "..") {
        const resolvedPath = $kc.resolve(workspaceUri.path, searchPath);
        return [{
          searchPath: workspaceUri.with({ path: resolvedPath })
        }];
      }
      const cleanedPattern = normalizeGlobPattern(searchPath);
      return [{
        searchPath: workspaceUri,
        pattern: cleanedPattern
      }];
    } else if (searchPath === "./" || searchPath === ".\\") {
      return [];
    } else {
      const searchPathWithoutDotSlash = searchPath.replace(/^\.[\/\\]/, "");
      const folders = this.b.getWorkspace().folders;
      const folderMatches = folders.map((folder) => {
        const match = searchPathWithoutDotSlash.match(new RegExp(`^${$Af(folder.name)}(?:/(.*)|$)`));
        return match ? {
          match,
          folder
        } : null;
      }).filter($Hg);
      if (folderMatches.length) {
        return folderMatches.map((match) => {
          const patternMatch = match.match[1];
          return {
            searchPath: match.folder.uri,
            pattern: patternMatch && normalizeGlobPattern(patternMatch)
          };
        });
      } else {
        const probableWorkspaceFolderNameMatch = searchPath.match(/\.[\/\\](.+)[\/\\]?/);
        const probableWorkspaceFolderName = probableWorkspaceFolderNameMatch ? probableWorkspaceFolderNameMatch[1] : searchPath;
        const searchPathNotFoundError = localize(13104, null, probableWorkspaceFolderName);
        throw new Error(searchPathNotFoundError);
      }
    }
  }
  r(oneExpandedResult, globPortion) {
    const pattern = oneExpandedResult.pattern && globPortion ? `${oneExpandedResult.pattern}/${globPortion}` : oneExpandedResult.pattern || globPortion;
    const results = [
      {
        searchPath: oneExpandedResult.searchPath,
        pattern
      }
    ];
    if (pattern && !pattern.endsWith("**")) {
      results.push({
        searchPath: oneExpandedResult.searchPath,
        pattern: pattern + "/**"
      });
    }
    return results;
  }
  t(searchPath, options3, searchPathExcludes) {
    const rootConfig = this.u($_k(searchPath.searchPath), options3, searchPathExcludes, false);
    if (!rootConfig) {
      return null;
    }
    return {
      ...rootConfig,
      ...{
        includePattern: searchPath.pattern
      }
    };
  }
  u(folder, options3, searchPathExcludes, includeFolderName) {
    let thisFolderExcludeSearchPathPattern;
    const folderUri = URI.isUri(folder) ? folder : folder.uri;
    let excludeFolderRoots = options3.excludePattern?.map((excludePattern2) => {
      const excludeRoot = options3.excludePattern && $cT(excludePattern2) ? excludePattern2.uri : void 0;
      const shouldUseExcludeRoot = !excludeRoot || !(URI.isUri(folder) && this.g.extUri.isEqual(folder, excludeRoot));
      return shouldUseExcludeRoot ? excludeRoot : void 0;
    });
    if (!excludeFolderRoots?.length) {
      excludeFolderRoots = [void 0];
    }
    if (searchPathExcludes.searchPaths) {
      const thisFolderExcludeSearchPath = searchPathExcludes.searchPaths.filter((sp) => $oh(sp.searchPath, folderUri))[0];
      if (thisFolderExcludeSearchPath && !thisFolderExcludeSearchPath.pattern) {
        return null;
      } else if (thisFolderExcludeSearchPath) {
        thisFolderExcludeSearchPathPattern = thisFolderExcludeSearchPath.pattern;
      }
    }
    const folderConfig = this.a.getValue({ resource: folderUri });
    const settingExcludes = this.n(folderConfig, options3);
    const excludePattern = {
      ...settingExcludes || {},
      ...thisFolderExcludeSearchPathPattern || {}
    };
    const folderName = URI.isUri(folder) ? $sh(folder) : folder.name;
    const excludePatternRet = excludeFolderRoots.map((excludeFolderRoot) => {
      return Object.keys(excludePattern).length > 0 ? {
        folder: excludeFolderRoot,
        pattern: excludePattern
      } : void 0;
    }).filter((e) => e);
    return {
      folder: folderUri,
      folderName: includeFolderName ? folderName : void 0,
      excludePattern: excludePatternRet,
      fileEncoding: folderConfig.files && folderConfig.files.encoding,
      disregardIgnoreFiles: typeof options3.disregardIgnoreFiles === "boolean" ? options3.disregardIgnoreFiles : !folderConfig.search.useIgnoreFiles,
      disregardGlobalIgnoreFiles: typeof options3.disregardGlobalIgnoreFiles === "boolean" ? options3.disregardGlobalIgnoreFiles : !folderConfig.search.useGlobalIgnoreFiles,
      disregardParentIgnoreFiles: typeof options3.disregardParentIgnoreFiles === "boolean" ? options3.disregardParentIgnoreFiles : !folderConfig.search.useParentIgnoreFiles,
      ignoreSymlinks: typeof options3.ignoreSymlinks === "boolean" ? options3.ignoreSymlinks : !folderConfig.search.followSymlinks
    };
  }
};
$eT = __decorate([
  __param(0, $kl),
  __param(1, $Zk),
  __param(2, $iJ),
  __param(3, $wn),
  __param(4, $aT),
  __param(5, $vl)
], $eT);
function splitGlobFromPath(searchPath) {
  const globCharMatch = searchPath.match(/[\*\{\}\(\)\[\]\?]/);
  if (globCharMatch) {
    const globCharIdx = globCharMatch.index;
    const lastSlashMatch = searchPath.substr(0, globCharIdx).match(/[/|\\][^/\\]*$/);
    if (lastSlashMatch) {
      let pathPortion = searchPath.substr(0, lastSlashMatch.index);
      if (!pathPortion.match(/[/\\]/)) {
        pathPortion += "/";
      }
      return {
        pathPortion,
        globPortion: searchPath.substr((lastSlashMatch.index || 0) + 1)
      };
    }
  }
  return {
    pathPortion: searchPath
  };
}
function patternListToIExpression(...patterns) {
  return patterns.length ? patterns.reduce((glob, cur) => {
    glob[cur] = true;
    return glob;
  }, /* @__PURE__ */ Object.create(null)) : void 0;
}
function splitGlobPattern(pattern) {
  return $Bl(pattern, ",").map((s) => s.trim()).filter((s) => !!s.length);
}
function expandGlobalGlob(pattern) {
  const patterns = [
    `**/${pattern}/**`,
    `**/${pattern}`
  ];
  return patterns.map((p) => p.replace(/\*\*\/\*\*/g, "**"));
}
function normalizeSlashes2(pattern) {
  return pattern.replace(/\\/g, "/");
}
function normalizeGlobPattern(pattern) {
  return normalizeSlashes2(pattern).replace(/^\.\//, "").replace(/\/+$/g, "");
}
function escapeGlobPattern(path) {
  return path.replace(/([?*[\]])/g, "[$1]");
}
function $fT(resources, contextService) {
  resources = $Rb(resources, (resource) => resource.toString());
  const folderPaths = [];
  const workspace2 = contextService.getWorkspace();
  if (resources) {
    resources.forEach((resource) => {
      let folderPath;
      if (contextService.getWorkbenchState() === 2) {
        folderPath = $xh(workspace2.folders[0].uri, resource);
        if (folderPath && folderPath !== ".") {
          folderPath = "./" + folderPath;
        }
      } else {
        const owningFolder = contextService.getWorkspaceFolder(resource);
        if (owningFolder) {
          const owningRootName = owningFolder.name;
          const isUniqueFolder = workspace2.folders.filter((folder) => folder.name === owningRootName).length === 1;
          if (isUniqueFolder) {
            const relPath = $xh(owningFolder.uri, resource);
            if (relPath === "") {
              folderPath = `./${owningFolder.name}`;
            } else {
              folderPath = `./${owningFolder.name}/${relPath}`;
            }
          } else {
            folderPath = resource.fsPath;
          }
        }
      }
      if (folderPath) {
        folderPaths.push(escapeGlobPattern(folderPath));
      }
    });
  }
  return folderPaths;
}

// out-build/vs/workbench/services/extensions/common/workspaceContains.js
var WORKSPACE_CONTAINS_TIMEOUT = 7e3;
function $7Rb(host, desc) {
  const activationEvents = desc.activationEvents;
  if (!activationEvents) {
    return Promise.resolve(void 0);
  }
  const fileNames = [];
  const globPatterns = [];
  for (const activationEvent of activationEvents) {
    if (/^workspaceContains:/.test(activationEvent)) {
      const fileNameOrGlob = activationEvent.substr("workspaceContains:".length);
      if (fileNameOrGlob.indexOf("*") >= 0 || fileNameOrGlob.indexOf("?") >= 0 || host.forceUsingSearch) {
        globPatterns.push(fileNameOrGlob);
      } else {
        fileNames.push(fileNameOrGlob);
      }
    }
  }
  if (fileNames.length === 0 && globPatterns.length === 0) {
    return Promise.resolve(void 0);
  }
  const { promise, resolve } = $Oh();
  const activate = (activationEvent) => resolve({ activationEvent });
  const fileNamePromise = Promise.all(fileNames.map((fileName) => _activateIfFileName(host, fileName, activate))).then(() => {
  });
  const globPatternPromise = _activateIfGlobPatterns(host, desc.identifier, globPatterns, activate);
  Promise.all([fileNamePromise, globPatternPromise]).then(() => {
    resolve(void 0);
  });
  return promise;
}
async function _activateIfFileName(host, fileName, activate) {
  for (const uri of host.folders) {
    if (await host.exists($vh(URI.revive(uri), fileName))) {
      activate(`workspaceContains:${fileName}`);
      return;
    }
  }
}
async function _activateIfGlobPatterns(host, extensionId, globPatterns, activate) {
  if (globPatterns.length === 0) {
    return Promise.resolve(void 0);
  }
  const tokenSource = new $ad();
  const searchP = host.checkExists(host.folders, globPatterns, tokenSource.token);
  const timer = setTimeout(async () => {
    tokenSource.cancel();
    host.logService.info(`Not activating extension '${extensionId.value}': Timed out while searching for 'workspaceContains' pattern ${globPatterns.join(",")}`);
  }, WORKSPACE_CONTAINS_TIMEOUT);
  let exists = false;
  try {
    exists = await searchP;
  } catch (err) {
    if (!$kb(err)) {
      $gb(err);
    }
  }
  tokenSource.dispose();
  clearTimeout(timer);
  if (exists) {
    activate(`workspaceContains:${globPatterns.join(",")}`);
  }
}
function $8Rb(accessor, folders, includes2, token) {
  const instantiationService = accessor.get($Pk);
  const searchService = accessor.get($TN);
  const queryBuilder = instantiationService.createInstance($eT);
  const query = queryBuilder.file(folders.map((folder) => $_k(URI.revive(folder))), {
    _reason: "checkExists",
    includePattern: includes2,
    exists: true
  });
  return searchService.fileSearch(query, token).then((result) => {
    return !!result.limitHit;
  }, (err) => {
    if (!$kb(err)) {
      return Promise.reject(err);
    }
    return false;
  });
}

// out-build/vs/platform/workspace/common/canonicalUri.js
var $9Rb = $Qk("canonicalUriIdentityService");

// out-build/vs/workbench/api/browser/mainThreadWorkspace.js
var $0Rb = class $0Rb2 {
  constructor(extHostContext, e, g, h3, i2, j, k, l, n, o, q, r2, fileService, s, t) {
    this.e = e;
    this.g = g;
    this.h = h3;
    this.i = i2;
    this.j = j;
    this.k = k;
    this.l = l;
    this.n = n;
    this.o = o;
    this.q = q;
    this.r = r2;
    this.s = s;
    this.t = t;
    this.a = new $2c();
    this.b = /* @__PURE__ */ Object.create(null);
    this.d = this.o.createInstance($eT);
    this.A = /* @__PURE__ */ new Map();
    this.B = /* @__PURE__ */ new Map();
    this.c = extHostContext.getProxy($yT.ExtHostWorkspace);
    const workspace2 = this.g.getWorkspace();
    if (workspace2.configuration && !$p && !fileService.hasProvider(workspace2.configuration)) {
      this.c.$initializeWorkspace(this.w(workspace2), this.y());
    } else {
      this.g.getCompleteWorkspace().then((workspace3) => this.c.$initializeWorkspace(this.w(workspace3), this.y()));
    }
    this.g.onDidChangeWorkspaceFolders(this.v, this, this.a);
    this.g.onDidChangeWorkbenchState(this.v, this, this.a);
    this.s.onDidChangeTrust(this.z, this, this.a);
  }
  dispose() {
    this.a.dispose();
    for (const requestId in this.b) {
      const tokenSource = this.b[requestId];
      tokenSource.cancel();
    }
  }
  // --- workspace ---
  $updateWorkspaceFolders(extensionName, index, deleteCount, foldersToAdd) {
    const workspaceFoldersToAdd = foldersToAdd.map((f) => ({ uri: URI.revive(f.uri), name: f.name }));
    this.l.status(this.u(extensionName, workspaceFoldersToAdd.length, deleteCount), {
      hideAfter: 10 * 1e3
      /* 10s */
    });
    return this.k.updateFolders(index, deleteCount, workspaceFoldersToAdd, true);
  }
  u(extensionName, addCount, removeCount) {
    let message;
    const wantsToAdd = addCount > 0;
    const wantsToDelete = removeCount > 0;
    if (wantsToAdd && !wantsToDelete) {
      if (addCount === 1) {
        message = localize(2632, null, extensionName);
      } else {
        message = localize(2633, null, extensionName, addCount);
      }
    } else if (wantsToDelete && !wantsToAdd) {
      if (removeCount === 1) {
        message = localize(2634, null, extensionName);
      } else {
        message = localize(2635, null, extensionName, removeCount);
      }
    } else {
      message = localize(2636, null, extensionName);
    }
    return message;
  }
  v() {
    this.c.$acceptWorkspaceData(this.w(this.g.getWorkspace()));
  }
  w(workspace2) {
    if (this.g.getWorkbenchState() === 1) {
      return null;
    }
    return {
      configuration: workspace2.configuration || void 0,
      isUntitled: workspace2.configuration ? $el(workspace2.configuration, this.r) : false,
      folders: workspace2.folders,
      id: workspace2.id,
      name: this.q.getWorkspaceLabel(workspace2),
      transient: workspace2.transient
    };
  }
  // --- search ---
  $startFileSearch(_includeFolder, options3, token) {
    const includeFolder = URI.revive(_includeFolder);
    const workspace2 = this.g.getWorkspace();
    const query = this.d.file(includeFolder ? [includeFolder] : workspace2.folders, $cu(options3));
    return this.e.fileSearch(query, token).then((result) => {
      return result.results.map((m) => m.resource);
    }, (err) => {
      if (!$kb(err)) {
        return Promise.reject(err);
      }
      return null;
    });
  }
  $startTextSearch(pattern, _folder, options3, requestId, token) {
    const folder = URI.revive(_folder);
    const workspace2 = this.g.getWorkspace();
    const folders = folder ? [folder] : workspace2.folders.map((folder2) => folder2.uri);
    const query = this.d.text(pattern, folders, $cu(options3));
    query._reason = "startTextSearch";
    const onProgress = (p) => {
      if (p.results) {
        this.c.$handleTextSearchResult(p, requestId);
      }
    };
    const search2 = this.e.textSearch(query, token, onProgress).then((result) => {
      return { limitHit: result.limitHit };
    }, (err) => {
      if (!$kb(err)) {
        return Promise.reject(err);
      }
      return null;
    });
    return search2;
  }
  $checkExists(folders, includes2, token) {
    return this.o.invokeFunction((accessor) => $8Rb(accessor, folders, includes2, token));
  }
  // --- save & edit resources ---
  async $save(uriComponents, options3) {
    const uri = URI.revive(uriComponents);
    const editors = [...this.j.findEditors(uri, { supportSideBySide: SideBySideEditor.PRIMARY })];
    const result = await this.j.save(editors, {
      reason: 1,
      saveAs: options3.saveAs,
      force: !options3.saveAs
    });
    return this.x(result).at(0);
  }
  x(result) {
    if (!result.success) {
      return [];
    }
    return $Mb(result.editors.map((editor) => $mL.getCanonicalUri(editor, { supportSideBySide: SideBySideEditor.PRIMARY })));
  }
  $saveAll(includeUntitled) {
    return this.j.saveAll({ includeUntitled }).then((res) => res.success);
  }
  $resolveProxy(url) {
    return this.n.resolveProxy(url);
  }
  $lookupAuthorization(authInfo) {
    return this.n.lookupAuthorization(authInfo);
  }
  $lookupKerberosAuthorization(url) {
    return this.n.lookupKerberosAuthorization(url);
  }
  $loadCertificates() {
    return this.n.loadCertificates();
  }
  // --- trust ---
  $requestWorkspaceTrust(options3) {
    return this.t.requestWorkspaceTrust(options3);
  }
  y() {
    return this.s.isWorkspaceTrusted();
  }
  z() {
    this.c.$onDidGrantWorkspaceTrust();
  }
  $registerEditSessionIdentityProvider(handle2, scheme) {
    const disposable = this.h.registerEditSessionIdentityProvider({
      scheme,
      getEditSessionIdentifier: async (workspaceFolder, token) => {
        return this.c.$getEditSessionIdentifier(workspaceFolder.uri, token);
      },
      provideEditSessionIdentityMatch: async (workspaceFolder, identity1, identity2, token) => {
        return this.c.$provideEditSessionIdentityMatch(workspaceFolder.uri, identity1, identity2, token);
      }
    });
    this.A.set(handle2, disposable);
    this.a.add(disposable);
  }
  $unregisterEditSessionIdentityProvider(handle2) {
    const disposable = this.A.get(handle2);
    disposable?.dispose();
    this.A.delete(handle2);
  }
  $registerCanonicalUriProvider(handle2, scheme) {
    const disposable = this.i.registerCanonicalUriProvider({
      scheme,
      provideCanonicalUri: async (uri, targetScheme, token) => {
        const result = await this.c.$provideCanonicalUri(uri, targetScheme, token);
        if (result) {
          return URI.revive(result);
        }
        return result;
      }
    });
    this.B.set(handle2, disposable);
    this.a.add(disposable);
  }
  $unregisterCanonicalUriProvider(handle2) {
    const disposable = this.B.get(handle2);
    disposable?.dispose();
    this.B.delete(handle2);
  }
};
$0Rb = __decorate([
  $frb($xT.MainThreadWorkspace),
  __param(1, $TN),
  __param(2, $Zk),
  __param(3, $2M),
  __param(4, $9Rb),
  __param(5, $mJ),
  __param(6, $zob),
  __param(7, $PJ),
  __param(8, $9u),
  __param(9, $Pk),
  __param(10, $ZI),
  __param(11, $Xk),
  __param(12, $km),
  __param(13, $4M),
  __param(14, $5M)
], $0Rb);

// out-build/vs/workbench/contrib/comments/browser/commentMenus.js
var $NJb = class $NJb2 {
  constructor(a) {
    this.a = a;
  }
  getCommentThreadTitleActions(contextKeyService) {
    return this.b($bJ.CommentThreadTitle, contextKeyService);
  }
  getCommentThreadActions(contextKeyService) {
    return this.b($bJ.CommentThreadActions, contextKeyService);
  }
  getCommentEditorActions(contextKeyService) {
    return this.b($bJ.CommentEditorActions, contextKeyService);
  }
  getCommentThreadAdditionalActions(contextKeyService) {
    return this.b($bJ.CommentThreadAdditionalActions, contextKeyService, { emitEventsForSubmenuChanges: true });
  }
  getCommentTitleActions(comment, contextKeyService) {
    return this.b($bJ.CommentTitle, contextKeyService);
  }
  getCommentActions(comment, contextKeyService) {
    return this.b($bJ.CommentActions, contextKeyService);
  }
  getCommentThreadTitleContextActions(contextKeyService) {
    return this.b($bJ.CommentThreadTitleContext, contextKeyService);
  }
  b(menuId, contextKeyService, options3) {
    return this.a.createMenu(menuId, contextKeyService, options3);
  }
  dispose() {
  }
};
$NJb = __decorate([
  __param(0, $cJ)
], $NJb);

// out-build/vs/workbench/contrib/comments/common/commentsConfiguration.js
var $OJb = "comments";

// out-build/vs/workbench/contrib/comments/common/commentContextKeys.js
var CommentContextKeys;
(function(CommentContextKeys2) {
  CommentContextKeys2.activeCursorHasCommentingRange = new $nn("activeCursorHasCommentingRange", false, {
    description: localize(5448, null),
    type: "boolean"
  });
  CommentContextKeys2.activeCursorHasComment = new $nn("activeCursorHasComment", false, {
    description: localize(5449, null),
    type: "boolean"
  });
  CommentContextKeys2.activeEditorHasCommentingRange = new $nn("activeEditorHasCommentingRange", false, {
    description: localize(5450, null),
    type: "boolean"
  });
  CommentContextKeys2.WorkspaceHasCommenting = new $nn("workspaceHasCommenting", false, {
    description: localize(5451, null),
    type: "boolean"
  });
  CommentContextKeys2.commentThreadIsEmpty = new $nn("commentThreadIsEmpty", false, { type: "boolean", description: localize(5452, null) });
  CommentContextKeys2.commentIsEmpty = new $nn("commentIsEmpty", false, { type: "boolean", description: localize(5453, null) });
  CommentContextKeys2.commentContext = new $nn("comment", void 0, { type: "string", description: localize(5454, null) });
  CommentContextKeys2.commentThreadContext = new $nn("commentThread", void 0, { type: "string", description: localize(5455, null) });
  CommentContextKeys2.commentControllerContext = new $nn("commentController", void 0, { type: "string", description: localize(5456, null) });
  CommentContextKeys2.commentFocused = new $nn("commentFocused", false, { type: "boolean", description: localize(5457, null) });
})(CommentContextKeys || (CommentContextKeys = {}));

// out-build/vs/workbench/contrib/comments/common/commentModel.js
var $LJb = class {
  constructor(uniqueOwner, owner, resource, comment, thread) {
    this.uniqueOwner = uniqueOwner;
    this.owner = owner;
    this.resource = resource;
    this.comment = comment;
    this.thread = thread;
    this.isRoot = false;
    this.replies = [];
    this.threadId = thread.threadId;
    this.range = thread.range;
    this.threadState = thread.state;
    this.threadRelevance = thread.applicability;
    this.contextValue = thread.contextValue;
    this.controllerHandle = thread.controllerHandle;
    this.threadHandle = thread.commentThreadHandle;
  }
  hasReply() {
    return this.replies && this.replies.length !== 0;
  }
  get lastUpdatedAt() {
    if (this.a === void 0) {
      let updatedAt = this.comment.timestamp || "";
      if (this.replies.length) {
        const reply = this.replies[this.replies.length - 1];
        const replyUpdatedAt = reply.lastUpdatedAt;
        if (replyUpdatedAt > updatedAt) {
          updatedAt = replyUpdatedAt;
        }
      }
      this.a = updatedAt;
    }
    return this.a;
  }
};
var $MJb = class _$MJb {
  constructor(uniqueOwner, owner, resource, commentThreads) {
    this.uniqueOwner = uniqueOwner;
    this.owner = owner;
    this.id = resource.toString();
    this.resource = resource;
    this.commentThreads = commentThreads.filter((thread) => thread.comments && thread.comments.length).map((thread) => _$MJb.createCommentNode(uniqueOwner, owner, resource, thread));
  }
  static createCommentNode(uniqueOwner, owner, resource, commentThread) {
    const { comments } = commentThread;
    const commentNodes = comments.map((comment) => new $LJb(uniqueOwner, owner, resource, comment, commentThread));
    if (commentNodes.length > 1) {
      commentNodes[0].replies = commentNodes.slice(1, commentNodes.length);
    }
    commentNodes[0].isRoot = true;
    return commentNodes[0];
  }
  get lastUpdatedAt() {
    if (this.a === void 0) {
      let updatedAt = "";
      if (!this.commentThreads.length) {
        return updatedAt;
      }
      for (const thread of this.commentThreads) {
        const threadUpdatedAt = thread.lastUpdatedAt;
        if (threadUpdatedAt && threadUpdatedAt > updatedAt) {
          updatedAt = threadUpdatedAt;
        }
      }
      this.a = updatedAt;
    }
    return this.a;
  }
};

// out-build/vs/workbench/contrib/comments/browser/commentsModel.js
function $PJb(thread) {
  return !!thread.comments && !!thread.comments.length && thread.comments.some((comment) => $dm(comment.body) ? comment.body.value.length > 0 : comment.body.length > 0);
}
var $QJb = class _$QJb extends $3c {
  get resourceCommentThreads() {
    return this.c;
  }
  constructor() {
    super();
    this.c = [];
    this.commentThreadsMap = /* @__PURE__ */ new Map();
  }
  f() {
    const includeLabel = this.commentThreadsMap.size > 1;
    this.c = [...this.commentThreadsMap.values()].map((value) => {
      return value.resourceWithCommentThreads.map((resource) => {
        resource.ownerLabel = includeLabel ? value.ownerLabel : void 0;
        return resource;
      }).flat();
    }).flat();
  }
  setCommentThreads(uniqueOwner, owner, ownerLabel, commentThreads) {
    this.commentThreadsMap.set(uniqueOwner, { ownerLabel, resourceWithCommentThreads: this.g(uniqueOwner, owner, commentThreads) });
    this.f();
  }
  deleteCommentsByOwner(uniqueOwner) {
    if (uniqueOwner) {
      const existingOwner = this.commentThreadsMap.get(uniqueOwner);
      this.commentThreadsMap.set(uniqueOwner, { ownerLabel: existingOwner?.ownerLabel, resourceWithCommentThreads: [] });
    } else {
      this.commentThreadsMap.clear();
    }
    this.f();
  }
  updateCommentThreads(event) {
    const { uniqueOwner, owner, ownerLabel, removed, changed, added } = event;
    const threadsForOwner = this.commentThreadsMap.get(uniqueOwner)?.resourceWithCommentThreads || [];
    removed.forEach((thread) => {
      const matchingResourceIndex = threadsForOwner.findIndex((resourceData) => resourceData.id === thread.resource);
      const matchingResourceData = matchingResourceIndex >= 0 ? threadsForOwner[matchingResourceIndex] : void 0;
      const index = matchingResourceData?.commentThreads.findIndex((commentThread) => commentThread.threadId === thread.threadId) ?? 0;
      if (index >= 0) {
        matchingResourceData?.commentThreads.splice(index, 1);
      }
      if (matchingResourceData?.commentThreads.length === 0) {
        threadsForOwner.splice(matchingResourceIndex, 1);
      }
    });
    changed.forEach((thread) => {
      const matchingResourceIndex = threadsForOwner.findIndex((resourceData) => resourceData.id === thread.resource);
      const matchingResourceData = matchingResourceIndex >= 0 ? threadsForOwner[matchingResourceIndex] : void 0;
      if (!matchingResourceData) {
        return;
      }
      const index = matchingResourceData.commentThreads.findIndex((commentThread) => commentThread.threadId === thread.threadId);
      if (index >= 0) {
        matchingResourceData.commentThreads[index] = $MJb.createCommentNode(uniqueOwner, owner, URI.parse(matchingResourceData.id), thread);
      } else if (thread.comments && thread.comments.length) {
        matchingResourceData.commentThreads.push($MJb.createCommentNode(uniqueOwner, owner, URI.parse(matchingResourceData.id), thread));
      }
    });
    added.forEach((thread) => {
      const existingResource = threadsForOwner.filter((resourceWithThreads) => resourceWithThreads.resource.toString() === thread.resource);
      if (existingResource.length) {
        const resource = existingResource[0];
        if (thread.comments && thread.comments.length) {
          resource.commentThreads.push($MJb.createCommentNode(uniqueOwner, owner, resource.resource, thread));
        }
      } else {
        threadsForOwner.push(new $MJb(uniqueOwner, owner, URI.parse(thread.resource), [thread]));
      }
    });
    this.commentThreadsMap.set(uniqueOwner, { ownerLabel, resourceWithCommentThreads: threadsForOwner });
    this.f();
    return removed.length > 0 || changed.length > 0 || added.length > 0;
  }
  hasCommentThreads() {
    return !!this.c.length && this.c.some((resource) => {
      return resource.commentThreads.length > 0 && resource.commentThreads.some((thread) => {
        return $PJb(thread.thread);
      });
    });
  }
  getMessage() {
    if (!this.c.length) {
      return localize(5392, null);
    } else {
      return "";
    }
  }
  g(uniqueOwner, owner, commentThreads) {
    const resourceCommentThreads = [];
    const commentThreadsByResource = /* @__PURE__ */ new Map();
    for (const group2 of $Eb(commentThreads, _$QJb.h)) {
      commentThreadsByResource.set(group2[0].resource, new $MJb(uniqueOwner, owner, URI.parse(group2[0].resource), group2));
    }
    commentThreadsByResource.forEach((v, i2, m) => {
      resourceCommentThreads.push(v);
    });
    return resourceCommentThreads;
  }
  static h(a, b) {
    const resourceA = a.resource.toString();
    const resourceB = b.resource.toString();
    if (resourceA < resourceB) {
      return -1;
    } else if (resourceA > resourceB) {
      return 1;
    } else {
      return 0;
    }
  }
};

// out-build/vs/workbench/contrib/comments/browser/commentService.js
var $RJb = $Qk("commentService");
var CONTINUE_ON_COMMENTS = "comments.continueOnComments";
var $SJb = class $SJb2 extends $3c {
  constructor(H, I, J, contextKeyService, L, M, N) {
    super();
    this.H = H;
    this.I = I;
    this.J = J;
    this.L = L;
    this.M = M;
    this.N = N;
    this.a = this.B(new $ze());
    this.onDidSetDataProvider = this.a.event;
    this.b = this.B(new $ze());
    this.onDidDeleteDataProvider = this.b.event;
    this.c = this.B(new $ze());
    this.onDidSetResourceCommentInfos = this.c.event;
    this.f = this.B(new $ze());
    this.onDidSetAllCommentThreads = this.f.event;
    this.g = this.B(new $ze());
    this.onDidUpdateCommentThreads = this.g.event;
    this.h = this.B(new $ze());
    this.onDidUpdateNotebookCommentThreads = this.h.event;
    this.j = this.B(new $ze());
    this.onDidUpdateCommentingRanges = this.j.event;
    this.m = this.B(new $ze());
    this.onDidChangeActiveEditingCommentThread = this.m.event;
    this.n = this.B(new $ze());
    this.onDidChangeCurrentCommentThread = this.n.event;
    this.r = this.B(new $ze());
    this.onDidChangeCommentingEnabled = this.r.event;
    this.s = this.B(new $ze());
    this.onDidChangeActiveCommentingRange = this.s.event;
    this.t = /* @__PURE__ */ new Map();
    this.u = /* @__PURE__ */ new Map();
    this.w = true;
    this.z = /* @__PURE__ */ new Map();
    this.C = /* @__PURE__ */ new Set();
    this.D = this.B(new $QJb());
    this.commentsModel = this.D;
    this.F = /* @__PURE__ */ new Set();
    this.G = /* @__PURE__ */ new Set();
    this.P();
    this.Q();
    this.y = CommentContextKeys.WorkspaceHasCommenting.bindTo(contextKeyService);
    const storageListener = this.B(new $2c());
    const storageEvent = Event2.debounce(this.L.onDidChangeValue(1, CONTINUE_ON_COMMENTS, storageListener), (last, event) => last?.external ? last : event, 500);
    storageListener.add(storageEvent((v) => {
      if (!v.external) {
        return;
      }
      const commentsToRestore = this.L.getObject(
        CONTINUE_ON_COMMENTS,
        1
        /* StorageScope.WORKSPACE */
      );
      if (!commentsToRestore) {
        return;
      }
      this.M.debug(`Comments: URIs of continue on comments from storage ${commentsToRestore.map((thread) => thread.uri.toString()).join(", ")}.`);
      const changedOwners = this.Y(commentsToRestore, this.z);
      for (const uniqueOwner of changedOwners) {
        const control = this.t.get(uniqueOwner);
        if (!control) {
          continue;
        }
        const evt = {
          uniqueOwner,
          owner: control.owner,
          ownerLabel: control.label,
          pending: this.z.get(uniqueOwner) || [],
          added: [],
          removed: [],
          changed: []
        };
        this.W(evt);
      }
    }));
    this.B(L.onWillSaveState(() => {
      const map = /* @__PURE__ */ new Map();
      for (const provider of this.C) {
        const pendingComments = provider.provideContinueOnComments();
        this.Y(pendingComments, map);
      }
      this.X(map);
    }));
    this.B(this.N.onModelAdded((model) => {
      if (!this.F.has(model.uri.toString())) {
        this.getDocumentComments(model.uri);
      }
    }));
  }
  O(resource, commentInfos) {
    for (const comments of commentInfos) {
      if (comments && (comments.commentingRanges.ranges.length > 0 || comments.threads.length > 0)) {
        this.F.add(resource.toString());
      }
    }
  }
  P() {
    this.w = this.R;
    this.B(this.J.onDidChangeConfiguration((e) => {
      if (e.affectsConfiguration("comments.visible")) {
        this.enableCommenting(this.R);
      }
    }));
  }
  Q() {
    let preZenModeValue = this.w;
    this.B(this.I.onDidChangeZenMode((e) => {
      if (e) {
        preZenModeValue = this.w;
        this.enableCommenting(false);
      } else {
        this.enableCommenting(preZenModeValue);
      }
    }));
  }
  get R() {
    return !!this.J.getValue($OJb)?.visible;
  }
  get isCommentingEnabled() {
    return this.w;
  }
  enableCommenting(enable) {
    if (enable !== this.w) {
      this.w = enable;
      this.r.fire(enable);
    }
  }
  /**
   * The current comment thread is the thread that has focus or is being hovered.
   * @param commentThread
   */
  setCurrentCommentThread(commentThread) {
    this.n.fire(commentThread);
  }
  /**
   * The active comment thread is the the thread that is currently being edited.
   * @param commentThread
   */
  setActiveEditingCommentThread(commentThread) {
    this.m.fire(commentThread);
  }
  get lastActiveCommentcontroller() {
    return this.S;
  }
  async setActiveCommentAndThread(uniqueOwner, commentInfo) {
    const commentController = this.t.get(uniqueOwner);
    if (!commentController) {
      return;
    }
    if (commentController !== this.S) {
      await this.S?.setActiveCommentAndThread(void 0);
    }
    this.S = commentController;
    return commentController.setActiveCommentAndThread(commentInfo);
  }
  setDocumentComments(resource, commentInfos) {
    this.c.fire({ resource, commentInfos });
  }
  U(ownerId2, owner, ownerLabel, commentThreads) {
    this.D.setCommentThreads(ownerId2, owner, ownerLabel, commentThreads);
    this.f.fire({ ownerId: ownerId2, ownerLabel, commentThreads });
  }
  W(event) {
    this.D.updateCommentThreads(event);
    this.g.fire(event);
  }
  setWorkspaceComments(uniqueOwner, commentsByResource) {
    if (commentsByResource.length) {
      this.y.set(true);
    }
    const control = this.t.get(uniqueOwner);
    if (control) {
      this.U(uniqueOwner, control.owner, control.label, commentsByResource);
    }
  }
  removeWorkspaceComments(uniqueOwner) {
    const control = this.t.get(uniqueOwner);
    if (control) {
      this.U(uniqueOwner, control.owner, control.label, []);
    }
  }
  registerCommentController(uniqueOwner, commentControl) {
    this.t.set(uniqueOwner, commentControl);
    this.a.fire();
  }
  unregisterCommentController(uniqueOwner) {
    if (uniqueOwner) {
      this.t.delete(uniqueOwner);
    } else {
      this.t.clear();
    }
    this.D.deleteCommentsByOwner(uniqueOwner);
    this.b.fire(uniqueOwner);
  }
  getCommentController(uniqueOwner) {
    return this.t.get(uniqueOwner);
  }
  async createCommentThreadTemplate(uniqueOwner, resource, range, editorId) {
    const commentController = this.t.get(uniqueOwner);
    if (!commentController) {
      return;
    }
    return commentController.createCommentThreadTemplate(resource, range, editorId);
  }
  async updateCommentThreadTemplate(uniqueOwner, threadHandle, range) {
    const commentController = this.t.get(uniqueOwner);
    if (!commentController) {
      return;
    }
    await commentController.updateCommentThreadTemplate(threadHandle, range);
  }
  disposeCommentThread(uniqueOwner, threadId) {
    const controller = this.getCommentController(uniqueOwner);
    controller?.deleteCommentThreadMain(threadId);
  }
  getCommentMenus(uniqueOwner) {
    if (this.u.get(uniqueOwner)) {
      return this.u.get(uniqueOwner);
    }
    const menu = this.H.createInstance($NJb);
    this.u.set(uniqueOwner, menu);
    return menu;
  }
  updateComments(ownerId2, event) {
    const control = this.t.get(ownerId2);
    if (control) {
      const evt = Object.assign({}, event, { uniqueOwner: ownerId2, ownerLabel: control.label, owner: control.owner });
      this.W(evt);
    }
  }
  updateNotebookComments(ownerId2, event) {
    const evt = Object.assign({}, event, { uniqueOwner: ownerId2 });
    this.h.fire(evt);
  }
  updateCommentingRanges(ownerId2, resourceHints) {
    if (resourceHints?.schemes && resourceHints.schemes.length > 0) {
      for (const scheme of resourceHints.schemes) {
        this.G.add(scheme);
      }
    }
    this.y.set(true);
    this.j.fire({ uniqueOwner: ownerId2 });
  }
  async toggleReaction(uniqueOwner, resource, thread, comment, reaction) {
    const commentController = this.t.get(uniqueOwner);
    if (commentController) {
      return commentController.toggleReaction(resource, thread, comment, reaction, CancellationToken.None);
    } else {
      throw new Error("Not supported");
    }
  }
  hasReactionHandler(uniqueOwner) {
    const commentProvider = this.t.get(uniqueOwner);
    if (commentProvider) {
      return !!commentProvider.features.reactionHandler;
    }
    return false;
  }
  async getDocumentComments(resource) {
    const commentControlResult = [];
    for (const control of this.t.values()) {
      commentControlResult.push(control.getDocumentComments(resource, CancellationToken.None).then((documentComments) => {
        for (const documentCommentThread of documentComments.threads) {
          if (documentCommentThread.comments?.length === 0 && documentCommentThread.range) {
            this.removeContinueOnComment({ range: documentCommentThread.range, uri: resource, uniqueOwner: documentComments.uniqueOwner });
          }
        }
        const pendingComments = this.z.get(documentComments.uniqueOwner);
        documentComments.pendingCommentThreads = pendingComments?.filter((pendingComment) => pendingComment.uri.toString() === resource.toString());
        return documentComments;
      }).catch((_) => {
        return null;
      }));
    }
    const commentInfos = await Promise.all(commentControlResult);
    this.O(resource, commentInfos);
    return commentInfos;
  }
  async getNotebookComments(resource) {
    const commentControlResult = [];
    this.t.forEach((control) => {
      commentControlResult.push(control.getNotebookComments(resource, CancellationToken.None).catch((_) => {
        return null;
      }));
    });
    return Promise.all(commentControlResult);
  }
  registerContinueOnCommentProvider(provider) {
    this.C.add(provider);
    return {
      dispose: () => {
        this.C.delete(provider);
      }
    };
  }
  X(map) {
    const commentsToSave = [];
    for (const pendingComments of map.values()) {
      commentsToSave.push(...pendingComments);
    }
    this.M.debug(`Comments: URIs of continue on comments to add to storage ${commentsToSave.map((thread) => thread.uri.toString()).join(", ")}.`);
    this.L.store(
      CONTINUE_ON_COMMENTS,
      commentsToSave,
      1,
      0
      /* StorageTarget.USER */
    );
  }
  removeContinueOnComment(pendingComment) {
    const pendingComments = this.z.get(pendingComment.uniqueOwner);
    if (pendingComments) {
      const commentIndex = pendingComments.findIndex((comment) => comment.uri.toString() === pendingComment.uri.toString() && $9C.equalsRange(comment.range, pendingComment.range) && (pendingComment.isReply === void 0 || comment.isReply === pendingComment.isReply));
      if (commentIndex > -1) {
        return pendingComments.splice(commentIndex, 1)[0];
      }
    }
    return void 0;
  }
  Y(pendingComments, map) {
    const changedOwners = /* @__PURE__ */ new Set();
    for (const pendingComment of pendingComments) {
      if (!map.has(pendingComment.uniqueOwner)) {
        map.set(pendingComment.uniqueOwner, [pendingComment]);
        changedOwners.add(pendingComment.uniqueOwner);
      } else {
        const commentsForOwner = map.get(pendingComment.uniqueOwner);
        if (commentsForOwner.every((comment) => comment.uri.toString() !== pendingComment.uri.toString() || !$9C.equalsRange(comment.range, pendingComment.range))) {
          commentsForOwner.push(pendingComment);
          changedOwners.add(pendingComment.uniqueOwner);
        }
      }
    }
    return changedOwners;
  }
  resourceHasCommentingRanges(resource) {
    return this.G.has(resource.scheme) || this.F.has(resource.toString());
  }
};
$SJb = __decorate([
  __param(0, $Pk),
  __param(1, $Vlb),
  __param(2, $kl),
  __param(3, $on),
  __param(4, $jv),
  __param(5, $wn),
  __param(6, $sG)
], $SJb);

// out-build/vs/workbench/contrib/comments/browser/timestamp.js
var $9Jb = class extends $3c {
  constructor(g, hoverService, container2, timeStamp) {
    super();
    this.g = g;
    this.a = $bk(container2, $("span.timestamp"));
    this.a.style.display = "none";
    this.c = this.h;
    this.f = this.B(hoverService.setupManagedHover($JZ("mouse"), this.a, ""));
    this.setTimestamp(timeStamp);
  }
  get h() {
    return this.g.getValue($OJb).useRelativeTime;
  }
  async setTimestamp(timestamp) {
    if (timestamp !== this.b || this.h !== this.c) {
      this.j(timestamp);
    }
    this.b = timestamp;
    this.c = this.h;
  }
  j(timestamp) {
    if (!timestamp) {
      this.a.textContent = "";
      this.a.style.display = "none";
    } else if (timestamp !== this.b || this.h !== this.c) {
      this.a.style.display = "";
      let textContent;
      let tooltip;
      if (this.h) {
        textContent = this.m(timestamp);
        tooltip = this.n(timestamp);
      } else {
        textContent = this.n(timestamp);
      }
      this.a.textContent = textContent;
      this.f.update(tooltip ?? "");
    }
  }
  m(date) {
    return $Qu(date, true, true);
  }
  n(date) {
    return date.toLocaleString($z);
  }
};

// out-build/vs/workbench/contrib/comments/browser/commentColors.js
var resolvedCommentViewIcon = $5n("commentsView.resolvedIcon", { dark: $fo, light: $fo, hcDark: $ko, hcLight: $ko }, localize(5312, null));
var unresolvedCommentViewIcon = $5n("commentsView.unresolvedIcon", { dark: $gr, light: $gr, hcDark: $ko, hcLight: $ko }, localize(5313, null));
$5n("editorCommentsWidget.replyInputBackground", $deb, localize(5314, null));
var resolvedCommentBorder = $5n("editorCommentsWidget.resolvedBorder", { dark: resolvedCommentViewIcon, light: resolvedCommentViewIcon, hcDark: $ko, hcLight: $ko }, localize(5315, null));
var unresolvedCommentBorder = $5n("editorCommentsWidget.unresolvedBorder", { dark: unresolvedCommentViewIcon, light: unresolvedCommentViewIcon, hcDark: $ko, hcLight: $ko }, localize(5316, null));
var $bKb = $5n("editorCommentsWidget.rangeBackground", $0n(unresolvedCommentBorder, 0.1), localize(5317, null));
var $cKb = $5n("editorCommentsWidget.rangeActiveBackground", $0n(unresolvedCommentBorder, 0.1), localize(5318, null));
var commentThreadStateBorderColors = /* @__PURE__ */ new Map([
  [CommentThreadState.Unresolved, unresolvedCommentBorder],
  [CommentThreadState.Resolved, resolvedCommentBorder]
]);
var commentThreadStateIconColors = /* @__PURE__ */ new Map([
  [CommentThreadState.Unresolved, unresolvedCommentViewIcon],
  [CommentThreadState.Resolved, resolvedCommentViewIcon]
]);
var $dKb = "--comment-thread-state-color";
var $eKb = "--comment-view-thread-state-color";
var $fKb = "--comment-thread-state-background-color";
function getCommentThreadStateColor(state, theme, map) {
  const colorId = state !== void 0 ? map.get(state) : void 0;
  return colorId !== void 0 ? theme.getColor(colorId) : void 0;
}
function $gKb(state, theme) {
  return getCommentThreadStateColor(state, theme, commentThreadStateBorderColors);
}
function $hKb(state, theme) {
  return getCommentThreadStateColor(state, theme, commentThreadStateIconColors);
}

// out-build/vs/workbench/contrib/comments/browser/commentsFilterOptions.js
var $$Rb = class {
  static {
    this._filter = $Sl;
  }
  static {
    this._messageFilter = $Rl;
  }
  constructor(filter, showResolved, showUnresolved) {
    this.filter = filter;
    this.showResolved = true;
    this.showUnresolved = true;
    filter = filter.trim();
    this.showResolved = showResolved;
    this.showUnresolved = showUnresolved;
    const negate = filter.startsWith("!");
    this.textFilter = { text: (negate ? $Ff(filter, "!") : filter).trim(), negate };
  }
};

// out-build/vs/workbench/contrib/comments/browser/commentsTreeViewer.js
var $_Rb = "workbench.panel.comments";
var $aSb = "Comments";
var $bSb = localize2(5402, "Comments");
var CommentsModelVirtualDelegate = class _CommentsModelVirtualDelegate {
  static {
    this.a = "resource-with-comments";
  }
  static {
    this.b = "comment-node";
  }
  getHeight(element) {
    if (element instanceof $LJb && element.hasReply()) {
      return 44;
    }
    return 22;
  }
  getTemplateId(element) {
    if (element instanceof $MJb) {
      return _CommentsModelVirtualDelegate.a;
    }
    if (element instanceof $LJb) {
      return _CommentsModelVirtualDelegate.b;
    }
    return "";
  }
};
var $cSb = class {
  constructor(a) {
    this.a = a;
    this.templateId = "resource-with-comments";
  }
  renderTemplate(container2) {
    const labelContainer = $bk(container2, $(".resource-container"));
    const resourceLabel = this.a.create(labelContainer);
    const separator = $bk(labelContainer, $(".separator"));
    const owner = labelContainer.appendChild($(".owner"));
    return { resourceLabel, owner, separator };
  }
  renderElement(node, index, templateData, height) {
    templateData.resourceLabel.setFile(node.element.resource);
    templateData.separator.innerText = "\xB7";
    if (node.element.ownerLabel) {
      templateData.owner.innerText = node.element.ownerLabel;
      templateData.separator.style.display = "inline";
    } else {
      templateData.owner.innerText = "";
      templateData.separator.style.display = "none";
    }
  }
  disposeTemplate(templateData) {
    templateData.resourceLabel.dispose();
  }
};
var $dSb = class $dSb2 {
  constructor(b) {
    this.b = b;
  }
  getResourceActions(element) {
    const actions = this.c($bJ.CommentsViewThreadActions, element);
    return { actions: actions.primary };
  }
  getResourceContextActions(element) {
    return this.c($bJ.CommentsViewThreadActions, element).secondary;
  }
  setContextKeyService(service) {
    this.a = service;
  }
  c(menuId, element) {
    if (!this.a) {
      return { primary: [], secondary: [] };
    }
    const overlay = [
      ["commentController", element.owner],
      ["resourceScheme", element.resource.scheme],
      ["commentThread", element.contextValue],
      ["canReply", element.thread.canReply]
    ];
    const contextKeyService = this.a.createOverlay(overlay);
    const menu = this.b.getMenuActions(menuId, contextKeyService, { shouldForwardArgs: true });
    return $O$(menu, "inline");
  }
  dispose() {
    this.a = void 0;
  }
};
$dSb = __decorate([
  __param(0, $cJ)
], $dSb);
var $eSb = class $eSb2 {
  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;
    this.templateId = "comment-node";
  }
  renderTemplate(container2) {
    const threadContainer = $bk(container2, $(".comment-thread-container"));
    const metadataContainer = $bk(threadContainer, $(".comment-metadata-container"));
    const metadata = $bk(metadataContainer, $(".comment-metadata"));
    const threadMetadata = {
      icon: $bk(metadata, $(".icon")),
      userNames: $bk(metadata, $(".user")),
      timestamp: new $9Jb(this.d, this.f, $bk(metadata, $(".timestamp-container"))),
      relevance: $bk(metadata, $(".relevance")),
      separator: $bk(metadata, $(".separator")),
      commentPreview: $bk(metadata, $(".text")),
      range: $bk(metadata, $(".range"))
    };
    threadMetadata.separator.innerText = "\xB7";
    const actionsContainer = $bk(metadataContainer, $(".actions"));
    const actionBar = new $LZ(actionsContainer, {
      actionViewItemProvider: this.a
    });
    const snippetContainer = $bk(threadContainer, $(".comment-snippet-container"));
    const repliesMetadata = {
      container: snippetContainer,
      icon: $bk(snippetContainer, $(".icon")),
      count: $bk(snippetContainer, $(".count")),
      lastReplyDetail: $bk(snippetContainer, $(".reply-detail")),
      separator: $bk(snippetContainer, $(".separator")),
      timestamp: new $9Jb(this.d, this.f, $bk(snippetContainer, $(".timestamp-container")))
    };
    repliesMetadata.separator.innerText = "\xB7";
    repliesMetadata.icon.classList.add(...ThemeIcon.asClassNameArray($6l.indent));
    const disposables = [threadMetadata.timestamp, repliesMetadata.timestamp];
    return { threadMetadata, repliesMetadata, actionBar, disposables };
  }
  h(commentCount) {
    if (commentCount > 2) {
      return localize(5393, null, commentCount - 1);
    } else if (commentCount === 2) {
      return localize(5394, null);
    } else {
      return localize(5395, null);
    }
  }
  j(commentBody, disposables) {
    const renderedComment = $D1(commentBody, {
      inline: true,
      actionHandler: {
        callback: (link2) => $R_(this.c, link2, commentBody.isTrusted),
        disposables
      }
    });
    const images = renderedComment.element.getElementsByTagName("img");
    for (let i2 = 0; i2 < images.length; i2++) {
      const image = images[i2];
      const textDescription = $("");
      textDescription.textContent = image.alt ? localize(5396, null, image.alt) : localize(5397, null);
      image.parentNode.replaceChild(textDescription, image);
    }
    while (renderedComment.element.children.length > 1 && renderedComment.element.firstElementChild?.tagName === "HR") {
      renderedComment.element.removeChild(renderedComment.element.firstElementChild);
    }
    return renderedComment;
  }
  k(threadState) {
    if (threadState === CommentThreadState.Unresolved) {
      return $6l.commentUnresolved;
    } else {
      return $6l.comment;
    }
  }
  renderElement(node, index, templateData, height) {
    templateData.actionBar.clear();
    const commentCount = node.element.replies.length + 1;
    if (node.element.threadRelevance === CommentThreadApplicability.Outdated) {
      templateData.threadMetadata.relevance.style.display = "";
      templateData.threadMetadata.relevance.innerText = localize(5398, null);
      templateData.threadMetadata.separator.style.display = "none";
    } else {
      templateData.threadMetadata.relevance.innerText = "";
      templateData.threadMetadata.relevance.style.display = "none";
      templateData.threadMetadata.separator.style.display = "";
    }
    templateData.threadMetadata.icon.classList.remove(...Array.from(templateData.threadMetadata.icon.classList.values()).filter((value) => value.startsWith("codicon")));
    templateData.threadMetadata.icon.classList.add(...ThemeIcon.asClassNameArray(this.k(node.element.threadState)));
    if (node.element.threadState !== void 0) {
      const color2 = this.l(node.element.threadState, this.g.getColorTheme());
      templateData.threadMetadata.icon.style.setProperty($eKb, `${color2}`);
      templateData.threadMetadata.icon.style.color = `var(${$eKb})`;
    }
    templateData.threadMetadata.userNames.textContent = node.element.comment.userName;
    templateData.threadMetadata.timestamp.setTimestamp(node.element.comment.timestamp ? new Date(node.element.comment.timestamp) : void 0);
    const originalComment = node.element;
    templateData.threadMetadata.commentPreview.innerText = "";
    templateData.threadMetadata.commentPreview.style.height = "22px";
    if (typeof originalComment.comment.body === "string") {
      templateData.threadMetadata.commentPreview.innerText = originalComment.comment.body;
    } else {
      const disposables = new $2c();
      templateData.disposables.push(disposables);
      const renderedComment = this.j(originalComment.comment.body, disposables);
      templateData.disposables.push(renderedComment);
      templateData.threadMetadata.commentPreview.appendChild(renderedComment.element.firstElementChild ?? renderedComment.element);
      templateData.disposables.push(this.f.setupManagedHover($JZ("mouse"), templateData.threadMetadata.commentPreview, renderedComment.element.textContent ?? ""));
    }
    if (node.element.range) {
      if (node.element.range.startLineNumber === node.element.range.endLineNumber) {
        templateData.threadMetadata.range.textContent = localize(5399, null, node.element.range.startLineNumber);
      } else {
        templateData.threadMetadata.range.textContent = localize(5400, null, node.element.range.startLineNumber, node.element.range.endLineNumber);
      }
    }
    const menuActions = this.b.getResourceActions(node.element);
    templateData.actionBar.push(menuActions.actions, { icon: true, label: false });
    templateData.actionBar.context = {
      commentControlHandle: node.element.controllerHandle,
      commentThreadHandle: node.element.threadHandle,
      $mid: 7
      /* MarshalledId.CommentThread */
    };
    if (!node.element.hasReply()) {
      templateData.repliesMetadata.container.style.display = "none";
      return;
    }
    templateData.repliesMetadata.container.style.display = "";
    templateData.repliesMetadata.count.textContent = this.h(commentCount);
    const lastComment = node.element.replies[node.element.replies.length - 1].comment;
    templateData.repliesMetadata.lastReplyDetail.textContent = localize(5401, null, lastComment.userName);
    templateData.repliesMetadata.timestamp.setTimestamp(lastComment.timestamp ? new Date(lastComment.timestamp) : void 0);
  }
  l(state, theme) {
    return state !== void 0 ? $hKb(state, theme) : void 0;
  }
  disposeTemplate(templateData) {
    templateData.disposables.forEach((disposeable) => disposeable.dispose());
    templateData.actionBar.dispose();
  }
};
$eSb = __decorate([
  __param(2, $O4),
  __param(3, $kl),
  __param(4, $5$),
  __param(5, $gs)
], $eSb);
var FilterDataType;
(function(FilterDataType3) {
  FilterDataType3[FilterDataType3["Resource"] = 0] = "Resource";
  FilterDataType3[FilterDataType3["Comment"] = 1] = "Comment";
})(FilterDataType || (FilterDataType = {}));
var $fSb = class {
  constructor(options3) {
    this.options = options3;
  }
  filter(element, parentVisibility) {
    if (this.options.filter === "" && this.options.showResolved && this.options.showUnresolved) {
      return 1;
    }
    if (element instanceof $MJb) {
      return this.a(element);
    } else {
      return this.b(element, parentVisibility);
    }
  }
  a(resourceMarkers) {
    if (this.options.textFilter.text && !this.options.textFilter.negate) {
      const uriMatches = $$Rb._filter(this.options.textFilter.text, $sh(resourceMarkers.resource));
      if (uriMatches) {
        return { visibility: true, data: { type: 0, uriMatches: uriMatches || [] } };
      }
    }
    return 2;
  }
  b(comment, parentVisibility) {
    const matchesResolvedState = comment.threadState === void 0 || this.options.showResolved && CommentThreadState.Resolved === comment.threadState || this.options.showUnresolved && CommentThreadState.Unresolved === comment.threadState;
    if (!matchesResolvedState) {
      return false;
    }
    if (!this.options.textFilter.text) {
      return true;
    }
    const textMatches = (
      // Check body of comment for value
      $$Rb._messageFilter(this.options.textFilter.text, typeof comment.comment.body === "string" ? comment.comment.body : comment.comment.body.value) || $$Rb._messageFilter(this.options.textFilter.text, comment.comment.userName) || comment.replies.map((reply) => {
        return $$Rb._messageFilter(this.options.textFilter.text, reply.comment.userName) || $$Rb._messageFilter(this.options.textFilter.text, typeof reply.comment.body === "string" ? reply.comment.body : reply.comment.body.value);
      }).filter((value) => !!value).flat()
    );
    if (textMatches.length && !this.options.textFilter.negate) {
      return { visibility: true, data: { type: 1, textMatches } };
    }
    if (textMatches.length && this.options.textFilter.negate && parentVisibility === 2) {
      return false;
    }
    if (textMatches.length === 0 && this.options.textFilter.negate && parentVisibility === 2) {
      return true;
    }
    return parentVisibility;
  }
};
var $gSb = class $gSb2 extends $1eb {
  constructor(labels2, container2, options3, contextKeyService, listService, instantiationService, configurationService, b, c) {
    const delegate = new CommentsModelVirtualDelegate();
    const actionViewItemProvider = $X$.bind(void 0, instantiationService);
    const menus = instantiationService.createInstance($dSb);
    menus.setContextKeyService(contextKeyService);
    const renderers = [
      instantiationService.createInstance($cSb, labels2),
      instantiationService.createInstance($eSb, actionViewItemProvider, menus)
    ];
    super("CommentsTree", container2, delegate, renderers, {
      accessibilityProvider: options3.accessibilityProvider,
      identityProvider: {
        getId: (element) => {
          if (element instanceof $QJb) {
            return "root";
          }
          if (element instanceof $MJb) {
            return `${element.uniqueOwner}-${element.id}`;
          }
          if (element instanceof $LJb) {
            return `${element.uniqueOwner}-${element.resource.toString()}-${element.threadId}-${element.comment.uniqueIdInThread}` + (element.isRoot ? "-root" : "");
          }
          return "";
        }
      },
      expandOnlyOnTwistieClick: true,
      collapseByDefault: false,
      overrideStyles: options3.overrideStyles,
      filter: options3.filter,
      sorter: options3.sorter,
      findWidgetEnabled: false,
      multipleSelectionSupport: false
    }, instantiationService, contextKeyService, listService, configurationService);
    this.b = b;
    this.c = c;
    this.a = menus;
    this.E.add(this.onContextMenu((e) => this.f(e)));
  }
  f(treeEvent) {
    const node = treeEvent.element;
    if (!(node instanceof $LJb)) {
      return;
    }
    const event = treeEvent.browserEvent;
    event.preventDefault();
    event.stopPropagation();
    this.setFocus([node]);
    const actions = this.a.getResourceContextActions(node);
    if (!actions.length) {
      return;
    }
    this.b.showContextMenu({
      getAnchor: () => treeEvent.anchor,
      getActions: () => actions,
      getActionViewItem: (action) => {
        const keybinding = this.c.lookupKeybinding(action.id);
        if (keybinding) {
          return new $U1(action, action, { label: true, keybinding: keybinding.getLabel() });
        }
        return void 0;
      },
      onHide: (wasCancelled) => {
        if (wasCancelled) {
          this.domFocus();
        }
      },
      getActionsContext: () => ({
        commentControlHandle: node.controllerHandle,
        commentThreadHandle: node.threadHandle,
        $mid: 7,
        thread: node.thread
      })
    });
  }
  filterComments() {
    this.refilter();
  }
  getVisibleItemCount() {
    let filtered = 0;
    const root = this.getNode();
    for (const resourceNode of root.children) {
      for (const commentNode of resourceNode.children) {
        if (commentNode.visible && resourceNode.visible) {
          filtered++;
        }
      }
    }
    return filtered;
  }
};
$gSb = __decorate([
  __param(3, $on),
  __param(4, $Deb),
  __param(5, $Pk),
  __param(6, $kl),
  __param(7, $50),
  __param(8, $Ty)
], $gSb);

// out-build/vs/workbench/contrib/comments/browser/comments.js
var $iSb = new $nn("commentsFilterFocus", false);

// out-build/vs/workbench/contrib/comments/browser/commentsViewActions.js
var CommentsSortOrder;
(function(CommentsSortOrder2) {
  CommentsSortOrder2["ResourceAscending"] = "resourceAscending";
  CommentsSortOrder2["UpdatedAtDescending"] = "updatedAtDescending";
})(CommentsSortOrder || (CommentsSortOrder = {}));
var CONTEXT_KEY_SHOW_RESOLVED = new $nn("commentsView.showResolvedFilter", true);
var CONTEXT_KEY_SHOW_UNRESOLVED = new $nn("commentsView.showUnResolvedFilter", true);
var CONTEXT_KEY_SORT_BY = new $nn(
  "commentsView.sortBy",
  "resourceAscending"
  /* CommentsSortOrder.ResourceAscending */
);
var $hSb = class extends $3c {
  constructor(options3, b) {
    super();
    this.b = b;
    this.a = this.B(new $ze());
    this.onDidChange = this.a.event;
    this.c = CONTEXT_KEY_SHOW_UNRESOLVED.bindTo(this.b);
    this.f = CONTEXT_KEY_SHOW_RESOLVED.bindTo(this.b);
    this.g = CONTEXT_KEY_SORT_BY.bindTo(this.b);
    this.f.set(options3.showResolved);
    this.c.set(options3.showUnresolved);
    this.g.set(options3.sortBy);
  }
  get showUnresolved() {
    return !!this.c.get();
  }
  set showUnresolved(showUnresolved) {
    if (this.c.get() !== showUnresolved) {
      this.c.set(showUnresolved);
      this.a.fire({ showUnresolved: true });
    }
  }
  get showResolved() {
    return !!this.f.get();
  }
  set showResolved(showResolved) {
    if (this.f.get() !== showResolved) {
      this.f.set(showResolved);
      this.a.fire({ showResolved: true });
    }
  }
  get sortBy() {
    return this.g.get() ?? "resourceAscending";
  }
  set sortBy(sortBy) {
    if (this.g.get() !== sortBy) {
      this.g.set(sortBy);
      this.a.fire({ sortBy });
    }
  }
};
$hJ(class extends $cpb {
  constructor() {
    super({
      id: "commentsFocusViewFromFilter",
      title: localize(5416, null),
      keybinding: {
        when: $iSb,
        weight: 200,
        primary: 2048 | 18
        /* KeyCode.DownArrow */
      },
      viewId: $_Rb
    });
  }
  async runInView(serviceAccessor, commentsView) {
    commentsView.focus();
  }
});
$hJ(class extends $cpb {
  constructor() {
    super({
      id: "commentsClearFilterText",
      title: localize(5417, null),
      keybinding: {
        when: $iSb,
        weight: 200,
        primary: 9
        /* KeyCode.Escape */
      },
      viewId: $_Rb
    });
  }
  async runInView(serviceAccessor, commentsView) {
    commentsView.clearFilterText();
  }
});
$hJ(class extends $cpb {
  constructor() {
    super({
      id: "commentsFocusFilter",
      title: localize(5418, null),
      keybinding: {
        when: $jqb.isEqualTo($_Rb),
        weight: 200,
        primary: 2048 | 36
        /* KeyCode.KeyF */
      },
      viewId: $_Rb
    });
  }
  async runInView(serviceAccessor, commentsView) {
    commentsView.focusFilter();
  }
});
$hJ(class extends $cpb {
  constructor() {
    super({
      id: `workbench.actions.${$_Rb}.toggleUnResolvedComments`,
      title: localize(5419, null),
      category: localize(5420, null),
      toggled: {
        condition: CONTEXT_KEY_SHOW_UNRESOLVED,
        title: localize(5421, null)
      },
      menu: {
        id: $7ob,
        group: "1_filter",
        when: $7m.equals("view", $_Rb),
        order: 1
      },
      viewId: $_Rb
    });
  }
  async runInView(serviceAccessor, view) {
    view.filters.showUnresolved = !view.filters.showUnresolved;
  }
});
$hJ(class extends $cpb {
  constructor() {
    super({
      id: `workbench.actions.${$_Rb}.toggleResolvedComments`,
      title: localize(5422, null),
      category: localize(5423, null),
      toggled: {
        condition: CONTEXT_KEY_SHOW_RESOLVED,
        title: localize(5424, null)
      },
      menu: {
        id: $7ob,
        group: "1_filter",
        when: $7m.equals("view", $_Rb),
        order: 1
      },
      viewId: $_Rb
    });
  }
  async runInView(serviceAccessor, view) {
    view.filters.showResolved = !view.filters.showResolved;
  }
});
var commentSortSubmenu = new $bJ("submenu.filter.commentSort");
$dJ.appendMenuItem($7ob, {
  submenu: commentSortSubmenu,
  title: localize(5425, null),
  group: "2_sort",
  icon: $6l.history,
  when: $7m.equals("view", $_Rb)
});
$hJ(class extends $cpb {
  constructor() {
    super({
      id: `workbench.actions.${$_Rb}.toggleSortByUpdatedAt`,
      title: localize(5426, null),
      category: localize(5427, null),
      icon: $6l.history,
      viewId: $_Rb,
      toggled: {
        condition: $7m.equals(
          CONTEXT_KEY_SORT_BY.key,
          "updatedAtDescending"
          /* CommentsSortOrder.UpdatedAtDescending */
        ),
        title: localize(5428, null)
      },
      menu: {
        id: commentSortSubmenu,
        group: "navigation",
        order: 1,
        isHiddenByDefault: false
      }
    });
  }
  async runInView(serviceAccessor, view) {
    view.filters.sortBy = "updatedAtDescending";
  }
});
$hJ(class extends $cpb {
  constructor() {
    super({
      id: `workbench.actions.${$_Rb}.toggleSortByResource`,
      title: localize(5429, null),
      category: localize(5430, null),
      icon: $6l.history,
      viewId: $_Rb,
      toggled: {
        condition: $7m.equals(
          CONTEXT_KEY_SORT_BY.key,
          "resourceAscending"
          /* CommentsSortOrder.ResourceAscending */
        ),
        title: localize(5431, null)
      },
      menu: {
        id: commentSortSubmenu,
        group: "navigation",
        order: 0,
        isHiddenByDefault: false
      }
    });
  }
  async runInView(serviceAccessor, view) {
    view.filters.sortBy = "resourceAscending";
  }
});

// out-build/vs/workbench/contrib/comments/browser/commentGlyphWidget.js
var $jSb = $5n("editorGutter.commentRangeForeground", { dark: $$n($lr, $Ko), light: $8n($$n($lr, $Ko), 0.05), hcDark: $Vn.white, hcLight: $Vn.black }, localize(5319, null));
var overviewRulerCommentForeground = $5n("editorOverviewRuler.commentForeground", $jSb, localize(5320, null));
var overviewRulerCommentUnresolvedForeground = $5n("editorOverviewRuler.commentUnresolvedForeground", overviewRulerCommentForeground, localize(5321, null));
var editorGutterCommentGlyphForeground = $5n("editorGutter.commentGlyphForeground", { dark: $Lo, light: $Lo, hcDark: $Vn.black, hcLight: $Vn.white }, localize(5322, null));
$5n("editorGutter.commentUnresolvedGlyphForeground", editorGutterCommentGlyphForeground, localize(5323, null));
var $kSb = class _$kSb extends $3c {
  static {
    this.description = "comment-glyph-widget";
  }
  constructor(editor, lineNumber) {
    super();
    this.h = this.B(new $ze());
    this.onDidChangeLineNumber = this.h.event;
    this.g = this.j();
    this.b = editor;
    this.f = this.b.createDecorationsCollection();
    this.B(this.f.onDidChange((e) => {
      const range = this.f.length > 0 ? this.f.getRange(0) : null;
      if (range && range.endLineNumber !== this.a) {
        this.a = range.endLineNumber;
        this.h.fire(this.a);
      }
    }));
    this.B($1c(() => this.f.clear()));
    this.setLineNumber(lineNumber);
  }
  j() {
    const unresolved = this.c === CommentThreadState.Unresolved;
    const decorationOptions = {
      description: _$kSb.description,
      isWholeLine: true,
      overviewRuler: {
        color: $hs(unresolved ? overviewRulerCommentUnresolvedForeground : overviewRulerCommentForeground),
        position: OverviewRulerLane.Center
      },
      collapseOnReplaceEdit: true,
      linesDecorationsClassName: `comment-range-glyph comment-thread${unresolved ? "-unresolved" : ""}`
    };
    return $WI.createDynamic(decorationOptions);
  }
  setThreadState(state) {
    if (this.c !== state) {
      this.c = state;
      this.g = this.j();
      this.m();
    }
  }
  m() {
    const commentsDecorations = [{
      range: {
        startLineNumber: this.a,
        startColumn: 1,
        endLineNumber: this.a,
        endColumn: 1
      },
      options: this.g
    }];
    this.f.set(commentsDecorations);
  }
  setLineNumber(lineNumber) {
    this.a = lineNumber;
    this.m();
  }
  getPosition() {
    const range = this.f.length > 0 ? this.f.getRange(0) : null;
    return {
      position: {
        lineNumber: range ? range.endLineNumber : this.a,
        column: 1
      },
      preference: [
        0
        /* ContentWidgetPositionPreference.EXACT */
      ]
    };
  }
};

// out-build/vs/workbench/contrib/comments/browser/commentFormActions.js
var $TJb = class {
  constructor(e, f, g, h3, i2, j, k) {
    this.e = e;
    this.f = f;
    this.g = g;
    this.h = h3;
    this.i = i2;
    this.j = j;
    this.k = k;
    this.a = [];
    this.c = new $2c();
    this.d = [];
  }
  setActions(menu, hasOnlySecondaryActions = false) {
    this.c.clear();
    this.a.forEach((b) => b.remove());
    this.a = [];
    const groups = menu.getActions({ shouldForwardArgs: true });
    let isPrimary = !hasOnlySecondaryActions;
    for (const group2 of groups) {
      const [, actions] = group2;
      this.d = actions;
      for (const current of actions) {
        const dropDownActions = this.k && current instanceof $eJ ? current.actions : [];
        const action = dropDownActions.length ? dropDownActions[0] : current;
        let keybinding = this.e.lookupKeybinding(action.id, this.f)?.getLabel();
        if (!keybinding && isPrimary) {
          keybinding = this.e.lookupKeybinding("editor.action.submitComment", this.f)?.getLabel();
        }
        const title = keybinding ? `${action.label} (${keybinding})` : action.label;
        const actionHandler = this.i;
        const button = dropDownActions.length ? new $l2(this.h, {
          contextMenuProvider: this.g,
          actions: dropDownActions,
          actionRunner: new class extends $Vm {
            async u(action2, context) {
              return actionHandler(action2);
            }
          }(),
          secondary: !isPrimary,
          title,
          addPrimaryActionToDropdown: false,
          ...$q$
        }) : new $k2(this.h, { secondary: !isPrimary, title, ...$q$ });
        isPrimary = false;
        this.a.push(button.element);
        this.c.add(button);
        this.c.add(button.onDidClick(() => this.i(action)));
        button.enabled = action.enabled;
        button.label = action.label;
        if (this.j !== void 0 && this.a.length >= this.j) {
          console.warn(`An extension has contributed more than the allowable number of actions to a comments menu.`);
          return;
        }
      }
    }
  }
  triggerDefaultAction() {
    if (this.d.length) {
      const lastAction = this.d[0];
      if (lastAction.enabled) {
        return this.i(lastAction);
      }
    }
  }
  dispose() {
    this.c.dispose();
  }
};

// out-build/vs/workbench/contrib/codeEditor/browser/dictation/editorDictation.js
var $XJb_1;
var EDITOR_DICTATION_IN_PROGRESS = new $nn("editorDictation.inProgress", false);
var VOICE_CATEGORY = localize2(5171, "Voice");
var $UJb = class extends $25 {
  constructor() {
    super({
      id: "workbench.action.editorDictation.start",
      title: localize2(5172, "Start Dictation in Editor"),
      category: VOICE_CATEGORY,
      precondition: $7m.and(
        $kS,
        $lS.toNegated(),
        // disable when any speech-to-text is in progress
        EditorContextKeys.readOnly.toNegated()
        // disable in read-only editors
      ),
      f1: true,
      keybinding: {
        primary: 2048 | 512 | 52,
        weight: 200,
        secondary: $l ? [
          512 | 91
          /* KeyCode.Backquote */
        ] : void 0
      }
    });
  }
  runEditorCommand(accessor, editor) {
    const keybindingService = accessor.get($Ty);
    const holdMode = keybindingService.enableKeybindingHoldMode(this.desc.id);
    if (holdMode) {
      let shouldCallStop = false;
      const handle2 = setTimeout(() => {
        shouldCallStop = true;
      }, 500);
      holdMode.finally(() => {
        clearTimeout(handle2);
        if (shouldCallStop) {
          $XJb.get(editor)?.stop();
        }
      });
    }
    $XJb.get(editor)?.start();
  }
};
var $VJb = class _$VJb extends $25 {
  static {
    this.ID = "workbench.action.editorDictation.stop";
  }
  constructor() {
    super({
      id: _$VJb.ID,
      title: localize2(5173, "Stop Dictation in Editor"),
      category: VOICE_CATEGORY,
      precondition: EDITOR_DICTATION_IN_PROGRESS,
      f1: true,
      keybinding: {
        primary: 9,
        weight: 200 + 100
      }
    });
  }
  runEditorCommand(_accessor, editor) {
    $XJb.get(editor)?.stop();
  }
};
var $WJb = class extends $3c {
  constructor(b, keybindingService) {
    super();
    this.b = b;
    this.suppressMouseDown = true;
    this.allowEditorOverflow = true;
    this.a = document.createElement("div");
    const actionBar = this.B(new $LZ(this.a));
    const stopActionKeybinding = keybindingService.lookupKeybinding($VJb.ID)?.getLabel();
    actionBar.push($Zm({
      id: $VJb.ID,
      label: stopActionKeybinding ? localize(5169, null, stopActionKeybinding) : localize(5170, null),
      class: ThemeIcon.asClassName($6l.micFilled),
      run: () => $XJb.get(b)?.stop()
    }), { icon: true, label: false, keybinding: stopActionKeybinding });
    this.a.classList.add("editor-dictation-widget");
    this.a.appendChild(actionBar.domNode);
  }
  getId() {
    return "editorDictation";
  }
  getDomNode() {
    return this.a;
  }
  getPosition() {
    if (!this.b.hasModel()) {
      return null;
    }
    const selection = this.b.getSelection();
    return {
      position: selection.getPosition(),
      preference: [
        selection.getPosition().equals(selection.getStartPosition()) ? 1 : 2,
        0
        /* ContentWidgetPositionPreference.EXACT */
      ]
    };
  }
  beforeRender() {
    const lineHeight = this.b.getOption(
      68
      /* EditorOption.lineHeight */
    );
    const width2 = this.b.getLayoutInfo().contentWidth * 0.7;
    this.a.style.setProperty("--vscode-editor-dictation-widget-height", `${lineHeight}px`);
    this.a.style.setProperty("--vscode-editor-dictation-widget-width", `${width2}px`);
    return null;
  }
  show() {
    this.b.addContentWidget(this);
  }
  layout() {
    this.b.layoutContentWidget(this);
  }
  active() {
    this.a.classList.add("recording");
  }
  hide() {
    this.a.classList.remove("recording");
    this.b.removeContentWidget(this);
  }
};
var $XJb = class $XJb2 extends $3c {
  static {
    $XJb_1 = this;
  }
  static {
    this.ID = "editorDictation";
  }
  static get(editor) {
    return editor.getContribution($XJb_1.ID);
  }
  constructor(f, g, h3, j) {
    super();
    this.f = f;
    this.g = g;
    this.h = h3;
    this.j = j;
    this.a = this.B(new $WJb(this.f, this.j));
    this.b = EDITOR_DICTATION_IN_PROGRESS.bindTo(this.h);
    this.c = this.B(new $4c());
  }
  async start() {
    const disposables = new $2c();
    this.c.value = disposables;
    this.a.show();
    disposables.add($1c(() => this.a.hide()));
    this.b.set(true);
    disposables.add($1c(() => this.b.reset()));
    const collection = this.f.createDecorationsCollection();
    disposables.add($1c(() => collection.clear()));
    disposables.add(this.f.onDidChangeCursorPosition(() => this.a.layout()));
    let previewStart = void 0;
    let lastReplaceTextLength = 0;
    const replaceText = (text2, isPreview) => {
      if (!previewStart) {
        previewStart = $Kg(this.f.getPosition());
      }
      const endPosition = new $8C(previewStart.lineNumber, previewStart.column + text2.length);
      this.f.executeEdits($XJb_1.ID, [
        $bD.replace($9C.fromPositions(previewStart, previewStart.with(void 0, previewStart.column + lastReplaceTextLength)), text2)
      ], [
        $_D.fromPositions(endPosition)
      ]);
      if (isPreview) {
        collection.set([
          {
            range: $9C.fromPositions(previewStart, previewStart.with(void 0, previewStart.column + text2.length)),
            options: {
              description: "editor-dictation-preview",
              inlineClassName: "ghost-text-decoration-preview"
            }
          }
        ]);
      } else {
        collection.clear();
      }
      lastReplaceTextLength = text2.length;
      if (!isPreview) {
        previewStart = void 0;
        lastReplaceTextLength = 0;
      }
      this.f.revealPositionInCenterIfOutsideViewport(endPosition);
    };
    const cts = new $ad();
    disposables.add($1c(() => cts.dispose(true)));
    const session = await this.g.createSpeechToTextSession(cts.token, "editor");
    disposables.add(session.onDidChange((e) => {
      if (cts.token.isCancellationRequested) {
        return;
      }
      switch (e.status) {
        case SpeechToTextStatus2.Started:
          this.a.active();
          break;
        case SpeechToTextStatus2.Stopped:
          disposables.dispose();
          break;
        case SpeechToTextStatus2.Recognizing: {
          if (!e.text) {
            return;
          }
          replaceText(e.text, true);
          break;
        }
        case SpeechToTextStatus2.Recognized: {
          if (!e.text) {
            return;
          }
          replaceText(`${e.text} `, false);
          break;
        }
      }
    }));
  }
  stop() {
    this.c.clear();
  }
};
$XJb = $XJb_1 = __decorate([
  __param(1, $jS),
  __param(2, $on),
  __param(3, $Ty)
], $XJb);
$85(
  $XJb.ID,
  $XJb,
  4
  /* EditorContributionInstantiation.Lazy */
);
$hJ($UJb);
$hJ($VJb);

// out-build/vs/workbench/contrib/comments/browser/simpleCommentEditor.js
var $YJb = new $nn("commentEditorFocused", false);
var $ZJb = 5 * 18;
var $1Jb = 25 * 18;
var $2Jb = class $2Jb2 extends $D9 {
  constructor(domElement, options3, scopedContextKeyService, parentThread, instantiationService, codeEditorService, commandService, themeService, notificationService, accessibilityService, languageConfigurationService, languageFeaturesService) {
    const codeEditorWidgetOptions = {
      contributions: [
        {
          id: $Esb.ID,
          ctor: $Esb,
          instantiation: 2
          /* EditorContributionInstantiation.BeforeFirstInteraction */
        },
        {
          id: $Mfb.ID,
          ctor: $Mfb,
          instantiation: 2
          /* EditorContributionInstantiation.BeforeFirstInteraction */
        },
        {
          id: $qdb.ID,
          ctor: $qdb,
          instantiation: 0
          /* EditorContributionInstantiation.Eager */
        },
        {
          id: $Dcb.ID,
          ctor: $Dcb,
          instantiation: 4
          /* EditorContributionInstantiation.Lazy */
        },
        {
          id: $Ysb.ID,
          ctor: $Ysb,
          instantiation: 0
          /* EditorContributionInstantiation.Eager */
        },
        // eager because it needs to define a context key
        {
          id: $XJb.ID,
          ctor: $XJb,
          instantiation: 4
          /* EditorContributionInstantiation.Lazy */
        },
        ...EditorExtensionsRegistry.getSomeEditorContributions([
          $iab.ID,
          $Yfb.ID,
          $Ajb.ID,
          $S_.ID,
          $Afb.ID,
          $Fib.ID,
          $Fsb,
          $3hb.ID,
          $fbb.ID,
          $Yjb.ID
        ])
      ],
      contextMenuId: $bJ.SimpleEditorContext
    };
    super(domElement, options3, codeEditorWidgetOptions, instantiationService, codeEditorService, commandService, scopedContextKeyService, themeService, notificationService, accessibilityService, languageConfigurationService, languageFeaturesService);
    this.mc = $YJb.bindTo(scopedContextKeyService);
    this.nc = CommentContextKeys.commentIsEmpty.bindTo(scopedContextKeyService);
    this.nc.set(!this.getModel()?.getValueLength());
    this.kb = parentThread;
    this.B(this.onDidFocusEditorWidget((_) => this.mc.set(true)));
    this.B(this.onDidChangeModelContent((e) => this.nc.set(!this.getModel()?.getValueLength())));
    this.B(this.onDidBlurEditorWidget((_) => this.mc.reset()));
  }
  getParentThread() {
    return this.kb;
  }
  oc() {
    return EditorExtensionsRegistry.getEditorActions();
  }
  updateOptions(newOptions) {
    const withLineNumberRemoved = { ...newOptions, lineNumbers: "off" };
    super.updateOptions(withLineNumberRemoved);
  }
  static getEditorOptions(configurationService) {
    return {
      wordWrap: "on",
      glyphMargin: false,
      lineNumbers: "off",
      folding: false,
      selectOnLineNumbers: false,
      scrollbar: {
        vertical: "visible",
        verticalScrollbarSize: 14,
        horizontal: "auto",
        useShadows: true,
        verticalHasArrows: false,
        horizontalHasArrows: false,
        alwaysConsumeMouseWheel: false
      },
      overviewRulerLanes: 2,
      lineDecorationsWidth: 0,
      scrollBeyondLastLine: false,
      renderLineHighlight: "none",
      fixedOverflowWidgets: true,
      acceptSuggestionOnEnter: "smart",
      minimap: {
        enabled: false
      },
      dropIntoEditor: { enabled: true },
      autoClosingBrackets: configurationService.getValue("editor.autoClosingBrackets"),
      quickSuggestions: false,
      accessibilitySupport: configurationService.getValue("editor.accessibilitySupport"),
      fontFamily: configurationService.getValue("editor.fontFamily"),
      fontSize: configurationService.getValue("editor.fontSize")
    };
  }
};
$2Jb = __decorate([
  __param(4, $Pk),
  __param(5, $U5),
  __param(6, $sn),
  __param(7, $gs),
  __param(8, $PJ),
  __param(9, $ND),
  __param(10, $NF),
  __param(11, $mP)
], $2Jb);
function $3Jb(parentEditor, editor, currentHeight) {
  const layoutInfo = editor.getLayoutInfo();
  const lineHeight = editor.getOption(
    68
    /* EditorOption.lineHeight */
  );
  const contentHeight = editor._getViewModel()?.getLineCount() * lineHeight;
  if (contentHeight > layoutInfo.height || contentHeight < layoutInfo.height && currentHeight > $ZJb) {
    const linesToAdd = Math.ceil((contentHeight - layoutInfo.height) / lineHeight);
    const proposedHeight = layoutInfo.height + lineHeight * linesToAdd;
    return $4i(proposedHeight, $ZJb, $4i(parentEditor.getLayoutInfo().height - 90, $ZJb, $1Jb));
  }
  return currentHeight;
}

// out-build/vs/workbench/contrib/comments/browser/commentReply.js
var INMEM_MODEL_ID = 0;
var $4Jb = "commenteditordecoration";
var $5Jb = class $5Jb2 extends $3c {
  constructor(owner, container2, n, r2, s, t, u, w, y, z, focus, C, D, configurationService, F, G, H, I) {
    super();
    this.owner = owner;
    this.n = n;
    this.r = r2;
    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 = G;
    this.H = H;
    this.I = I;
    this.f = [];
    this.m = $ZJb;
    this.form = $bk(container2, $(".comment-form"));
    this.commentEditor = this.B(this.s.createInstance($2Jb, this.form, $2Jb.getEditorOptions(configurationService), t, this.z));
    this.commentEditorIsEmpty = CommentContextKeys.commentIsEmpty.bindTo(this.t);
    this.commentEditorIsEmpty.set(!this.y);
    this.initialize(focus);
  }
  async initialize(focus) {
    const hasExistingComments = this.r.comments && this.r.comments.length > 0;
    const modeId = $ps() + "-" + (hasExistingComments ? this.r.threadId : ++INMEM_MODEL_ID);
    const params = JSON.stringify({
      extensionId: this.r.extensionId,
      commentThreadId: this.r.threadId
    });
    let resource = URI.from({
      scheme: Schemas.commentsInput,
      path: `/${this.r.extensionId}/commentinput-${modeId}.md?${params}`
      // TODO. Remove params once extensions adopt authority.
    });
    const commentController = this.D.getCommentController(this.owner);
    if (commentController) {
      resource = resource.with({ authority: commentController.id });
    }
    const model = await this.I.createModelReference(resource);
    model.object.textEditorModel.setValue(this.y?.body || "");
    this.B(model);
    this.commentEditor.setModel(model.object.textEditorModel);
    if (this.y) {
      this.commentEditor.setPosition(this.y.cursor);
    }
    this.J();
    this.B(model.object.textEditorModel.onDidChangeContent(() => {
      this.setCommentEditorDecorations();
      this.commentEditorIsEmpty?.set(!this.commentEditor.getValue());
      if (this.J()) {
        this.commentEditor.layout({ height: this.m, width: this.commentEditor.getLayoutInfo().width });
        this.commentEditor.render(true);
      }
    }));
    this.L(this.commentEditor, this.form);
    this.setCommentEditorDecorations();
    if (this.y) {
      this.P();
    } else if (hasExistingComments) {
      this.S(this.commentEditor, this.form);
    } else if (focus && (this.r.comments && this.r.comments.length === 0)) {
      this.P();
    }
    this.a = $bk(this.form, $(".validation-error.hidden"));
    const formActions = $bk(this.form, $(".form-actions"));
    this.b = $bk(formActions, $(".other-actions"));
    this.M(this.b, model.object.textEditorModel);
    this.c = $bk(formActions, $(".editor-actions"));
    this.N(this.c, model.object.textEditorModel);
  }
  J() {
    const newEditorHeight = $3Jb(this.n, this.commentEditor, this.m);
    if (newEditorHeight !== this.m) {
      this.m = newEditorHeight;
      return true;
    }
    return false;
  }
  updateCommentThread(commentThread) {
    const isReplying = this.commentEditor.hasTextFocus();
    const oldAndNewBothEmpty = !this.r.comments?.length && !commentThread.comments?.length;
    if (!this.j) {
      this.S(this.commentEditor, this.form);
    }
    if (this.r.comments && this.r.comments.length === 0 && !oldAndNewBothEmpty) {
      this.P();
    }
    if (isReplying) {
      this.commentEditor.focus();
    }
  }
  getPendingComment() {
    const model = this.commentEditor.getModel();
    if (model && model.getValueLength() > 0) {
      return { body: model.getValue(), cursor: this.commentEditor.getPosition() ?? new $8C(1, 1) };
    }
    return void 0;
  }
  setPendingComment(pending) {
    this.y = pending;
    this.P();
    this.commentEditor.setValue(pending.body);
    this.commentEditor.setPosition(pending.cursor);
  }
  layout(widthInPixel) {
    this.commentEditor.layout({
      height: this.m,
      width: widthInPixel - 54
      /* margin 20px * 10 + scrollbar 14px*/
    });
  }
  focusIfNeeded() {
    if (!this.r.comments || !this.r.comments.length) {
      this.commentEditor.focus();
    } else if ((this.commentEditor.getModel()?.getValueLength() ?? 0) > 0) {
      this.P();
    }
  }
  focusCommentEditor() {
    this.commentEditor.focus();
  }
  expandReplyAreaAndFocusCommentEditor() {
    this.P();
    this.commentEditor.focus();
  }
  isCommentEditorFocused() {
    return this.commentEditor.hasWidgetFocus();
  }
  updateCanReply() {
    if (!this.r.canReply) {
      this.form.style.display = "none";
    } else {
      this.form.style.display = "block";
    }
  }
  async submitComment() {
    await this.g?.triggerDefaultAction();
    this.y = void 0;
  }
  setCommentEditorDecorations() {
    const hasExistingComments = this.r.comments && this.r.comments.length > 0;
    const placeholder = hasExistingComments ? this.w?.placeHolder || localize(5331, null) : this.w?.placeHolder || localize(5332, null);
    this.commentEditor.updateOptions({ placeholder });
  }
  L(commentEditor, commentForm) {
    this.f.push(commentEditor.onDidFocusEditorWidget(() => {
      this.r.input = {
        uri: commentEditor.getModel().uri,
        value: commentEditor.getValue()
      };
      this.D.setActiveEditingCommentThread(this.r);
      this.D.setActiveCommentAndThread(this.owner, { thread: this.r });
    }));
    this.f.push(commentEditor.getModel().onDidChangeContent(() => {
      const modelContent = commentEditor.getValue();
      if (this.r.input && this.r.input.uri === commentEditor.getModel().uri && this.r.input.value !== modelContent) {
        const newInput = this.r.input;
        newInput.value = modelContent;
        this.r.input = newInput;
      }
      this.D.setActiveEditingCommentThread(this.r);
    }));
    this.f.push(this.r.onDidChangeInput((input) => {
      const thread = this.r;
      const model = commentEditor.getModel();
      if (thread.input && model && thread.input.uri !== model.uri) {
        return;
      }
      if (!input) {
        return;
      }
      if (commentEditor.getValue() !== input.value) {
        commentEditor.setValue(input.value);
        if (input.value === "") {
          this.y = { body: "", cursor: new $8C(1, 1) };
          commentForm.classList.remove("expand");
          commentEditor.getDomNode().style.outline = "";
          this.a.textContent = "";
          this.a.classList.add("hidden");
        }
      }
    }));
  }
  /**
   * Command based actions.
   */
  M(container2, model) {
    const menu = this.u.getCommentThreadActions(this.t);
    this.B(menu);
    this.B(menu.onDidChange(() => {
      this.g.setActions(menu);
    }));
    this.g = new $TJb(this.F, this.t, this.G, container2, async (action) => {
      await this.C?.();
      await action.run({
        thread: this.r,
        text: this.commentEditor.getValue(),
        $mid: 9
        /* MarshalledId.CommentThreadReply */
      });
      this.R();
    });
    this.B(this.g);
    this.g.setActions(menu);
  }
  N(container2, model) {
    const editorMenu = this.u.getCommentEditorActions(this.t);
    this.B(editorMenu);
    this.B(editorMenu.onDidChange(() => {
      this.h.setActions(editorMenu);
    }));
    this.h = new $TJb(this.F, this.t, this.G, container2, async (action) => {
      this.C?.();
      action.run({
        thread: this.r,
        text: this.commentEditor.getValue(),
        $mid: 9
        /* MarshalledId.CommentThreadReply */
      });
      this.focusCommentEditor();
    });
    this.B(this.h);
    this.h.setActions(editorMenu, true);
  }
  get O() {
    return this.form.classList.contains("expand");
  }
  P() {
    if (!this.O) {
      this.form.classList.add("expand");
      this.commentEditor.focus();
      this.commentEditor.layout();
    }
  }
  Q() {
    if (!this.O) {
      this.commentEditor.setValue("");
      this.P();
    }
  }
  R() {
    const domNode = this.commentEditor.getDomNode();
    if (domNode) {
      domNode.style.outline = "";
    }
    this.commentEditor.setValue("");
    this.y = { body: "", cursor: new $8C(1, 1) };
    this.form.classList.remove("expand");
    this.a.textContent = "";
    this.a.classList.add("hidden");
  }
  S(commentEditor, commentForm) {
    this.j = $bk(commentForm, $(`button.review-thread-reply-button.${$62}`));
    this.B(this.H.setupManagedHover($JZ("mouse"), this.j, this.w?.prompt || localize(5333, null)));
    this.j.textContent = this.w?.prompt || localize(5334, null);
    this.B($_i(this.j, "click", (_) => this.Q()));
    this.B($_i(this.j, "focus", (_) => this.Q()));
    commentEditor.onDidBlurEditorWidget(() => {
      if (commentEditor.getModel().getValueLength() === 0 && commentForm.classList.contains("expand")) {
        commentForm.classList.remove("expand");
      }
    });
  }
  dispose() {
    super.dispose();
    $Xc(this.f);
  }
};
$5Jb = __decorate([
  __param(12, $RJb),
  __param(13, $kl),
  __param(14, $Ty),
  __param(15, $50),
  __param(16, $5$),
  __param(17, $oG)
], $5Jb);

// out-build/vs/workbench/contrib/comments/browser/reactionsAction.js
var $6Jb = class _$6Jb extends $Um {
  static {
    this.ID = "toolbar.toggle.pickReactions";
  }
  constructor(toggleDropdownMenu, title) {
    super(_$6Jb.ID, title || localize(5441, null), "toggle-reactions", true);
    this.a = [];
    this.b = toggleDropdownMenu;
  }
  run() {
    this.b();
    return Promise.resolve(true);
  }
  get menuActions() {
    return this.a;
  }
  set menuActions(actions) {
    this.a = actions;
  }
};
var $7Jb = class extends $U1 {
  constructor(action) {
    super(null, action, {});
  }
  C() {
    if (!this.L) {
      return;
    }
    const action = this.action;
    if (action.class) {
      this.L.classList.add(action.class);
    }
    if (!action.icon) {
      const reactionLabel = $bk(this.L, $("span.reaction-label"));
      reactionLabel.innerText = action.label;
    } else {
      const reactionIcon = $bk(this.L, $(".reaction-icon"));
      const uri = URI.revive(action.icon);
      reactionIcon.style.backgroundImage = $5Z(uri);
    }
    if (action.count) {
      const reactionCount = $bk(this.L, $("span.reaction-count"));
      reactionCount.innerText = `${action.count}`;
    }
  }
  F() {
    const action = this.action;
    const toggleMessage = action.enabled ? localize(5442, null) : "";
    if (action.count === void 0) {
      return localize(5443, null, toggleMessage, action.label);
    } else if (action.reactors === void 0 || action.reactors.length === 0) {
      if (action.count === 1) {
        return localize(5444, null, toggleMessage, action.label);
      } else if (action.count > 1) {
        return localize(5445, null, toggleMessage, action.count, action.label);
      }
    } else {
      if (action.reactors.length <= 10 && action.reactors.length === action.count) {
        return localize(5446, null, toggleMessage, action.reactors.join(", "), action.label);
      } else if (action.count > 1) {
        const displayedReactors = action.reactors.slice(0, 10);
        return localize(5447, null, toggleMessage, displayedReactors.join(", "), action.count - displayedReactors.length, action.label);
      }
    }
    return void 0;
  }
};
var $8Jb = class _$8Jb extends $Um {
  static {
    this.ID = "toolbar.toggle.reaction";
  }
  constructor(id2, label3 = "", cssClass = "", enabled = true, actionCallback, reactors, icon2, count) {
    super(_$8Jb.ID, label3, cssClass, enabled, actionCallback);
    this.reactors = reactors;
    this.icon = icon2;
    this.count = count;
  }
};

// out-build/vs/workbench/contrib/comments/browser/commentNode.js
var CommentsActionRunner = class extends $Vm {
  async u(action, context) {
    await action.run(...context);
  }
};
var $0Jb = class $0Jb2 extends $3c {
  get domNode() {
    return this.b;
  }
  constructor(U, W, comment, X, Y, Z, ab, bb, db, eb, fb, gb, contextKeyService, hb, ib, jb, kb, lb) {
    super();
    this.U = U;
    this.W = W;
    this.comment = comment;
    this.X = X;
    this.Y = Y;
    this.Z = Z;
    this.ab = ab;
    this.bb = bb;
    this.db = db;
    this.eb = eb;
    this.fb = fb;
    this.gb = gb;
    this.hb = hb;
    this.ib = ib;
    this.jb = jb;
    this.kb = kb;
    this.lb = lb;
    this.n = null;
    this.r = null;
    this.y = null;
    this.z = [];
    this.C = null;
    this.D = $ZJb;
    this.Q = null;
    this.R = null;
    this.S = new $ze();
    this.isEditing = false;
    this.b = $("div.review-comment");
    this.I = this.B(contextKeyService.createScoped(this.b));
    this.J = CommentContextKeys.commentContext.bindTo(this.I);
    if (this.comment.contextValue) {
      this.J.set(this.comment.contextValue);
    }
    this.L = this.eb.getCommentMenus(this.Y);
    this.b.tabIndex = -1;
    this.f = $bk(this.b, $("div.avatar-container"));
    this.pb(this.comment.userIconPath);
    this.s = $bk(this.b, $(".review-comment-contents"));
    this.sb(this.s);
    this.c = document.createElement(`div`);
    this.c.classList.add("comment-body", $62);
    if (hb.getValue($OJb)?.maxHeight !== false) {
      this.c.classList.add("comment-body-max-height");
    }
    this.nb(this.s, this.c);
    this.ob(this.comment.body);
    if (this.comment.commentReactions && this.comment.commentReactions.length && this.comment.commentReactions.filter((reaction) => !!reaction.count).length) {
      this.zb(this.s);
    }
    this.b.setAttribute("aria-label", `${comment.userName}, ${this.commentBodyValue}`);
    this.b.setAttribute("role", "treeitem");
    this.m = null;
    this.B($_i(this.b, $7j.CLICK, () => this.isEditing || this.S.fire(this)));
    this.B($_i(this.b, $7j.CONTEXT_MENU, (e) => {
      return this.Gb(e);
    }));
    if (X) {
      this.switchToEditMode();
    }
    this.B(this.jb.onDidChangeScreenReaderOptimized(() => {
      this.tb(true);
    }));
    this.mb();
  }
  mb() {
    this.B($_i(this.b, $7j.FOCUS_IN, () => {
      this.eb.setActiveCommentAndThread(this.Y, { thread: this.W, comment: this.comment });
    }, true));
  }
  nb(container2, body) {
    this.M = new $AD({
      forceIntegerValues: true,
      smoothScrollDuration: 125,
      scheduleAtNextAnimationFrame: (cb) => $jj(getWindow(container2), cb)
    });
    this.N = this.B(new $BZ(body, {
      horizontal: 3,
      vertical: 3
      /* ScrollbarVisibility.Visible */
    }, this.M));
    this.B(this.N.onScroll((e) => {
      if (e.scrollLeftChanged) {
        body.scrollLeft = e.scrollLeft;
      }
      if (e.scrollTopChanged) {
        body.scrollTop = e.scrollTop;
      }
    }));
    const onDidScrollViewContainer = this.B(new $9Z(body, "scroll")).event;
    this.B(onDidScrollViewContainer((_) => {
      const position = this.N.getScrollPosition();
      const scrollLeft = Math.abs(body.scrollLeft - position.scrollLeft) <= 1 ? void 0 : body.scrollLeft;
      const scrollTop = Math.abs(body.scrollTop - position.scrollTop) <= 1 ? void 0 : body.scrollTop;
      if (scrollLeft !== void 0 || scrollTop !== void 0) {
        this.N.setScrollPosition({ scrollLeft, scrollTop });
      }
    }));
    container2.appendChild(this.N.getDomNode());
  }
  ob(body) {
    this.c.innerText = "";
    this.h = void 0;
    this.j = void 0;
    if (typeof body === "string") {
      this.j = $bk(this.c, $(".comment-body-plainstring"));
      this.j.innerText = body;
    } else {
      this.h = this.bb.render(body).element;
      this.c.appendChild(this.h);
    }
  }
  pb(userIconPath) {
    this.f.textContent = "";
    if (userIconPath) {
      const img = $bk(this.f, $("img.avatar"));
      img.src = $ih.uriToBrowserUri(URI.revive(userIconPath)).toString(true);
      img.onerror = (_) => img.remove();
    }
  }
  get onDidClick() {
    return this.S.event;
  }
  qb(container2) {
    this.G = $bk(container2, $("span.timestamp-container"));
    this.rb(this.comment.timestamp);
  }
  rb(raw) {
    if (!this.G) {
      return;
    }
    const timestamp = raw !== void 0 ? new Date(raw) : void 0;
    if (!timestamp) {
      this.H?.dispose();
    } else {
      if (!this.H) {
        this.H = new $9Jb(this.hb, this.ib, this.G, timestamp);
        this.B(this.H);
      } else {
        this.H.setTimestamp(timestamp);
      }
    }
  }
  sb(commentDetailsContainer) {
    const header = $bk(commentDetailsContainer, $(`div.comment-title.${$62}`));
    const infoContainer = $bk(header, $("comment-header-info"));
    const author = $bk(infoContainer, $("strong.author"));
    author.innerText = this.comment.userName;
    this.qb(infoContainer);
    this.F = $bk(infoContainer, $("span.isPending"));
    if (this.comment.label) {
      this.F.innerText = this.comment.label;
    } else {
      this.F.innerText = "";
    }
    this.t = $bk(header, $(".comment-actions"));
    this.tb(true);
    this.xb();
  }
  tb(hidden) {
    if (hidden && !this.jb.isScreenReaderOptimized()) {
      this.t.classList.add("hidden");
    } else {
      this.t.classList.remove("hidden");
    }
  }
  ub(menu) {
    const contributedActions = menu.getActions({ shouldForwardArgs: true });
    const primary = [];
    const secondary = [];
    const result = { primary, secondary };
    fillInActions2(contributedActions, result, false, (g) => /^inline/.test(g));
    return result;
  }
  get vb() {
    return [
      {
        thread: this.W,
        commentUniqueId: this.comment.uniqueIdInThread,
        $mid: 10
        /* MarshalledId.CommentNode */
      },
      {
        commentControlHandle: this.W.controllerHandle,
        commentThreadHandle: this.W.commentThreadHandle,
        $mid: 7
        /* MarshalledId.CommentThread */
      }
    ];
  }
  wb() {
    this.P = new $f3(this.t, this.gb, {
      actionViewItemProvider: (action, options3) => {
        if (action.id === $6Jb.ID) {
          return new $L2(action, action.menuActions, this.gb, {
            ...options3,
            actionViewItemProvider: (action2, options4) => this.actionViewItemProvider(action2, options4),
            actionRunner: this.O,
            classNames: ["toolbar-toggle-pickReactions", ...ThemeIcon.asClassNameArray($6l.reactions)],
            anchorAlignmentProvider: () => 1
            /* AnchorAlignment.RIGHT */
          });
        }
        return this.actionViewItemProvider(action, options3);
      },
      orientation: 0
      /* ActionsOrientation.HORIZONTAL */
    });
    this.P.context = this.vb;
    this.P.actionRunner = new CommentsActionRunner();
    this.Fb(this.t);
    this.B(this.P);
  }
  xb() {
    const actions = [];
    const hasReactionHandler = this.eb.hasReactionHandler(this.Y);
    if (hasReactionHandler) {
      const toggleReactionAction = this.yb(this.comment.commentReactions || []);
      actions.push(toggleReactionAction);
    }
    const menu = this.L.getCommentTitleActions(this.comment, this.I);
    this.B(menu);
    this.B(menu.onDidChange((e) => {
      const { primary: primary2, secondary: secondary2 } = this.ub(menu);
      if (!this.P && (primary2.length || secondary2.length)) {
        this.wb();
      }
      this.P.setActions(primary2, secondary2);
    }));
    const { primary, secondary } = this.ub(menu);
    actions.push(...primary);
    if (actions.length || secondary.length) {
      this.wb();
      this.P.setActions(actions, secondary);
    }
  }
  actionViewItemProvider(action, options3) {
    if (action.id === $6Jb.ID) {
      options3 = { label: false, icon: true };
    } else {
      options3 = { label: false, icon: true };
    }
    if (action.id === $8Jb.ID) {
      const item = new $7Jb(action);
      return item;
    } else if (action instanceof $fJ) {
      return this.db.createInstance($T$, action, { hoverDelegate: options3.hoverDelegate });
    } else if (action instanceof $eJ) {
      return this.db.createInstance($V$, action, options3);
    } else {
      const item = new $U1({}, action, options3);
      return item;
    }
  }
  async submitComment() {
    if (this.y && this.Q) {
      await this.Q.triggerDefaultAction();
      this.X = void 0;
    }
  }
  yb(reactionGroup) {
    const toggleReactionAction = this.B(new $6Jb(() => {
      toggleReactionActionViewItem?.show();
    }, localize(5324, null)));
    let reactionMenuActions = [];
    if (reactionGroup && reactionGroup.length) {
      reactionMenuActions = reactionGroup.map((reaction) => {
        return new $Um(`reaction.command.${reaction.label}`, `${reaction.label}`, "", true, async () => {
          try {
            await this.eb.toggleReaction(this.Y, this.Z, this.W, this.comment, reaction);
          } catch (e) {
            const error = e.message ? localize(5325, null, e.message) : localize(5326, null);
            this.fb.error(error);
          }
        });
      });
    }
    toggleReactionAction.menuActions = reactionMenuActions;
    const toggleReactionActionViewItem = new $L2(toggleReactionAction, toggleReactionAction.menuActions, this.gb, {
      actionViewItemProvider: (action, options3) => {
        if (action.id === $6Jb.ID) {
          return toggleReactionActionViewItem;
        }
        return this.actionViewItemProvider(action, options3);
      },
      actionRunner: this.O,
      classNames: "toolbar-toggle-pickReactions",
      anchorAlignmentProvider: () => 1
      /* AnchorAlignment.RIGHT */
    });
    return toggleReactionAction;
  }
  zb(commentDetailsContainer) {
    this.w = $bk(commentDetailsContainer, $("div.comment-reactions"));
    this.u = new $LZ(this.w, {
      actionViewItemProvider: (action, options3) => {
        if (action.id === $6Jb.ID) {
          return new $L2(action, action.menuActions, this.gb, {
            actionViewItemProvider: (action2, options4) => this.actionViewItemProvider(action2, options4),
            actionRunner: this.O,
            classNames: ["toolbar-toggle-pickReactions", ...ThemeIcon.asClassNameArray($6l.reactions)],
            anchorAlignmentProvider: () => 1
            /* AnchorAlignment.RIGHT */
          });
        }
        return this.actionViewItemProvider(action, options3);
      }
    });
    this.B(this.u);
    const hasReactionHandler = this.eb.hasReactionHandler(this.Y);
    this.comment.commentReactions.filter((reaction) => !!reaction.count).map((reaction) => {
      const action = new $8Jb(`reaction.${reaction.label}`, `${reaction.label}`, reaction.hasReacted && (reaction.canEdit || hasReactionHandler) ? "active" : "", reaction.canEdit || hasReactionHandler, async () => {
        try {
          await this.eb.toggleReaction(this.Y, this.Z, this.W, this.comment, reaction);
        } catch (e) {
          let error;
          if (reaction.hasReacted) {
            error = e.message ? localize(5327, null, e.message) : localize(5328, null);
          } else {
            error = e.message ? localize(5329, null, e.message) : localize(5330, null);
          }
          this.fb.error(error);
        }
      }, reaction.reactors, reaction.iconPath, reaction.count);
      this.u?.push(action, { label: true, icon: true });
    });
    if (hasReactionHandler) {
      const toggleReactionAction = this.yb(this.comment.commentReactions || []);
      this.u.push(toggleReactionAction, { label: false, icon: true });
    }
  }
  get commentBodyValue() {
    return typeof this.comment.body === "string" ? this.comment.body : this.comment.body.value;
  }
  async Ab(editContainer) {
    const container2 = $bk(editContainer, $(".edit-textarea"));
    this.y = this.db.createInstance($2Jb, container2, $2Jb.getEditorOptions(this.hb), this.I, this.ab);
    const resource = URI.from({
      scheme: Schemas.commentsInput,
      path: `/commentinput-${this.comment.uniqueIdInThread}-${Date.now()}.md`
    });
    const modelRef = await this.lb.createModelReference(resource);
    this.C = modelRef;
    this.y.setModel(this.C.object.textEditorModel);
    this.y.setValue(this.X?.body ?? this.commentBodyValue);
    if (this.X) {
      this.y.setPosition(this.X.cursor);
    } else {
      const lastLine = this.C.object.textEditorModel.getLineCount();
      const lastColumn = this.C.object.textEditorModel.getLineLength(lastLine) + 1;
      this.y.setPosition(new $8C(lastLine, lastColumn));
    }
    this.X = void 0;
    this.y.layout({ width: container2.clientWidth - 14, height: this.D });
    this.y.focus();
    $jj(getWindow(editContainer), () => {
      this.y.layout({ width: container2.clientWidth - 14, height: this.D });
      this.y.focus();
    });
    const commentThread = this.W;
    commentThread.input = {
      uri: this.y.getModel().uri,
      value: this.commentBodyValue
    };
    this.eb.setActiveEditingCommentThread(commentThread);
    this.eb.setActiveCommentAndThread(this.Y, { thread: commentThread, comment: this.comment });
    this.z.push(this.y.onDidFocusEditorWidget(() => {
      commentThread.input = {
        uri: this.y.getModel().uri,
        value: this.commentBodyValue
      };
      this.eb.setActiveEditingCommentThread(commentThread);
      this.eb.setActiveCommentAndThread(this.Y, { thread: commentThread, comment: this.comment });
    }));
    this.z.push(this.y.onDidChangeModelContent((e) => {
      if (commentThread.input && this.y && this.y.getModel().uri === commentThread.input.uri) {
        const newVal = this.y.getValue();
        if (newVal !== commentThread.input.value) {
          const input = commentThread.input;
          input.value = newVal;
          commentThread.input = input;
          this.eb.setActiveEditingCommentThread(commentThread);
          this.eb.setActiveCommentAndThread(this.Y, { thread: commentThread, comment: this.comment });
        }
      }
    }));
    this.Bb();
    this.B(this.C.object.textEditorModel.onDidChangeContent(() => {
      if (this.y && this.Bb()) {
        this.y.layout({ height: this.D, width: this.y.getLayoutInfo().width });
        this.y.render(true);
      }
    }));
    this.B(this.y);
    this.B(this.C);
  }
  Bb() {
    if (this.y) {
      const newEditorHeight = $3Jb(this.U, this.y, this.D);
      if (newEditorHeight !== this.D) {
        this.D = newEditorHeight;
        return true;
      }
    }
    return false;
  }
  getPendingEdit() {
    const model = this.y?.getModel();
    if (this.y && model && model.getValueLength() > 0) {
      return { body: model.getValue(), cursor: this.y.getPosition() };
    }
    return void 0;
  }
  Cb() {
    this.isEditing = false;
    if (this.n) {
      this.n.enabled = true;
    }
    this.c.classList.remove("hidden");
    this.C?.dispose();
    $Xc(this.z);
    this.z = [];
    this.y?.dispose();
    this.y = null;
    this.r.remove();
  }
  layout(widthInPixel) {
    const editorWidth = widthInPixel !== void 0 ? widthInPixel - 72 : this.y?.getLayoutInfo().width ?? 0;
    this.y?.layout({ width: editorWidth, height: this.D });
    const scrollWidth = this.c.scrollWidth;
    const width2 = $yj(this.c);
    const scrollHeight = this.c.scrollHeight;
    const height = $Aj(this.c) + 4;
    this.N.setScrollDimensions({ width: width2, scrollWidth, height, scrollHeight });
  }
  async switchToEditMode() {
    if (this.isEditing) {
      return;
    }
    this.isEditing = true;
    this.c.classList.add("hidden");
    this.r = $bk(this.s, $(".edit-container"));
    await this.Ab(this.r);
    const formActions = $bk(this.r, $(".form-actions"));
    const otherActions = $bk(formActions, $(".other-actions"));
    this.Db(otherActions);
    const editorActions = $bk(formActions, $(".editor-actions"));
    this.Eb(editorActions);
  }
  Db(container2) {
    const menus = this.eb.getCommentMenus(this.Y);
    const menu = menus.getCommentActions(this.comment, this.I);
    this.B(menu);
    this.B(menu.onDidChange(() => {
      this.Q?.setActions(menu);
    }));
    this.Q = new $TJb(this.kb, this.I, this.gb, container2, (action) => {
      const text2 = this.y.getValue();
      action.run({
        thread: this.W,
        commentUniqueId: this.comment.uniqueIdInThread,
        text: text2,
        $mid: 11
        /* MarshalledId.CommentThreadNode */
      });
      this.Cb();
    });
    this.B(this.Q);
    this.Q.setActions(menu);
  }
  Eb(container2) {
    const menus = this.eb.getCommentMenus(this.Y);
    const menu = menus.getCommentEditorActions(this.I);
    this.B(menu);
    this.B(menu.onDidChange(() => {
      this.R?.setActions(menu);
    }));
    this.R = new $TJb(this.kb, this.I, this.gb, container2, (action) => {
      const text2 = this.y.getValue();
      action.run({
        thread: this.W,
        commentUniqueId: this.comment.uniqueIdInThread,
        text: text2,
        $mid: 11
        /* MarshalledId.CommentThreadNode */
      });
      this.y?.focus();
    });
    this.B(this.R);
    this.R.setActions(menu, true);
  }
  setFocus(focused, visible = false) {
    if (focused) {
      this.b.focus();
      this.tb(false);
      this.t.classList.add("tabfocused");
      this.b.tabIndex = 0;
      if (this.comment.mode === CommentMode.Editing) {
        this.y?.focus();
      }
    } else {
      if (this.t.classList.contains("tabfocused") && !this.t.classList.contains("mouseover")) {
        this.tb(true);
        this.b.tabIndex = -1;
      }
      this.t.classList.remove("tabfocused");
    }
  }
  Fb(actionsContainer) {
    this.B($_i(this.b, "mouseenter", () => {
      this.tb(false);
      actionsContainer.classList.add("mouseover");
    }));
    this.B($_i(this.b, "mouseleave", () => {
      if (actionsContainer.classList.contains("mouseover") && !actionsContainer.classList.contains("tabfocused")) {
        this.tb(true);
      }
      actionsContainer.classList.remove("mouseover");
    }));
  }
  async update(newComment) {
    if (newComment.body !== this.comment.body) {
      this.ob(newComment.body);
    }
    if (this.comment.userIconPath && newComment.userIconPath && URI.from(this.comment.userIconPath).toString() !== URI.from(newComment.userIconPath).toString()) {
      this.pb(newComment.userIconPath);
    }
    const isChangingMode = newComment.mode !== void 0 && newComment.mode !== this.comment.mode;
    this.comment = newComment;
    if (isChangingMode) {
      if (newComment.mode === CommentMode.Editing) {
        await this.switchToEditMode();
      } else {
        this.Cb();
      }
    }
    if (newComment.label) {
      this.F.innerText = newComment.label;
    } else {
      this.F.innerText = "";
    }
    this.w?.remove();
    this.u?.clear();
    if (this.comment.commentReactions && this.comment.commentReactions.some((reaction) => !!reaction.count)) {
      this.zb(this.s);
    }
    if (this.comment.contextValue) {
      this.J.set(this.comment.contextValue);
    } else {
      this.J.reset();
    }
    if (this.comment.timestamp) {
      this.rb(this.comment.timestamp);
    }
  }
  Gb(e) {
    const event = new $lf(getWindow(this.b), e);
    this.gb.showContextMenu({
      getAnchor: () => event,
      menuId: $bJ.CommentThreadCommentContext,
      menuActionOptions: { shouldForwardArgs: true },
      contextKeyService: this.I,
      actionRunner: new CommentsActionRunner(),
      getActionsContext: () => {
        return this.vb;
      }
    });
  }
  focus() {
    this.domNode.focus();
    if (!this.m) {
      this.domNode.classList.add("focus");
      this.m = setTimeout(() => {
        this.domNode.classList.remove("focus");
      }, 3e3);
    }
  }
  dispose() {
    super.dispose();
    $Xc(this.z);
  }
};
$0Jb = __decorate([
  __param(8, $Pk),
  __param(9, $RJb),
  __param(10, $PJ),
  __param(11, $50),
  __param(12, $on),
  __param(13, $kl),
  __param(14, $5$),
  __param(15, $ND),
  __param(16, $Ty),
  __param(17, $oG)
], $0Jb);
function fillInActions2(groups, target, useAlternativeActions, isPrimaryGroup = (group2) => group2 === "navigation") {
  for (const tuple of groups) {
    let [group2, actions] = tuple;
    if (useAlternativeActions) {
      actions = actions.map((a) => a instanceof $fJ && !!a.alt ? a.alt : a);
    }
    if (isPrimaryGroup(group2)) {
      const to = Array.isArray(target) ? target : target.primary;
      to.unshift(...actions);
    } else {
      const to = Array.isArray(target) ? target : target.secondary;
      if (to.length > 0) {
        to.push(new $Wm());
      }
      to.push(...actions);
    }
  }
}

// out-build/vs/workbench/contrib/comments/browser/commentThreadBody.js
var $$Jb = class $$Jb2 extends $3c {
  get length() {
    return this.s.comments ? this.s.comments.length : 0;
  }
  get activeComment() {
    return this.b.filter((node) => node.isEditing)[0];
  }
  constructor(n, owner, parentResourceUri, container2, r2, s, t, u, w, y, z, C) {
    super();
    this.n = n;
    this.owner = owner;
    this.parentResourceUri = parentResourceUri;
    this.container = container2;
    this.r = r2;
    this.s = s;
    this.t = t;
    this.u = u;
    this.w = w;
    this.y = y;
    this.z = z;
    this.C = C;
    this.b = [];
    this.g = void 0;
    this.h = new $ze();
    this.onDidResize = this.h.event;
    this.j = new $_c();
    this.B($_i(container2, $7j.FOCUS_IN, (e) => {
      this.y.setActiveEditingCommentThread(this.s);
    }));
    this.m = this.B(new $Q_(this.r, this.C, this.z));
  }
  focus(commentUniqueId) {
    if (commentUniqueId !== void 0) {
      const comment = this.b.find((commentNode) => commentNode.comment.uniqueIdInThread === commentUniqueId);
      if (comment) {
        comment.focus();
        return;
      }
    }
    this.a.focus();
  }
  ensureFocusIntoNewEditingComment() {
    if (this.b.length === 1 && this.b[0].isEditing) {
      this.b[0].setFocus(true);
    }
  }
  async display() {
    this.a = $bk(this.container, $("div.comments-container"));
    this.a.setAttribute("role", "presentation");
    this.a.tabIndex = 0;
    this.F();
    this.B($_i(this.a, $7j.KEY_DOWN, (e) => {
      const event = new $if(e);
      if ((event.equals(
        16
        /* KeyCode.UpArrow */
      ) || event.equals(
        18
        /* KeyCode.DownArrow */
      )) && (!this.g || !this.b[this.g].isEditing)) {
        const moveFocusWithinBounds = (change) => {
          if (this.g === void 0 && change >= 0) {
            return 0;
          }
          if (this.g === void 0 && change < 0) {
            return this.b.length - 1;
          }
          const newIndex = this.g + change;
          return Math.min(Math.max(0, newIndex), this.b.length - 1);
        };
        this.G(event.equals(
          16
          /* KeyCode.UpArrow */
        ) ? moveFocusWithinBounds(-1) : moveFocusWithinBounds(1));
      }
    }));
    this.j.clearAndDisposeAll();
    this.b = [];
    if (this.s.comments) {
      for (const comment of this.s.comments) {
        const newCommentNode = this.H(comment);
        this.b.push(newCommentNode);
        this.a.appendChild(newCommentNode.domNode);
        if (comment.mode === CommentMode.Editing) {
          await newCommentNode.switchToEditMode();
        }
      }
    }
    this.f = new MutationObserver(this.D.bind(this));
    this.f.observe(this.container, {
      attributes: true,
      childList: true,
      characterData: true,
      subtree: true
    });
  }
  D() {
    const dimensions = $qj(this.container);
    this.h.fire(dimensions);
  }
  getDimensions() {
    return $qj(this.container);
  }
  layout(widthInPixel) {
    this.b.forEach((element) => {
      element.layout(widthInPixel);
    });
  }
  getPendingEdits() {
    const pendingEdits = {};
    this.b.forEach((element) => {
      if (element.isEditing) {
        const pendingEdit = element.getPendingEdit();
        if (pendingEdit) {
          pendingEdits[element.comment.uniqueIdInThread] = pendingEdit;
        }
      }
    });
    return pendingEdits;
  }
  getCommentCoords(commentUniqueId) {
    const matchedNode = this.b.filter((commentNode) => commentNode.comment.uniqueIdInThread === commentUniqueId);
    if (matchedNode && matchedNode.length) {
      const commentThreadCoords = $vj(this.b[0].domNode);
      const commentCoords = $vj(matchedNode[0].domNode);
      return {
        thread: commentThreadCoords,
        comment: commentCoords
      };
    }
    return;
  }
  async updateCommentThread(commentThread, preserveFocus) {
    const oldCommentsLen = this.b.length;
    const newCommentsLen = commentThread.comments ? commentThread.comments.length : 0;
    const commentElementsToDel = [];
    const commentElementsToDelIndex = [];
    for (let i2 = 0; i2 < oldCommentsLen; i2++) {
      const comment = this.b[i2].comment;
      const newComment = commentThread.comments ? commentThread.comments.filter((c) => c.uniqueIdInThread === comment.uniqueIdInThread) : [];
      if (newComment.length) {
        this.b[i2].update(newComment[0]);
      } else {
        commentElementsToDelIndex.push(i2);
        commentElementsToDel.push(this.b[i2]);
      }
    }
    for (let i2 = commentElementsToDel.length - 1; i2 >= 0; i2--) {
      const commentToDelete = commentElementsToDel[i2];
      this.j.deleteAndDispose(commentToDelete);
      this.b.splice(commentElementsToDelIndex[i2], 1);
      commentToDelete.domNode.remove();
    }
    let lastCommentElement = null;
    const newCommentNodeList = [];
    const newCommentsInEditMode = [];
    for (let i2 = newCommentsLen - 1; i2 >= 0; i2--) {
      const currentComment = commentThread.comments[i2];
      const oldCommentNode = this.b.filter((commentNode) => commentNode.comment.uniqueIdInThread === currentComment.uniqueIdInThread);
      if (oldCommentNode.length) {
        lastCommentElement = oldCommentNode[0].domNode;
        newCommentNodeList.unshift(oldCommentNode[0]);
      } else {
        const newElement = this.H(currentComment);
        newCommentNodeList.unshift(newElement);
        if (lastCommentElement) {
          this.a.insertBefore(newElement.domNode, lastCommentElement);
          lastCommentElement = newElement.domNode;
        } else {
          this.a.appendChild(newElement.domNode);
          lastCommentElement = newElement.domNode;
        }
        if (currentComment.mode === CommentMode.Editing) {
          await newElement.switchToEditMode();
          newCommentsInEditMode.push(newElement);
        }
      }
    }
    this.s = commentThread;
    this.b = newCommentNodeList;
    if (newCommentsInEditMode.length) {
      const lastIndex = this.b.indexOf(newCommentsInEditMode[newCommentsInEditMode.length - 1]);
      this.g = lastIndex;
    }
    this.F();
    if (!preserveFocus) {
      this.G(this.g);
    }
  }
  F() {
    if (this.s.isDocumentCommentThread()) {
      if (this.s.range) {
        this.a.ariaLabel = localize(5432, null, this.s.comments?.length, this.s.range.startLineNumber, this.s.range.endLineNumber, this.s.label);
      } else {
        this.a.ariaLabel = localize(5433, null, this.s.comments?.length, this.s.label);
      }
    } else {
      this.a.ariaLabel = localize(5434, null, this.s.comments?.length, this.s.label);
    }
  }
  G(value) {
    if (this.g !== void 0) {
      this.b[this.g]?.setFocus(false);
    }
    if (this.b.length === 0 || value === void 0) {
      this.g = void 0;
    } else {
      this.g = Math.min(value, this.b.length - 1);
      this.b[this.g].setFocus(true);
    }
  }
  H(comment) {
    const newCommentNode = this.u.createInstance($0Jb, this.n, this.s, comment, this.t ? this.t[comment.uniqueIdInThread] : void 0, this.owner, this.parentResourceUri, this.w, this.m);
    const disposables = new $2c();
    disposables.add(newCommentNode.onDidClick((clickedNode) => this.G(this.b.findIndex((commentNode) => commentNode.comment.uniqueIdInThread === clickedNode.comment.uniqueIdInThread))));
    disposables.add(newCommentNode);
    this.j.set(newCommentNode, disposables);
    return newCommentNode;
  }
  dispose() {
    super.dispose();
    if (this.f) {
      this.f.disconnect();
      this.f = null;
    }
    this.j.dispose();
  }
};
$$Jb = __decorate([
  __param(9, $RJb),
  __param(10, $O4),
  __param(11, $1E)
], $$Jb);

// out-build/vs/workbench/contrib/comments/browser/commentThreadHeader.js
var collapseIcon = $9r("review-comment-collapse", $6l.chevronUp, localize(5435, null));
var COLLAPSE_ACTION_CLASS = "expand-review-action " + ThemeIcon.asClassName(collapseIcon);
var DELETE_ACTION_CLASS = "expand-review-action " + ThemeIcon.asClassName($6l.trashcan);
function threadHasComments(comments) {
  return !!comments && comments.length > 0;
}
var $_Jb = class extends $3c {
  constructor(container2, g, h3, j, m, n, s) {
    super();
    this.g = g;
    this.h = h3;
    this.j = j;
    this.m = m;
    this.n = n;
    this.s = s;
    this.a = $(".head");
    container2.appendChild(this.a);
    this.B($1c(() => this.a.remove()));
    this.t();
  }
  t() {
    const titleElement = $bk(this.a, $(".review-title"));
    this.b = $bk(titleElement, $("span.filename"));
    this.createThreadLabel();
    const actionsContainer = $bk(this.a, $(".review-actions"));
    this.c = new $LZ(actionsContainer, {
      actionViewItemProvider: $X$.bind(void 0, this.n)
    });
    this.B(this.c);
    const collapseClass = threadHasComments(this.j.comments) ? COLLAPSE_ACTION_CLASS : DELETE_ACTION_CLASS;
    this.f = new $Um("workbench.action.hideComment", localize(5436, null), collapseClass, true, () => this.g.collapse());
    if (!threadHasComments(this.j.comments)) {
      const commentsChanged = this.B(new $4c());
      commentsChanged.value = this.j.onDidChangeComments(() => {
        if (threadHasComments(this.j.comments)) {
          this.f.class = COLLAPSE_ACTION_CLASS;
          commentsChanged.clear();
        }
      });
    }
    const menu = this.h.getCommentThreadTitleActions(this.m);
    this.B(menu);
    this.u(menu);
    this.B(menu);
    this.B(menu.onDidChange((e) => {
      this.u(menu);
    }));
    this.B($_i(this.a, $7j.CONTEXT_MENU, (e) => {
      return this.w(e);
    }));
    this.c.context = this.j;
  }
  u(menu) {
    const groups = menu.getActions({ shouldForwardArgs: true }).reduce((r2, [, actions]) => [...r2, ...actions], []);
    this.c.clear();
    this.c.push([...groups, this.f], { label: false, icon: true });
  }
  updateCommentThread(commentThread) {
    this.j = commentThread;
    this.c.context = this.j;
    this.createThreadLabel();
  }
  createThreadLabel() {
    let label3;
    label3 = this.j.label;
    if (label3 === void 0) {
      if (!(this.j.comments && this.j.comments.length)) {
        label3 = localize(5437, null);
      }
    }
    if (label3) {
      this.b.textContent = $zf(label3);
      this.b.setAttribute("aria-label", label3);
    }
  }
  updateHeight(headHeight) {
    this.a.style.height = `${headHeight}px`;
    this.a.style.lineHeight = this.a.style.height;
  }
  w(e) {
    const actions = this.h.getCommentThreadTitleContextActions(this.m).getActions({ shouldForwardArgs: true }).map((value) => value[1]).flat();
    if (!actions.length) {
      return;
    }
    const event = new $lf(getWindow(this.a), e);
    this.s.showContextMenu({
      getAnchor: () => event,
      getActions: () => actions,
      actionRunner: new $Vm(),
      getActionsContext: () => {
        return {
          commentControlHandle: this.j.controllerHandle,
          commentThreadHandle: this.j.commentThreadHandle,
          $mid: 7
          /* MarshalledId.CommentThread */
        };
      }
    });
  }
};

// out-build/vs/workbench/contrib/comments/browser/commentThreadAdditionalActions.js
var $aKb = class $aKb2 extends $3c {
  constructor(container2, f, g, h3, j, m, n) {
    super();
    this.f = f;
    this.g = g;
    this.h = h3;
    this.j = j;
    this.m = m;
    this.n = n;
    this.a = $bk(container2, $(".comment-additional-actions"));
    $bk(this.a, $(".section-separator"));
    this.b = $bk(this.a, $(".button-bar"));
    this.u(this.b);
  }
  r() {
    this.a?.classList.remove("hidden");
  }
  s() {
    this.a?.classList.add("hidden");
  }
  t(menu) {
    const groups = menu.getActions({ shouldForwardArgs: true });
    for (const group2 of groups) {
      const [, actions] = group2;
      for (const action of actions) {
        if (action.enabled) {
          this.r();
          return;
        }
        for (const subAction of action.actions ?? []) {
          if (subAction.enabled) {
            this.r();
            return;
          }
        }
      }
    }
    this.s();
  }
  u(container2) {
    const menu = this.h.getCommentThreadAdditionalActions(this.g);
    this.B(menu);
    this.B(menu.onDidChange(() => {
      this.c.setActions(
        menu,
        /*hasOnlySecondaryActions*/
        true
      );
      this.t(menu);
    }));
    this.c = new $TJb(this.m, this.g, this.n, container2, async (action) => {
      this.j?.();
      action.run({
        thread: this.f,
        $mid: 8
        /* MarshalledId.CommentThreadInstance */
      });
    }, 4, true);
    this.B(this.c);
    this.c.setActions(
      menu,
      /*hasOnlySecondaryActions*/
      true
    );
    this.t(menu);
  }
};
$aKb = __decorate([
  __param(5, $Ty),
  __param(6, $50)
], $aKb);

// out-build/vs/workbench/browser/actions/widgetNavigationCommands.js
var NavigableContainerManager_1;
function handleFocusEventsGroup(group2, handler, onPartFocusChange) {
  const focusedIndices = /* @__PURE__ */ new Set();
  return $Zc(...group2.map((events, index) => $Zc(events.onDidFocus(() => {
    onPartFocusChange?.(index, "focus");
    if (!focusedIndices.size) {
      handler(true);
    }
    focusedIndices.add(index);
  }), events.onDidBlur(() => {
    onPartFocusChange?.(index, "blur");
    focusedIndices.delete(index);
    if (!focusedIndices.size) {
      handler(false);
    }
  }))));
}
var NavigableContainerFocusedContextKey = new $nn("navigableContainerFocused", false);
var NavigableContainerManager = class NavigableContainerManager2 {
  static {
    NavigableContainerManager_1 = this;
  }
  static {
    this.ID = "workbench.contrib.navigableContainerManager";
  }
  constructor(contextKeyService, e, f) {
    this.e = e;
    this.f = f;
    this.b = /* @__PURE__ */ new Set();
    this.d = NavigableContainerFocusedContextKey.bindTo(contextKeyService);
    NavigableContainerManager_1.a = this;
  }
  dispose() {
    this.b.clear();
    this.d.reset();
    NavigableContainerManager_1.a = void 0;
  }
  get g() {
    return this.f.getValue("workbench.navigibleContainer.enableDebug");
  }
  h(msg, ...args2) {
    if (this.g) {
      this.e.debug(msg, ...args2);
    }
  }
  static register(container2) {
    const instance2 = this.a;
    if (!instance2) {
      return $3c.None;
    }
    instance2.b.add(container2);
    instance2.h("NavigableContainerManager.register", container2.name);
    return $Zc(handleFocusEventsGroup(container2.focusNotifiers, (isFocus) => {
      if (isFocus) {
        instance2.h("NavigableContainerManager.focus", container2.name);
        instance2.d.set(true);
        instance2.c = container2;
      } else {
        instance2.h("NavigableContainerManager.blur", container2.name, instance2.c?.name);
        if (instance2.c === container2) {
          instance2.d.set(false);
          instance2.c = void 0;
        }
      }
    }, (index, event) => {
      instance2.h("NavigableContainerManager.partFocusChange", container2.name, index, event);
    }), $1c(() => {
      instance2.b.delete(container2);
      instance2.h("NavigableContainerManager.unregister", container2.name, instance2.c?.name);
      if (instance2.c === container2) {
        instance2.d.set(false);
        instance2.c = void 0;
      }
    }));
  }
  static getActive() {
    return this.a?.c;
  }
};
NavigableContainerManager = NavigableContainerManager_1 = __decorate([
  __param(0, $on),
  __param(1, $wn),
  __param(2, $kl)
], NavigableContainerManager);
function $iKb(container2) {
  return NavigableContainerManager.register(container2);
}
$PL(
  NavigableContainerManager.ID,
  NavigableContainerManager,
  1
  /* WorkbenchPhase.BlockStartup */
);
$0I.registerCommandAndKeybindingRule({
  id: "widgetNavigation.focusPrevious",
  weight: 200,
  when: $7m.and(NavigableContainerFocusedContextKey, $7m.or($Leb?.negate(), $Geb)),
  primary: 2048 | 16,
  handler: () => {
    const activeContainer = NavigableContainerManager.getActive();
    activeContainer?.focusPreviousWidget();
  }
});
$0I.registerCommandAndKeybindingRule({
  id: "widgetNavigation.focusNext",
  weight: 200,
  when: $7m.and(NavigableContainerFocusedContextKey, $7m.or($Leb?.negate(), $Heb)),
  primary: 2048 | 18,
  handler: () => {
    const activeContainer = NavigableContainerManager.getActive();
    activeContainer?.focusNextWidget();
  }
});

// out-build/vs/workbench/contrib/comments/browser/commentThreadWidget.js
var $kKb = class $kKb2 extends $3c {
  get commentThread() {
    return this.C;
  }
  constructor(container2, _parentEditor, u, w, y, z, C, D, F, G, H, I, J, contextMenuService, L, M) {
    super();
    this.container = container2;
    this._parentEditor = _parentEditor;
    this.u = u;
    this.w = w;
    this.y = y;
    this.z = z;
    this.C = C;
    this.D = D;
    this.F = F;
    this.G = G;
    this.H = H;
    this.I = I;
    this.J = J;
    this.L = L;
    this.M = M;
    this.h = [];
    this.s = new $ze();
    this.onDidResize = this.s.event;
    this.j = CommentContextKeys.commentThreadIsEmpty.bindTo(this.y);
    this.j.set(!C.comments || !C.comments.length);
    this.r = CommentContextKeys.commentFocused.bindTo(this.y);
    this.g = this.J.getCommentMenus(this.u);
    this.B(this.a = new $_Jb(container2, {
      collapse: this.collapse.bind(this)
    }, this.g, this.C, this.y, this.z, contextMenuService));
    this.a.updateCommentThread(this.C);
    const bodyElement = $(".body");
    container2.appendChild(bodyElement);
    this.B($1c(() => bodyElement.remove()));
    const tracker2 = this.B($_j(bodyElement));
    this.B($iKb({
      name: "commentThreadWidget",
      focusNotifiers: [tracker2],
      focusNextWidget: () => {
        if (!this.c?.isCommentEditorFocused()) {
          this.c?.expandReplyAreaAndFocusCommentEditor();
        }
      },
      focusPreviousWidget: () => {
        if (this.c?.isCommentEditorFocused() && this.C.comments?.length) {
          this.b.focus();
        }
      }
    }));
    this.B(tracker2.onDidFocus(() => this.r.set(true)));
    this.B(tracker2.onDidBlur(() => this.r.reset()));
    this.B(this.L.onDidChangeConfiguration((e) => {
      if (e.affectsConfiguration(
        "accessibility.verbosity.comments"
        /* AccessibilityVerbositySettingId.Comments */
      )) {
        this.N();
      }
    }));
    this.b = this.z.createInstance($$Jb, this._parentEditor, this.u, this.w, bodyElement, this.G, this.C, this.F, this.z, this);
    this.B(this.b);
    this.N();
    this.m = $VZ(this.container);
    this.n = CommentContextKeys.commentThreadContext.bindTo(this.y);
    this.n.set(C.contextValue);
    const commentControllerKey = CommentContextKeys.commentControllerContext.bindTo(this.y);
    const controller = this.J.getCommentController(this.u);
    if (controller?.contextValue) {
      commentControllerKey.set(controller.contextValue);
    }
    this.P();
  }
  N() {
    let ariaLabel = localize(5438, null);
    let keybinding;
    const verbose = this.L.getValue(
      "accessibility.verbosity.comments"
      /* AccessibilityVerbositySettingId.Comments */
    );
    if (verbose) {
      keybinding = this.M.lookupKeybinding("editor.action.accessibilityHelp", this.y)?.getLabel() ?? void 0;
    }
    if (keybinding) {
      ariaLabel = localize(5439, null, ariaLabel, keybinding);
    } else if (verbose) {
      ariaLabel = localize(5440, null, ariaLabel);
    }
    this.b.container.ariaLabel = ariaLabel;
  }
  O(hasMouse, hasFocus) {
    if (hasMouse || hasFocus) {
      this.J.setCurrentCommentThread(this.commentThread);
    } else {
      this.J.setCurrentCommentThread(void 0);
    }
  }
  P() {
    let hasMouse = false;
    let hasFocus = false;
    this.B($_i(this.container, $7j.MOUSE_ENTER, (e) => {
      if (e.toElement === this.container) {
        hasMouse = true;
        this.O(hasMouse, hasFocus);
      }
    }, true));
    this.B($_i(this.container, $7j.MOUSE_LEAVE, (e) => {
      if (e.fromElement === this.container) {
        hasMouse = false;
        this.O(hasMouse, hasFocus);
      }
    }, true));
    this.B($_i(this.container, $7j.FOCUS_IN, () => {
      hasFocus = true;
      this.O(hasMouse, hasFocus);
    }, true));
    this.B($_i(this.container, $7j.FOCUS_OUT, () => {
      hasFocus = false;
      this.O(hasMouse, hasFocus);
    }, true));
  }
  async updateCommentThread(commentThread) {
    const shouldCollapse = this.C.collapsibleState === CommentThreadCollapsibleState.Expanded && this.t === CommentThreadState.Unresolved && commentThread.state === CommentThreadState.Resolved;
    this.t = commentThread.state;
    this.C = commentThread;
    $Xc(this.h);
    this.h = [];
    this.R();
    await this.b.updateCommentThread(commentThread, this.c?.isCommentEditorFocused() ?? false);
    this.j.set(!this.b.length);
    this.a.updateCommentThread(commentThread);
    this.c?.updateCommentThread(commentThread);
    if (this.C.contextValue) {
      this.n.set(this.C.contextValue);
    } else {
      this.n.reset();
    }
    if (shouldCollapse && this.L.getValue($OJb).collapseOnResolve) {
      this.collapse();
    }
  }
  async display(lineHeight, focus) {
    const headHeight = Math.max(23, Math.ceil(lineHeight * 1.2));
    this.a.updateHeight(headHeight);
    await this.b.display();
    if (this.C.canReply) {
      this.S(focus);
    }
    this.U();
    this.B(this.b.onDidResize((dimension) => {
      this.Q(dimension);
    }));
    if (this.C.canReply && this.c) {
      this.c.focusIfNeeded();
    }
    this.R();
  }
  Q(dimension) {
    this.b.layout();
    this.s.fire(dimension);
  }
  dispose() {
    super.dispose();
    $Xc(this.h);
    this.O(false, false);
  }
  R() {
    this.h.push(this.C.onDidChangeCanReply(() => {
      if (this.c) {
        this.c.updateCanReply();
      } else {
        if (this.C.canReply) {
          this.S(false);
        }
      }
    }));
    this.h.push(this.C.onDidChangeComments(async (_) => {
      await this.updateCommentThread(this.C);
    }));
    this.h.push(this.C.onDidChangeLabel((_) => {
      this.a.createThreadLabel();
    }));
  }
  S(focus) {
    this.c = this.z.createInstance($5Jb, this.u, this.b.container, this._parentEditor, this.C, this.z, this.y, this.g, this.H, this.D, this, focus, this.I.actionRunner);
    this.B(this.c);
  }
  U() {
    this.f = this.z.createInstance($aKb, this.b.container, this.C, this.y, this.g, this.I.actionRunner);
    this.B(this.f);
  }
  getCommentCoords(commentUniqueId) {
    return this.b.getCommentCoords(commentUniqueId);
  }
  getPendingEdits() {
    return this.b.getPendingEdits();
  }
  getPendingComment() {
    if (this.c) {
      return this.c.getPendingComment();
    }
    return void 0;
  }
  setPendingComment(pending) {
    this.D = pending;
    this.c?.setPendingComment(pending);
  }
  getDimensions() {
    return this.b.getDimensions();
  }
  layout(widthInPixel) {
    this.b.layout(widthInPixel);
    if (widthInPixel !== void 0) {
      this.c?.layout(widthInPixel);
    }
  }
  ensureFocusIntoNewEditingComment() {
    this.b.ensureFocusIntoNewEditingComment();
  }
  focusCommentEditor() {
    this.c?.expandReplyAreaAndFocusCommentEditor();
  }
  focus(commentUniqueId) {
    this.b.focus(commentUniqueId);
  }
  async submitComment() {
    const activeComment = this.b.activeComment;
    if (activeComment) {
      return activeComment.submitComment();
    } else if ((this.c?.getPendingComment()?.body.length ?? 0) > 0) {
      return this.c?.submitComment();
    }
  }
  collapse() {
    if ($9C.isIRange(this.commentThread.range) && $P5(this._parentEditor)) {
      this._parentEditor.setSelection(this.commentThread.range);
    }
    this.I.collapse();
  }
  applyTheme(theme, fontInfo) {
    const content = [];
    content.push(`.monaco-editor .review-widget > .body { border-top: 1px solid var(${$dKb}) }`);
    content.push(`.monaco-editor .review-widget > .head { background-color: var(${$fKb}) }`);
    const linkColor = theme.getColor($no);
    if (linkColor) {
      content.push(`.review-widget .body .comment-body a { color: ${linkColor} }`);
    }
    const linkActiveColor = theme.getColor($oo);
    if (linkActiveColor) {
      content.push(`.review-widget .body .comment-body a:hover, a:active { color: ${linkActiveColor} }`);
    }
    const focusColor = theme.getColor($jo);
    if (focusColor) {
      content.push(`.review-widget .body .comment-body a:focus { outline: 1px solid ${focusColor}; }`);
      content.push(`.review-widget .body .monaco-editor.focused { outline: 1px solid ${focusColor}; }`);
    }
    const blockQuoteBackground = theme.getColor($so);
    if (blockQuoteBackground) {
      content.push(`.review-widget .body .review-comment blockquote { background: ${blockQuoteBackground}; }`);
    }
    const blockQuoteBOrder = theme.getColor($to);
    if (blockQuoteBOrder) {
      content.push(`.review-widget .body .review-comment blockquote { border-color: ${blockQuoteBOrder}; }`);
    }
    const border = theme.getColor($Jmb);
    if (border) {
      content.push(`.review-widget .body .review-comment .review-comment-contents .comment-reactions .action-item a.action-label { border-color: ${border}; }`);
    }
    const hcBorder = theme.getColor($ko);
    if (hcBorder) {
      content.push(`.review-widget .body .comment-form .review-thread-reply-button { outline-color: ${hcBorder}; }`);
      content.push(`.review-widget .body .monaco-editor { outline: 1px solid ${hcBorder}; }`);
    }
    const errorBorder = theme.getColor($Nq);
    if (errorBorder) {
      content.push(`.review-widget .validation-error { border: 1px solid ${errorBorder}; }`);
    }
    const errorBackground = theme.getColor($Lq);
    if (errorBackground) {
      content.push(`.review-widget .validation-error { background: ${errorBackground}; }`);
    }
    const errorForeground = theme.getColor($Mq);
    if (errorForeground) {
      content.push(`.review-widget .body .comment-form .validation-error { color: ${errorForeground}; }`);
    }
    const fontFamilyVar = "--comment-thread-editor-font-family";
    const fontSizeVar = "--comment-thread-editor-font-size";
    const fontWeightVar = "--comment-thread-editor-font-weight";
    this.container?.style.setProperty(fontFamilyVar, fontInfo.fontFamily);
    this.container?.style.setProperty(fontSizeVar, `${fontInfo.fontSize}px`);
    this.container?.style.setProperty(fontWeightVar, fontInfo.fontWeight);
    content.push(`.review-widget .body code {
			font-family: var(${fontFamilyVar});
			font-weight: var(${fontWeightVar});
		}`);
    this.m.textContent = content.join("\n");
    this.c?.setCommentEditorDecorations();
  }
};
$kKb = __decorate([
  __param(12, $RJb),
  __param(13, $50),
  __param(14, $kl),
  __param(15, $Ty)
], $kKb);

// out-build/vs/workbench/contrib/comments/browser/commentThreadZoneWidget.js
function getCommentThreadWidgetStateColor(thread, theme) {
  return $gKb(thread, theme) ?? theme.getColor($geb);
}
var CommentWidgetFocus;
(function(CommentWidgetFocus2) {
  CommentWidgetFocus2[CommentWidgetFocus2["None"] = 0] = "None";
  CommentWidgetFocus2[CommentWidgetFocus2["Widget"] = 1] = "Widget";
  CommentWidgetFocus2[CommentWidgetFocus2["Editor"] = 2] = "Editor";
})(CommentWidgetFocus || (CommentWidgetFocus = {}));
function $lSb(e) {
  const range = e.target.range;
  if (!range) {
    return null;
  }
  if (!e.event.leftButton) {
    return null;
  }
  if (e.target.type !== 4) {
    return null;
  }
  const data = e.target.detail;
  const gutterOffsetX = data.offsetX - data.glyphMarginWidth - data.lineNumbersWidth - data.glyphMarginLeft;
  if (gutterOffsetX > 20) {
    return null;
  }
  return { lineNumber: range.startLineNumber };
}
function $mSb(mouseDownInfo, e) {
  if (!mouseDownInfo) {
    return null;
  }
  const { lineNumber } = mouseDownInfo;
  const range = e.target.range;
  if (!range) {
    return null;
  }
  return lineNumber;
}
var $oSb = class $oSb2 extends $_db {
  get uniqueOwner() {
    return this.L;
  }
  get commentThread() {
    return this.M;
  }
  get expanded() {
    return this.d;
  }
  constructor(editor, L, M, N, O, instantiationService, P, Q, contextKeyService, R) {
    super(editor, { keepEditorSelection: true, isAccessible: true });
    this.L = L;
    this.M = M;
    this.N = N;
    this.O = O;
    this.P = P;
    this.Q = Q;
    this.R = R;
    this.b = new $ze();
    this.c = new $ze();
    this.p = new $2c();
    this.r = [];
    this.s = contextKeyService.createScoped(this.domNode);
    this.J = this.p.add(instantiationService.createChild(new $Ok([$on, this.s])));
    const controller = this.Q.getCommentController(this.L);
    if (controller) {
      this.K = controller.options;
    }
    this.i = N ? CommentThreadCollapsibleState.Expanded : M.l;
    M.l = this.i;
    this.r = [];
    this.create();
    this.p.add(this.P.onDidColorThemeChange(this.cb, this));
    this.p.add(this.editor.onDidChangeConfiguration((e) => {
      if (e.hasChanged(
        52
        /* EditorOption.fontInfo */
      )) {
        this.cb(this.P.getColorTheme());
      }
    }));
    this.cb(this.P.getColorTheme());
  }
  get onDidClose() {
    return this.b.event;
  }
  get onDidCreateThread() {
    return this.c.event;
  }
  getPosition() {
    if (this.position) {
      return this.position;
    }
    if (this.m) {
      return this.m.getPosition().position ?? void 0;
    }
    return void 0;
  }
  z() {
  }
  reveal(commentUniqueId, focus = CommentWidgetFocus.None) {
    this.makeVisible(commentUniqueId, focus);
    const comment = this.M.comments?.find((comment2) => comment2.uniqueIdInThread === commentUniqueId);
    this.Q.setActiveCommentAndThread(this.uniqueOwner, { thread: this.M, comment });
  }
  T() {
    if (!this.d) {
      this.show(this.Y(this.M.range), 2);
    }
  }
  U(commentUniqueId, focus) {
    if (focus === CommentWidgetFocus.Widget) {
      this.a.focus(commentUniqueId);
    } else if (focus === CommentWidgetFocus.Editor) {
      this.a.focusCommentEditor();
    }
  }
  V(commentUniqueId, focus) {
    const height = this.editor.getLayoutInfo().height;
    const coords = this.a.getCommentCoords(commentUniqueId);
    if (coords) {
      let scrollTop = 1;
      if (this.M.range) {
        const commentThreadCoords = coords.thread;
        const commentCoords = coords.comment;
        scrollTop = this.editor.getTopForLineNumber(this.M.range.startLineNumber) - height / 2 + commentCoords.top - commentThreadCoords.top;
      }
      this.editor.setScrollTop(scrollTop);
      this.U(commentUniqueId, focus);
    } else {
      this.W(focus);
    }
  }
  W(focus) {
    const rangeToReveal = this.M.range ? new $9C(this.M.range.startLineNumber, this.M.range.startColumn, this.M.range.endLineNumber + 1, 1) : new $9C(1, 1, 1, 1);
    this.editor.revealRangeInCenter(rangeToReveal);
    this.U(void 0, focus);
  }
  makeVisible(commentUniqueId, focus = CommentWidgetFocus.None) {
    this.T();
    if (commentUniqueId !== void 0) {
      this.V(commentUniqueId, focus);
    } else {
      this.W(focus);
    }
  }
  getPendingComments() {
    return {
      newComment: this.a.getPendingComment(),
      edits: this.a.getPendingEdits()
    };
  }
  setPendingComment(pending) {
    this.N = pending;
    this.expand();
    this.a.setPendingComment(pending);
  }
  B(container2) {
    this.A("review-widget");
    this.a = this.J.createInstance($kKb, container2, this.editor, this.L, this.editor.getModel().uri, this.s, this.J, this.M, this.N, this.O, { editor: this.editor, codeBlockFontSize: "", codeBlockFontFamily: this.R.getValue("editor").fontFamily || EDITOR_FONT_DEFAULTS.fontFamily }, this.K, {
      actionRunner: async () => {
        if (!this.M.comments || !this.M.comments.length) {
          const newPosition = this.getPosition();
          if (newPosition) {
            const originalRange = this.M.range;
            if (!originalRange) {
              return;
            }
            let range;
            if (newPosition.lineNumber !== originalRange.endLineNumber) {
              const distance = newPosition.lineNumber - originalRange.endLineNumber;
              range = new $9C(originalRange.startLineNumber + distance, originalRange.startColumn, originalRange.endLineNumber + distance, originalRange.endColumn);
            } else {
              range = new $9C(originalRange.startLineNumber, originalRange.startColumn, originalRange.endLineNumber, originalRange.endColumn);
            }
            await this.Q.updateCommentThreadTemplate(this.uniqueOwner, this.M.commentThreadHandle, range);
          }
        }
      },
      collapse: () => {
        this.collapse();
      }
    });
    this.n.add(this.a);
  }
  Y(range) {
    if (!range) {
      return void 0;
    }
    return { lineNumber: range.endLineNumber, column: range.endLineNumber === range.startLineNumber ? (range.startColumn + range.endColumn + 1) / 2 : 1 };
  }
  Z() {
    this.dispose();
    this.Q.disposeCommentThread(this.uniqueOwner, this.M.threadId);
  }
  collapse() {
    this.M.collapsibleState = CommentThreadCollapsibleState.Collapsed;
  }
  expand(setActive) {
    this.M.collapsibleState = CommentThreadCollapsibleState.Expanded;
    if (setActive) {
      this.Q.setActiveCommentAndThread(this.uniqueOwner, { thread: this.M });
    }
  }
  getGlyphPosition() {
    if (this.m) {
      return this.m.getPosition().position.lineNumber;
    }
    return 0;
  }
  async update(commentThread) {
    if (this.M !== commentThread) {
      this.r.forEach((disposable) => disposable.dispose());
      this.M = commentThread;
      this.r = [];
      this.bb();
    }
    await this.a.updateCommentThread(commentThread);
    const lineNumber = this.M.range?.endLineNumber ?? 1;
    let shouldMoveWidget = false;
    if (this.m) {
      this.m.setThreadState(commentThread.state);
      if (this.m.getPosition().position.lineNumber !== lineNumber) {
        shouldMoveWidget = true;
        this.m.setLineNumber(lineNumber);
      }
    }
    if (shouldMoveWidget && this.d || this.M.collapsibleState === CommentThreadCollapsibleState.Expanded && !this.d) {
      this.show(this.Y(this.M.range), 2);
    } else if (this.M.collapsibleState !== CommentThreadCollapsibleState.Expanded) {
      this.hide();
    }
  }
  C(widthInPixel) {
    this.a.layout(widthInPixel);
  }
  D(heightInPixel, widthInPixel) {
    this.a.layout(widthInPixel);
  }
  async display(range, shouldReveal) {
    if (range) {
      this.m = new $kSb(this.editor, range?.endLineNumber ?? -1);
      this.m.setThreadState(this.M.state);
      this.p.add(this.m.onDidChangeLineNumber(async (e) => {
        if (!this.M.range) {
          return;
        }
        const shift = e - this.M.range.endLineNumber;
        const newRange = new $9C(this.M.range.startLineNumber + shift, this.M.range.startColumn, this.M.range.endLineNumber + shift, this.M.range.endColumn);
        this.M.range = newRange;
      }));
    }
    await this.a.display(this.editor.getOption(
      68
      /* EditorOption.lineHeight */
    ), shouldReveal);
    this.n.add(this.a.onDidResize((dimension) => {
      this._refresh(dimension);
    }));
    if (this.M.collapsibleState === CommentThreadCollapsibleState.Expanded || range === void 0) {
      this.show(this.Y(range), 2);
    }
    if (shouldReveal) {
      this.makeVisible();
    }
    this.bb();
  }
  bb() {
    this.r.push(this.M.onDidChangeComments(async (_) => {
      await this.update(this.M);
    }));
    this.r.push(this.M.onDidChangeCollapsibleState((state) => {
      if (state === CommentThreadCollapsibleState.Expanded && !this.d) {
        this.show(this.Y(this.M.range), 2);
        this.a.ensureFocusIntoNewEditingComment();
        return;
      }
      if (state === CommentThreadCollapsibleState.Collapsed && this.d) {
        this.hide();
        return;
      }
    }));
    if (this.i === void 0) {
      const onDidChangeInitialCollapsibleState = this.M.onDidChangeInitialCollapsibleState((state) => {
        this.i = state;
        this.M.collapsibleState = this.i;
        onDidChangeInitialCollapsibleState.dispose();
      });
      this.r.push(onDidChangeInitialCollapsibleState);
    }
    this.r.push(this.M.onDidChangeState(() => {
      const borderColor = getCommentThreadWidgetStateColor(this.M.state, this.P.getColorTheme()) || $Vn.transparent;
      this.style({
        frameColor: borderColor,
        arrowColor: borderColor
      });
      this.container?.style.setProperty($dKb, `${borderColor}`);
      this.container?.style.setProperty($fKb, `${borderColor.transparent(0.1)}`);
    }));
  }
  async submitComment() {
    return this.a.submitComment();
  }
  _refresh(dimensions) {
    if (this.d === void 0 && dimensions.height === 0 && dimensions.width === 0) {
      this.commentThread.collapsibleState = CommentThreadCollapsibleState.Collapsed;
      return;
    }
    if (this.d) {
      this.a.layout();
      const headHeight = Math.ceil(this.editor.getOption(
        68
        /* EditorOption.lineHeight */
      ) * 1.2);
      const lineHeight = this.editor.getOption(
        68
        /* EditorOption.lineHeight */
      );
      const arrowHeight = Math.round(lineHeight / 3);
      const frameThickness = Math.round(lineHeight / 9) * 2;
      const computedLinesNumber = Math.ceil((headHeight + dimensions.height + arrowHeight + frameThickness + 8) / lineHeight);
      if (this.l?.heightInLines === computedLinesNumber) {
        return;
      }
      const currentPosition = this.getPosition();
      if (this.l && currentPosition && currentPosition.lineNumber !== this.l.afterLineNumber && this.l.afterLineNumber !== 0) {
        this.l.afterLineNumber = currentPosition.lineNumber;
      }
      const capture = $O9.capture(this.editor);
      this.E(computedLinesNumber);
      capture.restore(this.editor);
    }
  }
  cb(theme) {
    const borderColor = getCommentThreadWidgetStateColor(this.M.state, this.P.getColorTheme()) || $Vn.transparent;
    this.style({
      arrowColor: borderColor,
      frameColor: borderColor
    });
    const fontInfo = this.editor.getOption(
      52
      /* EditorOption.fontInfo */
    );
    this.a.applyTheme(theme, fontInfo);
  }
  show(rangeOrPos, heightInLines) {
    const glyphPosition = this.m?.getPosition();
    let range = $9C.isIRange(rangeOrPos) ? rangeOrPos : rangeOrPos ? $9C.fromPositions(rangeOrPos) : void 0;
    if (glyphPosition?.position && range && glyphPosition.position.lineNumber !== range.endLineNumber) {
      const distance = glyphPosition.position.lineNumber - range.endLineNumber;
      range = new $9C(range.startLineNumber + distance, range.startColumn, range.endLineNumber + distance, range.endColumn);
    }
    this.d = true;
    super.show(range ?? new $9C(0, 0, 0, 0), heightInLines);
    this.M.collapsibleState = CommentThreadCollapsibleState.Expanded;
    this._refresh(this.a.getDimensions());
  }
  collapseAndFocusRange() {
    this.a.collapse();
  }
  hide() {
    if (this.d) {
      this.d = false;
      if (this.editor.hasWidgetFocus()) {
        this.editor.focus();
      }
      if (!this.M.comments || !this.M.comments.length) {
        this.Z();
      }
    }
    super.hide();
  }
  dispose() {
    super.dispose();
    if (this.m) {
      this.m.dispose();
      this.m = void 0;
    }
    this.p.dispose();
    this.r.forEach((global) => global.dispose());
    this.b.fire(void 0);
  }
};
$oSb = __decorate([
  __param(5, $Pk),
  __param(6, $gs),
  __param(7, $RJb),
  __param(8, $on),
  __param(9, $kl)
], $oSb);

// out-build/vs/workbench/contrib/comments/browser/commentThreadRangeDecorator.js
var CommentThreadRangeDecoration = class {
  get id() {
    return this.a;
  }
  set id(id2) {
    this.a = id2;
  }
  constructor(range, options3) {
    this.range = range;
    this.options = options3;
  }
};
var $pSb = class _$pSb extends $3c {
  static {
    this.a = "comment-thread-range-decorator";
  }
  constructor(commentService) {
    super();
    this.f = [];
    this.g = [];
    this.j = [];
    const decorationOptions = {
      description: _$pSb.a,
      isWholeLine: false,
      zIndex: 20,
      className: "comment-thread-range",
      shouldFillLineOnLineBreak: true
    };
    this.b = $WI.createDynamic(decorationOptions);
    const activeDecorationOptions = {
      description: _$pSb.a,
      isWholeLine: false,
      zIndex: 20,
      className: "comment-thread-range-current",
      shouldFillLineOnLineBreak: true
    };
    this.c = $WI.createDynamic(activeDecorationOptions);
    this.B(commentService.onDidChangeCurrentCommentThread((thread) => {
      this.n(thread);
    }));
    this.B(commentService.onDidUpdateCommentThreads(() => {
      this.n(void 0);
    }));
  }
  n(thread) {
    if (!this.h || thread?.resource && thread.resource?.toString() !== this.h.getModel()?.uri.toString()) {
      return;
    }
    this.m?.dispose();
    const newDecoration = [];
    if (thread) {
      const range = thread.range;
      if (range && !(range.startLineNumber === range.endLineNumber && range.startColumn === range.endColumn)) {
        if (thread.collapsibleState === CommentThreadCollapsibleState.Expanded) {
          this.m = thread.onDidChangeCollapsibleState((state) => {
            if (state === CommentThreadCollapsibleState.Collapsed) {
              this.n(void 0);
            }
          });
          newDecoration.push(new CommentThreadRangeDecoration(range, this.c));
        }
      }
    }
    this.h.changeDecorations((changeAccessor) => {
      this.g = changeAccessor.deltaDecorations(this.g, newDecoration);
      newDecoration.forEach((decoration3, index) => decoration3.id = this.f[index]);
    });
  }
  update(editor, commentInfos) {
    const model = editor?.getModel();
    if (!editor || !model) {
      return;
    }
    $Xc(this.j);
    this.h = editor;
    const commentThreadRangeDecorations = [];
    for (const info of commentInfos) {
      info.threads.forEach((thread) => {
        if (thread.isDisposed) {
          return;
        }
        const range = thread.range;
        if (!range || range.startLineNumber === range.endLineNumber && range.startColumn === range.endColumn) {
          return;
        }
        this.j.push(thread.onDidChangeCollapsibleState(() => {
          this.update(editor, commentInfos);
        }));
        if (thread.collapsibleState === CommentThreadCollapsibleState.Collapsed) {
          return;
        }
        commentThreadRangeDecorations.push(new CommentThreadRangeDecoration(range, this.b));
      });
    }
    editor.changeDecorations((changeAccessor) => {
      this.f = changeAccessor.deltaDecorations(this.f, commentThreadRangeDecorations);
      commentThreadRangeDecorations.forEach((decoration3, index) => decoration3.id = this.f[index]);
    });
  }
  dispose() {
    $Xc(this.j);
    this.m?.dispose();
    super.dispose();
  }
};

// out-build/vs/workbench/contrib/comments/browser/commentsController.js
var ID = "editor.contrib.review";
var CommentingRangeDecoration = class {
  get id() {
    return this.c;
  }
  set id(id2) {
    this.c = id2;
  }
  get range() {
    return {
      startLineNumber: this.d,
      startColumn: 1,
      endLineNumber: this.f,
      endColumn: 1
    };
  }
  constructor(g, h3, j, k, l, options3, m, isHover = false) {
    this.g = g;
    this.h = h3;
    this.j = j;
    this.k = k;
    this.l = l;
    this.options = options3;
    this.m = m;
    this.isHover = isHover;
    this.d = l.startLineNumber;
    this.f = l.endLineNumber;
  }
  getCommentAction() {
    return {
      extensionId: this.j,
      label: this.k,
      ownerId: this.h,
      commentingRangesInfo: this.m
    };
  }
  getOriginalRange() {
    return this.l;
  }
  getActiveRange() {
    return this.id ? this.g.getModel().getDecorationRange(this.id) : void 0;
  }
};
var CommentingRangeDecorator = class _CommentingRangeDecorator {
  static {
    this.description = "commenting-range-decorator";
  }
  constructor() {
    this.g = [];
    this.h = [];
    this.l = -1;
    this.o = new $ze();
    this.onDidChangeDecorationsCount = this.o.event;
    const decorationOptions = {
      description: _CommentingRangeDecorator.description,
      isWholeLine: true,
      linesDecorationsClassName: "comment-range-glyph comment-diff-added"
    };
    this.c = $WI.createDynamic(decorationOptions);
    const hoverDecorationOptions = {
      description: _CommentingRangeDecorator.description,
      isWholeLine: true,
      linesDecorationsClassName: `comment-range-glyph line-hover`
    };
    this.d = $WI.createDynamic(hoverDecorationOptions);
    const multilineDecorationOptions = {
      description: _CommentingRangeDecorator.description,
      isWholeLine: true,
      linesDecorationsClassName: `comment-range-glyph multiline-add`
    };
    this.f = $WI.createDynamic(multilineDecorationOptions);
  }
  updateHover(hoverLine) {
    if (this.j && this.k && hoverLine !== this.l) {
      this.q(this.j, this.k, hoverLine);
    }
    this.l = hoverLine ?? -1;
  }
  updateSelection(cursorLine, range = new $9C(0, 0, 0, 0)) {
    this.m = range.isEmpty() ? void 0 : range;
    this.n = range.isEmpty() ? void 0 : cursorLine;
    if (this.j && this.k) {
      this.q(this.j, this.k, cursorLine, range);
    }
  }
  update(editor, commentInfos, cursorLine, range) {
    if (editor) {
      this.j = editor;
      this.k = commentInfos;
      this.q(editor, commentInfos, cursorLine, range);
    }
  }
  p(editor, lineRange) {
    return editor.getDecorationsInRange(lineRange)?.find((decoration3) => decoration3.options.description === $kSb.description);
  }
  q(editor, commentInfos, emphasisLine = -1, selectionRange = this.m) {
    const model = editor.getModel();
    if (!model) {
      return;
    }
    emphasisLine = this.n ?? emphasisLine;
    const commentingRangeDecorations = [];
    for (const info of commentInfos) {
      info.commentingRanges.ranges.forEach((range) => {
        const rangeObject = new $9C(range.startLineNumber, range.startColumn, range.endLineNumber, range.endColumn);
        let intersectingSelectionRange = selectionRange ? rangeObject.intersectRanges(selectionRange) : void 0;
        if (selectionRange && emphasisLine >= 0 && intersectingSelectionRange && !(intersectingSelectionRange.startLineNumber === intersectingSelectionRange.endLineNumber && emphasisLine === intersectingSelectionRange.startLineNumber)) {
          let intersectingEmphasisRange;
          if (emphasisLine <= intersectingSelectionRange.startLineNumber) {
            intersectingEmphasisRange = intersectingSelectionRange.collapseToStart();
            intersectingSelectionRange = new $9C(intersectingSelectionRange.startLineNumber + 1, 1, intersectingSelectionRange.endLineNumber, 1);
          } else {
            intersectingEmphasisRange = new $9C(intersectingSelectionRange.endLineNumber, 1, intersectingSelectionRange.endLineNumber, 1);
            intersectingSelectionRange = new $9C(intersectingSelectionRange.startLineNumber, 1, intersectingSelectionRange.endLineNumber - 1, 1);
          }
          commentingRangeDecorations.push(new CommentingRangeDecoration(editor, info.uniqueOwner, info.extensionId, info.label, intersectingSelectionRange, this.f, info.commentingRanges, true));
          if (!this.p(editor, intersectingEmphasisRange)) {
            commentingRangeDecorations.push(new CommentingRangeDecoration(editor, info.uniqueOwner, info.extensionId, info.label, intersectingEmphasisRange, this.d, info.commentingRanges, true));
          }
          const beforeRangeEndLine = Math.min(intersectingEmphasisRange.startLineNumber, intersectingSelectionRange.startLineNumber) - 1;
          const hasBeforeRange = rangeObject.startLineNumber <= beforeRangeEndLine;
          const afterRangeStartLine = Math.max(intersectingEmphasisRange.endLineNumber, intersectingSelectionRange.endLineNumber) + 1;
          const hasAfterRange = rangeObject.endLineNumber >= afterRangeStartLine;
          if (hasBeforeRange) {
            const beforeRange = new $9C(range.startLineNumber, 1, beforeRangeEndLine, 1);
            commentingRangeDecorations.push(new CommentingRangeDecoration(editor, info.uniqueOwner, info.extensionId, info.label, beforeRange, this.c, info.commentingRanges, true));
          }
          if (hasAfterRange) {
            const afterRange = new $9C(afterRangeStartLine, 1, range.endLineNumber, 1);
            commentingRangeDecorations.push(new CommentingRangeDecoration(editor, info.uniqueOwner, info.extensionId, info.label, afterRange, this.c, info.commentingRanges, true));
          }
        } else if (rangeObject.startLineNumber <= emphasisLine && emphasisLine <= rangeObject.endLineNumber) {
          if (rangeObject.startLineNumber < emphasisLine) {
            const beforeRange = new $9C(range.startLineNumber, 1, emphasisLine - 1, 1);
            commentingRangeDecorations.push(new CommentingRangeDecoration(editor, info.uniqueOwner, info.extensionId, info.label, beforeRange, this.c, info.commentingRanges, true));
          }
          const emphasisRange = new $9C(emphasisLine, 1, emphasisLine, 1);
          if (!this.p(editor, emphasisRange)) {
            commentingRangeDecorations.push(new CommentingRangeDecoration(editor, info.uniqueOwner, info.extensionId, info.label, emphasisRange, this.d, info.commentingRanges, true));
          }
          if (emphasisLine < rangeObject.endLineNumber) {
            const afterRange = new $9C(emphasisLine + 1, 1, range.endLineNumber, 1);
            commentingRangeDecorations.push(new CommentingRangeDecoration(editor, info.uniqueOwner, info.extensionId, info.label, afterRange, this.c, info.commentingRanges, true));
          }
        } else {
          commentingRangeDecorations.push(new CommentingRangeDecoration(editor, info.uniqueOwner, info.extensionId, info.label, range, this.c, info.commentingRanges));
        }
      });
    }
    editor.changeDecorations((accessor) => {
      this.h = accessor.deltaDecorations(this.h, commentingRangeDecorations);
      commentingRangeDecorations.forEach((decoration3, index) => decoration3.id = this.h[index]);
    });
    const rangesDifference = this.g.length - commentingRangeDecorations.length;
    this.g = commentingRangeDecorations;
    if (rangesDifference) {
      this.o.fire(this.g.length);
    }
  }
  r(a, b) {
    if (a.endLineNumber < b.startLineNumber - 1) {
      return false;
    }
    if (b.endLineNumber + 1 < a.startLineNumber) {
      return false;
    }
    return true;
  }
  getMatchedCommentAction(commentRange) {
    if (commentRange === void 0) {
      const foundInfos = this.k?.filter((info) => info.commentingRanges.fileComments);
      if (foundInfos) {
        return foundInfos.map((foundInfo) => {
          return {
            action: {
              ownerId: foundInfo.uniqueOwner,
              extensionId: foundInfo.extensionId,
              label: foundInfo.label,
              commentingRangesInfo: foundInfo.commentingRanges
            }
          };
        });
      }
      return [];
    }
    const foundHoverActions = /* @__PURE__ */ new Map();
    for (const decoration3 of this.g) {
      const range = decoration3.getActiveRange();
      if (range && this.r(range, commentRange)) {
        const action = decoration3.getCommentAction();
        const alreadyFoundInfo = foundHoverActions.get(action.ownerId);
        if (alreadyFoundInfo?.action.commentingRangesInfo === action.commentingRangesInfo) {
          const newRange = new $9C(range.startLineNumber < alreadyFoundInfo.range.startLineNumber ? range.startLineNumber : alreadyFoundInfo.range.startLineNumber, range.startColumn < alreadyFoundInfo.range.startColumn ? range.startColumn : alreadyFoundInfo.range.startColumn, range.endLineNumber > alreadyFoundInfo.range.endLineNumber ? range.endLineNumber : alreadyFoundInfo.range.endLineNumber, range.endColumn > alreadyFoundInfo.range.endColumn ? range.endColumn : alreadyFoundInfo.range.endColumn);
          foundHoverActions.set(action.ownerId, { range: newRange, action });
        } else {
          foundHoverActions.set(action.ownerId, { range, action });
        }
      }
    }
    const seenOwners = /* @__PURE__ */ new Set();
    return Array.from(foundHoverActions.values()).filter((action) => {
      if (seenOwners.has(action.action.ownerId)) {
        return false;
      } else {
        seenOwners.add(action.action.ownerId);
        return true;
      }
    });
  }
  getNearestCommentingRange(findPosition, reverse) {
    let findPositionContainedWithin;
    let decorations;
    if (reverse) {
      decorations = [];
      for (let i2 = this.g.length - 1; i2 >= 0; i2--) {
        decorations.push(this.g[i2]);
      }
    } else {
      decorations = this.g;
    }
    for (const decoration3 of decorations) {
      const range = decoration3.getActiveRange();
      if (!range) {
        continue;
      }
      if (findPositionContainedWithin && this.r(range, findPositionContainedWithin)) {
        findPositionContainedWithin = $9C.plusRange(findPositionContainedWithin, range);
        continue;
      }
      if (range.startLineNumber <= findPosition.lineNumber && findPosition.lineNumber <= range.endLineNumber) {
        findPositionContainedWithin = new $9C(range.startLineNumber, range.startColumn, range.endLineNumber, range.endColumn);
        continue;
      }
      if (!reverse && range.endLineNumber < findPosition.lineNumber) {
        continue;
      }
      if (reverse && range.startLineNumber > findPosition.lineNumber) {
        continue;
      }
      return range;
    }
    return decorations.length > 0 ? decorations[0].getActiveRange() ?? void 0 : void 0;
  }
  dispose() {
    this.g = [];
  }
};
function $rSb(commentInfo, type) {
  if (!commentInfo?.comment || !commentInfo?.thread?.comments) {
    return;
  }
  const currentIndex = commentInfo.thread.comments?.indexOf(commentInfo.comment);
  if (currentIndex === void 0 || currentIndex < 0) {
    return;
  }
  if (type === "previous" && currentIndex === 0) {
    return;
  }
  if (type === "next" && currentIndex === commentInfo.thread.comments.length - 1) {
    return;
  }
  const comment = commentInfo.thread.comments?.[type === "previous" ? currentIndex - 1 : currentIndex + 1];
  if (!comment) {
    return;
  }
  return {
    ...commentInfo,
    comment
  };
}
function $sSb(commentService, editorService, uriIdentityService, commentThread, comment, focusReply, pinned, preserveFocus, sideBySide) {
  if (!commentThread.resource) {
    return;
  }
  if (!commentService.isCommentingEnabled) {
    commentService.enableCommenting(true);
  }
  const range = commentThread.range;
  const focus = focusReply ? CommentWidgetFocus.Editor : preserveFocus ? CommentWidgetFocus.None : CommentWidgetFocus.Widget;
  const activeEditor = editorService.activeTextEditorControl;
  const currentActiveResources = $Q5(activeEditor) ? [activeEditor.getOriginalEditor(), activeEditor.getModifiedEditor()] : activeEditor ? [activeEditor] : [];
  const threadToReveal = commentThread.threadId;
  const commentToReveal = comment?.uniqueIdInThread;
  const resource = URI.parse(commentThread.resource);
  for (const editor of currentActiveResources) {
    const model = editor.getModel();
    if (model instanceof $QI && uriIdentityService.extUri.isEqual(resource, model.uri)) {
      if (threadToReveal && $P5(editor)) {
        const controller = $tSb.get(editor);
        controller?.revealCommentThread(threadToReveal, commentToReveal, true, focus);
      }
      return;
    }
  }
  editorService.openEditor({
    resource,
    options: {
      pinned,
      preserveFocus,
      selection: range ?? new $9C(1, 1, 1, 1)
    }
  }, sideBySide ? $oJ : $nJ).then((editor) => {
    if (editor) {
      const control = editor.getControl();
      if (threadToReveal && $P5(control)) {
        const controller = $tSb.get(control);
        controller?.revealCommentThread(threadToReveal, commentToReveal, true, focus);
      }
    }
  });
}
var $tSb = class $tSb2 {
  constructor(editor, C, D, E, F, G, H, I, contextKeyService, J, K, L) {
    this.C = C;
    this.D = D;
    this.E = E;
    this.F = F;
    this.G = G;
    this.H = H;
    this.I = I;
    this.J = J;
    this.K = K;
    this.L = L;
    this.c = new $2c();
    this.d = new $2c();
    this.l = null;
    this.m = false;
    this.n = 0;
    this.r = [];
    this.w = /* @__PURE__ */ new Map();
    this.x = [];
    this.B = false;
    this.h = [];
    this.g = [];
    this.u = {};
    this.v = {};
    this.o = null;
    this.y = CommentContextKeys.activeCursorHasCommentingRange.bindTo(contextKeyService);
    this.z = CommentContextKeys.activeCursorHasComment.bindTo(contextKeyService);
    this.A = CommentContextKeys.activeEditorHasCommentingRange.bindTo(contextKeyService);
    if (editor instanceof $bdb) {
      return;
    }
    this.f = editor;
    this.j = new CommentingRangeDecorator();
    this.c.add(this.j.onDidChangeDecorationsCount((count) => {
      if (count === 0) {
        this.N();
      } else if (this.x.length === 0) {
        this.M();
      }
    }));
    this.c.add(this.k = new $pSb(this.C));
    this.c.add(this.C.onDidDeleteDataProvider((ownerId2) => {
      if (ownerId2) {
        delete this.u[ownerId2];
        delete this.v[ownerId2];
      } else {
        this.u = {};
        this.v = {};
      }
      this.T();
    }));
    this.c.add(this.C.onDidSetDataProvider((_) => this.$()));
    this.c.add(this.C.onDidUpdateCommentingRanges((_) => this.$()));
    this.c.add(this.C.onDidSetResourceCommentInfos(async (e) => {
      const editorURI = this.f && this.f.hasModel() && this.f.getModel().uri;
      if (editorURI && editorURI.toString() === e.resource.toString()) {
        await this.pb(e.commentInfos.filter((commentInfo) => commentInfo !== null));
      }
    }));
    this.c.add(this.C.onDidChangeCommentingEnabled((e) => {
      if (e) {
        this.M();
        this.T();
      } else {
        this.ob();
        this.N();
        this.j.update(this.f, []);
        this.k.update(this.f, []);
        $Xc(this.g);
        this.g = [];
      }
    }));
    this.c.add(this.f.onWillChangeModel((e) => this.X(e)));
    this.c.add(this.f.onDidChangeModel((_) => this.onModelChanged()));
    this.c.add(this.I.onDidChangeConfiguration((e) => {
      if (e.affectsConfiguration("diffEditor.renderSideBySide")) {
        this.T();
      }
    }));
    this.onModelChanged();
    this.E.registerDecorationType("comment-controller", $4Jb, {});
    this.c.add(this.C.registerContinueOnCommentProvider({
      provideContinueOnComments: () => {
        const pendingComments = [];
        if (this.g) {
          for (const zone of this.g) {
            const zonePendingComments = zone.getPendingComments();
            const pendingNewComment = zonePendingComments.newComment;
            if (!pendingNewComment) {
              continue;
            }
            let lastCommentBody;
            if (zone.commentThread.comments && zone.commentThread.comments.length) {
              const lastComment = zone.commentThread.comments[zone.commentThread.comments.length - 1];
              if (typeof lastComment.body === "string") {
                lastCommentBody = lastComment.body;
              } else {
                lastCommentBody = lastComment.body.value;
              }
            }
            if (pendingNewComment.body !== lastCommentBody) {
              pendingComments.push({
                uniqueOwner: zone.uniqueOwner,
                uri: zone.editor.getModel().uri,
                range: zone.commentThread.range,
                comment: pendingNewComment,
                isReply: zone.commentThread.comments !== void 0 && zone.commentThread.comments.length > 0
              });
            }
          }
        }
        return pendingComments;
      }
    }));
  }
  M() {
    this.x = [];
    if (!this.f) {
      return;
    }
    this.x.push(this.f.onMouseMove((e) => this.P(e)));
    this.x.push(this.f.onMouseLeave(() => this.O()));
    this.x.push(this.f.onDidChangeCursorPosition((e) => this.R(e.position)));
    this.x.push(this.f.onDidFocusEditorWidget(() => this.R(this.f?.getPosition() ?? null)));
    this.x.push(this.f.onDidChangeCursorSelection((e) => this.Q(e)));
    this.x.push(this.f.onDidBlurEditorWidget(() => this.Q()));
  }
  N() {
    $Xc(this.x);
    this.x = [];
  }
  O() {
    this.j.updateHover();
  }
  P(e) {
    const position = e.target.position?.lineNumber;
    if (e.event.leftButton.valueOf() && position && this.l) {
      this.j.updateSelection(position, new $9C(this.l.lineNumber, 1, position, 1));
    } else {
      this.j.updateHover(position);
    }
  }
  Q(e) {
    const position = this.f?.getPosition()?.lineNumber;
    if (position) {
      this.j.updateSelection(position, e?.selection);
    }
  }
  R(e) {
    if (!e) {
      return;
    }
    const range = $9C.fromPositions(e, { column: -1, lineNumber: e.lineNumber });
    const decorations = this.f?.getDecorationsInRange(range);
    let hasCommentingRange = false;
    if (decorations) {
      for (const decoration3 of decorations) {
        if (decoration3.options.description === $kSb.description) {
          hasCommentingRange = false;
          break;
        } else if (decoration3.options.description === CommentingRangeDecorator.description) {
          hasCommentingRange = true;
        }
      }
    }
    this.y.set(hasCommentingRange);
    this.z.set(this.getCommentsAtLine(range).length > 0);
  }
  S(testEditor) {
    if (this.I.getValue("diffEditor.renderSideBySide")) {
      return false;
    }
    const foundEditor = this.J.visibleTextEditorControls.find((editor) => {
      if (editor.getEditorType() === EditorType.IDiffEditor) {
        const diffEditor = editor;
        return diffEditor.getOriginalEditor() === testEditor;
      }
      return false;
    });
    return !!foundEditor;
  }
  T() {
    this.o = $Hh((token) => {
      const editorURI = this.f && this.f.hasModel() && this.f.getModel().uri;
      if (editorURI) {
        return this.C.getDocumentComments(editorURI);
      }
      return Promise.resolve([]);
    });
    this.p = this.o.then(async (commentInfos) => {
      await this.pb($Mb(commentInfos));
      this.o = null;
    }, (error) => console.log(error));
    this.o.then(() => this.p = void 0);
    return this.p;
  }
  U() {
    if (this.t) {
      if (this.s) {
        this.s.cancel();
        this.s = null;
      }
      this.t.trigger(() => {
        const editorURI = this.f && this.f.hasModel() && this.f.getModel().uri;
        if (editorURI) {
          return this.C.getDocumentComments(editorURI);
        }
        return Promise.resolve([]);
      }).then((commentInfos) => {
        if (this.C.isCommentingEnabled) {
          const meaningfulCommentInfos = $Mb(commentInfos);
          this.j.update(this.f, meaningfulCommentInfos, this.f?.getPosition()?.lineNumber, this.f?.getSelection() ?? void 0);
        }
      }, (err) => {
        $gb(err);
        return null;
      });
    }
  }
  static get(editor) {
    return editor.getContribution(ID);
  }
  revealCommentThread(threadId, commentUniqueId, fetchOnceIfNotExist, focus) {
    const commentThreadWidget = this.g.filter((widget) => widget.commentThread.threadId === threadId);
    if (commentThreadWidget.length === 1) {
      commentThreadWidget[0].reveal(commentUniqueId, focus);
    } else if (fetchOnceIfNotExist) {
      if (this.p) {
        this.p.then((_) => {
          this.revealCommentThread(threadId, commentUniqueId, false, focus);
        });
      } else {
        this.T().then((_) => {
          this.revealCommentThread(threadId, commentUniqueId, false, focus);
        });
      }
    }
  }
  collapseAll() {
    for (const widget of this.g) {
      widget.collapse();
    }
  }
  expandAll() {
    for (const widget of this.g) {
      widget.expand();
    }
  }
  expandUnresolved() {
    for (const widget of this.g) {
      if (widget.commentThread.state === CommentThreadState.Unresolved) {
        widget.expand();
      }
    }
  }
  nextCommentThread(focusThread) {
    this.V(focusThread);
  }
  V(focusThread, reverse) {
    if (!this.g.length || !this.f?.hasModel()) {
      return;
    }
    const after = reverse ? this.f.getSelection().getStartPosition() : this.f.getSelection().getEndPosition();
    const sortedWidgets = this.g.sort((a, b) => {
      if (reverse) {
        const temp = a;
        a = b;
        b = temp;
      }
      if (a.commentThread.range === void 0) {
        return -1;
      }
      if (b.commentThread.range === void 0) {
        return 1;
      }
      if (a.commentThread.range.startLineNumber < b.commentThread.range.startLineNumber) {
        return -1;
      }
      if (a.commentThread.range.startLineNumber > b.commentThread.range.startLineNumber) {
        return 1;
      }
      if (a.commentThread.range.startColumn < b.commentThread.range.startColumn) {
        return -1;
      }
      if (a.commentThread.range.startColumn > b.commentThread.range.startColumn) {
        return 1;
      }
      return 0;
    });
    const idx = $6(sortedWidgets, (widget) => {
      const lineValueOne = reverse ? after.lineNumber : widget.commentThread.range?.startLineNumber ?? 0;
      const lineValueTwo = reverse ? widget.commentThread.range?.startLineNumber ?? 0 : after.lineNumber;
      const columnValueOne = reverse ? after.column : widget.commentThread.range?.startColumn ?? 0;
      const columnValueTwo = reverse ? widget.commentThread.range?.startColumn ?? 0 : after.column;
      if (lineValueOne > lineValueTwo) {
        return true;
      }
      if (lineValueOne < lineValueTwo) {
        return false;
      }
      if (columnValueOne > columnValueTwo) {
        return true;
      }
      return false;
    });
    const nextWidget = sortedWidgets[idx];
    if (nextWidget !== void 0) {
      this.f.setSelection(nextWidget.commentThread.range ?? new $9C(1, 1, 1, 1));
      nextWidget.reveal(void 0, focusThread ? CommentWidgetFocus.Widget : CommentWidgetFocus.None);
    }
  }
  previousCommentThread(focusThread) {
    this.V(focusThread, true);
  }
  W(reverse) {
    if (!this.f?.hasModel()) {
      return;
    }
    const after = this.f.getSelection().getEndPosition();
    const range = this.j.getNearestCommentingRange(after, reverse);
    if (range) {
      const position = reverse ? range.getEndPosition() : range.getStartPosition();
      this.f.setPosition(position);
      this.f.revealLineInCenterIfOutsideViewport(position.lineNumber);
    }
    if (this.L.isScreenReaderOptimized()) {
      const commentRangeStart = range?.getStartPosition().lineNumber;
      const commentRangeEnd = range?.getEndPosition().lineNumber;
      if (commentRangeStart && commentRangeEnd) {
        const oneLine = commentRangeStart === commentRangeEnd;
        oneLine ? $_Z(localize(5363, null, commentRangeStart)) : $_Z(localize(5364, null, commentRangeStart, commentRangeEnd));
      }
    }
  }
  nextCommentingRange() {
    this.W();
  }
  previousCommentingRange() {
    this.W(true);
  }
  dispose() {
    this.c.dispose();
    this.d.dispose();
    $Xc(this.x);
    $Xc(this.g);
    this.f = null;
  }
  X(e) {
    if (e.newModelUrl) {
      this.ob(e.newModelUrl);
    }
  }
  async Y(editorId, uniqueOwner, thread) {
    const matchedZones = this.g.filter((zoneWidget) => zoneWidget.uniqueOwner === uniqueOwner && zoneWidget.commentThread.threadId === thread.threadId);
    if (matchedZones.length) {
      return;
    }
    const matchedNewCommentThreadZones = this.g.filter((zoneWidget) => zoneWidget.uniqueOwner === uniqueOwner && zoneWidget.commentThread.commentThreadHandle === -1 && $9C.equalsRange(zoneWidget.commentThread.range, thread.range));
    if (matchedNewCommentThreadZones.length) {
      matchedNewCommentThreadZones[0].update(thread);
      return;
    }
    const continueOnCommentIndex = this.w.get(uniqueOwner)?.findIndex((pending) => {
      if (pending.range === void 0) {
        return thread.range === void 0;
      } else {
        return $9C.lift(pending.range).equalsRange(thread.range);
      }
    });
    let continueOnCommentText;
    if (continueOnCommentIndex !== void 0 && continueOnCommentIndex >= 0) {
      continueOnCommentText = this.w.get(uniqueOwner)?.splice(continueOnCommentIndex, 1)[0].comment.body;
    }
    const pendingCommentText = (this.u[uniqueOwner] && this.u[uniqueOwner][thread.threadId]) ?? continueOnCommentText;
    const pendingEdits = this.v[uniqueOwner] && this.v[uniqueOwner][thread.threadId];
    const shouldReveal = thread.canReply && thread.isTemplate && (!thread.comments || thread.comments.length === 0) && (!thread.editorId || thread.editorId === editorId);
    await this.bb(uniqueOwner, thread, shouldReveal, pendingCommentText, pendingEdits);
    this.h.filter((info) => info.uniqueOwner === uniqueOwner)[0].threads.push(thread);
    this.ob();
  }
  onModelChanged() {
    this.d.clear();
    this.ob();
    this.qb();
    if (!this.f) {
      return;
    }
    this.B = false;
    this.d.add(this.f.onMouseDown((e) => this.cb(e)));
    this.d.add(this.f.onMouseUp((e) => this.db(e)));
    if (this.x.length) {
      this.N();
      this.M();
    }
    this.t = new $Sh(200);
    this.d.add({
      dispose: () => {
        this.t?.cancel();
        this.t = null;
      }
    });
    this.d.add(this.f.onDidChangeModelContent(async () => {
      this.U();
    }));
    this.d.add(this.C.onDidUpdateCommentThreads(async (e) => {
      const editorURI = this.f && this.f.hasModel() && this.f.getModel().uri;
      if (!editorURI || !this.C.isCommentingEnabled) {
        return;
      }
      if (this.o) {
        await this.o;
      }
      const commentInfo = this.h.filter((info) => info.uniqueOwner === e.uniqueOwner);
      if (!commentInfo || !commentInfo.length) {
        return;
      }
      const added = e.added.filter((thread) => thread.resource && thread.resource === editorURI.toString());
      const removed = e.removed.filter((thread) => thread.resource && thread.resource === editorURI.toString());
      const changed = e.changed.filter((thread) => thread.resource && thread.resource === editorURI.toString());
      const pending = e.pending.filter((pending2) => pending2.uri.toString() === editorURI.toString());
      removed.forEach((thread) => {
        const matchedZones = this.g.filter((zoneWidget) => zoneWidget.uniqueOwner === e.uniqueOwner && zoneWidget.commentThread.threadId === thread.threadId && zoneWidget.commentThread.threadId !== "");
        if (matchedZones.length) {
          const matchedZone = matchedZones[0];
          const index = this.g.indexOf(matchedZone);
          this.g.splice(index, 1);
          matchedZone.dispose();
        }
        const infosThreads = this.h.filter((info) => info.uniqueOwner === e.uniqueOwner)[0].threads;
        for (let i2 = 0; i2 < infosThreads.length; i2++) {
          if (infosThreads[i2] === thread) {
            infosThreads.splice(i2, 1);
            i2--;
          }
        }
      });
      for (const thread of changed) {
        const matchedZones = this.g.filter((zoneWidget) => zoneWidget.uniqueOwner === e.uniqueOwner && zoneWidget.commentThread.threadId === thread.threadId);
        if (matchedZones.length) {
          const matchedZone = matchedZones[0];
          matchedZone.update(thread);
          this.ab(thread);
        }
      }
      const editorId = this.f?.getId();
      for (const thread of added) {
        await this.Y(editorId, e.uniqueOwner, thread);
      }
      for (const thread of pending) {
        await this.Z(editorURI, thread);
      }
      this.k.update(this.f, commentInfo);
    }));
    this.$();
  }
  async Z(editorURI, thread) {
    const matchedZones = this.g.filter((zoneWidget) => zoneWidget.uniqueOwner === thread.uniqueOwner && $9C.lift(zoneWidget.commentThread.range)?.equalsRange(thread.range));
    if (thread.isReply && matchedZones.length) {
      this.C.removeContinueOnComment({ uniqueOwner: thread.uniqueOwner, uri: editorURI, range: thread.range, isReply: true });
      matchedZones[0].setPendingComment(thread.comment);
    } else if (matchedZones.length) {
      this.C.removeContinueOnComment({ uniqueOwner: thread.uniqueOwner, uri: editorURI, range: thread.range, isReply: false });
      const existingPendingComment = matchedZones[0].getPendingComments().newComment;
      let pendingComment;
      if (!existingPendingComment || thread.comment.body.includes(existingPendingComment.body)) {
        pendingComment = thread.comment;
      } else if (existingPendingComment.body.includes(thread.comment.body)) {
        pendingComment = existingPendingComment;
      } else {
        pendingComment = { body: `${existingPendingComment}
${thread.comment.body}`, cursor: thread.comment.cursor };
      }
      matchedZones[0].setPendingComment(pendingComment);
    } else if (!thread.isReply) {
      const threadStillAvailable = this.C.removeContinueOnComment({ uniqueOwner: thread.uniqueOwner, uri: editorURI, range: thread.range, isReply: false });
      if (!threadStillAvailable) {
        return;
      }
      if (!this.w.has(thread.uniqueOwner)) {
        this.w.set(thread.uniqueOwner, []);
      }
      this.w.get(thread.uniqueOwner)?.push(thread);
      await this.C.createCommentThreadTemplate(thread.uniqueOwner, thread.uri, thread.range ? $9C.lift(thread.range) : void 0);
    }
  }
  $() {
    this.T().then(() => {
      if (!this.B) {
        if (this.h.some((commentInfo) => commentInfo.commentingRanges.ranges.length > 0 || commentInfo.commentingRanges.fileComments)) {
          this.B = true;
          const verbose = this.I.getValue(
            "accessibility.verbosity.comments"
            /* AccessibilityVerbositySettingId.Comments */
          );
          if (verbose) {
            const keybinding = this.K.lookupKeybinding(
              "editor.action.accessibilityHelp"
              /* AccessibilityCommandId.OpenAccessibilityHelp */
            )?.getAriaLabel();
            if (keybinding) {
              $_Z(localize(5365, null, keybinding));
            } else {
              $_Z(localize(5366, null));
            }
          } else {
            $_Z(localize(5367, null));
          }
        }
      }
    });
  }
  async ab(thread) {
    if (thread.comments && thread.comments.length > 0 && $PJb(thread)) {
      const openViewState = this.I.getValue($OJb).openView;
      if (openViewState === "file") {
        return this.H.openView($_Rb);
      } else if (openViewState === "firstFile" || openViewState === "firstFileUnresolved" && thread.state === CommentThreadState.Unresolved) {
        const hasShownView = this.H.getViewWithId($_Rb)?.hasRendered;
        if (!hasShownView) {
          return this.H.openView($_Rb);
        }
      }
    }
    return void 0;
  }
  async bb(uniqueOwner, thread, shouldReveal, pendingComment, pendingEdits) {
    const editor = this.f?.getModel();
    if (!editor) {
      return;
    }
    if (!this.f || this.S(this.f)) {
      return;
    }
    let continueOnCommentReply;
    if (thread.range && !pendingComment) {
      continueOnCommentReply = this.C.removeContinueOnComment({ uniqueOwner, uri: editor.uri, range: thread.range, isReply: true });
    }
    const zoneWidget = this.D.createInstance($oSb, this.f, uniqueOwner, thread, pendingComment ?? continueOnCommentReply?.comment, pendingEdits);
    await zoneWidget.display(thread.range, shouldReveal);
    this.g.push(zoneWidget);
    this.ab(thread);
  }
  cb(e) {
    this.l = $lSb(e);
  }
  db(e) {
    const matchedLineNumber = $mSb(this.l, e);
    this.l = null;
    if (!this.f || matchedLineNumber === null || !e.target.element) {
      return;
    }
    const mouseUpIsOnDecorator = e.target.element.className.indexOf("comment-range-glyph") >= 0;
    const lineNumber = e.target.position.lineNumber;
    let range;
    let selection;
    if (matchedLineNumber !== lineNumber) {
      if (matchedLineNumber > lineNumber) {
        selection = new $9C(matchedLineNumber, this.f.getModel().getLineLength(matchedLineNumber) + 1, lineNumber, 1);
      } else {
        selection = new $9C(matchedLineNumber, 1, lineNumber, this.f.getModel().getLineLength(lineNumber) + 1);
      }
    } else if (mouseUpIsOnDecorator) {
      selection = this.f.getSelection();
    }
    if (selection && selection.startLineNumber <= lineNumber && lineNumber <= selection.endLineNumber) {
      range = selection;
      this.f.setSelection(new $9C(selection.endLineNumber, 1, selection.endLineNumber, 1));
    } else if (mouseUpIsOnDecorator) {
      range = new $9C(lineNumber, 1, lineNumber, 1);
    }
    if (range) {
      this.addOrToggleCommentAtLine(range, e);
    }
  }
  getCommentsAtLine(commentRange) {
    return this.g.filter((widget) => widget.getGlyphPosition() === (commentRange ? commentRange.endLineNumber : 0));
  }
  async addOrToggleCommentAtLine(commentRange, e) {
    if (!this.q) {
      this.q = true;
      const existingCommentsAtLine = this.getCommentsAtLine(commentRange);
      if (existingCommentsAtLine.length) {
        const allExpanded = existingCommentsAtLine.every((widget) => widget.expanded);
        existingCommentsAtLine.forEach(allExpanded ? (widget) => widget.collapse() : (widget) => widget.expand(true));
        this.eb();
        return;
      } else {
        this.addCommentAtLine(commentRange, e);
      }
    } else {
      this.r.push([commentRange, e]);
    }
  }
  eb() {
    this.q = false;
    const info = this.r.shift();
    if (info) {
      this.addOrToggleCommentAtLine(info[0], info[1]);
    }
  }
  fb(userRange, commentRange) {
    if (userRange.startLineNumber < commentRange.startLineNumber) {
      userRange = new $9C(commentRange.startLineNumber, commentRange.startColumn, userRange.endLineNumber, userRange.endColumn);
    }
    if (userRange.endLineNumber > commentRange.endLineNumber) {
      userRange = new $9C(userRange.startLineNumber, userRange.startColumn, commentRange.endLineNumber, commentRange.endColumn);
    }
    return userRange;
  }
  addCommentAtLine(range, e) {
    const newCommentInfos = this.j.getMatchedCommentAction(range);
    if (!newCommentInfos.length || !this.f?.hasModel()) {
      this.q = false;
      if (!newCommentInfos.length) {
        throw new Error(`There are no commenting ranges at the current position (${range ? "with range" : "without range"}).`);
      }
      return Promise.resolve();
    }
    if (newCommentInfos.length > 1) {
      if (e && range) {
        this.F.showContextMenu({
          getAnchor: () => e.event,
          getActions: () => this.hb(newCommentInfos, range),
          getActionsContext: () => newCommentInfos.length ? newCommentInfos[0] : void 0,
          onHide: () => {
            this.q = false;
          }
        });
        return Promise.resolve();
      } else {
        const picks = this.gb(newCommentInfos);
        return this.G.pick(picks, { placeHolder: localize(5368, null), matchOnDescription: true }).then((pick) => {
          if (!pick) {
            return;
          }
          const commentInfos = newCommentInfos.filter((info) => info.action.ownerId === pick.id);
          if (commentInfos.length) {
            const { ownerId: ownerId2 } = commentInfos[0].action;
            const clippedRange = range && commentInfos[0].range ? this.fb(range, commentInfos[0].range) : range;
            this.addCommentAtLine2(clippedRange, ownerId2);
          }
        }).then(() => {
          this.q = false;
        });
      }
    } else {
      const { ownerId: ownerId2 } = newCommentInfos[0].action;
      const clippedRange = range && newCommentInfos[0].range ? this.fb(range, newCommentInfos[0].range) : range;
      this.addCommentAtLine2(clippedRange, ownerId2);
    }
    return Promise.resolve();
  }
  gb(commentInfos) {
    const picks = commentInfos.map((commentInfo) => {
      const { ownerId: ownerId2, extensionId, label: label3 } = commentInfo.action;
      return {
        label: label3 ?? extensionId ?? ownerId2,
        id: ownerId2
      };
    });
    return picks;
  }
  hb(commentInfos, commentRange) {
    const actions = [];
    commentInfos.forEach((commentInfo) => {
      const { ownerId: ownerId2, extensionId, label: label3 } = commentInfo.action;
      actions.push(new $Um("addCommentThread", `${label3 || extensionId}`, void 0, true, () => {
        const clippedRange = commentInfo.range ? this.fb(commentRange, commentInfo.range) : commentRange;
        this.addCommentAtLine2(clippedRange, ownerId2);
        return Promise.resolve();
      }));
    });
    return actions;
  }
  addCommentAtLine2(range, ownerId2) {
    if (!this.f) {
      return;
    }
    this.C.createCommentThreadTemplate(ownerId2, this.f.getModel().uri, range, this.f.getId());
    this.eb();
    return;
  }
  ib(editor) {
    const lineDecorationsWidth = editor.getOption(
      67
      /* EditorOption.lineDecorationsWidth */
    );
    let extraEditorClassName = [];
    const configuredExtraClassName = editor.getRawOptions().extraEditorClassName;
    if (configuredExtraClassName) {
      extraEditorClassName = configuredExtraClassName.split(" ");
    }
    return { lineDecorationsWidth, extraEditorClassName };
  }
  jb(editor, extraEditorClassName, startingLineDecorationsWidth) {
    let lineDecorationsWidth = startingLineDecorationsWidth;
    const inlineCommentPos = extraEditorClassName.findIndex((name) => name === "inline-comment");
    if (inlineCommentPos >= 0) {
      extraEditorClassName.splice(inlineCommentPos, 1);
    }
    const options3 = editor.getOptions();
    if (options3.get(
      45
      /* EditorOption.folding */
    ) && options3.get(
      115
      /* EditorOption.showFoldingControls */
    ) !== "never") {
      lineDecorationsWidth += 11;
    }
    lineDecorationsWidth -= 24;
    return { extraEditorClassName, lineDecorationsWidth };
  }
  kb(editor, startingLineDecorationsWidth) {
    let lineDecorationsWidth = startingLineDecorationsWidth;
    const options3 = editor.getOptions();
    if (options3.get(
      45
      /* EditorOption.folding */
    ) && options3.get(
      115
      /* EditorOption.showFoldingControls */
    ) !== "never") {
      lineDecorationsWidth -= 11;
    }
    lineDecorationsWidth += 24;
    this.n = lineDecorationsWidth;
    return this.n;
  }
  lb(editor, extraEditorClassName, startingLineDecorationsWidth) {
    extraEditorClassName.push("inline-comment");
    return { lineDecorationsWidth: this.kb(editor, startingLineDecorationsWidth), extraEditorClassName };
  }
  mb(editor, extraEditorClassName, lineDecorationsWidth) {
    editor.updateOptions({
      extraEditorClassName: extraEditorClassName.join(" "),
      lineDecorationsWidth
    });
  }
  nb(editor) {
    const existing = this.ib(editor);
    if (existing.lineDecorationsWidth !== this.n) {
      editor.updateOptions({
        lineDecorationsWidth: this.kb(editor, existing.lineDecorationsWidth)
      });
    }
  }
  ob(uri) {
    if (!this.f) {
      return;
    }
    const hasCommentsOrRangesInInfo = this.h.some((info) => {
      const hasRanges = Boolean(info.commentingRanges && (Array.isArray(info.commentingRanges) ? info.commentingRanges : info.commentingRanges.ranges).length);
      return hasRanges || info.threads.length > 0;
    });
    uri = uri ?? this.f.getModel()?.uri;
    const resourceHasCommentingRanges = uri ? this.C.resourceHasCommentingRanges(uri) : false;
    const hasCommentsOrRanges = hasCommentsOrRangesInInfo || resourceHasCommentingRanges;
    if (hasCommentsOrRanges && this.C.isCommentingEnabled) {
      if (!this.m) {
        this.m = true;
        const { lineDecorationsWidth, extraEditorClassName } = this.ib(this.f);
        const newOptions = this.lb(this.f, extraEditorClassName, lineDecorationsWidth);
        this.mb(this.f, newOptions.extraEditorClassName, newOptions.lineDecorationsWidth);
      } else {
        this.nb(this.f);
      }
    } else if ((!hasCommentsOrRanges || !this.C.isCommentingEnabled) && this.m) {
      this.m = false;
      const { lineDecorationsWidth, extraEditorClassName } = this.ib(this.f);
      const newOptions = this.jb(this.f, extraEditorClassName, lineDecorationsWidth);
      this.mb(this.f, newOptions.extraEditorClassName, newOptions.lineDecorationsWidth);
    }
  }
  async pb(commentInfos) {
    if (!this.f || !this.C.isCommentingEnabled) {
      return;
    }
    this.h = commentInfos;
    this.ob();
    this.qb();
    let hasCommentingRanges = false;
    for (const info of this.h) {
      if (!hasCommentingRanges && (info.commentingRanges.ranges.length > 0 || info.commentingRanges.fileComments)) {
        hasCommentingRanges = true;
      }
      const providerCacheStore = this.u[info.uniqueOwner];
      const providerEditsCacheStore = this.v[info.uniqueOwner];
      info.threads = info.threads.filter((thread) => !thread.isDisposed);
      for (const thread of info.threads) {
        let pendingComment = void 0;
        if (providerCacheStore) {
          pendingComment = providerCacheStore[thread.threadId];
        }
        let pendingEdits = void 0;
        if (providerEditsCacheStore) {
          pendingEdits = providerEditsCacheStore[thread.threadId];
        }
        await this.bb(info.uniqueOwner, thread, false, pendingComment, pendingEdits);
      }
      for (const thread of info.pendingCommentThreads ?? []) {
        this.Z(this.f.getModel().uri, thread);
      }
    }
    this.j.update(this.f, this.h);
    this.k.update(this.f, this.h);
    if (hasCommentingRanges) {
      this.A.set(true);
    } else {
      this.A.set(false);
    }
  }
  collapseAndFocusRange(threadId) {
    this.g?.find((widget) => widget.commentThread.threadId === threadId)?.collapseAndFocusRange();
  }
  qb() {
    if (this.g) {
      this.g.forEach((zone) => {
        const pendingComments = zone.getPendingComments();
        const pendingNewComment = pendingComments.newComment;
        const providerNewCommentCacheStore = this.u[zone.uniqueOwner];
        let lastCommentBody;
        if (zone.commentThread.comments && zone.commentThread.comments.length) {
          const lastComment = zone.commentThread.comments[zone.commentThread.comments.length - 1];
          if (typeof lastComment.body === "string") {
            lastCommentBody = lastComment.body;
          } else {
            lastCommentBody = lastComment.body.value;
          }
        }
        if (pendingNewComment && pendingNewComment.body !== lastCommentBody) {
          if (!providerNewCommentCacheStore) {
            this.u[zone.uniqueOwner] = {};
          }
          this.u[zone.uniqueOwner][zone.commentThread.threadId] = pendingNewComment;
        } else {
          if (providerNewCommentCacheStore) {
            delete providerNewCommentCacheStore[zone.commentThread.threadId];
          }
        }
        const pendingEdits = pendingComments.edits;
        const providerEditsCacheStore = this.v[zone.uniqueOwner];
        if (Object.keys(pendingEdits).length > 0) {
          if (!providerEditsCacheStore) {
            this.v[zone.uniqueOwner] = {};
          }
          this.v[zone.uniqueOwner][zone.commentThread.threadId] = pendingEdits;
        } else if (providerEditsCacheStore) {
          delete providerEditsCacheStore[zone.commentThread.threadId];
        }
        zone.dispose();
      });
    }
    this.g = [];
  }
};
$tSb = __decorate([
  __param(1, $RJb),
  __param(2, $Pk),
  __param(3, $U5),
  __param(4, $50),
  __param(5, $1M),
  __param(6, $uob),
  __param(7, $kl),
  __param(8, $on),
  __param(9, $mJ),
  __param(10, $Ty),
  __param(11, $ND)
], $tSb);

// out-build/vs/workbench/contrib/accessibility/browser/accessibilityConfiguration.js
var $nsb = new $nn("accessibilityHelpIsShown", false, true);
var $osb = new $nn("accessibleViewIsShown", false, true);
var $psb = new $nn("accessibleViewSupportsNavigation", false, true);
var $qsb = new $nn("accessibleViewVerbosityEnabled", false, true);
var $rsb = new $nn("accessibleViewGoToSymbolSupported", false, true);
var $ssb = new $nn("accessibleViewOnLastLine", false, true);
var $tsb = new $nn("accessibleViewCurrentProviderId", void 0, void 0);
var $usb = new $nn("accessibleViewInCodeBlock", void 0, void 0);
var $vsb = new $nn("accessibleViewContainsCodeBlocks", void 0, void 0);
var $wsb = new $nn("accessibleViewHasUnassignedKeybindings", void 0, void 0);
var $xsb = new $nn("accessibleViewHasAssignedKeybindings", void 0, void 0);
var AccessibilityWorkbenchSettingId;
(function(AccessibilityWorkbenchSettingId2) {
  AccessibilityWorkbenchSettingId2["DimUnfocusedEnabled"] = "accessibility.dimUnfocused.enabled";
  AccessibilityWorkbenchSettingId2["DimUnfocusedOpacity"] = "accessibility.dimUnfocused.opacity";
  AccessibilityWorkbenchSettingId2["HideAccessibleView"] = "accessibility.hideAccessibleView";
  AccessibilityWorkbenchSettingId2["AccessibleViewCloseOnKeyPress"] = "accessibility.accessibleView.closeOnKeyPress";
})(AccessibilityWorkbenchSettingId || (AccessibilityWorkbenchSettingId = {}));
var ViewDimUnfocusedOpacityProperties;
(function(ViewDimUnfocusedOpacityProperties2) {
  ViewDimUnfocusedOpacityProperties2[ViewDimUnfocusedOpacityProperties2["Default"] = 0.75] = "Default";
  ViewDimUnfocusedOpacityProperties2[ViewDimUnfocusedOpacityProperties2["Minimum"] = 0.2] = "Minimum";
  ViewDimUnfocusedOpacityProperties2[ViewDimUnfocusedOpacityProperties2["Maximum"] = 1] = "Maximum";
})(ViewDimUnfocusedOpacityProperties || (ViewDimUnfocusedOpacityProperties = {}));
var AccessibilityVerbositySettingId;
(function(AccessibilityVerbositySettingId2) {
  AccessibilityVerbositySettingId2["Terminal"] = "accessibility.verbosity.terminal";
  AccessibilityVerbositySettingId2["DiffEditor"] = "accessibility.verbosity.diffEditor";
  AccessibilityVerbositySettingId2["Chat"] = "accessibility.verbosity.panelChat";
  AccessibilityVerbositySettingId2["InlineChat"] = "accessibility.verbosity.inlineChat";
  AccessibilityVerbositySettingId2["TerminalChat"] = "accessibility.verbosity.terminalChat";
  AccessibilityVerbositySettingId2["InlineCompletions"] = "accessibility.verbosity.inlineCompletions";
  AccessibilityVerbositySettingId2["KeybindingsEditor"] = "accessibility.verbosity.keybindingsEditor";
  AccessibilityVerbositySettingId2["Notebook"] = "accessibility.verbosity.notebook";
  AccessibilityVerbositySettingId2["Editor"] = "accessibility.verbosity.editor";
  AccessibilityVerbositySettingId2["Hover"] = "accessibility.verbosity.hover";
  AccessibilityVerbositySettingId2["Notification"] = "accessibility.verbosity.notification";
  AccessibilityVerbositySettingId2["EmptyEditorHint"] = "accessibility.verbosity.emptyEditorHint";
  AccessibilityVerbositySettingId2["ReplEditor"] = "accessibility.verbosity.replEditor";
  AccessibilityVerbositySettingId2["Comments"] = "accessibility.verbosity.comments";
  AccessibilityVerbositySettingId2["DiffEditorActive"] = "accessibility.verbosity.diffEditorActive";
  AccessibilityVerbositySettingId2["Debug"] = "accessibility.verbosity.debug";
  AccessibilityVerbositySettingId2["Walkthrough"] = "accessibility.verbosity.walkthrough";
})(AccessibilityVerbositySettingId || (AccessibilityVerbositySettingId = {}));
var baseVerbosityProperty = {
  type: "boolean",
  default: true,
  tags: ["accessibility"]
};
var $ysb = Object.freeze({
  id: "accessibility",
  title: localize(4302, null),
  type: "object"
});
var $zsb = {
  "type": "string",
  "enum": ["auto", "on", "off"],
  "default": "auto",
  "enumDescriptions": [
    localize(4303, null),
    localize(4304, null),
    localize(4305, null)
  ],
  tags: ["accessibility"]
};
var signalFeatureBase = {
  "type": "object",
  "tags": ["accessibility"],
  additionalProperties: false,
  default: {
    sound: "auto",
    announcement: "auto"
  }
};
var $Asb = {
  "type": "string",
  "enum": ["auto", "off"],
  "default": "auto",
  "enumDescriptions": [
    localize(4306, null),
    localize(4307, null)
  ],
  tags: ["accessibility"]
};
var defaultNoAnnouncement = {
  "type": "object",
  "tags": ["accessibility"],
  additionalProperties: false,
  "default": {
    "sound": "auto"
  }
};
var configuration = {
  ...$ysb,
  scope: 4,
  properties: {
    [
      "accessibility.verbosity.terminal"
      /* AccessibilityVerbositySettingId.Terminal */
    ]: {
      description: localize(4308, null),
      ...baseVerbosityProperty
    },
    [
      "accessibility.verbosity.diffEditor"
      /* AccessibilityVerbositySettingId.DiffEditor */
    ]: {
      description: localize(4309, null),
      ...baseVerbosityProperty
    },
    [
      "accessibility.verbosity.panelChat"
      /* AccessibilityVerbositySettingId.Chat */
    ]: {
      description: localize(4310, null),
      ...baseVerbosityProperty
    },
    [
      "accessibility.verbosity.inlineChat"
      /* AccessibilityVerbositySettingId.InlineChat */
    ]: {
      description: localize(4311, null),
      ...baseVerbosityProperty
    },
    [
      "accessibility.verbosity.inlineCompletions"
      /* AccessibilityVerbositySettingId.InlineCompletions */
    ]: {
      description: localize(4312, null),
      ...baseVerbosityProperty
    },
    [
      "accessibility.verbosity.keybindingsEditor"
      /* AccessibilityVerbositySettingId.KeybindingsEditor */
    ]: {
      description: localize(4313, null),
      ...baseVerbosityProperty
    },
    [
      "accessibility.verbosity.notebook"
      /* AccessibilityVerbositySettingId.Notebook */
    ]: {
      description: localize(4314, null),
      ...baseVerbosityProperty
    },
    [
      "accessibility.verbosity.hover"
      /* AccessibilityVerbositySettingId.Hover */
    ]: {
      description: localize(4315, null),
      ...baseVerbosityProperty
    },
    [
      "accessibility.verbosity.notification"
      /* AccessibilityVerbositySettingId.Notification */
    ]: {
      description: localize(4316, null),
      ...baseVerbosityProperty
    },
    [
      "accessibility.verbosity.emptyEditorHint"
      /* AccessibilityVerbositySettingId.EmptyEditorHint */
    ]: {
      description: localize(4317, null),
      ...baseVerbosityProperty
    },
    [
      "accessibility.verbosity.replEditor"
      /* AccessibilityVerbositySettingId.ReplEditor */
    ]: {
      description: localize(4318, null),
      ...baseVerbosityProperty
    },
    [
      "accessibility.verbosity.comments"
      /* AccessibilityVerbositySettingId.Comments */
    ]: {
      description: localize(4319, null),
      ...baseVerbosityProperty
    },
    [
      "accessibility.verbosity.diffEditorActive"
      /* AccessibilityVerbositySettingId.DiffEditorActive */
    ]: {
      description: localize(4320, null),
      ...baseVerbosityProperty
    },
    [
      "accessibility.verbosity.debug"
      /* AccessibilityVerbositySettingId.Debug */
    ]: {
      description: localize(4321, null),
      ...baseVerbosityProperty
    },
    [
      "accessibility.verbosity.walkthrough"
      /* AccessibilityVerbositySettingId.Walkthrough */
    ]: {
      description: localize(4322, null),
      ...baseVerbosityProperty
    },
    [
      "accessibility.accessibleView.closeOnKeyPress"
      /* AccessibilityWorkbenchSettingId.AccessibleViewCloseOnKeyPress */
    ]: {
      markdownDescription: localize(4323, null),
      type: "boolean",
      default: true
    },
    "accessibility.signalOptions.volume": {
      "description": localize(4324, null),
      "type": "number",
      "minimum": 0,
      "maximum": 100,
      "default": 70,
      "tags": ["accessibility"]
    },
    "accessibility.signalOptions.debouncePositionChanges": {
      "description": localize(4325, null),
      "type": "boolean",
      "default": false,
      "tags": ["accessibility"]
    },
    "accessibility.signalOptions.experimental.delays.general": {
      "type": "object",
      "description": "Delays for all signals besides error and warning at position",
      "additionalProperties": false,
      "properties": {
        "announcement": {
          "description": localize(4326, null),
          "type": "number",
          "minimum": 0,
          "default": 3e3
        },
        "sound": {
          "description": localize(4327, null),
          "type": "number",
          "minimum": 0,
          "default": 400
        }
      },
      "tags": ["accessibility"]
    },
    "accessibility.signalOptions.experimental.delays.warningAtPosition": {
      "type": "object",
      "additionalProperties": false,
      "properties": {
        "announcement": {
          "description": localize(4328, null),
          "type": "number",
          "minimum": 0,
          "default": 3e3
        },
        "sound": {
          "description": localize(4329, null),
          "type": "number",
          "minimum": 0,
          "default": 1e3
        }
      },
      "tags": ["accessibility"]
    },
    "accessibility.signalOptions.experimental.delays.errorAtPosition": {
      "type": "object",
      "additionalProperties": false,
      "properties": {
        "announcement": {
          "description": localize(4330, null),
          "type": "number",
          "minimum": 0,
          "default": 3e3
        },
        "sound": {
          "description": localize(4331, null),
          "type": "number",
          "minimum": 0,
          "default": 1e3
        }
      },
      "tags": ["accessibility"]
    },
    "accessibility.signals.lineHasBreakpoint": {
      ...signalFeatureBase,
      "description": localize(4332, null),
      "properties": {
        "sound": {
          "description": localize(4333, null),
          ...$zsb
        },
        "announcement": {
          "description": localize(4334, null),
          ...$Asb
        }
      }
    },
    "accessibility.signals.lineHasInlineSuggestion": {
      ...defaultNoAnnouncement,
      "description": localize(4335, null),
      "properties": {
        "sound": {
          "description": localize(4336, null),
          ...$zsb,
          "default": "off"
        }
      }
    },
    "accessibility.signals.lineHasError": {
      ...signalFeatureBase,
      "description": localize(4337, null),
      "properties": {
        "sound": {
          "description": localize(4338, null),
          ...$zsb
        },
        "announcement": {
          "description": localize(4339, null),
          ...$Asb,
          default: "off"
        }
      }
    },
    "accessibility.signals.lineHasFoldedArea": {
      ...signalFeatureBase,
      "description": localize(4340, null),
      "properties": {
        "sound": {
          "description": localize(4341, null),
          ...$zsb,
          default: "off"
        },
        "announcement": {
          "description": localize(4342, null),
          ...$Asb
        }
      }
    },
    "accessibility.signals.lineHasWarning": {
      ...signalFeatureBase,
      "description": localize(4343, null),
      "properties": {
        "sound": {
          "description": localize(4344, null),
          ...$zsb
        },
        "announcement": {
          "description": localize(4345, null),
          ...$Asb,
          default: "off"
        }
      }
    },
    "accessibility.signals.positionHasError": {
      ...signalFeatureBase,
      "description": localize(4346, null),
      "properties": {
        "sound": {
          "description": localize(4347, null),
          ...$zsb
        },
        "announcement": {
          "description": localize(4348, null),
          ...$Asb,
          default: "on"
        }
      }
    },
    "accessibility.signals.positionHasWarning": {
      ...signalFeatureBase,
      "description": localize(4349, null),
      "properties": {
        "sound": {
          "description": localize(4350, null),
          ...$zsb
        },
        "announcement": {
          "description": localize(4351, null),
          ...$Asb,
          default: "on"
        }
      }
    },
    "accessibility.signals.onDebugBreak": {
      ...signalFeatureBase,
      "description": localize(4352, null),
      "properties": {
        "sound": {
          "description": localize(4353, null),
          ...$zsb
        },
        "announcement": {
          "description": localize(4354, null),
          ...$Asb
        }
      }
    },
    "accessibility.signals.noInlayHints": {
      ...signalFeatureBase,
      "description": localize(4355, null),
      "properties": {
        "sound": {
          "description": localize(4356, null),
          ...$zsb
        },
        "announcement": {
          "description": localize(4357, null),
          ...$Asb
        }
      }
    },
    "accessibility.signals.taskCompleted": {
      ...signalFeatureBase,
      "description": localize(4358, null),
      "properties": {
        "sound": {
          "description": localize(4359, null),
          ...$zsb
        },
        "announcement": {
          "description": localize(4360, null),
          ...$Asb
        }
      }
    },
    "accessibility.signals.taskFailed": {
      ...signalFeatureBase,
      "description": localize(4361, null),
      "properties": {
        "sound": {
          "description": localize(4362, null),
          ...$zsb
        },
        "announcement": {
          "description": localize(4363, null),
          ...$Asb
        }
      }
    },
    "accessibility.signals.terminalCommandFailed": {
      ...signalFeatureBase,
      "description": localize(4364, null),
      "properties": {
        "sound": {
          "description": localize(4365, null),
          ...$zsb
        },
        "announcement": {
          "description": localize(4366, null),
          ...$Asb
        }
      }
    },
    "accessibility.signals.terminalCommandSucceeded": {
      ...signalFeatureBase,
      "description": localize(4367, null),
      "properties": {
        "sound": {
          "description": localize(4368, null),
          ...$zsb
        },
        "announcement": {
          "description": localize(4369, null),
          ...$Asb
        }
      }
    },
    "accessibility.signals.terminalQuickFix": {
      ...signalFeatureBase,
      "description": localize(4370, null),
      "properties": {
        "sound": {
          "description": localize(4371, null),
          ...$zsb
        },
        "announcement": {
          "description": localize(4372, null),
          ...$Asb
        }
      }
    },
    "accessibility.signals.terminalBell": {
      ...signalFeatureBase,
      "description": localize(4373, null),
      "properties": {
        "sound": {
          "description": localize(4374, null),
          ...$zsb
        },
        "announcement": {
          "description": localize(4375, null),
          ...$Asb
        }
      }
    },
    "accessibility.signals.diffLineInserted": {
      ...defaultNoAnnouncement,
      "description": localize(4376, null),
      "properties": {
        "sound": {
          "description": localize(4377, null),
          ...$zsb
        }
      }
    },
    "accessibility.signals.diffLineModified": {
      ...defaultNoAnnouncement,
      "description": localize(4378, null),
      "properties": {
        "sound": {
          "description": localize(4379, null),
          ...$zsb
        }
      }
    },
    "accessibility.signals.diffLineDeleted": {
      ...defaultNoAnnouncement,
      "description": localize(4380, null),
      "properties": {
        "sound": {
          "description": localize(4381, null),
          ...$zsb
        }
      }
    },
    "accessibility.signals.notebookCellCompleted": {
      ...signalFeatureBase,
      "description": localize(4382, null),
      "properties": {
        "sound": {
          "description": localize(4383, null),
          ...$zsb
        },
        "announcement": {
          "description": localize(4384, null),
          ...$Asb
        }
      }
    },
    "accessibility.signals.notebookCellFailed": {
      ...signalFeatureBase,
      "description": localize(4385, null),
      "properties": {
        "sound": {
          "description": localize(4386, null),
          ...$zsb
        },
        "announcement": {
          "description": localize(4387, null),
          ...$Asb
        }
      }
    },
    "accessibility.signals.progress": {
      ...signalFeatureBase,
      "description": localize(4388, null),
      "properties": {
        "sound": {
          "description": localize(4389, null),
          ...$zsb
        },
        "announcement": {
          "description": localize(4390, null),
          ...$Asb
        }
      }
    },
    "accessibility.signals.chatRequestSent": {
      ...signalFeatureBase,
      "description": localize(4391, null),
      "properties": {
        "sound": {
          "description": localize(4392, null),
          ...$zsb
        },
        "announcement": {
          "description": localize(4393, null),
          ...$Asb
        }
      }
    },
    "accessibility.signals.chatResponseReceived": {
      ...defaultNoAnnouncement,
      "description": localize(4394, null),
      "properties": {
        "sound": {
          "description": localize(4395, null),
          ...$zsb
        }
      }
    },
    "accessibility.signals.codeActionTriggered": {
      ...defaultNoAnnouncement,
      "description": localize(4396, null),
      "properties": {
        "sound": {
          "description": localize(4397, null),
          ...$zsb
        }
      }
    },
    "accessibility.signals.codeActionApplied": {
      ...defaultNoAnnouncement,
      "description": localize(4398, null),
      "properties": {
        "sound": {
          "description": localize(4399, null),
          ...$zsb
        }
      }
    },
    "accessibility.signals.voiceRecordingStarted": {
      ...defaultNoAnnouncement,
      "description": localize(4400, null),
      "properties": {
        "sound": {
          "description": localize(4401, null),
          ...$zsb
        }
      },
      "default": {
        "sound": "on"
      }
    },
    "accessibility.signals.voiceRecordingStopped": {
      ...defaultNoAnnouncement,
      "description": localize(4402, null),
      "properties": {
        "sound": {
          "description": localize(4403, null),
          ...$zsb,
          default: "off"
        }
      }
    },
    "accessibility.signals.clear": {
      ...signalFeatureBase,
      "description": localize(4404, null),
      "properties": {
        "sound": {
          "description": localize(4405, null),
          ...$zsb
        },
        "announcement": {
          "description": localize(4406, null),
          ...$Asb
        }
      }
    },
    "accessibility.signals.save": {
      "type": "object",
      "tags": ["accessibility"],
      additionalProperties: false,
      "markdownDescription": localize(4407, null),
      "properties": {
        "sound": {
          "description": localize(4408, null),
          "type": "string",
          "enum": ["userGesture", "always", "never"],
          "default": "never",
          "enumDescriptions": [
            localize(4409, null),
            localize(4410, null),
            localize(4411, null)
          ]
        },
        "announcement": {
          "description": localize(4412, null),
          "type": "string",
          "enum": ["userGesture", "always", "never"],
          "default": "never",
          "enumDescriptions": [
            localize(4413, null),
            localize(4414, null),
            localize(4415, null)
          ]
        }
      },
      default: {
        "sound": "never",
        "announcement": "never"
      }
    },
    "accessibility.signals.format": {
      "type": "object",
      "tags": ["accessibility"],
      additionalProperties: false,
      "markdownDescription": localize(4416, null),
      "properties": {
        "sound": {
          "description": localize(4417, null),
          "type": "string",
          "enum": ["userGesture", "always", "never"],
          "default": "never",
          "enumDescriptions": [
            localize(4418, null),
            localize(4419, null),
            localize(4420, null)
          ]
        },
        "announcement": {
          "description": localize(4421, null),
          "type": "string",
          "enum": ["userGesture", "always", "never"],
          "default": "never",
          "enumDescriptions": [
            localize(4422, null),
            localize(4423, null),
            localize(4424, null)
          ]
        }
      },
      default: {
        "sound": "never",
        "announcement": "never"
      }
    },
    "accessibility.underlineLinks": {
      "type": "boolean",
      "description": localize(4425, null),
      "default": false
    },
    "accessibility.debugWatchVariableAnnouncements": {
      "type": "boolean",
      "description": localize(4426, null),
      "default": true
    },
    "accessibility.replEditor.readLastExecutionOutput": {
      "type": "boolean",
      "description": localize(4427, null),
      "default": true
    },
    "accessibility.replEditor.autoFocusReplExecution": {
      type: "string",
      enum: ["none", "input", "lastExecution"],
      default: "input",
      description: localize(4428, null)
    }
  }
};
function $Bsb() {
  const registry4 = $Wn.as($Ht.Configuration);
  registry4.registerConfiguration(configuration);
  registry4.registerConfiguration({
    ...$UL,
    properties: {
      [
        "accessibility.dimUnfocused.enabled"
        /* AccessibilityWorkbenchSettingId.DimUnfocusedEnabled */
      ]: {
        description: localize(4429, null),
        type: "boolean",
        default: false,
        tags: ["accessibility"],
        scope: 1
      },
      [
        "accessibility.dimUnfocused.opacity"
        /* AccessibilityWorkbenchSettingId.DimUnfocusedOpacity */
      ]: {
        markdownDescription: localize(4430, null, `\`#${"accessibility.dimUnfocused.enabled"}#\``),
        type: "number",
        minimum: 0.2,
        maximum: 1,
        default: 0.75,
        tags: ["accessibility"],
        scope: 1
      },
      [
        "accessibility.hideAccessibleView"
        /* AccessibilityWorkbenchSettingId.HideAccessibleView */
      ]: {
        description: localize(4431, null),
        type: "boolean",
        default: false,
        tags: ["accessibility"]
      }
    }
  });
}
var $Csb = 1200;
var $Dsb = class $Dsb2 extends $3c {
  static {
    this.ID = "workbench.contrib.dynamicSpeechAccessibilityConfiguration";
  }
  constructor(a, b) {
    super();
    this.a = a;
    this.b = b;
    this.B(Event2.runAndSubscribe(a.onDidChangeHasSpeechProvider, () => this.c()));
  }
  c() {
    if (!this.a.hasSpeechProvider) {
      return;
    }
    const languages = this.f();
    const languagesSorted = Object.keys(languages).sort((langA, langB) => {
      return languages[langA].name.localeCompare(languages[langB].name);
    });
    const registry4 = $Wn.as($Ht.Configuration);
    registry4.registerConfiguration({
      ...$ysb,
      properties: {
        [
          "accessibility.voice.speechTimeout"
          /* AccessibilityVoiceSettingId.SpeechTimeout */
        ]: {
          "markdownDescription": localize(4432, null),
          "type": "number",
          "default": $Csb,
          "minimum": 0,
          "tags": ["accessibility"]
        },
        [
          "accessibility.voice.speechLanguage"
          /* AccessibilityVoiceSettingId.SpeechLanguage */
        ]: {
          "markdownDescription": localize(4433, null),
          "type": "string",
          "enum": languagesSorted,
          "default": "auto",
          "tags": ["accessibility"],
          "enumDescriptions": languagesSorted.map((key2) => languages[key2].name),
          "enumItemLabels": languagesSorted.map((key2) => languages[key2].name)
        },
        [
          "accessibility.voice.autoSynthesize"
          /* AccessibilityVoiceSettingId.AutoSynthesize */
        ]: {
          "type": "string",
          "enum": ["on", "off", "auto"],
          "enumDescriptions": [
            localize(4434, null),
            localize(4435, null),
            localize(4436, null)
          ],
          "markdownDescription": localize(4437, null),
          "default": this.b.quality !== "stable" ? "auto" : "off",
          // TODO@bpasero decide on a default
          "tags": ["accessibility"]
        }
      }
    });
  }
  f() {
    return {
      ["auto"]: {
        name: localize(4438, null)
      },
      ...$oS
    };
  }
};
$Dsb = __decorate([
  __param(0, $jS),
  __param(1, $Vu)
], $Dsb);
$Wn.as($YL.ConfigurationMigration).registerConfigurationMigrations([{
  key: "audioCues.volume",
  migrateFn: (value, accessor) => {
    return [
      ["accessibility.signalOptions.volume", { value }],
      ["audioCues.volume", { value: void 0 }]
    ];
  }
}]);
$Wn.as($YL.ConfigurationMigration).registerConfigurationMigrations([{
  key: "audioCues.debouncePositionChanges",
  migrateFn: (value) => {
    return [
      ["accessibility.signalOptions.debouncePositionChanges", { value }],
      ["audioCues.debouncePositionChanges", { value: void 0 }]
    ];
  }
}]);
$Wn.as($YL.ConfigurationMigration).registerConfigurationMigrations([{
  key: "accessibility.signalOptions",
  migrateFn: (value, accessor) => {
    const delayGeneral = getDelaysFromConfig(accessor, "general");
    const delayError = getDelaysFromConfig(accessor, "errorAtPosition");
    const delayWarning = getDelaysFromConfig(accessor, "warningAtPosition");
    const volume = getVolumeFromConfig(accessor);
    const debouncePositionChanges = getDebouncePositionChangesFromConfig(accessor);
    const result = [];
    if (!!volume) {
      result.push(["accessibility.signalOptions.volume", { value: volume }]);
    }
    if (!!delayGeneral) {
      result.push(["accessibility.signalOptions.experimental.delays.general", { value: delayGeneral }]);
    }
    if (!!delayError) {
      result.push(["accessibility.signalOptions.experimental.delays.errorAtPosition", { value: delayError }]);
    }
    if (!!delayWarning) {
      result.push(["accessibility.signalOptions.experimental.delays.warningAtPosition", { value: delayWarning }]);
    }
    if (!!debouncePositionChanges) {
      result.push(["accessibility.signalOptions.debouncePositionChanges", { value: debouncePositionChanges }]);
    }
    result.push(["accessibility.signalOptions", { value: void 0 }]);
    return result;
  }
}]);
$Wn.as($YL.ConfigurationMigration).registerConfigurationMigrations([{
  key: "accessibility.signals.sounds.volume",
  migrateFn: (value) => {
    return [
      ["accessibility.signalOptions.volume", { value }],
      ["accessibility.signals.sounds.volume", { value: void 0 }]
    ];
  }
}]);
$Wn.as($YL.ConfigurationMigration).registerConfigurationMigrations([{
  key: "accessibility.signals.debouncePositionChanges",
  migrateFn: (value) => {
    return [
      ["accessibility.signalOptions.debouncePositionChanges", { value }],
      ["accessibility.signals.debouncePositionChanges", { value: void 0 }]
    ];
  }
}]);
function getDelaysFromConfig(accessor, type) {
  return accessor(`accessibility.signalOptions.experimental.delays.${type}`) || accessor("accessibility.signalOptions")?.["experimental.delays"]?.[`${type}`] || accessor("accessibility.signalOptions")?.["delays"]?.[`${type}`];
}
function getVolumeFromConfig(accessor) {
  return accessor("accessibility.signalOptions.volume") || accessor("accessibility.signalOptions")?.volume || accessor("accessibility.signals.sounds.volume") || accessor("audioCues.volume");
}
function getDebouncePositionChangesFromConfig(accessor) {
  return accessor("accessibility.signalOptions.debouncePositionChanges") || accessor("accessibility.signalOptions")?.debouncePositionChanges || accessor("accessibility.signals.debouncePositionChanges") || accessor("audioCues.debouncePositionChanges");
}
$Wn.as($YL.ConfigurationMigration).registerConfigurationMigrations([{
  key: "accessibility.voice.autoSynthesize",
  migrateFn: (value) => {
    let newValue;
    if (value === true) {
      newValue = "on";
    } else if (value === false) {
      newValue = "off";
    } else {
      return [];
    }
    return [
      ["accessibility.voice.autoSynthesize", { value: newValue }]
    ];
  }
}]);
$Wn.as($YL.ConfigurationMigration).registerConfigurationMigrations([{
  key: "accessibility.signals.chatResponsePending",
  migrateFn: (value, accessor) => {
    return [
      ["accessibility.signals.progress", { value }],
      ["accessibility.signals.chatResponsePending", { value: void 0 }]
    ];
  }
}]);
$Wn.as($YL.ConfigurationMigration).registerConfigurationMigrations($N9.allAccessibilitySignals.map((item) => item.legacySoundSettingsKey ? {
  key: item.legacySoundSettingsKey,
  migrateFn: (sound, accessor) => {
    const configurationKeyValuePairs = [];
    const legacyAnnouncementSettingsKey = item.legacyAnnouncementSettingsKey;
    let announcement;
    if (legacyAnnouncementSettingsKey) {
      announcement = accessor(legacyAnnouncementSettingsKey) ?? void 0;
      if (announcement !== void 0 && typeof announcement !== "string") {
        announcement = announcement ? "auto" : "off";
      }
    }
    configurationKeyValuePairs.push([`${item.legacySoundSettingsKey}`, { value: void 0 }]);
    configurationKeyValuePairs.push([`${item.settingsKey}`, { value: announcement !== void 0 ? { announcement, sound } : { sound } }]);
    return configurationKeyValuePairs;
  }
} : void 0).filter($Hg));
$Wn.as($YL.ConfigurationMigration).registerConfigurationMigrations($N9.allAccessibilitySignals.filter((i2) => !!i2.legacyAnnouncementSettingsKey && !!i2.legacySoundSettingsKey).map((item) => ({
  key: item.legacyAnnouncementSettingsKey,
  migrateFn: (announcement, accessor) => {
    const configurationKeyValuePairs = [];
    const sound = accessor(item.settingsKey)?.sound || accessor(item.legacySoundSettingsKey);
    if (announcement !== void 0 && typeof announcement !== "string") {
      announcement = announcement ? "auto" : "off";
    }
    configurationKeyValuePairs.push([`${item.settingsKey}`, { value: announcement !== void 0 ? { announcement, sound } : { sound } }]);
    configurationKeyValuePairs.push([`${item.legacyAnnouncementSettingsKey}`, { value: void 0 }]);
    configurationKeyValuePairs.push([`${item.legacySoundSettingsKey}`, { value: void 0 }]);
    return configurationKeyValuePairs;
  }
})));

// out-build/vs/workbench/contrib/accessibility/browser/accessibleViewActions.js
var accessibleViewMenu = {
  id: $bJ.AccessibleView,
  group: "navigation",
  when: $osb
};
var commandPalette = {
  id: $bJ.CommandPalette,
  group: "",
  order: 1
};
var AccessibleViewNextAction = class extends $gJ {
  constructor() {
    super({
      id: "editor.action.accessibleViewNext",
      precondition: $7m.and($osb, $psb),
      keybinding: {
        primary: 512 | 94,
        weight: 200
        /* KeybindingWeight.WorkbenchContrib */
      },
      menu: [
        commandPalette,
        {
          ...accessibleViewMenu,
          when: $7m.and($osb, $psb)
        }
      ],
      icon: $6l.arrowDown,
      title: localize(4473, null)
    });
  }
  run(accessor) {
    accessor.get($shb).next();
  }
};
$hJ(AccessibleViewNextAction);
var AccessibleViewNextCodeBlockAction = class extends $gJ {
  constructor() {
    super({
      id: "editor.action.accessibleViewNextCodeBlock",
      precondition: $7m.and($vsb, $7m.or($7m.equals(
        $tsb.key,
        "panelChat"
        /* AccessibleViewProviderId.PanelChat */
      ), $7m.equals(
        $tsb.key,
        "inlineChat"
        /* AccessibleViewProviderId.InlineChat */
      ), $7m.equals(
        $tsb.key,
        "quickChat"
        /* AccessibleViewProviderId.QuickChat */
      ))),
      keybinding: {
        primary: 2048 | 512 | 12,
        mac: { primary: 2048 | 512 | 12 },
        weight: 200
      },
      icon: $6l.arrowRight,
      menu: {
        ...accessibleViewMenu,
        when: $7m.and($osb, $vsb)
      },
      title: localize(4474, null)
    });
  }
  run(accessor) {
    accessor.get($shb).navigateToCodeBlock("next");
  }
};
$hJ(AccessibleViewNextCodeBlockAction);
var AccessibleViewPreviousCodeBlockAction = class extends $gJ {
  constructor() {
    super({
      id: "editor.action.accessibleViewPreviousCodeBlock",
      precondition: $7m.and($vsb, $7m.or($7m.equals(
        $tsb.key,
        "panelChat"
        /* AccessibleViewProviderId.PanelChat */
      ), $7m.equals(
        $tsb.key,
        "inlineChat"
        /* AccessibleViewProviderId.InlineChat */
      ), $7m.equals(
        $tsb.key,
        "quickChat"
        /* AccessibleViewProviderId.QuickChat */
      ))),
      keybinding: {
        primary: 2048 | 512 | 11,
        mac: { primary: 2048 | 512 | 11 },
        weight: 200
      },
      icon: $6l.arrowLeft,
      menu: {
        ...accessibleViewMenu,
        when: $7m.and($osb, $vsb)
      },
      title: localize(4475, null)
    });
  }
  run(accessor) {
    accessor.get($shb).navigateToCodeBlock("previous");
  }
};
$hJ(AccessibleViewPreviousCodeBlockAction);
var AccessibleViewPreviousAction = class extends $gJ {
  constructor() {
    super({
      id: "editor.action.accessibleViewPrevious",
      precondition: $7m.and($osb, $psb),
      keybinding: {
        primary: 512 | 92,
        weight: 200
        /* KeybindingWeight.WorkbenchContrib */
      },
      icon: $6l.arrowUp,
      menu: [
        commandPalette,
        {
          ...accessibleViewMenu,
          when: $7m.and($osb, $psb)
        }
      ],
      title: localize(4476, null)
    });
  }
  run(accessor) {
    accessor.get($shb).previous();
  }
};
$hJ(AccessibleViewPreviousAction);
var AccessibleViewGoToSymbolAction = class extends $gJ {
  constructor() {
    super({
      id: "editor.action.accessibleViewGoToSymbol",
      precondition: $7m.and($7m.or($osb, $nsb), $rsb),
      keybinding: {
        primary: 2048 | 1024 | 45,
        secondary: [
          2048 | 1024 | 89
          /* KeyCode.Period */
        ],
        weight: 200 + 10
      },
      icon: $6l.symbolMisc,
      menu: [
        commandPalette,
        {
          ...accessibleViewMenu,
          when: $7m.and($7m.or($osb, $nsb), $rsb)
        }
      ],
      title: localize(4477, null)
    });
  }
  run(accessor) {
    accessor.get($shb).goToSymbol();
  }
};
$hJ(AccessibleViewGoToSymbolAction);
function registerCommand4(command4) {
  command4.register();
  return command4;
}
var $uSb = registerCommand4(new $W5({
  id: "editor.action.accessibilityHelp",
  precondition: void 0,
  kbOpts: {
    primary: 512 | 59,
    weight: 200,
    linux: {
      primary: 512 | 1024 | 59,
      secondary: [
        512 | 59
        /* KeyCode.F1 */
      ]
    },
    kbExpr: $nsb.toNegated()
  },
  menuOpts: [{
    menuId: $bJ.CommandPalette,
    group: "",
    title: localize(4478, null),
    order: 1
  }]
}));
var $vSb = registerCommand4(new $W5({
  id: "editor.action.accessibleView",
  precondition: void 0,
  kbOpts: {
    primary: 512 | 60,
    weight: 200,
    linux: {
      primary: 512 | 1024 | 60,
      secondary: [
        512 | 60
        /* KeyCode.F2 */
      ]
    }
  },
  menuOpts: [{
    menuId: $bJ.CommandPalette,
    group: "",
    title: localize(4479, null),
    order: 1
  }]
}));
var AccessibleViewDisableHintAction = class extends $gJ {
  constructor() {
    super({
      id: "editor.action.accessibleViewDisableHint",
      precondition: $7m.and($7m.or($osb, $nsb), $qsb),
      keybinding: {
        primary: 512 | 64,
        weight: 200
        /* KeybindingWeight.WorkbenchContrib */
      },
      icon: $6l.bellSlash,
      menu: [
        commandPalette,
        {
          id: $bJ.AccessibleView,
          group: "navigation",
          when: $7m.and($7m.or($osb, $nsb), $qsb)
        }
      ],
      title: localize(4480, null)
    });
  }
  run(accessor) {
    accessor.get($shb).disableHint();
  }
};
$hJ(AccessibleViewDisableHintAction);
var AccessibilityHelpConfigureKeybindingsAction = class extends $gJ {
  constructor() {
    super({
      id: "editor.action.accessibilityHelpConfigureKeybindings",
      precondition: $7m.and($nsb, $wsb),
      icon: $6l.key,
      keybinding: {
        primary: 512 | 41,
        weight: 200
        /* KeybindingWeight.WorkbenchContrib */
      },
      menu: [
        {
          id: $bJ.AccessibleView,
          group: "navigation",
          order: 3,
          when: $wsb
        }
      ],
      title: localize(4481, null)
    });
  }
  async run(accessor) {
    await accessor.get($shb).configureKeybindings(true);
  }
};
$hJ(AccessibilityHelpConfigureKeybindingsAction);
var AccessibilityHelpConfigureAssignedKeybindingsAction = class extends $gJ {
  constructor() {
    super({
      id: "editor.action.accessibilityHelpConfigureAssignedKeybindings",
      precondition: $7m.and($nsb, $xsb),
      icon: $6l.key,
      keybinding: {
        primary: 512 | 31,
        weight: 200
        /* KeybindingWeight.WorkbenchContrib */
      },
      menu: [
        {
          id: $bJ.AccessibleView,
          group: "navigation",
          order: 4,
          when: $xsb
        }
      ],
      title: localize(4482, null)
    });
  }
  async run(accessor) {
    await accessor.get($shb).configureKeybindings(false);
  }
};
$hJ(AccessibilityHelpConfigureAssignedKeybindingsAction);
var AccessibilityHelpOpenHelpLinkAction = class extends $gJ {
  constructor() {
    super({
      id: "editor.action.accessibilityHelpOpenHelpLink",
      precondition: $7m.and($nsb),
      keybinding: {
        primary: 512 | 38,
        weight: 200
        /* KeybindingWeight.WorkbenchContrib */
      },
      title: localize(4483, null)
    });
  }
  run(accessor) {
    accessor.get($shb).openHelpLink();
  }
};
$hJ(AccessibilityHelpOpenHelpLinkAction);
var AccessibleViewAcceptInlineCompletionAction = class extends $gJ {
  constructor() {
    super({
      id: "editor.action.accessibleViewAcceptInlineCompletion",
      precondition: $7m.and($osb, $7m.equals(
        $tsb.key,
        "inlineCompletions"
        /* AccessibleViewProviderId.InlineCompletions */
      )),
      keybinding: {
        primary: 2048 | 90,
        mac: {
          primary: 256 | 90
          /* KeyCode.Slash */
        },
        weight: 200
        /* KeybindingWeight.WorkbenchContrib */
      },
      icon: $6l.check,
      menu: [
        commandPalette,
        {
          id: $bJ.AccessibleView,
          group: "navigation",
          order: 0,
          when: $7m.and($osb, $7m.equals(
            $tsb.key,
            "inlineCompletions"
            /* AccessibleViewProviderId.InlineCompletions */
          ))
        }
      ],
      title: localize(4484, null)
    });
  }
  async run(accessor) {
    const codeEditorService = accessor.get($U5);
    const editor = codeEditorService.getActiveCodeEditor() || codeEditorService.getFocusedCodeEditor();
    if (!editor) {
      return;
    }
    const model = $3hb.get(editor)?.model.get();
    const state = model?.inlineCompletionState.get();
    if (!model || !state) {
      return;
    }
    await model.accept(editor);
    model.stop();
    editor.focus();
  }
};
$hJ(AccessibleViewAcceptInlineCompletionAction);

// out-build/vs/workbench/contrib/comments/browser/commentsView.js
var $wSb = new $nn("commentsView.hasComments", false);
var $xSb = new $nn("commentsView.someCommentsExpanded", false);
var $ySb = new $nn("commentsView.commentFocused", false);
var VIEW_STORAGE_ID = "commentsViewState";
function createResourceCommentsIterator(model) {
  const result = [];
  for (const m of model.resourceCommentThreads) {
    const children = [];
    for (const r2 of m.commentThreads) {
      if ($PJb(r2.thread)) {
        children.push({ element: r2 });
      }
    }
    if (children.length > 0) {
      result.push({ element: m, children });
    }
  }
  return result;
}
var $zSb = class $zSb2 extends $apb {
  get focusedCommentNode() {
    const focused = this.f?.getFocus();
    if (focused?.length === 1 && focused[0] instanceof $LJb) {
      return focused[0];
    }
    return void 0;
  }
  get focusedCommentInfo() {
    if (!this.focusedCommentNode) {
      return;
    }
    return this.sc(this.focusedCommentNode);
  }
  focusNextNode() {
    if (!this.f) {
      return;
    }
    const focused = this.f.getFocus()?.[0];
    if (!focused) {
      return;
    }
    let next = this.f.navigate(focused).next();
    while (next && !(next instanceof $LJb)) {
      next = this.f.navigate(next).next();
    }
    if (!next) {
      return;
    }
    this.f.setFocus([next]);
  }
  focusPreviousNode() {
    if (!this.f) {
      return;
    }
    const focused = this.f.getFocus()?.[0];
    if (!focused) {
      return;
    }
    let previous = this.f.navigate(focused).previous();
    while (previous && !(previous instanceof $LJb)) {
      previous = this.f.navigate(previous).previous();
    }
    if (!previous) {
      return;
    }
    this.f.setFocus([previous]);
  }
  constructor(options3, instantiationService, viewDescriptorService, ic, configurationService, contextKeyService, contextMenuService, keybindingService, openerService, themeService, jc, telemetryService, hoverService, kc, storageService, lc) {
    const stateMemento = new $Slb(VIEW_STORAGE_ID, storageService);
    const viewState = stateMemento.getMemento(
      1,
      1
      /* StorageTarget.MACHINE */
    );
    super({
      ...options3,
      filterOptions: {
        placeholder: localize(5403, null),
        ariaLabel: localize(5404, null),
        history: viewState["filterHistory"] || [],
        text: viewState["filter"] || "",
        focusContextKey: $iSb.key
      }
    }, keybindingService, contextMenuService, configurationService, contextKeyService, viewDescriptorService, instantiationService, openerService, themeService, telemetryService, hoverService);
    this.ic = ic;
    this.jc = jc;
    this.kc = kc;
    this.lc = lc;
    this.ab = 0;
    this.dc = 0;
    this.ec = 0;
    this.hc = void 0;
    this.onDidChangeVisibility = this.onDidChangeBodyVisibility;
    this.sb = $wSb.bindTo(contextKeyService);
    this.ac = $xSb.bindTo(contextKeyService);
    this.bc = $ySb.bindTo(contextKeyService);
    this.gc = stateMemento;
    this.fc = viewState;
    this.filters = this.B(new $hSb({
      showResolved: this.fc["showResolved"] !== false,
      showUnresolved: this.fc["showUnresolved"] !== false,
      sortBy: this.fc["sortBy"] ?? "resourceAscending"
    }, this.Bb));
    this.cc = new $fSb(new $$Rb(this.filterWidget.getFilterText(), this.filters.showResolved, this.filters.showUnresolved));
    this.B(this.filters.onDidChange((event) => {
      if (event.showResolved || event.showUnresolved) {
        this.mc();
      }
      if (event.sortBy) {
        this.xc();
      }
    }));
    this.B(this.filterWidget.onDidChangeFilterText(() => this.mc()));
  }
  saveState() {
    this.fc["filter"] = this.filterWidget.getFilterText();
    this.fc["filterHistory"] = this.filterWidget.getHistory();
    this.fc["showResolved"] = this.filters.showResolved;
    this.fc["showUnresolved"] = this.filters.showUnresolved;
    this.fc["sortBy"] = this.filters.sortBy;
    this.gc.saveMemento();
    super.saveState();
  }
  render() {
    super.render();
    this.B($iKb({
      name: "commentsView",
      focusNotifiers: [this, this.filterWidget],
      focusNextWidget: () => {
        if (this.filterWidget.hasFocus()) {
          this.focus();
        }
      },
      focusPreviousWidget: () => {
        if (!this.filterWidget.hasFocus()) {
          this.focusFilter();
        }
      }
    }));
  }
  focusFilter() {
    this.filterWidget.focus();
  }
  clearFilterText() {
    this.filterWidget.setFilterText("");
  }
  getFilterStats() {
    if (!this.hc) {
      this.hc = {
        total: this.ab,
        filtered: this.f?.getVisibleItemCount() ?? 0
      };
    }
    return this.hc;
  }
  mc() {
    this.cc.options = new $$Rb(this.filterWidget.getFilterText(), this.filters.showResolved, this.filters.showUnresolved);
    this.f?.filterComments();
    this.hc = void 0;
    const { total, filtered } = this.getFilterStats();
    this.filterWidget.updateBadge(total === filtered || total === 0 ? void 0 : localize(5405, null, filtered, total));
    this.filterWidget.checkMoreFilters(!this.filters.showResolved || !this.filters.showUnresolved);
  }
  W(container2) {
    super.W(container2);
    container2.classList.add("comments-panel");
    const domContainer = $bk(container2, $(".comments-panel-container"));
    this.h = $bk(domContainer, $(".tree-container"));
    this.h.classList.add("file-icon-themable-tree", "show-file-icons");
    this.hc = void 0;
    this.vc();
    this.qc(domContainer);
    this.B(this.jc.onDidSetAllCommentThreads(this.yc, this));
    this.B(this.jc.onDidUpdateCommentThreads(this.zc, this));
    this.B(this.jc.onDidDeleteDataProvider(this.Ac, this));
    this.B(this.onDidChangeBodyVisibility((visible) => {
      if (visible) {
        this.xc();
      }
    }));
    this.oc();
  }
  focus() {
    super.focus();
    const element = this.f?.getHTMLElement();
    if (element && $Mj(element)) {
      return;
    }
    if (!this.jc.commentsModel.hasCommentThreads() && this.s) {
      this.s.focus();
    } else if (this.f) {
      this.f.domFocus();
    }
  }
  oc() {
    this.h.classList.toggle("hidden", !this.jc.commentsModel.hasCommentThreads());
    this.rc();
    this.f?.setChildren(null, createResourceCommentsIterator(this.jc.commentsModel));
  }
  collapseAll() {
    if (this.f) {
      this.f.collapseAll();
      this.f.setSelection([]);
      this.f.setFocus([]);
      this.f.domFocus();
      this.f.focusFirst();
    }
  }
  expandAll() {
    if (this.f) {
      this.f.expandAll();
      this.f.setSelection([]);
      this.f.setFocus([]);
      this.f.domFocus();
      this.f.focusFirst();
    }
  }
  get hasRendered() {
    return !!this.f;
  }
  L(height = this.dc, width2 = this.ec) {
    if (this.s) {
      this.s.style.height = `${height}px`;
    }
    this.f?.layout(height, width2);
    this.dc = height;
    this.ec = width2;
  }
  qc(parent) {
    this.s = $bk(parent, $(".message-box-container"));
    this.s.setAttribute("tabIndex", "0");
  }
  rc() {
    this.s.textContent = this.jc.commentsModel.getMessage();
    this.s.classList.toggle("hidden", this.jc.commentsModel.hasCommentThreads());
  }
  sc(element, forAriaLabel) {
    let accessibleViewHint = "";
    if (forAriaLabel && this.Ab.getValue(
      "accessibility.verbosity.comments"
      /* AccessibilityVerbositySettingId.Comments */
    )) {
      const kbLabel = this.yb.lookupKeybinding($vSb.id)?.getAriaLabel();
      accessibleViewHint = kbLabel ? localize(5406, null, kbLabel) : localize(5407, null);
    }
    const replyCount = this.uc(element, forAriaLabel);
    const replies = this.tc(element, forAriaLabel);
    const editor = this.ic.findEditors(element.resource);
    const codeEditor = this.ic.activeEditorPane?.getControl();
    let content;
    if (element.range && editor?.length && $P5(codeEditor)) {
      content = codeEditor.getModel()?.getValueInRange(element.range);
      if (content) {
        content = "\nCorresponding code: \n" + content;
      }
    }
    if (!content) {
      content = "";
    }
    if (element.range) {
      if (element.threadRelevance === CommentThreadApplicability.Outdated) {
        return accessibleViewHint + localize(5408, null, element.comment.userName, element.range.startLineNumber, element.range.startColumn, $sh(element.resource), replyCount, typeof element.comment.body === "string" ? element.comment.body : element.comment.body.value, content) + replies;
      } else {
        return accessibleViewHint + localize(5409, null, element.comment.userName, element.range.startLineNumber, element.range.startColumn, $sh(element.resource), replyCount, typeof element.comment.body === "string" ? element.comment.body : element.comment.body.value, content) + replies;
      }
    } else {
      if (element.threadRelevance === CommentThreadApplicability.Outdated) {
        return accessibleViewHint + localize(5410, null, element.comment.userName, $sh(element.resource), replyCount, typeof element.comment.body === "string" ? element.comment.body : element.comment.body.value) + replies;
      } else {
        return accessibleViewHint + localize(5411, null, element.comment.userName, $sh(element.resource), replyCount, typeof element.comment.body === "string" ? element.comment.body : element.comment.body.value, content) + replies;
      }
    }
  }
  tc(node, forAriaLabel) {
    if (!node.replies.length || forAriaLabel) {
      return "";
    }
    return "\n" + node.replies.map((reply) => localize(5412, null, reply.comment.userName, typeof reply.comment.body === "string" ? reply.comment.body : reply.comment.body.value)).join("\n");
  }
  uc(node, forAriaLabel) {
    return node.replies.length && !forAriaLabel ? localize(5413, null, node.replies.length) : "";
  }
  vc() {
    this.c = this.B(this.Db.createInstance($lsb, this));
    this.f = this.B(this.Db.createInstance($gSb, this.c, this.h, {
      overrideStyles: this.Xb().listOverrideStyles,
      selectionNavigation: true,
      filter: this.cc,
      sorter: {
        compare: (a, b) => {
          if (a instanceof $QJb || b instanceof $QJb) {
            return 0;
          }
          if (this.filters.sortBy === "updatedAtDescending") {
            return a.lastUpdatedAt > b.lastUpdatedAt ? -1 : 1;
          } else if (this.filters.sortBy === "resourceAscending") {
            if (a instanceof $MJb && b instanceof $MJb) {
              const workspaceScheme = this.lc.defaultUriScheme;
              if (a.resource.scheme !== b.resource.scheme && (a.resource.scheme === workspaceScheme || b.resource.scheme === workspaceScheme)) {
                return b.resource.scheme === workspaceScheme ? 1 : -1;
              }
              return a.resource.toString() > b.resource.toString() ? 1 : -1;
            } else if (a instanceof $LJb && b instanceof $LJb && a.thread.range && b.thread.range) {
              return a.thread.range?.startLineNumber > b.thread.range?.startLineNumber ? 1 : -1;
            }
          }
          return 0;
        }
      },
      keyboardNavigationLabelProvider: {
        getKeyboardNavigationLabel: (item) => {
          return void 0;
        }
      },
      accessibilityProvider: {
        getAriaLabel: (element) => {
          if (element instanceof $QJb) {
            return localize(5414, null);
          }
          if (element instanceof $MJb) {
            return localize(5415, null, $sh(element.resource), element.resource.fsPath);
          }
          if (element instanceof $LJb) {
            return this.sc(element, true);
          }
          return "";
        },
        getWidgetAriaLabel() {
          return $bSb.value;
        }
      }
    }));
    this.B(this.f.onDidOpen((e) => {
      this.wc(e.element, e.editorOptions.pinned, e.editorOptions.preserveFocus, e.sideBySide);
    }));
    this.B(this.f.onDidChangeModel(() => {
      this.Bc();
    }));
    this.B(this.f.onDidChangeCollapseState(() => {
      this.Bc();
    }));
    this.B(this.f.onDidFocus(() => this.bc.set(true)));
    this.B(this.f.onDidBlur(() => this.bc.set(false)));
  }
  wc(element, pinned, preserveFocus, sideBySide) {
    if (!element) {
      return;
    }
    if (!(element instanceof $MJb || element instanceof $LJb)) {
      return;
    }
    const threadToReveal = element instanceof $MJb ? element.commentThreads[0].thread : element.thread;
    const commentToReveal = element instanceof $MJb ? element.commentThreads[0].comment : void 0;
    return $sSb(this.jc, this.ic, this.kc, threadToReveal, commentToReveal, false, pinned, preserveFocus, sideBySide);
  }
  async xc() {
    if (!this.f) {
      return;
    }
    if (this.isVisible()) {
      this.sb.set(this.jc.commentsModel.hasCommentThreads());
      this.hc = void 0;
      this.oc();
      if (this.f.getSelection().length === 0 && this.jc.commentsModel.hasCommentThreads()) {
        const firstComment = this.jc.commentsModel.resourceCommentThreads[0].commentThreads[0];
        if (firstComment) {
          this.f.setFocus([firstComment]);
          this.f.setSelection([firstComment]);
        }
      }
    }
  }
  yc(e) {
    this.hc = void 0;
    this.ab += e.commentThreads.length;
    let unresolved = 0;
    for (const thread of e.commentThreads) {
      if (thread.state === CommentThreadState.Unresolved) {
        unresolved++;
      }
    }
    this.xc();
  }
  zc(e) {
    this.hc = void 0;
    this.ab += e.added.length;
    this.ab -= e.removed.length;
    let unresolved = 0;
    for (const resource of this.jc.commentsModel.resourceCommentThreads) {
      for (const thread of resource.commentThreads) {
        if (thread.threadState === CommentThreadState.Unresolved) {
          unresolved++;
        }
      }
    }
    this.xc();
  }
  Ac(owner) {
    this.hc = void 0;
    this.ab = 0;
    this.xc();
  }
  Bc() {
    this.ac.set(this.isSomeCommentsExpanded());
  }
  areAllCommentsExpanded() {
    if (!this.f) {
      return false;
    }
    const navigator2 = this.f.navigate();
    while (navigator2.next()) {
      if (this.f.isCollapsed(navigator2.current())) {
        return false;
      }
    }
    return true;
  }
  isSomeCommentsExpanded() {
    if (!this.f) {
      return false;
    }
    const navigator2 = this.f.navigate();
    while (navigator2.next()) {
      if (!this.f.isCollapsed(navigator2.current())) {
        return true;
      }
    }
    return false;
  }
};
$zSb = __decorate([
  __param(1, $Pk),
  __param(2, $$M),
  __param(3, $mJ),
  __param(4, $kl),
  __param(5, $on),
  __param(6, $50),
  __param(7, $Ty),
  __param(8, $O4),
  __param(9, $gs),
  __param(10, $RJb),
  __param(11, $zv),
  __param(12, $5$),
  __param(13, $vl),
  __param(14, $jv),
  __param(15, $aT)
], $zSb);

// out-build/vs/workbench/browser/parts/views/viewPaneContainer.js
var $nqb = new $bJ("Views");
$dJ.appendMenuItem($bJ.ViewContainerTitle, {
  submenu: $nqb,
  title: localize(3804, null),
  order: 1
});
var DropDirection;
(function(DropDirection2) {
  DropDirection2[DropDirection2["UP"] = 0] = "UP";
  DropDirection2[DropDirection2["DOWN"] = 1] = "DOWN";
  DropDirection2[DropDirection2["LEFT"] = 2] = "LEFT";
  DropDirection2[DropDirection2["RIGHT"] = 3] = "RIGHT";
})(DropDirection || (DropDirection = {}));
var ViewPaneDropOverlay = class _ViewPaneDropOverlay extends $ns {
  static {
    this.c = "monaco-pane-drop-overlay";
  }
  get currentDropOperation() {
    return this.j;
  }
  constructor(s, t, u, C, themeService) {
    super(themeService);
    this.s = s;
    this.t = t;
    this.u = u;
    this.C = C;
    this.r = this.B(new $8h(() => this.dispose(), 300));
    this.D();
  }
  get disposed() {
    return !!this.m;
  }
  D() {
    this.f = document.createElement("div");
    this.f.id = _ViewPaneDropOverlay.c;
    this.f.style.top = "0px";
    this.s.appendChild(this.f);
    this.s.classList.add("dragged-over");
    this.B($1c(() => {
      this.f.remove();
      this.s.classList.remove("dragged-over");
    }));
    this.g = document.createElement("div");
    this.g.classList.add("pane-overlay-indicator");
    this.f.appendChild(this.g);
    this.F();
    this.updateStyles();
  }
  updateStyles() {
    this.g.style.backgroundColor = this.z(this.C === 1 ? $Qmb : $Vnb) || "";
    const activeContrastBorderColor = this.z($lo);
    this.g.style.outlineColor = activeContrastBorderColor || "";
    this.g.style.outlineOffset = activeContrastBorderColor ? "-2px" : "";
    this.g.style.outlineStyle = activeContrastBorderColor ? "dashed" : "";
    this.g.style.outlineWidth = activeContrastBorderColor ? "2px" : "";
    this.g.style.borderColor = activeContrastBorderColor || "";
    this.g.style.borderStyle = "solid";
    this.g.style.borderWidth = "0px";
  }
  F() {
    this.B(new $Ak(this.f, {
      onDragOver: (e) => {
        this.G(e.offsetX, e.offsetY);
        if (this.r.isScheduled()) {
          this.r.cancel();
        }
      },
      onDragLeave: (e) => this.dispose(),
      onDragEnd: (e) => this.dispose(),
      onDrop: (e) => {
        this.dispose();
      }
    }));
    this.B($_i(this.f, $7j.MOUSE_OVER, () => {
      if (!this.r.isScheduled()) {
        this.r.schedule();
      }
    }));
  }
  G(mousePosX, mousePosY) {
    const paneWidth = this.s.clientWidth;
    const paneHeight = this.s.clientHeight;
    const splitWidthThreshold = paneWidth / 2;
    const splitHeightThreshold = paneHeight / 2;
    let dropDirection;
    if (this.t === 0) {
      if (mousePosY < splitHeightThreshold) {
        dropDirection = 0;
      } else if (mousePosY >= splitHeightThreshold) {
        dropDirection = 1;
      }
    } else if (this.t === 1) {
      if (mousePosX < splitWidthThreshold) {
        dropDirection = 2;
      } else if (mousePosX >= splitWidthThreshold) {
        dropDirection = 3;
      }
    }
    switch (dropDirection) {
      case 0:
        this.I({ top: "0", left: "0", width: "100%", height: "50%" });
        break;
      case 1:
        this.I({ bottom: "0", left: "0", width: "100%", height: "50%" });
        break;
      case 2:
        this.I({ top: "0", left: "0", width: "50%", height: "100%" });
        break;
      case 3:
        this.I({ top: "0", right: "0", width: "50%", height: "100%" });
        break;
      default: {
        let top2 = "0";
        let left = "0";
        let width2 = "100%";
        let height = "100%";
        if (this.u) {
          const boundingRect = this.f.getBoundingClientRect();
          top2 = `${this.u.top - boundingRect.top}px`;
          left = `${this.u.left - boundingRect.left}px`;
          height = `${this.u.bottom - this.u.top}px`;
          width2 = `${this.u.right - this.u.left}px`;
        }
        this.I({ top: top2, left, width: width2, height });
      }
    }
    if (this.t === 0 && paneHeight <= 25 || this.t === 1 && paneWidth <= 25) {
      this.H(dropDirection);
    } else {
      this.H(void 0);
    }
    this.g.style.opacity = "1";
    setTimeout(() => this.g.classList.add("overlay-move-transition"), 0);
    this.j = dropDirection;
  }
  H(direction) {
    this.g.style.borderTopWidth = direction === 0 ? "2px" : "0px";
    this.g.style.borderLeftWidth = direction === 2 ? "2px" : "0px";
    this.g.style.borderBottomWidth = direction === 1 ? "2px" : "0px";
    this.g.style.borderRightWidth = direction === 3 ? "2px" : "0px";
  }
  I(options3) {
    this.f.style.height = "100%";
    this.g.style.top = options3.top || "";
    this.g.style.left = options3.left || "";
    this.g.style.bottom = options3.bottom || "";
    this.g.style.right = options3.right || "";
    this.g.style.width = options3.width;
    this.g.style.height = options3.height;
  }
  contains(element) {
    return element === this.f || element === this.g;
  }
  dispose() {
    super.dispose();
    this.m = true;
  }
};
var ViewContainerMenuActions = class ViewContainerMenuActions2 extends $yob {
  constructor(element, viewContainer5, viewDescriptorService, contextKeyService, menuService) {
    const scopedContextKeyService = contextKeyService.createScoped(element);
    scopedContextKeyService.createKey("viewContainer", viewContainer5.id);
    const viewContainerLocationKey = scopedContextKeyService.createKey("viewContainerLocation", $0M(viewDescriptorService.getViewContainerLocation(viewContainer5)));
    super($bJ.ViewContainerTitle, $bJ.ViewContainerTitleContext, { shouldForwardArgs: true, renderShortTitle: true }, scopedContextKeyService, menuService);
    this.B(scopedContextKeyService);
    this.B(Event2.filter(viewDescriptorService.onDidChangeContainerLocation, (e) => e.viewContainer === viewContainer5)(() => viewContainerLocationKey.set($0M(viewDescriptorService.getViewContainerLocation(viewContainer5)))));
  }
};
ViewContainerMenuActions = __decorate([
  __param(2, $$M),
  __param(3, $on),
  __param(4, $cJ)
], ViewContainerMenuActions);
var $oqb = class $oqb2 extends $Tlb {
  get onDidSashChange() {
    return $Kg(this.m).onDidSashChange;
  }
  get panes() {
    return this.j.map((i2) => i2.pane);
  }
  get views() {
    return this.panes;
  }
  get length() {
    return this.j.length;
  }
  get menuActions() {
    return this.Z;
  }
  constructor(id2, ab, bb, cb, db, eb, fb, gb, themeService, hb, ib, jb) {
    super(id2, themeService, hb);
    this.ab = ab;
    this.bb = bb;
    this.cb = cb;
    this.db = db;
    this.eb = eb;
    this.fb = fb;
    this.gb = gb;
    this.hb = hb;
    this.ib = ib;
    this.jb = jb;
    this.j = [];
    this.s = false;
    this.u = false;
    this.J = false;
    this.Q = this.B(new $ze());
    this.onTitleAreaUpdate = this.Q.event;
    this.R = this.B(new $ze());
    this.onDidChangeVisibility = this.R.event;
    this.S = this.B(new $ze());
    this.onDidAddViews = this.S.event;
    this.U = this.B(new $ze());
    this.onDidRemoveViews = this.U.event;
    this.W = this.B(new $ze());
    this.onDidChangeViewVisibility = this.W.event;
    this.X = this.B(new $ze());
    this.onDidFocusView = this.X.event;
    this.Y = this.B(new $ze());
    this.onDidBlurView = this.Y.event;
    const container2 = this.jb.getViewContainerById(id2);
    if (!container2) {
      throw new Error("Could not find container");
    }
    this.viewContainer = container2;
    this.O = `${id2}.numberOfVisibleViews`;
    this.N = this.hb.getNumber(this.O, 1, void 0);
    this.P = this.jb.getViewContainerModel(container2);
  }
  create(parent) {
    const options3 = this.ab;
    options3.orientation = this.lb;
    this.m = this.B(new $c3(parent, this.ab));
    if (this.M) {
      this.m.setBoundarySashes(this.M);
    }
    this.B(this.m.onDidDrop(({ from, to }) => this.movePane(from, to)));
    this.B(this.m.onDidScroll((_) => this.yb()));
    this.B(this.m.onDidSashReset((index) => this.zb(index)));
    this.B($_i(parent, $7j.CONTEXT_MENU, (e) => this.kb(new $lf(getWindow(parent), e))));
    this.B($mZ.addTarget(parent));
    this.B($_i(parent, EventType.Contextmenu, (e) => this.kb(new $lf(getWindow(parent), e))));
    this.Z = this.B(this.bb.createInstance(ViewContainerMenuActions, this.m.element, this.viewContainer));
    this.B(this.Z.onDidChange(() => this.mb()));
    let overlay;
    const getOverlayBounds = () => {
      const fullSize = parent.getBoundingClientRect();
      const lastPane = this.panes[this.panes.length - 1].element.getBoundingClientRect();
      const top2 = this.lb === 0 ? lastPane.bottom : fullSize.top;
      const left = this.lb === 1 ? lastPane.right : fullSize.left;
      return {
        top: top2,
        bottom: fullSize.bottom,
        left,
        right: fullSize.right
      };
    };
    const inBounds = (bounds2, pos) => {
      return pos.x >= bounds2.left && pos.x <= bounds2.right && pos.y >= bounds2.top && pos.y <= bounds2.bottom;
    };
    let bounds;
    this.B($Iob.INSTANCE.registerTarget(parent, {
      onDragEnter: (e) => {
        bounds = getOverlayBounds();
        if (overlay && overlay.disposed) {
          overlay = void 0;
        }
        if (!overlay && inBounds(bounds, e.eventData)) {
          const dropData = e.dragAndDropData.getData();
          if (dropData.type === "view") {
            const oldViewContainer = this.jb.getViewContainerByViewId(dropData.id);
            const viewDescriptor3 = this.jb.getViewDescriptorById(dropData.id);
            if (oldViewContainer !== this.viewContainer && (!viewDescriptor3 || !viewDescriptor3.canMoveView || this.viewContainer.rejectAddedViews)) {
              return;
            }
            overlay = new ViewPaneDropOverlay(parent, void 0, bounds, this.jb.getViewContainerLocation(this.viewContainer), this.n);
          }
          if (dropData.type === "composite" && dropData.id !== this.viewContainer.id) {
            const container2 = this.jb.getViewContainerById(dropData.id);
            const viewsToMove = this.jb.getViewContainerModel(container2).allViewDescriptors;
            if (!viewsToMove.some((v) => !v.canMoveView) && viewsToMove.length > 0) {
              overlay = new ViewPaneDropOverlay(parent, void 0, bounds, this.jb.getViewContainerLocation(this.viewContainer), this.n);
            }
          }
        }
      },
      onDragOver: (e) => {
        if (overlay && overlay.disposed) {
          overlay = void 0;
        }
        if (overlay && !inBounds(bounds, e.eventData)) {
          overlay.dispose();
          overlay = void 0;
        }
        if (inBounds(bounds, e.eventData)) {
          $Job(e.eventData.dataTransfer, "move", overlay !== void 0);
        }
      },
      onDragLeave: (e) => {
        overlay?.dispose();
        overlay = void 0;
      },
      onDrop: (e) => {
        if (overlay) {
          const dropData = e.dragAndDropData.getData();
          const viewsToMove = [];
          if (dropData.type === "composite" && dropData.id !== this.viewContainer.id) {
            const container2 = this.jb.getViewContainerById(dropData.id);
            const allViews = this.jb.getViewContainerModel(container2).allViewDescriptors;
            if (!allViews.some((v) => !v.canMoveView)) {
              viewsToMove.push(...allViews);
            }
          } else if (dropData.type === "view") {
            const oldViewContainer = this.jb.getViewContainerByViewId(dropData.id);
            const viewDescriptor3 = this.jb.getViewDescriptorById(dropData.id);
            if (oldViewContainer !== this.viewContainer && viewDescriptor3 && viewDescriptor3.canMoveView) {
              this.jb.moveViewsToContainer([viewDescriptor3], this.viewContainer, void 0, "dnd");
            }
          }
          const paneCount = this.panes.length;
          if (viewsToMove.length > 0) {
            this.jb.moveViewsToContainer(viewsToMove, this.viewContainer, void 0, "dnd");
          }
          if (paneCount > 0) {
            for (const view of viewsToMove) {
              const paneToMove = this.panes.find((p) => p.id === view.id);
              if (paneToMove) {
                this.movePane(paneToMove, this.panes[this.panes.length - 1]);
              }
            }
          }
        }
        overlay?.dispose();
        overlay = void 0;
      }
    }));
    this.B(this.onDidSashChange(() => this.ob()));
    this.B(this.P.onDidAddVisibleViewDescriptors((added) => this.tb(added)));
    this.B(this.P.onDidRemoveVisibleViewDescriptors((removed) => this.ub(removed)));
    const addedViews = this.P.visibleViewDescriptors.map((viewDescriptor3, index) => {
      const size = this.P.getSize(viewDescriptor3.id);
      const collapsed2 = this.P.isCollapsed(viewDescriptor3.id);
      return { viewDescriptor: viewDescriptor3, index, size, collapsed: collapsed2 };
    });
    if (addedViews.length) {
      this.tb(addedViews);
    }
    this.gb.whenInstalledExtensionsRegistered().then(() => {
      this.u = true;
      if (this.panes.length) {
        this.mb();
        this.xb();
      }
      this.B(this.cb.onDidChangeConfiguration((e) => {
        if (e.affectsConfiguration(
          "workbench.activityBar.location"
          /* LayoutSettings.ACTIVITY_BAR_LOCATION */
        )) {
          this.xb();
        }
      }));
    });
    this.B(this.P.onDidChangeActiveViewDescriptors(() => this.Q.fire()));
  }
  getTitle() {
    const containerTitle = this.P.title;
    if (this.isViewMergedWithContainer()) {
      const singleViewPaneContainerTitle = this.j[0].pane.singleViewPaneContainerTitle;
      if (singleViewPaneContainerTitle) {
        return singleViewPaneContainerTitle;
      }
      const paneItemTitle = this.j[0].pane.title;
      if (containerTitle === paneItemTitle) {
        return paneItemTitle;
      }
      return paneItemTitle ? `${containerTitle}: ${paneItemTitle}` : containerTitle;
    }
    return containerTitle;
  }
  kb(event) {
    for (const paneItem of this.j) {
      if ($Dj(event.target, paneItem.pane.element)) {
        return;
      }
    }
    event.stopPropagation();
    event.preventDefault();
    this.eb.showContextMenu({
      getAnchor: () => event,
      getActions: () => this.menuActions?.getContextMenuActions() ?? []
    });
  }
  getActionsContext() {
    if (this.isViewMergedWithContainer()) {
      return this.panes[0].getActionsContext();
    }
    return void 0;
  }
  getActionViewItem(action, options3) {
    if (this.isViewMergedWithContainer()) {
      return this.j[0].pane.getActionViewItem(action, options3);
    }
    return $X$(this.bb, action, options3);
  }
  focus() {
    let paneToFocus = void 0;
    if (this.f) {
      paneToFocus = this.f;
    } else if (this.j.length > 0) {
      for (const { pane } of this.j) {
        if (pane.isExpanded()) {
          paneToFocus = pane;
          break;
        }
      }
    }
    if (paneToFocus) {
      paneToFocus.focus();
    }
  }
  get lb() {
    switch (this.jb.getViewContainerLocation(this.viewContainer)) {
      case 0:
      case 2:
        return 0;
      case 1: {
        return $Wlb(this.db.getPanelPosition()) ? 1 : 0;
      }
    }
    return 0;
  }
  layout(dimension) {
    if (this.m) {
      if (this.m.orientation !== this.lb) {
        this.m.flipOrientation(dimension.height, dimension.width);
      }
      this.m.layout(dimension.height, dimension.width);
    }
    this.L = dimension;
    if (this.J) {
      this.ob();
    } else {
      this.J = true;
      this.pb();
    }
  }
  setBoundarySashes(sashes) {
    this.M = sashes;
    this.m?.setBoundarySashes(sashes);
  }
  getOptimalWidth() {
    const additionalMargin = 16;
    const optimalWidth = Math.max(...this.panes.map((view) => view.getOptimalWidth() || 0));
    return optimalWidth + additionalMargin;
  }
  addPanes(panes) {
    const wasMerged = this.isViewMergedWithContainer();
    for (const { pane, size, index, disposable } of panes) {
      this.vb(pane, size, disposable, index);
    }
    this.xb();
    if (this.isViewMergedWithContainer() !== wasMerged) {
      this.mb();
    }
    this.S.fire(panes.map(({ pane }) => pane));
  }
  setVisible(visible) {
    if (this.s !== !!visible) {
      this.s = visible;
      this.R.fire(visible);
    }
    this.panes.filter((view) => view.isVisible() !== visible).map((view) => view.setVisible(visible));
  }
  isVisible() {
    return this.s;
  }
  mb() {
    this.Q.fire();
  }
  nb(viewDescriptor3, options3) {
    return this.bb.createInstance(viewDescriptor3.ctorDescriptor.ctor, ...viewDescriptor3.ctorDescriptor.staticArguments || [], options3);
  }
  getView(id2) {
    return this.panes.filter((view) => view.id === id2)[0];
  }
  ob() {
    if (this.J) {
      this.P.setSizes(this.panes.map((view) => ({ id: view.id, size: this.getPaneSize(view) })));
    }
  }
  pb() {
    if (this.J) {
      let initialSizes;
      for (let i2 = 0; i2 < this.P.visibleViewDescriptors.length; i2++) {
        const pane = this.panes[i2];
        const viewDescriptor3 = this.P.visibleViewDescriptors[i2];
        const size = this.P.getSize(viewDescriptor3.id);
        if (typeof size === "number") {
          this.resizePane(pane, size);
        } else {
          initialSizes = initialSizes ? initialSizes : this.qb();
          this.resizePane(pane, initialSizes.get(pane.id) || 200);
        }
      }
    }
  }
  qb() {
    const sizes = /* @__PURE__ */ new Map();
    if (this.L) {
      const totalWeight = this.P.visibleViewDescriptors.reduce((totalWeight2, { weight: weight5 }) => totalWeight2 + (weight5 || 20), 0);
      for (const viewDescriptor3 of this.P.visibleViewDescriptors) {
        if (this.lb === 0) {
          sizes.set(viewDescriptor3.id, this.L.height * (viewDescriptor3.weight || 20) / totalWeight);
        } else {
          sizes.set(viewDescriptor3.id, this.L.width * (viewDescriptor3.weight || 20) / totalWeight);
        }
      }
    }
    return sizes;
  }
  I() {
    this.panes.forEach((view) => view.saveState());
    this.hb.store(
      this.O,
      this.length,
      1,
      1
      /* StorageTarget.MACHINE */
    );
  }
  sb(event, viewPane) {
    event.stopPropagation();
    event.preventDefault();
    const actions = viewPane.menuActions.getContextMenuActions();
    this.eb.showContextMenu({
      getAnchor: () => event,
      getActions: () => actions
    });
  }
  openView(id2, focus) {
    let view = this.getView(id2);
    if (!view) {
      this.toggleViewVisibility(id2);
    }
    view = this.getView(id2);
    if (view) {
      view.setExpanded(true);
      if (focus) {
        view.focus();
      }
    }
    return view;
  }
  tb(added) {
    const panesToAdd = [];
    for (const { viewDescriptor: viewDescriptor3, collapsed: collapsed2, index, size } of added) {
      const pane = this.nb(viewDescriptor3, {
        id: viewDescriptor3.id,
        title: viewDescriptor3.name.value,
        fromExtensionId: viewDescriptor3.extensionId,
        expanded: !collapsed2,
        singleViewPaneContainerTitle: viewDescriptor3.singleViewPaneContainerTitle
      });
      pane.render();
      const contextMenuDisposable = $_i(pane.draggableElement, "contextmenu", (e) => {
        e.stopPropagation();
        e.preventDefault();
        this.sb(new $lf(getWindow(pane.draggableElement), e), pane);
      });
      const collapseDisposable = Event2.latch(Event2.map(pane.onDidChange, () => !pane.isExpanded()))((collapsed3) => {
        this.P.setCollapsed(viewDescriptor3.id, collapsed3);
      });
      panesToAdd.push({ pane, size: size || pane.minimumSize, index, disposable: $Zc(contextMenuDisposable, collapseDisposable) });
    }
    this.addPanes(panesToAdd);
    this.pb();
    const panes = [];
    for (const { pane } of panesToAdd) {
      pane.setVisible(this.isVisible());
      panes.push(pane);
    }
    return panes;
  }
  ub(removed) {
    removed = removed.sort((a, b) => b.index - a.index);
    const panesToRemove = [];
    for (const { index } of removed) {
      const paneItem = this.j[index];
      if (paneItem) {
        panesToRemove.push(this.j[index].pane);
      }
    }
    if (panesToRemove.length) {
      this.removePanes(panesToRemove);
      for (const pane of panesToRemove) {
        pane.setVisible(false);
      }
    }
  }
  toggleViewVisibility(viewId) {
    if (this.P.activeViewDescriptors.some((viewDescriptor3) => viewDescriptor3.id === viewId)) {
      const visible = !this.P.isVisible(viewId);
      this.P.setVisible(viewId, visible);
    }
  }
  vb(pane, size, disposable, index = this.j.length - 1) {
    const onDidFocus = pane.onDidFocus(() => {
      this.X.fire(pane);
      this.f = pane;
    });
    const onDidBlur = pane.onDidBlur(() => this.Y.fire(pane));
    const onDidChangeTitleArea = pane.onDidChangeTitleArea(() => {
      if (this.isViewMergedWithContainer()) {
        this.mb();
      }
    });
    const onDidChangeVisibility = pane.onDidChangeBodyVisibility(() => this.W.fire(pane));
    const onDidChange = pane.onDidChange(() => {
      if (pane === this.f && !pane.isExpanded()) {
        this.f = void 0;
      }
    });
    const isPanel = this.jb.getViewContainerLocation(this.viewContainer) === 1;
    pane.style({
      headerForeground: $Zn(isPanel ? $Smb : $Xnb),
      headerBackground: $Zn(isPanel ? $Rmb : $Wnb),
      headerBorder: $Zn(isPanel ? $Tmb : $Ynb),
      dropBackground: $Zn(isPanel ? $Qmb : $Vnb),
      leftBorder: isPanel ? $Zn($Umb) : void 0
    });
    const store = new $2c();
    store.add(disposable);
    store.add($Zc(pane, onDidFocus, onDidBlur, onDidChangeTitleArea, onDidChange, onDidChangeVisibility));
    const paneItem = { pane, disposable: store };
    this.j.splice(index, 0, paneItem);
    $Kg(this.m).addPane(pane, size, index);
    let overlay;
    store.add($Iob.INSTANCE.registerDraggable(pane.draggableElement, () => {
      return { type: "view", id: pane.id };
    }, {}));
    store.add($Iob.INSTANCE.registerTarget(pane.dropTargetElement, {
      onDragEnter: (e) => {
        if (!overlay) {
          const dropData = e.dragAndDropData.getData();
          if (dropData.type === "view" && dropData.id !== pane.id) {
            const oldViewContainer = this.jb.getViewContainerByViewId(dropData.id);
            const viewDescriptor3 = this.jb.getViewDescriptorById(dropData.id);
            if (oldViewContainer !== this.viewContainer && (!viewDescriptor3 || !viewDescriptor3.canMoveView || this.viewContainer.rejectAddedViews)) {
              return;
            }
            overlay = new ViewPaneDropOverlay(pane.dropTargetElement, this.lb ?? 0, void 0, this.jb.getViewContainerLocation(this.viewContainer), this.n);
          }
          if (dropData.type === "composite" && dropData.id !== this.viewContainer.id && !this.viewContainer.rejectAddedViews) {
            const container2 = this.jb.getViewContainerById(dropData.id);
            const viewsToMove = this.jb.getViewContainerModel(container2).allViewDescriptors;
            if (!viewsToMove.some((v) => !v.canMoveView) && viewsToMove.length > 0) {
              overlay = new ViewPaneDropOverlay(pane.dropTargetElement, this.lb ?? 0, void 0, this.jb.getViewContainerLocation(this.viewContainer), this.n);
            }
          }
        }
      },
      onDragOver: (e) => {
        $Job(e.eventData.dataTransfer, "move", overlay !== void 0);
      },
      onDragLeave: (e) => {
        overlay?.dispose();
        overlay = void 0;
      },
      onDrop: (e) => {
        if (overlay) {
          const dropData = e.dragAndDropData.getData();
          const viewsToMove = [];
          let anchorView;
          if (dropData.type === "composite" && dropData.id !== this.viewContainer.id && !this.viewContainer.rejectAddedViews) {
            const container2 = this.jb.getViewContainerById(dropData.id);
            const allViews = this.jb.getViewContainerModel(container2).allViewDescriptors;
            if (allViews.length > 0 && !allViews.some((v) => !v.canMoveView)) {
              viewsToMove.push(...allViews);
              anchorView = allViews[0];
            }
          } else if (dropData.type === "view") {
            const oldViewContainer = this.jb.getViewContainerByViewId(dropData.id);
            const viewDescriptor3 = this.jb.getViewDescriptorById(dropData.id);
            if (oldViewContainer !== this.viewContainer && viewDescriptor3 && viewDescriptor3.canMoveView && !this.viewContainer.rejectAddedViews) {
              viewsToMove.push(viewDescriptor3);
            }
            if (viewDescriptor3) {
              anchorView = viewDescriptor3;
            }
          }
          if (viewsToMove) {
            this.jb.moveViewsToContainer(viewsToMove, this.viewContainer, void 0, "dnd");
          }
          if (anchorView) {
            if (overlay.currentDropOperation === 1 || overlay.currentDropOperation === 3) {
              const fromIndex = this.panes.findIndex((p) => p.id === anchorView.id);
              let toIndex = this.panes.findIndex((p) => p.id === pane.id);
              if (fromIndex >= 0 && toIndex >= 0) {
                if (fromIndex > toIndex) {
                  toIndex++;
                }
                if (toIndex < this.panes.length && toIndex !== fromIndex) {
                  this.movePane(this.panes[fromIndex], this.panes[toIndex]);
                }
              }
            }
            if (overlay.currentDropOperation === 0 || overlay.currentDropOperation === 2) {
              const fromIndex = this.panes.findIndex((p) => p.id === anchorView.id);
              let toIndex = this.panes.findIndex((p) => p.id === pane.id);
              if (fromIndex >= 0 && toIndex >= 0) {
                if (fromIndex < toIndex) {
                  toIndex--;
                }
                if (toIndex >= 0 && toIndex !== fromIndex) {
                  this.movePane(this.panes[fromIndex], this.panes[toIndex]);
                }
              }
            }
            if (viewsToMove.length > 1) {
              viewsToMove.slice(1).forEach((view) => {
                let toIndex = this.panes.findIndex((p) => p.id === anchorView.id);
                const fromIndex = this.panes.findIndex((p) => p.id === view.id);
                if (fromIndex >= 0 && toIndex >= 0) {
                  if (fromIndex > toIndex) {
                    toIndex++;
                  }
                  if (toIndex < this.panes.length && toIndex !== fromIndex) {
                    this.movePane(this.panes[fromIndex], this.panes[toIndex]);
                    anchorView = view;
                  }
                }
              });
            }
          }
        }
        overlay?.dispose();
        overlay = void 0;
      }
    }));
  }
  removePanes(panes) {
    const wasMerged = this.isViewMergedWithContainer();
    panes.forEach((pane) => this.wb(pane));
    this.xb();
    if (wasMerged !== this.isViewMergedWithContainer()) {
      this.mb();
    }
    this.U.fire(panes);
  }
  wb(pane) {
    const index = this.j.findIndex((i2) => i2.pane === pane);
    if (index === -1) {
      return;
    }
    if (this.f === pane) {
      this.f = void 0;
    }
    $Kg(this.m).removePane(pane);
    const [paneItem] = this.j.splice(index, 1);
    paneItem.disposable.dispose();
  }
  movePane(from, to) {
    const fromIndex = this.j.findIndex((item) => item.pane === from);
    const toIndex = this.j.findIndex((item) => item.pane === to);
    const fromViewDescriptor = this.P.visibleViewDescriptors[fromIndex];
    const toViewDescriptor = this.P.visibleViewDescriptors[toIndex];
    if (fromIndex < 0 || fromIndex >= this.j.length) {
      return;
    }
    if (toIndex < 0 || toIndex >= this.j.length) {
      return;
    }
    const [paneItem] = this.j.splice(fromIndex, 1);
    this.j.splice(toIndex, 0, paneItem);
    $Kg(this.m).movePane(from, to);
    this.P.move(fromViewDescriptor.id, toViewDescriptor.id);
    this.mb();
  }
  resizePane(pane, size) {
    $Kg(this.m).resizePane(pane, size);
  }
  getPaneSize(pane) {
    return $Kg(this.m).getPaneSize(pane);
  }
  xb() {
    if (this.isViewMergedWithContainer()) {
      if (this.j[0].pane.isExpanded()) {
        this.g = void 0;
      } else {
        this.g = this.j[0].pane;
        this.j[0].pane.setExpanded(true);
      }
      this.j[0].pane.headerVisible = false;
      this.j[0].pane.collapsible = true;
    } else {
      if (this.j.length === 1) {
        this.j[0].pane.headerVisible = true;
        if (this.j[0].pane === this.g) {
          this.j[0].pane.setExpanded(false);
        }
        this.j[0].pane.collapsible = false;
      } else {
        this.j.forEach((i2) => {
          i2.pane.headerVisible = true;
          i2.pane.collapsible = true;
          if (i2.pane === this.g) {
            i2.pane.setExpanded(false);
          }
        });
      }
      this.g = void 0;
    }
  }
  isViewMergedWithContainer() {
    if (!(this.ab.mergeViewWithContainerWhenSingleView && this.j.length === 1)) {
      return false;
    }
    if (!this.u) {
      if (this.N === void 0) {
        return this.j[0].pane.isExpanded();
      }
      return this.N === 1;
    }
    return true;
  }
  yb() {
    for (const pane of this.panes) {
      pane.onDidScrollRoot();
    }
  }
  zb(index) {
    let firstPane = void 0;
    let secondPane = void 0;
    for (let i2 = index; i2 >= 0; i2--) {
      if (this.j[i2].pane?.isVisible() && this.j[i2]?.pane.isExpanded()) {
        firstPane = this.j[i2].pane;
        break;
      }
    }
    for (let i2 = index + 1; i2 < this.j.length; i2++) {
      if (this.j[i2].pane?.isVisible() && this.j[i2]?.pane.isExpanded()) {
        secondPane = this.j[i2].pane;
        break;
      }
    }
    if (firstPane && secondPane) {
      const firstPaneSize = this.getPaneSize(firstPane);
      const secondPaneSize = this.getPaneSize(secondPane);
      const newFirstPaneSize = Math.ceil((firstPaneSize + secondPaneSize) / 2);
      const newSecondPaneSize = Math.floor((firstPaneSize + secondPaneSize) / 2);
      if (firstPaneSize > secondPaneSize) {
        this.resizePane(firstPane, newFirstPaneSize);
        this.resizePane(secondPane, newSecondPaneSize);
      } else {
        this.resizePane(secondPane, newSecondPaneSize);
        this.resizePane(firstPane, newFirstPaneSize);
      }
    }
  }
  dispose() {
    super.dispose();
    this.j.forEach((i2) => i2.disposable.dispose());
    if (this.m) {
      this.m.dispose();
    }
  }
};
$oqb = __decorate([
  __param(2, $Pk),
  __param(3, $kl),
  __param(4, $Vlb),
  __param(5, $50),
  __param(6, $zv),
  __param(7, $wN),
  __param(8, $gs),
  __param(9, $jv),
  __param(10, $Zk),
  __param(11, $$M)
], $oqb);
var $pqb = class extends $gJ {
  constructor(desc) {
    super(desc);
    this.desc = desc;
  }
  run(accessor, ...args2) {
    const viewPaneContainer = accessor.get($uob).getActiveViewPaneContainerWithId(this.desc.viewPaneContainerId);
    if (viewPaneContainer) {
      return this.runInViewPaneContainer(accessor, viewPaneContainer, ...args2);
    }
    return void 0;
  }
};
var MoveViewPosition = class extends $gJ {
  constructor(desc, c) {
    super(desc);
    this.c = c;
  }
  async run(accessor) {
    const viewDescriptorService = accessor.get($$M);
    const contextKeyService = accessor.get($on);
    const viewId = $jqb.getValue(contextKeyService);
    if (viewId === void 0) {
      return;
    }
    const viewContainer5 = viewDescriptorService.getViewContainerByViewId(viewId);
    const model = viewDescriptorService.getViewContainerModel(viewContainer5);
    const viewDescriptor3 = model.visibleViewDescriptors.find((vd) => vd.id === viewId);
    const currentIndex = model.visibleViewDescriptors.indexOf(viewDescriptor3);
    if (currentIndex + this.c < 0 || currentIndex + this.c >= model.visibleViewDescriptors.length) {
      return;
    }
    const newPosition = model.visibleViewDescriptors[currentIndex + this.c];
    model.move(viewDescriptor3.id, newPosition.id);
  }
};
$hJ(class MoveViewUp extends MoveViewPosition {
  constructor() {
    super({
      id: "views.moveViewUp",
      title: localize(3805, null),
      keybinding: {
        primary: $$e(
          2048 + 41,
          16
          /* KeyCode.UpArrow */
        ),
        weight: 200 + 1,
        when: $jqb.notEqualsTo("")
      }
    }, -1);
  }
});
$hJ(class MoveViewLeft extends MoveViewPosition {
  constructor() {
    super({
      id: "views.moveViewLeft",
      title: localize(3806, null),
      keybinding: {
        primary: $$e(
          2048 + 41,
          15
          /* KeyCode.LeftArrow */
        ),
        weight: 200 + 1,
        when: $jqb.notEqualsTo("")
      }
    }, -1);
  }
});
$hJ(class MoveViewDown extends MoveViewPosition {
  constructor() {
    super({
      id: "views.moveViewDown",
      title: localize(3807, null),
      keybinding: {
        primary: $$e(
          2048 + 41,
          18
          /* KeyCode.DownArrow */
        ),
        weight: 200 + 1,
        when: $jqb.notEqualsTo("")
      }
    }, 1);
  }
});
$hJ(class MoveViewRight extends MoveViewPosition {
  constructor() {
    super({
      id: "views.moveViewRight",
      title: localize(3808, null),
      keybinding: {
        primary: $$e(
          2048 + 41,
          17
          /* KeyCode.RightArrow */
        ),
        weight: 200 + 1,
        when: $jqb.notEqualsTo("")
      }
    }, 1);
  }
});
$hJ(class MoveViews extends $gJ {
  constructor() {
    super({
      id: "vscode.moveViews",
      title: localize(3809, null)
    });
  }
  async run(accessor, options3) {
    if (!Array.isArray(options3?.viewIds) || typeof options3?.destinationId !== "string") {
      return Promise.reject("Invalid arguments");
    }
    const viewDescriptorService = accessor.get($$M);
    const destination = viewDescriptorService.getViewContainerById(options3.destinationId);
    if (!destination) {
      return;
    }
    for (const viewId of options3.viewIds) {
      const viewDescriptor3 = viewDescriptorService.getViewDescriptorById(viewId);
      if (viewDescriptor3?.canMoveView) {
        viewDescriptorService.moveViewsToContainer([viewDescriptor3], destination, ViewVisibilityState.Default, this.desc.id);
      }
    }
    await accessor.get($uob).openViewContainer(destination.id, true);
  }
});

// out-build/vs/workbench/api/browser/mainThreadComments.js
var $ASb = class {
  get input() {
    return this.a;
  }
  set input(value) {
    this.a = value;
    this.b.fire(value);
  }
  get onDidChangeInput() {
    return this.b.event;
  }
  get label() {
    return this.c;
  }
  set label(label3) {
    this.c = label3;
    this.f.fire(this.c);
  }
  get contextValue() {
    return this.d;
  }
  set contextValue(context) {
    this.d = context;
  }
  get comments() {
    return this.g;
  }
  set comments(newComments) {
    this.g = newComments;
    this.h.fire(this.g);
  }
  get onDidChangeComments() {
    return this.h.event;
  }
  set range(range) {
    this.t = range;
  }
  get range() {
    return this.t;
  }
  get onDidChangeCanReply() {
    return this.i.event;
  }
  set canReply(state) {
    this.u = state;
    this.i.fire(this.u);
  }
  get canReply() {
    return this.u;
  }
  get collapsibleState() {
    return this.j;
  }
  set collapsibleState(newState) {
    if (this.l === void 0) {
      this.l = newState;
    }
    if (newState !== this.j) {
      this.j = newState;
      this.m.fire(this.j);
    }
  }
  get l() {
    return this.k;
  }
  set l(initialCollapsibleState) {
    this.k = initialCollapsibleState;
    this.n.fire(initialCollapsibleState);
  }
  get isDisposed() {
    return this.o;
  }
  isDocumentCommentThread() {
    return this.t === void 0 || $9C.isIRange(this.t);
  }
  get state() {
    return this.p;
  }
  set state(newState) {
    this.p = newState;
    this.s.fire(this.p);
  }
  get applicability() {
    return this.q;
  }
  set applicability(value) {
    this.q = value;
    this.r.fire(value);
  }
  get isTemplate() {
    return this.v;
  }
  constructor(commentThreadHandle, controllerHandle, extensionId, threadId, resource, t, comments, u, v, editorId) {
    this.commentThreadHandle = commentThreadHandle;
    this.controllerHandle = controllerHandle;
    this.extensionId = extensionId;
    this.threadId = threadId;
    this.resource = resource;
    this.t = t;
    this.u = u;
    this.v = v;
    this.editorId = editorId;
    this.b = new $ze();
    this.f = new $ze();
    this.onDidChangeLabel = this.f.event;
    this.h = new $ze();
    this.i = new $ze();
    this.j = CommentThreadCollapsibleState.Collapsed;
    this.m = new $ze();
    this.onDidChangeCollapsibleState = this.m.event;
    this.n = new $ze();
    this.onDidChangeInitialCollapsibleState = this.n.event;
    this.r = new $ze();
    this.onDidChangeApplicability = this.r.event;
    this.s = new $ze();
    this.onDidChangeState = this.s.event;
    this.o = false;
    if (v) {
      this.comments = [];
    } else if (comments) {
      this.g = comments;
    }
  }
  batchUpdate(changes) {
    const modified = (value) => Object.prototype.hasOwnProperty.call(changes, value);
    if (modified("range")) {
      this.t = changes.range;
    }
    if (modified("label")) {
      this.c = changes.label;
    }
    if (modified("contextValue")) {
      this.d = changes.contextValue === null ? void 0 : changes.contextValue;
    }
    if (modified("comments")) {
      this.comments = changes.comments;
    }
    if (modified("collapseState")) {
      this.collapsibleState = changes.collapseState;
    }
    if (modified("canReply")) {
      this.canReply = changes.canReply;
    }
    if (modified("state")) {
      this.state = changes.state;
    }
    if (modified("applicability")) {
      this.applicability = changes.applicability;
    }
    if (modified("isTemplate")) {
      this.v = changes.isTemplate;
    }
  }
  hasComments() {
    return !!this.comments && this.comments.length > 0;
  }
  dispose() {
    this.o = true;
    this.m.dispose();
    this.h.dispose();
    this.b.dispose();
    this.f.dispose();
    this.s.dispose();
  }
  toJSON() {
    return {
      $mid: 7,
      commentControlHandle: this.controllerHandle,
      commentThreadHandle: this.commentThreadHandle
    };
  }
};
var CommentThreadWithDisposable = class {
  constructor(thread) {
    this.thread = thread;
    this.disposableStore = new $2c();
  }
  dispose() {
    this.disposableStore.dispose();
  }
};
var $BSb = class {
  get handle() {
    return this.f;
  }
  get id() {
    return this.h;
  }
  get contextValue() {
    return this.h;
  }
  get proxy() {
    return this.c;
  }
  get label() {
    return this.i;
  }
  get reactions() {
    return this.a;
  }
  set reactions(reactions) {
    this.a = reactions;
  }
  get options() {
    return this.j.options;
  }
  get features() {
    return this.j;
  }
  get owner() {
    return this.h;
  }
  constructor(c, d, f, g, h3, i2, j) {
    this.c = c;
    this.d = d;
    this.f = f;
    this.g = g;
    this.h = h3;
    this.i = i2;
    this.j = j;
    this.b = new $_c();
  }
  get activeComment() {
    return this.k;
  }
  async setActiveCommentAndThread(commentInfo) {
    this.k = commentInfo;
    return this.c.$setActiveComment(this.f, commentInfo ? { commentThreadHandle: commentInfo.thread.commentThreadHandle, uniqueIdInThread: commentInfo.comment?.uniqueIdInThread } : void 0);
  }
  updateFeatures(features) {
    this.j = features;
  }
  createCommentThread(extensionId, commentThreadHandle, threadId, resource, range, comments, isTemplate, editorId) {
    const thread = new $ASb(commentThreadHandle, this.handle, extensionId, threadId, URI.revive(resource).toString(), range, comments, true, isTemplate, editorId);
    const threadWithDisposable = new CommentThreadWithDisposable(thread);
    this.b.set(commentThreadHandle, threadWithDisposable);
    threadWithDisposable.disposableStore.add(thread.onDidChangeCollapsibleState(() => {
      this.proxy.$updateCommentThread(this.handle, thread.commentThreadHandle, { collapseState: thread.collapsibleState });
    }));
    if (thread.isDocumentCommentThread()) {
      this.d.updateComments(this.g, {
        added: [thread],
        removed: [],
        changed: [],
        pending: []
      });
    } else {
      this.d.updateNotebookComments(this.g, {
        added: [thread],
        removed: [],
        changed: [],
        pending: []
      });
    }
    return thread;
  }
  updateCommentThread(commentThreadHandle, threadId, resource, changes) {
    const thread = this.l(commentThreadHandle);
    thread.batchUpdate(changes);
    if (thread.isDocumentCommentThread()) {
      this.d.updateComments(this.g, {
        added: [],
        removed: [],
        changed: [thread],
        pending: []
      });
    } else {
      this.d.updateNotebookComments(this.g, {
        added: [],
        removed: [],
        changed: [thread],
        pending: []
      });
    }
  }
  deleteCommentThread(commentThreadHandle) {
    const thread = this.l(commentThreadHandle);
    this.b.deleteAndDispose(commentThreadHandle);
    thread.dispose();
    if (thread.isDocumentCommentThread()) {
      this.d.updateComments(this.g, {
        added: [],
        removed: [thread],
        changed: [],
        pending: []
      });
    } else {
      this.d.updateNotebookComments(this.g, {
        added: [],
        removed: [thread],
        changed: [],
        pending: []
      });
    }
  }
  deleteCommentThreadMain(commentThreadId) {
    for (const { thread } of this.b.values()) {
      if (thread.threadId === commentThreadId) {
        this.c.$deleteCommentThread(this.f, thread.commentThreadHandle);
      }
    }
  }
  updateInput(input) {
    const thread = this.activeEditingCommentThread;
    if (thread && thread.input) {
      const commentInput = thread.input;
      commentInput.value = input;
      thread.input = commentInput;
    }
  }
  updateCommentingRanges(resourceHints) {
    this.d.updateCommentingRanges(this.g, resourceHints);
  }
  l(commentThreadHandle) {
    const thread = this.b.get(commentThreadHandle);
    if (!thread) {
      throw new Error("unknown thread");
    }
    return thread.thread;
  }
  async getDocumentComments(resource, token) {
    if (resource.scheme === Schemas.vscodeNotebookCell) {
      return {
        uniqueOwner: this.g,
        label: this.label,
        threads: [],
        commentingRanges: {
          resource,
          ranges: [],
          fileComments: false
        }
      };
    }
    const ret = [];
    for (const thread of [...this.b.keys()]) {
      const commentThread = this.b.get(thread);
      if (commentThread.thread.resource === resource.toString()) {
        if (commentThread.thread.isDocumentCommentThread()) {
          ret.push(commentThread.thread);
        }
      }
    }
    const commentingRanges = await this.c.$provideCommentingRanges(this.handle, resource, token);
    return {
      uniqueOwner: this.g,
      label: this.label,
      threads: ret,
      commentingRanges: {
        resource,
        ranges: commentingRanges?.ranges || [],
        fileComments: !!commentingRanges?.fileComments
      }
    };
  }
  async getNotebookComments(resource, token) {
    if (resource.scheme !== Schemas.vscodeNotebookCell) {
      return {
        uniqueOwner: this.g,
        label: this.label,
        threads: []
      };
    }
    const ret = [];
    for (const thread of [...this.b.keys()]) {
      const commentThread = this.b.get(thread);
      if (commentThread.thread.resource === resource.toString()) {
        if (!commentThread.thread.isDocumentCommentThread()) {
          ret.push(commentThread.thread);
        }
      }
    }
    return {
      uniqueOwner: this.g,
      label: this.label,
      threads: ret
    };
  }
  async toggleReaction(uri, thread, comment, reaction, token) {
    return this.c.$toggleReaction(this.f, thread.commentThreadHandle, uri, comment, reaction);
  }
  getAllComments() {
    const ret = [];
    for (const thread of [...this.b.keys()]) {
      ret.push(this.b.get(thread).thread);
    }
    return ret;
  }
  createCommentThreadTemplate(resource, range, editorId) {
    return this.c.$createCommentThreadTemplate(this.handle, resource, range, editorId);
  }
  async updateCommentThreadTemplate(threadHandle, range) {
    await this.c.$updateCommentThreadTemplate(this.handle, threadHandle, range);
  }
  toJSON() {
    return {
      $mid: 6,
      handle: this.handle
    };
  }
};
var commentsViewIcon = $9r("comments-view-icon", $6l.commentDiscussion, localize(2580, null));
var $CSb = class $CSb2 extends $3c {
  constructor(extHostContext, j, m, n, r2, s) {
    super();
    this.j = j;
    this.m = m;
    this.n = n;
    this.r = r2;
    this.s = s;
    this.b = /* @__PURE__ */ new Map();
    this.c = /* @__PURE__ */ new Map();
    this.g = this.B(new $2c());
    this.h = null;
    this.a = extHostContext.getProxy($yT.ExtHostComments);
    this.j.unregisterCommentController();
    this.B(this.j.onDidChangeActiveEditingCommentThread(async (thread) => {
      const handle2 = thread.controllerHandle;
      const controller = this.c.get(handle2);
      if (!controller) {
        return;
      }
      this.g.clear();
      this.f = thread;
      controller.activeEditingCommentThread = this.f;
    }));
  }
  $registerCommentController(handle2, id2, label3, extensionId) {
    const providerId = `${id2}-${extensionId}`;
    this.b.set(handle2, providerId);
    const provider = new $BSb(this.a, this.j, handle2, providerId, id2, label3, {});
    this.j.registerCommentController(providerId, provider);
    this.c.set(handle2, provider);
    const commentsPanelAlreadyConstructed = !!this.n.getViewDescriptorById($_Rb);
    if (!commentsPanelAlreadyConstructed) {
      this.t(commentsPanelAlreadyConstructed);
    }
    this.y(commentsPanelAlreadyConstructed);
    this.j.setWorkspaceComments(String(handle2), []);
  }
  $unregisterCommentController(handle2) {
    const providerId = this.b.get(handle2);
    this.b.delete(handle2);
    this.c.delete(handle2);
    if (typeof providerId !== "string") {
      return;
    } else {
      this.j.unregisterCommentController(providerId);
    }
  }
  $updateCommentControllerFeatures(handle2, features) {
    const provider = this.c.get(handle2);
    if (!provider) {
      return void 0;
    }
    provider.updateFeatures(features);
  }
  $createCommentThread(handle2, commentThreadHandle, threadId, resource, range, comments, extensionId, isTemplate, editorId) {
    const provider = this.c.get(handle2);
    if (!provider) {
      return void 0;
    }
    return provider.createCommentThread(extensionId.value, commentThreadHandle, threadId, resource, range, comments, isTemplate, editorId);
  }
  $updateCommentThread(handle2, commentThreadHandle, threadId, resource, changes) {
    const provider = this.c.get(handle2);
    if (!provider) {
      return void 0;
    }
    return provider.updateCommentThread(commentThreadHandle, threadId, resource, changes);
  }
  $deleteCommentThread(handle2, commentThreadHandle) {
    const provider = this.c.get(handle2);
    if (!provider) {
      return;
    }
    return provider.deleteCommentThread(commentThreadHandle);
  }
  $updateCommentingRanges(handle2, resourceHints) {
    const provider = this.c.get(handle2);
    if (!provider) {
      return;
    }
    provider.updateCommentingRanges(resourceHints);
  }
  async $revealCommentThread(handle2, commentThreadHandle, commentUniqueIdInThread, options3) {
    const provider = this.c.get(handle2);
    if (!provider) {
      return Promise.resolve();
    }
    const thread = provider.getAllComments().find((thread2) => thread2.commentThreadHandle === commentThreadHandle);
    if (!thread || !thread.isDocumentCommentThread()) {
      return Promise.resolve();
    }
    const comment = thread.comments?.find((comment2) => comment2.uniqueIdInThread === commentUniqueIdInThread);
    $sSb(this.j, this.s, this.r, thread, comment, options3.focusReply, void 0, options3.preserveFocus);
  }
  async $hideCommentThread(handle2, commentThreadHandle) {
    const provider = this.c.get(handle2);
    if (!provider) {
      return Promise.resolve();
    }
    const thread = provider.getAllComments().find((thread2) => thread2.commentThreadHandle === commentThreadHandle);
    if (!thread || !thread.isDocumentCommentThread()) {
      return Promise.resolve();
    }
    thread.collapsibleState = CommentThreadCollapsibleState.Collapsed;
  }
  t(commentsViewAlreadyRegistered) {
    if (!commentsViewAlreadyRegistered) {
      const VIEW_CONTAINER5 = $Wn.as(Extensions5.ViewContainersRegistry).registerViewContainer(
        {
          id: $_Rb,
          title: $bSb,
          ctorDescriptor: new $Nk($oqb, [$_Rb, { mergeViewWithContainerWhenSingleView: true }]),
          storageId: $aSb,
          hideIfEmpty: true,
          icon: commentsViewIcon,
          order: 10
        },
        1
        /* ViewContainerLocation.Panel */
      );
      $Wn.as(Extensions5.ViewsRegistry).registerViews([{
        id: $_Rb,
        name: $bSb,
        canToggleVisibility: false,
        ctorDescriptor: new $Nk($zSb),
        canMoveView: true,
        containerIcon: commentsViewIcon,
        focusCommand: {
          id: "workbench.action.focusCommentsPanel"
        }
      }], VIEW_CONTAINER5);
    }
  }
  u() {
    [...this.c.keys()].forEach((handle2) => {
      const threads = this.c.get(handle2).getAllComments();
      if (threads.length) {
        const providerId = this.z(handle2);
        this.j.setWorkspaceComments(providerId, threads);
      }
    });
  }
  w() {
    if (!this.h) {
      this.h = this.m.onDidChangeViewVisibility((e) => {
        if (e.id === $_Rb && e.visible) {
          this.u();
          if (this.h) {
            this.h.dispose();
            this.h = null;
          }
        }
      });
    }
  }
  /**
   * If the comments view has never been opened, the constructor for it has not yet run so it has
   * no listeners for comment threads being set or updated. Listen for the view opening for the
   * first time and send it comments then.
   */
  y(commentsPanelAlreadyConstructed) {
    if (!commentsPanelAlreadyConstructed) {
      this.w();
    }
    this.B(this.n.onDidChangeContainer((e) => {
      if (e.views.find((view) => view.id === $_Rb)) {
        this.u();
        this.w();
      }
    }));
    this.B(this.n.onDidChangeContainerLocation((e) => {
      const commentsContainer = this.n.getViewContainerByViewId($_Rb);
      if (e.viewContainer.id === commentsContainer?.id) {
        this.u();
        this.w();
      }
    }));
  }
  z(handle2) {
    if (!this.b.has(handle2)) {
      throw new Error("Unknown handler");
    }
    return this.b.get(handle2);
  }
};
$CSb = __decorate([
  $frb($xT.MainThreadComments),
  __param(1, $RJb),
  __param(2, $uob),
  __param(3, $$M),
  __param(4, $vl),
  __param(5, $mJ)
], $CSb);

// out-build/vs/workbench/contrib/notebook/common/notebookExecutionService.js
var CellExecutionUpdateType;
(function(CellExecutionUpdateType2) {
  CellExecutionUpdateType2[CellExecutionUpdateType2["Output"] = 1] = "Output";
  CellExecutionUpdateType2[CellExecutionUpdateType2["OutputItems"] = 2] = "OutputItems";
  CellExecutionUpdateType2[CellExecutionUpdateType2["ExecutionState"] = 3] = "ExecutionState";
})(CellExecutionUpdateType || (CellExecutionUpdateType = {}));
var $vL = $Qk("INotebookExecutionService");

// out-build/vs/workbench/api/browser/mainThreadNotebookDto.js
var NotebookDto;
(function(NotebookDto2) {
  function toNotebookOutputItemDto(item) {
    return {
      mime: item.mime,
      valueBytes: item.data
    };
  }
  NotebookDto2.toNotebookOutputItemDto = toNotebookOutputItemDto;
  function toNotebookOutputDto(output) {
    return {
      outputId: output.outputId,
      metadata: output.metadata,
      items: output.outputs.map(toNotebookOutputItemDto)
    };
  }
  NotebookDto2.toNotebookOutputDto = toNotebookOutputDto;
  function toNotebookCellDataDto(cell) {
    return {
      cellKind: cell.cellKind,
      language: cell.language,
      mime: cell.mime,
      source: cell.source,
      internalMetadata: cell.internalMetadata,
      metadata: cell.metadata,
      outputs: cell.outputs.map(toNotebookOutputDto)
    };
  }
  NotebookDto2.toNotebookCellDataDto = toNotebookCellDataDto;
  function toNotebookDataDto(data) {
    return {
      metadata: data.metadata,
      cells: data.cells.map(toNotebookCellDataDto)
    };
  }
  NotebookDto2.toNotebookDataDto = toNotebookDataDto;
  function fromNotebookOutputItemDto(item) {
    return {
      mime: item.mime,
      data: item.valueBytes
    };
  }
  NotebookDto2.fromNotebookOutputItemDto = fromNotebookOutputItemDto;
  function fromNotebookOutputDto(output) {
    return {
      outputId: output.outputId,
      metadata: output.metadata,
      outputs: output.items.map(fromNotebookOutputItemDto)
    };
  }
  NotebookDto2.fromNotebookOutputDto = fromNotebookOutputDto;
  function fromNotebookCellDataDto(cell) {
    return {
      cellKind: cell.cellKind,
      language: cell.language,
      mime: cell.mime,
      source: cell.source,
      outputs: cell.outputs.map(fromNotebookOutputDto),
      metadata: cell.metadata,
      internalMetadata: cell.internalMetadata
    };
  }
  NotebookDto2.fromNotebookCellDataDto = fromNotebookCellDataDto;
  function fromNotebookDataDto(data) {
    return {
      metadata: data.metadata,
      cells: data.cells.map(fromNotebookCellDataDto)
    };
  }
  NotebookDto2.fromNotebookDataDto = fromNotebookDataDto;
  function toNotebookCellDto(cell) {
    return {
      handle: cell.handle,
      uri: cell.uri,
      source: cell.textBuffer.getLinesContent(),
      eol: cell.textBuffer.getEOL(),
      language: cell.language,
      cellKind: cell.cellKind,
      outputs: cell.outputs.map(toNotebookOutputDto),
      metadata: cell.metadata,
      internalMetadata: cell.internalMetadata
    };
  }
  NotebookDto2.toNotebookCellDto = toNotebookCellDto;
  function fromCellExecuteUpdateDto(data) {
    if (data.editType === CellExecutionUpdateType.Output) {
      return {
        editType: data.editType,
        cellHandle: data.cellHandle,
        append: data.append,
        outputs: data.outputs.map(fromNotebookOutputDto)
      };
    } else if (data.editType === CellExecutionUpdateType.OutputItems) {
      return {
        editType: data.editType,
        append: data.append,
        outputId: data.outputId,
        items: data.items.map(fromNotebookOutputItemDto)
      };
    } else {
      return data;
    }
  }
  NotebookDto2.fromCellExecuteUpdateDto = fromCellExecuteUpdateDto;
  function fromCellExecuteCompleteDto(data) {
    return data;
  }
  NotebookDto2.fromCellExecuteCompleteDto = fromCellExecuteCompleteDto;
  function fromCellEditOperationDto(edit3) {
    if (edit3.editType === 1) {
      return {
        editType: edit3.editType,
        index: edit3.index,
        count: edit3.count,
        cells: edit3.cells.map(fromNotebookCellDataDto)
      };
    } else {
      return edit3;
    }
  }
  NotebookDto2.fromCellEditOperationDto = fromCellEditOperationDto;
})(NotebookDto || (NotebookDto = {}));

// out-build/vs/workbench/contrib/notebook/common/notebookCellStatusBarService.js
var $DSb = $Qk("notebookCellStatusBarService");

// out-build/vs/workbench/api/browser/mainThreadNotebook.js
var $ESb = class $ESb2 {
  constructor(extHostContext, f, g, h3) {
    this.f = f;
    this.g = g;
    this.h = h3;
    this.a = new $2c();
    this.c = /* @__PURE__ */ new Map();
    this.d = /* @__PURE__ */ new Map();
    this.b = extHostContext.getProxy($yT.ExtHostNotebook);
  }
  dispose() {
    this.a.dispose();
    $Xc(this.c.values());
  }
  $registerNotebookSerializer(handle2, extension, viewType, options3, data) {
    const disposables = new $2c();
    disposables.add(this.f.registerNotebookSerializer(viewType, extension, {
      options: options3,
      dataToNotebook: async (data2) => {
        const sw = new $te();
        let result;
        if (data2.byteLength === 0 && viewType === "interactive") {
          result = NotebookDto.fromNotebookDataDto({ cells: [], metadata: {} });
        } else {
          const dto = await this.b.$dataToNotebook(handle2, data2, CancellationToken.None);
          result = NotebookDto.fromNotebookDataDto(dto.value);
        }
        this.h.trace(`[NotebookSerializer] dataToNotebook DONE after ${sw.elapsed()}ms`, {
          viewType,
          extensionId: extension.id.value
        });
        return result;
      },
      notebookToData: (data2) => {
        const sw = new $te();
        const result = this.b.$notebookToData(handle2, new $ES(NotebookDto.toNotebookDataDto(data2)), CancellationToken.None);
        this.h.trace(`[NotebookSerializer] notebookToData DONE after ${sw.elapsed()}`, {
          viewType,
          extensionId: extension.id.value
        });
        return result;
      },
      save: async (uri, versionId, options4, token) => {
        const stat = await this.b.$saveNotebook(handle2, uri, versionId, options4, token);
        return {
          ...stat,
          children: void 0,
          resource: uri
        };
      },
      searchInNotebooks: async (textQuery, token, allPriorityInfo) => {
        const contributedType = this.f.getContributedNotebookType(viewType);
        if (!contributedType) {
          return { results: [], limitHit: false };
        }
        const fileNames = contributedType.selectors;
        const includes2 = fileNames.map((selector) => {
          const globPattern = selector.include || selector;
          return globPattern.toString();
        });
        if (!includes2.length) {
          return {
            results: [],
            limitHit: false
          };
        }
        const thisPriorityInfo = $Mb([{ isFromSettings: false, filenamePatterns: includes2 }, ...allPriorityInfo.get(viewType) ?? []]);
        const otherEditorsPriorityInfo = Array.from(allPriorityInfo.keys()).flatMap((key2) => {
          if (key2 !== viewType) {
            return allPriorityInfo.get(key2) ?? [];
          }
          return [];
        });
        const searchComplete = await this.b.$searchInNotebooks(handle2, textQuery, thisPriorityInfo, otherEditorsPriorityInfo, token);
        const revivedResults = searchComplete.results.map((result) => {
          const resource = URI.revive(result.resource);
          return {
            resource,
            cellResults: result.cellResults.map((e) => $cu(e))
          };
        });
        return { results: revivedResults, limitHit: searchComplete.limitHit };
      }
    }));
    if (data) {
      disposables.add(this.f.registerContributedNotebookType(viewType, data));
    }
    this.c.set(handle2, disposables);
    this.h.trace("[NotebookSerializer] registered notebook serializer", {
      viewType,
      extensionId: extension.id.value
    });
  }
  $unregisterNotebookSerializer(handle2) {
    this.c.get(handle2)?.dispose();
    this.c.delete(handle2);
  }
  $emitCellStatusBarEvent(eventHandle) {
    const emitter = this.d.get(eventHandle);
    if (emitter instanceof $ze) {
      emitter.fire(void 0);
    }
  }
  async $registerNotebookCellStatusBarItemProvider(handle2, eventHandle, viewType) {
    const that = this;
    const provider = {
      async provideCellStatusBarItems(uri, index, token) {
        const result = await that.b.$provideNotebookCellStatusBarItems(handle2, uri, index, token);
        return {
          items: result?.items ?? [],
          dispose() {
            if (result) {
              that.b.$releaseNotebookCellStatusBarItems(result.cacheId);
            }
          }
        };
      },
      viewType
    };
    if (typeof eventHandle === "number") {
      const emitter = new $ze();
      this.d.set(eventHandle, emitter);
      provider.onDidChangeStatusBarItems = emitter.event;
    }
    const disposable = this.g.registerCellStatusBarItemProvider(provider);
    this.d.set(handle2, disposable);
  }
  async $unregisterNotebookCellStatusBarItemProvider(handle2, eventHandle) {
    const unregisterThing = (handle3) => {
      const entry = this.d.get(handle3);
      if (entry) {
        this.d.get(handle3)?.dispose();
        this.d.delete(handle3);
      }
    };
    unregisterThing(handle2);
    if (typeof eventHandle === "number") {
      unregisterThing(eventHandle);
    }
  }
};
$ESb = __decorate([
  $frb($xT.MainThreadNotebook),
  __param(1, $mrb),
  __param(2, $DSb),
  __param(3, $wn)
], $ESb);
$tn.registerCommand("_executeDataToNotebook", async (accessor, ...args2) => {
  const [notebookType, bytes] = args2;
  $Jg(typeof notebookType === "string", "string");
  $Jg(bytes instanceof $Ci, "VSBuffer");
  const notebookService = accessor.get($mrb);
  const info = await notebookService.withNotebookDataProvider(notebookType);
  if (!(info instanceof $nrb)) {
    return;
  }
  const dto = await info.serializer.dataToNotebook(bytes);
  return new $ES(NotebookDto.toNotebookDataDto(dto));
});
$tn.registerCommand("_executeNotebookToData", async (accessor, ...args2) => {
  const [notebookType, dto] = args2;
  $Jg(typeof notebookType === "string", "string");
  $Jg(typeof dto === "object");
  const notebookService = accessor.get($mrb);
  const info = await notebookService.withNotebookDataProvider(notebookType);
  if (!(info instanceof $nrb)) {
    return;
  }
  const data = NotebookDto.fromNotebookDataDto(dto.value);
  const bytes = await info.serializer.notebookToData(data);
  return bytes;
});

// out-build/vs/workbench/contrib/notebook/common/notebookExecutionStateService.js
var NotebookExecutionType;
(function(NotebookExecutionType2) {
  NotebookExecutionType2[NotebookExecutionType2["cell"] = 0] = "cell";
  NotebookExecutionType2[NotebookExecutionType2["notebook"] = 1] = "notebook";
})(NotebookExecutionType || (NotebookExecutionType = {}));
var $wL = $Qk("INotebookExecutionStateService");

// out-build/vs/workbench/contrib/notebook/common/notebookKernelService.js
var $BL = 100;
var ProxyKernelState;
(function(ProxyKernelState2) {
  ProxyKernelState2[ProxyKernelState2["Disconnected"] = 1] = "Disconnected";
  ProxyKernelState2[ProxyKernelState2["Connected"] = 2] = "Connected";
  ProxyKernelState2[ProxyKernelState2["Initializing"] = 3] = "Initializing";
})(ProxyKernelState || (ProxyKernelState = {}));
var $CL = $Qk("INotebookKernelService");
var $DL = $Qk("INotebookKernelHistoryService");

// out-build/vs/workbench/api/browser/mainThreadNotebookKernels.js
var MainThreadKernel = class {
  get preloadUris() {
    return this.b.map((p) => p.uri);
  }
  get preloadProvides() {
    return this.b.flatMap((p) => p.provides);
  }
  constructor(data, c) {
    this.c = c;
    this.a = new $ze();
    this.onDidChange = this.a.event;
    this.id = data.id;
    this.viewType = data.notebookType;
    this.extension = data.extensionId;
    this.implementsInterrupt = data.supportsInterrupt ?? false;
    this.label = data.label;
    this.description = data.description;
    this.detail = data.detail;
    this.supportedLanguages = $Qb(data.supportedLanguages) ? data.supportedLanguages : c.getRegisteredLanguageIds();
    this.implementsExecutionOrder = data.supportsExecutionOrder ?? false;
    this.hasVariableProvider = data.hasVariableProvider ?? false;
    this.localResourceRoot = URI.revive(data.extensionLocation);
    this.b = data.preloads?.map((u) => ({ uri: URI.revive(u.uri), provides: u.provides })) ?? [];
  }
  update(data) {
    const event = /* @__PURE__ */ Object.create(null);
    if (data.label !== void 0) {
      this.label = data.label;
      event.label = true;
    }
    if (data.description !== void 0) {
      this.description = data.description;
      event.description = true;
    }
    if (data.detail !== void 0) {
      this.detail = data.detail;
      event.detail = true;
    }
    if (data.supportedLanguages !== void 0) {
      this.supportedLanguages = $Qb(data.supportedLanguages) ? data.supportedLanguages : this.c.getRegisteredLanguageIds();
      event.supportedLanguages = true;
    }
    if (data.supportsExecutionOrder !== void 0) {
      this.implementsExecutionOrder = data.supportsExecutionOrder;
      event.hasExecutionOrder = true;
    }
    if (data.supportsInterrupt !== void 0) {
      this.implementsInterrupt = data.supportsInterrupt;
      event.hasInterruptHandler = true;
    }
    if (data.hasVariableProvider !== void 0) {
      this.hasVariableProvider = data.hasVariableProvider;
      event.hasVariableProvider = true;
    }
    this.a.fire(event);
  }
};
var MainThreadKernelDetectionTask = class {
  constructor(notebookType) {
    this.notebookType = notebookType;
  }
};
var $FSb = class $FSb2 {
  constructor(extHostContext, k, l, m, n, notebookEditorService) {
    this.k = k;
    this.l = l;
    this.m = m;
    this.n = n;
    this.a = new $_c();
    this.b = new $2c();
    this.c = /* @__PURE__ */ new Map();
    this.d = /* @__PURE__ */ new Map();
    this.f = /* @__PURE__ */ new Map();
    this.g = /* @__PURE__ */ new Map();
    this.i = /* @__PURE__ */ new Map();
    this.j = /* @__PURE__ */ new Map();
    this.r = 0;
    this.s = /* @__PURE__ */ new Map();
    this.h = extHostContext.getProxy($yT.ExtHostNotebookKernels);
    notebookEditorService.listNotebookEditors().forEach(this.o, this);
    notebookEditorService.onDidAddNotebookEditor(this.o, this, this.b);
    notebookEditorService.onDidRemoveNotebookEditor(this.q, this, this.b);
    this.b.add($1c(() => {
      this.i.forEach((e) => {
        e.complete({});
      });
      this.j.forEach((e) => e.complete());
    }));
    this.b.add(this.m.onDidChangeExecution((e) => {
      if (e.type === NotebookExecutionType.cell) {
        this.h.$cellExecutionChanged(e.notebook, e.cellHandle, e.changed?.state);
      }
    }));
    this.b.add(this.l.onDidChangeSelectedNotebooks((e) => {
      for (const [handle2, [kernel]] of this.c) {
        if (e.oldKernel === kernel.id) {
          this.h.$acceptNotebookAssociation(handle2, e.notebook, false);
        } else if (e.newKernel === kernel.id) {
          this.h.$acceptNotebookAssociation(handle2, e.notebook, true);
        }
      }
    }));
  }
  dispose() {
    this.b.dispose();
    for (const [, registration] of this.c.values()) {
      registration.dispose();
    }
    for (const [, registration] of this.d.values()) {
      registration.dispose();
    }
    for (const [, registration] of this.f.values()) {
      registration.dispose();
    }
    this.a.dispose();
  }
  // --- kernel ipc
  o(editor) {
    const ipcListener = editor.onDidReceiveMessage((e) => {
      if (!editor.hasModel()) {
        return;
      }
      const { selected } = this.l.getMatchingKernel(editor.textModel);
      if (!selected) {
        return;
      }
      for (const [handle2, candidate] of this.c) {
        if (candidate[0] === selected) {
          this.h.$acceptKernelMessageFromRenderer(handle2, editor.getId(), e.message);
          break;
        }
      }
    });
    this.a.set(editor, ipcListener);
  }
  q(editor) {
    this.a.deleteAndDispose(editor);
  }
  async $postMessage(handle2, editorId, message) {
    const tuple = this.c.get(handle2);
    if (!tuple) {
      throw new Error("kernel already disposed");
    }
    const [kernel] = tuple;
    let didSend = false;
    for (const [editor] of this.a) {
      if (!editor.hasModel()) {
        continue;
      }
      if (this.l.getMatchingKernel(editor.textModel).selected !== kernel) {
        continue;
      }
      if (editorId === void 0) {
        editor.postMessage(message);
        didSend = true;
      } else if (editor.getId() === editorId) {
        editor.postMessage(message);
        didSend = true;
        break;
      }
    }
    return didSend;
  }
  $receiveVariable(requestId, variable) {
    const source = this.s.get(requestId);
    if (source) {
      source.emitOne(variable);
    }
  }
  // --- kernel adding/updating/removal
  async $addKernel(handle2, data) {
    const that = this;
    const kernel = new class extends MainThreadKernel {
      async executeNotebookCellsRequest(uri, handles) {
        await that.h.$executeCells(handle2, uri, handles);
      }
      async cancelNotebookCellExecution(uri, handles) {
        await that.h.$cancelCells(handle2, uri, handles);
      }
      provideVariables(notebookUri, parentId, kind, start, token) {
        const requestId = `${handle2}variables${that.r++}`;
        if (that.s.has(requestId)) {
          return that.s.get(requestId).asyncIterable;
        }
        const source = new $mi();
        that.s.set(requestId, source);
        that.h.$provideVariables(handle2, requestId, notebookUri, parentId, kind, start, token).then(() => {
          source.resolve();
          that.s.delete(requestId);
        }).catch((err) => {
          source.reject(err);
          that.s.delete(requestId);
        });
        return source.asyncIterable;
      }
    }(data, this.k);
    const disposables = this.b.add(new $2c());
    this.c.set(handle2, [kernel, disposables]);
    disposables.add(this.l.registerKernel(kernel));
  }
  $updateKernel(handle2, data) {
    const tuple = this.c.get(handle2);
    if (tuple) {
      tuple[0].update(data);
    }
  }
  $removeKernel(handle2) {
    const tuple = this.c.get(handle2);
    if (tuple) {
      tuple[1].dispose();
      this.c.delete(handle2);
    }
  }
  $updateNotebookPriority(handle2, notebook, value) {
    const tuple = this.c.get(handle2);
    if (tuple) {
      this.l.updateKernelNotebookAffinity(tuple[0], URI.revive(notebook), value);
    }
  }
  // --- Cell execution
  $createExecution(handle2, controllerId, rawUri, cellHandle) {
    const uri = URI.revive(rawUri);
    const notebook = this.n.getNotebookTextModel(uri);
    if (!notebook) {
      throw new Error(`Notebook not found: ${uri.toString()}`);
    }
    const kernel = this.l.getMatchingKernel(notebook);
    if (!kernel.selected || kernel.selected.id !== controllerId) {
      throw new Error(`Kernel is not selected: ${kernel.selected?.id} !== ${controllerId}`);
    }
    const execution = this.m.createCellExecution(uri, cellHandle);
    execution.confirm();
    this.i.set(handle2, execution);
  }
  $updateExecution(handle2, data) {
    const updates = data.value;
    try {
      const execution = this.i.get(handle2);
      execution?.update(updates.map(NotebookDto.fromCellExecuteUpdateDto));
    } catch (e) {
      $gb(e);
    }
  }
  $completeExecution(handle2, data) {
    try {
      const execution = this.i.get(handle2);
      execution?.complete(NotebookDto.fromCellExecuteCompleteDto(data.value));
    } catch (e) {
      $gb(e);
    } finally {
      this.i.delete(handle2);
    }
  }
  // --- Notebook execution
  $createNotebookExecution(handle2, controllerId, rawUri) {
    const uri = URI.revive(rawUri);
    const notebook = this.n.getNotebookTextModel(uri);
    if (!notebook) {
      throw new Error(`Notebook not found: ${uri.toString()}`);
    }
    const kernel = this.l.getMatchingKernel(notebook);
    if (!kernel.selected || kernel.selected.id !== controllerId) {
      throw new Error(`Kernel is not selected: ${kernel.selected?.id} !== ${controllerId}`);
    }
    const execution = this.m.createExecution(uri);
    execution.confirm();
    this.j.set(handle2, execution);
  }
  $beginNotebookExecution(handle2) {
    try {
      const execution = this.j.get(handle2);
      execution?.begin();
    } catch (e) {
      $gb(e);
    }
  }
  $completeNotebookExecution(handle2) {
    try {
      const execution = this.j.get(handle2);
      execution?.complete();
    } catch (e) {
      $gb(e);
    } finally {
      this.j.delete(handle2);
    }
  }
  // --- notebook kernel detection task
  async $addKernelDetectionTask(handle2, notebookType) {
    const kernelDetectionTask = new MainThreadKernelDetectionTask(notebookType);
    const registration = this.l.registerNotebookKernelDetectionTask(kernelDetectionTask);
    this.d.set(handle2, [kernelDetectionTask, registration]);
  }
  $removeKernelDetectionTask(handle2) {
    const tuple = this.d.get(handle2);
    if (tuple) {
      tuple[1].dispose();
      this.d.delete(handle2);
    }
  }
  // --- notebook kernel source action provider
  async $addKernelSourceActionProvider(handle2, eventHandle, notebookType) {
    const kernelSourceActionProvider = {
      viewType: notebookType,
      provideKernelSourceActions: async () => {
        const actions = await this.h.$provideKernelSourceActions(handle2, CancellationToken.None);
        return actions.map((action) => {
          let documentation = action.documentation;
          if (action.documentation && typeof action.documentation !== "string") {
            documentation = URI.revive(action.documentation);
          }
          return {
            label: action.label,
            command: action.command,
            description: action.description,
            detail: action.detail,
            documentation
          };
        });
      }
    };
    if (typeof eventHandle === "number") {
      const emitter = new $ze();
      this.g.set(eventHandle, emitter);
      kernelSourceActionProvider.onDidChangeSourceActions = emitter.event;
    }
    const registration = this.l.registerKernelSourceActionProvider(notebookType, kernelSourceActionProvider);
    this.f.set(handle2, [kernelSourceActionProvider, registration]);
  }
  $removeKernelSourceActionProvider(handle2, eventHandle) {
    const tuple = this.f.get(handle2);
    if (tuple) {
      tuple[1].dispose();
      this.f.delete(handle2);
    }
    if (typeof eventHandle === "number") {
      this.g.delete(eventHandle);
    }
  }
  $emitNotebookKernelSourceActionsChangeEvent(eventHandle) {
    const emitter = this.g.get(eventHandle);
    if (emitter instanceof $ze) {
      emitter.fire(void 0);
    }
  }
  $variablesUpdated(notebookUri) {
    this.l.notifyVariablesChange(URI.revive(notebookUri));
  }
};
$FSb = __decorate([
  $frb($xT.MainThreadNotebookKernels),
  __param(1, $1E),
  __param(2, $CL),
  __param(3, $wL),
  __param(4, $mrb),
  __param(5, $yMb)
], $FSb);

// out-build/vs/workbench/api/browser/mainThreadNotebookDocuments.js
var $GSb = class $GSb2 {
  constructor(extHostContext, f, g) {
    this.f = f;
    this.g = g;
    this.a = new $2c();
    this.c = new $Ec();
    this.b = extHostContext.getProxy($yT.ExtHostNotebookDocuments);
    this.d = new $DOb(this.g.extUri);
    this.a.add(this.f.onDidChangeDirty((model) => this.b.$acceptDirtyStateChanged(model.resource, model.isDirty())));
    this.a.add(this.f.onDidSaveNotebook((e) => this.b.$acceptModelSaved(e)));
    this.a.add(f.onWillFailWithConflict((e) => {
      this.d.remove(e.resource);
    }));
  }
  dispose() {
    this.a.dispose();
    this.d.dispose();
    $Xc(this.c.values());
  }
  handleNotebooksAdded(notebooks) {
    for (const textModel of notebooks) {
      const disposableStore = new $2c();
      disposableStore.add(textModel.onDidChangeContent((event) => {
        const eventDto = {
          versionId: event.versionId,
          rawEvents: []
        };
        for (const e of event.rawEvents) {
          switch (e.kind) {
            case NotebookCellsChangeType.ModelChange:
              eventDto.rawEvents.push({
                kind: e.kind,
                changes: e.changes.map((diff3) => [diff3[0], diff3[1], diff3[2].map((cell) => NotebookDto.toNotebookCellDto(cell))])
              });
              break;
            case NotebookCellsChangeType.Move:
              eventDto.rawEvents.push({
                kind: e.kind,
                index: e.index,
                length: e.length,
                newIdx: e.newIdx
              });
              break;
            case NotebookCellsChangeType.Output:
              eventDto.rawEvents.push({
                kind: e.kind,
                index: e.index,
                outputs: e.outputs.map(NotebookDto.toNotebookOutputDto)
              });
              break;
            case NotebookCellsChangeType.OutputItem:
              eventDto.rawEvents.push({
                kind: e.kind,
                index: e.index,
                outputId: e.outputId,
                outputItems: e.outputItems.map(NotebookDto.toNotebookOutputItemDto),
                append: e.append
              });
              break;
            case NotebookCellsChangeType.ChangeCellLanguage:
            case NotebookCellsChangeType.ChangeCellContent:
            case NotebookCellsChangeType.ChangeCellMetadata:
            case NotebookCellsChangeType.ChangeCellInternalMetadata:
              eventDto.rawEvents.push(e);
              break;
          }
        }
        const hasDocumentMetadataChangeEvent = event.rawEvents.find((e) => e.kind === NotebookCellsChangeType.ChangeDocumentMetadata);
        this.b.$acceptModelChanged(textModel.uri, new $ES(eventDto), this.f.isDirty(textModel.uri), hasDocumentMetadataChangeEvent ? textModel.metadata : void 0);
      }));
      this.c.set(textModel.uri, disposableStore);
    }
  }
  handleNotebooksRemoved(uris) {
    for (const uri of uris) {
      this.c.get(uri)?.dispose();
      this.c.delete(uri);
    }
  }
  async $tryCreateNotebook(options3) {
    if (options3.content) {
      const ref = await this.f.resolve({ untitledResource: void 0 }, options3.viewType);
      ref.object.notebook.onWillDispose(() => {
        ref.dispose();
      });
      this.b.$acceptDirtyStateChanged(ref.object.resource, true);
      if (options3.content) {
        const data = NotebookDto.fromNotebookDataDto(options3.content);
        ref.object.notebook.reset(data.cells, data.metadata, ref.object.notebook.transientOptions);
      }
      return ref.object.notebook.uri;
    } else {
      const notebook = await this.f.createUntitledNotebookTextModel(options3.viewType);
      return notebook.uri;
    }
  }
  async $tryOpenNotebook(uriComponents) {
    const uri = URI.revive(uriComponents);
    const ref = await this.f.resolve(uri, void 0);
    if (uriComponents.scheme === "untitled") {
      ref.object.notebook.onWillDispose(() => {
        ref.dispose();
      });
    }
    this.d.add(uri, ref);
    return uri;
  }
  async $trySaveNotebook(uriComponents) {
    const uri = URI.revive(uriComponents);
    const ref = await this.f.resolve(uri);
    const saveResult = await ref.object.save();
    ref.dispose();
    return saveResult;
  }
};
$GSb = __decorate([
  __param(1, $orb),
  __param(2, $vl)
], $GSb);

// out-build/vs/workbench/api/browser/mainThreadNotebookEditors.js
var MainThreadNotebook = class {
  constructor(editor, disposables) {
    this.editor = editor;
    this.disposables = disposables;
  }
  dispose() {
    this.disposables.dispose();
  }
};
var $HSb = class $HSb2 {
  constructor(extHostContext, e, f, g, h3) {
    this.e = e;
    this.f = f;
    this.g = g;
    this.h = h3;
    this.a = new $2c();
    this.c = /* @__PURE__ */ new Map();
    this.b = extHostContext.getProxy($yT.ExtHostNotebookEditors);
    this.e.onDidActiveEditorChange(() => this.i(), this, this.a);
    this.g.onDidRemoveGroup(() => this.i(), this, this.a);
    this.g.onDidMoveGroup(() => this.i(), this, this.a);
  }
  dispose() {
    this.a.dispose();
    $Xc(this.c.values());
  }
  handleEditorsAdded(editors) {
    for (const editor of editors) {
      const editorDisposables = new $2c();
      editorDisposables.add(editor.onDidChangeVisibleRanges(() => {
        this.b.$acceptEditorPropertiesChanged(editor.getId(), { visibleRanges: { ranges: editor.visibleRanges } });
      }));
      editorDisposables.add(editor.onDidChangeSelection(() => {
        this.b.$acceptEditorPropertiesChanged(editor.getId(), { selections: { selections: editor.getSelections() } });
      }));
      const wrapper = new MainThreadNotebook(editor, editorDisposables);
      this.c.set(editor.getId(), wrapper);
    }
  }
  handleEditorsRemoved(editorIds) {
    for (const id2 of editorIds) {
      this.c.get(id2)?.dispose();
      this.c.delete(id2);
    }
  }
  i() {
    const result = /* @__PURE__ */ Object.create(null);
    for (const editorPane of this.e.visibleEditorPanes) {
      const candidate = $Qrb(editorPane);
      if (candidate && this.c.has(candidate.getId())) {
        result[candidate.getId()] = $AS(this.g, editorPane.group);
      }
    }
    if (!$Pv(result, this.d)) {
      this.d = result;
      this.b.$acceptEditorViewColumns(result);
    }
  }
  async $tryShowNotebookDocument(resource, viewType, options3) {
    const editorOptions2 = {
      cellSelections: options3.selections,
      preserveFocus: options3.preserveFocus,
      pinned: options3.pinned,
      // selection: options.selection,
      // preserve pre 1.38 behaviour to not make group active when preserveFocus: true
      // but make sure to restore the editor to fix https://github.com/microsoft/vscode/issues/79633
      activation: options3.preserveFocus ? EditorActivation.RESTORE : void 0,
      label: options3.label,
      override: viewType
    };
    const editorPane = await this.e.openEditor({ resource: URI.revive(resource), options: editorOptions2 }, $zS(this.g, this.h, options3.position));
    const notebookEditor = $Qrb(editorPane);
    if (notebookEditor) {
      return notebookEditor.getId();
    } else {
      throw new Error(`Notebook Editor creation failure for document ${JSON.stringify(resource)}`);
    }
  }
  async $tryRevealRange(id2, range, revealType) {
    const editor = this.f.getNotebookEditor(id2);
    if (!editor) {
      return;
    }
    const notebookEditor = editor;
    if (!notebookEditor.hasModel()) {
      return;
    }
    if (range.start >= notebookEditor.getLength()) {
      return;
    }
    const cell = notebookEditor.cellAt(range.start);
    switch (revealType) {
      case NotebookEditorRevealType2.Default:
        return notebookEditor.revealCellRangeInView(range);
      case NotebookEditorRevealType2.InCenter:
        return notebookEditor.revealInCenter(cell);
      case NotebookEditorRevealType2.InCenterIfOutsideViewport:
        return notebookEditor.revealInCenterIfOutsideViewport(cell);
      case NotebookEditorRevealType2.AtTop:
        return notebookEditor.revealInViewAtTop(cell);
    }
  }
  $trySetSelections(id2, ranges) {
    const editor = this.f.getNotebookEditor(id2);
    if (!editor) {
      return;
    }
    editor.setSelections(ranges);
    if (ranges.length) {
      editor.setFocus({ start: ranges[0].start, end: ranges[0].start + 1 });
    }
  }
};
$HSb = __decorate([
  __param(1, $mJ),
  __param(2, $yMb),
  __param(3, $iJ),
  __param(4, $kl)
], $HSb);

// out-build/vs/workbench/api/browser/mainThreadNotebookDocumentsAndEditors.js
var $ISb_1;
var NotebookAndEditorState = class {
  static delta(before, after) {
    if (!before) {
      return {
        addedDocuments: [...after.documents],
        removedDocuments: [],
        addedEditors: [...after.textEditors.values()],
        removedEditors: [],
        visibleEditors: [...after.visibleEditors].map((editor) => editor[0])
      };
    }
    const documentDelta = $b(before.documents, after.documents);
    const editorDelta = $c(before.textEditors, after.textEditors);
    const newActiveEditor = before.activeEditor !== after.activeEditor ? after.activeEditor : void 0;
    const visibleEditorDelta = $c(before.visibleEditors, after.visibleEditors);
    return {
      addedDocuments: documentDelta.added,
      removedDocuments: documentDelta.removed.map((e) => e.uri),
      addedEditors: editorDelta.added,
      removedEditors: editorDelta.removed.map((removed) => removed.getId()),
      newActiveEditor,
      visibleEditors: visibleEditorDelta.added.length === 0 && visibleEditorDelta.removed.length === 0 ? void 0 : [...after.visibleEditors].map((editor) => editor[0])
    };
  }
  constructor(documents, textEditors, activeEditor, visibleEditors) {
    this.documents = documents;
    this.textEditors = textEditors;
    this.activeEditor = activeEditor;
    this.visibleEditors = visibleEditors;
  }
};
var $ISb = $ISb_1 = class $ISb2 {
  constructor(extHostContext, instantiationService, h3, i2, j, k, l) {
    this.h = h3;
    this.i = i2;
    this.j = j;
    this.k = k;
    this.l = l;
    this.b = new $2c();
    this.c = new $_c();
    this.a = extHostContext.getProxy($yT.ExtHostNotebook);
    this.f = instantiationService.createInstance($GSb, extHostContext);
    this.g = instantiationService.createInstance($HSb, extHostContext);
    extHostContext.set($xT.MainThreadNotebookDocuments, this.f);
    extHostContext.set($xT.MainThreadNotebookEditors, this.g);
    this.h.onWillAddNotebookDocument(() => this.o(), this, this.b);
    this.h.onDidRemoveNotebookDocument(() => this.o(), this, this.b);
    this.j.onDidActiveEditorChange(() => this.o(), this, this.b);
    this.j.onDidVisibleEditorsChange(() => this.o(), this, this.b);
    this.i.onDidAddNotebookEditor(this.m, this, this.b);
    this.i.onDidRemoveNotebookEditor(this.n, this, this.b);
    this.o();
  }
  dispose() {
    this.f.dispose();
    this.g.dispose();
    this.b.dispose();
    this.c.dispose();
  }
  m(editor) {
    this.c.set(editor.getId(), $Zc(editor.onDidChangeModel(() => this.o()), editor.onDidFocusWidget(() => this.o(editor))));
    this.o();
  }
  n(editor) {
    this.c.deleteAndDispose(editor.getId());
    this.o();
  }
  o(focusedEditor) {
    const editors = /* @__PURE__ */ new Map();
    const visibleEditorsMap = /* @__PURE__ */ new Map();
    for (const editor of this.i.listNotebookEditors()) {
      if (editor.hasModel()) {
        editors.set(editor.getId(), editor);
      }
    }
    const activeNotebookEditor = $Qrb(this.j.activeEditorPane);
    let activeEditor = null;
    if (activeNotebookEditor) {
      activeEditor = activeNotebookEditor.getId();
    } else if (focusedEditor?.textModel) {
      activeEditor = focusedEditor.getId();
    }
    if (activeEditor && !editors.has(activeEditor)) {
      this.l.trace("MainThreadNotebooksAndEditors#_updateState: active editor is not in editors list", activeEditor, editors.keys());
      activeEditor = null;
    }
    for (const editorPane of this.j.visibleEditorPanes) {
      const notebookEditor = $Qrb(editorPane);
      if (notebookEditor?.hasModel() && editors.has(notebookEditor.getId())) {
        visibleEditorsMap.set(notebookEditor.getId(), notebookEditor);
      }
    }
    const newState = new NotebookAndEditorState(new Set(this.h.listNotebookDocuments()), editors, activeEditor, visibleEditorsMap);
    this.p(NotebookAndEditorState.delta(this.d, newState));
    this.d = newState;
  }
  p(delta) {
    if ($ISb_1.q(delta)) {
      return;
    }
    const dto = {
      removedDocuments: delta.removedDocuments,
      removedEditors: delta.removedEditors,
      newActiveEditor: delta.newActiveEditor,
      visibleEditors: delta.visibleEditors,
      addedDocuments: delta.addedDocuments.map($ISb_1.r),
      addedEditors: delta.addedEditors.map(this.s, this)
    };
    this.a.$acceptDocumentAndEditorsDelta(new $ES(dto));
    this.g.handleEditorsRemoved(delta.removedEditors);
    this.f.handleNotebooksRemoved(delta.removedDocuments);
    this.f.handleNotebooksAdded(delta.addedDocuments);
    this.g.handleEditorsAdded(delta.addedEditors);
  }
  static q(delta) {
    if (delta.addedDocuments !== void 0 && delta.addedDocuments.length > 0) {
      return false;
    }
    if (delta.removedDocuments !== void 0 && delta.removedDocuments.length > 0) {
      return false;
    }
    if (delta.addedEditors !== void 0 && delta.addedEditors.length > 0) {
      return false;
    }
    if (delta.removedEditors !== void 0 && delta.removedEditors.length > 0) {
      return false;
    }
    if (delta.visibleEditors !== void 0 && delta.visibleEditors.length > 0) {
      return false;
    }
    if (delta.newActiveEditor !== void 0) {
      return false;
    }
    return true;
  }
  static r(e) {
    return {
      viewType: e.viewType,
      uri: e.uri,
      metadata: e.metadata,
      versionId: e.versionId,
      cells: e.cells.map(NotebookDto.toNotebookCellDto)
    };
  }
  s(add) {
    const pane = this.j.visibleEditorPanes.find((pane2) => $Qrb(pane2) === add);
    return {
      id: add.getId(),
      documentUri: add.textModel.uri,
      selections: add.getSelections(),
      visibleRanges: add.visibleRanges,
      viewColumn: pane && $AS(this.k, pane.group),
      viewType: add.getViewModel().viewType
    };
  }
};
$ISb = $ISb_1 = __decorate([
  $grb,
  __param(1, $Pk),
  __param(2, $mrb),
  __param(3, $yMb),
  __param(4, $mJ),
  __param(5, $iJ),
  __param(6, $wn)
], $ISb);

// out-build/vs/workbench/contrib/notebook/common/notebookRendererMessagingService.js
var $CJb = $Qk("INotebookRendererMessagingService");

// out-build/vs/workbench/api/browser/mainThreadNotebookRenderers.js
var $JSb = class $JSb2 extends $3c {
  constructor(extHostContext, b) {
    super();
    this.b = b;
    this.a = extHostContext.getProxy($yT.ExtHostNotebookRenderers);
    this.B(b.onShouldPostMessage((e) => {
      this.a.$postRendererMessage(e.editorId, e.rendererId, e.message);
    }));
  }
  $postMessage(editorId, rendererId, message) {
    return this.b.receiveMessage(editorId, rendererId, message);
  }
};
$JSb = __decorate([
  $frb($xT.MainThreadNotebookRenderers),
  __param(1, $CJb)
], $JSb);

// out-build/vs/workbench/contrib/notebook/common/notebookSynchronizerService.js
var $PSb = $Qk("notebookSynchronizerService");

// out-build/vs/workbench/contrib/notebook/common/notebookEditorModel.js
var $QSb_1;
var $QSb = $QSb_1 = class $QSb2 extends $rG {
  constructor(resource, s, viewType, t, scratchpad, u, w) {
    super();
    this.resource = resource;
    this.s = s;
    this.viewType = viewType;
    this.t = t;
    this.u = u;
    this.w = w;
    this.a = this.B(new $ze());
    this.b = this.B(new $ze());
    this.c = this.B(new $ze());
    this.g = this.B(new $ze());
    this.j = this.B(new $ze());
    this.onDidChangeDirty = this.a.event;
    this.onDidSave = this.b.event;
    this.onDidChangeOrphaned = this.c.event;
    this.onDidChangeReadonly = this.g.event;
    this.onDidRevertUntitled = this.j.event;
    this.n = this.B(new $2c());
    this.r = scratchpad;
  }
  dispose() {
    this.m?.dispose();
    super.dispose();
  }
  get notebook() {
    return this.m?.model?.notebookModel;
  }
  isResolved() {
    return Boolean(this.m?.model?.notebookModel);
  }
  async canDispose() {
    if (!this.m) {
      return true;
    }
    if ($QSb_1.y(this.m)) {
      return this.t.stored.canDispose(this.m);
    } else {
      return true;
    }
  }
  isDirty() {
    return this.m?.isDirty() ?? false;
  }
  isModified() {
    return this.m?.isModified() ?? false;
  }
  isOrphaned() {
    return $QSb_1.y(this.m) && this.m.hasState(
      4
      /* StoredFileWorkingCopyState.ORPHAN */
    );
  }
  hasAssociatedFilePath() {
    return !$QSb_1.y(this.m) && !!this.m?.hasAssociatedFilePath;
  }
  isReadonly() {
    if ($QSb_1.y(this.m)) {
      return this.m?.isReadonly();
    } else {
      return this.u.isReadonly(this.resource);
    }
  }
  get hasErrorState() {
    if (this.m && "hasState" in this.m) {
      return this.m.hasState(
        5
        /* StoredFileWorkingCopyState.ERROR */
      );
    }
    return false;
  }
  async revert(options3) {
    $Jg(this.isResolved());
    if (this.m) {
      await this.w.revert(this.m);
    }
    return this.m.revert(options3);
  }
  async save(options3) {
    $Jg(this.isResolved());
    return this.m.save(options3);
  }
  async load(options3) {
    if (!this.m || !this.m.model) {
      if (this.resource.scheme === Schemas.untitled) {
        if (this.s) {
          this.m = await this.t.resolve({ associatedResource: this.resource });
        } else {
          this.m = await this.t.resolve({ untitledResource: this.resource, isScratchpad: this.r });
        }
        this.m.onDidRevert(() => this.j.fire());
      } else {
        this.m = await this.t.resolve(this.resource, {
          limits: options3?.limits,
          reload: options3?.forceReadFromFile ? { async: false, force: true } : void 0
        });
        this.n.add(this.m.onDidSave((e) => this.b.fire(e)));
        this.n.add(this.m.onDidChangeOrphaned(() => this.c.fire()));
        this.n.add(this.m.onDidChangeReadonly(() => this.g.fire()));
      }
      this.n.add(this.m.onDidChangeDirty(() => this.a.fire(), void 0));
      this.n.add(this.m.onWillDispose(() => {
        this.n.clear();
        this.m?.model?.dispose();
      }));
    } else {
      await this.t.resolve(this.resource, {
        reload: {
          async: !options3?.forceReadFromFile,
          force: options3?.forceReadFromFile
        },
        limits: options3?.limits
      });
    }
    $Jg(this.isResolved());
    return this;
  }
  async saveAs(target) {
    const newWorkingCopy = await this.t.saveAs(this.resource, target);
    if (!newWorkingCopy) {
      return void 0;
    }
    return { resource: newWorkingCopy.resource };
  }
  static y(candidate) {
    const isUntitled = candidate && candidate.capabilities & 2;
    return !isUntitled;
  }
};
$QSb = $QSb_1 = __decorate([
  __param(5, $4J),
  __param(6, $PSb)
], $QSb);
var $RSb = class extends $3c {
  constructor(b, c, f, g, h3) {
    super();
    this.b = b;
    this.c = c;
    this.f = f;
    this.g = g;
    this.h = h3;
    this.a = this.B(new $ze());
    this.onDidChangeContent = this.a.event;
    this.configuration = void 0;
    this.onWillDispose = b.onWillDispose.bind(b);
    this.B(b.onDidChangeContent((e) => {
      for (const rawEvent of e.rawEvents) {
        if (rawEvent.kind === NotebookCellsChangeType.Initialize) {
          continue;
        }
        if (rawEvent.transient) {
          continue;
        }
        this.a.fire({
          isRedoing: false,
          //todo@rebornix forward this information from notebook model
          isUndoing: false,
          isInitial: false
          //_notebookModel.cells.length === 0 // todo@jrieken non transient metadata?
        });
        break;
      }
    }));
    const saveWithReducedCommunication = this.f.getValue($rM.remoteSaving);
    if (saveWithReducedCommunication || b.uri.scheme === Schemas.vscodeRemote) {
      this.configuration = {
        // Intentionally pick a larger delay for triggering backups to allow auto-save
        // to complete first on the optimized save path
        backupDelay: 1e4
      };
    }
    if (saveWithReducedCommunication) {
      this.j().catch(console.error);
    }
  }
  async j() {
    await this.getNotebookSerializer();
    this.save = async (options3, token) => {
      try {
        let serializer = this.c.tryGetDataProviderSync(this.notebookModel.viewType)?.serializer;
        if (!serializer) {
          this.h.info("WorkingCopyModel", "No serializer found for notebook model, checking if provider still needs to be resolved");
          serializer = await this.getNotebookSerializer();
        }
        if (token.isCancellationRequested) {
          throw new $lb();
        }
        const stat = await serializer.save(this.b.uri, this.b.versionId, options3, token);
        return stat;
      } catch (error) {
        if (!token.isCancellationRequested) {
          const isIPynb = this.b.viewType === "jupyter-notebook" || this.b.viewType === "interactive";
          this.g.publicLogError2("notebook/SaveError", {
            isRemote: this.b.uri.scheme === Schemas.vscodeRemote,
            isIPyNbWorkerSerializer: isIPynb && this.f.getValue("ipynb.experimental.serialization"),
            error
          });
        }
        throw error;
      }
    };
  }
  dispose() {
    this.b.dispose();
    super.dispose();
  }
  get notebookModel() {
    return this.b;
  }
  async snapshot(context, token) {
    return this.c.createNotebookTextDocumentSnapshot(this.b.uri, context, token);
  }
  async update(stream, token) {
    const serializer = await this.getNotebookSerializer();
    const bytes = await $Oi(stream);
    const data = await serializer.dataToNotebook(bytes);
    if (token.isCancellationRequested) {
      throw new $lb();
    }
    this.h.info("WorkingCopyModel", "Notebook content updated from file system - " + this.b.uri.toString());
    this.b.reset(data.cells, data.metadata, serializer.options);
  }
  async getNotebookSerializer() {
    const info = await this.c.withNotebookDataProvider(this.notebookModel.viewType);
    if (!(info instanceof $nrb)) {
      throw new Error("CANNOT open file notebook with this provider");
    }
    return info.serializer;
  }
  get versionId() {
    return this.b.alternativeVersionId;
  }
  pushStackElement() {
    this.b.pushStackElement();
  }
};
var $SSb = class $SSb2 {
  constructor(a, b, c, d, f) {
    this.a = a;
    this.b = b;
    this.c = c;
    this.d = d;
    this.f = f;
  }
  async createModel(resource, stream, token) {
    const notebookModel = this.b.getNotebookTextModel(resource) ?? await this.b.createNotebookTextModel(this.a, resource, stream);
    return new $RSb(notebookModel, this.b, this.c, this.d, this.f);
  }
};
$SSb = __decorate([
  __param(1, $mrb),
  __param(2, $kl),
  __param(3, $zv),
  __param(4, $qFb)
], $SSb);

// out-build/vs/workbench/api/browser/mainThreadNotebookSaveParticipant.js
var ExtHostNotebookDocumentSaveParticipant = class {
  constructor(extHostContext) {
    this.a = extHostContext.getProxy($yT.ExtHostNotebookDocumentSaveParticipant);
  }
  async participate(workingCopy, context, _progress, token) {
    if (!workingCopy.model || !(workingCopy.model instanceof $RSb)) {
      return void 0;
    }
    let _warningTimeout;
    const p = new Promise((resolve, reject) => {
      _warningTimeout = setTimeout(() => reject(new Error(localize(2620, null))), 1750);
      this.a.$participateInSave(workingCopy.resource, context.reason, token).then((_) => {
        clearTimeout(_warningTimeout);
        return void 0;
      }).then(resolve, reject);
    });
    return $Jh(p, token);
  }
};
var $TSb = class $TSb2 {
  constructor(extHostContext, instantiationService, b) {
    this.b = b;
    this.a = this.b.addSaveParticipant(instantiationService.createInstance(ExtHostNotebookDocumentSaveParticipant, extHostContext));
  }
  dispose() {
    this.a.dispose();
  }
};
$TSb = __decorate([
  $grb,
  __param(1, $Pk),
  __param(2, $aK)
], $TSb);

// out-build/vs/workbench/api/browser/mainThreadInteractive.js
var $USb = class $USb2 {
  constructor(extHostContext, interactiveDocumentService) {
    this.b = new $2c();
    this.a = extHostContext.getProxy($yT.ExtHostInteractive);
    this.b.add(interactiveDocumentService.onWillAddInteractiveDocument((e) => {
      this.a.$willAddInteractiveDocument(e.inputUri, "\n", $KF, e.notebookUri);
    }));
    this.b.add(interactiveDocumentService.onWillRemoveInteractiveDocument((e) => {
      this.a.$willRemoveInteractiveDocument(e.inputUri, e.notebookUri);
    }));
  }
  dispose() {
    this.b.dispose();
  }
};
$USb = __decorate([
  $frb($xT.MainThreadInteractive),
  __param(1, $WOb)
], $USb);

// out-build/vs/workbench/contrib/tasks/common/taskDefinitionRegistry.js
var taskDefinitionSchema = {
  type: "object",
  additionalProperties: false,
  properties: {
    type: {
      type: "string",
      description: localize(10347, null)
    },
    required: {
      type: "array",
      items: {
        type: "string"
      }
    },
    properties: {
      type: "object",
      description: localize(10348, null),
      additionalProperties: {
        $ref: "http://json-schema.org/draft-07/schema#"
      }
    },
    when: {
      type: "string",
      markdownDescription: localize(10349, null),
      default: ""
    }
  }
};
var Configuration;
(function(Configuration2) {
  function from(value, extensionId, messageCollector) {
    if (!value) {
      return void 0;
    }
    const taskType2 = $zg(value.type) ? value.type : void 0;
    if (!taskType2 || taskType2.length === 0) {
      messageCollector.error(localize(10350, null));
      return void 0;
    }
    const required = [];
    if (Array.isArray(value.required)) {
      for (const element of value.required) {
        if ($zg(element)) {
          required.push(element);
        }
      }
    }
    return {
      extensionId: extensionId.value,
      taskType: taskType2,
      required,
      properties: value.properties ? $Lv(value.properties) : {},
      when: value.when ? $7m.deserialize(value.when) : void 0
    };
  }
  Configuration2.from = from;
})(Configuration || (Configuration = {}));
var taskDefinitionsExtPoint = $tN.registerExtensionPoint({
  extensionPoint: "taskDefinitions",
  activationEventsGenerator: (contributions, result) => {
    for (const task of contributions) {
      if (task.type) {
        result.push(`onTaskType:${task.type}`);
      }
    }
  },
  jsonSchema: {
    description: localize(10351, null),
    type: "array",
    items: taskDefinitionSchema
  }
});
var TaskDefinitionRegistryImpl = class {
  constructor() {
    this.d = new $ze();
    this.onDefinitionsChanged = this.d.event;
    this.a = /* @__PURE__ */ Object.create(null);
    this.b = new Promise((resolve, reject) => {
      taskDefinitionsExtPoint.setHandler((extensions, delta) => {
        this.c = void 0;
        try {
          for (const extension of delta.removed) {
            const taskTypes = extension.value;
            for (const taskType2 of taskTypes) {
              if (this.a && taskType2.type && this.a[taskType2.type]) {
                delete this.a[taskType2.type];
              }
            }
          }
          for (const extension of delta.added) {
            const taskTypes = extension.value;
            for (const taskType2 of taskTypes) {
              const type = Configuration.from(taskType2, extension.description.identifier, extension.collector);
              if (type) {
                this.a[type.taskType] = type;
              }
            }
          }
          if (delta.removed.length > 0 || delta.added.length > 0) {
            this.d.fire();
          }
        } catch (error) {
        }
        resolve(void 0);
      });
    });
  }
  onReady() {
    return this.b;
  }
  get(key2) {
    return this.a[key2];
  }
  all() {
    return Object.keys(this.a).map((key2) => this.a[key2]);
  }
  getJsonSchema() {
    if (this.c === void 0) {
      const schemas2 = [];
      for (const definition of this.all()) {
        const schema9 = {
          type: "object",
          additionalProperties: false
        };
        if (definition.required.length > 0) {
          schema9.required = definition.required.slice(0);
        }
        if (definition.properties !== void 0) {
          schema9.properties = $Lv(definition.properties);
        } else {
          schema9.properties = /* @__PURE__ */ Object.create(null);
        }
        schema9.properties.type = {
          type: "string",
          enum: [definition.taskType]
        };
        schemas2.push(schema9);
      }
      this.c = { oneOf: schemas2 };
    }
    return this.c;
  }
};
var $aQ = new TaskDefinitionRegistryImpl();

// out-build/vs/workbench/contrib/tasks/common/tasks.js
var $bQ = "settings";
var $cQ = new $nn("taskRunning", false, localize(10352, null));
var $dQ = localize2(10354, "Tasks");
var ShellQuoting2;
(function(ShellQuoting4) {
  ShellQuoting4[ShellQuoting4["Escape"] = 1] = "Escape";
  ShellQuoting4[ShellQuoting4["Strong"] = 2] = "Strong";
  ShellQuoting4[ShellQuoting4["Weak"] = 3] = "Weak";
})(ShellQuoting2 || (ShellQuoting2 = {}));
var $eQ = "$customized";
(function(ShellQuoting4) {
  function from(value) {
    if (!value) {
      return ShellQuoting4.Strong;
    }
    switch (value.toLowerCase()) {
      case "escape":
        return ShellQuoting4.Escape;
      case "strong":
        return ShellQuoting4.Strong;
      case "weak":
        return ShellQuoting4.Weak;
      default:
        return ShellQuoting4.Strong;
    }
  }
  ShellQuoting4.from = from;
})(ShellQuoting2 || (ShellQuoting2 = {}));
var CommandOptions;
(function(CommandOptions3) {
  CommandOptions3.defaults = { cwd: "${workspaceFolder}" };
})(CommandOptions || (CommandOptions = {}));
var RevealKind;
(function(RevealKind2) {
  RevealKind2[RevealKind2["Always"] = 1] = "Always";
  RevealKind2[RevealKind2["Silent"] = 2] = "Silent";
  RevealKind2[RevealKind2["Never"] = 3] = "Never";
})(RevealKind || (RevealKind = {}));
(function(RevealKind2) {
  function fromString(value) {
    switch (value.toLowerCase()) {
      case "always":
        return RevealKind2.Always;
      case "silent":
        return RevealKind2.Silent;
      case "never":
        return RevealKind2.Never;
      default:
        return RevealKind2.Always;
    }
  }
  RevealKind2.fromString = fromString;
})(RevealKind || (RevealKind = {}));
var RevealProblemKind;
(function(RevealProblemKind2) {
  RevealProblemKind2[RevealProblemKind2["Never"] = 1] = "Never";
  RevealProblemKind2[RevealProblemKind2["OnProblem"] = 2] = "OnProblem";
  RevealProblemKind2[RevealProblemKind2["Always"] = 3] = "Always";
})(RevealProblemKind || (RevealProblemKind = {}));
(function(RevealProblemKind2) {
  function fromString(value) {
    switch (value.toLowerCase()) {
      case "always":
        return RevealProblemKind2.Always;
      case "never":
        return RevealProblemKind2.Never;
      case "onproblem":
        return RevealProblemKind2.OnProblem;
      default:
        return RevealProblemKind2.OnProblem;
    }
  }
  RevealProblemKind2.fromString = fromString;
})(RevealProblemKind || (RevealProblemKind = {}));
var PanelKind;
(function(PanelKind2) {
  PanelKind2[PanelKind2["Shared"] = 1] = "Shared";
  PanelKind2[PanelKind2["Dedicated"] = 2] = "Dedicated";
  PanelKind2[PanelKind2["New"] = 3] = "New";
})(PanelKind || (PanelKind = {}));
(function(PanelKind2) {
  function fromString(value) {
    switch (value.toLowerCase()) {
      case "shared":
        return PanelKind2.Shared;
      case "dedicated":
        return PanelKind2.Dedicated;
      case "new":
        return PanelKind2.New;
      default:
        return PanelKind2.Shared;
    }
  }
  PanelKind2.fromString = fromString;
})(PanelKind || (PanelKind = {}));
var PresentationOptions;
(function(PresentationOptions2) {
  PresentationOptions2.defaults = {
    echo: true,
    reveal: RevealKind.Always,
    revealProblems: RevealProblemKind.Never,
    focus: false,
    panel: PanelKind.Shared,
    showReuseMessage: true,
    clear: false
  };
})(PresentationOptions || (PresentationOptions = {}));
var RuntimeType;
(function(RuntimeType2) {
  RuntimeType2[RuntimeType2["Shell"] = 1] = "Shell";
  RuntimeType2[RuntimeType2["Process"] = 2] = "Process";
  RuntimeType2[RuntimeType2["CustomExecution"] = 3] = "CustomExecution";
})(RuntimeType || (RuntimeType = {}));
(function(RuntimeType2) {
  function fromString(value) {
    switch (value.toLowerCase()) {
      case "shell":
        return RuntimeType2.Shell;
      case "process":
        return RuntimeType2.Process;
      case "customExecution":
        return RuntimeType2.CustomExecution;
      default:
        return RuntimeType2.Process;
    }
  }
  RuntimeType2.fromString = fromString;
  function toString(value) {
    switch (value) {
      case RuntimeType2.Shell:
        return "shell";
      case RuntimeType2.Process:
        return "process";
      case RuntimeType2.CustomExecution:
        return "customExecution";
      default:
        return "process";
    }
  }
  RuntimeType2.toString = toString;
})(RuntimeType || (RuntimeType = {}));
var CommandString;
(function(CommandString3) {
  function value(value2) {
    if ($zg(value2)) {
      return value2;
    } else {
      return value2.value;
    }
  }
  CommandString3.value = value;
})(CommandString || (CommandString = {}));
var TaskGroup;
(function(TaskGroup2) {
  TaskGroup2.Clean = { _id: "clean", isDefault: false };
  TaskGroup2.Build = { _id: "build", isDefault: false };
  TaskGroup2.Rebuild = { _id: "rebuild", isDefault: false };
  TaskGroup2.Test = { _id: "test", isDefault: false };
  function is(value) {
    return value === TaskGroup2.Clean._id || value === TaskGroup2.Build._id || value === TaskGroup2.Rebuild._id || value === TaskGroup2.Test._id;
  }
  TaskGroup2.is = is;
  function from(value) {
    if (value === void 0) {
      return void 0;
    } else if ($zg(value)) {
      if (is(value)) {
        return { _id: value, isDefault: false };
      }
      return void 0;
    } else {
      return value;
    }
  }
  TaskGroup2.from = from;
})(TaskGroup || (TaskGroup = {}));
var TaskScope2;
(function(TaskScope3) {
  TaskScope3[TaskScope3["Global"] = 1] = "Global";
  TaskScope3[TaskScope3["Workspace"] = 2] = "Workspace";
  TaskScope3[TaskScope3["Folder"] = 3] = "Folder";
})(TaskScope2 || (TaskScope2 = {}));
var TaskSourceKind;
(function(TaskSourceKind2) {
  TaskSourceKind2.Workspace = "workspace";
  TaskSourceKind2.Extension = "extension";
  TaskSourceKind2.InMemory = "inMemory";
  TaskSourceKind2.WorkspaceFile = "workspaceFile";
  TaskSourceKind2.User = "user";
  function toConfigurationTarget(kind) {
    switch (kind) {
      case TaskSourceKind2.User:
        return 2;
      case TaskSourceKind2.WorkspaceFile:
        return 5;
      default:
        return 6;
    }
  }
  TaskSourceKind2.toConfigurationTarget = toConfigurationTarget;
})(TaskSourceKind || (TaskSourceKind = {}));
var DependsOrder;
(function(DependsOrder3) {
  DependsOrder3["parallel"] = "parallel";
  DependsOrder3["sequence"] = "sequence";
})(DependsOrder || (DependsOrder = {}));
var RunOnOptions;
(function(RunOnOptions3) {
  RunOnOptions3[RunOnOptions3["default"] = 1] = "default";
  RunOnOptions3[RunOnOptions3["folderOpen"] = 2] = "folderOpen";
})(RunOnOptions || (RunOnOptions = {}));
var RunOptions;
(function(RunOptions3) {
  RunOptions3.defaults = { reevaluateOnRerun: true, runOn: RunOnOptions.default, instanceLimit: 1 };
})(RunOptions || (RunOptions = {}));
var $fQ = class {
  constructor(id2, label3, type, runOptions2, configurationProperties, source) {
    this._label = "";
    this._id = id2;
    if (label3) {
      this._label = label3;
    }
    if (type) {
      this.type = type;
    }
    this.runOptions = runOptions2;
    this.configurationProperties = configurationProperties;
    this._source = source;
  }
  getDefinition(useSource) {
    return void 0;
  }
  getMapKey() {
    return this._id;
  }
  getKey() {
    return void 0;
  }
  getCommonTaskId() {
    const key2 = { folder: this.d(), id: this._id };
    return JSON.stringify(key2);
  }
  clone() {
    return this.f(Object.assign({}, this));
  }
  getWorkspaceFolder() {
    return void 0;
  }
  getWorkspaceFileName() {
    return void 0;
  }
  getTelemetryKind() {
    return "unknown";
  }
  matches(key2, compareId = false) {
    if (key2 === void 0) {
      return false;
    }
    if ($zg(key2)) {
      return key2 === this._label || key2 === this.configurationProperties.identifier || compareId && key2 === this._id;
    }
    const identifier2 = this.getDefinition(true);
    return identifier2 !== void 0 && identifier2._key === key2._key;
  }
  getQualifiedLabel() {
    const workspaceFolder = this.getWorkspaceFolder();
    if (workspaceFolder) {
      return `${this._label} (${workspaceFolder.name})`;
    } else {
      return this._label;
    }
  }
  getTaskExecution() {
    const result = {
      id: this._id,
      task: this
    };
    return result;
  }
  addTaskLoadMessages(messages) {
    if (this.c === void 0) {
      this.c = [];
    }
    if (messages) {
      this.c = this.c.concat(messages);
    }
  }
  get taskLoadMessages() {
    return this.c;
  }
};
var $gQ = class _$gQ extends $fQ {
  constructor(id2, source, label3, type, command4, hasDefinedMatchers, runOptions2, configurationProperties) {
    super(id2, label3, void 0, runOptions2, configurationProperties, source);
    this.command = {};
    this._source = source;
    this.hasDefinedMatchers = hasDefinedMatchers;
    if (command4) {
      this.command = command4;
    }
  }
  clone() {
    return new _$gQ(this._id, this._source, this._label, this.type, this.command, this.hasDefinedMatchers, this.runOptions, this.configurationProperties);
  }
  customizes() {
    if (this._source && this._source.customizes) {
      return this._source.customizes;
    }
    return void 0;
  }
  getDefinition(useSource = false) {
    if (useSource && this._source.customizes !== void 0) {
      return this._source.customizes;
    } else {
      let type;
      const commandRuntime = this.command ? this.command.runtime : void 0;
      switch (commandRuntime) {
        case RuntimeType.Shell:
          type = "shell";
          break;
        case RuntimeType.Process:
          type = "process";
          break;
        case RuntimeType.CustomExecution:
          type = "customExecution";
          break;
        case void 0:
          type = "$composite";
          break;
        default:
          throw new Error("Unexpected task runtime");
      }
      const result = {
        type,
        _key: this._id,
        id: this._id
      };
      return result;
    }
  }
  static is(value) {
    return value instanceof _$gQ;
  }
  getMapKey() {
    const workspaceFolder = this._source.config.workspaceFolder;
    return workspaceFolder ? `${workspaceFolder.uri.toString()}|${this._id}|${this.instance}` : `${this._id}|${this.instance}`;
  }
  d() {
    return this._source.kind === TaskSourceKind.User ? $bQ : this._source.config.workspaceFolder?.uri.toString();
  }
  getCommonTaskId() {
    return this._source.customizes ? super.getCommonTaskId() : this.getKey() ?? super.getCommonTaskId();
  }
  /**
   * @returns A key representing the task
   */
  getKey() {
    const workspaceFolder = this.d();
    if (!workspaceFolder) {
      return void 0;
    }
    let id2 = this.configurationProperties.identifier;
    if (this._source.kind !== TaskSourceKind.Workspace) {
      id2 += this._source.kind;
    }
    const key2 = { type: $eQ, folder: workspaceFolder, id: id2 };
    return JSON.stringify(key2);
  }
  getWorkspaceFolder() {
    return this._source.config.workspaceFolder;
  }
  getWorkspaceFileName() {
    return this._source.config.workspace && this._source.config.workspace.configuration ? $sh(this._source.config.workspace.configuration) : void 0;
  }
  getTelemetryKind() {
    if (this._source.customizes) {
      return "workspace>extension";
    } else {
      return "workspace";
    }
  }
  f(object) {
    return new _$gQ(object._id, object._source, object._label, object.type, object.command, object.hasDefinedMatchers, object.runOptions, object.configurationProperties);
  }
};
var $hQ = class _$hQ extends $fQ {
  constructor(id2, source, label3, type, configures, runOptions2, configurationProperties) {
    super(id2, label3, type, runOptions2, configurationProperties, source);
    this._source = source;
    this.configures = configures;
  }
  static is(value) {
    return value instanceof _$hQ;
  }
  f(object) {
    return object;
  }
  getDefinition() {
    return this.configures;
  }
  getWorkspaceFileName() {
    return this._source.config.workspace && this._source.config.workspace.configuration ? $sh(this._source.config.workspace.configuration) : void 0;
  }
  getWorkspaceFolder() {
    return this._source.config.workspaceFolder;
  }
  d() {
    return this._source.kind === TaskSourceKind.User ? $bQ : this._source.config.workspaceFolder?.uri.toString();
  }
  getKey() {
    const workspaceFolder = this.d();
    if (!workspaceFolder) {
      return void 0;
    }
    let id2 = this.configurationProperties.identifier;
    if (this._source.kind !== TaskSourceKind.Workspace) {
      id2 += this._source.kind;
    }
    const key2 = { type: $eQ, folder: workspaceFolder, id: id2 };
    return JSON.stringify(key2);
  }
};
var $iQ = class _$iQ extends $fQ {
  constructor(id2, source, label3, type, defines, command4, hasDefinedMatchers, runOptions2, configurationProperties) {
    super(id2, label3, type, runOptions2, configurationProperties, source);
    this.defines = defines;
    this.hasDefinedMatchers = hasDefinedMatchers;
    this.command = command4;
    this.icon = configurationProperties.icon;
    this.hide = configurationProperties.hide;
  }
  clone() {
    return new _$iQ(this._id, this._source, this._label, this.type, this.defines, this.command, this.hasDefinedMatchers, this.runOptions, this.configurationProperties);
  }
  getDefinition() {
    return this.defines;
  }
  static is(value) {
    return value instanceof _$iQ;
  }
  getMapKey() {
    const workspaceFolder = this._source.workspaceFolder;
    return workspaceFolder ? `${this._source.scope.toString()}|${workspaceFolder.uri.toString()}|${this._id}|${this.instance}` : `${this._source.scope.toString()}|${this._id}|${this.instance}`;
  }
  d() {
    if (this._source.scope === 3 && this._source.workspaceFolder) {
      return this._source.workspaceFolder.uri.toString();
    }
    return void 0;
  }
  getKey() {
    const key2 = { type: "contributed", scope: this._source.scope, id: this._id };
    key2.folder = this.d();
    return JSON.stringify(key2);
  }
  getWorkspaceFolder() {
    return this._source.workspaceFolder;
  }
  getTelemetryKind() {
    return "extension";
  }
  f(object) {
    return new _$iQ(object._id, object._source, object._label, object.type, object.defines, object.command, object.hasDefinedMatchers, object.runOptions, object.configurationProperties);
  }
};
var $jQ = class _$jQ extends $fQ {
  constructor(id2, source, label3, type, runOptions2, configurationProperties) {
    super(id2, label3, type, runOptions2, configurationProperties, source);
    this._source = source;
  }
  clone() {
    return new _$jQ(this._id, this._source, this._label, this.type, this.runOptions, this.configurationProperties);
  }
  static is(value) {
    return value instanceof _$jQ;
  }
  getTelemetryKind() {
    return "composite";
  }
  getMapKey() {
    return `${this._id}|${this.instance}`;
  }
  d() {
    return void 0;
  }
  f(object) {
    return new _$jQ(object._id, object._source, object._label, object.type, object.runOptions, object.configurationProperties);
  }
};
var ExecutionEngine;
(function(ExecutionEngine3) {
  ExecutionEngine3[ExecutionEngine3["Process"] = 1] = "Process";
  ExecutionEngine3[ExecutionEngine3["Terminal"] = 2] = "Terminal";
})(ExecutionEngine || (ExecutionEngine = {}));
(function(ExecutionEngine3) {
  ExecutionEngine3._default = ExecutionEngine3.Terminal;
})(ExecutionEngine || (ExecutionEngine = {}));
var JsonSchemaVersion;
(function(JsonSchemaVersion3) {
  JsonSchemaVersion3[JsonSchemaVersion3["V0_1_0"] = 1] = "V0_1_0";
  JsonSchemaVersion3[JsonSchemaVersion3["V2_0_0"] = 2] = "V2_0_0";
})(JsonSchemaVersion || (JsonSchemaVersion = {}));
var $kQ = class {
  constructor(workspaceFolders) {
    this.c = /* @__PURE__ */ new Map();
    for (let i2 = 0; i2 < workspaceFolders.length; i2++) {
      this.c.set(workspaceFolders[i2].uri.toString(), i2);
    }
  }
  compare(a, b) {
    const aw = a.getWorkspaceFolder();
    const bw = b.getWorkspaceFolder();
    if (aw && bw) {
      let ai = this.c.get(aw.uri.toString());
      ai = ai === void 0 ? 0 : ai + 1;
      let bi = this.c.get(bw.uri.toString());
      bi = bi === void 0 ? 0 : bi + 1;
      if (ai === bi) {
        return a._label.localeCompare(b._label);
      } else {
        return ai - bi;
      }
    } else if (!aw && bw) {
      return -1;
    } else if (aw && !bw) {
      return 1;
    } else {
      return 0;
    }
  }
};
var TaskEventKind;
(function(TaskEventKind2) {
  TaskEventKind2["DependsOnStarted"] = "dependsOnStarted";
  TaskEventKind2["AcquiredInput"] = "acquiredInput";
  TaskEventKind2["Start"] = "start";
  TaskEventKind2["ProcessStarted"] = "processStarted";
  TaskEventKind2["Active"] = "active";
  TaskEventKind2["Inactive"] = "inactive";
  TaskEventKind2["Changed"] = "changed";
  TaskEventKind2["Terminated"] = "terminated";
  TaskEventKind2["ProcessEnded"] = "processEnded";
  TaskEventKind2["End"] = "end";
})(TaskEventKind || (TaskEventKind = {}));
var TaskRunType;
(function(TaskRunType2) {
  TaskRunType2["SingleRun"] = "singleRun";
  TaskRunType2["Background"] = "background";
})(TaskRunType || (TaskRunType = {}));
var TaskRunSource;
(function(TaskRunSource2) {
  TaskRunSource2[TaskRunSource2["System"] = 0] = "System";
  TaskRunSource2[TaskRunSource2["User"] = 1] = "User";
  TaskRunSource2[TaskRunSource2["FolderOpen"] = 2] = "FolderOpen";
  TaskRunSource2[TaskRunSource2["ConfigurationChange"] = 3] = "ConfigurationChange";
  TaskRunSource2[TaskRunSource2["Reconnect"] = 4] = "Reconnect";
})(TaskRunSource || (TaskRunSource = {}));
var TaskEvent;
(function(TaskEvent2) {
  function common(task) {
    return {
      taskId: task._id,
      taskName: task.configurationProperties.name,
      runType: task.configurationProperties.isBackground ? "background" : "singleRun",
      group: task.configurationProperties.group,
      __task: task
    };
  }
  function start(task, terminalId, resolvedVariables) {
    return {
      ...common(task),
      kind: "start",
      terminalId,
      resolvedVariables
    };
  }
  TaskEvent2.start = start;
  function processStarted(task, terminalId, processId) {
    return {
      ...common(task),
      kind: "processStarted",
      terminalId,
      processId
    };
  }
  TaskEvent2.processStarted = processStarted;
  function processEnded(task, terminalId, exitCode) {
    return {
      ...common(task),
      kind: "processEnded",
      terminalId,
      exitCode
    };
  }
  TaskEvent2.processEnded = processEnded;
  function terminated(task, terminalId, exitReason) {
    return {
      ...common(task),
      kind: "terminated",
      exitReason,
      terminalId
    };
  }
  TaskEvent2.terminated = terminated;
  function general(kind, task, terminalId) {
    return {
      ...common(task),
      kind,
      terminalId
    };
  }
  TaskEvent2.general = general;
  function changed() {
    return {
      kind: "changed"
      /* TaskEventKind.Changed */
    };
  }
  TaskEvent2.changed = changed;
})(TaskEvent || (TaskEvent = {}));
var KeyedTaskIdentifier;
(function(KeyedTaskIdentifier2) {
  function sortedStringify(literal) {
    const keys = Object.keys(literal).sort();
    let result = "";
    for (const key2 of keys) {
      let stringified = literal[key2];
      if (stringified instanceof Object) {
        stringified = sortedStringify(stringified);
      } else if (typeof stringified === "string") {
        stringified = stringified.replace(/,/g, ",,");
      }
      result += key2 + "," + stringified + ",";
    }
    return result;
  }
  function create2(value) {
    const resultKey = sortedStringify(value);
    const result = { _key: resultKey, type: value.taskType };
    Object.assign(result, value);
    return result;
  }
  KeyedTaskIdentifier2.create = create2;
})(KeyedTaskIdentifier || (KeyedTaskIdentifier = {}));
var TaskSettingId;
(function(TaskSettingId2) {
  TaskSettingId2["AutoDetect"] = "task.autoDetect";
  TaskSettingId2["SaveBeforeRun"] = "task.saveBeforeRun";
  TaskSettingId2["ShowDecorations"] = "task.showDecorations";
  TaskSettingId2["ProblemMatchersNeverPrompt"] = "task.problemMatchers.neverPrompt";
  TaskSettingId2["SlowProviderWarning"] = "task.slowProviderWarning";
  TaskSettingId2["QuickOpenHistory"] = "task.quickOpen.history";
  TaskSettingId2["QuickOpenDetail"] = "task.quickOpen.detail";
  TaskSettingId2["QuickOpenSkip"] = "task.quickOpen.skip";
  TaskSettingId2["QuickOpenShowAll"] = "task.quickOpen.showAll";
  TaskSettingId2["AllowAutomaticTasks"] = "task.allowAutomaticTasks";
  TaskSettingId2["Reconnection"] = "task.reconnection";
  TaskSettingId2["VerboseLogging"] = "task.verboseLogging";
})(TaskSettingId || (TaskSettingId = {}));
var TasksSchemaProperties;
(function(TasksSchemaProperties2) {
  TasksSchemaProperties2["Tasks"] = "tasks";
  TasksSchemaProperties2["SuppressTaskName"] = "tasks.suppressTaskName";
  TasksSchemaProperties2["Windows"] = "tasks.windows";
  TasksSchemaProperties2["Osx"] = "tasks.osx";
  TasksSchemaProperties2["Linux"] = "tasks.linux";
  TasksSchemaProperties2["ShowOutput"] = "tasks.showOutput";
  TasksSchemaProperties2["IsShellCommand"] = "tasks.isShellCommand";
  TasksSchemaProperties2["ServiceTestSetting"] = "tasks.service.testSetting";
})(TasksSchemaProperties || (TasksSchemaProperties = {}));
var TaskDefinition;
(function(TaskDefinition2) {
  function createTaskIdentifier(external, reporter) {
    const definition = $aQ.get(external.type);
    if (definition === void 0) {
      const copy = $Lv(external);
      delete copy._key;
      return KeyedTaskIdentifier.create(copy);
    }
    const literal = /* @__PURE__ */ Object.create(null);
    literal.type = definition.taskType;
    const required = /* @__PURE__ */ new Set();
    definition.required.forEach((element) => required.add(element));
    const properties = definition.properties;
    for (const property of Object.keys(properties)) {
      const value = external[property];
      if (value !== void 0 && value !== null) {
        literal[property] = value;
      } else if (required.has(property)) {
        const schema9 = properties[property];
        if (schema9.default !== void 0) {
          literal[property] = $Lv(schema9.default);
        } else {
          switch (schema9.type) {
            case "boolean":
              literal[property] = false;
              break;
            case "number":
            case "integer":
              literal[property] = 0;
              break;
            case "string":
              literal[property] = "";
              break;
            default:
              reporter.error(localize(10353, null, JSON.stringify(external, void 0, 0), property));
              return void 0;
          }
        }
      }
    }
    return KeyedTaskIdentifier.create(literal);
  }
  TaskDefinition2.createTaskIdentifier = createTaskIdentifier;
})(TaskDefinition || (TaskDefinition = {}));

// out-build/vs/workbench/contrib/tasks/common/taskService.js
var $WSb = new $nn("customExecutionSupported", false, localize(10355, null));
var $XSb = new $nn("shellExecutionSupported", false, localize(10356, null));
var $YSb = new $nn("taskCommandsRegistered", false, localize(10357, null));
var $ZSb = new $nn("processExecutionSupported", false, localize(10358, null));
var $1Sb = new $nn("serverlessWebContext", false, localize(10359, null));
var $2Sb = $7m.or($7m.and($XSb, $ZSb), $WSb);
var $3Sb = $Qk("taskService");

// out-build/vs/workbench/services/configurationResolver/common/configurationResolver.js
var $nY = $Qk("configurationResolverService");
var VariableKind;
(function(VariableKind2) {
  VariableKind2["Unknown"] = "unknown";
  VariableKind2["Env"] = "env";
  VariableKind2["Config"] = "config";
  VariableKind2["Command"] = "command";
  VariableKind2["Input"] = "input";
  VariableKind2["ExtensionInstallFolder"] = "extensionInstallFolder";
  VariableKind2["WorkspaceFolder"] = "workspaceFolder";
  VariableKind2["Cwd"] = "cwd";
  VariableKind2["WorkspaceFolderBasename"] = "workspaceFolderBasename";
  VariableKind2["UserHome"] = "userHome";
  VariableKind2["LineNumber"] = "lineNumber";
  VariableKind2["SelectedText"] = "selectedText";
  VariableKind2["File"] = "file";
  VariableKind2["FileWorkspaceFolder"] = "fileWorkspaceFolder";
  VariableKind2["FileWorkspaceFolderBasename"] = "fileWorkspaceFolderBasename";
  VariableKind2["RelativeFile"] = "relativeFile";
  VariableKind2["RelativeFileDirname"] = "relativeFileDirname";
  VariableKind2["FileDirname"] = "fileDirname";
  VariableKind2["FileExtname"] = "fileExtname";
  VariableKind2["FileBasename"] = "fileBasename";
  VariableKind2["FileBasenameNoExtension"] = "fileBasenameNoExtension";
  VariableKind2["FileDirnameBasename"] = "fileDirnameBasename";
  VariableKind2["ExecPath"] = "execPath";
  VariableKind2["ExecInstallFolder"] = "execInstallFolder";
  VariableKind2["PathSeparator"] = "pathSeparator";
  VariableKind2["PathSeparatorAlias"] = "/";
})(VariableKind || (VariableKind = {}));
var $oY = class extends $ub {
  constructor(variable, message) {
    super(message);
    this.variable = variable;
  }
};

// out-build/vs/workbench/api/browser/mainThreadTask.js
var TaskExecutionDTO;
(function(TaskExecutionDTO2) {
  function from(value) {
    return {
      id: value.id,
      task: TaskDTO.from(value.task)
    };
  }
  TaskExecutionDTO2.from = from;
})(TaskExecutionDTO || (TaskExecutionDTO = {}));
var TaskProcessStartedDTO;
(function(TaskProcessStartedDTO2) {
  function from(value, processId) {
    return {
      id: value.id,
      processId
    };
  }
  TaskProcessStartedDTO2.from = from;
})(TaskProcessStartedDTO || (TaskProcessStartedDTO = {}));
var TaskProcessEndedDTO;
(function(TaskProcessEndedDTO2) {
  function from(value, exitCode) {
    return {
      id: value.id,
      exitCode
    };
  }
  TaskProcessEndedDTO2.from = from;
})(TaskProcessEndedDTO || (TaskProcessEndedDTO = {}));
var TaskDefinitionDTO;
(function(TaskDefinitionDTO2) {
  function from(value) {
    const result = Object.assign(/* @__PURE__ */ Object.create(null), value);
    delete result._key;
    return result;
  }
  TaskDefinitionDTO2.from = from;
  function to(value, executeOnly) {
    let result = TaskDefinition.createTaskIdentifier(value, console);
    if (result === void 0 && executeOnly) {
      result = {
        _key: $ps(),
        type: "$executeOnly"
      };
    }
    return result;
  }
  TaskDefinitionDTO2.to = to;
})(TaskDefinitionDTO || (TaskDefinitionDTO = {}));
var TaskPresentationOptionsDTO;
(function(TaskPresentationOptionsDTO2) {
  function from(value) {
    if (value === void 0 || value === null) {
      return void 0;
    }
    return Object.assign(/* @__PURE__ */ Object.create(null), value);
  }
  TaskPresentationOptionsDTO2.from = from;
  function to(value) {
    if (value === void 0 || value === null) {
      return PresentationOptions.defaults;
    }
    return Object.assign(/* @__PURE__ */ Object.create(null), PresentationOptions.defaults, value);
  }
  TaskPresentationOptionsDTO2.to = to;
})(TaskPresentationOptionsDTO || (TaskPresentationOptionsDTO = {}));
var RunOptionsDTO;
(function(RunOptionsDTO2) {
  function from(value) {
    if (value === void 0 || value === null) {
      return void 0;
    }
    return Object.assign(/* @__PURE__ */ Object.create(null), value);
  }
  RunOptionsDTO2.from = from;
  function to(value) {
    if (value === void 0 || value === null) {
      return RunOptions.defaults;
    }
    return Object.assign(/* @__PURE__ */ Object.create(null), RunOptions.defaults, value);
  }
  RunOptionsDTO2.to = to;
})(RunOptionsDTO || (RunOptionsDTO = {}));
var ProcessExecutionOptionsDTO;
(function(ProcessExecutionOptionsDTO2) {
  function from(value) {
    if (value === void 0 || value === null) {
      return void 0;
    }
    return {
      cwd: value.cwd,
      env: value.env
    };
  }
  ProcessExecutionOptionsDTO2.from = from;
  function to(value) {
    if (value === void 0 || value === null) {
      return CommandOptions.defaults;
    }
    return {
      cwd: value.cwd || CommandOptions.defaults.cwd,
      env: value.env
    };
  }
  ProcessExecutionOptionsDTO2.to = to;
})(ProcessExecutionOptionsDTO || (ProcessExecutionOptionsDTO = {}));
var ProcessExecutionDTO;
(function(ProcessExecutionDTO2) {
  function is(value) {
    const candidate = value;
    return candidate && !!candidate.process;
  }
  ProcessExecutionDTO2.is = is;
  function from(value) {
    const process2 = $zg(value.name) ? value.name : value.name.value;
    const args2 = value.args ? value.args.map((value2) => $zg(value2) ? value2 : value2.value) : [];
    const result = {
      process: process2,
      args: args2
    };
    if (value.options) {
      result.options = ProcessExecutionOptionsDTO.from(value.options);
    }
    return result;
  }
  ProcessExecutionDTO2.from = from;
  function to(value) {
    const result = {
      runtime: RuntimeType.Process,
      name: value.process,
      args: value.args,
      presentation: void 0
    };
    result.options = ProcessExecutionOptionsDTO.to(value.options);
    return result;
  }
  ProcessExecutionDTO2.to = to;
})(ProcessExecutionDTO || (ProcessExecutionDTO = {}));
var ShellExecutionOptionsDTO;
(function(ShellExecutionOptionsDTO2) {
  function from(value) {
    if (value === void 0 || value === null) {
      return void 0;
    }
    const result = {
      cwd: value.cwd || CommandOptions.defaults.cwd,
      env: value.env
    };
    if (value.shell) {
      result.executable = value.shell.executable;
      result.shellArgs = value.shell.args;
      result.shellQuoting = value.shell.quoting;
    }
    return result;
  }
  ShellExecutionOptionsDTO2.from = from;
  function to(value) {
    if (value === void 0 || value === null) {
      return void 0;
    }
    const result = {
      cwd: value.cwd,
      env: value.env
    };
    if (value.executable) {
      result.shell = {
        executable: value.executable
      };
      if (value.shellArgs) {
        result.shell.args = value.shellArgs;
      }
      if (value.shellQuoting) {
        result.shell.quoting = value.shellQuoting;
      }
    }
    return result;
  }
  ShellExecutionOptionsDTO2.to = to;
})(ShellExecutionOptionsDTO || (ShellExecutionOptionsDTO = {}));
var ShellExecutionDTO;
(function(ShellExecutionDTO2) {
  function is(value) {
    const candidate = value;
    return candidate && (!!candidate.commandLine || !!candidate.command);
  }
  ShellExecutionDTO2.is = is;
  function from(value) {
    const result = {};
    if (value.name && $zg(value.name) && (value.args === void 0 || value.args === null || value.args.length === 0)) {
      result.commandLine = value.name;
    } else {
      result.command = value.name;
      result.args = value.args;
    }
    if (value.options) {
      result.options = ShellExecutionOptionsDTO.from(value.options);
    }
    return result;
  }
  ShellExecutionDTO2.from = from;
  function to(value) {
    const result = {
      runtime: RuntimeType.Shell,
      name: value.commandLine ? value.commandLine : value.command,
      args: value.args,
      presentation: void 0
    };
    if (value.options) {
      result.options = ShellExecutionOptionsDTO.to(value.options);
    }
    return result;
  }
  ShellExecutionDTO2.to = to;
})(ShellExecutionDTO || (ShellExecutionDTO = {}));
var CustomExecutionDTO;
(function(CustomExecutionDTO2) {
  function is(value) {
    const candidate = value;
    return candidate && candidate.customExecution === "customExecution";
  }
  CustomExecutionDTO2.is = is;
  function from(value) {
    return {
      customExecution: "customExecution"
    };
  }
  CustomExecutionDTO2.from = from;
  function to(value) {
    return {
      runtime: RuntimeType.CustomExecution,
      presentation: void 0
    };
  }
  CustomExecutionDTO2.to = to;
})(CustomExecutionDTO || (CustomExecutionDTO = {}));
var TaskSourceDTO;
(function(TaskSourceDTO2) {
  function from(value) {
    const result = {
      label: value.label
    };
    if (value.kind === TaskSourceKind.Extension) {
      result.extensionId = value.extension;
      if (value.workspaceFolder) {
        result.scope = value.workspaceFolder.uri;
      } else {
        result.scope = value.scope;
      }
    } else if (value.kind === TaskSourceKind.Workspace) {
      result.extensionId = "$core";
      result.scope = value.config.workspaceFolder ? value.config.workspaceFolder.uri : 1;
    }
    return result;
  }
  TaskSourceDTO2.from = from;
  function to(value, workspace2) {
    let scope;
    let workspaceFolder;
    if (value.scope === void 0 || typeof value.scope === "number" && value.scope !== 1) {
      if (workspace2.getWorkspace().folders.length === 0) {
        scope = 1;
        workspaceFolder = void 0;
      } else {
        scope = 3;
        workspaceFolder = workspace2.getWorkspace().folders[0];
      }
    } else if (typeof value.scope === "number") {
      scope = value.scope;
    } else {
      scope = 3;
      workspaceFolder = workspace2.getWorkspaceFolder(URI.revive(value.scope)) ?? void 0;
    }
    const result = {
      kind: TaskSourceKind.Extension,
      label: value.label,
      extension: value.extensionId,
      scope,
      workspaceFolder
    };
    return result;
  }
  TaskSourceDTO2.to = to;
})(TaskSourceDTO || (TaskSourceDTO = {}));
var TaskHandleDTO;
(function(TaskHandleDTO2) {
  function is(value) {
    const candidate = value;
    return candidate && $zg(candidate.id) && !!candidate.workspaceFolder;
  }
  TaskHandleDTO2.is = is;
})(TaskHandleDTO || (TaskHandleDTO = {}));
var TaskDTO;
(function(TaskDTO2) {
  function from(task) {
    if (task === void 0 || task === null || !$gQ.is(task) && !$iQ.is(task) && !$hQ.is(task)) {
      return void 0;
    }
    const result = {
      _id: task._id,
      name: task.configurationProperties.name,
      definition: TaskDefinitionDTO.from(task.getDefinition(true)),
      source: TaskSourceDTO.from(task._source),
      execution: void 0,
      presentationOptions: !$hQ.is(task) && task.command ? TaskPresentationOptionsDTO.from(task.command.presentation) : void 0,
      isBackground: task.configurationProperties.isBackground,
      problemMatchers: [],
      hasDefinedMatchers: $iQ.is(task) ? task.hasDefinedMatchers : false,
      runOptions: RunOptionsDTO.from(task.runOptions)
    };
    result.group = TaskGroupDTO.from(task.configurationProperties.group);
    if (task.configurationProperties.detail) {
      result.detail = task.configurationProperties.detail;
    }
    if (!$hQ.is(task) && task.command) {
      switch (task.command.runtime) {
        case RuntimeType.Process:
          result.execution = ProcessExecutionDTO.from(task.command);
          break;
        case RuntimeType.Shell:
          result.execution = ShellExecutionDTO.from(task.command);
          break;
        case RuntimeType.CustomExecution:
          result.execution = CustomExecutionDTO.from(task.command);
          break;
      }
    }
    if (task.configurationProperties.problemMatchers) {
      for (const matcher of task.configurationProperties.problemMatchers) {
        if ($zg(matcher)) {
          result.problemMatchers.push(matcher);
        }
      }
    }
    return result;
  }
  TaskDTO2.from = from;
  function to(task, workspace2, executeOnly, icon2, hide3) {
    if (!task || typeof task.name !== "string") {
      return void 0;
    }
    let command4;
    if (task.execution) {
      if (ShellExecutionDTO.is(task.execution)) {
        command4 = ShellExecutionDTO.to(task.execution);
      } else if (ProcessExecutionDTO.is(task.execution)) {
        command4 = ProcessExecutionDTO.to(task.execution);
      } else if (CustomExecutionDTO.is(task.execution)) {
        command4 = CustomExecutionDTO.to(task.execution);
      }
    }
    if (!command4) {
      return void 0;
    }
    command4.presentation = TaskPresentationOptionsDTO.to(task.presentationOptions);
    const source = TaskSourceDTO.to(task.source, workspace2);
    const label3 = localize(2626, null, source.label, task.name);
    const definition = TaskDefinitionDTO.to(task.definition, executeOnly);
    const id2 = CustomExecutionDTO.is(task.execution) && task._id ? task._id : `${task.source.extensionId}.${definition._key}`;
    const result = new $iQ(
      id2,
      // uuidMap.getUUID(identifier)
      source,
      label3,
      definition.type,
      definition,
      command4,
      task.hasDefinedMatchers,
      RunOptionsDTO.to(task.runOptions),
      {
        name: task.name,
        identifier: label3,
        group: task.group,
        isBackground: !!task.isBackground,
        problemMatchers: task.problemMatchers.slice(),
        detail: task.detail,
        icon: icon2,
        hide: hide3
      }
    );
    return result;
  }
  TaskDTO2.to = to;
})(TaskDTO || (TaskDTO = {}));
var TaskGroupDTO;
(function(TaskGroupDTO2) {
  function from(value) {
    if (value === void 0) {
      return void 0;
    }
    return {
      _id: typeof value === "string" ? value : value._id,
      isDefault: typeof value === "string" ? false : typeof value.isDefault === "string" ? false : value.isDefault
    };
  }
  TaskGroupDTO2.from = from;
})(TaskGroupDTO || (TaskGroupDTO = {}));
var TaskFilterDTO;
(function(TaskFilterDTO2) {
  function from(value) {
    return value;
  }
  TaskFilterDTO2.from = from;
  function to(value) {
    return value;
  }
  TaskFilterDTO2.to = to;
})(TaskFilterDTO || (TaskFilterDTO = {}));
var $4Sb = class $4Sb2 extends $3c {
  constructor(extHostContext, f, g, h3) {
    super();
    this.f = f;
    this.g = g;
    this.h = h3;
    this.b = extHostContext.getProxy($yT.ExtHostTask);
    this.c = /* @__PURE__ */ new Map();
    this.B(this.f.onDidStateChange(async (event) => {
      if (event.kind === "changed") {
        return;
      }
      const task = event.__task;
      if (event.kind === "start") {
        const execution = TaskExecutionDTO.from(task.getTaskExecution());
        let resolvedDefinition = execution.task.definition;
        if (execution.task?.execution && CustomExecutionDTO.is(execution.task.execution) && event.resolvedVariables) {
          const dictionary = {};
          for (const [key2, value] of event.resolvedVariables.entries()) {
            dictionary[key2] = value;
          }
          resolvedDefinition = await this.h.resolveAnyAsync(task.getWorkspaceFolder(), execution.task.definition, dictionary);
        }
        this.b.$onDidStartTask(execution, event.terminalId, resolvedDefinition);
      } else if (event.kind === "processStarted") {
        this.b.$onDidStartTaskProcess(TaskProcessStartedDTO.from(task.getTaskExecution(), event.processId));
      } else if (event.kind === "processEnded") {
        this.b.$onDidEndTaskProcess(TaskProcessEndedDTO.from(task.getTaskExecution(), event.exitCode));
      } else if (event.kind === "end") {
        this.b.$OnDidEndTask(TaskExecutionDTO.from(task.getTaskExecution()));
      }
    }));
  }
  dispose() {
    for (const value of this.c.values()) {
      value.disposable.dispose();
    }
    this.c.clear();
    super.dispose();
  }
  $createTaskId(taskDTO) {
    return new Promise((resolve, reject) => {
      const task = TaskDTO.to(taskDTO, this.g, true);
      if (task) {
        resolve(task._id);
      } else {
        reject(new Error("Task could not be created from DTO"));
      }
    });
  }
  $registerTaskProvider(handle2, type) {
    const provider = {
      provideTasks: (validTypes) => {
        return Promise.resolve(this.b.$provideTasks(handle2, validTypes)).then((value) => {
          const tasks2 = [];
          for (const dto of value.tasks) {
            const task = TaskDTO.to(dto, this.g, true);
            if (task) {
              tasks2.push(task);
            } else {
              console.error(`Task System: can not convert task: ${JSON.stringify(dto.definition, void 0, 0)}. Task will be dropped`);
            }
          }
          const processedExtension = {
            ...value.extension,
            extensionLocation: URI.revive(value.extension.extensionLocation)
          };
          return {
            tasks: tasks2,
            extension: processedExtension
          };
        });
      },
      resolveTask: (task) => {
        const dto = TaskDTO.from(task);
        if (dto) {
          dto.name = dto.name === void 0 ? "" : dto.name;
          return Promise.resolve(this.b.$resolveTask(handle2, dto)).then((resolvedTask) => {
            if (resolvedTask) {
              return TaskDTO.to(resolvedTask, this.g, true, task.configurationProperties.icon, task.configurationProperties.hide);
            }
            return void 0;
          });
        }
        return Promise.resolve(void 0);
      }
    };
    const disposable = this.f.registerTaskProvider(provider, type);
    this.c.set(handle2, { disposable, provider });
    return Promise.resolve(void 0);
  }
  $unregisterTaskProvider(handle2) {
    const provider = this.c.get(handle2);
    if (provider) {
      provider.disposable.dispose();
      this.c.delete(handle2);
    }
    return Promise.resolve(void 0);
  }
  $fetchTasks(filter) {
    return this.f.tasks(TaskFilterDTO.to(filter)).then((tasks2) => {
      const result = [];
      for (const task of tasks2) {
        const item = TaskDTO.from(task);
        if (item) {
          result.push(item);
        }
      }
      return result;
    });
  }
  j(value) {
    let workspace2;
    if (typeof value === "string") {
      workspace2 = value;
    } else {
      const workspaceObject = this.g.getWorkspace();
      const uri = URI.revive(value);
      if (workspaceObject.configuration?.toString() === uri.toString()) {
        workspace2 = workspaceObject;
      } else {
        workspace2 = this.g.getWorkspaceFolder(uri);
      }
    }
    return workspace2;
  }
  async $getTaskExecution(value) {
    if (TaskHandleDTO.is(value)) {
      const workspace2 = this.j(value.workspaceFolder);
      if (workspace2) {
        const task = await this.f.getTask(workspace2, value.id, true);
        if (task) {
          return {
            id: task._id,
            task: TaskDTO.from(task)
          };
        }
        throw new Error("Task not found");
      } else {
        throw new Error("No workspace folder");
      }
    } else {
      const task = TaskDTO.to(value, this.g, true);
      return {
        id: task._id,
        task: TaskDTO.from(task)
      };
    }
  }
  // Passing in a TaskHandleDTO will cause the task to get re-resolved, which is important for tasks are coming from the core,
  // such as those gotten from a fetchTasks, since they can have missing configuration properties.
  $executeTask(value) {
    return new Promise((resolve, reject) => {
      if (TaskHandleDTO.is(value)) {
        const workspace2 = this.j(value.workspaceFolder);
        if (workspace2) {
          this.f.getTask(workspace2, value.id, true).then((task) => {
            if (!task) {
              reject(new Error("Task not found"));
            } else {
              const result = {
                id: value.id,
                task: TaskDTO.from(task)
              };
              this.f.run(task).then((summary) => {
                if (summary?.exitCode === void 0 || summary.exitCode !== 0) {
                  this.b.$OnDidEndTask(result);
                }
              }, (reason) => {
              });
              resolve(result);
            }
          }, (_error) => {
            reject(new Error("Task not found"));
          });
        } else {
          reject(new Error("No workspace folder"));
        }
      } else {
        const task = TaskDTO.to(value, this.g, true);
        this.f.run(task).then(void 0, (reason) => {
        });
        const result = {
          id: task._id,
          task: TaskDTO.from(task)
        };
        resolve(result);
      }
    });
  }
  $customExecutionComplete(id2, result) {
    return new Promise((resolve, reject) => {
      this.f.getActiveTasks().then((tasks2) => {
        for (const task of tasks2) {
          if (id2 === task._id) {
            this.f.extensionCallbackTaskComplete(task, result).then((value) => {
              resolve(void 0);
            }, (error) => {
              reject(error);
            });
            return;
          }
        }
        reject(new Error("Task to mark as complete not found"));
      });
    });
  }
  $terminateTask(id2) {
    return new Promise((resolve, reject) => {
      this.f.getActiveTasks().then((tasks2) => {
        for (const task of tasks2) {
          if (id2 === task._id) {
            this.f.terminate(task).then((value) => {
              resolve(void 0);
            }, (error) => {
              reject(void 0);
            });
            return;
          }
        }
        reject(new $ub("Task to terminate not found"));
      });
    });
  }
  $registerTaskSystem(key2, info) {
    let platform;
    switch (info.platform) {
      case "Web":
        platform = 0;
        break;
      case "win32":
        platform = 3;
        break;
      case "darwin":
        platform = 1;
        break;
      case "linux":
        platform = 2;
        break;
      default:
        platform = $x;
    }
    this.f.registerTaskSystem(key2, {
      platform,
      uriProvider: (path) => {
        return URI.from({ scheme: info.scheme, authority: info.authority, path });
      },
      context: this.a,
      resolveVariables: (workspaceFolder, toResolve, target) => {
        const vars = [];
        toResolve.variables.forEach((item) => vars.push(item));
        return Promise.resolve(this.b.$resolveVariables(workspaceFolder.uri, { process: toResolve.process, variables: vars })).then((values) => {
          const partiallyResolvedVars = Array.from(Object.values(values.variables));
          return new Promise((resolve, reject) => {
            this.h.resolveWithInteraction(workspaceFolder, partiallyResolvedVars, "tasks", void 0, target).then((resolvedVars) => {
              if (!resolvedVars) {
                resolve(void 0);
              }
              const result = {
                process: void 0,
                variables: /* @__PURE__ */ new Map()
              };
              for (let i2 = 0; i2 < partiallyResolvedVars.length; i2++) {
                const variableName = vars[i2].substring(2, vars[i2].length - 1);
                if (resolvedVars && values.variables[vars[i2]] === vars[i2]) {
                  const resolved = resolvedVars.get(variableName);
                  if (typeof resolved === "string") {
                    result.variables.set(variableName, resolved);
                  }
                } else {
                  result.variables.set(variableName, partiallyResolvedVars[i2]);
                }
              }
              if ($zg(values.process)) {
                result.process = values.process;
              }
              resolve(result);
            }, (reason) => {
              reject(reason);
            });
          });
        });
      },
      findExecutable: (command4, cwd2, paths) => {
        return this.b.$findExecutable(command4, cwd2, paths);
      }
    });
  }
  async $registerSupportedExecutions(custom, shell, process2) {
    return this.f.registerSupportedExecutions(custom, shell, process2);
  }
};
$4Sb = __decorate([
  $frb($xT.MainThreadTask),
  __param(1, $3Sb),
  __param(2, $Zk),
  __param(3, $nY)
], $4Sb);

// out-build/vs/workbench/api/browser/mainThreadLabelService.js
var $5Sb = class $5Sb2 extends $3c {
  constructor(_, b) {
    super();
    this.b = b;
    this.a = this.B(new $_c());
  }
  $registerResourceLabelFormatter(handle2, formatter) {
    formatter.priority = true;
    const disposable = this.b.registerCachedFormatter(formatter);
    this.a.set(handle2, disposable);
  }
  $unregisterResourceLabelFormatter(handle2) {
    this.a.deleteAndDispose(handle2);
  }
};
$5Sb = __decorate([
  $frb($xT.MainThreadLabelService),
  __param(1, $ZI)
], $5Sb);

// out-build/vs/platform/tunnel/common/tunnel.js
var $tC = $Qk("tunnelService");
var $uC = $Qk("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 $vC(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 $wC(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 $yC = ["localhost", "127.0.0.1", "0:0:0:0:0:0:0:1", "::1"];
function $zC(host) {
  return $yC.indexOf(host) >= 0;
}
var $AC = ["0.0.0.0", "0:0:0:0:0:0:0:0", "::"];
function $BC(host) {
  return $AC.indexOf(host) >= 0;
}
var $DC = class {
  constructor(remoteAddress, localAddress, b) {
    this.remoteAddress = remoteAddress;
    this.localAddress = localAddress;
    this.b = b;
    this.a = new $ze();
    this.onDidDispose = this.a.event;
  }
  dispose() {
    this.a.fire();
    return this.b();
  }
};
var $EC = class $EC2 extends $3c {
  constructor(r2, s) {
    super();
    this.r = r2;
    this.s = s;
    this.a = new $ze();
    this.onTunnelOpened = this.a.event;
    this.b = new $ze();
    this.onTunnelClosed = this.b.event;
    this.c = new $ze();
    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 ($BC(remoteHost) || $zC(remoteHost)) {
      remoteHost = $yC[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 ($zC(remoteHost)) {
      hosts.push(...$yC);
      hosts.push(...$AC);
    } else if ($BC(remoteHost)) {
      hosts.push(...$AC);
    }
    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 !!$wC(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 key2 = remotePort;
    this.n.add(key2);
    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(key2);
      });
    } else {
      this.n.delete(key2);
    }
    return tunnel;
  }
};
$EC = __decorate([
  __param(0, $wn),
  __param(1, $kl)
], $EC);

// out-build/vs/workbench/api/common/extHostInitDataService.js
var $wW = $Qk("IExtHostInitDataService");

// out-build/vs/workbench/api/common/extHostRpcService.js
var $gW = $Qk("IExtHostRpcService");

// out-build/vs/workbench/api/common/extHostTunnelService.js
var ExtensionTunnel = class extends $DC {
};
var TunnelDtoConverter;
(function(TunnelDtoConverter2) {
  function fromApiTunnel(tunnel) {
    return {
      remoteAddress: tunnel.remoteAddress,
      localAddress: tunnel.localAddress,
      public: !!tunnel.public,
      privacy: tunnel.privacy ?? (tunnel.public ? TunnelPrivacyId.Public : TunnelPrivacyId.Private),
      protocol: tunnel.protocol
    };
  }
  TunnelDtoConverter2.fromApiTunnel = fromApiTunnel;
  function fromServiceTunnel(tunnel) {
    return {
      remoteAddress: {
        host: tunnel.tunnelRemoteHost,
        port: tunnel.tunnelRemotePort
      },
      localAddress: tunnel.localAddress,
      public: tunnel.privacy !== TunnelPrivacyId.ConstantPrivate && tunnel.privacy !== TunnelPrivacyId.ConstantPrivate,
      privacy: tunnel.privacy,
      protocol: tunnel.protocol
    };
  }
  TunnelDtoConverter2.fromServiceTunnel = fromServiceTunnel;
})(TunnelDtoConverter || (TunnelDtoConverter = {}));
var $6Sb = $Qk("IExtHostTunnelService");
var $7Sb = class $7Sb2 extends $3c {
  constructor(extHostRpc, initData, s) {
    super();
    this.s = s;
    this.f = () => {
      return Promise.resolve(true);
    };
    this.g = /* @__PURE__ */ new Map();
    this.h = new $ze();
    this.onDidChangeTunnels = this.h.event;
    this.n = 0;
    this.r = /* @__PURE__ */ new Map();
    this.a = extHostRpc.getProxy($xT.MainThreadTunnelService);
  }
  async openTunnel(extension, forward) {
    this.s.trace(`ForwardedPorts: (ExtHostTunnelService) ${extension.identifier.value} called openTunnel API for ${forward.remoteAddress.host}:${forward.remoteAddress.port}.`);
    const tunnel = await this.a.$openTunnel(forward, extension.displayName);
    if (tunnel) {
      const disposableTunnel = new ExtensionTunnel(tunnel.remoteAddress, tunnel.localAddress, () => {
        return this.a.$closeTunnel(tunnel.remoteAddress);
      });
      this.B(disposableTunnel);
      return disposableTunnel;
    }
    return void 0;
  }
  async getTunnels() {
    return this.a.$getTunnels();
  }
  u() {
    return this.n++;
  }
  registerPortsAttributesProvider(portSelector, provider) {
    if (portSelector.portRange === void 0 && portSelector.commandPattern === void 0) {
      this.s.error("PortAttributesProvider must specify either a portRange or a commandPattern");
    }
    const providerHandle = this.u();
    this.r.set(providerHandle, { selector: portSelector, provider });
    this.a.$registerPortsAttributesProvider(portSelector, providerHandle);
    return new $zT(() => {
      this.r.delete(providerHandle);
      this.a.$unregisterPortsAttributesProvider(providerHandle);
    });
  }
  async $providePortAttributes(handles, ports, pid, commandLine, cancellationToken) {
    const providedAttributes = [];
    for (const handle2 of handles) {
      const provider = this.r.get(handle2);
      if (!provider) {
        return [];
      }
      providedAttributes.push(...await Promise.all(ports.map(async (port) => {
        let providedAttributes2;
        try {
          providedAttributes2 = await provider.provider.providePortAttributes({ port, pid, commandLine }, cancellationToken);
        } catch (e) {
          providedAttributes2 = await provider.provider.providePortAttributes(port, pid, commandLine, cancellationToken);
        }
        return { providedAttributes: providedAttributes2, port };
      })));
    }
    const allAttributes = providedAttributes.filter((attribute) => !!attribute.providedAttributes);
    return allAttributes.length > 0 ? allAttributes.map((attributes) => {
      return {
        autoForwardAction: attributes.providedAttributes.autoForwardAction,
        port: attributes.port
      };
    }) : [];
  }
  async $registerCandidateFinder(_enable) {
  }
  registerTunnelProvider(provider, information) {
    if (this.b) {
      throw new Error("A tunnel provider has already been registered. Only the first tunnel provider to be registered will be used.");
    }
    this.b = async (tunnelOptions, tunnelCreationOptions) => {
      const result = await provider.provideTunnel(tunnelOptions, tunnelCreationOptions, CancellationToken.None);
      return result ?? void 0;
    };
    const tunnelFeatures = information.tunnelFeatures ? {
      elevation: !!information.tunnelFeatures?.elevation,
      privacyOptions: information.tunnelFeatures?.privacyOptions,
      protocol: information.tunnelFeatures.protocol === void 0 ? true : information.tunnelFeatures.protocol
    } : void 0;
    this.a.$setTunnelProvider(tunnelFeatures, true);
    return Promise.resolve($1c(() => {
      this.b = void 0;
      this.a.$setTunnelProvider(void 0, false);
    }));
  }
  /**
   * Applies the tunnel metadata and factory found in the remote authority
   * resolver to the tunnel system.
   *
   * `managedRemoteAuthority` should be be passed if the resolver returned on.
   * If this is the case, the tunnel cannot be connected to via a websocket from
   * the share process, so a synethic tunnel factory is used as a default.
   */
  async setTunnelFactory(provider, managedRemoteAuthority) {
    if (provider) {
      if (provider.candidatePortSource !== void 0) {
        this.a.$setCandidatePortSource(provider.candidatePortSource);
      }
      if (provider.showCandidatePort) {
        this.f = provider.showCandidatePort;
        this.a.$setCandidateFilter();
      }
      const tunnelFactory = provider.tunnelFactory ?? (managedRemoteAuthority ? this.w(managedRemoteAuthority) : void 0);
      if (tunnelFactory) {
        this.b = tunnelFactory;
        let privacyOptions = provider.tunnelFeatures?.privacyOptions ?? [];
        if (provider.tunnelFeatures?.public && privacyOptions.length === 0) {
          privacyOptions = [
            {
              id: "private",
              label: localize(2770, null),
              themeIcon: "lock"
            },
            {
              id: "public",
              label: localize(2771, null),
              themeIcon: "eye"
            }
          ];
        }
        const tunnelFeatures = provider.tunnelFeatures ? {
          elevation: !!provider.tunnelFeatures?.elevation,
          public: !!provider.tunnelFeatures?.public,
          privacyOptions,
          protocol: true
        } : void 0;
        this.a.$setTunnelProvider(tunnelFeatures, !!provider.tunnelFactory);
      }
    } else {
      this.b = void 0;
    }
    return $1c(() => {
      this.b = void 0;
    });
  }
  w(_authority) {
    return void 0;
  }
  async $closeTunnel(remote, silent) {
    if (this.g.has(remote.host)) {
      const hostMap = this.g.get(remote.host);
      if (hostMap.has(remote.port)) {
        if (silent) {
          hostMap.get(remote.port).disposeListener.dispose();
        }
        await hostMap.get(remote.port).tunnel.dispose();
        hostMap.delete(remote.port);
      }
    }
  }
  async $onDidTunnelsChange() {
    this.h.fire();
  }
  async $forwardPort(tunnelOptions, tunnelCreationOptions) {
    if (this.b) {
      try {
        this.s.trace("ForwardedPorts: (ExtHostTunnelService) Getting tunnel from provider.");
        const providedPort = this.b(tunnelOptions, tunnelCreationOptions);
        this.s.trace("ForwardedPorts: (ExtHostTunnelService) Got tunnel promise from provider.");
        if (providedPort !== void 0) {
          const tunnel = await providedPort;
          this.s.trace("ForwardedPorts: (ExtHostTunnelService) Successfully awaited tunnel from provider.");
          if (tunnel === void 0) {
            this.s.error("ForwardedPorts: (ExtHostTunnelService) Resolved tunnel is undefined");
            return void 0;
          }
          if (!this.g.has(tunnelOptions.remoteAddress.host)) {
            this.g.set(tunnelOptions.remoteAddress.host, /* @__PURE__ */ new Map());
          }
          const disposeListener = this.B(tunnel.onDidDispose(() => {
            this.s.trace("ForwardedPorts: (ExtHostTunnelService) Extension fired tunnel's onDidDispose.");
            return this.a.$closeTunnel(tunnel.remoteAddress);
          }));
          this.g.get(tunnelOptions.remoteAddress.host).set(tunnelOptions.remoteAddress.port, { tunnel, disposeListener });
          return TunnelDtoConverter.fromApiTunnel(tunnel);
        } else {
          this.s.trace("ForwardedPorts: (ExtHostTunnelService) Tunnel is undefined");
        }
      } catch (e) {
        this.s.trace("ForwardedPorts: (ExtHostTunnelService) tunnel provider error");
        if (e instanceof Error) {
          return e.message;
        }
      }
    }
    return void 0;
  }
  async $applyCandidateFilter(candidates) {
    const filter = await Promise.all(candidates.map((candidate) => this.f(candidate.host, candidate.port, candidate.detail ?? "")));
    const result = candidates.filter((candidate, index) => filter[index]);
    this.s.trace(`ForwardedPorts: (ExtHostTunnelService) filtered from ${candidates.map((port) => port.port).join(", ")} to ${result.map((port) => port.port).join(", ")}`);
    return result;
  }
};
$7Sb = __decorate([
  __param(0, $gW),
  __param(1, $wW),
  __param(2, $wn)
], $7Sb);

// out-build/vs/workbench/services/remote/common/tunnelModel.js
var MISMATCH_LOCAL_PORT_COOLDOWN = 10 * 1e3;
var TUNNELS_TO_RESTORE = "remote.tunnels.toRestore";
var TUNNELS_TO_RESTORE_EXPIRATION = "remote.tunnels.toRestoreExpiration";
var RESTORE_EXPIRATION_TIME = 1e3 * 60 * 60 * 24 * 14;
var $VS = "onTunnel";
var $WS = new $nn("forwardedPortsViewEnabled", false, localize(13093, null));
var $XS = new $nn("forwardedPortsViewOnlyEnabled", false, localize(13094, null));
function $YS(address) {
  const matches = address.match(/^([a-zA-Z0-9_-]+(?:\.[a-zA-Z0-9_-]+)*:)?([0-9]+)$/);
  if (!matches) {
    return void 0;
  }
  return { host: matches[1]?.substring(0, matches[1].length - 1) || "localhost", port: Number(matches[2]) };
}
var TunnelCloseReason;
(function(TunnelCloseReason2) {
  TunnelCloseReason2["Other"] = "Other";
  TunnelCloseReason2["User"] = "User";
  TunnelCloseReason2["AutoForwardEnd"] = "AutoForwardEnd";
})(TunnelCloseReason || (TunnelCloseReason = {}));
var TunnelSource;
(function(TunnelSource2) {
  TunnelSource2[TunnelSource2["User"] = 0] = "User";
  TunnelSource2[TunnelSource2["Auto"] = 1] = "Auto";
  TunnelSource2[TunnelSource2["Extension"] = 2] = "Extension";
})(TunnelSource || (TunnelSource = {}));
var $ZS = {
  source: TunnelSource.User,
  description: localize(13095, null)
};
var $1S = {
  source: TunnelSource.Auto,
  description: localize(13096, null)
};
function $2S(map, host, port) {
  const initialAddress = map.get($4S(host, port));
  if (initialAddress) {
    return initialAddress;
  }
  if ($zC(host)) {
    for (const testHost of $yC) {
      const testAddress = $4S(testHost, port);
      if (map.has(testAddress)) {
        return map.get(testAddress);
      }
    }
  } else if ($BC(host)) {
    for (const testHost of $AC) {
      const testAddress = $4S(testHost, port);
      if (map.has(testAddress)) {
        return map.get(testAddress);
      }
    }
  }
  return void 0;
}
function $3S(map, host, port) {
  const originalAddress = $2S(map, host, port);
  if (originalAddress) {
    return originalAddress;
  }
  const otherHost = $BC(host) ? "localhost" : $zC(host) ? "0.0.0.0" : void 0;
  if (otherHost) {
    return $2S(map, otherHost, port);
  }
  return void 0;
}
function $4S(host, port) {
  return host + ":" + port;
}
var OnPortForward;
(function(OnPortForward2) {
  OnPortForward2["Notify"] = "notify";
  OnPortForward2["OpenBrowser"] = "openBrowser";
  OnPortForward2["OpenBrowserOnce"] = "openBrowserOnce";
  OnPortForward2["OpenPreview"] = "openPreview";
  OnPortForward2["Silent"] = "silent";
  OnPortForward2["Ignore"] = "ignore";
})(OnPortForward || (OnPortForward = {}));
function $5S(candidate) {
  return candidate && "host" in candidate && typeof candidate.host === "string" && "port" in candidate && typeof candidate.port === "number" && (!("detail" in candidate) || typeof candidate.detail === "string") && (!("pid" in candidate) || typeof candidate.pid === "string");
}
var $6S = class _$6S extends $3c {
  static {
    this.c = "remote.portsAttributes";
  }
  static {
    this.f = "remote.otherPortsAttributes";
  }
  static {
    this.g = /^(\d+)\-(\d+)$/;
  }
  static {
    this.h = /^([a-z0-9\-]+):(\d{1,5})$/;
  }
  constructor(r2) {
    super();
    this.r = r2;
    this.j = [];
    this.n = new $ze();
    this.onDidChangeAttributes = this.n.event;
    this.B(r2.onDidChangeConfiguration((e) => {
      if (e.affectsConfiguration(_$6S.c) || e.affectsConfiguration(_$6S.f)) {
        this.s();
      }
    }));
    this.s();
  }
  s() {
    this.j = this.y();
    this.n.fire();
  }
  getAttributes(port, host, commandLine) {
    let index = this.w(port, host, commandLine, this.j, 0);
    const attributes = {
      label: void 0,
      onAutoForward: void 0,
      elevateIfNeeded: void 0,
      requireLocalPort: void 0,
      protocol: void 0
    };
    while (index >= 0) {
      const found = this.j[index];
      if (found.key === port) {
        attributes.onAutoForward = found.onAutoForward ?? attributes.onAutoForward;
        attributes.elevateIfNeeded = found.elevateIfNeeded !== void 0 ? found.elevateIfNeeded : attributes.elevateIfNeeded;
        attributes.label = found.label ?? attributes.label;
        attributes.requireLocalPort = found.requireLocalPort;
        attributes.protocol = found.protocol;
      } else {
        attributes.onAutoForward = attributes.onAutoForward ?? found.onAutoForward;
        attributes.elevateIfNeeded = attributes.elevateIfNeeded !== void 0 ? attributes.elevateIfNeeded : found.elevateIfNeeded;
        attributes.label = attributes.label ?? found.label;
        attributes.requireLocalPort = attributes.requireLocalPort !== void 0 ? attributes.requireLocalPort : void 0;
        attributes.protocol = attributes.protocol ?? found.protocol;
      }
      index = this.w(port, host, commandLine, this.j, index + 1);
    }
    if (attributes.onAutoForward !== void 0 || attributes.elevateIfNeeded !== void 0 || attributes.label !== void 0 || attributes.requireLocalPort !== void 0 || attributes.protocol !== void 0) {
      return attributes;
    }
    return this.C();
  }
  t(value) {
    return value.start !== void 0 && value.end !== void 0;
  }
  u(value) {
    return value.host !== void 0 && value.port !== void 0 && $zg(value.host) && $Dg(value.port);
  }
  w(port, host, commandLine, attributes, fromIndex) {
    if (fromIndex >= attributes.length) {
      return -1;
    }
    const shouldUseHost = !$zC(host) && !$BC(host);
    const sliced = attributes.slice(fromIndex);
    const foundIndex = sliced.findIndex((value) => {
      if ($Dg(value.key)) {
        return shouldUseHost ? false : value.key === port;
      } else if (this.t(value.key)) {
        return shouldUseHost ? false : port >= value.key.start && port <= value.key.end;
      } else if (this.u(value.key)) {
        return port === value.key.port && host === value.key.host;
      } else {
        return commandLine ? value.key.test(commandLine) : false;
      }
    });
    return foundIndex >= 0 ? foundIndex + fromIndex : -1;
  }
  y() {
    const settingValue = this.r.getValue(_$6S.c);
    if (!settingValue || !$Bg(settingValue)) {
      return [];
    }
    const attributes = [];
    for (const attributesKey in settingValue) {
      if (attributesKey === void 0) {
        continue;
      }
      const setting = settingValue[attributesKey];
      let key2 = void 0;
      if (Number(attributesKey)) {
        key2 = Number(attributesKey);
      } else if ($zg(attributesKey)) {
        if (_$6S.g.test(attributesKey)) {
          const match = attributesKey.match(_$6S.g);
          key2 = { start: Number(match[1]), end: Number(match[2]) };
        } else if (_$6S.h.test(attributesKey)) {
          const match = attributesKey.match(_$6S.h);
          key2 = { host: match[1], port: Number(match[2]) };
        } else {
          let regTest = void 0;
          try {
            regTest = RegExp(attributesKey);
          } catch (e) {
          }
          if (regTest) {
            key2 = regTest;
          }
        }
      }
      if (!key2) {
        continue;
      }
      attributes.push({
        key: key2,
        elevateIfNeeded: setting.elevateIfNeeded,
        onAutoForward: setting.onAutoForward,
        label: setting.label,
        requireLocalPort: setting.requireLocalPort,
        protocol: setting.protocol
      });
    }
    const defaults = this.r.getValue(_$6S.f);
    if (defaults) {
      this.m = {
        elevateIfNeeded: defaults.elevateIfNeeded,
        label: defaults.label,
        onAutoForward: defaults.onAutoForward,
        requireLocalPort: defaults.requireLocalPort,
        protocol: defaults.protocol
      };
    }
    return this.z(attributes);
  }
  z(attributes) {
    function getVal(item, thisRef) {
      if ($Dg(item.key)) {
        return item.key;
      } else if (thisRef.t(item.key)) {
        return item.key.start;
      } else if (thisRef.u(item.key)) {
        return item.key.port;
      } else {
        return Number.MAX_VALUE;
      }
    }
    return attributes.sort((a, b) => {
      return getVal(a, this) - getVal(b, this);
    });
  }
  C() {
    return this.m;
  }
  static providedActionToAction(providedAction) {
    switch (providedAction) {
      case ProvidedOnAutoForward.Notify:
        return OnPortForward.Notify;
      case ProvidedOnAutoForward.OpenBrowser:
        return OnPortForward.OpenBrowser;
      case ProvidedOnAutoForward.OpenBrowserOnce:
        return OnPortForward.OpenBrowserOnce;
      case ProvidedOnAutoForward.OpenPreview:
        return OnPortForward.OpenPreview;
      case ProvidedOnAutoForward.Silent:
        return OnPortForward.Silent;
      case ProvidedOnAutoForward.Ignore:
        return OnPortForward.Ignore;
      default:
        return void 0;
    }
  }
  async addAttributes(port, attributes, target) {
    const settingValue = this.r.inspect(_$6S.c);
    const remoteValue = settingValue.userRemoteValue;
    let newRemoteValue;
    if (!remoteValue || !$Bg(remoteValue)) {
      newRemoteValue = {};
    } else {
      newRemoteValue = $Lv(remoteValue);
    }
    if (!newRemoteValue[`${port}`]) {
      newRemoteValue[`${port}`] = {};
    }
    for (const attribute in attributes) {
      newRemoteValue[`${port}`][attribute] = attributes[attribute];
    }
    return this.r.updateValue(_$6S.c, newRemoteValue, target);
  }
};
var $7S = class $7S2 extends $3c {
  constructor(H, I, J, L, M, N, O, P, Q, R) {
    super();
    this.H = H;
    this.I = I;
    this.J = J;
    this.L = L;
    this.M = M;
    this.N = N;
    this.O = O;
    this.P = P;
    this.Q = Q;
    this.R = R;
    this.c = /* @__PURE__ */ new Map();
    this.g = new $ze();
    this.onForwardPort = this.g.event;
    this.h = new $ze();
    this.onClosePort = this.h.event;
    this.j = new $ze();
    this.onPortName = this.j.event;
    this.n = new $ze();
    this.onCandidatesChanged = this.n.event;
    this.t = new $ze();
    this.onEnvironmentTunnelsSet = this.t.event;
    this.u = false;
    this.w = void 0;
    this.z = false;
    this.C = new $ze();
    this.D = /* @__PURE__ */ new Map();
    this.F = /* @__PURE__ */ new Map();
    this.G = [];
    this.U = false;
    this.eb = /* @__PURE__ */ new Date();
    this.configPortsAttributes = new $6S(J);
    this.s = this.bb();
    this.B(this.configPortsAttributes.onDidChangeAttributes(this.kb, this));
    this.forwarded = /* @__PURE__ */ new Map();
    this.f = /* @__PURE__ */ new Map();
    this.H.tunnels.then(async (tunnels) => {
      const attributes = await this.getAttributes(tunnels.map((tunnel) => {
        return { port: tunnel.tunnelRemotePort, host: tunnel.tunnelRemoteHost };
      }));
      for (const tunnel of tunnels) {
        if (tunnel.localAddress) {
          const key2 = $4S(tunnel.tunnelRemoteHost, tunnel.tunnelRemotePort);
          const matchingCandidate = $3S(this.m ?? /* @__PURE__ */ new Map(), tunnel.tunnelRemoteHost, tunnel.tunnelRemotePort);
          this.forwarded.set(key2, {
            remotePort: tunnel.tunnelRemotePort,
            remoteHost: tunnel.tunnelRemoteHost,
            localAddress: tunnel.localAddress,
            protocol: attributes?.get(tunnel.tunnelRemotePort)?.protocol ?? TunnelProtocol.Http,
            localUri: await this.Y(tunnel.localAddress, attributes?.get(tunnel.tunnelRemotePort)),
            localPort: tunnel.tunnelLocalPort,
            name: attributes?.get(tunnel.tunnelRemotePort)?.label,
            runningProcess: matchingCandidate?.detail,
            hasRunningProcess: !!matchingCandidate,
            pid: matchingCandidate?.pid,
            privacy: tunnel.privacy,
            source: $ZS
          });
          this.f.set(key2, tunnel);
        }
      }
    });
    this.detected = /* @__PURE__ */ new Map();
    this.B(this.H.onTunnelOpened(async (tunnel) => {
      const key2 = $4S(tunnel.tunnelRemoteHost, tunnel.tunnelRemotePort);
      if (!$3S(this.forwarded, tunnel.tunnelRemoteHost, tunnel.tunnelRemotePort) && !$3S(this.detected, tunnel.tunnelRemoteHost, tunnel.tunnelRemotePort) && !$3S(this.c, tunnel.tunnelRemoteHost, tunnel.tunnelRemotePort) && tunnel.localAddress) {
        const matchingCandidate = $3S(this.m ?? /* @__PURE__ */ new Map(), tunnel.tunnelRemoteHost, tunnel.tunnelRemotePort);
        const attributes = (await this.getAttributes([{ port: tunnel.tunnelRemotePort, host: tunnel.tunnelRemoteHost }]))?.get(tunnel.tunnelRemotePort);
        this.forwarded.set(key2, {
          remoteHost: tunnel.tunnelRemoteHost,
          remotePort: tunnel.tunnelRemotePort,
          localAddress: tunnel.localAddress,
          protocol: attributes?.protocol ?? TunnelProtocol.Http,
          localUri: await this.Y(tunnel.localAddress, attributes),
          localPort: tunnel.tunnelLocalPort,
          name: attributes?.label,
          closeable: true,
          runningProcess: matchingCandidate?.detail,
          hasRunningProcess: !!matchingCandidate,
          pid: matchingCandidate?.pid,
          privacy: tunnel.privacy,
          source: $ZS
        });
      }
      await this.db();
      this.W(true);
      this.f.set(key2, tunnel);
      this.g.fire(this.forwarded.get(key2));
    }));
    this.B(this.H.onTunnelClosed((address) => {
      return this.X(address, TunnelCloseReason.Other);
    }));
    this.W(false);
  }
  S() {
    if (this.Q.extensions.find((extension) => extension.activationEvents?.includes($VS))) {
      this.R.createKey($XS.key, true);
      return true;
    }
    return false;
  }
  W(tunnelOpened) {
    if (this.U) {
      return;
    }
    if (tunnelOpened) {
      this.U = true;
    }
    const hasRemote = this.L.remoteAuthority !== void 0;
    if (hasRemote && !tunnelOpened) {
      return;
    }
    if (this.S()) {
      return;
    }
    const activationDisposable = this.B(this.Q.onDidRegisterExtensions(() => {
      if (this.S()) {
        activationDisposable.dispose();
      }
    }));
  }
  async X(address, reason) {
    const key2 = $4S(address.host, address.port);
    if (this.forwarded.has(key2)) {
      this.forwarded.delete(key2);
      await this.db();
      this.h.fire(address);
    }
  }
  Y(localAddress, attributes) {
    if (localAddress.startsWith("http")) {
      return URI.parse(localAddress);
    }
    const protocol = attributes?.protocol ?? "http";
    return URI.parse(`${protocol}://${localAddress}`);
  }
  async Z(prefix) {
    const workspace2 = this.N.getWorkspace();
    const workspaceHash = workspace2.configuration ? $Xi(workspace2.configuration.path) : workspace2.folders.length > 0 ? $Xi(workspace2.folders[0].uri.path) : void 0;
    if (workspaceHash === void 0) {
      this.O.debug("Could not get workspace hash for forwarded ports storage key.");
      return void 0;
    }
    return `${prefix}.${this.L.remoteAuthority}.${workspaceHash}`;
  }
  async $() {
    return this.Z(TUNNELS_TO_RESTORE);
  }
  async ab() {
    return this.Z(TUNNELS_TO_RESTORE_EXPIRATION);
  }
  async bb() {
    const deprecatedValue = this.I.get(
      TUNNELS_TO_RESTORE,
      1
      /* StorageScope.WORKSPACE */
    );
    if (deprecatedValue) {
      this.I.remove(
        TUNNELS_TO_RESTORE,
        1
        /* StorageScope.WORKSPACE */
      );
      await this.db();
      return deprecatedValue;
    }
    const storageKey = await this.$();
    if (!storageKey) {
      return void 0;
    }
    return this.I.get(
      storageKey,
      0
      /* StorageScope.PROFILE */
    );
  }
  async restoreForwarded() {
    this.cb();
    if (this.J.getValue("remote.restoreForwardedPorts")) {
      const tunnelRestoreValue = await this.s;
      if (tunnelRestoreValue && tunnelRestoreValue !== this.y) {
        const tunnels = JSON.parse(tunnelRestoreValue) ?? [];
        this.O.trace(`ForwardedPorts: (TunnelModel) restoring ports ${tunnels.map((tunnel) => tunnel.remotePort).join(", ")}`);
        for (const tunnel of tunnels) {
          const alreadyForwarded2 = $3S(this.detected, tunnel.remoteHost, tunnel.remotePort);
          if (tunnel.source.source !== TunnelSource.Extension && !alreadyForwarded2 || tunnel.source.source === TunnelSource.Extension && alreadyForwarded2) {
            await this.gb({
              remote: { host: tunnel.remoteHost, port: tunnel.remotePort },
              local: tunnel.localPort,
              name: tunnel.name,
              elevateIfNeeded: true,
              source: tunnel.source
            });
          } else if (tunnel.source.source === TunnelSource.Extension && !alreadyForwarded2) {
            this.D.set($4S(tunnel.remoteHost, tunnel.remotePort), tunnel);
          }
        }
      }
    }
    this.z = true;
    this.C.fire();
    if (!this.w) {
      const key2 = await this.$();
      this.w = this.B(new $2c());
      this.w.add(this.I.onDidChangeValue(0, void 0, this.w)(async (e) => {
        if (e.key === key2) {
          this.s = Promise.resolve(this.I.get(
            key2,
            0
            /* StorageScope.PROFILE */
          ));
          await this.restoreForwarded();
        }
      }));
    }
  }
  cb() {
    const keys = this.I.keys(
      0,
      0
      /* StorageTarget.USER */
    ).filter((key2) => key2.startsWith(TUNNELS_TO_RESTORE_EXPIRATION));
    for (const key2 of keys) {
      const expiration = this.I.getNumber(
        key2,
        0
        /* StorageScope.PROFILE */
      );
      if (expiration && expiration < Date.now()) {
        this.s = Promise.resolve(void 0);
        const storageKey = key2.replace(TUNNELS_TO_RESTORE_EXPIRATION, TUNNELS_TO_RESTORE);
        this.I.remove(
          key2,
          0
          /* StorageScope.PROFILE */
        );
        this.I.remove(
          storageKey,
          0
          /* StorageScope.PROFILE */
        );
      }
    }
  }
  async db() {
    if (this.J.getValue("remote.restoreForwardedPorts")) {
      const forwarded = Array.from(this.forwarded.values());
      const restorableTunnels = forwarded.map((tunnel) => {
        return {
          remoteHost: tunnel.remoteHost,
          remotePort: tunnel.remotePort,
          localPort: tunnel.localPort,
          name: tunnel.name,
          localAddress: tunnel.localAddress,
          localUri: tunnel.localUri,
          protocol: tunnel.protocol,
          source: tunnel.source
        };
      });
      let valueToStore;
      if (forwarded.length > 0) {
        valueToStore = JSON.stringify(restorableTunnels);
      }
      const key2 = await this.$();
      const expirationKey = await this.ab();
      if (!valueToStore && key2 && expirationKey) {
        this.I.remove(
          key2,
          0
          /* StorageScope.PROFILE */
        );
        this.I.remove(
          expirationKey,
          0
          /* StorageScope.PROFILE */
        );
      } else if (valueToStore !== this.y && key2 && expirationKey) {
        this.I.store(
          key2,
          valueToStore,
          0,
          0
          /* StorageTarget.USER */
        );
        this.I.store(
          expirationKey,
          Date.now() + RESTORE_EXPIRATION_TIME,
          0,
          0
          /* StorageTarget.USER */
        );
      }
      this.y = valueToStore;
    }
  }
  async fb(tunnel, expectedLocal, attributes) {
    if (!tunnel.tunnelLocalPort || !attributes?.requireLocalPort) {
      return;
    }
    if (tunnel.tunnelLocalPort === expectedLocal) {
      return;
    }
    const newCooldown = /* @__PURE__ */ new Date();
    if (this.eb.getTime() + MISMATCH_LOCAL_PORT_COOLDOWN > newCooldown.getTime()) {
      return;
    }
    this.eb = newCooldown;
    const mismatchString = localize(13097, null, expectedLocal, tunnel.tunnelRemotePort, tunnel.tunnelLocalPort);
    return this.P.info(mismatchString);
  }
  async forward(tunnelProperties, attributes) {
    if (!this.z && this.L.remoteAuthority) {
      await Event2.toPromise(this.C.event);
    }
    return this.gb(tunnelProperties, attributes);
  }
  async gb(tunnelProperties, attributes) {
    await this.Q.activateByEvent($VS);
    const existingTunnel = $3S(this.forwarded, tunnelProperties.remote.host, tunnelProperties.remote.port);
    attributes = attributes ?? (attributes !== null ? (await this.getAttributes([tunnelProperties.remote]))?.get(tunnelProperties.remote.port) : void 0);
    const localPort = tunnelProperties.local !== void 0 ? tunnelProperties.local : tunnelProperties.remote.port;
    let noTunnelValue;
    if (!existingTunnel) {
      const authority = this.L.remoteAuthority;
      const addressProvider = authority ? {
        getAddress: async () => {
          return (await this.M.resolveAuthority(authority)).authority;
        }
      } : void 0;
      const key2 = $4S(tunnelProperties.remote.host, tunnelProperties.remote.port);
      this.c.set(key2, true);
      tunnelProperties = this.hb(key2, tunnelProperties);
      const tunnel = await this.H.openTunnel(addressProvider, tunnelProperties.remote.host, tunnelProperties.remote.port, void 0, localPort, !tunnelProperties.elevateIfNeeded ? attributes?.elevateIfNeeded : tunnelProperties.elevateIfNeeded, tunnelProperties.privacy, attributes?.protocol);
      if (typeof tunnel === "string") {
        noTunnelValue = tunnel;
      } else if (tunnel && tunnel.localAddress) {
        const matchingCandidate = $3S(this.m ?? /* @__PURE__ */ new Map(), tunnelProperties.remote.host, tunnelProperties.remote.port);
        const protocol = tunnel.protocol ? tunnel.protocol === TunnelProtocol.Https ? TunnelProtocol.Https : TunnelProtocol.Http : attributes?.protocol ?? TunnelProtocol.Http;
        const newForward = {
          remoteHost: tunnel.tunnelRemoteHost,
          remotePort: tunnel.tunnelRemotePort,
          localPort: tunnel.tunnelLocalPort,
          name: attributes?.label ?? tunnelProperties.name,
          closeable: true,
          localAddress: tunnel.localAddress,
          protocol,
          localUri: await this.Y(tunnel.localAddress, attributes),
          runningProcess: matchingCandidate?.detail,
          hasRunningProcess: !!matchingCandidate,
          pid: matchingCandidate?.pid,
          source: tunnelProperties.source ?? $ZS,
          privacy: tunnel.privacy
        };
        this.forwarded.set(key2, newForward);
        this.f.set(key2, tunnel);
        this.c.delete(key2);
        await this.db();
        await this.fb(tunnel, localPort, attributes);
        this.g.fire(newForward);
        return tunnel;
      }
      this.c.delete(key2);
    } else {
      return this.ib(existingTunnel, tunnelProperties, attributes);
    }
    return noTunnelValue;
  }
  hb(key2, tunnelProperties) {
    const map = this.D.has(key2) ? this.D : this.F.has(key2) ? this.F : void 0;
    if (map) {
      const updateProps = map.get(key2);
      map.delete(key2);
      if (updateProps) {
        tunnelProperties.name = updateProps.name ?? tunnelProperties.name;
        tunnelProperties.local = ("local" in updateProps ? updateProps.local : "localPort" in updateProps ? updateProps.localPort : void 0) ?? tunnelProperties.local;
        tunnelProperties.privacy = tunnelProperties.privacy;
      }
    }
    return tunnelProperties;
  }
  async ib(existingTunnel, tunnelProperties, attributes) {
    const newName = attributes?.label ?? tunnelProperties.name;
    let MergedAttributeAction;
    (function(MergedAttributeAction2) {
      MergedAttributeAction2[MergedAttributeAction2["None"] = 0] = "None";
      MergedAttributeAction2[MergedAttributeAction2["Fire"] = 1] = "Fire";
      MergedAttributeAction2[MergedAttributeAction2["Reopen"] = 2] = "Reopen";
    })(MergedAttributeAction || (MergedAttributeAction = {}));
    let mergedAction = MergedAttributeAction.None;
    if (newName !== existingTunnel.name) {
      existingTunnel.name = newName;
      mergedAction = MergedAttributeAction.Fire;
    }
    if ((attributes?.protocol || existingTunnel.protocol !== TunnelProtocol.Http) && attributes?.protocol !== existingTunnel.protocol) {
      tunnelProperties.source = existingTunnel.source;
      mergedAction = MergedAttributeAction.Reopen;
    }
    if (tunnelProperties.privacy && existingTunnel.privacy !== tunnelProperties.privacy) {
      mergedAction = MergedAttributeAction.Reopen;
    }
    switch (mergedAction) {
      case MergedAttributeAction.Fire: {
        this.g.fire();
        break;
      }
      case MergedAttributeAction.Reopen: {
        await this.close(existingTunnel.remoteHost, existingTunnel.remotePort, TunnelCloseReason.User);
        await this.gb(tunnelProperties, attributes);
      }
    }
    return $3S(this.f, tunnelProperties.remote.host, tunnelProperties.remote.port);
  }
  async name(host, port, name) {
    const existingForwarded = $3S(this.forwarded, host, port);
    const key2 = $4S(host, port);
    if (existingForwarded) {
      existingForwarded.name = name;
      await this.db();
      this.j.fire({ host, port });
      return;
    } else if (this.detected.has(key2)) {
      this.detected.get(key2).name = name;
      this.j.fire({ host, port });
    }
  }
  async close(host, port, reason) {
    const key2 = $4S(host, port);
    const oldTunnel = this.forwarded.get(key2);
    if (reason === TunnelCloseReason.AutoForwardEnd && oldTunnel && oldTunnel.source.source === TunnelSource.Auto) {
      this.F.set(key2, {
        local: oldTunnel.localPort,
        name: oldTunnel.name,
        privacy: oldTunnel.privacy
      });
    }
    await this.H.closeTunnel(host, port);
    return this.X({ host, port }, reason);
  }
  address(host, port) {
    const key2 = $4S(host, port);
    return (this.forwarded.get(key2) || this.detected.get(key2))?.localAddress;
  }
  get environmentTunnelsSet() {
    return this.u;
  }
  addEnvironmentTunnels(tunnels) {
    if (tunnels) {
      for (const tunnel of tunnels) {
        const matchingCandidate = $3S(this.m ?? /* @__PURE__ */ new Map(), tunnel.remoteAddress.host, tunnel.remoteAddress.port);
        const localAddress = typeof tunnel.localAddress === "string" ? tunnel.localAddress : $4S(tunnel.localAddress.host, tunnel.localAddress.port);
        this.detected.set($4S(tunnel.remoteAddress.host, tunnel.remoteAddress.port), {
          remoteHost: tunnel.remoteAddress.host,
          remotePort: tunnel.remoteAddress.port,
          localAddress,
          protocol: TunnelProtocol.Http,
          localUri: this.Y(localAddress),
          closeable: false,
          runningProcess: matchingCandidate?.detail,
          hasRunningProcess: !!matchingCandidate,
          pid: matchingCandidate?.pid,
          privacy: TunnelPrivacyId.ConstantPrivate,
          source: {
            source: TunnelSource.Extension,
            description: localize(13098, null)
          }
        });
        this.H.setEnvironmentTunnel(tunnel.remoteAddress.host, tunnel.remoteAddress.port, localAddress, TunnelPrivacyId.ConstantPrivate, TunnelProtocol.Http);
      }
    }
    this.u = true;
    this.t.fire();
    this.g.fire();
  }
  setCandidateFilter(filter) {
    this.r = filter;
  }
  async setCandidates(candidates) {
    let processedCandidates = candidates;
    if (this.r) {
      processedCandidates = await this.r(candidates);
    }
    const removedCandidates = this.jb(processedCandidates);
    this.O.trace(`ForwardedPorts: (TunnelModel) removed candidates ${Array.from(removedCandidates.values()).map((candidate) => candidate.port).join(", ")}`);
    this.n.fire(removedCandidates);
  }
  // Returns removed candidates
  jb(candidates) {
    const removedCandidates = this.m ?? /* @__PURE__ */ new Map();
    const candidatesMap = /* @__PURE__ */ new Map();
    this.m = candidatesMap;
    candidates.forEach((value) => {
      const addressKey = $4S(value.host, value.port);
      candidatesMap.set(addressKey, {
        host: value.host,
        port: value.port,
        detail: value.detail,
        pid: value.pid
      });
      if (removedCandidates.has(addressKey)) {
        removedCandidates.delete(addressKey);
      }
      const forwardedValue = $3S(this.forwarded, value.host, value.port);
      if (forwardedValue) {
        forwardedValue.runningProcess = value.detail;
        forwardedValue.hasRunningProcess = true;
        forwardedValue.pid = value.pid;
      }
    });
    removedCandidates.forEach((_value, key2) => {
      const parsedAddress = $YS(key2);
      if (!parsedAddress) {
        return;
      }
      const forwardedValue = $3S(this.forwarded, parsedAddress.host, parsedAddress.port);
      if (forwardedValue) {
        forwardedValue.runningProcess = void 0;
        forwardedValue.hasRunningProcess = false;
        forwardedValue.pid = void 0;
      }
      const detectedValue = $3S(this.detected, parsedAddress.host, parsedAddress.port);
      if (detectedValue) {
        detectedValue.runningProcess = void 0;
        detectedValue.hasRunningProcess = false;
        detectedValue.pid = void 0;
      }
    });
    return removedCandidates;
  }
  get candidates() {
    return this.m ? Array.from(this.m.values()) : [];
  }
  get candidatesOrUndefined() {
    return this.m ? this.candidates : void 0;
  }
  async kb() {
    const tunnels = Array.from(this.forwarded.values());
    const allAttributes = await this.getAttributes(tunnels.map((tunnel) => {
      return { port: tunnel.remotePort, host: tunnel.remoteHost };
    }), false);
    if (!allAttributes) {
      return;
    }
    for (const forwarded of tunnels) {
      const attributes = allAttributes.get(forwarded.remotePort);
      if ((attributes?.protocol || forwarded.protocol !== TunnelProtocol.Http) && attributes?.protocol !== forwarded.protocol) {
        await this.gb({
          remote: { host: forwarded.remoteHost, port: forwarded.remotePort },
          local: forwarded.localPort,
          name: forwarded.name,
          source: forwarded.source
        }, attributes);
      }
      if (!attributes) {
        continue;
      }
      if (attributes.label && attributes.label !== forwarded.name) {
        await this.name(forwarded.remoteHost, forwarded.remotePort, attributes.label);
      }
    }
  }
  async getAttributes(forwardedPorts, checkProviders = true) {
    const matchingCandidates = /* @__PURE__ */ new Map();
    const pidToPortsMapping = /* @__PURE__ */ new Map();
    forwardedPorts.forEach((forwardedPort) => {
      const matchingCandidate = $3S(this.m ?? /* @__PURE__ */ new Map(), $yC[0], forwardedPort.port) ?? forwardedPort;
      if (matchingCandidate) {
        matchingCandidates.set(forwardedPort.port, matchingCandidate);
        const pid = $5S(matchingCandidate) ? matchingCandidate.pid : void 0;
        if (!pidToPortsMapping.has(pid)) {
          pidToPortsMapping.set(pid, []);
        }
        pidToPortsMapping.get(pid)?.push(forwardedPort.port);
      }
    });
    const configAttributes = /* @__PURE__ */ new Map();
    forwardedPorts.forEach((forwardedPort) => {
      const attributes = this.configPortsAttributes.getAttributes(forwardedPort.port, forwardedPort.host, matchingCandidates.get(forwardedPort.port)?.detail);
      if (attributes) {
        configAttributes.set(forwardedPort.port, attributes);
      }
    });
    if (this.G.length === 0 || !checkProviders) {
      return configAttributes.size > 0 ? configAttributes : void 0;
    }
    const allProviderResults = await Promise.all(this.G.flatMap((provider) => {
      return Array.from(pidToPortsMapping.entries()).map((entry) => {
        const portGroup = entry[1];
        const matchingCandidate = matchingCandidates.get(portGroup[0]);
        return provider.providePortAttributes(portGroup, matchingCandidate?.pid, matchingCandidate?.detail, CancellationToken.None);
      });
    }));
    const providedAttributes = /* @__PURE__ */ new Map();
    allProviderResults.forEach((attributes) => attributes.forEach((attribute) => {
      if (attribute) {
        providedAttributes.set(attribute.port, attribute);
      }
    }));
    if (!configAttributes && !providedAttributes) {
      return void 0;
    }
    const mergedAttributes = /* @__PURE__ */ new Map();
    forwardedPorts.forEach((forwardedPorts2) => {
      const config = configAttributes.get(forwardedPorts2.port);
      const provider = providedAttributes.get(forwardedPorts2.port);
      mergedAttributes.set(forwardedPorts2.port, {
        elevateIfNeeded: config?.elevateIfNeeded,
        label: config?.label,
        onAutoForward: config?.onAutoForward ?? $6S.providedActionToAction(provider?.autoForwardAction),
        requireLocalPort: config?.requireLocalPort,
        protocol: config?.protocol
      });
    });
    return mergedAttributes;
  }
  addAttributesProvider(provider) {
    this.G.push(provider);
  }
};
__decorate([
  $$t(1e3)
], $7S.prototype, "db", null);
$7S = __decorate([
  __param(0, $tC),
  __param(1, $jv),
  __param(2, $kl),
  __param(3, $US),
  __param(4, $bC),
  __param(5, $Zk),
  __param(6, $wn),
  __param(7, $Yv),
  __param(8, $wN),
  __param(9, $on)
], $7S);

// out-build/vs/workbench/services/remote/common/remoteExplorerService.js
var $8Sb = $Qk("remoteExplorerService");
var $9Sb = "remote.explorerType";
var $0Sb = "~remote.forwardedPorts";
var $$Sb = "~remote.forwardedPortsContainer";
var $_Sb = "remote.autoForwardPorts";
var $aTb = "remote.autoForwardPortsSource";
var $bTb = "remote.autoForwardPortsFallback";
var $cTb = "process";
var $dTb = "output";
var $eTb = "hybrid";
var TunnelType;
(function(TunnelType2) {
  TunnelType2["Candidate"] = "Candidate";
  TunnelType2["Detected"] = "Detected";
  TunnelType2["Forwarded"] = "Forwarded";
  TunnelType2["Add"] = "Add";
})(TunnelType || (TunnelType = {}));
var TunnelEditId;
(function(TunnelEditId2) {
  TunnelEditId2[TunnelEditId2["None"] = 0] = "None";
  TunnelEditId2[TunnelEditId2["New"] = 1] = "New";
  TunnelEditId2[TunnelEditId2["Label"] = 2] = "Label";
  TunnelEditId2[TunnelEditId2["LocalPort"] = 3] = "LocalPort";
})(TunnelEditId || (TunnelEditId = {}));
var getStartedWalkthrough = {
  type: "object",
  required: ["id"],
  properties: {
    id: {
      description: localize(13085, null),
      type: "string"
    }
  }
};
var remoteHelpExtPoint = $tN.registerExtensionPoint({
  extensionPoint: "remoteHelp",
  jsonSchema: {
    description: localize(13086, null),
    type: "object",
    properties: {
      "getStarted": {
        description: localize(13087, null),
        oneOf: [
          { type: "string" },
          getStartedWalkthrough
        ]
      },
      "documentation": {
        description: localize(13088, null),
        type: "string"
      },
      "feedback": {
        description: localize(13089, null),
        type: "string",
        markdownDeprecationMessage: localize(13090, null, "`reportIssue`")
      },
      "reportIssue": {
        description: localize(13091, null),
        type: "string"
      },
      "issues": {
        description: localize(13092, null),
        type: "string"
      }
    }
  }
});
var PortsEnablement;
(function(PortsEnablement2) {
  PortsEnablement2[PortsEnablement2["Disabled"] = 0] = "Disabled";
  PortsEnablement2[PortsEnablement2["ViewOnly"] = 1] = "ViewOnly";
  PortsEnablement2[PortsEnablement2["AdditionalFeatures"] = 2] = "AdditionalFeatures";
})(PortsEnablement || (PortsEnablement = {}));
var RemoteExplorerService = class RemoteExplorerService2 {
  constructor(j, k, instantiationService) {
    this.j = j;
    this.k = k;
    this.a = [];
    this.b = new $ze();
    this.onDidChangeTargetType = this.b.event;
    this.c = new $ze();
    this.onDidChangeHelpInformation = this.c.event;
    this.d = [];
    this.g = new $ze();
    this.onDidChangeEditable = this.g.event;
    this.h = new $ze();
    this.onEnabledPortsFeatures = this.h.event;
    this.i = PortsEnablement.Disabled;
    this.namedProcesses = /* @__PURE__ */ new Map();
    this.e = instantiationService.createInstance($7S);
    remoteHelpExtPoint.setHandler((extensions) => {
      this.d.push(...extensions);
      this.c.fire(extensions);
    });
  }
  get helpInformation() {
    return this.d;
  }
  set targetType(name) {
    const current = this.a.length > 0 ? this.a[0] : "";
    const newName = name.length > 0 ? name[0] : "";
    if (current !== newName) {
      this.a = name;
      this.j.store(
        $9Sb,
        this.a.toString(),
        1,
        1
        /* StorageTarget.MACHINE */
      );
      this.j.store(
        $9Sb,
        this.a.toString(),
        0,
        0
        /* StorageTarget.USER */
      );
      this.b.fire(this.a);
    }
  }
  get targetType() {
    return this.a;
  }
  get tunnelModel() {
    return this.e;
  }
  forward(tunnelProperties, attributes) {
    return this.tunnelModel.forward(tunnelProperties, attributes);
  }
  close(remote, reason) {
    return this.tunnelModel.close(remote.host, remote.port, reason);
  }
  setTunnelInformation(tunnelInformation) {
    if (tunnelInformation?.features) {
      this.k.setTunnelFeatures(tunnelInformation.features);
    }
    this.tunnelModel.addEnvironmentTunnels(tunnelInformation?.environmentTunnels);
  }
  setEditable(tunnelItem, editId, data) {
    if (!data) {
      this.f = void 0;
    } else {
      this.f = { tunnelItem, data, editId };
    }
    this.g.fire(tunnelItem ? { tunnel: tunnelItem, editId } : void 0);
  }
  getEditableData(tunnelItem, editId) {
    return this.f && (!tunnelItem && tunnelItem === this.f.tunnelItem || tunnelItem && this.f.tunnelItem?.remotePort === tunnelItem.remotePort && this.f.tunnelItem.remoteHost === tunnelItem.remoteHost && this.f.editId === editId) ? this.f.data : void 0;
  }
  setCandidateFilter(filter) {
    if (!filter) {
      return {
        dispose: () => {
        }
      };
    }
    this.tunnelModel.setCandidateFilter(filter);
    return {
      dispose: () => {
        this.tunnelModel.setCandidateFilter(void 0);
      }
    };
  }
  onFoundNewCandidates(candidates) {
    this.tunnelModel.setCandidates(candidates);
  }
  restore() {
    return this.tunnelModel.restoreForwarded();
  }
  enablePortsFeatures(viewOnly) {
    this.i = viewOnly ? PortsEnablement.ViewOnly : PortsEnablement.AdditionalFeatures;
    this.h.fire();
  }
  get portsFeaturesEnabled() {
    return this.i;
  }
};
RemoteExplorerService = __decorate([
  __param(0, $jv),
  __param(1, $tC),
  __param(2, $Pk)
], RemoteExplorerService);
$SC(
  $8Sb,
  RemoteExplorerService,
  1
  /* InstantiationType.Delayed */
);

// out-build/vs/workbench/api/browser/mainThreadTunnelService.js
var $fTb = class $fTb2 extends $3c {
  constructor(extHostContext, f, g, h3, j, m, n, r2) {
    super();
    this.f = f;
    this.g = g;
    this.h = h3;
    this.j = j;
    this.m = m;
    this.n = n;
    this.r = r2;
    this.b = false;
    this.c = /* @__PURE__ */ new Map();
    this.t = false;
    this.a = extHostContext.getProxy($yT.ExtHostTunnelService);
    this.B(g.onTunnelOpened(() => this.a.$onDidTunnelsChange()));
    this.B(g.onTunnelClosed(() => this.a.$onDidTunnelsChange()));
  }
  s() {
    return (!!this.j.getValue($_Sb) || this.g.hasTunnelProvider) && this.j.getValue($aTb) !== $dTb;
  }
  async $setRemoteTunnelService(processId) {
    this.f.namedProcesses.set(processId, "Code Extension Host");
    if (this.f.portsFeaturesEnabled === PortsEnablement.AdditionalFeatures) {
      this.a.$registerCandidateFinder(this.s());
    } else {
      this.B(this.f.onEnabledPortsFeatures(() => this.a.$registerCandidateFinder(this.s())));
    }
    this.B(this.j.onDidChangeConfiguration(async (e) => {
      if (this.f.portsFeaturesEnabled === PortsEnablement.AdditionalFeatures && (e.affectsConfiguration($_Sb) || e.affectsConfiguration($aTb))) {
        return this.a.$registerCandidateFinder(this.s());
      }
    }));
    this.B(this.g.onAddedTunnelProvider(async () => {
      if (this.f.portsFeaturesEnabled === PortsEnablement.AdditionalFeatures) {
        return this.a.$registerCandidateFinder(this.s());
      }
    }));
  }
  async $registerPortsAttributesProvider(selector, providerHandle) {
    this.c.set(providerHandle, selector);
    if (!this.t) {
      this.f.tunnelModel.addAttributesProvider(this);
      this.t = true;
    }
  }
  async $unregisterPortsAttributesProvider(providerHandle) {
    this.c.delete(providerHandle);
  }
  async providePortAttributes(ports, pid, commandLine, token) {
    if (this.c.size === 0) {
      return [];
    }
    const appropriateHandles = Array.from(this.c.entries()).filter((entry) => {
      const selector = entry[1];
      const portRange = typeof selector.portRange === "number" ? [selector.portRange, selector.portRange + 1] : selector.portRange;
      const portInRange = portRange ? ports.some((port) => portRange[0] <= port && port < portRange[1]) : true;
      const commandMatches = !selector.commandPattern || commandLine && commandLine.match(selector.commandPattern);
      return portInRange && commandMatches;
    }).map((entry) => entry[0]);
    if (appropriateHandles.length === 0) {
      return [];
    }
    return this.a.$providePortAttributes(appropriateHandles, ports, pid, commandLine, token);
  }
  async $openTunnel(tunnelOptions, source) {
    const tunnel = await this.f.forward({
      remote: tunnelOptions.remoteAddress,
      local: tunnelOptions.localAddressPort,
      name: tunnelOptions.label,
      source: {
        source: TunnelSource.Extension,
        description: source
      },
      elevateIfNeeded: false
    });
    if (!tunnel || typeof tunnel === "string") {
      return void 0;
    }
    if (!this.b && tunnelOptions.localAddressPort !== void 0 && tunnel.tunnelLocalPort !== void 0 && this.g.isPortPrivileged(tunnelOptions.localAddressPort) && tunnel.tunnelLocalPort !== tunnelOptions.localAddressPort && this.g.canElevate) {
      this.u(tunnelOptions, tunnel, source);
    }
    return TunnelDtoConverter.fromServiceTunnel(tunnel);
  }
  async u(tunnelOptions, tunnel, source) {
    return this.h.prompt(Severity2.Info, localize(2627, null, source, tunnelOptions.remoteAddress.port, tunnelOptions.localAddressPort), [{
      label: localize(2628, null, tunnel.tunnelRemotePort),
      run: async () => {
        this.b = true;
        await this.f.close({ host: tunnel.tunnelRemoteHost, port: tunnel.tunnelRemotePort }, TunnelCloseReason.Other);
        await this.f.forward({
          remote: tunnelOptions.remoteAddress,
          local: tunnelOptions.localAddressPort,
          name: tunnelOptions.label,
          source: {
            source: TunnelSource.Extension,
            description: source
          },
          elevateIfNeeded: true
        });
        this.b = false;
      }
    }]);
  }
  async $closeTunnel(remote) {
    return this.f.close(remote, TunnelCloseReason.Other);
  }
  async $getTunnels() {
    return (await this.g.tunnels).map((tunnel) => {
      return {
        remoteAddress: { port: tunnel.tunnelRemotePort, host: tunnel.tunnelRemoteHost },
        localAddress: tunnel.localAddress,
        privacy: tunnel.privacy,
        protocol: tunnel.protocol
      };
    });
  }
  async $onFoundNewCandidates(candidates) {
    this.f.onFoundNewCandidates(candidates);
  }
  async $setTunnelProvider(features, isResolver) {
    const tunnelProvider = {
      forwardPort: (tunnelOptions, tunnelCreationOptions) => {
        const forward = this.a.$forwardPort(tunnelOptions, tunnelCreationOptions);
        return forward.then((tunnelOrError) => {
          if (!tunnelOrError) {
            return void 0;
          } else if (typeof tunnelOrError === "string") {
            return tunnelOrError;
          }
          const tunnel = tunnelOrError;
          this.m.trace(`ForwardedPorts: (MainThreadTunnelService) New tunnel established by tunnel provider: ${tunnel?.remoteAddress.host}:${tunnel?.remoteAddress.port}`);
          return {
            tunnelRemotePort: tunnel.remoteAddress.port,
            tunnelRemoteHost: tunnel.remoteAddress.host,
            localAddress: typeof tunnel.localAddress === "string" ? tunnel.localAddress : $4S(tunnel.localAddress.host, tunnel.localAddress.port),
            tunnelLocalPort: typeof tunnel.localAddress !== "string" ? tunnel.localAddress.port : void 0,
            public: tunnel.public,
            privacy: tunnel.privacy,
            protocol: tunnel.protocol ?? TunnelProtocol.Http,
            dispose: async (silent) => {
              this.m.trace(`ForwardedPorts: (MainThreadTunnelService) Closing tunnel from tunnel provider: ${tunnel?.remoteAddress.host}:${tunnel?.remoteAddress.port}`);
              return this.a.$closeTunnel({ host: tunnel.remoteAddress.host, port: tunnel.remoteAddress.port }, silent);
            }
          };
        });
      }
    };
    if (features) {
      this.g.setTunnelFeatures(features);
    }
    this.g.setTunnelProvider(tunnelProvider);
    if (isResolver) {
      this.r.createKey($WS.key, true);
    }
  }
  async $setCandidateFilter() {
    this.f.setCandidateFilter((candidates) => {
      return this.a.$applyCandidateFilter(candidates);
    });
  }
  async $setCandidatePortSource(source) {
    this.n.getEnvironment().then(() => {
      switch (source) {
        case CandidatePortSource.None: {
          $Wn.as($Ht.Configuration).registerDefaultConfigurations([{ overrides: { "remote.autoForwardPorts": false } }]);
          break;
        }
        case CandidatePortSource.Output: {
          $Wn.as($Ht.Configuration).registerDefaultConfigurations([{ overrides: { "remote.autoForwardPortsSource": $dTb } }]);
          break;
        }
        case CandidatePortSource.Hybrid: {
          $Wn.as($Ht.Configuration).registerDefaultConfigurations([{ overrides: { "remote.autoForwardPortsSource": $eTb } }]);
          break;
        }
        default:
      }
    }).catch(() => {
    });
  }
};
$fTb = __decorate([
  $frb($xT.MainThreadTunnelService),
  __param(1, $8Sb),
  __param(2, $tC),
  __param(3, $PJ),
  __param(4, $kl),
  __param(5, $wn),
  __param(6, $RL),
  __param(7, $on)
], $fTb);

// out-build/vs/workbench/services/authentication/browser/authenticationService.js
function $X4(id2) {
  return `onAuthenticationRequest:${id2}`;
}
async function $Y4(secretStorageService, productService) {
  const authenticationSessionValue = await secretStorageService.get(`${productService.urlProtocol}.loginAccount`);
  if (authenticationSessionValue) {
    try {
      const authenticationSessionInfo = JSON.parse(authenticationSessionValue);
      if (authenticationSessionInfo && $zg(authenticationSessionInfo.id) && $zg(authenticationSessionInfo.accessToken) && $zg(authenticationSessionInfo.providerId)) {
        return authenticationSessionInfo;
      }
    } catch (e) {
      console.error(`Failed parsing current auth session value: ${e}`);
    }
  }
  return void 0;
}
var authenticationDefinitionSchema = {
  type: "object",
  additionalProperties: false,
  properties: {
    id: {
      type: "string",
      description: localize(12548, null)
    },
    label: {
      type: "string",
      description: localize(12549, null)
    }
  }
};
var authenticationExtPoint = $tN.registerExtensionPoint({
  extensionPoint: "authentication",
  jsonSchema: {
    description: localize(12550, null),
    type: "array",
    items: authenticationDefinitionSchema
  },
  activationEventsGenerator: (authenticationProviders, result) => {
    for (const authenticationProvider of authenticationProviders) {
      if (authenticationProvider.id) {
        result.push(`onAuthenticationRequest:${authenticationProvider.id}`);
      }
    }
  }
});
var $Z4 = class $Z42 extends $3c {
  constructor(j, authenticationAccessService, m, n) {
    super();
    this.j = j;
    this.m = m;
    this.n = n;
    this.a = this.B(new $ze());
    this.onDidRegisterAuthenticationProvider = this.a.event;
    this.b = this.B(new $ze());
    this.onDidUnregisterAuthenticationProvider = this.b.event;
    this.c = this.B(new $ze());
    this.onDidChangeSessions = this.c.event;
    this.f = this.B(new $ze());
    this.onDidChangeDeclaredProviders = this.f.event;
    this.g = /* @__PURE__ */ new Map();
    this.h = this.B(new $_c());
    this.s = [];
    this.B(authenticationAccessService.onDidChangeExtensionSessionAccess((e) => {
      this.c.fire({
        providerId: e.providerId,
        label: e.accountName,
        event: {
          added: [],
          changed: [],
          removed: []
        }
      });
    }));
    this.t();
    this.u();
  }
  get declaredProviders() {
    return this.s;
  }
  t() {
    if (!this.m.options?.authenticationProviders?.length) {
      return;
    }
    for (const provider of this.m.options.authenticationProviders) {
      this.registerDeclaredAuthenticationProvider(provider);
      this.registerAuthenticationProvider(provider.id, provider);
    }
  }
  u() {
    this.B(authenticationExtPoint.setHandler((_extensions, { added, removed }) => {
      this.n.debug(`Found authentication providers. added: ${added.length}, removed: ${removed.length}`);
      added.forEach((point) => {
        for (const provider of point.value) {
          if ($vf(provider.id)) {
            point.collector.error(localize(12551, null));
            continue;
          }
          if ($vf(provider.label)) {
            point.collector.error(localize(12552, null));
            continue;
          }
          if (!this.declaredProviders.some((p) => p.id === provider.id)) {
            this.registerDeclaredAuthenticationProvider(provider);
            this.n.debug(`Declared authentication provider: ${provider.id}`);
          } else {
            point.collector.error(localize(12553, null, provider.id));
          }
        }
      });
      const removedExtPoints = removed.flatMap((r2) => r2.value);
      removedExtPoints.forEach((point) => {
        const provider = this.declaredProviders.find((provider2) => provider2.id === point.id);
        if (provider) {
          this.unregisterDeclaredAuthenticationProvider(provider.id);
          this.n.debug(`Undeclared authentication provider: ${provider.id}`);
        }
      });
    }));
  }
  registerDeclaredAuthenticationProvider(provider) {
    if ($vf(provider.id)) {
      throw new Error(localize(12554, null));
    }
    if ($vf(provider.label)) {
      throw new Error(localize(12555, null));
    }
    if (this.declaredProviders.some((p) => p.id === provider.id)) {
      throw new Error(localize(12556, null, provider.id));
    }
    this.s.push(provider);
    this.f.fire();
  }
  unregisterDeclaredAuthenticationProvider(id2) {
    const index = this.declaredProviders.findIndex((provider) => provider.id === id2);
    if (index > -1) {
      this.declaredProviders.splice(index, 1);
    }
    this.f.fire();
  }
  isAuthenticationProviderRegistered(id2) {
    return this.g.has(id2);
  }
  registerAuthenticationProvider(id2, authenticationProvider) {
    this.g.set(id2, authenticationProvider);
    const disposableStore = new $2c();
    disposableStore.add(authenticationProvider.onDidChangeSessions((e) => this.c.fire({
      providerId: id2,
      label: authenticationProvider.label,
      event: e
    })));
    if ($Wc(authenticationProvider)) {
      disposableStore.add(authenticationProvider);
    }
    this.h.set(id2, disposableStore);
    this.a.fire({ id: id2, label: authenticationProvider.label });
  }
  unregisterAuthenticationProvider(id2) {
    const provider = this.g.get(id2);
    if (provider) {
      this.g.delete(id2);
      this.b.fire({ id: id2, label: provider.label });
    }
    this.h.deleteAndDispose(id2);
  }
  getProviderIds() {
    const providerIds = [];
    this.g.forEach((provider) => {
      providerIds.push(provider.id);
    });
    return providerIds;
  }
  getProvider(id2) {
    if (this.g.has(id2)) {
      return this.g.get(id2);
    }
    throw new Error(`No authentication provider '${id2}' is currently registered.`);
  }
  async getAccounts(id2) {
    const sessions = await this.getSessions(id2);
    const accounts = new Array();
    const seenAccounts = /* @__PURE__ */ new Set();
    for (const session of sessions) {
      if (!seenAccounts.has(session.account.label)) {
        seenAccounts.add(session.account.label);
        accounts.push(session.account);
      }
    }
    return accounts;
  }
  async getSessions(id2, scopes, account, activateImmediate = false) {
    const authProvider = this.g.get(id2) || await this.w(id2, activateImmediate);
    if (authProvider) {
      return await authProvider.getSessions(scopes, { account });
    } else {
      throw new Error(`No authentication provider '${id2}' is currently registered.`);
    }
  }
  async createSession(id2, scopes, options3) {
    const authProvider = this.g.get(id2) || await this.w(id2, !!options3?.activateImmediate);
    if (authProvider) {
      return await authProvider.createSession(scopes, {
        account: options3?.account
      });
    } else {
      throw new Error(`No authentication provider '${id2}' is currently registered.`);
    }
  }
  async removeSession(id2, sessionId) {
    const authProvider = this.g.get(id2);
    if (authProvider) {
      return authProvider.removeSession(sessionId);
    } else {
      throw new Error(`No authentication provider '${id2}' is currently registered.`);
    }
  }
  async w(providerId, activateImmediate) {
    await this.j.activateByEvent(
      $X4(providerId),
      activateImmediate ? 1 : 0
      /* ActivationKind.Normal */
    );
    let provider = this.g.get(providerId);
    if (provider) {
      return provider;
    }
    const store = new $2c();
    const didRegister = new Promise((resolve, _) => {
      store.add(Event2.once(this.onDidRegisterAuthenticationProvider)((e) => {
        if (e.id === providerId) {
          provider = this.g.get(providerId);
          if (provider) {
            resolve(provider);
          } else {
            throw new Error(`No authentication provider '${providerId}' is currently registered.`);
          }
        }
      }));
    });
    const didTimeout = new Promise((_, reject) => {
      const handle2 = setTimeout(() => {
        reject("Timed out waiting for authentication provider to register");
      }, 5e3);
      store.add($1c(() => clearTimeout(handle2)));
    });
    return Promise.race([didRegister, didTimeout]).finally(() => store.dispose());
  }
};
$Z4 = __decorate([
  __param(0, $wN),
  __param(1, $V4),
  __param(2, $M4),
  __param(3, $wn)
], $Z4);
$SC(
  $xS,
  $Z4,
  1
  /* InstantiationType.Delayed */
);

// out-build/vs/workbench/api/browser/mainThreadAuthentication.js
var $gTb = class extends $3c {
  constructor(a, id2, label3, supportsMultipleAccounts, b, onDidChangeSessionsEmitter) {
    super();
    this.a = a;
    this.id = id2;
    this.label = label3;
    this.supportsMultipleAccounts = supportsMultipleAccounts;
    this.b = b;
    this.onDidChangeSessions = onDidChangeSessionsEmitter.event;
  }
  async getSessions(scopes, options3) {
    return this.a.$getSessions(this.id, scopes, options3);
  }
  createSession(scopes, options3) {
    return this.a.$createSession(this.id, scopes, options3);
  }
  async removeSession(sessionId) {
    await this.a.$removeSession(this.id, sessionId);
    this.b.info(localize(2569, null));
  }
};
var $hTb = class $hTb2 extends $3c {
  constructor(extHostContext, f, g, h3, j, m, n, r2, s, t, u) {
    super();
    this.f = f;
    this.g = g;
    this.h = h3;
    this.j = j;
    this.m = m;
    this.n = n;
    this.r = r2;
    this.s = s;
    this.t = t;
    this.u = u;
    this.b = this.B(new $_c());
    this.c = /* @__PURE__ */ new Set();
    this.C = /* @__PURE__ */ new Set();
    this.a = extHostContext.getProxy($yT.ExtHostAuthentication);
    this.B(this.f.onDidChangeSessions((e) => {
      this.a.$onDidChangeAuthenticationSessions(e.providerId, e.label);
    }));
    this.B(this.g.onDidChangeAccountPreference((e) => {
      const providerInfo = this.f.getProvider(e.providerId);
      this.a.$onDidChangeAuthenticationSessions(providerInfo.id, providerInfo.label, e.extensionIds);
    }));
  }
  async $registerAuthenticationProvider(id2, label3, supportsMultipleAccounts) {
    if (!this.f.declaredProviders.find((p) => p.id === id2)) {
      this.u.warn(`Authentication provider ${id2} was not declared in the Extension Manifest.`);
      this.s.publicLog2("authentication.providerNotDeclared", { id: id2 });
    }
    const emitter = new $ze();
    this.b.set(id2, emitter);
    const provider = new $gTb(this.a, id2, label3, supportsMultipleAccounts, this.n, emitter);
    this.f.registerAuthenticationProvider(id2, provider);
  }
  $unregisterAuthenticationProvider(id2) {
    this.b.deleteAndDispose(id2);
    this.f.unregisterAuthenticationProvider(id2);
  }
  async $ensureProvider(id2) {
    if (!this.f.isAuthenticationProviderRegistered(id2)) {
      return await this.r.activateByEvent(
        $X4(id2),
        1
        /* ActivationKind.Immediate */
      );
    }
  }
  $sendDidChangeSessions(providerId, event) {
    const obj = this.b.get(providerId);
    if (obj instanceof $ze) {
      obj.fire(event);
    }
  }
  $removeSession(providerId, sessionId) {
    return this.f.removeSession(providerId, sessionId);
  }
  async w(provider, extensionName, recreatingSession, options3) {
    let message;
    if (provider.id.startsWith($wS)) {
      message = localize(2570, null, extensionName, provider.label);
    } else {
      message = recreatingSession ? localize(2571, null, extensionName, provider.label) : localize(2572, null, extensionName, provider.label);
    }
    const buttons = [
      {
        label: localize(2573, null),
        run() {
          return true;
        }
      }
    ];
    if (options3?.learnMore) {
      buttons.push({
        label: localize(2574, null),
        run: async () => {
          const result2 = this.w(provider, extensionName, recreatingSession, options3);
          await this.t.open(URI.revive(options3.learnMore), { allowCommands: true });
          return await result2;
        }
      });
    }
    const { result } = await this.m.prompt({
      type: severity_default.Info,
      message,
      buttons,
      detail: options3?.detail,
      cancelButton: true
    });
    return result ?? false;
  }
  async y(chosenAccountLabel, requestedAccountLabel) {
    const result = await this.m.prompt({
      message: localize(2575, null),
      detail: localize(2576, null, chosenAccountLabel, requestedAccountLabel),
      type: severity_default.Warning,
      cancelButton: true,
      buttons: [
        {
          label: localize(2577, null, chosenAccountLabel),
          run: () => chosenAccountLabel
        },
        {
          label: localize(2578, null, requestedAccountLabel),
          run: () => requestedAccountLabel
        }
      ]
    });
    if (!result.result) {
      throw new $lb();
    }
    return result.result === chosenAccountLabel;
  }
  async z(providerId, scopes, extensionId, extensionName, options3) {
    const sessions = await this.f.getSessions(providerId, scopes, options3.account, true);
    const provider = this.f.getProvider(providerId);
    if (options3.forceNewSession && options3.createIfNone) {
      throw new Error("Invalid combination of options. Please remove one of the following: forceNewSession, createIfNone");
    }
    if (options3.forceNewSession && options3.silent) {
      throw new Error("Invalid combination of options. Please remove one of the following: forceNewSession, silent");
    }
    if (options3.createIfNone && options3.silent) {
      throw new Error("Invalid combination of options. Please remove one of the following: createIfNone, silent");
    }
    if (options3.clearSessionPreference) {
      this.I(extensionId, providerId, scopes);
    }
    const matchingAccountPreferenceSession = (
      // If an account was passed in, that takes precedence over the account preference
      options3.account ? sessions[0] : this.G(extensionId, providerId, scopes, sessions)
    );
    if (!options3.forceNewSession && sessions.length) {
      if (matchingAccountPreferenceSession && this.h.isAccessAllowed(providerId, matchingAccountPreferenceSession.account.label, extensionId)) {
        return matchingAccountPreferenceSession;
      }
      if (!provider.supportsMultipleAccounts && this.h.isAccessAllowed(providerId, sessions[0].account.label, extensionId)) {
        return sessions[0];
      }
    }
    if (options3.createIfNone || options3.forceNewSession) {
      let uiOptions;
      if (typeof options3.forceNewSession === "object") {
        uiOptions = options3.forceNewSession;
      }
      const recreatingSession = !!(options3.forceNewSession && sessions.length);
      const isAllowed = await this.w(provider, extensionName, recreatingSession, uiOptions);
      if (!isAllowed) {
        throw new Error("User did not consent to login.");
      }
      let session;
      if (sessions?.length && !options3.forceNewSession) {
        session = provider.supportsMultipleAccounts && !options3.account ? await this.g.selectSession(providerId, extensionId, extensionName, scopes, sessions) : sessions[0];
      } else {
        const accountToCreate = options3.account ?? matchingAccountPreferenceSession?.account;
        do {
          session = await this.f.createSession(providerId, scopes, { activateImmediate: true, account: accountToCreate });
        } while (accountToCreate && accountToCreate.label !== session.account.label && !await this.y(session.account.label, accountToCreate.label));
      }
      this.h.updateAllowedExtensions(providerId, session.account.label, [{ id: extensionId, name: extensionName, allowed: true }]);
      this.H(extensionId, providerId, session);
      return session;
    }
    if (!matchingAccountPreferenceSession && !this.g.getAccountPreference(extensionId, providerId)) {
      const validSession = sessions.find((session) => this.h.isAccessAllowed(providerId, session.account.label, extensionId));
      if (validSession) {
        return validSession;
      }
    }
    if (!options3.silent) {
      sessions.length ? this.g.requestSessionAccess(providerId, extensionId, extensionName, scopes, sessions) : await this.g.requestNewSession(providerId, scopes, extensionId, extensionName);
    }
    return void 0;
  }
  async $getSession(providerId, scopes, extensionId, extensionName, options3) {
    this.D(extensionId, providerId, scopes);
    const session = await this.z(providerId, scopes, extensionId, extensionName, options3);
    if (session) {
      this.F(extensionId, providerId);
      this.j.addAccountUsage(providerId, session.account.label, scopes, extensionId, extensionName);
    }
    return session;
  }
  async $getAccounts(providerId) {
    const accounts = await this.f.getAccounts(providerId);
    return accounts;
  }
  D(extensionId, providerId, scopes) {
    const containsVSCodeClientIdScope = scopes.some((scope) => scope.startsWith("VSCODE_CLIENT_ID:"));
    const key2 = `${extensionId}|${providerId}|${containsVSCodeClientIdScope}`;
    if (this.C.has(key2)) {
      return;
    }
    this.C.add(key2);
    if (containsVSCodeClientIdScope) {
      this.s.publicLog2("authentication.clientIdUsage", { extensionId });
    }
  }
  F(extensionId, providerId) {
    const key2 = `${extensionId}|${providerId}`;
    if (this.c.has(key2)) {
      return;
    }
    this.c.add(key2);
    this.s.publicLog2("authentication.providerUsage", { providerId, extensionId });
  }
  //#region Account Preferences
  // TODO@TylerLeonhardt: Update this after a few iterations to no longer fallback to the session preference
  G(extensionId, providerId, scopes, sessions) {
    if (sessions.length === 0) {
      return void 0;
    }
    const accountNamePreference = this.g.getAccountPreference(extensionId, providerId);
    if (accountNamePreference) {
      const session = sessions.find((session2) => session2.account.label === accountNamePreference);
      return session;
    }
    const sessionIdPreference = this.g.getSessionPreference(providerId, extensionId, scopes);
    if (sessionIdPreference) {
      const session = sessions.find((session2) => session2.id === sessionIdPreference);
      if (session) {
        this.g.updateAccountPreference(extensionId, providerId, session.account);
        return session;
      }
    }
    return void 0;
  }
  H(extensionId, providerId, session) {
    this.g.updateAccountPreference(extensionId, providerId, session.account);
    this.g.updateSessionPreference(providerId, extensionId, session);
  }
  I(extensionId, providerId, scopes) {
    this.g.removeAccountPreference(extensionId, providerId);
    this.g.removeSessionPreference(providerId, extensionId, scopes);
  }
};
$hTb = __decorate([
  $frb($xT.MainThreadAuthentication),
  __param(1, $xS),
  __param(2, $yS),
  __param(3, $V4),
  __param(4, $RCb),
  __param(5, $Yv),
  __param(6, $PJ),
  __param(7, $wN),
  __param(8, $zv),
  __param(9, $O4),
  __param(10, $wn)
], $hTb);

// out-build/vs/workbench/contrib/timeline/common/timeline.js
var $rS = "timeline";
var TIMELINE_SERVICE_ID = "timeline";
var $sS = $Qk(TIMELINE_SERVICE_ID);

// out-build/vs/workbench/api/browser/mainThreadTimeline.js
var $iTb = class $iTb2 {
  constructor(context, c, d) {
    this.c = c;
    this.d = d;
    this.b = /* @__PURE__ */ new Map();
    this.a = context.getProxy($yT.ExtHostTimeline);
  }
  $registerTimelineProvider(provider) {
    this.c.trace(`MainThreadTimeline#registerTimelineProvider: id=${provider.id}`);
    const proxy = this.a;
    const emitters = this.b;
    let onDidChange = emitters.get(provider.id);
    if (onDidChange === void 0) {
      onDidChange = new $ze();
      emitters.set(provider.id, onDidChange);
    }
    this.d.registerTimelineProvider({
      ...provider,
      onDidChange: onDidChange.event,
      async provideTimeline(uri, options3, token) {
        return $cu(await proxy.$getTimeline(provider.id, uri, options3, token));
      },
      dispose() {
        emitters.delete(provider.id);
        onDidChange?.dispose();
      }
    });
  }
  $unregisterTimelineProvider(id2) {
    this.c.trace(`MainThreadTimeline#unregisterTimelineProvider: id=${id2}`);
    this.d.unregisterTimelineProvider(id2);
  }
  $emitTimelineChangeEvent(e) {
    this.c.trace(`MainThreadTimeline#emitChangeEvent: id=${e.id}, uri=${e.uri?.toString(true)}`);
    const emitter = this.b.get(e.id);
    emitter?.fire(e);
  }
  dispose() {
  }
};
$iTb = __decorate([
  $frb($xT.MainThreadTimeline),
  __param(1, $wn),
  __param(2, $sS)
], $iTb);

// out-build/vs/workbench/contrib/testing/common/testCoverage.js
var incId = 0;
var $HQ = class {
  constructor(result, fromTaskId, b, c) {
    this.result = result;
    this.fromTaskId = fromTaskId;
    this.b = b;
    this.c = c;
    this.a = new $Ec();
    this.didAddCoverage = $Hd(this);
    this.tree = new $lQ();
    this.associatedData = /* @__PURE__ */ new Map();
  }
  /** Gets all test IDs that were included in this test run. */
  *allPerTestIDs() {
    const seen = /* @__PURE__ */ new Set();
    for (const root of this.tree.nodes) {
      if (root.value && root.value.perTestData) {
        for (const id2 of root.value.perTestData) {
          if (!seen.has(id2)) {
            seen.add(id2);
            yield id2;
          }
        }
      }
    }
  }
  append(coverage, tx) {
    const previous = this.getComputedForUri(coverage.uri);
    const result = this.result;
    const applyDelta = (kind, node) => {
      if (!node[kind]) {
        if (coverage[kind]) {
          node[kind] = { ...coverage[kind] };
        }
      } else {
        node[kind].covered += (coverage[kind]?.covered || 0) - (previous?.[kind]?.covered || 0);
        node[kind].total += (coverage[kind]?.total || 0) - (previous?.[kind]?.total || 0);
      }
    };
    const canonical = [...this.f(
      coverage.uri,
      /* canonical = */
      true
    )];
    const chain = [];
    this.tree.mutatePath(this.f(
      coverage.uri,
      /* canonical = */
      false
    ), (node) => {
      chain.push(node);
      if (chain.length === canonical.length) {
        if (node.value) {
          const v = node.value;
          v.id = coverage.id;
          v.statement = coverage.statement;
          v.branch = coverage.branch;
          v.declaration = coverage.declaration;
        } else {
          const v = node.value = new $MQ(coverage, result, this.c);
          this.a.set(coverage.uri, v);
        }
      } else {
        if (!node.value) {
          const intermediate = $Lv(coverage);
          intermediate.id = String(incId++);
          intermediate.uri = this.g(canonical.slice(0, chain.length));
          node.value = new $KQ(intermediate, result);
        } else {
          applyDelta("statement", node.value);
          applyDelta("branch", node.value);
          applyDelta("declaration", node.value);
          node.value.didChange.trigger(tx);
        }
      }
      if (coverage.testIds) {
        node.value.perTestData ??= /* @__PURE__ */ new Set();
        for (const id2 of coverage.testIds) {
          node.value.perTestData.add(id2);
        }
      }
    });
    if (chain) {
      this.didAddCoverage.trigger(tx, chain);
    }
  }
  /**
   * Builds a new tree filtered to per-test coverage data for the given ID.
   */
  filterTreeForTest(testId) {
    const tree = new $lQ();
    for (const node of this.tree.values()) {
      if (node instanceof $MQ) {
        if (!node.perTestData?.has(testId.toString())) {
          continue;
        }
        const canonical = [...this.f(
          node.uri,
          /* canonical = */
          true
        )];
        const chain = [];
        tree.mutatePath(this.f(
          node.uri,
          /* canonical = */
          false
        ), (n) => {
          chain.push(n);
          n.value ??= new $LQ(this.g(canonical.slice(0, chain.length)), node.fromResult);
        });
      }
    }
    return tree;
  }
  /**
   * Gets coverage information for all files.
   */
  getAllFiles() {
    return this.a;
  }
  /**
   * Gets coverage information for a specific file.
   */
  getUri(uri) {
    return this.a.get(uri);
  }
  /**
   * Gets computed information for a file, including DFS-computed information
   * from child tests.
   */
  getComputedForUri(uri) {
    return this.tree.find(this.f(
      uri,
      /* canonical = */
      false
    ));
  }
  *f(uri, canconicalPath) {
    yield uri.scheme;
    yield uri.authority;
    const path = !canconicalPath && this.b.extUri.ignorePathCasing(uri) ? uri.path.toLowerCase() : uri.path;
    yield* path.split("/");
  }
  g(path) {
    return URI.from({ scheme: path[0], authority: path[1], path: path.slice(2).join("/") });
  }
};
var $IQ = (statement, branch, function_) => {
  let numerator = statement.covered;
  let denominator = statement.total;
  if (branch) {
    numerator += branch.covered;
    denominator += branch.total;
  }
  if (function_) {
    numerator += function_.covered;
    denominator += function_.total;
  }
  return denominator === 0 ? 1 : numerator / denominator;
};
var $JQ = class {
  /**
   * Gets the total coverage percent based on information provided.
   * This is based on the Clover total coverage formula
   */
  get tpc() {
    return $IQ(this.statement, this.branch, this.declaration);
  }
  constructor(coverage, fromResult) {
    this.fromResult = fromResult;
    this.didChange = $Hd(this);
    this.id = coverage.id;
    this.uri = coverage.uri;
    this.statement = coverage.statement;
    this.branch = coverage.branch;
    this.declaration = coverage.declaration;
  }
};
var $KQ = class extends $JQ {
};
var $LQ = class extends $KQ {
  constructor(uri, result) {
    super({ id: String(incId++), uri, statement: { covered: 0, total: 0 } }, result);
  }
};
var $MQ = class extends $JQ {
  /** Gets whether details are synchronously available */
  get hasSynchronousDetails() {
    return this.a instanceof Array || this.b;
  }
  constructor(coverage, fromResult, f) {
    super(coverage, fromResult);
    this.f = f;
  }
  /**
   * Gets per-line coverage details.
   */
  async detailsForTest(_testId, token = CancellationToken.None) {
    this.c ??= /* @__PURE__ */ new Map();
    const testId = _testId.toString();
    const prev = this.c.get(testId);
    if (prev) {
      return prev;
    }
    const promise = (async () => {
      try {
        return await this.f.getCoverageDetails(this.id, testId, token);
      } catch (e) {
        this.c?.delete(testId);
        throw e;
      }
    })();
    this.c.set(testId, promise);
    return promise;
  }
  /**
   * Gets per-line coverage details.
   */
  async details(token = CancellationToken.None) {
    this.a ??= this.f.getCoverageDetails(this.id, void 0, token);
    try {
      const d = await this.a;
      this.b = true;
      return d;
    } catch (e) {
      this.a = void 0;
      throw e;
    }
  }
};

// out-build/vs/workbench/contrib/testing/common/storedValue.js
var defaultSerialization = {
  deserialize: (d) => JSON.parse(d),
  serialize: (d) => JSON.stringify(d)
};
var $jTb = class $jTb2 extends $3c {
  constructor(options3, h3) {
    super();
    this.h = h3;
    this.b = options3.key;
    this.c = options3.scope;
    this.f = options3.target;
    this.a = options3.serialization ?? defaultSerialization;
    this.onDidChange = this.h.onDidChangeValue(this.c, this.b, this.q);
  }
  get(defaultValue) {
    if (this.g === void 0) {
      const value = this.h.get(this.b, this.c);
      this.g = value === void 0 ? defaultValue : this.a.deserialize(value);
    }
    return this.g;
  }
  /**
   * Persists changes to the value.
   * @param value
   */
  store(value) {
    this.g = value;
    this.h.store(this.b, this.a.serialize(value), this.c, this.f);
  }
  /**
   * Delete an element stored under the provided key from storage.
   */
  delete() {
    this.h.remove(this.b, this.c);
  }
};
$jTb = __decorate([
  __param(1, $jv)
], $jTb);

// out-build/vs/workbench/contrib/testing/common/testingContextKeys.js
var TestingContextKeys;
(function(TestingContextKeys2) {
  TestingContextKeys2.providerCount = new $nn("testing.providerCount", 0);
  TestingContextKeys2.canRefreshTests = new $nn("testing.canRefresh", false, { type: "boolean", description: localize(11324, null) });
  TestingContextKeys2.isRefreshingTests = new $nn("testing.isRefreshing", false, { type: "boolean", description: localize(11325, null) });
  TestingContextKeys2.isContinuousModeOn = new $nn("testing.isContinuousModeOn", false, { type: "boolean", description: localize(11326, null) });
  TestingContextKeys2.hasDebuggableTests = new $nn("testing.hasDebuggableTests", false, { type: "boolean", description: localize(11327, null) });
  TestingContextKeys2.hasRunnableTests = new $nn("testing.hasRunnableTests", false, { type: "boolean", description: localize(11328, null) });
  TestingContextKeys2.hasCoverableTests = new $nn("testing.hasCoverableTests", false, { type: "boolean", description: localize(11329, null) });
  TestingContextKeys2.hasNonDefaultProfile = new $nn("testing.hasNonDefaultProfile", false, { type: "boolean", description: localize(11330, null) });
  TestingContextKeys2.hasConfigurableProfile = new $nn("testing.hasConfigurableProfile", false, { type: "boolean", description: localize(11331, null) });
  TestingContextKeys2.supportsContinuousRun = new $nn("testing.supportsContinuousRun", false, { type: "boolean", description: localize(11332, null) });
  TestingContextKeys2.isParentRunningContinuously = new $nn("testing.isParentRunningContinuously", false, { type: "boolean", description: localize(11333, null) });
  TestingContextKeys2.activeEditorHasTests = new $nn("testing.activeEditorHasTests", false, { type: "boolean", description: localize(11334, null) });
  TestingContextKeys2.cursorInsideTestRange = new $nn("testing.cursorInsideTestRange", false, { type: "boolean", description: localize(11335, null) });
  TestingContextKeys2.isTestCoverageOpen = new $nn("testing.isTestCoverageOpen", false, { type: "boolean", description: localize(11336, null) });
  TestingContextKeys2.hasPerTestCoverage = new $nn("testing.hasPerTestCoverage", false, { type: "boolean", description: localize(11337, null) });
  TestingContextKeys2.isCoverageFilteredToTest = new $nn("testing.isCoverageFilteredToTest", false, { type: "boolean", description: localize(11338, null) });
  TestingContextKeys2.coverageToolbarEnabled = new $nn("testing.coverageToolbarEnabled", true, { type: "boolean", description: localize(11339, null) });
  TestingContextKeys2.inlineCoverageEnabled = new $nn("testing.inlineCoverageEnabled", false, { type: "boolean", description: localize(11340, null) });
  TestingContextKeys2.canGoToRelatedCode = new $nn("testing.canGoToRelatedCode", false, { type: "boolean", description: localize(11341, null) });
  TestingContextKeys2.canGoToRelatedTest = new $nn("testing.canGoToRelatedTest", false, { type: "boolean", description: localize(11342, null) });
  TestingContextKeys2.peekHasStack = new $nn("testing.peekHasStack", false, { type: "boolean", description: localize(11343, null) });
  TestingContextKeys2.capabilityToContextKey = {
    [
      2
      /* TestRunProfileBitset.Run */
    ]: TestingContextKeys2.hasRunnableTests,
    [
      8
      /* TestRunProfileBitset.Coverage */
    ]: TestingContextKeys2.hasCoverableTests,
    [
      4
      /* TestRunProfileBitset.Debug */
    ]: TestingContextKeys2.hasDebuggableTests,
    [
      16
      /* TestRunProfileBitset.HasNonDefaultProfile */
    ]: TestingContextKeys2.hasNonDefaultProfile,
    [
      32
      /* TestRunProfileBitset.HasConfigurable */
    ]: TestingContextKeys2.hasConfigurableProfile,
    [
      64
      /* TestRunProfileBitset.SupportsContinuousRun */
    ]: TestingContextKeys2.supportsContinuousRun
  };
  TestingContextKeys2.hasAnyResults = new $nn("testing.hasAnyResults", false);
  TestingContextKeys2.viewMode = new $nn(
    "testing.explorerViewMode",
    "list"
    /* TestExplorerViewMode.List */
  );
  TestingContextKeys2.viewSorting = new $nn(
    "testing.explorerViewSorting",
    "location"
    /* TestExplorerViewSorting.ByLocation */
  );
  TestingContextKeys2.isRunning = new $nn("testing.isRunning", false);
  TestingContextKeys2.isInPeek = new $nn("testing.isInPeek", false);
  TestingContextKeys2.isPeekVisible = new $nn("testing.isPeekVisible", false);
  TestingContextKeys2.peekItemType = new $nn("peekItemType", void 0, {
    type: "string",
    description: localize(11344, null)
  });
  TestingContextKeys2.controllerId = new $nn("controllerId", void 0, {
    type: "string",
    description: localize(11345, null)
  });
  TestingContextKeys2.testItemExtId = new $nn("testId", void 0, {
    type: "string",
    description: localize(11346, null)
  });
  TestingContextKeys2.testItemHasUri = new $nn("testing.testItemHasUri", false, {
    type: "boolean",
    description: localize(11347, null)
  });
  TestingContextKeys2.testItemIsHidden = new $nn("testing.testItemIsHidden", false, {
    type: "boolean",
    description: localize(11348, null)
  });
  TestingContextKeys2.testMessageContext = new $nn("testMessage", void 0, {
    type: "string",
    description: localize(11349, null)
  });
  TestingContextKeys2.testResultOutdated = new $nn("testResultOutdated", void 0, {
    type: "boolean",
    description: localize(11350, null)
  });
  TestingContextKeys2.testResultState = new $nn("testResultState", void 0, {
    type: "string",
    description: localize(11351, null)
  });
  TestingContextKeys2.testProfileContextGroup = new $nn("testing.profile.context.group", void 0, {
    type: "string",
    description: localize(11352, null)
  });
})(TestingContextKeys || (TestingContextKeys = {}));

// out-build/vs/workbench/contrib/testing/common/testProfileService.js
var $wTb = $Qk("testProfileService");
var $xTb = (profile, test) => profile.controllerId === test.controllerId && ($mQ.isRoot(test.item.extId) || !profile.tag || test.item.tags.includes(profile.tag));
var sorter2 = (a, b) => {
  if (a.isDefault !== b.isDefault) {
    return a.isDefault ? -1 : 1;
  }
  return a.label.localeCompare(b.label);
};
var $yTb = (capabilities) => [
  [TestingContextKeys.hasRunnableTests.key, (capabilities & 2) !== 0],
  [TestingContextKeys.hasDebuggableTests.key, (capabilities & 4) !== 0],
  [TestingContextKeys.hasCoverableTests.key, (capabilities & 8) !== 0]
];
var $zTb = class $zTb2 extends $3c {
  constructor(contextKeyService, storageService) {
    super();
    this.h = this.B(new $ze());
    this.j = /* @__PURE__ */ new Map();
    this.onDidChange = this.h.event;
    storageService.remove(
      "testingPreferredProfiles",
      1
      /* StorageScope.WORKSPACE */
    );
    this.f = this.B(new $jTb({
      key: "testingPreferredProfiles2",
      scope: 1,
      target: 1
    }, storageService));
    this.g = {
      [
        2
        /* TestRunProfileBitset.Run */
      ]: TestingContextKeys.hasRunnableTests.bindTo(contextKeyService),
      [
        4
        /* TestRunProfileBitset.Debug */
      ]: TestingContextKeys.hasDebuggableTests.bindTo(contextKeyService),
      [
        8
        /* TestRunProfileBitset.Coverage */
      ]: TestingContextKeys.hasCoverableTests.bindTo(contextKeyService),
      [
        16
        /* TestRunProfileBitset.HasNonDefaultProfile */
      ]: TestingContextKeys.hasNonDefaultProfile.bindTo(contextKeyService),
      [
        32
        /* TestRunProfileBitset.HasConfigurable */
      ]: TestingContextKeys.hasConfigurableProfile.bindTo(contextKeyService),
      [
        64
        /* TestRunProfileBitset.SupportsContinuousRun */
      ]: TestingContextKeys.supportsContinuousRun.bindTo(contextKeyService)
    };
    this.m();
  }
  /** @inheritdoc */
  addProfile(controller, profile) {
    const previousExplicitDefaultValue = this.f.get()?.[controller.id]?.[profile.profileId];
    const extended = {
      ...profile,
      isDefault: previousExplicitDefaultValue ?? profile.isDefault,
      wasInitiallyDefault: profile.isDefault
    };
    let record = this.j.get(profile.controllerId);
    if (record) {
      record.profiles.push(extended);
      record.profiles.sort(sorter2);
    } else {
      record = {
        profiles: [extended],
        controller
      };
      this.j.set(profile.controllerId, record);
    }
    this.m();
    this.h.fire();
  }
  /** @inheritdoc */
  updateProfile(controllerId, profileId, update) {
    const ctrl = this.j.get(controllerId);
    if (!ctrl) {
      return;
    }
    const profile = ctrl.profiles.find((c) => c.controllerId === controllerId && c.profileId === profileId);
    if (!profile) {
      return;
    }
    Object.assign(profile, update);
    ctrl.profiles.sort(sorter2);
    if (update.isDefault !== void 0) {
      const map = $Lv(this.f.get({}));
      setIsDefault(map, profile, update.isDefault);
      this.f.store(map);
    }
    this.h.fire();
  }
  /** @inheritdoc */
  configure(controllerId, profileId) {
    this.j.get(controllerId)?.controller.configureRunProfile(profileId);
  }
  /** @inheritdoc */
  removeProfile(controllerId, profileId) {
    const ctrl = this.j.get(controllerId);
    if (!ctrl) {
      return;
    }
    if (!profileId) {
      this.j.delete(controllerId);
      this.h.fire();
      return;
    }
    const index = ctrl.profiles.findIndex((c) => c.profileId === profileId);
    if (index === -1) {
      return;
    }
    ctrl.profiles.splice(index, 1);
    this.m();
    this.h.fire();
  }
  /** @inheritdoc */
  capabilitiesForTest(test) {
    const ctrl = this.j.get($mQ.root(test.extId));
    if (!ctrl) {
      return 0;
    }
    let capabilities = 0;
    for (const profile of ctrl.profiles) {
      if (!profile.tag || test.tags.includes(profile.tag)) {
        capabilities |= capabilities & profile.group ? 16 : profile.group;
      }
    }
    return capabilities;
  }
  /** @inheritdoc */
  all() {
    return this.j.values();
  }
  /** @inheritdoc */
  getControllerProfiles(profileId) {
    return this.j.get(profileId)?.profiles ?? [];
  }
  /** @inheritdoc */
  getGroupDefaultProfiles(group2, controllerId) {
    const allProfiles = controllerId ? this.j.get(controllerId)?.profiles || [] : [...Iterable.flatMap(this.j.values(), (c) => c.profiles)];
    const defaults = allProfiles.filter((c) => c.group === group2 && c.isDefault);
    if (defaults.length === 0) {
      const first = allProfiles.find((p) => p.group === group2);
      if (first) {
        defaults.push(first);
      }
    }
    return defaults;
  }
  /** @inheritdoc */
  setGroupDefaultProfiles(group2, profiles2) {
    const next = {};
    for (const ctrl of this.j.values()) {
      next[ctrl.controller.id] = {};
      for (const profile of ctrl.profiles) {
        if (profile.group !== group2) {
          continue;
        }
        setIsDefault(next, profile, profiles2.some((p) => p.profileId === profile.profileId));
      }
      for (const profile of ctrl.profiles) {
        if (profile.group === group2) {
          continue;
        }
        const matching = ctrl.profiles.find((p) => p.group === group2 && p.label === profile.label);
        if (matching) {
          setIsDefault(next, profile, matching.isDefault);
        }
      }
      ctrl.profiles.sort(sorter2);
    }
    this.f.store(next);
    this.h.fire();
  }
  getDefaultProfileForTest(group2, test) {
    return this.getControllerProfiles(test.controllerId).find((p) => (p.group & group2) !== 0 && $xTb(p, test));
  }
  m() {
    let allCapabilities = 0;
    for (const { profiles: profiles2 } of this.j.values()) {
      for (const profile of profiles2) {
        allCapabilities |= allCapabilities & profile.group ? 16 : profile.group;
        allCapabilities |= profile.supportsContinuousRun ? 64 : 0;
      }
    }
    for (const group2 of $pQ) {
      this.g[group2].set((allCapabilities & group2) !== 0);
    }
  }
};
$zTb = __decorate([
  __param(0, $on),
  __param(1, $jv)
], $zTb);
var setIsDefault = (map, profile, isDefault) => {
  profile.isDefault = isDefault;
  map[profile.controllerId] ??= {};
  if (profile.isDefault !== profile.wasInitiallyDefault) {
    map[profile.controllerId][profile.profileId] = profile.isDefault;
  } else {
    delete map[profile.controllerId][profile.profileId];
  }
};

// out-build/vs/workbench/contrib/testing/common/testingStates.js
var $xQ = {
  [
    2
    /* TestResultState.Running */
  ]: 6,
  [
    6
    /* TestResultState.Errored */
  ]: 5,
  [
    4
    /* TestResultState.Failed */
  ]: 4,
  [
    1
    /* TestResultState.Queued */
  ]: 3,
  [
    3
    /* TestResultState.Passed */
  ]: 2,
  [
    0
    /* TestResultState.Unset */
  ]: 0,
  [
    5
    /* TestResultState.Skipped */
  ]: 1
};
var $yQ = (s) => s === 6 || s === 4;
var $zQ = (s) => s === 6 || s === 4 || s === 3;
var $AQ = $Xv($xQ, (priority, stateStr) => {
  const state = Number(stateStr);
  return { statusNode: true, state, priority };
});
var $BQ = (a, b) => $xQ[b] - $xQ[a];
var $CQ = (...states) => {
  switch (states.length) {
    case 0:
      return 0;
    case 1:
      return states[0];
    case 2:
      return $xQ[states[0]] > $xQ[states[1]] ? states[0] : states[1];
    default: {
      let max = states[0];
      for (let i2 = 1; i2 < states.length; i2++) {
        if ($xQ[max] < $xQ[states[i2]]) {
          max = states[i2];
        }
      }
      return max;
    }
  }
};
var $DQ = Object.keys($xQ).map((s) => Number(s)).sort($BQ);
var $EQ = {
  [
    3
    /* TestResultState.Passed */
  ]: 0,
  [
    5
    /* TestResultState.Skipped */
  ]: 1,
  [
    4
    /* TestResultState.Failed */
  ]: 2,
  [
    6
    /* TestResultState.Errored */
  ]: 3
};
var $FQ = () => {
  return new Uint32Array($DQ.length);
};

// out-build/vs/workbench/contrib/testing/common/getComputedState.js
var isDurationAccessor = (accessor) => "getOwnDuration" in accessor;
var getComputedState = (accessor, node, force = false) => {
  let computed = accessor.getCurrentComputedState(node);
  if (computed === void 0 || force) {
    computed = accessor.getOwnState(node) ?? 0;
    let childrenCount = 0;
    const stateMap = $FQ();
    for (const child of accessor.getChildren(node)) {
      const childComputed = getComputedState(accessor, child);
      childrenCount++;
      stateMap[childComputed]++;
      computed = childComputed === 5 && computed === 0 ? 5 : $CQ(computed, childComputed);
    }
    if (childrenCount > LARGE_NODE_THRESHOLD) {
      largeNodeChildrenStates.set(node, stateMap);
    }
    accessor.setComputedState(node, computed);
  }
  return computed;
};
var getComputedDuration = (accessor, node, force = false) => {
  let computed = accessor.getCurrentComputedDuration(node);
  if (computed === void 0 || force) {
    const own = accessor.getOwnDuration(node);
    if (own !== void 0) {
      computed = own;
    } else {
      computed = void 0;
      for (const child of accessor.getChildren(node)) {
        const d = getComputedDuration(accessor, child);
        if (d !== void 0) {
          computed = (computed || 0) + d;
        }
      }
    }
    accessor.setComputedDuration(node, computed);
  }
  return computed;
};
var LARGE_NODE_THRESHOLD = 64;
var largeNodeChildrenStates = /* @__PURE__ */ new WeakMap();
var $GQ = (accessor, node, explicitNewComputedState, refreshDuration = true) => {
  const oldState = accessor.getCurrentComputedState(node);
  const oldPriority = $xQ[oldState];
  const newState = explicitNewComputedState ?? getComputedState(accessor, node, true);
  const newPriority = $xQ[newState];
  const toUpdate = /* @__PURE__ */ new Set();
  if (newPriority !== oldPriority) {
    accessor.setComputedState(node, newState);
    toUpdate.add(node);
    let moveFromState = oldState;
    let moveToState = newState;
    for (const parent of accessor.getParents(node)) {
      const lnm = largeNodeChildrenStates.get(parent);
      if (lnm) {
        lnm[moveFromState]--;
        lnm[moveToState]++;
      }
      const prev = accessor.getCurrentComputedState(parent);
      if (newPriority > oldPriority) {
        if (prev !== void 0 && $xQ[prev] >= newPriority) {
          break;
        }
        if (lnm && lnm[moveToState] > 1) {
          break;
        }
        accessor.setComputedState(parent, newState);
        toUpdate.add(parent);
      } else {
        if (prev === void 0 || $xQ[prev] > oldPriority) {
          break;
        }
        if (lnm && lnm[moveFromState] > 0) {
          break;
        }
        moveToState = getComputedState(accessor, parent, true);
        accessor.setComputedState(parent, moveToState);
        toUpdate.add(parent);
      }
      moveFromState = prev;
    }
  }
  if (isDurationAccessor(accessor) && refreshDuration) {
    for (const parent of Iterable.concat(Iterable.single(node), accessor.getParents(node))) {
      const oldDuration = accessor.getCurrentComputedDuration(parent);
      const newDuration = getComputedDuration(accessor, parent, true);
      if (oldDuration === newDuration) {
        break;
      }
      accessor.setComputedDuration(parent, newDuration);
      toUpdate.add(parent);
    }
  }
  return toUpdate;
};

// out-build/vs/workbench/contrib/testing/common/testResult.js
var emptyRawOutput = {
  buffers: [],
  length: 0,
  onDidWriteData: Event2.None,
  endPromise: Promise.resolve(),
  getRange: () => $Ci.alloc(0),
  getRangeIter: () => []
};
var $OQ = class {
  constructor() {
    this.a = new $ze();
    this.c = new $gi();
    this.d = 0;
    this.onDidWriteData = this.a.event;
    this.endPromise = this.c.p;
    this.buffers = [];
  }
  /** @inheritdoc */
  get length() {
    return this.d;
  }
  /** @inheritdoc */
  getRange(start, length) {
    const buf = $Ci.alloc(length);
    let bufLastWrite = 0;
    for (const chunk of this.getRangeIter(start, length)) {
      buf.buffer.set(chunk.buffer, bufLastWrite);
      bufLastWrite += chunk.byteLength;
    }
    return bufLastWrite < length ? buf.slice(0, bufLastWrite) : buf;
  }
  /** @inheritdoc */
  *getRangeIter(start, length) {
    let soFar = 0;
    let internalLastRead = 0;
    for (const b of this.buffers) {
      if (internalLastRead + b.byteLength <= start) {
        internalLastRead += b.byteLength;
        continue;
      }
      const bstart = Math.max(0, start - internalLastRead);
      const bend = Math.min(b.byteLength, bstart + length - soFar);
      yield b.slice(bstart, bend);
      soFar += bend - bstart;
      internalLastRead += b.byteLength;
      if (soFar === length) {
        break;
      }
    }
  }
  /**
   * Appends data to the output, returning the byte range where the data can be found.
   */
  append(data, marker) {
    const offset = this.d;
    let length = data.byteLength;
    if (marker === void 0) {
      this.e(data);
      return { offset, length };
    }
    let TrimBytes;
    (function(TrimBytes2) {
      TrimBytes2[TrimBytes2["CR"] = 13] = "CR";
      TrimBytes2[TrimBytes2["LF"] = 10] = "LF";
    })(TrimBytes || (TrimBytes = {}));
    const start = $Ci.fromString(getMarkCode(marker, true));
    const end = $Ci.fromString(getMarkCode(marker, false));
    length += start.byteLength + end.byteLength;
    this.e(start);
    let trimLen = data.byteLength;
    for (; trimLen > 0; trimLen--) {
      const last = data.buffer[trimLen - 1];
      if (last !== 13 && last !== 10) {
        break;
      }
    }
    this.e(data.slice(0, trimLen));
    this.e(end);
    this.e(data.slice(trimLen));
    return { offset, length };
  }
  e(data) {
    if (data.byteLength === 0) {
      return;
    }
    this.buffers.push(data);
    this.a.fire(data);
    this.d += data.byteLength;
  }
  /** Signals the output has ended. */
  end() {
    this.c.complete();
  }
};
var $PQ = function* (results, item) {
  for (const id2 of $mQ.fromString(item.item.extId).idsToRoot()) {
    yield results.getStateById(id2.toString());
  }
};
var $QQ = (counts) => {
  for (const state of $DQ) {
    if (counts[state] > 0) {
      return state;
    }
  }
  return 0;
};
var getMarkCode = (marker, start) => `\x1B]633;SetMark;Id=${$rQ(marker, start)};Hidden\x07`;
var itemToNode = (controllerId, item, parent) => ({
  controllerId,
  expand: 0,
  item: { ...item },
  children: [],
  tasks: [],
  ownComputedState: 0,
  computedState: 0
});
var TestResultItemChangeReason;
(function(TestResultItemChangeReason2) {
  TestResultItemChangeReason2[TestResultItemChangeReason2["ComputedStateChange"] = 0] = "ComputedStateChange";
  TestResultItemChangeReason2[TestResultItemChangeReason2["OwnStateChange"] = 1] = "OwnStateChange";
  TestResultItemChangeReason2[TestResultItemChangeReason2["NewMessage"] = 2] = "NewMessage";
})(TestResultItemChangeReason || (TestResultItemChangeReason = {}));
var $RQ = class $RQ2 extends $3c {
  /**
   * @inheritdoc
   */
  get completedAt() {
    return this.n;
  }
  /**
   * @inheritdoc
   */
  get tests() {
    return this.j.values();
  }
  /** Gets an included test item by ID. */
  getTestById(id2) {
    return this.j.get(id2)?.item;
  }
  constructor(id2, persist, request, insertOrder, w) {
    super();
    this.id = id2;
    this.persist = persist;
    this.request = request;
    this.insertOrder = insertOrder;
    this.w = w;
    this.a = this.B(new $ze());
    this.f = this.B(new $ze());
    this.g = this.B(new $ze());
    this.h = this.B(new $ze());
    this.j = /* @__PURE__ */ new Map();
    this.m = 0;
    this.startedAt = Date.now();
    this.onChange = this.h.event;
    this.onComplete = this.a.event;
    this.onNewTask = this.f.event;
    this.onEndTask = this.g.event;
    this.tasks = [];
    this.name = localize(11353, null, (/* @__PURE__ */ new Date()).toLocaleString($z));
    this.counts = $FQ();
    this.u = {
      getOwnState: (i2) => i2.ownComputedState,
      getCurrentComputedState: (i2) => i2.computedState,
      setComputedState: (i2, s) => i2.computedState = s,
      getChildren: (i2) => i2.children,
      getParents: (i2) => {
        const { j: testByExtId } = this;
        return function* () {
          const parentId = $mQ.fromString(i2.item.extId).parentId;
          if (parentId) {
            for (const id3 of parentId.idsToRoot()) {
              yield testByExtId.get(id3.toString());
            }
          }
        }();
      }
    };
    this.F = new $sf(() => ({
      id: this.id,
      completedAt: this.completedAt,
      tasks: this.tasks.map((t) => ({ id: t.id, name: t.name, ctrlId: t.ctrlId, hasCoverage: !!t.coverage.get() })),
      name: this.name,
      request: this.request,
      items: [...this.j.values()].map(TestResultItem.serializeWithoutMessages)
    }));
    this.G = new $sf(() => ({
      id: this.id,
      completedAt: this.completedAt,
      tasks: this.tasks.map((t) => ({ id: t.id, name: t.name, ctrlId: t.ctrlId, hasCoverage: !!t.coverage.get() })),
      name: this.name,
      request: this.request,
      items: [...this.j.values()].map(TestResultItem.serialize)
    }));
  }
  /**
   * @inheritdoc
   */
  getStateById(extTestId) {
    return this.j.get(extTestId);
  }
  /**
   * Appends output that occurred during the test run.
   */
  appendOutput(output, taskId, location3, testId) {
    const preview = output.byteLength > 100 ? output.slice(0, 100).toString() + "\u2026" : output.toString();
    let marker;
    if (testId || location3) {
      marker = this.m++;
    }
    const index = this.D(taskId);
    const task = this.tasks[index];
    const { offset, length } = task.output.append(output, marker);
    const message = {
      location: location3,
      message: preview,
      offset,
      length,
      marker,
      type: 1
    };
    const test = testId && this.j.get(testId);
    if (test) {
      test.tasks[index].messages.push(message);
      this.h.fire({ item: test, result: this, reason: 2, message });
    } else {
      task.otherMessages.push(message);
    }
  }
  /**
   * Adds a new run task to the results.
   */
  addTask(task) {
    this.tasks.push({ ...task, coverage: $he(this, void 0), otherMessages: [], output: new $OQ() });
    for (const test of this.tests) {
      test.tasks.push({
        duration: void 0,
        messages: [],
        state: 0
        /* TestResultState.Unset */
      });
    }
    this.f.fire(this.tasks.length - 1);
  }
  /**
   * Add the chain of tests to the run. The first test in the chain should
   * be either a test root, or a previously-known test.
   */
  addTestChainToRun(controllerId, chain) {
    let parent = this.j.get(chain[0].extId);
    if (!parent) {
      parent = this.C(controllerId, chain[0], null);
    }
    for (let i2 = 1; i2 < chain.length; i2++) {
      parent = this.C(controllerId, chain[i2], parent.item.extId);
    }
    return void 0;
  }
  /**
   * Updates the state of the test by its internal ID.
   */
  updateState(testId, taskId, state, duration) {
    const entry = this.j.get(testId);
    if (!entry) {
      return;
    }
    const index = this.D(taskId);
    const oldTerminalStatePrio = $EQ[entry.tasks[index].state];
    const newTerminalStatePrio = $EQ[state];
    if (oldTerminalStatePrio !== void 0 && (newTerminalStatePrio === void 0 || newTerminalStatePrio < oldTerminalStatePrio)) {
      return;
    }
    this.z(entry, index, state, duration);
  }
  /**
   * Appends a message for the test in the run.
   */
  appendMessage(testId, taskId, message) {
    const entry = this.j.get(testId);
    if (!entry) {
      return;
    }
    entry.tasks[this.D(taskId)].messages.push(message);
    this.h.fire({ item: entry, result: this, reason: 2, message });
  }
  /**
   * Marks the task in the test run complete.
   */
  markTaskComplete(taskId) {
    const index = this.D(taskId);
    const task = this.tasks[index];
    task.running = false;
    task.output.end();
    this.y(
      0,
      taskId,
      (t) => t.state === 1 || t.state === 2
      /* TestResultState.Running */
    );
    this.g.fire(index);
  }
  /**
   * Notifies the service that all tests are complete.
   */
  markComplete() {
    if (this.n !== void 0) {
      throw new Error("cannot complete a test result multiple times");
    }
    for (const task of this.tasks) {
      if (task.running) {
        this.markTaskComplete(task.id);
      }
    }
    this.n = Date.now();
    this.a.fire();
    this.w.publicLog2("test.outcomes", {
      failures: this.counts[
        6
        /* TestResultState.Errored */
      ] + this.counts[
        4
        /* TestResultState.Failed */
      ],
      passes: this.counts[
        3
        /* TestResultState.Passed */
      ],
      controller: this.request.targets.map((t) => t.controllerId).join(",")
    });
  }
  /**
   * Marks the test and all of its children in the run as retired.
   */
  markRetired(testIds) {
    for (const [id2, test] of this.j) {
      if (!test.retired && (!testIds || testIds.hasKeyOrParent($mQ.fromString(id2).path))) {
        test.retired = true;
        this.h.fire({ reason: 0, item: test, result: this });
      }
    }
  }
  /**
   * @inheritdoc
   */
  toJSON() {
    return this.completedAt && this.persist ? this.F.value : void 0;
  }
  toJSONWithMessages() {
    return this.completedAt && this.persist ? this.G.value : void 0;
  }
  /**
   * Updates all tests in the collection to the given state.
   */
  y(state, taskId, when) {
    const index = this.D(taskId);
    for (const test of this.j.values()) {
      if (when(test.tasks[index], test)) {
        this.z(test, index, state);
      }
    }
  }
  z(entry, taskIndex, newState, newOwnDuration) {
    const previousOwnComputed = entry.ownComputedState;
    const previousOwnDuration = entry.ownDuration;
    const changeEvent = {
      item: entry,
      result: this,
      reason: 1,
      previousState: previousOwnComputed,
      previousOwnDuration
    };
    entry.tasks[taskIndex].state = newState;
    if (newOwnDuration !== void 0) {
      entry.tasks[taskIndex].duration = newOwnDuration;
      entry.ownDuration = Math.max(entry.ownDuration || 0, newOwnDuration);
    }
    const newOwnComputed = $CQ(...entry.tasks.map((t) => t.state));
    if (newOwnComputed === previousOwnComputed) {
      if (newOwnDuration !== previousOwnDuration) {
        this.h.fire(changeEvent);
      }
      return;
    }
    entry.ownComputedState = newOwnComputed;
    this.counts[previousOwnComputed]--;
    this.counts[newOwnComputed]++;
    $GQ(this.u, entry).forEach((t) => this.h.fire(t === entry ? changeEvent : {
      item: t,
      result: this,
      reason: 0
    }));
  }
  C(controllerId, item, parent) {
    const node = itemToNode(controllerId, item, parent);
    this.j.set(item.extId, node);
    this.counts[
      0
      /* TestResultState.Unset */
    ]++;
    if (parent) {
      this.j.get(parent)?.children.push(node);
    }
    if (this.tasks.length) {
      for (let i2 = 0; i2 < this.tasks.length; i2++) {
        node.tasks.push({
          duration: void 0,
          messages: [],
          state: 0
          /* TestResultState.Unset */
        });
      }
    }
    return node;
  }
  D(taskId) {
    const index = this.tasks.findIndex((t) => t.id === taskId);
    if (index === -1) {
      throw new Error(`Unknown task ${taskId} in updateState`);
    }
    return index;
  }
};
$RQ = __decorate([
  __param(4, $zv)
], $RQ);
var $SQ = class {
  /**
   * @inheritdoc
   */
  get tests() {
    return this.a.values();
  }
  constructor(identity, c, d = true) {
    this.c = c;
    this.d = d;
    this.counts = $FQ();
    this.a = /* @__PURE__ */ new Map();
    this.id = c.id;
    this.completedAt = c.completedAt;
    this.tasks = c.tasks.map((task, i2) => ({
      id: task.id,
      name: task.name || localize(11354, null),
      ctrlId: task.ctrlId,
      running: false,
      coverage: $he(this, void 0),
      output: emptyRawOutput,
      otherMessages: []
    }));
    this.name = c.name;
    this.request = c.request;
    for (const item of c.items) {
      const de = TestResultItem.deserialize(identity, item);
      this.counts[de.ownComputedState]++;
      this.a.set(item.item.extId, de);
    }
  }
  /**
   * @inheritdoc
   */
  getStateById(extTestId) {
    return this.a.get(extTestId);
  }
  /**
   * @inheritdoc
   */
  toJSON() {
    return this.d ? this.c : void 0;
  }
  /**
   * @inheritdoc
   */
  toJSONWithMessages() {
    return this.toJSON();
  }
};

// out-build/vs/workbench/contrib/testing/common/testResultStorage.js
var $ATb = 128;
var RETAIN_MIN_RESULTS = 16;
var RETAIN_MAX_BYTES = 1024 * 128;
var CLEANUP_PROBABILITY = 0.2;
var $BTb = $Qk("ITestResultStorage");
var currentRevision = 1;
var $CTb = class $CTb2 extends $3c {
  constructor(b, c, f) {
    super();
    this.b = b;
    this.c = c;
    this.f = f;
    this.a = this.B(new $jTb({
      key: "storedTestResults",
      scope: 1,
      target: 1
      /* StorageTarget.MACHINE */
    }, this.c));
  }
  /**
   * @override
   */
  async read() {
    const results = await Promise.all(this.a.get([]).map(async (rec) => {
      if (rec.rev !== currentRevision) {
        return void 0;
      }
      try {
        const contents = await this.g(rec.id);
        if (!contents) {
          return void 0;
        }
        return { rec, result: new $SQ(this.b, contents) };
      } catch (e) {
        this.f.warn(`Error deserializing stored test result ${rec.id}`, e);
        return void 0;
      }
    }));
    const defined = results.filter($Hg);
    if (defined.length !== results.length) {
      this.a.store(defined.map(({ rec }) => rec));
    }
    return defined.map(({ result }) => result);
  }
  /**
   * @override
   */
  getResultOutputWriter(resultId) {
    const stream = $Si();
    this.r(resultId, stream);
    return stream;
  }
  /**
   * @override
   */
  async persist(results) {
    const toDelete = new Map(this.a.get([]).map(({ id: id2, bytes }) => [id2, bytes]));
    const toStore = [];
    const todo = [];
    let budget = RETAIN_MAX_BYTES;
    for (let i2 = 0; i2 < results.length && i2 < $ATb && (budget > 0 || toStore.length < RETAIN_MIN_RESULTS); i2++) {
      const result = results[i2];
      const existingBytes = toDelete.get(result.id);
      if (existingBytes !== void 0) {
        toDelete.delete(result.id);
        toStore.push({ id: result.id, rev: currentRevision, bytes: existingBytes });
        budget -= existingBytes;
        continue;
      }
      const obj = result.toJSON();
      if (!obj) {
        continue;
      }
      const contents = $Ci.fromString(JSON.stringify(obj));
      todo.push(this.n(result.id, obj));
      toStore.push({ id: result.id, rev: currentRevision, bytes: contents.byteLength });
      budget -= contents.byteLength;
    }
    for (const id2 of toDelete.keys()) {
      todo.push(this.m(id2).catch(() => void 0));
    }
    this.a.store(toStore);
    await Promise.all(todo);
  }
};
$CTb = __decorate([
  __param(0, $vl),
  __param(1, $jv),
  __param(2, $wn)
], $CTb);
var $ETb = class $ETb2 extends $CTb {
  constructor(uriIdentityService, storageService, logService, workspaceContext, u, environmentService) {
    super(uriIdentityService, storageService, logService);
    this.u = u;
    this.t = URI.joinPath(environmentService.workspaceStorageHome, workspaceContext.getWorkspace().id, "testResults");
  }
  async g(id2) {
    const contents = await this.u.readFile(this.H(id2));
    return JSON.parse(contents.value.toString());
  }
  n(id2, contents) {
    return this.u.writeFile(this.H(id2), $Ci.fromString(JSON.stringify(contents)));
  }
  m(id2) {
    return this.u.del(this.H(id2)).catch(() => void 0);
  }
  async j(id2, offset, length) {
    try {
      const { value } = await this.u.readFile(this.I(id2), { position: offset, length });
      return value;
    } catch {
      return $Ci.alloc(0);
    }
  }
  async h(id2) {
    try {
      const { value } = await this.u.readFileStream(this.I(id2));
      return value;
    } catch {
      return $Qi($Ci.alloc(0));
    }
  }
  async r(id2, input) {
    await this.u.createFile(this.I(id2), input);
  }
  /**
   * @inheritdoc
   */
  async persist(results) {
    await super.persist(results);
    if (Math.random() < CLEANUP_PROBABILITY) {
      await this.G();
    }
  }
  /**
   * Cleans up orphaned files. For instance, output can get orphaned if it's
   * written but the editor is closed before the test run is complete.
   */
  async G() {
    const { children } = await this.u.resolve(this.t);
    if (!children) {
      return;
    }
    const stored = new Set(this.a.get([]).filter((s) => s.rev === currentRevision).map((s) => s.id));
    await Promise.all(children.filter((child) => !stored.has(child.name.replace(/\.[a-z]+$/, ""))).map((child) => this.u.del(child.resource).catch(() => void 0)));
  }
  H(id2) {
    return URI.joinPath(this.t, `${id2}.json`);
  }
  I(id2) {
    return URI.joinPath(this.t, `${id2}.output`);
  }
};
$ETb = __decorate([
  __param(0, $vl),
  __param(1, $jv),
  __param(2, $wn),
  __param(3, $Zk),
  __param(4, $km),
  __param(5, $Xk)
], $ETb);

// out-build/vs/workbench/contrib/testing/common/testResultService.js
var isRunningTests = (service) => service.results.length > 0 && service.results[0].completedAt === void 0;
var $FTb = $Qk("testResultService");
var $GTb = class $GTb2 extends $3c {
  /**
   * @inheritdoc
   */
  get results() {
    this.u();
    return this.g;
  }
  constructor(contextKeyService, y, z, C) {
    super();
    this.y = y;
    this.z = z;
    this.C = C;
    this.f = this.B(new $ze());
    this.g = [];
    this.h = [];
    this.j = this.B(new $ze());
    this.m = 0;
    this.onResultsChanged = this.f.event;
    this.onTestChanged = this.j.event;
    this.u = $Qc(() => this.y.read().then((loaded) => {
      for (let i2 = loaded.length - 1; i2 >= 0; i2--) {
        this.push(loaded[i2]);
      }
    }));
    this.w = new $8h(() => this.H(), 500);
    this.B($1c(() => $Xc(this.h)));
    this.n = TestingContextKeys.isRunning.bindTo(contextKeyService);
    this.s = TestingContextKeys.hasAnyResults.bindTo(contextKeyService);
  }
  /**
   * @inheritdoc
   */
  getStateById(extId) {
    for (const result of this.results) {
      const lookup = result.getStateById(extId);
      if (lookup && lookup.computedState !== 0) {
        return [result, lookup];
      }
    }
    return void 0;
  }
  /**
   * @inheritdoc
   */
  createLiveResult(req) {
    if ("targets" in req) {
      const id2 = $ps();
      return this.push(new $RQ(id2, true, req, this.m++, this.C));
    }
    let profile;
    if (req.profile) {
      const profiles2 = this.z.getControllerProfiles(req.controllerId);
      profile = profiles2.find((c) => c.profileId === req.profile.id);
    }
    const resolved = {
      preserveFocus: req.preserveFocus,
      targets: [],
      exclude: req.exclude,
      continuous: req.continuous,
      group: profile?.group ?? 2
    };
    if (profile) {
      resolved.targets.push({
        profileId: profile.profileId,
        controllerId: req.controllerId,
        testIds: req.include
      });
    }
    return this.push(new $RQ(req.id, req.persist, resolved, this.m++, this.C));
  }
  /**
   * @inheritdoc
   */
  push(result) {
    if (result.completedAt === void 0) {
      this.results.unshift(result);
    } else {
      const index = $6(this.results, (r2) => r2.completedAt !== void 0 && r2.completedAt <= result.completedAt);
      this.results.splice(index, 0, result);
      this.w.schedule();
    }
    this.s.set(true);
    if (this.results.length > $ATb) {
      this.results.pop();
      this.h.pop()?.dispose();
    }
    const ds = new $2c();
    this.h.push(ds);
    if (result instanceof $RQ) {
      ds.add(result);
      ds.add(result.onComplete(() => this.D(result)));
      ds.add(result.onChange(this.j.fire, this.j));
      this.n.set(true);
      this.f.fire({ started: result });
    } else {
      this.f.fire({ inserted: result });
      for (const item of result.tests) {
        for (const otherResult of this.results) {
          if (otherResult === result) {
            this.j.fire({
              item,
              result,
              reason: 0
              /* TestResultItemChangeReason.ComputedStateChange */
            });
            break;
          } else if (otherResult.getStateById(item.item.extId) !== void 0) {
            break;
          }
        }
      }
    }
    return result;
  }
  /**
   * @inheritdoc
   */
  getResult(id2) {
    return this.results.find((r2) => r2.id === id2);
  }
  /**
   * @inheritdoc
   */
  clear() {
    const keep = [];
    const removed = [];
    for (const result of this.results) {
      if (result.completedAt !== void 0) {
        removed.push(result);
      } else {
        keep.push(result);
      }
    }
    this.g = keep;
    this.w.schedule();
    if (keep.length === 0) {
      this.s.set(false);
    }
    this.f.fire({ removed });
  }
  D(result) {
    this.F();
    this.G();
    this.w.schedule();
    this.f.fire({ completed: result });
  }
  F() {
    this.results.sort((a, b) => {
      if (!!a.completedAt !== !!b.completedAt) {
        return a.completedAt === void 0 ? -1 : 1;
      }
      const aComp = a instanceof $RQ ? a.insertOrder : -1;
      const bComp = b instanceof $RQ ? b.insertOrder : -1;
      return bComp - aComp;
    });
  }
  G() {
    this.n.set(isRunningTests(this));
  }
  async H() {
    await this.u();
    this.y.persist(this.results);
  }
};
$GTb = __decorate([
  __param(0, $on),
  __param(1, $BTb),
  __param(2, $wTb),
  __param(3, $zv)
], $GTb);

// out-build/vs/workbench/contrib/testing/common/testService.js
var $nTb = $Qk("testService");
var $oTb = (collection) => !Iterable.some(collection.rootItems, (r2) => r2.children.size > 0);
var $pTb = (collection, id2) => {
  if (typeof id2 === "string") {
    id2 = $mQ.fromString(id2);
  }
  if (id2.isRoot) {
    return { controller: id2.toString() };
  }
  const context = { $mid: 16, tests: [] };
  for (const i2 of id2.idsFromRoot()) {
    if (!i2.isRoot) {
      const test = collection.getNodeById(i2.toString());
      if (test) {
        context.tests.push(test);
      }
    }
  }
  return context;
};
var $qTb = async (collection, id2, ct = CancellationToken.None) => {
  const idPath = [...$mQ.fromString(id2).idsFromRoot()];
  let expandToLevel = 0;
  for (let i2 = idPath.length - 1; !ct.isCancellationRequested && i2 >= expandToLevel; ) {
    const id3 = idPath[i2].toString();
    const existing = collection.getNodeById(id3);
    if (!existing) {
      i2--;
      continue;
    }
    if (i2 === idPath.length - 1) {
      return existing;
    }
    if (!existing.children.has(idPath[i2 + 1].toString())) {
      await collection.expand(id3, 0);
    }
    expandToLevel = i2 + 1;
    i2 = idPath.length - 1;
  }
  return void 0;
};
var waitForTestToBeIdle = (testService, test) => {
  if (!test.item.busy) {
    return;
  }
  return new Promise((resolve) => {
    const l = testService.onDidProcessDiff(() => {
      if (testService.collection.getNodeById(test.item.extId)?.item.busy !== true) {
        resolve();
        l.dispose();
      }
    });
  });
};
var $rTb = async function* (testService, ident, uri, waitForIdle = true) {
  for (const test of testService.collection.all) {
    if (!test.item.uri) {
      continue;
    }
    if (ident.extUri.isEqual(uri, test.item.uri)) {
      yield test;
    }
    if (ident.extUri.isEqualOrParent(uri, test.item.uri)) {
      if (test.expand === 1) {
        await testService.collection.expand(test.item.extId, 1);
      }
      if (waitForIdle) {
        await waitForTestToBeIdle(testService, test);
      }
    }
  }
};
var $sTb = async function* (testService, ident, uri, waitForIdle = true) {
  const queue = [testService.collection.rootIds];
  while (queue.length) {
    for (const testId of queue.pop()) {
      const test = testService.collection.getNodeById(testId);
      if (!test) {
      } else if (test.item.uri && ident.extUri.isEqualOrParent(test.item.uri, uri)) {
        yield test;
      } else if (!test.item.uri || ident.extUri.isEqualOrParent(uri, test.item.uri)) {
        if (test.expand === 1) {
          await testService.collection.expand(test.item.extId, 1);
        }
        if (waitForIdle) {
          await waitForTestToBeIdle(testService, test);
        }
        queue.push(test.children.values());
      }
    }
  }
};
var $tTb = (collection, tests) => {
  if (tests.length < 2) {
    return tests;
  }
  const tree = new $lQ();
  for (const test of tests) {
    tree.insert($mQ.fromString(test.item.extId).path, test);
  }
  const out = [];
  const process2 = (currentId, node) => {
    if (node.value) {
      return node.value;
    }
    $id(!!node.children, "expect to have children");
    const thisChildren = [];
    for (const [part, child] of node.children) {
      currentId.push(part);
      const c = process2(currentId, child);
      if (c) {
        thisChildren.push(c);
      }
      currentId.pop();
    }
    if (!thisChildren.length) {
      return;
    }
    const id2 = new $mQ(currentId);
    const test = collection.getNodeById(id2.toString());
    if (test?.children.size === thisChildren.length) {
      return test;
    }
    out.push(...thisChildren);
    return;
  };
  for (const [id2, node] of tree.entries) {
    const n = process2([id2], node);
    if (n) {
      out.push(n);
    }
  }
  return out;
};

// out-build/vs/workbench/api/browser/mainThreadTesting.js
var $HTb = class $HTb2 extends $3c {
  constructor(extHostContext, f, g, h3, j) {
    super();
    this.f = f;
    this.g = g;
    this.h = h3;
    this.j = j;
    this.b = this.B(new $4c());
    this.c = /* @__PURE__ */ new Map();
    this.a = extHostContext.getProxy($yT.ExtHostTesting);
    this.B(this.g.registerExtHost({
      provideTestFollowups: (req, token) => this.a.$provideTestFollowups(req, token),
      executeTestFollowup: (id2) => this.a.$executeTestFollowup(id2),
      disposeTestFollowups: (ids) => this.a.$disposeTestFollowups(ids),
      getTestsRelatedToCode: (uri, position, token) => this.a.$getTestsRelatedToCode(uri, position, token)
    }));
    this.B(this.g.onDidCancelTestRun(({ runId, taskId }) => {
      this.a.$cancelExtensionTestRun(runId, taskId);
    }));
    this.B(Event2.debounce(h3.onDidChange, (_last, e) => e)(() => {
      const obj = {};
      for (const group2 of [
        2,
        4,
        8
        /* TestRunProfileBitset.Coverage */
      ]) {
        for (const profile of this.h.getGroupDefaultProfiles(group2)) {
          obj[profile.controllerId] ??= [];
          obj[profile.controllerId].push(profile.profileId);
        }
      }
      this.a.$setDefaultRunProfiles(obj);
    }));
    this.B(j.onResultsChanged((evt) => {
      if ("completed" in evt) {
        const serialized = evt.completed.toJSONWithMessages();
        if (serialized) {
          this.a.$publishTestResults([serialized]);
        }
      } else if ("removed" in evt) {
        evt.removed.forEach((r2) => {
          if (r2 instanceof $RQ) {
            this.a.$disposeRun(r2.id);
          }
        });
      }
    }));
  }
  /**
   * @inheritdoc
   */
  $markTestRetired(testIds) {
    let tree;
    if (testIds) {
      tree = new $lQ();
      for (const id2 of testIds) {
        tree.insert($mQ.fromString(id2).path, void 0);
      }
    }
    for (const result of this.j.results) {
      if (result instanceof $RQ) {
        result.markRetired(tree);
      }
    }
  }
  /**
   * @inheritdoc
   */
  $publishTestRunProfile(profile) {
    const controller = this.c.get(profile.controllerId);
    if (controller) {
      this.h.addProfile(controller.instance, profile);
    }
  }
  /**
   * @inheritdoc
   */
  $updateTestRunConfig(controllerId, profileId, update) {
    this.h.updateProfile(controllerId, profileId, update);
  }
  /**
   * @inheritdoc
   */
  $removeTestProfile(controllerId, profileId) {
    this.h.removeProfile(controllerId, profileId);
  }
  /**
   * @inheritdoc
   */
  $addTestsToRun(controllerId, runId, tests) {
    this.m(runId, (r2) => r2.addTestChainToRun(controllerId, tests.map((t) => ITestItem.deserialize(this.f, t))));
  }
  /**
   * @inheritdoc
   */
  $appendCoverage(runId, taskId, coverage) {
    this.m(runId, (run) => {
      const task = run.tasks.find((t) => t.id === taskId);
      if (!task) {
        return;
      }
      const deserialized = IFileCoverage.deserialize(this.f, coverage);
      $ce((tx) => {
        let value = task.coverage.read(void 0);
        if (!value) {
          value = new $HQ(run, taskId, this.f, {
            getCoverageDetails: (id2, testId, token) => this.a.$getCoverageDetails(id2, testId, token).then((r2) => r2.map(CoverageDetails.deserialize))
          });
          value.append(deserialized, tx);
          task.coverage.set(value, tx);
        } else {
          value.append(deserialized, tx);
        }
      });
    });
  }
  /**
   * @inheritdoc
   */
  $startedExtensionTestRun(req) {
    this.j.createLiveResult(req);
  }
  /**
   * @inheritdoc
   */
  $startedTestRunTask(runId, task) {
    this.m(runId, (r2) => r2.addTask(task));
  }
  /**
   * @inheritdoc
   */
  $finishedTestRunTask(runId, taskId) {
    this.m(runId, (r2) => r2.markTaskComplete(taskId));
  }
  /**
   * @inheritdoc
   */
  $finishedExtensionTestRun(runId) {
    this.m(runId, (r2) => r2.markComplete());
  }
  /**
   * @inheritdoc
   */
  $updateTestStateInRun(runId, taskId, testId, state, duration) {
    this.m(runId, (r2) => r2.updateState(testId, taskId, state, duration));
  }
  /**
   * @inheritdoc
   */
  $appendOutputToRun(runId, taskId, output, locationDto, testId) {
    const location3 = locationDto && {
      uri: URI.revive(locationDto.uri),
      range: $9C.lift(locationDto.range)
    };
    this.m(runId, (r2) => r2.appendOutput(output, taskId, location3, testId));
  }
  /**
   * @inheritdoc
   */
  $appendTestMessagesInRun(runId, taskId, testId, messages) {
    const r2 = this.j.getResult(runId);
    if (r2 && r2 instanceof $RQ) {
      for (const message of messages) {
        r2.appendMessage(testId, taskId, ITestMessage.deserialize(this.f, message));
      }
    }
  }
  /**
   * @inheritdoc
   */
  $registerTestController(controllerId, _label, _capabilities) {
    const disposable = new $2c();
    const label3 = $he(`${controllerId}.label`, _label);
    const capabilities = $he(`${controllerId}.cap`, _capabilities);
    const controller = {
      id: controllerId,
      label: label3,
      capabilities,
      syncTests: () => this.a.$syncTests(),
      refreshTests: (token) => this.a.$refreshTests(controllerId, token),
      configureRunProfile: (id2) => this.a.$configureRunProfile(controllerId, id2),
      runTests: (reqs, token) => this.a.$runControllerTests(reqs, token),
      startContinuousRun: (reqs, token) => this.a.$startContinuousRun(reqs, token),
      expandTest: (testId, levels) => this.a.$expandTest(testId, isFinite(levels) ? levels : -1),
      getRelatedCode: (testId, token) => this.a.$getCodeRelatedToTest(testId, token).then((locations) => locations.map((l) => ({
        uri: URI.revive(l.uri),
        range: $9C.lift(l.range)
      })))
    };
    disposable.add($1c(() => this.h.removeProfile(controllerId)));
    disposable.add(this.g.registerTestController(controllerId, controller));
    this.c.set(controllerId, {
      instance: controller,
      label: label3,
      capabilities,
      disposable
    });
  }
  /**
   * @inheritdoc
   */
  $updateController(controllerId, patch2) {
    const controller = this.c.get(controllerId);
    if (!controller) {
      return;
    }
    $ce((tx) => {
      if (patch2.label !== void 0) {
        controller.label.set(patch2.label, tx);
      }
      if (patch2.capabilities !== void 0) {
        controller.capabilities.set(patch2.capabilities, tx);
      }
    });
  }
  /**
   * @inheritdoc
   */
  $unregisterTestController(controllerId) {
    this.c.get(controllerId)?.disposable.dispose();
    this.c.delete(controllerId);
  }
  /**
   * @inheritdoc
   */
  $subscribeToDiffs() {
    this.a.$acceptDiff(this.g.collection.getReviverDiff().map(TestsDiffOp.serialize));
    this.b.value = this.g.onDidProcessDiff(this.a.$acceptDiff, this.a);
  }
  /**
   * @inheritdoc
   */
  $unsubscribeFromDiffs() {
    this.b.clear();
  }
  /**
   * @inheritdoc
   */
  $publishDiff(controllerId, diff3) {
    this.g.publishDiff(controllerId, diff3.map((d) => TestsDiffOp.deserialize(this.f, d)));
  }
  /**
   * @inheritdoc
   */
  async $runTests(req, token) {
    const result = await this.g.runResolvedTests(req, token);
    return result.id;
  }
  /**
   * @inheritdoc
   */
  async $getCoverageDetails(resultId, taskIndex, uri, token) {
    const details = await this.j.getResult(resultId)?.tasks[taskIndex]?.coverage.get()?.getUri(URI.from(uri))?.details(token);
    return details || [];
  }
  dispose() {
    super.dispose();
    for (const subscription of this.c.values()) {
      subscription.disposable.dispose();
    }
    this.c.clear();
  }
  m(runId, fn) {
    const r2 = this.j.getResult(runId);
    return r2 && r2 instanceof $RQ ? fn(r2) : void 0;
  }
};
$HTb = __decorate([
  $frb($xT.MainThreadTesting),
  __param(1, $vl),
  __param(2, $nTb),
  __param(3, $wTb),
  __param(4, $FTb)
], $HTb);

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

// out-build/vs/platform/secrets/common/secrets.js
var $J4 = $Qk("secretStorageService");
var $K4 = class $K42 extends $3c {
  constructor(h3, j, m, n) {
    super();
    this.h = h3;
    this.j = j;
    this.m = m;
    this.n = n;
    this.a = "secret://";
    this.b = this.B(new $ze());
    this.onDidChangeSecret = this.b.event;
    this.c = new $Rh();
    this.f = "unknown";
    this.g = this.B(new $2c());
    this.r = new $sf(() => this.t());
  }
  /**
   * @Note initialize must be called first so that this can be resolved properly
   * otherwise it will return 'unknown'.
   */
  get type() {
    return this.f;
  }
  get s() {
    return this.r.value;
  }
  get(key2) {
    return this.c.queue(key2, async () => {
      const storageService = await this.s;
      const fullKey = this.y(key2);
      this.n.trace("[secrets] getting secret for key:", fullKey);
      const encrypted = storageService.get(
        fullKey,
        -1
        /* StorageScope.APPLICATION */
      );
      if (!encrypted) {
        this.n.trace("[secrets] no secret found for key:", fullKey);
        return void 0;
      }
      try {
        this.n.trace("[secrets] decrypting gotten secret for key:", fullKey);
        const result = this.f === "in-memory" ? encrypted : await this.m.decrypt(encrypted);
        this.n.trace("[secrets] decrypted secret for key:", fullKey);
        return result;
      } catch (e) {
        this.n.error(e);
        this.delete(key2);
        return void 0;
      }
    });
  }
  set(key2, value) {
    return this.c.queue(key2, async () => {
      const storageService = await this.s;
      this.n.trace("[secrets] encrypting secret for key:", key2);
      let encrypted;
      try {
        encrypted = this.f === "in-memory" ? value : await this.m.encrypt(value);
      } catch (e) {
        this.n.error(e);
        throw e;
      }
      const fullKey = this.y(key2);
      this.n.trace("[secrets] storing encrypted secret for key:", fullKey);
      storageService.store(
        fullKey,
        encrypted,
        -1,
        1
        /* StorageTarget.MACHINE */
      );
      this.n.trace("[secrets] stored encrypted secret for key:", fullKey);
    });
  }
  delete(key2) {
    return this.c.queue(key2, async () => {
      const storageService = await this.s;
      const fullKey = this.y(key2);
      this.n.trace("[secrets] deleting secret for key:", fullKey);
      storageService.remove(
        fullKey,
        -1
        /* StorageScope.APPLICATION */
      );
      this.n.trace("[secrets] deleted secret for key:", fullKey);
    });
  }
  async t() {
    let storageService;
    if (!this.h && await this.m.isEncryptionAvailable()) {
      this.n.trace(`[SecretStorageService] Encryption is available, using persisted storage`);
      this.f = "persisted";
      storageService = this.j;
    } else {
      if (this.f === "in-memory") {
        return this.j;
      }
      this.n.trace("[SecretStorageService] Encryption is not available, falling back to in-memory storage");
      this.f = "in-memory";
      storageService = this.B(new $nv());
    }
    this.g.clear();
    this.g.add(storageService.onDidChangeValue(-1, void 0, this.g)((e) => {
      this.w(e.key);
    }));
    return storageService;
  }
  u() {
    this.r = new $sf(() => this.t());
  }
  w(key2) {
    if (!key2.startsWith(this.a)) {
      return;
    }
    const secretKey = key2.slice(this.a.length);
    this.n.trace(`[SecretStorageService] Notifying change in value for secret: ${secretKey}`);
    this.b.fire(secretKey);
  }
  y(key2) {
    return `${this.a}${key2}`;
  }
};
$K4 = __decorate([
  __param(1, $jv),
  __param(2, $Mu),
  __param(3, $wn)
], $K4);

// out-build/vs/workbench/api/browser/mainThreadSecretState.js
var $ITb = class $ITb2 extends $3c {
  constructor(extHostContext, c, f, environmentService) {
    super();
    this.c = c;
    this.f = f;
    this.b = new $Rh();
    this.a = extHostContext.getProxy($yT.ExtHostSecretState);
    this.B(this.c.onDidChangeSecret((e) => {
      try {
        const { extensionId, key: key2 } = this.n(e);
        if (extensionId && key2) {
          this.a.$onDidChangePassword({ extensionId, key: key2 });
        }
      } catch (e2) {
      }
    }));
  }
  $getPassword(extensionId, key2) {
    this.f.trace(`[mainThreadSecretState] Getting password for ${extensionId} extension: `, key2);
    return this.b.queue(extensionId, () => this.g(extensionId, key2));
  }
  async g(extensionId, key2) {
    const fullKey = this.m(extensionId, key2);
    const password = await this.c.get(fullKey);
    this.f.trace(`[mainThreadSecretState] ${password ? "P" : "No p"}assword found for: `, extensionId, key2);
    return password;
  }
  $setPassword(extensionId, key2, value) {
    this.f.trace(`[mainThreadSecretState] Setting password for ${extensionId} extension: `, key2);
    return this.b.queue(extensionId, () => this.h(extensionId, key2, value));
  }
  async h(extensionId, key2, value) {
    const fullKey = this.m(extensionId, key2);
    await this.c.set(fullKey, value);
    this.f.trace("[mainThreadSecretState] Password set for: ", extensionId, key2);
  }
  $deletePassword(extensionId, key2) {
    this.f.trace(`[mainThreadSecretState] Deleting password for ${extensionId} extension: `, key2);
    return this.b.queue(extensionId, () => this.j(extensionId, key2));
  }
  async j(extensionId, key2) {
    const fullKey = this.m(extensionId, key2);
    await this.c.delete(fullKey);
    this.f.trace("[mainThreadSecretState] Password deleted for: ", extensionId, key2);
  }
  m(extensionId, key2) {
    return JSON.stringify({ extensionId, key: key2 });
  }
  n(key2) {
    return JSON.parse(key2);
  }
};
$ITb = __decorate([
  $frb($xT.MainThreadSecretState),
  __param(1, $J4),
  __param(2, $wn),
  __param(3, $M4)
], $ITb);

// out-build/vs/workbench/contrib/share/common/share.js
var $JTb = $Qk("shareService");

// out-build/vs/workbench/api/browser/mainThreadShare.js
var $KTb = class $KTb2 {
  constructor(extHostContext, d) {
    this.d = d;
    this.b = /* @__PURE__ */ new Map();
    this.c = /* @__PURE__ */ new Map();
    this.a = extHostContext.getProxy($yT.ExtHostShare);
  }
  $registerShareProvider(handle2, selector, id2, label3, priority) {
    const provider = {
      id: id2,
      label: label3,
      selector,
      priority,
      provideShare: async (item) => {
        const result = await this.a.$provideShare(handle2, item, CancellationToken.None);
        return typeof result === "string" ? result : URI.revive(result);
      }
    };
    this.b.set(handle2, provider);
    const disposable = this.d.registerShareProvider(provider);
    this.c.set(handle2, disposable);
  }
  $unregisterShareProvider(handle2) {
    if (this.b.has(handle2)) {
      this.b.delete(handle2);
    }
    if (this.c.has(handle2)) {
      this.c.delete(handle2);
    }
  }
  dispose() {
    this.b.clear();
    $Xc(this.c.values());
    this.c.clear();
  }
};
$KTb = __decorate([
  $frb($xT.MainThreadShare),
  __param(1, $JTb)
], $KTb);

// out-build/vs/workbench/api/browser/mainThreadProfileContentHandlers.js
var $LTb = class $LTb2 extends $3c {
  constructor(context, c) {
    super();
    this.c = c;
    this.b = this.B(new $_c());
    this.a = context.getProxy($yT.ExtHostProfileContentHandlers);
  }
  async $registerProfileContentHandler(id2, name, description, extensionId) {
    this.b.set(id2, this.c.registerProfileContentHandler(id2, {
      name,
      description,
      extensionId,
      saveProfile: async (name2, content, token) => {
        const result = await this.a.$saveProfile(id2, name2, content, token);
        return result ? $cu(result) : null;
      },
      readProfile: async (uri, token) => {
        return this.a.$readProfile(id2, uri, token);
      }
    }));
  }
  async $unregisterProfileContentHandler(id2) {
    this.b.deleteAndDispose(id2);
  }
};
$LTb = __decorate([
  $frb($xT.MainThreadProfileContentHandlers),
  __param(1, $nT)
], $LTb);

// out-build/vs/workbench/services/aiRelatedInformation/common/aiRelatedInformation.js
var $vS = $Qk("IAiRelatedInformationService");
var RelatedInformationType2;
(function(RelatedInformationType3) {
  RelatedInformationType3[RelatedInformationType3["SymbolInformation"] = 1] = "SymbolInformation";
  RelatedInformationType3[RelatedInformationType3["CommandInformation"] = 2] = "CommandInformation";
  RelatedInformationType3[RelatedInformationType3["SearchInformation"] = 3] = "SearchInformation";
  RelatedInformationType3[RelatedInformationType3["SettingInformation"] = 4] = "SettingInformation";
})(RelatedInformationType2 || (RelatedInformationType2 = {}));

// out-build/vs/workbench/api/browser/mainThreadAiRelatedInformation.js
var $MTb = class $MTb2 extends $3c {
  constructor(context, c) {
    super();
    this.c = c;
    this.b = this.B(new $_c());
    this.a = context.getProxy($yT.ExtHostAiRelatedInformation);
  }
  $getAiRelatedInformation(query, types) {
    return this.c.getRelatedInformation(query, types, CancellationToken.None);
  }
  $registerAiRelatedInformationProvider(handle2, type) {
    const provider = {
      provideAiRelatedInformation: (query, token) => {
        return this.a.$provideAiRelatedInformation(handle2, query, token);
      }
    };
    this.b.set(handle2, this.c.registerAiRelatedInformationProvider(type, provider));
  }
  $unregisterAiRelatedInformationProvider(handle2) {
    this.b.deleteAndDispose(handle2);
  }
};
$MTb = __decorate([
  $frb($xT.MainThreadAiRelatedInformation),
  __param(1, $vS)
], $MTb);

// out-build/vs/workbench/services/aiEmbeddingVector/common/aiEmbeddingVectorService.js
var $OTb_1;
var $NTb = $Qk("IAiEmbeddingVectorService");
var $OTb = class $OTb2 {
  static {
    $OTb_1 = this;
  }
  static {
    this.DEFAULT_TIMEOUT = 1e3 * 10;
  }
  // 10 seconds
  constructor(b) {
    this.b = b;
    this.a = [];
  }
  isEnabled() {
    return this.a.length > 0;
  }
  registerAiEmbeddingVectorProvider(model, provider) {
    this.a.push(provider);
    return {
      dispose: () => {
        const index = this.a.indexOf(provider);
        if (index >= 0) {
          this.a.splice(index, 1);
        }
      }
    };
  }
  async getEmbeddingVector(strings, token) {
    if (this.a.length === 0) {
      throw new Error("No embedding vector providers registered");
    }
    const stopwatch = $te.create();
    const cancellablePromises = [];
    const timer = $Wh($OTb_1.DEFAULT_TIMEOUT);
    const disposable = token.onCancellationRequested(() => {
      disposable.dispose();
      timer.cancel();
    });
    for (const provider of this.a) {
      cancellablePromises.push($Hh(async (t) => {
        try {
          return await provider.provideAiEmbeddingVector(Array.isArray(strings) ? strings : [strings], t);
        } catch (e) {
        }
        await timer;
        throw new Error("Embedding vector provider timed out");
      }));
    }
    cancellablePromises.push($Hh(async (t) => {
      const disposable2 = t.onCancellationRequested(() => {
        timer.cancel();
        disposable2.dispose();
      });
      await timer;
      throw new Error("Embedding vector provider timed out");
    }));
    try {
      const result = await $Kh(cancellablePromises);
      if (result.length === 1) {
        return result[0];
      }
      return result;
    } finally {
      stopwatch.stop();
      this.b.trace(`[AiEmbeddingVectorService]: getEmbeddingVector took ${stopwatch.elapsed()}ms`);
    }
  }
};
$OTb = $OTb_1 = __decorate([
  __param(0, $wn)
], $OTb);
$SC(
  $NTb,
  $OTb,
  1
  /* InstantiationType.Delayed */
);

// out-build/vs/workbench/api/browser/mainThreadAiEmbeddingVector.js
var $PTb = class $PTb2 extends $3c {
  constructor(context, c) {
    super();
    this.c = c;
    this.b = this.B(new $_c());
    this.a = context.getProxy($yT.ExtHostAiEmbeddingVector);
  }
  $registerAiEmbeddingVectorProvider(model, handle2) {
    const provider = {
      provideAiEmbeddingVector: (strings, token) => {
        return this.a.$provideAiEmbeddingVector(handle2, strings, token);
      }
    };
    this.b.set(handle2, this.c.registerAiEmbeddingVectorProvider(model, provider));
  }
  $unregisterAiEmbeddingVectorProvider(handle2) {
    this.b.deleteAndDispose(handle2);
  }
};
$PTb = __decorate([
  $frb($xT.MainThreadAiEmbeddingVector),
  __param(1, $NTb)
], $PTb);

// out-build/vs/workbench/api/browser/extensionHost.contribution.js
var $QTb = class $QTb2 {
  static {
    this.ID = "workbench.contrib.extensionPoints";
  }
  constructor(a) {
    this.a = a;
    this.a.createInstance($xlb);
    this.a.createInstance($ylb);
    this.a.createInstance($Hlb);
    this.a.createInstance($Nlb);
    this.a.createInstance($Rlb);
    this.a.createInstance($erb);
  }
};
$QTb = __decorate([
  __param(0, $Pk)
], $QTb);
$PL(
  $QTb.ID,
  $QTb,
  1
  /* WorkbenchPhase.BlockStartup */
);

// out-build/vs/workbench/browser/parts/titlebar/windowTitle.js
var $0Tb_1;
var WindowSettingNames;
(function(WindowSettingNames2) {
  WindowSettingNames2["titleSeparator"] = "window.titleSeparator";
  WindowSettingNames2["title"] = "window.title";
})(WindowSettingNames || (WindowSettingNames = {}));
var $8Tb = (() => {
  if ($m && $p) {
    return "${activeEditorShort}${separator}${rootName}${separator}${profileName}";
  }
  const base = "${dirty}${activeEditorShort}${separator}${rootName}${separator}${profileName}${separator}${appName}";
  if ($r) {
    return base + "${separator}${remoteName}";
  }
  return base;
})();
var $9Tb = $m ? " \u2014 " : " - ";
var $0Tb = class $0Tb2 extends $3c {
  static {
    $0Tb_1 = this;
  }
  static {
    this.a = $l ? localize(3787, null) : localize(3788, null);
  }
  static {
    this.b = localize(3789, null);
  }
  static {
    this.c = "\u25CF ";
  }
  get value() {
    return this.n ?? "";
  }
  get workspaceName() {
    return this.C.getWorkspaceLabel(this.z.getWorkspace());
  }
  get fileName() {
    const activeEditor = this.s.activeEditor;
    if (!activeEditor) {
      return void 0;
    }
    const fileName = activeEditor.getTitle(
      0
      /* Verbosity.SHORT */
    );
    const dirty = activeEditor?.isDirty() && !activeEditor.isSaving() ? $0Tb_1.c : "";
    return `${dirty}${fileName}`;
  }
  constructor(targetWindow, editorGroupsContainer, u, w, editorService, y, z, C, D, F, G) {
    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.f = { isPure: true, isAdmin: false, prefix: void 0 };
    this.g = /* @__PURE__ */ new Map();
    this.h = this.B(new $2c());
    this.j = this.B(new $8h(() => this.M(), 0));
    this.m = new $ze();
    this.onDidChange = this.m.event;
    this.r = false;
    this.s = editorService.createScoped(editorGroupsContainer, this.q);
    this.t = targetWindow.vscodeWindowId;
    this.J();
    this.H();
  }
  H() {
    this.B(this.u.onDidChangeConfiguration((e) => this.I(e)));
    this.B(this.s.onDidActiveEditorChange(() => this.L()));
    this.B(this.z.onDidChangeWorkspaceFolders(() => this.j.schedule()));
    this.B(this.z.onDidChangeWorkbenchState(() => this.j.schedule()));
    this.B(this.z.onDidChangeWorkspaceName(() => this.j.schedule()));
    this.B(this.C.onDidChangeFormatters(() => this.j.schedule()));
    this.B(this.D.onDidChangeCurrentProfile(() => this.j.schedule()));
    this.B(this.G.onDidChangeFocusedView(() => {
      if (this.r) {
        this.j.schedule();
      }
    }));
    this.B(this.w.onDidChangeContext((e) => {
      if (e.affectsSome(this.g)) {
        this.j.schedule();
      }
    }));
  }
  I(event) {
    if (event.affectsConfiguration(
      "window.title"
      /* WindowSettingNames.title */
    )) {
      this.J();
    }
    if (event.affectsConfiguration(
      "window.title"
      /* WindowSettingNames.title */
    ) || event.affectsConfiguration(
      "window.titleSeparator"
      /* WindowSettingNames.titleSeparator */
    )) {
      this.j.schedule();
    }
  }
  J() {
    const titleTemplate = this.u.getValue(
      "window.title"
      /* WindowSettingNames.title */
    );
    this.r = typeof titleTemplate === "string" && titleTemplate.includes("${focusedView}");
  }
  L() {
    this.h.clear();
    this.j.schedule();
    const activeEditor = this.s.activeEditor;
    if (activeEditor) {
      this.h.add(activeEditor.onDidChangeDirty(() => this.j.schedule()));
      this.h.add(activeEditor.onDidChangeLabel(() => this.j.schedule()));
    }
    if (this.r) {
      const activeTextEditorControl = this.s.activeTextEditorControl;
      const textEditorControls = [];
      if ($P5(activeTextEditorControl)) {
        textEditorControls.push(activeTextEditorControl);
      } else if ($Q5(activeTextEditorControl)) {
        textEditorControls.push(activeTextEditorControl.getOriginalEditor(), activeTextEditorControl.getModifiedEditor());
      }
      for (const textEditorControl of textEditorControls) {
        this.h.add(textEditorControl.onDidBlurEditorText(() => this.j.schedule()));
        this.h.add(textEditorControl.onDidFocusEditorText(() => this.j.schedule()));
      }
    }
  }
  M() {
    const title = this.N();
    if (title !== this.n) {
      let nativeTitle = title;
      if (!$Ef(nativeTitle)) {
        nativeTitle = this.F.nameLong;
      }
      const window3 = getWindowById(this.t, true).window;
      if (!window3.document.title && $m && nativeTitle === this.F.nameLong) {
        window3.document.title = `${this.F.nameLong} ${$0Tb_1.c}`;
      }
      window3.document.title = nativeTitle;
      this.n = title;
      this.m.fire();
    }
  }
  N() {
    const { prefix, suffix } = this.getTitleDecorations();
    let title = this.getWindowTitle() || this.F.nameLong;
    if (prefix) {
      title = `${prefix} ${title}`;
    }
    if (suffix) {
      title = `${title} ${suffix}`;
    }
    return title.replace(/[^\S ]/g, " ");
  }
  getTitleDecorations() {
    let prefix;
    let suffix;
    if (this.f.prefix) {
      prefix = this.f.prefix;
    }
    if (this.y.isExtensionDevelopment) {
      prefix = !prefix ? $0Tb_1.b : `${$0Tb_1.b} - ${prefix}`;
    }
    if (this.f.isAdmin) {
      suffix = $0Tb_1.a;
    }
    return { prefix, suffix };
  }
  updateProperties(properties) {
    const isAdmin = typeof properties.isAdmin === "boolean" ? properties.isAdmin : this.f.isAdmin;
    const isPure = typeof properties.isPure === "boolean" ? properties.isPure : this.f.isPure;
    const prefix = typeof properties.prefix === "string" ? properties.prefix : this.f.prefix;
    if (isAdmin !== this.f.isAdmin || isPure !== this.f.isPure || prefix !== this.f.prefix) {
      this.f.isAdmin = isAdmin;
      this.f.isPure = isPure;
      this.f.prefix = prefix;
      this.j.schedule();
    }
  }
  registerVariables(variables) {
    let changed = false;
    for (const { name, contextKey } of variables) {
      if (!this.g.has(contextKey)) {
        this.g.set(contextKey, name);
        changed = true;
      }
    }
    if (changed) {
      this.j.schedule();
    }
  }
  /**
   * Possible template values:
   *
   * {activeEditorLong}: e.g. /Users/Development/myFolder/myFileFolder/myFile.txt
   * {activeEditorMedium}: e.g. myFolder/myFileFolder/myFile.txt
   * {activeEditorShort}: e.g. myFile.txt
   * {activeFolderLong}: e.g. /Users/Development/myFolder/myFileFolder
   * {activeFolderMedium}: e.g. myFolder/myFileFolder
   * {activeFolderShort}: e.g. myFileFolder
   * {rootName}: e.g. myFolder1, myFolder2, myFolder3
   * {rootPath}: e.g. /Users/Development
   * {folderName}: e.g. myFolder
   * {folderPath}: e.g. /Users/Development/myFolder
   * {appName}: e.g. VS Code
   * {remoteName}: e.g. SSH
   * {dirty}: indicator
   * {focusedView}: e.g. Terminal
   * {separator}: conditional separator
   */
  getWindowTitle() {
    const editor = this.s.activeEditor;
    const workspace2 = this.z.getWorkspace();
    let root;
    if (workspace2.configuration) {
      root = workspace2.configuration;
    } else if (workspace2.folders.length) {
      root = workspace2.folders[0].uri;
    }
    const editorResource = $mL.getOriginalUri(editor, { supportSideBySide: SideBySideEditor.PRIMARY });
    let editorFolderResource = editorResource ? $uh(editorResource) : void 0;
    if (editorFolderResource?.path === ".") {
      editorFolderResource = void 0;
    }
    let folder = void 0;
    if (this.z.getWorkbenchState() === 2) {
      folder = workspace2.folders[0];
    } else if (editorResource) {
      folder = this.z.getWorkspaceFolder(editorResource) ?? void 0;
    }
    let remoteName = void 0;
    if (this.y.remoteAuthority && !$r) {
      remoteName = this.C.getHostLabel(Schemas.vscodeRemote, this.y.remoteAuthority);
    } else {
      const virtualWorkspaceLocation = $9S(workspace2);
      if (virtualWorkspaceLocation) {
        remoteName = this.C.getHostLabel(virtualWorkspaceLocation.scheme, virtualWorkspaceLocation.authority);
      }
    }
    const activeEditorShort = editor ? editor.getTitle(
      0
      /* Verbosity.SHORT */
    ) : "";
    const activeEditorMedium = editor ? editor.getTitle(
      1
      /* Verbosity.MEDIUM */
    ) : activeEditorShort;
    const activeEditorLong = editor ? editor.getTitle(
      2
      /* Verbosity.LONG */
    ) : activeEditorMedium;
    const activeFolderShort = editorFolderResource ? $sh(editorFolderResource) : "";
    const activeFolderMedium = editorFolderResource ? this.C.getUriLabel(editorFolderResource, { relative: true }) : "";
    const activeFolderLong = editorFolderResource ? this.C.getUriLabel(editorFolderResource) : "";
    const rootName = this.C.getWorkspaceLabel(workspace2);
    const rootNameShort = this.C.getWorkspaceLabel(workspace2, {
      verbose: 0
      /* LabelVerbosity.SHORT */
    });
    const rootPath = root ? this.C.getUriLabel(root) : "";
    const folderName = folder ? folder.name : "";
    const folderPath = folder ? this.C.getUriLabel(folder.uri) : "";
    const dirty = editor?.isDirty() && !editor.isSaving() ? $0Tb_1.c : "";
    const appName = this.F.nameLong;
    const profileName = this.D.currentProfile.isDefault ? "" : this.D.currentProfile.name;
    const focusedView = this.G.getFocusedViewName();
    const variables = {};
    for (const [contextKey, name] of this.g) {
      variables[name] = this.w.getContextKeyValue(contextKey) ?? "";
    }
    let titleTemplate = this.u.getValue(
      "window.title"
      /* WindowSettingNames.title */
    );
    if (typeof titleTemplate !== "string") {
      titleTemplate = $8Tb;
    }
    let separator = this.u.getValue(
      "window.titleSeparator"
      /* WindowSettingNames.titleSeparator */
    );
    if (typeof separator !== "string") {
      separator = $9Tb;
    }
    return $5t(titleTemplate, {
      ...variables,
      activeEditorShort,
      activeEditorLong,
      activeEditorMedium,
      activeFolderShort,
      activeFolderMedium,
      activeFolderLong,
      rootName,
      rootPath,
      rootNameShort,
      folderName,
      folderPath,
      dirty,
      appName,
      remoteName,
      profileName,
      focusedView,
      separator: { label: separator }
    });
  }
  isCustomTitleFormat() {
    const title = this.u.inspect(
      "window.title"
      /* WindowSettingNames.title */
    );
    const titleSeparator = this.u.inspect(
      "window.titleSeparator"
      /* WindowSettingNames.titleSeparator */
    );
    return title.value !== title.defaultValue || titleSeparator.value !== titleSeparator.defaultValue;
  }
};
$0Tb = $0Tb_1 = __decorate([
  __param(2, $kl),
  __param(3, $on),
  __param(4, $mJ),
  __param(5, $M4),
  __param(6, $Zk),
  __param(7, $ZI),
  __param(8, $gT),
  __param(9, $Vu),
  __param(10, $uob)
], $0Tb);

// out-build/vs/workbench/browser/workbench.contribution.js
var registry = $Wn.as($Ht.Configuration);
(function registerConfiguration() {
  $PL(
    $ZL.ID,
    $ZL,
    4
    /* WorkbenchPhase.Eventually */
  );
  $PL(
    $1L.ID,
    $1L,
    3
    /* WorkbenchPhase.AfterRestored */
  );
  registry.registerConfiguration({
    ...$UL,
    "properties": {
      "workbench.externalBrowser": {
        type: "string",
        markdownDescription: localize(3832, null),
        included: $p,
        restricted: true
      },
      "workbench.editor.titleScrollbarSizing": {
        type: "string",
        enum: ["default", "large"],
        enumDescriptions: [
          localize(3833, null),
          localize(3834, null)
        ],
        description: localize(3835, null),
        default: "default"
      },
      [
        "workbench.editor.showTabs"
        /* LayoutSettings.EDITOR_TABS_MODE */
      ]: {
        "type": "string",
        "enum": [
          "multiple",
          "single",
          "none"
          /* EditorTabsMode.NONE */
        ],
        "enumDescriptions": [
          localize(3836, null),
          localize(3837, null),
          localize(3838, null)
        ],
        "description": localize(3839, null),
        "default": "multiple"
      },
      [
        "workbench.editor.editorActionsLocation"
        /* LayoutSettings.EDITOR_ACTIONS_LOCATION */
      ]: {
        "type": "string",
        "enum": [
          "default",
          "titleBar",
          "hidden"
          /* EditorActionsLocation.HIDDEN */
        ],
        "markdownEnumDescriptions": [
          localize(3840, null, "`#workbench.editor.showTabs#`", "`none`"),
          localize(3841, null, "`#window.customTitleBarVisibility#`", "`never`"),
          localize(3842, null)
        ],
        "markdownDescription": localize(3843, null),
        "default": "default"
      },
      "workbench.editor.alwaysShowEditorActions": {
        "type": "boolean",
        "markdownDescription": localize(3844, null),
        "default": false
      },
      "workbench.editor.wrapTabs": {
        "type": "boolean",
        "markdownDescription": localize(3845, null, "`#workbench.editor.showTabs#`", "`multiple`"),
        "default": false
      },
      "workbench.editor.scrollToSwitchTabs": {
        "type": "boolean",
        "markdownDescription": localize(3846, null, "`#workbench.editor.showTabs#`", "`multiple`"),
        "default": false
      },
      "workbench.editor.highlightModifiedTabs": {
        "type": "boolean",
        "markdownDescription": localize(3847, null, "`#workbench.editor.showTabs#`", `multiple`),
        "default": false
      },
      "workbench.editor.decorations.badges": {
        "type": "boolean",
        "markdownDescription": localize(3848, null),
        "default": true
      },
      "workbench.editor.decorations.colors": {
        "type": "boolean",
        "markdownDescription": localize(3849, null),
        "default": true
      },
      [$prb.SETTING_ID_ENABLED]: {
        "type": "boolean",
        "markdownDescription": localize(3850, null),
        "default": true
      },
      [$prb.SETTING_ID_PATTERNS]: {
        "type": "object",
        "markdownDescription": (() => {
          let customEditorLabelDescription = localize(3851, null);
          customEditorLabelDescription += "\n- " + [
            localize(3852, null),
            localize(3853, null),
            localize(3854, null),
            localize(3855, null),
            localize(3856, null)
          ].join("\n- ");
          customEditorLabelDescription += "\n\n" + localize(3857, null);
          return customEditorLabelDescription;
        })(),
        additionalProperties: {
          type: ["string", "null"],
          markdownDescription: localize(3858, null),
          minLength: 1,
          pattern: ".*[a-zA-Z0-9].*"
        },
        "default": {}
      },
      "workbench.editor.labelFormat": {
        "type": "string",
        "enum": ["default", "short", "medium", "long"],
        "enumDescriptions": [
          localize(3859, null),
          localize(3860, null),
          localize(3861, null),
          localize(3862, null)
        ],
        "default": "default",
        "description": localize(3863, null)
      },
      "workbench.editor.untitled.labelFormat": {
        "type": "string",
        "enum": ["content", "name"],
        "enumDescriptions": [
          localize(3864, null),
          localize(3865, null)
        ],
        "default": "content",
        "description": localize(3866, null)
      },
      "workbench.editor.empty.hint": {
        "type": "string",
        "enum": ["text", "hidden"],
        "default": "text",
        "markdownDescription": localize(3867, null)
      },
      "workbench.editor.languageDetection": {
        type: "boolean",
        default: true,
        description: localize(3868, null),
        scope: 5
        /* ConfigurationScope.LANGUAGE_OVERRIDABLE */
      },
      "workbench.editor.historyBasedLanguageDetection": {
        type: "boolean",
        default: true,
        description: localize(3869, null)
      },
      "workbench.editor.preferHistoryBasedLanguageDetection": {
        type: "boolean",
        default: false,
        description: localize(3870, null)
      },
      "workbench.editor.languageDetectionHints": {
        type: "object",
        default: { "untitledEditors": true, "notebookEditors": true },
        description: localize(3871, null),
        additionalProperties: false,
        properties: {
          untitledEditors: {
            type: "boolean",
            description: localize(3872, null)
          },
          notebookEditors: {
            type: "boolean",
            description: localize(3873, null)
          }
        }
      },
      "workbench.editor.tabActionLocation": {
        type: "string",
        enum: ["left", "right"],
        default: "right",
        markdownDescription: localize(3874, null, "`#workbench.editor.showTabs#`", "`multiple`")
      },
      "workbench.editor.tabActionCloseVisibility": {
        type: "boolean",
        default: true,
        description: localize(3875, null)
      },
      "workbench.editor.tabActionUnpinVisibility": {
        type: "boolean",
        default: true,
        description: localize(3876, null)
      },
      "workbench.editor.tabSizing": {
        "type": "string",
        "enum": ["fit", "shrink", "fixed"],
        "default": "fit",
        "enumDescriptions": [
          localize(3877, null),
          localize(3878, null),
          localize(3879, null)
        ],
        "markdownDescription": localize(3880, null, "`#workbench.editor.showTabs#`", "`multiple`")
      },
      "workbench.editor.tabSizingFixedMinWidth": {
        "type": "number",
        "default": 50,
        "minimum": 38,
        "markdownDescription": localize(3881, null, "`#workbench.editor.tabSizing#`", "`fixed`")
      },
      "workbench.editor.tabSizingFixedMaxWidth": {
        "type": "number",
        "default": 160,
        "minimum": 38,
        "markdownDescription": localize(3882, null, "`#workbench.editor.tabSizing#`", "`fixed`")
      },
      "window.density.editorTabHeight": {
        "type": "string",
        "enum": ["default", "compact"],
        "default": "default",
        "markdownDescription": localize(3883, null, "`#workbench.editor.showTabs#`", "`multiple`")
      },
      "workbench.editor.pinnedTabSizing": {
        "type": "string",
        "enum": ["normal", "compact", "shrink"],
        "default": "normal",
        "enumDescriptions": [
          localize(3884, null),
          localize(3885, null),
          localize(3886, null)
        ],
        "markdownDescription": localize(3887, null, "`#workbench.editor.showTabs#`", "`multiple`")
      },
      "workbench.editor.pinnedTabsOnSeparateRow": {
        "type": "boolean",
        "default": false,
        "markdownDescription": localize(3888, null, "`#workbench.editor.showTabs#`", "`multiple`")
      },
      "workbench.editor.preventPinnedEditorClose": {
        "type": "string",
        "enum": ["keyboardAndMouse", "keyboard", "mouse", "never"],
        "default": "keyboardAndMouse",
        "enumDescriptions": [
          localize(3889, null),
          localize(3890, null),
          localize(3891, null),
          localize(3892, null)
        ],
        description: localize(3893, null)
      },
      "workbench.editor.splitSizing": {
        "type": "string",
        "enum": ["auto", "distribute", "split"],
        "default": "auto",
        "enumDescriptions": [
          localize(3894, null),
          localize(3895, null),
          localize(3896, null)
        ],
        "description": localize(3897, null)
      },
      "workbench.editor.splitOnDragAndDrop": {
        "type": "boolean",
        "default": true,
        "description": localize(3898, null)
      },
      "workbench.editor.dragToOpenWindow": {
        "type": "boolean",
        "default": true,
        "markdownDescription": localize(3899, null)
      },
      "workbench.editor.focusRecentEditorAfterClose": {
        "type": "boolean",
        "description": localize(3900, null),
        "default": true
      },
      "workbench.editor.showIcons": {
        "type": "boolean",
        "description": localize(3901, null),
        "default": true
      },
      "workbench.editor.enablePreview": {
        "type": "boolean",
        "description": localize(3902, null),
        "default": true
      },
      "workbench.editor.enablePreviewFromQuickOpen": {
        "type": "boolean",
        "markdownDescription": localize(3903, null, "`#workbench.editor.showTabs#`", "`multiple`"),
        "default": false
      },
      "workbench.editor.enablePreviewFromCodeNavigation": {
        "type": "boolean",
        "markdownDescription": localize(3904, null, "`#workbench.editor.showTabs#`", "`multiple`"),
        "default": false
      },
      "workbench.editor.closeOnFileDelete": {
        "type": "boolean",
        "description": localize(3905, null),
        "default": false
      },
      "workbench.editor.openPositioning": {
        "type": "string",
        "enum": ["left", "right", "first", "last"],
        "default": "right",
        "markdownDescription": localize(3906, null, "`left`", "`right`", "`first`", "`last`")
      },
      "workbench.editor.openSideBySideDirection": {
        "type": "string",
        "enum": ["right", "down"],
        "default": "right",
        "markdownDescription": localize(3907, null)
      },
      "workbench.editor.closeEmptyGroups": {
        "type": "boolean",
        "description": localize(3908, null),
        "default": true
      },
      "workbench.editor.revealIfOpen": {
        "type": "boolean",
        "description": localize(3909, null),
        "default": false
      },
      "workbench.editor.mouseBackForwardToNavigate": {
        "type": "boolean",
        "description": localize(3910, null),
        "default": true
      },
      "workbench.editor.navigationScope": {
        "type": "string",
        "enum": ["default", "editorGroup", "editor"],
        "default": "default",
        "markdownDescription": localize(3911, null),
        "enumDescriptions": [
          localize(3912, null),
          localize(3913, null),
          localize(3914, null)
        ]
      },
      "workbench.editor.restoreViewState": {
        "type": "boolean",
        "markdownDescription": localize(3915, null, "`#workbench.editor.sharedViewState#`"),
        "default": true,
        "scope": 5
        /* ConfigurationScope.LANGUAGE_OVERRIDABLE */
      },
      "workbench.editor.sharedViewState": {
        "type": "boolean",
        "description": localize(3916, null),
        "default": false
      },
      "workbench.editor.splitInGroupLayout": {
        "type": "string",
        "enum": ["vertical", "horizontal"],
        "default": "horizontal",
        "markdownDescription": localize(3917, null),
        "enumDescriptions": [
          localize(3918, null),
          localize(3919, null)
        ]
      },
      "workbench.editor.centeredLayoutAutoResize": {
        "type": "boolean",
        "default": true,
        "description": localize(3920, null)
      },
      "workbench.editor.centeredLayoutFixedWidth": {
        "type": "boolean",
        "default": false,
        "description": localize(3921, null)
      },
      "workbench.editor.doubleClickTabToToggleEditorGroupSizes": {
        "type": "string",
        "enum": ["maximize", "expand", "off"],
        "default": "expand",
        "markdownDescription": localize(3922, null, "`#workbench.editor.showTabs#`", "`multiple`"),
        "enumDescriptions": [
          localize(3923, null),
          localize(3924, null),
          localize(3925, null)
        ]
      },
      "workbench.editor.limit.enabled": {
        "type": "boolean",
        "default": false,
        "description": localize(3926, null)
      },
      "workbench.editor.limit.value": {
        "type": "number",
        "default": 10,
        "exclusiveMinimum": 0,
        "markdownDescription": localize(3927, null, "`#workbench.editor.limit.perEditorGroup#`")
      },
      "workbench.editor.limit.excludeDirty": {
        "type": "boolean",
        "default": false,
        "description": localize(3928, null)
      },
      "workbench.editor.limit.perEditorGroup": {
        "type": "boolean",
        "default": false,
        "description": localize(3929, null)
      },
      "workbench.localHistory.enabled": {
        "type": "boolean",
        "default": true,
        "description": localize(3930, null),
        "scope": 4
        /* ConfigurationScope.RESOURCE */
      },
      "workbench.localHistory.maxFileSize": {
        "type": "number",
        "default": 256,
        "minimum": 1,
        "description": localize(3931, null),
        "scope": 4
        /* ConfigurationScope.RESOURCE */
      },
      "workbench.localHistory.maxFileEntries": {
        "type": "number",
        "default": 50,
        "minimum": 0,
        "description": localize(3932, null),
        "scope": 4
        /* ConfigurationScope.RESOURCE */
      },
      "workbench.localHistory.exclude": {
        "type": "object",
        "patternProperties": {
          ".*": { "type": "boolean" }
        },
        "markdownDescription": localize(3933, null),
        "scope": 4
        /* ConfigurationScope.RESOURCE */
      },
      "workbench.localHistory.mergeWindow": {
        "type": "number",
        "default": 10,
        "minimum": 1,
        "markdownDescription": localize(3934, null),
        "scope": 4
        /* ConfigurationScope.RESOURCE */
      },
      "workbench.commandPalette.history": {
        "type": "number",
        "description": localize(3935, null),
        "default": 50,
        "minimum": 0
      },
      "workbench.commandPalette.preserveInput": {
        "type": "boolean",
        "description": localize(3936, null),
        "default": false
      },
      "workbench.commandPalette.experimental.suggestCommands": {
        "type": "boolean",
        tags: ["experimental"],
        "description": localize(3937, null),
        "default": false
      },
      "workbench.commandPalette.experimental.askChatLocation": {
        "type": "string",
        tags: ["experimental"],
        "description": localize(3938, null),
        "default": "chatView",
        enum: ["chatView", "quickChat"],
        enumDescriptions: [
          localize(3939, null),
          localize(3940, null)
        ]
      },
      "workbench.commandPalette.experimental.enableNaturalLanguageSearch": {
        "type": "boolean",
        tags: ["experimental"],
        "description": localize(3941, null),
        "default": true
      },
      "workbench.quickOpen.closeOnFocusLost": {
        "type": "boolean",
        "description": localize(3942, null),
        "default": true
      },
      "workbench.quickOpen.preserveInput": {
        "type": "boolean",
        "description": localize(3943, null),
        "default": false
      },
      "workbench.settings.openDefaultSettings": {
        "type": "boolean",
        "description": localize(3944, null),
        "default": false
      },
      "workbench.settings.useSplitJSON": {
        "type": "boolean",
        "markdownDescription": localize(3945, null),
        "default": false
      },
      "workbench.settings.openDefaultKeybindings": {
        "type": "boolean",
        "description": localize(3946, null),
        "default": false
      },
      "workbench.sideBar.location": {
        "type": "string",
        "enum": ["left", "right"],
        "default": "left",
        "description": localize(3947, null)
      },
      "workbench.panel.showLabels": {
        "type": "boolean",
        "default": true,
        "description": localize(3948, null)
      },
      "workbench.panel.defaultLocation": {
        "type": "string",
        "enum": ["left", "bottom", "top", "right"],
        "default": "bottom",
        "description": localize(3949, null)
      },
      "workbench.panel.opensMaximized": {
        "type": "string",
        "enum": ["always", "never", "preserve"],
        "default": "preserve",
        "description": localize(3950, null),
        "enumDescriptions": [
          localize(3951, null),
          localize(3952, null),
          localize(3953, null)
        ]
      },
      "workbench.statusBar.visible": {
        "type": "boolean",
        "default": true,
        "description": localize(3954, null)
      },
      [
        "workbench.activityBar.location"
        /* LayoutSettings.ACTIVITY_BAR_LOCATION */
      ]: {
        "type": "string",
        "enum": ["default", "top", "bottom", "hidden"],
        "default": "default",
        "markdownDescription": localize(3955, null),
        "enumDescriptions": [
          localize(3956, null),
          localize(3957, null),
          localize(3958, null),
          localize(3959, null)
        ]
      },
      "workbench.activityBar.iconClickBehavior": {
        "type": "string",
        "enum": ["toggle", "focus"],
        "default": "toggle",
        "markdownDescription": localize(3960, null, "`#workbench.activityBar.location#`", "`default`"),
        "enumDescriptions": [
          localize(3961, null),
          localize(3962, null)
        ]
      },
      "workbench.view.alwaysShowHeaderActions": {
        "type": "boolean",
        "default": false,
        "description": localize(3963, null)
      },
      "workbench.view.showQuietly": {
        "type": "object",
        "description": localize(3964, null),
        "scope": 3,
        "properties": {
          "workbench.panel.output": {
            "type": "boolean",
            "description": localize(3965, null)
          }
        },
        "additionalProperties": false
      },
      "workbench.fontAliasing": {
        "type": "string",
        "enum": ["default", "antialiased", "none", "auto"],
        "default": "default",
        "description": localize(3966, null),
        "enumDescriptions": [
          localize(3967, null),
          localize(3968, null),
          localize(3969, null),
          localize(3970, null)
        ],
        "included": $m
      },
      "workbench.settings.editor": {
        "type": "string",
        "enum": ["ui", "json"],
        "enumDescriptions": [
          localize(3971, null),
          localize(3972, null)
        ],
        "description": localize(3973, null),
        "default": "ui",
        "scope": 3
        /* ConfigurationScope.WINDOW */
      },
      "workbench.hover.delay": {
        "type": "number",
        "description": localize(3974, null),
        // Testing has indicated that on Windows and Linux 500 ms matches the native hovers most closely.
        // On Mac, the delay is 1500.
        "default": $m ? 1500 : 500,
        "minimum": 0
      },
      "workbench.reduceMotion": {
        type: "string",
        description: localize(3975, null),
        "enumDescriptions": [
          localize(3976, null),
          localize(3977, null),
          localize(3978, null)
        ],
        default: "auto",
        tags: ["accessibility"],
        enum: ["on", "off", "auto"]
      },
      "workbench.navigationControl.enabled": {
        "type": "boolean",
        "default": true,
        "markdownDescription": $r ? localize(3979, null) : localize(3980, null, "`#window.customTitleBarVisibility#`", "`never`")
      },
      [
        "workbench.layoutControl.enabled"
        /* LayoutSettings.LAYOUT_ACTIONS */
      ]: {
        "type": "boolean",
        "default": true,
        "markdownDescription": $r ? localize(3981, null) : localize(3982, null, "`#window.customTitleBarVisibility#`", "`never`")
      },
      "workbench.layoutControl.type": {
        "type": "string",
        "enum": ["menu", "toggles", "both"],
        "enumDescriptions": [
          localize(3983, null),
          localize(3984, null),
          localize(3985, null)
        ],
        "default": "both",
        "description": localize(3986, null)
      },
      "workbench.tips.enabled": {
        "type": "boolean",
        "default": true,
        "description": localize(3987, null)
      }
    }
  });
  let windowTitleDescription = localize(3988, null);
  windowTitleDescription += "\n- " + [
    localize(3989, null),
    localize(3990, null),
    localize(3991, null),
    localize(3992, null),
    localize(3993, null),
    localize(3994, null),
    localize(3995, null),
    localize(3996, null),
    localize(3997, null),
    localize(3998, null),
    localize(3999, null),
    localize(4e3, null),
    localize(4001, null),
    localize(4002, null),
    localize(4003, null),
    localize(4004, null),
    localize(4005, null),
    localize(4006, null),
    localize(4007, null)
  ].join("\n- ");
  registry.registerConfiguration({
    ...$XL,
    "properties": {
      "window.title": {
        "type": "string",
        "default": $8Tb,
        "markdownDescription": windowTitleDescription
      },
      "window.titleSeparator": {
        "type": "string",
        "default": $9Tb,
        "markdownDescription": localize(4008, null, "`#window.title#`")
      },
      [
        "window.commandCenter"
        /* LayoutSettings.COMMAND_CENTER */
      ]: {
        type: "boolean",
        default: true,
        markdownDescription: $r ? localize(4009, null) : localize(4010, null, "`#window.customTitleBarVisibility#`", "`never`")
      },
      "window.menuBarVisibility": {
        "type": "string",
        "enum": ["classic", "visible", "toggle", "hidden", "compact"],
        "markdownEnumDescriptions": [
          localize(4011, null),
          localize(4012, null),
          $m ? localize(4013, null) : localize(4014, null),
          localize(4015, null),
          $r ? localize(4016, null) : localize(4017, null, "`#window.titleBarStyle#`", "`native`")
        ],
        "default": $r ? "compact" : "classic",
        "scope": 1,
        "markdownDescription": $m ? localize(4018, null) : localize(4019, null),
        "included": $l || $n || $r
      },
      "window.enableMenuBarMnemonics": {
        "type": "boolean",
        "default": true,
        "scope": 1,
        "description": localize(4020, null),
        "included": $l || $n
      },
      "window.customMenuBarAltFocus": {
        "type": "boolean",
        "default": true,
        "scope": 1,
        "markdownDescription": localize(4021, null),
        "included": $l || $n
      },
      "window.openFilesInNewWindow": {
        "type": "string",
        "enum": ["on", "off", "default"],
        "enumDescriptions": [
          localize(4022, null),
          localize(4023, null),
          $m ? localize(4024, null) : localize(4025, null)
        ],
        "default": "off",
        "scope": 1,
        "markdownDescription": $m ? localize(4026, null) : localize(4027, null)
      },
      "window.openFoldersInNewWindow": {
        "type": "string",
        "enum": ["on", "off", "default"],
        "enumDescriptions": [
          localize(4028, null),
          localize(4029, null),
          localize(4030, null)
        ],
        "default": "default",
        "scope": 1,
        "markdownDescription": localize(4031, null)
      },
      "window.confirmBeforeClose": {
        "type": "string",
        "enum": ["always", "keyboardOnly", "never"],
        "enumDescriptions": [
          $r ? localize(4032, null) : localize(4033, null),
          $r ? localize(4034, null) : localize(4035, null),
          $r ? localize(4036, null) : localize(4037, null)
        ],
        "default": $r && !$2e() ? "keyboardOnly" : "never",
        // on by default in web, unless PWA, never on desktop
        "markdownDescription": $r ? localize(4038, null) : localize(4039, null),
        "scope": 1
        /* ConfigurationScope.APPLICATION */
      }
    }
  });
  $PL(
    $3L.ID,
    $3L,
    4
    /* WorkbenchPhase.Eventually */
  );
  registry.registerConfiguration({
    ...$WL,
    "properties": {
      "problems.visibility": {
        "type": "boolean",
        "default": true,
        "description": localize(4040, null)
      }
    }
  });
  registry.registerConfiguration({
    "id": "zenMode",
    "order": 9,
    "title": localize(4041, null),
    "type": "object",
    "properties": {
      "zenMode.fullScreen": {
        "type": "boolean",
        "default": true,
        "description": localize(4042, null)
      },
      "zenMode.centerLayout": {
        "type": "boolean",
        "default": true,
        "description": localize(4043, null)
      },
      "zenMode.showTabs": {
        "type": "string",
        "enum": ["multiple", "single", "none"],
        "description": localize(4044, null),
        "enumDescriptions": [
          localize(4045, null),
          localize(4046, null),
          localize(4047, null)
        ],
        "default": "multiple"
      },
      "zenMode.hideStatusBar": {
        "type": "boolean",
        "default": true,
        "description": localize(4048, null)
      },
      "zenMode.hideActivityBar": {
        "type": "boolean",
        "default": true,
        "description": localize(4049, null)
      },
      "zenMode.hideLineNumbers": {
        "type": "boolean",
        "default": true,
        "description": localize(4050, null)
      },
      "zenMode.restore": {
        "type": "boolean",
        "default": true,
        "description": localize(4051, null)
      },
      "zenMode.silentNotifications": {
        "type": "boolean",
        "default": true,
        "description": localize(4052, null)
      }
    }
  });
})();
$Wn.as($YL.ConfigurationMigration).registerConfigurationMigrations([{
  key: "workbench.activityBar.visible",
  migrateFn: (value) => {
    const result = [];
    if (value !== void 0) {
      result.push(["workbench.activityBar.visible", { value: void 0 }]);
    }
    if (value === false) {
      result.push(["workbench.activityBar.location", {
        value: "hidden"
        /* ActivityBarPosition.HIDDEN */
      }]);
    }
    return result;
  }
}]);
$Wn.as($YL.ConfigurationMigration).registerConfigurationMigrations([{
  key: "workbench.activityBar.location",
  migrateFn: (value) => {
    const results = [];
    if (value === "side") {
      results.push(["workbench.activityBar.location", {
        value: "default"
        /* ActivityBarPosition.DEFAULT */
      }]);
    }
    return results;
  }
}]);
$Wn.as($YL.ConfigurationMigration).registerConfigurationMigrations([{
  key: "workbench.editor.doubleClickTabToToggleEditorGroupSizes",
  migrateFn: (value) => {
    const results = [];
    if (typeof value === "boolean") {
      value = value ? "expand" : "off";
      results.push(["workbench.editor.doubleClickTabToToggleEditorGroupSizes", { value }]);
    }
    return results;
  }
}, {
  key: "workbench.editor.showTabs",
  migrateFn: (value) => {
    const results = [];
    if (typeof value === "boolean") {
      value = value ? "multiple" : "single";
      results.push(["workbench.editor.showTabs", { value }]);
    }
    return results;
  }
}, {
  key: "workbench.editor.tabCloseButton",
  migrateFn: (value) => {
    const result = [];
    if (value === "left" || value === "right") {
      result.push(["workbench.editor.tabActionLocation", { value }]);
    } else if (value === "off") {
      result.push(["workbench.editor.tabActionCloseVisibility", { value: false }]);
    }
    return result;
  }
}, {
  key: "zenMode.hideTabs",
  migrateFn: (value) => {
    const result = [["zenMode.hideTabs", { value: void 0 }]];
    if (value === true) {
      result.push(["zenMode.showTabs", { value: "single" }]);
    }
    return result;
  }
}]);

// out-build/vs/workbench/browser/actions/textInputActions.js
var $$Tb = class $$Tb2 extends $3c {
  static {
    this.ID = "workbench.contrib.textInputActionsProvider";
  }
  constructor(b, c, f) {
    super();
    this.b = b;
    this.c = c;
    this.f = f;
    this.a = new $sf(() => this.g());
    this.h();
  }
  g() {
    return [
      // Undo/Redo
      new $Um("undo", localize(2985, null), void 0, true, async () => $Pj().execCommand("undo")),
      new $Um("redo", localize(2986, null), void 0, true, async () => $Pj().execCommand("redo")),
      new $Wm(),
      // Cut / Copy / Paste
      new $Um("editor.action.clipboardCutAction", localize(2987, null), void 0, true, async () => $Pj().execCommand("cut")),
      new $Um("editor.action.clipboardCopyAction", localize(2988, null), void 0, true, async () => $Pj().execCommand("copy")),
      new $Um("editor.action.clipboardPasteAction", localize(2989, null), void 0, true, async (element) => {
        if ($p) {
          $Pj().execCommand("paste");
        } else {
          const clipboardText = await this.f.readText();
          if ($Xj(element) || $Yj(element)) {
            const selectionStart = element.selectionStart || 0;
            const selectionEnd = element.selectionEnd || 0;
            element.value = `${element.value.substring(0, selectionStart)}${clipboardText}${element.value.substring(selectionEnd, element.value.length)}`;
            element.selectionStart = selectionStart + clipboardText.length;
            element.selectionEnd = element.selectionStart;
            element.dispatchEvent(new Event("input", { bubbles: true, cancelable: true }));
          }
        }
      }),
      new $Wm(),
      // Select All
      new $Um("editor.action.selectAll", localize(2990, null), void 0, true, async () => $Pj().execCommand("selectAll"))
    ];
  }
  h() {
    this.B(Event2.runAndSubscribe(this.b.onDidAddContainer, ({ container: container2, disposables }) => {
      disposables.add($_i(container2, "contextmenu", (e) => this.j(getWindow(container2), e)));
    }, { container: this.b.mainContainer, disposables: this.q }));
  }
  j(targetWindow, e) {
    if (e.defaultPrevented) {
      return;
    }
    const target = e.target;
    if (!$Uj(target) || target.nodeName.toLowerCase() !== "input" && target.nodeName.toLowerCase() !== "textarea") {
      return;
    }
    $9j.stop(e, true);
    const event = new $lf(targetWindow, e);
    this.c.showContextMenu({
      getAnchor: () => event,
      getActions: () => this.a.value,
      getActionsContext: () => target
    });
  }
};
$$Tb = __decorate([
  __param(0, $Vlb),
  __param(1, $50),
  __param(2, $30)
], $$Tb);
$PL(
  $$Tb.ID,
  $$Tb,
  2
  /* WorkbenchPhase.BlockRestore */
);

// out-build/vs/workbench/browser/actions/developerActions.js
var InspectContextKeysAction = class extends $gJ {
  constructor() {
    super({
      id: "workbench.action.inspectContextKeys",
      title: localize2(2814, "Inspect Context Keys"),
      category: $qn.Developer,
      f1: true
    });
  }
  run(accessor) {
    const contextKeyService = accessor.get($on);
    const disposables = new $2c();
    const stylesheet = $VZ(void 0, void 0, disposables);
    $XZ("*", "cursor: crosshair !important;", stylesheet);
    const hoverFeedback = document.createElement("div");
    const activeDocument = $Pj();
    activeDocument.body.appendChild(hoverFeedback);
    disposables.add($1c(() => hoverFeedback.remove()));
    hoverFeedback.style.position = "absolute";
    hoverFeedback.style.pointerEvents = "none";
    hoverFeedback.style.backgroundColor = "rgba(255, 0, 0, 0.5)";
    hoverFeedback.style.zIndex = "1000";
    const onMouseMove = disposables.add(new $9Z(activeDocument, "mousemove", true));
    disposables.add(onMouseMove.event((e) => {
      const target = e.target;
      const position = $vj(target);
      hoverFeedback.style.top = `${position.top}px`;
      hoverFeedback.style.left = `${position.left}px`;
      hoverFeedback.style.width = `${position.width}px`;
      hoverFeedback.style.height = `${position.height}px`;
    }));
    const onMouseDown = disposables.add(new $9Z(activeDocument, "mousedown", true));
    Event2.once(onMouseDown.event)((e) => {
      e.preventDefault();
      e.stopPropagation();
    }, null, disposables);
    const onMouseUp = disposables.add(new $9Z(activeDocument, "mouseup", true));
    Event2.once(onMouseUp.event)((e) => {
      e.preventDefault();
      e.stopPropagation();
      const context = contextKeyService.getContext(e.target);
      console.log(context.collectAllValues());
      $Xc(disposables);
    }, null, disposables);
  }
};
var ToggleScreencastModeAction = class _ToggleScreencastModeAction extends $gJ {
  constructor() {
    super({
      id: "workbench.action.toggleScreencastMode",
      title: localize2(2815, "Toggle Screencast Mode"),
      category: $qn.Developer,
      f1: true
    });
  }
  run(accessor) {
    if (_ToggleScreencastModeAction.disposable) {
      _ToggleScreencastModeAction.disposable.dispose();
      _ToggleScreencastModeAction.disposable = void 0;
      return;
    }
    const layoutService = accessor.get($Ulb);
    const configurationService = accessor.get($kl);
    const keybindingService = accessor.get($Ty);
    const disposables = new $2c();
    const container2 = layoutService.activeContainer;
    const mouseMarker = $bk(container2, $(".screencast-mouse"));
    disposables.add($1c(() => mouseMarker.remove()));
    const keyboardMarker = $bk(container2, $(".screencast-keyboard"));
    disposables.add($1c(() => keyboardMarker.remove()));
    const onMouseDown = disposables.add(new $ze());
    const onMouseUp = disposables.add(new $ze());
    const onMouseMove = disposables.add(new $ze());
    function registerContainerListeners(container3, disposables2) {
      disposables2.add(disposables2.add(new $9Z(container3, "mousedown", true)).event((e) => onMouseDown.fire(e)));
      disposables2.add(disposables2.add(new $9Z(container3, "mouseup", true)).event((e) => onMouseUp.fire(e)));
      disposables2.add(disposables2.add(new $9Z(container3, "mousemove", true)).event((e) => onMouseMove.fire(e)));
    }
    for (const { window: window3, disposables: disposables2 } of getWindows()) {
      registerContainerListeners(layoutService.getContainer(window3), disposables2);
    }
    disposables.add(onDidRegisterWindow(({ window: window3, disposables: disposables2 }) => registerContainerListeners(layoutService.getContainer(window3), disposables2)));
    disposables.add(layoutService.onDidChangeActiveContainer(() => {
      layoutService.activeContainer.appendChild(mouseMarker);
      layoutService.activeContainer.appendChild(keyboardMarker);
    }));
    const updateMouseIndicatorColor = () => {
      mouseMarker.style.borderColor = $Vn.fromHex(configurationService.getValue("screencastMode.mouseIndicatorColor")).toString();
    };
    let mouseIndicatorSize;
    const updateMouseIndicatorSize = () => {
      mouseIndicatorSize = $4i(configurationService.getValue("screencastMode.mouseIndicatorSize") || 20, 20, 100);
      mouseMarker.style.height = `${mouseIndicatorSize}px`;
      mouseMarker.style.width = `${mouseIndicatorSize}px`;
    };
    updateMouseIndicatorColor();
    updateMouseIndicatorSize();
    disposables.add(onMouseDown.event((e) => {
      mouseMarker.style.top = `${e.clientY - mouseIndicatorSize / 2}px`;
      mouseMarker.style.left = `${e.clientX - mouseIndicatorSize / 2}px`;
      mouseMarker.style.display = "block";
      mouseMarker.style.transform = `scale(${1})`;
      mouseMarker.style.transition = "transform 0.1s";
      const mouseMoveListener = onMouseMove.event((e2) => {
        mouseMarker.style.top = `${e2.clientY - mouseIndicatorSize / 2}px`;
        mouseMarker.style.left = `${e2.clientX - mouseIndicatorSize / 2}px`;
        mouseMarker.style.transform = `scale(${0.8})`;
      });
      Event2.once(onMouseUp.event)(() => {
        mouseMarker.style.display = "none";
        mouseMoveListener.dispose();
      });
    }));
    const updateKeyboardFontSize = () => {
      keyboardMarker.style.fontSize = `${$4i(configurationService.getValue("screencastMode.fontSize") || 56, 20, 100)}px`;
    };
    const updateKeyboardMarker = () => {
      keyboardMarker.style.bottom = `${$4i(configurationService.getValue("screencastMode.verticalOffset") || 0, 0, 90)}%`;
    };
    let keyboardMarkerTimeout;
    const updateKeyboardMarkerTimeout = () => {
      keyboardMarkerTimeout = $4i(configurationService.getValue("screencastMode.keyboardOverlayTimeout") || 800, 500, 5e3);
    };
    updateKeyboardFontSize();
    updateKeyboardMarker();
    updateKeyboardMarkerTimeout();
    disposables.add(configurationService.onDidChangeConfiguration((e) => {
      if (e.affectsConfiguration("screencastMode.verticalOffset")) {
        updateKeyboardMarker();
      }
      if (e.affectsConfiguration("screencastMode.fontSize")) {
        updateKeyboardFontSize();
      }
      if (e.affectsConfiguration("screencastMode.keyboardOverlayTimeout")) {
        updateKeyboardMarkerTimeout();
      }
      if (e.affectsConfiguration("screencastMode.mouseIndicatorColor")) {
        updateMouseIndicatorColor();
      }
      if (e.affectsConfiguration("screencastMode.mouseIndicatorSize")) {
        updateMouseIndicatorSize();
      }
    }));
    const onKeyDown = disposables.add(new $ze());
    const onCompositionStart = disposables.add(new $ze());
    const onCompositionUpdate = disposables.add(new $ze());
    const onCompositionEnd = disposables.add(new $ze());
    function registerWindowListeners(window3, disposables2) {
      disposables2.add(disposables2.add(new $9Z(window3, "keydown", true)).event((e) => onKeyDown.fire(e)));
      disposables2.add(disposables2.add(new $9Z(window3, "compositionstart", true)).event((e) => onCompositionStart.fire(e)));
      disposables2.add(disposables2.add(new $9Z(window3, "compositionupdate", true)).event((e) => onCompositionUpdate.fire(e)));
      disposables2.add(disposables2.add(new $9Z(window3, "compositionend", true)).event((e) => onCompositionEnd.fire(e)));
    }
    for (const { window: window3, disposables: disposables2 } of getWindows()) {
      registerWindowListeners(window3, disposables2);
    }
    disposables.add(onDidRegisterWindow(({ window: window3, disposables: disposables2 }) => registerWindowListeners(window3, disposables2)));
    let length = 0;
    let composing = void 0;
    let imeBackSpace = false;
    const clearKeyboardScheduler = new $8h(() => {
      keyboardMarker.textContent = "";
      composing = void 0;
      length = 0;
    }, keyboardMarkerTimeout);
    disposables.add(onCompositionStart.event((e) => {
      imeBackSpace = true;
    }));
    disposables.add(onCompositionUpdate.event((e) => {
      if (e.data && imeBackSpace) {
        if (length > 20) {
          keyboardMarker.innerText = "";
          length = 0;
        }
        composing = composing ?? $bk(keyboardMarker, $("span.key"));
        composing.textContent = e.data;
      } else if (imeBackSpace) {
        keyboardMarker.innerText = "";
        $bk(keyboardMarker, $("span.key", {}, `Backspace`));
      }
      clearKeyboardScheduler.schedule();
    }));
    disposables.add(onCompositionEnd.event((e) => {
      composing = void 0;
      length++;
    }));
    disposables.add(onKeyDown.event((e) => {
      if (e.key === "Process" || /[\uac00-\ud787\u3131-\u314e\u314f-\u3163\u3041-\u3094\u30a1-\u30f4\u30fc\u3005\u3006\u3024\u4e00-\u9fa5]/u.test(e.key)) {
        if (e.code === "Backspace") {
          imeBackSpace = true;
        } else if (!e.code.includes("Key")) {
          composing = void 0;
          imeBackSpace = false;
        } else {
          imeBackSpace = true;
        }
        clearKeyboardScheduler.schedule();
        return;
      }
      if (e.isComposing) {
        return;
      }
      const options3 = configurationService.getValue("screencastMode.keyboardOptions");
      const event = new $if(e);
      const shortcut = keybindingService.softDispatch(event, event.target);
      if (shortcut.kind === 2 && shortcut.commandId && !(options3.showSingleEditorCursorMoves ?? true) && ["cursorLeft", "cursorRight", "cursorUp", "cursorDown"].includes(shortcut.commandId)) {
        return;
      }
      if (event.ctrlKey || event.altKey || event.metaKey || event.shiftKey || length > 20 || event.keyCode === 1 || event.keyCode === 9 || event.keyCode === 16 || event.keyCode === 18 || event.keyCode === 15 || event.keyCode === 17) {
        keyboardMarker.innerText = "";
        length = 0;
      }
      const keybinding = keybindingService.resolveKeyboardEvent(event);
      const commandDetails = this.a(shortcut) && shortcut.commandId ? this.b(shortcut.commandId) : void 0;
      let commandAndGroupLabel = commandDetails?.title;
      let keyLabel = keybinding.getLabel();
      if (commandDetails) {
        if ((options3.showCommandGroups ?? false) && commandDetails.category) {
          commandAndGroupLabel = `${commandDetails.category}: ${commandAndGroupLabel} `;
        }
        if (this.a(shortcut) && shortcut.commandId) {
          const keybindings = keybindingService.lookupKeybindings(shortcut.commandId).filter((k) => k.getLabel()?.endsWith(keyLabel ?? ""));
          if (keybindings.length > 0) {
            keyLabel = keybindings[keybindings.length - 1].getLabel();
          }
        }
      }
      if ((options3.showCommands ?? true) && commandAndGroupLabel) {
        $bk(keyboardMarker, $("span.title", {}, `${commandAndGroupLabel} `));
      }
      if ((options3.showKeys ?? true) || (options3.showKeybindings ?? true) && this.a(shortcut)) {
        keyLabel = keyLabel?.replace("UpArrow", "\u2191")?.replace("DownArrow", "\u2193")?.replace("LeftArrow", "\u2190")?.replace("RightArrow", "\u2192");
        $bk(keyboardMarker, $("span.key", {}, keyLabel ?? ""));
      }
      length++;
      clearKeyboardScheduler.schedule();
    }));
    _ToggleScreencastModeAction.disposable = disposables;
  }
  a(resolutionResult) {
    return resolutionResult.kind === 2;
  }
  b(commandId) {
    const fromMenuRegistry = $dJ.getCommand(commandId);
    if (fromMenuRegistry) {
      return {
        title: typeof fromMenuRegistry.title === "string" ? fromMenuRegistry.title : fromMenuRegistry.title.value,
        category: fromMenuRegistry.category ? typeof fromMenuRegistry.category === "string" ? fromMenuRegistry.category : fromMenuRegistry.category.value : void 0
      };
    }
    const fromCommandsRegistry = $tn.getCommand(commandId);
    if (fromCommandsRegistry && fromCommandsRegistry.metadata?.description) {
      return { title: typeof fromCommandsRegistry.metadata.description === "string" ? fromCommandsRegistry.metadata.description : fromCommandsRegistry.metadata.description.value };
    }
    return void 0;
  }
};
var LogStorageAction = class extends $gJ {
  constructor() {
    super({
      id: "workbench.action.logStorage",
      title: localize2(2816, "Log Storage Database Contents"),
      category: $qn.Developer,
      f1: true
    });
  }
  run(accessor) {
    const storageService = accessor.get($jv);
    const dialogService = accessor.get($Yv);
    storageService.log();
    dialogService.info(localize(2788, null), localize(2789, null));
  }
};
var LogWorkingCopiesAction = class extends $gJ {
  constructor() {
    super({
      id: "workbench.action.logWorkingCopies",
      title: localize2(2817, "Log Working Copies"),
      category: $qn.Developer,
      f1: true
    });
  }
  async run(accessor) {
    const workingCopyService = accessor.get($XI);
    const workingCopyBackupService = accessor.get($yG);
    const logService = accessor.get($wn);
    const outputService = accessor.get($RS);
    const backups = await workingCopyBackupService.getBackups();
    const msg = [
      ``,
      `[Working Copies]`,
      ...workingCopyService.workingCopies.length > 0 ? workingCopyService.workingCopies.map((workingCopy) => `${workingCopy.isDirty() ? "\u25CF " : ""}${workingCopy.resource.toString(true)} (typeId: ${workingCopy.typeId || "<no typeId>"})`) : ["<none>"],
      ``,
      `[Backups]`,
      ...backups.length > 0 ? backups.map((backup) => `${backup.resource.toString(true)} (typeId: ${backup.typeId || "<no typeId>"})`) : ["<none>"]
    ];
    logService.info(msg.join("\n"));
    outputService.showChannel($PCb, true);
  }
};
var RemoveLargeStorageEntriesAction = class _RemoveLargeStorageEntriesAction extends $gJ {
  static {
    this.a = 1024 * 16;
  }
  // 16kb
  constructor() {
    super({
      id: "workbench.action.removeLargeStorageDatabaseEntries",
      title: localize2(2818, "Remove Large Storage Database Entries..."),
      category: $qn.Developer,
      f1: true
    });
  }
  async run(accessor) {
    const storageService = accessor.get($jv);
    const quickInputService = accessor.get($1M);
    const userDataProfileService = accessor.get($gT);
    const dialogService = accessor.get($Yv);
    const environmentService = accessor.get($Xk);
    const items = [];
    for (const scope of [
      -1,
      0,
      1
      /* StorageScope.WORKSPACE */
    ]) {
      if (scope === 0 && userDataProfileService.currentProfile.isDefault) {
        continue;
      }
      for (const target of [
        1,
        0
        /* StorageTarget.USER */
      ]) {
        for (const key2 of storageService.keys(scope, target)) {
          const value = storageService.get(key2, scope);
          if (value && (!environmentService.isBuilt || value.length > _RemoveLargeStorageEntriesAction.a)) {
            items.push({
              key: key2,
              scope,
              target,
              size: value.length,
              label: key2,
              description: $Sm.formatSize(value.length),
              detail: localize(2790, null, scope === -1 ? localize(2791, null) : scope === 0 ? localize(2792, null) : localize(2793, null), target === 1 ? localize(2794, null) : localize(2795, null))
            });
          }
        }
      }
    }
    items.sort((itemA, itemB) => itemB.size - itemA.size);
    const selectedItems = await new Promise((resolve) => {
      const disposables = new $2c();
      const picker = disposables.add(quickInputService.createQuickPick());
      picker.items = items;
      picker.canSelectMany = true;
      picker.ok = false;
      picker.customButton = true;
      picker.hideCheckAll = true;
      picker.customLabel = localize(2796, null);
      picker.placeholder = localize(2797, null);
      if (items.length === 0) {
        picker.description = localize(2798, null);
      }
      picker.show();
      disposables.add(picker.onDidCustom(() => {
        resolve(picker.selectedItems);
        picker.hide();
      }));
      disposables.add(picker.onDidHide(() => disposables.dispose()));
    });
    if (selectedItems.length === 0) {
      return;
    }
    const { confirmed } = await dialogService.confirm({
      type: "warning",
      message: localize(2799, null),
      detail: localize(2800, null, selectedItems.map((item) => item.label).join("\n")),
      primaryButton: localize(2801, null)
    });
    if (!confirmed) {
      return;
    }
    const scopesToOptimize = /* @__PURE__ */ new Set();
    for (const item of selectedItems) {
      storageService.remove(item.key, item.scope);
      scopesToOptimize.add(item.scope);
    }
    for (const scope of scopesToOptimize) {
      await storageService.optimize(scope);
    }
  }
};
var tracker = void 0;
var trackedDisposables = /* @__PURE__ */ new Set();
var DisposablesSnapshotStateContext = new $nn("dirtyWorkingCopies", "stopped");
var StartTrackDisposables = class extends $gJ {
  constructor() {
    super({
      id: "workbench.action.startTrackDisposables",
      title: localize2(2819, "Start Tracking Disposables"),
      category: $qn.Developer,
      f1: true,
      precondition: $7m.and(DisposablesSnapshotStateContext.isEqualTo("pending").negate(), DisposablesSnapshotStateContext.isEqualTo("started").negate())
    });
  }
  run(accessor) {
    const disposablesSnapshotStateContext = DisposablesSnapshotStateContext.bindTo(accessor.get($on));
    disposablesSnapshotStateContext.set("started");
    trackedDisposables.clear();
    tracker = new $Rc();
    $Sc(tracker);
  }
};
var SnapshotTrackedDisposables = class extends $gJ {
  constructor() {
    super({
      id: "workbench.action.snapshotTrackedDisposables",
      title: localize2(2820, "Snapshot Tracked Disposables"),
      category: $qn.Developer,
      f1: true,
      precondition: DisposablesSnapshotStateContext.isEqualTo("started")
    });
  }
  run(accessor) {
    const disposablesSnapshotStateContext = DisposablesSnapshotStateContext.bindTo(accessor.get($on));
    disposablesSnapshotStateContext.set("pending");
    trackedDisposables = new Set(tracker?.computeLeakingDisposables(1e3)?.leaks.map((disposable) => disposable.value));
  }
};
var StopTrackDisposables = class extends $gJ {
  constructor() {
    super({
      id: "workbench.action.stopTrackDisposables",
      title: localize2(2821, "Stop Tracking Disposables"),
      category: $qn.Developer,
      f1: true,
      precondition: DisposablesSnapshotStateContext.isEqualTo("pending")
    });
  }
  run(accessor) {
    const editorService = accessor.get($mJ);
    const disposablesSnapshotStateContext = DisposablesSnapshotStateContext.bindTo(accessor.get($on));
    disposablesSnapshotStateContext.set("stopped");
    if (tracker) {
      const disposableLeaks = /* @__PURE__ */ new Set();
      for (const disposable of new Set(tracker.computeLeakingDisposables(1e3)?.leaks) ?? []) {
        if (trackedDisposables.has(disposable.value)) {
          disposableLeaks.add(disposable);
        }
      }
      const leaks = tracker.computeLeakingDisposables(1e3, Array.from(disposableLeaks));
      if (leaks) {
        editorService.openEditor({ resource: void 0, contents: leaks.details });
      }
    }
    $Sc(null);
    tracker = void 0;
    trackedDisposables.clear();
  }
};
$hJ(InspectContextKeysAction);
$hJ(ToggleScreencastModeAction);
$hJ(LogStorageAction);
$hJ(LogWorkingCopiesAction);
$hJ(RemoveLargeStorageEntriesAction);
if (!product_default.commit) {
  $hJ(StartTrackDisposables);
  $hJ(SnapshotTrackedDisposables);
  $hJ(StopTrackDisposables);
}
var configurationRegistry5 = $Wn.as($Ht.Configuration);
configurationRegistry5.registerConfiguration({
  id: "screencastMode",
  order: 9,
  title: localize(2802, null),
  type: "object",
  properties: {
    "screencastMode.verticalOffset": {
      type: "number",
      default: 20,
      minimum: 0,
      maximum: 90,
      description: localize(2803, null)
    },
    "screencastMode.fontSize": {
      type: "number",
      default: 56,
      minimum: 20,
      maximum: 100,
      description: localize(2804, null)
    },
    "screencastMode.keyboardOptions": {
      type: "object",
      description: localize(2805, null),
      properties: {
        "showKeys": {
          type: "boolean",
          default: true,
          description: localize(2806, null)
        },
        "showKeybindings": {
          type: "boolean",
          default: true,
          description: localize(2807, null)
        },
        "showCommands": {
          type: "boolean",
          default: true,
          description: localize(2808, null)
        },
        "showCommandGroups": {
          type: "boolean",
          default: false,
          description: localize(2809, null)
        },
        "showSingleEditorCursorMoves": {
          type: "boolean",
          default: true,
          description: localize(2810, null)
        }
      },
      default: {
        "showKeys": true,
        "showKeybindings": true,
        "showCommands": true,
        "showCommandGroups": false,
        "showSingleEditorCursorMoves": true
      },
      additionalProperties: false
    },
    "screencastMode.keyboardOverlayTimeout": {
      type: "number",
      default: 800,
      minimum: 500,
      maximum: 5e3,
      description: localize(2811, null)
    },
    "screencastMode.mouseIndicatorColor": {
      type: "string",
      format: "color-hex",
      default: "#FF0000",
      description: localize(2812, null)
    },
    "screencastMode.mouseIndicatorSize": {
      type: "number",
      default: 20,
      minimum: 20,
      maximum: 100,
      description: localize(2813, null)
    }
  }
});

// out-build/vs/workbench/browser/actions/helpActions.js
var KeybindingsReferenceAction = class _KeybindingsReferenceAction extends $gJ {
  static {
    this.ID = "workbench.action.keybindingsReference";
  }
  static {
    this.AVAILABLE = !!($n ? product_default.keyboardShortcutsUrlLinux : $m ? product_default.keyboardShortcutsUrlMac : product_default.keyboardShortcutsUrlWin);
  }
  constructor() {
    super({
      id: _KeybindingsReferenceAction.ID,
      title: {
        ...localize2(2830, "Keyboard Shortcuts Reference"),
        mnemonicTitle: localize(2822, null)
      },
      category: $qn.Help,
      f1: true,
      keybinding: {
        weight: 200,
        when: null,
        primary: $$e(
          2048 | 41,
          2048 | 48
          /* KeyCode.KeyR */
        )
      },
      menu: {
        id: $bJ.MenubarHelpMenu,
        group: "2_reference",
        order: 1
      }
    });
  }
  run(accessor) {
    const productService = accessor.get($Vu);
    const openerService = accessor.get($O4);
    const url = $n ? productService.keyboardShortcutsUrlLinux : $m ? productService.keyboardShortcutsUrlMac : productService.keyboardShortcutsUrlWin;
    if (url) {
      openerService.open(URI.parse(url));
    }
  }
};
var OpenIntroductoryVideosUrlAction = class _OpenIntroductoryVideosUrlAction extends $gJ {
  static {
    this.ID = "workbench.action.openVideoTutorialsUrl";
  }
  static {
    this.AVAILABLE = !!product_default.introductoryVideosUrl;
  }
  constructor() {
    super({
      id: _OpenIntroductoryVideosUrlAction.ID,
      title: {
        ...localize2(2831, "Video Tutorials"),
        mnemonicTitle: localize(2823, null)
      },
      category: $qn.Help,
      f1: true,
      menu: {
        id: $bJ.MenubarHelpMenu,
        group: "2_reference",
        order: 2
      }
    });
  }
  run(accessor) {
    const productService = accessor.get($Vu);
    const openerService = accessor.get($O4);
    if (productService.introductoryVideosUrl) {
      openerService.open(URI.parse(productService.introductoryVideosUrl));
    }
  }
};
var OpenTipsAndTricksUrlAction = class _OpenTipsAndTricksUrlAction extends $gJ {
  static {
    this.ID = "workbench.action.openTipsAndTricksUrl";
  }
  static {
    this.AVAILABLE = !!product_default.tipsAndTricksUrl;
  }
  constructor() {
    super({
      id: _OpenTipsAndTricksUrlAction.ID,
      title: {
        ...localize2(2832, "Tips and Tricks"),
        mnemonicTitle: localize(2824, null)
      },
      category: $qn.Help,
      f1: true,
      menu: {
        id: $bJ.MenubarHelpMenu,
        group: "2_reference",
        order: 3
      }
    });
  }
  run(accessor) {
    const productService = accessor.get($Vu);
    const openerService = accessor.get($O4);
    if (productService.tipsAndTricksUrl) {
      openerService.open(URI.parse(productService.tipsAndTricksUrl));
    }
  }
};
var OpenDocumentationUrlAction = class _OpenDocumentationUrlAction extends $gJ {
  static {
    this.ID = "workbench.action.openDocumentationUrl";
  }
  static {
    this.AVAILABLE = !!($r ? product_default.serverDocumentationUrl : product_default.documentationUrl);
  }
  constructor() {
    super({
      id: _OpenDocumentationUrlAction.ID,
      title: {
        ...localize2(2833, "Documentation"),
        mnemonicTitle: localize(2825, null)
      },
      category: $qn.Help,
      f1: true,
      menu: {
        id: $bJ.MenubarHelpMenu,
        group: "1_welcome",
        order: 3
      }
    });
  }
  run(accessor) {
    const productService = accessor.get($Vu);
    const openerService = accessor.get($O4);
    const url = $r ? productService.serverDocumentationUrl : productService.documentationUrl;
    if (url) {
      openerService.open(URI.parse(url));
    }
  }
};
var OpenNewsletterSignupUrlAction = class _OpenNewsletterSignupUrlAction extends $gJ {
  static {
    this.ID = "workbench.action.openNewsletterSignupUrl";
  }
  static {
    this.AVAILABLE = !!product_default.newsletterSignupUrl;
  }
  constructor() {
    super({
      id: _OpenNewsletterSignupUrlAction.ID,
      title: localize2(2834, "Signup for the VS Code Newsletter"),
      category: $qn.Help,
      f1: true
    });
  }
  run(accessor) {
    const productService = accessor.get($Vu);
    const openerService = accessor.get($O4);
    const telemetryService = accessor.get($zv);
    openerService.open(URI.parse(`${productService.newsletterSignupUrl}?machineId=${encodeURIComponent(telemetryService.machineId)}`));
  }
};
var OpenYouTubeUrlAction = class _OpenYouTubeUrlAction extends $gJ {
  static {
    this.ID = "workbench.action.openYouTubeUrl";
  }
  static {
    this.AVAILABLE = !!product_default.youTubeUrl;
  }
  constructor() {
    super({
      id: _OpenYouTubeUrlAction.ID,
      title: {
        ...localize2(2835, "Join Us on YouTube"),
        mnemonicTitle: localize(2826, null)
      },
      category: $qn.Help,
      f1: true,
      menu: {
        id: $bJ.MenubarHelpMenu,
        group: "3_feedback",
        order: 1
      }
    });
  }
  run(accessor) {
    const productService = accessor.get($Vu);
    const openerService = accessor.get($O4);
    if (productService.youTubeUrl) {
      openerService.open(URI.parse(productService.youTubeUrl));
    }
  }
};
var OpenRequestFeatureUrlAction = class _OpenRequestFeatureUrlAction extends $gJ {
  static {
    this.ID = "workbench.action.openRequestFeatureUrl";
  }
  static {
    this.AVAILABLE = !!product_default.requestFeatureUrl;
  }
  constructor() {
    super({
      id: _OpenRequestFeatureUrlAction.ID,
      title: {
        ...localize2(2836, "Search Feature Requests"),
        mnemonicTitle: localize(2827, null)
      },
      category: $qn.Help,
      f1: true,
      menu: {
        id: $bJ.MenubarHelpMenu,
        group: "3_feedback",
        order: 2
      }
    });
  }
  run(accessor) {
    const productService = accessor.get($Vu);
    const openerService = accessor.get($O4);
    if (productService.requestFeatureUrl) {
      openerService.open(URI.parse(productService.requestFeatureUrl));
    }
  }
};
var OpenLicenseUrlAction = class _OpenLicenseUrlAction extends $gJ {
  static {
    this.ID = "workbench.action.openLicenseUrl";
  }
  static {
    this.AVAILABLE = !!($r ? product_default.serverLicense : product_default.licenseUrl);
  }
  constructor() {
    super({
      id: _OpenLicenseUrlAction.ID,
      title: {
        ...localize2(2837, "View License"),
        mnemonicTitle: localize(2828, null)
      },
      category: $qn.Help,
      f1: true,
      menu: {
        id: $bJ.MenubarHelpMenu,
        group: "4_legal",
        order: 1
      }
    });
  }
  run(accessor) {
    const productService = accessor.get($Vu);
    const openerService = accessor.get($O4);
    const url = $r ? productService.serverLicenseUrl : productService.licenseUrl;
    if (url) {
      if ($z) {
        const queryArgChar = url.indexOf("?") > 0 ? "&" : "?";
        openerService.open(URI.parse(`${url}${queryArgChar}lang=${$z}`));
      } else {
        openerService.open(URI.parse(url));
      }
    }
  }
};
var OpenPrivacyStatementUrlAction = class _OpenPrivacyStatementUrlAction extends $gJ {
  static {
    this.ID = "workbench.action.openPrivacyStatementUrl";
  }
  static {
    this.AVAILABE = !!product_default.privacyStatementUrl;
  }
  constructor() {
    super({
      id: _OpenPrivacyStatementUrlAction.ID,
      title: {
        ...localize2(2838, "Privacy Statement"),
        mnemonicTitle: localize(2829, null)
      },
      category: $qn.Help,
      f1: true,
      menu: {
        id: $bJ.MenubarHelpMenu,
        group: "4_legal",
        order: 2
      }
    });
  }
  run(accessor) {
    const productService = accessor.get($Vu);
    const openerService = accessor.get($O4);
    if (productService.privacyStatementUrl) {
      openerService.open(URI.parse(productService.privacyStatementUrl));
    }
  }
};
var GetStartedWithAccessibilityFeatures = class _GetStartedWithAccessibilityFeatures extends $gJ {
  static {
    this.ID = "workbench.action.getStartedWithAccessibilityFeatures";
  }
  constructor() {
    super({
      id: _GetStartedWithAccessibilityFeatures.ID,
      title: localize2(2839, "Get Started with Accessibility Features"),
      category: $qn.Help,
      f1: true,
      menu: {
        id: $bJ.MenubarHelpMenu,
        group: "1_welcome",
        order: 6
      }
    });
  }
  run(accessor) {
    const commandService = accessor.get($sn);
    commandService.executeCommand("workbench.action.openWalkthrough", "SetupAccessibility");
  }
};
if (KeybindingsReferenceAction.AVAILABLE) {
  $hJ(KeybindingsReferenceAction);
}
if (OpenIntroductoryVideosUrlAction.AVAILABLE) {
  $hJ(OpenIntroductoryVideosUrlAction);
}
if (OpenTipsAndTricksUrlAction.AVAILABLE) {
  $hJ(OpenTipsAndTricksUrlAction);
}
if (OpenDocumentationUrlAction.AVAILABLE) {
  $hJ(OpenDocumentationUrlAction);
}
if (OpenNewsletterSignupUrlAction.AVAILABLE) {
  $hJ(OpenNewsletterSignupUrlAction);
}
if (OpenYouTubeUrlAction.AVAILABLE) {
  $hJ(OpenYouTubeUrlAction);
}
if (OpenRequestFeatureUrlAction.AVAILABLE) {
  $hJ(OpenRequestFeatureUrlAction);
}
if (OpenLicenseUrlAction.AVAILABLE) {
  $hJ(OpenLicenseUrlAction);
}
if (OpenPrivacyStatementUrlAction.AVAILABE) {
  $hJ(OpenPrivacyStatementUrlAction);
}
$hJ(GetStartedWithAccessibilityFeatures);

// out-build/vs/workbench/services/activity/common/activity.js
var $vqb = $Qk("activityService");
var BaseBadge = class {
  constructor(a, b) {
    this.a = a;
    this.b = b;
  }
  getDescription() {
    return this.a(null);
  }
  getColors(theme) {
    return this.b?.(theme);
  }
};
var $wqb = class extends BaseBadge {
  constructor(number, descriptorFn) {
    super(descriptorFn, void 0);
    this.number = number;
    this.number = number;
  }
  getDescription() {
    return this.a(this.number);
  }
};
var $xqb = class extends BaseBadge {
  constructor(icon2, descriptorFn, stylesFn) {
    super(descriptorFn, stylesFn);
    this.icon = icon2;
  }
};
var $yqb = class extends BaseBadge {
  constructor(descriptorFn) {
    super(descriptorFn, void 0);
  }
};
var $zqb = class extends $xqb {
  constructor(descriptorFn) {
    super($6l.warning, descriptorFn, (theme) => ({
      badgeBackground: theme.getColor($zo),
      badgeForeground: theme.getColor($yo),
      badgeBorder: void 0
    }));
  }
};

// out-build/vs/workbench/browser/parts/compositeBarActions.js
var $Fqb_1;
var $Bqb = class extends $Um {
  constructor(g) {
    super(g.id, g.name, g.classNames?.join(" "), true);
    this.g = g;
    this.a = this.B(new $ze());
    this.onDidChangeCompositeBarActionItem = this.a.event;
    this.b = this.B(new $ze());
    this.onDidChangeActivity = this.b.event;
  }
  get compositeBarActionItem() {
    return this.g;
  }
  set compositeBarActionItem(item) {
    this.n = item.name;
    this.g = item;
    this.a.fire(this);
  }
  get activity() {
    return this.f;
  }
  set activity(activity) {
    this.f = activity;
    this.b.fire(activity);
  }
  activate() {
    if (!this.checked) {
      this.J(true);
    }
  }
  deactivate() {
    if (this.checked) {
      this.J(false);
    }
  }
};
var $Cqb = class $Cqb2 extends $T1 {
  constructor(action, options3, L, M, N, O, P) {
    super(null, action, options3);
    this.L = L;
    this.M = M;
    this.N = N;
    this.O = O;
    this.P = P;
    this.n = this.B(new $4c());
    this.u = options3;
    this.B(this.M.onDidColorThemeChange(this.S, this));
    this.B(action.onDidChangeCompositeBarActionItem(() => this.U()));
    this.B(Event2.filter(P.onDidUpdateKeybindings, () => this.t !== this.bb())(() => this.Z()));
    this.B(action.onDidChangeActivity(() => this.X()));
  }
  get Q() {
    return this._action.compositeBarActionItem;
  }
  R() {
    const theme = this.M.getColorTheme();
    const colors = this.u.colors(theme);
    if (this.c) {
      if (this.u.icon) {
        const foreground = this._action.checked ? colors.activeForegroundColor : colors.inactiveForegroundColor;
        if (this.Q.iconUrl) {
          this.c.style.backgroundColor = foreground ? foreground.toString() : "";
          this.c.style.color = "";
        } else {
          this.c.style.color = foreground ? foreground.toString() : "";
          this.c.style.backgroundColor = "";
        }
      } else {
        const foreground = this._action.checked ? colors.activeForegroundColor : colors.inactiveForegroundColor;
        const borderBottomColor = this._action.checked ? colors.activeBorderBottomColor : null;
        this.c.style.color = foreground ? foreground.toString() : "";
        this.c.style.borderBottomColor = borderBottomColor ? borderBottomColor.toString() : "";
      }
      this.b.style.setProperty("--insert-border-color", colors.dragAndDropBorder ? colors.dragAndDropBorder.toString() : "");
    }
    if (this.m) {
      const badgeStyles = this.W()?.badge.getColors(theme);
      const badgeFg = badgeStyles?.badgeForeground ?? colors.badgeForeground ?? theme.getColor($xo);
      const badgeBg = badgeStyles?.badgeBackground ?? colors.badgeBackground ?? theme.getColor($wo);
      const contrastBorderColor = badgeStyles?.badgeBorder ?? theme.getColor($ko);
      this.m.style.color = badgeFg ? badgeFg.toString() : "";
      this.m.style.backgroundColor = badgeBg ? badgeBg.toString() : "";
      this.m.style.borderStyle = contrastBorderColor && !this.u.compact ? "solid" : "";
      this.m.style.borderWidth = contrastBorderColor ? "1px" : "";
      this.m.style.borderColor = contrastBorderColor ? contrastBorderColor.toString() : "";
    }
  }
  render(container2) {
    super.render(container2);
    this.b = container2;
    if (this.u.icon) {
      this.b.classList.add("icon");
    }
    if (this.u.hasPopup) {
      this.b.setAttribute("role", "button");
      this.b.setAttribute("aria-haspopup", "true");
    } else {
      this.b.setAttribute("role", "tab");
    }
    this.B($_i(this.b, $7j.MOUSE_DOWN, () => {
      this.b.classList.add("clicked");
    }));
    this.B($_i(this.b, $7j.MOUSE_UP, () => {
      if (this.r) {
        clearTimeout(this.r);
      }
      this.r = setTimeout(() => {
        this.b.classList.remove("clicked");
      }, 800);
    }));
    this.B(this.N.setupDelayedHover(this.b, () => ({
      content: this.ab(),
      position: {
        hoverPosition: this.u.hoverOptions.position()
      },
      persistence: {
        hideOnKeyDown: true
      },
      appearance: {
        showPointer: true,
        compact: true
      }
    }), { groupId: "composite-bar-actions" }));
    this.c = $bk(container2, $("a"));
    this.g = $bk(container2, $(".badge"));
    this.m = $bk(this.g, $(".badge-content"));
    $bk(container2, $(".active-item-indicator"));
    $ik(this.g);
    this.U();
    this.R();
    this.Z();
  }
  S(theme) {
    this.R();
  }
  U() {
    this.C();
    this.X();
    this.Z();
    this.R();
  }
  W() {
    if (this._action instanceof $Bqb) {
      return this._action.activity;
    }
    return void 0;
  }
  X() {
    if (!this.g || !this.m || !(this._action instanceof $Bqb)) {
      return;
    }
    const activity = this.W();
    this.n.value = new $2c();
    $$i(this.m);
    $ik(this.g);
    const shouldRenderBadges = this.L(this.Q.id);
    if (activity && shouldRenderBadges) {
      const { badge } = activity;
      const classes2 = [];
      if (this.u.compact) {
        classes2.push("compact");
      }
      if (badge instanceof $yqb) {
        $hk(this.g);
        classes2.push("progress-badge");
      } else if (badge instanceof $wqb) {
        if (badge.number) {
          let number = badge.number.toString();
          if (badge.number > 999) {
            const noOfThousands = badge.number / 1e3;
            const floor = Math.floor(noOfThousands);
            if (noOfThousands > floor) {
              number = `${floor}K+`;
            } else {
              number = `${noOfThousands}K`;
            }
          }
          if (this.u.compact && number.length >= 3) {
            classes2.push("compact-content");
          }
          this.m.textContent = number;
          $hk(this.g);
        }
      } else if (badge instanceof $xqb) {
        classes2.push("icon-badge");
        const badgeContentClassess = ["icon-overlay", ...ThemeIcon.asClassNameArray(badge.icon)];
        this.m.classList.add(...badgeContentClassess);
        this.n.value.add($1c(() => this.m?.classList.remove(...badgeContentClassess)));
        $hk(this.g);
      }
      if (classes2.length) {
        this.g.classList.add(...classes2);
        this.n.value.add($1c(() => this.g.classList.remove(...classes2)));
      }
    }
    this.Z();
    this.R();
  }
  C() {
    this.c.className = "action-label";
    if (this.Q.classNames) {
      this.c.classList.add(...this.Q.classNames);
    }
    if (!this.u.icon) {
      this.c.textContent = this.action.label;
    }
  }
  Z() {
    const title = this.ab();
    [this.c, this.g, this.b].forEach((element) => {
      if (element) {
        element.setAttribute("aria-label", title);
        element.setAttribute("title", "");
        element.removeAttribute("title");
      }
    });
  }
  ab() {
    this.t = this.bb();
    let title = this.t ? localize(3089, null, this.Q.name, this.t) : this.Q.name;
    const badge = this.action.activity?.badge;
    if (badge?.getDescription()) {
      title = localize(3090, null, title, badge.getDescription());
    }
    return title;
  }
  bb() {
    const keybinding = this.Q.keybindingId ? this.P.lookupKeybinding(this.Q.keybindingId) : null;
    return keybinding?.getLabel();
  }
  dispose() {
    super.dispose();
    if (this.r) {
      clearTimeout(this.r);
    }
    this.g.remove();
  }
};
$Cqb = __decorate([
  __param(3, $gs),
  __param(4, $5$),
  __param(5, $kl),
  __param(6, $Ty)
], $Cqb);
var $Dqb = class extends $Bqb {
  constructor(c) {
    super({
      id: "additionalComposites.action",
      name: localize(3091, null),
      classNames: ThemeIcon.asClassNameArray($6l.more)
    });
    this.c = c;
  }
  async run() {
    this.c();
  }
};
var $Eqb = class $Eqb2 extends $Cqb {
  constructor(action, a, s, cb, db, colors, hoverOptions, eb, themeService, hoverService, configurationService, keybindingService) {
    super(action, { icon: true, colors, hasPopup: true, hoverOptions }, () => true, themeService, hoverService, configurationService, keybindingService);
    this.a = a;
    this.s = s;
    this.cb = cb;
    this.db = db;
    this.eb = eb;
  }
  showMenu() {
    this.eb.showContextMenu({
      getAnchor: () => this.b,
      getActions: () => this.fb(),
      getCheckedActionsRepresentation: () => "radio"
    });
  }
  fb() {
    return this.a().map((composite) => {
      const action = this.db(composite.id);
      action.checked = this.s() === action.id;
      const badge = this.cb(composite.id);
      let suffix;
      if (badge instanceof $wqb) {
        suffix = badge.number;
      }
      if (suffix) {
        action.label = localize(3092, null, composite.name, suffix);
      } else {
        action.label = composite.name || "";
      }
      return action;
    });
  }
};
$Eqb = __decorate([
  __param(7, $50),
  __param(8, $gs),
  __param(9, $5$),
  __param(10, $kl),
  __param(11, $Ty)
], $Eqb);
var ManageExtensionAction2 = class ManageExtensionAction3 extends $Um {
  constructor(a) {
    super("activitybar.manage.extension", localize(3093, null));
    this.a = a;
  }
  run(id2) {
    return this.a.executeCommand("_extensions.manage", id2);
  }
};
ManageExtensionAction2 = __decorate([
  __param(0, $sn)
], ManageExtensionAction2);
var $Fqb = class $Fqb2 extends $Cqb {
  static {
    $Fqb_1 = this;
  }
  constructor(options3, s, cb, db, eb, fb, gb, hb, ib, keybindingService, instantiationService, themeService, hoverService, configurationService, jb) {
    super(s, options3, hb.areBadgesEnabled.bind(hb), themeService, hoverService, configurationService, keybindingService);
    this.s = s;
    this.cb = cb;
    this.db = db;
    this.eb = eb;
    this.fb = fb;
    this.gb = gb;
    this.hb = hb;
    this.ib = ib;
    this.jb = jb;
    if (!$Fqb_1.a) {
      $Fqb_1.a = instantiationService.createInstance(ManageExtensionAction2);
    }
  }
  render(container2) {
    super.render(container2);
    this.J();
    this.z();
    this.B($_i(this.b, $7j.CONTEXT_MENU, (e) => {
      $9j.stop(e, true);
      this.lb(container2);
    }));
    let insertDropBefore = void 0;
    this.B($Iob.INSTANCE.registerDraggable(this.b, () => {
      return { type: "composite", id: this.Q.id };
    }, {
      onDragOver: (e) => {
        const isValidMove = e.dragAndDropData.getData().id !== this.Q.id && this.gb.onDragOver(e.dragAndDropData, this.Q.id, e.eventData);
        $Job(e.eventData.dataTransfer, "move", isValidMove);
        insertDropBefore = this.kb(container2, isValidMove, e.eventData);
      },
      onDragLeave: (e) => {
        insertDropBefore = this.kb(container2, false, e.eventData);
      },
      onDragEnd: (e) => {
        insertDropBefore = this.kb(container2, false, e.eventData);
      },
      onDrop: (e) => {
        $9j.stop(e.eventData, true);
        this.gb.drop(e.dragAndDropData, this.Q.id, e.eventData, insertDropBefore);
        insertDropBefore = this.kb(container2, false, e.eventData);
      },
      onDragStart: (e) => {
        if (e.dragAndDropData.getData().id !== this.Q.id) {
          return;
        }
        if (e.eventData.dataTransfer) {
          e.eventData.dataTransfer.effectAllowed = "move";
        }
        this.blur();
      }
    }));
    [this.g, this.c].forEach((element) => this.B(new $jZ(element, () => {
      if (!this.action.checked) {
        this.action.run();
      }
    })));
    this.R();
  }
  kb(element, showFeedback, event) {
    const rect = element.getBoundingClientRect();
    const posX = event.clientX;
    const posY = event.clientY;
    const height = rect.bottom - rect.top;
    const width2 = rect.right - rect.left;
    const forceTop = posY <= rect.top + height * 0.4;
    const forceBottom = posY > rect.bottom - height * 0.4;
    const preferTop = posY <= rect.top + height * 0.5;
    const forceLeft = posX <= rect.left + width2 * 0.4;
    const forceRight = posX > rect.right - width2 * 0.4;
    const preferLeft = posX <= rect.left + width2 * 0.5;
    const classes2 = element.classList;
    const lastClasses = {
      vertical: classes2.contains("top") ? "top" : classes2.contains("bottom") ? "bottom" : void 0,
      horizontal: classes2.contains("left") ? "left" : classes2.contains("right") ? "right" : void 0
    };
    const top2 = forceTop || preferTop && !lastClasses.vertical || !forceBottom && lastClasses.vertical === "top";
    const bottom = forceBottom || !preferTop && !lastClasses.vertical || !forceTop && lastClasses.vertical === "bottom";
    const left = forceLeft || preferLeft && !lastClasses.horizontal || !forceRight && lastClasses.horizontal === "left";
    const right = forceRight || !preferLeft && !lastClasses.horizontal || !forceLeft && lastClasses.horizontal === "right";
    element.classList.toggle("top", showFeedback && top2);
    element.classList.toggle("bottom", showFeedback && bottom);
    element.classList.toggle("left", showFeedback && left);
    element.classList.toggle("right", showFeedback && right);
    if (!showFeedback) {
      return void 0;
    }
    return { verticallyBefore: top2, horizontallyBefore: left };
  }
  lb(container2) {
    const actions = [];
    if (this.Q.keybindingId) {
      actions.push($Z$(this.jb, this.P, this.Q.keybindingId));
    }
    actions.push(this.cb, this.db);
    const compositeContextMenuActions = this.eb(this.Q.id);
    if (compositeContextMenuActions.length) {
      actions.push(...compositeContextMenuActions);
    }
    if (this.s.compositeBarActionItem.extensionId) {
      actions.push(new $Wm());
      actions.push($Fqb_1.a);
    }
    const isPinned = this.hb.isPinned(this.Q.id);
    if (isPinned) {
      this.cb.label = localize(3094, null, this.Q.name);
      this.cb.checked = false;
      this.cb.enabled = this.hb.getPinnedCompositeIds().length > 1;
    } else {
      this.cb.label = localize(3095, null, this.Q.name);
      this.cb.enabled = true;
    }
    const isBadgeEnabled = this.hb.areBadgesEnabled(this.Q.id);
    if (isBadgeEnabled) {
      this.db.label = localize(3096, null);
    } else {
      this.db.label = localize(3097, null);
    }
    const otherActions = this.fb();
    if (otherActions.length) {
      actions.push(new $Wm());
      actions.push(...otherActions);
    }
    const elementPosition = $vj(container2);
    const anchor = {
      x: Math.floor(elementPosition.left + elementPosition.width / 2),
      y: elementPosition.top + elementPosition.height
    };
    this.ib.showContextMenu({
      getAnchor: () => anchor,
      getActions: () => actions,
      getActionsContext: () => this.Q.id
    });
  }
  J() {
    if (this.action.checked) {
      this.b.classList.add("checked");
      this.b.setAttribute("aria-label", this.F() ?? this.b.title);
      this.b.setAttribute("aria-expanded", "true");
      this.b.setAttribute("aria-selected", "true");
    } else {
      this.b.classList.remove("checked");
      this.b.setAttribute("aria-label", this.F() ?? this.b.title);
      this.b.setAttribute("aria-expanded", "false");
      this.b.setAttribute("aria-selected", "false");
    }
    this.R();
  }
  z() {
    if (!this.element) {
      return;
    }
    if (this.action.enabled) {
      this.element.classList.remove("disabled");
    } else {
      this.element.classList.add("disabled");
    }
  }
  dispose() {
    super.dispose();
    this.c.remove();
  }
};
$Fqb = $Fqb_1 = __decorate([
  __param(8, $50),
  __param(9, $Ty),
  __param(10, $Pk),
  __param(11, $gs),
  __param(12, $5$),
  __param(13, $kl),
  __param(14, $sn)
], $Fqb);
var $Gqb = class extends $Um {
  constructor(a, b) {
    super("show.toggleCompositePinned", a ? a.name : localize(3098, null));
    this.a = a;
    this.b = b;
    this.checked = !!this.a && this.b.isPinned(this.a.id);
  }
  async run(context) {
    const id2 = this.a ? this.a.id : context;
    if (this.b.isPinned(id2)) {
      this.b.unpin(id2);
    } else {
      this.b.pin(id2);
    }
  }
};
var $Hqb = class extends $Um {
  constructor(a, b) {
    super("show.toggleCompositeBadge", a ? a.name : localize(3099, null));
    this.a = a;
    this.b = b;
    this.checked = false;
  }
  async run(context) {
    const id2 = this.a ? this.a.id : context;
    this.b.toggleBadgeEnablement(id2);
  }
};
var $Iqb = class extends $gJ {
  constructor(desc, a, b) {
    super(desc);
    this.a = a;
    this.b = b;
  }
  async run(accessor) {
    const paneCompositeService = accessor.get($uqb);
    const activeComposite = paneCompositeService.getActivePaneComposite(this.a);
    if (!activeComposite) {
      return;
    }
    let targetCompositeId;
    const visibleCompositeIds = paneCompositeService.getVisiblePaneCompositeIds(this.a);
    for (let i2 = 0; i2 < visibleCompositeIds.length; i2++) {
      if (visibleCompositeIds[i2] === activeComposite.getId()) {
        targetCompositeId = visibleCompositeIds[(i2 + visibleCompositeIds.length + this.b) % visibleCompositeIds.length];
        break;
      }
    }
    if (typeof targetCompositeId !== "undefined") {
      await paneCompositeService.openPaneComposite(targetCompositeId, this.a, true);
    }
  }
};

// out-build/vs/workbench/browser/parts/auxiliarybar/auxiliaryBarActions.js
var auxiliaryBarRightIcon = $9r("auxiliarybar-right-layout-icon", $6l.layoutSidebarRight, localize(3070, null));
var auxiliaryBarRightOffIcon = $9r("auxiliarybar-right-off-layout-icon", $6l.layoutSidebarRightOff, localize(3071, null));
var auxiliaryBarLeftIcon = $9r("auxiliarybar-left-layout-icon", $6l.layoutSidebarLeft, localize(3072, null));
var auxiliaryBarLeftOffIcon = $9r("auxiliarybar-left-off-layout-icon", $6l.layoutSidebarLeftOff, localize(3073, null));
var $Jqb = class _$Jqb extends $gJ {
  static {
    this.ID = "workbench.action.toggleAuxiliaryBar";
  }
  static {
    this.LABEL = localize2(3078, "Toggle Secondary Side Bar Visibility");
  }
  constructor() {
    super({
      id: _$Jqb.ID,
      title: _$Jqb.LABEL,
      toggled: {
        condition: $cqb,
        title: localize(3074, null),
        mnemonicTitle: localize(3075, null)
      },
      category: $qn.View,
      f1: true,
      keybinding: {
        weight: 200,
        primary: 2048 | 512 | 32
        /* KeyCode.KeyB */
      },
      menu: [
        {
          id: $bJ.LayoutControlMenuSubmenu,
          group: "0_workbench_layout",
          order: 1
        },
        {
          id: $bJ.MenubarAppearanceMenu,
          group: "2_workbench_layout",
          order: 2
        }
      ]
    });
  }
  async run(accessor) {
    const layoutService = accessor.get($Vlb);
    layoutService.setPartHidden(
      layoutService.isVisible(
        "workbench.parts.auxiliarybar"
        /* Parts.AUXILIARYBAR_PART */
      ),
      "workbench.parts.auxiliarybar"
      /* Parts.AUXILIARYBAR_PART */
    );
  }
};
$hJ($Jqb);
$hJ(class FocusAuxiliaryBarAction extends $gJ {
  static {
    this.ID = "workbench.action.focusAuxiliaryBar";
  }
  static {
    this.LABEL = localize2(3079, "Focus into Secondary Side Bar");
  }
  constructor() {
    super({
      id: FocusAuxiliaryBarAction.ID,
      title: FocusAuxiliaryBarAction.LABEL,
      category: $qn.View,
      f1: true
    });
  }
  async run(accessor) {
    const paneCompositeService = accessor.get($uqb);
    const layoutService = accessor.get($Vlb);
    if (!layoutService.isVisible(
      "workbench.parts.auxiliarybar"
      /* Parts.AUXILIARYBAR_PART */
    )) {
      layoutService.setPartHidden(
        false,
        "workbench.parts.auxiliarybar"
        /* Parts.AUXILIARYBAR_PART */
      );
    }
    const composite = paneCompositeService.getActivePaneComposite(
      2
      /* ViewContainerLocation.AuxiliaryBar */
    );
    composite?.focus();
  }
});
$dJ.appendMenuItems([
  {
    id: $bJ.LayoutControlMenu,
    item: {
      group: "2_pane_toggles",
      command: {
        id: $Jqb.ID,
        title: localize(3076, null),
        toggled: { condition: $cqb, icon: auxiliaryBarLeftIcon },
        icon: auxiliaryBarLeftOffIcon
      },
      when: $7m.and($7m.or($7m.equals("config.workbench.layoutControl.type", "toggles"), $7m.equals("config.workbench.layoutControl.type", "both")), $7m.equals("config.workbench.sideBar.location", "right")),
      order: 0
    }
  },
  {
    id: $bJ.LayoutControlMenu,
    item: {
      group: "2_pane_toggles",
      command: {
        id: $Jqb.ID,
        title: localize(3077, null),
        toggled: { condition: $cqb, icon: auxiliaryBarRightIcon },
        icon: auxiliaryBarRightOffIcon
      },
      when: $7m.and($7m.or($7m.equals("config.workbench.layoutControl.type", "toggles"), $7m.equals("config.workbench.layoutControl.type", "both")), $7m.equals("config.workbench.sideBar.location", "left")),
      order: 2
    }
  },
  {
    id: $bJ.ViewTitleContext,
    item: {
      group: "3_workbench_layout_move",
      command: {
        id: $Jqb.ID,
        title: localize2(3080, "Hide Secondary Side Bar")
      },
      when: $7m.and($cqb, $7m.equals("viewLocation", $0M(
        2
        /* ViewContainerLocation.AuxiliaryBar */
      ))),
      order: 2
    }
  }
]);
$hJ(class extends $Iqb {
  constructor() {
    super({
      id: "workbench.action.previousAuxiliaryBarView",
      title: localize2(3081, "Previous Secondary Side Bar View"),
      category: $qn.View,
      f1: true
    }, 2, -1);
  }
});
$hJ(class extends $Iqb {
  constructor() {
    super({
      id: "workbench.action.nextAuxiliaryBarView",
      title: localize2(3082, "Next Secondary Side Bar View"),
      category: $qn.View,
      f1: true
    }, 2, 1);
  }
});

// out-build/vs/workbench/browser/parts/panel/panelActions.js
var maximizeIcon = $9r("panel-maximize", $6l.chevronUp, localize(3691, null));
var restoreIcon = $9r("panel-restore", $6l.chevronDown, localize(3692, null));
var closeIcon = $9r("panel-close", $6l.close, localize(3693, null));
var panelIcon = $9r("panel-layout-icon", $6l.layoutPanel, localize(3694, null));
var panelOffIcon = $9r("panel-layout-icon-off", $6l.layoutPanelOff, localize(3695, null));
var $Kqb = class _$Kqb extends $gJ {
  static {
    this.ID = "workbench.action.togglePanel";
  }
  static {
    this.LABEL = localize2(3713, "Toggle Panel Visibility");
  }
  constructor() {
    super({
      id: _$Kqb.ID,
      title: _$Kqb.LABEL,
      toggled: {
        condition: $hqb,
        title: localize(3696, null),
        mnemonicTitle: localize(3697, null)
      },
      f1: true,
      category: $qn.View,
      keybinding: {
        primary: 2048 | 40,
        weight: 200
        /* KeybindingWeight.WorkbenchContrib */
      },
      menu: [
        {
          id: $bJ.MenubarAppearanceMenu,
          group: "2_workbench_layout",
          order: 5
        },
        {
          id: $bJ.LayoutControlMenuSubmenu,
          group: "0_workbench_layout",
          order: 4
        }
      ]
    });
  }
  async run(accessor) {
    const layoutService = accessor.get($Vlb);
    layoutService.setPartHidden(
      layoutService.isVisible(
        "workbench.parts.panel"
        /* Parts.PANEL_PART */
      ),
      "workbench.parts.panel"
      /* Parts.PANEL_PART */
    );
  }
};
$hJ($Kqb);
$hJ(class extends $gJ {
  static {
    this.ID = "workbench.action.focusPanel";
  }
  static {
    this.LABEL = localize(3698, null);
  }
  constructor() {
    super({
      id: "workbench.action.focusPanel",
      title: localize2(3714, "Focus into Panel"),
      category: $qn.View,
      f1: true
    });
  }
  async run(accessor) {
    const layoutService = accessor.get($Vlb);
    const paneCompositeService = accessor.get($uqb);
    if (!layoutService.isVisible(
      "workbench.parts.panel"
      /* Parts.PANEL_PART */
    )) {
      layoutService.setPartHidden(
        false,
        "workbench.parts.panel"
        /* Parts.PANEL_PART */
      );
    }
    const panel = paneCompositeService.getActivePaneComposite(
      1
      /* ViewContainerLocation.Panel */
    );
    panel?.focus();
  }
});
var PositionPanelActionId = {
  LEFT: "workbench.action.positionPanelLeft",
  RIGHT: "workbench.action.positionPanelRight",
  BOTTOM: "workbench.action.positionPanelBottom",
  TOP: "workbench.action.positionPanelTop"
};
var AlignPanelActionId = {
  LEFT: "workbench.action.alignPanelLeft",
  RIGHT: "workbench.action.alignPanelRight",
  CENTER: "workbench.action.alignPanelCenter",
  JUSTIFY: "workbench.action.alignPanelJustify"
};
function createPanelActionConfig(id2, title, shortLabel, value, when) {
  return {
    id: id2,
    title,
    shortLabel,
    value,
    when
  };
}
function createPositionPanelActionConfig(id2, title, shortLabel, position) {
  return createPanelActionConfig(id2, title, shortLabel, position, $fqb.notEqualsTo($Xlb(position)));
}
function createAlignmentPanelActionConfig(id2, title, shortLabel, alignment) {
  return createPanelActionConfig(id2, title, shortLabel, alignment, $gqb.notEqualsTo(alignment));
}
var PositionPanelActionConfigs = [
  createPositionPanelActionConfig(
    PositionPanelActionId.TOP,
    localize2(3715, "Move Panel To Top"),
    localize(3699, null),
    3
    /* Position.TOP */
  ),
  createPositionPanelActionConfig(
    PositionPanelActionId.LEFT,
    localize2(3716, "Move Panel Left"),
    localize(3700, null),
    0
    /* Position.LEFT */
  ),
  createPositionPanelActionConfig(
    PositionPanelActionId.RIGHT,
    localize2(3717, "Move Panel Right"),
    localize(3701, null),
    1
    /* Position.RIGHT */
  ),
  createPositionPanelActionConfig(
    PositionPanelActionId.BOTTOM,
    localize2(3718, "Move Panel To Bottom"),
    localize(3702, null),
    2
    /* Position.BOTTOM */
  )
];
var AlignPanelActionConfigs = [
  createAlignmentPanelActionConfig(AlignPanelActionId.LEFT, localize2(3719, "Set Panel Alignment to Left"), localize(3703, null), "left"),
  createAlignmentPanelActionConfig(AlignPanelActionId.RIGHT, localize2(3720, "Set Panel Alignment to Right"), localize(3704, null), "right"),
  createAlignmentPanelActionConfig(AlignPanelActionId.CENTER, localize2(3721, "Set Panel Alignment to Center"), localize(3705, null), "center"),
  createAlignmentPanelActionConfig(AlignPanelActionId.JUSTIFY, localize2(3722, "Set Panel Alignment to Justify"), localize(3706, null), "justify")
];
$dJ.appendMenuItem($bJ.MenubarAppearanceMenu, {
  submenu: $bJ.PanelPositionMenu,
  title: localize(3707, null),
  group: "3_workbench_layout_move",
  order: 4
});
PositionPanelActionConfigs.forEach((positionPanelAction, index) => {
  const { id: id2, title, shortLabel, value, when } = positionPanelAction;
  $hJ(class extends $gJ {
    constructor() {
      super({
        id: id2,
        title,
        category: $qn.View,
        f1: true
      });
    }
    run(accessor) {
      const layoutService = accessor.get($Vlb);
      layoutService.setPanelPosition(value === void 0 ? 2 : value);
    }
  });
  $dJ.appendMenuItem($bJ.PanelPositionMenu, {
    command: {
      id: id2,
      title: shortLabel,
      toggled: when.negate()
    },
    order: 5 + index
  });
});
$dJ.appendMenuItem($bJ.MenubarAppearanceMenu, {
  submenu: $bJ.PanelAlignmentMenu,
  title: localize(3708, null),
  group: "3_workbench_layout_move",
  order: 5
});
AlignPanelActionConfigs.forEach((alignPanelAction) => {
  const { id: id2, title, shortLabel, value, when } = alignPanelAction;
  $hJ(class extends $gJ {
    constructor() {
      super({
        id: id2,
        title,
        category: $qn.View,
        toggled: when.negate(),
        f1: true
      });
    }
    run(accessor) {
      const layoutService = accessor.get($Vlb);
      layoutService.setPanelAlignment(value === void 0 ? "center" : value);
    }
  });
  $dJ.appendMenuItem($bJ.PanelAlignmentMenu, {
    command: {
      id: id2,
      title: shortLabel,
      toggled: when.negate()
    },
    order: 5
  });
});
$hJ(class extends $Iqb {
  constructor() {
    super({
      id: "workbench.action.previousPanelView",
      title: localize2(3723, "Previous Panel View"),
      category: $qn.View,
      f1: true
    }, 1, -1);
  }
});
$hJ(class extends $Iqb {
  constructor() {
    super({
      id: "workbench.action.nextPanelView",
      title: localize2(3724, "Next Panel View"),
      category: $qn.View,
      f1: true
    }, 1, 1);
  }
});
$hJ(class extends $gJ {
  constructor() {
    super({
      id: "workbench.action.toggleMaximizedPanel",
      title: localize2(3725, "Toggle Maximized Panel"),
      tooltip: localize(3709, null),
      category: $qn.View,
      f1: true,
      icon: maximizeIcon,
      // This is being rotated in CSS depending on the panel position
      // the workbench grid currently prevents us from supporting panel maximization with non-center panel alignment
      precondition: $7m.or($gqb.isEqualTo("center"), $7m.and($fqb.notEqualsTo("bottom"), $fqb.notEqualsTo("top"))),
      toggled: { condition: $iqb, icon: restoreIcon, tooltip: localize(3710, null) },
      menu: [{
        id: $bJ.PanelTitle,
        group: "navigation",
        order: 1,
        // the workbench grid currently prevents us from supporting panel maximization with non-center panel alignment
        when: $7m.or($gqb.isEqualTo("center"), $7m.and($fqb.notEqualsTo("bottom"), $fqb.notEqualsTo("top")))
      }]
    });
  }
  run(accessor) {
    const layoutService = accessor.get($Vlb);
    const notificationService = accessor.get($PJ);
    if (layoutService.getPanelAlignment() !== "center" && $Wlb(layoutService.getPanelPosition())) {
      notificationService.warn(localize(3711, null));
      return;
    }
    if (!layoutService.isVisible(
      "workbench.parts.panel"
      /* Parts.PANEL_PART */
    )) {
      layoutService.setPartHidden(
        false,
        "workbench.parts.panel"
        /* Parts.PANEL_PART */
      );
      if (!layoutService.isPanelMaximized()) {
        layoutService.toggleMaximizedPanel();
      }
    } else {
      layoutService.toggleMaximizedPanel();
    }
  }
});
$hJ(class extends $gJ {
  constructor() {
    super({
      id: "workbench.action.closePanel",
      title: localize2(3726, "Hide Panel"),
      category: $qn.View,
      icon: closeIcon,
      menu: [{
        id: $bJ.CommandPalette,
        when: $hqb
      }, {
        id: $bJ.PanelTitle,
        group: "navigation",
        order: 2
      }]
    });
  }
  run(accessor) {
    accessor.get($Vlb).setPartHidden(
      true,
      "workbench.parts.panel"
      /* Parts.PANEL_PART */
    );
  }
});
$hJ(class extends $gJ {
  constructor() {
    super({
      id: "workbench.action.closeAuxiliaryBar",
      title: localize2(3727, "Hide Secondary Side Bar"),
      category: $qn.View,
      icon: closeIcon,
      menu: [{
        id: $bJ.CommandPalette,
        when: $cqb
      }, {
        id: $bJ.AuxiliaryBarTitle,
        group: "navigation",
        order: 2,
        when: $7m.equals(
          `config.${"workbench.activityBar.location"}`,
          "default"
          /* ActivityBarPosition.DEFAULT */
        )
      }]
    });
  }
  run(accessor) {
    accessor.get($Vlb).setPartHidden(
      true,
      "workbench.parts.auxiliarybar"
      /* Parts.AUXILIARYBAR_PART */
    );
  }
});
$dJ.appendMenuItems([
  {
    id: $bJ.LayoutControlMenu,
    item: {
      group: "2_pane_toggles",
      command: {
        id: $Kqb.ID,
        title: localize(3712, null),
        icon: panelOffIcon,
        toggled: { condition: $hqb, icon: panelIcon }
      },
      when: $7m.or($7m.equals("config.workbench.layoutControl.type", "toggles"), $7m.equals("config.workbench.layoutControl.type", "both")),
      order: 1
    }
  },
  {
    id: $bJ.ViewTitleContext,
    item: {
      group: "3_workbench_layout_move",
      command: {
        id: $Kqb.ID,
        title: localize2(3728, "Hide Panel")
      },
      when: $7m.and($hqb, $7m.equals("viewLocation", $0M(
        1
        /* ViewContainerLocation.Panel */
      ))),
      order: 2
    }
  }
]);
var MoveViewsBetweenPanelsAction = class extends $gJ {
  constructor(a, b, desc) {
    super(desc);
    this.a = a;
    this.b = b;
  }
  run(accessor, ...args2) {
    const viewDescriptorService = accessor.get($$M);
    const layoutService = accessor.get($Vlb);
    const viewsService = accessor.get($uob);
    const srcContainers = viewDescriptorService.getViewContainersByLocation(this.a);
    const destContainers = viewDescriptorService.getViewContainersByLocation(this.b);
    if (srcContainers.length) {
      const activeViewContainer = viewsService.getVisibleViewContainer(this.a);
      srcContainers.forEach((viewContainer5) => viewDescriptorService.moveViewContainerToLocation(viewContainer5, this.b, void 0, this.desc.id));
      layoutService.setPartHidden(
        false,
        this.b === 1 ? "workbench.parts.panel" : "workbench.parts.auxiliarybar"
        /* Parts.AUXILIARYBAR_PART */
      );
      if (activeViewContainer && destContainers.length === 0) {
        viewsService.openViewContainer(activeViewContainer.id, true);
      }
    }
  }
};
var MovePanelToSidePanelAction = class _MovePanelToSidePanelAction extends MoveViewsBetweenPanelsAction {
  static {
    this.ID = "workbench.action.movePanelToSidePanel";
  }
  constructor() {
    super(1, 2, {
      id: _MovePanelToSidePanelAction.ID,
      title: localize2(3729, "Move Panel Views To Secondary Side Bar"),
      category: $qn.View,
      f1: false
    });
  }
};
var $Lqb = class _$Lqb extends MoveViewsBetweenPanelsAction {
  static {
    this.ID = "workbench.action.movePanelToSecondarySideBar";
  }
  constructor() {
    super(1, 2, {
      id: _$Lqb.ID,
      title: localize2(3730, "Move Panel Views To Secondary Side Bar"),
      category: $qn.View,
      f1: true
    });
  }
};
$hJ(MovePanelToSidePanelAction);
$hJ($Lqb);
var MoveSidePanelToPanelAction = class _MoveSidePanelToPanelAction extends MoveViewsBetweenPanelsAction {
  static {
    this.ID = "workbench.action.moveSidePanelToPanel";
  }
  constructor() {
    super(2, 1, {
      id: _MoveSidePanelToPanelAction.ID,
      title: localize2(3731, "Move Secondary Side Bar Views To Panel"),
      category: $qn.View,
      f1: false
    });
  }
};
var $Mqb = class _$Mqb extends MoveViewsBetweenPanelsAction {
  static {
    this.ID = "workbench.action.moveSecondarySideBarToPanel";
  }
  constructor() {
    super(2, 1, {
      id: _$Mqb.ID,
      title: localize2(3732, "Move Secondary Side Bar Views To Panel"),
      category: $qn.View,
      f1: true
    });
  }
};
$hJ(MoveSidePanelToPanelAction);
$hJ($Mqb);

// out-build/vs/workbench/browser/actions/layoutActions.js
var menubarIcon = $9r("menuBar", $6l.layoutMenubar, localize(2840, null));
var activityBarLeftIcon = $9r("activity-bar-left", $6l.layoutActivitybarLeft, localize(2841, null));
var activityBarRightIcon = $9r("activity-bar-right", $6l.layoutActivitybarRight, localize(2842, null));
var panelLeftIcon = $9r("panel-left", $6l.layoutSidebarLeft, localize(2843, null));
var panelLeftOffIcon = $9r("panel-left-off", $6l.layoutSidebarLeftOff, localize(2844, null));
var panelRightIcon = $9r("panel-right", $6l.layoutSidebarRight, localize(2845, null));
var panelRightOffIcon = $9r("panel-right-off", $6l.layoutSidebarRightOff, localize(2846, null));
var panelIcon2 = $9r("panel-bottom", $6l.layoutPanel, localize(2847, null));
var statusBarIcon = $9r("statusBar", $6l.layoutStatusbar, localize(2848, null));
var panelAlignmentLeftIcon = $9r("panel-align-left", $6l.layoutPanelLeft, localize(2849, null));
var panelAlignmentRightIcon = $9r("panel-align-right", $6l.layoutPanelRight, localize(2850, null));
var panelAlignmentCenterIcon = $9r("panel-align-center", $6l.layoutPanelCenter, localize(2851, null));
var panelAlignmentJustifyIcon = $9r("panel-align-justify", $6l.layoutPanelJustify, localize(2852, null));
var fullscreenIcon = $9r("fullscreen", $6l.screenFull, localize(2853, null));
var centerLayoutIcon = $9r("centerLayoutIcon", $6l.layoutCentered, localize(2854, null));
var zenModeIcon = $9r("zenMode", $6l.target, localize(2855, null));
$hJ(class extends $gJ {
  constructor() {
    super({
      id: "workbench.action.closeSidebar",
      title: localize2(2925, "Close Primary Side Bar"),
      category: $qn.View,
      f1: true
    });
  }
  run(accessor) {
    accessor.get($Vlb).setPartHidden(
      true,
      "workbench.parts.sidebar"
      /* Parts.SIDEBAR_PART */
    );
  }
});
var $Nqb = "workbench.action.toggleActivityBarVisibility";
$hJ(class extends $gJ {
  constructor() {
    super({
      id: "workbench.action.toggleCenteredLayout",
      title: {
        ...localize2(2926, "Toggle Centered Layout"),
        mnemonicTitle: localize(2856, null)
      },
      precondition: $opb.toNegated(),
      category: $qn.View,
      f1: true,
      toggled: $Ypb,
      menu: [{
        id: $bJ.MenubarAppearanceMenu,
        group: "1_toggle_view",
        order: 3
      }]
    });
  }
  run(accessor) {
    const layoutService = accessor.get($Vlb);
    layoutService.centerMainEditorLayout(!layoutService.isMainEditorLayoutCentered());
  }
});
var sidebarPositionConfigurationKey = "workbench.sideBar.location";
var MoveSidebarPositionAction = class extends $gJ {
  constructor(id2, title, a) {
    super({
      id: id2,
      title,
      f1: false
    });
    this.a = a;
  }
  async run(accessor) {
    const layoutService = accessor.get($Vlb);
    const configurationService = accessor.get($kl);
    const position = layoutService.getSideBarPosition();
    if (position !== this.a) {
      return configurationService.updateValue(sidebarPositionConfigurationKey, $Xlb(this.a));
    }
  }
};
var MoveSidebarRightAction = class _MoveSidebarRightAction extends MoveSidebarPositionAction {
  static {
    this.ID = "workbench.action.moveSideBarRight";
  }
  constructor() {
    super(
      _MoveSidebarRightAction.ID,
      localize2(2927, "Move Primary Side Bar Right"),
      1
      /* Position.RIGHT */
    );
  }
};
var MoveSidebarLeftAction = class _MoveSidebarLeftAction extends MoveSidebarPositionAction {
  static {
    this.ID = "workbench.action.moveSideBarLeft";
  }
  constructor() {
    super(
      _MoveSidebarLeftAction.ID,
      localize2(2928, "Move Primary Side Bar Left"),
      0
      /* Position.LEFT */
    );
  }
};
$hJ(MoveSidebarRightAction);
$hJ(MoveSidebarLeftAction);
var $Oqb = class _$Oqb extends $gJ {
  static {
    this.ID = "workbench.action.toggleSidebarPosition";
  }
  static {
    this.LABEL = localize(2857, null);
  }
  static getLabel(layoutService) {
    return layoutService.getSideBarPosition() === 0 ? localize(2858, null) : localize(2859, null);
  }
  constructor() {
    super({
      id: _$Oqb.ID,
      title: localize2(2929, "Toggle Primary Side Bar Position"),
      category: $qn.View,
      f1: true
    });
  }
  run(accessor) {
    const layoutService = accessor.get($Vlb);
    const configurationService = accessor.get($kl);
    const position = layoutService.getSideBarPosition();
    const newPositionValue = position === 0 ? "right" : "left";
    return configurationService.updateValue(sidebarPositionConfigurationKey, newPositionValue);
  }
};
$hJ($Oqb);
var configureLayoutIcon = $9r("configure-layout-icon", $6l.layout, localize(2860, null));
$dJ.appendMenuItem($bJ.LayoutControlMenu, {
  submenu: $bJ.LayoutControlMenuSubmenu,
  title: localize(2861, null),
  icon: configureLayoutIcon,
  group: "1_workbench_layout",
  when: $7m.equals("config.workbench.layoutControl.type", "menu")
});
$dJ.appendMenuItems([{
  id: $bJ.ViewContainerTitleContext,
  item: {
    group: "3_workbench_layout_move",
    command: {
      id: $Oqb.ID,
      title: localize(2862, null)
    },
    when: $7m.and($7m.notEquals("config.workbench.sideBar.location", "right"), $7m.equals("viewContainerLocation", $0M(
      0
      /* ViewContainerLocation.Sidebar */
    ))),
    order: 1
  }
}, {
  id: $bJ.ViewTitleContext,
  item: {
    group: "3_workbench_layout_move",
    command: {
      id: $Oqb.ID,
      title: localize(2863, null)
    },
    when: $7m.and($7m.notEquals("config.workbench.sideBar.location", "right"), $7m.equals("viewLocation", $0M(
      0
      /* ViewContainerLocation.Sidebar */
    ))),
    order: 1
  }
}, {
  id: $bJ.ViewContainerTitleContext,
  item: {
    group: "3_workbench_layout_move",
    command: {
      id: $Oqb.ID,
      title: localize(2864, null)
    },
    when: $7m.and($7m.equals("config.workbench.sideBar.location", "right"), $7m.equals("viewContainerLocation", $0M(
      0
      /* ViewContainerLocation.Sidebar */
    ))),
    order: 1
  }
}, {
  id: $bJ.ViewTitleContext,
  item: {
    group: "3_workbench_layout_move",
    command: {
      id: $Oqb.ID,
      title: localize(2865, null)
    },
    when: $7m.and($7m.equals("config.workbench.sideBar.location", "right"), $7m.equals("viewLocation", $0M(
      0
      /* ViewContainerLocation.Sidebar */
    ))),
    order: 1
  }
}, {
  id: $bJ.ViewTitleContext,
  item: {
    group: "3_workbench_layout_move",
    command: {
      id: $Oqb.ID,
      title: localize(2866, null)
    },
    when: $7m.and($7m.notEquals("config.workbench.sideBar.location", "right"), $7m.equals("viewLocation", $0M(
      2
      /* ViewContainerLocation.AuxiliaryBar */
    ))),
    order: 1
  }
}, {
  id: $bJ.ViewTitleContext,
  item: {
    group: "3_workbench_layout_move",
    command: {
      id: $Oqb.ID,
      title: localize(2867, null)
    },
    when: $7m.and($7m.equals("config.workbench.sideBar.location", "right"), $7m.equals("viewLocation", $0M(
      2
      /* ViewContainerLocation.AuxiliaryBar */
    ))),
    order: 1
  }
}]);
$dJ.appendMenuItem($bJ.MenubarAppearanceMenu, {
  group: "3_workbench_layout_move",
  command: {
    id: $Oqb.ID,
    title: localize(2868, null)
  },
  when: $7m.notEquals("config.workbench.sideBar.location", "right"),
  order: 2
});
$dJ.appendMenuItem($bJ.MenubarAppearanceMenu, {
  group: "3_workbench_layout_move",
  command: {
    id: $Oqb.ID,
    title: localize(2869, null)
  },
  when: $7m.equals("config.workbench.sideBar.location", "right"),
  order: 2
});
$hJ(class extends $gJ {
  constructor() {
    super({
      id: "workbench.action.toggleEditorVisibility",
      title: {
        ...localize2(2930, "Toggle Editor Area Visibility"),
        mnemonicTitle: localize(2870, null)
      },
      category: $qn.View,
      f1: true,
      toggled: $1pb,
      // the workbench grid currently prevents us from supporting panel maximization with non-center panel alignment
      precondition: $7m.and($opb.toNegated(), $7m.or($gqb.isEqualTo("center"), $fqb.notEqualsTo("bottom")))
    });
  }
  run(accessor) {
    accessor.get($Vlb).toggleMaximizedPanel();
  }
});
$dJ.appendMenuItem($bJ.MenubarViewMenu, {
  group: "2_appearance",
  title: localize(2871, null),
  submenu: $bJ.MenubarAppearanceMenu,
  order: 1
});
var ToggleSidebarVisibilityAction = class _ToggleSidebarVisibilityAction extends $gJ {
  static {
    this.ID = "workbench.action.toggleSidebarVisibility";
  }
  constructor() {
    super({
      id: _ToggleSidebarVisibilityAction.ID,
      title: localize2(2931, "Toggle Primary Side Bar Visibility"),
      toggled: {
        condition: $3pb,
        title: localize(2872, null),
        mnemonicTitle: localize(2873, null)
      },
      category: $qn.View,
      f1: true,
      keybinding: {
        weight: 200,
        primary: 2048 | 32
        /* KeyCode.KeyB */
      },
      menu: [
        {
          id: $bJ.LayoutControlMenuSubmenu,
          group: "0_workbench_layout",
          order: 0
        },
        {
          id: $bJ.MenubarAppearanceMenu,
          group: "2_workbench_layout",
          order: 1
        }
      ]
    });
  }
  run(accessor) {
    const layoutService = accessor.get($Vlb);
    layoutService.setPartHidden(
      layoutService.isVisible(
        "workbench.parts.sidebar"
        /* Parts.SIDEBAR_PART */
      ),
      "workbench.parts.sidebar"
      /* Parts.SIDEBAR_PART */
    );
  }
};
$hJ(ToggleSidebarVisibilityAction);
$dJ.appendMenuItems([
  {
    id: $bJ.ViewContainerTitleContext,
    item: {
      group: "3_workbench_layout_move",
      command: {
        id: ToggleSidebarVisibilityAction.ID,
        title: localize(2874, null)
      },
      when: $7m.and($3pb, $7m.equals("viewContainerLocation", $0M(
        0
        /* ViewContainerLocation.Sidebar */
      ))),
      order: 2
    }
  },
  {
    id: $bJ.ViewTitleContext,
    item: {
      group: "3_workbench_layout_move",
      command: {
        id: ToggleSidebarVisibilityAction.ID,
        title: localize(2875, null)
      },
      when: $7m.and($3pb, $7m.equals("viewLocation", $0M(
        0
        /* ViewContainerLocation.Sidebar */
      ))),
      order: 2
    }
  },
  {
    id: $bJ.LayoutControlMenu,
    item: {
      group: "2_pane_toggles",
      command: {
        id: ToggleSidebarVisibilityAction.ID,
        title: localize(2876, null),
        icon: panelLeftOffIcon,
        toggled: { condition: $3pb, icon: panelLeftIcon }
      },
      when: $7m.and($7m.or($7m.equals("config.workbench.layoutControl.type", "toggles"), $7m.equals("config.workbench.layoutControl.type", "both")), $7m.equals("config.workbench.sideBar.location", "left")),
      order: 0
    }
  },
  {
    id: $bJ.LayoutControlMenu,
    item: {
      group: "2_pane_toggles",
      command: {
        id: ToggleSidebarVisibilityAction.ID,
        title: localize(2877, null),
        icon: panelRightOffIcon,
        toggled: { condition: $3pb, icon: panelRightIcon }
      },
      when: $7m.and($7m.or($7m.equals("config.workbench.layoutControl.type", "toggles"), $7m.equals("config.workbench.layoutControl.type", "both")), $7m.equals("config.workbench.sideBar.location", "right")),
      order: 2
    }
  }
]);
var $Pqb = class _$Pqb extends $gJ {
  static {
    this.ID = "workbench.action.toggleStatusbarVisibility";
  }
  static {
    this.a = "workbench.statusBar.visible";
  }
  constructor() {
    super({
      id: _$Pqb.ID,
      title: {
        ...localize2(2932, "Toggle Status Bar Visibility"),
        mnemonicTitle: localize(2878, null)
      },
      category: $qn.View,
      f1: true,
      toggled: $7m.equals("config.workbench.statusBar.visible", true),
      menu: [{
        id: $bJ.MenubarAppearanceMenu,
        group: "2_workbench_layout",
        order: 3
      }]
    });
  }
  run(accessor) {
    const layoutService = accessor.get($Vlb);
    const configurationService = accessor.get($kl);
    const visibility = layoutService.isVisible("workbench.parts.statusbar", $Y);
    const newVisibilityValue = !visibility;
    return configurationService.updateValue(_$Pqb.a, newVisibilityValue);
  }
};
$hJ($Pqb);
var AbstractSetShowTabsAction = class extends $gJ {
  constructor(a, b, title, id2, precondition2, description) {
    super({
      id: id2,
      title,
      category: $qn.View,
      precondition: precondition2,
      metadata: description ? { description } : void 0,
      f1: true
    });
    this.a = a;
    this.b = b;
  }
  run(accessor) {
    const configurationService = accessor.get($kl);
    return configurationService.updateValue(this.a, this.b);
  }
};
var $Qqb = class _$Qqb extends AbstractSetShowTabsAction {
  static {
    this.ID = "workbench.action.hideEditorTabs";
  }
  constructor() {
    const precondition2 = $7m.and($7m.equals(
      `config.${"workbench.editor.showTabs"}`,
      "none"
      /* EditorTabsMode.NONE */
    ).negate(), $Xpb.negate());
    const title = localize2(2933, "Hide Editor Tabs");
    super("workbench.editor.showTabs", "none", title, _$Qqb.ID, precondition2, localize2(2934, "Hide Tab Bar"));
  }
};
var $Rqb = class _$Rqb extends AbstractSetShowTabsAction {
  static {
    this.ID = "workbench.action.zenHideEditorTabs";
  }
  constructor() {
    const precondition2 = $7m.and($7m.equals(
      `config.${"zenMode.showTabs"}`,
      "none"
      /* EditorTabsMode.NONE */
    ).negate(), $Xpb);
    const title = localize2(2935, "Hide Editor Tabs in Zen Mode");
    super("zenMode.showTabs", "none", title, _$Rqb.ID, precondition2, localize2(2936, "Hide Tab Bar in Zen Mode"));
  }
};
var $Sqb = class _$Sqb extends AbstractSetShowTabsAction {
  static {
    this.ID = "workbench.action.showMultipleEditorTabs";
  }
  constructor() {
    const precondition2 = $7m.and($7m.equals(
      `config.${"workbench.editor.showTabs"}`,
      "multiple"
      /* EditorTabsMode.MULTIPLE */
    ).negate(), $Xpb.negate());
    const title = localize2(2937, "Show Multiple Editor Tabs");
    super("workbench.editor.showTabs", "multiple", title, _$Sqb.ID, precondition2, localize2(2938, "Show Tab Bar with multiple tabs"));
  }
};
var $Tqb = class _$Tqb extends AbstractSetShowTabsAction {
  static {
    this.ID = "workbench.action.zenShowMultipleEditorTabs";
  }
  constructor() {
    const precondition2 = $7m.and($7m.equals(
      `config.${"zenMode.showTabs"}`,
      "multiple"
      /* EditorTabsMode.MULTIPLE */
    ).negate(), $Xpb);
    const title = localize2(2939, "Show Multiple Editor Tabs in Zen Mode");
    super("zenMode.showTabs", "multiple", title, _$Tqb.ID, precondition2, localize2(2940, "Show Tab Bar in Zen Mode"));
  }
};
var $Uqb = class _$Uqb extends AbstractSetShowTabsAction {
  static {
    this.ID = "workbench.action.showEditorTab";
  }
  constructor() {
    const precondition2 = $7m.and($7m.equals(
      `config.${"workbench.editor.showTabs"}`,
      "single"
      /* EditorTabsMode.SINGLE */
    ).negate(), $Xpb.negate());
    const title = localize2(2941, "Show Single Editor Tab");
    super("workbench.editor.showTabs", "single", title, _$Uqb.ID, precondition2, localize2(2942, "Show Tab Bar with one Tab"));
  }
};
var $Vqb = class _$Vqb extends AbstractSetShowTabsAction {
  static {
    this.ID = "workbench.action.zenShowEditorTab";
  }
  constructor() {
    const precondition2 = $7m.and($7m.equals(
      `config.${"zenMode.showTabs"}`,
      "single"
      /* EditorTabsMode.SINGLE */
    ).negate(), $Xpb);
    const title = localize2(2943, "Show Single Editor Tab in Zen Mode");
    super("zenMode.showTabs", "single", title, _$Vqb.ID, precondition2, localize2(2944, "Show Tab Bar in Zen Mode with one Tab"));
  }
};
$hJ($Qqb);
$hJ($Rqb);
$hJ($Sqb);
$hJ($Tqb);
$hJ($Uqb);
$hJ($Vqb);
$dJ.appendMenuItem($bJ.MenubarAppearanceMenu, {
  submenu: $bJ.EditorTabsBarShowTabsSubmenu,
  title: localize(2879, null),
  group: "3_workbench_layout_move",
  order: 10,
  when: $Xpb.negate()
});
$dJ.appendMenuItem($bJ.MenubarAppearanceMenu, {
  submenu: $bJ.EditorTabsBarShowTabsZenModeSubmenu,
  title: localize(2880, null),
  group: "3_workbench_layout_move",
  order: 10,
  when: $Xpb
});
var $Wqb = class _$Wqb extends $gJ {
  static {
    this.ID = "workbench.action.editorActionsTitleBar";
  }
  constructor() {
    super({
      id: _$Wqb.ID,
      title: localize2(2945, "Move Editor Actions to Title Bar"),
      category: $qn.View,
      precondition: $7m.equals(
        `config.${"workbench.editor.editorActionsLocation"}`,
        "titleBar"
        /* EditorActionsLocation.TITLEBAR */
      ).negate(),
      metadata: { description: localize2(2946, "Move Editor Actions from the tab bar to the title bar") },
      f1: true
    });
  }
  run(accessor) {
    const configurationService = accessor.get($kl);
    return configurationService.updateValue(
      "workbench.editor.editorActionsLocation",
      "titleBar"
      /* EditorActionsLocation.TITLEBAR */
    );
  }
};
$hJ($Wqb);
var $Xqb = class _$Xqb extends $gJ {
  static {
    this.ID = "workbench.action.editorActionsDefault";
  }
  constructor() {
    super({
      id: _$Xqb.ID,
      title: localize2(2947, "Move Editor Actions to Tab Bar"),
      category: $qn.View,
      precondition: $7m.and($7m.equals(
        `config.${"workbench.editor.editorActionsLocation"}`,
        "default"
        /* EditorActionsLocation.DEFAULT */
      ).negate(), $7m.equals(
        `config.${"workbench.editor.showTabs"}`,
        "none"
        /* EditorTabsMode.NONE */
      ).negate()),
      metadata: { description: localize2(2948, "Move Editor Actions from the title bar to the tab bar") },
      f1: true
    });
  }
  run(accessor) {
    const configurationService = accessor.get($kl);
    return configurationService.updateValue(
      "workbench.editor.editorActionsLocation",
      "default"
      /* EditorActionsLocation.DEFAULT */
    );
  }
};
$hJ($Xqb);
var $Yqb = class _$Yqb extends $gJ {
  static {
    this.ID = "workbench.action.hideEditorActions";
  }
  constructor() {
    super({
      id: _$Yqb.ID,
      title: localize2(2949, "Hide Editor Actions"),
      category: $qn.View,
      precondition: $7m.equals(
        `config.${"workbench.editor.editorActionsLocation"}`,
        "hidden"
        /* EditorActionsLocation.HIDDEN */
      ).negate(),
      metadata: { description: localize2(2950, "Hide Editor Actions in the tab and title bar") },
      f1: true
    });
  }
  run(accessor) {
    const configurationService = accessor.get($kl);
    return configurationService.updateValue(
      "workbench.editor.editorActionsLocation",
      "hidden"
      /* EditorActionsLocation.HIDDEN */
    );
  }
};
$hJ($Yqb);
var $Zqb = class _$Zqb extends $gJ {
  static {
    this.ID = "workbench.action.showEditorActions";
  }
  constructor() {
    super({
      id: _$Zqb.ID,
      title: localize2(2951, "Show Editor Actions"),
      category: $qn.View,
      precondition: $7m.equals(
        `config.${"workbench.editor.editorActionsLocation"}`,
        "hidden"
        /* EditorActionsLocation.HIDDEN */
      ),
      metadata: { description: localize2(2952, "Make Editor Actions visible.") },
      f1: true
    });
  }
  run(accessor) {
    const configurationService = accessor.get($kl);
    return configurationService.updateValue(
      "workbench.editor.editorActionsLocation",
      "default"
      /* EditorActionsLocation.DEFAULT */
    );
  }
};
$hJ($Zqb);
$dJ.appendMenuItem($bJ.MenubarAppearanceMenu, {
  submenu: $bJ.EditorActionsPositionSubmenu,
  title: localize(2881, null),
  group: "3_workbench_layout_move",
  order: 11
});
var $1qb = class _$1qb extends $gJ {
  static {
    this.ID = "workbench.action.configureEditorTabs";
  }
  constructor() {
    super({
      id: _$1qb.ID,
      title: localize2(2953, "Configure Tabs"),
      category: $qn.View
    });
  }
  run(accessor) {
    const preferencesService = accessor.get($TK);
    preferencesService.openSettings({ jsonEditor: false, query: "workbench.editor tab" });
  }
};
$hJ($1qb);
var $2qb = class _$2qb extends $gJ {
  static {
    this.ID = "workbench.action.configureEditor";
  }
  constructor() {
    super({
      id: _$2qb.ID,
      title: localize2(2954, "Configure Editors"),
      category: $qn.View
    });
  }
  run(accessor) {
    const preferencesService = accessor.get($TK);
    preferencesService.openSettings({ jsonEditor: false, query: "workbench.editor" });
  }
};
$hJ($2qb);
$hJ(class extends $gJ {
  constructor() {
    super({
      id: "workbench.action.toggleSeparatePinnedEditorTabs",
      title: localize2(2955, "Separate Pinned Editor Tabs"),
      category: $qn.View,
      precondition: $7m.equals(
        `config.${"workbench.editor.showTabs"}`,
        "multiple"
        /* EditorTabsMode.MULTIPLE */
      ),
      metadata: { description: localize2(2956, "Toggle whether pinned editor tabs are shown on a separate row above unpinned tabs.") },
      f1: true
    });
  }
  run(accessor) {
    const configurationService = accessor.get($kl);
    const oldettingValue = configurationService.getValue("workbench.editor.pinnedTabsOnSeparateRow");
    const newSettingValue = !oldettingValue;
    return configurationService.updateValue("workbench.editor.pinnedTabsOnSeparateRow", newSettingValue);
  }
});
$hJ(class extends $gJ {
  constructor() {
    super({
      id: "workbench.action.toggleZenMode",
      title: {
        ...localize2(2957, "Toggle Zen Mode"),
        mnemonicTitle: localize(2882, null)
      },
      precondition: $opb.toNegated(),
      category: $qn.View,
      f1: true,
      keybinding: {
        weight: 200,
        primary: $$e(
          2048 | 41,
          56
          /* KeyCode.KeyZ */
        )
      },
      toggled: $Xpb,
      menu: [{
        id: $bJ.MenubarAppearanceMenu,
        group: "1_toggle_view",
        order: 2
      }]
    });
  }
  run(accessor) {
    return accessor.get($Vlb).toggleZenMode();
  }
});
$0I.registerCommandAndKeybindingRule({
  id: "workbench.action.exitZenMode",
  weight: 100 - 1e3,
  handler(accessor) {
    const layoutService = accessor.get($Vlb);
    const contextKeyService = accessor.get($on);
    if ($Xpb.getValue(contextKeyService)) {
      layoutService.toggleZenMode();
    }
  },
  when: $Xpb,
  primary: $$e(
    9,
    9
    /* KeyCode.Escape */
  )
});
if ($l || $n || $r) {
  $hJ(class ToggleMenubarAction extends $gJ {
    constructor() {
      super({
        id: "workbench.action.toggleMenuBar",
        title: {
          ...localize2(2958, "Toggle Menu Bar"),
          mnemonicTitle: localize(2883, null)
        },
        category: $qn.View,
        f1: true,
        toggled: $7m.and($web.toNegated(), $7m.notEquals("config.window.menuBarVisibility", "hidden"), $7m.notEquals("config.window.menuBarVisibility", "toggle"), $7m.notEquals("config.window.menuBarVisibility", "compact")),
        menu: [{
          id: $bJ.MenubarAppearanceMenu,
          group: "2_workbench_layout",
          order: 0
        }]
      });
    }
    run(accessor) {
      return accessor.get($Vlb).toggleMenuBar();
    }
  });
  for (const menuId of [$bJ.TitleBarContext, $bJ.TitleBarTitleContext]) {
    $dJ.appendMenuItem(menuId, {
      command: {
        id: "workbench.action.toggleMenuBar",
        title: localize(2884, null),
        toggled: $7m.and($web.toNegated(), $7m.notEquals("config.window.menuBarVisibility", "hidden"), $7m.notEquals("config.window.menuBarVisibility", "toggle"), $7m.notEquals("config.window.menuBarVisibility", "compact"))
      },
      when: $7m.and($opb.toNegated(), $7m.notEquals(
        $7pb.key,
        "native"
        /* TitlebarStyle.NATIVE */
      ), $npb.negate()),
      group: "2_config",
      order: 0
    });
  }
}
$hJ(class extends $gJ {
  constructor() {
    super({
      id: "workbench.action.resetViewLocations",
      title: localize2(2959, "Reset View Locations"),
      category: $qn.View,
      f1: true
    });
  }
  run(accessor) {
    return accessor.get($$M).reset();
  }
});
$hJ(class extends $gJ {
  constructor() {
    super({
      id: "workbench.action.moveView",
      title: localize2(2960, "Move View"),
      category: $qn.View,
      f1: true
    });
  }
  async run(accessor) {
    const viewDescriptorService = accessor.get($$M);
    const instantiationService = accessor.get($Pk);
    const quickInputService = accessor.get($1M);
    const contextKeyService = accessor.get($on);
    const paneCompositePartService = accessor.get($uqb);
    const focusedViewId = $jqb.getValue(contextKeyService);
    let viewId;
    if (focusedViewId && viewDescriptorService.getViewDescriptorById(focusedViewId)?.canMoveView) {
      viewId = focusedViewId;
    }
    try {
      viewId = await this.b(quickInputService, viewDescriptorService, paneCompositePartService, viewId);
      if (!viewId) {
        return;
      }
      const moveFocusedViewAction = new MoveFocusedViewAction();
      instantiationService.invokeFunction((accessor2) => moveFocusedViewAction.run(accessor2, viewId));
    } catch {
    }
  }
  a(viewDescriptorService, paneCompositePartService) {
    const results = [];
    const viewlets = paneCompositePartService.getVisiblePaneCompositeIds(
      0
      /* ViewContainerLocation.Sidebar */
    );
    viewlets.forEach((viewletId) => {
      const container2 = viewDescriptorService.getViewContainerById(viewletId);
      const containerModel = viewDescriptorService.getViewContainerModel(container2);
      let hasAddedView = false;
      containerModel.visibleViewDescriptors.forEach((viewDescriptor3) => {
        if (viewDescriptor3.canMoveView) {
          if (!hasAddedView) {
            results.push({
              type: "separator",
              label: localize(2885, null, containerModel.title)
            });
            hasAddedView = true;
          }
          results.push({
            id: viewDescriptor3.id,
            label: viewDescriptor3.name.value
          });
        }
      });
    });
    const panels = paneCompositePartService.getPinnedPaneCompositeIds(
      1
      /* ViewContainerLocation.Panel */
    );
    panels.forEach((panel) => {
      const container2 = viewDescriptorService.getViewContainerById(panel);
      const containerModel = viewDescriptorService.getViewContainerModel(container2);
      let hasAddedView = false;
      containerModel.visibleViewDescriptors.forEach((viewDescriptor3) => {
        if (viewDescriptor3.canMoveView) {
          if (!hasAddedView) {
            results.push({
              type: "separator",
              label: localize(2886, null, containerModel.title)
            });
            hasAddedView = true;
          }
          results.push({
            id: viewDescriptor3.id,
            label: viewDescriptor3.name.value
          });
        }
      });
    });
    const sidePanels = paneCompositePartService.getPinnedPaneCompositeIds(
      2
      /* ViewContainerLocation.AuxiliaryBar */
    );
    sidePanels.forEach((panel) => {
      const container2 = viewDescriptorService.getViewContainerById(panel);
      const containerModel = viewDescriptorService.getViewContainerModel(container2);
      let hasAddedView = false;
      containerModel.visibleViewDescriptors.forEach((viewDescriptor3) => {
        if (viewDescriptor3.canMoveView) {
          if (!hasAddedView) {
            results.push({
              type: "separator",
              label: localize(2887, null, containerModel.title)
            });
            hasAddedView = true;
          }
          results.push({
            id: viewDescriptor3.id,
            label: viewDescriptor3.name.value
          });
        }
      });
    });
    return results;
  }
  async b(quickInputService, viewDescriptorService, paneCompositePartService, viewId) {
    const disposables = new $2c();
    const quickPick = disposables.add(quickInputService.createQuickPick({ useSeparators: true }));
    quickPick.placeholder = localize(2888, null);
    quickPick.items = this.a(viewDescriptorService, paneCompositePartService);
    quickPick.selectedItems = quickPick.items.filter((item) => item.id === viewId);
    return new Promise((resolve, reject) => {
      disposables.add(quickPick.onDidAccept(() => {
        const viewId2 = quickPick.selectedItems[0];
        if (viewId2.id) {
          resolve(viewId2.id);
        } else {
          reject();
        }
        quickPick.hide();
      }));
      disposables.add(quickPick.onDidHide(() => {
        disposables.dispose();
        reject();
      }));
      quickPick.show();
    });
  }
});
var MoveFocusedViewAction = class extends $gJ {
  constructor() {
    super({
      id: "workbench.action.moveFocusedView",
      title: localize2(2961, "Move Focused View"),
      category: $qn.View,
      precondition: $jqb.notEqualsTo(""),
      f1: true
    });
  }
  run(accessor, viewId) {
    const viewDescriptorService = accessor.get($$M);
    const viewsService = accessor.get($uob);
    const quickInputService = accessor.get($1M);
    const contextKeyService = accessor.get($on);
    const dialogService = accessor.get($Yv);
    const paneCompositePartService = accessor.get($uqb);
    const focusedViewId = viewId || $jqb.getValue(contextKeyService);
    if (focusedViewId === void 0 || focusedViewId.trim() === "") {
      dialogService.error(localize(2889, null));
      return;
    }
    const viewDescriptor3 = viewDescriptorService.getViewDescriptorById(focusedViewId);
    if (!viewDescriptor3 || !viewDescriptor3.canMoveView) {
      dialogService.error(localize(2890, null));
      return;
    }
    const disposables = new $2c();
    const quickPick = disposables.add(quickInputService.createQuickPick({ useSeparators: true }));
    quickPick.placeholder = localize(2891, null);
    quickPick.title = localize(2892, null, viewDescriptor3.name.value);
    const items = [];
    const currentContainer = viewDescriptorService.getViewContainerByViewId(focusedViewId);
    const currentLocation = viewDescriptorService.getViewLocationById(focusedViewId);
    const isViewSolo = viewDescriptorService.getViewContainerModel(currentContainer).allViewDescriptors.length === 1;
    if (!(isViewSolo && currentLocation === 1)) {
      items.push({
        id: "_.panel.newcontainer",
        label: localize(2893, null)
      });
    }
    if (!(isViewSolo && currentLocation === 0)) {
      items.push({
        id: "_.sidebar.newcontainer",
        label: localize(2894, null)
      });
    }
    if (!(isViewSolo && currentLocation === 2)) {
      items.push({
        id: "_.auxiliarybar.newcontainer",
        label: localize(2895, null)
      });
    }
    items.push({
      type: "separator",
      label: localize(2896, null)
    });
    const pinnedViewlets = paneCompositePartService.getVisiblePaneCompositeIds(
      0
      /* ViewContainerLocation.Sidebar */
    );
    items.push(...pinnedViewlets.filter((viewletId) => {
      if (viewletId === viewDescriptorService.getViewContainerByViewId(focusedViewId).id) {
        return false;
      }
      return !viewDescriptorService.getViewContainerById(viewletId).rejectAddedViews;
    }).map((viewletId) => {
      return {
        id: viewletId,
        label: viewDescriptorService.getViewContainerModel(viewDescriptorService.getViewContainerById(viewletId)).title
      };
    }));
    items.push({
      type: "separator",
      label: localize(2897, null)
    });
    const pinnedPanels = paneCompositePartService.getPinnedPaneCompositeIds(
      1
      /* ViewContainerLocation.Panel */
    );
    items.push(...pinnedPanels.filter((panel) => {
      if (panel === viewDescriptorService.getViewContainerByViewId(focusedViewId).id) {
        return false;
      }
      return !viewDescriptorService.getViewContainerById(panel).rejectAddedViews;
    }).map((panel) => {
      return {
        id: panel,
        label: viewDescriptorService.getViewContainerModel(viewDescriptorService.getViewContainerById(panel)).title
      };
    }));
    items.push({
      type: "separator",
      label: localize(2898, null)
    });
    const pinnedAuxPanels = paneCompositePartService.getPinnedPaneCompositeIds(
      2
      /* ViewContainerLocation.AuxiliaryBar */
    );
    items.push(...pinnedAuxPanels.filter((panel) => {
      if (panel === viewDescriptorService.getViewContainerByViewId(focusedViewId).id) {
        return false;
      }
      return !viewDescriptorService.getViewContainerById(panel).rejectAddedViews;
    }).map((panel) => {
      return {
        id: panel,
        label: viewDescriptorService.getViewContainerModel(viewDescriptorService.getViewContainerById(panel)).title
      };
    }));
    quickPick.items = items;
    disposables.add(quickPick.onDidAccept(() => {
      const destination = quickPick.selectedItems[0];
      if (destination.id === "_.panel.newcontainer") {
        viewDescriptorService.moveViewToLocation(viewDescriptor3, 1, this.desc.id);
        viewsService.openView(focusedViewId, true);
      } else if (destination.id === "_.sidebar.newcontainer") {
        viewDescriptorService.moveViewToLocation(viewDescriptor3, 0, this.desc.id);
        viewsService.openView(focusedViewId, true);
      } else if (destination.id === "_.auxiliarybar.newcontainer") {
        viewDescriptorService.moveViewToLocation(viewDescriptor3, 2, this.desc.id);
        viewsService.openView(focusedViewId, true);
      } else if (destination.id) {
        viewDescriptorService.moveViewsToContainer([viewDescriptor3], viewDescriptorService.getViewContainerById(destination.id), void 0, this.desc.id);
        viewsService.openView(focusedViewId, true);
      }
      quickPick.hide();
    }));
    disposables.add(quickPick.onDidHide(() => disposables.dispose()));
    quickPick.show();
  }
};
$hJ(MoveFocusedViewAction);
$hJ(class extends $gJ {
  constructor() {
    super({
      id: "workbench.action.resetFocusedViewLocation",
      title: localize2(2962, "Reset Focused View Location"),
      category: $qn.View,
      f1: true,
      precondition: $jqb.notEqualsTo("")
    });
  }
  run(accessor) {
    const viewDescriptorService = accessor.get($$M);
    const contextKeyService = accessor.get($on);
    const dialogService = accessor.get($Yv);
    const viewsService = accessor.get($uob);
    const focusedViewId = $jqb.getValue(contextKeyService);
    let viewDescriptor3 = null;
    if (focusedViewId !== void 0 && focusedViewId.trim() !== "") {
      viewDescriptor3 = viewDescriptorService.getViewDescriptorById(focusedViewId);
    }
    if (!viewDescriptor3) {
      dialogService.error(localize(2899, null));
      return;
    }
    const defaultContainer = viewDescriptorService.getDefaultContainerById(viewDescriptor3.id);
    if (!defaultContainer || defaultContainer === viewDescriptorService.getViewContainerByViewId(viewDescriptor3.id)) {
      return;
    }
    viewDescriptorService.moveViewsToContainer([viewDescriptor3], defaultContainer, void 0, this.desc.id);
    viewsService.openView(viewDescriptor3.id, true);
  }
});
var BaseResizeViewAction = class extends $gJ {
  static {
    this.a = 60;
  }
  // This is a css pixel size
  b(widthChange, heightChange, layoutService, partToResize) {
    let part;
    if (partToResize === void 0) {
      const isEditorFocus = layoutService.hasFocus(
        "workbench.parts.editor"
        /* Parts.EDITOR_PART */
      );
      const isSidebarFocus = layoutService.hasFocus(
        "workbench.parts.sidebar"
        /* Parts.SIDEBAR_PART */
      );
      const isPanelFocus = layoutService.hasFocus(
        "workbench.parts.panel"
        /* Parts.PANEL_PART */
      );
      const isAuxiliaryBarFocus = layoutService.hasFocus(
        "workbench.parts.auxiliarybar"
        /* Parts.AUXILIARYBAR_PART */
      );
      if (isSidebarFocus) {
        part = "workbench.parts.sidebar";
      } else if (isPanelFocus) {
        part = "workbench.parts.panel";
      } else if (isEditorFocus) {
        part = "workbench.parts.editor";
      } else if (isAuxiliaryBarFocus) {
        part = "workbench.parts.auxiliarybar";
      }
    } else {
      part = partToResize;
    }
    if (part) {
      layoutService.resizePart(part, widthChange, heightChange);
    }
  }
};
var IncreaseViewSizeAction = class extends BaseResizeViewAction {
  constructor() {
    super({
      id: "workbench.action.increaseViewSize",
      title: localize2(2963, "Increase Current View Size"),
      f1: true,
      precondition: $opb.toNegated()
    });
  }
  run(accessor) {
    this.b(BaseResizeViewAction.a, BaseResizeViewAction.a, accessor.get($Vlb));
  }
};
var IncreaseViewWidthAction = class extends BaseResizeViewAction {
  constructor() {
    super({
      id: "workbench.action.increaseViewWidth",
      title: localize2(2964, "Increase Editor Width"),
      f1: true,
      precondition: $opb.toNegated()
    });
  }
  run(accessor) {
    this.b(
      BaseResizeViewAction.a,
      0,
      accessor.get($Vlb),
      "workbench.parts.editor"
      /* Parts.EDITOR_PART */
    );
  }
};
var IncreaseViewHeightAction = class extends BaseResizeViewAction {
  constructor() {
    super({
      id: "workbench.action.increaseViewHeight",
      title: localize2(2965, "Increase Editor Height"),
      f1: true,
      precondition: $opb.toNegated()
    });
  }
  run(accessor) {
    this.b(
      0,
      BaseResizeViewAction.a,
      accessor.get($Vlb),
      "workbench.parts.editor"
      /* Parts.EDITOR_PART */
    );
  }
};
var DecreaseViewSizeAction = class extends BaseResizeViewAction {
  constructor() {
    super({
      id: "workbench.action.decreaseViewSize",
      title: localize2(2966, "Decrease Current View Size"),
      f1: true,
      precondition: $opb.toNegated()
    });
  }
  run(accessor) {
    this.b(-BaseResizeViewAction.a, -BaseResizeViewAction.a, accessor.get($Vlb));
  }
};
var DecreaseViewWidthAction = class extends BaseResizeViewAction {
  constructor() {
    super({
      id: "workbench.action.decreaseViewWidth",
      title: localize2(2967, "Decrease Editor Width"),
      f1: true,
      precondition: $opb.toNegated()
    });
  }
  run(accessor) {
    this.b(
      -BaseResizeViewAction.a,
      0,
      accessor.get($Vlb),
      "workbench.parts.editor"
      /* Parts.EDITOR_PART */
    );
  }
};
var DecreaseViewHeightAction = class extends BaseResizeViewAction {
  constructor() {
    super({
      id: "workbench.action.decreaseViewHeight",
      title: localize2(2968, "Decrease Editor Height"),
      f1: true,
      precondition: $opb.toNegated()
    });
  }
  run(accessor) {
    this.b(
      0,
      -BaseResizeViewAction.a,
      accessor.get($Vlb),
      "workbench.parts.editor"
      /* Parts.EDITOR_PART */
    );
  }
};
$hJ(IncreaseViewSizeAction);
$hJ(IncreaseViewWidthAction);
$hJ(IncreaseViewHeightAction);
$hJ(DecreaseViewSizeAction);
$hJ(DecreaseViewWidthAction);
$hJ(DecreaseViewHeightAction);
function isContextualLayoutVisualIcon(icon2) {
  return icon2.iconA !== void 0;
}
var CreateToggleLayoutItem = (id2, active, label3, visualIcon) => {
  return {
    id: id2,
    active,
    label: label3,
    visualIcon,
    activeIcon: $6l.eye,
    inactiveIcon: $6l.eyeClosed,
    activeAriaLabel: localize(2900, null),
    inactiveAriaLabel: localize(2901, null),
    useButtons: true
  };
};
var CreateOptionLayoutItem = (id2, active, label3, visualIcon) => {
  return {
    id: id2,
    active,
    label: label3,
    visualIcon,
    activeIcon: $6l.check,
    activeAriaLabel: localize(2902, null),
    useButtons: false
  };
};
var MenuBarToggledContext = $7m.and($web.toNegated(), $7m.notEquals("config.window.menuBarVisibility", "hidden"), $7m.notEquals("config.window.menuBarVisibility", "toggle"), $7m.notEquals("config.window.menuBarVisibility", "compact"));
var ToggleVisibilityActions = [];
if (!$m || !$p) {
  ToggleVisibilityActions.push(CreateToggleLayoutItem("workbench.action.toggleMenuBar", MenuBarToggledContext, localize(2903, null), menubarIcon));
}
ToggleVisibilityActions.push(...[
  CreateToggleLayoutItem($Nqb, $7m.notEquals("config.workbench.activityBar.location", "hidden"), localize(2904, null), { whenA: $7m.equals("config.workbench.sideBar.location", "left"), iconA: activityBarLeftIcon, iconB: activityBarRightIcon }),
  CreateToggleLayoutItem(ToggleSidebarVisibilityAction.ID, $3pb, localize(2905, null), { whenA: $7m.equals("config.workbench.sideBar.location", "left"), iconA: panelLeftIcon, iconB: panelRightIcon }),
  CreateToggleLayoutItem($Jqb.ID, $cqb, localize(2906, null), { whenA: $7m.equals("config.workbench.sideBar.location", "left"), iconA: panelRightIcon, iconB: panelLeftIcon }),
  CreateToggleLayoutItem($Kqb.ID, $hqb, localize(2907, null), panelIcon2),
  CreateToggleLayoutItem($Pqb.ID, $7m.equals("config.workbench.statusBar.visible", true), localize(2908, null), statusBarIcon)
]);
var MoveSideBarActions = [
  CreateOptionLayoutItem(MoveSidebarLeftAction.ID, $7m.equals("config.workbench.sideBar.location", "left"), localize(2909, null), panelLeftIcon),
  CreateOptionLayoutItem(MoveSidebarRightAction.ID, $7m.equals("config.workbench.sideBar.location", "right"), localize(2910, null), panelRightIcon)
];
var AlignPanelActions = [
  CreateOptionLayoutItem("workbench.action.alignPanelLeft", $gqb.isEqualTo("left"), localize(2911, null), panelAlignmentLeftIcon),
  CreateOptionLayoutItem("workbench.action.alignPanelRight", $gqb.isEqualTo("right"), localize(2912, null), panelAlignmentRightIcon),
  CreateOptionLayoutItem("workbench.action.alignPanelCenter", $gqb.isEqualTo("center"), localize(2913, null), panelAlignmentCenterIcon),
  CreateOptionLayoutItem("workbench.action.alignPanelJustify", $gqb.isEqualTo("justify"), localize(2914, null), panelAlignmentJustifyIcon)
];
var MiscLayoutOptions = [
  CreateOptionLayoutItem("workbench.action.toggleFullScreen", $npb, localize(2915, null), fullscreenIcon),
  CreateOptionLayoutItem("workbench.action.toggleZenMode", $Xpb, localize(2916, null), zenModeIcon),
  CreateOptionLayoutItem("workbench.action.toggleCenteredLayout", $Ypb, localize(2917, null), centerLayoutIcon)
];
var LayoutContextKeySet = /* @__PURE__ */ new Set();
for (const { active } of [...ToggleVisibilityActions, ...MoveSideBarActions, ...AlignPanelActions, ...MiscLayoutOptions]) {
  for (const key2 of active.keys()) {
    LayoutContextKeySet.add(key2);
  }
}
$hJ(class CustomizeLayoutAction extends $gJ {
  constructor() {
    super({
      id: "workbench.action.customizeLayout",
      title: localize2(2969, "Customize Layout..."),
      f1: true,
      icon: configureLayoutIcon,
      menu: [
        {
          id: $bJ.LayoutControlMenuSubmenu,
          group: "z_end"
        },
        {
          id: $bJ.LayoutControlMenu,
          when: $7m.equals("config.workbench.layoutControl.type", "both"),
          group: "1_layout"
        }
      ]
    });
  }
  getItems(contextKeyService, keybindingService) {
    const toQuickPickItem = (item) => {
      const toggled = item.active.evaluate(contextKeyService.getContext(null));
      let label3 = item.useButtons ? item.label : item.label + (toggled && item.activeIcon ? ` $(${item.activeIcon.id})` : !toggled && item.inactiveIcon ? ` $(${item.inactiveIcon.id})` : "");
      const ariaLabel = item.label + (toggled && item.activeAriaLabel ? ` (${item.activeAriaLabel})` : !toggled && item.inactiveAriaLabel ? ` (${item.inactiveAriaLabel})` : "");
      if (item.visualIcon) {
        let icon3 = item.visualIcon;
        if (isContextualLayoutVisualIcon(icon3)) {
          const useIconA = icon3.whenA.evaluate(contextKeyService.getContext(null));
          icon3 = useIconA ? icon3.iconA : icon3.iconB;
        }
        label3 = `$(${icon3.id}) ${label3}`;
      }
      const icon2 = toggled ? item.activeIcon : item.inactiveIcon;
      return {
        type: "item",
        id: item.id,
        label: label3,
        ariaLabel,
        keybinding: keybindingService.lookupKeybinding(item.id, contextKeyService),
        buttons: !item.useButtons ? void 0 : [
          {
            alwaysVisible: false,
            tooltip: ariaLabel,
            iconClass: icon2 ? ThemeIcon.asClassName(icon2) : void 0
          }
        ]
      };
    };
    return [
      {
        type: "separator",
        label: localize(2918, null)
      },
      ...ToggleVisibilityActions.map(toQuickPickItem),
      {
        type: "separator",
        label: localize(2919, null)
      },
      ...MoveSideBarActions.map(toQuickPickItem),
      {
        type: "separator",
        label: localize(2920, null)
      },
      ...AlignPanelActions.map(toQuickPickItem),
      {
        type: "separator",
        label: localize(2921, null)
      },
      ...MiscLayoutOptions.map(toQuickPickItem)
    ];
  }
  run(accessor) {
    if (this.a) {
      this.a.hide();
      return;
    }
    const configurationService = accessor.get($kl);
    const contextKeyService = accessor.get($on);
    const commandService = accessor.get($sn);
    const quickInputService = accessor.get($1M);
    const keybindingService = accessor.get($Ty);
    const disposables = new $2c();
    const quickPick = disposables.add(quickInputService.createQuickPick({ useSeparators: true }));
    this.a = quickPick;
    quickPick.items = this.getItems(contextKeyService, keybindingService);
    quickPick.ignoreFocusOut = true;
    quickPick.hideInput = true;
    quickPick.title = localize(2922, null);
    const closeButton = {
      alwaysVisible: true,
      iconClass: ThemeIcon.asClassName($6l.close),
      tooltip: localize(2923, null)
    };
    const resetButton = {
      alwaysVisible: true,
      iconClass: ThemeIcon.asClassName($6l.discard),
      tooltip: localize(2924, null)
    };
    quickPick.buttons = [
      resetButton,
      closeButton
    ];
    let selectedItem = void 0;
    disposables.add(contextKeyService.onDidChangeContext((changeEvent) => {
      if (changeEvent.affectsSome(LayoutContextKeySet)) {
        quickPick.items = this.getItems(contextKeyService, keybindingService);
        if (selectedItem) {
          quickPick.activeItems = quickPick.items.filter((item) => item.id === selectedItem?.id);
        }
        setTimeout(() => quickInputService.focus(), 0);
      }
    }));
    disposables.add(quickPick.onDidAccept((event) => {
      if (quickPick.selectedItems.length) {
        selectedItem = quickPick.selectedItems[0];
        commandService.executeCommand(selectedItem.id);
      }
    }));
    disposables.add(quickPick.onDidTriggerItemButton((event) => {
      if (event.item) {
        selectedItem = event.item;
        commandService.executeCommand(selectedItem.id);
      }
    }));
    disposables.add(quickPick.onDidTriggerButton((button) => {
      if (button === closeButton) {
        quickPick.hide();
      } else if (button === resetButton) {
        const resetSetting = (id2) => {
          const config = configurationService.inspect(id2);
          configurationService.updateValue(id2, config.defaultValue);
        };
        resetSetting("workbench.activityBar.location");
        resetSetting("workbench.sideBar.location");
        resetSetting("workbench.statusBar.visible");
        resetSetting("workbench.panel.defaultLocation");
        if (!$m || !$p) {
          resetSetting("window.menuBarVisibility");
        }
        commandService.executeCommand("workbench.action.alignPanelCenter");
      }
    }));
    disposables.add(quickPick.onDidHide(() => {
      quickPick.dispose();
    }));
    disposables.add(quickPick.onDispose(() => {
      this.a = void 0;
      disposables.dispose();
    }));
    quickPick.show();
  }
});

// out-build/vs/workbench/browser/actions/listCommands.js
function ensureDOMFocus(widget) {
  const element = widget?.getHTMLElement();
  if (element && !$Mj(element)) {
    widget?.domFocus();
  }
}
async function updateFocus(widget, updateFocusFn) {
  if (!$Peb.getValue(widget.contextKeyService)) {
    return updateFocusFn(widget);
  }
  const focus = widget.getFocus();
  const selection = widget.getSelection();
  await updateFocusFn(widget);
  const newFocus = widget.getFocus();
  if (selection.length > 1 || !$zb(focus, selection) || $zb(focus, newFocus)) {
    return;
  }
  const fakeKeyboardEvent = new KeyboardEvent("keydown");
  widget.setSelection(newFocus, fakeKeyboardEvent);
}
async function navigate(widget, updateFocusFn) {
  if (!widget) {
    return;
  }
  await updateFocus(widget, updateFocusFn);
  const listFocus = widget.getFocus();
  if (listFocus.length) {
    widget.reveal(listFocus[0]);
  }
  widget.setAnchor(listFocus[0]);
  ensureDOMFocus(widget);
}
$0I.registerCommandAndKeybindingRule({
  id: "list.focusDown",
  weight: 200,
  when: $Leb,
  primary: 18,
  mac: {
    primary: 18,
    secondary: [
      256 | 44
      /* KeyCode.KeyN */
    ]
  },
  handler: (accessor, arg2) => {
    navigate(accessor.get($Deb).lastFocusedList, async (widget) => {
      const fakeKeyboardEvent = new KeyboardEvent("keydown");
      await widget.focusNext(typeof arg2 === "number" ? arg2 : 1, false, fakeKeyboardEvent);
    });
  }
});
$0I.registerCommandAndKeybindingRule({
  id: "list.focusUp",
  weight: 200,
  when: $Leb,
  primary: 16,
  mac: {
    primary: 16,
    secondary: [
      256 | 46
      /* KeyCode.KeyP */
    ]
  },
  handler: (accessor, arg2) => {
    navigate(accessor.get($Deb).lastFocusedList, async (widget) => {
      const fakeKeyboardEvent = new KeyboardEvent("keydown");
      await widget.focusPrevious(typeof arg2 === "number" ? arg2 : 1, false, fakeKeyboardEvent);
    });
  }
});
$0I.registerCommandAndKeybindingRule({
  id: "list.focusAnyDown",
  weight: 200,
  when: $Leb,
  primary: 512 | 18,
  mac: {
    primary: 512 | 18,
    secondary: [
      256 | 512 | 44
      /* KeyCode.KeyN */
    ]
  },
  handler: (accessor, arg2) => {
    navigate(accessor.get($Deb).lastFocusedList, async (widget) => {
      const fakeKeyboardEvent = new KeyboardEvent("keydown", { altKey: true });
      await widget.focusNext(typeof arg2 === "number" ? arg2 : 1, false, fakeKeyboardEvent);
    });
  }
});
$0I.registerCommandAndKeybindingRule({
  id: "list.focusAnyUp",
  weight: 200,
  when: $Leb,
  primary: 512 | 16,
  mac: {
    primary: 512 | 16,
    secondary: [
      256 | 512 | 46
      /* KeyCode.KeyP */
    ]
  },
  handler: (accessor, arg2) => {
    navigate(accessor.get($Deb).lastFocusedList, async (widget) => {
      const fakeKeyboardEvent = new KeyboardEvent("keydown", { altKey: true });
      await widget.focusPrevious(typeof arg2 === "number" ? arg2 : 1, false, fakeKeyboardEvent);
    });
  }
});
$0I.registerCommandAndKeybindingRule({
  id: "list.focusPageDown",
  weight: 200,
  when: $Leb,
  primary: 12,
  handler: (accessor) => {
    navigate(accessor.get($Deb).lastFocusedList, async (widget) => {
      const fakeKeyboardEvent = new KeyboardEvent("keydown");
      await widget.focusNextPage(fakeKeyboardEvent);
    });
  }
});
$0I.registerCommandAndKeybindingRule({
  id: "list.focusPageUp",
  weight: 200,
  when: $Leb,
  primary: 11,
  handler: (accessor) => {
    navigate(accessor.get($Deb).lastFocusedList, async (widget) => {
      const fakeKeyboardEvent = new KeyboardEvent("keydown");
      await widget.focusPreviousPage(fakeKeyboardEvent);
    });
  }
});
$0I.registerCommandAndKeybindingRule({
  id: "list.focusFirst",
  weight: 200,
  when: $Leb,
  primary: 14,
  handler: (accessor) => {
    navigate(accessor.get($Deb).lastFocusedList, async (widget) => {
      const fakeKeyboardEvent = new KeyboardEvent("keydown");
      await widget.focusFirst(fakeKeyboardEvent);
    });
  }
});
$0I.registerCommandAndKeybindingRule({
  id: "list.focusLast",
  weight: 200,
  when: $Leb,
  primary: 13,
  handler: (accessor) => {
    navigate(accessor.get($Deb).lastFocusedList, async (widget) => {
      const fakeKeyboardEvent = new KeyboardEvent("keydown");
      await widget.focusLast(fakeKeyboardEvent);
    });
  }
});
$0I.registerCommandAndKeybindingRule({
  id: "list.focusAnyFirst",
  weight: 200,
  when: $Leb,
  primary: 512 | 14,
  handler: (accessor) => {
    navigate(accessor.get($Deb).lastFocusedList, async (widget) => {
      const fakeKeyboardEvent = new KeyboardEvent("keydown", { altKey: true });
      await widget.focusFirst(fakeKeyboardEvent);
    });
  }
});
$0I.registerCommandAndKeybindingRule({
  id: "list.focusAnyLast",
  weight: 200,
  when: $Leb,
  primary: 512 | 13,
  handler: (accessor) => {
    navigate(accessor.get($Deb).lastFocusedList, async (widget) => {
      const fakeKeyboardEvent = new KeyboardEvent("keydown", { altKey: true });
      await widget.focusLast(fakeKeyboardEvent);
    });
  }
});
function expandMultiSelection(focused, previousFocus) {
  if (focused instanceof $A1 || focused instanceof $422 || focused instanceof $e3) {
    const list2 = focused;
    const focus = list2.getFocus() ? list2.getFocus()[0] : void 0;
    const selection = list2.getSelection();
    if (selection && typeof focus === "number" && selection.indexOf(focus) >= 0) {
      list2.setSelection(selection.filter((s) => s !== previousFocus));
    } else {
      if (typeof focus === "number") {
        list2.setSelection(selection.concat(focus));
      }
    }
  } else if (focused instanceof $C3 || focused instanceof $G3 || focused instanceof $E3) {
    const list2 = focused;
    const focus = list2.getFocus() ? list2.getFocus()[0] : void 0;
    if (previousFocus === focus) {
      return;
    }
    const selection = list2.getSelection();
    const fakeKeyboardEvent = new KeyboardEvent("keydown", { shiftKey: true });
    if (selection && selection.indexOf(focus) >= 0) {
      list2.setSelection(selection.filter((s) => s !== previousFocus), fakeKeyboardEvent);
    } else {
      list2.setSelection(selection.concat(focus), fakeKeyboardEvent);
    }
  }
}
function revealFocusedStickyScroll(tree, postRevealAction) {
  const focus = tree.getStickyScrollFocus();
  if (focus.length === 0) {
    throw new Error(`StickyScroll has no focus`);
  }
  if (focus.length > 1) {
    throw new Error(`StickyScroll can only have a single focused item`);
  }
  tree.reveal(focus[0]);
  tree.getHTMLElement().focus();
  tree.setFocus(focus);
  postRevealAction?.(focus[0]);
}
$0I.registerCommandAndKeybindingRule({
  id: "list.expandSelectionDown",
  weight: 200,
  when: $7m.and($Leb, $Keb),
  primary: 1024 | 18,
  handler: (accessor, arg2) => {
    const widget = accessor.get($Deb).lastFocusedList;
    if (!widget) {
      return;
    }
    const previousFocus = widget.getFocus() ? widget.getFocus()[0] : void 0;
    const fakeKeyboardEvent = new KeyboardEvent("keydown");
    widget.focusNext(typeof arg2 === "number" ? arg2 : 1, false, fakeKeyboardEvent);
    expandMultiSelection(widget, previousFocus);
    const focus = widget.getFocus();
    if (focus.length) {
      widget.reveal(focus[0]);
    }
    ensureDOMFocus(widget);
  }
});
$0I.registerCommandAndKeybindingRule({
  id: "list.expandSelectionUp",
  weight: 200,
  when: $7m.and($Leb, $Keb),
  primary: 1024 | 16,
  handler: (accessor, arg2) => {
    const widget = accessor.get($Deb).lastFocusedList;
    if (!widget) {
      return;
    }
    const previousFocus = widget.getFocus() ? widget.getFocus()[0] : void 0;
    const fakeKeyboardEvent = new KeyboardEvent("keydown");
    widget.focusPrevious(typeof arg2 === "number" ? arg2 : 1, false, fakeKeyboardEvent);
    expandMultiSelection(widget, previousFocus);
    const focus = widget.getFocus();
    if (focus.length) {
      widget.reveal(focus[0]);
    }
    ensureDOMFocus(widget);
  }
});
$0I.registerCommandAndKeybindingRule({
  id: "list.collapse",
  weight: 200,
  when: $7m.and($Leb, $7m.or($Reb, $Seb)),
  primary: 15,
  mac: {
    primary: 15,
    secondary: [
      2048 | 16
      /* KeyCode.UpArrow */
    ]
  },
  handler: (accessor) => {
    const widget = accessor.get($Deb).lastFocusedList;
    if (!widget || !(widget instanceof $C3 || widget instanceof $G3 || widget instanceof $E3)) {
      return;
    }
    const tree = widget;
    const focusedElements = tree.getFocus();
    if (focusedElements.length === 0) {
      return;
    }
    const focus = focusedElements[0];
    if (!tree.collapse(focus)) {
      const parent = tree.getParentElement(focus);
      if (parent) {
        navigate(widget, (widget2) => {
          const fakeKeyboardEvent = new KeyboardEvent("keydown");
          widget2.setFocus([parent], fakeKeyboardEvent);
        });
      }
    }
  }
});
$0I.registerCommandAndKeybindingRule({
  id: "list.stickyScroll.collapse",
  weight: 200 + 50,
  when: $Jeb,
  primary: 15,
  mac: {
    primary: 15,
    secondary: [
      2048 | 16
      /* KeyCode.UpArrow */
    ]
  },
  handler: (accessor) => {
    const widget = accessor.get($Deb).lastFocusedList;
    if (!widget || !(widget instanceof $C3 || widget instanceof $G3 || widget instanceof $E3)) {
      return;
    }
    revealFocusedStickyScroll(widget, (focus) => widget.collapse(focus));
  }
});
$0I.registerCommandAndKeybindingRule({
  id: "list.collapseAll",
  weight: 200,
  when: $Leb,
  primary: 2048 | 15,
  mac: {
    primary: 2048 | 15,
    secondary: [
      2048 | 1024 | 16
      /* KeyCode.UpArrow */
    ]
  },
  handler: (accessor) => {
    const focused = accessor.get($Deb).lastFocusedList;
    if (focused && !(focused instanceof $A1 || focused instanceof $422 || focused instanceof $e3)) {
      focused.collapseAll();
    }
  }
});
$0I.registerCommandAndKeybindingRule({
  id: "list.collapseAllToFocus",
  weight: 200,
  when: $Leb,
  handler: (accessor) => {
    const focused = accessor.get($Deb).lastFocusedList;
    const fakeKeyboardEvent = $Zeb("keydown", true);
    if (focused instanceof $C3 || focused instanceof $G3 || focused instanceof $E3) {
      const tree = focused;
      const focus = tree.getFocus();
      if (focus.length > 0) {
        tree.collapse(focus[0], true);
      }
      tree.setSelection(focus, fakeKeyboardEvent);
      tree.setAnchor(focus[0]);
    }
  }
});
$0I.registerCommandAndKeybindingRule({
  id: "list.focusParent",
  weight: 200,
  when: $Leb,
  handler: (accessor) => {
    const widget = accessor.get($Deb).lastFocusedList;
    if (!widget || !(widget instanceof $C3 || widget instanceof $G3 || widget instanceof $E3)) {
      return;
    }
    const tree = widget;
    const focusedElements = tree.getFocus();
    if (focusedElements.length === 0) {
      return;
    }
    const focus = focusedElements[0];
    const parent = tree.getParentElement(focus);
    if (parent) {
      navigate(widget, (widget2) => {
        const fakeKeyboardEvent = new KeyboardEvent("keydown");
        widget2.setFocus([parent], fakeKeyboardEvent);
      });
    }
  }
});
$0I.registerCommandAndKeybindingRule({
  id: "list.expand",
  weight: 200,
  when: $7m.and($Leb, $7m.or($Teb, $Ueb)),
  primary: 17,
  handler: (accessor) => {
    const widget = accessor.get($Deb).lastFocusedList;
    if (!widget) {
      return;
    }
    if (widget instanceof $C3 || widget instanceof $G3) {
      const focusedElements = widget.getFocus();
      if (focusedElements.length === 0) {
        return;
      }
      const focus = focusedElements[0];
      if (!widget.expand(focus)) {
        const child = widget.getFirstElementChild(focus);
        if (child) {
          const node = widget.getNode(child);
          if (node.visible) {
            navigate(widget, (widget2) => {
              const fakeKeyboardEvent = new KeyboardEvent("keydown");
              widget2.setFocus([child], fakeKeyboardEvent);
            });
          }
        }
      }
    } else if (widget instanceof $E3) {
      const focusedElements = widget.getFocus();
      if (focusedElements.length === 0) {
        return;
      }
      const focus = focusedElements[0];
      widget.expand(focus).then((didExpand) => {
        if (focus && !didExpand) {
          const child = widget.getFirstElementChild(focus);
          if (child) {
            const node = widget.getNode(child);
            if (node.visible) {
              navigate(widget, (widget2) => {
                const fakeKeyboardEvent = new KeyboardEvent("keydown");
                widget2.setFocus([child], fakeKeyboardEvent);
              });
            }
          }
        }
      });
    }
  }
});
function selectElement(accessor, retainCurrentFocus) {
  const focused = accessor.get($Deb).lastFocusedList;
  const fakeKeyboardEvent = $Zeb("keydown", retainCurrentFocus);
  if (focused instanceof $A1 || focused instanceof $422 || focused instanceof $e3) {
    const list2 = focused;
    list2.setAnchor(list2.getFocus()[0]);
    list2.setSelection(list2.getFocus(), fakeKeyboardEvent);
  } else if (focused instanceof $C3 || focused instanceof $G3 || focused instanceof $E3) {
    const tree = focused;
    const focus = tree.getFocus();
    if (focus.length > 0) {
      let toggleCollapsed = true;
      if (tree.expandOnlyOnTwistieClick === true) {
        toggleCollapsed = false;
      } else if (typeof tree.expandOnlyOnTwistieClick !== "boolean" && tree.expandOnlyOnTwistieClick(focus[0])) {
        toggleCollapsed = false;
      }
      if (toggleCollapsed) {
        tree.toggleCollapsed(focus[0]);
      }
    }
    tree.setAnchor(focus[0]);
    tree.setSelection(focus, fakeKeyboardEvent);
  }
}
$0I.registerCommandAndKeybindingRule({
  id: "list.select",
  weight: 200,
  when: $Leb,
  primary: 3,
  mac: {
    primary: 3,
    secondary: [
      2048 | 18
      /* KeyCode.DownArrow */
    ]
  },
  handler: (accessor) => {
    selectElement(accessor, false);
  }
});
$0I.registerCommandAndKeybindingRule({
  id: "list.stickyScrollselect",
  weight: 200 + 50,
  // priorities over file explorer
  when: $Jeb,
  primary: 3,
  mac: {
    primary: 3,
    secondary: [
      2048 | 18
      /* KeyCode.DownArrow */
    ]
  },
  handler: (accessor) => {
    const widget = accessor.get($Deb).lastFocusedList;
    if (!widget || !(widget instanceof $C3 || widget instanceof $G3 || widget instanceof $E3)) {
      return;
    }
    revealFocusedStickyScroll(widget, (focus) => widget.setSelection([focus]));
  }
});
$0I.registerCommandAndKeybindingRule({
  id: "list.selectAndPreserveFocus",
  weight: 200,
  when: $Leb,
  handler: (accessor) => {
    selectElement(accessor, true);
  }
});
$0I.registerCommandAndKeybindingRule({
  id: "list.selectAll",
  weight: 200,
  when: $7m.and($Leb, $Keb),
  primary: 2048 | 31,
  handler: (accessor) => {
    const focused = accessor.get($Deb).lastFocusedList;
    if (focused instanceof $A1 || focused instanceof $422 || focused instanceof $e3) {
      const list2 = focused;
      const fakeKeyboardEvent = new KeyboardEvent("keydown");
      list2.setSelection($Ub(list2.length), fakeKeyboardEvent);
    } else if (focused instanceof $C3 || focused instanceof $G3 || focused instanceof $E3) {
      const tree = focused;
      const focus = tree.getFocus();
      const selection = tree.getSelection();
      let start = void 0;
      if (focus.length > 0 && (selection.length === 0 || !selection.includes(focus[0]))) {
        start = focus[0];
      }
      if (!start && selection.length > 0) {
        start = selection[0];
      }
      let scope = void 0;
      if (!start) {
        scope = void 0;
      } else {
        scope = tree.getParentElement(start);
      }
      const newSelection = [];
      const visit = (node) => {
        for (const child of node.children) {
          if (child.visible) {
            newSelection.push(child.element);
            if (!child.collapsed) {
              visit(child);
            }
          }
        }
      };
      visit(tree.getNode(scope));
      if (scope && selection.length === newSelection.length) {
        newSelection.unshift(scope);
      }
      const fakeKeyboardEvent = new KeyboardEvent("keydown");
      tree.setSelection(newSelection, fakeKeyboardEvent);
    }
  }
});
$0I.registerCommandAndKeybindingRule({
  id: "list.toggleSelection",
  weight: 200,
  when: $Leb,
  primary: 2048 | 1024 | 3,
  handler: (accessor) => {
    const widget = accessor.get($Deb).lastFocusedList;
    if (!widget) {
      return;
    }
    const focus = widget.getFocus();
    if (focus.length === 0) {
      return;
    }
    const selection = widget.getSelection();
    const index = selection.indexOf(focus[0]);
    if (index > -1) {
      widget.setSelection([...selection.slice(0, index), ...selection.slice(index + 1)]);
    } else {
      widget.setSelection([...selection, focus[0]]);
    }
  }
});
$0I.registerCommandAndKeybindingRule({
  id: "list.showHover",
  weight: 200,
  primary: $$e(
    2048 | 41,
    2048 | 39
    /* KeyCode.KeyI */
  ),
  when: $Leb,
  handler: async (accessor, ...args2) => {
    const listService = accessor.get($Deb);
    const lastFocusedList = listService.lastFocusedList;
    if (!lastFocusedList) {
      return;
    }
    const focus = lastFocusedList.getFocus();
    if (!focus || focus.length === 0) {
      return;
    }
    const treeDOM = lastFocusedList.getHTMLElement();
    const scrollableElement = treeDOM.querySelector(".monaco-scrollable-element");
    const listRows = scrollableElement?.querySelector(".monaco-list-rows");
    const focusedElement = listRows?.querySelector(".focused");
    if (!focusedElement) {
      return;
    }
    const elementWithHover = getCustomHoverForElement(focusedElement);
    if (elementWithHover) {
      accessor.get($5$).showManagedHover(elementWithHover);
    }
  }
});
function getCustomHoverForElement(element) {
  if (element.matches('[custom-hover="true"]')) {
    return element;
  }
  const noneFocusableElementWithHover = element.querySelector('[custom-hover="true"]:not([tabindex]):not(.action-item)');
  if (noneFocusableElementWithHover) {
    return noneFocusableElementWithHover;
  }
  return void 0;
}
$0I.registerCommandAndKeybindingRule({
  id: "list.toggleExpand",
  weight: 200,
  when: $Leb,
  primary: 10,
  handler: (accessor) => {
    const focused = accessor.get($Deb).lastFocusedList;
    if (focused instanceof $C3 || focused instanceof $G3 || focused instanceof $E3) {
      const tree = focused;
      const focus = tree.getFocus();
      if (focus.length > 0 && tree.isCollapsible(focus[0])) {
        tree.toggleCollapsed(focus[0]);
        return;
      }
    }
    selectElement(accessor, true);
  }
});
$0I.registerCommandAndKeybindingRule({
  id: "list.stickyScrolltoggleExpand",
  weight: 200 + 50,
  // priorities over file explorer
  when: $Jeb,
  primary: 10,
  handler: (accessor) => {
    const widget = accessor.get($Deb).lastFocusedList;
    if (!widget || !(widget instanceof $C3 || widget instanceof $G3 || widget instanceof $E3)) {
      return;
    }
    revealFocusedStickyScroll(widget);
  }
});
$0I.registerCommandAndKeybindingRule({
  id: "list.clear",
  weight: 200,
  when: $7m.and($Leb, $Meb),
  primary: 9,
  handler: (accessor) => {
    const widget = accessor.get($Deb).lastFocusedList;
    if (!widget) {
      return;
    }
    const selection = widget.getSelection();
    const fakeKeyboardEvent = new KeyboardEvent("keydown");
    if (selection.length > 1) {
      const useSelectionNavigation = $Peb.getValue(widget.contextKeyService);
      if (useSelectionNavigation) {
        const focus = widget.getFocus();
        widget.setSelection([focus[0]], fakeKeyboardEvent);
      } else {
        widget.setSelection([], fakeKeyboardEvent);
      }
    } else {
      widget.setSelection([], fakeKeyboardEvent);
      widget.setFocus([], fakeKeyboardEvent);
    }
    widget.setAnchor(void 0);
  }
});
$tn.registerCommand({
  id: "list.triggerTypeNavigation",
  handler: (accessor) => {
    const widget = accessor.get($Deb).lastFocusedList;
    widget?.triggerTypeNavigation();
  }
});
$tn.registerCommand({
  id: "list.toggleFindMode",
  handler: (accessor) => {
    const widget = accessor.get($Deb).lastFocusedList;
    if (widget instanceof $v3 || widget instanceof $E3) {
      const tree = widget;
      tree.findMode = tree.findMode === TreeFindMode.Filter ? TreeFindMode.Highlight : TreeFindMode.Filter;
    }
  }
});
$tn.registerCommand({
  id: "list.toggleFindMatchType",
  handler: (accessor) => {
    const widget = accessor.get($Deb).lastFocusedList;
    if (widget instanceof $v3 || widget instanceof $E3) {
      const tree = widget;
      tree.findMatchType = tree.findMatchType === TreeFindMatchType.Contiguous ? TreeFindMatchType.Fuzzy : TreeFindMatchType.Contiguous;
    }
  }
});
$tn.registerCommandAlias("list.toggleKeyboardNavigation", "list.triggerTypeNavigation");
$tn.registerCommandAlias("list.toggleFilterOnType", "list.toggleFindMode");
$0I.registerCommandAndKeybindingRule({
  id: "list.find",
  weight: 200,
  when: $7m.and($Ieb, $Qeb),
  primary: 2048 | 512 | 36,
  secondary: [
    61
    /* KeyCode.F3 */
  ],
  handler: (accessor) => {
    const widget = accessor.get($Deb).lastFocusedList;
    if (widget instanceof $A1 || widget instanceof $422 || widget instanceof $e3) {
    } else if (widget instanceof $v3 || widget instanceof $E3) {
      const tree = widget;
      tree.openFind();
    }
  }
});
$0I.registerCommandAndKeybindingRule({
  id: "list.closeFind",
  weight: 200,
  when: $7m.and($Ieb, $Veb),
  primary: 9,
  handler: (accessor) => {
    const widget = accessor.get($Deb).lastFocusedList;
    if (widget instanceof $v3 || widget instanceof $E3) {
      const tree = widget;
      tree.closeFind();
    }
  }
});
$0I.registerCommandAndKeybindingRule({
  id: "list.scrollUp",
  weight: 200,
  // Since the default keybindings for list.scrollUp and widgetNavigation.focusPrevious
  // are both Ctrl+UpArrow, we disable this command when the scrollbar is at
  // top-most position. This will give chance for widgetNavigation.focusPrevious to execute
  when: $7m.and($Leb, $Geb?.negate()),
  primary: 2048 | 16,
  handler: (accessor) => {
    const focused = accessor.get($Deb).lastFocusedList;
    if (!focused) {
      return;
    }
    focused.scrollTop -= 10;
  }
});
$0I.registerCommandAndKeybindingRule({
  id: "list.scrollDown",
  weight: 200,
  // same as above
  when: $7m.and($Leb, $Heb?.negate()),
  primary: 2048 | 18,
  handler: (accessor) => {
    const focused = accessor.get($Deb).lastFocusedList;
    if (!focused) {
      return;
    }
    focused.scrollTop += 10;
  }
});
$0I.registerCommandAndKeybindingRule({
  id: "list.scrollLeft",
  weight: 200,
  when: $Leb,
  handler: (accessor) => {
    const focused = accessor.get($Deb).lastFocusedList;
    if (!focused) {
      return;
    }
    focused.scrollLeft -= 10;
  }
});
$0I.registerCommandAndKeybindingRule({
  id: "list.scrollRight",
  weight: 200,
  when: $Leb,
  handler: (accessor) => {
    const focused = accessor.get($Deb).lastFocusedList;
    if (!focused) {
      return;
    }
    focused.scrollLeft += 10;
  }
});
$hJ(class ToggleStickyScroll extends $gJ {
  constructor() {
    super({
      id: "tree.toggleStickyScroll",
      title: {
        ...localize2(2972, "Toggle Tree Sticky Scroll"),
        mnemonicTitle: localize(2970, null)
      },
      category: "View",
      metadata: { description: localize(2971, null) },
      f1: true
    });
  }
  run(accessor) {
    const configurationService = accessor.get($kl);
    const newValue = !configurationService.getValue("workbench.tree.enableStickyScroll");
    configurationService.updateValue("workbench.tree.enableStickyScroll", newValue);
  }
});

// out-build/vs/workbench/browser/actions/navigationActions.js
var BaseNavigationAction = class extends $gJ {
  constructor(options3, a) {
    super(options3);
    this.a = a;
  }
  run(accessor) {
    const layoutService = accessor.get($Vlb);
    const editorGroupService = accessor.get($iJ);
    const paneCompositeService = accessor.get($uqb);
    const isEditorFocus = layoutService.hasFocus(
      "workbench.parts.editor"
      /* Parts.EDITOR_PART */
    );
    const isPanelFocus = layoutService.hasFocus(
      "workbench.parts.panel"
      /* Parts.PANEL_PART */
    );
    const isSidebarFocus = layoutService.hasFocus(
      "workbench.parts.sidebar"
      /* Parts.SIDEBAR_PART */
    );
    const isAuxiliaryBarFocus = layoutService.hasFocus(
      "workbench.parts.auxiliarybar"
      /* Parts.AUXILIARYBAR_PART */
    );
    let neighborPart;
    if (isEditorFocus) {
      const didNavigate = this.e(this.h(this.a), editorGroupService);
      if (didNavigate) {
        return;
      }
      neighborPart = layoutService.getVisibleNeighborPart("workbench.parts.editor", this.a);
    }
    if (isPanelFocus) {
      neighborPart = layoutService.getVisibleNeighborPart("workbench.parts.panel", this.a);
    }
    if (isSidebarFocus) {
      neighborPart = layoutService.getVisibleNeighborPart("workbench.parts.sidebar", this.a);
    }
    if (isAuxiliaryBarFocus) {
      neighborPart = neighborPart = layoutService.getVisibleNeighborPart("workbench.parts.auxiliarybar", this.a);
    }
    if (neighborPart === "workbench.parts.editor") {
      if (!this.g(this.h(this.a), editorGroupService)) {
        this.f(this.a === 3 ? 0 : 1, editorGroupService);
      }
    } else if (neighborPart === "workbench.parts.sidebar") {
      this.c(layoutService, paneCompositeService);
    } else if (neighborPart === "workbench.parts.panel") {
      this.b(layoutService, paneCompositeService);
    } else if (neighborPart === "workbench.parts.auxiliarybar") {
      this.d(layoutService, paneCompositeService);
    }
  }
  async b(layoutService, paneCompositeService) {
    if (!layoutService.isVisible(
      "workbench.parts.panel"
      /* Parts.PANEL_PART */
    )) {
      return false;
    }
    const activePanel = paneCompositeService.getActivePaneComposite(
      1
      /* ViewContainerLocation.Panel */
    );
    if (!activePanel) {
      return false;
    }
    const activePanelId = activePanel.getId();
    const res = await paneCompositeService.openPaneComposite(activePanelId, 1, true);
    if (!res) {
      return false;
    }
    return res;
  }
  async c(layoutService, paneCompositeService) {
    if (!layoutService.isVisible(
      "workbench.parts.sidebar"
      /* Parts.SIDEBAR_PART */
    )) {
      return false;
    }
    const activeViewlet = paneCompositeService.getActivePaneComposite(
      0
      /* ViewContainerLocation.Sidebar */
    );
    if (!activeViewlet) {
      return false;
    }
    const activeViewletId = activeViewlet.getId();
    const viewlet = await paneCompositeService.openPaneComposite(activeViewletId, 0, true);
    return !!viewlet;
  }
  async d(layoutService, paneCompositeService) {
    if (!layoutService.isVisible(
      "workbench.parts.auxiliarybar"
      /* Parts.AUXILIARYBAR_PART */
    )) {
      return false;
    }
    const activePanel = paneCompositeService.getActivePaneComposite(
      2
      /* ViewContainerLocation.AuxiliaryBar */
    );
    if (!activePanel) {
      return false;
    }
    const activePanelId = activePanel.getId();
    const res = await paneCompositeService.openPaneComposite(activePanelId, 2, true);
    if (!res) {
      return false;
    }
    return res;
  }
  e(direction, editorGroupService) {
    return this.j({ direction }, editorGroupService);
  }
  f(location3, editorGroupService) {
    return this.j({ location: location3 }, editorGroupService);
  }
  g(direction, editorGroupService) {
    if (!editorGroupService.activeGroup) {
      return false;
    }
    const oppositeDirection2 = this.i(direction);
    const groupInBetween = editorGroupService.findGroup({ direction: oppositeDirection2 }, editorGroupService.activeGroup);
    if (!groupInBetween) {
      editorGroupService.activeGroup.focus();
      return true;
    }
    return false;
  }
  h(direction) {
    switch (direction) {
      case 1:
        return 1;
      case 2:
        return 2;
      case 3:
        return 3;
      case 0:
        return 0;
    }
  }
  i(direction) {
    switch (direction) {
      case 0:
        return 1;
      case 3:
        return 2;
      case 2:
        return 3;
      case 1:
        return 0;
    }
  }
  j(scope, editorGroupService) {
    const targetGroup = editorGroupService.findGroup(scope, editorGroupService.activeGroup);
    if (targetGroup) {
      targetGroup.focus();
      return true;
    }
    return false;
  }
};
$hJ(class extends BaseNavigationAction {
  constructor() {
    super(
      {
        id: "workbench.action.navigateLeft",
        title: localize2(2973, "Navigate to the View on the Left"),
        category: $qn.View,
        f1: true
      },
      2
      /* Direction.Left */
    );
  }
});
$hJ(class extends BaseNavigationAction {
  constructor() {
    super(
      {
        id: "workbench.action.navigateRight",
        title: localize2(2974, "Navigate to the View on the Right"),
        category: $qn.View,
        f1: true
      },
      3
      /* Direction.Right */
    );
  }
});
$hJ(class extends BaseNavigationAction {
  constructor() {
    super(
      {
        id: "workbench.action.navigateUp",
        title: localize2(2975, "Navigate to the View Above"),
        category: $qn.View,
        f1: true
      },
      0
      /* Direction.Up */
    );
  }
});
$hJ(class extends BaseNavigationAction {
  constructor() {
    super(
      {
        id: "workbench.action.navigateDown",
        title: localize2(2976, "Navigate to the View Below"),
        category: $qn.View,
        f1: true
      },
      1
      /* Direction.Down */
    );
  }
});
var BaseFocusAction = class extends $gJ {
  constructor(options3, a) {
    super(options3);
    this.a = a;
  }
  run(accessor) {
    const layoutService = accessor.get($Vlb);
    const editorService = accessor.get($mJ);
    this.c(layoutService, editorService, this.a);
  }
  b(layoutService, part, next) {
    const activeWindow = $Qj();
    const windowIsAuxiliary = $Z(activeWindow);
    let neighbour;
    if (windowIsAuxiliary) {
      switch (part) {
        case "workbench.parts.editor":
          neighbour = "workbench.parts.statusbar";
          break;
        default:
          neighbour = "workbench.parts.editor";
      }
    } else {
      switch (part) {
        case "workbench.parts.editor":
          neighbour = next ? "workbench.parts.panel" : "workbench.parts.sidebar";
          break;
        case "workbench.parts.panel":
          neighbour = next ? "workbench.parts.auxiliarybar" : "workbench.parts.editor";
          break;
        case "workbench.parts.auxiliarybar":
          neighbour = next ? "workbench.parts.statusbar" : "workbench.parts.panel";
          break;
        case "workbench.parts.statusbar":
          neighbour = next ? "workbench.parts.activitybar" : "workbench.parts.auxiliarybar";
          break;
        case "workbench.parts.activitybar":
          neighbour = next ? "workbench.parts.sidebar" : "workbench.parts.statusbar";
          break;
        case "workbench.parts.sidebar":
          neighbour = next ? "workbench.parts.editor" : "workbench.parts.activitybar";
          break;
        default:
          neighbour = "workbench.parts.editor";
      }
    }
    if (layoutService.isVisible(neighbour, activeWindow) || neighbour === "workbench.parts.editor") {
      return neighbour;
    }
    return this.b(layoutService, neighbour, next);
  }
  c(layoutService, editorService, next) {
    let currentlyFocusedPart;
    if (editorService.activeEditorPane?.hasFocus() || layoutService.hasFocus(
      "workbench.parts.editor"
      /* Parts.EDITOR_PART */
    )) {
      currentlyFocusedPart = "workbench.parts.editor";
    } else if (layoutService.hasFocus(
      "workbench.parts.activitybar"
      /* Parts.ACTIVITYBAR_PART */
    )) {
      currentlyFocusedPart = "workbench.parts.activitybar";
    } else if (layoutService.hasFocus(
      "workbench.parts.statusbar"
      /* Parts.STATUSBAR_PART */
    )) {
      currentlyFocusedPart = "workbench.parts.statusbar";
    } else if (layoutService.hasFocus(
      "workbench.parts.sidebar"
      /* Parts.SIDEBAR_PART */
    )) {
      currentlyFocusedPart = "workbench.parts.sidebar";
    } else if (layoutService.hasFocus(
      "workbench.parts.auxiliarybar"
      /* Parts.AUXILIARYBAR_PART */
    )) {
      currentlyFocusedPart = "workbench.parts.auxiliarybar";
    } else if (layoutService.hasFocus(
      "workbench.parts.panel"
      /* Parts.PANEL_PART */
    )) {
      currentlyFocusedPart = "workbench.parts.panel";
    }
    layoutService.focusPart(currentlyFocusedPart ? this.b(layoutService, currentlyFocusedPart, next) : "workbench.parts.editor", $Qj());
  }
};
$hJ(class extends BaseFocusAction {
  constructor() {
    super({
      id: "workbench.action.focusNextPart",
      title: localize2(2977, "Focus Next Part"),
      category: $qn.View,
      f1: true,
      keybinding: {
        primary: 64,
        weight: 200
        /* KeybindingWeight.WorkbenchContrib */
      }
    }, true);
  }
});
$hJ(class extends BaseFocusAction {
  constructor() {
    super({
      id: "workbench.action.focusPreviousPart",
      title: localize2(2978, "Focus Previous Part"),
      category: $qn.View,
      f1: true,
      keybinding: {
        primary: 1024 | 64,
        weight: 200
        /* KeybindingWeight.WorkbenchContrib */
      }
    }, false);
  }
});

// out-build/vs/workbench/browser/quickaccess.js
var $4yb = "inQuickOpen";
var $5yb = new $nn($4yb, false, localize(3810, null));
var $6yb = $7m.has($4yb);
var $7yb = "inFilesPicker";
var $8yb = $7m.and($6yb, $7m.has($7yb));
function $9yb(id2, next) {
  return (accessor) => {
    const keybindingService = accessor.get($Ty);
    const quickInputService = accessor.get($1M);
    const keys = keybindingService.lookupKeybindings(id2);
    const quickNavigate = { keybindings: keys };
    quickInputService.navigate(!!next, quickNavigate);
  };
}
var $0yb = class $0yb2 extends $3c {
  constructor(c, f) {
    super();
    this.c = c;
    this.f = f;
    this.a = void 0;
    this.b = /* @__PURE__ */ new Set();
  }
  set() {
    if (this.a) {
      return;
    }
    const activeEditorPane = this.c.activeEditorPane;
    if (activeEditorPane) {
      this.a = {
        group: activeEditorPane.group,
        editor: activeEditorPane.input,
        state: $T5(activeEditorPane.getControl())?.saveViewState() ?? void 0
      };
    }
  }
  /**
   * Open a transient editor such that it may be closed when the state is restored.
   * Note that, when the state is restored, if the editor is no longer transient, it will not be closed.
   */
  async openTransientEditor(editor, group2) {
    editor.options = { ...editor.options, transient: true };
    const editorPane = await this.c.openEditor(editor, group2);
    if (editorPane?.input && editorPane.input !== this.a?.editor && editorPane.group.isTransient(editorPane.input)) {
      this.b.add(editorPane.input);
    }
    return editorPane;
  }
  async restore() {
    if (this.a) {
      for (const editor of this.b) {
        if (editor.isDirty()) {
          continue;
        }
        for (const group2 of this.f.groups) {
          if (group2.isTransient(editor)) {
            await group2.closeEditor(editor, { preserveFocus: true });
          }
        }
      }
      await this.a.group.openEditor(this.a.editor, {
        viewState: this.a.state,
        preserveFocus: true
        // important to not close the picker as a result
      });
      this.reset();
    }
  }
  reset() {
    this.a = void 0;
    this.b.clear();
  }
  dispose() {
    super.dispose();
    this.reset();
  }
};
$0yb = __decorate([
  __param(0, $mJ),
  __param(1, $iJ)
], $0yb);

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

// out-build/vs/workbench/browser/actions/windowActions.js
var $$yb = "inRecentFilesPicker";
var BaseOpenRecentAction = class extends $gJ {
  constructor(desc) {
    super(desc);
    this.a = {
      iconClass: ThemeIcon.asClassName($6l.removeClose),
      tooltip: localize(2991, null)
    };
    this.b = {
      iconClass: "dirty-workspace " + ThemeIcon.asClassName($6l.closeDirty),
      tooltip: localize(2992, null),
      alwaysVisible: true
    };
    this.c = {
      ...this.b,
      tooltip: localize(2993, null)
    };
  }
  async run(accessor) {
    const workspacesService = accessor.get($2w);
    const quickInputService = accessor.get($1M);
    const contextService = accessor.get($Zk);
    const labelService = accessor.get($ZI);
    const keybindingService = accessor.get($Ty);
    const modelService = accessor.get($sG);
    const languageService = accessor.get($1E);
    const hostService = accessor.get($S4);
    const dialogService = accessor.get($Yv);
    const recentlyOpened = await workspacesService.getRecentlyOpened();
    const dirtyWorkspacesAndFolders = await workspacesService.getDirtyWorkspaces();
    let hasWorkspaces = false;
    const dirtyFolders = new $Ec();
    const dirtyWorkspaces = new $Ec();
    for (const dirtyWorkspace of dirtyWorkspacesAndFolders) {
      if ($tv(dirtyWorkspace)) {
        dirtyFolders.set(dirtyWorkspace.folderUri, true);
      } else {
        dirtyWorkspaces.set(dirtyWorkspace.workspace.configPath, dirtyWorkspace.workspace);
        hasWorkspaces = true;
      }
    }
    const recentFolders = new $Ec();
    const recentWorkspaces = new $Ec();
    for (const recent of recentlyOpened.workspaces) {
      if ($4w(recent)) {
        recentFolders.set(recent.folderUri, true);
      } else {
        recentWorkspaces.set(recent.workspace.configPath, recent.workspace);
        hasWorkspaces = true;
      }
    }
    const workspacePicks = [];
    for (const recent of recentlyOpened.workspaces) {
      const isDirty = $4w(recent) ? dirtyFolders.has(recent.folderUri) : dirtyWorkspaces.has(recent.workspace.configPath);
      workspacePicks.push(this.e(modelService, languageService, labelService, recent, isDirty));
    }
    for (const dirtyWorkspaceOrFolder of dirtyWorkspacesAndFolders) {
      if ($tv(dirtyWorkspaceOrFolder) && !recentFolders.has(dirtyWorkspaceOrFolder.folderUri)) {
        workspacePicks.push(this.e(modelService, languageService, labelService, dirtyWorkspaceOrFolder, true));
      } else if ($uv(dirtyWorkspaceOrFolder) && !recentWorkspaces.has(dirtyWorkspaceOrFolder.workspace.configPath)) {
        workspacePicks.push(this.e(modelService, languageService, labelService, dirtyWorkspaceOrFolder, true));
      }
    }
    const filePicks = recentlyOpened.files.map((p) => this.e(modelService, languageService, labelService, p, false));
    const firstEntry = recentlyOpened.workspaces[0];
    const autoFocusSecondEntry = firstEntry && contextService.isCurrentWorkspace($3w(firstEntry) ? firstEntry.workspace : firstEntry.folderUri);
    let keyMods;
    const workspaceSeparator = { type: "separator", label: hasWorkspaces ? localize(2994, null) : localize(2995, null) };
    const fileSeparator = { type: "separator", label: localize(2996, null) };
    const picks = [workspaceSeparator, ...workspacePicks, fileSeparator, ...filePicks];
    const pick = await quickInputService.pick(picks, {
      contextKey: $$yb,
      activeItem: [...workspacePicks, ...filePicks][autoFocusSecondEntry ? 1 : 0],
      placeHolder: $m ? localize(2997, null) : localize(2998, null),
      matchOnDescription: true,
      onKeyMods: (mods) => keyMods = mods,
      quickNavigate: this.d() ? { keybindings: keybindingService.lookupKeybindings(this.desc.id) } : void 0,
      hideInput: this.d(),
      onDidTriggerItemButton: async (context) => {
        if (context.button === this.a) {
          await workspacesService.removeRecentlyOpened([context.item.resource]);
          context.removeItem();
        } else if (context.button === this.b || context.button === this.c) {
          const isDirtyWorkspace = context.button === this.c;
          const { confirmed } = await dialogService.confirm({
            title: isDirtyWorkspace ? localize(2999, null) : localize(3e3, null),
            message: isDirtyWorkspace ? localize(3001, null) : localize(3002, null),
            detail: isDirtyWorkspace ? localize(3003, null) : localize(3004, null)
          });
          if (confirmed) {
            hostService.openWindow([context.item.openable], {
              remoteAuthority: context.item.remoteAuthority || null
              // local window if remoteAuthority is not set or can not be deducted from the openable
            });
            quickInputService.cancel();
          }
        }
      }
    });
    if (pick) {
      return hostService.openWindow([pick.openable], {
        forceNewWindow: keyMods?.ctrlCmd,
        forceReuseWindow: keyMods?.alt,
        remoteAuthority: pick.remoteAuthority || null
        // local window if remoteAuthority is not set or can not be deducted from the openable
      });
    }
  }
  e(modelService, languageService, labelService, recent, isDirty) {
    let openable;
    let iconClasses;
    let fullLabel;
    let resource;
    let isWorkspace = false;
    if ($4w(recent)) {
      resource = recent.folderUri;
      iconClasses = $gdb(modelService, languageService, resource, FileKind.FOLDER);
      openable = { folderUri: resource };
      fullLabel = recent.label || labelService.getWorkspaceLabel(resource, {
        verbose: 2
        /* Verbosity.LONG */
      });
    } else if ($3w(recent)) {
      resource = recent.workspace.configPath;
      iconClasses = $gdb(modelService, languageService, resource, FileKind.ROOT_FOLDER);
      openable = { workspaceUri: resource };
      fullLabel = recent.label || labelService.getWorkspaceLabel(recent.workspace, {
        verbose: 2
        /* Verbosity.LONG */
      });
      isWorkspace = true;
    } else {
      resource = recent.fileUri;
      iconClasses = $gdb(modelService, languageService, resource, FileKind.FILE);
      openable = { fileUri: resource };
      fullLabel = recent.label || labelService.getUriLabel(resource);
    }
    const { name, parentPath } = $9t(fullLabel);
    return {
      iconClasses,
      label: name,
      ariaLabel: isDirty ? isWorkspace ? localize(3005, null, name) : localize(3006, null, name) : name,
      description: parentPath,
      buttons: isDirty ? [isWorkspace ? this.c : this.b] : [this.a],
      openable,
      resource,
      remoteAuthority: recent.remoteAuthority
    };
  }
};
var $_yb = class _$_yb extends BaseOpenRecentAction {
  static {
    this.ID = "workbench.action.openRecent";
  }
  constructor() {
    super({
      id: _$_yb.ID,
      title: {
        ...localize2(3013, "Open Recent..."),
        mnemonicTitle: localize(3007, null)
      },
      category: $qn.File,
      f1: true,
      keybinding: {
        weight: 200,
        primary: 2048 | 48,
        mac: {
          primary: 256 | 48
          /* KeyCode.KeyR */
        }
      },
      menu: {
        id: $bJ.MenubarRecentMenu,
        group: "y_more",
        order: 1
      }
    });
  }
  d() {
    return false;
  }
};
var QuickPickRecentAction = class extends BaseOpenRecentAction {
  constructor() {
    super({
      id: "workbench.action.quickOpenRecent",
      title: localize2(3014, "Quick Open Recent..."),
      category: $qn.File,
      f1: false
      // hide quick pickers from command palette to not confuse with the other entry that shows a input field
    });
  }
  d() {
    return true;
  }
};
var ToggleFullScreenAction = class extends $gJ {
  constructor() {
    super({
      id: "workbench.action.toggleFullScreen",
      title: {
        ...localize2(3015, "Toggle Full Screen"),
        mnemonicTitle: localize(3008, null)
      },
      category: $qn.View,
      f1: true,
      keybinding: {
        weight: 200,
        primary: 69,
        mac: {
          primary: 2048 | 256 | 36
          /* KeyCode.KeyF */
        }
      },
      precondition: $xeb.toNegated(),
      toggled: $npb,
      menu: [{
        id: $bJ.MenubarAppearanceMenu,
        group: "1_toggle_view",
        order: 1
      }]
    });
  }
  run(accessor) {
    const hostService = accessor.get($S4);
    return hostService.toggleFullScreen($Qj());
  }
};
var $azb = class _$azb extends $gJ {
  static {
    this.ID = "workbench.action.reloadWindow";
  }
  constructor() {
    super({
      id: _$azb.ID,
      title: localize2(3016, "Reload Window"),
      category: $qn.Developer,
      f1: true,
      keybinding: {
        weight: 200 + 50,
        when: $zeb,
        primary: 2048 | 48
        /* KeyCode.KeyR */
      }
    });
  }
  async run(accessor) {
    const hostService = accessor.get($S4);
    return hostService.reload();
  }
};
var ShowAboutDialogAction = class extends $gJ {
  constructor() {
    super({
      id: "workbench.action.showAboutDialog",
      title: {
        ...localize2(3017, "About"),
        mnemonicTitle: localize(3009, null)
      },
      category: $qn.Help,
      f1: true,
      menu: {
        id: $bJ.MenubarHelpMenu,
        group: "z_about",
        order: 1,
        when: $web.toNegated()
      }
    });
  }
  run(accessor) {
    const dialogService = accessor.get($Yv);
    return dialogService.about();
  }
};
var NewWindowAction = class extends $gJ {
  constructor() {
    super({
      id: "workbench.action.newWindow",
      title: {
        ...localize2(3018, "New Window"),
        mnemonicTitle: localize(3010, null)
      },
      f1: true,
      keybinding: {
        weight: 200,
        primary: $r ? $l ? $$e(
          2048 | 41,
          1024 | 44
          /* KeyCode.KeyN */
        ) : 2048 | 512 | 1024 | 44 : 2048 | 1024 | 44,
        secondary: $r ? [
          2048 | 1024 | 44
          /* KeyCode.KeyN */
        ] : void 0
      },
      menu: {
        id: $bJ.MenubarFileMenu,
        group: "1_new",
        order: 3
      }
    });
  }
  run(accessor) {
    const hostService = accessor.get($S4);
    return hostService.openWindow({ remoteAuthority: null });
  }
};
var BlurAction = class extends $gJ {
  constructor() {
    super({
      id: "workbench.action.blur",
      title: localize2(3019, "Remove keyboard focus from focused element")
    });
  }
  run() {
    const activeElement = $Lj();
    if ($Uj(activeElement)) {
      activeElement.blur();
    }
  }
};
$hJ(NewWindowAction);
$hJ(ToggleFullScreenAction);
$hJ(QuickPickRecentAction);
$hJ($_yb);
$hJ($azb);
$hJ(ShowAboutDialogAction);
$hJ(BlurAction);
var recentFilesPickerContext = $7m.and($6yb, $7m.has($$yb));
var quickPickNavigateNextInRecentFilesPickerId = "workbench.action.quickOpenNavigateNextInRecentFilesPicker";
$0I.registerCommandAndKeybindingRule({
  id: quickPickNavigateNextInRecentFilesPickerId,
  weight: 200 + 50,
  handler: $9yb(quickPickNavigateNextInRecentFilesPickerId, true),
  when: recentFilesPickerContext,
  primary: 2048 | 48,
  mac: {
    primary: 256 | 48
    /* KeyCode.KeyR */
  }
});
var quickPickNavigatePreviousInRecentFilesPicker = "workbench.action.quickOpenNavigatePreviousInRecentFilesPicker";
$0I.registerCommandAndKeybindingRule({
  id: quickPickNavigatePreviousInRecentFilesPicker,
  weight: 200 + 50,
  handler: $9yb(quickPickNavigatePreviousInRecentFilesPicker, false),
  when: recentFilesPickerContext,
  primary: 2048 | 1024 | 48,
  mac: {
    primary: 256 | 1024 | 48
    /* KeyCode.KeyR */
  }
});
$tn.registerCommand("workbench.action.toggleConfirmBeforeClose", (accessor) => {
  const configurationService = accessor.get($kl);
  const setting = configurationService.inspect("window.confirmBeforeClose").userValue;
  return configurationService.updateValue("window.confirmBeforeClose", setting === "never" ? "keyboardOnly" : "never");
});
$dJ.appendMenuItem($bJ.MenubarFileMenu, {
  group: "z_ConfirmClose",
  command: {
    id: "workbench.action.toggleConfirmBeforeClose",
    title: localize(3011, null),
    toggled: $7m.notEquals("config.window.confirmBeforeClose", "never")
  },
  order: 1,
  when: $veb
});
$dJ.appendMenuItem($bJ.MenubarFileMenu, {
  title: localize(3012, null),
  submenu: $bJ.MenubarRecentMenu,
  group: "2_open",
  order: 4
});

// out-build/vs/workbench/browser/actions/quickAccessActions.js
var globalQuickAccessKeybinding = {
  primary: 2048 | 46,
  secondary: [
    2048 | 35
    /* KeyCode.KeyE */
  ],
  mac: { primary: 2048 | 46, secondary: void 0 }
};
$0I.registerCommandAndKeybindingRule({
  id: "workbench.action.closeQuickOpen",
  weight: 200,
  when: $6yb,
  primary: 9,
  secondary: [
    1024 | 9
    /* KeyCode.Escape */
  ],
  handler: (accessor) => {
    const quickInputService = accessor.get($1M);
    return quickInputService.cancel();
  }
});
$0I.registerCommandAndKeybindingRule({
  id: "workbench.action.acceptSelectedQuickOpenItem",
  weight: 200,
  when: $6yb,
  primary: 0,
  handler: (accessor) => {
    const quickInputService = accessor.get($1M);
    return quickInputService.accept();
  }
});
$0I.registerCommandAndKeybindingRule({
  id: "workbench.action.alternativeAcceptSelectedQuickOpenItem",
  weight: 200,
  when: $6yb,
  primary: 0,
  handler: (accessor) => {
    const quickInputService = accessor.get($1M);
    return quickInputService.accept({ ctrlCmd: true, alt: false });
  }
});
$0I.registerCommandAndKeybindingRule({
  id: "workbench.action.focusQuickOpen",
  weight: 200,
  when: $6yb,
  primary: 0,
  handler: (accessor) => {
    const quickInputService = accessor.get($1M);
    quickInputService.focus();
  }
});
var quickAccessNavigateNextInFilePickerId = "workbench.action.quickOpenNavigateNextInFilePicker";
$0I.registerCommandAndKeybindingRule({
  id: quickAccessNavigateNextInFilePickerId,
  weight: 200 + 50,
  handler: $9yb(quickAccessNavigateNextInFilePickerId, true),
  when: $8yb,
  primary: globalQuickAccessKeybinding.primary,
  secondary: globalQuickAccessKeybinding.secondary,
  mac: globalQuickAccessKeybinding.mac
});
var quickAccessNavigatePreviousInFilePickerId = "workbench.action.quickOpenNavigatePreviousInFilePicker";
$0I.registerCommandAndKeybindingRule({
  id: quickAccessNavigatePreviousInFilePickerId,
  weight: 200 + 50,
  handler: $9yb(quickAccessNavigatePreviousInFilePickerId, false),
  when: $8yb,
  primary: globalQuickAccessKeybinding.primary | 1024,
  secondary: [
    globalQuickAccessKeybinding.secondary[0] | 1024
    /* KeyMod.Shift */
  ],
  mac: {
    primary: globalQuickAccessKeybinding.mac.primary | 1024,
    secondary: void 0
  }
});
$0I.registerCommandAndKeybindingRule({
  id: "workbench.action.quickPickManyToggle",
  weight: 200,
  when: $6yb,
  primary: 0,
  handler: (accessor) => {
    const quickInputService = accessor.get($1M);
    quickInputService.toggle();
  }
});
$0I.registerCommandAndKeybindingRule({
  id: "workbench.action.quickInputBack",
  weight: 200 + 50,
  when: $6yb,
  primary: 0,
  win: {
    primary: 512 | 15
    /* KeyCode.LeftArrow */
  },
  mac: {
    primary: 256 | 88
    /* KeyCode.Minus */
  },
  linux: {
    primary: 2048 | 512 | 88
    /* KeyCode.Minus */
  },
  handler: (accessor) => {
    const quickInputService = accessor.get($1M);
    quickInputService.back();
  }
});
$hJ(class QuickAccessAction extends $gJ {
  constructor() {
    super({
      id: "workbench.action.quickOpen",
      title: localize2(2980, "Go to File..."),
      metadata: {
        description: `Quick access`,
        args: [{
          name: "prefix",
          schema: {
            "type": "string"
          }
        }]
      },
      keybinding: {
        weight: 200,
        primary: globalQuickAccessKeybinding.primary,
        secondary: globalQuickAccessKeybinding.secondary,
        mac: globalQuickAccessKeybinding.mac
      },
      f1: true
    });
  }
  run(accessor, prefix) {
    const quickInputService = accessor.get($1M);
    quickInputService.quickAccess.show(typeof prefix === "string" ? prefix : void 0, {
      preserveValue: typeof prefix === "string"
      /* preserve as is if provided */
    });
  }
});
$hJ(class QuickAccessAction2 extends $gJ {
  constructor() {
    super({
      id: "workbench.action.quickOpenWithModes",
      title: localize(2979, null),
      icon: $6l.search,
      menu: {
        id: $bJ.CommandCenterCenter,
        order: 100
      }
    });
  }
  run(accessor) {
    const quickInputService = accessor.get($1M);
    const providerOptions = {
      includeHelp: true,
      from: "commandCenter"
    };
    quickInputService.quickAccess.show(void 0, {
      preserveValue: true,
      providerOptions
    });
  }
});
$tn.registerCommand("workbench.action.quickOpenPreviousEditor", async (accessor) => {
  const quickInputService = accessor.get($1M);
  quickInputService.quickAccess.show("", { itemActivation: ItemActivation.SECOND });
});
var BaseQuickAccessNavigateAction = class extends $gJ {
  constructor(a, title, b, c, keybinding) {
    super({ id: a, title, f1: true, keybinding });
    this.a = a;
    this.b = b;
    this.c = c;
  }
  async run(accessor) {
    const keybindingService = accessor.get($Ty);
    const quickInputService = accessor.get($1M);
    const keys = keybindingService.lookupKeybindings(this.a);
    const quickNavigate = this.c ? { keybindings: keys } : void 0;
    quickInputService.navigate(this.b, quickNavigate);
  }
};
var QuickAccessNavigateNextAction = class extends BaseQuickAccessNavigateAction {
  constructor() {
    super("workbench.action.quickOpenNavigateNext", localize2(2981, "Navigate Next in Quick Open"), true, true);
  }
};
var QuickAccessNavigatePreviousAction = class extends BaseQuickAccessNavigateAction {
  constructor() {
    super("workbench.action.quickOpenNavigatePrevious", localize2(2982, "Navigate Previous in Quick Open"), false, true);
  }
};
var QuickAccessSelectNextAction = class extends BaseQuickAccessNavigateAction {
  constructor() {
    super("workbench.action.quickOpenSelectNext", localize2(2983, "Select Next in Quick Open"), true, false, {
      weight: 200 + 50,
      when: $6yb,
      primary: 0,
      mac: {
        primary: 256 | 44
        /* KeyCode.KeyN */
      }
    });
  }
};
var QuickAccessSelectPreviousAction = class extends BaseQuickAccessNavigateAction {
  constructor() {
    super("workbench.action.quickOpenSelectPrevious", localize2(2984, "Select Previous in Quick Open"), false, false, {
      weight: 200 + 50,
      when: $6yb,
      primary: 0,
      mac: {
        primary: 256 | 46
        /* KeyCode.KeyP */
      }
    });
  }
};
$hJ(QuickAccessSelectNextAction);
$hJ(QuickAccessSelectPreviousAction);
$hJ(QuickAccessNavigateNextAction);
$hJ(QuickAccessNavigatePreviousAction);

// out-build/vs/workbench/services/actions/common/menusExtensionPoint.js
var apiMenus = [
  {
    key: "commandPalette",
    id: $bJ.CommandPalette,
    description: localize(12405, null),
    supportsSubmenus: false
  },
  {
    key: "touchBar",
    id: $bJ.TouchBarContext,
    description: localize(12406, null),
    supportsSubmenus: false
  },
  {
    key: "editor/title",
    id: $bJ.EditorTitle,
    description: localize(12407, null)
  },
  {
    key: "editor/title/run",
    id: $bJ.EditorTitleRun,
    description: localize(12408, null)
  },
  {
    key: "editor/context",
    id: $bJ.EditorContext,
    description: localize(12409, null)
  },
  {
    key: "editor/context/copy",
    id: $bJ.EditorContextCopy,
    description: localize(12410, null)
  },
  {
    key: "editor/context/share",
    id: $bJ.EditorContextShare,
    description: localize(12411, null),
    proposed: "contribShareMenu"
  },
  {
    key: "explorer/context",
    id: $bJ.ExplorerContext,
    description: localize(12412, null)
  },
  {
    key: "explorer/context/share",
    id: $bJ.ExplorerContextShare,
    description: localize(12413, null),
    proposed: "contribShareMenu"
  },
  {
    key: "editor/title/context",
    id: $bJ.EditorTitleContext,
    description: localize(12414, null)
  },
  {
    key: "editor/title/context/share",
    id: $bJ.EditorTitleContextShare,
    description: localize(12415, null),
    proposed: "contribShareMenu"
  },
  {
    key: "debug/callstack/context",
    id: $bJ.DebugCallStackContext,
    description: localize(12416, null)
  },
  {
    key: "debug/variables/context",
    id: $bJ.DebugVariablesContext,
    description: localize(12417, null)
  },
  {
    key: "debug/toolBar",
    id: $bJ.DebugToolBar,
    description: localize(12418, null)
  },
  {
    key: "debug/createConfiguration",
    id: $bJ.DebugCreateConfiguration,
    proposed: "contribDebugCreateConfiguration",
    description: localize(12419, null)
  },
  {
    key: "notebook/variables/context",
    id: $bJ.NotebookVariablesContext,
    description: localize(12420, null)
  },
  {
    key: "menuBar/home",
    id: $bJ.MenubarHomeMenu,
    description: localize(12421, null),
    proposed: "contribMenuBarHome",
    supportsSubmenus: false
  },
  {
    key: "menuBar/edit/copy",
    id: $bJ.MenubarCopy,
    description: localize(12422, null)
  },
  {
    key: "scm/title",
    id: $bJ.SCMTitle,
    description: localize(12423, null)
  },
  {
    key: "scm/sourceControl",
    id: $bJ.SCMSourceControl,
    description: localize(12424, null)
  },
  {
    key: "scm/sourceControl/title",
    id: $bJ.SCMSourceControlTitle,
    description: localize(12425, null),
    proposed: "contribSourceControlTitleMenu"
  },
  {
    key: "scm/resourceState/context",
    id: $bJ.SCMResourceContext,
    description: localize(12426, null)
  },
  {
    key: "scm/resourceFolder/context",
    id: $bJ.SCMResourceFolderContext,
    description: localize(12427, null)
  },
  {
    key: "scm/resourceGroup/context",
    id: $bJ.SCMResourceGroupContext,
    description: localize(12428, null)
  },
  {
    key: "scm/change/title",
    id: $bJ.SCMChangeContext,
    description: localize(12429, null)
  },
  {
    key: "scm/inputBox",
    id: $bJ.SCMInputBox,
    description: localize(12430, null),
    proposed: "contribSourceControlInputBoxMenu"
  },
  {
    key: "scm/history/title",
    id: $bJ.SCMHistoryTitle,
    description: localize(12431, null),
    proposed: "contribSourceControlHistoryTitleMenu"
  },
  {
    key: "scm/historyItem/context",
    id: $bJ.SCMChangesContext,
    description: localize(12432, null),
    proposed: "contribSourceControlHistoryItemMenu"
  },
  {
    key: "scm/historyItemRef/context",
    id: $bJ.SCMHistoryItemRefContext,
    description: localize(12433, null),
    proposed: "contribSourceControlHistoryItemMenu"
  },
  {
    key: "statusBar/remoteIndicator",
    id: $bJ.StatusBarRemoteIndicatorMenu,
    description: localize(12434, null),
    supportsSubmenus: false
  },
  {
    key: "terminal/context",
    id: $bJ.TerminalInstanceContext,
    description: localize(12435, null)
  },
  {
    key: "terminal/title/context",
    id: $bJ.TerminalTabContext,
    description: localize(12436, null)
  },
  {
    key: "view/title",
    id: $bJ.ViewTitle,
    description: localize(12437, null)
  },
  {
    key: "viewContainer/title",
    id: $bJ.ViewContainerTitle,
    description: localize(12438, null),
    proposed: "contribViewContainerTitle"
  },
  {
    key: "view/item/context",
    id: $bJ.ViewItemContext,
    description: localize(12439, null)
  },
  {
    key: "comments/comment/editorActions",
    id: $bJ.CommentEditorActions,
    description: localize(12440, null),
    proposed: "contribCommentEditorActionsMenu"
  },
  {
    key: "comments/commentThread/title",
    id: $bJ.CommentThreadTitle,
    description: localize(12441, null)
  },
  {
    key: "comments/commentThread/context",
    id: $bJ.CommentThreadActions,
    description: localize(12442, null),
    supportsSubmenus: false
  },
  {
    key: "comments/commentThread/additionalActions",
    id: $bJ.CommentThreadAdditionalActions,
    description: localize(12443, null),
    supportsSubmenus: true,
    proposed: "contribCommentThreadAdditionalMenu"
  },
  {
    key: "comments/commentThread/title/context",
    id: $bJ.CommentThreadTitleContext,
    description: localize(12444, null),
    proposed: "contribCommentPeekContext"
  },
  {
    key: "comments/comment/title",
    id: $bJ.CommentTitle,
    description: localize(12445, null)
  },
  {
    key: "comments/comment/context",
    id: $bJ.CommentActions,
    description: localize(12446, null),
    supportsSubmenus: false
  },
  {
    key: "comments/commentThread/comment/context",
    id: $bJ.CommentThreadCommentContext,
    description: localize(12447, null),
    proposed: "contribCommentPeekContext"
  },
  {
    key: "commentsView/commentThread/context",
    id: $bJ.CommentsViewThreadActions,
    description: localize(12448, null),
    proposed: "contribCommentsViewThreadMenus"
  },
  {
    key: "notebook/toolbar",
    id: $bJ.NotebookToolbar,
    description: localize(12449, null)
  },
  {
    key: "notebook/kernelSource",
    id: $bJ.NotebookKernelSource,
    description: localize(12450, null),
    proposed: "notebookKernelSource"
  },
  {
    key: "notebook/cell/title",
    id: $bJ.NotebookCellTitle,
    description: localize(12451, null)
  },
  {
    key: "notebook/cell/execute",
    id: $bJ.NotebookCellExecute,
    description: localize(12452, null)
  },
  {
    key: "interactive/toolbar",
    id: $bJ.InteractiveToolbar,
    description: localize(12453, null)
  },
  {
    key: "interactive/cell/title",
    id: $bJ.InteractiveCellTitle,
    description: localize(12454, null)
  },
  {
    key: "issue/reporter",
    id: $bJ.IssueReporter,
    description: localize(12455, null)
  },
  {
    key: "testing/item/context",
    id: $bJ.TestItem,
    description: localize(12456, null)
  },
  {
    key: "testing/item/gutter",
    id: $bJ.TestItemGutter,
    description: localize(12457, null)
  },
  {
    key: "testing/profiles/context",
    id: $bJ.TestProfilesContext,
    description: localize(12458, null)
  },
  {
    key: "testing/item/result",
    id: $bJ.TestPeekElement,
    description: localize(12459, null)
  },
  {
    key: "testing/message/context",
    id: $bJ.TestMessageContext,
    description: localize(12460, null)
  },
  {
    key: "testing/message/content",
    id: $bJ.TestMessageContent,
    description: localize(12461, null)
  },
  {
    key: "extension/context",
    id: $bJ.ExtensionContext,
    description: localize(12462, null)
  },
  {
    key: "timeline/title",
    id: $bJ.TimelineTitle,
    description: localize(12463, null)
  },
  {
    key: "timeline/item/context",
    id: $bJ.TimelineItemContext,
    description: localize(12464, null)
  },
  {
    key: "ports/item/context",
    id: $bJ.TunnelContext,
    description: localize(12465, null)
  },
  {
    key: "ports/item/origin/inline",
    id: $bJ.TunnelOriginInline,
    description: localize(12466, null)
  },
  {
    key: "ports/item/port/inline",
    id: $bJ.TunnelPortInline,
    description: localize(12467, null)
  },
  {
    key: "file/newFile",
    id: $bJ.NewFile,
    description: localize(12468, null),
    supportsSubmenus: false
  },
  {
    key: "webview/context",
    id: $bJ.WebviewContext,
    description: localize(12469, null)
  },
  {
    key: "file/share",
    id: $bJ.MenubarShare,
    description: localize(12470, null),
    proposed: "contribShareMenu"
  },
  {
    key: "editor/inlineCompletions/actions",
    id: $bJ.InlineCompletionsActions,
    description: localize(12471, null),
    supportsSubmenus: false,
    proposed: "inlineCompletionsAdditions"
  },
  {
    key: "editor/content",
    id: $bJ.EditorContent,
    description: localize(12472, null),
    proposed: "contribEditorContentMenu"
  },
  {
    key: "editor/lineNumber/context",
    id: $bJ.EditorLineNumberContext,
    description: localize(12473, null)
  },
  {
    key: "mergeEditor/result/title",
    id: $bJ.MergeInputResultToolbar,
    description: localize(12474, null),
    proposed: "contribMergeEditorMenus"
  },
  {
    key: "multiDiffEditor/resource/title",
    id: $bJ.MultiDiffEditorFileToolbar,
    description: localize(12475, null),
    proposed: "contribMultiDiffEditorMenus"
  },
  {
    key: "diffEditor/gutter/hunk",
    id: $bJ.DiffEditorHunkToolbar,
    description: localize(12476, null),
    proposed: "contribDiffEditorGutterToolBarMenus"
  },
  {
    key: "diffEditor/gutter/selection",
    id: $bJ.DiffEditorSelectionToolbar,
    description: localize(12477, null),
    proposed: "contribDiffEditorGutterToolBarMenus"
  }
];
var schema3;
(function(schema9) {
  function isMenuItem(item) {
    return typeof item.command === "string";
  }
  schema9.isMenuItem = isMenuItem;
  function isValidMenuItem(item, collector) {
    if (typeof item.command !== "string") {
      collector.error(localize(12478, null, "command"));
      return false;
    }
    if (item.alt && typeof item.alt !== "string") {
      collector.error(localize(12479, null, "alt"));
      return false;
    }
    if (item.when && typeof item.when !== "string") {
      collector.error(localize(12480, null, "when"));
      return false;
    }
    if (item.group && typeof item.group !== "string") {
      collector.error(localize(12481, null, "group"));
      return false;
    }
    return true;
  }
  schema9.isValidMenuItem = isValidMenuItem;
  function isValidSubmenuItem(item, collector) {
    if (typeof item.submenu !== "string") {
      collector.error(localize(12482, null, "submenu"));
      return false;
    }
    if (item.when && typeof item.when !== "string") {
      collector.error(localize(12483, null, "when"));
      return false;
    }
    if (item.group && typeof item.group !== "string") {
      collector.error(localize(12484, null, "group"));
      return false;
    }
    return true;
  }
  schema9.isValidSubmenuItem = isValidSubmenuItem;
  function isValidItems(items, collector) {
    if (!Array.isArray(items)) {
      collector.error(localize(12485, null));
      return false;
    }
    for (const item of items) {
      if (isMenuItem(item)) {
        if (!isValidMenuItem(item, collector)) {
          return false;
        }
      } else {
        if (!isValidSubmenuItem(item, collector)) {
          return false;
        }
      }
    }
    return true;
  }
  schema9.isValidItems = isValidItems;
  function isValidSubmenu(submenu2, collector) {
    if (typeof submenu2 !== "object") {
      collector.error(localize(12486, null));
      return false;
    }
    if (typeof submenu2.id !== "string") {
      collector.error(localize(12487, null, "id"));
      return false;
    }
    if (typeof submenu2.label !== "string") {
      collector.error(localize(12488, null, "label"));
      return false;
    }
    return true;
  }
  schema9.isValidSubmenu = isValidSubmenu;
  const menuItem = {
    type: "object",
    required: ["command"],
    properties: {
      command: {
        description: localize(12489, null),
        type: "string"
      },
      alt: {
        description: localize(12490, null),
        type: "string"
      },
      when: {
        description: localize(12491, null),
        type: "string"
      },
      group: {
        description: localize(12492, null),
        type: "string"
      }
    }
  };
  const submenuItem = {
    type: "object",
    required: ["submenu"],
    properties: {
      submenu: {
        description: localize(12493, null),
        type: "string"
      },
      when: {
        description: localize(12494, null),
        type: "string"
      },
      group: {
        description: localize(12495, null),
        type: "string"
      }
    }
  };
  const submenu = {
    type: "object",
    required: ["id", "label"],
    properties: {
      id: {
        description: localize(12496, null),
        type: "string"
      },
      label: {
        description: localize(12497, null),
        type: "string"
      },
      icon: {
        description: localize(12498, null),
        anyOf: [
          {
            type: "string"
          },
          {
            type: "object",
            properties: {
              light: {
                description: localize(12499, null),
                type: "string"
              },
              dark: {
                description: localize(12500, null),
                type: "string"
              }
            }
          }
        ]
      }
    }
  };
  schema9.menusContribution = {
    description: localize(12501, null),
    type: "object",
    properties: $Vb(apiMenus, (menu) => menu.key, (menu) => ({
      markdownDescription: menu.proposed ? localize(12502, null, menu.proposed, menu.description) : menu.description,
      type: "array",
      items: menu.supportsSubmenus === false ? menuItem : { oneOf: [menuItem, submenuItem] }
    })),
    additionalProperties: {
      description: "Submenu",
      type: "array",
      items: { oneOf: [menuItem, submenuItem] }
    }
  };
  schema9.submenusContribution = {
    description: localize(12503, null),
    type: "array",
    items: submenu
  };
  function isValidCommand(command4, collector) {
    if (!command4) {
      collector.error(localize(12504, null));
      return false;
    }
    if ($vf(command4.command)) {
      collector.error(localize(12505, null, "command"));
      return false;
    }
    if (!isValidLocalizedString(command4.title, collector, "title")) {
      return false;
    }
    if (command4.shortTitle && !isValidLocalizedString(command4.shortTitle, collector, "shortTitle")) {
      return false;
    }
    if (command4.enablement && typeof command4.enablement !== "string") {
      collector.error(localize(12506, null, "precondition"));
      return false;
    }
    if (command4.category && !isValidLocalizedString(command4.category, collector, "category")) {
      return false;
    }
    if (!isValidIcon(command4.icon, collector)) {
      return false;
    }
    return true;
  }
  schema9.isValidCommand = isValidCommand;
  function isValidIcon(icon2, collector) {
    if (typeof icon2 === "undefined") {
      return true;
    }
    if (typeof icon2 === "string") {
      return true;
    } else if (typeof icon2.dark === "string" && typeof icon2.light === "string") {
      return true;
    }
    collector.error(localize(12507, null));
    return false;
  }
  function isValidLocalizedString(localized, collector, propertyName) {
    if (typeof localized === "undefined") {
      collector.error(localize(12508, null, propertyName));
      return false;
    } else if (typeof localized === "string" && $vf(localized)) {
      collector.error(localize(12509, null, propertyName));
      return false;
    } else if (typeof localized !== "string" && ($vf(localized.original) || $vf(localized.value))) {
      collector.error(localize(12510, null, `${propertyName}.value`, `${propertyName}.original`));
      return false;
    }
    return true;
  }
  const commandType = {
    type: "object",
    required: ["command", "title"],
    properties: {
      command: {
        description: localize(12511, null),
        type: "string"
      },
      title: {
        description: localize(12512, null),
        type: "string"
      },
      shortTitle: {
        markdownDescription: localize(12513, null),
        type: "string"
      },
      category: {
        description: localize(12514, null),
        type: "string"
      },
      enablement: {
        description: localize(12515, null),
        type: "string"
      },
      icon: {
        description: localize(12516, null),
        anyOf: [
          {
            type: "string"
          },
          {
            type: "object",
            properties: {
              light: {
                description: localize(12517, null),
                type: "string"
              },
              dark: {
                description: localize(12518, null),
                type: "string"
              }
            }
          }
        ]
      }
    }
  };
  schema9.commandsContribution = {
    description: localize(12519, null),
    oneOf: [
      commandType,
      {
        type: "array",
        items: commandType
      }
    ]
  };
})(schema3 || (schema3 = {}));
var _commandRegistrations = new $2c();
var $dUb = $tN.registerExtensionPoint({
  extensionPoint: "commands",
  jsonSchema: schema3.commandsContribution,
  activationEventsGenerator: (contribs, result) => {
    for (const contrib of contribs) {
      if (contrib.command) {
        result.push(`onCommand:${contrib.command}`);
      }
    }
  }
});
$dUb.setHandler((extensions) => {
  function handleCommand(userFriendlyCommand, extension) {
    if (!schema3.isValidCommand(userFriendlyCommand, extension.collector)) {
      return;
    }
    const { icon: icon2, enablement, category: category8, title, shortTitle, command: command4 } = userFriendlyCommand;
    let absoluteIcon;
    if (icon2) {
      if (typeof icon2 === "string") {
        absoluteIcon = ThemeIcon.fromString(icon2) ?? { dark: $vh(extension.description.extensionLocation, icon2), light: $vh(extension.description.extensionLocation, icon2) };
      } else {
        absoluteIcon = {
          dark: $vh(extension.description.extensionLocation, icon2.dark),
          light: $vh(extension.description.extensionLocation, icon2.light)
        };
      }
    }
    const existingCmd = $dJ.getCommand(command4);
    if (existingCmd) {
      if (existingCmd.source) {
        extension.collector.info(localize(12520, null, userFriendlyCommand.command, existingCmd.source.title, existingCmd.source.id));
      } else {
        extension.collector.info(localize(12521, null, userFriendlyCommand.command));
      }
    }
    _commandRegistrations.add($dJ.addCommand({
      id: command4,
      title,
      source: { id: extension.description.identifier.value, title: extension.description.displayName ?? extension.description.name },
      shortTitle,
      tooltip: title,
      category: category8,
      precondition: $7m.deserialize(enablement),
      icon: absoluteIcon
    }));
  }
  _commandRegistrations.clear();
  for (const extension of extensions) {
    const { value } = extension;
    if (Array.isArray(value)) {
      for (const command4 of value) {
        handleCommand(command4, extension);
      }
    } else {
      handleCommand(value, extension);
    }
  }
});
var _submenus = /* @__PURE__ */ new Map();
var submenusExtensionPoint = $tN.registerExtensionPoint({
  extensionPoint: "submenus",
  jsonSchema: schema3.submenusContribution
});
submenusExtensionPoint.setHandler((extensions) => {
  _submenus.clear();
  for (const extension of extensions) {
    const { value, collector } = extension;
    for (const [, submenuInfo] of Object.entries(value)) {
      if (!schema3.isValidSubmenu(submenuInfo, collector)) {
        continue;
      }
      if (!submenuInfo.id) {
        collector.warn(localize(12522, null, submenuInfo.id));
        continue;
      }
      if (_submenus.has(submenuInfo.id)) {
        collector.info(localize(12523, null, submenuInfo.id));
        continue;
      }
      if (!submenuInfo.label) {
        collector.warn(localize(12524, null, submenuInfo.label));
        continue;
      }
      let absoluteIcon;
      if (submenuInfo.icon) {
        if (typeof submenuInfo.icon === "string") {
          absoluteIcon = ThemeIcon.fromString(submenuInfo.icon) || { dark: $vh(extension.description.extensionLocation, submenuInfo.icon) };
        } else {
          absoluteIcon = {
            dark: $vh(extension.description.extensionLocation, submenuInfo.icon.dark),
            light: $vh(extension.description.extensionLocation, submenuInfo.icon.light)
          };
        }
      }
      const item = {
        id: $bJ.for(`api:${submenuInfo.id}`),
        label: submenuInfo.label,
        icon: absoluteIcon
      };
      _submenus.set(submenuInfo.id, item);
    }
  }
});
var _apiMenusByKey = new Map(apiMenus.map((menu) => [menu.key, menu]));
var _menuRegistrations = new $2c();
var _submenuMenuItems = /* @__PURE__ */ new Map();
var menusExtensionPoint = $tN.registerExtensionPoint({
  extensionPoint: "menus",
  jsonSchema: schema3.menusContribution,
  deps: [submenusExtensionPoint]
});
menusExtensionPoint.setHandler((extensions) => {
  _menuRegistrations.clear();
  _submenuMenuItems.clear();
  for (const extension of extensions) {
    const { value, collector } = extension;
    for (const entry of Object.entries(value)) {
      if (!schema3.isValidItems(entry[1], collector)) {
        continue;
      }
      let menu = _apiMenusByKey.get(entry[0]);
      if (!menu) {
        const submenu = _submenus.get(entry[0]);
        if (submenu) {
          menu = {
            key: entry[0],
            id: submenu.id,
            description: ""
          };
        }
      }
      if (!menu) {
        continue;
      }
      if (menu.proposed && !$zN(extension.description, menu.proposed)) {
        collector.error(localize(12525, null, entry[0], menu.proposed, extension.description.identifier.value));
        continue;
      }
      for (const menuItem of entry[1]) {
        let item;
        if (schema3.isMenuItem(menuItem)) {
          const command4 = $dJ.getCommand(menuItem.command);
          const alt = menuItem.alt && $dJ.getCommand(menuItem.alt) || void 0;
          if (!command4) {
            collector.error(localize(12526, null, menuItem.command));
            continue;
          }
          if (menuItem.alt && !alt) {
            collector.warn(localize(12527, null, menuItem.alt));
          }
          if (menuItem.command === menuItem.alt) {
            collector.info(localize(12528, null));
          }
          item = { command: command4, alt, group: void 0, order: void 0, when: void 0 };
        } else {
          if (menu.supportsSubmenus === false) {
            collector.error(localize(12529, null));
            continue;
          }
          const submenu = _submenus.get(menuItem.submenu);
          if (!submenu) {
            collector.error(localize(12530, null, menuItem.submenu));
            continue;
          }
          let submenuRegistrations = _submenuMenuItems.get(menu.id.id);
          if (!submenuRegistrations) {
            submenuRegistrations = /* @__PURE__ */ new Set();
            _submenuMenuItems.set(menu.id.id, submenuRegistrations);
          }
          if (submenuRegistrations.has(submenu.id.id)) {
            collector.warn(localize(12531, null, menuItem.submenu, entry[0]));
            continue;
          }
          submenuRegistrations.add(submenu.id.id);
          item = { submenu: submenu.id, icon: submenu.icon, title: submenu.label, group: void 0, order: void 0, when: void 0 };
        }
        if (menuItem.group) {
          const idx = menuItem.group.lastIndexOf("@");
          if (idx > 0) {
            item.group = menuItem.group.substr(0, idx);
            item.order = Number(menuItem.group.substr(idx + 1)) || void 0;
          } else {
            item.group = menuItem.group;
          }
        }
        if (menu.id === $bJ.ViewContainerTitle && !menuItem.when?.includes("viewContainer == workbench.view.debug")) {
          collector.error(localize(12532, null, "`viewContainer/title`", "`viewContainer == workbench.view.debug`", '"when"'));
          continue;
        }
        item.when = $7m.deserialize(menuItem.when);
        _menuRegistrations.add($dJ.appendMenuItem(menu.id, item));
      }
    }
  }
});
var CommandsTableRenderer = class CommandsTableRenderer2 extends $3c {
  constructor(f) {
    super();
    this.f = f;
    this.type = "table";
  }
  shouldRender(manifest) {
    return !!manifest.contributes?.commands;
  }
  render(manifest) {
    const rawCommands = manifest.contributes?.commands || [];
    const commands2 = rawCommands.map((c) => ({
      id: c.command,
      title: c.title,
      keybindings: [],
      menus: []
    }));
    const byId = $Vb(commands2, (c) => c.id);
    const menus = manifest.contributes?.menus || {};
    const implicitlyOnCommandPalette = $Vb(commands2, (c) => c.id);
    if (menus["commandPalette"]) {
      for (const command4 of menus["commandPalette"]) {
        delete implicitlyOnCommandPalette[command4.command];
      }
    }
    if (Object.keys(implicitlyOnCommandPalette).length) {
      if (!menus["commandPalette"]) {
        menus["commandPalette"] = [];
      }
      for (const command4 in implicitlyOnCommandPalette) {
        menus["commandPalette"].push({ command: command4 });
      }
    }
    for (const context in menus) {
      for (const menu of menus[context]) {
        if (menu.when === "false") {
          continue;
        }
        if (menu.command) {
          let command4 = byId[menu.command];
          if (command4) {
            if (!command4.menus.includes(context)) {
              command4.menus.push(context);
            }
          } else {
            command4 = { id: menu.command, title: "", keybindings: [], menus: [context] };
            byId[command4.id] = command4;
            commands2.push(command4);
          }
        }
      }
    }
    const rawKeybindings = manifest.contributes?.keybindings ? Array.isArray(manifest.contributes.keybindings) ? manifest.contributes.keybindings : [manifest.contributes.keybindings] : [];
    rawKeybindings.forEach((rawKeybinding) => {
      const keybinding = this.g(rawKeybinding);
      if (!keybinding) {
        return;
      }
      let command4 = byId[rawKeybinding.command];
      if (command4) {
        command4.keybindings.push(keybinding);
      } else {
        command4 = { id: rawKeybinding.command, title: "", keybindings: [keybinding], menus: [] };
        byId[command4.id] = command4;
        commands2.push(command4);
      }
    });
    if (!commands2.length) {
      return { data: { headers: [], rows: [] }, dispose: () => {
      } };
    }
    const headers = [
      localize(12533, null),
      localize(12534, null),
      localize(12535, null),
      localize(12536, null)
    ];
    const rows = commands2.sort((a, b) => a.id.localeCompare(b.id)).map((command4) => {
      return [
        new $bm().appendMarkdown(`\`${command4.id}\``),
        typeof command4.title === "string" ? command4.title : command4.title.value,
        command4.keybindings,
        new $bm().appendMarkdown(`${command4.menus.sort((a, b) => a.localeCompare(b)).map((menu) => `\`${menu}\``).join("&nbsp;")}`)
      ];
    });
    return {
      data: {
        headers,
        rows
      },
      dispose: () => {
      }
    };
  }
  g(rawKeyBinding) {
    let key2;
    switch ($hc) {
      case "win32":
        key2 = rawKeyBinding.win;
        break;
      case "linux":
        key2 = rawKeyBinding.linux;
        break;
      case "darwin":
        key2 = rawKeyBinding.mac;
        break;
    }
    return this.f.resolveUserBinding(key2 ?? rawKeyBinding.key)[0];
  }
};
CommandsTableRenderer = __decorate([
  __param(0, $Ty)
], CommandsTableRenderer);
$Wn.as(Extensions3.ExtensionFeaturesRegistry).registerExtensionFeature({
  id: "commands",
  label: localize(12537, null),
  access: {
    canToggle: false
  },
  renderer: new $Nk(CommandsTableRenderer)
});

// out-build/vs/workbench/services/configuration/common/configuration.js
var $iK = ".vscode";
var $jK = "settings";
var $kK = `${$iK}/${$jK}.json`;
var $lK = "vscode://schemas/settings/default";
var $mK = "vscode://schemas/settings/user";
var $nK = "vscode://schemas/settings/profile";
var $oK = "vscode://schemas/settings/machine";
var $pK = "vscode://schemas/settings/workspace";
var $qK = "vscode://schemas/settings/folder";
var $rK = "vscode://schemas/launch";
var $sK = "vscode://schemas/tasks";
var $tK = [
  1
  /* ConfigurationScope.APPLICATION */
];
var $uK = [
  2,
  3,
  4,
  5,
  6
  /* ConfigurationScope.MACHINE_OVERRIDABLE */
];
var $vK = [
  3,
  4,
  5
  /* ConfigurationScope.LANGUAGE_OVERRIDABLE */
];
var $wK = [1, ...$vK];
var $xK = [
  2,
  3,
  4,
  5,
  6
  /* ConfigurationScope.MACHINE_OVERRIDABLE */
];
var $yK = [
  3,
  4,
  5,
  6
  /* ConfigurationScope.MACHINE_OVERRIDABLE */
];
var $zK = [
  4,
  5,
  6
  /* ConfigurationScope.MACHINE_OVERRIDABLE */
];
var $AK = "tasks";
var $BK = "launch";
var $CK = /* @__PURE__ */ Object.create(null);
$CK[$AK] = `${$iK}/${$AK}.json`;
$CK[$BK] = `${$iK}/${$BK}.json`;
var $DK = /* @__PURE__ */ Object.create(null);
$DK[$AK] = `${$AK}.json`;
var $EK = $Rk($kl);
var $FK = '{\n	"version": "2.0.0",\n	"tasks": []\n}';
var $GK = "workbench.settings.applyToAllProfiles";

// out-build/vs/workbench/api/common/configurationExtensionPoint.js
var jsonRegistry = $Wn.as($Xn.JSONContribution);
var configurationRegistry6 = $Wn.as($Ht.Configuration);
var configurationEntrySchema = {
  type: "object",
  defaultSnippets: [{ body: { title: "", properties: {} } }],
  properties: {
    title: {
      description: localize(2707, null),
      type: "string"
    },
    order: {
      description: localize(2708, null),
      type: "integer"
    },
    properties: {
      description: localize(2709, null),
      type: "object",
      propertyNames: {
        pattern: "\\S+",
        patternErrorMessage: localize(2710, null)
      },
      additionalProperties: {
        anyOf: [
          {
            title: localize(2711, null),
            $ref: "http://json-schema.org/draft-07/schema#"
          },
          {
            type: "object",
            properties: {
              scope: {
                type: "string",
                enum: ["application", "machine", "window", "resource", "language-overridable", "machine-overridable"],
                default: "window",
                enumDescriptions: [
                  localize(2712, null),
                  localize(2713, null),
                  localize(2714, null),
                  localize(2715, null),
                  localize(2716, null),
                  localize(2717, null)
                ],
                markdownDescription: localize(2718, null)
              },
              enumDescriptions: {
                type: "array",
                items: {
                  type: "string"
                },
                description: localize(2719, null)
              },
              markdownEnumDescriptions: {
                type: "array",
                items: {
                  type: "string"
                },
                description: localize(2720, null)
              },
              enumItemLabels: {
                type: "array",
                items: {
                  type: "string"
                },
                markdownDescription: localize(2721, null, "`enum`")
              },
              markdownDescription: {
                type: "string",
                description: localize(2722, null)
              },
              deprecationMessage: {
                type: "string",
                description: localize(2723, null)
              },
              markdownDeprecationMessage: {
                type: "string",
                description: localize(2724, null)
              },
              editPresentation: {
                type: "string",
                enum: ["singlelineText", "multilineText"],
                enumDescriptions: [
                  localize(2725, null),
                  localize(2726, null)
                ],
                default: "singlelineText",
                description: localize(2727, null)
              },
              order: {
                type: "integer",
                description: localize(2728, null)
              },
              ignoreSync: {
                type: "boolean",
                description: localize(2729, null)
              }
            }
          }
        ]
      }
    }
  }
};
var _configDelta;
var defaultConfigurationExtPoint = $tN.registerExtensionPoint({
  extensionPoint: "configurationDefaults",
  jsonSchema: {
    $ref: $Pt
  },
  canHandleResolver: true
});
defaultConfigurationExtPoint.setHandler((extensions, { added, removed }) => {
  if (_configDelta) {
    configurationRegistry6.deltaConfiguration(_configDelta);
  }
  const configNow = _configDelta = {};
  queueMicrotask(() => {
    if (_configDelta === configNow) {
      configurationRegistry6.deltaConfiguration(_configDelta);
      _configDelta = void 0;
    }
  });
  if (removed.length) {
    const removedDefaultConfigurations = removed.map((extension) => ({ overrides: $Lv(extension.value), source: { id: extension.description.identifier.value, displayName: extension.description.displayName } }));
    _configDelta.removedDefaults = removedDefaultConfigurations;
  }
  if (added.length) {
    const registeredProperties = configurationRegistry6.getConfigurationProperties();
    const allowedScopes = [
      6,
      3,
      4,
      5
      /* ConfigurationScope.LANGUAGE_OVERRIDABLE */
    ];
    const addedDefaultConfigurations = added.map((extension) => {
      const overrides = $Lv(extension.value);
      for (const key2 of Object.keys(overrides)) {
        const registeredPropertyScheme = registeredProperties[key2];
        if (registeredPropertyScheme?.disallowConfigurationDefault) {
          extension.collector.warn(localize(2730, null, key2));
          delete overrides[key2];
          continue;
        }
        if (!$Rt.test(key2)) {
          if (registeredPropertyScheme?.scope && !allowedScopes.includes(registeredPropertyScheme.scope)) {
            extension.collector.warn(localize(2731, null, key2));
            delete overrides[key2];
            continue;
          }
        }
      }
      return { overrides, source: { id: extension.description.identifier.value, displayName: extension.description.displayName } };
    });
    _configDelta.addedDefaults = addedDefaultConfigurations;
  }
});
var configurationExtPoint3 = $tN.registerExtensionPoint({
  extensionPoint: "configuration",
  deps: [defaultConfigurationExtPoint],
  jsonSchema: {
    description: localize(2732, null),
    oneOf: [
      configurationEntrySchema,
      {
        type: "array",
        items: configurationEntrySchema
      }
    ]
  },
  canHandleResolver: true
});
var extensionConfigurations = new $7z();
configurationExtPoint3.setHandler((extensions, { added, removed }) => {
  _configDelta ??= {};
  if (removed.length) {
    const removedConfigurations = [];
    for (const extension of removed) {
      removedConfigurations.push(...extensionConfigurations.get(extension.description.identifier) || []);
      extensionConfigurations.delete(extension.description.identifier);
    }
    _configDelta.removedConfigurations = removedConfigurations;
  }
  const seenProperties = /* @__PURE__ */ new Set();
  function handleConfiguration(node, extension) {
    const configuration2 = $Lv(node);
    if (configuration2.title && typeof configuration2.title !== "string") {
      extension.collector.error(localize(2733, null));
    }
    validateProperties(configuration2, extension);
    configuration2.id = node.id || extension.description.identifier.value;
    configuration2.extensionInfo = { id: extension.description.identifier.value, displayName: extension.description.displayName };
    configuration2.restrictedProperties = extension.description.capabilities?.untrustedWorkspaces?.supported === "limited" ? extension.description.capabilities?.untrustedWorkspaces.restrictedConfigurations : void 0;
    configuration2.title = configuration2.title || extension.description.displayName || extension.description.identifier.value;
    return configuration2;
  }
  function validateProperties(configuration2, extension) {
    const properties = configuration2.properties;
    if (properties) {
      if (typeof properties !== "object") {
        extension.collector.error(localize(2734, null));
        configuration2.properties = {};
      }
      for (const key2 in properties) {
        const propertyConfiguration = properties[key2];
        const message = $Vt(key2, propertyConfiguration);
        if (message) {
          delete properties[key2];
          extension.collector.warn(message);
          continue;
        }
        if (seenProperties.has(key2)) {
          delete properties[key2];
          extension.collector.warn(localize(2735, null, key2));
          continue;
        }
        if (!$Bg(propertyConfiguration)) {
          delete properties[key2];
          extension.collector.error(localize(2736, null, key2));
          continue;
        }
        seenProperties.add(key2);
        propertyConfiguration.scope = propertyConfiguration.scope ? $Yt(propertyConfiguration.scope.toString()) : 3;
      }
    }
    const subNodes = configuration2.allOf;
    if (subNodes) {
      extension.collector.error(localize(2737, null));
      for (const node of subNodes) {
        validateProperties(node, extension);
      }
    }
  }
  if (added.length) {
    const addedConfigurations = [];
    for (const extension of added) {
      const configurations = [];
      const value = extension.value;
      if (Array.isArray(value)) {
        value.forEach((v) => configurations.push(handleConfiguration(v, extension)));
      } else {
        configurations.push(handleConfiguration(value, extension));
      }
      extensionConfigurations.set(extension.description.identifier, configurations);
      addedConfigurations.push(...configurations);
    }
    _configDelta.addedConfigurations = addedConfigurations;
  }
  configurationRegistry6.deltaConfiguration(_configDelta);
  _configDelta = void 0;
});
jsonRegistry.registerSchema("vscode://schemas/workspaceConfig", {
  allowComments: true,
  allowTrailingCommas: true,
  default: {
    folders: [
      {
        path: ""
      }
    ],
    settings: {}
  },
  required: ["folders"],
  properties: {
    "folders": {
      minItems: 0,
      uniqueItems: true,
      description: localize(2738, null),
      items: {
        type: "object",
        defaultSnippets: [{ body: { path: "$1" } }],
        oneOf: [{
          properties: {
            path: {
              type: "string",
              description: localize(2739, null)
            },
            name: {
              type: "string",
              description: localize(2740, null)
            }
          },
          required: ["path"]
        }, {
          properties: {
            uri: {
              type: "string",
              description: localize(2741, null)
            },
            name: {
              type: "string",
              description: localize(2742, null)
            }
          },
          required: ["uri"]
        }]
      }
    },
    "settings": {
      type: "object",
      default: {},
      description: localize(2743, null),
      $ref: $pK
    },
    "launch": {
      type: "object",
      default: { configurations: [], compounds: [] },
      description: localize(2744, null),
      $ref: $rK
    },
    "tasks": {
      type: "object",
      default: { version: "2.0.0", tasks: [] },
      description: localize(2745, null),
      $ref: $sK
    },
    "extensions": {
      type: "object",
      default: {},
      description: localize(2746, null),
      $ref: "vscode://schemas/extensions"
    },
    "remoteAuthority": {
      type: "string",
      doNotSuggest: true,
      description: localize(2747, null)
    },
    "transient": {
      type: "boolean",
      doNotSuggest: true,
      description: localize(2748, null)
    }
  },
  errorMessage: localize(2749, null)
});
var SettingsTableRenderer = class extends $3c {
  constructor() {
    super(...arguments);
    this.type = "table";
  }
  shouldRender(manifest) {
    return !!manifest.contributes?.configuration;
  }
  render(manifest) {
    const configuration2 = manifest.contributes?.configuration ? Array.isArray(manifest.contributes.configuration) ? manifest.contributes.configuration : [manifest.contributes.configuration] : [];
    const properties = $Xt(configuration2);
    const contrib = properties ? Object.keys(properties) : [];
    const headers = [localize(2750, null), localize(2751, null), localize(2752, null)];
    const rows = contrib.sort((a, b) => a.localeCompare(b)).map((key2) => {
      return [
        new $bm().appendMarkdown(`\`${key2}\``),
        properties[key2].markdownDescription ? new $bm(properties[key2].markdownDescription, false) : properties[key2].description ?? "",
        new $bm().appendCodeblock("json", JSON.stringify($Gg(properties[key2].default) ? $Ut(properties[key2].type) : properties[key2].default, null, 2))
      ];
    });
    return {
      data: {
        headers,
        rows
      },
      dispose: () => {
      }
    };
  }
};
$Wn.as(Extensions3.ExtensionFeaturesRegistry).registerExtensionFeature({
  id: "configuration",
  label: localize(2753, null),
  access: {
    canToggle: false
  },
  renderer: new $Nk(SettingsTableRenderer)
});

// out-build/vs/workbench/browser/panecomposite.js
var $qqb = class $qqb2 extends $vob {
  constructor(id2, telemetryService, b, c, themeService, f, g, j) {
    super(id2, telemetryService, themeService, b);
    this.b = b;
    this.c = c;
    this.f = f;
    this.g = g;
    this.j = j;
  }
  create(parent) {
    super.create(parent);
    this.a = this.B(this.m(parent));
    this.B(this.a.onTitleAreaUpdate(() => this.R()));
    this.a.create(parent);
  }
  setVisible(visible) {
    super.setVisible(visible);
    this.a?.setVisible(visible);
  }
  layout(dimension) {
    this.a?.layout(dimension);
  }
  setBoundarySashes(sashes) {
    this.a?.setBoundarySashes(sashes);
  }
  getOptimalWidth() {
    return this.a?.getOptimalWidth() ?? 0;
  }
  openView(id2, focus) {
    return this.a?.openView(id2, focus);
  }
  getViewPaneContainer() {
    return this.a;
  }
  getActionsContext() {
    return this.getViewPaneContainer()?.getActionsContext();
  }
  getContextMenuActions() {
    return this.a?.menuActions?.getContextMenuActions() ?? [];
  }
  getMenuIds() {
    const result = [];
    if (this.a?.menuActions) {
      result.push(this.a.menuActions.menuId);
      if (this.a.isViewMergedWithContainer()) {
        result.push(this.a.panes[0].menuActions.menuId);
      }
    }
    return result;
  }
  getActions() {
    const result = [];
    if (this.a?.menuActions) {
      result.push(...this.a.menuActions.getPrimaryActions());
      if (this.a.isViewMergedWithContainer()) {
        const viewPane = this.a.panes[0];
        if (viewPane.shouldShowFilterInHeader()) {
          result.push($$ob);
        }
        result.push(...viewPane.menuActions.getPrimaryActions());
      }
    }
    return result;
  }
  getSecondaryActions() {
    if (!this.a?.menuActions) {
      return [];
    }
    const viewPaneActions = this.a.isViewMergedWithContainer() ? this.a.panes[0].menuActions.getSecondaryActions() : [];
    let menuActions = this.a.menuActions.getSecondaryActions();
    const viewsSubmenuActionIndex = menuActions.findIndex((action) => action instanceof $eJ && action.item.submenu === $nqb);
    if (viewsSubmenuActionIndex !== -1) {
      const viewsSubmenuAction = menuActions[viewsSubmenuActionIndex];
      if (viewsSubmenuAction.actions.some(({ enabled }) => enabled)) {
        if (menuActions.length === 1 && viewPaneActions.length === 0) {
          menuActions = viewsSubmenuAction.actions.slice();
        } else if (viewsSubmenuActionIndex !== 0) {
          menuActions = [viewsSubmenuAction, ...menuActions.slice(0, viewsSubmenuActionIndex), ...menuActions.slice(viewsSubmenuActionIndex + 1)];
        }
      } else {
        menuActions.splice(viewsSubmenuActionIndex, 1);
      }
    }
    if (menuActions.length && viewPaneActions.length) {
      return [
        ...menuActions,
        new $Wm(),
        ...viewPaneActions
      ];
    }
    return menuActions.length ? menuActions : viewPaneActions;
  }
  getActionViewItem(action, options3) {
    return this.a?.getActionViewItem(action, options3);
  }
  getTitle() {
    return this.a?.getTitle() ?? "";
  }
  focus() {
    super.focus();
    this.a?.focus();
  }
};
$qqb = __decorate([
  __param(1, $zv),
  __param(2, $jv),
  __param(3, $Pk),
  __param(4, $gs),
  __param(5, $50),
  __param(6, $wN),
  __param(7, $Zk)
], $qqb);
var $rqb = class _$rqb extends $wob {
  static create(ctor, id2, name, cssClass, order, requestedIndex, iconUrl) {
    return new _$rqb(ctor, id2, name, cssClass, order, requestedIndex, iconUrl);
  }
  constructor(ctor, id2, name, cssClass, order, requestedIndex, iconUrl) {
    super(ctor, id2, name, cssClass, order, requestedIndex);
    this.iconUrl = iconUrl;
  }
};
var $sqb = {
  Viewlets: "workbench.contributions.viewlets",
  Panels: "workbench.contributions.panels",
  Auxiliary: "workbench.contributions.auxiliary"
};
var $tqb = class extends $xob {
  /**
   * Registers a viewlet to the platform.
   */
  registerPaneComposite(descriptor) {
    super.f(descriptor);
  }
  /**
   * Deregisters a viewlet to the platform.
   */
  deregisterPaneComposite(id2) {
    super.g(id2);
  }
  /**
   * Returns the viewlet descriptor for the given id or null if none.
   */
  getPaneComposite(id2) {
    return this.getComposite(id2);
  }
  /**
   * Returns an array of registered viewlets known to the platform.
   */
  getPaneComposites() {
    return this.h();
  }
};
$Wn.add($sqb.Viewlets, new $tqb());
$Wn.add($sqb.Panels, new $tqb());
$Wn.add($sqb.Auxiliary, new $tqb());

// out-build/vs/base/browser/ui/tree/treeDefaults.js
var $I3 = class extends $Um {
  constructor(a, enabled) {
    super("vs.tree.collapse", localize(43, null), "collapse-all", enabled);
    this.a = a;
  }
  async run() {
    this.a.collapseAll();
    this.a.setSelection([]);
    this.a.setFocus([]);
  }
};

// out-build/vs/workbench/browser/parts/views/checkbox.js
var $eUb = class extends $3c {
  constructor() {
    super(...arguments);
    this.a = this.B(new $ze());
    this.onDidChangeCheckboxState = this.a.event;
  }
  setCheckboxState(node) {
    this.a.fire([node]);
  }
};
var $fUb = class _$fUb extends $3c {
  static {
    this.checkboxClass = "custom-view-tree-node-item-checkbox";
  }
  constructor(container2, f, g, h3) {
    super();
    this.f = f;
    this.g = g;
    this.h = h3;
    this.b = container2;
  }
  render(node) {
    if (node.checkbox) {
      if (!this.a) {
        this.j(node);
      } else {
        this.a.checked = node.checkbox.isChecked;
        this.a.setIcon(this.a.checked ? $6l.check : void 0);
      }
    }
  }
  j(node) {
    if (node.checkbox) {
      this.a = new $Q1({
        isChecked: node.checkbox.isChecked,
        title: "",
        icon: node.checkbox.isChecked ? $6l.check : void 0,
        ...$u$
      });
      this.n(node.checkbox);
      this.t(node.checkbox);
      this.a.domNode.classList.add(_$fUb.checkboxClass);
      this.a.domNode.tabIndex = 1;
      $bk(this.b, this.a.domNode);
      this.m(node);
    }
  }
  m(node) {
    if (this.a) {
      this.B({ dispose: () => this.u() });
      this.B(this.a);
      this.B(this.a.onChange(() => {
        this.r(node);
      }));
    }
  }
  n(checkbox) {
    if (this.a) {
      if (!this.c) {
        this.c = this.B(this.h.setupManagedHover(this.g, this.a.domNode, this.s(checkbox)));
      } else {
        this.c.update(checkbox.tooltip);
      }
    }
  }
  r(node) {
    if (this.a && node.checkbox) {
      node.checkbox.isChecked = this.a.checked;
      this.a.setIcon(this.a.checked ? $6l.check : void 0);
      this.n(node.checkbox);
      this.t(node.checkbox);
      this.f.setCheckboxState(node);
    }
  }
  s(checkbox) {
    return checkbox.tooltip ? checkbox.tooltip : checkbox.isChecked ? localize(3790, null) : localize(3791, null);
  }
  t(checkbox) {
    if (this.a && checkbox.accessibilityInformation) {
      this.a.domNode.ariaLabel = checkbox.accessibilityInformation.label;
      if (checkbox.accessibilityInformation.role) {
        this.a.domNode.role = checkbox.accessibilityInformation.role;
      }
    }
  }
  u() {
    const children = this.b.children;
    for (const child of children) {
      child.remove();
    }
  }
};

// out-build/vs/workbench/services/accessibility/common/accessibleViewInformationService.js
var $9ob = $Qk("accessibleViewInformationService");
var $0ob = class $0ob2 extends $3c {
  constructor(a) {
    super();
    this.a = a;
  }
  hasShownAccessibleView(viewId) {
    return this.a.getBoolean(`${$QD}${viewId}`, -1, false) === true;
  }
};
$0ob = __decorate([
  __param(0, $jv)
], $0ob);

// out-build/vs/workbench/browser/parts/views/treeView.js
var TreeRenderer_1;
var $gUb = class $gUb2 extends $_ob {
  constructor(options3, keybindingService, contextMenuService, configurationService, contextKeyService, viewDescriptorService, instantiationService, openerService, themeService, telemetryService, notificationService, hoverService, accessibleViewService) {
    super({ ...options3, titleMenuId: $bJ.ViewTitle, donotForwardArgs: false }, keybindingService, contextMenuService, configurationService, contextKeyService, viewDescriptorService, instantiationService, openerService, themeService, telemetryService, hoverService, accessibleViewService);
    const { treeView } = $Wn.as(Extensions5.ViewsRegistry).getView(options3.id);
    this.f = treeView;
    this.B(this.f.onDidChangeActions(() => this.$b(), this));
    this.B(this.f.onDidChangeTitle((newTitle) => this.Qb(newTitle)));
    this.B(this.f.onDidChangeDescription((newDescription) => this.Sb(newDescription)));
    this.B($1c(() => {
      if (this.g && this.f.container && this.g === this.f.container) {
        this.f.setVisibility(false);
      }
    }));
    this.B(this.onDidChangeBodyVisibility(() => this.L()));
    this.B(this.f.onDidChangeWelcomeState(() => this.eb.fire()));
    if (options3.title !== this.f.title) {
      this.Qb(this.f.title);
    }
    if (options3.titleDescription !== this.f.description) {
      this.Sb(this.f.description);
    }
    this.h = new MultipleSelectionActionRunner(notificationService, () => this.f.getSelection());
    this.L();
  }
  focus() {
    super.focus();
    this.f.focus();
  }
  W(container2) {
    this.g = container2;
    super.W(container2);
    this.n(container2);
  }
  shouldShowWelcome() {
    return (this.f.dataProvider === void 0 || !!this.f.dataProvider.isTreeEmpty) && (this.f.message === void 0 || this.f.message === "");
  }
  X(height, width2) {
    super.X(height, width2);
    this.t(height, width2);
  }
  getOptimalWidth() {
    return this.f.getOptimalWidth();
  }
  n(container2) {
    this.f.show(container2);
  }
  t(height, width2) {
    this.f.layout(height, width2);
  }
  L() {
    this.f.setVisibility(this.isBodyVisible());
  }
  getActionRunner() {
    return this.h;
  }
  getActionsContext() {
    return { $treeViewId: this.id, $focusedTreeItem: true, $selectedTreeItems: true };
  }
};
$gUb = __decorate([
  __param(1, $Ty),
  __param(2, $50),
  __param(3, $kl),
  __param(4, $on),
  __param(5, $$M),
  __param(6, $Pk),
  __param(7, $O4),
  __param(8, $gs),
  __param(9, $zv),
  __param(10, $PJ),
  __param(11, $5$),
  __param(12, $9ob)
], $gUb);
var Root = class {
  constructor() {
    this.label = { label: "root" };
    this.handle = "0";
    this.parentHandle = void 0;
    this.collapsibleState = TreeItemCollapsibleState2.Expanded;
    this.children = void 0;
  }
};
function commandPreconditions(commandId) {
  const command4 = $tn.getCommand(commandId);
  if (command4) {
    const commandAction = $dJ.getCommand(command4.id);
    return commandAction && commandAction.precondition;
  }
  return void 0;
}
function isTreeCommandEnabled(treeCommand, contextKeyService) {
  const commandId = treeCommand.originalId ? treeCommand.originalId : treeCommand.id;
  const precondition2 = commandPreconditions(commandId);
  if (precondition2) {
    return contextKeyService.contextMatchesRules(precondition2);
  }
  return true;
}
function isRenderedMessageValue(messageValue) {
  return !!messageValue && typeof messageValue !== "string" && "element" in messageValue && "disposables" in messageValue;
}
var noDataProviderMessage = localize(3792, null);
var $hUb = new $nn("customTreeView", false);
var Tree = class extends $4eb {
};
var AbstractTreeView = class AbstractTreeView2 extends $3c {
  constructor(id2, db, eb, fb, gb, hb, ib, jb, kb, lb, mb, nb, ob, pb, qb, rb) {
    super();
    this.id = id2;
    this.db = db;
    this.eb = eb;
    this.fb = fb;
    this.gb = gb;
    this.hb = hb;
    this.ib = ib;
    this.jb = jb;
    this.kb = kb;
    this.lb = lb;
    this.mb = mb;
    this.nb = nb;
    this.ob = ob;
    this.pb = pb;
    this.qb = qb;
    this.rb = rb;
    this.b = false;
    this.f = false;
    this.g = false;
    this.w = false;
    this.D = false;
    this.F = false;
    this.O = [];
    this.P = [];
    this.R = this.B(new $ze());
    this.onDidExpandItem = this.R.event;
    this.S = this.B(new $ze());
    this.onDidCollapseItem = this.S.event;
    this.U = this.B(new $ze());
    this.onDidChangeSelectionAndFocus = this.U.event;
    this.W = this.B(new $ze());
    this.onDidChangeVisibility = this.W.event;
    this.X = this.B(new $ze());
    this.onDidChangeActions = this.X.event;
    this.Y = this.B(new $ze());
    this.onDidChangeWelcomeState = this.Y.event;
    this.Z = this.B(new $ze());
    this.onDidChangeTitle = this.Z.event;
    this.ab = this.B(new $ze());
    this.onDidChangeDescription = this.ab.event;
    this.bb = this.B(new $ze());
    this.onDidChangeCheckboxState = this.bb.event;
    this.cb = this.B(new $ze());
    this.sb = false;
    this.zb = this.B(new $4c());
    this.Db = false;
    this.Gb = this.B(new $2c());
    this.Pb = 0;
    this.Qb = 0;
    this.Sb = false;
    this.M = new Root();
    this.Q = this.M;
  }
  tb() {
    if (this.sb) {
      return;
    }
    this.sb = true;
    this.ob.bufferChangeEvents(() => {
      this.Ab();
      this.Ub();
      this.Bb();
    });
    this.J = this.fb.createInstance($kUb, this.id);
    if (this.ub) {
      this.J.controller = this.ub;
    }
    this.B(this.hb.onDidChangeConfiguration((e) => {
      if (e.affectsConfiguration("explorer.decorations")) {
        this.Tb([this.M]);
      }
    }));
    this.B(this.mb.onDidChangeLocation(({ views, from, to }) => {
      if (views.some((v) => v.id === this.id)) {
        this.H?.updateOptions({ overrideStyles: $bpb(this.viewLocation).listOverrideStyles });
      }
    }));
    this.Cb();
    this.Fb();
  }
  get viewContainer() {
    return this.mb.getViewContainerByViewId(this.id);
  }
  get viewLocation() {
    return this.mb.getViewLocationById(this.id);
  }
  get dragAndDropController() {
    return this.ub;
  }
  set dragAndDropController(dnd) {
    this.ub = dnd;
    if (this.J) {
      this.J.controller = dnd;
    }
  }
  get dataProvider() {
    return this.vb;
  }
  set dataProvider(dataProvider) {
    if (dataProvider) {
      if (this.visible) {
        this.Eb();
      }
      const self2 = this;
      this.vb = new class {
        constructor() {
          this.b = true;
          this.d = new $ze();
          this.onDidChangeEmpty = this.d.event;
        }
        get isTreeEmpty() {
          return this.b;
        }
        async getChildren(element) {
          const batches = await this.getChildrenBatch(element ? [element] : void 0);
          return batches?.[0];
        }
        f(nodes, childrenGroups) {
          if (nodes.length === 1 && nodes[0] instanceof Root) {
            const oldEmpty = this.b;
            this.b = childrenGroups.length === 0 || childrenGroups[0].length === 0;
            if (oldEmpty !== this.b) {
              this.d.fire();
            }
          }
        }
        g(nodes, childrenGroups) {
          if (childrenGroups.length === 0) {
            return [];
          }
          const checkboxesUpdated = [];
          for (let i2 = 0; i2 < nodes.length; i2++) {
            const node = nodes[i2];
            const children = childrenGroups[i2];
            for (const child of children) {
              child.parent = node;
              if (!self2.manuallyManageCheckboxes && node?.checkbox?.isChecked === true && child.checkbox?.isChecked === false) {
                child.checkbox.isChecked = true;
                checkboxesUpdated.push(child);
              }
            }
          }
          return checkboxesUpdated;
        }
        async getChildrenBatch(nodes) {
          let childrenGroups;
          let checkboxesUpdated = [];
          if (nodes && nodes.every((node) => !!node.children)) {
            childrenGroups = nodes.map((node) => node.children);
          } else {
            nodes = nodes ?? [self2.M];
            const batchedChildren = await (nodes.length === 1 && nodes[0] instanceof Root ? doGetChildrenOrBatch(dataProvider, void 0) : doGetChildrenOrBatch(dataProvider, nodes));
            for (let i2 = 0; i2 < nodes.length; i2++) {
              const node = nodes[i2];
              node.children = batchedChildren ? batchedChildren[i2] : void 0;
            }
            childrenGroups = batchedChildren ?? [];
            checkboxesUpdated = this.g(nodes, childrenGroups);
          }
          this.f(nodes, childrenGroups);
          if (checkboxesUpdated.length > 0) {
            self2.bb.fire(checkboxesUpdated);
          }
          return childrenGroups;
        }
      }();
      if (this.vb.onDidChangeEmpty) {
        this.B(this.vb.onDidChangeEmpty(() => {
          this.Vb();
          this.Y.fire();
        }));
      }
      this.Kb();
      this.refresh();
    } else {
      this.vb = void 0;
      this.Gb.clear();
      this.Db = false;
      this.Kb();
    }
    this.Y.fire();
  }
  get message() {
    return this.wb;
  }
  set message(message) {
    this.wb = message;
    this.Kb();
    this.Y.fire();
  }
  get title() {
    return this.db;
  }
  set title(name) {
    this.db = name;
    this.Z.fire(this.db);
  }
  get description() {
    return this.xb;
  }
  set description(description) {
    this.xb = description;
    this.ab.fire(this.xb);
  }
  get badge() {
    return this.yb;
  }
  set badge(badge) {
    if (this.yb?.value === badge?.value && this.yb?.tooltip === badge?.tooltip) {
      return;
    }
    this.yb = badge;
    if (badge) {
      const activity = {
        badge: new $wqb(badge.value, () => badge.tooltip),
        priority: 50
      };
      this.zb.value = this.pb.showViewActivity(this.id, activity);
    } else {
      this.zb.clear();
    }
  }
  get canSelectMany() {
    return this.D;
  }
  set canSelectMany(canSelectMany) {
    const oldCanSelectMany = this.D;
    this.D = canSelectMany;
    if (this.D !== oldCanSelectMany) {
      this.H?.updateOptions({ multipleSelectionSupport: this.canSelectMany });
    }
  }
  get manuallyManageCheckboxes() {
    return this.F;
  }
  set manuallyManageCheckboxes(manuallyManageCheckboxes) {
    this.F = manuallyManageCheckboxes;
  }
  get hasIconForParentNode() {
    return this.f;
  }
  get hasIconForLeafNode() {
    return this.g;
  }
  get visible() {
    return this.b;
  }
  Ab(startingValue = false) {
    if (!this.j) {
      this.h = new $nn(`treeView.${this.id}.enableCollapseAll`, startingValue, localize(3793, null, this.id));
      this.j = this.h.bindTo(this.ob);
    }
    return true;
  }
  get showCollapseAllAction() {
    this.Ab();
    return !!this.j?.get();
  }
  set showCollapseAllAction(showCollapseAllAction) {
    this.Ab(showCollapseAllAction);
    this.j?.set(showCollapseAllAction);
  }
  Bb(startingValue = false) {
    if (!this.u) {
      this.t = new $nn(`treeView.${this.id}.enableRefresh`, startingValue, localize(3794, null, this.id));
      this.u = this.t.bindTo(this.ob);
    }
  }
  get showRefreshAction() {
    this.Bb();
    return !!this.u?.get();
  }
  set showRefreshAction(showRefreshAction) {
    this.Bb(showRefreshAction);
    this.u?.set(showRefreshAction);
  }
  Cb() {
    const that = this;
    this.B($hJ(class extends $gJ {
      constructor() {
        super({
          id: `workbench.actions.treeView.${that.id}.refresh`,
          title: localize(3795, null),
          menu: {
            id: $bJ.ViewTitle,
            when: $7m.and($7m.equals("view", that.id), that.t),
            group: "navigation",
            order: Number.MAX_SAFE_INTEGER - 1
          },
          icon: $6l.refresh
        });
      }
      async run() {
        return that.refresh();
      }
    }));
    this.B($hJ(class extends $gJ {
      constructor() {
        super({
          id: `workbench.actions.treeView.${that.id}.collapseAll`,
          title: localize(3796, null),
          menu: {
            id: $bJ.ViewTitle,
            when: $7m.and($7m.equals("view", that.id), that.h),
            group: "navigation",
            order: Number.MAX_SAFE_INTEGER
          },
          precondition: that.m,
          icon: $6l.collapseAll
        });
      }
      async run() {
        if (that.H) {
          return new $I3(that.H, true).run();
        }
      }
    }));
  }
  setVisibility(isVisible) {
    this.tb();
    isVisible = !!isVisible;
    if (this.b === isVisible) {
      return;
    }
    this.b = isVisible;
    if (this.H) {
      if (this.b) {
        $hk(this.H.getHTMLElement());
      } else {
        $ik(this.H.getHTMLElement());
      }
      if (this.b && this.O.length && this.dataProvider) {
        this.Tb(this.O);
        this.O = [];
      }
    }
    $E(() => {
      if (this.dataProvider) {
        this.W.fire(this.b);
      }
    });
    if (this.visible) {
      this.Eb();
    }
  }
  focus(reveal = true, revealItem) {
    if (this.H && this.M.children && this.M.children.length > 0) {
      const element = revealItem ?? this.H.getSelection()[0];
      if (element && reveal) {
        this.H.reveal(element, 0.5);
      }
      this.H.domFocus();
    } else if (this.H && this.z && !this.z.classList.contains("hide")) {
      this.H.domFocus();
    } else {
      this.y.focus();
    }
  }
  show(container2) {
    this.L = container2;
    $bk(container2, this.y);
  }
  Fb() {
    this.y = $(".tree-explorer-viewlet-tree-view");
    this.G = $bk(this.y, $(".message"));
    this.Kb();
    this.z = $bk(this.y, $(".customview-tree"));
    this.z.classList.add("file-icon-themable-tree", "show-file-icons");
    const focusTracker = this.B($_j(this.y));
    this.B(focusTracker.onDidFocus(() => this.w = true));
    this.B(focusTracker.onDidBlur(() => this.w = false));
  }
  Hb() {
    this.Gb.clear();
    const actionViewItemProvider = $X$.bind(void 0, this.fb);
    const treeMenus = this.Gb.add(this.fb.createInstance(TreeMenus, this.id));
    this.I = this.Gb.add(this.fb.createInstance($lsb, this));
    const dataSource = this.fb.createInstance(TreeDataSource, this, (task) => this.ib.withProgress({ location: this.id }, () => task));
    const aligner = this.Gb.add(new Aligner(this.eb));
    const checkboxStateHandler = this.Gb.add(new $eUb());
    const renderer = this.Gb.add(this.fb.createInstance(TreeRenderer, this.id, treeMenus, this.I, actionViewItemProvider, aligner, checkboxStateHandler, () => this.manuallyManageCheckboxes));
    this.Gb.add(renderer.onDidChangeCheckboxState((e) => this.bb.fire(e)));
    const widgetAriaLabel = this.db;
    this.H = this.Gb.add(this.fb.createInstance(Tree, this.id, this.z, new TreeViewDelegate(), [renderer], dataSource, {
      identityProvider: new TreeViewIdentityProvider(),
      accessibilityProvider: {
        getAriaLabel(element) {
          if (element.accessibilityInformation) {
            return element.accessibilityInformation.label;
          }
          if ($zg(element.tooltip)) {
            return element.tooltip;
          } else {
            if (element.resourceUri && !element.label) {
              return null;
            }
            let buildAriaLabel = "";
            if (element.label) {
              buildAriaLabel += element.label.label + " ";
            }
            if (element.description) {
              buildAriaLabel += element.description;
            }
            return buildAriaLabel;
          }
        },
        getRole(element) {
          return element.accessibilityInformation?.role ?? "treeitem";
        },
        getWidgetAriaLabel() {
          return widgetAriaLabel;
        }
      },
      keyboardNavigationLabelProvider: {
        getKeyboardNavigationLabel: (item) => {
          return item.label ? item.label.label : item.resourceUri ? $sh(URI.revive(item.resourceUri)) : void 0;
        }
      },
      expandOnlyOnTwistieClick: (e) => {
        return !!e.command || !!e.checkbox || this.hb.getValue("workbench.tree.expandMode") === "doubleClick";
      },
      collapseByDefault: (e) => {
        return e.collapsibleState !== TreeItemCollapsibleState2.Expanded;
      },
      multipleSelectionSupport: this.canSelectMany,
      dnd: this.J,
      overrideStyles: $bpb(this.viewLocation).listOverrideStyles
    }));
    this.Gb.add(renderer.onDidChangeMenuContext((e) => e.forEach((e2) => this.H?.rerender(e2))));
    this.Gb.add(this.H);
    treeMenus.setContextKeyService(this.H.contextKeyService);
    aligner.tree = this.H;
    const actionRunner = this.Gb.add(new MultipleSelectionActionRunner(this.lb, () => this.H.getSelection()));
    renderer.actionRunner = actionRunner;
    this.H.contextKeyService.createKey(this.id, true);
    const customTreeKey = $hUb.bindTo(this.H.contextKeyService);
    customTreeKey.set(true);
    this.Gb.add(this.H.onContextMenu((e) => this.Jb(treeMenus, e, actionRunner)));
    this.Gb.add(this.H.onDidChangeSelection((e) => {
      this.P = e.elements;
      this.Q = this.H?.getFocus()[0] ?? this.Q;
      this.U.fire({ selection: this.P, focus: this.Q });
    }));
    this.Gb.add(this.H.onDidChangeFocus((e) => {
      if (e.elements.length && e.elements[0] !== this.Q) {
        this.Q = e.elements[0];
        this.P = this.H?.getSelection() ?? this.P;
        this.U.fire({ selection: this.P, focus: this.Q });
      }
    }));
    this.Gb.add(this.H.onDidChangeCollapseState((e) => {
      if (!e.node.element) {
        return;
      }
      const element = Array.isArray(e.node.element.element) ? e.node.element.element[0] : e.node.element.element;
      if (e.node.collapsed) {
        this.S.fire(element);
      } else {
        this.R.fire(element);
      }
    }));
    this.H.setInput(this.M).then(() => this.Wb());
    this.Gb.add(this.H.onDidOpen(async (e) => {
      if (!e.browserEvent) {
        return;
      }
      if (e.browserEvent.target && e.browserEvent.target.classList.contains($fUb.checkboxClass)) {
        return;
      }
      const selection = this.H.getSelection();
      const command4 = await this.Ib(selection.length === 1 ? selection[0] : void 0);
      if (command4 && isTreeCommandEnabled(command4, this.ob)) {
        let args2 = command4.arguments || [];
        if (command4.id === $$ub || command4.id === $_ub) {
          args2 = [...args2, e];
        }
        try {
          await this.gb.executeCommand(command4.id, ...args2);
        } catch (err) {
          this.lb.error(err);
        }
      }
    }));
    this.Gb.add(treeMenus.onDidChange((changed) => {
      if (this.H?.hasNode(changed)) {
        this.H?.rerender(changed);
      }
    }));
  }
  async Ib(element) {
    let command4 = element?.command;
    if (element && !command4) {
      if (element instanceof $_M && element.hasResolve) {
        await element.resolve(CancellationToken.None);
        command4 = element.command;
      }
    }
    return command4;
  }
  Jb(treeMenus, treeEvent, actionRunner) {
    this.nb.hideHover();
    const node = treeEvent.element;
    if (node === null) {
      return;
    }
    const event = treeEvent.browserEvent;
    event.preventDefault();
    event.stopPropagation();
    this.H.setFocus([node]);
    let selected = this.canSelectMany ? this.getSelection() : [];
    if (!selected.find((item) => item.handle === node.handle)) {
      selected = [node];
    }
    const actions = treeMenus.getResourceContextActions(selected);
    if (!actions.length) {
      return;
    }
    this.jb.showContextMenu({
      getAnchor: () => treeEvent.anchor,
      getActions: () => actions,
      getActionViewItem: (action) => {
        const keybinding = this.kb.lookupKeybinding(action.id);
        if (keybinding) {
          return new $U1(action, action, { label: true, keybinding: keybinding.getLabel() });
        }
        return void 0;
      },
      onHide: (wasCancelled) => {
        if (wasCancelled) {
          this.H.domFocus();
        }
      },
      getActionsContext: () => ({ $treeViewId: this.id, $treeItemHandle: node.handle }),
      actionRunner
    });
  }
  Kb() {
    if (this.wb) {
      this.Mb(this.wb);
    } else if (!this.dataProvider) {
      this.Mb(noDataProviderMessage);
    } else {
      this.Nb();
    }
    this.Wb();
  }
  Lb(message, disposables) {
    const lines = message.value.split("\n");
    const result = [];
    let hasFoundButton = false;
    for (const line of lines) {
      const linkedText = $U3(line);
      if (linkedText.nodes.length === 1 && typeof linkedText.nodes[0] !== "string") {
        const node = linkedText.nodes[0];
        const buttonContainer = document.createElement("div");
        buttonContainer.classList.add("button-container");
        const button = new $k2(buttonContainer, { title: node.title, secondary: hasFoundButton, supportIcons: true, ...$q$ });
        button.label = node.label;
        button.onDidClick((_) => {
          this.rb.open(node.href, { allowCommands: true });
        }, null, disposables);
        const href = URI.parse(node.href);
        if (href.scheme === Schemas.command) {
          const preConditions = commandPreconditions(href.path);
          if (preConditions) {
            button.enabled = this.ob.contextMatchesRules(preConditions);
            disposables.add(this.ob.onDidChangeContext((e) => {
              if (e.affectsSome(new Set(preConditions.keys()))) {
                button.enabled = this.ob.contextMatchesRules(preConditions);
              }
            }));
          }
        }
        disposables.add(button);
        hasFoundButton = true;
        result.push(buttonContainer);
      } else {
        hasFoundButton = false;
        const rendered = this.N.render(new $bm(line, { isTrusted: message.isTrusted, supportThemeIcons: message.supportThemeIcons, supportHtml: message.supportHtml }));
        result.push(rendered.element);
        disposables.add(rendered);
      }
    }
    const container2 = document.createElement("div");
    container2.classList.add("rendered-message");
    for (const child of result) {
      if ($Uj(child)) {
        container2.appendChild(child);
      } else {
        container2.appendChild(child.element);
      }
    }
    return container2;
  }
  Mb(message) {
    if (isRenderedMessageValue(this.C)) {
      this.C.disposables.dispose();
    }
    if ($dm(message) && !this.N) {
      this.N = this.fb.createInstance($Q_, {});
    }
    if ($dm(message)) {
      const disposables = new $2c();
      const renderedMessage = this.Lb(message, disposables);
      this.C = { element: renderedMessage, disposables };
    } else {
      this.C = message;
    }
    if (!this.G) {
      return;
    }
    this.G.classList.remove("hide");
    this.Ob();
    if (typeof this.C === "string" && !$vf(this.C)) {
      this.G.textContent = this.C;
    } else if (isRenderedMessageValue(this.C)) {
      this.G.appendChild(this.C.element);
    }
    this.layout(this.Pb, this.Qb);
  }
  Nb() {
    this.Ob();
    this.G?.classList.add("hide");
    this.layout(this.Pb, this.Qb);
  }
  Ob() {
    if (this.G) {
      $$i(this.G);
    }
  }
  layout(height, width2) {
    if (height && width2 && this.G && this.z) {
      this.Pb = height;
      this.Qb = width2;
      const treeHeight = height - $Bj(this.G);
      this.z.style.height = treeHeight + "px";
      this.H?.layout(treeHeight, width2);
    }
  }
  getOptimalWidth() {
    if (this.H) {
      const parentNode = this.H.getHTMLElement();
      const childNodes = [].slice.call(parentNode.querySelectorAll(".outline-item-label > a"));
      return $Cj(parentNode, childNodes);
    }
    return 0;
  }
  Rb(elements) {
    return setCascadingCheckboxUpdates(elements);
  }
  async refresh(elements, checkboxes) {
    if (this.dataProvider && this.H) {
      if (this.Sb) {
        await Event2.toPromise(this.cb.event);
      }
      if (!elements) {
        elements = [this.M];
        this.O = [];
      }
      for (const element of elements) {
        element.children = void 0;
      }
      if (this.b) {
        const affectedElements = this.Rb(checkboxes ?? []);
        return this.Tb(elements.concat(affectedElements));
      } else {
        if (this.O.length) {
          const seen = /* @__PURE__ */ new Set();
          this.O.forEach((element) => seen.add(element.handle));
          for (const element of elements) {
            if (!seen.has(element.handle)) {
              this.O.push(element);
            }
          }
        } else {
          this.O.push(...elements);
        }
      }
    }
    return void 0;
  }
  async expand(itemOrItems) {
    const tree = this.H;
    if (!tree) {
      return;
    }
    try {
      itemOrItems = Array.isArray(itemOrItems) ? itemOrItems : [itemOrItems];
      for (const element of itemOrItems) {
        await tree.expand(element, false);
      }
    } catch (e) {
    }
  }
  isCollapsed(item) {
    return !!this.H?.isCollapsed(item);
  }
  setSelection(items) {
    this.H?.setSelection(items);
  }
  getSelection() {
    return this.H?.getSelection() ?? [];
  }
  setFocus(item) {
    if (this.H) {
      if (item) {
        this.focus(true, item);
        this.H.setFocus([item]);
      } else if (this.H.getFocus().length === 0) {
        this.H.setFocus([]);
      }
    }
  }
  async reveal(item) {
    if (this.H) {
      return this.H.reveal(item);
    }
  }
  async Tb(elements) {
    const tree = this.H;
    if (tree && this.visible) {
      this.Sb = true;
      const oldSelection = tree.getSelection();
      try {
        await Promise.all(elements.map((element) => tree.updateChildren(element, true, true)));
      } catch (e) {
        this.qb.error(e);
      }
      const newSelection = tree.getSelection();
      if (oldSelection.length !== newSelection.length || oldSelection.some((value, index) => value.handle !== newSelection[index].handle)) {
        this.P = newSelection;
        this.U.fire({ selection: this.P, focus: this.Q });
      }
      this.Sb = false;
      this.cb.fire();
      this.Wb();
      if (this.w) {
        this.focus(false);
      }
      this.Vb();
    }
  }
  Ub() {
    if (!this.n) {
      this.m = new $nn(`treeView.${this.id}.toggleCollapseAll`, false, localize(3797, null, this.id));
      this.n = this.m.bindTo(this.ob);
    }
  }
  Vb() {
    if (this.showCollapseAllAction) {
      this.Ub();
      this.n?.set(!!this.M.children && this.M.children.length > 0 && this.M.children.some((value) => value.collapsibleState !== TreeItemCollapsibleState2.None));
    }
  }
  Wb() {
    const isTreeEmpty = !this.M.children || this.M.children.length === 0;
    if (this.C && isTreeEmpty && !this.Sb && this.z) {
      if (!this.dragAndDropController) {
        this.z.classList.add("hide");
      }
      this.y.setAttribute("tabindex", "0");
    } else if (this.z) {
      this.z.classList.remove("hide");
      if (this.y === $Lj()) {
        this.focus();
      }
      this.y.removeAttribute("tabindex");
    }
  }
  get container() {
    return this.L;
  }
};
AbstractTreeView = __decorate([
  __param(2, $gs),
  __param(3, $Pk),
  __param(4, $sn),
  __param(5, $kl),
  __param(6, $TJ),
  __param(7, $50),
  __param(8, $Ty),
  __param(9, $PJ),
  __param(10, $$M),
  __param(11, $5$),
  __param(12, $on),
  __param(13, $vqb),
  __param(14, $wn),
  __param(15, $O4)
], AbstractTreeView);
var TreeViewIdentityProvider = class {
  getId(element) {
    return element.handle;
  }
};
var TreeViewDelegate = class {
  getHeight(element) {
    return TreeRenderer.ITEM_HEIGHT;
  }
  getTemplateId(element) {
    return TreeRenderer.TREE_TEMPLATE_ID;
  }
};
async function doGetChildrenOrBatch(dataProvider, nodes) {
  if (dataProvider.getChildrenBatch) {
    return dataProvider.getChildrenBatch(nodes);
  } else {
    if (nodes) {
      return Promise.all(nodes.map((node) => dataProvider.getChildren(node).then((children) => children ?? [])));
    } else {
      return [await dataProvider.getChildren()].filter((children) => children !== void 0);
    }
  }
}
var TreeDataSource = class {
  constructor(b, d) {
    this.b = b;
    this.d = d;
  }
  hasChildren(element) {
    return !!this.b.dataProvider && element.collapsibleState !== TreeItemCollapsibleState2.None;
  }
  async getChildren(element) {
    const dataProvider = this.b.dataProvider;
    if (!dataProvider) {
      return [];
    }
    if (this.f === void 0) {
      this.f = [element];
      this.g = void 0;
    } else {
      this.f.push(element);
    }
    const indexInBatch = this.f.length - 1;
    return new Promise((resolve, reject) => {
      setTimeout(async () => {
        const batch = this.f;
        this.f = void 0;
        if (!this.g) {
          this.g = this.d(doGetChildrenOrBatch(dataProvider, batch));
        }
        try {
          const result = await this.g;
          resolve(result && indexInBatch < result.length ? result[indexInBatch] : []);
        } catch (e) {
          if (!e.message.startsWith("Bad progress location:")) {
            reject(e);
          }
        }
      }, 0);
    });
  }
};
var TreeRenderer = class TreeRenderer2 extends $3c {
  static {
    TreeRenderer_1 = this;
  }
  static {
    this.ITEM_HEIGHT = 22;
  }
  static {
    this.TREE_TEMPLATE_ID = "treeExplorer";
  }
  constructor(n, t, u, w, y, z, C, D, F, G, H, I, instantiationService) {
    super();
    this.n = n;
    this.t = t;
    this.u = u;
    this.w = w;
    this.y = y;
    this.z = z;
    this.C = C;
    this.D = D;
    this.F = F;
    this.G = G;
    this.H = H;
    this.I = I;
    this.b = this.B(new $ze());
    this.onDidChangeCheckboxState = this.b.event;
    this.f = this.B(new $ze());
    this.onDidChangeMenuContext = this.f.event;
    this.j = false;
    this.m = /* @__PURE__ */ new Map();
    this.h = this.B(instantiationService.createInstance($6$, "mouse", false, {}));
    this.B(this.D.onDidFileIconThemeChange(() => this.L()));
    this.B(this.D.onDidColorThemeChange(() => this.L()));
    this.B(z.onDidChangeCheckboxState((items) => {
      this.W(items);
    }));
    this.B(this.H.onDidChangeContext((e) => this.U(e)));
  }
  get templateId() {
    return TreeRenderer_1.TREE_TEMPLATE_ID;
  }
  set actionRunner(actionRunner) {
    this.g = actionRunner;
  }
  renderTemplate(container2) {
    container2.classList.add("custom-view-tree-node-item");
    const checkboxContainer = $bk(container2, $(""));
    const resourceLabel = this.u.create(container2, { supportHighlights: true, hoverDelegate: this.h });
    const icon2 = $ck(resourceLabel.element, $(".custom-view-tree-node-item-icon"));
    const actionsContainer = $bk(resourceLabel.element, $(".actions"));
    const actionBar = new $LZ(actionsContainer, {
      actionViewItemProvider: this.w
    });
    return { resourceLabel, icon: icon2, checkboxContainer, actionBar, container: container2 };
  }
  J(label3, resource, node) {
    if (!(node instanceof $_M) || !node.hasResolve) {
      if (resource && !node.tooltip) {
        return void 0;
      } else if (node.tooltip === void 0) {
        return label3;
      } else if (!$zg(node.tooltip)) {
        return { markdown: node.tooltip, markdownNotSupportedFallback: resource ? void 0 : $G1(node.tooltip) };
      } else if (node.tooltip !== "") {
        return node.tooltip;
      } else {
        return void 0;
      }
    }
    return {
      markdown: typeof node.tooltip === "string" ? node.tooltip : (token) => {
        return new Promise((resolve) => {
          node.resolve(token).then(() => resolve(node.tooltip));
        });
      },
      markdownNotSupportedFallback: resource ? void 0 : label3 ?? ""
      // Passing undefined as the fallback for a resource falls back to the old native hover
    };
  }
  renderElement(element, index, templateData) {
    const node = element.element;
    const resource = node.resourceUri ? URI.revive(node.resourceUri) : null;
    const treeItemLabel = node.label ? node.label : resource ? { label: $sh(resource) } : void 0;
    const description = $zg(node.description) ? node.description : resource && node.description === true ? this.G.getUriLabel($uh(resource), { relative: true }) : void 0;
    const label3 = treeItemLabel ? treeItemLabel.label : void 0;
    const matches = treeItemLabel && treeItemLabel.highlights && label3 ? treeItemLabel.highlights.map(([start, end]) => {
      if (start < 0) {
        start = label3.length + start;
      }
      if (end < 0) {
        end = label3.length + end;
      }
      if (start >= label3.length || end > label3.length) {
        return { start: 0, end: 0 };
      }
      if (start > end) {
        const swap = start;
        start = end;
        end = swap;
      }
      return { start, end };
    }) : void 0;
    const icon2 = this.D.getColorTheme().type === ColorScheme.LIGHT ? node.icon : node.iconDark;
    const iconUrl = icon2 ? URI.revive(icon2) : void 0;
    const title = this.J(label3, resource, node);
    templateData.actionBar.clear();
    templateData.icon.style.color = "";
    let commandEnabled = true;
    if (node.command) {
      commandEnabled = isTreeCommandEnabled(node.command, this.H);
    }
    this.M(node, templateData);
    if (resource) {
      const fileDecorations = this.F.getValue("explorer.decorations");
      const labelResource = resource ? resource : URI.parse("missing:_icon_resource");
      templateData.resourceLabel.setResource({ name: label3, description, resource: labelResource }, {
        fileKind: this.S(node),
        title,
        hideIcon: this.O(iconUrl, node.themeIcon),
        fileDecorations,
        extraClasses: ["custom-view-tree-node-item-resourceLabel"],
        matches: matches ? matches : $Ul(element.filterData),
        strikethrough: treeItemLabel?.strikethrough,
        disabledCommand: !commandEnabled,
        labelEscapeNewLines: true,
        forceLabel: !!node.label
      });
    } else {
      templateData.resourceLabel.setResource({ name: label3, description }, {
        title,
        hideIcon: true,
        extraClasses: ["custom-view-tree-node-item-resourceLabel"],
        matches: matches ? matches : $Ul(element.filterData),
        strikethrough: treeItemLabel?.strikethrough,
        disabledCommand: !commandEnabled,
        labelEscapeNewLines: true
      });
    }
    if (iconUrl) {
      templateData.icon.className = "custom-view-tree-node-item-icon";
      templateData.icon.style.backgroundImage = $5Z(iconUrl);
    } else {
      let iconClass;
      if (this.P(!!resource, node.themeIcon)) {
        iconClass = ThemeIcon.asClassName(node.themeIcon);
        if (node.themeIcon.color) {
          templateData.icon.style.color = this.D.getColorTheme().getColor(node.themeIcon.color.id)?.toString() ?? "";
        }
      }
      templateData.icon.className = iconClass ? `custom-view-tree-node-item-icon ${iconClass}` : "";
      templateData.icon.style.backgroundImage = "";
    }
    if (!commandEnabled) {
      templateData.icon.className = templateData.icon.className + " disabled";
      if (templateData.container.parentElement) {
        templateData.container.parentElement.className = templateData.container.parentElement.className + " disabled";
      }
    }
    templateData.actionBar.context = { $treeViewId: this.n, $treeItemHandle: node.handle };
    const menuActions = this.t.getResourceActions([node]);
    templateData.actionBar.push(menuActions, { icon: true, label: false });
    if (this.g) {
      templateData.actionBar.actionRunner = this.g;
    }
    this.N(templateData.container, node);
    const renderedItems = this.m.get(element.element.handle) ?? [];
    this.m.set(element.element.handle, [...renderedItems, { original: element, rendered: templateData }]);
  }
  L() {
    const keys = new Set(this.m.keys());
    for (const key2 of keys) {
      const values = this.m.get(key2) ?? [];
      for (const value of values) {
        this.disposeElement(value.original, 0, value.rendered);
        this.renderElement(value.original, 0, value.rendered);
      }
    }
  }
  M(node, templateData) {
    if (node.checkbox) {
      if (!this.j) {
        this.j = true;
        this.L();
      }
      if (!templateData.checkbox) {
        const checkbox = new $fUb(templateData.checkboxContainer, this.z, this.h, this.I);
        templateData.checkbox = checkbox;
      }
      templateData.checkbox.render(node);
    } else if (templateData.checkbox) {
      templateData.checkbox.dispose();
      templateData.checkbox = void 0;
    }
  }
  N(container2, treeItem) {
    container2.parentElement.classList.toggle("align-icon-with-twisty", !this.j && this.y.alignIconWithTwisty(treeItem));
  }
  O(iconUrl, icon2) {
    return !!iconUrl || !!icon2 && !this.R(icon2);
  }
  P(hasResource, icon2) {
    if (!icon2) {
      return false;
    }
    return !(hasResource && this.R(icon2));
  }
  Q(icon2) {
    return icon2?.id === $js.id;
  }
  R(icon2) {
    if (icon2) {
      return icon2.id === $is.id || this.Q(icon2);
    } else {
      return false;
    }
  }
  S(node) {
    if (node.themeIcon) {
      switch (node.themeIcon.id) {
        case $is.id:
          return FileKind.FILE;
        case $js.id:
          return FileKind.FOLDER;
      }
    }
    return node.collapsibleState === TreeItemCollapsibleState2.Collapsed || node.collapsibleState === TreeItemCollapsibleState2.Expanded ? FileKind.FOLDER : FileKind.FILE;
  }
  U(e) {
    const items = [];
    for (const [_, elements] of this.m) {
      for (const element of elements) {
        if (e.affectsSome(this.t.getElementOverlayContexts(element.original.element)) || e.affectsSome(this.t.getEntireMenuContexts())) {
          items.push(element.original.element);
        }
      }
    }
    if (items.length) {
      this.f.fire(items);
    }
  }
  W(items) {
    let allItems = [];
    if (!this.C()) {
      allItems = setCascadingCheckboxUpdates(items);
    } else {
      allItems = items;
    }
    allItems.forEach((item) => {
      const renderedItems = this.m.get(item.handle);
      if (renderedItems) {
        renderedItems.forEach((renderedItems2) => renderedItems2.rendered.checkbox?.render(item));
      }
    });
    this.b.fire(allItems);
  }
  disposeElement(resource, index, templateData) {
    const itemRenders = this.m.get(resource.element.handle) ?? [];
    const renderedIndex = itemRenders.findIndex((renderedItem) => templateData === renderedItem.rendered);
    if (itemRenders.length === 1) {
      this.m.delete(resource.element.handle);
    } else if (itemRenders.length > 0) {
      itemRenders.splice(renderedIndex, 1);
    }
    templateData.checkbox?.dispose();
    templateData.checkbox = void 0;
  }
  disposeTemplate(templateData) {
    templateData.resourceLabel.dispose();
    templateData.actionBar.dispose();
  }
};
TreeRenderer = TreeRenderer_1 = __decorate([
  __param(7, $gs),
  __param(8, $kl),
  __param(9, $ZI),
  __param(10, $on),
  __param(11, $5$),
  __param(12, $Pk)
], TreeRenderer);
var Aligner = class extends $3c {
  constructor(f) {
    super();
    this.f = f;
  }
  set tree(tree) {
    this.b = tree;
  }
  alignIconWithTwisty(treeItem) {
    if (treeItem.collapsibleState !== TreeItemCollapsibleState2.None) {
      return false;
    }
    if (!this.g(treeItem)) {
      return false;
    }
    if (this.b) {
      const parent = this.b.getParentElement(treeItem) || this.b.getInput();
      if (this.g(parent)) {
        return !!parent.children && parent.children.some((c) => c.collapsibleState !== TreeItemCollapsibleState2.None && !this.g(c));
      }
      return !!parent.children && parent.children.every((c) => c.collapsibleState === TreeItemCollapsibleState2.None || !this.g(c));
    } else {
      return false;
    }
  }
  g(node) {
    const icon2 = this.f.getColorTheme().type === ColorScheme.LIGHT ? node.icon : node.iconDark;
    if (icon2) {
      return true;
    }
    if (node.resourceUri || node.themeIcon) {
      const fileIconTheme = this.f.getFileIconTheme();
      const isFolder = node.themeIcon ? node.themeIcon.id === $js.id : node.collapsibleState !== TreeItemCollapsibleState2.None;
      if (isFolder) {
        return fileIconTheme.hasFileIcons && fileIconTheme.hasFolderIcons;
      }
      return fileIconTheme.hasFileIcons;
    }
    return false;
  }
};
var MultipleSelectionActionRunner = class extends $Vm {
  constructor(notificationService, b) {
    super();
    this.b = b;
    this.B(this.onDidRun((e) => {
      if (e.error && !$kb(e.error)) {
        notificationService.error(localize(3798, null, e.error.message, e.action.id));
      }
    }));
  }
  async u(action, context) {
    const selection = this.b();
    let selectionHandleArgs = void 0;
    let actionInSelected = false;
    if (selection.length > 1) {
      selectionHandleArgs = selection.map((selected) => {
        if (selected.handle === context.$treeItemHandle || context.$selectedTreeItems) {
          actionInSelected = true;
        }
        return { $treeViewId: context.$treeViewId, $treeItemHandle: selected.handle };
      });
    }
    if (!actionInSelected && selectionHandleArgs) {
      selectionHandleArgs = void 0;
    }
    await action.run(context, selectionHandleArgs);
  }
};
var TreeMenus = class TreeMenus2 {
  constructor(f, g) {
    this.f = f;
    this.g = g;
    this.d = new $ze();
    this.onDidChange = this.d.event;
  }
  /**
   * Gets only the actions that apply to all of the given elements.
   */
  getResourceActions(elements) {
    const actions = this.l(this.getMenuId(), elements);
    return actions.primary;
  }
  /**
   * Gets only the actions that apply to all of the given elements.
   */
  getResourceContextActions(elements) {
    return this.l(this.getMenuId(), elements).secondary;
  }
  setContextKeyService(service) {
    this.b = service;
  }
  h(groups, newActions) {
    const newActionsSet = new Set(newActions.map((a) => a.id));
    for (const group2 of groups) {
      const actions = group2.keys();
      for (const action of actions) {
        if (!newActionsSet.has(action)) {
          group2.delete(action);
        }
      }
    }
  }
  j(groups) {
    const result = [];
    for (const group2 of groups) {
      if (group2.size > 0) {
        if (result.length) {
          result.push(new $Wm());
        }
        result.push(...group2.values());
      }
    }
    return result;
  }
  k(actions) {
    const groups = [];
    let group2 = /* @__PURE__ */ new Map();
    for (const action of actions) {
      if (action instanceof $Wm) {
        groups.push(group2);
        group2 = /* @__PURE__ */ new Map();
      } else {
        group2.set(action.id, action);
      }
    }
    groups.push(group2);
    return groups;
  }
  getElementOverlayContexts(element) {
    return /* @__PURE__ */ new Map([
      ["view", this.f],
      ["viewItem", element.contextValue]
    ]);
  }
  getEntireMenuContexts() {
    return this.g.getMenuContexts(this.getMenuId());
  }
  getMenuId() {
    return $bJ.ViewItemContext;
  }
  l(menuId, elements) {
    if (!this.b) {
      return { primary: [], secondary: [] };
    }
    let primaryGroups = [];
    let secondaryGroups = [];
    for (let i2 = 0; i2 < elements.length; i2++) {
      const element = elements[i2];
      const contextKeyService = this.b.createOverlay(this.getElementOverlayContexts(element));
      const menuData = this.g.getMenuActions(menuId, contextKeyService, { shouldForwardArgs: true });
      const result = $O$(menuData, "inline");
      if (i2 === 0) {
        primaryGroups = this.k(result.primary);
        secondaryGroups = this.k(result.secondary);
      } else {
        this.h(primaryGroups, result.primary);
        this.h(secondaryGroups, result.secondary);
      }
    }
    return { primary: this.j(primaryGroups), secondary: this.j(secondaryGroups) };
  }
  dispose() {
    this.b = void 0;
  }
};
TreeMenus = __decorate([
  __param(1, $cJ)
], TreeMenus);
var $iUb = class $iUb2 extends AbstractTreeView {
  constructor(id2, title, Xb, themeService, instantiationService, commandService, configurationService, progressService, contextMenuService, keybindingService, notificationService, viewDescriptorService, contextKeyService, hoverService, Yb, activityService, Zb, logService, openerService) {
    super(id2, title, themeService, instantiationService, commandService, configurationService, progressService, contextMenuService, keybindingService, notificationService, viewDescriptorService, hoverService, contextKeyService, activityService, logService, openerService);
    this.Xb = Xb;
    this.Yb = Yb;
    this.Zb = Zb;
  }
  Eb() {
    if (!this.Db) {
      this.Zb.publicLog2("Extension:ViewActivate", {
        extensionId: new $bw(this.Xb),
        id: this.id
      });
      this.Hb();
      this.ib.withProgress({ location: this.id }, () => this.Yb.activateByEvent(`onView:${this.id}`)).then(() => $Wh(2e3)).then(() => {
        this.Kb();
      });
      this.Db = true;
    }
  }
};
$iUb = __decorate([
  __param(3, $gs),
  __param(4, $Pk),
  __param(5, $sn),
  __param(6, $kl),
  __param(7, $TJ),
  __param(8, $50),
  __param(9, $Ty),
  __param(10, $PJ),
  __param(11, $$M),
  __param(12, $on),
  __param(13, $5$),
  __param(14, $wN),
  __param(15, $vqb),
  __param(16, $zv),
  __param(17, $wn),
  __param(18, $O4)
], $iUb);
var $jUb = class extends AbstractTreeView {
  Eb() {
    if (!this.Db) {
      this.Hb();
      this.Db = true;
    }
  }
};
var $kUb = class $kUb2 {
  constructor(g, h3, j, k, l) {
    this.g = g;
    this.h = h3;
    this.j = j;
    this.k = k;
    this.l = l;
    this.d = $B_.getInstance();
    this.b = `application/vnd.code.tree.${g.toLowerCase()}`;
  }
  set controller(controller) {
    this.m = controller;
  }
  n(dndController, itemHandles, uuid, dragCancellationToken) {
    return dndController.handleDrag(itemHandles, uuid, dragCancellationToken).then((additionalDataTransfer) => {
      if (additionalDataTransfer) {
        const unlistedTypes = [];
        for (const item of additionalDataTransfer) {
          if (item[0] !== this.b && dndController.dragMimeTypes.findIndex((value) => value === item[0]) < 0) {
            unlistedTypes.push(item[0]);
          }
        }
        if (unlistedTypes.length) {
          this.l.warn(`Drag and drop controller for tree ${this.g} adds the following data transfer types but does not declare them in dragMimeTypes: ${unlistedTypes.join(", ")}`);
        }
      }
      return additionalDataTransfer;
    });
  }
  o(originalEvent, itemHandles) {
    if (!originalEvent.dataTransfer || !this.m) {
      return;
    }
    const uuid = $ps();
    this.f = new $ad();
    this.k.addDragOperationTransfer(uuid, this.n(this.m, itemHandles, uuid, this.f.token));
    this.d.setData([new $Tfb(uuid)], $Tfb.prototype);
    originalEvent.dataTransfer.clearData($YC.text);
    if (this.m.dragMimeTypes.find((element) => element === $YC.uriList)) {
      originalEvent.dataTransfer?.setData($kZ.RESOURCES, "");
    }
    this.m.dragMimeTypes.forEach((supportedType) => {
      originalEvent.dataTransfer?.setData(supportedType, "");
    });
  }
  p(originalEvent, resources) {
    if (resources.length && originalEvent.dataTransfer) {
      this.j.invokeFunction((accessor) => $Eob(accessor, resources, originalEvent));
      const fileResources = resources.filter((s) => s.scheme === Schemas.file).map((r2) => r2.fsPath);
      if (fileResources.length) {
        originalEvent.dataTransfer.setData($u_.FILES, JSON.stringify(fileResources));
      }
    }
  }
  onDragStart(data, originalEvent) {
    if (originalEvent.dataTransfer) {
      const treeItemsData = data.getData();
      const resources = [];
      const sourceInfo = {
        id: this.g,
        itemHandles: []
      };
      treeItemsData.forEach((item) => {
        sourceInfo.itemHandles.push(item.handle);
        if (item.resourceUri) {
          resources.push(URI.revive(item.resourceUri));
        }
      });
      this.p(originalEvent, resources);
      this.o(originalEvent, sourceInfo.itemHandles);
      originalEvent.dataTransfer.setData(this.b, JSON.stringify(sourceInfo));
    }
  }
  q(types) {
    if (types.size) {
      this.l.debug(`TreeView dragged mime types: ${Array.from(types).join(", ")}`);
    } else {
      this.l.debug(`TreeView dragged with no supported mime types.`);
    }
  }
  onDragOver(data, targetElement, targetIndex, targetSector, originalEvent) {
    const dataTransfer = $G_(originalEvent.dataTransfer);
    const types = new Set(Array.from(dataTransfer, (x) => x[0]));
    if (originalEvent.dataTransfer) {
      for (const item of originalEvent.dataTransfer.items) {
        if (item.kind === "file" || item.type === $kZ.RESOURCES.toLowerCase()) {
          types.add($YC.uriList);
          break;
        }
      }
    }
    this.q(types);
    const dndController = this.m;
    if (!dndController || !originalEvent.dataTransfer || dndController.dropMimeTypes.length === 0) {
      return false;
    }
    const dragContainersSupportedType = Array.from(types).some((value, index) => {
      if (value === this.b) {
        return true;
      } else {
        return dndController.dropMimeTypes.indexOf(value) >= 0;
      }
    });
    if (dragContainersSupportedType) {
      return { accept: true, bubble: 0, autoExpand: true };
    }
    return false;
  }
  getDragURI(element) {
    if (!this.m) {
      return null;
    }
    return element.resourceUri ? URI.revive(element.resourceUri).toString() : element.handle;
  }
  getDragLabel(elements) {
    if (!this.m) {
      return void 0;
    }
    if (elements.length > 1) {
      return String(elements.length);
    }
    const element = elements[0];
    return element.label ? element.label.label : element.resourceUri ? this.h.getUriLabel(URI.revive(element.resourceUri)) : void 0;
  }
  async drop(data, targetNode, targetIndex, targetSector, originalEvent) {
    const dndController = this.m;
    if (!originalEvent.dataTransfer || !dndController) {
      return;
    }
    let treeSourceInfo;
    let willDropUuid;
    if (this.d.hasData($Tfb.prototype)) {
      willDropUuid = this.d.getData($Tfb.prototype)[0].identifier;
    }
    const originalDataTransfer = $G_(originalEvent.dataTransfer, true);
    const outDataTransfer = new $lE();
    for (const [type, item] of originalDataTransfer) {
      if (type === this.b || dndController.dropMimeTypes.includes(type) || item.asFile() && dndController.dropMimeTypes.includes($kZ.FILES.toLowerCase())) {
        outDataTransfer.append(type, item);
        if (type === this.b) {
          try {
            treeSourceInfo = JSON.parse(await item.asString());
          } catch {
          }
        }
      }
    }
    const additionalDataTransfer = await this.k.removeDragOperationTransfer(willDropUuid);
    if (additionalDataTransfer) {
      for (const [type, item] of additionalDataTransfer) {
        outDataTransfer.append(type, item);
      }
    }
    return dndController.handleDrop(outDataTransfer, targetNode, CancellationToken.None, willDropUuid, treeSourceInfo?.id, treeSourceInfo?.itemHandles);
  }
  onDragEnd(originalEvent) {
    if (originalEvent.dataTransfer?.dropEffect === "none") {
      this.f?.cancel();
    }
  }
  dispose() {
  }
};
$kUb = __decorate([
  __param(1, $ZI),
  __param(2, $Pk),
  __param(3, $Ufb),
  __param(4, $wn)
], $kUb);
function setCascadingCheckboxUpdates(items) {
  const additionalItems = [];
  for (const item of items) {
    if (item.checkbox !== void 0) {
      const checkChildren = (currentItem) => {
        for (const child of currentItem.children ?? []) {
          if (child.checkbox !== void 0 && currentItem.checkbox !== void 0 && child.checkbox.isChecked !== currentItem.checkbox.isChecked) {
            child.checkbox.isChecked = currentItem.checkbox.isChecked;
            additionalItems.push(child);
            checkChildren(child);
          }
        }
      };
      checkChildren(item);
      const visitedParents = /* @__PURE__ */ new Set();
      const checkParents = (currentItem) => {
        if (currentItem.parent && currentItem.parent.checkbox !== void 0 && currentItem.parent.children) {
          if (visitedParents.has(currentItem.parent)) {
            return;
          } else {
            visitedParents.add(currentItem.parent);
          }
          let someUnchecked = false;
          let someChecked = false;
          for (const child of currentItem.parent.children) {
            if (someUnchecked && someChecked) {
              break;
            }
            if (child.checkbox !== void 0) {
              if (child.checkbox.isChecked) {
                someChecked = true;
              } else {
                someUnchecked = true;
              }
            }
          }
          if (someChecked && !someUnchecked && currentItem.parent.checkbox.isChecked !== true) {
            currentItem.parent.checkbox.isChecked = true;
            additionalItems.push(currentItem.parent);
            checkParents(currentItem.parent);
          } else if (someUnchecked && currentItem.parent.checkbox.isChecked !== false) {
            currentItem.parent.checkbox.isChecked = false;
            additionalItems.push(currentItem.parent);
            checkParents(currentItem.parent);
          }
        }
      };
      checkParents(item);
    }
  }
  return items.concat(additionalItems);
}

// out-build/vs/workbench/contrib/remote/browser/remoteIcons.js
var $lUb = $9r("remote-explorer-get-started", $6l.star, localize(9151, null));
var $mUb = $9r("remote-explorer-documentation", $6l.book, localize(9152, null));
var $nUb = $9r("remote-explorer-feedback", $6l.twitter, localize(9153, null));
var $oUb = $9r("remote-explorer-review-issues", $6l.issues, localize(9154, null));
var $pUb = $9r("remote-explorer-report-issues", $6l.comment, localize(9155, null));
var $qUb = $9r("remote-explorer-view-icon", $6l.remoteExplorer, localize(9156, null));
var $rUb = $9r("ports-view-icon", $6l.plug, localize(9157, null));
var $sUb = $9r("ports-view-icon", $6l.plug, localize(9158, null));
var $tUb = $9r("private-ports-view-icon", $6l.lock, localize(9159, null));
var $uUb = $9r("ports-forward-icon", $6l.plus, localize(9160, null));
var $vUb = $9r("ports-stop-forward-icon", $6l.x, localize(9161, null));
var $wUb = $9r("ports-open-browser-icon", $6l.globe, localize(9162, null));
var $xUb = $9r("ports-open-preview-icon", $6l.openPreview, localize(9163, null));
var $yUb = $9r("ports-copy-address-icon", $6l.clippy, localize(9164, null));
var $zUb = $9r("ports-label-icon", $6l.tag, localize(9165, null));
var $AUb = $9r("ports-forwarded-without-process-icon", $6l.circleOutline, localize(9166, null));
var $BUb = $9r("ports-forwarded-with-process-icon", $6l.circleFilled, localize(9167, null));

// out-build/vs/workbench/contrib/remote/browser/tunnelView.js
var $EUb_1;
var $CUb = new $nn("openPreviewEnabled", false);
var TunnelTreeVirtualDelegate = class {
  constructor(c) {
    this.c = c;
    this.headerRowHeight = 22;
  }
  getHeight(row) {
    return row.tunnelType === TunnelType.Add && !this.c.getEditableData(void 0) ? 30 : 22;
  }
};
var $DUb = class $DUb2 {
  constructor(f, g) {
    this.f = f;
    this.g = g;
    this.d = /* @__PURE__ */ new Map();
    this.input = {
      label: localize(9196, null),
      icon: void 0,
      tunnelType: TunnelType.Add,
      hasRunningProcess: false,
      remoteHost: "",
      remotePort: 0,
      processDescription: "",
      tooltipPostfix: "",
      iconTooltip: "",
      portTooltip: "",
      processTooltip: "",
      originTooltip: "",
      privacyTooltip: "",
      source: { source: TunnelSource.User, description: "" },
      protocol: TunnelProtocol.Http,
      privacy: {
        id: TunnelPrivacyId.Private,
        themeIcon: $tUb.id,
        label: localize(9197, null)
      },
      strip: () => void 0
    };
    this.c = f.tunnelModel;
    this.onForwardedPortsChanged = Event2.any(this.c.onForwardPort, this.c.onClosePort, this.c.onPortName, this.c.onCandidatesChanged);
  }
  get all() {
    const result = [];
    this.d = /* @__PURE__ */ new Map();
    this.c.candidates.forEach((candidate) => {
      this.d.set($4S(candidate.host, candidate.port), candidate);
    });
    if (this.c.forwarded.size > 0 || this.f.getEditableData(void 0)) {
      result.push(...this.i);
    }
    if (this.c.detected.size > 0) {
      result.push(...this.j);
    }
    result.push(this.input);
    return result;
  }
  h(tunnelItem) {
    const key2 = $4S(tunnelItem.remoteHost, tunnelItem.remotePort);
    if (this.d.has(key2)) {
      tunnelItem.processDescription = this.d.get(key2).detail;
    }
  }
  get i() {
    const forwarded = Array.from(this.c.forwarded.values()).map((tunnel) => {
      const tunnelItem = TunnelItem.createFromTunnel(this.f, this.g, tunnel);
      this.h(tunnelItem);
      return tunnelItem;
    }).sort((a, b) => {
      if (a.remotePort === b.remotePort) {
        return a.remoteHost < b.remoteHost ? -1 : 1;
      } else {
        return a.remotePort < b.remotePort ? -1 : 1;
      }
    });
    return forwarded;
  }
  get j() {
    return Array.from(this.c.detected.values()).map((tunnel) => {
      const tunnelItem = TunnelItem.createFromTunnel(this.f, this.g, tunnel, TunnelType.Detected, false);
      this.h(tunnelItem);
      return tunnelItem;
    });
  }
  isEmpty() {
    return this.j.length === 0 && (this.i.length === 0 || this.i.length === 1 && this.i[0].tunnelType === TunnelType.Add && !this.f.getEditableData(void 0));
  }
};
$DUb = __decorate([
  __param(0, $8Sb),
  __param(1, $tC)
], $DUb);
function emptyCell(item) {
  return { label: "", tunnel: item, editId: TunnelEditId.None, tooltip: "" };
}
var IconColumn = class {
  constructor() {
    this.label = "";
    this.tooltip = "";
    this.weight = 1;
    this.minimumWidth = 40;
    this.maximumWidth = 40;
    this.templateId = "actionbar";
  }
  project(row) {
    if (row.tunnelType === TunnelType.Add) {
      return emptyCell(row);
    }
    const icon2 = row.processDescription ? $BUb : $AUb;
    let tooltip = "";
    if (row instanceof TunnelItem) {
      tooltip = `${row.iconTooltip} ${row.tooltipPostfix}`;
    }
    return {
      label: "",
      icon: icon2,
      tunnel: row,
      editId: TunnelEditId.None,
      tooltip
    };
  }
};
var PortColumn = class {
  constructor() {
    this.label = localize(9198, null);
    this.tooltip = localize(9199, null);
    this.weight = 1;
    this.templateId = "actionbar";
  }
  project(row) {
    const isAdd = row.tunnelType === TunnelType.Add;
    const label3 = row.label;
    let tooltip = "";
    if (row instanceof TunnelItem && !isAdd) {
      tooltip = `${row.portTooltip} ${row.tooltipPostfix}`;
    } else {
      tooltip = label3;
    }
    return {
      label: label3,
      tunnel: row,
      menuId: $bJ.TunnelPortInline,
      editId: row.tunnelType === TunnelType.Add ? TunnelEditId.New : TunnelEditId.Label,
      tooltip
    };
  }
};
var LocalAddressColumn = class _LocalAddressColumn {
  constructor() {
    this.label = localize(9200, null);
    this.tooltip = localize(9201, null);
    this.weight = 1;
    this.templateId = "actionbar";
  }
  project(row) {
    if (row.tunnelType === TunnelType.Add) {
      return emptyCell(row);
    }
    const label3 = row.localAddress ?? "";
    let tooltip = label3;
    if (row instanceof TunnelItem) {
      tooltip = row.tooltipPostfix;
    }
    return {
      label: label3,
      menuId: $bJ.TunnelLocalAddressInline,
      tunnel: row,
      editId: TunnelEditId.LocalPort,
      tooltip,
      markdownTooltip: label3 ? _LocalAddressColumn.c(label3) : void 0
    };
  }
  static c(localAddress) {
    return function(configurationService) {
      const editorConf = configurationService.getValue("editor");
      let clickLabel = "";
      if (editorConf.multiCursorModifier === "ctrlCmd") {
        if ($m) {
          clickLabel = localize(9202, null);
        } else {
          clickLabel = localize(9203, null);
        }
      } else {
        if ($m) {
          clickLabel = localize(9204, null);
        } else {
          clickLabel = localize(9205, null);
        }
      }
      const markdown = new $bm("", true);
      const uri = localAddress.startsWith("http") ? localAddress : `http://${localAddress}`;
      return markdown.appendLink(uri, "Follow link").appendMarkdown(` (${clickLabel})`);
    };
  }
};
var RunningProcessColumn = class {
  constructor() {
    this.label = localize(9206, null);
    this.tooltip = localize(9207, null);
    this.weight = 2;
    this.templateId = "actionbar";
  }
  project(row) {
    if (row.tunnelType === TunnelType.Add) {
      return emptyCell(row);
    }
    const label3 = row.processDescription ?? "";
    return { label: label3, tunnel: row, editId: TunnelEditId.None, tooltip: row instanceof TunnelItem ? row.processTooltip : "" };
  }
};
var OriginColumn = class {
  constructor() {
    this.label = localize(9208, null);
    this.tooltip = localize(9209, null);
    this.weight = 1;
    this.templateId = "actionbar";
  }
  project(row) {
    if (row.tunnelType === TunnelType.Add) {
      return emptyCell(row);
    }
    const label3 = row.source.description;
    const tooltip = `${row instanceof TunnelItem ? row.originTooltip : ""}. ${row instanceof TunnelItem ? row.tooltipPostfix : ""}`;
    return { label: label3, menuId: $bJ.TunnelOriginInline, tunnel: row, editId: TunnelEditId.None, tooltip };
  }
};
var PrivacyColumn = class {
  constructor() {
    this.label = localize(9210, null);
    this.tooltip = localize(9211, null);
    this.weight = 1;
    this.templateId = "actionbar";
  }
  project(row) {
    if (row.tunnelType === TunnelType.Add) {
      return emptyCell(row);
    }
    const label3 = row.privacy?.label;
    let tooltip = "";
    if (row instanceof TunnelItem) {
      tooltip = `${row.privacy.label} ${row.tooltipPostfix}`;
    }
    return { label: label3, tunnel: row, icon: { id: row.privacy.themeIcon }, editId: TunnelEditId.None, tooltip };
  }
};
var ActionBarRenderer = class ActionBarRenderer2 extends $3c {
  constructor(h3, j, m, n, r2, s, t) {
    super();
    this.h = h3;
    this.j = j;
    this.m = m;
    this.n = n;
    this.r = r2;
    this.s = s;
    this.t = t;
    this.templateId = "actionbar";
    this.g = $JZ("mouse");
  }
  set actionRunner(actionRunner) {
    this.f = actionRunner;
  }
  renderTemplate(container2) {
    const cell = $bk(container2, $(".ports-view-actionbar-cell"));
    const icon2 = $bk(cell, $(".ports-view-actionbar-cell-icon"));
    const label3 = new $T2(cell, {
      supportHighlights: true,
      hoverDelegate: this.g
    });
    const actionsContainer = $bk(cell, $(".actions"));
    const actionBar = new $LZ(actionsContainer, {
      actionViewItemProvider: $X$.bind(void 0, this.h),
      hoverDelegate: this.g
    });
    return { label: label3, icon: icon2, actionBar, container: cell, elementDisposable: $3c.None };
  }
  renderElement(element, index, templateData) {
    templateData.actionBar.clear();
    templateData.icon.className = "ports-view-actionbar-cell-icon";
    templateData.icon.style.display = "none";
    templateData.label.setLabel("");
    templateData.label.element.style.display = "none";
    templateData.container.style.height = "22px";
    if (templateData.button) {
      templateData.button.element.style.display = "none";
      templateData.button.dispose();
    }
    templateData.container.style.paddingLeft = "0px";
    templateData.elementDisposable.dispose();
    let editableData;
    if (element.editId === TunnelEditId.New && (editableData = this.r.getEditableData(void 0))) {
      this.w(templateData.container, editableData);
    } else {
      editableData = this.r.getEditableData(element.tunnel, element.editId);
      if (editableData) {
        this.w(templateData.container, editableData);
      } else if (element.tunnel.tunnelType === TunnelType.Add && element.menuId === $bJ.TunnelPortInline) {
        this.renderButton(element, templateData);
      } else {
        this.renderActionBarItem(element, templateData);
      }
    }
  }
  renderButton(element, templateData) {
    templateData.container.style.paddingLeft = "7px";
    templateData.container.style.height = "28px";
    templateData.button = this.B(new $k2(templateData.container, $q$));
    templateData.button.label = element.label;
    templateData.button.element.title = element.tooltip;
    this.B(templateData.button.onDidClick(() => {
      this.s.executeCommand(ForwardPortAction.INLINE_ID);
    }));
  }
  u(tunnel) {
    let context;
    if (tunnel instanceof TunnelItem) {
      context = tunnel.strip();
    }
    if (!context) {
      context = {
        tunnelType: tunnel.tunnelType,
        remoteHost: tunnel.remoteHost,
        remotePort: tunnel.remotePort,
        localAddress: tunnel.localAddress,
        protocol: tunnel.protocol,
        localUri: tunnel.localUri,
        localPort: tunnel.localPort,
        name: tunnel.name,
        closeable: tunnel.closeable,
        source: tunnel.source,
        privacy: tunnel.privacy,
        processDescription: tunnel.processDescription,
        label: tunnel.label
      };
    }
    return context;
  }
  renderActionBarItem(element, templateData) {
    templateData.label.element.style.display = "flex";
    templateData.label.setLabel(element.label, void 0, {
      title: element.markdownTooltip ? { markdown: element.markdownTooltip(this.t), markdownNotSupportedFallback: element.tooltip } : element.tooltip,
      extraClasses: element.menuId === $bJ.TunnelLocalAddressInline ? ["ports-view-actionbar-cell-localaddress"] : void 0
    });
    templateData.actionBar.context = this.u(element.tunnel);
    templateData.container.style.paddingLeft = "10px";
    const context = [
      ["view", $0Sb],
      [TunnelTypeContextKey.key, element.tunnel.tunnelType],
      [TunnelCloseableContextKey.key, element.tunnel.closeable],
      [TunnelPrivacyContextKey.key, element.tunnel.privacy.id],
      [TunnelProtocolContextKey.key, element.tunnel.protocol]
    ];
    const contextKeyService = this.j.createOverlay(context);
    const disposableStore = new $2c();
    templateData.elementDisposable = disposableStore;
    if (element.menuId) {
      const menu = disposableStore.add(this.m.createMenu(element.menuId, contextKeyService));
      let actions = $R$(menu.getActions({ shouldForwardArgs: true }));
      if (actions) {
        const labelActions = actions.filter((action) => action.id.toLowerCase().indexOf("label") >= 0);
        if (labelActions.length > 1) {
          labelActions.sort((a, b) => a.label.length - b.label.length);
          labelActions.pop();
          actions = actions.filter((action) => labelActions.indexOf(action) < 0);
        }
        templateData.actionBar.push(actions, { icon: true, label: false });
        if (this.f) {
          templateData.actionBar.actionRunner = this.f;
        }
      }
    }
    if (element.icon) {
      templateData.icon.className = `ports-view-actionbar-cell-icon ${ThemeIcon.asClassName(element.icon)}`;
      templateData.icon.title = element.tooltip;
      templateData.icon.style.display = "inline";
    }
  }
  w(container2, editableData) {
    if (this.c) {
      this.c(false, false);
      this.c = void 0;
    }
    container2.style.paddingLeft = "5px";
    const value = editableData.startingValue || "";
    const inputBox = new $I2(container2, this.n, {
      ariaLabel: localize(9212, null),
      validationOptions: {
        validation: (value2) => {
          const message = editableData.validationMessage(value2);
          if (!message) {
            return null;
          }
          return {
            content: message.content,
            formatContent: true,
            type: message.severity === Severity2.Error ? 3 : 1
            /* MessageType.INFO */
          };
        }
      },
      placeholder: editableData.placeholder || "",
      inputBoxStyles: $B$
    });
    inputBox.value = value;
    inputBox.focus();
    inputBox.select({ start: 0, end: editableData.startingValue ? editableData.startingValue.length : 0 });
    const done = $Qc(async (success, finishEditing) => {
      $Xc(toDispose);
      if (this.c) {
        this.c = void 0;
      }
      inputBox.element.style.display = "none";
      const inputValue = inputBox.value;
      if (finishEditing) {
        return editableData.onFinish(inputValue, success);
      }
    });
    this.c = done;
    const toDispose = [
      inputBox,
      $aj(inputBox.inputElement, $7j.KEY_DOWN, async (e) => {
        if (e.equals(
          3
          /* KeyCode.Enter */
        )) {
          e.stopPropagation();
          if (inputBox.validate() !== 3) {
            return done(true, true);
          } else {
            return done(false, true);
          }
        } else if (e.equals(
          9
          /* KeyCode.Escape */
        )) {
          e.preventDefault();
          e.stopPropagation();
          return done(false, true);
        }
      }),
      $_i(inputBox.inputElement, $7j.BLUR, () => {
        return done(inputBox.validate() !== 3, true);
      })
    ];
    return $1c(() => {
      done(false, false);
    });
  }
  disposeElement(element, index, templateData, height) {
    templateData.elementDisposable.dispose();
  }
  disposeTemplate(templateData) {
    templateData.label.dispose();
    templateData.actionBar.dispose();
    templateData.elementDisposable.dispose();
    templateData.button?.dispose();
  }
};
ActionBarRenderer = __decorate([
  __param(0, $Pk),
  __param(1, $on),
  __param(2, $cJ),
  __param(3, $40),
  __param(4, $8Sb),
  __param(5, $sn),
  __param(6, $kl)
], ActionBarRenderer);
var TunnelItem = class _TunnelItem {
  static createFromTunnel(remoteExplorerService, tunnelService, tunnel, type = TunnelType.Forwarded, closeable) {
    return new _TunnelItem(type, tunnel.remoteHost, tunnel.remotePort, tunnel.source, !!tunnel.hasRunningProcess, tunnel.protocol, tunnel.localUri, tunnel.localAddress, tunnel.localPort, closeable === void 0 ? tunnel.closeable : closeable, tunnel.name, tunnel.runningProcess, tunnel.pid, tunnel.privacy, remoteExplorerService, tunnelService);
  }
  /**
   * Removes all non-serializable properties from the tunnel
   * @returns A new TunnelItem without any services
   */
  strip() {
    return new _TunnelItem(this.tunnelType, this.remoteHost, this.remotePort, this.source, this.hasRunningProcess, this.protocol, this.localUri, this.localAddress, this.localPort, this.closeable, this.name, this.c, this.d, this.f);
  }
  constructor(tunnelType, remoteHost, remotePort, source, hasRunningProcess, protocol, localUri, localAddress, localPort, closeable, name, c, d, f, g, h3) {
    this.tunnelType = tunnelType;
    this.remoteHost = remoteHost;
    this.remotePort = remotePort;
    this.source = source;
    this.hasRunningProcess = hasRunningProcess;
    this.protocol = protocol;
    this.localUri = localUri;
    this.localAddress = localAddress;
    this.localPort = localPort;
    this.closeable = closeable;
    this.name = name;
    this.c = c;
    this.d = d;
    this.f = f;
    this.g = g;
    this.h = h3;
  }
  get label() {
    if (this.tunnelType === TunnelType.Add && this.name) {
      return this.name;
    }
    const portNumberLabel = $zC(this.remoteHost) || $BC(this.remoteHost) ? `${this.remotePort}` : `${this.remoteHost}:${this.remotePort}`;
    if (this.name) {
      return `${this.name} (${portNumberLabel})`;
    } else {
      return portNumberLabel;
    }
  }
  set processDescription(description) {
    this.c = description;
  }
  get processDescription() {
    let description = "";
    if (this.c) {
      if (this.d && this.g?.namedProcesses.has(this.d)) {
        description = this.g.namedProcesses.get(this.d);
      } else {
        description = this.c.replace(/\0/g, " ").trim();
      }
      if (this.d) {
        description += ` (${this.d})`;
      }
    } else if (this.hasRunningProcess) {
      description = localize(9213, null);
    }
    return description;
  }
  get tooltipPostfix() {
    let information;
    if (this.localAddress) {
      information = localize(9214, null, this.remoteHost, this.remotePort, this.localAddress);
    } else {
      information = localize(9215, null, this.remoteHost, this.remotePort);
    }
    return information;
  }
  get iconTooltip() {
    const isAdd = this.tunnelType === TunnelType.Add;
    if (!isAdd) {
      return `${this.processDescription ? localize(9216, null) : localize(9217, null)}`;
    } else {
      return this.label;
    }
  }
  get portTooltip() {
    const isAdd = this.tunnelType === TunnelType.Add;
    if (!isAdd) {
      return `${this.name ? localize(9218, null, this.name) : ""}`;
    } else {
      return "";
    }
  }
  get processTooltip() {
    return this.processDescription ?? "";
  }
  get originTooltip() {
    return this.source.description;
  }
  get privacy() {
    if (this.h?.privacyOptions) {
      return this.h?.privacyOptions.find((element) => element.id === this.f) ?? {
        id: "",
        themeIcon: $6l.question.id,
        label: localize(9219, null)
      };
    } else {
      return {
        id: TunnelPrivacyId.Private,
        themeIcon: $tUb.id,
        label: localize(9220, null)
      };
    }
  }
};
var TunnelTypeContextKey = new $nn("tunnelType", TunnelType.Add, true);
var TunnelCloseableContextKey = new $nn("tunnelCloseable", false, true);
var TunnelPrivacyContextKey = new $nn("tunnelPrivacy", void 0, true);
var TunnelPrivacyEnabledContextKey = new $nn("tunnelPrivacyEnabled", false, true);
var TunnelProtocolContextKey = new $nn("tunnelProtocol", TunnelProtocol.Http, true);
var TunnelViewFocusContextKey = new $nn("tunnelViewFocus", false, localize(9221, null));
var TunnelViewSelectionKeyName = "tunnelViewSelection";
var TunnelViewSelectionContextKey = new $nn(TunnelViewSelectionKeyName, void 0, true);
var TunnelViewMultiSelectionKeyName = "tunnelViewMultiSelection";
var TunnelViewMultiSelectionContextKey = new $nn(TunnelViewMultiSelectionKeyName, void 0, true);
var PortChangableContextKey = new $nn("portChangable", false, true);
var ProtocolChangeableContextKey = new $nn("protocolChangable", true, true);
var $EUb = class $EUb2 extends $_ob {
  static {
    $EUb_1 = this;
  }
  static {
    this.ID = $0Sb;
  }
  static {
    this.TITLE = localize2(9253, "Ports");
  }
  constructor(dc, options3, keybindingService, contextMenuService, contextKeyService, configurationService, instantiationService, viewDescriptorService, openerService, ec, fc, gc, themeService, hc, telemetryService, hoverService, ic, jc) {
    super(options3, keybindingService, contextMenuService, configurationService, contextKeyService, viewDescriptorService, instantiationService, openerService, themeService, telemetryService, hoverService);
    this.dc = dc;
    this.ec = ec;
    this.fc = fc;
    this.gc = gc;
    this.hc = hc;
    this.ic = ic;
    this.jc = jc;
    this.g = this.B(new $2c());
    this.ac = false;
    this.bc = [];
    this.cc = [];
    this.sc = 0;
    this.tc = 0;
    this.h = TunnelTypeContextKey.bindTo(contextKeyService);
    this.j = TunnelCloseableContextKey.bindTo(contextKeyService);
    this.m = TunnelPrivacyContextKey.bindTo(contextKeyService);
    this.n = TunnelPrivacyEnabledContextKey.bindTo(contextKeyService);
    this.n.set(ic.canChangePrivacy);
    this.sb = ProtocolChangeableContextKey.bindTo(contextKeyService);
    this.sb.set(ic.canChangeProtocol);
    this.r = TunnelProtocolContextKey.bindTo(contextKeyService);
    this.s = TunnelViewFocusContextKey.bindTo(contextKeyService);
    this.t = TunnelViewSelectionContextKey.bindTo(contextKeyService);
    this.L = TunnelViewMultiSelectionContextKey.bindTo(contextKeyService);
    this.ab = PortChangableContextKey.bindTo(contextKeyService);
    const overlayContextKeyService = this.Bb.createOverlay([["view", $EUb_1.ID]]);
    const titleMenu = this.B(this.gc.createMenu($bJ.TunnelTitle, overlayContextKeyService));
    const updateActions = () => {
      this.bc = $R$(titleMenu.getActions());
      this.$b();
    };
    this.B(titleMenu.onDidChange(updateActions));
    updateActions();
    this.B($1c(() => {
      this.bc = [];
    }));
    this.kc();
    this.B(Event2.once(this.ic.onAddedTunnelProvider)(() => {
      let updated = false;
      if (this.n.get() === false) {
        this.n.set(ic.canChangePrivacy);
        updated = true;
      }
      if (this.sb.get() === true) {
        this.sb.set(ic.canChangeProtocol);
        updated = true;
      }
      if (updated) {
        updateActions();
        this.kc();
        this.lc();
        this.f?.layout(this.sc, this.tc);
      }
    }));
  }
  kc() {
    for (const privacyOption of this.ic.privacyOptions) {
      const optionId = `remote.tunnel.privacy${privacyOption.id}`;
      $tn.registerCommand(optionId, ChangeTunnelPrivacyAction.handler(privacyOption.id));
      $dJ.appendMenuItem($bJ.TunnelPrivacy, {
        order: 0,
        command: {
          id: optionId,
          title: privacyOption.label,
          toggled: TunnelPrivacyContextKey.isEqualTo(privacyOption.id)
        }
      });
    }
  }
  get portCount() {
    return this.hc.tunnelModel.forwarded.size + this.hc.tunnelModel.detected.size;
  }
  lc() {
    if (!this.c) {
      return;
    }
    this.g.clear();
    $$i(this.c);
    const widgetContainer = $bk(this.c, $(".customview-tree"));
    widgetContainer.classList.add("ports-view");
    widgetContainer.classList.add("file-icon-themable-tree", "show-file-icons");
    const actionBarRenderer = new ActionBarRenderer(this.Db, this.Bb, this.gc, this.jc, this.hc, this.fc, this.Ab);
    const columns = [new IconColumn(), new PortColumn(), new LocalAddressColumn(), new RunningProcessColumn()];
    if (this.ic.canChangePrivacy) {
      columns.push(new PrivacyColumn());
    }
    columns.push(new OriginColumn());
    this.f = this.Db.createInstance($Yeb, "RemoteTunnels", widgetContainer, new TunnelTreeVirtualDelegate(this.hc), columns, [actionBarRenderer], {
      keyboardNavigationLabelProvider: {
        getKeyboardNavigationLabel: (item) => {
          return item.label;
        }
      },
      multipleSelectionSupport: true,
      accessibilityProvider: {
        getAriaLabel: (item) => {
          if (item instanceof TunnelItem) {
            return `${item.tooltipPostfix} ${item.portTooltip} ${item.iconTooltip} ${item.processTooltip} ${item.originTooltip} ${this.ic.canChangePrivacy ? item.privacy.label : ""}`;
          } else {
            return item.label;
          }
        },
        getWidgetAriaLabel: () => localize(9222, null)
      },
      openOnSingleClick: true
    });
    const actionRunner = new $Vm();
    actionBarRenderer.actionRunner = actionRunner;
    this.g.add(this.f);
    this.g.add(this.f.onContextMenu((e) => this.qc(e, actionRunner)));
    this.g.add(this.f.onMouseDblClick((e) => this.rc(e)));
    this.g.add(this.f.onDidChangeFocus((e) => this.nc(e)));
    this.g.add(this.f.onDidChangeSelection((e) => this.pc(e)));
    this.g.add(this.f.onDidFocus(() => this.s.set(true)));
    this.g.add(this.f.onDidBlur(() => this.s.set(false)));
    const rerender = () => this.f?.splice(0, Number.POSITIVE_INFINITY, this.dc.all);
    rerender();
    let lastPortCount = this.portCount;
    this.g.add(Event2.debounce(this.dc.onForwardedPortsChanged, (_last, e) => e, 50)(() => {
      const newPortCount = this.portCount;
      if ((lastPortCount === 0 || newPortCount === 0) && lastPortCount !== newPortCount) {
        this.eb.fire();
      }
      lastPortCount = newPortCount;
      rerender();
    }));
    this.g.add(this.f.onMouseClick((e) => {
      if (this.oc(e.browserEvent) && this.f) {
        const selection = this.f.getSelectedElements();
        if (selection.length === 0 || selection.length === 1 && selection[0] === e.element) {
          this.fc.executeCommand(OpenPortInBrowserAction.ID, e.element);
        }
      }
    }));
    this.g.add(this.f.onDidOpen((e) => {
      if (!e.element || e.element.tunnelType !== TunnelType.Forwarded) {
        return;
      }
      if (e.browserEvent?.type === "dblclick") {
        this.fc.executeCommand(LabelTunnelAction.ID);
      }
    }));
    this.g.add(this.hc.onDidChangeEditable((e) => {
      this.ac = !!this.hc.getEditableData(e?.tunnel, e?.editId);
      this.eb.fire();
      if (!this.ac) {
        widgetContainer.classList.remove("highlight");
      }
      rerender();
      if (this.ac) {
        widgetContainer.classList.add("highlight");
        if (!e) {
          this.f?.reveal(this.f.indexOf(this.dc.input));
        }
      } else {
        if (e && e.tunnel.tunnelType !== TunnelType.Add) {
          this.f?.setFocus(this.cc);
        }
        this.focus();
      }
    }));
  }
  W(container2) {
    super.W(container2);
    this.c = $bk(container2, $(".tree-explorer-viewlet-tree-view"));
    this.lc();
  }
  shouldShowWelcome() {
    return this.dc.isEmpty() && !this.ac;
  }
  focus() {
    super.focus();
    this.f?.domFocus();
  }
  nc(event) {
    if (event.indexes.length > 0 && event.elements.length > 0) {
      this.cc = [...event.indexes];
    }
    const elements = event.elements;
    const item = elements && elements.length ? elements[0] : void 0;
    if (item) {
      this.t.set($4S(item.remoteHost, item.remotePort));
      this.h.set(item.tunnelType);
      this.j.set(!!item.closeable);
      this.m.set(item.privacy.id);
      this.r.set(item.protocol === TunnelProtocol.Https ? TunnelProtocol.Https : TunnelProtocol.Https);
      this.ab.set(!!item.localPort);
    } else {
      this.h.reset();
      this.t.reset();
      this.j.reset();
      this.m.reset();
      this.r.reset();
      this.ab.reset();
    }
  }
  oc(e) {
    const editorConf = this.Ab.getValue("editor");
    let modifierKey = false;
    if (editorConf.multiCursorModifier === "ctrlCmd") {
      modifierKey = e.altKey;
    } else {
      if ($m) {
        modifierKey = e.metaKey;
      } else {
        modifierKey = e.ctrlKey;
      }
    }
    return modifierKey;
  }
  pc(event) {
    const elements = event.elements;
    if (elements.length > 1) {
      this.L.set(elements.map((element) => $4S(element.remoteHost, element.remotePort)));
    } else {
      this.L.set(void 0);
    }
  }
  qc(event, actionRunner) {
    if (event.element !== void 0 && !(event.element instanceof TunnelItem)) {
      return;
    }
    event.browserEvent.preventDefault();
    event.browserEvent.stopPropagation();
    const node = event.element;
    if (node) {
      this.f?.setFocus([this.f.indexOf(node)]);
      this.h.set(node.tunnelType);
      this.j.set(!!node.closeable);
      this.m.set(node.privacy.id);
      this.r.set(node.protocol);
      this.ab.set(!!node.localPort);
    } else {
      this.h.set(TunnelType.Add);
      this.j.set(false);
      this.m.set(void 0);
      this.r.set(void 0);
      this.ab.set(false);
    }
    this.zb.showContextMenu({
      menuId: $bJ.TunnelContext,
      menuActionOptions: { shouldForwardArgs: true },
      contextKeyService: this.f?.contextKeyService,
      getAnchor: () => event.anchor,
      getActionViewItem: (action) => {
        const keybinding = this.yb.lookupKeybinding(action.id);
        if (keybinding) {
          return new $U1(action, action, { label: true, keybinding: keybinding.getLabel() });
        }
        return void 0;
      },
      onHide: (wasCancelled) => {
        if (wasCancelled) {
          this.f?.domFocus();
        }
      },
      getActionsContext: () => node?.strip(),
      actionRunner
    });
  }
  rc(e) {
    if (!e.element) {
      this.fc.executeCommand(ForwardPortAction.INLINE_ID);
    }
  }
  X(height, width2) {
    this.sc = height;
    this.tc = width2;
    super.X(height, width2);
    this.f?.layout(height, width2);
  }
};
$EUb = $EUb_1 = __decorate([
  __param(2, $Ty),
  __param(3, $50),
  __param(4, $on),
  __param(5, $kl),
  __param(6, $Pk),
  __param(7, $$M),
  __param(8, $O4),
  __param(9, $1M),
  __param(10, $sn),
  __param(11, $cJ),
  __param(12, $gs),
  __param(13, $8Sb),
  __param(14, $zv),
  __param(15, $5$),
  __param(16, $tC),
  __param(17, $40)
], $EUb);
var $FUb = class {
  constructor(viewModel, environmentService) {
    this.id = $EUb.ID;
    this.name = $EUb.TITLE;
    this.canToggleVisibility = true;
    this.hideByDefault = false;
    this.group = "details@0";
    this.order = -500;
    this.canMoveView = true;
    this.containerIcon = $rUb;
    this.ctorDescriptor = new $Nk($EUb, [viewModel]);
    this.remoteAuthority = environmentService.remoteAuthority ? environmentService.remoteAuthority.split("+")[0] : void 0;
  }
};
function isITunnelItem(item) {
  return item && item.tunnelType && item.remoteHost && item.source;
}
var LabelTunnelAction;
(function(LabelTunnelAction2) {
  LabelTunnelAction2.ID = "remote.tunnel.label";
  LabelTunnelAction2.LABEL = localize(9223, null);
  LabelTunnelAction2.COMMAND_ID_KEYWORD = "label";
  function handler() {
    return async (accessor, arg) => {
      const remoteExplorerService = accessor.get($8Sb);
      let tunnelContext;
      if (isITunnelItem(arg)) {
        tunnelContext = arg;
      } else {
        const context = accessor.get($on).getContextKeyValue(TunnelViewSelectionKeyName);
        const tunnel = context ? remoteExplorerService.tunnelModel.forwarded.get(context) : void 0;
        if (tunnel) {
          const tunnelService = accessor.get($tC);
          tunnelContext = TunnelItem.createFromTunnel(remoteExplorerService, tunnelService, tunnel);
        }
      }
      if (tunnelContext) {
        const tunnelItem = tunnelContext;
        return new Promise((resolve) => {
          const startingValue = tunnelItem.name ? tunnelItem.name : `${tunnelItem.remotePort}`;
          remoteExplorerService.setEditable(tunnelItem, TunnelEditId.Label, {
            onFinish: async (value, success) => {
              value = value.trim();
              remoteExplorerService.setEditable(tunnelItem, TunnelEditId.Label, null);
              const changed = success && value !== startingValue;
              if (changed) {
                await remoteExplorerService.tunnelModel.name(tunnelItem.remoteHost, tunnelItem.remotePort, value);
              }
              resolve(changed ? { port: tunnelItem.remotePort, label: value } : void 0);
            },
            validationMessage: () => null,
            placeholder: localize(9224, null),
            startingValue
          });
        });
      }
      return void 0;
    };
  }
  LabelTunnelAction2.handler = handler;
})(LabelTunnelAction || (LabelTunnelAction = {}));
var invalidPortString = localize(9225, null);
var maxPortNumber = 65536;
var invalidPortNumberString = localize(9226, null, maxPortNumber);
var requiresSudoString = localize(9227, null);
var alreadyForwarded = localize(9228, null);
var ForwardPortAction;
(function(ForwardPortAction2) {
  ForwardPortAction2.INLINE_ID = "remote.tunnel.forwardInline";
  ForwardPortAction2.COMMANDPALETTE_ID = "remote.tunnel.forwardCommandPalette";
  ForwardPortAction2.LABEL = localize2(9254, "Forward a Port");
  ForwardPortAction2.TREEITEM_LABEL = localize(9229, null);
  const forwardPrompt = localize(9230, null);
  function validateInput(remoteExplorerService, tunnelService, value, canElevate) {
    const parsed = $YS(value);
    if (!parsed) {
      return { content: invalidPortString, severity: Severity2.Error };
    } else if (parsed.port >= maxPortNumber) {
      return { content: invalidPortNumberString, severity: Severity2.Error };
    } else if (canElevate && tunnelService.isPortPrivileged(parsed.port)) {
      return { content: requiresSudoString, severity: Severity2.Info };
    } else if ($3S(remoteExplorerService.tunnelModel.forwarded, parsed.host, parsed.port)) {
      return { content: alreadyForwarded, severity: Severity2.Error };
    }
    return null;
  }
  function error(notificationService, tunnelOrError, host, port) {
    if (!tunnelOrError) {
      notificationService.warn(localize(9231, null, host, port));
    } else if (typeof tunnelOrError === "string") {
      notificationService.warn(localize(9232, null, host, port, tunnelOrError));
    }
  }
  function inlineHandler() {
    return async (accessor, arg) => {
      const remoteExplorerService = accessor.get($8Sb);
      const notificationService = accessor.get($PJ);
      const tunnelService = accessor.get($tC);
      remoteExplorerService.setEditable(void 0, TunnelEditId.New, {
        onFinish: async (value, success) => {
          remoteExplorerService.setEditable(void 0, TunnelEditId.New, null);
          let parsed;
          if (success && (parsed = $YS(value))) {
            remoteExplorerService.forward({
              remote: { host: parsed.host, port: parsed.port },
              elevateIfNeeded: true
            }).then((tunnelOrError) => error(notificationService, tunnelOrError, parsed.host, parsed.port));
          }
        },
        validationMessage: (value) => validateInput(remoteExplorerService, tunnelService, value, tunnelService.canElevate),
        placeholder: forwardPrompt
      });
    };
  }
  ForwardPortAction2.inlineHandler = inlineHandler;
  function commandPaletteHandler() {
    return async (accessor, arg) => {
      const remoteExplorerService = accessor.get($8Sb);
      const notificationService = accessor.get($PJ);
      const viewsService = accessor.get($uob);
      const quickInputService = accessor.get($1M);
      const tunnelService = accessor.get($tC);
      await viewsService.openView($EUb.ID, true);
      const value = await quickInputService.input({
        prompt: forwardPrompt,
        validateInput: (value2) => Promise.resolve(validateInput(remoteExplorerService, tunnelService, value2, tunnelService.canElevate))
      });
      let parsed;
      if (value && (parsed = $YS(value))) {
        remoteExplorerService.forward({
          remote: { host: parsed.host, port: parsed.port },
          elevateIfNeeded: true
        }).then((tunnel) => error(notificationService, tunnel, parsed.host, parsed.port));
      }
    };
  }
  ForwardPortAction2.commandPaletteHandler = commandPaletteHandler;
})(ForwardPortAction || (ForwardPortAction = {}));
function makeTunnelPicks(tunnels, remoteExplorerService, tunnelService) {
  const picks = tunnels.map((forwarded) => {
    const item = TunnelItem.createFromTunnel(remoteExplorerService, tunnelService, forwarded);
    return {
      label: item.label,
      description: item.processDescription,
      tunnel: item
    };
  });
  if (picks.length === 0) {
    picks.push({
      label: localize(9233, null, ForwardPortAction.LABEL.value)
    });
  }
  return picks;
}
var ClosePortAction;
(function(ClosePortAction2) {
  ClosePortAction2.INLINE_ID = "remote.tunnel.closeInline";
  ClosePortAction2.COMMANDPALETTE_ID = "remote.tunnel.closeCommandPalette";
  ClosePortAction2.LABEL = localize2(9255, "Stop Forwarding Port");
  function inlineHandler() {
    return async (accessor, arg) => {
      const contextKeyService = accessor.get($on);
      const remoteExplorerService = accessor.get($8Sb);
      let ports = [];
      const multiSelectContext = contextKeyService.getContextKeyValue(TunnelViewMultiSelectionKeyName);
      if (multiSelectContext) {
        multiSelectContext.forEach((context) => {
          const tunnel = remoteExplorerService.tunnelModel.forwarded.get(context);
          if (tunnel) {
            ports?.push(tunnel);
          }
        });
      } else if (isITunnelItem(arg)) {
        ports = [arg];
      } else {
        const context = contextKeyService.getContextKeyValue(TunnelViewSelectionKeyName);
        const tunnel = context ? remoteExplorerService.tunnelModel.forwarded.get(context) : void 0;
        if (tunnel) {
          ports = [tunnel];
        }
      }
      if (!ports || ports.length === 0) {
        return;
      }
      return Promise.all(ports.map((port) => remoteExplorerService.close({ host: port.remoteHost, port: port.remotePort }, TunnelCloseReason.User)));
    };
  }
  ClosePortAction2.inlineHandler = inlineHandler;
  function commandPaletteHandler() {
    return async (accessor) => {
      const quickInputService = accessor.get($1M);
      const remoteExplorerService = accessor.get($8Sb);
      const tunnelService = accessor.get($tC);
      const commandService = accessor.get($sn);
      const picks = makeTunnelPicks(Array.from(remoteExplorerService.tunnelModel.forwarded.values()).filter((tunnel) => tunnel.closeable), remoteExplorerService, tunnelService);
      const result = await quickInputService.pick(picks, { placeHolder: localize(9234, null) });
      if (result && result.tunnel) {
        await remoteExplorerService.close({ host: result.tunnel.remoteHost, port: result.tunnel.remotePort }, TunnelCloseReason.User);
      } else if (result) {
        await commandService.executeCommand(ForwardPortAction.COMMANDPALETTE_ID);
      }
    };
  }
  ClosePortAction2.commandPaletteHandler = commandPaletteHandler;
})(ClosePortAction || (ClosePortAction = {}));
var OpenPortInBrowserAction;
(function(OpenPortInBrowserAction2) {
  OpenPortInBrowserAction2.ID = "remote.tunnel.open";
  OpenPortInBrowserAction2.LABEL = localize(9235, null);
  function handler() {
    return async (accessor, arg) => {
      let key2;
      if (isITunnelItem(arg)) {
        key2 = $4S(arg.remoteHost, arg.remotePort);
      } else if (arg.tunnelRemoteHost && arg.tunnelRemotePort) {
        key2 = $4S(arg.tunnelRemoteHost, arg.tunnelRemotePort);
      }
      if (key2) {
        const model = accessor.get($8Sb).tunnelModel;
        const openerService = accessor.get($O4);
        return run(model, openerService, key2);
      }
    };
  }
  OpenPortInBrowserAction2.handler = handler;
  function run(model, openerService, key2) {
    const tunnel = model.forwarded.get(key2) || model.detected.get(key2);
    if (tunnel) {
      return openerService.open(tunnel.localUri, { allowContributedOpeners: false });
    }
    return Promise.resolve();
  }
  OpenPortInBrowserAction2.run = run;
})(OpenPortInBrowserAction || (OpenPortInBrowserAction = {}));
var OpenPortInPreviewAction;
(function(OpenPortInPreviewAction2) {
  OpenPortInPreviewAction2.ID = "remote.tunnel.openPreview";
  OpenPortInPreviewAction2.LABEL = localize(9236, null);
  function handler() {
    return async (accessor, arg) => {
      let key2;
      if (isITunnelItem(arg)) {
        key2 = $4S(arg.remoteHost, arg.remotePort);
      } else if (arg.tunnelRemoteHost && arg.tunnelRemotePort) {
        key2 = $4S(arg.tunnelRemoteHost, arg.tunnelRemotePort);
      }
      if (key2) {
        const model = accessor.get($8Sb).tunnelModel;
        const openerService = accessor.get($O4);
        const externalOpenerService = accessor.get($MRb);
        return run(model, openerService, externalOpenerService, key2);
      }
    };
  }
  OpenPortInPreviewAction2.handler = handler;
  async function run(model, openerService, externalOpenerService, key2) {
    const tunnel = model.forwarded.get(key2) || model.detected.get(key2);
    if (tunnel) {
      const remoteHost = tunnel.remoteHost.includes(":") ? `[${tunnel.remoteHost}]` : tunnel.remoteHost;
      const sourceUri = URI.parse(`http://${remoteHost}:${tunnel.remotePort}`);
      const opener = await externalOpenerService.getOpener(tunnel.localUri, { sourceUri }, CancellationToken.None);
      if (opener) {
        return opener.openExternalUri(tunnel.localUri, { sourceUri }, CancellationToken.None);
      }
      return openerService.open(tunnel.localUri);
    }
    return Promise.resolve();
  }
  OpenPortInPreviewAction2.run = run;
})(OpenPortInPreviewAction || (OpenPortInPreviewAction = {}));
var OpenPortInBrowserCommandPaletteAction;
(function(OpenPortInBrowserCommandPaletteAction2) {
  OpenPortInBrowserCommandPaletteAction2.ID = "remote.tunnel.openCommandPalette";
  OpenPortInBrowserCommandPaletteAction2.LABEL = localize(9237, null);
  function handler() {
    return async (accessor, arg) => {
      const remoteExplorerService = accessor.get($8Sb);
      const tunnelService = accessor.get($tC);
      const model = remoteExplorerService.tunnelModel;
      const quickPickService = accessor.get($1M);
      const openerService = accessor.get($O4);
      const commandService = accessor.get($sn);
      const options3 = [...model.forwarded, ...model.detected].map((value) => {
        const tunnelItem = TunnelItem.createFromTunnel(remoteExplorerService, tunnelService, value[1]);
        return {
          label: tunnelItem.label,
          description: tunnelItem.processDescription,
          tunnel: tunnelItem
        };
      });
      if (options3.length === 0) {
        options3.push({
          label: localize(9238, null)
        });
      } else {
        options3.push({
          label: localize(9239, null)
        });
      }
      const picked = await quickPickService.pick(options3, { placeHolder: localize(9240, null) });
      if (picked && picked.tunnel) {
        return OpenPortInBrowserAction.run(model, openerService, $4S(picked.tunnel.remoteHost, picked.tunnel.remotePort));
      } else if (picked) {
        return commandService.executeCommand(`${$0Sb}.focus`);
      }
    };
  }
  OpenPortInBrowserCommandPaletteAction2.handler = handler;
})(OpenPortInBrowserCommandPaletteAction || (OpenPortInBrowserCommandPaletteAction = {}));
var CopyAddressAction;
(function(CopyAddressAction2) {
  CopyAddressAction2.INLINE_ID = "remote.tunnel.copyAddressInline";
  CopyAddressAction2.COMMANDPALETTE_ID = "remote.tunnel.copyAddressCommandPalette";
  CopyAddressAction2.INLINE_LABEL = localize(9241, null);
  CopyAddressAction2.COMMANDPALETTE_LABEL = localize(9242, null);
  async function copyAddress(remoteExplorerService, clipboardService, tunnelItem) {
    const address = remoteExplorerService.tunnelModel.address(tunnelItem.remoteHost, tunnelItem.remotePort);
    if (address) {
      await clipboardService.writeText(address.toString());
    }
  }
  function inlineHandler() {
    return async (accessor, arg) => {
      const remoteExplorerService = accessor.get($8Sb);
      let tunnelItem;
      if (isITunnelItem(arg)) {
        tunnelItem = arg;
      } else {
        const context = accessor.get($on).getContextKeyValue(TunnelViewSelectionKeyName);
        tunnelItem = context ? remoteExplorerService.tunnelModel.forwarded.get(context) : void 0;
      }
      if (tunnelItem) {
        return copyAddress(remoteExplorerService, accessor.get($30), tunnelItem);
      }
    };
  }
  CopyAddressAction2.inlineHandler = inlineHandler;
  function commandPaletteHandler() {
    return async (accessor, arg) => {
      const quickInputService = accessor.get($1M);
      const remoteExplorerService = accessor.get($8Sb);
      const tunnelService = accessor.get($tC);
      const commandService = accessor.get($sn);
      const clipboardService = accessor.get($30);
      const tunnels = Array.from(remoteExplorerService.tunnelModel.forwarded.values()).concat(Array.from(remoteExplorerService.tunnelModel.detected.values()));
      const result = await quickInputService.pick(makeTunnelPicks(tunnels, remoteExplorerService, tunnelService), { placeHolder: localize(9243, null) });
      if (result && result.tunnel) {
        await copyAddress(remoteExplorerService, clipboardService, result.tunnel);
      } else if (result) {
        await commandService.executeCommand(ForwardPortAction.COMMANDPALETTE_ID);
      }
    };
  }
  CopyAddressAction2.commandPaletteHandler = commandPaletteHandler;
})(CopyAddressAction || (CopyAddressAction = {}));
var ChangeLocalPortAction;
(function(ChangeLocalPortAction2) {
  ChangeLocalPortAction2.ID = "remote.tunnel.changeLocalPort";
  ChangeLocalPortAction2.LABEL = localize(9244, null);
  function validateInput(tunnelService, value, canElevate) {
    if (!value.match(/^[0-9]+$/)) {
      return { content: localize(9245, null), severity: Severity2.Error };
    } else if (Number(value) >= maxPortNumber) {
      return { content: invalidPortNumberString, severity: Severity2.Error };
    } else if (canElevate && tunnelService.isPortPrivileged(Number(value))) {
      return { content: requiresSudoString, severity: Severity2.Info };
    }
    return null;
  }
  function handler() {
    return async (accessor, arg) => {
      const remoteExplorerService = accessor.get($8Sb);
      const notificationService = accessor.get($PJ);
      const tunnelService = accessor.get($tC);
      let tunnelContext;
      if (isITunnelItem(arg)) {
        tunnelContext = arg;
      } else {
        const context = accessor.get($on).getContextKeyValue(TunnelViewSelectionKeyName);
        const tunnel = context ? remoteExplorerService.tunnelModel.forwarded.get(context) : void 0;
        if (tunnel) {
          const tunnelService2 = accessor.get($tC);
          tunnelContext = TunnelItem.createFromTunnel(remoteExplorerService, tunnelService2, tunnel);
        }
      }
      if (tunnelContext) {
        const tunnelItem = tunnelContext;
        remoteExplorerService.setEditable(tunnelItem, TunnelEditId.LocalPort, {
          onFinish: async (value, success) => {
            remoteExplorerService.setEditable(tunnelItem, TunnelEditId.LocalPort, null);
            if (success) {
              await remoteExplorerService.close({ host: tunnelItem.remoteHost, port: tunnelItem.remotePort }, TunnelCloseReason.Other);
              const numberValue = Number(value);
              const newForward = await remoteExplorerService.forward({
                remote: { host: tunnelItem.remoteHost, port: tunnelItem.remotePort },
                local: numberValue,
                name: tunnelItem.name,
                elevateIfNeeded: true,
                source: tunnelItem.source
              });
              if (newForward && typeof newForward !== "string" && newForward.tunnelLocalPort !== numberValue) {
                notificationService.warn(localize(9246, null, value, newForward.tunnelLocalPort ?? newForward.localAddress));
              }
            }
          },
          validationMessage: (value) => validateInput(tunnelService, value, tunnelService.canElevate),
          placeholder: localize(9247, null)
        });
      }
    };
  }
  ChangeLocalPortAction2.handler = handler;
})(ChangeLocalPortAction || (ChangeLocalPortAction = {}));
var ChangeTunnelPrivacyAction;
(function(ChangeTunnelPrivacyAction2) {
  function handler(privacyId) {
    return async (accessor, arg) => {
      if (isITunnelItem(arg)) {
        const remoteExplorerService = accessor.get($8Sb);
        await remoteExplorerService.close({ host: arg.remoteHost, port: arg.remotePort }, TunnelCloseReason.Other);
        return remoteExplorerService.forward({
          remote: { host: arg.remoteHost, port: arg.remotePort },
          local: arg.localPort,
          name: arg.name,
          elevateIfNeeded: true,
          privacy: privacyId,
          source: arg.source
        });
      }
      return void 0;
    };
  }
  ChangeTunnelPrivacyAction2.handler = handler;
})(ChangeTunnelPrivacyAction || (ChangeTunnelPrivacyAction = {}));
var SetTunnelProtocolAction;
(function(SetTunnelProtocolAction2) {
  SetTunnelProtocolAction2.ID_HTTP = "remote.tunnel.setProtocolHttp";
  SetTunnelProtocolAction2.ID_HTTPS = "remote.tunnel.setProtocolHttps";
  SetTunnelProtocolAction2.LABEL_HTTP = localize(9248, null);
  SetTunnelProtocolAction2.LABEL_HTTPS = localize(9249, null);
  async function handler(arg, protocol, remoteExplorerService, environmentService) {
    if (isITunnelItem(arg)) {
      const attributes = {
        protocol
      };
      const target = environmentService.remoteAuthority ? 4 : 3;
      return remoteExplorerService.tunnelModel.configPortsAttributes.addAttributes(arg.remotePort, attributes, target);
    }
  }
  function handlerHttp() {
    return async (accessor, arg) => {
      return handler(arg, TunnelProtocol.Http, accessor.get($8Sb), accessor.get($US));
    };
  }
  SetTunnelProtocolAction2.handlerHttp = handlerHttp;
  function handlerHttps() {
    return async (accessor, arg) => {
      return handler(arg, TunnelProtocol.Https, accessor.get($8Sb), accessor.get($US));
    };
  }
  SetTunnelProtocolAction2.handlerHttps = handlerHttps;
})(SetTunnelProtocolAction || (SetTunnelProtocolAction = {}));
var tunnelViewCommandsWeightBonus = 10;
var isForwardedExpr = TunnelTypeContextKey.isEqualTo(TunnelType.Forwarded);
var isForwardedOrDetectedExpr = $7m.or(isForwardedExpr, TunnelTypeContextKey.isEqualTo(TunnelType.Detected));
var isNotMultiSelectionExpr = TunnelViewMultiSelectionContextKey.isEqualTo(void 0);
$0I.registerCommandAndKeybindingRule({
  id: LabelTunnelAction.ID,
  weight: 200 + tunnelViewCommandsWeightBonus,
  when: $7m.and(TunnelViewFocusContextKey, isForwardedExpr, isNotMultiSelectionExpr),
  primary: 60,
  mac: {
    primary: 3
    /* KeyCode.Enter */
  },
  handler: LabelTunnelAction.handler()
});
$tn.registerCommand(ForwardPortAction.INLINE_ID, ForwardPortAction.inlineHandler());
$tn.registerCommand(ForwardPortAction.COMMANDPALETTE_ID, ForwardPortAction.commandPaletteHandler());
$0I.registerCommandAndKeybindingRule({
  id: ClosePortAction.INLINE_ID,
  weight: 200 + tunnelViewCommandsWeightBonus,
  when: $7m.and(TunnelCloseableContextKey, TunnelViewFocusContextKey),
  primary: 20,
  mac: {
    primary: 2048 | 1,
    secondary: [
      20
      /* KeyCode.Delete */
    ]
  },
  handler: ClosePortAction.inlineHandler()
});
$tn.registerCommand(ClosePortAction.COMMANDPALETTE_ID, ClosePortAction.commandPaletteHandler());
$tn.registerCommand(OpenPortInBrowserAction.ID, OpenPortInBrowserAction.handler());
$tn.registerCommand(OpenPortInPreviewAction.ID, OpenPortInPreviewAction.handler());
$tn.registerCommand(OpenPortInBrowserCommandPaletteAction.ID, OpenPortInBrowserCommandPaletteAction.handler());
$0I.registerCommandAndKeybindingRule({
  id: CopyAddressAction.INLINE_ID,
  weight: 200 + tunnelViewCommandsWeightBonus,
  when: $7m.and(TunnelViewFocusContextKey, isForwardedOrDetectedExpr, isNotMultiSelectionExpr),
  primary: 2048 | 33,
  handler: CopyAddressAction.inlineHandler()
});
$tn.registerCommand(CopyAddressAction.COMMANDPALETTE_ID, CopyAddressAction.commandPaletteHandler());
$tn.registerCommand(ChangeLocalPortAction.ID, ChangeLocalPortAction.handler());
$tn.registerCommand(SetTunnelProtocolAction.ID_HTTP, SetTunnelProtocolAction.handlerHttp());
$tn.registerCommand(SetTunnelProtocolAction.ID_HTTPS, SetTunnelProtocolAction.handlerHttps());
$dJ.appendMenuItem($bJ.CommandPalette, {
  command: {
    id: ClosePortAction.COMMANDPALETTE_ID,
    title: ClosePortAction.LABEL
  },
  when: $XS
});
$dJ.appendMenuItem($bJ.CommandPalette, {
  command: {
    id: ForwardPortAction.COMMANDPALETTE_ID,
    title: ForwardPortAction.LABEL
  },
  when: $XS
});
$dJ.appendMenuItem($bJ.CommandPalette, {
  command: {
    id: CopyAddressAction.COMMANDPALETTE_ID,
    title: CopyAddressAction.COMMANDPALETTE_LABEL
  },
  when: $XS
});
$dJ.appendMenuItem($bJ.CommandPalette, {
  command: {
    id: OpenPortInBrowserCommandPaletteAction.ID,
    title: OpenPortInBrowserCommandPaletteAction.LABEL
  },
  when: $XS
});
$dJ.appendMenuItem($bJ.TunnelContext, {
  group: "._open",
  order: 0,
  command: {
    id: OpenPortInBrowserAction.ID,
    title: OpenPortInBrowserAction.LABEL
  },
  when: $7m.and(isForwardedOrDetectedExpr, isNotMultiSelectionExpr)
});
$dJ.appendMenuItem($bJ.TunnelContext, {
  group: "._open",
  order: 1,
  command: {
    id: OpenPortInPreviewAction.ID,
    title: OpenPortInPreviewAction.LABEL
  },
  when: $7m.and(isForwardedOrDetectedExpr, isNotMultiSelectionExpr)
});
$dJ.appendMenuItem($bJ.TunnelContext, {
  group: "0_manage",
  order: 1,
  command: {
    id: LabelTunnelAction.ID,
    title: LabelTunnelAction.LABEL,
    icon: $zUb
  },
  when: $7m.and(isForwardedExpr, isNotMultiSelectionExpr)
});
$dJ.appendMenuItem($bJ.TunnelContext, {
  group: "2_localaddress",
  order: 0,
  command: {
    id: CopyAddressAction.INLINE_ID,
    title: CopyAddressAction.INLINE_LABEL
  },
  when: $7m.and(isForwardedOrDetectedExpr, isNotMultiSelectionExpr)
});
$dJ.appendMenuItem($bJ.TunnelContext, {
  group: "2_localaddress",
  order: 1,
  command: {
    id: ChangeLocalPortAction.ID,
    title: ChangeLocalPortAction.LABEL
  },
  when: $7m.and(isForwardedExpr, PortChangableContextKey, isNotMultiSelectionExpr)
});
$dJ.appendMenuItem($bJ.TunnelContext, {
  group: "2_localaddress",
  order: 2,
  submenu: $bJ.TunnelPrivacy,
  title: localize(9250, null),
  when: $7m.and(isForwardedExpr, TunnelPrivacyEnabledContextKey)
});
$dJ.appendMenuItem($bJ.TunnelContext, {
  group: "2_localaddress",
  order: 3,
  submenu: $bJ.TunnelProtocol,
  title: localize(9251, null),
  when: $7m.and(isForwardedExpr, isNotMultiSelectionExpr, ProtocolChangeableContextKey)
});
$dJ.appendMenuItem($bJ.TunnelContext, {
  group: "3_forward",
  order: 0,
  command: {
    id: ClosePortAction.INLINE_ID,
    title: ClosePortAction.LABEL
  },
  when: TunnelCloseableContextKey
});
$dJ.appendMenuItem($bJ.TunnelContext, {
  group: "3_forward",
  order: 1,
  command: {
    id: ForwardPortAction.INLINE_ID,
    title: ForwardPortAction.LABEL
  }
});
$dJ.appendMenuItem($bJ.TunnelProtocol, {
  order: 0,
  command: {
    id: SetTunnelProtocolAction.ID_HTTP,
    title: SetTunnelProtocolAction.LABEL_HTTP,
    toggled: TunnelProtocolContextKey.isEqualTo(TunnelProtocol.Http)
  }
});
$dJ.appendMenuItem($bJ.TunnelProtocol, {
  order: 1,
  command: {
    id: SetTunnelProtocolAction.ID_HTTPS,
    title: SetTunnelProtocolAction.LABEL_HTTPS,
    toggled: TunnelProtocolContextKey.isEqualTo(TunnelProtocol.Https)
  }
});
$dJ.appendMenuItem($bJ.TunnelPortInline, {
  group: "0_manage",
  order: 0,
  command: {
    id: ForwardPortAction.INLINE_ID,
    title: ForwardPortAction.TREEITEM_LABEL,
    icon: $uUb
  },
  when: TunnelTypeContextKey.isEqualTo(TunnelType.Candidate)
});
$dJ.appendMenuItem($bJ.TunnelPortInline, {
  group: "0_manage",
  order: 4,
  command: {
    id: LabelTunnelAction.ID,
    title: LabelTunnelAction.LABEL,
    icon: $zUb
  },
  when: isForwardedExpr
});
$dJ.appendMenuItem($bJ.TunnelPortInline, {
  group: "0_manage",
  order: 5,
  command: {
    id: ClosePortAction.INLINE_ID,
    title: ClosePortAction.LABEL,
    icon: $vUb
  },
  when: TunnelCloseableContextKey
});
$dJ.appendMenuItem($bJ.TunnelLocalAddressInline, {
  order: -1,
  command: {
    id: CopyAddressAction.INLINE_ID,
    title: CopyAddressAction.INLINE_LABEL,
    icon: $yUb
  },
  when: isForwardedOrDetectedExpr
});
$dJ.appendMenuItem($bJ.TunnelLocalAddressInline, {
  order: 0,
  command: {
    id: OpenPortInBrowserAction.ID,
    title: OpenPortInBrowserAction.LABEL,
    icon: $wUb
  },
  when: isForwardedOrDetectedExpr
});
$dJ.appendMenuItem($bJ.TunnelLocalAddressInline, {
  order: 1,
  command: {
    id: OpenPortInPreviewAction.ID,
    title: OpenPortInPreviewAction.LABEL,
    icon: $xUb
  },
  when: isForwardedOrDetectedExpr
});
$5n("ports.iconRunningProcessForeground", $Fnb, localize(9252, null));

// out-build/vs/workbench/contrib/remote/browser/urlFinder.js
var $GUb = class _$GUb extends $3c {
  static {
    this.a = /\b\w{0,20}(?::\/\/)?(?:localhost|127\.0\.0\.1|0\.0\.0\.0|:\d{2,5})[\w\-\.\~:\/\?\#[\]\@!\$&\(\)\*\+\,\;\=]*/gim;
  }
  static {
    this.b = /(localhost|127\.0\.0\.1|0\.0\.0\.0):(\d{1,5})/;
  }
  static {
    this.c = /HTTP\son\s(127\.0\.0\.1|0\.0\.0\.0)\sport\s(\d+)/;
  }
  static {
    this.f = ["Dev Containers"];
  }
  constructor(terminalService, debugService) {
    super();
    this.g = new $ze();
    this.onDidMatchLocalUrl = this.g.event;
    this.h = /* @__PURE__ */ new Map();
    this.m = /* @__PURE__ */ new Map();
    terminalService.instances.forEach((instance2) => {
      this.j(instance2);
    });
    this.B(terminalService.onDidCreateInstance((instance2) => {
      this.j(instance2);
    }));
    this.B(terminalService.onDidDisposeInstance((instance2) => {
      this.h.get(instance2)?.dispose();
      this.h.delete(instance2);
    }));
    this.B(debugService.onDidNewSession((session) => {
      if (!session.parentSession || session.parentSession && session.hasSeparateRepl()) {
        this.h.set(session.getId(), session.onDidChangeReplElements(() => {
          this.n(session);
        }));
      }
    }));
    this.B(debugService.onDidEndSession(({ session }) => {
      if (this.h.has(session.getId())) {
        this.h.get(session.getId())?.dispose();
        this.h.delete(session.getId());
      }
    }));
  }
  j(instance2) {
    if (!_$GUb.f.includes(instance2.title)) {
      this.h.set(instance2, instance2.onData((data) => {
        this.r(data);
      }));
    }
  }
  n(session) {
    const oldReplPosition = this.m.get(session.getId());
    const replElements = session.getReplElements();
    this.m.set(session.getId(), { position: replElements.length - 1, tail: replElements[replElements.length - 1] });
    if (!oldReplPosition && replElements.length > 0) {
      replElements.forEach((element) => this.r(element.toString()));
    } else if (oldReplPosition && replElements.length - 1 !== oldReplPosition.position) {
      for (let i2 = replElements.length - 1; i2 >= 0; i2--) {
        const element = replElements[i2];
        if (element === oldReplPosition.tail) {
          break;
        } else {
          this.r(element.toString());
        }
      }
    }
  }
  dispose() {
    super.dispose();
    const listeners = this.h.values();
    for (const listener of listeners) {
      listener.dispose();
    }
  }
  r(data) {
    data = $kg(data);
    const urlMatches = data.match(_$GUb.a) || [];
    if (urlMatches && urlMatches.length > 0) {
      urlMatches.forEach((match) => {
        let serverUrl;
        try {
          serverUrl = new URL(match);
        } catch (e) {
        }
        if (serverUrl) {
          const portMatch = match.match(_$GUb.b);
          const port = parseFloat(serverUrl.port ? serverUrl.port : portMatch ? portMatch[2] : "NaN");
          if (!isNaN(port) && Number.isInteger(port) && port > 0 && port <= 65535) {
            let host = serverUrl.hostname;
            if (host !== "0.0.0.0" && host !== "127.0.0.1") {
              host = "localhost";
            }
            if (port !== 9229 && data.startsWith("Debugger listening on")) {
              return;
            }
            this.g.fire({ port, host });
          }
        }
      });
    } else {
      const pythonMatch = data.match(_$GUb.c);
      if (pythonMatch && pythonMatch.length === 3) {
        this.g.fire({ host: pythonMatch[1], port: Number(pythonMatch[2]) });
      }
    }
  }
};

// out-build/vs/workbench/contrib/remote/browser/remoteExplorer.js
var $HUb = "workbench.view.remote";
var $IUb = class $IUb2 extends $3c {
  constructor(h3, j, m, r2, s, t) {
    super();
    this.h = h3;
    this.j = j;
    this.m = m;
    this.r = r2;
    this.s = s;
    this.t = t;
    this.c = this.B(new $4c());
    this.f = this.B(new $4c());
    this.B($Wn.as(Extensions5.ViewsRegistry).registerViewWelcomeContent($0Sb, {
      content: this.j.remoteAuthority ? localize(9135, null, `command:${ForwardPortAction.INLINE_ID}`) : localize(9136, null, `command:${ForwardPortAction.INLINE_ID}`)
    }));
    this.y();
    this.w();
  }
  async u() {
    return $Wn.as(Extensions5.ViewContainersRegistry).registerViewContainer(
      {
        id: $$Sb,
        title: localize2(9150, "Ports"),
        icon: $rUb,
        ctorDescriptor: new $Nk($oqb, [$$Sb, { mergeViewWithContainerWhenSingleView: true }]),
        storageId: $$Sb,
        hideIfEmpty: true,
        order: 5
      },
      1
      /* ViewContainerLocation.Panel */
    );
  }
  async w() {
    this.c.clear();
    const featuresEnabled = !!$WS.getValue(this.h);
    const viewEnabled = !!$XS.getValue(this.h);
    if (featuresEnabled || viewEnabled) {
      if (!viewEnabled) {
        this.h.createKey($XS.key, true);
      }
      const viewContainer5 = await this.u();
      const tunnelPanelDescriptor = new $FUb(new $DUb(this.m, this.r), this.j);
      const viewsRegistry8 = $Wn.as(Extensions5.ViewsRegistry);
      if (viewContainer5) {
        this.m.enablePortsFeatures(!featuresEnabled);
        viewsRegistry8.registerViews([tunnelPanelDescriptor], viewContainer5);
      }
    } else {
      this.c.value = this.h.onDidChangeContext((e) => {
        if (e.affectsSome(/* @__PURE__ */ new Set([...$WS.keys(), ...$XS.keys()]))) {
          this.w();
        }
      });
    }
  }
  y() {
    const disposable = $Wn.as(Extensions5.ViewsRegistry).onViewsRegistered((e) => {
      if (e.find((view) => view.views.find((viewDescriptor3) => viewDescriptor3.id === $0Sb))) {
        this.B(Event2.debounce(this.m.tunnelModel.onForwardPort, (_last, e2) => e2, 50)(() => {
          this.z();
          this.C();
        }));
        this.B(Event2.debounce(this.m.tunnelModel.onClosePort, (_last, e2) => e2, 50)(() => {
          this.z();
          this.C();
        }));
        this.z();
        this.C();
        disposable.dispose();
      }
    });
  }
  async z() {
    if (this.m.tunnelModel.forwarded.size > 0) {
      this.f.value = this.s.showViewActivity($0Sb, {
        badge: new $wqb(this.m.tunnelModel.forwarded.size, (n) => n === 1 ? localize(9137, null) : localize(9138, null, n))
      });
    } else {
      this.f.clear();
    }
  }
  C() {
    if (!this.g) {
      this.B(this.g = this.t.addEntry(this.D, "status.forwardedPorts", 0, 40));
    } else {
      this.g.update(this.D);
    }
  }
  get D() {
    let tooltip;
    const count = this.m.tunnelModel.forwarded.size + this.m.tunnelModel.detected.size;
    const text2 = `${count}`;
    if (count === 0) {
      tooltip = localize(9139, null);
    } else {
      const allTunnels = Array.from(this.m.tunnelModel.forwarded.values());
      allTunnels.push(...Array.from(this.m.tunnelModel.detected.values()));
      tooltip = localize(9140, null, allTunnels.map((forwarded) => forwarded.remotePort).join(", "));
    }
    return {
      name: localize(9141, null),
      text: `$(radio-tower) ${text2}`,
      ariaLabel: tooltip,
      tooltip,
      command: `${$0Sb}.focus`
    };
  }
};
$IUb = __decorate([
  __param(0, $on),
  __param(1, $US),
  __param(2, $8Sb),
  __param(3, $tC),
  __param(4, $vqb),
  __param(5, $$qb)
], $IUb);
var $JUb = class $JUb2 {
  constructor(c, d) {
    this.c = c;
    this.d = d;
    if (!this.c.tunnelModel.environmentTunnelsSet) {
      Event2.once(this.c.tunnelModel.onEnvironmentTunnelsSet)(async () => {
        await this.f();
      });
    } else {
      this.f();
    }
  }
  async f() {
    this.d.trace("ForwardedPorts: Doing first restore.");
    return this.c.restore();
  }
};
$JUb = __decorate([
  __param(0, $8Sb),
  __param(1, $wn)
], $JUb);
var $KUb = class $KUb2 extends $3c {
  constructor(h3, j, m, r2, s, environmentService, t, u, w, remoteAgentService, y, z, C, D, F) {
    super();
    this.h = h3;
    this.j = j;
    this.m = m;
    this.r = r2;
    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;
    if (!environmentService.remoteAuthority) {
      return;
    }
    u.whenRemoteConfigurationLoaded().then(() => remoteAgentService.getEnvironment()).then((environment) => {
      this.I(environment);
      this.B(u.onDidChangeConfiguration((e) => {
        if (e.affectsConfiguration($aTb)) {
          this.I(environment);
        } else if (e.affectsConfiguration($bTb) && !this.g) {
          this.H();
        }
      }));
    });
    if (!this.D.getBoolean("processPortForwardingFallback", 1, true)) {
      this.u.updateValue(
        $bTb,
        0,
        5
        /* ConfigurationTarget.WORKSPACE */
      );
    }
  }
  G() {
    const fallbackAt = this.u.inspect($bTb);
    if (fallbackAt.value !== void 0 && (fallbackAt.value === 0 || fallbackAt.value !== fallbackAt.defaultValue)) {
      return fallbackAt.value;
    }
    const inspectSource = this.u.inspect($aTb);
    if (inspectSource.applicationValue === $cTb || inspectSource.userValue === $cTb || inspectSource.userLocalValue === $cTb || inspectSource.userRemoteValue === $cTb || inspectSource.workspaceFolderValue === $cTb || inspectSource.workspaceValue === $cTb) {
      return 0;
    }
    return fallbackAt.value ?? 20;
  }
  H() {
    let fallbackAt = this.G();
    if (fallbackAt === 0) {
      this.g?.dispose();
      return;
    }
    if (this.c && !this.g && this.u.getValue($aTb) === $cTb) {
      this.g = this.B(this.s.tunnelModel.onForwardPort(async () => {
        fallbackAt = this.G();
        if (fallbackAt === 0) {
          this.g?.dispose();
          return;
        }
        if (Array.from(this.s.tunnelModel.forwarded.values()).filter((tunnel) => tunnel.source.source === TunnelSource.Auto).length > fallbackAt) {
          await this.u.updateValue($aTb, $eTb);
          this.j.notify({
            message: localize(9142, null),
            severity: severity_default.Warning,
            actions: {
              primary: [
                new $Um("switchBack", localize(9143, null), void 0, true, async () => {
                  await this.u.updateValue($aTb, $cTb);
                  await this.u.updateValue(
                    $bTb,
                    0,
                    5
                    /* ConfigurationTarget.WORKSPACE */
                  );
                  this.g?.dispose();
                  this.g = void 0;
                }),
                new $Um("showPortSourceSetting", localize(9144, null), void 0, true, async () => {
                  await this.F.openSettings({
                    query: "remote.autoForwardPortsSource"
                  });
                })
              ]
            }
          });
        }
      }));
    } else {
      this.g?.dispose();
      this.g = void 0;
    }
  }
  I(environment) {
    const alreadyForwarded2 = this.c?.forwarded;
    const isSwitch = this.f || this.c;
    this.c?.dispose();
    this.c = void 0;
    this.f?.dispose();
    this.f = void 0;
    if (environment?.os !== 3) {
      if (this.u.inspect($aTb).default?.value !== $dTb) {
        $Wn.as($Ht.Configuration).registerDefaultConfigurations([{ overrides: { "remote.autoForwardPortsSource": $dTb } }]);
      }
      this.f = this.B(new OutputAutomaticPortForwarding(this.h, this.j, this.m, this.r, this.s, this.u, this.w, this.y, this.z, this.C, this.t, () => false));
    } else {
      const useProc = () => this.u.getValue($aTb) === $cTb;
      if (useProc()) {
        this.c = this.B(new ProcAutomaticPortForwarding(false, alreadyForwarded2, !isSwitch, this.u, this.s, this.j, this.m, this.r, this.y, this.z, this.C, this.t));
      } else if (this.u.getValue($aTb) === $eTb) {
        this.c = this.B(new ProcAutomaticPortForwarding(true, alreadyForwarded2, !isSwitch, this.u, this.s, this.j, this.m, this.r, this.y, this.z, this.C, this.t));
      }
      this.f = this.B(new OutputAutomaticPortForwarding(this.h, this.j, this.m, this.r, this.s, this.u, this.w, this.y, this.z, this.C, this.t, useProc));
    }
    this.H();
  }
};
$KUb = __decorate([
  __param(0, $4Pb),
  __param(1, $PJ),
  __param(2, $O4),
  __param(3, $MRb),
  __param(4, $8Sb),
  __param(5, $US),
  __param(6, $on),
  __param(7, $EK),
  __param(8, $0R),
  __param(9, $RL),
  __param(10, $tC),
  __param(11, $S4),
  __param(12, $wn),
  __param(13, $jv),
  __param(14, $TK)
], $KUb);
var OnAutoForwardedAction = class _OnAutoForwardedAction extends $3c {
  static {
    this.f = 5e3;
  }
  // milliseconds
  constructor(r2, s, t, u, w, y, z, C) {
    super();
    this.r = r2;
    this.s = s;
    this.t = t;
    this.u = u;
    this.w = w;
    this.y = y;
    this.z = z;
    this.C = C;
    this.m = /* @__PURE__ */ new Set();
    this.c = /* @__PURE__ */ new Date();
    this.c.setFullYear(this.c.getFullYear() - 1);
  }
  async doAction(tunnels) {
    this.z.trace(`ForwardedPorts: (OnAutoForwardedAction) Starting action for ${tunnels[0]?.tunnelRemotePort}`);
    this.j = tunnels;
    const tunnel = await this.F();
    this.z.trace(`ForwardedPorts: (OnAutoForwardedAction) Heuristic chose ${tunnel?.tunnelRemotePort}`);
    if (tunnel) {
      const allAttributes = await this.s.tunnelModel.getAttributes([{ port: tunnel.tunnelRemotePort, host: tunnel.tunnelRemoteHost }]);
      const attributes = allAttributes?.get(tunnel.tunnelRemotePort)?.onAutoForward;
      this.z.trace(`ForwardedPorts: (OnAutoForwardedAction) onAutoForward action is ${attributes}`);
      switch (attributes) {
        case OnPortForward.OpenBrowserOnce: {
          if (this.m.has(tunnel.localAddress)) {
            break;
          }
          this.m.add(tunnel.localAddress);
        }
        case OnPortForward.OpenBrowser: {
          const address = $4S(tunnel.tunnelRemoteHost, tunnel.tunnelRemotePort);
          await OpenPortInBrowserAction.run(this.s.tunnelModel, this.t, address);
          break;
        }
        case OnPortForward.OpenPreview: {
          const address = $4S(tunnel.tunnelRemoteHost, tunnel.tunnelRemotePort);
          await OpenPortInPreviewAction.run(this.s.tunnelModel, this.t, this.u, address);
          break;
        }
        case OnPortForward.Silent:
          break;
        default: {
          const elapsed = (/* @__PURE__ */ new Date()).getTime() - this.c.getTime();
          this.z.trace(`ForwardedPorts: (OnAutoForwardedAction) time elapsed since last notification ${elapsed} ms`);
          if (elapsed > _OnAutoForwardedAction.f) {
            await this.I(tunnel);
          }
        }
      }
    }
  }
  hide(removedPorts) {
    if (this.j) {
      this.j = this.j.filter((value) => !removedPorts.includes(value.tunnelRemotePort));
    }
    if (this.h && removedPorts.indexOf(this.h) >= 0) {
      this.g?.close();
    }
  }
  async F() {
    this.z.trace(`ForwardedPorts: (OnAutoForwardedAction) Starting heuristic delay`);
    if (!this.j || this.j.length === 0) {
      return;
    }
    this.j = this.j.sort((a, b) => a.tunnelRemotePort - b.tunnelRemotePort);
    const firstTunnel = this.j.shift();
    if (firstTunnel.tunnelRemotePort % 1e3 === 0) {
      this.z.trace(`ForwardedPorts: (OnAutoForwardedAction) Heuristic chose tunnel because % 1000: ${firstTunnel.tunnelRemotePort}`);
      this.D = firstTunnel;
      return firstTunnel;
    } else if (firstTunnel.tunnelRemotePort < 1e4 && firstTunnel.tunnelRemotePort !== 9229) {
      this.z.trace(`ForwardedPorts: (OnAutoForwardedAction) Heuristic chose tunnel because < 10000: ${firstTunnel.tunnelRemotePort}`);
      this.D = firstTunnel;
      return firstTunnel;
    }
    this.z.trace(`ForwardedPorts: (OnAutoForwardedAction) Waiting for "better" tunnel than ${firstTunnel.tunnelRemotePort}`);
    this.D = void 0;
    return new Promise((resolve) => {
      setTimeout(() => {
        if (this.D) {
          resolve(void 0);
        } else if (this.j?.includes(firstTunnel)) {
          resolve(firstTunnel);
        } else {
          resolve(void 0);
        }
      }, 3e3);
    });
  }
  async G(tunnel) {
    const properties = await this.s.tunnelModel.getAttributes([{ host: tunnel.tunnelRemoteHost, port: tunnel.tunnelRemotePort }], false);
    const label3 = properties?.get(tunnel.tunnelRemotePort)?.label;
    return localize(9145, null, label3 ? ` (${label3})` : "", tunnel.tunnelRemotePort);
  }
  H() {
    return localize(9146, null, `command:${$EUb.ID}.focus`);
  }
  async I(tunnel) {
    if (!await this.y.hadLastFocus()) {
      return;
    }
    this.g?.close();
    let message = await this.G(tunnel);
    const choices = [this.L(tunnel)];
    if (!$r || $CUb.getValue(this.C)) {
      choices.push(this.M(tunnel));
    }
    if (tunnel.tunnelLocalPort !== tunnel.tunnelRemotePort && this.w.canElevate && this.w.isPortPrivileged(tunnel.tunnelRemotePort)) {
      message += localize(9147, null, tunnel.tunnelRemotePort);
      choices.unshift(this.N(tunnel));
    }
    if (tunnel.privacy === TunnelPrivacyId.Private && $r && this.w.canChangePrivacy) {
      choices.push(this.J(tunnel));
    }
    message += this.H();
    this.g = this.r.prompt(severity_default.Info, message, choices, { neverShowAgain: { id: "remote.tunnelsView.autoForwardNeverShow", isSecondary: true } });
    this.h = tunnel.tunnelRemotePort;
    this.c = /* @__PURE__ */ new Date();
    this.g.onDidClose(() => {
      this.g = void 0;
      this.h = void 0;
    });
  }
  J(tunnel) {
    return {
      label: localize(9148, null),
      run: async () => {
        const oldTunnelDetails = $3S(this.s.tunnelModel.forwarded, tunnel.tunnelRemoteHost, tunnel.tunnelRemotePort);
        await this.s.close({ host: tunnel.tunnelRemoteHost, port: tunnel.tunnelRemotePort }, TunnelCloseReason.Other);
        return this.s.forward({
          remote: { host: tunnel.tunnelRemoteHost, port: tunnel.tunnelRemotePort },
          local: tunnel.tunnelLocalPort,
          name: oldTunnelDetails?.name,
          elevateIfNeeded: true,
          privacy: TunnelPrivacyId.Public,
          source: oldTunnelDetails?.source
        });
      }
    };
  }
  L(tunnel) {
    const address = $4S(tunnel.tunnelRemoteHost, tunnel.tunnelRemotePort);
    return {
      label: OpenPortInBrowserAction.LABEL,
      run: () => OpenPortInBrowserAction.run(this.s.tunnelModel, this.t, address)
    };
  }
  M(tunnel) {
    const address = $4S(tunnel.tunnelRemoteHost, tunnel.tunnelRemotePort);
    return {
      label: OpenPortInPreviewAction.LABEL,
      run: () => OpenPortInPreviewAction.run(this.s.tunnelModel, this.t, this.u, address)
    };
  }
  N(tunnel) {
    return {
      // Privileged ports are not on Windows, so it's ok to stick to just "sudo".
      label: localize(9149, null, tunnel.tunnelRemotePort),
      run: async () => {
        await this.s.close({ host: tunnel.tunnelRemoteHost, port: tunnel.tunnelRemotePort }, TunnelCloseReason.Other);
        const newTunnel = await this.s.forward({
          remote: { host: tunnel.tunnelRemoteHost, port: tunnel.tunnelRemotePort },
          local: tunnel.tunnelRemotePort,
          elevateIfNeeded: true,
          source: $1S
        });
        if (!newTunnel || typeof newTunnel === "string") {
          return;
        }
        this.g?.close();
        this.h = newTunnel.tunnelRemotePort;
        this.g = this.r.prompt(severity_default.Info, await this.G(newTunnel) + this.H(), [this.L(newTunnel), this.M(tunnel)], { neverShowAgain: { id: "remote.tunnelsView.autoForwardNeverShow", isSecondary: true } });
        this.g.onDidClose(() => {
          this.g = void 0;
          this.h = void 0;
        });
      }
    };
  }
};
var OutputAutomaticPortForwarding = class extends $3c {
  constructor(h3, notificationService, openerService, externalOpenerService, j, m, r2, tunnelService, hostService, logService, contextKeyService, privilegedOnly) {
    super();
    this.h = h3;
    this.notificationService = notificationService;
    this.openerService = openerService;
    this.externalOpenerService = externalOpenerService;
    this.j = j;
    this.m = m;
    this.r = r2;
    this.tunnelService = tunnelService;
    this.hostService = hostService;
    this.logService = logService;
    this.contextKeyService = contextKeyService;
    this.privilegedOnly = privilegedOnly;
    this.g = new OnAutoForwardedAction(notificationService, j, openerService, externalOpenerService, tunnelService, hostService, logService, contextKeyService);
    this.B(m.onDidChangeConfiguration((e) => {
      if (e.affectsConfiguration($_Sb)) {
        this.s();
      }
    }));
    this.c = this.B(this.j.onEnabledPortsFeatures(() => {
      this.s();
    }));
    this.s();
    if (m.getValue($aTb) === $eTb) {
      this.B(this.tunnelService.onTunnelClosed((tunnel) => this.g.hide([tunnel.port])));
    }
  }
  s() {
    if (this.m.getValue($_Sb)) {
      this.t();
    } else {
      this.u();
    }
  }
  t() {
    if (!this.f && this.j.portsFeaturesEnabled !== PortsEnablement.AdditionalFeatures) {
      return;
    }
    this.c?.dispose();
    this.f = this.B(new $GUb(this.h, this.r));
    this.B(this.f.onDidMatchLocalUrl(async (localUrl) => {
      if ($3S(this.j.tunnelModel.detected, localUrl.host, localUrl.port)) {
        return;
      }
      const attributes = (await this.j.tunnelModel.getAttributes([localUrl]))?.get(localUrl.port);
      if (attributes?.onAutoForward === OnPortForward.Ignore) {
        return;
      }
      if (this.privilegedOnly() && !this.tunnelService.isPortPrivileged(localUrl.port)) {
        return;
      }
      const forwarded = await this.j.forward({ remote: localUrl, source: $1S }, attributes ?? null);
      if (forwarded && typeof forwarded !== "string") {
        this.g.doAction([forwarded]);
      }
    }));
  }
  u() {
    if (this.f) {
      this.f.dispose();
      this.f = void 0;
    }
  }
};
var ProcAutomaticPortForwarding = class extends $3c {
  constructor(r2, alreadyAutoForwarded, s, t, remoteExplorerService, notificationService, openerService, externalOpenerService, tunnelService, hostService, logService, contextKeyService) {
    super();
    this.r = r2;
    this.alreadyAutoForwarded = alreadyAutoForwarded;
    this.s = s;
    this.t = t;
    this.remoteExplorerService = remoteExplorerService;
    this.notificationService = notificationService;
    this.openerService = openerService;
    this.externalOpenerService = externalOpenerService;
    this.tunnelService = tunnelService;
    this.hostService = hostService;
    this.logService = logService;
    this.contextKeyService = contextKeyService;
    this.f = /* @__PURE__ */ new Set();
    this.g = /* @__PURE__ */ new Set();
    this.j = /* @__PURE__ */ new Set();
    this.h = new OnAutoForwardedAction(notificationService, remoteExplorerService, openerService, externalOpenerService, tunnelService, hostService, logService, contextKeyService);
    alreadyAutoForwarded?.forEach((port) => this.f.add(port));
    this.u();
  }
  get forwarded() {
    return this.f;
  }
  async u() {
    if (!this.remoteExplorerService.tunnelModel.environmentTunnelsSet) {
      await new Promise((resolve) => this.remoteExplorerService.tunnelModel.onEnvironmentTunnelsSet(() => resolve()));
    }
    this.B(this.t.onDidChangeConfiguration(async (e) => {
      if (e.affectsConfiguration($_Sb)) {
        await this.w();
      }
    }));
    this.m = this.B(this.remoteExplorerService.onEnabledPortsFeatures(async () => {
      await this.w();
    }));
    this.w();
  }
  async w() {
    if (this.t.getValue($_Sb)) {
      await this.z();
    } else {
      this.y();
    }
  }
  y() {
    if (this.c) {
      this.c.dispose();
      this.c = void 0;
    }
  }
  async z() {
    if (this.c || this.remoteExplorerService.portsFeaturesEnabled !== PortsEnablement.AdditionalFeatures) {
      return;
    }
    this.m?.dispose();
    await this.C();
    if (this.t.getValue($_Sb)) {
      this.c = this.B(this.remoteExplorerService.tunnelModel.onCandidatesChanged(this.F, this));
    }
  }
  async C() {
    if (!this.s) {
      this.logService.debug(`ForwardedPorts: (ProcForwarding) Not setting initial candidates`);
      return;
    }
    let startingCandidates = this.remoteExplorerService.tunnelModel.candidatesOrUndefined;
    if (!startingCandidates) {
      await new Promise((resolve) => this.remoteExplorerService.tunnelModel.onCandidatesChanged(() => resolve()));
      startingCandidates = this.remoteExplorerService.tunnelModel.candidates;
    }
    for (const value of startingCandidates) {
      this.j.add($4S(value.host, value.port));
    }
    this.logService.debug(`ForwardedPorts: (ProcForwarding) Initial candidates set to ${startingCandidates.map((candidate) => candidate.port).join(", ")}`);
  }
  async D() {
    let attributes;
    const allTunnels = [];
    this.logService.trace(`ForwardedPorts: (ProcForwarding) Attempting to forward ${this.remoteExplorerService.tunnelModel.candidates.length} candidates`);
    for (const value of this.remoteExplorerService.tunnelModel.candidates) {
      if (!value.detail) {
        this.logService.trace(`ForwardedPorts: (ProcForwarding) Port ${value.port} missing detail`);
        continue;
      }
      if (!attributes) {
        attributes = await this.remoteExplorerService.tunnelModel.getAttributes(this.remoteExplorerService.tunnelModel.candidates);
      }
      const portAttributes = attributes?.get(value.port);
      const address = $4S(value.host, value.port);
      if (this.j.has(address) && portAttributes?.onAutoForward === void 0) {
        continue;
      }
      if (this.g.has(address) || this.f.has(address)) {
        continue;
      }
      const alreadyForwarded2 = $3S(this.remoteExplorerService.tunnelModel.forwarded, value.host, value.port);
      if ($3S(this.remoteExplorerService.tunnelModel.detected, value.host, value.port)) {
        continue;
      }
      if (portAttributes?.onAutoForward === OnPortForward.Ignore) {
        this.logService.trace(`ForwardedPorts: (ProcForwarding) Port ${value.port} is ignored`);
        continue;
      }
      const forwarded = await this.remoteExplorerService.forward({ remote: value, source: $1S }, portAttributes ?? null);
      if (!alreadyForwarded2 && forwarded) {
        this.logService.trace(`ForwardedPorts: (ProcForwarding) Port ${value.port} has been forwarded`);
        this.f.add(address);
      } else if (forwarded) {
        this.logService.trace(`ForwardedPorts: (ProcForwarding) Port ${value.port} has been notified`);
        this.g.add(address);
      }
      if (forwarded && typeof forwarded !== "string") {
        allTunnels.push(forwarded);
      }
    }
    this.logService.trace(`ForwardedPorts: (ProcForwarding) Forwarded ${allTunnels.length} candidates`);
    if (allTunnels.length === 0) {
      return void 0;
    }
    return allTunnels;
  }
  async F(removed) {
    const removedPorts = [];
    let autoForwarded;
    if (this.r) {
      autoForwarded = /* @__PURE__ */ new Map();
      for (const entry of this.remoteExplorerService.tunnelModel.forwarded.entries()) {
        if (entry[1].source.source === TunnelSource.Auto) {
          autoForwarded.set(entry[0], entry[1]);
        }
      }
    } else {
      autoForwarded = new Map(this.f.entries());
    }
    for (const removedPort of removed) {
      const key2 = removedPort[0];
      let value = removedPort[1];
      const forwardedValue = $3S(autoForwarded, value.host, value.port);
      if (forwardedValue) {
        if (typeof forwardedValue === "string") {
          this.f.delete(key2);
        } else {
          value = { host: forwardedValue.remoteHost, port: forwardedValue.remotePort };
        }
        await this.remoteExplorerService.close(value, TunnelCloseReason.AutoForwardEnd);
        removedPorts.push(value.port);
      } else if (this.g.has(key2)) {
        this.g.delete(key2);
        removedPorts.push(value.port);
      } else if (this.j.has(key2)) {
        this.j.delete(key2);
      }
    }
    if (this.r) {
      return;
    }
    if (removedPorts.length > 0) {
      await this.h.hide(removedPorts);
    }
    const tunnels = await this.D();
    if (tunnels) {
      await this.h.doAction(tunnels);
    }
  }
};

// out-build/vs/workbench/contrib/webviewView/browser/webviewViewPane.js
var $LUb_1;
var storageKeys = {
  webviewState: "webviewState"
};
var $LUb = class $LUb2 extends $_ob {
  static {
    $LUb_1 = this;
  }
  static b(storageService) {
    this.a ??= new $Frb("webviewViews.origins", storageService);
    return this.a;
  }
  constructor(options3, configurationService, contextKeyService, contextMenuService, instantiationService, keybindingService, openerService, telemetryService, hoverService, themeService, viewDescriptorService, bc, cc, dc, ec, fc, gc, hc) {
    super({ ...options3, titleMenuId: $bJ.ViewTitle, showActions: ViewPaneShowActions.WhenExpanded }, keybindingService, contextMenuService, configurationService, contextKeyService, viewDescriptorService, instantiationService, openerService, themeService, telemetryService, hoverService);
    this.bc = bc;
    this.cc = cc;
    this.dc = dc;
    this.ec = ec;
    this.fc = fc;
    this.gc = gc;
    this.hc = hc;
    this.c = this.B(new $4c());
    this.f = this.B(new $2c());
    this.g = false;
    this.t = this.B(new $4c());
    this.ic = this.B(new $ze());
    this.onDidChangeVisibility = this.ic.event;
    this.jc = this.B(new $ze());
    this.onDispose = this.jc.event;
    this.sb = options3.fromExtensionId;
    this.n = this.title;
    this.L = new $Slb(`webviewView.${this.id}`, ec);
    this.ab = this.L.getMemento(
      1,
      1
      /* StorageTarget.MACHINE */
    );
    this.B(this.onDidChangeBodyVisibility(() => this.mc()));
    this.B(this.hc.onNewResolverRegistered((e) => {
      if (e.viewType === this.id) {
        this.mc();
      }
    }));
    this.mc();
  }
  dispose() {
    this.jc.fire();
    clearTimeout(this.ac);
    super.dispose();
  }
  focus() {
    super.focus();
    this.c.value?.focus();
  }
  W(container2) {
    super.W(container2);
    this.h = container2;
    this.j = void 0;
    if (!this.m) {
      this.m = new ResizeObserver(() => {
        setTimeout(() => {
          this.sc();
        }, 0);
      });
      this.B($1c(() => {
        this.m.disconnect();
      }));
      this.m.observe(container2);
    }
  }
  saveState() {
    if (this.c.value) {
      this.ab[storageKeys.webviewState] = this.c.value.state;
    }
    this.L.saveMemento();
    super.saveState();
  }
  X(height, width2) {
    super.X(height, width2);
    this.sc(new $rj(width2, height));
  }
  mc() {
    if (this.isBodyVisible()) {
      this.nc();
      this.c.value?.claim(this, getWindow(this.element), void 0);
    } else {
      this.c.value?.release(this);
    }
  }
  nc() {
    if (this.g) {
      return;
    }
    this.g = true;
    const origin = this.sb ? $LUb_1.b(this.ec).getOrigin(this.id, this.sb) : void 0;
    const webview = this.gc.createWebviewOverlay({
      origin,
      providedViewType: this.id,
      title: this.title,
      options: {
        purpose: "webviewView"
        /* WebviewContentPurpose.WebviewView */
      },
      contentOptions: {},
      extension: this.sb ? { id: this.sb } : void 0
    });
    webview.state = this.ab[storageKeys.webviewState];
    this.c.value = webview;
    if (this.h) {
      this.sc();
    }
    this.f.add($1c(() => {
      this.c.value?.release(this);
    }));
    this.f.add(webview.onDidUpdateState(() => {
      this.ab[storageKeys.webviewState] = webview.state;
    }));
    for (const event of [$7j.DRAG, $7j.DRAG_END, $7j.DRAG_ENTER, $7j.DRAG_LEAVE, $7j.DRAG_START]) {
      this.f.add($_i(this.c.value.container, event, (e) => {
        e.preventDefault();
        e.stopImmediatePropagation();
        this.dropTargetElement.dispatchEvent(new DragEvent(e.type, e));
      }));
    }
    this.f.add(new $DJb(getWindow(this.element), () => this.c.value));
    const source = this.f.add(new $ad());
    this.qc(async () => {
      await this.cc.activateByEvent(`onView:${this.id}`);
      const self2 = this;
      const webviewView = {
        webview,
        onDidChangeVisibility: this.onDidChangeBodyVisibility,
        onDispose: this.onDispose,
        get title() {
          return self2.r;
        },
        set title(value) {
          self2.Qb(value);
        },
        get description() {
          return self2.titleDescription;
        },
        set description(value) {
          self2.Sb(value);
        },
        get badge() {
          return self2.s;
        },
        set badge(badge) {
          self2.pc(badge);
        },
        dispose: () => {
          this.g = false;
          this.c.clear();
          this.f.clear();
        },
        show: (preserveFocus) => {
          this.fc.openView(this.id, !preserveFocus);
        }
      };
      await this.hc.resolve(this.id, webviewView, source.token);
    });
  }
  Qb(value) {
    this.r = value;
    super.Qb(typeof value === "string" ? value : this.n);
  }
  pc(badge) {
    if (this.s?.value === badge?.value && this.s?.tooltip === badge?.tooltip) {
      return;
    }
    this.s = badge;
    if (badge) {
      const activity = {
        badge: new $wqb(badge.value, () => badge.tooltip),
        priority: 150
      };
      this.t.value = this.bc.showViewActivity(this.id, activity);
    }
  }
  async qc(task) {
    return this.dc.withProgress({ location: this.id, delay: 500 }, task);
  }
  onDidScrollRoot() {
    this.sc();
  }
  rc(dimension) {
    const webviewEntry = this.c.value;
    if (!this.h || !webviewEntry) {
      return;
    }
    if (!this.j || !this.j.isConnected) {
      this.j = this.tc(this.h);
    }
    webviewEntry.layoutWebviewOverElement(this.h, dimension, this.j);
  }
  sc(dimension) {
    this.rc(dimension);
    clearTimeout(this.ac);
    this.ac = setTimeout(() => this.rc(dimension), 200);
  }
  tc(container2) {
    return $Gj(container2, "monaco-scrollable-element") ?? void 0;
  }
};
$LUb = $LUb_1 = __decorate([
  __param(1, $kl),
  __param(2, $on),
  __param(3, $50),
  __param(4, $Pk),
  __param(5, $Ty),
  __param(6, $O4),
  __param(7, $zv),
  __param(8, $5$),
  __param(9, $gs),
  __param(10, $$M),
  __param(11, $vqb),
  __param(12, $wN),
  __param(13, $TJ),
  __param(14, $jv),
  __param(15, $uob),
  __param(16, $Crb),
  __param(17, $3Rb)
], $LUb);

// out-build/vs/workbench/api/browser/viewsExtensionPoint.js
var viewsContainerSchema = {
  type: "object",
  properties: {
    id: {
      description: localize(2649, null),
      type: "string",
      pattern: "^[a-zA-Z0-9_-]+$"
    },
    title: {
      description: localize(2650, null),
      type: "string"
    },
    icon: {
      description: localize(2651, null),
      type: "string"
    }
  },
  required: ["id", "title", "icon"]
};
var $MUb = {
  description: localize(2652, null),
  type: "object",
  properties: {
    "activitybar": {
      description: localize(2653, null),
      type: "array",
      items: viewsContainerSchema
    },
    "panel": {
      description: localize(2654, null),
      type: "array",
      items: viewsContainerSchema
    }
  }
};
var ViewType;
(function(ViewType2) {
  ViewType2["Tree"] = "tree";
  ViewType2["Webview"] = "webview";
})(ViewType || (ViewType = {}));
var InitialVisibility;
(function(InitialVisibility2) {
  InitialVisibility2["Visible"] = "visible";
  InitialVisibility2["Hidden"] = "hidden";
  InitialVisibility2["Collapsed"] = "collapsed";
})(InitialVisibility || (InitialVisibility = {}));
var viewDescriptor = {
  type: "object",
  required: ["id", "name"],
  defaultSnippets: [{ body: { id: "${1:id}", name: "${2:name}" } }],
  properties: {
    type: {
      markdownDescription: localize(2655, null),
      type: "string",
      enum: [
        "tree",
        "webview"
      ],
      markdownEnumDescriptions: [
        localize(2656, null),
        localize(2657, null)
      ]
    },
    id: {
      markdownDescription: localize(2658, null),
      type: "string"
    },
    name: {
      description: localize(2659, null),
      type: "string"
    },
    when: {
      description: localize(2660, null),
      type: "string"
    },
    icon: {
      description: localize(2661, null),
      type: "string"
    },
    contextualTitle: {
      description: localize(2662, null),
      type: "string"
    },
    visibility: {
      description: localize(2663, null),
      type: "string",
      enum: [
        "visible",
        "hidden",
        "collapsed"
      ],
      default: "visible",
      enumDescriptions: [
        localize(2664, null),
        localize(2665, null),
        localize(2666, null)
      ]
    },
    initialSize: {
      type: "number",
      description: localize(2667, null)
    },
    accessibilityHelpContent: {
      type: "string",
      markdownDescription: localize(2668, null)
    }
  }
};
var remoteViewDescriptor = {
  type: "object",
  required: ["id", "name"],
  properties: {
    id: {
      description: localize(2669, null),
      type: "string"
    },
    name: {
      description: localize(2670, null),
      type: "string"
    },
    when: {
      description: localize(2671, null),
      type: "string"
    },
    group: {
      description: localize(2672, null),
      type: "string"
    },
    remoteName: {
      description: localize(2673, null),
      type: ["string", "array"],
      items: {
        type: "string"
      }
    }
  }
};
var viewsContribution = {
  description: localize(2674, null),
  type: "object",
  properties: {
    "explorer": {
      description: localize(2675, null),
      type: "array",
      items: viewDescriptor,
      default: []
    },
    "debug": {
      description: localize(2676, null),
      type: "array",
      items: viewDescriptor,
      default: []
    },
    "scm": {
      description: localize(2677, null),
      type: "array",
      items: viewDescriptor,
      default: []
    },
    "test": {
      description: localize(2678, null),
      type: "array",
      items: viewDescriptor,
      default: []
    },
    "remote": {
      description: localize(2679, null),
      type: "array",
      items: remoteViewDescriptor,
      default: []
    }
  },
  additionalProperties: {
    description: localize(2680, null),
    type: "array",
    items: viewDescriptor,
    default: []
  }
};
var viewsContainersExtensionPoint = $tN.registerExtensionPoint({
  extensionPoint: "viewsContainers",
  jsonSchema: $MUb
});
var viewsExtensionPoint = $tN.registerExtensionPoint({
  extensionPoint: "views",
  deps: [viewsContainersExtensionPoint],
  jsonSchema: viewsContribution,
  activationEventsGenerator: (viewExtensionPointTypeArray, result) => {
    for (const viewExtensionPointType of viewExtensionPointTypeArray) {
      for (const viewDescriptors of Object.values(viewExtensionPointType)) {
        for (const viewDescriptor3 of viewDescriptors) {
          if (viewDescriptor3.id) {
            result.push(`onView:${viewDescriptor3.id}`);
          }
        }
      }
    }
  }
});
var CUSTOM_VIEWS_START_ORDER = 7;
var ViewsExtensionHandler = class ViewsExtensionHandler2 {
  static {
    this.ID = "workbench.contrib.viewsExtensionHandler";
  }
  constructor(f, g) {
    this.f = f;
    this.g = g;
    this.c = $Wn.as(Extensions5.ViewContainersRegistry);
    this.d = $Wn.as(Extensions5.ViewsRegistry);
    this.h();
    this.o();
  }
  h() {
    viewsContainersExtensionPoint.setHandler((extensions, { added, removed }) => {
      if (removed.length) {
        this.j(removed);
      }
      if (added.length) {
        this.i(added, this.c.all);
      }
    });
  }
  i(extensionPoints, existingViewContainers) {
    const viewContainersRegistry = $Wn.as(Extensions5.ViewContainersRegistry);
    let activityBarOrder = CUSTOM_VIEWS_START_ORDER + viewContainersRegistry.all.filter(
      (v) => !!v.extensionId && viewContainersRegistry.getViewContainerLocation(v) === 0
      /* ViewContainerLocation.Sidebar */
    ).length;
    let panelOrder = 5 + viewContainersRegistry.all.filter(
      (v) => !!v.extensionId && viewContainersRegistry.getViewContainerLocation(v) === 1
      /* ViewContainerLocation.Panel */
    ).length + 1;
    for (const { value, collector, description } of extensionPoints) {
      Object.entries(value).forEach(([key2, value2]) => {
        if (!this.k(value2, collector)) {
          return;
        }
        switch (key2) {
          case "activitybar":
            activityBarOrder = this.l(
              value2,
              description,
              activityBarOrder,
              existingViewContainers,
              0
              /* ViewContainerLocation.Sidebar */
            );
            break;
          case "panel":
            panelOrder = this.l(
              value2,
              description,
              panelOrder,
              existingViewContainers,
              1
              /* ViewContainerLocation.Panel */
            );
            break;
        }
      });
    }
  }
  j(extensionPoints) {
    const viewContainersRegistry = $Wn.as(Extensions5.ViewContainersRegistry);
    const removedExtensions = extensionPoints.reduce((result, e) => {
      result.add(e.description.identifier);
      return result;
    }, new $6z());
    for (const viewContainer5 of viewContainersRegistry.all) {
      if (viewContainer5.extensionId && removedExtensions.has(viewContainer5.extensionId)) {
        const views = this.d.getViews(viewContainer5);
        if (views.length) {
          this.d.moveViews(views, this.r());
        }
        this.n(viewContainer5);
      }
    }
  }
  k(viewsContainersDescriptors, collector) {
    if (!Array.isArray(viewsContainersDescriptors)) {
      collector.error(localize(2681, null));
      return false;
    }
    for (const descriptor of viewsContainersDescriptors) {
      if (typeof descriptor.id !== "string" && $vf(descriptor.id)) {
        collector.error(localize(2682, null, "id"));
        return false;
      }
      if (!/^[a-z0-9_-]+$/i.test(descriptor.id)) {
        collector.error(localize(2683, null, "id"));
        return false;
      }
      if (typeof descriptor.title !== "string") {
        collector.error(localize(2684, null, "title"));
        return false;
      }
      if (typeof descriptor.icon !== "string") {
        collector.error(localize(2685, null, "icon"));
        return false;
      }
      if ($vf(descriptor.title)) {
        collector.warn(localize(2686, null, "title"));
        return true;
      }
    }
    return true;
  }
  l(containers, extension, order, existingViewContainers, location3) {
    containers.forEach((descriptor) => {
      const themeIcon = ThemeIcon.fromString(descriptor.icon);
      const icon2 = themeIcon || $vh(extension.extensionLocation, descriptor.icon);
      const id2 = `workbench.view.extension.${descriptor.id}`;
      const title = descriptor.title || id2;
      const viewContainer5 = this.m(id2, title, icon2, order++, extension.identifier, location3);
      if (existingViewContainers.length) {
        const viewsToMove = [];
        for (const existingViewContainer of existingViewContainers) {
          if (viewContainer5 !== existingViewContainer) {
            viewsToMove.push(...this.d.getViews(existingViewContainer).filter((view) => view.originalContainerId === descriptor.id));
          }
        }
        if (viewsToMove.length) {
          this.d.moveViews(viewsToMove, viewContainer5);
        }
      }
    });
    return order;
  }
  m(id2, title, icon2, order, extensionId, location3) {
    let viewContainer5 = this.c.get(id2);
    if (!viewContainer5) {
      viewContainer5 = this.c.registerViewContainer({
        id: id2,
        title: { value: title, original: title },
        extensionId,
        ctorDescriptor: new $Nk($oqb, [id2, { mergeViewWithContainerWhenSingleView: true }]),
        hideIfEmpty: true,
        order,
        icon: icon2
      }, location3);
    }
    return viewContainer5;
  }
  n(viewContainer5) {
    this.c.deregisterViewContainer(viewContainer5);
    $Wn.as($sqb.Viewlets).deregisterPaneComposite(viewContainer5.id);
  }
  o() {
    viewsExtensionPoint.setHandler((extensions, { added, removed }) => {
      if (removed.length) {
        this.s(removed);
      }
      if (added.length) {
        this.p(added);
      }
    });
  }
  p(extensions) {
    const viewIds = /* @__PURE__ */ new Set();
    const allViewDescriptors = [];
    for (const extension of extensions) {
      const { value, collector } = extension;
      Object.entries(value).forEach(([key2, value2]) => {
        if (!this.u(value2, collector)) {
          return;
        }
        if (key2 === "remote" && !$zN(extension.description, "contribViewsRemote")) {
          collector.warn(localize(2687, null, key2));
          return;
        }
        const viewContainer5 = this.w(key2);
        if (!viewContainer5) {
          collector.warn(localize(2688, null, key2));
        }
        const container2 = viewContainer5 || this.r();
        const viewDescriptors = [];
        for (let index = 0; index < value2.length; index++) {
          const item = value2[index];
          if (viewIds.has(item.id)) {
            collector.error(localize(2689, null, item.id));
            continue;
          }
          if (this.d.getView(item.id) !== null) {
            collector.error(localize(2690, null, item.id));
            continue;
          }
          const order = $5z.equals(extension.description.identifier, container2.extensionId) ? index + 1 : container2.viewOrderDelegate ? container2.viewOrderDelegate.getOrder(item.group) : void 0;
          let icon2;
          if (typeof item.icon === "string") {
            icon2 = ThemeIcon.fromString(item.icon) || $vh(extension.description.extensionLocation, item.icon);
          }
          const initialVisibility = this.t(item.visibility);
          const type = this.q(item.type);
          if (!type) {
            collector.error(localize(2691, null, item.type));
            continue;
          }
          let weight5 = void 0;
          if (typeof item.initialSize === "number") {
            if (container2.extensionId?.value === extension.description.identifier.value) {
              weight5 = item.initialSize;
            } else {
              this.g.warn(`${extension.description.identifier.value} tried to set the view size of ${item.id} but it was ignored because the view container does not belong to it.`);
            }
          }
          let accessibilityHelpContent;
          if ($zN(extension.description, "contribAccessibilityHelpContent") && item.accessibilityHelpContent) {
            accessibilityHelpContent = new $bm(item.accessibilityHelpContent);
          }
          const viewDescriptor3 = {
            type,
            ctorDescriptor: type === ViewType.Tree ? new $Nk($gUb) : new $Nk($LUb),
            id: item.id,
            name: { value: item.name, original: item.name },
            when: $7m.deserialize(item.when),
            containerIcon: icon2 || viewContainer5?.icon,
            containerTitle: item.contextualTitle || viewContainer5 && (typeof viewContainer5.title === "string" ? viewContainer5.title : viewContainer5.title.value),
            canToggleVisibility: true,
            canMoveView: viewContainer5?.id !== $HUb,
            treeView: type === ViewType.Tree ? this.f.createInstance($iUb, item.id, item.name, extension.description.identifier.value) : void 0,
            collapsed: this.x(container2) || initialVisibility === InitialVisibility.Collapsed,
            order,
            extensionId: extension.description.identifier,
            originalContainerId: key2,
            group: item.group,
            remoteAuthority: item.remoteName || item.remoteAuthority,
            // TODO@roblou - delete after remote extensions are updated
            virtualWorkspace: item.virtualWorkspace,
            hideByDefault: initialVisibility === InitialVisibility.Hidden,
            workspace: viewContainer5?.id === $HUb ? true : void 0,
            weight: weight5,
            accessibilityHelpContent
          };
          viewIds.add(viewDescriptor3.id);
          viewDescriptors.push(viewDescriptor3);
        }
        allViewDescriptors.push({ viewContainer: container2, views: viewDescriptors });
      });
    }
    this.d.registerViews2(allViewDescriptors);
  }
  q(type) {
    if (type === ViewType.Webview) {
      return ViewType.Webview;
    }
    if (!type || type === ViewType.Tree) {
      return ViewType.Tree;
    }
    return void 0;
  }
  r() {
    return this.c.get($3sb);
  }
  s(extensions) {
    const removedExtensions = extensions.reduce((result, e) => {
      result.add(e.description.identifier);
      return result;
    }, new $6z());
    for (const viewContainer5 of this.c.all) {
      const removedViews = this.d.getViews(viewContainer5).filter((v) => v.extensionId && removedExtensions.has(v.extensionId));
      if (removedViews.length) {
        this.d.deregisterViews(removedViews, viewContainer5);
        for (const view of removedViews) {
          const anyView = view;
          if (anyView.treeView) {
            anyView.treeView.dispose();
          }
        }
      }
    }
  }
  t(value) {
    if (Object.values(InitialVisibility).includes(value)) {
      return value;
    }
    return void 0;
  }
  u(viewDescriptors, collector) {
    if (!Array.isArray(viewDescriptors)) {
      collector.error(localize(2692, null));
      return false;
    }
    for (const descriptor of viewDescriptors) {
      if (typeof descriptor.id !== "string") {
        collector.error(localize(2693, null, "id"));
        return false;
      }
      if (typeof descriptor.name !== "string") {
        collector.error(localize(2694, null, "name"));
        return false;
      }
      if (descriptor.when && typeof descriptor.when !== "string") {
        collector.error(localize(2695, null, "when"));
        return false;
      }
      if (descriptor.icon && typeof descriptor.icon !== "string") {
        collector.error(localize(2696, null, "icon"));
        return false;
      }
      if (descriptor.contextualTitle && typeof descriptor.contextualTitle !== "string") {
        collector.error(localize(2697, null, "contextualTitle"));
        return false;
      }
      if (descriptor.visibility && !this.t(descriptor.visibility)) {
        collector.error(localize(2698, null, "visibility", Object.values(InitialVisibility).join(", ")));
        return false;
      }
    }
    return true;
  }
  w(value) {
    switch (value) {
      case "explorer":
        return this.c.get($3sb);
      case "debug":
        return this.c.get($TQ);
      case "scm":
        return this.c.get($_R);
      case "remote":
        return this.c.get($HUb);
      default:
        return this.c.get(`workbench.view.extension.${value}`);
    }
  }
  x(container2) {
    switch (container2.id) {
      case $3sb:
      case $_R:
      case $TQ:
        return true;
    }
    return false;
  }
};
ViewsExtensionHandler = __decorate([
  __param(0, $Pk),
  __param(1, $wn)
], ViewsExtensionHandler);
var ViewContainersDataRenderer = class extends $3c {
  constructor() {
    super(...arguments);
    this.type = "table";
  }
  shouldRender(manifest) {
    return !!manifest.contributes?.viewsContainers;
  }
  render(manifest) {
    const contrib = manifest.contributes?.viewsContainers || {};
    const viewContainers = Object.keys(contrib).reduce((result, location3) => {
      const viewContainersForLocation = contrib[location3];
      result.push(...viewContainersForLocation.map((viewContainer5) => ({ ...viewContainer5, location: location3 })));
      return result;
    }, []);
    if (!viewContainers.length) {
      return { data: { headers: [], rows: [] }, dispose: () => {
      } };
    }
    const headers = [
      localize(2699, null),
      localize(2700, null),
      localize(2701, null)
    ];
    const rows = viewContainers.sort((a, b) => a.id.localeCompare(b.id)).map((viewContainer5) => {
      return [
        viewContainer5.id,
        viewContainer5.title,
        viewContainer5.location
      ];
    });
    return {
      data: {
        headers,
        rows
      },
      dispose: () => {
      }
    };
  }
};
var ViewsDataRenderer = class extends $3c {
  constructor() {
    super(...arguments);
    this.type = "table";
  }
  shouldRender(manifest) {
    return !!manifest.contributes?.views;
  }
  render(manifest) {
    const contrib = manifest.contributes?.views || {};
    const views = Object.keys(contrib).reduce((result, location3) => {
      const viewsForLocation = contrib[location3];
      result.push(...viewsForLocation.map((view) => ({ ...view, location: location3 })));
      return result;
    }, []);
    if (!views.length) {
      return { data: { headers: [], rows: [] }, dispose: () => {
      } };
    }
    const headers = [
      localize(2702, null),
      localize(2703, null),
      localize(2704, null)
    ];
    const rows = views.sort((a, b) => a.id.localeCompare(b.id)).map((view) => {
      return [
        view.id,
        view.name,
        view.location
      ];
    });
    return {
      data: {
        headers,
        rows
      },
      dispose: () => {
      }
    };
  }
};
$Wn.as(Extensions3.ExtensionFeaturesRegistry).registerExtensionFeature({
  id: "viewsContainers",
  label: localize(2705, null),
  access: {
    canToggle: false
  },
  renderer: new $Nk(ViewContainersDataRenderer)
});
$Wn.as(Extensions3.ExtensionFeaturesRegistry).registerExtensionFeature({
  id: "views",
  label: localize(2706, null),
  access: {
    canToggle: false
  },
  renderer: new $Nk(ViewsDataRenderer)
});
$PL(
  ViewsExtensionHandler.ID,
  ViewsExtensionHandler,
  1
  /* WorkbenchPhase.BlockStartup */
);

// out-build/vs/workbench/browser/parts/editor/textCodeEditor.js
var $NUb = class extends $aub {
  constructor() {
    super(...arguments);
    this.a = void 0;
  }
  get scopedContextKeyService() {
    return this.a?.invokeWithinContext((accessor) => accessor.get($on));
  }
  getTitle() {
    if (this.input) {
      return this.input.getName();
    }
    return localize(3595, null);
  }
  Lb(parent, initialOptions) {
    this.a = this.B(this.m.createInstance($D9, parent, initialOptions, this.Sb()));
  }
  Sb() {
    return /* @__PURE__ */ Object.create(null);
  }
  Mb(options3) {
    this.a?.updateOptions(options3);
  }
  Nb() {
    return this.a;
  }
  getControl() {
    return this.a;
  }
  mb(resource) {
    if (!this.a) {
      return void 0;
    }
    const model = this.a.getModel();
    if (!model) {
      return void 0;
    }
    const modelUri = model.uri;
    if (!modelUri) {
      return void 0;
    }
    if (!$oh(modelUri, resource)) {
      return void 0;
    }
    return this.a.saveViewState() ?? void 0;
  }
  setOptions(options3) {
    super.setOptions(options3);
    if (options3) {
      applyTextEditorOptions(
        options3,
        $Kg(this.a),
        0
        /* ScrollType.Smooth */
      );
    }
  }
  focus() {
    super.focus();
    this.a?.focus();
  }
  hasFocus() {
    return this.a?.hasTextFocus() || super.hasFocus();
  }
  Z(visible) {
    super.Z(visible);
    if (visible) {
      this.a?.onVisible();
    } else {
      this.a?.onHide();
    }
  }
  layout(dimension) {
    this.a?.layout(dimension);
  }
};

// out-build/vs/workbench/browser/parts/editor/textResourceEditor.js
var $PUb_1;
var $OUb = class $OUb2 extends $NUb {
  constructor(id2, group2, telemetryService, instantiationService, storageService, textResourceConfigurationService, themeService, editorGroupService, editorService, fileService) {
    super(id2, group2, telemetryService, instantiationService, storageService, textResourceConfigurationService, themeService, editorService, editorGroupService, fileService);
  }
  async setInput(input, options3, context, token) {
    await super.setInput(input, options3, context, token);
    const resolvedModel = await input.resolve();
    if (token.isCancellationRequested) {
      return void 0;
    }
    if (!(resolvedModel instanceof $xG)) {
      throw new Error("Unable to open file as text");
    }
    const control = $Kg(this.a);
    const textEditorModel = resolvedModel.textEditorModel;
    control.setModel(textEditorModel);
    if (!$oL(options3?.viewState)) {
      const editorViewState = this.jb(input, context);
      if (editorViewState) {
        if (options3?.selection) {
          editorViewState.cursorState = [];
        }
        control.restoreViewState(editorViewState);
      }
    }
    if (options3) {
      applyTextEditorOptions(
        options3,
        control,
        1
        /* ScrollType.Immediate */
      );
    }
    control.updateOptions(this.Gb(resolvedModel.isReadonly()));
  }
  /**
   * Reveals the last line of this editor if it has a model set.
   */
  revealLastLine() {
    const control = this.a;
    if (!control) {
      return;
    }
    const model = control.getModel();
    if (model) {
      const lastLine = model.getLineCount();
      control.revealPosition(
        { lineNumber: lastLine, column: model.getLineMaxColumn(lastLine) },
        0
        /* ScrollType.Smooth */
      );
    }
  }
  clearInput() {
    super.clearInput();
    this.a?.setModel(null);
  }
  nb(input) {
    return input instanceof $0Gb || input instanceof $6vb;
  }
};
$OUb = __decorate([
  __param(2, $zv),
  __param(3, $Pk),
  __param(4, $jv),
  __param(5, $zG),
  __param(6, $gs),
  __param(7, $iJ),
  __param(8, $mJ),
  __param(9, $km)
], $OUb);
var $PUb = class $PUb2 extends $OUb {
  static {
    $PUb_1 = this;
  }
  static {
    this.ID = "workbench.editors.textResourceEditor";
  }
  constructor(group2, telemetryService, instantiationService, storageService, textResourceConfigurationService, themeService, editorService, editorGroupService, $149, Xb, fileService) {
    super($PUb_1.ID, group2, telemetryService, instantiationService, storageService, textResourceConfigurationService, themeService, editorGroupService, editorService, fileService);
    this.$ = $149;
    this.Xb = Xb;
  }
  Lb(parent, configuration2) {
    super.Lb(parent, configuration2);
    const control = this.a;
    if (control) {
      this.B(control.onDidPaste((e) => this.Zb(e, control)));
    }
  }
  Zb(e, codeEditor) {
    if (this.input instanceof $0Gb && this.input.hasLanguageSetExplicitly) {
      return;
    }
    if (e.range.startLineNumber !== 1 || e.range.startColumn !== 1) {
      return;
    }
    if (codeEditor.getOption(
      96
      /* EditorOption.readOnly */
    )) {
      return;
    }
    const textModel = codeEditor.getModel();
    if (!textModel) {
      return;
    }
    const pasteIsWholeContents = textModel.getLineCount() === e.range.endLineNumber && textModel.getLineMaxColumn(e.range.endLineNumber) === e.range.endColumn;
    if (!pasteIsWholeContents) {
      return;
    }
    const currentLanguageId = textModel.getLanguageId();
    if (currentLanguageId !== $KF) {
      return;
    }
    let candidateLanguage = void 0;
    if (e.languageId) {
      candidateLanguage = { id: e.languageId, source: "event" };
    } else {
      const guess = this.Xb.guessLanguageIdByFilepathOrFirstLine(textModel.uri, textModel.getLineContent(1).substr(
        0,
        1e3
        /* ModelConstants.FIRST_LINE_DETECTION_LENGTH_LIMIT */
      )) ?? void 0;
      if (guess) {
        candidateLanguage = { id: guess, source: "guess" };
      }
    }
    if (candidateLanguage && candidateLanguage.id !== $KF) {
      if (this.input instanceof $0Gb && candidateLanguage.source === "event") {
        this.input.setLanguageId(candidateLanguage.id);
      } else {
        textModel.setLanguage(this.Xb.createById(candidateLanguage.id));
      }
      const opts = this.$.getCreationOptions(textModel.getLanguageId(), textModel.uri, textModel.isForSimpleWidget);
      textModel.detectIndentation(opts.insertSpaces, opts.tabSize);
    }
  }
};
$PUb = $PUb_1 = __decorate([
  __param(1, $zv),
  __param(2, $Pk),
  __param(3, $jv),
  __param(4, $zG),
  __param(5, $gs),
  __param(6, $mJ),
  __param(7, $iJ),
  __param(8, $sG),
  __param(9, $1E),
  __param(10, $km)
], $PUb);

// out-build/vs/workbench/browser/parts/editor/binaryEditor.js
var $QUb = class $QUb2 extends $qyb {
  constructor(id2, group2, cb, telemetryService, themeService, storageService) {
    super(id2, group2, telemetryService, themeService, storageService);
    this.cb = cb;
    this.r = this.B(new $ze());
    this.onDidChangeMetadata = this.r.event;
    this.s = this.B(new $ze());
    this.onDidOpenInPlace = this.s.event;
  }
  getTitle() {
    return this.input ? this.input.getName() : localize(3107, null);
  }
  async m(input, options3) {
    const model = await input.resolve();
    if (!(model instanceof $7vb)) {
      throw new Error("Unable to open file as binary");
    }
    const size = model.getSize();
    this.eb(typeof size === "number" ? $Sm.formatSize(size) : "");
    return {
      icon: "$(warning)",
      label: localize(3108, null),
      actions: [
        {
          label: localize(3109, null),
          run: async () => {
            await this.cb.openInternal(input, options3);
            this.s.fire();
          }
        }
      ]
    };
  }
  eb(meta) {
    this.u = meta;
    this.r.fire();
  }
  getMetadata() {
    return this.u;
  }
};
$QUb = __decorate([
  __param(5, $jv)
], $QUb);

// out-build/vs/workbench/browser/parts/editor/binaryDiffEditor.js
var $RUb = class $RUb2 extends $_tb {
  static {
    this.ID = $4K;
  }
  constructor(group2, telemetryService, instantiationService, themeService, storageService, configurationService, textResourceConfigurationService, editorService, editorGroupService) {
    super(group2, telemetryService, instantiationService, themeService, storageService, configurationService, textResourceConfigurationService, editorService, editorGroupService);
  }
  getMetadata() {
    const primary = this.getPrimaryEditorPane();
    const secondary = this.getSecondaryEditorPane();
    if (primary instanceof $QUb && secondary instanceof $QUb) {
      return localize(3106, null, secondary.getMetadata(), primary.getMetadata());
    }
    return void 0;
  }
};
$RUb = __decorate([
  __param(1, $zv),
  __param(2, $Pk),
  __param(3, $gs),
  __param(4, $jv),
  __param(5, $kl),
  __param(6, $zG),
  __param(7, $mJ),
  __param(8, $iJ)
], $RUb);

// out-build/vs/workbench/browser/parts/editor/editorStatus.js
var $TUb_1;
var SideBySideEditorEncodingSupport = class {
  constructor(c, d) {
    this.c = c;
    this.d = d;
  }
  getEncoding() {
    return this.c.getEncoding();
  }
  async setEncoding(encoding, mode) {
    await Promises.settled([this.c, this.d].map((editor) => editor.setEncoding(encoding, mode)));
  }
};
var SideBySideEditorLanguageSupport = class {
  constructor(c, d) {
    this.c = c;
    this.d = d;
  }
  setLanguageId(languageId, source) {
    [this.c, this.d].forEach((editor) => editor.setLanguageId(languageId, source));
  }
};
function toEditorWithEncodingSupport(input) {
  if (input instanceof $0Gb) {
    return input;
  }
  if (input instanceof $1I) {
    const primaryEncodingSupport = toEditorWithEncodingSupport(input.primary);
    const secondaryEncodingSupport = toEditorWithEncodingSupport(input.secondary);
    if (primaryEncodingSupport && secondaryEncodingSupport) {
      return new SideBySideEditorEncodingSupport(primaryEncodingSupport, secondaryEncodingSupport);
    }
    return primaryEncodingSupport;
  }
  const encodingSupport = input;
  if ($Og(encodingSupport.setEncoding, encodingSupport.getEncoding)) {
    return encodingSupport;
  }
  return null;
}
function toEditorWithLanguageSupport(input) {
  if (input instanceof $0Gb) {
    return input;
  }
  if (input instanceof $1I) {
    const primaryLanguageSupport = toEditorWithLanguageSupport(input.primary);
    const secondaryLanguageSupport = toEditorWithLanguageSupport(input.secondary);
    if (primaryLanguageSupport && secondaryLanguageSupport) {
      return new SideBySideEditorLanguageSupport(primaryLanguageSupport, secondaryLanguageSupport);
    }
    return primaryLanguageSupport;
  }
  const languageSupport = input;
  if (typeof languageSupport.setLanguageId === "function") {
    return languageSupport;
  }
  return null;
}
var StateChange = class {
  constructor() {
    this.indentation = false;
    this.selectionStatus = false;
    this.languageId = false;
    this.languageStatus = false;
    this.encoding = false;
    this.EOL = false;
    this.tabFocusMode = false;
    this.inputMode = false;
    this.columnSelectionMode = false;
    this.metadata = false;
  }
  combine(other) {
    this.indentation = this.indentation || other.indentation;
    this.selectionStatus = this.selectionStatus || other.selectionStatus;
    this.languageId = this.languageId || other.languageId;
    this.languageStatus = this.languageStatus || other.languageStatus;
    this.encoding = this.encoding || other.encoding;
    this.EOL = this.EOL || other.EOL;
    this.tabFocusMode = this.tabFocusMode || other.tabFocusMode;
    this.inputMode = this.inputMode || other.inputMode;
    this.columnSelectionMode = this.columnSelectionMode || other.columnSelectionMode;
    this.metadata = this.metadata || other.metadata;
  }
  hasChanges() {
    return this.indentation || this.selectionStatus || this.languageId || this.languageStatus || this.encoding || this.EOL || this.tabFocusMode || this.inputMode || this.columnSelectionMode || this.metadata;
  }
};
var State7 = class {
  get selectionStatus() {
    return this.c;
  }
  get languageId() {
    return this.d;
  }
  get encoding() {
    return this.f;
  }
  get EOL() {
    return this.g;
  }
  get indentation() {
    return this.h;
  }
  get tabFocusMode() {
    return this.i;
  }
  get inputMode() {
    return this.j;
  }
  get columnSelectionMode() {
    return this.l;
  }
  get metadata() {
    return this.m;
  }
  update(update) {
    const change = new StateChange();
    switch (update.type) {
      case "selectionStatus":
        if (this.c !== update.selectionStatus) {
          this.c = update.selectionStatus;
          change.selectionStatus = true;
        }
        break;
      case "indentation":
        if (this.h !== update.indentation) {
          this.h = update.indentation;
          change.indentation = true;
        }
        break;
      case "languageId":
        if (this.d !== update.languageId) {
          this.d = update.languageId;
          change.languageId = true;
        }
        break;
      case "encoding":
        if (this.f !== update.encoding) {
          this.f = update.encoding;
          change.encoding = true;
        }
        break;
      case "EOL":
        if (this.g !== update.EOL) {
          this.g = update.EOL;
          change.EOL = true;
        }
        break;
      case "tabFocusMode":
        if (this.i !== update.tabFocusMode) {
          this.i = update.tabFocusMode;
          change.tabFocusMode = true;
        }
        break;
      case "inputMode":
        if (this.j !== update.inputMode) {
          this.j = update.inputMode;
          change.inputMode = true;
        }
        break;
      case "columnSelectionMode":
        if (this.l !== update.columnSelectionMode) {
          this.l = update.columnSelectionMode;
          change.columnSelectionMode = true;
        }
        break;
      case "metadata":
        if (this.m !== update.metadata) {
          this.m = update.metadata;
          change.metadata = true;
        }
        break;
    }
    return change;
  }
};
var TabFocusMode = class TabFocusMode2 extends $3c {
  constructor(f) {
    super();
    this.f = f;
    this.c = this.B(new $ze());
    this.onDidChange = this.c.event;
    this.g();
    const tabFocusModeConfig = f.getValue("editor.tabFocusMode") === true ? true : false;
    $94.setTabFocusMode(tabFocusModeConfig);
  }
  g() {
    this.B($94.onDidChangeTabFocus((tabFocusMode) => this.c.fire(tabFocusMode)));
    this.B(this.f.onDidChangeConfiguration((e) => {
      if (e.affectsConfiguration("editor.tabFocusMode")) {
        const tabFocusModeConfig = this.f.getValue("editor.tabFocusMode") === true ? true : false;
        $94.setTabFocusMode(tabFocusModeConfig);
        this.c.fire(tabFocusModeConfig);
      }
    }));
  }
};
TabFocusMode = __decorate([
  __param(0, $kl)
], TabFocusMode);
var StatusInputMode = class extends $3c {
  constructor() {
    super();
    this.c = this.B(new $ze());
    this.onDidChange = this.c.event;
    $04.setInputMode("insert");
    this.B($04.onDidChangeInputMode((inputMode) => this.c.fire(inputMode)));
  }
};
var nlsSingleSelectionRange = localize(3527, null);
var nlsSingleSelection = localize(3528, null);
var nlsMultiSelectionRange = localize(3529, null);
var nlsMultiSelection = localize(3530, null);
var nlsEOLLF = localize(3531, null);
var nlsEOLCRLF = localize(3532, null);
var EditorStatus = class EditorStatus2 extends $3c {
  constructor(G, H, I, J, L, M, N, O) {
    super();
    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.c = this.B(new $4c());
    this.f = this.B(new $4c());
    this.g = this.B(new $4c());
    this.h = this.B(new $4c());
    this.j = this.B(new $4c());
    this.m = this.B(new $4c());
    this.n = this.B(new $4c());
    this.s = this.B(new $4c());
    this.t = this.B(new $4c());
    this.u = this.B(this.N.createInstance(ShowCurrentMarkerInStatusbarContribution));
    this.w = this.B(this.N.createInstance(TabFocusMode));
    this.y = this.B(this.N.createInstance(StatusInputMode));
    this.z = new State7();
    this.C = void 0;
    this.D = this.B(new $2c());
    this.F = this.B(new $4c());
    this.Q();
    this.P();
  }
  P() {
    this.B(this.H.onDidActiveEditorChange(() => this.gb()));
    this.B(this.L.untitled.onDidChangeEncoding((model) => this.ob(model.resource)));
    this.B(this.L.files.onDidChangeEncoding((model) => this.ob(model.resource)));
    this.B(Event2.runAndSubscribe(this.w.onDidChange, (tabFocusMode) => {
      if (tabFocusMode !== void 0) {
        this.pb(tabFocusMode);
      } else {
        this.pb(this.O.getValue("editor.tabFocusMode"));
      }
    }));
    this.B(Event2.runAndSubscribe(this.y.onDidChange, (inputMode) => this.qb(inputMode ?? "insert")));
  }
  Q() {
    this.B($tn.registerCommand({ id: `changeEditorIndentation${this.G}`, handler: () => this.R() }));
  }
  async R() {
    const activeTextEditorControl = $S5(this.H.activeTextEditorControl);
    if (!activeTextEditorControl) {
      return this.I.pick([{ label: localize(3533, null) }]);
    }
    if (this.H.activeEditor?.isReadonly()) {
      return this.I.pick([{ label: localize(3534, null) }]);
    }
    const picks = [
      $Kg(activeTextEditorControl.getAction($Sib.ID)),
      $Kg(activeTextEditorControl.getAction($Rib.ID)),
      $Kg(activeTextEditorControl.getAction($Tib.ID)),
      $Kg(activeTextEditorControl.getAction($Uib.ID)),
      $Kg(activeTextEditorControl.getAction($Oib.ID)),
      $Kg(activeTextEditorControl.getAction($Pib.ID)),
      $Kg(activeTextEditorControl.getAction($bjb.ID))
    ].map((a) => {
      return {
        id: a.id,
        label: a.label,
        detail: Language.isDefaultVariant() || a.label === a.alias ? void 0 : a.alias,
        run: () => {
          activeTextEditorControl.focus();
          a.run();
        }
      };
    });
    picks.splice(3, 0, { type: "separator", label: localize(3535, null) });
    picks.unshift({ type: "separator", label: localize(3536, null) });
    const action = await this.I.pick(picks, { placeHolder: localize(3537, null), matchOnDetail: true });
    return action?.run();
  }
  S(visible) {
    if (visible) {
      if (!this.c.value) {
        const text2 = localize(3538, null);
        this.c.value = this.M.addEntry({
          name: localize(3539, null),
          text: text2,
          ariaLabel: text2,
          tooltip: localize(3540, null),
          command: "editor.action.toggleTabFocusMode",
          kind: "prominent"
        }, "status.editor.tabFocusMode", 1, 100.7);
      }
    } else {
      this.c.clear();
    }
  }
  U(inputMode) {
    if (inputMode === "overtype") {
      if (!this.f.value) {
        const text2 = localize(3541, null);
        const name = localize(3542, null);
        this.f.value = this.M.addEntry({
          name,
          text: text2,
          ariaLabel: text2,
          tooltip: name,
          command: "editor.action.toggleOvertypeInsertMode",
          kind: "prominent"
        }, "status.editor.inputMode", 1, 100.6);
      }
    } else {
      this.f.clear();
    }
  }
  W(visible) {
    if (visible) {
      if (!this.g.value) {
        const text2 = localize(3543, null);
        this.g.value = this.M.addEntry({
          name: localize(3544, null),
          text: text2,
          ariaLabel: text2,
          tooltip: localize(3545, null),
          command: "editor.action.toggleColumnSelection",
          kind: "prominent"
        }, "status.editor.columnSelectionMode", 1, 100.8);
      }
    } else {
      this.g.clear();
    }
  }
  X(text2) {
    if (!text2) {
      this.j.clear();
      return;
    }
    const editorURI = $S5(this.H.activeTextEditorControl)?.getModel()?.uri;
    if (editorURI?.scheme === Schemas.vscodeNotebookCell) {
      this.j.clear();
      return;
    }
    const props = {
      name: localize(3546, null),
      text: text2,
      ariaLabel: text2,
      tooltip: localize(3547, null),
      command: "workbench.action.gotoLine"
    };
    this.cb(this.j, props, "status.editor.selection", 1, 100.5);
  }
  Y(text2) {
    if (!text2) {
      this.h.clear();
      return;
    }
    const editorURI = $S5(this.H.activeTextEditorControl)?.getModel()?.uri;
    if (editorURI?.scheme === Schemas.vscodeNotebookCell) {
      this.h.clear();
      return;
    }
    const props = {
      name: localize(3548, null),
      text: text2,
      ariaLabel: text2,
      tooltip: localize(3549, null),
      command: `changeEditorIndentation${this.G}`
    };
    this.cb(this.h, props, "status.editor.indentation", 1, 100.4);
  }
  Z(text2) {
    if (!text2) {
      this.m.clear();
      return;
    }
    const props = {
      name: localize(3550, null),
      text: text2,
      ariaLabel: text2,
      tooltip: localize(3551, null),
      command: "workbench.action.editor.changeEncoding"
    };
    this.cb(this.m, props, "status.editor.encoding", 1, 100.3);
  }
  $(text2) {
    if (!text2) {
      this.n.clear();
      return;
    }
    const props = {
      name: localize(3552, null),
      text: text2,
      ariaLabel: text2,
      tooltip: localize(3553, null),
      command: "workbench.action.editor.changeEOL"
    };
    this.cb(this.n, props, "status.editor.eol", 1, 100.2);
  }
  ab(text2) {
    if (!text2) {
      this.s.clear();
      return;
    }
    const props = {
      name: localize(3554, null),
      text: text2,
      ariaLabel: text2,
      tooltip: localize(3555, null),
      command: "workbench.action.editor.changeLanguageMode"
    };
    this.cb(this.s, props, "status.editor.mode", 1, 100.1);
  }
  bb(text2) {
    if (!text2) {
      this.t.clear();
      return;
    }
    const props = {
      name: localize(3556, null),
      text: text2,
      ariaLabel: text2,
      tooltip: localize(3557, null)
    };
    this.cb(this.t, props, "status.editor.info", 1, 100);
  }
  cb(element, props, id2, alignment, priority) {
    if (!element.value) {
      element.value = this.M.addEntry(props, id2, alignment, priority);
    } else {
      element.value.update(props);
    }
  }
  db(update) {
    const changed = this.z.update(update);
    if (!changed.hasChanges()) {
      return;
    }
    if (!this.C) {
      this.C = changed;
      this.F.value = $ij(getWindowById(this.G, true).window, () => {
        this.F.clear();
        const toRender = this.C;
        this.C = void 0;
        if (toRender) {
          this.eb();
        }
      });
    } else {
      this.C.combine(changed);
    }
  }
  eb() {
    this.S(!!this.z.tabFocusMode);
    this.U(this.z.inputMode);
    this.W(!!this.z.columnSelectionMode);
    this.Y(this.z.indentation);
    this.X(this.z.selectionStatus);
    this.Z(this.z.encoding);
    this.$(this.z.EOL ? this.z.EOL === "\r\n" ? nlsEOLCRLF : nlsEOLLF : void 0);
    this.ab(this.z.languageId);
    this.bb(this.z.metadata);
  }
  fb(info) {
    if (!info || !info.selections) {
      return void 0;
    }
    if (info.selections.length === 1) {
      if (info.charactersSelected) {
        return $wf(nlsSingleSelectionRange, info.selections[0].positionLineNumber, info.selections[0].positionColumn, info.charactersSelected);
      }
      return $wf(nlsSingleSelection, info.selections[0].positionLineNumber, info.selections[0].positionColumn);
    }
    if (info.charactersSelected) {
      return $wf(nlsMultiSelectionRange, info.selections.length, info.charactersSelected);
    }
    if (info.selections.length > 0) {
      return $wf(nlsMultiSelection, info.selections.length);
    }
    return void 0;
  }
  gb() {
    const activeInput = this.H.activeEditor;
    const activeEditorPane = this.H.activeEditorPane;
    const activeCodeEditor = activeEditorPane ? $S5(activeEditorPane.getControl()) ?? void 0 : void 0;
    this.kb(activeCodeEditor);
    this.lb(activeCodeEditor);
    this.hb(activeCodeEditor, activeInput);
    this.mb(activeCodeEditor);
    this.nb(activeEditorPane, activeCodeEditor);
    this.ib(activeCodeEditor);
    this.jb(activeEditorPane);
    this.u.update(activeCodeEditor);
    this.D.clear();
    if (activeEditorPane) {
      this.D.add(activeEditorPane.onDidChangeControl(() => {
        this.gb();
      }));
    }
    if (activeCodeEditor) {
      this.D.add(activeCodeEditor.onDidChangeConfiguration((event) => {
        if (event.hasChanged(
          22
          /* EditorOption.columnSelection */
        )) {
          this.kb(activeCodeEditor);
        }
      }));
      this.D.add(Event2.defer(activeCodeEditor.onDidChangeCursorPosition)(() => {
        this.lb(activeCodeEditor);
        this.u.update(activeCodeEditor);
      }));
      this.D.add(activeCodeEditor.onDidChangeModelLanguage(() => {
        this.hb(activeCodeEditor, activeInput);
      }));
      this.D.add(Event2.accumulate(activeCodeEditor.onDidChangeModelContent)((e) => {
        this.mb(activeCodeEditor);
        this.u.update(activeCodeEditor);
        const selections = activeCodeEditor.getSelections();
        if (selections) {
          for (const inner of e) {
            for (const change of inner.changes) {
              if (selections.some((selection) => $9C.areIntersecting(selection, change.range))) {
                this.lb(activeCodeEditor);
                break;
              }
            }
          }
        }
      }));
      this.D.add(activeCodeEditor.onDidChangeModelOptions(() => {
        this.ib(activeCodeEditor);
      }));
    } else if (activeEditorPane instanceof $QUb || activeEditorPane instanceof $RUb) {
      const binaryEditors = [];
      if (activeEditorPane instanceof $RUb) {
        const primary = activeEditorPane.getPrimaryEditorPane();
        if (primary instanceof $QUb) {
          binaryEditors.push(primary);
        }
        const secondary = activeEditorPane.getSecondaryEditorPane();
        if (secondary instanceof $QUb) {
          binaryEditors.push(secondary);
        }
      } else {
        binaryEditors.push(activeEditorPane);
      }
      for (const editor of binaryEditors) {
        this.D.add(editor.onDidChangeMetadata(() => {
          this.jb(activeEditorPane);
        }));
        this.D.add(editor.onDidOpenInPlace(() => {
          this.gb();
        }));
      }
    }
  }
  hb(editorWidget, editorInput) {
    const info = { type: "languageId", languageId: void 0 };
    if (editorWidget && editorInput && toEditorWithLanguageSupport(editorInput)) {
      const textModel = editorWidget.getModel();
      if (textModel) {
        const languageId = textModel.getLanguageId();
        info.languageId = this.J.getLanguageName(languageId) ?? void 0;
      }
    }
    this.db(info);
  }
  ib(editorWidget) {
    const update = { type: "indentation", indentation: void 0 };
    if (editorWidget) {
      const model = editorWidget.getModel();
      if (model) {
        const modelOpts = model.getOptions();
        update.indentation = modelOpts.insertSpaces ? modelOpts.tabSize === modelOpts.indentSize ? localize(3558, null, modelOpts.indentSize) : localize(3559, null, modelOpts.indentSize, modelOpts.tabSize) : localize(3560, null, modelOpts.tabSize);
      }
    }
    this.db(update);
  }
  jb(editor) {
    const update = { type: "metadata", metadata: void 0 };
    if (editor instanceof $QUb || editor instanceof $RUb) {
      update.metadata = editor.getMetadata();
    }
    this.db(update);
  }
  kb(editorWidget) {
    const info = { type: "columnSelectionMode", columnSelectionMode: false };
    if (editorWidget?.getOption(
      22
      /* EditorOption.columnSelection */
    )) {
      info.columnSelectionMode = true;
    }
    this.db(info);
  }
  lb(editorWidget) {
    const info = /* @__PURE__ */ Object.create(null);
    if (editorWidget) {
      info.selections = editorWidget.getSelections() || [];
      info.charactersSelected = 0;
      const textModel = editorWidget.getModel();
      if (textModel) {
        for (const selection of info.selections) {
          if (typeof info.charactersSelected !== "number") {
            info.charactersSelected = 0;
          }
          info.charactersSelected += textModel.getCharacterCountInRange(selection);
        }
      }
      if (info.selections.length === 1) {
        const editorPosition = editorWidget.getPosition();
        const selectionClone = new $_D(info.selections[0].selectionStartLineNumber, info.selections[0].selectionStartColumn, info.selections[0].positionLineNumber, editorPosition ? editorWidget.getStatusbarColumn(editorPosition) : info.selections[0].positionColumn);
        info.selections[0] = selectionClone;
      }
    }
    this.db({ type: "selectionStatus", selectionStatus: this.fb(info) });
  }
  mb(editorWidget) {
    const info = { type: "EOL", EOL: void 0 };
    if (editorWidget && !editorWidget.getOption(
      96
      /* EditorOption.readOnly */
    )) {
      const codeEditorModel = editorWidget.getModel();
      if (codeEditorModel) {
        info.EOL = codeEditorModel.getEOL();
      }
    }
    this.db(info);
  }
  nb(editor, editorWidget) {
    if (editor && !this.rb(editor)) {
      return;
    }
    const info = { type: "encoding", encoding: void 0 };
    if (editor && editorWidget?.hasModel()) {
      const encodingSupport = editor.input ? toEditorWithEncodingSupport(editor.input) : null;
      if (encodingSupport) {
        const rawEncoding = encodingSupport.getEncoding();
        const encodingInfo = typeof rawEncoding === "string" ? $KJ[rawEncoding] : void 0;
        if (encodingInfo) {
          info.encoding = encodingInfo.labelShort;
        } else {
          info.encoding = rawEncoding;
        }
      }
    }
    this.db(info);
  }
  ob(resource) {
    const activeEditorPane = this.H.activeEditorPane;
    if (activeEditorPane) {
      const activeResource = $mL.getCanonicalUri(activeEditorPane.input, { supportSideBySide: SideBySideEditor.PRIMARY });
      if (activeResource && $oh(activeResource, resource)) {
        const activeCodeEditor = $S5(activeEditorPane.getControl()) ?? void 0;
        return this.nb(activeEditorPane, activeCodeEditor);
      }
    }
  }
  pb(tabFocusMode) {
    const info = { type: "tabFocusMode", tabFocusMode };
    this.db(info);
  }
  qb(inputMode) {
    const info = { type: "inputMode", inputMode };
    this.db(info);
  }
  rb(control) {
    const activeEditorPane = this.H.activeEditorPane;
    return !!activeEditorPane && activeEditorPane === control;
  }
};
EditorStatus = __decorate([
  __param(1, $mJ),
  __param(2, $1M),
  __param(3, $1E),
  __param(4, $cK),
  __param(5, $$qb),
  __param(6, $Pk),
  __param(7, $kl)
], EditorStatus);
var $SUb = class $SUb2 extends $3c {
  static {
    this.ID = "workbench.contrib.editorStatus";
  }
  constructor(c) {
    super();
    this.c = c;
    for (const part of c.parts) {
      this.f(part);
    }
    this.B(c.onDidCreateAuxiliaryEditorPart((part) => this.f(part)));
  }
  f(part) {
    const disposables = new $2c();
    Event2.once(part.onWillDispose)(() => disposables.dispose());
    const scopedInstantiationService = this.c.getScopedInstantiationService(part);
    disposables.add(scopedInstantiationService.createInstance(EditorStatus, part.windowId));
  }
};
$SUb = __decorate([
  __param(0, $iJ)
], $SUb);
var ShowCurrentMarkerInStatusbarContribution = class ShowCurrentMarkerInStatusbarContribution2 extends $3c {
  constructor(j, m, n) {
    super();
    this.j = j;
    this.m = m;
    this.n = n;
    this.f = void 0;
    this.g = [];
    this.h = null;
    this.c = this.B(new $4c());
    this.B(m.onMarkerChanged((changedResources) => this.y(changedResources)));
    this.B(Event2.filter(n.onDidChangeConfiguration, (e) => e.affectsConfiguration("problems.showCurrentInStatus"))(() => this.s()));
  }
  update(editor) {
    this.f = editor;
    this.z();
    this.s();
  }
  s() {
    const previousMarker = this.h;
    this.h = this.w();
    if (this.t(previousMarker, this.h)) {
      if (this.h) {
        const line = $Mf(this.h.message)[0];
        const text2 = `${this.u(this.h)} ${line}`;
        if (!this.c.value) {
          this.c.value = this.j.addEntry(
            { name: localize(3561, null), text: "", ariaLabel: "" },
            "statusbar.currentProblem",
            0
            /* StatusbarAlignment.LEFT */
          );
        }
        this.c.value.update({ name: localize(3562, null), text: text2, ariaLabel: text2 });
      } else {
        this.c.clear();
      }
    }
  }
  t(previousMarker, currentMarker) {
    if (!currentMarker) {
      return true;
    }
    if (!previousMarker) {
      return true;
    }
    return IMarkerData.makeKey(previousMarker) !== IMarkerData.makeKey(currentMarker);
  }
  u(marker) {
    switch (marker.severity) {
      case MarkerSeverity.Error:
        return "$(error)";
      case MarkerSeverity.Warning:
        return "$(warning)";
      case MarkerSeverity.Info:
        return "$(info)";
    }
    return "";
  }
  w() {
    if (!this.n.getValue("problems.showCurrentInStatus")) {
      return null;
    }
    if (!this.f) {
      return null;
    }
    const model = this.f.getModel();
    if (!model) {
      return null;
    }
    const position = this.f.getPosition();
    if (!position) {
      return null;
    }
    return this.g.find((marker) => $9C.containsPosition(marker, position)) || null;
  }
  y(changedResources) {
    if (!this.f) {
      return;
    }
    const model = this.f.getModel();
    if (!model) {
      return;
    }
    if (model && !changedResources.some((r2) => $oh(model.uri, r2))) {
      return;
    }
    this.z();
  }
  z() {
    if (!this.f) {
      return;
    }
    const model = this.f.getModel();
    if (!model) {
      return;
    }
    if (model) {
      this.g = this.m.read({
        resource: model.uri,
        severities: MarkerSeverity.Error | MarkerSeverity.Warning | MarkerSeverity.Info
      });
      this.g.sort(this.C);
    } else {
      this.g = [];
    }
    this.s();
  }
  C(a, b) {
    let res = $Tf(a.resource.toString(), b.resource.toString());
    if (res === 0) {
      res = MarkerSeverity.compare(a.severity, b.severity);
    }
    if (res === 0) {
      res = $9C.compareRangesUsingStarts(a, b);
    }
    return res;
  }
};
ShowCurrentMarkerInStatusbarContribution = __decorate([
  __param(0, $$qb),
  __param(1, $DE),
  __param(2, $kl)
], ShowCurrentMarkerInStatusbarContribution);
var $TUb = class $TUb2 extends $Um {
  static {
    $TUb_1 = this;
  }
  static {
    this.ID = "workbench.action.showLanguageExtensions";
  }
  constructor(c, f, galleryService) {
    super($TUb_1.ID, localize(3563, null, c));
    this.c = c;
    this.f = f;
    this.enabled = galleryService.isEnabled();
  }
  async run() {
    await this.f.executeCommand("workbench.extensions.action.showExtensionsForLanguage", this.c);
  }
};
$TUb = $TUb_1 = __decorate([
  __param(1, $sn),
  __param(2, $pA)
], $TUb);
var $UUb = class _$UUb extends $gJ {
  static {
    this.ID = "workbench.action.editor.changeLanguageMode";
  }
  constructor() {
    super({
      id: _$UUb.ID,
      title: localize2(3588, "Change Language Mode"),
      f1: true,
      keybinding: {
        weight: 200,
        primary: $$e(
          2048 | 41,
          43
          /* KeyCode.KeyM */
        )
      },
      precondition: $7m.not("notebookEditorFocused"),
      metadata: {
        description: localize(3564, null),
        args: [
          {
            name: localize(3565, null),
            constraint: (value) => typeof value === "string"
          }
        ]
      }
    });
  }
  async run(accessor, languageMode) {
    const quickInputService = accessor.get($1M);
    const editorService = accessor.get($mJ);
    const languageService = accessor.get($1E);
    const languageDetectionService = accessor.get($tG);
    const textFileService = accessor.get($cK);
    const preferencesService = accessor.get($TK);
    const instantiationService = accessor.get($Pk);
    const configurationService = accessor.get($kl);
    const telemetryService = accessor.get($zv);
    const activeTextEditorControl = $S5(editorService.activeTextEditorControl);
    if (!activeTextEditorControl) {
      await quickInputService.pick([{ label: localize(3566, null) }]);
      return;
    }
    const textModel = activeTextEditorControl.getModel();
    const resource = $mL.getOriginalUri(editorService.activeEditor, { supportSideBySide: SideBySideEditor.PRIMARY });
    let currentLanguageName;
    let currentLanguageId;
    if (textModel) {
      currentLanguageId = textModel.getLanguageId();
      currentLanguageName = languageService.getLanguageName(currentLanguageId) ?? void 0;
    }
    let hasLanguageSupport = !!resource;
    if (resource?.scheme === Schemas.untitled && !textFileService.untitled.get(resource)?.hasAssociatedFilePath) {
      hasLanguageSupport = false;
    }
    const languages = languageService.getSortedRegisteredLanguageNames();
    const picks = languages.map(({ languageName, languageId }) => {
      const extensions = languageService.getExtensions(languageId).join(" ");
      let description;
      if (currentLanguageName === languageName) {
        description = localize(3567, null, languageId);
      } else {
        description = localize(3568, null, languageId);
      }
      return {
        label: languageName,
        meta: extensions,
        iconClasses: $hdb(languageId),
        description
      };
    });
    picks.unshift({ type: "separator", label: localize(3569, null) });
    let configureLanguageAssociations;
    let configureLanguageSettings;
    let galleryAction;
    if (hasLanguageSupport && resource) {
      const ext = $th(resource) || $sh(resource);
      galleryAction = instantiationService.createInstance($TUb, ext);
      if (galleryAction.enabled) {
        picks.unshift(galleryAction);
      }
      configureLanguageSettings = { label: localize(3570, null, currentLanguageName) };
      picks.unshift(configureLanguageSettings);
      configureLanguageAssociations = { label: localize(3571, null, ext) };
      picks.unshift(configureLanguageAssociations);
    }
    const autoDetectLanguage = {
      label: localize(3572, null)
    };
    picks.unshift(autoDetectLanguage);
    const pick = typeof languageMode === "string" ? { label: languageMode } : await quickInputService.pick(picks, { placeHolder: localize(3573, null), matchOnDescription: true });
    if (!pick) {
      return;
    }
    if (pick === galleryAction) {
      galleryAction.run();
      return;
    }
    if (pick === configureLanguageAssociations) {
      if (resource) {
        this.c(resource, languageService, quickInputService, configurationService);
      }
      return;
    }
    if (pick === configureLanguageSettings) {
      preferencesService.openUserSettings({ jsonEditor: true, revealSetting: { key: `[${currentLanguageId ?? null}]`, edit: true } });
      return;
    }
    const activeEditor = editorService.activeEditor;
    if (activeEditor) {
      const languageSupport = toEditorWithLanguageSupport(activeEditor);
      if (languageSupport) {
        let languageSelection;
        let detectedLanguage;
        if (pick === autoDetectLanguage) {
          if (textModel) {
            const resource2 = $mL.getOriginalUri(activeEditor, { supportSideBySide: SideBySideEditor.PRIMARY });
            if (resource2) {
              let languageId = languageService.guessLanguageIdByFilepathOrFirstLine(resource2, textModel.getLineContent(1)) ?? void 0;
              if (!languageId || languageId === "unknown") {
                detectedLanguage = await languageDetectionService.detectLanguage(resource2);
                languageId = detectedLanguage;
              }
              if (languageId) {
                languageSelection = languageService.createById(languageId);
              }
            }
          }
        } else {
          const languageId = languageService.getLanguageIdByLanguageName(pick.label);
          languageSelection = languageService.createById(languageId);
          if (resource) {
            languageDetectionService.detectLanguage(resource).then((detectedLanguageId) => {
              const chosenLanguageId = languageService.getLanguageIdByLanguageName(pick.label) || "unknown";
              if (detectedLanguageId === currentLanguageId && currentLanguageId !== chosenLanguageId) {
                const modelPreference = configurationService.getValue("workbench.editor.preferHistoryBasedLanguageDetection") ? "history" : "classic";
                telemetryService.publicLog2($vG, {
                  currentLanguageId: currentLanguageName ?? "unknown",
                  nextLanguageId: pick.label,
                  lineCount: textModel?.getLineCount() ?? -1,
                  modelPreference
                });
              }
            });
          }
        }
        if (typeof languageSelection !== "undefined") {
          languageSupport.setLanguageId(languageSelection.languageId, _$UUb.ID);
          if (resource?.scheme === Schemas.untitled) {
            const modelPreference = configurationService.getValue("workbench.editor.preferHistoryBasedLanguageDetection") ? "history" : "classic";
            telemetryService.publicLog2("setUntitledDocumentLanguage", {
              to: languageSelection.languageId,
              from: currentLanguageId ?? "none",
              modelPreference
            });
          }
        }
      }
      activeTextEditorControl.focus();
    }
  }
  c(resource, languageService, quickInputService, configurationService) {
    const extension = $th(resource);
    const base = $sh(resource);
    const currentAssociation = languageService.guessLanguageIdByFilepathOrFirstLine(URI.file(base));
    const languages = languageService.getSortedRegisteredLanguageNames();
    const picks = languages.map(({ languageName, languageId }) => {
      return {
        id: languageId,
        label: languageName,
        iconClasses: $hdb(languageId),
        description: languageId === currentAssociation ? localize(3574, null) : void 0
      };
    });
    setTimeout(
      async () => {
        const language = await quickInputService.pick(picks, { placeHolder: localize(3575, null, extension || base) });
        if (language) {
          const fileAssociationsConfig = configurationService.inspect($Km);
          let associationKey;
          if (extension && base[0] !== ".") {
            associationKey = `*${extension}`;
          } else {
            associationKey = base;
          }
          let target = 2;
          if (fileAssociationsConfig.workspaceValue && !!fileAssociationsConfig.workspaceValue[associationKey]) {
            target = 5;
          }
          const currentAssociations = $Lv(target === 5 ? fileAssociationsConfig.workspaceValue : fileAssociationsConfig.userValue) || /* @__PURE__ */ Object.create(null);
          currentAssociations[associationKey] = language.id;
          configurationService.updateValue($Km, currentAssociations, target);
        }
      },
      50
      /* quick input is sensitive to being opened so soon after another */
    );
  }
};
var $VUb = class extends $gJ {
  constructor() {
    super({
      id: "workbench.action.editor.changeEOL",
      title: localize2(3589, "Change End of Line Sequence"),
      f1: true
    });
  }
  async run(accessor) {
    const editorService = accessor.get($mJ);
    const quickInputService = accessor.get($1M);
    const activeTextEditorControl = $S5(editorService.activeTextEditorControl);
    if (!activeTextEditorControl) {
      await quickInputService.pick([{ label: localize(3576, null) }]);
      return;
    }
    if (editorService.activeEditor?.isReadonly()) {
      await quickInputService.pick([{ label: localize(3577, null) }]);
      return;
    }
    let textModel = activeTextEditorControl.getModel();
    const EOLOptions = [
      {
        label: nlsEOLLF,
        eol: 0
        /* EndOfLineSequence.LF */
      },
      {
        label: nlsEOLCRLF,
        eol: 1
        /* EndOfLineSequence.CRLF */
      }
    ];
    const selectedIndex = textModel?.getEOL() === "\n" ? 0 : 1;
    const eol = await quickInputService.pick(EOLOptions, { placeHolder: localize(3578, null), activeItem: EOLOptions[selectedIndex] });
    if (eol) {
      const activeCodeEditor = $S5(editorService.activeTextEditorControl);
      if (activeCodeEditor?.hasModel() && !editorService.activeEditor?.isReadonly()) {
        textModel = activeCodeEditor.getModel();
        textModel.pushStackElement();
        textModel.pushEOL(eol.eol);
        textModel.pushStackElement();
      }
    }
    activeTextEditorControl.focus();
  }
};
var $WUb = class extends $gJ {
  constructor() {
    super({
      id: "workbench.action.editor.changeEncoding",
      title: localize2(3590, "Change File Encoding"),
      f1: true
    });
  }
  async run(accessor) {
    const editorService = accessor.get($mJ);
    const quickInputService = accessor.get($1M);
    const fileService = accessor.get($km);
    const textFileService = accessor.get($cK);
    const textResourceConfigurationService = accessor.get($zG);
    const activeTextEditorControl = $S5(editorService.activeTextEditorControl);
    if (!activeTextEditorControl) {
      await quickInputService.pick([{ label: localize(3579, null) }]);
      return;
    }
    const activeEditorPane = editorService.activeEditorPane;
    if (!activeEditorPane) {
      await quickInputService.pick([{ label: localize(3580, null) }]);
      return;
    }
    const encodingSupport = toEditorWithEncodingSupport(activeEditorPane.input);
    if (!encodingSupport) {
      await quickInputService.pick([{ label: localize(3581, null) }]);
      return;
    }
    const saveWithEncodingPick = { label: localize(3582, null) };
    const reopenWithEncodingPick = { label: localize(3583, null) };
    if (!Language.isDefaultVariant()) {
      const saveWithEncodingAlias = "Save with Encoding";
      if (saveWithEncodingAlias !== saveWithEncodingPick.label) {
        saveWithEncodingPick.detail = saveWithEncodingAlias;
      }
      const reopenWithEncodingAlias = "Reopen with Encoding";
      if (reopenWithEncodingAlias !== reopenWithEncodingPick.label) {
        reopenWithEncodingPick.detail = reopenWithEncodingAlias;
      }
    }
    let action;
    if (encodingSupport instanceof $0Gb) {
      action = saveWithEncodingPick;
    } else if (activeEditorPane.input.isReadonly()) {
      action = reopenWithEncodingPick;
    } else {
      action = await quickInputService.pick([reopenWithEncodingPick, saveWithEncodingPick], { placeHolder: localize(3584, null), matchOnDetail: true });
    }
    if (!action) {
      return;
    }
    await $Wh(50);
    const resource = $mL.getOriginalUri(activeEditorPane.input, { supportSideBySide: SideBySideEditor.PRIMARY });
    if (!resource || !fileService.hasProvider(resource) && resource.scheme !== Schemas.untitled) {
      return;
    }
    let guessedEncoding = void 0;
    if (fileService.hasProvider(resource)) {
      const content = await textFileService.readStream(resource, {
        autoGuessEncoding: true,
        candidateGuessEncodings: textResourceConfigurationService.getValue(resource, "files.candidateGuessEncodings")
      });
      guessedEncoding = content.encoding;
    }
    const isReopenWithEncoding = action === reopenWithEncodingPick;
    const configuredEncoding = textResourceConfigurationService.getValue(resource, "files.encoding");
    let directMatchIndex;
    let aliasMatchIndex;
    const picks = Object.keys($KJ).sort((k1, k2) => {
      if (k1 === configuredEncoding) {
        return -1;
      } else if (k2 === configuredEncoding) {
        return 1;
      }
      return $KJ[k1].order - $KJ[k2].order;
    }).filter((k) => {
      if (k === guessedEncoding && guessedEncoding !== configuredEncoding) {
        return false;
      }
      return !isReopenWithEncoding || !$KJ[k].encodeOnly;
    }).map((key2, index) => {
      if (key2 === encodingSupport.getEncoding()) {
        directMatchIndex = index;
      } else if ($KJ[key2].alias === encodingSupport.getEncoding()) {
        aliasMatchIndex = index;
      }
      return { id: key2, label: $KJ[key2].labelLong, description: key2 };
    });
    const items = picks.slice();
    if (guessedEncoding && configuredEncoding !== guessedEncoding && $KJ[guessedEncoding]) {
      picks.unshift({ type: "separator" });
      picks.unshift({ id: guessedEncoding, label: $KJ[guessedEncoding].labelLong, description: localize(3585, null) });
    }
    const encoding = await quickInputService.pick(picks, {
      placeHolder: isReopenWithEncoding ? localize(3586, null) : localize(3587, null),
      activeItem: items[typeof directMatchIndex === "number" ? directMatchIndex : typeof aliasMatchIndex === "number" ? aliasMatchIndex : -1]
    });
    if (!encoding) {
      return;
    }
    if (!editorService.activeEditorPane) {
      return;
    }
    const activeEncodingSupport = toEditorWithEncodingSupport(editorService.activeEditorPane.input);
    if (typeof encoding.id !== "undefined" && activeEncodingSupport) {
      await activeEncodingSupport.setEncoding(
        encoding.id,
        isReopenWithEncoding ? 1 : 0
        /* EncodingMode.Encode */
      );
    }
    activeTextEditorControl.focus();
  }
};

// out-build/vs/platform/actions/browser/floatingMenu.js
var $yLb = class extends $qZ {
  constructor(g) {
    super();
    this.g = g;
    this.a = this.B(new $ze());
    this.onClick = this.a.event;
    this.c = $(".floating-click-widget");
    this.c.style.padding = "6px 11px";
    this.c.style.borderRadius = "2px";
    this.c.style.cursor = "pointer";
    this.c.style.zIndex = "1";
  }
  getDomNode() {
    return this.c;
  }
  render() {
    $$i(this.c);
    this.c.style.backgroundColor = $1n($Uq, $Zn($Ko));
    this.c.style.color = $1n($Sq, $Zn($Lo));
    this.c.style.border = `1px solid ${$Zn($ko)}`;
    $bk(this.c, $("")).textContent = this.g;
    this.b(this.c, () => this.a.fire());
  }
};
var $zLb = class $zLb2 extends $3c {
  constructor(menuId, menuService, contextKeyService) {
    super();
    this.a = new $ze();
    this.b = this.a.event;
    this.c = this.B(menuService.createMenu(menuId, contextKeyService));
  }
  /** Should be called in implementation constructors after they initialized */
  f() {
    const menuDisposables = this.B(new $2c());
    const renderMenuAsFloatingClickBtn = () => {
      menuDisposables.clear();
      if (!this.j()) {
        return;
      }
      const actions = $R$(this.c.getActions({ renderShortTitle: true, shouldForwardArgs: true }));
      if (actions.length === 0) {
        return;
      }
      const [first] = actions;
      const widget = this.g(first, menuDisposables);
      menuDisposables.add(widget);
      menuDisposables.add(widget.onClick(() => first.run(this.h())));
      widget.render();
    };
    this.B(this.c.onDidChange(renderMenuAsFloatingClickBtn));
    renderMenuAsFloatingClickBtn();
  }
  h() {
    return void 0;
  }
  j() {
    return true;
  }
};
$zLb = __decorate([
  __param(1, $cJ),
  __param(2, $on)
], $zLb);
var $ALb = class $ALb2 extends $zLb {
  constructor(m, n, menuService, contextKeyService) {
    super(m.menuId, menuService, contextKeyService);
    this.m = m;
    this.n = n;
    this.f();
  }
  g(action, disposable) {
    const w = this.n.createInstance($yLb, action.label);
    const node = w.getDomNode();
    this.m.container.appendChild(node);
    disposable.add($1c(() => node.remove()));
    return w;
  }
  h() {
    return this.m.getActionArg();
  }
};
$ALb = __decorate([
  __param(1, $Pk),
  __param(2, $cJ),
  __param(3, $on)
], $ALb);

// out-build/vs/workbench/browser/codeeditor.js
var $BLb_1;
var $BLb = class $BLb2 extends $3c {
  static {
    $BLb_1 = this;
  }
  constructor(g) {
    super();
    this.g = g;
    this.a = this.B(new $ze());
    this.onHighlightRemoved = this.a.event;
    this.b = null;
    this.c = null;
    this.f = this.B(new $2c());
  }
  removeHighlightRange() {
    if (this.c && this.b) {
      const decorationId = this.b;
      this.c.changeDecorations((accessor) => {
        accessor.removeDecoration(decorationId);
      });
      this.a.fire();
    }
    this.b = null;
  }
  highlightRange(range, editor) {
    editor = editor ?? this.j(range);
    if ($P5(editor)) {
      this.h(editor, range);
    } else if ($R5(editor) && $P5(editor.activeCodeEditor)) {
      this.h(editor.activeCodeEditor, range);
    }
  }
  h(editor, selectionRange) {
    this.removeHighlightRange();
    editor.changeDecorations((changeAccessor) => {
      this.b = changeAccessor.addDecoration(selectionRange.range, this.s(selectionRange.isWholeLine));
    });
    this.m(editor);
  }
  j(resourceRange) {
    const resource = this.g.activeEditor?.resource;
    if (resource && $oh(resource, resourceRange.resource) && $P5(this.g.activeTextEditorControl)) {
      return this.g.activeTextEditorControl;
    }
    return void 0;
  }
  m(editor) {
    if (this.c !== editor) {
      this.f.clear();
      this.c = editor;
      this.f.add(this.c.onDidChangeCursorPosition((e) => {
        if (e.reason === 0 || e.reason === 3 || e.reason === 5 || e.reason === 6) {
          this.removeHighlightRange();
        }
      }));
      this.f.add(this.c.onDidChangeModel(() => {
        this.removeHighlightRange();
      }));
      this.f.add(this.c.onDidDispose(() => {
        this.removeHighlightRange();
        this.c = null;
      }));
    }
  }
  static {
    this.n = $WI.register({
      description: "codeeditor-range-highlight-whole",
      stickiness: 1,
      className: "rangeHighlight",
      isWholeLine: true
    });
  }
  static {
    this.r = $WI.register({
      description: "codeeditor-range-highlight",
      stickiness: 1,
      className: "rangeHighlight"
    });
  }
  s(isWholeLine = true) {
    return isWholeLine ? $BLb_1.n : $BLb_1.r;
  }
  dispose() {
    super.dispose();
    if (this.c?.getModel()) {
      this.removeHighlightRange();
      this.c = null;
    }
  }
};
$BLb = $BLb_1 = __decorate([
  __param(0, $mJ)
], $BLb);
var $CLb = class $CLb2 extends $yLb {
  constructor(h3, label3, keyBindingAction, keybindingService) {
    super(keyBindingAction && keybindingService.lookupKeybinding(keyBindingAction) ? `${label3} (${keybindingService.lookupKeybinding(keyBindingAction).getLabel()})` : label3);
    this.h = h3;
  }
  getId() {
    return "editor.overlayWidget.floatingClickWidget";
  }
  getPosition() {
    return {
      preference: 1
      /* OverlayWidgetPositionPreference.BOTTOM_RIGHT_CORNER */
    };
  }
  render() {
    super.render();
    this.h.addOverlayWidget(this);
  }
  dispose() {
    this.h.removeOverlayWidget(this);
    super.dispose();
  }
};
$CLb = __decorate([
  __param(3, $Ty)
], $CLb);
var $DLb = class $DLb2 extends $zLb {
  static {
    this.ID = "editor.contrib.floatingClickMenu";
  }
  constructor(m, n, menuService, contextKeyService) {
    super($bJ.EditorContent, menuService, contextKeyService);
    this.m = m;
    this.n = n;
    this.f();
  }
  g(action) {
    return this.n.createInstance($CLb, this.m, action.label, action.id);
  }
  j() {
    return !(this.m instanceof $bdb) && this.m?.hasModel() && !this.m.getOption(
      63
      /* EditorOption.inDiffEditor */
    );
  }
  h() {
    return this.m.getModel()?.uri;
  }
};
$DLb = __decorate([
  __param(1, $Pk),
  __param(2, $cJ),
  __param(3, $on)
], $DLb);

// out-build/vs/workbench/browser/parts/editor/editorAutoSave.js
var $XUb = class $XUb2 extends $3c {
  static {
    this.ID = "workbench.contrib.editorAutoSave";
  }
  constructor(j, m, n, r2, s, t, u, w) {
    super();
    this.j = j;
    this.m = m;
    this.n = n;
    this.r = r2;
    this.s = s;
    this.t = t;
    this.u = u;
    this.w = w;
    this.a = /* @__PURE__ */ new Map();
    this.b = void 0;
    this.c = void 0;
    this.f = this.B(new $2c());
    this.g = new $Ec((resource) => this.w.extUri.getComparisonKey(resource));
    this.h = new $Ec((resource) => this.w.extUri.getComparisonKey(resource));
    for (const dirtyWorkingCopy of this.s.dirtyWorkingCopies) {
      this.J(dirtyWorkingCopy);
    }
    this.y();
  }
  y() {
    this.B(this.m.onDidChangeFocus((focused) => this.C(focused)));
    this.B(this.m.onDidChangeActiveWindow(() => this.D()));
    this.B(this.n.onDidActiveEditorChange(() => this.F()));
    this.B(this.j.onDidChangeAutoSaveConfiguration(() => this.H()));
    this.B(this.s.onDidRegister((workingCopy) => this.J(workingCopy)));
    this.B(this.s.onDidUnregister((workingCopy) => this.L(workingCopy)));
    this.B(this.s.onDidChangeDirty((workingCopy) => this.M(workingCopy)));
    this.B(this.s.onDidChangeContent((workingCopy) => this.N(workingCopy)));
    this.B(this.u.onMarkerChanged((e) => this.z(
      e,
      3
      /* AutoSaveDisabledReason.ERRORS */
    )));
    this.B(this.j.onDidChangeAutoSaveDisabled((resource) => this.z(
      [resource],
      4
      /* AutoSaveDisabledReason.DISABLED */
    )));
  }
  z(resources, condition) {
    for (const resource of resources) {
      const workingCopyResult = this.g.get(resource);
      if (workingCopyResult?.condition === condition) {
        if (workingCopyResult.workingCopy.isDirty() && this.j.getAutoSaveMode(workingCopyResult.workingCopy.resource, workingCopyResult.reason).mode !== 0) {
          this.P(workingCopyResult.workingCopy);
          this.t.trace(`[editor auto save] running auto save from condition change event`, workingCopyResult.workingCopy.resource.toString(), workingCopyResult.workingCopy.typeId);
          workingCopyResult.workingCopy.save({ reason: workingCopyResult.reason });
        }
      } else {
        const editorResult = this.h.get(resource);
        if (editorResult?.condition === condition && !editorResult.editor.editor.isDisposed() && editorResult.editor.editor.isDirty() && this.j.getAutoSaveMode(editorResult.editor.editor, editorResult.reason).mode !== 0) {
          this.h.delete(resource);
          this.t.trace(`[editor auto save] running auto save from condition change event with reason ${editorResult.reason}`);
          this.n.save(editorResult.editor, { reason: editorResult.reason });
        }
      }
    }
  }
  C(focused) {
    if (!focused) {
      this.G(
        4
        /* SaveReason.WINDOW_CHANGE */
      );
    }
  }
  D() {
    this.G(
      4
      /* SaveReason.WINDOW_CHANGE */
    );
  }
  F() {
    if (this.b && typeof this.c === "number") {
      this.G(3, { groupId: this.c, editor: this.b });
    }
    const activeGroup = this.r.activeGroup;
    const activeEditor = this.b = activeGroup.activeEditor ?? void 0;
    this.c = activeGroup.id;
    this.f.clear();
    const activeEditorPane = this.n.activeEditorPane;
    if (activeEditor && activeEditorPane) {
      this.f.add(activeEditorPane.onDidBlur(() => {
        this.G(3, { groupId: activeGroup.id, editor: activeEditor });
      }));
    }
  }
  G(reason, editorIdentifier) {
    if (editorIdentifier) {
      if (!editorIdentifier.editor.isDirty() || editorIdentifier.editor.isReadonly() || editorIdentifier.editor.hasCapability(
        4
        /* EditorInputCapabilities.Untitled */
      )) {
        return;
      }
      const autoSaveMode = this.j.getAutoSaveMode(editorIdentifier.editor, reason);
      if (autoSaveMode.mode !== 0) {
        if (reason === 4 && (autoSaveMode.mode === 3 || autoSaveMode.mode === 4) || reason === 3 && autoSaveMode.mode === 3) {
          this.t.trace(`[editor auto save] triggering auto save with reason ${reason}`);
          this.n.save(editorIdentifier, { reason });
        }
      } else if (editorIdentifier.editor.resource && (autoSaveMode.reason === 3 || autoSaveMode.reason === 4)) {
        this.h.set(editorIdentifier.editor.resource, { editor: editorIdentifier, reason, condition: autoSaveMode.reason });
      }
    } else {
      this.I(reason);
    }
  }
  H() {
    let reason = void 0;
    switch (this.j.getAutoSaveMode(void 0).mode) {
      case 3:
        reason = 3;
        break;
      case 4:
        reason = 4;
        break;
      case 1:
      case 2:
        reason = 2;
        break;
    }
    if (reason) {
      this.I(reason);
    }
  }
  I(reason) {
    for (const workingCopy of this.s.dirtyWorkingCopies) {
      if (workingCopy.capabilities & 2) {
        continue;
      }
      const autoSaveMode = this.j.getAutoSaveMode(workingCopy.resource, reason);
      if (autoSaveMode.mode !== 0) {
        workingCopy.save({ reason });
      } else if (autoSaveMode.reason === 3 || autoSaveMode.reason === 4) {
        this.g.set(workingCopy.resource, { workingCopy, reason, condition: autoSaveMode.reason });
      }
    }
  }
  J(workingCopy) {
    if (workingCopy.isDirty()) {
      this.O(workingCopy);
    }
  }
  L(workingCopy) {
    this.P(workingCopy);
  }
  M(workingCopy) {
    if (workingCopy.isDirty()) {
      this.O(workingCopy);
    } else {
      this.P(workingCopy);
    }
  }
  N(workingCopy) {
    if (workingCopy.isDirty()) {
      this.O(workingCopy);
    }
  }
  O(workingCopy) {
    if (workingCopy.capabilities & 2) {
      return;
    }
    const autoSaveAfterDelay = this.j.getAutoSaveConfiguration(workingCopy.resource).autoSaveDelay;
    if (typeof autoSaveAfterDelay !== "number") {
      return;
    }
    this.P(workingCopy);
    this.t.trace(`[editor auto save] scheduling auto save after ${autoSaveAfterDelay}ms`, workingCopy.resource.toString(), workingCopy.typeId);
    const handle2 = setTimeout(() => {
      this.P(workingCopy);
      if (workingCopy.isDirty()) {
        const reason = 2;
        const autoSaveMode = this.j.getAutoSaveMode(workingCopy.resource, reason);
        if (autoSaveMode.mode !== 0) {
          this.t.trace(`[editor auto save] running auto save`, workingCopy.resource.toString(), workingCopy.typeId);
          workingCopy.save({ reason });
        } else if (autoSaveMode.reason === 3 || autoSaveMode.reason === 4) {
          this.g.set(workingCopy.resource, { workingCopy, reason, condition: autoSaveMode.reason });
        }
      }
    }, autoSaveAfterDelay);
    this.a.set(workingCopy, $1c(() => {
      this.t.trace(`[editor auto save] clearing pending auto save`, workingCopy.resource.toString(), workingCopy.typeId);
      clearTimeout(handle2);
    }));
  }
  P(workingCopy) {
    $Xc(this.a.get(workingCopy));
    this.a.delete(workingCopy);
    this.g.delete(workingCopy.resource);
    this.h.delete(workingCopy.resource);
  }
};
$XUb = __decorate([
  __param(0, $4J),
  __param(1, $S4),
  __param(2, $mJ),
  __param(3, $iJ),
  __param(4, $XI),
  __param(5, $wn),
  __param(6, $DE),
  __param(7, $vl)
], $XUb);

// out-build/vs/platform/quickinput/common/quickAccess.js
var DefaultQuickAccessFilterValue;
(function(DefaultQuickAccessFilterValue2) {
  DefaultQuickAccessFilterValue2[DefaultQuickAccessFilterValue2["PRESERVE"] = 0] = "PRESERVE";
  DefaultQuickAccessFilterValue2[DefaultQuickAccessFilterValue2["LAST"] = 1] = "LAST";
})(DefaultQuickAccessFilterValue || (DefaultQuickAccessFilterValue = {}));
var $CM = {
  Quickaccess: "workbench.contributions.quickaccess"
};
var $DM = class {
  constructor() {
    this.a = [];
    this.b = void 0;
  }
  registerQuickAccessProvider(provider) {
    if (provider.prefix.length === 0) {
      this.b = provider;
    } else {
      this.a.push(provider);
    }
    this.a.sort((providerA, providerB) => providerB.prefix.length - providerA.prefix.length);
    return $1c(() => {
      this.a.splice(this.a.indexOf(provider), 1);
      if (this.b === provider) {
        this.b = void 0;
      }
    });
  }
  getQuickAccessProviders() {
    return $Mb([this.b, ...this.a]);
  }
  getQuickAccessProvider(prefix) {
    const result = prefix ? this.a.find((provider) => prefix.startsWith(provider.prefix)) || void 0 : void 0;
    return result || this.b;
  }
  clear() {
    const providers2 = [...this.a];
    const defaultProvider = this.b;
    this.a = [];
    this.b = void 0;
    return () => {
      this.a = providers2;
      this.b = defaultProvider;
    };
  }
};
$Wn.add($CM.Quickaccess, new $DM());

// out-build/vs/workbench/services/textfile/common/textEditorService.js
var $YUb = $Qk("textEditorService");
var $ZUb = class $ZUb2 extends $3c {
  constructor(c, f, g, h3, j) {
    super();
    this.c = c;
    this.f = f;
    this.g = g;
    this.h = h3;
    this.j = j;
    this.a = new $Ec();
    this.b = $Wn.as($ZK.EditorFactory).getFileEditorFactory();
    this.m();
  }
  m() {
    this.B(this.j.registerEditor("*", {
      id: $1K.id,
      label: $1K.displayName,
      detail: $1K.providerDisplayName,
      priority: RegisteredEditorPriority.builtin
    }, {}, {
      createEditorInput: (editor) => ({ editor: this.createTextEditor(editor) }),
      createUntitledEditorInput: (untitledEditor) => ({ editor: this.createTextEditor(untitledEditor) }),
      createDiffEditorInput: (diffEditor) => ({ editor: this.createTextEditor(diffEditor) })
    }));
  }
  async resolveTextEditor(input) {
    return this.createTextEditor(input);
  }
  createTextEditor(input) {
    if ($aL(input)) {
      return this.createTextEditor(input.result);
    }
    if ($9K(input)) {
      const original = this.createTextEditor(input.original);
      const modified = this.createTextEditor(input.modified);
      return this.f.createInstance($fub, input.label, input.description, original, modified, void 0);
    }
    if ($$K(input)) {
      const primary = this.createTextEditor(input.primary);
      const secondary = this.createTextEditor(input.secondary);
      return this.f.createInstance($1I, input.label, input.description, secondary, primary);
    }
    const untitledInput = input;
    if (untitledInput.forceUntitled || !untitledInput.resource || untitledInput.resource.scheme === Schemas.untitled) {
      const untitledOptions = {
        languageId: untitledInput.languageId,
        initialValue: untitledInput.contents,
        encoding: untitledInput.encoding
      };
      let untitledModel;
      if (untitledInput.resource?.scheme === Schemas.untitled) {
        untitledModel = this.c.create({ untitledResource: untitledInput.resource, ...untitledOptions });
      } else {
        untitledModel = this.c.create({ associatedResource: untitledInput.resource, ...untitledOptions });
      }
      return this.n(untitledModel.resource, () => this.f.createInstance($0Gb, untitledModel));
    }
    const textResourceEditorInput = input;
    if (textResourceEditorInput.resource instanceof URI) {
      const label3 = textResourceEditorInput.label || $sh(textResourceEditorInput.resource);
      const preferredResource = textResourceEditorInput.resource;
      const canonicalResource = this.g.asCanonicalUri(preferredResource);
      return this.n(canonicalResource, () => {
        if (textResourceEditorInput.forceFile || this.h.hasProvider(canonicalResource)) {
          return this.b.createFileEditor(canonicalResource, preferredResource, textResourceEditorInput.label, textResourceEditorInput.description, textResourceEditorInput.encoding, textResourceEditorInput.languageId, textResourceEditorInput.contents, this.f);
        }
        return this.f.createInstance($6vb, canonicalResource, textResourceEditorInput.label, textResourceEditorInput.description, textResourceEditorInput.languageId, textResourceEditorInput.contents);
      }, (cachedInput) => {
        if (cachedInput instanceof $0Gb) {
          return;
        } else if (!(cachedInput instanceof $6vb)) {
          cachedInput.setPreferredResource(preferredResource);
          if (textResourceEditorInput.label) {
            cachedInput.setPreferredName(textResourceEditorInput.label);
          }
          if (textResourceEditorInput.description) {
            cachedInput.setPreferredDescription(textResourceEditorInput.description);
          }
          if (textResourceEditorInput.encoding) {
            cachedInput.setPreferredEncoding(textResourceEditorInput.encoding);
          }
          if (textResourceEditorInput.languageId) {
            cachedInput.setPreferredLanguageId(textResourceEditorInput.languageId);
          }
          if (typeof textResourceEditorInput.contents === "string") {
            cachedInput.setPreferredContents(textResourceEditorInput.contents);
          }
        } else {
          if (label3) {
            cachedInput.setName(label3);
          }
          if (textResourceEditorInput.description) {
            cachedInput.setDescription(textResourceEditorInput.description);
          }
          if (textResourceEditorInput.languageId) {
            cachedInput.setPreferredLanguageId(textResourceEditorInput.languageId);
          }
          if (typeof textResourceEditorInput.contents === "string") {
            cachedInput.setPreferredContents(textResourceEditorInput.contents);
          }
        }
      });
    }
    throw new Error(`ITextEditorService: Unable to create texteditor from ${JSON.stringify(input)}`);
  }
  n(resource, factoryFn, cachedFn) {
    let input = this.a.get(resource);
    if (input) {
      cachedFn?.(input);
      return input;
    }
    input = factoryFn();
    this.a.set(resource, input);
    Event2.once(input.onWillDispose)(() => this.a.delete(resource));
    return input;
  }
};
$ZUb = __decorate([
  __param(0, $NJ),
  __param(1, $Pk),
  __param(2, $vl),
  __param(3, $km),
  __param(4, $4L)
], $ZUb);
$SC(
  $YUb,
  $ZUb,
  0
  /* InstantiationType.Eager */
);

// out-build/vs/workbench/services/workingCopy/common/workingCopyEditorService.js
var $6J = $Qk("workingCopyEditorService");
var $7J = class $7J2 extends $3c {
  constructor(c) {
    super();
    this.c = c;
    this.a = this.B(new $ze());
    this.onDidRegisterHandler = this.a.event;
    this.b = /* @__PURE__ */ new Set();
  }
  registerHandler(handler) {
    this.b.add(handler);
    this.a.fire(handler);
    return $1c(() => this.b.delete(handler));
  }
  findEditor(workingCopy) {
    for (const editorIdentifier of this.c.getEditors(
      0
      /* EditorsOrder.MOST_RECENTLY_ACTIVE */
    )) {
      if (this.f(workingCopy, editorIdentifier.editor)) {
        return editorIdentifier;
      }
    }
    return void 0;
  }
  f(workingCopy, editor) {
    for (const handler of this.b) {
      if (handler.isOpen(workingCopy, editor)) {
        return true;
      }
    }
    return false;
  }
};
$7J = __decorate([
  __param(0, $mJ)
], $7J);
$SC(
  $6J,
  $7J,
  1
  /* InstantiationType.Delayed */
);

// out-build/vs/workbench/services/untitled/common/untitledTextEditorHandler.js
var $1Ub = class $1Ub2 {
  constructor(a, b, c) {
    this.a = a;
    this.b = b;
    this.c = c;
  }
  canSerialize(editorInput) {
    return this.a.isHotExitEnabled && !editorInput.isDisposed();
  }
  serialize(editorInput) {
    if (!this.canSerialize(editorInput)) {
      return void 0;
    }
    const untitledTextEditorInput = editorInput;
    let resource = untitledTextEditorInput.resource;
    if (untitledTextEditorInput.hasAssociatedFilePath) {
      resource = $Fh(resource, this.b.remoteAuthority, this.c.defaultUriScheme);
    }
    let languageId;
    const languageIdCandidate = untitledTextEditorInput.getLanguageId();
    if (languageIdCandidate !== $KF) {
      languageId = languageIdCandidate;
    } else if (untitledTextEditorInput.hasLanguageSetExplicitly) {
      languageId = languageIdCandidate;
    }
    const serialized = {
      resourceJSON: resource.toJSON(),
      modeId: languageId,
      encoding: untitledTextEditorInput.getEncoding()
    };
    return JSON.stringify(serialized);
  }
  deserialize(instantiationService, serializedEditorInput) {
    return instantiationService.invokeFunction((accessor) => {
      const deserialized = JSON.parse(serializedEditorInput);
      const resource = URI.revive(deserialized.resourceJSON);
      const languageId = deserialized.modeId;
      const encoding = deserialized.encoding;
      return accessor.get($YUb).createTextEditor({ resource, languageId, encoding, forceUntitled: true });
    });
  }
};
$1Ub = __decorate([
  __param(0, $4J),
  __param(1, $US),
  __param(2, $aT)
], $1Ub);
var $2Ub = class $2Ub2 extends $3c {
  static {
    this.ID = "workbench.contrib.untitledTextEditorWorkingCopyEditorHandler";
  }
  constructor(workingCopyEditorService, a, b, c, f) {
    super();
    this.a = a;
    this.b = b;
    this.c = c;
    this.f = f;
    this.B(workingCopyEditorService.registerHandler(this));
  }
  handles(workingCopy) {
    return workingCopy.resource.scheme === Schemas.untitled && workingCopy.typeId === $qG;
  }
  isOpen(workingCopy, editor) {
    if (!this.handles(workingCopy)) {
      return false;
    }
    return editor instanceof $0Gb && $oh(workingCopy.resource, editor.resource);
  }
  createEditor(workingCopy) {
    let editorInputResource;
    if (this.f.isUntitledWithAssociatedResource(workingCopy.resource)) {
      editorInputResource = $Fh(workingCopy.resource, this.a.remoteAuthority, this.b.defaultUriScheme);
    } else {
      editorInputResource = workingCopy.resource;
    }
    return this.c.createTextEditor({ resource: editorInputResource, forceUntitled: true });
  }
};
$2Ub = __decorate([
  __param(0, $6J),
  __param(1, $US),
  __param(2, $aT),
  __param(3, $YUb),
  __param(4, $NJ)
], $2Ub);

// out-build/vs/workbench/browser/parts/editor/editorConfiguration.js
var $3Ub_1;
var $3Ub = class $3Ub2 extends $3c {
  static {
    $3Ub_1 = this;
  }
  static {
    this.ID = "workbench.contrib.dynamicEditorConfigurations";
  }
  static {
    this.a = /* @__PURE__ */ new Set([
      "terminalEditor",
      "mainThreadWebview-simpleBrowser.view",
      "mainThreadWebview-browserPreview"
    ]);
  }
  static {
    this.b = [
      // List some editor input identifiers that are not
      // registered yet via the editor resolver infrastructure
      {
        id: "workbench.input.interactive",
        label: localize(3480, null),
        priority: RegisteredEditorPriority.builtin
      },
      {
        id: "mainThreadWebview-markdown.preview",
        label: localize(3481, null),
        priority: RegisteredEditorPriority.builtin
      },
      {
        id: "mainThreadWebview-simpleBrowser.view",
        label: localize(3482, null),
        priority: RegisteredEditorPriority.builtin
      },
      {
        id: "mainThreadWebview-browserPreview",
        label: localize(3483, null),
        priority: RegisteredEditorPriority.builtin
      }
    ];
  }
  static {
    this.c = /* @__PURE__ */ new Set([
      // List some editor types that the above `AUTO_LOCK_EXTRA_EDITORS`
      // already covers to avoid duplicates.
      "vscode-interactive-input",
      "interactive",
      "vscode.markdown.preview.editor"
    ]);
  }
  constructor(n, extensionService, r2) {
    super();
    this.n = n;
    this.r = r2;
    this.f = $Wn.as($Ht.Configuration);
    (async () => {
      await extensionService.whenInstalledExtensionsRegistered();
      this.t();
      this.s();
    })();
  }
  s() {
    this.B(Event2.debounce(this.n.onDidChangeEditorRegistrations, (_, e) => e)(() => this.t()));
  }
  t() {
    const lockableEditors = [...this.n.getEditors(), ...$3Ub_1.b].filter((e) => !$3Ub_1.c.has(e.id));
    const binaryEditorCandidates = this.n.getEditors().filter((e) => e.priority !== RegisteredEditorPriority.exclusive).map((e) => e.id);
    const autoLockGroupConfiguration = /* @__PURE__ */ Object.create(null);
    for (const editor of lockableEditors) {
      autoLockGroupConfiguration[editor.id] = {
        type: "boolean",
        default: $3Ub_1.a.has(editor.id),
        description: editor.label
      };
    }
    const defaultAutoLockGroupConfiguration = /* @__PURE__ */ Object.create(null);
    for (const editor of lockableEditors) {
      defaultAutoLockGroupConfiguration[editor.id] = $3Ub_1.a.has(editor.id);
    }
    const oldAutoLockConfigurationNode = this.g;
    this.g = {
      ...$UL,
      properties: {
        "workbench.editor.autoLockGroups": {
          type: "object",
          description: localize(3484, null),
          properties: autoLockGroupConfiguration,
          default: defaultAutoLockGroupConfiguration,
          additionalProperties: false
        }
      }
    };
    const oldDefaultBinaryEditorConfigurationNode = this.h;
    this.h = {
      ...$UL,
      properties: {
        "workbench.editor.defaultBinaryEditor": {
          type: "string",
          default: "",
          // This allows for intellisense autocompletion
          enum: [...binaryEditorCandidates, ""],
          description: localize(3485, null)
        }
      }
    };
    const oldEditorAssociationsConfigurationNode = this.j;
    this.j = {
      ...$UL,
      properties: {
        "workbench.editorAssociations": {
          type: "object",
          markdownDescription: localize(3486, null),
          patternProperties: {
            ".*": {
              type: "string",
              enum: binaryEditorCandidates
            }
          }
        }
      }
    };
    const oldEditorLargeFileConfirmationConfigurationNode = this.m;
    this.m = {
      ...$UL,
      properties: {
        "workbench.editorLargeFileConfirmation": {
          type: "number",
          default: $Tm(this.r.remoteAuthority) / $Sm.MB,
          minimum: 1,
          scope: 4,
          markdownDescription: localize(3487, null)
        }
      }
    };
    this.f.updateConfigurations({
      add: [
        this.g,
        this.h,
        this.j,
        this.m
      ],
      remove: $Mb([
        oldAutoLockConfigurationNode,
        oldDefaultBinaryEditorConfigurationNode,
        oldEditorAssociationsConfigurationNode,
        oldEditorLargeFileConfirmationConfigurationNode
      ])
    });
  }
};
$3Ub = $3Ub_1 = __decorate([
  __param(0, $4L),
  __param(1, $wN),
  __param(2, $US)
], $3Ub);

// out-build/vs/workbench/browser/parts/editor/editor.contribution.js
$Wn.as($ZK.EditorPane).registerEditorPane($7tb.create($PUb, $PUb.ID, localize(3169, null)), [
  new $Nk($0Gb),
  new $Nk($6vb)
]);
$Wn.as($ZK.EditorPane).registerEditorPane($7tb.create($hub, $hub.ID, localize(3170, null)), [
  new $Nk($fub)
]);
$Wn.as($ZK.EditorPane).registerEditorPane($7tb.create($RUb, $RUb.ID, localize(3171, null)), [
  new $Nk($fub)
]);
$Wn.as($ZK.EditorPane).registerEditorPane($7tb.create($_tb, $_tb.ID, localize(3172, null)), [
  new $Nk($1I)
]);
$Wn.as($ZK.EditorFactory).registerEditorSerializer($0Gb.ID, $1Ub);
$Wn.as($ZK.EditorFactory).registerEditorSerializer($1I.ID, $3I);
$Wn.as($ZK.EditorFactory).registerEditorSerializer($fub.ID, $gub);
$PL(
  $XUb.ID,
  $XUb,
  2
  /* WorkbenchPhase.BlockRestore */
);
$PL(
  $SUb.ID,
  $SUb,
  2
  /* WorkbenchPhase.BlockRestore */
);
$PL(
  $2Ub.ID,
  $2Ub,
  2
  /* WorkbenchPhase.BlockRestore */
);
$PL(
  $3Ub.ID,
  $3Ub,
  2
  /* WorkbenchPhase.BlockRestore */
);
$85(
  $DLb.ID,
  $DLb,
  1
  /* EditorContributionInstantiation.AfterFirstRender */
);
var quickAccessRegistry = $Wn.as($CM.Quickaccess);
var editorPickerContextKey = "inEditorsPicker";
var editorPickerContext = $7m.and($6yb, $7m.has(editorPickerContextKey));
quickAccessRegistry.registerQuickAccessProvider({
  ctor: $2tb,
  prefix: $2tb.PREFIX,
  contextKey: editorPickerContextKey,
  placeholder: localize(3173, null),
  helpEntries: [{ description: localize(3174, null), commandId: $Cxb.ID }]
});
quickAccessRegistry.registerQuickAccessProvider({
  ctor: $3tb,
  prefix: $3tb.PREFIX,
  contextKey: editorPickerContextKey,
  placeholder: localize(3175, null),
  helpEntries: [{ description: localize(3176, null), commandId: $Dxb.ID }]
});
quickAccessRegistry.registerQuickAccessProvider({
  ctor: $4tb,
  prefix: $4tb.PREFIX,
  contextKey: editorPickerContextKey,
  placeholder: localize(3177, null),
  helpEntries: [{ description: localize(3178, null), commandId: $Exb.ID }]
});
$hJ($pyb);
$hJ($UUb);
$hJ($VUb);
$hJ($WUb);
$hJ($pxb);
$hJ($qxb);
$hJ($jxb);
$hJ($kxb);
$hJ($lxb);
$hJ($mxb);
$hJ($nxb);
$hJ($oxb);
$hJ($Kxb);
$hJ($Lxb);
$hJ($Mxb);
$hJ($Nxb);
$hJ($Axb);
$hJ($Bxb);
$hJ($Dxb);
$hJ($Exb);
$hJ($Cxb);
$hJ($4wb);
$hJ($5wb);
$hJ($3wb);
$hJ($6wb);
$hJ($7wb);
$hJ($2wb);
$hJ($Gwb);
$hJ($Hwb);
$hJ($Iwb);
$hJ($Jwb);
$hJ($Kwb);
$hJ($Lwb);
$hJ($Mwb);
$hJ($Nwb);
$hJ($Owb);
$hJ($fxb);
$hJ($gxb);
$hJ($hxb);
$hJ($ixb);
$hJ($dxb);
$hJ($exb);
$hJ($Pxb);
$hJ($Qxb);
$hJ($8wb);
$hJ($9wb);
$hJ($0wb);
$hJ($$wb);
$hJ($_wb);
$hJ($axb);
$hJ($bxb);
$hJ($cxb);
$hJ($Rxb);
$hJ($Sxb);
$hJ($Xxb);
$hJ($Yxb);
$hJ($Vxb);
$hJ($Wxb);
$hJ($Txb);
$hJ($Uxb);
$hJ($Zxb);
$hJ($1xb);
$hJ($6xb);
$hJ($7xb);
$hJ($4xb);
$hJ($5xb);
$hJ($2xb);
$hJ($3xb);
$hJ($Pwb);
$hJ($Qwb);
$hJ($Rwb);
$hJ($Twb);
$hJ($Swb);
$hJ($Uwb);
$hJ($Vwb);
$hJ($Wwb);
$hJ($Xwb);
$hJ($dyb);
$hJ($eyb);
$hJ($fyb);
$hJ($gyb);
$hJ($rxb);
$hJ($sxb);
$hJ($txb);
$hJ($uxb);
$hJ($vxb);
$hJ($wxb);
$hJ($xxb);
$hJ($yxb);
$hJ($zxb);
$hJ($Oxb);
$hJ($8xb);
$hJ($9xb);
$hJ($0xb);
$hJ($$xb);
$hJ($_xb);
$hJ($ayb);
$hJ($cyb);
$hJ($byb);
$hJ($hyb);
$hJ($iyb);
$hJ($Fxb);
$hJ($Gxb);
$hJ($Hxb);
$hJ($Ixb);
$hJ($Jxb);
$hJ($jyb);
$hJ($kyb);
$hJ($lyb);
$hJ($myb);
$hJ($nyb);
$hJ($oyb);
var quickAccessNavigateNextInEditorPickerId = "workbench.action.quickOpenNavigateNextInEditorPicker";
$0I.registerCommandAndKeybindingRule({
  id: quickAccessNavigateNextInEditorPickerId,
  weight: 200 + 50,
  handler: $9yb(quickAccessNavigateNextInEditorPickerId, true),
  when: editorPickerContext,
  primary: 2048 | 2,
  mac: {
    primary: 256 | 2
    /* KeyCode.Tab */
  }
});
var quickAccessNavigatePreviousInEditorPickerId = "workbench.action.quickOpenNavigatePreviousInEditorPicker";
$0I.registerCommandAndKeybindingRule({
  id: quickAccessNavigatePreviousInEditorPickerId,
  weight: 200 + 50,
  handler: $9yb(quickAccessNavigatePreviousInEditorPickerId, false),
  when: editorPickerContext,
  primary: 2048 | 1024 | 2,
  mac: {
    primary: 256 | 1024 | 2
    /* KeyCode.Tab */
  }
});
$dvb();
if ($m) {
  $dJ.appendMenuItem($bJ.TouchBarContext, {
    command: { id: $qxb.ID, title: $qxb.LABEL, icon: { dark: $ih.asFileUri("vs/workbench/browser/parts/editor/media/back-tb.png") } },
    group: "navigation",
    order: 0
  });
  $dJ.appendMenuItem($bJ.TouchBarContext, {
    command: { id: $pxb.ID, title: $pxb.LABEL, icon: { dark: $ih.asFileUri("vs/workbench/browser/parts/editor/media/forward-tb.png") } },
    group: "navigation",
    order: 1
  });
}
$dJ.appendMenuItem($bJ.EmptyEditorGroup, { command: { id: $Hub, title: localize(3179, null), icon: $6l.unlock }, group: "navigation", order: 10, when: $7m.and($Vpb, $Mpb.toNegated()) });
$dJ.appendMenuItem($bJ.EmptyEditorGroup, { command: { id: $Iub, title: localize(3180, null), icon: $6l.lock, toggled: $7m.true() }, group: "navigation", order: 10, when: $Mpb });
$dJ.appendMenuItem($bJ.EmptyEditorGroup, { command: { id: $zub, title: localize(3181, null), icon: $6l.close }, group: "navigation", order: 20, when: $7m.or($Vpb, $Spb) });
$dJ.appendMenuItem($bJ.EmptyEditorGroupContext, { command: { id: $Oub, title: localize(3182, null) }, group: "2_split", order: 10 });
$dJ.appendMenuItem($bJ.EmptyEditorGroupContext, { command: { id: $Pub, title: localize(3183, null) }, group: "2_split", order: 20 });
$dJ.appendMenuItem($bJ.EmptyEditorGroupContext, { command: { id: $Qub, title: localize(3184, null) }, group: "2_split", order: 30 });
$dJ.appendMenuItem($bJ.EmptyEditorGroupContext, { command: { id: $Rub, title: localize(3185, null) }, group: "2_split", order: 40 });
$dJ.appendMenuItem($bJ.EmptyEditorGroupContext, { command: { id: $0ub, title: localize(3186, null) }, group: "3_window", order: 10 });
$dJ.appendMenuItem($bJ.EmptyEditorGroupContext, {
  command: { id: $Gub, title: localize(3187, null), toggled: $Mpb },
  group: "4_lock",
  order: 10,
  when: $Vpb.toNegated()
  /* already a primary action for aux windows */
});
$dJ.appendMenuItem($bJ.EmptyEditorGroupContext, { command: { id: $zub, title: localize(3188, null) }, group: "5_close", order: 10, when: $Npb });
$dJ.appendMenuItem($bJ.EditorTabsBarContext, { command: { id: $Oub, title: localize(3189, null) }, group: "2_split", order: 10 });
$dJ.appendMenuItem($bJ.EditorTabsBarContext, { command: { id: $Pub, title: localize(3190, null) }, group: "2_split", order: 20 });
$dJ.appendMenuItem($bJ.EditorTabsBarContext, { command: { id: $Qub, title: localize(3191, null) }, group: "2_split", order: 30 });
$dJ.appendMenuItem($bJ.EditorTabsBarContext, { command: { id: $Rub, title: localize(3192, null) }, group: "2_split", order: 40 });
$dJ.appendMenuItem($bJ.EditorTabsBarContext, { command: { id: $8ub, title: localize(3193, null) }, group: "3_window", order: 10 });
$dJ.appendMenuItem($bJ.EditorTabsBarContext, { command: { id: $9ub, title: localize(3194, null) }, group: "3_window", order: 20 });
$dJ.appendMenuItem($bJ.EditorTabsBarContext, { submenu: $bJ.EditorTabsBarShowTabsSubmenu, title: localize(3195, null), group: "4_config", order: 10, when: $Xpb.negate() });
$dJ.appendMenuItem($bJ.EditorTabsBarShowTabsSubmenu, { command: { id: $Sqb.ID, title: localize(3196, null), toggled: $7m.equals("config.workbench.editor.showTabs", "multiple") }, group: "1_config", order: 10 });
$dJ.appendMenuItem($bJ.EditorTabsBarShowTabsSubmenu, { command: { id: $Uqb.ID, title: localize(3197, null), toggled: $7m.equals("config.workbench.editor.showTabs", "single") }, group: "1_config", order: 20 });
$dJ.appendMenuItem($bJ.EditorTabsBarShowTabsSubmenu, { command: { id: $Qqb.ID, title: localize(3198, null), toggled: $7m.equals("config.workbench.editor.showTabs", "none") }, group: "1_config", order: 30 });
$dJ.appendMenuItem($bJ.EditorTabsBarContext, { submenu: $bJ.EditorTabsBarShowTabsZenModeSubmenu, title: localize(3199, null), group: "4_config", order: 10, when: $Xpb });
$dJ.appendMenuItem($bJ.EditorTabsBarShowTabsZenModeSubmenu, { command: { id: $Tqb.ID, title: localize(3200, null), toggled: $7m.equals("config.zenMode.showTabs", "multiple") }, group: "1_config", order: 10 });
$dJ.appendMenuItem($bJ.EditorTabsBarShowTabsZenModeSubmenu, { command: { id: $Vqb.ID, title: localize(3201, null), toggled: $7m.equals("config.zenMode.showTabs", "single") }, group: "1_config", order: 20 });
$dJ.appendMenuItem($bJ.EditorTabsBarShowTabsZenModeSubmenu, { command: { id: $Rqb.ID, title: localize(3202, null), toggled: $7m.equals("config.zenMode.showTabs", "none") }, group: "1_config", order: 30 });
$dJ.appendMenuItem($bJ.EditorTabsBarContext, { submenu: $bJ.EditorActionsPositionSubmenu, title: localize(3203, null), group: "4_config", order: 20 });
$dJ.appendMenuItem($bJ.EditorActionsPositionSubmenu, { command: { id: $Xqb.ID, title: localize(3204, null), toggled: $7m.equals("config.workbench.editor.editorActionsLocation", "default") }, group: "1_config", order: 10, when: $7m.equals("config.workbench.editor.showTabs", "none").negate() });
$dJ.appendMenuItem($bJ.EditorActionsPositionSubmenu, { command: { id: $Wqb.ID, title: localize(3205, null), toggled: $7m.or($7m.equals("config.workbench.editor.editorActionsLocation", "titleBar"), $7m.and($7m.equals("config.workbench.editor.showTabs", "none"), $7m.equals("config.workbench.editor.editorActionsLocation", "default"))) }, group: "1_config", order: 20 });
$dJ.appendMenuItem($bJ.EditorActionsPositionSubmenu, { command: { id: $Yqb.ID, title: localize(3206, null), toggled: $7m.equals("config.workbench.editor.editorActionsLocation", "hidden") }, group: "1_config", order: 30 });
$dJ.appendMenuItem($bJ.EditorTabsBarContext, { command: { id: $1qb.ID, title: localize(3207, null) }, group: "9_configure", order: 10 });
$dJ.appendMenuItem($bJ.EditorTitleContext, { command: { id: $xub, title: localize(3208, null) }, group: "1_close", order: 10 });
$dJ.appendMenuItem($bJ.EditorTitleContext, { command: { id: $Aub, title: localize(3209, null), precondition: $Ipb.notEqualsTo("1") }, group: "1_close", order: 20 });
$dJ.appendMenuItem($bJ.EditorTitleContext, { command: { id: $wub, title: localize(3210, null), precondition: $7m.and($wpb.toNegated(), $Ppb.negate()) }, group: "1_close", order: 30, when: $2pb });
$dJ.appendMenuItem($bJ.EditorTitleContext, { command: { id: $tub, title: localize(3211, null) }, group: "1_close", order: 40 });
$dJ.appendMenuItem($bJ.EditorTitleContext, { command: { id: $uub, title: localize(3212, null) }, group: "1_close", order: 50 });
$dJ.appendMenuItem($bJ.EditorTitleContext, { command: { id: $Kub, title: localize(3213, null) }, group: "1_open", order: 10, when: $Epb });
$dJ.appendMenuItem($bJ.EditorTitleContext, { command: { id: $Eub, title: localize(3214, null), precondition: $upb.toNegated() }, group: "3_preview", order: 10, when: $7m.has("config.workbench.editor.enablePreview") });
$dJ.appendMenuItem($bJ.EditorTitleContext, { command: { id: $Lub, title: localize(3215, null) }, group: "3_preview", order: 20, when: $xpb.toNegated() });
$dJ.appendMenuItem($bJ.EditorTitleContext, { command: { id: $Mub, title: localize(3216, null) }, group: "3_preview", order: 20, when: $xpb });
$dJ.appendMenuItem($bJ.EditorTitleContext, { command: { id: $Oub, title: localize(3217, null) }, group: "5_split", order: 10 });
$dJ.appendMenuItem($bJ.EditorTitleContext, { command: { id: $Pub, title: localize(3218, null) }, group: "5_split", order: 20 });
$dJ.appendMenuItem($bJ.EditorTitleContext, { command: { id: $Qub, title: localize(3219, null) }, group: "5_split", order: 30 });
$dJ.appendMenuItem($bJ.EditorTitleContext, { command: { id: $Rub, title: localize(3220, null) }, group: "5_split", order: 40 });
$dJ.appendMenuItem($bJ.EditorTitleContext, { command: { id: $Tub, title: localize(3221, null), precondition: $Ppb.negate() }, group: "6_split_in_group", order: 10, when: $Cpb });
$dJ.appendMenuItem($bJ.EditorTitleContext, { command: { id: $Vub, title: localize(3222, null), precondition: $Ppb.negate() }, group: "6_split_in_group", order: 10, when: $Hpb });
$dJ.appendMenuItem($bJ.EditorTitleContext, { command: { id: $6ub, title: localize(3223, null) }, group: "7_new_window", order: 10 });
$dJ.appendMenuItem($bJ.EditorTitleContext, { command: { id: $7ub, title: localize(3224, null) }, group: "7_new_window", order: 20 });
$dJ.appendMenuItem($bJ.EditorTitleContext, { submenu: $bJ.EditorTitleContextShare, title: localize(3225, null), group: "11_share", order: -1, when: $Ppb.negate() });
$dJ.appendMenuItem($bJ.EditorTitle, { command: { id: $iub, title: localize(3226, null), toggled: $7m.equals("config.diffEditor.renderSideBySide", false) }, group: "1_diff", order: 10, when: $7m.has("isInDiffEditor") });
$dJ.appendMenuItem($bJ.EditorTitle, { command: { id: $Jub, title: localize(3227, null) }, group: "3_open", order: 10 });
$dJ.appendMenuItem($bJ.EditorTitle, { command: { id: $uub, title: localize(3228, null) }, group: "5_close", order: 10 });
$dJ.appendMenuItem($bJ.EditorTitle, { command: { id: $tub, title: localize(3229, null) }, group: "5_close", order: 20 });
$dJ.appendMenuItem($bJ.EditorTitle, { command: { id: $Fub, title: localize(3230, null), toggled: $7m.has("config.workbench.editor.enablePreview") }, group: "7_settings", order: 10 });
$dJ.appendMenuItem($bJ.EditorTitle, { command: { id: $Sub, title: localize(3231, null) }, group: "8_group_operations", order: 5, when: $7m.and($Upb.negate(), $Spb) });
$dJ.appendMenuItem($bJ.EditorTitle, { command: { id: $Sub, title: localize(3232, null) }, group: "8_group_operations", order: 5, when: $Upb });
$dJ.appendMenuItem($bJ.EditorTitle, {
  command: { id: $Gub, title: localize(3233, null), toggled: $Mpb },
  group: "8_group_operations",
  order: 10,
  when: $Vpb.toNegated()
  /* already a primary action for aux windows */
});
$dJ.appendMenuItem($bJ.EditorTitle, { command: { id: $2qb.ID, title: localize(3234, null) }, group: "9_configure", order: 10 });
function appendEditorToolItem(primary, when, order, alternative, precondition2) {
  const item = {
    command: {
      id: primary.id,
      title: primary.title,
      icon: primary.icon,
      toggled: primary.toggled,
      precondition: precondition2
    },
    group: "navigation",
    when,
    order
  };
  if (alternative) {
    item.alt = {
      id: alternative.id,
      title: alternative.title,
      icon: alternative.icon
    };
  }
  $dJ.appendMenuItem($bJ.EditorTitle, item);
}
var SPLIT_ORDER = 1e5;
var CLOSE_ORDER = 1e6;
appendEditorToolItem({
  id: $Nub,
  title: localize(3235, null),
  icon: $6l.splitHorizontal
}, $7m.not("splitEditorsVertically"), SPLIT_ORDER, {
  id: $Pub,
  title: localize(3236, null),
  icon: $6l.splitVertical
});
appendEditorToolItem({
  id: $Nub,
  title: localize(3237, null),
  icon: $6l.splitVertical
}, $7m.has("splitEditorsVertically"), SPLIT_ORDER, {
  id: $Rub,
  title: localize(3238, null),
  icon: $6l.splitHorizontal
});
appendEditorToolItem({
  id: $Wub,
  title: localize(3239, null),
  icon: $6l.editorLayout
}, $Hpb, SPLIT_ORDER - 1);
appendEditorToolItem({
  id: $xub,
  title: localize(3240, null),
  icon: $6l.close
}, $7m.and($2pb.toNegated(), $tpb.toNegated(), $xpb.toNegated()), CLOSE_ORDER, {
  id: $uub,
  title: localize(3241, null),
  icon: $6l.closeAll
});
appendEditorToolItem({
  id: $xub,
  title: localize(3242, null),
  icon: $6l.closeDirty
}, $7m.and($2pb.toNegated(), $tpb, $xpb.toNegated()), CLOSE_ORDER, {
  id: $uub,
  title: localize(3243, null),
  icon: $6l.closeAll
});
appendEditorToolItem({
  id: $Mub,
  title: localize(3244, null),
  icon: $6l.pinned
}, $7m.and($2pb.toNegated(), $tpb.toNegated(), $xpb), CLOSE_ORDER, {
  id: $xub,
  title: localize(3245, null),
  icon: $6l.close
});
appendEditorToolItem({
  id: $Mub,
  title: localize(3246, null),
  icon: $6l.pinnedDirty
}, $7m.and($2pb.toNegated(), $tpb, $xpb), CLOSE_ORDER, {
  id: $xub,
  title: localize(3247, null),
  icon: $6l.close
});
appendEditorToolItem({
  id: $Hub,
  title: localize(3248, null),
  icon: $6l.unlock
}, $7m.and($Vpb, $Mpb.toNegated()), CLOSE_ORDER - 1);
appendEditorToolItem({
  id: $Iub,
  title: localize(3249, null),
  icon: $6l.lock,
  toggled: $7m.true()
}, $Mpb, CLOSE_ORDER - 1);
var previousChangeIcon = $9r("diff-editor-previous-change", $6l.arrowUp, localize(3250, null));
appendEditorToolItem({
  id: $kub,
  title: localize(3251, null),
  icon: previousChangeIcon
}, $Gpb, 10, void 0, EditorContextKeys.hasChanges);
var nextChangeIcon = $9r("diff-editor-next-change", $6l.arrowDown, localize(3252, null));
appendEditorToolItem({
  id: $jub,
  title: localize(3253, null),
  icon: nextChangeIcon
}, $Gpb, 11, void 0, EditorContextKeys.hasChanges);
appendEditorToolItem({
  id: $qub,
  title: localize(3254, null),
  icon: $6l.arrowSwap
}, $7m.and($Gpb, $zpb), 15, void 0, void 0);
var toggleWhitespace = $9r("diff-editor-toggle-whitespace", $6l.whitespace, localize(3255, null));
$dJ.appendMenuItem($bJ.EditorTitle, {
  command: {
    id: $pub,
    title: localize(3256, null),
    icon: toggleWhitespace,
    precondition: $Gpb,
    toggled: $7m.equals("config.diffEditor.ignoreTrimWhitespace", false)
  },
  group: "navigation",
  when: $Gpb,
  order: 20
});
$dJ.appendMenuItem($bJ.CommandPalette, { command: { id: $Eub, title: localize2(3301, "Keep Editor"), category: $qn.View }, when: $7m.has("config.workbench.editor.enablePreview") });
$dJ.appendMenuItem($bJ.CommandPalette, { command: { id: $Lub, title: localize2(3302, "Pin Editor"), category: $qn.View } });
$dJ.appendMenuItem($bJ.CommandPalette, { command: { id: $Mub, title: localize2(3303, "Unpin Editor"), category: $qn.View } });
$dJ.appendMenuItem($bJ.CommandPalette, { command: { id: $xub, title: localize2(3304, "Close Editor"), category: $qn.View } });
$dJ.appendMenuItem($bJ.CommandPalette, { command: { id: $yub, title: localize2(3305, "Close Pinned Editor"), category: $qn.View } });
$dJ.appendMenuItem($bJ.CommandPalette, { command: { id: $uub, title: localize2(3306, "Close All Editors in Group"), category: $qn.View } });
$dJ.appendMenuItem($bJ.CommandPalette, { command: { id: $tub, title: localize2(3307, "Close Saved Editors in Group"), category: $qn.View } });
$dJ.appendMenuItem($bJ.CommandPalette, { command: { id: $Aub, title: localize2(3308, "Close Other Editors in Group"), category: $qn.View } });
$dJ.appendMenuItem($bJ.CommandPalette, { command: { id: $wub, title: localize2(3309, "Close Editors to the Right in Group"), category: $qn.View }, when: $wpb.toNegated() });
$dJ.appendMenuItem($bJ.CommandPalette, { command: { id: $vub, title: localize2(3310, "Close Editor Group"), category: $qn.View }, when: $Npb });
$dJ.appendMenuItem($bJ.CommandPalette, { command: { id: $Kub, title: localize2(3311, "Reopen Editor With..."), category: $qn.View }, when: $Epb });
$dJ.appendMenuItem($bJ.MenubarRecentMenu, {
  group: "1_editor",
  command: {
    id: $Axb.ID,
    title: localize(3257, null),
    precondition: $7m.has("canReopenClosedEditor")
  },
  order: 1
});
$dJ.appendMenuItem($bJ.MenubarRecentMenu, {
  group: "z_clear",
  command: {
    id: $Bxb.ID,
    title: localize(3258, null)
  },
  order: 1
});
$dJ.appendMenuItem($bJ.MenubarFileMenu, {
  title: localize(3259, null),
  submenu: $bJ.MenubarShare,
  group: "45_share",
  order: 1
});
$dJ.appendMenuItem($bJ.MenubarViewMenu, {
  group: "2_appearance",
  title: localize(3260, null),
  submenu: $bJ.MenubarLayoutMenu,
  order: 2
});
$dJ.appendMenuItem($bJ.MenubarLayoutMenu, {
  group: "1_split",
  command: {
    id: $Oub,
    title: {
      ...localize2(3312, "Split Up"),
      mnemonicTitle: localize(3261, null)
    }
  },
  order: 1
});
$dJ.appendMenuItem($bJ.MenubarLayoutMenu, {
  group: "1_split",
  command: {
    id: $Pub,
    title: {
      ...localize2(3313, "Split Down"),
      mnemonicTitle: localize(3262, null)
    }
  },
  order: 2
});
$dJ.appendMenuItem($bJ.MenubarLayoutMenu, {
  group: "1_split",
  command: {
    id: $Qub,
    title: {
      ...localize2(3314, "Split Left"),
      mnemonicTitle: localize(3263, null)
    }
  },
  order: 3
});
$dJ.appendMenuItem($bJ.MenubarLayoutMenu, {
  group: "1_split",
  command: {
    id: $Rub,
    title: {
      ...localize2(3315, "Split Right"),
      mnemonicTitle: localize(3264, null)
    }
  },
  order: 4
});
$dJ.appendMenuItem($bJ.MenubarLayoutMenu, {
  group: "2_split_in_group",
  command: {
    id: $Tub,
    title: {
      ...localize2(3316, "Split in Group"),
      mnemonicTitle: localize(3265, null)
    }
  },
  when: $Cpb,
  order: 1
});
$dJ.appendMenuItem($bJ.MenubarLayoutMenu, {
  group: "2_split_in_group",
  command: {
    id: $Vub,
    title: {
      ...localize2(3317, "Join in Group"),
      mnemonicTitle: localize(3266, null)
    }
  },
  when: $Hpb,
  order: 1
});
$dJ.appendMenuItem($bJ.MenubarLayoutMenu, {
  group: "3_new_window",
  command: {
    id: $6ub,
    title: {
      ...localize2(3318, "Move Editor into New Window"),
      mnemonicTitle: localize(3267, null)
    }
  },
  order: 1
});
$dJ.appendMenuItem($bJ.MenubarLayoutMenu, {
  group: "3_new_window",
  command: {
    id: $7ub,
    title: {
      ...localize2(3319, "Copy Editor into New Window"),
      mnemonicTitle: localize(3268, null)
    }
  },
  order: 2
});
$dJ.appendMenuItem($bJ.MenubarLayoutMenu, {
  group: "4_layouts",
  command: {
    id: $8xb.ID,
    title: {
      ...localize2(3320, "Single"),
      mnemonicTitle: localize(3269, null)
    }
  },
  order: 1
});
$dJ.appendMenuItem($bJ.MenubarLayoutMenu, {
  group: "4_layouts",
  command: {
    id: $9xb.ID,
    title: {
      ...localize2(3321, "Two Columns"),
      mnemonicTitle: localize(3270, null)
    }
  },
  order: 3
});
$dJ.appendMenuItem($bJ.MenubarLayoutMenu, {
  group: "4_layouts",
  command: {
    id: $0xb.ID,
    title: {
      ...localize2(3322, "Three Columns"),
      mnemonicTitle: localize(3271, null)
    }
  },
  order: 4
});
$dJ.appendMenuItem($bJ.MenubarLayoutMenu, {
  group: "4_layouts",
  command: {
    id: $$xb.ID,
    title: {
      ...localize2(3323, "Two Rows"),
      mnemonicTitle: localize(3272, null)
    }
  },
  order: 5
});
$dJ.appendMenuItem($bJ.MenubarLayoutMenu, {
  group: "4_layouts",
  command: {
    id: $_xb.ID,
    title: {
      ...localize2(3324, "Three Rows"),
      mnemonicTitle: localize(3273, null)
    }
  },
  order: 6
});
$dJ.appendMenuItem($bJ.MenubarLayoutMenu, {
  group: "4_layouts",
  command: {
    id: $ayb.ID,
    title: {
      ...localize2(3325, "Grid (2x2)"),
      mnemonicTitle: localize(3274, null)
    }
  },
  order: 7
});
$dJ.appendMenuItem($bJ.MenubarLayoutMenu, {
  group: "4_layouts",
  command: {
    id: $cyb.ID,
    title: {
      ...localize2(3326, "Two Rows Right"),
      mnemonicTitle: localize(3275, null)
    }
  },
  order: 8
});
$dJ.appendMenuItem($bJ.MenubarLayoutMenu, {
  group: "4_layouts",
  command: {
    id: $byb.ID,
    title: {
      ...localize2(3327, "Two Columns Bottom"),
      mnemonicTitle: localize(3276, null)
    }
  },
  order: 9
});
$dJ.appendMenuItem($bJ.MenubarGoMenu, {
  group: "1_history_nav",
  command: {
    id: "workbench.action.navigateToLastEditLocation",
    title: localize(3277, null),
    precondition: $7m.has("canNavigateToLastEditLocation")
  },
  order: 3
});
$dJ.appendMenuItem($bJ.MenubarSwitchEditorMenu, {
  group: "1_sideBySide",
  command: {
    id: $Xub,
    title: localize(3278, null)
  },
  when: $7m.or($Hpb, $Gpb),
  order: 1
});
$dJ.appendMenuItem($bJ.MenubarSwitchEditorMenu, {
  group: "1_sideBySide",
  command: {
    id: $Yub,
    title: localize(3279, null)
  },
  when: $7m.or($Hpb, $Gpb),
  order: 2
});
$dJ.appendMenuItem($bJ.MenubarSwitchEditorMenu, {
  group: "2_any",
  command: {
    id: "workbench.action.nextEditor",
    title: localize(3280, null)
  },
  order: 1
});
$dJ.appendMenuItem($bJ.MenubarSwitchEditorMenu, {
  group: "2_any",
  command: {
    id: "workbench.action.previousEditor",
    title: localize(3281, null)
  },
  order: 2
});
$dJ.appendMenuItem($bJ.MenubarSwitchEditorMenu, {
  group: "3_any_used",
  command: {
    id: "workbench.action.openNextRecentlyUsedEditor",
    title: localize(3282, null)
  },
  order: 1
});
$dJ.appendMenuItem($bJ.MenubarSwitchEditorMenu, {
  group: "3_any_used",
  command: {
    id: "workbench.action.openPreviousRecentlyUsedEditor",
    title: localize(3283, null)
  },
  order: 2
});
$dJ.appendMenuItem($bJ.MenubarSwitchEditorMenu, {
  group: "4_group",
  command: {
    id: "workbench.action.nextEditorInGroup",
    title: localize(3284, null)
  },
  order: 1
});
$dJ.appendMenuItem($bJ.MenubarSwitchEditorMenu, {
  group: "4_group",
  command: {
    id: "workbench.action.previousEditorInGroup",
    title: localize(3285, null)
  },
  order: 2
});
$dJ.appendMenuItem($bJ.MenubarSwitchEditorMenu, {
  group: "5_group_used",
  command: {
    id: "workbench.action.openNextRecentlyUsedEditorInGroup",
    title: localize(3286, null)
  },
  order: 1
});
$dJ.appendMenuItem($bJ.MenubarSwitchEditorMenu, {
  group: "5_group_used",
  command: {
    id: "workbench.action.openPreviousRecentlyUsedEditorInGroup",
    title: localize(3287, null)
  },
  order: 2
});
$dJ.appendMenuItem($bJ.MenubarGoMenu, {
  group: "2_editor_nav",
  title: localize(3288, null),
  submenu: $bJ.MenubarSwitchEditorMenu,
  order: 1
});
$dJ.appendMenuItem($bJ.MenubarSwitchGroupMenu, {
  group: "1_focus_index",
  command: {
    id: "workbench.action.focusFirstEditorGroup",
    title: localize(3289, null)
  },
  order: 1
});
$dJ.appendMenuItem($bJ.MenubarSwitchGroupMenu, {
  group: "1_focus_index",
  command: {
    id: "workbench.action.focusSecondEditorGroup",
    title: localize(3290, null)
  },
  order: 2
});
$dJ.appendMenuItem($bJ.MenubarSwitchGroupMenu, {
  group: "1_focus_index",
  command: {
    id: "workbench.action.focusThirdEditorGroup",
    title: localize(3291, null),
    precondition: $Npb
  },
  order: 3
});
$dJ.appendMenuItem($bJ.MenubarSwitchGroupMenu, {
  group: "1_focus_index",
  command: {
    id: "workbench.action.focusFourthEditorGroup",
    title: localize(3292, null),
    precondition: $Npb
  },
  order: 4
});
$dJ.appendMenuItem($bJ.MenubarSwitchGroupMenu, {
  group: "1_focus_index",
  command: {
    id: "workbench.action.focusFifthEditorGroup",
    title: localize(3293, null),
    precondition: $Npb
  },
  order: 5
});
$dJ.appendMenuItem($bJ.MenubarSwitchGroupMenu, {
  group: "2_next_prev",
  command: {
    id: "workbench.action.focusNextGroup",
    title: localize(3294, null),
    precondition: $Npb
  },
  order: 1
});
$dJ.appendMenuItem($bJ.MenubarSwitchGroupMenu, {
  group: "2_next_prev",
  command: {
    id: "workbench.action.focusPreviousGroup",
    title: localize(3295, null),
    precondition: $Npb
  },
  order: 2
});
$dJ.appendMenuItem($bJ.MenubarSwitchGroupMenu, {
  group: "3_directional",
  command: {
    id: "workbench.action.focusLeftGroup",
    title: localize(3296, null),
    precondition: $Npb
  },
  order: 1
});
$dJ.appendMenuItem($bJ.MenubarSwitchGroupMenu, {
  group: "3_directional",
  command: {
    id: "workbench.action.focusRightGroup",
    title: localize(3297, null),
    precondition: $Npb
  },
  order: 2
});
$dJ.appendMenuItem($bJ.MenubarSwitchGroupMenu, {
  group: "3_directional",
  command: {
    id: "workbench.action.focusAboveGroup",
    title: localize(3298, null),
    precondition: $Npb
  },
  order: 3
});
$dJ.appendMenuItem($bJ.MenubarSwitchGroupMenu, {
  group: "3_directional",
  command: {
    id: "workbench.action.focusBelowGroup",
    title: localize(3299, null),
    precondition: $Npb
  },
  order: 4
});
$dJ.appendMenuItem($bJ.MenubarGoMenu, {
  group: "2_editor_nav",
  title: localize(3300, null),
  submenu: $bJ.MenubarSwitchGroupMenu,
  order: 2
});

// out-build/vs/workbench/browser/part.js
var Part = class extends $Tlb {
  get dimension() {
    return this.f;
  }
  get contentPosition() {
    return this.g;
  }
  constructor(id2, L, themeService, storageService, M) {
    super(id2, themeService, storageService);
    this.L = L;
    this.M = M;
    this.j = this.B(new $ze());
    this.onDidVisibilityChange = this.j.event;
    this.ab = this.B(new $ze());
    this.B(M.registerPart(this));
  }
  w(theme) {
    if (this.m) {
      super.w(theme);
    }
  }
  /**
   * Note: Clients should not call this method, the workbench calls this
   * method. Calling it otherwise may result in unexpected behavior.
   *
   * Called to create title and content area of the part.
   */
  create(parent, options3) {
    this.m = parent;
    this.s = this.O(parent, options3);
    this.t = this.Q(parent, options3);
    this.J = new PartLayout(this.L, this.t);
    this.updateStyles();
  }
  /**
   * Returns the overall part container.
   */
  getContainer() {
    return this.m;
  }
  /**
   * Subclasses override to provide a title area implementation.
   */
  O(parent, options3) {
    return void 0;
  }
  /**
   * Returns the title area container.
   */
  P() {
    return this.s;
  }
  /**
   * Subclasses override to provide a content area implementation.
   */
  Q(parent, options3) {
    return void 0;
  }
  /**
   * Returns the content area container.
   */
  R() {
    return this.t;
  }
  /**
   * Sets the header area
   */
  S(headerContainer) {
    if (this.r) {
      throw new Error("Header already exists");
    }
    if (!this.m || !this.s) {
      return;
    }
    $ck(this.m, headerContainer);
    headerContainer.classList.add("header-or-footer");
    headerContainer.classList.add("header");
    this.r = headerContainer;
    this.J?.setHeaderVisibility(true);
    this.Y();
  }
  /**
   * Sets the footer area
   */
  U(footerContainer) {
    if (this.u) {
      throw new Error("Footer already exists");
    }
    if (!this.m || !this.s) {
      return;
    }
    this.m.appendChild(footerContainer);
    footerContainer.classList.add("header-or-footer");
    footerContainer.classList.add("footer");
    this.u = footerContainer;
    this.J?.setFooterVisibility(true);
    this.Y();
  }
  /**
   * removes the header area
   */
  W() {
    if (this.r) {
      this.r.remove();
      this.r = void 0;
      this.J?.setHeaderVisibility(false);
      this.Y();
    }
  }
  /**
   * removes the footer area
   */
  X() {
    if (this.u) {
      this.u.remove();
      this.u = void 0;
      this.J?.setFooterVisibility(false);
      this.Y();
    }
  }
  Y() {
    if (this.dimension && this.contentPosition) {
      this.layout(this.dimension.width, this.dimension.height, this.contentPosition.top, this.contentPosition.left);
    }
  }
  /**
   * Layout title and content area in the given dimension.
   */
  Z(width2, height) {
    const partLayout = $Kg(this.J);
    return partLayout.layout(width2, height);
  }
  get onDidChange() {
    return this.ab.event;
  }
  layout(width2, height, top2, left) {
    this.f = new $rj(width2, height);
    this.g = { top: top2, left };
  }
  setVisible(visible) {
    this.j.fire(visible);
  }
};
var PartLayout = class _PartLayout {
  static {
    this.a = 35;
  }
  static {
    this.b = 35;
  }
  static {
    this.c = 35;
  }
  constructor(f, g) {
    this.f = f;
    this.g = g;
    this.d = false;
    this.e = false;
  }
  layout(width2, height) {
    let titleSize;
    if (this.f.hasTitle) {
      titleSize = new $rj(width2, Math.min(height, _PartLayout.b));
    } else {
      titleSize = $rj.None;
    }
    let headerSize;
    if (this.d) {
      headerSize = new $rj(width2, Math.min(height, _PartLayout.a));
    } else {
      headerSize = $rj.None;
    }
    let footerSize;
    if (this.e) {
      footerSize = new $rj(width2, Math.min(height, _PartLayout.c));
    } else {
      footerSize = $rj.None;
    }
    let contentWidth = width2;
    if (this.f && typeof this.f.borderWidth === "function") {
      contentWidth -= this.f.borderWidth();
    }
    const contentSize = new $rj(contentWidth, height - titleSize.height - headerSize.height - footerSize.height);
    if (this.g) {
      $tj(this.g, contentSize.width, contentSize.height);
    }
    return { headerSize, titleSize, contentSize, footerSize };
  }
  setFooterVisibility(visible) {
    this.e = visible;
  }
  setHeaderVisibility(visible) {
    this.d = visible;
  }
};
var $3lb = class extends $Tlb {
  constructor() {
    super(...arguments);
    this.f = /* @__PURE__ */ new Set();
  }
  get parts() {
    return Array.from(this.f);
  }
  registerPart(part) {
    this.f.add(part);
    return $1c(() => this.g(part));
  }
  g(part) {
    this.f.delete(part);
  }
  getPart(container2) {
    return this.j(container2.ownerDocument);
  }
  j(document2) {
    if (this.f.size > 1) {
      for (const part of this.f) {
        if (part.element?.ownerDocument === document2) {
          return part;
        }
      }
    }
    return this.mainPart;
  }
  get activePart() {
    return this.j($Pj());
  }
};

// out-build/vs/base/browser/ui/grid/gridview.js
var defaultStyles2 = {
  separatorBorder: $Vn.transparent
};
function $s2(orientation) {
  return orientation === 0 ? 1 : 0;
}
var LayoutController = class {
  constructor(isLayoutEnabled) {
    this.isLayoutEnabled = isLayoutEnabled;
  }
};
function toAbsoluteBoundarySashes(sashes, orientation) {
  if (orientation === 1) {
    return { left: sashes.start, right: sashes.end, top: sashes.orthogonalStart, bottom: sashes.orthogonalEnd };
  } else {
    return { top: sashes.start, bottom: sashes.end, left: sashes.orthogonalStart, right: sashes.orthogonalEnd };
  }
}
function fromAbsoluteBoundarySashes(sashes, orientation) {
  if (orientation === 1) {
    return { start: sashes.left, end: sashes.right, orthogonalStart: sashes.top, orthogonalEnd: sashes.bottom };
  } else {
    return { start: sashes.top, end: sashes.bottom, orthogonalStart: sashes.left, orthogonalEnd: sashes.right };
  }
}
function validateIndex(index, numChildren) {
  if (Math.abs(index) > numChildren) {
    throw new Error("Invalid index");
  }
  return rot(index, numChildren + 1);
}
var BranchNode = class _BranchNode {
  get size() {
    return this.b;
  }
  get orthogonalSize() {
    return this.d;
  }
  get absoluteOffset() {
    return this.f;
  }
  get absoluteOrthogonalOffset() {
    return this.g;
  }
  get styles() {
    return this.j;
  }
  get width() {
    return this.orientation === 1 ? this.size : this.orthogonalSize;
  }
  get height() {
    return this.orientation === 1 ? this.orthogonalSize : this.size;
  }
  get top() {
    return this.orientation === 1 ? this.f : this.g;
  }
  get left() {
    return this.orientation === 1 ? this.g : this.f;
  }
  get minimumSize() {
    return this.children.length === 0 ? 0 : Math.max(...this.children.map((c, index) => this.a.isViewVisible(index) ? c.minimumOrthogonalSize : 0));
  }
  get maximumSize() {
    return Math.min(...this.children.map((c, index) => this.a.isViewVisible(index) ? c.maximumOrthogonalSize : Number.POSITIVE_INFINITY));
  }
  get priority() {
    if (this.children.length === 0) {
      return 0;
    }
    const priorities = this.children.map((c) => typeof c.priority === "undefined" ? 0 : c.priority);
    if (priorities.some(
      (p) => p === 2
      /* LayoutPriority.High */
    )) {
      return 2;
    } else if (priorities.some(
      (p) => p === 1
      /* LayoutPriority.Low */
    )) {
      return 1;
    }
    return 0;
  }
  get proportionalLayout() {
    if (this.children.length === 0) {
      return true;
    }
    return this.children.every((c) => c.proportionalLayout);
  }
  get minimumOrthogonalSize() {
    return this.a.minimumSize;
  }
  get maximumOrthogonalSize() {
    return this.a.maximumSize;
  }
  get minimumWidth() {
    return this.orientation === 1 ? this.minimumOrthogonalSize : this.minimumSize;
  }
  get minimumHeight() {
    return this.orientation === 1 ? this.minimumSize : this.minimumOrthogonalSize;
  }
  get maximumWidth() {
    return this.orientation === 1 ? this.maximumOrthogonalSize : this.maximumSize;
  }
  get maximumHeight() {
    return this.orientation === 1 ? this.maximumSize : this.maximumOrthogonalSize;
  }
  get boundarySashes() {
    return this.u;
  }
  set boundarySashes(boundarySashes) {
    if (this.u.start === boundarySashes.start && this.u.end === boundarySashes.end && this.u.orthogonalStart === boundarySashes.orthogonalStart && this.u.orthogonalEnd === boundarySashes.orthogonalEnd) {
      return;
    }
    this.u = boundarySashes;
    this.a.orthogonalStartSash = boundarySashes.orthogonalStart;
    this.a.orthogonalEndSash = boundarySashes.orthogonalEnd;
    for (let index = 0; index < this.children.length; index++) {
      const child = this.children[index];
      const first = index === 0;
      const last = index === this.children.length - 1;
      child.boundarySashes = {
        start: boundarySashes.orthogonalStart,
        end: boundarySashes.orthogonalEnd,
        orthogonalStart: first ? boundarySashes.start : child.boundarySashes.orthogonalStart,
        orthogonalEnd: last ? boundarySashes.end : child.boundarySashes.orthogonalEnd
      };
    }
  }
  get edgeSnapping() {
    return this.v;
  }
  set edgeSnapping(edgeSnapping) {
    if (this.v === edgeSnapping) {
      return;
    }
    this.v = edgeSnapping;
    for (const child of this.children) {
      if (child instanceof _BranchNode) {
        child.edgeSnapping = edgeSnapping;
      }
    }
    this.z();
  }
  constructor(orientation, layoutController, styles, splitviewProportionalLayout, size = 0, orthogonalSize = 0, edgeSnapping = false, childDescriptors) {
    this.orientation = orientation;
    this.layoutController = layoutController;
    this.splitviewProportionalLayout = splitviewProportionalLayout;
    this.children = [];
    this.f = 0;
    this.g = 0;
    this.h = 0;
    this.k = new $ze();
    this.onDidChange = this.k.event;
    this.l = new $ze();
    this.onDidVisibilityChange = this.l.event;
    this.m = new $2c();
    this.n = new $ze();
    this.o = $3c.None;
    this.onDidScroll = this.n.event;
    this.q = $3c.None;
    this.r = new $ze();
    this.onDidSashReset = this.r.event;
    this.s = $3c.None;
    this.t = $3c.None;
    this.u = {};
    this.v = false;
    this.j = styles;
    this.b = size;
    this.d = orthogonalSize;
    this.element = $(".monaco-grid-branch-node");
    if (!childDescriptors) {
      this.a = new $r2(this.element, { orientation, styles, proportionalLayout: splitviewProportionalLayout });
      this.a.layout(size, { orthogonalSize, absoluteOffset: 0, absoluteOrthogonalOffset: 0, absoluteSize: size, absoluteOrthogonalSize: orthogonalSize });
    } else {
      const descriptor = {
        views: childDescriptors.map((childDescriptor) => {
          return {
            view: childDescriptor.node,
            size: childDescriptor.node.size,
            visible: childDescriptor.visible !== false
          };
        }),
        size: this.orthogonalSize
      };
      const options3 = { proportionalLayout: splitviewProportionalLayout, orientation, styles };
      this.children = childDescriptors.map((c) => c.node);
      this.a = new $r2(this.element, { ...options3, descriptor });
      this.children.forEach((node, index) => {
        const first = index === 0;
        const last = index === this.children.length;
        node.boundarySashes = {
          start: this.boundarySashes.orthogonalStart,
          end: this.boundarySashes.orthogonalEnd,
          orthogonalStart: first ? this.boundarySashes.start : this.a.sashes[index - 1],
          orthogonalEnd: last ? this.boundarySashes.end : this.a.sashes[index]
        };
      });
    }
    const onDidSashReset = Event2.map(this.a.onDidSashReset, (i2) => [i2]);
    this.s = onDidSashReset(this.r.fire, this.r);
    this.y();
  }
  style(styles) {
    this.j = styles;
    this.a.style(styles);
    for (const child of this.children) {
      if (child instanceof _BranchNode) {
        child.style(styles);
      }
    }
  }
  layout(size, offset, ctx) {
    if (!this.layoutController.isLayoutEnabled) {
      return;
    }
    if (typeof ctx === "undefined") {
      throw new Error("Invalid state");
    }
    this.b = ctx.orthogonalSize;
    this.d = size;
    this.f = ctx.absoluteOffset + offset;
    this.g = ctx.absoluteOrthogonalOffset;
    this.h = ctx.absoluteOrthogonalSize;
    this.a.layout(ctx.orthogonalSize, {
      orthogonalSize: size,
      absoluteOffset: this.g,
      absoluteOrthogonalOffset: this.f,
      absoluteSize: ctx.absoluteOrthogonalSize,
      absoluteOrthogonalSize: ctx.absoluteSize
    });
    this.z();
  }
  setVisible(visible) {
    for (const child of this.children) {
      child.setVisible(visible);
    }
  }
  addChild(node, size, index, skipLayout) {
    index = validateIndex(index, this.children.length);
    this.a.addView(node, size, index, skipLayout);
    this.children.splice(index, 0, node);
    this.w();
    this.x();
  }
  removeChild(index, sizing) {
    index = validateIndex(index, this.children.length);
    const result = this.a.removeView(index, sizing);
    this.children.splice(index, 1);
    this.w();
    this.x();
    return result;
  }
  removeAllChildren() {
    const result = this.a.removeAllViews();
    this.children.splice(0, this.children.length);
    this.w();
    this.x();
    return result;
  }
  moveChild(from, to) {
    from = validateIndex(from, this.children.length);
    to = validateIndex(to, this.children.length);
    if (from === to) {
      return;
    }
    if (from < to) {
      to -= 1;
    }
    this.a.moveView(from, to);
    this.children.splice(to, 0, this.children.splice(from, 1)[0]);
    this.w();
    this.x();
  }
  swapChildren(from, to) {
    from = validateIndex(from, this.children.length);
    to = validateIndex(to, this.children.length);
    if (from === to) {
      return;
    }
    this.a.swapViews(from, to);
    [this.children[from].boundarySashes, this.children[to].boundarySashes] = [this.children[from].boundarySashes, this.children[to].boundarySashes];
    [this.children[from], this.children[to]] = [this.children[to], this.children[from]];
    this.x();
  }
  resizeChild(index, size) {
    index = validateIndex(index, this.children.length);
    this.a.resizeView(index, size);
  }
  isChildExpanded(index) {
    return this.a.isViewExpanded(index);
  }
  distributeViewSizes(recursive = false) {
    this.a.distributeViewSizes();
    if (recursive) {
      for (const child of this.children) {
        if (child instanceof _BranchNode) {
          child.distributeViewSizes(true);
        }
      }
    }
  }
  getChildSize(index) {
    index = validateIndex(index, this.children.length);
    return this.a.getViewSize(index);
  }
  isChildVisible(index) {
    index = validateIndex(index, this.children.length);
    return this.a.isViewVisible(index);
  }
  setChildVisible(index, visible) {
    index = validateIndex(index, this.children.length);
    if (this.a.isViewVisible(index) === visible) {
      return;
    }
    const wereAllChildrenHidden = this.a.contentSize === 0;
    this.a.setViewVisible(index, visible);
    const areAllChildrenHidden = this.a.contentSize === 0;
    if (visible && wereAllChildrenHidden || !visible && areAllChildrenHidden) {
      this.l.fire(visible);
    }
  }
  getChildCachedVisibleSize(index) {
    index = validateIndex(index, this.children.length);
    return this.a.getViewCachedVisibleSize(index);
  }
  w() {
    for (let i2 = 0; i2 < this.children.length; i2++) {
      this.children[i2].boundarySashes = {
        start: this.boundarySashes.orthogonalStart,
        end: this.boundarySashes.orthogonalEnd,
        orthogonalStart: i2 === 0 ? this.boundarySashes.start : this.a.sashes[i2 - 1],
        orthogonalEnd: i2 === this.children.length - 1 ? this.boundarySashes.end : this.a.sashes[i2]
      };
    }
  }
  x() {
    this.y();
    this.k.fire(void 0);
  }
  y() {
    const onDidChildrenChange = Event2.map(Event2.any(...this.children.map((c) => c.onDidChange)), () => void 0);
    this.q.dispose();
    this.q = onDidChildrenChange(this.k.fire, this.k);
    const onDidChildrenSashReset = Event2.any(...this.children.map((c, i2) => Event2.map(c.onDidSashReset, (location3) => [i2, ...location3])));
    this.t.dispose();
    this.t = onDidChildrenSashReset(this.r.fire, this.r);
    const onDidScroll = Event2.any(Event2.signal(this.a.onDidScroll), ...this.children.map((c) => c.onDidScroll));
    this.o.dispose();
    this.o = onDidScroll(this.n.fire, this.n);
    this.m.clear();
    this.children.forEach((child, index) => {
      if (child instanceof _BranchNode) {
        this.m.add(child.onDidVisibilityChange((visible) => {
          this.setChildVisible(index, visible);
        }));
      }
    });
  }
  trySet2x2(other) {
    if (this.children.length !== 2 || other.children.length !== 2) {
      return $3c.None;
    }
    if (this.getChildSize(0) !== other.getChildSize(0)) {
      return $3c.None;
    }
    const [firstChild, secondChild] = this.children;
    const [otherFirstChild, otherSecondChild] = other.children;
    if (!(firstChild instanceof LeafNode) || !(secondChild instanceof LeafNode)) {
      return $3c.None;
    }
    if (!(otherFirstChild instanceof LeafNode) || !(otherSecondChild instanceof LeafNode)) {
      return $3c.None;
    }
    if (this.orientation === 0) {
      secondChild.linkedWidthNode = otherFirstChild.linkedHeightNode = firstChild;
      firstChild.linkedWidthNode = otherSecondChild.linkedHeightNode = secondChild;
      otherSecondChild.linkedWidthNode = firstChild.linkedHeightNode = otherFirstChild;
      otherFirstChild.linkedWidthNode = secondChild.linkedHeightNode = otherSecondChild;
    } else {
      otherFirstChild.linkedWidthNode = secondChild.linkedHeightNode = firstChild;
      otherSecondChild.linkedWidthNode = firstChild.linkedHeightNode = secondChild;
      firstChild.linkedWidthNode = otherSecondChild.linkedHeightNode = otherFirstChild;
      secondChild.linkedWidthNode = otherFirstChild.linkedHeightNode = otherSecondChild;
    }
    const mySash = this.a.sashes[0];
    const otherSash = other.a.sashes[0];
    mySash.linkedSash = otherSash;
    otherSash.linkedSash = mySash;
    this.k.fire(void 0);
    other.k.fire(void 0);
    return $1c(() => {
      mySash.linkedSash = otherSash.linkedSash = void 0;
      firstChild.linkedHeightNode = firstChild.linkedWidthNode = void 0;
      secondChild.linkedHeightNode = secondChild.linkedWidthNode = void 0;
      otherFirstChild.linkedHeightNode = otherFirstChild.linkedWidthNode = void 0;
      otherSecondChild.linkedHeightNode = otherSecondChild.linkedWidthNode = void 0;
    });
  }
  z() {
    this.a.startSnappingEnabled = this.v || this.g > 0;
    this.a.endSnappingEnabled = this.v || this.g + this.b < this.h;
  }
  dispose() {
    for (const child of this.children) {
      child.dispose();
    }
    this.k.dispose();
    this.r.dispose();
    this.l.dispose();
    this.m.dispose();
    this.s.dispose();
    this.t.dispose();
    this.q.dispose();
    this.o.dispose();
    this.a.dispose();
  }
};
function createLatchedOnDidChangeViewEvent(view) {
  const [onDidChangeViewConstraints, onDidSetViewSize] = Event2.split(view.onDidChange, $Gg);
  return Event2.any(onDidSetViewSize, Event2.map(Event2.latch(Event2.map(onDidChangeViewConstraints, (_) => [view.minimumWidth, view.maximumWidth, view.minimumHeight, view.maximumHeight]), $zb), (_) => void 0));
}
var LeafNode = class {
  get size() {
    return this.a;
  }
  get orthogonalSize() {
    return this.b;
  }
  get linkedWidthNode() {
    return this.h;
  }
  set linkedWidthNode(node) {
    this.g.input = node ? node.m : Event2.None;
    this.h = node;
    this.l.fire(void 0);
  }
  get linkedHeightNode() {
    return this.k;
  }
  set linkedHeightNode(node) {
    this.j.input = node ? node.m : Event2.None;
    this.k = node;
    this.l.fire(void 0);
  }
  constructor(view, orientation, layoutController, orthogonalSize, size = 0) {
    this.view = view;
    this.orientation = orientation;
    this.layoutController = layoutController;
    this.a = 0;
    this.d = 0;
    this.f = 0;
    this.onDidScroll = Event2.None;
    this.onDidSashReset = Event2.None;
    this.g = new $Ie();
    this.h = void 0;
    this.j = new $Ie();
    this.k = void 0;
    this.l = new $ze();
    this.n = new $2c();
    this.t = {};
    this.u = 0;
    this.v = 0;
    this.w = 0;
    this.x = 0;
    this.b = orthogonalSize;
    this.a = size;
    const onDidChange = createLatchedOnDidChangeViewEvent(view);
    this.m = Event2.map(onDidChange, (e) => e && (this.orientation === 0 ? e.width : e.height), this.n);
    this.onDidChange = Event2.any(this.m, this.l.event, this.g.event, this.j.event);
  }
  get width() {
    return this.orientation === 1 ? this.orthogonalSize : this.size;
  }
  get height() {
    return this.orientation === 1 ? this.size : this.orthogonalSize;
  }
  get top() {
    return this.orientation === 1 ? this.d : this.f;
  }
  get left() {
    return this.orientation === 1 ? this.f : this.d;
  }
  get element() {
    return this.view.element;
  }
  get o() {
    return this.linkedWidthNode ? Math.max(this.linkedWidthNode.view.minimumWidth, this.view.minimumWidth) : this.view.minimumWidth;
  }
  get q() {
    return this.linkedWidthNode ? Math.min(this.linkedWidthNode.view.maximumWidth, this.view.maximumWidth) : this.view.maximumWidth;
  }
  get r() {
    return this.linkedHeightNode ? Math.max(this.linkedHeightNode.view.minimumHeight, this.view.minimumHeight) : this.view.minimumHeight;
  }
  get s() {
    return this.linkedHeightNode ? Math.min(this.linkedHeightNode.view.maximumHeight, this.view.maximumHeight) : this.view.maximumHeight;
  }
  get minimumSize() {
    return this.orientation === 1 ? this.r : this.o;
  }
  get maximumSize() {
    return this.orientation === 1 ? this.s : this.q;
  }
  get priority() {
    return this.view.priority;
  }
  get proportionalLayout() {
    return this.view.proportionalLayout ?? true;
  }
  get snap() {
    return this.view.snap;
  }
  get minimumOrthogonalSize() {
    return this.orientation === 1 ? this.o : this.r;
  }
  get maximumOrthogonalSize() {
    return this.orientation === 1 ? this.q : this.s;
  }
  get boundarySashes() {
    return this.t;
  }
  set boundarySashes(boundarySashes) {
    this.t = boundarySashes;
    this.view.setBoundarySashes?.(toAbsoluteBoundarySashes(boundarySashes, this.orientation));
  }
  layout(size, offset, ctx) {
    if (!this.layoutController.isLayoutEnabled) {
      return;
    }
    if (typeof ctx === "undefined") {
      throw new Error("Invalid state");
    }
    this.a = size;
    this.b = ctx.orthogonalSize;
    this.d = ctx.absoluteOffset + offset;
    this.f = ctx.absoluteOrthogonalOffset;
    this.y(this.width, this.height, this.top, this.left);
  }
  y(width2, height, top2, left) {
    if (this.u === width2 && this.v === height && this.w === top2 && this.x === left) {
      return;
    }
    this.u = width2;
    this.v = height;
    this.w = top2;
    this.x = left;
    this.view.layout(width2, height, top2, left);
  }
  setVisible(visible) {
    this.view.setVisible?.(visible);
  }
  dispose() {
    this.n.dispose();
  }
};
function flipNode(node, size, orthogonalSize) {
  if (node instanceof BranchNode) {
    const result = new BranchNode($s2(node.orientation), node.layoutController, node.styles, node.splitviewProportionalLayout, size, orthogonalSize, node.edgeSnapping);
    let totalSize = 0;
    for (let i2 = node.children.length - 1; i2 >= 0; i2--) {
      const child = node.children[i2];
      const childSize = child instanceof BranchNode ? child.orthogonalSize : child.size;
      let newSize = node.size === 0 ? 0 : Math.round(size * childSize / node.size);
      totalSize += newSize;
      if (i2 === 0) {
        newSize += size - totalSize;
      }
      result.addChild(flipNode(child, orthogonalSize, newSize), newSize, 0, true);
    }
    node.dispose();
    return result;
  } else {
    const result = new LeafNode(node.view, $s2(node.orientation), node.layoutController, orthogonalSize);
    node.dispose();
    return result;
  }
}
var $u2 = class _$u2 {
  get m() {
    return this.d;
  }
  set m(root) {
    const oldRoot = this.d;
    if (oldRoot) {
      oldRoot.element.remove();
      oldRoot.dispose();
    }
    this.d = root;
    this.element.appendChild(root.element);
    this.f.input = root.onDidSashReset;
    this.h.input = Event2.map(root.onDidChange, () => void 0);
    this.g.input = root.onDidScroll;
  }
  /**
   * The width of the grid.
   */
  get width() {
    return this.m.width;
  }
  /**
   * The height of the grid.
   */
  get height() {
    return this.m.height;
  }
  /**
   * The minimum width of the grid.
   */
  get minimumWidth() {
    return this.m.minimumWidth;
  }
  /**
   * The minimum height of the grid.
   */
  get minimumHeight() {
    return this.m.minimumHeight;
  }
  /**
   * The maximum width of the grid.
   */
  get maximumWidth() {
    return this.m.maximumHeight;
  }
  /**
   * The maximum height of the grid.
   */
  get maximumHeight() {
    return this.m.maximumHeight;
  }
  get orientation() {
    return this.d.orientation;
  }
  get boundarySashes() {
    return this.j;
  }
  /**
   * The orientation of the grid. Matches the orientation of the root
   * {@link $r2} in the grid's tree model.
   */
  set orientation(orientation) {
    if (this.d.orientation === orientation) {
      return;
    }
    const { size, orthogonalSize, absoluteOffset, absoluteOrthogonalOffset } = this.d;
    this.m = flipNode(this.d, orthogonalSize, size);
    this.m.layout(size, 0, { orthogonalSize, absoluteOffset: absoluteOrthogonalOffset, absoluteOrthogonalOffset: absoluteOffset, absoluteSize: size, absoluteOrthogonalSize: orthogonalSize });
    this.boundarySashes = this.boundarySashes;
  }
  /**
   * A collection of sashes perpendicular to each edge of the grid.
   * Corner sashes will be created for each intersection.
   */
  set boundarySashes(boundarySashes) {
    this.j = boundarySashes;
    this.m.boundarySashes = fromAbsoluteBoundarySashes(boundarySashes, this.orientation);
  }
  /**
   * Enable/disable edge snapping across all grid views.
   */
  set edgeSnapping(edgeSnapping) {
    this.m.edgeSnapping = edgeSnapping;
  }
  /**
   * Create a new {@link $u2} instance.
   *
   * @remarks It's the caller's responsibility to append the
   * {@link $u2.element} to the page's DOM.
   */
  constructor(options3 = {}) {
    this.f = new $Ie();
    this.g = new $Ie();
    this.h = new $Ie();
    this.j = {};
    this.l = $3c.None;
    this.onDidSashReset = this.f.event;
    this.onDidScroll = this.g.event;
    this.onDidChange = this.h.event;
    this.n = void 0;
    this.o = new $ze();
    this.onDidChangeViewMaximized = this.o.event;
    this.element = $(".monaco-grid-view");
    this.a = options3.styles || defaultStyles2;
    this.b = typeof options3.proportionalLayout !== "undefined" ? !!options3.proportionalLayout : true;
    this.k = new LayoutController(false);
    this.m = new BranchNode(0, this.k, this.a, this.b);
  }
  style(styles) {
    this.a = styles;
    this.m.style(styles);
  }
  /**
   * Layout the {@link $u2}.
   *
   * Optionally provide a `top` and `left` positions, those will propagate
   * as an origin for positions passed to {@link IView.layout}.
   *
   * @param width The width of the {@link $u2}.
   * @param height The height of the {@link $u2}.
   * @param top Optional, the top location of the {@link $u2}.
   * @param left Optional, the left location of the {@link $u2}.
   */
  layout(width2, height, top2 = 0, left = 0) {
    this.k.isLayoutEnabled = true;
    const [size, orthogonalSize, offset, orthogonalOffset] = this.m.orientation === 1 ? [height, width2, top2, left] : [width2, height, left, top2];
    this.m.layout(size, 0, { orthogonalSize, absoluteOffset: offset, absoluteOrthogonalOffset: orthogonalOffset, absoluteSize: size, absoluteOrthogonalSize: orthogonalSize });
  }
  /**
   * Add a {@link IView view} to this {@link $u2}.
   *
   * @param view The view to add.
   * @param size Either a fixed size, or a dynamic {@link Sizing} strategy.
   * @param location The {@link GridLocation location} to insert the view on.
   */
  addView(view, size, location3) {
    if (this.hasMaximizedView()) {
      this.exitMaximizedView();
    }
    this.l.dispose();
    this.l = $3c.None;
    const [rest, index] = $yb(location3);
    const [pathToParent, parent] = this.t(rest);
    if (parent instanceof BranchNode) {
      const node = new LeafNode(view, $s2(parent.orientation), this.k, parent.orthogonalSize);
      try {
        parent.addChild(node, size, index);
      } catch (err) {
        node.dispose();
        throw err;
      }
    } else {
      const [, grandParent] = $yb(pathToParent);
      const [, parentIndex] = $yb(rest);
      let newSiblingSize = 0;
      const newSiblingCachedVisibleSize = grandParent.getChildCachedVisibleSize(parentIndex);
      if (typeof newSiblingCachedVisibleSize === "number") {
        newSiblingSize = Sizing.Invisible(newSiblingCachedVisibleSize);
      }
      const oldChild = grandParent.removeChild(parentIndex);
      oldChild.dispose();
      const newParent = new BranchNode(parent.orientation, parent.layoutController, this.a, this.b, parent.size, parent.orthogonalSize, grandParent.edgeSnapping);
      grandParent.addChild(newParent, parent.size, parentIndex);
      const newSibling = new LeafNode(parent.view, grandParent.orientation, this.k, parent.size);
      newParent.addChild(newSibling, newSiblingSize, 0);
      if (typeof size !== "number" && size.type === "split") {
        size = Sizing.Split(0);
      }
      const node = new LeafNode(view, grandParent.orientation, this.k, parent.size);
      newParent.addChild(node, size, index);
    }
    this.trySet2x2();
  }
  /**
   * Remove a {@link IView view} from this {@link $u2}.
   *
   * @param location The {@link GridLocation location} of the {@link IView view}.
   * @param sizing Whether to distribute other {@link IView view}'s sizes.
   */
  removeView(location3, sizing) {
    if (this.hasMaximizedView()) {
      this.exitMaximizedView();
    }
    this.l.dispose();
    this.l = $3c.None;
    const [rest, index] = $yb(location3);
    const [pathToParent, parent] = this.t(rest);
    if (!(parent instanceof BranchNode)) {
      throw new Error("Invalid location");
    }
    const node = parent.children[index];
    if (!(node instanceof LeafNode)) {
      throw new Error("Invalid location");
    }
    parent.removeChild(index, sizing);
    node.dispose();
    if (parent.children.length === 0) {
      throw new Error("Invalid grid state");
    }
    if (parent.children.length > 1) {
      this.trySet2x2();
      return node.view;
    }
    if (pathToParent.length === 0) {
      const sibling2 = parent.children[0];
      if (sibling2 instanceof LeafNode) {
        return node.view;
      }
      parent.removeChild(0);
      parent.dispose();
      this.m = sibling2;
      this.boundarySashes = this.boundarySashes;
      this.trySet2x2();
      return node.view;
    }
    const [, grandParent] = $yb(pathToParent);
    const [, parentIndex] = $yb(rest);
    const isSiblingVisible = parent.isChildVisible(0);
    const sibling = parent.removeChild(0);
    const sizes = grandParent.children.map((_, i2) => grandParent.getChildSize(i2));
    grandParent.removeChild(parentIndex, sizing);
    parent.dispose();
    if (sibling instanceof BranchNode) {
      sizes.splice(parentIndex, 1, ...sibling.children.map((c) => c.size));
      const siblingChildren = sibling.removeAllChildren();
      for (let i2 = 0; i2 < siblingChildren.length; i2++) {
        grandParent.addChild(siblingChildren[i2], siblingChildren[i2].size, parentIndex + i2);
      }
    } else {
      const newSibling = new LeafNode(sibling.view, $s2(sibling.orientation), this.k, sibling.size);
      const sizing2 = isSiblingVisible ? sibling.orthogonalSize : Sizing.Invisible(sibling.orthogonalSize);
      grandParent.addChild(newSibling, sizing2, parentIndex);
    }
    sibling.dispose();
    for (let i2 = 0; i2 < sizes.length; i2++) {
      grandParent.resizeChild(i2, sizes[i2]);
    }
    this.trySet2x2();
    return node.view;
  }
  /**
   * Move a {@link IView view} within its parent.
   *
   * @param parentLocation The {@link GridLocation location} of the {@link IView view}'s parent.
   * @param from The index of the {@link IView view} to move.
   * @param to The index where the {@link IView view} should move to.
   */
  moveView(parentLocation, from, to) {
    if (this.hasMaximizedView()) {
      this.exitMaximizedView();
    }
    const [, parent] = this.t(parentLocation);
    if (!(parent instanceof BranchNode)) {
      throw new Error("Invalid location");
    }
    parent.moveChild(from, to);
    this.trySet2x2();
  }
  /**
   * Swap two {@link IView views} within the {@link $u2}.
   *
   * @param from The {@link GridLocation location} of one view.
   * @param to The {@link GridLocation location} of another view.
   */
  swapViews(from, to) {
    if (this.hasMaximizedView()) {
      this.exitMaximizedView();
    }
    const [fromRest, fromIndex] = $yb(from);
    const [, fromParent] = this.t(fromRest);
    if (!(fromParent instanceof BranchNode)) {
      throw new Error("Invalid from location");
    }
    const fromSize = fromParent.getChildSize(fromIndex);
    const fromNode = fromParent.children[fromIndex];
    if (!(fromNode instanceof LeafNode)) {
      throw new Error("Invalid from location");
    }
    const [toRest, toIndex] = $yb(to);
    const [, toParent] = this.t(toRest);
    if (!(toParent instanceof BranchNode)) {
      throw new Error("Invalid to location");
    }
    const toSize2 = toParent.getChildSize(toIndex);
    const toNode = toParent.children[toIndex];
    if (!(toNode instanceof LeafNode)) {
      throw new Error("Invalid to location");
    }
    if (fromParent === toParent) {
      fromParent.swapChildren(fromIndex, toIndex);
    } else {
      fromParent.removeChild(fromIndex);
      toParent.removeChild(toIndex);
      fromParent.addChild(toNode, fromSize, fromIndex);
      toParent.addChild(fromNode, toSize2, toIndex);
    }
    this.trySet2x2();
  }
  /**
   * Resize a {@link IView view}.
   *
   * @param location The {@link GridLocation location} of the view.
   * @param size The size the view should be. Optionally provide a single dimension.
   */
  resizeView(location3, size) {
    if (this.hasMaximizedView()) {
      this.exitMaximizedView();
    }
    const [rest, index] = $yb(location3);
    const [pathToParent, parent] = this.t(rest);
    if (!(parent instanceof BranchNode)) {
      throw new Error("Invalid location");
    }
    if (!size.width && !size.height) {
      return;
    }
    const [parentSize, grandParentSize] = parent.orientation === 1 ? [size.width, size.height] : [size.height, size.width];
    if (typeof grandParentSize === "number" && pathToParent.length > 0) {
      const [, grandParent] = $yb(pathToParent);
      const [, parentIndex] = $yb(rest);
      grandParent.resizeChild(parentIndex, grandParentSize);
    }
    if (typeof parentSize === "number") {
      parent.resizeChild(index, parentSize);
    }
    this.trySet2x2();
  }
  /**
   * Get the size of a {@link IView view}.
   *
   * @param location The {@link GridLocation location} of the view. Provide `undefined` to get
   * the size of the grid itself.
   */
  getViewSize(location3) {
    if (!location3) {
      return { width: this.m.width, height: this.m.height };
    }
    const [, node] = this.t(location3);
    return { width: node.width, height: node.height };
  }
  /**
   * Get the cached visible size of a {@link IView view}. This was the size
   * of the view at the moment it last became hidden.
   *
   * @param location The {@link GridLocation location} of the view.
   */
  getViewCachedVisibleSize(location3) {
    const [rest, index] = $yb(location3);
    const [, parent] = this.t(rest);
    if (!(parent instanceof BranchNode)) {
      throw new Error("Invalid location");
    }
    return parent.getChildCachedVisibleSize(index);
  }
  /**
   * Maximize the size of a {@link IView view} by collapsing all other views
   * to their minimum sizes.
   *
   * @param location The {@link GridLocation location} of the view.
   */
  expandView(location3) {
    if (this.hasMaximizedView()) {
      this.exitMaximizedView();
    }
    const [ancestors, node] = this.t(location3);
    if (!(node instanceof LeafNode)) {
      throw new Error("Invalid location");
    }
    for (let i2 = 0; i2 < ancestors.length; i2++) {
      ancestors[i2].resizeChild(location3[i2], Number.POSITIVE_INFINITY);
    }
  }
  /**
   * Returns whether all other {@link IView views} are at their minimum size.
   *
   * @param location The {@link GridLocation location} of the view.
   */
  isViewExpanded(location3) {
    if (this.hasMaximizedView()) {
      return false;
    }
    const [ancestors, node] = this.t(location3);
    if (!(node instanceof LeafNode)) {
      throw new Error("Invalid location");
    }
    for (let i2 = 0; i2 < ancestors.length; i2++) {
      if (!ancestors[i2].isChildExpanded(location3[i2])) {
        return false;
      }
    }
    return true;
  }
  maximizeView(location3) {
    const [, nodeToMaximize] = this.t(location3);
    if (!(nodeToMaximize instanceof LeafNode)) {
      throw new Error("Location is not a LeafNode");
    }
    if (this.n === nodeToMaximize) {
      return;
    }
    if (this.hasMaximizedView()) {
      this.exitMaximizedView();
    }
    function hideAllViewsBut(parent, exclude) {
      for (let i2 = 0; i2 < parent.children.length; i2++) {
        const child = parent.children[i2];
        if (child instanceof LeafNode) {
          if (child !== exclude) {
            parent.setChildVisible(i2, false);
          }
        } else {
          hideAllViewsBut(child, exclude);
        }
      }
    }
    hideAllViewsBut(this.m, nodeToMaximize);
    this.n = nodeToMaximize;
    this.o.fire(true);
  }
  exitMaximizedView() {
    if (!this.n) {
      return;
    }
    this.n = void 0;
    function showViewsInReverseOrder(parent) {
      for (let index = parent.children.length - 1; index >= 0; index--) {
        const child = parent.children[index];
        if (child instanceof LeafNode) {
          parent.setChildVisible(index, true);
        } else {
          showViewsInReverseOrder(child);
        }
      }
    }
    showViewsInReverseOrder(this.m);
    this.o.fire(false);
  }
  hasMaximizedView() {
    return this.n !== void 0;
  }
  /**
   * Returns whether the {@link IView view} is maximized.
   *
   * @param location The {@link GridLocation location} of the view.
   */
  isViewMaximized(location3) {
    const [, node] = this.t(location3);
    if (!(node instanceof LeafNode)) {
      throw new Error("Location is not a LeafNode");
    }
    return node === this.n;
  }
  /**
   * Distribute the size among all {@link IView views} within the entire
   * grid or within a single {@link $r2}.
   *
   * @param location The {@link GridLocation location} of a view containing
   * children views, which will have their sizes distributed within the parent
   * view's size. Provide `undefined` to recursively distribute all views' sizes
   * in the entire grid.
   */
  distributeViewSizes(location3) {
    if (this.hasMaximizedView()) {
      this.exitMaximizedView();
    }
    if (!location3) {
      this.m.distributeViewSizes(true);
      return;
    }
    const [, node] = this.t(location3);
    if (!(node instanceof BranchNode)) {
      throw new Error("Invalid location");
    }
    node.distributeViewSizes();
    this.trySet2x2();
  }
  /**
   * Returns whether a {@link IView view} is visible.
   *
   * @param location The {@link GridLocation location} of the view.
   */
  isViewVisible(location3) {
    const [rest, index] = $yb(location3);
    const [, parent] = this.t(rest);
    if (!(parent instanceof BranchNode)) {
      throw new Error("Invalid from location");
    }
    return parent.isChildVisible(index);
  }
  /**
   * Set the visibility state of a {@link IView view}.
   *
   * @param location The {@link GridLocation location} of the view.
   */
  setViewVisible(location3, visible) {
    if (this.hasMaximizedView()) {
      this.exitMaximizedView();
      return;
    }
    const [rest, index] = $yb(location3);
    const [, parent] = this.t(rest);
    if (!(parent instanceof BranchNode)) {
      throw new Error("Invalid from location");
    }
    parent.setChildVisible(index, visible);
  }
  getView(location3) {
    const node = location3 ? this.t(location3)[1] : this.d;
    return this.s(node, this.orientation);
  }
  /**
   * Construct a new {@link $u2} from a JSON object.
   *
   * @param json The JSON object.
   * @param deserializer A deserializer which can revive each view.
   * @returns A new {@link $u2} instance.
   */
  static deserialize(json, deserializer, options3 = {}) {
    if (typeof json.orientation !== "number") {
      throw new Error("Invalid JSON: 'orientation' property must be a number.");
    } else if (typeof json.width !== "number") {
      throw new Error("Invalid JSON: 'width' property must be a number.");
    } else if (typeof json.height !== "number") {
      throw new Error("Invalid JSON: 'height' property must be a number.");
    } else if (json.root?.type !== "branch") {
      throw new Error("Invalid JSON: 'root' property must have 'type' value of branch.");
    }
    const orientation = json.orientation;
    const height = json.height;
    const result = new _$u2(options3);
    result.q(json.root, orientation, deserializer, height);
    return result;
  }
  q(root, orientation, deserializer, orthogonalSize) {
    this.m = this.r(root, orientation, deserializer, orthogonalSize);
  }
  r(node, orientation, deserializer, orthogonalSize) {
    let result;
    if (node.type === "branch") {
      const serializedChildren = node.data;
      const children = serializedChildren.map((serializedChild) => {
        return {
          node: this.r(serializedChild, $s2(orientation), deserializer, node.size),
          visible: serializedChild.visible
        };
      });
      result = new BranchNode(orientation, this.k, this.a, this.b, node.size, orthogonalSize, void 0, children);
    } else {
      result = new LeafNode(deserializer.fromJSON(node.data), orientation, this.k, orthogonalSize, node.size);
      if (node.maximized && !this.n) {
        this.n = result;
        this.o.fire(true);
      }
    }
    return result;
  }
  s(node, orientation, cachedVisibleSize) {
    const box = { top: node.top, left: node.left, width: node.width, height: node.height };
    if (node instanceof LeafNode) {
      return { view: node.view, box, cachedVisibleSize, maximized: this.n === node };
    }
    const children = [];
    for (let i2 = 0; i2 < node.children.length; i2++) {
      const child = node.children[i2];
      const cachedVisibleSize2 = node.getChildCachedVisibleSize(i2);
      children.push(this.s(child, $s2(orientation), cachedVisibleSize2));
    }
    return { children, box };
  }
  t(location3, node = this.m, path = []) {
    if (location3.length === 0) {
      return [path, node];
    }
    if (!(node instanceof BranchNode)) {
      throw new Error("Invalid location");
    }
    const [index, ...rest] = location3;
    if (index < 0 || index >= node.children.length) {
      throw new Error("Invalid location");
    }
    const child = node.children[index];
    path.push(node);
    return this.t(rest, child, path);
  }
  /**
   * Attempt to lock the {@link $q2 sashes} in this {@link $u2} so
   * the grid behaves as a 2x2 matrix, with a corner sash in the middle.
   *
   * In case the grid isn't a 2x2 grid _and_ all sashes are not aligned,
   * this method is a no-op.
   */
  trySet2x2() {
    this.l.dispose();
    this.l = $3c.None;
    if (this.m.children.length !== 2) {
      return;
    }
    const [first, second] = this.m.children;
    if (!(first instanceof BranchNode) || !(second instanceof BranchNode)) {
      return;
    }
    this.l = first.trySet2x2(second);
  }
  /**
   * Populate a map with views to DOM nodes.
   * @remarks To be used internally only.
   */
  getViewMap(map, node) {
    if (!node) {
      node = this.m;
    }
    if (node instanceof BranchNode) {
      node.children.forEach((child) => this.getViewMap(map, child));
    } else {
      map.set(node.view, node.element);
    }
  }
  dispose() {
    this.f.dispose();
    this.m.dispose();
    this.element.remove();
  }
};

// out-build/vs/base/browser/ui/grid/grid.js
var Direction3;
(function(Direction4) {
  Direction4[Direction4["Up"] = 0] = "Up";
  Direction4[Direction4["Down"] = 1] = "Down";
  Direction4[Direction4["Left"] = 2] = "Left";
  Direction4[Direction4["Right"] = 3] = "Right";
})(Direction3 || (Direction3 = {}));
function oppositeDirection(direction) {
  switch (direction) {
    case 0:
      return 1;
    case 1:
      return 0;
    case 2:
      return 3;
    case 3:
      return 2;
  }
}
function $v2(node) {
  return !!node.children;
}
function getGridNode(node, location3) {
  if (location3.length === 0) {
    return node;
  }
  if (!$v2(node)) {
    throw new Error("Invalid location");
  }
  const [index, ...rest] = location3;
  return getGridNode(node.children[index], rest);
}
function intersects3(one, other) {
  return !(one.start >= other.end || other.start >= one.end);
}
function getBoxBoundary(box, direction) {
  const orientation = getDirectionOrientation(direction);
  const offset = direction === 0 ? box.top : direction === 3 ? box.left + box.width : direction === 1 ? box.top + box.height : box.left;
  const range = {
    start: orientation === 1 ? box.top : box.left,
    end: orientation === 1 ? box.top + box.height : box.left + box.width
  };
  return { offset, range };
}
function findAdjacentBoxLeafNodes(boxNode, direction, boundary) {
  const result = [];
  function _(boxNode2, direction2, boundary2) {
    if ($v2(boxNode2)) {
      for (const child of boxNode2.children) {
        _(child, direction2, boundary2);
      }
    } else {
      const { offset, range } = getBoxBoundary(boxNode2.box, direction2);
      if (offset === boundary2.offset && intersects3(range, boundary2.range)) {
        result.push(boxNode2);
      }
    }
  }
  _(boxNode, direction, boundary);
  return result;
}
function getLocationOrientation(rootOrientation, location3) {
  return location3.length % 2 === 0 ? $s2(rootOrientation) : rootOrientation;
}
function getDirectionOrientation(direction) {
  return direction === 0 || direction === 1 ? 0 : 1;
}
function $w2(rootOrientation, location3, direction) {
  const orientation = getLocationOrientation(rootOrientation, location3);
  const directionOrientation = getDirectionOrientation(direction);
  if (orientation === directionOrientation) {
    let [rest, index] = $yb(location3);
    if (direction === 3 || direction === 1) {
      index += 1;
    }
    return [...rest, index];
  } else {
    const index = direction === 3 || direction === 1 ? 1 : 0;
    return [...location3, index];
  }
}
function indexInParent(element) {
  const parentElement = element.parentElement;
  if (!parentElement) {
    throw new Error("Invalid grid element");
  }
  let el = parentElement.firstElementChild;
  let index = 0;
  while (el !== element && el !== parentElement.lastElementChild && el) {
    el = el.nextElementSibling;
    index++;
  }
  return index;
}
function getGridLocation(element) {
  const parentElement = element.parentElement;
  if (!parentElement) {
    throw new Error("Invalid grid element");
  }
  if (/\bmonaco-grid-view\b/.test(parentElement.className)) {
    return [];
  }
  const index = indexInParent(parentElement);
  const ancestor = parentElement.parentElement.parentElement.parentElement.parentElement;
  return [...getGridLocation(ancestor), index];
}
var Sizing2;
(function(Sizing3) {
  Sizing3.Distribute = { type: "distribute" };
  Sizing3.Split = { type: "split" };
  Sizing3.Auto = { type: "auto" };
  function Invisible(cachedVisibleSize) {
    return { type: "invisible", cachedVisibleSize };
  }
  Sizing3.Invisible = Invisible;
})(Sizing2 || (Sizing2 = {}));
var $x2 = class extends $3c {
  /**
   * The orientation of the grid. Matches the orientation of the root
   * {@link $r2} in the grid's {@link GridLocation} model.
   */
  get orientation() {
    return this.a.orientation;
  }
  set orientation(orientation) {
    this.a.orientation = orientation;
  }
  /**
   * The width of the grid.
   */
  get width() {
    return this.a.width;
  }
  /**
   * The height of the grid.
   */
  get height() {
    return this.a.height;
  }
  /**
   * The minimum width of the grid.
   */
  get minimumWidth() {
    return this.a.minimumWidth;
  }
  /**
   * The minimum height of the grid.
   */
  get minimumHeight() {
    return this.a.minimumHeight;
  }
  /**
   * The maximum width of the grid.
   */
  get maximumWidth() {
    return this.a.maximumWidth;
  }
  /**
   * The maximum height of the grid.
   */
  get maximumHeight() {
    return this.a.maximumHeight;
  }
  /**
   * A collection of sashes perpendicular to each edge of the grid.
   * Corner sashes will be created for each intersection.
   */
  get boundarySashes() {
    return this.a.boundarySashes;
  }
  set boundarySashes(boundarySashes) {
    this.a.boundarySashes = boundarySashes;
  }
  /**
   * Enable/disable edge snapping across all grid views.
   */
  set edgeSnapping(edgeSnapping) {
    this.a.edgeSnapping = edgeSnapping;
  }
  /**
   * The DOM element for this view.
   */
  get element() {
    return this.a.element;
  }
  /**
   * Create a new {@link $x2}. A grid must *always* have a view
   * inside.
   *
   * @param view An initial view for this Grid.
   */
  constructor(view, options3 = {}) {
    super();
    this.b = /* @__PURE__ */ new Map();
    this.f = false;
    if (view instanceof $u2) {
      this.a = view;
      this.a.getViewMap(this.b);
    } else {
      this.a = new $u2(options3);
    }
    this.B(this.a);
    this.B(this.a.onDidSashReset(this.m, this));
    if (!(view instanceof $u2)) {
      this.h(view, 0, [0]);
    }
    this.onDidChange = this.a.onDidChange;
    this.onDidScroll = this.a.onDidScroll;
    this.onDidChangeViewMaximized = this.a.onDidChangeViewMaximized;
  }
  style(styles) {
    this.a.style(styles);
  }
  /**
   * Layout the {@link $x2}.
   *
   * Optionally provide a `top` and `left` positions, those will propagate
   * as an origin for positions passed to {@link IView.layout}.
   *
   * @param width The width of the {@link $x2}.
   * @param height The height of the {@link $x2}.
   * @param top Optional, the top location of the {@link $x2}.
   * @param left Optional, the left location of the {@link $x2}.
   */
  layout(width2, height, top2 = 0, left = 0) {
    this.a.layout(width2, height, top2, left);
    this.f = true;
  }
  /**
   * Add a {@link IView view} to this {@link $x2}, based on another reference view.
   *
   * Take this grid as an example:
   *
   * ```
   *  +-----+---------------+
   *  |  A  |      B        |
   *  +-----+---------+-----+
   *  |        C      |     |
   *  +---------------+  D  |
   *  |        E      |     |
   *  +---------------+-----+
   * ```
   *
   * Calling `addView(X, Sizing.Distribute, C, Direction.Right)` will make the following
   * changes:
   *
   * ```
   *  +-----+---------------+
   *  |  A  |      B        |
   *  +-----+-+-------+-----+
   *  |   C   |   X   |     |
   *  +-------+-------+  D  |
   *  |        E      |     |
   *  +---------------+-----+
   * ```
   *
   * Or `addView(X, Sizing.Distribute, D, Direction.Down)`:
   *
   * ```
   *  +-----+---------------+
   *  |  A  |      B        |
   *  +-----+---------+-----+
   *  |        C      |  D  |
   *  +---------------+-----+
   *  |        E      |  X  |
   *  +---------------+-----+
   * ```
   *
   * @param newView The view to add.
   * @param size Either a fixed size, or a dynamic {@link Sizing} strategy.
   * @param referenceView Another view to place this new view next to.
   * @param direction The direction the new view should be placed next to the reference view.
   */
  addView(newView, size, referenceView, direction) {
    if (this.b.has(newView)) {
      throw new Error("Can't add same view twice");
    }
    const orientation = getDirectionOrientation(direction);
    if (this.b.size === 1 && this.orientation !== orientation) {
      this.orientation = orientation;
    }
    const referenceLocation = this.j(referenceView);
    const location3 = $w2(this.a.orientation, referenceLocation, direction);
    let viewSize;
    if (typeof size === "number") {
      viewSize = size;
    } else if (size.type === "split") {
      const [, index] = $yb(referenceLocation);
      viewSize = Sizing.Split(index);
    } else if (size.type === "distribute") {
      viewSize = Sizing.Distribute;
    } else if (size.type === "auto") {
      const [, index] = $yb(referenceLocation);
      viewSize = Sizing.Auto(index);
    } else {
      viewSize = size;
    }
    this.h(newView, viewSize, location3);
  }
  g(newView, size, location3) {
    if (this.b.has(newView)) {
      throw new Error("Can't add same view twice");
    }
    let viewSize;
    if (typeof size === "number") {
      viewSize = size;
    } else if (size.type === "distribute") {
      viewSize = Sizing.Distribute;
    } else {
      viewSize = size;
    }
    this.h(newView, viewSize, location3);
  }
  h(newView, size, location3) {
    this.b.set(newView, newView.element);
    this.a.addView(newView, size, location3);
  }
  /**
   * Remove a {@link IView view} from this {@link $x2}.
   *
   * @param view The {@link IView view} to remove.
   * @param sizing Whether to distribute other {@link IView view}'s sizes.
   */
  removeView(view, sizing) {
    if (this.b.size === 1) {
      throw new Error("Can't remove last view");
    }
    const location3 = this.j(view);
    let gridViewSizing;
    if (sizing?.type === "distribute") {
      gridViewSizing = Sizing.Distribute;
    } else if (sizing?.type === "auto") {
      const index = location3[location3.length - 1];
      gridViewSizing = Sizing.Auto(index === 0 ? 1 : index - 1);
    }
    this.a.removeView(location3, gridViewSizing);
    this.b.delete(view);
  }
  /**
   * Move a {@link IView view} to another location in the grid.
   *
   * @remarks See {@link $x2.addView}.
   *
   * @param view The {@link IView view} to move.
   * @param sizing Either a fixed size, or a dynamic {@link Sizing} strategy.
   * @param referenceView Another view to place the view next to.
   * @param direction The direction the view should be placed next to the reference view.
   */
  moveView(view, sizing, referenceView, direction) {
    const sourceLocation = this.j(view);
    const [sourceParentLocation, from] = $yb(sourceLocation);
    const referenceLocation = this.j(referenceView);
    const targetLocation = $w2(this.a.orientation, referenceLocation, direction);
    const [targetParentLocation, to] = $yb(targetLocation);
    if ($zb(sourceParentLocation, targetParentLocation)) {
      this.a.moveView(sourceParentLocation, from, to);
    } else {
      this.removeView(view, typeof sizing === "number" ? void 0 : sizing);
      this.addView(view, sizing, referenceView, direction);
    }
  }
  /**
   * Move a {@link IView view} to another location in the grid.
   *
   * @remarks Internal method, do not use without knowing what you're doing.
   * @remarks See {@link $u2.moveView}.
   *
   * @param view The {@link IView view} to move.
   * @param location The {@link GridLocation location} to insert the view on.
   */
  moveViewTo(view, location3) {
    const sourceLocation = this.j(view);
    const [sourceParentLocation, from] = $yb(sourceLocation);
    const [targetParentLocation, to] = $yb(location3);
    if ($zb(sourceParentLocation, targetParentLocation)) {
      this.a.moveView(sourceParentLocation, from, to);
    } else {
      const size = this.getViewSize(view);
      const orientation = getLocationOrientation(this.a.orientation, sourceLocation);
      const cachedViewSize = this.getViewCachedVisibleSize(view);
      const sizing = typeof cachedViewSize === "undefined" ? orientation === 1 ? size.width : size.height : Sizing2.Invisible(cachedViewSize);
      this.removeView(view);
      this.g(view, sizing, location3);
    }
  }
  /**
   * Swap two {@link IView views} within the {@link $x2}.
   *
   * @param from One {@link IView view}.
   * @param to Another {@link IView view}.
   */
  swapViews(from, to) {
    const fromLocation = this.j(from);
    const toLocation = this.j(to);
    return this.a.swapViews(fromLocation, toLocation);
  }
  /**
   * Resize a {@link IView view}.
   *
   * @param view The {@link IView view} to resize.
   * @param size The size the view should be.
   */
  resizeView(view, size) {
    const location3 = this.j(view);
    return this.a.resizeView(location3, size);
  }
  /**
   * Returns whether all other {@link IView views} are at their minimum size.
   *
   * @param view The reference {@link IView view}.
   */
  isViewExpanded(view) {
    const location3 = this.j(view);
    return this.a.isViewExpanded(location3);
  }
  /**
   * Returns whether the {@link IView view} is maximized.
   *
   * @param view The reference {@link IView view}.
   */
  isViewMaximized(view) {
    const location3 = this.j(view);
    return this.a.isViewMaximized(location3);
  }
  /**
   * Returns whether the {@link IView view} is maximized.
   *
   * @param view The reference {@link IView view}.
   */
  hasMaximizedView() {
    return this.a.hasMaximizedView();
  }
  /**
   * Get the size of a {@link IView view}.
   *
   * @param view The {@link IView view}. Provide `undefined` to get the size
   * of the grid itself.
   */
  getViewSize(view) {
    if (!view) {
      return this.a.getViewSize();
    }
    const location3 = this.j(view);
    return this.a.getViewSize(location3);
  }
  /**
   * Get the cached visible size of a {@link IView view}. This was the size
   * of the view at the moment it last became hidden.
   *
   * @param view The {@link IView view}.
   */
  getViewCachedVisibleSize(view) {
    const location3 = this.j(view);
    return this.a.getViewCachedVisibleSize(location3);
  }
  /**
   * Maximizes the specified view and hides all other views.
   * @param view The view to maximize.
   */
  maximizeView(view) {
    if (this.b.size < 2) {
      throw new Error("At least two views are required to maximize a view");
    }
    const location3 = this.j(view);
    this.a.maximizeView(location3);
  }
  exitMaximizedView() {
    this.a.exitMaximizedView();
  }
  /**
   * Expand the size of a {@link IView view} by collapsing all other views
   * to their minimum sizes.
   *
   * @param view The {@link IView view}.
   */
  expandView(view) {
    const location3 = this.j(view);
    this.a.expandView(location3);
  }
  /**
   * Distribute the size among all {@link IView views} within the entire
   * grid or within a single {@link $r2}.
   */
  distributeViewSizes() {
    this.a.distributeViewSizes();
  }
  /**
   * Returns whether a {@link IView view} is visible.
   *
   * @param view The {@link IView view}.
   */
  isViewVisible(view) {
    const location3 = this.j(view);
    return this.a.isViewVisible(location3);
  }
  /**
   * Set the visibility state of a {@link IView view}.
   *
   * @param view The {@link IView view}.
   */
  setViewVisible(view, visible) {
    const location3 = this.j(view);
    this.a.setViewVisible(location3, visible);
  }
  /**
   * Returns a descriptor for the entire grid.
   */
  getViews() {
    return this.a.getView();
  }
  /**
   * Utility method to return the collection all views which intersect
   * a view's edge.
   *
   * @param view The {@link IView view}.
   * @param direction Which direction edge to be considered.
   * @param wrap Whether the grid wraps around (from right to left, from bottom to top).
   */
  getNeighborViews(view, direction, wrap = false) {
    if (!this.f) {
      throw new Error("Can't call getNeighborViews before first layout");
    }
    const location3 = this.j(view);
    const root = this.getViews();
    const node = getGridNode(root, location3);
    let boundary = getBoxBoundary(node.box, direction);
    if (wrap) {
      if (direction === 0 && node.box.top === 0) {
        boundary = { offset: root.box.top + root.box.height, range: boundary.range };
      } else if (direction === 3 && node.box.left + node.box.width === root.box.width) {
        boundary = { offset: 0, range: boundary.range };
      } else if (direction === 1 && node.box.top + node.box.height === root.box.height) {
        boundary = { offset: 0, range: boundary.range };
      } else if (direction === 2 && node.box.left === 0) {
        boundary = { offset: root.box.left + root.box.width, range: boundary.range };
      }
    }
    return findAdjacentBoxLeafNodes(root, oppositeDirection(direction), boundary).map((node2) => node2.view);
  }
  j(view) {
    const element = this.b.get(view);
    if (!element) {
      throw new Error("View not found");
    }
    return getGridLocation(element);
  }
  m(location3) {
    const resizeToPreferredSize = (location4) => {
      const node = this.a.getView(location4);
      if ($v2(node)) {
        return false;
      }
      const direction = getLocationOrientation(this.orientation, location4);
      const size = direction === 1 ? node.view.preferredWidth : node.view.preferredHeight;
      if (typeof size !== "number") {
        return false;
      }
      const viewSize = direction === 1 ? { width: Math.round(size) } : { height: Math.round(size) };
      this.a.resizeView(location4, viewSize);
      return true;
    };
    if (resizeToPreferredSize(location3)) {
      return;
    }
    const [parentLocation, index] = $yb(location3);
    if (resizeToPreferredSize([...parentLocation, index + 1])) {
      return;
    }
    this.a.distributeViewSizes(parentLocation);
  }
};
var $y2 = class _$y2 extends $x2 {
  constructor() {
    super(...arguments);
    this.s = true;
  }
  static n(node, orientation) {
    const size = orientation === 0 ? node.box.width : node.box.height;
    if (!$v2(node)) {
      const serializedLeafNode = { type: "leaf", data: node.view.toJSON(), size };
      if (typeof node.cachedVisibleSize === "number") {
        serializedLeafNode.size = node.cachedVisibleSize;
        serializedLeafNode.visible = false;
      } else if (node.maximized) {
        serializedLeafNode.maximized = true;
      }
      return serializedLeafNode;
    }
    const data = node.children.map((c) => _$y2.n(c, $s2(orientation)));
    if (data.some((c) => c.visible !== false)) {
      return { type: "branch", data, size };
    }
    return { type: "branch", data, size, visible: false };
  }
  /**
   * Construct a new {@link $y2} from a JSON object.
   *
   * @param json The JSON object.
   * @param deserializer A deserializer which can revive each view.
   * @returns A new {@link $y2} instance.
   */
  static deserialize(json, deserializer, options3 = {}) {
    if (typeof json.orientation !== "number") {
      throw new Error("Invalid JSON: 'orientation' property must be a number.");
    } else if (typeof json.width !== "number") {
      throw new Error("Invalid JSON: 'width' property must be a number.");
    } else if (typeof json.height !== "number") {
      throw new Error("Invalid JSON: 'height' property must be a number.");
    }
    const gridview = $u2.deserialize(json, deserializer, options3);
    const result = new _$y2(gridview, options3);
    return result;
  }
  /**
   * Construct a new {@link $y2} from a grid descriptor.
   *
   * @param gridDescriptor A grid descriptor in which leaf nodes point to actual views.
   * @returns A new {@link $y2} instance.
   */
  static from(gridDescriptor, options3 = {}) {
    return _$y2.deserialize($A2(gridDescriptor), { fromJSON: (view) => view }, options3);
  }
  /**
   * Serialize this grid into a JSON object.
   */
  serialize() {
    return {
      root: _$y2.n(this.getViews(), this.orientation),
      orientation: this.orientation,
      width: this.width,
      height: this.height
    };
  }
  layout(width2, height, top2 = 0, left = 0) {
    super.layout(width2, height, top2, left);
    if (this.s) {
      this.s = false;
      this.a.trySet2x2();
    }
  }
};
function isGridBranchNodeDescriptor(nodeDescriptor) {
  return !!nodeDescriptor.groups;
}
function $z2(nodeDescriptor, rootNode) {
  if (!rootNode && nodeDescriptor.groups && nodeDescriptor.groups.length <= 1) {
    nodeDescriptor.groups = void 0;
  }
  if (!isGridBranchNodeDescriptor(nodeDescriptor)) {
    return;
  }
  let totalDefinedSize = 0;
  let totalDefinedSizeCount = 0;
  for (const child of nodeDescriptor.groups) {
    $z2(child, false);
    if (child.size) {
      totalDefinedSize += child.size;
      totalDefinedSizeCount++;
    }
  }
  const totalUndefinedSize = totalDefinedSizeCount > 0 ? totalDefinedSize : 1;
  const totalUndefinedSizeCount = nodeDescriptor.groups.length - totalDefinedSizeCount;
  const eachUndefinedSize = totalUndefinedSize / totalUndefinedSizeCount;
  for (const child of nodeDescriptor.groups) {
    if (!child.size) {
      child.size = eachUndefinedSize;
    }
  }
}
function createSerializedNode(nodeDescriptor) {
  if (isGridBranchNodeDescriptor(nodeDescriptor)) {
    return { type: "branch", data: nodeDescriptor.groups.map((c) => createSerializedNode(c)), size: nodeDescriptor.size };
  } else {
    return { type: "leaf", data: nodeDescriptor.data, size: nodeDescriptor.size };
  }
}
function getDimensions(node, orientation) {
  if (node.type === "branch") {
    const childrenDimensions = node.data.map((c) => getDimensions(c, $s2(orientation)));
    if (orientation === 0) {
      const width2 = node.size || (childrenDimensions.length === 0 ? void 0 : Math.max(...childrenDimensions.map((d) => d.width || 0)));
      const height = childrenDimensions.length === 0 ? void 0 : childrenDimensions.reduce((r2, d) => r2 + (d.height || 0), 0);
      return { width: width2, height };
    } else {
      const width2 = childrenDimensions.length === 0 ? void 0 : childrenDimensions.reduce((r2, d) => r2 + (d.width || 0), 0);
      const height = node.size || (childrenDimensions.length === 0 ? void 0 : Math.max(...childrenDimensions.map((d) => d.height || 0)));
      return { width: width2, height };
    }
  } else {
    const width2 = orientation === 0 ? node.size : void 0;
    const height = orientation === 0 ? void 0 : node.size;
    return { width: width2, height };
  }
}
function $A2(gridDescriptor) {
  $z2(gridDescriptor, true);
  const root = createSerializedNode(gridDescriptor);
  const { width: width2, height } = getDimensions(root, gridDescriptor.orientation);
  return {
    root,
    orientation: gridDescriptor.orientation,
    width: width2 || 1,
    height: height || 1
  };
}

// out-build/vs/workbench/browser/parts/editor/editorDropTarget.js
var DropOverlay_1;
function isDropIntoEditorEnabledGlobally(configurationService) {
  return configurationService.getValue("editor.dropIntoEditor.enabled");
}
function isDragIntoEditorEvent(e) {
  return e.shiftKey;
}
var DropOverlay = class DropOverlay2 extends $ns {
  static {
    DropOverlay_1 = this;
  }
  static {
    this.a = "monaco-workbench-editor-drop-overlay";
  }
  get disposed() {
    return !!this.j;
  }
  constructor(y, themeService, C, D, F, G, H, I) {
    super(themeService);
    this.y = y;
    this.C = C;
    this.D = D;
    this.F = F;
    this.G = G;
    this.H = H;
    this.I = I;
    this.r = $B_.getInstance();
    this.s = $B_.getInstance();
    this.t = $B_.getInstance();
    this.m = this.B(new $8h(() => this.dispose(), 300));
    this.u = isDropIntoEditorEnabledGlobally(this.C) && this.M();
    this.J();
  }
  J() {
    const overlayOffsetHeight = this.U();
    const container2 = this.b = document.createElement("div");
    container2.id = DropOverlay_1.a;
    container2.style.top = `${overlayOffsetHeight}px`;
    this.y.element.appendChild(container2);
    this.y.element.classList.add("dragged-over");
    this.B($1c(() => {
      container2.remove();
      this.y.element.classList.remove("dragged-over");
    }));
    this.c = document.createElement("div");
    this.c.classList.add("editor-group-overlay-indicator");
    container2.appendChild(this.c);
    if (this.u) {
      this.f = $RZ(localize(3488, null, $m ? "\u21E7" : "Shift"), {});
      this.f.classList.add("editor-group-overlay-drop-into-prompt");
      this.c.appendChild(this.f);
    }
    this.L(container2);
    this.updateStyles();
  }
  updateStyles() {
    const overlay = $Kg(this.c);
    overlay.style.backgroundColor = this.z($Cmb) || "";
    const activeContrastBorderColor = this.z($lo);
    overlay.style.outlineColor = activeContrastBorderColor || "";
    overlay.style.outlineOffset = activeContrastBorderColor ? "-2px" : "";
    overlay.style.outlineStyle = activeContrastBorderColor ? "dashed" : "";
    overlay.style.outlineWidth = activeContrastBorderColor ? "2px" : "";
    if (this.f) {
      this.f.style.backgroundColor = this.z($Emb) ?? "";
      this.f.style.color = this.z($Dmb) ?? "";
      const borderColor = this.z($Fmb);
      if (borderColor) {
        this.f.style.borderWidth = "1px";
        this.f.style.borderStyle = "solid";
        this.f.style.borderColor = borderColor;
      } else {
        this.f.style.borderWidth = "0";
      }
    }
  }
  L(container2) {
    this.B(new $Ak(container2, {
      onDragOver: (e) => {
        if (this.u && isDragIntoEditorEvent(e)) {
          this.dispose();
          return;
        }
        const isDraggingGroup = this.s.hasData($Bob.prototype);
        const isDraggingEditor = this.r.hasData($Aob.prototype);
        if (!isDraggingEditor && !isDraggingGroup && e.dataTransfer) {
          e.dataTransfer.dropEffect = "copy";
        }
        let isCopy = true;
        if (isDraggingGroup) {
          isCopy = this.P(e);
        } else if (isDraggingEditor) {
          const data = this.r.getData($Aob.prototype);
          if (Array.isArray(data) && data.length > 0) {
            isCopy = this.P(e, data[0].identifier);
          }
        }
        if (!isCopy) {
          const sourceGroupView = this.N();
          if (sourceGroupView === this.y) {
            if (isDraggingGroup || isDraggingEditor && sourceGroupView.count < 2) {
              this.W();
              return;
            }
          }
        }
        let splitOnDragAndDrop = !!this.G.partOptions.splitOnDragAndDrop;
        if (this.Q(e)) {
          splitOnDragAndDrop = !splitOnDragAndDrop;
        }
        this.R(e.offsetX, e.offsetY, isDraggingGroup, splitOnDragAndDrop);
        if (this.m.isScheduled()) {
          this.m.cancel();
        }
      },
      onDragLeave: (e) => this.dispose(),
      onDragEnd: (e) => this.dispose(),
      onDrop: (e) => {
        $9j.stop(e, true);
        this.dispose();
        if (this.g) {
          this.O(e, this.g.splitDirection);
        }
      }
    }));
    this.B($_i(container2, $7j.MOUSE_OVER, () => {
      if (!this.m.isScheduled()) {
        this.m.schedule();
      }
    }));
  }
  M() {
    return !!this.y.activeEditor?.hasCapability(
      128
      /* EditorInputCapabilities.CanDropIntoEditor */
    );
  }
  N() {
    if (this.s.hasData($Bob.prototype)) {
      const data = this.s.getData($Bob.prototype);
      if (Array.isArray(data) && data.length > 0) {
        return this.G.getGroup(data[0].identifier);
      }
    } else if (this.r.hasData($Aob.prototype)) {
      const data = this.r.getData($Aob.prototype);
      if (Array.isArray(data) && data.length > 0) {
        return this.G.getGroup(data[0].identifier.groupId);
      }
    }
    return void 0;
  }
  async O(event, splitDirection) {
    const ensureTargetGroup = () => {
      let targetGroup;
      if (typeof splitDirection === "number") {
        targetGroup = this.G.addGroup(this.y, splitDirection);
      } else {
        targetGroup = this.y;
      }
      return targetGroup;
    };
    if (this.s.hasData($Bob.prototype)) {
      const data = this.s.getData($Bob.prototype);
      if (Array.isArray(data) && data.length > 0) {
        const sourceGroup = this.G.getGroup(data[0].identifier);
        if (sourceGroup) {
          if (typeof splitDirection !== "number" && sourceGroup === this.y) {
            return;
          }
          let targetGroup;
          if (typeof splitDirection === "number") {
            if (this.P(event)) {
              targetGroup = this.G.copyGroup(sourceGroup, this.y, splitDirection);
            } else {
              targetGroup = this.G.moveGroup(sourceGroup, this.y, splitDirection);
            }
          } else {
            let mergeGroupOptions = void 0;
            if (this.P(event)) {
              mergeGroupOptions = {
                mode: 0
                /* MergeGroupMode.COPY_EDITORS */
              };
            }
            this.G.mergeGroup(sourceGroup, this.y, mergeGroupOptions);
          }
          if (targetGroup) {
            this.G.activateGroup(targetGroup);
          }
        }
        this.s.clearData($Bob.prototype);
      }
    } else if (this.r.hasData($Aob.prototype)) {
      const data = this.r.getData($Aob.prototype);
      if (Array.isArray(data) && data.length > 0) {
        const draggedEditors = data;
        const firstDraggedEditor = data[0].identifier;
        const sourceGroup = this.G.getGroup(firstDraggedEditor.groupId);
        if (sourceGroup) {
          const copyEditor = this.P(event, firstDraggedEditor);
          let targetGroup = void 0;
          if (this.G.partOptions.closeEmptyGroups && sourceGroup.count === 1 && typeof splitDirection === "number" && !copyEditor) {
            targetGroup = this.G.moveGroup(sourceGroup, this.y, splitDirection);
          } else {
            targetGroup = ensureTargetGroup();
            if (sourceGroup === targetGroup) {
              return;
            }
            const editors = draggedEditors.map((draggedEditor) => ({
              editor: draggedEditor.identifier.editor,
              options: $3ob(sourceGroup, draggedEditor.identifier.editor, {
                pinned: true,
                // always pin dropped editor
                sticky: sourceGroup.isSticky(draggedEditor.identifier.editor)
                // preserve sticky state
              })
            }));
            if (!copyEditor) {
              sourceGroup.moveEditors(editors, targetGroup);
            } else {
              sourceGroup.copyEditors(editors, targetGroup);
            }
          }
          targetGroup.focus();
        }
        this.r.clearData($Aob.prototype);
      }
    } else if (this.t.hasData($Tfb.prototype)) {
      const data = this.t.getData($Tfb.prototype);
      if (Array.isArray(data) && data.length > 0) {
        const editors = [];
        for (const id2 of data) {
          const dataTransferItem = await this.H.removeDragOperationTransfer(id2.identifier);
          if (dataTransferItem) {
            const treeDropData = await $Cob(dataTransferItem);
            editors.push(...treeDropData.map((editor) => ({ ...editor, options: { ...editor.options, pinned: true } })));
          }
        }
        if (editors.length) {
          this.F.openEditors(editors, ensureTargetGroup(), { validateTrust: true });
        }
      }
      this.t.clearData($Tfb.prototype);
    } else {
      const dropHandler = this.D.createInstance($Dob, { allowWorkspaceOpen: !$r || $fl(this.I.getWorkspace()) });
      dropHandler.handleDrop(event, getWindow(this.y.element), () => ensureTargetGroup(), (targetGroup) => targetGroup?.focus());
    }
  }
  P(e, draggedEditor) {
    if (draggedEditor?.editor.hasCapability(
      8
      /* EditorInputCapabilities.Singleton */
    )) {
      return false;
    }
    return e.ctrlKey && !$m || e.altKey && $m;
  }
  Q(e) {
    return e.altKey && !$m || e.shiftKey && $m;
  }
  R(mousePosX, mousePosY, isDraggingGroup, enableSplitting) {
    const preferSplitVertically = this.G.partOptions.openSideBySideDirection === "right";
    const editorControlWidth = this.y.element.clientWidth;
    const editorControlHeight = this.y.element.clientHeight - this.U();
    let edgeWidthThresholdFactor;
    let edgeHeightThresholdFactor;
    if (enableSplitting) {
      if (isDraggingGroup) {
        edgeWidthThresholdFactor = preferSplitVertically ? 0.3 : 0.1;
      } else {
        edgeWidthThresholdFactor = 0.1;
      }
      if (isDraggingGroup) {
        edgeHeightThresholdFactor = preferSplitVertically ? 0.1 : 0.3;
      } else {
        edgeHeightThresholdFactor = 0.1;
      }
    } else {
      edgeWidthThresholdFactor = 0;
      edgeHeightThresholdFactor = 0;
    }
    const edgeWidthThreshold = editorControlWidth * edgeWidthThresholdFactor;
    const edgeHeightThreshold = editorControlHeight * edgeHeightThresholdFactor;
    const splitWidthThreshold = editorControlWidth / 3;
    const splitHeightThreshold = editorControlHeight / 3;
    let splitDirection;
    if (mousePosX > edgeWidthThreshold && mousePosX < editorControlWidth - edgeWidthThreshold && mousePosY > edgeHeightThreshold && mousePosY < editorControlHeight - edgeHeightThreshold) {
      splitDirection = void 0;
    } else {
      if (preferSplitVertically) {
        if (mousePosX < splitWidthThreshold) {
          splitDirection = 2;
        } else if (mousePosX > splitWidthThreshold * 2) {
          splitDirection = 3;
        } else if (mousePosY < editorControlHeight / 2) {
          splitDirection = 0;
        } else {
          splitDirection = 1;
        }
      } else {
        if (mousePosY < splitHeightThreshold) {
          splitDirection = 0;
        } else if (mousePosY > splitHeightThreshold * 2) {
          splitDirection = 1;
        } else if (mousePosX < editorControlWidth / 2) {
          splitDirection = 2;
        } else {
          splitDirection = 3;
        }
      }
    }
    switch (splitDirection) {
      case 0:
        this.S({ top: "0", left: "0", width: "100%", height: "50%" });
        this.X(false);
        break;
      case 1:
        this.S({ top: "50%", left: "0", width: "100%", height: "50%" });
        this.X(false);
        break;
      case 2:
        this.S({ top: "0", left: "0", width: "50%", height: "100%" });
        this.X(false);
        break;
      case 3:
        this.S({ top: "0", left: "50%", width: "50%", height: "100%" });
        this.X(false);
        break;
      default:
        this.S({ top: "0", left: "0", width: "100%", height: "100%" });
        this.X(true);
    }
    const overlay = $Kg(this.c);
    overlay.style.opacity = "1";
    setTimeout(() => overlay.classList.add("overlay-move-transition"), 0);
    this.g = { splitDirection };
  }
  S(options3) {
    const [container2, overlay] = $Lg(this.b, this.c);
    const offsetHeight = this.U();
    if (offsetHeight) {
      container2.style.height = `calc(100% - ${offsetHeight}px)`;
    } else {
      container2.style.height = "100%";
    }
    overlay.style.top = options3.top;
    overlay.style.left = options3.left;
    overlay.style.width = options3.width;
    overlay.style.height = options3.height;
  }
  U() {
    if (!this.y.isEmpty && this.G.partOptions.showTabs === "multiple") {
      return this.y.titleHeight.offset;
    }
    return 0;
  }
  W() {
    const overlay = $Kg(this.c);
    this.S({ top: "0", left: "0", width: "100%", height: "100%" });
    overlay.style.opacity = "0";
    overlay.classList.remove("overlay-move-transition");
    this.g = void 0;
  }
  X(showing) {
    if (!this.f) {
      return;
    }
    this.f.style.opacity = showing ? "1" : "0";
  }
  contains(element) {
    return element === this.b || element === this.c;
  }
  dispose() {
    super.dispose();
    this.j = true;
  }
};
DropOverlay = DropOverlay_1 = __decorate([
  __param(1, $gs),
  __param(2, $kl),
  __param(3, $Pk),
  __param(4, $mJ),
  __param(5, $iJ),
  __param(6, $Ufb),
  __param(7, $Zk)
], DropOverlay);
var $4Ub = class $4Ub2 extends $ns {
  constructor(g, j, m, themeService, r2, s) {
    super(themeService);
    this.g = g;
    this.j = j;
    this.m = m;
    this.r = r2;
    this.s = s;
    this.b = 0;
    this.c = $B_.getInstance();
    this.f = $B_.getInstance();
    this.u();
  }
  get t() {
    if (this.a && !this.a.disposed) {
      return this.a;
    }
    return void 0;
  }
  u() {
    this.B($_i(this.g, $7j.DRAG_ENTER, (e) => this.y(e)));
    this.B($_i(this.g, $7j.DRAG_LEAVE, () => this.C()));
    for (const target of [this.g, getWindow(this.g)]) {
      this.B($_i(target, $7j.DRAG_END, () => this.D()));
    }
  }
  y(event) {
    if (isDropIntoEditorEnabledGlobally(this.r) && isDragIntoEditorEvent(event)) {
      return;
    }
    this.b++;
    if (!this.c.hasData($Aob.prototype) && !this.f.hasData($Bob.prototype) && event.dataTransfer) {
      const dndContributions = $Wn.as($A_.DragAndDropContribution).getAll();
      const dndContributionKeys = Array.from(dndContributions).map((e) => e.dataFormatKey);
      if (!$z_(event, $kZ.FILES, $u_.FILES, $kZ.RESOURCES, $u_.EDITORS, ...dndContributionKeys)) {
        event.dataTransfer.dropEffect = "none";
        return;
      }
    }
    this.G(true);
    const target = event.target;
    if (target) {
      if (this.t && !this.t.contains(target)) {
        this.H();
      }
      if (!this.t) {
        const targetGroupView = this.F(target);
        if (targetGroupView) {
          this.a = this.s.createInstance(DropOverlay, targetGroupView);
        }
      }
    }
  }
  C() {
    this.b--;
    if (this.b === 0) {
      this.G(false);
    }
  }
  D() {
    this.b = 0;
    this.G(false);
    this.H();
  }
  F(child) {
    const groups = this.m.groups;
    return groups.find((groupView) => $Dj(child, groupView.element) || this.j.containsGroup?.(groupView));
  }
  G(isDraggedOver) {
    this.g.classList.toggle("dragged-over", isDraggedOver);
  }
  dispose() {
    super.dispose();
    this.H();
  }
  H() {
    if (this.t) {
      this.t.dispose();
      this.a = void 0;
    }
  }
};
$4Ub = __decorate([
  __param(2, $iJ),
  __param(3, $gs),
  __param(4, $kl),
  __param(5, $Pk)
], $4Ub);

// out-build/vs/base/browser/ui/centered/centeredViewLayout.js
var defaultState = {
  targetWidth: 900,
  leftMarginRatio: 0.1909,
  rightMarginRatio: 0.1909
};
var distributeSizing = { type: "distribute" };
function createEmptyView(background) {
  const element = $(".centered-layout-margin");
  element.style.height = "100%";
  if (background) {
    element.style.backgroundColor = background.toString();
  }
  return {
    element,
    layout: () => void 0,
    minimumSize: 60,
    maximumSize: Number.POSITIVE_INFINITY,
    onDidChange: Event2.None
  };
}
function toSplitViewView(view, getHeight) {
  return {
    element: view.element,
    get maximumSize() {
      return view.maximumWidth;
    },
    get minimumSize() {
      return view.minimumWidth;
    },
    onDidChange: Event2.map(view.onDidChange, (e) => e && e.width),
    layout: (size, offset, ctx) => view.layout(size, getHeight(), ctx?.top ?? 0, (ctx?.left ?? 0) + offset)
  };
}
var $B2 = class {
  constructor(h3, i2, state = { ...defaultState }, j = false) {
    this.h = h3;
    this.i = i2;
    this.state = state;
    this.j = j;
    this.b = { width: 0, height: 0, left: 0, top: 0 };
    this.d = false;
    this.g = new $2c();
    this.k = {};
    this.h.appendChild(this.i.element);
    this.h.style.overflow = "hidden";
  }
  get minimumWidth() {
    return this.a ? this.a.minimumSize : this.i.minimumWidth;
  }
  get maximumWidth() {
    return this.a ? this.a.maximumSize : this.i.maximumWidth;
  }
  get minimumHeight() {
    return this.i.minimumHeight;
  }
  get maximumHeight() {
    return this.i.maximumHeight;
  }
  get onDidChange() {
    return this.i.onDidChange;
  }
  get boundarySashes() {
    return this.k;
  }
  set boundarySashes(boundarySashes) {
    this.k = boundarySashes;
    if (!this.a) {
      return;
    }
    this.a.orthogonalStartSash = boundarySashes.top;
    this.a.orthogonalEndSash = boundarySashes.bottom;
  }
  layout(width2, height, top2, left) {
    this.b = { width: width2, height, top: top2, left };
    if (this.a) {
      this.a.layout(width2, this.b);
      if (!this.d || this.j) {
        this.l();
      }
    } else {
      this.i.layout(width2, height, top2, left);
    }
    this.d = true;
  }
  l() {
    if (!this.a) {
      return;
    }
    if (this.j) {
      const centerViewWidth = Math.min(this.b.width, this.state.targetWidth);
      const marginWidthFloat = (this.b.width - centerViewWidth) / 2;
      this.a.resizeView(0, Math.floor(marginWidthFloat));
      this.a.resizeView(1, centerViewWidth);
      this.a.resizeView(2, Math.ceil(marginWidthFloat));
    } else {
      const leftMargin = this.state.leftMarginRatio * this.b.width;
      const rightMargin = this.state.rightMarginRatio * this.b.width;
      const center = this.b.width - leftMargin - rightMargin;
      this.a.resizeView(0, leftMargin);
      this.a.resizeView(1, center);
      this.a.resizeView(2, rightMargin);
    }
  }
  setFixedWidth(option) {
    this.j = option;
    if (!!this.a) {
      this.m();
      this.l();
    }
  }
  m() {
    if (!!this.a) {
      this.state.targetWidth = this.a.getViewSize(1);
      this.state.leftMarginRatio = this.a.getViewSize(0) / this.b.width;
      this.state.rightMarginRatio = this.a.getViewSize(2) / this.b.width;
    }
  }
  isActive() {
    return !!this.a;
  }
  styles(style) {
    this.c = style;
    if (this.a && this.f) {
      this.a.style(this.c);
      this.f[0].element.style.backgroundColor = this.c.background.toString();
      this.f[1].element.style.backgroundColor = this.c.background.toString();
    }
  }
  activate(active) {
    if (active === this.isActive()) {
      return;
    }
    if (active) {
      this.i.element.remove();
      this.a = new $r2(this.h, {
        inverseAltBehavior: true,
        orientation: 1,
        styles: this.c
      });
      this.a.orthogonalStartSash = this.boundarySashes.top;
      this.a.orthogonalEndSash = this.boundarySashes.bottom;
      this.g.add(this.a.onDidSashChange(() => {
        if (!!this.a) {
          this.m();
        }
      }));
      this.g.add(this.a.onDidSashReset(() => {
        this.state = { ...defaultState };
        this.l();
      }));
      this.a.layout(this.b.width, this.b);
      const backgroundColor = this.c ? this.c.background : void 0;
      this.f = [createEmptyView(backgroundColor), createEmptyView(backgroundColor)];
      this.a.addView(this.f[0], distributeSizing, 0);
      this.a.addView(toSplitViewView(this.i, () => this.b.height), distributeSizing, 1);
      this.a.addView(this.f[1], distributeSizing, 2);
      this.l();
    } else {
      this.a?.el.remove();
      this.g.clear();
      this.a?.dispose();
      this.a = void 0;
      this.f = void 0;
      this.h.appendChild(this.i.element);
      this.i.layout(this.b.width, this.b.height, this.b.top, this.b.left);
    }
  }
  isDefault(state) {
    if (this.j) {
      return state.targetWidth === defaultState.targetWidth;
    } else {
      return state.leftMarginRatio === defaultState.leftMarginRatio && state.rightMarginRatio === defaultState.rightMarginRatio;
    }
  }
  dispose() {
    this.g.dispose();
    if (this.a) {
      this.a.dispose();
      this.a = void 0;
    }
  }
};

// out-build/vs/workbench/services/editor/common/editorGroupFinder.js
function $5Ub(accessor, editor, preferredGroup) {
  const editorGroupService = accessor.get($iJ);
  const configurationService = accessor.get($kl);
  const group2 = doFindGroup(editor, preferredGroup, editorGroupService, configurationService);
  if (group2 instanceof Promise) {
    return group2.then((group3) => handleGroupActivation(group3, editor, preferredGroup, editorGroupService));
  }
  return handleGroupActivation(group2, editor, preferredGroup, editorGroupService);
}
function handleGroupActivation(group2, editor, preferredGroup, editorGroupService) {
  let activation = void 0;
  if (editorGroupService.activeGroup !== group2 && // only if target group is not already active
  editor.options && !editor.options.inactive && // never for inactive editors
  editor.options.preserveFocus && // only if preserveFocus
  typeof editor.options.activation !== "number" && // only if activation is not already defined (either true or false)
  preferredGroup !== $oJ) {
    activation = EditorActivation.ACTIVATE;
  }
  return [group2, activation];
}
function doFindGroup(input, preferredGroup, editorGroupService, configurationService) {
  let group2;
  const editor = $hL(input) ? input.editor : input;
  const options3 = input.options;
  if (preferredGroup && typeof preferredGroup !== "number") {
    group2 = preferredGroup;
  } else if (typeof preferredGroup === "number" && preferredGroup >= 0) {
    group2 = editorGroupService.getGroup(preferredGroup);
  } else if (preferredGroup === $oJ) {
    const direction = $lJ(configurationService);
    let candidateGroup = editorGroupService.findGroup({ direction });
    if (!candidateGroup || isGroupLockedForEditor(candidateGroup, editor)) {
      candidateGroup = editorGroupService.addGroup(editorGroupService.activeGroup, direction);
    }
    group2 = candidateGroup;
  } else if (preferredGroup === $pJ) {
    group2 = editorGroupService.createAuxiliaryEditorPart().then((group3) => group3.activeGroup);
  } else if (!options3 || typeof options3.index !== "number") {
    const groupsByLastActive = editorGroupService.getGroups(
      1
      /* GroupsOrder.MOST_RECENTLY_ACTIVE */
    );
    if (options3?.revealIfVisible) {
      for (const lastActiveGroup of groupsByLastActive) {
        if (isActive(lastActiveGroup, editor)) {
          group2 = lastActiveGroup;
          break;
        }
      }
    }
    if (!group2) {
      if (options3?.revealIfOpened || configurationService.getValue("workbench.editor.revealIfOpen") || $dL(editor) && editor.hasCapability(
        8
        /* EditorInputCapabilities.Singleton */
      )) {
        let groupWithInputActive = void 0;
        let groupWithInputOpened = void 0;
        for (const group3 of groupsByLastActive) {
          if (isOpened(group3, editor)) {
            if (!groupWithInputOpened) {
              groupWithInputOpened = group3;
            }
            if (!groupWithInputActive && group3.isActive(editor)) {
              groupWithInputActive = group3;
            }
          }
          if (groupWithInputOpened && groupWithInputActive) {
            break;
          }
        }
        group2 = groupWithInputActive || groupWithInputOpened;
      }
    }
  }
  if (!group2) {
    let candidateGroup = editorGroupService.activeGroup;
    if (isGroupLockedForEditor(candidateGroup, editor)) {
      for (const group3 of editorGroupService.getGroups(
        1
        /* GroupsOrder.MOST_RECENTLY_ACTIVE */
      )) {
        if (isGroupLockedForEditor(group3, editor)) {
          continue;
        }
        candidateGroup = group3;
        break;
      }
      if (isGroupLockedForEditor(candidateGroup, editor)) {
        group2 = editorGroupService.addGroup(candidateGroup, $lJ(configurationService));
      } else {
        group2 = candidateGroup;
      }
    } else {
      group2 = candidateGroup;
    }
  }
  return group2;
}
function isGroupLockedForEditor(group2, editor) {
  if (!group2.isLocked) {
    return false;
  }
  if (isOpened(group2, editor)) {
    return false;
  }
  return true;
}
function isActive(group2, editor) {
  if (!group2.activeEditor) {
    return false;
  }
  return group2.activeEditor.matches(editor);
}
function isOpened(group2, editor) {
  for (const typedEditor of group2.editors) {
    if (typedEditor.matches(editor)) {
      return true;
    }
  }
  return false;
}

// out-build/vs/workbench/browser/parts/editor/editorPart.js
var $6Ub_1;
var GridWidgetView = class {
  constructor() {
    this.element = $(".grid-view-container");
    this.a = new $Ie();
    this.onDidChange = this.a.event;
  }
  get minimumWidth() {
    return this.gridWidget ? this.gridWidget.minimumWidth : 0;
  }
  get maximumWidth() {
    return this.gridWidget ? this.gridWidget.maximumWidth : Number.POSITIVE_INFINITY;
  }
  get minimumHeight() {
    return this.gridWidget ? this.gridWidget.minimumHeight : 0;
  }
  get maximumHeight() {
    return this.gridWidget ? this.gridWidget.maximumHeight : Number.POSITIVE_INFINITY;
  }
  get gridWidget() {
    return this.b;
  }
  set gridWidget(grid) {
    this.element.innerText = "";
    if (grid) {
      this.element.appendChild(grid.element);
      this.a.input = grid.onDidChange;
    } else {
      this.a.input = Event2.None;
    }
    this.b = grid;
  }
  layout(width2, height, top2, left) {
    this.gridWidget?.layout(width2, height, top2, left);
  }
  dispose() {
    this.a.dispose();
  }
};
var $6Ub = class $6Ub2 extends Part {
  static {
    $6Ub_1 = this;
  }
  static {
    this.a = "editorpart.state";
  }
  static {
    this.b = "editorpart.centeredview";
  }
  constructor(Ab, id2, Bb, windowId, Cb, themeService, Db, storageService, layoutService, Eb, Fb) {
    super(id2, { hasTitle: false }, themeService, storageService, layoutService);
    this.Ab = Ab;
    this.Bb = Bb;
    this.windowId = windowId;
    this.Cb = Cb;
    this.Db = Db;
    this.Eb = Eb;
    this.Fb = Fb;
    this.y = this.B(new $ze());
    this.onDidFocus = this.y.event;
    this.bb = this.B(new $ze());
    this.onDidLayout = this.bb.event;
    this.cb = this.B(new $ze());
    this.onDidChangeActiveGroup = this.cb.event;
    this.db = this.B(new $ze());
    this.onDidChangeGroupIndex = this.db.event;
    this.eb = this.B(new $ze());
    this.onDidChangeGroupLabel = this.eb.event;
    this.fb = this.B(new $ze());
    this.onDidChangeGroupLocked = this.fb.event;
    this.gb = this.B(new $ze());
    this.onDidChangeGroupMaximized = this.gb.event;
    this.hb = this.B(new $ze());
    this.onDidActivateGroup = this.hb.event;
    this.ib = this.B(new $Ce());
    this.onDidAddGroup = this.ib.event;
    this.jb = this.B(new $Ce());
    this.onDidRemoveGroup = this.jb.event;
    this.kb = this.B(new $ze());
    this.onDidMoveGroup = this.kb.event;
    this.lb = this.B(new $ze());
    this.mb = this.B(new $Ie());
    this.onDidChangeSizeConstraints = Event2.any(this.lb.event, this.mb.event);
    this.nb = this.B(new $Ie());
    this.onDidScroll = Event2.any(this.lb.event, this.nb.event);
    this.ob = this.B(new $ze());
    this.onDidChangeEditorPartOptions = this.ob.event;
    this.pb = this.B(new $ze());
    this.onWillDispose = this.pb.event;
    this.qb = this.F(
      1,
      0
      /* StorageTarget.USER */
    );
    this.rb = this.F(
      0,
      1
      /* StorageTarget.MACHINE */
    );
    this.sb = /* @__PURE__ */ new Map();
    this.tb = [];
    this.yb = this.B(new $2c());
    this.zb = this.B(new GridWidgetView());
    this.Jb = [];
    this.Kb = $2ob(this.Db, this.n);
    this.Lb = 0;
    this.Mb = 0;
    this.sideGroup = {
      openEditor: (editor, options3) => {
        const [group2] = this.vb.invokeFunction((accessor) => $5Ub(accessor, { editor, options: options3 }, $oJ));
        return group2.openEditor(editor, options3);
      }
    };
    this.Pb = false;
    this.Qb = new $gi();
    this.whenReady = this.Qb.p;
    this.Rb = new $gi();
    this.whenRestored = this.Rb.p;
    this.Sb = false;
    this.priority = 2;
    this.Gb();
  }
  Gb() {
    this.B(this.Db.onDidChangeConfiguration((e) => this.Hb(e)));
    this.B(this.n.onDidFileIconThemeChange(() => this.Ib()));
    this.B(this.H(1, this.q)((e) => this.Cc(e)));
  }
  Hb(event) {
    if ($1ob(event)) {
      this.Ib();
    }
  }
  Ib() {
    const oldPartOptions = this.Kb;
    const newPartOptions = $2ob(this.Db, this.n);
    for (const enforcedPartOptions of this.Jb) {
      Object.assign(newPartOptions, enforcedPartOptions);
    }
    this.Kb = newPartOptions;
    this.ob.fire({ oldPartOptions, newPartOptions });
  }
  get partOptions() {
    return this.Kb;
  }
  enforcePartOptions(options3) {
    this.Jb.push(options3);
    this.Ib();
    return $1c(() => {
      this.Jb.splice(this.Jb.indexOf(options3), 1);
      this.Ib();
    });
  }
  get contentDimension() {
    return this.Nb;
  }
  get activeGroup() {
    return this.Ob;
  }
  get groups() {
    return Array.from(this.sb.values());
  }
  get count() {
    return this.sb.size;
  }
  get orientation() {
    return this.xb && this.xb.orientation === 0 ? 1 : 0;
  }
  get isReady() {
    return this.Pb;
  }
  get hasRestorableState() {
    return !!this.qb[$6Ub_1.a];
  }
  get willRestoreState() {
    return this.Sb;
  }
  getGroups(order = 0) {
    switch (order) {
      case 0:
        return this.groups;
      case 1: {
        const mostRecentActive = $Mb(this.tb.map((groupId) => this.getGroup(groupId)));
        return $Rb([...mostRecentActive, ...this.groups]);
      }
      case 2: {
        const views = [];
        if (this.xb) {
          this.Tb(views, this.xb.getViews());
        }
        return views;
      }
    }
  }
  Tb(target, node) {
    if ($v2(node)) {
      node.children.forEach((child) => this.Tb(target, child));
    } else {
      target.push(node.view);
    }
  }
  hasGroup(identifier2) {
    return this.sb.has(identifier2);
  }
  getGroup(identifier2) {
    return this.sb.get(identifier2);
  }
  findGroup(scope, source = this.activeGroup, wrap) {
    if (typeof scope.direction === "number") {
      return this.Ub(scope.direction, source, wrap);
    }
    if (typeof scope.location === "number") {
      return this.Vb(scope.location, source, wrap);
    }
    throw new Error("invalid arguments");
  }
  Ub(direction, source, wrap) {
    const sourceGroupView = this.jc(source);
    const neighbours = this.xb.getNeighborViews(sourceGroupView, this.fc(direction), wrap);
    neighbours.sort((n1, n2) => this.tb.indexOf(n1.id) - this.tb.indexOf(n2.id));
    return neighbours[0];
  }
  Vb(location3, source, wrap) {
    const sourceGroupView = this.jc(source);
    const groups = this.getGroups(
      2
      /* GroupsOrder.GRID_APPEARANCE */
    );
    const index = groups.indexOf(sourceGroupView);
    switch (location3) {
      case 0:
        return groups[0];
      case 1:
        return groups[groups.length - 1];
      case 2: {
        let nextGroup = groups[index + 1];
        if (!nextGroup && wrap) {
          nextGroup = this.Vb(0, source);
        }
        return nextGroup;
      }
      case 3: {
        let previousGroup = groups[index - 1];
        if (!previousGroup && wrap) {
          previousGroup = this.Vb(1, source);
        }
        return previousGroup;
      }
    }
  }
  activateGroup(group2, preserveWindowOrder) {
    const groupView = this.jc(group2);
    this.cc(groupView);
    if (!preserveWindowOrder) {
      this.Eb.moveTop(getWindow(this.element));
    }
    return groupView;
  }
  restoreGroup(group2) {
    const groupView = this.jc(group2);
    this.dc(groupView);
    return groupView;
  }
  getSize(group2) {
    const groupView = this.jc(group2);
    return this.xb.getViewSize(groupView);
  }
  setSize(group2, size) {
    const groupView = this.jc(group2);
    this.xb.resizeView(groupView, size);
  }
  arrangeGroups(arrangement, target = this.activeGroup) {
    if (this.count < 2) {
      return;
    }
    if (!this.xb) {
      return;
    }
    const groupView = this.jc(target);
    switch (arrangement) {
      case 2:
        this.xb.distributeViewSizes();
        break;
      case 0:
        if (this.groups.length < 2) {
          return;
        }
        this.xb.maximizeView(groupView);
        groupView.focus();
        break;
      case 1:
        this.xb.expandView(groupView);
        break;
    }
  }
  toggleMaximizeGroup(target = this.activeGroup) {
    if (this.hasMaximizedGroup()) {
      this.Wb();
    } else {
      this.arrangeGroups(0, target);
    }
  }
  toggleExpandGroup(target = this.activeGroup) {
    if (this.isGroupExpanded(this.activeGroup)) {
      this.arrangeGroups(
        2
        /* GroupsArrangement.EVEN */
      );
    } else {
      this.arrangeGroups(1, target);
    }
  }
  Wb() {
    this.xb.exitMaximizedView();
    this.Ob.focus();
  }
  hasMaximizedGroup() {
    return this.xb.hasMaximizedView();
  }
  Xb(targetGroup) {
    return this.xb.isViewMaximized(targetGroup);
  }
  isGroupExpanded(targetGroup) {
    return this.xb.isViewExpanded(targetGroup);
  }
  setGroupOrientation(orientation) {
    if (!this.xb) {
      return;
    }
    const newOrientation = orientation === 0 ? 1 : 0;
    if (this.xb.orientation !== newOrientation) {
      this.xb.orientation = newOrientation;
    }
  }
  applyLayout(layout) {
    const restoreFocus = this.Zb(this.ub);
    let layoutGroupsCount = 0;
    function countGroups(groups) {
      for (const group2 of groups) {
        if (Array.isArray(group2.groups)) {
          countGroups(group2.groups);
        } else {
          layoutGroupsCount++;
        }
      }
    }
    countGroups(layout.groups);
    let currentGroupViews = this.getGroups(
      2
      /* GroupsOrder.GRID_APPEARANCE */
    );
    if (layoutGroupsCount < currentGroupViews.length) {
      const lastGroupInLayout = currentGroupViews[layoutGroupsCount - 1];
      currentGroupViews.forEach((group2, index) => {
        if (index >= layoutGroupsCount) {
          this.mergeGroup(group2, lastGroupInLayout);
        }
      });
      currentGroupViews = this.getGroups(
        2
        /* GroupsOrder.GRID_APPEARANCE */
      );
    }
    const activeGroup = this.activeGroup;
    const gridDescriptor = $A2({
      orientation: this.gc(
        layout.orientation,
        this.$b() ? this.xb.orientation : (
          // preserve original orientation for 2-dimensional grids
          $s2(this.xb.orientation)
        )
        // otherwise flip (fix https://github.com/microsoft/vscode/issues/52975)
      ),
      groups: layout.groups
    });
    this.Bc(gridDescriptor, activeGroup.id, currentGroupViews);
    if (restoreFocus) {
      this.Ob.focus();
    }
  }
  getLayout() {
    const serializedGrid = this.xb.serialize();
    const orientation = serializedGrid.orientation === 1 ? 0 : 1;
    const root = this.Yb(serializedGrid.root);
    return {
      orientation,
      groups: root.groups
    };
  }
  Yb(serializedNode) {
    if (serializedNode.type === "branch") {
      return {
        size: serializedNode.size,
        groups: serializedNode.data.map((node) => this.Yb(node))
      };
    }
    return { size: serializedNode.size };
  }
  Zb(target) {
    if (!target) {
      return false;
    }
    const activeElement = $Lj();
    if (activeElement === target.ownerDocument.body) {
      return true;
    }
    return $Nj(target);
  }
  $b() {
    const views = this.xb.getViews();
    if ($v2(views)) {
      return views.children.some((child) => $v2(child));
    }
    return false;
  }
  addGroup(location3, direction, groupToCopy) {
    const locationView = this.jc(location3);
    let newGroupView;
    if (locationView.groupsView === this) {
      const restoreFocus = this.Zb(locationView.element);
      const shouldExpand = this.sb.size > 1 && this.isGroupExpanded(locationView);
      newGroupView = this.bc(groupToCopy);
      this.xb.addView(newGroupView, this.ac(), locationView, this.fc(direction));
      this.sc();
      this.ib.fire(newGroupView);
      this.tc();
      if (shouldExpand) {
        this.arrangeGroups(1, newGroupView);
      }
      if (restoreFocus) {
        locationView.focus();
      }
    } else {
      newGroupView = locationView.groupsView.addGroup(locationView, direction, groupToCopy);
    }
    return newGroupView;
  }
  ac() {
    switch (this.Kb.splitSizing) {
      case "distribute":
        return Sizing2.Distribute;
      case "split":
        return Sizing2.Split;
      default:
        return Sizing2.Auto;
    }
  }
  bc(from, options3) {
    let groupView;
    if (from instanceof $Ryb) {
      groupView = $Ryb.createCopy(from, this.Ab, this, this.Bb, this.count, this.vb, options3);
    } else if ($4I(from)) {
      groupView = $Ryb.createFromSerialized(from, this.Ab, this, this.Bb, this.count, this.vb, options3);
    } else {
      groupView = $Ryb.createNew(this.Ab, this, this.Bb, this.count, this.vb, options3);
    }
    this.sb.set(groupView.id, groupView);
    const groupDisposables = new $2c();
    groupDisposables.add(groupView.onDidFocus(() => {
      this.cc(groupView);
      this.y.fire();
    }));
    groupDisposables.add(groupView.onDidModelChange((e) => {
      switch (e.kind) {
        case 3:
          this.fb.fire(groupView);
          break;
        case 1:
          this.db.fire(groupView);
          break;
        case 2:
          this.eb.fire(groupView);
          break;
      }
    }));
    groupDisposables.add(groupView.onDidActiveEditorChange(() => {
      this.sc();
    }));
    Event2.once(groupView.onWillDispose)(() => {
      $Xc(groupDisposables);
      this.sb.delete(groupView.id);
      this.ec(groupView);
    });
    return groupView;
  }
  cc(group2) {
    if (this.Ob !== group2) {
      const previousActiveGroup = this.Ob;
      this.Ob = group2;
      this.ec(group2, true);
      if (previousActiveGroup && !previousActiveGroup.disposed) {
        previousActiveGroup.setActive(false);
      }
      group2.setActive(true);
      this.dc(group2);
      this.cb.fire(group2);
    }
    this.hb.fire(group2);
  }
  dc(group2) {
    if (!this.xb) {
      return;
    }
    if (this.hasMaximizedGroup() && !this.Xb(group2)) {
      this.Wb();
    }
    try {
      const viewSize = this.xb.getViewSize(group2);
      if (viewSize.width === group2.minimumWidth || viewSize.height === group2.minimumHeight) {
        this.arrangeGroups(1, group2);
      }
    } catch (error) {
    }
  }
  ec(group2, makeMostRecentlyActive) {
    const index = this.tb.indexOf(group2.id);
    if (index !== -1) {
      this.tb.splice(index, 1);
    }
    if (makeMostRecentlyActive) {
      this.tb.unshift(group2.id);
    }
  }
  fc(direction) {
    switch (direction) {
      case 0:
        return 0;
      case 1:
        return 1;
      case 2:
        return 2;
      case 3:
        return 3;
    }
  }
  gc(orientation, fallback2) {
    if (typeof orientation === "number") {
      return orientation === 0 ? 1 : 0;
    }
    return fallback2;
  }
  removeGroup(group2, preserveFocus) {
    const groupView = this.jc(group2);
    if (this.count === 1) {
      return;
    }
    if (groupView.isEmpty) {
      this.ic(groupView, preserveFocus);
    } else {
      this.hc(groupView);
    }
  }
  hc(groupView) {
    const mostRecentlyActiveGroups = this.getGroups(
      1
      /* GroupsOrder.MOST_RECENTLY_ACTIVE */
    );
    let lastActiveGroup;
    if (this.Ob === groupView) {
      lastActiveGroup = mostRecentlyActiveGroups[1];
    } else {
      lastActiveGroup = mostRecentlyActiveGroups[0];
    }
    this.mergeGroup(groupView, lastActiveGroup);
  }
  ic(groupView, preserveFocus) {
    const restoreFocus = !preserveFocus && this.Zb(this.ub);
    if (this.Ob === groupView) {
      const mostRecentlyActiveGroups = this.getGroups(
        1
        /* GroupsOrder.MOST_RECENTLY_ACTIVE */
      );
      const nextActiveGroup = mostRecentlyActiveGroups[1];
      this.cc(nextActiveGroup);
    }
    this.xb.removeView(groupView, this.ac());
    groupView.dispose();
    if (restoreFocus) {
      this.Ob.focus();
    }
    this.tc();
    this.sc();
    this.jb.fire(groupView);
  }
  moveGroup(group2, location3, direction) {
    const sourceView = this.jc(group2);
    const targetView = this.jc(location3);
    if (sourceView.id === targetView.id) {
      throw new Error("Cannot move group into its own");
    }
    const restoreFocus = this.Zb(sourceView.element);
    let movedView;
    if (sourceView.groupsView === targetView.groupsView) {
      this.xb.moveView(sourceView, this.ac(), targetView, this.fc(direction));
      movedView = sourceView;
    } else {
      movedView = targetView.groupsView.addGroup(targetView, direction, sourceView);
      sourceView.closeAllEditors();
      this.removeGroup(sourceView, restoreFocus);
    }
    if (restoreFocus) {
      movedView.focus();
    }
    this.kb.fire(movedView);
    this.tc();
    return movedView;
  }
  copyGroup(group2, location3, direction) {
    const groupView = this.jc(group2);
    const locationView = this.jc(location3);
    const restoreFocus = this.Zb(groupView.element);
    const copiedGroupView = this.addGroup(locationView, direction, groupView);
    if (restoreFocus) {
      copiedGroupView.focus();
    }
    return copiedGroupView;
  }
  mergeGroup(group2, target, options3) {
    const sourceView = this.jc(group2);
    const targetView = this.jc(target);
    const editors = [];
    let index = options3 && typeof options3.index === "number" ? options3.index : targetView.count;
    for (const editor of sourceView.editors) {
      const inactive = !sourceView.isActive(editor) || this.Ob !== sourceView;
      const sticky = sourceView.isSticky(editor);
      const options4 = { index: !sticky ? index : void 0, inactive, preserveFocus: inactive };
      editors.push({ editor, options: options4 });
      index++;
    }
    let result = true;
    if (options3?.mode === 0) {
      sourceView.copyEditors(editors, targetView);
    } else {
      result = sourceView.moveEditors(editors, targetView);
    }
    if (sourceView.isEmpty && !sourceView.disposed) {
      this.removeGroup(sourceView, true);
    }
    return result;
  }
  mergeAllGroups(target) {
    const targetView = this.jc(target);
    let result = true;
    for (const group2 of this.getGroups(
      1
      /* GroupsOrder.MOST_RECENTLY_ACTIVE */
    )) {
      if (group2 === targetView) {
        continue;
      }
      const merged = this.mergeGroup(group2, targetView);
      if (!merged) {
        result = false;
      }
    }
    return result;
  }
  jc(group2) {
    let groupView;
    if (typeof group2 === "number") {
      groupView = this.Ab.getGroup(group2);
    } else {
      groupView = group2;
    }
    if (!groupView) {
      throw new Error("Invalid editor group provided!");
    }
    return groupView;
  }
  createEditorDropTarget(container2, delegate) {
    $Jg($Uj(container2));
    return this.vb.createInstance($4Ub, container2, delegate);
  }
  //#region Part
  // TODO @sbatten @joao find something better to prevent editor taking over #79897
  get minimumWidth() {
    return Math.min(this.wb.minimumWidth, this.M.getMaximumEditorDimensions(this.M.getContainer(getWindow(this.ub))).width);
  }
  get maximumWidth() {
    return this.wb.maximumWidth;
  }
  get minimumHeight() {
    return Math.min(this.wb.minimumHeight, this.M.getMaximumEditorDimensions(this.M.getContainer(getWindow(this.ub))).height);
  }
  get maximumHeight() {
    return this.wb.maximumHeight;
  }
  get snap() {
    return this.M.getPanelAlignment() === "center";
  }
  get onDidChange() {
    return Event2.any(this.wb.onDidChange, this.lb.event);
  }
  get kc() {
    return this.h.getColor($Bmb) || this.h.getColor($ko) || $Vn.transparent;
  }
  updateStyles() {
    const container2 = $Kg(this.ub);
    container2.style.backgroundColor = this.z($Ko) || "";
    const separatorBorderStyle = { separatorBorder: this.kc, background: this.h.getColor($umb) || $Vn.transparent };
    this.xb.style(separatorBorderStyle);
    this.wb.styles(separatorBorderStyle);
  }
  Q(parent, options3) {
    this.element = parent;
    this.ub = document.createElement("div");
    this.ub.classList.add("content");
    if (this.windowId !== $Y.vscodeWindowId) {
      this.ub.classList.add("auxiliary");
    }
    parent.appendChild(this.ub);
    const scopedContextKeyService = this.B(this.Fb.createScoped(this.ub));
    this.vb = this.B(this.Cb.createChild(new $Ok([$on, scopedContextKeyService])));
    this.Sb = !options3 || options3.restorePreviousState;
    this.oc();
    this.wb = this.B(new $B2(this.ub, this.zb, this.rb[$6Ub_1.b], this.Kb.centeredLayoutFixedWidth));
    this.B(this.onDidChangeEditorPartOptions((e) => this.wb.setFixedWidth(e.newPartOptions.centeredLayoutFixedWidth ?? false)));
    this.nc(parent, this.ub);
    this.mc(scopedContextKeyService);
    this.Qb.complete();
    this.Pb = true;
    Promises.settled(this.groups.map((group2) => group2.whenRestored)).finally(() => {
      this.Rb.complete();
    });
    return this.ub;
  }
  mc(contextKeyService) {
    const isAuxiliaryEditorPartContext = $Vpb.bindTo(contextKeyService);
    isAuxiliaryEditorPartContext.set(this.windowId !== $Y.vscodeWindowId);
    const multipleEditorGroupsContext = $Spb.bindTo(contextKeyService);
    const maximizedEditorGroupContext = $Upb.bindTo(contextKeyService);
    const updateContextKeys = () => {
      const groupCount = this.count;
      if (groupCount > 1) {
        multipleEditorGroupsContext.set(true);
      } else {
        multipleEditorGroupsContext.reset();
      }
      if (this.hasMaximizedGroup()) {
        maximizedEditorGroupContext.set(true);
      } else {
        maximizedEditorGroupContext.reset();
      }
    };
    updateContextKeys();
    this.B(this.onDidAddGroup(() => updateContextKeys()));
    this.B(this.onDidRemoveGroup(() => updateContextKeys()));
    this.B(this.onDidChangeGroupMaximized(() => updateContextKeys()));
  }
  nc(parent, container2) {
    this.B(this.createEditorDropTarget(container2, /* @__PURE__ */ Object.create(null)));
    const overlay = document.createElement("div");
    overlay.classList.add("drop-block-overlay");
    parent.appendChild(overlay);
    this.B($dj(overlay, () => overlay.classList.remove("visible")));
    this.B($Iob.INSTANCE.registerTarget(this.element, {
      onDragStart: (e) => overlay.classList.add("visible"),
      onDragEnd: (e) => overlay.classList.remove("visible")
    }));
    let horizontalOpenerTimeout;
    let verticalOpenerTimeout;
    let lastOpenHorizontalPosition;
    let lastOpenVerticalPosition;
    const openPartAtPosition = (position) => {
      if (!this.M.isVisible(
        "workbench.parts.panel"
        /* Parts.PANEL_PART */
      ) && position === this.M.getPanelPosition()) {
        this.M.setPartHidden(
          false,
          "workbench.parts.panel"
          /* Parts.PANEL_PART */
        );
      } else if (!this.M.isVisible(
        "workbench.parts.auxiliarybar"
        /* Parts.AUXILIARYBAR_PART */
      ) && position === (this.M.getSideBarPosition() === 1 ? 0 : 1)) {
        this.M.setPartHidden(
          false,
          "workbench.parts.auxiliarybar"
          /* Parts.AUXILIARYBAR_PART */
        );
      }
    };
    const clearAllTimeouts = () => {
      if (horizontalOpenerTimeout) {
        clearTimeout(horizontalOpenerTimeout);
        horizontalOpenerTimeout = void 0;
      }
      if (verticalOpenerTimeout) {
        clearTimeout(verticalOpenerTimeout);
        verticalOpenerTimeout = void 0;
      }
    };
    this.B($Iob.INSTANCE.registerTarget(overlay, {
      onDragOver: (e) => {
        $9j.stop(e.eventData, true);
        if (e.eventData.dataTransfer) {
          e.eventData.dataTransfer.dropEffect = "none";
        }
        const boundingRect = overlay.getBoundingClientRect();
        let openHorizontalPosition = void 0;
        let openVerticalPosition = void 0;
        const proximity = 100;
        if (e.eventData.clientX < boundingRect.left + proximity) {
          openHorizontalPosition = 0;
        }
        if (e.eventData.clientX > boundingRect.right - proximity) {
          openHorizontalPosition = 1;
        }
        if (e.eventData.clientY > boundingRect.bottom - proximity) {
          openVerticalPosition = 2;
        }
        if (e.eventData.clientY < boundingRect.top + proximity) {
          openVerticalPosition = 3;
        }
        if (horizontalOpenerTimeout && openHorizontalPosition !== lastOpenHorizontalPosition) {
          clearTimeout(horizontalOpenerTimeout);
          horizontalOpenerTimeout = void 0;
        }
        if (verticalOpenerTimeout && openVerticalPosition !== lastOpenVerticalPosition) {
          clearTimeout(verticalOpenerTimeout);
          verticalOpenerTimeout = void 0;
        }
        if (!horizontalOpenerTimeout && openHorizontalPosition !== void 0) {
          lastOpenHorizontalPosition = openHorizontalPosition;
          horizontalOpenerTimeout = setTimeout(() => openPartAtPosition(openHorizontalPosition), 200);
        }
        if (!verticalOpenerTimeout && openVerticalPosition !== void 0) {
          lastOpenVerticalPosition = openVerticalPosition;
          verticalOpenerTimeout = setTimeout(() => openPartAtPosition(openVerticalPosition), 200);
        }
      },
      onDragLeave: () => clearAllTimeouts(),
      onDragEnd: () => clearAllTimeouts(),
      onDrop: () => clearAllTimeouts()
    }));
  }
  centerLayout(active) {
    this.wb.activate(active);
    this.Ob.focus();
  }
  isLayoutCentered() {
    if (this.wb) {
      return this.wb.isActive();
    }
    return false;
  }
  oc() {
    let restoreError = false;
    if (this.Sb) {
      restoreError = !this.pc();
    }
    if (!this.xb || restoreError) {
      const initialGroup = this.bc();
      this.rc(new $y2(initialGroup));
      this.cc(initialGroup);
    }
    this.sc();
    this.tc();
  }
  pc() {
    const state = this.xc();
    if (state?.serializedGrid) {
      try {
        this.tb = state.mostRecentActiveGroups;
        this.qc(state.serializedGrid, state.activeGroup);
      } catch (error) {
        $gb(new Error(`Error restoring editor grid widget: ${error} (with state: ${JSON.stringify(state)})`));
        this.Dc();
        return false;
      }
    }
    return true;
  }
  qc(serializedGrid, activeGroupId, editorGroupViewsToReuse, options3) {
    let reuseGroupViews;
    if (editorGroupViewsToReuse) {
      reuseGroupViews = editorGroupViewsToReuse.slice(0);
    } else {
      reuseGroupViews = [];
    }
    const groupViews = [];
    const gridWidget = $y2.deserialize(serializedGrid, {
      fromJSON: (serializedEditorGroup) => {
        let groupView;
        if (reuseGroupViews.length > 0) {
          groupView = reuseGroupViews.shift();
        } else {
          groupView = this.bc(serializedEditorGroup, options3);
        }
        groupViews.push(groupView);
        if (groupView.id === activeGroupId) {
          this.cc(groupView);
        }
        return groupView;
      }
    }, { styles: { separatorBorder: this.kc } });
    if (!this.Ob) {
      this.cc(groupViews[0]);
    }
    if (this.tb.some((groupId) => !this.getGroup(groupId))) {
      this.tb = groupViews.map((group2) => group2.id);
    }
    this.rc(gridWidget);
  }
  rc(gridWidget) {
    let boundarySashes = {};
    if (this.xb) {
      boundarySashes = this.xb.boundarySashes;
      this.xb.dispose();
    }
    this.xb = gridWidget;
    this.xb.boundarySashes = boundarySashes;
    this.zb.gridWidget = gridWidget;
    this.mb.input = gridWidget.onDidChange;
    this.nb.input = gridWidget.onDidScroll;
    this.yb.clear();
    this.yb.add(gridWidget.onDidChangeViewMaximized((maximized) => this.gb.fire(maximized)));
    this.lb.fire(void 0);
  }
  sc() {
    const container2 = $Kg(this.ub);
    container2.classList.toggle("empty", this.uc);
  }
  tc() {
    this.getGroups(
      2
      /* GroupsOrder.GRID_APPEARANCE */
    ).forEach((group2, index) => group2.notifyIndexChanged(index));
  }
  notifyGroupsLabelChange(newLabel) {
    for (const group2 of this.groups) {
      group2.notifyLabelChanged(newLabel);
    }
  }
  get uc() {
    return this.count === 1 && this.Ob.isEmpty;
  }
  setBoundarySashes(sashes) {
    this.xb.boundarySashes = sashes;
    this.wb.boundarySashes = sashes;
  }
  layout(width2, height, top2, left) {
    this.Lb = top2;
    this.Mb = left;
    const contentAreaSize = super.Z(width2, height).contentSize;
    this.vc($rj.lift(contentAreaSize), top2, left);
  }
  vc(dimension, top2 = this.Lb, left = this.Mb) {
    this.Nb = dimension;
    this.wb.layout(this.Nb.width, this.Nb.height, top2, left);
    this.bb.fire(dimension);
  }
  I() {
    if (this.xb) {
      if (this.uc) {
        delete this.qb[$6Ub_1.a];
      } else {
        this.qb[$6Ub_1.a] = this.createState();
      }
    }
    if (this.wb) {
      const centeredLayoutState = this.wb.state;
      if (this.wb.isDefault(centeredLayoutState)) {
        delete this.rb[$6Ub_1.b];
      } else {
        this.rb[$6Ub_1.b] = centeredLayoutState;
      }
    }
    super.I();
  }
  xc() {
    return this.qb[$6Ub_1.a];
  }
  createState() {
    return {
      serializedGrid: this.xb.serialize(),
      activeGroup: this.Ob.id,
      mostRecentActiveGroups: this.tb
    };
  }
  applyState(state, options3) {
    if (state === "empty") {
      return this.zc();
    } else {
      return this.yc(state, options3);
    }
  }
  async yc(state, options3) {
    const groups = await this.Ac();
    this.ib.pause();
    this.jb.pause();
    this.Dc();
    this.tb = state.mostRecentActiveGroups;
    try {
      this.Bc(state.serializedGrid, state.activeGroup, void 0, options3);
    } finally {
      this.jb.resume();
      this.ib.resume();
    }
    await this.activeGroup.openEditors(groups.flatMap((group2) => group2.editors).filter((editor) => this.Ab.groups.every((groupView) => !groupView.contains(editor))).map((editor) => ({
      editor,
      options: { pinned: true, preserveFocus: true, inactive: true }
    })));
  }
  async zc() {
    await this.Ac();
    this.mergeAllGroups(this.activeGroup);
  }
  async Ac() {
    const groups = this.getGroups(
      1
      /* GroupsOrder.MOST_RECENTLY_ACTIVE */
    );
    for (const group2 of groups) {
      await group2.closeAllEditors({ excludeConfirming: true });
    }
    return groups;
  }
  Bc(gridState, activeGroupId, editorGroupViewsToReuse, options3) {
    this.qc(gridState, activeGroupId, editorGroupViewsToReuse, options3);
    this.vc(this.Nb);
    this.sc();
    for (const groupView of this.getGroups(
      2
      /* GroupsOrder.GRID_APPEARANCE */
    )) {
      if (!editorGroupViewsToReuse?.includes(groupView)) {
        this.ib.fire(groupView);
      }
    }
    this.tc();
  }
  Cc(e) {
    if (e.external && e.scope === 1) {
      this.G(e.scope);
      const state = this.xc();
      if (state) {
        this.applyState(state);
      }
    }
  }
  toJSON() {
    return {
      type: "workbench.parts.editor"
      /* Parts.EDITOR_PART */
    };
  }
  Dc() {
    for (const group2 of this.groups) {
      group2.dispose();
      this.jb.fire(group2);
    }
    this.sb.clear();
    this.tb = [];
  }
  dispose() {
    this.pb.fire();
    this.Dc();
    this.xb?.dispose();
    super.dispose();
  }
};
$6Ub = $6Ub_1 = __decorate([
  __param(4, $Pk),
  __param(5, $gs),
  __param(6, $kl),
  __param(7, $jv),
  __param(8, $Vlb),
  __param(9, $S4),
  __param(10, $on)
], $6Ub);
var $7Ub = class $7Ub2 extends $6Ub {
  constructor(editorPartsView, instantiationService, themeService, configurationService, storageService, layoutService, hostService, contextKeyService) {
    super(editorPartsView, "workbench.parts.editor", "", $Y.vscodeWindowId, instantiationService, themeService, configurationService, storageService, layoutService, hostService, contextKeyService);
  }
};
$7Ub = __decorate([
  __param(1, $Pk),
  __param(2, $gs),
  __param(3, $kl),
  __param(4, $jv),
  __param(5, $Vlb),
  __param(6, $S4),
  __param(7, $on)
], $7Ub);

// out-build/vs/base/browser/deviceAccess.js
async function $512(options3) {
  const usb = navigator.usb;
  if (!usb) {
    return void 0;
  }
  const device = await usb.requestDevice({ filters: options3?.filters ?? [] });
  if (!device) {
    return void 0;
  }
  return {
    deviceClass: device.deviceClass,
    deviceProtocol: device.deviceProtocol,
    deviceSubclass: device.deviceSubclass,
    deviceVersionMajor: device.deviceVersionMajor,
    deviceVersionMinor: device.deviceVersionMinor,
    deviceVersionSubminor: device.deviceVersionSubminor,
    manufacturerName: device.manufacturerName,
    productId: device.productId,
    productName: device.productName,
    serialNumber: device.serialNumber,
    usbVersionMajor: device.usbVersionMajor,
    usbVersionMinor: device.usbVersionMinor,
    usbVersionSubminor: device.usbVersionSubminor,
    vendorId: device.vendorId
  };
}
async function $612(options3) {
  const serial = navigator.serial;
  if (!serial) {
    return void 0;
  }
  const port = await serial.requestPort({ filters: options3?.filters ?? [] });
  if (!port) {
    return void 0;
  }
  const info = port.getInfo();
  return {
    usbVendorId: info.usbVendorId,
    usbProductId: info.usbProductId
  };
}
async function $712(options3) {
  const hid = navigator.hid;
  if (!hid) {
    return void 0;
  }
  const devices = await hid.requestDevice({ filters: options3?.filters ?? [] });
  if (!devices.length) {
    return void 0;
  }
  const device = devices[0];
  return {
    opened: device.opened,
    vendorId: device.vendorId,
    productId: device.productId,
    productName: device.productName,
    collections: device.collections
  };
}

// out-build/vs/platform/languagePacks/common/localizedStrings.js
var open = localize(1962, null);
var close = localize(1963, null);
var find = localize(1964, null);
var localizedStrings_default = {
  open,
  close,
  find
};

// out-build/vs/platform/log/browser/log.js
async function $Oob(fileService, environmentService) {
  const result = [];
  await doGetLogs(fileService, result, environmentService.logsHome, environmentService.logsHome);
  return result;
}
async function doGetLogs(fileService, logs, curFolder, logsHome) {
  const stat = await fileService.resolve(curFolder);
  for (const { resource, isDirectory } of stat.children || []) {
    if (isDirectory) {
      await doGetLogs(fileService, logs, resource, logsHome);
    } else {
      const contents = (await fileService.readFile(resource)).value.toString();
      if (contents) {
        const path = $xh(logsHome, resource);
        if (path) {
          logs.push({ relativePath: path, contents });
        }
      }
    }
  }
}
function logLevelToString(level) {
  switch (level) {
    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";
  }
  return "info";
}
var $Pob = class extends $Fn {
  constructor(logLevel = $zn) {
    super({ log: (level, args2) => this.m(logLevelToString(level), args2) }, logLevel);
  }
  m(type, args2) {
    const automatedWindow = $Y;
    if (typeof automatedWindow.codeAutomationLog === "function") {
      try {
        automatedWindow.codeAutomationLog(type, args2);
      } catch (err) {
        console.error("Problems writing to codeAutomationLog", err);
      }
    }
  }
};

// out-build/vs/workbench/services/driver/browser/driver.js
var $Qob = class $Qob2 {
  constructor(a, b, d, e) {
    this.a = a;
    this.b = b;
    this.d = d;
    this.e = e;
  }
  async getLogs() {
    return $Oob(this.a, this.b);
  }
  async whenWorkbenchRestored() {
    this.e.info("[driver] Waiting for restored lifecycle phase...");
    await this.d.when(
      3
      /* LifecyclePhase.Restored */
    );
    this.e.info("[driver] Restored lifecycle phase reached. Waiting for contributions...");
    await $Wn.as(Extensions2.Workbench).whenRestored;
    this.e.info("[driver] Workbench contributions created.");
  }
  async setValue(selector, text2) {
    const element = $Y.document.querySelector(selector);
    if (!element) {
      return Promise.reject(new Error(`Element not found: ${selector}`));
    }
    const inputElement = element;
    inputElement.value = text2;
    const event = new Event("input", { bubbles: true, cancelable: true });
    inputElement.dispatchEvent(event);
  }
  async isActiveElement(selector) {
    const element = $Y.document.querySelector(selector);
    if (element !== $Y.document.activeElement) {
      const chain = [];
      let el = $Y.document.activeElement;
      while (el) {
        const tagName = el.tagName;
        const id2 = el.id ? `#${el.id}` : "";
        const classes2 = $Mb(el.className.split(/\s+/g).map((c) => c.trim())).map((c) => `.${c}`).join("");
        chain.unshift(`${tagName}${id2}${classes2}`);
        el = el.parentElement;
      }
      throw new Error(`Active element not found. Current active element is '${chain.join(" > ")}'. Looking for ${selector}`);
    }
    return true;
  }
  async getElements(selector, recursive) {
    const query = $Y.document.querySelectorAll(selector);
    const result = [];
    for (let i2 = 0; i2 < query.length; i2++) {
      const element = query.item(i2);
      result.push(this.f(element, recursive));
    }
    return result;
  }
  f(element, recursive) {
    const attributes = /* @__PURE__ */ Object.create(null);
    for (let j = 0; j < element.attributes.length; j++) {
      const attr = element.attributes.item(j);
      if (attr) {
        attributes[attr.name] = attr.value;
      }
    }
    const children = [];
    if (recursive) {
      for (let i2 = 0; i2 < element.children.length; i2++) {
        const child = element.children.item(i2);
        if (child) {
          children.push(this.f(child, true));
        }
      }
    }
    const { left, top: top2 } = $sj(element);
    return {
      tagName: element.tagName,
      className: element.className,
      textContent: element.textContent || "",
      attributes,
      children,
      left,
      top: top2
    };
  }
  async getElementXY(selector, xoffset, yoffset) {
    const offset = typeof xoffset === "number" && typeof yoffset === "number" ? { x: xoffset, y: yoffset } : void 0;
    return this.g(selector, offset);
  }
  async typeInEditor(selector, text2) {
    const element = $Y.document.querySelector(selector);
    if (!element) {
      throw new Error(`Editor not found: ${selector}`);
    }
    const textarea = element;
    const start = textarea.selectionStart;
    const newStart = start + text2.length;
    const value = textarea.value;
    const newValue = value.substr(0, start) + text2 + value.substr(start);
    textarea.value = newValue;
    textarea.setSelectionRange(newStart, newStart);
    const event = new Event("input", { "bubbles": true, "cancelable": true });
    textarea.dispatchEvent(event);
  }
  async getTerminalBuffer(selector) {
    const element = $Y.document.querySelector(selector);
    if (!element) {
      throw new Error(`Terminal not found: ${selector}`);
    }
    const xterm = element.xterm;
    if (!xterm) {
      throw new Error(`Xterm not found: ${selector}`);
    }
    const lines = [];
    for (let i2 = 0; i2 < xterm.buffer.active.length; i2++) {
      lines.push(xterm.buffer.active.getLine(i2).translateToString(true));
    }
    return lines;
  }
  async writeInTerminal(selector, text2) {
    const element = $Y.document.querySelector(selector);
    if (!element) {
      throw new Error(`Element not found: ${selector}`);
    }
    const xterm = element.xterm;
    if (!xterm) {
      throw new Error(`Xterm not found: ${selector}`);
    }
    xterm.input(text2);
  }
  getLocaleInfo() {
    return Promise.resolve({
      language: $z,
      locale: $A
    });
  }
  getLocalizedStrings() {
    return Promise.resolve({
      open: localizedStrings_default.open,
      close: localizedStrings_default.close,
      find: localizedStrings_default.find
    });
  }
  async g(selector, offset) {
    const element = $Y.document.querySelector(selector);
    if (!element) {
      return Promise.reject(new Error(`Element not found: ${selector}`));
    }
    const { left, top: top2 } = $sj(element);
    const { width: width2, height } = $qj(element);
    let x, y;
    if (offset) {
      x = left + offset.x;
      y = top2 + offset.y;
    } else {
      x = left + width2 / 2;
      y = top2 + height / 2;
    }
    x = Math.round(x);
    y = Math.round(y);
    return { x, y };
  }
  async exitApplication() {
  }
};
$Qob = __decorate([
  __param(0, $km),
  __param(1, $Xk),
  __param(2, $KL),
  __param(3, $wn)
], $Qob);
function $Rob(instantiationService) {
  Object.assign($Y, { driver: instantiationService.createInstance($Qob) });
}

// out-build/vs/workbench/browser/window.js
var $Sob_1;
var $Sob = class $Sob2 extends $3c {
  static {
    $Sob_1 = this;
  }
  static {
    this.a = Number.MIN_SAFE_INTEGER;
  }
  static {
    this.b = /* @__PURE__ */ new Map();
  }
  constructor(targetWindow, dom = { getWindowsCount, getWindows }, c, f) {
    super();
    this.c = c;
    this.f = f;
    this.g(targetWindow);
    this.j(targetWindow, dom);
    this.m(targetWindow.vscodeWindowId);
  }
  //#region focus handling in multi-window applications
  g(targetWindow) {
    const originalFocus = targetWindow.HTMLElement.prototype.focus;
    const that = this;
    targetWindow.HTMLElement.prototype.focus = function(options3) {
      that.h(getWindow(this));
      originalFocus.apply(this, [options3]);
    };
  }
  h(targetWindow) {
    const activeWindow = $Qj();
    if (activeWindow !== targetWindow && activeWindow.document.hasFocus()) {
      targetWindow.focus();
      if (!this.f.extensionTestsLocationURI && !targetWindow.document.hasFocus()) {
        this.c.focus(targetWindow);
      }
    }
  }
  //#endregion
  //#region timeout handling in multi-window applications
  j(targetWindow, dom = { getWindowsCount, getWindows }) {
    const originalSetTimeout = targetWindow.setTimeout;
    Object.defineProperty(targetWindow, "vscodeOriginalSetTimeout", { get: () => originalSetTimeout });
    const originalClearTimeout = targetWindow.clearTimeout;
    Object.defineProperty(targetWindow, "vscodeOriginalClearTimeout", { get: () => originalClearTimeout });
    targetWindow.setTimeout = function(handler, timeout = 0, ...args2) {
      if (dom.getWindowsCount() === 1 || typeof handler === "string" || timeout === 0) {
        return originalSetTimeout.apply(this, [handler, timeout, ...args2]);
      }
      const timeoutDisposables = /* @__PURE__ */ new Set();
      const timeoutHandle = $Sob_1.a++;
      $Sob_1.b.set(timeoutHandle, timeoutDisposables);
      const handlerFn = $Qc(handler, () => {
        $Xc(timeoutDisposables);
        $Sob_1.b.delete(timeoutHandle);
      });
      for (const { window: window3, disposables } of dom.getWindows()) {
        if ($Z(window3) && window3.document.visibilityState === "hidden") {
          continue;
        }
        let didClear = false;
        const handle2 = window3.vscodeOriginalSetTimeout.apply(this, [(...args3) => {
          if (didClear) {
            return;
          }
          handlerFn(...args3);
        }, timeout, ...args2]);
        const timeoutDisposable = $1c(() => {
          didClear = true;
          window3.vscodeOriginalClearTimeout(handle2);
          timeoutDisposables.delete(timeoutDisposable);
        });
        disposables.add(timeoutDisposable);
        timeoutDisposables.add(timeoutDisposable);
      }
      return timeoutHandle;
    };
    targetWindow.clearTimeout = function(timeoutHandle) {
      const timeoutDisposables = typeof timeoutHandle === "number" ? $Sob_1.b.get(timeoutHandle) : void 0;
      if (timeoutDisposables) {
        $Xc(timeoutDisposables);
        $Sob_1.b.delete(timeoutHandle);
      } else {
        originalClearTimeout.apply(this, [timeoutHandle]);
      }
    };
  }
  //#endregion
  m(targetWindowId) {
    this.B(this.c.onDidChangeFullScreen(({ windowId, fullscreen }) => {
      if (windowId === targetWindowId) {
        const targetWindow = getWindowById(targetWindowId);
        if (targetWindow) {
          $Re(fullscreen, targetWindow.window);
        }
      }
    }));
  }
  //#region Confirm on Shutdown
  static async confirmOnShutdown(accessor, reason) {
    const dialogService = accessor.get($Yv);
    const configurationService = accessor.get($kl);
    const message = reason === 2 ? $m ? localize(3814, null) : localize(3815, null) : localize(3816, null);
    const primaryButton = reason === 2 ? $m ? localize(3817, null) : localize(3818, null) : localize(3819, null);
    const res = await dialogService.confirm({
      message,
      primaryButton,
      checkbox: {
        label: localize(3820, null)
      }
    });
    if (res.confirmed && res.checkboxChecked) {
      await configurationService.updateValue("window.confirmBeforeClose", "never");
    }
    return res.confirmed;
  }
};
$Sob = $Sob_1 = __decorate([
  __param(2, $S4),
  __param(3, $US)
], $Sob);
var $Tob = class $Tob2 extends $Sob {
  constructor(n, r2, s, t, u, w, y, z, hostService) {
    super($Y, void 0, hostService, w);
    this.n = n;
    this.r = r2;
    this.s = s;
    this.t = t;
    this.u = u;
    this.w = w;
    this.y = y;
    this.z = z;
    this.C();
    this.F();
  }
  C() {
    this.B(this.r.onWillShutdown(() => this.D()));
    const viewport = $u && $Y.visualViewport ? $Y.visualViewport : $Y;
    this.B($_i(viewport, $7j.RESIZE, () => {
      this.y.layout();
      if ($u) {
        $Y.scrollTo(0, 0);
      }
    }));
    this.B($_i(this.y.mainContainer, $7j.WHEEL, (e) => e.preventDefault(), { passive: false }));
    this.B($_i(this.y.mainContainer, $7j.CONTEXT_MENU, (e) => $9j.stop(e, true)));
    this.B($_i(this.y.mainContainer, $7j.DROP, (e) => $9j.stop(e, true)));
  }
  D() {
    Event2.toPromise(Event2.any(Event2.once(new $9Z($Y.document.body, $7j.KEY_DOWN, true).event), Event2.once(new $9Z($Y.document.body, $7j.MOUSE_DOWN, true).event))).then(async () => {
      await $Wh(3e3);
      await this.s.prompt({
        type: severity_default.Error,
        message: localize(3821, null),
        detail: localize(3822, null),
        buttons: [
          {
            label: localize(3823, null),
            run: () => $Y.location.reload()
            // do not use any services at this point since they are likely not functional at this point
          }
        ]
      });
    });
  }
  F() {
    this.H();
    this.I();
    this.J();
    this.G();
  }
  G() {
    if (this.f.enableSmokeTestDriver) {
      $Rob(this.z);
    }
  }
  H() {
    this.n.setDefaultExternalOpener({
      openExternal: async (href) => {
        let isAllowedOpener = false;
        if (this.w.options?.openerAllowedExternalUrlPrefixes) {
          for (const trustedPopupPrefix of this.w.options.openerAllowedExternalUrlPrefixes) {
            if (href.startsWith(trustedPopupPrefix)) {
              isAllowedOpener = true;
              break;
            }
          }
        }
        if ($0g(href, Schemas.http) || $0g(href, Schemas.https)) {
          if ($Xe) {
            const opened = $pk(href, !isAllowedOpener);
            if (!opened) {
              await this.s.prompt({
                type: severity_default.Warning,
                message: localize(3824, null),
                detail: href,
                buttons: [
                  {
                    label: localize(3825, null),
                    run: () => isAllowedOpener ? $ok(href) : $nk(href)
                  },
                  {
                    label: localize(3826, null),
                    run: () => this.n.open(URI.parse("https://aka.ms/allow-vscode-popup"))
                  }
                ],
                cancelButton: true
              });
            }
          } else {
            isAllowedOpener ? $ok(href) : $nk(href);
          }
        } else {
          const invokeProtocolHandler = () => {
            this.r.withExpectedShutdown({ disableShutdownHandling: true }, () => $Y.location.href = href);
          };
          invokeProtocolHandler();
          const showProtocolUrlOpenedDialog = async () => {
            const { downloadUrl } = this.u;
            let detail2;
            const buttons = [
              {
                label: localize(3827, null),
                run: () => invokeProtocolHandler()
              }
            ];
            if (downloadUrl !== void 0) {
              detail2 = localize(3828, null, this.u.nameLong, this.u.nameLong);
              buttons.push({
                label: localize(3829, null),
                run: async () => {
                  await this.n.open(URI.parse(downloadUrl));
                  showProtocolUrlOpenedDialog();
                }
              });
            } else {
              detail2 = localize(3830, null, this.u.nameLong, this.u.nameLong);
            }
            await this.c.withExpectedShutdown(() => this.s.prompt({
              type: severity_default.Info,
              message: localize(3831, null),
              detail: detail2,
              buttons,
              cancelButton: true
            }));
          };
          if ($0g(href, this.u.urlProtocol)) {
            await showProtocolUrlOpenedDialog();
          }
        }
        return true;
      }
    });
  }
  I() {
    this.B(this.t.registerFormatter({
      scheme: Schemas.vscodeUserData,
      priority: true,
      formatting: {
        label: "(Settings) ${path}",
        separator: "/"
      }
    }));
  }
  J() {
    $tn.registerCommand("workbench.experimental.requestUsbDevice", async (_accessor, options3) => {
      return $512(options3);
    });
    $tn.registerCommand("workbench.experimental.requestSerialPort", async (_accessor, options3) => {
      return $612(options3);
    });
    $tn.registerCommand("workbench.experimental.requestHidDevice", async (_accessor, options3) => {
      return $712(options3);
    });
  }
};
$Tob = __decorate([
  __param(0, $O4),
  __param(1, $KL),
  __param(2, $Yv),
  __param(3, $ZI),
  __param(4, $Vu),
  __param(5, $M4),
  __param(6, $Vlb),
  __param(7, $Pk),
  __param(8, $S4)
], $Tob);

// out-build/vs/workbench/services/auxiliaryWindow/browser/auxiliaryWindowService.js
var $Wob_1;
var $Uob = $Qk("auxiliaryWindowService");
var AuxiliaryWindowMode;
(function(AuxiliaryWindowMode2) {
  AuxiliaryWindowMode2[AuxiliaryWindowMode2["Maximized"] = 0] = "Maximized";
  AuxiliaryWindowMode2[AuxiliaryWindowMode2["Normal"] = 1] = "Normal";
  AuxiliaryWindowMode2[AuxiliaryWindowMode2["Fullscreen"] = 2] = "Fullscreen";
})(AuxiliaryWindowMode || (AuxiliaryWindowMode = {}));
var $Vob = class $Vob2 extends $Sob {
  constructor(window3, container2, stylesHaveLoaded, w, hostService, environmentService) {
    super(window3, void 0, hostService, environmentService);
    this.window = window3;
    this.container = container2;
    this.w = w;
    this.n = this.B(new $ze());
    this.onWillLayout = this.n.event;
    this.r = this.B(new $ze());
    this.onDidLayout = this.r.event;
    this.s = this.B(new $ze());
    this.onBeforeUnload = this.s.event;
    this.t = this.B(new $ze());
    this.onUnload = this.t.event;
    this.u = this.B(new $ze());
    this.onWillDispose = this.u.event;
    this.whenStylesHaveLoaded = stylesHaveLoaded.wait().then(() => void 0);
    this.z();
  }
  z() {
    this.B($_i(this.window, $7j.BEFORE_UNLOAD, (e) => this.C(e)));
    this.B($_i(this.window, $7j.UNLOAD, () => this.H()));
    this.B($_i(this.window, "unhandledrejection", (e) => {
      $gb(e.reason);
      e.preventDefault();
    }));
    this.B($_i(this.window, $7j.RESIZE, () => this.layout()));
    this.B($_i(this.container, $7j.SCROLL, () => this.container.scrollTop = 0));
    if ($r) {
      this.B($_i(this.container, $7j.DROP, (e) => $9j.stop(e, true)));
      this.B($_i(this.container, $7j.WHEEL, (e) => e.preventDefault(), { passive: false }));
      this.B($_i(this.container, $7j.CONTEXT_MENU, (e) => $9j.stop(e, true)));
    } else {
      this.B($_i(this.window.document.body, $7j.DRAG_OVER, (e) => $9j.stop(e)));
      this.B($_i(this.window.document.body, $7j.DROP, (e) => $9j.stop(e)));
    }
  }
  C(e) {
    let veto;
    this.s.fire({
      veto(reason) {
        if (reason) {
          veto = reason;
        }
      }
    });
    if (veto) {
      this.D(e, veto);
      return;
    }
    const confirmBeforeCloseSetting = this.w.getValue("window.confirmBeforeClose");
    const confirmBeforeClose = confirmBeforeCloseSetting === "always" || confirmBeforeCloseSetting === "keyboardOnly" && $yk.getInstance().isModifierPressed;
    if (confirmBeforeClose) {
      this.G(e);
    }
  }
  D(e, reason) {
    this.F(e);
  }
  F(e) {
    e.preventDefault();
    e.returnValue = localize(12557, null);
  }
  G(e) {
    this.F(e);
  }
  H() {
    this.t.fire();
  }
  layout() {
    const dimension = $qj(this.window.document.body, this.container);
    this.n.fire(dimension);
    this.r.fire(dimension);
  }
  createState() {
    return {
      bounds: {
        x: this.window.screenX,
        y: this.window.screenY,
        width: this.window.outerWidth,
        height: this.window.outerHeight
      },
      zoomLevel: $Ne(this.window)
    };
  }
  dispose() {
    if (this.q.isDisposed) {
      return;
    }
    this.u.fire();
    super.dispose();
  }
};
$Vob = __decorate([
  __param(3, $kl),
  __param(4, $S4),
  __param(5, $US)
], $Vob);
var $Wob = class $Wob2 extends $3c {
  static {
    $Wob_1 = this;
  }
  static {
    this.a = { width: 800, height: 600 };
  }
  static {
    this.b = getWindowId($Y) + 1;
  }
  // start from the main window ID + 1
  constructor(g, h3, j, m, n, r2) {
    super();
    this.g = g;
    this.h = h3;
    this.j = j;
    this.m = m;
    this.n = n;
    this.r = r2;
    this.c = this.B(new $ze());
    this.onDidOpenAuxiliaryWindow = this.c.event;
    this.f = /* @__PURE__ */ new Map();
  }
  async open(options3) {
    $S("code/auxiliaryWindow/willOpen");
    const targetWindow = await this.t(options3);
    if (!targetWindow) {
      throw new Error(localize(12558, null));
    }
    const resolvedWindowId = await this.u(targetWindow);
    $X(targetWindow, resolvedWindowId);
    const containerDisposables = new $2c();
    const { container: container2, stylesLoaded } = this.w(targetWindow, containerDisposables, options3);
    const auxiliaryWindow = this.s(targetWindow, container2, stylesLoaded);
    const registryDisposables = new $2c();
    this.f.set(targetWindow.vscodeWindowId, auxiliaryWindow);
    registryDisposables.add($1c(() => this.f.delete(targetWindow.vscodeWindowId)));
    const eventDisposables = new $2c();
    Event2.once(auxiliaryWindow.onWillDispose)(() => {
      targetWindow.close();
      containerDisposables.dispose();
      registryDisposables.dispose();
      eventDisposables.dispose();
    });
    registryDisposables.add(registerWindow(targetWindow));
    this.c.fire({ window: auxiliaryWindow, disposables: eventDisposables });
    $S("code/auxiliaryWindow/didOpen");
    this.m.publicLog2("auxiliaryWindowOpen", { bounds: !!options3?.bounds });
    return auxiliaryWindow;
  }
  s(targetWindow, container2, stylesLoaded) {
    return new $Vob(targetWindow, container2, stylesLoaded, this.j, this.n, this.r);
  }
  async t(options3) {
    const activeWindow = $Qj();
    const activeWindowBounds = {
      x: activeWindow.screenX,
      y: activeWindow.screenY,
      width: activeWindow.outerWidth,
      height: activeWindow.outerHeight
    };
    const width2 = Math.max(options3?.bounds?.width ?? $Wob_1.a.width, $ws.WIDTH);
    const height = Math.max(options3?.bounds?.height ?? $Wob_1.a.height, $ws.HEIGHT);
    let newWindowBounds = {
      x: options3?.bounds?.x ?? Math.max(activeWindowBounds.x + activeWindowBounds.width / 2 - width2 / 2, 0),
      y: options3?.bounds?.y ?? Math.max(activeWindowBounds.y + activeWindowBounds.height / 2 - height / 2, 0),
      width: width2,
      height
    };
    if (!options3?.bounds && newWindowBounds.x === activeWindowBounds.x && newWindowBounds.y === activeWindowBounds.y) {
      newWindowBounds = {
        ...newWindowBounds,
        x: newWindowBounds.x + 30,
        y: newWindowBounds.y + 30
      };
    }
    const features = $Mb([
      "popup=yes",
      `left=${newWindowBounds.x}`,
      `top=${newWindowBounds.y}`,
      `width=${newWindowBounds.width}`,
      `height=${newWindowBounds.height}`,
      // non-standard properties
      options3?.nativeTitlebar ? "window-native-titlebar=yes" : void 0,
      options3?.disableFullscreen ? "window-disable-fullscreen=yes" : void 0,
      options3?.mode === AuxiliaryWindowMode.Maximized ? "window-maximized=yes" : void 0,
      options3?.mode === AuxiliaryWindowMode.Fullscreen ? "window-fullscreen=yes" : void 0
    ]);
    const auxiliaryWindow = $Y.open($I ? "" : "about:blank", void 0, features.join(","));
    if (!auxiliaryWindow && $r) {
      return (await this.h.prompt({
        type: severity_default.Warning,
        message: localize(12559, null),
        detail: localize(12560, null),
        buttons: [
          {
            label: localize(12561, null),
            run: () => this.t(options3)
          }
        ],
        cancelButton: true
      })).result;
    }
    return auxiliaryWindow?.window;
  }
  async u(auxiliaryWindow) {
    return $Wob_1.b++;
  }
  w(auxiliaryWindow, disposables, options3) {
    auxiliaryWindow.document.createElement = function() {
      throw new Error('Not allowed to create elements in child window JavaScript context. Always use the main window so that "xyz instanceof HTMLElement" continues to work.');
    };
    this.z(auxiliaryWindow);
    const { stylesLoaded } = this.C(auxiliaryWindow, disposables);
    const container2 = this.D(auxiliaryWindow, disposables);
    return { stylesLoaded, container: container2 };
  }
  z(auxiliaryWindow) {
    for (const metaTag of ['meta[charset="utf-8"]', 'meta[http-equiv="Content-Security-Policy"]', 'meta[name="viewport"]', 'meta[name="theme-color"]']) {
      const metaElement = $Y.document.querySelector(metaTag);
      if (metaElement) {
        const clonedMetaElement = $Sj(auxiliaryWindow.document.head);
        $Dk(metaElement, clonedMetaElement);
        if (metaTag === 'meta[http-equiv="Content-Security-Policy"]') {
          const content = clonedMetaElement.getAttribute("content");
          if (content) {
            clonedMetaElement.setAttribute("content", content.replace(/(script-src[^\;]*)/, `script-src 'none'`));
          }
        }
      }
    }
    const originalIconLinkTag = $Y.document.querySelector('link[rel="icon"]');
    if (originalIconLinkTag) {
      const icon2 = $Tj(auxiliaryWindow.document.head);
      $Dk(originalIconLinkTag, icon2);
    }
  }
  C(auxiliaryWindow, disposables) {
    $S("code/auxiliaryWindow/willApplyCSS");
    const mapOriginalToClone = /* @__PURE__ */ new Map();
    const stylesLoaded = new $Uh();
    stylesLoaded.wait().then(() => $S("code/auxiliaryWindow/didLoadCSSStyles"));
    const pendingLinksDisposables = disposables.add(new $2c());
    let pendingLinksToSettle = 0;
    function onLinkSettled() {
      if (--pendingLinksToSettle === 0) {
        pendingLinksDisposables.dispose();
        stylesLoaded.open();
      }
    }
    function cloneNode(originalNode) {
      if ($TZ(originalNode)) {
        return;
      }
      const clonedNode = auxiliaryWindow.document.head.appendChild(originalNode.cloneNode(true));
      if (originalNode.tagName.toLowerCase() === "link") {
        pendingLinksToSettle++;
        pendingLinksDisposables.add($_i(clonedNode, "load", onLinkSettled));
        pendingLinksDisposables.add($_i(clonedNode, "error", onLinkSettled));
      }
      mapOriginalToClone.set(originalNode, clonedNode);
    }
    pendingLinksToSettle++;
    try {
      for (const originalNode of $Y.document.head.querySelectorAll('link[rel="stylesheet"], style')) {
        cloneNode(originalNode);
      }
    } finally {
      onLinkSettled();
    }
    disposables.add($WZ(auxiliaryWindow));
    disposables.add($Rj.observe($Y.document.head, disposables, { childList: true, subtree: true })((mutations) => {
      for (const mutation of mutations) {
        if (mutation.type !== "childList" || // only interested in added/removed nodes
        mutation.target.nodeName.toLowerCase() === "title" || // skip over title changes that happen frequently
        mutation.target.nodeName.toLowerCase() === "script" || // block <script> changes that are unsupported anyway
        mutation.target.nodeName.toLowerCase() === "meta") {
          continue;
        }
        for (const node of mutation.addedNodes) {
          if ($Uj(node) && (node.tagName.toLowerCase() === "style" || node.tagName.toLowerCase() === "link")) {
            cloneNode(node);
          } else if (node.nodeType === Node.TEXT_NODE && node.parentNode) {
            const clonedNode = mapOriginalToClone.get(node.parentNode);
            if (clonedNode) {
              clonedNode.textContent = node.textContent;
            }
          }
        }
        for (const node of mutation.removedNodes) {
          const clonedNode = mapOriginalToClone.get(node);
          if (clonedNode) {
            clonedNode.parentNode?.removeChild(clonedNode);
            mapOriginalToClone.delete(node);
          }
        }
      }
    }));
    $S("code/auxiliaryWindow/didApplyCSS");
    return { stylesLoaded };
  }
  D(auxiliaryWindow, disposables) {
    $S("code/auxiliaryWindow/willApplyHTML");
    const container2 = document.createElement("div");
    container2.setAttribute("role", "application");
    $uj(container2, 0, 0, 0, 0, "relative");
    container2.style.display = "flex";
    container2.style.height = "100%";
    container2.style.flexDirection = "column";
    auxiliaryWindow.document.body.append(container2);
    disposables.add($Ek($Y.document.documentElement, auxiliaryWindow.document.documentElement));
    disposables.add($Ek($Y.document.body, auxiliaryWindow.document.body));
    disposables.add($Ek(this.g.mainContainer, container2, ["class"]));
    $S("code/auxiliaryWindow/didApplyHTML");
    return container2;
  }
  getWindow(windowId) {
    return this.f.get(windowId);
  }
};
$Wob = $Wob_1 = __decorate([
  __param(0, $Vlb),
  __param(1, $Yv),
  __param(2, $kl),
  __param(3, $zv),
  __param(4, $S4),
  __param(5, $US)
], $Wob);
$SC(
  $Uob,
  $Wob,
  1
  /* InstantiationType.Delayed */
);

// out-build/vs/workbench/services/title/browser/titleService.js
var $RTb = $Qk("titleService");

// out-build/vs/workbench/browser/parts/editor/auxiliaryEditorPart.js
var $8Ub_1;
var AuxiliaryEditorPartImpl_1;
var $8Ub = class $8Ub2 {
  static {
    $8Ub_1 = this;
  }
  static {
    this.a = "workbench.statusBar.visible";
  }
  constructor(b, c, d, f, g, h3, i2, j, k) {
    this.b = b;
    this.c = c;
    this.d = d;
    this.f = f;
    this.g = g;
    this.h = h3;
    this.i = i2;
    this.j = j;
    this.k = k;
  }
  async create(label3, options3) {
    function computeEditorPartHeightOffset() {
      let editorPartHeightOffset = 0;
      if (statusbarVisible) {
        editorPartHeightOffset += statusbarPart.height;
      }
      if (titlebarPart && titlebarVisible) {
        editorPartHeightOffset += titlebarPart.height;
      }
      return editorPartHeightOffset;
    }
    function updateStatusbarVisibility(fromEvent) {
      if (statusbarVisible) {
        $hk(statusbarPart.container);
      } else {
        $ik(statusbarPart.container);
      }
      if (fromEvent) {
        auxiliaryWindow.layout();
      }
    }
    function updateTitlebarVisibility(fromEvent) {
      if (!titlebarPart) {
        return;
      }
      if (titlebarVisible) {
        $hk(titlebarPart.container);
      } else {
        $ik(titlebarPart.container);
      }
      if (fromEvent) {
        auxiliaryWindow.layout();
      }
    }
    const disposables = new $2c();
    const auxiliaryWindow = disposables.add(await this.d.open(options3));
    const editorPartContainer = document.createElement("div");
    editorPartContainer.classList.add("part", "editor");
    editorPartContainer.setAttribute("role", "main");
    editorPartContainer.style.position = "relative";
    auxiliaryWindow.container.appendChild(editorPartContainer);
    const editorPart = disposables.add(this.c.createInstance(AuxiliaryEditorPartImpl, auxiliaryWindow.window.vscodeWindowId, this.b, options3?.state, label3));
    disposables.add(this.b.registerPart(editorPart));
    editorPart.create(editorPartContainer);
    let titlebarPart = void 0;
    let titlebarVisible = false;
    const useCustomTitle = $p && $Cs(this.g);
    if (useCustomTitle) {
      titlebarPart = disposables.add(this.i.createAuxiliaryTitlebarPart(auxiliaryWindow.container, editorPart));
      titlebarVisible = $1lb(this.g, auxiliaryWindow.window, void 0);
      const handleTitleBarVisibilityEvent = () => {
        const oldTitlebarPartVisible = titlebarVisible;
        titlebarVisible = $1lb(this.g, auxiliaryWindow.window, void 0);
        if (oldTitlebarPartVisible !== titlebarVisible) {
          updateTitlebarVisibility(true);
        }
      };
      disposables.add(titlebarPart.onDidChange(() => auxiliaryWindow.layout()));
      disposables.add(this.k.onDidChangePartVisibility(() => handleTitleBarVisibilityEvent()));
      disposables.add($Te((windowId) => {
        if (windowId !== auxiliaryWindow.window.vscodeWindowId) {
          return;
        }
        handleTitleBarVisibilityEvent();
      }));
      updateTitlebarVisibility(false);
    } else {
      disposables.add(this.c.createInstance($0Tb, auxiliaryWindow.window, editorPart));
    }
    const statusbarPart = disposables.add(this.h.createAuxiliaryStatusbarPart(auxiliaryWindow.container));
    let statusbarVisible = this.g.getValue($8Ub_1.a) !== false;
    disposables.add(this.g.onDidChangeConfiguration((e) => {
      if (e.affectsConfiguration($8Ub_1.a)) {
        statusbarVisible = this.g.getValue($8Ub_1.a) !== false;
        updateStatusbarVisibility(true);
      }
    }));
    updateStatusbarVisibility(false);
    const editorCloseListener = disposables.add(Event2.once(editorPart.onWillClose)(() => auxiliaryWindow.window.close()));
    disposables.add(Event2.once(auxiliaryWindow.onUnload)(() => {
      if (disposables.isDisposed) {
        return;
      }
      editorCloseListener.dispose();
      editorPart.close();
      disposables.dispose();
    }));
    disposables.add(Event2.once(this.f.onDidShutdown)(() => disposables.dispose()));
    disposables.add(auxiliaryWindow.onBeforeUnload((event) => {
      for (const group2 of editorPart.groups) {
        for (const editor of group2.editors) {
          const canMoveVeto = editor.canMove(group2.id, this.b.mainPart.activeGroup.id);
          if (typeof canMoveVeto === "string") {
            group2.openEditor(editor);
            event.veto(canMoveVeto);
            break;
          }
        }
      }
    }));
    disposables.add(auxiliaryWindow.onWillLayout((dimension) => {
      const titlebarPartHeight = titlebarPart?.height ?? 0;
      titlebarPart?.layout(dimension.width, titlebarPartHeight, 0, 0);
      const editorPartHeight = dimension.height - computeEditorPartHeightOffset();
      editorPart.layout(dimension.width, editorPartHeight, titlebarPartHeight, 0);
      statusbarPart.layout(dimension.width, statusbarPart.height, dimension.height - statusbarPart.height, 0);
    }));
    auxiliaryWindow.layout();
    const instantiationService = disposables.add(this.c.createChild(new $Ok([$$qb, this.h.createScoped(statusbarPart, disposables)], [$mJ, this.j.createScoped(editorPart, disposables)])));
    return {
      part: editorPart,
      instantiationService,
      disposables
    };
  }
};
$8Ub = $8Ub_1 = __decorate([
  __param(1, $Pk),
  __param(2, $Uob),
  __param(3, $KL),
  __param(4, $kl),
  __param(5, $$qb),
  __param(6, $RTb),
  __param(7, $mJ),
  __param(8, $Vlb)
], $8Ub);
var AuxiliaryEditorPartImpl = class AuxiliaryEditorPartImpl2 extends $6Ub {
  static {
    AuxiliaryEditorPartImpl_1 = this;
  }
  static {
    this.c = 1;
  }
  constructor(windowId, editorPartsView, Fc, groupsLabel, instantiationService, themeService, configurationService, storageService, layoutService, hostService, contextKeyService) {
    const id2 = AuxiliaryEditorPartImpl_1.c++;
    super(editorPartsView, `workbench.parts.auxiliaryEditor.${id2}`, groupsLabel, windowId, instantiationService, themeService, configurationService, storageService, layoutService, hostService, contextKeyService);
    this.Fc = Fc;
    this.Ec = this.B(new $ze());
    this.onWillClose = this.Ec.event;
  }
  removeGroup(group2, preserveFocus) {
    const groupView = this.jc(group2);
    if (this.count === 1 && this.activeGroup === groupView) {
      this.Gc(preserveFocus);
    } else {
      super.removeGroup(group2, preserveFocus);
    }
  }
  Gc(preserveFocus) {
    const restoreFocus = !preserveFocus && this.Zb(this.ub);
    const mostRecentlyActiveGroups = this.Ab.getGroups(
      1
      /* GroupsOrder.MOST_RECENTLY_ACTIVE */
    );
    const nextActiveGroup = mostRecentlyActiveGroups[1];
    if (nextActiveGroup) {
      nextActiveGroup.groupsView.activateGroup(nextActiveGroup);
      if (restoreFocus) {
        nextActiveGroup.focus();
      }
    }
    this.Jc(
      false
      /* do not merge any groups to main part */
    );
  }
  xc() {
    return this.Fc;
  }
  I() {
    return;
  }
  close() {
    return this.Jc(
      true
      /* merge all groups to main part */
    );
  }
  Jc(mergeGroupsToMainPart) {
    let result = true;
    if (mergeGroupsToMainPart) {
      result = this.Kc();
    }
    this.Ec.fire();
    return result;
  }
  Kc() {
    if (!this.groups.some((group2) => group2.count > 0)) {
      return true;
    }
    let targetGroup = void 0;
    for (const group2 of this.Ab.mainPart.getGroups(
      1
      /* GroupsOrder.MOST_RECENTLY_ACTIVE */
    )) {
      if (!group2.isLocked) {
        targetGroup = group2;
        break;
      }
    }
    if (!targetGroup) {
      targetGroup = this.Ab.mainPart.addGroup(
        this.Ab.mainPart.activeGroup,
        this.partOptions.openSideBySideDirection === "right" ? 3 : 1
        /* GroupDirection.DOWN */
      );
    }
    const result = this.mergeAllGroups(targetGroup);
    targetGroup.focus();
    return result;
  }
};
AuxiliaryEditorPartImpl = AuxiliaryEditorPartImpl_1 = __decorate([
  __param(4, $Pk),
  __param(5, $gs),
  __param(6, $kl),
  __param(7, $jv),
  __param(8, $Vlb),
  __param(9, $S4),
  __param(10, $on)
], AuxiliaryEditorPartImpl);

// out-build/vs/workbench/browser/parts/editor/editorParts.js
var $9Ub_1;
var $9Ub = class $9Ub2 extends $3lb {
  static {
    $9Ub_1 = this;
  }
  constructor(b, m, themeService, r2, s) {
    super("workbench.editorParts", themeService, m);
    this.b = b;
    this.m = m;
    this.r = r2;
    this.s = s;
    this.mainPart = this.B(this.u());
    this.a = [this.mainPart];
    this.y = /* @__PURE__ */ new Map();
    this.J = this.B(new $ze());
    this.onDidCreateAuxiliaryEditorPart = this.J.event;
    this.Q = this.F(
      1,
      0
      /* StorageTarget.USER */
    );
    this.R = false;
    this.S = new $gi();
    this.whenReady = this.S.p;
    this.U = new $gi();
    this.whenRestored = this.U.p;
    this.db = (() => {
      const workingSetsRaw = this.m.get(
        $9Ub_1.cb,
        1
        /* StorageScope.WORKSPACE */
      );
      if (workingSetsRaw) {
        return JSON.parse(workingSetsRaw);
      }
      return [];
    })();
    this.gb = this.B(new $ze());
    this.onDidChangeActiveGroup = this.gb.event;
    this.hb = this.B(new $ze());
    this.onDidAddGroup = this.hb.event;
    this.ib = this.B(new $ze());
    this.onDidRemoveGroup = this.ib.event;
    this.jb = this.B(new $ze());
    this.onDidMoveGroup = this.jb.event;
    this.kb = this.B(new $ze());
    this.onDidActivateGroup = this.kb.event;
    this.lb = this.B(new $ze());
    this.onDidChangeGroupIndex = this.lb.event;
    this.mb = this.B(new $ze());
    this.onDidChangeGroupLocked = this.mb.event;
    this.nb = this.B(new $ze());
    this.onDidChangeGroupMaximized = this.nb.event;
    this.pb = /* @__PURE__ */ new Map();
    this.qb = /* @__PURE__ */ new Map();
    this.tb = /* @__PURE__ */ new Map();
    this.ub = /* @__PURE__ */ new Map();
    this.vb = this.B(new $_c());
    this.B(this.registerPart(this.mainPart));
    this.W();
    this.t();
  }
  t() {
    this.B(this.H(1, this.q)((e) => this.ab(e)));
    this.whenReady.then(() => this.rb());
  }
  u() {
    return this.b.createInstance($7Ub, this);
  }
  getScopedInstantiationService(part) {
    if (part === this.mainPart) {
      if (!this.y.has(part.windowId)) {
        this.b.invokeFunction((accessor) => {
          const editorService = accessor.get($mJ);
          this.y.set(part.windowId, this.B(this.b.createChild(new $Ok([$mJ, editorService.createScoped("main", this.q)]))));
        });
      }
    }
    return this.y.get(part.windowId) ?? this.b;
  }
  async createAuxiliaryEditorPart(options3) {
    const { part, instantiationService, disposables } = await this.b.createInstance($8Ub, this).create(this.O(this.f.size), options3);
    this.y.set(part.windowId, instantiationService);
    disposables.add($1c(() => this.y.delete(part.windowId)));
    this.hb.fire(part.activeGroup);
    this.J.fire(part);
    return part;
  }
  //#endregion
  //#region Registration
  registerPart(part) {
    const disposables = this.B(new $2c());
    disposables.add(super.registerPart(part));
    this.M(part, disposables);
    return disposables;
  }
  g(part) {
    super.g(part);
    this.parts.forEach((part2, index) => {
      if (part2 === this.mainPart) {
        return;
      }
      part2.notifyGroupsLabelChange(this.O(index));
    });
  }
  M(part, disposables) {
    disposables.add(part.onDidFocus(() => {
      this.N(part, true);
      if (this.f.size > 1) {
        this.gb.fire(this.activeGroup);
      }
    }));
    disposables.add($1c(() => this.N(part)));
    disposables.add(part.onDidChangeActiveGroup((group2) => this.gb.fire(group2)));
    disposables.add(part.onDidAddGroup((group2) => this.hb.fire(group2)));
    disposables.add(part.onDidRemoveGroup((group2) => this.ib.fire(group2)));
    disposables.add(part.onDidMoveGroup((group2) => this.jb.fire(group2)));
    disposables.add(part.onDidActivateGroup((group2) => this.kb.fire(group2)));
    disposables.add(part.onDidChangeGroupMaximized((maximized) => this.nb.fire(maximized)));
    disposables.add(part.onDidChangeGroupIndex((group2) => this.lb.fire(group2)));
    disposables.add(part.onDidChangeGroupLocked((group2) => this.mb.fire(group2)));
  }
  N(part, makeMostRecentlyActive) {
    const index = this.a.indexOf(part);
    if (index !== -1) {
      this.a.splice(index, 1);
    }
    if (makeMostRecentlyActive) {
      this.a.unshift(part);
    }
  }
  O(index) {
    return localize(3512, null, index + 1);
  }
  getPart(groupOrElement) {
    if (this.f.size > 1) {
      if ($Uj(groupOrElement)) {
        const element = groupOrElement;
        return this.j(element.ownerDocument);
      } else {
        const group2 = groupOrElement;
        let id2;
        if (typeof group2 === "number") {
          id2 = group2;
        } else {
          id2 = group2.id;
        }
        for (const part of this.f) {
          if (part.hasGroup(id2)) {
            return part;
          }
        }
      }
    }
    return this.mainPart;
  }
  static {
    this.P = "editorparts.state";
  }
  get isReady() {
    return this.R;
  }
  async W() {
    await this.mainPart.whenReady;
    if (this.mainPart.willRestoreState) {
      const state = this.X();
      if (state) {
        await this.$(state);
      }
    }
    const mostRecentActivePart = this.a.at(0);
    mostRecentActivePart?.activeGroup.focus();
    this.R = true;
    this.S.complete();
    await Promise.allSettled(this.parts.map((part) => part.whenRestored));
    this.U.complete();
  }
  X() {
    return this.Q[$9Ub_1.P];
  }
  I() {
    const state = this.Z();
    if (state.auxiliary.length === 0) {
      delete this.Q[$9Ub_1.P];
    } else {
      this.Q[$9Ub_1.P] = state;
    }
  }
  Z() {
    return {
      auxiliary: this.parts.filter((part) => part !== this.mainPart).map((part) => {
        const auxiliaryWindow = this.r.getWindow(part.windowId);
        return {
          state: part.createState(),
          ...auxiliaryWindow?.createState()
        };
      }),
      mru: this.a.map((part) => this.parts.indexOf(part))
    };
  }
  async $(state) {
    if (state.auxiliary.length) {
      const auxiliaryEditorPartPromises = [];
      for (const auxiliaryEditorPartState of state.auxiliary) {
        auxiliaryEditorPartPromises.push(this.createAuxiliaryEditorPart(auxiliaryEditorPartState));
      }
      await Promise.allSettled(auxiliaryEditorPartPromises);
      if (state.mru.length === this.parts.length) {
        this.a = state.mru.map((index) => this.parts[index]);
      } else {
        this.a = [...this.parts];
      }
      await Promise.allSettled(this.parts.map((part) => part.whenReady));
    }
  }
  get hasRestorableState() {
    return this.parts.some((part) => part.hasRestorableState);
  }
  ab(e) {
    if (e.external && e.scope === 1) {
      this.G(e.scope);
      const state = this.X();
      if (state) {
        this.bb(state);
      }
    }
  }
  async bb(state) {
    for (const part of this.parts) {
      if (part === this.mainPart) {
        continue;
      }
      for (const group2 of part.getGroups(
        1
        /* GroupsOrder.MOST_RECENTLY_ACTIVE */
      )) {
        await group2.closeAllEditors({ excludeConfirming: true });
      }
      const closed = part.close();
      if (!closed) {
        return false;
      }
    }
    if (state !== "empty") {
      await this.$(state);
    }
    return true;
  }
  static {
    this.cb = "editor.workingSets";
  }
  saveWorkingSet(name) {
    const workingSet = {
      id: $ps(),
      name,
      main: this.mainPart.createState(),
      auxiliary: this.Z()
    };
    this.db.push(workingSet);
    this.fb();
    return {
      id: workingSet.id,
      name: workingSet.name
    };
  }
  getWorkingSets() {
    return this.db.map((workingSet) => ({ id: workingSet.id, name: workingSet.name }));
  }
  deleteWorkingSet(workingSet) {
    const index = this.eb(workingSet);
    if (typeof index === "number") {
      this.db.splice(index, 1);
      this.fb();
    }
  }
  async applyWorkingSet(workingSet, options3) {
    let workingSetState;
    if (workingSet === "empty") {
      workingSetState = "empty";
    } else {
      workingSetState = this.db[this.eb(workingSet) ?? -1];
    }
    if (!workingSetState) {
      return false;
    }
    const applied = await this.bb(workingSetState === "empty" ? workingSetState : workingSetState.auxiliary);
    if (!applied) {
      return false;
    }
    await this.mainPart.applyState(workingSetState === "empty" ? workingSetState : workingSetState.main, options3);
    if (!options3?.preserveFocus) {
      const mostRecentActivePart = this.a.at(0);
      if (mostRecentActivePart) {
        await mostRecentActivePart.whenReady;
        mostRecentActivePart.activeGroup.focus();
      }
    }
    return true;
  }
  eb(workingSet) {
    for (let i2 = 0; i2 < this.db.length; i2++) {
      if (this.db[i2].id === workingSet.id) {
        return i2;
      }
    }
    return void 0;
  }
  fb() {
    this.m.store(
      $9Ub_1.cb,
      JSON.stringify(this.db),
      1,
      1
      /* StorageTarget.MACHINE */
    );
  }
  //#endregion
  //#region Group Management
  get activeGroup() {
    return this.activePart.activeGroup;
  }
  get sideGroup() {
    return this.activePart.sideGroup;
  }
  get groups() {
    return this.getGroups();
  }
  get count() {
    return this.groups.length;
  }
  getGroups(order = 0) {
    if (this.f.size > 1) {
      let parts;
      switch (order) {
        case 2:
        case 0:
          parts = this.parts;
          break;
        case 1:
          parts = $Rb([...this.a, ...this.parts]);
          break;
      }
      return parts.map((part) => part.getGroups(order)).flat();
    }
    return this.mainPart.getGroups(order);
  }
  getGroup(identifier2) {
    if (this.f.size > 1) {
      for (const part of this.f) {
        const group2 = part.getGroup(identifier2);
        if (group2) {
          return group2;
        }
      }
    }
    return this.mainPart.getGroup(identifier2);
  }
  ob(group2) {
    let groupView;
    if (typeof group2 === "number") {
      groupView = this.getGroup(group2);
    } else {
      groupView = group2;
    }
    if (!groupView) {
      throw new Error("Invalid editor group provided!");
    }
    return groupView;
  }
  activateGroup(group2) {
    return this.getPart(group2).activateGroup(group2);
  }
  getSize(group2) {
    return this.getPart(group2).getSize(group2);
  }
  setSize(group2, size) {
    this.getPart(group2).setSize(group2, size);
  }
  arrangeGroups(arrangement, group2 = this.activePart.activeGroup) {
    this.getPart(group2).arrangeGroups(arrangement, group2);
  }
  toggleMaximizeGroup(group2 = this.activePart.activeGroup) {
    this.getPart(group2).toggleMaximizeGroup(group2);
  }
  toggleExpandGroup(group2 = this.activePart.activeGroup) {
    this.getPart(group2).toggleExpandGroup(group2);
  }
  restoreGroup(group2) {
    return this.getPart(group2).restoreGroup(group2);
  }
  applyLayout(layout) {
    this.activePart.applyLayout(layout);
  }
  getLayout() {
    return this.activePart.getLayout();
  }
  get orientation() {
    return this.activePart.orientation;
  }
  setGroupOrientation(orientation) {
    this.activePart.setGroupOrientation(orientation);
  }
  findGroup(scope, source = this.activeGroup, wrap) {
    const sourcePart = this.getPart(source);
    if (this.f.size > 1) {
      const groups = this.getGroups(
        2
        /* GroupsOrder.GRID_APPEARANCE */
      );
      if (scope.location === 0 || scope.location === 1) {
        return scope.location === 0 ? groups[0] : groups[groups.length - 1];
      }
      const group2 = sourcePart.findGroup(scope, source, false);
      if (group2) {
        return group2;
      }
      if (scope.location === 2 || scope.location === 3) {
        const sourceGroup = this.ob(source);
        const index = groups.indexOf(sourceGroup);
        if (scope.location === 2) {
          let nextGroup = groups[index + 1];
          if (!nextGroup && wrap) {
            nextGroup = groups[0];
          }
          return nextGroup;
        } else {
          let previousGroup = groups[index - 1];
          if (!previousGroup && wrap) {
            previousGroup = groups[groups.length - 1];
          }
          return previousGroup;
        }
      }
    }
    return sourcePart.findGroup(scope, source, wrap);
  }
  addGroup(location3, direction) {
    return this.getPart(location3).addGroup(location3, direction);
  }
  removeGroup(group2) {
    this.getPart(group2).removeGroup(group2);
  }
  moveGroup(group2, location3, direction) {
    return this.getPart(group2).moveGroup(group2, location3, direction);
  }
  mergeGroup(group2, target, options3) {
    return this.getPart(group2).mergeGroup(group2, target, options3);
  }
  mergeAllGroups(target) {
    return this.activePart.mergeAllGroups(target);
  }
  copyGroup(group2, location3, direction) {
    return this.getPart(group2).copyGroup(group2, location3, direction);
  }
  createEditorDropTarget(container2, delegate) {
    return this.getPart(container2).createEditorDropTarget(container2, delegate);
  }
  rb() {
    this.B(this.onDidChangeActiveGroup(() => this.sb()));
    this.groups.forEach((group2) => this.wb(group2));
    this.B(this.onDidAddGroup((group2) => this.wb(group2)));
    this.B(this.onDidRemoveGroup((group2) => {
      this.qb.delete(group2.id);
      this.ub.delete(group2.id);
      this.vb.deleteAndDispose(group2.id);
    }));
  }
  sb() {
    const activeGroupScopedContextKeys = this.qb.get(this.activeGroup.id);
    if (!activeGroupScopedContextKeys) {
      return;
    }
    for (const [key2, globalContextKey] of this.pb) {
      const scopedContextKey = activeGroupScopedContextKeys.get(key2);
      if (scopedContextKey) {
        globalContextKey.set(scopedContextKey.get());
      } else {
        globalContextKey.reset();
      }
    }
  }
  bind(contextKey, group2) {
    let globalContextKey = this.pb.get(contextKey.key);
    if (!globalContextKey) {
      globalContextKey = contextKey.bindTo(this.s);
      this.pb.set(contextKey.key, globalContextKey);
    }
    let groupScopedContextKeys = this.qb.get(group2.id);
    if (!groupScopedContextKeys) {
      groupScopedContextKeys = /* @__PURE__ */ new Map();
      this.qb.set(group2.id, groupScopedContextKeys);
    }
    let scopedContextKey = groupScopedContextKeys.get(contextKey.key);
    if (!scopedContextKey) {
      scopedContextKey = contextKey.bindTo(group2.scopedContextKeyService);
      groupScopedContextKeys.set(contextKey.key, scopedContextKey);
    }
    const that = this;
    return {
      get() {
        return scopedContextKey.get();
      },
      set(value) {
        if (that.activeGroup === group2) {
          globalContextKey.set(value);
        }
        scopedContextKey.set(value);
      },
      reset() {
        if (that.activeGroup === group2) {
          globalContextKey.reset();
        }
        scopedContextKey.reset();
      }
    };
  }
  registerContextKeyProvider(provider) {
    if (this.tb.has(provider.contextKey.key) || this.pb.has(provider.contextKey.key)) {
      throw new Error(`A context key provider for key ${provider.contextKey.key} already exists.`);
    }
    this.tb.set(provider.contextKey.key, provider);
    const setContextKeyForGroups = () => {
      for (const group2 of this.groups) {
        this.xb(group2, provider);
      }
    };
    setContextKeyForGroups();
    const onDidChange = provider.onDidChange?.(() => setContextKeyForGroups());
    return $1c(() => {
      onDidChange?.dispose();
      this.pb.delete(provider.contextKey.key);
      this.qb.forEach((scopedContextKeys) => scopedContextKeys.delete(provider.contextKey.key));
      this.tb.delete(provider.contextKey.key);
      this.ub.forEach((registeredContextKeys) => registeredContextKeys.delete(provider.contextKey.key));
    });
  }
  wb(group2) {
    const disposable = group2.onDidActiveEditorChange(() => {
      for (const contextKeyProvider of this.tb.values()) {
        this.xb(group2, contextKeyProvider);
      }
    });
    this.vb.set(group2.id, disposable);
  }
  xb(group2, provider) {
    let groupRegisteredContextKeys = this.ub.get(group2.id);
    if (!groupRegisteredContextKeys) {
      groupRegisteredContextKeys = /* @__PURE__ */ new Map();
      this.ub.set(group2.id, groupRegisteredContextKeys);
    }
    let scopedRegisteredContextKey = groupRegisteredContextKeys.get(provider.contextKey.key);
    if (!scopedRegisteredContextKey) {
      scopedRegisteredContextKey = this.bind(provider.contextKey, group2);
      groupRegisteredContextKeys.set(provider.contextKey.key, scopedRegisteredContextKey);
    }
    scopedRegisteredContextKey.set(provider.getGroupContextKeyValue(group2));
  }
  //#endregion
  //#region Main Editor Part Only
  get partOptions() {
    return this.mainPart.partOptions;
  }
  get onDidChangeEditorPartOptions() {
    return this.mainPart.onDidChangeEditorPartOptions;
  }
};
$9Ub = $9Ub_1 = __decorate([
  __param(0, $Pk),
  __param(1, $jv),
  __param(2, $gs),
  __param(3, $Uob),
  __param(4, $on)
], $9Ub);
$SC(
  $iJ,
  $9Ub,
  0
  /* InstantiationType.Eager */
);

// out-build/vs/workbench/browser/parts/compositePart.js
var $0Ub = class extends Part {
  constructor(pb, qb, rb, layoutService, sb, tb, ub, themeService, vb, wb, xb, yb, zb, Ab, Bb, id2, options3) {
    super(id2, options3, themeService, qb, layoutService);
    this.pb = pb;
    this.qb = qb;
    this.rb = rb;
    this.sb = sb;
    this.tb = tb;
    this.ub = ub;
    this.vb = vb;
    this.wb = wb;
    this.xb = xb;
    this.yb = yb;
    this.zb = zb;
    this.Ab = Ab;
    this.Bb = Bb;
    this.b = this.B(new $ze());
    this.y = this.B(new $ze());
    this.eb = /* @__PURE__ */ new Map();
    this.fb = /* @__PURE__ */ new Map();
    this.ib = /* @__PURE__ */ new Map();
    this.mb = this.B(new $4c());
    this.hb = qb.get(wb, 1, this.xb);
    this.db = this.B($KZ());
  }
  Cb(id2, focus) {
    if (this.gb?.getId() === id2) {
      if (focus) {
        this.gb.focus();
      }
      return this.gb;
    }
    if (!this.element) {
      return;
    }
    return this.Db(id2, focus);
  }
  Db(id2, focus = false) {
    const currentCompositeOpenToken = $mW.nextId();
    this.nb = currentCompositeOpenToken;
    if (this.gb) {
      this.Lb();
    }
    this.Hb(id2);
    const composite = this.Eb(id2, true);
    if (this.nb !== currentCompositeOpenToken || this.gb && this.gb.getId() !== composite.getId()) {
      return void 0;
    }
    if (this.gb?.getId() === composite.getId()) {
      if (focus) {
        composite.focus();
      }
      this.b.fire({ composite, focus });
      return composite;
    }
    this.Fb(composite);
    if (focus) {
      composite.focus();
    }
    if (composite) {
      this.b.fire({ composite, focus });
    }
    return composite;
  }
  Eb(id2, isActive2) {
    const compositeItem = this.ib.get(id2);
    if (compositeItem) {
      return compositeItem.composite;
    }
    const compositeDescriptor = this.vb.getComposite(id2);
    if (compositeDescriptor) {
      const that = this;
      const compositeProgressIndicator = new $5ob($Kg(this.kb), new class extends $6ob {
        constructor() {
          super(compositeDescriptor.id, !!isActive2);
          this.B(that.b.event((e) => this.f(e.composite.getId())));
          this.B(that.y.event((e) => this.g(e.getId())));
        }
      }());
      const compositeInstantiationService = this.B(this.ub.createChild(new $Ok(
        [$ZJ, compositeProgressIndicator]
        // provide the editor progress service for any editors instantiated within the composite
      )));
      const composite = compositeDescriptor.instantiate(compositeInstantiationService);
      const disposable = new $2c();
      this.ib.set(id2, { composite, disposable, progress: compositeProgressIndicator });
      disposable.add(composite.onTitleAreaUpdate(() => this.Gb(composite.getId()), this));
      disposable.add(compositeInstantiationService);
      return composite;
    }
    throw new Error(`Unable to find composite with id ${id2}`);
  }
  Fb(composite) {
    this.gb = composite;
    const id2 = this.gb.getId();
    if (id2 !== this.xb) {
      this.qb.store(
        this.wb,
        id2,
        1,
        1
        /* StorageTarget.MACHINE */
      );
    } else {
      this.qb.remove(
        this.wb,
        1
        /* StorageScope.WORKSPACE */
      );
    }
    this.hb = this.gb.getId();
    let compositeContainer = this.eb.get(composite.getId());
    if (!compositeContainer) {
      compositeContainer = $(".composite");
      compositeContainer.classList.add(...this.zb.split(" "));
      compositeContainer.id = composite.getId();
      composite.create(compositeContainer);
      composite.updateStyles();
      this.eb.set(composite.getId(), compositeContainer);
    }
    if (!this.gb || composite.getId() !== this.gb.getId()) {
      return void 0;
    }
    const contentArea = this.R();
    contentArea?.appendChild(compositeContainer);
    $hk(compositeContainer);
    const toolBar = $Kg(this.bb);
    toolBar.actionRunner = composite.getActionRunner();
    const descriptor = this.vb.getComposite(composite.getId());
    if (descriptor && descriptor.name !== composite.getTitle()) {
      this.Hb(composite.getId(), composite.getTitle());
    }
    let actionsBinding = this.fb.get(composite.getId());
    if (!actionsBinding) {
      actionsBinding = this.Ib(composite);
      this.fb.set(composite.getId(), actionsBinding);
    }
    actionsBinding();
    this.mb.value = toolBar.actionRunner.onDidRun((e) => {
      if (e.error && !$kb(e.error)) {
        this.pb.error(e.error);
      }
    });
    composite.setVisible(true);
    if (!this.gb || composite.getId() !== this.gb.getId()) {
      return;
    }
    if (this.lb) {
      composite.layout(this.lb);
    }
    if (this.ob) {
      composite.setBoundarySashes(this.ob);
    }
  }
  Gb(compositeId) {
    const composite = this.ib.get(compositeId);
    if (composite) {
      this.Hb(compositeId, composite.composite.getTitle());
    }
    if (this.gb?.getId() === compositeId) {
      const actionsBinding = this.Ib(this.gb);
      this.fb.set(this.gb.getId(), actionsBinding);
      actionsBinding();
    } else {
      this.fb.delete(compositeId);
    }
  }
  Hb(compositeId, compositeTitle) {
    const compositeDescriptor = this.vb.getComposite(compositeId);
    if (!compositeDescriptor || !this.jb) {
      return;
    }
    if (!compositeTitle) {
      compositeTitle = compositeDescriptor.name;
    }
    const keybinding = this.sb.lookupKeybinding(compositeId);
    this.jb.updateTitle(compositeId, compositeTitle, keybinding?.getLabel() ?? void 0);
    const toolBar = $Kg(this.bb);
    toolBar.setAriaLabel(localize(3100, null, compositeTitle));
  }
  Ib(composite) {
    const menuIds = composite?.getMenuIds();
    const primaryActions = composite?.getActions().slice(0) || [];
    const secondaryActions = composite?.getSecondaryActions().slice(0) || [];
    const toolBar = $Kg(this.bb);
    toolBar.context = this.Rb();
    return () => toolBar.setActions($MZ(primaryActions), $MZ(secondaryActions), menuIds);
  }
  Jb() {
    return this.gb;
  }
  Kb() {
    return this.hb;
  }
  Lb() {
    if (!this.gb) {
      return void 0;
    }
    const composite = this.gb;
    this.gb = void 0;
    const compositeContainer = this.eb.get(composite.getId());
    composite.setVisible(false);
    if (compositeContainer) {
      compositeContainer.remove();
      $ik(compositeContainer);
    }
    this.kb?.stop().hide();
    if (this.bb) {
      this.Ib()();
    }
    this.y.fire(composite);
    return composite;
  }
  O(parent) {
    const titleArea = $bk(parent, $(".composite"));
    titleArea.classList.add("title");
    this.jb = this.Nb(titleArea);
    const titleActionsContainer = $bk(titleArea, $(".title-actions"));
    this.bb = this.B(this.ub.createInstance($3$, titleActionsContainer, {
      actionViewItemProvider: (action, options3) => this.Qb(action, options3),
      orientation: 0,
      getKeyBinding: (action) => this.sb.lookupKeybinding(action.id),
      anchorAlignmentProvider: () => this.Tb(),
      toggleMenuTitle: localize(3101, null),
      telemetrySource: this.yb,
      hoverDelegate: this.db
    }));
    this.Ib()();
    return titleArea;
  }
  Nb(parent) {
    const titleContainer = $bk(parent, $(".title-label"));
    const titleLabel = $bk(titleContainer, $("h2"));
    this.cb = titleLabel;
    const hover = this.B(this.tb.setupManagedHover($JZ("mouse"), titleLabel, ""));
    const $this = this;
    return {
      updateTitle: (id2, title, keybinding) => {
        if (!this.gb || this.gb.getId() === id2) {
          titleLabel.innerText = title;
          hover.update(keybinding ? localize(3102, null, title, keybinding) : title);
        }
      },
      updateStyles: () => {
        titleLabel.style.color = $this.Ab ? $this.z($this.Ab) || "" : "";
        const borderColor = $this.Bb ? $this.z($this.Bb) : void 0;
        parent.style.borderBottom = borderColor ? `1px solid ${borderColor}` : "";
      }
    };
  }
  Ob() {
    return $(".composite");
  }
  Pb() {
    return $(".composite");
  }
  updateStyles() {
    super.updateStyles();
    const titleLabel = $Kg(this.jb);
    titleLabel.updateStyles();
  }
  Qb(action, options3) {
    if (this.gb) {
      return this.gb.getActionViewItem(action, options3);
    }
    return $X$(this.ub, action, options3);
  }
  Rb() {
    if (this.gb) {
      return this.gb.getActionsContext();
    }
    return null;
  }
  Q(parent) {
    const contentContainer = $bk(parent, $(".content"));
    this.kb = this.B(new $02(contentContainer, $s$));
    this.kb.hide();
    return contentContainer;
  }
  getProgressIndicator(id2) {
    const compositeItem = this.ib.get(id2);
    return compositeItem ? compositeItem.progress : void 0;
  }
  Tb() {
    return 1;
  }
  layout(width2, height, top2, left) {
    super.layout(width2, height, top2, left);
    this.lb = $rj.lift(super.Z(width2, height).contentSize);
    this.gb?.layout(this.lb);
  }
  setBoundarySashes(sashes) {
    this.ob = sashes;
    this.gb?.setBoundarySashes(sashes);
  }
  Ub(compositeId) {
    if (this.gb?.getId() === compositeId) {
      return false;
    }
    this.eb.delete(compositeId);
    this.fb.delete(compositeId);
    const compositeItem = this.ib.get(compositeId);
    if (compositeItem) {
      compositeItem.composite.dispose();
      $Xc(compositeItem.disposable);
      this.ib.delete(compositeId);
    }
    return true;
  }
  dispose() {
    this.eb.clear();
    this.fb.clear();
    this.ib.forEach((compositeItem) => {
      compositeItem.composite.dispose();
      $Xc(compositeItem.disposable);
    });
    this.ib.clear();
    super.dispose();
  }
};

// out-build/vs/workbench/browser/parts/compositeBar.js
var $$Ub = class {
  constructor(a, b, d, f, g, h3) {
    this.a = a;
    this.b = b;
    this.d = d;
    this.f = f;
    this.g = g;
    this.h = h3;
  }
  drop(data, targetCompositeId, originalEvent, before) {
    const dragData = data.getData();
    if (dragData.type === "composite") {
      const currentContainer = this.a.getViewContainerById(dragData.id);
      const currentLocation = this.a.getViewContainerLocation(currentContainer);
      let moved = false;
      if (currentLocation === this.b) {
        if (targetCompositeId) {
          this.g(dragData.id, targetCompositeId, before);
          moved = true;
        }
      } else {
        this.a.moveViewContainerToLocation(currentContainer, this.b, this.j(targetCompositeId, before), "dnd");
        moved = true;
      }
      if (moved) {
        this.f(currentContainer.id, true);
      }
    }
    if (dragData.type === "view") {
      const viewToMove = this.a.getViewDescriptorById(dragData.id);
      if (viewToMove && viewToMove.canMoveView) {
        this.a.moveViewToLocation(viewToMove, this.b, "dnd");
        const newContainer = this.a.getViewContainerByViewId(viewToMove.id);
        if (targetCompositeId) {
          this.g(newContainer.id, targetCompositeId, before);
        }
        this.f(newContainer.id, true).then((composite) => {
          composite?.openView(viewToMove.id, true);
        });
      }
    }
  }
  onDragEnter(data, targetCompositeId, originalEvent) {
    return this.k(data, targetCompositeId);
  }
  onDragOver(data, targetCompositeId, originalEvent) {
    return this.k(data, targetCompositeId);
  }
  j(targetId, before2d) {
    if (!targetId) {
      return void 0;
    }
    const items = this.h();
    const before = this.d === 0 ? before2d?.horizontallyBefore : before2d?.verticallyBefore;
    return items.filter((item) => item.visible).findIndex((item) => item.id === targetId) + (before ? 0 : 1);
  }
  k(data, targetCompositeId) {
    const dragData = data.getData();
    if (dragData.type === "composite") {
      const currentContainer = this.a.getViewContainerById(dragData.id);
      const currentLocation = this.a.getViewContainerLocation(currentContainer);
      if (currentLocation === this.b) {
        return dragData.id !== targetCompositeId;
      }
      return true;
    } else {
      const viewDescriptor3 = this.a.getViewDescriptorById(dragData.id);
      if (!viewDescriptor3 || !viewDescriptor3.canMoveView) {
        return false;
      }
      return true;
    }
  }
};
var CompositeBarDndCallbacks = class {
  constructor(b, d, f, g, h3) {
    this.b = b;
    this.d = d;
    this.f = f;
    this.g = g;
    this.h = h3;
    this.a = void 0;
  }
  onDragOver(e) {
    const visibleItems = this.f.visibleItems;
    if (!visibleItems.length || e.eventData.target && $Dj(e.eventData.target, this.d)) {
      this.a = this.k(this.b, false, false, true);
      return;
    }
    const insertAtFront = this.j(this.d, e.eventData);
    const target = insertAtFront ? visibleItems[0] : visibleItems[visibleItems.length - 1];
    const validDropTarget = this.g.onDragOver(e.dragAndDropData, target.id, e.eventData);
    $Job(e.eventData.dataTransfer, "move", validDropTarget);
    this.a = this.k(this.b, validDropTarget, insertAtFront, true);
  }
  onDragLeave(e) {
    this.a = this.k(this.b, false, false, false);
  }
  onDragEnd(e) {
    this.a = this.k(this.b, false, false, false);
  }
  onDrop(e) {
    const visibleItems = this.f.visibleItems;
    let targetId = void 0;
    if (visibleItems.length) {
      targetId = this.j(this.d, e.eventData) ? visibleItems[0].id : visibleItems[visibleItems.length - 1].id;
    }
    this.g.drop(e.dragAndDropData, targetId, e.eventData, this.a);
    this.a = this.k(this.b, false, false, false);
  }
  j(element, event) {
    const rect = element.getBoundingClientRect();
    const posX = event.clientX;
    const posY = event.clientY;
    switch (this.h) {
      case 0:
        return posX < rect.left;
      case 1:
        return posY < rect.top;
    }
  }
  k(element, showFeedback, front, isDragging) {
    element.classList.toggle("dragged-over", isDragging);
    element.classList.toggle("dragged-over-head", showFeedback && front);
    element.classList.toggle("dragged-over-tail", showFeedback && !front);
    if (!showFeedback) {
      return void 0;
    }
    return { verticallyBefore: front, horizontallyBefore: front };
  }
};
var $_Ub = class $_Ub2 extends $qZ {
  constructor(items, H, I, J, L) {
    super();
    this.H = H;
    this.I = I;
    this.J = J;
    this.L = L;
    this.a = this.B(new $ze());
    this.onDidChange = this.a.event;
    this.t = new CompositeBarModel(items, H);
    this.w = [];
    this.y = /* @__PURE__ */ new Map();
    this.N(this.t.visibleItems);
  }
  getCompositeBarItems() {
    return [...this.t.items];
  }
  setCompositeBarItems(items) {
    this.t.setItems(items);
    this.O(true);
  }
  getPinnedComposites() {
    return this.t.pinnedItems;
  }
  getPinnedCompositeIds() {
    return this.getPinnedComposites().map((c) => c.id);
  }
  getVisibleComposites() {
    return this.t.visibleItems;
  }
  create(parent) {
    const actionBarDiv = parent.appendChild($(".composite-bar"));
    this.h = this.B(new $LZ(actionBarDiv, {
      actionViewItemProvider: (action, options3) => {
        if (action instanceof $Dqb) {
          return this.r;
        }
        const item = this.t.findItem(action.id);
        return item && this.I.createInstance($Fqb, { ...options3, draggable: true, colors: this.H.colors, icon: this.H.icon, hoverOptions: this.H.activityHoverOptions, compact: this.H.compact }, action, item.pinnedAction, item.toggleBadgeAction, (compositeId) => this.H.getContextMenuActionsForComposite(compositeId), () => this.getContextMenuActions(), this.H.dndHandler, this);
      },
      orientation: this.H.orientation,
      ariaLabel: localize(3088, null),
      ariaRole: "tablist",
      preventLoopNavigation: this.H.preventLoopNavigation,
      triggerKeys: { keyDown: true }
    }));
    this.B($_i(parent, $7j.CONTEXT_MENU, (e) => this.Q(getWindow(parent), e)));
    this.B($mZ.addTarget(parent));
    this.B($_i(parent, EventType.Contextmenu, (e) => this.Q(getWindow(parent), e)));
    const dndCallback = new CompositeBarDndCallbacks(parent, actionBarDiv, this.t, this.H.dndHandler, this.H.orientation);
    this.B($Iob.INSTANCE.registerTarget(parent, dndCallback));
    return actionBarDiv;
  }
  focus(index) {
    this.h?.focus(index);
  }
  recomputeSizes() {
    this.N(this.t.visibleItems);
    this.O();
  }
  layout(dimension) {
    this.g = dimension;
    if (dimension.height === 0 || dimension.width === 0) {
      return;
    }
    if (this.y.size === 0) {
      this.N(this.t.visibleItems);
    }
    this.O();
  }
  addComposite({ id: id2, name, order, requestedIndex }) {
    if (this.t.add(id2, name, order, requestedIndex)) {
      this.N([this.t.findItem(id2)]);
      this.O();
    }
  }
  removeComposite(id2) {
    if (this.isPinned(id2)) {
      this.unpin(id2);
    }
    if (this.t.remove(id2)) {
      this.O();
    }
  }
  hideComposite(id2) {
    if (this.t.hide(id2)) {
      this.M(id2);
      this.O();
    }
  }
  activateComposite(id2) {
    const previousActiveItem = this.t.activeItem;
    if (this.t.activate(id2)) {
      if (this.w.indexOf(id2) === -1 || !!this.t.activeItem && !this.t.activeItem.pinned || previousActiveItem && !previousActiveItem.pinned) {
        this.O();
      }
    }
  }
  deactivateComposite(id2) {
    const previousActiveItem = this.t.activeItem;
    if (this.t.deactivate()) {
      if (previousActiveItem && !previousActiveItem.pinned) {
        this.O();
      }
    }
  }
  async pin(compositeId, open2) {
    if (this.t.setPinned(compositeId, true)) {
      this.O();
      if (open2) {
        await this.H.openComposite(compositeId);
        this.activateComposite(compositeId);
      }
    }
  }
  unpin(compositeId) {
    if (this.t.setPinned(compositeId, false)) {
      this.O();
      this.M(compositeId);
    }
  }
  areBadgesEnabled(compositeId) {
    return this.L.getViewContainerBadgeEnablementState(compositeId);
  }
  toggleBadgeEnablement(compositeId) {
    this.L.setViewContainerBadgeEnablementState(compositeId, !this.areBadgesEnabled(compositeId));
    this.O();
    const item = this.t.findItem(compositeId);
    if (item) {
      item.activityAction.activity = item.activityAction.activity;
    }
  }
  M(compositeId) {
    const defaultCompositeId = this.H.getDefaultCompositeId();
    if (!this.t.activeItem || this.t.activeItem.id !== compositeId) {
      return;
    }
    this.deactivateComposite(compositeId);
    if (defaultCompositeId && defaultCompositeId !== compositeId && this.isPinned(defaultCompositeId)) {
      this.H.openComposite(defaultCompositeId, true);
    } else {
      const visibleComposite = this.w.find((cid) => cid !== compositeId);
      if (visibleComposite) {
        this.H.openComposite(visibleComposite);
      }
    }
  }
  isPinned(compositeId) {
    const item = this.t.findItem(compositeId);
    return item?.pinned;
  }
  move(compositeId, toCompositeId, before) {
    if (before !== void 0) {
      const fromIndex = this.t.items.findIndex((c) => c.id === compositeId);
      let toIndex = this.t.items.findIndex((c) => c.id === toCompositeId);
      if (fromIndex >= 0 && toIndex >= 0) {
        if (!before && fromIndex > toIndex) {
          toIndex++;
        }
        if (before && fromIndex < toIndex) {
          toIndex--;
        }
        if (toIndex < this.t.items.length && toIndex >= 0 && toIndex !== fromIndex) {
          if (this.t.move(this.t.items[fromIndex].id, this.t.items[toIndex].id)) {
            setTimeout(() => this.O(), 0);
          }
        }
      }
    } else {
      if (this.t.move(compositeId, toCompositeId)) {
        setTimeout(() => this.O(), 0);
      }
    }
  }
  getAction(compositeId) {
    const item = this.t.findItem(compositeId);
    return item?.activityAction;
  }
  N(items) {
    const size = this.H.compositeSize;
    if (size) {
      items.forEach((composite) => this.y.set(composite.id, size));
    } else {
      const compositeSwitcherBar = this.h;
      if (compositeSwitcherBar && this.g && this.g.height !== 0 && this.g.width !== 0) {
        const currentItemsLength = compositeSwitcherBar.viewItems.length;
        compositeSwitcherBar.push(items.map((composite) => composite.activityAction));
        items.map((composite, index) => this.y.set(composite.id, this.H.orientation === 1 ? compositeSwitcherBar.getHeight(currentItemsLength + index) : compositeSwitcherBar.getWidth(currentItemsLength + index)));
        items.forEach(() => compositeSwitcherBar.pull(compositeSwitcherBar.viewItems.length - 1));
      }
    }
  }
  O(donotTrigger) {
    const compositeSwitcherBar = this.h;
    if (!compositeSwitcherBar || !this.g) {
      return;
    }
    let compositesToShow = this.t.visibleItems.filter(
      (item) => item.pinned || this.t.activeItem && this.t.activeItem.id === item.id
      /* Show the active composite even if it is not pinned */
    ).map((item) => item.id);
    let maxVisible = compositesToShow.length;
    const totalComposites = compositesToShow.length;
    let size = 0;
    const limit = this.H.orientation === 1 ? this.g.height : this.g.width;
    for (let i2 = 0; i2 < compositesToShow.length; i2++) {
      const compositeSize = this.y.get(compositesToShow[i2]);
      if (size + compositeSize > limit) {
        maxVisible = i2;
        break;
      }
      size += compositeSize;
    }
    if (totalComposites > maxVisible) {
      compositesToShow = compositesToShow.slice(0, maxVisible);
    }
    if (this.t.activeItem && compositesToShow.every((compositeId) => !!this.t.activeItem && compositeId !== this.t.activeItem.id)) {
      size += this.y.get(this.t.activeItem.id);
      compositesToShow.push(this.t.activeItem.id);
    }
    while (size > limit && compositesToShow.length) {
      const removedComposite = compositesToShow.length > 1 ? compositesToShow.splice(compositesToShow.length - 2, 1)[0] : compositesToShow.pop();
      size -= this.y.get(removedComposite);
    }
    if (totalComposites > compositesToShow.length) {
      size += this.H.overflowActionSize;
    }
    while (size > limit && compositesToShow.length) {
      const removedComposite = compositesToShow.length > 1 && compositesToShow[compositesToShow.length - 1] === this.t.activeItem?.id ? compositesToShow.splice(compositesToShow.length - 2, 1)[0] : compositesToShow.pop();
      size -= this.y.get(removedComposite);
    }
    if (totalComposites === compositesToShow.length && this.n) {
      compositeSwitcherBar.pull(compositeSwitcherBar.length() - 1);
      this.n.dispose();
      this.n = void 0;
      this.r?.dispose();
      this.r = void 0;
    }
    const compositesToRemove = [];
    this.w.forEach((compositeId, index) => {
      if (!compositesToShow.includes(compositeId)) {
        compositesToRemove.push(index);
      }
    });
    compositesToRemove.reverse().forEach((index) => {
      compositeSwitcherBar.pull(index);
      this.w.splice(index, 1);
    });
    compositesToShow.forEach((compositeId, newIndex) => {
      const currentIndex = this.w.indexOf(compositeId);
      if (newIndex !== currentIndex) {
        if (currentIndex !== -1) {
          compositeSwitcherBar.pull(currentIndex);
          this.w.splice(currentIndex, 1);
        }
        compositeSwitcherBar.push(this.t.findItem(compositeId).activityAction, { label: true, icon: this.H.icon, index: newIndex });
        this.w.splice(newIndex, 0, compositeId);
      }
    });
    if (totalComposites > compositesToShow.length && !this.n) {
      this.n = this.B(this.I.createInstance($Dqb, () => {
        this.r?.showMenu();
      }));
      this.r = this.B(this.I.createInstance($Eqb, this.n, () => this.P(), () => this.t.activeItem ? this.t.activeItem.id : void 0, (compositeId) => {
        const item = this.t.findItem(compositeId);
        return item?.activity[0]?.badge;
      }, this.H.getOnCompositeClickAction, this.H.colors, this.H.activityHoverOptions));
      compositeSwitcherBar.push(this.n, { label: false, icon: true });
    }
    if (!donotTrigger) {
      this.a.fire();
    }
  }
  P() {
    let overflowingIds = this.t.visibleItems.filter((item) => item.pinned).map((item) => item.id);
    if (this.t.activeItem && !this.t.activeItem.pinned) {
      overflowingIds.push(this.t.activeItem.id);
    }
    overflowingIds = overflowingIds.filter((compositeId) => !this.w.includes(compositeId));
    return this.t.visibleItems.filter((c) => overflowingIds.includes(c.id)).map((item) => {
      return { id: item.id, name: this.getAction(item.id)?.label || item.name };
    });
  }
  Q(targetWindow, e) {
    $9j.stop(e, true);
    const event = new $lf(targetWindow, e);
    this.J.showContextMenu({
      getAnchor: () => event,
      getActions: () => this.getContextMenuActions(e)
    });
  }
  getContextMenuActions(e) {
    const actions = this.t.visibleItems.map(({ id: id2, name, activityAction }) => {
      const isPinned = this.isPinned(id2);
      return $Zm({
        id: id2,
        label: this.getAction(id2).label || name || id2,
        checked: isPinned,
        enabled: activityAction.enabled && (!isPinned || this.getPinnedCompositeIds().length > 1),
        run: () => {
          if (this.isPinned(id2)) {
            this.unpin(id2);
          } else {
            this.pin(id2, true);
          }
        }
      });
    });
    this.H.fillExtraContextMenuActions(actions, e);
    return actions;
  }
};
$_Ub = __decorate([
  __param(2, $Pk),
  __param(3, $50),
  __param(4, $$M)
], $_Ub);
var CompositeBarModel = class {
  get items() {
    return this.a;
  }
  constructor(items, options3) {
    this.a = [];
    this.b = options3;
    this.setItems(items);
  }
  setItems(items) {
    this.a = [];
    this.a = items.map((i2) => this.d(i2.id, i2.name, i2.order, i2.pinned, i2.visible));
  }
  get visibleItems() {
    return this.items.filter((item) => item.visible);
  }
  get pinnedItems() {
    return this.items.filter((item) => item.visible && item.pinned);
  }
  d(id2, name, order, pinned, visible) {
    const options3 = this.b;
    return {
      id: id2,
      name,
      pinned,
      order,
      visible,
      activity: [],
      get activityAction() {
        return options3.getActivityAction(id2);
      },
      get pinnedAction() {
        return options3.getCompositePinnedAction(id2);
      },
      get toggleBadgeAction() {
        return options3.getCompositeBadgeAction(id2);
      }
    };
  }
  add(id2, name, order, requestedIndex) {
    const item = this.findItem(id2);
    if (item) {
      let changed = false;
      item.name = name;
      if (!$Ig(order)) {
        changed = item.order !== order;
        item.order = order;
      }
      if (!item.visible) {
        item.visible = true;
        changed = true;
      }
      return changed;
    } else {
      const item2 = this.d(id2, name, order, true, true);
      if (!$Ig(requestedIndex)) {
        let index = 0;
        let rIndex = requestedIndex;
        while (rIndex > 0 && index < this.items.length) {
          if (this.items[index++].visible) {
            rIndex--;
          }
        }
        this.items.splice(index, 0, item2);
      } else if ($Ig(order)) {
        this.items.push(item2);
      } else {
        let index = 0;
        while (index < this.items.length && typeof this.items[index].order === "number" && this.items[index].order < order) {
          index++;
        }
        this.items.splice(index, 0, item2);
      }
      return true;
    }
  }
  remove(id2) {
    for (let index = 0; index < this.items.length; index++) {
      if (this.items[index].id === id2) {
        this.items.splice(index, 1);
        return true;
      }
    }
    return false;
  }
  hide(id2) {
    for (const item of this.items) {
      if (item.id === id2) {
        if (item.visible) {
          item.visible = false;
          return true;
        }
        return false;
      }
    }
    return false;
  }
  move(compositeId, toCompositeId) {
    const fromIndex = this.f(compositeId);
    const toIndex = this.f(toCompositeId);
    if (fromIndex === -1 || toIndex === -1) {
      return false;
    }
    const sourceItem = this.items.splice(fromIndex, 1)[0];
    this.items.splice(toIndex, 0, sourceItem);
    sourceItem.pinned = true;
    return true;
  }
  setPinned(id2, pinned) {
    for (const item of this.items) {
      if (item.id === id2) {
        if (item.pinned !== pinned) {
          item.pinned = pinned;
          return true;
        }
        return false;
      }
    }
    return false;
  }
  activate(id2) {
    if (!this.activeItem || this.activeItem.id !== id2) {
      if (this.activeItem) {
        this.deactivate();
      }
      for (const item of this.items) {
        if (item.id === id2) {
          this.activeItem = item;
          this.activeItem.activityAction.activate();
          return true;
        }
      }
    }
    return false;
  }
  deactivate() {
    if (this.activeItem) {
      this.activeItem.activityAction.deactivate();
      this.activeItem = void 0;
      return true;
    }
    return false;
  }
  findItem(id2) {
    return this.items.filter((item) => item.id === id2)[0];
  }
  f(id2) {
    for (let index = 0; index < this.items.length; index++) {
      if (this.items[index].id === id2) {
        return index;
      }
    }
    return -1;
  }
};

// out-build/vs/workbench/browser/parts/paneCompositeBar.js
var ViewContainerActivityAction_1;
var $aVb = class $aVb2 extends $3c {
  constructor(j, m, n, r2, s, t, u, w, y, z, C) {
    super();
    this.j = j;
    this.m = m;
    this.n = n;
    this.r = r2;
    this.s = s;
    this.t = t;
    this.u = u;
    this.w = w;
    this.y = y;
    this.z = z;
    this.C = C;
    this.a = this.B(new $_c());
    this.g = /* @__PURE__ */ new Map();
    this.h = false;
    this.fb = void 0;
    this.b = n.partId === "workbench.parts.panel" ? 1 : n.partId === "workbench.parts.auxiliarybar" ? 2 : 0;
    this.dndHandler = new $$Ub(this.u, this.b, this.j.orientation, async (id2, focus) => {
      return await this.n.openPaneComposite(id2, focus) ?? null;
    }, (from, to, before) => this.f.move(from, to, this.j.orientation === 1 ? before?.verticallyBefore : before?.horizontallyBefore), () => this.f.getCompositeBarItems());
    const cachedItems = this.gb.map((container2) => ({
      id: container2.id,
      name: container2.name,
      visible: !this.X(container2.id, container2),
      order: container2.order,
      pinned: container2.pinned
    }));
    this.f = this.D(cachedItems);
    this.P(this.cb());
    this.H();
  }
  D(cachedItems) {
    return this.B(this.r.createInstance($_Ub, cachedItems, {
      icon: this.j.icon,
      compact: this.j.compact,
      orientation: this.j.orientation,
      activityHoverOptions: this.j.activityHoverOptions,
      preventLoopNavigation: this.j.preventLoopNavigation,
      openComposite: async (compositeId, preserveFocus) => {
        return await this.n.openPaneComposite(compositeId, !preserveFocus) ?? null;
      },
      getActivityAction: (compositeId) => this.O(compositeId).activityAction,
      getCompositePinnedAction: (compositeId) => this.O(compositeId).pinnedAction,
      getCompositeBadgeAction: (compositeId) => this.O(compositeId).badgeAction,
      getOnCompositeClickAction: (compositeId) => this.O(compositeId).activityAction,
      fillExtraContextMenuActions: (actions, e) => this.j.fillExtraContextMenuActions(actions, e),
      getContextMenuActionsForComposite: (compositeId) => this.F(compositeId),
      getDefaultCompositeId: () => this.u.getDefaultViewContainer(this.b)?.id,
      dndHandler: this.dndHandler,
      compositeSize: this.j.compositeSize,
      overflowActionSize: this.j.overflowActionSize,
      colors: (theme) => this.j.colors(theme)
    }));
  }
  F(compositeId) {
    const actions = [new $Wm()];
    const viewContainer5 = this.u.getViewContainerById(compositeId);
    const defaultLocation = this.u.getDefaultViewContainerLocation(viewContainer5);
    const currentLocation = this.u.getViewContainerLocation(viewContainer5);
    const moveActions = [];
    for (const location3 of [
      0,
      2,
      1
      /* ViewContainerLocation.Panel */
    ]) {
      if (currentLocation !== location3) {
        moveActions.push(this.G(viewContainer5, location3, defaultLocation));
      }
    }
    actions.push(new $Xm("moveToMenu", localize(3682, null), moveActions));
    if (defaultLocation !== currentLocation) {
      actions.push($Zm({
        id: "resetLocationAction",
        label: localize(3683, null),
        run: () => {
          this.u.moveViewContainerToLocation(viewContainer5, defaultLocation, void 0, "resetLocationAction");
          this.w.openViewContainer(viewContainer5.id, true);
        }
      }));
    } else {
      const viewContainerModel = this.u.getViewContainerModel(viewContainer5);
      if (viewContainerModel.allViewDescriptors.length === 1) {
        const viewToReset = viewContainerModel.allViewDescriptors[0];
        const defaultContainer = this.u.getDefaultContainerById(viewToReset.id);
        if (defaultContainer !== viewContainer5) {
          actions.push($Zm({
            id: "resetLocationAction",
            label: localize(3684, null),
            run: () => {
              this.u.moveViewsToContainer([viewToReset], defaultContainer, void 0, "resetLocationAction");
              this.w.openViewContainer(viewContainer5.id, true);
            }
          }));
        }
      }
    }
    return actions;
  }
  G(viewContainer5, newLocation, defaultLocation) {
    return $Zm({
      id: `moveViewContainerTo${newLocation}`,
      label: newLocation === 1 ? localize(3685, null) : newLocation === 0 ? localize(3686, null) : localize(3687, null),
      run: () => {
        let index;
        if (newLocation !== defaultLocation) {
          index = this.u.getViewContainersByLocation(newLocation).length;
        } else {
          index = void 0;
        }
        this.u.moveViewContainerToLocation(viewContainer5, newLocation, index);
        this.w.openViewContainer(viewContainer5.id, true);
      }
    });
  }
  H() {
    this.B(this.u.onDidChangeViewContainers(({ added, removed }) => this.I(added, removed)));
    this.B(this.u.onDidChangeContainerLocation(({ viewContainer: viewContainer5, from, to }) => this.J(viewContainer5, from, to)));
    this.B(this.n.onDidPaneCompositeOpen((e) => this.L(e.getId(), true)));
    this.B(this.n.onDidPaneCompositeClose((e) => this.L(e.getId(), false)));
    this.t.whenInstalledExtensionsRegistered().then(() => {
      if (this.q.isDisposed) {
        return;
      }
      this.M();
      this.B(this.f.onDidChange(() => {
        this.db(true);
        this.eb();
      }));
      this.B(this.s.onDidChangeValue(0, this.j.pinnedViewContainersKey, this.q)(() => this.db(false)));
    });
  }
  I(added, removed) {
    removed.filter(({ location: location3 }) => location3 === this.b).forEach(({ container: container2 }) => this.Q(container2));
    this.P(added.filter(({ location: location3 }) => location3 === this.b).map(({ container: container2 }) => container2));
  }
  J(container2, from, to) {
    if (from === this.b) {
      this.Q(container2);
    }
    if (to === this.b) {
      this.P([container2]);
    }
  }
  L(id2, visible) {
    if (visible) {
      this.N(id2);
    } else {
      this.f.deactivateComposite(id2);
    }
  }
  M() {
    this.h = true;
    for (const { id: id2 } of this.gb) {
      const viewContainer5 = this.bb(id2);
      if (viewContainer5) {
        this.W(viewContainer5);
      } else {
        if (this.u.isViewContainerRemovedPermanently(id2)) {
          this.ab(id2);
        } else {
          this.Z(id2);
        }
      }
    }
    this.eb();
  }
  N(id2) {
    const viewContainer5 = this.bb(id2);
    if (viewContainer5) {
      this.Y(viewContainer5);
      this.f.activateComposite(viewContainer5.id);
      if (this.X(viewContainer5)) {
        const viewContainerModel = this.u.getViewContainerModel(viewContainer5);
        if (viewContainerModel.activeViewDescriptors.length === 0) {
          this.Z(viewContainer5.id);
        }
      }
    }
  }
  create(parent) {
    return this.f.create(parent);
  }
  O(compositeId) {
    let compositeActions = this.g.get(compositeId);
    if (!compositeActions) {
      const viewContainer5 = this.bb(compositeId);
      if (viewContainer5) {
        const viewContainerModel = this.u.getViewContainerModel(viewContainer5);
        compositeActions = {
          activityAction: this.B(this.r.createInstance(ViewContainerActivityAction, this.S(viewContainerModel), this.m, this.n)),
          pinnedAction: this.B(new $Gqb(this.S(viewContainerModel), this.f)),
          badgeAction: this.B(new $Hqb(this.S(viewContainerModel), this.f))
        };
      } else {
        const cachedComposite = this.gb.filter((c) => c.id === compositeId)[0];
        compositeActions = {
          activityAction: this.B(this.r.createInstance(PlaceHolderViewContainerActivityAction, this.U(compositeId, cachedComposite?.name ?? compositeId, cachedComposite?.icon, void 0), this.m, this.n)),
          pinnedAction: this.B(new PlaceHolderToggleCompositePinnedAction(compositeId, this.f)),
          badgeAction: this.B(new PlaceHolderToggleCompositeBadgeAction(compositeId, this.f))
        };
      }
      this.g.set(compositeId, compositeActions);
    }
    return compositeActions;
  }
  P(viewContainers) {
    for (const viewContainer5 of viewContainers) {
      this.Y(viewContainer5);
      const cachedViewContainer = this.gb.filter(({ id: id2 }) => id2 === viewContainer5.id)[0];
      if (!cachedViewContainer) {
        this.f.pin(viewContainer5.id);
      }
      const visibleViewContainer = this.n.getActivePaneComposite();
      if (visibleViewContainer?.getId() === viewContainer5.id) {
        this.f.activateComposite(viewContainer5.id);
      }
      const viewContainerModel = this.u.getViewContainerModel(viewContainer5);
      this.R(viewContainer5, viewContainerModel);
      this.W(viewContainer5);
      const disposables = new $2c();
      disposables.add(viewContainerModel.onDidChangeContainerInfo(() => this.R(viewContainer5, viewContainerModel)));
      disposables.add(viewContainerModel.onDidChangeActiveViewDescriptors(() => this.W(viewContainer5)));
      this.a.set(viewContainer5.id, disposables);
    }
  }
  Q(viewContainer5) {
    this.a.deleteAndDispose(viewContainer5.id);
    this.ab(viewContainer5.id);
  }
  R(viewContainer5, viewContainerModel) {
    const compositeBarActionItem = this.S(viewContainerModel);
    const { activityAction, pinnedAction } = this.O(viewContainer5.id);
    activityAction.updateCompositeBarActionItem(compositeBarActionItem);
    if (pinnedAction instanceof PlaceHolderToggleCompositePinnedAction) {
      pinnedAction.setActivity(compositeBarActionItem);
    }
    if (this.j.recomputeSizes) {
      this.f.recomputeSizes();
    }
    this.eb();
  }
  S(viewContainerModel) {
    return this.U(viewContainerModel.viewContainer.id, viewContainerModel.title, viewContainerModel.icon, viewContainerModel.keybindingId);
  }
  U(id2, name, icon2, keybindingId) {
    let classNames = void 0;
    let iconUrl = void 0;
    if (this.j.icon) {
      if (URI.isUri(icon2)) {
        iconUrl = icon2;
        const cssUrl = $5Z(icon2);
        const hash = new $3i();
        hash.update(cssUrl);
        const iconId = `activity-${id2.replace(/\./g, "-")}-${hash.digest()}`;
        const iconClass = `.monaco-workbench .${this.j.partContainerClass} .monaco-action-bar .action-label.${iconId}`;
        classNames = [iconId, "uri-icon"];
        $XZ(iconClass, `
				mask: ${cssUrl} no-repeat 50% 50%;
				mask-size: ${this.j.iconSize}px;
				-webkit-mask: ${cssUrl} no-repeat 50% 50%;
				-webkit-mask-size: ${this.j.iconSize}px;
				mask-origin: padding;
				-webkit-mask-origin: padding;
			`);
      } else if (ThemeIcon.isThemeIcon(icon2)) {
        classNames = ThemeIcon.asClassNameArray(icon2);
      }
    }
    return { id: id2, name, classNames, iconUrl, keybindingId };
  }
  W(viewContainer5) {
    if (this.X(viewContainer5)) {
      this.Z(viewContainer5.id);
    } else {
      this.Y(viewContainer5);
      const activePaneComposite = this.n.getActivePaneComposite();
      if (activePaneComposite?.getId() === viewContainer5.id) {
        this.f.activateComposite(viewContainer5.id);
      }
    }
  }
  X(viewContainerOrId, cachedViewContainer) {
    const viewContainer5 = $zg(viewContainerOrId) ? this.bb(viewContainerOrId) : viewContainerOrId;
    const viewContainerId = $zg(viewContainerOrId) ? viewContainerOrId : viewContainerOrId.id;
    if (viewContainer5) {
      if (viewContainer5.hideIfEmpty) {
        if (this.w.isViewContainerActive(viewContainerId)) {
          return false;
        }
      } else {
        return false;
      }
    }
    if (!this.h && !(this.m === "workbench.parts.sidebar" && this.z.remoteAuthority && $p)) {
      cachedViewContainer = cachedViewContainer || this.gb.find(({ id: id2 }) => id2 === viewContainerId);
      if (!viewContainer5 && cachedViewContainer?.isBuiltin && cachedViewContainer?.visible) {
        return false;
      }
      if (cachedViewContainer?.views?.length) {
        return cachedViewContainer.views.every(({ when }) => !!when && !this.y.contextMatchesRules($7m.deserialize(when)));
      }
    }
    return true;
  }
  Y(viewContainer5) {
    this.f.addComposite({ id: viewContainer5.id, name: typeof viewContainer5.title === "string" ? viewContainer5.title : viewContainer5.title.value, order: viewContainer5.order, requestedIndex: viewContainer5.requestedIndex });
  }
  Z(compositeId) {
    this.f.hideComposite(compositeId);
    const compositeActions = this.g.get(compositeId);
    if (compositeActions) {
      compositeActions.activityAction.dispose();
      compositeActions.pinnedAction.dispose();
      this.g.delete(compositeId);
    }
  }
  ab(compositeId) {
    this.f.removeComposite(compositeId);
    const compositeActions = this.g.get(compositeId);
    if (compositeActions) {
      compositeActions.activityAction.dispose();
      compositeActions.pinnedAction.dispose();
      this.g.delete(compositeId);
    }
  }
  getPinnedPaneCompositeIds() {
    const pinnedCompositeIds = this.f.getPinnedComposites().map((v) => v.id);
    return this.cb().filter((v) => this.f.isPinned(v.id)).sort((v1, v2) => pinnedCompositeIds.indexOf(v1.id) - pinnedCompositeIds.indexOf(v2.id)).map((v) => v.id);
  }
  getVisiblePaneCompositeIds() {
    return this.f.getVisibleComposites().filter((v) => this.n.getActivePaneComposite()?.getId() === v.id || this.f.isPinned(v.id)).map((v) => v.id);
  }
  getPaneCompositeIds() {
    return this.f.getVisibleComposites().map((v) => v.id);
  }
  getContextMenuActions() {
    return this.f.getContextMenuActions();
  }
  focus(index) {
    this.f.focus(index);
  }
  layout(width2, height) {
    this.f.layout(new $rj(width2, height));
  }
  bb(id2) {
    const viewContainer5 = this.u.getViewContainerById(id2);
    return viewContainer5 && this.u.getViewContainerLocation(viewContainer5) === this.b ? viewContainer5 : void 0;
  }
  cb() {
    return this.u.getViewContainersByLocation(this.b);
  }
  db(retainExisting) {
    if (this.lb === this.mb()) {
      return;
    }
    this.qb = void 0;
    this.kb = void 0;
    this.fb = void 0;
    const newCompositeItems = [];
    const compositeItems = this.f.getCompositeBarItems();
    for (const cachedViewContainer of this.gb) {
      newCompositeItems.push({
        id: cachedViewContainer.id,
        name: cachedViewContainer.name,
        order: cachedViewContainer.order,
        pinned: cachedViewContainer.pinned,
        visible: cachedViewContainer.visible && !!this.bb(cachedViewContainer.id)
      });
    }
    for (const viewContainer5 of this.cb()) {
      if (!newCompositeItems.some(({ id: id2 }) => id2 === viewContainer5.id)) {
        const index = compositeItems.findIndex(({ id: id2 }) => id2 === viewContainer5.id);
        if (index !== -1) {
          const compositeItem = compositeItems[index];
          newCompositeItems.splice(index, 0, {
            id: viewContainer5.id,
            name: typeof viewContainer5.title === "string" ? viewContainer5.title : viewContainer5.title.value,
            order: compositeItem.order,
            pinned: compositeItem.pinned,
            visible: compositeItem.visible
          });
        } else {
          newCompositeItems.push({
            id: viewContainer5.id,
            name: typeof viewContainer5.title === "string" ? viewContainer5.title : viewContainer5.title.value,
            order: viewContainer5.order,
            pinned: true,
            visible: !this.X(viewContainer5)
          });
        }
      }
    }
    if (retainExisting) {
      for (const compositeItem of compositeItems) {
        const newCompositeItem = newCompositeItems.find(({ id: id2 }) => id2 === compositeItem.id);
        if (!newCompositeItem) {
          newCompositeItems.push(compositeItem);
        }
      }
    }
    this.f.setCompositeBarItems(newCompositeItems);
  }
  eb() {
    const state = [];
    const compositeItems = this.f.getCompositeBarItems();
    for (const compositeItem of compositeItems) {
      const viewContainer5 = this.bb(compositeItem.id);
      if (viewContainer5) {
        const viewContainerModel = this.u.getViewContainerModel(viewContainer5);
        const views = [];
        for (const { when } of viewContainerModel.allViewDescriptors) {
          views.push({ when: when ? when.serialize() : void 0 });
        }
        state.push({
          id: compositeItem.id,
          name: viewContainerModel.title,
          icon: URI.isUri(viewContainerModel.icon) && this.z.remoteAuthority ? void 0 : viewContainerModel.icon,
          // Do not cache uri icons with remote connection
          views,
          pinned: compositeItem.pinned,
          order: compositeItem.order,
          visible: compositeItem.visible,
          isBuiltin: !viewContainer5.extensionId
        });
      } else {
        state.push({ id: compositeItem.id, name: compositeItem.name, pinned: compositeItem.pinned, order: compositeItem.order, visible: false, isBuiltin: false });
      }
    }
    this.hb(state);
  }
  get gb() {
    if (this.fb === void 0) {
      this.fb = this.ib();
      for (const placeholderViewContainer of this.ob()) {
        const cachedViewContainer = this.fb.find((cached) => cached.id === placeholderViewContainer.id);
        if (cachedViewContainer) {
          cachedViewContainer.visible = placeholderViewContainer.visible ?? cachedViewContainer.visible;
          cachedViewContainer.name = placeholderViewContainer.name;
          cachedViewContainer.icon = placeholderViewContainer.themeIcon ? placeholderViewContainer.themeIcon : placeholderViewContainer.iconUrl ? URI.revive(placeholderViewContainer.iconUrl) : void 0;
          if (URI.isUri(cachedViewContainer.icon) && this.z.remoteAuthority) {
            cachedViewContainer.icon = void 0;
          }
          cachedViewContainer.views = placeholderViewContainer.views;
          cachedViewContainer.isBuiltin = placeholderViewContainer.isBuiltin;
        }
      }
      for (const viewContainerWorkspaceState of this.ub()) {
        const cachedViewContainer = this.fb.find((cached) => cached.id === viewContainerWorkspaceState.id);
        if (cachedViewContainer) {
          cachedViewContainer.visible = viewContainerWorkspaceState.visible ?? cachedViewContainer.visible;
        }
      }
    }
    return this.fb;
  }
  hb(cachedViewContainers) {
    const pinnedViewContainers = this.ib();
    this.jb(cachedViewContainers.map(({ id: id2, pinned, order }) => ({
      id: id2,
      pinned,
      visible: Boolean(pinnedViewContainers.find(({ id: pinnedId }) => pinnedId === id2)?.visible),
      order
    })));
    this.pb(cachedViewContainers.map(({ id: id2, icon: icon2, name, views, isBuiltin }) => ({
      id: id2,
      iconUrl: URI.isUri(icon2) ? icon2 : void 0,
      themeIcon: ThemeIcon.isThemeIcon(icon2) ? icon2 : void 0,
      name,
      isBuiltin,
      views
    })));
    this.vb(cachedViewContainers.map(({ id: id2, visible }) => ({
      id: id2,
      visible
    })));
  }
  ib() {
    return JSON.parse(this.lb);
  }
  jb(pinnedViewContainers) {
    this.lb = JSON.stringify(pinnedViewContainers);
  }
  get lb() {
    if (!this.kb) {
      this.kb = this.mb();
    }
    return this.kb;
  }
  set lb(pinnedViewContainersValue) {
    if (this.lb !== pinnedViewContainersValue) {
      this.kb = pinnedViewContainersValue;
      this.nb(pinnedViewContainersValue);
    }
  }
  mb() {
    return this.s.get(this.j.pinnedViewContainersKey, 0, "[]");
  }
  nb(value) {
    this.s.store(
      this.j.pinnedViewContainersKey,
      value,
      0,
      0
      /* StorageTarget.USER */
    );
  }
  ob() {
    return JSON.parse(this.rb);
  }
  pb(placeholderViewContainers) {
    this.rb = JSON.stringify(placeholderViewContainers);
  }
  get rb() {
    if (!this.qb) {
      this.qb = this.sb();
    }
    return this.qb;
  }
  set rb(placeholderViewContainesValue) {
    if (this.rb !== placeholderViewContainesValue) {
      this.qb = placeholderViewContainesValue;
      this.tb(placeholderViewContainesValue);
    }
  }
  sb() {
    return this.s.get(this.j.placeholderViewContainersKey, 0, "[]");
  }
  tb(value) {
    this.s.store(
      this.j.placeholderViewContainersKey,
      value,
      0,
      1
      /* StorageTarget.MACHINE */
    );
  }
  ub() {
    return JSON.parse(this.xb);
  }
  vb(viewContainersWorkspaceState) {
    this.xb = JSON.stringify(viewContainersWorkspaceState);
  }
  get xb() {
    if (!this.wb) {
      this.wb = this.yb();
    }
    return this.wb;
  }
  set xb(viewContainersWorkspaceStateValue) {
    if (this.xb !== viewContainersWorkspaceStateValue) {
      this.wb = viewContainersWorkspaceStateValue;
      this.zb(viewContainersWorkspaceStateValue);
    }
  }
  yb() {
    return this.s.get(this.j.viewContainersWorkspaceStateKey, 1, "[]");
  }
  zb(value) {
    this.s.store(
      this.j.viewContainersWorkspaceStateKey,
      value,
      1,
      1
      /* StorageTarget.MACHINE */
    );
  }
};
$aVb = __decorate([
  __param(3, $Pk),
  __param(4, $jv),
  __param(5, $wN),
  __param(6, $$M),
  __param(7, $uob),
  __param(8, $on),
  __param(9, $US),
  __param(10, $Vlb)
], $aVb);
var ViewContainerActivityAction = class ViewContainerActivityAction2 extends $Bqb {
  static {
    ViewContainerActivityAction_1 = this;
  }
  static {
    this.h = 300;
  }
  constructor(compositeBarActionItem, s, t, L, M, N, O) {
    super(compositeBarActionItem);
    this.s = s;
    this.t = t;
    this.L = L;
    this.M = M;
    this.N = N;
    this.O = O;
    this.r = 0;
    this.P();
    this.B(this.O.onDidChangeActivity((viewContainerOrAction) => {
      if (!$zg(viewContainerOrAction) && viewContainerOrAction.id === this.compositeBarActionItem.id) {
        this.P();
      }
    }));
  }
  updateCompositeBarActionItem(compositeBarActionItem) {
    this.compositeBarActionItem = compositeBarActionItem;
  }
  P() {
    const activities = this.O.getViewContainerActivities(this.compositeBarActionItem.id);
    this.activity = activities[0];
  }
  async run(event) {
    if ($3j(event) && event.button === 2) {
      return;
    }
    const now = Date.now();
    if (now > this.r && now - this.r < ViewContainerActivityAction_1.h) {
      return;
    }
    this.r = now;
    const focus = event && "preserveFocus" in event ? !event.preserveFocus : true;
    if (this.s === "workbench.parts.activitybar") {
      const sideBarVisible = this.L.isVisible(
        "workbench.parts.sidebar"
        /* Parts.SIDEBAR_PART */
      );
      const activeViewlet = this.t.getActivePaneComposite();
      const focusBehavior = this.N.getValue("workbench.activityBar.iconClickBehavior");
      if (sideBarVisible && activeViewlet?.getId() === this.compositeBarActionItem.id) {
        switch (focusBehavior) {
          case "focus":
            this.Q("refocus");
            this.t.openPaneComposite(this.compositeBarActionItem.id, focus);
            break;
          case "toggle":
          default:
            this.Q("hide");
            this.L.setPartHidden(
              true,
              "workbench.parts.sidebar"
              /* Parts.SIDEBAR_PART */
            );
            break;
        }
        return;
      }
      this.Q("show");
    }
    await this.t.openPaneComposite(this.compositeBarActionItem.id, focus);
    return this.activate();
  }
  Q(action) {
    this.M.publicLog2("activityBarAction", { viewletId: this.compositeBarActionItem.id, action });
  }
};
ViewContainerActivityAction = ViewContainerActivityAction_1 = __decorate([
  __param(3, $Vlb),
  __param(4, $zv),
  __param(5, $kl),
  __param(6, $vqb)
], ViewContainerActivityAction);
var PlaceHolderViewContainerActivityAction = class extends ViewContainerActivityAction {
};
var PlaceHolderToggleCompositePinnedAction = class extends $Gqb {
  constructor(id2, compositeBar) {
    super({ id: id2, name: id2, classNames: void 0 }, compositeBar);
  }
  setActivity(activity) {
    this.label = activity.name;
  }
};
var PlaceHolderToggleCompositeBadgeAction = class extends $Hqb {
  constructor(id2, compositeBar) {
    super({ id: id2, name: id2, classNames: void 0 }, compositeBar);
  }
  setCompositeBarActionItem(actionItem) {
    this.label = actionItem.name;
  }
};

// out-build/vs/workbench/browser/parts/paneCompositePart.js
var $bVb_1;
var CompositeBarPosition;
(function(CompositeBarPosition2) {
  CompositeBarPosition2[CompositeBarPosition2["TOP"] = 0] = "TOP";
  CompositeBarPosition2[CompositeBarPosition2["TITLE"] = 1] = "TITLE";
  CompositeBarPosition2[CompositeBarPosition2["BOTTOM"] = 2] = "BOTTOM";
})(CompositeBarPosition || (CompositeBarPosition = {}));
var $bVb = class $bVb2 extends $0Ub {
  static {
    $bVb_1 = this;
  }
  static {
    this.Vb = 50;
  }
  get snap() {
    return this.M.isVisible(this.partId) || !!this.ac.value?.getVisiblePaneCompositeIds().length;
  }
  get onDidPaneCompositeOpen() {
    return Event2.map(this.b.event, (compositeEvent) => compositeEvent.composite);
  }
  constructor(partId, partOptions, activePaneCompositeSettingsKey, hc, ic, nameForTelemetry, compositeCSSClass, titleForegroundColor, titleBorderColor, notificationService, storageService, contextMenuService, layoutService, keybindingService, hoverService, instantiationService, themeService, jc, kc, lc, mc) {
    let location3 = 0;
    let registryId = $sqb.Viewlets;
    let globalActionsMenuId = $bJ.SidebarTitle;
    if (partId === "workbench.parts.panel") {
      location3 = 1;
      registryId = $sqb.Panels;
      globalActionsMenuId = $bJ.PanelTitle;
    } else if (partId === "workbench.parts.auxiliarybar") {
      location3 = 2;
      registryId = $sqb.Auxiliary;
      globalActionsMenuId = $bJ.AuxiliaryBarTitle;
    }
    super(notificationService, storageService, contextMenuService, layoutService, keybindingService, hoverService, instantiationService, themeService, $Wn.as(registryId), activePaneCompositeSettingsKey, jc.getDefaultViewContainer(location3)?.id || "", nameForTelemetry, compositeCSSClass, titleForegroundColor, titleBorderColor, partId, partOptions);
    this.partId = partId;
    this.hc = hc;
    this.ic = ic;
    this.jc = jc;
    this.kc = kc;
    this.lc = lc;
    this.mc = mc;
    this.onDidPaneCompositeClose = this.y.event;
    this.Zb = this.B(new $2c());
    this.ac = this.B(new $4c());
    this.bc = void 0;
    this.fc = false;
    this.Wb = location3;
    this.ec = this.B(this.ub.createInstance($yob, globalActionsMenuId, void 0, void 0));
    this.nc();
  }
  nc() {
    this.B(this.onDidPaneCompositeOpen((composite) => this.oc(composite)));
    this.B(this.onDidPaneCompositeClose(this.pc, this));
    this.B(this.ec.onDidChange(() => this.Gc()));
    this.B(this.vb.onDidDeregister((viewletDescriptor) => {
      const activeContainers = this.jc.getViewContainersByLocation(this.Wb).filter((container2) => this.jc.getViewContainerModel(container2).activeViewDescriptors.length > 0);
      if (activeContainers.length) {
        if (this.Jb()?.getId() === viewletDescriptor.id) {
          const defaultViewletId = this.jc.getDefaultViewContainer(this.Wb)?.id;
          const containerToOpen = activeContainers.filter((c) => c.id === defaultViewletId)[0] || activeContainers[0];
          this.Cc(containerToOpen.id);
        }
      } else {
        this.M.setPartHidden(true, this.partId);
      }
      this.Ub(viewletDescriptor.id);
    }));
    this.B(this.lc.onDidRegisterExtensions(() => {
      this.Ec();
    }));
  }
  oc(composite) {
    this.hc.set(composite.getId());
  }
  pc(composite) {
    const id2 = composite.getId();
    if (this.hc.get() === id2) {
      this.hc.reset();
    }
  }
  Fb(composite) {
    super.Fb(composite);
    this.Ec();
    this.Fc();
  }
  Lb() {
    const composite = super.Lb();
    this.Ec();
    this.Fc();
    return composite;
  }
  create(parent) {
    this.element = parent;
    this.element.classList.add("pane-composite-part");
    super.create(parent);
    const contentArea = this.R();
    if (contentArea) {
      this.sc(contentArea);
    }
    this.vc();
    const focusTracker = this.B($_j(parent));
    this.B(focusTracker.onDidFocus(() => this.ic.set(true)));
    this.B(focusTracker.onDidBlur(() => this.ic.set(false)));
  }
  sc(parent) {
    this.cc = document.createElement("div");
    this.cc.classList.add("empty-pane-message-area");
    const messageElement = document.createElement("div");
    messageElement.classList.add("empty-pane-message");
    messageElement.innerText = localize(3688, null);
    this.cc.appendChild(messageElement);
    parent.appendChild(this.cc);
    this.B($Iob.INSTANCE.registerTarget(this.element, {
      onDragOver: (e) => {
        $9j.stop(e.eventData, true);
        if (this.ac.value) {
          const validDropTarget = this.ac.value.dndHandler.onDragEnter(e.dragAndDropData, void 0, e.eventData);
          $Job(e.eventData.dataTransfer, "move", validDropTarget);
        }
      },
      onDragEnter: (e) => {
        $9j.stop(e.eventData, true);
        if (this.ac.value) {
          const validDropTarget = this.ac.value.dndHandler.onDragEnter(e.dragAndDropData, void 0, e.eventData);
          this.cc.style.backgroundColor = validDropTarget ? this.h.getColor($Cmb)?.toString() || "" : "";
        }
      },
      onDragLeave: (e) => {
        $9j.stop(e.eventData, true);
        this.cc.style.backgroundColor = "";
      },
      onDragEnd: (e) => {
        $9j.stop(e.eventData, true);
        this.cc.style.backgroundColor = "";
      },
      onDrop: (e) => {
        $9j.stop(e.eventData, true);
        this.cc.style.backgroundColor = "";
        if (this.ac.value) {
          this.ac.value.dndHandler.drop(e.dragAndDropData, void 0, e.eventData);
        } else {
          const dragData = e.dragAndDropData.getData();
          if (dragData.type === "composite") {
            const currentContainer = this.jc.getViewContainerById(dragData.id);
            this.jc.moveViewContainerToLocation(currentContainer, this.Wb, void 0, "dnd");
            this.openPaneComposite(currentContainer.id, true);
          } else if (dragData.type === "view") {
            const viewToMove = this.jc.getViewDescriptorById(dragData.id);
            if (viewToMove && viewToMove.canMoveView) {
              this.jc.moveViewToLocation(viewToMove, this.Wb, "dnd");
              const newContainer = this.jc.getViewContainerByViewId(viewToMove.id);
              this.openPaneComposite(newContainer.id, true).then((composite) => {
                composite?.openView(viewToMove.id, true);
              });
            }
          }
        }
      }
    }));
  }
  O(parent) {
    const titleArea = super.O(parent);
    this.B($_i(titleArea, $7j.CONTEXT_MENU, (e) => {
      this.Ic(new $lf(getWindow(titleArea), e));
    }));
    this.B($mZ.addTarget(titleArea));
    this.B($_i(titleArea, EventType.Contextmenu, (e) => {
      this.Ic(new $lf(getWindow(titleArea), e));
    }));
    const globalTitleActionsContainer = titleArea.appendChild($(".global-actions"));
    this.dc = this.B(this.ub.createInstance($3$, globalTitleActionsContainer, {
      actionViewItemProvider: (action, options3) => this.Qb(action, options3),
      orientation: 0,
      getKeyBinding: (action) => this.sb.lookupKeybinding(action.id),
      anchorAlignmentProvider: () => this.Tb(),
      toggleMenuTitle: localize(3689, null),
      hoverDelegate: this.db,
      hiddenItemStrategy: -1
      /* HiddenItemStrategy.NoHide */
    }));
    this.Gc();
    return titleArea;
  }
  Nb(parent) {
    this.Xb = parent;
    const titleLabel = super.Nb(parent);
    this.cb.draggable = true;
    const draggedItemProvider = () => {
      const activeViewlet = this.getActivePaneComposite();
      return { type: "composite", id: activeViewlet.getId() };
    };
    this.B($Iob.INSTANCE.registerDraggable(this.cb, draggedItemProvider, {}));
    return titleLabel;
  }
  vc(updateCompositeBarOption = false) {
    const wasCompositeBarVisible = this.bc !== void 0;
    const isCompositeBarVisible = this.Mc();
    const previousPosition = this.bc;
    const newPosition = isCompositeBarVisible ? this.Oc() : void 0;
    if (!updateCompositeBarOption && previousPosition === newPosition) {
      return;
    }
    if (wasCompositeBarVisible) {
      const previousCompositeBarContainer = previousPosition === CompositeBarPosition.TITLE ? this.Xb : this.Yb;
      if (!this.$b || !this.ac.value || !previousCompositeBarContainer) {
        throw new Error("Composite bar containers should exist when removing the previous composite bar");
      }
      this.$b.remove();
      this.$b = void 0;
      this.ac.value = void 0;
      previousCompositeBarContainer.classList.remove("has-composite-bar");
      if (previousPosition === CompositeBarPosition.TOP) {
        this.zc(true);
      } else if (previousPosition === CompositeBarPosition.BOTTOM) {
        this.zc(false);
      }
    }
    let newCompositeBarContainer;
    switch (newPosition) {
      case CompositeBarPosition.TOP:
        newCompositeBarContainer = this.Ob();
        break;
      case CompositeBarPosition.TITLE:
        newCompositeBarContainer = this.Xb;
        break;
      case CompositeBarPosition.BOTTOM:
        newCompositeBarContainer = this.Pb();
        break;
    }
    if (isCompositeBarVisible) {
      if (this.$b || this.ac.value || !newCompositeBarContainer) {
        throw new Error("Invalid composite bar state when creating the new composite bar");
      }
      newCompositeBarContainer.classList.add("has-composite-bar");
      this.$b = $ck(newCompositeBarContainer, $(".composite-bar-container"));
      this.ac.value = this.Ac();
      this.ac.value.create(this.$b);
      if (newPosition === CompositeBarPosition.TOP) {
        this.S(newCompositeBarContainer);
      } else if (newPosition === CompositeBarPosition.BOTTOM) {
        this.U(newCompositeBarContainer);
      }
    }
    this.bc = newPosition;
    if (updateCompositeBarOption) {
      this.Ec();
    }
  }
  Ob() {
    const headerArea = super.Ob();
    return this.yc(headerArea);
  }
  Pb() {
    const footerArea = super.Pb();
    return this.yc(footerArea);
  }
  yc(area) {
    if (this.Yb) {
      throw new Error("Header or Footer composite bar already exists");
    }
    this.Yb = area;
    this.Zb.add($_i(area, $7j.CONTEXT_MENU, (e) => {
      this.Jc(new $lf(getWindow(area), e));
    }));
    this.Zb.add($mZ.addTarget(area));
    this.Zb.add($_i(area, EventType.Contextmenu, (e) => {
      this.Jc(new $lf(getWindow(area), e));
    }));
    return area;
  }
  zc(header) {
    this.Yb = void 0;
    this.Zb.clear();
    if (header) {
      this.W();
    } else {
      this.X();
    }
  }
  Ac() {
    return this.ub.createInstance($aVb, this.Nc(), this.partId, this);
  }
  Gb(compositeId) {
    super.Gb(compositeId);
    this.Ec();
  }
  async openPaneComposite(id2, focus) {
    if (typeof id2 === "string" && this.getPaneComposite(id2)) {
      return this.Cc(id2, focus);
    }
    await this.lc.whenInstalledExtensionsRegistered();
    if (typeof id2 === "string" && this.getPaneComposite(id2)) {
      return this.Cc(id2, focus);
    }
    return void 0;
  }
  Cc(id2, focus) {
    if (this.fc) {
      return void 0;
    }
    if (!this.M.isVisible(this.partId)) {
      try {
        this.fc = true;
        this.M.setPartHidden(false, this.partId);
      } finally {
        this.fc = false;
      }
    }
    return this.Cb(id2, focus);
  }
  getPaneComposite(id2) {
    return this.vb.getPaneComposite(id2);
  }
  getPaneComposites() {
    return this.vb.getPaneComposites().sort((v1, v2) => {
      if (typeof v1.order !== "number") {
        return 1;
      }
      if (typeof v2.order !== "number") {
        return -1;
      }
      return v1.order - v2.order;
    });
  }
  getPinnedPaneCompositeIds() {
    return this.ac.value?.getPinnedPaneCompositeIds() ?? [];
  }
  getVisiblePaneCompositeIds() {
    return this.ac.value?.getVisiblePaneCompositeIds() ?? [];
  }
  getPaneCompositeIds() {
    return this.ac.value?.getPaneCompositeIds() ?? [];
  }
  getActivePaneComposite() {
    return this.Jb();
  }
  getLastActivePaneCompositeId() {
    return this.Kb();
  }
  hideActivePaneComposite() {
    if (this.M.isVisible(this.partId)) {
      this.M.setPartHidden(true, this.partId);
    }
    this.Lb();
  }
  Dc() {
    this.ac.value?.focus();
  }
  layout(width2, height, top2, left) {
    if (!this.M.isVisible(this.partId)) {
      return;
    }
    this.gc = new $rj(width2, height);
    super.layout(this.gc.width, this.gc.height, top2, left);
    this.Ec();
    this.Fc();
  }
  Ec() {
    if (this.gc && this.dimension && this.ac.value) {
      const padding = this.bc === CompositeBarPosition.TITLE ? 16 : 8;
      const borderWidth = this.partId === "workbench.parts.panel" ? 0 : 1;
      let availableWidth = this.gc.width - padding - borderWidth;
      availableWidth = Math.max($bVb_1.Vb, availableWidth - this.Hc());
      this.ac.value.layout(availableWidth, this.dimension.height);
    }
  }
  Fc() {
    const visible = !this.Jb();
    this.cc?.classList.toggle("visible", visible);
    if (visible) {
      this.jb?.updateTitle("", "");
    }
  }
  Gc() {
    const primaryActions = this.ec.getPrimaryActions();
    const secondaryActions = this.ec.getSecondaryActions();
    this.dc?.setActions($MZ(primaryActions), $MZ(secondaryActions));
  }
  Hc() {
    if (!this.bb || this.bc !== CompositeBarPosition.TITLE) {
      return 0;
    }
    const activePane = this.getActivePaneComposite();
    if (!activePane) {
      return 0;
    }
    const toolBarWidth = this.bb.getItemsWidth() + this.bb.getItemsLength() * 4;
    const globalToolBarWidth = this.dc ? this.dc.getItemsWidth() + this.dc.getItemsLength() * 4 : 0;
    return toolBarWidth + globalToolBarWidth + 5;
  }
  Ic(event) {
    if (this.Mc() && this.Oc() === CompositeBarPosition.TITLE) {
      return this.Kc(event);
    } else {
      const activePaneComposite = this.getActivePaneComposite();
      const activePaneCompositeActions = activePaneComposite ? activePaneComposite.getContextMenuActions() : [];
      if (activePaneCompositeActions.length) {
        this.rb.showContextMenu({
          getAnchor: () => event,
          getActions: () => activePaneCompositeActions,
          getActionViewItem: (action, options3) => this.Qb(action, options3),
          actionRunner: activePaneComposite.getActionRunner(),
          skipTelemetry: true
        });
      }
    }
  }
  Jc(event) {
    return this.Kc(event);
  }
  Kc(event) {
    if (this.ac.value) {
      const actions = [...this.ac.value.getContextMenuActions()];
      if (actions.length) {
        this.rb.showContextMenu({
          getAnchor: () => event,
          getActions: () => actions,
          skipTelemetry: true
        });
      }
    }
  }
  Lc() {
    const viewPaneContainer = this.getActivePaneComposite()?.getViewPaneContainer();
    if (viewPaneContainer) {
      const disposables = new $2c();
      const scopedContextKeyService = disposables.add(this.kc.createScoped(this.element));
      scopedContextKeyService.createKey("viewContainer", viewPaneContainer.viewContainer.id);
      const menu = this.mc.getMenuActions($nqb, scopedContextKeyService, { shouldForwardArgs: true, renderShortTitle: true });
      const viewsActions = $Q$(menu, () => true).primary;
      disposables.dispose();
      return viewsActions.length > 1 && viewsActions.some((a) => a.enabled) ? new $Xm("views", localize(3690, null), viewsActions) : void 0;
    }
    return void 0;
  }
};
$bVb = $bVb_1 = __decorate([
  __param(9, $PJ),
  __param(10, $jv),
  __param(11, $50),
  __param(12, $Vlb),
  __param(13, $Ty),
  __param(14, $5$),
  __param(15, $Pk),
  __param(16, $gs),
  __param(17, $$M),
  __param(18, $on),
  __param(19, $wN),
  __param(20, $cJ)
], $bVb);

// out-build/vs/workbench/browser/parts/auxiliarybar/auxiliaryBarPart.js
var $cVb_1;
var $cVb = class $cVb2 extends $bVb {
  static {
    $cVb_1 = this;
  }
  static {
    this.activePanelSettingsKey = "workbench.auxiliarybar.activepanelid";
  }
  static {
    this.pinnedPanelsKey = "workbench.auxiliarybar.pinnedPanels";
  }
  static {
    this.placeholdeViewContainersKey = "workbench.auxiliarybar.placeholderPanels";
  }
  static {
    this.viewContainersWorkspaceStateKey = "workbench.auxiliarybar.viewContainersWorkspaceState";
  }
  get preferredHeight() {
    return this.M.mainContainerDimension.height * 0.4;
  }
  get preferredWidth() {
    const activeComposite = this.getActivePaneComposite();
    if (!activeComposite) {
      return;
    }
    const width2 = activeComposite.getOptimalWidth();
    if (typeof width2 !== "number") {
      return;
    }
    return Math.max(width2, 300);
  }
  constructor(notificationService, storageService, contextMenuService, layoutService, keybindingService, hoverService, instantiationService, themeService, viewDescriptorService, contextKeyService, extensionService, Pc, menuService, Qc) {
    super("workbench.parts.auxiliarybar", {
      hasTitle: true,
      borderWidth: () => this.z($Rnb) || this.z($ko) ? 1 : 0
    }, $cVb_1.activePanelSettingsKey, $aqb.bindTo(contextKeyService), $bqb.bindTo(contextKeyService), "auxiliarybar", "auxiliarybar", void 0, $Unb, notificationService, storageService, contextMenuService, layoutService, keybindingService, hoverService, instantiationService, themeService, viewDescriptorService, contextKeyService, extensionService, menuService);
    this.Pc = Pc;
    this.Qc = Qc;
    this.minimumWidth = 170;
    this.maximumWidth = Number.POSITIVE_INFINITY;
    this.minimumHeight = 0;
    this.maximumHeight = Number.POSITIVE_INFINITY;
    this.priority = 1;
    this.B(Qc.onDidChangeConfiguration((e) => {
      if (e.affectsConfiguration(
        "workbench.activityBar.location"
        /* LayoutSettings.ACTIVITY_BAR_LOCATION */
      )) {
        this.Rc();
      }
    }));
  }
  Rc() {
    this.vc();
    const id2 = this.Jb()?.getId();
    if (id2) {
      this.Gb(id2);
    }
  }
  updateStyles() {
    super.updateStyles();
    const container2 = $Kg(this.getContainer());
    container2.style.backgroundColor = this.z($Pnb) || "";
    const borderColor = this.z($Rnb) || this.z($ko);
    const isPositionLeft = this.M.getSideBarPosition() === 1;
    container2.style.color = this.z($Qnb) || "";
    container2.style.borderLeftColor = borderColor ?? "";
    container2.style.borderRightColor = borderColor ?? "";
    container2.style.borderLeftStyle = borderColor && !isPositionLeft ? "solid" : "none";
    container2.style.borderRightStyle = borderColor && isPositionLeft ? "solid" : "none";
    container2.style.borderLeftWidth = borderColor && !isPositionLeft ? "1px" : "0px";
    container2.style.borderRightWidth = borderColor && isPositionLeft ? "1px" : "0px";
  }
  Nc() {
    const $this = this;
    return {
      partContainerClass: "auxiliarybar",
      pinnedViewContainersKey: $cVb_1.pinnedPanelsKey,
      placeholderViewContainersKey: $cVb_1.placeholdeViewContainersKey,
      viewContainersWorkspaceStateKey: $cVb_1.viewContainersWorkspaceStateKey,
      icon: true,
      orientation: 0,
      recomputeSizes: true,
      activityHoverOptions: {
        position: () => this.Oc() === CompositeBarPosition.BOTTOM ? 3 : 2
      },
      fillExtraContextMenuActions: (actions) => this.Tc(actions),
      compositeSize: 0,
      iconSize: 16,
      // Add 10px spacing if the overflow action is visible to no confuse the user with ... between the toolbars
      get overflowActionSize() {
        return $this.Oc() === CompositeBarPosition.TITLE ? 40 : 30;
      },
      colors: (theme) => ({
        activeBackgroundColor: theme.getColor($Pnb),
        inactiveBackgroundColor: theme.getColor($Pnb),
        get activeBorderBottomColor() {
          return $this.Oc() === CompositeBarPosition.TITLE ? theme.getColor($Nmb) : theme.getColor($ynb);
        },
        get activeForegroundColor() {
          return $this.Oc() === CompositeBarPosition.TITLE ? theme.getColor($Lmb) : theme.getColor($xnb);
        },
        get inactiveForegroundColor() {
          return $this.Oc() === CompositeBarPosition.TITLE ? theme.getColor($Mmb) : theme.getColor($Anb);
        },
        badgeBackground: theme.getColor($vnb),
        badgeForeground: theme.getColor($wnb),
        get dragAndDropBorder() {
          return $this.Oc() === CompositeBarPosition.TITLE ? theme.getColor($Pmb) : theme.getColor($Bnb);
        }
      }),
      compact: true
    };
  }
  Tc(actions) {
    const currentPositionRight = this.M.getSideBarPosition() === 0;
    if (this.Oc() === CompositeBarPosition.TITLE) {
      const viewsSubmenuAction = this.Lc();
      if (viewsSubmenuAction) {
        actions.push(new $Wm());
        actions.push(viewsSubmenuAction);
      }
    }
    const activityBarPositionMenu = this.mc.getMenuActions($bJ.ActivityBarPositionMenu, this.kc, { shouldForwardArgs: true, renderShortTitle: true });
    const positionActions = $O$(activityBarPositionMenu).secondary;
    actions.push(...[
      new $Wm(),
      new $Xm("workbench.action.panel.position", localize(3083, null), positionActions),
      $Zm({ id: $Oqb.ID, label: currentPositionRight ? localize(3084, null) : localize(3085, null), run: () => this.Pc.executeCommand($Oqb.ID) }),
      $Zm({ id: $Jqb.ID, label: localize(3086, null), run: () => this.Pc.executeCommand($Jqb.ID) })
    ]);
  }
  Mc() {
    return this.Qc.getValue(
      "workbench.activityBar.location"
      /* LayoutSettings.ACTIVITY_BAR_LOCATION */
    ) !== "hidden";
  }
  // TODO@benibenj chache this
  Oc() {
    const activityBarPosition = this.Qc.getValue(
      "workbench.activityBar.location"
      /* LayoutSettings.ACTIVITY_BAR_LOCATION */
    );
    switch (activityBarPosition) {
      case "top":
        return CompositeBarPosition.TOP;
      case "bottom":
        return CompositeBarPosition.BOTTOM;
      case "hidden":
        return CompositeBarPosition.TITLE;
      case "default":
        return CompositeBarPosition.TITLE;
      default:
        return CompositeBarPosition.TITLE;
    }
  }
  Ob() {
    const headerArea = super.Ob();
    const globalHeaderContainer = $(".auxiliary-bar-global-header");
    const menu = this.Zb.add(this.ub.createInstance($yob, $bJ.AuxiliaryBarHeader, void 0, void 0));
    const toolBar = this.Zb.add(this.ub.createInstance($3$, globalHeaderContainer, {
      actionViewItemProvider: (action, options3) => this.Xc(action, options3),
      orientation: 0,
      hiddenItemStrategy: -1,
      getKeyBinding: (action) => this.sb.lookupKeybinding(action.id)
    }));
    toolBar.setActions($MZ(menu.getPrimaryActions()));
    this.Zb.add(menu.onDidChange(() => toolBar.setActions($MZ(menu.getPrimaryActions()))));
    headerArea.appendChild(globalHeaderContainer);
    return headerArea;
  }
  Xc(action, options3) {
    if (action.id === $Jqb.ID) {
      return this.ub.createInstance($U1, void 0, action, options3);
    }
    return void 0;
  }
  toJSON() {
    return {
      type: "workbench.parts.auxiliarybar"
      /* Parts.AUXILIARYBAR_PART */
    };
  }
};
$cVb = $cVb_1 = __decorate([
  __param(0, $PJ),
  __param(1, $jv),
  __param(2, $50),
  __param(3, $Vlb),
  __param(4, $Ty),
  __param(5, $5$),
  __param(6, $Pk),
  __param(7, $gs),
  __param(8, $$M),
  __param(9, $on),
  __param(10, $wN),
  __param(11, $sn),
  __param(12, $cJ),
  __param(13, $kl)
], $cVb);

// out-build/vs/workbench/browser/parts/panel/panelPart.js
var $dVb_1;
var $dVb = class $dVb2 extends $bVb {
  static {
    $dVb_1 = this;
  }
  get preferredHeight() {
    return this.M.mainContainerDimension.height * 0.4;
  }
  get preferredWidth() {
    const activeComposite = this.getActivePaneComposite();
    if (!activeComposite) {
      return;
    }
    const width2 = activeComposite.getOptimalWidth();
    if (typeof width2 !== "number") {
      return;
    }
    return Math.max(width2, 300);
  }
  static {
    this.activePanelSettingsKey = "workbench.panelpart.activepanelid";
  }
  constructor(notificationService, storageService, contextMenuService, layoutService, keybindingService, hoverService, instantiationService, themeService, viewDescriptorService, contextKeyService, extensionService, Pc, menuService, Qc) {
    super("workbench.parts.panel", { hasTitle: true }, $dVb_1.activePanelSettingsKey, $dqb.bindTo(contextKeyService), $eqb.bindTo(contextKeyService), "panel", "panel", void 0, $Kmb, notificationService, storageService, contextMenuService, layoutService, keybindingService, hoverService, instantiationService, themeService, viewDescriptorService, contextKeyService, extensionService, menuService);
    this.Pc = Pc;
    this.Qc = Qc;
    this.minimumWidth = 300;
    this.maximumWidth = Number.POSITIVE_INFINITY;
    this.minimumHeight = 77;
    this.maximumHeight = Number.POSITIVE_INFINITY;
    this.B(this.Qc.onDidChangeConfiguration((e) => {
      if (e.affectsConfiguration("workbench.panel.showLabels")) {
        this.vc(true);
      }
    }));
  }
  updateStyles() {
    super.updateStyles();
    const container2 = $Kg(this.getContainer());
    container2.style.backgroundColor = this.z($Imb) || "";
    const borderColor = this.z($Jmb) || this.z($ko) || "";
    container2.style.borderLeftColor = borderColor;
    container2.style.borderRightColor = borderColor;
    container2.style.borderBottomColor = borderColor;
    const title = this.P();
    if (title) {
      title.style.borderTopColor = this.z($Jmb) || this.z($ko) || "";
    }
  }
  Nc() {
    return {
      partContainerClass: "panel",
      pinnedViewContainersKey: "workbench.panel.pinnedPanels",
      placeholderViewContainersKey: "workbench.panel.placeholderPanels",
      viewContainersWorkspaceStateKey: "workbench.panel.viewContainersWorkspaceState",
      icon: this.Qc.getValue("workbench.panel.showLabels") === false,
      orientation: 0,
      recomputeSizes: true,
      activityHoverOptions: {
        position: () => this.M.getPanelPosition() === 2 && !this.M.isPanelMaximized() ? 3 : 2
      },
      fillExtraContextMenuActions: (actions) => this.Sc(actions),
      compositeSize: 0,
      iconSize: 16,
      compact: true,
      // Only applies to icons, not labels
      overflowActionSize: 44,
      colors: (theme) => ({
        activeBackgroundColor: theme.getColor($Imb),
        // Background color for overflow action
        inactiveBackgroundColor: theme.getColor($Imb),
        // Background color for overflow action
        activeBorderBottomColor: theme.getColor($Nmb),
        activeForegroundColor: theme.getColor($Lmb),
        inactiveForegroundColor: theme.getColor($Mmb),
        badgeBackground: theme.getColor($wo),
        badgeForeground: theme.getColor($xo),
        dragAndDropBorder: theme.getColor($Pmb)
      })
    };
  }
  Sc(actions) {
    if (this.Oc() === CompositeBarPosition.TITLE) {
      const viewsSubmenuAction = this.Lc();
      if (viewsSubmenuAction) {
        actions.push(new $Wm());
        actions.push(viewsSubmenuAction);
      }
    }
    const panelPositionMenu = this.mc.getMenuActions($bJ.PanelPositionMenu, this.kc, { shouldForwardArgs: true });
    const panelAlignMenu = this.mc.getMenuActions($bJ.PanelAlignmentMenu, this.kc, { shouldForwardArgs: true });
    const positionActions = $O$(panelPositionMenu).secondary;
    const alignActions = $O$(panelAlignMenu).secondary;
    const panelShowLabels = this.Qc.getValue("workbench.panel.showLabels");
    const toggleShowLabelsAction = $Zm({
      id: "workbench.action.panel.toggleShowLabels",
      label: panelShowLabels ? localize(3733, null) : localize(3734, null),
      run: () => this.Qc.updateValue("workbench.panel.showLabels", !panelShowLabels)
    });
    actions.push(...[
      new $Wm(),
      new $Xm("workbench.action.panel.position", localize(3735, null), positionActions),
      new $Xm("workbench.action.panel.align", localize(3736, null), alignActions),
      toggleShowLabelsAction,
      $Zm({ id: $Kqb.ID, label: localize(3737, null), run: () => this.Pc.executeCommand($Kqb.ID) })
    ]);
  }
  layout(width2, height, top2, left) {
    let dimensions;
    switch (this.M.getPanelPosition()) {
      case 1:
        dimensions = new $rj(width2 - 1, height);
        break;
      case 3:
        dimensions = new $rj(width2, height - 1);
        break;
      default:
        dimensions = new $rj(width2, height);
        break;
    }
    super.layout(dimensions.width, dimensions.height, top2, left);
  }
  Mc() {
    return true;
  }
  Oc() {
    return CompositeBarPosition.TITLE;
  }
  toJSON() {
    return {
      type: "workbench.parts.panel"
      /* Parts.PANEL_PART */
    };
  }
};
$dVb = $dVb_1 = __decorate([
  __param(0, $PJ),
  __param(1, $jv),
  __param(2, $50),
  __param(3, $Vlb),
  __param(4, $Ty),
  __param(5, $5$),
  __param(6, $Pk),
  __param(7, $gs),
  __param(8, $$M),
  __param(9, $on),
  __param(10, $wN),
  __param(11, $sn),
  __param(12, $cJ),
  __param(13, $kl)
], $dVb);

// out-build/vs/workbench/browser/parts/sidebar/sidebarActions.js
var $eVb = class extends $gJ {
  constructor() {
    super({
      id: "workbench.action.focusSideBar",
      title: localize2(3738, "Focus into Primary Side Bar"),
      category: $qn.View,
      f1: true,
      keybinding: {
        weight: 200,
        when: null,
        primary: 2048 | 21
        /* KeyCode.Digit0 */
      }
    });
  }
  async run(accessor) {
    const layoutService = accessor.get($Vlb);
    const paneCompositeService = accessor.get($uqb);
    if (!layoutService.isVisible(
      "workbench.parts.sidebar"
      /* Parts.SIDEBAR_PART */
    )) {
      layoutService.setPartHidden(
        false,
        "workbench.parts.sidebar"
        /* Parts.SIDEBAR_PART */
      );
    }
    const viewlet = paneCompositeService.getActivePaneComposite(
      0
      /* ViewContainerLocation.Sidebar */
    );
    viewlet?.focus();
  }
};
$hJ($eVb);

// out-build/vs/base/browser/ui/contextview/contextview.js
var ContextViewDOMPosition;
(function(ContextViewDOMPosition2) {
  ContextViewDOMPosition2[ContextViewDOMPosition2["ABSOLUTE"] = 1] = "ABSOLUTE";
  ContextViewDOMPosition2[ContextViewDOMPosition2["FIXED"] = 2] = "FIXED";
  ContextViewDOMPosition2[ContextViewDOMPosition2["FIXED_SHADOW"] = 3] = "FIXED_SHADOW";
})(ContextViewDOMPosition || (ContextViewDOMPosition = {}));
function $NZ(obj) {
  const anchor = obj;
  return !!anchor && typeof anchor.x === "number" && typeof anchor.y === "number";
}
var AnchorAlignment;
(function(AnchorAlignment2) {
  AnchorAlignment2[AnchorAlignment2["LEFT"] = 0] = "LEFT";
  AnchorAlignment2[AnchorAlignment2["RIGHT"] = 1] = "RIGHT";
})(AnchorAlignment || (AnchorAlignment = {}));
var AnchorPosition;
(function(AnchorPosition2) {
  AnchorPosition2[AnchorPosition2["BELOW"] = 0] = "BELOW";
  AnchorPosition2[AnchorPosition2["ABOVE"] = 1] = "ABOVE";
})(AnchorPosition || (AnchorPosition = {}));
var AnchorAxisAlignment;
(function(AnchorAxisAlignment2) {
  AnchorAxisAlignment2[AnchorAxisAlignment2["VERTICAL"] = 0] = "VERTICAL";
  AnchorAxisAlignment2[AnchorAxisAlignment2["HORIZONTAL"] = 1] = "HORIZONTAL";
})(AnchorAxisAlignment || (AnchorAxisAlignment = {}));
var LayoutAnchorPosition;
(function(LayoutAnchorPosition2) {
  LayoutAnchorPosition2[LayoutAnchorPosition2["Before"] = 0] = "Before";
  LayoutAnchorPosition2[LayoutAnchorPosition2["After"] = 1] = "After";
})(LayoutAnchorPosition || (LayoutAnchorPosition = {}));
var LayoutAnchorMode;
(function(LayoutAnchorMode2) {
  LayoutAnchorMode2[LayoutAnchorMode2["AVOID"] = 0] = "AVOID";
  LayoutAnchorMode2[LayoutAnchorMode2["ALIGN"] = 1] = "ALIGN";
})(LayoutAnchorMode || (LayoutAnchorMode = {}));
function $OZ(viewportSize, viewSize, anchor) {
  const layoutAfterAnchorBoundary = anchor.mode === LayoutAnchorMode.ALIGN ? anchor.offset : anchor.offset + anchor.size;
  const layoutBeforeAnchorBoundary = anchor.mode === LayoutAnchorMode.ALIGN ? anchor.offset + anchor.size : anchor.offset;
  if (anchor.position === 0) {
    if (viewSize <= viewportSize - layoutAfterAnchorBoundary) {
      return layoutAfterAnchorBoundary;
    }
    if (viewSize <= layoutBeforeAnchorBoundary) {
      return layoutBeforeAnchorBoundary - viewSize;
    }
    return Math.max(viewportSize - viewSize, 0);
  } else {
    if (viewSize <= layoutBeforeAnchorBoundary) {
      return layoutBeforeAnchorBoundary - viewSize;
    }
    if (viewSize <= viewportSize - layoutAfterAnchorBoundary) {
      return layoutAfterAnchorBoundary;
    }
    return 0;
  }
}
var $PZ = class _$PZ extends $3c {
  static {
    this.a = ["click", "keydown", "focus", "blur"];
  }
  static {
    this.b = ["click"];
  }
  constructor(container2, domPosition) {
    super();
    this.c = null;
    this.g = false;
    this.h = false;
    this.j = null;
    this.m = $3c.None;
    this.n = $3c.None;
    this.r = null;
    this.s = null;
    this.f = $(".context-view");
    $ik(this.f);
    this.setContainer(container2, domPosition);
    this.B($1c(() => this.setContainer(
      null,
      1
      /* ContextViewDOMPosition.ABSOLUTE */
    )));
  }
  setContainer(container2, domPosition) {
    this.g = domPosition !== 1;
    const usedShadowDOM = this.h;
    this.h = domPosition === 3;
    if (container2 === this.c && usedShadowDOM === this.h) {
      return;
    }
    if (this.c) {
      this.n.dispose();
      this.f.remove();
      if (this.r) {
        this.r = null;
        this.s?.remove();
        this.s = null;
      }
      this.c = null;
    }
    if (container2) {
      this.c = container2;
      if (this.h) {
        this.s = $(".shadow-root-host");
        this.c.appendChild(this.s);
        this.r = this.s.attachShadow({ mode: "open" });
        const style = document.createElement("style");
        style.textContent = SHADOW_ROOT_CSS;
        this.r.appendChild(style);
        this.r.appendChild(this.f);
        this.r.appendChild($("slot"));
      } else {
        this.c.appendChild(this.f);
      }
      const toDisposeOnSetContainer = new $2c();
      _$PZ.a.forEach((event) => {
        toDisposeOnSetContainer.add($aj(this.c, event, (e) => {
          this.w(e, false);
        }));
      });
      _$PZ.b.forEach((event) => {
        toDisposeOnSetContainer.add($aj(this.c, event, (e) => {
          this.w(e, true);
        }, true));
      });
      this.n = toDisposeOnSetContainer;
    }
  }
  show(delegate) {
    if (this.u()) {
      this.hide();
    }
    $$i(this.f);
    this.f.className = "context-view monaco-component";
    this.f.style.top = "0px";
    this.f.style.left = "0px";
    this.f.style.zIndex = `${2575 + (delegate.layer ?? 0)}`;
    this.f.style.position = this.g ? "fixed" : "absolute";
    $hk(this.f);
    this.m = delegate.render(this.f) || $3c.None;
    this.j = delegate;
    this.t();
    this.j.focus?.();
  }
  getViewElement() {
    return this.f;
  }
  layout() {
    if (!this.u()) {
      return;
    }
    if (this.j.canRelayout === false && !($u && $5e.pointerEvents)) {
      this.hide();
      return;
    }
    this.j?.layout?.();
    this.t();
  }
  t() {
    if (!this.u()) {
      return;
    }
    const anchor = this.j.getAnchor();
    let around;
    if ($Uj(anchor)) {
      const elementPosition = $vj(anchor);
      const zoom = $wj(anchor);
      around = {
        top: elementPosition.top * zoom,
        left: elementPosition.left * zoom,
        width: elementPosition.width * zoom,
        height: elementPosition.height * zoom
      };
    } else if ($NZ(anchor)) {
      around = {
        top: anchor.y,
        left: anchor.x,
        width: anchor.width || 1,
        height: anchor.height || 2
      };
    } else {
      around = {
        top: anchor.posy,
        left: anchor.posx,
        // We are about to position the context view where the mouse
        // cursor is. To prevent the view being exactly under the mouse
        // when showing and thus potentially triggering an action within,
        // we treat the mouse location like a small sized block element.
        width: 2,
        height: 2
      };
    }
    const viewSizeWidth = $xj(this.f);
    const viewSizeHeight = $Bj(this.f);
    const anchorPosition = this.j.anchorPosition ?? 0;
    const anchorAlignment = this.j.anchorAlignment ?? 0;
    const anchorAxisAlignment = this.j.anchorAxisAlignment ?? 0;
    let top2;
    let left;
    const activeWindow = $Qj();
    if (anchorAxisAlignment === 0) {
      const verticalAnchor = {
        offset: around.top - activeWindow.pageYOffset,
        size: around.height,
        position: anchorPosition === 0 ? 0 : 1
        /* LayoutAnchorPosition.After */
      };
      const horizontalAnchor = { offset: around.left, size: around.width, position: anchorAlignment === 0 ? 0 : 1, mode: LayoutAnchorMode.ALIGN };
      top2 = $OZ(activeWindow.innerHeight, viewSizeHeight, verticalAnchor) + activeWindow.pageYOffset;
      if (Range2.intersects({ start: top2, end: top2 + viewSizeHeight }, { start: verticalAnchor.offset, end: verticalAnchor.offset + verticalAnchor.size })) {
        horizontalAnchor.mode = LayoutAnchorMode.AVOID;
      }
      left = $OZ(activeWindow.innerWidth, viewSizeWidth, horizontalAnchor);
    } else {
      const horizontalAnchor = {
        offset: around.left,
        size: around.width,
        position: anchorAlignment === 0 ? 0 : 1
        /* LayoutAnchorPosition.After */
      };
      const verticalAnchor = { offset: around.top, size: around.height, position: anchorPosition === 0 ? 0 : 1, mode: LayoutAnchorMode.ALIGN };
      left = $OZ(activeWindow.innerWidth, viewSizeWidth, horizontalAnchor);
      if (Range2.intersects({ start: left, end: left + viewSizeWidth }, { start: horizontalAnchor.offset, end: horizontalAnchor.offset + horizontalAnchor.size })) {
        verticalAnchor.mode = LayoutAnchorMode.AVOID;
      }
      top2 = $OZ(activeWindow.innerHeight, viewSizeHeight, verticalAnchor) + activeWindow.pageYOffset;
    }
    this.f.classList.remove("top", "bottom", "left", "right");
    this.f.classList.add(anchorPosition === 0 ? "bottom" : "top");
    this.f.classList.add(anchorAlignment === 0 ? "left" : "right");
    this.f.classList.toggle("fixed", this.g);
    const containerPosition = $vj(this.c);
    this.f.style.top = `${top2 - (this.g ? $vj(this.f).top : containerPosition.top)}px`;
    this.f.style.left = `${left - (this.g ? $vj(this.f).left : containerPosition.left)}px`;
    this.f.style.width = "initial";
  }
  hide(data) {
    const delegate = this.j;
    this.j = null;
    if (delegate?.onHide) {
      delegate.onHide(data);
    }
    this.m.dispose();
    $ik(this.f);
  }
  u() {
    return !!this.j;
  }
  w(e, onCapture) {
    if (this.j) {
      if (this.j.onDOMEvent) {
        this.j.onDOMEvent(e, getWindow(e).document.activeElement);
      } else if (onCapture && !$Dj(e.target, this.c)) {
        this.hide();
      }
    }
  }
  dispose() {
    this.hide();
    super.dispose();
  }
};
var SHADOW_ROOT_CSS = (
  /* css */
  `
	:host {
		all: initial; /* 1st rule so subsequent properties are reset. */
	}

	.codicon[class*='codicon-'] {
		font: normal normal normal 16px/1 codicon;
		display: inline-block;
		text-decoration: none;
		text-rendering: auto;
		text-align: center;
		-webkit-font-smoothing: antialiased;
		-moz-osx-font-smoothing: grayscale;
		user-select: none;
		-webkit-user-select: none;
		-ms-user-select: none;
	}

	:host {
		font-family: -apple-system, BlinkMacSystemFont, "Segoe WPC", "Segoe UI", "HelveticaNeue-Light", system-ui, "Ubuntu", "Droid Sans", sans-serif;
	}

	:host-context(.mac) { font-family: -apple-system, BlinkMacSystemFont, sans-serif; }
	:host-context(.mac:lang(zh-Hans)) { font-family: -apple-system, BlinkMacSystemFont, "PingFang SC", "Hiragino Sans GB", sans-serif; }
	:host-context(.mac:lang(zh-Hant)) { font-family: -apple-system, BlinkMacSystemFont, "PingFang TC", sans-serif; }
	:host-context(.mac:lang(ja)) { font-family: -apple-system, BlinkMacSystemFont, "Hiragino Kaku Gothic Pro", sans-serif; }
	:host-context(.mac:lang(ko)) { font-family: -apple-system, BlinkMacSystemFont, "Apple SD Gothic Neo", "Nanum Gothic", "AppleGothic", sans-serif; }

	:host-context(.windows) { font-family: "Segoe WPC", "Segoe UI", sans-serif; }
	:host-context(.windows:lang(zh-Hans)) { font-family: "Segoe WPC", "Segoe UI", "Microsoft YaHei", sans-serif; }
	:host-context(.windows:lang(zh-Hant)) { font-family: "Segoe WPC", "Segoe UI", "Microsoft Jhenghei", sans-serif; }
	:host-context(.windows:lang(ja)) { font-family: "Segoe WPC", "Segoe UI", "Yu Gothic UI", "Meiryo UI", sans-serif; }
	:host-context(.windows:lang(ko)) { font-family: "Segoe WPC", "Segoe UI", "Malgun Gothic", "Dotom", sans-serif; }

	:host-context(.linux) { font-family: system-ui, "Ubuntu", "Droid Sans", sans-serif; }
	:host-context(.linux:lang(zh-Hans)) { font-family: system-ui, "Ubuntu", "Droid Sans", "Source Han Sans SC", "Source Han Sans CN", "Source Han Sans", sans-serif; }
	:host-context(.linux:lang(zh-Hant)) { font-family: system-ui, "Ubuntu", "Droid Sans", "Source Han Sans TC", "Source Han Sans TW", "Source Han Sans", sans-serif; }
	:host-context(.linux:lang(ja)) { font-family: system-ui, "Ubuntu", "Droid Sans", "Source Han Sans J", "Source Han Sans JP", "Source Han Sans", sans-serif; }
	:host-context(.linux:lang(ko)) { font-family: system-ui, "Ubuntu", "Droid Sans", "Source Han Sans K", "Source Han Sans JR", "Source Han Sans", "UnDotum", "FBaekmuk Gulim", sans-serif; }
`
);

// out-build/vs/base/browser/ui/menu/menu.js
var $c2 = /\(&([^\s&])\)|(^|[^&])&([^\s&])/;
var $d2 = /(&amp;)?(&amp;)([^\s&])/g;
var HorizontalDirection;
(function(HorizontalDirection2) {
  HorizontalDirection2[HorizontalDirection2["Right"] = 0] = "Right";
  HorizontalDirection2[HorizontalDirection2["Left"] = 1] = "Left";
})(HorizontalDirection || (HorizontalDirection = {}));
var VerticalDirection;
(function(VerticalDirection2) {
  VerticalDirection2[VerticalDirection2["Above"] = 0] = "Above";
  VerticalDirection2[VerticalDirection2["Below"] = 1] = "Below";
})(VerticalDirection || (VerticalDirection = {}));
var $f2 = class _$f2 extends $LZ {
  constructor(container2, actions, options3, Z) {
    container2.classList.add("monaco-menu-container");
    container2.setAttribute("role", "presentation");
    const menuElement = document.createElement("div");
    menuElement.classList.add("monaco-menu");
    menuElement.setAttribute("role", "presentation");
    super(menuElement, {
      orientation: 1,
      actionViewItemProvider: (action) => this.fb(action, options3, parentData),
      context: options3.context,
      actionRunner: options3.actionRunner,
      ariaLabel: options3.ariaLabel,
      ariaRole: "menu",
      focusOnlyEnabledItems: true,
      triggerKeys: { keys: [3, ...$m || $n ? [
        10
        /* KeyCode.Space */
      ] : []], keyDown: true }
    });
    this.Z = Z;
    this.X = menuElement;
    this.C.tabIndex = 0;
    this.ab(container2, Z);
    this.B($mZ.addTarget(menuElement));
    this.B($_i(menuElement, $7j.KEY_DOWN, (e) => {
      const event = new $if(e);
      if (event.equals(
        2
        /* KeyCode.Tab */
      )) {
        e.preventDefault();
      }
    }));
    if (options3.enableMnemonics) {
      this.B($_i(menuElement, $7j.KEY_DOWN, (e) => {
        const key2 = e.key.toLocaleLowerCase();
        if (this.U.has(key2)) {
          $9j.stop(e, true);
          const actions2 = this.U.get(key2);
          if (actions2.length === 1) {
            if (actions2[0] instanceof SubmenuMenuActionViewItem && actions2[0].container) {
              this.cb(actions2[0].container);
            }
            actions2[0].onClick(e);
          }
          if (actions2.length > 1) {
            const action = actions2.shift();
            if (action && action.container) {
              this.cb(action.container);
              actions2.push(action);
            }
            this.U.set(key2, actions2);
          }
        }
      }));
    }
    if ($n) {
      this.B($_i(menuElement, $7j.KEY_DOWN, (e) => {
        const event = new $if(e);
        if (event.equals(
          14
          /* KeyCode.Home */
        ) || event.equals(
          11
          /* KeyCode.PageUp */
        )) {
          this.u = this.viewItems.length - 1;
          this.P();
          $9j.stop(e, true);
        } else if (event.equals(
          13
          /* KeyCode.End */
        ) || event.equals(
          12
          /* KeyCode.PageDown */
        )) {
          this.u = 0;
          this.Q();
          $9j.stop(e, true);
        }
      }));
    }
    this.B($_i(this.domNode, $7j.MOUSE_OUT, (e) => {
      const relatedTarget = e.relatedTarget;
      if (!$Dj(relatedTarget, this.domNode)) {
        this.u = void 0;
        this.R();
        e.stopPropagation();
      }
    }));
    this.B($_i(this.C, $7j.MOUSE_OVER, (e) => {
      let target = e.target;
      if (!target || !$Dj(target, this.C) || target === this.C) {
        return;
      }
      while (target.parentElement !== this.C && target.parentElement !== null) {
        target = target.parentElement;
      }
      if (target.classList.contains("action-item")) {
        const lastFocusedItem = this.u;
        this.db(target);
        if (lastFocusedItem !== this.u) {
          this.R();
        }
      }
    }));
    this.B($mZ.addTarget(this.C));
    this.B($_i(this.C, EventType.Tap, (e) => {
      let target = e.initialTarget;
      if (!target || !$Dj(target, this.C) || target === this.C) {
        return;
      }
      while (target.parentElement !== this.C && target.parentElement !== null) {
        target = target.parentElement;
      }
      if (target.classList.contains("action-item")) {
        const lastFocusedItem = this.u;
        this.db(target);
        if (lastFocusedItem !== this.u) {
          this.R();
        }
      }
    }));
    const parentData = {
      parent: this
    };
    this.U = /* @__PURE__ */ new Map();
    this.W = this.B(new $CZ(menuElement, {
      alwaysConsumeMouseWheel: true,
      horizontal: 2,
      vertical: 3,
      verticalScrollbarSize: 7,
      handleMouseWheel: true,
      useShadows: true
    }));
    const scrollElement = this.W.getDomNode();
    scrollElement.style.position = "";
    this.bb(scrollElement, Z);
    this.B($_i(menuElement, EventType.Change, (e) => {
      $9j.stop(e, true);
      const scrollTop = this.W.getScrollPosition().scrollTop;
      this.W.setScrollPosition({ scrollTop: scrollTop - e.translationY });
    }));
    this.B($_i(scrollElement, $7j.MOUSE_UP, (e) => {
      e.preventDefault();
    }));
    const window3 = getWindow(container2);
    menuElement.style.maxHeight = `${Math.max(10, window3.innerHeight - container2.getBoundingClientRect().top - 35)}px`;
    actions = actions.filter((a, idx) => {
      if (options3.submenuIds?.has(a.id)) {
        console.warn(`Found submenu cycle: ${a.id}`);
        return false;
      }
      if (a instanceof $Wm) {
        if (idx === actions.length - 1 || idx === 0) {
          return false;
        }
        const prevAction = actions[idx - 1];
        if (prevAction instanceof $Wm) {
          return false;
        }
      }
      return true;
    });
    this.push(actions, { icon: true, label: true, isMenu: true });
    container2.appendChild(this.W.getDomNode());
    this.W.scanDomNode();
    this.viewItems.filter((item) => !(item instanceof MenuSeparatorActionViewItem)).forEach((item, index, array2) => {
      item.updatePositionInSet(index + 1, array2.length);
    });
  }
  ab(container2, style) {
    if (!this.Y) {
      if ($Jj(container2)) {
        this.Y = $VZ(container2);
      } else {
        if (!_$f2.globalStyleSheet) {
          _$f2.globalStyleSheet = $VZ();
        }
        this.Y = _$f2.globalStyleSheet;
      }
    }
    this.Y.textContent = getMenuWidgetCSS(style, $Jj(container2));
  }
  bb(scrollElement, style) {
    const fgColor = style.foregroundColor ?? "";
    const bgColor = style.backgroundColor ?? "";
    const border = style.borderColor ? `1px solid ${style.borderColor}` : "";
    const borderRadius = "5px";
    const shadow = style.shadowColor ? `0 2px 8px ${style.shadowColor}` : "";
    scrollElement.style.outline = border;
    scrollElement.style.borderRadius = borderRadius;
    scrollElement.style.color = fgColor;
    scrollElement.style.backgroundColor = bgColor;
    scrollElement.style.boxShadow = shadow;
  }
  getContainer() {
    return this.W.getDomNode();
  }
  get onScroll() {
    return this.W.onScroll;
  }
  get scrollOffset() {
    return this.X.scrollTop;
  }
  trigger(index) {
    if (index <= this.viewItems.length && index >= 0) {
      const item = this.viewItems[index];
      if (item instanceof SubmenuMenuActionViewItem) {
        super.focus(index);
        item.open(true);
      } else if (item instanceof BaseMenuActionViewItem) {
        super.run(item._action, item._context);
      } else {
        return;
      }
    }
  }
  cb(element) {
    const lastFocusedItem = this.u;
    this.db(element);
    if (lastFocusedItem !== this.u) {
      this.R();
    }
  }
  db(element) {
    for (let i2 = 0; i2 < this.C.children.length; i2++) {
      const elem = this.C.children[i2];
      if (element === elem) {
        this.u = i2;
        break;
      }
    }
  }
  R(fromRight) {
    super.R(fromRight, true, true);
    if (typeof this.u !== "undefined") {
      this.W.setScrollPosition({
        scrollTop: Math.round(this.X.scrollTop)
      });
    }
  }
  fb(action, options3, parentData) {
    if (action instanceof $Wm) {
      return new MenuSeparatorActionViewItem(options3.context, action, { icon: true }, this.Z);
    } else if (action instanceof $Xm) {
      const menuActionViewItem = new SubmenuMenuActionViewItem(action, action.actions, parentData, { ...options3, submenuIds: /* @__PURE__ */ new Set([...options3.submenuIds || [], action.id]) }, this.Z);
      if (options3.enableMnemonics) {
        const mnemonic = menuActionViewItem.getMnemonic();
        if (mnemonic && menuActionViewItem.isEnabled()) {
          let actionViewItems = [];
          if (this.U.has(mnemonic)) {
            actionViewItems = this.U.get(mnemonic);
          }
          actionViewItems.push(menuActionViewItem);
          this.U.set(mnemonic, actionViewItems);
        }
      }
      return menuActionViewItem;
    } else {
      const menuItemOptions = { enableMnemonics: options3.enableMnemonics, useEventAsContext: options3.useEventAsContext };
      if (options3.getKeyBinding) {
        const keybinding = options3.getKeyBinding(action);
        if (keybinding) {
          const keybindingLabel = keybinding.getLabel();
          if (keybindingLabel) {
            menuItemOptions.keybinding = keybindingLabel;
          }
        }
      }
      const menuActionViewItem = new BaseMenuActionViewItem(options3.context, action, menuItemOptions, this.Z);
      if (options3.enableMnemonics) {
        const mnemonic = menuActionViewItem.getMnemonic();
        if (mnemonic && menuActionViewItem.isEnabled()) {
          let actionViewItems = [];
          if (this.U.has(mnemonic)) {
            actionViewItems = this.U.get(mnemonic);
          }
          actionViewItems.push(menuActionViewItem);
          this.U.set(mnemonic, actionViewItems);
        }
      }
      return menuActionViewItem;
    }
  }
};
var BaseMenuActionViewItem = class extends $T1 {
  constructor(ctx, action, options3, t) {
    options3.isMenu = true;
    super(action, action, options3);
    this.t = t;
    this.u = options3;
    this.u.icon = options3.icon !== void 0 ? options3.icon : false;
    this.u.label = options3.label !== void 0 ? options3.label : true;
    this.s = "";
    if (this.u.label && options3.enableMnemonics) {
      const label3 = this.action.label;
      if (label3) {
        const matches = $c2.exec(label3);
        if (matches) {
          this.r = (!!matches[1] ? matches[1] : matches[3]).toLocaleLowerCase();
        }
      }
    }
    this.h = new $8h(() => {
      if (!this.element) {
        return;
      }
      this.B($_i(this.element, $7j.MOUSE_UP, (e) => {
        $9j.stop(e, true);
        if ($Ue) {
          const mouseEvent = new $lf(getWindow(this.element), e);
          if (mouseEvent.rightButton) {
            return;
          }
          this.onClick(e);
        } else {
          setTimeout(() => {
            this.onClick(e);
          }, 0);
        }
      }));
      this.B($_i(this.element, $7j.CONTEXT_MENU, (e) => {
        $9j.stop(e, true);
      }));
    }, 100);
    this.B(this.h);
  }
  render(container2) {
    super.render(container2);
    if (!this.element) {
      return;
    }
    this.container = container2;
    this.g = $bk(this.element, $("a.action-menu-item"));
    if (this._action.id === $Wm.ID) {
      this.g.setAttribute("role", "presentation");
    } else {
      this.g.setAttribute("role", "menuitem");
      if (this.r) {
        this.g.setAttribute("aria-keyshortcuts", `${this.r}`);
      }
    }
    this.n = $bk(this.g, $("span.menu-item-check" + ThemeIcon.asCSSSelector($6l.menuSelection)));
    this.n.setAttribute("role", "none");
    this.m = $bk(this.g, $("span.action-label"));
    if (this.u.label && this.u.keybinding) {
      $bk(this.g, $("span.keybinding")).textContent = this.u.keybinding;
    }
    this.h.schedule();
    this.I();
    this.C();
    this.G();
    this.z();
    this.J();
    this.P();
  }
  blur() {
    super.blur();
    this.P();
  }
  focus() {
    super.focus();
    this.g?.focus();
    this.P();
  }
  updatePositionInSet(pos, setSize) {
    if (this.g) {
      this.g.setAttribute("aria-posinset", `${pos}`);
      this.g.setAttribute("aria-setsize", `${setSize}`);
    }
  }
  C() {
    if (!this.m) {
      return;
    }
    if (this.u.label) {
      $$i(this.m);
      let label3 = $0l(this.action.label);
      if (label3) {
        const cleanLabel = $g2(label3);
        if (!this.u.enableMnemonics) {
          label3 = cleanLabel;
        }
        this.m.setAttribute("aria-label", cleanLabel.replace(/&&/g, "&"));
        const matches = $c2.exec(label3);
        if (matches) {
          label3 = $zf(label3);
          $d2.lastIndex = 0;
          let escMatch = $d2.exec(label3);
          while (escMatch && escMatch[1]) {
            escMatch = $d2.exec(label3);
          }
          const replaceDoubleEscapes = (str) => str.replace(/&amp;&amp;/g, "&amp;");
          if (escMatch) {
            this.m.append($Ff(replaceDoubleEscapes(label3.substr(0, escMatch.index)), " "), $("u", { "aria-hidden": "true" }, escMatch[3]), $Gf(replaceDoubleEscapes(label3.substr(escMatch.index + escMatch[0].length)), " "));
          } else {
            this.m.innerText = replaceDoubleEscapes(label3).trim();
          }
          this.g?.setAttribute("aria-keyshortcuts", (!!matches[1] ? matches[1] : matches[3]).toLocaleLowerCase());
        } else {
          this.m.innerText = label3.replace(/&&/g, "&").trim();
        }
      }
    }
  }
  G() {
  }
  I() {
    if (this.s && this.g) {
      this.g.classList.remove(...this.s.split(" "));
    }
    if (this.u.icon && this.m) {
      this.s = this.action.class || "";
      this.m.classList.add("icon");
      if (this.s) {
        this.m.classList.add(...this.s.split(" "));
      }
      this.z();
    } else if (this.m) {
      this.m.classList.remove("icon");
    }
  }
  z() {
    if (this.action.enabled) {
      if (this.element) {
        this.element.classList.remove("disabled");
        this.element.removeAttribute("aria-disabled");
      }
      if (this.g) {
        this.g.classList.remove("disabled");
        this.g.removeAttribute("aria-disabled");
        this.g.tabIndex = 0;
      }
    } else {
      if (this.element) {
        this.element.classList.add("disabled");
        this.element.setAttribute("aria-disabled", "true");
      }
      if (this.g) {
        this.g.classList.add("disabled");
        this.g.setAttribute("aria-disabled", "true");
      }
    }
  }
  J() {
    if (!this.g) {
      return;
    }
    const checked = this.action.checked;
    this.g.classList.toggle("checked", !!checked);
    if (checked !== void 0) {
      this.g.setAttribute("role", "menuitemcheckbox");
      this.g.setAttribute("aria-checked", checked ? "true" : "false");
    } else {
      this.g.setAttribute("role", "menuitem");
      this.g.setAttribute("aria-checked", "");
    }
  }
  getMnemonic() {
    return this.r;
  }
  P() {
    const isSelected = this.element && this.element.classList.contains("focused");
    const fgColor = isSelected && this.t.selectionForegroundColor ? this.t.selectionForegroundColor : this.t.foregroundColor;
    const bgColor = isSelected && this.t.selectionBackgroundColor ? this.t.selectionBackgroundColor : void 0;
    const outline = isSelected && this.t.selectionBorderColor ? `1px solid ${this.t.selectionBorderColor}` : "";
    const outlineOffset = isSelected && this.t.selectionBorderColor ? `-1px` : "";
    if (this.g) {
      this.g.style.color = fgColor ?? "";
      this.g.style.backgroundColor = bgColor ?? "";
      this.g.style.outline = outline;
      this.g.style.outlineOffset = outlineOffset;
    }
    if (this.n) {
      this.n.style.color = fgColor ?? "";
    }
  }
};
var SubmenuMenuActionViewItem = class extends BaseMenuActionViewItem {
  constructor(action, ab, bb, cb, menuStyles) {
    super(action, action, cb, menuStyles);
    this.ab = ab;
    this.bb = bb;
    this.cb = cb;
    this.Q = null;
    this.U = this.B(new $2c());
    this.W = false;
    this.Z = cb && cb.expandDirection !== void 0 ? cb.expandDirection : { horizontal: HorizontalDirection.Right, vertical: VerticalDirection.Below };
    this.X = new $8h(() => {
      if (this.W) {
        this.eb(false);
        this.gb(false);
      }
    }, 250);
    this.Y = new $8h(() => {
      if (this.element && (!$Dj($Lj(), this.element) && this.bb.submenu === this.Q)) {
        this.bb.parent.focus(false);
        this.eb(true);
      }
    }, 750);
  }
  render(container2) {
    super.render(container2);
    if (!this.element) {
      return;
    }
    if (this.g) {
      this.g.classList.add("monaco-submenu-item");
      this.g.tabIndex = 0;
      this.g.setAttribute("aria-haspopup", "true");
      this.hb("false");
      this.S = $bk(this.g, $("span.submenu-indicator" + ThemeIcon.asCSSSelector($6l.menuSubmenu)));
      this.S.setAttribute("aria-hidden", "true");
    }
    this.B($_i(this.element, $7j.KEY_UP, (e) => {
      const event = new $if(e);
      if (event.equals(
        17
        /* KeyCode.RightArrow */
      ) || event.equals(
        3
        /* KeyCode.Enter */
      )) {
        $9j.stop(e, true);
        this.gb(true);
      }
    }));
    this.B($_i(this.element, $7j.KEY_DOWN, (e) => {
      const event = new $if(e);
      if ($Lj() === this.g) {
        if (event.equals(
          17
          /* KeyCode.RightArrow */
        ) || event.equals(
          3
          /* KeyCode.Enter */
        )) {
          $9j.stop(e, true);
        }
      }
    }));
    this.B($_i(this.element, $7j.MOUSE_OVER, (e) => {
      if (!this.W) {
        this.W = true;
        this.X.schedule();
      }
    }));
    this.B($_i(this.element, $7j.MOUSE_LEAVE, (e) => {
      this.W = false;
    }));
    this.B($_i(this.element, $7j.FOCUS_OUT, (e) => {
      if (this.element && !$Dj($Lj(), this.element)) {
        this.Y.schedule();
      }
    }));
    this.B(this.bb.parent.onScroll(() => {
      if (this.bb.submenu === this.Q) {
        this.bb.parent.focus(false);
        this.eb(true);
      }
    }));
  }
  z() {
  }
  open(selectFirst) {
    this.eb(false);
    this.gb(selectFirst);
  }
  onClick(e) {
    $9j.stop(e, true);
    this.eb(false);
    this.gb(true);
  }
  eb(force) {
    if (this.bb.submenu && (force || this.bb.submenu !== this.Q)) {
      try {
        this.bb.submenu.dispose();
      } catch {
      }
      this.bb.submenu = void 0;
      this.hb("false");
      if (this.R) {
        this.U.clear();
        this.R = void 0;
      }
    }
  }
  fb(windowDimensions, submenu, entry, expandDirection) {
    const ret = { top: 0, left: 0 };
    ret.left = $OZ(windowDimensions.width, submenu.width, { position: expandDirection.horizontal === HorizontalDirection.Right ? 0 : 1, offset: entry.left, size: entry.width });
    if (ret.left >= entry.left && ret.left < entry.left + entry.width) {
      if (entry.left + 10 + submenu.width <= windowDimensions.width) {
        ret.left = entry.left + 10;
      }
      entry.top += 10;
      entry.height = 0;
    }
    ret.top = $OZ(windowDimensions.height, submenu.height, { position: 0, offset: entry.top, size: 0 });
    if (ret.top + submenu.height === entry.top && ret.top + entry.height + submenu.height <= windowDimensions.height) {
      ret.top += entry.height;
    }
    return ret;
  }
  gb(selectFirstItem = true) {
    if (!this.element) {
      return;
    }
    if (!this.bb.submenu) {
      this.hb("true");
      this.R = $bk(this.element, $("div.monaco-submenu"));
      this.R.classList.add("menubar-menu-items-holder", "context-view");
      const computedStyles = getWindow(this.bb.parent.domNode).getComputedStyle(this.bb.parent.domNode);
      const paddingTop = parseFloat(computedStyles.paddingTop || "0") || 0;
      this.R.style.zIndex = "1";
      this.R.style.position = "fixed";
      this.R.style.top = "0";
      this.R.style.left = "0";
      this.bb.submenu = new $f2(this.R, this.ab.length ? this.ab : [new $Ym()], this.cb, this.t);
      const entryBox = this.element.getBoundingClientRect();
      const entryBoxUpdated = {
        top: entryBox.top - paddingTop,
        left: entryBox.left,
        height: entryBox.height + 2 * paddingTop,
        width: entryBox.width
      };
      const viewBox = this.R.getBoundingClientRect();
      const window3 = getWindow(this.element);
      const { top: top2, left } = this.fb(new $rj(window3.innerWidth, window3.innerHeight), $rj.lift(viewBox), entryBoxUpdated, this.Z);
      this.R.style.left = `${left - viewBox.left}px`;
      this.R.style.top = `${top2 - viewBox.top}px`;
      this.U.add($_i(this.R, $7j.KEY_UP, (e) => {
        const event = new $if(e);
        if (event.equals(
          15
          /* KeyCode.LeftArrow */
        )) {
          $9j.stop(e, true);
          this.bb.parent.focus();
          this.eb(true);
        }
      }));
      this.U.add($_i(this.R, $7j.KEY_DOWN, (e) => {
        const event = new $if(e);
        if (event.equals(
          15
          /* KeyCode.LeftArrow */
        )) {
          $9j.stop(e, true);
        }
      }));
      this.U.add(this.bb.submenu.onDidCancel(() => {
        this.bb.parent.focus();
        this.eb(true);
      }));
      this.bb.submenu.focus(selectFirstItem);
      this.Q = this.bb.submenu;
    } else {
      this.bb.submenu.focus(false);
    }
  }
  hb(value) {
    if (this.g) {
      this.g?.setAttribute("aria-expanded", value);
    }
  }
  P() {
    super.P();
    const isSelected = this.element && this.element.classList.contains("focused");
    const fgColor = isSelected && this.t.selectionForegroundColor ? this.t.selectionForegroundColor : this.t.foregroundColor;
    if (this.S) {
      this.S.style.color = fgColor ?? "";
    }
  }
  dispose() {
    super.dispose();
    this.Y.dispose();
    if (this.Q) {
      this.Q.dispose();
      this.Q = null;
    }
    if (this.R) {
      this.R = void 0;
    }
  }
};
var MenuSeparatorActionViewItem = class extends $U1 {
  constructor(context, action, options3, b) {
    super(context, action, options3);
    this.b = b;
  }
  render(container2) {
    super.render(container2);
    if (this.L) {
      this.L.style.borderBottomColor = this.b.separatorColor ? `${this.b.separatorColor}` : "";
    }
  }
};
function $g2(label3) {
  const regex = $c2;
  const matches = regex.exec(label3);
  if (!matches) {
    return label3;
  }
  const mnemonicInText = !matches[1];
  return label3.replace(regex, mnemonicInText ? "$2$3" : "").trim();
}
function $h2(c) {
  const fontCharacter = $2l()[c.id];
  return `.codicon-${c.id}:before { content: '\\${fontCharacter.toString(16)}'; }`;
}
function getMenuWidgetCSS(style, isForShadowDom) {
  let result = (
    /* css */
    `
.monaco-menu {
	font-size: 13px;
	border-radius: 5px;
	min-width: 160px;
}

${$h2($6l.menuSelection)}
${$h2($6l.menuSubmenu)}

.monaco-menu .monaco-action-bar {
	text-align: right;
	overflow: hidden;
	white-space: nowrap;
}

.monaco-menu .monaco-action-bar .actions-container {
	display: flex;
	margin: 0 auto;
	padding: 0;
	width: 100%;
	justify-content: flex-end;
}

.monaco-menu .monaco-action-bar.vertical .actions-container {
	display: inline-block;
}

.monaco-menu .monaco-action-bar.reverse .actions-container {
	flex-direction: row-reverse;
}

.monaco-menu .monaco-action-bar .action-item {
	cursor: pointer;
	display: inline-block;
	transition: transform 50ms ease;
	position: relative;  /* DO NOT REMOVE - this is the key to preventing the ghosting icon bug in Chrome 42 */
}

.monaco-menu .monaco-action-bar .action-item.disabled {
	cursor: default;
}

.monaco-menu .monaco-action-bar .action-item .icon,
.monaco-menu .monaco-action-bar .action-item .codicon {
	display: inline-block;
}

.monaco-menu .monaco-action-bar .action-item .codicon {
	display: flex;
	align-items: center;
}

.monaco-menu .monaco-action-bar .action-label {
	font-size: 11px;
	margin-right: 4px;
}

.monaco-menu .monaco-action-bar .action-item.disabled .action-label,
.monaco-menu .monaco-action-bar .action-item.disabled .action-label:hover {
	color: var(--vscode-disabledForeground);
}

/* Vertical actions */

.monaco-menu .monaco-action-bar.vertical {
	text-align: left;
}

.monaco-menu .monaco-action-bar.vertical .action-item {
	display: block;
}

.monaco-menu .monaco-action-bar.vertical .action-label.separator {
	display: block;
	border-bottom: 1px solid var(--vscode-menu-separatorBackground);
	padding-top: 1px;
	padding: 30px;
}

.monaco-menu .secondary-actions .monaco-action-bar .action-label {
	margin-left: 6px;
}

/* Action Items */
.monaco-menu .monaco-action-bar .action-item.select-container {
	overflow: hidden; /* somehow the dropdown overflows its container, we prevent it here to not push */
	flex: 1;
	max-width: 170px;
	min-width: 60px;
	display: flex;
	align-items: center;
	justify-content: center;
	margin-right: 10px;
}

.monaco-menu .monaco-action-bar.vertical {
	margin-left: 0;
	overflow: visible;
}

.monaco-menu .monaco-action-bar.vertical .actions-container {
	display: block;
}

.monaco-menu .monaco-action-bar.vertical .action-item {
	padding: 0;
	transform: none;
	display: flex;
}

.monaco-menu .monaco-action-bar.vertical .action-item.active {
	transform: none;
}

.monaco-menu .monaco-action-bar.vertical .action-menu-item {
	flex: 1 1 auto;
	display: flex;
	height: 2em;
	align-items: center;
	position: relative;
	margin: 0 4px;
	border-radius: 4px;
}

.monaco-menu .monaco-action-bar.vertical .action-menu-item:hover .keybinding,
.monaco-menu .monaco-action-bar.vertical .action-menu-item:focus .keybinding {
	opacity: unset;
}

.monaco-menu .monaco-action-bar.vertical .action-label {
	flex: 1 1 auto;
	text-decoration: none;
	padding: 0 1em;
	background: none;
	font-size: 12px;
	line-height: 1;
}

.monaco-menu .monaco-action-bar.vertical .keybinding,
.monaco-menu .monaco-action-bar.vertical .submenu-indicator {
	display: inline-block;
	flex: 2 1 auto;
	padding: 0 1em;
	text-align: right;
	font-size: 12px;
	line-height: 1;
}

.monaco-menu .monaco-action-bar.vertical .submenu-indicator {
	height: 100%;
}

.monaco-menu .monaco-action-bar.vertical .submenu-indicator.codicon {
	font-size: 16px !important;
	display: flex;
	align-items: center;
}

.monaco-menu .monaco-action-bar.vertical .submenu-indicator.codicon::before {
	margin-left: auto;
	margin-right: -20px;
}

.monaco-menu .monaco-action-bar.vertical .action-item.disabled .keybinding,
.monaco-menu .monaco-action-bar.vertical .action-item.disabled .submenu-indicator {
	opacity: 0.4;
}

.monaco-menu .monaco-action-bar.vertical .action-label:not(.separator) {
	display: inline-block;
	box-sizing: border-box;
	margin: 0;
}

.monaco-menu .monaco-action-bar.vertical .action-item {
	position: static;
	overflow: visible;
}

.monaco-menu .monaco-action-bar.vertical .action-item .monaco-submenu {
	position: absolute;
}

.monaco-menu .monaco-action-bar.vertical .action-label.separator {
	width: 100%;
	height: 0px !important;
	opacity: 1;
}

.monaco-menu .monaco-action-bar.vertical .action-label.separator.text {
	padding: 0.7em 1em 0.1em 1em;
	font-weight: bold;
	opacity: 1;
}

.monaco-menu .monaco-action-bar.vertical .action-label:hover {
	color: inherit;
}

.monaco-menu .monaco-action-bar.vertical .menu-item-check {
	position: absolute;
	visibility: hidden;
	width: 1em;
	height: 100%;
}

.monaco-menu .monaco-action-bar.vertical .action-menu-item.checked .menu-item-check {
	visibility: visible;
	display: flex;
	align-items: center;
	justify-content: center;
}

/* Context Menu */

.context-view.monaco-menu-container {
	outline: 0;
	border: none;
	animation: fadeIn 0.083s linear;
	-webkit-app-region: no-drag;
}

.context-view.monaco-menu-container :focus,
.context-view.monaco-menu-container .monaco-action-bar.vertical:focus,
.context-view.monaco-menu-container .monaco-action-bar.vertical :focus {
	outline: 0;
}

.hc-black .context-view.monaco-menu-container,
.hc-light .context-view.monaco-menu-container,
:host-context(.hc-black) .context-view.monaco-menu-container,
:host-context(.hc-light) .context-view.monaco-menu-container {
	box-shadow: none;
}

.hc-black .monaco-menu .monaco-action-bar.vertical .action-item.focused,
.hc-light .monaco-menu .monaco-action-bar.vertical .action-item.focused,
:host-context(.hc-black) .monaco-menu .monaco-action-bar.vertical .action-item.focused,
:host-context(.hc-light) .monaco-menu .monaco-action-bar.vertical .action-item.focused {
	background: none;
}

/* Vertical Action Bar Styles */

.monaco-menu .monaco-action-bar.vertical {
	padding: 4px 0;
}

.monaco-menu .monaco-action-bar.vertical .action-menu-item {
	height: 2em;
}

.monaco-menu .monaco-action-bar.vertical .action-label:not(.separator),
.monaco-menu .monaco-action-bar.vertical .keybinding {
	font-size: inherit;
	padding: 0 2em;
	max-height: 100%;
}

.monaco-menu .monaco-action-bar.vertical .menu-item-check {
	font-size: inherit;
	width: 2em;
}

.monaco-menu .monaco-action-bar.vertical .action-label.separator {
	font-size: inherit;
	margin: 5px 0 !important;
	padding: 0;
	border-radius: 0;
}

.linux .monaco-menu .monaco-action-bar.vertical .action-label.separator,
:host-context(.linux) .monaco-menu .monaco-action-bar.vertical .action-label.separator {
	margin-left: 0;
	margin-right: 0;
}

.monaco-menu .monaco-action-bar.vertical .submenu-indicator {
	font-size: 60%;
	padding: 0 1.8em;
}

.linux .monaco-menu .monaco-action-bar.vertical .submenu-indicator,
:host-context(.linux) .monaco-menu .monaco-action-bar.vertical .submenu-indicator {
	height: 100%;
	mask-size: 10px 10px;
	-webkit-mask-size: 10px 10px;
}

.monaco-menu .action-item {
	cursor: default;
}`
  );
  if (isForShadowDom) {
    result += `
			/* Arrows */
			.monaco-scrollable-element > .scrollbar > .scra {
				cursor: pointer;
				font-size: 11px !important;
			}

			.monaco-scrollable-element > .visible {
				opacity: 1;

				/* Background rule added for IE9 - to allow clicks on dom node */
				background:rgba(0,0,0,0);

				transition: opacity 100ms linear;
			}
			.monaco-scrollable-element > .invisible {
				opacity: 0;
				pointer-events: none;
			}
			.monaco-scrollable-element > .invisible.fade {
				transition: opacity 800ms linear;
			}

			/* Scrollable Content Inset Shadow */
			.monaco-scrollable-element > .shadow {
				position: absolute;
				display: none;
			}
			.monaco-scrollable-element > .shadow.top {
				display: block;
				top: 0;
				left: 3px;
				height: 3px;
				width: 100%;
			}
			.monaco-scrollable-element > .shadow.left {
				display: block;
				top: 3px;
				left: 0;
				height: 100%;
				width: 3px;
			}
			.monaco-scrollable-element > .shadow.top-left-corner {
				display: block;
				top: 0;
				left: 0;
				height: 3px;
				width: 3px;
			}
		`;
    const scrollbarShadowColor = style.scrollbarShadow;
    if (scrollbarShadowColor) {
      result += `
				.monaco-scrollable-element > .shadow.top {
					box-shadow: ${scrollbarShadowColor} 0 6px 6px -6px inset;
				}

				.monaco-scrollable-element > .shadow.left {
					box-shadow: ${scrollbarShadowColor} 6px 0 6px -6px inset;
				}

				.monaco-scrollable-element > .shadow.top.left {
					box-shadow: ${scrollbarShadowColor} 6px 6px 6px -6px inset;
				}
			`;
    }
    const scrollbarSliderBackgroundColor = style.scrollbarSliderBackground;
    if (scrollbarSliderBackgroundColor) {
      result += `
				.monaco-scrollable-element > .scrollbar > .slider {
					background: ${scrollbarSliderBackgroundColor};
				}
			`;
    }
    const scrollbarSliderHoverBackgroundColor = style.scrollbarSliderHoverBackground;
    if (scrollbarSliderHoverBackgroundColor) {
      result += `
				.monaco-scrollable-element > .scrollbar > .slider:hover {
					background: ${scrollbarSliderHoverBackgroundColor};
				}
			`;
    }
    const scrollbarSliderActiveBackgroundColor = style.scrollbarSliderActiveBackground;
    if (scrollbarSliderActiveBackgroundColor) {
      result += `
				.monaco-scrollable-element > .scrollbar > .slider.active {
					background: ${scrollbarSliderActiveBackgroundColor};
				}
			`;
    }
  }
  return result;
}

// out-build/vs/base/browser/ui/menu/menubar.js
var $110 = $;
var MenubarState;
(function(MenubarState2) {
  MenubarState2[MenubarState2["HIDDEN"] = 0] = "HIDDEN";
  MenubarState2[MenubarState2["VISIBLE"] = 1] = "VISIBLE";
  MenubarState2[MenubarState2["FOCUSED"] = 2] = "FOCUSED";
  MenubarState2[MenubarState2["OPEN"] = 3] = "OPEN";
})(MenubarState || (MenubarState = {}));
var $522 = class _$52 extends $3c {
  static {
    this.OVERFLOW_INDEX = -1;
  }
  constructor(F, G, H) {
    super();
    this.F = F;
    this.G = G;
    this.H = H;
    this.h = false;
    this.j = false;
    this.m = false;
    this.n = false;
    this.s = false;
    this.z = 0;
    this.C = void 0;
    this.D = this.B(new $2c());
    this.F.setAttribute("role", "menubar");
    if (this.S) {
      this.F.classList.add("compact");
    }
    this.a = [];
    this.r = /* @__PURE__ */ new Map();
    this.t = MenubarState.VISIBLE;
    this.w = this.B(new $ze());
    this.y = this.B(new $ze());
    this.createOverflowMenu();
    this.g = this.B(new $8h(() => this.update(), 200));
    this.u = this.G.actionRunner ?? this.B(new $Vm());
    this.B(this.u.onWillRun(() => {
      this.U();
    }));
    this.B($yk.getInstance().event(this.cb, this));
    this.B($_i(this.F, $7j.KEY_DOWN, (e) => {
      const event = new $if(e);
      let eventHandled = true;
      const key2 = !!e.key ? e.key.toLocaleLowerCase() : "";
      const tabNav = $m && !this.S;
      if (event.equals(
        15
        /* KeyCode.LeftArrow */
      ) || tabNav && event.equals(
        2 | 1024
        /* KeyMod.Shift */
      )) {
        this.W();
      } else if (event.equals(
        17
        /* KeyCode.RightArrow */
      ) || tabNav && event.equals(
        2
        /* KeyCode.Tab */
      )) {
        this.X();
      } else if (event.equals(
        9
        /* KeyCode.Escape */
      ) && this.P && !this.Q) {
        this.U();
      } else if (!this.Q && !event.ctrlKey && this.G.enableMnemonics && this.Z && this.r.has(key2)) {
        const menuIndex = this.r.get(key2);
        this.bb(menuIndex, false);
      } else {
        eventHandled = false;
      }
      if (!this.S && (event.equals(
        2 | 1024
        /* KeyMod.Shift */
      ) || event.equals(
        2
        /* KeyCode.Tab */
      ))) {
        event.preventDefault();
      }
      if (eventHandled) {
        event.preventDefault();
        event.stopPropagation();
      }
    }));
    const window3 = getWindow(this.F);
    this.B($_i(window3, $7j.MOUSE_DOWN, () => {
      if (this.P) {
        this.U();
      }
    }));
    this.B($_i(this.F, $7j.FOCUS_IN, (e) => {
      const event = e;
      if (event.relatedTarget) {
        if (!this.F.contains(event.relatedTarget)) {
          this.f = event.relatedTarget;
        }
      }
    }));
    this.B($_i(this.F, $7j.FOCUS_OUT, (e) => {
      const event = e;
      if (!event.relatedTarget) {
        this.U();
      } else if (event.relatedTarget && !this.F.contains(event.relatedTarget)) {
        this.f = void 0;
        this.U();
      }
    }));
    this.B($_i(window3, $7j.KEY_DOWN, (e) => {
      if (!this.G.enableMnemonics || !e.altKey || e.ctrlKey || e.defaultPrevented) {
        return;
      }
      const key2 = e.key.toLocaleLowerCase();
      if (!this.r.has(key2)) {
        return;
      }
      this.Z = true;
      this.Y(true);
      const menuIndex = this.r.get(key2);
      this.bb(menuIndex, false);
    }));
    this.U();
  }
  push(arg) {
    const menus = $5b(arg);
    menus.forEach((menuBarMenu) => {
      const menuIndex = this.a.length;
      const cleanMenuLabel = $g2(menuBarMenu.label);
      const mnemonicMatches = $c2.exec(menuBarMenu.label);
      if (mnemonicMatches) {
        const mnemonic = !!mnemonicMatches[1] ? mnemonicMatches[1] : mnemonicMatches[3];
        this.L(this.a.length, mnemonic);
      }
      if (this.S) {
        this.a.push(menuBarMenu);
      } else {
        const buttonElement = $110("div.menubar-menu-button", { "role": "menuitem", "tabindex": -1, "aria-label": cleanMenuLabel, "aria-haspopup": true });
        const titleElement = $110("div.menubar-menu-title", { "role": "none", "aria-hidden": true });
        buttonElement.appendChild(titleElement);
        this.F.insertBefore(buttonElement, this.b.buttonElement);
        this.J(titleElement, buttonElement, menuBarMenu.label);
        this.B($_i(buttonElement, $7j.KEY_UP, (e) => {
          const event = new $if(e);
          let eventHandled = true;
          if ((event.equals(
            18
            /* KeyCode.DownArrow */
          ) || event.equals(
            3
            /* KeyCode.Enter */
          )) && !this.Q) {
            this.c = { index: menuIndex };
            this.j = true;
            this.O = MenubarState.OPEN;
          } else {
            eventHandled = false;
          }
          if (eventHandled) {
            event.preventDefault();
            event.stopPropagation();
          }
        }));
        this.B($mZ.addTarget(buttonElement));
        this.B($_i(buttonElement, EventType.Tap, (e) => {
          if (this.Q && this.c && this.c.holder && $Dj(e.initialTarget, this.c.holder)) {
            return;
          }
          this.n = false;
          this.bb(menuIndex, true);
          e.preventDefault();
          e.stopPropagation();
        }));
        this.B($_i(buttonElement, $7j.MOUSE_DOWN, (e) => {
          const mouseEvent = new $lf(getWindow(buttonElement), e);
          if (!mouseEvent.leftButton) {
            e.preventDefault();
            return;
          }
          if (!this.Q) {
            this.n = true;
            this.bb(menuIndex, true);
          } else {
            this.n = false;
          }
          e.preventDefault();
          e.stopPropagation();
        }));
        this.B($_i(buttonElement, $7j.MOUSE_UP, (e) => {
          if (e.defaultPrevented) {
            return;
          }
          if (!this.n) {
            if (this.P) {
              this.bb(menuIndex, true);
            }
          } else {
            this.n = false;
          }
        }));
        this.B($_i(buttonElement, $7j.MOUSE_ENTER, () => {
          if (this.Q && !this.db(menuIndex)) {
            buttonElement.focus();
            this.eb();
            this.fb(menuIndex, false);
          } else if (this.P && !this.Q) {
            this.c = { index: menuIndex };
            buttonElement.focus();
          }
        }));
        this.a.push({
          label: menuBarMenu.label,
          actions: menuBarMenu.actions,
          buttonElement,
          titleElement
        });
      }
    });
  }
  createOverflowMenu() {
    const label3 = this.S ? localize(26, null) : localize(27, null);
    const buttonElement = $110("div.menubar-menu-button", { "role": "menuitem", "tabindex": this.S ? 0 : -1, "aria-label": label3, "aria-haspopup": true });
    const titleElement = $110("div.menubar-menu-title.toolbar-toggle-more" + ThemeIcon.asCSSSelector($6l.menuBarMore), { "role": "none", "aria-hidden": true });
    buttonElement.appendChild(titleElement);
    this.F.appendChild(buttonElement);
    buttonElement.style.visibility = "hidden";
    this.B($_i(buttonElement, $7j.KEY_UP, (e) => {
      const event = new $if(e);
      let eventHandled = true;
      const triggerKeys = [
        3
        /* KeyCode.Enter */
      ];
      if (!this.S) {
        triggerKeys.push(
          18
          /* KeyCode.DownArrow */
        );
      } else {
        triggerKeys.push(
          10
          /* KeyCode.Space */
        );
        if (this.G.compactMode?.horizontal === HorizontalDirection.Right) {
          triggerKeys.push(
            17
            /* KeyCode.RightArrow */
          );
        } else if (this.G.compactMode?.horizontal === HorizontalDirection.Left) {
          triggerKeys.push(
            15
            /* KeyCode.LeftArrow */
          );
        }
      }
      if (triggerKeys.some((k) => event.equals(k)) && !this.Q) {
        this.c = { index: _$52.OVERFLOW_INDEX };
        this.j = true;
        this.O = MenubarState.OPEN;
      } else {
        eventHandled = false;
      }
      if (eventHandled) {
        event.preventDefault();
        event.stopPropagation();
      }
    }));
    this.B($mZ.addTarget(buttonElement));
    this.B($_i(buttonElement, EventType.Tap, (e) => {
      if (this.Q && this.c && this.c.holder && $Dj(e.initialTarget, this.c.holder)) {
        return;
      }
      this.n = false;
      this.bb(_$52.OVERFLOW_INDEX, true);
      e.preventDefault();
      e.stopPropagation();
    }));
    this.B($_i(buttonElement, $7j.MOUSE_DOWN, (e) => {
      const mouseEvent = new $lf(getWindow(buttonElement), e);
      if (!mouseEvent.leftButton) {
        e.preventDefault();
        return;
      }
      if (!this.Q) {
        this.n = true;
        this.bb(_$52.OVERFLOW_INDEX, true);
      } else {
        this.n = false;
      }
      e.preventDefault();
      e.stopPropagation();
    }));
    this.B($_i(buttonElement, $7j.MOUSE_UP, (e) => {
      if (e.defaultPrevented) {
        return;
      }
      if (!this.n) {
        if (this.P) {
          this.bb(_$52.OVERFLOW_INDEX, true);
        }
      } else {
        this.n = false;
      }
    }));
    this.B($_i(buttonElement, $7j.MOUSE_ENTER, () => {
      if (this.Q && !this.db(_$52.OVERFLOW_INDEX)) {
        this.b.buttonElement.focus();
        this.eb();
        this.fb(_$52.OVERFLOW_INDEX, false);
      } else if (this.P && !this.Q) {
        this.c = { index: _$52.OVERFLOW_INDEX };
        buttonElement.focus();
      }
    }));
    this.b = {
      buttonElement,
      titleElement,
      label: "More",
      actions: []
    };
  }
  updateMenu(menu) {
    const menuToUpdate = this.a.filter((menuBarMenu) => menuBarMenu.label === menu.label);
    if (menuToUpdate && menuToUpdate.length) {
      menuToUpdate[0].actions = menu.actions;
    }
  }
  dispose() {
    super.dispose();
    this.a.forEach((menuBarMenu) => {
      menuBarMenu.titleElement?.remove();
      menuBarMenu.buttonElement?.remove();
    });
    this.b.titleElement.remove();
    this.b.buttonElement.remove();
    $Xc(this.C);
    this.C = void 0;
  }
  blur() {
    this.U();
  }
  getWidth() {
    if (!this.S && this.a) {
      const left = this.a[0].buttonElement.getBoundingClientRect().left;
      const right = this.R ? this.b.buttonElement.getBoundingClientRect().right : this.a[this.a.length - 1].buttonElement.getBoundingClientRect().right;
      return right - left;
    }
    return 0;
  }
  getHeight() {
    return this.F.clientHeight;
  }
  toggleFocus() {
    if (!this.P && this.G.visibility !== "hidden") {
      this.Z = true;
      this.c = { index: this.z > 0 ? 0 : _$52.OVERFLOW_INDEX };
      this.O = MenubarState.FOCUSED;
    } else if (!this.Q) {
      this.U();
    }
  }
  I() {
    if (!this.a || !this.a.length) {
      return;
    }
    const overflowMenuOnlyClass = "overflow-menu-only";
    this.F.classList.toggle(overflowMenuOnlyClass, false);
    const sizeAvailable = this.F.offsetWidth;
    let currentSize = 0;
    let full = this.S;
    const prevNumMenusShown = this.z;
    this.z = 0;
    const showableMenus = this.a.filter((menu) => menu.buttonElement !== void 0 && menu.titleElement !== void 0);
    for (const menuBarMenu of showableMenus) {
      if (!full) {
        const size = menuBarMenu.buttonElement.offsetWidth;
        if (currentSize + size > sizeAvailable) {
          full = true;
        } else {
          currentSize += size;
          this.z++;
          if (this.z > prevNumMenusShown) {
            menuBarMenu.buttonElement.style.visibility = "visible";
          }
        }
      }
      if (full) {
        menuBarMenu.buttonElement.style.visibility = "hidden";
      }
    }
    if (this.z - 1 <= showableMenus.length / 4) {
      for (const menuBarMenu of showableMenus) {
        menuBarMenu.buttonElement.style.visibility = "hidden";
      }
      full = true;
      this.z = 0;
      currentSize = 0;
    }
    if (this.S) {
      this.b.actions = [];
      for (let idx = this.z; idx < this.a.length; idx++) {
        this.b.actions.push(new $Xm(`menubar.submenu.${this.a[idx].label}`, this.a[idx].label, this.a[idx].actions || []));
      }
      const compactMenuActions = this.G.getCompactMenuActions?.();
      if (compactMenuActions && compactMenuActions.length) {
        this.b.actions.push(new $Wm());
        this.b.actions.push(...compactMenuActions);
      }
      this.b.buttonElement.style.visibility = "visible";
    } else if (full) {
      while (currentSize + this.b.buttonElement.offsetWidth > sizeAvailable && this.z > 0) {
        this.z--;
        const size = showableMenus[this.z].buttonElement.offsetWidth;
        showableMenus[this.z].buttonElement.style.visibility = "hidden";
        currentSize -= size;
      }
      this.b.actions = [];
      for (let idx = this.z; idx < showableMenus.length; idx++) {
        this.b.actions.push(new $Xm(`menubar.submenu.${showableMenus[idx].label}`, showableMenus[idx].label, showableMenus[idx].actions || []));
      }
      if (this.b.buttonElement.nextElementSibling !== showableMenus[this.z].buttonElement) {
        this.b.buttonElement.remove();
        this.F.insertBefore(this.b.buttonElement, showableMenus[this.z].buttonElement);
      }
      this.b.buttonElement.style.visibility = "visible";
    } else {
      this.b.buttonElement.remove();
      this.F.appendChild(this.b.buttonElement);
      this.b.buttonElement.style.visibility = "hidden";
    }
    this.F.classList.toggle(overflowMenuOnlyClass, this.z === 0);
  }
  J(titleElement, buttonElement, label3) {
    const cleanMenuLabel = $g2(label3);
    if (this.G.enableMnemonics) {
      const cleanLabel = $zf(label3);
      $d2.lastIndex = 0;
      let escMatch = $d2.exec(cleanLabel);
      while (escMatch && escMatch[1]) {
        escMatch = $d2.exec(cleanLabel);
      }
      const replaceDoubleEscapes = (str) => str.replace(/&amp;&amp;/g, "&amp;");
      if (escMatch) {
        titleElement.innerText = "";
        titleElement.append($Ff(replaceDoubleEscapes(cleanLabel.substr(0, escMatch.index)), " "), $110("mnemonic", { "aria-hidden": "true" }, escMatch[3]), $Gf(replaceDoubleEscapes(cleanLabel.substr(escMatch.index + escMatch[0].length)), " "));
      } else {
        titleElement.innerText = replaceDoubleEscapes(cleanLabel).trim();
      }
    } else {
      titleElement.innerText = cleanMenuLabel.replace(/&&/g, "&");
    }
    const mnemonicMatches = $c2.exec(label3);
    if (mnemonicMatches) {
      const mnemonic = !!mnemonicMatches[1] ? mnemonicMatches[1] : mnemonicMatches[3];
      if (this.G.enableMnemonics) {
        buttonElement.setAttribute("aria-keyshortcuts", "Alt+" + mnemonic.toLocaleLowerCase());
      } else {
        buttonElement.removeAttribute("aria-keyshortcuts");
      }
    }
  }
  update(options3) {
    if (options3) {
      this.G = options3;
    }
    if (this.P) {
      this.s = true;
      return;
    }
    this.a.forEach((menuBarMenu) => {
      if (!menuBarMenu.buttonElement || !menuBarMenu.titleElement) {
        return;
      }
      this.J(menuBarMenu.titleElement, menuBarMenu.buttonElement, menuBarMenu.label);
    });
    if (!this.C) {
      this.C = $jj(getWindow(this.F), () => {
        this.I();
        this.C = void 0;
      });
    }
    this.U();
  }
  L(menuIndex, mnemonic) {
    this.r.set(mnemonic.toLocaleLowerCase(), menuIndex);
  }
  M() {
    if (this.F.style.display !== "none") {
      this.F.style.display = "none";
      this.w.fire(false);
    }
  }
  N() {
    if (this.F.style.display !== "flex") {
      this.F.style.display = "flex";
      this.w.fire(true);
      this.I();
    }
  }
  get O() {
    return this.t;
  }
  set O(value) {
    if (this.t >= MenubarState.FOCUSED && value < MenubarState.FOCUSED) {
      if (this.s) {
        this.g.schedule();
        this.s = false;
      }
    }
    if (value === this.t) {
      return;
    }
    const isVisible = this.isVisible;
    const isOpen = this.Q;
    const isFocused = this.P;
    this.t = value;
    switch (value) {
      case MenubarState.HIDDEN:
        if (isVisible) {
          this.M();
        }
        if (isOpen) {
          this.eb();
        }
        if (isFocused) {
          this.c = void 0;
          if (this.f) {
            this.f.focus();
            this.f = void 0;
          }
        }
        break;
      case MenubarState.VISIBLE:
        if (!isVisible) {
          this.N();
        }
        if (isOpen) {
          this.eb();
        }
        if (isFocused) {
          if (this.c) {
            if (this.c.index === _$52.OVERFLOW_INDEX) {
              this.b.buttonElement.blur();
            } else {
              this.a[this.c.index].buttonElement?.blur();
            }
          }
          this.c = void 0;
          if (this.f) {
            this.f.focus();
            this.f = void 0;
          }
        }
        break;
      case MenubarState.FOCUSED:
        if (!isVisible) {
          this.N();
        }
        if (isOpen) {
          this.eb();
        }
        if (this.c) {
          if (this.c.index === 0 && this.z === 0) {
            this.c.index = _$52.OVERFLOW_INDEX;
          }
          if (this.c.index === _$52.OVERFLOW_INDEX) {
            this.b.buttonElement.focus();
          } else {
            this.a[this.c.index].buttonElement?.focus();
          }
        }
        break;
      case MenubarState.OPEN:
        if (!isVisible) {
          this.N();
        }
        if (this.c) {
          this.eb();
          this.fb(this.c.index, this.j);
        }
        break;
    }
    this.t = value;
    this.y.fire(this.O >= MenubarState.FOCUSED);
  }
  get isVisible() {
    return this.O >= MenubarState.VISIBLE;
  }
  get P() {
    return this.O >= MenubarState.FOCUSED;
  }
  get Q() {
    return this.O >= MenubarState.OPEN;
  }
  get R() {
    return this.S || this.z < this.a.length;
  }
  get S() {
    return this.G.compactMode !== void 0;
  }
  U() {
    if (this.G.visibility === "toggle" || this.G.visibility === "hidden") {
      this.O = MenubarState.HIDDEN;
    } else if (this.G.visibility === "classic" && $Se($Y)) {
      this.O = MenubarState.HIDDEN;
    } else {
      this.O = MenubarState.VISIBLE;
    }
    this.n = false;
    this.Z = false;
    this.Y(false);
  }
  W() {
    if (!this.c || this.z === 0) {
      return;
    }
    let newFocusedIndex = (this.c.index - 1 + this.z) % this.z;
    if (this.c.index === _$52.OVERFLOW_INDEX) {
      newFocusedIndex = this.z - 1;
    } else if (this.c.index === 0 && this.R) {
      newFocusedIndex = _$52.OVERFLOW_INDEX;
    }
    if (newFocusedIndex === this.c.index) {
      return;
    }
    if (this.Q) {
      this.eb();
      this.fb(newFocusedIndex);
    } else if (this.P) {
      this.c.index = newFocusedIndex;
      if (newFocusedIndex === _$52.OVERFLOW_INDEX) {
        this.b.buttonElement.focus();
      } else {
        this.a[newFocusedIndex].buttonElement?.focus();
      }
    }
  }
  X() {
    if (!this.c || this.z === 0) {
      return;
    }
    let newFocusedIndex = (this.c.index + 1) % this.z;
    if (this.c.index === _$52.OVERFLOW_INDEX) {
      newFocusedIndex = 0;
    } else if (this.c.index === this.z - 1) {
      newFocusedIndex = _$52.OVERFLOW_INDEX;
    }
    if (newFocusedIndex === this.c.index) {
      return;
    }
    if (this.Q) {
      this.eb();
      this.fb(newFocusedIndex);
    } else if (this.P) {
      this.c.index = newFocusedIndex;
      if (newFocusedIndex === _$52.OVERFLOW_INDEX) {
        this.b.buttonElement.focus();
      } else {
        this.a[newFocusedIndex].buttonElement?.focus();
      }
    }
  }
  Y(visible) {
    if (this.a) {
      this.a.forEach((menuBarMenu) => {
        if (menuBarMenu.titleElement && menuBarMenu.titleElement.children.length) {
          const child = menuBarMenu.titleElement.children.item(0);
          if (child) {
            child.style.textDecoration = this.G.alwaysOnMnemonics || visible ? "underline" : "";
          }
        }
      });
    }
  }
  get Z() {
    return this.h;
  }
  set Z(value) {
    this.h = value;
  }
  get ab() {
    if ($m) {
      return false;
    }
    if (!this.G.disableAltFocus) {
      return true;
    }
    if (this.G.visibility === "toggle") {
      return true;
    }
    return false;
  }
  get onVisibilityChange() {
    return this.w.event;
  }
  get onFocusStateChange() {
    return this.y.event;
  }
  bb(menuIndex, clicked) {
    if (this.Q) {
      if (this.db(menuIndex)) {
        this.U();
      } else {
        this.eb();
        this.fb(menuIndex, this.j);
      }
    } else {
      this.c = { index: menuIndex };
      this.j = !clicked;
      this.O = MenubarState.OPEN;
    }
  }
  cb(modifierKeyStatus) {
    const allModifiersReleased = !modifierKeyStatus.altKey && !modifierKeyStatus.ctrlKey && !modifierKeyStatus.shiftKey && !modifierKeyStatus.metaKey;
    if (this.G.visibility === "hidden") {
      return;
    }
    if (modifierKeyStatus.event && this.ab) {
      if ($8e.toEnum(modifierKeyStatus.event.code) === 159) {
        modifierKeyStatus.event.preventDefault();
      }
    }
    if (this.P && modifierKeyStatus.lastKeyPressed === "alt" && modifierKeyStatus.altKey) {
      this.U();
      this.Z = false;
      this.m = true;
    }
    if (allModifiersReleased && modifierKeyStatus.lastKeyPressed === "alt" && modifierKeyStatus.lastKeyReleased === "alt") {
      if (!this.m) {
        if (!this.P && this.ab) {
          this.Z = true;
          this.c = { index: this.z > 0 ? 0 : _$52.OVERFLOW_INDEX };
          this.O = MenubarState.FOCUSED;
        } else if (!this.Q) {
          this.U();
        }
      }
    }
    if (!modifierKeyStatus.altKey && modifierKeyStatus.lastKeyReleased === "alt") {
      this.m = false;
    }
    if (this.G.enableMnemonics && this.a && !this.Q) {
      this.Y(!this.m && modifierKeyStatus.altKey || this.Z);
    }
  }
  db(menuIndex) {
    if (!this.c) {
      return false;
    }
    return this.c.index === menuIndex;
  }
  eb() {
    if (this.c) {
      if (this.c.index === _$52.OVERFLOW_INDEX) {
        this.b.buttonElement.focus();
      } else {
        this.a[this.c.index].buttonElement?.focus();
      }
      if (this.c.holder) {
        this.c.holder.parentElement?.classList.remove("open");
        this.c.holder.remove();
      }
      this.c.widget?.dispose();
      this.c = { index: this.c.index };
    }
    this.D.clear();
  }
  fb(menuIndex, selectFirst = true) {
    const actualMenuIndex = menuIndex >= this.z ? _$52.OVERFLOW_INDEX : menuIndex;
    const customMenu = actualMenuIndex === _$52.OVERFLOW_INDEX ? this.b : this.a[actualMenuIndex];
    if (!customMenu.actions || !customMenu.buttonElement || !customMenu.titleElement) {
      return;
    }
    const menuHolder = $110("div.menubar-menu-items-holder", { "title": "" });
    customMenu.buttonElement.classList.add("open");
    const titleBoundingRect = customMenu.titleElement.getBoundingClientRect();
    const titleBoundingRectZoom = $wj(customMenu.titleElement);
    if (this.G.compactMode?.horizontal === HorizontalDirection.Right) {
      menuHolder.style.left = `${titleBoundingRect.left + this.F.clientWidth}px`;
    } else if (this.G.compactMode?.horizontal === HorizontalDirection.Left) {
      const windowWidth = getWindow(this.F).innerWidth;
      menuHolder.style.right = `${windowWidth - titleBoundingRect.left}px`;
      menuHolder.style.left = "auto";
    } else {
      menuHolder.style.left = `${titleBoundingRect.left * titleBoundingRectZoom}px`;
    }
    if (this.G.compactMode?.vertical === VerticalDirection.Above) {
      menuHolder.style.top = `${titleBoundingRect.top - this.a.length * 30 + this.F.clientHeight}px`;
    } else if (this.G.compactMode?.vertical === VerticalDirection.Below) {
      menuHolder.style.top = `${titleBoundingRect.top}px`;
    } else {
      menuHolder.style.top = `${titleBoundingRect.bottom * titleBoundingRectZoom}px`;
    }
    customMenu.buttonElement.appendChild(menuHolder);
    const menuOptions = {
      getKeyBinding: this.G.getKeybinding,
      actionRunner: this.u,
      enableMnemonics: this.G.alwaysOnMnemonics || this.Z && this.G.enableMnemonics,
      ariaLabel: customMenu.buttonElement.getAttribute("aria-label") ?? void 0,
      expandDirection: this.S ? this.G.compactMode : { horizontal: HorizontalDirection.Right, vertical: VerticalDirection.Below },
      useEventAsContext: true
    };
    const menuWidget = this.D.add(new $f2(menuHolder, customMenu.actions, menuOptions, this.H));
    this.D.add(menuWidget.onDidCancel(() => {
      this.O = MenubarState.FOCUSED;
    }));
    if (actualMenuIndex !== menuIndex) {
      menuWidget.trigger(menuIndex - this.z);
    } else {
      menuWidget.focus(selectFirst);
    }
    this.c = {
      index: actualMenuIndex,
      holder: menuHolder,
      widget: menuWidget
    };
  }
};

// out-build/vs/workbench/browser/parts/titlebar/menubarControl.js
$dJ.appendMenuItem($bJ.MenubarMainMenu, {
  submenu: $bJ.MenubarFileMenu,
  title: {
    value: "File",
    original: "File",
    mnemonicTitle: localize(3749, null)
  },
  order: 1
});
$dJ.appendMenuItem($bJ.MenubarMainMenu, {
  submenu: $bJ.MenubarEditMenu,
  title: {
    value: "Edit",
    original: "Edit",
    mnemonicTitle: localize(3750, null)
  },
  order: 2
});
$dJ.appendMenuItem($bJ.MenubarMainMenu, {
  submenu: $bJ.MenubarSelectionMenu,
  title: {
    value: "Selection",
    original: "Selection",
    mnemonicTitle: localize(3751, null)
  },
  order: 3
});
$dJ.appendMenuItem($bJ.MenubarMainMenu, {
  submenu: $bJ.MenubarViewMenu,
  title: {
    value: "View",
    original: "View",
    mnemonicTitle: localize(3752, null)
  },
  order: 4
});
$dJ.appendMenuItem($bJ.MenubarMainMenu, {
  submenu: $bJ.MenubarGoMenu,
  title: {
    value: "Go",
    original: "Go",
    mnemonicTitle: localize(3753, null)
  },
  order: 5
});
$dJ.appendMenuItem($bJ.MenubarMainMenu, {
  submenu: $bJ.MenubarTerminalMenu,
  title: {
    value: "Terminal",
    original: "Terminal",
    mnemonicTitle: localize(3754, null)
  },
  order: 7
});
$dJ.appendMenuItem($bJ.MenubarMainMenu, {
  submenu: $bJ.MenubarHelpMenu,
  title: {
    value: "Help",
    original: "Help",
    mnemonicTitle: localize(3755, null)
  },
  order: 8
});
$dJ.appendMenuItem($bJ.MenubarMainMenu, {
  submenu: $bJ.MenubarPreferencesMenu,
  title: {
    value: "Preferences",
    original: "Preferences",
    mnemonicTitle: localize(3756, null)
  },
  when: $web,
  order: 9
});
var $STb = class _$STb extends $3c {
  static {
    this.m = 10;
  }
  constructor(n, r2, s, t, u, w, y, z, C, D, F, G, H, I) {
    super();
    this.n = n;
    this.r = r2;
    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 = G;
    this.H = H;
    this.I = I;
    this.a = [
      "window.menuBarVisibility",
      "window.enableMenuBarMnemonics",
      "window.customMenuBarAltFocus",
      "workbench.sideBar.location",
      "window.nativeTabs"
    ];
    this.c = {};
    this.f = {};
    this.h = { files: [], workspaces: [] };
    this.b = this.B(this.n.createMenu($bJ.MenubarMainMenu, this.s));
    this.g = this.B(new $2c());
    this.M();
    this.j = this.B(new $8h(() => this.J(false), 200));
    this.Z();
  }
  L() {
    this.B(this.H.onDidChangeFocus((e) => this.S(e)));
    this.B(this.u.onDidChangeConfiguration((e) => this.U(e)));
    this.B(this.y.onStateChange(() => this.P()));
    this.B(this.r.onDidChangeRecentlyOpened(() => {
      this.X();
    }));
    this.B(this.t.onDidUpdateKeybindings(() => this.N()));
    this.B(this.w.onDidChangeFormatters(() => {
      this.X();
    }));
    this.B(this.b.onDidChange(() => {
      this.M();
      this.J(true);
    }));
  }
  M() {
    this.g.clear();
    this.c = {};
    this.f = {};
    const [, mainMenuActions] = this.b.getActions()[0];
    for (const mainMenuAction of mainMenuActions) {
      if (mainMenuAction instanceof $eJ && typeof mainMenuAction.item.title !== "string") {
        this.c[mainMenuAction.item.title.original] = this.g.add(this.n.createMenu(mainMenuAction.item.submenu, this.s, { emitEventsForSubmenuChanges: true }));
        this.f[mainMenuAction.item.title.original] = mainMenuAction.item.title.mnemonicTitle ?? mainMenuAction.item.title.value;
      }
    }
  }
  N() {
    this.j.schedule();
  }
  O(action) {
    const label3 = action.label;
    switch (action.id) {
      default:
        break;
    }
    return label3;
  }
  P() {
    this.N();
  }
  Q() {
    this.N();
  }
  R() {
    if (!this.h) {
      return [];
    }
    const { workspaces, files } = this.h;
    const result = [];
    if (workspaces.length > 0) {
      for (let i2 = 0; i2 < _$STb.m && i2 < workspaces.length; i2++) {
        result.push(this.Y(workspaces[i2]));
      }
      result.push(new $Wm());
    }
    if (files.length > 0) {
      for (let i2 = 0; i2 < _$STb.m && i2 < files.length; i2++) {
        result.push(this.Y(files[i2]));
      }
      result.push(new $Wm());
    }
    return result;
  }
  S(hasFocus) {
    if (hasFocus) {
      this.X();
    }
  }
  U(event) {
    if (this.a.some((key2) => event.affectsConfiguration(key2))) {
      this.N();
    }
    if (event.affectsConfiguration("editor.accessibilitySupport")) {
      this.Z();
    }
    if (event.affectsConfiguration("window.menuBarVisibility")) {
      this.X();
    }
  }
  get W() {
    return $m && $p ? false : $Bs(this.u) === "hidden";
  }
  X() {
    if (!this.W) {
      this.r.getRecentlyOpened().then((recentlyOpened) => {
        this.h = recentlyOpened;
        this.N();
      });
    }
  }
  Y(recent) {
    let label3;
    let uri;
    let commandId;
    let openable;
    const remoteAuthority = recent.remoteAuthority;
    if ($4w(recent)) {
      uri = recent.folderUri;
      label3 = recent.label || this.w.getWorkspaceLabel(uri, {
        verbose: 2
        /* Verbosity.LONG */
      });
      commandId = "openRecentFolder";
      openable = { folderUri: uri };
    } else if ($3w(recent)) {
      uri = recent.workspace.configPath;
      label3 = recent.label || this.w.getWorkspaceLabel(recent.workspace, {
        verbose: 2
        /* Verbosity.LONG */
      });
      commandId = "openRecentWorkspace";
      openable = { workspaceUri: uri };
    } else {
      uri = recent.fileUri;
      label3 = recent.label || this.w.getUriLabel(uri);
      commandId = "openRecentFile";
      openable = { fileUri: uri };
    }
    const ret = $Zm({
      id: commandId,
      label: $8t(label3),
      run: (browserEvent) => {
        const openInNewWindow = browserEvent && (!$m && (browserEvent.ctrlKey || browserEvent.shiftKey) || $m && (browserEvent.metaKey || browserEvent.altKey));
        return this.H.openWindow([openable], {
          forceNewWindow: !!openInNewWindow,
          remoteAuthority: remoteAuthority || null
          // local window if remoteAuthority is not set or can not be deducted from the openable
        });
      }
    });
    return Object.assign(ret, { uri, remoteAuthority });
  }
  Z() {
    if ($r || $m) {
      return;
    }
    const hasBeenNotified = this.z.getBoolean("menubar/accessibleMenubarNotified", -1, false);
    const usingCustomMenubar = !$Ds(this.u);
    if (hasBeenNotified || usingCustomMenubar || !this.G.isScreenReaderOptimized()) {
      return;
    }
    const message = localize(3757, null);
    this.C.prompt(Severity2.Info, message, [
      {
        label: localize(3758, null),
        run: () => {
          return this.D.openUserSettings({
            query: "window.titleBarStyle"
            /* TitleBarSetting.TITLE_BAR_STYLE */
          });
        }
      }
    ]);
    this.z.store(
      "menubar/accessibleMenubarNotified",
      true,
      -1,
      0
      /* StorageTarget.USER */
    );
  }
};
var focusMenuBarEmitter = void 0;
function enableFocusMenuBarAction() {
  if (!focusMenuBarEmitter) {
    focusMenuBarEmitter = new $ze();
    $hJ(class extends $gJ {
      constructor() {
        super({
          id: `workbench.actions.menubar.focus`,
          title: localize2(3766, "Focus Application Menu"),
          keybinding: {
            primary: 512 | 68,
            weight: 200,
            when: $veb
          },
          f1: true
        });
      }
      async run() {
        focusMenuBarEmitter?.fire();
      }
    });
  }
  return focusMenuBarEmitter;
}
var $TTb = class $TTb2 extends $STb {
  constructor(menuService, workspacesService, contextKeyService, keybindingService, configurationService, labelService, updateService, storageService, notificationService, preferencesService, environmentService, accessibilityService, jb, hostService, commandService) {
    super(menuService, workspacesService, contextKeyService, keybindingService, configurationService, labelService, updateService, storageService, notificationService, preferencesService, environmentService, accessibilityService, hostService, commandService);
    this.jb = jb;
    this.bb = false;
    this.cb = false;
    this.db = false;
    this.eb = true;
    this.gb = this.B(this.n.createMenu($bJ.MenubarHomeMenu, this.s));
    this.tb = this.B(new $2c());
    this.hb = this.B(new $ze());
    this.ib = this.B(new $ze());
    this.fb = this.B(new $Vm());
    this.fb.onDidRun((e) => {
      this.jb.publicLog2("workbenchActionExecuted", { id: e.action.id, from: "menu" });
    });
    this.r.getRecentlyOpened().then((recentlyOpened) => {
      this.h = recentlyOpened;
    });
    this.L();
  }
  J(firstTime) {
    if (!this.cb) {
      this.ub(firstTime);
    }
    if (firstTime) {
      this.db = true;
    }
  }
  lb() {
    const state = this.y.state;
    switch (state.type) {
      case "idle":
        return new $Um("update.check", localize(3759, null), void 0, true, () => this.y.checkForUpdates(true));
      case "checking for updates":
        return new $Um("update.checking", localize(3760, null), void 0, false);
      case "available for download":
        return new $Um("update.downloadNow", localize(3761, null), void 0, true, () => this.y.downloadUpdate());
      case "downloading":
        return new $Um("update.downloading", localize(3762, null), void 0, false);
      case "downloaded":
        return $m ? null : new $Um("update.install", localize(3763, null), void 0, true, () => this.y.applyUpdate());
      case "updating":
        return new $Um("update.updating", localize(3764, null), void 0, false);
      case "ready":
        return new $Um("update.restart", localize(3765, null), void 0, true, () => this.y.quitAndInstall());
      default:
        return null;
    }
  }
  get mb() {
    return $Bs(this.u);
  }
  get nb() {
    const settingValue = this.u.getValue("window.customMenuBarAltFocus");
    let disableMenuBarAltBehavior = false;
    if (typeof settingValue === "boolean") {
      disableMenuBarAltBehavior = !settingValue;
    }
    return disableMenuBarAltBehavior;
  }
  ob(nextAction, target) {
    switch (nextAction.id) {
      case $_yb.ID:
        target.push(...this.R());
        break;
      case "workbench.action.showAboutDialog":
        if (!$m && !$r) {
          const updateAction = this.lb();
          if (updateAction) {
            updateAction.label = $6t(updateAction.label);
            target.push(updateAction);
            target.push(new $Wm());
          }
        }
        break;
      default:
        break;
    }
  }
  get pb() {
    let enableMenuBarMnemonics = this.u.getValue("window.enableMenuBarMnemonics");
    if (typeof enableMenuBarMnemonics !== "boolean") {
      enableMenuBarMnemonics = true;
    }
    return enableMenuBarMnemonics && (!$r || $Se($Y));
  }
  get qb() {
    if (this.mb !== "compact") {
      return void 0;
    }
    const currentSidebarLocation = this.u.getValue("workbench.sideBar.location");
    const horizontalDirection = currentSidebarLocation === "right" ? HorizontalDirection.Left : HorizontalDirection.Right;
    const activityBarLocation = this.u.getValue("workbench.activityBar.location");
    const verticalDirection = activityBarLocation === "bottom" ? VerticalDirection.Above : VerticalDirection.Below;
    return { horizontal: horizontalDirection, vertical: verticalDirection };
  }
  rb(visible) {
    this.eb = visible;
    this.X();
    this.hb.fire(visible);
  }
  sb(menu) {
    return $P$(menu.getActions({ shouldForwardArgs: true }));
  }
  ub(firstTime) {
    if (!this.ab) {
      return;
    }
    if (firstTime) {
      if (this.$) {
        this.tb.clear();
      }
      this.$ = this.tb.add(new $522(this.ab, this.wb(), $M$));
      this.G.alwaysUnderlineAccessKeys().then((val) => {
        this.bb = val;
        this.$?.update(this.wb());
      });
      this.tb.add(this.$.onFocusStateChange((focused) => {
        this.ib.fire(focused);
        if (!focused) {
          if (this.db) {
            this.ub(true);
            this.db = false;
          } else {
            this.N();
          }
          this.cb = false;
        }
      }));
      this.tb.add(this.$.onVisibilityChange((e) => this.rb(e)));
      this.tb.add($_i(this.ab, $7j.FOCUS_IN, () => {
        this.cb = true;
      }));
      this.tb.add($_i(this.ab, $7j.FOCUS_OUT, () => {
        this.cb = false;
      }));
      if (this.$.isVisible) {
        this.rb(true);
      }
    } else {
      this.$?.update(this.wb());
    }
    const updateActions = (menuActions, target, topLevelTitle) => {
      target.splice(0);
      for (const menuItem of menuActions) {
        this.ob(menuItem, target);
        if (menuItem instanceof $Wm) {
          target.push(menuItem);
        } else if (menuItem instanceof $eJ || menuItem instanceof $fJ) {
          let title = typeof menuItem.item.title === "string" ? menuItem.item.title : menuItem.item.title.mnemonicTitle ?? menuItem.item.title.value;
          if (menuItem instanceof $eJ) {
            const submenuActions = [];
            updateActions(menuItem.actions, submenuActions, topLevelTitle);
            if (submenuActions.length > 0) {
              target.push(new $Xm(menuItem.id, $6t(title), submenuActions));
            }
          } else {
            if ($vn(menuItem.item.toggled)) {
              title = menuItem.item.toggled.mnemonicTitle ?? menuItem.item.toggled.title ?? title;
            }
            const newAction = new $Um(menuItem.id, $6t(title), menuItem.class, menuItem.enabled, () => this.I.executeCommand(menuItem.id));
            newAction.tooltip = menuItem.tooltip;
            newAction.checked = menuItem.checked;
            target.push(newAction);
          }
        }
      }
      if (topLevelTitle === "File" && this.qb === void 0) {
        const webActions = this.vb();
        if (webActions.length) {
          target.push(...webActions);
        }
      }
    };
    for (const title of Object.keys(this.f)) {
      const menu = this.c[title];
      if (firstTime && menu) {
        this.tb.add(menu.onDidChange(() => {
          if (!this.cb) {
            const actions2 = [];
            updateActions(this.sb(menu), actions2, title);
            this.$?.updateMenu({ actions: actions2, label: $6t(this.f[title]) });
          }
        }));
        if (menu === this.c.File) {
          this.tb.add(this.gb.onDidChange(() => {
            if (!this.cb) {
              const actions2 = [];
              updateActions(this.sb(menu), actions2, title);
              this.$?.updateMenu({ actions: actions2, label: $6t(this.f[title]) });
            }
          }));
        }
      }
      const actions = [];
      if (menu) {
        updateActions(this.sb(menu), actions, title);
      }
      if (this.$) {
        if (!firstTime) {
          this.$.updateMenu({ actions, label: $6t(this.f[title]) });
        } else {
          this.$.push({ actions, label: $6t(this.f[title]) });
        }
      }
    }
  }
  vb() {
    if (!$r) {
      return [];
    }
    const webNavigationActions = [];
    for (const groups of this.gb.getActions()) {
      const [, actions] = groups;
      for (const action of actions) {
        if (action instanceof $fJ) {
          const title = typeof action.item.title === "string" ? action.item.title : action.item.title.mnemonicTitle ?? action.item.title.value;
          webNavigationActions.push(new $Um(action.id, $6t(title), action.class, action.enabled, async (event) => {
            this.I.executeCommand(action.id, event);
          }));
        }
      }
      webNavigationActions.push(new $Wm());
    }
    if (webNavigationActions.length) {
      webNavigationActions.pop();
    }
    return webNavigationActions;
  }
  wb() {
    return {
      enableMnemonics: this.pb,
      disableAltFocus: this.nb,
      visibility: this.mb,
      actionRunner: this.fb,
      getKeybinding: (action) => this.t.lookupKeybinding(action.id),
      alwaysOnMnemonics: this.bb,
      compactMode: this.qb,
      getCompactMenuActions: () => {
        if (!$r) {
          return [];
        }
        return this.vb();
      }
    };
  }
  S(hasFocus) {
    if (!this.eb) {
      return;
    }
    super.S(hasFocus);
    if (this.ab) {
      if (hasFocus) {
        this.ab.classList.remove("inactive");
      } else {
        this.ab.classList.add("inactive");
        this.$?.blur();
      }
    }
  }
  P() {
    if (!this.eb) {
      return;
    }
    super.P();
  }
  X() {
    if (!this.eb) {
      return;
    }
    super.X();
  }
  Q() {
    if (!this.eb) {
      return;
    }
    super.Q();
  }
  L() {
    super.L();
    this.B($_i($Y, $7j.RESIZE, () => {
      if (this.$ && !($u && $5e.pointerEvents)) {
        this.$.blur();
      }
    }));
    if ($r) {
      this.B($Te((windowId) => {
        if (windowId === $Y.vscodeWindowId) {
          this.N();
        }
      }));
      this.B(this.gb.onDidChange(() => this.N()));
      this.B(enableFocusMenuBarAction().event(() => this.$?.toggleFocus()));
    }
  }
  get onVisibilityChange() {
    return this.hb.event;
  }
  get onFocusStateChange() {
    return this.ib.event;
  }
  getMenubarItemsDimensions() {
    if (this.$) {
      return new $rj(this.$.getWidth(), this.$.getHeight());
    }
    return new $rj(0, 0);
  }
  create(parent) {
    this.ab = parent;
    if (this.ab) {
      this.J(true);
    }
    return this.ab;
  }
  layout(dimension) {
    this.$?.update(this.wb());
  }
  toggleFocus() {
    this.$?.toggleFocus();
  }
};
$TTb = __decorate([
  __param(0, $cJ),
  __param(1, $2w),
  __param(2, $on),
  __param(3, $Ty),
  __param(4, $kl),
  __param(5, $ZI),
  __param(6, $az),
  __param(7, $jv),
  __param(8, $PJ),
  __param(9, $TK),
  __param(10, $US),
  __param(11, $ND),
  __param(12, $zv),
  __param(13, $S4),
  __param(14, $sn)
], $TTb);

// out-build/vs/workbench/services/userDataProfile/common/userDataProfileIcons.js
var $VTb = $9r("settings-view-bar-icon", $6l.settingsGear, localize(13425, null));
var $WTb = [
  /* Default */
  $VTb,
  /* hardware/devices */
  $6l.vm,
  $6l.server,
  $6l.recordKeys,
  $6l.deviceMobile,
  $6l.watch,
  $6l.vr,
  $6l.piano,
  /* languages */
  $6l.ruby,
  $6l.code,
  $6l.coffee,
  $6l.snake,
  /* project types */
  $6l.project,
  $6l.window,
  $6l.library,
  $6l.extensions,
  $6l.terminal,
  $6l.terminalDebian,
  $6l.terminalLinux,
  $6l.terminalUbuntu,
  $6l.beaker,
  $6l.package,
  $6l.cloud,
  $6l.book,
  $6l.globe,
  $6l.database,
  $6l.notebook,
  $6l.robot,
  $6l.game,
  $6l.chip,
  $6l.music,
  $6l.remoteExplorer,
  $6l.github,
  $6l.azure,
  $6l.vscode,
  $6l.copilot,
  /* misc */
  $6l.gift,
  $6l.send,
  $6l.bookmark,
  $6l.briefcase,
  $6l.megaphone,
  $6l.comment,
  $6l.telescope,
  $6l.creditCard,
  $6l.map,
  $6l.deviceCameraVideo,
  $6l.unmute,
  $6l.law,
  $6l.graphLine,
  $6l.heart,
  $6l.home,
  $6l.inbox,
  $6l.mortarBoard,
  $6l.rocket,
  $6l.magnet,
  $6l.lock,
  $6l.milestone,
  $6l.tag,
  $6l.pulse,
  $6l.radioTower,
  $6l.smiley,
  $6l.zap,
  $6l.squirrel,
  $6l.symbolColor,
  $6l.mail,
  $6l.key,
  $6l.pieChart,
  $6l.organization,
  $6l.preview,
  $6l.wand,
  $6l.starEmpty,
  $6l.lightbulb,
  $6l.symbolRuler,
  $6l.dashboard,
  $6l.calendar,
  $6l.shield,
  $6l.verified,
  $6l.debug,
  $6l.flame,
  $6l.compass,
  $6l.paintcan,
  $6l.archive,
  $6l.mic,
  $6l.jersey
];

// out-build/vs/workbench/browser/parts/globalCompositeBar.js
var $XTb_1;
var $XTb = class $XTb2 extends $3c {
  static {
    $XTb_1 = this;
  }
  static {
    this.b = 0;
  }
  static {
    this.ACCOUNTS_ICON = $9r("accounts-view-bar-icon", $6l.account, localize(3600, null));
  }
  constructor(h3, j, m, configurationService, n, r2, t) {
    super();
    this.h = h3;
    this.j = j;
    this.m = m;
    this.n = n;
    this.r = r2;
    this.t = t;
    this.c = this.B(new $Um($Pzb));
    this.f = this.B(new $Um($Qzb));
    this.element = document.createElement("div");
    const contextMenuAlignmentOptions = () => ({
      anchorAlignment: configurationService.getValue("workbench.sideBar.location") === "left" ? 1 : 0,
      anchorAxisAlignment: 1
      /* AnchorAxisAlignment.HORIZONTAL */
    });
    this.g = this.B(new $LZ(this.element, {
      actionViewItemProvider: (action, options3) => {
        if (action.id === $Pzb) {
          return this.n.createInstance($ZTb, this.h, { ...options3, colors: this.j, hoverOptions: this.m }, contextMenuAlignmentOptions);
        }
        if (action.id === $Qzb) {
          return this.n.createInstance($YTb, this.h, {
            ...options3,
            colors: this.j,
            hoverOptions: this.m
          }, contextMenuAlignmentOptions, (actions) => {
            actions.unshift(...[
              $Zm({ id: "hideAccounts", label: localize(3601, null), run: () => setAccountsActionVisible(r2, false) }),
              new $Wm()
            ]);
          });
        }
        throw new Error(`No view item for action '${action.id}'`);
      },
      orientation: 1,
      ariaLabel: localize(3602, null),
      preventLoopNavigation: true
    }));
    if (this.y) {
      this.g.push(this.f, { index: $XTb_1.b });
    }
    this.g.push(this.c);
    this.u();
  }
  u() {
    this.t.whenInstalledExtensionsRegistered().then(() => {
      if (!this.q.isDisposed) {
        this.B(this.r.onDidChangeValue(0, $YTb.ACCOUNTS_VISIBILITY_PREFERENCE_KEY, this.q)(() => this.w()));
      }
    });
  }
  create(parent) {
    parent.appendChild(this.element);
  }
  focus() {
    this.g.focus(true);
  }
  size() {
    return this.g.viewItems.length;
  }
  getContextMenuActions() {
    return [$Zm({ id: "toggleAccountsVisibility", label: localize(3603, null), checked: this.y, run: () => this.y = !this.y })];
  }
  w() {
    if (this.g.length() === 2 && this.y) {
      return;
    }
    if (this.g.length() === 2) {
      this.g.pull($XTb_1.b);
    } else {
      this.g.push(this.f, { index: $XTb_1.b });
    }
  }
  get y() {
    return $3Tb(this.r);
  }
  set y(value) {
    setAccountsActionVisible(this.r, value);
  }
};
$XTb = $XTb_1 = __decorate([
  __param(3, $kl),
  __param(4, $Pk),
  __param(5, $jv),
  __param(6, $wN)
], $XTb);
var AbstractGlobalActivityActionViewItem = class AbstractGlobalActivityActionViewItem2 extends $Cqb {
  constructor(cb, action, options3, db, eb, themeService, hoverService, fb, gb, hb, configurationService, keybindingService, ib) {
    super(action, { draggable: false, icon: true, hasPopup: true, ...options3 }, () => true, themeService, hoverService, configurationService, keybindingService);
    this.cb = cb;
    this.db = db;
    this.eb = eb;
    this.fb = fb;
    this.gb = gb;
    this.hb = hb;
    this.ib = ib;
    this.jb();
    this.B(this.ib.onDidChangeActivity((viewContainerOrAction) => {
      if ($zg(viewContainerOrAction) && viewContainerOrAction === this.Q.id) {
        this.jb();
      }
    }));
  }
  jb() {
    const activities = this.ib.getActivity(this.Q.id);
    let activity = activities[0];
    if (activity) {
      const { badge, priority } = activity;
      if (badge instanceof $wqb && activities.length > 1) {
        const cumulativeNumberBadge = this.kb(activities, priority ?? 0);
        activity = { badge: cumulativeNumberBadge };
      }
    }
    this.action.activity = activity;
  }
  kb(activityCache, priority) {
    const numberActivities = activityCache.filter((activity) => activity.badge instanceof $wqb && (activity.priority ?? 0) === priority);
    const number = numberActivities.reduce((result, activity) => {
      return result + activity.badge.number;
    }, 0);
    const descriptorFn = () => {
      return numberActivities.reduce((result, activity, index) => {
        result = result + activity.badge.getDescription();
        if (index < numberActivities.length - 1) {
          result = `${result}
`;
        }
        return result;
      }, "");
    };
    return new $wqb(number, descriptorFn);
  }
  render(container2) {
    super.render(container2);
    this.B($_i(this.b, $7j.MOUSE_DOWN, async (e) => {
      $9j.stop(e, true);
      const isLeftClick = e?.button !== 2;
      if (isLeftClick) {
        this.mb();
      }
    }));
    this.B($_i(this.b, $7j.CONTEXT_MENU, async (e) => {
      e.stopPropagation();
      const disposables = new $2c();
      const actions = await this.lb(disposables);
      const event = new $lf(getWindow(this.b), e);
      this.gb.showContextMenu({
        getAnchor: () => event,
        getActions: () => actions,
        onHide: () => disposables.dispose()
      });
    }));
    this.B($_i(this.b, $7j.KEY_UP, (e) => {
      const event = new $if(e);
      if (event.equals(
        3
        /* KeyCode.Enter */
      ) || event.equals(
        10
        /* KeyCode.Space */
      )) {
        $9j.stop(e, true);
        this.mb();
      }
    }));
    this.B($_i(this.b, EventType.Tap, (e) => {
      $9j.stop(e, true);
      this.mb();
    }));
  }
  async lb(disposables) {
    return this.db();
  }
  async mb() {
    const disposables = new $2c();
    const menu = disposables.add(this.fb.createMenu(this.cb, this.hb));
    const actions = await this.nb(menu, disposables);
    const { anchorAlignment, anchorAxisAlignment } = this.eb() ?? { anchorAlignment: void 0, anchorAxisAlignment: void 0 };
    this.gb.showContextMenu({
      getAnchor: () => this.c,
      anchorAlignment,
      anchorAxisAlignment,
      getActions: () => actions,
      onHide: () => disposables.dispose(),
      menuActionOptions: { renderShortTitle: true }
    });
  }
  async nb(menu, _disposable) {
    return $Q$(menu.getActions({ renderShortTitle: true })).secondary;
  }
};
AbstractGlobalActivityActionViewItem = __decorate([
  __param(5, $gs),
  __param(6, $5$),
  __param(7, $cJ),
  __param(8, $50),
  __param(9, $on),
  __param(10, $kl),
  __param(11, $Ty),
  __param(12, $vqb)
], AbstractGlobalActivityActionViewItem);
var $YTb = class $YTb2 extends AbstractGlobalActivityActionViewItem {
  static {
    this.ACCOUNTS_VISIBILITY_PREFERENCE_KEY = "workbench.activity.showAccounts";
  }
  constructor(contextMenuActionsProvider, options3, contextMenuAlignmentOptions, sb, themeService, tb, hoverService, contextMenuService, menuService, contextKeyService, ub, environmentService, vb, configurationService, keybindingService, wb, xb, activityService, instantiationService, yb) {
    const action = instantiationService.createInstance($Bqb, {
      id: $Qzb,
      name: localize(3604, null),
      classNames: ThemeIcon.asClassNameArray($XTb.ACCOUNTS_ICON)
    });
    super($bJ.AccountsContext, action, options3, contextMenuActionsProvider, contextMenuAlignmentOptions, themeService, hoverService, menuService, contextMenuService, contextKeyService, configurationService, keybindingService, activityService);
    this.sb = sb;
    this.tb = tb;
    this.ub = ub;
    this.vb = vb;
    this.wb = wb;
    this.xb = xb;
    this.yb = yb;
    this.ob = /* @__PURE__ */ new Map();
    this.pb = /* @__PURE__ */ new Set();
    this.qb = false;
    this.rb = new $sf(() => $Y4(this.wb, this.vb));
    this.B(action);
    this.zb();
    this.Ab();
  }
  zb() {
    this.B(this.ub.onDidRegisterAuthenticationProvider(async (e) => {
      await this.Gb(e.id);
    }));
    this.B(this.ub.onDidUnregisterAuthenticationProvider((e) => {
      this.ob.delete(e.id);
      this.pb.delete(e.id);
    }));
    this.B(this.ub.onDidChangeSessions(async (e) => {
      if (e.event.removed) {
        for (const removed of e.event.removed) {
          this.Fb(e.providerId, removed.account);
        }
      }
      for (const changed of [...e.event.changed ?? [], ...e.event.added ?? []]) {
        try {
          await this.Eb(e.providerId, changed.account);
        } catch (e2) {
          this.xb.error(e2);
        }
      }
    }));
  }
  // This function exists to ensure that the accounts are added for auth providers that had already been registered
  // before the menu was created.
  async Ab() {
    await this.tb.when(
      3
      /* LifecyclePhase.Restored */
    );
    if (this.q.isDisposed) {
      return;
    }
    const disposable = this.B($gj(getWindow(this.element), async () => {
      await this.Bb();
      disposable.dispose();
    }));
  }
  async Bb() {
    const providerIds = this.ub.getProviderIds();
    const results = await Promise.allSettled(providerIds.map((providerId) => this.Gb(providerId)));
    for (const result of results) {
      if (result.status === "rejected") {
        this.xb.error(result.reason);
      }
    }
    this.qb = true;
  }
  //#region overrides
  async nb(accountsMenu, disposables) {
    await super.nb(accountsMenu, disposables);
    const providers2 = this.ub.getProviderIds();
    const otherCommands = accountsMenu.getActions();
    let menus = [];
    for (const providerId of providers2) {
      if (!this.qb) {
        const noAccountsAvailableAction = disposables.add(new $Um("noAccountsAvailable", localize(3605, null), void 0, false));
        menus.push(noAccountsAvailableAction);
        break;
      }
      const providerLabel = this.ub.getProvider(providerId).label;
      const accounts = this.ob.get(providerId);
      if (!accounts) {
        if (this.pb.has(providerId)) {
          const providerUnavailableAction = disposables.add(new $Um("providerUnavailable", localize(3606, null, providerLabel), void 0, false));
          menus.push(providerUnavailableAction);
          try {
            await this.Gb(providerId);
          } catch (e) {
            this.xb.error(e);
          }
        }
        continue;
      }
      for (const account of accounts) {
        const manageExtensionsAction = $Zm({
          id: `configureSessions${account.label}`,
          label: localize(3607, null),
          enabled: true,
          run: () => this.yb.executeCommand("_manageTrustedExtensionsForAccount", { providerId, accountLabel: account.label })
        });
        const providerSubMenuActions = [manageExtensionsAction];
        if (account.canSignOut) {
          providerSubMenuActions.push($Zm({
            id: "signOut",
            label: localize(3608, null),
            enabled: true,
            run: () => this.yb.executeCommand("_signOutOfAccount", { providerId, accountLabel: account.label })
          }));
        }
        const providerSubMenu = new $Xm("activitybar.submenu", `${account.label} (${providerLabel})`, providerSubMenuActions);
        menus.push(providerSubMenu);
      }
    }
    if (providers2.length && !menus.length) {
      const noAccountsAvailableAction = disposables.add(new $Um("noAccountsAvailable", localize(3609, null), void 0, false));
      menus.push(noAccountsAvailableAction);
    }
    if (menus.length && otherCommands.length) {
      menus.push(new $Wm());
    }
    otherCommands.forEach((group2, i2) => {
      const actions = group2[1];
      menus = menus.concat(actions);
      if (i2 !== otherCommands.length - 1) {
        menus.push(new $Wm());
      }
    });
    return menus;
  }
  async lb(disposables) {
    const actions = await super.lb(disposables);
    this.sb(actions);
    return actions;
  }
  //#endregion
  //#region groupedAccounts helpers
  async Eb(providerId, account) {
    let accounts = this.ob.get(providerId);
    if (!accounts) {
      accounts = [];
      this.ob.set(providerId, accounts);
    }
    const sessionFromEmbedder = await this.rb.value;
    let canSignOut = true;
    if (sessionFromEmbedder && !sessionFromEmbedder.canSignOut && (await this.ub.getSessions(providerId)).some((s) => s.id === sessionFromEmbedder.id && s.account.id === account.id)) {
      canSignOut = false;
    }
    const existingAccount = accounts.find((a) => a.label === account.label);
    if (existingAccount) {
      if (!canSignOut) {
        existingAccount.canSignOut = canSignOut;
      }
    } else {
      accounts.push({ ...account, canSignOut });
    }
  }
  Fb(providerId, account) {
    const accounts = this.ob.get(providerId);
    if (!accounts) {
      return;
    }
    const index = accounts.findIndex((a) => a.id === account.id);
    if (index === -1) {
      return;
    }
    accounts.splice(index, 1);
    if (accounts.length === 0) {
      this.ob.delete(providerId);
    }
  }
  async Gb(providerId) {
    try {
      const sessions = await this.ub.getSessions(providerId);
      this.pb.delete(providerId);
      for (const session of sessions) {
        try {
          await this.Eb(providerId, session.account);
        } catch (e) {
          this.xb.error(e);
        }
      }
    } catch (e) {
      this.xb.error(e);
      this.pb.add(providerId);
    }
  }
};
$YTb = __decorate([
  __param(4, $gs),
  __param(5, $KL),
  __param(6, $5$),
  __param(7, $50),
  __param(8, $cJ),
  __param(9, $on),
  __param(10, $xS),
  __param(11, $US),
  __param(12, $Vu),
  __param(13, $kl),
  __param(14, $Ty),
  __param(15, $J4),
  __param(16, $wn),
  __param(17, $vqb),
  __param(18, $Pk),
  __param(19, $sn)
], $YTb);
var $ZTb = class $ZTb2 extends AbstractGlobalActivityActionViewItem {
  constructor(contextMenuActionsProvider, options3, contextMenuAlignmentOptions, qb, themeService, hoverService, menuService, contextMenuService, contextKeyService, configurationService, environmentService, keybindingService, instantiationService, activityService) {
    const action = instantiationService.createInstance($Bqb, {
      id: $Pzb,
      name: localize(3610, null),
      classNames: ThemeIcon.asClassNameArray(qb.currentProfile.icon ? ThemeIcon.fromId(qb.currentProfile.icon) : $VTb)
    });
    super($bJ.GlobalActivity, action, options3, contextMenuActionsProvider, contextMenuAlignmentOptions, themeService, hoverService, menuService, contextMenuService, contextKeyService, configurationService, keybindingService, activityService);
    this.qb = qb;
    this.B(action);
    this.B(this.qb.onDidChangeCurrentProfile((e) => {
      action.compositeBarActionItem = {
        ...action.compositeBarActionItem,
        classNames: ThemeIcon.asClassNameArray(qb.currentProfile.icon ? ThemeIcon.fromId(qb.currentProfile.icon) : $VTb)
      };
    }));
  }
  render(container2) {
    super.render(container2);
    this.ob = $bk(container2, $(".profile-badge"));
    this.pb = $bk(this.ob, $(".profile-badge-content"));
    this.rb();
  }
  rb() {
    if (!this.ob || !this.pb) {
      return;
    }
    $$i(this.pb);
    $ik(this.ob);
    if (this.qb.currentProfile.isDefault) {
      return;
    }
    if (this.qb.currentProfile.icon && this.qb.currentProfile.icon !== $VTb.id) {
      return;
    }
    if (this.action.activity) {
      return;
    }
    $hk(this.ob);
    this.pb.classList.add("profile-text-overlay");
    this.pb.textContent = this.qb.currentProfile.name.substring(0, 2).toUpperCase();
  }
  X() {
    super.X();
    this.rb();
  }
  ab() {
    return this.qb.currentProfile.isDefault ? super.ab() : localize(3611, null, this.qb.currentProfile.name);
  }
};
$ZTb = __decorate([
  __param(3, $gT),
  __param(4, $gs),
  __param(5, $5$),
  __param(6, $cJ),
  __param(7, $50),
  __param(8, $on),
  __param(9, $kl),
  __param(10, $US),
  __param(11, $Ty),
  __param(12, $Pk),
  __param(13, $vqb)
], $ZTb);
var $1Tb = class $1Tb2 extends $YTb {
  constructor(hoverOptions, options3, themeService, lifecycleService, hoverService, contextMenuService, menuService, contextKeyService, authenticationService, environmentService, productService, configurationService, keybindingService, secretStorageService, storageService, logService, activityService, instantiationService, commandService) {
    super(() => simpleActivityContextMenuActions(storageService, true), {
      ...options3,
      colors: (theme) => ({
        badgeBackground: theme.getColor($vnb),
        badgeForeground: theme.getColor($wnb)
      }),
      hoverOptions,
      compact: true
    }, () => void 0, (actions) => actions, themeService, lifecycleService, hoverService, contextMenuService, menuService, contextKeyService, authenticationService, environmentService, productService, configurationService, keybindingService, secretStorageService, logService, activityService, instantiationService, commandService);
  }
};
$1Tb = __decorate([
  __param(2, $gs),
  __param(3, $KL),
  __param(4, $5$),
  __param(5, $50),
  __param(6, $cJ),
  __param(7, $on),
  __param(8, $xS),
  __param(9, $US),
  __param(10, $Vu),
  __param(11, $kl),
  __param(12, $Ty),
  __param(13, $J4),
  __param(14, $jv),
  __param(15, $wn),
  __param(16, $vqb),
  __param(17, $Pk),
  __param(18, $sn)
], $1Tb);
var $2Tb = class $2Tb2 extends $ZTb {
  constructor(hoverOptions, options3, userDataProfileService, themeService, hoverService, menuService, contextMenuService, contextKeyService, configurationService, environmentService, keybindingService, instantiationService, activityService, storageService) {
    super(() => simpleActivityContextMenuActions(storageService, false), {
      ...options3,
      colors: (theme) => ({
        badgeBackground: theme.getColor($vnb),
        badgeForeground: theme.getColor($wnb)
      }),
      hoverOptions,
      compact: true
    }, () => void 0, userDataProfileService, themeService, hoverService, menuService, contextMenuService, contextKeyService, configurationService, environmentService, keybindingService, instantiationService, activityService);
  }
};
$2Tb = __decorate([
  __param(2, $gT),
  __param(3, $gs),
  __param(4, $5$),
  __param(5, $cJ),
  __param(6, $50),
  __param(7, $on),
  __param(8, $kl),
  __param(9, $US),
  __param(10, $Ty),
  __param(11, $Pk),
  __param(12, $vqb),
  __param(13, $jv)
], $2Tb);
function simpleActivityContextMenuActions(storageService, isAccount) {
  const currentElementContextMenuActions = [];
  if (isAccount) {
    currentElementContextMenuActions.push($Zm({ id: "hideAccounts", label: localize(3612, null), run: () => setAccountsActionVisible(storageService, false) }), new $Wm());
  }
  return [
    ...currentElementContextMenuActions,
    $Zm({ id: "toggle.hideAccounts", label: localize(3613, null), checked: $3Tb(storageService), run: () => setAccountsActionVisible(storageService, !$3Tb(storageService)) }),
    $Zm({ id: "toggle.hideManage", label: localize(3614, null), checked: true, enabled: false, run: () => {
      throw new Error('"Manage" can not be hidden');
    } })
  ];
}
function $3Tb(storageService) {
  return storageService.getBoolean($YTb.ACCOUNTS_VISIBILITY_PREFERENCE_KEY, 0, true);
}
function setAccountsActionVisible(storageService, visible) {
  storageService.store(
    $YTb.ACCOUNTS_VISIBILITY_PREFERENCE_KEY,
    visible,
    0,
    0
    /* StorageTarget.USER */
  );
}

// out-build/vs/workbench/browser/parts/activitybar/activitybarPart.js
var $fVb_1;
var $fVb = class $fVb2 extends Part {
  static {
    $fVb_1 = this;
  }
  static {
    this.ACTION_HEIGHT = 48;
  }
  static {
    this.pinnedViewContainersKey = "workbench.activity.pinnedViewlets2";
  }
  static {
    this.placeholderViewContainersKey = "workbench.activity.placeholderViewlets";
  }
  static {
    this.viewContainersWorkspaceStateKey = "workbench.activity.viewletsWorkspaceState";
  }
  constructor(c, y, layoutService, themeService, storageService) {
    super("workbench.parts.activitybar", { hasTitle: false }, themeService, storageService, layoutService);
    this.c = c;
    this.y = y;
    this.minimumWidth = 48;
    this.maximumWidth = 48;
    this.minimumHeight = 0;
    this.maximumHeight = Number.POSITIVE_INFINITY;
    this.a = this.B(new $4c());
  }
  bb() {
    return this.y.createInstance($gVb, {
      partContainerClass: "activitybar",
      pinnedViewContainersKey: $fVb_1.pinnedViewContainersKey,
      placeholderViewContainersKey: $fVb_1.placeholderViewContainersKey,
      viewContainersWorkspaceStateKey: $fVb_1.viewContainersWorkspaceStateKey,
      orientation: 1,
      icon: true,
      iconSize: 24,
      activityHoverOptions: {
        position: () => this.M.getSideBarPosition() === 0 ? 1 : 0
      },
      preventLoopNavigation: true,
      recomputeSizes: false,
      fillExtraContextMenuActions: (actions, e) => {
      },
      compositeSize: 52,
      colors: (theme) => ({
        activeForegroundColor: theme.getColor($onb),
        inactiveForegroundColor: theme.getColor($pnb),
        activeBorderColor: theme.getColor($rnb),
        activeBackground: theme.getColor($tnb),
        badgeBackground: theme.getColor($vnb),
        badgeForeground: theme.getColor($wnb),
        dragAndDropBorder: theme.getColor($unb),
        activeBackgroundColor: void 0,
        inactiveBackgroundColor: void 0,
        activeBorderBottomColor: void 0
      }),
      overflowActionSize: $fVb_1.ACTION_HEIGHT
    }, "workbench.parts.activitybar", this.c, true);
  }
  Q(parent) {
    this.element = parent;
    this.b = $bk(this.element, $(".content"));
    if (this.M.isVisible(
      "workbench.parts.activitybar"
      /* Parts.ACTIVITYBAR_PART */
    )) {
      this.show();
    }
    return this.b;
  }
  getPinnedPaneCompositeIds() {
    return this.a.value?.getPinnedPaneCompositeIds() ?? [];
  }
  getVisiblePaneCompositeIds() {
    return this.a.value?.getVisiblePaneCompositeIds() ?? [];
  }
  getPaneCompositeIds() {
    return this.a.value?.getPaneCompositeIds() ?? [];
  }
  focus() {
    this.a.value?.focus();
  }
  updateStyles() {
    super.updateStyles();
    const container2 = $Kg(this.getContainer());
    const background = this.z($nnb) || "";
    container2.style.backgroundColor = background;
    const borderColor = this.z($qnb) || this.z($ko) || "";
    container2.classList.toggle("bordered", !!borderColor);
    container2.style.borderColor = borderColor ? borderColor : "";
  }
  show(focus) {
    if (!this.b) {
      return;
    }
    if (!this.a.value) {
      this.a.value = this.bb();
      this.a.value.create(this.b);
      if (this.dimension) {
        this.layout(this.dimension.width, this.dimension.height);
      }
    }
    if (focus) {
      this.focus();
    }
  }
  hide() {
    if (!this.a.value) {
      return;
    }
    this.a.clear();
    if (this.b) {
      $$i(this.b);
    }
  }
  layout(width2, height) {
    super.layout(width2, height, 0, 0);
    if (!this.a.value) {
      return;
    }
    const contentAreaSize = super.Z(width2, height).contentSize;
    this.a.value.layout(width2, contentAreaSize.height);
  }
  toJSON() {
    return {
      type: "workbench.parts.activitybar"
      /* Parts.ACTIVITYBAR_PART */
    };
  }
};
$fVb = $fVb_1 = __decorate([
  __param(1, $Pk),
  __param(2, $Vlb),
  __param(3, $gs),
  __param(4, $jv)
], $fVb);
var $gVb = class $gVb2 extends $aVb {
  constructor(options3, part, paneCompositePart, showGlobalActivities, instantiationService, storageService, extensionService, viewDescriptorService, viewService, contextKeyService, environmentService, Gb, Hb, layoutService) {
    super({
      ...options3,
      fillExtraContextMenuActions: (actions, e) => {
        options3.fillExtraContextMenuActions(actions, e);
        this.Ib(actions, e);
      }
    }, part, paneCompositePart, instantiationService, storageService, extensionService, viewDescriptorService, viewService, contextKeyService, environmentService, layoutService);
    this.Gb = Gb;
    this.Hb = Hb;
    this.Fb = this.B(new $2c());
    if (showGlobalActivities) {
      this.Eb = this.B(instantiationService.createInstance($XTb, () => this.getContextMenuActions(), (theme) => this.j.colors(theme), this.j.activityHoverOptions));
    }
    this.B(this.Gb.onDidChangeConfiguration((e) => {
      if (e.affectsConfiguration("window.menuBarVisibility")) {
        if ($Bs(this.Gb) === "compact") {
          this.Kb();
        } else {
          this.Jb();
        }
      }
    }));
  }
  Ib(actions, e) {
    const menuBarVisibility = $Bs(this.Gb);
    if (menuBarVisibility === "compact" || menuBarVisibility === "hidden" || menuBarVisibility === "toggle") {
      actions.unshift(...[$Zm({ id: "toggleMenuVisibility", label: localize(3049, null), checked: menuBarVisibility === "compact", run: () => this.Gb.updateValue("window.menuBarVisibility", menuBarVisibility === "compact" ? "toggle" : "compact") }), new $Wm()]);
    }
    if (menuBarVisibility === "compact" && this.Cb && e?.target) {
      if ($Dj(e.target, this.Cb)) {
        actions.unshift(...[$Zm({ id: "hideCompactMenu", label: localize(3050, null), run: () => this.Gb.updateValue("window.menuBarVisibility", "toggle") }), new $Wm()]);
      }
    }
    if (this.Eb) {
      actions.push(new $Wm());
      actions.push(...this.Eb.getContextMenuActions());
    }
    actions.push(new $Wm());
    actions.push(...this.getActivityBarContextMenuActions());
  }
  Jb() {
    if (this.Bb) {
      this.Bb.dispose();
      this.Bb = void 0;
    }
    if (this.Cb) {
      this.Cb.remove();
      this.Cb = void 0;
    }
  }
  Kb() {
    if (this.Bb) {
      return;
    }
    this.Cb = document.createElement("div");
    this.Cb.classList.add("menubar");
    const content = $Kg(this.Ab);
    content.prepend(this.Cb);
    this.Bb = this.B(this.r.createInstance($TTb));
    this.Bb.create(this.Cb);
  }
  Lb() {
    this.Fb.clear();
    if (this.Cb) {
      this.Fb.add($_i(this.Cb, $7j.KEY_DOWN, (e) => {
        const kbEvent = new $if(e);
        if (kbEvent.equals(
          18
          /* KeyCode.DownArrow */
        ) || kbEvent.equals(
          17
          /* KeyCode.RightArrow */
        )) {
          this.focus();
        }
      }));
    }
    if (this.Db) {
      this.Fb.add($_i(this.Db, $7j.KEY_DOWN, (e) => {
        const kbEvent = new $if(e);
        if (kbEvent.equals(
          18
          /* KeyCode.DownArrow */
        ) || kbEvent.equals(
          17
          /* KeyCode.RightArrow */
        )) {
          this.Eb?.focus();
        } else if (kbEvent.equals(
          16
          /* KeyCode.UpArrow */
        ) || kbEvent.equals(
          15
          /* KeyCode.LeftArrow */
        )) {
          this.Bb?.toggleFocus();
        }
      }));
    }
    if (this.Eb) {
      this.Fb.add($_i(this.Eb.element, $7j.KEY_DOWN, (e) => {
        const kbEvent = new $if(e);
        if (kbEvent.equals(
          16
          /* KeyCode.UpArrow */
        ) || kbEvent.equals(
          15
          /* KeyCode.LeftArrow */
        )) {
          this.focus(this.getVisiblePaneCompositeIds().length - 1);
        }
      }));
    }
  }
  create(parent) {
    this.Ab = parent;
    if ($Bs(this.Gb) === "compact") {
      this.Kb();
    }
    this.Db = super.create(this.Ab);
    if (this.Eb) {
      this.Eb.create(this.Ab);
    }
    this.Lb();
    return this.Db;
  }
  layout(width2, height) {
    if (this.Cb) {
      if (this.j.orientation === 1) {
        height -= this.Cb.clientHeight;
      } else {
        width2 -= this.Cb.clientWidth;
      }
    }
    if (this.Eb) {
      if (this.j.orientation === 1) {
        height -= this.Eb.size() * $fVb.ACTION_HEIGHT;
      } else {
        width2 -= this.Eb.element.clientWidth;
      }
    }
    super.layout(width2, height);
  }
  getActivityBarContextMenuActions() {
    const activityBarPositionMenu = this.Hb.getMenuActions($bJ.ActivityBarPositionMenu, this.y, { shouldForwardArgs: true, renderShortTitle: true });
    const positionActions = $O$(activityBarPositionMenu).secondary;
    return [
      new $Xm("workbench.action.panel.position", localize(3051, null), positionActions),
      $Zm({ id: $Oqb.ID, label: $Oqb.getLabel(this.C), run: () => this.r.invokeFunction((accessor) => new $Oqb().run(accessor)) })
    ];
  }
};
$gVb = __decorate([
  __param(4, $Pk),
  __param(5, $jv),
  __param(6, $wN),
  __param(7, $$M),
  __param(8, $uob),
  __param(9, $on),
  __param(10, $US),
  __param(11, $kl),
  __param(12, $cJ),
  __param(13, $Vlb)
], $gVb);
$hJ(class extends $gJ {
  constructor() {
    super({
      id: "workbench.action.activityBarLocation.default",
      title: {
        ...localize2(3063, "Move Activity Bar to Side"),
        mnemonicTitle: localize(3052, null)
      },
      shortTitle: localize(3053, null),
      category: $qn.View,
      toggled: $7m.equals(
        `config.${"workbench.activityBar.location"}`,
        "default"
        /* ActivityBarPosition.DEFAULT */
      ),
      menu: [{
        id: $bJ.ActivityBarPositionMenu,
        order: 1
      }, {
        id: $bJ.CommandPalette,
        when: $7m.notEquals(
          `config.${"workbench.activityBar.location"}`,
          "default"
          /* ActivityBarPosition.DEFAULT */
        )
      }]
    });
  }
  run(accessor) {
    const configurationService = accessor.get($kl);
    configurationService.updateValue(
      "workbench.activityBar.location",
      "default"
      /* ActivityBarPosition.DEFAULT */
    );
  }
});
$hJ(class extends $gJ {
  constructor() {
    super({
      id: "workbench.action.activityBarLocation.top",
      title: {
        ...localize2(3064, "Move Activity Bar to Top"),
        mnemonicTitle: localize(3054, null)
      },
      shortTitle: localize(3055, null),
      category: $qn.View,
      toggled: $7m.equals(
        `config.${"workbench.activityBar.location"}`,
        "top"
        /* ActivityBarPosition.TOP */
      ),
      menu: [{
        id: $bJ.ActivityBarPositionMenu,
        order: 2
      }, {
        id: $bJ.CommandPalette,
        when: $7m.notEquals(
          `config.${"workbench.activityBar.location"}`,
          "top"
          /* ActivityBarPosition.TOP */
        )
      }]
    });
  }
  run(accessor) {
    const configurationService = accessor.get($kl);
    configurationService.updateValue(
      "workbench.activityBar.location",
      "top"
      /* ActivityBarPosition.TOP */
    );
  }
});
$hJ(class extends $gJ {
  constructor() {
    super({
      id: "workbench.action.activityBarLocation.bottom",
      title: {
        ...localize2(3065, "Move Activity Bar to Bottom"),
        mnemonicTitle: localize(3056, null)
      },
      shortTitle: localize(3057, null),
      category: $qn.View,
      toggled: $7m.equals(
        `config.${"workbench.activityBar.location"}`,
        "bottom"
        /* ActivityBarPosition.BOTTOM */
      ),
      menu: [{
        id: $bJ.ActivityBarPositionMenu,
        order: 3
      }, {
        id: $bJ.CommandPalette,
        when: $7m.notEquals(
          `config.${"workbench.activityBar.location"}`,
          "bottom"
          /* ActivityBarPosition.BOTTOM */
        )
      }]
    });
  }
  run(accessor) {
    const configurationService = accessor.get($kl);
    configurationService.updateValue(
      "workbench.activityBar.location",
      "bottom"
      /* ActivityBarPosition.BOTTOM */
    );
  }
});
$hJ(class extends $gJ {
  constructor() {
    super({
      id: "workbench.action.activityBarLocation.hide",
      title: {
        ...localize2(3066, "Hide Activity Bar"),
        mnemonicTitle: localize(3058, null)
      },
      shortTitle: localize(3059, null),
      category: $qn.View,
      toggled: $7m.equals(
        `config.${"workbench.activityBar.location"}`,
        "hidden"
        /* ActivityBarPosition.HIDDEN */
      ),
      menu: [{
        id: $bJ.ActivityBarPositionMenu,
        order: 4
      }, {
        id: $bJ.CommandPalette,
        when: $7m.notEquals(
          `config.${"workbench.activityBar.location"}`,
          "hidden"
          /* ActivityBarPosition.HIDDEN */
        )
      }]
    });
  }
  run(accessor) {
    const configurationService = accessor.get($kl);
    configurationService.updateValue(
      "workbench.activityBar.location",
      "hidden"
      /* ActivityBarPosition.HIDDEN */
    );
  }
});
$dJ.appendMenuItem($bJ.MenubarAppearanceMenu, {
  submenu: $bJ.ActivityBarPositionMenu,
  title: localize(3060, null),
  group: "3_workbench_layout_move",
  order: 2
});
$dJ.appendMenuItem($bJ.ViewContainerTitleContext, {
  submenu: $bJ.ActivityBarPositionMenu,
  title: localize(3061, null),
  when: $7m.equals("viewContainerLocation", $0M(
    0
    /* ViewContainerLocation.Sidebar */
  )),
  group: "3_workbench_layout_move",
  order: 1
});
$dJ.appendMenuItem($bJ.ViewTitleContext, {
  submenu: $bJ.ActivityBarPositionMenu,
  title: localize(3062, null),
  when: $7m.equals("viewLocation", $0M(
    0
    /* ViewContainerLocation.Sidebar */
  )),
  group: "3_workbench_layout_move",
  order: 1
});
$hJ(class extends $Iqb {
  constructor() {
    super({
      id: "workbench.action.previousSideBarView",
      title: localize2(3067, "Previous Primary Side Bar View"),
      category: $qn.View,
      f1: true
    }, 0, -1);
  }
});
$hJ(class extends $Iqb {
  constructor() {
    super({
      id: "workbench.action.nextSideBarView",
      title: localize2(3068, "Next Primary Side Bar View"),
      category: $qn.View,
      f1: true
    }, 0, 1);
  }
});
$hJ(class FocusActivityBarAction extends $gJ {
  constructor() {
    super({
      id: "workbench.action.focusActivityBar",
      title: localize2(3069, "Focus Activity Bar"),
      category: $qn.View,
      f1: true
    });
  }
  async run(accessor) {
    const layoutService = accessor.get($Vlb);
    layoutService.focusPart(
      "workbench.parts.activitybar"
      /* Parts.ACTIVITYBAR_PART */
    );
  }
});
$ms((theme, collector) => {
  const activityBarActiveBorderColor = theme.getColor($rnb);
  if (activityBarActiveBorderColor) {
    collector.addRule(`
			.monaco-workbench .activitybar > .content :not(.monaco-menu) > .monaco-action-bar .action-item.checked .active-item-indicator:before {
				border-left-color: ${activityBarActiveBorderColor};
			}
		`);
  }
  const activityBarActiveFocusBorderColor = theme.getColor($snb);
  if (activityBarActiveFocusBorderColor) {
    collector.addRule(`
			.monaco-workbench .activitybar > .content :not(.monaco-menu) > .monaco-action-bar .action-item.checked:focus::before {
				visibility: hidden;
			}

			.monaco-workbench .activitybar > .content :not(.monaco-menu) > .monaco-action-bar .action-item.checked:focus .active-item-indicator:before {
				visibility: visible;
				border-left-color: ${activityBarActiveFocusBorderColor};
			}
		`);
  }
  const activityBarActiveBackgroundColor = theme.getColor($tnb);
  if (activityBarActiveBackgroundColor) {
    collector.addRule(`
			.monaco-workbench .activitybar > .content :not(.monaco-menu) > .monaco-action-bar .action-item.checked .active-item-indicator {
				z-index: 0;
				background-color: ${activityBarActiveBackgroundColor};
			}
		`);
  }
  const outline = theme.getColor($lo);
  if (outline) {
    collector.addRule(`
			.monaco-workbench .activitybar > .content :not(.monaco-menu) > .monaco-action-bar .action-item .action-label::before{
				padding: 6px;
			}

			.monaco-workbench .activitybar > .content :not(.monaco-menu) > .monaco-action-bar .action-item.active .action-label::before,
			.monaco-workbench .activitybar > .content :not(.monaco-menu) > .monaco-action-bar .action-item.active:hover .action-label::before,
			.monaco-workbench .activitybar > .content :not(.monaco-menu) > .monaco-action-bar .action-item.checked .action-label::before,
			.monaco-workbench .activitybar > .content :not(.monaco-menu) > .monaco-action-bar .action-item.checked:hover .action-label::before {
				outline: 1px solid ${outline};
			}

			.monaco-workbench .activitybar > .content :not(.monaco-menu) > .monaco-action-bar .action-item:hover .action-label::before {
				outline: 1px dashed ${outline};
			}

			.monaco-workbench .activitybar > .content :not(.monaco-menu) > .monaco-action-bar .action-item:focus .active-item-indicator:before {
				border-left-color: ${outline};
			}
		`);
  } else {
    const focusBorderColor = theme.getColor($jo);
    if (focusBorderColor) {
      collector.addRule(`
				.monaco-workbench .activitybar > .content :not(.monaco-menu) > .monaco-action-bar .action-item:focus .active-item-indicator::before {
						border-left-color: ${focusBorderColor};
					}
				`);
    }
  }
});

// out-build/vs/workbench/browser/parts/sidebar/sidebarPart.js
var $hVb_1;
var $hVb = class $hVb2 extends $bVb {
  static {
    $hVb_1 = this;
  }
  static {
    this.activeViewletSettingsKey = "workbench.sidebar.activeviewletid";
  }
  get snap() {
    return true;
  }
  get preferredWidth() {
    const viewlet = this.getActivePaneComposite();
    if (!viewlet) {
      return;
    }
    const width2 = viewlet.getOptimalWidth();
    if (typeof width2 !== "number") {
      return;
    }
    return Math.max(width2, 300);
  }
  //#endregion
  constructor(notificationService, storageService, contextMenuService, layoutService, keybindingService, hoverService, instantiationService, themeService, viewDescriptorService, contextKeyService, extensionService, Qc, menuService) {
    super("workbench.parts.sidebar", { hasTitle: true, borderWidth: () => this.z($Rnb) || this.z($ko) ? 1 : 0 }, $hVb_1.activeViewletSettingsKey, $5pb.bindTo(contextKeyService), $4pb.bindTo(contextKeyService), "sideBar", "viewlet", $Tnb, $Unb, notificationService, storageService, contextMenuService, layoutService, keybindingService, hoverService, instantiationService, themeService, viewDescriptorService, contextKeyService, extensionService, menuService);
    this.Qc = Qc;
    this.minimumWidth = 170;
    this.maximumWidth = Number.POSITIVE_INFINITY;
    this.minimumHeight = 0;
    this.maximumHeight = Number.POSITIVE_INFINITY;
    this.priority = 1;
    this.Pc = this.B(this.ub.createInstance($fVb, this));
    this.Yc();
    this.B(Qc.onDidChangeConfiguration((e) => {
      if (e.affectsConfiguration(
        "workbench.activityBar.location"
        /* LayoutSettings.ACTIVITY_BAR_LOCATION */
      )) {
        this.Rc();
      }
    }));
    this.$c();
  }
  Rc() {
    this.Pc.hide();
    this.vc();
    const id2 = this.Jb()?.getId();
    if (id2) {
      this.Gb(id2);
    }
    if (this.Wc()) {
      this.Pc.show();
    }
    this.Yc();
  }
  updateStyles() {
    super.updateStyles();
    const container2 = $Kg(this.getContainer());
    container2.style.backgroundColor = this.z($Pnb) || "";
    container2.style.color = this.z($Qnb) || "";
    const borderColor = this.z($Rnb) || this.z($ko);
    const isPositionLeft = this.M.getSideBarPosition() === 0;
    container2.style.borderRightWidth = borderColor && isPositionLeft ? "1px" : "";
    container2.style.borderRightStyle = borderColor && isPositionLeft ? "solid" : "";
    container2.style.borderRightColor = isPositionLeft ? borderColor || "" : "";
    container2.style.borderLeftWidth = borderColor && !isPositionLeft ? "1px" : "";
    container2.style.borderLeftStyle = borderColor && !isPositionLeft ? "solid" : "";
    container2.style.borderLeftColor = !isPositionLeft ? borderColor || "" : "";
    container2.style.outlineColor = this.z($Vnb) ?? "";
  }
  layout(width2, height, top2, left) {
    if (!this.M.isVisible(
      "workbench.parts.sidebar"
      /* Parts.SIDEBAR_PART */
    )) {
      return;
    }
    super.layout(width2, height, top2, left);
  }
  Tb() {
    return this.M.getSideBarPosition() === 0 ? 0 : 1;
  }
  Ac() {
    return this.ub.createInstance($gVb, this.Nc(), this.partId, this, false);
  }
  Nc() {
    return {
      partContainerClass: "sidebar",
      pinnedViewContainersKey: $fVb.pinnedViewContainersKey,
      placeholderViewContainersKey: $fVb.placeholderViewContainersKey,
      viewContainersWorkspaceStateKey: $fVb.viewContainersWorkspaceStateKey,
      icon: true,
      orientation: 0,
      recomputeSizes: true,
      activityHoverOptions: {
        position: () => this.Oc() === CompositeBarPosition.BOTTOM ? 3 : 2
      },
      fillExtraContextMenuActions: (actions) => {
        if (this.Oc() === CompositeBarPosition.TITLE) {
          const viewsSubmenuAction = this.Lc();
          if (viewsSubmenuAction) {
            actions.push(new $Wm());
            actions.push(viewsSubmenuAction);
          }
        }
      },
      compositeSize: 0,
      iconSize: 16,
      overflowActionSize: 30,
      colors: (theme) => ({
        activeBackgroundColor: theme.getColor($Pnb),
        inactiveBackgroundColor: theme.getColor($Pnb),
        activeBorderBottomColor: theme.getColor($ynb),
        activeForegroundColor: theme.getColor($xnb),
        inactiveForegroundColor: theme.getColor($Anb),
        badgeBackground: theme.getColor($vnb),
        badgeForeground: theme.getColor($wnb),
        dragAndDropBorder: theme.getColor($Bnb)
      }),
      compact: true
    };
  }
  Mc() {
    const activityBarPosition = this.Qc.getValue(
      "workbench.activityBar.location"
      /* LayoutSettings.ACTIVITY_BAR_LOCATION */
    );
    return activityBarPosition === "top" || activityBarPosition === "bottom";
  }
  Wc() {
    if (this.Mc()) {
      return false;
    }
    return this.Qc.getValue(
      "workbench.activityBar.location"
      /* LayoutSettings.ACTIVITY_BAR_LOCATION */
    ) !== "hidden";
  }
  Oc() {
    const activityBarPosition = this.Qc.getValue(
      "workbench.activityBar.location"
      /* LayoutSettings.ACTIVITY_BAR_LOCATION */
    );
    switch (activityBarPosition) {
      case "top":
        return CompositeBarPosition.TOP;
      case "bottom":
        return CompositeBarPosition.BOTTOM;
      case "hidden":
      case "default":
      default:
        return CompositeBarPosition.TITLE;
    }
  }
  Yc() {
    const activityBarPosition = this.Qc.getValue(
      "workbench.activityBar.location"
      /* LayoutSettings.ACTIVITY_BAR_LOCATION */
    );
    if (activityBarPosition !== "hidden") {
      this.qb.store(
        "workbench.activityBar.location",
        activityBarPosition,
        0,
        0
        /* StorageTarget.USER */
      );
    }
  }
  Zc() {
    const activityBarPosition = this.qb.get(
      "workbench.activityBar.location",
      0
      /* StorageScope.PROFILE */
    );
    switch (activityBarPosition) {
      case "top":
        return "top";
      case "bottom":
        return "bottom";
      default:
        return "default";
    }
  }
  getPinnedPaneCompositeIds() {
    return this.Mc() ? super.getPinnedPaneCompositeIds() : this.Pc.getPinnedPaneCompositeIds();
  }
  getVisiblePaneCompositeIds() {
    return this.Mc() ? super.getVisiblePaneCompositeIds() : this.Pc.getVisiblePaneCompositeIds();
  }
  getPaneCompositeIds() {
    return this.Mc() ? super.getPaneCompositeIds() : this.Pc.getPaneCompositeIds();
  }
  async focusActivityBar() {
    if (this.Qc.getValue(
      "workbench.activityBar.location"
      /* LayoutSettings.ACTIVITY_BAR_LOCATION */
    ) === "hidden") {
      await this.Qc.updateValue("workbench.activityBar.location", this.Zc());
      this.Rc();
    }
    if (this.Mc()) {
      this.Dc();
    } else {
      if (!this.M.isVisible(
        "workbench.parts.activitybar"
        /* Parts.ACTIVITYBAR_PART */
      )) {
        this.M.setPartHidden(
          false,
          "workbench.parts.activitybar"
          /* Parts.ACTIVITYBAR_PART */
        );
      }
      this.Pc.show(true);
    }
  }
  $c() {
    const that = this;
    this.B($hJ(class extends $gJ {
      constructor() {
        super({
          id: $Nqb,
          title: localize2(3739, "Toggle Activity Bar Visibility")
        });
      }
      run() {
        const value = that.Qc.getValue(
          "workbench.activityBar.location"
          /* LayoutSettings.ACTIVITY_BAR_LOCATION */
        ) === "hidden" ? that.Zc() : "hidden";
        return that.Qc.updateValue("workbench.activityBar.location", value);
      }
    }));
  }
  toJSON() {
    return {
      type: "workbench.parts.sidebar"
      /* Parts.SIDEBAR_PART */
    };
  }
};
$hVb = $hVb_1 = __decorate([
  __param(0, $PJ),
  __param(1, $jv),
  __param(2, $50),
  __param(3, $Vlb),
  __param(4, $Ty),
  __param(5, $5$),
  __param(6, $Pk),
  __param(7, $gs),
  __param(8, $$M),
  __param(9, $on),
  __param(10, $wN),
  __param(11, $kl),
  __param(12, $cJ)
], $hVb);

// out-build/vs/workbench/browser/parts/paneCompositePartService.js
var $iVb = class $iVb2 extends $3c {
  constructor(instantiationService) {
    super();
    this.a = /* @__PURE__ */ new Map();
    const panelPart = instantiationService.createInstance($dVb);
    const sideBarPart = instantiationService.createInstance($hVb);
    const auxiliaryBarPart = instantiationService.createInstance($cVb);
    this.a.set(1, panelPart);
    this.a.set(0, sideBarPart);
    this.a.set(2, auxiliaryBarPart);
    const eventDisposables = this.B(new $2c());
    this.onDidPaneCompositeOpen = Event2.any(...$9M.map((loc) => Event2.map(this.a.get(loc).onDidPaneCompositeOpen, (composite) => {
      return { composite, viewContainerLocation: loc };
    }, eventDisposables)));
    this.onDidPaneCompositeClose = Event2.any(...$9M.map((loc) => Event2.map(this.a.get(loc).onDidPaneCompositeClose, (composite) => {
      return { composite, viewContainerLocation: loc };
    }, eventDisposables)));
  }
  openPaneComposite(id2, viewContainerLocation, focus) {
    return this.b(viewContainerLocation).openPaneComposite(id2, focus);
  }
  getActivePaneComposite(viewContainerLocation) {
    return this.b(viewContainerLocation).getActivePaneComposite();
  }
  getPaneComposite(id2, viewContainerLocation) {
    return this.b(viewContainerLocation).getPaneComposite(id2);
  }
  getPaneComposites(viewContainerLocation) {
    return this.b(viewContainerLocation).getPaneComposites();
  }
  getPinnedPaneCompositeIds(viewContainerLocation) {
    return this.b(viewContainerLocation).getPinnedPaneCompositeIds();
  }
  getVisiblePaneCompositeIds(viewContainerLocation) {
    return this.b(viewContainerLocation).getVisiblePaneCompositeIds();
  }
  getPaneCompositeIds(viewContainerLocation) {
    return this.b(viewContainerLocation).getPaneCompositeIds();
  }
  getProgressIndicator(id2, viewContainerLocation) {
    return this.b(viewContainerLocation).getProgressIndicator(id2);
  }
  hideActivePaneComposite(viewContainerLocation) {
    this.b(viewContainerLocation).hideActivePaneComposite();
  }
  getLastActivePaneCompositeId(viewContainerLocation) {
    return this.b(viewContainerLocation).getLastActivePaneCompositeId();
  }
  b(viewContainerLocation) {
    return $Kg(this.a.get(viewContainerLocation));
  }
};
$iVb = __decorate([
  __param(0, $Pk)
], $iVb);
$SC(
  $uqb,
  $iVb,
  1
  /* InstantiationType.Delayed */
);

// out-build/vs/workbench/services/banner/browser/bannerService.js
var $jVb = $Qk("bannerService");

// out-build/vs/workbench/browser/parts/banner/bannerPart.js
var $kVb = class $kVb2 extends Part {
  get minimumHeight() {
    return this.y ? this.height : 0;
  }
  get maximumHeight() {
    return this.y ? this.height : 0;
  }
  get onDidChange() {
    return this.a.event;
  }
  constructor(themeService, layoutService, storageService, eb, fb) {
    super("workbench.parts.banner", { hasTitle: false }, themeService, storageService, layoutService);
    this.eb = eb;
    this.fb = fb;
    this.height = 26;
    this.minimumWidth = 0;
    this.maximumWidth = Number.POSITIVE_INFINITY;
    this.a = this.B(new $ze());
    this.y = false;
    this.db = -1;
    this.c = this.fb.createInstance($Q_, {});
  }
  Q(parent) {
    this.element = parent;
    this.element.tabIndex = 0;
    this.B($_i(this.element, $7j.FOCUS, () => {
      if (this.db !== -1) {
        this.ib();
      }
    }));
    const scopedContextKeyService = this.B(this.eb.createScoped(this.element));
    $9pb.bindTo(scopedContextKeyService).set(true);
    return this.element;
  }
  hb(item) {
    this.lb(false);
    $$i(this.element);
    if (typeof item.onClose === "function") {
      item.onClose();
    }
    this.b = void 0;
  }
  ib() {
    const length = this.b?.actions?.length ?? 0;
    if (this.db < length) {
      const actionLink = this.cb?.children[this.db];
      if ($Uj(actionLink)) {
        this.bb?.setFocusable(false);
        actionLink.focus();
      }
    } else {
      this.bb?.focus(0);
    }
  }
  jb(item) {
    if (item.ariaLabel) {
      return item.ariaLabel;
    }
    if (typeof item.message === "string") {
      return item.message;
    }
    return void 0;
  }
  kb(message) {
    if (typeof message === "string") {
      const element = $("span");
      element.innerText = message;
      return element;
    }
    return this.c.render(message).element;
  }
  lb(visible) {
    if (visible !== this.y) {
      this.y = visible;
      this.db = -1;
      this.M.setPartHidden(
        !visible,
        "workbench.parts.banner"
        /* Parts.BANNER_PART */
      );
      this.a.fire(void 0);
    }
  }
  focus() {
    this.db = -1;
    this.element.focus();
  }
  focusNextAction() {
    const length = this.b?.actions?.length ?? 0;
    this.db = this.db < length ? this.db + 1 : 0;
    this.ib();
  }
  focusPreviousAction() {
    const length = this.b?.actions?.length ?? 0;
    this.db = this.db > 0 ? this.db - 1 : length;
    this.ib();
  }
  hide(id2) {
    if (this.b?.id !== id2) {
      return;
    }
    this.lb(false);
  }
  show(item) {
    if (item.id === this.b?.id) {
      this.lb(true);
      return;
    }
    $$i(this.element);
    const ariaLabel = this.jb(item);
    if (ariaLabel) {
      this.element.setAttribute("aria-label", ariaLabel);
    }
    const iconContainer = $bk(this.element, $("div.icon-container"));
    iconContainer.setAttribute("aria-hidden", "true");
    if (ThemeIcon.isThemeIcon(item.icon)) {
      iconContainer.appendChild($(`div${ThemeIcon.asCSSSelector(item.icon)}`));
    } else {
      iconContainer.classList.add("custom-icon");
      if (URI.isUri(item.icon)) {
        iconContainer.style.backgroundImage = $5Z(item.icon);
      }
    }
    const messageContainer = $bk(this.element, $("div.message-container"));
    messageContainer.setAttribute("aria-hidden", "true");
    messageContainer.appendChild(this.kb(item.message));
    this.cb = $bk(this.element, $("div.message-actions-container"));
    if (item.actions) {
      for (const action of item.actions) {
        this.B(this.fb.createInstance(Link2, this.cb, { ...action, tabIndex: -1 }, {}));
      }
    }
    const actionBarContainer = $bk(this.element, $("div.action-container"));
    this.bb = this.B(new $LZ(actionBarContainer));
    const label3 = item.closeLabel ?? "Close Banner";
    const closeAction = this.B(new $Um("banner.close", label3, ThemeIcon.asClassName($_r), true, () => this.hb(item)));
    this.bb.push(closeAction, { icon: true, label: false });
    this.bb.setFocusable(false);
    this.lb(true);
    this.b = item;
  }
  toJSON() {
    return {
      type: "workbench.parts.banner"
      /* Parts.BANNER_PART */
    };
  }
};
$kVb = __decorate([
  __param(0, $gs),
  __param(1, $Vlb),
  __param(2, $jv),
  __param(3, $on),
  __param(4, $Pk)
], $kVb);
$SC(
  $jVb,
  $kVb,
  0
  /* InstantiationType.Eager */
);
$0I.registerCommandAndKeybindingRule({
  id: "workbench.banner.focusBanner",
  weight: 200,
  primary: 9,
  when: $9pb,
  handler: (accessor) => {
    const bannerService = accessor.get($jVb);
    bannerService.focus();
  }
});
$0I.registerCommandAndKeybindingRule({
  id: "workbench.banner.focusNextAction",
  weight: 200,
  primary: 17,
  secondary: [
    18
    /* KeyCode.DownArrow */
  ],
  when: $9pb,
  handler: (accessor) => {
    const bannerService = accessor.get($jVb);
    bannerService.focusNextAction();
  }
});
$0I.registerCommandAndKeybindingRule({
  id: "workbench.banner.focusPreviousAction",
  weight: 200,
  primary: 15,
  secondary: [
    16
    /* KeyCode.UpArrow */
  ],
  when: $9pb,
  handler: (accessor) => {
    const bannerService = accessor.get($jVb);
    bannerService.focusPreviousAction();
  }
});
var FocusBannerAction = class _FocusBannerAction extends $gJ {
  static {
    this.ID = "workbench.action.focusBanner";
  }
  static {
    this.LABEL = localize2(3087, "Focus Banner");
  }
  constructor() {
    super({
      id: _FocusBannerAction.ID,
      title: _FocusBannerAction.LABEL,
      category: $qn.View,
      f1: true
    });
  }
  async run(accessor) {
    const layoutService = accessor.get($Vlb);
    layoutService.focusPart(
      "workbench.parts.banner"
      /* Parts.BANNER_PART */
    );
  }
};
$hJ(FocusBannerAction);

// out-build/vs/workbench/browser/parts/statusbar/statusbarActions.js
var $4qb = class extends $Um {
  constructor(id2, label3, a) {
    super(id2, label3, void 0, true);
    this.a = a;
    this.checked = !a.isHidden(id2);
  }
  async run() {
    if (this.a.isHidden(this.id)) {
      this.a.show(this.id);
    } else {
      this.a.hide(this.id);
    }
  }
};
var $5qb = class extends $Um {
  constructor(id2, name, a) {
    super(id2, localize(3740, null, name), void 0, true);
    this.a = a;
  }
  async run() {
    this.a.hide(this.id);
  }
};
$0I.registerCommandAndKeybindingRule({
  id: "workbench.statusBar.focusPrevious",
  weight: 200,
  primary: 15,
  secondary: [
    16
    /* KeyCode.UpArrow */
  ],
  when: $6pb,
  handler: (accessor) => {
    const statusBarService = accessor.get($$qb);
    statusBarService.focusPreviousEntry();
  }
});
$0I.registerCommandAndKeybindingRule({
  id: "workbench.statusBar.focusNext",
  weight: 200,
  primary: 17,
  secondary: [
    18
    /* KeyCode.DownArrow */
  ],
  when: $6pb,
  handler: (accessor) => {
    const statusBarService = accessor.get($$qb);
    statusBarService.focusNextEntry();
  }
});
$0I.registerCommandAndKeybindingRule({
  id: "workbench.statusBar.focusFirst",
  weight: 200,
  primary: 14,
  when: $6pb,
  handler: (accessor) => {
    const statusBarService = accessor.get($$qb);
    statusBarService.focus(false);
    statusBarService.focusNextEntry();
  }
});
$0I.registerCommandAndKeybindingRule({
  id: "workbench.statusBar.focusLast",
  weight: 200,
  primary: 13,
  when: $6pb,
  handler: (accessor) => {
    const statusBarService = accessor.get($$qb);
    statusBarService.focus(false);
    statusBarService.focusPreviousEntry();
  }
});
$0I.registerCommandAndKeybindingRule({
  id: "workbench.statusBar.clearFocus",
  weight: 200,
  primary: 9,
  when: $6pb,
  handler: (accessor) => {
    const statusBarService = accessor.get($$qb);
    const editorService = accessor.get($mJ);
    if (statusBarService.isEntryFocused()) {
      statusBarService.focus(false);
    } else if (editorService.activeEditorPane) {
      editorService.activeEditorPane.focus();
    }
  }
});
var FocusStatusBarAction = class extends $gJ {
  constructor() {
    super({
      id: "workbench.action.focusStatusBar",
      title: localize2(3741, "Focus Status Bar"),
      category: $qn.View,
      f1: true
    });
  }
  async run(accessor) {
    const layoutService = accessor.get($Vlb);
    layoutService.focusPart("workbench.parts.statusbar", $Qj());
  }
};
$hJ(FocusStatusBarAction);

// out-build/vs/workbench/browser/parts/statusbar/statusbarModel.js
var $3qb = class _$3qb extends $3c {
  static {
    this.a = "workbench.statusbar.hidden";
  }
  get entries() {
    return this.c.slice(0);
  }
  get lastFocusedEntry() {
    return this.f && !this.isHidden(this.f.id) ? this.f : void 0;
  }
  constructor(h3) {
    super();
    this.h = h3;
    this.b = this.B(new $ze());
    this.onDidChangeEntryVisibility = this.b.event;
    this.c = [];
    this.g = /* @__PURE__ */ new Set();
    this.j();
    this.m();
  }
  j() {
    const hiddenRaw = this.h.get(
      _$3qb.a,
      0
      /* StorageScope.PROFILE */
    );
    if (hiddenRaw) {
      try {
        this.g = new Set(JSON.parse(hiddenRaw));
      } catch (error) {
      }
    }
  }
  m() {
    this.B(this.h.onDidChangeValue(0, _$3qb.a, this.q)(() => this.n()));
  }
  n() {
    const currentlyHidden = new Set(this.g);
    this.g.clear();
    this.j();
    const changed = /* @__PURE__ */ new Set();
    for (const id2 of currentlyHidden) {
      if (!this.g.has(id2)) {
        changed.add(id2);
      }
    }
    for (const id2 of this.g) {
      if (!currentlyHidden.has(id2)) {
        changed.add(id2);
      }
    }
    if (changed.size > 0) {
      for (const entry of this.c) {
        if (changed.has(entry.id)) {
          this.t(entry.id, true);
          changed.delete(entry.id);
        }
      }
    }
  }
  add(entry) {
    this.c.push(entry);
    this.t(entry, false);
    this.w();
    this.y();
  }
  remove(entry) {
    const index = this.c.indexOf(entry);
    if (index >= 0) {
      this.c.splice(index, 1);
      if (this.c.some((otherEntry) => $_qb(otherEntry.priority.primary) && otherEntry.priority.primary.id === entry.id)) {
        this.w();
      }
      this.y();
    }
  }
  isHidden(id2) {
    return this.g.has(id2);
  }
  hide(id2) {
    if (!this.g.has(id2)) {
      this.g.add(id2);
      this.t(id2, true);
      this.u();
    }
  }
  show(id2) {
    if (this.g.has(id2)) {
      this.g.delete(id2);
      this.t(id2, true);
      this.u();
    }
  }
  findEntry(container2) {
    return this.c.find((entry) => entry.container === container2);
  }
  getEntries(alignment) {
    return this.c.filter((entry) => entry.alignment === alignment);
  }
  focusNextEntry() {
    this.s(1, 0);
  }
  focusPreviousEntry() {
    this.s(-1, this.entries.length - 1);
  }
  isEntryFocused() {
    return !!this.r();
  }
  r() {
    return this.c.find((entry) => $Nj(entry.container));
  }
  s(delta, restartPosition) {
    const getVisibleEntry = (start) => {
      let indexToFocus = start;
      let entry2 = indexToFocus >= 0 && indexToFocus < this.c.length ? this.c[indexToFocus] : void 0;
      while (entry2 && this.isHidden(entry2.id)) {
        indexToFocus += delta;
        entry2 = indexToFocus >= 0 && indexToFocus < this.c.length ? this.c[indexToFocus] : void 0;
      }
      return entry2;
    };
    const focused = this.r();
    if (focused) {
      const entry2 = getVisibleEntry(this.c.indexOf(focused) + delta);
      if (entry2) {
        this.f = entry2;
        entry2.labelContainer.focus();
        return;
      }
    }
    const entry = getVisibleEntry(restartPosition);
    if (entry) {
      this.f = entry;
      entry.labelContainer.focus();
    }
  }
  t(arg1, trigger) {
    if (typeof arg1 === "string") {
      const id2 = arg1;
      for (const entry of this.c) {
        if (entry.id === id2) {
          this.t(entry, trigger);
        }
      }
    } else {
      const entry = arg1;
      const isHidden = this.isHidden(entry.id);
      if (isHidden) {
        $ik(entry.container);
      } else {
        $hk(entry.container);
      }
      if (trigger) {
        this.b.fire({ id: entry.id, visible: !isHidden });
      }
      this.y();
    }
  }
  u() {
    if (this.g.size > 0) {
      this.h.store(
        _$3qb.a,
        JSON.stringify(Array.from(this.g.values())),
        0,
        0
        /* StorageTarget.USER */
      );
    } else {
      this.h.remove(
        _$3qb.a,
        0
        /* StorageScope.PROFILE */
      );
    }
  }
  w() {
    const mapEntryWithNumberedPriorityToIndex = /* @__PURE__ */ new Map();
    const mapEntryWithRelativePriority = /* @__PURE__ */ new Map();
    for (let i2 = 0; i2 < this.c.length; i2++) {
      const entry = this.c[i2];
      if (typeof entry.priority.primary === "number") {
        mapEntryWithNumberedPriorityToIndex.set(entry, i2);
      } else {
        const referenceEntryId = entry.priority.primary.id;
        let entries2 = mapEntryWithRelativePriority.get(referenceEntryId);
        if (!entries2) {
          for (const relativeEntries of mapEntryWithRelativePriority.values()) {
            if (relativeEntries.has(referenceEntryId)) {
              entries2 = relativeEntries;
              break;
            }
          }
          if (!entries2) {
            entries2 = /* @__PURE__ */ new Map();
            mapEntryWithRelativePriority.set(referenceEntryId, entries2);
          }
        }
        entries2.set(entry.id, entry);
      }
    }
    const sortedEntriesWithNumberedPriority = Array.from(mapEntryWithNumberedPriorityToIndex.keys());
    sortedEntriesWithNumberedPriority.sort((entryA, entryB) => {
      if (entryA.alignment === entryB.alignment) {
        if (entryA.priority.primary !== entryB.priority.primary) {
          return Number(entryB.priority.primary) - Number(entryA.priority.primary);
        }
        if (entryA.priority.secondary !== entryB.priority.secondary) {
          return entryB.priority.secondary - entryA.priority.secondary;
        }
        return mapEntryWithNumberedPriorityToIndex.get(entryA) - mapEntryWithNumberedPriorityToIndex.get(entryB);
      }
      if (entryA.alignment === 0) {
        return -1;
      }
      if (entryB.alignment === 0) {
        return 1;
      }
      return 0;
    });
    let sortedEntries;
    if (mapEntryWithRelativePriority.size > 0) {
      sortedEntries = [];
      for (const entry of sortedEntriesWithNumberedPriority) {
        const relativeEntriesMap = mapEntryWithRelativePriority.get(entry.id);
        const relativeEntries = relativeEntriesMap ? Array.from(relativeEntriesMap.values()) : void 0;
        if (relativeEntries) {
          sortedEntries.push(...relativeEntries.filter(
            (entry2) => $_qb(entry2.priority.primary) && entry2.priority.primary.alignment === 0
            /* StatusbarAlignment.LEFT */
          ));
        }
        sortedEntries.push(entry);
        if (relativeEntries) {
          sortedEntries.push(...relativeEntries.filter(
            (entry2) => $_qb(entry2.priority.primary) && entry2.priority.primary.alignment === 1
            /* StatusbarAlignment.RIGHT */
          ));
        }
        mapEntryWithRelativePriority.delete(entry.id);
      }
      for (const [, entries2] of mapEntryWithRelativePriority) {
        sortedEntries.push(...entries2.values());
      }
    } else {
      sortedEntries = sortedEntriesWithNumberedPriority;
    }
    this.c = sortedEntries;
  }
  y() {
    this.z(this.getEntries(
      0
      /* StatusbarAlignment.LEFT */
    ));
    this.z(this.getEntries(
      1
      /* StatusbarAlignment.RIGHT */
    ));
  }
  z(entries2) {
    let firstVisibleItem;
    let lastVisibleItem;
    for (const entry of entries2) {
      entry.container.classList.remove("first-visible-item", "last-visible-item");
      const isVisible = !this.isHidden(entry.id);
      if (isVisible) {
        if (!firstVisibleItem) {
          firstVisibleItem = entry;
        }
        lastVisibleItem = entry;
      }
    }
    firstVisibleItem?.container.classList.add("first-visible-item");
    lastVisibleItem?.container.classList.add("last-visible-item");
  }
};

// out-build/vs/workbench/browser/parts/statusbar/statusbarItem.js
var $6qb = class $6qb2 extends $3c {
  get name() {
    return $Kg(this.b).name;
  }
  get hasCommand() {
    return typeof this.b?.command !== "undefined";
  }
  constructor(n, entry, r2, s, t, u, w, y) {
    super();
    this.n = n;
    this.r = r2;
    this.s = s;
    this.t = t;
    this.u = u;
    this.w = w;
    this.y = y;
    this.b = void 0;
    this.c = this.B(new $4c());
    this.f = this.B(new $4c());
    this.g = this.B(new $4c());
    this.h = this.B(new $4c());
    this.j = this.B(new $4c());
    this.m = void 0;
    this.labelContainer = document.createElement("a");
    this.labelContainer.tabIndex = -1;
    this.labelContainer.setAttribute("role", "button");
    this.labelContainer.className = "statusbar-item-label";
    this.B($mZ.addTarget(this.labelContainer));
    this.a = this.B(new StatusBarCodiconLabel(this.labelContainer));
    this.n.appendChild(this.labelContainer);
    this.beakContainer = document.createElement("div");
    this.beakContainer.className = "status-bar-item-beak-container";
    this.n.appendChild(this.beakContainer);
    this.update(entry);
  }
  update(entry) {
    this.a.showProgress = entry.showProgress ?? false;
    if (!this.b || entry.text !== this.b.text) {
      this.a.text = entry.text;
      if (entry.text) {
        $hk(this.labelContainer);
      } else {
        $ik(this.labelContainer);
      }
    }
    if (!this.b || entry.ariaLabel !== this.b.ariaLabel) {
      this.n.setAttribute("aria-label", entry.ariaLabel);
      this.labelContainer.setAttribute("aria-label", entry.ariaLabel);
    }
    if (!this.b || entry.role !== this.b.role) {
      this.labelContainer.setAttribute("role", entry.role || "button");
    }
    if (!this.b || !this.z(this.b, entry)) {
      const hoverContents = $dm(entry.tooltip) ? { markdown: entry.tooltip, markdownNotSupportedFallback: void 0 } : entry.tooltip;
      if (this.m) {
        this.m.update(hoverContents);
      } else {
        this.m = this.B(this.t.setupManagedHover(this.r, this.n, hoverContents));
      }
    }
    if (!this.b || entry.command !== this.b.command) {
      this.g.clear();
      this.h.clear();
      this.j.clear();
      const command4 = entry.command;
      if (command4 && (command4 !== $brb || this.m)) {
        this.g.value = $_i(this.labelContainer, $7j.CLICK, () => this.C(command4));
        this.h.value = $_i(this.labelContainer, EventType.Tap, () => this.C(command4));
        this.j.value = $_i(this.labelContainer, $7j.KEY_DOWN, (e) => {
          const event = new $if(e);
          if (event.equals(
            10
            /* KeyCode.Space */
          ) || event.equals(
            3
            /* KeyCode.Enter */
          )) {
            $9j.stop(e);
            this.C(command4);
          } else if (event.equals(
            9
            /* KeyCode.Escape */
          ) || event.equals(
            15
            /* KeyCode.LeftArrow */
          ) || event.equals(
            17
            /* KeyCode.RightArrow */
          )) {
            $9j.stop(e);
            this.m?.hide();
          }
        });
        this.labelContainer.classList.remove("disabled");
      } else {
        this.labelContainer.classList.add("disabled");
      }
    }
    if (!this.b || entry.showBeak !== this.b.showBeak) {
      if (entry.showBeak) {
        this.n.classList.add("has-beak");
      } else {
        this.n.classList.remove("has-beak");
      }
    }
    const hasBackgroundColor = !!entry.backgroundColor || entry.kind && entry.kind !== "standard";
    if (!this.b || entry.kind !== this.b.kind) {
      for (const kind of $crb) {
        this.n.classList.remove(`${kind}-kind`);
      }
      if (entry.kind && entry.kind !== "standard") {
        this.n.classList.add(`${entry.kind}-kind`);
      }
      this.n.classList.toggle("has-background-color", hasBackgroundColor);
    }
    if (!this.b || entry.color !== this.b.color) {
      this.D(this.labelContainer, entry.color);
    }
    if (!this.b || entry.backgroundColor !== this.b.backgroundColor) {
      this.n.classList.toggle("has-background-color", hasBackgroundColor);
      this.D(this.n, entry.backgroundColor, true);
    }
    this.b = entry;
  }
  z({ tooltip }, { tooltip: otherTooltip }) {
    if (tooltip === void 0) {
      return otherTooltip === void 0;
    }
    if ($dm(tooltip)) {
      return $dm(otherTooltip) && $em(tooltip, otherTooltip);
    }
    return tooltip === otherTooltip;
  }
  async C(command4) {
    if (command4 === $brb) {
      this.m?.show(
        true
        /* focus */
      );
    } else {
      const id2 = typeof command4 === "string" ? command4 : command4.id;
      const args2 = typeof command4 === "string" ? [] : command4.arguments ?? [];
      this.w.publicLog2("workbenchActionExecuted", { id: id2, from: "status bar" });
      try {
        await this.s.executeCommand(id2, ...args2);
      } catch (error) {
        this.u.error($1m(error));
      }
    }
  }
  D(container2, color2, isBackground) {
    let colorResult = void 0;
    if (isBackground) {
      this.f.clear();
    } else {
      this.c.clear();
    }
    if (color2) {
      if (isThemeColor(color2)) {
        colorResult = this.y.getColorTheme().getColor(color2.id)?.toString();
        const listener = this.y.onDidColorThemeChange((theme) => {
          const colorValue = theme.getColor(color2.id)?.toString();
          if (isBackground) {
            container2.style.backgroundColor = colorValue ?? "";
          } else {
            container2.style.color = colorValue ?? "";
          }
        });
        if (isBackground) {
          this.f.value = listener;
        } else {
          this.c.value = listener;
        }
      } else {
        colorResult = color2;
      }
    }
    if (isBackground) {
      container2.style.backgroundColor = colorResult ?? "";
    } else {
      container2.style.color = colorResult ?? "";
    }
  }
};
$6qb = __decorate([
  __param(3, $sn),
  __param(4, $5$),
  __param(5, $PJ),
  __param(6, $zv),
  __param(7, $gs)
], $6qb);
var StatusBarCodiconLabel = class extends $U2 {
  constructor(g) {
    super(g);
    this.g = g;
    this.c = $C1($cs);
    this.d = "";
    this.f = false;
  }
  set showProgress(showProgress) {
    if (this.f !== showProgress) {
      this.f = showProgress;
      this.c = $C1(showProgress === "syncing" ? $cs : $ds);
      this.text = this.d;
    }
  }
  set text(text2) {
    if (this.f) {
      if (this.g.firstChild !== this.c) {
        this.g.appendChild(this.c);
      }
      for (const node of Array.from(this.g.childNodes)) {
        if (node !== this.c) {
          node.remove();
        }
      }
      let textContent = text2 ?? "";
      if (textContent) {
        textContent = `\xA0${textContent}`;
      }
      $bk(this.g, ...$B1(textContent));
    } else {
      super.text = text2;
    }
  }
};

// out-build/vs/workbench/browser/parts/statusbar/statusbarPart.js
var StatusbarPart_1;
var $8qb_1;
var StatusbarPart = class StatusbarPart2 extends Part {
  static {
    StatusbarPart_1 = this;
  }
  static {
    this.HEIGHT = 22;
  }
  constructor(id2, jb, themeService, kb, lb, layoutService, mb, nb) {
    super(id2, { hasTitle: false }, themeService, lb, layoutService);
    this.jb = jb;
    this.kb = kb;
    this.lb = lb;
    this.mb = mb;
    this.nb = nb;
    this.minimumWidth = 0;
    this.maximumWidth = Number.POSITIVE_INFINITY;
    this.minimumHeight = StatusbarPart_1.HEIGHT;
    this.maximumHeight = StatusbarPart_1.HEIGHT;
    this.y = [];
    this.$ = this.B(new $3qb(this.lb));
    this.onDidChangeEntryVisibility = this.$.onDidChangeEntryVisibility;
    this.bb = this.B(new $ze());
    this.onWillDispose = this.bb.event;
    this.cb = this.B(new $ze());
    this.db = /* @__PURE__ */ new Map();
    this.gb = this.B(this.jb.createInstance($6$, "element", true, (_, focus) => ({
      persistence: {
        hideOnKeyDown: true,
        sticky: focus
      }
    })));
    this.hb = this.B(new $4c());
    this.ib = /* @__PURE__ */ new Set();
    this.ob();
  }
  ob() {
    this.B(this.onDidChangeEntryVisibility(() => this.yb()));
    this.B(this.kb.onDidChangeWorkbenchState(() => this.updateStyles()));
  }
  overrideEntry(id2, override) {
    this.db.set(id2, override);
    this.cb.fire(id2);
    return $1c(() => {
      const currentOverride = this.db.get(id2);
      if (currentOverride === override) {
        this.db.delete(id2);
        this.cb.fire(id2);
      }
    });
  }
  pb(entry, id2) {
    const override = this.db.get(id2);
    if (override) {
      entry = { ...entry, ...override };
    }
    return entry;
  }
  addEntry(entry, id2, alignment, priorityOrLocation = 0) {
    let priority;
    if ($arb(priorityOrLocation)) {
      priority = priorityOrLocation;
    } else {
      priority = {
        primary: priorityOrLocation,
        secondary: $Xi(id2)
        // derive from identifier to accomplish uniqueness
      };
    }
    if (!this.element) {
      return this.qb(entry, id2, alignment, priority);
    }
    return this.rb(entry, id2, alignment, priority);
  }
  qb(entry, id2, alignment, priority) {
    const pendingEntry = { entry, id: id2, alignment, priority };
    this.y.push(pendingEntry);
    const accessor = {
      update: (entry2) => {
        if (pendingEntry.accessor) {
          pendingEntry.accessor.update(entry2);
        } else {
          pendingEntry.entry = entry2;
        }
      },
      dispose: () => {
        if (pendingEntry.accessor) {
          pendingEntry.accessor.dispose();
        } else {
          this.y = this.y.filter((entry2) => entry2 !== pendingEntry);
        }
      }
    };
    return accessor;
  }
  rb(entry, id2, alignment, priority) {
    const disposables = new $2c();
    const itemContainer = this.sb(id2, alignment);
    const item = disposables.add(this.jb.createInstance($6qb, itemContainer, this.pb(entry, id2), this.gb));
    const viewModelEntry = new class {
      constructor() {
        this.id = id2;
        this.alignment = alignment;
        this.priority = priority;
        this.container = itemContainer;
        this.labelContainer = item.labelContainer;
      }
      get name() {
        return item.name;
      }
      get hasCommand() {
        return item.hasCommand;
      }
    }();
    const { needsFullRefresh } = this.tb(viewModelEntry, true);
    if (needsFullRefresh) {
      this.wb();
    } else {
      this.xb(viewModelEntry);
    }
    let lastEntry = entry;
    const accessor = {
      update: (entry2) => {
        lastEntry = entry2;
        item.update(this.pb(entry2, id2));
      },
      dispose: () => {
        const { needsFullRefresh: needsFullRefresh2 } = this.tb(viewModelEntry, false);
        if (needsFullRefresh2) {
          this.wb();
        } else {
          itemContainer.remove();
          this.yb();
        }
        disposables.dispose();
      }
    };
    disposables.add(this.cb.event((overrideEntryId) => {
      if (overrideEntryId === id2) {
        accessor.update(lastEntry);
      }
    }));
    return accessor;
  }
  sb(id2, alignment, ...extraClasses) {
    const itemContainer = document.createElement("div");
    itemContainer.id = id2;
    itemContainer.classList.add("statusbar-item");
    if (extraClasses) {
      itemContainer.classList.add(...extraClasses);
    }
    if (alignment === 1) {
      itemContainer.classList.add("right");
    } else {
      itemContainer.classList.add("left");
    }
    return itemContainer;
  }
  tb(entry, add) {
    const entriesBefore = this.$.entries;
    if (add) {
      this.$.add(entry);
    } else {
      this.$.remove(entry);
    }
    const entriesAfter = this.$.entries;
    if (add) {
      entriesBefore.splice(entriesAfter.indexOf(entry), 0, entry);
    } else {
      entriesBefore.splice(entriesBefore.indexOf(entry), 1);
    }
    const needsFullRefresh = !$zb(entriesBefore, entriesAfter);
    return { needsFullRefresh };
  }
  isEntryVisible(id2) {
    return !this.$.isHidden(id2);
  }
  updateEntryVisibility(id2, visible) {
    if (visible) {
      this.$.show(id2);
    } else {
      this.$.hide(id2);
    }
  }
  focusNextEntry() {
    this.$.focusNextEntry();
  }
  focusPreviousEntry() {
    this.$.focusPreviousEntry();
  }
  isEntryFocused() {
    return this.$.isEntryFocused();
  }
  focus(preserveEntryFocus = true) {
    this.getContainer()?.focus();
    const lastFocusedEntry = this.$.lastFocusedEntry;
    if (preserveEntryFocus && lastFocusedEntry) {
      setTimeout(() => lastFocusedEntry.labelContainer.focus(), 0);
    }
  }
  Q(parent) {
    this.element = parent;
    const scopedContextKeyService = this.B(this.nb.createScoped(this.element));
    $6pb.bindTo(scopedContextKeyService).set(true);
    this.eb = document.createElement("div");
    this.eb.classList.add("left-items", "items-container");
    this.element.appendChild(this.eb);
    this.element.tabIndex = 0;
    this.fb = document.createElement("div");
    this.fb.classList.add("right-items", "items-container");
    this.element.appendChild(this.fb);
    this.B($_i(parent, $7j.CONTEXT_MENU, (e) => this.zb(e)));
    this.B($mZ.addTarget(parent));
    this.B($_i(parent, EventType.Contextmenu, (e) => this.zb(e)));
    this.vb();
    return this.element;
  }
  vb() {
    this.wb();
    while (this.y.length) {
      const pending = this.y.shift();
      if (pending) {
        pending.accessor = this.addEntry(pending.entry, pending.id, pending.alignment, pending.priority.primary);
      }
    }
  }
  wb() {
    const leftItemsContainer = $Kg(this.eb);
    const rightItemsContainer = $Kg(this.fb);
    $$i(leftItemsContainer);
    $$i(rightItemsContainer);
    for (const entry of [
      ...this.$.getEntries(
        0
        /* StatusbarAlignment.LEFT */
      ),
      ...this.$.getEntries(
        1
        /* StatusbarAlignment.RIGHT */
      ).reverse()
      // reversing due to flex: row-reverse
    ]) {
      const target = entry.alignment === 0 ? leftItemsContainer : rightItemsContainer;
      target.appendChild(entry.container);
    }
    this.yb();
  }
  xb(entry) {
    const entries2 = this.$.getEntries(entry.alignment);
    if (entry.alignment === 1) {
      entries2.reverse();
    }
    const target = $Kg(entry.alignment === 0 ? this.eb : this.fb);
    const index = entries2.indexOf(entry);
    if (index + 1 === entries2.length) {
      target.appendChild(entry.container);
    } else {
      target.insertBefore(entry.container, entries2[index + 1].container);
    }
    this.yb();
  }
  yb() {
    const entries2 = this.$.entries;
    const mapIdToVisibleEntry = /* @__PURE__ */ new Map();
    for (const entry of entries2) {
      if (!this.$.isHidden(entry.id)) {
        mapIdToVisibleEntry.set(entry.id, entry);
      }
      entry.container.classList.remove("compact-left", "compact-right");
    }
    const compactEntryGroups = /* @__PURE__ */ new Map();
    for (const entry of mapIdToVisibleEntry.values()) {
      if ($_qb(entry.priority.primary) && // entry references another entry as location
      entry.priority.primary.compact) {
        const locationId = entry.priority.primary.id;
        const location3 = mapIdToVisibleEntry.get(locationId);
        if (!location3) {
          continue;
        }
        let compactEntryGroup = compactEntryGroups.get(locationId);
        if (!compactEntryGroup) {
          for (const group2 of compactEntryGroups.values()) {
            if (group2.has(locationId)) {
              compactEntryGroup = group2;
              break;
            }
          }
          if (!compactEntryGroup) {
            compactEntryGroup = /* @__PURE__ */ new Map();
            compactEntryGroups.set(locationId, compactEntryGroup);
          }
        }
        compactEntryGroup.set(entry.id, entry);
        compactEntryGroup.set(location3.id, location3);
        if (entry.priority.primary.alignment === 0) {
          location3.container.classList.add("compact-left");
          entry.container.classList.add("compact-right");
        } else {
          location3.container.classList.add("compact-right");
          entry.container.classList.add("compact-left");
        }
      }
    }
    const statusBarItemHoverBackground = this.z($$mb);
    const statusBarItemCompactHoverBackground = this.z($anb);
    this.hb.value = new $2c();
    if (statusBarItemHoverBackground && statusBarItemCompactHoverBackground && !$es(this.h.type)) {
      for (const [, compactEntryGroup] of compactEntryGroups) {
        for (const compactEntry of compactEntryGroup.values()) {
          if (!compactEntry.hasCommand) {
            continue;
          }
          this.hb.value.add($_i(compactEntry.labelContainer, $7j.MOUSE_OVER, () => {
            compactEntryGroup.forEach((compactEntry2) => compactEntry2.labelContainer.style.backgroundColor = statusBarItemHoverBackground);
            compactEntry.labelContainer.style.backgroundColor = statusBarItemCompactHoverBackground;
          }));
          this.hb.value.add($_i(compactEntry.labelContainer, $7j.MOUSE_OUT, () => {
            compactEntryGroup.forEach((compactEntry2) => compactEntry2.labelContainer.style.backgroundColor = "");
          }));
        }
      }
    }
  }
  zb(e) {
    $9j.stop(e, true);
    const event = new $lf(getWindow(this.element), e);
    let actions = void 0;
    this.mb.showContextMenu({
      getAnchor: () => event,
      getActions: () => {
        actions = this.Ab(event);
        return actions;
      },
      onHide: () => {
        if (actions) {
          $Yc(actions);
        }
      }
    });
  }
  Ab(event) {
    const actions = [];
    actions.push($Zm({ id: $Pqb.ID, label: localize(3742, null), run: () => this.jb.invokeFunction((accessor) => new $Pqb().run(accessor)) }));
    actions.push(new $Wm());
    const handledEntries = /* @__PURE__ */ new Set();
    for (const entry of this.$.entries) {
      if (!handledEntries.has(entry.id)) {
        actions.push(new $4qb(entry.id, entry.name, this.$));
        handledEntries.add(entry.id);
      }
    }
    let statusEntryUnderMouse = void 0;
    for (let element = event.target; element; element = element.parentElement) {
      const entry = this.$.findEntry(element);
      if (entry) {
        statusEntryUnderMouse = entry;
        break;
      }
    }
    if (statusEntryUnderMouse) {
      actions.push(new $Wm());
      actions.push(new $5qb(statusEntryUnderMouse.id, statusEntryUnderMouse.name, this.$));
    }
    return actions;
  }
  updateStyles() {
    super.updateStyles();
    const container2 = $Kg(this.getContainer());
    const styleOverride = [...this.ib].sort((a, b) => a.priority - b.priority)[0];
    const backgroundColor = this.z(styleOverride?.background ?? (this.kb.getWorkbenchState() !== 1 ? $4mb : $5mb)) || "";
    container2.style.backgroundColor = backgroundColor;
    const foregroundColor = this.z(styleOverride?.foreground ?? (this.kb.getWorkbenchState() !== 1 ? $2mb : $3mb)) || "";
    container2.style.color = foregroundColor;
    const itemBorderColor = this.z($0mb);
    const borderColor = this.z(styleOverride?.border ?? (this.kb.getWorkbenchState() !== 1 ? $6mb : $8mb)) || this.z($ko);
    if (borderColor) {
      container2.classList.add("status-border-top");
      container2.style.setProperty("--status-border-top-color", borderColor);
    } else {
      container2.classList.remove("status-border-top");
      container2.style.removeProperty("--status-border-top-color");
    }
    const statusBarFocusColor = this.z($7mb);
    if (!this.c) {
      this.c = $VZ(container2);
    }
    this.c.textContent = `

				/* Status bar focus outline */
				.monaco-workbench .part.statusbar:focus {
					outline-color: ${statusBarFocusColor};
				}

				/* Status bar item focus outline */
				.monaco-workbench .part.statusbar > .items-container > .statusbar-item a:focus-visible {
					outline: 1px solid ${this.z($lo) ?? itemBorderColor};
					outline-offset: ${borderColor ? "-2px" : "-1px"};
				}

				/* Notification Beak */
				.monaco-workbench .part.statusbar > .items-container > .statusbar-item.has-beak > .status-bar-item-beak-container:before {
					border-bottom-color: ${backgroundColor};
				}
			`;
  }
  layout(width2, height, top2, left) {
    super.layout(width2, height, top2, left);
    super.Z(width2, height);
  }
  overrideStyle(style) {
    this.ib.add(style);
    this.updateStyles();
    return $1c(() => {
      this.ib.delete(style);
      this.updateStyles();
    });
  }
  toJSON() {
    return {
      type: "workbench.parts.statusbar"
      /* Parts.STATUSBAR_PART */
    };
  }
  dispose() {
    this.bb.fire();
    super.dispose();
  }
};
StatusbarPart = StatusbarPart_1 = __decorate([
  __param(1, $Pk),
  __param(2, $gs),
  __param(3, $Zk),
  __param(4, $jv),
  __param(5, $Vlb),
  __param(6, $50),
  __param(7, $on)
], StatusbarPart);
var $7qb = class $7qb2 extends StatusbarPart {
  constructor(instantiationService, themeService, contextService, storageService, layoutService, contextMenuService, contextKeyService) {
    super("workbench.parts.statusbar", instantiationService, themeService, contextService, storageService, layoutService, contextMenuService, contextKeyService);
  }
};
$7qb = __decorate([
  __param(0, $Pk),
  __param(1, $gs),
  __param(2, $Zk),
  __param(3, $jv),
  __param(4, $Vlb),
  __param(5, $50),
  __param(6, $on)
], $7qb);
var $8qb = class $8qb2 extends StatusbarPart {
  static {
    $8qb_1 = this;
  }
  static {
    this.Bb = 1;
  }
  constructor(container2, instantiationService, themeService, contextService, storageService, layoutService, contextMenuService, contextKeyService) {
    const id2 = $8qb_1.Bb++;
    super(`workbench.parts.auxiliaryStatus.${id2}`, instantiationService, themeService, contextService, storageService, layoutService, contextMenuService, contextKeyService);
    this.container = container2;
    this.height = StatusbarPart.HEIGHT;
  }
};
$8qb = $8qb_1 = __decorate([
  __param(1, $Pk),
  __param(2, $gs),
  __param(3, $Zk),
  __param(4, $jv),
  __param(5, $Vlb),
  __param(6, $50),
  __param(7, $on)
], $8qb);
var $9qb = class $9qb2 extends $3lb {
  constructor(r2, storageService, themeService) {
    super("workbench.statusBarService", themeService, storageService);
    this.r = r2;
    this.mainPart = this.B(this.r.createInstance($7qb));
    this.c = this.B(new $ze());
    this.m = this.c.event;
    this.onDidChangeEntryVisibility = this.mainPart.onDidChangeEntryVisibility;
    this.B(this.registerPart(this.mainPart));
  }
  //#region Auxiliary Statusbar Parts
  createAuxiliaryStatusbarPart(container2) {
    const statusbarPartContainer = document.createElement("footer");
    statusbarPartContainer.classList.add("part", "statusbar");
    statusbarPartContainer.setAttribute("role", "status");
    statusbarPartContainer.style.position = "relative";
    statusbarPartContainer.setAttribute("aria-live", "off");
    statusbarPartContainer.setAttribute("tabindex", "0");
    container2.appendChild(statusbarPartContainer);
    const statusbarPart = this.r.createInstance($8qb, statusbarPartContainer);
    const disposable = this.registerPart(statusbarPart);
    statusbarPart.create(statusbarPartContainer);
    Event2.once(statusbarPart.onWillDispose)(() => disposable.dispose());
    this.c.fire(statusbarPart);
    return statusbarPart;
  }
  createScoped(statusbarEntryContainer, disposables) {
    return disposables.add(this.r.createInstance($0qb, statusbarEntryContainer));
  }
  addEntry(entry, id2, alignment, priorityOrLocation = 0) {
    if (entry.showInAllWindows) {
      return this.s(entry, id2, alignment, priorityOrLocation);
    }
    return this.mainPart.addEntry(entry, id2, alignment, priorityOrLocation);
  }
  s(entry, id2, alignment, priorityOrLocation = 0) {
    const entryDisposables = new $2c();
    const accessors = /* @__PURE__ */ new Set();
    function addEntry(part) {
      const partDisposables = new $2c();
      partDisposables.add(part.onWillDispose(() => partDisposables.dispose()));
      const accessor = partDisposables.add(part.addEntry(entry, id2, alignment, priorityOrLocation));
      accessors.add(accessor);
      partDisposables.add($1c(() => accessors.delete(accessor)));
      entryDisposables.add(partDisposables);
      partDisposables.add($1c(() => entryDisposables.delete(partDisposables)));
    }
    for (const part of this.parts) {
      addEntry(part);
    }
    entryDisposables.add(this.m((part) => addEntry(part)));
    return {
      update: (entry2) => {
        for (const update of accessors) {
          update.update(entry2);
        }
      },
      dispose: () => entryDisposables.dispose()
    };
  }
  isEntryVisible(id2) {
    return this.mainPart.isEntryVisible(id2);
  }
  updateEntryVisibility(id2, visible) {
    for (const part of this.parts) {
      part.updateEntryVisibility(id2, visible);
    }
  }
  overrideEntry(id2, override) {
    const disposables = new $2c();
    for (const part of this.parts) {
      disposables.add(part.overrideEntry(id2, override));
    }
    return disposables;
  }
  focus(preserveEntryFocus) {
    this.activePart.focus(preserveEntryFocus);
  }
  focusNextEntry() {
    this.activePart.focusNextEntry();
  }
  focusPreviousEntry() {
    this.activePart.focusPreviousEntry();
  }
  isEntryFocused() {
    return this.activePart.isEntryFocused();
  }
  overrideStyle(style) {
    const disposables = new $2c();
    for (const part of this.parts) {
      disposables.add(part.overrideStyle(style));
    }
    return disposables;
  }
};
$9qb = __decorate([
  __param(0, $Pk),
  __param(1, $jv),
  __param(2, $gs)
], $9qb);
var $0qb = class $0qb2 extends $3c {
  constructor(c, f) {
    super();
    this.c = c;
    this.f = f;
    this.onDidChangeEntryVisibility = this.c.onDidChangeEntryVisibility;
  }
  createAuxiliaryStatusbarPart(container2) {
    return this.f.createAuxiliaryStatusbarPart(container2);
  }
  createScoped(statusbarEntryContainer, disposables) {
    return this.f.createScoped(statusbarEntryContainer, disposables);
  }
  getPart() {
    return this.c;
  }
  addEntry(entry, id2, alignment, priorityOrLocation = 0) {
    return this.c.addEntry(entry, id2, alignment, priorityOrLocation);
  }
  isEntryVisible(id2) {
    return this.c.isEntryVisible(id2);
  }
  updateEntryVisibility(id2, visible) {
    this.c.updateEntryVisibility(id2, visible);
  }
  overrideEntry(id2, override) {
    return this.c.overrideEntry(id2, override);
  }
  focus(preserveEntryFocus) {
    this.c.focus(preserveEntryFocus);
  }
  focusNextEntry() {
    this.c.focusNextEntry();
  }
  focusPreviousEntry() {
    this.c.focusPreviousEntry();
  }
  isEntryFocused() {
    return this.c.isEntryFocused();
  }
  overrideStyle(style) {
    return this.c.overrideStyle(style);
  }
};
$0qb = __decorate([
  __param(1, $$qb)
], $0qb);
$SC(
  $$qb,
  $9qb,
  0
  /* InstantiationType.Eager */
);

// out-build/vs/platform/actions/common/menuResetAction.js
var $lVb = class extends $gJ {
  constructor() {
    super({
      id: "menu.resetHiddenStates",
      title: localize2(1679, "Reset All Menus"),
      category: $qn.View,
      f1: true
    });
  }
  run(accessor) {
    accessor.get($cJ).resetHiddenStates();
    accessor.get($wn).info("did RESET all menu hidden states");
  }
};

// out-build/vs/platform/actions/common/actions.contribution.js
$SC(
  $cJ,
  $Y$,
  1
  /* InstantiationType.Delayed */
);
$hJ($lVb);

// out-build/vs/platform/undoRedo/common/undoRedoService.js
var DEBUG2 = false;
function getResourceLabel(resource) {
  return resource.scheme === Schemas.file ? resource.fsPath : resource.path;
}
var stackElementCounter = 0;
var ResourceStackElement = class {
  constructor(actual, resourceLabel, strResource, groupId, groupOrder, sourceId, sourceOrder) {
    this.id = ++stackElementCounter;
    this.type = 0;
    this.actual = actual;
    this.label = actual.label;
    this.confirmBeforeUndo = actual.confirmBeforeUndo || false;
    this.resourceLabel = resourceLabel;
    this.strResource = strResource;
    this.resourceLabels = [this.resourceLabel];
    this.strResources = [this.strResource];
    this.groupId = groupId;
    this.groupOrder = groupOrder;
    this.sourceId = sourceId;
    this.sourceOrder = sourceOrder;
    this.isValid = true;
  }
  setValid(isValid2) {
    this.isValid = isValid2;
  }
  toString() {
    return `[id:${this.id}] [group:${this.groupId}] [${this.isValid ? "  VALID" : "INVALID"}] ${this.actual.constructor.name} - ${this.actual}`;
  }
};
var RemovedResourceReason;
(function(RemovedResourceReason2) {
  RemovedResourceReason2[RemovedResourceReason2["ExternalRemoval"] = 0] = "ExternalRemoval";
  RemovedResourceReason2[RemovedResourceReason2["NoParallelUniverses"] = 1] = "NoParallelUniverses";
})(RemovedResourceReason || (RemovedResourceReason = {}));
var ResourceReasonPair = class {
  constructor(resourceLabel, reason) {
    this.resourceLabel = resourceLabel;
    this.reason = reason;
  }
};
var RemovedResources = class {
  constructor() {
    this.a = /* @__PURE__ */ new Map();
  }
  createMessage() {
    const externalRemoval = [];
    const noParallelUniverses = [];
    for (const [, element] of this.a) {
      const dest = element.reason === 0 ? externalRemoval : noParallelUniverses;
      dest.push(element.resourceLabel);
    }
    const messages = [];
    if (externalRemoval.length > 0) {
      messages.push(localize(2458, null, externalRemoval.join(", ")));
    }
    if (noParallelUniverses.length > 0) {
      messages.push(localize(2459, null, noParallelUniverses.join(", ")));
    }
    return messages.join("\n");
  }
  get size() {
    return this.a.size;
  }
  has(strResource) {
    return this.a.has(strResource);
  }
  set(strResource, value) {
    this.a.set(strResource, value);
  }
  delete(strResource) {
    return this.a.delete(strResource);
  }
};
var WorkspaceStackElement = class {
  constructor(actual, resourceLabels, strResources, groupId, groupOrder, sourceId, sourceOrder) {
    this.id = ++stackElementCounter;
    this.type = 1;
    this.actual = actual;
    this.label = actual.label;
    this.confirmBeforeUndo = actual.confirmBeforeUndo || false;
    this.resourceLabels = resourceLabels;
    this.strResources = strResources;
    this.groupId = groupId;
    this.groupOrder = groupOrder;
    this.sourceId = sourceId;
    this.sourceOrder = sourceOrder;
    this.removedResources = null;
    this.invalidatedResources = null;
  }
  canSplit() {
    return typeof this.actual.split === "function";
  }
  removeResource(resourceLabel, strResource, reason) {
    if (!this.removedResources) {
      this.removedResources = new RemovedResources();
    }
    if (!this.removedResources.has(strResource)) {
      this.removedResources.set(strResource, new ResourceReasonPair(resourceLabel, reason));
    }
  }
  setValid(resourceLabel, strResource, isValid2) {
    if (isValid2) {
      if (this.invalidatedResources) {
        this.invalidatedResources.delete(strResource);
        if (this.invalidatedResources.size === 0) {
          this.invalidatedResources = null;
        }
      }
    } else {
      if (!this.invalidatedResources) {
        this.invalidatedResources = new RemovedResources();
      }
      if (!this.invalidatedResources.has(strResource)) {
        this.invalidatedResources.set(strResource, new ResourceReasonPair(
          resourceLabel,
          0
          /* RemovedResourceReason.ExternalRemoval */
        ));
      }
    }
  }
  toString() {
    return `[id:${this.id}] [group:${this.groupId}] [${this.invalidatedResources ? "INVALID" : "  VALID"}] ${this.actual.constructor.name} - ${this.actual}`;
  }
};
var ResourceEditStack = class {
  constructor(resourceLabel, strResource) {
    this.resourceLabel = resourceLabel;
    this.a = strResource;
    this.b = [];
    this.c = [];
    this.locked = false;
    this.versionId = 1;
  }
  dispose() {
    for (const element of this.b) {
      if (element.type === 1) {
        element.removeResource(
          this.resourceLabel,
          this.a,
          0
          /* RemovedResourceReason.ExternalRemoval */
        );
      }
    }
    for (const element of this.c) {
      if (element.type === 1) {
        element.removeResource(
          this.resourceLabel,
          this.a,
          0
          /* RemovedResourceReason.ExternalRemoval */
        );
      }
    }
    this.versionId++;
  }
  toString() {
    const result = [];
    result.push(`* ${this.a}:`);
    for (let i2 = 0; i2 < this.b.length; i2++) {
      result.push(`   * [UNDO] ${this.b[i2]}`);
    }
    for (let i2 = this.c.length - 1; i2 >= 0; i2--) {
      result.push(`   * [REDO] ${this.c[i2]}`);
    }
    return result.join("\n");
  }
  flushAllElements() {
    this.b = [];
    this.c = [];
    this.versionId++;
  }
  setElementsIsValid(isValid2) {
    for (const element of this.b) {
      if (element.type === 1) {
        element.setValid(this.resourceLabel, this.a, isValid2);
      } else {
        element.setValid(isValid2);
      }
    }
    for (const element of this.c) {
      if (element.type === 1) {
        element.setValid(this.resourceLabel, this.a, isValid2);
      } else {
        element.setValid(isValid2);
      }
    }
  }
  d(element, isValid2) {
    if (element.type === 1) {
      element.setValid(this.resourceLabel, this.a, isValid2);
    } else {
      element.setValid(isValid2);
    }
  }
  setElementsValidFlag(isValid2, filter) {
    for (const element of this.b) {
      if (filter(element.actual)) {
        this.d(element, isValid2);
      }
    }
    for (const element of this.c) {
      if (filter(element.actual)) {
        this.d(element, isValid2);
      }
    }
  }
  pushElement(element) {
    for (const futureElement of this.c) {
      if (futureElement.type === 1) {
        futureElement.removeResource(
          this.resourceLabel,
          this.a,
          1
          /* RemovedResourceReason.NoParallelUniverses */
        );
      }
    }
    this.c = [];
    this.b.push(element);
    this.versionId++;
  }
  createSnapshot(resource) {
    const elements = [];
    for (let i2 = 0, len = this.b.length; i2 < len; i2++) {
      elements.push(this.b[i2].id);
    }
    for (let i2 = this.c.length - 1; i2 >= 0; i2--) {
      elements.push(this.c[i2].id);
    }
    return new $aG(resource, elements);
  }
  restoreSnapshot(snapshot) {
    const snapshotLength = snapshot.elements.length;
    let isOK = true;
    let snapshotIndex = 0;
    let removePastAfter = -1;
    for (let i2 = 0, len = this.b.length; i2 < len; i2++, snapshotIndex++) {
      const element = this.b[i2];
      if (isOK && (snapshotIndex >= snapshotLength || element.id !== snapshot.elements[snapshotIndex])) {
        isOK = false;
        removePastAfter = 0;
      }
      if (!isOK && element.type === 1) {
        element.removeResource(
          this.resourceLabel,
          this.a,
          0
          /* RemovedResourceReason.ExternalRemoval */
        );
      }
    }
    let removeFutureBefore = -1;
    for (let i2 = this.c.length - 1; i2 >= 0; i2--, snapshotIndex++) {
      const element = this.c[i2];
      if (isOK && (snapshotIndex >= snapshotLength || element.id !== snapshot.elements[snapshotIndex])) {
        isOK = false;
        removeFutureBefore = i2;
      }
      if (!isOK && element.type === 1) {
        element.removeResource(
          this.resourceLabel,
          this.a,
          0
          /* RemovedResourceReason.ExternalRemoval */
        );
      }
    }
    if (removePastAfter !== -1) {
      this.b = this.b.slice(0, removePastAfter);
    }
    if (removeFutureBefore !== -1) {
      this.c = this.c.slice(removeFutureBefore + 1);
    }
    this.versionId++;
  }
  getElements() {
    const past = [];
    const future = [];
    for (const element of this.b) {
      past.push(element.actual);
    }
    for (const element of this.c) {
      future.push(element.actual);
    }
    return { past, future };
  }
  getClosestPastElement() {
    if (this.b.length === 0) {
      return null;
    }
    return this.b[this.b.length - 1];
  }
  getSecondClosestPastElement() {
    if (this.b.length < 2) {
      return null;
    }
    return this.b[this.b.length - 2];
  }
  getClosestFutureElement() {
    if (this.c.length === 0) {
      return null;
    }
    return this.c[this.c.length - 1];
  }
  hasPastElements() {
    return this.b.length > 0;
  }
  hasFutureElements() {
    return this.c.length > 0;
  }
  splitPastWorkspaceElement(toRemove, individualMap) {
    for (let j = this.b.length - 1; j >= 0; j--) {
      if (this.b[j] === toRemove) {
        if (individualMap.has(this.a)) {
          this.b[j] = individualMap.get(this.a);
        } else {
          this.b.splice(j, 1);
        }
        break;
      }
    }
    this.versionId++;
  }
  splitFutureWorkspaceElement(toRemove, individualMap) {
    for (let j = this.c.length - 1; j >= 0; j--) {
      if (this.c[j] === toRemove) {
        if (individualMap.has(this.a)) {
          this.c[j] = individualMap.get(this.a);
        } else {
          this.c.splice(j, 1);
        }
        break;
      }
    }
    this.versionId++;
  }
  moveBackward(element) {
    this.b.pop();
    this.c.push(element);
    this.versionId++;
  }
  moveForward(element) {
    this.c.pop();
    this.b.push(element);
    this.versionId++;
  }
};
var EditStackSnapshot = class {
  constructor(editStacks) {
    this.editStacks = editStacks;
    this.a = [];
    for (let i2 = 0, len = this.editStacks.length; i2 < len; i2++) {
      this.a[i2] = this.editStacks[i2].versionId;
    }
  }
  isValid() {
    for (let i2 = 0, len = this.editStacks.length; i2 < len; i2++) {
      if (this.a[i2] !== this.editStacks[i2].versionId) {
        return false;
      }
    }
    return true;
  }
};
var missingEditStack = new ResourceEditStack("", "");
missingEditStack.locked = true;
var $mVb = class $mVb2 {
  constructor(c, d) {
    this.c = c;
    this.d = d;
    this.a = /* @__PURE__ */ new Map();
    this.b = [];
  }
  registerUriComparisonKeyComputer(scheme, uriComparisonKeyComputer) {
    this.b.push([scheme, uriComparisonKeyComputer]);
    return {
      dispose: () => {
        for (let i2 = 0, len = this.b.length; i2 < len; i2++) {
          if (this.b[i2][1] === uriComparisonKeyComputer) {
            this.b.splice(i2, 1);
            return;
          }
        }
      }
    };
  }
  getUriComparisonKey(resource) {
    for (const uriComparisonKeyComputer of this.b) {
      if (uriComparisonKeyComputer[0] === resource.scheme) {
        return uriComparisonKeyComputer[1].getComparisonKey(resource);
      }
    }
    return resource.toString();
  }
  e(label3) {
    console.log(`------------------------------------`);
    console.log(`AFTER ${label3}: `);
    const str = [];
    for (const element of this.a) {
      str.push(element[1].toString());
    }
    console.log(str.join("\n"));
  }
  pushElement(element, group2 = $bG.None, source = $cG.None) {
    if (element.type === 0) {
      const resourceLabel = getResourceLabel(element.resource);
      const strResource = this.getUriComparisonKey(element.resource);
      this.f(new ResourceStackElement(element, resourceLabel, strResource, group2.id, group2.nextOrder(), source.id, source.nextOrder()));
    } else {
      const seen = /* @__PURE__ */ new Set();
      const resourceLabels = [];
      const strResources = [];
      for (const resource of element.resources) {
        const resourceLabel = getResourceLabel(resource);
        const strResource = this.getUriComparisonKey(resource);
        if (seen.has(strResource)) {
          continue;
        }
        seen.add(strResource);
        resourceLabels.push(resourceLabel);
        strResources.push(strResource);
      }
      if (resourceLabels.length === 1) {
        this.f(new ResourceStackElement(element, resourceLabels[0], strResources[0], group2.id, group2.nextOrder(), source.id, source.nextOrder()));
      } else {
        this.f(new WorkspaceStackElement(element, resourceLabels, strResources, group2.id, group2.nextOrder(), source.id, source.nextOrder()));
      }
    }
    if (DEBUG2) {
      this.e("pushElement");
    }
  }
  f(element) {
    for (let i2 = 0, len = element.strResources.length; i2 < len; i2++) {
      const resourceLabel = element.resourceLabels[i2];
      const strResource = element.strResources[i2];
      let editStack;
      if (this.a.has(strResource)) {
        editStack = this.a.get(strResource);
      } else {
        editStack = new ResourceEditStack(resourceLabel, strResource);
        this.a.set(strResource, editStack);
      }
      editStack.pushElement(element);
    }
  }
  getLastElement(resource) {
    const strResource = this.getUriComparisonKey(resource);
    if (this.a.has(strResource)) {
      const editStack = this.a.get(strResource);
      if (editStack.hasFutureElements()) {
        return null;
      }
      const closestPastElement = editStack.getClosestPastElement();
      return closestPastElement ? closestPastElement.actual : null;
    }
    return null;
  }
  g(toRemove, ignoreResources) {
    const individualArr = toRemove.actual.split();
    const individualMap = /* @__PURE__ */ new Map();
    for (const _element of individualArr) {
      const resourceLabel = getResourceLabel(_element.resource);
      const strResource = this.getUriComparisonKey(_element.resource);
      const element = new ResourceStackElement(_element, resourceLabel, strResource, 0, 0, 0, 0);
      individualMap.set(element.strResource, element);
    }
    for (const strResource of toRemove.strResources) {
      if (ignoreResources && ignoreResources.has(strResource)) {
        continue;
      }
      const editStack = this.a.get(strResource);
      editStack.splitPastWorkspaceElement(toRemove, individualMap);
    }
  }
  h(toRemove, ignoreResources) {
    const individualArr = toRemove.actual.split();
    const individualMap = /* @__PURE__ */ new Map();
    for (const _element of individualArr) {
      const resourceLabel = getResourceLabel(_element.resource);
      const strResource = this.getUriComparisonKey(_element.resource);
      const element = new ResourceStackElement(_element, resourceLabel, strResource, 0, 0, 0, 0);
      individualMap.set(element.strResource, element);
    }
    for (const strResource of toRemove.strResources) {
      if (ignoreResources && ignoreResources.has(strResource)) {
        continue;
      }
      const editStack = this.a.get(strResource);
      editStack.splitFutureWorkspaceElement(toRemove, individualMap);
    }
  }
  removeElements(resource) {
    const strResource = typeof resource === "string" ? resource : this.getUriComparisonKey(resource);
    if (this.a.has(strResource)) {
      const editStack = this.a.get(strResource);
      editStack.dispose();
      this.a.delete(strResource);
    }
    if (DEBUG2) {
      this.e("removeElements");
    }
  }
  setElementsValidFlag(resource, isValid2, filter) {
    const strResource = this.getUriComparisonKey(resource);
    if (this.a.has(strResource)) {
      const editStack = this.a.get(strResource);
      editStack.setElementsValidFlag(isValid2, filter);
    }
    if (DEBUG2) {
      this.e("setElementsValidFlag");
    }
  }
  hasElements(resource) {
    const strResource = this.getUriComparisonKey(resource);
    if (this.a.has(strResource)) {
      const editStack = this.a.get(strResource);
      return editStack.hasPastElements() || editStack.hasFutureElements();
    }
    return false;
  }
  createSnapshot(resource) {
    const strResource = this.getUriComparisonKey(resource);
    if (this.a.has(strResource)) {
      const editStack = this.a.get(strResource);
      return editStack.createSnapshot(resource);
    }
    return new $aG(resource, []);
  }
  restoreSnapshot(snapshot) {
    const strResource = this.getUriComparisonKey(snapshot.resource);
    if (this.a.has(strResource)) {
      const editStack = this.a.get(strResource);
      editStack.restoreSnapshot(snapshot);
      if (!editStack.hasPastElements() && !editStack.hasFutureElements()) {
        editStack.dispose();
        this.a.delete(strResource);
      }
    }
    if (DEBUG2) {
      this.e("restoreSnapshot");
    }
  }
  getElements(resource) {
    const strResource = this.getUriComparisonKey(resource);
    if (this.a.has(strResource)) {
      const editStack = this.a.get(strResource);
      return editStack.getElements();
    }
    return { past: [], future: [] };
  }
  k(sourceId) {
    if (!sourceId) {
      return [null, null];
    }
    let matchedElement = null;
    let matchedStrResource = null;
    for (const [strResource, editStack] of this.a) {
      const candidate = editStack.getClosestPastElement();
      if (!candidate) {
        continue;
      }
      if (candidate.sourceId === sourceId) {
        if (!matchedElement || candidate.sourceOrder > matchedElement.sourceOrder) {
          matchedElement = candidate;
          matchedStrResource = strResource;
        }
      }
    }
    return [matchedElement, matchedStrResource];
  }
  canUndo(resourceOrSource) {
    if (resourceOrSource instanceof $cG) {
      const [, matchedStrResource] = this.k(resourceOrSource.id);
      return matchedStrResource ? true : false;
    }
    const strResource = this.getUriComparisonKey(resourceOrSource);
    if (this.a.has(strResource)) {
      const editStack = this.a.get(strResource);
      return editStack.hasPastElements();
    }
    return false;
  }
  l(err, element) {
    $gb(err);
    for (const strResource of element.strResources) {
      this.removeElements(strResource);
    }
    this.d.error(err);
  }
  m(editStackSnapshot) {
    for (const editStack of editStackSnapshot.editStacks) {
      if (editStack.locked) {
        throw new Error("Cannot acquire edit stack lock");
      }
    }
    for (const editStack of editStackSnapshot.editStacks) {
      editStack.locked = true;
    }
    return () => {
      for (const editStack of editStackSnapshot.editStacks) {
        editStack.locked = false;
      }
    };
  }
  n(element, invoke, editStackSnapshot, cleanup, continuation) {
    const releaseLocks = this.m(editStackSnapshot);
    let result;
    try {
      result = invoke();
    } catch (err) {
      releaseLocks();
      cleanup.dispose();
      return this.l(err, element);
    }
    if (result) {
      return result.then(() => {
        releaseLocks();
        cleanup.dispose();
        return continuation();
      }, (err) => {
        releaseLocks();
        cleanup.dispose();
        return this.l(err, element);
      });
    } else {
      releaseLocks();
      cleanup.dispose();
      return continuation();
    }
  }
  async o(element) {
    if (typeof element.actual.prepareUndoRedo === "undefined") {
      return $3c.None;
    }
    const result = element.actual.prepareUndoRedo();
    if (typeof result === "undefined") {
      return $3c.None;
    }
    return result;
  }
  p(element, callback) {
    if (element.actual.type !== 1 || typeof element.actual.prepareUndoRedo === "undefined") {
      return callback($3c.None);
    }
    const r2 = element.actual.prepareUndoRedo();
    if (!r2) {
      return callback($3c.None);
    }
    if ($Wc(r2)) {
      return callback(r2);
    }
    return r2.then((disposable) => {
      return callback(disposable);
    });
  }
  q(element) {
    const affectedEditStacks = [];
    for (const strResource of element.strResources) {
      affectedEditStacks.push(this.a.get(strResource) || missingEditStack);
    }
    return new EditStackSnapshot(affectedEditStacks);
  }
  s(strResource, element, ignoreResources, message) {
    if (element.canSplit()) {
      this.g(element, ignoreResources);
      this.d.warn(message);
      return new WorkspaceVerificationError(this.A(strResource, 0, true));
    } else {
      for (const strResource2 of element.strResources) {
        this.removeElements(strResource2);
      }
      this.d.warn(message);
      return new WorkspaceVerificationError();
    }
  }
  t(strResource, element, editStackSnapshot, checkInvalidatedResources) {
    if (element.removedResources) {
      return this.s(strResource, element, element.removedResources, localize(2460, null, element.label, element.removedResources.createMessage()));
    }
    if (checkInvalidatedResources && element.invalidatedResources) {
      return this.s(strResource, element, element.invalidatedResources, localize(2461, null, element.label, element.invalidatedResources.createMessage()));
    }
    const cannotUndoDueToResources = [];
    for (const editStack of editStackSnapshot.editStacks) {
      if (editStack.getClosestPastElement() !== element) {
        cannotUndoDueToResources.push(editStack.resourceLabel);
      }
    }
    if (cannotUndoDueToResources.length > 0) {
      return this.s(strResource, element, null, localize(2462, null, element.label, cannotUndoDueToResources.join(", ")));
    }
    const cannotLockDueToResources = [];
    for (const editStack of editStackSnapshot.editStacks) {
      if (editStack.locked) {
        cannotLockDueToResources.push(editStack.resourceLabel);
      }
    }
    if (cannotLockDueToResources.length > 0) {
      return this.s(strResource, element, null, localize(2463, null, element.label, cannotLockDueToResources.join(", ")));
    }
    if (!editStackSnapshot.isValid()) {
      return this.s(strResource, element, null, localize(2464, null, element.label));
    }
    return null;
  }
  u(strResource, element, undoConfirmed) {
    const affectedEditStacks = this.q(element);
    const verificationError = this.t(
      strResource,
      element,
      affectedEditStacks,
      /*invalidated resources will be checked after the prepare call*/
      false
    );
    if (verificationError) {
      return verificationError.returnValue;
    }
    return this.w(strResource, element, affectedEditStacks, undoConfirmed);
  }
  v(element) {
    if (!element.groupId) {
      return false;
    }
    for (const [, editStack] of this.a) {
      const pastElement = editStack.getClosestPastElement();
      if (!pastElement) {
        continue;
      }
      if (pastElement === element) {
        const secondPastElement = editStack.getSecondClosestPastElement();
        if (secondPastElement && secondPastElement.groupId === element.groupId) {
          return true;
        }
      }
      if (pastElement.groupId === element.groupId) {
        return true;
      }
    }
    return false;
  }
  async w(strResource, element, editStackSnapshot, undoConfirmed) {
    if (element.canSplit() && !this.v(element)) {
      let UndoChoice;
      (function(UndoChoice2) {
        UndoChoice2[UndoChoice2["All"] = 0] = "All";
        UndoChoice2[UndoChoice2["This"] = 1] = "This";
        UndoChoice2[UndoChoice2["Cancel"] = 2] = "Cancel";
      })(UndoChoice || (UndoChoice = {}));
      const { result } = await this.c.prompt({
        type: severity_default.Info,
        message: localize(2465, null, element.label),
        buttons: [
          {
            label: localize(2466, null, editStackSnapshot.editStacks.length),
            run: () => UndoChoice.All
          },
          {
            label: localize(2467, null),
            run: () => UndoChoice.This
          }
        ],
        cancelButton: {
          run: () => UndoChoice.Cancel
        }
      });
      if (result === UndoChoice.Cancel) {
        return;
      }
      if (result === UndoChoice.This) {
        this.g(element, null);
        return this.A(strResource, 0, true);
      }
      const verificationError1 = this.t(
        strResource,
        element,
        editStackSnapshot,
        /*invalidated resources will be checked after the prepare call*/
        false
      );
      if (verificationError1) {
        return verificationError1.returnValue;
      }
      undoConfirmed = true;
    }
    let cleanup;
    try {
      cleanup = await this.o(element);
    } catch (err) {
      return this.l(err, element);
    }
    const verificationError2 = this.t(
      strResource,
      element,
      editStackSnapshot,
      /*now also check that there are no more invalidated resources*/
      true
    );
    if (verificationError2) {
      cleanup.dispose();
      return verificationError2.returnValue;
    }
    for (const editStack of editStackSnapshot.editStacks) {
      editStack.moveBackward(element);
    }
    return this.n(element, () => element.actual.undo(), editStackSnapshot, cleanup, () => this.z(element.groupId, undoConfirmed));
  }
  x(editStack, element, undoConfirmed) {
    if (!element.isValid) {
      editStack.flushAllElements();
      return;
    }
    if (editStack.locked) {
      const message = localize(2468, null, element.label);
      this.d.warn(message);
      return;
    }
    return this.p(element, (cleanup) => {
      editStack.moveBackward(element);
      return this.n(element, () => element.actual.undo(), new EditStackSnapshot([editStack]), cleanup, () => this.z(element.groupId, undoConfirmed));
    });
  }
  y(groupId) {
    if (!groupId) {
      return [null, null];
    }
    let matchedElement = null;
    let matchedStrResource = null;
    for (const [strResource, editStack] of this.a) {
      const candidate = editStack.getClosestPastElement();
      if (!candidate) {
        continue;
      }
      if (candidate.groupId === groupId) {
        if (!matchedElement || candidate.groupOrder > matchedElement.groupOrder) {
          matchedElement = candidate;
          matchedStrResource = strResource;
        }
      }
    }
    return [matchedElement, matchedStrResource];
  }
  z(groupId, undoConfirmed) {
    if (!groupId) {
      return;
    }
    const [, matchedStrResource] = this.y(groupId);
    if (matchedStrResource) {
      return this.A(matchedStrResource, 0, undoConfirmed);
    }
  }
  undo(resourceOrSource) {
    if (resourceOrSource instanceof $cG) {
      const [, matchedStrResource] = this.k(resourceOrSource.id);
      return matchedStrResource ? this.A(matchedStrResource, resourceOrSource.id, false) : void 0;
    }
    if (typeof resourceOrSource === "string") {
      return this.A(resourceOrSource, 0, false);
    }
    return this.A(this.getUriComparisonKey(resourceOrSource), 0, false);
  }
  A(strResource, sourceId = 0, undoConfirmed) {
    if (!this.a.has(strResource)) {
      return;
    }
    const editStack = this.a.get(strResource);
    const element = editStack.getClosestPastElement();
    if (!element) {
      return;
    }
    if (element.groupId) {
      const [matchedElement, matchedStrResource] = this.y(element.groupId);
      if (element !== matchedElement && matchedStrResource) {
        return this.A(matchedStrResource, sourceId, undoConfirmed);
      }
    }
    const shouldPromptForConfirmation = element.sourceId !== sourceId || element.confirmBeforeUndo;
    if (shouldPromptForConfirmation && !undoConfirmed) {
      return this.B(strResource, sourceId, element);
    }
    try {
      if (element.type === 1) {
        return this.u(strResource, element, undoConfirmed);
      } else {
        return this.x(editStack, element, undoConfirmed);
      }
    } finally {
      if (DEBUG2) {
        this.e("undo");
      }
    }
  }
  async B(strResource, sourceId, element) {
    const result = await this.c.confirm({
      message: localize(2469, null, element.label),
      primaryButton: localize(2470, null),
      cancelButton: localize(2471, null)
    });
    if (!result.confirmed) {
      return;
    }
    return this.A(strResource, sourceId, true);
  }
  C(sourceId) {
    if (!sourceId) {
      return [null, null];
    }
    let matchedElement = null;
    let matchedStrResource = null;
    for (const [strResource, editStack] of this.a) {
      const candidate = editStack.getClosestFutureElement();
      if (!candidate) {
        continue;
      }
      if (candidate.sourceId === sourceId) {
        if (!matchedElement || candidate.sourceOrder < matchedElement.sourceOrder) {
          matchedElement = candidate;
          matchedStrResource = strResource;
        }
      }
    }
    return [matchedElement, matchedStrResource];
  }
  canRedo(resourceOrSource) {
    if (resourceOrSource instanceof $cG) {
      const [, matchedStrResource] = this.C(resourceOrSource.id);
      return matchedStrResource ? true : false;
    }
    const strResource = this.getUriComparisonKey(resourceOrSource);
    if (this.a.has(strResource)) {
      const editStack = this.a.get(strResource);
      return editStack.hasFutureElements();
    }
    return false;
  }
  D(strResource, element, ignoreResources, message) {
    if (element.canSplit()) {
      this.h(element, ignoreResources);
      this.d.warn(message);
      return new WorkspaceVerificationError(this.K(strResource));
    } else {
      for (const strResource2 of element.strResources) {
        this.removeElements(strResource2);
      }
      this.d.warn(message);
      return new WorkspaceVerificationError();
    }
  }
  E(strResource, element, editStackSnapshot, checkInvalidatedResources) {
    if (element.removedResources) {
      return this.D(strResource, element, element.removedResources, localize(2472, null, element.label, element.removedResources.createMessage()));
    }
    if (checkInvalidatedResources && element.invalidatedResources) {
      return this.D(strResource, element, element.invalidatedResources, localize(2473, null, element.label, element.invalidatedResources.createMessage()));
    }
    const cannotRedoDueToResources = [];
    for (const editStack of editStackSnapshot.editStacks) {
      if (editStack.getClosestFutureElement() !== element) {
        cannotRedoDueToResources.push(editStack.resourceLabel);
      }
    }
    if (cannotRedoDueToResources.length > 0) {
      return this.D(strResource, element, null, localize(2474, null, element.label, cannotRedoDueToResources.join(", ")));
    }
    const cannotLockDueToResources = [];
    for (const editStack of editStackSnapshot.editStacks) {
      if (editStack.locked) {
        cannotLockDueToResources.push(editStack.resourceLabel);
      }
    }
    if (cannotLockDueToResources.length > 0) {
      return this.D(strResource, element, null, localize(2475, null, element.label, cannotLockDueToResources.join(", ")));
    }
    if (!editStackSnapshot.isValid()) {
      return this.D(strResource, element, null, localize(2476, null, element.label));
    }
    return null;
  }
  F(strResource, element) {
    const affectedEditStacks = this.q(element);
    const verificationError = this.E(
      strResource,
      element,
      affectedEditStacks,
      /*invalidated resources will be checked after the prepare call*/
      false
    );
    if (verificationError) {
      return verificationError.returnValue;
    }
    return this.G(strResource, element, affectedEditStacks);
  }
  async G(strResource, element, editStackSnapshot) {
    let cleanup;
    try {
      cleanup = await this.o(element);
    } catch (err) {
      return this.l(err, element);
    }
    const verificationError = this.E(
      strResource,
      element,
      editStackSnapshot,
      /*now also check that there are no more invalidated resources*/
      true
    );
    if (verificationError) {
      cleanup.dispose();
      return verificationError.returnValue;
    }
    for (const editStack of editStackSnapshot.editStacks) {
      editStack.moveForward(element);
    }
    return this.n(element, () => element.actual.redo(), editStackSnapshot, cleanup, () => this.J(element.groupId));
  }
  H(editStack, element) {
    if (!element.isValid) {
      editStack.flushAllElements();
      return;
    }
    if (editStack.locked) {
      const message = localize(2477, null, element.label);
      this.d.warn(message);
      return;
    }
    return this.p(element, (cleanup) => {
      editStack.moveForward(element);
      return this.n(element, () => element.actual.redo(), new EditStackSnapshot([editStack]), cleanup, () => this.J(element.groupId));
    });
  }
  I(groupId) {
    if (!groupId) {
      return [null, null];
    }
    let matchedElement = null;
    let matchedStrResource = null;
    for (const [strResource, editStack] of this.a) {
      const candidate = editStack.getClosestFutureElement();
      if (!candidate) {
        continue;
      }
      if (candidate.groupId === groupId) {
        if (!matchedElement || candidate.groupOrder < matchedElement.groupOrder) {
          matchedElement = candidate;
          matchedStrResource = strResource;
        }
      }
    }
    return [matchedElement, matchedStrResource];
  }
  J(groupId) {
    if (!groupId) {
      return;
    }
    const [, matchedStrResource] = this.I(groupId);
    if (matchedStrResource) {
      return this.K(matchedStrResource);
    }
  }
  redo(resourceOrSource) {
    if (resourceOrSource instanceof $cG) {
      const [, matchedStrResource] = this.C(resourceOrSource.id);
      return matchedStrResource ? this.K(matchedStrResource) : void 0;
    }
    if (typeof resourceOrSource === "string") {
      return this.K(resourceOrSource);
    }
    return this.K(this.getUriComparisonKey(resourceOrSource));
  }
  K(strResource) {
    if (!this.a.has(strResource)) {
      return;
    }
    const editStack = this.a.get(strResource);
    const element = editStack.getClosestFutureElement();
    if (!element) {
      return;
    }
    if (element.groupId) {
      const [matchedElement, matchedStrResource] = this.I(element.groupId);
      if (element !== matchedElement && matchedStrResource) {
        return this.K(matchedStrResource);
      }
    }
    try {
      if (element.type === 1) {
        return this.F(strResource, element);
      } else {
        return this.H(editStack, element);
      }
    } finally {
      if (DEBUG2) {
        this.e("redo");
      }
    }
  }
};
$mVb = __decorate([
  __param(0, $Yv),
  __param(1, $PJ)
], $mVb);
var WorkspaceVerificationError = class {
  constructor(returnValue) {
    this.returnValue = returnValue;
  }
};
$SC(
  $_F,
  $mVb,
  1
  /* InstantiationType.Delayed */
);

// out-build/vs/workbench/services/workspaces/common/editSessionIdentityService.js
var $nVb = class $nVb2 {
  constructor(b, c) {
    this.b = b;
    this.c = c;
    this.a = /* @__PURE__ */ new Map();
    this.d = [];
  }
  registerEditSessionIdentityProvider(provider) {
    if (this.a.get(provider.scheme)) {
      throw new Error(`A provider has already been registered for scheme ${provider.scheme}`);
    }
    this.a.set(provider.scheme, provider);
    return $1c(() => {
      this.a.delete(provider.scheme);
    });
  }
  async getEditSessionIdentifier(workspaceFolder, token) {
    const { scheme } = workspaceFolder.uri;
    const provider = await this.e(scheme);
    this.c.trace(`EditSessionIdentityProvider for scheme ${scheme} available: ${!!provider}`);
    return provider?.getEditSessionIdentifier(workspaceFolder, token);
  }
  async provideEditSessionIdentityMatch(workspaceFolder, identity1, identity2, cancellationToken) {
    const { scheme } = workspaceFolder.uri;
    const provider = await this.e(scheme);
    this.c.trace(`EditSessionIdentityProvider for scheme ${scheme} available: ${!!provider}`);
    return provider?.provideEditSessionIdentityMatch?.(workspaceFolder, identity1, identity2, cancellationToken);
  }
  async onWillCreateEditSessionIdentity(workspaceFolder, cancellationToken) {
    this.c.debug("Running onWillCreateEditSessionIdentity participants...");
    for (const participant of this.d) {
      await participant.participate(workspaceFolder, cancellationToken);
    }
    this.c.debug(`Done running ${this.d.length} onWillCreateEditSessionIdentity participants.`);
  }
  addEditSessionIdentityCreateParticipant(participant) {
    const dispose = $Wb(this.d, participant);
    return $1c(() => dispose());
  }
  async e(scheme) {
    const transformedScheme = scheme === "vscode-remote" ? "file" : scheme;
    const provider = this.a.get(scheme);
    if (provider) {
      return provider;
    }
    await this.b.activateByEvent(`onEditSession:${transformedScheme}`);
    return this.a.get(scheme);
  }
};
$nVb = __decorate([
  __param(0, $wN),
  __param(1, $wn)
], $nVb);
$SC(
  $2M,
  $nVb,
  1
  /* InstantiationType.Delayed */
);

// out-build/vs/workbench/services/workspaces/common/canonicalUriService.js
var $oVb = class {
  constructor() {
    this.a = /* @__PURE__ */ new Map();
  }
  registerCanonicalUriProvider(provider) {
    this.a.set(provider.scheme, provider);
    return {
      dispose: () => this.a.delete(provider.scheme)
    };
  }
  async provideCanonicalUri(uri, targetScheme, token) {
    const provider = this.a.get(uri.scheme);
    if (provider) {
      return provider.provideCanonicalUri(uri, targetScheme, token);
    }
    return void 0;
  }
};
$SC(
  $9Rb,
  $oVb,
  1
  /* InstantiationType.Delayed */
);

// out-build/vs/workbench/services/keybinding/common/keybindingEditing.js
var $pVb = $Qk("keybindingEditingService");
var $qVb = class $qVb2 extends $3c {
  constructor(f, g, h3, j) {
    super();
    this.f = f;
    this.g = g;
    this.h = h3;
    this.j = j;
    this.c = new $3h();
  }
  addKeybinding(keybindingItem, key2, when) {
    return this.c.queue(() => this.m(keybindingItem, key2, when, true));
  }
  editKeybinding(keybindingItem, key2, when) {
    return this.c.queue(() => this.m(keybindingItem, key2, when, false));
  }
  resetKeybinding(keybindingItem) {
    return this.c.queue(() => this.r(keybindingItem));
  }
  removeKeybinding(keybindingItem) {
    return this.c.queue(() => this.n(keybindingItem));
  }
  async m(keybindingItem, key2, when, add) {
    const reference = await this.I();
    const model = reference.object.textEditorModel;
    if (add) {
      this.t(keybindingItem, key2, when, model, -1);
    } else {
      const userKeybindingEntries = $yw(model.getValue());
      const userKeybindingEntryIndex = this.z(keybindingItem, userKeybindingEntries);
      this.t(keybindingItem, key2, when, model, userKeybindingEntryIndex);
      if (keybindingItem.isDefault && keybindingItem.resolvedKeybinding) {
        this.w(keybindingItem, model);
      }
    }
    try {
      await this.s();
    } finally {
      reference.dispose();
    }
  }
  async n(keybindingItem) {
    const reference = await this.I();
    const model = reference.object.textEditorModel;
    if (keybindingItem.isDefault) {
      this.w(keybindingItem, model);
    } else {
      this.u(keybindingItem, model);
    }
    try {
      return await this.s();
    } finally {
      reference.dispose();
    }
  }
  async r(keybindingItem) {
    const reference = await this.I();
    const model = reference.object.textEditorModel;
    if (!keybindingItem.isDefault) {
      this.u(keybindingItem, model);
      this.y(keybindingItem, model);
    }
    try {
      return await this.s();
    } finally {
      reference.dispose();
    }
  }
  s() {
    return this.g.save(this.j.currentProfile.keybindingsResource);
  }
  t(keybindingItem, newKey, when, model, userKeybindingEntryIndex) {
    const { tabSize, insertSpaces } = model.getOptions();
    const eol = model.getEOL();
    if (userKeybindingEntryIndex !== -1) {
      this.G($Xw(model.getValue(), [userKeybindingEntryIndex, "key"], newKey, { tabSize, insertSpaces, eol })[0], model);
      const edits = $Xw(model.getValue(), [userKeybindingEntryIndex, "when"], when, { tabSize, insertSpaces, eol });
      if (edits.length > 0) {
        this.G(edits[0], model);
      }
    } else {
      this.G($Xw(model.getValue(), [-1], this.D(newKey, keybindingItem.command, when, false), { tabSize, insertSpaces, eol })[0], model);
    }
  }
  u(keybindingItem, model) {
    const { tabSize, insertSpaces } = model.getOptions();
    const eol = model.getEOL();
    const userKeybindingEntries = $yw(model.getValue());
    const userKeybindingEntryIndex = this.z(keybindingItem, userKeybindingEntries);
    if (userKeybindingEntryIndex !== -1) {
      this.G($Xw(model.getValue(), [userKeybindingEntryIndex], void 0, { tabSize, insertSpaces, eol })[0], model);
    }
  }
  w(keybindingItem, model) {
    const { tabSize, insertSpaces } = model.getOptions();
    const eol = model.getEOL();
    const key2 = keybindingItem.resolvedKeybinding ? keybindingItem.resolvedKeybinding.getUserSettingsLabel() : null;
    if (key2) {
      const entry = this.D(key2, keybindingItem.command, keybindingItem.when ? keybindingItem.when.serialize() : void 0, true);
      const userKeybindingEntries = $yw(model.getValue());
      if (userKeybindingEntries.every((e) => !this.F(e, entry))) {
        this.G($Xw(model.getValue(), [-1], entry, { tabSize, insertSpaces, eol })[0], model);
      }
    }
  }
  y(keybindingItem, model) {
    const { tabSize, insertSpaces } = model.getOptions();
    const eol = model.getEOL();
    const userKeybindingEntries = $yw(model.getValue());
    const indices = this.C(keybindingItem, userKeybindingEntries).reverse();
    for (const index of indices) {
      this.G($Xw(model.getValue(), [index], void 0, { tabSize, insertSpaces, eol })[0], model);
    }
  }
  z(keybindingItem, userKeybindingEntries) {
    for (let index = 0; index < userKeybindingEntries.length; index++) {
      const keybinding = userKeybindingEntries[index];
      if (keybinding.command === keybindingItem.command) {
        if (!keybinding.when && !keybindingItem.when) {
          return index;
        }
        if (keybinding.when && keybindingItem.when) {
          const contextKeyExpr2 = $7m.deserialize(keybinding.when);
          if (contextKeyExpr2 && contextKeyExpr2.serialize() === keybindingItem.when.serialize()) {
            return index;
          }
        }
      }
    }
    return -1;
  }
  C(keybindingItem, userKeybindingEntries) {
    const indices = [];
    for (let index = 0; index < userKeybindingEntries.length; index++) {
      if (userKeybindingEntries[index].command === `-${keybindingItem.command}`) {
        indices.push(index);
      }
    }
    return indices;
  }
  D(key2, command4, when, negate) {
    const object = { key: key2 };
    if (command4) {
      object["command"] = negate ? `-${command4}` : command4;
    }
    if (when) {
      object["when"] = when;
    }
    return object;
  }
  F(a, b) {
    if (a.command !== b.command) {
      return false;
    }
    if (a.key !== b.key) {
      return false;
    }
    const whenA = $7m.deserialize(a.when);
    const whenB = $7m.deserialize(b.when);
    if (whenA && !whenB || !whenA && whenB) {
      return false;
    }
    if (whenA && whenB && !whenA.equals(whenB)) {
      return false;
    }
    if (!$Pv(a.args, b.args)) {
      return false;
    }
    return true;
  }
  G(edit3, model) {
    const startPosition = model.getPositionAt(edit3.offset);
    const endPosition = model.getPositionAt(edit3.offset + edit3.length);
    const range = new $9C(startPosition.lineNumber, startPosition.column, endPosition.lineNumber, endPosition.column);
    const currentText = model.getValueInRange(range);
    const editOperation = currentText ? $bD.replace(range, edit3.content) : $bD.insert(startPosition, edit3.content);
    model.pushEditOperations([new $_D(startPosition.lineNumber, startPosition.column, startPosition.lineNumber, startPosition.column)], [editOperation], () => []);
  }
  async H() {
    const exists = await this.h.exists(this.j.currentProfile.keybindingsResource);
    if (!exists) {
      await this.g.write(this.j.currentProfile.keybindingsResource, this.L(), { encoding: "utf8" });
    }
    return this.f.createModelReference(this.j.currentProfile.keybindingsResource);
  }
  async I() {
    if (this.g.isDirty(this.j.currentProfile.keybindingsResource)) {
      throw new Error(localize(12966, null));
    }
    const reference = await this.H();
    const model = reference.object.textEditorModel;
    const EOL = model.getEOL();
    if (model.getValue()) {
      const parsed = this.J(model);
      if (parsed.parseErrors.length) {
        reference.dispose();
        throw new Error(localize(12967, null));
      }
      if (parsed.result) {
        if (!Array.isArray(parsed.result)) {
          reference.dispose();
          throw new Error(localize(12968, null));
        }
      } else {
        const content = EOL + "[]";
        this.G({ content, length: content.length, offset: model.getValue().length }, model);
      }
    } else {
      const content = this.L();
      this.G({ content, length: content.length, offset: 0 }, model);
    }
    return reference;
  }
  J(model) {
    const parseErrors = [];
    const result = $yw(model.getValue(), parseErrors, { allowTrailingComma: true, allowEmptyContent: true });
    return { result, parseErrors };
  }
  L() {
    return "// " + localize(12969, null) + "\n[\n]";
  }
};
$qVb = __decorate([
  __param(0, $oG),
  __param(1, $cK),
  __param(2, $km),
  __param(3, $gT)
], $qVb);
$SC(
  $pVb,
  $qVb,
  1
  /* InstantiationType.Delayed */
);

// out-build/vs/workbench/services/decorations/browser/decorationsService.js
var DecorationRule = class _DecorationRule {
  static keyOf(data) {
    if (Array.isArray(data)) {
      return data.map(_DecorationRule.keyOf).join(",");
    } else {
      const { color: color2, letter } = data;
      if (ThemeIcon.isThemeIcon(letter)) {
        return `${color2}+${letter.id}`;
      } else {
        return `${color2}/${letter}`;
      }
    }
  }
  static {
    this.c = "monaco-decoration";
  }
  constructor(themeService, data, key2) {
    this.themeService = themeService;
    this.e = 0;
    this.data = data;
    const suffix = $Xi(key2).toString(36);
    this.itemColorClassName = `${_DecorationRule.c}-itemColor-${suffix}`;
    this.itemBadgeClassName = `${_DecorationRule.c}-itemBadge-${suffix}`;
    this.bubbleBadgeClassName = `${_DecorationRule.c}-bubbleBadge-${suffix}`;
    this.iconBadgeClassName = `${_DecorationRule.c}-iconBadge-${suffix}`;
  }
  acquire() {
    this.e += 1;
  }
  release() {
    return --this.e === 0;
  }
  appendCSSRules(element) {
    if (!Array.isArray(this.data)) {
      this.f(this.data, element);
    } else {
      this.g(this.data, element);
    }
  }
  f(data, element) {
    const { color: color2, letter } = data;
    $XZ(`.${this.itemColorClassName}`, `color: ${getColor(color2)};`, element);
    if (ThemeIcon.isThemeIcon(letter)) {
      this.h(letter, color2, element);
    } else if (letter) {
      $XZ(`.${this.itemBadgeClassName}::after`, `content: "${letter}"; color: ${getColor(color2)};`, element);
    }
  }
  g(data, element) {
    const { color: color2 } = data.find((d) => !!d.color) ?? data[0];
    $XZ(`.${this.itemColorClassName}`, `color: ${getColor(color2)};`, element);
    const letters = [];
    let icon2;
    for (const d of data) {
      if (ThemeIcon.isThemeIcon(d.letter)) {
        icon2 = d.letter;
        break;
      } else if (d.letter) {
        letters.push(d.letter);
      }
    }
    if (icon2) {
      this.h(icon2, color2, element);
    } else {
      if (letters.length) {
        $XZ(`.${this.itemBadgeClassName}::after`, `content: "${letters.join(", ")}"; color: ${getColor(color2)};`, element);
      }
      $XZ(`.${this.bubbleBadgeClassName}::after`, `content: "\uEA71"; color: ${getColor(color2)}; font-family: codicon; font-size: 14px; margin-right: 14px; opacity: 0.4;`, element);
    }
  }
  h(icon2, color2, element) {
    const modifier = ThemeIcon.getModifier(icon2);
    if (modifier) {
      icon2 = ThemeIcon.modify(icon2, void 0);
    }
    const iconContribution = $0r().getIcon(icon2.id);
    if (!iconContribution) {
      return;
    }
    const definition = this.themeService.getProductIconTheme().getIcon(iconContribution);
    if (!definition) {
      return;
    }
    $XZ(`.${this.iconBadgeClassName}::after`, `content: '${definition.fontCharacter}';
			color: ${icon2.color ? getColor(icon2.color.id) : getColor(color2)};
			font-family: ${$4Z(definition.font?.id ?? "codicon")};
			font-size: 16px;
			margin-right: 14px;
			font-weight: normal;
			${modifier === "spin" ? "animation: codicon-spin 1.5s steps(30) infinite" : ""};
			`, element);
  }
  removeCSSRules(element) {
    $YZ(this.itemColorClassName, element);
    $YZ(this.itemBadgeClassName, element);
    $YZ(this.bubbleBadgeClassName, element);
    $YZ(this.iconBadgeClassName, element);
  }
};
var DecorationStyles = class {
  constructor(g) {
    this.g = g;
    this.c = new $2c();
    this.e = $VZ(void 0, void 0, this.c);
    this.f = /* @__PURE__ */ new Map();
  }
  dispose() {
    this.c.dispose();
  }
  asDecoration(data, onlyChildren) {
    data.sort((a, b) => (b.weight || 0) - (a.weight || 0));
    const key2 = DecorationRule.keyOf(data);
    let rule = this.f.get(key2);
    if (!rule) {
      rule = new DecorationRule(this.g, data, key2);
      this.f.set(key2, rule);
      rule.appendCSSRules(this.e);
    }
    rule.acquire();
    const labelClassName = rule.itemColorClassName;
    let badgeClassName = rule.itemBadgeClassName;
    const iconClassName = rule.iconBadgeClassName;
    let tooltip = $Rb(data.filter((d) => !$vf(d.tooltip)).map((d) => d.tooltip)).join(" \u2022 ");
    const strikethrough = data.some((d) => d.strikethrough);
    if (onlyChildren) {
      badgeClassName = rule.bubbleBadgeClassName;
      tooltip = localize(12650, null);
    }
    return {
      labelClassName,
      badgeClassName,
      iconClassName,
      strikethrough,
      tooltip,
      dispose: () => {
        if (rule?.release()) {
          this.f.delete(key2);
          rule.removeCSSRules(this.e);
          rule = void 0;
        }
      }
    };
  }
};
var FileDecorationChangeEvent = class {
  constructor(all) {
    this.c = $Wk.forUris((_uri) => true);
    this.c.fill(true, $5b(all));
  }
  affectsResource(uri) {
    return this.c.hasElementOrSubtree(uri);
  }
};
var DecorationDataRequest = class {
  constructor(source, thenable) {
    this.source = source;
    this.thenable = thenable;
  }
};
function getColor(color2) {
  return color2 ? $Zn(color2) : "inherit";
}
var $rVb = class $rVb2 {
  constructor(uriIdentityService, themeService) {
    this.c = new $2c();
    this.e = this.c.add(new $De({ merge: (all) => all.flat() }));
    this.f = this.c.add(new $ze());
    this.onDidChangeDecorations = this.f.event;
    this.g = new $cd();
    this.h = new DecorationStyles(themeService);
    this.i = $Wk.forUris((key2) => uriIdentityService.extUri.ignorePathCasing(key2));
    this.c.add(this.e.event((event) => {
      this.f.fire(new FileDecorationChangeEvent(event));
    }));
  }
  dispose() {
    this.c.dispose();
    this.i.clear();
  }
  registerDecorationsProvider(provider) {
    const rm = this.g.unshift(provider);
    this.f.fire({
      // everything might have changed
      affectsResource() {
        return true;
      }
    });
    const removeAll = () => {
      const uris = [];
      for (const [uri, map] of this.i) {
        if (map.delete(provider)) {
          uris.push(uri);
        }
      }
      if (uris.length > 0) {
        this.e.fire(uris);
      }
    };
    const listener = provider.onDidChange((uris) => {
      if (!uris) {
        removeAll();
      } else {
        for (const uri of uris) {
          const map = this.j(uri);
          this.k(map, uri, provider);
        }
      }
    });
    return $1c(() => {
      rm();
      listener.dispose();
      removeAll();
    });
  }
  j(uri) {
    let map = this.i.get(uri);
    if (!map) {
      map = /* @__PURE__ */ new Map();
      this.i.set(uri, map);
    }
    return map;
  }
  getDecoration(uri, includeChildren) {
    const all = [];
    let containsChildren = false;
    const map = this.j(uri);
    for (const provider of this.g) {
      let data = map.get(provider);
      if (data === void 0) {
        data = this.k(map, uri, provider);
      }
      if (data && !(data instanceof DecorationDataRequest)) {
        all.push(data);
      }
    }
    if (includeChildren) {
      const iter = this.i.findSuperstr(uri);
      if (iter) {
        for (const tuple of iter) {
          for (const data of tuple[1].values()) {
            if (data && !(data instanceof DecorationDataRequest)) {
              if (data.bubble) {
                all.push(data);
                containsChildren = true;
              }
            }
          }
        }
      }
    }
    return all.length === 0 ? void 0 : this.h.asDecoration(all, containsChildren);
  }
  k(map, uri, provider) {
    const pendingRequest = map.get(provider);
    if (pendingRequest instanceof DecorationDataRequest) {
      pendingRequest.source.cancel();
      map.delete(provider);
    }
    const cts = new $ad();
    const dataOrThenable = provider.provideDecorations(uri, cts.token);
    if (!$Gh(dataOrThenable)) {
      cts.dispose();
      return this.l(map, provider, uri, dataOrThenable);
    } else {
      const request = new DecorationDataRequest(cts, Promise.resolve(dataOrThenable).then((data) => {
        if (map.get(provider) === request) {
          this.l(map, provider, uri, data);
        }
      }).catch((err) => {
        if (!$kb(err) && map.get(provider) === request) {
          map.delete(provider);
        }
      }).finally(() => {
        cts.dispose();
      }));
      map.set(provider, request);
      return null;
    }
  }
  l(map, provider, uri, data) {
    const deco = data ? data : null;
    const old = map.get(provider);
    map.set(provider, deco);
    if (deco || old) {
      this.e.fire(uri);
    }
    return deco;
  }
};
$rVb = __decorate([
  __param(0, $vl),
  __param(1, $gs)
], $rVb);
$SC(
  $jsb,
  $rVb,
  1
  /* InstantiationType.Delayed */
);

// out-build/vs/workbench/common/dialogs.js
var $sVb = class extends $3c {
  constructor() {
    super(...arguments);
    this.dialogs = [];
    this.a = this.B(new $ze());
    this.onWillShowDialog = this.a.event;
    this.b = this.B(new $ze());
    this.onDidShowDialog = this.b.event;
  }
  show(dialog) {
    const promise = new $gi();
    const item = {
      args: dialog,
      close: (result) => {
        this.dialogs.splice(0, 1);
        if (result instanceof Error) {
          promise.error(result);
        } else {
          promise.complete(result);
        }
        this.b.fire();
      }
    };
    this.dialogs.push(item);
    this.a.fire();
    return {
      item,
      result: promise.p
    };
  }
};

// out-build/vs/workbench/services/dialogs/common/dialogService.js
var $tVb = class $tVb2 extends $3c {
  constructor(a, b) {
    super();
    this.a = a;
    this.b = b;
    this.model = this.B(new $sVb());
    this.onWillShowDialog = this.model.onWillShowDialog;
    this.onDidShowDialog = this.model.onDidShowDialog;
  }
  c() {
    if (this.a.isExtensionDevelopment && this.a.extensionTestsLocationURI) {
      return true;
    }
    return !!this.a.enableSmokeTestDriver;
  }
  async confirm(confirmation) {
    if (this.c()) {
      this.b.trace("DialogService: refused to show confirmation dialog in tests.");
      return { confirmed: true };
    }
    const handle2 = this.model.show({ confirmArgs: { confirmation } });
    return await handle2.result;
  }
  async prompt(prompt) {
    if (this.c()) {
      throw new Error(`DialogService: refused to show dialog in tests. Contents: ${prompt.message}`);
    }
    const handle2 = this.model.show({ promptArgs: { prompt } });
    const dialogResult = await handle2.result;
    return {
      result: await dialogResult.result,
      checkboxChecked: dialogResult.checkboxChecked
    };
  }
  async input(input) {
    if (this.c()) {
      throw new Error("DialogService: refused to show input dialog in tests.");
    }
    const handle2 = this.model.show({ inputArgs: { input } });
    return await handle2.result;
  }
  async info(message, detail2) {
    await this.prompt({ type: severity_default.Info, message, detail: detail2 });
  }
  async warn(message, detail2) {
    await this.prompt({ type: severity_default.Warning, message, detail: detail2 });
  }
  async error(message, detail2) {
    await this.prompt({ type: severity_default.Error, message, detail: detail2 });
  }
  async about() {
    if (this.c()) {
      throw new Error("DialogService: refused to show about dialog in tests.");
    }
    const handle2 = this.model.show({});
    await handle2.result;
  }
};
$tVb = __decorate([
  __param(0, $US),
  __param(1, $wn)
], $tVb);
$SC(
  $Yv,
  $tVb,
  1
  /* InstantiationType.Delayed */
);

// out-build/vs/base/browser/ui/dialog/dialog.js
var $K2 = class extends $3c {
  constructor(y, z, buttons, C) {
    super();
    this.y = y;
    this.z = z;
    this.C = C;
    this.c = this.y.appendChild($(`.monaco-dialog-modal-block.dimmed`));
    this.b = this.c.appendChild($(".dialog-shadow"));
    this.a = this.b.appendChild($(".monaco-dialog-box"));
    this.a.setAttribute("role", "dialog");
    this.a.tabIndex = -1;
    $ik(this.a);
    this.w = C.buttonStyles;
    if (Array.isArray(buttons) && buttons.length > 0) {
      this.u = buttons;
    } else if (!this.C.disableDefaultAction) {
      this.u = [localize(2, null)];
    } else {
      this.u = [];
    }
    const buttonsRowElement = this.a.appendChild($(".dialog-buttons-row"));
    this.f = buttonsRowElement.appendChild($(".dialog-buttons"));
    const messageRowElement = this.a.appendChild($(".dialog-message-row"));
    this.j = messageRowElement.appendChild($("#monaco-dialog-icon.dialog-icon"));
    this.j.setAttribute("aria-label", this.D());
    this.h = messageRowElement.appendChild($(".dialog-message-container"));
    if (this.C.detail || this.C.renderBody) {
      const messageElement = this.h.appendChild($(".dialog-message"));
      const messageTextElement = messageElement.appendChild($("#monaco-dialog-message-text.dialog-message-text"));
      messageTextElement.innerText = this.z;
    }
    this.g = this.h.appendChild($("#monaco-dialog-message-detail.dialog-message-detail"));
    if (this.C.detail || !this.C.renderBody) {
      this.g.innerText = this.C.detail ? this.C.detail : z;
    } else {
      this.g.style.display = "none";
    }
    if (this.C.renderBody) {
      const customBody = this.h.appendChild($("#monaco-dialog-message-body.dialog-message-body"));
      this.C.renderBody(customBody);
      for (const el of this.h.querySelectorAll("a")) {
        el.tabIndex = 0;
      }
    }
    if (this.C.inputs) {
      this.t = this.C.inputs.map((input) => {
        const inputRowElement = this.h.appendChild($(".dialog-message-input"));
        const inputBox = this.B(new $I2(inputRowElement, void 0, {
          placeholder: input.placeholder,
          type: input.type ?? "text",
          inputBoxStyles: C.inputBoxStyles
        }));
        if (input.value) {
          inputBox.value = input.value;
        }
        return inputBox;
      });
    } else {
      this.t = [];
    }
    if (this.C.checkboxLabel) {
      const checkboxRowElement = this.h.appendChild($(".dialog-checkbox-row"));
      const checkbox = this.m = this.B(new $R1(this.C.checkboxLabel, !!this.C.checkboxChecked, C.checkboxStyles));
      checkboxRowElement.appendChild(checkbox.domNode);
      const checkboxMessageElement = checkboxRowElement.appendChild($(".dialog-checkbox-message"));
      checkboxMessageElement.innerText = this.C.checkboxLabel;
      this.B($_i(checkboxMessageElement, $7j.CLICK, () => checkbox.checked = !checkbox.checked));
    }
    const toolbarRowElement = this.a.appendChild($(".dialog-toolbar-row"));
    this.n = toolbarRowElement.appendChild($(".dialog-toolbar"));
    this.F();
  }
  D() {
    let typeLabel = localize(3, null);
    switch (this.C.type) {
      case "error":
        typeLabel = localize(4, null);
        break;
      case "warning":
        typeLabel = localize(5, null);
        break;
      case "pending":
        typeLabel = localize(6, null);
        break;
      case "none":
      case "info":
      case "question":
      default:
        break;
    }
    return typeLabel;
  }
  updateMessage(message) {
    this.g.innerText = message;
  }
  async show() {
    this.s = this.y.ownerDocument.activeElement;
    return new Promise((resolve) => {
      $$i(this.f);
      const close2 = () => {
        resolve({
          button: this.C.cancelId || 0,
          checkboxChecked: this.m ? this.m.checked : void 0
        });
        return;
      };
      if (this.C.closeOnLinkClick) {
        for (const el of this.h.getElementsByTagName("a")) {
          this.B($_i(el, $7j.CLICK, () => {
            setTimeout(close2);
          }));
          this.B($_i(el, $7j.KEY_DOWN, (e) => {
            const evt = new $if(e);
            if (evt.equals(
              3
              /* KeyCode.Enter */
            )) {
              setTimeout(close2);
            }
          }));
        }
      }
      const buttonBar = this.r = this.B(new $n2(this.f));
      const buttonMap = this.G(this.u, this.C.cancelId);
      buttonMap.forEach((entry, index) => {
        const primary = buttonMap[index].index === 0;
        const button = this.C.buttonDetails ? this.B(buttonBar.addButtonWithDescription({ secondary: !primary, ...this.w })) : this.B(buttonBar.addButton({ secondary: !primary, ...this.w }));
        button.label = $7t(buttonMap[index].label, true);
        if (button instanceof $m2) {
          button.description = this.C.buttonDetails[buttonMap[index].index];
        }
        this.B(button.onDidClick((e) => {
          if (e) {
            $9j.stop(e);
          }
          resolve({
            button: buttonMap[index].index,
            checkboxChecked: this.m ? this.m.checked : void 0,
            values: this.t.length > 0 ? this.t.map((input) => input.value) : void 0
          });
        }));
      });
      const window3 = getWindow(this.y);
      this.B($_i(window3, "keydown", (e) => {
        const evt = new $if(e);
        if (evt.equals(
          512
          /* KeyMod.Alt */
        )) {
          evt.preventDefault();
        }
        if (evt.equals(
          3
          /* KeyCode.Enter */
        )) {
          if (this.t.some((input) => input.hasFocus())) {
            $9j.stop(e);
            resolve({
              button: buttonMap.find((button) => button.index !== this.C.cancelId)?.index ?? 0,
              checkboxChecked: this.m ? this.m.checked : void 0,
              values: this.t.length > 0 ? this.t.map((input) => input.value) : void 0
            });
          }
          return;
        }
        if (evt.equals(
          10
          /* KeyCode.Space */
        )) {
          return;
        }
        let eventHandled = false;
        if (evt.equals(
          2
          /* KeyCode.Tab */
        ) || evt.equals(
          17
          /* KeyCode.RightArrow */
        ) || evt.equals(
          1024 | 2
          /* KeyCode.Tab */
        ) || evt.equals(
          15
          /* KeyCode.LeftArrow */
        )) {
          const focusableElements = [];
          let focusedIndex = -1;
          if (this.h) {
            const links = this.h.querySelectorAll("a");
            for (const link2 of links) {
              focusableElements.push(link2);
              if ($Mj(link2)) {
                focusedIndex = focusableElements.length - 1;
              }
            }
          }
          for (const input of this.t) {
            focusableElements.push(input);
            if (input.hasFocus()) {
              focusedIndex = focusableElements.length - 1;
            }
          }
          if (this.m) {
            focusableElements.push(this.m);
            if (this.m.hasFocus()) {
              focusedIndex = focusableElements.length - 1;
            }
          }
          if (this.r) {
            for (const button of this.r.buttons) {
              focusableElements.push(button);
              if (button.hasFocus()) {
                focusedIndex = focusableElements.length - 1;
              }
            }
          }
          if (evt.equals(
            2
            /* KeyCode.Tab */
          ) || evt.equals(
            17
            /* KeyCode.RightArrow */
          )) {
            if (focusedIndex === -1) {
              focusedIndex = 0;
            }
            const newFocusedIndex = (focusedIndex + 1) % focusableElements.length;
            focusableElements[newFocusedIndex].focus();
          } else {
            if (focusedIndex === -1) {
              focusedIndex = focusableElements.length;
            }
            let newFocusedIndex = focusedIndex - 1;
            if (newFocusedIndex === -1) {
              newFocusedIndex = focusableElements.length - 1;
            }
            focusableElements[newFocusedIndex].focus();
          }
          eventHandled = true;
        }
        if (eventHandled) {
          $9j.stop(e, true);
        } else if (this.C.keyEventProcessor) {
          this.C.keyEventProcessor(evt);
        }
      }, true));
      this.B($_i(window3, "keyup", (e) => {
        $9j.stop(e, true);
        const evt = new $if(e);
        if (!this.C.disableCloseAction && evt.equals(
          9
          /* KeyCode.Escape */
        )) {
          close2();
        }
      }, true));
      this.B($_i(this.a, "focusout", (e) => {
        if (!!e.relatedTarget && !!this.a) {
          if (!$Dj(e.relatedTarget, this.a)) {
            this.s = e.relatedTarget;
            if (e.target) {
              e.target.focus();
              $9j.stop(e, true);
            }
          }
        }
      }, false));
      const spinModifierClassName = "codicon-modifier-spin";
      this.j.classList.remove(...ThemeIcon.asClassNameArray($6l.dialogError), ...ThemeIcon.asClassNameArray($6l.dialogWarning), ...ThemeIcon.asClassNameArray($6l.dialogInfo), ...ThemeIcon.asClassNameArray($6l.loading), spinModifierClassName);
      if (this.C.icon) {
        this.j.classList.add(...ThemeIcon.asClassNameArray(this.C.icon));
      } else {
        switch (this.C.type) {
          case "error":
            this.j.classList.add(...ThemeIcon.asClassNameArray($6l.dialogError));
            break;
          case "warning":
            this.j.classList.add(...ThemeIcon.asClassNameArray($6l.dialogWarning));
            break;
          case "pending":
            this.j.classList.add(...ThemeIcon.asClassNameArray($6l.loading), spinModifierClassName);
            break;
          case "none":
            this.j.classList.add("no-codicon");
            break;
          case "info":
          case "question":
          default:
            this.j.classList.add(...ThemeIcon.asClassNameArray($6l.dialogInfo));
            break;
        }
      }
      if (!this.C.disableCloseAction) {
        const actionBar = this.B(new $LZ(this.n, {}));
        const action = this.B(new $Um("dialog.close", localize(7, null), ThemeIcon.asClassName($6l.dialogClose), true, async () => {
          resolve({
            button: this.C.cancelId || 0,
            checkboxChecked: this.m ? this.m.checked : void 0
          });
        }));
        actionBar.push(action, { icon: true, label: false });
      }
      this.F();
      this.a.setAttribute("aria-modal", "true");
      this.a.setAttribute("aria-labelledby", "monaco-dialog-icon monaco-dialog-message-text");
      this.a.setAttribute("aria-describedby", "monaco-dialog-icon monaco-dialog-message-text monaco-dialog-message-detail monaco-dialog-message-body");
      $hk(this.a);
      if (this.t.length > 0) {
        this.t[0].focus();
        this.t[0].select();
      } else {
        buttonMap.forEach((value, index) => {
          if (value.index === 0) {
            buttonBar.buttons[index].focus();
          }
        });
      }
    });
  }
  F() {
    const style = this.C.dialogStyles;
    const fgColor = style.dialogForeground;
    const bgColor = style.dialogBackground;
    const shadowColor = style.dialogShadow ? `0 0px 8px ${style.dialogShadow}` : "";
    const border = style.dialogBorder ? `1px solid ${style.dialogBorder}` : "";
    const linkFgColor = style.textLinkForeground;
    this.b.style.boxShadow = shadowColor;
    this.a.style.color = fgColor ?? "";
    this.a.style.backgroundColor = bgColor ?? "";
    this.a.style.border = border;
    if (linkFgColor) {
      for (const el of this.h.getElementsByTagName("a")) {
        el.style.color = linkFgColor;
      }
    }
    let color2;
    switch (this.C.type) {
      case "none":
        break;
      case "error":
        color2 = style.errorIconForeground;
        break;
      case "warning":
        color2 = style.warningIconForeground;
        break;
      default:
        color2 = style.infoIconForeground;
        break;
    }
    if (color2) {
      this.j.style.color = color2;
    }
  }
  dispose() {
    super.dispose();
    if (this.c) {
      this.c.remove();
      this.c = void 0;
    }
    if (this.s && $Dj(this.s, this.y.ownerDocument.body)) {
      this.s.focus();
      this.s = void 0;
    }
  }
  G(buttons, cancelId) {
    const buttonMap = buttons.map((label3, index) => ({ label: label3, index }));
    if (buttons.length < 2) {
      return buttonMap;
    }
    if ($m || $n) {
      if (typeof cancelId === "number" && buttonMap[cancelId]) {
        const cancelButton = buttonMap.splice(cancelId, 1)[0];
        buttonMap.splice(1, 0, cancelButton);
      }
      buttonMap.reverse();
    } else if ($l) {
      if (typeof cancelId === "number" && buttonMap[cancelId]) {
        const cancelButton = buttonMap.splice(cancelId, 1)[0];
        buttonMap.push(cancelButton);
      }
    }
    return buttonMap;
  }
};

// out-build/vs/workbench/services/progress/browser/progressService.js
var $uVb = class $uVb2 extends $3c {
  constructor(a, b, c, f, g, h3, j, m, n) {
    super();
    this.a = a;
    this.b = b;
    this.c = c;
    this.f = f;
    this.g = g;
    this.h = h3;
    this.j = j;
    this.m = m;
    this.n = n;
    this.r = [];
    this.s = void 0;
  }
  async withProgress(options3, originalTask, onDidCancel) {
    const { location: location3 } = options3;
    const task = async (progress) => {
      const activeLock = this.n.markActive({ whenHeldFor: 15e3 });
      try {
        return await originalTask(progress);
      } finally {
        activeLock.dispose();
      }
    };
    const handleStringLocation = (location4) => {
      const viewContainer5 = this.c.getViewContainerById(location4);
      if (viewContainer5) {
        const viewContainerLocation = this.c.getViewContainerLocation(viewContainer5);
        if (viewContainerLocation !== null) {
          return this.y(location4, viewContainerLocation, task, { ...options3, location: location4 });
        }
      }
      if (this.c.getViewDescriptorById(location4) !== null) {
        return this.z(location4, task, { ...options3, location: location4 });
      }
      throw new Error(`Bad progress location: ${location4}`);
    };
    if (typeof location3 === "string") {
      return handleStringLocation(location3);
    }
    switch (location3) {
      case 15: {
        let priority = options3.priority;
        if (priority !== NotificationPriority.URGENT) {
          if (this.g.getFilter() === NotificationsFilter.ERROR) {
            priority = NotificationPriority.SILENT;
          } else if ($QJ(options3.source) && this.g.getFilter(options3.source) === NotificationsFilter.ERROR) {
            priority = NotificationPriority.SILENT;
          }
        }
        return this.w({ ...options3, location: location3, priority }, task, onDidCancel);
      }
      case 10: {
        const type = options3.type;
        if (options3.command) {
          return this.t({ ...options3, location: location3, type }, task);
        }
        return this.w({ delay: 150, ...options3, priority: NotificationPriority.SILENT, location: 15, type }, task, onDidCancel);
      }
      case 1:
        return this.y("workbench.view.explorer", 0, task, { ...options3, location: location3 });
      case 3:
        return handleStringLocation("workbench.scm");
      case 5:
        return this.y("workbench.view.extensions", 0, task, { ...options3, location: location3 });
      case 20:
        return this.F(options3, task, onDidCancel);
      default:
        throw new Error(`Bad progress location: ${location3}`);
    }
  }
  t(options3, callback) {
    const task = [options3, new $VJ(() => this.u())];
    const promise = callback(task[1]);
    let delayHandle = setTimeout(() => {
      delayHandle = void 0;
      this.r.unshift(task);
      this.u();
      Promise.all([
        $Wh(150),
        promise
      ]).finally(() => {
        const idx = this.r.indexOf(task);
        this.r.splice(idx, 1);
        this.u();
      });
    }, 150);
    return promise.finally(() => clearTimeout(delayHandle));
  }
  u(idx = 0) {
    if (idx < this.r.length) {
      const [options3, progress] = this.r[idx];
      const progressTitle = options3.title;
      const progressMessage = progress.value && progress.value.message;
      const progressCommand = options3.command;
      let text2;
      let title;
      const source = options3.source && typeof options3.source !== "string" ? options3.source.label : options3.source;
      if (progressTitle && progressMessage) {
        text2 = localize(13074, null, progressTitle, progressMessage);
        title = source ? localize(13075, null, source, progressTitle, progressMessage) : text2;
      } else if (progressTitle) {
        text2 = progressTitle;
        title = source ? localize(13076, null, source, progressTitle) : text2;
      } else if (progressMessage) {
        text2 = progressMessage;
        title = source ? localize(13077, null, source, progressMessage) : text2;
      } else {
        this.u(idx + 1);
        return;
      }
      const statusEntryProperties = {
        name: localize(13078, null),
        text: text2,
        showProgress: options3.type || true,
        ariaLabel: text2,
        tooltip: $0l(title).trim(),
        command: progressCommand
      };
      if (this.s) {
        this.s.update(statusEntryProperties);
      } else {
        this.s = this.h.addEntry(
          statusEntryProperties,
          "status.progress",
          0
          /* StatusbarAlignment.LEFT */
        );
      }
    } else {
      this.s?.dispose();
      this.s = void 0;
    }
  }
  w(options3, callback, onDidCancel) {
    const progressStateModel = new class extends $3c {
      get step() {
        return this.c;
      }
      get done() {
        return this.f;
      }
      constructor() {
        super();
        this.a = this.B(new $ze());
        this.onDidReport = this.a.event;
        this.b = this.B(new $ze());
        this.onWillDispose = this.b.event;
        this.c = void 0;
        this.f = false;
        this.promise = callback(this);
        this.promise.finally(() => {
          this.dispose();
        });
      }
      report(step) {
        this.c = step;
        this.a.fire(step);
      }
      cancel(choice) {
        onDidCancel?.(choice);
        this.dispose();
      }
      dispose() {
        this.f = true;
        this.b.fire();
        super.dispose();
      }
    }();
    const createWindowProgress = () => {
      const promise = new $gi();
      this.t({
        location: 10,
        title: options3.title ? $U3(options3.title).toString() : void 0,
        // convert markdown links => string
        command: "notifications.showList",
        type: options3.type
      }, (progress) => {
        function reportProgress(step) {
          if (step.message) {
            progress.report({
              message: $U3(step.message).toString()
              // convert markdown links => string
            });
          }
        }
        if (progressStateModel.step) {
          reportProgress(progressStateModel.step);
        }
        const onDidReportListener = progressStateModel.onDidReport((step) => reportProgress(step));
        promise.p.finally(() => onDidReportListener.dispose());
        Event2.once(progressStateModel.onWillDispose)(() => promise.complete());
        return promise.p;
      });
      return $1c(() => promise.complete());
    };
    const createNotification = (message, priority, increment) => {
      const notificationDisposables = new $2c();
      const primaryActions = options3.primaryActions ? Array.from(options3.primaryActions) : [];
      const secondaryActions = options3.secondaryActions ? Array.from(options3.secondaryActions) : [];
      if (options3.buttons) {
        options3.buttons.forEach((button, index) => {
          const buttonAction = new class extends $Um {
            constructor() {
              super(`progress.button.${button}`, button, void 0, true);
            }
            async run() {
              progressStateModel.cancel(index);
            }
          }();
          notificationDisposables.add(buttonAction);
          primaryActions.push(buttonAction);
        });
      }
      if (options3.cancellable) {
        const cancelAction = new class extends $Um {
          constructor() {
            super("progress.cancel", typeof options3.cancellable === "string" ? options3.cancellable : localize(13079, null), void 0, true);
          }
          async run() {
            progressStateModel.cancel();
          }
        }();
        notificationDisposables.add(cancelAction);
        primaryActions.push(cancelAction);
      }
      const notification = this.g.notify({
        severity: Severity2.Info,
        message: $0l(message),
        // status entries support codicons, but notifications do not (https://github.com/microsoft/vscode/issues/145722)
        source: options3.source,
        actions: { primary: primaryActions, secondary: secondaryActions },
        progress: typeof increment === "number" && increment >= 0 ? { total: 100, worked: increment } : { infinite: true },
        priority
      });
      let windowProgressDisposable = void 0;
      const onVisibilityChange = (visible) => {
        $Xc(windowProgressDisposable);
        if (!visible && !progressStateModel.done) {
          windowProgressDisposable = createWindowProgress();
        }
      };
      notificationDisposables.add(notification.onDidChangeVisibility(onVisibilityChange));
      if (priority === NotificationPriority.SILENT) {
        onVisibilityChange(false);
      }
      Event2.once(notification.onDidClose)(() => notificationDisposables.dispose());
      return notification;
    };
    const updateProgress = (notification, increment) => {
      if (typeof increment === "number" && increment >= 0) {
        notification.progress.total(100);
        notification.progress.worked(increment);
      } else {
        notification.progress.infinite();
      }
    };
    let notificationHandle;
    let notificationTimeout;
    let titleAndMessage;
    const updateNotification = (step) => {
      if (step?.message && options3.title) {
        titleAndMessage = `${options3.title}: ${step.message}`;
      } else {
        titleAndMessage = options3.title || step?.message;
      }
      if (!notificationHandle && titleAndMessage) {
        if (typeof options3.delay === "number" && options3.delay > 0) {
          if (typeof notificationTimeout !== "number") {
            notificationTimeout = setTimeout(() => notificationHandle = createNotification(titleAndMessage, options3.priority, step?.increment), options3.delay);
          }
        } else {
          notificationHandle = createNotification(titleAndMessage, options3.priority, step?.increment);
        }
      }
      if (notificationHandle) {
        if (titleAndMessage) {
          notificationHandle.updateMessage(titleAndMessage);
        }
        if (typeof step?.increment === "number") {
          updateProgress(notificationHandle, step.increment);
        }
      }
    };
    updateNotification(progressStateModel.step);
    const listener = progressStateModel.onDidReport((step) => updateNotification(step));
    Event2.once(progressStateModel.onWillDispose)(() => listener.dispose());
    (async () => {
      try {
        if (typeof options3.delay === "number" && options3.delay > 0) {
          await progressStateModel.promise;
        } else {
          await Promise.all([$Wh(800), progressStateModel.promise]);
        }
      } finally {
        clearTimeout(notificationTimeout);
        notificationHandle?.close();
      }
    })();
    return progressStateModel.promise;
  }
  y(paneCompositeId, viewContainerLocation, task, options3) {
    const progressIndicator = this.b.getProgressIndicator(paneCompositeId, viewContainerLocation);
    const promise = progressIndicator ? this.D(progressIndicator, task, options3) : task({ report: () => {
    } });
    if (viewContainerLocation === 0) {
      this.C(paneCompositeId, options3, promise);
    }
    return promise;
  }
  z(viewId, task, options3) {
    const progressIndicator = this.f.getViewProgressIndicator(viewId);
    const promise = progressIndicator ? this.D(progressIndicator, task, options3) : task({ report: () => {
    } });
    const location3 = this.c.getViewLocationById(viewId);
    if (location3 !== 0) {
      return promise;
    }
    const viewletId = this.c.getViewContainerByViewId(viewId)?.id;
    if (viewletId === void 0) {
      return promise;
    }
    this.C(viewletId, options3, promise);
    return promise;
  }
  C(viewletId, options3, promise) {
    let activityProgress;
    let delayHandle = setTimeout(() => {
      delayHandle = void 0;
      const handle2 = this.a.showViewContainerActivity(viewletId, { badge: new $yqb(() => ""), priority: 100 });
      const startTimeVisible = Date.now();
      const minTimeVisible = 300;
      activityProgress = {
        dispose() {
          const d = Date.now() - startTimeVisible;
          if (d < minTimeVisible) {
            setTimeout(() => handle2.dispose(), minTimeVisible - d);
          } else {
            handle2.dispose();
          }
        }
      };
    }, options3.delay || 300);
    promise.finally(() => {
      clearTimeout(delayHandle);
      $Xc(activityProgress);
    });
  }
  D(progressIndicator, task, options3) {
    let discreteProgressRunner = void 0;
    function updateProgress(stepOrTotal) {
      let total = void 0;
      let increment = void 0;
      if (typeof stepOrTotal !== "undefined") {
        if (typeof stepOrTotal === "number") {
          total = stepOrTotal;
        } else if (typeof stepOrTotal.increment === "number") {
          total = stepOrTotal.total ?? 100;
          increment = stepOrTotal.increment;
        }
      }
      if (typeof total === "number") {
        if (!discreteProgressRunner) {
          discreteProgressRunner = progressIndicator.show(total, options3.delay);
          promise.catch(
            () => void 0
            /* ignore */
          ).finally(() => discreteProgressRunner?.done());
        }
        if (typeof increment === "number") {
          discreteProgressRunner.worked(increment);
        }
      } else {
        discreteProgressRunner?.done();
        progressIndicator.showWhile(promise, options3.delay);
      }
      return discreteProgressRunner;
    }
    const promise = task({
      report: (progress) => {
        updateProgress(progress);
      }
    });
    updateProgress(options3.total);
    return promise;
  }
  F(options3, task, onDidCancel) {
    const disposables = new $2c();
    const allowableCommands = [
      "workbench.action.quit",
      "workbench.action.reloadWindow",
      "copy",
      "cut",
      "editor.action.clipboardCopyAction",
      "editor.action.clipboardCutAction"
    ];
    let dialog;
    const createDialog = (message) => {
      const buttons = options3.buttons || [];
      if (!options3.sticky) {
        buttons.push(options3.cancellable ? typeof options3.cancellable === "boolean" ? localize(13080, null) : options3.cancellable : localize(13081, null));
      }
      dialog = new $K2(this.j.activeContainer, message, buttons, {
        type: "pending",
        detail: options3.detail,
        cancelId: buttons.length - 1,
        disableCloseAction: options3.sticky,
        disableDefaultAction: options3.sticky,
        keyEventProcessor: (event) => {
          const resolved = this.m.softDispatch(event, this.j.activeContainer);
          if (resolved.kind === 2 && resolved.commandId) {
            if (!allowableCommands.includes(resolved.commandId)) {
              $9j.stop(event, true);
            }
          }
        },
        buttonStyles: $q$,
        checkboxStyles: $x$,
        inputBoxStyles: $B$,
        dialogStyles: $z$
      });
      disposables.add(dialog);
      dialog.show().then((dialogResult) => {
        onDidCancel?.(dialogResult.button);
        $Xc(dialog);
      });
      return dialog;
    };
    let delay = options3.delay ?? 0;
    let latestMessage = void 0;
    const scheduler = disposables.add(new $8h(() => {
      delay = 0;
      if (latestMessage && !dialog) {
        dialog = createDialog(latestMessage);
      } else if (latestMessage) {
        dialog.updateMessage(latestMessage);
      }
    }, 0));
    const updateDialog = function(message) {
      latestMessage = message;
      if (!scheduler.isScheduled()) {
        scheduler.schedule(delay);
      }
    };
    const promise = task({
      report: (progress) => {
        updateDialog(progress.message);
      }
    });
    promise.finally(() => {
      $Xc(disposables);
    });
    if (options3.title) {
      updateDialog(options3.title);
    }
    return promise;
  }
};
$uVb = __decorate([
  __param(0, $vqb),
  __param(1, $uqb),
  __param(2, $$M),
  __param(3, $uob),
  __param(4, $PJ),
  __param(5, $$qb),
  __param(6, $Ulb),
  __param(7, $Ty),
  __param(8, $QRb)
], $uVb);
$SC(
  $TJ,
  $uVb,
  1
  /* InstantiationType.Delayed */
);

// out-build/vs/editor/browser/services/abstractCodeEditorService.js
var $vVb = class $vVb2 extends $3c {
  constructor(z) {
    super();
    this.z = z;
    this.a = this.B(new $ze());
    this.onWillCreateCodeEditor = this.a.event;
    this.b = this.B(new $ze());
    this.onCodeEditorAdd = this.b.event;
    this.c = this.B(new $ze());
    this.onCodeEditorRemove = this.c.event;
    this.f = this.B(new $ze());
    this.onWillCreateDiffEditor = this.f.event;
    this.g = this.B(new $ze());
    this.onDiffEditorAdd = this.g.event;
    this.h = this.B(new $ze());
    this.onDiffEditorRemove = this.h.event;
    this.j = this.B(new $ze());
    this.onDidChangeTransientModelProperty = this.j.event;
    this.m = this.B(new $ze());
    this.onDecorationTypeRegistered = this.m.event;
    this.t = /* @__PURE__ */ new Map();
    this.u = /* @__PURE__ */ new Map();
    this.y = new $cd();
    this.G = {};
    this.H = /* @__PURE__ */ new Map();
    this.n = /* @__PURE__ */ Object.create(null);
    this.r = /* @__PURE__ */ Object.create(null);
    this.s = null;
  }
  willCreateCodeEditor() {
    this.a.fire();
  }
  addCodeEditor(editor) {
    this.n[editor.getId()] = editor;
    this.b.fire(editor);
  }
  removeCodeEditor(editor) {
    if (delete this.n[editor.getId()]) {
      this.c.fire(editor);
    }
  }
  listCodeEditors() {
    return Object.keys(this.n).map((id2) => this.n[id2]);
  }
  willCreateDiffEditor() {
    this.f.fire();
  }
  addDiffEditor(editor) {
    this.r[editor.getId()] = editor;
    this.g.fire(editor);
  }
  removeDiffEditor(editor) {
    if (delete this.r[editor.getId()]) {
      this.h.fire(editor);
    }
  }
  listDiffEditors() {
    return Object.keys(this.r).map((id2) => this.r[id2]);
  }
  getFocusedCodeEditor() {
    let editorWithWidgetFocus = null;
    const editors = this.listCodeEditors();
    for (const editor of editors) {
      if (editor.hasTextFocus()) {
        return editor;
      }
      if (editor.hasWidgetFocus()) {
        editorWithWidgetFocus = editor;
      }
    }
    return editorWithWidgetFocus;
  }
  C() {
    if (!this.s) {
      this.s = this.D();
    }
    return this.s;
  }
  D() {
    return new $xVb($VZ());
  }
  F(editor) {
    if (!editor) {
      return this.C();
    }
    const domNode = editor.getContainerDomNode();
    if (!$Jj(domNode)) {
      return this.C();
    }
    const editorId = editor.getId();
    if (!this.u.has(editorId)) {
      const refCountedStyleSheet = new RefCountedStyleSheet(this, editorId, $VZ(domNode));
      this.u.set(editorId, refCountedStyleSheet);
    }
    return this.u.get(editorId);
  }
  _removeEditorStyleSheets(editorId) {
    this.u.delete(editorId);
  }
  registerDecorationType(description, key2, options3, parentTypeKey, editor) {
    let provider = this.t.get(key2);
    if (!provider) {
      const styleSheet = this.F(editor);
      const providerArgs = {
        styleSheet,
        key: key2,
        parentTypeKey,
        options: options3 || /* @__PURE__ */ Object.create(null)
      };
      if (!parentTypeKey) {
        provider = new DecorationTypeOptionsProvider(description, this.z, styleSheet, providerArgs);
      } else {
        provider = new DecorationSubTypeOptionsProvider(this.z, styleSheet, providerArgs);
      }
      this.t.set(key2, provider);
      this.m.fire(key2);
    }
    provider.refCount++;
    return {
      dispose: () => {
        this.removeDecorationType(key2);
      }
    };
  }
  listDecorationTypes() {
    return Array.from(this.t.keys());
  }
  removeDecorationType(key2) {
    const provider = this.t.get(key2);
    if (provider) {
      provider.refCount--;
      if (provider.refCount <= 0) {
        this.t.delete(key2);
        provider.dispose();
        this.listCodeEditors().forEach((ed) => ed.removeDecorationsByType(key2));
      }
    }
  }
  resolveDecorationOptions(decorationTypeKey, writable) {
    const provider = this.t.get(decorationTypeKey);
    if (!provider) {
      throw new Error("Unknown decoration type key: " + decorationTypeKey);
    }
    return provider.getOptions(this, writable);
  }
  resolveDecorationCSSRules(decorationTypeKey) {
    const provider = this.t.get(decorationTypeKey);
    if (!provider) {
      return null;
    }
    return provider.resolveDecorationCSSRules();
  }
  setModelProperty(resource, key2, value) {
    const key1 = resource.toString();
    let dest;
    if (this.H.has(key1)) {
      dest = this.H.get(key1);
    } else {
      dest = /* @__PURE__ */ new Map();
      this.H.set(key1, dest);
    }
    dest.set(key2, value);
  }
  getModelProperty(resource, key2) {
    const key1 = resource.toString();
    if (this.H.has(key1)) {
      const innerMap = this.H.get(key1);
      return innerMap.get(key2);
    }
    return void 0;
  }
  setTransientModelProperty(model, key2, value) {
    const uri = model.uri.toString();
    let w;
    if (this.G.hasOwnProperty(uri)) {
      w = this.G[uri];
    } else {
      w = new $wVb(uri, model, this);
      this.G[uri] = w;
    }
    const previousValue = w.get(key2);
    if (previousValue !== value) {
      w.set(key2, value);
      this.j.fire(model);
    }
  }
  getTransientModelProperty(model, key2) {
    const uri = model.uri.toString();
    if (!this.G.hasOwnProperty(uri)) {
      return void 0;
    }
    return this.G[uri].get(key2);
  }
  getTransientModelProperties(model) {
    const uri = model.uri.toString();
    if (!this.G.hasOwnProperty(uri)) {
      return void 0;
    }
    return this.G[uri].keys().map((key2) => [key2, this.G[uri].get(key2)]);
  }
  _removeWatcher(w) {
    delete this.G[w.uri];
  }
  async openCodeEditor(input, source, sideBySide) {
    for (const handler of this.y) {
      const candidate = await handler(input, source, sideBySide);
      if (candidate !== null) {
        return candidate;
      }
    }
    return null;
  }
  registerCodeEditorOpenHandler(handler) {
    const rm = this.y.unshift(handler);
    return $1c(rm);
  }
};
$vVb = __decorate([
  __param(0, $gs)
], $vVb);
var $wVb = class {
  constructor(uri, model, owner) {
    this.uri = uri;
    this.a = {};
    model.onWillDispose(() => owner._removeWatcher(this));
  }
  set(key2, value) {
    this.a[key2] = value;
  }
  get(key2) {
    return this.a[key2];
  }
  keys() {
    return Object.keys(this.a);
  }
};
var RefCountedStyleSheet = class {
  get sheet() {
    return this.c.sheet;
  }
  constructor(parent, editorId, styleSheet) {
    this.a = parent;
    this.b = editorId;
    this.c = styleSheet;
    this.d = 0;
  }
  ref() {
    this.d++;
  }
  unref() {
    this.d--;
    if (this.d === 0) {
      this.c.remove();
      this.a._removeEditorStyleSheets(this.b);
    }
  }
  insertRule(selector, rule) {
    $XZ(selector, rule, this.c);
  }
  removeRulesContainingSelector(ruleName) {
    $YZ(ruleName, this.c);
  }
};
var $xVb = class {
  get sheet() {
    return this.a.sheet;
  }
  constructor(styleSheet) {
    this.a = styleSheet;
  }
  ref() {
  }
  unref() {
  }
  insertRule(selector, rule) {
    $XZ(selector, rule, this.a);
  }
  removeRulesContainingSelector(ruleName) {
    $YZ(ruleName, this.a);
  }
};
var DecorationSubTypeOptionsProvider = class {
  constructor(themeService, styleSheet, providerArgs) {
    this.a = styleSheet;
    this.a.ref();
    this.b = providerArgs.parentTypeKey;
    this.refCount = 0;
    this.c = new DecorationCSSRules(3, providerArgs, themeService);
    this.d = new DecorationCSSRules(4, providerArgs, themeService);
  }
  getOptions(codeEditorService, writable) {
    const options3 = codeEditorService.resolveDecorationOptions(this.b, true);
    if (this.c) {
      options3.beforeContentClassName = this.c.className;
    }
    if (this.d) {
      options3.afterContentClassName = this.d.className;
    }
    return options3;
  }
  resolveDecorationCSSRules() {
    return this.a.sheet.cssRules;
  }
  dispose() {
    if (this.c) {
      this.c.dispose();
      this.c = null;
    }
    if (this.d) {
      this.d.dispose();
      this.d = null;
    }
    this.a.unref();
  }
};
var DecorationTypeOptionsProvider = class {
  constructor(description, themeService, styleSheet, providerArgs) {
    this.a = new $2c();
    this.description = description;
    this.b = styleSheet;
    this.b.ref();
    this.refCount = 0;
    const createCSSRules = (type) => {
      const rules = new DecorationCSSRules(type, providerArgs, themeService);
      this.a.add(rules);
      if (rules.hasContent) {
        return rules.className;
      }
      return void 0;
    };
    const createInlineCSSRules = (type) => {
      const rules = new DecorationCSSRules(type, providerArgs, themeService);
      this.a.add(rules);
      if (rules.hasContent) {
        return { className: rules.className, hasLetterSpacing: rules.hasLetterSpacing };
      }
      return null;
    };
    this.className = createCSSRules(
      0
      /* ModelDecorationCSSRuleType.ClassName */
    );
    const inlineData = createInlineCSSRules(
      1
      /* ModelDecorationCSSRuleType.InlineClassName */
    );
    if (inlineData) {
      this.inlineClassName = inlineData.className;
      this.inlineClassNameAffectsLetterSpacing = inlineData.hasLetterSpacing;
    }
    this.beforeContentClassName = createCSSRules(
      3
      /* ModelDecorationCSSRuleType.BeforeContentClassName */
    );
    this.afterContentClassName = createCSSRules(
      4
      /* ModelDecorationCSSRuleType.AfterContentClassName */
    );
    if (providerArgs.options.beforeInjectedText && providerArgs.options.beforeInjectedText.contentText) {
      const beforeInlineData = createInlineCSSRules(
        5
        /* ModelDecorationCSSRuleType.BeforeInjectedTextClassName */
      );
      this.beforeInjectedText = {
        content: providerArgs.options.beforeInjectedText.contentText,
        inlineClassName: beforeInlineData?.className,
        inlineClassNameAffectsLetterSpacing: beforeInlineData?.hasLetterSpacing || providerArgs.options.beforeInjectedText.affectsLetterSpacing
      };
    }
    if (providerArgs.options.afterInjectedText && providerArgs.options.afterInjectedText.contentText) {
      const afterInlineData = createInlineCSSRules(
        6
        /* ModelDecorationCSSRuleType.AfterInjectedTextClassName */
      );
      this.afterInjectedText = {
        content: providerArgs.options.afterInjectedText.contentText,
        inlineClassName: afterInlineData?.className,
        inlineClassNameAffectsLetterSpacing: afterInlineData?.hasLetterSpacing || providerArgs.options.afterInjectedText.affectsLetterSpacing
      };
    }
    this.glyphMarginClassName = createCSSRules(
      2
      /* ModelDecorationCSSRuleType.GlyphMarginClassName */
    );
    const options3 = providerArgs.options;
    this.isWholeLine = Boolean(options3.isWholeLine);
    this.stickiness = options3.rangeBehavior;
    const lightOverviewRulerColor = options3.light && options3.light.overviewRulerColor || options3.overviewRulerColor;
    const darkOverviewRulerColor = options3.dark && options3.dark.overviewRulerColor || options3.overviewRulerColor;
    if (typeof lightOverviewRulerColor !== "undefined" || typeof darkOverviewRulerColor !== "undefined") {
      this.overviewRuler = {
        color: lightOverviewRulerColor || darkOverviewRulerColor,
        darkColor: darkOverviewRulerColor || lightOverviewRulerColor,
        position: options3.overviewRulerLane || OverviewRulerLane.Center
      };
    }
  }
  getOptions(codeEditorService, writable) {
    if (!writable) {
      return this;
    }
    return {
      description: this.description,
      inlineClassName: this.inlineClassName,
      beforeContentClassName: this.beforeContentClassName,
      afterContentClassName: this.afterContentClassName,
      className: this.className,
      glyphMarginClassName: this.glyphMarginClassName,
      isWholeLine: this.isWholeLine,
      overviewRuler: this.overviewRuler,
      stickiness: this.stickiness,
      before: this.beforeInjectedText,
      after: this.afterInjectedText
    };
  }
  resolveDecorationCSSRules() {
    return this.b.sheet.rules;
  }
  dispose() {
    this.a.dispose();
    this.b.unref();
  }
};
var $yVb = {
  color: "color:{0} !important;",
  opacity: "opacity:{0};",
  backgroundColor: "background-color:{0};",
  outline: "outline:{0};",
  outlineColor: "outline-color:{0};",
  outlineStyle: "outline-style:{0};",
  outlineWidth: "outline-width:{0};",
  border: "border:{0};",
  borderColor: "border-color:{0};",
  borderRadius: "border-radius:{0};",
  borderSpacing: "border-spacing:{0};",
  borderStyle: "border-style:{0};",
  borderWidth: "border-width:{0};",
  fontStyle: "font-style:{0};",
  fontWeight: "font-weight:{0};",
  fontSize: "font-size:{0};",
  fontFamily: "font-family:{0};",
  textDecoration: "text-decoration:{0};",
  cursor: "cursor:{0};",
  letterSpacing: "letter-spacing:{0};",
  gutterIconPath: "background:{0} center center no-repeat;",
  gutterIconSize: "background-size:{0};",
  contentText: "content:'{0}';",
  contentIconPath: "content:{0};",
  margin: "margin:{0};",
  padding: "padding:{0};",
  width: "width:{0};",
  height: "height:{0};",
  verticalAlign: "vertical-align:{0};"
};
var DecorationCSSRules = class {
  constructor(ruleType, providerArgs, themeService) {
    this.a = themeService.getColorTheme();
    this.f = ruleType;
    this.h = providerArgs;
    this.i = false;
    this.d = false;
    this.e = false;
    let className = CSSNameHelper.getClassName(this.h.key, ruleType);
    if (this.h.parentTypeKey) {
      className = className + " " + CSSNameHelper.getClassName(this.h.parentTypeKey, ruleType);
    }
    this.b = className;
    this.c = CSSNameHelper.getSelector(this.h.key, this.h.parentTypeKey, ruleType);
    this.j();
    if (this.i) {
      this.g = themeService.onDidColorThemeChange((theme) => {
        this.a = themeService.getColorTheme();
        this.k();
        this.j();
      });
    } else {
      this.g = null;
    }
  }
  dispose() {
    if (this.d) {
      this.k();
      this.d = false;
    }
    if (this.g) {
      this.g.dispose();
      this.g = null;
    }
  }
  get hasContent() {
    return this.d;
  }
  get hasLetterSpacing() {
    return this.e;
  }
  get className() {
    return this.b;
  }
  j() {
    const options3 = this.h.options;
    let unthemedCSS, lightCSS, darkCSS;
    switch (this.f) {
      case 0:
        unthemedCSS = this.l(options3);
        lightCSS = this.l(options3.light);
        darkCSS = this.l(options3.dark);
        break;
      case 1:
        unthemedCSS = this.m(options3);
        lightCSS = this.m(options3.light);
        darkCSS = this.m(options3.dark);
        break;
      case 2:
        unthemedCSS = this.o(options3);
        lightCSS = this.o(options3.light);
        darkCSS = this.o(options3.dark);
        break;
      case 3:
        unthemedCSS = this.n(options3.before);
        lightCSS = this.n(options3.light && options3.light.before);
        darkCSS = this.n(options3.dark && options3.dark.before);
        break;
      case 4:
        unthemedCSS = this.n(options3.after);
        lightCSS = this.n(options3.light && options3.light.after);
        darkCSS = this.n(options3.dark && options3.dark.after);
        break;
      case 5:
        unthemedCSS = this.n(options3.beforeInjectedText);
        lightCSS = this.n(options3.light && options3.light.beforeInjectedText);
        darkCSS = this.n(options3.dark && options3.dark.beforeInjectedText);
        break;
      case 6:
        unthemedCSS = this.n(options3.afterInjectedText);
        lightCSS = this.n(options3.light && options3.light.afterInjectedText);
        darkCSS = this.n(options3.dark && options3.dark.afterInjectedText);
        break;
      default:
        throw new Error("Unknown rule type: " + this.f);
    }
    const sheet = this.h.styleSheet;
    let hasContent = false;
    if (unthemedCSS.length > 0) {
      sheet.insertRule(this.c, unthemedCSS);
      hasContent = true;
    }
    if (lightCSS.length > 0) {
      sheet.insertRule(`.vs${this.c}, .hc-light${this.c}`, lightCSS);
      hasContent = true;
    }
    if (darkCSS.length > 0) {
      sheet.insertRule(`.vs-dark${this.c}, .hc-black${this.c}`, darkCSS);
      hasContent = true;
    }
    this.d = hasContent;
  }
  k() {
    this.h.styleSheet.removeRulesContainingSelector(this.c);
  }
  /**
   * Build the CSS for decorations styled via `className`.
   */
  l(opts) {
    if (!opts) {
      return "";
    }
    const cssTextArr = [];
    this.q(opts, ["backgroundColor"], cssTextArr);
    this.q(opts, ["outline", "outlineColor", "outlineStyle", "outlineWidth"], cssTextArr);
    this.p(opts, cssTextArr);
    return cssTextArr.join("");
  }
  /**
   * Build the CSS for decorations styled via `inlineClassName`.
   */
  m(opts) {
    if (!opts) {
      return "";
    }
    const cssTextArr = [];
    this.q(opts, ["fontStyle", "fontWeight", "textDecoration", "cursor", "color", "opacity", "letterSpacing"], cssTextArr);
    if (opts.letterSpacing) {
      this.e = true;
    }
    return cssTextArr.join("");
  }
  /**
   * Build the CSS for decorations styled before or after content.
   */
  n(opts) {
    if (!opts) {
      return "";
    }
    const cssTextArr = [];
    if (typeof opts !== "undefined") {
      this.p(opts, cssTextArr);
      if (typeof opts.contentIconPath !== "undefined") {
        cssTextArr.push($wf($yVb.contentIconPath, $5Z(URI.revive(opts.contentIconPath))));
      }
      if (typeof opts.contentText === "string") {
        const truncated = opts.contentText.match(/^.*$/m)[0];
        const escaped = truncated.replace(/['\\]/g, "\\$&");
        cssTextArr.push($wf($yVb.contentText, escaped));
      }
      this.q(opts, ["verticalAlign", "fontStyle", "fontWeight", "fontSize", "fontFamily", "textDecoration", "color", "opacity", "backgroundColor", "margin", "padding"], cssTextArr);
      if (this.q(opts, ["width", "height"], cssTextArr)) {
        cssTextArr.push("display:inline-block;");
      }
    }
    return cssTextArr.join("");
  }
  /**
   * Build the CSS for decorations styled via `glyphMarginClassName`.
   */
  o(opts) {
    if (!opts) {
      return "";
    }
    const cssTextArr = [];
    if (typeof opts.gutterIconPath !== "undefined") {
      cssTextArr.push($wf($yVb.gutterIconPath, $5Z(URI.revive(opts.gutterIconPath))));
      if (typeof opts.gutterIconSize !== "undefined") {
        cssTextArr.push($wf($yVb.gutterIconSize, opts.gutterIconSize));
      }
    }
    return cssTextArr.join("");
  }
  p(opts, cssTextArr) {
    if (this.q(opts, ["border", "borderColor", "borderRadius", "borderSpacing", "borderStyle", "borderWidth"], cssTextArr)) {
      cssTextArr.push($wf("box-sizing: border-box;"));
      return true;
    }
    return false;
  }
  q(opts, properties, cssTextArr) {
    const lenBefore = cssTextArr.length;
    for (const property of properties) {
      const value = this.r(opts[property]);
      if (typeof value === "string") {
        cssTextArr.push($wf($yVb[property], value));
      }
    }
    return cssTextArr.length !== lenBefore;
  }
  r(value) {
    if (isThemeColor(value)) {
      this.i = true;
      const color2 = this.a.getColor(value.id);
      if (color2) {
        return color2.toString();
      }
      return "transparent";
    }
    return value;
  }
};
var ModelDecorationCSSRuleType;
(function(ModelDecorationCSSRuleType2) {
  ModelDecorationCSSRuleType2[ModelDecorationCSSRuleType2["ClassName"] = 0] = "ClassName";
  ModelDecorationCSSRuleType2[ModelDecorationCSSRuleType2["InlineClassName"] = 1] = "InlineClassName";
  ModelDecorationCSSRuleType2[ModelDecorationCSSRuleType2["GlyphMarginClassName"] = 2] = "GlyphMarginClassName";
  ModelDecorationCSSRuleType2[ModelDecorationCSSRuleType2["BeforeContentClassName"] = 3] = "BeforeContentClassName";
  ModelDecorationCSSRuleType2[ModelDecorationCSSRuleType2["AfterContentClassName"] = 4] = "AfterContentClassName";
  ModelDecorationCSSRuleType2[ModelDecorationCSSRuleType2["BeforeInjectedTextClassName"] = 5] = "BeforeInjectedTextClassName";
  ModelDecorationCSSRuleType2[ModelDecorationCSSRuleType2["AfterInjectedTextClassName"] = 6] = "AfterInjectedTextClassName";
})(ModelDecorationCSSRuleType || (ModelDecorationCSSRuleType = {}));
var CSSNameHelper = class {
  static getClassName(key2, type) {
    return "ced-" + key2 + "-" + type;
  }
  static getSelector(key2, parentKey, ruleType) {
    let selector = ".monaco-editor ." + this.getClassName(key2, ruleType);
    if (parentKey) {
      selector = selector + "." + this.getClassName(parentKey, ruleType);
    }
    if (ruleType === 3) {
      selector += "::before";
    } else if (ruleType === 4) {
      selector += "::after";
    }
    return selector;
  }
};

// out-build/vs/workbench/services/editor/browser/codeEditorService.js
var $zVb = class $zVb2 extends $vVb {
  constructor(I, themeService, J) {
    super(themeService);
    this.I = I;
    this.J = J;
    this.B(this.registerCodeEditorOpenHandler(this.M.bind(this)));
    this.B(this.registerCodeEditorOpenHandler(this.L.bind(this)));
  }
  getActiveCodeEditor() {
    const activeTextEditorControl = this.I.activeTextEditorControl;
    if ($P5(activeTextEditorControl)) {
      return activeTextEditorControl;
    }
    if ($Q5(activeTextEditorControl)) {
      return activeTextEditorControl.getModifiedEditor();
    }
    const activeControl = this.I.activeEditorPane?.getControl();
    if ($R5(activeControl) && $P5(activeControl.activeCodeEditor)) {
      return activeControl.activeCodeEditor;
    }
    return null;
  }
  async L(input, source, sideBySide) {
    const activeTextEditorControl = this.I.activeTextEditorControl;
    if (!sideBySide && // we need the current active group to be the target
    $Q5(activeTextEditorControl) && // we only support this for active text diff editors
    input.options && // we need options to apply
    input.resource && // we need a request resource to compare with
    source === activeTextEditorControl.getModifiedEditor() && // we need the source of this request to be the modified side of the diff editor
    activeTextEditorControl.getModel() && // we need a target model to compare with
    $oh(input.resource, activeTextEditorControl.getModel()?.modified.uri)) {
      const targetEditor = activeTextEditorControl.getModifiedEditor();
      applyTextEditorOptions(
        input.options,
        targetEditor,
        0
        /* ScrollType.Smooth */
      );
      return targetEditor;
    }
    return null;
  }
  // Open using our normal editor service
  async M(input, source, sideBySide) {
    const enablePreviewFromCodeNavigation = this.J.getValue().workbench?.editor?.enablePreviewFromCodeNavigation;
    if (!enablePreviewFromCodeNavigation && // we only need to do this if the configuration requires it
    source && // we need to know the origin of the navigation
    !input.options?.pinned && // we only need to look at preview editors that open
    !sideBySide && // we only need to care if editor opens in same group
    !$oh(source.getModel()?.uri, input.resource)) {
      for (const visiblePane of this.I.visibleEditorPanes) {
        if ($S5(visiblePane.getControl()) === source) {
          visiblePane.group.pinEditor();
          break;
        }
      }
    }
    const control = await this.I.openEditor(input, sideBySide ? $oJ : $nJ);
    if (control) {
      const widget = control.getControl();
      if ($P5(widget)) {
        return widget;
      }
      if ($R5(widget) && $P5(widget.activeCodeEditor)) {
        return widget.activeCodeEditor;
      }
    }
    return null;
  }
};
$zVb = __decorate([
  __param(0, $mJ),
  __param(1, $gs),
  __param(2, $kl)
], $zVb);
$SC(
  $U5,
  $zVb,
  1
  /* InstantiationType.Delayed */
);

// out-build/vs/platform/keybinding/common/resolvedKeybindingItem.js
var $Py = class {
  constructor(resolvedKeybinding, command4, commandArgs, when, isDefault, extensionId, isBuiltinExtension) {
    this._resolvedKeybindingItemBrand = void 0;
    this.resolvedKeybinding = resolvedKeybinding;
    this.chords = resolvedKeybinding ? $Qy(resolvedKeybinding.getDispatchChords()) : [];
    if (resolvedKeybinding && this.chords.length === 0) {
      this.chords = $Qy(resolvedKeybinding.getSingleModifierDispatchChords());
    }
    this.bubble = command4 ? command4.charCodeAt(0) === 94 : false;
    this.command = this.bubble ? command4.substr(1) : command4;
    this.commandArgs = commandArgs;
    this.when = when;
    this.isDefault = isDefault;
    this.extensionId = extensionId;
    this.isBuiltinExtension = isBuiltinExtension;
  }
};
function $Qy(arr) {
  const result = [];
  for (let i2 = 0, len = arr.length; i2 < len; i2++) {
    const element = arr[i2];
    if (!element) {
      return [];
    }
    result.push(element);
  }
  return result;
}

// out-build/vs/workbench/services/keybinding/browser/unboundCommands.js
function $AVb(boundCommands) {
  const unboundCommands = [];
  const seenMap = /* @__PURE__ */ new Map();
  const addCommand = (id2, includeCommandWithArgs) => {
    if (seenMap.has(id2)) {
      return;
    }
    seenMap.set(id2, true);
    if (id2[0] === "_" || id2.indexOf("vscode.") === 0) {
      return;
    }
    if (boundCommands.get(id2) === true) {
      return;
    }
    if (!includeCommandWithArgs) {
      const command4 = $tn.getCommand(id2);
      if (command4 && typeof command4.metadata === "object" && $Qb(command4.metadata.args)) {
        return;
      }
    }
    unboundCommands.push(id2);
  };
  for (const menuItem of $dJ.getMenuItems($bJ.CommandPalette)) {
    if ($_I(menuItem)) {
      addCommand(menuItem.command.id, true);
    }
  }
  for (const editorAction of EditorExtensionsRegistry.getEditorActions()) {
    addCommand(editorAction.id, true);
  }
  for (const id2 of $tn.getCommands().keys()) {
    addCommand(id2, false);
  }
  return unboundCommands;
}

// out-build/vs/workbench/services/preferences/browser/keybindingsEditorModel.js
var $DVb_1;
var $BVb = "keybinding.entry.template";
var SOURCE_SYSTEM = localize(13029, null);
var SOURCE_EXTENSION = localize(13030, null);
var SOURCE_USER = localize(13031, null);
function $CVb(commandId, when) {
  const whenPart = when ? ` +when:${when}` : "";
  return `@command:${commandId}${whenPart}`;
}
var wordFilter = or($Ll, $Ql, $Ml);
var COMMAND_REGEX = /@command:\s*([^\+]+)/i;
var WHEN_REGEX = /\+when:\s*(.+)/i;
var SOURCE_REGEX = /@source:\s*(user|default|system|extension)/i;
var EXTENSION_REGEX = /@ext:\s*((".+")|([^\s]+))/i;
var KEYBINDING_REGEX = /@keybinding:\s*((\".+\")|(\S+))/i;
var $DVb = $DVb_1 = class $DVb2 extends $rG {
  constructor(os, n, r2) {
    super();
    this.n = n;
    this.r = r2;
    this.c = [];
    this.g = [];
    this.j = {
      ui: $X2.modifierLabels[os],
      aria: $Y2.modifierLabels[os],
      user: $12.modifierLabels[os]
    };
  }
  fetch(searchValue, sortByPrecedence = false) {
    let keybindingItems = sortByPrecedence ? this.g : this.c;
    const commandIdMatches = COMMAND_REGEX.exec(searchValue);
    if (commandIdMatches && commandIdMatches[1]) {
      const command4 = commandIdMatches[1].trim();
      let filteredKeybindingItems = keybindingItems.filter((k) => k.command === command4);
      if (filteredKeybindingItems.length) {
        const whenMatches = WHEN_REGEX.exec(searchValue);
        if (whenMatches && whenMatches[1]) {
          const whenValue = whenMatches[1].trim();
          filteredKeybindingItems = this.w(filteredKeybindingItems, command4, whenValue);
        }
      }
      return filteredKeybindingItems.map((keybindingItem) => ({ id: $DVb_1.z(keybindingItem), keybindingItem, templateId: $BVb }));
    }
    if (SOURCE_REGEX.test(searchValue)) {
      keybindingItems = this.s(keybindingItems, searchValue);
      searchValue = searchValue.replace(SOURCE_REGEX, "");
    } else {
      const extensionMatches = EXTENSION_REGEX.exec(searchValue);
      if (extensionMatches && (extensionMatches[2] || extensionMatches[3])) {
        const extensionId = extensionMatches[2] ? extensionMatches[2].substring(1, extensionMatches[2].length - 1) : extensionMatches[3];
        keybindingItems = this.t(keybindingItems, extensionId);
        searchValue = searchValue.replace(EXTENSION_REGEX, "");
      } else {
        const keybindingMatches = KEYBINDING_REGEX.exec(searchValue);
        if (keybindingMatches && (keybindingMatches[2] || keybindingMatches[3])) {
          searchValue = keybindingMatches[2] || `"${keybindingMatches[3]}"`;
        }
      }
    }
    searchValue = searchValue.trim();
    if (!searchValue) {
      return keybindingItems.map((keybindingItem) => ({ id: $DVb_1.z(keybindingItem), keybindingItem, templateId: $BVb }));
    }
    return this.u(keybindingItems, searchValue);
  }
  s(keybindingItems, searchValue) {
    if (/@source:\s*default/i.test(searchValue) || /@source:\s*system/i.test(searchValue)) {
      return keybindingItems.filter((k) => k.source === SOURCE_SYSTEM);
    }
    if (/@source:\s*user/i.test(searchValue)) {
      return keybindingItems.filter((k) => k.source === SOURCE_USER);
    }
    if (/@source:\s*extension/i.test(searchValue)) {
      return keybindingItems.filter((k) => !$zg(k.source) || k.source === SOURCE_EXTENSION);
    }
    return keybindingItems;
  }
  t(keybindingItems, extension) {
    extension = extension.toLowerCase().trim();
    return keybindingItems.filter((k) => !$zg(k.source) && ($5z.equals(k.source.identifier, extension) || k.source.displayName?.toLowerCase() === extension.toLowerCase()));
  }
  u(keybindingItems, searchValue) {
    const quoteAtFirstChar = searchValue.charAt(0) === '"';
    const quoteAtLastChar = searchValue.charAt(searchValue.length - 1) === '"';
    const completeMatch = quoteAtFirstChar && quoteAtLastChar;
    if (quoteAtFirstChar) {
      searchValue = searchValue.substring(1);
    }
    if (quoteAtLastChar) {
      searchValue = searchValue.substring(0, searchValue.length - 1);
    }
    searchValue = searchValue.trim();
    const result = [];
    const words = searchValue.split(" ");
    const keybindingWords = this.y(words);
    for (const keybindingItem of keybindingItems) {
      const keybindingMatches = new KeybindingItemMatches(this.j, keybindingItem, searchValue, words, keybindingWords, completeMatch);
      if (keybindingMatches.commandIdMatches || keybindingMatches.commandLabelMatches || keybindingMatches.commandDefaultLabelMatches || keybindingMatches.sourceMatches || keybindingMatches.whenMatches || keybindingMatches.keybindingMatches || keybindingMatches.extensionIdMatches || keybindingMatches.extensionLabelMatches) {
        result.push({
          id: $DVb_1.z(keybindingItem),
          templateId: $BVb,
          commandLabelMatches: keybindingMatches.commandLabelMatches || void 0,
          commandDefaultLabelMatches: keybindingMatches.commandDefaultLabelMatches || void 0,
          keybindingItem,
          keybindingMatches: keybindingMatches.keybindingMatches || void 0,
          commandIdMatches: keybindingMatches.commandIdMatches || void 0,
          sourceMatches: keybindingMatches.sourceMatches || void 0,
          whenMatches: keybindingMatches.whenMatches || void 0,
          extensionIdMatches: keybindingMatches.extensionIdMatches || void 0,
          extensionLabelMatches: keybindingMatches.extensionLabelMatches || void 0
        });
      }
    }
    return result;
  }
  w(keybindingItems, command4, when) {
    if (keybindingItems.length === 0) {
      return [];
    }
    const keybindingItemsWithWhen = keybindingItems.filter((k) => k.when === when);
    if (keybindingItemsWithWhen.length) {
      return keybindingItemsWithWhen;
    }
    const commandLabel = keybindingItems[0].commandLabel;
    const keybindingItem = new $Py(void 0, command4, null, $7m.deserialize(when), false, null, false);
    const actionLabels = /* @__PURE__ */ new Map([[command4, commandLabel]]);
    return [$DVb_1.F(command4, keybindingItem, actionLabels, this.C())];
  }
  y(wordsSeparatedBySpaces) {
    const result = [];
    for (const word of wordsSeparatedBySpaces) {
      result.push(...$Mb(word.split("+")));
    }
    return result;
  }
  async resolve(actionLabels = /* @__PURE__ */ new Map()) {
    const extensions = this.C();
    this.g = [];
    const boundCommands = /* @__PURE__ */ new Map();
    for (const keybinding of this.n.getKeybindings()) {
      if (keybinding.command) {
        this.g.push($DVb_1.F(keybinding.command, keybinding, actionLabels, extensions));
        boundCommands.set(keybinding.command, true);
      }
    }
    const commandsWithDefaultKeybindings = this.n.getDefaultKeybindings().map((keybinding) => keybinding.command);
    for (const command4 of $AVb(boundCommands)) {
      const keybindingItem = new $Py(void 0, command4, null, void 0, commandsWithDefaultKeybindings.indexOf(command4) === -1, null, false);
      this.g.push($DVb_1.F(command4, keybindingItem, actionLabels, extensions));
    }
    this.g = $Rb(this.g, (keybindingItem) => $DVb_1.z(keybindingItem));
    this.c = this.g.slice(0).sort((a, b) => $DVb_1.D(a, b));
    return super.resolve();
  }
  static z(keybindingItem) {
    return keybindingItem.command + (keybindingItem?.keybinding?.getAriaLabel() ?? "") + keybindingItem.when + ($zg(keybindingItem.source) ? keybindingItem.source : keybindingItem.source.identifier.value);
  }
  C() {
    const extensions = new $7z();
    for (const extension of this.r.extensions) {
      extensions.set(extension.identifier, extension);
    }
    return extensions;
  }
  static D(a, b) {
    if (a.keybinding && !b.keybinding) {
      return -1;
    }
    if (b.keybinding && !a.keybinding) {
      return 1;
    }
    if (a.commandLabel && !b.commandLabel) {
      return -1;
    }
    if (b.commandLabel && !a.commandLabel) {
      return 1;
    }
    if (a.commandLabel && b.commandLabel) {
      if (a.commandLabel !== b.commandLabel) {
        return a.commandLabel.localeCompare(b.commandLabel);
      }
    }
    if (a.command === b.command) {
      return a.keybindingItem.isDefault ? 1 : -1;
    }
    return a.command.localeCompare(b.command);
  }
  static F(command4, keybindingItem, actions, extensions) {
    const menuCommand = $dJ.getCommand(command4);
    const editorActionLabel = actions.get(command4);
    let source = SOURCE_USER;
    if (keybindingItem.isDefault) {
      const extensionId = keybindingItem.extensionId ?? (keybindingItem.resolvedKeybinding ? void 0 : menuCommand?.source?.id);
      source = extensionId ? extensions.get(extensionId) ?? SOURCE_EXTENSION : SOURCE_SYSTEM;
    }
    return {
      keybinding: keybindingItem.resolvedKeybinding,
      keybindingItem,
      command: command4,
      commandLabel: $DVb_1.H(menuCommand, editorActionLabel),
      commandDefaultLabel: $DVb_1.G(menuCommand),
      when: keybindingItem.when ? keybindingItem.when.serialize() : "",
      source
    };
  }
  static G(menuCommand) {
    if (!Language.isDefaultVariant()) {
      if (menuCommand && menuCommand.title && menuCommand.title.original) {
        const category8 = menuCommand.category ? menuCommand.category.original : void 0;
        const title = menuCommand.title.original;
        return category8 ? localize(13032, null, category8, title) : title;
      }
    }
    return null;
  }
  static H(menuCommand, editorActionLabel) {
    if (menuCommand) {
      const category8 = menuCommand.category ? typeof menuCommand.category === "string" ? menuCommand.category : menuCommand.category.value : void 0;
      const title = typeof menuCommand.title === "string" ? menuCommand.title : menuCommand.title.value;
      return category8 ? localize(13033, null, category8, title) : title;
    }
    if (editorActionLabel) {
      return editorActionLabel;
    }
    return "";
  }
};
$DVb = $DVb_1 = __decorate([
  __param(1, $Ty),
  __param(2, $wN)
], $DVb);
var KeybindingItemMatches = class {
  constructor(c, keybindingItem, searchValue, words, keybindingWords, completeMatch) {
    this.c = c;
    this.commandIdMatches = null;
    this.commandLabelMatches = null;
    this.commandDefaultLabelMatches = null;
    this.sourceMatches = null;
    this.whenMatches = null;
    this.keybindingMatches = null;
    this.extensionIdMatches = null;
    this.extensionLabelMatches = null;
    if (!completeMatch) {
      this.commandIdMatches = this.d(searchValue, keybindingItem.command, or($Ql, $Pl), words);
      this.commandLabelMatches = keybindingItem.commandLabel ? this.d(searchValue, keybindingItem.commandLabel, (word, wordToMatchAgainst) => $Ql(word, keybindingItem.commandLabel, true), words) : null;
      this.commandDefaultLabelMatches = keybindingItem.commandDefaultLabel ? this.d(searchValue, keybindingItem.commandDefaultLabel, (word, wordToMatchAgainst) => $Ql(word, keybindingItem.commandDefaultLabel, true), words) : null;
      this.whenMatches = keybindingItem.when ? this.d(null, keybindingItem.when, or($Ql, $Pl), words) : null;
      if ($zg(keybindingItem.source)) {
        this.sourceMatches = this.d(searchValue, keybindingItem.source, (word, wordToMatchAgainst) => $Ql(word, keybindingItem.source, true), words);
      } else {
        this.extensionLabelMatches = keybindingItem.source.displayName ? this.d(searchValue, keybindingItem.source.displayName, (word, wordToMatchAgainst) => $Ql(word, keybindingItem.commandLabel, true), words) : null;
      }
    }
    this.keybindingMatches = keybindingItem.keybinding ? this.g(keybindingItem.keybinding, searchValue, keybindingWords, completeMatch) : null;
  }
  d(searchValue, wordToMatchAgainst, wordMatchesFilter, words) {
    let matches = searchValue ? wordFilter(searchValue, wordToMatchAgainst) : null;
    if (!matches) {
      matches = this.e(words, wordToMatchAgainst, wordMatchesFilter);
    }
    if (matches) {
      matches = this.f(matches);
    }
    return matches;
  }
  e(words, wordToMatchAgainst, wordMatchesFilter) {
    let matches = [];
    for (const word of words) {
      const wordMatches = wordMatchesFilter(word, wordToMatchAgainst);
      if (wordMatches) {
        matches = [...matches || [], ...wordMatches];
      } else {
        matches = null;
        break;
      }
    }
    return matches;
  }
  f(matches) {
    return $Rb(matches, (a) => a.start + "." + a.end).filter((match) => !matches.some((m) => !(m.start === match.start && m.end === match.end) && (m.start <= match.start && m.end >= match.end))).sort((a, b) => a.start - b.start);
  }
  g(keybinding, searchValue, words, completeMatch) {
    const [firstPart, chordPart] = keybinding.getChords();
    const userSettingsLabel = keybinding.getUserSettingsLabel();
    const ariaLabel = keybinding.getAriaLabel();
    const label3 = keybinding.getLabel();
    if (userSettingsLabel && $Vf(searchValue, userSettingsLabel) === 0 || ariaLabel && $Vf(searchValue, ariaLabel) === 0 || label3 && $Vf(searchValue, label3) === 0) {
      return {
        firstPart: this.r(firstPart),
        chordPart: this.r(chordPart)
      };
    }
    const firstPartMatch = {};
    let chordPartMatch = {};
    const matchedWords = [];
    const firstPartMatchedWords = [];
    let chordPartMatchedWords = [];
    let matchFirstPart = true;
    for (let index = 0; index < words.length; index++) {
      const word = words[index];
      let firstPartMatched = false;
      let chordPartMatched = false;
      matchFirstPart = matchFirstPart && !firstPartMatch.keyCode;
      let matchChordPart = !chordPartMatch.keyCode;
      if (matchFirstPart) {
        firstPartMatched = this.h(firstPart, firstPartMatch, word, completeMatch);
        if (firstPartMatch.keyCode) {
          for (const cordPartMatchedWordIndex of chordPartMatchedWords) {
            if (firstPartMatchedWords.indexOf(cordPartMatchedWordIndex) === -1) {
              matchedWords.splice(matchedWords.indexOf(cordPartMatchedWordIndex), 1);
            }
          }
          chordPartMatch = {};
          chordPartMatchedWords = [];
          matchChordPart = false;
        }
      }
      if (matchChordPart) {
        chordPartMatched = this.h(chordPart, chordPartMatch, word, completeMatch);
      }
      if (firstPartMatched) {
        firstPartMatchedWords.push(index);
      }
      if (chordPartMatched) {
        chordPartMatchedWords.push(index);
      }
      if (firstPartMatched || chordPartMatched) {
        matchedWords.push(index);
      }
      matchFirstPart = matchFirstPart && this.s(word);
    }
    if (matchedWords.length !== words.length) {
      return null;
    }
    if (completeMatch) {
      if (!this.q(firstPart, firstPartMatch)) {
        return null;
      }
      if (!$Mg(chordPartMatch) && !this.q(chordPart, chordPartMatch)) {
        return null;
      }
    }
    return this.p(firstPartMatch) || this.p(chordPartMatch) ? { firstPart: firstPartMatch, chordPart: chordPartMatch } : null;
  }
  h(chord, match, word, completeMatch) {
    let matched = false;
    if (this.j(chord, word)) {
      matched = true;
      match.metaKey = true;
    }
    if (this.l(chord, word)) {
      matched = true;
      match.ctrlKey = true;
    }
    if (this.n(chord, word)) {
      matched = true;
      match.shiftKey = true;
    }
    if (this.o(chord, word)) {
      matched = true;
      match.altKey = true;
    }
    if (this.i(chord, word, completeMatch)) {
      match.keyCode = true;
      matched = true;
    }
    return matched;
  }
  i(chord, word, completeMatch) {
    if (!chord) {
      return false;
    }
    const ariaLabel = chord.keyAriaLabel || "";
    if (completeMatch || ariaLabel.length === 1 || word.length === 1) {
      if ($Vf(ariaLabel, word) === 0) {
        return true;
      }
    } else {
      if ($Ml(word, ariaLabel)) {
        return true;
      }
    }
    return false;
  }
  j(chord, word) {
    if (!chord) {
      return false;
    }
    if (!chord.metaKey) {
      return false;
    }
    return this.v(word);
  }
  l(chord, word) {
    if (!chord) {
      return false;
    }
    if (!chord.ctrlKey) {
      return false;
    }
    return this.u(word);
  }
  n(chord, word) {
    if (!chord) {
      return false;
    }
    if (!chord.shiftKey) {
      return false;
    }
    return this.w(word);
  }
  o(chord, word) {
    if (!chord) {
      return false;
    }
    if (!chord.altKey) {
      return false;
    }
    return this.t(word);
  }
  p(keybindingMatch) {
    return !!keybindingMatch.altKey || !!keybindingMatch.ctrlKey || !!keybindingMatch.metaKey || !!keybindingMatch.shiftKey || !!keybindingMatch.keyCode;
  }
  q(chord, match) {
    if (!chord) {
      return true;
    }
    if (!match.keyCode) {
      return false;
    }
    if (chord.metaKey && !match.metaKey) {
      return false;
    }
    if (chord.altKey && !match.altKey) {
      return false;
    }
    if (chord.ctrlKey && !match.ctrlKey) {
      return false;
    }
    if (chord.shiftKey && !match.shiftKey) {
      return false;
    }
    return true;
  }
  r(chord) {
    const match = {};
    if (chord) {
      match.keyCode = true;
      if (chord.metaKey) {
        match.metaKey = true;
      }
      if (chord.altKey) {
        match.altKey = true;
      }
      if (chord.ctrlKey) {
        match.ctrlKey = true;
      }
      if (chord.shiftKey) {
        match.shiftKey = true;
      }
    }
    return match;
  }
  s(word) {
    if (this.t(word)) {
      return true;
    }
    if (this.u(word)) {
      return true;
    }
    if (this.v(word)) {
      return true;
    }
    if (this.w(word)) {
      return true;
    }
    return false;
  }
  t(word) {
    if ($1f(this.c.ui.altKey, word)) {
      return true;
    }
    if ($1f(this.c.aria.altKey, word)) {
      return true;
    }
    if ($1f(this.c.user.altKey, word)) {
      return true;
    }
    if ($1f(localize(13034, null), word)) {
      return true;
    }
    return false;
  }
  u(word) {
    if ($1f(this.c.ui.ctrlKey, word)) {
      return true;
    }
    if ($1f(this.c.aria.ctrlKey, word)) {
      return true;
    }
    if ($1f(this.c.user.ctrlKey, word)) {
      return true;
    }
    return false;
  }
  v(word) {
    if ($1f(this.c.ui.metaKey, word)) {
      return true;
    }
    if ($1f(this.c.aria.metaKey, word)) {
      return true;
    }
    if ($1f(this.c.user.metaKey, word)) {
      return true;
    }
    if ($1f(localize(13035, null), word)) {
      return true;
    }
    return false;
  }
  w(word) {
    if ($1f(this.c.ui.shiftKey, word)) {
      return true;
    }
    if ($1f(this.c.aria.shiftKey, word)) {
      return true;
    }
    if ($1f(this.c.user.shiftKey, word)) {
      return true;
    }
    return false;
  }
};

// out-build/vs/workbench/services/preferences/browser/keybindingsEditorInput.js
var $EVb_1;
var KeybindingsEditorIcon = $9r("keybindings-editor-label-icon", $6l.keyboard, localize(13027, null));
var $EVb = class $EVb2 extends $nG {
  static {
    $EVb_1 = this;
  }
  static {
    this.ID = "workbench.input.keybindings";
  }
  constructor(instantiationService) {
    super();
    this.searchOptions = null;
    this.resource = void 0;
    this.keybindingsModel = instantiationService.createInstance($DVb, OS);
  }
  get typeId() {
    return $EVb_1.ID;
  }
  getName() {
    return localize(13028, null);
  }
  getIcon() {
    return KeybindingsEditorIcon;
  }
  async resolve() {
    return this.keybindingsModel;
  }
  matches(otherInput) {
    return otherInput instanceof $EVb_1;
  }
  dispose() {
    this.keybindingsModel.dispose();
    super.dispose();
  }
};
$EVb = $EVb_1 = __decorate([
  __param(0, $Pk)
], $EVb);

// out-build/vs/workbench/services/preferences/common/preferencesEditorInput.js
var $FVb_1;
var SettingsEditorIcon = $9r("settings-editor-label-icon", $6l.settings, localize(13041, null));
var $FVb = class $FVb2 extends $nG {
  static {
    $FVb_1 = this;
  }
  static {
    this.ID = "workbench.input.settings2";
  }
  constructor(_preferencesService) {
    super();
    this.resource = URI.from({
      scheme: Schemas.vscodeSettings,
      path: `settingseditor`
    });
    this.a = _preferencesService.createSettings2EditorModel();
  }
  matches(otherInput) {
    return super.matches(otherInput) || otherInput instanceof $FVb_1;
  }
  get typeId() {
    return $FVb_1.ID;
  }
  getName() {
    return localize(13042, null);
  }
  getIcon() {
    return SettingsEditorIcon;
  }
  async resolve() {
    return this.a;
  }
  dispose() {
    this.a.dispose();
    super.dispose();
  }
};
$FVb = $FVb_1 = __decorate([
  __param(0, $TK)
], $FVb);

// out-build/vs/workbench/services/preferences/common/preferencesValidation.js
function canBeType(propTypes, ...types) {
  return types.some((t) => propTypes.includes(t));
}
function isNullOrEmpty(value) {
  return value === "" || $Ig(value);
}
function $HK(prop) {
  const type = Array.isArray(prop.type) ? prop.type : [prop.type];
  const isNullable = canBeType(type, "null");
  const isNumeric = (canBeType(type, "number") || canBeType(type, "integer")) && (type.length === 1 || type.length === 2 && isNullable);
  const numericValidations = getNumericValidators(prop);
  const stringValidations = getStringValidators(prop);
  const arrayValidator = getArrayValidator(prop);
  const objectValidator = getObjectValidator(prop);
  return (value) => {
    if (isNullable && isNullOrEmpty(value)) {
      return "";
    }
    const errors = [];
    if (arrayValidator) {
      const err = arrayValidator(value);
      if (err) {
        errors.push(err);
      }
    }
    if (objectValidator) {
      const err = objectValidator(value);
      if (err) {
        errors.push(err);
      }
    }
    if (prop.type === "boolean" && value !== true && value !== false) {
      errors.push(localize(13045, null));
    }
    if (isNumeric) {
      if (isNullOrEmpty(value) || typeof value === "boolean" || Array.isArray(value) || isNaN(+value)) {
        errors.push(localize(13046, null));
      } else {
        errors.push(...numericValidations.filter((validator) => !validator.isValid(+value)).map((validator) => validator.message));
      }
    }
    if (prop.type === "string") {
      if (prop.enum && !$Ag(prop.enum)) {
        errors.push(localize(13047, null));
      } else if (!$zg(value)) {
        errors.push(localize(13048, null));
      } else {
        errors.push(...stringValidations.filter((validator) => !validator.isValid(value)).map((validator) => validator.message));
      }
    }
    if (errors.length) {
      return prop.errorMessage ? [prop.errorMessage, ...errors].join(" ") : errors.join(" ");
    }
    return "";
  };
}
function $IK(value, type) {
  if (typeof type === "undefined") {
    return;
  }
  const typeArr = Array.isArray(type) ? type : [type];
  if (!typeArr.some((_type) => valueValidatesAsType(value, _type))) {
    return localize(13049, null, JSON.stringify(type));
  }
  return;
}
function valueValidatesAsType(value, type) {
  const valueType = typeof value;
  if (type === "boolean") {
    return valueType === "boolean";
  } else if (type === "object") {
    return value && !Array.isArray(value) && valueType === "object";
  } else if (type === "null") {
    return value === null;
  } else if (type === "array") {
    return Array.isArray(value);
  } else if (type === "string") {
    return valueType === "string";
  } else if (type === "number" || type === "integer") {
    return valueType === "number";
  }
  return true;
}
function toRegExp2(pattern) {
  try {
    return new RegExp(pattern, "u");
  } catch (e) {
    try {
      return new RegExp(pattern);
    } catch (e2) {
      console.error(localize(13050, null), pattern);
      return /.*/;
    }
  }
}
function getStringValidators(prop) {
  const uriRegex = /^(([^:/?#]+?):)?(\/\/([^/?#]*))?([^?#]*)(\?([^#]*))?(#(.*))?/;
  let patternRegex;
  if (typeof prop.pattern === "string") {
    patternRegex = toRegExp2(prop.pattern);
  }
  return [
    {
      enabled: prop.maxLength !== void 0,
      isValid: (value) => value.length <= prop.maxLength,
      message: localize(13051, null, prop.maxLength)
    },
    {
      enabled: prop.minLength !== void 0,
      isValid: (value) => value.length >= prop.minLength,
      message: localize(13052, null, prop.minLength)
    },
    {
      enabled: patternRegex !== void 0,
      isValid: (value) => patternRegex.test(value),
      message: prop.patternErrorMessage || localize(13053, null, prop.pattern)
    },
    {
      enabled: prop.format === "color-hex",
      isValid: (value) => $Vn.Format.CSS.parseHex(value),
      message: localize(13054, null)
    },
    {
      enabled: prop.format === "uri" || prop.format === "uri-reference",
      isValid: (value) => !!value.length,
      message: localize(13055, null)
    },
    {
      enabled: prop.format === "uri" || prop.format === "uri-reference",
      isValid: (value) => uriRegex.test(value),
      message: localize(13056, null)
    },
    {
      enabled: prop.format === "uri",
      isValid: (value) => {
        const matches = value.match(uriRegex);
        return !!(matches && matches[2]);
      },
      message: localize(13057, null)
    },
    {
      enabled: prop.enum !== void 0,
      isValid: (value) => {
        return prop.enum.includes(value);
      },
      message: localize(13058, null, prop.enum ? prop.enum.map((key2) => `"${key2}"`).join(", ") : "[]")
    }
  ].filter((validation) => validation.enabled);
}
function getNumericValidators(prop) {
  const type = Array.isArray(prop.type) ? prop.type : [prop.type];
  const isNullable = canBeType(type, "null");
  const isIntegral = canBeType(type, "integer") && (type.length === 1 || type.length === 2 && isNullable);
  const isNumeric = canBeType(type, "number", "integer") && (type.length === 1 || type.length === 2 && isNullable);
  if (!isNumeric) {
    return [];
  }
  let exclusiveMax;
  let exclusiveMin;
  if (typeof prop.exclusiveMaximum === "boolean") {
    exclusiveMax = prop.exclusiveMaximum ? prop.maximum : void 0;
  } else {
    exclusiveMax = prop.exclusiveMaximum;
  }
  if (typeof prop.exclusiveMinimum === "boolean") {
    exclusiveMin = prop.exclusiveMinimum ? prop.minimum : void 0;
  } else {
    exclusiveMin = prop.exclusiveMinimum;
  }
  return [
    {
      enabled: exclusiveMax !== void 0 && (prop.maximum === void 0 || exclusiveMax <= prop.maximum),
      isValid: (value) => value < exclusiveMax,
      message: localize(13059, null, exclusiveMax)
    },
    {
      enabled: exclusiveMin !== void 0 && (prop.minimum === void 0 || exclusiveMin >= prop.minimum),
      isValid: (value) => value > exclusiveMin,
      message: localize(13060, null, exclusiveMin)
    },
    {
      enabled: prop.maximum !== void 0 && (exclusiveMax === void 0 || exclusiveMax > prop.maximum),
      isValid: (value) => value <= prop.maximum,
      message: localize(13061, null, prop.maximum)
    },
    {
      enabled: prop.minimum !== void 0 && (exclusiveMin === void 0 || exclusiveMin < prop.minimum),
      isValid: (value) => value >= prop.minimum,
      message: localize(13062, null, prop.minimum)
    },
    {
      enabled: prop.multipleOf !== void 0,
      isValid: (value) => value % prop.multipleOf === 0,
      message: localize(13063, null, prop.multipleOf)
    },
    {
      enabled: isIntegral,
      isValid: (value) => value % 1 === 0,
      message: localize(13064, null)
    }
  ].filter((validation) => validation.enabled);
}
function getArrayValidator(prop) {
  if (prop.type === "array" && prop.items && !Array.isArray(prop.items)) {
    const propItems = prop.items;
    if (propItems && !Array.isArray(propItems.type)) {
      const withQuotes = (s) => `'` + s + `'`;
      return (value) => {
        if (!value) {
          return null;
        }
        let message = "";
        if (!Array.isArray(value)) {
          message += localize(13065, null);
          message += "\n";
          return message;
        }
        const arrayValue = value;
        if (prop.uniqueItems) {
          if (new Set(arrayValue).size < arrayValue.length) {
            message += localize(13066, null);
            message += "\n";
          }
        }
        if (prop.minItems && arrayValue.length < prop.minItems) {
          message += localize(13067, null, prop.minItems);
          message += "\n";
        }
        if (prop.maxItems && arrayValue.length > prop.maxItems) {
          message += localize(13068, null, prop.maxItems);
          message += "\n";
        }
        if (propItems.type === "string") {
          if (!$Ag(arrayValue)) {
            message += localize(13069, null);
            message += "\n";
            return message;
          }
          if (typeof propItems.pattern === "string") {
            const patternRegex = toRegExp2(propItems.pattern);
            arrayValue.forEach((v) => {
              if (!patternRegex.test(v)) {
                message += propItems.patternErrorMessage || localize(13070, null, withQuotes(v), withQuotes(propItems.pattern));
              }
            });
          }
          const propItemsEnum = propItems.enum;
          if (propItemsEnum) {
            arrayValue.forEach((v) => {
              if (propItemsEnum.indexOf(v) === -1) {
                message += localize(13071, null, withQuotes(v), "[" + propItemsEnum.map(withQuotes).join(", ") + "]");
                message += "\n";
              }
            });
          }
        } else if (propItems.type === "integer" || propItems.type === "number") {
          arrayValue.forEach((v) => {
            const errorMessage = getErrorsForSchema(propItems, v);
            if (errorMessage) {
              message += `${v}: ${errorMessage}
`;
            }
          });
        }
        return message;
      };
    }
  }
  return null;
}
function getObjectValidator(prop) {
  if (prop.type === "object") {
    const { properties, patternProperties, additionalProperties } = prop;
    return (value) => {
      if (!value) {
        return null;
      }
      const errors = [];
      if (!$Bg(value)) {
        errors.push(localize(13072, null));
      } else {
        Object.keys(value).forEach((key2) => {
          const data = value[key2];
          if (properties && key2 in properties) {
            const errorMessage = getErrorsForSchema(properties[key2], data);
            if (errorMessage) {
              errors.push(`${key2}: ${errorMessage}
`);
            }
            return;
          }
          if (patternProperties) {
            for (const pattern in patternProperties) {
              if (RegExp(pattern).test(key2)) {
                const errorMessage = getErrorsForSchema(patternProperties[pattern], data);
                if (errorMessage) {
                  errors.push(`${key2}: ${errorMessage}
`);
                }
                return;
              }
            }
          }
          if (additionalProperties === false) {
            errors.push(localize(13073, null, key2));
          } else if (typeof additionalProperties === "object") {
            const errorMessage = getErrorsForSchema(additionalProperties, data);
            if (errorMessage) {
              errors.push(`${key2}: ${errorMessage}
`);
            }
          }
        });
      }
      if (errors.length) {
        return prop.errorMessage ? [prop.errorMessage, ...errors].join(" ") : errors.join(" ");
      }
      return "";
    };
  }
  return null;
}
function getErrorsForSchema(propertySchema, data) {
  const validator = $HK(propertySchema);
  const errorMessage = validator(data);
  return errorMessage;
}

// out-build/vs/workbench/services/preferences/common/preferencesModels.js
var $JK = { startLineNumber: -1, startColumn: -1, endLineNumber: -1, endColumn: -1 };
function isNullRange(range) {
  return range.startLineNumber === -1 && range.startColumn === -1 && range.endLineNumber === -1 && range.endColumn === -1;
}
var AbstractSettingsModel = class extends $rG {
  constructor() {
    super(...arguments);
    this.j = /* @__PURE__ */ new Map();
  }
  updateResultGroup(id2, resultGroup) {
    if (resultGroup) {
      this.j.set(id2, resultGroup);
    } else {
      this.j.delete(id2);
    }
    this.n();
    return this.u();
  }
  /**
   * Remove duplicates between result groups, preferring results in earlier groups
   */
  n() {
    const settingKeys = /* @__PURE__ */ new Set();
    [...this.j.keys()].sort((a, b) => this.j.get(a).order - this.j.get(b).order).forEach((groupId) => {
      const group2 = this.j.get(groupId);
      group2.result.filterMatches = group2.result.filterMatches.filter((s) => !settingKeys.has(s.setting.key));
      group2.result.filterMatches.forEach((s) => settingKeys.add(s.setting.key));
    });
  }
  filterSettings(filter, groupFilter, settingMatcher) {
    const allGroups = this.t;
    const filterMatches = [];
    for (const group2 of allGroups) {
      const groupMatched = groupFilter(group2);
      for (const section of group2.sections) {
        for (const setting of section.settings) {
          const settingMatchResult = settingMatcher(setting, group2);
          if (groupMatched || settingMatchResult) {
            filterMatches.push({
              setting,
              matches: settingMatchResult && settingMatchResult.matches,
              matchType: settingMatchResult?.matchType ?? SettingMatchType.None,
              score: settingMatchResult?.score ?? 0
            });
          }
        }
      }
    }
    return filterMatches;
  }
  getPreference(key2) {
    for (const group2 of this.settingsGroups) {
      for (const section of group2.sections) {
        for (const setting of section.settings) {
          if (key2 === setting.key) {
            return setting;
          }
        }
      }
    }
    return void 0;
  }
  r(groups) {
    const metadata = /* @__PURE__ */ Object.create(null);
    let hasMetadata = false;
    groups.forEach((g) => {
      if (g.result.metadata) {
        metadata[g.id] = g.result.metadata;
        hasMetadata = true;
      }
    });
    return hasMetadata ? metadata : null;
  }
  get t() {
    return this.settingsGroups;
  }
};
var $KK = class extends AbstractSettingsModel {
  constructor(reference, C) {
    super();
    this.C = C;
    this.z = this.B(new $ze());
    this.onDidChangeGroups = this.z.event;
    this.y = reference.object.textEditorModel;
    this.B(this.onWillDispose(() => reference.dispose()));
    this.B(this.y.onDidChangeContent(() => {
      this.w = void 0;
      this.z.fire();
    }));
  }
  get uri() {
    return this.y.uri;
  }
  get configurationTarget() {
    return this.C;
  }
  get settingsGroups() {
    if (!this.w) {
      this.F();
    }
    return this.w;
  }
  get content() {
    return this.y.getValue();
  }
  findValueMatches(filter, setting) {
    return this.y.findMatches(filter, setting.valueRange, false, false, null, false).map((match) => match.range);
  }
  D(property, previousParents) {
    return previousParents.length === 0;
  }
  F() {
    this.w = parse3(this.y, (property, previousParents) => this.D(property, previousParents));
  }
  u() {
    const resultGroups = [...this.j.values()];
    if (!resultGroups.length) {
      return void 0;
    }
    const filteredSettings = [];
    const matches = [];
    resultGroups.forEach((group2) => {
      group2.result.filterMatches.forEach((filterMatch) => {
        filteredSettings.push(filterMatch.setting);
        if (filterMatch.matches) {
          matches.push(...filterMatch.matches);
        }
      });
    });
    let filteredGroup;
    const modelGroup = this.settingsGroups[0];
    if (modelGroup) {
      filteredGroup = {
        id: modelGroup.id,
        range: modelGroup.range,
        sections: [{
          settings: filteredSettings
        }],
        title: modelGroup.title,
        titleRange: modelGroup.titleRange,
        order: modelGroup.order,
        extensionInfo: modelGroup.extensionInfo
      };
    }
    const metadata = this.r(resultGroups);
    return {
      allGroups: this.settingsGroups,
      filteredGroups: filteredGroup ? [filteredGroup] : [],
      matches,
      metadata: metadata ?? void 0
    };
  }
};
var $LK = class $LK2 extends AbstractSettingsModel {
  constructor(C, configurationService) {
    super();
    this.C = C;
    this.w = this.B(new $ze());
    this.onDidChangeGroups = this.w.event;
    this.y = [];
    this.z = false;
    this.B(configurationService.onDidChangeConfiguration((e) => {
      if (e.source === 7) {
        this.z = true;
        this.w.fire();
      }
    }));
    this.B($Wn.as($Ht.Configuration).onDidSchemaChange((e) => {
      this.z = true;
      this.w.fire();
    }));
  }
  /** Doesn't include the "Commonly Used" group */
  get t() {
    return this.settingsGroups.slice(1);
  }
  get settingsGroups() {
    const groups = this.C.getSettingsGroups(this.z);
    this.z = false;
    return [...groups, ...this.y];
  }
  /** For programmatically added groups outside of registered configurations */
  setAdditionalGroups(groups) {
    this.y = groups;
  }
  findValueMatches(filter, setting) {
    return [];
  }
  u() {
    throw new Error("Not supported");
  }
};
$LK = __decorate([
  __param(1, $kl)
], $LK);
function parse3(model, isSettingsProperty) {
  const settings = [];
  let overrideSetting = null;
  let currentProperty = null;
  let currentParent = [];
  const previousParents = [];
  let settingsPropertyIndex = -1;
  const range = {
    startLineNumber: 0,
    startColumn: 0,
    endLineNumber: 0,
    endColumn: 0
  };
  function onValue(value, offset, length) {
    if (Array.isArray(currentParent)) {
      currentParent.push(value);
    } else if (currentProperty) {
      currentParent[currentProperty] = value;
    }
    if (previousParents.length === settingsPropertyIndex + 1 || previousParents.length === settingsPropertyIndex + 2 && overrideSetting !== null) {
      const setting = previousParents.length === settingsPropertyIndex + 1 ? settings[settings.length - 1] : overrideSetting.overrides[overrideSetting.overrides.length - 1];
      if (setting) {
        const valueStartPosition = model.getPositionAt(offset);
        const valueEndPosition = model.getPositionAt(offset + length);
        setting.value = value;
        setting.valueRange = {
          startLineNumber: valueStartPosition.lineNumber,
          startColumn: valueStartPosition.column,
          endLineNumber: valueEndPosition.lineNumber,
          endColumn: valueEndPosition.column
        };
        setting.range = Object.assign(setting.range, {
          endLineNumber: valueEndPosition.lineNumber,
          endColumn: valueEndPosition.column
        });
      }
    }
  }
  const visitor = {
    onObjectBegin: (offset, length) => {
      if (isSettingsProperty(currentProperty, previousParents)) {
        settingsPropertyIndex = previousParents.length;
        const position = model.getPositionAt(offset);
        range.startLineNumber = position.lineNumber;
        range.startColumn = position.column;
      }
      const object = {};
      onValue(object, offset, length);
      currentParent = object;
      currentProperty = null;
      previousParents.push(currentParent);
    },
    onObjectProperty: (name, offset, length) => {
      currentProperty = name;
      if (previousParents.length === settingsPropertyIndex + 1 || previousParents.length === settingsPropertyIndex + 2 && overrideSetting !== null) {
        const settingStartPosition = model.getPositionAt(offset);
        const setting = {
          description: [],
          descriptionIsMarkdown: false,
          key: name,
          keyRange: {
            startLineNumber: settingStartPosition.lineNumber,
            startColumn: settingStartPosition.column + 1,
            endLineNumber: settingStartPosition.lineNumber,
            endColumn: settingStartPosition.column + length
          },
          range: {
            startLineNumber: settingStartPosition.lineNumber,
            startColumn: settingStartPosition.column,
            endLineNumber: 0,
            endColumn: 0
          },
          value: null,
          valueRange: $JK,
          descriptionRanges: [],
          overrides: [],
          overrideOf: overrideSetting ?? void 0
        };
        if (previousParents.length === settingsPropertyIndex + 1) {
          settings.push(setting);
          if ($Rt.test(name)) {
            overrideSetting = setting;
          }
        } else {
          overrideSetting.overrides.push(setting);
        }
      }
    },
    onObjectEnd: (offset, length) => {
      currentParent = previousParents.pop();
      if (settingsPropertyIndex !== -1 && (previousParents.length === settingsPropertyIndex + 1 || previousParents.length === settingsPropertyIndex + 2 && overrideSetting !== null)) {
        const setting = previousParents.length === settingsPropertyIndex + 1 ? settings[settings.length - 1] : overrideSetting.overrides[overrideSetting.overrides.length - 1];
        if (setting) {
          const valueEndPosition = model.getPositionAt(offset + length);
          setting.valueRange = Object.assign(setting.valueRange, {
            endLineNumber: valueEndPosition.lineNumber,
            endColumn: valueEndPosition.column
          });
          setting.range = Object.assign(setting.range, {
            endLineNumber: valueEndPosition.lineNumber,
            endColumn: valueEndPosition.column
          });
        }
        if (previousParents.length === settingsPropertyIndex + 1) {
          overrideSetting = null;
        }
      }
      if (previousParents.length === settingsPropertyIndex) {
        const position = model.getPositionAt(offset);
        range.endLineNumber = position.lineNumber;
        range.endColumn = position.column;
        settingsPropertyIndex = -1;
      }
    },
    onArrayBegin: (offset, length) => {
      const array2 = [];
      onValue(array2, offset, length);
      previousParents.push(currentParent);
      currentParent = array2;
      currentProperty = null;
    },
    onArrayEnd: (offset, length) => {
      currentParent = previousParents.pop();
      if (previousParents.length === settingsPropertyIndex + 1 || previousParents.length === settingsPropertyIndex + 2 && overrideSetting !== null) {
        const setting = previousParents.length === settingsPropertyIndex + 1 ? settings[settings.length - 1] : overrideSetting.overrides[overrideSetting.overrides.length - 1];
        if (setting) {
          const valueEndPosition = model.getPositionAt(offset + length);
          setting.valueRange = Object.assign(setting.valueRange, {
            endLineNumber: valueEndPosition.lineNumber,
            endColumn: valueEndPosition.column
          });
          setting.range = Object.assign(setting.range, {
            endLineNumber: valueEndPosition.lineNumber,
            endColumn: valueEndPosition.column
          });
        }
      }
    },
    onLiteralValue: onValue,
    onError: (error) => {
      const setting = settings[settings.length - 1];
      if (setting && (isNullRange(setting.range) || isNullRange(setting.keyRange) || isNullRange(setting.valueRange))) {
        settings.pop();
      }
    }
  };
  if (!model.isDisposed()) {
    $Fw(model.getValue(), visitor);
  }
  return settings.length > 0 ? [{
    id: model.isDisposed() ? "" : model.id,
    sections: [
      {
        settings
      }
    ],
    title: "",
    titleRange: $JK,
    range
  }] : [];
}
var $MK = class extends $KK {
  constructor() {
    super(...arguments);
    this.H = [];
  }
  get configurationGroups() {
    return this.H;
  }
  F() {
    super.F();
    this.H = parse3(this.y, (property, previousParents) => previousParents.length === 0);
  }
  D(property, previousParents) {
    return property === "settings" && previousParents.length === 1;
  }
};
var $NK = class extends $3c {
  constructor(t, target, configurationService) {
    super();
    this.t = t;
    this.target = target;
    this.configurationService = configurationService;
    this.n = /* @__PURE__ */ new Map();
    this.r = this.B(new $ze());
    this.onDidChange = this.r.event;
    this.B(configurationService.onDidChangeConfiguration((e) => {
      if (e.source === 7) {
        this.w();
        this.r.fire();
      }
    }));
  }
  getContent(forceUpdate = false) {
    if (!this.h || forceUpdate) {
      this.u();
    }
    return this.h;
  }
  getContentWithoutMostCommonlyUsed(forceUpdate = false) {
    if (!this.j || forceUpdate) {
      this.u();
    }
    return this.j;
  }
  getSettingsGroups(forceUpdate = false) {
    if (!this.f || forceUpdate) {
      this.u();
    }
    return this.f;
  }
  u() {
    this.f = this.y();
    this.h = this.M(this.f, 0);
    this.j = this.M(this.f, 1);
  }
  w() {
    this.h = void 0;
    this.j = void 0;
    this.f = void 0;
  }
  y() {
    const settingsGroups = this.getRegisteredGroups();
    this.C(settingsGroups);
    const mostCommonlyUsed = this.D();
    return [mostCommonlyUsed, ...settingsGroups];
  }
  getRegisteredGroups() {
    const configurations = $Wn.as($Ht.Configuration).getConfigurations().slice();
    const groups = this.G(configurations.sort(this.L).reduce((result, config, index, array2) => this.F(config, result, array2), []));
    return this.z(groups);
  }
  z(groups) {
    groups.forEach((group2) => {
      group2.sections.forEach((section) => {
        section.settings.sort((a, b) => a.key.localeCompare(b.key));
      });
    });
    return groups;
  }
  C(allSettingsGroups) {
    this.n = /* @__PURE__ */ new Map();
    for (const group2 of allSettingsGroups) {
      for (const section of group2.sections) {
        for (const setting of section.settings) {
          this.n.set(setting.key, setting);
        }
      }
    }
  }
  D() {
    const settings = $Mb(this.t.map((key2) => {
      const setting = this.n.get(key2);
      if (setting) {
        return {
          description: setting.description,
          key: setting.key,
          value: setting.value,
          keyRange: $JK,
          range: $JK,
          valueRange: $JK,
          overrides: [],
          scope: 4,
          type: setting.type,
          enum: setting.enum,
          enumDescriptions: setting.enumDescriptions,
          descriptionRanges: []
        };
      }
      return null;
    }));
    return {
      id: "mostCommonlyUsed",
      range: $JK,
      title: localize(13043, null),
      titleRange: $JK,
      sections: [
        {
          settings
        }
      ]
    };
  }
  F(config, result, configurations, settingsGroup, seenSettings) {
    seenSettings = seenSettings ? seenSettings : {};
    let title = config.title;
    if (!title) {
      const configWithTitleAndSameId = configurations.find((c) => c.id === config.id && c.title);
      if (configWithTitleAndSameId) {
        title = configWithTitleAndSameId.title;
      }
    }
    if (title) {
      if (!settingsGroup) {
        settingsGroup = result.find((g) => g.title === title && g.extensionInfo?.id === config.extensionInfo?.id);
        if (!settingsGroup) {
          settingsGroup = { sections: [{ settings: [] }], id: config.id || "", title: title || "", titleRange: $JK, order: config.order, range: $JK, extensionInfo: config.extensionInfo };
          result.push(settingsGroup);
        }
      } else {
        settingsGroup.sections[settingsGroup.sections.length - 1].title = title;
      }
    }
    if (config.properties) {
      if (!settingsGroup) {
        settingsGroup = { sections: [{ settings: [] }], id: config.id || "", title: config.id || "", titleRange: $JK, order: config.order, range: $JK, extensionInfo: config.extensionInfo };
        result.push(settingsGroup);
      }
      const configurationSettings = [];
      for (const setting of [...settingsGroup.sections[settingsGroup.sections.length - 1].settings, ...this.H(config)]) {
        if (!seenSettings[setting.key]) {
          configurationSettings.push(setting);
          seenSettings[setting.key] = true;
        }
      }
      if (configurationSettings.length) {
        settingsGroup.sections[settingsGroup.sections.length - 1].settings = configurationSettings;
      }
    }
    config.allOf?.forEach((c) => this.F(c, result, configurations, settingsGroup, seenSettings));
    return result;
  }
  G(settingsGroups) {
    const result = [];
    for (const settingsGroup of settingsGroups) {
      settingsGroup.sections = settingsGroup.sections.filter((section) => section.settings.length > 0);
      if (settingsGroup.sections.length) {
        result.push(settingsGroup);
      }
    }
    return result;
  }
  H(config) {
    const result = [];
    const settingsObject = config.properties;
    const extensionInfo = config.extensionInfo;
    const categoryLabel = config.extensionInfo?.id === config.id ? config.title : config.id;
    for (const key2 in settingsObject) {
      const prop = settingsObject[key2];
      if (this.J(prop)) {
        const value = prop.default;
        let description = prop.markdownDescription || prop.description || "";
        if (typeof description !== "string") {
          description = "";
        }
        const descriptionLines = description.split("\n");
        const overrides = $Rt.test(key2) ? this.I(prop.default) : [];
        let listItemType;
        if (prop.type === "array" && prop.items && !Array.isArray(prop.items) && prop.items.type) {
          if (prop.items.enum) {
            listItemType = "enum";
          } else if (!Array.isArray(prop.items.type)) {
            listItemType = prop.items.type;
          }
        }
        const objectProperties = prop.type === "object" ? prop.properties : void 0;
        const objectPatternProperties = prop.type === "object" ? prop.patternProperties : void 0;
        const objectAdditionalProperties = prop.type === "object" ? prop.additionalProperties : void 0;
        let enumToUse = prop.enum;
        let enumDescriptions = prop.markdownEnumDescriptions ?? prop.enumDescriptions;
        let enumDescriptionsAreMarkdown = !!prop.markdownEnumDescriptions;
        if (listItemType === "enum" && !Array.isArray(prop.items)) {
          enumToUse = prop.items.enum;
          enumDescriptions = prop.items.markdownEnumDescriptions ?? prop.items.enumDescriptions;
          enumDescriptionsAreMarkdown = !!prop.items.markdownEnumDescriptions;
        }
        let allKeysAreBoolean = false;
        if (prop.type === "object" && !prop.additionalProperties && prop.properties && Object.keys(prop.properties).length) {
          allKeysAreBoolean = Object.keys(prop.properties).every((key3) => {
            return prop.properties[key3].type === "boolean";
          });
        }
        let isLanguageTagSetting = false;
        if ($Rt.test(key2)) {
          isLanguageTagSetting = true;
        }
        let defaultValueSource;
        if (!isLanguageTagSetting) {
          const registeredConfigurationProp = prop;
          if (registeredConfigurationProp && registeredConfigurationProp.defaultValueSource) {
            defaultValueSource = registeredConfigurationProp.defaultValueSource;
          }
        }
        if (!enumToUse && (prop.enumItemLabels || enumDescriptions || enumDescriptionsAreMarkdown)) {
          console.error(`The setting ${key2} has enum-related fields, but doesn't have an enum field. This setting may render improperly in the Settings editor.`);
        }
        result.push({
          key: key2,
          value,
          description: descriptionLines,
          descriptionIsMarkdown: !!prop.markdownDescription,
          range: $JK,
          keyRange: $JK,
          valueRange: $JK,
          descriptionRanges: [],
          overrides,
          scope: prop.scope,
          type: prop.type,
          arrayItemType: listItemType,
          objectProperties,
          objectPatternProperties,
          objectAdditionalProperties,
          enum: enumToUse,
          enumDescriptions,
          enumDescriptionsAreMarkdown,
          enumItemLabels: prop.enumItemLabels,
          uniqueItems: prop.uniqueItems,
          tags: prop.tags,
          disallowSyncIgnore: prop.disallowSyncIgnore,
          restricted: prop.restricted,
          extensionInfo,
          deprecationMessage: prop.markdownDeprecationMessage || prop.deprecationMessage,
          deprecationMessageIsMarkdown: !!prop.markdownDeprecationMessage,
          validator: $HK(prop),
          allKeysAreBoolean,
          editPresentation: prop.editPresentation,
          order: prop.order,
          nonLanguageSpecificDefaultValueSource: defaultValueSource,
          isLanguageTagSetting,
          categoryLabel
        });
      }
    }
    return result;
  }
  I(overrideSettings) {
    return Object.keys(overrideSettings).map((key2) => ({
      key: key2,
      value: overrideSettings[key2],
      description: [],
      descriptionIsMarkdown: false,
      range: $JK,
      keyRange: $JK,
      valueRange: $JK,
      descriptionRanges: [],
      overrides: []
    }));
  }
  J(property) {
    if (!property.scope) {
      return true;
    }
    if (this.target === 6) {
      return $zK.indexOf(property.scope) !== -1;
    }
    if (this.target === 5) {
      return $yK.indexOf(property.scope) !== -1;
    }
    return true;
  }
  L(c1, c2) {
    if (typeof c1.order !== "number") {
      return 1;
    }
    if (typeof c2.order !== "number") {
      return -1;
    }
    if (c1.order === c2.order) {
      const title1 = c1.title || "";
      const title2 = c2.title || "";
      return title1.localeCompare(title2);
    }
    return c1.order - c2.order;
  }
  M(settingsGroups, startIndex) {
    const builder = new SettingsContentBuilder();
    for (let i2 = startIndex; i2 < settingsGroups.length; i2++) {
      builder.pushGroup(settingsGroups[i2], i2 === startIndex, i2 === settingsGroups.length - 1);
    }
    return builder.getContent();
  }
};
var $OK = class extends AbstractSettingsModel {
  constructor(z, reference, C) {
    super();
    this.z = z;
    this.C = C;
    this.y = this.B(new $ze());
    this.onDidChangeGroups = this.y.event;
    this.B(C.onDidChange(() => this.y.fire()));
    this.w = reference.object.textEditorModel;
    this.B(this.onWillDispose(() => reference.dispose()));
  }
  get uri() {
    return this.z;
  }
  get target() {
    return this.C.target;
  }
  get settingsGroups() {
    return this.C.getSettingsGroups();
  }
  get t() {
    return this.settingsGroups.slice(1);
  }
  u() {
    if (this.w.isDisposed()) {
      return void 0;
    }
    const resultGroups = [...this.j.values()].sort((a, b) => a.order - b.order);
    const nonEmptyResultGroups = resultGroups.filter((group2) => group2.result.filterMatches.length);
    const startLine = this.settingsGroups.at(-1).range.endLineNumber + 2;
    const { settingsGroups: filteredGroups, matches } = this.G(nonEmptyResultGroups, startLine);
    const metadata = this.r(resultGroups);
    return resultGroups.length ? {
      allGroups: this.settingsGroups,
      filteredGroups,
      matches,
      metadata: metadata ?? void 0
    } : void 0;
  }
  /**
   * Translate the ISearchResultGroups to text, and write it to the editor model
   */
  G(groups, startLine) {
    const contentBuilderOffset = startLine - 1;
    const builder = new SettingsContentBuilder(contentBuilderOffset);
    const settingsGroups = [];
    const matches = [];
    if (groups.length) {
      builder.pushLine(",");
      groups.forEach((resultGroup) => {
        const settingsGroup = this.J(resultGroup);
        settingsGroups.push(settingsGroup);
        matches.push(...this.H(builder, settingsGroup, resultGroup.result.filterMatches));
      });
    }
    const groupContent = builder.getContent() + "\n";
    const groupEndLine = this.w.getLineCount();
    const cursorPosition = new $_D(startLine, 1, startLine, 1);
    const edit3 = {
      text: groupContent,
      forceMoveMarkers: true,
      range: new $9C(startLine, 1, groupEndLine, 1)
    };
    this.w.pushEditOperations([cursorPosition], [edit3], () => [cursorPosition]);
    const tokenizeTo = Math.min(startLine + 60, this.w.getLineCount());
    this.w.tokenization.forceTokenization(tokenizeTo);
    return { matches, settingsGroups };
  }
  H(builder, settingsGroup, filterMatches) {
    filterMatches = filterMatches.map((filteredMatch) => {
      return {
        setting: filteredMatch.setting,
        score: filteredMatch.score,
        matchType: filteredMatch.matchType,
        matches: filteredMatch.matches && filteredMatch.matches.map((match) => {
          return new $9C(match.startLineNumber - filteredMatch.setting.range.startLineNumber, match.startColumn, match.endLineNumber - filteredMatch.setting.range.startLineNumber, match.endColumn);
        })
      };
    });
    builder.pushGroup(settingsGroup);
    const fixedMatches = filterMatches.map((m) => m.matches || []).flatMap((settingMatches2, i2) => {
      const setting = settingsGroup.sections[0].settings[i2];
      return settingMatches2.map((range) => {
        return new $9C(range.startLineNumber + setting.range.startLineNumber, range.startColumn, range.endLineNumber + setting.range.startLineNumber, range.endColumn);
      });
    });
    return fixedMatches;
  }
  I(setting) {
    return {
      description: setting.description,
      scope: setting.scope,
      type: setting.type,
      enum: setting.enum,
      enumDescriptions: setting.enumDescriptions,
      key: setting.key,
      value: setting.value,
      range: setting.range,
      overrides: [],
      overrideOf: setting.overrideOf,
      tags: setting.tags,
      deprecationMessage: setting.deprecationMessage,
      keyRange: $JK,
      valueRange: $JK,
      descriptionIsMarkdown: void 0,
      descriptionRanges: []
    };
  }
  findValueMatches(filter, setting) {
    return [];
  }
  getPreference(key2) {
    for (const group2 of this.settingsGroups) {
      for (const section of group2.sections) {
        for (const setting of section.settings) {
          if (setting.key === key2) {
            return setting;
          }
        }
      }
    }
    return void 0;
  }
  J(resultGroup) {
    return {
      id: resultGroup.id,
      range: $JK,
      title: resultGroup.label,
      titleRange: $JK,
      sections: [
        {
          settings: resultGroup.result.filterMatches.map((m) => this.I(m.setting))
        }
      ]
    };
  }
};
var SettingsContentBuilder = class {
  get f() {
    return this.d.length + this.j;
  }
  get h() {
    return this.d[this.d.length - 1] || "";
  }
  constructor(j = 0) {
    this.j = j;
    this.d = [];
  }
  pushLine(...lineText) {
    this.d.push(...lineText);
  }
  pushGroup(settingsGroups, isFirst, isLast) {
    this.d.push(isFirst ? "[{" : "{");
    const lastSetting = this.k(settingsGroups, "  ");
    if (lastSetting) {
      const lineIdx = lastSetting.range.endLineNumber - this.j;
      const content = this.d[lineIdx - 2];
      this.d[lineIdx - 2] = content.substring(0, content.length - 1);
    }
    this.d.push(isLast ? "}]" : "},");
  }
  k(group2, indent) {
    let lastSetting = null;
    const groupStart = this.f + 1;
    for (const section of group2.sections) {
      if (section.title) {
        const sectionTitleStart = this.f + 1;
        this.q([section.title], indent, this.d);
        section.titleRange = { startLineNumber: sectionTitleStart, startColumn: 1, endLineNumber: this.f, endColumn: this.h.length };
      }
      if (section.settings.length) {
        for (const setting of section.settings) {
          this.n(setting, indent);
          lastSetting = setting;
        }
      }
    }
    group2.range = { startLineNumber: groupStart, startColumn: 1, endLineNumber: this.f, endColumn: this.h.length };
    return lastSetting;
  }
  getContent() {
    return this.d.join("\n");
  }
  n(setting, indent) {
    const settingStart = this.f + 1;
    this.o(setting, indent);
    let preValueContent = indent;
    const keyString = JSON.stringify(setting.key);
    preValueContent += keyString;
    setting.keyRange = { startLineNumber: this.f + 1, startColumn: preValueContent.indexOf(setting.key) + 1, endLineNumber: this.f + 1, endColumn: setting.key.length };
    preValueContent += ": ";
    const valueStart = this.f + 1;
    this.p(setting, preValueContent, indent);
    setting.valueRange = { startLineNumber: valueStart, startColumn: preValueContent.length + 1, endLineNumber: this.f, endColumn: this.h.length + 1 };
    this.d[this.d.length - 1] += ",";
    this.d.push("");
    setting.range = { startLineNumber: settingStart, startColumn: 1, endLineNumber: this.f, endColumn: this.h.length };
  }
  o(setting, indent) {
    const fixSettingLink = (line) => line.replace(/`#(.*)#`/g, (match, settingName) => `\`${settingName}\``);
    setting.descriptionRanges = [];
    const descriptionPreValue = indent + "// ";
    const deprecationMessageLines = setting.deprecationMessage?.split(/\n/g) ?? [];
    for (let line of [...deprecationMessageLines, ...setting.description]) {
      line = fixSettingLink(line);
      this.d.push(descriptionPreValue + line);
      setting.descriptionRanges.push({ startLineNumber: this.f, startColumn: this.h.indexOf(line) + 1, endLineNumber: this.f, endColumn: this.h.length });
    }
    if (setting.enum && setting.enumDescriptions?.some((desc) => !!desc)) {
      setting.enumDescriptions.forEach((desc, i2) => {
        const displayEnum = escapeInvisibleChars(String(setting.enum[i2]));
        const line = desc ? `${displayEnum}: ${fixSettingLink(desc)}` : displayEnum;
        const lines = line.split(/\n/g);
        lines[0] = " - " + lines[0];
        this.d.push(...lines.map((l) => `${indent}// ${l}`));
        setting.descriptionRanges.push({ startLineNumber: this.f, startColumn: this.h.indexOf(line) + 1, endLineNumber: this.f, endColumn: this.h.length });
      });
    }
  }
  p(setting, preValueConent, indent) {
    const valueString = JSON.stringify(setting.value, null, indent);
    if (valueString && typeof setting.value === "object") {
      if (setting.overrides && setting.overrides.length) {
        this.d.push(preValueConent + " {");
        for (const subSetting of setting.overrides) {
          this.n(subSetting, indent + indent);
          this.d.pop();
        }
        const lastSetting = setting.overrides[setting.overrides.length - 1];
        const content = this.d[lastSetting.range.endLineNumber - 2];
        this.d[lastSetting.range.endLineNumber - 2] = content.substring(0, content.length - 1);
        this.d.push(indent + "}");
      } else {
        const mulitLineValue = valueString.split("\n");
        this.d.push(preValueConent + mulitLineValue[0]);
        for (let i2 = 1; i2 < mulitLineValue.length; i2++) {
          this.d.push(indent + mulitLineValue[i2]);
        }
      }
    } else {
      this.d.push(preValueConent + valueString);
    }
  }
  q(description, indent, result) {
    for (const line of description) {
      result.push(indent + "// " + line);
    }
  }
};
var RawSettingsContentBuilder = class extends SettingsContentBuilder {
  constructor(r2 = "	") {
    super(0);
    this.r = r2;
  }
  pushGroup(settingsGroups) {
    this.k(settingsGroups, this.r);
  }
};
var $PK = class extends $3c {
  constructor(j) {
    super();
    this.j = j;
    this.f = null;
    this.h = this.B(new $ze());
    this.onDidContentChanged = this.h.event;
    this.B(j.onDidChange(() => {
      this.f = null;
      this.h.fire();
    }));
  }
  get content() {
    if (this.f === null) {
      const builder = new RawSettingsContentBuilder();
      builder.pushLine("{");
      for (const settingsGroup of this.j.getRegisteredGroups()) {
        builder.pushGroup(settingsGroup);
      }
      builder.pushLine("}");
      this.f = builder.getContent();
    }
    return this.f;
  }
};
function escapeInvisibleChars(enumValue) {
  return enumValue && enumValue.replace(/\n/g, "\\n").replace(/\r/g, "\\r");
}
function $QK(keybindingService) {
  const defaultsHeader = "// " + localize(13044, null);
  return defaultsHeader + "\n" + keybindingService.getDefaultKeybindingsContent();
}
var $RK = class $RK2 {
  constructor(f, h3) {
    this.f = f;
    this.h = h3;
  }
  get uri() {
    return this.f;
  }
  get content() {
    if (!this.d) {
      this.d = $QK(this.h);
    }
    return this.d;
  }
  getPreference() {
    return null;
  }
  dispose() {
  }
};
$RK = __decorate([
  __param(1, $Ty)
], $RK);

// out-build/vs/workbench/services/preferences/browser/preferencesService.js
var emptyEditableSettingsContent = "{\n}";
var $GVb = class $GVb2 extends $3c {
  constructor(n, r2, s, t, u, w, y, z, C, D, keybindingService, modelService, F, G, H, I, urlService, J, L) {
    super();
    this.n = n;
    this.r = r2;
    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 = G;
    this.H = H;
    this.I = I;
    this.J = J;
    this.L = L;
    this.a = this.B(new $ze());
    this.b = this.B(new $ze());
    this.onDidDefaultSettingsContentChanged = this.b.event;
    this.j = new $Fc();
    this.m = void 0;
    this.defaultKeybindingsResource = URI.from({ scheme: Schemas.vscode, authority: "defaultsettings", path: "/keybindings.json" });
    this.M = URI.from({ scheme: Schemas.vscode, authority: "defaultsettings", path: "/defaultSettings.json" });
    this.B(keybindingService.onDidUpdateKeybindings(() => {
      const model = modelService.getModel(this.defaultKeybindingsResource);
      if (!model) {
        return;
      }
      modelService.updateModel(model, $QK(keybindingService));
    }));
    this.B(urlService.registerHandler(this));
  }
  get userSettingsResource() {
    return this.z.currentProfile.settingsResource;
  }
  get workspaceSettingsResource() {
    if (this.w.getWorkbenchState() === 1) {
      return null;
    }
    const workspace2 = this.w.getWorkspace();
    return workspace2.configuration || workspace2.folders[0].toResource($VK);
  }
  createSettingsEditor2Input() {
    return new $FVb(this);
  }
  getFolderSettingsResource(resource) {
    const folder = this.w.getWorkspaceFolder(resource);
    return folder ? folder.toResource($VK) : null;
  }
  hasDefaultSettingsContent(uri) {
    return this.W(uri) || $oh(uri, this.M) || $oh(uri, this.defaultKeybindingsResource);
  }
  getDefaultSettingsContent(uri) {
    if (this.W(uri)) {
      const target = this.U(uri);
      const defaultSettings = this.db(target);
      if (!this.j.has(uri)) {
        this.B(defaultSettings.onDidChange(() => this.b.fire(uri)));
        this.j.add(uri);
      }
      return defaultSettings.getContentWithoutMostCommonlyUsed(true);
    }
    if ($oh(uri, this.M)) {
      if (!this.h) {
        this.h = this.B(this.y.createInstance($PK, this.db(
          3
          /* ConfigurationTarget.USER_LOCAL */
        )));
        this.B(this.h.onDidContentChanged(() => this.b.fire(uri)));
      }
      return this.h.content;
    }
    if ($oh(uri, this.defaultKeybindingsResource)) {
      const defaultKeybindingsEditorModel = this.y.createInstance($RK, uri);
      return defaultKeybindingsEditorModel.content;
    }
    return void 0;
  }
  async createPreferencesEditorModel(uri) {
    if (this.W(uri)) {
      return this.cb(uri);
    }
    if (this.userSettingsResource.toString() === uri.toString() || this.C.defaultProfile.settingsResource.toString() === uri.toString()) {
      return this.bb(3, uri);
    }
    const workspaceSettingsUri = await this.getEditableSettingsURI(
      5
      /* ConfigurationTarget.WORKSPACE */
    );
    if (workspaceSettingsUri && workspaceSettingsUri.toString() === uri.toString()) {
      return this.bb(5, workspaceSettingsUri);
    }
    if (this.w.getWorkbenchState() === 3) {
      const settingsUri = await this.getEditableSettingsURI(6, uri);
      if (settingsUri && settingsUri.toString() === uri.toString()) {
        return this.bb(6, uri);
      }
    }
    const remoteEnvironment = await this.H.getEnvironment();
    const remoteSettingsUri = remoteEnvironment ? remoteEnvironment.settingsPath : null;
    if (remoteSettingsUri && remoteSettingsUri.toString() === uri.toString()) {
      return this.bb(4, uri);
    }
    return null;
  }
  openRawDefaultSettings() {
    return this.n.openEditor({ resource: this.M });
  }
  openRawUserSettings() {
    return this.n.openEditor({ resource: this.userSettingsResource });
  }
  N() {
    return this.t.getValue("workbench.settings.editor") === "json";
  }
  openSettings(options3 = {}) {
    options3 = {
      ...options3,
      target: 3
    };
    if (options3.query) {
      options3.jsonEditor = false;
    }
    return this.O(this.userSettingsResource, options3);
  }
  openLanguageSpecificSettings(languageId, options3 = {}) {
    if (this.N()) {
      options3.query = void 0;
      options3.revealSetting = { key: `[${languageId}]`, edit: true };
    } else {
      options3.query = `@lang:${languageId}${options3.query ? ` ${options3.query}` : ""}`;
    }
    options3.target = options3.target ?? 3;
    return this.O(this.userSettingsResource, options3);
  }
  O(settingsResource, options3) {
    options3 = {
      ...options3,
      jsonEditor: options3.jsonEditor ?? this.N()
    };
    return options3.jsonEditor ? this.Q(settingsResource, options3) : this.P(options3);
  }
  async P(options3) {
    const input = this.createSettingsEditor2Input();
    options3 = {
      ...options3,
      focusSearch: true
    };
    await this.n.openEditor(input, $SK(options3), options3.openToSide ? $oJ : void 0);
    return this.r.activeGroup.activeEditorPane;
  }
  openApplicationSettings(options3 = {}) {
    options3 = {
      ...options3,
      target: 3
    };
    return this.O(this.C.defaultProfile.settingsResource, options3);
  }
  openUserSettings(options3 = {}) {
    options3 = {
      ...options3,
      target: 3
    };
    return this.O(this.userSettingsResource, options3);
  }
  async openRemoteSettings(options3 = {}) {
    const environment = await this.H.getEnvironment();
    if (environment) {
      options3 = {
        ...options3,
        target: 4
      };
      this.O(environment.settingsPath, options3);
    }
    return void 0;
  }
  openWorkspaceSettings(options3 = {}) {
    if (!this.workspaceSettingsResource) {
      this.u.info(localize(13036, null));
      return Promise.reject(null);
    }
    options3 = {
      ...options3,
      target: 5
      /* ConfigurationTarget.WORKSPACE */
    };
    return this.O(this.workspaceSettingsResource, options3);
  }
  async openFolderSettings(options3 = {}) {
    options3 = {
      ...options3,
      target: 6
      /* ConfigurationTarget.WORKSPACE_FOLDER */
    };
    if (!options3.folderUri) {
      throw new Error(`Missing folder URI`);
    }
    const folderSettingsUri = await this.getEditableSettingsURI(6, options3.folderUri);
    if (!folderSettingsUri) {
      throw new Error(`Invalid folder URI - ${options3.folderUri.toString()}`);
    }
    return this.O(folderSettingsUri, options3);
  }
  async openGlobalKeybindingSettings(textual, options3) {
    options3 = { pinned: true, revealIfOpened: true, ...options3 };
    if (textual) {
      const emptyContents = "// " + localize(13037, null) + "\n[\n]";
      const editableKeybindings = this.z.currentProfile.keybindingsResource;
      const openDefaultKeybindings = !!this.t.getValue("workbench.settings.openDefaultKeybindings");
      await this.fb(editableKeybindings, emptyContents);
      if (openDefaultKeybindings) {
        const activeEditorGroup = this.r.activeGroup;
        const sideEditorGroup = this.r.addGroup(
          activeEditorGroup.id,
          3
          /* GroupDirection.RIGHT */
        );
        await Promise.all([
          this.n.openEditor({ resource: this.defaultKeybindingsResource, options: { pinned: true, preserveFocus: true, revealIfOpened: true, override: $1K.id }, label: localize(13038, null), description: "" }),
          this.n.openEditor({ resource: editableKeybindings, options: options3 }, sideEditorGroup.id)
        ]);
      } else {
        await this.n.openEditor({ resource: editableKeybindings, options: options3 });
      }
    } else {
      const editor = await this.n.openEditor(this.y.createInstance($EVb), { ...options3 });
      if (options3.query) {
        editor.search(options3.query);
      }
    }
  }
  openDefaultKeybindingsFile() {
    return this.n.openEditor({ resource: this.defaultKeybindingsResource, label: localize(13039, null) });
  }
  async Q(resource, options3) {
    const group2 = options3?.openToSide ? $oJ : void 0;
    const editor = await this.R(resource, options3, group2);
    if (editor && options3?.revealSetting) {
      await this.hb(options3.revealSetting.key, !!options3.revealSetting.edit, editor, resource);
    }
    return editor;
  }
  async R(resource, options3, group2) {
    const openSplitJSON = !!this.t.getValue($XK);
    const openDefaultSettings = !!this.t.getValue($WK);
    if (openSplitJSON || openDefaultSettings) {
      return this.S(resource, options3, group2);
    }
    const configurationTarget = options3?.target ?? 2;
    const editableSettingsEditorInput = await this.ab(configurationTarget, resource);
    options3 = { ...options3, pinned: true };
    return await this.n.openEditor(editableSettingsEditorInput, $SK(options3), group2);
  }
  async S(resource, options3 = {}, group2) {
    const configurationTarget = options3.target ?? 2;
    await this.eb(configurationTarget, resource);
    const preferencesEditorInput = this.createSplitJsonEditorInput(configurationTarget, resource);
    options3 = { ...options3, pinned: true };
    return this.n.openEditor(preferencesEditorInput, $SK(options3), group2);
  }
  createSplitJsonEditorInput(configurationTarget, resource) {
    const editableSettingsEditorInput = this.I.createTextEditor({ resource });
    const defaultPreferencesEditorInput = this.I.createTextEditor({ resource: this.$(configurationTarget) });
    return this.y.createInstance($1I, editableSettingsEditorInput.getName(), void 0, defaultPreferencesEditorInput, editableSettingsEditorInput);
  }
  createSettings2EditorModel() {
    return this.y.createInstance($LK, this.db(
      3
      /* ConfigurationTarget.USER_LOCAL */
    ));
  }
  U(uri) {
    return this.Y(uri) ? 5 : this.Z(uri) ? 6 : 3;
  }
  W(uri) {
    return this.X(uri) || this.Y(uri) || this.Z(uri);
  }
  X(uri) {
    return uri.authority === "defaultsettings" && uri.scheme === Schemas.vscode && !!uri.path.match(/\/(\d+\/)?settings\.json$/);
  }
  Y(uri) {
    return uri.authority === "defaultsettings" && uri.scheme === Schemas.vscode && !!uri.path.match(/\/(\d+\/)?workspaceSettings\.json$/);
  }
  Z(uri) {
    return uri.authority === "defaultsettings" && uri.scheme === Schemas.vscode && !!uri.path.match(/\/(\d+\/)?resourceSettings\.json$/);
  }
  $(configurationTarget) {
    switch (configurationTarget) {
      case 5:
        return URI.from({ scheme: Schemas.vscode, authority: "defaultsettings", path: `/workspaceSettings.json` });
      case 6:
        return URI.from({ scheme: Schemas.vscode, authority: "defaultsettings", path: `/resourceSettings.json` });
    }
    return URI.from({ scheme: Schemas.vscode, authority: "defaultsettings", path: `/settings.json` });
  }
  async ab(target, resource) {
    await this.eb(target, resource);
    return this.I.createTextEditor({ resource });
  }
  async bb(configurationTarget, settingsUri) {
    const workspace2 = this.w.getWorkspace();
    if (workspace2.configuration && workspace2.configuration.toString() === settingsUri.toString()) {
      const reference2 = await this.D.createModelReference(settingsUri);
      return this.y.createInstance($MK, reference2, configurationTarget);
    }
    const reference = await this.D.createModelReference(settingsUri);
    return this.y.createInstance($KK, reference, configurationTarget);
  }
  async cb(defaultSettingsUri) {
    const reference = await this.D.createModelReference(defaultSettingsUri);
    const target = this.U(defaultSettingsUri);
    return this.y.createInstance($OK, defaultSettingsUri, reference, this.db(target));
  }
  db(target) {
    if (target === 5) {
      this.f ??= this.B(new $NK(this.gb(), target, this.t));
      return this.f;
    }
    if (target === 6) {
      this.g ??= this.B(new $NK(this.gb(), target, this.t));
      return this.g;
    }
    this.c ??= this.B(new $NK(this.gb(), target, this.t));
    return this.c;
  }
  async getEditableSettingsURI(configurationTarget, resource) {
    switch (configurationTarget) {
      case 1:
        return this.C.defaultProfile.settingsResource;
      case 2:
      case 3:
        return this.userSettingsResource;
      case 4: {
        const remoteEnvironment = await this.H.getEnvironment();
        return remoteEnvironment ? remoteEnvironment.settingsPath : null;
      }
      case 5:
        return this.workspaceSettingsResource;
      case 6:
        if (resource) {
          return this.getFolderSettingsResource(resource);
        }
    }
    return null;
  }
  async eb(target, resource) {
    if (this.w.getWorkbenchState() === 3 && target === 5) {
      const workspaceConfig = this.w.getWorkspace().configuration;
      if (!workspaceConfig) {
        return;
      }
      const content = await this.s.read(workspaceConfig);
      if (Object.keys($yw(content.value)).indexOf("settings") === -1) {
        await this.F.write(resource, [{ path: ["settings"], value: {} }], true);
      }
      return void 0;
    }
    await this.fb(resource, emptyEditableSettingsContent);
  }
  async fb(resource, contents) {
    try {
      await this.s.read(resource, { acceptTextOnly: true });
    } catch (error) {
      if (error.fileOperationResult === 1) {
        try {
          await this.s.write(resource, contents);
          return;
        } catch (error2) {
          throw new Error(localize(13040, null, this.G.getUriLabel(resource, { relative: true }), $qb(error2)));
        }
      } else {
        throw error;
      }
    }
  }
  gb() {
    return [
      "files.autoSave",
      "editor.fontSize",
      "editor.fontFamily",
      "editor.tabSize",
      "editor.renderWhitespace",
      "editor.cursorStyle",
      "editor.multiCursorModifier",
      "editor.insertSpaces",
      "editor.wordWrap",
      "files.exclude",
      "files.associations",
      "workbench.editor.enablePreview"
    ];
  }
  async hb(settingKey, edit3, editor, settingsResource) {
    const codeEditor = editor ? $S5(editor.getControl()) : null;
    if (!codeEditor) {
      return;
    }
    const settingsModel = await this.createPreferencesEditorModel(settingsResource);
    if (!settingsModel) {
      return;
    }
    const position = await this.ib(settingKey, edit3, settingsModel, codeEditor);
    if (position) {
      codeEditor.setPosition(position);
      codeEditor.revealPositionNearTop(position);
      codeEditor.focus();
      if (edit3) {
        $qdb.get(codeEditor)?.triggerSuggest();
      }
    }
  }
  async ib(settingKey, edit3, settingsModel, codeEditor) {
    const model = codeEditor.getModel();
    if (!model) {
      return null;
    }
    const schema9 = $Wn.as($Ht.Configuration).getConfigurationProperties()[settingKey];
    const isOverrideProperty = $Rt.test(settingKey);
    if (!schema9 && !isOverrideProperty) {
      return null;
    }
    let position = null;
    const type = schema9?.type ?? "object";
    let setting = settingsModel.getPreference(settingKey);
    if (!setting && edit3) {
      let defaultValue = type === "object" || type === "array" ? this.t.inspect(settingKey).defaultValue : $Ut(type);
      defaultValue = defaultValue === void 0 && isOverrideProperty ? {} : defaultValue;
      if (defaultValue !== void 0) {
        const key2 = settingsModel instanceof $MK ? ["settings", settingKey] : [settingKey];
        await this.F.write(settingsModel.uri, [{ path: key2, value: defaultValue }], false);
        setting = settingsModel.getPreference(settingKey);
      }
    }
    if (setting) {
      if (edit3) {
        if ($Bg(setting.value) || Array.isArray(setting.value)) {
          position = { lineNumber: setting.valueRange.startLineNumber, column: setting.valueRange.startColumn + 1 };
          codeEditor.setPosition(position);
          await CoreEditingCommands.LineBreakInsert.runEditorCommand(null, codeEditor, null);
          position = { lineNumber: position.lineNumber + 1, column: model.getLineMaxColumn(position.lineNumber + 1) };
          const firstNonWhiteSpaceColumn = model.getLineFirstNonWhitespaceColumn(position.lineNumber);
          if (firstNonWhiteSpaceColumn) {
            codeEditor.setPosition({ lineNumber: position.lineNumber, column: firstNonWhiteSpaceColumn });
            await CoreEditingCommands.LineBreakInsert.runEditorCommand(null, codeEditor, null);
            position = { lineNumber: position.lineNumber, column: model.getLineMaxColumn(position.lineNumber) };
          }
        } else {
          position = { lineNumber: setting.valueRange.startLineNumber, column: setting.valueRange.endColumn };
        }
      } else {
        position = { lineNumber: setting.keyRange.startLineNumber, column: setting.keyRange.startColumn };
      }
    }
    return position;
  }
  getSetting(settingId) {
    if (!this.m) {
      const defaultSettings = this.db(
        2
        /* ConfigurationTarget.USER */
      );
      const defaultsChangedDisposable = this.B(new $4c());
      defaultsChangedDisposable.value = defaultSettings.onDidChange(() => {
        this.m = void 0;
        defaultsChangedDisposable.clear();
      });
      this.m = defaultSettings.getSettingsGroups();
    }
    for (const group2 of this.m) {
      for (const section of group2.sections) {
        for (const setting of section.settings) {
          if ($Vf(setting.key, settingId) === 0) {
            return setting;
          }
        }
      }
    }
    return void 0;
  }
  /**
   * Should be of the format:
   * 	code://settings/settingName
   * Examples:
   * 	code://settings/files.autoSave
   *
   */
  async handleURL(uri) {
    if ($Vf(uri.authority, $YK) !== 0) {
      return false;
    }
    const settingInfo = uri.path.split("/").filter((part) => !!part);
    const settingId = settingInfo.length > 0 ? settingInfo[0] : void 0;
    if (!settingId) {
      this.openSettings();
      return true;
    }
    let setting = this.getSetting(settingId);
    if (!setting && this.J.extensions.length === 0) {
      await this.L.withProgress({
        location: 10
        /* ProgressLocation.Window */
      }, () => Event2.toPromise(this.J.onDidRegisterExtensions));
      setting = this.getSetting(settingId);
    }
    const openSettingsOptions = {};
    if (setting) {
      openSettingsOptions.query = settingId;
    }
    this.openSettings(openSettingsOptions);
    return true;
  }
  dispose() {
    this.a.fire();
    super.dispose();
  }
};
$GVb = __decorate([
  __param(0, $mJ),
  __param(1, $iJ),
  __param(2, $cK),
  __param(3, $kl),
  __param(4, $PJ),
  __param(5, $Zk),
  __param(6, $Pk),
  __param(7, $gT),
  __param(8, $rs),
  __param(9, $oG),
  __param(10, $Ty),
  __param(11, $sG),
  __param(12, $CBb),
  __param(13, $ZI),
  __param(14, $RL),
  __param(15, $YUb),
  __param(16, $4y),
  __param(17, $wN),
  __param(18, $TJ)
], $GVb);
$SC(
  $TK,
  $GVb,
  1
  /* InstantiationType.Delayed */
);

// out-build/vs/workbench/services/configuration/common/jsonEditingService.js
var $HVb = class $HVb2 {
  constructor(b, c, d) {
    this.b = b;
    this.c = c;
    this.d = d;
    this.a = new $3h();
  }
  write(resource, values) {
    return Promise.resolve(this.a.queue(() => this.e(resource, values)));
  }
  async e(resource, values) {
    const reference = await this.k(resource, true);
    try {
      await this.f(reference.object.textEditorModel, values);
    } finally {
      reference.dispose();
    }
  }
  async f(model, values) {
    let hasEdits = false;
    for (const value of values) {
      const edit3 = this.h(model, value)[0];
      hasEdits = !!edit3 && this.g(edit3, model);
    }
    if (hasEdits) {
      return this.d.save(model.uri);
    }
  }
  g(edit3, model) {
    const startPosition = model.getPositionAt(edit3.offset);
    const endPosition = model.getPositionAt(edit3.offset + edit3.length);
    const range = new $9C(startPosition.lineNumber, startPosition.column, endPosition.lineNumber, endPosition.column);
    const currentText = model.getValueInRange(range);
    if (edit3.content !== currentText) {
      const editOperation = currentText ? $bD.replace(range, edit3.content) : $bD.insert(startPosition, edit3.content);
      model.pushEditOperations([new $_D(startPosition.lineNumber, startPosition.column, startPosition.lineNumber, startPosition.column)], [editOperation], () => []);
      return true;
    }
    return false;
  }
  h(model, configurationValue) {
    const { tabSize, insertSpaces } = model.getOptions();
    const eol = model.getEOL();
    const { path, value } = configurationValue;
    if (!path.length) {
      const content = JSON.stringify(value, null, insertSpaces ? " ".repeat(tabSize) : "	");
      return [{
        content,
        length: content.length,
        offset: 0
      }];
    }
    return $Xw(model.getValue(), path, value, { tabSize, insertSpaces, eol });
  }
  async i(resource) {
    const exists = await this.b.exists(resource);
    if (!exists) {
      await this.d.write(resource, "{}", { encoding: "utf8" });
    }
    return this.c.createModelReference(resource);
  }
  j(model) {
    const parseErrors = [];
    $yw(model.getValue(), parseErrors, { allowTrailingComma: true, allowEmptyContent: true });
    return parseErrors.length > 0;
  }
  async k(resource, checkDirty) {
    const reference = await this.i(resource);
    const model = reference.object.textEditorModel;
    if (this.j(model)) {
      reference.dispose();
      return this.l(
        0
        /* JSONEditingErrorCode.ERROR_INVALID_FILE */
      );
    }
    return reference;
  }
  l(code) {
    const message = this.m(code);
    return Promise.reject(new $DBb(message, code));
  }
  m(error) {
    switch (error) {
      case 0: {
        return localize(12610, null);
      }
    }
  }
};
$HVb = __decorate([
  __param(0, $km),
  __param(1, $oG),
  __param(2, $cK)
], $HVb);
$SC(
  $CBb,
  $HVb,
  1
  /* InstantiationType.Delayed */
);

// out-build/vs/workbench/services/textfile/common/textFileEditorModel.js
var $IVb_1;
var $IVb = class $IVb2 extends $xG {
  static {
    $IVb_1 = this;
  }
  static {
    this.L = $bL.registerSource("textFileEncoding.source", localize(13129, null));
  }
  static {
    this.cb = 500;
  }
  constructor(resource, jb, kb, languageService, modelService, lb, mb, nb, ob, pb, qb, rb, languageDetectionService, accessibilityService, sb, tb, ub) {
    super(modelService, languageService, languageDetectionService, accessibilityService);
    this.resource = resource;
    this.jb = jb;
    this.kb = kb;
    this.lb = lb;
    this.mb = mb;
    this.nb = nb;
    this.ob = ob;
    this.pb = pb;
    this.qb = qb;
    this.rb = rb;
    this.sb = sb;
    this.tb = tb;
    this.ub = ub;
    this.M = this.B(new $ze());
    this.onDidChangeContent = this.M.event;
    this.N = this.B(new $ze());
    this.onDidResolve = this.N.event;
    this.O = this.B(new $ze());
    this.onDidChangeDirty = this.O.event;
    this.P = this.B(new $ze());
    this.onDidSaveError = this.P.event;
    this.Q = this.B(new $ze());
    this.onDidSave = this.Q.event;
    this.R = this.B(new $ze());
    this.onDidRevert = this.R.event;
    this.S = this.B(new $ze());
    this.onDidChangeEncoding = this.S.event;
    this.U = this.B(new $ze());
    this.onDidChangeOrphaned = this.U.event;
    this.W = this.B(new $ze());
    this.onDidChangeReadonly = this.W.event;
    this.typeId = $qG;
    this.capabilities = 0;
    this.name = $rc(this.rb.getUriLabel(this.resource));
    this.X = !!$lh.extname(this.resource);
    this.Z = 0;
    this.ab = false;
    this.bb = false;
    this.db = void 0;
    this.eb = new $ei();
    this.fb = false;
    this.gb = false;
    this.hb = false;
    this.ib = false;
    this.Tb = false;
    this.B(this.pb.registerWorkingCopy(this));
    this.vb();
  }
  vb() {
    this.B(this.lb.onDidFilesChange((e) => this.wb(e)));
    this.B(this.qb.onDidChangeFilesAssociation(() => this.yb()));
    this.B(this.qb.onDidChangeReadonly(() => this.W.fire()));
  }
  async wb(e) {
    let fileEventImpactsModel = false;
    let newInOrphanModeGuess;
    if (this.hb) {
      const modelFileAdded = e.contains(
        this.resource,
        1
        /* FileChangeType.ADDED */
      );
      if (modelFileAdded) {
        newInOrphanModeGuess = false;
        fileEventImpactsModel = true;
      }
    } else {
      const modelFileDeleted = e.contains(
        this.resource,
        2
        /* FileChangeType.DELETED */
      );
      if (modelFileDeleted) {
        newInOrphanModeGuess = true;
        fileEventImpactsModel = true;
      }
    }
    if (fileEventImpactsModel && this.hb !== newInOrphanModeGuess) {
      let newInOrphanModeValidated = false;
      if (newInOrphanModeGuess) {
        await $Wh(100, CancellationToken.None);
        if (this.isDisposed()) {
          newInOrphanModeValidated = true;
        } else {
          const exists = await this.lb.exists(this.resource);
          newInOrphanModeValidated = !exists;
        }
      }
      if (this.hb !== newInOrphanModeValidated && !this.isDisposed()) {
        this.xb(newInOrphanModeValidated);
      }
    }
  }
  xb(orphaned) {
    if (this.hb !== orphaned) {
      this.hb = orphaned;
      this.U.fire();
    }
  }
  yb() {
    if (!this.isResolved()) {
      return;
    }
    const firstLineText = this.I(this.textEditorModel);
    const languageSelection = this.J(this.resource, this.r, this.kb, firstLineText);
    this.textEditorModel.setLanguage(languageSelection);
  }
  setLanguageId(languageId, source) {
    super.setLanguageId(languageId, source);
    this.kb = languageId;
  }
  //#region Backup
  async backup(token) {
    let meta = void 0;
    if (this.lastResolvedFileStat) {
      meta = {
        mtime: this.lastResolvedFileStat.mtime,
        ctime: this.lastResolvedFileStat.ctime,
        size: this.lastResolvedFileStat.size,
        etag: this.lastResolvedFileStat.etag,
        orphaned: this.hb
      };
    }
    const content = await this.mb.getEncodedReadable(this.resource, this.createSnapshot() ?? void 0, { encoding: $uJ });
    return { meta, content };
  }
  //#endregion
  //#region Revert
  async revert(options3) {
    if (!this.isResolved()) {
      return;
    }
    const wasDirty = this.fb;
    const undo = this.Lb(false);
    const softUndo = options3?.soft;
    if (!softUndo) {
      try {
        await this.Kb();
      } catch (error) {
        if (error.fileOperationResult !== 1) {
          undo();
          throw error;
        }
      }
    }
    this.R.fire();
    if (wasDirty) {
      this.O.fire();
    }
  }
  //#endregion
  //#region Resolve
  async resolve(options3) {
    this.Wb("resolve() - enter");
    $S("code/willResolveTextFileEditorModel");
    if (this.isDisposed()) {
      this.Wb("resolve() - exit - without resolving because model is disposed");
      return;
    }
    if (!options3?.contents && (this.fb || this.eb.isRunning())) {
      this.Wb("resolve() - exit - without resolving because model is dirty or being saved");
      return;
    }
    await this.zb(options3);
    $S("code/didResolveTextFileEditorModel");
  }
  async zb(options3) {
    if (options3?.contents) {
      return this.Ab(options3.contents, options3);
    }
    const isNewModel = !this.isResolved();
    if (isNewModel) {
      const resolvedFromBackup = await this.Bb(options3);
      if (resolvedFromBackup) {
        return;
      }
    }
    return this.Db(options3);
  }
  async Ab(buffer, options3) {
    this.Wb("resolveFromBuffer()");
    let mtime;
    let ctime;
    let size;
    let etag;
    try {
      const metadata = await this.lb.stat(this.resource);
      mtime = metadata.mtime;
      ctime = metadata.ctime;
      size = metadata.size;
      etag = metadata.etag;
      this.xb(false);
    } catch (error) {
      mtime = Date.now();
      ctime = Date.now();
      size = 0;
      etag = $Pm;
      this.xb(
        error.fileOperationResult === 1
        /* FileOperationResult.FILE_NOT_FOUND */
      );
    }
    const preferredEncoding = await this.mb.encoding.getPreferredWriteEncoding(this.resource, this.jb);
    this.Eb({
      resource: this.resource,
      name: this.name,
      mtime,
      ctime,
      size,
      etag,
      value: buffer,
      encoding: preferredEncoding.encoding,
      readonly: false,
      locked: false
    }, true, options3);
  }
  async Bb(options3) {
    const backup = await this.nb.resolve(this);
    let encoding = $uJ;
    if (backup) {
      encoding = (await this.mb.encoding.getPreferredWriteEncoding(this.resource, this.jb)).encoding;
    }
    const isNewModel = !this.isResolved();
    if (!isNewModel) {
      this.Wb("resolveFromBackup() - exit - without resolving because previously new model got created meanwhile");
      return true;
    }
    if (backup) {
      await this.Cb(backup, encoding, options3);
      return true;
    }
    return false;
  }
  async Cb(backup, encoding, options3) {
    this.Wb("doResolveFromBackup()");
    this.Eb({
      resource: this.resource,
      name: this.name,
      mtime: backup.meta ? backup.meta.mtime : Date.now(),
      ctime: backup.meta ? backup.meta.ctime : Date.now(),
      size: backup.meta ? backup.meta.size : 0,
      etag: backup.meta ? backup.meta.etag : $Pm,
      // etag disabled if unknown!
      value: await $NI(await this.mb.getDecodedStream(this.resource, backup.value, { encoding: $uJ })),
      encoding,
      readonly: false,
      locked: false
    }, true, options3);
    if (backup.meta?.orphaned) {
      this.xb(true);
    }
  }
  async Db(options3) {
    this.Wb("resolveFromFile()");
    const forceReadFromFile = options3?.forceReadFromFile;
    const allowBinary = this.isResolved() || options3?.allowBinary;
    let etag;
    if (forceReadFromFile) {
      etag = $Pm;
    } else if (this.lastResolvedFileStat) {
      etag = this.lastResolvedFileStat.etag;
    }
    const currentVersionId = this.Z;
    try {
      const content = await this.mb.readStream(this.resource, {
        acceptTextOnly: !allowBinary,
        etag,
        encoding: this.jb,
        limits: options3?.limits
      });
      this.xb(false);
      if (currentVersionId !== this.Z) {
        this.Wb("resolveFromFile() - exit - without resolving because model content changed");
        return;
      }
      return this.Eb(content, false, options3);
    } catch (error) {
      const result = error.fileOperationResult;
      this.xb(
        result === 1
        /* FileOperationResult.FILE_NOT_FOUND */
      );
      if (this.isResolved() && result === 2) {
        if (error instanceof $Hm) {
          this.Rb(error.stat);
        }
        return;
      }
      if (this.isResolved() && result === 1 && !forceReadFromFile) {
        return;
      }
      throw error;
    }
  }
  Eb(content, dirty, options3) {
    this.Wb("resolveFromContent() - enter");
    if (this.isDisposed()) {
      this.Wb("resolveFromContent() - exit - because model is disposed");
      return;
    }
    this.Rb({
      resource: this.resource,
      name: content.name,
      mtime: content.mtime,
      ctime: content.ctime,
      size: content.size,
      etag: content.etag,
      readonly: content.readonly,
      locked: content.locked,
      isFile: true,
      isDirectory: false,
      isSymbolicLink: false,
      children: void 0
    });
    const oldEncoding = this.Y;
    this.Y = content.encoding;
    if (this.jb) {
      this.updatePreferredEncoding(this.Y);
    } else if (oldEncoding !== this.Y) {
      this.S.fire();
    }
    if (this.textEditorModel) {
      this.Gb(content.value);
    } else {
      this.Fb(content.resource, content.value);
    }
    this.setDirty(!!dirty);
    this.N.fire(
      options3?.reason ?? 3
      /* TextFileResolveReason.OTHER */
    );
  }
  Fb(resource, value) {
    this.Wb("doCreateTextModel()");
    const textModel = this.G(value, resource, this.kb);
    this.C(textModel);
    this.D();
  }
  Gb(value) {
    this.Wb("doUpdateTextModel()");
    this.ab = true;
    try {
      this.updateTextEditorModel(value, this.kb);
    } finally {
      this.ab = false;
    }
  }
  C(model) {
    this.B(model.onDidChangeContent((e) => this.Ib(model, e.isUndoing || e.isRedoing)));
    this.B(model.onDidChangeLanguage(() => this.Sb()));
    super.C(model);
  }
  Ib(model, isUndoingOrRedoing) {
    this.Wb(`onModelContentChanged() - enter`);
    this.Z++;
    this.Wb(`onModelContentChanged() - new versionId ${this.Z}`);
    if (isUndoingOrRedoing) {
      this.db = Date.now();
    }
    if (!this.ab && !this.isReadonly()) {
      if (model.getAlternativeVersionId() === this.$) {
        this.Wb("onModelContentChanged() - model content changed back to last saved version");
        const wasDirty = this.fb;
        this.setDirty(false);
        if (wasDirty) {
          this.R.fire();
        }
      } else {
        this.Wb("onModelContentChanged() - model content changed and marked as dirty");
        this.setDirty(true);
      }
    }
    this.M.fire();
    this.D();
  }
  async D() {
    await this.tb?.whenInstalledExtensionsRegistered();
    const languageId = this.getLanguageId();
    if (this.resource.scheme === this.sb.defaultUriScheme && // make sure to not detect language for non-user visible documents
    (!languageId || languageId === $KF) && // only run on files with plaintext language set or no language set at all
    !this.X) {
      return super.D();
    }
  }
  async Kb() {
    if (this.isDisposed()) {
      return;
    }
    await this.mb.files.resolve(this.resource, {
      reload: { async: false },
      forceReadFromFile: true
    });
  }
  //#endregion
  //#region Dirty
  isDirty() {
    return this.fb;
  }
  isModified() {
    return this.isDirty();
  }
  setDirty(dirty) {
    if (!this.isResolved()) {
      return;
    }
    const wasDirty = this.fb;
    this.Lb(dirty);
    if (dirty !== wasDirty) {
      this.O.fire();
    }
  }
  Lb(dirty) {
    const wasDirty = this.fb;
    const wasInConflictMode = this.gb;
    const wasInErrorMode = this.ib;
    const oldBufferSavedVersionId = this.$;
    if (!dirty) {
      this.fb = false;
      this.gb = false;
      this.ib = false;
      this.Qb();
    } else {
      this.fb = true;
    }
    return () => {
      this.fb = wasDirty;
      this.gb = wasInConflictMode;
      this.ib = wasInErrorMode;
      this.$ = oldBufferSavedVersionId;
    };
  }
  //#endregion
  //#region Save
  async save(options3 = /* @__PURE__ */ Object.create(null)) {
    if (!this.isResolved()) {
      return false;
    }
    if (this.isReadonly()) {
      this.Wb("save() - ignoring request for readonly resource");
      return false;
    }
    if ((this.hasState(
      3
      /* TextFileEditorModelState.CONFLICT */
    ) || this.hasState(
      5
      /* TextFileEditorModelState.ERROR */
    )) && (options3.reason === 2 || options3.reason === 3 || options3.reason === 4)) {
      this.Wb("save() - ignoring auto save request for model that is in conflict or error");
      return false;
    }
    this.Wb("save() - enter");
    await this.Mb(options3);
    this.Wb("save() - exit");
    return this.hasState(
      0
      /* TextFileEditorModelState.SAVED */
    );
  }
  async Mb(options3) {
    if (typeof options3.reason !== "number") {
      options3.reason = 1;
    }
    const versionId = this.Z;
    this.Wb(`doSave(${versionId}) - enter with versionId ${versionId}`);
    if (this.bb) {
      this.Wb(`doSave(${versionId}) - exit - refusing to save() recursively from save participant`);
      return;
    }
    if (this.eb.isRunning(versionId)) {
      this.Wb(`doSave(${versionId}) - exit - found a running save for versionId ${versionId}`);
      return this.eb.running;
    }
    if (!options3.force && !this.fb) {
      this.Wb(`doSave(${versionId}) - exit - because not dirty and/or versionId is different (this.isDirty: ${this.fb}, this.versionId: ${this.Z})`);
      return;
    }
    if (this.eb.isRunning()) {
      this.Wb(`doSave(${versionId}) - exit - because busy saving`);
      this.eb.cancelRunning();
      return this.eb.queue(() => this.Mb(options3));
    }
    if (this.isResolved()) {
      this.textEditorModel.pushStackElement();
    }
    const saveCancellation = new $ad();
    return this.ub.withProgress({
      title: localize(13130, null, this.name),
      location: 10,
      cancellable: true,
      delay: this.isDirty() ? 3e3 : 5e3
    }, (progress) => {
      return this.Nb(versionId, options3, progress, saveCancellation);
    }, () => {
      saveCancellation.cancel();
    }).finally(() => {
      saveCancellation.dispose();
    });
  }
  Nb(versionId, options3, progress, saveCancellation) {
    return this.eb.run(versionId, (async () => {
      if (this.isResolved() && !options3.skipSaveParticipants) {
        try {
          if (options3.reason === 2 && typeof this.db === "number") {
            const timeFromUndoRedoToSave = Date.now() - this.db;
            if (timeFromUndoRedoToSave < $IVb_1.cb) {
              await $Wh($IVb_1.cb - timeFromUndoRedoToSave);
            }
          }
          if (!saveCancellation.token.isCancellationRequested) {
            this.bb = true;
            try {
              await this.mb.files.runSaveParticipants(this, { reason: options3.reason ?? 1, savedFrom: options3.from }, progress, saveCancellation.token);
            } catch (err) {
              if ($kb(err) && !saveCancellation.token.isCancellationRequested) {
                saveCancellation.cancel();
              }
            } finally {
              this.bb = false;
            }
          }
        } catch (error) {
          this.ob.error(`[text file model] runSaveParticipants(${versionId}) - resulted in an error: ${error.toString()}`, this.resource.toString());
        }
      }
      if (saveCancellation.token.isCancellationRequested) {
        return;
      } else {
        saveCancellation.dispose();
      }
      if (this.isDisposed()) {
        return;
      }
      if (!this.isResolved()) {
        return;
      }
      versionId = this.Z;
      this.ib = false;
      progress.report({ message: localize(13131, null) });
      this.Wb(`doSave(${versionId}) - before write()`);
      const lastResolvedFileStat = $Kg(this.lastResolvedFileStat);
      const resolvedTextFileEditorModel = this;
      return this.eb.run(versionId, (async () => {
        try {
          const stat = await this.mb.write(lastResolvedFileStat.resource, resolvedTextFileEditorModel.createSnapshot(), {
            mtime: lastResolvedFileStat.mtime,
            encoding: this.getEncoding(),
            etag: options3.ignoreModifiedSince || !this.qb.preventSaveConflicts(lastResolvedFileStat.resource, resolvedTextFileEditorModel.getLanguageId()) ? $Pm : lastResolvedFileStat.etag,
            unlock: options3.writeUnlock,
            writeElevated: options3.writeElevated
          });
          this.Ob(stat, versionId, options3);
        } catch (error) {
          this.Pb(error, versionId, options3);
        }
      })());
    })(), () => saveCancellation.cancel());
  }
  Ob(stat, versionId, options3) {
    this.Rb(stat);
    if (versionId === this.Z) {
      this.Wb(`handleSaveSuccess(${versionId}) - setting dirty to false because versionId did not change`);
      this.setDirty(false);
    } else {
      this.Wb(`handleSaveSuccess(${versionId}) - not setting dirty to false because versionId did change meanwhile`);
    }
    this.xb(false);
    this.Q.fire({ reason: options3.reason, stat, source: options3.source });
  }
  Pb(error, versionId, options3) {
    (options3.ignoreErrorHandler ? this.ob.trace : this.ob.error).apply(this.ob, [`[text file model] handleSaveError(${versionId}) - exit - resulted in a save error: ${error.toString()}`, this.resource.toString()]);
    if (options3.ignoreErrorHandler) {
      throw error;
    }
    this.setDirty(true);
    this.ib = true;
    if (error.fileOperationResult === 3) {
      this.gb = true;
    }
    this.mb.files.saveErrorHandler.onSaveError(error, this, options3);
    this.P.fire();
  }
  Qb() {
    if (this.isResolved()) {
      this.$ = this.textEditorModel.getAlternativeVersionId();
    }
  }
  Rb(newFileStat) {
    const oldReadonly = this.isReadonly();
    if (!this.lastResolvedFileStat) {
      this.lastResolvedFileStat = newFileStat;
    } else if (this.lastResolvedFileStat.mtime <= newFileStat.mtime) {
      this.lastResolvedFileStat = newFileStat;
    } else {
      this.lastResolvedFileStat = { ...this.lastResolvedFileStat, readonly: newFileStat.readonly, locked: newFileStat.locked };
    }
    if (this.isReadonly() !== oldReadonly) {
      this.W.fire();
    }
  }
  //#endregion
  hasState(state) {
    switch (state) {
      case 3:
        return this.gb;
      case 1:
        return this.fb;
      case 5:
        return this.ib;
      case 4:
        return this.hb;
      case 2:
        return this.eb.isRunning();
      case 0:
        return !this.fb;
    }
  }
  async joinState(state) {
    return this.eb.running;
  }
  getLanguageId() {
    if (this.textEditorModel) {
      return this.textEditorModel.getLanguageId();
    }
    return this.kb;
  }
  //#region Encoding
  async Sb() {
    if (this.Tb) {
      this.Wb("onMaybeShouldChangeEncoding() - ignoring because encoding was set explicitly");
      return;
    }
    if (this.Y === $vJ || this.Y === $wJ || this.Y === $xJ) {
      this.Wb("onMaybeShouldChangeEncoding() - ignoring because content encoding has a BOM");
      return;
    }
    const { encoding } = await this.mb.encoding.getPreferredReadEncoding(this.resource);
    if (typeof encoding !== "string" || !this.Vb(encoding)) {
      this.Wb(`onMaybeShouldChangeEncoding() - ignoring because preferred encoding ${encoding} is not new`);
      return;
    }
    if (this.isDirty()) {
      this.Wb("onMaybeShouldChangeEncoding() - ignoring because model is dirty");
      return;
    }
    this.ob.info(`Adjusting encoding based on configured language override to '${encoding}' for ${this.resource.toString(true)}.`);
    return this.Kb();
  }
  setEncoding(encoding, mode) {
    this.Tb = true;
    return this.Ub(encoding, mode);
  }
  async Ub(encoding, mode) {
    if (mode === 0) {
      this.updatePreferredEncoding(encoding);
      if (!this.isDirty()) {
        this.Z++;
        this.setDirty(true);
      }
      if (!this.gb) {
        await this.save({ source: $IVb_1.L });
      }
    } else {
      if (!this.Vb(encoding)) {
        return;
      }
      if (this.isDirty() && !this.gb) {
        await this.save();
      }
      this.updatePreferredEncoding(encoding);
      await this.Kb();
    }
  }
  updatePreferredEncoding(encoding) {
    if (!this.Vb(encoding)) {
      return;
    }
    this.jb = encoding;
    this.S.fire();
  }
  Vb(encoding) {
    if (this.jb === encoding) {
      return false;
    }
    if (!this.jb && this.Y === encoding) {
      return false;
    }
    return true;
  }
  getEncoding() {
    return this.jb || this.Y;
  }
  //#endregion
  Wb(msg) {
    this.ob.trace(`[text file model] ${msg}`, this.resource.toString());
  }
  isResolved() {
    return !!this.textEditorModel;
  }
  isReadonly() {
    return this.qb.isReadonly(this.resource, this.lastResolvedFileStat);
  }
  dispose() {
    this.Wb("dispose()");
    this.gb = false;
    this.hb = false;
    this.ib = false;
    super.dispose();
  }
};
$IVb = $IVb_1 = __decorate([
  __param(3, $1E),
  __param(4, $sG),
  __param(5, $km),
  __param(6, $cK),
  __param(7, $yG),
  __param(8, $wn),
  __param(9, $XI),
  __param(10, $4J),
  __param(11, $ZI),
  __param(12, $tG),
  __param(13, $ND),
  __param(14, $aT),
  __param(15, $wN),
  __param(16, $TJ)
], $IVb);

// out-build/vs/editor/common/services/modelUndoRedoParticipant.js
var $JVb = class $JVb2 extends $3c {
  constructor(a, b, c) {
    super();
    this.a = a;
    this.b = b;
    this.c = c;
    this.B(this.a.onModelRemoved((model) => {
      const elements = this.c.getElements(model.uri);
      if (elements.past.length === 0 && elements.future.length === 0) {
        return;
      }
      for (const element of elements.past) {
        if (element instanceof $RH) {
          element.setDelegate(this);
        }
      }
      for (const element of elements.future) {
        if (element instanceof $RH) {
          element.setDelegate(this);
        }
      }
    }));
  }
  prepareUndoRedo(element) {
    const missingModels = element.getMissingModels();
    if (missingModels.length === 0) {
      return $3c.None;
    }
    const disposablesPromises = missingModels.map(async (uri) => {
      try {
        const reference = await this.b.createModelReference(uri);
        return reference;
      } catch (err) {
        return $3c.None;
      }
    });
    return Promise.all(disposablesPromises).then((disposables) => {
      return {
        dispose: () => $Xc(disposables)
      };
    });
  }
};
$JVb = __decorate([
  __param(0, $sG),
  __param(1, $oG),
  __param(2, $_F)
], $JVb);

// out-build/vs/workbench/services/textmodelResolver/common/textModelResolverService.js
var ResourceModelCollection = class ResourceModelCollection2 extends $8c {
  constructor(h3, j, m, n) {
    super();
    this.h = h3;
    this.j = j;
    this.m = m;
    this.n = n;
    this.f = /* @__PURE__ */ new Map();
    this.g = /* @__PURE__ */ new Set();
  }
  b(key2) {
    return this.r(key2);
  }
  async r(key2, skipActivateProvider) {
    this.g.delete(key2);
    const resource = URI.parse(key2);
    if (resource.scheme === Schemas.inMemory) {
      const cachedModel = this.n.getModel(resource);
      if (!cachedModel) {
        throw new Error(`Unable to resolve inMemory resource ${key2}`);
      }
      const model = this.h.createInstance($4vb, resource);
      if (this.s(model, key2)) {
        return model;
      }
    }
    if (resource.scheme === Schemas.untitled) {
      const model = await this.j.untitled.resolve({ untitledResource: resource });
      if (this.s(model, key2)) {
        return model;
      }
    }
    if (this.m.hasProvider(resource)) {
      const model = await this.j.files.resolve(resource, {
        reason: 2
        /* TextFileResolveReason.REFERENCE */
      });
      if (this.s(model, key2)) {
        return model;
      }
    }
    if (this.f.has(resource.scheme)) {
      await this.u(key2);
      const model = this.h.createInstance($4vb, resource);
      if (this.s(model, key2)) {
        return model;
      }
    }
    if (!skipActivateProvider) {
      await this.m.activateProvider(resource.scheme);
      return this.r(key2, true);
    }
    throw new Error(`Unable to resolve resource ${key2}`);
  }
  s(model, key2) {
    if ($pG(model)) {
      return true;
    }
    throw new Error(`Unable to resolve resource ${key2}`);
  }
  c(key2, modelPromise) {
    const resource = URI.parse(key2);
    if (resource.scheme === Schemas.inMemory) {
      return;
    }
    this.g.add(key2);
    (async () => {
      try {
        const model = await modelPromise;
        if (!this.g.has(key2)) {
          return;
        }
        if (model instanceof $IVb) {
          await this.j.files.canDispose(model);
        } else if (model instanceof $MJ) {
          await this.j.untitled.canDispose(model);
        }
        if (!this.g.has(key2)) {
          return;
        }
        model.dispose();
      } catch (error) {
      } finally {
        this.g.delete(key2);
      }
    })();
  }
  registerTextModelContentProvider(scheme, provider) {
    let providers2 = this.f.get(scheme);
    if (!providers2) {
      providers2 = [];
      this.f.set(scheme, providers2);
    }
    providers2.unshift(provider);
    return $1c(() => {
      const providersForScheme = this.f.get(scheme);
      if (!providersForScheme) {
        return;
      }
      const index = providersForScheme.indexOf(provider);
      if (index === -1) {
        return;
      }
      providersForScheme.splice(index, 1);
      if (providersForScheme.length === 0) {
        this.f.delete(scheme);
      }
    });
  }
  hasTextModelContentProvider(scheme) {
    return this.f.get(scheme) !== void 0;
  }
  async u(key2) {
    const resource = URI.parse(key2);
    const providersForScheme = this.f.get(resource.scheme) || [];
    for (const provider of providersForScheme) {
      const value = await provider.provideTextContent(resource);
      if (value) {
        return value;
      }
    }
    throw new Error(`Unable to resolve text model content for resource ${key2}`);
  }
};
ResourceModelCollection = __decorate([
  __param(0, $Pk),
  __param(1, $cK),
  __param(2, $km),
  __param(3, $sG)
], ResourceModelCollection);
var $KVb = class $KVb2 extends $3c {
  get b() {
    if (!this.a) {
      this.a = this.g.createInstance(ResourceModelCollection);
    }
    return this.a;
  }
  get f() {
    if (!this.c) {
      this.c = new $9c(this.b);
    }
    return this.c;
  }
  constructor(g, h3, j, m, n) {
    super();
    this.g = g;
    this.h = h3;
    this.j = j;
    this.m = m;
    this.n = n;
    this.a = void 0;
    this.c = void 0;
    this.B(new $JVb(this.m, this, this.j));
  }
  async createModelReference(resource) {
    resource = this.n.asCanonicalUri(resource);
    return await this.f.acquire(resource.toString());
  }
  registerTextModelContentProvider(scheme, provider) {
    return this.b.registerTextModelContentProvider(scheme, provider);
  }
  canHandleResource(resource) {
    if (this.h.hasProvider(resource) || resource.scheme === Schemas.untitled || resource.scheme === Schemas.inMemory) {
      return true;
    }
    return this.b.hasTextModelContentProvider(resource.scheme);
  }
};
$KVb = __decorate([
  __param(0, $Pk),
  __param(1, $km),
  __param(2, $_F),
  __param(3, $sG),
  __param(4, $vl)
], $KVb);
$SC(
  $oG,
  $KVb,
  1
  /* InstantiationType.Delayed */
);

// out-build/vs/workbench/browser/parts/editor/editorsObserver.js
var $LVb_1;
var $LVb = class $LVb2 extends $3c {
  static {
    $LVb_1 = this;
  }
  static {
    this.a = "editors.mru";
  }
  get count() {
    return this.c.size;
  }
  get editors() {
    return [...this.c.values()];
  }
  hasEditor(editor) {
    const editors = this.f.get(editor.resource);
    return editors?.has(this.h(editor)) ?? false;
  }
  hasEditors(resource) {
    return this.f.has(resource);
  }
  h(arg1, editorId) {
    if (typeof arg1 !== "string") {
      return this.h(arg1.typeId, arg1.editorId);
    }
    if (editorId) {
      return `${arg1}/${editorId}`;
    }
    return arg1;
  }
  constructor(editorGroupsContainer, n, r2) {
    super();
    this.n = n;
    this.r = r2;
    this.b = /* @__PURE__ */ new Map();
    this.c = new $Gc();
    this.f = new $Ec();
    this.g = this.B(new $ze());
    this.onDidMostRecentlyActiveEditorsChange = this.g.event;
    this.j = editorGroupsContainer ?? n;
    this.m = !!editorGroupsContainer;
    this.s();
    this.L();
  }
  s() {
    this.B(this.j.onDidAddGroup((group2) => this.t(group2)));
    this.B(this.n.onDidChangeEditorPartOptions((e) => this.w(e)));
    this.B(this.r.onWillSaveState(() => this.I()));
  }
  t(group2) {
    const groupEditorsMru = group2.getEditors(
      0
      /* EditorsOrder.MOST_RECENTLY_ACTIVE */
    );
    for (let i2 = groupEditorsMru.length - 1; i2 >= 0; i2--) {
      this.y(
        group2,
        groupEditorsMru[i2],
        false,
        true
        /* is new */
      );
    }
    if (this.j.activeGroup === group2 && group2.activeEditor) {
      this.y(
        group2,
        group2.activeEditor,
        true,
        false
        /* already added before */
      );
    }
    this.u(group2);
  }
  u(group2) {
    const groupDisposables = new $2c();
    groupDisposables.add(group2.onDidModelChange((e) => {
      switch (e.kind) {
        case 0: {
          if (this.j.activeGroup === group2 && group2.activeEditor) {
            this.y(
              group2,
              group2.activeEditor,
              true,
              false
              /* editor already opened */
            );
          }
          break;
        }
        case 5: {
          if (e.editor) {
            this.y(
              group2,
              e.editor,
              false,
              true
              /* is new */
            );
            this.G({ groupId: group2.id, editor: e.editor }, group2.id);
          }
          break;
        }
      }
    }));
    groupDisposables.add(group2.onDidCloseEditor((e) => {
      this.C(group2, e.editor);
    }));
    groupDisposables.add(group2.onDidActiveEditorChange((e) => {
      if (e.editor) {
        this.y(
          group2,
          e.editor,
          this.j.activeGroup === group2,
          false
          /* editor already opened */
        );
      }
    }));
    Event2.once(group2.onWillDispose)(() => $Xc(groupDisposables));
  }
  w(event) {
    if (!$Pv(event.newPartOptions.limit, event.oldPartOptions.limit)) {
      const activeGroup = this.j.activeGroup;
      let exclude = void 0;
      if (activeGroup.activeEditor) {
        exclude = { editor: activeGroup.activeEditor, groupId: activeGroup.id };
      }
      this.G(exclude);
    }
  }
  y(group2, editor, isActive2, isNew) {
    const key2 = this.F(group2, editor);
    const mostRecentEditor = this.c.first;
    if (isActive2 || !mostRecentEditor) {
      this.c.set(key2, key2, mostRecentEditor ? 1 : void 0);
    } else {
      this.c.set(
        key2,
        key2,
        1
        /* Touch.AsOld */
      );
      this.c.set(
        mostRecentEditor,
        mostRecentEditor,
        1
        /* Touch.AsOld */
      );
    }
    if (isNew) {
      this.z(editor, true);
    }
    this.g.fire();
  }
  z(editor, add) {
    let resource = void 0;
    let typeId2 = void 0;
    let editorId = void 0;
    if (editor instanceof $1I) {
      resource = editor.primary.resource;
      typeId2 = editor.primary.typeId;
      editorId = editor.primary.editorId;
    } else {
      resource = editor.resource;
      typeId2 = editor.typeId;
      editorId = editor.editorId;
    }
    if (!resource) {
      return;
    }
    const identifier2 = this.h(typeId2, editorId);
    if (add) {
      let editorsPerResource = this.f.get(resource);
      if (!editorsPerResource) {
        editorsPerResource = /* @__PURE__ */ new Map();
        this.f.set(resource, editorsPerResource);
      }
      editorsPerResource.set(identifier2, (editorsPerResource.get(identifier2) ?? 0) + 1);
    } else {
      const editorsPerResource = this.f.get(resource);
      if (editorsPerResource) {
        const counter = editorsPerResource.get(identifier2) ?? 0;
        if (counter > 1) {
          editorsPerResource.set(identifier2, counter - 1);
        } else {
          editorsPerResource.delete(identifier2);
          if (editorsPerResource.size === 0) {
            this.f.delete(resource);
          }
        }
      }
    }
  }
  C(group2, editor) {
    this.z(editor, false);
    const key2 = this.D(group2, editor);
    if (key2) {
      this.c.delete(key2);
      const map = this.b.get(group2.id);
      if (map && map.delete(key2.editor) && map.size === 0) {
        this.b.delete(group2.id);
      }
      this.g.fire();
    }
  }
  D(group2, editor) {
    const groupMap = this.b.get(group2.id);
    if (!groupMap) {
      return void 0;
    }
    return groupMap.get(editor);
  }
  F(group2, editor) {
    let groupMap = this.b.get(group2.id);
    if (!groupMap) {
      groupMap = /* @__PURE__ */ new Map();
      this.b.set(group2.id, groupMap);
    }
    let key2 = groupMap.get(editor);
    if (!key2) {
      key2 = { groupId: group2.id, editor };
      groupMap.set(editor, key2);
    }
    return key2;
  }
  async G(exclude, groupId) {
    if (!this.n.partOptions.limit?.enabled || typeof this.n.partOptions.limit.value !== "number" || this.n.partOptions.limit.value <= 0) {
      return;
    }
    const limit = this.n.partOptions.limit.value;
    if (this.n.partOptions.limit?.perEditorGroup) {
      if (typeof groupId === "number") {
        const group2 = this.j.getGroup(groupId);
        if (group2) {
          await this.H(limit, group2.getEditors(
            0
            /* EditorsOrder.MOST_RECENTLY_ACTIVE */
          ).map((editor) => ({ editor, groupId })), exclude);
        }
      } else {
        for (const group2 of this.j.groups) {
          await this.G(exclude, group2.id);
        }
      }
    } else {
      await this.H(limit, [...this.c.values()], exclude);
    }
  }
  async H(limit, mostRecentEditors, exclude) {
    let mostRecentEditorsCountingForLimit;
    if (this.n.partOptions.limit?.excludeDirty) {
      mostRecentEditorsCountingForLimit = mostRecentEditors.filter(({ editor }) => {
        if (editor.isDirty() && !editor.isSaving() || editor.hasCapability(
          512
          /* EditorInputCapabilities.Scratchpad */
        )) {
          return false;
        }
        return true;
      });
    } else {
      mostRecentEditorsCountingForLimit = mostRecentEditors;
    }
    if (limit >= mostRecentEditorsCountingForLimit.length) {
      return;
    }
    const leastRecentlyClosableEditors = mostRecentEditorsCountingForLimit.reverse().filter(({ editor, groupId }) => {
      if (editor.isDirty() && !editor.isSaving() || editor.hasCapability(
        512
        /* EditorInputCapabilities.Scratchpad */
      )) {
        return false;
      }
      if (exclude && editor === exclude.editor && groupId === exclude.groupId) {
        return false;
      }
      if (this.j.getGroup(groupId)?.isSticky(editor)) {
        return false;
      }
      return true;
    });
    let editorsToCloseCount = mostRecentEditorsCountingForLimit.length - limit;
    const mapGroupToEditorsToClose = /* @__PURE__ */ new Map();
    for (const { groupId, editor } of leastRecentlyClosableEditors) {
      let editorsInGroupToClose = mapGroupToEditorsToClose.get(groupId);
      if (!editorsInGroupToClose) {
        editorsInGroupToClose = [];
        mapGroupToEditorsToClose.set(groupId, editorsInGroupToClose);
      }
      editorsInGroupToClose.push(editor);
      editorsToCloseCount--;
      if (editorsToCloseCount === 0) {
        break;
      }
    }
    for (const [groupId, editors] of mapGroupToEditorsToClose) {
      const group2 = this.j.getGroup(groupId);
      if (group2) {
        await group2.closeEditors(editors, { preserveFocus: true });
      }
    }
  }
  I() {
    if (this.m) {
      return;
    }
    if (this.c.isEmpty()) {
      this.r.remove(
        $LVb_1.a,
        1
        /* StorageScope.WORKSPACE */
      );
    } else {
      this.r.store(
        $LVb_1.a,
        JSON.stringify(this.J()),
        1,
        1
        /* StorageTarget.MACHINE */
      );
    }
  }
  J() {
    const registry4 = $Wn.as($ZK.EditorFactory);
    const entries2 = [...this.c.values()];
    const mapGroupToSerializableEditorsOfGroup = /* @__PURE__ */ new Map();
    return {
      entries: $Mb(entries2.map(({ editor, groupId }) => {
        const group2 = this.j.getGroup(groupId);
        if (!group2) {
          return void 0;
        }
        let serializableEditorsOfGroup = mapGroupToSerializableEditorsOfGroup.get(group2);
        if (!serializableEditorsOfGroup) {
          serializableEditorsOfGroup = group2.getEditors(
            1
            /* EditorsOrder.SEQUENTIAL */
          ).filter((editor2) => {
            const editorSerializer = registry4.getEditorSerializer(editor2);
            return editorSerializer?.canSerialize(editor2);
          });
          mapGroupToSerializableEditorsOfGroup.set(group2, serializableEditorsOfGroup);
        }
        const index = serializableEditorsOfGroup.indexOf(editor);
        if (index === -1) {
          return void 0;
        }
        return { groupId, index };
      }))
    };
  }
  async L() {
    if (this.j === this.n.mainPart || this.j === this.n) {
      await this.n.whenReady;
    }
    let hasRestorableState = false;
    if (!this.m) {
      const serialized = this.r.get(
        $LVb_1.a,
        1
        /* StorageScope.WORKSPACE */
      );
      if (serialized) {
        hasRestorableState = true;
        this.M(JSON.parse(serialized));
      }
    }
    if (!hasRestorableState) {
      const groups = this.j.getGroups(
        1
        /* GroupsOrder.MOST_RECENTLY_ACTIVE */
      );
      for (let i2 = groups.length - 1; i2 >= 0; i2--) {
        const group2 = groups[i2];
        const groupEditorsMru = group2.getEditors(
          0
          /* EditorsOrder.MOST_RECENTLY_ACTIVE */
        );
        for (let i3 = groupEditorsMru.length - 1; i3 >= 0; i3--) {
          this.y(
            group2,
            groupEditorsMru[i3],
            true,
            true
            /* is new */
          );
        }
      }
    }
    for (const group2 of this.j.groups) {
      this.u(group2);
    }
  }
  M(serialized) {
    const mapValues = [];
    for (const { groupId, index } of serialized.entries) {
      const group2 = this.j.getGroup(groupId);
      if (!group2) {
        continue;
      }
      const editor = group2.getEditorByIndex(index);
      if (!editor) {
        continue;
      }
      const editorIdentifier = this.F(group2, editor);
      mapValues.push([editorIdentifier, editorIdentifier]);
      this.z(editor, true);
    }
    this.c.fromJSON(mapValues);
  }
};
$LVb = $LVb_1 = __decorate([
  __param(1, $iJ),
  __param(2, $jv)
], $LVb);

// out-build/vs/workbench/services/editor/browser/editorService.js
var $MVb_1;
var $MVb = $MVb_1 = class $MVb2 extends $3c {
  constructor(editorGroupsContainer, n, r2, s, t, u, w, y, z, C, D) {
    super();
    this.n = n;
    this.r = r2;
    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.a = this.B(new $ze());
    this.onDidActiveEditorChange = this.a.event;
    this.b = this.B(new $ze());
    this.onDidVisibleEditorsChange = this.b.event;
    this.c = this.B(new $ze());
    this.onDidEditorsChange = this.c.event;
    this.f = this.B(new $ze());
    this.onWillOpenEditor = this.f.event;
    this.g = this.B(new $ze());
    this.onDidCloseEditor = this.g.event;
    this.h = this.B(new $ze());
    this.onDidOpenEditorFail = this.h.event;
    this.j = this.B(new $ze());
    this.onDidMostRecentlyActiveEditorsChange = this.j.event;
    this.G = void 0;
    this.M = new $Ec();
    this.R = false;
    this.m = editorGroupsContainer ?? n;
    this.X = this.B(this.r.createInstance($LVb, this.m));
    this.S();
    this.F();
  }
  createScoped(editorGroupsContainer, disposables) {
    return disposables.add(new $MVb_1(editorGroupsContainer === "main" ? this.n.mainPart : editorGroupsContainer, this.n, this.r, this.s, this.t, this.u, this.w, this.y, this.z, this.C, this.D));
  }
  F() {
    if (this.m === this.n.mainPart || this.m === this.n) {
      this.n.whenReady.then(() => this.H());
    } else {
      this.H();
    }
    this.B(this.m.onDidChangeActiveGroup((group2) => this.I(group2)));
    this.B(this.m.onDidAddGroup((group2) => this.L(group2)));
    this.B(this.X.onDidMostRecentlyActiveEditorsChange(() => this.j.fire()));
    this.B(this.onDidVisibleEditorsChange(() => this.N()));
    this.B(this.s.onDidRunOperation((e) => this.O(e)));
    this.B(this.s.onDidFilesChange((e) => this.P(e)));
    this.B(this.t.onDidChangeConfiguration((e) => this.S(e)));
  }
  H() {
    for (const group2 of this.m.groups) {
      this.L(group2);
    }
    if (this.activeEditor) {
      this.J();
      this.b.fire();
    }
  }
  I(group2) {
    if (group2 !== this.m.activeGroup) {
      return;
    }
    if (!this.G && !group2.activeEditor) {
      return;
    }
    this.J();
  }
  J() {
    const activeGroup = this.m.activeGroup;
    this.G = activeGroup.activeEditor ?? void 0;
    this.a.fire();
  }
  L(group2) {
    const groupDisposables = new $2c();
    groupDisposables.add(group2.onDidModelChange((e) => {
      this.c.fire({ groupId: group2.id, event: e });
    }));
    groupDisposables.add(group2.onDidActiveEditorChange(() => {
      this.I(group2);
      this.b.fire();
    }));
    groupDisposables.add(group2.onWillOpenEditor((e) => {
      this.f.fire(e);
    }));
    groupDisposables.add(group2.onDidCloseEditor((e) => {
      this.g.fire(e);
    }));
    groupDisposables.add(group2.onDidOpenEditorFail((editor) => {
      this.h.fire({ editor, groupId: group2.id });
    }));
    Event2.once(group2.onWillDispose)(() => {
      $Xc(groupDisposables);
    });
  }
  N() {
    const visibleOutOfWorkspaceResources = new $Fc();
    for (const editor of this.visibleEditors) {
      const resources = $Rb($Mb([
        $mL.getCanonicalUri(editor, { supportSideBySide: SideBySideEditor.PRIMARY }),
        $mL.getCanonicalUri(editor, { supportSideBySide: SideBySideEditor.SECONDARY })
      ]), (resource) => resource.toString());
      for (const resource of resources) {
        if (this.s.hasProvider(resource) && !this.u.isInsideWorkspace(resource)) {
          visibleOutOfWorkspaceResources.add(resource);
        }
      }
    }
    for (const resource of this.M.keys()) {
      if (!visibleOutOfWorkspaceResources.has(resource)) {
        $Xc(this.M.get(resource));
        this.M.delete(resource);
      }
    }
    for (const resource of visibleOutOfWorkspaceResources.keys()) {
      if (!this.M.get(resource)) {
        const disposable = this.s.watch(resource);
        this.M.set(resource, disposable);
      }
    }
  }
  //#endregion
  //#region File Changes: Move & Deletes to move or close opend editors
  async O(e) {
    if (e.isOperation(
      2
      /* FileOperation.MOVE */
    )) {
      this.Q(e.resource, e.target.resource);
    }
    if (e.isOperation(
      1
      /* FileOperation.DELETE */
    ) || e.isOperation(
      2
      /* FileOperation.MOVE */
    )) {
      this.U(e.resource, false, e.target ? e.target.resource : void 0);
    }
  }
  P(e) {
    if (e.gotDeleted()) {
      this.U(e, true);
    }
  }
  async Q(source, target) {
    for (const group2 of this.m.groups) {
      const replacements = [];
      for (const editor of group2.editors) {
        const resource = editor.resource;
        if (!resource || !this.w.extUri.isEqualOrParent(resource, source)) {
          continue;
        }
        let targetResource;
        if (this.w.extUri.isEqual(source, resource)) {
          targetResource = target;
        } else {
          const index = $7g(resource.path, source.path, this.w.extUri.ignorePathCasing(resource));
          targetResource = $vh(target, resource.path.substr(index + source.path.length + 1));
        }
        const moveResult = await editor.rename(group2.id, targetResource);
        if (!moveResult) {
          return;
        }
        const optionOverrides = {
          preserveFocus: true,
          pinned: group2.isPinned(editor),
          sticky: group2.isSticky(editor),
          index: group2.getIndexOfEditor(editor),
          inactive: !group2.isActive(editor)
        };
        if ($dL(moveResult.editor)) {
          replacements.push({
            editor,
            replacement: moveResult.editor,
            options: {
              ...moveResult.options,
              ...optionOverrides
            }
          });
        } else {
          replacements.push({
            editor,
            replacement: {
              ...moveResult.editor,
              options: {
                ...moveResult.editor.options,
                ...optionOverrides
              }
            }
          });
        }
      }
      if (replacements.length) {
        this.replaceEditors(replacements, group2);
      }
    }
  }
  S(e) {
    if (e && !e.affectsConfiguration("workbench.editor.closeOnFileDelete")) {
      return;
    }
    const configuration2 = this.t.getValue();
    if (typeof configuration2.workbench?.editor?.closeOnFileDelete === "boolean") {
      this.R = configuration2.workbench.editor.closeOnFileDelete;
    } else {
      this.R = false;
    }
  }
  U(arg1, isExternal, movedTo) {
    for (const editor of this.W({ includeUntitled: false, supportSideBySide: true })) {
      (async () => {
        const resource = editor.resource;
        if (!resource) {
          return;
        }
        if (this.R || !isExternal) {
          if (movedTo && this.w.extUri.isEqualOrParent(resource, movedTo)) {
            return;
          }
          let matches = false;
          if (arg1 instanceof $Dm) {
            matches = arg1.contains(
              resource,
              2
              /* FileChangeType.DELETED */
            );
          } else {
            matches = this.w.extUri.isEqualOrParent(resource, arg1);
          }
          if (!matches) {
            return;
          }
          let exists = false;
          if (isExternal && this.s.hasProvider(resource)) {
            await $Wh(100);
            exists = await this.s.exists(resource);
          }
          if (!exists && !editor.isDisposed()) {
            editor.dispose();
          }
        }
      })();
    }
  }
  W(options3) {
    const editors = [];
    function conditionallyAddEditor(editor) {
      if (editor.hasCapability(
        4
        /* EditorInputCapabilities.Untitled */
      ) && !options3.includeUntitled) {
        return;
      }
      if (editor.isDirty()) {
        return;
      }
      editors.push(editor);
    }
    for (const editor of this.editors) {
      if (options3.supportSideBySide && editor instanceof $1I) {
        conditionallyAddEditor(editor.primary);
        conditionallyAddEditor(editor.secondary);
      } else {
        conditionallyAddEditor(editor);
      }
    }
    return editors;
  }
  get activeEditorPane() {
    return this.m.activeGroup?.activeEditorPane;
  }
  get activeTextEditorControl() {
    const activeEditorPane = this.activeEditorPane;
    if (activeEditorPane) {
      const activeControl = activeEditorPane.getControl();
      if ($P5(activeControl) || $Q5(activeControl)) {
        return activeControl;
      }
      if ($R5(activeControl) && $P5(activeControl.activeCodeEditor)) {
        return activeControl.activeCodeEditor;
      }
    }
    return void 0;
  }
  get activeTextEditorLanguageId() {
    let activeCodeEditor = void 0;
    const activeTextEditorControl = this.activeTextEditorControl;
    if ($Q5(activeTextEditorControl)) {
      activeCodeEditor = activeTextEditorControl.getModifiedEditor();
    } else {
      activeCodeEditor = activeTextEditorControl;
    }
    return activeCodeEditor?.getModel()?.getLanguageId();
  }
  get count() {
    return this.X.count;
  }
  get editors() {
    return this.getEditors(
      1
      /* EditorsOrder.SEQUENTIAL */
    ).map(({ editor }) => editor);
  }
  getEditors(order, options3) {
    switch (order) {
      case 0:
        if (options3?.excludeSticky) {
          return this.X.editors.filter(({ groupId, editor }) => !this.m.getGroup(groupId)?.isSticky(editor));
        }
        return this.X.editors;
      case 1: {
        const editors = [];
        for (const group2 of this.m.getGroups(
          2
          /* GroupsOrder.GRID_APPEARANCE */
        )) {
          editors.push(...group2.getEditors(1, options3).map((editor) => ({ editor, groupId: group2.id })));
        }
        return editors;
      }
    }
  }
  get activeEditor() {
    const activeGroup = this.m.activeGroup;
    return activeGroup ? activeGroup.activeEditor ?? void 0 : void 0;
  }
  get visibleEditorPanes() {
    return $Mb(this.m.groups.map((group2) => group2.activeEditorPane));
  }
  get visibleTextEditorControls() {
    return this.Y(this.visibleEditorPanes);
  }
  Y(editorPanes) {
    const visibleTextEditorControls = [];
    for (const editorPane of editorPanes) {
      const controls = [];
      if (editorPane instanceof $_tb) {
        controls.push(editorPane.getPrimaryEditorPane()?.getControl());
        controls.push(editorPane.getSecondaryEditorPane()?.getControl());
      } else {
        controls.push(editorPane.getControl());
      }
      for (const control of controls) {
        if ($P5(control) || $Q5(control)) {
          visibleTextEditorControls.push(control);
        }
      }
    }
    return visibleTextEditorControls;
  }
  getVisibleTextEditorControls(order) {
    return this.Y($Mb(this.m.getGroups(
      order === 1 ? 2 : 1
      /* GroupsOrder.MOST_RECENTLY_ACTIVE */
    ).map((group2) => group2.activeEditorPane)));
  }
  get visibleEditors() {
    return $Mb(this.m.groups.map((group2) => group2.activeEditor));
  }
  async openEditor(editor, optionsOrPreferredGroup, preferredGroup) {
    let typedEditor = void 0;
    let options3 = $dL(editor) ? optionsOrPreferredGroup : editor.options;
    let group2 = void 0;
    if ($qJ(optionsOrPreferredGroup)) {
      preferredGroup = optionsOrPreferredGroup;
    }
    if (!$dL(editor)) {
      const resolvedEditor = await this.y.resolveEditor(editor, preferredGroup);
      if (resolvedEditor === 1) {
        return;
      }
      if ($iL(resolvedEditor)) {
        typedEditor = resolvedEditor.editor;
        options3 = resolvedEditor.options;
        group2 = resolvedEditor.group;
      }
    }
    if (!typedEditor) {
      typedEditor = $dL(editor) ? editor : await this.D.resolveTextEditor(editor);
    }
    if (!group2) {
      let activation = void 0;
      const findGroupResult = this.r.invokeFunction($5Ub, { editor: typedEditor, options: options3 }, preferredGroup);
      if (findGroupResult instanceof Promise) {
        [group2, activation] = await findGroupResult;
      } else {
        [group2, activation] = findGroupResult;
      }
      if (activation) {
        options3 = { ...options3, activation };
      }
    }
    return group2.openEditor(typedEditor, options3);
  }
  async openEditors(editors, preferredGroup, options3) {
    if (options3?.validateTrust) {
      const editorsTrusted = await this.Z(editors);
      if (!editorsTrusted) {
        return [];
      }
    }
    const mapGroupToTypedEditors = /* @__PURE__ */ new Map();
    for (const editor of editors) {
      let typedEditor = void 0;
      let group2 = void 0;
      if (!$hL(editor)) {
        const resolvedEditor = await this.y.resolveEditor(editor, preferredGroup);
        if (resolvedEditor === 1) {
          continue;
        }
        if ($iL(resolvedEditor)) {
          typedEditor = resolvedEditor;
          group2 = resolvedEditor.group;
        }
      }
      if (!typedEditor) {
        typedEditor = $hL(editor) ? editor : { editor: await this.D.resolveTextEditor(editor), options: editor.options };
      }
      if (!group2) {
        const findGroupResult = this.r.invokeFunction($5Ub, typedEditor, preferredGroup);
        if (findGroupResult instanceof Promise) {
          [group2] = await findGroupResult;
        } else {
          [group2] = findGroupResult;
        }
      }
      let targetGroupEditors = mapGroupToTypedEditors.get(group2);
      if (!targetGroupEditors) {
        targetGroupEditors = [];
        mapGroupToTypedEditors.set(group2, targetGroupEditors);
      }
      targetGroupEditors.push(typedEditor);
    }
    const result = [];
    for (const [group2, editors2] of mapGroupToTypedEditors) {
      result.push(group2.openEditors(editors2));
    }
    return $Mb(await Promises.settled(result));
  }
  async Z(editors) {
    const { resources, diffMode, mergeMode } = this.$(editors);
    const trustResult = await this.z.requestOpenFilesTrust(resources);
    switch (trustResult) {
      case 1:
        return true;
      case 2:
        await this.C.openWindow(resources.map((resource) => ({ fileUri: resource })), { forceNewWindow: true, diffMode, mergeMode });
        return false;
      case 3:
        return false;
    }
  }
  $(editors) {
    const resources = new $Fc();
    let diffMode = false;
    let mergeMode = false;
    for (const editor of editors) {
      if ($hL(editor)) {
        const resource = $mL.getOriginalUri(editor.editor, { supportSideBySide: SideBySideEditor.BOTH });
        if (URI.isUri(resource)) {
          resources.add(resource);
        } else if (resource) {
          if (resource.primary) {
            resources.add(resource.primary);
          }
          if (resource.secondary) {
            resources.add(resource.secondary);
          }
          diffMode = editor.editor instanceof $fub;
        }
      } else {
        if ($aL(editor)) {
          if (URI.isUri(editor.input1)) {
            resources.add(editor.input1.resource);
          }
          if (URI.isUri(editor.input2)) {
            resources.add(editor.input2.resource);
          }
          if (URI.isUri(editor.base)) {
            resources.add(editor.base.resource);
          }
          if (URI.isUri(editor.result)) {
            resources.add(editor.result.resource);
          }
          mergeMode = true;
        }
        if ($9K(editor)) {
          if (URI.isUri(editor.original.resource)) {
            resources.add(editor.original.resource);
          }
          if (URI.isUri(editor.modified.resource)) {
            resources.add(editor.modified.resource);
          }
          diffMode = true;
        } else if ($8K(editor)) {
          resources.add(editor.resource);
        }
      }
    }
    return {
      resources: Array.from(resources.keys()),
      diffMode,
      mergeMode
    };
  }
  //#endregion
  //#region isOpened() / isVisible()
  isOpened(editor) {
    return this.X.hasEditor({
      resource: this.w.asCanonicalUri(editor.resource),
      typeId: editor.typeId,
      editorId: editor.editorId
    });
  }
  isVisible(editor) {
    for (const group2 of this.m.groups) {
      if (group2.activeEditor?.matches(editor)) {
        return true;
      }
    }
    return false;
  }
  //#endregion
  //#region closeEditor()
  async closeEditor({ editor, groupId }, options3) {
    const group2 = this.m.getGroup(groupId);
    await group2?.closeEditor(editor, options3);
  }
  //#endregion
  //#region closeEditors()
  async closeEditors(editors, options3) {
    const mapGroupToEditors = /* @__PURE__ */ new Map();
    for (const { editor, groupId } of editors) {
      const group2 = this.m.getGroup(groupId);
      if (!group2) {
        continue;
      }
      let editors2 = mapGroupToEditors.get(group2);
      if (!editors2) {
        editors2 = [];
        mapGroupToEditors.set(group2, editors2);
      }
      editors2.push(editor);
    }
    for (const [group2, editors2] of mapGroupToEditors) {
      await group2.closeEditors(editors2, options3);
    }
  }
  findEditors(arg1, options3, arg2) {
    const resource = URI.isUri(arg1) ? arg1 : arg1.resource;
    const typeId2 = URI.isUri(arg1) ? void 0 : arg1.typeId;
    if (options3?.supportSideBySide !== SideBySideEditor.ANY && options3?.supportSideBySide !== SideBySideEditor.SECONDARY) {
      if (!this.X.hasEditors(resource)) {
        if (URI.isUri(arg1) || $Gg(arg2)) {
          return [];
        }
        return void 0;
      }
    }
    if (!$Gg(arg2)) {
      const targetGroup = typeof arg2 === "number" ? this.m.getGroup(arg2) : arg2;
      if (URI.isUri(arg1)) {
        if (!targetGroup) {
          return [];
        }
        return targetGroup.findEditors(resource, options3);
      } else {
        if (!targetGroup) {
          return void 0;
        }
        const editors = targetGroup.findEditors(resource, options3);
        for (const editor of editors) {
          if (editor.typeId === typeId2) {
            return editor;
          }
        }
        return void 0;
      }
    } else {
      const result = [];
      for (const group2 of this.m.getGroups(
        1
        /* GroupsOrder.MOST_RECENTLY_ACTIVE */
      )) {
        const editors = [];
        if (URI.isUri(arg1)) {
          editors.push(...this.findEditors(arg1, options3, group2));
        } else {
          const editor = this.findEditors(arg1, options3, group2);
          if (editor) {
            editors.push(editor);
          }
        }
        result.push(...editors.map((editor) => ({ editor, groupId: group2.id })));
      }
      return result;
    }
  }
  async replaceEditors(replacements, group2) {
    const targetGroup = typeof group2 === "number" ? this.m.getGroup(group2) : group2;
    const typedReplacements = [];
    for (const replacement of replacements) {
      let typedReplacement = void 0;
      if (!$dL(replacement.replacement)) {
        const resolvedEditor = await this.y.resolveEditor(replacement.replacement, targetGroup);
        if (resolvedEditor === 1) {
          continue;
        }
        if ($iL(resolvedEditor)) {
          typedReplacement = {
            editor: replacement.editor,
            replacement: resolvedEditor.editor,
            options: resolvedEditor.options,
            forceReplaceDirty: replacement.forceReplaceDirty
          };
        }
      }
      if (!typedReplacement) {
        typedReplacement = {
          editor: replacement.editor,
          replacement: $jJ(replacement) ? replacement.replacement : await this.D.resolveTextEditor(replacement.replacement),
          options: $jJ(replacement) ? replacement.options : replacement.replacement.options,
          forceReplaceDirty: replacement.forceReplaceDirty
        };
      }
      typedReplacements.push(typedReplacement);
    }
    return targetGroup?.replaceEditors(typedReplacements);
  }
  //#endregion
  //#region save/revert
  async save(editors, options3) {
    if (!Array.isArray(editors)) {
      editors = [editors];
    }
    const uniqueEditors = this.bb(editors);
    const editorsToSaveParallel = [];
    const editorsToSaveSequentially = [];
    if (options3?.saveAs) {
      editorsToSaveSequentially.push(...uniqueEditors);
    } else {
      for (const { groupId, editor } of uniqueEditors) {
        if (editor.hasCapability(
          4
          /* EditorInputCapabilities.Untitled */
        )) {
          editorsToSaveSequentially.push({ groupId, editor });
        } else {
          editorsToSaveParallel.push({ groupId, editor });
        }
      }
    }
    const saveResults = await Promises.settled(editorsToSaveParallel.map(({ groupId, editor }) => {
      if (options3?.reason === 1) {
        this.m.getGroup(groupId)?.pinEditor(editor);
      }
      return editor.save(groupId, options3);
    }));
    for (const { groupId, editor } of editorsToSaveSequentially) {
      if (editor.isDisposed()) {
        continue;
      }
      const editorPane = await this.openEditor(editor, groupId);
      const editorOptions2 = {
        pinned: true,
        viewState: editorPane?.getViewState()
      };
      const result = options3?.saveAs ? await editor.saveAs(groupId, options3) : await editor.save(groupId, options3);
      saveResults.push(result);
      if (!result) {
        break;
      }
      if (!editor.matches(result)) {
        const targetGroups = editor.hasCapability(
          4
          /* EditorInputCapabilities.Untitled */
        ) ? this.m.groups.map((group2) => group2.id) : [groupId];
        for (const targetGroup of targetGroups) {
          if (result instanceof $nG) {
            await this.replaceEditors([{ editor, replacement: result, options: editorOptions2 }], targetGroup);
          } else {
            await this.replaceEditors([{ editor, replacement: { ...result, options: editorOptions2 } }], targetGroup);
          }
        }
      }
    }
    return {
      success: saveResults.every((result) => !!result),
      editors: $Mb(saveResults)
    };
  }
  saveAll(options3) {
    return this.save(this.ab(options3), options3);
  }
  async revert(editors, options3) {
    if (!Array.isArray(editors)) {
      editors = [editors];
    }
    const uniqueEditors = this.bb(editors);
    await Promises.settled(uniqueEditors.map(async ({ groupId, editor }) => {
      this.m.getGroup(groupId)?.pinEditor(editor);
      return editor.revert(groupId, options3);
    }));
    return !uniqueEditors.some(({ editor }) => editor.isDirty());
  }
  async revertAll(options3) {
    return this.revert(this.ab(options3), options3);
  }
  ab(options3) {
    const editors = [];
    for (const group2 of this.m.getGroups(
      1
      /* GroupsOrder.MOST_RECENTLY_ACTIVE */
    )) {
      for (const editor of group2.getEditors(
        0
        /* EditorsOrder.MOST_RECENTLY_ACTIVE */
      )) {
        if (!editor.isModified()) {
          continue;
        }
        if ((typeof options3?.includeUntitled === "boolean" || !options3?.includeUntitled?.includeScratchpad) && editor.hasCapability(
          512
          /* EditorInputCapabilities.Scratchpad */
        )) {
          continue;
        }
        if (!options3?.includeUntitled && editor.hasCapability(
          4
          /* EditorInputCapabilities.Untitled */
        )) {
          continue;
        }
        if (options3?.excludeSticky && group2.isSticky(editor)) {
          continue;
        }
        editors.push({ groupId: group2.id, editor });
      }
    }
    return editors;
  }
  bb(editors) {
    const uniqueEditors = [];
    for (const { editor, groupId } of editors) {
      if (uniqueEditors.some((uniqueEditor) => uniqueEditor.editor.matches(editor))) {
        continue;
      }
      uniqueEditors.push({ editor, groupId });
    }
    return uniqueEditors;
  }
  //#endregion
  dispose() {
    super.dispose();
    this.M.forEach((disposable) => $Xc(disposable));
    this.M.clear();
  }
};
$MVb = $MVb_1 = __decorate([
  __param(1, $iJ),
  __param(2, $Pk),
  __param(3, $km),
  __param(4, $kl),
  __param(5, $Zk),
  __param(6, $vl),
  __param(7, $4L),
  __param(8, $5M),
  __param(9, $S4),
  __param(10, $YUb)
], $MVb);
$SC($mJ, new $Nk($MVb, [void 0], false));

// out-build/vs/workbench/services/editor/browser/editorResolverService.js
var $NVb_1;
var $NVb = class $NVb2 extends $3c {
  static {
    $NVb_1 = this;
  }
  static {
    this.g = "promptOpenWith.configureDefault";
  }
  static {
    this.h = "editorOverrideService.cache";
  }
  static {
    this.j = "editorOverrideService.conflictingDefaults";
  }
  constructor(t, u, w, y, z, C, D, F, G) {
    super();
    this.t = t;
    this.u = u;
    this.w = w;
    this.y = y;
    this.z = z;
    this.C = C;
    this.D = D;
    this.F = F;
    this.G = G;
    this.f = this.B(new $Ce());
    this.onDidChangeEditorRegistrations = this.f.event;
    this.m = /* @__PURE__ */ new Map();
    this.n = /* @__PURE__ */ new Map();
    this.r = true;
    this.s = new Set(JSON.parse(this.D.get($NVb_1.h, 0, JSON.stringify([]))));
    this.D.remove(
      $NVb_1.h,
      0
      /* StorageScope.PROFILE */
    );
    this.B(this.D.onWillSaveState(() => {
      this.X();
    }));
    this.B(this.F.onDidRegisterExtensions(() => {
      this.s = void 0;
    }));
  }
  H(editor, preferredGroup) {
    const untypedEditor = editor;
    const findGroupResult = this.u.invokeFunction($5Ub, untypedEditor, preferredGroup);
    if (findGroupResult instanceof Promise) {
      return findGroupResult.then(([group2, activation]) => [untypedEditor, group2, activation]);
    } else {
      const [group2, activation] = findGroupResult;
      return [untypedEditor, group2, activation];
    }
  }
  async resolveEditor(editor, preferredGroup) {
    this.n = this.J();
    if ($$K(editor)) {
      return this.I(editor, preferredGroup);
    }
    let resolvedUntypedAndGroup;
    const resolvedUntypedAndGroupResult = this.H(editor, preferredGroup);
    if (resolvedUntypedAndGroupResult instanceof Promise) {
      resolvedUntypedAndGroup = await resolvedUntypedAndGroupResult;
    } else {
      resolvedUntypedAndGroup = resolvedUntypedAndGroupResult;
    }
    if (!resolvedUntypedAndGroup) {
      return 2;
    }
    const [untypedEditor, group2, activation] = resolvedUntypedAndGroup;
    if (activation) {
      untypedEditor.options = { ...untypedEditor.options, activation };
    }
    let resource = $mL.getCanonicalUri(untypedEditor, { supportSideBySide: SideBySideEditor.PRIMARY });
    if (this.s && resource && this.Y(resource)) {
      await this.F.whenInstalledExtensionsRegistered();
    }
    if (resource === void 0) {
      resource = URI.from({ scheme: Schemas.untitled });
    } else if (resource.scheme === void 0 || resource === null) {
      return 2;
    }
    if (untypedEditor.options?.override === EditorResolution.PICK) {
      const picked = await this.U(untypedEditor);
      if (!picked) {
        return 1;
      }
      untypedEditor.options = picked;
    }
    let { editor: selectedEditor, conflictingDefault } = this.N(resource, untypedEditor.options?.override);
    if (!selectedEditor && (untypedEditor.options?.override || $hL(editor))) {
      return 2;
    } else if (!selectedEditor) {
      const resolvedEditor = this.N(resource, $1K.id);
      selectedEditor = resolvedEditor?.editor;
      conflictingDefault = resolvedEditor?.conflictingDefault;
      if (!selectedEditor) {
        return 2;
      }
    }
    if ($9K(untypedEditor) && untypedEditor.options?.override === void 0) {
      let resource2 = $mL.getCanonicalUri(untypedEditor, { supportSideBySide: SideBySideEditor.SECONDARY });
      if (!resource2) {
        resource2 = URI.from({ scheme: Schemas.untitled });
      }
      const { editor: selectedEditor2 } = this.N(resource2, void 0);
      if (!selectedEditor2 || selectedEditor.editorInfo.id !== selectedEditor2.editorInfo.id) {
        const { editor: selectedDiff, conflictingDefault: conflictingDefaultDiff } = this.N(resource, $1K.id);
        selectedEditor = selectedDiff;
        conflictingDefault = conflictingDefaultDiff;
      }
      if (!selectedEditor) {
        return 2;
      }
    }
    untypedEditor.options = { override: selectedEditor.editorInfo.id, ...untypedEditor.options };
    if (selectedEditor.editorFactoryObject.createDiffEditorInput === void 0 && $9K(untypedEditor)) {
      return 2;
    }
    const input = await this.O(untypedEditor, group2, selectedEditor);
    if (conflictingDefault && input) {
      await this.R(resource, selectedEditor.editorInfo.label, untypedEditor, input.editor, group2);
    }
    if (input) {
      this.W(input.editor);
      if (input.editor.editorId !== selectedEditor.editorInfo.id) {
        this.G.warn(`Editor ID Mismatch: ${input.editor.editorId} !== ${selectedEditor.editorInfo.id}. This will cause bugs. Please ensure editorInput.editorId matches the registered id`);
      }
      return { ...input, group: group2 };
    }
    return 1;
  }
  async I(editor, preferredGroup) {
    const primaryResolvedEditor = await this.resolveEditor(editor.primary, preferredGroup);
    if (!$iL(primaryResolvedEditor)) {
      return 2;
    }
    const secondaryResolvedEditor = await this.resolveEditor(editor.secondary, primaryResolvedEditor.group ?? preferredGroup);
    if (!$iL(secondaryResolvedEditor)) {
      return 2;
    }
    return {
      group: primaryResolvedEditor.group ?? secondaryResolvedEditor.group,
      editor: this.u.createInstance($1I, editor.label, editor.description, secondaryResolvedEditor.editor, primaryResolvedEditor.editor),
      options: editor.options
    };
  }
  bufferChangeEvents(callback) {
    this.f.pause();
    try {
      callback();
    } finally {
      this.f.resume();
    }
  }
  registerEditor(globPattern, editorInfo, options3, editorFactoryObject) {
    let registeredEditor = this.m.get(globPattern);
    if (registeredEditor === void 0) {
      registeredEditor = /* @__PURE__ */ new Map();
      this.m.set(globPattern, registeredEditor);
    }
    let editorsWithId = registeredEditor.get(editorInfo.id);
    if (editorsWithId === void 0) {
      editorsWithId = [];
    }
    const remove = $Wb(editorsWithId, {
      globPattern,
      editorInfo,
      options: options3,
      editorFactoryObject
    });
    registeredEditor.set(editorInfo.id, editorsWithId);
    this.r = true;
    this.f.fire();
    return $1c(() => {
      remove();
      if (editorsWithId && editorsWithId.length === 0) {
        registeredEditor?.delete(editorInfo.id);
      }
      this.r = true;
      this.f.fire();
    });
  }
  getAssociationsForResource(resource) {
    const associations = this.getAllUserAssociations();
    let matchingAssociations = associations.filter((association) => association.filenamePattern && $7L(association.filenamePattern, resource));
    matchingAssociations = matchingAssociations.sort((a, b) => (b.filenamePattern?.length ?? 0) - (a.filenamePattern?.length ?? 0));
    const allEditors = this.L;
    return matchingAssociations.filter((association) => allEditors.find((c) => c.editorInfo.id === association.viewType));
  }
  getAllUserAssociations() {
    const inspectedEditorAssociations = this.w.inspect($5L) || {};
    const defaultAssociations = inspectedEditorAssociations.defaultValue ?? {};
    const workspaceAssociations = inspectedEditorAssociations.workspaceValue ?? {};
    const userAssociations = inspectedEditorAssociations.userValue ?? {};
    const rawAssociations = { ...workspaceAssociations };
    for (const [key2, value] of Object.entries({ ...defaultAssociations, ...userAssociations })) {
      if (rawAssociations[key2] === void 0) {
        rawAssociations[key2] = value;
      }
    }
    const associations = [];
    for (const [key2, value] of Object.entries(rawAssociations)) {
      const association = {
        filenamePattern: key2,
        viewType: value
      };
      associations.push(association);
    }
    return associations;
  }
  /**
   * Given the nested nature of the editors map, we merge factories of the same glob and id to make it flat
   * and easier to work with
   */
  J() {
    if (!this.r) {
      return this.n;
    }
    this.r = false;
    const editors = /* @__PURE__ */ new Map();
    for (const [glob, value] of this.m) {
      const registeredEditors = [];
      for (const editors2 of value.values()) {
        let registeredEditor = void 0;
        for (const editor of editors2) {
          if (!registeredEditor) {
            registeredEditor = {
              editorInfo: editor.editorInfo,
              globPattern: editor.globPattern,
              options: {},
              editorFactoryObject: {}
            };
          }
          registeredEditor.options = { ...registeredEditor.options, ...editor.options };
          registeredEditor.editorFactoryObject = { ...registeredEditor.editorFactoryObject, ...editor.editorFactoryObject };
        }
        if (registeredEditor) {
          registeredEditors.push(registeredEditor);
        }
      }
      editors.set(glob, registeredEditors);
    }
    return editors;
  }
  /**
   * Returns all editors as an array. Possible to contain duplicates
   */
  get L() {
    return Array.from(this.n.values()).flat();
  }
  updateUserAssociations(globPattern, editorID) {
    const newAssociation = { viewType: editorID, filenamePattern: globPattern };
    const currentAssociations = this.getAllUserAssociations();
    const newSettingObject = /* @__PURE__ */ Object.create(null);
    for (const association of [...currentAssociations, newAssociation]) {
      if (association.filenamePattern) {
        newSettingObject[association.filenamePattern] = association.viewType;
      }
    }
    this.w.updateValue($5L, newSettingObject);
  }
  M(resource) {
    const userSettings = this.getAssociationsForResource(resource);
    const matchingEditors = [];
    for (const [key2, editors] of this.n) {
      for (const editor of editors) {
        const foundInSettings = userSettings.find((setting) => setting.viewType === editor.editorInfo.id);
        if (foundInSettings && editor.editorInfo.priority !== RegisteredEditorPriority.exclusive || $7L(key2, resource)) {
          matchingEditors.push(editor);
        }
      }
    }
    return matchingEditors.sort((a, b) => {
      if ($6L(b.editorInfo.priority) === $6L(a.editorInfo.priority) && typeof b.globPattern === "string" && typeof a.globPattern === "string") {
        return b.globPattern.length - a.globPattern.length;
      }
      return $6L(b.editorInfo.priority) - $6L(a.editorInfo.priority);
    });
  }
  getEditors(resource) {
    this.n = this.J();
    if (URI.isUri(resource)) {
      const editors = this.M(resource);
      if (editors.find((e) => e.editorInfo.priority === RegisteredEditorPriority.exclusive)) {
        return [];
      }
      return editors.map((editor) => editor.editorInfo);
    }
    return $Rb(this.L.map((editor) => editor.editorInfo), (editor) => editor.id);
  }
  /**
   * Given a resource and an editorId selects the best possible editor
   * @returns The editor and whether there was another default which conflicted with it
   */
  N(resource, editorId) {
    const findMatchingEditor = (editors2, viewType) => {
      return editors2.find((editor) => {
        if (editor.options && editor.options.canSupportResource !== void 0) {
          return editor.editorInfo.id === viewType && editor.options.canSupportResource(resource);
        }
        return editor.editorInfo.id === viewType;
      });
    };
    if (editorId && editorId !== EditorResolution.EXCLUSIVE_ONLY) {
      const registeredEditors = this.L;
      return {
        editor: findMatchingEditor(registeredEditors, editorId),
        conflictingDefault: false
      };
    }
    const editors = this.M(resource);
    const associationsFromSetting = this.getAssociationsForResource(resource);
    const minPriority = editorId === EditorResolution.EXCLUSIVE_ONLY ? RegisteredEditorPriority.exclusive : RegisteredEditorPriority.builtin;
    let possibleEditors = editors.filter((editor) => $6L(editor.editorInfo.priority) >= $6L(minPriority) && editor.editorInfo.id !== $1K.id);
    if (possibleEditors.length === 0) {
      return {
        editor: associationsFromSetting[0] && minPriority !== RegisteredEditorPriority.exclusive ? findMatchingEditor(editors, associationsFromSetting[0].viewType) : void 0,
        conflictingDefault: false
      };
    }
    const selectedViewType = possibleEditors[0].editorInfo.priority === RegisteredEditorPriority.exclusive ? possibleEditors[0].editorInfo.id : associationsFromSetting[0]?.viewType || possibleEditors[0].editorInfo.id;
    let conflictingDefault = false;
    possibleEditors = possibleEditors.filter((editor) => editor.editorInfo.priority !== RegisteredEditorPriority.exclusive);
    if (associationsFromSetting.length === 0 && possibleEditors.length > 1) {
      conflictingDefault = true;
    }
    return {
      editor: findMatchingEditor(editors, selectedViewType),
      conflictingDefault
    };
  }
  async O(editor, group2, selectedEditor) {
    let options3 = editor.options;
    const resource = $mL.getCanonicalUri(editor, { supportSideBySide: SideBySideEditor.PRIMARY });
    if (options3 && typeof options3.activation === "undefined") {
      options3 = { ...options3, activation: options3.preserveFocus ? EditorActivation.RESTORE : void 0 };
    }
    if ($aL(editor)) {
      if (!selectedEditor.editorFactoryObject.createMergeEditorInput) {
        return;
      }
      const inputWithOptions2 = await selectedEditor.editorFactoryObject.createMergeEditorInput(editor, group2);
      return { editor: inputWithOptions2.editor, options: inputWithOptions2.options ?? options3 };
    }
    if ($9K(editor)) {
      if (!selectedEditor.editorFactoryObject.createDiffEditorInput) {
        return;
      }
      const inputWithOptions2 = await selectedEditor.editorFactoryObject.createDiffEditorInput(editor, group2);
      return { editor: inputWithOptions2.editor, options: inputWithOptions2.options ?? options3 };
    }
    if ($0K(editor)) {
      if (!selectedEditor.editorFactoryObject.createMultiDiffEditorInput) {
        return;
      }
      const inputWithOptions2 = await selectedEditor.editorFactoryObject.createMultiDiffEditorInput(editor, group2);
      return { editor: inputWithOptions2.editor, options: inputWithOptions2.options ?? options3 };
    }
    if ($$K(editor)) {
      throw new Error(`Untyped side by side editor input not supported here.`);
    }
    if ($_K(editor)) {
      if (!selectedEditor.editorFactoryObject.createUntitledEditorInput) {
        return;
      }
      const inputWithOptions2 = await selectedEditor.editorFactoryObject.createUntitledEditorInput(editor, group2);
      return { editor: inputWithOptions2.editor, options: inputWithOptions2.options ?? options3 };
    }
    if (resource === void 0) {
      throw new Error(`Undefined resource on non untitled editor input.`);
    }
    const singleEditorPerResource = typeof selectedEditor.options?.singlePerResource === "function" ? selectedEditor.options.singlePerResource() : selectedEditor.options?.singlePerResource;
    if (singleEditorPerResource) {
      const existingEditors = this.Q(resource, selectedEditor.editorInfo.id);
      if (existingEditors.length) {
        const editor2 = await this.P(existingEditors, group2);
        if (editor2) {
          return { editor: editor2, options: options3 };
        } else {
          return;
        }
      }
    }
    if (!selectedEditor.editorFactoryObject.createEditorInput) {
      return;
    }
    const inputWithOptions = await selectedEditor.editorFactoryObject.createEditorInput(editor, group2);
    options3 = inputWithOptions.options ?? options3;
    const input = inputWithOptions.editor;
    return { editor: input, options: options3 };
  }
  /**
   * Moves the first existing editor for a resource to the target group unless already opened there.
   * Additionally will close any other editors that are open for that resource and viewtype besides the first one found
   * @param resource The resource of the editor
   * @param viewType the viewtype of the editor
   * @param targetGroup The group to move it to
   * @returns The moved editor input or `undefined` if the editor could not be moved
   */
  async P(existingEditorsForResource, targetGroup) {
    const editorToUse = existingEditorsForResource[0];
    for (const { editor, group: group2 } of existingEditorsForResource) {
      if (editor !== editorToUse.editor) {
        const closed = await group2.closeEditor(editor);
        if (!closed) {
          return;
        }
      }
    }
    if (targetGroup.id !== editorToUse.group.id) {
      const moved = editorToUse.group.moveEditor(editorToUse.editor, targetGroup);
      if (!moved) {
        return;
      }
    }
    return editorToUse.editor;
  }
  /**
   * Given a resource and an editorId, returns all editors open for that resource and editorId.
   * @param resource The resource specified
   * @param editorId The editorID
   * @returns A list of editors
   */
  Q(resource, editorId) {
    const out = [];
    const orderedGroups = $Rb([
      ...this.t.groups
    ]);
    for (const group2 of orderedGroups) {
      for (const editor of group2.editors) {
        if ($oh(editor.resource, resource) && editor.editorId === editorId) {
          out.push({ editor, group: group2 });
        }
      }
    }
    return out;
  }
  async R(resource, editorName, untypedInput, currentEditor, group2) {
    const editors = this.M(resource);
    const storedChoices = JSON.parse(this.D.get($NVb_1.j, 0, "{}"));
    const globForResource = `*${$th(resource)}`;
    const writeCurrentEditorsToStorage = () => {
      storedChoices[globForResource] = [];
      editors.forEach((editor) => storedChoices[globForResource].push(editor.editorInfo.id));
      this.D.store(
        $NVb_1.j,
        JSON.stringify(storedChoices),
        0,
        1
        /* StorageTarget.MACHINE */
      );
    };
    if (storedChoices[globForResource] && storedChoices[globForResource].find((editorID) => editorID === currentEditor.editorId)) {
      return;
    }
    const handle2 = this.z.prompt(Severity2.Warning, localize(12693, null), [
      {
        label: localize(12694, null),
        run: async () => {
          const picked = await this.U(untypedInput, true);
          if (!picked) {
            return;
          }
          untypedInput.options = picked;
          const replacementEditor = await this.resolveEditor(untypedInput, group2);
          if (replacementEditor === 1 || replacementEditor === 2) {
            return;
          }
          group2.replaceEditors([
            {
              editor: currentEditor,
              replacement: replacementEditor.editor,
              options: replacementEditor.options ?? picked
            }
          ]);
        }
      },
      {
        label: localize(12695, null, editorName),
        run: writeCurrentEditorsToStorage
      }
    ]);
    const onCloseListener = handle2.onDidClose(() => {
      writeCurrentEditorsToStorage();
      onCloseListener.dispose();
    });
  }
  S(resource, showDefaultPicker) {
    const currentEditor = this.t.activeGroup.findEditors(resource).at(0);
    let registeredEditors = resource.scheme === Schemas.untitled ? this.L.filter((e) => e.editorInfo.priority !== RegisteredEditorPriority.exclusive) : this.M(resource);
    registeredEditors = $Rb(registeredEditors, (c) => c.editorInfo.id);
    const defaultSetting = this.getAssociationsForResource(resource)[0]?.viewType;
    registeredEditors = registeredEditors.sort((a, b) => {
      if (a.editorInfo.id === $1K.id) {
        return -1;
      } else if (b.editorInfo.id === $1K.id) {
        return 1;
      } else {
        return $6L(b.editorInfo.priority) - $6L(a.editorInfo.priority);
      }
    });
    const quickPickEntries = [];
    const currentlyActiveLabel = localize(12696, null);
    const currentDefaultLabel = localize(12697, null);
    const currentDefaultAndActiveLabel = localize(12698, null);
    let defaultViewType = defaultSetting;
    if (!defaultViewType && registeredEditors.length > 2 && registeredEditors[1]?.editorInfo.priority !== RegisteredEditorPriority.option) {
      defaultViewType = registeredEditors[1]?.editorInfo.id;
    }
    if (!defaultViewType) {
      defaultViewType = $1K.id;
    }
    registeredEditors.forEach((editor) => {
      const currentViewType = currentEditor?.editorId ?? $1K.id;
      const isActive2 = currentEditor ? editor.editorInfo.id === currentViewType : false;
      const isDefault = editor.editorInfo.id === defaultViewType;
      const quickPickEntry = {
        id: editor.editorInfo.id,
        label: editor.editorInfo.label,
        description: isActive2 && isDefault ? currentDefaultAndActiveLabel : isActive2 ? currentlyActiveLabel : isDefault ? currentDefaultLabel : void 0,
        detail: editor.editorInfo.detail ?? editor.editorInfo.priority
      };
      quickPickEntries.push(quickPickEntry);
    });
    if (!showDefaultPicker && $th(resource) !== "") {
      const separator = { type: "separator" };
      quickPickEntries.push(separator);
      const configureDefaultEntry = {
        id: $NVb_1.g,
        label: localize(12699, null, `*${$th(resource)}`)
      };
      quickPickEntries.push(configureDefaultEntry);
    }
    return quickPickEntries;
  }
  async U(editor, showDefaultPicker) {
    let resource = $mL.getOriginalUri(editor, { supportSideBySide: SideBySideEditor.PRIMARY });
    if (resource === void 0) {
      resource = URI.from({ scheme: Schemas.untitled });
    }
    const editorPicks = this.S(resource, showDefaultPicker);
    const disposables = new $2c();
    const editorPicker = disposables.add(this.y.createQuickPick({ useSeparators: true }));
    const placeHolderMessage = showDefaultPicker ? localize(12700, null, `*${$th(resource)}`) : localize(12701, null, $sh(resource));
    editorPicker.placeholder = placeHolderMessage;
    editorPicker.canAcceptInBackground = true;
    editorPicker.items = editorPicks;
    const firstItem = editorPicker.items.find((item) => item.type === "item");
    if (firstItem) {
      editorPicker.selectedItems = [firstItem];
    }
    const picked = await new Promise((resolve) => {
      disposables.add(editorPicker.onDidAccept((e) => {
        let result = void 0;
        if (editorPicker.selectedItems.length === 1) {
          result = {
            item: editorPicker.selectedItems[0],
            keyMods: editorPicker.keyMods,
            openInBackground: e.inBackground
          };
        }
        if (resource && showDefaultPicker && result?.item.id) {
          this.updateUserAssociations(`*${$th(resource)}`, result.item.id);
        }
        resolve(result);
      }));
      disposables.add(editorPicker.onDidHide(() => {
        disposables.dispose();
        resolve(void 0);
      }));
      disposables.add(editorPicker.onDidTriggerItemButton((e) => {
        resolve({ item: e.item, openInBackground: false });
        if (resource && e.item && e.item.id) {
          this.updateUserAssociations(`*${$th(resource)}`, e.item.id);
        }
      }));
      editorPicker.show();
    });
    editorPicker.dispose();
    if (picked) {
      if (picked.item.id === $NVb_1.g) {
        return this.U(editor, true);
      }
      const targetOptions = {
        ...editor.options,
        override: picked.item.id,
        preserveFocus: picked.openInBackground || editor.options?.preserveFocus
      };
      return targetOptions;
    }
    return void 0;
  }
  W(chosenInput) {
    if (chosenInput.editorId) {
      this.C.publicLog2("override.viewType", { viewType: chosenInput.editorId });
    }
  }
  X() {
    const cacheStorage = /* @__PURE__ */ new Set();
    for (const [globPattern, contribPoint] of this.n) {
      const nonOptional = !!contribPoint.find((c) => c.editorInfo.priority !== RegisteredEditorPriority.option && c.editorInfo.id !== $1K.id);
      if (!nonOptional) {
        continue;
      }
      if ($El(globPattern)) {
        cacheStorage.add(`${globPattern.pattern}`);
      } else {
        cacheStorage.add(globPattern);
      }
    }
    const userAssociations = this.getAllUserAssociations();
    for (const association of userAssociations) {
      if (association.filenamePattern) {
        cacheStorage.add(association.filenamePattern);
      }
    }
    this.D.store(
      $NVb_1.h,
      JSON.stringify(Array.from(cacheStorage)),
      0,
      1
      /* StorageTarget.MACHINE */
    );
  }
  Y(resource) {
    if (!this.s) {
      return false;
    }
    for (const cacheEntry of this.s) {
      if ($7L(cacheEntry, resource)) {
        return true;
      }
    }
    return false;
  }
};
$NVb = $NVb_1 = __decorate([
  __param(0, $iJ),
  __param(1, $Pk),
  __param(2, $kl),
  __param(3, $1M),
  __param(4, $PJ),
  __param(5, $zv),
  __param(6, $jv),
  __param(7, $wN),
  __param(8, $wn)
], $NVb);
$SC(
  $4L,
  $NVb,
  0
  /* InstantiationType.Eager */
);

// out-build/vs/workbench/services/aiRelatedInformation/common/aiRelatedInformationService.js
var $OVb_1;
var $OVb = class $OVb2 {
  static {
    $OVb_1 = this;
  }
  static {
    this.DEFAULT_TIMEOUT = 1e3 * 10;
  }
  // 10 seconds
  constructor(b) {
    this.b = b;
    this.a = /* @__PURE__ */ new Map();
  }
  isEnabled() {
    return this.a.size > 0;
  }
  registerAiRelatedInformationProvider(type, provider) {
    const providers2 = this.a.get(type) ?? [];
    providers2.push(provider);
    this.a.set(type, providers2);
    return {
      dispose: () => {
        const providers3 = this.a.get(type) ?? [];
        const index = providers3.indexOf(provider);
        if (index !== -1) {
          providers3.splice(index, 1);
        }
        if (providers3.length === 0) {
          this.a.delete(type);
        }
      }
    };
  }
  async getRelatedInformation(query, types, token) {
    if (this.a.size === 0) {
      throw new Error("No related information providers registered");
    }
    const providers2 = [];
    for (const type of types) {
      const typeProviders = this.a.get(type);
      if (typeProviders) {
        providers2.push(...typeProviders);
      }
    }
    if (providers2.length === 0) {
      throw new Error("No related information providers registered for the given types");
    }
    const stopwatch = $te.create();
    const cancellablePromises = providers2.map((provider) => {
      return $Hh(async (t) => {
        try {
          const result = await provider.provideAiRelatedInformation(query, t);
          return result.filter((r2) => types.includes(r2.type));
        } catch (e) {
        }
        return [];
      });
    });
    try {
      const results = await $Lh(Promise.allSettled(cancellablePromises), $OVb_1.DEFAULT_TIMEOUT, () => {
        cancellablePromises.forEach((p) => p.cancel());
        this.b.warn("[AiRelatedInformationService]: Related information provider timed out");
      });
      if (!results) {
        return [];
      }
      const result = results.filter((r2) => r2.status === "fulfilled").flatMap((r2) => r2.value);
      return result;
    } finally {
      stopwatch.stop();
      this.b.trace(`[AiRelatedInformationService]: getRelatedInformation took ${stopwatch.elapsed()}ms`);
    }
  }
};
$OVb = $OVb_1 = __decorate([
  __param(0, $wn)
], $OVb);
$SC(
  $vS,
  $OVb,
  1
  /* InstantiationType.Delayed */
);

// out-build/vs/workbench/services/history/browser/historyService.js
var $PVb_1;
var $QVb_1;
var $PVb = class $PVb2 extends $3c {
  static {
    $PVb_1 = this;
  }
  static {
    this.a = "workbench.editor.mouseBackForwardToNavigate";
  }
  static {
    this.b = "workbench.editor.navigationScope";
  }
  constructor(h3, j, m, n, r2, s, t, u, w, y, z) {
    super();
    this.h = h3;
    this.j = j;
    this.m = m;
    this.n = n;
    this.r = r2;
    this.s = s;
    this.t = t;
    this.u = u;
    this.w = w;
    this.y = y;
    this.z = z;
    this.c = this.B(new $2c());
    this.f = void 0;
    this.g = this.u.createInstance(EditorHelper);
    this.Q = new $nn("canNavigateBack", false, localize(12926, null)).bindTo(this.y);
    this.R = new $nn("canNavigateForward", false, localize(12927, null)).bindTo(this.y);
    this.S = new $nn("canNavigateBackInNavigationLocations", false, localize(12928, null)).bindTo(this.y);
    this.U = new $nn("canNavigateForwardInNavigationLocations", false, localize(12929, null)).bindTo(this.y);
    this.W = new $nn("canNavigateToLastNavigationLocation", false, localize(12930, null)).bindTo(this.y);
    this.X = new $nn("canNavigateBackInEditLocations", false, localize(12931, null)).bindTo(this.y);
    this.Y = new $nn("canNavigateForwardInEditLocations", false, localize(12932, null)).bindTo(this.y);
    this.Z = new $nn("canNavigateToLastEditLocation", false, localize(12933, null)).bindTo(this.y);
    this.$ = new $nn("canReopenClosedEditor", false, localize(12934, null)).bindTo(this.y);
    this.ab = this.B(new $ze());
    this.onDidChangeEditorNavigationStack = this.ab.event;
    this.bb = void 0;
    this.cb = /* @__PURE__ */ new Map();
    this.db = /* @__PURE__ */ new Map();
    this.eb = 0;
    this.qb = void 0;
    this.rb = 0;
    this.sb = void 0;
    this.tb = 0;
    this.ub = false;
    this.vb = false;
    this.Ab = [];
    this.Bb = false;
    this.Hb = void 0;
    this.Ib = /* @__PURE__ */ new Map();
    this.Jb = this.B(new $hj($Y, () => {
      const matcher = this.B(this.u.createInstance($2J, (root) => $2N(root ? this.r.getValue({ resource: root }) : this.r.getValue()) || /* @__PURE__ */ Object.create(null), (event) => event.affectsConfiguration($Lm) || event.affectsConfiguration($RN)));
      this.B(matcher.onExpressionChange(() => this.Ob()));
      return matcher;
    }));
    this.C();
    if (this.h.activeEditorPane) {
      this.I();
    }
  }
  C() {
    this.F();
    this.B(this.h.onDidActiveEditorChange(() => this.I()));
    this.B(this.h.onDidOpenEditorFail((event) => this.O(event.editor)));
    this.B(this.h.onDidCloseEditor((event) => this.D(event)));
    this.B(this.h.onDidMostRecentlyActiveEditorsChange(() => this.yb()));
    this.B(this.j.onDidRemoveGroup((e) => this.H(e)));
    this.B(this.s.onDidFilesChange((event) => this.J(event)));
    this.B(this.s.onDidRunOperation((event) => this.J(event)));
    this.B(this.n.onWillSaveState(() => this.Ub()));
    this.fb();
    this.B(this.onDidChangeEditorNavigationStack(() => this.updateContextKeys()));
    this.B(this.j.onDidChangeActiveGroup(() => this.updateContextKeys()));
  }
  D(e) {
    this.jb(e);
    this.Cb(e);
  }
  F() {
    const mouseBackForwardSupportListener = this.B(new $2c());
    const handleMouseBackForwardSupport = () => {
      mouseBackForwardSupportListener.clear();
      if (this.r.getValue($PVb_1.a)) {
        this.B(Event2.runAndSubscribe(this.w.onDidAddContainer, ({ container: container2, disposables }) => {
          const eventDisposables = disposables.add(new $2c());
          eventDisposables.add($_i(container2, $7j.MOUSE_DOWN, (e) => this.G(e, true)));
          eventDisposables.add($_i(container2, $7j.MOUSE_UP, (e) => this.G(e, false)));
          mouseBackForwardSupportListener.add(eventDisposables);
        }, { container: this.w.mainContainer, disposables: this.q }));
      }
    };
    this.B(this.r.onDidChangeConfiguration((event) => {
      if (event.affectsConfiguration($PVb_1.a)) {
        handleMouseBackForwardSupport();
      }
    }));
    handleMouseBackForwardSupport();
  }
  G(event, isMouseDown) {
    switch (event.button) {
      case 3:
        $9j.stop(event);
        if (isMouseDown) {
          this.goBack();
        }
        break;
      case 4:
        $9j.stop(event);
        if (isMouseDown) {
          this.goForward();
        }
        break;
    }
  }
  H(group2) {
    this.kb(group2);
  }
  I() {
    const activeEditorGroup = this.j.activeGroup;
    const activeEditorPane = activeEditorGroup.activeEditorPane;
    if (this.f && this.g.matchesEditorIdentifier(this.f, activeEditorPane)) {
      return;
    }
    this.f = activeEditorPane?.input ? { editor: activeEditorPane.input, groupId: activeEditorPane.group.id } : void 0;
    this.c.clear();
    if (!activeEditorPane?.group.isTransient(activeEditorPane.input)) {
      this.L(activeEditorGroup, activeEditorPane);
    } else {
      this.z.trace(`[History]: ignoring transient editor change until becoming non-transient (editor: ${activeEditorPane.input?.resource?.toString()}})`);
      const transientListener = activeEditorGroup.onDidModelChange((e) => {
        if (e.kind === 12 && e.editor === activeEditorPane.input && !activeEditorPane.group.isTransient(activeEditorPane.input)) {
          transientListener.dispose();
          this.L(activeEditorGroup, activeEditorPane);
        }
      });
      this.c.add(transientListener);
    }
    if ($5K(activeEditorPane)) {
      this.c.add(activeEditorPane.onDidChangeSelection((e) => {
        if (!activeEditorPane.group.isTransient(activeEditorPane.input)) {
          this.M(activeEditorGroup, activeEditorPane, e);
        } else {
          this.z.trace(`[History]: ignoring transient editor selection change (editor: ${activeEditorPane.input?.resource?.toString()}})`);
        }
      }));
    }
    this.updateContextKeys();
  }
  J(event) {
    if (event instanceof $Dm) {
      if (event.gotDeleted()) {
        this.O(event);
      }
    } else {
      if (event.isOperation(
        1
        /* FileOperation.DELETE */
      )) {
        this.O(event);
      } else if (event.isOperation(
        2
        /* FileOperation.MOVE */
      ) && event.target.isFile) {
        this.N(event);
      }
    }
  }
  L(group2, editorPane) {
    this.Kb(editorPane);
    this.hb(group2, editorPane);
  }
  M(group2, editorPane, event) {
    this.ib(group2, editorPane, event);
  }
  N(event) {
    this.Pb(event);
    this.nb(event);
  }
  O(arg1) {
    this.removeFromHistory(arg1);
    this.mb(arg1);
    this.Eb(arg1);
    this.P(arg1);
  }
  P(arg1) {
    let resource = void 0;
    if ($dL(arg1)) {
      resource = $mL.getOriginalUri(arg1);
    } else if (arg1 instanceof $Dm) {
    } else {
      resource = arg1.resource;
    }
    if (resource) {
      this.t.removeRecentlyOpened([resource]);
    }
  }
  clear() {
    this.clearRecentlyOpened();
    this.lb();
    this.Ab = [];
    this.updateContextKeys();
  }
  updateContextKeys() {
    this.y.bufferChangeEvents(() => {
      const activeStack = this.gb();
      this.Q.set(activeStack.canGoBack(
        0
        /* GoFilter.NONE */
      ));
      this.R.set(activeStack.canGoForward(
        0
        /* GoFilter.NONE */
      ));
      this.S.set(activeStack.canGoBack(
        2
        /* GoFilter.NAVIGATION */
      ));
      this.U.set(activeStack.canGoForward(
        2
        /* GoFilter.NAVIGATION */
      ));
      this.W.set(activeStack.canGoLast(
        2
        /* GoFilter.NAVIGATION */
      ));
      this.X.set(activeStack.canGoBack(
        1
        /* GoFilter.EDITS */
      ));
      this.Y.set(activeStack.canGoForward(
        1
        /* GoFilter.EDITS */
      ));
      this.Z.set(activeStack.canGoLast(
        1
        /* GoFilter.EDITS */
      ));
      this.$.set(this.Ab.length > 0);
    });
  }
  fb() {
    const handleEditorNavigationScopeChange = () => {
      this.pb();
      const configuredScope = this.r.getValue($PVb_1.b);
      if (configuredScope === "editorGroup") {
        this.eb = 1;
      } else if (configuredScope === "editor") {
        this.eb = 2;
      } else {
        this.eb = 0;
      }
    };
    this.B(this.r.onDidChangeConfiguration((event) => {
      if (event.affectsConfiguration($PVb_1.b)) {
        handleEditorNavigationScopeChange();
      }
    }));
    handleEditorNavigationScopeChange();
  }
  gb(group2 = this.j.activeGroup, editor = group2.activeEditor) {
    switch (this.eb) {
      case 2: {
        if (!editor) {
          return new NoOpEditorNavigationStacks();
        }
        let stacksForGroup = this.db.get(group2.id);
        if (!stacksForGroup) {
          stacksForGroup = /* @__PURE__ */ new Map();
          this.db.set(group2.id, stacksForGroup);
        }
        let stack = stacksForGroup.get(editor)?.stack;
        if (!stack) {
          const disposable = new $2c();
          stack = disposable.add(this.u.createInstance(
            EditorNavigationStacks,
            2
            /* GoScope.EDITOR */
          ));
          disposable.add(stack.onDidChange(() => this.ab.fire()));
          stacksForGroup.set(editor, { stack, disposable });
        }
        return stack;
      }
      case 1: {
        let stack = this.cb.get(group2.id)?.stack;
        if (!stack) {
          const disposable = new $2c();
          stack = disposable.add(this.u.createInstance(
            EditorNavigationStacks,
            1
            /* GoScope.EDITOR_GROUP */
          ));
          disposable.add(stack.onDidChange(() => this.ab.fire()));
          this.cb.set(group2.id, { stack, disposable });
        }
        return stack;
      }
      case 0: {
        if (!this.bb) {
          this.bb = this.B(this.u.createInstance(
            EditorNavigationStacks,
            0
            /* GoScope.DEFAULT */
          ));
          this.B(this.bb.onDidChange(() => this.ab.fire()));
        }
        return this.bb;
      }
    }
  }
  goForward(filter) {
    return this.gb().goForward(filter);
  }
  goBack(filter) {
    return this.gb().goBack(filter);
  }
  goPrevious(filter) {
    return this.gb().goPrevious(filter);
  }
  goLast(filter) {
    return this.gb().goLast(filter);
  }
  hb(group2, editorPane) {
    this.gb(group2, editorPane?.input).handleActiveEditorChange(editorPane);
  }
  ib(group2, editorPane, event) {
    this.gb(group2, editorPane.input).handleActiveEditorSelectionChange(editorPane, event);
  }
  jb(e) {
    const editors = this.db.get(e.groupId);
    if (editors) {
      const editorStack = editors.get(e.editor);
      if (editorStack) {
        editorStack.disposable.dispose();
        editors.delete(e.editor);
      }
      if (editors.size === 0) {
        this.db.delete(e.groupId);
      }
    }
  }
  kb(group2) {
    this.bb?.remove(group2.id);
    const editorGroupStack = this.cb.get(group2.id);
    if (editorGroupStack) {
      editorGroupStack.disposable.dispose();
      this.cb.delete(group2.id);
    }
  }
  lb() {
    this.ob((stack) => stack.clear());
  }
  mb(arg1) {
    this.ob((stack) => stack.remove(arg1));
  }
  nb(event) {
    this.ob((stack) => stack.move(event));
  }
  ob(fn) {
    if (this.bb) {
      fn(this.bb);
    }
    for (const [, entry] of this.cb) {
      fn(entry.stack);
    }
    for (const [, entries2] of this.db) {
      for (const [, entry] of entries2) {
        fn(entry.stack);
      }
    }
  }
  pb() {
    this.bb?.dispose();
    this.bb = void 0;
    for (const [, stack] of this.cb) {
      stack.disposable.dispose();
    }
    this.cb.clear();
    for (const [, stacks] of this.db) {
      for (const [, stack] of stacks) {
        stack.disposable.dispose();
      }
    }
    this.db.clear();
  }
  openNextRecentlyUsedEditor(groupId) {
    const [stack, index] = this.xb((index2) => index2 - 1, groupId);
    return this.wb(stack[index], groupId);
  }
  openPreviouslyUsedEditor(groupId) {
    const [stack, index] = this.xb((index2) => index2 + 1, groupId);
    return this.wb(stack[index], groupId);
  }
  async wb(editorIdentifier, groupId) {
    if (editorIdentifier) {
      const acrossGroups = typeof groupId !== "number" || !this.j.getGroup(groupId);
      if (acrossGroups) {
        this.ub = true;
      } else {
        this.vb = true;
      }
      const group2 = this.j.getGroup(editorIdentifier.groupId) ?? this.j.activeGroup;
      try {
        await group2.openEditor(editorIdentifier.editor);
      } finally {
        if (acrossGroups) {
          this.ub = false;
        } else {
          this.vb = false;
        }
      }
    }
  }
  xb(indexModifier, groupId) {
    let editors;
    let index;
    const group2 = typeof groupId === "number" ? this.j.getGroup(groupId) : void 0;
    if (!group2) {
      editors = this.qb || this.h.getEditors(
        0
        /* EditorsOrder.MOST_RECENTLY_ACTIVE */
      );
      index = this.rb;
    } else {
      editors = this.sb || group2.getEditors(
        0
        /* EditorsOrder.MOST_RECENTLY_ACTIVE */
      ).map((editor) => ({ groupId: group2.id, editor }));
      index = this.tb;
    }
    let newIndex = indexModifier(index);
    if (newIndex < 0) {
      newIndex = 0;
    } else if (newIndex > editors.length - 1) {
      newIndex = editors.length - 1;
    }
    if (!group2) {
      this.qb = editors;
      this.rb = newIndex;
    } else {
      this.sb = editors;
      this.tb = newIndex;
    }
    return [editors, newIndex];
  }
  yb() {
    if (!this.ub) {
      this.qb = void 0;
      this.rb = 0;
    }
    if (!this.vb) {
      this.sb = void 0;
      this.tb = 0;
    }
  }
  static {
    this.zb = 20;
  }
  Cb(event) {
    if (this.Bb) {
      return;
    }
    const { editor, context } = event;
    if (context === EditorCloseContext.REPLACE || context === EditorCloseContext.MOVE) {
      return;
    }
    const untypedEditor = editor.toUntyped();
    if (!untypedEditor) {
      return;
    }
    const associatedResources = [];
    const editorResource = $mL.getOriginalUri(editor, { supportSideBySide: SideBySideEditor.BOTH });
    if (URI.isUri(editorResource)) {
      associatedResources.push(editorResource);
    } else if (editorResource) {
      associatedResources.push(...$Mb([editorResource.primary, editorResource.secondary]));
    }
    this.Eb(editor);
    this.Ab.push({
      editorId: editor.editorId,
      editor: untypedEditor,
      resource: $mL.getOriginalUri(editor),
      associatedResources,
      index: event.index,
      sticky: event.sticky
    });
    if (this.Ab.length > $PVb_1.zb) {
      this.Ab.shift();
    }
    this.$.set(true);
  }
  async reopenLastClosedEditor() {
    const lastClosedEditor = this.Ab.pop();
    let reopenClosedEditorPromise = void 0;
    if (lastClosedEditor) {
      reopenClosedEditorPromise = this.Db(lastClosedEditor);
    }
    this.$.set(this.Ab.length > 0);
    return reopenClosedEditorPromise;
  }
  async Db(lastClosedEditor) {
    const options3 = { pinned: true, sticky: lastClosedEditor.sticky, index: lastClosedEditor.index, ignoreError: true };
    if (lastClosedEditor.sticky && !this.j.activeGroup.isSticky(lastClosedEditor.index) || !lastClosedEditor.sticky && this.j.activeGroup.isSticky(lastClosedEditor.index)) {
      options3.index = void 0;
    }
    let editorPane = void 0;
    if (!this.j.activeGroup.contains(lastClosedEditor.editor)) {
      this.Bb = true;
      try {
        editorPane = await this.h.openEditor({
          ...lastClosedEditor.editor,
          options: {
            ...lastClosedEditor.editor.options,
            ...options3
          }
        });
      } finally {
        this.Bb = false;
      }
    }
    if (!editorPane) {
      $Xb(this.Ab, lastClosedEditor);
      this.reopenLastClosedEditor();
    }
  }
  Eb(arg1) {
    this.Ab = this.Ab.filter((recentlyClosedEditor) => {
      if ($dL(arg1) && recentlyClosedEditor.editorId !== arg1.editorId) {
        return true;
      }
      if (recentlyClosedEditor.resource && this.g.matchesFile(recentlyClosedEditor.resource, arg1)) {
        return false;
      }
      if (recentlyClosedEditor.associatedResources.some((associatedResource) => this.g.matchesFile(associatedResource, arg1))) {
        return false;
      }
      return true;
    });
    this.$.set(this.Ab.length > 0);
  }
  static {
    this.Fb = 200;
  }
  static {
    this.Gb = "history.entries";
  }
  Kb(editorPane) {
    const editor = editorPane?.input;
    if (!editor || editor.isDisposed() || !this.Nb(editor)) {
      return;
    }
    this.removeFromHistory(editor);
    this.Lb(editor);
  }
  Lb(editor, insertFirst = true) {
    this.Rb(this.Hb);
    const historyInput = this.g.preferResourceEditorInput(editor);
    if (!historyInput) {
      return;
    }
    if (insertFirst) {
      this.Hb.unshift(historyInput);
    } else {
      this.Hb.push(historyInput);
    }
    if (this.Hb.length > $PVb_1.Fb) {
      this.g.clearOnEditorDispose(this.Hb.pop(), this.Ib);
    }
    if ($dL(editor)) {
      this.g.onEditorDispose(editor, () => this.Mb(historyInput), this.Ib);
    }
  }
  Mb(editor) {
    if ($dL(editor)) {
      if (!$eL(editor)) {
        this.removeFromHistory(editor);
      } else {
        const resourceInputs = [];
        const sideInputs = editor.primary.matches(editor.secondary) ? [editor.primary] : [editor.primary, editor.secondary];
        for (const sideInput of sideInputs) {
          const candidateResourceInput = this.g.preferResourceEditorInput(sideInput);
          if ($8K(candidateResourceInput) && this.Nb(candidateResourceInput)) {
            resourceInputs.push(candidateResourceInput);
          }
        }
        this.Qb(editor, ...resourceInputs);
      }
    } else {
      if (!this.Nb(editor)) {
        this.removeFromHistory(editor);
      }
    }
  }
  Nb(editor) {
    if ($dL(editor)) {
      return true;
    }
    return !this.Jb.value.matches(editor.resource);
  }
  Ob() {
    this.Rb(this.Hb);
    this.Hb = this.Hb.filter((entry) => {
      const include = this.Nb(entry);
      if (!include) {
        this.g.clearOnEditorDispose(entry, this.Ib);
      }
      return include;
    });
  }
  Pb(event) {
    if (event.isOperation(
      2
      /* FileOperation.MOVE */
    )) {
      const removed = this.removeFromHistory(event);
      if (removed) {
        this.Lb({ resource: event.target.resource });
      }
    }
  }
  removeFromHistory(arg1) {
    let removed = false;
    this.Rb(this.Hb);
    this.Hb = this.Hb.filter((entry) => {
      const matches = this.g.matchesEditor(arg1, entry);
      if (matches) {
        this.g.clearOnEditorDispose(arg1, this.Ib);
        removed = true;
      }
      return !matches;
    });
    return removed;
  }
  Qb(editor, ...replacements) {
    this.Rb(this.Hb);
    let replaced = false;
    const newHistory = [];
    for (const entry of this.Hb) {
      if (this.g.matchesEditor(editor, entry)) {
        this.g.clearOnEditorDispose(editor, this.Ib);
        if (!replaced) {
          newHistory.push(...replacements);
          replaced = true;
        }
      } else if (!replacements.some((replacement) => this.g.matchesEditor(replacement, entry))) {
        newHistory.push(entry);
      }
    }
    if (!replaced) {
      newHistory.push(...replacements);
    }
    this.Hb = newHistory;
  }
  clearRecentlyOpened() {
    this.Hb = [];
    for (const [, disposable] of this.Ib) {
      $Xc(disposable);
    }
    this.Ib.clear();
  }
  getHistory() {
    this.Rb(this.Hb);
    return this.Hb;
  }
  Rb(history) {
    if (!this.Hb) {
      this.Hb = [];
      if (this.j.isReady) {
        this.Sb();
      } else {
        (async () => {
          await this.j.whenReady;
          this.Sb();
        })();
      }
    }
  }
  Sb() {
    this.Hb = [];
    const storedEditorHistory = this.Tb();
    const openedEditorsLru = [...this.h.getEditors(
      0
      /* EditorsOrder.MOST_RECENTLY_ACTIVE */
    )].reverse();
    const handledEditors = /* @__PURE__ */ new Set();
    for (const { editor } of openedEditorsLru) {
      if (!this.Nb(editor)) {
        continue;
      }
      if (editor.resource) {
        const historyEntryId = `${editor.resource.toString()}/${editor.editorId}`;
        if (handledEditors.has(historyEntryId)) {
          continue;
        }
        handledEditors.add(historyEntryId);
      }
      this.Lb(editor);
    }
    for (const editor of storedEditorHistory) {
      const historyEntryId = `${editor.resource.toString()}/${editor.options?.override}`;
      if (!handledEditors.has(historyEntryId) && this.Nb(editor)) {
        handledEditors.add(historyEntryId);
        this.Lb(
          editor,
          false
          /* at the end */
        );
      }
    }
  }
  Tb() {
    const entries2 = [];
    const entriesRaw = this.n.get(
      $PVb_1.Gb,
      1
      /* StorageScope.WORKSPACE */
    );
    if (entriesRaw) {
      try {
        const entriesParsed = JSON.parse(entriesRaw);
        for (const entryParsed of entriesParsed) {
          if (!entryParsed.editor || !entryParsed.editor.resource) {
            continue;
          }
          try {
            entries2.push({
              ...entryParsed.editor,
              resource: typeof entryParsed.editor.resource === "string" ? URI.parse(entryParsed.editor.resource) : (
                //  from 1.67.x: URI is stored efficiently as URI.toString()
                URI.from(entryParsed.editor.resource)
              )
              // until 1.66.x: URI was stored very verbose as URI.toJSON()
            });
          } catch (error) {
            $gb(error);
          }
        }
      } catch (error) {
        $gb(error);
      }
    }
    return entries2;
  }
  Ub() {
    if (!this.Hb) {
      return;
    }
    const entries2 = [];
    for (const editor of this.Hb) {
      if ($dL(editor) || !$8K(editor)) {
        continue;
      }
      entries2.push({
        editor: {
          ...editor,
          resource: editor.resource.toString()
        }
      });
    }
    this.n.store(
      $PVb_1.Gb,
      JSON.stringify(entries2),
      1,
      1
      /* StorageTarget.MACHINE */
    );
  }
  //#endregion
  //#region Last Active Workspace/File
  getLastActiveWorkspaceRoot(schemeFilter, authorityFilter) {
    const folders = this.m.getWorkspace().folders;
    if (folders.length === 0) {
      return void 0;
    }
    if (folders.length === 1) {
      const resource = folders[0].uri;
      if ((!schemeFilter || resource.scheme === schemeFilter) && (!authorityFilter || resource.authority === authorityFilter)) {
        return resource;
      }
      return void 0;
    }
    for (const input of this.getHistory()) {
      if ($dL(input)) {
        continue;
      }
      if (schemeFilter && input.resource.scheme !== schemeFilter) {
        continue;
      }
      if (authorityFilter && input.resource.authority !== authorityFilter) {
        continue;
      }
      const resourceWorkspace = this.m.getWorkspaceFolder(input.resource);
      if (resourceWorkspace) {
        return resourceWorkspace.uri;
      }
    }
    for (const folder of folders) {
      const resource = folder.uri;
      if ((!schemeFilter || resource.scheme === schemeFilter) && (!authorityFilter || resource.authority === authorityFilter)) {
        return resource;
      }
    }
    return void 0;
  }
  getLastActiveFile(filterByScheme, filterByAuthority) {
    for (const input of this.getHistory()) {
      let resource;
      if ($dL(input)) {
        resource = $mL.getOriginalUri(input, { filterByScheme });
      } else {
        resource = input.resource;
      }
      if (resource && resource.scheme === filterByScheme && (!filterByAuthority || resource.authority === filterByAuthority)) {
        return resource;
      }
    }
    return void 0;
  }
  //#endregion
  dispose() {
    super.dispose();
    for (const [, stack] of this.cb) {
      stack.disposable.dispose();
    }
    for (const [, editors] of this.db) {
      for (const [, stack] of editors) {
        stack.disposable.dispose();
      }
    }
    for (const [, listener] of this.Ib) {
      listener.dispose();
    }
  }
};
$PVb = $PVb_1 = __decorate([
  __param(0, $mJ),
  __param(1, $iJ),
  __param(2, $Zk),
  __param(3, $jv),
  __param(4, $kl),
  __param(5, $km),
  __param(6, $2w),
  __param(7, $Pk),
  __param(8, $Vlb),
  __param(9, $on),
  __param(10, $wn)
], $PVb);
$SC(
  $tY,
  $PVb,
  0
  /* InstantiationType.Eager */
);
var EditorSelectionState = class {
  constructor(a, selection, b) {
    this.a = a;
    this.selection = selection;
    this.b = b;
  }
  justifiesNewNavigationEntry(other) {
    if (this.a.groupId !== other.a.groupId) {
      return true;
    }
    if (!this.a.editor.matches(other.a.editor)) {
      return true;
    }
    if (!this.selection || !other.selection) {
      return true;
    }
    const result = this.selection.compare(other.selection);
    if (result === 2 && (other.b === 4 || other.b === 5)) {
      return true;
    }
    return result === 3;
  }
};
var EditorNavigationStacks = class EditorNavigationStacks2 extends $3c {
  constructor(g, h3) {
    super();
    this.g = g;
    this.h = h3;
    this.a = this.B(this.h.createInstance($QVb, 0, this.g));
    this.b = this.B(this.h.createInstance($QVb, 1, this.g));
    this.c = this.B(this.h.createInstance($QVb, 2, this.g));
    this.f = [
      this.a,
      this.b,
      this.c
    ];
    this.onDidChange = Event2.any(this.a.onDidChange, this.b.onDidChange, this.c.onDidChange);
  }
  canGoForward(filter) {
    return this.j(filter).canGoForward();
  }
  goForward(filter) {
    return this.j(filter).goForward();
  }
  canGoBack(filter) {
    return this.j(filter).canGoBack();
  }
  goBack(filter) {
    return this.j(filter).goBack();
  }
  goPrevious(filter) {
    return this.j(filter).goPrevious();
  }
  canGoLast(filter) {
    return this.j(filter).canGoLast();
  }
  goLast(filter) {
    return this.j(filter).goLast();
  }
  j(filter = 0) {
    switch (filter) {
      case 0:
        return this.a;
      case 1:
        return this.b;
      case 2:
        return this.c;
    }
  }
  handleActiveEditorChange(editorPane) {
    this.a.notifyNavigation(editorPane);
  }
  handleActiveEditorSelectionChange(editorPane, event) {
    const previous = this.a.s;
    this.a.notifyNavigation(editorPane, event);
    if (event.reason === 3) {
      this.b.notifyNavigation(editorPane, event);
    } else if ((event.reason === 4 || event.reason === 5) && !this.a.isNavigating()) {
      if (event.reason === 5 && !this.c.isNavigating()) {
        if (previous) {
          this.c.addOrReplace(previous.groupId, previous.editor, previous.selection);
        }
      }
      this.c.notifyNavigation(editorPane, event);
    }
  }
  clear() {
    for (const stack of this.f) {
      stack.clear();
    }
  }
  remove(arg1) {
    for (const stack of this.f) {
      stack.remove(arg1);
    }
  }
  move(event) {
    for (const stack of this.f) {
      stack.move(event);
    }
  }
};
EditorNavigationStacks = __decorate([
  __param(1, $Pk)
], EditorNavigationStacks);
var NoOpEditorNavigationStacks = class {
  constructor() {
    this.onDidChange = Event2.None;
  }
  canGoForward() {
    return false;
  }
  async goForward() {
  }
  canGoBack() {
    return false;
  }
  async goBack() {
  }
  async goPrevious() {
  }
  canGoLast() {
    return false;
  }
  async goLast() {
  }
  handleActiveEditorChange() {
  }
  handleActiveEditorSelectionChange() {
  }
  clear() {
  }
  remove() {
  }
  move() {
  }
  dispose() {
  }
};
var $QVb = class $QVb2 extends $3c {
  static {
    $QVb_1 = this;
  }
  static {
    this.a = 50;
  }
  get s() {
    return this.h[this.j];
  }
  set s(entry) {
    if (entry) {
      this.h[this.j] = entry;
    }
  }
  constructor(t, u, w, y, z, C) {
    super();
    this.t = t;
    this.u = u;
    this.w = w;
    this.y = y;
    this.z = z;
    this.C = C;
    this.b = this.B(new $ze());
    this.onDidChange = this.b.event;
    this.c = /* @__PURE__ */ new Map();
    this.f = /* @__PURE__ */ new Map();
    this.g = this.w.createInstance(EditorHelper);
    this.h = [];
    this.j = -1;
    this.m = -1;
    this.n = false;
    this.r = void 0;
    this.D();
  }
  D() {
    this.B(this.onDidChange(() => this.F()));
    this.B(this.C.onDidChangeLogLevel(() => this.F()));
  }
  F() {
    if (this.C.getLevel() !== LogLevel.Trace) {
      return;
    }
    const entryLabels = [];
    for (const entry of this.h) {
      if (typeof entry.selection?.log === "function") {
        entryLabels.push(`- group: ${entry.groupId}, editor: ${entry.editor.resource?.toString()}, selection: ${entry.selection.log()}`);
      } else {
        entryLabels.push(`- group: ${entry.groupId}, editor: ${entry.editor.resource?.toString()}, selection: <none>`);
      }
    }
    if (entryLabels.length === 0) {
      this.G(`index: ${this.j}, navigating: ${this.isNavigating()}: <empty>`);
    } else {
      this.G(`index: ${this.j}, navigating: ${this.isNavigating()}
${entryLabels.join("\n")}
			`);
    }
  }
  G(msg, editor = null, event) {
    if (this.C.getLevel() !== LogLevel.Trace) {
      return;
    }
    let filterLabel;
    switch (this.t) {
      case 0:
        filterLabel = "global";
        break;
      case 1:
        filterLabel = "edits";
        break;
      case 2:
        filterLabel = "navigation";
        break;
    }
    let scopeLabel;
    switch (this.u) {
      case 0:
        scopeLabel = "default";
        break;
      case 1:
        scopeLabel = "editorGroup";
        break;
      case 2:
        scopeLabel = "editor";
        break;
    }
    if (editor !== null) {
      this.C.trace(`[History stack ${filterLabel}-${scopeLabel}]: ${msg} (editor: ${editor?.resource?.toString()}, event: ${this.H(event)})`);
    } else {
      this.C.trace(`[History stack ${filterLabel}-${scopeLabel}]: ${msg}`);
    }
  }
  H(event) {
    if (!event) {
      return "<none>";
    }
    switch (event.reason) {
      case 3:
        return "edit";
      case 4:
        return "navigation";
      case 5:
        return "jump";
      case 1:
        return "programmatic";
      case 2:
        return "user";
    }
  }
  I(groupId) {
    if (!this.f.has(groupId)) {
      const group2 = this.z.getGroup(groupId);
      if (group2) {
        this.f.set(groupId, group2.onWillMoveEditor((e) => this.J(e)));
      }
    }
  }
  J(e) {
    this.G("onWillMoveEditor()", e.editor);
    if (this.u === 1) {
      return;
    }
    for (const entry of this.h) {
      if (entry.groupId !== e.groupId) {
        continue;
      }
      if (!this.g.matchesEditor(e.editor, entry.editor)) {
        continue;
      }
      entry.groupId = e.target;
    }
  }
  //#region Stack Mutation
  notifyNavigation(editorPane, event) {
    this.G("notifyNavigation()", editorPane?.input, event);
    const isSelectionAwareEditorPane = $5K(editorPane);
    const hasValidEditor = editorPane?.input && !editorPane.input.isDisposed();
    if (this.n) {
      this.G(`notifyNavigation() ignoring (navigating)`, editorPane?.input, event);
      if (isSelectionAwareEditorPane && hasValidEditor) {
        this.G("notifyNavigation() updating current selection state", editorPane?.input, event);
        this.r = new EditorSelectionState({ groupId: editorPane.group.id, editor: editorPane.input }, editorPane.getSelection(), event?.reason);
      } else {
        this.G("notifyNavigation() dropping current selection state", editorPane?.input, event);
        this.r = void 0;
      }
    } else {
      this.G(`notifyNavigation() not ignoring`, editorPane?.input, event);
      if (isSelectionAwareEditorPane && hasValidEditor) {
        this.L(editorPane.group.id, editorPane.input, editorPane.getSelection(), event);
      } else {
        this.r = void 0;
        if (hasValidEditor) {
          this.M(editorPane.group.id, editorPane.input);
        }
      }
    }
  }
  L(groupId, editor, selection, event) {
    if (this.s?.groupId === groupId && !selection && this.g.matchesEditor(this.s.editor, editor)) {
      return;
    }
    this.G("onSelectionAwareEditorNavigation()", editor, event);
    const stateCandidate = new EditorSelectionState({ groupId, editor }, selection, event?.reason);
    if (!this.r || this.r.justifiesNewNavigationEntry(stateCandidate)) {
      this.N(groupId, editor, stateCandidate.selection);
    } else {
      this.O(groupId, editor, stateCandidate.selection);
    }
    this.r = stateCandidate;
  }
  M(groupId, editor) {
    if (this.s?.groupId === groupId && this.g.matchesEditor(this.s.editor, editor)) {
      return;
    }
    this.G("onNonSelectionAwareEditorNavigation()", editor);
    this.N(groupId, editor);
  }
  N(groupId, editor, selection) {
    if (!this.n) {
      this.addOrReplace(groupId, editor, selection);
    }
  }
  O(groupId, editor, selection) {
    if (!this.n) {
      this.addOrReplace(
        groupId,
        editor,
        selection,
        true
        /* force replace */
      );
    }
  }
  addOrReplace(groupId, editorCandidate, selection, forceReplace) {
    this.I(groupId);
    let replace = false;
    if (this.s) {
      if (forceReplace) {
        replace = true;
      } else if (this.P(this.s, { groupId, editor: editorCandidate, selection })) {
        replace = true;
      }
    }
    const editor = this.g.preferResourceEditorInput(editorCandidate);
    if (!editor) {
      return;
    }
    if (replace) {
      this.G("replace()", editor);
    } else {
      this.G("add()", editor);
    }
    const newStackEntry = { groupId, editor, selection };
    const removedEntries = [];
    if (replace) {
      if (this.s) {
        removedEntries.push(this.s);
      }
      this.s = newStackEntry;
    } else {
      if (this.h.length > this.j + 1) {
        for (let i2 = this.j + 1; i2 < this.h.length; i2++) {
          removedEntries.push(this.h[i2]);
        }
        this.h = this.h.slice(0, this.j + 1);
      }
      this.h.splice(this.j + 1, 0, newStackEntry);
      if (this.h.length > $QVb_1.a) {
        removedEntries.push(this.h.shift());
        if (this.m >= 0) {
          this.m--;
        }
      } else {
        this.U(
          this.j + 1,
          true
          /* skip event, we fire it later */
        );
      }
    }
    for (const removedEntry of removedEntries) {
      this.g.clearOnEditorDispose(removedEntry.editor, this.c);
    }
    if ($dL(editor)) {
      this.g.onEditorDispose(editor, () => this.remove(editor), this.c);
    }
    this.b.fire();
  }
  P(entry, candidate) {
    if (entry.groupId !== candidate.groupId) {
      return false;
    }
    if (!this.g.matchesEditor(entry.editor, candidate.editor)) {
      return false;
    }
    if (!entry.selection) {
      return true;
    }
    if (!candidate.selection) {
      return false;
    }
    return entry.selection.compare(candidate.selection) === 1;
  }
  move(event) {
    if (event.isOperation(
      2
      /* FileOperation.MOVE */
    )) {
      for (const entry of this.h) {
        if (this.g.matchesEditor(event, entry.editor)) {
          entry.editor = { resource: event.target.resource };
        }
      }
    }
  }
  remove(arg1) {
    const previousStackSize = this.h.length;
    this.h = this.h.filter((entry) => {
      const matches = typeof arg1 === "number" ? entry.groupId === arg1 : this.g.matchesEditor(arg1, entry.editor);
      if (matches) {
        this.g.clearOnEditorDispose(entry.editor, this.c);
      }
      return !matches;
    });
    if (previousStackSize === this.h.length) {
      return;
    }
    this.Q();
    this.j = this.h.length - 1;
    this.m = -1;
    if (typeof arg1 === "number") {
      this.f.get(arg1)?.dispose();
      this.f.delete(arg1);
    }
    this.b.fire();
  }
  Q() {
    const flattenedStack = [];
    let previousEntry = void 0;
    for (const entry of this.h) {
      if (previousEntry && this.P(entry, previousEntry)) {
        continue;
      }
      previousEntry = entry;
      flattenedStack.push(entry);
    }
    this.h = flattenedStack;
  }
  clear() {
    this.j = -1;
    this.m = -1;
    this.h.splice(0);
    for (const [, disposable] of this.c) {
      $Xc(disposable);
    }
    this.c.clear();
    for (const [, disposable] of this.f) {
      $Xc(disposable);
    }
    this.f.clear();
  }
  dispose() {
    super.dispose();
    this.clear();
  }
  //#endregion
  //#region Navigation
  canGoForward() {
    return this.h.length > this.j + 1;
  }
  async goForward() {
    const navigated = await this.R();
    if (navigated) {
      return;
    }
    if (!this.canGoForward()) {
      return;
    }
    this.U(this.j + 1);
    return this.W();
  }
  canGoBack() {
    return this.j > 0;
  }
  async goBack() {
    const navigated = await this.R();
    if (navigated) {
      return;
    }
    if (!this.canGoBack()) {
      return;
    }
    this.U(this.j - 1);
    return this.W();
  }
  async goPrevious() {
    const navigated = await this.R();
    if (navigated) {
      return;
    }
    if (this.m === -1) {
      return this.goBack();
    }
    this.U(this.m);
    return this.W();
  }
  canGoLast() {
    return this.h.length > 0;
  }
  async goLast() {
    if (!this.canGoLast()) {
      return;
    }
    this.U(this.h.length - 1);
    return this.W();
  }
  async R() {
    if (this.t === 0) {
      return false;
    }
    if (this.S()) {
      return false;
    }
    await this.W();
    return true;
  }
  S() {
    if (!this.s?.selection) {
      return false;
    }
    const pane = this.y.activeEditorPane;
    if (!$5K(pane)) {
      return false;
    }
    if (pane.group.id !== this.s.groupId) {
      return false;
    }
    if (!pane.input || !this.g.matchesEditor(pane.input, this.s.editor)) {
      return false;
    }
    const paneSelection = pane.getSelection();
    if (!paneSelection) {
      return false;
    }
    return paneSelection.compare(this.s.selection) === 1;
  }
  U(newIndex, skipEvent) {
    this.m = this.j;
    this.j = newIndex;
    if (!skipEvent) {
      this.b.fire();
    }
  }
  async W() {
    this.n = true;
    try {
      if (this.s) {
        await this.X(this.s);
      }
    } finally {
      this.n = false;
    }
  }
  X(location3) {
    let options3 = /* @__PURE__ */ Object.create(null);
    if (location3.selection) {
      options3 = location3.selection.restore(options3);
    }
    if ($dL(location3.editor)) {
      return this.y.openEditor(location3.editor, options3, location3.groupId);
    }
    return this.y.openEditor({
      ...location3.editor,
      options: {
        ...location3.editor.options,
        ...options3
      }
    }, location3.groupId);
  }
  isNavigating() {
    return this.n;
  }
};
$QVb = $QVb_1 = __decorate([
  __param(2, $Pk),
  __param(3, $mJ),
  __param(4, $iJ),
  __param(5, $wn)
], $QVb);
var EditorHelper = class EditorHelper2 {
  constructor(a, b, c, d) {
    this.a = a;
    this.b = b;
    this.c = c;
    this.d = d;
  }
  preferResourceEditorInput(editor) {
    const resource = $mL.getOriginalUri(editor);
    const hasValidResourceEditorInputScheme = resource?.scheme === Schemas.file || resource?.scheme === Schemas.vscodeRemote || resource?.scheme === Schemas.vscodeUserData || resource?.scheme === this.d.defaultUriScheme;
    if (hasValidResourceEditorInputScheme) {
      if ($dL(editor)) {
        const untypedInput = editor.toUntyped();
        if ($8K(untypedInput)) {
          return untypedInput;
        }
      }
      return editor;
    } else {
      return $dL(editor) ? editor : void 0;
    }
  }
  matchesEditor(arg1, inputB) {
    if (arg1 instanceof $Dm || arg1 instanceof $Cm) {
      if ($dL(inputB)) {
        return false;
      }
      if (arg1 instanceof $Dm) {
        return arg1.contains(
          inputB.resource,
          2
          /* FileChangeType.DELETED */
        );
      }
      return this.matchesFile(inputB.resource, arg1);
    }
    if ($dL(arg1)) {
      if ($dL(inputB)) {
        return arg1.matches(inputB);
      }
      return this.matchesFile(inputB.resource, arg1);
    }
    if ($dL(inputB)) {
      return this.matchesFile(arg1.resource, inputB);
    }
    return arg1 && inputB && this.a.extUri.isEqual(arg1.resource, inputB.resource);
  }
  matchesFile(resource, arg2) {
    if (arg2 instanceof $Dm) {
      return arg2.contains(
        resource,
        2
        /* FileChangeType.DELETED */
      );
    }
    if (arg2 instanceof $Cm) {
      return this.a.extUri.isEqualOrParent(resource, arg2.resource);
    }
    if ($dL(arg2)) {
      const inputResource = arg2.resource;
      if (!inputResource) {
        return false;
      }
      if (this.b.phase >= 3 && !this.c.hasProvider(inputResource)) {
        return false;
      }
      return this.a.extUri.isEqual(inputResource, resource);
    }
    return this.a.extUri.isEqual(arg2?.resource, resource);
  }
  matchesEditorIdentifier(identifier2, editorPane) {
    if (!editorPane?.group) {
      return false;
    }
    if (identifier2.groupId !== editorPane.group.id) {
      return false;
    }
    return editorPane.input ? identifier2.editor.matches(editorPane.input) : false;
  }
  onEditorDispose(editor, listener, mapEditorToDispose) {
    const toDispose = Event2.once(editor.onWillDispose)(() => listener());
    let disposables = mapEditorToDispose.get(editor);
    if (!disposables) {
      disposables = new $2c();
      mapEditorToDispose.set(editor, disposables);
    }
    disposables.add(toDispose);
  }
  clearOnEditorDispose(editor, mapEditorToDispose) {
    if (!$dL(editor)) {
      return;
    }
    const disposables = mapEditorToDispose.get(editor);
    if (disposables) {
      $Xc(disposables);
      mapEditorToDispose.delete(editor);
    }
  }
};
EditorHelper = __decorate([
  __param(0, $vl),
  __param(1, $KL),
  __param(2, $km),
  __param(3, $aT)
], EditorHelper);

// out-build/vs/workbench/services/activity/browser/activityService.js
var ViewContainerActivityByView = class ViewContainerActivityByView2 extends $3c {
  constructor(c, f, g) {
    super();
    this.c = c;
    this.f = f;
    this.g = g;
    this.a = void 0;
    this.b = $3c.None;
    this.B(Event2.filter(this.f.onDidChangeContainer, (e) => e.views.some((view) => view.id === c))(() => this.h()));
    this.B(Event2.filter(this.f.onDidChangeLocation, (e) => e.views.some((view) => view.id === c))(() => this.h()));
  }
  setActivity(activity) {
    this.a = activity;
    this.h();
  }
  clearActivity() {
    this.a = void 0;
    this.h();
  }
  h() {
    this.b.dispose();
    const container2 = this.f.getViewContainerByViewId(this.c);
    if (container2 && this.a) {
      this.b = this.g.showViewContainerActivity(container2.id, this.a);
    }
  }
  dispose() {
    this.b.dispose();
    super.dispose();
  }
};
ViewContainerActivityByView = __decorate([
  __param(1, $$M),
  __param(2, $vqb)
], ViewContainerActivityByView);
var $RVb = class $RVb2 extends $3c {
  constructor(g, h3) {
    super();
    this.g = g;
    this.h = h3;
    this.a = /* @__PURE__ */ new Map();
    this.b = this.B(new $ze());
    this.onDidChangeActivity = this.b.event;
    this.c = /* @__PURE__ */ new Map();
    this.f = /* @__PURE__ */ new Map();
  }
  showViewContainerActivity(viewContainerId, activity) {
    const viewContainer5 = this.g.getViewContainerById(viewContainerId);
    if (viewContainer5) {
      let activities = this.c.get(viewContainerId);
      if (!activities) {
        activities = [];
        this.c.set(viewContainerId, activities);
      }
      for (let i2 = 0; i2 <= activities.length; i2++) {
        if (i2 === activities.length || $Gg(activity.priority)) {
          activities.push(activity);
          break;
        } else if ($Gg(activities[i2].priority) || activities[i2].priority <= activity.priority) {
          activities.splice(i2, 0, activity);
          break;
        }
      }
      this.b.fire(viewContainer5);
      return $1c(() => {
        activities.splice(activities.indexOf(activity), 1);
        if (activities.length === 0) {
          this.c.delete(viewContainerId);
        }
        this.b.fire(viewContainer5);
      });
    }
    return $3c.None;
  }
  getViewContainerActivities(viewContainerId) {
    const viewContainer5 = this.g.getViewContainerById(viewContainerId);
    if (viewContainer5) {
      return this.c.get(viewContainerId) ?? [];
    }
    return [];
  }
  showViewActivity(viewId, activity) {
    let maybeItem = this.a.get(viewId);
    if (maybeItem) {
      maybeItem.id++;
    } else {
      maybeItem = {
        id: 1,
        activity: this.h.createInstance(ViewContainerActivityByView, viewId)
      };
      this.a.set(viewId, maybeItem);
    }
    const id2 = maybeItem.id;
    maybeItem.activity.setActivity(activity);
    const item = maybeItem;
    return $1c(() => {
      if (item.id === id2) {
        item.activity.dispose();
        this.a.delete(viewId);
      }
    });
  }
  showAccountsActivity(activity) {
    return this.j($Qzb, activity);
  }
  showGlobalActivity(activity) {
    return this.j($Pzb, activity);
  }
  getActivity(id2) {
    return this.f.get(id2) ?? [];
  }
  j(id2, activity) {
    let activities = this.f.get(id2);
    if (!activities) {
      activities = [];
      this.f.set(id2, activities);
    }
    activities.push(activity);
    this.b.fire(id2);
    return $1c(() => {
      activities.splice(activities.indexOf(activity), 1);
      if (activities.length === 0) {
        this.f.delete(id2);
      }
      this.b.fire(id2);
    });
  }
};
$RVb = __decorate([
  __param(0, $$M),
  __param(1, $Pk)
], $RVb);
$SC(
  $vqb,
  $RVb,
  1
  /* InstantiationType.Delayed */
);

// out-build/vs/base/common/keybindingParser.js
var $S3 = class {
  static a(input) {
    input = input.toLowerCase().trim();
    let ctrl = false;
    let shift = false;
    let alt = false;
    let meta = false;
    let matchedModifier;
    do {
      matchedModifier = false;
      if (/^ctrl(\+|\-)/.test(input)) {
        ctrl = true;
        input = input.substr("ctrl-".length);
        matchedModifier = true;
      }
      if (/^shift(\+|\-)/.test(input)) {
        shift = true;
        input = input.substr("shift-".length);
        matchedModifier = true;
      }
      if (/^alt(\+|\-)/.test(input)) {
        alt = true;
        input = input.substr("alt-".length);
        matchedModifier = true;
      }
      if (/^meta(\+|\-)/.test(input)) {
        meta = true;
        input = input.substr("meta-".length);
        matchedModifier = true;
      }
      if (/^win(\+|\-)/.test(input)) {
        meta = true;
        input = input.substr("win-".length);
        matchedModifier = true;
      }
      if (/^cmd(\+|\-)/.test(input)) {
        meta = true;
        input = input.substr("cmd-".length);
        matchedModifier = true;
      }
    } while (matchedModifier);
    let key2;
    const firstSpaceIdx = input.indexOf(" ");
    if (firstSpaceIdx > 0) {
      key2 = input.substring(0, firstSpaceIdx);
      input = input.substring(firstSpaceIdx);
    } else {
      key2 = input;
      input = "";
    }
    return {
      remains: input,
      ctrl,
      shift,
      alt,
      meta,
      key: key2
    };
  }
  static b(input) {
    const mods = this.a(input);
    const scanCodeMatch = mods.key.match(/^\[([^\]]+)\]$/);
    if (scanCodeMatch) {
      const strScanCode = scanCodeMatch[1];
      const scanCode = $8e.lowerCaseToEnum(strScanCode);
      return [new $cf(mods.ctrl, mods.shift, mods.alt, mods.meta, scanCode), mods.remains];
    }
    const keyCode = KeyCodeUtils.fromUserSettings(mods.key);
    return [new $bf(mods.ctrl, mods.shift, mods.alt, mods.meta, keyCode), mods.remains];
  }
  static parseKeybinding(input) {
    if (!input) {
      return null;
    }
    const chords = [];
    let chord;
    while (input.length > 0) {
      [chord, input] = this.b(input);
      chords.push(chord);
    }
    return chords.length > 0 ? new $df(chords) : null;
  }
};

// out-build/vs/platform/keybinding/common/keybindingResolver.js
var ResultKind;
(function(ResultKind2) {
  ResultKind2[ResultKind2["NoMatchingKb"] = 0] = "NoMatchingKb";
  ResultKind2[ResultKind2["MoreChordsNeeded"] = 1] = "MoreChordsNeeded";
  ResultKind2[ResultKind2["KbFound"] = 2] = "KbFound";
})(ResultKind || (ResultKind = {}));
var $Ry = {
  kind: 0
  /* ResultKind.NoMatchingKb */
};
var MoreChordsNeeded = {
  kind: 1
  /* ResultKind.MoreChordsNeeded */
};
function KbFound(commandId, commandArgs, isBubble) {
  return { kind: 2, commandId, commandArgs, isBubble };
}
var $Sy = class _$Sy {
  constructor(defaultKeybindings, overrides, log4) {
    this.c = log4;
    this.d = defaultKeybindings;
    this.f = /* @__PURE__ */ new Map();
    for (const defaultKeybinding of defaultKeybindings) {
      const command4 = defaultKeybinding.command;
      if (command4 && command4.charAt(0) !== "-") {
        this.f.set(command4, true);
      }
    }
    this.g = /* @__PURE__ */ new Map();
    this.h = /* @__PURE__ */ new Map();
    this.e = _$Sy.handleRemovals([].concat(defaultKeybindings).concat(overrides));
    for (let i2 = 0, len = this.e.length; i2 < len; i2++) {
      const k = this.e[i2];
      if (k.chords.length === 0) {
        continue;
      }
      const when = k.when?.substituteConstants();
      if (when && when.type === 0) {
        continue;
      }
      this.l(k.chords[0], k);
    }
  }
  static j(defaultKb, keypress, when) {
    if (keypress) {
      for (let i2 = 0; i2 < keypress.length; i2++) {
        if (keypress[i2] !== defaultKb.chords[i2]) {
          return false;
        }
      }
    }
    if (when && when.type !== 1) {
      if (!defaultKb.when) {
        return false;
      }
      if (!$9m(when, defaultKb.when)) {
        return false;
      }
    }
    return true;
  }
  /**
   * Looks for rules containing "-commandId" and removes them.
   */
  static handleRemovals(rules) {
    const removals = /* @__PURE__ */ new Map();
    for (let i2 = 0, len = rules.length; i2 < len; i2++) {
      const rule = rules[i2];
      if (rule.command && rule.command.charAt(0) === "-") {
        const command4 = rule.command.substring(1);
        if (!removals.has(command4)) {
          removals.set(command4, [rule]);
        } else {
          removals.get(command4).push(rule);
        }
      }
    }
    if (removals.size === 0) {
      return rules;
    }
    const result = [];
    for (let i2 = 0, len = rules.length; i2 < len; i2++) {
      const rule = rules[i2];
      if (!rule.command || rule.command.length === 0) {
        result.push(rule);
        continue;
      }
      if (rule.command.charAt(0) === "-") {
        continue;
      }
      const commandRemovals = removals.get(rule.command);
      if (!commandRemovals || !rule.isDefault) {
        result.push(rule);
        continue;
      }
      let isRemoved = false;
      for (const commandRemoval of commandRemovals) {
        const when = commandRemoval.when;
        if (this.j(rule, commandRemoval.chords, when)) {
          isRemoved = true;
          break;
        }
      }
      if (!isRemoved) {
        result.push(rule);
        continue;
      }
    }
    return result;
  }
  l(keypress, item) {
    const conflicts = this.g.get(keypress);
    if (typeof conflicts === "undefined") {
      this.g.set(keypress, [item]);
      this.m(item);
      return;
    }
    for (let i2 = conflicts.length - 1; i2 >= 0; i2--) {
      const conflict = conflicts[i2];
      if (conflict.command === item.command) {
        continue;
      }
      let isShorterKbPrefix = true;
      for (let i3 = 1; i3 < conflict.chords.length && i3 < item.chords.length; i3++) {
        if (conflict.chords[i3] !== item.chords[i3]) {
          isShorterKbPrefix = false;
          break;
        }
      }
      if (!isShorterKbPrefix) {
        continue;
      }
      if (_$Sy.whenIsEntirelyIncluded(conflict.when, item.when)) {
        this.n(conflict);
      }
    }
    conflicts.push(item);
    this.m(item);
  }
  m(item) {
    if (!item.command) {
      return;
    }
    let arr = this.h.get(item.command);
    if (typeof arr === "undefined") {
      arr = [item];
      this.h.set(item.command, arr);
    } else {
      arr.push(item);
    }
  }
  n(item) {
    if (!item.command) {
      return;
    }
    const arr = this.h.get(item.command);
    if (typeof arr === "undefined") {
      return;
    }
    for (let i2 = 0, len = arr.length; i2 < len; i2++) {
      if (arr[i2] === item) {
        arr.splice(i2, 1);
        return;
      }
    }
  }
  /**
   * Returns true if it is provable `a` implies `b`.
   */
  static whenIsEntirelyIncluded(a, b) {
    if (!b || b.type === 1) {
      return true;
    }
    if (!a || a.type === 1) {
      return false;
    }
    return $pn(a, b);
  }
  getDefaultBoundCommands() {
    return this.f;
  }
  getDefaultKeybindings() {
    return this.d;
  }
  getKeybindings() {
    return this.e;
  }
  lookupKeybindings(commandId) {
    const items = this.h.get(commandId);
    if (typeof items === "undefined" || items.length === 0) {
      return [];
    }
    const result = [];
    let resultLen = 0;
    for (let i2 = items.length - 1; i2 >= 0; i2--) {
      result[resultLen++] = items[i2];
    }
    return result;
  }
  lookupPrimaryKeybinding(commandId, context, enforceContextCheck = false) {
    const items = this.h.get(commandId);
    if (typeof items === "undefined" || items.length === 0) {
      return null;
    }
    if (items.length === 1 && !enforceContextCheck) {
      return items[0];
    }
    for (let i2 = items.length - 1; i2 >= 0; i2--) {
      const item = items[i2];
      if (context.contextMatchesRules(item.when)) {
        return item;
      }
    }
    if (enforceContextCheck) {
      return null;
    }
    return items[items.length - 1];
  }
  /**
   * Looks up a keybinding trigged as a result of pressing a sequence of chords - `[...currentChords, keypress]`
   *
   * Example: resolving 3 chords pressed sequentially - `cmd+k cmd+p cmd+i`:
   * 	`currentChords = [ 'cmd+k' , 'cmd+p' ]` and `keypress = `cmd+i` - last pressed chord
   */
  resolve(context, currentChords, keypress) {
    const pressedChords = [...currentChords, keypress];
    this.c(`| Resolving ${pressedChords}`);
    const kbCandidates = this.g.get(pressedChords[0]);
    if (kbCandidates === void 0) {
      this.c(`\\ No keybinding entries.`);
      return $Ry;
    }
    let lookupMap = null;
    if (pressedChords.length < 2) {
      lookupMap = kbCandidates;
    } else {
      lookupMap = [];
      for (let i2 = 0, len = kbCandidates.length; i2 < len; i2++) {
        const candidate = kbCandidates[i2];
        if (pressedChords.length > candidate.chords.length) {
          continue;
        }
        let prefixMatches = true;
        for (let i3 = 1; i3 < pressedChords.length; i3++) {
          if (candidate.chords[i3] !== pressedChords[i3]) {
            prefixMatches = false;
            break;
          }
        }
        if (prefixMatches) {
          lookupMap.push(candidate);
        }
      }
    }
    const result = this.o(context, lookupMap);
    if (!result) {
      this.c(`\\ From ${lookupMap.length} keybinding entries, no when clauses matched the context.`);
      return $Ry;
    }
    if (pressedChords.length < result.chords.length) {
      this.c(`\\ From ${lookupMap.length} keybinding entries, awaiting ${result.chords.length - pressedChords.length} more chord(s), when: ${printWhenExplanation(result.when)}, source: ${printSourceExplanation(result)}.`);
      return MoreChordsNeeded;
    }
    this.c(`\\ From ${lookupMap.length} keybinding entries, matched ${result.command}, when: ${printWhenExplanation(result.when)}, source: ${printSourceExplanation(result)}.`);
    return KbFound(result.command, result.commandArgs, result.bubble);
  }
  o(context, matches) {
    for (let i2 = matches.length - 1; i2 >= 0; i2--) {
      const k = matches[i2];
      if (!_$Sy.p(context, k.when)) {
        continue;
      }
      return k;
    }
    return null;
  }
  static p(context, rules) {
    if (!rules) {
      return true;
    }
    return rules.evaluate(context);
  }
};
function printWhenExplanation(when) {
  if (!when) {
    return `no when condition`;
  }
  return `${when.serialize()}`;
}
function printSourceExplanation(kb) {
  return kb.extensionId ? kb.isBuiltinExtension ? `built-in extension ${kb.extensionId}` : `user extension ${kb.extensionId}` : kb.isDefault ? `built-in` : `user`;
}

// out-build/vs/platform/keybinding/common/abstractKeybindingService.js
var HIGH_FREQ_COMMANDS = /^(cursor|delete|undo|redo|tab|editor\.action\.clipboard)/;
var $SVb = class extends $3c {
  get onDidUpdateKeybindings() {
    return this.a ? this.a.event : Event2.None;
  }
  get inChordMode() {
    return this.b.length > 0;
  }
  constructor(s, t, u, w, y) {
    super();
    this.s = s;
    this.t = t;
    this.u = u;
    this.w = w;
    this.y = y;
    this.a = this.B(new $ze());
    this.b = [];
    this.c = new $7h();
    this.f = null;
    this.g = KeybindingModifierSet.EMPTY;
    this.h = null;
    this.j = new $6h();
    this.m = null;
    this.n = false;
  }
  dispose() {
    super.dispose();
  }
  getDefaultKeybindingsContent() {
    return "";
  }
  toggleLogging() {
    this.n = !this.n;
    return this.n;
  }
  F(str) {
    if (this.n) {
      this.y.info(`[KeybindingService]: ${str}`);
    }
  }
  getDefaultKeybindings() {
    return this.z().getDefaultKeybindings();
  }
  getKeybindings() {
    return this.z().getKeybindings();
  }
  customKeybindingsCount() {
    return 0;
  }
  lookupKeybindings(commandId) {
    return $Mb(this.z().lookupKeybindings(commandId).map((item) => item.resolvedKeybinding));
  }
  lookupKeybinding(commandId, context, enforceContextCheck = false) {
    const result = this.z().lookupPrimaryKeybinding(commandId, context || this.s, enforceContextCheck);
    if (!result) {
      return void 0;
    }
    return result.resolvedKeybinding;
  }
  dispatchEvent(e, target) {
    return this.J(e, target);
  }
  // TODO@ulugbekna: update namings to align with `_doDispatch`
  // TODO@ulugbekna: this fn doesn't seem to take into account single-modifier keybindings, eg `shift shift`
  softDispatch(e, target) {
    this.F(`/ Soft dispatching keyboard event`);
    const keybinding = this.resolveKeyboardEvent(e);
    if (keybinding.hasMultipleChords()) {
      console.warn("keyboard event should not be mapped to multiple chords");
      return $Ry;
    }
    const [firstChord] = keybinding.getDispatchChords();
    if (firstChord === null) {
      this.F(`\\ Keyboard event cannot be dispatched`);
      return $Ry;
    }
    const contextValue = this.s.getContext(target);
    const currentChords = this.b.map(({ keypress }) => keypress);
    return this.z().resolve(contextValue, currentChords, firstChord);
  }
  G() {
    const chordLastInteractedTime = Date.now();
    this.c.cancelAndSet(() => {
      if (!this.D()) {
        this.I();
        return;
      }
      if (Date.now() - chordLastInteractedTime > 5e3) {
        this.I();
      }
    }, 500);
  }
  H(firstChord, keypressLabel) {
    this.b.push({ keypress: firstChord, label: keypressLabel });
    switch (this.b.length) {
      case 0:
        throw $ob("impossible");
      case 1:
        this.f = this.w.status(localize(1954, null, keypressLabel));
        break;
      default: {
        const fullKeypressLabel = this.b.map(({ label: label3 }) => label3).join(", ");
        this.f = this.w.status(localize(1955, null, fullKeypressLabel));
      }
    }
    this.G();
    if (IME.enabled) {
      IME.disable();
    }
  }
  I() {
    if (this.f) {
      this.f.dispose();
      this.f = null;
    }
    this.c.cancel();
    this.b = [];
    IME.enable();
  }
  dispatchByUserSettingsLabel(userSettingsLabel, target) {
    this.F(`/ Dispatching keybinding triggered via menu entry accelerator - ${userSettingsLabel}`);
    const keybindings = this.resolveUserBinding(userSettingsLabel);
    if (keybindings.length === 0) {
      this.F(`\\ Could not resolve - ${userSettingsLabel}`);
    } else {
      this.M(
        keybindings[0],
        target,
        /*isSingleModiferChord*/
        false
      );
    }
  }
  J(e, target) {
    return this.M(
      this.resolveKeyboardEvent(e),
      target,
      /*isSingleModiferChord*/
      false
    );
  }
  L(e, target) {
    const keybinding = this.resolveKeyboardEvent(e);
    const [singleModifier] = keybinding.getSingleModifierDispatchChords();
    if (singleModifier) {
      if (this.g.has(singleModifier)) {
        this.F(`+ Ignoring single modifier ${singleModifier} due to it being pressed together with other keys.`);
        this.g = KeybindingModifierSet.EMPTY;
        this.j.cancel();
        this.h = null;
        return false;
      }
      this.g = KeybindingModifierSet.EMPTY;
      if (this.h === null) {
        this.F(`+ Storing single modifier for possible chord ${singleModifier}.`);
        this.h = singleModifier;
        this.j.cancelAndSet(() => {
          this.F(`+ Clearing single modifier due to 300ms elapsed.`);
          this.h = null;
        }, 300);
        return false;
      }
      if (singleModifier === this.h) {
        this.F(`/ Dispatching single modifier chord ${singleModifier} ${singleModifier}`);
        this.j.cancel();
        this.h = null;
        return this.M(
          keybinding,
          target,
          /*isSingleModiferChord*/
          true
        );
      }
      this.F(`+ Clearing single modifier due to modifier mismatch: ${this.h} ${singleModifier}`);
      this.j.cancel();
      this.h = null;
      return false;
    }
    const [firstChord] = keybinding.getChords();
    this.g = new KeybindingModifierSet(firstChord);
    if (this.h !== null) {
      this.F(`+ Clearing single modifier due to other key up.`);
    }
    this.j.cancel();
    this.h = null;
    return false;
  }
  M(userKeypress, target, isSingleModiferChord = false) {
    let shouldPreventDefault = false;
    if (userKeypress.hasMultipleChords()) {
      console.warn("Unexpected keyboard event mapped to multiple chords");
      return false;
    }
    let userPressedChord = null;
    let currentChords = null;
    if (isSingleModiferChord) {
      const [dispatchKeyname] = userKeypress.getSingleModifierDispatchChords();
      userPressedChord = dispatchKeyname;
      currentChords = dispatchKeyname ? [dispatchKeyname] : [];
    } else {
      [userPressedChord] = userKeypress.getDispatchChords();
      currentChords = this.b.map(({ keypress }) => keypress);
    }
    if (userPressedChord === null) {
      this.F(`\\ Keyboard event cannot be dispatched in keydown phase.`);
      return shouldPreventDefault;
    }
    const contextValue = this.s.getContext(target);
    const keypressLabel = userKeypress.getLabel();
    const resolveResult = this.z().resolve(contextValue, currentChords, userPressedChord);
    switch (resolveResult.kind) {
      case 0: {
        this.y.trace("KeybindingService#dispatch", keypressLabel, `[ No matching keybinding ]`);
        if (this.inChordMode) {
          const currentChordsLabel = this.b.map(({ label: label3 }) => label3).join(", ");
          this.F(`+ Leaving multi-chord mode: Nothing bound to "${currentChordsLabel}, ${keypressLabel}".`);
          this.w.status(localize(1956, null, currentChordsLabel, keypressLabel), {
            hideAfter: 10 * 1e3
            /* 10s */
          });
          this.I();
          shouldPreventDefault = true;
        }
        return shouldPreventDefault;
      }
      case 1: {
        this.y.trace("KeybindingService#dispatch", keypressLabel, `[ Several keybindings match - more chords needed ]`);
        shouldPreventDefault = true;
        this.H(userPressedChord, keypressLabel);
        this.F(this.b.length === 1 ? `+ Entering multi-chord mode...` : `+ Continuing multi-chord mode...`);
        return shouldPreventDefault;
      }
      case 2: {
        this.y.trace("KeybindingService#dispatch", keypressLabel, `[ Will dispatch command ${resolveResult.commandId} ]`);
        if (resolveResult.commandId === null || resolveResult.commandId === "") {
          if (this.inChordMode) {
            const currentChordsLabel = this.b.map(({ label: label3 }) => label3).join(", ");
            this.F(`+ Leaving chord mode: Nothing bound to "${currentChordsLabel}, ${keypressLabel}".`);
            this.w.status(localize(1957, null, currentChordsLabel, keypressLabel), {
              hideAfter: 10 * 1e3
              /* 10s */
            });
            this.I();
            shouldPreventDefault = true;
          }
        } else {
          if (this.inChordMode) {
            this.I();
          }
          if (!resolveResult.isBubble) {
            shouldPreventDefault = true;
          }
          this.F(`+ Invoking command ${resolveResult.commandId}.`);
          this.m = resolveResult.commandId;
          try {
            if (typeof resolveResult.commandArgs === "undefined") {
              this.t.executeCommand(resolveResult.commandId).then(void 0, (err) => this.w.warn(err));
            } else {
              this.t.executeCommand(resolveResult.commandId, resolveResult.commandArgs).then(void 0, (err) => this.w.warn(err));
            }
          } finally {
            this.m = null;
          }
          if (!HIGH_FREQ_COMMANDS.test(resolveResult.commandId)) {
            this.u.publicLog2("workbenchActionExecuted", { id: resolveResult.commandId, from: "keybinding", detail: userKeypress.getUserSettingsLabel() ?? void 0 });
          }
        }
        return shouldPreventDefault;
      }
    }
  }
  mightProducePrintableCharacter(event) {
    if (event.ctrlKey || event.metaKey) {
      return false;
    }
    if (event.keyCode >= 31 && event.keyCode <= 56 || event.keyCode >= 21 && event.keyCode <= 30) {
      return true;
    }
    return false;
  }
};
var KeybindingModifierSet = class _KeybindingModifierSet {
  static {
    this.EMPTY = new _KeybindingModifierSet(null);
  }
  constructor(source) {
    this.a = source ? source.ctrlKey : false;
    this.b = source ? source.shiftKey : false;
    this.c = source ? source.altKey : false;
    this.d = source ? source.metaKey : false;
  }
  has(modifier) {
    switch (modifier) {
      case "ctrl":
        return this.a;
      case "shift":
        return this.b;
      case "alt":
        return this.c;
      case "meta":
        return this.d;
    }
  }
};

// out-build/vs/platform/keyboardLayout/common/keyboardLayout.js
var $Vy = $Qk("keyboardLayoutService");
function $Wy(a, b) {
  if (!a || !b) {
    return false;
  }
  if (a.name && b.name && a.name === b.name) {
    return true;
  }
  if (a.id && b.id && a.id === b.id) {
    return true;
  }
  if (a.model && b.model && a.model === b.model && a.layout === b.layout) {
    return true;
  }
  return false;
}
function $Xy(layout) {
  if (!layout) {
    return { label: "", description: "" };
  }
  if (layout.name) {
    const windowsLayout = layout;
    return {
      label: windowsLayout.text,
      description: ""
    };
  }
  if (layout.id) {
    const macLayout = layout;
    if (macLayout.localizedName) {
      return {
        label: macLayout.localizedName,
        description: ""
      };
    }
    if (/^com\.apple\.keylayout\./.test(macLayout.id)) {
      return {
        label: macLayout.id.replace(/^com\.apple\.keylayout\./, "").replace(/-/, " "),
        description: ""
      };
    }
    if (/^.*inputmethod\./.test(macLayout.id)) {
      return {
        label: macLayout.id.replace(/^.*inputmethod\./, "").replace(/[-\.]/, " "),
        description: `Input Method (${macLayout.lang})`
      };
    }
    return {
      label: macLayout.lang,
      description: ""
    };
  }
  const linuxLayout = layout;
  return {
    label: linuxLayout.layout,
    description: ""
  };
}
function $Yy(layout) {
  if (layout.name) {
    return layout.name;
  }
  if (layout.id) {
    return layout.id;
  }
  return layout.layout;
}

// out-build/vs/workbench/services/keybinding/common/keybindingIO.js
var $TVb = class {
  static writeKeybindingItem(out, item) {
    if (!item.resolvedKeybinding) {
      return;
    }
    const quotedSerializedKeybinding = JSON.stringify(item.resolvedKeybinding.getUserSettingsLabel());
    out.write(`{ "key": ${rightPaddedString(quotedSerializedKeybinding + ",", 25)} "command": `);
    const quotedSerializedWhen = item.when ? JSON.stringify(item.when.serialize()) : "";
    const quotedSerializeCommand = JSON.stringify(item.command);
    if (quotedSerializedWhen.length > 0) {
      out.write(`${quotedSerializeCommand},`);
      out.writeLine();
      out.write(`                                     "when": ${quotedSerializedWhen}`);
    } else {
      out.write(`${quotedSerializeCommand}`);
    }
    if (item.commandArgs) {
      out.write(",");
      out.writeLine();
      out.write(`                                     "args": ${JSON.stringify(item.commandArgs)}`);
    }
    out.write(" }");
  }
  static readUserKeybindingItem(input) {
    const keybinding = "key" in input && typeof input.key === "string" ? $S3.parseKeybinding(input.key) : null;
    const when = "when" in input && typeof input.when === "string" ? $7m.deserialize(input.when) : void 0;
    const command4 = "command" in input && typeof input.command === "string" ? input.command : null;
    const commandArgs = "args" in input && typeof input.args !== "undefined" ? input.args : void 0;
    return {
      keybinding,
      command: command4,
      commandArgs,
      when,
      _sourceKey: "key" in input && typeof input.key === "string" ? input.key : void 0
    };
  }
};
function rightPaddedString(str, minChars) {
  if (str.length < minChars) {
    return str + new Array(minChars - str.length).join(" ");
  }
  return str;
}
var $UVb = class {
  constructor() {
    this.a = [];
    this.b = "";
  }
  write(str) {
    this.b += str;
  }
  writeLine(str = "") {
    this.a.push(this.b + str);
    this.b = "";
  }
  toString() {
    this.writeLine();
    return this.a.join("\n");
  }
};

// out-build/vs/workbench/services/keybinding/browser/keybindingService.js
var $VVb_1;
function isValidContributedKeyBinding(keyBinding, rejects) {
  if (!keyBinding) {
    rejects.push(localize(12940, null));
    return false;
  }
  if (typeof keyBinding.command !== "string") {
    rejects.push(localize(12941, null, "command"));
    return false;
  }
  if (keyBinding.key && typeof keyBinding.key !== "string") {
    rejects.push(localize(12942, null, "key"));
    return false;
  }
  if (keyBinding.when && typeof keyBinding.when !== "string") {
    rejects.push(localize(12943, null, "when"));
    return false;
  }
  if (keyBinding.mac && typeof keyBinding.mac !== "string") {
    rejects.push(localize(12944, null, "mac"));
    return false;
  }
  if (keyBinding.linux && typeof keyBinding.linux !== "string") {
    rejects.push(localize(12945, null, "linux"));
    return false;
  }
  if (keyBinding.win && typeof keyBinding.win !== "string") {
    rejects.push(localize(12946, null, "win"));
    return false;
  }
  return true;
}
var keybindingType = {
  type: "object",
  default: { command: "", key: "" },
  properties: {
    command: {
      description: localize(12947, null),
      type: "string"
    },
    args: {
      description: localize(12948, null)
    },
    key: {
      description: localize(12949, null),
      type: "string"
    },
    mac: {
      description: localize(12950, null),
      type: "string"
    },
    linux: {
      description: localize(12951, null),
      type: "string"
    },
    win: {
      description: localize(12952, null),
      type: "string"
    },
    when: {
      description: localize(12953, null),
      type: "string"
    }
  }
};
var keybindingsExtPoint = $tN.registerExtensionPoint({
  extensionPoint: "keybindings",
  deps: [$dUb],
  jsonSchema: {
    description: localize(12954, null),
    oneOf: [
      keybindingType,
      {
        type: "array",
        items: keybindingType
      }
    ]
  }
});
var NUMPAD_PRINTABLE_SCANCODES = [
  90,
  91,
  92,
  93,
  95,
  96,
  97,
  98,
  99,
  100,
  101,
  102,
  103,
  104,
  105
  /* ScanCode.NumpadDecimal */
];
var otherMacNumpadMapping = /* @__PURE__ */ new Map();
otherMacNumpadMapping.set(
  95,
  22
  /* KeyCode.Digit1 */
);
otherMacNumpadMapping.set(
  96,
  23
  /* KeyCode.Digit2 */
);
otherMacNumpadMapping.set(
  97,
  24
  /* KeyCode.Digit3 */
);
otherMacNumpadMapping.set(
  98,
  25
  /* KeyCode.Digit4 */
);
otherMacNumpadMapping.set(
  99,
  26
  /* KeyCode.Digit5 */
);
otherMacNumpadMapping.set(
  100,
  27
  /* KeyCode.Digit6 */
);
otherMacNumpadMapping.set(
  101,
  28
  /* KeyCode.Digit7 */
);
otherMacNumpadMapping.set(
  102,
  29
  /* KeyCode.Digit8 */
);
otherMacNumpadMapping.set(
  103,
  30
  /* KeyCode.Digit9 */
);
otherMacNumpadMapping.set(
  104,
  21
  /* KeyCode.Digit0 */
);
var $VVb = $VVb_1 = class $VVb2 extends $SVb {
  constructor(contextKeyService, commandService, telemetryService, notificationService, userDataProfileService, S, extensionService, fileService, uriIdentityService, logService, U) {
    super(contextKeyService, commandService, telemetryService, notificationService, logService);
    this.S = S;
    this.U = U;
    this.Q = [];
    this.O = contextKeyService.createKey("isComposing", false);
    this.R = new KeybindingsJsonSchema();
    this.X();
    this.r = this.U.getKeyboardMapper();
    this.B(this.U.onDidChangeKeyboardLayout(() => {
      this.r = this.U.getKeyboardMapper();
      this.cb();
    }));
    this.P = null;
    this.C = null;
    this.N = this.B(new UserKeybindings(userDataProfileService, uriIdentityService, fileService, logService));
    this.N.initialize().then(() => {
      if (this.N.keybindings.length) {
        this.cb();
      }
    });
    this.B(this.N.onDidChange(() => {
      logService.debug("User keybindings changed");
      this.cb();
    }));
    keybindingsExtPoint.setHandler((extensions) => {
      const keybindings = [];
      for (const extension of extensions) {
        this.ib(extension.description.identifier, extension.description.isBuiltin, extension.value, extension.collector, keybindings);
      }
      $0I.setExtensionKeybindings(keybindings);
      this.cb();
    });
    this.X();
    this.B(extensionService.onDidRegisterExtensions(() => this.X()));
    this.B(Event2.runAndSubscribe(onDidRegisterWindow, ({ window: window3, disposables }) => disposables.add(this.W(window3)), { window: $Y, disposables: this.q }));
    this.B($Te((windowId) => {
      if (windowId !== $Y.vscodeWindowId) {
        return;
      }
      const keyboard = navigator.keyboard;
      if ($5e.keyboard === 2) {
        return;
      }
      if ($Se($Y)) {
        keyboard?.lock(["Escape"]);
      } else {
        keyboard?.unlock();
      }
      this.C = null;
      this.a.fire();
    }));
  }
  W(window3) {
    const disposables = new $2c();
    disposables.add($_i(window3, $7j.KEY_DOWN, (e) => {
      if (this.P) {
        return;
      }
      this.O.set(e.isComposing);
      const keyEvent = new $if(e);
      this.F(`/ Received  keydown event - ${$gf(e)}`);
      this.F(`| Converted keydown event - ${$hf(keyEvent)}`);
      const shouldPreventDefault = this.J(keyEvent, keyEvent.target);
      if (shouldPreventDefault) {
        keyEvent.preventDefault();
      }
      this.O.set(false);
    }));
    disposables.add($_i(window3, $7j.KEY_UP, (e) => {
      this.bb();
      this.O.set(e.isComposing);
      const keyEvent = new $if(e);
      const shouldPreventDefault = this.L(keyEvent, keyEvent.target);
      if (shouldPreventDefault) {
        keyEvent.preventDefault();
      }
      this.O.set(false);
    }));
    return disposables;
  }
  registerSchemaContribution(contribution) {
    this.Q.push(contribution);
    if (contribution.onDidChange) {
      this.B(contribution.onDidChange(() => this.X()));
    }
    this.X();
  }
  X() {
    this.R.updateSchema(this.Q.flatMap((x) => x.getSchemaAdditions()));
  }
  Y(keybinding) {
    return $12.toLabel(OS, keybinding.chords, (chord) => {
      if (chord instanceof $bf) {
        return KeyCodeUtils.toString(chord.keyCode);
      }
      return $8e.toString(chord.scanCode);
    }) || "[null]";
  }
  Z(resolvedKeybinding) {
    return resolvedKeybinding.getDispatchChords().map((x) => x || "[null]").join(" ");
  }
  $(output, input, resolvedKeybindings) {
    const padLength = 35;
    const firstRow = `${input.padStart(padLength, " ")} => `;
    if (resolvedKeybindings.length === 0) {
      output.push(`${firstRow}${"[NO BINDING]".padStart(padLength, " ")}`);
      return;
    }
    const firstRowIndentation = firstRow.length;
    const isFirst = true;
    for (const resolvedKeybinding of resolvedKeybindings) {
      if (isFirst) {
        output.push(`${firstRow}${this.Z(resolvedKeybinding).padStart(padLength, " ")}`);
      } else {
        output.push(`${" ".repeat(firstRowIndentation)}${this.Z(resolvedKeybinding).padStart(padLength, " ")}`);
      }
    }
  }
  ab() {
    const seenBindings = /* @__PURE__ */ new Set();
    const result = [];
    result.push(`Default Resolved Keybindings (unique only):`);
    for (const item of $0I.getDefaultKeybindings()) {
      if (!item.keybinding) {
        continue;
      }
      const input = this.Y(item.keybinding);
      if (seenBindings.has(input)) {
        continue;
      }
      seenBindings.add(input);
      const resolvedKeybindings = this.r.resolveKeybinding(item.keybinding);
      this.$(result, input, resolvedKeybindings);
    }
    result.push(`User Resolved Keybindings (unique only):`);
    for (const item of this.N.keybindings) {
      if (!item.keybinding) {
        continue;
      }
      const input = item._sourceKey ?? "Impossible: missing source key, but has keybinding";
      if (seenBindings.has(input)) {
        continue;
      }
      seenBindings.add(input);
      const resolvedKeybindings = this.r.resolveKeybinding(item.keybinding);
      this.$(result, input, resolvedKeybindings);
    }
    return result.join("\n");
  }
  _dumpDebugInfo() {
    const layoutInfo = JSON.stringify(this.U.getCurrentKeyboardLayout(), null, "	");
    const mapperInfo = this.r.dumpDebugInfo();
    const resolvedKeybindings = this.ab();
    const rawMapping = JSON.stringify(this.U.getRawKeyboardMapping(), null, "	");
    return `Layout info:
${layoutInfo}

${resolvedKeybindings}

${mapperInfo}

Raw mapping:
${rawMapping}`;
  }
  _dumpDebugInfoJSON() {
    const info = {
      layout: this.U.getCurrentKeyboardLayout(),
      rawMapping: this.U.getRawKeyboardMapping()
    };
    return JSON.stringify(info, null, "	");
  }
  enableKeybindingHoldMode(commandId) {
    if (this.m !== commandId) {
      return void 0;
    }
    this.P = new $gi();
    const focusTracker = $_j(getWindow(void 0));
    const listener = focusTracker.onDidBlur(() => this.bb());
    this.P.p.finally(() => {
      listener.dispose();
      focusTracker.dispose();
    });
    this.F(`+ Enabled hold-mode for ${commandId}.`);
    return this.P.p;
  }
  bb() {
    if (this.P) {
      this.P?.complete();
      this.P = null;
    }
  }
  customKeybindingsCount() {
    return this.N.keybindings.length;
  }
  cb() {
    this.C = null;
    this.a.fire();
  }
  z() {
    if (!this.C) {
      const defaults = this.fb($0I.getDefaultKeybindings(), true);
      const overrides = this.gb(this.N.keybindings, false);
      this.C = new $Sy(defaults, overrides, (str) => this.F(str));
    }
    return this.C;
  }
  D() {
    return this.S.hasFocus;
  }
  fb(items, isDefault) {
    const result = [];
    let resultLen = 0;
    for (const item of items) {
      const when = item.when || void 0;
      const keybinding = item.keybinding;
      if (!keybinding) {
        result[resultLen++] = new $Py(void 0, item.command, item.commandArgs, when, isDefault, item.extensionId, item.isBuiltinExtension);
      } else {
        if (this.hb(keybinding)) {
          continue;
        }
        const resolvedKeybindings = this.r.resolveKeybinding(keybinding);
        for (let i2 = resolvedKeybindings.length - 1; i2 >= 0; i2--) {
          const resolvedKeybinding = resolvedKeybindings[i2];
          result[resultLen++] = new $Py(resolvedKeybinding, item.command, item.commandArgs, when, isDefault, item.extensionId, item.isBuiltinExtension);
        }
      }
    }
    return result;
  }
  gb(items, isDefault) {
    const result = [];
    let resultLen = 0;
    for (const item of items) {
      const when = item.when || void 0;
      if (!item.keybinding) {
        result[resultLen++] = new $Py(void 0, item.command, item.commandArgs, when, isDefault, null, false);
      } else {
        const resolvedKeybindings = this.r.resolveKeybinding(item.keybinding);
        for (const resolvedKeybinding of resolvedKeybindings) {
          result[resultLen++] = new $Py(resolvedKeybinding, item.command, item.commandArgs, when, isDefault, null, false);
        }
      }
    }
    return result;
  }
  hb(keybinding) {
    if ($5e.keyboard === 0) {
      return false;
    }
    if ($5e.keyboard === 1 && $Se($Y)) {
      return false;
    }
    for (const chord of keybinding.chords) {
      if (!chord.metaKey && !chord.altKey && !chord.ctrlKey && !chord.shiftKey) {
        continue;
      }
      const modifiersMask = 2048 | 512 | 1024;
      let partModifiersMask = 0;
      if (chord.metaKey) {
        partModifiersMask |= 2048;
      }
      if (chord.shiftKey) {
        partModifiersMask |= 1024;
      }
      if (chord.altKey) {
        partModifiersMask |= 512;
      }
      if (chord.ctrlKey && OS === 2) {
        partModifiersMask |= 256;
      }
      if ((partModifiersMask & modifiersMask) === (2048 | 512)) {
        if (chord instanceof $cf && (chord.scanCode === 86 || chord.scanCode === 85)) {
          return true;
        }
        if (chord instanceof $bf && (chord.keyCode === 15 || chord.keyCode === 17)) {
          return true;
        }
      }
      if ((partModifiersMask & modifiersMask) === 2048) {
        if (chord instanceof $cf && (chord.scanCode >= 36 && chord.scanCode <= 45)) {
          return true;
        }
        if (chord instanceof $bf && (chord.keyCode >= 21 && chord.keyCode <= 30)) {
          return true;
        }
      }
    }
    return false;
  }
  resolveKeybinding(kb) {
    return this.r.resolveKeybinding(kb);
  }
  resolveKeyboardEvent(keyboardEvent) {
    this.U.validateCurrentKeyboardMapping(keyboardEvent);
    return this.r.resolveKeyboardEvent(keyboardEvent);
  }
  resolveUserBinding(userBinding) {
    const keybinding = $S3.parseKeybinding(userBinding);
    return keybinding ? this.r.resolveKeybinding(keybinding) : [];
  }
  ib(extensionId, isBuiltin, keybindings, collector, result) {
    if (Array.isArray(keybindings)) {
      for (let i2 = 0, len = keybindings.length; i2 < len; i2++) {
        this.jb(extensionId, isBuiltin, i2 + 1, keybindings[i2], collector, result);
      }
    } else {
      this.jb(extensionId, isBuiltin, 1, keybindings, collector, result);
    }
  }
  jb(extensionId, isBuiltin, idx, keybindings, collector, result) {
    const rejects = [];
    if (isValidContributedKeyBinding(keybindings, rejects)) {
      const rule = this.mb(extensionId, isBuiltin, idx++, keybindings);
      if (rule) {
        result.push(rule);
      }
    }
    if (rejects.length > 0) {
      collector.error(localize(12955, null, keybindingsExtPoint.name, rejects.join("\n")));
    }
  }
  static lb(key2, mac, linux, win) {
    if (OS === 1 && win) {
      if (win) {
        return win;
      }
    } else if (OS === 2) {
      if (mac) {
        return mac;
      }
    } else {
      if (linux) {
        return linux;
      }
    }
    return key2;
  }
  mb(extensionId, isBuiltin, idx, binding) {
    const { command: command4, args: args2, when, key: key2, mac, linux, win } = binding;
    const keybinding = $VVb_1.lb(key2, mac, linux, win);
    if (!keybinding) {
      return void 0;
    }
    let weight5;
    if (isBuiltin) {
      weight5 = 300 + idx;
    } else {
      weight5 = 400 + idx;
    }
    const commandAction = $dJ.getCommand(command4);
    const precondition2 = commandAction && commandAction.precondition;
    let fullWhen;
    if (when && precondition2) {
      fullWhen = $7m.and(precondition2, $7m.deserialize(when));
    } else if (when) {
      fullWhen = $7m.deserialize(when);
    } else if (precondition2) {
      fullWhen = precondition2;
    }
    const desc = {
      id: command4,
      args: args2,
      when: fullWhen,
      weight: weight5,
      keybinding: $S3.parseKeybinding(keybinding),
      extensionId: extensionId.value,
      isBuiltinExtension: isBuiltin
    };
    return desc;
  }
  getDefaultKeybindingsContent() {
    const resolver = this.z();
    const defaultKeybindings = resolver.getDefaultKeybindings();
    const boundCommands = resolver.getDefaultBoundCommands();
    return $VVb_1.nb(defaultKeybindings) + "\n\n" + $VVb_1.ob(boundCommands);
  }
  static nb(defaultKeybindings) {
    const out = new $UVb();
    out.writeLine("[");
    const lastIndex = defaultKeybindings.length - 1;
    defaultKeybindings.forEach((k, index) => {
      $TVb.writeKeybindingItem(out, k);
      if (index !== lastIndex) {
        out.writeLine(",");
      } else {
        out.writeLine();
      }
    });
    out.writeLine("]");
    return out.toString();
  }
  static ob(boundCommands) {
    const unboundCommands = $AVb(boundCommands);
    const pretty2 = unboundCommands.sort().join("\n// - ");
    return "// " + localize(12956, null) + "\n// - " + pretty2;
  }
  mightProducePrintableCharacter(event) {
    if (event.ctrlKey || event.metaKey || event.altKey) {
      return false;
    }
    const code = $8e.toEnum(event.code);
    if (NUMPAD_PRINTABLE_SCANCODES.indexOf(code) !== -1) {
      if (event.keyCode === $9e[code]) {
        return true;
      }
      if ($m && event.keyCode === otherMacNumpadMapping.get(code)) {
        return true;
      }
      return false;
    }
    const keycode = $9e[code];
    if (keycode !== -1) {
      return false;
    }
    const mapping2 = this.U.getRawKeyboardMapping();
    if (!mapping2) {
      return false;
    }
    const keyInfo = mapping2[event.code];
    if (!keyInfo) {
      return false;
    }
    if (!keyInfo.value || /\s/.test(keyInfo.value)) {
      return false;
    }
    return true;
  }
};
$VVb = $VVb_1 = __decorate([
  __param(0, $on),
  __param(1, $sn),
  __param(2, $zv),
  __param(3, $PJ),
  __param(4, $gT),
  __param(5, $S4),
  __param(6, $wN),
  __param(7, $km),
  __param(8, $vl),
  __param(9, $wn),
  __param(10, $Vy)
], $VVb);
var UserKeybindings = class extends $3c {
  get keybindings() {
    return this.b;
  }
  constructor(h3, j, m, logService) {
    super();
    this.h = h3;
    this.j = j;
    this.m = m;
    this.a = [];
    this.b = [];
    this.f = this.B(new $2c());
    this.g = this.B(new $ze());
    this.onDidChange = this.g.event;
    this.r();
    this.c = this.B(new $8h(() => this.s().then((changed) => {
      if (changed) {
        this.g.fire();
      }
    }), 50));
    this.B(Event2.filter(this.m.onDidFilesChange, (e) => e.contains(this.h.currentProfile.keybindingsResource))(() => {
      logService.debug("Keybindings file changed");
      this.c.schedule();
    }));
    this.B(this.m.onDidRunOperation((e) => {
      if (e.operation === 4 && e.resource.toString() === this.h.currentProfile.keybindingsResource.toString()) {
        logService.debug("Keybindings file written");
        this.c.schedule();
      }
    }));
    this.B(h3.onDidChangeCurrentProfile((e) => {
      if (!this.j.extUri.isEqual(e.previous.keybindingsResource, e.profile.keybindingsResource)) {
        e.join(this.n());
      }
    }));
  }
  async n() {
    this.r();
    this.c.schedule();
  }
  r() {
    this.f.clear();
    this.f.add(this.m.watch($uh(this.h.currentProfile.keybindingsResource)));
    this.f.add(this.m.watch(this.h.currentProfile.keybindingsResource));
  }
  async initialize() {
    await this.s();
  }
  async s() {
    const newKeybindings = await this.t();
    if ($Pv(this.a, newKeybindings)) {
      return false;
    }
    this.a = newKeybindings;
    this.b = this.a.map((k) => $TVb.readUserKeybindingItem(k));
    return true;
  }
  async t() {
    try {
      const content = await this.m.readFile(this.h.currentProfile.keybindingsResource);
      const value = $yw(content.value.toString());
      return Array.isArray(value) ? value.filter(
        (v) => v && typeof v === "object"
        /* just typeof === object doesn't catch `null` */
      ) : [];
    } catch (e) {
      return [];
    }
  }
};
var KeybindingsJsonSchema = class _KeybindingsJsonSchema {
  static {
    this.a = "vscode://schemas/keybindings";
  }
  constructor() {
    this.b = [];
    this.c = [];
    this.d = [];
    this.f = [];
    this.g = {
      id: _KeybindingsJsonSchema.a,
      type: "array",
      title: localize(12957, null),
      allowTrailingCommas: true,
      allowComments: true,
      definitions: {
        "editorGroupsSchema": {
          "type": "array",
          "items": {
            "type": "object",
            "properties": {
              "groups": {
                "$ref": "#/definitions/editorGroupsSchema",
                "default": [{}, {}]
              },
              "size": {
                "type": "number",
                "default": 0.5
              }
            }
          }
        },
        "commandNames": {
          "type": "string",
          "enum": this.c,
          "enumDescriptions": this.f,
          "description": localize(12958, null)
        },
        "commandType": {
          "anyOf": [
            {
              $ref: "#/definitions/commandNames"
            },
            {
              "type": "string",
              "enum": this.d,
              "enumDescriptions": this.f,
              "description": localize(12959, null)
            },
            {
              "type": "string"
            }
          ]
        },
        "commandsSchemas": {
          "allOf": this.b
        }
      },
      items: {
        "required": ["key"],
        "type": "object",
        "defaultSnippets": [{ "body": { "key": "$1", "command": "$2", "when": "$3" } }],
        "properties": {
          "key": {
            "type": "string",
            "description": localize(12960, null)
          },
          "command": {
            "anyOf": [
              {
                "if": {
                  "type": "array"
                },
                "then": {
                  "not": {
                    "type": "array"
                  },
                  "errorMessage": localize(12961, null, "string")
                },
                "else": {
                  "$ref": "#/definitions/commandType"
                }
              },
              {
                "$ref": "#/definitions/commandType"
              }
            ]
          },
          "when": {
            "type": "string",
            "description": localize(12962, null)
          },
          "args": {
            "description": localize(12963, null)
          }
        },
        "$ref": "#/definitions/commandsSchemas"
      }
    };
    this.h = $Wn.as($Xn.JSONContribution);
    this.h.registerSchema(_KeybindingsJsonSchema.a, this.g);
  }
  // TODO@ulugbekna: can updates happen incrementally rather than rebuilding; concerns:
  // - is just appending additional schemas enough for the registry to pick them up?
  // - can `CommandsRegistry.getCommands` and `MenuRegistry.getCommands` return different values at different times? ie would just pushing new schemas from `additionalContributions` not be enough?
  updateSchema(additionalContributions) {
    this.b.length = 0;
    this.c.length = 0;
    this.d.length = 0;
    this.f.length = 0;
    const knownCommands = /* @__PURE__ */ new Set();
    const addKnownCommand = (commandId, description) => {
      if (!/^_/.test(commandId)) {
        if (!knownCommands.has(commandId)) {
          knownCommands.add(commandId);
          this.c.push(commandId);
          this.f.push($un(description) ? description.value : description);
          this.d.push(`-${commandId}`);
        }
      }
    };
    const allCommands = $tn.getCommands();
    for (const [commandId, command4] of allCommands) {
      const commandMetadata = command4.metadata;
      addKnownCommand(commandId, commandMetadata?.description ?? $dJ.getCommand(commandId)?.title);
      if (!commandMetadata || !commandMetadata.args || commandMetadata.args.length !== 1 || !commandMetadata.args[0].schema) {
        continue;
      }
      const argsSchema2 = commandMetadata.args[0].schema;
      const argsRequired = typeof commandMetadata.args[0].isOptional !== "undefined" ? !commandMetadata.args[0].isOptional : Array.isArray(argsSchema2.required) && argsSchema2.required.length > 0;
      const addition = {
        "if": {
          "required": ["command"],
          "properties": {
            "command": { "const": commandId }
          }
        },
        "then": {
          "required": [].concat(argsRequired ? ["args"] : []),
          "properties": {
            "args": argsSchema2
          }
        }
      };
      this.b.push(addition);
    }
    const menuCommands = $dJ.getCommands();
    for (const commandId of menuCommands.keys()) {
      addKnownCommand(commandId);
    }
    this.b.push(...additionalContributions);
    this.h.notifySchemaChanged(_KeybindingsJsonSchema.a);
  }
};
$SC(
  $Ty,
  $VVb,
  0
  /* InstantiationType.Eager */
);

// out-build/vs/workbench/services/textresourceProperties/common/textResourcePropertiesService.js
var $WVb = class $WVb2 {
  constructor(b, remoteAgentService, c, d) {
    this.b = b;
    this.c = c;
    this.d = d;
    this.a = null;
    remoteAgentService.getEnvironment().then((remoteEnv) => this.a = remoteEnv);
  }
  getEOL(resource, language) {
    const eol = this.b.getValue("files.eol", { overrideIdentifier: language, resource });
    if (eol && typeof eol === "string" && eol !== "auto") {
      return eol;
    }
    const os = this.e(resource);
    return os === 3 || os === 2 ? "\n" : "\r\n";
  }
  e(resource) {
    let os = OS;
    const remoteAuthority = this.c.remoteAuthority;
    if (remoteAuthority) {
      if (resource && resource.scheme !== Schemas.file) {
        const osCacheKey = `resource.authority.os.${remoteAuthority}`;
        os = this.a ? this.a.os : (
          /* Get it from cache */
          this.d.getNumber(osCacheKey, 1, OS)
        );
        this.d.store(
          osCacheKey,
          os,
          1,
          1
          /* StorageTarget.MACHINE */
        );
      }
    }
    return os;
  }
};
$WVb = __decorate([
  __param(0, $kl),
  __param(1, $RL),
  __param(2, $US),
  __param(3, $jv)
], $WVb);
$SC(
  $AG,
  $WVb,
  1
  /* InstantiationType.Delayed */
);

// out-build/vs/workbench/services/model/common/modelService.js
var $XVb = class $XVb2 extends $BGb {
  constructor(configurationService, resourcePropertiesService, undoRedoService, Q, instantiationService) {
    super(configurationService, resourcePropertiesService, undoRedoService, instantiationService);
    this.Q = Q;
  }
  M(resource) {
    return super.M(resource) || resource.scheme === this.Q.defaultUriScheme;
  }
};
$XVb = __decorate([
  __param(0, $kl),
  __param(1, $AG),
  __param(2, $_F),
  __param(3, $aT),
  __param(4, $Pk)
], $XVb);
$SC(
  $sG,
  $XVb,
  1
  /* InstantiationType.Delayed */
);

// out-build/vs/workbench/services/commands/common/commandService.js
var $YVb = class $YVb2 extends $3c {
  constructor(g, h3, j) {
    super();
    this.g = g;
    this.h = h3;
    this.j = j;
    this.a = false;
    this.c = this.B(new $ze());
    this.onWillExecuteCommand = this.c.event;
    this.f = new $ze();
    this.onDidExecuteCommand = this.f.event;
    this.h.whenInstalledExtensionsRegistered().then((value) => this.a = value);
    this.b = null;
  }
  m() {
    if (!this.b) {
      this.b = Promise.race([
        this.h.activateByEvent(`*`),
        $Wh(3e4)
      ]);
    }
    return this.b;
  }
  async executeCommand(id2, ...args2) {
    this.j.trace("CommandService#executeCommand", id2);
    const activationEvent = `onCommand:${id2}`;
    const commandIsRegistered = !!$tn.getCommand(id2);
    if (commandIsRegistered) {
      if (this.h.activationEventIsDone(activationEvent)) {
        return this.n(id2, args2);
      }
      if (!this.a) {
        this.h.activateByEvent(activationEvent);
        return this.n(id2, args2);
      }
      await this.h.activateByEvent(activationEvent);
      return this.n(id2, args2);
    }
    await Promise.all([
      this.h.activateByEvent(activationEvent),
      Promise.race([
        // race * activation against command registration
        this.m(),
        Event2.toPromise(Event2.filter($tn.onDidRegisterCommand, (e) => e === id2))
      ])
    ]);
    return this.n(id2, args2);
  }
  n(id2, args2) {
    const command4 = $tn.getCommand(id2);
    if (!command4) {
      return Promise.reject(new Error(`command '${id2}' not found`));
    }
    try {
      this.c.fire({ commandId: id2, args: args2 });
      const result = this.g.invokeFunction(command4.handler, ...args2);
      this.f.fire({ commandId: id2, args: args2 });
      return Promise.resolve(result);
    } catch (err) {
      return Promise.reject(err);
    }
  }
};
$YVb = __decorate([
  __param(0, $Pk),
  __param(1, $wN),
  __param(2, $wn)
], $YVb);
$SC(
  $sn,
  $YVb,
  1
  /* InstantiationType.Delayed */
);

// out-build/vs/workbench/services/themes/common/themeCompatibility.js
var settingToColorIdMapping = {};
function addSettingMapping(settingId, colorId) {
  let colorIds = settingToColorIdMapping[settingId];
  if (!colorIds) {
    settingToColorIdMapping[settingId] = colorIds = [];
  }
  colorIds.push(colorId);
}
function $GGb(oldSettings, result) {
  for (const rule of oldSettings) {
    result.textMateRules.push(rule);
    if (!rule.scope) {
      const settings = rule.settings;
      if (!settings) {
        rule.settings = {};
      } else {
        for (const settingKey in settings) {
          const key2 = settingKey;
          const mappings = settingToColorIdMapping[key2];
          if (mappings) {
            const colorHex = settings[key2];
            if (typeof colorHex === "string") {
              const color2 = $Vn.fromHex(colorHex);
              for (const colorId of mappings) {
                result.colors[colorId] = color2;
              }
            }
          }
          if (key2 !== "foreground" && key2 !== "background" && key2 !== "fontStyle") {
            delete settings[key2];
          }
        }
      }
    }
  }
}
addSettingMapping("background", $Ko);
addSettingMapping("foreground", $Lo);
addSettingMapping("selection", $7o);
addSettingMapping("inactiveSelection", $9o);
addSettingMapping("selectionHighlightColor", $0o);
addSettingMapping("findMatchHighlight", $cp);
addSettingMapping("currentFindMatchHighlight", $ap);
addSettingMapping("hoverHighlight", $ip);
addSettingMapping("wordHighlight", "editor.wordHighlightBackground");
addSettingMapping("wordHighlightStrong", "editor.wordHighlightStrongBackground");
addSettingMapping("findRangeHighlight", $ep);
addSettingMapping("findMatchHighlight", "peekViewResult.matchHighlightBackground");
addSettingMapping("referenceHighlight", "peekViewEditor.matchHighlightBackground");
addSettingMapping("lineHighlight", $LG);
addSettingMapping("rangeHighlight", $NG);
addSettingMapping("caret", $RG);
addSettingMapping("invisibles", $XG);
addSettingMapping("guide", $2G);
addSettingMapping("activeGuide", $8G);
var ansiColorMap = [
  "ansiBlack",
  "ansiRed",
  "ansiGreen",
  "ansiYellow",
  "ansiBlue",
  "ansiMagenta",
  "ansiCyan",
  "ansiWhite",
  "ansiBrightBlack",
  "ansiBrightRed",
  "ansiBrightGreen",
  "ansiBrightYellow",
  "ansiBrightBlue",
  "ansiBrightMagenta",
  "ansiBrightCyan",
  "ansiBrightWhite"
];
for (const color2 of ansiColorMap) {
  addSettingMapping(color2, "terminal." + color2);
}

// out-build/vs/workbench/services/themes/common/plistParser.js
var ChCode;
(function(ChCode2) {
  ChCode2[ChCode2["BOM"] = 65279] = "BOM";
  ChCode2[ChCode2["SPACE"] = 32] = "SPACE";
  ChCode2[ChCode2["TAB"] = 9] = "TAB";
  ChCode2[ChCode2["CARRIAGE_RETURN"] = 13] = "CARRIAGE_RETURN";
  ChCode2[ChCode2["LINE_FEED"] = 10] = "LINE_FEED";
  ChCode2[ChCode2["SLASH"] = 47] = "SLASH";
  ChCode2[ChCode2["LESS_THAN"] = 60] = "LESS_THAN";
  ChCode2[ChCode2["QUESTION_MARK"] = 63] = "QUESTION_MARK";
  ChCode2[ChCode2["EXCLAMATION_MARK"] = 33] = "EXCLAMATION_MARK";
})(ChCode || (ChCode = {}));
var State8;
(function(State14) {
  State14[State14["ROOT_STATE"] = 0] = "ROOT_STATE";
  State14[State14["DICT_STATE"] = 1] = "DICT_STATE";
  State14[State14["ARR_STATE"] = 2] = "ARR_STATE";
})(State8 || (State8 = {}));
function $HGb(content) {
  return _parse(content, null, null);
}
function _parse(content, filename, locationKeyName) {
  const len = content.length;
  let pos = 0;
  let line = 1;
  let char = 0;
  if (len > 0 && content.charCodeAt(0) === 65279) {
    pos = 1;
  }
  function advancePosBy(by) {
    if (locationKeyName === null) {
      pos = pos + by;
    } else {
      while (by > 0) {
        const chCode = content.charCodeAt(pos);
        if (chCode === 10) {
          pos++;
          line++;
          char = 0;
        } else {
          pos++;
          char++;
        }
        by--;
      }
    }
  }
  function advancePosTo(to) {
    if (locationKeyName === null) {
      pos = to;
    } else {
      advancePosBy(to - pos);
    }
  }
  function skipWhitespace() {
    while (pos < len) {
      const chCode = content.charCodeAt(pos);
      if (chCode !== 32 && chCode !== 9 && chCode !== 13 && chCode !== 10) {
        break;
      }
      advancePosBy(1);
    }
  }
  function advanceIfStartsWith(str) {
    if (content.substr(pos, str.length) === str) {
      advancePosBy(str.length);
      return true;
    }
    return false;
  }
  function advanceUntil(str) {
    const nextOccurence = content.indexOf(str, pos);
    if (nextOccurence !== -1) {
      advancePosTo(nextOccurence + str.length);
    } else {
      advancePosTo(len);
    }
  }
  function captureUntil(str) {
    const nextOccurence = content.indexOf(str, pos);
    if (nextOccurence !== -1) {
      const r2 = content.substring(pos, nextOccurence);
      advancePosTo(nextOccurence + str.length);
      return r2;
    } else {
      const r2 = content.substr(pos);
      advancePosTo(len);
      return r2;
    }
  }
  let state = 0;
  let cur = null;
  const stateStack = [];
  const objStack = [];
  let curKey = null;
  function pushState(newState, newCur) {
    stateStack.push(state);
    objStack.push(cur);
    state = newState;
    cur = newCur;
  }
  function popState() {
    if (stateStack.length === 0) {
      return fail("illegal state stack");
    }
    state = stateStack.pop();
    cur = objStack.pop();
  }
  function fail(msg) {
    throw new Error("Near offset " + pos + ": " + msg + " ~~~" + content.substr(pos, 50) + "~~~");
  }
  const dictState = {
    enterDict: function() {
      if (curKey === null) {
        return fail("missing <key>");
      }
      const newDict = {};
      if (locationKeyName !== null) {
        newDict[locationKeyName] = {
          filename,
          line,
          char
        };
      }
      cur[curKey] = newDict;
      curKey = null;
      pushState(1, newDict);
    },
    enterArray: function() {
      if (curKey === null) {
        return fail("missing <key>");
      }
      const newArr = [];
      cur[curKey] = newArr;
      curKey = null;
      pushState(2, newArr);
    }
  };
  const arrState = {
    enterDict: function() {
      const newDict = {};
      if (locationKeyName !== null) {
        newDict[locationKeyName] = {
          filename,
          line,
          char
        };
      }
      cur.push(newDict);
      pushState(1, newDict);
    },
    enterArray: function() {
      const newArr = [];
      cur.push(newArr);
      pushState(2, newArr);
    }
  };
  function enterDict() {
    if (state === 1) {
      dictState.enterDict();
    } else if (state === 2) {
      arrState.enterDict();
    } else {
      cur = {};
      if (locationKeyName !== null) {
        cur[locationKeyName] = {
          filename,
          line,
          char
        };
      }
      pushState(1, cur);
    }
  }
  function leaveDict() {
    if (state === 1) {
      popState();
    } else if (state === 2) {
      return fail("unexpected </dict>");
    } else {
      return fail("unexpected </dict>");
    }
  }
  function enterArray() {
    if (state === 1) {
      dictState.enterArray();
    } else if (state === 2) {
      arrState.enterArray();
    } else {
      cur = [];
      pushState(2, cur);
    }
  }
  function leaveArray() {
    if (state === 1) {
      return fail("unexpected </array>");
    } else if (state === 2) {
      popState();
    } else {
      return fail("unexpected </array>");
    }
  }
  function acceptKey(val) {
    if (state === 1) {
      if (curKey !== null) {
        return fail("too many <key>");
      }
      curKey = val;
    } else if (state === 2) {
      return fail("unexpected <key>");
    } else {
      return fail("unexpected <key>");
    }
  }
  function acceptString(val) {
    if (state === 1) {
      if (curKey === null) {
        return fail("missing <key>");
      }
      cur[curKey] = val;
      curKey = null;
    } else if (state === 2) {
      cur.push(val);
    } else {
      cur = val;
    }
  }
  function acceptReal(val) {
    if (isNaN(val)) {
      return fail("cannot parse float");
    }
    if (state === 1) {
      if (curKey === null) {
        return fail("missing <key>");
      }
      cur[curKey] = val;
      curKey = null;
    } else if (state === 2) {
      cur.push(val);
    } else {
      cur = val;
    }
  }
  function acceptInteger(val) {
    if (isNaN(val)) {
      return fail("cannot parse integer");
    }
    if (state === 1) {
      if (curKey === null) {
        return fail("missing <key>");
      }
      cur[curKey] = val;
      curKey = null;
    } else if (state === 2) {
      cur.push(val);
    } else {
      cur = val;
    }
  }
  function acceptDate(val) {
    if (state === 1) {
      if (curKey === null) {
        return fail("missing <key>");
      }
      cur[curKey] = val;
      curKey = null;
    } else if (state === 2) {
      cur.push(val);
    } else {
      cur = val;
    }
  }
  function acceptData(val) {
    if (state === 1) {
      if (curKey === null) {
        return fail("missing <key>");
      }
      cur[curKey] = val;
      curKey = null;
    } else if (state === 2) {
      cur.push(val);
    } else {
      cur = val;
    }
  }
  function acceptBool(val) {
    if (state === 1) {
      if (curKey === null) {
        return fail("missing <key>");
      }
      cur[curKey] = val;
      curKey = null;
    } else if (state === 2) {
      cur.push(val);
    } else {
      cur = val;
    }
  }
  function escapeVal(str) {
    return str.replace(/&#([0-9]+);/g, function(_, m0) {
      return String.fromCodePoint(parseInt(m0, 10));
    }).replace(/&#x([0-9a-f]+);/g, function(_, m0) {
      return String.fromCodePoint(parseInt(m0, 16));
    }).replace(/&amp;|&lt;|&gt;|&quot;|&apos;/g, function(_) {
      switch (_) {
        case "&amp;":
          return "&";
        case "&lt;":
          return "<";
        case "&gt;":
          return ">";
        case "&quot;":
          return '"';
        case "&apos;":
          return "'";
      }
      return _;
    });
  }
  function parseOpenTag() {
    let r2 = captureUntil(">");
    let isClosed = false;
    if (r2.charCodeAt(r2.length - 1) === 47) {
      isClosed = true;
      r2 = r2.substring(0, r2.length - 1);
    }
    return {
      name: r2.trim(),
      isClosed
    };
  }
  function parseTagValue(tag2) {
    if (tag2.isClosed) {
      return "";
    }
    const val = captureUntil("</");
    advanceUntil(">");
    return escapeVal(val);
  }
  while (pos < len) {
    skipWhitespace();
    if (pos >= len) {
      break;
    }
    const chCode = content.charCodeAt(pos);
    advancePosBy(1);
    if (chCode !== 60) {
      return fail("expected <");
    }
    if (pos >= len) {
      return fail("unexpected end of input");
    }
    const peekChCode = content.charCodeAt(pos);
    if (peekChCode === 63) {
      advancePosBy(1);
      advanceUntil("?>");
      continue;
    }
    if (peekChCode === 33) {
      advancePosBy(1);
      if (advanceIfStartsWith("--")) {
        advanceUntil("-->");
        continue;
      }
      advanceUntil(">");
      continue;
    }
    if (peekChCode === 47) {
      advancePosBy(1);
      skipWhitespace();
      if (advanceIfStartsWith("plist")) {
        advanceUntil(">");
        continue;
      }
      if (advanceIfStartsWith("dict")) {
        advanceUntil(">");
        leaveDict();
        continue;
      }
      if (advanceIfStartsWith("array")) {
        advanceUntil(">");
        leaveArray();
        continue;
      }
      return fail("unexpected closed tag");
    }
    const tag2 = parseOpenTag();
    switch (tag2.name) {
      case "dict":
        enterDict();
        if (tag2.isClosed) {
          leaveDict();
        }
        continue;
      case "array":
        enterArray();
        if (tag2.isClosed) {
          leaveArray();
        }
        continue;
      case "key":
        acceptKey(parseTagValue(tag2));
        continue;
      case "string":
        acceptString(parseTagValue(tag2));
        continue;
      case "real":
        acceptReal(parseFloat(parseTagValue(tag2)));
        continue;
      case "integer":
        acceptInteger(parseInt(parseTagValue(tag2), 10));
        continue;
      case "date":
        acceptDate(new Date(parseTagValue(tag2)));
        continue;
      case "data":
        acceptData(parseTagValue(tag2));
        continue;
      case "true":
        parseTagValue(tag2);
        acceptBool(true);
        continue;
      case "false":
        parseTagValue(tag2);
        acceptBool(false);
        continue;
    }
    if (/^plist/.test(tag2.name)) {
      continue;
    }
    return fail("unexpected opened tag " + tag2.name);
  }
  return cur;
}

// out-build/vs/workbench/services/themes/common/textMateScopeMatcher.js
function $IGb(selector, matchesName, results) {
  const tokenizer = newTokenizer(selector);
  let token = tokenizer.next();
  while (token !== null) {
    let priority = 0;
    if (token.length === 2 && token.charAt(1) === ":") {
      switch (token.charAt(0)) {
        case "R":
          priority = 1;
          break;
        case "L":
          priority = -1;
          break;
        default:
          console.log(`Unknown priority ${token} in scope selector`);
      }
      token = tokenizer.next();
    }
    const matcher = parseConjunction();
    if (matcher) {
      results.push({ matcher, priority });
    }
    if (token !== ",") {
      break;
    }
    token = tokenizer.next();
  }
  function parseOperand() {
    if (token === "-") {
      token = tokenizer.next();
      const expressionToNegate = parseOperand();
      if (!expressionToNegate) {
        return null;
      }
      return (matcherInput) => {
        const score2 = expressionToNegate(matcherInput);
        return score2 < 0 ? 0 : -1;
      };
    }
    if (token === "(") {
      token = tokenizer.next();
      const expressionInParents = parseInnerExpression();
      if (token === ")") {
        token = tokenizer.next();
      }
      return expressionInParents;
    }
    if (isIdentifier(token)) {
      const identifiers2 = [];
      do {
        identifiers2.push(token);
        token = tokenizer.next();
      } while (isIdentifier(token));
      return (matcherInput) => matchesName(identifiers2, matcherInput);
    }
    return null;
  }
  function parseConjunction() {
    let matcher = parseOperand();
    if (!matcher) {
      return null;
    }
    const matchers = [];
    while (matcher) {
      matchers.push(matcher);
      matcher = parseOperand();
    }
    return (matcherInput) => {
      let min = matchers[0](matcherInput);
      for (let i2 = 1; min >= 0 && i2 < matchers.length; i2++) {
        min = Math.min(min, matchers[i2](matcherInput));
      }
      return min;
    };
  }
  function parseInnerExpression() {
    let matcher = parseConjunction();
    if (!matcher) {
      return null;
    }
    const matchers = [];
    while (matcher) {
      matchers.push(matcher);
      if (token === "|" || token === ",") {
        do {
          token = tokenizer.next();
        } while (token === "|" || token === ",");
      } else {
        break;
      }
      matcher = parseConjunction();
    }
    return (matcherInput) => {
      let max = matchers[0](matcherInput);
      for (let i2 = 1; i2 < matchers.length; i2++) {
        max = Math.max(max, matchers[i2](matcherInput));
      }
      return max;
    };
  }
}
function isIdentifier(token) {
  return !!token && !!token.match(/[\w\.:]+/);
}
function newTokenizer(input) {
  const regex = /([LR]:|[\w\.:][\w\.:\-]*|[\,\|\-\(\)])/g;
  let match = regex.exec(input);
  return {
    next: () => {
      if (!match) {
        return null;
      }
      const res = match[0];
      match = regex.exec(input);
      return res;
    }
  };
}

// out-build/vs/editor/common/languages/supports/tokenization.js
var STANDARD_TOKEN_TYPE_REGEXP = /\b(comment|string|regex|regexp)\b/;
function $YGb(tokenType) {
  const m = tokenType.match(STANDARD_TOKEN_TYPE_REGEXP);
  if (!m) {
    return 0;
  }
  switch (m[1]) {
    case "comment":
      return 1;
    case "string":
      return 2;
    case "regex":
      return 3;
    case "regexp":
      return 3;
  }
  throw new Error("Unexpected match for standard token type!");
}
function $4Gb(colorMap) {
  const rules = [];
  for (let i2 = 1, len = colorMap.length; i2 < len; i2++) {
    const color2 = colorMap[i2];
    rules[i2] = `.mtk${i2} { color: ${color2}; }`;
  }
  rules.push(".mtki { font-style: italic; }");
  rules.push(".mtkb { font-weight: bold; }");
  rules.push(".mtku { text-decoration: underline; text-underline-position: under; }");
  rules.push(".mtks { text-decoration: line-through; }");
  rules.push(".mtks.mtku { text-decoration: underline line-through; text-underline-position: under; }");
  return rules.join("\n");
}

// out-build/vs/workbench/services/themes/common/colorThemeData.js
var colorRegistry3 = $Wn.as($3n.ColorContribution);
var tokenClassificationRegistry3 = $Llb();
var tokenGroupToScopesMap = {
  comments: ["comment", "punctuation.definition.comment"],
  strings: ["string", "meta.embedded.assembly"],
  keywords: ["keyword - keyword.operator", "keyword.control", "storage", "storage.type"],
  numbers: ["constant.numeric"],
  types: ["entity.name.type", "entity.name.class", "support.type", "support.class"],
  functions: ["entity.name.function", "support.function"],
  variables: ["variable", "entity.name.variable"]
};
var $5Gb = class _$5Gb {
  static {
    this.STORAGE_KEY = "colorThemeData";
  }
  constructor(id2, label3, settingsId) {
    this.h = [];
    this.j = [];
    this.l = {};
    this.m = {};
    this.n = [];
    this.o = [];
    this.t = void 0;
    this.u = void 0;
    this.id = id2;
    this.label = label3;
    this.settingsId = settingsId;
    this.isLoaded = false;
  }
  get semanticHighlighting() {
    if (this.c !== void 0) {
      return this.c;
    }
    if (this.g !== void 0) {
      return this.g;
    }
    return !!this.b;
  }
  get tokenColors() {
    if (!this.t) {
      let addRule2 = function(rule) {
        if (rule.scope && rule.settings) {
          if (rule.scope === "token.info-token") {
            hasDefaultTokens = true;
          }
          result.push({ scope: rule.scope, settings: { foreground: normalizeColor(rule.settings.foreground), background: normalizeColor(rule.settings.background), fontStyle: rule.settings.fontStyle } });
        }
      };
      var addRule = addRule2;
      const result = [];
      const foreground = this.getColor($Lo) || this.getDefault($Lo);
      const background = this.getColor($Ko) || this.getDefault($Ko);
      result.push({
        settings: {
          foreground: normalizeColor(foreground),
          background: normalizeColor(background)
        }
      });
      let hasDefaultTokens = false;
      this.h.forEach(addRule2);
      this.j.forEach(addRule2);
      if (!hasDefaultTokens) {
        defaultThemeColors[this.type].forEach(addRule2);
      }
      this.t = result;
    }
    return this.t;
  }
  getColor(colorId, useDefault) {
    const customColor = this.m[colorId];
    if (customColor instanceof $Vn) {
      return customColor;
    }
    if (customColor === void 0) {
      const color2 = this.l[colorId];
      if (color2 !== void 0) {
        return color2;
      }
    }
    if (useDefault !== false) {
      return this.getDefault(colorId);
    }
    return void 0;
  }
  v(type, modifiers, language, useDefault = true, definitions3 = {}) {
    const result = {
      foreground: void 0,
      bold: void 0,
      underline: void 0,
      strikethrough: void 0,
      italic: void 0
    };
    const score2 = {
      foreground: -1,
      bold: -1,
      underline: -1,
      strikethrough: -1,
      italic: -1
    };
    function _processStyle(matchScore, style, definition) {
      if (style.foreground && score2.foreground <= matchScore) {
        score2.foreground = matchScore;
        result.foreground = style.foreground;
        definitions3.foreground = definition;
      }
      for (const p of ["bold", "underline", "strikethrough", "italic"]) {
        const property = p;
        const info = style[property];
        if (info !== void 0) {
          if (score2[property] <= matchScore) {
            score2[property] = matchScore;
            result[property] = info;
            definitions3[property] = definition;
          }
        }
      }
    }
    function _processSemanticTokenRule(rule) {
      const matchScore = rule.selector.match(type, modifiers, language);
      if (matchScore >= 0) {
        _processStyle(matchScore, rule.style, rule);
      }
    }
    this.n.forEach(_processSemanticTokenRule);
    this.o.forEach(_processSemanticTokenRule);
    let hasUndefinedStyleProperty = false;
    for (const k in score2) {
      const key2 = k;
      if (score2[key2] === -1) {
        hasUndefinedStyleProperty = true;
      } else {
        score2[key2] = Number.MAX_VALUE;
      }
    }
    if (hasUndefinedStyleProperty) {
      for (const rule of tokenClassificationRegistry3.getTokenStylingDefaultRules()) {
        const matchScore = rule.selector.match(type, modifiers, language);
        if (matchScore >= 0) {
          let style;
          if (rule.defaults.scopesToProbe) {
            style = this.resolveScopes(rule.defaults.scopesToProbe);
            if (style) {
              _processStyle(matchScore, style, rule.defaults.scopesToProbe);
            }
          }
          if (!style && useDefault !== false) {
            const tokenStyleValue = rule.defaults[this.type];
            style = this.resolveTokenStyleValue(tokenStyleValue);
            if (style) {
              _processStyle(matchScore, style, tokenStyleValue);
            }
          }
        }
      }
    }
    return $Jlb.fromData(result);
  }
  /**
   * @param tokenStyleValue Resolve a tokenStyleValue in the context of a theme
   */
  resolveTokenStyleValue(tokenStyleValue) {
    if (tokenStyleValue === void 0) {
      return void 0;
    } else if (typeof tokenStyleValue === "string") {
      const { type, modifiers, language } = $Klb(tokenStyleValue, "");
      return this.v(type, modifiers, language);
    } else if (typeof tokenStyleValue === "object") {
      return tokenStyleValue;
    }
    return void 0;
  }
  getTokenColorIndex() {
    if (!this.u) {
      const index = new TokenColorIndex();
      this.tokenColors.forEach((rule) => {
        index.add(rule.settings.foreground);
        index.add(rule.settings.background);
      });
      this.n.forEach((r2) => index.add(r2.style.foreground));
      tokenClassificationRegistry3.getTokenStylingDefaultRules().forEach((r2) => {
        const defaultColor2 = r2.defaults[this.type];
        if (defaultColor2 && typeof defaultColor2 === "object") {
          index.add(defaultColor2.foreground);
        }
      });
      this.o.forEach((r2) => index.add(r2.style.foreground));
      this.u = index;
    }
    return this.u;
  }
  get tokenColorMap() {
    return this.getTokenColorIndex().asArray();
  }
  getTokenStyleMetadata(typeWithLanguage, modifiers, defaultLanguage, useDefault = true, definitions3 = {}) {
    const { type, language } = $Klb(typeWithLanguage, defaultLanguage);
    const style = this.v(type, modifiers, language, useDefault, definitions3);
    if (!style) {
      return void 0;
    }
    return {
      foreground: this.getTokenColorIndex().get(style.foreground),
      bold: style.bold,
      underline: style.underline,
      strikethrough: style.strikethrough,
      italic: style.italic
    };
  }
  getTokenStylingRuleScope(rule) {
    if (this.o.indexOf(rule) !== -1) {
      return "setting";
    }
    if (this.n.indexOf(rule) !== -1) {
      return "theme";
    }
    return void 0;
  }
  getDefault(colorId) {
    return colorRegistry3.resolveDefaultColor(colorId, this);
  }
  resolveScopes(scopes, definitions3) {
    if (!this.q) {
      this.q = this.h.map(getScopeMatcher);
    }
    if (!this.s) {
      this.s = this.j.map(getScopeMatcher);
    }
    for (const scope of scopes) {
      let findTokenStyleForScopeInScopes2 = function(scopeMatchers, themingRules) {
        for (let i2 = 0; i2 < scopeMatchers.length; i2++) {
          const score2 = scopeMatchers[i2](scope);
          if (score2 >= 0) {
            const themingRule = themingRules[i2];
            const settings = themingRules[i2].settings;
            if (score2 >= foregroundScore && settings.foreground) {
              foreground = settings.foreground;
              foregroundScore = score2;
              foregroundThemingRule = themingRule;
            }
            if (score2 >= fontStyleScore && $zg(settings.fontStyle)) {
              fontStyle = settings.fontStyle;
              fontStyleScore = score2;
              fontStyleThemingRule = themingRule;
            }
          }
        }
      };
      var findTokenStyleForScopeInScopes = findTokenStyleForScopeInScopes2;
      let foreground = void 0;
      let fontStyle = void 0;
      let foregroundScore = -1;
      let fontStyleScore = -1;
      let fontStyleThemingRule = void 0;
      let foregroundThemingRule = void 0;
      findTokenStyleForScopeInScopes2(this.q, this.h);
      findTokenStyleForScopeInScopes2(this.s, this.j);
      if (foreground !== void 0 || fontStyle !== void 0) {
        if (definitions3) {
          definitions3.foreground = foregroundThemingRule;
          definitions3.bold = definitions3.italic = definitions3.underline = definitions3.strikethrough = fontStyleThemingRule;
          definitions3.scope = scope;
        }
        return $Jlb.fromSettings(foreground, fontStyle);
      }
    }
    return void 0;
  }
  defines(colorId) {
    const customColor = this.m[colorId];
    if (customColor instanceof $Vn) {
      return true;
    }
    return customColor === void 0 && this.l.hasOwnProperty(colorId);
  }
  setCustomizations(settings) {
    this.setCustomColors(settings.colorCustomizations);
    this.setCustomTokenColors(settings.tokenColorCustomizations);
    this.setCustomSemanticTokenColors(settings.semanticTokenColorCustomizations);
  }
  setCustomColors(colors) {
    this.m = {};
    this.w(colors);
    const themeSpecificColors = this.getThemeSpecificColors(colors);
    if ($Bg(themeSpecificColors)) {
      this.w(themeSpecificColors);
    }
    this.u = void 0;
    this.t = void 0;
    this.s = void 0;
  }
  w(colors) {
    for (const id2 in colors) {
      const colorVal = colors[id2];
      if (colorVal === $4n) {
        this.m[id2] = $4n;
      } else if (typeof colorVal === "string") {
        this.m[id2] = $Vn.fromHex(colorVal);
      }
    }
  }
  setCustomTokenColors(customTokenColors) {
    this.j = [];
    this.g = void 0;
    this.y(customTokenColors);
    const themeSpecificTokenColors = this.getThemeSpecificColors(customTokenColors);
    if ($Bg(themeSpecificTokenColors)) {
      this.y(themeSpecificTokenColors);
    }
    this.u = void 0;
    this.t = void 0;
    this.s = void 0;
  }
  setCustomSemanticTokenColors(semanticTokenColors) {
    this.o = [];
    this.c = void 0;
    if (semanticTokenColors) {
      this.c = semanticTokenColors.enabled;
      if (semanticTokenColors.rules) {
        this.x(semanticTokenColors.rules);
      }
      const themeSpecificColors = this.getThemeSpecificColors(semanticTokenColors);
      if ($Bg(themeSpecificColors)) {
        if (themeSpecificColors.enabled !== void 0) {
          this.c = themeSpecificColors.enabled;
        }
        if (themeSpecificColors.rules) {
          this.x(themeSpecificColors.rules);
        }
      }
    }
    this.u = void 0;
    this.t = void 0;
  }
  isThemeScope(key2) {
    return key2.charAt(0) === $wwb && key2.charAt(key2.length - 1) === $xwb;
  }
  isThemeScopeMatch(themeId) {
    const themeIdFirstChar = themeId.charAt(0);
    const themeIdLastChar = themeId.charAt(themeId.length - 1);
    const themeIdPrefix = themeId.slice(0, -1);
    const themeIdInfix = themeId.slice(1, -1);
    const themeIdSuffix = themeId.slice(1);
    return themeId === this.settingsId || this.settingsId.includes(themeIdInfix) && themeIdFirstChar === $ywb && themeIdLastChar === $ywb || this.settingsId.startsWith(themeIdPrefix) && themeIdLastChar === $ywb || this.settingsId.endsWith(themeIdSuffix) && themeIdFirstChar === $ywb;
  }
  getThemeSpecificColors(colors) {
    let themeSpecificColors;
    for (const key2 in colors) {
      const scopedColors = colors[key2];
      if (this.isThemeScope(key2) && scopedColors instanceof Object && !Array.isArray(scopedColors)) {
        const themeScopeList = key2.match($zwb) || [];
        for (const themeScope of themeScopeList) {
          const themeId = themeScope.substring(1, themeScope.length - 1);
          if (this.isThemeScopeMatch(themeId)) {
            if (!themeSpecificColors) {
              themeSpecificColors = {};
            }
            const scopedThemeSpecificColors = scopedColors;
            for (const subkey in scopedThemeSpecificColors) {
              const originalColors = themeSpecificColors[subkey];
              const overrideColors = scopedThemeSpecificColors[subkey];
              if (Array.isArray(originalColors) && Array.isArray(overrideColors)) {
                themeSpecificColors[subkey] = originalColors.concat(overrideColors);
              } else if (overrideColors) {
                themeSpecificColors[subkey] = overrideColors;
              }
            }
          }
        }
      }
    }
    return themeSpecificColors;
  }
  x(tokenStylingRuleSection) {
    for (const key2 in tokenStylingRuleSection) {
      if (!this.isThemeScope(key2)) {
        try {
          const rule = readSemanticTokenRule(key2, tokenStylingRuleSection[key2]);
          if (rule) {
            this.o.push(rule);
          }
        } catch (e) {
        }
      }
    }
  }
  y(customTokenColors) {
    for (const tokenGroup in tokenGroupToScopesMap) {
      const group2 = tokenGroup;
      const value = customTokenColors[group2];
      if (value) {
        const settings = typeof value === "string" ? { foreground: value } : value;
        const scopes = tokenGroupToScopesMap[group2];
        for (const scope of scopes) {
          this.j.push({ scope, settings });
        }
      }
    }
    if (Array.isArray(customTokenColors.textMateRules)) {
      for (const rule of customTokenColors.textMateRules) {
        if (rule.scope && rule.settings) {
          this.j.push(rule);
        }
      }
    }
    if (customTokenColors.semanticHighlighting !== void 0) {
      this.g = customTokenColors.semanticHighlighting;
    }
  }
  ensureLoaded(extensionResourceLoaderService) {
    return !this.isLoaded ? this.z(extensionResourceLoaderService) : Promise.resolve(void 0);
  }
  reload(extensionResourceLoaderService) {
    return this.z(extensionResourceLoaderService);
  }
  z(extensionResourceLoaderService) {
    if (!this.location) {
      return Promise.resolve(void 0);
    }
    this.h = [];
    this.clearCaches();
    const result = {
      colors: {},
      textMateRules: [],
      semanticTokenRules: [],
      semanticHighlighting: false
    };
    return _loadColorTheme(extensionResourceLoaderService, this.location, result).then((_) => {
      this.isLoaded = true;
      this.n = result.semanticTokenRules;
      this.l = result.colors;
      this.h = result.textMateRules;
      this.b = result.semanticHighlighting;
    });
  }
  clearCaches() {
    this.u = void 0;
    this.t = void 0;
    this.q = void 0;
    this.s = void 0;
  }
  toStorage(storageService) {
    const colorMapData = {};
    for (const key2 in this.l) {
      colorMapData[key2] = $Vn.Format.CSS.formatHexA(this.l[key2], true);
    }
    const value = JSON.stringify({
      id: this.id,
      label: this.label,
      settingsId: this.settingsId,
      themeTokenColors: this.h.map((tc) => ({ settings: tc.settings, scope: tc.scope })),
      // don't persist names
      semanticTokenRules: this.n.map(SemanticTokenRule.toJSONObject),
      extensionData: ExtensionData.toJSONObject(this.extensionData),
      themeSemanticHighlighting: this.b,
      colorMap: colorMapData,
      watch: this.watch
    });
    storageService.store(
      _$5Gb.STORAGE_KEY,
      value,
      0,
      0
      /* StorageTarget.USER */
    );
  }
  get baseTheme() {
    return this.classNames[0];
  }
  get classNames() {
    return this.id.split(" ");
  }
  get type() {
    switch (this.baseTheme) {
      case $swb:
        return ColorScheme.LIGHT;
      case $uwb:
        return ColorScheme.HIGH_CONTRAST_DARK;
      case $vwb:
        return ColorScheme.HIGH_CONTRAST_LIGHT;
      default:
        return ColorScheme.DARK;
    }
  }
  // constructors
  static createUnloadedThemeForThemeType(themeType, colorMap) {
    return _$5Gb.createUnloadedTheme($ks(themeType), colorMap);
  }
  static createUnloadedTheme(id2, colorMap) {
    const themeData = new _$5Gb(id2, "", "__" + id2);
    themeData.isLoaded = false;
    themeData.h = [];
    themeData.watch = false;
    if (colorMap) {
      for (const id3 in colorMap) {
        themeData.l[id3] = $Vn.fromHex(colorMap[id3]);
      }
    }
    return themeData;
  }
  static createLoadedEmptyTheme(id2, settingsId) {
    const themeData = new _$5Gb(id2, "", settingsId);
    themeData.isLoaded = true;
    themeData.h = [];
    themeData.watch = false;
    return themeData;
  }
  static fromStorageData(storageService) {
    const input = storageService.get(
      _$5Gb.STORAGE_KEY,
      0
      /* StorageScope.PROFILE */
    );
    if (!input) {
      return void 0;
    }
    try {
      const data = JSON.parse(input);
      const theme = new _$5Gb("", "", "");
      for (const key2 in data) {
        switch (key2) {
          case "colorMap": {
            const colorMapData = data[key2];
            for (const id2 in colorMapData) {
              theme.l[id2] = $Vn.fromHex(colorMapData[id2]);
            }
            break;
          }
          case "themeTokenColors":
          case "id":
          case "label":
          case "settingsId":
          case "watch":
          case "themeSemanticHighlighting":
            theme[key2] = data[key2];
            break;
          case "semanticTokenRules": {
            const rulesData = data[key2];
            if (Array.isArray(rulesData)) {
              for (const d of rulesData) {
                const rule = SemanticTokenRule.fromJSONObject(tokenClassificationRegistry3, d);
                if (rule) {
                  theme.n.push(rule);
                }
              }
            }
            break;
          }
          case "location":
            break;
          case "extensionData":
            theme.extensionData = ExtensionData.fromJSONObject(data.extensionData);
            break;
        }
      }
      if (!theme.id || !theme.settingsId) {
        return void 0;
      }
      return theme;
    } catch (e) {
      return void 0;
    }
  }
  static fromExtensionTheme(theme, colorThemeLocation, extensionData) {
    const baseTheme = theme["uiTheme"] || "vs-dark";
    const themeSelector = toCSSSelector(extensionData.extensionId, theme.path);
    const id2 = `${baseTheme} ${themeSelector}`;
    const label3 = theme.label || $rc(theme.path);
    const settingsId = theme.id || label3;
    const themeData = new _$5Gb(id2, label3, settingsId);
    themeData.description = theme.description;
    themeData.watch = theme._watch === true;
    themeData.location = colorThemeLocation;
    themeData.extensionData = extensionData;
    themeData.isLoaded = false;
    return themeData;
  }
};
function toCSSSelector(extensionId, path) {
  if (path.startsWith("./")) {
    path = path.substr(2);
  }
  let str = `${extensionId}-${path}`;
  str = str.replace(/[^_a-zA-Z0-9-]/g, "-");
  if (str.charAt(0).match(/[0-9-]/)) {
    str = "_" + str;
  }
  return str;
}
async function _loadColorTheme(extensionResourceLoaderService, themeLocation, result) {
  if ($th(themeLocation) === ".json") {
    const content = await extensionResourceLoaderService.readExtensionResource(themeLocation);
    const errors = [];
    const contentValue = $yw(content, errors);
    if (errors.length > 0) {
      return Promise.reject(new Error(localize(13193, null, errors.map((e) => $SA(e.error)).join(", "))));
    } else if ($Gw(contentValue) !== "object") {
      return Promise.reject(new Error(localize(13194, null)));
    }
    if (contentValue.include) {
      await _loadColorTheme(extensionResourceLoaderService, $vh($uh(themeLocation), contentValue.include), result);
    }
    if (Array.isArray(contentValue.settings)) {
      $GGb(contentValue.settings, result);
      return null;
    }
    result.semanticHighlighting = result.semanticHighlighting || contentValue.semanticHighlighting;
    const colors = contentValue.colors;
    if (colors) {
      if (typeof colors !== "object") {
        return Promise.reject(new Error(localize(13195, null, themeLocation.toString())));
      }
      for (const colorId in colors) {
        const colorVal = colors[colorId];
        if (colorVal === $4n) {
          delete result.colors[colorId];
        } else if (typeof colorVal === "string") {
          result.colors[colorId] = $Vn.fromHex(colors[colorId]);
        }
      }
    }
    const tokenColors = contentValue.tokenColors;
    if (tokenColors) {
      if (Array.isArray(tokenColors)) {
        result.textMateRules.push(...tokenColors);
      } else if (typeof tokenColors === "string") {
        await _loadSyntaxTokens(extensionResourceLoaderService, $vh($uh(themeLocation), tokenColors), result);
      } else {
        return Promise.reject(new Error(localize(13196, null, themeLocation.toString())));
      }
    }
    const semanticTokenColors = contentValue.semanticTokenColors;
    if (semanticTokenColors && typeof semanticTokenColors === "object") {
      for (const key2 in semanticTokenColors) {
        try {
          const rule = readSemanticTokenRule(key2, semanticTokenColors[key2]);
          if (rule) {
            result.semanticTokenRules.push(rule);
          }
        } catch (e) {
          return Promise.reject(new Error(localize(13197, null, themeLocation.toString())));
        }
      }
    }
  } else {
    return _loadSyntaxTokens(extensionResourceLoaderService, themeLocation, result);
  }
}
function _loadSyntaxTokens(extensionResourceLoaderService, themeLocation, result) {
  return extensionResourceLoaderService.readExtensionResource(themeLocation).then((content) => {
    try {
      const contentValue = $HGb(content);
      const settings = contentValue.settings;
      if (!Array.isArray(settings)) {
        return Promise.reject(new Error(localize(13198, null)));
      }
      $GGb(settings, result);
      return Promise.resolve(null);
    } catch (e) {
      return Promise.reject(new Error(localize(13199, null, e.message)));
    }
  }, (error) => {
    return Promise.reject(new Error(localize(13200, null, themeLocation.toString(), error.message)));
  });
}
var defaultThemeColors = {
  "light": [
    { scope: "token.info-token", settings: { foreground: "#316bcd" } },
    { scope: "token.warn-token", settings: { foreground: "#cd9731" } },
    { scope: "token.error-token", settings: { foreground: "#cd3131" } },
    { scope: "token.debug-token", settings: { foreground: "#800080" } }
  ],
  "dark": [
    { scope: "token.info-token", settings: { foreground: "#6796e6" } },
    { scope: "token.warn-token", settings: { foreground: "#cd9731" } },
    { scope: "token.error-token", settings: { foreground: "#f44747" } },
    { scope: "token.debug-token", settings: { foreground: "#b267e6" } }
  ],
  "hcLight": [
    { scope: "token.info-token", settings: { foreground: "#316bcd" } },
    { scope: "token.warn-token", settings: { foreground: "#cd9731" } },
    { scope: "token.error-token", settings: { foreground: "#cd3131" } },
    { scope: "token.debug-token", settings: { foreground: "#800080" } }
  ],
  "hcDark": [
    { scope: "token.info-token", settings: { foreground: "#6796e6" } },
    { scope: "token.warn-token", settings: { foreground: "#008000" } },
    { scope: "token.error-token", settings: { foreground: "#FF0000" } },
    { scope: "token.debug-token", settings: { foreground: "#b267e6" } }
  ]
};
var noMatch = (_scope) => -1;
function nameMatcher(identifiers2, scopes) {
  if (scopes.length < identifiers2.length) {
    return -1;
  }
  let lastIndex = 0;
  let score2 = void 0;
  const every = identifiers2.every((identifier2, identifierIndex) => {
    for (let i2 = lastIndex; i2 < scopes.length; i2++) {
      if (scopesAreMatching(scopes[i2], identifier2)) {
        score2 = (identifierIndex + 1) * 65536 + identifier2.length;
        lastIndex = i2 + 1;
        return true;
      }
    }
    return false;
  });
  return every && score2 !== void 0 ? score2 : -1;
}
function scopesAreMatching(thisScopeName, scopeName) {
  if (!thisScopeName) {
    return false;
  }
  if (thisScopeName === scopeName) {
    return true;
  }
  const len = scopeName.length;
  return thisScopeName.length > len && thisScopeName.substr(0, len) === scopeName && thisScopeName[len] === ".";
}
function getScopeMatcher(rule) {
  const ruleScope = rule.scope;
  if (!ruleScope || !rule.settings) {
    return noMatch;
  }
  const matchers = [];
  if (Array.isArray(ruleScope)) {
    for (const rs of ruleScope) {
      $IGb(rs, nameMatcher, matchers);
    }
  } else {
    $IGb(ruleScope, nameMatcher, matchers);
  }
  if (matchers.length === 0) {
    return noMatch;
  }
  return (scope) => {
    let max = matchers[0].matcher(scope);
    for (let i2 = 1; i2 < matchers.length; i2++) {
      max = Math.max(max, matchers[i2].matcher(scope));
    }
    return max;
  };
}
function readSemanticTokenRule(selectorString, settings) {
  const selector = tokenClassificationRegistry3.parseTokenSelector(selectorString);
  let style;
  if (typeof settings === "string") {
    style = $Jlb.fromSettings(settings, void 0);
  } else if (isSemanticTokenColorizationSetting(settings)) {
    style = $Jlb.fromSettings(settings.foreground, settings.fontStyle, settings.bold, settings.underline, settings.strikethrough, settings.italic);
  }
  if (style) {
    return { selector, style };
  }
  return void 0;
}
function isSemanticTokenColorizationSetting(style) {
  return style && ($zg(style.foreground) || $zg(style.fontStyle) || $Fg(style.italic) || $Fg(style.underline) || $Fg(style.strikethrough) || $Fg(style.bold));
}
function $6Gb(colorThemeData, captureNames, languageId) {
  let metadata = 0;
  metadata |= languageId << 0;
  const definitions3 = {};
  const tokenStyle = colorThemeData.resolveScopes([captureNames], definitions3);
  if (captureNames.length > 0) {
    const standardToken = $YGb(captureNames[captureNames.length - 1]);
    metadata |= standardToken << 8;
  }
  switch (definitions3.foreground?.settings.fontStyle) {
    case "italic":
      metadata |= 1 | 2048;
      break;
    case "bold":
      metadata |= 2 | 4096;
      break;
    case "underline":
      metadata |= 4 | 8192;
      break;
    case "strikethrough":
      metadata |= 8 | 16384;
      break;
  }
  const foreground = tokenStyle?.foreground;
  const tokenStyleForeground = foreground !== void 0 ? colorThemeData.getTokenColorIndex().get(foreground) : 1;
  metadata |= tokenStyleForeground << 15;
  return metadata;
}
var TokenColorIndex = class {
  constructor() {
    this.b = 0;
    this.c = [];
    this.g = /* @__PURE__ */ Object.create(null);
  }
  add(color2) {
    color2 = normalizeColor(color2);
    if (color2 === void 0) {
      return 0;
    }
    let value = this.g[color2];
    if (value) {
      return value;
    }
    value = ++this.b;
    this.g[color2] = value;
    this.c[value] = color2;
    return value;
  }
  get(color2) {
    color2 = normalizeColor(color2);
    if (color2 === void 0) {
      return 0;
    }
    const value = this.g[color2];
    if (value) {
      return value;
    }
    console.log(`Color ${color2} not in index.`);
    return 0;
  }
  asArray() {
    return this.c.slice(0);
  }
};
function normalizeColor(color2) {
  if (!color2) {
    return void 0;
  }
  if (typeof color2 !== "string") {
    color2 = $Vn.Format.CSS.formatHexA(color2, true);
  }
  const len = color2.length;
  if (color2.charCodeAt(0) !== 35 || len !== 4 && len !== 5 && len !== 7 && len !== 9) {
    return void 0;
  }
  const result = [
    35
    /* CharCode.Hash */
  ];
  for (let i2 = 1; i2 < len; i2++) {
    const upper = hexUpper(color2.charCodeAt(i2));
    if (!upper) {
      return void 0;
    }
    result.push(upper);
    if (len === 4 || len === 5) {
      result.push(upper);
    }
  }
  if (result.length === 9 && result[7] === 70 && result[8] === 70) {
    result.length = 7;
  }
  return String.fromCharCode(...result);
}
function hexUpper(charCode) {
  if (charCode >= 48 && charCode <= 57 || charCode >= 65 && charCode <= 70) {
    return charCode;
  } else if (charCode >= 97 && charCode <= 102) {
    return charCode - 97 + 65;
  }
  return 0;
}

// out-build/vs/workbench/services/themes/common/fileIconThemeSchema.js
var schemaId4 = "vscode://schemas/icon-theme";
var schema4 = {
  type: "object",
  allowComments: true,
  allowTrailingCommas: true,
  definitions: {
    folderExpanded: {
      type: "string",
      description: localize(13214, null)
    },
    folder: {
      type: "string",
      description: localize(13215, null)
    },
    file: {
      type: "string",
      description: localize(13216, null)
    },
    rootFolder: {
      type: "string",
      description: localize(13217, null)
    },
    rootFolderExpanded: {
      type: "string",
      description: localize(13218, null)
    },
    rootFolderNames: {
      type: "object",
      description: localize(13219, null),
      additionalProperties: {
        type: "string",
        description: localize(13220, null)
      }
    },
    rootFolderNamesExpanded: {
      type: "object",
      description: localize(13221, null),
      additionalProperties: {
        type: "string",
        description: localize(13222, null)
      }
    },
    folderNames: {
      type: "object",
      description: localize(13223, null),
      additionalProperties: {
        type: "string",
        description: localize(13224, null)
      }
    },
    folderNamesExpanded: {
      type: "object",
      description: localize(13225, null),
      additionalProperties: {
        type: "string",
        description: localize(13226, null)
      }
    },
    fileExtensions: {
      type: "object",
      description: localize(13227, null),
      additionalProperties: {
        type: "string",
        description: localize(13228, null)
      }
    },
    fileNames: {
      type: "object",
      description: localize(13229, null),
      additionalProperties: {
        type: "string",
        description: localize(13230, null)
      }
    },
    languageIds: {
      type: "object",
      description: localize(13231, null),
      additionalProperties: {
        type: "string",
        description: localize(13232, null)
      }
    },
    associations: {
      type: "object",
      properties: {
        folderExpanded: {
          $ref: "#/definitions/folderExpanded"
        },
        folder: {
          $ref: "#/definitions/folder"
        },
        file: {
          $ref: "#/definitions/file"
        },
        folderNames: {
          $ref: "#/definitions/folderNames"
        },
        folderNamesExpanded: {
          $ref: "#/definitions/folderNamesExpanded"
        },
        rootFolder: {
          $ref: "#/definitions/rootFolder"
        },
        rootFolderExpanded: {
          $ref: "#/definitions/rootFolderExpanded"
        },
        rootFolderNames: {
          $ref: "#/definitions/rootFolderNames"
        },
        rootFolderNamesExpanded: {
          $ref: "#/definitions/rootFolderNamesExpanded"
        },
        fileExtensions: {
          $ref: "#/definitions/fileExtensions"
        },
        fileNames: {
          $ref: "#/definitions/fileNames"
        },
        languageIds: {
          $ref: "#/definitions/languageIds"
        }
      }
    }
  },
  properties: {
    fonts: {
      type: "array",
      description: localize(13233, null),
      items: {
        type: "object",
        properties: {
          id: {
            type: "string",
            description: localize(13234, null),
            pattern: $zlb,
            patternErrorMessage: localize(13235, null)
          },
          src: {
            type: "array",
            description: localize(13236, null),
            items: {
              type: "object",
              properties: {
                path: {
                  type: "string",
                  description: localize(13237, null)
                },
                format: {
                  type: "string",
                  description: localize(13238, null),
                  enum: ["woff", "woff2", "truetype", "opentype", "embedded-opentype", "svg"]
                }
              },
              required: [
                "path",
                "format"
              ]
            }
          },
          weight: {
            type: "string",
            description: localize(13239, null),
            pattern: $Blb
          },
          style: {
            type: "string",
            description: localize(13240, null),
            pattern: $Alb
          },
          size: {
            type: "string",
            description: localize(13241, null),
            pattern: $Clb
          }
        },
        required: [
          "id",
          "src"
        ]
      }
    },
    iconDefinitions: {
      type: "object",
      description: localize(13242, null),
      additionalProperties: {
        type: "object",
        description: localize(13243, null),
        properties: {
          iconPath: {
            type: "string",
            description: localize(13244, null)
          },
          fontCharacter: {
            type: "string",
            description: localize(13245, null),
            pattern: $Elb,
            patternErrorMessage: localize(13246, null)
          },
          fontColor: {
            type: "string",
            format: "color-hex",
            description: localize(13247, null),
            pattern: $Flb
          },
          fontSize: {
            type: "string",
            description: localize(13248, null),
            pattern: $Clb
          },
          fontId: {
            type: "string",
            description: localize(13249, null)
          }
        }
      }
    },
    folderExpanded: {
      $ref: "#/definitions/folderExpanded"
    },
    folder: {
      $ref: "#/definitions/folder"
    },
    file: {
      $ref: "#/definitions/file"
    },
    folderNames: {
      $ref: "#/definitions/folderNames"
    },
    folderNamesExpanded: {
      $ref: "#/definitions/folderNamesExpanded"
    },
    rootFolder: {
      $ref: "#/definitions/rootFolder"
    },
    rootFolderExpanded: {
      $ref: "#/definitions/rootFolderExpanded"
    },
    rootFolderNames: {
      $ref: "#/definitions/rootFolderNames"
    },
    rootFolderNamesExpanded: {
      $ref: "#/definitions/rootFolderNamesExpanded"
    },
    fileExtensions: {
      $ref: "#/definitions/fileExtensions"
    },
    fileNames: {
      $ref: "#/definitions/fileNames"
    },
    languageIds: {
      $ref: "#/definitions/languageIds"
    },
    light: {
      $ref: "#/definitions/associations",
      description: localize(13250, null)
    },
    highContrast: {
      $ref: "#/definitions/associations",
      description: localize(13251, null)
    },
    hidesExplorerArrows: {
      type: "boolean",
      description: localize(13252, null)
    },
    showLanguageModeIcons: {
      type: "boolean",
      description: localize(13253, null)
    }
  }
};
function $ZVb() {
  const schemaRegistry7 = $Wn.as($Xn.JSONContribution);
  schemaRegistry7.registerSchema(schemaId4, schema4);
}

// out-build/vs/workbench/services/themes/browser/fileIconThemeData.js
var $1Vb = class _$1Vb {
  static {
    this.STORAGE_KEY = "iconThemeData";
  }
  constructor(id2, label3, settingsId) {
    this.id = id2;
    this.label = label3;
    this.settingsId = settingsId;
    this.isLoaded = false;
    this.hasFileIcons = false;
    this.hasFolderIcons = false;
    this.hidesExplorerArrows = false;
  }
  ensureLoaded(themeLoader) {
    return !this.isLoaded ? this.a(themeLoader) : Promise.resolve(this.styleSheetContent);
  }
  reload(themeLoader) {
    return this.a(themeLoader);
  }
  a(themeLoader) {
    return themeLoader.load(this);
  }
  static fromExtensionTheme(iconTheme, iconThemeLocation, extensionData) {
    const id2 = extensionData.extensionId + "-" + iconTheme.id;
    const label3 = iconTheme.label || $rc(iconTheme.path);
    const settingsId = iconTheme.id;
    const themeData = new _$1Vb(id2, label3, settingsId);
    themeData.description = iconTheme.description;
    themeData.location = iconThemeLocation;
    themeData.extensionData = extensionData;
    themeData.watch = iconTheme._watch;
    themeData.isLoaded = false;
    return themeData;
  }
  static {
    this.b = null;
  }
  static get noIconTheme() {
    let themeData = _$1Vb.b;
    if (!themeData) {
      themeData = _$1Vb.b = new _$1Vb("", "", null);
      themeData.hasFileIcons = false;
      themeData.hasFolderIcons = false;
      themeData.hidesExplorerArrows = false;
      themeData.isLoaded = true;
      themeData.extensionData = void 0;
      themeData.watch = false;
    }
    return themeData;
  }
  static createUnloadedTheme(id2) {
    const themeData = new _$1Vb(id2, "", "__" + id2);
    themeData.isLoaded = false;
    themeData.hasFileIcons = false;
    themeData.hasFolderIcons = false;
    themeData.hidesExplorerArrows = false;
    themeData.extensionData = void 0;
    themeData.watch = false;
    return themeData;
  }
  static fromStorageData(storageService) {
    const input = storageService.get(
      _$1Vb.STORAGE_KEY,
      0
      /* StorageScope.PROFILE */
    );
    if (!input) {
      return void 0;
    }
    try {
      const data = JSON.parse(input);
      const theme = new _$1Vb("", "", null);
      for (const key2 in data) {
        switch (key2) {
          case "id":
          case "label":
          case "description":
          case "settingsId":
          case "styleSheetContent":
          case "hasFileIcons":
          case "hidesExplorerArrows":
          case "hasFolderIcons":
          case "watch":
            theme[key2] = data[key2];
            break;
          case "location":
            break;
          case "extensionData":
            theme.extensionData = ExtensionData.fromJSONObject(data.extensionData);
            break;
        }
      }
      return theme;
    } catch (e) {
      return void 0;
    }
  }
  toStorage(storageService) {
    const data = JSON.stringify({
      id: this.id,
      label: this.label,
      description: this.description,
      settingsId: this.settingsId,
      styleSheetContent: this.styleSheetContent,
      hasFileIcons: this.hasFileIcons,
      hasFolderIcons: this.hasFolderIcons,
      hidesExplorerArrows: this.hidesExplorerArrows,
      extensionData: ExtensionData.toJSONObject(this.extensionData),
      watch: this.watch
    });
    storageService.store(
      _$1Vb.STORAGE_KEY,
      data,
      0,
      1
      /* StorageTarget.MACHINE */
    );
  }
};
var $2Vb = class {
  constructor(a, b) {
    this.a = a;
    this.b = b;
  }
  load(data) {
    if (!data.location) {
      return Promise.resolve(data.styleSheetContent);
    }
    return this.c(data.location).then((iconThemeDocument) => {
      const result = this.d(data.id, data.location, iconThemeDocument);
      data.styleSheetContent = result.content;
      data.hasFileIcons = result.hasFileIcons;
      data.hasFolderIcons = result.hasFolderIcons;
      data.hidesExplorerArrows = result.hidesExplorerArrows;
      data.isLoaded = true;
      return data.styleSheetContent;
    });
  }
  c(location3) {
    return this.a.readExtensionResource(location3).then((content) => {
      const errors = [];
      const contentValue = $yw(content, errors);
      if (errors.length > 0) {
        return Promise.reject(new Error(localize(13156, null, errors.map((e) => $SA(e.error)).join(", "))));
      } else if ($Gw(contentValue) !== "object") {
        return Promise.reject(new Error(localize(13157, null)));
      }
      return Promise.resolve(contentValue);
    });
  }
  d(id2, iconThemeDocumentLocation, iconThemeDocument) {
    const result = { content: "", hasFileIcons: false, hasFolderIcons: false, hidesExplorerArrows: !!iconThemeDocument.hidesExplorerArrows };
    let hasSpecificFileIcons = false;
    if (!iconThemeDocument.iconDefinitions) {
      return result;
    }
    const selectorByDefinitionId = {};
    const coveredLanguages = {};
    const iconThemeDocumentLocationDirname = $uh(iconThemeDocumentLocation);
    function resolvePath(path) {
      return $vh(iconThemeDocumentLocationDirname, path);
    }
    function collectSelectors(associations, baseThemeClassName) {
      function addSelector(selector, defId) {
        if (defId) {
          let list2 = selectorByDefinitionId[defId];
          if (!list2) {
            list2 = selectorByDefinitionId[defId] = new $8Z();
          }
          list2.push(selector);
        }
      }
      if (associations) {
        let qualifier = $7Z`.show-file-icons`;
        if (baseThemeClassName) {
          qualifier = $7Z`${baseThemeClassName} ${qualifier}`;
        }
        const expanded2 = $7Z`.monaco-tl-twistie.collapsible:not(.collapsed) + .monaco-tl-contents`;
        if (associations.folder) {
          addSelector($7Z`${qualifier} .folder-icon::before`, associations.folder);
          result.hasFolderIcons = true;
        }
        if (associations.folderExpanded) {
          addSelector($7Z`${qualifier} ${expanded2} .folder-icon::before`, associations.folderExpanded);
          result.hasFolderIcons = true;
        }
        const rootFolder = associations.rootFolder || associations.folder;
        const rootFolderExpanded = associations.rootFolderExpanded || associations.folderExpanded;
        if (rootFolder) {
          addSelector($7Z`${qualifier} .rootfolder-icon::before`, rootFolder);
          result.hasFolderIcons = true;
        }
        if (rootFolderExpanded) {
          addSelector($7Z`${qualifier} ${expanded2} .rootfolder-icon::before`, rootFolderExpanded);
          result.hasFolderIcons = true;
        }
        if (associations.file) {
          addSelector($7Z`${qualifier} .file-icon::before`, associations.file);
          result.hasFileIcons = true;
        }
        const folderNames = associations.folderNames;
        if (folderNames) {
          for (const key2 in folderNames) {
            const selectors = new $8Z();
            const name = handleParentFolder(key2.toLowerCase(), selectors);
            selectors.push($7Z`.${classSelectorPart(name)}-name-folder-icon`);
            addSelector($7Z`${qualifier} ${selectors.join("")}.folder-icon::before`, folderNames[key2]);
            result.hasFolderIcons = true;
          }
        }
        const folderNamesExpanded = associations.folderNamesExpanded;
        if (folderNamesExpanded) {
          for (const key2 in folderNamesExpanded) {
            const selectors = new $8Z();
            const name = handleParentFolder(key2.toLowerCase(), selectors);
            selectors.push($7Z`.${classSelectorPart(name)}-name-folder-icon`);
            addSelector($7Z`${qualifier} ${expanded2} ${selectors.join("")}.folder-icon::before`, folderNamesExpanded[key2]);
            result.hasFolderIcons = true;
          }
        }
        const rootFolderNames = associations.rootFolderNames;
        if (rootFolderNames) {
          for (const key2 in rootFolderNames) {
            const name = key2.toLowerCase();
            addSelector($7Z`${qualifier} .${classSelectorPart(name)}-root-name-folder-icon.rootfolder-icon::before`, rootFolderNames[key2]);
            result.hasFolderIcons = true;
          }
        }
        const rootFolderNamesExpanded = associations.rootFolderNamesExpanded;
        if (rootFolderNamesExpanded) {
          for (const key2 in rootFolderNamesExpanded) {
            const name = key2.toLowerCase();
            addSelector($7Z`${qualifier} ${expanded2} .${classSelectorPart(name)}-root-name-folder-icon.rootfolder-icon::before`, rootFolderNamesExpanded[key2]);
            result.hasFolderIcons = true;
          }
        }
        const languageIds = associations.languageIds;
        if (languageIds) {
          if (!languageIds.jsonc && languageIds.json) {
            languageIds.jsonc = languageIds.json;
          }
          for (const languageId in languageIds) {
            addSelector($7Z`${qualifier} .${classSelectorPart(languageId)}-lang-file-icon.file-icon::before`, languageIds[languageId]);
            result.hasFileIcons = true;
            hasSpecificFileIcons = true;
            coveredLanguages[languageId] = true;
          }
        }
        const fileExtensions = associations.fileExtensions;
        if (fileExtensions) {
          for (const key2 in fileExtensions) {
            const selectors = new $8Z();
            const name = handleParentFolder(key2.toLowerCase(), selectors);
            const segments = name.split(".");
            if (segments.length) {
              for (let i2 = 0; i2 < segments.length; i2++) {
                selectors.push($7Z`.${classSelectorPart(segments.slice(i2).join("."))}-ext-file-icon`);
              }
              selectors.push($7Z`.ext-file-icon`);
            }
            addSelector($7Z`${qualifier} ${selectors.join("")}.file-icon::before`, fileExtensions[key2]);
            result.hasFileIcons = true;
            hasSpecificFileIcons = true;
          }
        }
        const fileNames = associations.fileNames;
        if (fileNames) {
          for (const key2 in fileNames) {
            const selectors = new $8Z();
            const fileName = handleParentFolder(key2.toLowerCase(), selectors);
            selectors.push($7Z`.${classSelectorPart(fileName)}-name-file-icon`);
            selectors.push($7Z`.name-file-icon`);
            const segments = fileName.split(".");
            if (segments.length) {
              for (let i2 = 1; i2 < segments.length; i2++) {
                selectors.push($7Z`.${classSelectorPart(segments.slice(i2).join("."))}-ext-file-icon`);
              }
              selectors.push($7Z`.ext-file-icon`);
            }
            addSelector($7Z`${qualifier} ${selectors.join("")}.file-icon::before`, fileNames[key2]);
            result.hasFileIcons = true;
            hasSpecificFileIcons = true;
          }
        }
      }
    }
    collectSelectors(iconThemeDocument);
    collectSelectors(iconThemeDocument.light, $7Z`.vs`);
    collectSelectors(iconThemeDocument.highContrast, $7Z`.hc-black`);
    collectSelectors(iconThemeDocument.highContrast, $7Z`.hc-light`);
    if (!result.hasFileIcons && !result.hasFolderIcons) {
      return result;
    }
    const showLanguageModeIcons = iconThemeDocument.showLanguageModeIcons === true || hasSpecificFileIcons && iconThemeDocument.showLanguageModeIcons !== false;
    const cssRules = new $8Z();
    const fonts = iconThemeDocument.fonts;
    const fontSizes = /* @__PURE__ */ new Map();
    if (Array.isArray(fonts)) {
      const defaultFontSize = this.f(fonts[0].size) || "150%";
      fonts.forEach((font) => {
        const fontSrcs = new $8Z();
        fontSrcs.push(...font.src.map((l) => $7Z`${$5Z(resolvePath(l.path))} format(${$4Z(l.format)})`));
        cssRules.push($7Z`@font-face { src: ${fontSrcs.join(", ")}; font-family: ${$4Z(font.id)}; font-weight: ${$3Z(font.weight)}; font-style: ${$3Z(font.style)}; font-display: block; }`);
        const fontSize = this.f(font.size);
        if (fontSize !== void 0 && fontSize !== defaultFontSize) {
          fontSizes.set(font.id, fontSize);
        }
      });
      cssRules.push($7Z`.show-file-icons .file-icon::before, .show-file-icons .folder-icon::before, .show-file-icons .rootfolder-icon::before { font-family: ${$4Z(fonts[0].id)}; font-size: ${$1Z(defaultFontSize)}; }`);
    }
    const emQuad = $4Z("\\2001");
    for (const defId in selectorByDefinitionId) {
      const selectors = selectorByDefinitionId[defId];
      const definition = iconThemeDocument.iconDefinitions[defId];
      if (definition) {
        if (definition.iconPath) {
          cssRules.push($7Z`${selectors.join(", ")} { content: ${emQuad}; background-image: ${$5Z(resolvePath(definition.iconPath))}; }`);
        } else if (definition.fontCharacter || definition.fontColor) {
          const body = new $8Z();
          if (definition.fontColor && definition.fontColor.match($Flb)) {
            body.push($7Z`color: ${$2Z(definition.fontColor)};`);
          }
          if (definition.fontCharacter && definition.fontCharacter.match($Elb)) {
            body.push($7Z`content: ${$4Z(definition.fontCharacter)};`);
          }
          const fontSize = definition.fontSize ?? (definition.fontId ? fontSizes.get(definition.fontId) : void 0);
          if (fontSize && fontSize.match($Clb)) {
            body.push($7Z`font-size: ${$1Z(fontSize)};`);
          }
          if (definition.fontId) {
            body.push($7Z`font-family: ${$4Z(definition.fontId)};`);
          }
          if (showLanguageModeIcons) {
            body.push($7Z`background-image: unset;`);
          }
          cssRules.push($7Z`${selectors.join(", ")} { ${body.join(" ")} }`);
        }
      }
    }
    if (showLanguageModeIcons) {
      for (const languageId of this.b.getRegisteredLanguageIds()) {
        if (!coveredLanguages[languageId]) {
          const icon2 = this.b.getIcon(languageId);
          if (icon2) {
            const selector = $7Z`.show-file-icons .${classSelectorPart(languageId)}-lang-file-icon.file-icon::before`;
            cssRules.push($7Z`${selector} { content: ${emQuad}; background-image: ${$5Z(icon2.dark)}; }`);
            cssRules.push($7Z`.vs ${selector} { content: ${emQuad}; background-image: ${$5Z(icon2.light)}; }`);
          }
        }
      }
    }
    result.content = cssRules.join("\n");
    return result;
  }
  /**
   * Try converting absolute font sizes to relative values.
   *
   * This allows them to be scaled nicely depending on where they are used.
   */
  f(size) {
    if (!size) {
      return void 0;
    }
    const defaultFontSizeInPx = 13;
    if (size.endsWith("px")) {
      const value = parseInt(size, 10);
      if (!isNaN(value)) {
        return Math.round(value / defaultFontSizeInPx * 100) + "%";
      }
    }
    return size;
  }
};
function handleParentFolder(key2, selectors) {
  const lastIndexOfSlash = key2.lastIndexOf("/");
  if (lastIndexOfSlash >= 0) {
    const parentFolder = key2.substring(0, lastIndexOfSlash);
    selectors.push($7Z`.${classSelectorPart(parentFolder)}-name-dir-icon`);
    return key2.substring(lastIndexOfSlash + 1);
  }
  return key2;
}
function classSelectorPart(str) {
  str = $idb(str);
  return $6Z(str, true);
}

// out-build/vs/workbench/services/themes/common/colorThemeSchema.js
var textMateScopes = [
  "comment",
  "comment.block",
  "comment.block.documentation",
  "comment.line",
  "constant",
  "constant.character",
  "constant.character.escape",
  "constant.numeric",
  "constant.numeric.integer",
  "constant.numeric.float",
  "constant.numeric.hex",
  "constant.numeric.octal",
  "constant.other",
  "constant.regexp",
  "constant.rgb-value",
  "emphasis",
  "entity",
  "entity.name",
  "entity.name.class",
  "entity.name.function",
  "entity.name.method",
  "entity.name.section",
  "entity.name.selector",
  "entity.name.tag",
  "entity.name.type",
  "entity.other",
  "entity.other.attribute-name",
  "entity.other.inherited-class",
  "invalid",
  "invalid.deprecated",
  "invalid.illegal",
  "keyword",
  "keyword.control",
  "keyword.operator",
  "keyword.operator.new",
  "keyword.operator.assignment",
  "keyword.operator.arithmetic",
  "keyword.operator.logical",
  "keyword.other",
  "markup",
  "markup.bold",
  "markup.changed",
  "markup.deleted",
  "markup.heading",
  "markup.inline.raw",
  "markup.inserted",
  "markup.italic",
  "markup.list",
  "markup.list.numbered",
  "markup.list.unnumbered",
  "markup.other",
  "markup.quote",
  "markup.raw",
  "markup.underline",
  "markup.underline.link",
  "meta",
  "meta.block",
  "meta.cast",
  "meta.class",
  "meta.function",
  "meta.function-call",
  "meta.preprocessor",
  "meta.return-type",
  "meta.selector",
  "meta.tag",
  "meta.type.annotation",
  "meta.type",
  "punctuation.definition.string.begin",
  "punctuation.definition.string.end",
  "punctuation.separator",
  "punctuation.separator.continuation",
  "punctuation.terminator",
  "storage",
  "storage.modifier",
  "storage.type",
  "string",
  "string.interpolated",
  "string.other",
  "string.quoted",
  "string.quoted.double",
  "string.quoted.other",
  "string.quoted.single",
  "string.quoted.triple",
  "string.regexp",
  "string.unquoted",
  "strong",
  "support",
  "support.class",
  "support.constant",
  "support.function",
  "support.other",
  "support.type",
  "support.type.property-name",
  "support.variable",
  "variable",
  "variable.language",
  "variable.name",
  "variable.other",
  "variable.other.readwrite",
  "variable.parameter"
];
var $JGb = "vscode://schemas/textmate-colors";
var $KGb = `${$JGb}#/definitions/colorGroup`;
var textmateColorSchema = {
  type: "array",
  definitions: {
    colorGroup: {
      default: "#FF0000",
      anyOf: [
        {
          type: "string",
          format: "color-hex"
        },
        {
          $ref: "#/definitions/settings"
        }
      ]
    },
    settings: {
      type: "object",
      description: localize(13201, null),
      properties: {
        foreground: {
          type: "string",
          description: localize(13202, null),
          format: "color-hex",
          default: "#ff0000"
        },
        background: {
          type: "string",
          deprecationMessage: localize(13203, null)
        },
        fontStyle: {
          type: "string",
          description: localize(13204, null),
          pattern: "^(\\s*\\b(italic|bold|underline|strikethrough))*\\s*$",
          patternErrorMessage: localize(13205, null),
          defaultSnippets: [
            { label: localize(13206, null), bodyText: '""' },
            { body: "italic" },
            { body: "bold" },
            { body: "underline" },
            { body: "strikethrough" },
            { body: "italic bold" },
            { body: "italic underline" },
            { body: "italic strikethrough" },
            { body: "bold underline" },
            { body: "bold strikethrough" },
            { body: "underline strikethrough" },
            { body: "italic bold underline" },
            { body: "italic bold strikethrough" },
            { body: "italic underline strikethrough" },
            { body: "bold underline strikethrough" },
            { body: "italic bold underline strikethrough" }
          ]
        }
      },
      additionalProperties: false,
      defaultSnippets: [{ body: { foreground: "${1:#FF0000}", fontStyle: "${2:bold}" } }]
    }
  },
  items: {
    type: "object",
    defaultSnippets: [{ body: { scope: "${1:keyword.operator}", settings: { foreground: "${2:#FF0000}" } } }],
    properties: {
      name: {
        type: "string",
        description: localize(13207, null)
      },
      scope: {
        description: localize(13208, null),
        anyOf: [
          {
            enum: textMateScopes
          },
          {
            type: "string"
          },
          {
            type: "array",
            items: {
              enum: textMateScopes
            }
          },
          {
            type: "array",
            items: {
              type: "string"
            }
          }
        ]
      },
      settings: {
        $ref: "#/definitions/settings"
      }
    },
    required: [
      "settings"
    ],
    additionalProperties: false
  }
};
var $LGb = "vscode://schemas/color-theme";
var colorThemeSchema = {
  type: "object",
  allowComments: true,
  allowTrailingCommas: true,
  properties: {
    colors: {
      description: localize(13209, null),
      $ref: $do,
      additionalProperties: false
    },
    tokenColors: {
      anyOf: [
        {
          type: "string",
          description: localize(13210, null)
        },
        {
          description: localize(13211, null),
          $ref: $JGb
        }
      ]
    },
    semanticHighlighting: {
      type: "boolean",
      description: localize(13212, null)
    },
    semanticTokenColors: {
      type: "object",
      description: localize(13213, null),
      $ref: $Mlb
    }
  }
};
function $MGb() {
  const schemaRegistry7 = $Wn.as($Xn.JSONContribution);
  schemaRegistry7.registerSchema($LGb, colorThemeSchema);
  schemaRegistry7.registerSchema($JGb, textmateColorSchema);
}

// out-build/vs/workbench/services/themes/common/themeExtensionPoints.js
function $3Vb() {
  return $tN.registerExtensionPoint({
    extensionPoint: "themes",
    jsonSchema: {
      description: localize(13313, null),
      type: "array",
      items: {
        type: "object",
        defaultSnippets: [{ body: { label: "${1:label}", id: "${2:id}", uiTheme: $twb, path: "./themes/${3:id}.tmTheme." } }],
        properties: {
          id: {
            description: localize(13314, null),
            type: "string"
          },
          label: {
            description: localize(13315, null),
            type: "string"
          },
          uiTheme: {
            description: localize(13316, null),
            enum: [$swb, $twb, $uwb, $vwb]
          },
          path: {
            description: localize(13317, null),
            type: "string"
          }
        },
        required: ["path", "uiTheme"]
      }
    }
  });
}
function $4Vb() {
  return $tN.registerExtensionPoint({
    extensionPoint: "iconThemes",
    jsonSchema: {
      description: localize(13318, null),
      type: "array",
      items: {
        type: "object",
        defaultSnippets: [{ body: { id: "${1:id}", label: "${2:label}", path: "./fileicons/${3:id}-icon-theme.json" } }],
        properties: {
          id: {
            description: localize(13319, null),
            type: "string"
          },
          label: {
            description: localize(13320, null),
            type: "string"
          },
          path: {
            description: localize(13321, null),
            type: "string"
          }
        },
        required: ["path", "id"]
      }
    }
  });
}
function $5Vb() {
  return $tN.registerExtensionPoint({
    extensionPoint: "productIconThemes",
    jsonSchema: {
      description: localize(13322, null),
      type: "array",
      items: {
        type: "object",
        defaultSnippets: [{ body: { id: "${1:id}", label: "${2:label}", path: "./producticons/${3:id}-product-icon-theme.json" } }],
        properties: {
          id: {
            description: localize(13323, null),
            type: "string"
          },
          label: {
            description: localize(13324, null),
            type: "string"
          },
          path: {
            description: localize(13325, null),
            type: "string"
          }
        },
        required: ["path", "id"]
      }
    }
  });
}
var ThemeDataRenderer = class extends $3c {
  constructor() {
    super(...arguments);
    this.type = "markdown";
  }
  shouldRender(manifest) {
    return !!manifest.contributes?.themes || !!manifest.contributes?.iconThemes || !!manifest.contributes?.productIconThemes;
  }
  render(manifest) {
    const markdown = new $bm();
    if (manifest.contributes?.themes) {
      markdown.appendMarkdown(`### ${localize(13326, null)}

`);
      for (const theme of manifest.contributes.themes) {
        markdown.appendMarkdown(`- ${theme.label}
`);
      }
    }
    if (manifest.contributes?.iconThemes) {
      markdown.appendMarkdown(`### ${localize(13327, null)}

`);
      for (const theme of manifest.contributes.iconThemes) {
        markdown.appendMarkdown(`- ${theme.label}
`);
      }
    }
    if (manifest.contributes?.productIconThemes) {
      markdown.appendMarkdown(`### ${localize(13328, null)}

`);
      for (const theme of manifest.contributes.productIconThemes) {
        markdown.appendMarkdown(`- ${theme.label}
`);
      }
    }
    return {
      data: markdown,
      dispose: () => {
      }
    };
  }
};
$Wn.as(Extensions3.ExtensionFeaturesRegistry).registerExtensionFeature({
  id: "themes",
  label: localize(13329, null),
  access: {
    canToggle: false
  },
  renderer: new $Nk(ThemeDataRenderer)
});
var $6Vb = class {
  constructor(c, d, e = false, f = void 0) {
    this.c = c;
    this.d = d;
    this.e = e;
    this.f = f;
    this.b = new $ze();
    this.onDidChange = this.b.event;
    this.a = [];
    this.g();
  }
  dispose() {
    this.c.setHandler(() => {
    });
  }
  g() {
    this.c.setHandler((extensions, delta) => {
      const previousIds = {};
      const added = [];
      for (const theme of this.a) {
        previousIds[theme.id] = theme;
      }
      this.a.length = 0;
      for (const ext of extensions) {
        const extensionData = ExtensionData.fromName(ext.description.publisher, ext.description.name, ext.description.isBuiltin);
        this.h(extensionData, ext.description.extensionLocation, ext.value, this.a, ext.collector);
      }
      for (const theme of this.a) {
        if (!previousIds[theme.id]) {
          added.push(theme);
        } else {
          delete previousIds[theme.id];
        }
      }
      const removed = Object.values(previousIds);
      this.b.fire({ themes: this.a, added, removed });
    });
  }
  h(extensionData, extensionLocation, themeContributions, resultingThemes = [], log4) {
    if (!Array.isArray(themeContributions)) {
      log4?.error(localize(13330, null, this.c.name));
      return resultingThemes;
    }
    themeContributions.forEach((theme) => {
      if (!theme.path || !$zg(theme.path)) {
        log4?.error(localize(13331, null, this.c.name, String(theme.path)));
        return;
      }
      if (this.e && (!theme.id || !$zg(theme.id))) {
        log4?.error(localize(13332, null, this.c.name, String(theme.id)));
        return;
      }
      const themeLocation = $vh(extensionLocation, theme.path);
      if (!$ph(themeLocation, extensionLocation)) {
        log4?.warn(localize(13333, null, this.c.name, themeLocation.path, extensionLocation.path));
      }
      const themeData = this.d(theme, themeLocation, extensionData);
      resultingThemes.push(themeData);
    });
    return resultingThemes;
  }
  findThemeById(themeId) {
    if (this.f && this.f.id === themeId) {
      return this.f;
    }
    const allThemes = this.getThemes();
    for (const t of allThemes) {
      if (t.id === themeId) {
        return t;
      }
    }
    return void 0;
  }
  findThemeBySettingsId(settingsId, defaultSettingsId) {
    if (this.f && this.f.settingsId === settingsId) {
      return this.f;
    }
    const allThemes = this.getThemes();
    let defaultTheme = void 0;
    for (const t of allThemes) {
      if (t.settingsId === settingsId) {
        return t;
      }
      if (t.settingsId === defaultSettingsId) {
        defaultTheme = t;
      }
    }
    return defaultTheme;
  }
  findThemeByExtensionLocation(extLocation) {
    if (extLocation) {
      return this.getThemes().filter((t) => t.location && $ph(t.location, extLocation));
    }
    return [];
  }
  getThemes() {
    return this.a;
  }
  getMarketplaceThemes(manifest, extensionLocation, extensionData) {
    const themes = manifest?.contributes?.[this.c.name];
    if (Array.isArray(themes)) {
      return this.h(extensionData, extensionLocation, themes);
    }
    return [];
  }
};

// out-build/vs/workbench/services/themes/common/themeConfiguration.js
var configurationRegistry7 = $Wn.as($Ht.Configuration);
var colorThemeSettingEnum = [];
var colorThemeSettingEnumItemLabels = [];
var colorThemeSettingEnumDescriptions = [];
function $OGb(str) {
  return `\`#${str}#\``;
}
var $PGb = "colorThemeConfiguration";
var colorThemeSettingSchema = {
  type: "string",
  markdownDescription: localize(13277, null, $OGb(ThemeSettings.DETECT_COLOR_SCHEME)),
  default: $r ? ThemeSettingDefaults.COLOR_THEME_LIGHT : ThemeSettingDefaults.COLOR_THEME_DARK,
  tags: [$PGb],
  enum: colorThemeSettingEnum,
  enumDescriptions: colorThemeSettingEnumDescriptions,
  enumItemLabels: colorThemeSettingEnumItemLabels,
  errorMessage: localize(13278, null)
};
var preferredDarkThemeSettingSchema = {
  type: "string",
  //
  markdownDescription: localize(13279, null, $OGb(ThemeSettings.DETECT_COLOR_SCHEME)),
  default: ThemeSettingDefaults.COLOR_THEME_DARK,
  tags: [$PGb],
  enum: colorThemeSettingEnum,
  enumDescriptions: colorThemeSettingEnumDescriptions,
  enumItemLabels: colorThemeSettingEnumItemLabels,
  errorMessage: localize(13280, null)
};
var preferredLightThemeSettingSchema = {
  type: "string",
  markdownDescription: localize(13281, null, $OGb(ThemeSettings.DETECT_COLOR_SCHEME)),
  default: ThemeSettingDefaults.COLOR_THEME_LIGHT,
  tags: [$PGb],
  enum: colorThemeSettingEnum,
  enumDescriptions: colorThemeSettingEnumDescriptions,
  enumItemLabels: colorThemeSettingEnumItemLabels,
  errorMessage: localize(13282, null)
};
var preferredHCDarkThemeSettingSchema = {
  type: "string",
  markdownDescription: localize(13283, null, $OGb(ThemeSettings.DETECT_HC)),
  default: ThemeSettingDefaults.COLOR_THEME_HC_DARK,
  tags: [$PGb],
  enum: colorThemeSettingEnum,
  enumDescriptions: colorThemeSettingEnumDescriptions,
  enumItemLabels: colorThemeSettingEnumItemLabels,
  errorMessage: localize(13284, null)
};
var preferredHCLightThemeSettingSchema = {
  type: "string",
  markdownDescription: localize(13285, null, $OGb(ThemeSettings.DETECT_HC)),
  default: ThemeSettingDefaults.COLOR_THEME_HC_LIGHT,
  tags: [$PGb],
  enum: colorThemeSettingEnum,
  enumDescriptions: colorThemeSettingEnumDescriptions,
  enumItemLabels: colorThemeSettingEnumItemLabels,
  errorMessage: localize(13286, null)
};
var detectColorSchemeSettingSchema = {
  type: "boolean",
  markdownDescription: localize(13287, null, $OGb(ThemeSettings.PREFERRED_DARK_THEME), $OGb(ThemeSettings.PREFERRED_LIGHT_THEME)),
  default: false,
  tags: [$PGb]
};
var colorCustomizationsSchema = {
  type: "object",
  description: localize(13288, null),
  allOf: [{ $ref: $do }],
  default: {},
  defaultSnippets: [{
    body: {}
  }]
};
var fileIconThemeSettingSchema = {
  type: ["string", "null"],
  default: ThemeSettingDefaults.FILE_ICON_THEME,
  description: localize(13289, null),
  enum: [null],
  enumItemLabels: [localize(13290, null)],
  enumDescriptions: [localize(13291, null)],
  errorMessage: localize(13292, null)
};
var productIconThemeSettingSchema = {
  type: ["string", "null"],
  default: ThemeSettingDefaults.PRODUCT_ICON_THEME,
  description: localize(13293, null),
  enum: [ThemeSettingDefaults.PRODUCT_ICON_THEME],
  enumItemLabels: [localize(13294, null)],
  enumDescriptions: [localize(13295, null)],
  errorMessage: localize(13296, null)
};
var detectHCSchemeSettingSchema = {
  type: "boolean",
  default: true,
  markdownDescription: localize(13297, null, $OGb(ThemeSettings.PREFERRED_HC_DARK_THEME), $OGb(ThemeSettings.PREFERRED_HC_LIGHT_THEME)),
  scope: 1,
  tags: [$PGb]
};
var themeSettingsConfiguration = {
  id: "workbench",
  order: 7.1,
  type: "object",
  properties: {
    [ThemeSettings.COLOR_THEME]: colorThemeSettingSchema,
    [ThemeSettings.PREFERRED_DARK_THEME]: preferredDarkThemeSettingSchema,
    [ThemeSettings.PREFERRED_LIGHT_THEME]: preferredLightThemeSettingSchema,
    [ThemeSettings.PREFERRED_HC_DARK_THEME]: preferredHCDarkThemeSettingSchema,
    [ThemeSettings.PREFERRED_HC_LIGHT_THEME]: preferredHCLightThemeSettingSchema,
    [ThemeSettings.FILE_ICON_THEME]: fileIconThemeSettingSchema,
    [ThemeSettings.COLOR_CUSTOMIZATIONS]: colorCustomizationsSchema,
    [ThemeSettings.PRODUCT_ICON_THEME]: productIconThemeSettingSchema
  }
};
configurationRegistry7.registerConfiguration(themeSettingsConfiguration);
var themeSettingsWindowConfiguration = {
  id: "window",
  order: 8.1,
  type: "object",
  properties: {
    [ThemeSettings.DETECT_HC]: detectHCSchemeSettingSchema,
    [ThemeSettings.DETECT_COLOR_SCHEME]: detectColorSchemeSettingSchema
  }
};
configurationRegistry7.registerConfiguration(themeSettingsWindowConfiguration);
function tokenGroupSettings(description) {
  return {
    description,
    $ref: $KGb
  };
}
var themeSpecificSettingKey = "^\\[[^\\]]*(\\]\\s*\\[[^\\]]*)*\\]$";
var tokenColorSchema = {
  type: "object",
  properties: {
    comments: tokenGroupSettings(localize(13298, null)),
    strings: tokenGroupSettings(localize(13299, null)),
    keywords: tokenGroupSettings(localize(13300, null)),
    numbers: tokenGroupSettings(localize(13301, null)),
    types: tokenGroupSettings(localize(13302, null)),
    functions: tokenGroupSettings(localize(13303, null)),
    variables: tokenGroupSettings(localize(13304, null)),
    textMateRules: {
      description: localize(13305, null),
      $ref: $JGb
    },
    semanticHighlighting: {
      description: localize(13306, null),
      deprecationMessage: localize(13307, null),
      markdownDeprecationMessage: localize(13308, null, $OGb("editor.semanticTokenColorCustomizations")),
      type: "boolean"
    }
  },
  additionalProperties: false
};
var tokenColorCustomizationSchema = {
  description: localize(13309, null),
  default: {},
  allOf: [{ ...tokenColorSchema, patternProperties: { "^\\[": {} } }]
};
var semanticTokenColorSchema = {
  type: "object",
  properties: {
    enabled: {
      type: "boolean",
      description: localize(13310, null),
      suggestSortText: "0_enabled"
    },
    rules: {
      $ref: $Mlb,
      description: localize(13311, null),
      suggestSortText: "0_rules"
    }
  },
  additionalProperties: false
};
var semanticTokenColorCustomizationSchema = {
  description: localize(13312, null),
  default: {},
  allOf: [{ ...semanticTokenColorSchema, patternProperties: { "^\\[": {} } }]
};
var tokenColorCustomizationConfiguration = {
  id: "editor",
  order: 7.2,
  type: "object",
  properties: {
    [ThemeSettings.TOKEN_COLOR_CUSTOMIZATIONS]: tokenColorCustomizationSchema,
    [ThemeSettings.SEMANTIC_TOKEN_COLOR_CUSTOMIZATIONS]: semanticTokenColorCustomizationSchema
  }
};
configurationRegistry7.registerConfiguration(tokenColorCustomizationConfiguration);
function $QGb(themes) {
  themes.sort((a, b) => a.label.localeCompare(b.label));
  colorThemeSettingEnum.splice(0, colorThemeSettingEnum.length, ...themes.map((t) => t.settingsId));
  colorThemeSettingEnumDescriptions.splice(0, colorThemeSettingEnumDescriptions.length, ...themes.map((t) => t.description || ""));
  colorThemeSettingEnumItemLabels.splice(0, colorThemeSettingEnumItemLabels.length, ...themes.map((t) => t.label || ""));
  const themeSpecificWorkbenchColors = { properties: {} };
  const themeSpecificTokenColors = { properties: {} };
  const themeSpecificSemanticTokenColors = { properties: {} };
  const workbenchColors = { $ref: $do, additionalProperties: false };
  const tokenColors = { properties: tokenColorSchema.properties, additionalProperties: false };
  for (const t of themes) {
    const themeId = `[${t.settingsId}]`;
    themeSpecificWorkbenchColors.properties[themeId] = workbenchColors;
    themeSpecificTokenColors.properties[themeId] = tokenColors;
    themeSpecificSemanticTokenColors.properties[themeId] = semanticTokenColorSchema;
  }
  themeSpecificWorkbenchColors.patternProperties = { [themeSpecificSettingKey]: workbenchColors };
  themeSpecificTokenColors.patternProperties = { [themeSpecificSettingKey]: tokenColors };
  themeSpecificSemanticTokenColors.patternProperties = { [themeSpecificSettingKey]: semanticTokenColorSchema };
  colorCustomizationsSchema.allOf[1] = themeSpecificWorkbenchColors;
  tokenColorCustomizationSchema.allOf[1] = themeSpecificTokenColors;
  semanticTokenColorCustomizationSchema.allOf[1] = themeSpecificSemanticTokenColors;
  configurationRegistry7.notifyConfigurationSchemaUpdated(themeSettingsConfiguration, tokenColorCustomizationConfiguration);
}
function $RGb(themes) {
  fileIconThemeSettingSchema.enum.splice(1, Number.MAX_VALUE, ...themes.map((t) => t.settingsId));
  fileIconThemeSettingSchema.enumItemLabels.splice(1, Number.MAX_VALUE, ...themes.map((t) => t.label));
  fileIconThemeSettingSchema.enumDescriptions.splice(1, Number.MAX_VALUE, ...themes.map((t) => t.description || ""));
  configurationRegistry7.notifyConfigurationSchemaUpdated(themeSettingsConfiguration);
}
function $SGb(themes) {
  productIconThemeSettingSchema.enum.splice(1, Number.MAX_VALUE, ...themes.map((t) => t.settingsId));
  productIconThemeSettingSchema.enumItemLabels.splice(1, Number.MAX_VALUE, ...themes.map((t) => t.label));
  productIconThemeSettingSchema.enumDescriptions.splice(1, Number.MAX_VALUE, ...themes.map((t) => t.description || ""));
  configurationRegistry7.notifyConfigurationSchemaUpdated(themeSettingsConfiguration);
}
var colorSchemeToPreferred = {
  [ColorScheme.DARK]: ThemeSettings.PREFERRED_DARK_THEME,
  [ColorScheme.LIGHT]: ThemeSettings.PREFERRED_LIGHT_THEME,
  [ColorScheme.HIGH_CONTRAST_DARK]: ThemeSettings.PREFERRED_HC_DARK_THEME,
  [ColorScheme.HIGH_CONTRAST_LIGHT]: ThemeSettings.PREFERRED_HC_LIGHT_THEME
};
var $TGb = class {
  constructor(c, d) {
    this.c = c;
    this.d = d;
  }
  get colorTheme() {
    return this.c.getValue(this.getColorThemeSettingId());
  }
  get fileIconTheme() {
    return this.c.getValue(ThemeSettings.FILE_ICON_THEME);
  }
  get productIconTheme() {
    return this.c.getValue(ThemeSettings.PRODUCT_ICON_THEME);
  }
  get colorCustomizations() {
    return this.c.getValue(ThemeSettings.COLOR_CUSTOMIZATIONS) || {};
  }
  get tokenColorCustomizations() {
    return this.c.getValue(ThemeSettings.TOKEN_COLOR_CUSTOMIZATIONS) || {};
  }
  get semanticTokenColorCustomizations() {
    return this.c.getValue(ThemeSettings.SEMANTIC_TOKEN_COLOR_CUSTOMIZATIONS);
  }
  getPreferredColorScheme() {
    if (this.c.getValue(ThemeSettings.DETECT_HC) && this.d.highContrast) {
      return this.d.dark ? ColorScheme.HIGH_CONTRAST_DARK : ColorScheme.HIGH_CONTRAST_LIGHT;
    }
    if (this.c.getValue(ThemeSettings.DETECT_COLOR_SCHEME)) {
      return this.d.dark ? ColorScheme.DARK : ColorScheme.LIGHT;
    }
    return void 0;
  }
  isDetectingColorScheme() {
    return this.c.getValue(ThemeSettings.DETECT_COLOR_SCHEME);
  }
  getColorThemeSettingId() {
    const preferredScheme = this.getPreferredColorScheme();
    return preferredScheme ? colorSchemeToPreferred[preferredScheme] : ThemeSettings.COLOR_THEME;
  }
  async setColorTheme(theme, settingsTarget) {
    await this.e(this.getColorThemeSettingId(), theme.settingsId, settingsTarget);
    return theme;
  }
  async setFileIconTheme(theme, settingsTarget) {
    await this.e(ThemeSettings.FILE_ICON_THEME, theme.settingsId, settingsTarget);
    return theme;
  }
  async setProductIconTheme(theme, settingsTarget) {
    await this.e(ThemeSettings.PRODUCT_ICON_THEME, theme.settingsId, settingsTarget);
    return theme;
  }
  isDefaultColorTheme() {
    const settings = this.c.inspect(this.getColorThemeSettingId());
    return settings && settings.default?.value === settings.value;
  }
  findAutoConfigurationTarget(key2) {
    const settings = this.c.inspect(key2);
    if (!$Gg(settings.workspaceFolderValue)) {
      return 6;
    } else if (!$Gg(settings.workspaceValue)) {
      return 5;
    } else if (!$Gg(settings.userRemote)) {
      return 4;
    }
    return 2;
  }
  async e(key2, value, settingsTarget) {
    if (settingsTarget === void 0 || settingsTarget === "preview") {
      return;
    }
    const settings = this.c.inspect(key2);
    if (settingsTarget === "auto") {
      return this.c.updateValue(key2, value);
    }
    if (settingsTarget === 2) {
      if (value === settings.userValue) {
        return Promise.resolve(void 0);
      } else if (value === settings.defaultValue) {
        if ($Gg(settings.userValue)) {
          return Promise.resolve(void 0);
        }
        value = void 0;
      }
    } else if (settingsTarget === 5 || settingsTarget === 6 || settingsTarget === 4) {
      if (value === settings.value) {
        return Promise.resolve(void 0);
      }
    }
    return this.c.updateValue(key2, value, settingsTarget);
  }
};

// out-build/vs/workbench/services/themes/browser/productIconThemeData.js
var $7Vb = "";
var $8Vb = class _$8Vb {
  static {
    this.STORAGE_KEY = "productIconThemeData";
  }
  constructor(id2, label3, settingsId) {
    this.iconThemeDocument = { iconDefinitions: /* @__PURE__ */ new Map() };
    this.id = id2;
    this.label = label3;
    this.settingsId = settingsId;
    this.isLoaded = false;
  }
  getIcon(iconContribution) {
    return _resolveIconDefinition(iconContribution, this.iconThemeDocument);
  }
  ensureLoaded(fileService, logService) {
    return !this.isLoaded ? this.a(fileService, logService) : Promise.resolve(this.styleSheetContent);
  }
  reload(fileService, logService) {
    return this.a(fileService, logService);
  }
  async a(fileService, logService) {
    const location3 = this.location;
    if (!location3) {
      return Promise.resolve(this.styleSheetContent);
    }
    const warnings = [];
    this.iconThemeDocument = await _loadProductIconThemeDocument(fileService, location3, warnings);
    this.isLoaded = true;
    if (warnings.length) {
      logService.error(localize(13158, null, location3.toString(), warnings.join("\n")));
    }
    return this.styleSheetContent;
  }
  static fromExtensionTheme(iconTheme, iconThemeLocation, extensionData) {
    const id2 = extensionData.extensionId + "-" + iconTheme.id;
    const label3 = iconTheme.label || $rc(iconTheme.path);
    const settingsId = iconTheme.id;
    const themeData = new _$8Vb(id2, label3, settingsId);
    themeData.description = iconTheme.description;
    themeData.location = iconThemeLocation;
    themeData.extensionData = extensionData;
    themeData.watch = iconTheme._watch;
    themeData.isLoaded = false;
    return themeData;
  }
  static createUnloadedTheme(id2) {
    const themeData = new _$8Vb(id2, "", "__" + id2);
    themeData.isLoaded = false;
    themeData.extensionData = void 0;
    themeData.watch = false;
    return themeData;
  }
  static {
    this.b = null;
  }
  static get defaultTheme() {
    let themeData = _$8Vb.b;
    if (!themeData) {
      themeData = _$8Vb.b = new _$8Vb($7Vb, localize(13159, null), ThemeSettingDefaults.PRODUCT_ICON_THEME);
      themeData.isLoaded = true;
      themeData.extensionData = void 0;
      themeData.watch = false;
    }
    return themeData;
  }
  static fromStorageData(storageService) {
    const input = storageService.get(
      _$8Vb.STORAGE_KEY,
      0
      /* StorageScope.PROFILE */
    );
    if (!input) {
      return void 0;
    }
    try {
      const data = JSON.parse(input);
      const theme = new _$8Vb("", "", "");
      for (const key2 in data) {
        switch (key2) {
          case "id":
          case "label":
          case "description":
          case "settingsId":
          case "styleSheetContent":
          case "watch":
            theme[key2] = data[key2];
            break;
          case "location":
            break;
          case "extensionData":
            theme.extensionData = ExtensionData.fromJSONObject(data.extensionData);
            break;
        }
      }
      const { iconDefinitions, iconFontDefinitions } = data;
      if (Array.isArray(iconDefinitions) && $Bg(iconFontDefinitions)) {
        const restoredIconDefinitions = /* @__PURE__ */ new Map();
        for (const entry of iconDefinitions) {
          const { id: id2, fontCharacter, fontId } = entry;
          if ($zg(id2) && $zg(fontCharacter)) {
            if ($zg(fontId)) {
              const iconFontDefinition = IconFontDefinition.fromJSONObject(iconFontDefinitions[fontId]);
              if (iconFontDefinition) {
                restoredIconDefinitions.set(id2, { fontCharacter, font: { id: fontId, definition: iconFontDefinition } });
              }
            } else {
              restoredIconDefinitions.set(id2, { fontCharacter });
            }
          }
        }
        theme.iconThemeDocument = { iconDefinitions: restoredIconDefinitions };
      }
      return theme;
    } catch (e) {
      return void 0;
    }
  }
  toStorage(storageService) {
    const iconDefinitions = [];
    const iconFontDefinitions = {};
    for (const entry of this.iconThemeDocument.iconDefinitions.entries()) {
      const font = entry[1].font;
      iconDefinitions.push({ id: entry[0], fontCharacter: entry[1].fontCharacter, fontId: font?.id });
      if (font && iconFontDefinitions[font.id] === void 0) {
        iconFontDefinitions[font.id] = IconFontDefinition.toJSONObject(font.definition);
      }
    }
    const data = JSON.stringify({
      id: this.id,
      label: this.label,
      description: this.description,
      settingsId: this.settingsId,
      styleSheetContent: this.styleSheetContent,
      watch: this.watch,
      extensionData: ExtensionData.toJSONObject(this.extensionData),
      iconDefinitions,
      iconFontDefinitions
    });
    storageService.store(
      _$8Vb.STORAGE_KEY,
      data,
      0,
      1
      /* StorageTarget.MACHINE */
    );
  }
};
function _loadProductIconThemeDocument(fileService, location3, warnings) {
  return fileService.readExtensionResource(location3).then((content) => {
    const parseErrors = [];
    const contentValue = $yw(content, parseErrors);
    if (parseErrors.length > 0) {
      return Promise.reject(new Error(localize(13160, null, parseErrors.map((e) => $SA(e.error)).join(", "))));
    } else if ($Gw(contentValue) !== "object") {
      return Promise.reject(new Error(localize(13161, null)));
    } else if (!contentValue.iconDefinitions || !Array.isArray(contentValue.fonts) || !contentValue.fonts.length) {
      return Promise.reject(new Error(localize(13162, null)));
    }
    const iconThemeDocumentLocationDirname = $uh(location3);
    const sanitizedFonts = /* @__PURE__ */ new Map();
    for (const font of contentValue.fonts) {
      const fontId = font.id;
      if ($zg(fontId) && fontId.match($zlb)) {
        let fontWeight = void 0;
        if ($zg(font.weight) && font.weight.match($Blb)) {
          fontWeight = font.weight;
        } else {
          warnings.push(localize(13163, null, font.id));
        }
        let fontStyle = void 0;
        if ($zg(font.style) && font.style.match($Alb)) {
          fontStyle = font.style;
        } else {
          warnings.push(localize(13164, null, font.id));
        }
        const sanitizedSrc = [];
        if (Array.isArray(font.src)) {
          for (const s of font.src) {
            if ($zg(s.path) && $zg(s.format) && s.format.match($Dlb)) {
              const iconFontLocation = $vh(iconThemeDocumentLocationDirname, s.path);
              sanitizedSrc.push({ location: iconFontLocation, format: s.format });
            } else {
              warnings.push(localize(13165, null, font.id));
            }
          }
        }
        if (sanitizedSrc.length) {
          sanitizedFonts.set(fontId, { weight: fontWeight, style: fontStyle, src: sanitizedSrc });
        } else {
          warnings.push(localize(13166, null, font.id));
        }
      } else {
        warnings.push(localize(13167, null, font.id));
      }
    }
    const iconDefinitions = /* @__PURE__ */ new Map();
    const primaryFontId = contentValue.fonts[0].id;
    for (const iconId in contentValue.iconDefinitions) {
      const definition = contentValue.iconDefinitions[iconId];
      if ($zg(definition.fontCharacter) && definition.fontCharacter.match($Elb)) {
        const fontId = definition.fontId ?? primaryFontId;
        const fontDefinition = sanitizedFonts.get(fontId);
        if (fontDefinition) {
          const font = { id: `pi-${fontId}`, definition: fontDefinition };
          iconDefinitions.set(iconId, { fontCharacter: definition.fontCharacter, font });
        } else {
          warnings.push(localize(13168, null, iconId));
        }
      } else {
        warnings.push(localize(13169, null, iconId));
      }
    }
    return { iconDefinitions };
  });
}
var iconRegistry3 = $0r();
function _resolveIconDefinition(iconContribution, iconThemeDocument) {
  const iconDefinitions = iconThemeDocument.iconDefinitions;
  let definition = iconDefinitions.get(iconContribution.id);
  let defaults = iconContribution.defaults;
  while (!definition && ThemeIcon.isThemeIcon(defaults)) {
    const ic = iconRegistry3.getIcon(defaults.id);
    if (ic) {
      definition = iconDefinitions.get(ic.id);
      defaults = ic.defaults;
    } else {
      return void 0;
    }
  }
  if (definition) {
    return definition;
  }
  if (!ThemeIcon.isThemeIcon(defaults)) {
    return defaults;
  }
  return void 0;
}

// out-build/vs/workbench/services/themes/common/hostColorSchemeService.js
var $NGb = $Qk("hostColorSchemeService");

// out-build/vs/workbench/services/userData/browser/userDataInit.js
var $9Vb = $Qk("IUserDataInitializationService");
var $0Vb = class {
  constructor(a = []) {
    this.a = a;
  }
  async whenInitializationFinished() {
    if (await this.requiresInitialization()) {
      await Promise.all(this.a.map((initializer) => initializer.whenInitializationFinished()));
    }
  }
  async requiresInitialization() {
    return (await Promise.all(this.a.map((initializer) => initializer.requiresInitialization()))).some((result) => result);
  }
  async initializeRequiredResources() {
    if (await this.requiresInitialization()) {
      await Promise.all(this.a.map((initializer) => initializer.initializeRequiredResources()));
    }
  }
  async initializeOtherResources(instantiationService) {
    if (await this.requiresInitialization()) {
      await Promise.all(this.a.map((initializer) => initializer.initializeOtherResources(instantiationService)));
    }
  }
  async initializeInstalledExtensions(instantiationService) {
    if (await this.requiresInitialization()) {
      await Promise.all(this.a.map((initializer) => initializer.initializeInstalledExtensions(instantiationService)));
    }
  }
};
var InitializeOtherResourcesContribution = class InitializeOtherResourcesContribution2 {
  constructor(userDataInitializeService, instantiationService, extensionService) {
    extensionService.whenInstalledExtensionsRegistered().then(() => this.a(userDataInitializeService, instantiationService));
  }
  async a(userDataInitializeService, instantiationService) {
    if (await userDataInitializeService.requiresInitialization()) {
      $S("code/willInitOtherUserData");
      await userDataInitializeService.initializeOtherResources(instantiationService);
      $S("code/didInitOtherUserData");
    }
  }
};
InitializeOtherResourcesContribution = __decorate([
  __param(0, $9Vb),
  __param(1, $Pk),
  __param(2, $wN)
], InitializeOtherResourcesContribution);
if ($r) {
  const workbenchRegistry10 = $Wn.as(Extensions2.Workbench);
  workbenchRegistry10.registerWorkbenchContribution(
    InitializeOtherResourcesContribution,
    3
    /* LifecyclePhase.Restored */
  );
}

// out-build/vs/platform/theme/browser/iconsStyleSheet.js
function $$Vb(themeService) {
  const disposable = new $2c();
  const onDidChangeEmmiter = disposable.add(new $ze());
  const iconRegistry4 = $0r();
  disposable.add(iconRegistry4.onDidChange(() => onDidChangeEmmiter.fire()));
  if (themeService) {
    disposable.add(themeService.onDidProductIconThemeChange(() => onDidChangeEmmiter.fire()));
  }
  return {
    dispose: () => disposable.dispose(),
    onDidChange: onDidChangeEmmiter.event,
    getCSS() {
      const productIconTheme = themeService ? themeService.getProductIconTheme() : new $_Vb();
      const usedFontIds = {};
      const rules = new $8Z();
      const rootAttribs = new $8Z();
      for (const contribution of iconRegistry4.getIcons()) {
        const definition = productIconTheme.getIcon(contribution);
        if (!definition) {
          continue;
        }
        const fontContribution = definition.font;
        const fontFamilyVar = $7Z`--vscode-icon-${$6Z(contribution.id)}-font-family`;
        const contentVar = $7Z`--vscode-icon-${$6Z(contribution.id)}-content`;
        if (fontContribution) {
          usedFontIds[fontContribution.id] = fontContribution.definition;
          rootAttribs.push($7Z`${fontFamilyVar}: ${$4Z(fontContribution.id)};`, $7Z`${contentVar}: ${$4Z(definition.fontCharacter)};`);
          rules.push($7Z`.codicon-${$6Z(contribution.id)}:before { content: ${$4Z(definition.fontCharacter)}; font-family: ${$4Z(fontContribution.id)}; }`);
        } else {
          rootAttribs.push($7Z`${contentVar}: ${$4Z(definition.fontCharacter)}; ${fontFamilyVar}: 'codicon';`);
          rules.push($7Z`.codicon-${$6Z(contribution.id)}:before { content: ${$4Z(definition.fontCharacter)}; }`);
        }
      }
      for (const id2 in usedFontIds) {
        const definition = usedFontIds[id2];
        const fontWeight = definition.weight ? $7Z`font-weight: ${$3Z(definition.weight)};` : $7Z``;
        const fontStyle = definition.style ? $7Z`font-style: ${$3Z(definition.style)};` : $7Z``;
        const src = new $8Z();
        for (const l of definition.src) {
          src.push($7Z`${$5Z(l.location)} format(${$4Z(l.format)})`);
        }
        rules.push($7Z`@font-face { src: ${src.join(", ")}; font-family: ${$4Z(id2)};${fontWeight}${fontStyle} font-display: block; }`);
      }
      rules.push($7Z`:root { ${rootAttribs.join(" ")} }`);
      return rules.join("\n");
    }
  };
}
var $_Vb = class {
  getIcon(contribution) {
    const iconRegistry4 = $0r();
    let definition = contribution.defaults;
    while (ThemeIcon.isThemeIcon(definition)) {
      const c = iconRegistry4.getIcon(definition.id);
      if (!c) {
        return void 0;
      }
      definition = c.defaults;
    }
    return definition;
  }
};

// out-build/vs/workbench/services/themes/browser/workbenchThemeService.js
var defaultThemeExtensionId = "vscode-theme-defaults";
var DEFAULT_FILE_ICON_THEME_ID = "vscode.vscode-theme-seti-vs-seti";
var fileIconsEnabledClass = "file-icons-enabled";
var colorThemeRulesClassName = "contributedColorTheme";
var fileIconThemeRulesClassName = "contributedFileIconTheme";
var productIconThemeRulesClassName = "contributedProductIconTheme";
var themingRegistry2 = $Wn.as($ls.ThemingContribution);
function validateThemeId(theme) {
  switch (theme) {
    case $swb:
      return `vs ${defaultThemeExtensionId}-themes-light_vs-json`;
    case $twb:
      return `vs-dark ${defaultThemeExtensionId}-themes-dark_vs-json`;
    case $uwb:
      return `hc-black ${defaultThemeExtensionId}-themes-hc_black-json`;
    case $vwb:
      return `hc-light ${defaultThemeExtensionId}-themes-hc_light-json`;
  }
  return theme;
}
var colorThemesExtPoint = $3Vb();
var fileIconThemesExtPoint = $4Vb();
var productIconThemesExtPoint = $5Vb();
var $aWb = class $aWb2 extends $3c {
  constructor(extensionService, I, J, L, M, fileService, N, layoutService, O, P, Q, R) {
    super();
    this.I = I;
    this.J = J;
    this.L = L;
    this.M = M;
    this.N = N;
    this.O = O;
    this.P = P;
    this.Q = Q;
    this.R = R;
    this.H = false;
    this.bb = /* @__PURE__ */ new Map();
    this.a = layoutService.mainContainer;
    this.b = new $TGb(J, P);
    this.c = this.B(new $6Vb(colorThemesExtPoint, $5Gb.fromExtensionTheme));
    this.h = this.B(new ThemeFileWatcher(fileService, M, this.Z.bind(this)));
    this.g = new $ze({ leakWarningThreshold: 400 });
    this.f = $5Gb.createUnloadedTheme("");
    this.m = new $Qh();
    this.w = this.B(new ThemeFileWatcher(fileService, M, this.eb.bind(this)));
    this.n = this.B(new $6Vb(fileIconThemesExtPoint, $1Vb.fromExtensionTheme, true, $1Vb.noIconTheme));
    this.u = new $2Vb(N, R);
    this.s = new $ze({ leakWarningThreshold: 400 });
    this.r = $1Vb.createUnloadedTheme("");
    this.y = new $Qh();
    this.F = this.B(new ThemeFileWatcher(fileService, M, this.hb.bind(this)));
    this.z = this.B(new $6Vb(productIconThemesExtPoint, $8Vb.fromExtensionTheme, true, $8Vb.defaultTheme));
    this.D = new $ze();
    this.C = $8Vb.createUnloadedTheme("");
    this.G = new $Qh();
    this.B(this.onDidColorThemeChange((theme) => $6n().notifyThemeUpdate(theme)));
    let themeData = $5Gb.fromStorageData(this.I);
    const colorThemeSetting = this.b.colorTheme;
    if (themeData && colorThemeSetting !== themeData.settingsId && this.b.isDefaultColorTheme()) {
      this.H = themeData.settingsId === ThemeSettingDefaults.COLOR_THEME_DARK_OLD || themeData.settingsId === ThemeSettingDefaults.COLOR_THEME_LIGHT_OLD;
      themeData = void 0;
    }
    const defaultColorMap = colorThemeSetting === ThemeSettingDefaults.COLOR_THEME_LIGHT ? $Bwb : colorThemeSetting === ThemeSettingDefaults.COLOR_THEME_DARK ? $Awb : void 0;
    if (!themeData) {
      const initialColorTheme = M.options?.initialColorTheme;
      if (initialColorTheme) {
        themeData = $5Gb.createUnloadedThemeForThemeType(initialColorTheme.themeType, initialColorTheme.colors ?? defaultColorMap);
      }
    }
    if (!themeData) {
      themeData = $5Gb.createUnloadedThemeForThemeType($r ? ColorScheme.LIGHT : ColorScheme.DARK, defaultColorMap);
    }
    themeData.setCustomizations(this.b);
    this.ab(themeData, void 0, true);
    const fileIconData = $1Vb.fromStorageData(this.I);
    if (fileIconData) {
      this.fb(fileIconData, true);
    }
    const productIconData = $8Vb.fromStorageData(this.I);
    if (productIconData) {
      this.ib(productIconData, true);
    }
    extensionService.whenInstalledExtensionsRegistered().then((_) => {
      this.U();
      this.X();
      this.W();
      this.S().catch($gb);
    });
    const codiconStyleSheet = $VZ();
    codiconStyleSheet.id = "codiconStyles";
    const iconsStyleSheet = this.B($$Vb(this));
    function updateAll() {
      codiconStyleSheet.textContent = iconsStyleSheet.getCSS();
    }
    const delayer4 = this.B(new $8h(updateAll, 0));
    this.B(iconsStyleSheet.onDidChange(() => delayer4.schedule()));
    delayer4.schedule();
  }
  S() {
    const extDevLocs = this.M.extensionDevelopmentLocationURI;
    const extDevLoc = extDevLocs && extDevLocs.length === 1 ? extDevLocs[0] : void 0;
    const initializeColorTheme = async () => {
      const devThemes = this.c.findThemeByExtensionLocation(extDevLoc);
      if (devThemes.length) {
        const matchedColorTheme = devThemes.find((theme2) => theme2.type === this.f.type);
        return this.setColorTheme(matchedColorTheme ? matchedColorTheme.id : devThemes[0].id, void 0);
      }
      let theme = this.c.findThemeBySettingsId(this.b.colorTheme, void 0);
      if (!theme) {
        await this.Q.whenInitializationFinished();
        const fallbackTheme = this.f.type === ColorScheme.LIGHT ? ThemeSettingDefaults.COLOR_THEME_LIGHT : ThemeSettingDefaults.COLOR_THEME_DARK;
        theme = this.c.findThemeBySettingsId(this.b.colorTheme, fallbackTheme);
      }
      return this.setColorTheme(theme && theme.id, void 0);
    };
    const initializeFileIconTheme = async () => {
      const devThemes = this.n.findThemeByExtensionLocation(extDevLoc);
      if (devThemes.length) {
        return this.setFileIconTheme(
          devThemes[0].id,
          8
          /* ConfigurationTarget.MEMORY */
        );
      }
      let theme = this.n.findThemeBySettingsId(this.b.fileIconTheme);
      if (!theme) {
        await this.Q.whenInitializationFinished();
        theme = this.n.findThemeBySettingsId(this.b.fileIconTheme);
      }
      return this.setFileIconTheme(theme ? theme.id : DEFAULT_FILE_ICON_THEME_ID, void 0);
    };
    const initializeProductIconTheme = async () => {
      const devThemes = this.z.findThemeByExtensionLocation(extDevLoc);
      if (devThemes.length) {
        return this.setProductIconTheme(
          devThemes[0].id,
          8
          /* ConfigurationTarget.MEMORY */
        );
      }
      let theme = this.z.findThemeBySettingsId(this.b.productIconTheme);
      if (!theme) {
        await this.Q.whenInitializationFinished();
        theme = this.z.findThemeBySettingsId(this.b.productIconTheme);
      }
      return this.setProductIconTheme(theme ? theme.id : $7Vb, void 0);
    };
    return Promise.all([initializeColorTheme(), initializeFileIconTheme(), initializeProductIconTheme()]);
  }
  U() {
    this.B(this.J.onDidChangeConfiguration((e) => {
      if (e.affectsConfiguration(ThemeSettings.COLOR_THEME) || e.affectsConfiguration(ThemeSettings.PREFERRED_DARK_THEME) || e.affectsConfiguration(ThemeSettings.PREFERRED_LIGHT_THEME) || e.affectsConfiguration(ThemeSettings.PREFERRED_HC_DARK_THEME) || e.affectsConfiguration(ThemeSettings.PREFERRED_HC_LIGHT_THEME) || e.affectsConfiguration(ThemeSettings.DETECT_COLOR_SCHEME) || e.affectsConfiguration(ThemeSettings.DETECT_HC) || e.affectsConfiguration(ThemeSettings.SYSTEM_COLOR_THEME)) {
        this.restoreColorTheme();
      }
      if (e.affectsConfiguration(ThemeSettings.FILE_ICON_THEME)) {
        this.restoreFileIconTheme();
      }
      if (e.affectsConfiguration(ThemeSettings.PRODUCT_ICON_THEME)) {
        this.restoreProductIconTheme();
      }
      if (this.f) {
        let hasColorChanges = false;
        if (e.affectsConfiguration(ThemeSettings.COLOR_CUSTOMIZATIONS)) {
          this.f.setCustomColors(this.b.colorCustomizations);
          hasColorChanges = true;
        }
        if (e.affectsConfiguration(ThemeSettings.TOKEN_COLOR_CUSTOMIZATIONS)) {
          this.f.setCustomTokenColors(this.b.tokenColorCustomizations);
          hasColorChanges = true;
        }
        if (e.affectsConfiguration(ThemeSettings.SEMANTIC_TOKEN_COLOR_CUSTOMIZATIONS)) {
          this.f.setCustomSemanticTokenColors(this.b.semanticTokenColorCustomizations);
          hasColorChanges = true;
        }
        if (hasColorChanges) {
          this.$(this.f);
          this.g.fire(this.f);
        }
      }
    }));
  }
  W() {
    let prevColorId = void 0;
    this.B(this.c.onDidChange(async (event) => {
      $QGb(event.themes);
      if (await this.restoreColorTheme()) {
        if (this.f.settingsId === ThemeSettingDefaults.COLOR_THEME_DARK && !$Gg(prevColorId) && await this.c.findThemeById(prevColorId)) {
          await this.setColorTheme(prevColorId, "auto");
          prevColorId = void 0;
        } else if (event.added.some((t) => t.settingsId === this.f.settingsId)) {
          await this.Z();
        }
      } else if (event.removed.some((t) => t.settingsId === this.f.settingsId)) {
        prevColorId = this.f.id;
        const defaultTheme = this.c.findThemeBySettingsId(ThemeSettingDefaults.COLOR_THEME_DARK);
        await this.setColorTheme(defaultTheme, "auto");
      }
    }));
    let prevFileIconId = void 0;
    this.B(this.B(this.n.onDidChange(async (event) => {
      $RGb(event.themes);
      if (await this.restoreFileIconTheme()) {
        if (this.r.id === DEFAULT_FILE_ICON_THEME_ID && !$Gg(prevFileIconId) && this.n.findThemeById(prevFileIconId)) {
          await this.setFileIconTheme(prevFileIconId, "auto");
          prevFileIconId = void 0;
        } else if (event.added.some((t) => t.settingsId === this.r.settingsId)) {
          await this.eb();
        }
      } else if (event.removed.some((t) => t.settingsId === this.r.settingsId)) {
        prevFileIconId = this.r.id;
        await this.setFileIconTheme(DEFAULT_FILE_ICON_THEME_ID, "auto");
      }
    })));
    let prevProductIconId = void 0;
    this.B(this.z.onDidChange(async (event) => {
      $SGb(event.themes);
      if (await this.restoreProductIconTheme()) {
        if (this.C.id === $7Vb && !$Gg(prevProductIconId) && this.z.findThemeById(prevProductIconId)) {
          await this.setProductIconTheme(prevProductIconId, "auto");
          prevProductIconId = void 0;
        } else if (event.added.some((t) => t.settingsId === this.C.settingsId)) {
          await this.hb();
        }
      } else if (event.removed.some((t) => t.settingsId === this.C.settingsId)) {
        prevProductIconId = this.C.id;
        await this.setProductIconTheme($7Vb, "auto");
      }
    }));
    this.B(this.R.onDidChange(() => this.eb()));
    return Promise.all([this.getColorThemes(), this.getFileIconThemes(), this.getProductIconThemes()]).then(([ct, fit, pit]) => {
      $QGb(ct);
      $RGb(fit);
      $SGb(pit);
    });
  }
  // preferred scheme handling
  X() {
    this.B(this.P.onDidChangeColorScheme(() => {
      if (this.b.isDetectingColorScheme()) {
        this.restoreColorTheme();
      }
    }));
  }
  hasUpdatedDefaultThemes() {
    return this.H;
  }
  getColorTheme() {
    return this.f;
  }
  async getColorThemes() {
    return this.c.getThemes();
  }
  getPreferredColorScheme() {
    return this.b.getPreferredColorScheme();
  }
  async getMarketplaceColorThemes(publisher, name, version2) {
    const extensionLocation = this.N.getExtensionGalleryResourceURL({ publisher, name, version: version2 }, "extension");
    if (extensionLocation) {
      try {
        const manifestContent = await this.N.readExtensionResource($vh(extensionLocation, "package.json"));
        return this.c.getMarketplaceThemes(JSON.parse(manifestContent), extensionLocation, ExtensionData.fromName(publisher, name));
      } catch (e) {
        this.O.error("Problem loading themes from marketplace", e);
      }
    }
    return [];
  }
  get onDidColorThemeChange() {
    return this.g.event;
  }
  setColorTheme(themeIdOrTheme, settingsTarget) {
    return this.m.queue(async () => {
      return this.Y(themeIdOrTheme, settingsTarget);
    });
  }
  async Y(themeIdOrTheme, settingsTarget) {
    if (!themeIdOrTheme) {
      return null;
    }
    const themeId = $zg(themeIdOrTheme) ? validateThemeId(themeIdOrTheme) : themeIdOrTheme.id;
    if (this.f.isLoaded && themeId === this.f.id) {
      if (settingsTarget !== "preview") {
        this.f.toStorage(this.I);
      }
      return this.b.setColorTheme(this.f, settingsTarget);
    }
    let themeData = this.c.findThemeById(themeId);
    if (!themeData) {
      if (themeIdOrTheme instanceof $5Gb) {
        themeData = themeIdOrTheme;
      } else {
        return null;
      }
    }
    try {
      await themeData.ensureLoaded(this.N);
      themeData.setCustomizations(this.b);
      return this.ab(themeData, settingsTarget);
    } catch (error) {
      throw new Error(localize(13170, null, themeData.location?.toString(), error.message));
    }
  }
  Z() {
    return this.m.queue(async () => {
      try {
        const theme = this.c.findThemeBySettingsId(this.f.settingsId) || this.f;
        await theme.reload(this.N);
        theme.setCustomizations(this.b);
        await this.ab(theme, void 0, false);
      } catch (error) {
        this.O.info("Unable to reload {0}: {1}", this.f.location?.toString());
      }
    });
  }
  async restoreColorTheme() {
    return this.m.queue(async () => {
      const settingId = this.b.colorTheme;
      const theme = this.c.findThemeBySettingsId(settingId);
      if (theme) {
        if (settingId !== this.f.settingsId) {
          await this.Y(theme.id, void 0);
        } else if (theme !== this.f) {
          await theme.ensureLoaded(this.N);
          theme.setCustomizations(this.b);
          await this.ab(theme, void 0, true);
        }
        return true;
      }
      return false;
    });
  }
  $(themeData) {
    const cssRules = /* @__PURE__ */ new Set();
    const ruleCollector = {
      addRule: (rule) => {
        if (!cssRules.has(rule)) {
          cssRules.add(rule);
        }
      }
    };
    ruleCollector.addRule(`.monaco-workbench { forced-color-adjust: none; }`);
    themingRegistry2.getThemingParticipants().forEach((p) => p(themeData, ruleCollector, this.M));
    const colorVariables = [];
    for (const item of $6n().getColors()) {
      const color2 = themeData.getColor(item.id, true);
      if (color2) {
        colorVariables.push(`${$Yn(item.id)}: ${color2.toString()};`);
      }
    }
    ruleCollector.addRule(`.monaco-workbench { ${colorVariables.join("\n")} }`);
    _applyRules([...cssRules].join("\n"), colorThemeRulesClassName);
  }
  ab(newTheme, settingsTarget, silent = false) {
    this.$(newTheme);
    if (this.f.id) {
      this.a.classList.remove(...this.f.classNames);
    } else {
      this.a.classList.remove($twb, $swb, $uwb, $vwb);
    }
    this.a.classList.add(...newTheme.classNames);
    this.f.clearCaches();
    this.f = newTheme;
    if (!this.j) {
      this.j = themingRegistry2.onThemingParticipantAdded((_) => this.$(this.f));
    }
    this.h.update(newTheme);
    this.cb(newTheme.id, newTheme.extensionData, "color");
    if (silent) {
      return Promise.resolve(null);
    }
    this.g.fire(this.f);
    if (newTheme.isLoaded && settingsTarget !== "preview") {
      newTheme.toStorage(this.I);
    }
    return this.b.setColorTheme(this.f, settingsTarget);
  }
  cb(themeId, themeData, themeType) {
    if (themeData) {
      const key2 = themeType + themeData.extensionId;
      if (!this.bb.get(key2)) {
        this.L.publicLog2("activatePlugin", {
          id: themeData.extensionId,
          name: themeData.extensionName,
          isBuiltin: themeData.extensionIsBuiltin,
          publisherDisplayName: themeData.extensionPublisher,
          themeId
        });
        this.bb.set(key2, true);
      }
    }
  }
  async getFileIconThemes() {
    return this.n.getThemes();
  }
  getFileIconTheme() {
    return this.r;
  }
  get onDidFileIconThemeChange() {
    return this.s.event;
  }
  async setFileIconTheme(iconThemeOrId, settingsTarget) {
    return this.y.queue(async () => {
      return this.db(iconThemeOrId, settingsTarget);
    });
  }
  async db(iconThemeOrId, settingsTarget) {
    if (iconThemeOrId === void 0) {
      iconThemeOrId = "";
    }
    const themeId = $zg(iconThemeOrId) ? iconThemeOrId : iconThemeOrId.id;
    if (themeId !== this.r.id || !this.r.isLoaded) {
      let newThemeData = this.n.findThemeById(themeId);
      if (!newThemeData && iconThemeOrId instanceof $1Vb) {
        newThemeData = iconThemeOrId;
      }
      if (!newThemeData) {
        newThemeData = $1Vb.noIconTheme;
      }
      await newThemeData.ensureLoaded(this.u);
      this.fb(newThemeData);
    }
    const themeData = this.r;
    if (themeData.isLoaded && settingsTarget !== "preview" && (!themeData.location || !$8v(themeData.location))) {
      themeData.toStorage(this.I);
    }
    await this.b.setFileIconTheme(this.r, settingsTarget);
    return themeData;
  }
  async getMarketplaceFileIconThemes(publisher, name, version2) {
    const extensionLocation = this.N.getExtensionGalleryResourceURL({ publisher, name, version: version2 }, "extension");
    if (extensionLocation) {
      try {
        const manifestContent = await this.N.readExtensionResource($vh(extensionLocation, "package.json"));
        return this.n.getMarketplaceThemes(JSON.parse(manifestContent), extensionLocation, ExtensionData.fromName(publisher, name));
      } catch (e) {
        this.O.error("Problem loading themes from marketplace", e);
      }
    }
    return [];
  }
  async eb() {
    return this.y.queue(async () => {
      await this.r.reload(this.u);
      this.fb(this.r);
    });
  }
  async restoreFileIconTheme() {
    return this.y.queue(async () => {
      const settingId = this.b.fileIconTheme;
      const theme = this.n.findThemeBySettingsId(settingId);
      if (theme) {
        if (settingId !== this.r.settingsId) {
          await this.db(theme.id, void 0);
        } else if (theme !== this.r) {
          await theme.ensureLoaded(this.u);
          this.fb(theme, true);
        }
        return true;
      }
      return false;
    });
  }
  fb(iconThemeData, silent = false) {
    this.r = iconThemeData;
    _applyRules(iconThemeData.styleSheetContent, fileIconThemeRulesClassName);
    if (iconThemeData.id) {
      this.a.classList.add(fileIconsEnabledClass);
    } else {
      this.a.classList.remove(fileIconsEnabledClass);
    }
    this.w.update(iconThemeData);
    if (iconThemeData.id) {
      this.cb(iconThemeData.id, iconThemeData.extensionData, "fileIcon");
    }
    if (!silent) {
      this.s.fire(this.r);
    }
  }
  async getProductIconThemes() {
    return this.z.getThemes();
  }
  getProductIconTheme() {
    return this.C;
  }
  get onDidProductIconThemeChange() {
    return this.D.event;
  }
  async setProductIconTheme(iconThemeOrId, settingsTarget) {
    return this.G.queue(async () => {
      return this.gb(iconThemeOrId, settingsTarget);
    });
  }
  async gb(iconThemeOrId, settingsTarget) {
    if (iconThemeOrId === void 0) {
      iconThemeOrId = "";
    }
    const themeId = $zg(iconThemeOrId) ? iconThemeOrId : iconThemeOrId.id;
    if (themeId !== this.C.id || !this.C.isLoaded) {
      let newThemeData = this.z.findThemeById(themeId);
      if (!newThemeData && iconThemeOrId instanceof $8Vb) {
        newThemeData = iconThemeOrId;
      }
      if (!newThemeData) {
        newThemeData = $8Vb.defaultTheme;
      }
      await newThemeData.ensureLoaded(this.N, this.O);
      this.ib(newThemeData);
    }
    const themeData = this.C;
    if (themeData.isLoaded && settingsTarget !== "preview" && (!themeData.location || !$8v(themeData.location))) {
      themeData.toStorage(this.I);
    }
    await this.b.setProductIconTheme(this.C, settingsTarget);
    return themeData;
  }
  async getMarketplaceProductIconThemes(publisher, name, version2) {
    const extensionLocation = this.N.getExtensionGalleryResourceURL({ publisher, name, version: version2 }, "extension");
    if (extensionLocation) {
      try {
        const manifestContent = await this.N.readExtensionResource($vh(extensionLocation, "package.json"));
        return this.z.getMarketplaceThemes(JSON.parse(manifestContent), extensionLocation, ExtensionData.fromName(publisher, name));
      } catch (e) {
        this.O.error("Problem loading themes from marketplace", e);
      }
    }
    return [];
  }
  async hb() {
    return this.G.queue(async () => {
      await this.C.reload(this.N, this.O);
      this.ib(this.C);
    });
  }
  async restoreProductIconTheme() {
    return this.G.queue(async () => {
      const settingId = this.b.productIconTheme;
      const theme = this.z.findThemeBySettingsId(settingId);
      if (theme) {
        if (settingId !== this.C.settingsId) {
          await this.gb(theme.id, void 0);
        } else if (theme !== this.C) {
          await theme.ensureLoaded(this.N, this.O);
          this.ib(theme, true);
        }
        return true;
      }
      return false;
    });
  }
  ib(iconThemeData, silent = false) {
    this.C = iconThemeData;
    _applyRules(iconThemeData.styleSheetContent, productIconThemeRulesClassName);
    this.F.update(iconThemeData);
    if (iconThemeData.id) {
      this.cb(iconThemeData.id, iconThemeData.extensionData, "productIcon");
    }
    if (!silent) {
      this.D.fire(this.C);
    }
  }
};
$aWb = __decorate([
  __param(0, $wN),
  __param(1, $jv),
  __param(2, $kl),
  __param(3, $zv),
  __param(4, $M4),
  __param(5, $km),
  __param(6, $Olb),
  __param(7, $Vlb),
  __param(8, $wn),
  __param(9, $NGb),
  __param(10, $9Vb),
  __param(11, $1E)
], $aWb);
var ThemeFileWatcher = class {
  constructor(d, f, g) {
    this.d = d;
    this.f = f;
    this.g = g;
  }
  update(theme) {
    if (!$oh(theme.location, this.a)) {
      this.dispose();
      if (theme.location && (theme.watch || this.f.isExtensionDevelopment)) {
        this.a = theme.location;
        this.b = this.d.watch(theme.location);
        this.d.onDidFilesChange((e) => {
          if (this.a && e.contains(
            this.a,
            0
            /* FileChangeType.UPDATED */
          )) {
            this.g();
          }
        });
      }
    }
  }
  dispose() {
    this.b = $Xc(this.b);
    this.c = $Xc(this.c);
    this.a = void 0;
  }
};
function _applyRules(styleSheetContent, rulesClassName) {
  const themeStyles = $Y.document.head.getElementsByClassName(rulesClassName);
  if (themeStyles.length === 0) {
    const elStyle = $VZ();
    elStyle.className = rulesClassName;
    elStyle.textContent = styleSheetContent;
  } else {
    themeStyles[0].textContent = styleSheetContent;
  }
}
$MGb();
$ZVb();
$Glb();
$SC(
  $rwb,
  $aWb,
  0
  /* InstantiationType.Eager */
);

// out-build/vs/workbench/services/label/common/labelService.js
var resourceLabelFormattersExtPoint = $tN.registerExtensionPoint({
  extensionPoint: "resourceLabelFormatters",
  jsonSchema: {
    description: localize(12970, null),
    type: "array",
    items: {
      type: "object",
      required: ["scheme", "formatting"],
      properties: {
        scheme: {
          type: "string",
          description: localize(12971, null)
        },
        authority: {
          type: "string",
          description: localize(12972, null)
        },
        formatting: {
          description: localize(12973, null),
          type: "object",
          properties: {
            label: {
              type: "string",
              description: localize(12974, null)
            },
            separator: {
              type: "string",
              description: localize(12975, null)
            },
            stripPathStartingSeparator: {
              type: "boolean",
              description: localize(12976, null)
            },
            tildify: {
              type: "boolean",
              description: localize(12977, null)
            },
            workspaceSuffix: {
              type: "string",
              description: localize(12978, null)
            }
          }
        }
      }
    }
  }
});
var sepRegexp = /\//g;
var labelMatchingRegexp = /\$\{(scheme|authoritySuffix|authority|path|(query)\.(.+?))\}/g;
function hasDriveLetterIgnorePlatform(path) {
  return !!(path && path[2] === ":");
}
var ResourceLabelFormattersHandler = class ResourceLabelFormattersHandler2 {
  constructor(labelService) {
    this.a = /* @__PURE__ */ new Map();
    resourceLabelFormattersExtPoint.setHandler((extensions, delta) => {
      for (const added of delta.added) {
        for (const untrustedFormatter of added.value) {
          const formatter = { ...untrustedFormatter };
          if (typeof formatter.formatting.label !== "string") {
            formatter.formatting.label = "${authority}${path}";
          }
          if (typeof formatter.formatting.separator !== `string`) {
            formatter.formatting.separator = sep;
          }
          if (!$zN(added.description, "contribLabelFormatterWorkspaceTooltip") && formatter.formatting.workspaceTooltip) {
            formatter.formatting.workspaceTooltip = void 0;
          }
          this.a.set(formatter, labelService.registerFormatter(formatter));
        }
      }
      for (const removed of delta.removed) {
        for (const formatter of removed.value) {
          $Xc(this.a.get(formatter));
        }
      }
    });
  }
};
ResourceLabelFormattersHandler = __decorate([
  __param(0, $ZI)
], ResourceLabelFormattersHandler);
$Wn.as(Extensions2.Workbench).registerWorkbenchContribution(
  ResourceLabelFormattersHandler,
  3
  /* LifecyclePhase.Restored */
);
var FORMATTER_CACHE_SIZE = 50;
var $bWb = class $bWb2 extends $3c {
  constructor(m, n, r2, s, storageService, lifecycleService) {
    super();
    this.m = m;
    this.n = n;
    this.r = r2;
    this.s = s;
    this.b = this.B(new $ze({ leakWarningThreshold: 400 }));
    this.onDidChangeFormatters = this.b.event;
    this.h = OS;
    this.j = r2.defaultUriScheme === Schemas.file ? this.r.userHome({ preferLocal: true }) : void 0;
    const memento = this.c = new $Slb("cachedResourceLabelFormatters2", storageService);
    this.g = memento.getMemento(
      0,
      1
      /* StorageTarget.MACHINE */
    );
    this.a = this.g?.formatters?.slice() || [];
    this.t();
  }
  async t() {
    const env3 = await this.s.getEnvironment();
    this.h = env3?.os ?? OS;
    this.j = await this.r.userHome();
  }
  findFormatting(resource) {
    let bestResult;
    for (const formatter of this.a) {
      if (formatter.scheme === resource.scheme) {
        if (!formatter.authority && (!bestResult || formatter.priority)) {
          bestResult = formatter;
          continue;
        }
        if (!formatter.authority) {
          continue;
        }
        if ($Cl(formatter.authority.toLowerCase(), resource.authority.toLowerCase()) && (!bestResult || !bestResult.authority || formatter.authority.length > bestResult.authority.length || formatter.authority.length === bestResult.authority.length && formatter.priority)) {
          bestResult = formatter;
        }
      }
    }
    return bestResult ? bestResult.formatting : void 0;
  }
  getUriLabel(resource, options3 = {}) {
    let formatting = this.findFormatting(resource);
    if (formatting && options3.separator) {
      formatting = { ...formatting, separator: options3.separator };
    }
    const label3 = this.u(resource, formatting, options3);
    if (!formatting && options3.separator) {
      return label3.replace(sepRegexp, options3.separator);
    }
    return label3;
  }
  u(resource, formatting, options3 = {}) {
    if (!formatting) {
      return $Zt(resource, {
        os: this.h,
        tildify: this.j ? { userHome: this.j } : void 0,
        relative: options3.relative ? {
          noPrefix: options3.noPrefix,
          getWorkspace: () => this.n.getWorkspace(),
          getWorkspaceFolder: (resource2) => this.n.getWorkspaceFolder(resource2)
        } : void 0
      });
    }
    if (options3.relative && this.n) {
      let folder = this.n.getWorkspaceFolder(resource);
      if (!folder) {
        const workspace2 = this.n.getWorkspace();
        const firstFolder = workspace2.folders.at(0);
        if (firstFolder && resource.scheme !== firstFolder.uri.scheme && resource.path.startsWith($kc.sep)) {
          folder = this.n.getWorkspaceFolder(firstFolder.uri.with({ path: resource.path }));
        }
      }
      if (folder) {
        const folderLabel = this.z(folder.uri, formatting, options3.noPrefix);
        let relativeLabel = this.z(resource, formatting, options3.noPrefix);
        let overlap = 0;
        while (relativeLabel[overlap] && relativeLabel[overlap] === folderLabel[overlap]) {
          overlap++;
        }
        if (!relativeLabel[overlap] || relativeLabel[overlap] === formatting.separator) {
          relativeLabel = relativeLabel.substring(1 + overlap);
        } else if (overlap === folderLabel.length && folder.uri.path === $kc.sep) {
          relativeLabel = relativeLabel.substring(overlap);
        }
        const hasMultipleRoots = this.n.getWorkspace().folders.length > 1;
        if (hasMultipleRoots && !options3.noPrefix) {
          const rootName = folder?.name ?? $rh(folder.uri);
          relativeLabel = relativeLabel ? `${rootName} \u2022 ${relativeLabel}` : rootName;
        }
        return relativeLabel;
      }
    }
    return this.z(resource, formatting, options3.noPrefix);
  }
  getUriBasenameLabel(resource) {
    const formatting = this.findFormatting(resource);
    const label3 = this.u(resource, formatting);
    let pathLib;
    if (formatting?.separator === $jc.sep) {
      pathLib = $jc;
    } else if (formatting?.separator === $kc.sep) {
      pathLib = $kc;
    } else {
      pathLib = this.h === 1 ? $jc : $kc;
    }
    return pathLib.basename(label3);
  }
  getWorkspaceLabel(workspace2, options3) {
    if ($8k(workspace2)) {
      const identifier2 = $5k(workspace2);
      if ($1k(identifier2) || $6k(identifier2)) {
        return this.getWorkspaceLabel(identifier2, options3);
      }
      return "";
    }
    if (URI.isUri(workspace2)) {
      return this.y(workspace2, options3);
    }
    if ($1k(workspace2)) {
      return this.y(workspace2.uri, options3);
    }
    if ($6k(workspace2)) {
      return this.w(workspace2.configPath, options3);
    }
    return "";
  }
  w(workspaceUri, options3) {
    if ($el(workspaceUri, this.m)) {
      return localize(12979, null);
    }
    if ($fl(workspaceUri)) {
      return localize(12980, null);
    }
    let filename = $sh(workspaceUri);
    if (filename.endsWith($al)) {
      filename = filename.substr(0, filename.length - $al.length - 1);
    }
    let label3;
    switch (options3?.verbose) {
      case 0:
        label3 = filename;
        break;
      case 2:
        label3 = localize(12981, null, this.getUriLabel($vh($uh(workspaceUri), filename)));
        break;
      case 1:
      default:
        label3 = localize(12982, null, filename);
        break;
    }
    if (options3?.verbose === 0) {
      return label3;
    }
    return this.C(label3, workspaceUri);
  }
  y(folderUri, options3) {
    let label3;
    switch (options3?.verbose) {
      case 2:
        label3 = this.getUriLabel(folderUri);
        break;
      case 0:
      case 1:
      default:
        label3 = $sh(folderUri) || $kc.sep;
        break;
    }
    if (options3?.verbose === 0) {
      return label3;
    }
    return this.C(label3, folderUri);
  }
  getSeparator(scheme, authority) {
    const formatter = this.findFormatting(URI.from({ scheme, authority }));
    return formatter?.separator || $kc.sep;
  }
  getHostLabel(scheme, authority) {
    const formatter = this.findFormatting(URI.from({ scheme, authority }));
    return formatter?.workspaceSuffix || authority || "";
  }
  getHostTooltip(scheme, authority) {
    const formatter = this.findFormatting(URI.from({ scheme, authority }));
    return formatter?.workspaceTooltip;
  }
  registerCachedFormatter(formatter) {
    const list2 = this.g.formatters ??= [];
    let replace = list2.findIndex((f) => f.scheme === formatter.scheme && f.authority === formatter.authority);
    if (replace === -1 && list2.length >= FORMATTER_CACHE_SIZE) {
      replace = FORMATTER_CACHE_SIZE - 1;
    }
    if (replace === -1) {
      list2.unshift(formatter);
    } else {
      for (let i2 = replace; i2 > 0; i2--) {
        list2[i2] = list2[i2 - 1];
      }
      list2[0] = formatter;
    }
    this.c.saveMemento();
    return this.registerFormatter(formatter);
  }
  registerFormatter(formatter) {
    this.a.push(formatter);
    this.b.fire({ scheme: formatter.scheme });
    return {
      dispose: () => {
        this.a = this.a.filter((f) => f !== formatter);
        this.b.fire({ scheme: formatter.scheme });
      }
    };
  }
  z(resource, formatting, forceNoTildify) {
    let label3 = formatting.label.replace(labelMatchingRegexp, (match, token, qsToken, qsValue) => {
      switch (token) {
        case "scheme":
          return resource.scheme;
        case "authority":
          return resource.authority;
        case "authoritySuffix": {
          const i2 = resource.authority.indexOf("+");
          return i2 === -1 ? resource.authority : resource.authority.slice(i2 + 1);
        }
        case "path":
          return formatting.stripPathStartingSeparator ? resource.path.slice(resource.path[0] === formatting.separator ? 1 : 0) : resource.path;
        default: {
          if (qsToken === "query") {
            const { query } = resource;
            if (query && query[0] === "{" && query[query.length - 1] === "}") {
              try {
                return JSON.parse(query)[qsValue] || "";
              } catch {
              }
            }
          }
          return "";
        }
      }
    });
    if (formatting.normalizeDriveLetter && hasDriveLetterIgnorePlatform(label3)) {
      label3 = label3.charAt(1).toUpperCase() + label3.substr(2);
    }
    if (formatting.tildify && !forceNoTildify) {
      if (this.j) {
        label3 = $2t(label3, this.j.fsPath, this.h);
      }
    }
    if (formatting.authorityPrefix && resource.authority) {
      label3 = formatting.authorityPrefix + label3;
    }
    return label3.replace(sepRegexp, formatting.separator);
  }
  C(label3, uri) {
    const formatting = this.findFormatting(uri);
    const suffix = formatting && typeof formatting.workspaceSuffix === "string" ? formatting.workspaceSuffix : void 0;
    return suffix ? `${label3} [${suffix}]` : label3;
  }
};
$bWb = __decorate([
  __param(0, $US),
  __param(1, $Zk),
  __param(2, $aT),
  __param(3, $RL),
  __param(4, $jv),
  __param(5, $KL)
], $bWb);
$SC(
  $ZI,
  $bWb,
  1
  /* InstantiationType.Delayed */
);

// out-build/vs/platform/extensionManagement/common/extensionEnablementService.js
var $cWb = class $cWb2 extends $3c {
  constructor(storageService, extensionManagementService) {
    super();
    this.a = new $ze();
    this.onDidChangeEnablement = this.a.event;
    this.b = this.B(new $dWb(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($tA);
  }
  async getDisabledExtensionsAsync() {
    return this.getDisabledExtensions();
  }
  c(identifier2) {
    const disabledExtensions = this.getDisabledExtensions();
    if (disabledExtensions.every((e) => !$DA(e, identifier2))) {
      disabledExtensions.push(identifier2);
      this.g(disabledExtensions);
      return true;
    }
    return false;
  }
  f(identifier2) {
    const disabledExtensions = this.getDisabledExtensions();
    for (let index = 0; index < disabledExtensions.length; index++) {
      const disabledExtension = disabledExtensions[index];
      if ($DA(disabledExtension, identifier2)) {
        disabledExtensions.splice(index, 1);
        this.g(disabledExtensions);
        return true;
      }
    }
    return false;
  }
  g(disabledExtensions) {
    this.j($tA, disabledExtensions);
  }
  h(storageId) {
    return this.b.get(
      storageId,
      0
      /* StorageScope.PROFILE */
    );
  }
  j(storageId, extensions) {
    this.b.set(
      storageId,
      extensions,
      0
      /* StorageScope.PROFILE */
    );
  }
};
$cWb = __decorate([
  __param(0, $jv),
  __param(1, $sA)
], $cWb);
var $dWb = class extends $3c {
  constructor(c) {
    super();
    this.c = c;
    this.a = /* @__PURE__ */ Object.create(null);
    this.b = this.B(new $ze());
    this.onDidChange = this.b.event;
    this.B(c.onDidChangeValue(0, void 0, this.q)((e) => this.f(e)));
  }
  get(key2, scope) {
    let value;
    if (scope === 0) {
      if ($Ig(this.a[key2])) {
        this.a[key2] = this.g(key2, scope);
      }
      value = this.a[key2];
    } else {
      value = this.g(key2, scope);
    }
    return JSON.parse(value);
  }
  set(key2, value, scope) {
    const newValue = JSON.stringify(value.map(({ id: id2, uuid }) => ({ id: id2, uuid })));
    const oldValue = this.g(key2, scope);
    if (oldValue !== newValue) {
      if (scope === 0) {
        if (value.length) {
          this.a[key2] = newValue;
        } else {
          delete this.a[key2];
        }
      }
      this.h(key2, value.length ? newValue : void 0, scope);
    }
  }
  f(storageChangeEvent) {
    if (!$Ig(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) => $DA(oldValue, newValue2)));
        const removed = newValues.filter((newValue2) => !oldValues.some((oldValue) => $DA(oldValue, newValue2)));
        if (added.length || removed.length) {
          this.b.fire([...added, ...removed]);
        }
      }
    }
  }
  g(key2, scope) {
    return this.c.get(key2, scope, "[]");
  }
  h(key2, value, scope) {
    if (value) {
      this.c.store(
        key2,
        value,
        scope,
        1
        /* StorageTarget.MACHINE */
      );
    } else {
      this.c.remove(key2, scope);
    }
  }
};

// out-build/vs/platform/userDataSync/common/userDataSyncAccount.js
var $eWb = $Qk("IUserDataSyncAccountService");
var $fWb = class $fWb2 extends $3c {
  get account() {
    return this.a;
  }
  constructor(g, h3) {
    super();
    this.g = g;
    this.h = h3;
    this.b = this.B(new $ze());
    this.onDidChangeAccount = this.b.event;
    this.c = this.B(new $ze());
    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);
    }
  }
};
$fWb = __decorate([
  __param(0, $VBb),
  __param(1, $$Bb)
], $fWb);

// out-build/vs/workbench/services/extensionManagement/browser/extensionBisect.js
var ExtensionBisectService_1;
var ExtensionBisectUi_1;
var $gWb = $Qk("IExtensionBisectService");
var BisectState = class _BisectState {
  static fromJSON(raw) {
    if (!raw) {
      return void 0;
    }
    try {
      const data = JSON.parse(raw);
      return new _BisectState(data.extensions, data.low, data.high, data.mid);
    } catch {
      return void 0;
    }
  }
  constructor(extensions, low, high, mid = (low + high) / 2 | 0) {
    this.extensions = extensions;
    this.low = low;
    this.high = high;
    this.mid = mid;
  }
};
var ExtensionBisectService = class ExtensionBisectService2 {
  static {
    ExtensionBisectService_1 = this;
  }
  static {
    this.a = "extensionBisectState";
  }
  constructor(logService, d, e) {
    this.d = d;
    this.e = e;
    this.c = /* @__PURE__ */ new Map();
    const raw = d.get(
      ExtensionBisectService_1.a,
      -1
      /* StorageScope.APPLICATION */
    );
    this.b = BisectState.fromJSON(raw);
    if (this.b) {
      const { mid, high } = this.b;
      for (let i2 = 0; i2 < this.b.extensions.length; i2++) {
        const isDisabled = i2 >= mid && i2 < high;
        this.c.set(this.b.extensions[i2], isDisabled);
      }
      logService.warn("extension BISECT active", [...this.c]);
    }
  }
  get isActive() {
    return !!this.b;
  }
  get disabledCount() {
    return this.b ? this.b.high - this.b.mid : -1;
  }
  isDisabledByBisect(extension) {
    if (!this.b) {
      return false;
    }
    if ($$z(extension.manifest, this.e.remoteAuthority)) {
      return false;
    }
    if (this.f(extension)) {
      return false;
    }
    const disabled = this.c.get(extension.identifier.id);
    return disabled ?? false;
  }
  f(extension) {
    return Array.isArray(this.e.enableExtensions) && this.e.enableExtensions.some((id2) => $DA({ id: id2 }, extension.identifier));
  }
  async start(extensions) {
    if (this.b) {
      throw new Error("invalid state");
    }
    const extensionIds = extensions.map((ext) => ext.identifier.id);
    const newState = new BisectState(extensionIds, 0, extensionIds.length, 0);
    this.d.store(
      ExtensionBisectService_1.a,
      JSON.stringify(newState),
      -1,
      1
      /* StorageTarget.MACHINE */
    );
    await this.d.flush();
  }
  async next(seeingBad) {
    if (!this.b) {
      throw new Error("invalid state");
    }
    if (seeingBad && this.b.mid === 0 && this.b.high === this.b.extensions.length) {
      return { bad: true, id: "" };
    }
    if (this.b.low === this.b.high - 1) {
      await this.reset();
      return { id: this.b.extensions[this.b.low], bad: seeingBad };
    }
    const nextState = new BisectState(this.b.extensions, seeingBad ? this.b.low : this.b.mid, seeingBad ? this.b.mid : this.b.high);
    this.d.store(
      ExtensionBisectService_1.a,
      JSON.stringify(nextState),
      -1,
      1
      /* StorageTarget.MACHINE */
    );
    await this.d.flush();
    return void 0;
  }
  async reset() {
    this.d.remove(
      ExtensionBisectService_1.a,
      -1
      /* StorageScope.APPLICATION */
    );
    await this.d.flush();
  }
};
ExtensionBisectService = ExtensionBisectService_1 = __decorate([
  __param(0, $wn),
  __param(1, $jv),
  __param(2, $US)
], ExtensionBisectService);
$SC(
  $gWb,
  ExtensionBisectService,
  1
  /* InstantiationType.Delayed */
);
var ExtensionBisectUi = class ExtensionBisectUi2 {
  static {
    ExtensionBisectUi_1 = this;
  }
  static {
    this.ctxIsBisectActive = new $nn("isExtensionBisectActive", false);
  }
  constructor(contextKeyService, a, b, c) {
    this.a = a;
    this.b = b;
    this.c = c;
    if (a.isActive) {
      ExtensionBisectUi_1.ctxIsBisectActive.bindTo(contextKeyService).set(true);
      this.d();
    }
  }
  d() {
    const goodPrompt = {
      label: localize(12703, null),
      run: () => this.c.executeCommand("extension.bisect.next", false)
    };
    const badPrompt = {
      label: localize(12704, null),
      run: () => this.c.executeCommand("extension.bisect.next", true)
    };
    const stop = {
      label: "Stop Bisect",
      run: () => this.c.executeCommand("extension.bisect.stop")
    };
    const message = this.a.disabledCount === 1 ? localize(12705, null) : localize(12706, null, this.a.disabledCount);
    this.b.prompt(Severity2.Info, message, [goodPrompt, badPrompt, stop], { sticky: true, priority: NotificationPriority.URGENT });
  }
};
ExtensionBisectUi = ExtensionBisectUi_1 = __decorate([
  __param(0, $on),
  __param(1, $gWb),
  __param(2, $PJ),
  __param(3, $sn)
], ExtensionBisectUi);
$Wn.as(Extensions2.Workbench).registerWorkbenchContribution(
  ExtensionBisectUi,
  3
  /* LifecyclePhase.Restored */
);
$hJ(class extends $gJ {
  constructor() {
    super({
      id: "extension.bisect.start",
      title: localize2(12723, "Start Extension Bisect"),
      category: $qn.Help,
      f1: true,
      precondition: ExtensionBisectUi.ctxIsBisectActive.negate(),
      menu: {
        id: $bJ.ViewContainerTitle,
        when: $7m.equals("viewContainer", "workbench.view.extensions"),
        group: "2_enablement",
        order: 4
      }
    });
  }
  async run(accessor) {
    const dialogService = accessor.get($Yv);
    const hostService = accessor.get($S4);
    const extensionManagement = accessor.get($sA);
    const extensionEnablementService = accessor.get($qzb);
    const extensionsBisect = accessor.get($gWb);
    const extensions = (await extensionManagement.getInstalled(
      1
      /* ExtensionType.User */
    )).filter((ext) => extensionEnablementService.isEnabled(ext));
    const res = await dialogService.confirm({
      message: localize(12707, null),
      detail: localize(12708, null, 2 + Math.log2(extensions.length) | 0),
      primaryButton: localize(12709, null)
    });
    if (res.confirmed) {
      await extensionsBisect.start(extensions);
      hostService.reload();
    }
  }
});
$hJ(class extends $gJ {
  constructor() {
    super({
      id: "extension.bisect.next",
      title: localize2(12724, "Continue Extension Bisect"),
      category: $qn.Help,
      f1: true,
      precondition: ExtensionBisectUi.ctxIsBisectActive
    });
  }
  async run(accessor, seeingBad) {
    const dialogService = accessor.get($Yv);
    const hostService = accessor.get($S4);
    const bisectService = accessor.get($gWb);
    const productService = accessor.get($Vu);
    const extensionEnablementService = accessor.get($vA);
    const commandService = accessor.get($sn);
    if (!bisectService.isActive) {
      return;
    }
    if (seeingBad === void 0) {
      const goodBadStopCancel = await this.a(dialogService, bisectService);
      if (goodBadStopCancel === null) {
        return;
      }
      seeingBad = goodBadStopCancel;
    }
    if (seeingBad === void 0) {
      await bisectService.reset();
      hostService.reload();
      return;
    }
    const done = await bisectService.next(seeingBad);
    if (!done) {
      hostService.reload();
      return;
    }
    if (done.bad) {
      await dialogService.info(localize(12710, null), localize(12711, null, productService.nameShort));
    } else {
      const res = await dialogService.confirm({
        type: Severity2.Info,
        message: localize(12712, null),
        primaryButton: localize(12713, null),
        cancelButton: localize(12714, null),
        detail: localize(12715, null, done.id),
        checkbox: { label: localize(12716, null), checked: true }
      });
      if (res.checkboxChecked) {
        await extensionEnablementService.disableExtension({ id: done.id }, void 0);
      }
      if (res.confirmed) {
        await commandService.executeCommand("workbench.action.openIssueReporter", done.id);
      }
    }
    await bisectService.reset();
    hostService.reload();
  }
  async a(dialogService, bisectService) {
    const { result } = await dialogService.prompt({
      type: Severity2.Info,
      message: localize(12717, null),
      detail: localize(12718, null, bisectService.disabledCount),
      buttons: [
        {
          label: localize(12719, null),
          run: () => false
          // good now
        },
        {
          label: localize(12720, null),
          run: () => true
          // bad
        },
        {
          label: localize(12721, null),
          run: () => void 0
          // stop
        }
      ],
      cancelButton: {
        label: localize(12722, null),
        run: () => null
        // cancel
      }
    });
    return result;
  }
});
$hJ(class extends $gJ {
  constructor() {
    super({
      id: "extension.bisect.stop",
      title: localize2(12725, "Stop Extension Bisect"),
      category: $qn.Help,
      f1: true,
      precondition: ExtensionBisectUi.ctxIsBisectActive
    });
  }
  async run(accessor) {
    const extensionsBisect = accessor.get($gWb);
    const hostService = accessor.get($S4);
    await extensionsBisect.reset();
    hostService.reload();
  }
});

// out-build/vs/workbench/services/extensionManagement/browser/extensionEnablementService.js
var SOURCE = "IWorkbenchExtensionEnablementService";
var $hWb = class $hWb2 extends $3c {
  constructor(storageService, h3, j, m, extensionManagementService, n, s, t, u, w, y, hostService, z, C, D, F, G, instantiationService) {
    super();
    this.h = h3;
    this.j = j;
    this.m = m;
    this.n = n;
    this.s = s;
    this.t = t;
    this.u = u;
    this.w = w;
    this.y = y;
    this.z = z;
    this.C = C;
    this.D = D;
    this.F = F;
    this.G = G;
    this.b = new $ze();
    this.onEnablementChanged = this.b.event;
    this.g = [];
    this.f = this.B(new $dWb(storageService));
    const uninstallDisposable = this.B(Event2.filter(extensionManagementService.onDidUninstallExtension, (e) => !e.error)(({ identifier: identifier2 }) => this.qb(identifier2)));
    let isDisposed = false;
    this.B($1c(() => isDisposed = true));
    this.c = this.B(instantiationService.createInstance(ExtensionsManager));
    this.c.whenInitialized().then(() => {
      if (!isDisposed) {
        this.ob([], [], false);
        this.B(this.c.onDidChangeExtensions(({ added, removed, isProfileSwitch }) => this.ob(added, removed, isProfileSwitch)));
        uninstallDisposable.dispose();
      }
    });
    this.B(this.h.onDidChangeEnablement(({ extensions, source }) => this.nb(extensions, source)));
    this.B(C.onDidChangeAllowedExtensions(() => this.ob([], [], false)));
    if (this.I) {
      this.w.when(
        4
        /* LifecyclePhase.Eventually */
      ).then(() => {
        this.y.prompt(Severity2.Info, localize(12726, null), [{
          label: localize(12727, null),
          run: () => hostService.reload({ disableExtensions: false })
        }], {
          sticky: true,
          priority: NotificationPriority.URGENT
        });
      });
    }
  }
  get H() {
    return this.j.getWorkbenchState() !== 1;
  }
  get I() {
    return this.m.disableExtensions === true;
  }
  getEnablementState(extension) {
    return this.P(extension, this.c.extensions, this.pb());
  }
  getEnablementStates(extensions, workspaceTypeOverrides = {}) {
    const extensionsEnablements = /* @__PURE__ */ new Map();
    const workspaceType = { ...this.pb(), ...workspaceTypeOverrides };
    return extensions.map((extension) => this.P(extension, extensions, workspaceType, extensionsEnablements));
  }
  getDependenciesEnablementStates(extension) {
    return $NA(this.c.extensions, extension).map((e) => [e, this.getEnablementState(e)]);
  }
  canChangeEnablement(extension) {
    try {
      this.J(extension);
      return true;
    } catch (error) {
      return false;
    }
  }
  canChangeWorkspaceEnablement(extension) {
    if (!this.canChangeEnablement(extension)) {
      return false;
    }
    try {
      this.M(extension);
      return true;
    } catch (error) {
      return false;
    }
  }
  J(extension, donotCheckDependencies) {
    if ($9z(extension.manifest)) {
      throw new Error(localize(12728, null, extension.manifest.displayName || extension.identifier.id));
    }
    if (this.t.isEnabled() && this.u.account && $0z(extension.manifest) && extension.manifest.contributes.authentication.some((a) => a.id === this.u.account.authenticationProviderId)) {
      throw new Error(localize(12729, null, extension.manifest.displayName || extension.identifier.id));
    }
    if (this.R(extension)) {
      throw new Error(localize(12730, null, extension.manifest.displayName || extension.identifier.id));
    }
    this.L(extension, this.getEnablementState(extension), donotCheckDependencies);
  }
  L(extension, enablementStateOfExtension, donotCheckDependencies) {
    switch (enablementStateOfExtension) {
      case 2:
        throw new Error(localize(12731, null, extension.manifest.displayName || extension.identifier.id));
      case 4:
        throw new Error(localize(12732, null, extension.manifest.displayName || extension.identifier.id));
      case 1:
        throw new Error(localize(12733, null, extension.manifest.displayName || extension.identifier.id));
      case 6:
        throw new Error(localize(12734, null, extension.manifest.displayName || extension.identifier.id));
      case 5:
        throw new Error(localize(12735, null, extension.manifest.displayName || extension.identifier.id));
      case 7:
        if (donotCheckDependencies) {
          break;
        }
        for (const dependency of $NA(this.c.extensions, extension)) {
          if (this.isEnabled(dependency)) {
            continue;
          }
          throw new Error(localize(12736, null, extension.manifest.displayName || extension.identifier.id, dependency.manifest.displayName || dependency.identifier.id));
        }
    }
  }
  M(extension) {
    if (!this.H) {
      throw new Error(localize(12737, null));
    }
    if ($0z(extension.manifest)) {
      throw new Error(localize(12738, null, extension.manifest.displayName || extension.identifier.id));
    }
  }
  async setEnablement(extensions, newState) {
    await this.c.whenInitialized();
    if (newState === 10 || newState === 11) {
      extensions.push(...this.N(extensions, this.c.extensions, newState, { dependencies: true, pack: true }));
    }
    const workspace2 = newState === 9 || newState === 11;
    for (const extension of extensions) {
      if (workspace2) {
        this.M(extension);
      } else {
        this.J(extension);
      }
    }
    const result = [];
    for (const extension of extensions) {
      const enablementState = this.getEnablementState(extension);
      if (enablementState === 0 || enablementState === 7 && this.getDependenciesEnablementStates(extension).every(
        ([, e]) => this.isEnabledEnablementState(e) || e === 0
        /* EnablementState.DisabledByTrustRequirement */
      )) {
        const trustState = await this.F.requestWorkspaceTrust();
        result.push(trustState ?? false);
      } else {
        result.push(await this.O(extension, newState));
      }
    }
    const changedExtensions = extensions.filter((e, index) => result[index]);
    if (changedExtensions.length) {
      this.b.fire(changedExtensions);
    }
    return result;
  }
  N(extensions, allExtensions, enablementState, options3, checked = []) {
    if (!options3.dependencies && !options3.pack) {
      return [];
    }
    const toCheck = extensions.filter((e) => checked.indexOf(e) === -1);
    if (!toCheck.length) {
      return [];
    }
    for (const extension of toCheck) {
      checked.push(extension);
    }
    const extensionsToEnable = [];
    for (const extension of allExtensions) {
      if (checked.some((e) => $DA(e.identifier, extension.identifier))) {
        continue;
      }
      const enablementStateOfExtension = this.getEnablementState(extension);
      if (this.isEnabledEnablementState(enablementStateOfExtension)) {
        continue;
      }
      if (enablementStateOfExtension === 1) {
        continue;
      }
      if (extensions.some((e) => options3.dependencies && e.manifest.extensionDependencies?.some((id2) => $DA({ id: id2 }, extension.identifier)) || options3.pack && e.manifest.extensionPack?.some((id2) => $DA({ id: id2 }, extension.identifier)))) {
        const index = extensionsToEnable.findIndex((e) => $DA(e.identifier, extension.identifier));
        if (index === -1) {
          extensionsToEnable.push(extension);
        } else {
          try {
            this.L(extension, enablementStateOfExtension, true);
            extensionsToEnable.splice(index, 1, extension);
          } catch (error) {
          }
        }
      }
    }
    if (extensionsToEnable.length) {
      extensionsToEnable.push(...this.N(extensionsToEnable, allExtensions, enablementState, options3, checked));
    }
    return extensionsToEnable;
  }
  O(extension, newState) {
    const currentState = this.Y(extension.identifier);
    if (currentState === newState) {
      return Promise.resolve(false);
    }
    switch (newState) {
      case 10:
        this.$(extension.identifier);
        break;
      case 8:
        this.ab(extension.identifier);
        break;
      case 11:
        this.bb(extension.identifier);
        break;
      case 9:
        this.cb(extension.identifier);
        break;
    }
    return Promise.resolve(true);
  }
  isEnabled(extension) {
    const enablementState = this.getEnablementState(extension);
    return this.isEnabledEnablementState(enablementState);
  }
  isEnabledEnablementState(enablementState) {
    return enablementState === 3 || enablementState === 11 || enablementState === 10;
  }
  isDisabledGlobally(extension) {
    return this.Z(extension.identifier);
  }
  P(extension, extensions, workspaceType, computedEnablementStates) {
    computedEnablementStates = computedEnablementStates ?? /* @__PURE__ */ new Map();
    let enablementState = computedEnablementStates.get(extension);
    if (enablementState !== void 0) {
      return enablementState;
    }
    enablementState = this.Y(extension.identifier);
    const isEnabled = this.isEnabledEnablementState(enablementState);
    if (isEnabled && extension.type === 1 && this.C.isAllowed(extension) !== true) {
      enablementState = 6;
    } else if (isEnabled && !extension.isValid) {
      enablementState = 5;
    } else if (this.z.isDisabledByBisect(extension)) {
      enablementState = 2;
    } else if (this.Q(extension)) {
      enablementState = 2;
    } else if (this.S(extension, workspaceType)) {
      enablementState = 4;
    } else if (isEnabled && this.W(extension, workspaceType)) {
      enablementState = 0;
    } else if (this.U(extension)) {
      enablementState = 1;
    } else if (isEnabled && this.X(extension, extensions, workspaceType, computedEnablementStates)) {
      enablementState = 7;
    } else if (!isEnabled && this.R(extension)) {
      enablementState = 3;
    }
    computedEnablementStates.set(extension, enablementState);
    return enablementState;
  }
  Q(extension) {
    if (this.I) {
      return !extension.isBuiltin && !$$z(extension.manifest, this.m.remoteAuthority);
    }
    const disabledExtensions = this.m.disableExtensions;
    if (Array.isArray(disabledExtensions)) {
      return disabledExtensions.some((id2) => $DA({ id: id2 }, extension.identifier));
    }
    if ($DA({ id: $MA.value }, extension.identifier)) {
      return true;
    }
    return false;
  }
  R(extension) {
    const enabledExtensions = this.m.enableExtensions;
    if (Array.isArray(enabledExtensions)) {
      return enabledExtensions.some((id2) => $DA({ id: id2 }, extension.identifier));
    }
    return false;
  }
  S(extension, workspaceType) {
    if (!workspaceType.virtual) {
      return false;
    }
    if (this.G.getExtensionVirtualWorkspaceSupportType(extension.manifest) !== false) {
      return false;
    }
    if (this.s.getExtensionManagementServer(extension) === this.s.webExtensionManagementServer && this.G.canExecuteOnWeb(extension.manifest)) {
      return false;
    }
    return true;
  }
  U(extension) {
    if (this.s.remoteExtensionManagementServer || this.s.webExtensionManagementServer) {
      const installLocation = this.s.getExtensionInstallLocation(extension);
      for (const extensionKind of this.G.getExtensionKind(extension.manifest)) {
        if (extensionKind === "ui") {
          if (installLocation === 1) {
            return false;
          }
        }
        if (extensionKind === "workspace") {
          if (installLocation === 2) {
            return false;
          }
        }
        if (extensionKind === "web") {
          if (this.s.webExtensionManagementServer) {
            if (installLocation === 3 || installLocation === 2) {
              return false;
            }
          } else if (installLocation === 1) {
            const enableLocalWebWorker = this.n.getValue($vN);
            if (enableLocalWebWorker === true || enableLocalWebWorker === "auto") {
              return false;
            }
          }
        }
      }
      return true;
    }
    return false;
  }
  W(extension, workspaceType) {
    if (workspaceType.trusted) {
      return false;
    }
    if (this.j.isInsideWorkspace(extension.location)) {
      return true;
    }
    return this.G.getExtensionUntrustedWorkspaceSupportType(extension.manifest) === false;
  }
  X(extension, extensions, workspaceType, computedEnablementStates) {
    if (!extension.manifest.extensionDependencies) {
      return false;
    }
    const dependencyExtensions = extensions.filter((e) => extension.manifest.extensionDependencies?.some((id2) => $DA(e.identifier, { id: id2 }) && (this.s.getExtensionManagementServer(e) === this.s.getExtensionManagementServer(extension) || (e.manifest.main || e.manifest.browser) && e.manifest.api === "none")));
    if (!dependencyExtensions.length) {
      return false;
    }
    const hasEnablementState = computedEnablementStates.has(extension);
    if (!hasEnablementState) {
      computedEnablementStates.set(
        extension,
        10
        /* EnablementState.EnabledGlobally */
      );
    }
    try {
      for (const dependencyExtension of dependencyExtensions) {
        const enablementState = this.P(dependencyExtension, extensions, workspaceType, computedEnablementStates);
        if (!this.isEnabledEnablementState(enablementState) && enablementState !== 1) {
          return true;
        }
      }
    } finally {
      if (!hasEnablementState) {
        computedEnablementStates.delete(extension);
      }
    }
    return false;
  }
  Y(identifier2) {
    if (this.H) {
      if (this.hb().filter((e) => $DA(e, identifier2))[0]) {
        return 11;
      }
      if (this.jb().filter((e) => $DA(e, identifier2))[0]) {
        return 9;
      }
    }
    if (this.Z(identifier2)) {
      return 8;
    }
    return 10;
  }
  Z(identifier2) {
    return this.h.getDisabledExtensions().some((e) => $DA(e, identifier2));
  }
  $(identifier2) {
    this.eb(identifier2);
    this.gb(identifier2);
    return this.h.enableExtension(identifier2, SOURCE);
  }
  ab(identifier2) {
    this.eb(identifier2);
    this.gb(identifier2);
    return this.h.disableExtension(identifier2, SOURCE);
  }
  bb(identifier2) {
    this.eb(identifier2);
    this.fb(identifier2);
  }
  cb(identifier2) {
    this.db(identifier2);
    this.gb(identifier2);
  }
  db(identifier2) {
    if (!this.H) {
      return Promise.resolve(false);
    }
    const disabledExtensions = this.jb();
    if (disabledExtensions.every((e) => !$DA(e, identifier2))) {
      disabledExtensions.push(identifier2);
      this.kb(disabledExtensions);
      return Promise.resolve(true);
    }
    return Promise.resolve(false);
  }
  async eb(identifier2) {
    if (!this.H) {
      return false;
    }
    const disabledExtensions = this.jb();
    for (let index = 0; index < disabledExtensions.length; index++) {
      const disabledExtension = disabledExtensions[index];
      if ($DA(disabledExtension, identifier2)) {
        disabledExtensions.splice(index, 1);
        this.kb(disabledExtensions);
        return true;
      }
    }
    return false;
  }
  fb(identifier2) {
    if (!this.H) {
      return false;
    }
    const enabledExtensions = this.hb();
    if (enabledExtensions.every((e) => !$DA(e, identifier2))) {
      enabledExtensions.push(identifier2);
      this.ib(enabledExtensions);
      return true;
    }
    return false;
  }
  gb(identifier2) {
    if (!this.H) {
      return false;
    }
    const enabledExtensions = this.hb();
    for (let index = 0; index < enabledExtensions.length; index++) {
      const disabledExtension = enabledExtensions[index];
      if ($DA(disabledExtension, identifier2)) {
        enabledExtensions.splice(index, 1);
        this.ib(enabledExtensions);
        return true;
      }
    }
    return false;
  }
  hb() {
    return this.lb($uA);
  }
  ib(enabledExtensions) {
    this.mb($uA, enabledExtensions);
  }
  jb() {
    return this.lb($tA);
  }
  kb(disabledExtensions) {
    this.mb($tA, disabledExtensions);
  }
  lb(storageId) {
    if (!this.H) {
      return [];
    }
    return this.f.get(
      storageId,
      1
      /* StorageScope.WORKSPACE */
    );
  }
  mb(storageId, extensions) {
    this.f.set(
      storageId,
      extensions,
      1
      /* StorageScope.WORKSPACE */
    );
  }
  async nb(extensionIdentifiers, source) {
    if (source !== SOURCE) {
      await this.c.whenInitialized();
      const extensions = this.c.extensions.filter((installedExtension) => extensionIdentifiers.some((identifier2) => $DA(identifier2, installedExtension.identifier)));
      this.b.fire(extensions);
    }
  }
  ob(added, removed, isProfileSwitch) {
    const changedExtensions = added.filter((e) => !this.isEnabledEnablementState(this.getEnablementState(e)));
    const existingDisabledExtensions = this.g;
    this.g = this.c.extensions.filter((extension) => {
      const enablementState = this.getEnablementState(extension);
      return enablementState === 7 || enablementState === 6;
    });
    for (const extension of existingDisabledExtensions) {
      if (this.g.every((e) => !$DA(e.identifier, extension.identifier))) {
        changedExtensions.push(extension);
      }
    }
    for (const extension of this.g) {
      if (existingDisabledExtensions.every((e) => !$DA(e.identifier, extension.identifier))) {
        changedExtensions.push(extension);
      }
    }
    if (changedExtensions.length) {
      this.b.fire(changedExtensions);
    }
    if (!isProfileSwitch) {
      removed.forEach(({ identifier: identifier2 }) => this.qb(identifier2));
    }
  }
  async updateExtensionsEnablementsWhenWorkspaceTrustChanges() {
    await this.c.whenInitialized();
    const computeEnablementStates = (workspaceType2) => {
      const extensionsEnablements = /* @__PURE__ */ new Map();
      return this.c.extensions.map((extension) => [extension, this.P(extension, this.c.extensions, workspaceType2, extensionsEnablements)]);
    };
    const workspaceType = this.pb();
    const enablementStatesWithTrustedWorkspace = computeEnablementStates({ ...workspaceType, trusted: true });
    const enablementStatesWithUntrustedWorkspace = computeEnablementStates({ ...workspaceType, trusted: false });
    const enablementChangedExtensionsBecauseOfTrust = enablementStatesWithTrustedWorkspace.filter(([, enablementState], index) => enablementState !== enablementStatesWithUntrustedWorkspace[index][1]).map(([extension]) => extension);
    if (enablementChangedExtensionsBecauseOfTrust.length) {
      this.b.fire(enablementChangedExtensionsBecauseOfTrust);
    }
  }
  pb() {
    return { trusted: this.D.isWorkspaceTrusted(), virtual: $_S(this.j.getWorkspace()) };
  }
  qb(extension) {
    this.eb(extension);
    this.gb(extension);
    this.h.enableExtension(extension);
  }
};
$hWb = __decorate([
  __param(0, $jv),
  __param(1, $vA),
  __param(2, $Zk),
  __param(3, $US),
  __param(4, $sA),
  __param(5, $kl),
  __param(6, $nzb),
  __param(7, $6Bb),
  __param(8, $eWb),
  __param(9, $KL),
  __param(10, $PJ),
  __param(11, $S4),
  __param(12, $gWb),
  __param(13, $xA),
  __param(14, $4M),
  __param(15, $5M),
  __param(16, $LCb),
  __param(17, $Pk)
], $hWb);
var ExtensionsManager = class ExtensionsManager2 extends $3c {
  get extensions() {
    return this.b;
  }
  constructor(h3, j, m) {
    super();
    this.h = h3;
    this.j = j;
    this.m = m;
    this.b = [];
    this.c = this.B(new $ze());
    this.onDidChangeExtensions = this.c.event;
    this.g = false;
    this.B($1c(() => this.g = true));
    this.f = this.n();
  }
  whenInitialized() {
    return this.f;
  }
  async n() {
    try {
      this.b = [
        ...await this.h.getInstalled(),
        ...await this.h.getInstalledWorkspaceExtensions(true)
      ];
      if (this.g) {
        return;
      }
      this.c.fire({ added: this.extensions, removed: [], isProfileSwitch: false });
    } catch (error) {
      this.m.error(error);
    }
    this.B(this.h.onDidInstallExtensions((e) => this.r(e.reduce((result, { local, operation }) => {
      if (local && operation !== 4) {
        result.push(local);
      }
      return result;
    }, []), [], void 0, false)));
    this.B(Event2.filter(this.h.onDidUninstallExtension, (e) => !e.error)((e) => this.r([], [e.identifier], e.server, false)));
    this.B(this.h.onDidChangeProfile(({ added, removed, server }) => {
      this.r(added, removed.map(({ identifier: identifier2 }) => identifier2), server, true);
    }));
  }
  r(added, identifiers2, server, isProfileSwitch) {
    if (added.length) {
      for (const extension of added) {
        const extensionServer = this.j.getExtensionManagementServer(extension);
        const index = this.b.findIndex((e) => $DA(e.identifier, extension.identifier) && this.j.getExtensionManagementServer(e) === extensionServer);
        if (index !== -1) {
          this.b.splice(index, 1);
        }
      }
      this.b.push(...added);
    }
    const removed = [];
    for (const identifier2 of identifiers2) {
      const index = this.b.findIndex((e) => $DA(e.identifier, identifier2) && this.j.getExtensionManagementServer(e) === server);
      if (index !== -1) {
        removed.push(...this.b.splice(index, 1));
      }
    }
    if (added.length || removed.length) {
      this.c.fire({ added, removed, isProfileSwitch });
    }
  }
};
ExtensionsManager = __decorate([
  __param(0, $pzb),
  __param(1, $nzb),
  __param(2, $wn)
], ExtensionsManager);
$SC(
  $qzb,
  $hWb,
  1
  /* InstantiationType.Delayed */
);

// out-build/vs/platform/extensionManagement/common/extensionNls.js
function $3A(logger2, extensionManifest, translations, fallbackTranslations) {
  try {
    replaceNLStrings(logger2, extensionManifest, translations, fallbackTranslations);
  } catch (error) {
    logger2.error(error?.message ?? error);
  }
  return extensionManifest;
}
function replaceNLStrings(logger2, extensionManifest, messages, originalMessages) {
  const processEntry = (obj, key2, command4) => {
    const value = obj[key2];
    if ($zg(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) {
            logger2.warn(`[${extensionManifest.name}]: ${localize(1854, null, messageKey)}`);
          }
          return;
        }
        if (
          // if we are translating the title or category of a command
          command4 && (key2 === "title" || key2 === "category") && // and the original value is not the same as the translated value
          originalMessage && originalMessage !== message
        ) {
          const localizedString = {
            value: message,
            original: originalMessage
          };
          obj[key2] = localizedString;
        } else {
          obj[key2] = message;
        }
      }
    } else if ($Bg(value)) {
      for (const k in value) {
        if (value.hasOwnProperty(k)) {
          k === "commands" ? processEntry(value, k, true) : processEntry(value, k, command4);
        }
      }
    } else if (Array.isArray(value)) {
      for (let i2 = 0; i2 < value.length; i2++) {
        processEntry(value, i2, command4);
      }
    }
  };
  for (const key2 in extensionManifest) {
    if (extensionManifest.hasOwnProperty(key2)) {
      processEntry(extensionManifest, key2);
    }
  }
}

// out-build/vs/workbench/services/extensionManagement/browser/builtinExtensionsScannerService.js
var $iWb = class $iWb2 {
  constructor(environmentService, uriIdentityService, c, productService, d) {
    this.c = c;
    this.d = d;
    this.a = [];
    if ($r) {
      const nlsBaseUrl = productService.extensionsGallery?.nlsBaseUrl;
      if (nlsBaseUrl && productService.commit && !Language.isDefaultVariant()) {
        this.b = URI.joinPath(URI.parse(nlsBaseUrl), productService.commit, productService.version, Language.value());
      }
      const builtinExtensionsServiceUrl = $ih.asBrowserUri($dh);
      if (builtinExtensionsServiceUrl) {
        let bundledExtensions = [];
        if (environmentService.isBuilt) {
          bundledExtensions = [{ "extensionPath": "bat", "packageJSON": { "name": "bat", "displayName": "%displayName%", "description": "%description%", "version": "1.0.0", "publisher": "vscode", "license": "MIT", "engines": { "vscode": "^1.52.0" }, "scripts": { "update-grammar": "node ../node_modules/vscode-grammar-updater/bin mmims/language-batchfile grammars/batchfile.cson ./syntaxes/batchfile.tmLanguage.json" }, "categories": ["Programming Languages"], "contributes": { "languages": [{ "id": "bat", "extensions": [".bat", ".cmd"], "aliases": ["Batch", "bat"], "configuration": "./language-configuration.json" }], "grammars": [{ "language": "bat", "scopeName": "source.batchfile", "path": "./syntaxes/batchfile.tmLanguage.json" }], "snippets": [{ "language": "bat", "path": "./snippets/batchfile.code-snippets" }] }, "repository": { "type": "git", "url": "https://github.com/microsoft/vscode.git" } }, "packageNLS": { "displayName": "Windows Bat Language Basics", "description": "Provides snippets, syntax highlighting, bracket matching and folding in Windows batch files." } }, { "extensionPath": "clojure", "packageJSON": { "name": "clojure", "displayName": "%displayName%", "description": "%description%", "version": "1.0.0", "publisher": "vscode", "license": "MIT", "engines": { "vscode": "*" }, "scripts": { "update-grammar": "node ../node_modules/vscode-grammar-updater/bin atom/language-clojure grammars/clojure.cson ./syntaxes/clojure.tmLanguage.json" }, "categories": ["Programming Languages"], "contributes": { "languages": [{ "id": "clojure", "aliases": ["Clojure", "clojure"], "extensions": [".clj", ".cljs", ".cljc", ".cljx", ".clojure", ".edn"], "configuration": "./language-configuration.json" }], "grammars": [{ "language": "clojure", "scopeName": "source.clojure", "path": "./syntaxes/clojure.tmLanguage.json" }], "configurationDefaults": { "[clojure]": { "diffEditor.ignoreTrimWhitespace": false } } }, "repository": { "type": "git", "url": "https://github.com/microsoft/vscode.git" } }, "packageNLS": { "displayName": "Clojure Language Basics", "description": "Provides syntax highlighting and bracket matching in Clojure files." } }, { "extensionPath": "coffeescript", "packageJSON": { "name": "coffeescript", "displayName": "%displayName%", "description": "%description%", "version": "1.0.0", "publisher": "vscode", "license": "MIT", "engines": { "vscode": "*" }, "scripts": { "update-grammar": "node ../node_modules/vscode-grammar-updater/bin atom/language-coffee-script grammars/coffeescript.cson ./syntaxes/coffeescript.tmLanguage.json" }, "categories": ["Programming Languages"], "contributes": { "languages": [{ "id": "coffeescript", "extensions": [".coffee", ".cson", ".iced"], "aliases": ["CoffeeScript", "coffeescript", "coffee"], "configuration": "./language-configuration.json" }], "grammars": [{ "language": "coffeescript", "scopeName": "source.coffee", "path": "./syntaxes/coffeescript.tmLanguage.json" }], "breakpoints": [{ "language": "coffeescript" }], "snippets": [{ "language": "coffeescript", "path": "./snippets/coffeescript.code-snippets" }], "configurationDefaults": { "[coffeescript]": { "diffEditor.ignoreTrimWhitespace": false, "editor.defaultColorDecorators": false } } }, "repository": { "type": "git", "url": "https://github.com/microsoft/vscode.git" } }, "packageNLS": { "displayName": "CoffeeScript Language Basics", "description": "Provides snippets, syntax highlighting, bracket matching and folding in CoffeeScript files." } }, { "extensionPath": "configuration-editing", "packageJSON": { "name": "configuration-editing", "displayName": "%displayName%", "description": "%description%", "version": "1.0.0", "publisher": "vscode", "license": "MIT", "engines": { "vscode": "^1.0.0" }, "icon": "images/icon.png", "activationEvents": ["onProfile", "onProfile:github", "onLanguage:json", "onLanguage:jsonc"], "enabledApiProposals": ["profileContentHandlers"], "main": "./dist/configurationEditingMain", "browser": "./dist/browser/configurationEditingMain", "capabilities": { "virtualWorkspaces": true, "untrustedWorkspaces": { "supported": true } }, "contributes": { "languages": [{ "id": "jsonc", "extensions": [".code-workspace", "language-configuration.json", "icon-theme.json", "color-theme.json"], "filenames": ["settings.json", "launch.json", "tasks.json", "keybindings.json", "extensions.json", "argv.json", "profiles.json", "devcontainer.json", ".devcontainer.json"] }, { "id": "json", "extensions": [".code-profile"] }], "jsonValidation": [{ "fileMatch": "vscode://defaultsettings/keybindings.json", "url": "vscode://schemas/keybindings" }, { "fileMatch": "%APP_SETTINGS_HOME%/keybindings.json", "url": "vscode://schemas/keybindings" }, { "fileMatch": "%APP_SETTINGS_HOME%/profiles/*/keybindings.json", "url": "vscode://schemas/keybindings" }, { "fileMatch": "vscode://defaultsettings/*.json", "url": "vscode://schemas/settings/default" }, { "fileMatch": "%APP_SETTINGS_HOME%/settings.json", "url": "vscode://schemas/settings/user" }, { "fileMatch": "%APP_SETTINGS_HOME%/profiles/*/settings.json", "url": "vscode://schemas/settings/profile" }, { "fileMatch": "%MACHINE_SETTINGS_HOME%/settings.json", "url": "vscode://schemas/settings/machine" }, { "fileMatch": "%APP_WORKSPACES_HOME%/*/workspace.json", "url": "vscode://schemas/workspaceConfig" }, { "fileMatch": "**/*.code-workspace", "url": "vscode://schemas/workspaceConfig" }, { "fileMatch": "**/argv.json", "url": "vscode://schemas/argv" }, { "fileMatch": "/.vscode/settings.json", "url": "vscode://schemas/settings/folder" }, { "fileMatch": "/.vscode/launch.json", "url": "vscode://schemas/launch" }, { "fileMatch": "/.vscode/tasks.json", "url": "vscode://schemas/tasks" }, { "fileMatch": "%APP_SETTINGS_HOME%/tasks.json", "url": "vscode://schemas/tasks" }, { "fileMatch": "%APP_SETTINGS_HOME%/snippets/*.json", "url": "vscode://schemas/snippets" }, { "fileMatch": "%APP_SETTINGS_HOME%/profiles/*/snippets/.json", "url": "vscode://schemas/snippets" }, { "fileMatch": "%APP_SETTINGS_HOME%/sync/snippets/preview/*.json", "url": "vscode://schemas/snippets" }, { "fileMatch": "**/*.code-snippets", "url": "vscode://schemas/global-snippets" }, { "fileMatch": "/.vscode/extensions.json", "url": "vscode://schemas/extensions" }, { "fileMatch": "devcontainer.json", "url": "https://raw.githubusercontent.com/devcontainers/spec/main/schemas/devContainer.schema.json" }, { "fileMatch": ".devcontainer.json", "url": "https://raw.githubusercontent.com/devcontainers/spec/main/schemas/devContainer.schema.json" }, { "fileMatch": "%APP_SETTINGS_HOME%/globalStorage/ms-vscode-remote.remote-containers/nameConfigs/*.json", "url": "./schemas/attachContainer.schema.json" }, { "fileMatch": "%APP_SETTINGS_HOME%/globalStorage/ms-vscode-remote.remote-containers/imageConfigs/*.json", "url": "./schemas/attachContainer.schema.json" }, { "fileMatch": "**/quality/*/product.json", "url": "vscode://schemas/vscode-product" }] }, "repository": { "type": "git", "url": "https://github.com/microsoft/vscode.git" } }, "packageNLS": { "displayName": "Configuration Editing", "description": "Provides capabilities (advanced IntelliSense, auto-fixing) in configuration files like settings, launch, and extension recommendation files." } }, { "extensionPath": "cpp", "packageJSON": { "name": "cpp", "displayName": "%displayName%", "description": "%description%", "version": "1.0.0", "publisher": "vscode", "license": "MIT", "engines": { "vscode": "*" }, "scripts": { "update-grammar": "node ./build/update-grammars.js" }, "categories": ["Programming Languages"], "contributes": { "languages": [{ "id": "c", "extensions": [".c", ".i"], "aliases": ["C", "c"], "configuration": "./language-configuration.json" }, { "id": "cpp", "extensions": [".cpp", ".cppm", ".cc", ".ccm", ".cxx", ".cxxm", ".c++", ".c++m", ".hpp", ".hh", ".hxx", ".h++", ".h", ".ii", ".ino", ".inl", ".ipp", ".ixx", ".tpp", ".txx", ".hpp.in", ".h.in"], "aliases": ["C++", "Cpp", "cpp"], "configuration": "./language-configuration.json" }, { "id": "cuda-cpp", "extensions": [".cu", ".cuh"], "aliases": ["CUDA C++"], "configuration": "./language-configuration.json" }], "grammars": [{ "language": "c", "scopeName": "source.c", "path": "./syntaxes/c.tmLanguage.json" }, { "language": "cpp", "scopeName": "source.cpp.embedded.macro", "path": "./syntaxes/cpp.embedded.macro.tmLanguage.json" }, { "language": "cpp", "scopeName": "source.cpp", "path": "./syntaxes/cpp.tmLanguage.json" }, { "scopeName": "source.c.platform", "path": "./syntaxes/platform.tmLanguage.json" }, { "language": "cuda-cpp", "scopeName": "source.cuda-cpp", "path": "./syntaxes/cuda-cpp.tmLanguage.json" }], "problemPatterns": [{ "name": "nvcc-location", "regexp": "^(.*)\\((\\d+)\\):\\s+(warning|error):\\s+(.*)", "kind": "location", "file": 1, "location": 2, "severity": 3, "message": 4 }], "problemMatchers": [{ "name": "nvcc", "owner": "cuda-cpp", "fileLocation": ["relative", "${workspaceFolder}"], "pattern": "$nvcc-location" }], "snippets": [{ "language": "c", "path": "./snippets/c.code-snippets" }, { "language": "cpp", "path": "./snippets/cpp.code-snippets" }] }, "repository": { "type": "git", "url": "https://github.com/microsoft/vscode.git" } }, "packageNLS": { "displayName": "C/C++ Language Basics", "description": "Provides snippets, syntax highlighting, bracket matching and folding in C/C++ files." } }, { "extensionPath": "csharp", "packageJSON": { "name": "csharp", "displayName": "%displayName%", "description": "%description%", "version": "1.0.0", "publisher": "vscode", "license": "MIT", "engines": { "vscode": "0.10.x" }, "scripts": { "update-grammar": "node ../node_modules/vscode-grammar-updater/bin dotnet/csharp-tmLanguage grammars/csharp.tmLanguage ./syntaxes/csharp.tmLanguage.json" }, "categories": ["Programming Languages"], "contributes": { "configurationDefaults": { "[csharp]": { "editor.maxTokenizationLineLength": 2500 } }, "languages": [{ "id": "csharp", "extensions": [".cs", ".csx", ".cake"], "aliases": ["C#", "csharp"], "configuration": "./language-configuration.json" }], "grammars": [{ "language": "csharp", "scopeName": "source.cs", "path": "./syntaxes/csharp.tmLanguage.json", "tokenTypes": { "meta.interpolation": "other" } }], "snippets": [{ "language": "csharp", "path": "./snippets/csharp.code-snippets" }] }, "repository": { "type": "git", "url": "https://github.com/microsoft/vscode.git" } }, "packageNLS": { "displayName": "C# Language Basics", "description": "Provides snippets, syntax highlighting, bracket matching and folding in C# files." } }, { "extensionPath": "css", "packageJSON": { "name": "css", "displayName": "%displayName%", "description": "%description%", "version": "1.0.0", "publisher": "vscode", "license": "MIT", "engines": { "vscode": "0.10.x" }, "scripts": { "update-grammar": "node ../node_modules/vscode-grammar-updater/bin microsoft/vscode-css grammars/css.cson ./syntaxes/css.tmLanguage.json" }, "categories": ["Programming Languages"], "contributes": { "languages": [{ "id": "css", "aliases": ["CSS", "css"], "extensions": [".css"], "mimetypes": ["text/css"], "configuration": "./language-configuration.json" }], "grammars": [{ "language": "css", "scopeName": "source.css", "path": "./syntaxes/css.tmLanguage.json", "tokenTypes": { "meta.function.url string.quoted": "other" } }] }, "repository": { "type": "git", "url": "https://github.com/microsoft/vscode.git" } }, "packageNLS": { "displayName": "CSS Language Basics", "description": "Provides syntax highlighting and bracket matching for CSS, LESS and SCSS files." } }, { "extensionPath": "css-language-features", "packageJSON": { "name": "css-language-features", "displayName": "%displayName%", "description": "%description%", "version": "1.0.0", "publisher": "vscode", "license": "MIT", "engines": { "vscode": "^1.77.0" }, "icon": "icons/css.png", "activationEvents": ["onLanguage:css", "onLanguage:less", "onLanguage:scss", "onCommand:_css.applyCodeAction"], "main": "./client/dist/node/cssClientMain", "browser": "./client/dist/browser/cssClientMain", "capabilities": { "virtualWorkspaces": true, "untrustedWorkspaces": { "supported": true } }, "enabledApiProposals": ["documentPaste"], "categories": ["Programming Languages"], "contributes": { "configuration": [{ "order": 22, "id": "css", "title": "%css.title%", "properties": { "css.customData": { "type": "array", "markdownDescription": "%css.customData.desc%", "default": [], "items": { "type": "string" }, "scope": "resource" }, "css.completion.triggerPropertyValueCompletion": { "type": "boolean", "scope": "resource", "default": true, "description": "%css.completion.triggerPropertyValueCompletion.desc%" }, "css.completion.completePropertyWithSemicolon": { "type": "boolean", "scope": "resource", "default": true, "description": "%css.completion.completePropertyWithSemicolon.desc%" }, "css.validate": { "type": "boolean", "scope": "resource", "default": true, "description": "%css.validate.desc%" }, "css.hover.documentation": { "type": "boolean", "scope": "resource", "default": true, "description": "%css.hover.documentation%" }, "css.hover.references": { "type": "boolean", "scope": "resource", "default": true, "description": "%css.hover.references%" }, "css.lint.compatibleVendorPrefixes": { "type": "string", "scope": "resource", "enum": ["ignore", "warning", "error"], "default": "ignore", "description": "%css.lint.compatibleVendorPrefixes.desc%" }, "css.lint.vendorPrefix": { "type": "string", "scope": "resource", "enum": ["ignore", "warning", "error"], "default": "warning", "description": "%css.lint.vendorPrefix.desc%" }, "css.lint.duplicateProperties": { "type": "string", "scope": "resource", "enum": ["ignore", "warning", "error"], "default": "ignore", "description": "%css.lint.duplicateProperties.desc%" }, "css.lint.emptyRules": { "type": "string", "scope": "resource", "enum": ["ignore", "warning", "error"], "default": "warning", "description": "%css.lint.emptyRules.desc%" }, "css.lint.importStatement": { "type": "string", "scope": "resource", "enum": ["ignore", "warning", "error"], "default": "ignore", "description": "%css.lint.importStatement.desc%" }, "css.lint.boxModel": { "type": "string", "scope": "resource", "enum": ["ignore", "warning", "error"], "default": "ignore", "markdownDescription": "%css.lint.boxModel.desc%" }, "css.lint.universalSelector": { "type": "string", "scope": "resource", "enum": ["ignore", "warning", "error"], "default": "ignore", "markdownDescription": "%css.lint.universalSelector.desc%" }, "css.lint.zeroUnits": { "type": "string", "scope": "resource", "enum": ["ignore", "warning", "error"], "default": "ignore", "description": "%css.lint.zeroUnits.desc%" }, "css.lint.fontFaceProperties": { "type": "string", "scope": "resource", "enum": ["ignore", "warning", "error"], "default": "warning", "markdownDescription": "%css.lint.fontFaceProperties.desc%" }, "css.lint.hexColorLength": { "type": "string", "scope": "resource", "enum": ["ignore", "warning", "error"], "default": "error", "description": "%css.lint.hexColorLength.desc%" }, "css.lint.argumentsInColorFunction": { "type": "string", "scope": "resource", "enum": ["ignore", "warning", "error"], "default": "error", "description": "%css.lint.argumentsInColorFunction.desc%" }, "css.lint.unknownProperties": { "type": "string", "scope": "resource", "enum": ["ignore", "warning", "error"], "default": "warning", "description": "%css.lint.unknownProperties.desc%" }, "css.lint.validProperties": { "type": "array", "uniqueItems": true, "items": { "type": "string" }, "scope": "resource", "default": [], "description": "%css.lint.validProperties.desc%" }, "css.lint.ieHack": { "type": "string", "scope": "resource", "enum": ["ignore", "warning", "error"], "default": "ignore", "description": "%css.lint.ieHack.desc%" }, "css.lint.unknownVendorSpecificProperties": { "type": "string", "scope": "resource", "enum": ["ignore", "warning", "error"], "default": "ignore", "description": "%css.lint.unknownVendorSpecificProperties.desc%" }, "css.lint.propertyIgnoredDueToDisplay": { "type": "string", "scope": "resource", "enum": ["ignore", "warning", "error"], "default": "warning", "markdownDescription": "%css.lint.propertyIgnoredDueToDisplay.desc%" }, "css.lint.important": { "type": "string", "scope": "resource", "enum": ["ignore", "warning", "error"], "default": "ignore", "markdownDescription": "%css.lint.important.desc%" }, "css.lint.float": { "type": "string", "scope": "resource", "enum": ["ignore", "warning", "error"], "default": "ignore", "markdownDescription": "%css.lint.float.desc%" }, "css.lint.idSelector": { "type": "string", "scope": "resource", "enum": ["ignore", "warning", "error"], "default": "ignore", "description": "%css.lint.idSelector.desc%" }, "css.lint.unknownAtRules": { "type": "string", "scope": "resource", "enum": ["ignore", "warning", "error"], "default": "warning", "description": "%css.lint.unknownAtRules.desc%" }, "css.trace.server": { "type": "string", "scope": "window", "enum": ["off", "messages", "verbose"], "default": "off", "description": "%css.trace.server.desc%" }, "css.format.enable": { "type": "boolean", "scope": "window", "default": true, "description": "%css.format.enable.desc%" }, "css.format.newlineBetweenSelectors": { "type": "boolean", "scope": "resource", "default": true, "markdownDescription": "%css.format.newlineBetweenSelectors.desc%" }, "css.format.newlineBetweenRules": { "type": "boolean", "scope": "resource", "default": true, "markdownDescription": "%css.format.newlineBetweenRules.desc%" }, "css.format.spaceAroundSelectorSeparator": { "type": "boolean", "scope": "resource", "default": false, "markdownDescription": "%css.format.spaceAroundSelectorSeparator.desc%" }, "css.format.braceStyle": { "type": "string", "scope": "resource", "default": "collapse", "enum": ["collapse", "expand"], "markdownDescription": "%css.format.braceStyle.desc%" }, "css.format.preserveNewLines": { "type": "boolean", "scope": "resource", "default": true, "markdownDescription": "%css.format.preserveNewLines.desc%" }, "css.format.maxPreserveNewLines": { "type": ["number", "null"], "scope": "resource", "default": null, "markdownDescription": "%css.format.maxPreserveNewLines.desc%" } } }, { "id": "scss", "order": 24, "title": "%scss.title%", "properties": { "scss.completion.triggerPropertyValueCompletion": { "type": "boolean", "scope": "resource", "default": true, "description": "%scss.completion.triggerPropertyValueCompletion.desc%" }, "scss.completion.completePropertyWithSemicolon": { "type": "boolean", "scope": "resource", "default": true, "description": "%scss.completion.completePropertyWithSemicolon.desc%" }, "scss.validate": { "type": "boolean", "scope": "resource", "default": true, "description": "%scss.validate.desc%" }, "scss.hover.documentation": { "type": "boolean", "scope": "resource", "default": true, "description": "%scss.hover.documentation%" }, "scss.hover.references": { "type": "boolean", "scope": "resource", "default": true, "description": "%scss.hover.references%" }, "scss.lint.compatibleVendorPrefixes": { "type": "string", "scope": "resource", "enum": ["ignore", "warning", "error"], "default": "ignore", "description": "%scss.lint.compatibleVendorPrefixes.desc%" }, "scss.lint.vendorPrefix": { "type": "string", "scope": "resource", "enum": ["ignore", "warning", "error"], "default": "warning", "description": "%scss.lint.vendorPrefix.desc%" }, "scss.lint.duplicateProperties": { "type": "string", "scope": "resource", "enum": ["ignore", "warning", "error"], "default": "ignore", "description": "%scss.lint.duplicateProperties.desc%" }, "scss.lint.emptyRules": { "type": "string", "scope": "resource", "enum": ["ignore", "warning", "error"], "default": "warning", "description": "%scss.lint.emptyRules.desc%" }, "scss.lint.importStatement": { "type": "string", "scope": "resource", "enum": ["ignore", "warning", "error"], "default": "ignore", "description": "%scss.lint.importStatement.desc%" }, "scss.lint.boxModel": { "type": "string", "scope": "resource", "enum": ["ignore", "warning", "error"], "default": "ignore", "markdownDescription": "%scss.lint.boxModel.desc%" }, "scss.lint.universalSelector": { "type": "string", "scope": "resource", "enum": ["ignore", "warning", "error"], "default": "ignore", "markdownDescription": "%scss.lint.universalSelector.desc%" }, "scss.lint.zeroUnits": { "type": "string", "scope": "resource", "enum": ["ignore", "warning", "error"], "default": "ignore", "description": "%scss.lint.zeroUnits.desc%" }, "scss.lint.fontFaceProperties": { "type": "string", "scope": "resource", "enum": ["ignore", "warning", "error"], "default": "warning", "markdownDescription": "%scss.lint.fontFaceProperties.desc%" }, "scss.lint.hexColorLength": { "type": "string", "scope": "resource", "enum": ["ignore", "warning", "error"], "default": "error", "description": "%scss.lint.hexColorLength.desc%" }, "scss.lint.argumentsInColorFunction": { "type": "string", "scope": "resource", "enum": ["ignore", "warning", "error"], "default": "error", "description": "%scss.lint.argumentsInColorFunction.desc%" }, "scss.lint.unknownProperties": { "type": "string", "scope": "resource", "enum": ["ignore", "warning", "error"], "default": "warning", "description": "%scss.lint.unknownProperties.desc%" }, "scss.lint.validProperties": { "type": "array", "uniqueItems": true, "items": { "type": "string" }, "scope": "resource", "default": [], "description": "%scss.lint.validProperties.desc%" }, "scss.lint.ieHack": { "type": "string", "scope": "resource", "enum": ["ignore", "warning", "error"], "default": "ignore", "description": "%scss.lint.ieHack.desc%" }, "scss.lint.unknownVendorSpecificProperties": { "type": "string", "scope": "resource", "enum": ["ignore", "warning", "error"], "default": "ignore", "description": "%scss.lint.unknownVendorSpecificProperties.desc%" }, "scss.lint.propertyIgnoredDueToDisplay": { "type": "string", "scope": "resource", "enum": ["ignore", "warning", "error"], "default": "warning", "markdownDescription": "%scss.lint.propertyIgnoredDueToDisplay.desc%" }, "scss.lint.important": { "type": "string", "scope": "resource", "enum": ["ignore", "warning", "error"], "default": "ignore", "markdownDescription": "%scss.lint.important.desc%" }, "scss.lint.float": { "type": "string", "scope": "resource", "enum": ["ignore", "warning", "error"], "default": "ignore", "markdownDescription": "%scss.lint.float.desc%" }, "scss.lint.idSelector": { "type": "string", "scope": "resource", "enum": ["ignore", "warning", "error"], "default": "ignore", "description": "%scss.lint.idSelector.desc%" }, "scss.lint.unknownAtRules": { "type": "string", "scope": "resource", "enum": ["ignore", "warning", "error"], "default": "warning", "description": "%scss.lint.unknownAtRules.desc%" }, "scss.format.enable": { "type": "boolean", "scope": "window", "default": true, "description": "%scss.format.enable.desc%" }, "scss.format.newlineBetweenSelectors": { "type": "boolean", "scope": "resource", "default": true, "markdownDescription": "%scss.format.newlineBetweenSelectors.desc%" }, "scss.format.newlineBetweenRules": { "type": "boolean", "scope": "resource", "default": true, "markdownDescription": "%scss.format.newlineBetweenRules.desc%" }, "scss.format.spaceAroundSelectorSeparator": { "type": "boolean", "scope": "resource", "default": false, "markdownDescription": "%scss.format.spaceAroundSelectorSeparator.desc%" }, "scss.format.braceStyle": { "type": "string", "scope": "resource", "default": "collapse", "enum": ["collapse", "expand"], "markdownDescription": "%scss.format.braceStyle.desc%" }, "scss.format.preserveNewLines": { "type": "boolean", "scope": "resource", "default": true, "markdownDescription": "%scss.format.preserveNewLines.desc%" }, "scss.format.maxPreserveNewLines": { "type": ["number", "null"], "scope": "resource", "default": null, "markdownDescription": "%scss.format.maxPreserveNewLines.desc%" } } }, { "id": "less", "order": 23, "type": "object", "title": "%less.title%", "properties": { "less.completion.triggerPropertyValueCompletion": { "type": "boolean", "scope": "resource", "default": true, "description": "%less.completion.triggerPropertyValueCompletion.desc%" }, "less.completion.completePropertyWithSemicolon": { "type": "boolean", "scope": "resource", "default": true, "description": "%less.completion.completePropertyWithSemicolon.desc%" }, "less.validate": { "type": "boolean", "scope": "resource", "default": true, "description": "%less.validate.desc%" }, "less.hover.documentation": { "type": "boolean", "scope": "resource", "default": true, "description": "%less.hover.documentation%" }, "less.hover.references": { "type": "boolean", "scope": "resource", "default": true, "description": "%less.hover.references%" }, "less.lint.compatibleVendorPrefixes": { "type": "string", "scope": "resource", "enum": ["ignore", "warning", "error"], "default": "ignore", "description": "%less.lint.compatibleVendorPrefixes.desc%" }, "less.lint.vendorPrefix": { "type": "string", "scope": "resource", "enum": ["ignore", "warning", "error"], "default": "warning", "description": "%less.lint.vendorPrefix.desc%" }, "less.lint.duplicateProperties": { "type": "string", "scope": "resource", "enum": ["ignore", "warning", "error"], "default": "ignore", "description": "%less.lint.duplicateProperties.desc%" }, "less.lint.emptyRules": { "type": "string", "scope": "resource", "enum": ["ignore", "warning", "error"], "default": "warning", "description": "%less.lint.emptyRules.desc%" }, "less.lint.importStatement": { "type": "string", "scope": "resource", "enum": ["ignore", "warning", "error"], "default": "ignore", "description": "%less.lint.importStatement.desc%" }, "less.lint.boxModel": { "type": "string", "scope": "resource", "enum": ["ignore", "warning", "error"], "default": "ignore", "markdownDescription": "%less.lint.boxModel.desc%" }, "less.lint.universalSelector": { "type": "string", "scope": "resource", "enum": ["ignore", "warning", "error"], "default": "ignore", "markdownDescription": "%less.lint.universalSelector.desc%" }, "less.lint.zeroUnits": { "type": "string", "scope": "resource", "enum": ["ignore", "warning", "error"], "default": "ignore", "description": "%less.lint.zeroUnits.desc%" }, "less.lint.fontFaceProperties": { "type": "string", "scope": "resource", "enum": ["ignore", "warning", "error"], "default": "warning", "markdownDescription": "%less.lint.fontFaceProperties.desc%" }, "less.lint.hexColorLength": { "type": "string", "scope": "resource", "enum": ["ignore", "warning", "error"], "default": "error", "description": "%less.lint.hexColorLength.desc%" }, "less.lint.argumentsInColorFunction": { "type": "string", "scope": "resource", "enum": ["ignore", "warning", "error"], "default": "error", "description": "%less.lint.argumentsInColorFunction.desc%" }, "less.lint.unknownProperties": { "type": "string", "scope": "resource", "enum": ["ignore", "warning", "error"], "default": "warning", "description": "%less.lint.unknownProperties.desc%" }, "less.lint.validProperties": { "type": "array", "uniqueItems": true, "items": { "type": "string" }, "scope": "resource", "default": [], "description": "%less.lint.validProperties.desc%" }, "less.lint.ieHack": { "type": "string", "scope": "resource", "enum": ["ignore", "warning", "error"], "default": "ignore", "description": "%less.lint.ieHack.desc%" }, "less.lint.unknownVendorSpecificProperties": { "type": "string", "scope": "resource", "enum": ["ignore", "warning", "error"], "default": "ignore", "description": "%less.lint.unknownVendorSpecificProperties.desc%" }, "less.lint.propertyIgnoredDueToDisplay": { "type": "string", "scope": "resource", "enum": ["ignore", "warning", "error"], "default": "warning", "markdownDescription": "%less.lint.propertyIgnoredDueToDisplay.desc%" }, "less.lint.important": { "type": "string", "scope": "resource", "enum": ["ignore", "warning", "error"], "default": "ignore", "markdownDescription": "%less.lint.important.desc%" }, "less.lint.float": { "type": "string", "scope": "resource", "enum": ["ignore", "warning", "error"], "default": "ignore", "markdownDescription": "%less.lint.float.desc%" }, "less.lint.idSelector": { "type": "string", "scope": "resource", "enum": ["ignore", "warning", "error"], "default": "ignore", "description": "%less.lint.idSelector.desc%" }, "less.lint.unknownAtRules": { "type": "string", "scope": "resource", "enum": ["ignore", "warning", "error"], "default": "warning", "description": "%less.lint.unknownAtRules.desc%" }, "less.format.enable": { "type": "boolean", "scope": "window", "default": true, "description": "%less.format.enable.desc%" }, "less.format.newlineBetweenSelectors": { "type": "boolean", "scope": "resource", "default": true, "markdownDescription": "%less.format.newlineBetweenSelectors.desc%" }, "less.format.newlineBetweenRules": { "type": "boolean", "scope": "resource", "default": true, "markdownDescription": "%less.format.newlineBetweenRules.desc%" }, "less.format.spaceAroundSelectorSeparator": { "type": "boolean", "scope": "resource", "default": false, "markdownDescription": "%less.format.spaceAroundSelectorSeparator.desc%" }, "less.format.braceStyle": { "type": "string", "scope": "resource", "default": "collapse", "enum": ["collapse", "expand"], "markdownDescription": "%less.format.braceStyle.desc%" }, "less.format.preserveNewLines": { "type": "boolean", "scope": "resource", "default": true, "markdownDescription": "%less.format.preserveNewLines.desc%" }, "less.format.maxPreserveNewLines": { "type": ["number", "null"], "scope": "resource", "default": null, "markdownDescription": "%less.format.maxPreserveNewLines.desc%" } } }], "configurationDefaults": { "[css]": { "editor.suggest.insertMode": "replace" }, "[scss]": { "editor.suggest.insertMode": "replace" }, "[less]": { "editor.suggest.insertMode": "replace" } }, "jsonValidation": [{ "fileMatch": "*.css-data.json", "url": "https://raw.githubusercontent.com/microsoft/vscode-css-languageservice/master/docs/customData.schema.json" }, { "fileMatch": "package.json", "url": "./schemas/package.schema.json" }] }, "repository": { "type": "git", "url": "https://github.com/microsoft/vscode.git" } }, "packageNLS": { "displayName": "CSS Language Features", "description": "Provides rich language support for CSS, LESS and SCSS files.", "css.title": "CSS", "css.customData.desc": "A list of relative file paths pointing to JSON files following the [custom data format](https://github.com/microsoft/vscode-css-languageservice/blob/master/docs/customData.md).\n\nVS Code loads custom data on startup to enhance its CSS support for CSS custom properties (variables), at-rules, pseudo-classes, and pseudo-elements you specify in the JSON files.\n\nThe file paths are relative to workspace and only workspace folder settings are considered.", "css.completion.triggerPropertyValueCompletion.desc": "By default, VS Code triggers property value completion after selecting a CSS property. Use this setting to disable this behavior.", "css.completion.completePropertyWithSemicolon.desc": "Insert semicolon at end of line when completing CSS properties.", "css.lint.argumentsInColorFunction.desc": "Invalid number of parameters.", "css.lint.boxModel.desc": "Do not use `width` or `height` when using `padding` or `border`.", "css.lint.compatibleVendorPrefixes.desc": "When using a vendor-specific prefix make sure to also include all other vendor-specific properties.", "css.lint.duplicateProperties.desc": "Do not use duplicate style definitions.", "css.lint.emptyRules.desc": "Do not use empty rulesets.", "css.lint.float.desc": "Avoid using `float`. Floats lead to fragile CSS that is easy to break if one aspect of the layout changes.", "css.lint.fontFaceProperties.desc": "`@font-face` rule must define `src` and `font-family` properties.", "css.lint.hexColorLength.desc": "Hex colors must consist of 3, 4, 6 or 8 hex numbers.", "css.lint.idSelector.desc": "Selectors should not contain IDs because these rules are too tightly coupled with the HTML.", "css.lint.ieHack.desc": "IE hacks are only necessary when supporting IE7 and older.", "css.lint.important.desc": "Avoid using `!important`. It is an indication that the specificity of the entire CSS has gotten out of control and needs to be refactored.", "css.lint.importStatement.desc": "Import statements do not load in parallel.", "css.lint.propertyIgnoredDueToDisplay.desc": "Property is ignored due to the display. E.g. with `display: inline`, the `width`, `height`, `margin-top`, `margin-bottom`, and `float` properties have no effect.", "css.lint.universalSelector.desc": "The universal selector (`*`) is known to be slow.", "css.lint.unknownAtRules.desc": "Unknown at-rule.", "css.lint.unknownProperties.desc": "Unknown property.", "css.lint.validProperties.desc": "A list of properties that are not validated against the `unknownProperties` rule.", "css.lint.unknownVendorSpecificProperties.desc": "Unknown vendor specific property.", "css.lint.vendorPrefix.desc": "When using a vendor-specific prefix, also include the standard property.", "css.lint.zeroUnits.desc": "No unit for zero needed.", "css.trace.server.desc": "Traces the communication between VS Code and the CSS language server.", "css.validate.title": "Controls CSS validation and problem severities.", "css.validate.desc": "Enables or disables all validations.", "css.hover.documentation": "Show property and value documentation in CSS hovers.", "css.hover.references": "Show references to MDN in CSS hovers.", "css.format.enable.desc": "Enable/disable default CSS formatter.", "css.format.newlineBetweenSelectors.desc": "Separate selectors with a new line.", "css.format.newlineBetweenRules.desc": "Separate rulesets by a blank line.", "css.format.spaceAroundSelectorSeparator.desc": "Ensure a space character around selector separators '>', '+', '~' (e.g. `a > b`).", "css.format.braceStyle.desc": "Put braces on the same line as rules (`collapse`) or put braces on own line (`expand`).", "css.format.preserveNewLines.desc": "Whether existing line breaks before elements should be preserved.", "css.format.maxPreserveNewLines.desc": "Maximum number of line breaks to be preserved in one chunk, when `#css.format.preserveNewLines#` is enabled.", "less.title": "LESS", "less.completion.triggerPropertyValueCompletion.desc": "By default, VS Code triggers property value completion after selecting a CSS property. Use this setting to disable this behavior.", "less.completion.completePropertyWithSemicolon.desc": "Insert semicolon at end of line when completing CSS properties.", "less.lint.argumentsInColorFunction.desc": "Invalid number of parameters.", "less.lint.boxModel.desc": "Do not use `width` or `height` when using `padding` or `border`.", "less.lint.compatibleVendorPrefixes.desc": "When using a vendor-specific prefix make sure to also include all other vendor-specific properties.", "less.lint.duplicateProperties.desc": "Do not use duplicate style definitions.", "less.lint.emptyRules.desc": "Do not use empty rulesets.", "less.lint.float.desc": "Avoid using `float`. Floats lead to fragile CSS that is easy to break if one aspect of the layout changes.", "less.lint.fontFaceProperties.desc": "`@font-face` rule must define `src` and `font-family` properties.", "less.lint.hexColorLength.desc": "Hex colors must consist of 3, 4, 6 or 8 hex numbers.", "less.lint.idSelector.desc": "Selectors should not contain IDs because these rules are too tightly coupled with the HTML.", "less.lint.ieHack.desc": "IE hacks are only necessary when supporting IE7 and older.", "less.lint.important.desc": "Avoid using `!important`. It is an indication that the specificity of the entire CSS has gotten out of control and needs to be refactored.", "less.lint.importStatement.desc": "Import statements do not load in parallel.", "less.lint.propertyIgnoredDueToDisplay.desc": "Property is ignored due to the display. E.g. with `display: inline`, the `width`, `height`, `margin-top`, `margin-bottom`, and `float` properties have no effect.", "less.lint.universalSelector.desc": "The universal selector (`*`) is known to be slow.", "less.lint.unknownAtRules.desc": "Unknown at-rule.", "less.lint.unknownProperties.desc": "Unknown property.", "less.lint.validProperties.desc": "A list of properties that are not validated against the `unknownProperties` rule.", "less.lint.unknownVendorSpecificProperties.desc": "Unknown vendor specific property.", "less.lint.vendorPrefix.desc": "When using a vendor-specific prefix, also include the standard property.", "less.lint.zeroUnits.desc": "No unit for zero needed.", "less.validate.title": "Controls LESS validation and problem severities.", "less.validate.desc": "Enables or disables all validations.", "less.hover.documentation": "Show property and value documentation in LESS hovers.", "less.hover.references": "Show references to MDN in LESS hovers.", "less.format.enable.desc": "Enable/disable default LESS formatter.", "less.format.newlineBetweenSelectors.desc": "Separate selectors with a new line.", "less.format.newlineBetweenRules.desc": "Separate rulesets by a blank line.", "less.format.spaceAroundSelectorSeparator.desc": "Ensure a space character around selector separators '>', '+', '~' (e.g. `a > b`).", "less.format.braceStyle.desc": "Put braces on the same line as rules (`collapse`) or put braces on own line (`expand`).", "less.format.preserveNewLines.desc": "Whether existing line breaks before elements should be preserved.", "less.format.maxPreserveNewLines.desc": "Maximum number of line breaks to be preserved in one chunk, when `#less.format.preserveNewLines#` is enabled.", "scss.title": "SCSS (Sass)", "scss.completion.triggerPropertyValueCompletion.desc": "By default, VS Code triggers property value completion after selecting a CSS property. Use this setting to disable this behavior.", "scss.completion.completePropertyWithSemicolon.desc": "Insert semicolon at end of line when completing CSS properties.", "scss.lint.argumentsInColorFunction.desc": "Invalid number of parameters.", "scss.lint.boxModel.desc": "Do not use `width` or `height` when using `padding` or `border`.", "scss.lint.compatibleVendorPrefixes.desc": "When using a vendor-specific prefix make sure to also include all other vendor-specific properties.", "scss.lint.duplicateProperties.desc": "Do not use duplicate style definitions.", "scss.lint.emptyRules.desc": "Do not use empty rulesets.", "scss.lint.float.desc": "Avoid using `float`. Floats lead to fragile CSS that is easy to break if one aspect of the layout changes.", "scss.lint.fontFaceProperties.desc": "`@font-face` rule must define `src` and `font-family` properties.", "scss.lint.hexColorLength.desc": "Hex colors must consist of 3, 4, 6 or 8 hex numbers.", "scss.lint.idSelector.desc": "Selectors should not contain IDs because these rules are too tightly coupled with the HTML.", "scss.lint.ieHack.desc": "IE hacks are only necessary when supporting IE7 and older.", "scss.lint.important.desc": "Avoid using `!important`. It is an indication that the specificity of the entire CSS has gotten out of control and needs to be refactored.", "scss.lint.importStatement.desc": "Import statements do not load in parallel.", "scss.lint.propertyIgnoredDueToDisplay.desc": "Property is ignored due to the display. E.g. with `display: inline`, the `width`, `height`, `margin-top`, `margin-bottom`, and `float` properties have no effect.", "scss.lint.universalSelector.desc": "The universal selector (`*`) is known to be slow.", "scss.lint.unknownAtRules.desc": "Unknown at-rule.", "scss.lint.unknownProperties.desc": "Unknown property.", "scss.lint.validProperties.desc": "A list of properties that are not validated against the `unknownProperties` rule.", "scss.lint.unknownVendorSpecificProperties.desc": "Unknown vendor specific property.", "scss.lint.vendorPrefix.desc": "When using a vendor-specific prefix, also include the standard property.", "scss.lint.zeroUnits.desc": "No unit for zero needed.", "scss.validate.title": "Controls SCSS validation and problem severities.", "scss.validate.desc": "Enables or disables all validations.", "scss.hover.documentation": "Show property and value documentation in SCSS hovers.", "scss.hover.references": "Show references to MDN in SCSS hovers.", "scss.format.enable.desc": "Enable/disable default SCSS formatter.", "scss.format.newlineBetweenSelectors.desc": "Separate selectors with a new line.", "scss.format.newlineBetweenRules.desc": "Separate rulesets by a blank line.", "scss.format.spaceAroundSelectorSeparator.desc": "Ensure a space character around selector separators '>', '+', '~' (e.g. `a > b`).", "scss.format.braceStyle.desc": "Put braces on the same line as rules (`collapse`) or put braces on own line (`expand`).", "scss.format.preserveNewLines.desc": "Whether existing line breaks before elements should be preserved.", "scss.format.maxPreserveNewLines.desc": "Maximum number of line breaks to be preserved in one chunk, when `#scss.format.preserveNewLines#` is enabled.", "css.colorDecorators.enable.deprecationMessage": "The setting `css.colorDecorators.enable` has been deprecated in favor of `editor.colorDecorators`.", "scss.colorDecorators.enable.deprecationMessage": "The setting `scss.colorDecorators.enable` has been deprecated in favor of `editor.colorDecorators`.", "less.colorDecorators.enable.deprecationMessage": "The setting `less.colorDecorators.enable` has been deprecated in favor of `editor.colorDecorators`." }, "readmePath": "css-language-features/README.md" }, { "extensionPath": "dart", "packageJSON": { "name": "dart", "displayName": "%displayName%", "description": "%description%", "version": "1.0.0", "publisher": "vscode", "license": "MIT", "engines": { "vscode": "0.10.x" }, "scripts": { "update-grammar": "node ../node_modules/vscode-grammar-updater/bin dart-lang/dart-syntax-highlight grammars/dart.json ./syntaxes/dart.tmLanguage.json" }, "categories": ["Programming Languages"], "contributes": { "languages": [{ "id": "dart", "extensions": [".dart"], "aliases": ["Dart"], "configuration": "./language-configuration.json" }], "grammars": [{ "language": "dart", "scopeName": "source.dart", "path": "./syntaxes/dart.tmLanguage.json" }] } }, "packageNLS": { "displayName": "Dart Language Basics", "description": "Provides syntax highlighting & bracket matching in Dart files." } }, { "extensionPath": "diff", "packageJSON": { "name": "diff", "displayName": "%displayName%", "description": "%description%", "version": "1.0.0", "publisher": "vscode", "license": "MIT", "engines": { "vscode": "0.10.x" }, "scripts": { "update-grammar": "node ../node_modules/vscode-grammar-updater/bin textmate/diff.tmbundle Syntaxes/Diff.plist ./syntaxes/diff.tmLanguage.json" }, "categories": ["Programming Languages"], "contributes": { "languages": [{ "id": "diff", "aliases": ["Diff", "diff"], "extensions": [".diff", ".patch", ".rej"], "configuration": "./language-configuration.json" }], "grammars": [{ "language": "diff", "scopeName": "source.diff", "path": "./syntaxes/diff.tmLanguage.json" }] } }, "packageNLS": { "displayName": "Diff Language Basics", "description": "Provides syntax highlighting & bracket matching in Diff files." } }, { "extensionPath": "docker", "packageJSON": { "name": "docker", "displayName": "%displayName%", "description": "%description%", "version": "1.0.0", "publisher": "vscode", "license": "MIT", "engines": { "vscode": "*" }, "scripts": { "update-grammar": "node ../node_modules/vscode-grammar-updater/bin moby/moby contrib/syntax/textmate/Docker.tmbundle/Syntaxes/Dockerfile.tmLanguage ./syntaxes/docker.tmLanguage.json" }, "categories": ["Programming Languages"], "contributes": { "languages": [{ "id": "dockerfile", "extensions": [".dockerfile", ".containerfile"], "filenames": ["Dockerfile", "Containerfile"], "filenamePatterns": ["Dockerfile.*", "Containerfile.*"], "aliases": ["Docker", "Dockerfile", "Containerfile"], "configuration": "./language-configuration.json" }], "grammars": [{ "language": "dockerfile", "scopeName": "source.dockerfile", "path": "./syntaxes/docker.tmLanguage.json" }], "configurationDefaults": { "[dockerfile]": { "editor.quickSuggestions": { "strings": true } } } }, "repository": { "type": "git", "url": "https://github.com/microsoft/vscode.git" } }, "packageNLS": { "displayName": "Docker Language Basics", "description": "Provides syntax highlighting and bracket matching in Docker files." } }, { "extensionPath": "emmet", "packageJSON": { "name": "emmet", "displayName": "Emmet", "description": "%description%", "version": "1.0.0", "publisher": "vscode", "license": "MIT", "engines": { "vscode": "^1.13.0" }, "icon": "images/icon.png", "categories": ["Other"], "repository": { "type": "git", "url": "https://github.com/microsoft/vscode.git" }, "activationEvents": ["onCommand:emmet.expandAbbreviation", "onLanguage"], "main": "./dist/node/emmetNodeMain", "browser": "./dist/browser/emmetBrowserMain", "contributes": { "configuration": { "type": "object", "title": "Emmet", "properties": { "emmet.showExpandedAbbreviation": { "type": ["string"], "enum": ["never", "always", "inMarkupAndStylesheetFilesOnly"], "default": "always", "markdownDescription": "%emmetShowExpandedAbbreviation%" }, "emmet.showAbbreviationSuggestions": { "type": "boolean", "default": true, "scope": "language-overridable", "markdownDescription": "%emmetShowAbbreviationSuggestions%" }, "emmet.includeLanguages": { "type": "object", "additionalProperties": { "type": "string" }, "default": {}, "markdownDescription": "%emmetIncludeLanguages%" }, "emmet.variables": { "type": "object", "properties": { "lang": { "type": "string", "default": "en" }, "charset": { "type": "string", "default": "UTF-8" } }, "additionalProperties": { "type": "string" }, "default": {}, "markdownDescription": "%emmetVariables%" }, "emmet.syntaxProfiles": { "type": "object", "default": {}, "markdownDescription": "%emmetSyntaxProfiles%" }, "emmet.excludeLanguages": { "type": "array", "items": { "type": "string" }, "default": ["markdown"], "markdownDescription": "%emmetExclude%" }, "emmet.extensionsPath": { "type": "array", "items": { "type": "string", "markdownDescription": "%emmetExtensionsPathItem%" }, "default": [], "scope": "machine-overridable", "markdownDescription": "%emmetExtensionsPath%" }, "emmet.triggerExpansionOnTab": { "type": "boolean", "default": false, "scope": "language-overridable", "markdownDescription": "%emmetTriggerExpansionOnTab%" }, "emmet.useInlineCompletions": { "type": "boolean", "default": false, "markdownDescription": "%emmetUseInlineCompletions%" }, "emmet.preferences": { "type": "object", "default": {}, "markdownDescription": "%emmetPreferences%", "properties": { "css.intUnit": { "type": "string", "default": "px", "markdownDescription": "%emmetPreferencesIntUnit%" }, "css.floatUnit": { "type": "string", "default": "em", "markdownDescription": "%emmetPreferencesFloatUnit%" }, "css.propertyEnd": { "type": "string", "default": ";", "markdownDescription": "%emmetPreferencesCssAfter%" }, "sass.propertyEnd": { "type": "string", "default": "", "markdownDescription": "%emmetPreferencesSassAfter%" }, "stylus.propertyEnd": { "type": "string", "default": "", "markdownDescription": "%emmetPreferencesStylusAfter%" }, "css.valueSeparator": { "type": "string", "default": ": ", "markdownDescription": "%emmetPreferencesCssBetween%" }, "sass.valueSeparator": { "type": "string", "default": ": ", "markdownDescription": "%emmetPreferencesSassBetween%" }, "stylus.valueSeparator": { "type": "string", "default": " ", "markdownDescription": "%emmetPreferencesStylusBetween%" }, "bem.elementSeparator": { "type": "string", "default": "__", "markdownDescription": "%emmetPreferencesBemElementSeparator%" }, "bem.modifierSeparator": { "type": "string", "default": "_", "markdownDescription": "%emmetPreferencesBemModifierSeparator%" }, "filter.commentBefore": { "type": "string", "default": "", "markdownDescription": "%emmetPreferencesFilterCommentBefore%" }, "filter.commentAfter": { "type": "string", "default": "\n<!-- /[#ID][.CLASS] -->", "markdownDescription": "%emmetPreferencesFilterCommentAfter%" }, "filter.commentTrigger": { "type": "array", "default": ["id", "class"], "markdownDescription": "%emmetPreferencesFilterCommentTrigger%" }, "format.noIndentTags": { "type": "array", "default": ["html"], "markdownDescription": "%emmetPreferencesFormatNoIndentTags%" }, "format.forceIndentationForTags": { "type": "array", "default": ["body"], "markdownDescription": "%emmetPreferencesFormatForceIndentTags%" }, "profile.allowCompactBoolean": { "type": "boolean", "default": false, "markdownDescription": "%emmetPreferencesAllowCompactBoolean%" }, "css.webkitProperties": { "type": "string", "default": null, "markdownDescription": "%emmetPreferencesCssWebkitProperties%" }, "css.mozProperties": { "type": "string", "default": null, "markdownDescription": "%emmetPreferencesCssMozProperties%" }, "css.oProperties": { "type": "string", "default": null, "markdownDescription": "%emmetPreferencesCssOProperties%" }, "css.msProperties": { "type": "string", "default": null, "markdownDescription": "%emmetPreferencesCssMsProperties%" }, "css.fuzzySearchMinScore": { "type": "number", "default": 0.3, "markdownDescription": "%emmetPreferencesCssFuzzySearchMinScore%" }, "output.inlineBreak": { "type": "number", "default": 0, "markdownDescription": "%emmetPreferencesOutputInlineBreak%" }, "output.reverseAttributes": { "type": "boolean", "default": false, "markdownDescription": "%emmetPreferencesOutputReverseAttributes%" }, "output.selfClosingStyle": { "type": "string", "enum": ["html", "xhtml", "xml"], "default": "html", "markdownDescription": "%emmetPreferencesOutputSelfClosingStyle%" }, "css.color.short": { "type": "boolean", "default": true, "markdownDescription": "%emmetPreferencesCssColorShort%" } } }, "emmet.showSuggestionsAsSnippets": { "type": "boolean", "default": false, "markdownDescription": "%emmetShowSuggestionsAsSnippets%" }, "emmet.optimizeStylesheetParsing": { "type": "boolean", "default": true, "markdownDescription": "%emmetOptimizeStylesheetParsing%" } } }, "commands": [{ "command": "editor.emmet.action.wrapWithAbbreviation", "title": "%command.wrapWithAbbreviation%", "category": "Emmet" }, { "command": "editor.emmet.action.removeTag", "title": "%command.removeTag%", "category": "Emmet" }, { "command": "editor.emmet.action.updateTag", "title": "%command.updateTag%", "category": "Emmet" }, { "command": "editor.emmet.action.matchTag", "title": "%command.matchTag%", "category": "Emmet" }, { "command": "editor.emmet.action.balanceIn", "title": "%command.balanceIn%", "category": "Emmet" }, { "command": "editor.emmet.action.balanceOut", "title": "%command.balanceOut%", "category": "Emmet" }, { "command": "editor.emmet.action.prevEditPoint", "title": "%command.prevEditPoint%", "category": "Emmet" }, { "command": "editor.emmet.action.nextEditPoint", "title": "%command.nextEditPoint%", "category": "Emmet" }, { "command": "editor.emmet.action.mergeLines", "title": "%command.mergeLines%", "category": "Emmet" }, { "command": "editor.emmet.action.selectPrevItem", "title": "%command.selectPrevItem%", "category": "Emmet" }, { "command": "editor.emmet.action.selectNextItem", "title": "%command.selectNextItem%", "category": "Emmet" }, { "command": "editor.emmet.action.splitJoinTag", "title": "%command.splitJoinTag%", "category": "Emmet" }, { "command": "editor.emmet.action.toggleComment", "title": "%command.toggleComment%", "category": "Emmet" }, { "command": "editor.emmet.action.evaluateMathExpression", "title": "%command.evaluateMathExpression%", "category": "Emmet" }, { "command": "editor.emmet.action.updateImageSize", "title": "%command.updateImageSize%", "category": "Emmet" }, { "command": "editor.emmet.action.incrementNumberByOneTenth", "title": "%command.incrementNumberByOneTenth%", "category": "Emmet" }, { "command": "editor.emmet.action.incrementNumberByOne", "title": "%command.incrementNumberByOne%", "category": "Emmet" }, { "command": "editor.emmet.action.incrementNumberByTen", "title": "%command.incrementNumberByTen%", "category": "Emmet" }, { "command": "editor.emmet.action.decrementNumberByOneTenth", "title": "%command.decrementNumberByOneTenth%", "category": "Emmet" }, { "command": "editor.emmet.action.decrementNumberByOne", "title": "%command.decrementNumberByOne%", "category": "Emmet" }, { "command": "editor.emmet.action.decrementNumberByTen", "title": "%command.decrementNumberByTen%", "category": "Emmet" }, { "command": "editor.emmet.action.reflectCSSValue", "title": "%command.reflectCSSValue%", "category": "Emmet" }, { "command": "workbench.action.showEmmetCommands", "title": "%command.showEmmetCommands%", "category": "" }], "menus": { "commandPalette": [{ "command": "editor.emmet.action.wrapWithAbbreviation", "when": "!activeEditorIsReadonly" }, { "command": "editor.emmet.action.removeTag", "when": "!activeEditorIsReadonly" }, { "command": "editor.emmet.action.updateTag", "when": "!activeEditorIsReadonly" }, { "command": "editor.emmet.action.matchTag", "when": "!activeEditorIsReadonly" }, { "command": "editor.emmet.action.balanceIn", "when": "!activeEditorIsReadonly" }, { "command": "editor.emmet.action.balanceOut", "when": "!activeEditorIsReadonly" }, { "command": "editor.emmet.action.prevEditPoint", "when": "!activeEditorIsReadonly" }, { "command": "editor.emmet.action.nextEditPoint", "when": "!activeEditorIsReadonly" }, { "command": "editor.emmet.action.mergeLines", "when": "!activeEditorIsReadonly" }, { "command": "editor.emmet.action.selectPrevItem", "when": "!activeEditorIsReadonly" }, { "command": "editor.emmet.action.selectNextItem", "when": "!activeEditorIsReadonly" }, { "command": "editor.emmet.action.splitJoinTag", "when": "!activeEditorIsReadonly" }, { "command": "editor.emmet.action.toggleComment", "when": "!activeEditorIsReadonly" }, { "command": "editor.emmet.action.evaluateMathExpression", "when": "!activeEditorIsReadonly" }, { "command": "editor.emmet.action.updateImageSize", "when": "!activeEditorIsReadonly" }, { "command": "editor.emmet.action.incrementNumberByOneTenth", "when": "!activeEditorIsReadonly" }, { "command": "editor.emmet.action.incrementNumberByOne", "when": "!activeEditorIsReadonly" }, { "command": "editor.emmet.action.incrementNumberByTen", "when": "!activeEditorIsReadonly" }, { "command": "editor.emmet.action.decrementNumberByOneTenth", "when": "!activeEditorIsReadonly" }, { "command": "editor.emmet.action.decrementNumberByOne", "when": "!activeEditorIsReadonly" }, { "command": "editor.emmet.action.decrementNumberByTen", "when": "!activeEditorIsReadonly" }, { "command": "editor.emmet.action.reflectCSSValue", "when": "!activeEditorIsReadonly" }] } }, "capabilities": { "virtualWorkspaces": true, "untrustedWorkspaces": { "supported": true } } }, "packageNLS": { "description": "Emmet support for VS Code", "command.wrapWithAbbreviation": "Wrap with Abbreviation", "command.removeTag": "Remove Tag", "command.updateTag": "Update Tag", "command.matchTag": "Go to Matching Pair", "command.balanceIn": "Balance (inward)", "command.balanceOut": "Balance (outward)", "command.prevEditPoint": "Go to Previous Edit Point", "command.nextEditPoint": "Go to Next Edit Point", "command.mergeLines": "Merge Lines", "command.selectPrevItem": "Select Previous Item", "command.selectNextItem": "Select Next Item", "command.splitJoinTag": "Split/Join Tag", "command.toggleComment": "Toggle Comment", "command.evaluateMathExpression": "Evaluate Math Expression", "command.updateImageSize": "Update Image Size", "command.reflectCSSValue": "Reflect CSS Value", "command.incrementNumberByOne": "Increment by 1", "command.decrementNumberByOne": "Decrement by 1", "command.incrementNumberByOneTenth": "Increment by 0.1", "command.decrementNumberByOneTenth": "Decrement by 0.1", "command.incrementNumberByTen": "Increment by 10", "command.decrementNumberByTen": "Decrement by 10", "command.showEmmetCommands": "Show Emmet Commands", "emmetSyntaxProfiles": "Define profile for specified syntax or use your own profile with specific rules.", "emmetExclude": "An array of languages where Emmet abbreviations should not be expanded.", "emmetExtensionsPath": "An array of paths, where each path can contain Emmet syntaxProfiles and/or snippet files.\nIn case of conflicts, the profiles/snippets of later paths will override those of earlier paths.\nSee https://code.visualstudio.com/docs/editor/emmet for more information and an example snippet file.", "emmetExtensionsPathItem": "A path containing Emmet syntaxProfiles and/or snippets.", "emmetShowExpandedAbbreviation": 'Shows expanded Emmet abbreviations as suggestions.\nThe option `"inMarkupAndStylesheetFilesOnly"` applies to html, haml, jade, slim, xml, xsl, css, scss, sass, less and stylus.\nThe option `"always"` applies to all parts of the file regardless of markup/css.', "emmetShowAbbreviationSuggestions": 'Shows possible Emmet abbreviations as suggestions. Not applicable in stylesheets or when emmet.showExpandedAbbreviation is set to `"never"`.', "emmetIncludeLanguages": 'Enable Emmet abbreviations in languages that are not supported by default. Add a mapping here between the language and Emmet supported language.\n For example: `{"vue-html": "html", "javascript": "javascriptreact"}`', "emmetVariables": "Variables to be used in Emmet snippets.", "emmetTriggerExpansionOnTab": "When enabled, Emmet abbreviations are expanded when pressing TAB, even when completions do not show up. When disabled, completions that show up can still be accepted by pressing TAB.", "emmetPreferences": "Preferences used to modify behavior of some actions and resolvers of Emmet.", "emmetPreferencesIntUnit": "Default unit for integer values.", "emmetPreferencesFloatUnit": "Default unit for float values.", "emmetPreferencesCssAfter": "Symbol to be placed at the end of CSS property when expanding CSS abbreviations.", "emmetPreferencesSassAfter": "Symbol to be placed at the end of CSS property when expanding CSS abbreviations in Sass files.", "emmetPreferencesStylusAfter": "Symbol to be placed at the end of CSS property when expanding CSS abbreviations in Stylus files.", "emmetPreferencesCssBetween": "Symbol to be placed at the between CSS property and value when expanding CSS abbreviations.", "emmetPreferencesSassBetween": "Symbol to be placed at the between CSS property and value when expanding CSS abbreviations in Sass files.", "emmetPreferencesStylusBetween": "Symbol to be placed at the between CSS property and value when expanding CSS abbreviations in Stylus files.", "emmetShowSuggestionsAsSnippets": "If `true`, then Emmet suggestions will show up as snippets allowing you to order them as per `#editor.snippetSuggestions#` setting.", "emmetPreferencesBemElementSeparator": "Element separator used for classes when using the BEM filter.", "emmetPreferencesBemModifierSeparator": "Modifier separator used for classes when using the BEM filter.", "emmetPreferencesFilterCommentBefore": "A definition of comment that should be placed before matched element when comment filter is applied.", "emmetPreferencesFilterCommentAfter": "A definition of comment that should be placed after matched element when comment filter is applied.", "emmetPreferencesFilterCommentTrigger": "A comma-separated list of attribute names that should exist in the abbreviation for the comment filter to be applied.", "emmetPreferencesFormatNoIndentTags": "An array of tag names that should never get inner indentation.", "emmetPreferencesFormatForceIndentTags": "An array of tag names that should always get inner indentation.", "emmetPreferencesAllowCompactBoolean": "If `true`, compact notation of boolean attributes are produced.", "emmetPreferencesCssWebkitProperties": "Comma separated CSS properties that get the 'webkit' vendor prefix when used in Emmet abbreviation that starts with `-`. Set to empty string to always avoid the 'webkit' prefix.", "emmetPreferencesCssMozProperties": "Comma separated CSS properties that get the 'moz' vendor prefix when used in Emmet abbreviation that starts with `-`. Set to empty string to always avoid the 'moz' prefix.", "emmetPreferencesCssOProperties": "Comma separated CSS properties that get the 'o' vendor prefix when used in Emmet abbreviation that starts with `-`. Set to empty string to always avoid the 'o' prefix.", "emmetPreferencesCssMsProperties": "Comma separated CSS properties that get the 'ms' vendor prefix when used in Emmet abbreviation that starts with `-`. Set to empty string to always avoid the 'ms' prefix.", "emmetPreferencesCssFuzzySearchMinScore": "The minimum score (from 0 to 1) that fuzzy-matched abbreviation should achieve. Lower values may produce many false-positive matches, higher values may reduce possible matches.", "emmetOptimizeStylesheetParsing": "When set to `false`, the whole file is parsed to determine if current position is valid for expanding Emmet abbreviations. When set to `true`, only the content around the current position in CSS/SCSS/Less files is parsed.", "emmetPreferencesOutputInlineBreak": "The number of sibling inline elements needed for line breaks to be placed between those elements. If `0`, inline elements are always expanded onto a single line.", "emmetPreferencesOutputReverseAttributes": "If `true`, reverses attribute merging directions when resolving snippets.", "emmetPreferencesOutputSelfClosingStyle": "Style of self-closing tags: html (`<br>`), xml (`<br/>`) or xhtml (`<br />`).", "emmetPreferencesCssColorShort": "If `true`, color values like `#f` will be expanded to `#fff` instead of `#ffffff`.", "emmetUseInlineCompletions": "If `true`, Emmet will use inline completions to suggest expansions. To prevent the non-inline completion item provider from showing up as often while this setting is `true`, turn `#editor.quickSuggestions#` to `inline` or `off` for the `other` item." }, "readmePath": "emmet/README.md" }, { "extensionPath": "extension-editing", "packageJSON": { "name": "extension-editing", "displayName": "%displayName%", "description": "%description%", "version": "1.0.0", "publisher": "vscode", "license": "MIT", "engines": { "vscode": "^1.4.0" }, "icon": "images/icon.png", "activationEvents": ["onLanguage:json", "onLanguage:markdown"], "main": "./dist/extensionEditingMain", "browser": "./dist/browser/extensionEditingBrowserMain", "capabilities": { "virtualWorkspaces": true, "untrustedWorkspaces": { "supported": true } }, "contributes": { "jsonValidation": [{ "fileMatch": "package.json", "url": "vscode://schemas/vscode-extensions" }, { "fileMatch": "*language-configuration.json", "url": "vscode://schemas/language-configuration" }, { "fileMatch": ["*icon-theme.json", "!*product-icon-theme.json"], "url": "vscode://schemas/icon-theme" }, { "fileMatch": "*product-icon-theme.json", "url": "vscode://schemas/product-icon-theme" }, { "fileMatch": "*color-theme.json", "url": "vscode://schemas/color-theme" }], "languages": [{ "id": "ignore", "filenames": [".vscodeignore"] }] }, "repository": { "type": "git", "url": "https://github.com/microsoft/vscode.git" } }, "packageNLS": { "displayName": "Extension Authoring", "description": "Provides linting capabilities for authoring extensions." } }, { "extensionPath": "fsharp", "packageJSON": { "name": "fsharp", "displayName": "%displayName%", "description": "%description%", "version": "1.0.0", "publisher": "vscode", "license": "MIT", "engines": { "vscode": "*" }, "scripts": { "update-grammar": "node ../node_modules/vscode-grammar-updater/bin ionide/ionide-fsgrammar grammars/fsharp.json ./syntaxes/fsharp.tmLanguage.json" }, "categories": ["Programming Languages"], "contributes": { "languages": [{ "id": "fsharp", "extensions": [".fs", ".fsi", ".fsx", ".fsscript"], "aliases": ["F#", "FSharp", "fsharp"], "configuration": "./language-configuration.json" }], "grammars": [{ "language": "fsharp", "scopeName": "source.fsharp", "path": "./syntaxes/fsharp.tmLanguage.json" }], "snippets": [{ "language": "fsharp", "path": "./snippets/fsharp.code-snippets" }], "configurationDefaults": { "[fsharp]": { "diffEditor.ignoreTrimWhitespace": false } } }, "repository": { "type": "git", "url": "https://github.com/microsoft/vscode.git" } }, "packageNLS": { "displayName": "F# Language Basics", "description": "Provides snippets, syntax highlighting, bracket matching and folding in F# files." } }, { "extensionPath": "git-base", "packageJSON": { "name": "git-base", "displayName": "%displayName%", "description": "%description%", "version": "1.0.0", "publisher": "vscode", "license": "MIT", "engines": { "vscode": "0.10.x" }, "categories": ["Other"], "activationEvents": ["*"], "main": "./dist/extension.js", "browser": "./dist/browser/extension.js", "icon": "resources/icons/git.png", "capabilities": { "virtualWorkspaces": true, "untrustedWorkspaces": { "supported": true } }, "contributes": { "commands": [{ "command": "git-base.api.getRemoteSources", "title": "%command.api.getRemoteSources%", "category": "Git Base API" }], "menus": { "commandPalette": [{ "command": "git-base.api.getRemoteSources", "when": "false" }] }, "languages": [{ "id": "git-commit", "aliases": ["Git Commit Message", "git-commit"], "filenames": ["COMMIT_EDITMSG", "MERGE_MSG"], "configuration": "./languages/git-commit.language-configuration.json" }, { "id": "git-rebase", "aliases": ["Git Rebase Message", "git-rebase"], "filenames": ["git-rebase-todo"], "filenamePatterns": ["**/rebase-merge/done"], "configuration": "./languages/git-rebase.language-configuration.json" }, { "id": "ignore", "aliases": ["Ignore", "ignore"], "extensions": [".gitignore_global", ".gitignore", ".git-blame-ignore-revs"], "configuration": "./languages/ignore.language-configuration.json" }], "grammars": [{ "language": "git-commit", "scopeName": "text.git-commit", "path": "./syntaxes/git-commit.tmLanguage.json" }, { "language": "git-rebase", "scopeName": "text.git-rebase", "path": "./syntaxes/git-rebase.tmLanguage.json" }, { "language": "ignore", "scopeName": "source.ignore", "path": "./syntaxes/ignore.tmLanguage.json" }] }, "repository": { "type": "git", "url": "https://github.com/microsoft/vscode.git" } }, "packageNLS": { "displayName": "Git Base", "description": "Git static contributions and pickers.", "command.api.getRemoteSources": "Get Remote Sources" }, "readmePath": "git-base/README.md" }, { "extensionPath": "github-authentication", "packageJSON": { "name": "github-authentication", "displayName": "%displayName%", "description": "%description%", "publisher": "vscode", "license": "MIT", "version": "0.0.2", "engines": { "vscode": "^1.41.0" }, "icon": "images/icon.png", "categories": ["Other"], "api": "none", "extensionKind": ["ui", "workspace"], "activationEvents": [], "capabilities": { "virtualWorkspaces": true, "untrustedWorkspaces": { "supported": "limited", "restrictedConfigurations": ["github-enterprise.uri"] } }, "contributes": { "authentication": [{ "label": "GitHub", "id": "github" }, { "label": "GitHub Enterprise Server", "id": "github-enterprise" }], "configuration": [{ "title": "GitHub Enterprise Server Authentication Provider", "properties": { "github-enterprise.uri": { "type": "string", "description": "GitHub Enterprise Server URI" } } }] }, "aiKey": "0c6ae279ed8443289764825290e4f9e2-1a736e7c-1324-4338-be46-fc2a58ae4d14-7255", "main": "./dist/extension.js", "browser": "./dist/browser/extension.js", "repository": { "type": "git", "url": "https://github.com/microsoft/vscode.git" } }, "packageNLS": { "displayName": "GitHub Authentication", "description": "GitHub Authentication Provider" }, "readmePath": "github-authentication/README.md" }, { "extensionPath": "go", "packageJSON": { "name": "go", "displayName": "%displayName%", "description": "%description%", "version": "1.0.0", "publisher": "vscode", "license": "MIT", "engines": { "vscode": "*" }, "scripts": { "update-grammar": "node ../node_modules/vscode-grammar-updater/bin worlpaker/go-syntax syntaxes/go.tmLanguage.json ./syntaxes/go.tmLanguage.json" }, "categories": ["Programming Languages"], "contributes": { "languages": [{ "id": "go", "extensions": [".go"], "aliases": ["Go"], "configuration": "./language-configuration.json" }], "grammars": [{ "language": "go", "scopeName": "source.go", "path": "./syntaxes/go.tmLanguage.json" }], "configurationDefaults": { "[go]": { "editor.insertSpaces": false } } }, "repository": { "type": "git", "url": "https://github.com/microsoft/vscode.git" } }, "packageNLS": { "displayName": "Go Language Basics", "description": "Provides syntax highlighting and bracket matching in Go files." } }, { "extensionPath": "groovy", "packageJSON": { "name": "groovy", "displayName": "%displayName%", "description": "%description%", "version": "1.0.0", "publisher": "vscode", "license": "MIT", "engines": { "vscode": "*" }, "scripts": { "update-grammar": "node ../node_modules/vscode-grammar-updater/bin textmate/groovy.tmbundle Syntaxes/Groovy.tmLanguage ./syntaxes/groovy.tmLanguage.json" }, "categories": ["Programming Languages"], "contributes": { "languages": [{ "id": "groovy", "aliases": ["Groovy", "groovy"], "extensions": [".groovy", ".gvy", ".gradle", ".jenkinsfile", ".nf"], "filenames": ["Jenkinsfile"], "filenamePatterns": ["Jenkinsfile*"], "firstLine": "^#!.*\\bgroovy\\b", "configuration": "./language-configuration.json" }], "grammars": [{ "language": "groovy", "scopeName": "source.groovy", "path": "./syntaxes/groovy.tmLanguage.json" }], "snippets": [{ "language": "groovy", "path": "./snippets/groovy.code-snippets" }] }, "repository": { "type": "git", "url": "https://github.com/microsoft/vscode.git" } }, "packageNLS": { "displayName": "Groovy Language Basics", "description": "Provides snippets, syntax highlighting and bracket matching in Groovy files." } }, { "extensionPath": "handlebars", "packageJSON": { "name": "handlebars", "displayName": "%displayName%", "description": "%description%", "version": "1.0.0", "publisher": "vscode", "license": "MIT", "engines": { "vscode": "0.10.x" }, "scripts": { "update-grammar": "node ../node_modules/vscode-grammar-updater/bin daaain/Handlebars grammars/Handlebars.json ./syntaxes/Handlebars.tmLanguage.json" }, "categories": ["Programming Languages"], "extensionKind": ["ui", "workspace"], "contributes": { "languages": [{ "id": "handlebars", "extensions": [".handlebars", ".hbs", ".hjs"], "aliases": ["Handlebars", "handlebars"], "mimetypes": ["text/x-handlebars-template"], "configuration": "./language-configuration.json" }], "grammars": [{ "language": "handlebars", "scopeName": "text.html.handlebars", "path": "./syntaxes/Handlebars.tmLanguage.json" }], "htmlLanguageParticipants": [{ "languageId": "handlebars", "autoInsert": true }] }, "repository": { "type": "git", "url": "https://github.com/microsoft/vscode.git" } }, "packageNLS": { "displayName": "Handlebars Language Basics", "description": "Provides syntax highlighting and bracket matching in Handlebars files." } }, { "extensionPath": "hlsl", "packageJSON": { "name": "hlsl", "displayName": "%displayName%", "description": "%description%", "version": "1.0.0", "publisher": "vscode", "license": "MIT", "engines": { "vscode": "*" }, "scripts": { "update-grammar": "node ../node_modules/vscode-grammar-updater/bin tgjones/shaders-tmLanguage grammars/hlsl.json ./syntaxes/hlsl.tmLanguage.json" }, "categories": ["Programming Languages"], "contributes": { "languages": [{ "id": "hlsl", "extensions": [".hlsl", ".hlsli", ".fx", ".fxh", ".vsh", ".psh", ".cginc", ".compute"], "aliases": ["HLSL", "hlsl"], "configuration": "./language-configuration.json" }], "grammars": [{ "language": "hlsl", "path": "./syntaxes/hlsl.tmLanguage.json", "scopeName": "source.hlsl" }] }, "repository": { "type": "git", "url": "https://github.com/microsoft/vscode.git" } }, "packageNLS": { "displayName": "HLSL Language Basics", "description": "Provides syntax highlighting and bracket matching in HLSL files." } }, { "extensionPath": "html", "packageJSON": { "name": "html", "displayName": "%displayName%", "description": "%description%", "version": "1.0.0", "publisher": "vscode", "license": "MIT", "engines": { "vscode": "0.10.x" }, "scripts": { "update-grammar": "node ./build/update-grammar.mjs" }, "categories": ["Programming Languages"], "contributes": { "languages": [{ "id": "html", "extensions": [".html", ".htm", ".shtml", ".xhtml", ".xht", ".mdoc", ".jsp", ".asp", ".aspx", ".jshtm", ".volt", ".ejs", ".rhtml"], "aliases": ["HTML", "htm", "html", "xhtml"], "mimetypes": ["text/html", "text/x-jshtm", "text/template", "text/ng-template", "application/xhtml+xml"], "configuration": "./language-configuration.json" }], "grammars": [{ "scopeName": "text.html.basic", "path": "./syntaxes/html.tmLanguage.json", "embeddedLanguages": { "text.html": "html", "source.css": "css", "source.js": "javascript", "source.python": "python", "source.smarty": "smarty" }, "tokenTypes": { "meta.tag string.quoted": "other" } }, { "language": "html", "scopeName": "text.html.derivative", "path": "./syntaxes/html-derivative.tmLanguage.json", "embeddedLanguages": { "text.html": "html", "source.css": "css", "source.js": "javascript", "source.python": "python", "source.smarty": "smarty" }, "tokenTypes": { "meta.tag string.quoted": "other" } }], "snippets": [{ "language": "html", "path": "./snippets/html.code-snippets" }] }, "repository": { "type": "git", "url": "https://github.com/microsoft/vscode.git" } }, "packageNLS": { "displayName": "HTML Language Basics", "description": "Provides syntax highlighting, bracket matching & snippets in HTML files." } }, { "extensionPath": "html-language-features", "packageJSON": { "name": "html-language-features", "displayName": "%displayName%", "description": "%description%", "version": "1.0.0", "publisher": "vscode", "license": "MIT", "aiKey": "0c6ae279ed8443289764825290e4f9e2-1a736e7c-1324-4338-be46-fc2a58ae4d14-7255", "engines": { "vscode": "^1.77.0" }, "icon": "icons/html.png", "activationEvents": ["onLanguage:html", "onLanguage:handlebars"], "enabledApiProposals": ["extensionsAny"], "main": "./client/dist/node/htmlClientMain", "browser": "./client/dist/browser/htmlClientMain", "capabilities": { "virtualWorkspaces": true, "untrustedWorkspaces": { "supported": true } }, "categories": ["Programming Languages"], "contributes": { "configuration": { "id": "html", "order": 20, "type": "object", "title": "HTML", "properties": { "html.completion.attributeDefaultValue": { "type": "string", "scope": "resource", "enum": ["doublequotes", "singlequotes", "empty"], "enumDescriptions": ["%html.completion.attributeDefaultValue.doublequotes%", "%html.completion.attributeDefaultValue.singlequotes%", "%html.completion.attributeDefaultValue.empty%"], "default": "doublequotes", "markdownDescription": "%html.completion.attributeDefaultValue%" }, "html.customData": { "type": "array", "markdownDescription": "%html.customData.desc%", "default": [], "items": { "type": "string" }, "scope": "resource" }, "html.format.enable": { "type": "boolean", "scope": "window", "default": true, "description": "%html.format.enable.desc%" }, "html.format.wrapLineLength": { "type": "integer", "scope": "resource", "default": 120, "description": "%html.format.wrapLineLength.desc%" }, "html.format.unformatted": { "type": ["string", "null"], "scope": "resource", "default": "wbr", "markdownDescription": "%html.format.unformatted.desc%" }, "html.format.contentUnformatted": { "type": ["string", "null"], "scope": "resource", "default": "pre,code,textarea", "markdownDescription": "%html.format.contentUnformatted.desc%" }, "html.format.indentInnerHtml": { "type": "boolean", "scope": "resource", "default": false, "markdownDescription": "%html.format.indentInnerHtml.desc%" }, "html.format.preserveNewLines": { "type": "boolean", "scope": "resource", "default": true, "description": "%html.format.preserveNewLines.desc%" }, "html.format.maxPreserveNewLines": { "type": ["number", "null"], "scope": "resource", "default": null, "markdownDescription": "%html.format.maxPreserveNewLines.desc%" }, "html.format.indentHandlebars": { "type": "boolean", "scope": "resource", "default": false, "markdownDescription": "%html.format.indentHandlebars.desc%" }, "html.format.extraLiners": { "type": ["string", "null"], "scope": "resource", "default": "head, body, /html", "markdownDescription": "%html.format.extraLiners.desc%" }, "html.format.wrapAttributes": { "type": "string", "scope": "resource", "default": "auto", "enum": ["auto", "force", "force-aligned", "force-expand-multiline", "aligned-multiple", "preserve", "preserve-aligned"], "enumDescriptions": ["%html.format.wrapAttributes.auto%", "%html.format.wrapAttributes.force%", "%html.format.wrapAttributes.forcealign%", "%html.format.wrapAttributes.forcemultiline%", "%html.format.wrapAttributes.alignedmultiple%", "%html.format.wrapAttributes.preserve%", "%html.format.wrapAttributes.preservealigned%"], "description": "%html.format.wrapAttributes.desc%" }, "html.format.wrapAttributesIndentSize": { "type": ["number", "null"], "scope": "resource", "default": null, "markdownDescription": "%html.format.wrapAttributesIndentSize.desc%" }, "html.format.templating": { "type": "boolean", "scope": "resource", "default": false, "description": "%html.format.templating.desc%" }, "html.format.unformattedContentDelimiter": { "type": "string", "scope": "resource", "default": "", "markdownDescription": "%html.format.unformattedContentDelimiter.desc%" }, "html.suggest.html5": { "type": "boolean", "scope": "resource", "default": true, "description": "%html.suggest.html5.desc%" }, "html.validate.scripts": { "type": "boolean", "scope": "resource", "default": true, "description": "%html.validate.scripts%" }, "html.validate.styles": { "type": "boolean", "scope": "resource", "default": true, "description": "%html.validate.styles%" }, "html.autoCreateQuotes": { "type": "boolean", "scope": "resource", "default": true, "description": "%html.autoCreateQuotes%" }, "html.autoClosingTags": { "type": "boolean", "scope": "resource", "default": true, "description": "%html.autoClosingTags%" }, "html.hover.documentation": { "type": "boolean", "scope": "resource", "default": true, "description": "%html.hover.documentation%" }, "html.hover.references": { "type": "boolean", "scope": "resource", "default": true, "description": "%html.hover.references%" }, "html.mirrorCursorOnMatchingTag": { "type": "boolean", "scope": "resource", "default": false, "description": "%html.mirrorCursorOnMatchingTag%", "deprecationMessage": "%html.mirrorCursorOnMatchingTagDeprecationMessage%" }, "html.trace.server": { "type": "string", "scope": "window", "enum": ["off", "messages", "verbose"], "default": "off", "description": "%html.trace.server.desc%" } } }, "configurationDefaults": { "[html]": { "editor.suggest.insertMode": "replace" }, "[handlebars]": { "editor.suggest.insertMode": "replace" } }, "jsonValidation": [{ "fileMatch": "*.html-data.json", "url": "https://raw.githubusercontent.com/microsoft/vscode-html-languageservice/master/docs/customData.schema.json" }, { "fileMatch": "package.json", "url": "./schemas/package.schema.json" }] }, "repository": { "type": "git", "url": "https://github.com/microsoft/vscode.git" } }, "packageNLS": { "displayName": "HTML Language Features", "description": "Provides rich language support for HTML and Handlebar files", "html.customData.desc": "A list of relative file paths pointing to JSON files following the [custom data format](https://github.com/microsoft/vscode-html-languageservice/blob/master/docs/customData.md).\n\nVS Code loads custom data on startup to enhance its HTML support for the custom HTML tags, attributes and attribute values you specify in the JSON files.\n\nThe file paths are relative to workspace and only workspace folder settings are considered.", "html.format.enable.desc": "Enable/disable default HTML formatter.", "html.format.wrapLineLength.desc": "Maximum amount of characters per line (0 = disable).", "html.format.unformatted.desc": "List of tags, comma separated, that shouldn't be reformatted. `null` defaults to all tags listed at https://www.w3.org/TR/html5/dom.html#phrasing-content.", "html.format.contentUnformatted.desc": "List of tags, comma separated, where the content shouldn't be reformatted. `null` defaults to the `pre` tag.", "html.format.indentInnerHtml.desc": "Indent `<head>` and `<body>` sections.", "html.format.preserveNewLines.desc": "Controls whether existing line breaks before elements should be preserved. Only works before elements, not inside tags or for text.", "html.format.maxPreserveNewLines.desc": "Maximum number of line breaks to be preserved in one chunk. Use `null` for unlimited.", "html.format.indentHandlebars.desc": "Format and indent `{{#foo}}` and `{{/foo}}`.", "html.format.extraLiners.desc": 'List of tags, comma separated, that should have an extra newline before them. `null` defaults to `"head, body, /html"`.', "html.format.wrapAttributes.desc": "Wrap attributes.", "html.format.wrapAttributes.auto": "Wrap attributes only when line length is exceeded.", "html.format.wrapAttributes.force": "Wrap each attribute except first.", "html.format.wrapAttributes.forcealign": "Wrap each attribute except first and keep aligned.", "html.format.wrapAttributes.forcemultiline": "Wrap each attribute.", "html.format.wrapAttributes.alignedmultiple": "Wrap when line length is exceeded, align attributes vertically.", "html.format.wrapAttributes.preserve": "Preserve wrapping of attributes.", "html.format.wrapAttributes.preservealigned": "Preserve wrapping of attributes but align.", "html.format.templating.desc": "Honor django, erb, handlebars and php templating language tags.", "html.format.unformattedContentDelimiter.desc": "Keep text content together between this string.", "html.format.wrapAttributesIndentSize.desc": "Indent wrapped attributes to after N characters. Use `null` to use the default indent size. Ignored if `#html.format.wrapAttributes#` is set to `aligned`.", "html.suggest.html5.desc": "Controls whether the built-in HTML language support suggests HTML5 tags, properties and values.", "html.trace.server.desc": "Traces the communication between VS Code and the HTML language server.", "html.validate.scripts": "Controls whether the built-in HTML language support validates embedded scripts.", "html.validate.styles": "Controls whether the built-in HTML language support validates embedded styles.", "html.autoCreateQuotes": "Enable/disable auto creation of quotes for HTML attribute assignment. The type of quotes can be configured by `#html.completion.attributeDefaultValue#`.", "html.autoClosingTags": "Enable/disable autoclosing of HTML tags.", "html.completion.attributeDefaultValue": "Controls the default value for attributes when completion is accepted.", "html.completion.attributeDefaultValue.doublequotes": 'Attribute value is set to "".', "html.completion.attributeDefaultValue.singlequotes": "Attribute value is set to ''.", "html.completion.attributeDefaultValue.empty": "Attribute value is not set.", "html.mirrorCursorOnMatchingTag": "Enable/disable mirroring cursor on matching HTML tag.", "html.mirrorCursorOnMatchingTagDeprecationMessage": "Deprecated in favor of `editor.linkedEditing`", "html.hover.documentation": "Show tag and attribute documentation in hover.", "html.hover.references": "Show references to MDN in hover." }, "readmePath": "html-language-features/README.md" }, { "extensionPath": "ini", "packageJSON": { "name": "ini", "displayName": "%displayName%", "description": "%description%", "version": "1.0.0", "private": true, "publisher": "vscode", "license": "MIT", "engines": { "vscode": "*" }, "scripts": { "update-grammar": "node ../node_modules/vscode-grammar-updater/bin textmate/ini.tmbundle Syntaxes/Ini.plist ./syntaxes/ini.tmLanguage.json" }, "categories": ["Programming Languages"], "contributes": { "languages": [{ "id": "ini", "extensions": [".ini"], "aliases": ["Ini", "ini"], "configuration": "./ini.language-configuration.json" }, { "id": "properties", "extensions": [".conf", ".properties", ".cfg", ".directory", ".gitattributes", ".gitconfig", ".gitmodules", ".editorconfig", ".repo"], "filenames": ["gitconfig", ".env"], "filenamePatterns": ["**/.config/git/config", "**/.git/config"], "aliases": ["Properties", "properties"], "configuration": "./properties.language-configuration.json" }], "grammars": [{ "language": "ini", "scopeName": "source.ini", "path": "./syntaxes/ini.tmLanguage.json" }, { "language": "properties", "scopeName": "source.ini", "path": "./syntaxes/ini.tmLanguage.json" }] }, "repository": { "type": "git", "url": "https://github.com/microsoft/vscode.git" } }, "packageNLS": { "displayName": "Ini Language Basics", "description": "Provides syntax highlighting and bracket matching in Ini files." } }, { "extensionPath": "ipynb", "packageJSON": { "name": "ipynb", "displayName": "%displayName%", "description": "%description%", "publisher": "vscode", "version": "1.0.0", "license": "MIT", "icon": "media/icon.png", "engines": { "vscode": "^1.57.0" }, "enabledApiProposals": ["documentPaste", "diffContentOptions"], "activationEvents": ["onNotebook:jupyter-notebook", "onNotebookSerializer:interactive", "onNotebookSerializer:repl"], "extensionKind": ["workspace", "ui"], "main": "./dist/ipynbMain.node.js", "browser": "./dist/browser/ipynbMain.browser.js", "capabilities": { "virtualWorkspaces": true, "untrustedWorkspaces": { "supported": true } }, "contributes": { "configuration": [{ "properties": { "ipynb.pasteImagesAsAttachments.enabled": { "type": "boolean", "scope": "resource", "markdownDescription": "%ipynb.pasteImagesAsAttachments.enabled%", "default": true }, "ipynb.experimental.serialization": { "type": "boolean", "scope": "resource", "markdownDescription": "%ipynb.experimental.serialization%", "default": false, "tags": ["experimental"] } } }], "commands": [{ "command": "ipynb.newUntitledIpynb", "title": "%newUntitledIpynb.title%", "shortTitle": "%newUntitledIpynb.shortTitle%", "category": "Create" }, { "command": "ipynb.openIpynbInNotebookEditor", "title": "%openIpynbInNotebookEditor.title%" }, { "command": "ipynb.cleanInvalidImageAttachment", "title": "%cleanInvalidImageAttachment.title%" }, { "command": "notebook.cellOutput.copy", "title": "%copyCellOutput.title%", "category": "Notebook" }, { "command": "notebook.cellOutput.openInTextEditor", "title": "%openCellOutput.title%", "category": "Notebook" }], "notebooks": [{ "type": "jupyter-notebook", "displayName": "Jupyter Notebook", "selector": [{ "filenamePattern": "*.ipynb" }], "priority": "default" }], "notebookRenderer": [{ "id": "vscode.markdown-it-cell-attachment-renderer", "displayName": "%markdownAttachmentRenderer.displayName%", "entrypoint": { "extends": "vscode.markdown-it-renderer", "path": "./notebook-out/cellAttachmentRenderer.js" } }], "menus": { "file/newFile": [{ "command": "ipynb.newUntitledIpynb", "group": "notebook" }], "commandPalette": [{ "command": "ipynb.newUntitledIpynb" }, { "command": "ipynb.openIpynbInNotebookEditor", "when": "false" }, { "command": "ipynb.cleanInvalidImageAttachment", "when": "false" }, { "command": "notebook.cellOutput.copy", "when": "notebookCellHasOutputs" }, { "command": "notebook.cellOutput.openInTextEditor", "when": "false" }], "webview/context": [{ "command": "notebook.cellOutput.copy", "when": "webviewId == 'notebook.output' && webviewSection == 'image'" }, { "command": "notebook.cellOutput.copy", "when": "webviewId == 'notebook.output' && webviewSection == 'text'" }, { "command": "notebook.cellOutput.openInTextEditor", "when": "webviewId == 'notebook.output' && webviewSection == 'text'" }] } }, "repository": { "type": "git", "url": "https://github.com/microsoft/vscode.git" } }, "packageNLS": { "displayName": ".ipynb Support", "description": "Provides basic support for opening and reading Jupyter's .ipynb notebook files", "ipynb.pasteImagesAsAttachments.enabled": "Enable/disable pasting of images into Markdown cells in ipynb notebook files. Pasted images are inserted as attachments to the cell.", "ipynb.experimental.serialization": "Experimental feature to serialize the Jupyter notebook in a worker thread.", "newUntitledIpynb.title": "New Jupyter Notebook", "newUntitledIpynb.shortTitle": "Jupyter Notebook", "openIpynbInNotebookEditor.title": "Open IPYNB File In Notebook Editor", "cleanInvalidImageAttachment.title": "Clean Invalid Image Attachment Reference", "copyCellOutput.title": "Copy Cell Output", "openCellOutput.title": "Open Cell Output in Text Editor", "markdownAttachmentRenderer.displayName": { "message": "Markdown-It ipynb Cell Attachment renderer", "comment": ["Markdown-It is a product name and should not be translated"] } }, "readmePath": "ipynb/README.md" }, { "extensionPath": "java", "packageJSON": { "name": "java", "displayName": "%displayName%", "description": "%description%", "version": "1.0.0", "publisher": "vscode", "license": "MIT", "engines": { "vscode": "*" }, "scripts": { "update-grammar": "node ../node_modules/vscode-grammar-updater/bin redhat-developer/vscode-java language-support/java/java.tmLanguage.json ./syntaxes/java.tmLanguage.json" }, "categories": ["Programming Languages"], "contributes": { "languages": [{ "id": "java", "extensions": [".java", ".jav"], "aliases": ["Java", "java"], "configuration": "./language-configuration.json" }], "grammars": [{ "language": "java", "scopeName": "source.java", "path": "./syntaxes/java.tmLanguage.json" }], "snippets": [{ "language": "java", "path": "./snippets/java.code-snippets" }] }, "repository": { "type": "git", "url": "https://github.com/microsoft/vscode.git" } }, "packageNLS": { "displayName": "Java Language Basics", "description": "Provides snippets, syntax highlighting, bracket matching and folding in Java files." } }, { "extensionPath": "javascript", "packageJSON": { "name": "javascript", "displayName": "%displayName%", "description": "%description%", "version": "1.0.0", "publisher": "vscode", "license": "MIT", "engines": { "vscode": "0.10.x" }, "categories": ["Programming Languages"], "contributes": { "configurationDefaults": { "[javascript]": { "editor.maxTokenizationLineLength": 2500 } }, "languages": [{ "id": "javascriptreact", "aliases": ["JavaScript JSX", "JavaScript React", "jsx"], "extensions": [".jsx"], "configuration": "./javascript-language-configuration.json" }, { "id": "javascript", "aliases": ["JavaScript", "javascript", "js"], "extensions": [".js", ".es6", ".mjs", ".cjs", ".pac"], "filenames": ["jakefile"], "firstLine": "^#!.*\\bnode", "mimetypes": ["text/javascript"], "configuration": "./javascript-language-configuration.json" }, { "id": "jsx-tags", "aliases": [], "configuration": "./tags-language-configuration.json" }], "grammars": [{ "language": "javascriptreact", "scopeName": "source.js.jsx", "path": "./syntaxes/JavaScriptReact.tmLanguage.json", "embeddedLanguages": { "meta.tag.js": "jsx-tags", "meta.tag.without-attributes.js": "jsx-tags", "meta.tag.attributes.js.jsx": "javascriptreact", "meta.embedded.expression.js": "javascriptreact" }, "tokenTypes": { "meta.template.expression": "other", "meta.template.expression string": "string", "meta.template.expression comment": "comment", "entity.name.type.instance.jsdoc": "other", "entity.name.function.tagged-template": "other", "meta.import string.quoted": "other", "variable.other.jsdoc": "other" } }, { "language": "javascript", "scopeName": "source.js", "path": "./syntaxes/JavaScript.tmLanguage.json", "embeddedLanguages": { "meta.tag.js": "jsx-tags", "meta.tag.without-attributes.js": "jsx-tags", "meta.tag.attributes.js": "javascript", "meta.embedded.expression.js": "javascript" }, "tokenTypes": { "meta.template.expression": "other", "meta.template.expression string": "string", "meta.template.expression comment": "comment", "entity.name.type.instance.jsdoc": "other", "entity.name.function.tagged-template": "other", "meta.import string.quoted": "other", "variable.other.jsdoc": "other" } }, { "scopeName": "source.js.regexp", "path": "./syntaxes/Regular Expressions (JavaScript).tmLanguage" }], "semanticTokenScopes": [{ "language": "javascript", "scopes": { "property": ["variable.other.property.js"], "property.readonly": ["variable.other.constant.property.js"], "variable": ["variable.other.readwrite.js"], "variable.readonly": ["variable.other.constant.object.js"], "function": ["entity.name.function.js"], "namespace": ["entity.name.type.module.js"], "variable.defaultLibrary": ["support.variable.js"], "function.defaultLibrary": ["support.function.js"] } }, { "language": "javascriptreact", "scopes": { "property": ["variable.other.property.jsx"], "property.readonly": ["variable.other.constant.property.jsx"], "variable": ["variable.other.readwrite.jsx"], "variable.readonly": ["variable.other.constant.object.jsx"], "function": ["entity.name.function.jsx"], "namespace": ["entity.name.type.module.jsx"], "variable.defaultLibrary": ["support.variable.js"], "function.defaultLibrary": ["support.function.js"] } }], "snippets": [{ "language": "javascript", "path": "./snippets/javascript.code-snippets" }, { "language": "javascriptreact", "path": "./snippets/javascript.code-snippets" }] }, "repository": { "type": "git", "url": "https://github.com/microsoft/vscode.git" } }, "packageNLS": { "displayName": "JavaScript Language Basics", "description": "Provides snippets, syntax highlighting, bracket matching and folding in JavaScript files." } }, { "extensionPath": "json", "packageJSON": { "name": "json", "displayName": "%displayName%", "description": "%description%", "version": "1.0.0", "publisher": "vscode", "license": "MIT", "engines": { "vscode": "0.10.x" }, "scripts": { "update-grammar": "node ./build/update-grammars.js" }, "categories": ["Programming Languages"], "contributes": { "languages": [{ "id": "json", "aliases": ["JSON", "json"], "extensions": [".json", ".bowerrc", ".jscsrc", ".webmanifest", ".js.map", ".css.map", ".ts.map", ".har", ".jslintrc", ".jsonld", ".geojson", ".ipynb", ".vuerc"], "filenames": ["composer.lock", ".watchmanconfig"], "mimetypes": ["application/json", "application/manifest+json"], "configuration": "./language-configuration.json" }, { "id": "jsonc", "aliases": ["JSON with Comments"], "extensions": [".jsonc", ".eslintrc", ".eslintrc.json", ".jsfmtrc", ".jshintrc", ".swcrc", ".hintrc", ".babelrc"], "filenames": ["babel.config.json", ".babelrc.json", ".ember-cli", "typedoc.json"], "configuration": "./language-configuration.json" }, { "id": "jsonl", "aliases": ["JSON Lines"], "extensions": [".jsonl"], "filenames": [], "configuration": "./language-configuration.json" }, { "id": "snippets", "aliases": ["Code Snippets"], "extensions": [".code-snippets"], "filenamePatterns": ["**/User/snippets/*.json", "**/User/profiles/*/snippets/*.json"], "configuration": "./language-configuration.json" }], "grammars": [{ "language": "json", "scopeName": "source.json", "path": "./syntaxes/JSON.tmLanguage.json" }, { "language": "jsonc", "scopeName": "source.json.comments", "path": "./syntaxes/JSONC.tmLanguage.json" }, { "language": "jsonl", "scopeName": "source.json.lines", "path": "./syntaxes/JSONL.tmLanguage.json" }, { "language": "snippets", "scopeName": "source.json.comments.snippets", "path": "./syntaxes/snippets.tmLanguage.json" }] }, "repository": { "type": "git", "url": "https://github.com/microsoft/vscode.git" } }, "packageNLS": { "displayName": "JSON Language Basics", "description": "Provides syntax highlighting & bracket matching in JSON files." } }, { "extensionPath": "json-language-features", "packageJSON": { "name": "json-language-features", "displayName": "%displayName%", "description": "%description%", "version": "1.0.0", "publisher": "vscode", "license": "MIT", "aiKey": "0c6ae279ed8443289764825290e4f9e2-1a736e7c-1324-4338-be46-fc2a58ae4d14-7255", "engines": { "vscode": "^1.77.0" }, "enabledApiProposals": ["extensionsAny"], "icon": "icons/json.png", "activationEvents": ["onLanguage:json", "onLanguage:jsonc", "onLanguage:snippets"], "main": "./client/dist/node/jsonClientMain", "browser": "./client/dist/browser/jsonClientMain", "capabilities": { "virtualWorkspaces": true, "untrustedWorkspaces": { "supported": true } }, "categories": ["Programming Languages"], "contributes": { "configuration": { "id": "json", "order": 20, "type": "object", "title": "JSON", "properties": { "json.schemas": { "type": "array", "scope": "resource", "description": "%json.schemas.desc%", "items": { "type": "object", "default": { "fileMatch": ["/myfile"], "url": "schemaURL" }, "properties": { "url": { "type": "string", "default": "/user.schema.json", "description": "%json.schemas.url.desc%" }, "fileMatch": { "type": "array", "items": { "type": "string", "default": "MyFile.json", "description": "%json.schemas.fileMatch.item.desc%" }, "minItems": 1, "description": "%json.schemas.fileMatch.desc%" }, "schema": { "$ref": "http://json-schema.org/draft-07/schema#", "description": "%json.schemas.schema.desc%" } } } }, "json.validate.enable": { "type": "boolean", "scope": "window", "default": true, "description": "%json.validate.enable.desc%" }, "json.format.enable": { "type": "boolean", "scope": "window", "default": true, "description": "%json.format.enable.desc%" }, "json.format.keepLines": { "type": "boolean", "scope": "window", "default": false, "description": "%json.format.keepLines.desc%" }, "json.trace.server": { "type": "string", "scope": "window", "enum": ["off", "messages", "verbose"], "default": "off", "description": "%json.tracing.desc%" }, "json.colorDecorators.enable": { "type": "boolean", "scope": "window", "default": true, "description": "%json.colorDecorators.enable.desc%", "deprecationMessage": "%json.colorDecorators.enable.deprecationMessage%" }, "json.maxItemsComputed": { "type": "number", "default": 5e3, "description": "%json.maxItemsComputed.desc%" }, "json.schemaDownload.enable": { "type": "boolean", "default": true, "description": "%json.enableSchemaDownload.desc%", "tags": ["usesOnlineServices"] } } }, "configurationDefaults": { "[json]": { "editor.quickSuggestions": { "strings": true }, "editor.suggest.insertMode": "replace" }, "[jsonc]": { "editor.quickSuggestions": { "strings": true }, "editor.suggest.insertMode": "replace" } }, "jsonValidation": [{ "fileMatch": "*.schema.json", "url": "http://json-schema.org/draft-07/schema#" }], "commands": [{ "command": "json.clearCache", "title": "%json.command.clearCache%", "category": "JSON" }, { "command": "json.sort", "title": "%json.command.sort%", "category": "JSON" }] }, "repository": { "type": "git", "url": "https://github.com/microsoft/vscode.git" } }, "packageNLS": { "displayName": "JSON Language Features", "description": "Provides rich language support for JSON files.", "json.schemas.desc": "Associate schemas to JSON files in the current project.", "json.schemas.url.desc": "A URL or absolute file path to a schema. Can be a relative path (starting with './') in workspace and workspace folder settings.", "json.schemas.fileMatch.desc": "An array of file patterns to match against when resolving JSON files to schemas. `*` and '**' can be used as a wildcard. Exclusion patterns can also be defined and start with '!'. A file matches when there is at least one matching pattern and the last matching pattern is not an exclusion pattern.", "json.schemas.fileMatch.item.desc": "A file pattern that can contain '*' and '**' to match against when resolving JSON files to schemas. When beginning with '!', it defines an exclusion pattern.", "json.schemas.schema.desc": "The schema definition for the given URL. The schema only needs to be provided to avoid accesses to the schema URL.", "json.format.enable.desc": "Enable/disable default JSON formatter", "json.format.keepLines.desc": "Keep all existing new lines when formatting.", "json.validate.enable.desc": "Enable/disable JSON validation.", "json.tracing.desc": "Traces the communication between VS Code and the JSON language server.", "json.colorDecorators.enable.desc": "Enables or disables color decorators", "json.colorDecorators.enable.deprecationMessage": "The setting `json.colorDecorators.enable` has been deprecated in favor of `editor.colorDecorators`.", "json.schemaResolutionErrorMessage": "Unable to resolve schema.", "json.clickToRetry": "Click to retry.", "json.maxItemsComputed.desc": "The maximum number of outline symbols and folding regions computed (limited for performance reasons).", "json.maxItemsExceededInformation.desc": "Show notification when exceeding the maximum number of outline symbols and folding regions.", "json.enableSchemaDownload.desc": "When enabled, JSON schemas can be fetched from http and https locations.", "json.command.clearCache": "Clear Schema Cache", "json.command.sort": "Sort Document" }, "readmePath": "json-language-features/README.md" }, { "extensionPath": "julia", "packageJSON": { "name": "julia", "displayName": "%displayName%", "description": "%description%", "version": "1.0.0", "publisher": "vscode", "license": "MIT", "engines": { "vscode": "0.10.x" }, "scripts": { "update-grammar": "node ../node_modules/vscode-grammar-updater/bin JuliaEditorSupport/atom-language-julia grammars/julia_vscode.json ./syntaxes/julia.tmLanguage.json" }, "categories": ["Programming Languages"], "contributes": { "languages": [{ "id": "julia", "aliases": ["Julia", "julia"], "extensions": [".jl"], "firstLine": "^#!\\s*/.*\\bjulia[0-9.-]*\\b", "configuration": "./language-configuration.json" }, { "id": "juliamarkdown", "aliases": ["Julia Markdown", "juliamarkdown"], "extensions": [".jmd"] }], "grammars": [{ "language": "julia", "scopeName": "source.julia", "path": "./syntaxes/julia.tmLanguage.json", "embeddedLanguages": { "meta.embedded.inline.cpp": "cpp", "meta.embedded.inline.javascript": "javascript", "meta.embedded.inline.python": "python", "meta.embedded.inline.r": "r", "meta.embedded.inline.sql": "sql" } }], "configurationDefaults": { "[julia]": { "editor.defaultColorDecorators": false } } } }, "packageNLS": { "displayName": "Julia Language Basics", "description": "Provides syntax highlighting & bracket matching in Julia files." } }, { "extensionPath": "latex", "packageJSON": { "name": "latex", "displayName": "%displayName%", "description": "%description%", "version": "1.0.0", "publisher": "vscode", "license": "MIT", "engines": { "vscode": "*" }, "scripts": { "update-grammar": "node ./build/update-grammars.js" }, "categories": ["Programming Languages"], "contributes": { "languages": [{ "id": "tex", "aliases": ["TeX", "tex"], "extensions": [".sty", ".cls", ".bbx", ".cbx"], "configuration": "latex-language-configuration.json" }, { "id": "latex", "aliases": ["LaTeX", "latex"], "extensions": [".tex", ".ltx", ".ctx"], "configuration": "latex-language-configuration.json" }, { "id": "bibtex", "aliases": ["BibTeX", "bibtex"], "extensions": [".bib"] }, { "id": "cpp_embedded_latex", "configuration": "latex-cpp-embedded-language-configuration.json", "aliases": [] }, { "id": "markdown_latex_combined", "configuration": "markdown-latex-combined-language-configuration.json", "aliases": [] }], "grammars": [{ "language": "tex", "scopeName": "text.tex", "path": "./syntaxes/TeX.tmLanguage.json" }, { "language": "latex", "scopeName": "text.tex.latex", "path": "./syntaxes/LaTeX.tmLanguage.json", "embeddedLanguages": { "source.cpp": "cpp_embedded_latex", "source.css": "css", "text.html": "html", "source.java": "java", "source.js": "javascript", "source.julia": "julia", "source.lua": "lua", "source.python": "python", "source.ruby": "ruby", "source.ts": "typescript", "text.xml": "xml", "source.yaml": "yaml", "meta.embedded.markdown_latex_combined": "markdown_latex_combined" } }, { "language": "bibtex", "scopeName": "text.bibtex", "path": "./syntaxes/Bibtex.tmLanguage.json" }, { "language": "markdown_latex_combined", "scopeName": "text.tex.markdown_latex_combined", "path": "./syntaxes/markdown-latex-combined.tmLanguage.json" }, { "language": "cpp_embedded_latex", "scopeName": "source.cpp.embedded.latex", "path": "./syntaxes/cpp-grammar-bailout.tmLanguage.json" }] }, "repository": { "type": "git", "url": "https://github.com/microsoft/vscode.git" } }, "packageNLS": { "displayName": "LaTeX Language Basics", "description": "Provides syntax highlighting and bracket matching for TeX, LaTeX and BibTeX." } }, { "extensionPath": "less", "packageJSON": { "name": "less", "displayName": "%displayName%", "description": "%description%", "version": "1.0.0", "publisher": "vscode", "license": "MIT", "engines": { "vscode": "*" }, "scripts": { "update-grammar": "node ./build/update-grammar.js" }, "categories": ["Programming Languages"], "contributes": { "languages": [{ "id": "less", "aliases": ["Less", "less"], "extensions": [".less"], "mimetypes": ["text/x-less", "text/less"], "configuration": "./language-configuration.json" }], "grammars": [{ "language": "less", "scopeName": "source.css.less", "path": "./syntaxes/less.tmLanguage.json" }], "problemMatchers": [{ "name": "lessc", "label": "Lessc compiler", "owner": "lessc", "source": "less", "fileLocation": "absolute", "pattern": { "regexp": "(.*)\\sin\\s(.*)\\son line\\s(\\d+),\\scolumn\\s(\\d+)", "message": 1, "file": 2, "line": 3, "column": 4 } }] }, "repository": { "type": "git", "url": "https://github.com/microsoft/vscode.git" } }, "packageNLS": { "displayName": "Less Language Basics", "description": "Provides syntax highlighting, bracket matching and folding in Less files." } }, { "extensionPath": "log", "packageJSON": { "name": "log", "displayName": "%displayName%", "description": "%description%", "version": "1.0.0", "publisher": "vscode", "license": "MIT", "engines": { "vscode": "*" }, "scripts": { "update-grammar": "node ../node_modules/vscode-grammar-updater/bin emilast/vscode-logfile-highlighter syntaxes/log.tmLanguage ./syntaxes/log.tmLanguage.json" }, "categories": ["Programming Languages"], "contributes": { "languages": [{ "id": "log", "extensions": [".log", "*.log.?"], "aliases": ["Log"] }], "grammars": [{ "language": "log", "scopeName": "text.log", "path": "./syntaxes/log.tmLanguage.json" }] }, "repository": { "type": "git", "url": "https://github.com/microsoft/vscode.git" } }, "packageNLS": { "displayName": "Log", "description": "Provides syntax highlighting for files with .log extension." } }, { "extensionPath": "lua", "packageJSON": { "name": "lua", "displayName": "%displayName%", "description": "%description%", "version": "1.0.0", "publisher": "vscode", "license": "MIT", "engines": { "vscode": "*" }, "scripts": { "update-grammar": "node ../node_modules/vscode-grammar-updater/bin sumneko/lua.tmbundle Syntaxes/Lua.plist ./syntaxes/lua.tmLanguage.json" }, "categories": ["Programming Languages"], "contributes": { "languages": [{ "id": "lua", "extensions": [".lua"], "aliases": ["Lua", "lua"], "configuration": "./language-configuration.json" }], "grammars": [{ "language": "lua", "scopeName": "source.lua", "path": "./syntaxes/lua.tmLanguage.json", "tokenTypes": { "comment.line.double-dash.doc.lua": "other" } }] }, "repository": { "type": "git", "url": "https://github.com/microsoft/vscode.git" } }, "packageNLS": { "displayName": "Lua Language Basics", "description": "Provides syntax highlighting and bracket matching in Lua files." } }, { "extensionPath": "make", "packageJSON": { "name": "make", "displayName": "%displayName%", "description": "%description%", "version": "1.0.0", "publisher": "vscode", "license": "MIT", "engines": { "vscode": "*" }, "scripts": { "update-grammar": "node ../node_modules/vscode-grammar-updater/bin fadeevab/make.tmbundle Syntaxes/Makefile.plist ./syntaxes/make.tmLanguage.json" }, "categories": ["Programming Languages"], "contributes": { "languages": [{ "id": "makefile", "aliases": ["Makefile", "makefile"], "extensions": [".mak", ".mk"], "filenames": ["Makefile", "makefile", "GNUmakefile", "OCamlMakefile"], "firstLine": "^#!\\s*/usr/bin/make", "configuration": "./language-configuration.json" }], "grammars": [{ "language": "makefile", "scopeName": "source.makefile", "path": "./syntaxes/make.tmLanguage.json", "tokenTypes": { "string.interpolated": "other" } }], "configurationDefaults": { "[makefile]": { "editor.insertSpaces": false } } }, "repository": { "type": "git", "url": "https://github.com/microsoft/vscode.git" } }, "packageNLS": { "displayName": "Make Language Basics", "description": "Provides syntax highlighting and bracket matching in Make files." } }, { "extensionPath": "markdown-basics", "packageJSON": { "name": "markdown", "displayName": "%displayName%", "description": "%description%", "version": "1.0.0", "publisher": "vscode", "license": "MIT", "engines": { "vscode": "^1.20.0" }, "categories": ["Programming Languages"], "contributes": { "languages": [{ "id": "markdown", "aliases": ["Markdown", "markdown"], "extensions": [".md", ".mkd", ".mdwn", ".mdown", ".markdown", ".markdn", ".mdtxt", ".mdtext", ".workbook"], "configuration": "./language-configuration.json" }], "grammars": [{ "language": "markdown", "scopeName": "text.html.markdown", "path": "./syntaxes/markdown.tmLanguage.json", "embeddedLanguages": { "meta.embedded.block.html": "html", "source.js": "javascript", "source.css": "css", "meta.embedded.block.frontmatter": "yaml", "meta.embedded.block.css": "css", "meta.embedded.block.ini": "ini", "meta.embedded.block.java": "java", "meta.embedded.block.lua": "lua", "meta.embedded.block.makefile": "makefile", "meta.embedded.block.perl": "perl", "meta.embedded.block.r": "r", "meta.embedded.block.ruby": "ruby", "meta.embedded.block.php": "php", "meta.embedded.block.sql": "sql", "meta.embedded.block.vs_net": "vs_net", "meta.embedded.block.xml": "xml", "meta.embedded.block.xsl": "xsl", "meta.embedded.block.yaml": "yaml", "meta.embedded.block.dosbatch": "dosbatch", "meta.embedded.block.clojure": "clojure", "meta.embedded.block.coffee": "coffee", "meta.embedded.block.c": "c", "meta.embedded.block.cpp": "cpp", "meta.embedded.block.diff": "diff", "meta.embedded.block.dockerfile": "dockerfile", "meta.embedded.block.go": "go", "meta.embedded.block.groovy": "groovy", "meta.embedded.block.pug": "jade", "meta.embedded.block.javascript": "javascript", "meta.embedded.block.json": "json", "meta.embedded.block.jsonc": "jsonc", "meta.embedded.block.latex": "latex", "meta.embedded.block.less": "less", "meta.embedded.block.objc": "objc", "meta.embedded.block.scss": "scss", "meta.embedded.block.perl6": "perl6", "meta.embedded.block.powershell": "powershell", "meta.embedded.block.python": "python", "meta.embedded.block.rust": "rust", "meta.embedded.block.scala": "scala", "meta.embedded.block.shellscript": "shellscript", "meta.embedded.block.typescript": "typescript", "meta.embedded.block.typescriptreact": "typescriptreact", "meta.embedded.block.csharp": "csharp", "meta.embedded.block.fsharp": "fsharp" }, "unbalancedBracketScopes": ["markup.underline.link.markdown", "punctuation.definition.list.begin.markdown"] }], "snippets": [{ "language": "markdown", "path": "./snippets/markdown.code-snippets" }], "configurationDefaults": { "[markdown]": { "editor.unicodeHighlight.ambiguousCharacters": false, "editor.unicodeHighlight.invisibleCharacters": false, "diffEditor.ignoreTrimWhitespace": false } } }, "scripts": { "update-grammar": "node ../node_modules/vscode-grammar-updater/bin microsoft/vscode-markdown-tm-grammar syntaxes/markdown.tmLanguage ./syntaxes/markdown.tmLanguage.json" }, "repository": { "type": "git", "url": "https://github.com/microsoft/vscode.git" } }, "packageNLS": { "displayName": "Markdown Language Basics", "description": "Provides snippets and syntax highlighting for Markdown." } }, { "extensionPath": "markdown-language-features", "packageJSON": { "name": "markdown-language-features", "displayName": "%displayName%", "description": "%description%", "version": "1.0.0", "icon": "icon.png", "publisher": "vscode", "license": "MIT", "aiKey": "0c6ae279ed8443289764825290e4f9e2-1a736e7c-1324-4338-be46-fc2a58ae4d14-7255", "engines": { "vscode": "^1.70.0" }, "main": "./dist/extension", "browser": "./dist/browser/extension", "categories": ["Programming Languages"], "enabledApiProposals": ["documentPaste"], "activationEvents": ["onLanguage:markdown", "onCommand:markdown.api.render", "onCommand:markdown.api.reloadPlugins", "onWebviewPanel:markdown.preview"], "capabilities": { "virtualWorkspaces": true, "untrustedWorkspaces": { "supported": "limited", "description": "%workspaceTrust%", "restrictedConfigurations": ["markdown.styles"] } }, "contributes": { "notebookRenderer": [{ "id": "vscode.markdown-it-renderer", "displayName": "Markdown it renderer", "entrypoint": "./notebook-out/index.js", "mimeTypes": ["text/markdown", "text/latex", "text/x-css", "text/x-html", "text/x-json", "text/x-typescript", "text/x-abap", "text/x-apex", "text/x-azcli", "text/x-bat", "text/x-cameligo", "text/x-clojure", "text/x-coffee", "text/x-cpp", "text/x-csharp", "text/x-csp", "text/x-css", "text/x-dart", "text/x-dockerfile", "text/x-ecl", "text/x-fsharp", "text/x-go", "text/x-graphql", "text/x-handlebars", "text/x-hcl", "text/x-html", "text/x-ini", "text/x-java", "text/x-javascript", "text/x-julia", "text/x-kotlin", "text/x-less", "text/x-lexon", "text/x-lua", "text/x-m3", "text/x-markdown", "text/x-mips", "text/x-msdax", "text/x-mysql", "text/x-objective-c/objective", "text/x-pascal", "text/x-pascaligo", "text/x-perl", "text/x-pgsql", "text/x-php", "text/x-postiats", "text/x-powerquery", "text/x-powershell", "text/x-pug", "text/x-python", "text/x-r", "text/x-razor", "text/x-redis", "text/x-redshift", "text/x-restructuredtext", "text/x-ruby", "text/x-rust", "text/x-sb", "text/x-scala", "text/x-scheme", "text/x-scss", "text/x-shell", "text/x-solidity", "text/x-sophia", "text/x-sql", "text/x-st", "text/x-swift", "text/x-systemverilog", "text/x-tcl", "text/x-twig", "text/x-typescript", "text/x-vb", "text/x-xml", "text/x-yaml", "application/json"] }], "commands": [{ "command": "_markdown.copyImage", "title": "%markdown.copyImage.title%", "category": "Markdown" }, { "command": "markdown.showPreview", "title": "%markdown.preview.title%", "category": "Markdown", "icon": { "light": "./media/preview-light.svg", "dark": "./media/preview-dark.svg" } }, { "command": "markdown.showPreviewToSide", "title": "%markdown.previewSide.title%", "category": "Markdown", "icon": "$(open-preview)" }, { "command": "markdown.showLockedPreviewToSide", "title": "%markdown.showLockedPreviewToSide.title%", "category": "Markdown", "icon": "$(open-preview)" }, { "command": "markdown.showSource", "title": "%markdown.showSource.title%", "category": "Markdown", "icon": "$(go-to-file)" }, { "command": "markdown.showPreviewSecuritySelector", "title": "%markdown.showPreviewSecuritySelector.title%", "category": "Markdown" }, { "command": "markdown.preview.refresh", "title": "%markdown.preview.refresh.title%", "category": "Markdown" }, { "command": "markdown.preview.toggleLock", "title": "%markdown.preview.toggleLock.title%", "category": "Markdown" }, { "command": "markdown.findAllFileReferences", "title": "%markdown.findAllFileReferences%", "category": "Markdown" }, { "command": "markdown.editor.insertLinkFromWorkspace", "title": "%markdown.editor.insertLinkFromWorkspace%", "category": "Markdown", "enablement": "editorLangId == markdown && !activeEditorIsReadonly" }, { "command": "markdown.editor.insertImageFromWorkspace", "title": "%markdown.editor.insertImageFromWorkspace%", "category": "Markdown", "enablement": "editorLangId == markdown && !activeEditorIsReadonly" }], "menus": { "webview/context": [{ "command": "_markdown.copyImage", "when": "webviewId == 'markdown.preview' && webviewSection == 'image'" }], "editor/title": [{ "command": "markdown.showPreviewToSide", "when": "editorLangId == markdown && !notebookEditorFocused && !hasCustomMarkdownPreview", "alt": "markdown.showPreview", "group": "navigation" }, { "command": "markdown.showSource", "when": "activeWebviewPanelId == 'markdown.preview' || activeCustomEditorId == 'vscode.markdown.preview.editor'", "group": "navigation" }, { "command": "markdown.preview.refresh", "when": "activeWebviewPanelId == 'markdown.preview' || activeCustomEditorId == 'vscode.markdown.preview.editor'", "group": "1_markdown" }, { "command": "markdown.preview.toggleLock", "when": "activeWebviewPanelId == 'markdown.preview' || activeCustomEditorId == 'vscode.markdown.preview.editor'", "group": "1_markdown" }, { "command": "markdown.showPreviewSecuritySelector", "when": "activeWebviewPanelId == 'markdown.preview' || activeCustomEditorId == 'vscode.markdown.preview.editor'", "group": "1_markdown" }], "explorer/context": [{ "command": "markdown.showPreview", "when": "resourceLangId == markdown && !hasCustomMarkdownPreview", "group": "navigation" }, { "command": "markdown.findAllFileReferences", "when": "resourceLangId == markdown", "group": "4_search" }], "editor/title/context": [{ "command": "markdown.showPreview", "when": "resourceLangId == markdown && !hasCustomMarkdownPreview", "group": "1_open" }, { "command": "markdown.findAllFileReferences", "when": "resourceLangId == markdown" }], "commandPalette": [{ "command": "_markdown.copyImage", "when": "false" }, { "command": "markdown.showPreview", "when": "editorLangId == markdown && !notebookEditorFocused", "group": "navigation" }, { "command": "markdown.showPreviewToSide", "when": "editorLangId == markdown && !notebookEditorFocused", "group": "navigation" }, { "command": "markdown.showLockedPreviewToSide", "when": "editorLangId == markdown && !notebookEditorFocused", "group": "navigation" }, { "command": "markdown.showSource", "when": "activeWebviewPanelId == 'markdown.preview' || activeCustomEditorId == 'vscode.markdown.preview.editor'", "group": "navigation" }, { "command": "markdown.showPreviewSecuritySelector", "when": "editorLangId == markdown && !notebookEditorFocused" }, { "command": "markdown.showPreviewSecuritySelector", "when": "activeWebviewPanelId == 'markdown.preview' || activeCustomEditorId == 'vscode.markdown.preview.editor'" }, { "command": "markdown.preview.toggleLock", "when": "activeWebviewPanelId == 'markdown.preview' || activeCustomEditorId == 'vscode.markdown.preview.editor'" }, { "command": "markdown.preview.refresh", "when": "editorLangId == markdown && !notebookEditorFocused" }, { "command": "markdown.preview.refresh", "when": "activeWebviewPanelId == 'markdown.preview' || activeCustomEditorId == 'vscode.markdown.preview.editor'" }, { "command": "markdown.findAllFileReferences", "when": "editorLangId == markdown" }] }, "keybindings": [{ "command": "markdown.showPreview", "key": "shift+ctrl+v", "mac": "shift+cmd+v", "when": "editorLangId == markdown && !notebookEditorFocused" }, { "command": "markdown.showPreviewToSide", "key": "ctrl+k v", "mac": "cmd+k v", "when": "editorLangId == markdown && !notebookEditorFocused" }], "configuration": { "type": "object", "title": "Markdown", "order": 20, "properties": { "markdown.styles": { "type": "array", "items": { "type": "string" }, "default": [], "description": "%markdown.styles.dec%", "scope": "resource" }, "markdown.preview.breaks": { "type": "boolean", "default": false, "markdownDescription": "%markdown.preview.breaks.desc%", "scope": "resource" }, "markdown.preview.linkify": { "type": "boolean", "default": true, "description": "%markdown.preview.linkify%", "scope": "resource" }, "markdown.preview.typographer": { "type": "boolean", "default": false, "description": "%markdown.preview.typographer%", "scope": "resource" }, "markdown.preview.fontFamily": { "type": "string", "default": "-apple-system, BlinkMacSystemFont, 'Segoe WPC', 'Segoe UI', system-ui, 'Ubuntu', 'Droid Sans', sans-serif", "description": "%markdown.preview.fontFamily.desc%", "scope": "resource" }, "markdown.preview.fontSize": { "type": "number", "default": 14, "description": "%markdown.preview.fontSize.desc%", "scope": "resource" }, "markdown.preview.lineHeight": { "type": "number", "default": 1.6, "description": "%markdown.preview.lineHeight.desc%", "scope": "resource" }, "markdown.preview.scrollPreviewWithEditor": { "type": "boolean", "default": true, "description": "%markdown.preview.scrollPreviewWithEditor.desc%", "scope": "resource" }, "markdown.preview.markEditorSelection": { "type": "boolean", "default": true, "description": "%markdown.preview.markEditorSelection.desc%", "scope": "resource" }, "markdown.preview.scrollEditorWithPreview": { "type": "boolean", "default": true, "description": "%markdown.preview.scrollEditorWithPreview.desc%", "scope": "resource" }, "markdown.preview.doubleClickToSwitchToEditor": { "type": "boolean", "default": true, "description": "%markdown.preview.doubleClickToSwitchToEditor.desc%", "scope": "resource" }, "markdown.preview.openMarkdownLinks": { "type": "string", "default": "inPreview", "description": "%configuration.markdown.preview.openMarkdownLinks.description%", "scope": "resource", "enum": ["inPreview", "inEditor"], "enumDescriptions": ["%configuration.markdown.preview.openMarkdownLinks.inPreview%", "%configuration.markdown.preview.openMarkdownLinks.inEditor%"] }, "markdown.links.openLocation": { "type": "string", "default": "currentGroup", "description": "%configuration.markdown.links.openLocation.description%", "scope": "resource", "enum": ["currentGroup", "beside"], "enumDescriptions": ["%configuration.markdown.links.openLocation.currentGroup%", "%configuration.markdown.links.openLocation.beside%"] }, "markdown.suggest.paths.enabled": { "type": "boolean", "default": true, "description": "%configuration.markdown.suggest.paths.enabled.description%", "scope": "resource" }, "markdown.suggest.paths.includeWorkspaceHeaderCompletions": { "type": "string", "default": "onDoubleHash", "scope": "resource", "markdownDescription": "%configuration.markdown.suggest.paths.includeWorkspaceHeaderCompletions%", "enum": ["never", "onDoubleHash", "onSingleOrDoubleHash"], "markdownEnumDescriptions": ["%configuration.markdown.suggest.paths.includeWorkspaceHeaderCompletions.never%", "%configuration.markdown.suggest.paths.includeWorkspaceHeaderCompletions.onDoubleHash%", "%configuration.markdown.suggest.paths.includeWorkspaceHeaderCompletions.onSingleOrDoubleHash%"] }, "markdown.trace.extension": { "type": "string", "enum": ["off", "verbose"], "default": "off", "description": "%markdown.trace.extension.desc%", "scope": "window" }, "markdown.trace.server": { "type": "string", "scope": "window", "enum": ["off", "messages", "verbose"], "default": "off", "description": "%markdown.trace.server.desc%" }, "markdown.server.log": { "type": "string", "scope": "window", "enum": ["off", "debug", "trace"], "default": "off", "description": "%markdown.server.log.desc%" }, "markdown.editor.drop.enabled": { "type": "string", "scope": "resource", "markdownDescription": "%configuration.markdown.editor.drop.enabled%", "default": "smart", "enum": ["always", "smart", "never"], "markdownEnumDescriptions": ["%configuration.markdown.editor.drop.enabled.always%", "%configuration.markdown.editor.drop.enabled.smart%", "%configuration.markdown.editor.drop.enabled.never%"] }, "markdown.editor.drop.copyIntoWorkspace": { "type": "string", "markdownDescription": "%configuration.markdown.editor.drop.copyIntoWorkspace%", "default": "mediaFiles", "enum": ["mediaFiles", "never"], "markdownEnumDescriptions": ["%configuration.copyIntoWorkspace.mediaFiles%", "%configuration.copyIntoWorkspace.never%"] }, "markdown.editor.filePaste.enabled": { "type": "string", "scope": "resource", "markdownDescription": "%configuration.markdown.editor.filePaste.enabled%", "default": "smart", "enum": ["always", "smart", "never"], "markdownEnumDescriptions": ["%configuration.markdown.editor.filePaste.enabled.always%", "%configuration.markdown.editor.filePaste.enabled.smart%", "%configuration.markdown.editor.filePaste.enabled.never%"] }, "markdown.editor.filePaste.copyIntoWorkspace": { "type": "string", "markdownDescription": "%configuration.markdown.editor.filePaste.copyIntoWorkspace%", "default": "mediaFiles", "enum": ["mediaFiles", "never"], "markdownEnumDescriptions": ["%configuration.copyIntoWorkspace.mediaFiles%", "%configuration.copyIntoWorkspace.never%"] }, "markdown.editor.filePaste.videoSnippet": { "type": "string", "markdownDescription": "%configuration.markdown.editor.filePaste.videoSnippet%", "default": '<video controls src="${src}" title="${title}"></video>' }, "markdown.editor.filePaste.audioSnippet": { "type": "string", "markdownDescription": "%configuration.markdown.editor.filePaste.audioSnippet%", "default": '<audio controls src="${src}" title="${title}"></audio>' }, "markdown.editor.pasteUrlAsFormattedLink.enabled": { "type": "string", "scope": "resource", "markdownDescription": "%configuration.markdown.editor.pasteUrlAsFormattedLink.enabled%", "default": "smartWithSelection", "enum": ["always", "smart", "smartWithSelection", "never"], "markdownEnumDescriptions": ["%configuration.pasteUrlAsFormattedLink.always%", "%configuration.pasteUrlAsFormattedLink.smart%", "%configuration.pasteUrlAsFormattedLink.smartWithSelection%", "%configuration.pasteUrlAsFormattedLink.never%"] }, "markdown.validate.enabled": { "type": "boolean", "scope": "resource", "description": "%configuration.markdown.validate.enabled.description%", "default": false }, "markdown.validate.referenceLinks.enabled": { "type": "string", "scope": "resource", "markdownDescription": "%configuration.markdown.validate.referenceLinks.enabled.description%", "default": "warning", "enum": ["ignore", "warning", "error"] }, "markdown.validate.fragmentLinks.enabled": { "type": "string", "scope": "resource", "markdownDescription": "%configuration.markdown.validate.fragmentLinks.enabled.description%", "default": "warning", "enum": ["ignore", "warning", "error"] }, "markdown.validate.fileLinks.enabled": { "type": "string", "scope": "resource", "markdownDescription": "%configuration.markdown.validate.fileLinks.enabled.description%", "default": "warning", "enum": ["ignore", "warning", "error"] }, "markdown.validate.fileLinks.markdownFragmentLinks": { "type": "string", "scope": "resource", "markdownDescription": "%configuration.markdown.validate.fileLinks.markdownFragmentLinks.description%", "default": "inherit", "enum": ["inherit", "ignore", "warning", "error"] }, "markdown.validate.ignoredLinks": { "type": "array", "scope": "resource", "markdownDescription": "%configuration.markdown.validate.ignoredLinks.description%", "items": { "type": "string" } }, "markdown.validate.unusedLinkDefinitions.enabled": { "type": "string", "scope": "resource", "markdownDescription": "%configuration.markdown.validate.unusedLinkDefinitions.description%", "default": "hint", "enum": ["ignore", "hint", "warning", "error"] }, "markdown.validate.duplicateLinkDefinitions.enabled": { "type": "string", "scope": "resource", "markdownDescription": "%configuration.markdown.validate.duplicateLinkDefinitions.description%", "default": "warning", "enum": ["ignore", "warning", "error"] }, "markdown.updateLinksOnFileMove.enabled": { "type": "string", "enum": ["prompt", "always", "never"], "markdownEnumDescriptions": ["%configuration.markdown.updateLinksOnFileMove.enabled.prompt%", "%configuration.markdown.updateLinksOnFileMove.enabled.always%", "%configuration.markdown.updateLinksOnFileMove.enabled.never%"], "default": "never", "markdownDescription": "%configuration.markdown.updateLinksOnFileMove.enabled%", "scope": "window" }, "markdown.updateLinksOnFileMove.include": { "type": "array", "markdownDescription": "%configuration.markdown.updateLinksOnFileMove.include%", "scope": "window", "items": { "type": "string", "description": "%configuration.markdown.updateLinksOnFileMove.include.property%" }, "default": ["**/*.{md,mkd,mdwn,mdown,markdown,markdn,mdtxt,mdtext,workbook}", "**/*.{jpg,jpe,jpeg,png,bmp,gif,ico,webp,avif,tiff,svg,mp4}"] }, "markdown.updateLinksOnFileMove.enableForDirectories": { "type": "boolean", "default": true, "description": "%configuration.markdown.updateLinksOnFileMove.enableForDirectories%", "scope": "window" }, "markdown.occurrencesHighlight.enabled": { "type": "boolean", "default": false, "description": "%configuration.markdown.occurrencesHighlight.enabled%", "scope": "resource" }, "markdown.copyFiles.destination": { "type": "object", "markdownDescription": "%configuration.markdown.copyFiles.destination%", "additionalProperties": { "type": "string" } }, "markdown.copyFiles.overwriteBehavior": { "type": "string", "markdownDescription": "%configuration.markdown.copyFiles.overwriteBehavior%", "default": "nameIncrementally", "enum": ["nameIncrementally", "overwrite"], "markdownEnumDescriptions": ["%configuration.markdown.copyFiles.overwriteBehavior.nameIncrementally%", "%configuration.markdown.copyFiles.overwriteBehavior.overwrite%"] }, "markdown.preferredMdPathExtensionStyle": { "type": "string", "default": "auto", "markdownDescription": "%configuration.markdown.preferredMdPathExtensionStyle%", "enum": ["auto", "includeExtension", "removeExtension"], "markdownEnumDescriptions": ["%configuration.markdown.preferredMdPathExtensionStyle.auto%", "%configuration.markdown.preferredMdPathExtensionStyle.includeExtension%", "%configuration.markdown.preferredMdPathExtensionStyle.removeExtension%"] }, "markdown.editor.updateLinksOnPaste.enabled": { "type": "boolean", "markdownDescription": "%configuration.markdown.editor.updateLinksOnPaste.enabled%", "scope": "resource", "default": true } } }, "configurationDefaults": { "[markdown]": { "editor.wordWrap": "on", "editor.quickSuggestions": { "comments": "off", "strings": "off", "other": "off" } } }, "jsonValidation": [{ "fileMatch": "package.json", "url": "./schemas/package.schema.json" }], "markdown.previewStyles": ["./media/markdown.css", "./media/highlight.css"], "markdown.previewScripts": ["./media/index.js"], "customEditors": [{ "viewType": "vscode.markdown.preview.editor", "displayName": "Markdown Preview", "priority": "option", "selector": [{ "filenamePattern": "*.md" }] }] }, "repository": { "type": "git", "url": "https://github.com/microsoft/vscode.git" } }, "packageNLS": { "displayName": "Markdown Language Features", "description": "Provides rich language support for Markdown.", "markdown.copyImage.title": "Copy Image", "markdown.preview.breaks.desc": "Sets how line-breaks are rendered in the Markdown preview. Setting it to `true` creates a `<br>` for newlines inside paragraphs.", "markdown.preview.linkify": "Convert URL-like text to links in the Markdown preview.", "markdown.preview.typographer": "Enable some language-neutral replacement and quotes beautification in the Markdown preview.", "markdown.preview.doubleClickToSwitchToEditor.desc": "Double-click in the Markdown preview to switch to the editor.", "markdown.preview.fontFamily.desc": "Controls the font family used in the Markdown preview.", "markdown.preview.fontSize.desc": "Controls the font size in pixels used in the Markdown preview.", "markdown.preview.lineHeight.desc": "Controls the line height used in the Markdown preview. This number is relative to the font size.", "markdown.preview.markEditorSelection.desc": "Mark the current editor selection in the Markdown preview.", "markdown.preview.scrollEditorWithPreview.desc": "When a Markdown preview is scrolled, update the view of the editor.", "markdown.preview.scrollPreviewWithEditor.desc": "When a Markdown editor is scrolled, update the view of the preview.", "markdown.preview.title": "Open Preview", "markdown.previewSide.title": "Open Preview to the Side", "markdown.showLockedPreviewToSide.title": "Open Locked Preview to the Side", "markdown.showSource.title": "Show Source", "markdown.styles.dec": "A list of URLs or local paths to CSS style sheets to use from the Markdown preview. Relative paths are interpreted relative to the folder open in the Explorer. If there is no open folder, they are interpreted relative to the location of the Markdown file. All '\\' need to be written as '\\\\'.", "markdown.showPreviewSecuritySelector.title": "Change Preview Security Settings", "markdown.trace.extension.desc": "Enable debug logging for the Markdown extension.", "markdown.trace.server.desc": "Traces the communication between VS Code and the Markdown language server.", "markdown.server.log.desc": "Controls the logging level of the Markdown language server.", "markdown.preview.refresh.title": "Refresh Preview", "markdown.preview.toggleLock.title": "Toggle Preview Locking", "markdown.findAllFileReferences": "Find File References", "markdown.editor.insertLinkFromWorkspace": "Insert Link to File in Workspace", "markdown.editor.insertImageFromWorkspace": "Insert Image from Workspace", "configuration.markdown.preview.openMarkdownLinks.description": "Controls how links to other Markdown files in the Markdown preview should be opened.", "configuration.markdown.preview.openMarkdownLinks.inEditor": "Try to open links in the editor.", "configuration.markdown.preview.openMarkdownLinks.inPreview": "Try to open links in the Markdown preview.", "configuration.markdown.links.openLocation.description": "Controls where links in Markdown files should be opened.", "configuration.markdown.links.openLocation.currentGroup": "Open links in the active editor group.", "configuration.markdown.links.openLocation.beside": "Open links beside the active editor.", "configuration.markdown.suggest.paths.enabled.description": "Enable path suggestions while writing links in Markdown files.", "configuration.markdown.suggest.paths.includeWorkspaceHeaderCompletions": "Enable suggestions for headers in other Markdown files in the current workspace. Accepting one of these suggestions inserts the full path to header in that file, for example: `[link text](/path/to/file.md#header)`.", "configuration.markdown.suggest.paths.includeWorkspaceHeaderCompletions.never": "Disable workspace header suggestions.", "configuration.markdown.suggest.paths.includeWorkspaceHeaderCompletions.onDoubleHash": "Enable workspace header suggestions after typing `##` in a path, for example: `[link text](##`.", "configuration.markdown.suggest.paths.includeWorkspaceHeaderCompletions.onSingleOrDoubleHash": "Enable workspace header suggestions after typing either `##` or `#` in a path, for example: `[link text](#` or `[link text](##`.", "configuration.markdown.editor.drop.enabled": "Enable dropping files into a Markdown editor while holding Shift. Requires enabling `#editor.dropIntoEditor.enabled#`.", "configuration.markdown.editor.drop.enabled.always": "Always insert Markdown links.", "configuration.markdown.editor.drop.enabled.smart": "Smartly create Markdown links by default when not dropping into a code block or other special element. Use the drop widget to switch between pasting as plain text or as Markdown links.", "configuration.markdown.editor.drop.enabled.never": "Never create Markdown links.", "configuration.markdown.editor.drop.copyIntoWorkspace": "Controls if files outside of the workspace that are dropped into a Markdown editor should be copied into the workspace.\n\nUse `#markdown.copyFiles.destination#` to configure where copied dropped files should be created", "configuration.markdown.editor.filePaste.enabled": "Enable pasting files into a Markdown editor to create Markdown links. Requires enabling `#editor.pasteAs.enabled#`.", "configuration.markdown.editor.filePaste.enabled.always": "Always insert Markdown links.", "configuration.markdown.editor.filePaste.enabled.smart": "Smartly create Markdown links by default when not pasting into a code block or other special element. Use the paste widget to switch between pasting as plain text or as Markdown links.", "configuration.markdown.editor.filePaste.enabled.never": "Never create Markdown links.", "configuration.markdown.editor.filePaste.copyIntoWorkspace": "Controls if files outside of the workspace that are pasted into a Markdown editor should be copied into the workspace.\n\nUse `#markdown.copyFiles.destination#` to configure where copied files should be created.", "configuration.copyIntoWorkspace.mediaFiles": "Try to copy external image and video files into the workspace.", "configuration.copyIntoWorkspace.never": "Do not copy external files into the workspace.", "configuration.markdown.editor.pasteUrlAsFormattedLink.enabled": "Controls if Markdown links are created when URLs are pasted into a Markdown editor. Requires enabling `#editor.pasteAs.enabled#`.", "configuration.pasteUrlAsFormattedLink.always": "Always insert Markdown links.", "configuration.pasteUrlAsFormattedLink.smart": "Smartly create Markdown links by default when not pasting into a code block or other special element. Use the paste widget to switch between pasting as plain text or as Markdown links.", "configuration.pasteUrlAsFormattedLink.smartWithSelection": "Smartly create Markdown links by default when you have selected text and are not pasting into a code block or other special element. Use the paste widget to switch between pasting as plain text or as Markdown links.", "configuration.pasteUrlAsFormattedLink.never": "Never create Markdown links.", "configuration.markdown.validate.enabled.description": "Enable all error reporting in Markdown files.", "configuration.markdown.validate.referenceLinks.enabled.description": "Validate reference links in Markdown files, for example: `[link][ref]`. Requires enabling `#markdown.validate.enabled#`.", "configuration.markdown.validate.fragmentLinks.enabled.description": "Validate fragment links to headers in the current Markdown file, for example: `[link](#header)`. Requires enabling `#markdown.validate.enabled#`.", "configuration.markdown.validate.fileLinks.enabled.description": "Validate links to other files in Markdown files, for example `[link](/path/to/file.md)`. This checks that the target files exists. Requires enabling `#markdown.validate.enabled#`.", "configuration.markdown.validate.fileLinks.markdownFragmentLinks.description": "Validate the fragment part of links to headers in other files in Markdown files, for example: `[link](/path/to/file.md#header)`. Inherits the setting value from `#markdown.validate.fragmentLinks.enabled#` by default.", "configuration.markdown.validate.ignoredLinks.description": "Configure links that should not be validated. For example adding `/about` would not validate the link `[about](/about)`, while the glob `/assets/**/*.svg` would let you skip validation for any link to `.svg` files under the `assets` directory.", "configuration.markdown.validate.unusedLinkDefinitions.description": "Validate link definitions that are unused in the current file.", "configuration.markdown.validate.duplicateLinkDefinitions.description": "Validate duplicated definitions in the current file.", "configuration.markdown.updateLinksOnFileMove.enabled": "Try to update links in Markdown files when a file is renamed/moved in the workspace. Use `#markdown.updateLinksOnFileMove.include#` to configure which files trigger link updates.", "configuration.markdown.updateLinksOnFileMove.enabled.prompt": "Prompt on each file move.", "configuration.markdown.updateLinksOnFileMove.enabled.always": "Always update links automatically.", "configuration.markdown.updateLinksOnFileMove.enabled.never": "Never try to update link and don't prompt.", "configuration.markdown.updateLinksOnFileMove.include": "Glob patterns that specifies files that trigger automatic link updates. See `#markdown.updateLinksOnFileMove.enabled#` for details about this feature.", "configuration.markdown.updateLinksOnFileMove.include.property": "The glob pattern to match file paths against. Set to true to enable the pattern.", "configuration.markdown.updateLinksOnFileMove.enableForDirectories": "Enable updating links when a directory is moved or renamed in the workspace.", "configuration.markdown.occurrencesHighlight.enabled": "Enable highlighting link occurrences in the current document.", "configuration.markdown.copyFiles.destination": { "message": "Configures the path and file name of files created by copy/paste or drag and drop. This is a map of globs that match against a Markdown document path to the destination path where the new file should be created.\n\nThe destination path may use the following variables:\n\n- `${documentDirName}` \u2014 Absolute parent directory path of the Markdown document, e.g. `/Users/me/myProject/docs`.\n- `${documentRelativeDirName}` \u2014 Relative parent directory path of the Markdown document, e.g. `docs`. This is the same as `${documentDirName}` if the file is not part of a workspace.\n- `${documentFileName}` \u2014 The full filename of the Markdown document, e.g. `README.md`.\n- `${documentBaseName}` \u2014 The basename of the Markdown document, e.g. `README`.\n- `${documentExtName}` \u2014 The extension of the Markdown document, e.g. `md`.\n- `${documentFilePath}` \u2014 Absolute path of the Markdown document, e.g. `/Users/me/myProject/docs/README.md`.\n- `${documentRelativeFilePath}` \u2014 Relative path of the Markdown document, e.g. `docs/README.md`. This is the same as `${documentFilePath}` if the file is not part of a workspace.\n- `${documentWorkspaceFolder}` \u2014 The workspace folder for the Markdown document, e.g. `/Users/me/myProject`. This is the same as `${documentDirName}` if the file is not part of a workspace.\n- `${fileName}` \u2014 The file name of the dropped file, e.g. `image.png`.\n- `${fileExtName}` \u2014 The extension of the dropped file, e.g. `png`.", "comment": ["This setting is use the user drops or pastes image data into the editor. In this case, VS Code automatically creates a new image file in the workspace containing the dropped/pasted image.", "It's easier to explain this setting with an example. For example, let's say the setting value was:", "", "{ 'docs/*.md': '${documentDirName}/images/${fileName}' }", "", "Here the setting is an object mapping from a set of globs to a set of file destinations.", "The left hand side ('docs/*.md') is a glob that matches against a markdown document. If the glob, matches then we use the right hand side to compute the new file's path and name. The right hand side can also use the special variables document in this setting description."] }, "configuration.markdown.copyFiles.overwriteBehavior": "Controls if files created by drop or paste should overwrite existing files.", "configuration.markdown.copyFiles.overwriteBehavior.nameIncrementally": "If a file with the same name already exists, append a number to the file name, for example: `image.png` becomes `image-1.png`.", "configuration.markdown.copyFiles.overwriteBehavior.overwrite": "If a file with the same name already exists, overwrite it.", "configuration.markdown.preferredMdPathExtensionStyle": "Controls if file extensions (for example `.md`) are added or not for links to Markdown files. This setting is used when file paths are added by tooling such as path completions or file renames.", "configuration.markdown.preferredMdPathExtensionStyle.auto": "For existing paths, try to maintain the file extension style. For new paths, add file extensions.", "configuration.markdown.preferredMdPathExtensionStyle.includeExtension": "Prefer including the file extension. For example, path completions to a file named `file.md` will insert `file.md`.", "configuration.markdown.preferredMdPathExtensionStyle.removeExtension": "Prefer removing the file extension. For example, path completions to a file named `file.md` will insert `file` without the `.md`.", "configuration.markdown.editor.filePaste.videoSnippet": "Snippet used when adding videos to Markdown. This snippet can use the following variables:\n- `${src}` \u2014 The resolved path of the video file.\n- `${title}` \u2014 The title used for the video. A snippet placeholder will automatically be created for this variable.", "configuration.markdown.editor.filePaste.audioSnippet": "Snippet used when adding audio to Markdown. This snippet can use the following variables:\n- `${src}` \u2014 The resolved path of the audio  file.\n- `${title}` \u2014 The title used for the audio. A snippet placeholder will automatically be created for this variable.", "configuration.markdown.editor.updateLinksOnPaste.enabled": "Enable/disable a paste option that updates links and reference in text that is copied and pasted between Markdown editors.\n\nTo use this feature, after pasting text that contains updatable links, just click on the Paste Widget and select `Paste and update pasted links`.", "workspaceTrust": "Required for loading styles configured in the workspace." }, "readmePath": "markdown-language-features/README.md" }, { "extensionPath": "markdown-math", "packageJSON": { "name": "markdown-math", "displayName": "%displayName%", "description": "%description%", "version": "1.0.0", "icon": "icon.png", "publisher": "vscode", "license": "MIT", "aiKey": "0c6ae279ed8443289764825290e4f9e2-1a736e7c-1324-4338-be46-fc2a58ae4d14-7255", "engines": { "vscode": "^1.54.0" }, "categories": ["Other", "Programming Languages"], "capabilities": { "virtualWorkspaces": true, "untrustedWorkspaces": { "supported": true } }, "main": "./dist/extension", "browser": "./dist/browser/extension", "activationEvents": [], "contributes": { "languages": [{ "id": "markdown-math", "aliases": [] }], "grammars": [{ "language": "markdown-math", "scopeName": "text.html.markdown.math", "path": "./syntaxes/md-math.tmLanguage.json" }, { "scopeName": "markdown.math.block", "path": "./syntaxes/md-math-block.tmLanguage.json", "injectTo": ["text.html.markdown"], "embeddedLanguages": { "meta.embedded.math.markdown": "latex" } }, { "scopeName": "markdown.math.inline", "path": "./syntaxes/md-math-inline.tmLanguage.json", "injectTo": ["text.html.markdown"], "embeddedLanguages": { "meta.embedded.math.markdown": "latex", "punctuation.definition.math.end.markdown": "latex" } }, { "scopeName": "markdown.math.codeblock", "path": "./syntaxes/md-math-fence.tmLanguage.json", "injectTo": ["text.html.markdown"], "embeddedLanguages": { "meta.embedded.math.markdown": "latex" } }], "notebookRenderer": [{ "id": "vscode.markdown-it-katex-extension", "displayName": "Markdown it KaTeX renderer", "entrypoint": { "extends": "vscode.markdown-it-renderer", "path": "./notebook-out/katex.js" } }], "markdown.markdownItPlugins": true, "markdown.previewStyles": ["./notebook-out/katex.min.css", "./preview-styles/index.css"], "configuration": [{ "title": "Markdown Math", "properties": { "markdown.math.enabled": { "type": "boolean", "default": true, "description": "%config.markdown.math.enabled%" }, "markdown.math.macros": { "type": "object", "additionalProperties": { "type": "string" }, "default": {}, "description": "%config.markdown.math.macros%", "scope": "resource" } } }] }, "repository": { "type": "git", "url": "https://github.com/microsoft/vscode.git" } }, "packageNLS": { "displayName": "Markdown Math", "description": "Adds math support to Markdown in notebooks.", "config.markdown.math.enabled": "Enable/disable rendering math in the built-in Markdown preview.", "config.markdown.math.macros": "A collection of custom macros. Each macro is a key-value pair where the key is a new command name and the value is the expansion of the macro." }, "readmePath": "markdown-math/README.md" }, { "extensionPath": "media-preview", "packageJSON": { "name": "media-preview", "displayName": "%displayName%", "description": "%description%", "extensionKind": ["ui", "workspace"], "version": "1.0.0", "publisher": "vscode", "icon": "icon.png", "license": "MIT", "aiKey": "0c6ae279ed8443289764825290e4f9e2-1a736e7c-1324-4338-be46-fc2a58ae4d14-7255", "engines": { "vscode": "^1.70.0" }, "main": "./dist/extension", "browser": "./dist/browser/extension.js", "categories": ["Other"], "activationEvents": [], "capabilities": { "virtualWorkspaces": true, "untrustedWorkspaces": { "supported": true } }, "contributes": { "configuration": { "type": "object", "title": "Media Previewer", "properties": { "mediaPreview.video.autoPlay": { "type": "boolean", "default": false, "markdownDescription": "%videoPreviewerAutoPlay%" }, "mediaPreview.video.loop": { "type": "boolean", "default": false, "markdownDescription": "%videoPreviewerLoop%" } } }, "customEditors": [{ "viewType": "imagePreview.previewEditor", "displayName": "%customEditor.imagePreview.displayName%", "priority": "builtin", "selector": [{ "filenamePattern": "*.{jpg,jpe,jpeg,png,bmp,gif,ico,webp,avif}" }] }, { "viewType": "vscode.audioPreview", "displayName": "%customEditor.audioPreview.displayName%", "priority": "builtin", "selector": [{ "filenamePattern": "*.{mp3,wav,ogg,oga}" }] }, { "viewType": "vscode.videoPreview", "displayName": "%customEditor.videoPreview.displayName%", "priority": "builtin", "selector": [{ "filenamePattern": "*.{mp4,webm}" }] }], "commands": [{ "command": "imagePreview.zoomIn", "title": "%command.zoomIn%", "category": "Image Preview" }, { "command": "imagePreview.zoomOut", "title": "%command.zoomOut%", "category": "Image Preview" }, { "command": "imagePreview.copyImage", "title": "%command.copyImage%", "category": "Image Preview" }], "menus": { "commandPalette": [{ "command": "imagePreview.zoomIn", "when": "activeCustomEditorId == 'imagePreview.previewEditor'", "group": "1_imagePreview" }, { "command": "imagePreview.zoomOut", "when": "activeCustomEditorId == 'imagePreview.previewEditor'", "group": "1_imagePreview" }, { "command": "imagePreview.copyImage", "when": "false" }], "webview/context": [{ "command": "imagePreview.copyImage", "when": "webviewId == 'imagePreview.previewEditor'" }] } }, "repository": { "type": "git", "url": "https://github.com/microsoft/vscode.git" } }, "packageNLS": { "displayName": "Media Preview", "description": "Provides VS Code's built-in previews for images, audio, and video", "customEditor.audioPreview.displayName": "Audio Preview", "customEditor.imagePreview.displayName": "Image Preview", "customEditor.videoPreview.displayName": "Video Preview", "videoPreviewerAutoPlay": "Start playing videos on mute automatically.", "videoPreviewerLoop": "Loop videos over again automatically.", "command.zoomIn": "Zoom in", "command.zoomOut": "Zoom out", "command.copyImage": "Copy" }, "readmePath": "media-preview/README.md" }, { "extensionPath": "merge-conflict", "packageJSON": { "name": "merge-conflict", "publisher": "vscode", "displayName": "%displayName%", "description": "%description%", "icon": "media/icon.png", "version": "1.0.0", "license": "MIT", "aiKey": "0c6ae279ed8443289764825290e4f9e2-1a736e7c-1324-4338-be46-fc2a58ae4d14-7255", "engines": { "vscode": "^1.5.0" }, "categories": ["Other"], "capabilities": { "virtualWorkspaces": true, "untrustedWorkspaces": { "supported": true } }, "activationEvents": ["onStartupFinished"], "main": "./dist/mergeConflictMain", "browser": "./dist/browser/mergeConflictMain", "contributes": { "commands": [{ "category": "%command.category%", "title": "%command.accept.all-current%", "original": "Accept All Current", "command": "merge-conflict.accept.all-current", "enablement": "!isMergeEditor" }, { "category": "%command.category%", "title": "%command.accept.all-incoming%", "original": "Accept All Incoming", "command": "merge-conflict.accept.all-incoming", "enablement": "!isMergeEditor" }, { "category": "%command.category%", "title": "%command.accept.all-both%", "original": "Accept All Both", "command": "merge-conflict.accept.all-both", "enablement": "!isMergeEditor" }, { "category": "%command.category%", "title": "%command.accept.current%", "original": "Accept Current", "command": "merge-conflict.accept.current", "enablement": "!isMergeEditor" }, { "category": "%command.category%", "title": "%command.accept.incoming%", "original": "Accept Incoming", "command": "merge-conflict.accept.incoming", "enablement": "!isMergeEditor" }, { "category": "%command.category%", "title": "%command.accept.selection%", "original": "Accept Selection", "command": "merge-conflict.accept.selection", "enablement": "!isMergeEditor" }, { "category": "%command.category%", "title": "%command.accept.both%", "original": "Accept Both", "command": "merge-conflict.accept.both", "enablement": "!isMergeEditor" }, { "category": "%command.category%", "title": "%command.next%", "original": "Next Conflict", "command": "merge-conflict.next", "enablement": "!isMergeEditor", "icon": "$(arrow-down)" }, { "category": "%command.category%", "title": "%command.previous%", "original": "Previous Conflict", "command": "merge-conflict.previous", "enablement": "!isMergeEditor", "icon": "$(arrow-up)" }, { "category": "%command.category%", "title": "%command.compare%", "original": "Compare Current Conflict", "command": "merge-conflict.compare", "enablement": "!isMergeEditor" }], "menus": { "scm/resourceState/context": [{ "command": "merge-conflict.accept.all-current", "when": "scmProvider == git && scmResourceGroup == merge", "group": "1_modification" }, { "command": "merge-conflict.accept.all-incoming", "when": "scmProvider == git && scmResourceGroup == merge", "group": "1_modification" }], "editor/title": [{ "command": "merge-conflict.previous", "group": "navigation@1", "when": "!isMergeEditor && mergeConflictsCount && mergeConflictsCount != 0" }, { "command": "merge-conflict.next", "group": "navigation@2", "when": "!isMergeEditor && mergeConflictsCount && mergeConflictsCount != 0" }] }, "configuration": { "title": "%config.title%", "properties": { "merge-conflict.codeLens.enabled": { "type": "boolean", "description": "%config.codeLensEnabled%", "default": true }, "merge-conflict.decorators.enabled": { "type": "boolean", "description": "%config.decoratorsEnabled%", "default": true }, "merge-conflict.autoNavigateNextConflict.enabled": { "type": "boolean", "description": "%config.autoNavigateNextConflictEnabled%", "default": false }, "merge-conflict.diffViewPosition": { "type": "string", "enum": ["Current", "Beside", "Below"], "description": "%config.diffViewPosition%", "enumDescriptions": ["%config.diffViewPosition.current%", "%config.diffViewPosition.beside%", "%config.diffViewPosition.below%"], "default": "Current" } } } }, "repository": { "type": "git", "url": "https://github.com/microsoft/vscode.git" } }, "packageNLS": { "displayName": "Merge Conflict", "description": "Highlighting and commands for inline merge conflicts.", "command.category": "Merge Conflict", "command.accept.all-current": "Accept All Current", "command.accept.all-incoming": "Accept All Incoming", "command.accept.all-both": "Accept All Both", "command.accept.current": "Accept Current", "command.accept.incoming": "Accept Incoming", "command.accept.selection": "Accept Selection", "command.accept.both": "Accept Both", "command.next": "Next Conflict", "command.previous": "Previous Conflict", "command.compare": "Compare Current Conflict", "config.title": "Merge Conflict", "config.autoNavigateNextConflictEnabled": "Whether to automatically navigate to the next merge conflict after resolving a merge conflict.", "config.codeLensEnabled": "Create a CodeLens for merge conflict blocks within editor.", "config.decoratorsEnabled": "Create decorators for merge conflict blocks within editor.", "config.diffViewPosition": "Controls where the diff view should be opened when comparing changes in merge conflicts.", "config.diffViewPosition.current": "Open the diff view in the current editor group.", "config.diffViewPosition.beside": "Open the diff view next to the current editor group.", "config.diffViewPosition.below": "Open the diff view below the current editor group." }, "readmePath": "merge-conflict/README.md" }, { "extensionPath": "ms-vscode.vscode-js-profile-table", "packageJSON": { "name": "vscode-js-profile-table", "version": "1.0.10", "displayName": "Table Visualizer for JavaScript Profiles", "description": "Text visualizer for profiles taken from the JavaScript debugger", "author": "Connor Peet <connor@peet.io>", "homepage": "https://github.com/microsoft/vscode-js-profile-visualizer#readme", "license": "MIT", "main": "out/extension.js", "browser": "out/extension.web.js", "repository": { "type": "git", "url": "https://github.com/microsoft/vscode-js-profile-visualizer.git" }, "capabilities": { "virtualWorkspaces": true, "untrustedWorkspaces": { "supported": true } }, "icon": "resources/icon.png", "publisher": "ms-vscode", "sideEffects": false, "engines": { "vscode": "^1.74.0" }, "contributes": { "customEditors": [{ "viewType": "jsProfileVisualizer.cpuprofile.table", "displayName": "CPU Profile Table Visualizer", "priority": "default", "selector": [{ "filenamePattern": "*.cpuprofile" }] }, { "viewType": "jsProfileVisualizer.heapprofile.table", "displayName": "Heap Profile Table Visualizer", "priority": "default", "selector": [{ "filenamePattern": "*.heapprofile" }] }, { "viewType": "jsProfileVisualizer.heapsnapshot.table", "displayName": "Heap Snapshot Table Visualizer", "priority": "default", "selector": [{ "filenamePattern": "*.heapsnapshot" }] }], "commands": [{ "command": "extension.jsProfileVisualizer.table.clearCodeLenses", "title": "Clear Profile Code Lenses" }], "menus": { "commandPalette": [{ "command": "extension.jsProfileVisualizer.table.clearCodeLenses", "when": "jsProfileVisualizer.hasCodeLenses == true" }] } }, "bugs": { "url": "https://github.com/microsoft/vscode-js-profile-visualizer/issues" }, "__metadata": { "id": "7e52b41b-71ad-457b-ab7e-0620f1fc4feb", "publisherId": { "publisherId": "5f5636e7-69ed-4afe-b5d6-8d231fb3d3ee", "publisherName": "ms-vscode", "displayName": "Microsoft", "flags": "verified" }, "publisherDisplayName": "Microsoft" } }, "readmePath": "ms-vscode.vscode-js-profile-table/README.md" }, { "extensionPath": "notebook-renderers", "packageJSON": { "name": "builtin-notebook-renderers", "displayName": "%displayName%", "description": "%description%", "publisher": "vscode", "version": "1.0.0", "license": "MIT", "icon": "media/icon.png", "engines": { "vscode": "^1.57.0" }, "capabilities": { "virtualWorkspaces": true, "untrustedWorkspaces": { "supported": true } }, "contributes": { "notebookRenderer": [{ "id": "vscode.builtin-renderer", "entrypoint": "./renderer-out/index.js", "displayName": "VS Code Builtin Notebook Output Renderer", "requiresMessaging": "never", "mimeTypes": ["image/gif", "image/png", "image/jpeg", "image/git", "image/svg+xml", "text/html", "application/javascript", "application/vnd.code.notebook.error", "application/vnd.code.notebook.stdout", "application/x.notebook.stdout", "application/x.notebook.stream", "application/vnd.code.notebook.stderr", "application/x.notebook.stderr", "text/plain"] }] }, "scripts": { "compile": "npx gulp compile-extension:notebook-renderers && npm run build-notebook", "watch": "npx gulp compile-watch:notebook-renderers", "build-notebook": "node ./esbuild" }, "dependencies": {}, "devDependencies": { "@types/jsdom": "^21.1.0", "@types/vscode-notebook-renderer": "^1.60.0", "jsdom": "^21.1.1" }, "repository": { "type": "git", "url": "https://github.com/microsoft/vscode.git" } }, "packageNLS": { "displayName": "Builtin Notebook Output Renderers", "description": "Provides basic output renderers for notebooks" }, "readmePath": "notebook-renderers/README.md" }, { "extensionPath": "npm", "packageJSON": { "name": "npm", "publisher": "vscode", "displayName": "%displayName%", "description": "%description%", "version": "1.0.1", "private": true, "license": "MIT", "engines": { "vscode": "0.10.x" }, "icon": "images/npm_icon.png", "categories": ["Other"], "enabledApiProposals": ["terminalQuickFixProvider"], "overrides": { "micromatch": "^4.0.8", "braces": "^3.0.3" }, "resolutions": { "micromatch": "^4.0.8", "braces": "^3.0.3" }, "main": "./dist/npmMain", "browser": "./dist/browser/npmBrowserMain", "activationEvents": ["onTaskType:npm", "onLanguage:json", "workspaceContains:package.json"], "capabilities": { "virtualWorkspaces": { "supported": "limited", "description": "%virtualWorkspaces%" }, "untrustedWorkspaces": { "supported": "limited", "description": "%workspaceTrust%" } }, "contributes": { "languages": [{ "id": "ignore", "extensions": [".npmignore"] }, { "id": "properties", "extensions": [".npmrc"] }], "views": { "explorer": [{ "id": "npm", "name": "%view.name%", "when": "npm:showScriptExplorer", "icon": "$(json)", "visibility": "hidden", "contextualTitle": "%view.name%" }] }, "commands": [{ "command": "npm.runScript", "title": "%command.run%", "icon": "$(run)" }, { "command": "npm.debugScript", "title": "%command.debug%", "icon": "$(debug)" }, { "command": "npm.openScript", "title": "%command.openScript%" }, { "command": "npm.runInstall", "title": "%command.runInstall%" }, { "command": "npm.refresh", "title": "%command.refresh%", "icon": "$(refresh)" }, { "command": "npm.runSelectedScript", "title": "%command.runSelectedScript%" }, { "command": "npm.runScriptFromFolder", "title": "%command.runScriptFromFolder%" }, { "command": "npm.packageManager", "title": "%command.packageManager%" }], "menus": { "commandPalette": [{ "command": "npm.refresh", "when": "false" }, { "command": "npm.runScript", "when": "false" }, { "command": "npm.debugScript", "when": "false" }, { "command": "npm.openScript", "when": "false" }, { "command": "npm.runInstall", "when": "false" }, { "command": "npm.runSelectedScript", "when": "false" }, { "command": "npm.runScriptFromFolder", "when": "false" }, { "command": "npm.packageManager", "when": "false" }], "editor/context": [{ "command": "npm.runSelectedScript", "when": "resourceFilename == 'package.json' && resourceScheme == file", "group": "navigation@+1" }], "view/title": [{ "command": "npm.refresh", "when": "view == npm", "group": "navigation" }], "view/item/context": [{ "command": "npm.openScript", "when": "view == npm && viewItem == packageJSON", "group": "navigation@1" }, { "command": "npm.runInstall", "when": "view == npm && viewItem == packageJSON", "group": "navigation@2" }, { "command": "npm.openScript", "when": "view == npm && viewItem == script", "group": "navigation@1" }, { "command": "npm.runScript", "when": "view == npm && viewItem == script", "group": "navigation@2" }, { "command": "npm.runScript", "when": "view == npm && viewItem == script", "group": "inline" }, { "command": "npm.debugScript", "when": "view == npm && viewItem == script", "group": "inline" }, { "command": "npm.debugScript", "when": "view == npm && viewItem == script", "group": "navigation@3" }], "explorer/context": [{ "when": "config.npm.enableRunFromFolder && explorerViewletVisible && explorerResourceIsFolder && resourceScheme == file", "command": "npm.runScriptFromFolder", "group": "2_workspace" }] }, "configuration": { "id": "npm", "type": "object", "title": "Npm", "properties": { "npm.autoDetect": { "type": "string", "enum": ["off", "on"], "default": "on", "scope": "resource", "description": "%config.npm.autoDetect%" }, "npm.runSilent": { "type": "boolean", "default": false, "scope": "resource", "markdownDescription": "%config.npm.runSilent%" }, "npm.packageManager": { "scope": "resource", "type": "string", "enum": ["auto", "npm", "yarn", "pnpm", "bun"], "enumDescriptions": ["%config.npm.packageManager.auto%", "%config.npm.packageManager.npm%", "%config.npm.packageManager.yarn%", "%config.npm.packageManager.pnpm%", "%config.npm.packageManager.bun%"], "default": "auto", "description": "%config.npm.packageManager%" }, "npm.exclude": { "type": ["string", "array"], "items": { "type": "string" }, "description": "%config.npm.exclude%", "scope": "resource" }, "npm.enableScriptExplorer": { "type": "boolean", "default": false, "scope": "resource", "deprecationMessage": "The NPM Script Explorer is now available in 'Views' menu in the Explorer in all folders.", "description": "%config.npm.enableScriptExplorer%" }, "npm.enableRunFromFolder": { "type": "boolean", "default": false, "scope": "resource", "description": "%config.npm.enableRunFromFolder%" }, "npm.scriptExplorerAction": { "type": "string", "enum": ["open", "run"], "markdownDescription": "%config.npm.scriptExplorerAction%", "scope": "window", "default": "open" }, "npm.scriptExplorerExclude": { "type": "array", "items": { "type": "string" }, "markdownDescription": "%config.npm.scriptExplorerExclude%", "scope": "resource", "default": [] }, "npm.fetchOnlinePackageInfo": { "type": "boolean", "description": "%config.npm.fetchOnlinePackageInfo%", "default": true, "scope": "window", "tags": ["usesOnlineServices"] }, "npm.scriptHover": { "type": "boolean", "description": "%config.npm.scriptHover%", "default": true, "scope": "window" } } }, "jsonValidation": [{ "fileMatch": "package.json", "url": "https://json.schemastore.org/package" }, { "fileMatch": "bower.json", "url": "https://json.schemastore.org/bower" }], "taskDefinitions": [{ "type": "npm", "required": ["script"], "properties": { "script": { "type": "string", "description": "%taskdef.script%" }, "path": { "type": "string", "description": "%taskdef.path%" } }, "when": "shellExecutionSupported" }], "terminalQuickFixes": [{ "id": "ms-vscode.npm-command", "commandLineMatcher": "npm", "commandExitResult": "error", "outputMatcher": { "anchor": "bottom", "length": 8, "lineMatcher": "Did you mean (?:this|one of these)\\?((?:\\n.+?npm .+ #.+)+)", "offset": 2 } }] }, "repository": { "type": "git", "url": "https://github.com/microsoft/vscode.git" } }, "packageNLS": { "description": "Extension to add task support for npm scripts.", "displayName": "NPM support for VS Code", "workspaceTrust": "This extension executes tasks, which require trust to run.", "virtualWorkspaces": "Functionality that requires running the 'npm' command is not available in virtual workspaces.", "config.npm.autoDetect": "Controls whether npm scripts should be automatically detected.", "config.npm.runSilent": "Run npm commands with the `--silent` option.", "config.npm.packageManager": "The package manager used to run scripts.", "config.npm.packageManager.npm": "Use npm as the package manager for running scripts.", "config.npm.packageManager.yarn": "Use yarn as the package manager for running scripts.", "config.npm.packageManager.pnpm": "Use pnpm as the package manager for running scripts.", "config.npm.packageManager.bun": "Use bun as the package manager for running scripts.", "config.npm.packageManager.auto": "Auto-detect which package manager to use for running scripts based on lock files and installed package managers.", "config.npm.exclude": "Configure glob patterns for folders that should be excluded from automatic script detection.", "config.npm.enableScriptExplorer": "Enable an explorer view for npm scripts when there is no top-level 'package.json' file.", "config.npm.scriptExplorerAction": "The default click action used in the NPM Scripts Explorer: `open` or `run`, the default is `open`.", "config.npm.scriptExplorerExclude": "An array of regular expressions that indicate which scripts should be excluded from the NPM Scripts view.", "config.npm.enableRunFromFolder": "Enable running npm scripts contained in a folder from the Explorer context menu.", "config.npm.fetchOnlinePackageInfo": "Fetch data from https://registry.npmjs.org and https://registry.bower.io to provide auto-completion and information on hover features on npm dependencies.", "config.npm.scriptHover": "Display hover with 'Run' and 'Debug' commands for scripts.", "npm.parseError": "Npm task detection: failed to parse the file {0}", "taskdef.script": "The npm script to customize.", "taskdef.path": "The path to the folder of the package.json file that provides the script. Can be omitted.", "view.name": "NPM Scripts", "command.refresh": "Refresh", "command.run": "Run", "command.debug": "Debug", "command.openScript": "Open", "command.runInstall": "Run Install", "command.runSelectedScript": "Run Script", "command.runScriptFromFolder": "Run NPM Script in Folder...", "command.packageManager": "Get Configured Package Manager" }, "readmePath": "npm/README.md" }, { "extensionPath": "objective-c", "packageJSON": { "name": "objective-c", "displayName": "%displayName%", "description": "%description%", "version": "1.0.0", "publisher": "vscode", "license": "MIT", "engines": { "vscode": "*" }, "scripts": { "update-grammar": "node ./build/update-grammars.js" }, "categories": ["Programming Languages"], "contributes": { "languages": [{ "id": "objective-c", "extensions": [".m"], "aliases": ["Objective-C"], "configuration": "./language-configuration.json" }, { "id": "objective-cpp", "extensions": [".mm"], "aliases": ["Objective-C++"], "configuration": "./language-configuration.json" }], "grammars": [{ "language": "objective-c", "scopeName": "source.objc", "path": "./syntaxes/objective-c.tmLanguage.json" }, { "language": "objective-cpp", "scopeName": "source.objcpp", "path": "./syntaxes/objective-c++.tmLanguage.json" }] }, "repository": { "type": "git", "url": "https://github.com/microsoft/vscode.git" } }, "packageNLS": { "displayName": "Objective-C Language Basics", "description": "Provides syntax highlighting and bracket matching in Objective-C files." } }, { "extensionPath": "perl", "packageJSON": { "name": "perl", "displayName": "%displayName%", "description": "%description%", "version": "1.0.0", "publisher": "vscode", "license": "MIT", "engines": { "vscode": "*" }, "scripts": { "update-grammar": "node ../node_modules/vscode-grammar-updater/bin textmate/perl.tmbundle Syntaxes/Perl.plist ./syntaxes/perl.tmLanguage.json Syntaxes/Perl%206.tmLanguage ./syntaxes/perl6.tmLanguage.json" }, "categories": ["Programming Languages"], "contributes": { "languages": [{ "id": "perl", "aliases": ["Perl", "perl"], "extensions": [".pl", ".pm", ".pod", ".t", ".PL", ".psgi"], "firstLine": "^#!.*\\bperl\\b", "configuration": "./perl.language-configuration.json" }, { "id": "raku", "aliases": ["Raku", "Perl6", "perl6"], "extensions": [".raku", ".rakumod", ".rakutest", ".rakudoc", ".nqp", ".p6", ".pl6", ".pm6"], "firstLine": "(^#!.*\\bperl6\\b)|use\\s+v6|raku|=begin\\spod|my\\sclass", "configuration": "./perl6.language-configuration.json" }], "grammars": [{ "language": "perl", "scopeName": "source.perl", "path": "./syntaxes/perl.tmLanguage.json", "unbalancedBracketScopes": ["variable.other.predefined.perl"] }, { "language": "raku", "scopeName": "source.perl.6", "path": "./syntaxes/perl6.tmLanguage.json" }] }, "repository": { "type": "git", "url": "https://github.com/microsoft/vscode.git" } }, "packageNLS": { "displayName": "Perl Language Basics", "description": "Provides syntax highlighting and bracket matching in Perl files." } }, { "extensionPath": "php", "packageJSON": { "name": "php", "displayName": "%displayName%", "description": "%description%", "version": "1.0.0", "publisher": "vscode", "license": "MIT", "engines": { "vscode": "0.10.x" }, "categories": ["Programming Languages"], "contributes": { "languages": [{ "id": "php", "extensions": [".php", ".php4", ".php5", ".phtml", ".ctp"], "aliases": ["PHP", "php"], "firstLine": "^#!\\s*/.*\\bphp\\b", "mimetypes": ["application/x-php"], "configuration": "./language-configuration.json" }], "grammars": [{ "language": "php", "scopeName": "source.php", "path": "./syntaxes/php.tmLanguage.json" }, { "language": "php", "scopeName": "text.html.php", "path": "./syntaxes/html.tmLanguage.json", "embeddedLanguages": { "text.html": "html", "source.php": "php", "source.sql": "sql", "text.xml": "xml", "source.js": "javascript", "source.json": "json", "source.css": "css" } }], "snippets": [{ "language": "php", "path": "./snippets/php.code-snippets" }] }, "scripts": { "update-grammar": "node ./build/update-grammar.mjs" }, "repository": { "type": "git", "url": "https://github.com/microsoft/vscode.git" } }, "packageNLS": { "displayName": "PHP Language Basics", "description": "Provides syntax highlighting and bracket matching for PHP files." } }, { "extensionPath": "powershell", "packageJSON": { "name": "powershell", "displayName": "%displayName%", "description": "%description%", "version": "1.0.0", "publisher": "vscode", "license": "MIT", "engines": { "vscode": "*" }, "categories": ["Programming Languages"], "contributes": { "languages": [{ "id": "powershell", "extensions": [".ps1", ".psm1", ".psd1", ".pssc", ".psrc"], "aliases": ["PowerShell", "powershell", "ps", "ps1", "pwsh"], "firstLine": "^#!\\s*/.*\\bpwsh\\b", "configuration": "./language-configuration.json" }], "grammars": [{ "language": "powershell", "scopeName": "source.powershell", "path": "./syntaxes/powershell.tmLanguage.json" }] }, "scripts": { "update-grammar": "node ../node_modules/vscode-grammar-updater/bin PowerShell/EditorSyntax PowerShellSyntax.tmLanguage ./syntaxes/powershell.tmLanguage.json" }, "repository": { "type": "git", "url": "https://github.com/microsoft/vscode.git" } }, "packageNLS": { "displayName": "Powershell Language Basics", "description": "Provides snippets, syntax highlighting, bracket matching and folding in Powershell files." } }, { "extensionPath": "pug", "packageJSON": { "name": "pug", "displayName": "%displayName%", "description": "%description%", "version": "1.0.0", "publisher": "vscode", "license": "MIT", "engines": { "vscode": "*" }, "scripts": { "update-grammar": "node ../node_modules/vscode-grammar-updater/bin davidrios/pug-tmbundle Syntaxes/Pug.JSON-tmLanguage ./syntaxes/pug.tmLanguage.json" }, "categories": ["Programming Languages"], "contributes": { "languages": [{ "id": "jade", "extensions": [".pug", ".jade"], "aliases": ["Pug", "Jade", "jade"], "configuration": "./language-configuration.json" }], "grammars": [{ "language": "jade", "scopeName": "text.pug", "path": "./syntaxes/pug.tmLanguage.json" }], "configurationDefaults": { "[jade]": { "diffEditor.ignoreTrimWhitespace": false } } }, "repository": { "type": "git", "url": "https://github.com/microsoft/vscode.git" } }, "packageNLS": { "displayName": "Pug Language Basics", "description": "Provides syntax highlighting and bracket matching in Pug files." } }, { "extensionPath": "python", "packageJSON": { "name": "python", "displayName": "%displayName%", "description": "%description%", "version": "1.0.0", "publisher": "vscode", "license": "MIT", "engines": { "vscode": "*" }, "categories": ["Programming Languages"], "contributes": { "languages": [{ "id": "python", "extensions": [".py", ".rpy", ".pyw", ".cpy", ".gyp", ".gypi", ".pyi", ".ipy", ".pyt"], "aliases": ["Python", "py"], "filenames": ["SConstruct", "SConscript"], "firstLine": "^#!\\s*/?.*\\bpython[0-9.-]*\\b", "configuration": "./language-configuration.json" }], "grammars": [{ "language": "python", "scopeName": "source.python", "path": "./syntaxes/MagicPython.tmLanguage.json" }, { "scopeName": "source.regexp.python", "path": "./syntaxes/MagicRegExp.tmLanguage.json" }], "configurationDefaults": { "[python]": { "diffEditor.ignoreTrimWhitespace": false, "editor.defaultColorDecorators": false } } }, "scripts": { "update-grammar": "node ../node_modules/vscode-grammar-updater/bin MagicStack/MagicPython grammars/MagicPython.tmLanguage ./syntaxes/MagicPython.tmLanguage.json grammars/MagicRegExp.tmLanguage ./syntaxes/MagicRegExp.tmLanguage.json" }, "repository": { "type": "git", "url": "https://github.com/microsoft/vscode.git" } }, "packageNLS": { "displayName": "Python Language Basics", "description": "Provides syntax highlighting, bracket matching and folding in Python files." } }, { "extensionPath": "r", "packageJSON": { "name": "r", "displayName": "%displayName%", "description": "%description%", "version": "1.0.0", "publisher": "vscode", "license": "MIT", "engines": { "vscode": "*" }, "scripts": { "update-grammar": "node ../node_modules/vscode-grammar-updater/bin REditorSupport/vscode-R syntax/r.json ./syntaxes/r.tmLanguage.json" }, "categories": ["Programming Languages"], "contributes": { "languages": [{ "id": "r", "extensions": [".r", ".rhistory", ".rprofile", ".rt"], "aliases": ["R", "r"], "configuration": "./language-configuration.json" }], "grammars": [{ "language": "r", "scopeName": "source.r", "path": "./syntaxes/r.tmLanguage.json" }] }, "repository": { "type": "git", "url": "https://github.com/microsoft/vscode.git" } }, "packageNLS": { "displayName": "R Language Basics", "description": "Provides syntax highlighting and bracket matching in R files." } }, { "extensionPath": "razor", "packageJSON": { "name": "razor", "displayName": "%displayName%", "description": "%description%", "version": "1.0.0", "publisher": "vscode", "license": "MIT", "engines": { "vscode": "0.10.x" }, "scripts": { "update-grammar": "node ./build/update-grammar.mjs" }, "categories": ["Programming Languages"], "contributes": { "languages": [{ "id": "razor", "extensions": [".cshtml", ".razor"], "aliases": ["Razor", "razor"], "mimetypes": ["text/x-cshtml"], "configuration": "./language-configuration.json" }], "grammars": [{ "language": "razor", "scopeName": "text.html.cshtml", "path": "./syntaxes/cshtml.tmLanguage.json", "embeddedLanguages": { "section.embedded.source.cshtml": "csharp", "source.css": "css", "source.js": "javascript" } }] }, "repository": { "type": "git", "url": "https://github.com/microsoft/vscode.git" } }, "packageNLS": { "displayName": "Razor Language Basics", "description": "Provides syntax highlighting, bracket matching and folding in Razor files." } }, { "extensionPath": "references-view", "packageJSON": { "name": "references-view", "displayName": "%displayName%", "description": "%description%", "icon": "media/icon.png", "version": "1.0.0", "publisher": "vscode", "license": "MIT", "engines": { "vscode": "^1.67.0" }, "capabilities": { "virtualWorkspaces": true, "untrustedWorkspaces": { "supported": true } }, "repository": { "type": "git", "url": "https://github.com/Microsoft/vscode-references-view" }, "bugs": { "url": "https://github.com/Microsoft/vscode-references-view/issues" }, "activationEvents": ["onCommand:references-view.find", "onCommand:editor.action.showReferences"], "main": "./dist/extension", "browser": "./dist/extension.js", "contributes": { "configuration": { "properties": { "references.preferredLocation": { "description": "%config.references.preferredLocation%", "type": "string", "default": "peek", "enum": ["peek", "view"], "enumDescriptions": ["%config.references.preferredLocation.peek%", "%config.references.preferredLocation.view%"] } } }, "viewsContainers": { "activitybar": [{ "id": "references-view", "icon": "$(references)", "title": "%container.title%" }] }, "views": { "references-view": [{ "id": "references-view.tree", "name": "%view.title%", "when": "reference-list.isActive" }] }, "commands": [{ "command": "references-view.findReferences", "title": "%cmd.references-view.findReferences%", "category": "%cmd.category.references%" }, { "command": "references-view.findImplementations", "title": "%cmd.references-view.findImplementations%", "category": "%cmd.category.references%" }, { "command": "references-view.clearHistory", "title": "%cmd.references-view.clearHistory%", "category": "%cmd.category.references%", "icon": "$(clear-all)" }, { "command": "references-view.clear", "title": "%cmd.references-view.clear%", "category": "%cmd.category.references%", "icon": "$(clear-all)" }, { "command": "references-view.refresh", "title": "%cmd.references-view.refresh%", "category": "%cmd.category.references%", "icon": "$(refresh)" }, { "command": "references-view.pickFromHistory", "title": "%cmd.references-view.pickFromHistory%", "category": "%cmd.category.references%" }, { "command": "references-view.removeReferenceItem", "title": "%cmd.references-view.removeReferenceItem%", "icon": "$(close)" }, { "command": "references-view.copy", "title": "%cmd.references-view.copy%" }, { "command": "references-view.copyAll", "title": "%cmd.references-view.copyAll%" }, { "command": "references-view.copyPath", "title": "%cmd.references-view.copyPath%" }, { "command": "references-view.refind", "title": "%cmd.references-view.refind%", "icon": "$(refresh)" }, { "command": "references-view.showCallHierarchy", "title": "%cmd.references-view.showCallHierarchy%", "category": "Calls" }, { "command": "references-view.showOutgoingCalls", "title": "%cmd.references-view.showOutgoingCalls%", "category": "Calls", "icon": "$(call-outgoing)" }, { "command": "references-view.showIncomingCalls", "title": "%cmd.references-view.showIncomingCalls%", "category": "Calls", "icon": "$(call-incoming)" }, { "command": "references-view.removeCallItem", "title": "%cmd.references-view.removeCallItem%", "icon": "$(close)" }, { "command": "references-view.next", "title": "%cmd.references-view.next%", "enablement": "references-view.canNavigate" }, { "command": "references-view.prev", "title": "%cmd.references-view.prev%", "enablement": "references-view.canNavigate" }, { "command": "references-view.showTypeHierarchy", "title": "%cmd.references-view.showTypeHierarchy%", "category": "Types" }, { "command": "references-view.showSupertypes", "title": "%cmd.references-view.showSupertypes%", "category": "Types", "icon": "$(type-hierarchy-super)" }, { "command": "references-view.showSubtypes", "title": "%cmd.references-view.showSubtypes%", "category": "Types", "icon": "$(type-hierarchy-sub)" }, { "command": "references-view.removeTypeItem", "title": "%cmd.references-view.removeTypeItem%", "icon": "$(close)" }], "menus": { "editor/context": [{ "command": "references-view.findReferences", "when": "editorHasReferenceProvider", "group": "0_navigation@1" }, { "command": "references-view.findImplementations", "when": "editorHasImplementationProvider", "group": "0_navigation@2" }, { "command": "references-view.showCallHierarchy", "when": "editorHasCallHierarchyProvider", "group": "0_navigation@3" }, { "command": "references-view.showTypeHierarchy", "when": "editorHasTypeHierarchyProvider", "group": "0_navigation@4" }], "view/title": [{ "command": "references-view.clear", "group": "navigation@3", "when": "view == references-view.tree && reference-list.hasResult" }, { "command": "references-view.clearHistory", "group": "navigation@3", "when": "view == references-view.tree && reference-list.hasHistory && !reference-list.hasResult" }, { "command": "references-view.refresh", "group": "navigation@2", "when": "view == references-view.tree && reference-list.hasResult" }, { "command": "references-view.showOutgoingCalls", "group": "navigation@1", "when": "view == references-view.tree && reference-list.hasResult && reference-list.source == callHierarchy &&  references-view.callHierarchyMode == showIncoming" }, { "command": "references-view.showIncomingCalls", "group": "navigation@1", "when": "view == references-view.tree && reference-list.hasResult && reference-list.source == callHierarchy &&  references-view.callHierarchyMode == showOutgoing" }, { "command": "references-view.showSupertypes", "group": "navigation@1", "when": "view == references-view.tree && reference-list.hasResult && reference-list.source == typeHierarchy &&  references-view.typeHierarchyMode != supertypes" }, { "command": "references-view.showSubtypes", "group": "navigation@1", "when": "view == references-view.tree && reference-list.hasResult && reference-list.source == typeHierarchy &&  references-view.typeHierarchyMode != subtypes" }], "view/item/context": [{ "command": "references-view.removeReferenceItem", "group": "inline", "when": "view == references-view.tree && viewItem == file-item || view == references-view.tree && viewItem == reference-item" }, { "command": "references-view.removeCallItem", "group": "inline", "when": "view == references-view.tree && viewItem == call-item" }, { "command": "references-view.removeTypeItem", "group": "inline", "when": "view == references-view.tree && viewItem == type-item" }, { "command": "references-view.refind", "group": "inline", "when": "view == references-view.tree && viewItem == history-item" }, { "command": "references-view.removeReferenceItem", "group": "1", "when": "view == references-view.tree && viewItem == file-item || view == references-view.tree && viewItem == reference-item" }, { "command": "references-view.removeCallItem", "group": "1", "when": "view == references-view.tree && viewItem == call-item" }, { "command": "references-view.removeTypeItem", "group": "1", "when": "view == references-view.tree && viewItem == type-item" }, { "command": "references-view.refind", "group": "1", "when": "view == references-view.tree && viewItem == history-item" }, { "command": "references-view.copy", "group": "2@1", "when": "view == references-view.tree && viewItem == file-item || view == references-view.tree && viewItem == reference-item" }, { "command": "references-view.copyPath", "group": "2@2", "when": "view == references-view.tree && viewItem == file-item" }, { "command": "references-view.copyAll", "group": "2@3", "when": "view == references-view.tree && viewItem == file-item || view == references-view.tree && viewItem == reference-item" }, { "command": "references-view.showOutgoingCalls", "group": "1", "when": "view == references-view.tree && viewItem == call-item" }, { "command": "references-view.showIncomingCalls", "group": "1", "when": "view == references-view.tree && viewItem == call-item" }, { "command": "references-view.showSupertypes", "group": "1", "when": "view == references-view.tree && viewItem == type-item" }, { "command": "references-view.showSubtypes", "group": "1", "when": "view == references-view.tree && viewItem == type-item" }], "commandPalette": [{ "command": "references-view.removeReferenceItem", "when": "never" }, { "command": "references-view.removeCallItem", "when": "never" }, { "command": "references-view.removeTypeItem", "when": "never" }, { "command": "references-view.copy", "when": "never" }, { "command": "references-view.copyAll", "when": "never" }, { "command": "references-view.copyPath", "when": "never" }, { "command": "references-view.refind", "when": "never" }, { "command": "references-view.findReferences", "when": "editorHasReferenceProvider" }, { "command": "references-view.clear", "when": "reference-list.hasResult" }, { "command": "references-view.clearHistory", "when": "reference-list.isActive && !reference-list.hasResult" }, { "command": "references-view.refresh", "when": "reference-list.hasResult" }, { "command": "references-view.pickFromHistory", "when": "reference-list.isActive" }, { "command": "references-view.next", "when": "never" }, { "command": "references-view.prev", "when": "never" }] }, "keybindings": [{ "command": "references-view.findReferences", "when": "editorHasReferenceProvider", "key": "shift+alt+f12" }, { "command": "references-view.next", "when": "reference-list.hasResult", "key": "f4" }, { "command": "references-view.prev", "when": "reference-list.hasResult", "key": "shift+f4" }, { "command": "references-view.showCallHierarchy", "when": "editorHasCallHierarchyProvider", "key": "shift+alt+h" }] } }, "packageNLS": { "displayName": "Reference Search View", "description": "Reference Search results as separate, stable view in the sidebar", "config.references.preferredLocation": "Controls whether 'Peek References' or 'Find References' is invoked when selecting CodeLens references.", "config.references.preferredLocation.peek": "Show references in peek editor.", "config.references.preferredLocation.view": "Show references in separate view.", "container.title": "References", "view.title": "Reference Search Results", "cmd.category.references": "References", "cmd.references-view.findReferences": "Find All References", "cmd.references-view.findImplementations": "Find All Implementations", "cmd.references-view.clearHistory": "Clear History", "cmd.references-view.clear": "Clear", "cmd.references-view.refresh": "Refresh", "cmd.references-view.pickFromHistory": "Show History", "cmd.references-view.removeReferenceItem": "Dismiss", "cmd.references-view.copy": "Copy", "cmd.references-view.copyAll": "Copy All", "cmd.references-view.copyPath": "Copy Path", "cmd.references-view.refind": "Rerun", "cmd.references-view.showCallHierarchy": "Show Call Hierarchy", "cmd.references-view.showOutgoingCalls": "Show Outgoing Calls", "cmd.references-view.showIncomingCalls": "Show Incoming Calls", "cmd.references-view.removeCallItem": "Dismiss", "cmd.references-view.next": "Go to Next Reference", "cmd.references-view.prev": "Go to Previous Reference", "cmd.references-view.showTypeHierarchy": "Show Type Hierarchy", "cmd.references-view.showSupertypes": "Show Supertypes", "cmd.references-view.showSubtypes": "Show Subtypes", "cmd.references-view.removeTypeItem": "Dismiss" }, "readmePath": "references-view/README.md" }, { "extensionPath": "restructuredtext", "packageJSON": { "name": "restructuredtext", "displayName": "%displayName%", "description": "%description%", "version": "1.0.0", "publisher": "vscode", "license": "MIT", "engines": { "vscode": "*" }, "scripts": { "update-grammar": "node ../node_modules/vscode-grammar-updater/bin trond-snekvik/vscode-rst syntaxes/rst.tmLanguage.json ./syntaxes/rst.tmLanguage.json" }, "categories": ["Programming Languages"], "contributes": { "languages": [{ "id": "restructuredtext", "aliases": ["reStructuredText"], "configuration": "./language-configuration.json", "extensions": [".rst"] }], "grammars": [{ "language": "restructuredtext", "scopeName": "source.rst", "path": "./syntaxes/rst.tmLanguage.json" }] }, "repository": { "type": "git", "url": "https://github.com/microsoft/vscode.git" } }, "packageNLS": { "displayName": "reStructuredText Language Basics", "description": "Provides syntax highlighting in reStructuredText files." } }, { "extensionPath": "ruby", "packageJSON": { "name": "ruby", "displayName": "%displayName%", "description": "%description%", "version": "1.0.0", "publisher": "vscode", "license": "MIT", "engines": { "vscode": "*" }, "scripts": { "update-grammar": "node ../node_modules/vscode-grammar-updater/bin textmate/ruby.tmbundle Syntaxes/Ruby.plist ./syntaxes/ruby.tmLanguage.json" }, "categories": ["Programming Languages"], "contributes": { "languages": [{ "id": "ruby", "extensions": [".rb", ".rbx", ".rjs", ".gemspec", ".rake", ".ru", ".erb", ".podspec", ".rbi"], "filenames": ["rakefile", "gemfile", "guardfile", "podfile", "capfile", "cheffile", "hobofile", "vagrantfile", "appraisals", "rantfile", "berksfile", "berksfile.lock", "thorfile", "puppetfile", "dangerfile", "brewfile", "fastfile", "appfile", "deliverfile", "matchfile", "scanfile", "snapfile", "gymfile"], "aliases": ["Ruby", "rb"], "firstLine": "^#!\\s*/.*\\bruby\\b", "configuration": "./language-configuration.json" }], "grammars": [{ "language": "ruby", "scopeName": "source.ruby", "path": "./syntaxes/ruby.tmLanguage.json" }], "configurationDefaults": { "[ruby]": { "editor.defaultColorDecorators": false } } }, "repository": { "type": "git", "url": "https://github.com/microsoft/vscode.git" } }, "packageNLS": { "displayName": "Ruby Language Basics", "description": "Provides syntax highlighting and bracket matching in Ruby files." } }, { "extensionPath": "rust", "packageJSON": { "name": "rust", "displayName": "%displayName%", "description": "%description%", "version": "1.0.0", "publisher": "vscode", "license": "MIT", "engines": { "vscode": "*" }, "scripts": { "update-grammar": "node ./build/update-grammar.mjs" }, "categories": ["Programming Languages"], "contributes": { "languages": [{ "id": "rust", "extensions": [".rs"], "aliases": ["Rust", "rust"], "configuration": "./language-configuration.json" }], "grammars": [{ "language": "rust", "path": "./syntaxes/rust.tmLanguage.json", "scopeName": "source.rust" }] }, "repository": { "type": "git", "url": "https://github.com/microsoft/vscode.git" } }, "packageNLS": { "displayName": "Rust Language Basics", "description": "Provides syntax highlighting and bracket matching in Rust files." } }, { "extensionPath": "scss", "packageJSON": { "name": "scss", "displayName": "%displayName%", "description": "%description%", "version": "1.0.0", "publisher": "vscode", "license": "MIT", "engines": { "vscode": "*" }, "scripts": { "update-grammar": "node ../node_modules/vscode-grammar-updater/bin atom/language-sass grammars/scss.cson ./syntaxes/scss.tmLanguage.json grammars/sassdoc.cson ./syntaxes/sassdoc.tmLanguage.json" }, "categories": ["Programming Languages"], "contributes": { "languages": [{ "id": "scss", "aliases": ["SCSS", "scss"], "extensions": [".scss"], "mimetypes": ["text/x-scss", "text/scss"], "configuration": "./language-configuration.json" }], "grammars": [{ "language": "scss", "scopeName": "source.css.scss", "path": "./syntaxes/scss.tmLanguage.json" }, { "scopeName": "source.sassdoc", "path": "./syntaxes/sassdoc.tmLanguage.json" }], "problemMatchers": [{ "name": "node-sass", "label": "Node Sass Compiler", "owner": "node-sass", "fileLocation": "absolute", "pattern": [{ "regexp": "^{$" }, { "regexp": '\\s*"status":\\s\\d+,' }, { "regexp": '\\s*"file":\\s"(.*)",', "file": 1 }, { "regexp": '\\s*"line":\\s(\\d+),', "line": 1 }, { "regexp": '\\s*"column":\\s(\\d+),', "column": 1 }, { "regexp": '\\s*"message":\\s"(.*)",', "message": 1 }, { "regexp": '\\s*"formatted":\\s(.*)' }, { "regexp": "^}$" }] }] }, "repository": { "type": "git", "url": "https://github.com/microsoft/vscode.git" } }, "packageNLS": { "displayName": "SCSS Language Basics", "description": "Provides syntax highlighting, bracket matching and folding in SCSS files." } }, { "extensionPath": "search-result", "packageJSON": { "name": "search-result", "displayName": "%displayName%", "description": "%description%", "version": "1.0.0", "publisher": "vscode", "license": "MIT", "icon": "images/icon.png", "engines": { "vscode": "^1.39.0" }, "main": "./dist/extension.js", "browser": "./dist/extension.js", "activationEvents": ["onLanguage:search-result"], "capabilities": { "virtualWorkspaces": true, "untrustedWorkspaces": { "supported": true } }, "enabledApiProposals": ["documentFiltersExclusive"], "contributes": { "configurationDefaults": { "[search-result]": { "editor.lineNumbers": "off" } }, "languages": [{ "id": "search-result", "extensions": [".code-search"], "aliases": ["Search Result"] }], "grammars": [{ "language": "search-result", "scopeName": "text.searchResult", "path": "./syntaxes/searchResult.tmLanguage.json" }] }, "repository": { "type": "git", "url": "https://github.com/microsoft/vscode.git" } }, "packageNLS": { "displayName": "Search Result", "description": "Provides syntax highlighting and language features for tabbed search results." }, "readmePath": "search-result/README.md" }, { "extensionPath": "shaderlab", "packageJSON": { "name": "shaderlab", "displayName": "%displayName%", "description": "%description%", "version": "1.0.0", "publisher": "vscode", "license": "MIT", "engines": { "vscode": "*" }, "scripts": { "update-grammar": "node ../node_modules/vscode-grammar-updater/bin tgjones/shaders-tmLanguage grammars/shaderlab.json ./syntaxes/shaderlab.tmLanguage.json" }, "categories": ["Programming Languages"], "contributes": { "languages": [{ "id": "shaderlab", "extensions": [".shader"], "aliases": ["ShaderLab", "shaderlab"], "configuration": "./language-configuration.json" }], "grammars": [{ "language": "shaderlab", "path": "./syntaxes/shaderlab.tmLanguage.json", "scopeName": "source.shaderlab" }] }, "repository": { "type": "git", "url": "https://github.com/microsoft/vscode.git" } }, "packageNLS": { "displayName": "Shaderlab Language Basics", "description": "Provides syntax highlighting and bracket matching in Shaderlab files." } }, { "extensionPath": "shellscript", "packageJSON": { "name": "shellscript", "displayName": "%displayName%", "description": "%description%", "version": "1.0.0", "publisher": "vscode", "license": "MIT", "engines": { "vscode": "*" }, "scripts": { "update-grammar": "node ../node_modules/vscode-grammar-updater/bin jeff-hykin/better-shell-syntax autogenerated/shell.tmLanguage.json ./syntaxes/shell-unix-bash.tmLanguage.json" }, "categories": ["Programming Languages"], "contributes": { "languages": [{ "id": "shellscript", "aliases": ["Shell Script", "shellscript", "bash", "fish", "sh", "zsh", "ksh", "csh"], "extensions": [".sh", ".bash", ".bashrc", ".bash_aliases", ".bash_profile", ".bash_login", ".ebuild", ".eclass", ".profile", ".bash_logout", ".xprofile", ".xsession", ".xsessionrc", ".Xsession", ".zsh", ".zshrc", ".zprofile", ".zlogin", ".zlogout", ".zshenv", ".zsh-theme", ".fish", ".ksh", ".csh", ".cshrc", ".tcshrc", ".yashrc", ".yash_profile"], "filenames": ["APKBUILD", "PKGBUILD", ".envrc", ".hushlogin", "zshrc", "zshenv", "zlogin", "zprofile", "zlogout", "bashrc_Apple_Terminal", "zshrc_Apple_Terminal"], "filenamePatterns": [".env.*"], "firstLine": "^#!.*\\b(bash|fish|zsh|sh|ksh|dtksh|pdksh|mksh|ash|dash|yash|sh|csh|jcsh|tcsh|itcsh).*|^#\\s*-\\*-[^*]*mode:\\s*shell-script[^*]*-\\*-", "configuration": "./language-configuration.json", "mimetypes": ["text/x-shellscript"] }], "grammars": [{ "language": "shellscript", "scopeName": "source.shell", "path": "./syntaxes/shell-unix-bash.tmLanguage.json", "balancedBracketScopes": ["*"], "unbalancedBracketScopes": ["meta.scope.case-pattern.shell"] }], "configurationDefaults": { "[shellscript]": { "files.eol": "\n", "editor.defaultColorDecorators": false } } }, "repository": { "type": "git", "url": "https://github.com/microsoft/vscode.git" } }, "packageNLS": { "displayName": "Shell Script Language Basics", "description": "Provides syntax highlighting and bracket matching in Shell Script files." } }, { "extensionPath": "simple-browser", "packageJSON": { "name": "simple-browser", "displayName": "%displayName%", "description": "%description%", "enabledApiProposals": ["externalUriOpener"], "version": "1.0.0", "icon": "media/icon.png", "publisher": "vscode", "license": "MIT", "aiKey": "0c6ae279ed8443289764825290e4f9e2-1a736e7c-1324-4338-be46-fc2a58ae4d14-7255", "engines": { "vscode": "^1.70.0" }, "main": "./dist/extension", "browser": "./dist/browser/extension", "categories": ["Other"], "extensionKind": ["ui", "workspace"], "activationEvents": ["onCommand:simpleBrowser.api.open", "onOpenExternalUri:http", "onOpenExternalUri:https", "onWebviewPanel:simpleBrowser.view"], "capabilities": { "virtualWorkspaces": true, "untrustedWorkspaces": { "supported": true } }, "contributes": { "commands": [{ "command": "simpleBrowser.show", "title": "Show", "category": "Simple Browser" }], "configuration": [{ "title": "Simple Browser", "properties": { "simpleBrowser.focusLockIndicator.enabled": { "type": "boolean", "default": true, "title": "Focus Lock Indicator Enabled", "description": "%configuration.focusLockIndicator.enabled.description%" } } }] }, "repository": { "type": "git", "url": "https://github.com/microsoft/vscode.git" } }, "packageNLS": { "displayName": "Simple Browser", "description": "A very basic built-in webview for displaying web content.", "configuration.focusLockIndicator.enabled.description": "Enable/disable the floating indicator that shows when focused in the simple browser." }, "readmePath": "simple-browser/README.md" }, { "extensionPath": "sql", "packageJSON": { "name": "sql", "displayName": "%displayName%", "description": "%description%", "version": "1.0.0", "publisher": "vscode", "license": "MIT", "engines": { "vscode": "*" }, "scripts": { "update-grammar": "node ./build/update-grammar.mjs" }, "categories": ["Programming Languages"], "contributes": { "languages": [{ "id": "sql", "extensions": [".sql", ".dsql"], "aliases": ["MS SQL", "T-SQL"], "configuration": "./language-configuration.json" }], "grammars": [{ "language": "sql", "scopeName": "source.sql", "path": "./syntaxes/sql.tmLanguage.json" }] }, "repository": { "type": "git", "url": "https://github.com/microsoft/vscode.git" } }, "packageNLS": { "displayName": "SQL Language Basics", "description": "Provides syntax highlighting and bracket matching in SQL files." } }, { "extensionPath": "swift", "packageJSON": { "name": "swift", "displayName": "%displayName%", "description": "%description%", "version": "1.0.0", "publisher": "vscode", "license": "MIT", "engines": { "vscode": "*" }, "scripts": { "update-grammar": "node ../node_modules/vscode-grammar-updater/bin jtbandes/swift-tmlanguage Swift.tmLanguage.json ./syntaxes/swift.tmLanguage.json" }, "categories": ["Programming Languages"], "contributes": { "languages": [{ "id": "swift", "aliases": ["Swift", "swift"], "extensions": [".swift"], "configuration": "./language-configuration.json" }], "grammars": [{ "language": "swift", "scopeName": "source.swift", "path": "./syntaxes/swift.tmLanguage.json" }], "snippets": [{ "language": "swift", "path": "./snippets/swift.code-snippets" }] }, "repository": { "type": "git", "url": "https://github.com/microsoft/vscode.git" } }, "packageNLS": { "displayName": "Swift Language Basics", "description": "Provides snippets, syntax highlighting and bracket matching in Swift files." } }, { "extensionPath": "theme-abyss", "packageJSON": { "name": "theme-abyss", "displayName": "%displayName%", "description": "%description%", "version": "1.0.0", "publisher": "vscode", "license": "MIT", "engines": { "vscode": "*" }, "categories": ["Themes"], "contributes": { "themes": [{ "id": "Abyss", "label": "%themeLabel%", "uiTheme": "vs-dark", "path": "./themes/abyss-color-theme.json" }] }, "repository": { "type": "git", "url": "https://github.com/microsoft/vscode.git" } }, "packageNLS": { "displayName": "Abyss Theme", "description": "Abyss theme for Visual Studio Code", "themeLabel": "Abyss" } }, { "extensionPath": "theme-defaults", "packageJSON": { "name": "theme-defaults", "displayName": "%displayName%", "description": "%description%", "categories": ["Themes"], "version": "1.0.0", "publisher": "vscode", "license": "MIT", "engines": { "vscode": "*" }, "contributes": { "themes": [{ "id": "Default Dark+", "label": "%darkPlusColorThemeLabel%", "uiTheme": "vs-dark", "path": "./themes/dark_plus.json" }, { "id": "Default Dark Modern", "label": "%darkModernThemeLabel%", "uiTheme": "vs-dark", "path": "./themes/dark_modern.json" }, { "id": "Default Light+", "label": "%lightPlusColorThemeLabel%", "uiTheme": "vs", "path": "./themes/light_plus.json" }, { "id": "Default Light Modern", "label": "%lightModernThemeLabel%", "uiTheme": "vs", "path": "./themes/light_modern.json" }, { "id": "Visual Studio Dark", "label": "%darkColorThemeLabel%", "uiTheme": "vs-dark", "path": "./themes/dark_vs.json" }, { "id": "Visual Studio Light", "label": "%lightColorThemeLabel%", "uiTheme": "vs", "path": "./themes/light_vs.json" }, { "id": "Default High Contrast", "label": "%hcColorThemeLabel%", "uiTheme": "hc-black", "path": "./themes/hc_black.json" }, { "id": "Default High Contrast Light", "label": "%lightHcColorThemeLabel%", "uiTheme": "hc-light", "path": "./themes/hc_light.json" }], "iconThemes": [{ "id": "vs-minimal", "label": "%minimalIconThemeLabel%", "path": "./fileicons/vs_minimal-icon-theme.json" }] }, "repository": { "type": "git", "url": "https://github.com/microsoft/vscode.git" } }, "packageNLS": { "displayName": "Default Themes", "description": "The default Visual Studio light and dark themes", "darkPlusColorThemeLabel": "Dark+", "darkModernThemeLabel": "Dark Modern", "lightPlusColorThemeLabel": "Light+", "lightModernThemeLabel": "Light Modern", "darkColorThemeLabel": "Dark (Visual Studio)", "lightColorThemeLabel": "Light (Visual Studio)", "hcColorThemeLabel": "Dark High Contrast", "lightHcColorThemeLabel": "Light High Contrast", "minimalIconThemeLabel": "Minimal (Visual Studio Code)" } }, { "extensionPath": "theme-kimbie-dark", "packageJSON": { "name": "theme-kimbie-dark", "displayName": "%displayName%", "description": "%description%", "version": "1.0.0", "publisher": "vscode", "license": "MIT", "engines": { "vscode": "*" }, "categories": ["Themes"], "contributes": { "themes": [{ "id": "Kimbie Dark", "label": "%themeLabel%", "uiTheme": "vs-dark", "path": "./themes/kimbie-dark-color-theme.json" }] }, "repository": { "type": "git", "url": "https://github.com/microsoft/vscode.git" } }, "packageNLS": { "displayName": "Kimbie Dark Theme", "description": "Kimbie dark theme for Visual Studio Code", "themeLabel": "Kimbie Dark" } }, { "extensionPath": "theme-monokai", "packageJSON": { "name": "theme-monokai", "displayName": "%displayName%", "description": "%description%", "version": "1.0.0", "publisher": "vscode", "license": "MIT", "engines": { "vscode": "*" }, "categories": ["Themes"], "contributes": { "themes": [{ "id": "Monokai", "label": "%themeLabel%", "uiTheme": "vs-dark", "path": "./themes/monokai-color-theme.json" }] }, "repository": { "type": "git", "url": "https://github.com/microsoft/vscode.git" } }, "packageNLS": { "displayName": "Monokai Theme", "description": "Monokai theme for Visual Studio Code", "themeLabel": "Monokai" } }, { "extensionPath": "theme-monokai-dimmed", "packageJSON": { "name": "theme-monokai-dimmed", "displayName": "%displayName%", "description": "%description%", "version": "1.0.0", "publisher": "vscode", "license": "MIT", "engines": { "vscode": "*" }, "categories": ["Themes"], "contributes": { "themes": [{ "id": "Monokai Dimmed", "label": "%themeLabel%", "uiTheme": "vs-dark", "path": "./themes/dimmed-monokai-color-theme.json" }] }, "repository": { "type": "git", "url": "https://github.com/microsoft/vscode.git" } }, "packageNLS": { "displayName": "Monokai Dimmed Theme", "description": "Monokai dimmed theme for Visual Studio Code", "themeLabel": "Monokai Dimmed" } }, { "extensionPath": "theme-quietlight", "packageJSON": { "name": "theme-quietlight", "displayName": "%displayName%", "description": "%description%", "version": "1.0.0", "publisher": "vscode", "license": "MIT", "engines": { "vscode": "*" }, "categories": ["Themes"], "contributes": { "themes": [{ "id": "Quiet Light", "label": "%themeLabel%", "uiTheme": "vs", "path": "./themes/quietlight-color-theme.json" }] }, "repository": { "type": "git", "url": "https://github.com/microsoft/vscode.git" } }, "packageNLS": { "displayName": "Quiet Light Theme", "description": "Quiet light theme for Visual Studio Code", "themeLabel": "Quiet Light" } }, { "extensionPath": "theme-red", "packageJSON": { "name": "theme-red", "displayName": "%displayName%", "description": "%description%", "version": "1.0.0", "publisher": "vscode", "license": "MIT", "engines": { "vscode": "*" }, "categories": ["Themes"], "contributes": { "themes": [{ "id": "Red", "label": "%themeLabel%", "uiTheme": "vs-dark", "path": "./themes/Red-color-theme.json" }] }, "repository": { "type": "git", "url": "https://github.com/microsoft/vscode.git" } }, "packageNLS": { "displayName": "Red Theme", "description": "Red theme for Visual Studio Code", "themeLabel": "Red" } }, { "extensionPath": "theme-seti", "packageJSON": { "name": "vscode-theme-seti", "private": true, "version": "1.0.0", "displayName": "%displayName%", "description": "%description%", "publisher": "vscode", "license": "MIT", "icon": "icons/seti-circular-128x128.png", "scripts": { "update": "node ./build/update-icon-theme.js" }, "engines": { "vscode": "*" }, "categories": ["Themes"], "contributes": { "iconThemes": [{ "id": "vs-seti", "label": "%themeLabel%", "path": "./icons/vs-seti-icon-theme.json" }] }, "repository": { "type": "git", "url": "https://github.com/microsoft/vscode.git" } }, "packageNLS": { "displayName": "Seti File Icon Theme", "description": "A file icon theme made out of the Seti UI file icons", "themeLabel": "Seti (Visual Studio Code)" }, "readmePath": "theme-seti/README.md" }, { "extensionPath": "theme-solarized-dark", "packageJSON": { "name": "theme-solarized-dark", "displayName": "%displayName%", "description": "%description%", "version": "1.0.0", "publisher": "vscode", "license": "MIT", "engines": { "vscode": "*" }, "categories": ["Themes"], "contributes": { "themes": [{ "id": "Solarized Dark", "label": "%themeLabel%", "uiTheme": "vs-dark", "path": "./themes/solarized-dark-color-theme.json" }] }, "repository": { "type": "git", "url": "https://github.com/microsoft/vscode.git" } }, "packageNLS": { "displayName": "Solarized Dark Theme", "description": "Solarized dark theme for Visual Studio Code", "themeLabel": "Solarized Dark" } }, { "extensionPath": "theme-solarized-light", "packageJSON": { "name": "theme-solarized-light", "displayName": "%displayName%", "description": "%description%", "version": "1.0.0", "publisher": "vscode", "license": "MIT", "engines": { "vscode": "*" }, "categories": ["Themes"], "contributes": { "themes": [{ "id": "Solarized Light", "label": "%themeLabel%", "uiTheme": "vs", "path": "./themes/solarized-light-color-theme.json" }] }, "repository": { "type": "git", "url": "https://github.com/microsoft/vscode.git" } }, "packageNLS": { "displayName": "Solarized Light Theme", "description": "Solarized light theme for Visual Studio Code", "themeLabel": "Solarized Light" } }, { "extensionPath": "theme-tomorrow-night-blue", "packageJSON": { "name": "theme-tomorrow-night-blue", "displayName": "%displayName%", "description": "%description%", "version": "1.0.0", "publisher": "vscode", "license": "MIT", "engines": { "vscode": "*" }, "categories": ["Themes"], "contributes": { "themes": [{ "id": "Tomorrow Night Blue", "label": "%themeLabel%", "uiTheme": "vs-dark", "path": "./themes/tomorrow-night-blue-color-theme.json" }] }, "repository": { "type": "git", "url": "https://github.com/microsoft/vscode.git" } }, "packageNLS": { "displayName": "Tomorrow Night Blue Theme", "description": "Tomorrow night blue theme for Visual Studio Code", "themeLabel": "Tomorrow Night Blue" } }, { "extensionPath": "typescript-basics", "packageJSON": { "name": "typescript", "description": "%description%", "displayName": "%displayName%", "version": "1.0.0", "author": "vscode", "publisher": "vscode", "license": "MIT", "engines": { "vscode": "*" }, "scripts": { "update-grammar": "node ./build/update-grammars.mjs" }, "categories": ["Programming Languages"], "contributes": { "languages": [{ "id": "typescript", "aliases": ["TypeScript", "ts", "typescript"], "extensions": [".ts", ".cts", ".mts"], "configuration": "./language-configuration.json" }, { "id": "typescriptreact", "aliases": ["TypeScript JSX", "TypeScript React", "tsx"], "extensions": [".tsx"], "configuration": "./language-configuration.json" }, { "id": "jsonc", "filenames": ["tsconfig.json", "jsconfig.json"], "filenamePatterns": ["tsconfig.*.json", "jsconfig.*.json", "tsconfig-*.json", "jsconfig-*.json"] }, { "id": "json", "extensions": [".tsbuildinfo"] }], "grammars": [{ "language": "typescript", "scopeName": "source.ts", "path": "./syntaxes/TypeScript.tmLanguage.json", "unbalancedBracketScopes": ["keyword.operator.relational", "storage.type.function.arrow", "keyword.operator.bitwise.shift", "meta.brace.angle", "punctuation.definition.tag", "keyword.operator.assignment.compound.bitwise.ts"], "tokenTypes": { "meta.template.expression": "other", "meta.template.expression string": "string", "meta.template.expression comment": "comment", "entity.name.type.instance.jsdoc": "other", "entity.name.function.tagged-template": "other", "meta.import string.quoted": "other", "variable.other.jsdoc": "other" } }, { "language": "typescriptreact", "scopeName": "source.tsx", "path": "./syntaxes/TypeScriptReact.tmLanguage.json", "unbalancedBracketScopes": ["keyword.operator.relational", "storage.type.function.arrow", "keyword.operator.bitwise.shift", "punctuation.definition.tag", "keyword.operator.assignment.compound.bitwise.ts"], "embeddedLanguages": { "meta.tag.tsx": "jsx-tags", "meta.tag.without-attributes.tsx": "jsx-tags", "meta.tag.attributes.tsx": "typescriptreact", "meta.embedded.expression.tsx": "typescriptreact" }, "tokenTypes": { "meta.template.expression": "other", "meta.template.expression string": "string", "meta.template.expression comment": "comment", "entity.name.type.instance.jsdoc": "other", "entity.name.function.tagged-template": "other", "meta.import string.quoted": "other", "variable.other.jsdoc": "other" } }, { "scopeName": "documentation.injection.ts", "path": "./syntaxes/jsdoc.ts.injection.tmLanguage.json", "injectTo": ["source.ts", "source.tsx"] }, { "scopeName": "documentation.injection.js.jsx", "path": "./syntaxes/jsdoc.js.injection.tmLanguage.json", "injectTo": ["source.js", "source.js.jsx"] }], "semanticTokenScopes": [{ "language": "typescript", "scopes": { "property": ["variable.other.property.ts"], "property.readonly": ["variable.other.constant.property.ts"], "variable": ["variable.other.readwrite.ts"], "variable.readonly": ["variable.other.constant.object.ts"], "function": ["entity.name.function.ts"], "namespace": ["entity.name.type.module.ts"], "variable.defaultLibrary": ["support.variable.ts"], "function.defaultLibrary": ["support.function.ts"] } }, { "language": "typescriptreact", "scopes": { "property": ["variable.other.property.tsx"], "property.readonly": ["variable.other.constant.property.tsx"], "variable": ["variable.other.readwrite.tsx"], "variable.readonly": ["variable.other.constant.object.tsx"], "function": ["entity.name.function.tsx"], "namespace": ["entity.name.type.module.tsx"], "variable.defaultLibrary": ["support.variable.tsx"], "function.defaultLibrary": ["support.function.tsx"] } }], "snippets": [{ "language": "typescript", "path": "./snippets/typescript.code-snippets" }, { "language": "typescriptreact", "path": "./snippets/typescript.code-snippets" }] }, "repository": { "type": "git", "url": "https://github.com/microsoft/vscode.git" } }, "packageNLS": { "displayName": "TypeScript Language Basics", "description": "Provides snippets, syntax highlighting, bracket matching and folding in TypeScript files." } }, { "extensionPath": "typescript-language-features", "packageJSON": { "name": "typescript-language-features", "description": "%description%", "displayName": "%displayName%", "version": "1.0.0", "author": "vscode", "publisher": "vscode", "license": "MIT", "aiKey": "0c6ae279ed8443289764825290e4f9e2-1a736e7c-1324-4338-be46-fc2a58ae4d14-7255", "enabledApiProposals": ["workspaceTrust", "multiDocumentHighlightProvider", "mappedEditsProvider", "codeActionAI", "codeActionRanges", "documentPaste", "editorHoverVerbosityLevel"], "capabilities": { "virtualWorkspaces": { "supported": "limited", "description": "%virtualWorkspaces%" }, "untrustedWorkspaces": { "supported": "limited", "description": "%workspaceTrust%", "restrictedConfigurations": ["typescript.tsdk", "typescript.tsserver.pluginPaths", "typescript.npm", "typescript.tsserver.nodePath"] } }, "engines": { "vscode": "^1.30.0" }, "icon": "media/icon.png", "categories": ["Programming Languages"], "activationEvents": ["onLanguage:javascript", "onLanguage:javascriptreact", "onLanguage:typescript", "onLanguage:typescriptreact", "onLanguage:jsx-tags", "onCommand:typescript.tsserverRequest", "onCommand:_typescript.configurePlugin", "onCommand:_typescript.learnMoreAboutRefactorings", "onCommand:typescript.fileReferences", "onTaskType:typescript", "onLanguage:jsonc", "onWalkthrough:nodejsWelcome"], "main": "./dist/extension", "browser": "./dist/browser/extension", "contributes": { "jsonValidation": [{ "fileMatch": "package.json", "url": "./schemas/package.schema.json" }, { "fileMatch": "tsconfig.json", "url": "https://json.schemastore.org/tsconfig" }, { "fileMatch": "tsconfig.json", "url": "./schemas/tsconfig.schema.json" }, { "fileMatch": "tsconfig.*.json", "url": "https://json.schemastore.org/tsconfig" }, { "fileMatch": "tsconfig-*.json", "url": "./schemas/tsconfig.schema.json" }, { "fileMatch": "tsconfig-*.json", "url": "https://json.schemastore.org/tsconfig" }, { "fileMatch": "tsconfig.*.json", "url": "./schemas/tsconfig.schema.json" }, { "fileMatch": "typings.json", "url": "https://json.schemastore.org/typings" }, { "fileMatch": ".bowerrc", "url": "https://json.schemastore.org/bowerrc" }, { "fileMatch": ".babelrc", "url": "https://json.schemastore.org/babelrc" }, { "fileMatch": ".babelrc.json", "url": "https://json.schemastore.org/babelrc" }, { "fileMatch": "babel.config.json", "url": "https://json.schemastore.org/babelrc" }, { "fileMatch": "jsconfig.json", "url": "https://json.schemastore.org/jsconfig" }, { "fileMatch": "jsconfig.json", "url": "./schemas/jsconfig.schema.json" }, { "fileMatch": "jsconfig.*.json", "url": "https://json.schemastore.org/jsconfig" }, { "fileMatch": "jsconfig.*.json", "url": "./schemas/jsconfig.schema.json" }, { "fileMatch": ".swcrc", "url": "https://swc.rs/schema.json" }, { "fileMatch": "typedoc.json", "url": "https://typedoc.org/schema.json" }], "configuration": { "type": "object", "title": "%configuration.typescript%", "order": 20, "properties": { "typescript.tsdk": { "type": "string", "markdownDescription": "%typescript.tsdk.desc%", "scope": "window" }, "typescript.disableAutomaticTypeAcquisition": { "type": "boolean", "default": false, "markdownDescription": "%typescript.disableAutomaticTypeAcquisition%", "scope": "window", "tags": ["usesOnlineServices"] }, "typescript.enablePromptUseWorkspaceTsdk": { "type": "boolean", "default": false, "description": "%typescript.enablePromptUseWorkspaceTsdk%", "scope": "window" }, "typescript.npm": { "type": "string", "markdownDescription": "%typescript.npm%", "scope": "machine" }, "typescript.check.npmIsInstalled": { "type": "boolean", "default": true, "markdownDescription": "%typescript.check.npmIsInstalled%", "scope": "window" }, "javascript.referencesCodeLens.enabled": { "type": "boolean", "default": false, "description": "%javascript.referencesCodeLens.enabled%", "scope": "window" }, "javascript.referencesCodeLens.showOnAllFunctions": { "type": "boolean", "default": false, "description": "%javascript.referencesCodeLens.showOnAllFunctions%", "scope": "window" }, "typescript.referencesCodeLens.enabled": { "type": "boolean", "default": false, "description": "%typescript.referencesCodeLens.enabled%", "scope": "window" }, "typescript.referencesCodeLens.showOnAllFunctions": { "type": "boolean", "default": false, "description": "%typescript.referencesCodeLens.showOnAllFunctions%", "scope": "window" }, "typescript.implementationsCodeLens.enabled": { "type": "boolean", "default": false, "description": "%typescript.implementationsCodeLens.enabled%", "scope": "window" }, "typescript.implementationsCodeLens.showOnInterfaceMethods": { "type": "boolean", "default": false, "description": "%typescript.implementationsCodeLens.showOnInterfaceMethods%", "scope": "window" }, "typescript.tsserver.enableTracing": { "type": "boolean", "default": false, "description": "%typescript.tsserver.enableTracing%", "scope": "window" }, "typescript.tsserver.log": { "type": "string", "enum": ["off", "terse", "normal", "verbose"], "default": "off", "description": "%typescript.tsserver.log%", "scope": "window" }, "typescript.tsserver.pluginPaths": { "type": "array", "items": { "type": "string", "description": "%typescript.tsserver.pluginPaths.item%" }, "default": [], "description": "%typescript.tsserver.pluginPaths%", "scope": "machine" }, "javascript.suggest.completeFunctionCalls": { "type": "boolean", "default": false, "description": "%configuration.suggest.completeFunctionCalls%", "scope": "resource" }, "typescript.suggest.completeFunctionCalls": { "type": "boolean", "default": false, "description": "%configuration.suggest.completeFunctionCalls%", "scope": "resource" }, "javascript.suggest.includeAutomaticOptionalChainCompletions": { "type": "boolean", "default": true, "description": "%configuration.suggest.includeAutomaticOptionalChainCompletions%", "scope": "resource" }, "typescript.suggest.includeAutomaticOptionalChainCompletions": { "type": "boolean", "default": true, "description": "%configuration.suggest.includeAutomaticOptionalChainCompletions%", "scope": "resource" }, "typescript.inlayHints.parameterNames.enabled": { "type": "string", "enum": ["none", "literals", "all"], "enumDescriptions": ["%inlayHints.parameterNames.none%", "%inlayHints.parameterNames.literals%", "%inlayHints.parameterNames.all%"], "default": "none", "markdownDescription": "%configuration.inlayHints.parameterNames.enabled%", "scope": "resource" }, "typescript.inlayHints.parameterNames.suppressWhenArgumentMatchesName": { "type": "boolean", "default": true, "markdownDescription": "%configuration.inlayHints.parameterNames.suppressWhenArgumentMatchesName%", "scope": "resource" }, "typescript.inlayHints.parameterTypes.enabled": { "type": "boolean", "default": false, "markdownDescription": "%configuration.inlayHints.parameterTypes.enabled%", "scope": "resource" }, "typescript.inlayHints.variableTypes.enabled": { "type": "boolean", "default": false, "markdownDescription": "%configuration.inlayHints.variableTypes.enabled%", "scope": "resource" }, "typescript.inlayHints.variableTypes.suppressWhenTypeMatchesName": { "type": "boolean", "default": true, "markdownDescription": "%configuration.inlayHints.variableTypes.suppressWhenTypeMatchesName%", "scope": "resource" }, "typescript.inlayHints.propertyDeclarationTypes.enabled": { "type": "boolean", "default": false, "markdownDescription": "%configuration.inlayHints.propertyDeclarationTypes.enabled%", "scope": "resource" }, "typescript.inlayHints.functionLikeReturnTypes.enabled": { "type": "boolean", "default": false, "markdownDescription": "%configuration.inlayHints.functionLikeReturnTypes.enabled%", "scope": "resource" }, "typescript.inlayHints.enumMemberValues.enabled": { "type": "boolean", "default": false, "markdownDescription": "%configuration.inlayHints.enumMemberValues.enabled%", "scope": "resource" }, "javascript.inlayHints.parameterNames.enabled": { "type": "string", "enum": ["none", "literals", "all"], "enumDescriptions": ["%inlayHints.parameterNames.none%", "%inlayHints.parameterNames.literals%", "%inlayHints.parameterNames.all%"], "default": "none", "markdownDescription": "%configuration.inlayHints.parameterNames.enabled%", "scope": "resource" }, "javascript.inlayHints.parameterNames.suppressWhenArgumentMatchesName": { "type": "boolean", "default": true, "markdownDescription": "%configuration.inlayHints.parameterNames.suppressWhenArgumentMatchesName%", "scope": "resource" }, "javascript.inlayHints.parameterTypes.enabled": { "type": "boolean", "default": false, "markdownDescription": "%configuration.inlayHints.parameterTypes.enabled%", "scope": "resource" }, "javascript.inlayHints.variableTypes.enabled": { "type": "boolean", "default": false, "markdownDescription": "%configuration.inlayHints.variableTypes.enabled%", "scope": "resource" }, "javascript.inlayHints.variableTypes.suppressWhenTypeMatchesName": { "type": "boolean", "default": true, "markdownDescription": "%configuration.inlayHints.variableTypes.suppressWhenTypeMatchesName%", "scope": "resource" }, "javascript.inlayHints.propertyDeclarationTypes.enabled": { "type": "boolean", "default": false, "markdownDescription": "%configuration.inlayHints.propertyDeclarationTypes.enabled%", "scope": "resource" }, "javascript.inlayHints.functionLikeReturnTypes.enabled": { "type": "boolean", "default": false, "markdownDescription": "%configuration.inlayHints.functionLikeReturnTypes.enabled%", "scope": "resource" }, "javascript.inlayHints.enumMemberValues.enabled": { "type": "boolean", "default": false, "markdownDescription": "%configuration.inlayHints.enumMemberValues.enabled%", "scope": "resource" }, "javascript.suggest.includeCompletionsForImportStatements": { "type": "boolean", "default": true, "description": "%configuration.suggest.includeCompletionsForImportStatements%", "scope": "resource" }, "typescript.suggest.includeCompletionsForImportStatements": { "type": "boolean", "default": true, "description": "%configuration.suggest.includeCompletionsForImportStatements%", "scope": "resource" }, "typescript.reportStyleChecksAsWarnings": { "type": "boolean", "default": true, "description": "%typescript.reportStyleChecksAsWarnings%", "scope": "window" }, "typescript.validate.enable": { "type": "boolean", "default": true, "description": "%typescript.validate.enable%", "scope": "window" }, "typescript.format.enable": { "type": "boolean", "default": true, "description": "%typescript.format.enable%", "scope": "window" }, "typescript.format.insertSpaceAfterCommaDelimiter": { "type": "boolean", "default": true, "description": "%format.insertSpaceAfterCommaDelimiter%", "scope": "resource" }, "typescript.format.insertSpaceAfterConstructor": { "type": "boolean", "default": false, "description": "%format.insertSpaceAfterConstructor%", "scope": "resource" }, "typescript.format.insertSpaceAfterSemicolonInForStatements": { "type": "boolean", "default": true, "description": "%format.insertSpaceAfterSemicolonInForStatements%", "scope": "resource" }, "typescript.format.insertSpaceBeforeAndAfterBinaryOperators": { "type": "boolean", "default": true, "description": "%format.insertSpaceBeforeAndAfterBinaryOperators%", "scope": "resource" }, "typescript.format.insertSpaceAfterKeywordsInControlFlowStatements": { "type": "boolean", "default": true, "description": "%format.insertSpaceAfterKeywordsInControlFlowStatements%", "scope": "resource" }, "typescript.format.insertSpaceAfterFunctionKeywordForAnonymousFunctions": { "type": "boolean", "default": true, "description": "%format.insertSpaceAfterFunctionKeywordForAnonymousFunctions%", "scope": "resource" }, "typescript.format.insertSpaceBeforeFunctionParenthesis": { "type": "boolean", "default": false, "description": "%format.insertSpaceBeforeFunctionParenthesis%", "scope": "resource" }, "typescript.format.insertSpaceAfterOpeningAndBeforeClosingNonemptyParenthesis": { "type": "boolean", "default": false, "description": "%format.insertSpaceAfterOpeningAndBeforeClosingNonemptyParenthesis%", "scope": "resource" }, "typescript.format.insertSpaceAfterOpeningAndBeforeClosingNonemptyBrackets": { "type": "boolean", "default": false, "description": "%format.insertSpaceAfterOpeningAndBeforeClosingNonemptyBrackets%", "scope": "resource" }, "typescript.format.insertSpaceAfterOpeningAndBeforeClosingNonemptyBraces": { "type": "boolean", "default": true, "description": "%format.insertSpaceAfterOpeningAndBeforeClosingNonemptyBraces%", "scope": "resource" }, "typescript.format.insertSpaceAfterOpeningAndBeforeClosingEmptyBraces": { "type": "boolean", "default": true, "description": "%format.insertSpaceAfterOpeningAndBeforeClosingEmptyBraces%", "scope": "resource" }, "typescript.format.insertSpaceAfterOpeningAndBeforeClosingTemplateStringBraces": { "type": "boolean", "default": false, "description": "%format.insertSpaceAfterOpeningAndBeforeClosingTemplateStringBraces%", "scope": "resource" }, "typescript.format.insertSpaceAfterOpeningAndBeforeClosingJsxExpressionBraces": { "type": "boolean", "default": false, "description": "%format.insertSpaceAfterOpeningAndBeforeClosingJsxExpressionBraces%", "scope": "resource" }, "typescript.format.insertSpaceAfterTypeAssertion": { "type": "boolean", "default": false, "description": "%format.insertSpaceAfterTypeAssertion%", "scope": "resource" }, "typescript.format.placeOpenBraceOnNewLineForFunctions": { "type": "boolean", "default": false, "description": "%format.placeOpenBraceOnNewLineForFunctions%", "scope": "resource" }, "typescript.format.placeOpenBraceOnNewLineForControlBlocks": { "type": "boolean", "default": false, "description": "%format.placeOpenBraceOnNewLineForControlBlocks%", "scope": "resource" }, "typescript.format.semicolons": { "type": "string", "default": "ignore", "description": "%format.semicolons%", "scope": "resource", "enum": ["ignore", "insert", "remove"], "enumDescriptions": ["%format.semicolons.ignore%", "%format.semicolons.insert%", "%format.semicolons.remove%"] }, "typescript.format.indentSwitchCase": { "type": "boolean", "default": true, "description": "%format.indentSwitchCase%", "scope": "resource" }, "javascript.validate.enable": { "type": "boolean", "default": true, "description": "%javascript.validate.enable%", "scope": "window" }, "javascript.format.enable": { "type": "boolean", "default": true, "description": "%javascript.format.enable%", "scope": "window" }, "javascript.format.insertSpaceAfterCommaDelimiter": { "type": "boolean", "default": true, "description": "%format.insertSpaceAfterCommaDelimiter%", "scope": "resource" }, "javascript.format.insertSpaceAfterConstructor": { "type": "boolean", "default": false, "description": "%format.insertSpaceAfterConstructor%", "scope": "resource" }, "javascript.format.insertSpaceAfterSemicolonInForStatements": { "type": "boolean", "default": true, "description": "%format.insertSpaceAfterSemicolonInForStatements%", "scope": "resource" }, "javascript.format.insertSpaceBeforeAndAfterBinaryOperators": { "type": "boolean", "default": true, "description": "%format.insertSpaceBeforeAndAfterBinaryOperators%", "scope": "resource" }, "javascript.format.insertSpaceAfterKeywordsInControlFlowStatements": { "type": "boolean", "default": true, "description": "%format.insertSpaceAfterKeywordsInControlFlowStatements%", "scope": "resource" }, "javascript.format.insertSpaceAfterFunctionKeywordForAnonymousFunctions": { "type": "boolean", "default": true, "description": "%format.insertSpaceAfterFunctionKeywordForAnonymousFunctions%", "scope": "resource" }, "javascript.format.insertSpaceBeforeFunctionParenthesis": { "type": "boolean", "default": false, "description": "%format.insertSpaceBeforeFunctionParenthesis%", "scope": "resource" }, "javascript.format.insertSpaceAfterOpeningAndBeforeClosingNonemptyParenthesis": { "type": "boolean", "default": false, "description": "%format.insertSpaceAfterOpeningAndBeforeClosingNonemptyParenthesis%", "scope": "resource" }, "javascript.format.insertSpaceAfterOpeningAndBeforeClosingNonemptyBrackets": { "type": "boolean", "default": false, "description": "%format.insertSpaceAfterOpeningAndBeforeClosingNonemptyBrackets%", "scope": "resource" }, "javascript.format.insertSpaceAfterOpeningAndBeforeClosingNonemptyBraces": { "type": "boolean", "default": true, "description": "%format.insertSpaceAfterOpeningAndBeforeClosingNonemptyBraces%", "scope": "resource" }, "javascript.format.insertSpaceAfterOpeningAndBeforeClosingEmptyBraces": { "type": "boolean", "default": true, "description": "%format.insertSpaceAfterOpeningAndBeforeClosingEmptyBraces%", "scope": "resource" }, "javascript.format.insertSpaceAfterOpeningAndBeforeClosingTemplateStringBraces": { "type": "boolean", "default": false, "description": "%format.insertSpaceAfterOpeningAndBeforeClosingTemplateStringBraces%", "scope": "resource" }, "javascript.format.insertSpaceAfterOpeningAndBeforeClosingJsxExpressionBraces": { "type": "boolean", "default": false, "description": "%format.insertSpaceAfterOpeningAndBeforeClosingJsxExpressionBraces%", "scope": "resource" }, "javascript.format.placeOpenBraceOnNewLineForFunctions": { "type": "boolean", "default": false, "description": "%format.placeOpenBraceOnNewLineForFunctions%", "scope": "resource" }, "javascript.format.placeOpenBraceOnNewLineForControlBlocks": { "type": "boolean", "default": false, "description": "%format.placeOpenBraceOnNewLineForControlBlocks%", "scope": "resource" }, "javascript.format.semicolons": { "type": "string", "default": "ignore", "description": "%format.semicolons%", "scope": "resource", "enum": ["ignore", "insert", "remove"], "enumDescriptions": ["%format.semicolons.ignore%", "%format.semicolons.insert%", "%format.semicolons.remove%"] }, "js/ts.implicitProjectConfig.module": { "type": "string", "markdownDescription": "%configuration.implicitProjectConfig.module%", "default": "ESNext", "enum": ["CommonJS", "AMD", "System", "UMD", "ES6", "ES2015", "ES2020", "ESNext", "None", "ES2022", "Node12", "NodeNext"], "scope": "window" }, "js/ts.implicitProjectConfig.target": { "type": "string", "default": "ES2022", "markdownDescription": "%configuration.implicitProjectConfig.target%", "enum": ["ES3", "ES5", "ES6", "ES2015", "ES2016", "ES2017", "ES2018", "ES2019", "ES2020", "ES2021", "ES2022", "ES2023", "ES2024", "ESNext"], "scope": "window" }, "javascript.implicitProjectConfig.checkJs": { "type": "boolean", "default": false, "markdownDescription": "%configuration.implicitProjectConfig.checkJs%", "markdownDeprecationMessage": "%configuration.javascript.checkJs.checkJs.deprecation%", "scope": "window" }, "js/ts.implicitProjectConfig.checkJs": { "type": "boolean", "default": false, "markdownDescription": "%configuration.implicitProjectConfig.checkJs%", "scope": "window" }, "javascript.implicitProjectConfig.experimentalDecorators": { "type": "boolean", "default": false, "markdownDescription": "%configuration.implicitProjectConfig.experimentalDecorators%", "markdownDeprecationMessage": "%configuration.javascript.checkJs.experimentalDecorators.deprecation%", "scope": "window" }, "js/ts.implicitProjectConfig.experimentalDecorators": { "type": "boolean", "default": false, "markdownDescription": "%configuration.implicitProjectConfig.experimentalDecorators%", "scope": "window" }, "js/ts.implicitProjectConfig.strictNullChecks": { "type": "boolean", "default": true, "markdownDescription": "%configuration.implicitProjectConfig.strictNullChecks%", "scope": "window" }, "js/ts.implicitProjectConfig.strictFunctionTypes": { "type": "boolean", "default": true, "markdownDescription": "%configuration.implicitProjectConfig.strictFunctionTypes%", "scope": "window" }, "javascript.suggest.names": { "type": "boolean", "default": true, "markdownDescription": "%configuration.suggest.names%", "scope": "resource" }, "typescript.tsc.autoDetect": { "type": "string", "default": "on", "enum": ["on", "off", "build", "watch"], "markdownEnumDescriptions": ["%typescript.tsc.autoDetect.on%", "%typescript.tsc.autoDetect.off%", "%typescript.tsc.autoDetect.build%", "%typescript.tsc.autoDetect.watch%"], "description": "%typescript.tsc.autoDetect%", "scope": "window" }, "javascript.suggest.paths": { "type": "boolean", "default": true, "description": "%configuration.suggest.paths%", "scope": "resource" }, "typescript.suggest.paths": { "type": "boolean", "default": true, "description": "%configuration.suggest.paths%", "scope": "resource" }, "javascript.suggest.autoImports": { "type": "boolean", "default": true, "description": "%configuration.suggest.autoImports%", "scope": "resource" }, "typescript.suggest.autoImports": { "type": "boolean", "default": true, "description": "%configuration.suggest.autoImports%", "scope": "resource" }, "javascript.suggest.completeJSDocs": { "type": "boolean", "default": true, "description": "%configuration.suggest.completeJSDocs%", "scope": "language-overridable" }, "typescript.suggest.completeJSDocs": { "type": "boolean", "default": true, "description": "%configuration.suggest.completeJSDocs%", "scope": "language-overridable" }, "javascript.suggest.jsdoc.generateReturns": { "type": "boolean", "default": true, "markdownDescription": "%configuration.suggest.jsdoc.generateReturns%", "scope": "language-overridable" }, "typescript.suggest.jsdoc.generateReturns": { "type": "boolean", "default": true, "markdownDescription": "%configuration.suggest.jsdoc.generateReturns%", "scope": "language-overridable" }, "typescript.locale": { "type": "string", "default": "auto", "enum": ["auto", "de", "es", "en", "fr", "it", "ja", "ko", "ru", "zh-CN", "zh-TW"], "enumDescriptions": ["%typescript.locale.auto%", "Deutsch", "espa\xF1ol", "English", "fran\xE7ais", "italiano", "\u65E5\u672C\u8A9E", "\uD55C\uAD6D\uC5B4", "\u0440\u0443\u0441\u0441\u043A\u0438\u0439", "\u4E2D\u6587(\u7B80\u4F53)", "\u4E2D\u6587(\u7E41\u9AD4)"], "markdownDescription": "%typescript.locale%", "scope": "window" }, "javascript.suggestionActions.enabled": { "type": "boolean", "default": true, "description": "%javascript.suggestionActions.enabled%", "scope": "resource" }, "typescript.suggestionActions.enabled": { "type": "boolean", "default": true, "description": "%typescript.suggestionActions.enabled%", "scope": "resource" }, "javascript.preferences.quoteStyle": { "type": "string", "enum": ["auto", "single", "double"], "default": "auto", "markdownDescription": "%typescript.preferences.quoteStyle%", "markdownEnumDescriptions": ["%typescript.preferences.quoteStyle.auto%", "%typescript.preferences.quoteStyle.single%", "%typescript.preferences.quoteStyle.double%"], "scope": "language-overridable" }, "typescript.preferences.quoteStyle": { "type": "string", "enum": ["auto", "single", "double"], "default": "auto", "markdownDescription": "%typescript.preferences.quoteStyle%", "markdownEnumDescriptions": ["%typescript.preferences.quoteStyle.auto%", "%typescript.preferences.quoteStyle.single%", "%typescript.preferences.quoteStyle.double%"], "scope": "language-overridable" }, "javascript.preferences.importModuleSpecifier": { "type": "string", "enum": ["shortest", "relative", "non-relative", "project-relative"], "markdownEnumDescriptions": ["%typescript.preferences.importModuleSpecifier.shortest%", "%typescript.preferences.importModuleSpecifier.relative%", "%typescript.preferences.importModuleSpecifier.nonRelative%", "%typescript.preferences.importModuleSpecifier.projectRelative%"], "default": "shortest", "description": "%typescript.preferences.importModuleSpecifier%", "scope": "language-overridable" }, "typescript.preferences.importModuleSpecifier": { "type": "string", "enum": ["shortest", "relative", "non-relative", "project-relative"], "markdownEnumDescriptions": ["%typescript.preferences.importModuleSpecifier.shortest%", "%typescript.preferences.importModuleSpecifier.relative%", "%typescript.preferences.importModuleSpecifier.nonRelative%", "%typescript.preferences.importModuleSpecifier.projectRelative%"], "default": "shortest", "description": "%typescript.preferences.importModuleSpecifier%", "scope": "language-overridable" }, "javascript.preferences.importModuleSpecifierEnding": { "type": "string", "enum": ["auto", "minimal", "index", "js"], "enumItemLabels": [null, null, null, "%typescript.preferences.importModuleSpecifierEnding.label.js%"], "markdownEnumDescriptions": ["%typescript.preferences.importModuleSpecifierEnding.auto%", "%typescript.preferences.importModuleSpecifierEnding.minimal%", "%typescript.preferences.importModuleSpecifierEnding.index%", "%typescript.preferences.importModuleSpecifierEnding.js%"], "default": "auto", "description": "%typescript.preferences.importModuleSpecifierEnding%", "scope": "language-overridable" }, "typescript.preferences.importModuleSpecifierEnding": { "type": "string", "enum": ["auto", "minimal", "index", "js"], "enumItemLabels": [null, null, null, "%typescript.preferences.importModuleSpecifierEnding.label.js%"], "markdownEnumDescriptions": ["%typescript.preferences.importModuleSpecifierEnding.auto%", "%typescript.preferences.importModuleSpecifierEnding.minimal%", "%typescript.preferences.importModuleSpecifierEnding.index%", "%typescript.preferences.importModuleSpecifierEnding.js%"], "default": "auto", "description": "%typescript.preferences.importModuleSpecifierEnding%", "scope": "language-overridable" }, "javascript.preferences.jsxAttributeCompletionStyle": { "type": "string", "enum": ["auto", "braces", "none"], "markdownEnumDescriptions": ["%javascript.preferences.jsxAttributeCompletionStyle.auto%", "%typescript.preferences.jsxAttributeCompletionStyle.braces%", "%typescript.preferences.jsxAttributeCompletionStyle.none%"], "default": "auto", "description": "%typescript.preferences.jsxAttributeCompletionStyle%", "scope": "language-overridable" }, "typescript.preferences.jsxAttributeCompletionStyle": { "type": "string", "enum": ["auto", "braces", "none"], "markdownEnumDescriptions": ["%typescript.preferences.jsxAttributeCompletionStyle.auto%", "%typescript.preferences.jsxAttributeCompletionStyle.braces%", "%typescript.preferences.jsxAttributeCompletionStyle.none%"], "default": "auto", "description": "%typescript.preferences.jsxAttributeCompletionStyle%", "scope": "language-overridable" }, "typescript.preferences.includePackageJsonAutoImports": { "type": "string", "enum": ["auto", "on", "off"], "enumDescriptions": ["%typescript.preferences.includePackageJsonAutoImports.auto%", "%typescript.preferences.includePackageJsonAutoImports.on%", "%typescript.preferences.includePackageJsonAutoImports.off%"], "default": "auto", "markdownDescription": "%typescript.preferences.includePackageJsonAutoImports%", "scope": "window" }, "typescript.preferences.autoImportFileExcludePatterns": { "type": "array", "items": { "type": "string" }, "markdownDescription": "%typescript.preferences.autoImportFileExcludePatterns%", "scope": "resource" }, "javascript.preferences.autoImportFileExcludePatterns": { "type": "array", "items": { "type": "string" }, "markdownDescription": "%typescript.preferences.autoImportFileExcludePatterns%", "scope": "resource" }, "typescript.preferences.autoImportSpecifierExcludeRegexes": { "type": "array", "items": { "type": "string" }, "markdownDescription": "%typescript.preferences.autoImportSpecifierExcludeRegexes%", "scope": "resource" }, "javascript.preferences.autoImportSpecifierExcludeRegexes": { "type": "array", "items": { "type": "string" }, "markdownDescription": "%typescript.preferences.autoImportSpecifierExcludeRegexes%", "scope": "resource" }, "typescript.preferences.preferTypeOnlyAutoImports": { "type": "boolean", "default": false, "markdownDescription": "%typescript.preferences.preferTypeOnlyAutoImports%", "scope": "resource" }, "javascript.preferences.renameShorthandProperties": { "type": "boolean", "default": true, "description": "%typescript.preferences.useAliasesForRenames%", "deprecationMessage": "%typescript.preferences.renameShorthandProperties.deprecationMessage%", "scope": "language-overridable" }, "typescript.preferences.renameShorthandProperties": { "type": "boolean", "default": true, "description": "%typescript.preferences.useAliasesForRenames%", "deprecationMessage": "%typescript.preferences.renameShorthandProperties.deprecationMessage%", "scope": "language-overridable" }, "javascript.preferences.useAliasesForRenames": { "type": "boolean", "default": true, "description": "%typescript.preferences.useAliasesForRenames%", "scope": "language-overridable" }, "typescript.preferences.useAliasesForRenames": { "type": "boolean", "default": true, "description": "%typescript.preferences.useAliasesForRenames%", "scope": "language-overridable" }, "javascript.preferences.renameMatchingJsxTags": { "type": "boolean", "default": true, "description": "%typescript.preferences.renameMatchingJsxTags%", "scope": "language-overridable" }, "typescript.preferences.renameMatchingJsxTags": { "type": "boolean", "default": true, "description": "%typescript.preferences.renameMatchingJsxTags%", "scope": "language-overridable" }, "typescript.preferences.organizeImports": { "type": "object", "markdownDescription": "%typescript.preferences.organizeImports%", "properties": { "caseSensitivity": { "type": "string", "markdownDescription": "%typescript.preferences.organizeImports.caseSensitivity%", "enum": ["auto", "caseInsensitive", "caseSensitive"], "markdownEnumDescriptions": ["%typescript.preferences.organizeImports.caseSensitivity.auto%", "%typescript.preferences.organizeImports.caseSensitivity.insensitive", "%typescript.preferences.organizeImports.caseSensitivity.sensitive%"], "default": "auto" }, "typeOrder": { "type": "string", "markdownDescription": "%typescript.preferences.organizeImports.typeOrder%", "enum": ["auto", "last", "inline", "first"], "default": "auto", "markdownEnumDescriptions": ["%typescript.preferences.organizeImports.typeOrder.auto%", "%typescript.preferences.organizeImports.typeOrder.last%", "%typescript.preferences.organizeImports.typeOrder.inline%", "%typescript.preferences.organizeImports.typeOrder.first%"] }, "unicodeCollation": { "type": "string", "markdownDescription": "%typescript.preferences.organizeImports.unicodeCollation%", "enum": ["ordinal", "unicode"], "markdownEnumDescriptions": ["%typescript.preferences.organizeImports.unicodeCollation.ordinal%", "%typescript.preferences.organizeImports.unicodeCollation.unicode%"], "default": "ordinal" }, "locale": { "type": "string", "markdownDescription": "%typescript.preferences.organizeImports.locale%" }, "numericCollation": { "type": "boolean", "markdownDescription": "%typescript.preferences.organizeImports.numericCollation%" }, "accentCollation": { "type": "boolean", "markdownDescription": "%typescript.preferences.organizeImports.accentCollation%" }, "caseFirst": { "type": "string", "markdownDescription": "%typescript.preferences.organizeImports.caseFirst%", "enum": ["default", "upper", "lower"], "markdownEnumDescriptions": ["%typescript.preferences.organizeImports.caseFirst.default%", "%typescript.preferences.organizeImports.caseFirst.upper%", "%typescript.preferences.organizeImports.caseFirst.lower%"], "default": "default" } } }, "javascript.preferences.organizeImports": { "type": "object", "markdownDescription": "%typescript.preferences.organizeImports%", "properties": { "caseSensitivity": { "type": "string", "markdownDescription": "%typescript.preferences.organizeImports.caseSensitivity%", "enum": ["auto", "caseInsensitive", "caseSensitive"], "markdownEnumDescriptions": ["%typescript.preferences.organizeImports.caseSensitivity.auto%", "%typescript.preferences.organizeImports.caseSensitivity.insensitive", "%typescript.preferences.organizeImports.caseSensitivity.sensitive%"], "default": "auto" }, "typeOrder": { "type": "string", "markdownDescription": "%typescript.preferences.organizeImports.typeOrder%", "enum": ["auto", "last", "inline", "first"], "default": "auto", "markdownEnumDescriptions": ["%typescript.preferences.organizeImports.typeOrder.auto%", "%typescript.preferences.organizeImports.typeOrder.last%", "%typescript.preferences.organizeImports.typeOrder.inline%", "%typescript.preferences.organizeImports.typeOrder.first%"] }, "unicodeCollation": { "type": "string", "markdownDescription": "%typescript.preferences.organizeImports.unicodeCollation%", "enum": ["ordinal", "unicode"], "markdownEnumDescriptions": ["%typescript.preferences.organizeImports.unicodeCollation.ordinal%", "%typescript.preferences.organizeImports.unicodeCollation.unicode%"], "default": "ordinal" }, "locale": { "type": "string", "markdownDescription": "%typescript.preferences.organizeImports.locale%" }, "numericCollation": { "type": "boolean", "markdownDescription": "%typescript.preferences.organizeImports.numericCollation%" }, "accentCollation": { "type": "boolean", "markdownDescription": "%typescript.preferences.organizeImports.accentCollation%" }, "caseFirst": { "type": "string", "markdownDescription": "%typescript.preferences.organizeImports.caseFirst%", "enum": ["default", "upper", "lower"], "markdownEnumDescriptions": ["%typescript.preferences.organizeImports.caseFirst.default%", "%typescript.preferences.organizeImports.caseFirst.upper%", "%typescript.preferences.organizeImports.caseFirst.lower%"], "default": "default" } } }, "typescript.updateImportsOnFileMove.enabled": { "type": "string", "enum": ["prompt", "always", "never"], "markdownEnumDescriptions": ["%typescript.updateImportsOnFileMove.enabled.prompt%", "%typescript.updateImportsOnFileMove.enabled.always%", "%typescript.updateImportsOnFileMove.enabled.never%"], "default": "prompt", "description": "%typescript.updateImportsOnFileMove.enabled%", "scope": "resource" }, "javascript.updateImportsOnFileMove.enabled": { "type": "string", "enum": ["prompt", "always", "never"], "markdownEnumDescriptions": ["%typescript.updateImportsOnFileMove.enabled.prompt%", "%typescript.updateImportsOnFileMove.enabled.always%", "%typescript.updateImportsOnFileMove.enabled.never%"], "default": "prompt", "description": "%typescript.updateImportsOnFileMove.enabled%", "scope": "resource" }, "typescript.autoClosingTags": { "type": "boolean", "default": true, "description": "%typescript.autoClosingTags%", "scope": "language-overridable" }, "javascript.autoClosingTags": { "type": "boolean", "default": true, "description": "%typescript.autoClosingTags%", "scope": "language-overridable" }, "javascript.suggest.enabled": { "type": "boolean", "default": true, "description": "%typescript.suggest.enabled%", "scope": "language-overridable" }, "typescript.suggest.enabled": { "type": "boolean", "default": true, "description": "%typescript.suggest.enabled%", "scope": "language-overridable" }, "typescript.surveys.enabled": { "type": "boolean", "default": true, "description": "%configuration.surveys.enabled%", "scope": "window" }, "typescript.tsserver.useSeparateSyntaxServer": { "type": "boolean", "default": true, "description": "%configuration.tsserver.useSeparateSyntaxServer%", "markdownDeprecationMessage": "%configuration.tsserver.useSeparateSyntaxServer.deprecation%", "scope": "window" }, "typescript.tsserver.useSyntaxServer": { "type": "string", "scope": "window", "description": "%configuration.tsserver.useSyntaxServer%", "default": "auto", "enum": ["always", "never", "auto"], "enumDescriptions": ["%configuration.tsserver.useSyntaxServer.always%", "%configuration.tsserver.useSyntaxServer.never%", "%configuration.tsserver.useSyntaxServer.auto%"] }, "typescript.tsserver.maxTsServerMemory": { "type": "number", "default": 3072, "markdownDescription": "%configuration.tsserver.maxTsServerMemory%", "scope": "window" }, "typescript.tsserver.experimental.enableProjectDiagnostics": { "type": "boolean", "default": false, "description": "%configuration.tsserver.experimental.enableProjectDiagnostics%", "scope": "window", "tags": ["experimental"] }, "typescript.tsserver.experimental.useVsCodeWatcher": { "type": "boolean", "description": "%configuration.tsserver.useVsCodeWatcher%", "deprecationMessage": "%configuration.tsserver.useVsCodeWatcher.deprecation%", "default": true }, "typescript.tsserver.watchOptions": { "description": "%configuration.tsserver.watchOptions%", "scope": "window", "default": "vscode", "oneOf": [{ "type": "string", "const": "vscode", "description": "%configuration.tsserver.watchOptions.vscode%" }, { "type": "object", "properties": { "watchFile": { "type": "string", "description": "%configuration.tsserver.watchOptions.watchFile%", "enum": ["fixedChunkSizePolling", "fixedPollingInterval", "priorityPollingInterval", "dynamicPriorityPolling", "useFsEvents", "useFsEventsOnParentDirectory"], "enumDescriptions": ["%configuration.tsserver.watchOptions.watchFile.fixedChunkSizePolling%", "%configuration.tsserver.watchOptions.watchFile.fixedPollingInterval%", "%configuration.tsserver.watchOptions.watchFile.priorityPollingInterval%", "%configuration.tsserver.watchOptions.watchFile.dynamicPriorityPolling%", "%configuration.tsserver.watchOptions.watchFile.useFsEvents%", "%configuration.tsserver.watchOptions.watchFile.useFsEventsOnParentDirectory%"], "default": "useFsEvents" }, "watchDirectory": { "type": "string", "description": "%configuration.tsserver.watchOptions.watchDirectory%", "enum": ["fixedChunkSizePolling", "fixedPollingInterval", "dynamicPriorityPolling", "useFsEvents"], "enumDescriptions": ["%configuration.tsserver.watchOptions.watchDirectory.fixedChunkSizePolling%", "%configuration.tsserver.watchOptions.watchDirectory.fixedPollingInterval%", "%configuration.tsserver.watchOptions.watchDirectory.dynamicPriorityPolling%", "%configuration.tsserver.watchOptions.watchDirectory.useFsEvents%"], "default": "useFsEvents" }, "fallbackPolling": { "type": "string", "description": "%configuration.tsserver.watchOptions.fallbackPolling%", "enum": ["fixedPollingInterval", "priorityPollingInterval", "dynamicPriorityPolling"], "enumDescriptions": ["configuration.tsserver.watchOptions.fallbackPolling.fixedPollingInterval", "configuration.tsserver.watchOptions.fallbackPolling.priorityPollingInterval", "configuration.tsserver.watchOptions.fallbackPolling.dynamicPriorityPolling"] }, "synchronousWatchDirectory": { "type": "boolean", "description": "%configuration.tsserver.watchOptions.synchronousWatchDirectory%" } } }] }, "typescript.workspaceSymbols.scope": { "type": "string", "enum": ["allOpenProjects", "currentProject"], "enumDescriptions": ["%typescript.workspaceSymbols.scope.allOpenProjects%", "%typescript.workspaceSymbols.scope.currentProject%"], "default": "allOpenProjects", "markdownDescription": "%typescript.workspaceSymbols.scope%", "scope": "window" }, "javascript.suggest.classMemberSnippets.enabled": { "type": "boolean", "default": true, "description": "%configuration.suggest.classMemberSnippets.enabled%", "scope": "resource" }, "typescript.suggest.classMemberSnippets.enabled": { "type": "boolean", "default": true, "description": "%configuration.suggest.classMemberSnippets.enabled%", "scope": "resource" }, "typescript.suggest.objectLiteralMethodSnippets.enabled": { "type": "boolean", "default": true, "description": "%configuration.suggest.objectLiteralMethodSnippets.enabled%", "scope": "resource" }, "typescript.tsserver.web.projectWideIntellisense.enabled": { "type": "boolean", "default": true, "description": "%configuration.tsserver.web.projectWideIntellisense.enabled%", "scope": "window" }, "typescript.tsserver.web.projectWideIntellisense.suppressSemanticErrors": { "type": "boolean", "default": false, "description": "%configuration.tsserver.web.projectWideIntellisense.suppressSemanticErrors%", "scope": "window" }, "typescript.tsserver.web.typeAcquisition.enabled": { "type": "boolean", "default": true, "description": "%configuration.tsserver.web.typeAcquisition.enabled%", "scope": "window" }, "typescript.tsserver.nodePath": { "type": "string", "description": "%configuration.tsserver.nodePath%", "scope": "window" }, "typescript.preferGoToSourceDefinition": { "type": "boolean", "default": false, "description": "%configuration.preferGoToSourceDefinition%", "scope": "window" }, "javascript.preferGoToSourceDefinition": { "type": "boolean", "default": false, "description": "%configuration.preferGoToSourceDefinition%", "scope": "window" }, "typescript.workspaceSymbols.excludeLibrarySymbols": { "type": "boolean", "default": true, "markdownDescription": "%typescript.workspaceSymbols.excludeLibrarySymbols%", "scope": "window" }, "typescript.tsserver.enableRegionDiagnostics": { "type": "boolean", "default": true, "description": "%typescript.tsserver.enableRegionDiagnostics%", "scope": "window" }, "javascript.updateImportsOnPaste.enabled": { "scope": "window", "type": "boolean", "default": true, "markdownDescription": "%configuration.updateImportsOnPaste%" }, "typescript.updateImportsOnPaste.enabled": { "scope": "window", "type": "boolean", "default": true, "markdownDescription": "%configuration.updateImportsOnPaste%" }, "typescript.experimental.expandableHover": { "type": "boolean", "default": false, "description": "%configuration.expandableHover%", "scope": "window", "tags": ["experimental"] } } }, "commands": [{ "command": "typescript.reloadProjects", "title": "%reloadProjects.title%", "category": "TypeScript" }, { "command": "javascript.reloadProjects", "title": "%reloadProjects.title%", "category": "JavaScript" }, { "command": "typescript.selectTypeScriptVersion", "title": "%typescript.selectTypeScriptVersion.title%", "category": "TypeScript" }, { "command": "typescript.goToProjectConfig", "title": "%typescript.goToProjectConfig.title%", "category": "TypeScript" }, { "command": "javascript.goToProjectConfig", "title": "%javascript.goToProjectConfig.title%", "category": "JavaScript" }, { "command": "typescript.openTsServerLog", "title": "%typescript.openTsServerLog.title%", "category": "TypeScript" }, { "command": "typescript.restartTsServer", "title": "%typescript.restartTsServer%", "category": "TypeScript" }, { "command": "typescript.findAllFileReferences", "title": "%typescript.findAllFileReferences%", "category": "TypeScript" }, { "command": "typescript.goToSourceDefinition", "title": "%typescript.goToSourceDefinition%", "category": "TypeScript" }, { "command": "typescript.sortImports", "title": "%typescript.sortImports%", "category": "TypeScript" }, { "command": "javascript.sortImports", "title": "%typescript.sortImports%", "category": "JavaScript" }, { "command": "typescript.removeUnusedImports", "title": "%typescript.removeUnusedImports%", "category": "TypeScript" }, { "command": "javascript.removeUnusedImports", "title": "%typescript.removeUnusedImports%", "category": "JavaScript" }], "menus": { "commandPalette": [{ "command": "typescript.reloadProjects", "when": "editorLangId == typescript && typescript.isManagedFile" }, { "command": "typescript.reloadProjects", "when": "editorLangId == typescriptreact && typescript.isManagedFile" }, { "command": "javascript.reloadProjects", "when": "editorLangId == javascript && typescript.isManagedFile" }, { "command": "javascript.reloadProjects", "when": "editorLangId == javascriptreact && typescript.isManagedFile" }, { "command": "typescript.goToProjectConfig", "when": "editorLangId == typescript && typescript.isManagedFile" }, { "command": "typescript.goToProjectConfig", "when": "editorLangId == typescriptreact" }, { "command": "javascript.goToProjectConfig", "when": "editorLangId == javascript && typescript.isManagedFile" }, { "command": "javascript.goToProjectConfig", "when": "editorLangId == javascriptreact && typescript.isManagedFile" }, { "command": "typescript.selectTypeScriptVersion", "when": "typescript.isManagedFile" }, { "command": "typescript.openTsServerLog", "when": "typescript.isManagedFile" }, { "command": "typescript.restartTsServer", "when": "typescript.isManagedFile" }, { "command": "typescript.findAllFileReferences", "when": "tsSupportsFileReferences && typescript.isManagedFile" }, { "command": "typescript.goToSourceDefinition", "when": "tsSupportsSourceDefinition && typescript.isManagedFile" }, { "command": "typescript.sortImports", "when": "supportedCodeAction =~ /(\\s|^)source\\.sortImports\\b/ && editorLangId =~ /^typescript(react)?$/" }, { "command": "javascript.sortImports", "when": "supportedCodeAction =~ /(\\s|^)source\\.sortImports\\b/ && editorLangId =~ /^javascript(react)?$/" }, { "command": "typescript.removeUnusedImports", "when": "supportedCodeAction =~ /(\\s|^)source\\.removeUnusedImports\\b/ && editorLangId =~ /^typescript(react)?$/" }, { "command": "javascript.removeUnusedImports", "when": "supportedCodeAction =~ /(\\s|^)source\\.removeUnusedImports\\b/ && editorLangId =~ /^javascript(react)?$/" }], "editor/context": [{ "command": "typescript.goToSourceDefinition", "when": "tsSupportsSourceDefinition && (resourceLangId == typescript || resourceLangId == typescriptreact || resourceLangId == javascript || resourceLangId == javascriptreact)", "group": "navigation@1.41" }], "explorer/context": [{ "command": "typescript.findAllFileReferences", "when": "tsSupportsFileReferences && resourceLangId == typescript", "group": "4_search" }, { "command": "typescript.findAllFileReferences", "when": "tsSupportsFileReferences && resourceLangId == typescriptreact", "group": "4_search" }, { "command": "typescript.findAllFileReferences", "when": "tsSupportsFileReferences && resourceLangId == javascript", "group": "4_search" }, { "command": "typescript.findAllFileReferences", "when": "tsSupportsFileReferences && resourceLangId == javascriptreact", "group": "4_search" }], "editor/title/context": [{ "command": "typescript.findAllFileReferences", "when": "tsSupportsFileReferences && resourceLangId == javascript" }, { "command": "typescript.findAllFileReferences", "when": "tsSupportsFileReferences && resourceLangId == javascriptreact" }, { "command": "typescript.findAllFileReferences", "when": "tsSupportsFileReferences && resourceLangId == typescript" }, { "command": "typescript.findAllFileReferences", "when": "tsSupportsFileReferences && resourceLangId == typescriptreact" }] }, "breakpoints": [{ "language": "typescript" }, { "language": "typescriptreact" }], "taskDefinitions": [{ "type": "typescript", "required": ["tsconfig"], "properties": { "tsconfig": { "type": "string", "description": "%taskDefinition.tsconfig.description%" }, "option": { "type": "string" } }, "when": "shellExecutionSupported" }], "problemPatterns": [{ "name": "tsc", "regexp": "^([^\\s].*)[\\(:](\\d+)[,:](\\d+)(?:\\):\\s+|\\s+-\\s+)(error|warning|info)\\s+TS(\\d+)\\s*:\\s*(.*)$", "file": 1, "line": 2, "column": 3, "severity": 4, "code": 5, "message": 6 }], "problemMatchers": [{ "name": "tsc", "label": "%typescript.problemMatchers.tsc.label%", "owner": "typescript", "source": "ts", "applyTo": "closedDocuments", "fileLocation": ["relative", "${cwd}"], "pattern": "$tsc" }, { "name": "tsc-watch", "label": "%typescript.problemMatchers.tscWatch.label%", "owner": "typescript", "source": "ts", "applyTo": "closedDocuments", "fileLocation": ["relative", "${cwd}"], "pattern": "$tsc", "background": { "activeOnStart": true, "beginsPattern": { "regexp": "^\\s*(?:message TS6032:|\\[?\\D*.{1,2}[:.].{1,2}[:.].{1,2}\\D*(\u251C\\D*\\d{1,2}\\D+\u2524)?(?:\\]| -)) (Starting compilation in watch mode|File change detected\\. Starting incremental compilation)\\.\\.\\." }, "endsPattern": { "regexp": "^\\s*(?:message TS6042:|\\[?\\D*.{1,2}[:.].{1,2}[:.].{1,2}\\D*(\u251C\\D*\\d{1,2}\\D+\u2524)?(?:\\]| -)) (?:Compilation complete\\.|Found \\d+ errors?\\.) Watching for file changes\\." } } }] }, "repository": { "type": "git", "url": "https://github.com/microsoft/vscode.git" } }, "packageNLS": { "displayName": "TypeScript and JavaScript Language Features", "description": "Provides rich language support for JavaScript and TypeScript.", "workspaceTrust": "The extension requires workspace trust when the workspace version is used because it executes code specified by the workspace.", "virtualWorkspaces": "In virtual workspaces, resolving and finding references across files is not supported.", "reloadProjects.title": "Reload Project", "configuration.typescript": "TypeScript", "configuration.suggest.completeFunctionCalls": "Complete functions with their parameter signature.", "configuration.suggest.includeAutomaticOptionalChainCompletions": "Enable/disable showing completions on potentially undefined values that insert an optional chain call. Requires strict null checks to be enabled.", "configuration.suggest.includeCompletionsForImportStatements": "Enable/disable auto-import-style completions on partially-typed import statements.", "typescript.tsdk.desc": "Specifies the folder path to the tsserver and `lib*.d.ts` files under a TypeScript install to use for IntelliSense, for example: `./node_modules/typescript/lib`.\n\n- When specified as a user setting, the TypeScript version from `typescript.tsdk` automatically replaces the built-in TypeScript version.\n- When specified as a workspace setting, `typescript.tsdk` allows you to switch to use that workspace version of TypeScript for IntelliSense with the `TypeScript: Select TypeScript version` command.\n\nSee the [TypeScript documentation](https://code.visualstudio.com/docs/typescript/typescript-compiling#_using-newer-typescript-versions) for more detail about managing TypeScript versions.", "typescript.disableAutomaticTypeAcquisition": "Disables [automatic type acquisition](https://code.visualstudio.com/docs/nodejs/working-with-javascript#_typings-and-automatic-type-acquisition). Automatic type acquisition fetches `@types` packages from npm to improve IntelliSense for external libraries.", "typescript.enablePromptUseWorkspaceTsdk": "Enables prompting of users to use the TypeScript version configured in the workspace for Intellisense.", "typescript.tsserver.enableTracing": "Enables tracing TS server performance to a directory. These trace files can be used to diagnose TS Server performance issues. The log may contain file paths, source code, and other potentially sensitive information from your project.", "typescript.tsserver.log": "Enables logging of the TS server to a file. This log can be used to diagnose TS Server issues. The log may contain file paths, source code, and other potentially sensitive information from your project.", "typescript.tsserver.pluginPaths": "Additional paths to discover TypeScript Language Service plugins.", "typescript.tsserver.pluginPaths.item": "Either an absolute or relative path. Relative path will be resolved against workspace folder(s).", "typescript.tsserver.trace": "Enables tracing of messages sent to the TS server. This trace can be used to diagnose TS Server issues. The trace may contain file paths, source code, and other potentially sensitive information from your project.", "typescript.tsserver.enableRegionDiagnostics": "Enables region-based diagnostics in TypeScript. Requires using TypeScript 5.6+ in the workspace.", "typescript.validate.enable": "Enable/disable TypeScript validation.", "typescript.format.enable": "Enable/disable default TypeScript formatter.", "javascript.format.enable": "Enable/disable default JavaScript formatter.", "format.insertSpaceAfterCommaDelimiter": "Defines space handling after a comma delimiter.", "format.insertSpaceAfterConstructor": "Defines space handling after the constructor keyword.", "format.insertSpaceAfterSemicolonInForStatements": "Defines space handling after a semicolon in a for statement.", "format.insertSpaceBeforeAndAfterBinaryOperators": "Defines space handling after a binary operator.", "format.insertSpaceAfterKeywordsInControlFlowStatements": "Defines space handling after keywords in a control flow statement.", "format.insertSpaceAfterFunctionKeywordForAnonymousFunctions": "Defines space handling after function keyword for anonymous functions.", "format.insertSpaceBeforeFunctionParenthesis": "Defines space handling before function argument parentheses.", "format.insertSpaceAfterOpeningAndBeforeClosingNonemptyParenthesis": "Defines space handling after opening and before closing non-empty parenthesis.", "format.insertSpaceAfterOpeningAndBeforeClosingNonemptyBrackets": "Defines space handling after opening and before closing non-empty brackets.", "format.insertSpaceAfterOpeningAndBeforeClosingNonemptyBraces": "Defines space handling after opening and before closing non-empty braces.", "format.insertSpaceAfterOpeningAndBeforeClosingEmptyBraces": "Defines space handling after opening and before closing empty braces.", "format.insertSpaceAfterOpeningAndBeforeClosingTemplateStringBraces": "Defines space handling after opening and before closing template string braces.", "format.insertSpaceAfterOpeningAndBeforeClosingJsxExpressionBraces": "Defines space handling after opening and before closing JSX expression braces.", "format.insertSpaceAfterTypeAssertion": "Defines space handling after type assertions in TypeScript.", "format.placeOpenBraceOnNewLineForFunctions": "Defines whether an open brace is put onto a new line for functions or not.", "format.placeOpenBraceOnNewLineForControlBlocks": "Defines whether an open brace is put onto a new line for control blocks or not.", "format.semicolons": "Defines handling of optional semicolons.", "format.semicolons.ignore": "Don't insert or remove any semicolons.", "format.semicolons.insert": "Insert semicolons at statement ends.", "format.semicolons.remove": "Remove unnecessary semicolons.", "format.indentSwitchCase": "Indent case clauses in switch statements. Requires using TypeScript 5.1+ in the workspace.", "javascript.validate.enable": "Enable/disable JavaScript validation.", "javascript.goToProjectConfig.title": "Go to Project Configuration (jsconfig / tsconfig)", "typescript.goToProjectConfig.title": "Go to Project Configuration (tsconfig)", "javascript.referencesCodeLens.enabled": "Enable/disable references CodeLens in JavaScript files.", "javascript.referencesCodeLens.showOnAllFunctions": "Enable/disable references CodeLens on all functions in JavaScript files.", "typescript.referencesCodeLens.enabled": "Enable/disable references CodeLens in TypeScript files.", "typescript.referencesCodeLens.showOnAllFunctions": "Enable/disable references CodeLens on all functions in TypeScript files.", "typescript.implementationsCodeLens.enabled": "Enable/disable implementations CodeLens. This CodeLens shows the implementers of an interface.", "typescript.implementationsCodeLens.showOnInterfaceMethods": "Enable/disable implementations CodeLens on interface methods.", "typescript.openTsServerLog.title": "Open TS Server log", "typescript.restartTsServer": "Restart TS Server", "typescript.selectTypeScriptVersion.title": "Select TypeScript Version...", "typescript.reportStyleChecksAsWarnings": "Report style checks as warnings.", "typescript.npm": "Specifies the path to the npm executable used for [Automatic Type Acquisition](https://code.visualstudio.com/docs/nodejs/working-with-javascript#_typings-and-automatic-type-acquisition).", "typescript.check.npmIsInstalled": "Check if npm is installed for [Automatic Type Acquisition](https://code.visualstudio.com/docs/nodejs/working-with-javascript#_typings-and-automatic-type-acquisition).", "configuration.suggest.names": "Enable/disable including unique names from the file in JavaScript suggestions. Note that name suggestions are always disabled in JavaScript code that is semantically checked using `@ts-check` or `checkJs`.", "typescript.tsc.autoDetect": "Controls auto detection of tsc tasks.", "typescript.tsc.autoDetect.off": "Disable this feature.", "typescript.tsc.autoDetect.on": "Create both build and watch tasks.", "typescript.tsc.autoDetect.build": "Only create single run compile tasks.", "typescript.tsc.autoDetect.watch": "Only create compile and watch tasks.", "typescript.problemMatchers.tsc.label": "TypeScript problems", "typescript.problemMatchers.tscWatch.label": "TypeScript problems (watch mode)", "configuration.suggest.paths": "Enable/disable suggestions for paths in import statements and require calls.", "configuration.tsserver.useSeparateSyntaxServer": "Enable/disable spawning a separate TypeScript server that can more quickly respond to syntax related operations, such as calculating folding or computing document symbols.", "configuration.tsserver.useSeparateSyntaxServer.deprecation": "This setting has been deprecated in favor of `typescript.tsserver.useSyntaxServer`.", "configuration.tsserver.useSyntaxServer": "Controls if TypeScript launches a dedicated server to more quickly handle syntax related operations, such as computing code folding.", "configuration.tsserver.useSyntaxServer.always": "Use a lighter weight syntax server to handle all IntelliSense operations. This syntax server can only provide IntelliSense for opened files.", "configuration.tsserver.useSyntaxServer.never": "Don't use a dedicated syntax server. Use a single server to handle all IntelliSense operations.", "configuration.tsserver.useSyntaxServer.auto": "Spawn both a full server and a lighter weight server dedicated to syntax operations. The syntax server is used to speed up syntax operations and provide IntelliSense while projects are loading.", "configuration.tsserver.maxTsServerMemory": "The maximum amount of memory (in MB) to allocate to the TypeScript server process. To use a memory limit greater than 4 GB, use `#typescript.tsserver.nodePath#` to run TS Server with a custom Node installation.", "configuration.tsserver.experimental.enableProjectDiagnostics": "Enables project wide error reporting.", "typescript.locale": "Sets the locale used to report JavaScript and TypeScript errors. Defaults to use VS Code's locale.", "typescript.locale.auto": "Use VS Code's configured display language.", "configuration.implicitProjectConfig.module": "Sets the module system for the program. See more: https://www.typescriptlang.org/tsconfig#module.", "configuration.implicitProjectConfig.target": "Set target JavaScript language version for emitted JavaScript and include library declarations. See more: https://www.typescriptlang.org/tsconfig#target.", "configuration.implicitProjectConfig.checkJs": "Enable/disable semantic checking of JavaScript files. Existing `jsconfig.json` or `tsconfig.json` files override this setting.", "configuration.javascript.checkJs.checkJs.deprecation": "This setting has been deprecated in favor of `js/ts.implicitProjectConfig.checkJs`.", "configuration.implicitProjectConfig.experimentalDecorators": "Enable/disable `experimentalDecorators` in JavaScript files that are not part of a project. Existing `jsconfig.json` or `tsconfig.json` files override this setting.", "configuration.javascript.checkJs.experimentalDecorators.deprecation": "This setting has been deprecated in favor of `js/ts.implicitProjectConfig.experimentalDecorators`.", "configuration.implicitProjectConfig.strictNullChecks": "Enable/disable [strict null checks](https://www.typescriptlang.org/tsconfig#strictNullChecks) in JavaScript and TypeScript files that are not part of a project. Existing `jsconfig.json` or `tsconfig.json` files override this setting.", "configuration.implicitProjectConfig.strictFunctionTypes": "Enable/disable [strict function types](https://www.typescriptlang.org/tsconfig#strictFunctionTypes) in JavaScript and TypeScript files that are not part of a project. Existing `jsconfig.json` or `tsconfig.json` files override this setting.", "configuration.suggest.jsdoc.generateReturns": "Enable/disable generating `@returns` annotations for JSDoc templates.", "configuration.suggest.autoImports": "Enable/disable auto import suggestions.", "configuration.preferGoToSourceDefinition": "Makes `Go to Definition` avoid type declaration files when possible by triggering `Go to Source Definition` instead. This allows `Go to Source Definition` to be triggered with the mouse gesture.", "inlayHints.parameterNames.none": "Disable parameter name hints.", "inlayHints.parameterNames.literals": "Enable parameter name hints only for literal arguments.", "inlayHints.parameterNames.all": "Enable parameter name hints for literal and non-literal arguments.", "configuration.inlayHints.parameterNames.enabled": { "message": "Enable/disable inlay hints for parameter names:\n```typescript\n\nparseInt(/* str: */ '123', /* radix: */ 8)\n \n```", "comment": ["The text inside the ``` block is code and should not be localized."] }, "configuration.inlayHints.parameterNames.suppressWhenArgumentMatchesName": "Suppress parameter name hints on arguments whose text is identical to the parameter name.", "configuration.inlayHints.parameterTypes.enabled": { "message": "Enable/disable inlay hints for implicit parameter types:\n```typescript\n\nel.addEventListener('click', e /* :MouseEvent */ => ...)\n \n```", "comment": ["The text inside the ``` block is code and should not be localized."] }, "configuration.inlayHints.variableTypes.enabled": { "message": "Enable/disable inlay hints for implicit variable types:\n```typescript\n\nconst foo /* :number */ = Date.now();\n \n```", "comment": ["The text inside the ``` block is code and should not be localized."] }, "configuration.inlayHints.variableTypes.suppressWhenTypeMatchesName": "Suppress type hints on variables whose name is identical to the type name.", "configuration.inlayHints.propertyDeclarationTypes.enabled": { "message": "Enable/disable inlay hints for implicit types on property declarations:\n```typescript\n\nclass Foo {\n	prop /* :number */ = Date.now();\n}\n \n```", "comment": ["The text inside the ``` block is code and should not be localized."] }, "configuration.inlayHints.functionLikeReturnTypes.enabled": { "message": "Enable/disable inlay hints for implicit return types on function signatures:\n```typescript\n\nfunction foo() /* :number */ {\n	return Date.now();\n} \n \n```", "comment": ["The text inside the ``` block is code and should not be localized."] }, "configuration.inlayHints.enumMemberValues.enabled": { "message": "Enable/disable inlay hints for member values in enum declarations:\n```typescript\n\nenum MyValue {\n	A /* = 0 */;\n	B /* = 1 */;\n}\n \n```", "comment": ["The text inside the ``` block is code and should not be localized."] }, "taskDefinition.tsconfig.description": "The tsconfig file that defines the TS build.", "javascript.suggestionActions.enabled": "Enable/disable suggestion diagnostics for JavaScript files in the editor.", "typescript.suggestionActions.enabled": "Enable/disable suggestion diagnostics for TypeScript files in the editor.", "typescript.preferences.quoteStyle": "Preferred quote style to use for Quick Fixes.", "typescript.preferences.quoteStyle.single": "Always use single quotes: `'`", "typescript.preferences.quoteStyle.double": 'Always use double quotes: `"`', "typescript.preferences.quoteStyle.auto": "Infer quote type from existing code", "typescript.preferences.importModuleSpecifier": "Preferred path style for auto imports.", "typescript.preferences.importModuleSpecifier.shortest": "Prefers a non-relative import only if one is available that has fewer path segments than a relative import.", "typescript.preferences.importModuleSpecifier.relative": "Prefers a relative path to the imported file location.", "typescript.preferences.importModuleSpecifier.nonRelative": "Prefers a non-relative import based on the `baseUrl` or `paths` configured in your `jsconfig.json` / `tsconfig.json`.", "typescript.preferences.importModuleSpecifier.projectRelative": "Prefers a non-relative import only if the relative import path would leave the package or project directory.", "typescript.preferences.importModuleSpecifierEnding": "Preferred path ending for auto imports.", "typescript.preferences.importModuleSpecifierEnding.label.js": ".js / .ts", "typescript.preferences.importModuleSpecifierEnding.auto": "Use project settings to select a default.", "typescript.preferences.importModuleSpecifierEnding.minimal": "Shorten `./component/index.js` to `./component`.", "typescript.preferences.importModuleSpecifierEnding.index": "Shorten `./component/index.js` to `./component/index`.", "typescript.preferences.importModuleSpecifierEnding.js": "Do not shorten path endings; include the `.js` or `.ts` extension.", "typescript.preferences.jsxAttributeCompletionStyle": "Preferred style for JSX attribute completions.", "javascript.preferences.jsxAttributeCompletionStyle.auto": 'Insert `={}` or `=""` after attribute names based on the prop type. See `#javascript.preferences.quoteStyle#` to control the type of quotes used for string attributes.', "typescript.preferences.jsxAttributeCompletionStyle.auto": 'Insert `={}` or `=""` after attribute names based on the prop type. See `#typescript.preferences.quoteStyle#` to control the type of quotes used for string attributes.', "typescript.preferences.jsxAttributeCompletionStyle.braces": "Insert `={}` after attribute names.", "typescript.preferences.jsxAttributeCompletionStyle.none": "Only insert attribute names.", "typescript.preferences.includePackageJsonAutoImports": "Enable/disable searching `package.json` dependencies for available auto imports.", "typescript.preferences.includePackageJsonAutoImports.auto": "Search dependencies based on estimated performance impact.", "typescript.preferences.includePackageJsonAutoImports.on": "Always search dependencies.", "typescript.preferences.includePackageJsonAutoImports.off": "Never search dependencies.", "typescript.preferences.autoImportFileExcludePatterns": "Specify glob patterns of files to exclude from auto imports. Relative paths are resolved relative to the workspace root. Patterns are evaluated using tsconfig.json [`exclude`](https://www.typescriptlang.org/tsconfig#exclude) semantics.", "typescript.preferences.autoImportSpecifierExcludeRegexes": "Specify regular expressions to exclude auto imports with matching import specifiers. Examples:\n\n- `^node:`\n- `lib/internal` (slashes don't need to be escaped...)\n- `/lib\\/internal/i` (...unless including surrounding slashes for `i` or `u` flags)\n- `^lodash$` (only allow subpath imports from lodash)", "typescript.preferences.preferTypeOnlyAutoImports": "Include the `type` keyword in auto-imports whenever possible. Requires using TypeScript 5.3+ in the workspace.", "typescript.workspaceSymbols.excludeLibrarySymbols": "Exclude symbols that come from library files in `Go to Symbol in Workspace` results. Requires using TypeScript 5.3+ in the workspace.", "typescript.updateImportsOnFileMove.enabled": "Enable/disable automatic updating of import paths when you rename or move a file in VS Code.", "typescript.updateImportsOnFileMove.enabled.prompt": "Prompt on each rename.", "typescript.updateImportsOnFileMove.enabled.always": "Always update paths automatically.", "typescript.updateImportsOnFileMove.enabled.never": "Never rename paths and don't prompt.", "typescript.autoClosingTags": "Enable/disable automatic closing of JSX tags.", "typescript.suggest.enabled": "Enabled/disable autocomplete suggestions.", "configuration.surveys.enabled": "Enabled/disable occasional surveys that help us improve VS Code's JavaScript and TypeScript support.", "configuration.suggest.completeJSDocs": "Enable/disable suggestion to complete JSDoc comments.", "configuration.tsserver.useVsCodeWatcher": "Use VS Code's file watchers instead of TypeScript's. Requires using TypeScript 5.4+ in the workspace.", "configuration.tsserver.useVsCodeWatcher.deprecation": "Please use the `#typescript.tsserver.watchOptions#` setting instead.", "configuration.tsserver.watchOptions": "Configure which watching strategies should be used to keep track of files and directories.", "configuration.tsserver.watchOptions.vscode": "Use VS Code's file watchers instead of TypeScript's. Requires using TypeScript 5.4+ in the workspace.", "configuration.tsserver.watchOptions.watchFile": "Strategy for how individual files are watched.", "configuration.tsserver.watchOptions.watchFile.fixedChunkSizePolling": "Polls files in chunks at regular interval.", "configuration.tsserver.watchOptions.watchFile.fixedPollingInterval": "Check every file for changes several times a second at a fixed interval.", "configuration.tsserver.watchOptions.watchFile.priorityPollingInterval": "Check every file for changes several times a second, but use heuristics to check certain types of files less frequently than others.", "configuration.tsserver.watchOptions.watchFile.dynamicPriorityPolling": "Use a dynamic queue where less-frequently modified files will be checked less often.", "configuration.tsserver.watchOptions.watchFile.useFsEvents": "Attempt to use the operating system/file system's native events for file changes.", "configuration.tsserver.watchOptions.watchFile.useFsEventsOnParentDirectory": "Attempt to use the operating system/file system's native events to listen for changes on a file's containing directories. This can use fewer file watchers, but might be less accurate.", "configuration.tsserver.watchOptions.watchDirectory": "Strategy for how entire directory trees are watched under systems that lack recursive file-watching functionality.", "configuration.tsserver.watchOptions.watchDirectory.fixedChunkSizePolling": "Polls directories in chunks at regular interval.", "configuration.tsserver.watchOptions.watchDirectory.fixedPollingInterval": "Check every directory for changes several times a second at a fixed interval.", "configuration.tsserver.watchOptions.watchDirectory.dynamicPriorityPolling": "Use a dynamic queue where less-frequently modified directories will be checked less often.", "configuration.tsserver.watchOptions.watchDirectory.useFsEvents": "Attempt to use the operating system/file system's native events for directory changes.", "configuration.tsserver.watchOptions.fallbackPolling": "When using file system events, this option specifies the polling strategy that gets used when the system runs out of native file watchers and/or doesn't support native file watchers.", "configuration.tsserver.watchOptions.fallbackPolling.fixedPollingInterval": "Check every file for changes several times a second at a fixed interval.", "configuration.tsserver.watchOptions.fallbackPolling.priorityPollingInterval": "Check every file for changes several times a second, but use heuristics to check certain types of files less frequently than others.", "configuration.tsserver.watchOptions.fallbackPolling.dynamicPriorityPolling ": "Use a dynamic queue where less-frequently modified files will be checked less often.", "configuration.tsserver.watchOptions.synchronousWatchDirectory": "Disable deferred watching on directories. Deferred watching is useful when lots of file changes might occur at once (e.g. a change in node_modules from running npm install), but you might want to disable it with this flag for some less-common setups.", "typescript.preferences.renameShorthandProperties.deprecationMessage": "The setting 'typescript.preferences.renameShorthandProperties' has been deprecated in favor of 'typescript.preferences.useAliasesForRenames'", "typescript.preferences.useAliasesForRenames": "Enable/disable introducing aliases for object shorthand properties during renames.", "typescript.preferences.renameMatchingJsxTags": "When on a JSX tag, try to rename the matching tag instead of renaming the symbol. Requires using TypeScript 5.1+ in the workspace.", "typescript.preferences.organizeImports": "Advanced preferences that control how imports are ordered.", "javascript.preferences.organizeImports": "Advanced preferences that control how imports are ordered.", "typescript.preferences.organizeImports.caseSensitivity": "Specifies how imports should be sorted with regards to case-sensitivity. If `auto` or unspecified, we will detect the case-sensitivity per file", "typescript.preferences.organizeImports.caseSensitivity.auto": "Detect case-sensitivity for import sorting.", "typescript.preferences.organizeImports.caseSensitivity.insensitive": "Sort imports case-insensitively.", "typescript.preferences.organizeImports.caseSensitivity.sensitive": "Sort imports case-sensitively.", "typescript.preferences.organizeImports.typeOrder": "Specify how type-only named imports should be sorted.", "typescript.preferences.organizeImports.typeOrder.auto": "Detect where type-only named imports should be sorted.", "typescript.preferences.organizeImports.typeOrder.last": "Type only named imports are sorted to the end of the import list. E.g. `import { B, Z, type A, type Y } from 'module';`", "typescript.preferences.organizeImports.typeOrder.inline": "Named imports are sorted by name only. E.g. `import { type A, B, type Y, Z } from 'module';`", "typescript.preferences.organizeImports.typeOrder.first": "Type only named imports are sorted to the beginning of the import list. E.g. `import { type A, type Y, B, Z } from 'module';`", "typescript.preferences.organizeImports.unicodeCollation": "Specify whether to sort imports using Unicode or Ordinal collation.", "typescript.preferences.organizeImports.unicodeCollation.ordinal": "Sort imports using the numeric value of each code point.", "typescript.preferences.organizeImports.unicodeCollation.unicode": "Sort imports using the Unicode code collation.", "typescript.preferences.organizeImports.locale": "Requires `organizeImports.unicodeCollation: 'unicode'`. Overrides the locale used for collation. Specify `auto` to use the UI locale.", "typescript.preferences.organizeImports.caseFirst": "Requires `organizeImports.unicodeCollation: 'unicode'`, and `organizeImports.caseSensitivity` is not `caseInsensitive`. Indicates whether upper-case will sort before lower-case.", "typescript.preferences.organizeImports.caseFirst.default": "Default order given by `locale`.", "typescript.preferences.organizeImports.caseFirst.lower": "Lower-case comes before upper-case. E.g.` a, A, z, Z`.", "typescript.preferences.organizeImports.caseFirst.upper": "Upper-case comes before lower-case. E.g. ` A, a, B, b`.", "typescript.preferences.organizeImports.numericCollation": "Requires `organizeImports.unicodeCollation: 'unicode'`. Sort numeric strings by integer value.", "typescript.preferences.organizeImports.accentCollation": "Requires `organizeImports.unicodeCollation: 'unicode'`. Compare characters with diacritical marks as unequal to base character.", "typescript.workspaceSymbols.scope": "Controls which files are searched by [Go to Symbol in Workspace](https://code.visualstudio.com/docs/editor/editingevolved#_open-symbol-by-name).", "typescript.workspaceSymbols.scope.allOpenProjects": "Search all open JavaScript or TypeScript projects for symbols.", "typescript.workspaceSymbols.scope.currentProject": "Only search for symbols in the current JavaScript or TypeScript project.", "typescript.sortImports": "Sort Imports", "typescript.removeUnusedImports": "Remove Unused Imports", "typescript.findAllFileReferences": "Find File References", "typescript.goToSourceDefinition": "Go to Source Definition", "configuration.suggest.classMemberSnippets.enabled": "Enable/disable snippet completions for class members.", "configuration.suggest.objectLiteralMethodSnippets.enabled": "Enable/disable snippet completions for methods in object literals.", "configuration.tsserver.web.projectWideIntellisense.enabled": "Enable/disable project-wide IntelliSense on web. Requires that VS Code is running in a trusted context.", "configuration.tsserver.web.projectWideIntellisense.suppressSemanticErrors": "Suppresses semantic errors on web even when project wide IntelliSense is enabled. This is always on when project wide IntelliSense is not enabled or available. See `#typescript.tsserver.web.projectWideIntellisense.enabled#`", "configuration.tsserver.web.typeAcquisition.enabled": "Enable/disable package acquisition on the web. This enables IntelliSense for imported packages. Requires `#typescript.tsserver.web.projectWideIntellisense.enabled#`. Currently not supported for Safari.", "configuration.tsserver.nodePath": "Run TS Server on a custom Node installation. This can be a path to a Node executable, or 'node' if you want VS Code to detect a Node installation.", "configuration.updateImportsOnPaste": 'Enable updating imports when pasting code. Requires TypeScript 5.7+.\n\nBy default this shows a option to update imports after pasting. You can use the `#editor.pasteAs.preferences#` setting to update imports automatically when pasting: `"editor.pasteAs.preferences": [ "text.updateImports.jsts" ]`.', "configuration.expandableHover": "Enable/disable expanding on hover.", "walkthroughs.nodejsWelcome.title": "Get started with JavaScript and Node.js", "walkthroughs.nodejsWelcome.description": "Make the most of Visual Studio Code's first-class JavaScript experience.", "walkthroughs.nodejsWelcome.downloadNode.forMacOrWindows.title": "Install Node.js", "walkthroughs.nodejsWelcome.downloadNode.forMacOrWindows.description": "Node.js is an easy way to run JavaScript code. You can use it to quickly build command-line apps and servers. It also comes with npm, a package manager which makes reusing and sharing JavaScript code easy.\n[Install Node.js](https://nodejs.org/en/download/)", "walkthroughs.nodejsWelcome.downloadNode.forLinux.title": "Install Node.js", "walkthroughs.nodejsWelcome.downloadNode.forLinux.description": "Node.js is an easy way to run JavaScript code. You can use it to quickly build command-line apps and servers. It also comes with npm, a package manager which makes reusing and sharing JavaScript code easy.\n[Install Node.js](https://nodejs.org/en/download/package-manager/)", "walkthroughs.nodejsWelcome.makeJsFile.title": "Create a JavaScript File", "walkthroughs.nodejsWelcome.makeJsFile.description": "Let's write our first JavaScript file. We'll have to create a new file and save it with the ``.js`` extension at the end of the file name.\n[Create a JavaScript File](command:javascript-walkthrough.commands.createJsFile)", "walkthroughs.nodejsWelcome.debugJsFile.title": "Run and Debug your JavaScript", "walkthroughs.nodejsWelcome.debugJsFile.description": "Once you've installed Node.js, you can run JavaScript programs at a terminal by entering ``node your-file-name.js``\nAnother easy way to run Node.js programs is by using VS Code's debugger which lets you run your code, pause at different points, and help you understand what's going on step-by-step.\n[Start Debugging](command:javascript-walkthrough.commands.debugJsFile)", "walkthroughs.nodejsWelcome.debugJsFile.altText": "Debug and run your JavaScript code in Node.js with Visual Studio Code.", "walkthroughs.nodejsWelcome.learnMoreAboutJs.title": "Explore More", "walkthroughs.nodejsWelcome.learnMoreAboutJs.description": "Want to get more comfortable with JavaScript, Node.js, and VS Code? Be sure to check out our docs!\nWe've got lots of resources for learning [JavaScript](https://code.visualstudio.com/docs/nodejs/working-with-javascript) and [Node.js](https://code.visualstudio.com/docs/nodejs/nodejs-tutorial).\n\n[Learn More](https://code.visualstudio.com/docs/nodejs/nodejs-tutorial)", "walkthroughs.nodejsWelcome.learnMoreAboutJs.altText": "Learn more about JavaScript and Node.js in Visual Studio Code." }, "readmePath": "typescript-language-features/README.md" }, { "extensionPath": "vb", "packageJSON": { "name": "vb", "displayName": "%displayName%", "description": "%description%", "version": "1.0.0", "publisher": "vscode", "license": "MIT", "engines": { "vscode": "*" }, "scripts": { "update-grammar": "node ../node_modules/vscode-grammar-updater/bin textmate/asp.vb.net.tmbundle Syntaxes/ASP%20VB.net.plist ./syntaxes/asp-vb-net.tmLanguage.json" }, "categories": ["Programming Languages"], "contributes": { "languages": [{ "id": "vb", "extensions": [".vb", ".brs", ".vbs", ".bas", ".vba"], "aliases": ["Visual Basic", "vb"], "configuration": "./language-configuration.json" }], "grammars": [{ "language": "vb", "scopeName": "source.asp.vb.net", "path": "./syntaxes/asp-vb-net.tmLanguage.json" }], "snippets": [{ "language": "vb", "path": "./snippets/vb.code-snippets" }] }, "repository": { "type": "git", "url": "https://github.com/microsoft/vscode.git" } }, "packageNLS": { "displayName": "Visual Basic Language Basics", "description": "Provides snippets, syntax highlighting, bracket matching and folding in Visual Basic files." } }, { "extensionPath": "xml", "packageJSON": { "name": "xml", "displayName": "%displayName%", "description": "%description%", "version": "1.0.0", "publisher": "vscode", "license": "MIT", "engines": { "vscode": "*" }, "categories": ["Programming Languages"], "contributes": { "languages": [{ "id": "xml", "extensions": [".xml", ".xsd", ".ascx", ".atom", ".axml", ".axaml", ".bpmn", ".cpt", ".csl", ".csproj", ".csproj.user", ".dita", ".ditamap", ".dtd", ".ent", ".mod", ".dtml", ".fsproj", ".fxml", ".iml", ".isml", ".jmx", ".launch", ".menu", ".mxml", ".nuspec", ".opml", ".owl", ".proj", ".props", ".pt", ".publishsettings", ".pubxml", ".pubxml.user", ".rbxlx", ".rbxmx", ".rdf", ".rng", ".rss", ".shproj", ".storyboard", ".svg", ".targets", ".tld", ".tmx", ".vbproj", ".vbproj.user", ".vcxproj", ".vcxproj.filters", ".wsdl", ".wxi", ".wxl", ".wxs", ".xaml", ".xbl", ".xib", ".xlf", ".xliff", ".xpdl", ".xul", ".xoml"], "firstLine": "(\\<\\?xml.*)|(\\<svg)|(\\<\\!doctype\\s+svg)", "aliases": ["XML", "xml"], "configuration": "./xml.language-configuration.json" }, { "id": "xsl", "extensions": [".xsl", ".xslt"], "aliases": ["XSL", "xsl"], "configuration": "./xsl.language-configuration.json" }], "grammars": [{ "language": "xml", "scopeName": "text.xml", "path": "./syntaxes/xml.tmLanguage.json" }, { "language": "xsl", "scopeName": "text.xml.xsl", "path": "./syntaxes/xsl.tmLanguage.json" }] }, "scripts": { "update-grammar": "node ../node_modules/vscode-grammar-updater/bin atom/language-xml grammars/xml.cson ./syntaxes/xml.tmLanguage.json grammars/xsl.cson ./syntaxes/xsl.tmLanguage.json" }, "repository": { "type": "git", "url": "https://github.com/microsoft/vscode.git" } }, "packageNLS": { "displayName": "XML Language Basics", "description": "Provides syntax highlighting and bracket matching in XML files." } }, { "extensionPath": "yaml", "packageJSON": { "name": "yaml", "displayName": "%displayName%", "description": "%description%", "version": "1.0.0", "publisher": "vscode", "license": "MIT", "engines": { "vscode": "*" }, "scripts": { "update-grammar": "node ./build/update-grammar.js" }, "categories": ["Programming Languages"], "contributes": { "languages": [{ "id": "dockercompose", "aliases": ["Compose", "compose"], "filenamePatterns": ["compose.yml", "compose.yaml", "compose.*.yml", "compose.*.yaml", "*docker*compose*.yml", "*docker*compose*.yaml"], "configuration": "./language-configuration.json" }, { "id": "yaml", "aliases": ["YAML", "yaml"], "extensions": [".yaml", ".yml", ".eyaml", ".eyml", ".cff", ".yaml-tmlanguage", ".yaml-tmpreferences", ".yaml-tmtheme", ".winget"], "firstLine": "^#cloud-config", "configuration": "./language-configuration.json" }], "grammars": [{ "language": "dockercompose", "scopeName": "source.yaml", "path": "./syntaxes/yaml.tmLanguage.json" }, { "language": "yaml", "scopeName": "source.yaml", "path": "./syntaxes/yaml.tmLanguage.json" }], "configurationDefaults": { "[yaml]": { "editor.insertSpaces": true, "editor.tabSize": 2, "editor.autoIndent": "advanced", "diffEditor.ignoreTrimWhitespace": false, "editor.defaultColorDecorators": false }, "[dockercompose]": { "editor.insertSpaces": true, "editor.tabSize": 2, "editor.autoIndent": "advanced" } } }, "repository": { "type": "git", "url": "https://github.com/microsoft/vscode.git" } }, "packageNLS": { "displayName": "YAML Language Basics", "description": "Provides syntax highlighting and bracket matching in YAML files." } }];
        } else {
          const builtinExtensionsElement = $Y.document.getElementById("vscode-workbench-builtin-extensions");
          const builtinExtensionsElementAttribute = builtinExtensionsElement ? builtinExtensionsElement.getAttribute("data-settings") : void 0;
          if (builtinExtensionsElementAttribute) {
            try {
              bundledExtensions = JSON.parse(builtinExtensionsElementAttribute);
            } catch (error) {
            }
          }
        }
        this.a = bundledExtensions.map(async (e) => {
          const id2 = $IA(e.packageJSON.publisher, e.packageJSON.name);
          return {
            identifier: { id: id2 },
            location: uriIdentityService.extUri.joinPath(builtinExtensionsServiceUrl, e.extensionPath),
            type: 0,
            isBuiltin: true,
            manifest: e.packageNLS ? await this.f(id2, e.packageJSON, e.packageNLS) : e.packageJSON,
            readmeUrl: e.readmePath ? uriIdentityService.extUri.joinPath(builtinExtensionsServiceUrl, e.readmePath) : void 0,
            changelogUrl: e.changelogPath ? uriIdentityService.extUri.joinPath(builtinExtensionsServiceUrl, e.changelogPath) : void 0,
            targetPlatform: "web",
            validations: [],
            isValid: true,
            preRelease: false
          };
        });
      }
    }
  }
  async scanBuiltinExtensions() {
    return [...await Promise.all(this.a)];
  }
  async f(extensionId, manifest, fallbackTranslations) {
    if (!this.b) {
      return $3A(this.d, manifest, fallbackTranslations);
    }
    const uri = URI.joinPath(this.b, extensionId, "package");
    try {
      const res = await this.c.readExtensionResource(uri);
      const json = JSON.parse(res.toString());
      return $3A(this.d, manifest, json, fallbackTranslations);
    } catch (e) {
      this.d.error(e);
      return $3A(this.d, manifest, fallbackTranslations);
    }
  }
};
$iWb = __decorate([
  __param(0, $US),
  __param(1, $vl),
  __param(2, $Olb),
  __param(3, $Vu),
  __param(4, $wn)
], $iWb);
$SC(
  $bA,
  $iWb,
  1
  /* InstantiationType.Delayed */
);

// out-build/vs/workbench/services/extensionRecommendations/common/extensionIgnoredRecommendationsService.js
var ignoredRecommendationsStorageKey = "extensionsAssistant/ignored_recommendations";
var $jWb = class $jWb2 extends $3c {
  get globalIgnoredRecommendations() {
    return [...this.b];
  }
  get ignoredRecommendations() {
    return $Rb([...this.globalIgnoredRecommendations, ...this.f]);
  }
  constructor(g, h3) {
    super();
    this.g = g;
    this.h = h3;
    this.a = this.B(new $ze());
    this.onDidChangeIgnoredRecommendations = this.a.event;
    this.b = [];
    this.c = this.B(new $ze());
    this.onDidChangeGlobalIgnoredRecommendation = this.c.event;
    this.f = [];
    this.b = this.m();
    this.B(this.h.onDidChangeValue(0, ignoredRecommendationsStorageKey, this.q)(() => this.n()));
    this.j();
  }
  async j() {
    this.f = await this.g.getUnwantedRecommendations();
    this.a.fire();
    this.B(this.g.onDidChangeExtensionsConfigs(async () => {
      this.f = await this.g.getUnwantedRecommendations();
      this.a.fire();
    }));
  }
  toggleGlobalIgnoredRecommendation(extensionId, shouldIgnore) {
    extensionId = extensionId.toLowerCase();
    const ignored = this.b.indexOf(extensionId) !== -1;
    if (ignored === shouldIgnore) {
      return;
    }
    this.b = shouldIgnore ? [...this.b, extensionId] : this.b.filter((id2) => id2 !== extensionId);
    this.r(this.b);
    this.c.fire({ extensionId, isRecommended: !shouldIgnore });
    this.a.fire();
  }
  m() {
    const ignoredRecommendations = JSON.parse(this.t);
    return ignoredRecommendations.map((e) => e.toLowerCase());
  }
  n() {
    if (this.t !== this.u()) {
      this.s = void 0;
      this.b = this.m();
      this.a.fire();
    }
  }
  r(ignoredRecommendations) {
    this.t = JSON.stringify(ignoredRecommendations);
  }
  get t() {
    if (!this.s) {
      this.s = this.u();
    }
    return this.s;
  }
  set t(ignoredRecommendationsValue) {
    if (this.t !== ignoredRecommendationsValue) {
      this.s = ignoredRecommendationsValue;
      this.w(ignoredRecommendationsValue);
    }
  }
  u() {
    return this.h.get(ignoredRecommendationsStorageKey, 0, "[]");
  }
  w(value) {
    this.h.store(
      ignoredRecommendationsStorageKey,
      value,
      0,
      0
      /* StorageTarget.USER */
    );
  }
};
$jWb = __decorate([
  __param(0, $FBb),
  __param(1, $jv)
], $jWb);
$SC(
  $BBb,
  $jWb,
  1
  /* InstantiationType.Delayed */
);

// out-build/vs/workbench/services/extensionManagement/common/extensionFeaturesManagemetService.js
var FEATURES_STATE_KEY = "extension.features.state";
var ExtensionFeaturesManagementService = class ExtensionFeaturesManagementService2 extends $3c {
  constructor(g, h3, j) {
    super();
    this.g = g;
    this.h = h3;
    this.j = j;
    this.a = this.B(new $ze());
    this.onDidChangeEnablement = this.a.event;
    this.b = this.B(new $ze());
    this.onDidChangeAccessData = this.b.event;
    this.f = /* @__PURE__ */ new Map();
    this.c = $Wn.as(Extensions3.ExtensionFeaturesRegistry);
    this.f = this.s();
    this.u();
    this.B(g.onDidChangeValue(0, FEATURES_STATE_KEY, this.q)((e) => this.r(e)));
  }
  isEnabled(extension, featureId) {
    const feature = this.c.getExtensionFeature(featureId);
    if (!feature) {
      return false;
    }
    const isDisabled = this.m(extension, featureId)?.disabled;
    if ($Fg(isDisabled)) {
      return !isDisabled;
    }
    const defaultExtensionAccess = feature.access.extensionsList?.[extension._lower];
    if ($Fg(defaultExtensionAccess)) {
      return defaultExtensionAccess;
    }
    return !feature.access.requireUserConsent;
  }
  setEnablement(extension, featureId, enabled) {
    const feature = this.c.getExtensionFeature(featureId);
    if (!feature) {
      throw new Error(`No feature with id '${featureId}'`);
    }
    const featureState = this.n(extension, featureId);
    if (featureState.disabled !== !enabled) {
      featureState.disabled = !enabled;
      this.a.fire({ extension, featureId, enabled });
      this.t();
    }
  }
  getEnablementData(featureId) {
    const result = [];
    const feature = this.c.getExtensionFeature(featureId);
    if (feature) {
      for (const [extension, featuresStateMap] of this.f) {
        const featureState = featuresStateMap.get(featureId);
        if (featureState?.disabled !== void 0) {
          result.push({ extension: new $5z(extension), enabled: !featureState.disabled });
        }
      }
    }
    return result;
  }
  async getAccess(extension, featureId, justification) {
    const feature = this.c.getExtensionFeature(featureId);
    if (!feature) {
      return false;
    }
    const featureState = this.n(extension, featureId);
    if (featureState.disabled) {
      return false;
    }
    if (featureState.disabled === void 0) {
      let enabled = true;
      if (feature.access.requireUserConsent) {
        const extensionDescription = this.j.extensions.find((e) => $5z.equals(e.identifier, extension));
        const confirmationResult = await this.h.confirm({
          title: localize(12741, null, feature.label),
          message: localize(12742, null, extensionDescription?.displayName ?? extension._lower, feature.label),
          detail: justification ?? feature.description,
          custom: true,
          primaryButton: localize(12743, null),
          cancelButton: localize(12744, null)
        });
        enabled = confirmationResult.confirmed;
      }
      this.setEnablement(extension, featureId, enabled);
      if (!enabled) {
        return false;
      }
    }
    const accessTime = /* @__PURE__ */ new Date();
    featureState.accessData.current = {
      accessTimes: [accessTime].concat(featureState.accessData.current?.accessTimes ?? []),
      lastAccessed: accessTime,
      status: featureState.accessData.current?.status
    };
    featureState.accessData.accessTimes = (featureState.accessData.accessTimes ?? []).concat(accessTime);
    this.t();
    this.b.fire({ extension, featureId, accessData: featureState.accessData });
    return true;
  }
  getAllAccessDataForExtension(extension) {
    const result = /* @__PURE__ */ new Map();
    const extensionState = this.f.get(extension._lower);
    if (extensionState) {
      for (const [featureId, featureState] of extensionState) {
        result.set(featureId, featureState.accessData);
      }
    }
    return result;
  }
  getAccessData(extension, featureId) {
    const feature = this.c.getExtensionFeature(featureId);
    if (!feature) {
      return;
    }
    return this.m(extension, featureId)?.accessData;
  }
  setStatus(extension, featureId, status) {
    const feature = this.c.getExtensionFeature(featureId);
    if (!feature) {
      throw new Error(`No feature with id '${featureId}'`);
    }
    const featureState = this.n(extension, featureId);
    featureState.accessData.current = {
      accessTimes: featureState.accessData.current?.accessTimes ?? [],
      lastAccessed: featureState.accessData.current?.lastAccessed ?? /* @__PURE__ */ new Date(),
      status
    };
    this.b.fire({ extension, featureId, accessData: this.getAccessData(extension, featureId) });
  }
  m(extension, featureId) {
    return this.f.get(extension._lower)?.get(featureId);
  }
  n(extension, featureId) {
    let extensionState = this.f.get(extension._lower);
    if (!extensionState) {
      extensionState = /* @__PURE__ */ new Map();
      this.f.set(extension._lower, extensionState);
    }
    let featureState = extensionState.get(featureId);
    if (!featureState) {
      featureState = { accessData: { accessTimes: [] } };
      extensionState.set(featureId, featureState);
    }
    return featureState;
  }
  r(e) {
    if (e.external) {
      const oldState = this.f;
      this.f = this.s();
      for (const extensionId of $Rb([...oldState.keys(), ...this.f.keys()])) {
        const extension = new $5z(extensionId);
        const oldExtensionFeaturesState = oldState.get(extensionId);
        const newExtensionFeaturesState = this.f.get(extensionId);
        for (const featureId of $Rb([...oldExtensionFeaturesState?.keys() ?? [], ...newExtensionFeaturesState?.keys() ?? []])) {
          const isEnabled = this.isEnabled(extension, featureId);
          const wasEnabled = !oldExtensionFeaturesState?.get(featureId)?.disabled;
          if (isEnabled !== wasEnabled) {
            this.a.fire({ extension, featureId, enabled: isEnabled });
          }
          const newAccessData = this.getAccessData(extension, featureId);
          const oldAccessData = oldExtensionFeaturesState?.get(featureId)?.accessData;
          if (!$Pv(newAccessData, oldAccessData)) {
            this.b.fire({ extension, featureId, accessData: newAccessData ?? { accessTimes: [] } });
          }
        }
      }
    }
  }
  s() {
    let data = {};
    const raw = this.g.get(FEATURES_STATE_KEY, 0, "{}");
    try {
      data = JSON.parse(raw);
    } catch (e) {
    }
    const result = /* @__PURE__ */ new Map();
    for (const extensionId in data) {
      const extensionFeatureState = /* @__PURE__ */ new Map();
      const extensionFeatures = data[extensionId];
      for (const featureId in extensionFeatures) {
        const extensionFeature2 = extensionFeatures[featureId];
        extensionFeatureState.set(featureId, {
          disabled: extensionFeature2.disabled,
          accessData: {
            accessTimes: (extensionFeature2.accessTimes ?? []).map((time) => new Date(time))
          }
        });
      }
      result.set(extensionId.toLowerCase(), extensionFeatureState);
    }
    return result;
  }
  t() {
    const data = {};
    this.f.forEach((extensionState, extensionId) => {
      const extensionFeatures = {};
      extensionState.forEach((featureState, featureId) => {
        extensionFeatures[featureId] = {
          disabled: featureState.disabled,
          accessTimes: featureState.accessData.accessTimes.map((time) => time.getTime())
        };
      });
      data[extensionId] = extensionFeatures;
    });
    this.g.store(
      FEATURES_STATE_KEY,
      JSON.stringify(data),
      0,
      0
      /* StorageTarget.USER */
    );
  }
  u() {
    const now = /* @__PURE__ */ new Date();
    const thirtyDaysAgo = new Date(now.setDate(now.getDate() - 30));
    let modified = false;
    for (const [, featuresStateMap] of this.f) {
      for (const [, featureState] of featuresStateMap) {
        const originalLength = featureState.accessData.accessTimes.length;
        featureState.accessData.accessTimes = featureState.accessData.accessTimes.filter((accessTime) => accessTime > thirtyDaysAgo);
        if (featureState.accessData.accessTimes.length !== originalLength) {
          modified = true;
        }
      }
    }
    if (modified) {
      this.t();
    }
  }
};
ExtensionFeaturesManagementService = __decorate([
  __param(0, $jv),
  __param(1, $Yv),
  __param(2, $wN)
], ExtensionFeaturesManagementService);
$SC(
  $wlb,
  ExtensionFeaturesManagementService,
  1
  /* InstantiationType.Delayed */
);

// out-build/vs/workbench/common/notifications.js
var NotificationChangeType;
(function(NotificationChangeType2) {
  NotificationChangeType2[NotificationChangeType2["ADD"] = 0] = "ADD";
  NotificationChangeType2[NotificationChangeType2["CHANGE"] = 1] = "CHANGE";
  NotificationChangeType2[NotificationChangeType2["EXPAND_COLLAPSE"] = 2] = "EXPAND_COLLAPSE";
  NotificationChangeType2[NotificationChangeType2["REMOVE"] = 3] = "REMOVE";
})(NotificationChangeType || (NotificationChangeType = {}));
var StatusMessageChangeType;
(function(StatusMessageChangeType2) {
  StatusMessageChangeType2[StatusMessageChangeType2["ADD"] = 0] = "ADD";
  StatusMessageChangeType2[StatusMessageChangeType2["REMOVE"] = 1] = "REMOVE";
})(StatusMessageChangeType || (StatusMessageChangeType = {}));
var $kWb = class extends $3c {
  constructor(f, g) {
    super();
    this.f = f;
    this.g = g;
    this.a = this.B(new $ze());
    this.onDidClose = this.a.event;
    this.b = this.B(new $ze());
    this.onDidChangeVisibility = this.b.event;
    this.h();
  }
  h() {
    this.B(this.f.onDidChangeVisibility((visible) => this.b.fire(visible)));
    Event2.once(this.f.onDidClose)(() => {
      this.a.fire();
      this.dispose();
    });
  }
  get progress() {
    return this.f.progress;
  }
  updateSeverity(severity) {
    this.f.updateSeverity(severity);
  }
  updateMessage(message) {
    this.f.updateMessage(message);
  }
  updateActions(actions) {
    this.f.updateActions(actions);
  }
  close() {
    this.g(this.f);
    this.dispose();
  }
};
var $lWb = class _$lWb extends $3c {
  constructor() {
    super(...arguments);
    this.b = this.B(new $ze());
    this.onDidChangeNotification = this.b.event;
    this.f = this.B(new $ze());
    this.onDidChangeStatusMessage = this.f.event;
    this.g = this.B(new $ze());
    this.onDidChangeFilter = this.g.event;
    this.h = [];
    this.m = {
      global: NotificationsFilter.OFF,
      sources: /* @__PURE__ */ new Map()
    };
  }
  static {
    this.a = new $RJ();
  }
  get notifications() {
    return this.h;
  }
  get statusMessage() {
    return this.j;
  }
  setFilter(filter) {
    let globalChanged = false;
    if (typeof filter.global === "number") {
      globalChanged = this.m.global !== filter.global;
      this.m.global = filter.global;
    }
    let sourcesChanged = false;
    if (filter.sources) {
      sourcesChanged = !$Mc(this.m.sources, filter.sources);
      this.m.sources = filter.sources;
    }
    if (globalChanged || sourcesChanged) {
      this.g.fire({
        global: globalChanged ? filter.global : void 0,
        sources: sourcesChanged ? filter.sources : void 0
      });
    }
  }
  addNotification(notification) {
    const item = this.s(notification);
    if (!item) {
      return _$lWb.a;
    }
    const duplicate = this.r(item);
    duplicate?.close();
    this.h.splice(0, 0, item);
    this.b.fire({
      item,
      index: 0,
      kind: 0
      /* NotificationChangeType.ADD */
    });
    return new $kWb(item, (item2) => this.n(item2));
  }
  n(item) {
    const liveItem = this.r(item);
    if (liveItem && liveItem !== item) {
      liveItem.close();
    } else {
      item.close();
    }
  }
  r(item) {
    return this.h.find((notification) => notification.equals(item));
  }
  s(notification) {
    const item = $oWb.create(notification, this.m);
    if (!item) {
      return void 0;
    }
    const fireNotificationChangeEvent = (kind, detail2) => {
      const index = this.h.indexOf(item);
      if (index >= 0) {
        this.b.fire({ item, index, kind, detail: detail2 });
      }
    };
    const itemExpansionChangeListener = item.onDidChangeExpansion(() => fireNotificationChangeEvent(
      2
      /* NotificationChangeType.EXPAND_COLLAPSE */
    ));
    const itemContentChangeListener = item.onDidChangeContent((e) => fireNotificationChangeEvent(1, e.kind));
    Event2.once(item.onDidClose)(() => {
      itemExpansionChangeListener.dispose();
      itemContentChangeListener.dispose();
      const index = this.h.indexOf(item);
      if (index >= 0) {
        this.h.splice(index, 1);
        this.b.fire({
          item,
          index,
          kind: 3
          /* NotificationChangeType.REMOVE */
        });
      }
    });
    return item;
  }
  showStatusMessage(message, options3) {
    const item = StatusMessageViewItem.create(message, options3);
    if (!item) {
      return $3c.None;
    }
    this.j = item;
    this.f.fire({ kind: 0, item });
    return $1c(() => {
      if (this.j === item) {
        this.j = void 0;
        this.f.fire({ kind: 1, item });
      }
    });
  }
};
function $mWb(obj) {
  return obj instanceof $oWb;
}
var NotificationViewItemContentChangeKind;
(function(NotificationViewItemContentChangeKind2) {
  NotificationViewItemContentChangeKind2[NotificationViewItemContentChangeKind2["SEVERITY"] = 0] = "SEVERITY";
  NotificationViewItemContentChangeKind2[NotificationViewItemContentChangeKind2["MESSAGE"] = 1] = "MESSAGE";
  NotificationViewItemContentChangeKind2[NotificationViewItemContentChangeKind2["ACTIONS"] = 2] = "ACTIONS";
  NotificationViewItemContentChangeKind2[NotificationViewItemContentChangeKind2["PROGRESS"] = 3] = "PROGRESS";
})(NotificationViewItemContentChangeKind || (NotificationViewItemContentChangeKind = {}));
var $nWb = class extends $3c {
  constructor() {
    super();
    this.b = this.B(new $ze());
    this.onDidChange = this.b.event;
    this.a = /* @__PURE__ */ Object.create(null);
  }
  get state() {
    return this.a;
  }
  infinite() {
    if (this.a.infinite) {
      return;
    }
    this.a.infinite = true;
    this.a.total = void 0;
    this.a.worked = void 0;
    this.a.done = void 0;
    this.b.fire();
  }
  done() {
    if (this.a.done) {
      return;
    }
    this.a.done = true;
    this.a.infinite = void 0;
    this.a.total = void 0;
    this.a.worked = void 0;
    this.b.fire();
  }
  total(value) {
    if (this.a.total === value) {
      return;
    }
    this.a.total = value;
    this.a.infinite = void 0;
    this.a.done = void 0;
    this.b.fire();
  }
  worked(value) {
    if (typeof this.a.worked === "number") {
      this.a.worked += value;
    } else {
      this.a.worked = value;
    }
    this.a.infinite = void 0;
    this.a.done = void 0;
    this.b.fire();
  }
};
var $oWb = class _$oWb extends $3c {
  static {
    this.a = 1e3;
  }
  static create(notification, filter) {
    if (!notification || !notification.message || $kb(notification.message)) {
      return void 0;
    }
    let severity;
    if (typeof notification.severity === "number") {
      severity = notification.severity;
    } else {
      severity = Severity2.Info;
    }
    const message = _$oWb.s(notification.message);
    if (!message) {
      return void 0;
    }
    let actions;
    if (notification.actions) {
      actions = notification.actions;
    } else if ($2m(notification.message)) {
      actions = { primary: notification.message.actions };
    }
    let priority = notification.priority ?? NotificationPriority.DEFAULT;
    if (priority === NotificationPriority.DEFAULT && severity !== Severity2.Error) {
      if (filter.global === NotificationsFilter.ERROR) {
        priority = NotificationPriority.SILENT;
      } else if ($QJ(notification.source) && filter.sources.get(notification.source.id) === NotificationsFilter.ERROR) {
        priority = NotificationPriority.SILENT;
      }
    }
    return new _$oWb(notification.id, severity, notification.sticky, priority, message, notification.source, notification.progress, actions);
  }
  static s(input) {
    let message;
    if (input instanceof Error) {
      message = $1m(input, false);
    } else if (typeof input === "string") {
      message = input;
    }
    if (!message) {
      return void 0;
    }
    const raw = message;
    if (message.length > _$oWb.a) {
      message = `${message.substr(0, _$oWb.a)}...`;
    }
    message = message.replace(/(\r\n|\n|\r)/gm, " ").trim();
    const linkedText = $U3(message);
    return { raw, linkedText, original: input };
  }
  constructor(id2, t, u, w, y, z, progress, actions) {
    super();
    this.id = id2;
    this.t = t;
    this.u = u;
    this.w = w;
    this.y = y;
    this.z = z;
    this.f = false;
    this.j = this.B(new $ze());
    this.onDidChangeExpansion = this.j.event;
    this.m = this.B(new $ze());
    this.onDidClose = this.m.event;
    this.n = this.B(new $ze());
    this.onDidChangeContent = this.n.event;
    this.r = this.B(new $ze());
    this.onDidChangeVisibility = this.r.event;
    if (progress) {
      this.C(progress);
    }
    this.D(actions);
  }
  C(progress) {
    if (progress.infinite) {
      this.progress.infinite();
    } else if (progress.total) {
      this.progress.total(progress.total);
      if (progress.worked) {
        this.progress.worked(progress.worked);
      }
    }
  }
  D(actions = { primary: [], secondary: [] }) {
    this.g = {
      primary: Array.isArray(actions.primary) ? actions.primary : [],
      secondary: Array.isArray(actions.secondary) ? actions.secondary : []
    };
    this.b = actions.primary && actions.primary.length > 0;
  }
  get canCollapse() {
    return !this.F;
  }
  get expanded() {
    return !!this.b;
  }
  get severity() {
    return this.t;
  }
  get sticky() {
    if (this.u) {
      return true;
    }
    const hasActions = this.F;
    if (hasActions && this.t === Severity2.Error || // notification errors with actions are sticky
    !hasActions && this.b || // notifications that got expanded are sticky
    this.h && !this.h.state.done) {
      return true;
    }
    return false;
  }
  get priority() {
    return this.w;
  }
  get F() {
    if (!this.g) {
      return false;
    }
    if (!this.g.primary) {
      return false;
    }
    return this.g.primary.length > 0;
  }
  get hasProgress() {
    return !!this.h;
  }
  get progress() {
    if (!this.h) {
      this.h = this.B(new $nWb());
      this.B(this.h.onDidChange(() => this.n.fire({
        kind: 3
        /* NotificationViewItemContentChangeKind.PROGRESS */
      })));
    }
    return this.h;
  }
  get message() {
    return this.y;
  }
  get source() {
    return typeof this.z === "string" ? this.z : this.z ? this.z.label : void 0;
  }
  get sourceId() {
    return this.z && typeof this.z !== "string" && "id" in this.z ? this.z.id : void 0;
  }
  get actions() {
    return this.g;
  }
  get visible() {
    return this.f;
  }
  updateSeverity(severity) {
    if (severity === this.t) {
      return;
    }
    this.t = severity;
    this.n.fire({
      kind: 0
      /* NotificationViewItemContentChangeKind.SEVERITY */
    });
  }
  updateMessage(input) {
    const message = _$oWb.s(input);
    if (!message || message.raw === this.y.raw) {
      return;
    }
    this.y = message;
    this.n.fire({
      kind: 1
      /* NotificationViewItemContentChangeKind.MESSAGE */
    });
  }
  updateActions(actions) {
    this.D(actions);
    this.n.fire({
      kind: 2
      /* NotificationViewItemContentChangeKind.ACTIONS */
    });
  }
  updateVisibility(visible) {
    if (this.f !== visible) {
      this.f = visible;
      this.r.fire(visible);
    }
  }
  expand() {
    if (this.b || !this.canCollapse) {
      return;
    }
    this.b = true;
    this.j.fire();
  }
  collapse(skipEvents) {
    if (!this.b || !this.canCollapse) {
      return;
    }
    this.b = false;
    if (!skipEvents) {
      this.j.fire();
    }
  }
  toggle() {
    if (this.b) {
      this.collapse();
    } else {
      this.expand();
    }
  }
  close() {
    this.m.fire();
    this.dispose();
  }
  equals(other) {
    if (this.hasProgress || other.hasProgress) {
      return false;
    }
    if (typeof this.id === "string" || typeof other.id === "string") {
      return this.id === other.id;
    }
    if (typeof this.z === "object") {
      if (this.z.label !== other.source || this.z.id !== other.sourceId) {
        return false;
      }
    } else if (this.z !== other.source) {
      return false;
    }
    if (this.y.raw !== other.message.raw) {
      return false;
    }
    const primaryActions = this.g && this.g.primary || [];
    const otherPrimaryActions = other.actions && other.actions.primary || [];
    return $zb(primaryActions, otherPrimaryActions, (action, otherAction) => action.id + action.label === otherAction.id + otherAction.label);
  }
};
var $pWb = class _$pWb extends $Um {
  constructor(id2, choice) {
    super(id2, choice.label, void 0, true, async () => {
      choice.run();
      this.a.fire();
    });
    this.a = this.B(new $ze());
    this.onDidRun = this.a.event;
    this.b = !!choice.keepOpen;
    this.f = !choice.isSecondary && choice.menu ? choice.menu.map((c, index) => new _$pWb(`${id2}.${index}`, c)) : void 0;
  }
  get menu() {
    return this.f;
  }
  get keepOpen() {
    return this.b;
  }
};
var StatusMessageViewItem = class {
  static create(notification, options3) {
    if (!notification || $kb(notification)) {
      return void 0;
    }
    let message;
    if (notification instanceof Error) {
      message = $1m(notification, false);
    } else if (typeof notification === "string") {
      message = notification;
    }
    if (!message) {
      return void 0;
    }
    return { message, options: options3 };
  }
};

// out-build/vs/workbench/services/notification/common/notificationService.js
var $qWb_1;
var $qWb = class $qWb2 extends $3c {
  static {
    $qWb_1 = this;
  }
  constructor(c) {
    super();
    this.c = c;
    this.model = this.B(new $lWb());
    this.a = this.B(new $ze());
    this.onDidAddNotification = this.a.event;
    this.b = this.B(new $ze());
    this.onDidRemoveNotification = this.b.event;
    this.j = this.B(new $ze());
    this.onDidChangeFilter = this.j.event;
    this.m = this.c.getBoolean($qWb_1.g, -1, false);
    this.n = (() => {
      const map = /* @__PURE__ */ new Map();
      for (const sourceFilter of this.c.getObject($qWb_1.h, -1, [])) {
        map.set(sourceFilter.id, sourceFilter);
      }
      return map;
    })();
    this.t();
    this.f();
  }
  f() {
    this.B(this.model.onDidChangeNotification((e) => {
      switch (e.kind) {
        case 0:
        case 3: {
          const source = typeof e.item.sourceId === "string" && typeof e.item.source === "string" ? { id: e.item.sourceId, label: e.item.source } : e.item.source;
          const notification = {
            message: e.item.message.original,
            severity: e.item.severity,
            source,
            priority: e.item.priority
          };
          if (e.kind === 0) {
            if ($QJ(source)) {
              if (!this.n.has(source.id)) {
                this.setFilter({ ...source, filter: NotificationsFilter.OFF });
              } else {
                this.r(source);
              }
            }
            this.a.fire(notification);
          }
          if (e.kind === 3) {
            this.b.fire(notification);
          }
          break;
        }
      }
    }));
  }
  static {
    this.g = "notifications.doNotDisturbMode";
  }
  static {
    this.h = "notifications.perSourceDoNotDisturbMode";
  }
  setFilter(filter) {
    if (typeof filter === "number") {
      if (this.m === (filter === NotificationsFilter.ERROR)) {
        return;
      }
      this.m = filter === NotificationsFilter.ERROR;
      this.c.store(
        $qWb_1.g,
        this.m,
        -1,
        1
        /* StorageTarget.MACHINE */
      );
      this.t();
      this.j.fire();
    } else {
      const existing = this.n.get(filter.id);
      if (existing?.filter === filter.filter && existing.label === filter.label) {
        return;
      }
      this.n.set(filter.id, { id: filter.id, label: filter.label, filter: filter.filter });
      this.s();
      this.t();
    }
  }
  getFilter(source) {
    if (source) {
      return this.n.get(source.id)?.filter ?? NotificationsFilter.OFF;
    }
    return this.m ? NotificationsFilter.ERROR : NotificationsFilter.OFF;
  }
  r(source) {
    const existing = this.n.get(source.id);
    if (!existing) {
      return;
    }
    if (existing.label !== source.label) {
      this.n.set(source.id, { id: source.id, label: source.label, filter: existing.filter });
      this.s();
    }
  }
  s() {
    this.c.store(
      $qWb_1.h,
      JSON.stringify([...this.n.values()]),
      -1,
      1
      /* StorageTarget.MACHINE */
    );
  }
  getFilters() {
    return [...this.n.values()];
  }
  t() {
    this.model.setFilter({
      global: this.m ? NotificationsFilter.ERROR : NotificationsFilter.OFF,
      sources: new Map([...this.n.values()].map((source) => [source.id, source.filter]))
    });
  }
  removeFilter(sourceId) {
    if (this.n.delete(sourceId)) {
      this.s();
      this.t();
    }
  }
  //#endregion
  info(message) {
    if (Array.isArray(message)) {
      for (const messageEntry of message) {
        this.info(messageEntry);
      }
      return;
    }
    this.model.addNotification({ severity: Severity2.Info, message });
  }
  warn(message) {
    if (Array.isArray(message)) {
      for (const messageEntry of message) {
        this.warn(messageEntry);
      }
      return;
    }
    this.model.addNotification({ severity: Severity2.Warning, message });
  }
  error(message) {
    if (Array.isArray(message)) {
      for (const messageEntry of message) {
        this.error(messageEntry);
      }
      return;
    }
    this.model.addNotification({ severity: Severity2.Error, message });
  }
  notify(notification) {
    const toDispose = new $2c();
    if (notification.neverShowAgain) {
      const scope = this.u(notification.neverShowAgain);
      const id2 = notification.neverShowAgain.id;
      if (this.c.getBoolean(id2, scope)) {
        return new $RJ();
      }
      const neverShowAgainAction = toDispose.add(new $Um("workbench.notification.neverShowAgain", localize(13025, null), void 0, true, async () => {
        handle2.close();
        this.c.store(
          id2,
          true,
          scope,
          0
          /* StorageTarget.USER */
        );
      }));
      const actions = {
        primary: notification.actions?.primary || [],
        secondary: notification.actions?.secondary || []
      };
      if (!notification.neverShowAgain.isSecondary) {
        actions.primary = [neverShowAgainAction, ...actions.primary];
      } else {
        actions.secondary = [...actions.secondary, neverShowAgainAction];
      }
      notification.actions = actions;
    }
    const handle2 = this.model.addNotification(notification);
    Event2.once(handle2.onDidClose)(() => toDispose.dispose());
    return handle2;
  }
  u(options3) {
    switch (options3.scope) {
      case NeverShowAgainScope.APPLICATION:
        return -1;
      case NeverShowAgainScope.PROFILE:
        return 0;
      case NeverShowAgainScope.WORKSPACE:
        return 1;
      default:
        return -1;
    }
  }
  prompt(severity, message, choices, options3) {
    const toDispose = new $2c();
    if (options3?.neverShowAgain) {
      const scope = this.u(options3.neverShowAgain);
      const id2 = options3.neverShowAgain.id;
      if (this.c.getBoolean(id2, scope)) {
        return new $RJ();
      }
      const neverShowAgainChoice = {
        label: localize(13026, null),
        run: () => this.c.store(
          id2,
          true,
          scope,
          0
          /* StorageTarget.USER */
        ),
        isSecondary: options3.neverShowAgain.isSecondary
      };
      if (!options3.neverShowAgain.isSecondary) {
        choices = [neverShowAgainChoice, ...choices];
      } else {
        choices = [...choices, neverShowAgainChoice];
      }
    }
    let choiceClicked = false;
    const primaryActions = [];
    const secondaryActions = [];
    choices.forEach((choice, index) => {
      const action = new $pWb(`workbench.dialog.choice.${index}`, choice);
      if (!choice.isSecondary) {
        primaryActions.push(action);
      } else {
        secondaryActions.push(action);
      }
      toDispose.add(action.onDidRun(() => {
        choiceClicked = true;
        if (!choice.keepOpen) {
          handle2.close();
        }
      }));
      toDispose.add(action);
    });
    const actions = { primary: primaryActions, secondary: secondaryActions };
    const handle2 = this.notify({ severity, message, actions, sticky: options3?.sticky, priority: options3?.priority });
    Event2.once(handle2.onDidClose)(() => {
      toDispose.dispose();
      if (options3 && typeof options3.onCancel === "function" && !choiceClicked) {
        options3.onCancel();
      }
    });
    return handle2;
  }
  status(message, options3) {
    return this.model.showStatusMessage(message, options3);
  }
};
$qWb = $qWb_1 = __decorate([
  __param(0, $jv)
], $qWb);
$SC(
  $PJ,
  $qWb,
  1
  /* InstantiationType.Delayed */
);

// out-build/vs/workbench/services/userDataSync/common/userDataSyncUtil.js
var UserDataSyncUtilService = class UserDataSyncUtilService2 {
  constructor(a, b, c, d) {
    this.a = a;
    this.b = b;
    this.c = c;
    this.d = d;
  }
  async resolveDefaultCoreIgnoredSettings() {
    return $LBb(true);
  }
  async resolveUserBindings(userBindings) {
    const keys = {};
    for (const userbinding of userBindings) {
      keys[userbinding] = this.a.resolveUserBinding(userbinding).map((part) => part.getUserSettingsLabel()).join(" ");
    }
    return keys;
  }
  async resolveFormattingOptions(resource) {
    try {
      const modelReference = await this.b.createModelReference(resource);
      const { insertSpaces, tabSize } = modelReference.object.textEditorModel.getOptions();
      const eol = modelReference.object.textEditorModel.getEOL();
      modelReference.dispose();
      return { eol, insertSpaces, tabSize };
    } catch (e) {
    }
    return {
      eol: this.c.getEOL(resource),
      insertSpaces: !!this.d.getValue(resource, "editor.insertSpaces"),
      tabSize: this.d.getValue(resource, "editor.tabSize")
    };
  }
};
UserDataSyncUtilService = __decorate([
  __param(0, $Ty),
  __param(1, $oG),
  __param(2, $AG),
  __param(3, $zG)
], UserDataSyncUtilService);
$SC(
  $0Bb,
  UserDataSyncUtilService,
  1
  /* InstantiationType.Delayed */
);

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

// out-build/vs/platform/userDataSync/common/settingsMerge.js
function $uWb(defaultIgnoredSettings, configurationService, settingsContent) {
  let value = [];
  if (settingsContent) {
    value = getIgnoredSettingsFromContent(settingsContent);
  } else {
    value = getIgnoredSettingsFromConfig(configurationService);
  }
  const added = [], removed = [...$KBb()];
  if (Array.isArray(value)) {
    for (const key2 of value) {
      if (key2.startsWith("-")) {
        removed.push(key2.substring(1));
      } else {
        added.push(key2);
      }
    }
  }
  return $Rb([...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 = $yw(settingsContent);
  return parsed ? parsed["settingsSync.ignoredSettings"] || parsed["sync.ignoredSettings"] || [] : [];
}
function $wWb(targetContent, sourceContent, ignoredSettings, formattingOptions) {
  if (ignoredSettings.length) {
    const sourceTree = parseSettings(sourceContent);
    const source = $yw(sourceContent) || {};
    const target = $yw(targetContent);
    if (!target) {
      return targetContent;
    }
    const settingsToAdd = [];
    for (const key2 of ignoredSettings) {
      const sourceValue = source[key2];
      const targetValue = target[key2];
      if (sourceValue === void 0) {
        targetContent = edit2(targetContent, [key2], void 0, formattingOptions);
      } else if (targetValue !== void 0) {
        targetContent = edit2(targetContent, [key2], sourceValue, formattingOptions);
      } else {
        settingsToAdd.push(findSettingNode(key2, sourceTree));
      }
    }
    settingsToAdd.sort((a, b) => a.startOffset - b.startOffset);
    settingsToAdd.forEach((s) => targetContent = $zWb(s.setting.key, sourceContent, targetContent, formattingOptions));
  }
  return targetContent;
}
function $xWb(originalLocalContent, originalRemoteContent, baseContent, ignoredSettings, resolvedConflicts, formattingOptions) {
  const localContentWithoutIgnoredSettings = $wWb(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: $wWb(originalRemoteContent, originalLocalContent, ignoredSettings, formattingOptions), remoteContent: null, hasConflicts: false };
  }
  if (baseContent === null && $yWb(originalLocalContent)) {
    const localContent2 = areSame(originalLocalContent, originalRemoteContent, ignoredSettings) ? null : $wWb(originalRemoteContent, originalLocalContent, ignoredSettings, formattingOptions);
    return { conflictsSettings: [], localContent: localContent2, remoteContent: null, hasConflicts: false };
  }
  let localContent = originalLocalContent;
  let remoteContent = originalRemoteContent;
  const local = $yw(originalLocalContent);
  const remote = $yw(originalRemoteContent);
  const base = baseContent ? $yw(baseContent) : null;
  const ignored = ignoredSettings.reduce((set, key2) => {
    set.add(key2);
    return set;
  }, /* @__PURE__ */ new Set());
  const localToRemote = compare2(local, remote, ignored);
  const baseToLocal = compare2(base, local, ignored);
  const baseToRemote = compare2(base, remote, ignored);
  const conflicts = /* @__PURE__ */ new Map();
  const handledConflicts = /* @__PURE__ */ new Set();
  const handleConflict = (conflictKey) => {
    handledConflicts.add(conflictKey);
    const resolvedConflict = resolvedConflicts.filter(({ key: key2 }) => key2 === conflictKey)[0];
    if (resolvedConflict) {
      localContent = edit2(localContent, [conflictKey], resolvedConflict.value, formattingOptions);
      remoteContent = edit2(remoteContent, [conflictKey], resolvedConflict.value, formattingOptions);
    } else {
      conflicts.set(conflictKey, { key: conflictKey, localValue: local[conflictKey], remoteValue: remote[conflictKey] });
    }
  };
  for (const key2 of baseToLocal.removed.values()) {
    if (baseToRemote.updated.has(key2)) {
      handleConflict(key2);
    } else {
      remoteContent = edit2(remoteContent, [key2], void 0, formattingOptions);
    }
  }
  for (const key2 of baseToRemote.removed.values()) {
    if (handledConflicts.has(key2)) {
      continue;
    }
    if (baseToLocal.updated.has(key2)) {
      handleConflict(key2);
    } else {
      localContent = edit2(localContent, [key2], void 0, formattingOptions);
    }
  }
  for (const key2 of baseToLocal.updated.values()) {
    if (handledConflicts.has(key2)) {
      continue;
    }
    if (baseToRemote.updated.has(key2)) {
      if (localToRemote.updated.has(key2)) {
        handleConflict(key2);
      }
    } else {
      remoteContent = edit2(remoteContent, [key2], local[key2], formattingOptions);
    }
  }
  for (const key2 of baseToRemote.updated.values()) {
    if (handledConflicts.has(key2)) {
      continue;
    }
    if (baseToLocal.updated.has(key2)) {
      if (localToRemote.updated.has(key2)) {
        handleConflict(key2);
      }
    } else {
      localContent = edit2(localContent, [key2], remote[key2], formattingOptions);
    }
  }
  for (const key2 of baseToLocal.added.values()) {
    if (handledConflicts.has(key2)) {
      continue;
    }
    if (baseToRemote.added.has(key2)) {
      if (localToRemote.updated.has(key2)) {
        handleConflict(key2);
      }
    } else {
      remoteContent = $zWb(key2, localContent, remoteContent, formattingOptions);
    }
  }
  for (const key2 of baseToRemote.added.values()) {
    if (handledConflicts.has(key2)) {
      continue;
    }
    if (baseToLocal.added.has(key2)) {
      if (localToRemote.updated.has(key2)) {
        handleConflict(key2);
      }
    } else {
      localContent = $zWb(key2, remoteContent, localContent, formattingOptions);
    }
  }
  const hasConflicts = conflicts.size > 0 || !areSame(localContent, remoteContent, ignoredSettings);
  const hasLocalChanged = hasConflicts || !areSame(localContent, originalLocalContent, []);
  const hasRemoteChanged = hasConflicts || !areSame(remoteContent, originalRemoteContent, []);
  return { localContent: hasLocalChanged ? localContent : null, remoteContent: hasRemoteChanged ? remoteContent : null, conflictsSettings: [...conflicts.values()], hasConflicts };
}
function areSame(localContent, remoteContent, ignoredSettings) {
  if (localContent === remoteContent) {
    return true;
  }
  const local = $yw(localContent);
  const remote = $yw(remoteContent);
  const ignored = ignoredSettings.reduce((set, key2) => {
    set.add(key2);
    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 (!$Pv(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 $yWb(content) {
  if (content) {
    const nodes = parseSettings(content);
    return nodes.length === 0;
  }
  return true;
}
function compare2(from, to, ignored) {
  const fromKeys = from ? Object.keys(from).filter((key2) => !ignored.has(key2)) : [];
  const toKeys = Object.keys(to).filter((key2) => !ignored.has(key2));
  const added = toKeys.filter((key2) => !fromKeys.includes(key2)).reduce((r2, key2) => {
    r2.add(key2);
    return r2;
  }, /* @__PURE__ */ new Set());
  const removed = fromKeys.filter((key2) => !toKeys.includes(key2)).reduce((r2, key2) => {
    r2.add(key2);
    return r2;
  }, /* @__PURE__ */ new Set());
  const updated = /* @__PURE__ */ new Set();
  if (from) {
    for (const key2 of fromKeys) {
      if (removed.has(key2)) {
        continue;
      }
      const value1 = from[key2];
      const value2 = to[key2];
      if (!$Pv(value1, value2)) {
        updated.add(key2);
      }
    }
  }
  return { added, removed, updated };
}
function $zWb(key2, sourceContent, targetContent, formattingOptions) {
  const source = $yw(sourceContent);
  const sourceTree = parseSettings(sourceContent);
  const targetTree = parseSettings(targetContent);
  const insertLocation = getInsertLocation(key2, sourceTree, targetTree);
  return insertAtLocation(targetContent, key2, source[key2], insertLocation, targetTree, formattingOptions);
}
function getInsertLocation(key2, sourceTree, targetTree) {
  const sourceNodeIndex = sourceTree.findIndex((node) => node.setting?.key === key2);
  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, key2, value, location3, tree, formattingOptions) {
  let edits;
  if (location3.index === -1) {
    edits = $Xw(content, [key2], value, formattingOptions);
  } else {
    edits = getEditToInsertAtLocation(content, key2, value, location3, tree, formattingOptions).map((edit3) => $Yw(content, edit3, formattingOptions)[0]);
  }
  return $1w(content, edits);
}
function getEditToInsertAtLocation(content, key2, value, location3, tree, formattingOptions) {
  const newProperty = `${JSON.stringify(key2)}: ${JSON.stringify(value)}`;
  const eol = $Uw(formattingOptions, content);
  const node = tree[location3.index];
  if (location3.insertAfter) {
    const edits = [];
    if (node.setting) {
      edits.push({ offset: node.endOffset, length: 0, content: "," + newProperty });
    } else {
      const nextSettingNode = findNextSettingNode(location3.index, tree);
      const previousSettingNode = findPreviousSettingNode(location3.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[location3.index - 1] && !tree[location3.index - 1].setting ? eol : "") + newProperty + (findNextSettingNode(location3.index, tree) ? "," : "") + eol;
    return [{ offset: node.startOffset, length: 0, content: content2 }];
  }
}
function findSettingNode(key2, tree) {
  return tree.filter((node) => node.setting?.key === key2)[0];
}
function findPreviousSettingNode(index, tree) {
  for (let i2 = index - 1; i2 >= 0; i2--) {
    if (tree[i2].setting) {
      return tree[i2];
    }
  }
  return void 0;
}
function findNextSettingNode(index, tree) {
  for (let i2 = index + 1; i2 < tree.length; i2++) {
    if (tree[i2].setting) {
      return tree[i2];
    }
  }
  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 key2;
  const visitor = {
    onObjectBegin: (offset) => {
      hierarchyLevel++;
    },
    onObjectProperty: (name, offset, length) => {
      if (hierarchyLevel === 0) {
        startOffset = offset;
        key2 = name;
      }
    },
    onObjectEnd: (offset, length) => {
      hierarchyLevel--;
      if (hierarchyLevel === 0) {
        nodes.push({
          startOffset,
          endOffset: offset + length,
          value: content.substring(startOffset, offset + length),
          setting: {
            key: key2,
            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: key2,
            commaOffset: void 0
          }
        });
      }
    },
    onLiteralValue: (value, offset, length) => {
      if (hierarchyLevel === 0) {
        nodes.push({
          startOffset,
          endOffset: offset + length,
          value: content.substring(startOffset, offset + length),
          setting: {
            key: key2,
            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)
        });
      }
    }
  };
  $Fw(content, visitor);
  return nodes;
}

// out-build/vs/workbench/services/userDataProfile/browser/settingsResource.js
var $AWb = class $AWb2 {
  constructor(a, b, c) {
    this.a = a;
    this.b = b;
    this.c = c;
  }
  async initialize(content) {
    const settingsContent = JSON.parse(content);
    if (settingsContent.settings === null) {
      this.c.info(`Initializing Profile: No settings to apply...`);
      return;
    }
    await this.b.writeFile(this.a.currentProfile.settingsResource, $Ci.fromString(settingsContent.settings));
  }
};
$AWb = __decorate([
  __param(0, $gT),
  __param(1, $km),
  __param(2, $wn)
], $AWb);
var $BWb = class $BWb2 {
  constructor(a, b, c) {
    this.a = a;
    this.b = b;
    this.c = c;
  }
  async getContent(profile) {
    const settingsContent = await this.getSettingsContent(profile);
    return JSON.stringify(settingsContent);
  }
  async getSettingsContent(profile) {
    const localContent = await this.e(profile);
    if (localContent === null) {
      return { settings: null };
    } else {
      const ignoredSettings = this.d();
      const formattingOptions = await this.b.resolveFormattingOptions(profile.settingsResource);
      const settings = $wWb(localContent || "{}", "{}", ignoredSettings, formattingOptions);
      return { settings };
    }
  }
  async apply(content, profile) {
    const settingsContent = JSON.parse(content);
    if (settingsContent.settings === null) {
      this.c.info(`Importing Profile (${profile.name}): No settings to apply...`);
      return;
    }
    const localSettingsContent = await this.e(profile);
    const formattingOptions = await this.b.resolveFormattingOptions(profile.settingsResource);
    const contentToUpdate = $wWb(settingsContent.settings, localSettingsContent || "{}", this.d(), formattingOptions);
    await this.a.writeFile(profile.settingsResource, $Ci.fromString(contentToUpdate));
  }
  d() {
    const allSettings = $Wn.as($Ht.Configuration).getConfigurationProperties();
    const ignoredSettings = Object.keys(allSettings).filter(
      (key2) => allSettings[key2]?.scope === 2 || allSettings[key2]?.scope === 6
      /* ConfigurationScope.MACHINE_OVERRIDABLE */
    );
    return ignoredSettings;
  }
  async e(profile) {
    try {
      const content = await this.a.readFile(profile.settingsResource);
      return content.value.toString();
    } catch (error) {
      if (error instanceof $Fm && error.fileOperationResult === 1) {
        return null;
      } else {
        throw error;
      }
    }
  }
};
$BWb = __decorate([
  __param(0, $km),
  __param(1, $0Bb),
  __param(2, $wn)
], $BWb);
var $CWb = class $CWb2 {
  constructor(a, b, c) {
    this.a = a;
    this.b = b;
    this.c = c;
    this.type = "settings";
    this.handle = "settings";
    this.label = { label: localize(13370, null) };
    this.collapsibleState = TreeItemCollapsibleState2.Expanded;
  }
  async getChildren() {
    return [{
      handle: this.a.settingsResource.toString(),
      resourceUri: this.a.settingsResource,
      collapsibleState: TreeItemCollapsibleState2.None,
      parent: this,
      accessibilityInformation: {
        label: this.b.extUri.basename(this.a.settingsResource)
      },
      command: {
        id: $$ub,
        title: "",
        arguments: [this.a.settingsResource, void 0, void 0]
      }
    }];
  }
  async hasContent() {
    const settingsContent = await this.c.createInstance($BWb).getSettingsContent(this.a);
    return settingsContent.settings !== null;
  }
  async getContent() {
    return this.c.createInstance($BWb).getContent(this.a);
  }
  isFromDefaultProfile() {
    return !this.a.isDefault && !!this.a.useDefaultFlags?.settings;
  }
};
$CWb = __decorate([
  __param(1, $vl),
  __param(2, $Pk)
], $CWb);

// out-build/vs/workbench/services/userDataProfile/browser/keybindingsResource.js
var $DWb = class $DWb2 {
  constructor(a, b, c) {
    this.a = a;
    this.b = b;
    this.c = c;
  }
  async initialize(content) {
    const keybindingsContent = JSON.parse(content);
    if (keybindingsContent.keybindings === null) {
      this.c.info(`Initializing Profile: No keybindings to apply...`);
      return;
    }
    await this.b.writeFile(this.a.currentProfile.keybindingsResource, $Ci.fromString(keybindingsContent.keybindings));
  }
};
$DWb = __decorate([
  __param(0, $gT),
  __param(1, $km),
  __param(2, $wn)
], $DWb);
var $EWb = class $EWb2 {
  constructor(a, b) {
    this.a = a;
    this.b = b;
  }
  async getContent(profile) {
    const keybindingsContent = await this.getKeybindingsResourceContent(profile);
    return JSON.stringify(keybindingsContent);
  }
  async getKeybindingsResourceContent(profile) {
    const keybindings = await this.c(profile);
    return { keybindings, platform: $x };
  }
  async apply(content, profile) {
    const keybindingsContent = JSON.parse(content);
    if (keybindingsContent.keybindings === null) {
      this.b.info(`Importing Profile (${profile.name}): No keybindings to apply...`);
      return;
    }
    await this.a.writeFile(profile.keybindingsResource, $Ci.fromString(keybindingsContent.keybindings));
  }
  async c(profile) {
    try {
      const content = await this.a.readFile(profile.keybindingsResource);
      return content.value.toString();
    } catch (error) {
      if (error instanceof $Fm && error.fileOperationResult === 1) {
        return null;
      } else {
        throw error;
      }
    }
  }
};
$EWb = __decorate([
  __param(0, $km),
  __param(1, $wn)
], $EWb);
var $FWb = class $FWb2 {
  constructor(a, b, c) {
    this.a = a;
    this.b = b;
    this.c = c;
    this.type = "keybindings";
    this.handle = "keybindings";
    this.label = { label: localize(13369, null) };
    this.collapsibleState = TreeItemCollapsibleState2.Expanded;
  }
  isFromDefaultProfile() {
    return !this.a.isDefault && !!this.a.useDefaultFlags?.keybindings;
  }
  async getChildren() {
    return [{
      handle: this.a.keybindingsResource.toString(),
      resourceUri: this.a.keybindingsResource,
      collapsibleState: TreeItemCollapsibleState2.None,
      parent: this,
      accessibilityInformation: {
        label: this.b.extUri.basename(this.a.settingsResource)
      },
      command: {
        id: $$ub,
        title: "",
        arguments: [this.a.keybindingsResource, void 0, void 0]
      }
    }];
  }
  async hasContent() {
    const keybindingsContent = await this.c.createInstance($EWb).getKeybindingsResourceContent(this.a);
    return keybindingsContent.keybindings !== null;
  }
  async getContent() {
    return this.c.createInstance($EWb).getContent(this.a);
  }
};
$FWb = __decorate([
  __param(1, $vl),
  __param(2, $Pk)
], $FWb);

// out-build/vs/workbench/services/userDataProfile/browser/snippetsResource.js
var $GWb = class $GWb2 {
  constructor(a, b, c) {
    this.a = a;
    this.b = b;
    this.c = c;
  }
  async initialize(content) {
    const snippetsContent = JSON.parse(content);
    for (const key2 in snippetsContent.snippets) {
      const resource = this.c.extUri.joinPath(this.a.currentProfile.snippetsHome, key2);
      await this.b.writeFile(resource, $Ci.fromString(snippetsContent.snippets[key2]));
    }
  }
};
$GWb = __decorate([
  __param(0, $gT),
  __param(1, $km),
  __param(2, $vl)
], $GWb);
var $HWb = class $HWb2 {
  constructor(a, b) {
    this.a = a;
    this.b = b;
  }
  async getContent(profile, excluded) {
    const snippets = await this.c(profile, excluded);
    return JSON.stringify({ snippets });
  }
  async apply(content, profile) {
    const snippetsContent = JSON.parse(content);
    for (const key2 in snippetsContent.snippets) {
      const resource = this.b.extUri.joinPath(profile.snippetsHome, key2);
      await this.a.writeFile(resource, $Ci.fromString(snippetsContent.snippets[key2]));
    }
  }
  async c(profile, excluded) {
    const snippets = {};
    const snippetsResources = await this.getSnippetsResources(profile, excluded);
    for (const resource of snippetsResources) {
      const key2 = this.b.extUri.relativePath(profile.snippetsHome, resource);
      const content = await this.a.readFile(resource);
      snippets[key2] = content.value.toString();
    }
    return snippets;
  }
  async getSnippetsResources(profile, excluded) {
    const snippets = [];
    let stat;
    try {
      stat = await this.a.resolve(profile.snippetsHome);
    } catch (e) {
      if (e instanceof $Fm && e.fileOperationResult === 1) {
        return snippets;
      } else {
        throw e;
      }
    }
    for (const { resource } of stat.children || []) {
      if (excluded?.has(resource)) {
        continue;
      }
      const extension = this.b.extUri.extname(resource);
      if (extension === ".json" || extension === ".code-snippets") {
        snippets.push(resource);
      }
    }
    return snippets;
  }
};
$HWb = __decorate([
  __param(0, $km),
  __param(1, $vl)
], $HWb);
var $IWb = class $IWb2 {
  constructor(b, c, d) {
    this.b = b;
    this.c = c;
    this.d = d;
    this.type = "snippets";
    this.handle = this.b.snippetsHome.toString();
    this.label = { label: localize(13371, null) };
    this.collapsibleState = TreeItemCollapsibleState2.Collapsed;
    this.a = new $Fc();
  }
  async getChildren() {
    const snippetsResources = await this.c.createInstance($HWb).getSnippetsResources(this.b);
    const that = this;
    return snippetsResources.map((resource) => ({
      handle: resource.toString(),
      parent: that,
      resourceUri: resource,
      collapsibleState: TreeItemCollapsibleState2.None,
      accessibilityInformation: {
        label: this.d.extUri.basename(resource)
      },
      checkbox: that.checkbox ? {
        get isChecked() {
          return !that.a.has(resource);
        },
        set isChecked(value) {
          if (value) {
            that.a.delete(resource);
          } else {
            that.a.add(resource);
          }
        },
        accessibilityInformation: {
          label: localize(13372, null, this.d.extUri.basename(resource))
        }
      } : void 0,
      command: {
        id: $$ub,
        title: "",
        arguments: [resource, void 0, void 0]
      }
    }));
  }
  async hasContent() {
    const snippetsResources = await this.c.createInstance($HWb).getSnippetsResources(this.b);
    return snippetsResources.length > 0;
  }
  async getContent() {
    return this.c.createInstance($HWb).getContent(this.b, this.a);
  }
  isFromDefaultProfile() {
    return !this.b.isDefault && !!this.b.useDefaultFlags?.snippets;
  }
};
$IWb = __decorate([
  __param(1, $Pk),
  __param(2, $vl)
], $IWb);

// out-build/vs/workbench/services/userDataProfile/browser/tasksResource.js
var $JWb = class $JWb2 {
  constructor(a, b, c) {
    this.a = a;
    this.b = b;
    this.c = c;
  }
  async initialize(content) {
    const tasksContent = JSON.parse(content);
    if (!tasksContent.tasks) {
      this.c.info(`Initializing Profile: No tasks to apply...`);
      return;
    }
    await this.b.writeFile(this.a.currentProfile.tasksResource, $Ci.fromString(tasksContent.tasks));
  }
};
$JWb = __decorate([
  __param(0, $gT),
  __param(1, $km),
  __param(2, $wn)
], $JWb);
var $KWb = class $KWb2 {
  constructor(a, b) {
    this.a = a;
    this.b = b;
  }
  async getContent(profile) {
    const tasksContent = await this.getTasksResourceContent(profile);
    return JSON.stringify(tasksContent);
  }
  async getTasksResourceContent(profile) {
    const tasksContent = await this.c(profile);
    return { tasks: tasksContent };
  }
  async apply(content, profile) {
    const tasksContent = JSON.parse(content);
    if (!tasksContent.tasks) {
      this.b.info(`Importing Profile (${profile.name}): No tasks to apply...`);
      return;
    }
    await this.a.writeFile(profile.tasksResource, $Ci.fromString(tasksContent.tasks));
  }
  async c(profile) {
    try {
      const content = await this.a.readFile(profile.tasksResource);
      return content.value.toString();
    } catch (error) {
      if (error instanceof $Fm && error.fileOperationResult === 1) {
        return null;
      } else {
        throw error;
      }
    }
  }
};
$KWb = __decorate([
  __param(0, $km),
  __param(1, $wn)
], $KWb);
var $LWb = class $LWb2 {
  constructor(a, b, c) {
    this.a = a;
    this.b = b;
    this.c = c;
    this.type = "tasks";
    this.handle = "tasks";
    this.label = { label: localize(13373, null) };
    this.collapsibleState = TreeItemCollapsibleState2.Expanded;
  }
  async getChildren() {
    return [{
      handle: this.a.tasksResource.toString(),
      resourceUri: this.a.tasksResource,
      collapsibleState: TreeItemCollapsibleState2.None,
      parent: this,
      accessibilityInformation: {
        label: this.b.extUri.basename(this.a.settingsResource)
      },
      command: {
        id: $$ub,
        title: "",
        arguments: [this.a.tasksResource, void 0, void 0]
      }
    }];
  }
  async hasContent() {
    const tasksContent = await this.c.createInstance($KWb).getTasksResourceContent(this.a);
    return tasksContent.tasks !== null;
  }
  async getContent() {
    return this.c.createInstance($KWb).getContent(this.a);
  }
  isFromDefaultProfile() {
    return !this.a.isDefault && !!this.a.useDefaultFlags?.tasks;
  }
};
$LWb = __decorate([
  __param(1, $vl),
  __param(2, $Pk)
], $LWb);

// out-build/vs/platform/userDataProfile/common/userDataProfileStorageService.js
var $$A = $Qk("IUserDataProfileStorageService");
var $_A = class $_A2 extends $3c {
  constructor(persistStorages, b) {
    super();
    this.b = b;
    if (persistStorages) {
      this.a = this.B(new $_c());
    }
  }
  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 key2 of storageService.keys(0, target)) {
        result.set(key2, { value: storageService.get(
          key2,
          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(([key2, value]) => ({ key: key2, value, scope: 0, target })), true);
  }
};
$_A = __decorate([
  __param(1, $jv)
], $_A);
var StorageService = class extends $lv {
  constructor(U) {
    super({ flushInterval: 100 });
    this.U = U;
  }
  async O() {
    const profileStorageDatabase = await this.U;
    const profileStorage = new $fv(profileStorageDatabase);
    this.B(profileStorage.onDidChangeStorage((e) => {
      this.u(0, e);
    }));
    this.B($1c(() => {
      profileStorage.close();
      profileStorage.dispose();
      if ($Wc(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/workbench/services/userDataProfile/browser/extensionsResource.js
var $MWb = class $MWb2 {
  constructor(c, d, f, g, h3) {
    this.c = c;
    this.d = d;
    this.f = f;
    this.g = g;
    this.h = h3;
  }
  async initialize(content) {
    const profileExtensions = JSON.parse(content);
    const installedExtensions = await this.d.getInstalled(void 0, this.c.currentProfile.extensionsResource);
    const extensionsToEnableOrDisable = [];
    const extensionsToInstall = [];
    for (const e of profileExtensions) {
      const isDisabled = this.g.getDisabledExtensions().some((disabledExtension) => $DA(disabledExtension, e.identifier));
      const installedExtension = installedExtensions.find((installed) => $DA(installed.identifier, e.identifier));
      if (!installedExtension || !installedExtension.isBuiltin && installedExtension.preRelease !== e.preRelease) {
        extensionsToInstall.push(e);
      }
      if (isDisabled !== !!e.disabled) {
        extensionsToEnableOrDisable.push({ extension: e.identifier, enable: !e.disabled });
      }
    }
    const extensionsToUninstall = installedExtensions.filter((extension) => !extension.isBuiltin && !profileExtensions.some(({ identifier: identifier2 }) => $DA(identifier2, extension.identifier)));
    for (const { extension, enable } of extensionsToEnableOrDisable) {
      if (enable) {
        this.h.trace(`Initializing Profile: Enabling extension...`, extension.id);
        await this.g.enableExtension(extension);
        this.h.info(`Initializing Profile: Enabled extension...`, extension.id);
      } else {
        this.h.trace(`Initializing Profile: Disabling extension...`, extension.id);
        await this.g.disableExtension(extension);
        this.h.info(`Initializing Profile: Disabled extension...`, extension.id);
      }
    }
    if (extensionsToInstall.length) {
      const galleryExtensions = await this.f.getExtensions(extensionsToInstall.map((e) => ({ ...e.identifier, version: e.version, hasPreRelease: e.version ? void 0 : e.preRelease })), CancellationToken.None);
      await Promise.all(extensionsToInstall.map(async (e) => {
        const extension = galleryExtensions.find((galleryExtension) => $DA(galleryExtension.identifier, e.identifier));
        if (!extension) {
          return;
        }
        if (await this.d.canInstall(extension) === true) {
          this.h.trace(`Initializing Profile: Installing extension...`, extension.identifier.id, extension.version);
          await this.d.installFromGallery(extension, {
            isMachineScoped: false,
            /* set isMachineScoped value to prevent install and sync dialog in web */
            donotIncludePackAndDependencies: true,
            installGivenVersion: !!e.version,
            installPreReleaseVersion: e.preRelease,
            profileLocation: this.c.currentProfile.extensionsResource,
            context: { [$fA]: true }
          });
          this.h.info(`Initializing Profile: Installed extension...`, extension.identifier.id, extension.version);
        } else {
          this.h.info(`Initializing Profile: Skipped installing extension because it cannot be installed.`, extension.identifier.id);
        }
      }));
    }
    if (extensionsToUninstall.length) {
      await Promise.all(extensionsToUninstall.map((e) => this.d.uninstall(e)));
    }
  }
};
$MWb = __decorate([
  __param(0, $gT),
  __param(1, $sA),
  __param(2, $pA),
  __param(3, $vA),
  __param(4, $wn)
], $MWb);
var $NWb = class $NWb2 {
  constructor(c, d, f, g, h3) {
    this.c = c;
    this.d = d;
    this.f = f;
    this.g = g;
    this.h = h3;
  }
  async getContent(profile, exclude) {
    const extensions = await this.getLocalExtensions(profile);
    return this.toContent(extensions, exclude);
  }
  toContent(extensions, exclude) {
    return JSON.stringify(exclude?.length ? extensions.filter((e) => !exclude.includes(e.identifier.id.toLowerCase())) : extensions);
  }
  async apply(content, profile, progress, token) {
    return this.i(profile, async (extensionEnablementService) => {
      const profileExtensions = await this.getProfileExtensions(content);
      const installedExtensions = await this.c.getInstalled(void 0, profile.extensionsResource);
      const extensionsToEnableOrDisable = [];
      const extensionsToInstall = [];
      for (const e of profileExtensions) {
        const isDisabled = extensionEnablementService.getDisabledExtensions().some((disabledExtension) => $DA(disabledExtension, e.identifier));
        const installedExtension = installedExtensions.find((installed) => $DA(installed.identifier, e.identifier));
        if (!installedExtension || !installedExtension.isBuiltin && installedExtension.preRelease !== e.preRelease) {
          extensionsToInstall.push(e);
        }
        if (isDisabled !== !!e.disabled) {
          extensionsToEnableOrDisable.push({ extension: e.identifier, enable: !e.disabled });
        }
      }
      const extensionsToUninstall = installedExtensions.filter((extension) => !extension.isBuiltin && !profileExtensions.some(({ identifier: identifier2 }) => $DA(identifier2, extension.identifier)) && !extension.isApplicationScoped);
      for (const { extension, enable } of extensionsToEnableOrDisable) {
        if (enable) {
          this.h.trace(`Importing Profile (${profile.name}): Enabling extension...`, extension.id);
          await extensionEnablementService.enableExtension(extension);
          this.h.info(`Importing Profile (${profile.name}): Enabled extension...`, extension.id);
        } else {
          this.h.trace(`Importing Profile (${profile.name}): Disabling extension...`, extension.id);
          await extensionEnablementService.disableExtension(extension);
          this.h.info(`Importing Profile (${profile.name}): Disabled extension...`, extension.id);
        }
      }
      if (extensionsToInstall.length) {
        this.h.info(`Importing Profile (${profile.name}): Started installing extensions.`);
        const galleryExtensions = await this.d.getExtensions(extensionsToInstall.map((e) => ({ ...e.identifier, version: e.version, hasPreRelease: e.version ? void 0 : e.preRelease })), CancellationToken.None);
        const installExtensionInfos = [];
        await Promise.all(extensionsToInstall.map(async (e) => {
          const extension = galleryExtensions.find((galleryExtension) => $DA(galleryExtension.identifier, e.identifier));
          if (!extension) {
            return;
          }
          if (await this.c.canInstall(extension) === true) {
            installExtensionInfos.push({
              extension,
              options: {
                isMachineScoped: false,
                /* set isMachineScoped value to prevent install and sync dialog in web */
                donotIncludePackAndDependencies: true,
                installGivenVersion: !!e.version,
                installPreReleaseVersion: e.preRelease,
                profileLocation: profile.extensionsResource,
                context: { [$fA]: true }
              }
            });
          } else {
            this.h.info(`Importing Profile (${profile.name}): Skipped installing extension because it cannot be installed.`, extension.identifier.id);
          }
        }));
        if (installExtensionInfos.length) {
          if (token) {
            for (const installExtensionInfo of installExtensionInfos) {
              if (token.isCancellationRequested) {
                return;
              }
              progress?.(localize(13363, null, installExtensionInfo.extension.displayName ?? installExtensionInfo.extension.identifier.id));
              await this.c.installFromGallery(installExtensionInfo.extension, installExtensionInfo.options);
            }
          } else {
            await this.c.installGalleryExtensions(installExtensionInfos);
          }
        }
        this.h.info(`Importing Profile (${profile.name}): Finished installing extensions.`);
      }
      if (extensionsToUninstall.length) {
        await Promise.all(extensionsToUninstall.map((e) => this.c.uninstall(e)));
      }
    });
  }
  async copy(from, to, disableExtensions) {
    await this.c.copyExtensions(from.extensionsResource, to.extensionsResource);
    const extensionsToDisable = await this.i(from, async (extensionEnablementService) => extensionEnablementService.getDisabledExtensions());
    if (disableExtensions) {
      const extensions = await this.c.getInstalled(1, to.extensionsResource);
      for (const extension of extensions) {
        extensionsToDisable.push(extension.identifier);
      }
    }
    await this.i(to, async (extensionEnablementService) => Promise.all(extensionsToDisable.map((extension) => extensionEnablementService.disableExtension(extension))));
  }
  async getLocalExtensions(profile) {
    return this.i(profile, async (extensionEnablementService) => {
      const result = /* @__PURE__ */ new Map();
      const installedExtensions = await this.c.getInstalled(void 0, profile.extensionsResource);
      const disabledExtensions = extensionEnablementService.getDisabledExtensions();
      for (const extension of installedExtensions) {
        const { identifier: identifier2, preRelease } = extension;
        const disabled = disabledExtensions.some((disabledExtension) => $DA(disabledExtension, identifier2));
        if (extension.isBuiltin && !disabled) {
          continue;
        }
        if (!extension.isBuiltin) {
          if (!extension.identifier.uuid) {
            continue;
          }
        }
        const existing = result.get(identifier2.id.toLowerCase());
        if (existing?.disabled) {
          result.delete(identifier2.id.toLowerCase());
        }
        const profileExtension = { identifier: identifier2, displayName: extension.manifest.displayName };
        if (disabled) {
          profileExtension.disabled = true;
        }
        if (!extension.isBuiltin && extension.pinned) {
          profileExtension.version = extension.manifest.version;
        }
        if (!profileExtension.version && preRelease) {
          profileExtension.preRelease = true;
        }
        profileExtension.applicationScoped = extension.isApplicationScoped;
        result.set(profileExtension.identifier.id.toLowerCase(), profileExtension);
      }
      return [...result.values()];
    });
  }
  async getProfileExtensions(content) {
    return JSON.parse(content);
  }
  async i(profile, fn) {
    return this.f.withProfileScopedStorageService(profile, async (storageService) => {
      const disposables = new $2c();
      const instantiationService = disposables.add(this.g.createChild(new $Ok([$jv, storageService])));
      const extensionEnablementService = disposables.add(instantiationService.createInstance($cWb));
      try {
        return await fn(extensionEnablementService);
      } finally {
        disposables.dispose();
      }
    });
  }
};
$NWb = __decorate([
  __param(0, $sA),
  __param(1, $pA),
  __param(2, $$A),
  __param(3, $Pk),
  __param(4, $wn)
], $NWb);
var $OWb = class {
  constructor() {
    this.type = "extensions";
    this.handle = "extensions";
    this.label = { label: localize(13364, null) };
    this.collapsibleState = TreeItemCollapsibleState2.Expanded;
    this.contextValue = "extensions";
    this.c = /* @__PURE__ */ new Set();
  }
  async getChildren() {
    const extensions = (await this.d()).sort((a, b) => (a.displayName ?? a.identifier.id).localeCompare(b.displayName ?? b.identifier.id));
    const that = this;
    return extensions.map((e) => ({
      ...e,
      handle: e.identifier.id.toLowerCase(),
      parent: this,
      label: { label: e.displayName || e.identifier.id },
      description: e.applicationScoped ? localize(13365, null) : void 0,
      collapsibleState: TreeItemCollapsibleState2.None,
      checkbox: that.checkbox ? {
        get isChecked() {
          return !that.c.has(e.identifier.id.toLowerCase());
        },
        set isChecked(value) {
          if (value) {
            that.c.delete(e.identifier.id.toLowerCase());
          } else {
            that.c.add(e.identifier.id.toLowerCase());
          }
        },
        tooltip: localize(13366, null, e.displayName || e.identifier.id),
        accessibilityInformation: {
          label: localize(13367, null, e.displayName || e.identifier.id)
        }
      } : void 0,
      themeIcon: $6l.extensions,
      command: {
        id: "extension.open",
        title: "",
        arguments: [e.identifier.id, void 0, true]
      }
    }));
  }
  async hasContent() {
    const extensions = await this.d();
    return extensions.length > 0;
  }
};
var $PWb = class $PWb2 extends $OWb {
  constructor(f, g) {
    super();
    this.f = f;
    this.g = g;
  }
  isFromDefaultProfile() {
    return !this.f.isDefault && !!this.f.useDefaultFlags?.extensions;
  }
  d() {
    return this.g.createInstance($NWb).getLocalExtensions(this.f);
  }
  async getContent() {
    return this.g.createInstance($NWb).getContent(this.f, [...this.c.values()]);
  }
};
$PWb = __decorate([
  __param(1, $Pk)
], $PWb);
var $QWb = class $QWb2 extends $OWb {
  constructor(f, g) {
    super();
    this.f = f;
    this.g = g;
  }
  isFromDefaultProfile() {
    return false;
  }
  d() {
    return this.g.createInstance($NWb).getProfileExtensions(this.f);
  }
  async getContent() {
    const extensionsResource = this.g.createInstance($NWb);
    const extensions = await extensionsResource.getProfileExtensions(this.f);
    return extensionsResource.toContent(extensions, [...this.c.values()]);
  }
};
$QWb = __decorate([
  __param(1, $Pk)
], $QWb);

// out-build/vs/workbench/services/userDataProfile/browser/globalStateResource.js
var $RWb = class $RWb2 {
  constructor(a) {
    this.a = a;
  }
  async initialize(content) {
    const globalState = JSON.parse(content);
    const storageKeys2 = Object.keys(globalState.storage);
    if (storageKeys2.length) {
      const storageEntries = [];
      for (const key2 of storageKeys2) {
        storageEntries.push({
          key: key2,
          value: globalState.storage[key2],
          scope: 0,
          target: 0
          /* StorageTarget.USER */
        });
      }
      this.a.storeAll(storageEntries, true);
    }
  }
};
$RWb = __decorate([
  __param(0, $jv)
], $RWb);
var $SWb = class $SWb2 {
  constructor(a, b, c) {
    this.a = a;
    this.b = b;
    this.c = c;
  }
  async getContent(profile) {
    const globalState = await this.getGlobalState(profile);
    return JSON.stringify(globalState);
  }
  async apply(content, profile) {
    const globalState = JSON.parse(content);
    await this.d(globalState, profile);
  }
  async getGlobalState(profile) {
    const storage = {};
    const storageData = await this.b.readStorageData(profile);
    for (const [key2, value] of storageData) {
      if (value.value !== void 0 && value.target === 0) {
        storage[key2] = value.value;
      }
    }
    return { storage };
  }
  async d(globalState, profile) {
    const storageKeys2 = Object.keys(globalState.storage);
    if (storageKeys2.length) {
      const updatedStorage = /* @__PURE__ */ new Map();
      const nonProfileKeys = [
        // Do not include application scope user target keys because they also include default profile user target keys
        ...this.a.keys(
          -1,
          1
          /* StorageTarget.MACHINE */
        ),
        ...this.a.keys(
          1,
          0
          /* StorageTarget.USER */
        ),
        ...this.a.keys(
          1,
          1
          /* StorageTarget.MACHINE */
        )
      ];
      for (const key2 of storageKeys2) {
        if (nonProfileKeys.includes(key2)) {
          this.c.info(`Importing Profile (${profile.name}): Ignoring global state key '${key2}' because it is not a profile key.`);
        } else {
          updatedStorage.set(key2, globalState.storage[key2]);
        }
      }
      await this.b.updateStorageData(
        profile,
        updatedStorage,
        0
        /* StorageTarget.USER */
      );
    }
  }
};
$SWb = __decorate([
  __param(0, $jv),
  __param(1, $$A),
  __param(2, $wn)
], $SWb);
var $TWb = class {
  constructor(a, b) {
    this.a = a;
    this.b = b;
    this.type = "globalState";
    this.handle = "globalState";
    this.label = { label: localize(13368, null) };
    this.collapsibleState = TreeItemCollapsibleState2.Collapsed;
  }
  async getChildren() {
    return [{
      handle: this.a.toString(),
      resourceUri: this.a,
      collapsibleState: TreeItemCollapsibleState2.None,
      accessibilityInformation: {
        label: this.b.extUri.basename(this.a)
      },
      parent: this,
      command: {
        id: $$ub,
        title: "",
        arguments: [this.a, void 0, void 0]
      }
    }];
  }
};
var $UWb = class $UWb2 extends $TWb {
  constructor(c, resource, uriIdentityService, d) {
    super(resource, uriIdentityService);
    this.c = c;
    this.d = d;
  }
  async hasContent() {
    const globalState = await this.d.createInstance($SWb).getGlobalState(this.c);
    return Object.keys(globalState.storage).length > 0;
  }
  async getContent() {
    return this.d.createInstance($SWb).getContent(this.c);
  }
  isFromDefaultProfile() {
    return !this.c.isDefault && !!this.c.useDefaultFlags?.globalState;
  }
};
$UWb = __decorate([
  __param(2, $vl),
  __param(3, $Pk)
], $UWb);
var $VWb = class $VWb2 extends $TWb {
  constructor(c, resource, uriIdentityService) {
    super(resource, uriIdentityService);
    this.c = c;
  }
  async getContent() {
    return this.c;
  }
  isFromDefaultProfile() {
    return false;
  }
};
$VWb = __decorate([
  __param(2, $vl)
], $VWb);

// out-build/vs/platform/files/common/inMemoryFilesystemProvider.js
var File = class {
  constructor(name) {
    this.type = FileType.File;
    this.ctime = Date.now();
    this.mtime = Date.now();
    this.size = 0;
    this.name = name;
  }
};
var Directory = class {
  constructor(name) {
    this.type = FileType.Directory;
    this.ctime = Date.now();
    this.mtime = Date.now();
    this.size = 0;
    this.name = name;
    this.entries = /* @__PURE__ */ new Map();
  }
};
var $WWb = class extends $3c {
  constructor() {
    super(...arguments);
    this.a = 0;
    this.b = /* @__PURE__ */ new Map();
    this.f = this.B(new $ze());
    this.onDidChangeCapabilities = this.f.event;
    this.g = 2 | 1024;
    this.root = new Directory("");
    this.r = this.B(new $ze());
    this.onDidChangeFile = this.r.event;
    this.s = [];
  }
  get capabilities() {
    return this.g;
  }
  setReadOnly(readonly) {
    const isReadonly = !!(this.g & 2048);
    if (readonly !== isReadonly) {
      this.g = readonly ? 2048 | 1024 | 2 : 2 | 1024;
      this.f.fire();
    }
  }
  // --- manage file metadata
  async stat(resource) {
    return this.h(resource, false);
  }
  async readdir(resource) {
    const entry = this.j(resource, false);
    const result = [];
    entry.entries.forEach((child, name) => result.push([name, child.type]));
    return result;
  }
  // --- manage file contents
  async readFile(resource) {
    const data = this.m(resource, false).data;
    if (data) {
      return data;
    }
    throw $xm("file not found", FileSystemProviderErrorCode.FileNotFound);
  }
  readFileStream(resource) {
    const data = this.m(resource, false).data;
    const stream = $qi((data2) => $Ci.concat(data2.map((data3) => $Ci.wrap(data3))).buffer);
    stream.end(data);
    return stream;
  }
  async writeFile(resource, content, opts) {
    const basename = $sh(resource);
    const parent = this.n(resource);
    let entry = parent.entries.get(basename);
    if (entry instanceof Directory) {
      throw $xm("file is directory", FileSystemProviderErrorCode.FileIsADirectory);
    }
    if (!entry && !opts.create) {
      throw $xm("file not found", FileSystemProviderErrorCode.FileNotFound);
    }
    if (entry && opts.create && !opts.overwrite) {
      throw $xm("file exists already", FileSystemProviderErrorCode.FileExists);
    }
    if (!entry) {
      entry = new File(basename);
      parent.entries.set(basename, entry);
      this.u({ type: 1, resource });
    }
    entry.mtime = Date.now();
    entry.size = content.byteLength;
    entry.data = content;
    this.u({ type: 0, resource });
  }
  // file open/read/write/close
  open(resource, opts) {
    const data = this.m(resource, false).data;
    if (data) {
      const fd = this.a++;
      this.b.set(fd, data);
      return Promise.resolve(fd);
    }
    throw $xm("file not found", FileSystemProviderErrorCode.FileNotFound);
  }
  close(fd) {
    this.b.delete(fd);
    return Promise.resolve();
  }
  read(fd, pos, data, offset, length) {
    const memory = this.b.get(fd);
    if (!memory) {
      throw $xm(`No file with that descriptor open`, FileSystemProviderErrorCode.Unavailable);
    }
    const toWrite = $Ci.wrap(memory).slice(pos, pos + length);
    data.set(toWrite.buffer, offset);
    return Promise.resolve(toWrite.byteLength);
  }
  write(fd, pos, data, offset, length) {
    const memory = this.b.get(fd);
    if (!memory) {
      throw $xm(`No file with that descriptor open`, FileSystemProviderErrorCode.Unavailable);
    }
    const toWrite = $Ci.wrap(data).slice(offset, offset + length);
    memory.set(toWrite.buffer, pos);
    return Promise.resolve(toWrite.byteLength);
  }
  // --- manage files/folders
  async rename(from, to, opts) {
    if (!opts.overwrite && this.h(to, true)) {
      throw $xm("file exists already", FileSystemProviderErrorCode.FileExists);
    }
    const entry = this.h(from, false);
    const oldParent = this.n(from);
    const newParent = this.n(to);
    const newName = $sh(to);
    oldParent.entries.delete(entry.name);
    entry.name = newName;
    newParent.entries.set(newName, entry);
    this.u({ type: 2, resource: from }, { type: 1, resource: to });
  }
  async delete(resource, opts) {
    const dirname = $uh(resource);
    const basename = $sh(resource);
    const parent = this.j(dirname, false);
    if (parent.entries.has(basename)) {
      parent.entries.delete(basename);
      parent.mtime = Date.now();
      parent.size -= 1;
      this.u({ type: 0, resource: dirname }, {
        resource,
        type: 2
        /* FileChangeType.DELETED */
      });
    }
  }
  async mkdir(resource) {
    if (this.h(resource, true)) {
      throw $xm("file exists already", FileSystemProviderErrorCode.FileExists);
    }
    const basename = $sh(resource);
    const dirname = $uh(resource);
    const parent = this.j(dirname, false);
    const entry = new Directory(basename);
    parent.entries.set(entry.name, entry);
    parent.mtime = Date.now();
    parent.size += 1;
    this.u({ type: 0, resource: dirname }, { type: 1, resource });
  }
  h(uri, silent) {
    const parts = uri.path.split("/");
    let entry = this.root;
    for (const part of parts) {
      if (!part) {
        continue;
      }
      let child;
      if (entry instanceof Directory) {
        child = entry.entries.get(part);
      }
      if (!child) {
        if (!silent) {
          throw $xm("file not found", FileSystemProviderErrorCode.FileNotFound);
        } else {
          return void 0;
        }
      }
      entry = child;
    }
    return entry;
  }
  j(uri, silent) {
    const entry = this.h(uri, silent);
    if (entry instanceof Directory) {
      return entry;
    }
    throw $xm("file not a directory", FileSystemProviderErrorCode.FileNotADirectory);
  }
  m(uri, silent) {
    const entry = this.h(uri, silent);
    if (entry instanceof File) {
      return entry;
    }
    throw $xm("file is a directory", FileSystemProviderErrorCode.FileIsADirectory);
  }
  n(uri) {
    const dirname = $uh(uri);
    return this.j(dirname, false);
  }
  watch(resource, opts) {
    return $3c.None;
  }
  u(...changes) {
    this.s.push(...changes);
    if (this.t) {
      clearTimeout(this.t);
    }
    this.t = setTimeout(() => {
      this.r.fire(this.s);
      this.s.length = 0;
    }, 5);
  }
  dispose() {
    super.dispose();
    this.b.clear();
  }
};

// out-build/vs/workbench/services/userDataProfile/browser/userDataProfileImportExportService.js
function isUserDataProfileTemplate(thing) {
  const candidate = thing;
  return !!(candidate && typeof candidate === "object" && (candidate.name && typeof candidate.name === "string") && ($Gg(candidate.icon) || typeof candidate.icon === "string") && ($Gg(candidate.settings) || typeof candidate.settings === "string") && ($Gg(candidate.globalState) || typeof candidate.globalState === "string") && ($Gg(candidate.extensions) || typeof candidate.extensions === "string"));
}
var $XWb = class $XWb2 extends $3c {
  constructor(c, f, g, h3, j, m, n, r2, s, t, u, w, y) {
    super();
    this.c = c;
    this.f = f;
    this.g = g;
    this.h = h3;
    this.j = j;
    this.m = m;
    this.n = n;
    this.r = r2;
    this.s = s;
    this.t = t;
    this.u = u;
    this.w = w;
    this.y = y;
    this.a = /* @__PURE__ */ new Map();
    this.registerProfileContentHandler(Schemas.file, this.b = c.createInstance(FileUserDataProfileContentHandler));
  }
  registerProfileContentHandler(id2, profileContentHandler) {
    if (this.a.has(id2)) {
      throw new Error(`Profile content handler with id '${id2}' already registered.`);
    }
    this.a.set(id2, profileContentHandler);
    return $1c(() => this.unregisterProfileContentHandler(id2));
  }
  unregisterProfileContentHandler(id2) {
    this.a.delete(id2);
  }
  async createFromProfile(from, options3, token) {
    const disposables = new $2c();
    let creationPromise;
    disposables.add(token.onCancellationRequested(() => creationPromise.cancel()));
    let profile;
    return this.n.withProgress({
      location: 15,
      delay: 500,
      sticky: true,
      cancellable: true
    }, async (progress) => {
      const reportProgress = (message) => progress.report({ message: localize(13374, null, message) });
      creationPromise = $Hh(async (token2) => {
        const userDataProfilesExportState = disposables.add(this.c.createInstance(UserDataProfileExportState, from, { ...options3?.resourceTypeFlags, extensions: false }));
        const profileTemplate = await userDataProfilesExportState.getProfileTemplate(options3.name ?? from.name, options3?.icon);
        profile = await this.H({ ...profileTemplate, name: options3.name ?? profileTemplate.name }, !!options3.transient, options3);
        if (!profile) {
          return;
        }
        if (token2.isCancellationRequested) {
          return;
        }
        await this.z(profileTemplate, profile, options3, reportProgress, token2);
      });
      try {
        await creationPromise;
        if (profile && (options3?.resourceTypeFlags?.extensions ?? true)) {
          reportProgress(localize(13375, null));
          await this.c.createInstance($NWb).copy(from, profile, false);
        }
      } catch (error) {
        if (profile) {
          await this.h.removeProfile(profile);
          profile = void 0;
        }
      }
      return profile;
    }, () => creationPromise.cancel()).finally(() => disposables.dispose());
  }
  async createProfileFromTemplate(profileTemplate, options3, token) {
    const disposables = new $2c();
    let creationPromise;
    disposables.add(token.onCancellationRequested(() => creationPromise.cancel()));
    let profile;
    return this.n.withProgress({
      location: 15,
      delay: 500,
      sticky: true,
      cancellable: true
    }, async (progress) => {
      const reportProgress = (message) => progress.report({ message: localize(13376, null, message) });
      creationPromise = $Hh(async (token2) => {
        profile = await this.H({ ...profileTemplate, name: options3.name ?? profileTemplate.name }, !!options3.transient, options3);
        if (!profile) {
          return;
        }
        if (token2.isCancellationRequested) {
          return;
        }
        await this.z(profileTemplate, profile, options3, reportProgress, token2);
      });
      try {
        await creationPromise;
      } catch (error) {
        if (profile) {
          await this.h.removeProfile(profile);
          profile = void 0;
        }
      }
      return profile;
    }, () => creationPromise.cancel()).finally(() => disposables.dispose());
  }
  async z(profileTemplate, profile, options3, reportProgress, token) {
    if (profileTemplate.settings && (options3.resourceTypeFlags?.settings ?? true) && !profile.useDefaultFlags?.settings) {
      reportProgress(localize(13377, null));
      await this.c.createInstance($BWb).apply(profileTemplate.settings, profile);
    }
    if (token.isCancellationRequested) {
      return;
    }
    if (profileTemplate.keybindings && (options3.resourceTypeFlags?.keybindings ?? true) && !profile.useDefaultFlags?.keybindings) {
      reportProgress(localize(13378, null));
      await this.c.createInstance($EWb).apply(profileTemplate.keybindings, profile);
    }
    if (token.isCancellationRequested) {
      return;
    }
    if (profileTemplate.tasks && (options3.resourceTypeFlags?.tasks ?? true) && !profile.useDefaultFlags?.tasks) {
      reportProgress(localize(13379, null));
      await this.c.createInstance($KWb).apply(profileTemplate.tasks, profile);
    }
    if (token.isCancellationRequested) {
      return;
    }
    if (profileTemplate.snippets && (options3.resourceTypeFlags?.snippets ?? true) && !profile.useDefaultFlags?.snippets) {
      reportProgress(localize(13380, null));
      await this.c.createInstance($HWb).apply(profileTemplate.snippets, profile);
    }
    if (token.isCancellationRequested) {
      return;
    }
    if (profileTemplate.globalState && !profile.useDefaultFlags?.globalState) {
      reportProgress(localize(13381, null));
      await this.c.createInstance($SWb).apply(profileTemplate.globalState, profile);
    }
    if (token.isCancellationRequested) {
      return;
    }
    if (profileTemplate.extensions && (options3.resourceTypeFlags?.extensions ?? true) && !profile.useDefaultFlags?.extensions) {
      reportProgress(localize(13382, null));
      await this.c.createInstance($NWb).apply(profileTemplate.extensions, profile, reportProgress, token);
    }
  }
  async exportProfile(profile, exportFlags) {
    const disposables = new $2c();
    try {
      const userDataProfilesExportState = disposables.add(this.c.createInstance(UserDataProfileExportState, profile, exportFlags));
      await this.C(
        userDataProfilesExportState,
        15
        /* ProgressLocation.Notification */
      );
    } finally {
      disposables.dispose();
    }
  }
  async createTroubleshootProfile() {
    const userDataProfilesExportState = this.c.createInstance(UserDataProfileExportState, this.f.currentProfile, void 0);
    try {
      const profileTemplate = await userDataProfilesExportState.getProfileTemplate(localize(13383, null), void 0);
      await this.n.withProgress({
        location: 15,
        delay: 1e3,
        sticky: true
      }, async (progress) => {
        const reportProgress = (message) => progress.report({ message: localize(13384, null, message) });
        const profile = await this.D(profileTemplate, true, false, { useDefaultFlags: this.f.currentProfile.useDefaultFlags }, reportProgress);
        if (profile) {
          reportProgress(localize(13385, null));
          await this.c.createInstance($NWb).copy(this.f.currentProfile, profile, true);
          reportProgress(localize(13386, null));
          await this.g.switchProfile(profile);
        }
      });
    } finally {
      userDataProfilesExportState.dispose();
    }
  }
  async C(userDataProfilesExportState, location3) {
    const profile = await userDataProfilesExportState.getProfileToExport();
    if (!profile) {
      return;
    }
    const disposables = new $2c();
    try {
      await this.n.withProgress({
        location: location3,
        title: localize(13387, null, $qT.value)
      }, async (progress) => {
        const id2 = await this.G(profile.name);
        if (!id2) {
          return;
        }
        const profileContentHandler = this.a.get(id2);
        if (!profileContentHandler) {
          return;
        }
        const saveResult = await profileContentHandler.saveProfile(profile.name.replace("/", "-"), JSON.stringify(profile), CancellationToken.None);
        if (!saveResult) {
          return;
        }
        const message = localize(13388, null, profile.name);
        if (profileContentHandler.extensionId) {
          const buttons = [];
          const link2 = this.w.webUrl ? `${this.w.webUrl}/${$jT}/${id2}/${saveResult.id}` : $kT(`/${id2}/${saveResult.id}`, this.w).toString();
          buttons.push({
            label: localize(13389, null),
            run: () => this.s.writeText(link2)
          });
          if (this.w.webUrl) {
            buttons.push({
              label: localize(13390, null),
              run: async () => {
                await this.t.open(link2);
              }
            });
          } else {
            buttons.push({
              label: localize(13391, null, profileContentHandler.name),
              run: async () => {
                await this.t.open(saveResult.link.toString());
              }
            });
          }
          await this.r.prompt({
            type: severity_default.Info,
            message,
            buttons,
            cancelButton: localize(13392, null)
          });
        } else {
          await this.r.info(message);
        }
      });
    } finally {
      disposables.dispose();
    }
  }
  async resolveProfileTemplate(uri, options3) {
    const profileContent = await this.F(uri);
    if (profileContent === null) {
      return null;
    }
    let profileTemplate;
    try {
      profileTemplate = JSON.parse(profileContent);
    } catch (error) {
      throw new Error(localize(13393, null));
    }
    if (!isUserDataProfileTemplate(profileTemplate)) {
      throw new Error(localize(13394, null));
    }
    if (options3?.name) {
      profileTemplate.name = options3.name;
    }
    if (options3?.icon) {
      profileTemplate.icon = options3.icon;
    }
    if (options3?.resourceTypeFlags?.settings === false) {
      profileTemplate.settings = void 0;
    }
    if (options3?.resourceTypeFlags?.keybindings === false) {
      profileTemplate.keybindings = void 0;
    }
    if (options3?.resourceTypeFlags?.snippets === false) {
      profileTemplate.snippets = void 0;
    }
    if (options3?.resourceTypeFlags?.tasks === false) {
      profileTemplate.tasks = void 0;
    }
    if (options3?.resourceTypeFlags?.globalState === false) {
      profileTemplate.globalState = void 0;
    }
    if (options3?.resourceTypeFlags?.extensions === false) {
      profileTemplate.extensions = void 0;
    }
    return profileTemplate;
  }
  async D(profileTemplate, temporaryProfile, extensions, options3, progress) {
    const profile = await this.H(profileTemplate, temporaryProfile, options3);
    if (!profile) {
      return void 0;
    }
    if (profileTemplate.settings && !profile.useDefaultFlags?.settings) {
      progress(localize(13395, null));
      await this.c.createInstance($BWb).apply(profileTemplate.settings, profile);
    }
    if (profileTemplate.keybindings && !profile.useDefaultFlags?.keybindings) {
      progress(localize(13396, null));
      await this.c.createInstance($EWb).apply(profileTemplate.keybindings, profile);
    }
    if (profileTemplate.tasks && !profile.useDefaultFlags?.tasks) {
      progress(localize(13397, null));
      await this.c.createInstance($KWb).apply(profileTemplate.tasks, profile);
    }
    if (profileTemplate.snippets && !profile.useDefaultFlags?.snippets) {
      progress(localize(13398, null));
      await this.c.createInstance($HWb).apply(profileTemplate.snippets, profile);
    }
    if (profileTemplate.globalState && !profile.useDefaultFlags?.globalState) {
      progress(localize(13399, null));
      await this.c.createInstance($SWb).apply(profileTemplate.globalState, profile);
    }
    if (profileTemplate.extensions && extensions && !profile.useDefaultFlags?.extensions) {
      progress(localize(13400, null));
      await this.c.createInstance($NWb).apply(profileTemplate.extensions, profile);
    }
    return profile;
  }
  async F(resource) {
    if (await this.b.canHandle(resource)) {
      return this.b.readProfile(resource, CancellationToken.None);
    }
    if ($mT(resource)) {
      let handlerId, idOrUri;
      if (resource.authority === $jT) {
        idOrUri = this.y.extUri.basename(resource);
        handlerId = this.y.extUri.basename(this.y.extUri.dirname(resource));
      } else {
        handlerId = resource.authority.substring($lT.length);
        idOrUri = URI.parse(resource.path.substring(1));
      }
      await this.j.activateByEvent(`onProfile:${handlerId}`);
      const profileContentHandler = this.a.get(handlerId);
      if (profileContentHandler) {
        return profileContentHandler.readProfile(idOrUri, CancellationToken.None);
      }
    }
    await this.j.activateByEvent("onProfile");
    for (const profileContentHandler of this.a.values()) {
      const content = await profileContentHandler.readProfile(resource, CancellationToken.None);
      if (content !== null) {
        return content;
      }
    }
    const context = await this.u.request({ type: "GET", url: resource.toString(true) }, CancellationToken.None);
    if (context.res.statusCode === 200) {
      return await $av(context);
    } else {
      const message = await $av(context);
      throw new Error(`Failed to get profile from URL: ${resource.toString()}. Status code: ${context.res.statusCode}. Message: ${message}`);
    }
  }
  async G(name) {
    await this.j.activateByEvent("onProfile");
    if (this.a.size === 1) {
      return this.a.keys().next().value;
    }
    const options3 = [];
    for (const [id2, profileContentHandler] of this.a) {
      options3.push({ id: id2, label: profileContentHandler.name, description: profileContentHandler.description });
    }
    const result = await this.m.pick(options3.reverse(), {
      title: localize(13401, null, name),
      hideInput: true
    });
    return result?.id;
  }
  async H(profileTemplate, temp, options3) {
    const profileName = profileTemplate.name;
    const profile = this.h.profiles.find((p) => p.name === profileName);
    if (profile) {
      if (temp) {
        return this.h.createNamedProfile(`${profileName} ${this.I(profileName)}`, { ...options3, transient: temp });
      }
      const { confirmed } = await this.r.confirm({
        type: severity_default.Info,
        message: localize(13402, null, profileName),
        primaryButton: localize(13403, null)
      });
      if (!confirmed) {
        return void 0;
      }
      return profile.isDefault ? profile : this.h.updateProfile(profile, options3);
    } else {
      return this.h.createNamedProfile(profileName, { ...options3, transient: temp });
    }
  }
  I(name) {
    const nameRegEx = new RegExp(`${$Af(name)}\\s(\\d+)`);
    let nameIndex = 0;
    for (const profile of this.h.profiles) {
      const matches = nameRegEx.exec(profile.name);
      const index = matches ? parseInt(matches[1]) : 0;
      nameIndex = index > nameIndex ? index : nameIndex;
    }
    return nameIndex + 1;
  }
};
$XWb = __decorate([
  __param(0, $Pk),
  __param(1, $gT),
  __param(2, $hT),
  __param(3, $rs),
  __param(4, $wN),
  __param(5, $1M),
  __param(6, $TJ),
  __param(7, $Yv),
  __param(8, $30),
  __param(9, $O4),
  __param(10, $9u),
  __param(11, $Vu),
  __param(12, $vl)
], $XWb);
var FileUserDataProfileContentHandler = class FileUserDataProfileContentHandler2 {
  constructor(a, b, c, d, e) {
    this.a = a;
    this.b = b;
    this.c = c;
    this.d = d;
    this.e = e;
    this.name = localize(13404, null);
    this.description = localize(13405, null);
  }
  async saveProfile(name, content, token) {
    const link2 = await this.a.showSaveDialog({
      title: localize(13406, null),
      filters: $sT,
      defaultUri: this.b.extUri.joinPath(await this.a.defaultFilePath(), `${name}.${$rT}`)
    });
    if (!link2) {
      return null;
    }
    await this.e.create([{ resource: link2, value: content, options: { overwrite: true } }]);
    return { link: link2, id: link2.toString() };
  }
  async canHandle(uri) {
    return uri.scheme !== Schemas.http && uri.scheme !== Schemas.https && uri.scheme !== this.d.urlProtocol && await this.c.canHandleResource(uri);
  }
  async readProfile(uri, token) {
    if (await this.canHandle(uri)) {
      return (await this.c.readFile(uri, void 0, token)).value.toString();
    }
    return null;
  }
  async selectProfile() {
    const profileLocation = await this.a.showOpenDialog({
      canSelectFolders: false,
      canSelectFiles: true,
      canSelectMany: false,
      filters: $sT,
      title: localize(13407, null)
    });
    return profileLocation ? profileLocation[0] : null;
  }
};
FileUserDataProfileContentHandler = __decorate([
  __param(0, $1v),
  __param(1, $vl),
  __param(2, $km),
  __param(3, $Vu),
  __param(4, $cK)
], FileUserDataProfileContentHandler);
var USER_DATA_PROFILE_EXPORT_SCHEME = "userdataprofileexport";
var USER_DATA_PROFILE_EXPORT_PREVIEW_SCHEME = "userdataprofileexportpreview";
var UserDataProfileImportExportState = class UserDataProfileImportExportState2 extends $3c {
  constructor(b) {
    super();
    this.b = b;
    this.a = this.B(new $ze());
    this.onDidChangeRoots = this.a.event;
    this.c = [];
  }
  async getChildren(element) {
    if (element) {
      const children = await element.getChildren();
      if (children) {
        for (const child of children) {
          if (child.parent.checkbox && child.checkbox) {
            child.checkbox.isChecked = child.parent.checkbox.isChecked && child.checkbox.isChecked;
          }
        }
      }
      return children;
    } else {
      this.f = void 0;
      this.a.fire();
      return this.getRoots();
    }
  }
  getRoots() {
    if (!this.f) {
      this.f = (async () => {
        this.c = await this.h();
        for (const root of this.c) {
          root.checkbox = {
            isChecked: !root.isFromDefaultProfile(),
            tooltip: localize(13408, null, root.label.label),
            accessibilityInformation: {
              label: localize(13409, null, root.label.label)
            }
          };
          if (root.isFromDefaultProfile()) {
            root.description = localize(13410, null);
          }
        }
        return this.c;
      })();
    }
    return this.f;
  }
  isEnabled(resourceType) {
    if (resourceType !== void 0) {
      return this.c.some((root) => root.type === resourceType && this.g(root));
    }
    return this.c.some((root) => this.g(root));
  }
  async getProfileTemplate(name, icon2) {
    const roots = await this.getRoots();
    let settings;
    let keybindings;
    let tasks2;
    let snippets;
    let extensions;
    let globalState;
    for (const root of roots) {
      if (!this.g(root)) {
        continue;
      }
      if (root instanceof $CWb) {
        settings = await root.getContent();
      } else if (root instanceof $FWb) {
        keybindings = await root.getContent();
      } else if (root instanceof $LWb) {
        tasks2 = await root.getContent();
      } else if (root instanceof $IWb) {
        snippets = await root.getContent();
      } else if (root instanceof $OWb) {
        extensions = await root.getContent();
      } else if (root instanceof $TWb) {
        globalState = await root.getContent();
      }
    }
    return {
      name,
      icon: icon2,
      settings,
      keybindings,
      tasks: tasks2,
      snippets,
      extensions,
      globalState
    };
  }
  g(treeItem) {
    if (treeItem.checkbox) {
      return treeItem.checkbox.isChecked || !!treeItem.children?.some((child) => child.checkbox?.isChecked);
    }
    return true;
  }
};
UserDataProfileImportExportState = __decorate([
  __param(0, $1M)
], UserDataProfileImportExportState);
var UserDataProfileExportState = class UserDataProfileExportState2 extends UserDataProfileImportExportState {
  constructor(profile, m, quickInputService, n, r2) {
    super(quickInputService);
    this.profile = profile;
    this.m = m;
    this.n = n;
    this.r = r2;
    this.j = this.B(new $2c());
  }
  async h() {
    this.j.clear();
    this.j.add(this.n.registerProvider(USER_DATA_PROFILE_EXPORT_SCHEME, this.B(new $WWb())));
    const previewFileSystemProvider = this.B(new $WWb());
    this.j.add(this.n.registerProvider(USER_DATA_PROFILE_EXPORT_PREVIEW_SCHEME, previewFileSystemProvider));
    const roots = [];
    const exportPreviewProfle = this.t(this.profile);
    if (this.m?.settings ?? true) {
      const settingsResource = this.r.createInstance($BWb);
      const settingsContent = await settingsResource.getContent(this.profile);
      await settingsResource.apply(settingsContent, exportPreviewProfle);
      const settingsResourceTreeItem = this.r.createInstance($CWb, exportPreviewProfle);
      if (await settingsResourceTreeItem.hasContent()) {
        roots.push(settingsResourceTreeItem);
      }
    }
    if (this.m?.keybindings ?? true) {
      const keybindingsResource = this.r.createInstance($EWb);
      const keybindingsContent = await keybindingsResource.getContent(this.profile);
      await keybindingsResource.apply(keybindingsContent, exportPreviewProfle);
      const keybindingsResourceTreeItem = this.r.createInstance($FWb, exportPreviewProfle);
      if (await keybindingsResourceTreeItem.hasContent()) {
        roots.push(keybindingsResourceTreeItem);
      }
    }
    if (this.m?.snippets ?? true) {
      const snippetsResource = this.r.createInstance($HWb);
      const snippetsContent = await snippetsResource.getContent(this.profile);
      await snippetsResource.apply(snippetsContent, exportPreviewProfle);
      const snippetsResourceTreeItem = this.r.createInstance($IWb, exportPreviewProfle);
      if (await snippetsResourceTreeItem.hasContent()) {
        roots.push(snippetsResourceTreeItem);
      }
    }
    if (this.m?.tasks ?? true) {
      const tasksResource = this.r.createInstance($KWb);
      const tasksContent = await tasksResource.getContent(this.profile);
      await tasksResource.apply(tasksContent, exportPreviewProfle);
      const tasksResourceTreeItem = this.r.createInstance($LWb, exportPreviewProfle);
      if (await tasksResourceTreeItem.hasContent()) {
        roots.push(tasksResourceTreeItem);
      }
    }
    if (this.m?.globalState ?? true) {
      const globalStateResource = $vh(exportPreviewProfle.globalStorageHome, "globalState.json").with({ scheme: USER_DATA_PROFILE_EXPORT_PREVIEW_SCHEME });
      const globalStateResourceTreeItem = this.r.createInstance($UWb, exportPreviewProfle, globalStateResource);
      const content = await globalStateResourceTreeItem.getContent();
      if (content) {
        await this.n.writeFile(globalStateResource, $Ci.fromString(JSON.stringify(JSON.parse(content), null, "	")));
        roots.push(globalStateResourceTreeItem);
      }
    }
    if (this.m?.extensions ?? true) {
      const extensionsResourceTreeItem = this.r.createInstance($PWb, exportPreviewProfle);
      if (await extensionsResourceTreeItem.hasContent()) {
        roots.push(extensionsResourceTreeItem);
      }
    }
    previewFileSystemProvider.setReadOnly(true);
    return roots;
  }
  t(profile) {
    return {
      id: profile.id,
      name: profile.name,
      location: profile.location,
      isDefault: profile.isDefault,
      icon: profile.icon,
      globalStorageHome: profile.globalStorageHome,
      settingsResource: profile.settingsResource.with({ scheme: USER_DATA_PROFILE_EXPORT_SCHEME }),
      keybindingsResource: profile.keybindingsResource.with({ scheme: USER_DATA_PROFILE_EXPORT_SCHEME }),
      tasksResource: profile.tasksResource.with({ scheme: USER_DATA_PROFILE_EXPORT_SCHEME }),
      snippetsHome: profile.snippetsHome.with({ scheme: USER_DATA_PROFILE_EXPORT_SCHEME }),
      extensionsResource: profile.extensionsResource,
      cacheHome: profile.cacheHome,
      useDefaultFlags: profile.useDefaultFlags,
      isTransient: profile.isTransient
    };
  }
  async getProfileToExport() {
    let name = this.profile.name;
    if (this.profile.isDefault) {
      name = await this.b.input({
        placeHolder: localize(13411, null),
        title: localize(13412, null),
        async validateInput(input) {
          if (!input.trim()) {
            return localize(13413, null);
          }
          return void 0;
        }
      });
      if (!name) {
        return null;
      }
    }
    return super.getProfileTemplate(name, this.profile.icon);
  }
};
UserDataProfileExportState = __decorate([
  __param(2, $1M),
  __param(3, $km),
  __param(4, $Pk)
], UserDataProfileExportState);
$SC(
  $nT,
  $XWb,
  1
  /* InstantiationType.Delayed */
);

// out-build/vs/workbench/services/userDataProfile/browser/userDataProfileManagement.js
var $YWb = class $YWb2 extends $3c {
  constructor(a, b, c, f, g, h3, j, m, n, r2, s, t, u) {
    super();
    this.a = a;
    this.b = b;
    this.c = c;
    this.f = f;
    this.g = g;
    this.h = h3;
    this.j = j;
    this.m = m;
    this.n = n;
    this.r = r2;
    this.s = s;
    this.t = t;
    this.u = u;
    this.B(b.onDidChangeCurrentProfile((e) => this.w(e)));
    this.B(a.onDidChangeProfiles((e) => {
      if (e.removed.some((profile) => profile.id === this.b.currentProfile.id)) {
        const profileToUse = this.z();
        this.switchProfile(profileToUse);
        this.C(profileToUse, localize(13414, null));
        return;
      }
      const updatedCurrentProfile = e.updated.find((p) => this.b.currentProfile.id === p.id);
      if (updatedCurrentProfile) {
        const profileToUse = this.z();
        if (profileToUse?.id !== updatedCurrentProfile.id) {
          this.switchProfile(profileToUse);
          this.C(profileToUse, localize(13415, null));
        } else {
          this.C(updatedCurrentProfile, localize(13416, null));
        }
      }
    }));
  }
  async w(e) {
    if (e.previous.isTransient) {
      await this.a.cleanUpTransientProfiles();
    }
  }
  y() {
    const workspace2 = this.g.getWorkspace();
    return workspace2.configuration ?? workspace2.folders[0]?.uri;
  }
  z() {
    const workspaceUri = this.y();
    if (workspaceUri) {
      const profileForWorkspace = this.a.profiles.find((profile) => profile.workspaces?.some((ws) => this.t.extUri.isEqual(ws, workspaceUri)));
      if (profileForWorkspace) {
        return profileForWorkspace;
      }
    } else {
      const currentProfile = this.a.profiles.find((profile) => profile.id === this.b.currentProfile.id);
      if (currentProfile) {
        return currentProfile;
      }
    }
    return this.getDefaultProfileToUse();
  }
  getDefaultProfileToUse() {
    const newWindowProfileConfigValue = this.s.getValue($2L);
    if (newWindowProfileConfigValue) {
      const newWindowProfile = this.a.profiles.find((profile) => profile.name === newWindowProfileConfigValue);
      if (newWindowProfile) {
        return newWindowProfile;
      }
    }
    return this.a.defaultProfile;
  }
  async createProfile(name, options3) {
    return this.a.createNamedProfile(name, options3);
  }
  async createAndEnterProfile(name, options3) {
    const profile = await this.a.createNamedProfile(name, options3, $5k(this.g.getWorkspace()));
    await this.C(profile);
    this.m.publicLog2("profileManagementActionExecuted", { id: "createAndEnterProfile" });
    return profile;
  }
  async createAndEnterTransientProfile() {
    const profile = await this.a.createTransientProfile($5k(this.g.getWorkspace()));
    await this.C(profile);
    this.m.publicLog2("profileManagementActionExecuted", { id: "createAndEnterTransientProfile" });
    return profile;
  }
  async updateProfile(profile, updateOptions) {
    if (!this.a.profiles.some((p) => p.id === profile.id)) {
      throw new Error(`Profile ${profile.name} does not exist`);
    }
    if (profile.isDefault) {
      throw new Error(localize(13417, null));
    }
    const updatedProfile = await this.a.updateProfile(profile, updateOptions);
    this.m.publicLog2("profileManagementActionExecuted", { id: "updateProfile" });
    return updatedProfile;
  }
  async removeProfile(profile) {
    if (!this.a.profiles.some((p) => p.id === profile.id)) {
      throw new Error(`Profile ${profile.name} does not exist`);
    }
    if (profile.isDefault) {
      throw new Error(localize(13418, null));
    }
    await this.a.removeProfile(profile);
    this.m.publicLog2("profileManagementActionExecuted", { id: "removeProfile" });
  }
  async switchProfile(profile) {
    if (!this.a.profiles.some((p) => p.id === profile.id)) {
      throw new Error(`Profile ${profile.name} does not exist`);
    }
    if (this.b.currentProfile.id === profile.id) {
      return;
    }
    const workspaceUri = this.y();
    if (workspaceUri && profile.workspaces?.some((ws) => this.t.extUri.isEqual(ws, workspaceUri))) {
      return;
    }
    const workspaceIdentifier = $5k(this.g.getWorkspace());
    await this.a.setProfileForWorkspace(workspaceIdentifier, profile);
    this.m.publicLog2("profileManagementActionExecuted", { id: "switchProfile" });
    if ($2k(workspaceIdentifier)) {
      await this.C(profile);
    }
  }
  async getBuiltinProfileTemplates() {
    if (this.n.profileTemplatesUrl) {
      try {
        const context = await this.r.request({ type: "GET", url: this.n.profileTemplatesUrl }, CancellationToken.None);
        if (context.res.statusCode === 200) {
          return await $cv(context) || [];
        } else {
          this.u.error("Could not get profile templates.", context.res.statusCode);
        }
      } catch (error) {
        this.u.error(error);
      }
    }
    return [];
  }
  async C(profile, reloadMessage) {
    const isRemoteWindow = !!this.j.remoteAuthority;
    const shouldRestartExtensionHosts = this.b.currentProfile.id !== profile.id || !$Pv(this.b.currentProfile.useDefaultFlags, profile.useDefaultFlags);
    if (shouldRestartExtensionHosts) {
      if (!isRemoteWindow) {
        if (!await this.h.stopExtensionHosts(localize(13419, null))) {
          if (this.a.profiles.some((p) => p.id === this.b.currentProfile.id)) {
            await this.a.setProfileForWorkspace($5k(this.g.getWorkspace()), this.b.currentProfile);
          }
          throw new $lb();
        }
      }
    }
    await this.b.updateCurrentProfile(profile);
    if (shouldRestartExtensionHosts) {
      if (isRemoteWindow) {
        const { confirmed } = await this.f.confirm({
          message: reloadMessage ?? localize(13420, null),
          primaryButton: localize(13421, null)
        });
        if (confirmed) {
          await this.c.reload();
        }
      } else {
        await this.h.startExtensionHosts();
      }
    }
  }
};
$YWb = __decorate([
  __param(0, $rs),
  __param(1, $gT),
  __param(2, $S4),
  __param(3, $Yv),
  __param(4, $Zk),
  __param(5, $wN),
  __param(6, $US),
  __param(7, $zv),
  __param(8, $Vu),
  __param(9, $9u),
  __param(10, $kl),
  __param(11, $vl),
  __param(12, $wn)
], $YWb);
$SC(
  $hT,
  $YWb,
  0
  /* InstantiationType.Eager */
);

// out-build/vs/base/common/uriIpc.js
var $sy = 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 $Ci) {
      return null;
    }
    for (const key2 in obj) {
      if (Object.hasOwnProperty.call(obj, key2)) {
        const r2 = _transformIncomingURIs(obj[key2], transformer, revive, depth + 1);
        if (r2 !== null) {
          obj[key2] = r2;
        }
      }
    }
  }
  return null;
}
function $uy(obj, transformer) {
  const result = _transformIncomingURIs(obj, transformer, false, 0);
  if (result === null) {
    return obj;
  }
  return result;
}
function $vy(obj, transformer) {
  const result = _transformIncomingURIs(obj, transformer, true, 0);
  if (result === null) {
    return obj;
  }
  return result;
}

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

// out-build/vs/workbench/services/userDataProfile/common/remoteUserDataProfiles.js
var associatedRemoteProfilesKey = "associatedRemoteProfiles";
var $ZWb = $Qk("IRemoteUserDataProfilesService");
var RemoteUserDataProfilesService = class RemoteUserDataProfilesService2 extends $3c {
  constructor(c, f, g, h3, j, m) {
    super();
    this.c = c;
    this.f = f;
    this.g = g;
    this.h = h3;
    this.j = j;
    this.m = m;
    this.a = this.n();
  }
  async n() {
    const connection = this.f.getConnection();
    if (!connection) {
      return;
    }
    const environment = await this.f.getEnvironment();
    if (!environment) {
      return;
    }
    this.b = new $SY(environment.profiles.all, environment.profiles.home, connection.getChannel("userDataProfiles"));
    this.B(this.g.onDidChangeProfiles((e) => this.r(e)));
    const remoteProfile = await this.s(this.h.currentProfile, this.b);
    if (!remoteProfile.isDefault) {
      this.u([...this.t(), remoteProfile.id]);
    }
    this.y();
  }
  async r(e) {
    for (const profile of e.removed) {
      const remoteProfile = this.b?.profiles.find((p) => p.id === profile.id);
      if (remoteProfile) {
        await this.b?.removeProfile(remoteProfile);
      }
    }
  }
  async getRemoteProfiles() {
    await this.a;
    if (!this.b) {
      throw new Error("Remote profiles service not available in the current window");
    }
    return this.b.profiles;
  }
  async getRemoteProfile(localProfile) {
    await this.a;
    if (!this.b) {
      throw new Error("Remote profiles service not available in the current window");
    }
    return this.s(localProfile, this.b);
  }
  async s(localProfile, remoteUserDataProfilesService) {
    if (localProfile.isDefault) {
      return remoteUserDataProfilesService.defaultProfile;
    }
    let profile = remoteUserDataProfilesService.profiles.find((p) => p.id === localProfile.id);
    if (!profile) {
      profile = await remoteUserDataProfilesService.createProfile(localProfile.id, localProfile.name, {
        transient: localProfile.isTransient,
        useDefaultFlags: localProfile.useDefaultFlags
      });
      this.u([...this.t(), this.h.currentProfile.id]);
    }
    return profile;
  }
  t() {
    if (this.c.remoteAuthority) {
      const remotes = this.w();
      return remotes[this.c.remoteAuthority] ?? [];
    }
    return [];
  }
  u(profiles2) {
    if (this.c.remoteAuthority) {
      const remotes = this.w();
      profiles2 = $Rb(profiles2);
      if (profiles2.length) {
        remotes[this.c.remoteAuthority] = profiles2;
      } else {
        delete remotes[this.c.remoteAuthority];
      }
      if (Object.keys(remotes).length) {
        this.j.store(
          associatedRemoteProfilesKey,
          JSON.stringify(remotes),
          -1,
          1
          /* StorageTarget.MACHINE */
        );
      } else {
        this.j.remove(
          associatedRemoteProfilesKey,
          -1
          /* StorageScope.APPLICATION */
        );
      }
    }
  }
  w() {
    if (this.c.remoteAuthority) {
      const value = this.j.get(
        associatedRemoteProfilesKey,
        -1
        /* StorageScope.APPLICATION */
      );
      try {
        return value ? JSON.parse(value) : {};
      } catch (error) {
        this.m.error(error);
      }
    }
    return {};
  }
  async y() {
    const associatedRemoteProfiles = [];
    for (const profileId of this.t()) {
      const remoteProfile = this.b?.profiles.find((p) => p.id === profileId);
      if (!remoteProfile) {
        continue;
      }
      const localProfile = this.g.profiles.find((p) => p.id === profileId);
      if (localProfile) {
        if (localProfile.name !== remoteProfile.name) {
          await this.b?.updateProfile(remoteProfile, { name: localProfile.name });
        }
        associatedRemoteProfiles.push(profileId);
        continue;
      }
      if (remoteProfile) {
        await this.b?.removeProfile(remoteProfile);
      }
    }
    this.u(associatedRemoteProfiles);
  }
};
RemoteUserDataProfilesService = __decorate([
  __param(0, $US),
  __param(1, $RL),
  __param(2, $rs),
  __param(3, $gT),
  __param(4, $jv),
  __param(5, $wn)
], RemoteUserDataProfilesService);
$SC(
  $ZWb,
  RemoteUserDataProfilesService,
  1
  /* InstantiationType.Delayed */
);

// out-build/vs/platform/remote/common/remoteExtensionsScanner.js
var $NY = $Qk("IRemoteExtensionsScannerService");
var $OY = "remoteExtensionsScanner";

// out-build/vs/workbench/services/remote/common/remoteExtensionsScanner.js
var RemoteExtensionsScannerService = class RemoteExtensionsScannerService2 {
  constructor(a, b, c, d, e, f, g) {
    this.a = a;
    this.b = b;
    this.c = c;
    this.d = d;
    this.e = e;
    this.f = f;
    this.g = g;
  }
  whenExtensionsReady() {
    return this.h((channel) => channel.call("whenExtensionsReady"), void 0);
  }
  async scanExtensions() {
    try {
      const languagePack = await this.e.getExtensionIdProvidingCurrentLocale();
      return await this.h(async (channel) => {
        const profileLocation = this.c.currentProfile.isDefault ? void 0 : (await this.d.getRemoteProfile(this.c.currentProfile)).extensionsResource;
        const scannedExtensions = await channel.call("scanExtensions", [
          $z,
          profileLocation,
          this.f.getInstalledWorkspaceExtensionLocations(),
          this.b.extensionDevelopmentLocationURI,
          languagePack
        ]);
        scannedExtensions.forEach((extension) => {
          extension.extensionLocation = URI.revive(extension.extensionLocation);
        });
        return scannedExtensions;
      }, []);
    } catch (error) {
      this.g.error(error);
      return [];
    }
  }
  h(callback, fallback2) {
    const connection = this.a.getConnection();
    if (!connection) {
      return Promise.resolve(fallback2);
    }
    return connection.withChannel($OY, (channel) => callback(channel));
  }
};
RemoteExtensionsScannerService = __decorate([
  __param(0, $RL),
  __param(1, $US),
  __param(2, $gT),
  __param(3, $ZWb),
  __param(4, $OCb),
  __param(5, $pzb),
  __param(6, $wn)
], RemoteExtensionsScannerService);
$SC(
  $NY,
  RemoteExtensionsScannerService,
  1
  /* InstantiationType.Delayed */
);

// out-build/vs/workbench/services/terminal/common/embedderTerminalService.js
var $U4 = $Qk("embedderTerminalService");
var EmbedderTerminalService = class {
  constructor() {
    this.a = new $ze();
    this.onDidCreateTerminal = Event2.buffer(this.a.event);
  }
  createTerminal(options3) {
    const slc = {
      name: options3.name,
      isFeatureTerminal: true,
      customPtyImplementation(terminalId, cols, rows) {
        return new EmbedderTerminalProcess(terminalId, options3.pty);
      }
    };
    this.a.fire(slc);
  }
};
var EmbedderTerminalProcess = class extends $3c {
  constructor(id2, pty) {
    super();
    this.id = id2;
    this.shouldPersist = false;
    this.b = this.B(new $ze());
    this.onProcessReady = this.b.event;
    this.c = this.B(new $ze());
    this.onDidChangeProperty = this.c.event;
    this.f = this.B(new $ze());
    this.onProcessExit = this.f.event;
    this.a = pty;
    this.onProcessData = this.a.onDidWrite;
    if (this.a.onDidClose) {
      this.B(this.a.onDidClose((e) => this.f.fire(e || void 0)));
    }
    if (this.a.onDidChangeName) {
      this.B(this.a.onDidChangeName((e) => this.c.fire({
        type: "title",
        value: e
      })));
    }
  }
  async start() {
    this.b.fire({ pid: -1, cwd: "", windowsPty: void 0 });
    this.a.open();
    return void 0;
  }
  shutdown() {
    this.a.close();
  }
  // TODO: A lot of these aren't useful for some implementations of ITerminalChildProcess, should
  // they be optional? Should there be a base class for "external" consumers to implement?
  input() {
  }
  async processBinary() {
  }
  resize() {
  }
  clearBuffer() {
  }
  acknowledgeDataEvent() {
  }
  async setUnicodeVersion() {
  }
  async getInitialCwd() {
    return "";
  }
  async getCwd() {
    return "";
  }
  refreshProperty(property) {
    throw new Error(`refreshProperty is not suppported in EmbedderTerminalProcess. property: ${property}`);
  }
  updateProperty(property, value) {
    throw new Error(`updateProperty is not suppported in EmbedderTerminalProcess. property: ${property}, value: ${value}`);
  }
};
$SC(
  $U4,
  EmbedderTerminalService,
  1
  /* InstantiationType.Delayed */
);

// out-build/vs/workbench/services/views/common/viewContainerModel.js
$hJ(class extends $gJ {
  constructor() {
    super({
      id: "_workbench.output.showViewsLog",
      title: localize2(13475, "Show Views Log"),
      category: $qn.Developer,
      f1: true
    });
  }
  async run(servicesAccessor) {
    const loggerService = servicesAccessor.get($xn);
    const outputService = servicesAccessor.get($RS);
    loggerService.setVisibility($6M, true);
    outputService.showChannel($6M);
  }
});
function $1Wb(viewContainerStorageId) {
  return `${viewContainerStorageId}.hidden`;
}
var ViewDescriptorsState = class ViewDescriptorsState2 extends $3c {
  constructor(viewContainerStorageId, m, n, loggerService) {
    super();
    this.m = m;
    this.n = n;
    this.h = this.B(new $ze());
    this.onDidChangeStoredState = this.h.event;
    this.j = new $sf(() => loggerService.createLogger($6M, { name: $7M, hidden: true }));
    this.f = $1Wb(viewContainerStorageId);
    this.c = viewContainerStorageId;
    this.B(this.n.onDidChangeValue(0, this.f, this.q)(() => this.t()));
    this.g = this.u();
  }
  set(id2, state) {
    this.g.set(id2, state);
  }
  get(id2) {
    return this.g.get(id2);
  }
  updateState(viewDescriptors) {
    this.r(viewDescriptors);
    this.s(viewDescriptors);
  }
  r(viewDescriptors) {
    const storedViewsStates = this.w();
    for (const viewDescriptor3 of viewDescriptors) {
      const viewState = this.get(viewDescriptor3.id);
      if (viewState) {
        storedViewsStates[viewDescriptor3.id] = {
          collapsed: !!viewState.collapsed,
          isHidden: !viewState.visibleWorkspace,
          size: viewState.size,
          order: viewDescriptor3.workspace && viewState ? viewState.order : void 0
        };
      }
    }
    if (Object.keys(storedViewsStates).length > 0) {
      this.n.store(
        this.c,
        JSON.stringify(storedViewsStates),
        1,
        1
        /* StorageTarget.MACHINE */
      );
    } else {
      this.n.remove(
        this.c,
        1
        /* StorageScope.WORKSPACE */
      );
    }
  }
  s(viewDescriptors) {
    const storedGlobalState = this.y();
    for (const viewDescriptor3 of viewDescriptors) {
      const state = this.get(viewDescriptor3.id);
      storedGlobalState.set(viewDescriptor3.id, {
        id: viewDescriptor3.id,
        isHidden: state && viewDescriptor3.canToggleVisibility ? !state.visibleGlobal : false,
        order: !viewDescriptor3.workspace && state ? state.order : void 0
      });
    }
    this.z(storedGlobalState);
  }
  t() {
    if (this.F !== this.G()) {
      this.D = void 0;
      const storedViewsVisibilityStates = this.y();
      const storedWorkspaceViewsStates = this.w();
      const changedStates = [];
      for (const [id2, storedState] of storedViewsVisibilityStates) {
        const state = this.get(id2);
        if (state) {
          if (state.visibleGlobal !== !storedState.isHidden) {
            if (!storedState.isHidden) {
              this.j.value.info(`View visibility state changed: ${id2} is now visible`, this.m);
            }
            changedStates.push({ id: id2, visible: !storedState.isHidden });
          }
        } else {
          const workspaceViewState = storedWorkspaceViewsStates[id2];
          this.set(id2, {
            active: false,
            visibleGlobal: !storedState.isHidden,
            visibleWorkspace: $Gg(workspaceViewState?.isHidden) ? void 0 : !workspaceViewState?.isHidden,
            collapsed: workspaceViewState?.collapsed,
            order: workspaceViewState?.order,
            size: workspaceViewState?.size
          });
        }
      }
      if (changedStates.length) {
        this.h.fire(changedStates);
        for (const changedState of changedStates) {
          const state = this.get(changedState.id);
          if (state) {
            state.visibleGlobal = changedState.visible;
          }
        }
      }
    }
  }
  u() {
    const viewStates = /* @__PURE__ */ new Map();
    const workspaceViewsStates = this.w();
    for (const id2 of Object.keys(workspaceViewsStates)) {
      const workspaceViewState = workspaceViewsStates[id2];
      viewStates.set(id2, {
        active: false,
        visibleGlobal: void 0,
        visibleWorkspace: $Gg(workspaceViewState.isHidden) ? void 0 : !workspaceViewState.isHidden,
        collapsed: workspaceViewState.collapsed,
        order: workspaceViewState.order,
        size: workspaceViewState.size
      });
    }
    const value = this.n.get(this.f, 1, "[]");
    const { state: workspaceVisibilityStates } = this.C(value);
    if (workspaceVisibilityStates.size > 0) {
      for (const { id: id2, isHidden } of workspaceVisibilityStates.values()) {
        const viewState = viewStates.get(id2);
        if (viewState) {
          if ($Gg(viewState.visibleWorkspace)) {
            viewState.visibleWorkspace = !isHidden;
          }
        } else {
          viewStates.set(id2, {
            active: false,
            collapsed: void 0,
            visibleGlobal: void 0,
            visibleWorkspace: !isHidden
          });
        }
      }
      this.n.remove(
        this.f,
        1
        /* StorageScope.WORKSPACE */
      );
    }
    const { state, hasDuplicates } = this.C(this.F);
    if (hasDuplicates) {
      this.z(state);
    }
    for (const { id: id2, isHidden, order } of state.values()) {
      const viewState = viewStates.get(id2);
      if (viewState) {
        viewState.visibleGlobal = !isHidden;
        if (!$Gg(order)) {
          viewState.order = order;
        }
      } else {
        viewStates.set(id2, {
          active: false,
          visibleGlobal: !isHidden,
          order,
          collapsed: void 0,
          visibleWorkspace: void 0
        });
      }
    }
    return viewStates;
  }
  w() {
    return JSON.parse(this.n.get(this.c, 1, "{}"));
  }
  y() {
    return this.C(this.F).state;
  }
  z(storedGlobalState) {
    this.F = JSON.stringify([...storedGlobalState.values()]);
  }
  C(value) {
    const storedValue = JSON.parse(value);
    let hasDuplicates = false;
    const state = storedValue.reduce((result, storedState) => {
      if (typeof storedState === "string") {
        hasDuplicates = hasDuplicates || result.has(storedState);
        result.set(storedState, { id: storedState, isHidden: true });
      } else {
        hasDuplicates = hasDuplicates || result.has(storedState.id);
        result.set(storedState.id, storedState);
      }
      return result;
    }, /* @__PURE__ */ new Map());
    return { state, hasDuplicates };
  }
  get F() {
    if (!this.D) {
      this.D = this.G();
    }
    return this.D;
  }
  set F(globalViewsStatesValue) {
    if (this.F !== globalViewsStatesValue) {
      this.D = globalViewsStatesValue;
      this.H(globalViewsStatesValue);
    }
  }
  G() {
    return this.n.get(this.f, 0, "[]");
  }
  H(value) {
    this.n.store(
      this.f,
      value,
      0,
      0
      /* StorageTarget.USER */
    );
  }
};
ViewDescriptorsState = __decorate([
  __param(2, $jv),
  __param(3, $xn)
], ViewDescriptorsState);
var $2Wb = class $2Wb2 extends $3c {
  get title() {
    return this.h;
  }
  get icon() {
    return this.j;
  }
  get keybindingId() {
    return this.m;
  }
  // All View Descriptors
  get allViewDescriptors() {
    return this.f.map((item) => item.viewDescriptor);
  }
  // Active View Descriptors
  get activeViewDescriptors() {
    return this.f.filter((item) => item.state.active).map((item) => item.viewDescriptor);
  }
  // Visible View Descriptors
  get visibleViewDescriptors() {
    return this.f.filter((item) => this.N(item)).map((item) => item.viewDescriptor);
  }
  constructor(viewContainer5, instantiationService, z, loggerService) {
    super();
    this.viewContainer = viewContainer5;
    this.z = z;
    this.c = new $Jc();
    this.f = [];
    this.n = this.B(new $ze());
    this.onDidChangeContainerInfo = this.n.event;
    this.r = this.B(new $ze());
    this.onDidChangeAllViewDescriptors = this.r.event;
    this.s = this.B(new $ze());
    this.onDidChangeActiveViewDescriptors = this.s.event;
    this.t = this.B(new $ze());
    this.onDidAddVisibleViewDescriptors = this.t.event;
    this.u = this.B(new $ze());
    this.onDidRemoveVisibleViewDescriptors = this.u.event;
    this.w = this.B(new $ze());
    this.onDidMoveVisibleViewDescriptors = this.w.event;
    this.y = new $sf(() => loggerService.createLogger($6M, { name: $7M, hidden: true }));
    this.B(Event2.filter(z.onDidChangeContext, (e) => e.affectsSome(this.c))(() => this.H()));
    this.g = this.B(instantiationService.createInstance(ViewDescriptorsState, viewContainer5.storageId || `${viewContainer5.id}.state`, typeof viewContainer5.title === "string" ? viewContainer5.title : viewContainer5.title.original));
    this.B(this.g.onDidChangeStoredState((items) => this.F(items)));
    this.C();
  }
  C() {
    const useDefaultContainerInfo = this.viewContainer.alwaysUseContainerInfo || this.visibleViewDescriptors.length === 0 || this.visibleViewDescriptors.some((v) => $Wn.as(Extensions5.ViewsRegistry).getViewContainer(v.id) === this.viewContainer);
    const title = useDefaultContainerInfo ? typeof this.viewContainer.title === "string" ? this.viewContainer.title : this.viewContainer.title.value : this.visibleViewDescriptors[0]?.containerTitle || this.visibleViewDescriptors[0]?.name?.value || "";
    let titleChanged = false;
    if (this.h !== title) {
      this.h = title;
      titleChanged = true;
    }
    const icon2 = useDefaultContainerInfo ? this.viewContainer.icon : this.visibleViewDescriptors[0]?.containerIcon || $8M;
    let iconChanged = false;
    if (!this.D(icon2)) {
      this.j = icon2;
      iconChanged = true;
    }
    const keybindingId = this.viewContainer.openCommandActionDescriptor?.id ?? this.activeViewDescriptors.find((v) => v.openCommandActionDescriptor)?.openCommandActionDescriptor?.id;
    let keybindingIdChanged = false;
    if (this.m !== keybindingId) {
      this.m = keybindingId;
      keybindingIdChanged = true;
    }
    if (titleChanged || iconChanged || keybindingIdChanged) {
      this.n.fire({ title: titleChanged, icon: iconChanged, keybindingId: keybindingIdChanged });
    }
  }
  D(icon2) {
    if (URI.isUri(icon2)) {
      return URI.isUri(this.j) && $oh(icon2, this.j);
    } else if (ThemeIcon.isThemeIcon(icon2)) {
      return ThemeIcon.isThemeIcon(this.j) && ThemeIcon.isEqual(icon2, this.j);
    }
    return icon2 === this.j;
  }
  isVisible(id2) {
    const viewDescriptorItem = this.f.find((v) => v.viewDescriptor.id === id2);
    if (!viewDescriptorItem) {
      throw new Error(`Unknown view ${id2}`);
    }
    return this.N(viewDescriptorItem);
  }
  setVisible(id2, visible) {
    this.F([{ id: id2, visible }]);
  }
  F(viewDescriptors) {
    const viewDescriptorItemsToHide = $Mb(viewDescriptors.filter(({ visible }) => !visible).map(({ id: id2 }) => this.Q(id2)));
    const removed = [];
    for (const { viewDescriptorItem, visibleIndex } of viewDescriptorItemsToHide) {
      if (this.G(viewDescriptorItem, false)) {
        removed.push({ viewDescriptor: viewDescriptorItem.viewDescriptor, index: visibleIndex });
      }
    }
    if (removed.length) {
      this.J(removed);
    }
    const added = [];
    for (const { id: id2, visible } of viewDescriptors) {
      if (!visible) {
        continue;
      }
      const foundViewDescriptor = this.Q(id2);
      if (!foundViewDescriptor) {
        continue;
      }
      const { viewDescriptorItem, visibleIndex } = foundViewDescriptor;
      if (this.G(viewDescriptorItem, true)) {
        added.push({ index: visibleIndex, viewDescriptor: viewDescriptorItem.viewDescriptor, size: viewDescriptorItem.state.size, collapsed: !!viewDescriptorItem.state.collapsed });
      }
    }
    if (added.length) {
      this.I(added);
    }
  }
  G(viewDescriptorItem, visible) {
    if (!viewDescriptorItem.viewDescriptor.canToggleVisibility) {
      return false;
    }
    if (this.O(viewDescriptorItem) === visible) {
      return false;
    }
    if (viewDescriptorItem.viewDescriptor.workspace) {
      viewDescriptorItem.state.visibleWorkspace = visible;
    } else {
      viewDescriptorItem.state.visibleGlobal = visible;
      if (visible) {
        this.y.value.info(`Showing view ${viewDescriptorItem.viewDescriptor.id} in the container ${this.viewContainer.id}`);
      }
    }
    return this.N(viewDescriptorItem) === visible;
  }
  isCollapsed(id2) {
    return !!this.P(id2).viewDescriptorItem.state.collapsed;
  }
  setCollapsed(id2, collapsed2) {
    const { viewDescriptorItem } = this.P(id2);
    if (viewDescriptorItem.state.collapsed !== collapsed2) {
      viewDescriptorItem.state.collapsed = collapsed2;
    }
    this.g.updateState(this.allViewDescriptors);
  }
  getSize(id2) {
    return this.P(id2).viewDescriptorItem.state.size;
  }
  setSizes(newSizes) {
    for (const { id: id2, size } of newSizes) {
      const { viewDescriptorItem } = this.P(id2);
      if (viewDescriptorItem.state.size !== size) {
        viewDescriptorItem.state.size = size;
      }
    }
    this.g.updateState(this.allViewDescriptors);
  }
  move(from, to) {
    const fromIndex = this.f.findIndex((v) => v.viewDescriptor.id === from);
    const toIndex = this.f.findIndex((v) => v.viewDescriptor.id === to);
    const fromViewDescriptor = this.f[fromIndex];
    const toViewDescriptor = this.f[toIndex];
    $Ob(this.f, fromIndex, toIndex);
    for (let index = 0; index < this.f.length; index++) {
      this.f[index].state.order = index;
    }
    this.L({ index: fromIndex, viewDescriptor: fromViewDescriptor.viewDescriptor }, { index: toIndex, viewDescriptor: toViewDescriptor.viewDescriptor });
  }
  add(addedViewDescriptorStates) {
    const addedItems = [];
    for (const addedViewDescriptorState of addedViewDescriptorStates) {
      const viewDescriptor3 = addedViewDescriptorState.viewDescriptor;
      if (viewDescriptor3.when) {
        for (const key2 of viewDescriptor3.when.keys()) {
          this.c.add(key2);
        }
      }
      let state = this.g.get(viewDescriptor3.id);
      if (state) {
        if (viewDescriptor3.workspace) {
          state.visibleWorkspace = $Ig(addedViewDescriptorState.visible) ? $Ig(state.visibleWorkspace) ? !viewDescriptor3.hideByDefault : state.visibleWorkspace : addedViewDescriptorState.visible;
        } else {
          const isVisible = state.visibleGlobal;
          state.visibleGlobal = $Ig(addedViewDescriptorState.visible) ? $Ig(state.visibleGlobal) ? !viewDescriptor3.hideByDefault : state.visibleGlobal : addedViewDescriptorState.visible;
          if (state.visibleGlobal && !isVisible) {
            this.y.value.info(`Added view ${viewDescriptor3.id} in the container ${this.viewContainer.id} and showing it.`, `${isVisible}`, `${viewDescriptor3.hideByDefault}`, `${addedViewDescriptorState.visible}`);
          }
        }
        state.collapsed = $Ig(addedViewDescriptorState.collapsed) ? $Ig(state.collapsed) ? !!viewDescriptor3.collapsed : state.collapsed : addedViewDescriptorState.collapsed;
      } else {
        state = {
          active: false,
          visibleGlobal: $Ig(addedViewDescriptorState.visible) ? !viewDescriptor3.hideByDefault : addedViewDescriptorState.visible,
          visibleWorkspace: $Ig(addedViewDescriptorState.visible) ? !viewDescriptor3.hideByDefault : addedViewDescriptorState.visible,
          collapsed: $Ig(addedViewDescriptorState.collapsed) ? !!viewDescriptor3.collapsed : addedViewDescriptorState.collapsed
        };
      }
      this.g.set(viewDescriptor3.id, state);
      state.active = this.z.contextMatchesRules(viewDescriptor3.when);
      addedItems.push({ viewDescriptor: viewDescriptor3, state });
    }
    this.f.push(...addedItems);
    this.f.sort(this.R.bind(this));
    this.r.fire({ added: addedItems.map(({ viewDescriptor: viewDescriptor3 }) => viewDescriptor3), removed: [] });
    const addedActiveItems = [];
    for (const viewDescriptorItem of addedItems) {
      if (viewDescriptorItem.state.active) {
        addedActiveItems.push({ viewDescriptorItem, visible: this.N(viewDescriptorItem) });
      }
    }
    if (addedActiveItems.length) {
      this.s.fire({ added: addedActiveItems.map(({ viewDescriptorItem }) => viewDescriptorItem.viewDescriptor), removed: [] });
    }
    const addedVisibleDescriptors = [];
    for (const { viewDescriptorItem, visible } of addedActiveItems) {
      if (visible && this.N(viewDescriptorItem)) {
        const { visibleIndex } = this.P(viewDescriptorItem.viewDescriptor.id);
        addedVisibleDescriptors.push({ index: visibleIndex, viewDescriptor: viewDescriptorItem.viewDescriptor, size: viewDescriptorItem.state.size, collapsed: !!viewDescriptorItem.state.collapsed });
      }
    }
    this.I(addedVisibleDescriptors);
  }
  remove(viewDescriptors) {
    const removed = [];
    const removedItems = [];
    const removedActiveDescriptors = [];
    const removedVisibleDescriptors = [];
    for (const viewDescriptor3 of viewDescriptors) {
      if (viewDescriptor3.when) {
        for (const key2 of viewDescriptor3.when.keys()) {
          this.c.delete(key2);
        }
      }
      const index = this.f.findIndex((i2) => i2.viewDescriptor.id === viewDescriptor3.id);
      if (index !== -1) {
        removed.push(viewDescriptor3);
        const viewDescriptorItem = this.f[index];
        if (viewDescriptorItem.state.active) {
          removedActiveDescriptors.push(viewDescriptorItem.viewDescriptor);
        }
        if (this.N(viewDescriptorItem)) {
          const { visibleIndex } = this.P(viewDescriptorItem.viewDescriptor.id);
          removedVisibleDescriptors.push({ index: visibleIndex, viewDescriptor: viewDescriptorItem.viewDescriptor });
        }
        removedItems.push(viewDescriptorItem);
      }
    }
    removedItems.forEach((item) => this.f.splice(this.f.indexOf(item), 1));
    this.J(removedVisibleDescriptors);
    if (removedActiveDescriptors.length) {
      this.s.fire({ added: [], removed: removedActiveDescriptors });
    }
    if (removed.length) {
      this.r.fire({ added: [], removed });
    }
  }
  H() {
    const addedActiveItems = [];
    const removedActiveItems = [];
    for (const item of this.f) {
      const wasActive = item.state.active;
      const isActive2 = this.z.contextMatchesRules(item.viewDescriptor.when);
      if (wasActive !== isActive2) {
        if (isActive2) {
          addedActiveItems.push({ item, visibleWhenActive: this.O(item) });
        } else {
          removedActiveItems.push(item);
        }
      }
    }
    const removedVisibleDescriptors = [];
    for (const item of removedActiveItems) {
      if (this.N(item)) {
        const { visibleIndex } = this.P(item.viewDescriptor.id);
        removedVisibleDescriptors.push({ index: visibleIndex, viewDescriptor: item.viewDescriptor });
      }
    }
    removedActiveItems.forEach((item) => item.state.active = false);
    addedActiveItems.forEach(({ item }) => item.state.active = true);
    this.J(removedVisibleDescriptors);
    if (addedActiveItems.length || removedActiveItems.length) {
      this.s.fire({ added: addedActiveItems.map(({ item }) => item.viewDescriptor), removed: removedActiveItems.map((item) => item.viewDescriptor) });
    }
    const addedVisibleDescriptors = [];
    for (const { item, visibleWhenActive } of addedActiveItems) {
      if (visibleWhenActive && this.N(item)) {
        const { visibleIndex } = this.P(item.viewDescriptor.id);
        addedVisibleDescriptors.push({ index: visibleIndex, viewDescriptor: item.viewDescriptor, size: item.state.size, collapsed: !!item.state.collapsed });
      }
    }
    this.I(addedVisibleDescriptors);
  }
  I(added) {
    if (added.length) {
      this.t.fire(added.sort((a, b) => a.index - b.index));
      this.M(`Added views:${added.map((v) => v.viewDescriptor.id).join(",")} in ${this.viewContainer.id}`);
    }
  }
  J(removed) {
    if (removed.length) {
      this.u.fire(removed.sort((a, b) => b.index - a.index));
      this.M(`Removed views:${removed.map((v) => v.viewDescriptor.id).join(",")} from ${this.viewContainer.id}`);
    }
  }
  L(from, to) {
    this.w.fire({ from, to });
    this.M(`Moved view ${from.viewDescriptor.id} to ${to.viewDescriptor.id} in ${this.viewContainer.id}`);
  }
  M(reason) {
    this.y.value.info(reason);
    this.g.updateState(this.allViewDescriptors);
    this.C();
  }
  N(viewDescriptorItem) {
    if (!viewDescriptorItem.state.active) {
      return false;
    }
    return this.O(viewDescriptorItem);
  }
  O(viewDescriptorItem) {
    if (viewDescriptorItem.viewDescriptor.workspace) {
      return !!viewDescriptorItem.state.visibleWorkspace;
    }
    return !!viewDescriptorItem.state.visibleGlobal;
  }
  P(id2) {
    const result = this.Q(id2);
    if (result) {
      return result;
    }
    throw new Error(`view descriptor ${id2} not found`);
  }
  Q(id2) {
    for (let i2 = 0, visibleIndex = 0; i2 < this.f.length; i2++) {
      const viewDescriptorItem = this.f[i2];
      if (viewDescriptorItem.viewDescriptor.id === id2) {
        return { index: i2, visibleIndex, viewDescriptorItem };
      }
      if (this.N(viewDescriptorItem)) {
        visibleIndex++;
      }
    }
    return void 0;
  }
  R(a, b) {
    if (a.viewDescriptor.id === b.viewDescriptor.id) {
      return 0;
    }
    return this.S(a) - this.S(b) || this.U(a.viewDescriptor, b.viewDescriptor);
  }
  S(viewDescriptorItem) {
    const viewOrder = typeof viewDescriptorItem.state.order === "number" ? viewDescriptorItem.state.order : viewDescriptorItem.viewDescriptor.order;
    return typeof viewOrder === "number" ? viewOrder : Number.MAX_VALUE;
  }
  U(a, b) {
    if (!a.group || !b.group) {
      return 0;
    }
    if (a.group === b.group) {
      return 0;
    }
    return a.group < b.group ? -1 : 1;
  }
};
$2Wb = __decorate([
  __param(1, $Pk),
  __param(2, $on),
  __param(3, $xn)
], $2Wb);

// out-build/vs/workbench/services/views/browser/viewDescriptorService.js
var $3Wb_1;
function getViewContainerStorageId(viewContainerId) {
  return `${viewContainerId}.state`;
}
var $3Wb = class $3Wb2 extends $3c {
  static {
    $3Wb_1 = this;
  }
  static {
    this.a = "views.customizations";
  }
  static {
    this.b = "workbench.views.service";
  }
  get viewContainers() {
    return this.w.all;
  }
  constructor(G, H, I, J, L, loggerService) {
    super();
    this.G = G;
    this.H = H;
    this.I = I;
    this.J = J;
    this.L = L;
    this.c = this.B(new $ze());
    this.onDidChangeContainer = this.c.event;
    this.f = this.B(new $ze());
    this.onDidChangeLocation = this.f.event;
    this.g = this.B(new $ze());
    this.onDidChangeContainerLocation = this.g.event;
    this.h = this.B(new $_c());
    this.j = this.B(new $_c());
    this.m = false;
    this.D = this.B(new $ze());
    this.onDidChangeViewContainers = this.D.event;
    this.F = new $sf(() => loggerService.createLogger($6M, { name: $7M, hidden: true }));
    this.n = /* @__PURE__ */ new Map();
    this.r = /* @__PURE__ */ new Map();
    this.s = /* @__PURE__ */ new Map();
    this.t = /* @__PURE__ */ new Map();
    this.w = $Wn.as(Extensions5.ViewContainersRegistry);
    this.u = $Wn.as(Extensions5.ViewsRegistry);
    this.M();
    this.y = new Map(Object.entries(this.gb.viewContainerLocations));
    this.z = new Map(Object.entries(this.gb.viewLocations));
    this.C = new Map(Object.entries(this.gb.viewContainerBadgeEnablementStates));
    this.viewContainers.forEach((viewContainer5) => this.kb(viewContainer5));
    this.B(this.u.onViewsRegistered((views) => this.Q(views)));
    this.B(this.u.onViewsDeregistered(({ views, viewContainer: viewContainer5 }) => this.S(views, viewContainer5)));
    this.B(this.u.onDidChangeContainer(({ views, from, to }) => this.W(views, from, to)));
    this.B(this.w.onDidRegister(({ viewContainer: viewContainer5 }) => {
      this.kb(viewContainer5);
      this.D.fire({ added: [{ container: viewContainer5, location: this.getViewContainerLocation(viewContainer5) }], removed: [] });
    }));
    this.B(this.w.onDidDeregister(({ viewContainer: viewContainer5, viewContainerLocation }) => {
      this.mb(viewContainer5);
      this.D.fire({ removed: [{ container: viewContainer5, location: viewContainerLocation }], added: [] });
    }));
    this.B(this.I.onDidChangeValue(0, $3Wb_1.a, this.q)(() => this.bb()));
    this.J.whenInstalledExtensionsRegistered().then(() => this.whenExtensionsRegistered());
  }
  M() {
    if (this.I.get(
      $3Wb_1.a,
      0
      /* StorageScope.PROFILE */
    )) {
      return;
    }
    const viewContainerLocationsValue = this.I.get(
      "views.cachedViewContainerLocations",
      0
      /* StorageScope.PROFILE */
    );
    const viewDescriptorLocationsValue = this.I.get(
      "views.cachedViewPositions",
      0
      /* StorageScope.PROFILE */
    );
    if (!viewContainerLocationsValue && !viewDescriptorLocationsValue) {
      return;
    }
    const viewContainerLocations = viewContainerLocationsValue ? JSON.parse(viewContainerLocationsValue) : [];
    const viewDescriptorLocations = viewDescriptorLocationsValue ? JSON.parse(viewDescriptorLocationsValue) : [];
    const viewsCustomizations = {
      viewContainerLocations: viewContainerLocations.reduce((result, [id2, location3]) => {
        result[id2] = location3;
        return result;
      }, {}),
      viewLocations: viewDescriptorLocations.reduce((result, [id2, { containerId }]) => {
        result[id2] = containerId;
        return result;
      }, {}),
      viewContainerBadgeEnablementStates: {}
    };
    this.I.store(
      $3Wb_1.a,
      JSON.stringify(viewsCustomizations),
      0,
      0
      /* StorageTarget.USER */
    );
    this.I.remove(
      "views.cachedViewContainerLocations",
      0
      /* StorageScope.PROFILE */
    );
    this.I.remove(
      "views.cachedViewPositions",
      0
      /* StorageScope.PROFILE */
    );
  }
  N(groupedViews) {
    for (const [containerId, views] of groupedViews.entries()) {
      const viewContainer5 = this.w.get(containerId);
      if (!viewContainer5 || !this.h.has(viewContainer5)) {
        if (this.R(containerId)) {
          const viewContainerLocation = this.y.get(containerId);
          if (viewContainerLocation !== void 0) {
            this.ab(viewContainerLocation, containerId);
          }
        }
        continue;
      }
      const viewsToAdd = views.filter((view) => this.getViewContainerModel(viewContainer5).allViewDescriptors.filter((vd) => vd.id === view.id).length === 0);
      this.sb(viewContainer5, viewsToAdd);
    }
  }
  O(groupedViews) {
    for (const [viewContainerId, views] of groupedViews.entries()) {
      const viewContainer5 = this.w.get(viewContainerId);
      if (!viewContainer5 || !this.h.has(viewContainer5)) {
        continue;
      }
      this.tb(viewContainer5, views);
    }
  }
  P() {
    for (const [viewId, containerId] of this.z.entries()) {
      if (this.w.get(containerId)) {
        continue;
      }
      const viewContainer5 = this.u.getViewContainer(viewId);
      const viewDescriptor3 = this.getViewDescriptorById(viewId);
      if (viewContainer5 && viewDescriptor3) {
        this.sb(viewContainer5, [viewDescriptor3]);
      }
    }
  }
  whenExtensionsRegistered() {
    this.P();
    for (const viewContainerId of [...this.y.keys()]) {
      this.$(viewContainerId);
    }
    this.eb();
    for (const [key2, value] of this.h) {
      this.pb(key2, value);
    }
    this.m = true;
  }
  Q(views) {
    this.H.bufferChangeEvents(() => {
      views.forEach(({ views: views2, viewContainer: viewContainer5 }) => {
        const regroupedViews = this.U(viewContainer5.id, views2);
        this.N(regroupedViews);
        views2.forEach((viewDescriptor3) => this.wb(viewDescriptor3).set(!!viewDescriptor3.canMoveView));
      });
    });
  }
  R(id2) {
    return id2.startsWith($3Wb_1.b);
  }
  S(views, viewContainer5) {
    const regroupedViews = this.U(viewContainer5.id, views);
    this.O(regroupedViews);
    this.H.bufferChangeEvents(() => {
      views.forEach((viewDescriptor3) => this.wb(viewDescriptor3).set(false));
    });
  }
  U(containerId, views) {
    const viewsByContainer = /* @__PURE__ */ new Map();
    for (const viewDescriptor3 of views) {
      const correctContainerId = this.z.get(viewDescriptor3.id) ?? containerId;
      let containerViews = viewsByContainer.get(correctContainerId);
      if (!containerViews) {
        viewsByContainer.set(correctContainerId, containerViews = []);
      }
      containerViews.push(viewDescriptor3);
    }
    return viewsByContainer;
  }
  getViewDescriptorById(viewId) {
    return this.u.getView(viewId);
  }
  getViewLocationById(viewId) {
    const container2 = this.getViewContainerByViewId(viewId);
    if (container2 === null) {
      return null;
    }
    return this.getViewContainerLocation(container2);
  }
  getViewContainerByViewId(viewId) {
    const containerId = this.z.get(viewId);
    return containerId ? this.w.get(containerId) ?? null : this.getDefaultContainerById(viewId);
  }
  getViewContainerLocation(viewContainer5) {
    return this.y.get(viewContainer5.id) ?? this.getDefaultViewContainerLocation(viewContainer5);
  }
  getDefaultViewContainerLocation(viewContainer5) {
    return this.w.getViewContainerLocation(viewContainer5);
  }
  getDefaultContainerById(viewId) {
    return this.u.getViewContainer(viewId) ?? null;
  }
  getViewContainerModel(container2) {
    return this.lb(container2);
  }
  getViewContainerById(id2) {
    return this.w.get(id2) || null;
  }
  getViewContainersByLocation(location3) {
    return this.viewContainers.filter((v) => this.getViewContainerLocation(v) === location3);
  }
  getDefaultViewContainer(location3) {
    return this.w.getDefaultViewContainer(location3);
  }
  moveViewContainerToLocation(viewContainer5, location3, requestedIndex, reason) {
    this.F.value.info(`moveViewContainerToLocation: viewContainer:${viewContainer5.id} location:${location3} reason:${reason}`);
    this.Z(viewContainer5, location3, requestedIndex);
    this.eb();
  }
  getViewContainerBadgeEnablementState(id2) {
    return this.C.get(id2) ?? true;
  }
  setViewContainerBadgeEnablementState(id2, badgesEnabled) {
    this.C.set(id2, badgesEnabled);
    this.eb();
  }
  moveViewToLocation(view, location3, reason) {
    this.F.value.info(`moveViewToLocation: view:${view.id} location:${location3} reason:${reason}`);
    const container2 = this.ab(location3);
    this.moveViewsToContainer([view], container2);
  }
  moveViewsToContainer(views, viewContainer5, visibilityState, reason) {
    if (!views.length) {
      return;
    }
    this.F.value.info(`moveViewsToContainer: views:${views.map((view) => view.id).join(",")} viewContainer:${viewContainer5.id} reason:${reason}`);
    const from = this.getViewContainerByViewId(views[0].id);
    const to = viewContainer5;
    if (from && to && from !== to) {
      this.Y(views, from, to, visibilityState);
      this.$(from.id);
      this.eb();
      this.X(views, from, to);
    }
  }
  reset() {
    for (const viewContainer5 of this.viewContainers) {
      const viewContainerModel = this.getViewContainerModel(viewContainer5);
      for (const viewDescriptor3 of viewContainerModel.allViewDescriptors) {
        const defaultContainer = this.getDefaultContainerById(viewDescriptor3.id);
        const currentContainer = this.getViewContainerByViewId(viewDescriptor3.id);
        if (currentContainer && defaultContainer && currentContainer !== defaultContainer) {
          this.Y([viewDescriptor3], currentContainer, defaultContainer);
        }
      }
      const defaultContainerLocation = this.getDefaultViewContainerLocation(viewContainer5);
      const currentContainerLocation = this.getViewContainerLocation(viewContainer5);
      if (defaultContainerLocation !== null && currentContainerLocation !== defaultContainerLocation) {
        this.Z(viewContainer5, defaultContainerLocation);
      }
      this.$(viewContainer5.id);
    }
    this.y.clear();
    this.z.clear();
    this.eb();
  }
  isViewContainerRemovedPermanently(viewContainerId) {
    return this.R(viewContainerId) && !this.y.has(viewContainerId);
  }
  W(views, from, to) {
    const viewsToMove = views.filter(
      (view) => !this.z.has(view.id) || !this.viewContainers.includes(from) && this.z.get(view.id) === from.id
      // Move views which are moved from a removed container
    );
    if (viewsToMove.length) {
      this.Y(viewsToMove, from, to);
    }
  }
  X(views, from, to) {
    const containerToString = (container2) => {
      if (container2.id.startsWith($3Wb_1.b)) {
        return "custom";
      }
      if (!container2.extensionId) {
        return container2.id;
      }
      return "extension";
    };
    const oldLocation = this.getViewContainerLocation(from);
    const newLocation = this.getViewContainerLocation(to);
    const viewCount = views.length;
    const fromContainer = containerToString(from);
    const toContainer = containerToString(to);
    const fromLocation = oldLocation === 1 ? "panel" : "sidebar";
    const toLocation = newLocation === 1 ? "panel" : "sidebar";
    this.L.publicLog2("viewDescriptorService.moveViews", { viewCount, fromContainer, toContainer, fromLocation, toLocation });
  }
  Y(views, from, to, visibilityState = ViewVisibilityState.Expand) {
    this.tb(from, views);
    this.sb(to, views, visibilityState);
    const oldLocation = this.getViewContainerLocation(from);
    const newLocation = this.getViewContainerLocation(to);
    if (oldLocation !== newLocation) {
      this.f.fire({ views, from: oldLocation, to: newLocation });
    }
    this.c.fire({ views, from, to });
  }
  Z(viewContainer5, location3, requestedIndex) {
    const from = this.getViewContainerLocation(viewContainer5);
    const to = location3;
    if (from !== to) {
      const isGeneratedViewContainer = this.R(viewContainer5.id);
      const isDefaultViewContainerLocation = to === this.getDefaultViewContainerLocation(viewContainer5);
      if (isGeneratedViewContainer || !isDefaultViewContainerLocation) {
        this.y.set(viewContainer5.id, to);
      } else {
        this.y.delete(viewContainer5.id);
      }
      this.yb(viewContainer5).set(isGeneratedViewContainer || isDefaultViewContainerLocation);
      viewContainer5.requestedIndex = requestedIndex;
      this.g.fire({ viewContainer: viewContainer5, from, to });
      const views = this.jb(viewContainer5);
      this.f.fire({ views, from, to });
    }
  }
  $(viewContainerId) {
    if (!this.R(viewContainerId)) {
      return;
    }
    const viewContainer5 = this.getViewContainerById(viewContainerId);
    if (viewContainer5 && this.getViewContainerModel(viewContainer5)?.allViewDescriptors.length) {
      return;
    }
    if ([...this.z.values()].includes(viewContainerId)) {
      return;
    }
    if (viewContainer5) {
      this.w.deregisterViewContainer(viewContainer5);
    }
    this.y.delete(viewContainerId);
    this.C.delete(viewContainerId);
    this.I.remove(
      $1Wb(viewContainer5?.storageId || getViewContainerStorageId(viewContainerId)),
      0
      /* StorageScope.PROFILE */
    );
  }
  ab(location3, existingId) {
    const id2 = existingId || this.db(location3);
    const container2 = this.w.registerViewContainer({
      id: id2,
      ctorDescriptor: new $Nk($oqb, [id2, { mergeViewWithContainerWhenSingleView: true }]),
      title: { value: localize(13463, null), original: "User View Container" },
      // having a placeholder title - this should not be shown anywhere
      icon: location3 === 0 ? $8M : void 0,
      storageId: getViewContainerStorageId(id2),
      hideIfEmpty: true
    }, location3, { doNotRegisterOpenCommand: true });
    if (this.y.get(container2.id) !== location3) {
      this.y.set(container2.id, location3);
    }
    this.yb(container2).set(true);
    return container2;
  }
  bb() {
    if (JSON.stringify(this.gb) !== this.hb()) {
      this.cb();
    }
  }
  cb() {
    this.fb = void 0;
    const newViewContainerCustomizations = new Map(Object.entries(this.gb.viewContainerLocations));
    const newViewDescriptorCustomizations = new Map(Object.entries(this.gb.viewLocations));
    const viewContainersToMove = [];
    const viewsToMove = [];
    for (const [containerId, location3] of newViewContainerCustomizations.entries()) {
      const container2 = this.getViewContainerById(containerId);
      if (container2) {
        if (location3 !== this.getViewContainerLocation(container2)) {
          viewContainersToMove.push([container2, location3]);
        }
      } else if (this.R(containerId)) {
        this.ab(location3, containerId);
      }
    }
    for (const viewContainer5 of this.viewContainers) {
      if (!newViewContainerCustomizations.has(viewContainer5.id)) {
        const currentLocation = this.getViewContainerLocation(viewContainer5);
        const defaultLocation = this.getDefaultViewContainerLocation(viewContainer5);
        if (currentLocation !== defaultLocation) {
          viewContainersToMove.push([viewContainer5, defaultLocation]);
        }
      }
    }
    for (const [viewId, viewContainerId] of newViewDescriptorCustomizations.entries()) {
      const viewDescriptor3 = this.getViewDescriptorById(viewId);
      if (viewDescriptor3) {
        const prevViewContainer = this.getViewContainerByViewId(viewId);
        const newViewContainer = this.w.get(viewContainerId);
        if (prevViewContainer && newViewContainer && newViewContainer !== prevViewContainer) {
          viewsToMove.push({ views: [viewDescriptor3], from: prevViewContainer, to: newViewContainer });
        }
      }
    }
    for (const viewContainer5 of this.viewContainers) {
      const viewContainerModel = this.getViewContainerModel(viewContainer5);
      for (const viewDescriptor3 of viewContainerModel.allViewDescriptors) {
        if (!newViewDescriptorCustomizations.has(viewDescriptor3.id)) {
          const currentContainer = this.getViewContainerByViewId(viewDescriptor3.id);
          const defaultContainer = this.getDefaultContainerById(viewDescriptor3.id);
          if (currentContainer && defaultContainer && currentContainer !== defaultContainer) {
            viewsToMove.push({ views: [viewDescriptor3], from: currentContainer, to: defaultContainer });
          }
        }
      }
    }
    for (const [container2, location3] of viewContainersToMove) {
      this.Z(container2, location3);
    }
    for (const { views, from, to } of viewsToMove) {
      this.Y(views, from, to, ViewVisibilityState.Default);
    }
    this.y = newViewContainerCustomizations;
    this.z = newViewDescriptorCustomizations;
  }
  // Generated Container Id Format
  // {Common Prefix}.{Location}.{Uniqueness Id}
  // Old Format (deprecated)
  // {Common Prefix}.{Uniqueness Id}.{Source View Id}
  db(location3) {
    return `${$3Wb_1.b}.${$0M(location3)}.${$ps()}`;
  }
  eb() {
    const viewCustomizations = { viewContainerLocations: {}, viewLocations: {}, viewContainerBadgeEnablementStates: {} };
    for (const [containerId, location3] of this.y) {
      const container2 = this.getViewContainerById(containerId);
      if (container2 && !this.R(containerId) && location3 === this.getDefaultViewContainerLocation(container2)) {
        continue;
      }
      viewCustomizations.viewContainerLocations[containerId] = location3;
    }
    for (const [viewId, viewContainerId] of this.z) {
      const viewContainer5 = this.getViewContainerById(viewContainerId);
      if (viewContainer5) {
        const defaultContainer = this.getDefaultContainerById(viewId);
        if (defaultContainer?.id === viewContainer5.id) {
          continue;
        }
      }
      viewCustomizations.viewLocations[viewId] = viewContainerId;
    }
    for (const [viewContainerId, badgeEnablementState] of this.C) {
      if (badgeEnablementState === false) {
        viewCustomizations.viewContainerBadgeEnablementStates[viewContainerId] = badgeEnablementState;
      }
    }
    this.gb = viewCustomizations;
  }
  get gb() {
    if (!this.fb) {
      this.fb = JSON.parse(this.hb());
      this.fb.viewContainerLocations = this.fb.viewContainerLocations ?? {};
      this.fb.viewLocations = this.fb.viewLocations ?? {};
      this.fb.viewContainerBadgeEnablementStates = this.fb.viewContainerBadgeEnablementStates ?? {};
    }
    return this.fb;
  }
  set gb(viewCustomizations) {
    const value = JSON.stringify(viewCustomizations);
    if (JSON.stringify(this.gb) !== value) {
      this.fb = viewCustomizations;
      this.ib(value);
    }
  }
  hb() {
    return this.I.get($3Wb_1.a, 0, "{}");
  }
  ib(value) {
    this.I.store(
      $3Wb_1.a,
      value,
      0,
      0
      /* StorageTarget.USER */
    );
  }
  jb(viewContainer5) {
    const result = this.u.getViews(viewContainer5).filter((viewDescriptor3) => {
      const viewDescriptorViewContainerId = this.z.get(viewDescriptor3.id) ?? viewContainer5.id;
      return viewDescriptorViewContainerId === viewContainer5.id;
    });
    for (const [viewId, viewContainerId] of this.z.entries()) {
      if (viewContainerId !== viewContainer5.id) {
        continue;
      }
      if (this.u.getViewContainer(viewId) === viewContainer5) {
        continue;
      }
      const viewDescriptor3 = this.getViewDescriptorById(viewId);
      if (viewDescriptor3) {
        result.push(viewDescriptor3);
      }
    }
    return result;
  }
  kb(viewContainer5) {
    const defaultLocation = this.R(viewContainer5.id) ? true : this.getViewContainerLocation(viewContainer5) === this.getDefaultViewContainerLocation(viewContainer5);
    this.yb(viewContainer5).set(defaultLocation);
    this.lb(viewContainer5);
  }
  lb(viewContainer5) {
    let viewContainerModel = this.h.get(viewContainer5)?.viewContainerModel;
    if (!viewContainerModel) {
      const disposables = new $2c();
      viewContainerModel = disposables.add(this.G.createInstance($2Wb, viewContainer5));
      this.nb({ added: viewContainerModel.activeViewDescriptors, removed: [] });
      viewContainerModel.onDidChangeActiveViewDescriptors((changed) => this.nb(changed), this, disposables);
      this.ob({ added: [...viewContainerModel.visibleViewDescriptors], removed: [] });
      viewContainerModel.onDidAddVisibleViewDescriptors((added) => this.ob({ added: added.map(({ viewDescriptor: viewDescriptor3 }) => viewDescriptor3), removed: [] }), this, disposables);
      viewContainerModel.onDidRemoveVisibleViewDescriptors((removed) => this.ob({ added: [], removed: removed.map(({ viewDescriptor: viewDescriptor3 }) => viewDescriptor3) }), this, disposables);
      disposables.add($1c(() => this.j.deleteAndDispose(viewContainer5)));
      disposables.add(this.rb(viewContainer5));
      const value = { viewContainerModel, disposables, dispose: () => disposables.dispose() };
      this.h.set(viewContainer5, value);
      this.Q([{ views: this.u.getViews(viewContainer5), viewContainer: viewContainer5 }]);
      const viewsToRegister = this.jb(viewContainer5).filter((view) => this.getDefaultContainerById(view.id) !== viewContainer5);
      if (viewsToRegister.length) {
        this.sb(viewContainer5, viewsToRegister);
        this.H.bufferChangeEvents(() => {
          viewsToRegister.forEach((viewDescriptor3) => this.wb(viewDescriptor3).set(!!viewDescriptor3.canMoveView));
        });
      }
      if (this.m) {
        this.pb(viewContainer5, value);
      }
    }
    return viewContainerModel;
  }
  mb(viewContainer5) {
    this.h.deleteAndDispose(viewContainer5);
    this.j.deleteAndDispose(viewContainer5);
  }
  nb({ added, removed }) {
    this.H.bufferChangeEvents(() => {
      added.forEach((viewDescriptor3) => this.ub(viewDescriptor3).set(true));
      removed.forEach((viewDescriptor3) => this.ub(viewDescriptor3).set(false));
    });
  }
  ob({ added, removed }) {
    this.H.bufferChangeEvents(() => {
      added.forEach((viewDescriptor3) => this.vb(viewDescriptor3).set(true));
      removed.forEach((viewDescriptor3) => this.vb(viewDescriptor3).set(false));
    });
  }
  pb(viewContainer5, { viewContainerModel, disposables }) {
    this.j.deleteAndDispose(viewContainer5);
    this.j.set(viewContainer5, this.qb(viewContainerModel));
    disposables.add(Event2.any(viewContainerModel.onDidChangeActiveViewDescriptors, viewContainerModel.onDidAddVisibleViewDescriptors, viewContainerModel.onDidRemoveVisibleViewDescriptors, viewContainerModel.onDidMoveVisibleViewDescriptors)((e) => {
      this.j.deleteAndDispose(viewContainer5);
      this.j.set(viewContainer5, this.qb(viewContainerModel));
    }));
  }
  qb(viewContainerModel) {
    const disposables = new $2c();
    viewContainerModel.activeViewDescriptors.forEach((viewDescriptor3, index) => {
      if (!viewDescriptor3.remoteAuthority) {
        disposables.add($hJ(class extends $pqb {
          constructor() {
            super({
              id: `${viewDescriptor3.id}.toggleVisibility`,
              viewPaneContainerId: viewContainerModel.viewContainer.id,
              precondition: viewDescriptor3.canToggleVisibility && (!viewContainerModel.isVisible(viewDescriptor3.id) || viewContainerModel.visibleViewDescriptors.length > 1) ? $7m.true() : $7m.false(),
              toggled: $7m.has(`${viewDescriptor3.id}.visible`),
              title: viewDescriptor3.name,
              metadata: {
                description: localize2(13465, "Toggles the visibility of the {0} view if the view container it is located in is visible", viewDescriptor3.name.value)
              },
              menu: [{
                id: $nqb,
                when: $7m.equals("viewContainer", viewContainerModel.viewContainer.id),
                order: index
              }, {
                id: $bJ.ViewContainerTitleContext,
                when: $7m.and($7m.equals("viewContainer", viewContainerModel.viewContainer.id)),
                order: index,
                group: "1_toggleVisibility"
              }, {
                id: $bJ.ViewTitleContext,
                when: $7m.and($7m.or(...viewContainerModel.visibleViewDescriptors.map((v) => $7m.equals("view", v.id)))),
                order: index,
                group: "2_toggleVisibility"
              }]
            });
          }
          async runInViewPaneContainer(serviceAccessor, viewPaneContainer) {
            viewPaneContainer.toggleViewVisibility(viewDescriptor3.id);
          }
        }));
        disposables.add($hJ(class extends $pqb {
          constructor() {
            super({
              id: `${viewDescriptor3.id}.removeView`,
              viewPaneContainerId: viewContainerModel.viewContainer.id,
              title: localize(13464, null, viewDescriptor3.name.value),
              metadata: {
                description: localize2(13466, "Hides the {0} view if it is visible and the view container it is located in is visible", viewDescriptor3.name.value)
              },
              precondition: viewDescriptor3.canToggleVisibility && (!viewContainerModel.isVisible(viewDescriptor3.id) || viewContainerModel.visibleViewDescriptors.length > 1) ? $7m.true() : $7m.false(),
              menu: [{
                id: $bJ.ViewTitleContext,
                when: $7m.and($7m.equals("view", viewDescriptor3.id), $7m.has(`${viewDescriptor3.id}.visible`)),
                group: "1_hide",
                order: 1
              }]
            });
          }
          async runInViewPaneContainer(serviceAccessor, viewPaneContainer) {
            if (viewPaneContainer.getView(viewDescriptor3.id)?.isVisible()) {
              viewPaneContainer.toggleViewVisibility(viewDescriptor3.id);
            }
          }
        }));
      }
    });
    return disposables;
  }
  rb(viewContainer5) {
    const that = this;
    return $hJ(class ResetViewLocationAction extends $gJ {
      constructor() {
        super({
          id: `${viewContainer5.id}.resetViewContainerLocation`,
          title: localize2(13467, "Reset Location"),
          menu: [{
            id: $bJ.ViewContainerTitleContext,
            group: "1_viewActions",
            when: $7m.or($7m.and($7m.equals("viewContainer", viewContainer5.id), $7m.equals(`${viewContainer5.id}.defaultViewContainerLocation`, false)))
          }]
        });
      }
      run(accessor) {
        that.moveViewContainerToLocation(viewContainer5, that.getDefaultViewContainerLocation(viewContainer5), void 0, this.desc.id);
        accessor.get($uob).openViewContainer(viewContainer5.id, true);
      }
    });
  }
  sb(container2, views, visibilityState = ViewVisibilityState.Default) {
    this.H.bufferChangeEvents(() => {
      views.forEach((view) => {
        const isDefaultContainer = this.getDefaultContainerById(view.id) === container2;
        this.xb(view).set(isDefaultContainer);
        if (isDefaultContainer) {
          this.z.delete(view.id);
        } else {
          this.z.set(view.id, container2.id);
        }
      });
    });
    this.getViewContainerModel(container2).add(views.map((view) => {
      return {
        viewDescriptor: view,
        collapsed: visibilityState === ViewVisibilityState.Default ? void 0 : false,
        visible: visibilityState === ViewVisibilityState.Default ? void 0 : true
      };
    }));
  }
  tb(container2, views) {
    this.H.bufferChangeEvents(() => {
      views.forEach((view) => {
        if (this.z.get(view.id) === container2.id) {
          this.z.delete(view.id);
        }
        this.xb(view).set(false);
      });
    });
    this.getViewContainerModel(container2).remove(views);
  }
  ub(viewDescriptor3) {
    const activeContextKeyId = `${viewDescriptor3.id}.active`;
    let contextKey = this.n.get(activeContextKeyId);
    if (!contextKey) {
      contextKey = new $nn(activeContextKeyId, false).bindTo(this.H);
      this.n.set(activeContextKeyId, contextKey);
    }
    return contextKey;
  }
  vb(viewDescriptor3) {
    const activeContextKeyId = `${viewDescriptor3.id}.visible`;
    let contextKey = this.n.get(activeContextKeyId);
    if (!contextKey) {
      contextKey = new $nn(activeContextKeyId, false).bindTo(this.H);
      this.n.set(activeContextKeyId, contextKey);
    }
    return contextKey;
  }
  wb(viewDescriptor3) {
    const movableViewContextKeyId = `${viewDescriptor3.id}.canMove`;
    let contextKey = this.r.get(movableViewContextKeyId);
    if (!contextKey) {
      contextKey = new $nn(movableViewContextKeyId, false).bindTo(this.H);
      this.r.set(movableViewContextKeyId, contextKey);
    }
    return contextKey;
  }
  xb(viewDescriptor3) {
    const defaultViewLocationContextKeyId = `${viewDescriptor3.id}.defaultViewLocation`;
    let contextKey = this.s.get(defaultViewLocationContextKeyId);
    if (!contextKey) {
      contextKey = new $nn(defaultViewLocationContextKeyId, false).bindTo(this.H);
      this.s.set(defaultViewLocationContextKeyId, contextKey);
    }
    return contextKey;
  }
  yb(viewContainer5) {
    const defaultViewContainerLocationContextKeyId = `${viewContainer5.id}.defaultViewContainerLocation`;
    let contextKey = this.t.get(defaultViewContainerLocationContextKeyId);
    if (!contextKey) {
      contextKey = new $nn(defaultViewContainerLocationContextKeyId, false).bindTo(this.H);
      this.t.set(defaultViewContainerLocationContextKeyId, contextKey);
    }
    return contextKey;
  }
};
$3Wb = $3Wb_1 = __decorate([
  __param(0, $Pk),
  __param(1, $on),
  __param(2, $jv),
  __param(3, $wN),
  __param(4, $zv),
  __param(5, $xn)
], $3Wb);
$SC(
  $$M,
  $3Wb,
  1
  /* InstantiationType.Delayed */
);

// out-build/vs/workbench/browser/parts/views/viewsViewlet.js
var $dpb = class $dpb2 extends $oqb {
  constructor(viewletId, onDidChangeFilterValue, configurationService, layoutService, telemetryService, storageService, instantiationService, themeService, contextMenuService, extensionService, contextService, viewDescriptorService) {
    super(viewletId, { mergeViewWithContainerWhenSingleView: false }, instantiationService, configurationService, layoutService, contextMenuService, telemetryService, extensionService, themeService, storageService, contextService, viewDescriptorService);
    this.c = /* @__PURE__ */ new Map();
    this.r = /* @__PURE__ */ new Map();
    this.B(onDidChangeFilterValue((newFilterValue) => {
      this.t = newFilterValue;
      this.Eb(newFilterValue);
    }));
    this.B(this.P.onDidChangeActiveViewDescriptors(() => {
      this.Ab(this.P.activeViewDescriptors);
    }));
  }
  Ab(viewDescriptors) {
    viewDescriptors.forEach((descriptor) => {
      const filterOnValue = this.Cb(descriptor);
      if (!filterOnValue) {
        return;
      }
      if (!this.r.has(filterOnValue)) {
        this.r.set(filterOnValue, /* @__PURE__ */ new Map());
      }
      this.r.get(filterOnValue).set(descriptor.id, descriptor);
      if (this.t && !this.t.includes(filterOnValue) && this.panes.find((pane) => pane.id === descriptor.id)) {
        this.P.setVisible(descriptor.id, false);
      }
    });
  }
  Bb(constantViewDescriptors) {
    constantViewDescriptors.forEach((viewDescriptor3) => this.c.set(viewDescriptor3.id, viewDescriptor3));
  }
  Eb(newFilterValue) {
    if (this.r.size === 0) {
      this.Ab(this.P.activeViewDescriptors);
    }
    this.Gb(newFilterValue).forEach((item) => this.P.setVisible(item.id, false));
    this.Fb(newFilterValue).forEach((item) => this.P.setVisible(item.id, true));
  }
  Fb(target) {
    const views = [];
    for (let i2 = 0; i2 < target.length; i2++) {
      if (this.r.has(target[i2])) {
        views.push(...Array.from(this.r.get(target[i2]).values()));
      }
    }
    return views;
  }
  Gb(target) {
    const iterable = this.r.keys();
    let key2 = iterable.next();
    let views = [];
    while (!key2.done) {
      let isForTarget = false;
      target.forEach((value) => {
        if (key2.value === value) {
          isForTarget = true;
        }
      });
      if (!isForTarget) {
        views = views.concat(this.Fb([key2.value]));
      }
      key2 = iterable.next();
    }
    return views;
  }
  tb(added) {
    const panes = super.tb(added);
    for (let i2 = 0; i2 < added.length; i2++) {
      if (this.c.has(added[i2].viewDescriptor.id)) {
        panes[i2].setExpanded(false);
      }
    }
    if (this.r.size === 0) {
      this.Ab(this.P.activeViewDescriptors);
    }
    return panes;
  }
  openView(id2, focus) {
    const result = super.openView(id2, focus);
    if (result) {
      const descriptorMap = Array.from(this.r.entries()).find((entry) => entry[1].has(id2));
      if (descriptorMap && !this.t?.includes(descriptorMap[0])) {
        this.Db(descriptorMap[1].get(id2));
      }
    }
    return result;
  }
};
$dpb = __decorate([
  __param(2, $kl),
  __param(3, $Vlb),
  __param(4, $zv),
  __param(5, $jv),
  __param(6, $Pk),
  __param(7, $gs),
  __param(8, $50),
  __param(9, $wN),
  __param(10, $Zk),
  __param(11, $$M)
], $dpb);

// out-build/vs/workbench/services/views/browser/viewsService.js
var $4Wb = class $4Wb2 extends $3c {
  constructor(r2, s, t, u, w) {
    super();
    this.r = r2;
    this.s = s;
    this.t = t;
    this.u = u;
    this.w = w;
    this.c = this.B(new $ze());
    this.onDidChangeViewVisibility = this.c.event;
    this.f = this.B(new $ze());
    this.onDidChangeViewContainerVisibility = this.f.event;
    this.g = this.B(new $ze());
    this.onDidChangeFocusedView = this.g.event;
    this.h = this.B(new $_c());
    this.a = /* @__PURE__ */ new Map();
    this.j = /* @__PURE__ */ new Map();
    this.m = /* @__PURE__ */ new Map();
    this.b = /* @__PURE__ */ new Map();
    this.B($1c(() => {
      this.a.forEach((disposable) => disposable.dispose());
      this.a.clear();
    }));
    this.r.viewContainers.forEach((viewContainer5) => this.G(viewContainer5, this.r.getViewContainerLocation(viewContainer5)));
    this.B(this.r.onDidChangeViewContainers(({ added, removed }) => this.F(added, removed)));
    this.B(this.r.onDidChangeContainerLocation(({ viewContainer: viewContainer5, from, to }) => this.I(viewContainer5, from, to)));
    this.B(this.s.onDidPaneCompositeOpen((e) => this.f.fire({ id: e.composite.getId(), visible: true, location: e.viewContainerLocation })));
    this.B(this.s.onDidPaneCompositeClose((e) => this.f.fire({ id: e.composite.getId(), visible: false, location: e.viewContainerLocation })));
    this.n = $jqb.bindTo(t);
  }
  y(added) {
    for (const view of added) {
      this.z(view, view.isBodyVisible());
    }
  }
  z(view, visible) {
    this.D(view).set(visible);
    this.c.fire({ id: view.id, visible });
  }
  C(removed) {
    for (const view of removed) {
      this.z(view, false);
    }
  }
  D(view) {
    const visibleContextKeyId = $kqb(view.id);
    let contextKey = this.m.get(visibleContextKeyId);
    if (!contextKey) {
      contextKey = new $nn(visibleContextKeyId, false).bindTo(this.t);
      this.m.set(visibleContextKeyId, contextKey);
    }
    return contextKey;
  }
  F(added, removed) {
    for (const { container: container2, location: location3 } of removed) {
      this.H(container2, location3);
    }
    for (const { container: container2, location: location3 } of added) {
      this.G(container2, location3);
    }
  }
  G(viewContainer5, viewContainerLocation) {
    this.X(viewContainer5, viewContainerLocation);
    const disposables = new $2c();
    const viewContainerModel = this.r.getViewContainerModel(viewContainer5);
    this.J(viewContainerModel.allViewDescriptors, viewContainer5);
    disposables.add(viewContainerModel.onDidChangeAllViewDescriptors(({ added, removed }) => {
      this.J(added, viewContainer5);
      this.L(removed);
    }));
    this.M(viewContainer5);
    disposables.add(viewContainerModel.onDidChangeActiveViewDescriptors(() => this.M(viewContainer5)));
    disposables.add(this.R(viewContainer5));
    this.h.set(viewContainer5.id, disposables);
  }
  H(viewContainer5, viewContainerLocation) {
    this.Y(viewContainer5, viewContainerLocation);
    this.h.deleteAndDispose(viewContainer5.id);
  }
  I(viewContainer5, from, to) {
    this.Y(viewContainer5, from);
    this.X(viewContainer5, to);
    if (this.u.isVisible($5Wb(to)) && this.r.getViewContainersByLocation(to).filter((vc) => this.isViewContainerActive(vc.id)).length === 1) {
      this.openViewContainer(viewContainer5.id);
    }
  }
  J(views, container2) {
    const location3 = this.r.getViewContainerLocation(container2);
    if (location3 === null) {
      return;
    }
    for (const viewDescriptor3 of views) {
      const disposables = new $2c();
      disposables.add(this.S(viewDescriptor3));
      disposables.add(this.U(viewDescriptor3, container2.title));
      disposables.add(this.W(viewDescriptor3));
      this.a.set(viewDescriptor3, disposables);
    }
  }
  L(views) {
    for (const view of views) {
      const disposable = this.a.get(view);
      if (disposable) {
        disposable.dispose();
        this.a.delete(view);
      }
    }
  }
  M(viewContainer5) {
    let contextKey = this.j.get(viewContainer5.id);
    if (!contextKey) {
      contextKey = this.t.createKey(getEnabledViewContainerContextKey(viewContainer5.id), false);
      this.j.set(viewContainer5.id, contextKey);
    }
    contextKey.set(!(viewContainer5.hideIfEmpty && this.r.getViewContainerModel(viewContainer5).activeViewDescriptors.length === 0));
  }
  async N(compositeId, location3, focus) {
    return this.s.openPaneComposite(compositeId, location3, focus);
  }
  O(compositeId, location3) {
    return this.s.getPaneComposite(compositeId, location3);
  }
  // One view container can be visible at a time in a location
  isViewContainerVisible(id2) {
    const viewContainer5 = this.r.getViewContainerById(id2);
    if (!viewContainer5) {
      return false;
    }
    const viewContainerLocation = this.r.getViewContainerLocation(viewContainer5);
    if (viewContainerLocation === null) {
      return false;
    }
    return this.s.getActivePaneComposite(viewContainerLocation)?.getId() === id2;
  }
  // Multiple view containers can be active/inactive at a time in a location
  isViewContainerActive(id2) {
    const viewContainer5 = this.r.getViewContainerById(id2);
    if (!viewContainer5) {
      return false;
    }
    if (!viewContainer5.hideIfEmpty) {
      return true;
    }
    return this.r.getViewContainerModel(viewContainer5).activeViewDescriptors.length > 0;
  }
  getVisibleViewContainer(location3) {
    const viewContainerId = this.s.getActivePaneComposite(location3)?.getId();
    return viewContainerId ? this.r.getViewContainerById(viewContainerId) : null;
  }
  getActiveViewPaneContainerWithId(viewContainerId) {
    const viewContainer5 = this.r.getViewContainerById(viewContainerId);
    return viewContainer5 ? this.P(viewContainer5) : null;
  }
  async openViewContainer(id2, focus) {
    const viewContainer5 = this.r.getViewContainerById(id2);
    if (viewContainer5) {
      const viewContainerLocation = this.r.getViewContainerLocation(viewContainer5);
      if (viewContainerLocation !== null) {
        const paneComposite = await this.s.openPaneComposite(id2, viewContainerLocation, focus);
        return paneComposite || null;
      }
    }
    return null;
  }
  async closeViewContainer(id2) {
    const viewContainer5 = this.r.getViewContainerById(id2);
    if (viewContainer5) {
      const viewContainerLocation = this.r.getViewContainerLocation(viewContainer5);
      const isActive2 = viewContainerLocation !== null && this.s.getActivePaneComposite(viewContainerLocation);
      if (viewContainerLocation !== null) {
        return isActive2 ? this.u.setPartHidden(true, $5Wb(viewContainerLocation)) : void 0;
      }
    }
  }
  isViewVisible(id2) {
    const activeView = this.getActiveViewWithId(id2);
    return activeView?.isBodyVisible() || false;
  }
  getActiveViewWithId(id2) {
    const viewContainer5 = this.r.getViewContainerByViewId(id2);
    if (viewContainer5) {
      const activeViewPaneContainer = this.P(viewContainer5);
      if (activeViewPaneContainer) {
        return activeViewPaneContainer.getView(id2);
      }
    }
    return null;
  }
  getViewWithId(id2) {
    const viewContainer5 = this.r.getViewContainerByViewId(id2);
    if (viewContainer5) {
      const viewPaneContainer = this.b.get(viewContainer5.id);
      if (viewPaneContainer) {
        return viewPaneContainer.getView(id2);
      }
    }
    return null;
  }
  getFocusedView() {
    const viewId = this.t.getContextKeyValue($jqb.key) ?? "";
    return this.r.getViewDescriptorById(viewId.toString());
  }
  getFocusedViewName() {
    const textEditorFocused = this.w.activeTextEditorControl?.hasTextFocus() ? localize(13468, null) : void 0;
    return this.getFocusedView()?.name?.value ?? textEditorFocused ?? "";
  }
  async openView(id2, focus) {
    const viewContainer5 = this.r.getViewContainerByViewId(id2);
    if (!viewContainer5) {
      return null;
    }
    if (!this.r.getViewContainerModel(viewContainer5).activeViewDescriptors.some((viewDescriptor3) => viewDescriptor3.id === id2)) {
      return null;
    }
    const location3 = this.r.getViewContainerLocation(viewContainer5);
    const compositeDescriptor = this.O(viewContainer5.id, location3);
    if (compositeDescriptor) {
      const paneComposite = await this.N(compositeDescriptor.id, location3);
      if (paneComposite && paneComposite.openView) {
        return paneComposite.openView(id2, focus) || null;
      } else if (focus) {
        paneComposite?.focus();
      }
    }
    return null;
  }
  closeView(id2) {
    const viewContainer5 = this.r.getViewContainerByViewId(id2);
    if (viewContainer5) {
      const activeViewPaneContainer = this.P(viewContainer5);
      if (activeViewPaneContainer) {
        const view = activeViewPaneContainer.getView(id2);
        if (view) {
          if (activeViewPaneContainer.views.length === 1) {
            const location3 = this.r.getViewContainerLocation(viewContainer5);
            if (location3 === 0) {
              this.u.setPartHidden(
                true,
                "workbench.parts.sidebar"
                /* Parts.SIDEBAR_PART */
              );
            } else if (location3 === 1 || location3 === 2) {
              this.s.hideActivePaneComposite(location3);
            }
            if (this.n.get() === id2) {
              this.n.reset();
            }
          } else {
            view.setExpanded(false);
          }
        }
      }
    }
  }
  P(viewContainer5) {
    const location3 = this.r.getViewContainerLocation(viewContainer5);
    if (location3 === null) {
      return null;
    }
    const activePaneComposite = this.s.getActivePaneComposite(location3);
    if (activePaneComposite?.getId() === viewContainer5.id) {
      return activePaneComposite.getViewPaneContainer() || null;
    }
    return null;
  }
  getViewProgressIndicator(viewId) {
    const viewContainer5 = this.r.getViewContainerByViewId(viewId);
    if (!viewContainer5) {
      return void 0;
    }
    const viewPaneContainer = this.b.get(viewContainer5.id);
    if (!viewPaneContainer) {
      return void 0;
    }
    const view = viewPaneContainer.getView(viewId);
    if (!view) {
      return void 0;
    }
    if (viewPaneContainer.isViewMergedWithContainer()) {
      return this.Q(viewContainer5);
    }
    return view.getProgressIndicator();
  }
  Q(viewContainer5) {
    const viewContainerLocation = this.r.getViewContainerLocation(viewContainer5);
    if (viewContainerLocation === null) {
      return void 0;
    }
    return this.s.getProgressIndicator(viewContainer5.id, viewContainerLocation);
  }
  R(viewContainer5) {
    const disposables = new $2c();
    if (viewContainer5.openCommandActionDescriptor) {
      const { id: id2, mnemonicTitle, keybindings, order } = viewContainer5.openCommandActionDescriptor ?? { id: viewContainer5.id };
      const title = viewContainer5.openCommandActionDescriptor.title ?? viewContainer5.title;
      const that = this;
      disposables.add($hJ(class OpenViewContainerAction extends $gJ {
        constructor() {
          super({
            id: id2,
            get title() {
              const viewContainerLocation = that.r.getViewContainerLocation(viewContainer5);
              const localizedTitle = typeof title === "string" ? title : title.value;
              const originalTitle = typeof title === "string" ? title : title.original;
              if (viewContainerLocation === 0) {
                return { value: localize(13469, null, localizedTitle), original: `Show ${originalTitle}` };
              } else {
                return { value: localize(13470, null, localizedTitle), original: `Toggle ${originalTitle}` };
              }
            },
            category: $qn.View,
            precondition: $7m.has(getEnabledViewContainerContextKey(viewContainer5.id)),
            keybinding: keybindings ? {
              ...keybindings,
              weight: 200
              /* KeybindingWeight.WorkbenchContrib */
            } : void 0,
            f1: true
          });
        }
        async run(serviceAccessor) {
          const editorGroupService = serviceAccessor.get($iJ);
          const viewDescriptorService = serviceAccessor.get($$M);
          const layoutService = serviceAccessor.get($Vlb);
          const viewsService = serviceAccessor.get($uob);
          const viewContainerLocation = viewDescriptorService.getViewContainerLocation(viewContainer5);
          switch (viewContainerLocation) {
            case 2:
            case 0: {
              const part = viewContainerLocation === 0 ? "workbench.parts.sidebar" : "workbench.parts.auxiliarybar";
              if (!viewsService.isViewContainerVisible(viewContainer5.id) || !layoutService.hasFocus(part)) {
                await viewsService.openViewContainer(viewContainer5.id, true);
              } else {
                editorGroupService.activeGroup.focus();
              }
              break;
            }
            case 1:
              if (!viewsService.isViewContainerVisible(viewContainer5.id) || !layoutService.hasFocus(
                "workbench.parts.panel"
                /* Parts.PANEL_PART */
              )) {
                await viewsService.openViewContainer(viewContainer5.id, true);
              } else {
                viewsService.closeViewContainer(viewContainer5.id);
              }
              break;
          }
        }
      }));
      if (mnemonicTitle) {
        const defaultLocation = this.r.getDefaultViewContainerLocation(viewContainer5);
        disposables.add($dJ.appendMenuItem($bJ.MenubarViewMenu, {
          command: {
            id: id2,
            title: mnemonicTitle
          },
          group: defaultLocation === 0 ? "3_sidebar" : defaultLocation === 2 ? "4_auxbar" : "5_panel",
          when: $7m.has(getEnabledViewContainerContextKey(viewContainer5.id)),
          order: order ?? Number.MAX_VALUE
        }));
      }
    }
    return disposables;
  }
  S(viewDescriptor3) {
    const disposables = new $2c();
    if (viewDescriptor3.openCommandActionDescriptor) {
      const title = viewDescriptor3.openCommandActionDescriptor.title ?? viewDescriptor3.name;
      const commandId = viewDescriptor3.openCommandActionDescriptor.id;
      const that = this;
      disposables.add($hJ(class OpenViewAction extends $gJ {
        constructor() {
          super({
            id: commandId,
            get title() {
              const viewContainerLocation = that.r.getViewLocationById(viewDescriptor3.id);
              const localizedTitle = typeof title === "string" ? title : title.value;
              const originalTitle = typeof title === "string" ? title : title.original;
              if (viewContainerLocation === 0) {
                return { value: localize(13471, null, localizedTitle), original: `Show ${originalTitle}` };
              } else {
                return { value: localize(13472, null, localizedTitle), original: `Toggle ${originalTitle}` };
              }
            },
            category: $qn.View,
            precondition: $7m.has(`${viewDescriptor3.id}.active`),
            keybinding: viewDescriptor3.openCommandActionDescriptor.keybindings ? {
              ...viewDescriptor3.openCommandActionDescriptor.keybindings,
              weight: 200
              /* KeybindingWeight.WorkbenchContrib */
            } : void 0,
            f1: true
          });
        }
        async run(serviceAccessor) {
          const editorGroupService = serviceAccessor.get($iJ);
          const viewDescriptorService = serviceAccessor.get($$M);
          const layoutService = serviceAccessor.get($Vlb);
          const viewsService = serviceAccessor.get($uob);
          const contextKeyService = serviceAccessor.get($on);
          const focusedViewId = $jqb.getValue(contextKeyService);
          if (focusedViewId === viewDescriptor3.id) {
            const viewLocation = viewDescriptorService.getViewLocationById(viewDescriptor3.id);
            if (viewDescriptorService.getViewLocationById(viewDescriptor3.id) === 0) {
              editorGroupService.activeGroup.focus();
            } else if (viewLocation !== null) {
              layoutService.setPartHidden(true, $5Wb(viewLocation));
            }
          } else {
            viewsService.openView(viewDescriptor3.id, true);
          }
        }
      }));
      if (viewDescriptor3.openCommandActionDescriptor.mnemonicTitle) {
        const defaultViewContainer = this.r.getDefaultContainerById(viewDescriptor3.id);
        if (defaultViewContainer) {
          const defaultLocation = this.r.getDefaultViewContainerLocation(defaultViewContainer);
          disposables.add($dJ.appendMenuItem($bJ.MenubarViewMenu, {
            command: {
              id: commandId,
              title: viewDescriptor3.openCommandActionDescriptor.mnemonicTitle
            },
            group: defaultLocation === 0 ? "3_sidebar" : defaultLocation === 2 ? "4_auxbar" : "5_panel",
            when: $7m.has(`${viewDescriptor3.id}.active`),
            order: viewDescriptor3.openCommandActionDescriptor.order ?? Number.MAX_VALUE
          }));
        }
      }
    }
    return disposables;
  }
  U(viewDescriptor3, category8) {
    return $hJ(class FocusViewAction extends $gJ {
      constructor() {
        const title = localize2(13473, "Focus on {0} View", viewDescriptor3.name.value);
        super({
          id: viewDescriptor3.focusCommand ? viewDescriptor3.focusCommand.id : `${viewDescriptor3.id}.focus`,
          title,
          category: category8,
          menu: [{
            id: $bJ.CommandPalette,
            when: viewDescriptor3.when
          }],
          keybinding: {
            when: $7m.has(`${viewDescriptor3.id}.active`),
            weight: 200,
            primary: viewDescriptor3.focusCommand?.keybindings?.primary,
            secondary: viewDescriptor3.focusCommand?.keybindings?.secondary,
            linux: viewDescriptor3.focusCommand?.keybindings?.linux,
            mac: viewDescriptor3.focusCommand?.keybindings?.mac,
            win: viewDescriptor3.focusCommand?.keybindings?.win
          },
          metadata: {
            description: title.value,
            args: [
              {
                name: "focusOptions",
                description: "Focus Options",
                schema: {
                  type: "object",
                  properties: {
                    "preserveFocus": {
                      type: "boolean",
                      default: false
                    }
                  }
                }
              }
            ]
          }
        });
      }
      run(accessor, options3) {
        accessor.get($uob).openView(viewDescriptor3.id, !options3?.preserveFocus);
      }
    });
  }
  W(viewDescriptor3) {
    return $hJ(class ResetViewLocationAction extends $gJ {
      constructor() {
        super({
          id: `${viewDescriptor3.id}.resetViewLocation`,
          title: localize2(13474, "Reset Location"),
          menu: [{
            id: $bJ.ViewTitleContext,
            when: $7m.or($7m.and($7m.equals("view", viewDescriptor3.id), $7m.equals(`${viewDescriptor3.id}.defaultViewLocation`, false))),
            group: "1_hide",
            order: 2
          }]
        });
      }
      run(accessor) {
        const viewDescriptorService = accessor.get($$M);
        const defaultContainer = viewDescriptorService.getDefaultContainerById(viewDescriptor3.id);
        const containerModel = viewDescriptorService.getViewContainerModel(defaultContainer);
        if (defaultContainer.hideIfEmpty && containerModel.visibleViewDescriptors.length === 0) {
          const defaultLocation = viewDescriptorService.getDefaultViewContainerLocation(defaultContainer);
          viewDescriptorService.moveViewContainerToLocation(defaultContainer, defaultLocation, void 0, this.desc.id);
        }
        viewDescriptorService.moveViewsToContainer([viewDescriptor3], defaultContainer, void 0, this.desc.id);
        accessor.get($uob).openView(viewDescriptor3.id, true);
      }
    });
  }
  X(viewContainer5, viewContainerLocation) {
    const that = this;
    let PaneContainer = class PaneContainer extends $qqb {
      constructor(telemetryService, contextService, storageService, instantiationService, themeService, contextMenuService, extensionService) {
        super(viewContainer5.id, telemetryService, storageService, instantiationService, themeService, contextMenuService, extensionService, contextService);
      }
      m(element) {
        const viewPaneContainerDisposables = this.B(new $2c());
        const viewPaneContainer = that.Z(element, viewContainer5, viewContainerLocation, viewPaneContainerDisposables, this.c);
        if (!(viewPaneContainer instanceof $dpb)) {
          viewPaneContainerDisposables.add(Event2.any(viewPaneContainer.onDidAddViews, viewPaneContainer.onDidRemoveViews, viewPaneContainer.onTitleAreaUpdate)(() => {
            this.R();
          }));
        }
        return viewPaneContainer;
      }
    };
    PaneContainer = __decorate([
      __param(0, $zv),
      __param(1, $Zk),
      __param(2, $jv),
      __param(3, $Pk),
      __param(4, $gs),
      __param(5, $50),
      __param(6, $wN)
    ], PaneContainer);
    $Wn.as(getPaneCompositeExtension(viewContainerLocation)).registerPaneComposite($rqb.create(PaneContainer, viewContainer5.id, typeof viewContainer5.title === "string" ? viewContainer5.title : viewContainer5.title.value, $zg(viewContainer5.icon) ? viewContainer5.icon : void 0, viewContainer5.order, viewContainer5.requestedIndex, viewContainer5.icon instanceof URI ? viewContainer5.icon : void 0));
  }
  Y(viewContainer5, viewContainerLocation) {
    $Wn.as(getPaneCompositeExtension(viewContainerLocation)).deregisterPaneComposite(viewContainer5.id);
  }
  Z(element, viewContainer5, viewContainerLocation, disposables, instantiationService) {
    const viewPaneContainer = instantiationService.createInstance(viewContainer5.ctorDescriptor.ctor, ...viewContainer5.ctorDescriptor.staticArguments || []);
    this.b.set(viewPaneContainer.getId(), viewPaneContainer);
    disposables.add($1c(() => this.b.delete(viewPaneContainer.getId())));
    disposables.add(viewPaneContainer.onDidAddViews((views) => this.y(views)));
    disposables.add(viewPaneContainer.onDidChangeViewVisibility((view) => this.z(view, view.isBodyVisible())));
    disposables.add(viewPaneContainer.onDidRemoveViews((views) => this.C(views)));
    disposables.add(viewPaneContainer.onDidFocusView((view) => {
      if (this.n.get() !== view.id) {
        this.n.set(view.id);
        this.g.fire();
      }
    }));
    disposables.add(viewPaneContainer.onDidBlurView((view) => {
      if (this.n.get() === view.id) {
        this.n.reset();
        this.g.fire();
      }
    }));
    return viewPaneContainer;
  }
};
$4Wb = __decorate([
  __param(0, $$M),
  __param(1, $uqb),
  __param(2, $on),
  __param(3, $Vlb),
  __param(4, $mJ)
], $4Wb);
function getEnabledViewContainerContextKey(viewContainerId) {
  return `viewContainer.${viewContainerId}.enabled`;
}
function getPaneCompositeExtension(viewContainerLocation) {
  switch (viewContainerLocation) {
    case 2:
      return $sqb.Auxiliary;
    case 1:
      return $sqb.Panels;
    case 0:
    default:
      return $sqb.Viewlets;
  }
}
function $5Wb(viewContainerLocation) {
  switch (viewContainerLocation) {
    case 2:
      return "workbench.parts.auxiliarybar";
    case 1:
      return "workbench.parts.panel";
    case 0:
    default:
      return "workbench.parts.sidebar";
  }
}
$SC(
  $uob,
  $4Wb,
  0
  /* InstantiationType.Eager */
);

// out-build/vs/platform/quickinput/browser/quickAccess.js
var $lXb = class $lXb2 extends $3c {
  constructor(g, h3) {
    super();
    this.g = g;
    this.h = h3;
    this.a = $Wn.as($CM.Quickaccess);
    this.b = /* @__PURE__ */ new Map();
    this.c = /* @__PURE__ */ new Map();
    this.f = void 0;
  }
  pick(value = "", options3) {
    return this.j(value, true, options3);
  }
  show(value = "", options3) {
    this.j(value, false, options3);
  }
  j(value, pick, options3) {
    const [provider, descriptor] = this.r(value, options3?.enabledProviderPrefixes);
    const visibleQuickAccess = this.f;
    const visibleDescriptor = visibleQuickAccess?.descriptor;
    if (visibleQuickAccess && descriptor && visibleDescriptor === descriptor) {
      if (value !== descriptor.prefix && !options3?.preserveValue) {
        visibleQuickAccess.picker.value = value;
      }
      this.m(visibleQuickAccess.picker, descriptor, options3);
      return;
    }
    if (descriptor && !options3?.preserveValue) {
      let newValue = void 0;
      if (visibleQuickAccess && visibleDescriptor && visibleDescriptor !== descriptor) {
        const newValueCandidateWithoutPrefix = visibleQuickAccess.value.substr(visibleDescriptor.prefix.length);
        if (newValueCandidateWithoutPrefix) {
          newValue = `${descriptor.prefix}${newValueCandidateWithoutPrefix}`;
        }
      }
      if (!newValue) {
        const defaultFilterValue = provider?.defaultFilterValue;
        if (defaultFilterValue === DefaultQuickAccessFilterValue.LAST) {
          newValue = this.c.get(descriptor);
        } else if (typeof defaultFilterValue === "string") {
          newValue = `${descriptor.prefix}${defaultFilterValue}`;
        }
      }
      if (typeof newValue === "string") {
        value = newValue;
      }
    }
    const visibleSelection = visibleQuickAccess?.picker?.valueSelection;
    const visibleValue = visibleQuickAccess?.picker?.value;
    const disposables = new $2c();
    const picker = disposables.add(this.g.createQuickPick({ useSeparators: true }));
    picker.value = value;
    this.m(picker, descriptor, options3);
    picker.placeholder = options3?.placeholder ?? descriptor?.placeholder;
    picker.quickNavigate = options3?.quickNavigateConfiguration;
    picker.hideInput = !!picker.quickNavigate && !visibleQuickAccess;
    if (typeof options3?.itemActivation === "number" || options3?.quickNavigateConfiguration) {
      picker.itemActivation = options3?.itemActivation ?? ItemActivation.SECOND;
    }
    picker.contextKey = descriptor?.contextKey;
    picker.filterValue = (value2) => value2.substring(descriptor ? descriptor.prefix.length : 0);
    let pickPromise = void 0;
    if (pick) {
      pickPromise = new $gi();
      disposables.add(Event2.once(picker.onWillAccept)((e) => {
        e.veto();
        picker.hide();
      }));
    }
    disposables.add(this.n(picker, provider, descriptor, value, options3));
    const cts = disposables.add(new $ad());
    if (provider) {
      disposables.add(provider.provide(picker, cts.token, options3?.providerOptions));
    }
    Event2.once(picker.onDidHide)(() => {
      if (picker.selectedItems.length === 0) {
        cts.cancel();
      }
      disposables.dispose();
      pickPromise?.complete(picker.selectedItems.slice(0));
    });
    picker.show();
    if (visibleSelection && visibleValue === value) {
      picker.valueSelection = visibleSelection;
    }
    if (pick) {
      return pickPromise?.p;
    }
  }
  m(picker, descriptor, options3) {
    let valueSelection;
    if (options3?.preserveValue) {
      valueSelection = [picker.value.length, picker.value.length];
    } else {
      valueSelection = [descriptor?.prefix.length ?? 0, picker.value.length];
    }
    picker.valueSelection = valueSelection;
  }
  n(picker, provider, descriptor, value, options3) {
    const disposables = new $2c();
    const visibleQuickAccess = this.f = { picker, descriptor, value };
    disposables.add($1c(() => {
      if (visibleQuickAccess === this.f) {
        this.f = void 0;
      }
    }));
    disposables.add(picker.onDidChangeValue((value2) => {
      const [providerForValue] = this.r(value2, options3?.enabledProviderPrefixes);
      if (providerForValue !== provider) {
        this.show(value2, {
          enabledProviderPrefixes: options3?.enabledProviderPrefixes,
          // do not rewrite value from user typing!
          preserveValue: true,
          // persist the value of the providerOptions from the original showing
          providerOptions: options3?.providerOptions
        });
      } else {
        visibleQuickAccess.value = value2;
      }
    }));
    if (descriptor) {
      disposables.add(picker.onDidAccept(() => {
        this.c.set(descriptor, picker.value);
      }));
    }
    return disposables;
  }
  r(value, enabledProviderPrefixes) {
    const providerDescriptor = this.a.getQuickAccessProvider(value);
    if (!providerDescriptor || enabledProviderPrefixes && !enabledProviderPrefixes?.includes(providerDescriptor.prefix)) {
      return [void 0, void 0];
    }
    let provider = this.b.get(providerDescriptor);
    if (!provider) {
      provider = this.h.createInstance(providerDescriptor.ctor);
      this.b.set(providerDescriptor, provider);
    }
    return [provider, providerDescriptor];
  }
};
$lXb = __decorate([
  __param(0, $1M),
  __param(1, $Pk)
], $lXb);

// out-build/vs/platform/quickinput/browser/quickInputUtils.js
var iconPathToClass = {};
var iconClassGenerator = new $lW("quick-input-button-icon-");
function getIconClass(iconPath) {
  if (!iconPath) {
    return void 0;
  }
  let iconClass;
  const key2 = iconPath.dark.toString();
  if (iconPathToClass[key2]) {
    iconClass = iconPathToClass[key2];
  } else {
    iconClass = iconClassGenerator.nextId();
    $XZ(`.${iconClass}, .hc-light .${iconClass}`, `background-image: ${$5Z(iconPath.light || iconPath.dark)}`);
    $XZ(`.vs-dark .${iconClass}, .hc-black .${iconClass}`, `background-image: ${$5Z(iconPath.dark)}`);
    iconPathToClass[key2] = iconClass;
  }
  return iconClass;
}
function $7Wb(button, id2, run) {
  let cssClasses = button.iconClass || getIconClass(button.iconPath);
  if (button.alwaysVisible) {
    cssClasses = cssClasses ? `${cssClasses} always-visible` : "always-visible";
  }
  return {
    id: id2,
    label: "",
    tooltip: button.tooltip || "",
    class: cssClasses,
    enabled: true,
    run
  };
}
function $8Wb(description, container2, actionHandler) {
  $dk(container2);
  const parsed = $U3(description);
  let tabIndex = 0;
  for (const node of parsed.nodes) {
    if (typeof node === "string") {
      container2.append(...$B1(node));
    } else {
      let title = node.title;
      if (!title && node.href.startsWith("command:")) {
        title = localize(2078, null, node.href.substring("command:".length));
      } else if (!title) {
        title = node.href;
      }
      const anchor = $("a", { href: node.href, title, tabIndex: tabIndex++ }, node.label);
      anchor.style.textDecoration = "underline";
      const handleOpen = (e) => {
        if ($8j(e)) {
          $9j.stop(e, true);
        }
        actionHandler.callback(node.href);
      };
      const onClick2 = actionHandler.disposables.add(new $9Z(anchor, $7j.CLICK)).event;
      const onKeydown = actionHandler.disposables.add(new $9Z(anchor, $7j.KEY_DOWN)).event;
      const onSpaceOrEnter = Event2.chain(onKeydown, ($149) => $149.filter((e) => {
        const event = new $if(e);
        return event.equals(
          10
          /* KeyCode.Space */
        ) || event.equals(
          3
          /* KeyCode.Enter */
        );
      }));
      actionHandler.disposables.add($mZ.addTarget(anchor));
      const onTap = actionHandler.disposables.add(new $9Z(anchor, EventType.Tap)).event;
      Event2.any(onClick2, onTap, onSpaceOrEnter)(handleOpen, null, actionHandler.disposables);
      container2.appendChild(anchor);
    }
  }
}

// out-build/vs/platform/quickinput/browser/quickInput.js
var $0Wb = "inQuickInput";
var $$Wb = new $nn($0Wb, false, localize(2059, null));
var $_Wb = $7m.has($0Wb);
var $aXb = "quickInputType";
var $bXb = new $nn($aXb, void 0, localize(2060, null));
var $cXb = "cursorAtEndOfQuickInputBox";
var $dXb = new $nn($cXb, false, localize(2061, null));
var $eXb = $7m.has($cXb);
var $fXb = {
  iconClass: ThemeIcon.asClassName($6l.quickInputBack),
  tooltip: localize(2062, null),
  handle: -1
  // TODO
};
var QuickInput = class _QuickInput extends $3c {
  static {
    this.c = localize(2063, null);
  }
  constructor(X) {
    super();
    this.X = X;
    this.j = false;
    this.r = false;
    this.s = true;
    this.u = false;
    this.w = false;
    this.y = [];
    this.z = [];
    this.C = [];
    this.D = false;
    this.F = [];
    this.G = false;
    this.H = _QuickInput.c;
    this.L = severity_default.Ignore;
    this.N = this.B(new $ze());
    this.Q = this.B(new $ze());
    this.R = this.B(new $ze());
    this.S = this.B(new $ze());
    this.U = this.B(new $2c());
    this.onDidTriggerButton = this.N.event;
    this.onDidHide = this.Q.event;
    this.onWillHide = this.R.event;
    this.onDispose = this.S.event;
  }
  get title() {
    return this.f;
  }
  set title(title) {
    this.f = title;
    this.Z();
  }
  get description() {
    return this.g;
  }
  set description(description) {
    this.g = description;
    this.Z();
  }
  get widget() {
    return this.h;
  }
  set widget(widget) {
    if (!$Uj(widget)) {
      return;
    }
    if (this.h !== widget) {
      this.h = widget;
      this.j = true;
      this.Z();
    }
  }
  get step() {
    return this.m;
  }
  set step(step) {
    this.m = step;
    this.Z();
  }
  get totalSteps() {
    return this.n;
  }
  set totalSteps(totalSteps) {
    this.n = totalSteps;
    this.Z();
  }
  get enabled() {
    return this.s;
  }
  set enabled(enabled) {
    this.s = enabled;
    this.Z();
  }
  get contextKey() {
    return this.t;
  }
  set contextKey(contextKey) {
    this.t = contextKey;
    this.Z();
  }
  get busy() {
    return this.u;
  }
  set busy(busy) {
    this.u = busy;
    this.Z();
  }
  get ignoreFocusOut() {
    return this.w;
  }
  set ignoreFocusOut(ignoreFocusOut) {
    const shouldUpdate = this.w !== ignoreFocusOut && !$u;
    this.w = ignoreFocusOut && !$u;
    if (shouldUpdate) {
      this.Z();
    }
  }
  get Y() {
    return this.y.length ? [...this.y, this.z] : this.z;
  }
  get buttons() {
    return [
      ...this.y,
      ...this.z,
      ...this.C
    ];
  }
  set buttons(buttons) {
    this.y = buttons.filter((b) => b === $fXb);
    this.z = buttons.filter((b) => b !== $fXb && b.location !== QuickInputButtonLocation.Inline);
    this.C = buttons.filter((b) => b.location === QuickInputButtonLocation.Inline);
    this.D = true;
    this.Z();
  }
  get toggles() {
    return this.F;
  }
  set toggles(toggles) {
    this.F = toggles ?? [];
    this.G = true;
    this.Z();
  }
  get validationMessage() {
    return this.I;
  }
  set validationMessage(validationMessage) {
    this.I = validationMessage;
    this.Z();
  }
  get severity() {
    return this.L;
  }
  set severity(severity) {
    this.L = severity;
    this.Z();
  }
  show() {
    if (this.r) {
      return;
    }
    this.U.add(this.X.onDidTriggerButton((button) => {
      if (this.buttons.indexOf(button) !== -1) {
        this.N.fire(button);
      }
    }));
    this.X.show(this);
    this.r = true;
    this.J = void 0;
    this.M = void 0;
    if (this.buttons.length) {
      this.D = true;
    }
    if (this.toggles.length) {
      this.G = true;
    }
    this.Z();
  }
  hide() {
    if (!this.r) {
      return;
    }
    this.X.hide();
  }
  didHide(reason = QuickInputHideReason.Other) {
    this.r = false;
    this.U.clear();
    this.Q.fire({ reason });
  }
  willHide(reason = QuickInputHideReason.Other) {
    this.R.fire({ reason });
  }
  Z() {
    if (!this.r) {
      return;
    }
    const title = this.$();
    if (title && this.X.title.textContent !== title) {
      this.X.title.textContent = title;
    } else if (!title && this.X.title.innerHTML !== "&nbsp;") {
      this.X.title.innerText = "\xA0";
    }
    const description = this.ab();
    if (this.X.description1.textContent !== description) {
      this.X.description1.textContent = description;
    }
    if (this.X.description2.textContent !== description) {
      this.X.description2.textContent = description;
    }
    if (this.j) {
      this.j = false;
      if (this.h) {
        $dk(this.X.widget, this.h);
      } else {
        $dk(this.X.widget);
      }
    }
    if (this.busy && !this.W) {
      this.W = new $6h();
      this.W.setIfNotSet(() => {
        if (this.r) {
          this.X.progressBar.infinite();
        }
      }, 800);
    }
    if (!this.busy && this.W) {
      this.X.progressBar.stop();
      this.W.cancel();
      this.W = void 0;
    }
    if (this.D) {
      this.D = false;
      this.X.leftActionBar.clear();
      const leftButtons = this.y.map((button, index) => $7Wb(button, `id-${index}`, async () => this.N.fire(button)));
      this.X.leftActionBar.push(leftButtons, { icon: true, label: false });
      this.X.rightActionBar.clear();
      const rightButtons = this.z.map((button, index) => $7Wb(button, `id-${index}`, async () => this.N.fire(button)));
      this.X.rightActionBar.push(rightButtons, { icon: true, label: false });
      this.X.inlineActionBar.clear();
      const inlineButtons = this.C.map((button, index) => $7Wb(button, `id-${index}`, async () => this.N.fire(button)));
      this.X.inlineActionBar.push(inlineButtons, { icon: true, label: false });
    }
    if (this.G) {
      this.G = false;
      const concreteToggles = this.toggles?.filter((opts) => opts instanceof $Q1) ?? [];
      this.X.inputBox.toggles = concreteToggles;
    }
    this.X.ignoreFocusOut = this.ignoreFocusOut;
    this.X.setEnabled(this.enabled);
    this.X.setContextKey(this.contextKey);
    const validationMessage = this.validationMessage || this.H;
    if (this.J !== validationMessage) {
      this.J = validationMessage;
      $dk(this.X.message);
      $8Wb(validationMessage, this.X.message, {
        callback: (content) => {
          this.X.linkOpenerDelegate(content);
        },
        disposables: this.U
      });
    }
    if (this.M !== this.severity) {
      this.M = this.severity;
      this.cb(this.severity);
    }
  }
  $() {
    if (this.title && this.step) {
      return `${this.title} (${this.bb()})`;
    }
    if (this.title) {
      return this.title;
    }
    if (this.step) {
      return this.bb();
    }
    return "";
  }
  ab() {
    return this.description || "";
  }
  bb() {
    if (this.step && this.totalSteps) {
      return localize(2064, null, this.step, this.totalSteps);
    }
    if (this.step) {
      return String(this.step);
    }
    return "";
  }
  cb(severity) {
    this.X.inputBox.showDecoration(severity);
    if (severity !== severity_default.Ignore) {
      const styles = this.X.inputBox.stylesForType(severity);
      this.X.message.style.color = styles.foreground ? `${styles.foreground}` : "";
      this.X.message.style.backgroundColor = styles.background ? `${styles.background}` : "";
      this.X.message.style.border = styles.border ? `1px solid ${styles.border}` : "";
      this.X.message.style.marginBottom = "-2px";
    } else {
      this.X.message.style.color = "";
      this.X.message.style.backgroundColor = "";
      this.X.message.style.border = "";
      this.X.message.style.marginBottom = "";
    }
  }
  dispose() {
    this.hide();
    this.S.fire();
    super.dispose();
  }
};
var $gXb = class _$gXb extends QuickInput {
  constructor() {
    super(...arguments);
    this.eb = "";
    this.hb = this.B(new $ze());
    this.ib = this.B(new $ze());
    this.jb = this.B(new $ze());
    this.kb = this.B(new $ze());
    this.lb = [];
    this.mb = false;
    this.nb = false;
    this.ob = false;
    this.pb = false;
    this.qb = false;
    this.rb = true;
    this.sb = "fuzzy";
    this.tb = true;
    this.ub = false;
    this.vb = ItemActivation.FIRST;
    this.wb = [];
    this.xb = false;
    this.yb = [];
    this.zb = this.B(new $ze());
    this.Ab = [];
    this.Bb = false;
    this.Cb = [];
    this.Db = this.B(new $ze());
    this.Eb = this.B(new $ze());
    this.Fb = this.B(new $ze());
    this.Hb = true;
    this.Ib = "default";
    this.Jb = false;
    this.Qb = new $He();
    this.type = "quickPick";
    this.filterValue = (value) => value;
    this.onDidChangeValue = this.hb.event;
    this.onWillAccept = this.ib.event;
    this.onDidAccept = this.jb.event;
    this.onDidCustom = this.kb.event;
    this.onDidChangeActive = this.zb.event;
    this.onDidChangeSelection = this.Db.event;
    this.onDidTriggerItemButton = this.Eb.event;
    this.onDidTriggerSeparatorButton = this.Fb.event;
  }
  static {
    this.db = localize(2065, null);
  }
  get quickNavigate() {
    return this.Mb;
  }
  set quickNavigate(quickNavigate) {
    this.Mb = quickNavigate;
    this.Z();
  }
  get value() {
    return this.eb;
  }
  set value(value) {
    this.Rb(value);
  }
  Rb(value, skipUpdate) {
    if (this.eb !== value) {
      this.eb = value;
      if (!skipUpdate) {
        this.Z();
      }
      if (this.r) {
        const didFilter = this.X.list.filter(this.filterValue(this.eb));
        if (didFilter) {
          this.Tb();
        }
      }
      this.hb.fire(this.eb);
    }
  }
  set ariaLabel(ariaLabel) {
    this.fb = ariaLabel;
    this.Z();
  }
  get ariaLabel() {
    return this.fb;
  }
  get placeholder() {
    return this.gb;
  }
  set placeholder(placeholder) {
    this.gb = placeholder;
    this.Z();
  }
  get items() {
    return this.lb;
  }
  get Sb() {
    return this.X.list.scrollTop;
  }
  set Sb(scrollTop) {
    this.X.list.scrollTop = scrollTop;
  }
  set items(items) {
    this.lb = items;
    this.mb = true;
    this.Z();
  }
  get canSelectMany() {
    return this.nb;
  }
  set canSelectMany(canSelectMany) {
    this.nb = canSelectMany;
    this.Z();
  }
  get canAcceptInBackground() {
    return this.ob;
  }
  set canAcceptInBackground(canAcceptInBackground) {
    this.ob = canAcceptInBackground;
  }
  get matchOnDescription() {
    return this.pb;
  }
  set matchOnDescription(matchOnDescription) {
    this.pb = matchOnDescription;
    this.Z();
  }
  get matchOnDetail() {
    return this.qb;
  }
  set matchOnDetail(matchOnDetail) {
    this.qb = matchOnDetail;
    this.Z();
  }
  get matchOnLabel() {
    return this.rb;
  }
  set matchOnLabel(matchOnLabel) {
    this.rb = matchOnLabel;
    this.Z();
  }
  get matchOnLabelMode() {
    return this.sb;
  }
  set matchOnLabelMode(matchOnLabelMode) {
    this.sb = matchOnLabelMode;
    this.Z();
  }
  get sortByLabel() {
    return this.tb;
  }
  set sortByLabel(sortByLabel) {
    this.tb = sortByLabel;
    this.Z();
  }
  get keepScrollPosition() {
    return this.ub;
  }
  set keepScrollPosition(keepScrollPosition) {
    this.ub = keepScrollPosition;
  }
  get itemActivation() {
    return this.vb;
  }
  set itemActivation(itemActivation) {
    this.vb = itemActivation;
  }
  get activeItems() {
    return this.wb;
  }
  set activeItems(activeItems) {
    this.wb = activeItems;
    this.xb = true;
    this.Z();
  }
  get selectedItems() {
    return this.Ab;
  }
  set selectedItems(selectedItems) {
    this.Ab = selectedItems;
    this.Bb = true;
    this.Z();
  }
  get keyMods() {
    if (this.Mb) {
      return $XM;
    }
    return this.X.keyMods;
  }
  get valueSelection() {
    const selection = this.X.inputBox.getSelection();
    if (!selection) {
      return void 0;
    }
    return [selection.start, selection.end];
  }
  set valueSelection(valueSelection) {
    this.Gb = valueSelection;
    this.Hb = true;
    this.Z();
  }
  get customButton() {
    return this.Jb;
  }
  set customButton(showCustomButton) {
    this.Jb = showCustomButton;
    this.Z();
  }
  get customLabel() {
    return this.Kb;
  }
  set customLabel(label3) {
    this.Kb = label3;
    this.Z();
  }
  get customHover() {
    return this.Lb;
  }
  set customHover(hover) {
    this.Lb = hover;
    this.Z();
  }
  get ok() {
    return this.Ib;
  }
  set ok(showOkButton) {
    this.Ib = showOkButton;
    this.Z();
  }
  inputHasFocus() {
    return this.r ? this.X.inputBox.hasFocus() : false;
  }
  focusOnInput() {
    this.X.inputBox.setFocus();
  }
  get hideInput() {
    return !!this.Nb;
  }
  set hideInput(hideInput) {
    this.Nb = hideInput;
    this.Z();
  }
  get hideCountBadge() {
    return !!this.Ob;
  }
  set hideCountBadge(hideCountBadge) {
    this.Ob = hideCountBadge;
    this.Z();
  }
  get hideCheckAll() {
    return !!this.Pb;
  }
  set hideCheckAll(hideCheckAll) {
    this.Pb = hideCheckAll;
    this.Z();
  }
  Tb() {
    if (!this.canSelectMany) {
      this.X.list.focus(QuickPickFocus.First);
    }
  }
  show() {
    if (!this.r) {
      this.U.add(this.X.inputBox.onDidChange((value) => {
        this.Rb(
          value,
          true
          /* skip update since this originates from the UI */
        );
      }));
      this.U.add(this.X.onDidAccept(() => {
        if (this.canSelectMany) {
          if (!this.X.list.getCheckedElements().length) {
            this.Ab = [];
            this.Db.fire(this.selectedItems);
          }
        } else if (this.activeItems[0]) {
          this.Ab = [this.activeItems[0]];
          this.Db.fire(this.selectedItems);
        }
        this.Ub(false);
      }));
      this.U.add(this.X.onDidCustom(() => {
        this.kb.fire();
      }));
      this.U.add(this.Qb.wrapEvent(
        this.X.list.onDidChangeFocus,
        // Only fire the last event
        (_, e) => e
      )((focusedItems) => {
        if (this.xb) {
          return;
        }
        if (this.yb !== this.wb && $zb(focusedItems, this.wb, (a, b) => a === b)) {
          return;
        }
        this.wb = focusedItems;
        this.zb.fire(focusedItems);
      }));
      this.U.add(this.X.list.onDidChangeSelection(({ items: selectedItems, event }) => {
        if (this.canSelectMany) {
          if (selectedItems.length) {
            this.X.list.setSelectedElements([]);
          }
          return;
        }
        if (this.Cb !== this.Ab && $zb(selectedItems, this.Ab, (a, b) => a === b)) {
          return;
        }
        this.Ab = selectedItems;
        this.Db.fire(selectedItems);
        if (selectedItems.length) {
          this.Ub(
            $3j(event) && event.button === 1
            /* mouse middle click */
          );
        }
      }));
      this.U.add(this.X.list.onChangedCheckedElements((checkedItems) => {
        if (!this.canSelectMany || !this.r) {
          return;
        }
        if (this.Cb !== this.Ab && $zb(checkedItems, this.Ab, (a, b) => a === b)) {
          return;
        }
        this.Ab = checkedItems;
        this.Db.fire(checkedItems);
      }));
      this.U.add(this.X.list.onButtonTriggered((event) => this.Eb.fire(event)));
      this.U.add(this.X.list.onSeparatorButtonTriggered((event) => this.Fb.fire(event)));
      this.U.add(this.Vb());
      this.Hb = true;
    }
    super.show();
  }
  Ub(inBackground) {
    let veto = false;
    this.ib.fire({ veto: () => veto = true });
    if (!veto) {
      this.jb.fire({ inBackground });
    }
  }
  Vb() {
    return $_i(this.X.container, $7j.KEY_UP, (e) => {
      if (this.canSelectMany || !this.Mb) {
        return;
      }
      const keyboardEvent = new $if(e);
      const keyCode = keyboardEvent.keyCode;
      const quickNavKeys = this.Mb.keybindings;
      const wasTriggerKeyPressed = quickNavKeys.some((k) => {
        const chords = k.getChords();
        if (chords.length > 1) {
          return false;
        }
        if (chords[0].shiftKey && keyCode === 4) {
          if (keyboardEvent.ctrlKey || keyboardEvent.altKey || keyboardEvent.metaKey) {
            return false;
          }
          return true;
        }
        if (chords[0].altKey && keyCode === 6) {
          return true;
        }
        if (chords[0].ctrlKey && keyCode === 5) {
          return true;
        }
        if (chords[0].metaKey && keyCode === 57) {
          return true;
        }
        return false;
      });
      if (wasTriggerKeyPressed) {
        if (this.activeItems[0]) {
          this.Ab = [this.activeItems[0]];
          this.Db.fire(this.selectedItems);
          this.Ub(false);
        }
        this.Mb = void 0;
      }
    });
  }
  Z() {
    if (!this.r) {
      return;
    }
    const scrollTopBefore = this.keepScrollPosition ? this.Sb : 0;
    const hasDescription = !!this.description;
    const visibilities = {
      title: !!this.title || !!this.step || !!this.Y.length,
      description: hasDescription,
      checkAll: this.canSelectMany && !this.Pb,
      checkBox: this.canSelectMany,
      inputBox: !this.Nb,
      progressBar: !this.Nb || hasDescription,
      visibleCount: true,
      count: this.canSelectMany && !this.Ob,
      ok: this.ok === "default" ? this.canSelectMany : this.ok,
      list: true,
      message: !!this.validationMessage,
      customButton: this.customButton
    };
    this.X.setVisibilities(visibilities);
    super.Z();
    if (this.X.inputBox.value !== this.value) {
      this.X.inputBox.value = this.value;
    }
    if (this.Hb) {
      this.Hb = false;
      this.X.inputBox.select(this.Gb && { start: this.Gb[0], end: this.Gb[1] });
    }
    if (this.X.inputBox.placeholder !== (this.placeholder || "")) {
      this.X.inputBox.placeholder = this.placeholder || "";
    }
    let ariaLabel = this.ariaLabel;
    if (!ariaLabel && visibilities.inputBox) {
      ariaLabel = this.placeholder || _$gXb.db;
      if (this.title) {
        ariaLabel += ` - ${this.title}`;
      }
    }
    if (this.X.list.ariaLabel !== ariaLabel) {
      this.X.list.ariaLabel = ariaLabel ?? null;
    }
    this.X.list.matchOnDescription = this.matchOnDescription;
    this.X.list.matchOnDetail = this.matchOnDetail;
    this.X.list.matchOnLabel = this.matchOnLabel;
    this.X.list.matchOnLabelMode = this.matchOnLabelMode;
    this.X.list.sortByLabel = this.sortByLabel;
    if (this.mb) {
      this.mb = false;
      this.Qb.bufferEvents(() => {
        this.X.list.setElements(this.items);
        this.X.list.shouldLoop = !this.canSelectMany;
        this.X.list.filter(this.filterValue(this.X.inputBox.value));
        switch (this.vb) {
          case ItemActivation.NONE:
            this.vb = ItemActivation.FIRST;
            break;
          case ItemActivation.SECOND:
            this.X.list.focus(QuickPickFocus.Second);
            this.vb = ItemActivation.FIRST;
            break;
          case ItemActivation.LAST:
            this.X.list.focus(QuickPickFocus.Last);
            this.vb = ItemActivation.FIRST;
            break;
          default:
            this.Tb();
            break;
        }
      });
    }
    if (this.X.container.classList.contains("show-checkboxes") !== !!this.canSelectMany) {
      if (this.canSelectMany) {
        this.X.list.clearFocus();
      } else {
        this.Tb();
      }
    }
    if (this.xb) {
      this.xb = false;
      this.yb = this.wb;
      this.X.list.setFocusedElements(this.activeItems);
      if (this.yb === this.wb) {
        this.yb = null;
      }
    }
    if (this.Bb) {
      this.Bb = false;
      this.Cb = this.Ab;
      if (this.canSelectMany) {
        this.X.list.setCheckedElements(this.selectedItems);
      } else {
        this.X.list.setSelectedElements(this.selectedItems);
      }
      if (this.Cb === this.Ab) {
        this.Cb = null;
      }
    }
    this.X.customButton.label = this.customLabel || "";
    this.X.customButton.element.title = this.customHover || "";
    if (!visibilities.inputBox) {
      this.X.list.domFocus();
      if (this.canSelectMany) {
        this.X.list.focus(QuickPickFocus.First);
      }
    }
    if (this.keepScrollPosition) {
      this.Sb = scrollTopBefore;
    }
  }
  focus(focus) {
    this.X.list.focus(focus);
    if (this.canSelectMany) {
      this.X.list.domFocus();
    }
  }
  accept(inBackground) {
    if (inBackground && !this.ob) {
      return;
    }
    if (this.activeItems[0]) {
      this.Ab = [this.activeItems[0]];
      this.Db.fire(this.selectedItems);
      this.Ub(inBackground ?? false);
    }
  }
};
var $hXb = class extends QuickInput {
  constructor() {
    super(...arguments);
    this.db = "";
    this.fb = true;
    this.hb = false;
    this.jb = this.B(new $ze());
    this.kb = this.B(new $ze());
    this.type = "inputBox";
    this.onDidChangeValue = this.jb.event;
    this.onDidAccept = this.kb.event;
  }
  get value() {
    return this.db;
  }
  set value(value) {
    this.db = value || "";
    this.Z();
  }
  get valueSelection() {
    const selection = this.X.inputBox.getSelection();
    if (!selection) {
      return void 0;
    }
    return [selection.start, selection.end];
  }
  set valueSelection(valueSelection) {
    this.eb = valueSelection;
    this.fb = true;
    this.Z();
  }
  get placeholder() {
    return this.gb;
  }
  set placeholder(placeholder) {
    this.gb = placeholder;
    this.Z();
  }
  get password() {
    return this.hb;
  }
  set password(password) {
    this.hb = password;
    this.Z();
  }
  get prompt() {
    return this.ib;
  }
  set prompt(prompt) {
    this.ib = prompt;
    this.H = prompt ? localize(2066, null, prompt) : QuickInput.c;
    this.Z();
  }
  show() {
    if (!this.r) {
      this.U.add(this.X.inputBox.onDidChange((value) => {
        if (value === this.value) {
          return;
        }
        this.db = value;
        this.jb.fire(value);
      }));
      this.U.add(this.X.onDidAccept(() => this.kb.fire()));
      this.fb = true;
    }
    super.show();
  }
  Z() {
    if (!this.r) {
      return;
    }
    this.X.container.classList.remove("hidden-input");
    const visibilities = {
      title: !!this.title || !!this.step || !!this.Y.length,
      description: !!this.description || !!this.step,
      inputBox: true,
      message: true,
      progressBar: true
    };
    this.X.setVisibilities(visibilities);
    super.Z();
    if (this.X.inputBox.value !== this.value) {
      this.X.inputBox.value = this.value;
    }
    if (this.fb) {
      this.fb = false;
      this.X.inputBox.select(this.eb && { start: this.eb[0], end: this.eb[1] });
    }
    if (this.X.inputBox.placeholder !== (this.placeholder || "")) {
      this.X.inputBox.placeholder = this.placeholder || "";
    }
    if (this.X.inputBox.password !== this.password) {
      this.X.inputBox.password = this.password;
    }
  }
};
var $iXb = class extends QuickInput {
  constructor() {
    super(...arguments);
    this.type = "quickWidget";
  }
  Z() {
    if (!this.r) {
      return;
    }
    const visibilities = {
      title: !!this.title || !!this.step || !!this.Y.length,
      description: !!this.description || !!this.step
    };
    this.X.setVisibilities(visibilities);
    super.Z();
  }
};
var $jXb = class $jXb2 extends $6$ {
  constructor(configurationService, hoverService) {
    super("element", false, (options3) => this.h(options3), configurationService, hoverService);
  }
  h(options3) {
    const showHoverHint = ($Uj(options3.content) ? options3.content.textContent ?? "" : typeof options3.content === "string" ? options3.content : options3.content.value).includes("\n");
    return {
      persistence: {
        hideOnKeyDown: false
      },
      appearance: {
        showHoverHint,
        skipFadeInAnimation: true
      }
    };
  }
};
$jXb = __decorate([
  __param(0, $kl),
  __param(1, $5$)
], $jXb);

// out-build/vs/platform/quickinput/browser/quickInputBox.js
var $111 = $;
var $6Wb = class extends $3c {
  constructor(c, inputBoxStyles, toggleStyles) {
    super();
    this.c = c;
    this.onKeyDown = (handler) => {
      return $aj(this.b.inputBox.inputElement, $7j.KEY_DOWN, handler);
    };
    this.onMouseDown = (handler) => {
      return $aj(this.b.inputBox.inputElement, $7j.MOUSE_DOWN, handler);
    };
    this.onDidChange = (handler) => {
      return this.b.onDidChange(handler);
    };
    this.a = $bk(this.c, $111(".quick-input-box"));
    this.b = this.B(new $Q2(this.a, void 0, { label: "", inputBoxStyles, toggleStyles }));
    const input = this.b.inputBox.inputElement;
    input.role = "combobox";
    input.ariaHasPopup = "menu";
    input.ariaAutoComplete = "list";
    input.ariaExpanded = "true";
  }
  get value() {
    return this.b.getValue();
  }
  set value(value) {
    this.b.setValue(value);
  }
  select(range = null) {
    this.b.inputBox.select(range);
  }
  getSelection() {
    return this.b.inputBox.getSelection();
  }
  isSelectionAtEnd() {
    return this.b.inputBox.isSelectionAtEnd();
  }
  setPlaceholder(placeholder) {
    this.b.inputBox.setPlaceHolder(placeholder);
  }
  get placeholder() {
    return this.b.inputBox.inputElement.getAttribute("placeholder") || "";
  }
  set placeholder(placeholder) {
    this.b.inputBox.setPlaceHolder(placeholder);
  }
  get password() {
    return this.b.inputBox.inputElement.type === "password";
  }
  set password(password) {
    this.b.inputBox.inputElement.type = password ? "password" : "text";
  }
  set enabled(enabled) {
    this.b.inputBox.inputElement.toggleAttribute("readonly", !enabled);
  }
  set toggles(toggles) {
    this.b.setAdditionalToggles(toggles);
  }
  hasFocus() {
    return this.b.inputBox.hasFocus();
  }
  setAttribute(name, value) {
    this.b.inputBox.inputElement.setAttribute(name, value);
  }
  removeAttribute(name) {
    this.b.inputBox.inputElement.removeAttribute(name);
  }
  showDecoration(decoration3) {
    if (decoration3 === severity_default.Ignore) {
      this.b.clearMessage();
    } else {
      this.b.showMessage({ type: decoration3 === severity_default.Info ? 1 : decoration3 === severity_default.Warning ? 2 : 3, content: "" });
    }
  }
  stylesForType(decoration3) {
    return this.b.inputBox.stylesForType(
      decoration3 === severity_default.Info ? 1 : decoration3 === severity_default.Warning ? 2 : 3
      /* MessageType.ERROR */
    );
  }
  setFocus() {
    this.b.focus();
  }
  layout() {
    this.b.inputBox.layout();
  }
};

// out-build/vs/platform/quickinput/browser/quickInputTree.js
var QuickPickItemElementRenderer_1;
var $112 = $;
var BaseQuickPickItemElement = class {
  constructor(index, hasCheckbox, mainItem) {
    this.index = index;
    this.hasCheckbox = hasCheckbox;
    this.c = false;
    this.a = new $sf(() => {
      const saneLabel = mainItem.label ?? "";
      const saneSortLabel = $_l(saneLabel).text.trim();
      const saneAriaLabel = mainItem.ariaLabel || [saneLabel, this.saneDescription, this.saneDetail].map((s) => $$l(s)).filter((s) => !!s).join(", ");
      return {
        saneLabel,
        saneSortLabel,
        saneAriaLabel
      };
    });
    this.d = mainItem.description;
    this.g = mainItem.tooltip;
  }
  // #region Lazy Getters
  get saneLabel() {
    return this.a.value.saneLabel;
  }
  get saneSortLabel() {
    return this.a.value.saneSortLabel;
  }
  get saneAriaLabel() {
    return this.a.value.saneAriaLabel;
  }
  get element() {
    return this.b;
  }
  set element(value) {
    this.b = value;
  }
  get hidden() {
    return this.c;
  }
  set hidden(value) {
    this.c = value;
  }
  get saneDescription() {
    return this.d;
  }
  set saneDescription(value) {
    this.d = value;
  }
  get saneDetail() {
    return this.f;
  }
  set saneDetail(value) {
    this.f = value;
  }
  get saneTooltip() {
    return this.g;
  }
  set saneTooltip(value) {
    this.g = value;
  }
  get labelHighlights() {
    return this.h;
  }
  set labelHighlights(value) {
    this.h = value;
  }
  get descriptionHighlights() {
    return this.j;
  }
  set descriptionHighlights(value) {
    this.j = value;
  }
  get detailHighlights() {
    return this.k;
  }
  set detailHighlights(value) {
    this.k = value;
  }
};
var QuickPickItemElement = class extends BaseQuickPickItemElement {
  constructor(index, hasCheckbox, fireButtonTriggered, l, item, m) {
    super(index, hasCheckbox, item);
    this.fireButtonTriggered = fireButtonTriggered;
    this.l = l;
    this.item = item;
    this.m = m;
    this.o = false;
    this.onChecked = hasCheckbox ? Event2.map(Event2.filter(this.l.event, (e) => e.element === this), (e) => e.checked) : Event2.None;
    this.f = item.detail;
    this.h = item.highlights?.label;
    this.j = item.highlights?.description;
    this.k = item.highlights?.detail;
  }
  get separator() {
    return this.m;
  }
  set separator(value) {
    this.m = value;
  }
  get checked() {
    return this.o;
  }
  set checked(value) {
    if (value !== this.o) {
      this.o = value;
      this.l.fire({ element: this, checked: value });
    }
  }
  get checkboxDisabled() {
    return !!this.item.disabled;
  }
};
var QuickPickSeparatorFocusReason;
(function(QuickPickSeparatorFocusReason2) {
  QuickPickSeparatorFocusReason2[QuickPickSeparatorFocusReason2["NONE"] = 0] = "NONE";
  QuickPickSeparatorFocusReason2[QuickPickSeparatorFocusReason2["MOUSE_HOVER"] = 1] = "MOUSE_HOVER";
  QuickPickSeparatorFocusReason2[QuickPickSeparatorFocusReason2["ACTIVE_ITEM"] = 2] = "ACTIVE_ITEM";
})(QuickPickSeparatorFocusReason || (QuickPickSeparatorFocusReason = {}));
var QuickPickSeparatorElement = class extends BaseQuickPickItemElement {
  constructor(index, fireSeparatorButtonTriggered, separator) {
    super(index, false, separator);
    this.fireSeparatorButtonTriggered = fireSeparatorButtonTriggered;
    this.separator = separator;
    this.children = new Array();
    this.focusInsideSeparator = QuickPickSeparatorFocusReason.NONE;
  }
};
var QuickInputItemDelegate = class {
  getHeight(element) {
    if (element instanceof QuickPickSeparatorElement) {
      return 30;
    }
    return element.saneDetail ? 44 : 22;
  }
  getTemplateId(element) {
    if (element instanceof QuickPickItemElement) {
      return QuickPickItemElementRenderer.ID;
    } else {
      return QuickPickSeparatorElementRenderer.ID;
    }
  }
};
var QuickInputAccessibilityProvider = class {
  getWidgetAriaLabel() {
    return localize(2077, null);
  }
  getAriaLabel(element) {
    return element.separator?.label ? `${element.saneAriaLabel}, ${element.separator.label}` : element.saneAriaLabel;
  }
  getWidgetRole() {
    return "listbox";
  }
  getRole(element) {
    return element.hasCheckbox ? "checkbox" : "option";
  }
  isChecked(element) {
    if (!element.hasCheckbox || !(element instanceof QuickPickItemElement)) {
      return void 0;
    }
    return {
      get value() {
        return element.checked;
      },
      onDidChange: (e) => element.onChecked(() => e())
    };
  }
};
var BaseQuickInputListRenderer = class {
  constructor(a) {
    this.a = a;
  }
  // TODO: only do the common stuff here and have a subclass handle their specific stuff
  renderTemplate(container2) {
    const data = /* @__PURE__ */ Object.create(null);
    data.toDisposeElement = new $2c();
    data.toDisposeTemplate = new $2c();
    data.entry = $bk(container2, $112(".quick-input-list-entry"));
    const label3 = $bk(data.entry, $112("label.quick-input-list-label"));
    data.toDisposeTemplate.add($aj(label3, $7j.CLICK, (e) => {
      if (!data.checkbox.offsetParent) {
        e.preventDefault();
      }
    }));
    data.checkbox = $bk(label3, $112("input.quick-input-list-checkbox"));
    data.checkbox.type = "checkbox";
    const rows = $bk(label3, $112(".quick-input-list-rows"));
    const row1 = $bk(rows, $112(".quick-input-list-row"));
    const row2 = $bk(rows, $112(".quick-input-list-row"));
    data.label = new $T2(row1, { supportHighlights: true, supportDescriptionHighlights: true, supportIcons: true, hoverDelegate: this.a });
    data.toDisposeTemplate.add(data.label);
    data.icon = $ck(data.label.element, $112(".quick-input-list-icon"));
    const keybindingContainer = $bk(row1, $112(".quick-input-list-entry-keybinding"));
    data.keybinding = new $32(keybindingContainer, OS);
    data.toDisposeTemplate.add(data.keybinding);
    const detailContainer = $bk(row2, $112(".quick-input-list-label-meta"));
    data.detail = new $T2(detailContainer, { supportHighlights: true, supportIcons: true, hoverDelegate: this.a });
    data.toDisposeTemplate.add(data.detail);
    data.separator = $bk(data.entry, $112(".quick-input-list-separator"));
    data.actionBar = new $LZ(data.entry, this.a ? { hoverDelegate: this.a } : void 0);
    data.actionBar.domNode.classList.add("quick-input-list-entry-action-bar");
    data.toDisposeTemplate.add(data.actionBar);
    return data;
  }
  disposeTemplate(data) {
    data.toDisposeElement.dispose();
    data.toDisposeTemplate.dispose();
  }
  disposeElement(_element, _index, data) {
    data.toDisposeElement.clear();
    data.actionBar.clear();
  }
};
var QuickPickItemElementRenderer = class QuickPickItemElementRenderer2 extends BaseQuickInputListRenderer {
  static {
    QuickPickItemElementRenderer_1 = this;
  }
  static {
    this.ID = "quickpickitem";
  }
  constructor(hoverDelegate, c) {
    super(hoverDelegate);
    this.c = c;
    this.b = /* @__PURE__ */ new Map();
  }
  get templateId() {
    return QuickPickItemElementRenderer_1.ID;
  }
  renderTemplate(container2) {
    const data = super.renderTemplate(container2);
    data.toDisposeTemplate.add($aj(data.checkbox, $7j.CHANGE, (e) => {
      data.element.checked = data.checkbox.checked;
    }));
    return data;
  }
  renderElement(node, index, data) {
    const element = node.element;
    data.element = element;
    element.element = data.entry ?? void 0;
    const mainItem = element.item;
    data.checkbox.checked = element.checked;
    data.toDisposeElement.add(element.onChecked((checked) => data.checkbox.checked = checked));
    data.checkbox.disabled = element.checkboxDisabled;
    const { labelHighlights, descriptionHighlights, detailHighlights } = element;
    if (mainItem.iconPath) {
      const icon2 = $fs(this.c.getColorTheme().type) ? mainItem.iconPath.dark : mainItem.iconPath.light ?? mainItem.iconPath.dark;
      const iconUrl = URI.revive(icon2);
      data.icon.className = "quick-input-list-icon";
      data.icon.style.backgroundImage = $5Z(iconUrl);
    } else {
      data.icon.style.backgroundImage = "";
      data.icon.className = mainItem.iconClass ? `quick-input-list-icon ${mainItem.iconClass}` : "";
    }
    let descriptionTitle;
    if (!element.saneTooltip && element.saneDescription) {
      descriptionTitle = {
        markdown: {
          value: $zf(element.saneDescription),
          supportThemeIcons: true
        },
        markdownNotSupportedFallback: element.saneDescription
      };
    }
    const options3 = {
      matches: labelHighlights || [],
      // If we have a tooltip, we want that to be shown and not any other hover
      descriptionTitle,
      descriptionMatches: descriptionHighlights || [],
      labelEscapeNewLines: true
    };
    options3.extraClasses = mainItem.iconClasses;
    options3.italic = mainItem.italic;
    options3.strikethrough = mainItem.strikethrough;
    data.entry.classList.remove("quick-input-list-separator-as-item");
    data.label.setLabel(element.saneLabel, element.saneDescription, options3);
    data.keybinding.set(mainItem.keybinding);
    if (element.saneDetail) {
      let title;
      if (!element.saneTooltip) {
        title = {
          markdown: {
            value: $zf(element.saneDetail),
            supportThemeIcons: true
          },
          markdownNotSupportedFallback: element.saneDetail
        };
      }
      data.detail.element.style.display = "";
      data.detail.setLabel(element.saneDetail, void 0, {
        matches: detailHighlights,
        title,
        labelEscapeNewLines: true
      });
    } else {
      data.detail.element.style.display = "none";
    }
    if (element.separator?.label) {
      data.separator.textContent = element.separator.label;
      data.separator.style.display = "";
      this.d(element);
    } else {
      data.separator.style.display = "none";
    }
    data.entry.classList.toggle("quick-input-list-separator-border", !!element.separator);
    const buttons = mainItem.buttons;
    if (buttons && buttons.length) {
      data.actionBar.push(buttons.map((button, index2) => $7Wb(button, `id-${index2}`, () => element.fireButtonTriggered({ button, item: element.item }))), { icon: true, label: false });
      data.entry.classList.add("has-actions");
    } else {
      data.entry.classList.remove("has-actions");
    }
  }
  disposeElement(element, _index, data) {
    this.f(element.element);
    super.disposeElement(element, _index, data);
  }
  isItemWithSeparatorVisible(item) {
    return this.b.has(item);
  }
  d(item) {
    this.b.set(item, (this.b.get(item) || 0) + 1);
  }
  f(item) {
    const frequency = this.b.get(item) || 0;
    if (frequency > 1) {
      this.b.set(item, frequency - 1);
    } else {
      this.b.delete(item);
    }
  }
};
QuickPickItemElementRenderer = QuickPickItemElementRenderer_1 = __decorate([
  __param(1, $gs)
], QuickPickItemElementRenderer);
var QuickPickSeparatorElementRenderer = class _QuickPickSeparatorElementRenderer extends BaseQuickInputListRenderer {
  constructor() {
    super(...arguments);
    this.b = /* @__PURE__ */ new Map();
  }
  static {
    this.ID = "quickpickseparator";
  }
  get templateId() {
    return _QuickPickSeparatorElementRenderer.ID;
  }
  get visibleSeparators() {
    return [...this.b.keys()];
  }
  isSeparatorVisible(separator) {
    return this.b.has(separator);
  }
  renderTemplate(container2) {
    const data = super.renderTemplate(container2);
    data.checkbox.style.display = "none";
    return data;
  }
  renderElement(node, index, data) {
    const element = node.element;
    data.element = element;
    element.element = data.entry ?? void 0;
    element.element.classList.toggle("focus-inside", !!element.focusInsideSeparator);
    const mainItem = element.separator;
    const { labelHighlights, descriptionHighlights } = element;
    data.icon.style.backgroundImage = "";
    data.icon.className = "";
    let descriptionTitle;
    if (!element.saneTooltip && element.saneDescription) {
      descriptionTitle = {
        markdown: {
          value: $zf(element.saneDescription),
          supportThemeIcons: true
        },
        markdownNotSupportedFallback: element.saneDescription
      };
    }
    const options3 = {
      matches: labelHighlights || [],
      // If we have a tooltip, we want that to be shown and not any other hover
      descriptionTitle,
      descriptionMatches: descriptionHighlights || [],
      labelEscapeNewLines: true
    };
    data.entry.classList.add("quick-input-list-separator-as-item");
    data.label.setLabel(element.saneLabel, element.saneDescription, options3);
    data.separator.style.display = "none";
    data.entry.classList.add("quick-input-list-separator-border");
    const buttons = mainItem.buttons;
    if (buttons && buttons.length) {
      data.actionBar.push(buttons.map((button, index2) => $7Wb(button, `id-${index2}`, () => element.fireSeparatorButtonTriggered({ button, separator: element.separator }))), { icon: true, label: false });
      data.entry.classList.add("has-actions");
    } else {
      data.entry.classList.remove("has-actions");
    }
    this.c(element);
  }
  disposeElement(element, _index, data) {
    this.d(element.element);
    if (!this.isSeparatorVisible(element.element)) {
      element.element.element?.classList.remove("focus-inside");
    }
    super.disposeElement(element, _index, data);
  }
  c(separator) {
    this.b.set(separator, (this.b.get(separator) || 0) + 1);
  }
  d(separator) {
    const frequency = this.b.get(separator) || 0;
    if (frequency > 1) {
      this.b.set(separator, frequency - 1);
    } else {
      this.b.delete(separator);
    }
  }
};
var $9Wb = class $9Wb2 extends $3c {
  constructor(M, N, O, id2, instantiationService, P) {
    super();
    this.M = M;
    this.N = N;
    this.O = O;
    this.P = P;
    this.a = new $ze();
    this.onKeyDown = this.a.event;
    this.b = new $ze();
    this.onLeave = this.b.event;
    this.c = $he("VisibleCount", 0);
    this.onChangedVisibleCount = Event2.fromObservable(this.c, this.q);
    this.f = $he("AllVisibleChecked", false);
    this.onChangedAllVisibleChecked = Event2.fromObservable(this.f, this.q);
    this.g = $he("CheckedCount", 0);
    this.onChangedCheckedCount = Event2.fromObservable(this.g, this.q);
    this.h = $me({ equalsFn: $zb }, new Array());
    this.onChangedCheckedElements = Event2.fromObservable(this.h, this.q);
    this.j = new $ze();
    this.onButtonTriggered = this.j.event;
    this.m = new $ze();
    this.onSeparatorButtonTriggered = this.m.event;
    this.r = new $ze();
    this.t = new $He();
    this.u = false;
    this.F = new Array();
    this.G = new Array();
    this.H = new Array();
    this.I = this.B(new $2c());
    this.Q = false;
    this.R = false;
    this.S = true;
    this.U = "fuzzy";
    this.W = true;
    this.X = true;
    this.Y = true;
    this.w = $bk(this.M, $112(".quick-input-list"));
    this.C = new QuickPickSeparatorElementRenderer(N);
    this.D = instantiationService.createInstance(QuickPickItemElementRenderer, N);
    this.z = this.B(instantiationService.createInstance($1eb, "QuickInput", this.w, new QuickInputItemDelegate(), [this.D, this.C], {
      filter: {
        filter(element) {
          return element.hidden ? 0 : element instanceof QuickPickSeparatorElement ? 2 : 1;
        }
      },
      sorter: {
        compare: (element, otherElement) => {
          if (!this.sortByLabel || !this.L) {
            return 0;
          }
          const normalizedSearchValue = this.L.toLowerCase();
          return compareEntries(element, otherElement, normalizedSearchValue);
        }
      },
      accessibilityProvider: new QuickInputAccessibilityProvider(),
      setRowLineHeight: false,
      multipleSelectionSupport: false,
      hideTwistiesOfChildlessElements: true,
      renderIndentGuides: RenderIndentGuides.None,
      findWidgetEnabled: false,
      indent: 0,
      horizontalScrolling: false,
      allowNonCollapsibleParents: true,
      alwaysConsumeMouseWheel: true
    }));
    this.z.getHTMLElement().id = id2;
    this.Z();
  }
  //#region public getters/setters
  get onDidChangeFocus() {
    return Event2.map(this.z.onDidChangeFocus, (e) => e.elements.filter((e2) => e2 instanceof QuickPickItemElement).map((e2) => e2.item), this.q);
  }
  get onDidChangeSelection() {
    return Event2.map(this.z.onDidChangeSelection, (e) => ({
      items: e.elements.filter((e2) => e2 instanceof QuickPickItemElement).map((e2) => e2.item),
      event: e.browserEvent
    }), this.q);
  }
  get displayed() {
    return this.w.style.display !== "none";
  }
  set displayed(value) {
    this.w.style.display = value ? "" : "none";
  }
  get scrollTop() {
    return this.z.scrollTop;
  }
  set scrollTop(scrollTop) {
    this.z.scrollTop = scrollTop;
  }
  get ariaLabel() {
    return this.z.ariaLabel;
  }
  set ariaLabel(label3) {
    this.z.ariaLabel = label3 ?? "";
  }
  set enabled(value) {
    this.z.getHTMLElement().style.pointerEvents = value ? "" : "none";
  }
  get matchOnDescription() {
    return this.Q;
  }
  set matchOnDescription(value) {
    this.Q = value;
  }
  get matchOnDetail() {
    return this.R;
  }
  set matchOnDetail(value) {
    this.R = value;
  }
  get matchOnLabel() {
    return this.S;
  }
  set matchOnLabel(value) {
    this.S = value;
  }
  get matchOnLabelMode() {
    return this.U;
  }
  set matchOnLabelMode(value) {
    this.U = value;
  }
  get matchOnMeta() {
    return this.W;
  }
  set matchOnMeta(value) {
    this.W = value;
  }
  get sortByLabel() {
    return this.X;
  }
  set sortByLabel(value) {
    this.X = value;
  }
  get shouldLoop() {
    return this.Y;
  }
  set shouldLoop(value) {
    this.Y = value;
  }
  //#endregion
  //#region register listeners
  Z() {
    this.ab();
    this.bb();
    this.cb();
    this.db();
    this.eb();
    this.fb();
    this.gb();
    this.ib();
    this.hb();
  }
  ab() {
    this.B(this.z.onKeyDown((e) => {
      const event = new $if(e);
      switch (event.keyCode) {
        case 10:
          this.toggleCheckbox();
          break;
      }
      this.a.fire(event);
    }));
  }
  bb() {
    this.B($_i(this.w, $7j.CLICK, (e) => {
      if (e.x || e.y) {
        this.b.fire();
      }
    }));
  }
  cb() {
    this.B($_i(this.w, $7j.AUXCLICK, (e) => {
      if (e.button === 1) {
        this.b.fire();
      }
    }));
  }
  db() {
    this.B(this.z.onDidChangeModel(() => {
      const visibleCount = this.H.filter((e) => !e.hidden).length;
      this.c.set(visibleCount, void 0);
      if (this.u) {
        this.lb();
      }
    }));
  }
  eb() {
    this.B(this.t.wrapEvent(this.r.event, (_, e) => e)((_) => this.lb()));
  }
  fb() {
    this.B(this.z.onContextMenu((e) => {
      if (e.element) {
        e.browserEvent.preventDefault();
        this.z.setSelection([e.element]);
      }
    }));
  }
  gb() {
    const delayer4 = this.B(new $Th(this.N.delay));
    this.B(this.z.onMouseOver(async (e) => {
      if ($Vj(e.browserEvent.target)) {
        delayer4.cancel();
        return;
      }
      if (
        // anchors are an exception as called out above so we skip them here
        !$Vj(e.browserEvent.relatedTarget) && // check if the mouse is still over the same element
        $Dj(e.browserEvent.relatedTarget, e.element?.element)
      ) {
        return;
      }
      try {
        await delayer4.trigger(async () => {
          if (e.element instanceof QuickPickItemElement) {
            this.mb(e.element);
          }
        });
      } catch (e2) {
        if (!$kb(e2)) {
          throw e2;
        }
      }
    }));
    this.B(this.z.onMouseOut((e) => {
      if ($Dj(e.browserEvent.relatedTarget, e.element?.element)) {
        return;
      }
      delayer4.cancel();
    }));
  }
  /**
   * Register's focus change and mouse events so that we can track when items inside of a
   * separator's section are focused or hovered so that we can display the separator's actions
   */
  hb() {
    this.B(this.z.onDidChangeFocus((e) => {
      const parent = e.elements[0] ? this.z.getParentElement(e.elements[0]) : null;
      for (const separator of this.C.visibleSeparators) {
        const value = separator === parent;
        const currentActive = !!(separator.focusInsideSeparator & QuickPickSeparatorFocusReason.ACTIVE_ITEM);
        if (currentActive !== value) {
          if (value) {
            separator.focusInsideSeparator |= QuickPickSeparatorFocusReason.ACTIVE_ITEM;
          } else {
            separator.focusInsideSeparator &= ~QuickPickSeparatorFocusReason.ACTIVE_ITEM;
          }
          this.z.rerender(separator);
        }
      }
    }));
    this.B(this.z.onMouseOver((e) => {
      const parent = e.element ? this.z.getParentElement(e.element) : null;
      for (const separator of this.C.visibleSeparators) {
        if (separator !== parent) {
          continue;
        }
        const currentMouse = !!(separator.focusInsideSeparator & QuickPickSeparatorFocusReason.MOUSE_HOVER);
        if (!currentMouse) {
          separator.focusInsideSeparator |= QuickPickSeparatorFocusReason.MOUSE_HOVER;
          this.z.rerender(separator);
        }
      }
    }));
    this.B(this.z.onMouseOut((e) => {
      const parent = e.element ? this.z.getParentElement(e.element) : null;
      for (const separator of this.C.visibleSeparators) {
        if (separator !== parent) {
          continue;
        }
        const currentMouse = !!(separator.focusInsideSeparator & QuickPickSeparatorFocusReason.MOUSE_HOVER);
        if (currentMouse) {
          separator.focusInsideSeparator &= ~QuickPickSeparatorFocusReason.MOUSE_HOVER;
          this.z.rerender(separator);
        }
      }
    }));
  }
  ib() {
    this.B(this.z.onDidChangeSelection((e) => {
      const elementsWithoutSeparators = e.elements.filter((e2) => e2 instanceof QuickPickItemElement);
      if (elementsWithoutSeparators.length !== e.elements.length) {
        if (e.elements.length === 1 && e.elements[0] instanceof QuickPickSeparatorElement) {
          this.z.setFocus([e.elements[0].children[0]]);
          this.z.reveal(e.elements[0], 0);
        }
        this.z.setSelection(elementsWithoutSeparators);
      }
    }));
  }
  //#endregion
  //#region public methods
  setAllVisibleChecked(checked) {
    this.t.bufferEvents(() => {
      this.H.forEach((element) => {
        if (!element.hidden && !element.checkboxDisabled) {
          element.checked = checked;
        }
      });
    });
  }
  setElements(inputElements) {
    this.I.clear();
    this.L = void 0;
    this.F = inputElements;
    this.u = this.M.classList.contains("show-checkboxes");
    let currentSeparatorElement;
    this.H = new Array();
    this.G = inputElements.reduce((result, item, index) => {
      let element;
      if (item.type === "separator") {
        if (!item.buttons) {
          return result;
        }
        currentSeparatorElement = new QuickPickSeparatorElement(index, (e) => this.m.fire(e), item);
        element = currentSeparatorElement;
      } else {
        const previous = index > 0 ? inputElements[index - 1] : void 0;
        let separator;
        if (previous && previous.type === "separator" && !previous.buttons) {
          currentSeparatorElement = void 0;
          separator = previous;
        }
        const qpi = new QuickPickItemElement(index, this.u, (e) => this.j.fire(e), this.r, item, separator);
        this.H.push(qpi);
        if (currentSeparatorElement) {
          currentSeparatorElement.children.push(qpi);
          return result;
        }
        element = qpi;
      }
      result.push(element);
      return result;
    }, new Array());
    this.jb(this.G);
    if (this.P.isScreenReaderOptimized()) {
      setTimeout(() => {
        const focusedElement = this.z.getHTMLElement().querySelector(`.monaco-list-row.focused`);
        const parent = focusedElement?.parentNode;
        if (focusedElement && parent) {
          const nextSibling = focusedElement.nextSibling;
          focusedElement.remove();
          parent.insertBefore(focusedElement, nextSibling);
        }
      }, 0);
    }
  }
  setFocusedElements(items) {
    const elements = items.map((item) => this.H.find((e) => e.item === item)).filter((e) => !!e).filter((e) => !e.hidden);
    this.z.setFocus(elements);
    if (items.length > 0) {
      const focused = this.z.getFocus()[0];
      if (focused) {
        this.z.reveal(focused);
      }
    }
  }
  getActiveDescendant() {
    return this.z.getHTMLElement().getAttribute("aria-activedescendant");
  }
  setSelectedElements(items) {
    const elements = items.map((item) => this.H.find((e) => e.item === item)).filter((e) => !!e);
    this.z.setSelection(elements);
  }
  getCheckedElements() {
    return this.H.filter((e) => e.checked).map((e) => e.item);
  }
  setCheckedElements(items) {
    this.t.bufferEvents(() => {
      const checked = /* @__PURE__ */ new Set();
      for (const item of items) {
        checked.add(item);
      }
      for (const element of this.H) {
        element.checked = checked.has(element.item);
      }
    });
  }
  focus(what) {
    if (!this.H.length) {
      return;
    }
    if (what === QuickPickFocus.Second && this.H.length < 2) {
      what = QuickPickFocus.First;
    }
    switch (what) {
      case QuickPickFocus.First:
        this.z.scrollTop = 0;
        this.z.focusFirst(void 0, (e) => e.element instanceof QuickPickItemElement);
        break;
      case QuickPickFocus.Second: {
        this.z.scrollTop = 0;
        let isSecondItem = false;
        this.z.focusFirst(void 0, (e) => {
          if (!(e.element instanceof QuickPickItemElement)) {
            return false;
          }
          if (isSecondItem) {
            return true;
          }
          isSecondItem = !isSecondItem;
          return false;
        });
        break;
      }
      case QuickPickFocus.Last:
        this.z.scrollTop = this.z.scrollHeight;
        this.z.focusLast(void 0, (e) => e.element instanceof QuickPickItemElement);
        break;
      case QuickPickFocus.Next: {
        const prevFocus = this.z.getFocus();
        this.z.focusNext(void 0, this.Y, void 0, (e) => {
          if (!(e.element instanceof QuickPickItemElement)) {
            return false;
          }
          this.z.reveal(e.element);
          return true;
        });
        const currentFocus = this.z.getFocus();
        if (prevFocus.length && prevFocus[0] === currentFocus[0] && prevFocus[0] === this.H[this.H.length - 1]) {
          this.b.fire();
        }
        break;
      }
      case QuickPickFocus.Previous: {
        const prevFocus = this.z.getFocus();
        this.z.focusPrevious(void 0, this.Y, void 0, (e) => {
          if (!(e.element instanceof QuickPickItemElement)) {
            return false;
          }
          const parent = this.z.getParentElement(e.element);
          if (parent === null || parent.children[0] !== e.element) {
            this.z.reveal(e.element);
          } else {
            this.z.reveal(parent);
          }
          return true;
        });
        const currentFocus = this.z.getFocus();
        if (prevFocus.length && prevFocus[0] === currentFocus[0] && prevFocus[0] === this.H[0]) {
          this.b.fire();
        }
        break;
      }
      case QuickPickFocus.NextPage:
        this.z.focusNextPage(void 0, (e) => {
          if (!(e.element instanceof QuickPickItemElement)) {
            return false;
          }
          this.z.reveal(e.element);
          return true;
        });
        break;
      case QuickPickFocus.PreviousPage:
        this.z.focusPreviousPage(void 0, (e) => {
          if (!(e.element instanceof QuickPickItemElement)) {
            return false;
          }
          const parent = this.z.getParentElement(e.element);
          if (parent === null || parent.children[0] !== e.element) {
            this.z.reveal(e.element);
          } else {
            this.z.reveal(parent);
          }
          return true;
        });
        break;
      case QuickPickFocus.NextSeparator: {
        let foundSeparatorAsItem = false;
        const before = this.z.getFocus()[0];
        this.z.focusNext(void 0, true, void 0, (e) => {
          if (foundSeparatorAsItem) {
            return true;
          }
          if (e.element instanceof QuickPickSeparatorElement) {
            foundSeparatorAsItem = true;
            if (this.C.isSeparatorVisible(e.element)) {
              this.z.reveal(e.element.children[0]);
            } else {
              this.z.reveal(e.element, 0);
            }
          } else if (e.element instanceof QuickPickItemElement) {
            if (e.element.separator) {
              if (this.D.isItemWithSeparatorVisible(e.element)) {
                this.z.reveal(e.element);
              } else {
                this.z.reveal(e.element, 0);
              }
              return true;
            } else if (e.element === this.G[0]) {
              this.z.reveal(e.element, 0);
              return true;
            }
          }
          return false;
        });
        const after = this.z.getFocus()[0];
        if (before === after) {
          this.z.scrollTop = this.z.scrollHeight;
          this.z.focusLast(void 0, (e) => e.element instanceof QuickPickItemElement);
        }
        break;
      }
      case QuickPickFocus.PreviousSeparator: {
        let focusElement;
        let foundSeparator = !!this.z.getFocus()[0]?.separator;
        this.z.focusPrevious(void 0, true, void 0, (e) => {
          if (e.element instanceof QuickPickSeparatorElement) {
            if (foundSeparator) {
              if (!focusElement) {
                if (this.C.isSeparatorVisible(e.element)) {
                  this.z.reveal(e.element);
                } else {
                  this.z.reveal(e.element, 0);
                }
                focusElement = e.element.children[0];
              }
            } else {
              foundSeparator = true;
            }
          } else if (e.element instanceof QuickPickItemElement) {
            if (!focusElement) {
              if (e.element.separator) {
                if (this.D.isItemWithSeparatorVisible(e.element)) {
                  this.z.reveal(e.element);
                } else {
                  this.z.reveal(e.element, 0);
                }
                focusElement = e.element;
              } else if (e.element === this.G[0]) {
                this.z.reveal(e.element, 0);
                return true;
              }
            }
          }
          return false;
        });
        if (focusElement) {
          this.z.setFocus([focusElement]);
        }
        break;
      }
    }
  }
  clearFocus() {
    this.z.setFocus([]);
  }
  domFocus() {
    this.z.domFocus();
  }
  layout(maxHeight) {
    this.z.getHTMLElement().style.maxHeight = maxHeight ? `${// Make sure height aligns with list item heights
    Math.floor(maxHeight / 44) * 44 + 6}px` : "";
    this.z.layout();
  }
  filter(query) {
    this.L = query;
    if (!(this.X || this.S || this.Q || this.R)) {
      this.z.layout();
      return false;
    }
    const queryWithWhitespace = query;
    query = query.trim();
    if (!query || !(this.matchOnLabel || this.matchOnDescription || this.matchOnDetail)) {
      this.H.forEach((element) => {
        element.labelHighlights = void 0;
        element.descriptionHighlights = void 0;
        element.detailHighlights = void 0;
        element.hidden = false;
        const previous = element.index && this.F[element.index - 1];
        if (element.item) {
          element.separator = previous && previous.type === "separator" && !previous.buttons ? previous : void 0;
        }
      });
    } else {
      let currentSeparator;
      this.H.forEach((element) => {
        let labelHighlights;
        if (this.matchOnLabelMode === "fuzzy") {
          labelHighlights = this.matchOnLabel ? $am(query, $_l(element.saneLabel)) ?? void 0 : void 0;
        } else {
          labelHighlights = this.matchOnLabel ? matchesContiguousIconAware(queryWithWhitespace, $_l(element.saneLabel)) ?? void 0 : void 0;
        }
        const descriptionHighlights = this.matchOnDescription ? $am(query, $_l(element.saneDescription || "")) ?? void 0 : void 0;
        const detailHighlights = this.matchOnDetail ? $am(query, $_l(element.saneDetail || "")) ?? void 0 : void 0;
        if (labelHighlights || descriptionHighlights || detailHighlights) {
          element.labelHighlights = labelHighlights;
          element.descriptionHighlights = descriptionHighlights;
          element.detailHighlights = detailHighlights;
          element.hidden = false;
        } else {
          element.labelHighlights = void 0;
          element.descriptionHighlights = void 0;
          element.detailHighlights = void 0;
          element.hidden = element.item ? !element.item.alwaysShow : true;
        }
        if (element.item) {
          element.separator = void 0;
        } else if (element.separator) {
          element.hidden = true;
        }
        if (!this.sortByLabel) {
          const previous = element.index && this.F[element.index - 1] || void 0;
          if (previous?.type === "separator" && !previous.buttons) {
            currentSeparator = previous;
          }
          if (currentSeparator && !element.hidden) {
            element.separator = currentSeparator;
            currentSeparator = void 0;
          }
        }
      });
    }
    this.jb(this.X && query ? this.H : this.G);
    this.z.layout();
    return true;
  }
  toggleCheckbox() {
    this.t.bufferEvents(() => {
      const elements = this.z.getFocus().filter((e) => e instanceof QuickPickItemElement);
      const allChecked = this.kb(elements);
      for (const element of elements) {
        if (!element.checkboxDisabled) {
          element.checked = !allChecked;
        }
      }
    });
  }
  style(styles) {
    this.z.style(styles);
  }
  toggleHover() {
    const focused = this.z.getFocus()[0];
    if (!focused?.saneTooltip || !(focused instanceof QuickPickItemElement)) {
      return;
    }
    if (this.J && !this.J.isDisposed) {
      this.J.dispose();
      return;
    }
    this.mb(focused);
    const store = new $2c();
    store.add(this.z.onDidChangeFocus((e) => {
      if (e.elements[0] instanceof QuickPickItemElement) {
        this.mb(e.elements[0]);
      }
    }));
    if (this.J) {
      store.add(this.J);
    }
    this.I.add(store);
  }
  //#endregion
  //#region private methods
  jb(elements) {
    const treeElements = new Array();
    for (const element of elements) {
      if (element instanceof QuickPickSeparatorElement) {
        treeElements.push({
          element,
          collapsible: false,
          collapsed: false,
          children: element.children.map((e) => ({
            element: e,
            collapsible: false,
            collapsed: false
          }))
        });
      } else {
        treeElements.push({
          element,
          collapsible: false,
          collapsed: false
        });
      }
    }
    this.z.setChildren(null, treeElements);
  }
  kb(elements, whenNoneVisible = true) {
    for (let i2 = 0, n = elements.length; i2 < n; i2++) {
      const element = elements[i2];
      if (!element.hidden) {
        if (!element.checked) {
          return false;
        } else {
          whenNoneVisible = true;
        }
      }
    }
    return whenNoneVisible;
  }
  lb() {
    $ce((tx) => {
      this.f.set(this.kb(this.H, false), tx);
      const checkedCount = this.H.filter((element) => element.checked).length;
      this.g.set(checkedCount, tx);
      this.h.set(this.getCheckedElements(), tx);
    });
  }
  /**
   * Disposes of the hover and shows a new one for the given index if it has a tooltip.
   * @param element The element to show the hover for
   */
  mb(element) {
    if (this.J && !this.J.isDisposed) {
      this.N.onDidHideHover?.();
      this.J?.dispose();
    }
    if (!element.element || !element.saneTooltip) {
      return;
    }
    this.J = this.N.showHover({
      content: element.saneTooltip,
      target: element.element,
      linkHandler: (url) => {
        this.O(url);
      },
      appearance: {
        showPointer: true
      },
      container: this.w,
      position: {
        hoverPosition: 1
        /* HoverPosition.RIGHT */
      }
    }, false);
  }
};
__decorate([
  $0t
], $9Wb.prototype, "onDidChangeFocus", null);
__decorate([
  $0t
], $9Wb.prototype, "onDidChangeSelection", null);
$9Wb = __decorate([
  __param(4, $Pk),
  __param(5, $ND)
], $9Wb);
function matchesContiguousIconAware(query, target) {
  const { text: text2, iconOffsets } = target;
  if (!iconOffsets || iconOffsets.length === 0) {
    return matchesContiguous(query, text2);
  }
  const wordToMatchAgainstWithoutIconsTrimmed = $Ff(text2, " ");
  const leadingWhitespaceOffset = text2.length - wordToMatchAgainstWithoutIconsTrimmed.length;
  const matches = matchesContiguous(query, wordToMatchAgainstWithoutIconsTrimmed);
  if (matches) {
    for (const match of matches) {
      const iconOffset = iconOffsets[match.start + leadingWhitespaceOffset] + leadingWhitespaceOffset;
      match.start += iconOffset;
      match.end += iconOffset;
    }
  }
  return matches;
}
function matchesContiguous(word, wordToMatchAgainst) {
  const matchIndex = wordToMatchAgainst.toLowerCase().indexOf(word.toLowerCase());
  if (matchIndex !== -1) {
    return [{ start: matchIndex, end: matchIndex + word.length }];
  }
  return null;
}
function compareEntries(elementA, elementB, lookFor) {
  const labelHighlightsA = elementA.labelHighlights || [];
  const labelHighlightsB = elementB.labelHighlights || [];
  if (labelHighlightsA.length && !labelHighlightsB.length) {
    return -1;
  }
  if (!labelHighlightsA.length && labelHighlightsB.length) {
    return 1;
  }
  if (labelHighlightsA.length === 0 && labelHighlightsB.length === 0) {
    return 0;
  }
  return $PM(elementA.saneSortLabel, elementB.saneSortLabel, lookFor);
}

// out-build/vs/platform/quickinput/browser/quickInputActions.js
var defaultCommandAndKeybindingRule = {
  weight: 200,
  when: $7m.and($7m.equals(
    $aXb,
    "quickPick"
    /* QuickInputType.QuickPick */
  ), $_Wb),
  metadata: { description: localize(2067, null) }
};
function registerQuickPickCommandAndKeybindingRule(rule, options3 = {}) {
  $0I.registerCommandAndKeybindingRule({
    ...defaultCommandAndKeybindingRule,
    ...rule,
    secondary: getSecondary(rule.primary, rule.secondary ?? [], options3)
  });
}
var ctrlKeyMod3 = $m ? 256 : 2048;
function getSecondary(primary, secondary, options3 = {}) {
  if (options3.withAltMod) {
    secondary.push(512 + primary);
  }
  if (options3.withCtrlMod) {
    secondary.push(ctrlKeyMod3 + primary);
    if (options3.withAltMod) {
      secondary.push(512 + ctrlKeyMod3 + primary);
    }
  }
  if (options3.withCmdMod && $m) {
    secondary.push(2048 + primary);
    if (options3.withCtrlMod) {
      secondary.push(2048 + 256 + primary);
    }
    if (options3.withAltMod) {
      secondary.push(2048 + 512 + primary);
      if (options3.withCtrlMod) {
        secondary.push(2048 + 512 + 256 + primary);
      }
    }
  }
  return secondary;
}
function focusHandler(focus, focusOnQuickNatigate) {
  return (accessor) => {
    const currentQuickPick = accessor.get($1M).currentQuickInput;
    if (!currentQuickPick) {
      return;
    }
    if (focusOnQuickNatigate && currentQuickPick.quickNavigate) {
      return currentQuickPick.focus(focusOnQuickNatigate);
    }
    return currentQuickPick.focus(focus);
  };
}
registerQuickPickCommandAndKeybindingRule({ id: "quickInput.pageNext", primary: 12, handler: focusHandler(QuickPickFocus.NextPage) }, { withAltMod: true, withCtrlMod: true, withCmdMod: true });
registerQuickPickCommandAndKeybindingRule({ id: "quickInput.pagePrevious", primary: 11, handler: focusHandler(QuickPickFocus.PreviousPage) }, { withAltMod: true, withCtrlMod: true, withCmdMod: true });
registerQuickPickCommandAndKeybindingRule({ id: "quickInput.first", primary: ctrlKeyMod3 + 14, handler: focusHandler(QuickPickFocus.First) }, { withAltMod: true, withCmdMod: true });
registerQuickPickCommandAndKeybindingRule({ id: "quickInput.last", primary: ctrlKeyMod3 + 13, handler: focusHandler(QuickPickFocus.Last) }, { withAltMod: true, withCmdMod: true });
registerQuickPickCommandAndKeybindingRule({ id: "quickInput.next", primary: 18, handler: focusHandler(QuickPickFocus.Next) }, { withCtrlMod: true });
registerQuickPickCommandAndKeybindingRule({ id: "quickInput.previous", primary: 16, handler: focusHandler(QuickPickFocus.Previous) }, { withCtrlMod: true });
var nextSeparatorFallbackDesc = localize(2068, null);
var prevSeparatorFallbackDesc = localize(2069, null);
if ($m) {
  registerQuickPickCommandAndKeybindingRule({
    id: "quickInput.nextSeparatorWithQuickAccessFallback",
    primary: 2048 + 18,
    handler: focusHandler(QuickPickFocus.NextSeparator, QuickPickFocus.Next),
    metadata: { description: nextSeparatorFallbackDesc }
  });
  registerQuickPickCommandAndKeybindingRule({
    id: "quickInput.nextSeparator",
    primary: 2048 + 512 + 18,
    // Since macOS has the cmd key as the primary modifier, we need to add this additional
    // keybinding to capture cmd+ctrl+upArrow
    secondary: [
      2048 + 256 + 18
      /* KeyCode.DownArrow */
    ],
    handler: focusHandler(QuickPickFocus.NextSeparator)
  }, { withCtrlMod: true });
  registerQuickPickCommandAndKeybindingRule({
    id: "quickInput.previousSeparatorWithQuickAccessFallback",
    primary: 2048 + 16,
    handler: focusHandler(QuickPickFocus.PreviousSeparator, QuickPickFocus.Previous),
    metadata: { description: prevSeparatorFallbackDesc }
  });
  registerQuickPickCommandAndKeybindingRule({
    id: "quickInput.previousSeparator",
    primary: 2048 + 512 + 16,
    // Since macOS has the cmd key as the primary modifier, we need to add this additional
    // keybinding to capture cmd+ctrl+upArrow
    secondary: [
      2048 + 256 + 16
      /* KeyCode.UpArrow */
    ],
    handler: focusHandler(QuickPickFocus.PreviousSeparator)
  }, { withCtrlMod: true });
} else {
  registerQuickPickCommandAndKeybindingRule({
    id: "quickInput.nextSeparatorWithQuickAccessFallback",
    primary: 512 + 18,
    handler: focusHandler(QuickPickFocus.NextSeparator, QuickPickFocus.Next),
    metadata: { description: nextSeparatorFallbackDesc }
  });
  registerQuickPickCommandAndKeybindingRule({
    id: "quickInput.nextSeparator",
    primary: 2048 + 512 + 18,
    handler: focusHandler(QuickPickFocus.NextSeparator)
  });
  registerQuickPickCommandAndKeybindingRule({
    id: "quickInput.previousSeparatorWithQuickAccessFallback",
    primary: 512 + 16,
    handler: focusHandler(QuickPickFocus.PreviousSeparator, QuickPickFocus.Previous),
    metadata: { description: prevSeparatorFallbackDesc }
  });
  registerQuickPickCommandAndKeybindingRule({
    id: "quickInput.previousSeparator",
    primary: 2048 + 512 + 16,
    handler: focusHandler(QuickPickFocus.PreviousSeparator)
  });
}
registerQuickPickCommandAndKeybindingRule({
  id: "quickInput.acceptInBackground",
  // If we are in the quick pick but the input box is not focused or our cursor is at the end of the input box
  when: $7m.and(defaultCommandAndKeybindingRule.when, $7m.or($Ceb.negate(), $eXb)),
  primary: 17,
  // Need a little extra weight to ensure this keybinding is preferred over the default cmd+alt+right arrow keybinding
  // https://github.com/microsoft/vscode/blob/1451e4fbbbf074a4355cc537c35b547b80ce1c52/src/vs/workbench/browser/parts/editor/editorActions.ts#L1178-L1195
  weight: 200 + 50,
  handler: (accessor) => {
    const currentQuickPick = accessor.get($1M).currentQuickInput;
    currentQuickPick?.accept(true);
  }
}, { withAltMod: true, withCtrlMod: true, withCmdMod: true });

// out-build/vs/platform/quickinput/browser/quickInputController.js
var $kXb_1;
var $113 = $;
var $kXb = class $kXb2 extends $3c {
  static {
    $kXb_1 = this;
  }
  static {
    this.a = 600;
  }
  // Max total width of quick input widget
  get currentQuickInput() {
    return this.t ?? void 0;
  }
  get container() {
    return this.u;
  }
  constructor(I, J, L, M) {
    super();
    this.I = I;
    this.J = J;
    this.L = L;
    this.M = M;
    this.j = true;
    this.m = this.B(new $ze());
    this.n = this.B(new $ze());
    this.r = this.B(new $ze());
    this.s = { ctrlCmd: false, alt: false };
    this.t = null;
    this.z = this.B(new $ze());
    this.onShow = this.z.event;
    this.C = this.B(new $ze());
    this.onHide = this.C.event;
    this.F = $$Wb.bindTo(this.M);
    this.G = $bXb.bindTo(this.M);
    this.H = $dXb.bindTo(this.M);
    this.backButton = $fXb;
    this.b = I.idPrefix;
    this.u = I.container;
    this.w = I.styles;
    this.B(Event2.runAndSubscribe(onDidRegisterWindow, ({ window: window3, disposables }) => this.N(window3, disposables), { window: $Y, disposables: this.q }));
    this.B(onWillUnregisterWindow((window3) => {
      if (this.f && getWindow(this.f.container) === window3) {
        this.Q(this.J.mainContainer);
        this.layout(this.J.mainContainerDimension, this.J.mainContainerOffset.quickPickTop);
      }
    }));
  }
  N(window3, disposables) {
    const listener = (e) => {
      this.s.ctrlCmd = e.ctrlKey || e.metaKey;
      this.s.alt = e.altKey;
    };
    for (const event of [$7j.KEY_DOWN, $7j.KEY_UP, $7j.MOUSE_DOWN]) {
      disposables.add($_i(window3, event, listener, true));
    }
  }
  P(showInActiveContainer) {
    if (this.f) {
      if (showInActiveContainer) {
        if (getWindow(this.u) !== getWindow(this.J.activeContainer)) {
          this.Q(this.J.activeContainer);
          this.layout(this.J.activeContainerDimension, this.J.activeContainerOffset.quickPickTop);
        }
      }
      return this.f;
    }
    const container2 = $bk(this.u, $113(".quick-input-widget.show-file-icons"));
    container2.tabIndex = -1;
    container2.style.display = "none";
    const styleSheet = $VZ(container2);
    const titleBar = $bk(container2, $113(".quick-input-titlebar"));
    const leftActionBar = this.B(new $LZ(titleBar, { hoverDelegate: this.I.hoverDelegate }));
    leftActionBar.domNode.classList.add("quick-input-left-action-bar");
    const title = $bk(titleBar, $113(".quick-input-title"));
    const rightActionBar = this.B(new $LZ(titleBar, { hoverDelegate: this.I.hoverDelegate }));
    rightActionBar.domNode.classList.add("quick-input-right-action-bar");
    const headerContainer = $bk(container2, $113(".quick-input-header"));
    const checkAll = $bk(headerContainer, $113("input.quick-input-check-all"));
    checkAll.type = "checkbox";
    checkAll.setAttribute("aria-label", localize(2070, null));
    this.B($aj(checkAll, $7j.CHANGE, (e) => {
      const checked = checkAll.checked;
      list2.setAllVisibleChecked(checked);
    }));
    this.B($_i(checkAll, $7j.CLICK, (e) => {
      if (e.x || e.y) {
        inputBox.setFocus();
      }
    }));
    const description2 = $bk(headerContainer, $113(".quick-input-description"));
    const inputContainer = $bk(headerContainer, $113(".quick-input-and-message"));
    const filterContainer = $bk(inputContainer, $113(".quick-input-filter"));
    const inputBox = this.B(new $6Wb(filterContainer, this.w.inputBox, this.w.toggle));
    inputBox.setAttribute("aria-describedby", `${this.b}message`);
    const visibleCountContainer = $bk(filterContainer, $113(".quick-input-visible-count"));
    visibleCountContainer.setAttribute("aria-live", "polite");
    visibleCountContainer.setAttribute("aria-atomic", "true");
    const visibleCount = this.B(new $D2(visibleCountContainer, { countFormat: localize(2071, null) }, this.w.countBadge));
    const countContainer = $bk(filterContainer, $113(".quick-input-count"));
    countContainer.setAttribute("aria-live", "polite");
    const count = this.B(new $D2(countContainer, { countFormat: localize(2072, null) }, this.w.countBadge));
    const inlineActionBar = this.B(new $LZ(headerContainer, { hoverDelegate: this.I.hoverDelegate }));
    inlineActionBar.domNode.classList.add("quick-input-inline-action-bar");
    const okContainer = $bk(headerContainer, $113(".quick-input-action"));
    const ok2 = this.B(new $k2(okContainer, this.w.button));
    ok2.label = localize(2073, null);
    this.B(ok2.onDidClick((e) => {
      this.m.fire();
    }));
    const customButtonContainer = $bk(headerContainer, $113(".quick-input-action"));
    const customButton = this.B(new $k2(customButtonContainer, { ...this.w.button, supportIcons: true }));
    customButton.label = localize(2074, null);
    this.B(customButton.onDidClick((e) => {
      this.n.fire();
    }));
    const message = $bk(inputContainer, $113(`#${this.b}message.quick-input-message`));
    const progressBar = this.B(new $02(container2, this.w.progressBar));
    progressBar.getContainer().classList.add("quick-input-progress");
    const widget = $bk(container2, $113(".quick-input-html-widget"));
    widget.tabIndex = -1;
    const description1 = $bk(container2, $113(".quick-input-description"));
    const listId = this.b + "list";
    const list2 = this.B(this.L.createInstance($9Wb, container2, this.I.hoverDelegate, this.I.linkOpenerDelegate, listId));
    inputBox.setAttribute("aria-controls", listId);
    this.B(list2.onDidChangeFocus(() => {
      inputBox.setAttribute("aria-activedescendant", list2.getActiveDescendant() ?? "");
    }));
    this.B(list2.onChangedAllVisibleChecked((checked) => {
      checkAll.checked = checked;
    }));
    this.B(list2.onChangedVisibleCount((c) => {
      visibleCount.setCount(c);
    }));
    this.B(list2.onChangedCheckedCount((c) => {
      count.setCount(c);
    }));
    this.B(list2.onLeave(() => {
      setTimeout(() => {
        if (!this.t) {
          return;
        }
        inputBox.setFocus();
        if (this.t instanceof $gXb && this.t.canSelectMany) {
          list2.clearFocus();
        }
      }, 0);
    }));
    const focusTracker = $_j(container2);
    this.B(focusTracker);
    this.B($_i(container2, $7j.FOCUS, (e) => {
      const ui = this.P();
      if ($Dj(e.relatedTarget, ui.inputContainer)) {
        const value = ui.inputBox.isSelectionAtEnd();
        if (this.H.get() !== value) {
          this.H.set(value);
        }
      }
      if ($Dj(e.relatedTarget, ui.container)) {
        return;
      }
      this.F.set(true);
      this.D = $Uj(e.relatedTarget) ? e.relatedTarget : void 0;
    }, true));
    this.B(focusTracker.onDidBlur(() => {
      if (!this.P().ignoreFocusOut && !this.I.ignoreFocusOut()) {
        this.hide(QuickInputHideReason.Blur);
      }
      this.F.set(false);
      this.H.set(false);
      this.D = void 0;
    }));
    this.B(inputBox.onKeyDown((_) => {
      const value = this.P().inputBox.isSelectionAtEnd();
      if (this.H.get() !== value) {
        this.H.set(value);
      }
    }));
    this.B($_i(container2, $7j.FOCUS, (e) => {
      inputBox.setFocus();
    }));
    this.B($aj(container2, $7j.KEY_DOWN, (event) => {
      if ($Dj(event.target, widget)) {
        return;
      }
      switch (event.keyCode) {
        case 3:
          $9j.stop(event, true);
          if (this.j) {
            this.m.fire();
          }
          break;
        case 9:
          $9j.stop(event, true);
          this.hide(QuickInputHideReason.Gesture);
          break;
        case 2:
          if (!event.altKey && !event.ctrlKey && !event.metaKey) {
            const selectors = [
              ".quick-input-list .monaco-action-bar .always-visible",
              ".quick-input-list-entry:hover .monaco-action-bar",
              ".monaco-list-row.focused .monaco-action-bar"
            ];
            if (container2.classList.contains("show-checkboxes")) {
              selectors.push("input");
            } else {
              selectors.push("input[type=text]");
            }
            if (this.P().list.displayed) {
              selectors.push(".monaco-list");
            }
            if (this.P().message) {
              selectors.push(".quick-input-message a");
            }
            if (this.P().widget) {
              if ($Dj(event.target, this.P().widget)) {
                break;
              }
              selectors.push(".quick-input-html-widget");
            }
            const stops = container2.querySelectorAll(selectors.join(", "));
            if (event.shiftKey && event.target === stops[0]) {
              $9j.stop(event, true);
              list2.clearFocus();
            } else if (!event.shiftKey && $Dj(event.target, stops[stops.length - 1])) {
              $9j.stop(event, true);
              stops[0].focus();
            }
          }
          break;
        case 10:
          if (event.ctrlKey) {
            $9j.stop(event, true);
            this.P().list.toggleHover();
          }
          break;
      }
    }));
    this.f = {
      container: container2,
      styleSheet,
      leftActionBar,
      titleBar,
      title,
      description1,
      description2,
      widget,
      rightActionBar,
      inlineActionBar,
      checkAll,
      inputContainer,
      filterContainer,
      inputBox,
      visibleCountContainer,
      visibleCount,
      countContainer,
      count,
      okContainer,
      ok: ok2,
      message,
      customButtonContainer,
      customButton,
      list: list2,
      progressBar,
      onDidAccept: this.m.event,
      onDidCustom: this.n.event,
      onDidTriggerButton: this.r.event,
      ignoreFocusOut: false,
      keyMods: this.s,
      show: (controller) => this.U(controller),
      hide: () => this.hide(),
      setVisibilities: (visibilities) => this.W(visibilities),
      setEnabled: (enabled) => this.X(enabled),
      setContextKey: (contextKey) => this.I.setContextKey(contextKey),
      linkOpenerDelegate: (content) => this.I.linkOpenerDelegate(content)
    };
    this.Z();
    return this.f;
  }
  Q(container2) {
    if (this.f) {
      this.u = container2;
      $bk(this.u, this.f.container);
    }
  }
  pick(picks, options3 = {}, token = CancellationToken.None) {
    return new Promise((doResolve, reject) => {
      let resolve = (result) => {
        resolve = doResolve;
        options3.onKeyMods?.(input.keyMods);
        doResolve(result);
      };
      if (token.isCancellationRequested) {
        resolve(void 0);
        return;
      }
      const input = this.createQuickPick({ useSeparators: true });
      let activeItem;
      const disposables = [
        input,
        input.onDidAccept(() => {
          if (input.canSelectMany) {
            resolve(input.selectedItems.slice());
            input.hide();
          } else {
            const result = input.activeItems[0];
            if (result) {
              resolve(result);
              input.hide();
            }
          }
        }),
        input.onDidChangeActive((items) => {
          const focused = items[0];
          if (focused && options3.onDidFocus) {
            options3.onDidFocus(focused);
          }
        }),
        input.onDidChangeSelection((items) => {
          if (!input.canSelectMany) {
            const result = items[0];
            if (result) {
              resolve(result);
              input.hide();
            }
          }
        }),
        input.onDidTriggerItemButton((event) => options3.onDidTriggerItemButton && options3.onDidTriggerItemButton({
          ...event,
          removeItem: () => {
            const index = input.items.indexOf(event.item);
            if (index !== -1) {
              const items = input.items.slice();
              const removed = items.splice(index, 1);
              const activeItems = input.activeItems.filter((activeItem2) => activeItem2 !== removed[0]);
              const keepScrollPositionBefore = input.keepScrollPosition;
              input.keepScrollPosition = true;
              input.items = items;
              if (activeItems) {
                input.activeItems = activeItems;
              }
              input.keepScrollPosition = keepScrollPositionBefore;
            }
          }
        })),
        input.onDidTriggerSeparatorButton((event) => options3.onDidTriggerSeparatorButton?.(event)),
        input.onDidChangeValue((value) => {
          if (activeItem && !value && (input.activeItems.length !== 1 || input.activeItems[0] !== activeItem)) {
            input.activeItems = [activeItem];
          }
        }),
        token.onCancellationRequested(() => {
          input.hide();
        }),
        input.onDidHide(() => {
          $Xc(disposables);
          resolve(void 0);
        })
      ];
      input.title = options3.title;
      if (options3.value) {
        input.value = options3.value;
      }
      input.canSelectMany = !!options3.canPickMany;
      input.placeholder = options3.placeHolder;
      input.ignoreFocusOut = !!options3.ignoreFocusLost;
      input.matchOnDescription = !!options3.matchOnDescription;
      input.matchOnDetail = !!options3.matchOnDetail;
      input.matchOnLabel = options3.matchOnLabel === void 0 || options3.matchOnLabel;
      input.quickNavigate = options3.quickNavigate;
      input.hideInput = !!options3.hideInput;
      input.contextKey = options3.contextKey;
      input.busy = true;
      Promise.all([picks, options3.activeItem]).then(([items, _activeItem]) => {
        activeItem = _activeItem;
        input.busy = false;
        input.items = items;
        if (input.canSelectMany) {
          input.selectedItems = items.filter((item) => item.type !== "separator" && item.picked);
        }
        if (activeItem) {
          input.activeItems = [activeItem];
        }
      });
      input.show();
      Promise.resolve(picks).then(void 0, (err) => {
        reject(err);
        input.hide();
      });
    });
  }
  S(input, validationResult) {
    if (validationResult && $zg(validationResult)) {
      input.severity = severity_default.Error;
      input.validationMessage = validationResult;
    } else if (validationResult && !$zg(validationResult)) {
      input.severity = validationResult.severity;
      input.validationMessage = validationResult.content;
    } else {
      input.severity = severity_default.Ignore;
      input.validationMessage = void 0;
    }
  }
  input(options3 = {}, token = CancellationToken.None) {
    return new Promise((resolve) => {
      if (token.isCancellationRequested) {
        resolve(void 0);
        return;
      }
      const input = this.createInputBox();
      const validateInput = options3.validateInput || (() => Promise.resolve(void 0));
      const onDidValueChange = Event2.debounce(input.onDidChangeValue, (last, cur) => cur, 100);
      let validationValue = options3.value || "";
      let validation = Promise.resolve(validateInput(validationValue));
      const disposables = [
        input,
        onDidValueChange((value) => {
          if (value !== validationValue) {
            validation = Promise.resolve(validateInput(value));
            validationValue = value;
          }
          validation.then((result) => {
            if (value === validationValue) {
              this.S(input, result);
            }
          });
        }),
        input.onDidAccept(() => {
          const value = input.value;
          if (value !== validationValue) {
            validation = Promise.resolve(validateInput(value));
            validationValue = value;
          }
          validation.then((result) => {
            if (!result || !$zg(result) && result.severity !== severity_default.Error) {
              resolve(value);
              input.hide();
            } else if (value === validationValue) {
              this.S(input, result);
            }
          });
        }),
        token.onCancellationRequested(() => {
          input.hide();
        }),
        input.onDidHide(() => {
          $Xc(disposables);
          resolve(void 0);
        })
      ];
      input.title = options3.title;
      input.value = options3.value || "";
      input.valueSelection = options3.valueSelection;
      input.prompt = options3.prompt;
      input.placeholder = options3.placeHolder;
      input.password = !!options3.password;
      input.ignoreFocusOut = !!options3.ignoreFocusLost;
      input.show();
    });
  }
  createQuickPick(options3 = { useSeparators: false }) {
    const ui = this.P(true);
    return new $gXb(ui);
  }
  createInputBox() {
    const ui = this.P(true);
    return new $hXb(ui);
  }
  createQuickWidget() {
    const ui = this.P(true);
    return new $iXb(ui);
  }
  U(controller) {
    const ui = this.P(true);
    this.z.fire();
    const oldController = this.t;
    this.t = controller;
    oldController?.didHide();
    this.X(true);
    ui.leftActionBar.clear();
    ui.title.textContent = "";
    ui.description1.textContent = "";
    ui.description2.textContent = "";
    $dk(ui.widget);
    ui.rightActionBar.clear();
    ui.inlineActionBar.clear();
    ui.checkAll.checked = false;
    ui.inputBox.placeholder = "";
    ui.inputBox.password = false;
    ui.inputBox.showDecoration(severity_default.Ignore);
    ui.visibleCount.setCount(0);
    ui.count.setCount(0);
    $dk(ui.message);
    ui.progressBar.stop();
    ui.list.setElements([]);
    ui.list.matchOnDescription = false;
    ui.list.matchOnDetail = false;
    ui.list.matchOnLabel = true;
    ui.list.sortByLabel = true;
    ui.ignoreFocusOut = false;
    ui.inputBox.toggles = void 0;
    const backKeybindingLabel = this.I.backKeybindingLabel();
    $fXb.tooltip = backKeybindingLabel ? localize(2075, null, backKeybindingLabel) : localize(2076, null);
    ui.container.style.display = "";
    this.Y();
    ui.inputBox.setFocus();
    this.G.set(controller.type);
  }
  isVisible() {
    return !!this.f && this.f.container.style.display !== "none";
  }
  W(visibilities) {
    const ui = this.P();
    ui.title.style.display = visibilities.title ? "" : "none";
    ui.description1.style.display = visibilities.description && (visibilities.inputBox || visibilities.checkAll) ? "" : "none";
    ui.description2.style.display = visibilities.description && !(visibilities.inputBox || visibilities.checkAll) ? "" : "none";
    ui.checkAll.style.display = visibilities.checkAll ? "" : "none";
    ui.inputContainer.style.display = visibilities.inputBox ? "" : "none";
    ui.filterContainer.style.display = visibilities.inputBox ? "" : "none";
    ui.visibleCountContainer.style.display = visibilities.visibleCount ? "" : "none";
    ui.countContainer.style.display = visibilities.count ? "" : "none";
    ui.okContainer.style.display = visibilities.ok ? "" : "none";
    ui.customButtonContainer.style.display = visibilities.customButton ? "" : "none";
    ui.message.style.display = visibilities.message ? "" : "none";
    ui.progressBar.getContainer().style.display = visibilities.progressBar ? "" : "none";
    ui.list.displayed = !!visibilities.list;
    ui.container.classList.toggle("show-checkboxes", !!visibilities.checkBox);
    ui.container.classList.toggle("hidden-input", !visibilities.inputBox && !visibilities.description);
    this.Y();
  }
  X(enabled) {
    if (enabled !== this.j) {
      this.j = enabled;
      for (const item of this.P().leftActionBar.viewItems) {
        item.action.enabled = enabled;
      }
      for (const item of this.P().rightActionBar.viewItems) {
        item.action.enabled = enabled;
      }
      this.P().checkAll.disabled = !enabled;
      this.P().inputBox.enabled = enabled;
      this.P().ok.enabled = enabled;
      this.P().list.enabled = enabled;
    }
  }
  hide(reason) {
    const controller = this.t;
    if (!controller) {
      return;
    }
    controller.willHide(reason);
    const container2 = this.f?.container;
    const focusChanged = container2 && !$Nj(container2);
    this.t = null;
    this.C.fire();
    if (container2) {
      container2.style.display = "none";
    }
    if (!focusChanged) {
      let currentElement = this.D;
      while (currentElement && !currentElement.offsetParent) {
        currentElement = currentElement.parentElement ?? void 0;
      }
      if (currentElement?.offsetParent) {
        currentElement.focus();
        this.D = void 0;
      } else {
        this.I.returnFocus();
      }
    }
    controller.didHide(reason);
  }
  focus() {
    if (this.isVisible()) {
      const ui = this.P();
      if (ui.inputBox.enabled) {
        ui.inputBox.setFocus();
      } else {
        ui.list.domFocus();
      }
    }
  }
  toggle() {
    if (this.isVisible() && this.t instanceof $gXb && this.t.canSelectMany) {
      this.P().list.toggleCheckbox();
    }
  }
  navigate(next, quickNavigate) {
    if (this.isVisible() && this.P().list.displayed) {
      this.P().list.focus(next ? QuickPickFocus.Next : QuickPickFocus.Previous);
      if (quickNavigate && this.t instanceof $gXb) {
        this.t.quickNavigate = quickNavigate;
      }
    }
  }
  async accept(keyMods = { alt: false, ctrlCmd: false }) {
    this.s.alt = keyMods.alt;
    this.s.ctrlCmd = keyMods.ctrlCmd;
    this.m.fire();
  }
  async back() {
    this.r.fire(this.backButton);
  }
  async cancel() {
    this.hide();
  }
  layout(dimension, titleBarOffset) {
    this.g = dimension;
    this.h = titleBarOffset;
    this.Y();
  }
  Y() {
    if (this.f && this.isVisible()) {
      this.f.container.style.top = `${this.h}px`;
      const style = this.f.container.style;
      const width2 = Math.min(this.g.width * 0.62, $kXb_1.a);
      style.width = width2 + "px";
      style.marginLeft = "-" + width2 / 2 + "px";
      this.f.inputBox.layout();
      this.f.list.layout(this.g && this.g.height * 0.4);
    }
  }
  applyStyles(styles) {
    this.w = styles;
    this.Z();
  }
  Z() {
    if (this.f) {
      const { quickInputTitleBackground, quickInputBackground, quickInputForeground, widgetBorder, widgetShadow } = this.w.widget;
      this.f.titleBar.style.backgroundColor = quickInputTitleBackground ?? "";
      this.f.container.style.backgroundColor = quickInputBackground ?? "";
      this.f.container.style.color = quickInputForeground ?? "";
      this.f.container.style.border = widgetBorder ? `1px solid ${widgetBorder}` : "";
      this.f.container.style.boxShadow = widgetShadow ? `0 0 8px 2px ${widgetShadow}` : "";
      this.f.list.style(this.w.list);
      const content = [];
      if (this.w.pickerGroup.pickerGroupBorder) {
        content.push(`.quick-input-list .quick-input-list-entry { border-top-color:  ${this.w.pickerGroup.pickerGroupBorder}; }`);
      }
      if (this.w.pickerGroup.pickerGroupForeground) {
        content.push(`.quick-input-list .quick-input-list-separator { color:  ${this.w.pickerGroup.pickerGroupForeground}; }`);
      }
      if (this.w.pickerGroup.pickerGroupForeground) {
        content.push(`.quick-input-list .quick-input-list-separator-as-item { color: var(--vscode-descriptionForeground); }`);
      }
      if (this.w.keybindingLabel.keybindingLabelBackground || this.w.keybindingLabel.keybindingLabelBorder || this.w.keybindingLabel.keybindingLabelBottomBorder || this.w.keybindingLabel.keybindingLabelShadow || this.w.keybindingLabel.keybindingLabelForeground) {
        content.push(".quick-input-list .monaco-keybinding > .monaco-keybinding-key {");
        if (this.w.keybindingLabel.keybindingLabelBackground) {
          content.push(`background-color: ${this.w.keybindingLabel.keybindingLabelBackground};`);
        }
        if (this.w.keybindingLabel.keybindingLabelBorder) {
          content.push(`border-color: ${this.w.keybindingLabel.keybindingLabelBorder};`);
        }
        if (this.w.keybindingLabel.keybindingLabelBottomBorder) {
          content.push(`border-bottom-color: ${this.w.keybindingLabel.keybindingLabelBottomBorder};`);
        }
        if (this.w.keybindingLabel.keybindingLabelShadow) {
          content.push(`box-shadow: inset 0 -1px 0 ${this.w.keybindingLabel.keybindingLabelShadow};`);
        }
        if (this.w.keybindingLabel.keybindingLabelForeground) {
          content.push(`color: ${this.w.keybindingLabel.keybindingLabelForeground};`);
        }
        content.push("}");
      }
      const newStyles = content.join("\n");
      if (newStyles !== this.f.styleSheet.textContent) {
        this.f.styleSheet.textContent = newStyles;
      }
    }
  }
};
$kXb = $kXb_1 = __decorate([
  __param(1, $Ulb),
  __param(2, $Pk),
  __param(3, $on)
], $kXb);

// out-build/vs/platform/quickinput/browser/quickInputService.js
var $mXb = class $mXb2 extends $ns {
  get backButton() {
    return this.f.backButton;
  }
  get f() {
    if (!this.c) {
      this.c = this.B(this.y());
    }
    return this.c;
  }
  get g() {
    return !!this.c;
  }
  get currentQuickInput() {
    return this.f.currentQuickInput;
  }
  get quickAccess() {
    if (!this.j) {
      this.j = this.B(this.r.createInstance($lXb));
    }
    return this.j;
  }
  constructor(r2, s, themeService, t, u) {
    super(themeService);
    this.r = r2;
    this.s = s;
    this.t = t;
    this.u = u;
    this.a = this.B(new $ze());
    this.onShow = this.a.event;
    this.b = this.B(new $ze());
    this.onHide = this.b.event;
    this.m = /* @__PURE__ */ new Map();
  }
  y(host = this.t, options3) {
    const defaultOptions4 = {
      idPrefix: "quickInput_",
      container: host.activeContainer,
      ignoreFocusOut: () => false,
      backKeybindingLabel: () => void 0,
      setContextKey: (id2) => this.C(id2),
      linkOpenerDelegate: (content) => {
        this.r.invokeFunction((accessor) => {
          const openerService = accessor.get($O4);
          openerService.open(content, { allowCommands: true, fromUserGesture: true });
        });
      },
      returnFocus: () => host.focus(),
      styles: this.F(),
      hoverDelegate: this.B(this.r.createInstance($jXb))
    };
    const controller = this.B(this.r.createInstance($kXb, {
      ...defaultOptions4,
      ...options3
    }));
    controller.layout(host.activeContainerDimension, host.activeContainerOffset.quickPickTop);
    this.B(host.onDidLayoutActiveContainer((dimension) => {
      if (getWindow(host.activeContainer) === getWindow(controller.container)) {
        controller.layout(dimension, host.activeContainerOffset.quickPickTop);
      }
    }));
    this.B(host.onDidChangeActiveContainer(() => {
      if (controller.isVisible()) {
        return;
      }
      controller.layout(host.activeContainerDimension, host.activeContainerOffset.quickPickTop);
    }));
    this.B(controller.onShow(() => {
      this.D();
      this.a.fire();
    }));
    this.B(controller.onHide(() => {
      this.D();
      this.b.fire();
    }));
    return controller;
  }
  C(id2) {
    let key2;
    if (id2) {
      key2 = this.m.get(id2);
      if (!key2) {
        key2 = new $nn(id2, false).bindTo(this.s);
        this.m.set(id2, key2);
      }
    }
    if (key2 && key2.get()) {
      return;
    }
    this.D();
    key2?.set(true);
  }
  D() {
    this.m.forEach((context) => {
      if (context.get()) {
        context.reset();
      }
    });
  }
  pick(picks, options3, token = CancellationToken.None) {
    return this.f.pick(picks, options3, token);
  }
  input(options3 = {}, token = CancellationToken.None) {
    return this.f.input(options3, token);
  }
  createQuickPick(options3 = { useSeparators: false }) {
    return this.f.createQuickPick(options3);
  }
  createInputBox() {
    return this.f.createInputBox();
  }
  createQuickWidget() {
    return this.f.createQuickWidget();
  }
  focus() {
    this.f.focus();
  }
  toggle() {
    this.f.toggle();
  }
  navigate(next, quickNavigate) {
    this.f.navigate(next, quickNavigate);
  }
  accept(keyMods) {
    return this.f.accept(keyMods);
  }
  back() {
    return this.f.back();
  }
  cancel() {
    return this.f.cancel();
  }
  updateStyles() {
    if (this.g) {
      this.f.applyStyles(this.F());
    }
  }
  F() {
    return {
      widget: {
        quickInputBackground: $Zn($Vr),
        quickInputForeground: $Zn($Wr),
        quickInputTitleBackground: $Zn($Xr),
        widgetBorder: $Zn($Sp),
        widgetShadow: $Zn($Rp)
      },
      inputBox: $B$,
      toggle: $u$,
      countBadge: $E$,
      button: $q$,
      progressBar: $s$,
      keybindingLabel: $o$,
      list: $J$({
        listBackground: $Vr,
        listFocusBackground: $4r,
        listFocusForeground: $2r,
        // Look like focused when inactive.
        listInactiveFocusForeground: $2r,
        listInactiveSelectionIconForeground: $3r,
        listInactiveFocusBackground: $4r,
        listFocusOutline: $lo,
        listInactiveFocusOutline: $lo
      }),
      pickerGroup: {
        pickerGroupBorder: $Zn($Zr),
        pickerGroupForeground: $Zn($Yr)
      }
    };
  }
};
$mXb = __decorate([
  __param(0, $Pk),
  __param(1, $on),
  __param(2, $gs),
  __param(3, $Ulb),
  __param(4, $kl)
], $mXb);

// out-build/vs/workbench/services/quickinput/browser/quickInputService.js
var $nXb = class $nXb2 extends $mXb {
  constructor(configurationService, instantiationService, H, contextKeyService, themeService, layoutService) {
    super(instantiationService, contextKeyService, themeService, layoutService, configurationService);
    this.H = H;
    this.G = $5yb.bindTo(this.s);
    this.I();
  }
  I() {
    this.B(this.onShow(() => this.G.set(true)));
    this.B(this.onHide(() => this.G.set(false)));
  }
  y() {
    return super.y(this.t, {
      ignoreFocusOut: () => !this.u.getValue("workbench.quickOpen.closeOnFocusLost"),
      backKeybindingLabel: () => this.H.lookupKeybinding("workbench.action.quickInputBack")?.getLabel() || void 0
    });
  }
};
$nXb = __decorate([
  __param(0, $kl),
  __param(1, $Pk),
  __param(2, $Ty),
  __param(3, $on),
  __param(4, $gs),
  __param(5, $Ulb)
], $nXb);
$SC(
  $1M,
  $nXb,
  1
  /* InstantiationType.Delayed */
);

// out-build/vs/workbench/services/userDataSync/common/userDataSync.js
var $oXb = $Qk("IUserDataSyncWorkbenchService");
function $pXb(source) {
  switch (source) {
    case "settings":
      return localize(13452, null);
    case "keybindings":
      return localize(13453, null);
    case "snippets":
      return localize(13454, null);
    case "tasks":
      return localize(13455, null);
    case "extensions":
      return localize(13456, null);
    case "globalState":
      return localize(13457, null);
    case "profiles":
      return localize(13458, null);
    case "workspaceState":
      return localize(13459, null);
  }
}
var AccountStatus;
(function(AccountStatus2) {
  AccountStatus2["Uninitialized"] = "uninitialized";
  AccountStatus2["Unavailable"] = "unavailable";
  AccountStatus2["Available"] = "available";
})(AccountStatus || (AccountStatus = {}));
var $qXb = localize2(13461, "Settings Sync");
var $rXb = $9r("settings-sync-view-icon", $6l.sync, localize(13460, null));
var $sXb = new $nn(
  "syncStatus",
  "uninitialized"
  /* SyncStatus.Uninitialized */
);
var $tXb = new $nn("syncEnabled", false);
var $uXb = new $nn(
  "userDataSyncAccountStatus",
  "uninitialized"
  /* AccountStatus.Uninitialized */
);
var $vXb = new $nn(`enableSyncActivityViews`, false);
var $wXb = new $nn(`enableSyncConflictsView`, false);
var $xXb = new $nn("hasConflicts", false);
var $yXb = "workbench.userDataSync.actions.configure";
var $zXb = "workbench.userDataSync.actions.showLog";
var $AXb = "workbench.view.sync";
var $BXb = "workbench.views.sync.conflicts";
var $CXb = {
  id: "workbench.userDataSync.actions.downloadSyncActivity",
  title: localize2(13462, "Download Settings Sync Activity"),
  category: $qn.Developer,
  f1: true,
  precondition: $7m.and($uXb.isEqualTo(
    "available"
    /* AccountStatus.Available */
  ), $sXb.notEqualsTo(
    "uninitialized"
    /* SyncStatus.Uninitialized */
  ))
};

// 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 $DXb = class $DXb2 extends $3c {
  get userDataSyncStore() {
    return this.b;
  }
  get c() {
    return this.h.get(
      $4Bb,
      -1
      /* StorageScope.APPLICATION */
    );
  }
  set c(type) {
    this.h.store(
      $4Bb,
      type,
      -1,
      $r ? 0 : 1
      /* StorageTarget.MACHINE */
    );
  }
  constructor(f, g, h3) {
    super();
    this.f = f;
    this.g = g;
    this.h = h3;
    this.a = this.B(new $ze());
    this.onDidChangeUserDataSyncStore = this.a.event;
    this.j();
    const disposable = this.B(new $2c());
    this.B(Event2.filter(h3.onDidChangeValue(-1, $4Bb, 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 ($zg(configurationSyncStore.url) && $Bg(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 type = (canSwitch ? this.c : void 0) || defaultType;
      const url = type === "insiders" ? syncStore.insidersUrl : type === "stable" ? syncStore.stableUrl : syncStore.url;
      return {
        url: URI.parse(url),
        type,
        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;
  }
};
$DXb = __decorate([
  __param(0, $Vu),
  __param(1, $kl),
  __param(2, $jv)
], $DXb);
var $EXb = class $EXb2 extends $DXb {
  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(type) {
    if (type !== this.c) {
      this.c = type;
      this.j();
    }
  }
  async getPreviousUserDataSyncStore() {
    return this.m(this.n);
  }
};
$EXb = __decorate([
  __param(0, $Vu),
  __param(1, $kl),
  __param(2, $jv)
], $EXb);
var $FXb = class $FXb2 extends $3c {
  get donotMakeRequestsUntil() {
    return this.j;
  }
  constructor(userDataSyncStoreUrl, productService, n, r2, environmentService, fileService, s) {
    super();
    this.n = n;
    this.r = r2;
    this.s = s;
    this.g = this.B(new $ze());
    this.onTokenFailed = this.g.event;
    this.h = this.B(new $ze());
    this.onTokenSucceed = this.h.event;
    this.j = void 0;
    this.m = this.B(new $ze());
    this.onDidChangeDonotMakeRequestsUntil = this.m.event;
    this.w = void 0;
    this.t(userDataSyncStoreUrl);
    this.c = $7v(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 $HXb(REQUEST_SESSION_LIMIT, REQUEST_SESSION_INTERVAL, this.n, this.r);
    this.u();
    this.B($1c(() => {
      if (this.w) {
        this.w.cancel();
        this.w = void 0;
      }
    }));
  }
  setAuthToken(token, type) {
    this.b = { token, type };
  }
  t(userDataSyncStoreUrl) {
    this.a = userDataSyncStoreUrl ? $vh(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 = $Hh((token) => $Wh(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 = $vh(this.a, "collection").toString();
    headers = { ...headers };
    headers["Content-Type"] = "application/json";
    const context = await this.D(url, { type: "GET", headers }, [], CancellationToken.None);
    return (await $cv(context))?.map(({ id: id2 }) => id2) || [];
  }
  async createCollection(headers = {}) {
    if (!this.a) {
      throw new Error("No settings sync store url configured.");
    }
    const url = $vh(this.a, "collection").toString();
    headers = { ...headers };
    headers["Content-Type"] = $YC.text;
    const context = await this.D(url, { type: "POST", headers }, [], CancellationToken.None);
    const collectionId = await $bv(context);
    if (!collectionId) {
      throw new $2Bb("Server did not return the collection id", url, "NoCollection", context.res.statusCode, context.res.headers[$XBb]);
    }
    return collectionId;
  }
  async deleteCollection(collection, headers = {}) {
    if (!this.a) {
      throw new Error("No settings sync store url configured.");
    }
    const url = collection ? $vh(this.a, "collection", collection).toString() : $vh(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 $cv(context) || [];
    return result.map(({ url, created: created2 }) => ({
      ref: $xh(uri, uri.with({ path: url })),
      created: created2 * 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 = $vh(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 $bv(context);
    return content;
  }
  async deleteResource(resource, ref, collection) {
    if (!this.a) {
      throw new Error("No settings sync store url configured.");
    }
    const url = ref !== null ? $vh(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 = $vh(this.a, "resource").toString();
    const headers = { "Content-Type": $YC.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 = $vh(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 $2Bb("Server did not return the ref", url, "NoRef", context.res.statusCode, context.res.headers[$XBb]);
      }
      const content = await $bv(context);
      if (!content && context.res.statusCode === 304) {
        throw new $2Bb("Empty response", url, "EmptyResponse", context.res.statusCode, context.res.headers[$XBb]);
      }
      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"] = $YC.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 $2Bb("Server did not return the ref", url, "NoRef", context.res.statusCode, context.res.headers[$XBb]);
    }
    return newRef;
  }
  // #endregion
  async manifest(oldValue, headers = {}) {
    if (!this.a) {
      throw new Error("No settings sync store url configured.");
    }
    const url = $vh(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 $2Bb("Server did not return the ref", url, "NoRef", context.res.statusCode, context.res.headers[$XBb]);
      }
      const content = await $bv(context);
      if (!content && context.res.statusCode === 304) {
        throw new $2Bb("Empty response", url, "EmptyResponse", context.res.statusCode, context.res.headers[$XBb]);
      }
      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 = $vh(this.a, "download").toString();
    const headers = {};
    const context = await this.D(url, { type: "GET", headers }, [], CancellationToken.None);
    if (!$$u(context)) {
      throw new $2Bb("Server returned " + context.res.statusCode, url, "EmptyResponse", context.res.statusCode, context.res.headers[$XBb]);
    }
    if ($_u(context)) {
      throw new $2Bb("Empty response", url, "EmptyResponse", context.res.statusCode, context.res.headers[$XBb]);
    }
    return context.stream;
  }
  z(userDataSyncStoreUrl, collection, resource) {
    return collection ? $vh(userDataSyncStoreUrl, "collection", collection, "resource", resource) : $vh(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, options3, successCodes, token) {
    if (!this.b) {
      throw new $2Bb("No Auth Token Available", url, "Unauthorized", void 0, void 0);
    }
    if (this.j && Date.now() < this.j.getTime()) {
      throw new $2Bb(`${options3.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;
    options3.headers = {
      ...options3.headers || {},
      ...commonHeaders,
      "X-Account-Type": this.b.type,
      "authorization": `Bearer ${this.b.token}`
    };
    this.F(options3.headers);
    this.r.trace("Sending request to server", { url, type: options3.type, headers: { ...options3.headers, ...{ authorization: void 0 } } });
    let context;
    try {
      context = await this.f.request(url, options3, token);
    } catch (e) {
      if (!(e instanceof $2Bb)) {
        let code = "RequestFailed";
        const errorMessage = $qb(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 ($kb(e)) {
          code = "RequestCanceled";
        }
        e = new $2Bb(`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[$XBb];
    const requestInfo = { url, status: context.res.statusCode, "execution-id": options3.headers[$YBb], "operation-id": operationId };
    const isSuccess = $$u(context) || context.res.statusCode && successCodes.includes(context.res.statusCode);
    let failureMessage = "";
    if (isSuccess) {
      this.r.trace("Request succeeded", requestInfo);
    } else {
      failureMessage = await $av(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 $2Bb(`${options3.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 $2Bb(`${options3.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 $2Bb(`${options3.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 $2Bb(`${options3.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 $2Bb(`${options3.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 $2Bb(`${options3.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 $2Bb(`${options3.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 $2Bb(`${options3.type} request '${url}' failed because of too large payload (413).`, url, "TooLarge", context.res.statusCode, operationId);
    }
    if (context.res.statusCode === 426) {
      throw new $2Bb(`${options3.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 $2Bb(`${options3.type} request '${url}' failed because of too many requests (429).`, url, "TooManyRequestsAndRetryAfter", context.res.statusCode, operationId);
      } else {
        throw new $2Bb(`${options3.type} request '${url}' failed because of too many requests (429).`, url, "RemoteTooManyRequests", context.res.statusCode, operationId);
      }
    }
    if (!isSuccess) {
      throw new $2Bb("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 = $ps();
      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;
    }
  }
};
$FXb = __decorate([
  __param(1, $Vu),
  __param(2, $9u),
  __param(3, $$Bb),
  __param(4, $Xk),
  __param(5, $km),
  __param(6, $jv)
], $FXb);
var $GXb = class $GXb2 extends $FXb {
  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)));
  }
};
$GXb = __decorate([
  __param(0, $UBb),
  __param(1, $Vu),
  __param(2, $9u),
  __param(3, $$Bb),
  __param(4, $Xk),
  __param(5, $km),
  __param(6, $jv)
], $GXb);
var $HXb = 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, options3, token) {
    if (this.h()) {
      this.i();
    }
    options3.url = url;
    if (this.a.length >= this.c) {
      this.g.info("Too many requests", ...this.a);
      throw new $2Bb(`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(options3, 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/abstractSynchronizer.js
function $IXb(thing) {
  if (thing && (thing.ref !== void 0 && typeof thing.ref === "string" && thing.ref !== "") && (thing.syncData !== void 0 && (thing.syncData === null || $JXb(thing.syncData)))) {
    return true;
  }
  return false;
}
function $JXb(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 $KXb(syncResource, profile) {
  return `${$rg(syncResource)}${profile.isDefault ? "" : ` (${profile.name})`}`;
}
var $LXb = class $LXb2 extends $3c {
  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 $ze());
    this.onDidChangeStatus = this.n.event;
    this.s = [];
    this.t = this.B(new $ze());
    this.onDidChangeConflicts = this.t.event;
    this.u = this.B(new $Th(50));
    this.w = this.B(new $ze());
    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 = $KXb(syncResource.syncResource, syncResource.profile);
    this.h = uriIdentityService.extUri;
    this.f = this.h.joinPath(H.userDataSyncHome, ...$SBb(syncResource.profile.isDefault ? void 0 : syncResource.profile.id, syncResource.syncResource));
    this.g = this.h.joinPath(this.f, $bCb);
    this.y = $TBb(syncResource.profile.isDefault ? void 0 : syncResource.profile.id, syncResource.syncResource, H, this.h);
    this.j = $7v(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, apply2, 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, apply2, 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, apply2, userDataSyncConfiguration) {
    if (remoteUserData.syncData && remoteUserData.syncData.version > this.pb) {
      this.N.publicLog2("sync/incompatible", { source: this.resource });
      throw new $1Bb(localize(2490, null, this.resource, this.pb, remoteUserData.syncData.version), "IncompatibleLocalContent", this.resource);
    }
    try {
      return await this.Z(remoteUserData, lastSyncUserData, apply2, userDataSyncConfiguration);
    } catch (e) {
      if (e instanceof $1Bb) {
        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, apply2, 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, apply2, userDataSyncConfiguration);
        }
      }
      throw e;
    }
  }
  async Z(remoteUserData, lastSyncUserData, apply2, userDataSyncConfiguration) {
    try {
      const isRemoteDataFromCurrentMachine = await this.W(remoteUserData);
      const acceptRemote = !isRemoteDataFromCurrentMachine && lastSyncUserData === null && this.gb() !== void 0;
      const merge2 = apply2 && !acceptRemote;
      if (!this.c) {
        this.c = $Hh((token) => this.eb(remoteUserData, lastSyncUserData, isRemoteDataFromCurrentMachine, merge2, userDataSyncConfiguration, token));
      }
      let preview = await this.c;
      if (apply2 && 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 (apply2) {
        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, $Ci.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, $Ci.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 = $Hh(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 (!$zb(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 ($Bm(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: $aCb, 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, $Ci.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 $Fm && error.fileOperationResult === 1) {
          this.O.info(`${this.D}: Last sync resource does not exist locally.`);
          break;
        } else if (error instanceof $1Bb) {
          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 $1Bb && 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 version2 = this.M.getResourceSyncStateVersion(this.resource);
    const lastSyncUserDataState = {
      ref: lastSyncRemoteUserData.ref,
      version: version2,
      ...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 ($IXb(lastSyncStoredRemoteUserData)) {
        return lastSyncStoredRemoteUserData;
      }
    } catch (e) {
      this.O.error(e);
    }
    return void 0;
  }
  async ib(lastSyncRemoteUserData) {
    await this.G.writeFile(this.y, $Ci.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 $Fm && 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 ($JXb(syncData)) {
        return syncData;
      }
    } catch (error) {
      this.O.error(error);
    }
    throw new $1Bb(localize(2491, 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 $1Bb && error.code === "TooLarge") {
        error = new $1Bb(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($NBb);
  }
};
$LXb = __decorate([
  __param(2, $km),
  __param(3, $Xk),
  __param(4, $jv),
  __param(5, $VBb),
  __param(6, $WBb),
  __param(7, $6Bb),
  __param(8, $zv),
  __param(9, $$Bb),
  __param(10, $kl),
  __param(11, $vl)
], $LXb);
var $MXb = class $MXb2 extends $LXb {
  constructor(r2, 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 = r2;
    this.B(this.G.watch(this.h.dirname(r2)));
    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, $Ci.fromString(newContent), force ? void 0 : oldContent);
      } else {
        await this.G.createFile(this.r, $Ci.fromString(newContent), { overwrite: force });
      }
    } catch (e) {
      if (e instanceof $Fm && e.fileOperationResult === 1 || e instanceof $Fm && e.fileOperationResult === 3) {
        throw new $1Bb(
          e.message,
          "LocalPreconditionFailed"
          /* UserDataSyncErrorCode.LocalPreconditionFailed */
        );
      } else {
        throw e;
      }
    }
  }
  async xb() {
    try {
      await this.G.del(this.r);
    } catch (e) {
      if (!(e instanceof $Fm && e.fileOperationResult === 1)) {
        throw e;
      }
    }
  }
  yb(e) {
    if (!e.contains(this.r)) {
      return;
    }
    this.Q();
  }
};
$MXb = __decorate([
  __param(3, $km),
  __param(4, $Xk),
  __param(5, $jv),
  __param(6, $VBb),
  __param(7, $WBb),
  __param(8, $6Bb),
  __param(9, $zv),
  __param(10, $$Bb),
  __param(11, $kl),
  __param(12, $vl)
], $MXb);
var $NXb = class $NXb2 extends $MXb {
  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 = $yw(content, parseErrors, { allowEmptyContent: true, allowTrailingComma: true });
    return parseErrors.length > 0 || !$Gg(result) && isArray !== Array.isArray(result);
  }
  Cb() {
    if (!this.Bb) {
      this.Bb = this.zb.resolveFormattingOptions(this.r);
    }
    return this.Bb;
  }
};
$NXb = __decorate([
  __param(3, $km),
  __param(4, $Xk),
  __param(5, $jv),
  __param(6, $VBb),
  __param(7, $WBb),
  __param(8, $6Bb),
  __param(9, $zv),
  __param(10, $$Bb),
  __param(11, $0Bb),
  __param(12, $kl),
  __param(13, $vl)
], $NXb);
var $OXb = class $OXb2 {
  constructor(resource, g, h3, j, k, l, uriIdentityService) {
    this.resource = resource;
    this.g = g;
    this.h = h3;
    this.j = j;
    this.k = k;
    this.l = l;
    this.d = uriIdentityService.extUri;
    this.f = $TBb(void 0, this.resource, h3, 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 ($JXb(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, $Ci.fromString(JSON.stringify(lastSyncRemoteUserData)));
  }
};
$OXb = __decorate([
  __param(1, $rs),
  __param(2, $Xk),
  __param(3, $wn),
  __param(4, $km),
  __param(5, $jv),
  __param(6, $vl)
], $OXb);

// out-build/vs/platform/userDataSync/common/globalStateMerge.js
function $PXb(localStorage2, remoteStorage, baseStorage, storageKeys2, logService) {
  if (!remoteStorage) {
    return { remote: { added: Object.keys(localStorage2), removed: [], updated: [], all: Object.keys(localStorage2).length > 0 ? localStorage2 : null }, local: { added: {}, removed: [], updated: {} } };
  }
  const localToRemote = compare3(localStorage2, 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 ? compare3(baseStorage, remoteStorage) : { added: Object.keys(remoteStorage).reduce((r2, k) => {
    r2.add(k);
    return r2;
  }, /* @__PURE__ */ new Set()), removed: /* @__PURE__ */ new Set(), updated: /* @__PURE__ */ new Set() };
  const baseToLocal = baseStorage ? compare3(baseStorage, localStorage2) : { added: Object.keys(localStorage2).reduce((r2, k) => {
    r2.add(k);
    return r2;
  }, /* @__PURE__ */ new Set()), removed: /* @__PURE__ */ new Set(), updated: /* @__PURE__ */ new Set() };
  const local = { added: {}, removed: [], updated: {} };
  const remote = $Lv(remoteStorage);
  const isFirstTimeSync = !baseStorage;
  for (const key2 of baseToLocal.added.values()) {
    if (key2 !== $4Bb && isFirstTimeSync && baseToRemote.added.has(key2)) {
      continue;
    }
    remote[key2] = localStorage2[key2];
  }
  for (const key2 of baseToLocal.updated.values()) {
    remote[key2] = localStorage2[key2];
  }
  for (const key2 of baseToLocal.removed.values()) {
    if (storageKeys2.unregistered.includes(key2)) {
      continue;
    }
    delete remote[key2];
  }
  for (const key2 of baseToRemote.added.values()) {
    const remoteValue = remoteStorage[key2];
    if (storageKeys2.machine.includes(key2)) {
      logService.info(`GlobalState: Skipped adding ${key2} in local storage because it is declared as machine scoped.`);
      continue;
    }
    if (baseStorage && baseToLocal.added.has(key2)) {
      continue;
    }
    const localValue = localStorage2[key2];
    if (localValue && localValue.value === remoteValue.value) {
      continue;
    }
    if (key2 === $4Bb && isFirstTimeSync && baseToLocal.added.has(key2)) {
      continue;
    }
    if (localValue) {
      local.updated[key2] = remoteValue;
    } else {
      local.added[key2] = remoteValue;
    }
  }
  for (const key2 of baseToRemote.updated.values()) {
    const remoteValue = remoteStorage[key2];
    if (storageKeys2.machine.includes(key2)) {
      logService.info(`GlobalState: Skipped updating ${key2} in local storage because it is declared as machine scoped.`);
      continue;
    }
    if (baseToLocal.updated.has(key2) || baseToLocal.removed.has(key2)) {
      continue;
    }
    const localValue = localStorage2[key2];
    if (localValue && localValue.value === remoteValue.value) {
      continue;
    }
    local.updated[key2] = remoteValue;
  }
  for (const key2 of baseToRemote.removed.values()) {
    if (storageKeys2.machine.includes(key2)) {
      logService.trace(`GlobalState: Skipped removing ${key2} in local storage because it is declared as machine scoped.`);
      continue;
    }
    if (baseToLocal.updated.has(key2) || baseToLocal.removed.has(key2)) {
      continue;
    }
    local.removed.push(key2);
  }
  const result = compare3(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 compare3(from, to) {
  const fromKeys = Object.keys(from);
  const toKeys = Object.keys(to);
  const added = toKeys.filter((key2) => !fromKeys.includes(key2)).reduce((r2, key2) => {
    r2.add(key2);
    return r2;
  }, /* @__PURE__ */ new Set());
  const removed = fromKeys.filter((key2) => !toKeys.includes(key2)).reduce((r2, key2) => {
    r2.add(key2);
    return r2;
  }, /* @__PURE__ */ new Set());
  const updated = /* @__PURE__ */ new Set();
  for (const key2 of fromKeys) {
    if (removed.has(key2)) {
      continue;
    }
    const value1 = from[key2];
    const value2 = to[key2];
    if (!$Pv(value1, value2)) {
      updated.add(key2);
    }
  }
  return { added, removed, updated };
}

// out-build/vs/platform/userDataSync/common/globalStateSync.js
var argvStoragePrefx = "globalState.argv.";
var argvProperties = ["locale"];
function $QXb(globalState, format2) {
  const storageKeys2 = globalState.storage ? Object.keys(globalState.storage).sort() : [];
  const storage = {};
  storageKeys2.forEach((key2) => storage[key2] = globalState.storage[key2]);
  globalState.storage = storage;
  return format2 ? $Tw(globalState, {}) : JSON.stringify(globalState);
}
var GLOBAL_STATE_DATA_VERSION = 1;
var $RXb = class $RXb2 extends $LXb {
  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: $aCb, authority: "base" });
    this.xb = this.vb.with({ scheme: $aCb, authority: "local" });
    this.yb = this.vb.with({ scheme: $aCb, authority: "remote" });
    this.zb = this.vb.with({ scheme: $aCb, authority: "accepted" });
    this.Ab = instantiationService.createInstance($SXb);
    this.B(fileService.watch(this.h.dirname(this.H.argvResource)));
    this.B(Event2.any(
      /* Locale change */
      Event2.filter(fileService.onDidFilesChange, (e) => e.contains(this.H.argvResource)),
      Event2.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 storageKeys2 = await this.Jb(lastSyncGlobalState);
    const { local, remote } = $PXb(localGlobalState.storage, remoteGlobalState ? remoteGlobalState.storage : null, lastSyncGlobalState ? lastSyncGlobalState.storage : null, storageKeys2, 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 = $QXb(localGlobalState, false);
    return [{
      baseResource: this.wb,
      baseContent: lastSyncGlobalState ? $QXb(lastSyncGlobalState, false) : localContent,
      localResource: this.xb,
      localContent,
      localUserData: localGlobalState,
      remoteResource: this.yb,
      remoteContent: remoteGlobalState ? $QXb(remoteGlobalState, false) : null,
      previewResource: this.vb,
      previewResult,
      localChange: previewResult.localChange,
      remoteChange: previewResult.remoteChange,
      acceptedResource: this.zb,
      storageKeys: storageKeys2
    }];
  }
  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 storageKeys2 = await this.Jb(lastSyncGlobalState);
    const { remote } = $PXb(localGlobalState.storage, lastSyncGlobalState.storage, lastSyncGlobalState.storage, storageKeys2, 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 } = $PXb(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 ? $QXb(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 [key2, value] of storageData) {
      if (value.target === 0) {
        user.push(key2);
      } else if (value.target === 1) {
        machine.push(key2);
      }
    }
    const registered = [...user, ...machine];
    const unregistered = lastSyncGlobalState?.storage ? Object.keys(lastSyncGlobalState.storage).filter((key2) => !key2.startsWith(argvStoragePrefx) && !registered.includes(key2) && storageData.get(key2) !== void 0) : [];
    if (!$r) {
      const keysSyncedOnlyInWeb = [...$RBb.map((resource) => $5Bb(resource)), $4Bb];
      unregistered.push(...keysSyncedOnlyInWeb);
      machine.push(...keysSyncedOnlyInWeb);
    }
    return { user, machine, unregistered };
  }
};
$RXb = __decorate([
  __param(2, $$A),
  __param(3, $km),
  __param(4, $VBb),
  __param(5, $WBb),
  __param(6, $$Bb),
  __param(7, $Xk),
  __param(8, $6Bb),
  __param(9, $zv),
  __param(10, $kl),
  __param(11, $jv),
  __param(12, $vl),
  __param(13, $Pk)
], $RXb);
var $SXb = class $SXb2 {
  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 = $yw(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 [key2, value] of storageData) {
      if (value.value && value.target === 0) {
        storage[key2] = { 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($qb(error));
    }
    return "{}";
  }
  async writeLocalGlobalState({ added, removed, updated }, profile) {
    const syncResourceLogLabel = $KXb("globalState", profile);
    const argv = {};
    const updatedStorage = /* @__PURE__ */ new Map();
    const storageData = await this.c.readStorageData(profile);
    const handleUpdatedStorage = (keys, storage) => {
      for (const key2 of keys) {
        if (key2.startsWith(argvStoragePrefx)) {
          argv[key2.substring(argvStoragePrefx.length)] = storage ? storage[key2].value : void 0;
          continue;
        }
        if (storage) {
          const storageValue = storage[key2];
          if (storageValue.value !== storageData.get(key2)?.value) {
            updatedStorage.set(key2, storageValue.value);
          }
        } else {
          if (storageData.get(key2) !== void 0) {
            updatedStorage.set(key2, 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 = edit2(content, [argvProperty], argv[argvProperty], {});
      }
      if (argvContent !== content) {
        this.d.trace(`${syncResourceLogLabel}: Updating locale...`);
        await this.a.writeFile(this.b.argvResource, $Ci.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()]);
    }
  }
};
$SXb = __decorate([
  __param(0, $km),
  __param(1, $Xk),
  __param(2, $$A),
  __param(3, $$Bb)
], $SXb);
var $TXb = class $TXb2 extends $OXb {
  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 key2 of Object.keys(remoteGlobalState.storage)) {
      if (key2.startsWith(argvStoragePrefx)) {
        argv[key2.substring(argvStoragePrefx.length)] = remoteGlobalState.storage[key2].value;
      } else {
        if (this.l.get(
          key2,
          0
          /* StorageScope.PROFILE */
        ) === void 0) {
          storage[key2] = remoteGlobalState.storage[key2].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 = edit2(content, [argvProperty], argv[argvProperty], {});
      }
      await this.k.writeFile(this.h.argvResource, $Ci.fromString(content));
    }
    if (Object.keys(storage).length) {
      const storageEntries = [];
      for (const key2 of Object.keys(storage)) {
        storageEntries.push({
          key: key2,
          value: storage[key2],
          scope: 0,
          target: 0
          /* StorageTarget.USER */
        });
      }
      this.l.storeAll(storageEntries, true);
    }
  }
};
$TXb = __decorate([
  __param(0, $jv),
  __param(1, $km),
  __param(2, $rs),
  __param(3, $Xk),
  __param(4, $$Bb),
  __param(5, $vl)
], $TXb);
var $UXb = class $UXb2 {
  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[$4Bb]?.value;
  }
  async sync(userDataSyncStoreType) {
    const syncHeaders = $ZBb($ps());
    try {
      return await this.g(userDataSyncStoreType, syncHeaders);
    } catch (e) {
      if (e instanceof $1Bb) {
        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[$4Bb] = { value: userDataSyncStoreType, version: GLOBAL_STATE_DATA_VERSION };
    const machineId = await $7v(this.c, this.d, this.b);
    const syncDataToUpdate = { version: GLOBAL_STATE_DATA_VERSION, machineId, content: $QXb(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 ($JXb(syncData)) {
      return syncData ? JSON.parse(syncData.content) : null;
    }
    throw new Error("Invalid remote data");
  }
};
$UXb = __decorate([
  __param(1, $jv),
  __param(2, $Xk),
  __param(3, $km),
  __param(4, $wn)
], $UXb);

// out-build/vs/platform/userDataSync/common/userDataSyncMachines.js
var $JBb_1;
var $HBb = $Qk("IUserDataSyncMachinesService");
var currentMachineNameKey = "sync.currentMachineName";
var Safari = "Safari";
var Chrome = "Chrome";
var Edge = "Edge";
var Firefox = "Firefox";
var Android = "Android";
function $IBb(platform) {
  switch (platform) {
    case Safari:
    case Chrome:
    case Edge:
    case Firefox:
    case Android:
    case $k(
      0
      /* Platform.Web */
    ):
      return true;
  }
  return false;
}
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 $JBb = class $JBb2 extends $3c {
  static {
    $JBb_1 = this;
  }
  static {
    this.a = 1;
  }
  static {
    this.b = "machines";
  }
  constructor(environmentService, fileService, h3, j, m, n) {
    super();
    this.h = h3;
    this.j = j;
    this.m = m;
    this.n = n;
    this.c = this.B(new $ze());
    this.onDidChange = this.c.event;
    this.g = null;
    this.f = $7v(environmentService, fileService, h3);
  }
  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 !== $JBb_1.a) {
      throw new Error(localize(2508, null, this.n.nameLong));
    }
    return machinesData;
  }
  async t(machinesData) {
    const content = JSON.stringify(machinesData);
    const ref = await this.j.writeResource($JBb_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[$JBb_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($JBb_1.b, this.g);
  }
  w(userData) {
    if (userData.content !== null) {
      try {
        return JSON.parse(userData.content);
      } catch (e) {
        this.m.error(e);
      }
    }
    return {
      version: $JBb_1.a,
      machines: []
    };
  }
};
$JBb = $JBb_1 = __decorate([
  __param(0, $Xk),
  __param(1, $km),
  __param(2, $jv),
  __param(3, $VBb),
  __param(4, $$Bb),
  __param(5, $Vu)
], $JBb);

// out-build/vs/workbench/services/userDataSync/browser/userDataSyncWorkbenchService.js
var $WXb_1;
var UserDataSyncAccount = class {
  constructor(authenticationProviderId, f) {
    this.authenticationProviderId = authenticationProviderId;
    this.f = f;
  }
  get sessionId() {
    return this.f.id;
  }
  get accountName() {
    return this.f.account.label;
  }
  get accountId() {
    return this.f.account.id;
  }
  get token() {
    return this.f.idToken || this.f.accessToken;
  }
};
function $VXb(editor) {
  const candidate = editor;
  return URI.isUri(candidate?.base) && URI.isUri(candidate?.input1?.uri) && URI.isUri(candidate?.input2?.uri) && URI.isUri(candidate?.result);
}
var $WXb = class $WXb2 extends $3c {
  static {
    $WXb_1 = this;
  }
  static {
    this.f = "userDataSyncAccount.donotUseWorkbenchSession";
  }
  static {
    this.g = "userDataSyncAccountProvider";
  }
  static {
    this.h = "userDataSyncAccountPreference";
  }
  get enabled() {
    return !!this.bb.userDataSyncStore;
  }
  get authenticationProviders() {
    return this.j;
  }
  get accountStatus() {
    return this.n;
  }
  get current() {
    return this.t;
  }
  constructor(G, H, I, J, L, M, N, O, P, Q, R, S, U, W, X, Y, Z, contextKeyService, $149, ab, bb, cb, db, eb, fb, gb, hb, ib) {
    super();
    this.G = G;
    this.H = H;
    this.I = I;
    this.J = J;
    this.L = L;
    this.M = M;
    this.N = N;
    this.O = O;
    this.P = P;
    this.Q = Q;
    this.R = R;
    this.S = S;
    this.U = U;
    this.W = W;
    this.X = X;
    this.Y = Y;
    this.Z = Z;
    this.$ = $149;
    this.ab = ab;
    this.bb = bb;
    this.cb = cb;
    this.db = db;
    this.eb = eb;
    this.fb = fb;
    this.gb = gb;
    this.hb = hb;
    this.ib = ib;
    this.j = [];
    this.n = "uninitialized";
    this.r = this.B(new $ze());
    this.onDidChangeAccountStatus = this.r.event;
    this.s = this.B(new $ze());
    this.onDidTurnOnSync = this.s.event;
    this.F = void 0;
    this.Db = null;
    this.Fb = null;
    this.u = $tXb.bindTo(contextKeyService);
    this.w = $sXb.bindTo(contextKeyService);
    this.y = $uXb.bindTo(contextKeyService);
    this.D = $vXb.bindTo(contextKeyService);
    this.C = $xXb.bindTo(contextKeyService);
    this.z = $wXb.bindTo(contextKeyService);
    if (this.bb.userDataSyncStore) {
      this.w.set(this.G.status);
      this.B(G.onDidChangeStatus((status) => this.w.set(status)));
      this.u.set(N.isEnabled());
      this.B(N.onDidChangeEnablement((enabled) => this.u.set(enabled)));
      this.lb();
    }
  }
  jb() {
    const oldValue = this.j;
    this.j = (this.bb.userDataSyncStore?.authenticationProviders || []).filter(({ id: id2 }) => this.I.declaredProviders.some((provider) => provider.id === id2));
    this.Q.trace("Settings Sync: Authentication providers updated", this.j.map(({ id: id2 }) => id2));
    return $zb(oldValue, this.j, (a, b) => a.id === b.id);
  }
  kb(authenticationProviderId) {
    return this.authenticationProviders.some(({ id: id2 }) => id2 === authenticationProviderId);
  }
  async lb() {
    try {
      await Promise.all([this.S.whenInstalledExtensionsRegistered(), this.fb.whenInitializationFinished()]);
      await this.mb();
    } catch (error) {
      if (!this.U.extensionTestsLocationURI) {
        this.Q.error(error);
      }
    }
  }
  async mb() {
    if ($r) {
      const authenticationSession = await $Y4(this.W, this.R);
      if (this.Gb === void 0 && authenticationSession?.id) {
        if (this.U.options?.settingsSyncOptions?.authenticationProvider && this.U.options.settingsSyncOptions.enabled) {
          this.Gb = authenticationSession.id;
        } else if (this.Ib) {
          this.Gb = authenticationSession.id;
        }
        this.Ib = false;
      }
    }
    const initPromise = this.nb("initialize");
    this.B(this.I.onDidChangeDeclaredProviders(() => {
      if (this.jb()) {
        initPromise.finally(() => this.nb("declared authentication providers changed"));
      }
    }));
    await initPromise;
    this.B(Event2.filter(Event2.any(this.I.onDidRegisterAuthenticationProvider, this.I.onDidUnregisterAuthenticationProvider), (info) => this.kb(info.id))(() => this.nb("authentication provider change")));
    this.B(Event2.filter(this.J.onTokenFailed, (isSuccessive) => !isSuccessive)(() => this.nb("token failure")));
    this.B(Event2.filter(this.I.onDidChangeSessions, (e) => this.kb(e.providerId))(({ event }) => this.Bb(event)));
    this.B(this.M.onDidChangeValue(-1, $WXb_1.h, this.q)(() => this.Cb()));
    this.B(Event2.filter(this.J.onTokenFailed, (bailout) => bailout)(() => this.Ab()));
    this.C.set(this.G.conflicts.length > 0);
    this.B(this.G.onDidChangeConflicts((conflicts) => {
      this.C.set(conflicts.length > 0);
      if (!conflicts.length) {
        this.z.reset();
      }
      this.eb.editors.filter((input) => {
        const remoteResource = $fL(input) ? input.original.resource : $VXb(input) ? input.input1.uri : void 0;
        if (remoteResource?.scheme !== $aCb) {
          return false;
        }
        return !this.G.conflicts.some(({ conflicts: conflicts2 }) => conflicts2.some(({ previewResource }) => this.H.extUri.isEqual(previewResource, input.resource)));
      }).forEach((input) => input.dispose());
    }));
  }
  async nb(reason) {
    this.Q.trace(`Settings Sync: Updating due to ${reason}`);
    this.jb();
    await this.ob();
    if (this.t) {
      this.Eb = this.t.authenticationProviderId;
    }
    await this.pb(this.t);
    this.qb(
      this.t ? "available" : "unavailable"
      /* AccountStatus.Unavailable */
    );
  }
  async ob() {
    this.Q.trace("Settings Sync: Updating the current account");
    const currentSessionId = this.Gb;
    const currentAuthenticationProviderId = this.Eb;
    if (currentSessionId) {
      const authenticationProviders = currentAuthenticationProviderId ? this.authenticationProviders.filter(({ id: id2 }) => id2 === currentAuthenticationProviderId) : this.authenticationProviders;
      for (const { id: id2, scopes } of authenticationProviders) {
        const sessions = await this.I.getSessions(id2, scopes) || [];
        for (const session of sessions) {
          if (session.id === currentSessionId) {
            this.t = new UserDataSyncAccount(id2, session);
            this.Q.trace("Settings Sync: Updated the current account", this.t.accountName);
            return;
          }
        }
      }
    }
    this.t = void 0;
  }
  async pb(current) {
    let value = void 0;
    if (current) {
      try {
        this.Q.trace("Settings Sync: Updating the token for the account", current.accountName);
        const token = current.token;
        this.Q.info("Settings Sync: Token updated for the account", current.accountName);
        value = { token, authenticationProviderId: current.authenticationProviderId };
      } catch (e) {
        this.Q.error(e);
      }
    }
    await this.J.updateAccount(value);
  }
  qb(accountStatus) {
    this.Q.trace(`Settings Sync: Updating the account status to ${accountStatus}`);
    if (this.n !== accountStatus) {
      const previous = this.n;
      this.Q.info(`Settings Sync: Account status changed from ${previous} to ${accountStatus}`);
      this.n = accountStatus;
      this.y.set(accountStatus);
      this.r.fire(accountStatus);
    }
  }
  async turnOn() {
    if (!this.authenticationProviders.length) {
      throw new Error(localize(13426, null));
    }
    if (this.N.isEnabled()) {
      return;
    }
    if (this.G.status !== "idle") {
      throw new Error("Cannot turn on sync while syncing");
    }
    const picked = await this.vb();
    if (!picked) {
      throw new $lb();
    }
    if (this.accountStatus !== "available") {
      throw new Error(localize(13427, null));
    }
    const turnOnSyncCancellationToken = this.F = new $ad();
    const disposable = $r ? $3c.None : this.cb.onBeforeShutdown((e) => e.veto((async () => {
      const { confirmed } = await this.Z.confirm({
        type: "warning",
        message: localize(13428, null),
        title: localize(13429, null),
        primaryButton: localize(13430, null),
        cancelButton: localize(13431, null)
      });
      if (confirmed) {
        turnOnSyncCancellationToken.cancel();
      }
      return !confirmed;
    })(), "veto.settingsSync"));
    try {
      await this.rb(turnOnSyncCancellationToken.token);
    } finally {
      disposable.dispose();
      this.F = void 0;
    }
    await this.O.turnOn();
    if (this.bb.userDataSyncStore?.canSwitch) {
      await this.synchroniseUserDataSyncStoreType();
    }
    this.Eb = this.current?.authenticationProviderId;
    if (this.U.options?.settingsSyncOptions?.enablementHandler && this.Eb) {
      this.U.options.settingsSyncOptions.enablementHandler(true, this.Eb);
    }
    this.X.info(localize(13432, null, $qXb.value));
    this.s.fire();
  }
  async turnoff(everywhere) {
    if (this.N.isEnabled()) {
      await this.O.turnOff(everywhere);
      if (this.U.options?.settingsSyncOptions?.enablementHandler && this.Eb) {
        this.U.options.settingsSyncOptions.enablementHandler(false, this.Eb);
      }
    }
    if (this.F) {
      this.F.cancel();
    }
  }
  async synchroniseUserDataSyncStoreType() {
    if (!this.J.account) {
      throw new Error("Cannot update because you are signed out from settings sync. Please sign in and try again.");
    }
    if (!$r || !this.bb.userDataSyncStore) {
      return;
    }
    const userDataSyncStoreUrl = this.bb.userDataSyncStore.type === "insiders" ? this.bb.userDataSyncStore.stableUrl : this.bb.userDataSyncStore.insidersUrl;
    const userDataSyncStoreClient = this.db.createInstance($FXb, userDataSyncStoreUrl);
    userDataSyncStoreClient.setAuthToken(this.J.account.token, this.J.account.authenticationProviderId);
    await this.db.createInstance($UXb, userDataSyncStoreClient).sync(this.bb.userDataSyncStore.type);
  }
  syncNow() {
    return this.O.triggerSync(["Sync Now"], false, true);
  }
  async rb(token) {
    const disposables = new $2c();
    const manualSyncTask = await this.G.createManualSyncTask();
    try {
      await this.Y.withProgress({
        location: 10,
        title: $qXb.value,
        command: $zXb,
        delay: 500
      }, async (progress) => {
        progress.report({ message: localize(13433, null) });
        disposables.add(this.G.onDidChangeStatus((status) => {
          if (status === "hasConflicts") {
            progress.report({ message: localize(13434, null) });
          } else {
            progress.report({ message: localize(13435, null) });
          }
        }));
        await manualSyncTask.merge();
        if (this.G.status === "hasConflicts") {
          await this.sb(token);
        }
        await manualSyncTask.apply();
      });
    } catch (error) {
      await manualSyncTask.stop();
      throw error;
    } finally {
      disposables.dispose();
    }
  }
  async sb(token) {
    await this.Z.prompt({
      type: Severity2.Warning,
      message: localize(13436, null),
      detail: localize(13437, null),
      buttons: [
        {
          label: localize(13438, null),
          run: async () => {
            const waitUntilConflictsAreResolvedPromise = $Jh(Event2.toPromise(Event2.filter(this.G.onDidChangeConflicts, (conficts) => conficts.length === 0)), token);
            await this.showConflicts(this.G.conflicts[0]?.conflicts[0]);
            await waitUntilConflictsAreResolvedPromise;
          }
        },
        {
          label: localize(13439, null),
          run: async () => this.tb(true)
        },
        {
          label: localize(13440, null),
          run: () => this.tb(false)
        }
      ],
      cancelButton: {
        run: () => {
          throw new $lb();
        }
      }
    });
  }
  async tb(local) {
    for (const conflict of this.G.conflicts) {
      for (const preview of conflict.conflicts) {
        await this.accept({ syncResource: conflict.syncResource, profile: conflict.profile }, local ? preview.remoteResource : preview.localResource, void 0, { force: true });
      }
    }
  }
  async accept(resource, conflictResource, content, apply2) {
    return this.G.accept(resource, conflictResource, content, apply2);
  }
  async showConflicts(conflictToOpen) {
    if (!this.G.conflicts.length) {
      return;
    }
    this.z.set(true);
    const view = await this.$.openView($BXb);
    if (view && conflictToOpen) {
      await view.open(conflictToOpen);
    }
  }
  async resetSyncedData() {
    const { confirmed } = await this.Z.confirm({
      type: "info",
      message: localize(13441, null),
      title: localize(13442, null),
      primaryButton: localize(13443, null)
    });
    if (confirmed) {
      await this.G.resetRemote();
    }
  }
  async getAllLogResources() {
    const logsFolders = [];
    const stat = await this.gb.resolve(this.H.extUri.dirname(this.U.logsHome));
    if (stat.children) {
      logsFolders.push(...stat.children.filter((stat2) => stat2.isDirectory && /^\d{8}T\d{6}$/.test(stat2.name)).sort().reverse().map((d) => d.resource));
    }
    const result = [];
    for (const logFolder of logsFolders) {
      const folderStat = await this.gb.resolve(logFolder);
      const childStat = folderStat.children?.find((stat2) => this.H.extUri.basename(stat2.resource).startsWith(`${$_Bb}.`));
      if (childStat) {
        result.push(childStat.resource);
      }
    }
    return result;
  }
  async showSyncActivity() {
    this.D.set(true);
    await this.ub();
    await this.$.openViewContainer($AXb);
  }
  async downloadSyncActivity() {
    const result = await this.hb.showOpenDialog({
      title: localize(13444, null),
      canSelectFiles: false,
      canSelectFolders: true,
      canSelectMany: false,
      openLabel: localize(13445, null)
    });
    if (!result?.[0]) {
      return;
    }
    return this.Y.withProgress({
      location: 10
      /* ProgressLocation.Window */
    }, async () => {
      const machines = await this.ib.getMachines();
      const currentMachine = machines.find((m) => m.isCurrent);
      const name = (currentMachine ? currentMachine.name + " - " : "") + "Settings Sync Activity";
      const stat = await this.gb.resolve(result[0]);
      const nameRegEx = new RegExp(`${$Af(name)}\\s(\\d+)`);
      const indexes = [];
      for (const child of stat.children ?? []) {
        if (child.name === name) {
          indexes.push(0);
        } else {
          const matches = nameRegEx.exec(child.name);
          if (matches) {
            indexes.push(parseInt(matches[1]));
          }
        }
      }
      indexes.sort((a, b) => a - b);
      const folder = this.H.extUri.joinPath(result[0], indexes[0] !== 0 ? name : `${name} ${indexes[indexes.length - 1] + 1}`);
      await Promise.all([
        this.G.saveRemoteActivityData(this.H.extUri.joinPath(folder, "remoteActivity.json")),
        (async () => {
          const logResources = await this.getAllLogResources();
          await Promise.all(logResources.map(async (logResource) => this.gb.copy(logResource, this.H.extUri.joinPath(folder, "logs", `${this.H.extUri.basename(this.H.extUri.dirname(logResource))}.log`))));
        })(),
        this.gb.copy(this.U.userDataSyncHome, this.H.extUri.joinPath(folder, "localActivity"))
      ]);
      return folder;
    });
  }
  async ub() {
    const viewContainer5 = this.ab.getViewContainerById($AXb);
    if (viewContainer5) {
      const model = this.ab.getViewContainerModel(viewContainer5);
      if (!model.activeViewDescriptors.length) {
        await Event2.toPromise(Event2.filter(model.onDidChangeActiveViewDescriptors, (e) => model.activeViewDescriptors.length > 0));
      }
    }
  }
  async signIn() {
    const currentAuthenticationProviderId = this.Eb;
    const authenticationProvider = currentAuthenticationProviderId ? this.authenticationProviders.find((p) => p.id === currentAuthenticationProviderId) : void 0;
    if (authenticationProvider) {
      await this.zb(authenticationProvider);
    } else {
      if (!this.authenticationProviders.length) {
        throw new Error(localize(13446, null));
      }
      await this.vb();
    }
  }
  async vb() {
    const result = await this.wb();
    if (!result) {
      return false;
    }
    await this.zb(result);
    return true;
  }
  async wb() {
    if (this.authenticationProviders.length === 0) {
      return void 0;
    }
    const authenticationProviders = [...this.authenticationProviders].sort(({ id: id2 }) => id2 === this.Eb ? -1 : 1);
    const allAccounts = /* @__PURE__ */ new Map();
    if (authenticationProviders.length === 1) {
      const accounts = await this.xb(authenticationProviders[0].id, authenticationProviders[0].scopes);
      if (accounts.length) {
        allAccounts.set(authenticationProviders[0].id, accounts);
      } else {
        return authenticationProviders[0];
      }
    }
    let result;
    const disposables = new $2c();
    const quickPick = disposables.add(this.L.createQuickPick({ useSeparators: true }));
    const promise = new Promise((c) => {
      disposables.add(quickPick.onDidHide(() => {
        disposables.dispose();
        c(result);
      }));
    });
    quickPick.title = $qXb.value;
    quickPick.ok = false;
    quickPick.ignoreFocusOut = true;
    quickPick.placeholder = localize(13447, null);
    quickPick.show();
    if (authenticationProviders.length > 1) {
      quickPick.busy = true;
      for (const { id: id2, scopes } of authenticationProviders) {
        const accounts = await this.xb(id2, scopes);
        if (accounts.length) {
          allAccounts.set(id2, accounts);
        }
      }
      quickPick.busy = false;
    }
    quickPick.items = this.yb(authenticationProviders, allAccounts);
    disposables.add(quickPick.onDidAccept(() => {
      result = quickPick.selectedItems[0]?.account ? quickPick.selectedItems[0]?.account : quickPick.selectedItems[0]?.authenticationProvider;
      quickPick.hide();
    }));
    return promise;
  }
  async xb(authenticationProviderId, scopes) {
    const accounts = /* @__PURE__ */ new Map();
    let currentAccount = null;
    const sessions = await this.I.getSessions(authenticationProviderId, scopes) || [];
    for (const session of sessions) {
      const account = new UserDataSyncAccount(authenticationProviderId, session);
      accounts.set(account.accountId, account);
      if (account.sessionId === this.Gb) {
        currentAccount = account;
      }
    }
    if (currentAccount) {
      accounts.set(currentAccount.accountId, currentAccount);
    }
    return currentAccount ? [...accounts.values()] : [...accounts.values()].sort(({ sessionId }) => sessionId === this.Gb ? -1 : 1);
  }
  yb(authenticationProviders, allAccounts) {
    const quickPickItems = [];
    if (allAccounts.size) {
      quickPickItems.push({ type: "separator", label: localize(13448, null) });
      for (const authenticationProvider of authenticationProviders) {
        const accounts = (allAccounts.get(authenticationProvider.id) || []).sort(({ sessionId }) => sessionId === this.Gb ? -1 : 1);
        const providerName = this.I.getProvider(authenticationProvider.id).label;
        for (const account of accounts) {
          quickPickItems.push({
            label: `${account.accountName} (${providerName})`,
            description: account.sessionId === this.current?.sessionId ? localize(13449, null) : void 0,
            account,
            authenticationProvider
          });
        }
      }
      quickPickItems.push({ type: "separator", label: localize(13450, null) });
    }
    for (const authenticationProvider of authenticationProviders) {
      const provider = this.I.getProvider(authenticationProvider.id);
      if (!allAccounts.has(authenticationProvider.id) || provider.supportsMultipleAccounts) {
        const providerName = provider.label;
        quickPickItems.push({ label: localize(13451, null, providerName), authenticationProvider });
      }
    }
    return quickPickItems;
  }
  async zb(accountOrAuthProvider) {
    let sessionId;
    if ($QBb(accountOrAuthProvider)) {
      if (this.U.options?.settingsSyncOptions?.authenticationProvider?.id === accountOrAuthProvider.id) {
        sessionId = await this.U.options?.settingsSyncOptions?.authenticationProvider?.signIn();
      } else {
        sessionId = (await this.I.createSession(accountOrAuthProvider.id, accountOrAuthProvider.scopes)).id;
      }
      this.Eb = accountOrAuthProvider.id;
    } else {
      if (this.U.options?.settingsSyncOptions?.authenticationProvider?.id === accountOrAuthProvider.authenticationProviderId) {
        sessionId = await this.U.options?.settingsSyncOptions?.authenticationProvider?.signIn();
      } else {
        sessionId = accountOrAuthProvider.sessionId;
      }
      this.Eb = accountOrAuthProvider.authenticationProviderId;
    }
    this.Gb = sessionId;
    await this.nb("sign in");
  }
  async Ab() {
    this.P.publicLog2("sync/successiveAuthFailures");
    this.Gb = void 0;
    await this.nb("auth failure");
  }
  Bb(e) {
    if (this.Gb && e.removed?.find((session) => session.id === this.Gb)) {
      this.Gb = void 0;
    }
    this.nb("change in sessions");
  }
  Cb() {
    if (this.Gb !== this.Hb()) {
      this.Fb = null;
      this.nb("change in storage");
    }
  }
  get Eb() {
    if (this.Db === null) {
      this.Db = this.M.get(
        $WXb_1.g,
        -1
        /* StorageScope.APPLICATION */
      );
    }
    return this.Db;
  }
  set Eb(currentAuthenticationProviderId) {
    if (this.Db !== currentAuthenticationProviderId) {
      this.Db = currentAuthenticationProviderId;
      if (currentAuthenticationProviderId === void 0) {
        this.M.remove(
          $WXb_1.g,
          -1
          /* StorageScope.APPLICATION */
        );
      } else {
        this.M.store(
          $WXb_1.g,
          currentAuthenticationProviderId,
          -1,
          1
          /* StorageTarget.MACHINE */
        );
      }
    }
  }
  get Gb() {
    if (this.Fb === null) {
      this.Fb = this.Hb();
    }
    return this.Fb;
  }
  set Gb(cachedSessionId) {
    if (this.Fb !== cachedSessionId) {
      this.Fb = cachedSessionId;
      if (cachedSessionId === void 0) {
        this.Q.info("Settings Sync: Reset current session");
        this.M.remove(
          $WXb_1.h,
          -1
          /* StorageScope.APPLICATION */
        );
      } else {
        this.Q.info("Settings Sync: Updated current session", cachedSessionId);
        this.M.store(
          $WXb_1.h,
          cachedSessionId,
          -1,
          1
          /* StorageTarget.MACHINE */
        );
      }
    }
  }
  Hb() {
    return this.M.get(
      $WXb_1.h,
      -1
      /* StorageScope.APPLICATION */
    );
  }
  get Ib() {
    return !this.M.getBoolean($WXb_1.f, -1, false);
  }
  set Ib(useWorkbenchSession) {
    this.M.store(
      $WXb_1.f,
      !useWorkbenchSession,
      -1,
      1
      /* StorageTarget.MACHINE */
    );
  }
};
$WXb = $WXb_1 = __decorate([
  __param(0, $7Bb),
  __param(1, $vl),
  __param(2, $xS),
  __param(3, $eWb),
  __param(4, $1M),
  __param(5, $jv),
  __param(6, $6Bb),
  __param(7, $9Bb),
  __param(8, $zv),
  __param(9, $wn),
  __param(10, $Vu),
  __param(11, $wN),
  __param(12, $M4),
  __param(13, $J4),
  __param(14, $PJ),
  __param(15, $TJ),
  __param(16, $Yv),
  __param(17, $on),
  __param(18, $uob),
  __param(19, $$M),
  __param(20, $UBb),
  __param(21, $KL),
  __param(22, $Pk),
  __param(23, $mJ),
  __param(24, $9Vb),
  __param(25, $km),
  __param(26, $1v),
  __param(27, $HBb)
], $WXb);
$SC(
  $oXb,
  $WXb,
  0
  /* InstantiationType.Eager */
);

// out-build/vs/workbench/services/authentication/browser/authenticationExtensionsService.js
var SCOPESLIST_SEPARATOR = " ";
var $XXb = class $XXb2 extends $3c {
  constructor(j, m, n, r2, s, t, u, w) {
    super();
    this.j = j;
    this.m = m;
    this.n = n;
    this.r = r2;
    this.s = s;
    this.t = t;
    this.u = u;
    this.w = w;
    this.a = /* @__PURE__ */ new Map();
    this.b = /* @__PURE__ */ new Map();
    this.c = this.B(new $4c());
    this.f = this.B(new $ze());
    this.onDidChangeAccountPreference = this.f.event;
    this.g = this.s.inheritAuthAccountPreference || {};
    this.h = Object.entries(this.g).reduce((acc, [parent, children]) => {
      children.forEach((child) => {
        acc[child] = parent;
      });
      return acc;
    }, {});
    this.y();
  }
  y() {
    this.B(this.t.onDidChangeSessions(async (e) => {
      if (e.event.added?.length) {
        await this.z(e.providerId, e.event.added);
      }
      if (e.event.removed?.length) {
        await this.C(e.providerId, e.event.removed);
      }
      this.D();
    }));
    this.B(this.t.onDidUnregisterAuthenticationProvider((e) => {
      const accessRequests = this.b.get(e.id) || {};
      Object.keys(accessRequests).forEach((extensionId) => {
        this.F(e.id, extensionId);
      });
    }));
  }
  async z(providerId, addedSessions) {
    const existingRequestsForProvider = this.a.get(providerId);
    if (!existingRequestsForProvider) {
      return;
    }
    Object.keys(existingRequestsForProvider).forEach((requestedScopes) => {
      if (addedSessions.some((session) => session.scopes.slice().join(SCOPESLIST_SEPARATOR) === requestedScopes)) {
        const sessionRequest = existingRequestsForProvider[requestedScopes];
        sessionRequest?.disposables.forEach((item) => item.dispose());
        delete existingRequestsForProvider[requestedScopes];
        if (Object.keys(existingRequestsForProvider).length === 0) {
          this.a.delete(providerId);
        } else {
          this.a.set(providerId, existingRequestsForProvider);
        }
      }
    });
  }
  async C(providerId, removedSessions) {
    const providerRequests = this.b.get(providerId);
    if (providerRequests) {
      Object.keys(providerRequests).forEach((extensionId) => {
        removedSessions.forEach((removed) => {
          const indexOfSession = providerRequests[extensionId].possibleSessions.findIndex((session) => session.id === removed.id);
          if (indexOfSession) {
            providerRequests[extensionId].possibleSessions.splice(indexOfSession, 1);
          }
        });
        if (!providerRequests[extensionId].possibleSessions.length) {
          this.F(providerId, extensionId);
        }
      });
    }
  }
  D() {
    this.c.clear();
    let numberOfRequests = 0;
    this.a.forEach((providerRequests) => {
      Object.keys(providerRequests).forEach((request) => {
        numberOfRequests += providerRequests[request].requestingExtensionIds.length;
      });
    });
    this.b.forEach((accessRequest) => {
      numberOfRequests += Object.keys(accessRequest).length;
    });
    if (numberOfRequests > 0) {
      const badge = new $wqb(numberOfRequests, () => localize(12539, null));
      this.c.value = this.j.showAccountsActivity({ badge });
    }
  }
  F(providerId, extensionId) {
    const providerRequests = this.b.get(providerId) || {};
    if (providerRequests[extensionId]) {
      $Xc(providerRequests[extensionId].disposables);
      delete providerRequests[extensionId];
      this.D();
    }
  }
  //#region Account/Session Preference
  updateAccountPreference(extensionId, providerId, account) {
    const realExtensionId = $5z.toKey(extensionId);
    const parentExtensionId = this.h[realExtensionId] ?? realExtensionId;
    const key2 = this.G(parentExtensionId, providerId);
    this.m.store(
      key2,
      account.label,
      1,
      1
      /* StorageTarget.MACHINE */
    );
    this.m.store(
      key2,
      account.label,
      -1,
      1
      /* StorageTarget.MACHINE */
    );
    const childrenExtensions = this.g[parentExtensionId];
    const extensionIds = childrenExtensions ? [parentExtensionId, ...childrenExtensions] : [parentExtensionId];
    this.f.fire({ extensionIds, providerId });
  }
  getAccountPreference(extensionId, providerId) {
    const realExtensionId = $5z.toKey(extensionId);
    const key2 = this.G(this.h[realExtensionId] ?? realExtensionId, providerId);
    return this.m.get(
      key2,
      1
      /* StorageScope.WORKSPACE */
    ) ?? this.m.get(
      key2,
      -1
      /* StorageScope.APPLICATION */
    );
  }
  removeAccountPreference(extensionId, providerId) {
    const realExtensionId = $5z.toKey(extensionId);
    const key2 = this.G(this.h[realExtensionId] ?? realExtensionId, providerId);
    this.m.remove(
      key2,
      1
      /* StorageScope.WORKSPACE */
    );
    this.m.remove(
      key2,
      -1
      /* StorageScope.APPLICATION */
    );
  }
  G(extensionId, providerId) {
    return `${extensionId}-${providerId}`;
  }
  // TODO@TylerLeonhardt: Remove all of this after a couple iterations
  updateSessionPreference(providerId, extensionId, session) {
    const realExtensionId = $5z.toKey(extensionId);
    const key2 = `${realExtensionId}-${providerId}-${session.scopes.join(SCOPESLIST_SEPARATOR)}`;
    this.m.store(
      key2,
      session.id,
      1,
      1
      /* StorageTarget.MACHINE */
    );
    this.m.store(
      key2,
      session.id,
      -1,
      1
      /* StorageTarget.MACHINE */
    );
  }
  getSessionPreference(providerId, extensionId, scopes) {
    const realExtensionId = $5z.toKey(extensionId);
    const key2 = `${realExtensionId}-${providerId}-${scopes.join(SCOPESLIST_SEPARATOR)}`;
    return this.m.get(
      key2,
      1
      /* StorageScope.WORKSPACE */
    ) ?? this.m.get(
      key2,
      -1
      /* StorageScope.APPLICATION */
    );
  }
  removeSessionPreference(providerId, extensionId, scopes) {
    const realExtensionId = $5z.toKey(extensionId);
    const key2 = `${realExtensionId}-${providerId}-${scopes.join(SCOPESLIST_SEPARATOR)}`;
    this.m.remove(
      key2,
      1
      /* StorageScope.WORKSPACE */
    );
    this.m.remove(
      key2,
      -1
      /* StorageScope.APPLICATION */
    );
  }
  H(providerId, extensionId, session) {
    this.updateAccountPreference(extensionId, providerId, session.account);
    this.updateSessionPreference(providerId, extensionId, session);
  }
  //#endregion
  async I(provider, accountName, extensionId, extensionName) {
    let SessionPromptChoice;
    (function(SessionPromptChoice2) {
      SessionPromptChoice2[SessionPromptChoice2["Allow"] = 0] = "Allow";
      SessionPromptChoice2[SessionPromptChoice2["Deny"] = 1] = "Deny";
      SessionPromptChoice2[SessionPromptChoice2["Cancel"] = 2] = "Cancel";
    })(SessionPromptChoice || (SessionPromptChoice = {}));
    const { result } = await this.n.prompt({
      type: Severity2.Info,
      message: localize(12540, null, extensionName, provider.label, accountName),
      buttons: [
        {
          label: localize(12541, null),
          run: () => SessionPromptChoice.Allow
        },
        {
          label: localize(12542, null),
          run: () => SessionPromptChoice.Deny
        }
      ],
      cancelButton: {
        run: () => SessionPromptChoice.Cancel
      }
    });
    if (result !== SessionPromptChoice.Cancel) {
      this.w.updateAllowedExtensions(provider.id, accountName, [{ id: extensionId, name: extensionName, allowed: result === SessionPromptChoice.Allow }]);
      this.F(provider.id, extensionId);
    }
    return result === SessionPromptChoice.Allow;
  }
  /**
   * This function should be used only when there are sessions to disambiguate.
   */
  async selectSession(providerId, extensionId, extensionName, scopes, availableSessions) {
    const allAccounts = await this.t.getAccounts(providerId);
    if (!allAccounts.length) {
      throw new Error("No accounts available");
    }
    const disposables = new $2c();
    const quickPick = disposables.add(this.r.createQuickPick());
    quickPick.ignoreFocusOut = true;
    const accountsWithSessions = /* @__PURE__ */ new Set();
    const items = availableSessions.filter((session) => !accountsWithSessions.has(session.account.label) && accountsWithSessions.add(session.account.label)).map((session) => {
      return {
        label: session.account.label,
        session
      };
    });
    allAccounts.forEach((account) => {
      if (!accountsWithSessions.has(account.label)) {
        items.push({ label: account.label, account });
      }
    });
    items.push({ label: localize(12543, null) });
    quickPick.items = items;
    quickPick.title = localize(12544, null, extensionName, this.t.getProvider(providerId).label);
    quickPick.placeholder = localize(12545, null, extensionName);
    return await new Promise((resolve, reject) => {
      disposables.add(quickPick.onDidAccept(async (_) => {
        quickPick.dispose();
        let session = quickPick.selectedItems[0].session;
        if (!session) {
          const account = quickPick.selectedItems[0].account;
          try {
            session = await this.t.createSession(providerId, scopes, { account });
          } catch (e) {
            reject(e);
            return;
          }
        }
        const accountName = session.account.label;
        this.w.updateAllowedExtensions(providerId, accountName, [{ id: extensionId, name: extensionName, allowed: true }]);
        this.H(providerId, extensionId, session);
        this.F(providerId, extensionId);
        resolve(session);
      }));
      disposables.add(quickPick.onDidHide((_) => {
        if (!quickPick.selectedItems[0]) {
          reject("User did not consent to account access");
        }
        disposables.dispose();
      }));
      quickPick.show();
    });
  }
  async J(provider, extensionId, extensionName, scopes) {
    const providerRequests = this.b.get(provider.id) || {};
    const existingRequest = providerRequests[extensionId];
    if (!existingRequest) {
      return;
    }
    if (!provider) {
      return;
    }
    const possibleSessions = existingRequest.possibleSessions;
    let session;
    if (provider.supportsMultipleAccounts) {
      try {
        session = await this.selectSession(provider.id, extensionId, extensionName, scopes, possibleSessions);
      } catch (_) {
      }
    } else {
      const approved = await this.I(provider, possibleSessions[0].account.label, extensionId, extensionName);
      if (approved) {
        session = possibleSessions[0];
      }
    }
    if (session) {
      this.u.addAccountUsage(provider.id, session.account.label, session.scopes, extensionId, extensionName);
    }
  }
  requestSessionAccess(providerId, extensionId, extensionName, scopes, possibleSessions) {
    const providerRequests = this.b.get(providerId) || {};
    const hasExistingRequest = providerRequests[extensionId];
    if (hasExistingRequest) {
      return;
    }
    const provider = this.t.getProvider(providerId);
    const menuItem = $dJ.appendMenuItem($bJ.AccountsContext, {
      group: "3_accessRequests",
      command: {
        id: `${providerId}${extensionId}Access`,
        title: localize(12546, null, provider.label, extensionName)
      }
    });
    const accessCommand = $tn.registerCommand({
      id: `${providerId}${extensionId}Access`,
      handler: async (accessor) => {
        this.J(provider, extensionId, extensionName, scopes);
      }
    });
    providerRequests[extensionId] = { possibleSessions, disposables: [menuItem, accessCommand] };
    this.b.set(providerId, providerRequests);
    this.D();
  }
  async requestNewSession(providerId, scopes, extensionId, extensionName) {
    if (!this.t.isAuthenticationProviderRegistered(providerId)) {
      await new Promise((resolve, _) => {
        const dispose = this.t.onDidRegisterAuthenticationProvider((e) => {
          if (e.id === providerId) {
            dispose.dispose();
            resolve();
          }
        });
      });
    }
    let provider;
    try {
      provider = this.t.getProvider(providerId);
    } catch (_e) {
      return;
    }
    const providerRequests = this.a.get(providerId);
    const scopesList = scopes.join(SCOPESLIST_SEPARATOR);
    const extensionHasExistingRequest = providerRequests && providerRequests[scopesList] && providerRequests[scopesList].requestingExtensionIds.includes(extensionId);
    if (extensionHasExistingRequest) {
      return;
    }
    const commandId = `${providerId}:${extensionId}:signIn${Object.keys(providerRequests || []).length}`;
    const menuItem = $dJ.appendMenuItem($bJ.AccountsContext, {
      group: "2_signInRequests",
      command: {
        id: commandId,
        title: localize(12547, null, provider.label, extensionName)
      }
    });
    const signInCommand = $tn.registerCommand({
      id: commandId,
      handler: async (accessor) => {
        const authenticationService = accessor.get($xS);
        const session = await authenticationService.createSession(providerId, scopes);
        this.w.updateAllowedExtensions(providerId, session.account.label, [{ id: extensionId, name: extensionName, allowed: true }]);
        this.H(providerId, extensionId, session);
      }
    });
    if (providerRequests) {
      const existingRequest = providerRequests[scopesList] || { disposables: [], requestingExtensionIds: [] };
      providerRequests[scopesList] = {
        disposables: [...existingRequest.disposables, menuItem, signInCommand],
        requestingExtensionIds: [...existingRequest.requestingExtensionIds, extensionId]
      };
      this.a.set(providerId, providerRequests);
    } else {
      this.a.set(providerId, {
        [scopesList]: {
          disposables: [menuItem, signInCommand],
          requestingExtensionIds: [extensionId]
        }
      });
    }
    this.D();
  }
};
$XXb = __decorate([
  __param(0, $vqb),
  __param(1, $jv),
  __param(2, $Yv),
  __param(3, $1M),
  __param(4, $Vu),
  __param(5, $xS),
  __param(6, $RCb),
  __param(7, $V4)
], $XXb);
$SC(
  $yS,
  $XXb,
  1
  /* InstantiationType.Delayed */
);

// out-build/vs/editor/browser/services/hoverService/hoverWidget.js
var $114 = $;
var Constants11;
(function(Constants27) {
  Constants27[Constants27["PointerSize"] = 3] = "PointerSize";
  Constants27[Constants27["HoverBorderWidth"] = 2] = "HoverBorderWidth";
  Constants27[Constants27["HoverWindowEdgeMargin"] = 2] = "HoverWindowEdgeMargin";
})(Constants11 || (Constants11 = {}));
var $YXb = class $YXb2 extends $qZ {
  get P() {
    return getWindow(this.r.targetElements[0]);
  }
  get Q() {
    return getWindow(this.r.targetElements[0]).document.documentElement;
  }
  get isDisposed() {
    return this.w;
  }
  get isMouseIn() {
    return this.c.isMouseIn;
  }
  get domNode() {
    return this.g.containerDomNode;
  }
  get onDispose() {
    return this.R.event;
  }
  get onRequestLayout() {
    return this.S.event;
  }
  get anchor() {
    return this.H === 2 ? 0 : 1;
  }
  get x() {
    return this.J;
  }
  get y() {
    return this.L;
  }
  /**
   * Whether the hover is "locked" by holding the alt/option key. When locked, the hover will not
   * hide and can be hovered regardless of whether the `hideOnHover` hover option is set.
   */
  get isLocked() {
    return this.M;
  }
  set isLocked(value) {
    if (this.M === value) {
      return;
    }
    this.M = value;
    this.n.classList.toggle("locked", this.M);
  }
  constructor(options3, U, W, X, Y, Z) {
    super();
    this.U = U;
    this.W = W;
    this.X = X;
    this.Y = Y;
    this.Z = Z;
    this.a = new $2c();
    this.w = false;
    this.I = false;
    this.J = 0;
    this.L = 0;
    this.M = false;
    this.N = false;
    this.O = false;
    this.R = this.B(new $ze());
    this.S = this.B(new $ze());
    this.t = options3.linkHandler || ((url) => {
      return $R_(this.X, url, $dm(options3.content) ? options3.content.isTrusted : void 0);
    });
    this.r = "targetElements" in options3.target ? options3.target : new ElementHoverTarget(options3.target);
    this.h = options3.appearance?.showPointer ? $114("div.workbench-hover-pointer") : void 0;
    this.g = this.B(new $DZ(!options3.appearance?.skipFadeInAnimation));
    this.g.containerDomNode.classList.add("workbench-hover");
    if (options3.appearance?.compact) {
      this.g.containerDomNode.classList.add("workbench-hover", "compact");
    }
    if (options3.additionalClasses) {
      this.g.containerDomNode.classList.add(...options3.additionalClasses);
    }
    if (options3.position?.forcePosition) {
      this.I = true;
    }
    if (options3.trapFocus) {
      this.N = true;
    }
    this.H = options3.position?.hoverPosition === void 0 ? 3 : $Dg(options3.position.hoverPosition) ? options3.position.hoverPosition : 2;
    this.f(this.g.containerDomNode, (e) => e.stopPropagation());
    this.s(this.g.containerDomNode, (e) => {
      if (e.equals(
        9
        /* KeyCode.Escape */
      )) {
        this.dispose();
      }
    });
    this.B($_i(this.P, "blur", () => this.dispose()));
    const rowElement = $114("div.hover-row.markdown-hover");
    const contentsElement = $114("div.hover-contents");
    if (typeof options3.content === "string") {
      contentsElement.textContent = options3.content;
      contentsElement.style.whiteSpace = "pre-wrap";
    } else if ($Uj(options3.content)) {
      contentsElement.appendChild(options3.content);
      contentsElement.classList.add("html-hover-contents");
    } else {
      const markdown = options3.content;
      const mdRenderer = this.Y.createInstance($Q_, { codeBlockFontFamily: this.W.getValue("editor").fontFamily || EDITOR_FONT_DEFAULTS.fontFamily });
      const { element } = mdRenderer.render(markdown, {
        actionHandler: {
          callback: (content) => this.t(content),
          disposables: this.a
        },
        asyncRenderCallback: () => {
          contentsElement.classList.add("code-hover-contents");
          this.layout();
          this.S.fire();
        }
      });
      contentsElement.appendChild(element);
    }
    rowElement.appendChild(contentsElement);
    this.g.contentsDomNode.appendChild(rowElement);
    if (options3.actions && options3.actions.length > 0) {
      const statusBarElement = $114("div.hover-row.status-bar");
      const actionsElement = $114("div.actions");
      options3.actions.forEach((action) => {
        const keybinding = this.U.lookupKeybinding(action.commandId);
        const keybindingLabel = keybinding ? keybinding.getLabel() : null;
        $EZ.render(actionsElement, {
          label: action.label,
          commandId: action.commandId,
          run: (e) => {
            action.run(e);
            this.dispose();
          },
          iconClass: action.iconClass
        }, keybindingLabel);
      });
      statusBarElement.appendChild(actionsElement);
      this.g.containerDomNode.appendChild(statusBarElement);
    }
    this.n = $114("div.workbench-hover-container");
    if (this.h) {
      this.n.appendChild(this.h);
    }
    this.n.appendChild(this.g.containerDomNode);
    let hideOnHover;
    if (options3.actions && options3.actions.length > 0) {
      hideOnHover = false;
    } else {
      if (options3.persistence?.hideOnHover === void 0) {
        hideOnHover = typeof options3.content === "string" || $dm(options3.content) && !options3.content.value.includes("](") && !options3.content.value.includes("</a>");
      } else {
        hideOnHover = options3.persistence.hideOnHover;
      }
    }
    if (options3.appearance?.showHoverHint) {
      const statusBarElement = $114("div.hover-row.status-bar");
      const infoElement = $114("div.info");
      infoElement.textContent = localize(192, null, $m ? "Option" : "Alt");
      statusBarElement.appendChild(infoElement);
      this.g.containerDomNode.appendChild(statusBarElement);
    }
    const mouseTrackerTargets = [...this.r.targetElements];
    if (!hideOnHover) {
      mouseTrackerTargets.push(this.n);
    }
    const mouseTracker = this.B(new CompositeMouseTracker(mouseTrackerTargets));
    this.B(mouseTracker.onMouseOut(() => {
      if (!this.M) {
        this.dispose();
      }
    }));
    if (hideOnHover) {
      const mouseTracker2Targets = [...this.r.targetElements, this.n];
      this.c = this.B(new CompositeMouseTracker(mouseTracker2Targets));
      this.B(this.c.onMouseOut(() => {
        if (!this.M) {
          this.dispose();
        }
      }));
    } else {
      this.c = mouseTracker;
    }
  }
  ab() {
    if (!this.N || this.O) {
      return;
    }
    this.O = true;
    const firstContainerFocusElement = this.g.containerDomNode;
    const lastContainerFocusElement = this.bb(this.g.containerDomNode);
    if (lastContainerFocusElement) {
      const beforeContainerFocusElement = $ck(this.n, $114("div"));
      const afterContainerFocusElement = $bk(this.n, $114("div"));
      beforeContainerFocusElement.tabIndex = 0;
      afterContainerFocusElement.tabIndex = 0;
      this.B($_i(afterContainerFocusElement, "focus", (e) => {
        firstContainerFocusElement.focus();
        e.preventDefault();
      }));
      this.B($_i(beforeContainerFocusElement, "focus", (e) => {
        lastContainerFocusElement.focus();
        e.preventDefault();
      }));
    }
  }
  bb(root) {
    if (root.hasChildNodes()) {
      for (let i2 = 0; i2 < root.childNodes.length; i2++) {
        const node = root.childNodes.item(root.childNodes.length - i2 - 1);
        if (node.nodeType === node.ELEMENT_NODE) {
          const parsedNode = node;
          if (typeof parsedNode.tabIndex === "number" && parsedNode.tabIndex >= 0) {
            return parsedNode;
          }
        }
        const recursivelyFoundElement = this.bb(node);
        if (recursivelyFoundElement) {
          return recursivelyFoundElement;
        }
      }
    }
    return void 0;
  }
  render(container2) {
    container2.appendChild(this.n);
    const hoverFocused = this.n.contains(this.n.ownerDocument.activeElement);
    const accessibleViewHint = hoverFocused && $FZ(this.W.getValue("accessibility.verbosity.hover") === true && this.Z.isScreenReaderOptimized(), this.U.lookupKeybinding("editor.action.accessibleView")?.getAriaLabel());
    if (accessibleViewHint) {
      $_Z(accessibleViewHint);
    }
    this.layout();
    this.ab();
  }
  layout() {
    this.g.containerDomNode.classList.remove("right-aligned");
    this.g.contentsDomNode.style.maxHeight = "";
    const getZoomAccountedBoundingClientRect = (e) => {
      const zoom = $wj(e);
      const boundingRect = e.getBoundingClientRect();
      return {
        top: boundingRect.top * zoom,
        bottom: boundingRect.bottom * zoom,
        right: boundingRect.right * zoom,
        left: boundingRect.left * zoom
      };
    };
    const targetBounds = this.r.targetElements.map((e) => getZoomAccountedBoundingClientRect(e));
    const { top: top2, right, bottom, left } = targetBounds[0];
    const width2 = right - left;
    const height = bottom - top2;
    const targetRect = {
      top: top2,
      right,
      bottom,
      left,
      width: width2,
      height,
      center: {
        x: left + width2 / 2,
        y: top2 + height / 2
      }
    };
    this.eb(targetRect);
    this.fb(targetRect);
    this.gb(targetRect);
    this.n.style.padding = "";
    this.n.style.margin = "";
    if (this.h) {
      switch (this.H) {
        case 1:
          targetRect.left += 3;
          targetRect.right += 3;
          this.n.style.paddingLeft = `${3}px`;
          this.n.style.marginLeft = `${-3}px`;
          break;
        case 0:
          targetRect.left -= 3;
          targetRect.right -= 3;
          this.n.style.paddingRight = `${3}px`;
          this.n.style.marginRight = `${-3}px`;
          break;
        case 2:
          targetRect.top += 3;
          targetRect.bottom += 3;
          this.n.style.paddingTop = `${3}px`;
          this.n.style.marginTop = `${-3}px`;
          break;
        case 3:
          targetRect.top -= 3;
          targetRect.bottom -= 3;
          this.n.style.paddingBottom = `${3}px`;
          this.n.style.marginBottom = `${-3}px`;
          break;
      }
      targetRect.center.x = targetRect.left + width2 / 2;
      targetRect.center.y = targetRect.top + height / 2;
    }
    this.cb(targetRect);
    this.db(targetRect);
    if (this.h) {
      this.h.classList.remove("top");
      this.h.classList.remove("left");
      this.h.classList.remove("right");
      this.h.classList.remove("bottom");
      this.hb(targetRect);
    }
    this.g.onContentsChanged();
  }
  cb(target) {
    const hoverWidth = this.g.containerDomNode.clientWidth + 2;
    if (this.r.x !== void 0) {
      this.J = this.r.x;
    } else if (this.H === 1) {
      this.J = target.right;
    } else if (this.H === 0) {
      this.J = target.left - hoverWidth;
    } else {
      if (this.h) {
        this.J = target.center.x - this.g.containerDomNode.clientWidth / 2;
      } else {
        this.J = target.left;
      }
      if (this.J + hoverWidth >= this.Q.clientWidth) {
        this.g.containerDomNode.classList.add("right-aligned");
        this.J = Math.max(this.Q.clientWidth - hoverWidth - 2, this.Q.clientLeft);
      }
    }
    if (this.J < this.Q.clientLeft) {
      this.J = target.left + 2;
    }
  }
  db(target) {
    if (this.r.y !== void 0) {
      this.L = this.r.y;
    } else if (this.H === 3) {
      this.L = target.top;
    } else if (this.H === 2) {
      this.L = target.bottom - 2;
    } else {
      if (this.h) {
        this.L = target.center.y + this.g.containerDomNode.clientHeight / 2;
      } else {
        this.L = target.bottom;
      }
    }
    if (this.L > this.P.innerHeight) {
      this.L = target.bottom;
    }
  }
  eb(target) {
    if (this.r.x !== void 0) {
      return;
    }
    const hoverPointerOffset = this.h ? 3 : 0;
    if (this.I) {
      const padding = hoverPointerOffset + 2;
      if (this.H === 1) {
        this.g.containerDomNode.style.maxWidth = `${this.Q.clientWidth - target.right - padding}px`;
      } else if (this.H === 0) {
        this.g.containerDomNode.style.maxWidth = `${target.left - padding}px`;
      }
      return;
    }
    if (this.H === 1) {
      const roomOnRight = this.Q.clientWidth - target.right;
      if (roomOnRight < this.g.containerDomNode.clientWidth + hoverPointerOffset) {
        const roomOnLeft = target.left;
        if (roomOnLeft >= this.g.containerDomNode.clientWidth + hoverPointerOffset) {
          this.H = 0;
        } else {
          this.H = 2;
        }
      }
    } else if (this.H === 0) {
      const roomOnLeft = target.left;
      if (roomOnLeft < this.g.containerDomNode.clientWidth + hoverPointerOffset) {
        const roomOnRight = this.Q.clientWidth - target.right;
        if (roomOnRight >= this.g.containerDomNode.clientWidth + hoverPointerOffset) {
          this.H = 1;
        } else {
          this.H = 2;
        }
      }
      if (target.left - this.g.containerDomNode.clientWidth - hoverPointerOffset <= this.Q.clientLeft) {
        this.H = 1;
      }
    }
  }
  fb(target) {
    if (this.r.y !== void 0 || this.I) {
      return;
    }
    const hoverPointerOffset = this.h ? 3 : 0;
    if (this.H === 3) {
      if (target.top - this.g.containerDomNode.clientHeight - hoverPointerOffset < 0) {
        this.H = 2;
      }
    } else if (this.H === 2) {
      if (target.bottom + this.g.containerDomNode.clientHeight + hoverPointerOffset > this.P.innerHeight) {
        this.H = 3;
      }
    }
  }
  gb(target) {
    let maxHeight = this.P.innerHeight / 2;
    if (this.I) {
      const padding = (this.h ? 3 : 0) + 2;
      if (this.H === 3) {
        maxHeight = Math.min(maxHeight, target.top - padding);
      } else if (this.H === 2) {
        maxHeight = Math.min(maxHeight, this.P.innerHeight - target.bottom - padding);
      }
    }
    this.g.containerDomNode.style.maxHeight = `${maxHeight}px`;
    if (this.g.contentsDomNode.clientHeight < this.g.contentsDomNode.scrollHeight) {
      const extraRightPadding = `${this.g.scrollbar.options.verticalScrollbarSize}px`;
      if (this.g.contentsDomNode.style.paddingRight !== extraRightPadding) {
        this.g.contentsDomNode.style.paddingRight = extraRightPadding;
      }
    }
  }
  hb(target) {
    if (!this.h) {
      return;
    }
    switch (this.H) {
      case 0:
      case 1: {
        this.h.classList.add(this.H === 0 ? "right" : "left");
        const hoverHeight = this.g.containerDomNode.clientHeight;
        if (hoverHeight > target.height) {
          this.h.style.top = `${target.center.y - (this.L - hoverHeight) - 3}px`;
        } else {
          this.h.style.top = `${Math.round(hoverHeight / 2) - 3}px`;
        }
        break;
      }
      case 3:
      case 2: {
        this.h.classList.add(this.H === 3 ? "bottom" : "top");
        const hoverWidth = this.g.containerDomNode.clientWidth;
        let pointerLeftPosition = Math.round(hoverWidth / 2) - 3;
        const pointerX = this.J + pointerLeftPosition;
        if (pointerX < target.left || pointerX > target.right) {
          pointerLeftPosition = target.center.x - this.J - 3;
        }
        this.h.style.left = `${pointerLeftPosition}px`;
        break;
      }
    }
  }
  focus() {
    this.g.containerDomNode.focus();
  }
  hide() {
    this.dispose();
  }
  dispose() {
    if (!this.w) {
      this.R.fire();
      this.r.dispose?.();
      this.n.remove();
      this.a.dispose();
      super.dispose();
    }
    this.w = true;
  }
};
$YXb = __decorate([
  __param(1, $Ty),
  __param(2, $kl),
  __param(3, $O4),
  __param(4, $Pk),
  __param(5, $ND)
], $YXb);
var CompositeMouseTracker = class extends $qZ {
  get onMouseOut() {
    return this.g.event;
  }
  get isMouseIn() {
    return this.a;
  }
  /**
   * @param h The target elements to track mouse in/out events on.
   * @param n The delay in ms to debounce the event firing. This is used to
   * allow a short period for the mouse to move into the hover or a nearby target element. For
   * example hovering a scroll bar will not hide the hover immediately.
   */
  constructor(h3, n = 200) {
    super();
    this.h = h3;
    this.n = n;
    this.a = true;
    this.c = this.B(new $4c());
    this.g = this.B(new $ze());
    for (const element of this.h) {
      this.j(element, () => this.r());
      this.m(element, () => this.t());
    }
  }
  r() {
    this.a = true;
    this.c.clear();
  }
  t() {
    this.a = false;
    this.c.value = new $6h(() => this.w(), this.n);
  }
  w() {
    if (!this.a) {
      this.g.fire();
    }
  }
};
var ElementHoverTarget = class {
  constructor(a) {
    this.a = a;
    this.targetElements = [this.a];
  }
  dispose() {
  }
};

// out-build/vs/platform/contextview/browser/contextViewService.js
var $ZXb = class $ZXb2 extends $3c {
  constructor(c) {
    super();
    this.c = c;
    this.b = this.B(new $PZ(
      this.c.mainContainer,
      1
      /* ContextViewDOMPosition.ABSOLUTE */
    ));
    this.layout();
    this.B(c.onDidLayoutContainer(() => this.layout()));
  }
  // ContextView
  showContextView(delegate, container2, shadowRoot) {
    let domPosition;
    if (container2) {
      if (container2 === this.c.getContainer(getWindow(container2))) {
        domPosition = 1;
      } else if (shadowRoot) {
        domPosition = 3;
      } else {
        domPosition = 2;
      }
    } else {
      domPosition = 1;
    }
    this.b.setContainer(container2 ?? this.c.activeContainer, domPosition);
    this.b.show(delegate);
    const openContextView = {
      close: () => {
        if (this.a === openContextView) {
          this.hideContextView();
        }
      }
    };
    this.a = openContextView;
    return openContextView;
  }
  layout() {
    this.b.layout();
  }
  hideContextView(data) {
    this.b.hide(data);
    this.a = void 0;
  }
};
$ZXb = __decorate([
  __param(0, $Ulb)
], $ZXb);
var $1Xb = class extends $ZXb {
  getContextViewElement() {
    return this.b.getViewElement();
  }
};

// out-build/vs/editor/browser/services/hoverService/updatableHoverWidget.js
var $2Xb = class {
  constructor(c, d, e) {
    this.c = c;
    this.d = d;
    this.e = e;
  }
  async update(content, focus, options3) {
    if (this.b) {
      this.b.dispose(true);
      this.b = void 0;
    }
    if (this.isDisposed) {
      return;
    }
    let resolvedContent;
    if (content === void 0 || $zg(content) || $Uj(content)) {
      resolvedContent = content;
    } else if (!$Ng(content.markdown)) {
      resolvedContent = content.markdown ?? content.markdownNotSupportedFallback;
    } else {
      if (!this.a) {
        this.f(localize(193, null), focus, options3);
      }
      this.b = new $ad();
      const token = this.b.token;
      resolvedContent = await content.markdown(token);
      if (resolvedContent === void 0) {
        resolvedContent = content.markdownNotSupportedFallback;
      }
      if (this.isDisposed || token.isCancellationRequested) {
        return;
      }
    }
    this.f(resolvedContent, focus, options3);
  }
  f(content, focus, options3) {
    const oldHoverWidget = this.a;
    if (this.g(content)) {
      const hoverOptions = {
        content,
        target: this.d,
        actions: options3?.actions,
        linkHandler: options3?.linkHandler,
        trapFocus: options3?.trapFocus,
        appearance: {
          showPointer: this.c.placement === "element",
          skipFadeInAnimation: !this.e || !!oldHoverWidget,
          // do not fade in if the hover is already showing
          showHoverHint: options3?.appearance?.showHoverHint
        },
        position: {
          hoverPosition: 2
        }
      };
      this.a = this.c.showHover(hoverOptions, focus);
    }
    oldHoverWidget?.dispose();
  }
  g(content) {
    if (!content) {
      return false;
    }
    if ($dm(content)) {
      return !!content.value;
    }
    return true;
  }
  get isDisposed() {
    return this.a?.isDisposed;
  }
  dispose() {
    this.a?.dispose();
    this.b?.dispose(true);
    this.b = void 0;
  }
};

// out-build/vs/editor/browser/services/hoverService/hoverService.js
var $3Xb = class $3Xb2 extends $3c {
  constructor(n, r2, contextMenuService, s, t, u) {
    super();
    this.n = n;
    this.r = r2;
    this.s = s;
    this.t = t;
    this.u = u;
    this.g = false;
    this.I = /* @__PURE__ */ new Map();
    contextMenuService.onDidShowContextMenu(() => this.hideHover());
    this.a = this.B(new $ZXb(this.t));
  }
  showHover(options3, focus, skipLastFocusedUpdate, dontShow) {
    const hover = this.z(options3, skipLastFocusedUpdate);
    if (!hover) {
      return void 0;
    }
    this.C(hover, options3, focus);
    return hover;
  }
  showDelayedHover(options3, lifecycleOptions) {
    if (!this.f || this.g) {
      if (this.c && this.b?.persistence?.sticky) {
        return void 0;
      }
      if (getHoverOptionsIdentity(this.b) === getHoverOptionsIdentity(options3)) {
        return this.c;
      }
      if (this.c && !this.c.isDisposed && this.h !== void 0 && this.h === lifecycleOptions?.groupId) {
        return this.showHover({
          ...options3,
          appearance: {
            ...options3.appearance,
            skipFadeInAnimation: true
          }
        });
      }
    }
    const hover = this.z(options3, void 0);
    if (!hover) {
      this.f = void 0;
      this.g = false;
      this.h = void 0;
      return void 0;
    }
    this.f = hover;
    this.g = false;
    this.h = lifecycleOptions?.groupId;
    $Wh(this.r.getValue("workbench.hover.delay")).then(() => {
      if (hover && !hover.isDisposed) {
        this.g = true;
        this.g = true;
        this.C(hover, options3);
      }
    });
    return hover;
  }
  setupDelayedHover(target, options3, lifecycleOptions) {
    const resolveHoverOptions = () => ({
      ...typeof options3 === "function" ? options3() : options3,
      target
    });
    return this.w(target, resolveHoverOptions, lifecycleOptions);
  }
  setupDelayedHoverAtMouse(target, options3, lifecycleOptions) {
    const resolveHoverOptions = (e) => ({
      ...typeof options3 === "function" ? options3() : options3,
      target: {
        targetElements: [target],
        x: e !== void 0 ? e.x + 10 : void 0
      }
    });
    return this.w(target, resolveHoverOptions, lifecycleOptions);
  }
  w(target, resolveHoverOptions, lifecycleOptions) {
    const store = new $2c();
    store.add($_i(target, $7j.MOUSE_OVER, (e) => {
      this.showDelayedHover(resolveHoverOptions(e), {
        groupId: lifecycleOptions?.groupId
      });
    }));
    if (lifecycleOptions?.setupKeyboardEvents) {
      store.add($_i(target, $7j.KEY_DOWN, (e) => {
        const evt = new $if(e);
        if (evt.equals(
          10
          /* KeyCode.Space */
        ) || evt.equals(
          3
          /* KeyCode.Enter */
        )) {
          this.showHover(resolveHoverOptions(), true);
        }
      }));
    }
    return store;
  }
  z(options3, skipLastFocusedUpdate) {
    this.f = void 0;
    if (this.c && this.b?.persistence?.sticky) {
      return void 0;
    }
    if (getHoverOptionsIdentity(this.b) === getHoverOptionsIdentity(options3)) {
      return void 0;
    }
    this.b = options3;
    this.j = options3;
    const trapFocus = options3.trapFocus || this.u.isScreenReaderOptimized();
    const activeElement = $Lj();
    if (!skipLastFocusedUpdate) {
      if (trapFocus && activeElement) {
        if (!activeElement.classList.contains("monaco-hover")) {
          this.m = activeElement;
        }
      } else {
        this.m = void 0;
      }
    }
    if (options3.id === void 0) {
      options3.id = $Uj(options3.content) ? void 0 : typeof options3.content === "string" ? options3.content.toString() : options3.content.value;
    }
    const hoverDisposables = new $2c();
    const hover = this.n.createInstance($YXb, options3);
    if (options3.persistence?.sticky) {
      hover.isLocked = true;
    }
    if (options3.position?.hoverPosition && !$Dg(options3.position.hoverPosition)) {
      options3.target = {
        targetElements: $Uj(options3.target) ? [options3.target] : options3.target.targetElements,
        x: options3.position.hoverPosition.x + 10
      };
    }
    hover.onDispose(() => {
      const hoverWasFocused = this.c?.domNode && $Nj(this.c.domNode);
      if (hoverWasFocused) {
        this.m?.focus();
      }
      if (getHoverOptionsIdentity(this.b) === getHoverOptionsIdentity(options3)) {
        this.b = void 0;
      }
      hoverDisposables.dispose();
    }, void 0, hoverDisposables);
    if (!options3.container) {
      const targetElement = $Uj(options3.target) ? options3.target : options3.target.targetElements[0];
      options3.container = this.t.getContainer(getWindow(targetElement));
    }
    hover.onRequestLayout(() => this.a.layout(), void 0, hoverDisposables);
    if (options3.persistence?.sticky) {
      hoverDisposables.add($_i(getWindow(options3.container).document, $7j.MOUSE_DOWN, (e) => {
        if (!$Dj(e.target, hover.domNode)) {
          this.D();
        }
      }));
    } else {
      if ("targetElements" in options3.target) {
        for (const element of options3.target.targetElements) {
          hoverDisposables.add($_i(element, $7j.CLICK, () => this.hideHover()));
        }
      } else {
        hoverDisposables.add($_i(options3.target, $7j.CLICK, () => this.hideHover()));
      }
      const focusedElement = $Lj();
      if (focusedElement) {
        const focusedElementDocument = getWindow(focusedElement).document;
        hoverDisposables.add($_i(focusedElement, $7j.KEY_DOWN, (e) => this.G(e, hover, !!options3.persistence?.hideOnKeyDown)));
        hoverDisposables.add($_i(focusedElementDocument, $7j.KEY_DOWN, (e) => this.G(e, hover, !!options3.persistence?.hideOnKeyDown)));
        hoverDisposables.add($_i(focusedElement, $7j.KEY_UP, (e) => this.H(e, hover)));
        hoverDisposables.add($_i(focusedElementDocument, $7j.KEY_UP, (e) => this.H(e, hover)));
      }
    }
    if ("IntersectionObserver" in $Y) {
      const observer = new IntersectionObserver((e) => this.F(e, hover), { threshold: 0 });
      const firstTargetElement = "targetElements" in options3.target ? options3.target.targetElements[0] : options3.target;
      observer.observe(firstTargetElement);
      hoverDisposables.add($1c(() => observer.disconnect()));
    }
    this.c = hover;
    return hover;
  }
  C(hover, options3, focus) {
    this.a.showContextView(new HoverContextViewDelegate(hover, focus), options3.container);
  }
  hideHover() {
    if (this.c?.isLocked || !this.b) {
      return;
    }
    this.D();
  }
  D() {
    this.c = void 0;
    this.b = void 0;
    this.a.hideContextView();
  }
  F(entries2, hover) {
    const entry = entries2[entries2.length - 1];
    if (!entry.isIntersecting) {
      hover.dispose();
    }
  }
  showAndFocusLastHover() {
    if (!this.j) {
      return;
    }
    this.showHover(this.j, true, true);
  }
  G(e, hover, hideOnKeyDown) {
    if (e.key === "Alt") {
      hover.isLocked = true;
      return;
    }
    const event = new $if(e);
    const keybinding = this.s.resolveKeyboardEvent(event);
    if (keybinding.getSingleModifierDispatchChords().some((value) => !!value) || this.s.softDispatch(event, event.target).kind !== 0) {
      return;
    }
    if (hideOnKeyDown && (!this.b?.trapFocus || e.key !== "Tab")) {
      this.hideHover();
      this.m?.focus();
    }
  }
  H(e, hover) {
    if (e.key === "Alt") {
      hover.isLocked = false;
      if (!hover.isMouseIn) {
        this.hideHover();
        this.m?.focus();
      }
    }
  }
  // TODO: Investigate performance of this function. There seems to be a lot of content created
  //       and thrown away on start up
  setupManagedHover(hoverDelegate, targetElement, content, options3) {
    targetElement.setAttribute("custom-hover", "true");
    if (targetElement.title !== "") {
      console.warn("HTML element already has a title attribute, which will conflict with the custom hover. Please remove the title attribute.");
      console.trace("Stack trace:", targetElement.title);
      targetElement.title = "";
    }
    let hoverPreparation;
    let hoverWidget;
    const hideHover = (disposeWidget, disposePreparation) => {
      const hadHover = hoverWidget !== void 0;
      if (disposeWidget) {
        hoverWidget?.dispose();
        hoverWidget = void 0;
      }
      if (disposePreparation) {
        hoverPreparation?.dispose();
        hoverPreparation = void 0;
      }
      if (hadHover) {
        hoverDelegate.onDidHideHover?.();
        hoverWidget = void 0;
      }
    };
    const triggerShowHover = (delay, focus, target, trapFocus) => {
      return new $6h(async () => {
        if (!hoverWidget || hoverWidget.isDisposed) {
          hoverWidget = new $2Xb(hoverDelegate, target || targetElement, delay > 0);
          await hoverWidget.update(typeof content === "function" ? content() : content, focus, { ...options3, trapFocus });
        }
      }, delay);
    };
    const store = new $2c();
    let isMouseDown = false;
    store.add($_i(targetElement, $7j.MOUSE_DOWN, () => {
      isMouseDown = true;
      hideHover(true, true);
    }, true));
    store.add($_i(targetElement, $7j.MOUSE_UP, () => {
      isMouseDown = false;
    }, true));
    store.add($_i(targetElement, $7j.MOUSE_LEAVE, (e) => {
      isMouseDown = false;
      hideHover(false, e.fromElement === targetElement);
    }, true));
    store.add($_i(targetElement, $7j.MOUSE_OVER, (e) => {
      if (hoverPreparation) {
        return;
      }
      const mouseOverStore = new $2c();
      const target = {
        targetElements: [targetElement],
        dispose: () => {
        }
      };
      if (hoverDelegate.placement === void 0 || hoverDelegate.placement === "mouse") {
        const onMouseMove = (e2) => {
          target.x = e2.x + 10;
          if ($Uj(e2.target) && getHoverTargetElement(e2.target, targetElement) !== targetElement) {
            hideHover(true, true);
          }
        };
        mouseOverStore.add($_i(targetElement, $7j.MOUSE_MOVE, onMouseMove, true));
      }
      hoverPreparation = mouseOverStore;
      if ($Uj(e.target) && getHoverTargetElement(e.target, targetElement) !== targetElement) {
        return;
      }
      mouseOverStore.add(triggerShowHover(hoverDelegate.delay, false, target));
    }, true));
    const onFocus = () => {
      if (isMouseDown || hoverPreparation) {
        return;
      }
      const target = {
        targetElements: [targetElement],
        dispose: () => {
        }
      };
      const toDispose = new $2c();
      const onBlur = () => hideHover(true, true);
      toDispose.add($_i(targetElement, $7j.BLUR, onBlur, true));
      toDispose.add(triggerShowHover(hoverDelegate.delay, false, target));
      hoverPreparation = toDispose;
    };
    if (!$Fk(targetElement)) {
      store.add($_i(targetElement, $7j.FOCUS, onFocus, true));
    }
    const hover = {
      show: (focus) => {
        hideHover(false, true);
        triggerShowHover(0, focus, void 0, focus);
      },
      hide: () => {
        hideHover(true, true);
      },
      update: async (newContent, hoverOptions) => {
        content = newContent;
        await hoverWidget?.update(content, void 0, hoverOptions);
      },
      dispose: () => {
        this.I.delete(targetElement);
        store.dispose();
        hideHover(true, true);
      }
    };
    this.I.set(targetElement, hover);
    return hover;
  }
  showManagedHover(target) {
    const hover = this.I.get(target);
    if (hover) {
      hover.show(true);
    }
  }
  dispose() {
    this.I.forEach((hover) => hover.dispose());
    super.dispose();
  }
};
$3Xb = __decorate([
  __param(0, $Pk),
  __param(1, $kl),
  __param(2, $50),
  __param(3, $Ty),
  __param(4, $Ulb),
  __param(5, $ND)
], $3Xb);
function getHoverOptionsIdentity(options3) {
  if (options3 === void 0) {
    return void 0;
  }
  return options3?.id ?? options3;
}
var HoverContextViewDelegate = class {
  get anchorPosition() {
    return this.a.anchor;
  }
  constructor(a, b = false) {
    this.a = a;
    this.b = b;
    this.layer = 1;
  }
  render(container2) {
    this.a.render(container2);
    if (this.b) {
      this.a.focus();
    }
    return this.a;
  }
  getAnchor() {
    return {
      x: this.a.x,
      y: this.a.y
    };
  }
  layout() {
    this.a.layout();
  }
};
function getHoverTargetElement(element, stopElement) {
  stopElement = stopElement ?? getWindow(element).document.body;
  while (!element.hasAttribute("custom-hover") && element !== stopElement) {
    element = element.parentElement;
  }
  return element;
}
$SC(
  $5$,
  $3Xb,
  1
  /* InstantiationType.Delayed */
);
$ms((theme, collector) => {
  const hoverBorder = theme.getColor($lp);
  if (hoverBorder) {
    collector.addRule(`.monaco-workbench .workbench-hover .hover-row:not(:first-child):not(:empty) { border-top: 1px solid ${hoverBorder.transparent(0.5)}; }`);
    collector.addRule(`.monaco-workbench .workbench-hover hr { border-top: 1px solid ${hoverBorder.transparent(0.5)}; }`);
  }
});

// out-build/vs/platform/assignment/common/assignment.js
var $dFb = "VSCode.ABExp.FeatureData";
var $eFb = 0;
var TargetPopulation;
(function(TargetPopulation2) {
  TargetPopulation2["Insiders"] = "insider";
  TargetPopulation2["Public"] = "public";
  TargetPopulation2["Exploration"] = "exploration";
})(TargetPopulation || (TargetPopulation = {}));
var Filters;
(function(Filters2) {
  Filters2["Market"] = "X-MSEdge-Market";
  Filters2["CorpNet"] = "X-FD-Corpnet";
  Filters2["ApplicationVersion"] = "X-VSCode-AppVersion";
  Filters2["Build"] = "X-VSCode-Build";
  Filters2["ClientId"] = "X-MSEdge-ClientId";
  Filters2["ExtensionName"] = "X-VSCode-ExtensionName";
  Filters2["ExtensionVersion"] = "X-VSCode-ExtensionVersion";
  Filters2["Language"] = "X-VSCode-Language";
  Filters2["TargetPopulation"] = "X-VSCode-TargetPopulation";
})(Filters || (Filters = {}));
var $fFb = class _$fFb {
  constructor(a, b, c, d) {
    this.a = a;
    this.b = b;
    this.c = c;
    this.d = d;
  }
  /**
   * Returns a version string that can be parsed by the TAS client.
   * The tas client cannot handle suffixes lke "-insider"
   * Ref: https://github.com/microsoft/tas-client/blob/30340d5e1da37c2789049fcf45928b954680606f/vscode-tas-client/src/vscode-tas-client/VSCodeFilterProvider.ts#L35
   *
   * @param version Version string to be trimmed.
  */
  static e(version2) {
    const regex = /\-[a-zA-Z0-9]+$/;
    const result = version2.split(regex);
    return result[0];
  }
  getFilterValue(filter) {
    switch (filter) {
      case Filters.ApplicationVersion:
        return _$fFb.e(this.a);
      case Filters.Build:
        return this.b;
      case Filters.ClientId:
        return this.c;
      case Filters.Language:
        return $z;
      case Filters.ExtensionName:
        return "vscode-core";
      case Filters.ExtensionVersion:
        return "999999.0";
      case Filters.TargetPopulation:
        return this.d;
      default:
        return "";
    }
  }
  getFilters() {
    const filters2 = /* @__PURE__ */ new Map();
    const filterValues = Object.values(Filters);
    for (const value of filterValues) {
      filters2.set(value, this.getFilterValue(value));
    }
    return filters2;
  }
};

// out-build/vs/platform/assignment/common/assignmentService.js
var $gFb = class {
  get d() {
    return true;
  }
  constructor(e, f, g, h3, i2, j) {
    this.e = e;
    this.f = f;
    this.g = g;
    this.h = h3;
    this.i = i2;
    this.j = j;
    this.b = false;
    const isTesting = h3.extensionTestsLocationURI !== void 0;
    if (!isTesting && g.tasConfig && this.d && $kw(this.f) === 3) {
      this.a = this.k();
    }
    const overrideDelaySetting = this.f.getValue("experiments.overrideDelay");
    const overrideDelay = typeof overrideDelaySetting === "number" ? overrideDelaySetting : 0;
    this.c = new Promise((resolve) => setTimeout(resolve, overrideDelay));
  }
  async getTreatment(name) {
    await this.c;
    const override = this.f.getValue("experiments.override." + name);
    if (override !== void 0) {
      return override;
    }
    if (!this.a) {
      return void 0;
    }
    if (!this.d) {
      return void 0;
    }
    let result;
    const client = await this.a;
    if (this.b) {
      result = client.getTreatmentVariable("vscode", name);
    } else {
      result = await client.getTreatmentVariableAsync("vscode", name, true);
    }
    result = client.getTreatmentVariable("vscode", name);
    return result;
  }
  async k() {
    const targetPopulation = this.g.quality === "stable" ? TargetPopulation.Public : this.g.quality === "exploration" ? TargetPopulation.Exploration : TargetPopulation.Insiders;
    const filterProvider = new $fFb(this.g.version, this.g.nameLong, this.e, targetPopulation);
    const tasConfig = this.g.tasConfig;
    const tasClient = new (await $sJ("tas-client-umd", "lib/tas-client-umd.js")).ExperimentationService({
      filterProviders: [filterProvider],
      telemetry: this.i,
      storageKey: $dFb,
      keyValueStorage: this.j,
      assignmentContextTelemetryPropertyName: tasConfig.assignmentContextTelemetryPropertyName,
      telemetryEventName: tasConfig.telemetryEventName,
      endpoint: tasConfig.endpoint,
      refetchInterval: $eFb
    });
    await tasClient.initializePromise;
    tasClient.initialFetch.then(() => this.b = true);
    return tasClient;
  }
};

// out-build/vs/workbench/services/assignment/common/assignmentService.js
var $hFb = $Qk("WorkbenchAssignmentService");
var MementoKeyValueStorage = class {
  constructor(b) {
    this.b = b;
    this.a = b.getMemento(
      -1,
      1
      /* StorageTarget.MACHINE */
    );
  }
  async getValue(key2, defaultValue) {
    const value = await this.a[key2];
    return value || defaultValue;
  }
  setValue(key2, value) {
    this.a[key2] = value;
    this.b.saveMemento();
  }
};
var WorkbenchAssignmentServiceTelemetry = class {
  constructor(b, c) {
    this.b = b;
    this.c = c;
  }
  get assignmentContext() {
    return this.a?.split(";");
  }
  // __GDPR__COMMON__ "abexp.assignmentcontext" : { "classification": "SystemMetaData", "purpose": "FeatureInsight" }
  setSharedProperty(name, value) {
    if (name === this.c.tasConfig?.assignmentContextTelemetryPropertyName) {
      this.a = value;
    }
    this.b.setExperimentProperty(name, value);
  }
  postEvent(eventName, props) {
    const data = {};
    for (const [key2, value] of props.entries()) {
      data[key2] = value;
    }
    this.b.publicLog(eventName, data);
  }
};
var $iFb = class $iFb2 extends $gFb {
  constructor(l, storageService, configurationService, productService, environmentService) {
    super(l.machineId, configurationService, productService, environmentService, new WorkbenchAssignmentServiceTelemetry(l, productService), new MementoKeyValueStorage(new $Slb("experiment.service.memento", storageService)));
    this.l = l;
  }
  get d() {
    return this.f.getValue("workbench.enableExperiments") === true;
  }
  async getTreatment(name) {
    const result = await super.getTreatment(name);
    this.l.publicLog2("tasClientReadTreatmentComplete", { treatmentName: name, treatmentValue: JSON.stringify(result) });
    return result;
  }
  async getCurrentExperiments() {
    if (!this.a) {
      return void 0;
    }
    if (!this.d) {
      return void 0;
    }
    await this.a;
    return this.i?.assignmentContext;
  }
};
$iFb = __decorate([
  __param(0, $zv),
  __param(1, $jv),
  __param(2, $kl),
  __param(3, $Vu),
  __param(4, $Xk)
], $iFb);
$SC(
  $hFb,
  $iFb,
  1
  /* InstantiationType.Delayed */
);
var registry2 = $Wn.as($Ht.Configuration);
registry2.registerConfiguration({
  ...$UL,
  "properties": {
    "workbench.enableExperiments": {
      "type": "boolean",
      "description": localize(12538, null),
      "default": true,
      "scope": 1,
      "restricted": true,
      "tags": ["usesOnlineServices"]
    }
  }
});

// out-build/vs/workbench/services/outline/browser/outlineService.js
var OutlineService = class {
  constructor() {
    this.a = new $cd();
    this.b = new $ze();
    this.onDidChange = this.b.event;
  }
  canCreateOutline(pane) {
    for (const factory of this.a) {
      if (factory.matches(pane)) {
        return true;
      }
    }
    return false;
  }
  async createOutline(pane, target, token) {
    for (const factory of this.a) {
      if (factory.matches(pane)) {
        return await factory.createOutline(pane, target, token);
      }
    }
    return void 0;
  }
  registerOutlineCreator(creator) {
    const rm = this.a.push(creator);
    this.b.fire();
    return $1c(() => {
      rm();
      this.b.fire();
    });
  }
};
$SC(
  $vyb,
  OutlineService,
  1
  /* InstantiationType.Delayed */
);

// out-build/vs/platform/diagnostics/common/diagnostics.js
var ID2 = "diagnosticsService";
var $Hx = $Qk(ID2);
function $Ix(x) {
  return !!x.hostName && !!x.errorMessage;
}
var $Jx = class {
  async getPerformanceInfo(mainProcessInfo, remoteInfo) {
    return {};
  }
  async getSystemInfo(mainProcessInfo, remoteInfo) {
    return {
      processArgs: "nullProcessArgs",
      gpuStatus: "nullGpuStatus",
      screenReader: "nullScreenReader",
      remoteData: [],
      os: "nullOs",
      memory: "nullMemory",
      vmHint: "nullVmHint"
    };
  }
  async getDiagnostics(mainProcessInfo, remoteInfo) {
    return "";
  }
  async getWorkspaceFileExtensions(workspace2) {
    return { extensions: [] };
  }
  async reportWorkspaceStats(workspace2) {
  }
};

// out-build/vs/editor/common/model/mirrorTextModel.js
var $zM = class {
  constructor(uri, lines, eol, versionId) {
    this.a = uri;
    this.b = lines;
    this.c = eol;
    this.d = versionId;
    this.f = null;
    this.g = null;
  }
  dispose() {
    this.b.length = 0;
  }
  get version() {
    return this.d;
  }
  getText() {
    if (this.g === null) {
      this.g = this.b.join(this.c);
    }
    return this.g;
  }
  onEvents(e) {
    if (e.eol && e.eol !== this.c) {
      this.c = e.eol;
      this.f = null;
    }
    const changes = e.changes;
    for (const change of changes) {
      this.k(change.range);
      this.l(new $8C(change.range.startLineNumber, change.range.startColumn), change.text);
    }
    this.d = e.versionId;
    this.g = null;
  }
  h() {
    if (!this.f) {
      const eolLength = this.c.length;
      const linesLength = this.b.length;
      const lineStartValues = new Uint32Array(linesLength);
      for (let i2 = 0; i2 < linesLength; i2++) {
        lineStartValues[i2] = this.b[i2].length + eolLength;
      }
      this.f = new $wM(lineStartValues);
    }
  }
  /**
   * All changes to a line's text go through this method
   */
  j(lineIndex, newValue) {
    this.b[lineIndex] = newValue;
    if (this.f) {
      this.f.setValue(lineIndex, this.b[lineIndex].length + this.c.length);
    }
  }
  k(range) {
    if (range.startLineNumber === range.endLineNumber) {
      if (range.startColumn === range.endColumn) {
        return;
      }
      this.j(range.startLineNumber - 1, this.b[range.startLineNumber - 1].substring(0, range.startColumn - 1) + this.b[range.startLineNumber - 1].substring(range.endColumn - 1));
      return;
    }
    this.j(range.startLineNumber - 1, this.b[range.startLineNumber - 1].substring(0, range.startColumn - 1) + this.b[range.endLineNumber - 1].substring(range.endColumn - 1));
    this.b.splice(range.startLineNumber, range.endLineNumber - range.startLineNumber);
    if (this.f) {
      this.f.removeValues(range.startLineNumber, range.endLineNumber - range.startLineNumber);
    }
  }
  l(position, insertText) {
    if (insertText.length === 0) {
      return;
    }
    const insertLines = $Mf(insertText);
    if (insertLines.length === 1) {
      this.j(position.lineNumber - 1, this.b[position.lineNumber - 1].substring(0, position.column - 1) + insertLines[0] + this.b[position.lineNumber - 1].substring(position.column - 1));
      return;
    }
    insertLines[insertLines.length - 1] += this.b[position.lineNumber - 1].substring(position.column - 1);
    this.j(position.lineNumber - 1, this.b[position.lineNumber - 1].substring(0, position.column - 1) + insertLines[0]);
    const newLengths = new Uint32Array(insertLines.length - 1);
    for (let i2 = 1; i2 < insertLines.length; i2++) {
      this.b.splice(position.lineNumber + i2 - 1, 0, insertLines[i2]);
      newLengths[i2 - 1] = insertLines[i2].length + this.c.length;
    }
    if (this.f) {
      this.f.insertValues(position.lineNumber, newLengths);
    }
  }
};

// out-build/vs/editor/common/services/textModelSync/textModelSync.impl.js
var $A0 = 60 * 1e3;
var $B0 = "workerTextModelSync";
var $C0 = class _$C0 extends $3c {
  static create(workerClient, modelService) {
    return new _$C0(workerClient.getChannel($B0), modelService);
  }
  constructor(proxy, modelService, keepIdleModels = false) {
    super();
    this.c = /* @__PURE__ */ Object.create(null);
    this.f = /* @__PURE__ */ Object.create(null);
    this.a = proxy;
    this.b = modelService;
    if (!keepIdleModels) {
      const timer = new $7h();
      timer.cancelAndSet(() => this.g(), Math.round($A0 / 2));
      this.B(timer);
    }
  }
  dispose() {
    for (const modelUrl in this.c) {
      $Xc(this.c[modelUrl]);
    }
    this.c = /* @__PURE__ */ Object.create(null);
    this.f = /* @__PURE__ */ Object.create(null);
    super.dispose();
  }
  ensureSyncedResources(resources, forceLargeModels = false) {
    for (const resource of resources) {
      const resourceStr = resource.toString();
      if (!this.c[resourceStr]) {
        this.h(resource, forceLargeModels);
      }
      if (this.c[resourceStr]) {
        this.f[resourceStr] = (/* @__PURE__ */ new Date()).getTime();
      }
    }
  }
  g() {
    const currentTime = (/* @__PURE__ */ new Date()).getTime();
    const toRemove = [];
    for (const modelUrl in this.f) {
      const elapsedTime = currentTime - this.f[modelUrl];
      if (elapsedTime > $A0) {
        toRemove.push(modelUrl);
      }
    }
    for (const e of toRemove) {
      this.j(e);
    }
  }
  h(resource, forceLargeModels) {
    const model = this.b.getModel(resource);
    if (!model) {
      return;
    }
    if (!forceLargeModels && model.isTooLargeForSyncing()) {
      return;
    }
    const modelUrl = resource.toString();
    this.a.$acceptNewModel({
      url: model.uri.toString(),
      lines: model.getLinesContent(),
      EOL: model.getEOL(),
      versionId: model.getVersionId()
    });
    const toDispose = new $2c();
    toDispose.add(model.onDidChangeContent((e) => {
      this.a.$acceptModelChanged(modelUrl.toString(), e);
    }));
    toDispose.add(model.onWillDispose(() => {
      this.j(modelUrl);
    }));
    toDispose.add($1c(() => {
      this.a.$acceptRemovedModel(modelUrl);
    }));
    this.c[modelUrl] = toDispose;
  }
  j(modelUrl) {
    const toDispose = this.c[modelUrl];
    delete this.c[modelUrl];
    delete this.f[modelUrl];
    $Xc(toDispose);
  }
};
var $D0 = class {
  constructor() {
    this.a = /* @__PURE__ */ Object.create(null);
  }
  bindToServer(workerServer) {
    workerServer.setChannel($B0, this);
  }
  getModel(uri) {
    return this.a[uri];
  }
  getModels() {
    const all = [];
    Object.keys(this.a).forEach((key2) => all.push(this.a[key2]));
    return all;
  }
  $acceptNewModel(data) {
    this.a[data.url] = new $E0(URI.parse(data.url), data.lines, data.EOL, data.versionId);
  }
  $acceptModelChanged(uri, e) {
    if (!this.a[uri]) {
      return;
    }
    const model = this.a[uri];
    model.onEvents(e);
  }
  $acceptRemovedModel(uri) {
    if (!this.a[uri]) {
      return;
    }
    delete this.a[uri];
  }
};
var $E0 = class extends $zM {
  get uri() {
    return this.a;
  }
  get eol() {
    return this.c;
  }
  getValue() {
    return this.getText();
  }
  findMatches(regex) {
    const matches = [];
    for (let i2 = 0; i2 < this.b.length; i2++) {
      const line = this.b[i2];
      const offsetToAdd = this.offsetAt(new $8C(i2 + 1, 1));
      const iteratorOverMatches = line.matchAll(regex);
      for (const match of iteratorOverMatches) {
        if (match.index || match.index === 0) {
          match.index = match.index + offsetToAdd;
        }
        matches.push(match);
      }
    }
    return matches;
  }
  getLinesContent() {
    return this.b.slice(0);
  }
  getLineCount() {
    return this.b.length;
  }
  getLineContent(lineNumber) {
    return this.b[lineNumber - 1];
  }
  getWordAtPosition(position, wordDefinition) {
    const wordAtText = $MD(position.column, $KD(wordDefinition), this.b[position.lineNumber - 1], 0);
    if (wordAtText) {
      return new $9C(position.lineNumber, wordAtText.startColumn, position.lineNumber, wordAtText.endColumn);
    }
    return null;
  }
  getWordUntilPosition(position, wordDefinition) {
    const wordAtPosition = this.getWordAtPosition(position, wordDefinition);
    if (!wordAtPosition) {
      return {
        word: "",
        startColumn: position.column,
        endColumn: position.column
      };
    }
    return {
      word: this.b[position.lineNumber - 1].substring(wordAtPosition.startColumn - 1, position.column - 1),
      startColumn: wordAtPosition.startColumn,
      endColumn: position.column
    };
  }
  words(wordDefinition) {
    const lines = this.b;
    const wordenize = this.m.bind(this);
    let lineNumber = 0;
    let lineText = "";
    let wordRangesIdx = 0;
    let wordRanges = [];
    return {
      *[Symbol.iterator]() {
        while (true) {
          if (wordRangesIdx < wordRanges.length) {
            const value = lineText.substring(wordRanges[wordRangesIdx].start, wordRanges[wordRangesIdx].end);
            wordRangesIdx += 1;
            yield value;
          } else {
            if (lineNumber < lines.length) {
              lineText = lines[lineNumber];
              wordRanges = wordenize(lineText, wordDefinition);
              wordRangesIdx = 0;
              lineNumber += 1;
            } else {
              break;
            }
          }
        }
      }
    };
  }
  getLineWords(lineNumber, wordDefinition) {
    const content = this.b[lineNumber - 1];
    const ranges = this.m(content, wordDefinition);
    const words = [];
    for (const range of ranges) {
      words.push({
        word: content.substring(range.start, range.end),
        startColumn: range.start + 1,
        endColumn: range.end + 1
      });
    }
    return words;
  }
  m(content, wordDefinition) {
    const result = [];
    let match;
    wordDefinition.lastIndex = 0;
    while (match = wordDefinition.exec(content)) {
      if (match[0].length === 0) {
        break;
      }
      result.push({ start: match.index, end: match.index + match[0].length });
    }
    return result;
  }
  getValueInRange(range) {
    range = this.n(range);
    if (range.startLineNumber === range.endLineNumber) {
      return this.b[range.startLineNumber - 1].substring(range.startColumn - 1, range.endColumn - 1);
    }
    const lineEnding = this.c;
    const startLineIndex = range.startLineNumber - 1;
    const endLineIndex = range.endLineNumber - 1;
    const resultLines = [];
    resultLines.push(this.b[startLineIndex].substring(range.startColumn - 1));
    for (let i2 = startLineIndex + 1; i2 < endLineIndex; i2++) {
      resultLines.push(this.b[i2]);
    }
    resultLines.push(this.b[endLineIndex].substring(0, range.endColumn - 1));
    return resultLines.join(lineEnding);
  }
  offsetAt(position) {
    position = this.o(position);
    this.h();
    return this.f.getPrefixSum(position.lineNumber - 2) + (position.column - 1);
  }
  positionAt(offset) {
    offset = Math.floor(offset);
    offset = Math.max(0, offset);
    this.h();
    const out = this.f.getIndexOf(offset);
    const lineLength = this.b[out.index].length;
    return {
      lineNumber: 1 + out.index,
      column: 1 + Math.min(out.remainder, lineLength)
    };
  }
  n(range) {
    const start = this.o({ lineNumber: range.startLineNumber, column: range.startColumn });
    const end = this.o({ lineNumber: range.endLineNumber, column: range.endColumn });
    if (start.lineNumber !== range.startLineNumber || start.column !== range.startColumn || end.lineNumber !== range.endLineNumber || end.column !== range.endColumn) {
      return {
        startLineNumber: start.lineNumber,
        startColumn: start.column,
        endLineNumber: end.lineNumber,
        endColumn: end.column
      };
    }
    return range;
  }
  o(position) {
    if (!$8C.isIPosition(position)) {
      throw new Error("bad position");
    }
    let { lineNumber, column } = position;
    let hasChanged = false;
    if (lineNumber < 1) {
      lineNumber = 1;
      column = 1;
      hasChanged = true;
    } else if (lineNumber > this.b.length) {
      lineNumber = this.b.length;
      column = this.b[lineNumber - 1].length + 1;
      hasChanged = true;
    } else {
      const maxCharacter = this.b[lineNumber - 1].length + 1;
      if (column < 1) {
        column = 1;
        hasChanged = true;
      } else if (column > maxCharacter) {
        column = maxCharacter;
        hasChanged = true;
      }
    }
    if (!hasChanged) {
      return position;
    } else {
      return { lineNumber, column };
    }
  }
};

// out-build/vs/workbench/services/languageDetection/browser/languageDetectionWorker.protocol.js
var $4Xb = class _$4Xb {
  static {
    this.CHANNEL_NAME = "languageDetectionWorkerHost";
  }
  static getChannel(workerServer) {
    return workerServer.getChannel(_$4Xb.CHANNEL_NAME);
  }
  static setChannel(workerClient, obj) {
    workerClient.setChannel(_$4Xb.CHANNEL_NAME, obj);
  }
};

// out-build/vs/workbench/services/languageDetection/browser/languageDetectionWorkerServiceImpl.js
var $5Xb_1;
var TOP_LANG_COUNTS = 12;
var regexpModuleLocation = `${$eh}/vscode-regexp-languagedetection`;
var regexpModuleLocationAsar = `${$fh}/vscode-regexp-languagedetection`;
var moduleLocation = `${$eh}/@vscode/vscode-languagedetection`;
var moduleLocationAsar = `${$fh}/@vscode/vscode-languagedetection`;
var $5Xb = class $5Xb2 extends $3c {
  static {
    $5Xb_1 = this;
  }
  static {
    this.enablementSettingKey = "workbench.editor.languageDetection";
  }
  static {
    this.historyBasedEnablementConfig = "workbench.editor.historyBasedLanguageDetection";
  }
  static {
    this.preferHistoryConfig = "workbench.editor.preferHistoryBasedLanguageDetection";
  }
  static {
    this.workspaceOpenedLanguagesStorageKey = "workbench.editor.languageDetectionOpenedLanguages.workspace";
  }
  static {
    this.globalOpenedLanguagesStorageKey = "workbench.editor.languageDetectionOpenedLanguages.global";
  }
  constructor(n, languageService, r2, s, t, modelService, u, telemetryService, storageService, w) {
    super();
    this.n = n;
    this.r = r2;
    this.s = s;
    this.t = t;
    this.u = u;
    this.w = w;
    this.b = false;
    this.c = /* @__PURE__ */ new Set();
    this.f = /* @__PURE__ */ new Set();
    this.g = new $Hc(TOP_LANG_COUNTS);
    this.h = new $Hc(TOP_LANG_COUNTS);
    this.j = true;
    this.m = {};
    const useAsar = $rJ && this.n.isBuilt && !$r;
    this.a = this.B(new $6Xb(
      modelService,
      languageService,
      telemetryService,
      // TODO See if it's possible to bundle vscode-languagedetection
      useAsar ? $ih.asBrowserUri(`${moduleLocationAsar}/dist/lib/index.js`).toString(true) : $ih.asBrowserUri(`${moduleLocation}/dist/lib/index.js`).toString(true),
      useAsar ? $ih.asBrowserUri(`${moduleLocationAsar}/model/model.json`).toString(true) : $ih.asBrowserUri(`${moduleLocation}/model/model.json`).toString(true),
      useAsar ? $ih.asBrowserUri(`${moduleLocationAsar}/model/group1-shard1of1.bin`).toString(true) : $ih.asBrowserUri(`${moduleLocation}/model/group1-shard1of1.bin`).toString(true),
      useAsar ? $ih.asBrowserUri(`${regexpModuleLocationAsar}/dist/index.js`).toString(true) : $ih.asBrowserUri(`${regexpModuleLocation}/dist/index.js`).toString(true)
    ));
    this.C(storageService);
  }
  async y() {
    if (this.b) {
      return;
    }
    this.b = true;
    const fileExtensions = await this.s.getWorkspaceFileExtensions(this.t.getWorkspace());
    let count = 0;
    for (const ext of fileExtensions.extensions) {
      const langId = this.a.getLanguageId(ext);
      if (langId && count < TOP_LANG_COUNTS) {
        this.c.add(langId);
        count++;
        if (count > TOP_LANG_COUNTS) {
          break;
        }
      }
    }
    this.j = true;
  }
  isEnabledForLanguage(languageId) {
    return !!languageId && this.r.getValue($5Xb_1.enablementSettingKey, { overrideIdentifier: languageId });
  }
  z() {
    if (!this.j) {
      return this.m;
    }
    const biases = {};
    this.f.forEach((lang) => biases[lang] = (biases[lang] ?? 0) + 7);
    this.c.forEach((lang) => biases[lang] = (biases[lang] ?? 0) + 5);
    [...this.h.keys()].forEach((lang) => biases[lang] = (biases[lang] ?? 0) + 3);
    [...this.g.keys()].forEach((lang) => biases[lang] = (biases[lang] ?? 0) + 1);
    this.w.trace("Session Languages:", JSON.stringify([...this.f]));
    this.w.trace("Workspace Languages:", JSON.stringify([...this.c]));
    this.w.trace("Historical Workspace Opened Languages:", JSON.stringify([...this.h.keys()]));
    this.w.trace("Historical Globally Opened Languages:", JSON.stringify([...this.g.keys()]));
    this.w.trace("Computed Language Detection Biases:", JSON.stringify(biases));
    this.j = false;
    this.m = biases;
    return biases;
  }
  async detectLanguage(resource, supportedLangs) {
    const useHistory = this.r.getValue($5Xb_1.historyBasedEnablementConfig);
    const preferHistory = this.r.getValue($5Xb_1.preferHistoryConfig);
    if (useHistory) {
      await this.y();
    }
    const biases = useHistory ? this.z() : void 0;
    return this.a.detectLanguage(resource, biases, preferHistory, supportedLangs);
  }
  // TODO: explore using the history service or something similar to provide this list of opened editors
  // so this service can support delayed instantiation. This may be tricky since it seems the IHistoryService
  // only gives history for a workspace... where this takes advantage of history at a global level as well.
  C(storageService) {
    try {
      const globalLangHistoryData = JSON.parse(storageService.get($5Xb_1.globalOpenedLanguagesStorageKey, 0, "[]"));
      this.g.fromJSON(globalLangHistoryData);
    } catch (e) {
      console.error(e);
    }
    try {
      const workspaceLangHistoryData = JSON.parse(storageService.get($5Xb_1.workspaceOpenedLanguagesStorageKey, 1, "[]"));
      this.h.fromJSON(workspaceLangHistoryData);
    } catch (e) {
      console.error(e);
    }
    this.B(this.u.onDidActiveEditorChange(() => {
      const activeLanguage = this.u.activeTextEditorLanguageId;
      if (activeLanguage && this.u.activeEditor?.resource?.scheme !== Schemas.untitled) {
        this.f.add(activeLanguage);
        this.g.set(activeLanguage, true);
        this.h.set(activeLanguage, true);
        storageService.store(
          $5Xb_1.globalOpenedLanguagesStorageKey,
          JSON.stringify(this.g.toJSON()),
          0,
          1
          /* StorageTarget.MACHINE */
        );
        storageService.store(
          $5Xb_1.workspaceOpenedLanguagesStorageKey,
          JSON.stringify(this.h.toJSON()),
          1,
          1
          /* StorageTarget.MACHINE */
        );
        this.j = true;
      }
    }));
  }
};
$5Xb = $5Xb_1 = __decorate([
  __param(0, $US),
  __param(1, $1E),
  __param(2, $kl),
  __param(3, $Hx),
  __param(4, $Zk),
  __param(5, $sG),
  __param(6, $mJ),
  __param(7, $zv),
  __param(8, $jv),
  __param(9, $wn)
], $5Xb);
var $6Xb = class extends $3c {
  constructor(b, c, f, g, h3, j, m) {
    super();
    this.b = b;
    this.c = c;
    this.f = f;
    this.g = g;
    this.h = h3;
    this.j = j;
    this.m = m;
  }
  n() {
    if (!this.a) {
      const workerClient = this.B($412("vs/workbench/services/languageDetection/browser/languageDetectionSimpleWorker", "LanguageDetectionWorker"));
      $4Xb.setChannel(workerClient, {
        $getIndexJsUri: async () => this.getIndexJsUri(),
        $getLanguageId: async (languageIdOrExt) => this.getLanguageId(languageIdOrExt),
        $sendTelemetryEvent: async (languages, confidences, timeSpent) => this.sendTelemetryEvent(languages, confidences, timeSpent),
        $getRegexpModelUri: async () => this.getRegexpModelUri(),
        $getModelJsonUri: async () => this.getModelJsonUri(),
        $getWeightsUri: async () => this.getWeightsUri()
      });
      const workerTextModelSyncClient = $C0.create(workerClient, this.b);
      this.a = { workerClient, workerTextModelSyncClient };
    }
    return this.a;
  }
  r(uri) {
    const guess = this.c.guessLanguageIdByFilepathOrFirstLine(uri);
    if (guess && guess !== "unknown") {
      return guess;
    }
    return void 0;
  }
  async getIndexJsUri() {
    return this.g;
  }
  getLanguageId(languageIdOrExt) {
    if (!languageIdOrExt) {
      return void 0;
    }
    if (this.c.isRegisteredLanguageId(languageIdOrExt)) {
      return languageIdOrExt;
    }
    const guessed = this.r(URI.file(`file.${languageIdOrExt}`));
    if (!guessed || guessed === "unknown") {
      return void 0;
    }
    return guessed;
  }
  async getModelJsonUri() {
    return this.h;
  }
  async getWeightsUri() {
    return this.j;
  }
  async getRegexpModelUri() {
    return this.m;
  }
  async sendTelemetryEvent(languages, confidences, timeSpent) {
    this.f.publicLog2($wG, {
      languages: languages.join(","),
      confidences: confidences.join(","),
      timeSpent
    });
  }
  async detectLanguage(resource, langBiases, preferHistory, supportedLangs) {
    const startTime = Date.now();
    const quickGuess = this.r(resource);
    if (quickGuess) {
      return quickGuess;
    }
    const { workerClient, workerTextModelSyncClient } = this.n();
    await workerTextModelSyncClient.ensureSyncedResources([resource]);
    const modelId = await workerClient.proxy.$detectLanguage(resource.toString(), langBiases, preferHistory, supportedLangs);
    const languageId = this.getLanguageId(modelId);
    const LanguageDetectionStatsId = "automaticlanguagedetection.perf";
    this.f.publicLog2(LanguageDetectionStatsId, {
      timeSpent: Date.now() - startTime,
      detection: languageId || "unknown"
    });
    return languageId;
  }
};
$SC(
  $tG,
  $5Xb,
  0
  /* InstantiationType.Eager */
);

// out-build/vs/editor/common/services/languageFeaturesService.js
var $7Xb = class {
  constructor() {
    this.referenceProvider = new $bN(this.b.bind(this));
    this.renameProvider = new $bN(this.b.bind(this));
    this.newSymbolNamesProvider = new $bN(this.b.bind(this));
    this.codeActionProvider = new $bN(this.b.bind(this));
    this.definitionProvider = new $bN(this.b.bind(this));
    this.typeDefinitionProvider = new $bN(this.b.bind(this));
    this.declarationProvider = new $bN(this.b.bind(this));
    this.implementationProvider = new $bN(this.b.bind(this));
    this.documentSymbolProvider = new $bN(this.b.bind(this));
    this.inlayHintsProvider = new $bN(this.b.bind(this));
    this.colorProvider = new $bN(this.b.bind(this));
    this.codeLensProvider = new $bN(this.b.bind(this));
    this.documentFormattingEditProvider = new $bN(this.b.bind(this));
    this.documentRangeFormattingEditProvider = new $bN(this.b.bind(this));
    this.onTypeFormattingEditProvider = new $bN(this.b.bind(this));
    this.signatureHelpProvider = new $bN(this.b.bind(this));
    this.hoverProvider = new $bN(this.b.bind(this));
    this.documentHighlightProvider = new $bN(this.b.bind(this));
    this.multiDocumentHighlightProvider = new $bN(this.b.bind(this));
    this.selectionRangeProvider = new $bN(this.b.bind(this));
    this.foldingRangeProvider = new $bN(this.b.bind(this));
    this.linkProvider = new $bN(this.b.bind(this));
    this.inlineCompletionsProvider = new $bN(this.b.bind(this));
    this.inlineEditProvider = new $bN(this.b.bind(this));
    this.completionProvider = new $bN(this.b.bind(this));
    this.linkedEditingRangeProvider = new $bN(this.b.bind(this));
    this.inlineValuesProvider = new $bN(this.b.bind(this));
    this.evaluatableExpressionProvider = new $bN(this.b.bind(this));
    this.documentRangeSemanticTokensProvider = new $bN(this.b.bind(this));
    this.documentSemanticTokensProvider = new $bN(this.b.bind(this));
    this.documentDropEditProvider = new $bN(this.b.bind(this));
    this.documentPasteEditProvider = new $bN(this.b.bind(this));
    this.mappedEditsProvider = new $bN(this.b.bind(this));
  }
  setNotebookTypeResolver(resolver) {
    this.a = resolver;
  }
  b(uri) {
    return this.a?.(uri);
  }
};
$SC(
  $mP,
  $7Xb,
  1
  /* InstantiationType.Delayed */
);

// out-build/vs/editor/common/services/semanticTokensStylingService.js
var $8Xb = class $8Xb2 extends $3c {
  constructor(b, c, f) {
    super();
    this.b = b;
    this.c = c;
    this.f = f;
    this.a = /* @__PURE__ */ new WeakMap();
    this.B(this.b.onDidColorThemeChange(() => {
      this.a = /* @__PURE__ */ new WeakMap();
    }));
  }
  getStyling(provider) {
    if (!this.a.has(provider)) {
      this.a.set(provider, new $8jb(provider.getLegend(), this.b, this.f, this.c));
    }
    return this.a.get(provider);
  }
};
$8Xb = __decorate([
  __param(0, $gs),
  __param(1, $wn),
  __param(2, $1E)
], $8Xb);
$SC(
  $0jb,
  $8Xb,
  1
  /* InstantiationType.Delayed */
);

// out-build/vs/workbench/services/textMate/browser/tokenizationSupport/textMateTokenizationSupport.js
var $9Xb = class extends $3c {
  constructor(c, f, g, h3, j, m, n) {
    super();
    this.c = c;
    this.f = f;
    this.g = g;
    this.h = h3;
    this.j = j;
    this.m = m;
    this.n = n;
    this.a = [];
    this.b = this.B(new $ze());
    this.onDidEncounterLanguage = this.b.event;
  }
  get backgroundTokenizerShouldOnlyVerifyTokens() {
    return this.j();
  }
  getInitialState() {
    return this.f;
  }
  tokenize(line, hasEOL, state) {
    throw new Error("Not supported!");
  }
  createBackgroundTokenizer(textModel, store) {
    if (this.h) {
      return this.h(textModel, store);
    }
    return void 0;
  }
  tokenizeEncoded(line, hasEOL, state) {
    const isRandomSample = Math.random() * 1e4 < 1;
    const shouldMeasure = this.n || isRandomSample;
    const sw = shouldMeasure ? new $te(true) : void 0;
    const textMateResult = this.c.tokenizeLine2(line, state, 500);
    if (shouldMeasure) {
      const timeMS = sw.elapsed();
      if (isRandomSample || timeMS > 32) {
        this.m(timeMS, line.length, isRandomSample);
      }
    }
    if (textMateResult.stoppedEarly) {
      console.warn(`Time limit reached when tokenizing line: ${line.substring(0, 100)}`);
      return new $PE(textMateResult.tokens, state);
    }
    if (this.g) {
      const seenLanguages = this.a;
      const tokens = textMateResult.tokens;
      for (let i2 = 0, len = tokens.length >>> 1; i2 < len; i2++) {
        const metadata = tokens[(i2 << 1) + 1];
        const languageId = $pE.getLanguageId(metadata);
        if (!seenLanguages[languageId]) {
          seenLanguages[languageId] = true;
          this.b.fire(languageId);
        }
      }
    }
    let endState;
    if (state.equals(textMateResult.ruleStack)) {
      endState = state;
    } else {
      endState = textMateResult.ruleStack;
    }
    return new $PE(textMateResult.tokens, endState);
  }
};

// out-build/vs/workbench/services/textMate/browser/tokenizationSupport/tokenizationSupportWithLineLimit.js
var $0Xb = class extends $3c {
  get backgroundTokenizerShouldOnlyVerifyTokens() {
    return this.b.backgroundTokenizerShouldOnlyVerifyTokens;
  }
  constructor(a, b, disposable, c) {
    super();
    this.a = a;
    this.b = b;
    this.c = c;
    this.B($Md(this.c));
    this.B(disposable);
  }
  getInitialState() {
    return this.b.getInitialState();
  }
  tokenize(line, hasEOL, state) {
    throw new Error("Not supported!");
  }
  tokenizeEncoded(line, hasEOL, state) {
    if (line.length >= this.c.get()) {
      return $uI(this.a, state);
    }
    return this.b.tokenizeEncoded(line, hasEOL, state);
  }
  createBackgroundTokenizer(textModel, store) {
    if (this.b.createBackgroundTokenizer) {
      return this.b.createBackgroundTokenizer(textModel, store);
    } else {
      return void 0;
    }
  }
};

// out-build/vs/workbench/services/textMate/browser/backgroundTokenization/worker/textMateWorkerHost.js
var $cYb = class _$cYb {
  static {
    this.CHANNEL_NAME = "textMateWorkerHost";
  }
  static getChannel(workerServer) {
    return workerServer.getChannel(_$cYb.CHANNEL_NAME);
  }
  static setChannel(workerClient, obj) {
    workerClient.setChannel(_$cYb.CHANNEL_NAME, obj);
  }
};

// out-build/vs/workbench/services/textMate/browser/arrayOperation.js
var $fYb = class {
  constructor(edits) {
    this.edits = edits.slice().sort($9b((c) => c.offset, $$b));
  }
  applyToArray(array2) {
    for (let i2 = this.edits.length - 1; i2 >= 0; i2--) {
      const c = this.edits[i2];
      array2.splice(c.offset, c.length, ...new Array(c.newLength));
    }
  }
};
var $gYb = class {
  constructor(offset, length, newLength) {
    this.offset = offset;
    this.length = length;
    this.newLength = newLength;
  }
  toString() {
    return `[${this.offset}, +${this.length}) -> +${this.newLength}}`;
  }
};
var $hYb = class _$hYb {
  static fromMany(transformations) {
    const transformers = transformations.map((t) => new _$hYb(t));
    return new $iYb(transformers);
  }
  constructor(d) {
    this.d = d;
    this.a = 0;
    this.b = 0;
  }
  /**
   * Precondition: index >= previous-value-of(index).
   */
  transform(index) {
    let nextChange = this.d.edits[this.a];
    while (nextChange && nextChange.offset + nextChange.length <= index) {
      this.b += nextChange.newLength - nextChange.length;
      this.a++;
      nextChange = this.d.edits[this.a];
    }
    if (nextChange && nextChange.offset <= index) {
      return void 0;
    }
    return index + this.b;
  }
};
var $iYb = class {
  constructor(a) {
    this.a = a;
  }
  transform(index) {
    for (const transformer of this.a) {
      const result = transformer.transform(index);
      if (result === void 0) {
        return void 0;
      }
      index = result;
    }
    return index;
  }
};

// out-build/vs/workbench/services/textMate/browser/backgroundTokenization/textMateWorkerTokenizerController.js
var $jYb = class _$jYb extends $3c {
  static {
    this.a = 0;
  }
  constructor(r2, u, w, y, z, C) {
    super();
    this.r = r2;
    this.u = u;
    this.w = w;
    this.y = y;
    this.z = z;
    this.C = C;
    this.controllerId = _$jYb.a++;
    this.f = [];
    this.g = new $AI();
    this.h = $G9("editor.experimental.asyncTokenizationLogging", false, this.z);
    this.B($Md(this.h));
    this.B(this.r.onDidChangeContent((e) => {
      if (this.D) {
        console.log("model change", {
          fileName: this.r.uri.fsPath.split("\\").pop(),
          changes: changesToString(e.changes)
        });
      }
      this.u.$acceptModelChanged(this.controllerId, e);
      this.f.push(e);
    }));
    this.B(this.r.onDidChangeLanguage((e) => {
      const languageId2 = this.r.getLanguageId();
      const encodedLanguageId2 = this.w.encodeLanguageId(languageId2);
      this.u.$acceptModelLanguageChanged(this.controllerId, languageId2, encodedLanguageId2);
    }));
    const languageId = this.r.getLanguageId();
    const encodedLanguageId = this.w.encodeLanguageId(languageId);
    this.u.$acceptNewModel({
      uri: this.r.uri,
      versionId: this.r.getVersionId(),
      lines: this.r.getLinesContent(),
      EOL: this.r.getEOL(),
      languageId,
      encodedLanguageId,
      maxTokenizationLineLength: this.C.get(),
      controllerId: this.controllerId
    });
    this.B($td((reader) => {
      const maxTokenizationLineLength = this.C.read(reader);
      this.u.$acceptMaxTokenizationLineLength(this.controllerId, maxTokenizationLineLength);
    }));
  }
  dispose() {
    super.dispose();
    this.u.$acceptRemovedModel(this.controllerId);
  }
  requestTokens(startLineNumber, endLineNumberExclusive) {
    this.u.$retokenize(this.controllerId, startLineNumber, endLineNumberExclusive);
  }
  /**
   * This method is called from the worker through the worker host.
   */
  async setTokensAndStates(controllerId, versionId, rawTokens, stateDeltas) {
    if (this.controllerId !== controllerId) {
      return;
    }
    let tokens = $wI.deserialize(new Uint8Array(rawTokens));
    if (this.D) {
      console.log("received background tokenization result", {
        fileName: this.r.uri.fsPath.split("\\").pop(),
        updatedTokenLines: tokens.map((t) => t.getLineRange()).join(" & "),
        updatedStateLines: stateDeltas.map((s) => new $_C(s.startLineNumber, s.startLineNumber + s.stateDeltas.length).toString()).join(" & ")
      });
    }
    if (this.D) {
      const changes = this.f.filter((c) => c.versionId <= versionId).map((c) => c.changes).map((c) => changesToString(c)).join(" then ");
      console.log("Applying changes to local states", changes);
    }
    while (this.f.length > 0 && this.f[0].versionId <= versionId) {
      const change = this.f.shift();
      this.g.acceptChanges(change.changes);
    }
    if (this.f.length > 0) {
      if (this.D) {
        const changes = this.f.map((c) => c.changes).map((c) => changesToString(c)).join(" then ");
        console.log("Considering non-processed changes", changes);
      }
      const curToFutureTransformerTokens = $hYb.fromMany(this.f.map((c) => fullLineArrayEditFromModelContentChange(c.changes)));
      const b = new $wI();
      for (const t of tokens) {
        for (let i2 = t.startLineNumber; i2 <= t.endLineNumber; i2++) {
          const result = curToFutureTransformerTokens.transform(i2 - 1);
          if (result !== void 0) {
            b.add(i2, t.getLineTokens(i2));
          }
        }
      }
      tokens = b.finalize();
      for (const change of this.f) {
        for (const innerChanges of change.changes) {
          for (let j = 0; j < tokens.length; j++) {
            tokens[j].applyEdit(innerChanges.range, innerChanges.text);
          }
        }
      }
    }
    const curToFutureTransformerStates = $hYb.fromMany(this.f.map((c) => fullLineArrayEditFromModelContentChange(c.changes)));
    if (!this.m || !this.n) {
      const { applyStateStackDiff, INITIAL } = await $sJ("vscode-textmate", "release/main.js");
      this.m = applyStateStackDiff;
      this.n = INITIAL;
    }
    for (const d of stateDeltas) {
      let prevState = d.startLineNumber <= 1 ? this.n : this.g.getEndState(d.startLineNumber - 1);
      for (let i2 = 0; i2 < d.stateDeltas.length; i2++) {
        const delta = d.stateDeltas[i2];
        let state;
        if (delta) {
          state = this.m(prevState, delta);
          this.g.setEndState(d.startLineNumber + i2, state);
        } else {
          state = this.g.getEndState(d.startLineNumber + i2);
        }
        const offset = curToFutureTransformerStates.transform(d.startLineNumber + i2 - 1);
        if (offset !== void 0) {
          this.y.setEndState(offset + 1, state);
        }
        if (d.startLineNumber + i2 >= this.r.getLineCount() - 1) {
          this.y.backgroundTokenizationFinished();
        }
        prevState = state;
      }
    }
    this.y.setTokens(tokens);
  }
  get D() {
    return this.h.get();
  }
};
function fullLineArrayEditFromModelContentChange(c) {
  return new $fYb(c.map((c2) => new $gYb(
    c2.range.startLineNumber - 1,
    // Expand the edit range to include the entire line
    c2.range.endLineNumber - c2.range.startLineNumber + 1,
    $tE(c2.text)[0] + 1
  )));
}
function changesToString(changes) {
  return changes.map((c) => $9C.lift(c.range).toString() + " => " + c.text).join(" & ");
}

// out-build/vs/workbench/services/textMate/browser/backgroundTokenization/threadedBackgroundTokenizerFactory.js
var $kYb_1;
var $kYb = class $kYb2 {
  static {
    $kYb_1 = this;
  }
  static {
    this.a = false;
  }
  constructor(i2, j, k, l, m, n, o, p) {
    this.i = i2;
    this.j = j;
    this.k = k;
    this.l = l;
    this.m = m;
    this.n = n;
    this.o = o;
    this.p = p;
    this.b = null;
    this.c = null;
    this.d = null;
    this.e = /* @__PURE__ */ new Map();
    this.f = null;
    this.g = null;
    this.h = [];
  }
  dispose() {
    this.s();
  }
  // Will be recreated after worker is disposed (because tokenizer is re-registered when languages change)
  createBackgroundTokenizer(textModel, tokenStore, maxTokenizationLineLength) {
    if (!this.j() || textModel.isTooLargeForSyncing()) {
      return void 0;
    }
    const store = new $2c();
    const controllerContainer = this.q().then((workerProxy) => {
      if (store.isDisposed || !workerProxy) {
        return void 0;
      }
      const controllerContainer2 = { controller: void 0, worker: this.c };
      store.add(keepAliveWhenAttached(textModel, () => {
        const controller = new $jYb(textModel, workerProxy, this.m.languageIdCodec, tokenStore, this.l, maxTokenizationLineLength);
        controllerContainer2.controller = controller;
        this.e.set(controller.controllerId, controller);
        return $1c(() => {
          controllerContainer2.controller = void 0;
          this.e.delete(controller.controllerId);
          controller.dispose();
        });
      }));
      return controllerContainer2;
    });
    return {
      dispose() {
        store.dispose();
      },
      requestTokens: async (startLineNumber, endLineNumberExclusive) => {
        const container2 = await controllerContainer;
        if (container2?.controller && container2.worker === this.c) {
          container2.controller.requestTokens(startLineNumber, endLineNumberExclusive);
        }
      },
      reportMismatchingTokens: (lineNumber) => {
        if ($kYb_1.a) {
          return;
        }
        $kYb_1.a = true;
        this.o.error({
          message: "Async Tokenization Token Mismatch in line " + lineNumber,
          name: "Async Tokenization Token Mismatch"
        });
        this.p.publicLog2("asyncTokenizationMismatchingTokens", {});
      }
    };
  }
  setGrammarDefinitions(grammarDefinitions) {
    this.h = grammarDefinitions;
    this.s();
  }
  acceptTheme(theme, colorMap) {
    this.f = theme;
    this.g = colorMap;
    if (this.f && this.g && this.d) {
      this.d.$acceptTheme(this.f, this.g);
    }
  }
  q() {
    if (!this.b) {
      this.b = this.r();
    }
    return this.b;
  }
  async r() {
    const onigurumaModuleLocation = `${$eh}/vscode-oniguruma`;
    const onigurumaModuleLocationAsar = `${$fh}/vscode-oniguruma`;
    const useAsar = $rJ && this.n.isBuilt && !$r;
    const onigurumaLocation = useAsar ? onigurumaModuleLocationAsar : onigurumaModuleLocation;
    const onigurumaWASM = `${onigurumaLocation}/release/onig.wasm`;
    const createData = {
      grammarDefinitions: this.h,
      onigurumaWASMUri: $ih.asBrowserUri(onigurumaWASM).toString(true)
    };
    const worker = this.c = $412("vs/workbench/services/textMate/browser/backgroundTokenization/worker/textMateTokenizationWorker.worker", "TextMateWorker");
    $cYb.setChannel(worker, {
      $readFile: async (_resource) => {
        const resource = URI.revive(_resource);
        return this.k.readExtensionResource(resource);
      },
      $setTokensAndStates: async (controllerId, versionId, tokens, lineEndStateDeltas) => {
        const controller = this.e.get(controllerId);
        if (controller) {
          controller.setTokensAndStates(controllerId, versionId, tokens, lineEndStateDeltas);
        }
      },
      $reportTokenizationTime: (timeMs, languageId, sourceExtensionId, lineLength, isRandomSample) => {
        this.i(timeMs, languageId, sourceExtensionId, lineLength, isRandomSample);
      }
    });
    await worker.proxy.$init(createData);
    if (this.c !== worker) {
      return null;
    }
    this.d = worker.proxy;
    if (this.f && this.g) {
      this.d.$acceptTheme(this.f, this.g);
    }
    return worker.proxy;
  }
  s() {
    for (const controller of this.e.values()) {
      controller.dispose();
    }
    this.e.clear();
    if (this.c) {
      this.c.dispose();
      this.c = null;
    }
    this.d = null;
    this.b = null;
  }
};
$kYb = $kYb_1 = __decorate([
  __param(2, $Olb),
  __param(3, $kl),
  __param(4, $1E),
  __param(5, $Xk),
  __param(6, $PJ),
  __param(7, $zv)
], $kYb);
function keepAliveWhenAttached(textModel, factory) {
  const disposableStore = new $2c();
  const subStore = disposableStore.add(new $2c());
  function checkAttached() {
    if (textModel.isAttachedToEditor()) {
      subStore.add(factory());
    } else {
      subStore.clear();
    }
  }
  checkAttached();
  disposableStore.add(textModel.onDidChangeAttached(() => {
    checkAttached();
  }));
  return disposableStore;
}

// out-build/vs/workbench/services/textMate/common/TMScopeRegistry.js
var $$Xb = class {
  constructor() {
    this.a = /* @__PURE__ */ Object.create(null);
  }
  reset() {
    this.a = /* @__PURE__ */ Object.create(null);
  }
  register(def2) {
    if (this.a[def2.scopeName]) {
      const existingRegistration = this.a[def2.scopeName];
      if (!$oh(existingRegistration.location, def2.location)) {
        console.warn(`Overwriting grammar scope name to file mapping for scope ${def2.scopeName}.
Old grammar file: ${existingRegistration.location.toString()}.
New grammar file: ${def2.location.toString()}`);
      }
    }
    this.a[def2.scopeName] = def2;
  }
  getGrammarDefinition(scopeName) {
    return this.a[scopeName] || null;
  }
};

// out-build/vs/workbench/services/textMate/common/TMGrammarFactory.js
var $_Xb = "No TM Grammar registered for this language.";
var $aYb = class extends $3c {
  constructor(host, grammarDefinitions, vscodeTextmate, onigLib) {
    super();
    this.a = host;
    this.b = vscodeTextmate.INITIAL;
    this.c = new $$Xb();
    this.f = {};
    this.g = {};
    this.h = /* @__PURE__ */ new Map();
    this.j = this.B(new vscodeTextmate.Registry({
      onigLib,
      loadGrammar: async (scopeName) => {
        const grammarDefinition = this.c.getGrammarDefinition(scopeName);
        if (!grammarDefinition) {
          this.a.logTrace(`No grammar found for scope ${scopeName}`);
          return null;
        }
        const location3 = grammarDefinition.location;
        try {
          const content = await this.a.readFile(location3);
          return vscodeTextmate.parseRawGrammar(content, location3.path);
        } catch (e) {
          this.a.logError(`Unable to load and parse grammar for scope ${scopeName} from ${location3}`, e);
          return null;
        }
      },
      getInjections: (scopeName) => {
        const scopeParts = scopeName.split(".");
        let injections = [];
        for (let i2 = 1; i2 <= scopeParts.length; i2++) {
          const subScopeName = scopeParts.slice(0, i2).join(".");
          injections = [...injections, ...this.f[subScopeName] || []];
        }
        return injections;
      }
    }));
    for (const validGrammar of grammarDefinitions) {
      this.c.register(validGrammar);
      if (validGrammar.injectTo) {
        for (const injectScope of validGrammar.injectTo) {
          let injections = this.f[injectScope];
          if (!injections) {
            this.f[injectScope] = injections = [];
          }
          injections.push(validGrammar.scopeName);
        }
        if (validGrammar.embeddedLanguages) {
          for (const injectScope of validGrammar.injectTo) {
            let injectedEmbeddedLanguages = this.g[injectScope];
            if (!injectedEmbeddedLanguages) {
              this.g[injectScope] = injectedEmbeddedLanguages = [];
            }
            injectedEmbeddedLanguages.push(validGrammar.embeddedLanguages);
          }
        }
      }
      if (validGrammar.language) {
        this.h.set(validGrammar.language, validGrammar.scopeName);
      }
    }
  }
  has(languageId) {
    return this.h.has(languageId);
  }
  setTheme(theme, colorMap) {
    this.j.setTheme(theme, colorMap);
  }
  getColorMap() {
    return this.j.getColorMap();
  }
  async createGrammar(languageId, encodedLanguageId) {
    const scopeName = this.h.get(languageId);
    if (typeof scopeName !== "string") {
      throw new Error($_Xb);
    }
    const grammarDefinition = this.c.getGrammarDefinition(scopeName);
    if (!grammarDefinition) {
      throw new Error($_Xb);
    }
    const embeddedLanguages = grammarDefinition.embeddedLanguages;
    if (this.g[scopeName]) {
      const injectedEmbeddedLanguages = this.g[scopeName];
      for (const injected of injectedEmbeddedLanguages) {
        for (const scope of Object.keys(injected)) {
          embeddedLanguages[scope] = injected[scope];
        }
      }
    }
    const containsEmbeddedLanguages = Object.keys(embeddedLanguages).length > 0;
    let grammar;
    try {
      grammar = await this.j.loadGrammarWithConfiguration(scopeName, encodedLanguageId, {
        embeddedLanguages,
        tokenTypes: grammarDefinition.tokenTypes,
        balancedBracketSelectors: grammarDefinition.balancedBracketSelectors,
        unbalancedBracketSelectors: grammarDefinition.unbalancedBracketSelectors
      });
    } catch (err) {
      if (err.message && err.message.startsWith("No grammar provided for")) {
        throw new Error($_Xb);
      }
      throw err;
    }
    return {
      languageId,
      grammar,
      initialState: this.b,
      containsEmbeddedLanguages,
      sourceExtensionId: grammarDefinition.sourceExtensionId
    };
  }
};

// out-build/vs/workbench/services/textMate/common/TMGrammars.js
var $lYb = $tN.registerExtensionPoint({
  extensionPoint: "grammars",
  deps: [$Ssb],
  jsonSchema: {
    description: localize(13147, null),
    type: "array",
    defaultSnippets: [{ body: [{ language: "${1:id}", scopeName: "source.${2:id}", path: "./syntaxes/${3:id}.tmLanguage." }] }],
    items: {
      type: "object",
      defaultSnippets: [{ body: { language: "${1:id}", scopeName: "source.${2:id}", path: "./syntaxes/${3:id}.tmLanguage." } }],
      properties: {
        language: {
          description: localize(13148, null),
          type: "string"
        },
        scopeName: {
          description: localize(13149, null),
          type: "string"
        },
        path: {
          description: localize(13150, null),
          type: "string"
        },
        embeddedLanguages: {
          description: localize(13151, null),
          type: "object"
        },
        tokenTypes: {
          description: localize(13152, null),
          type: "object",
          additionalProperties: {
            enum: ["string", "comment", "other"]
          }
        },
        injectTo: {
          description: localize(13153, null),
          type: "array",
          items: {
            type: "string"
          }
        },
        balancedBracketScopes: {
          description: localize(13154, null),
          type: "array",
          items: {
            type: "string"
          },
          default: ["*"]
        },
        unbalancedBracketScopes: {
          description: localize(13155, null),
          type: "array",
          items: {
            type: "string"
          },
          default: []
        }
      },
      required: ["scopeName", "path"]
    }
  }
});

// out-build/vs/workbench/services/textMate/browser/textMateTokenizationFeatureImpl.js
var $mYb_1;
var $mYb = class $mYb2 extends $3c {
  static {
    $mYb_1 = this;
  }
  static {
    this.c = { sync: 0, async: 0 };
  }
  constructor(z, C, D, F, G, H, I, J, L, M) {
    super();
    this.z = z;
    this.C = C;
    this.D = D;
    this.F = F;
    this.G = G;
    this.H = H;
    this.I = I;
    this.J = J;
    this.L = L;
    this.M = M;
    this.g = [];
    this.h = [];
    this.j = false;
    this.m = () => {
    };
    this.n = null;
    this.s = null;
    this.t = new $2c();
    this.u = null;
    this.w = null;
    this.y = this.L.createInstance($kYb, (timeMs, languageId, sourceExtensionId, lineLength, isRandomSample) => this.$(timeMs, languageId, sourceExtensionId, lineLength, true, isRandomSample), () => this.N());
    this.X = null;
    this.f = $VZ();
    this.f.className = "vscode-tokens-styles";
    $lYb.setHandler((extensions) => this.P(extensions));
    this.W(this.C.getColorTheme(), true);
    this.B(this.C.onDidColorThemeChange(() => {
      this.W(this.C.getColorTheme(), false);
    }));
    this.B(this.z.onDidRequestRichLanguageFeatures((languageId) => {
      this.g.push(languageId);
    }));
  }
  N() {
    return !!this.H.getValue("editor.experimental.asyncTokenization");
  }
  O() {
    return !!this.H.getValue("editor.experimental.asyncTokenizationVerification");
  }
  P(extensions) {
    this.n = null;
    if (this.s) {
      this.s.dispose();
      this.s = null;
    }
    this.t.clear();
    this.n = [];
    for (const extension of extensions) {
      const grammars = extension.value;
      for (const grammar of grammars) {
        const validatedGrammar = this.Q(extension, grammar);
        if (validatedGrammar) {
          this.n.push(validatedGrammar);
          if (validatedGrammar.language) {
            const lazyTokenizationSupport = new $XE(() => this.U(validatedGrammar.language));
            this.t.add(lazyTokenizationSupport);
            this.t.add($YE.registerFactory(validatedGrammar.language, lazyTokenizationSupport));
          }
        }
      }
    }
    this.y.setGrammarDefinitions(this.n);
    for (const createdMode of this.g) {
      $YE.getOrCreate(createdMode);
    }
  }
  Q(extension, grammar) {
    if (!validateGrammarExtensionPoint(extension.description.extensionLocation, grammar, extension.collector, this.z)) {
      return null;
    }
    const grammarLocation = $vh(extension.description.extensionLocation, grammar.path);
    const embeddedLanguages = /* @__PURE__ */ Object.create(null);
    if (grammar.embeddedLanguages) {
      const scopes = Object.keys(grammar.embeddedLanguages);
      for (let i2 = 0, len = scopes.length; i2 < len; i2++) {
        const scope = scopes[i2];
        const language = grammar.embeddedLanguages[scope];
        if (typeof language !== "string") {
          continue;
        }
        if (this.z.isRegisteredLanguageId(language)) {
          embeddedLanguages[scope] = this.z.languageIdCodec.encodeLanguageId(language);
        }
      }
    }
    const tokenTypes = /* @__PURE__ */ Object.create(null);
    if (grammar.tokenTypes) {
      const scopes = Object.keys(grammar.tokenTypes);
      for (const scope of scopes) {
        const tokenType = grammar.tokenTypes[scope];
        switch (tokenType) {
          case "string":
            tokenTypes[scope] = 2;
            break;
          case "other":
            tokenTypes[scope] = 0;
            break;
          case "comment":
            tokenTypes[scope] = 1;
            break;
        }
      }
    }
    const validLanguageId = grammar.language && this.z.isRegisteredLanguageId(grammar.language) ? grammar.language : void 0;
    function asStringArray(array2, defaultValue) {
      if (!Array.isArray(array2)) {
        return defaultValue;
      }
      if (!array2.every((e) => typeof e === "string")) {
        return defaultValue;
      }
      return array2;
    }
    return {
      location: grammarLocation,
      language: validLanguageId,
      scopeName: grammar.scopeName,
      embeddedLanguages,
      tokenTypes,
      injectTo: grammar.injectTo,
      balancedBracketSelectors: asStringArray(grammar.balancedBracketScopes, ["*"]),
      unbalancedBracketSelectors: asStringArray(grammar.unbalancedBracketScopes, []),
      sourceExtensionId: extension.description.id
    };
  }
  startDebugMode(printFn, onStop) {
    if (this.j) {
      this.F.error(localize(13136, null));
      return;
    }
    this.m = printFn;
    this.j = true;
    if (this.j) {
      this.I.withProgress({
        location: 15,
        buttons: [localize(13137, null)]
      }, (progress) => {
        progress.report({
          message: localize(13138, null)
        });
        return this.Y().then((vscodeOniguruma) => {
          vscodeOniguruma.setDefaultDebugCall(true);
          progress.report({
            message: localize(13139, null)
          });
          return new Promise((resolve, reject) => {
          });
        });
      }, (choice) => {
        this.Y().then((vscodeOniguruma) => {
          this.m = () => {
          };
          this.j = false;
          vscodeOniguruma.setDefaultDebugCall(false);
          onStop();
        });
      });
    }
  }
  R() {
    return !!this.n;
  }
  async S() {
    if (this.s) {
      return this.s;
    }
    const [vscodeTextmate, vscodeOniguruma] = await Promise.all([$sJ("vscode-textmate", "release/main.js"), this.Y()]);
    const onigLib = Promise.resolve({
      createOnigScanner: (sources) => vscodeOniguruma.createOnigScanner(sources),
      createOnigString: (str) => vscodeOniguruma.createOnigString(str)
    });
    if (this.s) {
      return this.s;
    }
    this.s = new $aYb({
      logTrace: (msg) => this.G.trace(msg),
      logError: (msg, err) => this.G.error(msg, err),
      readFile: (resource) => this.D.readExtensionResource(resource)
    }, this.n || [], vscodeTextmate, onigLib);
    this.W(this.C.getColorTheme(), true);
    return this.s;
  }
  async U(languageId) {
    if (!this.z.isRegisteredLanguageId(languageId)) {
      return null;
    }
    if (!this.R()) {
      return null;
    }
    try {
      const grammarFactory = await this.S();
      if (!grammarFactory.has(languageId)) {
        return null;
      }
      const encodedLanguageId = this.z.languageIdCodec.encodeLanguageId(languageId);
      const r2 = await grammarFactory.createGrammar(languageId, encodedLanguageId);
      if (!r2.grammar) {
        return null;
      }
      const maxTokenizationLineLength = observableConfigValue("editor.maxTokenizationLineLength", languageId, -1, this.H);
      const tokenization = new $9Xb(r2.grammar, r2.initialState, r2.containsEmbeddedLanguages, (textModel, tokenStore) => this.y.createBackgroundTokenizer(textModel, tokenStore, maxTokenizationLineLength), () => this.O(), (timeMs, lineLength, isRandomSample) => {
        this.$(timeMs, languageId, r2.sourceExtensionId, lineLength, false, isRandomSample);
      }, true);
      const disposable = tokenization.onDidEncounterLanguage((encodedLanguageId2) => {
        if (!this.h[encodedLanguageId2]) {
          const languageId2 = this.z.languageIdCodec.decodeLanguageId(encodedLanguageId2);
          this.h[encodedLanguageId2] = true;
          this.z.requestBasicLanguageFeatures(languageId2);
        }
      });
      return new $0Xb(encodedLanguageId, tokenization, disposable, maxTokenizationLineLength);
    } catch (err) {
      if (err.message && err.message === $_Xb) {
        return null;
      }
      $gb(err);
      return null;
    }
  }
  W(colorTheme, forceUpdate) {
    if (!forceUpdate && this.u && this.w && equalsTokenRules(this.u.settings, colorTheme.tokenColors) && $zb(this.w, colorTheme.tokenColorMap)) {
      return;
    }
    this.u = { name: colorTheme.label, settings: colorTheme.tokenColors };
    this.w = colorTheme.tokenColorMap;
    this.s?.setTheme(this.u, this.w);
    const colorMap = toColorMap(this.w);
    const cssRules = $4Gb(colorMap);
    this.f.textContent = cssRules;
    $YE.setColorMap(colorMap);
    if (this.u && this.w) {
      this.y.acceptTheme(this.u, this.w);
    }
  }
  async createTokenizer(languageId) {
    if (!this.z.isRegisteredLanguageId(languageId)) {
      return null;
    }
    const grammarFactory = await this.S();
    if (!grammarFactory.has(languageId)) {
      return null;
    }
    const encodedLanguageId = this.z.languageIdCodec.encodeLanguageId(languageId);
    const { grammar } = await grammarFactory.createGrammar(languageId, encodedLanguageId);
    return grammar;
  }
  Y() {
    if (!this.X) {
      this.X = (async () => {
        const [vscodeOniguruma, wasm] = await Promise.all([$sJ("vscode-oniguruma", "release/main.js"), this.Z()]);
        await vscodeOniguruma.loadWASM({
          data: wasm,
          print: (str) => {
            this.m(str);
          }
        });
        return vscodeOniguruma;
      })();
    }
    return this.X;
  }
  async Z() {
    if ($r) {
      const response = await fetch($tJ("vscode-oniguruma", "release/onig.wasm"));
      return await response.arrayBuffer();
    } else {
      const response = await fetch($rJ && this.J.isBuilt ? $ih.asBrowserUri(`${$gh}/vscode-oniguruma/release/onig.wasm`).toString(true) : $ih.asBrowserUri(`${$eh}/vscode-oniguruma/release/onig.wasm`).toString(true));
      return response;
    }
  }
  $(timeMs, languageId, sourceExtensionId, lineLength, fromWorker, isRandomSample) {
    const key2 = fromWorker ? "async" : "sync";
    if ($mYb_1.c[key2] > 50) {
      return;
    }
    if ($mYb_1.c[key2] === 0) {
      setTimeout(() => {
        $mYb_1.c[key2] = 0;
      }, 1e3 * 60 * 60);
    }
    $mYb_1.c[key2]++;
    this.M.publicLog2("editor.tokenizedLine", {
      timeMs,
      languageId,
      lineLength,
      fromWorker,
      sourceExtensionId,
      isRandomSample,
      tokenizationSetting: this.N() ? this.O() ? 2 : 1 : 0
    });
  }
};
$mYb = $mYb_1 = __decorate([
  __param(0, $1E),
  __param(1, $rwb),
  __param(2, $Olb),
  __param(3, $PJ),
  __param(4, $wn),
  __param(5, $kl),
  __param(6, $TJ),
  __param(7, $US),
  __param(8, $Pk),
  __param(9, $zv)
], $mYb);
function toColorMap(colorMap) {
  const result = [null];
  for (let i2 = 1, len = colorMap.length; i2 < len; i2++) {
    result[i2] = $Vn.fromHex(colorMap[i2]);
  }
  return result;
}
function equalsTokenRules(a, b) {
  if (!b || !a || b.length !== a.length) {
    return false;
  }
  for (let i2 = b.length - 1; i2 >= 0; i2--) {
    const r1 = b[i2];
    const r2 = a[i2];
    if (r1.scope !== r2.scope) {
      return false;
    }
    const s1 = r1.settings;
    const s2 = r2.settings;
    if (s1 && s2) {
      if (s1.fontStyle !== s2.fontStyle || s1.foreground !== s2.foreground || s1.background !== s2.background) {
        return false;
      }
    } else if (!s1 || !s2) {
      return false;
    }
  }
  return true;
}
function validateGrammarExtensionPoint(extensionLocation, syntax, collector, _languageService) {
  if (syntax.language && (typeof syntax.language !== "string" || !_languageService.isRegisteredLanguageId(syntax.language))) {
    collector.error(localize(13140, null, $lYb.name, String(syntax.language)));
    return false;
  }
  if (!syntax.scopeName || typeof syntax.scopeName !== "string") {
    collector.error(localize(13141, null, $lYb.name, String(syntax.scopeName)));
    return false;
  }
  if (!syntax.path || typeof syntax.path !== "string") {
    collector.error(localize(13142, null, $lYb.name, String(syntax.path)));
    return false;
  }
  if (syntax.injectTo && (!Array.isArray(syntax.injectTo) || syntax.injectTo.some((scope) => typeof scope !== "string"))) {
    collector.error(localize(13143, null, $lYb.name, JSON.stringify(syntax.injectTo)));
    return false;
  }
  if (syntax.embeddedLanguages && !$Bg(syntax.embeddedLanguages)) {
    collector.error(localize(13144, null, $lYb.name, JSON.stringify(syntax.embeddedLanguages)));
    return false;
  }
  if (syntax.tokenTypes && !$Bg(syntax.tokenTypes)) {
    collector.error(localize(13145, null, $lYb.name, JSON.stringify(syntax.tokenTypes)));
    return false;
  }
  const grammarLocation = $vh(extensionLocation, syntax.path);
  if (!$ph(grammarLocation, extensionLocation)) {
    collector.warn(localize(13146, null, $lYb.name, grammarLocation.path, extensionLocation.path));
  }
  return true;
}
function observableConfigValue(key2, languageId, defaultValue, configurationService) {
  return $Dd((handleChange) => configurationService.onDidChangeConfiguration((e) => {
    if (e.affectsConfiguration(key2, { overrideIdentifier: languageId })) {
      handleChange(e);
    }
  }), () => configurationService.getValue(key2, { overrideIdentifier: languageId }) ?? defaultValue);
}

// out-build/vs/workbench/services/textMate/browser/textMateTokenizationFeature.contribution.js
var TextMateTokenizationInstantiator = class TextMateTokenizationInstantiator2 {
  static {
    this.ID = "workbench.contrib.textMateTokenizationInstantiator";
  }
  constructor(_textMateTokenizationService) {
  }
};
TextMateTokenizationInstantiator = __decorate([
  __param(0, $FGb)
], TextMateTokenizationInstantiator);
$SC(
  $FGb,
  $mYb,
  0
  /* InstantiationType.Eager */
);
$PL(
  TextMateTokenizationInstantiator.ID,
  TextMateTokenizationInstantiator,
  2
  /* WorkbenchPhase.BlockRestore */
);
$tn.registerCommand("_workbench.colorizeTextMateTokens", async (accessor, resource) => {
  const textModelService = accessor.get($cK);
  const textModel = resource ? (await textModelService.files.resolve(resource)).textEditorModel : void 0;
  if (!textModel) {
    throw new Error(`Cannot resolve text model for resource ${resource}`);
  }
  const tokenizer = await $YE.getOrCreate(textModel.getLanguageId());
  if (!tokenizer) {
    throw new Error(`Cannot resolve tokenizer for language ${textModel.getLanguageId()}`);
  }
  const stopwatch = new $te();
  let state = tokenizer.getInitialState();
  for (let i2 = 1; i2 <= textModel.getLineCount(); i2++) {
    state = tokenizer.tokenizeEncoded(textModel.getLineContent(i2), true, state).endState;
  }
  stopwatch.stop();
  return { tokenizeTime: stopwatch.elapsed() };
});

// out-build/vs/editor/browser/services/treeSitter/treeSitterParserService.js
var EDITOR_TREESITTER_TELEMETRY = "editor.experimental.treeSitterTelemetry";
var MODULE_LOCATION_SUBPATH = `@vscode/tree-sitter-wasm/wasm`;
var FILENAME_TREESITTER_WASM = `tree-sitter.wasm`;
function getModuleLocation(environmentService) {
  return `${$rJ && environmentService.isBuilt ? $gh : $eh}/${MODULE_LOCATION_SUBPATH}`;
}
var $nYb = class extends $3c {
  get parseResult() {
    return this.b;
  }
  constructor(model, c, f, g, h3, parseImmediately = true) {
    super();
    this.model = model;
    this.c = c;
    this.f = f;
    this.g = g;
    this.h = h3;
    this.a = this.B(new $ze());
    this.onDidChangeParseResult = this.a.event;
    this.j = this.B(new $2c());
    if (parseImmediately) {
      this.B(Event2.runAndSubscribe(this.model.onDidChangeLanguage, (e) => this.m(e ? e.newLanguage : this.model.getLanguageId())));
    } else {
      this.B(this.model.onDidChangeLanguage((e) => this.m(e ? e.newLanguage : this.model.getLanguageId())));
    }
  }
  /**
   * Be very careful when making changes to this method as it is easy to introduce race conditions.
   */
  async m(languageId) {
    this.parse(languageId);
  }
  async parse(languageId = this.model.getLanguageId()) {
    this.j.clear();
    this.b = void 0;
    const token = $bd(this.j);
    let language;
    try {
      language = await this.n(languageId, token);
    } catch (e) {
      if ($kb(e)) {
        return;
      }
      throw e;
    }
    const Parser2 = await this.f.getParserClass();
    if (token.isCancellationRequested) {
      return;
    }
    const treeSitterTree = this.j.add(new $oYb(new Parser2(), language, this.g, this.h));
    this.j.add(this.model.onDidChangeContent((e) => this.s(treeSitterTree, e.changes)));
    await this.s(treeSitterTree, []);
    if (token.isCancellationRequested) {
      return;
    }
    this.b = treeSitterTree;
    return this.b;
  }
  n(languageId, token) {
    const language = this.c.getOrInitLanguage(languageId);
    if (language) {
      return Promise.resolve(language);
    }
    const disposables = [];
    return new Promise((resolve, reject) => {
      disposables.push(this.c.onDidAddLanguage((e) => {
        if (e.id === languageId) {
          $Xc(disposables);
          resolve(e.language);
        }
      }));
      token.onCancellationRequested(() => {
        $Xc(disposables);
        reject(new $lb());
      }, void 0, disposables);
    });
  }
  async s(treeSitterTree, changes) {
    const diff3 = await treeSitterTree.onDidChangeContent(this.model, changes);
    if (!diff3 || diff3.length > 0) {
      const ranges = diff3 ? diff3.map((r2) => new $9C(r2.startPosition.row + 1, r2.startPosition.column + 1, r2.endPosition.row + 1, r2.endPosition.column + 1)) : [this.model.getFullModelRange()];
      this.a.fire(ranges);
    }
  }
};
var TelemetryParseType;
(function(TelemetryParseType2) {
  TelemetryParseType2["Full"] = "fullParse";
  TelemetryParseType2["Incremental"] = "incrementalParse";
})(TelemetryParseType || (TelemetryParseType = {}));
var $oYb = class {
  constructor(parser2, language, c, d) {
    this.parser = parser2;
    this.language = language;
    this.c = c;
    this.d = d;
    this.b = false;
    this.g = Promise.resolve();
    this.h = true;
    this.parser.setTimeoutMicros(50 * 1e3);
    this.parser.setLanguage(language);
  }
  dispose() {
    this.b = true;
    this.a?.delete();
    this.parser?.delete();
  }
  get f() {
    return this.a;
  }
  set f(newTree) {
    this.a?.delete();
    this.a = newTree;
  }
  get isDisposed() {
    return this.b;
  }
  async onDidChangeContent(model, changes) {
    const oldTree = this.f?.copy();
    this.i(model, changes);
    return new Promise((resolve) => {
      this.g = this.g.then(async () => {
        if (this.isDisposed) {
          return;
        }
        await this.j(model);
        resolve(this.f && oldTree ? oldTree.getChangedRanges(this.f) : void 0);
      }).catch((e) => {
        this.c.error("Error parsing tree-sitter tree", e);
      });
    });
  }
  i(model, changes) {
    for (const change of changes) {
      const newEndOffset = change.rangeOffset + change.text.length;
      const newEndPosition = model.getPositionAt(newEndOffset);
      this.f?.edit({
        startIndex: change.rangeOffset,
        oldEndIndex: change.rangeOffset + change.rangeLength,
        newEndIndex: change.rangeOffset + change.text.length,
        startPosition: { row: change.range.startLineNumber - 1, column: change.range.startColumn - 1 },
        oldEndPosition: { row: change.range.endLineNumber - 1, column: change.range.endColumn - 1 },
        newEndPosition: { row: newEndPosition.lineNumber - 1, column: newEndPosition.column - 1 }
      });
      this.h = true;
    }
  }
  async j(model) {
    const tree = await this.k(model);
    if (!this.h) {
      this.f = tree;
    }
  }
  k(model) {
    let parseType = "fullParse";
    if (this.f) {
      parseType = "incrementalParse";
    }
    return this.l(model, parseType);
  }
  async l(model, parseType) {
    const language = model.getLanguageId();
    let tree;
    let time = 0;
    let passes = 0;
    this.h = false;
    do {
      const timer = performance.now();
      try {
        tree = this.parser.parse((index, position) => this.m(model, index), this.f);
      } catch (e) {
      } finally {
        time += performance.now() - timer;
        passes++;
      }
      await new Promise((resolve) => $E(resolve));
      if (model.isDisposed() || this.isDisposed) {
        return;
      }
    } while (!tree && !this.h);
    this.n(parseType, language, time, passes);
    return tree;
  }
  m(textModel, index) {
    try {
      return textModel.getTextBuffer().getNearestChunk(index);
    } catch (e) {
      this.c.debug("Error getting chunk for tree-sitter parsing", e);
    }
    return null;
  }
  n(parseType, languageId, time, passes) {
    this.c.debug(`Tree parsing (${parseType}) took ${time} ms and ${passes} passes.`);
    if (parseType === "fullParse") {
      this.d.publicLog2(`treeSitter.fullParse`, { languageId, time, passes });
    } else {
      this.d.publicLog2(`treeSitter.incrementalParse`, { languageId, time, passes });
    }
  }
};
var $pYb = class extends $3c {
  constructor(b, c, f, g) {
    super();
    this.b = b;
    this.c = c;
    this.f = f;
    this.g = g;
    this.a = new AsyncCache();
    this._onDidAddLanguage = this.B(new $ze());
    this.onDidAddLanguage = this._onDidAddLanguage.event;
  }
  getOrInitLanguage(languageId) {
    if (this.a.isCached(languageId)) {
      return this.a.getSyncIfCached(languageId);
    } else {
      this.h(languageId);
      return void 0;
    }
  }
  async getLanguage(languageId) {
    if (this.a.isCached(languageId)) {
      return this.a.getSyncIfCached(languageId);
    } else {
      await this.h(languageId);
      return this.a.get(languageId);
    }
  }
  async h(languageId) {
    const languagePromise = this.a.get(languageId);
    if (!languagePromise) {
      this.a.set(languageId, this.j(languageId));
      const language = await this.a.get(languageId);
      if (!language) {
        return void 0;
      }
      this._onDidAddLanguage.fire({ id: languageId, language });
    }
  }
  async j(languageId) {
    const grammarName = this.g.get(languageId);
    const languageLocation = this.m(languageId);
    if (!grammarName || !languageLocation) {
      return void 0;
    }
    const wasmPath = `${languageLocation}/${grammarName}.wasm`;
    const languageFile = await this.c.readFile($ih.asFileUri(wasmPath));
    const Parser2 = await this.b.getParserClass();
    return Parser2.Language.load(languageFile.value.buffer);
  }
  m(languageId) {
    const grammarName = this.g.get(languageId);
    if (!grammarName) {
      return void 0;
    }
    return getModuleLocation(this.f);
  }
};
var $qYb = class {
  async b() {
    if (!this.a) {
      this.a = await $sJ("@vscode/tree-sitter-wasm", "wasm/tree-sitter.js");
    }
    return this.a;
  }
  async getParserClass() {
    if (!this.c) {
      this.c = (await this.b()).Parser;
    }
    return this.c;
  }
};
var $rYb = class $rYb2 extends $3c {
  constructor(j, fileService, m, n, s, t) {
    super();
    this.j = j;
    this.m = m;
    this.n = n;
    this.s = s;
    this.t = t;
    this.b = this.B(new $_c());
    this.c = /* @__PURE__ */ new Map();
    this.f = new $qYb();
    this.h = this.B(new $ze());
    this.onDidUpdateTree = this.h.event;
    this.w = false;
    this.g = this.B(new $pYb(this.f, fileService, this.t, this.c));
    this.onDidAddLanguage = this.g.onDidAddLanguage;
    this.B(this.s.onDidChangeConfiguration((e) => {
      if (e.affectsConfiguration($GI)) {
        this.z();
      }
    }));
    this.z();
  }
  getOrInitLanguage(languageId) {
    return this.g.getOrInitLanguage(languageId);
  }
  getParseResult(textModel) {
    const textModelTreeSitter = this.b.get(textModel);
    return textModelTreeSitter?.textModelTreeSitter.parseResult;
  }
  async getTree(content, languageId) {
    await this.a;
    const language = await this.g.getLanguage(languageId);
    const Parser2 = await this.f.getParserClass();
    if (language) {
      const parser2 = new Parser2();
      parser2.setLanguage(language);
      return parser2.parse(content);
    }
    return void 0;
  }
  async u() {
    const Parser2 = await this.f.getParserClass();
    const environmentService = this.t;
    await Parser2.init({
      locateFile(_file, _folder) {
        return $ih.asBrowserUri(`${getModuleLocation(environmentService)}/${FILENAME_TREESITTER_WASM}`).toString(true);
      }
    });
    return true;
  }
  async y(hasLanguages) {
    if (this.w) {
      return this.a;
    }
    if (hasLanguages) {
      this.w = true;
      this.a = this.u();
      this.a.then(() => this.D());
    } else {
      this.a = Promise.resolve(false);
    }
    return this.a;
  }
  async z() {
    const setting = this.C();
    let hasLanguages = true;
    if (setting.length === 0) {
      hasLanguages = false;
    }
    if (setting.includes("typescript")) {
      this.G("typescript", "tree-sitter-typescript");
    } else {
      this.H("typescript");
    }
    return this.y(hasLanguages);
  }
  C() {
    const setting = this.s.getValue($GI);
    if (setting && setting.length > 0) {
      return setting;
    } else {
      const expSetting = this.s.getValue(EDITOR_TREESITTER_TELEMETRY);
      if (expSetting) {
        return ["typescript"];
      }
    }
    return [];
  }
  async D() {
    this.B(this.j.onModelAdded((model) => {
      this.F(model);
    }));
    this.B(this.j.onModelRemoved((model) => {
      this.b.deleteAndDispose(model);
    }));
    this.j.getModels().forEach((model) => this.F(model));
  }
  getTextModelTreeSitter(model) {
    return new $nYb(model, this.g, this.f, this.n, this.m, false);
  }
  F(model) {
    const textModelTreeSitter = new $nYb(model, this.g, this.f, this.n, this.m);
    const disposables = new $2c();
    disposables.add(textModelTreeSitter);
    disposables.add(textModelTreeSitter.onDidChangeParseResult((ranges) => this.h.fire({ textModel: model, ranges })));
    this.b.set(model, {
      textModelTreeSitter,
      disposables,
      dispose: disposables.dispose.bind(disposables)
    });
  }
  G(languageId, grammarName) {
    if (!this.c.has(languageId)) {
      this.c.set(languageId, grammarName);
    }
  }
  H(languageId) {
    if (this.c.has(languageId)) {
      this.c.delete("typescript");
    }
  }
};
$rYb = __decorate([
  __param(0, $sG),
  __param(1, $km),
  __param(2, $zv),
  __param(3, $wn),
  __param(4, $kl),
  __param(5, $Xk)
], $rYb);
var PromiseWithSyncAccess = class {
  /**
   * Returns undefined if the promise did not resolve yet.
   */
  get result() {
    return this.a;
  }
  constructor(promise) {
    this.promise = promise;
    promise.then((result) => {
      this.a = new $pe(result, void 0);
    }).catch((e) => {
      this.a = new $pe(void 0, e);
    });
  }
};
var AsyncCache = class {
  constructor() {
    this.a = /* @__PURE__ */ new Map();
  }
  set(key2, promise) {
    this.a.set(key2, new PromiseWithSyncAccess(promise));
  }
  get(key2) {
    return this.a.get(key2)?.promise;
  }
  getSyncIfCached(key2) {
    return this.a.get(key2)?.result?.data;
  }
  isCached(key2) {
    return this.a.get(key2)?.result !== void 0;
  }
};

// out-build/vs/workbench/services/treeSitter/browser/treeSitterTokenizationFeature.js
var ALLOWED_SUPPORT = ["typescript"];
var $sYb = $Qk("treeSitterTokenizationFeature");
var TreeSitterTokenizationFeature = class TreeSitterTokenizationFeature2 extends $3c {
  constructor(b, c, f, g) {
    super();
    this.b = b;
    this.c = c;
    this.f = f;
    this.g = g;
    this.a = new $_c();
    this.j();
    this.B(this.c.onDidChangeConfiguration((e) => {
      if (e.affectsConfiguration($GI)) {
        this.j();
      }
    }));
  }
  h() {
    return this.c.getValue($GI) || [];
  }
  j() {
    const setting = this.h();
    for (const languageId of setting) {
      if (ALLOWED_SUPPORT.includes(languageId) && !this.a.has(languageId)) {
        const lazyTokenizationSupport = new $XE(() => this.n(languageId));
        const disposableStore = new $2c();
        disposableStore.add(lazyTokenizationSupport);
        disposableStore.add($ZE.registerFactory(languageId, lazyTokenizationSupport));
        this.a.set(languageId, disposableStore);
        $ZE.getOrCreate(languageId);
      }
    }
    const languagesToUnregister = [...this.a.keys()].filter((languageId) => !setting.includes(languageId));
    for (const languageId of languagesToUnregister) {
      this.a.deleteAndDispose(languageId);
    }
  }
  async m(newLanguage) {
    const languageLocation = `vs/editor/common/languages/highlights/${newLanguage}.scm`;
    const query = await this.g.readFile($ih.asFileUri(languageLocation));
    return query.value.toString();
  }
  async n(languageId) {
    const queries = await this.m(languageId);
    return this.f.createInstance(TreeSitterTokenizationSupport, queries, languageId, this.b.languageIdCodec);
  }
};
TreeSitterTokenizationFeature = __decorate([
  __param(0, $1E),
  __param(1, $kl),
  __param(2, $Pk),
  __param(3, $km)
], TreeSitterTokenizationFeature);
var TreeSitterTokenizationSupport = class TreeSitterTokenizationSupport2 extends $3c {
  constructor(g, h3, j, m, n) {
    super();
    this.g = g;
    this.h = h3;
    this.j = j;
    this.m = m;
    this.n = n;
    this.b = new $ze();
    this.onDidChangeTokens = this.b.event;
    this.B(Event2.runAndSubscribe(this.n.onDidColorThemeChange, () => this.t()));
    this.B(this.m.onDidUpdateTree((e) => {
      const maxLine = e.textModel.getLineCount();
      this.b.fire({
        textModel: e.textModel,
        changes: {
          semanticTokensApplied: false,
          ranges: e.ranges.map((range) => ({ fromLineNumber: range.startLineNumber, toLineNumber: range.endLineNumber < maxLine ? range.endLineNumber : maxLine }))
        }
      });
    }));
  }
  r(textModel) {
    return this.m.getParseResult(textModel);
  }
  s() {
    if (!this.a) {
      const language = this.m.getOrInitLanguage(this.h);
      if (!language) {
        if (!this.f) {
          this.f = this.B(Event2.onceIf(this.m.onDidAddLanguage, (e) => e.id === this.h)((e) => {
            this.a = e.language.query(this.g);
          }));
        }
        return;
      }
      this.a = language.query(this.g);
    }
    return this.a;
  }
  t() {
    this.c = this.n.getColorTheme();
  }
  captureAtPosition(lineNumber, column, textModel) {
    const tree = this.r(textModel);
    const captures = this.u(lineNumber, new $Fcb(column, column), tree?.f);
    return captures;
  }
  captureAtPositionTree(lineNumber, column, tree) {
    const captures = this.u(lineNumber, new $Fcb(column, column), tree);
    return captures;
  }
  u(lineNumber, columnRange, tree) {
    const query = this.s();
    if (!tree || !query) {
      return [];
    }
    return query.captures(tree.rootNode, { startPosition: { row: lineNumber - 1, column: columnRange.startColumn - 1 }, endPosition: { row: lineNumber - 1, column: columnRange.endColumnExclusive } });
  }
  /**
   * Gets the tokens for a given line.
   * Each token takes 2 elements in the array. The first element is the offset of the end of the token *in the line, not in the document*, and the second element is the metadata.
   *
   * @param lineNumber
   * @returns
   */
  tokenizeEncoded(lineNumber, textModel) {
    return this.w(lineNumber, textModel)?.result;
  }
  tokenizeEncodedInstrumented(lineNumber, textModel) {
    return this.w(lineNumber, textModel);
  }
  w(lineNumber, textModel) {
    const stopwatch = $te.create();
    const lineLength = textModel.getLineMaxColumn(lineNumber);
    const tree = this.r(textModel);
    const captures = this.u(lineNumber, new $Fcb(1, lineLength), tree?.f);
    if (captures.length === 0) {
      return void 0;
    }
    const endOffsetsAndScopes = Array(captures.length);
    endOffsetsAndScopes.fill({ endOffset: 0, scopes: [] });
    let tokenIndex = 0;
    const lineStartOffset = textModel.getOffsetAt({ lineNumber, column: 1 });
    const increaseSizeOfTokensByOneToken = () => {
      endOffsetsAndScopes.push({ endOffset: 0, scopes: [] });
    };
    const encodedLanguageId = this.j.encodeLanguageId(this.h);
    for (let captureIndex = 0; captureIndex < captures.length; captureIndex++) {
      const capture = captures[captureIndex];
      const tokenEndIndex = capture.node.endIndex < lineStartOffset + lineLength ? capture.node.endIndex : lineStartOffset + lineLength;
      const tokenStartIndex = capture.node.startIndex < lineStartOffset ? lineStartOffset : capture.node.startIndex;
      const lineRelativeOffset = tokenEndIndex - lineStartOffset;
      let previousTokenEnd;
      const currentTokenLength = tokenEndIndex - tokenStartIndex;
      if (captureIndex > 0) {
        previousTokenEnd = endOffsetsAndScopes[tokenIndex - 1].endOffset;
      } else {
        previousTokenEnd = tokenStartIndex - lineStartOffset - 1;
      }
      const intermediateTokenOffset = lineRelativeOffset - currentTokenLength;
      if (previousTokenEnd >= 0 && previousTokenEnd < intermediateTokenOffset) {
        endOffsetsAndScopes[tokenIndex] = { endOffset: intermediateTokenOffset, scopes: [] };
        tokenIndex++;
        increaseSizeOfTokensByOneToken();
      }
      const addCurrentTokenToArray = () => {
        endOffsetsAndScopes[tokenIndex] = { endOffset: lineRelativeOffset, scopes: [capture.name] };
        tokenIndex++;
      };
      if (previousTokenEnd >= lineRelativeOffset) {
        const previousTokenStartOffset = tokenIndex >= 2 ? endOffsetsAndScopes[tokenIndex - 2].endOffset : 0;
        const originalPreviousTokenEndOffset = endOffsetsAndScopes[tokenIndex - 1].endOffset;
        if (previousTokenStartOffset + currentTokenLength === originalPreviousTokenEndOffset) {
          endOffsetsAndScopes[tokenIndex - 1].scopes[endOffsetsAndScopes[tokenIndex - 1].scopes.length - 1] = capture.name;
        } else {
          endOffsetsAndScopes[tokenIndex - 1].endOffset = intermediateTokenOffset;
          addCurrentTokenToArray();
          increaseSizeOfTokensByOneToken();
          endOffsetsAndScopes[tokenIndex].endOffset = originalPreviousTokenEndOffset;
          endOffsetsAndScopes[tokenIndex].scopes = endOffsetsAndScopes[tokenIndex - 2].scopes;
          tokenIndex++;
        }
      } else {
        addCurrentTokenToArray();
      }
    }
    if (captures[captures.length - 1].node.endPosition.column + 1 < lineLength) {
      increaseSizeOfTokensByOneToken();
      endOffsetsAndScopes[tokenIndex].endOffset = lineLength - 1;
      tokenIndex++;
    }
    const captureTime = stopwatch.elapsed();
    stopwatch.reset();
    const tokens = new Uint32Array(tokenIndex * 2);
    for (let i2 = 0; i2 < tokenIndex; i2++) {
      const token = endOffsetsAndScopes[i2];
      if (token.endOffset === 0 && token.scopes.length === 0) {
        break;
      }
      tokens[i2 * 2] = token.endOffset;
      tokens[i2 * 2 + 1] = $6Gb(this.c, token.scopes, encodedLanguageId);
    }
    const metadataTime = stopwatch.elapsed();
    return { result: tokens, captureTime, metadataTime };
  }
  dispose() {
    super.dispose();
    this.a?.delete();
    this.a = void 0;
  }
};
TreeSitterTokenizationSupport = __decorate([
  __param(3, $HI),
  __param(4, $gs)
], TreeSitterTokenizationSupport);
$SC(
  $sYb,
  TreeSitterTokenizationFeature,
  0
  /* InstantiationType.Eager */
);

// out-build/vs/workbench/services/treeSitter/browser/treeSitterTokenizationFeature.contribution.js
var TreeSitterTokenizationInstantiator = class TreeSitterTokenizationInstantiator2 {
  static {
    this.ID = "workbench.contrib.treeSitterTokenizationInstantiator";
  }
  constructor(_treeSitterTokenizationService, _treeSitterTokenizationFeature) {
  }
};
TreeSitterTokenizationInstantiator = __decorate([
  __param(0, $HI),
  __param(1, $sYb)
], TreeSitterTokenizationInstantiator);
$SC(
  $HI,
  $rYb,
  0
  /* InstantiationType.Eager */
);
$PL(
  TreeSitterTokenizationInstantiator.ID,
  TreeSitterTokenizationInstantiator,
  2
  /* WorkbenchPhase.BlockRestore */
);
$tn.registerCommand("_workbench.colorizeTreeSitterTokens", async (accessor, resource) => {
  const treeSitterParserService = accessor.get($HI);
  const textModelService = accessor.get($cK);
  const textModel = resource ? (await textModelService.files.resolve(resource)).textEditorModel : void 0;
  if (!textModel) {
    throw new Error(`Cannot resolve text model for resource ${resource}`);
  }
  const tokenizer = await $ZE.getOrCreate(textModel.getLanguageId());
  if (!tokenizer) {
    throw new Error(`Cannot resolve tokenizer for language ${textModel.getLanguageId()}`);
  }
  const textModelTreeSitter = treeSitterParserService.getTextModelTreeSitter(textModel);
  if (!textModelTreeSitter) {
    throw new Error(`Cannot resolve tree sitter parser for language ${textModel.getLanguageId()}`);
  }
  const stopwatch = new $te();
  await textModelTreeSitter.parse();
  stopwatch.stop();
  let captureTime = 0;
  let metadataTime = 0;
  for (let i2 = 1; i2 <= textModel.getLineCount(); i2++) {
    const result = tokenizer.tokenizeEncodedInstrumented(i2, textModel);
    if (result) {
      captureTime += result.captureTime;
      metadataTime += result.metadataTime;
    }
  }
  textModelTreeSitter.dispose();
  textModel.dispose();
  return { parseTime: stopwatch.elapsed(), captureTime, metadataTime };
});

// out-build/vs/workbench/services/userActivity/browser/domActivityTracker.js
var CHECK_INTERVAL = 3e4;
var MIN_INTERVALS_WITHOUT_ACTIVITY = 2;
var eventListenerOptions = {
  passive: true,
  /** does not preventDefault() */
  capture: true
  /** should dispatch first (before anyone stopPropagation()) */
};
var $tYb = class extends $3c {
  constructor(userActivityService) {
    super();
    let intervalsWithoutActivity = MIN_INTERVALS_WITHOUT_ACTIVITY;
    const intervalTimer = this.B(new $lj());
    const activeMutex = this.B(new $4c());
    activeMutex.value = userActivityService.markActive();
    const onInterval = () => {
      if (++intervalsWithoutActivity === MIN_INTERVALS_WITHOUT_ACTIVITY) {
        activeMutex.clear();
        intervalTimer.cancel();
      }
    };
    const onActivity = (targetWindow) => {
      if (intervalsWithoutActivity === MIN_INTERVALS_WITHOUT_ACTIVITY) {
        activeMutex.value = userActivityService.markActive();
        intervalTimer.cancelAndSet(onInterval, CHECK_INTERVAL, targetWindow);
      }
      intervalsWithoutActivity = 0;
    };
    this.B(Event2.runAndSubscribe(onDidRegisterWindow, ({ window: window3, disposables }) => {
      disposables.add($_i(window3.document, "touchstart", () => onActivity(window3), eventListenerOptions));
      disposables.add($_i(window3.document, "mousedown", () => onActivity(window3), eventListenerOptions));
      disposables.add($_i(window3.document, "keydown", () => onActivity(window3), eventListenerOptions));
    }, { window: $Y, disposables: this.q }));
    onActivity($Y);
  }
};

// out-build/vs/workbench/services/userActivity/browser/userActivityBrowser.js
$PRb.add($tYb);

// out-build/vs/workbench/services/editor/browser/editorPaneService.js
var $uYb = class {
  constructor() {
    this.onWillInstantiateEditorPane = $7tb.onWillInstantiateEditorPane;
  }
  didInstantiateEditorPane(typeId2) {
    return $7tb.didInstantiateEditorPane(typeId2);
  }
};
$SC(
  $NL,
  $uYb,
  1
  /* InstantiationType.Delayed */
);

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

// 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 $UA(version2) {
  version2 = version2.trim();
  return version2 === "*" || VERSION_REGEXP.test(version2);
}
function $VA(version2) {
  if (!$UA(version2)) {
    return null;
  }
  version2 = version2.trim();
  if (version2 === "*") {
    return {
      hasCaret: false,
      hasGreaterEquals: false,
      majorBase: 0,
      majorMustEqual: false,
      minorBase: 0,
      minorMustEqual: false,
      patchBase: 0,
      patchMustEqual: false,
      preRelease: null
    };
  }
  const m = version2.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 $WA(version2) {
  if (!version2) {
    return null;
  }
  const majorBase = version2.majorBase;
  const majorMustEqual = version2.majorMustEqual;
  const minorBase = version2.minorBase;
  let minorMustEqual = version2.minorMustEqual;
  const patchBase = version2.patchBase;
  let patchMustEqual = version2.patchMustEqual;
  if (version2.hasCaret) {
    if (majorBase === 0) {
      patchMustEqual = false;
    } else {
      minorMustEqual = false;
      patchMustEqual = false;
    }
  }
  let notBefore = 0;
  if (version2.preRelease) {
    const match = NOT_BEFORE_REGEXP.exec(version2.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: version2.hasGreaterEquals,
    notBefore
  };
}
function $XA(_inputVersion, _inputDate, _desiredVersion) {
  let version2;
  if (typeof _inputVersion === "string") {
    version2 = $WA($VA(_inputVersion));
  } else {
    version2 = _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 = $WA($VA(_desiredVersion));
  } else {
    desiredVersion = _desiredVersion;
  }
  if (!version2 || !desiredVersion) {
    return false;
  }
  const majorBase = version2.majorBase;
  const minorBase = version2.minorBase;
  const patchBase = version2.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 $YA(productVersion, productDate, extensionLocation, extensionManifest, extensionIsBuiltin, validateApiVersion) {
  const validations = [];
  if (typeof extensionManifest.publisher !== "undefined" && typeof extensionManifest.publisher !== "string") {
    validations.push([severity_default.Error, localize(1876, null)]);
    return validations;
  }
  if (typeof extensionManifest.name !== "string") {
    validations.push([severity_default.Error, localize(1877, null, "name")]);
    return validations;
  }
  if (typeof extensionManifest.version !== "string") {
    validations.push([severity_default.Error, localize(1878, null, "version")]);
    return validations;
  }
  if (!extensionManifest.engines) {
    validations.push([severity_default.Error, localize(1879, null, "engines")]);
    return validations;
  }
  if (typeof extensionManifest.engines.vscode !== "string") {
    validations.push([severity_default.Error, localize(1880, null, "engines.vscode")]);
    return validations;
  }
  if (typeof extensionManifest.extensionDependencies !== "undefined") {
    if (!isStringArray(extensionManifest.extensionDependencies)) {
      validations.push([severity_default.Error, localize(1881, null, "extensionDependencies")]);
      return validations;
    }
  }
  if (typeof extensionManifest.activationEvents !== "undefined") {
    if (!isStringArray(extensionManifest.activationEvents)) {
      validations.push([severity_default.Error, localize(1882, null, "activationEvents")]);
      return validations;
    }
    if (typeof extensionManifest.main === "undefined" && typeof extensionManifest.browser === "undefined") {
      validations.push([severity_default.Error, localize(1883, null, "activationEvents", "main", "browser")]);
      return validations;
    }
  }
  if (typeof extensionManifest.extensionKind !== "undefined") {
    if (typeof extensionManifest.main === "undefined") {
      validations.push([severity_default.Warning, localize(1884, null, "extensionKind")]);
    }
  }
  if (typeof extensionManifest.main !== "undefined") {
    if (typeof extensionManifest.main !== "string") {
      validations.push([severity_default.Error, localize(1885, null, "main")]);
      return validations;
    } else {
      const mainLocation = $vh(extensionLocation, extensionManifest.main);
      if (!$ph(mainLocation, extensionLocation)) {
        validations.push([severity_default.Warning, localize(1886, null, mainLocation.path, extensionLocation.path)]);
      }
    }
  }
  if (typeof extensionManifest.browser !== "undefined") {
    if (typeof extensionManifest.browser !== "string") {
      validations.push([severity_default.Error, localize(1887, null, "browser")]);
      return validations;
    } else {
      const browserLocation = $vh(extensionLocation, extensionManifest.browser);
      if (!$ph(browserLocation, extensionLocation)) {
        validations.push([severity_default.Warning, localize(1888, null, browserLocation.path, extensionLocation.path)]);
      }
    }
  }
  if (!valid(extensionManifest.version)) {
    validations.push([severity_default.Error, localize(1889, null)]);
    return validations;
  }
  const notices = [];
  const validExtensionVersion = $ZA(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 (!$2A([...extensionManifest.enabledApiProposals], incompatibleNotices)) {
      for (const notice of incompatibleNotices) {
        validations.push([severity_default.Error, notice]);
      }
    }
  }
  return validations;
}
function $ZA(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 $1A(engine, version2, date) {
  return engine === "*" || isVersionValid(version2, date, engine);
}
function $2A(apiProposals, arg1) {
  if (apiProposals.length === 0) {
    return true;
  }
  const notices = Array.isArray(arg1) ? arg1 : void 0;
  const productApiProposals = (notices ? void 0 : arg1) ?? allApiProposals;
  const incompatibleProposals = [];
  const parsedProposals = $_z(apiProposals);
  for (const { proposalName, version: version2 } of parsedProposals) {
    if (!version2) {
      continue;
    }
    const existingProposal = productApiProposals[proposalName];
    if (existingProposal?.version !== version2) {
      incompatibleProposals.push(proposalName);
    }
  }
  if (incompatibleProposals.length) {
    if (notices) {
      if (incompatibleProposals.length === 1) {
        notices.push(localize(1890, null, incompatibleProposals[0]));
      } else {
        notices.push(localize(1891, null, incompatibleProposals.slice(0, incompatibleProposals.length - 1).map((p) => `'${p}'`).join(", "), incompatibleProposals[incompatibleProposals.length - 1]));
      }
    }
    return false;
  }
  return true;
}
function isVersionValid(currentVersion, date, requestedVersion, notices = []) {
  const desiredVersion = $WA($VA(requestedVersion));
  if (!desiredVersion) {
    notices.push(localize(1892, null, requestedVersion));
    return false;
  }
  if (desiredVersion.majorBase === 0) {
    if (!desiredVersion.majorMustEqual || !desiredVersion.minorMustEqual) {
      notices.push(localize(1893, null, requestedVersion));
      return false;
    }
  } else {
    if (!desiredVersion.majorMustEqual) {
      notices.push(localize(1894, null, requestedVersion));
      return false;
    }
  }
  if (!$XA(currentVersion, date, desiredVersion)) {
    notices.push(localize(1895, null, currentVersion, requestedVersion));
    return false;
  }
  return true;
}
function isStringArray(arr) {
  if (!Array.isArray(arr)) {
    return false;
  }
  for (let i2 = 0, len = arr.length; i2 < len; i2++) {
    if (typeof arr[i2] !== "string") {
      return false;
    }
  }
  return true;
}

// out-build/vs/platform/externalServices/common/marketplace.js
async function $qw(version2, productService, environmentService, configurationService, fileService, storageService, telemetryService) {
  const headers = {
    "X-Market-Client-Id": `VSCode ${version2}`,
    "User-Agent": `VSCode ${version2} (${productService.nameShort})`
  };
  if ($iw(productService, environmentService) && $kw(configurationService) === 3) {
    const serviceMachineId = await $7v(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" : $lA($x, $ic);
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((r2, f) => r2 | 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((r2, f) => r2 | 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 filters2 = [{ criteria, pageNumber, pageSize, sortBy, sortOrder }];
    return { filters: filters2, 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(version2) {
  const coreTranslationAssetPrefix = "Microsoft.VisualStudio.Code.Translation.";
  const result = version2.files.filter((f) => f.assetType.indexOf(coreTranslationAssetPrefix) === 0);
  return result.reduce((result2, file) => {
    const asset = getVersionAsset(version2, file.assetType);
    if (asset) {
      result2.push([file.assetType.substring(coreTranslationAssetPrefix.length), asset]);
    }
    return result2;
  }, []);
}
function getRepositoryAsset(version2) {
  if (version2.properties) {
    const results = version2.properties.filter((p) => p.key === AssetType.Repository);
    const gitRegExp = new RegExp("((git|ssh|http(s)?)|(git@[\\w.]+))(:(//)?)([\\w.@:/\\-~]+)(.git)(/)?");
    const uri = results.filter((r2) => gitRegExp.test(r2.value))[0];
    return uri ? { uri: uri.value, fallbackUri: uri.value } : null;
  }
  return getVersionAsset(version2, AssetType.Repository);
}
function getDownloadAsset(version2) {
  return {
    // always use fallbackAssetUri for download asset to hit the Marketplace API so that downloads are counted
    uri: `${version2.fallbackAssetUri}/${AssetType.VSIX}?redirect=true${version2.targetPlatform ? `&targetPlatform=${version2.targetPlatform}` : ""}`,
    fallbackUri: `${version2.fallbackAssetUri}/${AssetType.VSIX}${version2.targetPlatform ? `?targetPlatform=${version2.targetPlatform}` : ""}`
  };
}
function getVersionAsset(version2, type) {
  const result = version2.files.filter((f) => f.assetType === type)[0];
  return result ? {
    uri: `${version2.assetUri}/${type}${version2.targetPlatform ? `?targetPlatform=${version2.targetPlatform}` : ""}`,
    fallbackUri: `${version2.fallbackAssetUri}/${type}${version2.targetPlatform ? `?targetPlatform=${version2.targetPlatform}` : ""}`
  } : null;
}
function getExtensions(version2, property) {
  const values = version2.properties ? version2.properties.filter((p) => p.key === property) : [];
  const value = values.length > 0 && values[0].value;
  return value ? value.split(",").map((v) => $HA(v)) : [];
}
function getEngine(version2) {
  const values = version2.properties ? version2.properties.filter((p) => p.key === PropertyType.Engine) : [];
  return values.length > 0 && values[0].value || "";
}
function isPreReleaseVersion(version2) {
  const values = version2.properties ? version2.properties.filter((p) => p.key === PropertyType.PreRelease) : [];
  return values.length > 0 && values[0].value === "true";
}
function executesCode(version2) {
  const values = version2.properties ? version2.properties.filter((p) => p.key === PropertyType.ExecutesCode) : [];
  return values.length > 0 ? values[0].value === "true" : void 0;
}
function getEnabledApiProposals(version2) {
  const values = version2.properties ? version2.properties.filter((p) => p.key === PropertyType.EnabledApiProposals) : [];
  const value = values.length > 0 && values[0].value || "";
  return value ? value.split(",") : [];
}
function getLocalizedLanguages(version2) {
  const values = version2.properties ? version2.properties.filter((p) => p.key === PropertyType.LocalizedLanguages) : [];
  const value = values.length > 0 && values[0].value || "";
  return value ? value.split(",") : [];
}
function getSponsorLink(version2) {
  return version2.properties?.find((p) => p.key === PropertyType.SponsorLink)?.value;
}
function getSupportLink(version2) {
  return version2.properties?.find((p) => p.key === PropertyType.SupportLink)?.value;
}
function getIsPreview(flags) {
  return flags.indexOf("preview") !== -1;
}
function getTargetPlatformForExtensionVersion(version2) {
  return version2.targetPlatform ? $kA(version2.targetPlatform) : "undefined";
}
function getAllTargetPlatforms(rawGalleryExtension) {
  const allTargetPlatforms = $Rb(rawGalleryExtension.versions.map(getTargetPlatformForExtensionVersion));
  const isWebExtension = !!rawGalleryExtension.tags?.includes($eA);
  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 $9W(versions, preferredTargetPlatform) {
  for (let index = 0; index < versions.length; index++) {
    const version2 = versions[index];
    if (version2.version === versions[index - 1]?.version) {
      let insertionIndex = index;
      const versionTargetPlatform = getTargetPlatformForExtensionVersion(version2);
      if (versionTargetPlatform === preferredTargetPlatform) {
        while (insertionIndex > 0 && versions[insertionIndex - 1].version === version2.version) {
          insertionIndex--;
        }
      }
      if (insertionIndex !== index) {
        versions.splice(index, 1);
        versions.splice(insertionIndex, 0, version2);
      }
    }
  }
  return versions;
}
function setTelemetry(extension, index, querySource) {
  extension.telemetryData = { index, querySource, queryActivityId: extension.queryContext?.[ACTIVITY_HEADER_NAME] };
}
function toExtension(galleryExtension, version2, allTargetPlatforms, queryContext) {
  const latestVersion = galleryExtension.versions[0];
  const assets = {
    manifest: getVersionAsset(version2, AssetType.Manifest),
    readme: getVersionAsset(version2, AssetType.Details),
    changelog: getVersionAsset(version2, AssetType.Changelog),
    license: getVersionAsset(version2, AssetType.License),
    repository: getRepositoryAsset(version2),
    download: getDownloadAsset(version2),
    icon: getVersionAsset(version2, AssetType.Icon),
    signature: getVersionAsset(version2, AssetType.Signature),
    coreTranslations: getCoreTranslationAssets(version2)
  };
  return {
    type: "gallery",
    identifier: {
      id: $IA(galleryExtension.publisher.publisherName, galleryExtension.extensionName),
      uuid: galleryExtension.extensionId
    },
    name: galleryExtension.extensionName,
    version: version2.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(version2, PropertyType.Dependency),
      extensionPack: getExtensions(version2, PropertyType.ExtensionPack),
      engine: getEngine(version2),
      enabledApiProposals: getEnabledApiProposals(version2),
      localizedLanguages: getLocalizedLanguages(version2),
      targetPlatform: getTargetPlatformForExtensionVersion(version2),
      isPreReleaseVersion: isPreReleaseVersion(version2),
      executesCode: executesCode(version2)
    },
    hasPreReleaseVersion: isPreReleaseVersion(latestVersion),
    hasReleaseVersion: true,
    preview: getIsPreview(galleryExtension.flags),
    isSigned: !!assets.signature,
    queryContext,
    supportLink: getSupportLink(latestVersion)
  };
}
var AbstractExtensionGalleryService = class AbstractExtensionGalleryService2 {
  constructor(storageService, n, o, q, u, w, x, y, z) {
    this.n = n;
    this.o = o;
    this.q = q;
    this.u = u;
    this.w = w;
    this.x = x;
    this.y = y;
    this.z = z;
    const config = x.extensionsGallery;
    const isPPEEnabled = config?.servicePPEUrl && y.getValue("_extensionsGallery.enablePPE");
    this.d = isPPEEnabled ? config.servicePPEUrl : config?.serviceUrl;
    this.g = isPPEEnabled ? void 0 : config?.searchUrl;
    this.h = config?.controlUrl;
    this.j = config?.extensionUrlTemplate;
    this.l = x.extensionsEnabledWithApiProposalVersion?.map((id2) => id2.toLowerCase()) ?? [];
    this.k = $qw(x.version, x, this.q, this.y, this.w, storageService, this.u);
  }
  A(path = "") {
    return `${this.d}${path}`;
  }
  isEnabled() {
    return !!this.d;
  }
  async getExtensions(extensionInfos, arg1, arg2) {
    if (!this.isEnabled()) {
      throw new Error("No extension gallery service configured.");
    }
    const options3 = CancellationToken.isCancellationToken(arg1) ? {} : arg1;
    const token = CancellationToken.isCancellationToken(arg1) ? arg1 : arg2;
    const useResourceApi = options3.preferResourceApi && (this.y.getValue($BA) ?? false);
    const result = useResourceApi ? await this.C(extensionInfos, options3, token) : await this.B(extensionInfos, options3, token);
    const uuids = result.map((r2) => r2.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.u.publicLog2("galleryService:additionalQueryByName", {
        count: extensionInfosByName.length
      });
      const extensions = await this.B(extensionInfosByName, options3, token);
      result.push(...extensions);
    }
    return result;
  }
  async B(extensionInfos, options3, 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 (options3.queryAllVersions || isQueryForReleaseVersionFromPreReleaseVersion) {
      query = query.withFlags(query.flags, Flags.IncludeVersions);
    }
    if (options3.source) {
      query = query.withSource(options3.source);
    }
    const { extensions } = await this.F(query, { targetPlatform: options3.targetPlatform ?? CURRENT_TARGET_PLATFORM, includePreRelease: includePreReleases, versions, compatible: !!options3.compatible, productVersion: options3.productVersion ?? { version: this.x.version, date: this.x.date } }, token);
    if (options3.source) {
      extensions.forEach((e, index) => setTelemetry(e, index, options3.source));
    }
    return extensions;
  }
  async C(extensionInfos, options3, token) {
    const toQuery = [];
    const result = [];
    await Promise.allSettled(extensionInfos.map(async (extensionInfo) => {
      if (extensionInfo.version) {
        toQuery.push(extensionInfo);
        return;
      }
      try {
        const rawGalleryExtension = await this.I(extensionInfo.id, token);
        if (!rawGalleryExtension) {
          toQuery.push(extensionInfo);
          return;
        }
        const extension = await this.G(rawGalleryExtension, {
          targetPlatform: options3.targetPlatform ?? CURRENT_TARGET_PLATFORM,
          includePreRelease: !!extensionInfo.preRelease,
          compatible: !!options3.compatible,
          productVersion: options3.productVersion ?? {
            version: this.x.version,
            date: this.x.date
          }
        });
        if (extension) {
          result.push(extension);
        } else {
          this.u.publicLog2("galleryService:fallbacktoquery", {
            extension: extensionInfo.id,
            preRelease: !!extensionInfo.preRelease,
            compatible: !!options3.compatible
          });
          if (!options3.compatible || this.z.isAllowed({ id: extensionInfo.id, publisherDisplayName: rawGalleryExtension.publisher.displayName }) === true) {
            toQuery.push(extensionInfo);
          }
        }
      } catch (error) {
        this.o.error(`Error while getting the latest version for the extension ${extensionInfo.id}.`, $qb(error));
        toQuery.push(extensionInfo);
      }
    }));
    const extensions = await this.B(toQuery, options3, token);
    result.push(...extensions);
    return result;
  }
  async getCompatibleExtension(extension, includePreRelease, targetPlatform, productVersion = { version: this.x.version, date: this.x.date }) {
    if ($mA(extension.allTargetPlatforms, targetPlatform)) {
      return null;
    }
    if (await this.isExtensionCompatible(extension, includePreRelease, targetPlatform)) {
      return extension;
    }
    if (this.z.isAllowed({ id: extension.identifier.id, publisherDisplayName: extension.publisherDisplayName }) !== true) {
      return null;
    }
    const query = new Query().withFlags(Flags.IncludeVersions).withPage(1, 1).withFilter(FilterType.ExtensionId, extension.identifier.uuid);
    const { extensions } = await this.F(query, { targetPlatform, compatible: true, includePreRelease, productVersion }, CancellationToken.None);
    return extensions[0] || null;
  }
  async isExtensionCompatible(extension, includePreRelease, targetPlatform, productVersion = { version: this.x.version, date: this.x.date }) {
    if (this.z.isAllowed(extension) !== true) {
      return false;
    }
    if (!$nA(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 (!$1A(engine, productVersion.version, productVersion.date)) {
      return false;
    }
    if (!this.D(extension.identifier, extension.properties.enabledApiProposals)) {
      return false;
    }
    return true;
  }
  D(extensionIdentifier, enabledApiProposals) {
    if (!enabledApiProposals) {
      return true;
    }
    if (!this.l.includes(extensionIdentifier.id.toLowerCase())) {
      return true;
    }
    return $2A(enabledApiProposals);
  }
  async E(extension, rawGalleryExtensionVersion, publisherDisplayName, versionType, compatible, allTargetPlatforms, targetPlatform, productVersion = { version: this.x.version, date: this.x.date }) {
    const targetPlatformForExtension = getTargetPlatformForExtensionVersion(rawGalleryExtensionVersion);
    if (!$nA(targetPlatformForExtension, allTargetPlatforms, targetPlatform)) {
      return false;
    }
    if (versionType !== "any" && isPreReleaseVersion(rawGalleryExtensionVersion) !== (versionType === "prerelease")) {
      return false;
    }
    if (compatible) {
      if (this.z.isAllowed({ id: extension, publisherDisplayName, version: rawGalleryExtensionVersion.version, prerelease: isPreReleaseVersion(rawGalleryExtensionVersion), targetPlatform: targetPlatformForExtension }) !== true) {
        return false;
      }
      try {
        const engine = await this.L(extension, rawGalleryExtensionVersion);
        if (!$1A(engine, productVersion.version, productVersion.date)) {
          return false;
        }
      } catch (error) {
        this.o.error(`Error while getting the engine for the version ${rawGalleryExtensionVersion.version}.`, $qb(error));
        return false;
      }
    }
    return true;
  }
  async query(options3, token) {
    let text2 = options3.text || "";
    const pageSize = options3.pageSize ?? 50;
    let query = new Query().withPage(1, pageSize);
    if (text2) {
      text2 = text2.replace(/\bcategory:("([^"]*)"|([^"]\S*))(\s+|\b|$)/g, (_, quotedCategory, category8) => {
        query = query.withFilter(FilterType.Category, category8 || quotedCategory);
        return "";
      });
      text2 = text2.replace(/\btag:("([^"]*)"|([^"]\S*))(\s+|\b|$)/g, (_, quotedTag, tag2) => {
        query = query.withFilter(FilterType.Tag, tag2 || quotedTag);
        return "";
      });
      text2 = text2.replace(/\bfeatured(\s+|\b|$)/g, () => {
        query = query.withFilter(FilterType.Featured);
        return "";
      });
      text2 = text2.trim();
      if (text2) {
        text2 = text2.length < 200 ? text2 : text2.substring(0, 200);
        query = query.withFilter(FilterType.SearchText, text2);
      }
      query = query.withSortBy(
        0
        /* SortBy.NoneOrRelevance */
      );
    } else {
      query = query.withSortBy(
        4
        /* SortBy.InstallCount */
      );
    }
    if (typeof options3.sortBy === "number") {
      query = query.withSortBy(options3.sortBy);
    }
    if (typeof options3.sortOrder === "number") {
      query = query.withSortOrder(options3.sortOrder);
    }
    if (options3.source) {
      query = query.withSource(options3.source);
    }
    const runQuery = async (query2, token2) => {
      const { extensions: extensions2, total: total2 } = await this.F(query2, { targetPlatform: CURRENT_TARGET_PLATFORM, compatible: false, includePreRelease: !!options3.includePreRelease, productVersion: options3.productVersion ?? { version: this.x.version, date: this.x.date } }, token2);
      extensions2.forEach((e, index) => setTelemetry(e, (query2.pageNumber - 1) * query2.pageSize + index, options3.source));
      return { extensions: extensions2, total: total2 };
    };
    const { extensions, total } = await runQuery(query, token);
    const getPage = async (pageIndex, ct) => {
      if (ct.isCancellationRequested) {
        throw new $lb();
      }
      const { extensions: extensions2 } = await runQuery(query.withPage(pageIndex + 1), ct);
      return extensions2;
    };
    return { firstPage: extensions, total, pageSize: query.pageSize, getPage };
  }
  async F(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.H(query, token);
    const hasAllVersions = !(query.flags & Flags.IncludeLatestVersionOnly);
    if (hasAllVersions) {
      const extensions = [];
      for (const rawGalleryExtension of rawGalleryExtensions) {
        const extension = await this.G(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: $IA(rawGalleryExtension.publisher.publisherName, rawGalleryExtension.extensionName), uuid: rawGalleryExtension.extensionId };
      const includePreRelease = $Fg(criteria.includePreRelease) ? criteria.includePreRelease : !!criteria.includePreRelease.find((extensionIdentifierWithPreRelease) => $DA(extensionIdentifierWithPreRelease, extensionIdentifier))?.includePreRelease;
      if (criteria.compatible) {
        if ($mA(getAllTargetPlatforms(rawGalleryExtension), criteria.targetPlatform)) {
          continue;
        }
        if (this.z.isAllowed({ id: extensionIdentifier.id, publisherDisplayName: rawGalleryExtension.publisher.displayName }) !== true) {
          continue;
        }
      }
      const extension = await this.G(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 $te();
      const query2 = new Query().withFlags(flags & ~Flags.IncludeLatestVersionOnly, Flags.IncludeVersions).withPage(1, needAllVersions.size).withFilter(FilterType.ExtensionId, ...needAllVersions.keys());
      const { extensions } = await this.F(query2, criteria, token);
      this.u.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 G(rawGalleryExtension, criteria, queryContext) {
    const extensionIdentifier = { id: $IA(rawGalleryExtension.publisher.publisherName, rawGalleryExtension.extensionName), uuid: rawGalleryExtension.extensionId };
    const version2 = criteria.versions?.find((extensionIdentifierWithVersion) => $DA(extensionIdentifierWithVersion, extensionIdentifier))?.version;
    const includePreRelease = $Fg(criteria.includePreRelease) ? criteria.includePreRelease : !!criteria.includePreRelease.find((extensionIdentifierWithPreRelease) => $DA(extensionIdentifierWithPreRelease, extensionIdentifier))?.includePreRelease;
    const allTargetPlatforms = getAllTargetPlatforms(rawGalleryExtension);
    const rawGalleryExtensionVersions = $9W(rawGalleryExtension.versions, criteria.targetPlatform);
    if (criteria.compatible && $mA(allTargetPlatforms, criteria.targetPlatform)) {
      return null;
    }
    for (let index = 0; index < rawGalleryExtensionVersions.length; index++) {
      const rawGalleryExtensionVersion = rawGalleryExtensionVersions[index];
      if (version2 && rawGalleryExtensionVersion.version !== version2) {
        continue;
      }
      if (await this.E(extensionIdentifier.id, rawGalleryExtensionVersion, rawGalleryExtension.publisher.displayName, includePreRelease ? "any" : "release", criteria.compatible, allTargetPlatforms, criteria.targetPlatform, criteria.productVersion)) {
        if (criteria.compatible && !this.D(extensionIdentifier, getEnabledApiProposals(rawGalleryExtensionVersion))) {
          continue;
        }
        return toExtension(rawGalleryExtension, rawGalleryExtensionVersion, allTargetPlatforms, queryContext);
      }
      if (version2 && rawGalleryExtensionVersion.version === version2) {
        return null;
      }
    }
    if (version2 || criteria.compatible) {
      return null;
    }
    return toExtension(rawGalleryExtension, rawGalleryExtension.versions[0], allTargetPlatforms);
  }
  async H(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.k;
    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 $te();
    let context, errorCode, total = 0;
    try {
      context = await this.n.request({
        type: "POST",
        url: this.g && query.criteria.some((c) => c.filterType === FilterType.SearchText) ? this.g : this.A("/extensionquery"),
        data,
        headers
      }, token);
      if (context.res.statusCode && context.res.statusCode >= 400 && context.res.statusCode < 500) {
        return { galleryExtensions: [], total };
      }
      const result = await $cv(context);
      if (result) {
        const r2 = result.results[0];
        const galleryExtensions = r2.extensions;
        const resultCount = r2.resultMetadata && r2.resultMetadata.filter((m) => m.metadataType === "ResultCount")[0];
        total = resultCount && resultCount.metadataItems.filter((i2) => i2.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 ($kb(e)) {
        errorCode = "Cancelled";
        throw e;
      } else {
        const errorMessage = $qb(e);
        errorCode = $7u(e) ? "Offline" : errorMessage.startsWith("XHR timeout") ? "Timeout" : "Failed";
        throw new $qA(errorMessage, errorCode);
      }
    } finally {
      this.u.publicLog2("galleryService:query", {
        ...query.telemetryData,
        requestBodySize: String(data.length),
        duration: stopWatch.elapsed(),
        success: !!context && $$u(context),
        responseBodySize: context?.res.headers["Content-Length"],
        statusCode: context ? String(context.res.statusCode) : void 0,
        errorCode,
        count: String(total)
      });
    }
  }
  async I(extensionId, token) {
    let errorCode;
    const stopWatch = new $te();
    try {
      const [publisher, name] = extensionId.split(".");
      if (!publisher || !name) {
        errorCode = "InvalidExtensionId";
        return void 0;
      }
      const uri = URI.parse($xf(this.j, { publisher, name }));
      const commonHeaders = await this.k;
      const headers = {
        ...commonHeaders,
        "Content-Type": "application/json",
        "Accept": "application/json;api-version=7.2-preview",
        "Accept-Encoding": "gzip"
      };
      const context = await this.n.request({
        type: "GET",
        url: uri.toString(true),
        headers,
        timeout: 1e4
        /*10s*/
      }, token);
      if (context.res.statusCode && context.res.statusCode !== 200) {
        errorCode = `GalleryServiceError:` + context.res.statusCode;
        this.o.warn("Error getting latest version of the extension", extensionId, context.res.statusCode);
        return void 0;
      }
      const result = await $cv(context);
      if (result) {
        return result;
      }
      errorCode = "NoData";
      this.o.warn("Error getting latest version of the extension", extensionId, errorCode);
    } catch (error) {
      if ($kb(error)) {
        errorCode = "Cancelled";
      } else {
        const errorMessage = $qb(error);
        errorCode = $7u(error) ? "Offline" : errorMessage.startsWith("XHR timeout") ? "Timeout" : "Failed";
      }
    } finally {
      this.u.publicLog2("galleryService:getLatest", { extension: extensionId, duration: stopWatch.elapsed(), errorCode });
    }
    return void 0;
  }
  async reportStatistic(publisher, name, version2, type) {
    if (!this.isEnabled()) {
      return void 0;
    }
    const url = $r ? this.A(`/itemName/${publisher}.${name}/version/${version2}/statType/${type === "install" ? "1" : "3"}/vscodewebextension`) : this.A(`/publishers/${publisher}/extensions/${name}/${version2}/stats?statType=${type}`);
    const Accept = $r ? "api-version=6.1-preview.1" : "*/*;api-version=4.0-preview.1";
    const commonHeaders = await this.k;
    const headers = { ...commonHeaders, Accept };
    try {
      await this.n.request({
        type: "POST",
        url,
        headers
      }, CancellationToken.None);
    } catch (error) {
    }
  }
  async download(extension, location3, operation) {
    this.o.trace("ExtensionGalleryService#download", extension.identifier.id);
    const data = $LA(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.K(extension.identifier.id, downloadAsset, AssetType.VSIX, headers ? { headers } : void 0);
    try {
      await this.w.writeFile(location3, context.stream);
    } catch (error) {
      try {
        await this.w.del(location3);
      } catch (e) {
        this.o.warn(`Error while deleting the file ${location3.toString()}`, $qb(e));
      }
      throw new $qA(
        $qb(error),
        "DownloadFailedWriting"
        /* ExtensionGalleryErrorCode.DownloadFailedWriting */
      );
    }
    this.u.publicLog("galleryService:downloadVSIX", { ...data, duration: (/* @__PURE__ */ new Date()).getTime() - startTime });
  }
  async downloadSignatureArchive(extension, location3) {
    if (!extension.assets.signature) {
      throw new Error("No signature asset found");
    }
    this.o.trace("ExtensionGalleryService#downloadSignatureArchive", extension.identifier.id);
    const context = await this.K(extension.identifier.id, extension.assets.signature, AssetType.Signature);
    try {
      await this.w.writeFile(location3, context.stream);
    } catch (error) {
      try {
        await this.w.del(location3);
      } catch (e) {
        this.o.warn(`Error while deleting the file ${location3.toString()}`, $qb(e));
      }
      throw new $qA(
        $qb(error),
        "DownloadFailedWriting"
        /* ExtensionGalleryErrorCode.DownloadFailedWriting */
      );
    }
  }
  async getReadme(extension, token) {
    if (extension.assets.readme) {
      const context = await this.K(extension.identifier.id, extension.assets.readme, AssetType.Details, {}, token);
      const content = await $bv(context);
      return content || "";
    }
    return "";
  }
  async getManifest(extension, token) {
    if (extension.assets.manifest) {
      const context = await this.K(extension.identifier.id, extension.assets.manifest, AssetType.Manifest, {}, token);
      const text2 = await $bv(context);
      return text2 ? JSON.parse(text2) : null;
    }
    return null;
  }
  async J(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.K(extension, manifestAsset, AssetType.Manifest, { headers });
    return await $cv(context);
  }
  async getCoreTranslation(extension, languageId) {
    const asset = extension.assets.coreTranslations.filter((t) => t[0] === languageId.toUpperCase())[0];
    if (asset) {
      const context = await this.K(extension.identifier.id, asset[1], asset[0]);
      const text2 = await $bv(context);
      return text2 ? JSON.parse(text2) : null;
    }
    return null;
  }
  async getChangelog(extension, token) {
    if (extension.assets.changelog) {
      const context = await this.K(extension.identifier.id, extension.assets.changelog, AssetType.Changelog, {}, token);
      const content = await $bv(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.H(query, CancellationToken.None);
    if (!galleryExtensions.length) {
      return [];
    }
    const allTargetPlatforms = getAllTargetPlatforms(galleryExtensions[0]);
    if ($mA(allTargetPlatforms, targetPlatform)) {
      return [];
    }
    const validVersions = [];
    await Promise.all(galleryExtensions[0].versions.map(async (version2) => {
      try {
        if (await this.E(extensionIdentifier.id, version2, galleryExtensions[0].publisher.displayName, includePreRelease ? "any" : "release", true, allTargetPlatforms, targetPlatform) && this.D(extensionIdentifier, getEnabledApiProposals(version2))) {
          validVersions.push(version2);
        }
      } catch (error) {
      }
    }));
    const result = [];
    const seen = /* @__PURE__ */ new Set();
    for (const version2 of $9W(validVersions, targetPlatform)) {
      if (!seen.has(version2.version)) {
        seen.add(version2.version);
        result.push({ version: version2.version, date: version2.lastUpdated, isPreReleaseVersion: isPreReleaseVersion(version2) });
      }
    }
    return result;
  }
  async K(extension, asset, assetType, options3 = {}, token = CancellationToken.None) {
    const commonHeaders = await this.k;
    const baseOptions = { type: "GET" };
    const headers = { ...commonHeaders, ...options3.headers || {} };
    options3 = { ...options3, ...baseOptions, headers };
    const url = asset.uri;
    const fallbackUrl = asset.fallbackUri;
    const firstOptions = { ...options3, url };
    try {
      const context = await this.n.request(firstOptions, token);
      if (context.res.statusCode === 200) {
        return context;
      }
      const message = await $bv(context);
      throw new Error(`Expected 200, got back ${context.res.statusCode} instead.

${message}`);
    } catch (err) {
      if ($kb(err)) {
        throw err;
      }
      const message = $qb(err);
      this.u.publicLog2("galleryService:cdnFallback", { extension, assetType, message });
      const fallbackOptions = { ...options3, url: fallbackUrl };
      return this.n.request(fallbackOptions, token);
    }
  }
  async L(extension, rawExtensionVersion) {
    let engine = getEngine(rawExtensionVersion);
    if (!engine) {
      this.u.publicLog2("galleryService:engineFallback", { extension, version: rawExtensionVersion.version });
      const manifest = await this.J(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.n.request({ type: "GET", url: this.h }, CancellationToken.None);
    if (context.res.statusCode !== 200) {
      throw new Error("Could not get extensions report.");
    }
    const result = await $cv(context);
    const malicious = [];
    const deprecated = {};
    const search2 = [];
    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 || $1A(preReleaseExtensionInfo.engine, this.x.version, this.x.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()] = $Fg(deprecationInfo) ? {} : deprecationInfo;
          }
        }
      }
      if (result.search) {
        for (const s of result.search) {
          search2.push(s);
        }
      }
      if (Array.isArray(result.extensionsEnabledWithPreRelease)) {
        for (const id2 of result.extensionsEnabledWithPreRelease) {
          extensionsEnabledWithPreRelease.push(id2.toLowerCase());
        }
      }
    }
    return { malicious, deprecated, search: search2, extensionsEnabledWithPreRelease };
  }
};
AbstractExtensionGalleryService = __decorate([
  __param(1, $9u),
  __param(2, $wn),
  __param(3, $Xk),
  __param(4, $zv),
  __param(5, $km),
  __param(6, $Vu),
  __param(7, $kl),
  __param(8, $xA)
], AbstractExtensionGalleryService);
var $0W = class $0W2 extends AbstractExtensionGalleryService {
  constructor(storageService, requestService, logService, environmentService, telemetryService, fileService, productService, configurationService, allowedExtensionsService) {
    super(storageService, requestService, logService, environmentService, telemetryService, fileService, productService, configurationService, allowedExtensionsService);
  }
};
$0W = __decorate([
  __param(0, $jv),
  __param(1, $9u),
  __param(2, $wn),
  __param(3, $Xk),
  __param(4, $zv),
  __param(5, $km),
  __param(6, $Vu),
  __param(7, $kl),
  __param(8, $xA)
], $0W);
var $$W = class $$W2 extends AbstractExtensionGalleryService {
  constructor(requestService, logService, environmentService, telemetryService, fileService, productService, configurationService, allowedExtensionsService) {
    super(void 0, requestService, logService, environmentService, telemetryService, fileService, productService, configurationService, allowedExtensionsService);
  }
};
$$W = __decorate([
  __param(0, $9u),
  __param(1, $wn),
  __param(2, $Xk),
  __param(3, $zv),
  __param(4, $km),
  __param(5, $Vu),
  __param(6, $kl),
  __param(7, $xA)
], $$W);

// out-build/vs/editor/common/languages/linkComputer.js
var State9;
(function(State14) {
  State14[State14["Invalid"] = 0] = "Invalid";
  State14[State14["Start"] = 1] = "Start";
  State14[State14["H"] = 2] = "H";
  State14[State14["HT"] = 3] = "HT";
  State14[State14["HTT"] = 4] = "HTT";
  State14[State14["HTTP"] = 5] = "HTTP";
  State14[State14["F"] = 6] = "F";
  State14[State14["FI"] = 7] = "FI";
  State14[State14["FIL"] = 8] = "FIL";
  State14[State14["BeforeColon"] = 9] = "BeforeColon";
  State14[State14["AfterColon"] = 10] = "AfterColon";
  State14[State14["AlmostThere"] = 11] = "AlmostThere";
  State14[State14["End"] = 12] = "End";
  State14[State14["Accept"] = 13] = "Accept";
  State14[State14["LastKnownState"] = 14] = "LastKnownState";
})(State9 || (State9 = {}));
var Uint8Matrix = class {
  constructor(rows, cols, defaultValue) {
    const data = new Uint8Array(rows * cols);
    for (let i2 = 0, len = rows * cols; i2 < len; i2++) {
      data[i2] = defaultValue;
    }
    this.a = data;
    this.rows = rows;
    this.cols = cols;
  }
  get(row, col) {
    return this.a[row * this.cols + col];
  }
  set(row, col, value) {
    this.a[row * this.cols + col] = value;
  }
};
var $09 = class {
  constructor(edges) {
    let maxCharCode = 0;
    let maxState = 0;
    for (let i2 = 0, len = edges.length; i2 < len; i2++) {
      const [from, chCode, to] = edges[i2];
      if (chCode > maxCharCode) {
        maxCharCode = chCode;
      }
      if (from > maxState) {
        maxState = from;
      }
      if (to > maxState) {
        maxState = to;
      }
    }
    maxCharCode++;
    maxState++;
    const states = new Uint8Matrix(
      maxState,
      maxCharCode,
      0
      /* State.Invalid */
    );
    for (let i2 = 0, len = edges.length; i2 < len; i2++) {
      const [from, chCode, to] = edges[i2];
      states.set(from, chCode, to);
    }
    this.a = states;
    this.b = maxCharCode;
  }
  nextState(currentState, chCode) {
    if (chCode < 0 || chCode >= this.b) {
      return 0;
    }
    return this.a.get(currentState, chCode);
  }
};
var _stateMachine = null;
function getStateMachine() {
  if (_stateMachine === null) {
    _stateMachine = new $09([
      [
        1,
        104,
        2
        /* State.H */
      ],
      [
        1,
        72,
        2
        /* State.H */
      ],
      [
        1,
        102,
        6
        /* State.F */
      ],
      [
        1,
        70,
        6
        /* State.F */
      ],
      [
        2,
        116,
        3
        /* State.HT */
      ],
      [
        2,
        84,
        3
        /* State.HT */
      ],
      [
        3,
        116,
        4
        /* State.HTT */
      ],
      [
        3,
        84,
        4
        /* State.HTT */
      ],
      [
        4,
        112,
        5
        /* State.HTTP */
      ],
      [
        4,
        80,
        5
        /* State.HTTP */
      ],
      [
        5,
        115,
        9
        /* State.BeforeColon */
      ],
      [
        5,
        83,
        9
        /* State.BeforeColon */
      ],
      [
        5,
        58,
        10
        /* State.AfterColon */
      ],
      [
        6,
        105,
        7
        /* State.FI */
      ],
      [
        6,
        73,
        7
        /* State.FI */
      ],
      [
        7,
        108,
        8
        /* State.FIL */
      ],
      [
        7,
        76,
        8
        /* State.FIL */
      ],
      [
        8,
        101,
        9
        /* State.BeforeColon */
      ],
      [
        8,
        69,
        9
        /* State.BeforeColon */
      ],
      [
        9,
        58,
        10
        /* State.AfterColon */
      ],
      [
        10,
        47,
        11
        /* State.AlmostThere */
      ],
      [
        11,
        47,
        12
        /* State.End */
      ]
    ]);
  }
  return _stateMachine;
}
var CharacterClass2;
(function(CharacterClass3) {
  CharacterClass3[CharacterClass3["None"] = 0] = "None";
  CharacterClass3[CharacterClass3["ForceTermination"] = 1] = "ForceTermination";
  CharacterClass3[CharacterClass3["CannotEndIn"] = 2] = "CannotEndIn";
})(CharacterClass2 || (CharacterClass2 = {}));
var _classifier = null;
function getClassifier() {
  if (_classifier === null) {
    _classifier = new $fE(
      0
      /* CharacterClass.None */
    );
    const FORCE_TERMINATION_CHARACTERS = ` 	<>'"\u3001\u3002\uFF61\uFF64\uFF0C\uFF0E\uFF1A\uFF1B\u2018\u3008\u300C\u300E\u3014\uFF08\uFF3B\uFF5B\uFF62\uFF63\uFF5D\uFF3D\uFF09\u3015\u300F\u300D\u3009\u2019\uFF40\uFF5E\u2026`;
    for (let i2 = 0; i2 < FORCE_TERMINATION_CHARACTERS.length; i2++) {
      _classifier.set(
        FORCE_TERMINATION_CHARACTERS.charCodeAt(i2),
        1
        /* CharacterClass.ForceTermination */
      );
    }
    const CANNOT_END_WITH_CHARACTERS = ".,;:";
    for (let i2 = 0; i2 < CANNOT_END_WITH_CHARACTERS.length; i2++) {
      _classifier.set(
        CANNOT_END_WITH_CHARACTERS.charCodeAt(i2),
        2
        /* CharacterClass.CannotEndIn */
      );
    }
  }
  return _classifier;
}
var $$9 = class _$$9 {
  static a(classifier, line, lineNumber, linkBeginIndex, linkEndIndex) {
    let lastIncludedCharIndex = linkEndIndex - 1;
    do {
      const chCode = line.charCodeAt(lastIncludedCharIndex);
      const chClass = classifier.get(chCode);
      if (chClass !== 2) {
        break;
      }
      lastIncludedCharIndex--;
    } while (lastIncludedCharIndex > linkBeginIndex);
    if (linkBeginIndex > 0) {
      const charCodeBeforeLink = line.charCodeAt(linkBeginIndex - 1);
      const lastCharCodeInLink = line.charCodeAt(lastIncludedCharIndex);
      if (charCodeBeforeLink === 40 && lastCharCodeInLink === 41 || charCodeBeforeLink === 91 && lastCharCodeInLink === 93 || charCodeBeforeLink === 123 && lastCharCodeInLink === 125) {
        lastIncludedCharIndex--;
      }
    }
    return {
      range: {
        startLineNumber: lineNumber,
        startColumn: linkBeginIndex + 1,
        endLineNumber: lineNumber,
        endColumn: lastIncludedCharIndex + 2
      },
      url: line.substring(linkBeginIndex, lastIncludedCharIndex + 1)
    };
  }
  static computeLinks(model, stateMachine = getStateMachine()) {
    const classifier = getClassifier();
    const result = [];
    for (let i2 = 1, lineCount = model.getLineCount(); i2 <= lineCount; i2++) {
      const line = model.getLineContent(i2);
      const len = line.length;
      let j = 0;
      let linkBeginIndex = 0;
      let linkBeginChCode = 0;
      let state = 1;
      let hasOpenParens = false;
      let hasOpenSquareBracket = false;
      let inSquareBrackets = false;
      let hasOpenCurlyBracket = false;
      while (j < len) {
        let resetStateMachine = false;
        const chCode = line.charCodeAt(j);
        if (state === 13) {
          let chClass;
          switch (chCode) {
            case 40:
              hasOpenParens = true;
              chClass = 0;
              break;
            case 41:
              chClass = hasOpenParens ? 0 : 1;
              break;
            case 91:
              inSquareBrackets = true;
              hasOpenSquareBracket = true;
              chClass = 0;
              break;
            case 93:
              inSquareBrackets = false;
              chClass = hasOpenSquareBracket ? 0 : 1;
              break;
            case 123:
              hasOpenCurlyBracket = true;
              chClass = 0;
              break;
            case 125:
              chClass = hasOpenCurlyBracket ? 0 : 1;
              break;
            case 39:
            case 34:
            case 96:
              if (linkBeginChCode === chCode) {
                chClass = 1;
              } else if (linkBeginChCode === 39 || linkBeginChCode === 34 || linkBeginChCode === 96) {
                chClass = 0;
              } else {
                chClass = 1;
              }
              break;
            case 42:
              chClass = linkBeginChCode === 42 ? 1 : 0;
              break;
            case 124:
              chClass = linkBeginChCode === 124 ? 1 : 0;
              break;
            case 32:
              chClass = inSquareBrackets ? 0 : 1;
              break;
            default:
              chClass = classifier.get(chCode);
          }
          if (chClass === 1) {
            result.push(_$$9.a(classifier, line, i2, linkBeginIndex, j));
            resetStateMachine = true;
          }
        } else if (state === 12) {
          let chClass;
          if (chCode === 91) {
            hasOpenSquareBracket = true;
            chClass = 0;
          } else {
            chClass = classifier.get(chCode);
          }
          if (chClass === 1) {
            resetStateMachine = true;
          } else {
            state = 13;
          }
        } else {
          state = stateMachine.nextState(state, chCode);
          if (state === 0) {
            resetStateMachine = true;
          }
        }
        if (resetStateMachine) {
          state = 1;
          hasOpenParens = false;
          hasOpenSquareBracket = false;
          hasOpenCurlyBracket = false;
          linkBeginIndex = j + 1;
          linkBeginChCode = chCode;
        }
        j++;
      }
      if (state === 13) {
        result.push(_$$9.a(classifier, line, i2, linkBeginIndex, len));
      }
    }
    return result;
  }
};
function $_9(model) {
  if (!model || typeof model.getLineCount !== "function" || typeof model.getLineContent !== "function") {
    return [];
  }
  return $$9.computeLinks(model);
}

// out-build/vs/editor/common/languages/supports/inplaceReplaceSupport.js
var $a0 = class _$a0 {
  constructor() {
    this.c = [
      ["true", "false"],
      ["True", "False"],
      ["Private", "Public", "Friend", "ReadOnly", "Partial", "Protected", "WriteOnly"],
      ["public", "protected", "private"]
    ];
  }
  static {
    this.INSTANCE = new _$a0();
  }
  navigateValueSet(range1, text1, range2, text2, up) {
    if (range1 && text1) {
      const result = this.a(text1, up);
      if (result) {
        return {
          range: range1,
          value: result
        };
      }
    }
    if (range2 && text2) {
      const result = this.a(text2, up);
      if (result) {
        return {
          range: range2,
          value: result
        };
      }
    }
    return null;
  }
  a(text2, up) {
    const numberResult = this.b(text2, up);
    if (numberResult !== null) {
      return numberResult;
    }
    return this.d(text2, up);
  }
  b(value, up) {
    const precision = Math.pow(10, value.length - (value.lastIndexOf(".") + 1));
    let n1 = Number(value);
    const n2 = parseFloat(value);
    if (!isNaN(n1) && !isNaN(n2) && n1 === n2) {
      if (n1 === 0 && !up) {
        return null;
      } else {
        n1 = Math.floor(n1 * precision);
        n1 += up ? precision : -precision;
        return String(n1 / precision);
      }
    }
    return null;
  }
  d(value, up) {
    return this.e(this.c, value, up);
  }
  e(valueSets, value, up) {
    let result = null;
    for (let i2 = 0, len = valueSets.length; result === null && i2 < len; i2++) {
      result = this.f(valueSets[i2], value, up);
    }
    return result;
  }
  f(valueSet, value, up) {
    let idx = valueSet.indexOf(value);
    if (idx >= 0) {
      idx += up ? 1 : -1;
      if (idx < 0) {
        idx = valueSet.length - 1;
      } else {
        idx %= valueSet.length;
      }
      return valueSet[idx];
    }
    return null;
  }
};

// out-build/vs/editor/common/standalone/standaloneEnums.js
var AccessibilitySupport2;
(function(AccessibilitySupport3) {
  AccessibilitySupport3[AccessibilitySupport3["Unknown"] = 0] = "Unknown";
  AccessibilitySupport3[AccessibilitySupport3["Disabled"] = 1] = "Disabled";
  AccessibilitySupport3[AccessibilitySupport3["Enabled"] = 2] = "Enabled";
})(AccessibilitySupport2 || (AccessibilitySupport2 = {}));
var CodeActionTriggerType2;
(function(CodeActionTriggerType3) {
  CodeActionTriggerType3[CodeActionTriggerType3["Invoke"] = 1] = "Invoke";
  CodeActionTriggerType3[CodeActionTriggerType3["Auto"] = 2] = "Auto";
})(CodeActionTriggerType2 || (CodeActionTriggerType2 = {}));
var CompletionItemInsertTextRule2;
(function(CompletionItemInsertTextRule3) {
  CompletionItemInsertTextRule3[CompletionItemInsertTextRule3["None"] = 0] = "None";
  CompletionItemInsertTextRule3[CompletionItemInsertTextRule3["KeepWhitespace"] = 1] = "KeepWhitespace";
  CompletionItemInsertTextRule3[CompletionItemInsertTextRule3["InsertAsSnippet"] = 4] = "InsertAsSnippet";
})(CompletionItemInsertTextRule2 || (CompletionItemInsertTextRule2 = {}));
var CompletionItemKind4;
(function(CompletionItemKind5) {
  CompletionItemKind5[CompletionItemKind5["Method"] = 0] = "Method";
  CompletionItemKind5[CompletionItemKind5["Function"] = 1] = "Function";
  CompletionItemKind5[CompletionItemKind5["Constructor"] = 2] = "Constructor";
  CompletionItemKind5[CompletionItemKind5["Field"] = 3] = "Field";
  CompletionItemKind5[CompletionItemKind5["Variable"] = 4] = "Variable";
  CompletionItemKind5[CompletionItemKind5["Class"] = 5] = "Class";
  CompletionItemKind5[CompletionItemKind5["Struct"] = 6] = "Struct";
  CompletionItemKind5[CompletionItemKind5["Interface"] = 7] = "Interface";
  CompletionItemKind5[CompletionItemKind5["Module"] = 8] = "Module";
  CompletionItemKind5[CompletionItemKind5["Property"] = 9] = "Property";
  CompletionItemKind5[CompletionItemKind5["Event"] = 10] = "Event";
  CompletionItemKind5[CompletionItemKind5["Operator"] = 11] = "Operator";
  CompletionItemKind5[CompletionItemKind5["Unit"] = 12] = "Unit";
  CompletionItemKind5[CompletionItemKind5["Value"] = 13] = "Value";
  CompletionItemKind5[CompletionItemKind5["Constant"] = 14] = "Constant";
  CompletionItemKind5[CompletionItemKind5["Enum"] = 15] = "Enum";
  CompletionItemKind5[CompletionItemKind5["EnumMember"] = 16] = "EnumMember";
  CompletionItemKind5[CompletionItemKind5["Keyword"] = 17] = "Keyword";
  CompletionItemKind5[CompletionItemKind5["Text"] = 18] = "Text";
  CompletionItemKind5[CompletionItemKind5["Color"] = 19] = "Color";
  CompletionItemKind5[CompletionItemKind5["File"] = 20] = "File";
  CompletionItemKind5[CompletionItemKind5["Reference"] = 21] = "Reference";
  CompletionItemKind5[CompletionItemKind5["Customcolor"] = 22] = "Customcolor";
  CompletionItemKind5[CompletionItemKind5["Folder"] = 23] = "Folder";
  CompletionItemKind5[CompletionItemKind5["TypeParameter"] = 24] = "TypeParameter";
  CompletionItemKind5[CompletionItemKind5["User"] = 25] = "User";
  CompletionItemKind5[CompletionItemKind5["Issue"] = 26] = "Issue";
  CompletionItemKind5[CompletionItemKind5["Snippet"] = 27] = "Snippet";
})(CompletionItemKind4 || (CompletionItemKind4 = {}));
var CompletionItemTag4;
(function(CompletionItemTag5) {
  CompletionItemTag5[CompletionItemTag5["Deprecated"] = 1] = "Deprecated";
})(CompletionItemTag4 || (CompletionItemTag4 = {}));
var CompletionTriggerKind4;
(function(CompletionTriggerKind5) {
  CompletionTriggerKind5[CompletionTriggerKind5["Invoke"] = 0] = "Invoke";
  CompletionTriggerKind5[CompletionTriggerKind5["TriggerCharacter"] = 1] = "TriggerCharacter";
  CompletionTriggerKind5[CompletionTriggerKind5["TriggerForIncompleteCompletions"] = 2] = "TriggerForIncompleteCompletions";
})(CompletionTriggerKind4 || (CompletionTriggerKind4 = {}));
var ContentWidgetPositionPreference2;
(function(ContentWidgetPositionPreference3) {
  ContentWidgetPositionPreference3[ContentWidgetPositionPreference3["EXACT"] = 0] = "EXACT";
  ContentWidgetPositionPreference3[ContentWidgetPositionPreference3["ABOVE"] = 1] = "ABOVE";
  ContentWidgetPositionPreference3[ContentWidgetPositionPreference3["BELOW"] = 2] = "BELOW";
})(ContentWidgetPositionPreference2 || (ContentWidgetPositionPreference2 = {}));
var CursorChangeReason;
(function(CursorChangeReason2) {
  CursorChangeReason2[CursorChangeReason2["NotSet"] = 0] = "NotSet";
  CursorChangeReason2[CursorChangeReason2["ContentFlush"] = 1] = "ContentFlush";
  CursorChangeReason2[CursorChangeReason2["RecoverFromMarkers"] = 2] = "RecoverFromMarkers";
  CursorChangeReason2[CursorChangeReason2["Explicit"] = 3] = "Explicit";
  CursorChangeReason2[CursorChangeReason2["Paste"] = 4] = "Paste";
  CursorChangeReason2[CursorChangeReason2["Undo"] = 5] = "Undo";
  CursorChangeReason2[CursorChangeReason2["Redo"] = 6] = "Redo";
})(CursorChangeReason || (CursorChangeReason = {}));
var DefaultEndOfLine2;
(function(DefaultEndOfLine3) {
  DefaultEndOfLine3[DefaultEndOfLine3["LF"] = 1] = "LF";
  DefaultEndOfLine3[DefaultEndOfLine3["CRLF"] = 2] = "CRLF";
})(DefaultEndOfLine2 || (DefaultEndOfLine2 = {}));
var DocumentHighlightKind3;
(function(DocumentHighlightKind4) {
  DocumentHighlightKind4[DocumentHighlightKind4["Text"] = 0] = "Text";
  DocumentHighlightKind4[DocumentHighlightKind4["Read"] = 1] = "Read";
  DocumentHighlightKind4[DocumentHighlightKind4["Write"] = 2] = "Write";
})(DocumentHighlightKind3 || (DocumentHighlightKind3 = {}));
var EditorAutoIndentStrategy2;
(function(EditorAutoIndentStrategy3) {
  EditorAutoIndentStrategy3[EditorAutoIndentStrategy3["None"] = 0] = "None";
  EditorAutoIndentStrategy3[EditorAutoIndentStrategy3["Keep"] = 1] = "Keep";
  EditorAutoIndentStrategy3[EditorAutoIndentStrategy3["Brackets"] = 2] = "Brackets";
  EditorAutoIndentStrategy3[EditorAutoIndentStrategy3["Advanced"] = 3] = "Advanced";
  EditorAutoIndentStrategy3[EditorAutoIndentStrategy3["Full"] = 4] = "Full";
})(EditorAutoIndentStrategy2 || (EditorAutoIndentStrategy2 = {}));
var EditorOption2;
(function(EditorOption3) {
  EditorOption3[EditorOption3["acceptSuggestionOnCommitCharacter"] = 0] = "acceptSuggestionOnCommitCharacter";
  EditorOption3[EditorOption3["acceptSuggestionOnEnter"] = 1] = "acceptSuggestionOnEnter";
  EditorOption3[EditorOption3["accessibilitySupport"] = 2] = "accessibilitySupport";
  EditorOption3[EditorOption3["accessibilityPageSize"] = 3] = "accessibilityPageSize";
  EditorOption3[EditorOption3["ariaLabel"] = 4] = "ariaLabel";
  EditorOption3[EditorOption3["ariaRequired"] = 5] = "ariaRequired";
  EditorOption3[EditorOption3["autoClosingBrackets"] = 6] = "autoClosingBrackets";
  EditorOption3[EditorOption3["autoClosingComments"] = 7] = "autoClosingComments";
  EditorOption3[EditorOption3["screenReaderAnnounceInlineSuggestion"] = 8] = "screenReaderAnnounceInlineSuggestion";
  EditorOption3[EditorOption3["autoClosingDelete"] = 9] = "autoClosingDelete";
  EditorOption3[EditorOption3["autoClosingOvertype"] = 10] = "autoClosingOvertype";
  EditorOption3[EditorOption3["autoClosingQuotes"] = 11] = "autoClosingQuotes";
  EditorOption3[EditorOption3["autoIndent"] = 12] = "autoIndent";
  EditorOption3[EditorOption3["automaticLayout"] = 13] = "automaticLayout";
  EditorOption3[EditorOption3["autoSurround"] = 14] = "autoSurround";
  EditorOption3[EditorOption3["bracketPairColorization"] = 15] = "bracketPairColorization";
  EditorOption3[EditorOption3["guides"] = 16] = "guides";
  EditorOption3[EditorOption3["codeLens"] = 17] = "codeLens";
  EditorOption3[EditorOption3["codeLensFontFamily"] = 18] = "codeLensFontFamily";
  EditorOption3[EditorOption3["codeLensFontSize"] = 19] = "codeLensFontSize";
  EditorOption3[EditorOption3["colorDecorators"] = 20] = "colorDecorators";
  EditorOption3[EditorOption3["colorDecoratorsLimit"] = 21] = "colorDecoratorsLimit";
  EditorOption3[EditorOption3["columnSelection"] = 22] = "columnSelection";
  EditorOption3[EditorOption3["comments"] = 23] = "comments";
  EditorOption3[EditorOption3["contextmenu"] = 24] = "contextmenu";
  EditorOption3[EditorOption3["copyWithSyntaxHighlighting"] = 25] = "copyWithSyntaxHighlighting";
  EditorOption3[EditorOption3["cursorBlinking"] = 26] = "cursorBlinking";
  EditorOption3[EditorOption3["cursorSmoothCaretAnimation"] = 27] = "cursorSmoothCaretAnimation";
  EditorOption3[EditorOption3["cursorStyle"] = 28] = "cursorStyle";
  EditorOption3[EditorOption3["cursorSurroundingLines"] = 29] = "cursorSurroundingLines";
  EditorOption3[EditorOption3["cursorSurroundingLinesStyle"] = 30] = "cursorSurroundingLinesStyle";
  EditorOption3[EditorOption3["cursorWidth"] = 31] = "cursorWidth";
  EditorOption3[EditorOption3["disableLayerHinting"] = 32] = "disableLayerHinting";
  EditorOption3[EditorOption3["disableMonospaceOptimizations"] = 33] = "disableMonospaceOptimizations";
  EditorOption3[EditorOption3["domReadOnly"] = 34] = "domReadOnly";
  EditorOption3[EditorOption3["dragAndDrop"] = 35] = "dragAndDrop";
  EditorOption3[EditorOption3["dropIntoEditor"] = 36] = "dropIntoEditor";
  EditorOption3[EditorOption3["experimentalEditContextEnabled"] = 37] = "experimentalEditContextEnabled";
  EditorOption3[EditorOption3["emptySelectionClipboard"] = 38] = "emptySelectionClipboard";
  EditorOption3[EditorOption3["experimentalGpuAcceleration"] = 39] = "experimentalGpuAcceleration";
  EditorOption3[EditorOption3["experimentalWhitespaceRendering"] = 40] = "experimentalWhitespaceRendering";
  EditorOption3[EditorOption3["extraEditorClassName"] = 41] = "extraEditorClassName";
  EditorOption3[EditorOption3["fastScrollSensitivity"] = 42] = "fastScrollSensitivity";
  EditorOption3[EditorOption3["find"] = 43] = "find";
  EditorOption3[EditorOption3["fixedOverflowWidgets"] = 44] = "fixedOverflowWidgets";
  EditorOption3[EditorOption3["folding"] = 45] = "folding";
  EditorOption3[EditorOption3["foldingStrategy"] = 46] = "foldingStrategy";
  EditorOption3[EditorOption3["foldingHighlight"] = 47] = "foldingHighlight";
  EditorOption3[EditorOption3["foldingImportsByDefault"] = 48] = "foldingImportsByDefault";
  EditorOption3[EditorOption3["foldingMaximumRegions"] = 49] = "foldingMaximumRegions";
  EditorOption3[EditorOption3["unfoldOnClickAfterEndOfLine"] = 50] = "unfoldOnClickAfterEndOfLine";
  EditorOption3[EditorOption3["fontFamily"] = 51] = "fontFamily";
  EditorOption3[EditorOption3["fontInfo"] = 52] = "fontInfo";
  EditorOption3[EditorOption3["fontLigatures"] = 53] = "fontLigatures";
  EditorOption3[EditorOption3["fontSize"] = 54] = "fontSize";
  EditorOption3[EditorOption3["fontWeight"] = 55] = "fontWeight";
  EditorOption3[EditorOption3["fontVariations"] = 56] = "fontVariations";
  EditorOption3[EditorOption3["formatOnPaste"] = 57] = "formatOnPaste";
  EditorOption3[EditorOption3["formatOnType"] = 58] = "formatOnType";
  EditorOption3[EditorOption3["glyphMargin"] = 59] = "glyphMargin";
  EditorOption3[EditorOption3["gotoLocation"] = 60] = "gotoLocation";
  EditorOption3[EditorOption3["hideCursorInOverviewRuler"] = 61] = "hideCursorInOverviewRuler";
  EditorOption3[EditorOption3["hover"] = 62] = "hover";
  EditorOption3[EditorOption3["inDiffEditor"] = 63] = "inDiffEditor";
  EditorOption3[EditorOption3["inlineSuggest"] = 64] = "inlineSuggest";
  EditorOption3[EditorOption3["letterSpacing"] = 65] = "letterSpacing";
  EditorOption3[EditorOption3["lightbulb"] = 66] = "lightbulb";
  EditorOption3[EditorOption3["lineDecorationsWidth"] = 67] = "lineDecorationsWidth";
  EditorOption3[EditorOption3["lineHeight"] = 68] = "lineHeight";
  EditorOption3[EditorOption3["lineNumbers"] = 69] = "lineNumbers";
  EditorOption3[EditorOption3["lineNumbersMinChars"] = 70] = "lineNumbersMinChars";
  EditorOption3[EditorOption3["linkedEditing"] = 71] = "linkedEditing";
  EditorOption3[EditorOption3["links"] = 72] = "links";
  EditorOption3[EditorOption3["matchBrackets"] = 73] = "matchBrackets";
  EditorOption3[EditorOption3["minimap"] = 74] = "minimap";
  EditorOption3[EditorOption3["mouseStyle"] = 75] = "mouseStyle";
  EditorOption3[EditorOption3["mouseWheelScrollSensitivity"] = 76] = "mouseWheelScrollSensitivity";
  EditorOption3[EditorOption3["mouseWheelZoom"] = 77] = "mouseWheelZoom";
  EditorOption3[EditorOption3["multiCursorMergeOverlapping"] = 78] = "multiCursorMergeOverlapping";
  EditorOption3[EditorOption3["multiCursorModifier"] = 79] = "multiCursorModifier";
  EditorOption3[EditorOption3["multiCursorPaste"] = 80] = "multiCursorPaste";
  EditorOption3[EditorOption3["multiCursorLimit"] = 81] = "multiCursorLimit";
  EditorOption3[EditorOption3["occurrencesHighlight"] = 82] = "occurrencesHighlight";
  EditorOption3[EditorOption3["occurrencesHighlightDelay"] = 83] = "occurrencesHighlightDelay";
  EditorOption3[EditorOption3["overtypeCursorStyle"] = 84] = "overtypeCursorStyle";
  EditorOption3[EditorOption3["overtypeOnPaste"] = 85] = "overtypeOnPaste";
  EditorOption3[EditorOption3["overviewRulerBorder"] = 86] = "overviewRulerBorder";
  EditorOption3[EditorOption3["overviewRulerLanes"] = 87] = "overviewRulerLanes";
  EditorOption3[EditorOption3["padding"] = 88] = "padding";
  EditorOption3[EditorOption3["pasteAs"] = 89] = "pasteAs";
  EditorOption3[EditorOption3["parameterHints"] = 90] = "parameterHints";
  EditorOption3[EditorOption3["peekWidgetDefaultFocus"] = 91] = "peekWidgetDefaultFocus";
  EditorOption3[EditorOption3["placeholder"] = 92] = "placeholder";
  EditorOption3[EditorOption3["definitionLinkOpensInPeek"] = 93] = "definitionLinkOpensInPeek";
  EditorOption3[EditorOption3["quickSuggestions"] = 94] = "quickSuggestions";
  EditorOption3[EditorOption3["quickSuggestionsDelay"] = 95] = "quickSuggestionsDelay";
  EditorOption3[EditorOption3["readOnly"] = 96] = "readOnly";
  EditorOption3[EditorOption3["readOnlyMessage"] = 97] = "readOnlyMessage";
  EditorOption3[EditorOption3["renameOnType"] = 98] = "renameOnType";
  EditorOption3[EditorOption3["renderControlCharacters"] = 99] = "renderControlCharacters";
  EditorOption3[EditorOption3["renderFinalNewline"] = 100] = "renderFinalNewline";
  EditorOption3[EditorOption3["renderLineHighlight"] = 101] = "renderLineHighlight";
  EditorOption3[EditorOption3["renderLineHighlightOnlyWhenFocus"] = 102] = "renderLineHighlightOnlyWhenFocus";
  EditorOption3[EditorOption3["renderValidationDecorations"] = 103] = "renderValidationDecorations";
  EditorOption3[EditorOption3["renderWhitespace"] = 104] = "renderWhitespace";
  EditorOption3[EditorOption3["revealHorizontalRightPadding"] = 105] = "revealHorizontalRightPadding";
  EditorOption3[EditorOption3["roundedSelection"] = 106] = "roundedSelection";
  EditorOption3[EditorOption3["rulers"] = 107] = "rulers";
  EditorOption3[EditorOption3["scrollbar"] = 108] = "scrollbar";
  EditorOption3[EditorOption3["scrollBeyondLastColumn"] = 109] = "scrollBeyondLastColumn";
  EditorOption3[EditorOption3["scrollBeyondLastLine"] = 110] = "scrollBeyondLastLine";
  EditorOption3[EditorOption3["scrollPredominantAxis"] = 111] = "scrollPredominantAxis";
  EditorOption3[EditorOption3["selectionClipboard"] = 112] = "selectionClipboard";
  EditorOption3[EditorOption3["selectionHighlight"] = 113] = "selectionHighlight";
  EditorOption3[EditorOption3["selectOnLineNumbers"] = 114] = "selectOnLineNumbers";
  EditorOption3[EditorOption3["showFoldingControls"] = 115] = "showFoldingControls";
  EditorOption3[EditorOption3["showUnused"] = 116] = "showUnused";
  EditorOption3[EditorOption3["snippetSuggestions"] = 117] = "snippetSuggestions";
  EditorOption3[EditorOption3["smartSelect"] = 118] = "smartSelect";
  EditorOption3[EditorOption3["smoothScrolling"] = 119] = "smoothScrolling";
  EditorOption3[EditorOption3["stickyScroll"] = 120] = "stickyScroll";
  EditorOption3[EditorOption3["stickyTabStops"] = 121] = "stickyTabStops";
  EditorOption3[EditorOption3["stopRenderingLineAfter"] = 122] = "stopRenderingLineAfter";
  EditorOption3[EditorOption3["suggest"] = 123] = "suggest";
  EditorOption3[EditorOption3["suggestFontSize"] = 124] = "suggestFontSize";
  EditorOption3[EditorOption3["suggestLineHeight"] = 125] = "suggestLineHeight";
  EditorOption3[EditorOption3["suggestOnTriggerCharacters"] = 126] = "suggestOnTriggerCharacters";
  EditorOption3[EditorOption3["suggestSelection"] = 127] = "suggestSelection";
  EditorOption3[EditorOption3["tabCompletion"] = 128] = "tabCompletion";
  EditorOption3[EditorOption3["tabIndex"] = 129] = "tabIndex";
  EditorOption3[EditorOption3["unicodeHighlighting"] = 130] = "unicodeHighlighting";
  EditorOption3[EditorOption3["unusualLineTerminators"] = 131] = "unusualLineTerminators";
  EditorOption3[EditorOption3["useShadowDOM"] = 132] = "useShadowDOM";
  EditorOption3[EditorOption3["useTabStops"] = 133] = "useTabStops";
  EditorOption3[EditorOption3["wordBreak"] = 134] = "wordBreak";
  EditorOption3[EditorOption3["wordSegmenterLocales"] = 135] = "wordSegmenterLocales";
  EditorOption3[EditorOption3["wordSeparators"] = 136] = "wordSeparators";
  EditorOption3[EditorOption3["wordWrap"] = 137] = "wordWrap";
  EditorOption3[EditorOption3["wordWrapBreakAfterCharacters"] = 138] = "wordWrapBreakAfterCharacters";
  EditorOption3[EditorOption3["wordWrapBreakBeforeCharacters"] = 139] = "wordWrapBreakBeforeCharacters";
  EditorOption3[EditorOption3["wordWrapColumn"] = 140] = "wordWrapColumn";
  EditorOption3[EditorOption3["wordWrapOverride1"] = 141] = "wordWrapOverride1";
  EditorOption3[EditorOption3["wordWrapOverride2"] = 142] = "wordWrapOverride2";
  EditorOption3[EditorOption3["wrappingIndent"] = 143] = "wrappingIndent";
  EditorOption3[EditorOption3["wrappingStrategy"] = 144] = "wrappingStrategy";
  EditorOption3[EditorOption3["showDeprecated"] = 145] = "showDeprecated";
  EditorOption3[EditorOption3["inlayHints"] = 146] = "inlayHints";
  EditorOption3[EditorOption3["effectiveCursorStyle"] = 147] = "effectiveCursorStyle";
  EditorOption3[EditorOption3["editorClassName"] = 148] = "editorClassName";
  EditorOption3[EditorOption3["pixelRatio"] = 149] = "pixelRatio";
  EditorOption3[EditorOption3["tabFocusMode"] = 150] = "tabFocusMode";
  EditorOption3[EditorOption3["layoutInfo"] = 151] = "layoutInfo";
  EditorOption3[EditorOption3["wrappingInfo"] = 152] = "wrappingInfo";
  EditorOption3[EditorOption3["defaultColorDecorators"] = 153] = "defaultColorDecorators";
  EditorOption3[EditorOption3["colorDecoratorsActivatedOn"] = 154] = "colorDecoratorsActivatedOn";
  EditorOption3[EditorOption3["inlineCompletionsAccessibilityVerbose"] = 155] = "inlineCompletionsAccessibilityVerbose";
})(EditorOption2 || (EditorOption2 = {}));
var EndOfLinePreference2;
(function(EndOfLinePreference3) {
  EndOfLinePreference3[EndOfLinePreference3["TextDefined"] = 0] = "TextDefined";
  EndOfLinePreference3[EndOfLinePreference3["LF"] = 1] = "LF";
  EndOfLinePreference3[EndOfLinePreference3["CRLF"] = 2] = "CRLF";
})(EndOfLinePreference2 || (EndOfLinePreference2 = {}));
var EndOfLineSequence2;
(function(EndOfLineSequence3) {
  EndOfLineSequence3[EndOfLineSequence3["LF"] = 0] = "LF";
  EndOfLineSequence3[EndOfLineSequence3["CRLF"] = 1] = "CRLF";
})(EndOfLineSequence2 || (EndOfLineSequence2 = {}));
var GlyphMarginLane2;
(function(GlyphMarginLane3) {
  GlyphMarginLane3[GlyphMarginLane3["Left"] = 1] = "Left";
  GlyphMarginLane3[GlyphMarginLane3["Center"] = 2] = "Center";
  GlyphMarginLane3[GlyphMarginLane3["Right"] = 3] = "Right";
})(GlyphMarginLane2 || (GlyphMarginLane2 = {}));
var HoverVerbosityAction3;
(function(HoverVerbosityAction4) {
  HoverVerbosityAction4[HoverVerbosityAction4["Increase"] = 0] = "Increase";
  HoverVerbosityAction4[HoverVerbosityAction4["Decrease"] = 1] = "Decrease";
})(HoverVerbosityAction3 || (HoverVerbosityAction3 = {}));
var IndentAction2;
(function(IndentAction3) {
  IndentAction3[IndentAction3["None"] = 0] = "None";
  IndentAction3[IndentAction3["Indent"] = 1] = "Indent";
  IndentAction3[IndentAction3["IndentOutdent"] = 2] = "IndentOutdent";
  IndentAction3[IndentAction3["Outdent"] = 3] = "Outdent";
})(IndentAction2 || (IndentAction2 = {}));
var InjectedTextCursorStops2;
(function(InjectedTextCursorStops3) {
  InjectedTextCursorStops3[InjectedTextCursorStops3["Both"] = 0] = "Both";
  InjectedTextCursorStops3[InjectedTextCursorStops3["Right"] = 1] = "Right";
  InjectedTextCursorStops3[InjectedTextCursorStops3["Left"] = 2] = "Left";
  InjectedTextCursorStops3[InjectedTextCursorStops3["None"] = 3] = "None";
})(InjectedTextCursorStops2 || (InjectedTextCursorStops2 = {}));
var InlayHintKind4;
(function(InlayHintKind5) {
  InlayHintKind5[InlayHintKind5["Type"] = 1] = "Type";
  InlayHintKind5[InlayHintKind5["Parameter"] = 2] = "Parameter";
})(InlayHintKind4 || (InlayHintKind4 = {}));
var InlineCompletionTriggerKind3;
(function(InlineCompletionTriggerKind4) {
  InlineCompletionTriggerKind4[InlineCompletionTriggerKind4["Automatic"] = 0] = "Automatic";
  InlineCompletionTriggerKind4[InlineCompletionTriggerKind4["Explicit"] = 1] = "Explicit";
})(InlineCompletionTriggerKind3 || (InlineCompletionTriggerKind3 = {}));
var InlineEditTriggerKind3;
(function(InlineEditTriggerKind4) {
  InlineEditTriggerKind4[InlineEditTriggerKind4["Invoke"] = 0] = "Invoke";
  InlineEditTriggerKind4[InlineEditTriggerKind4["Automatic"] = 1] = "Automatic";
})(InlineEditTriggerKind3 || (InlineEditTriggerKind3 = {}));
var KeyCode2;
(function(KeyCode3) {
  KeyCode3[KeyCode3["DependsOnKbLayout"] = -1] = "DependsOnKbLayout";
  KeyCode3[KeyCode3["Unknown"] = 0] = "Unknown";
  KeyCode3[KeyCode3["Backspace"] = 1] = "Backspace";
  KeyCode3[KeyCode3["Tab"] = 2] = "Tab";
  KeyCode3[KeyCode3["Enter"] = 3] = "Enter";
  KeyCode3[KeyCode3["Shift"] = 4] = "Shift";
  KeyCode3[KeyCode3["Ctrl"] = 5] = "Ctrl";
  KeyCode3[KeyCode3["Alt"] = 6] = "Alt";
  KeyCode3[KeyCode3["PauseBreak"] = 7] = "PauseBreak";
  KeyCode3[KeyCode3["CapsLock"] = 8] = "CapsLock";
  KeyCode3[KeyCode3["Escape"] = 9] = "Escape";
  KeyCode3[KeyCode3["Space"] = 10] = "Space";
  KeyCode3[KeyCode3["PageUp"] = 11] = "PageUp";
  KeyCode3[KeyCode3["PageDown"] = 12] = "PageDown";
  KeyCode3[KeyCode3["End"] = 13] = "End";
  KeyCode3[KeyCode3["Home"] = 14] = "Home";
  KeyCode3[KeyCode3["LeftArrow"] = 15] = "LeftArrow";
  KeyCode3[KeyCode3["UpArrow"] = 16] = "UpArrow";
  KeyCode3[KeyCode3["RightArrow"] = 17] = "RightArrow";
  KeyCode3[KeyCode3["DownArrow"] = 18] = "DownArrow";
  KeyCode3[KeyCode3["Insert"] = 19] = "Insert";
  KeyCode3[KeyCode3["Delete"] = 20] = "Delete";
  KeyCode3[KeyCode3["Digit0"] = 21] = "Digit0";
  KeyCode3[KeyCode3["Digit1"] = 22] = "Digit1";
  KeyCode3[KeyCode3["Digit2"] = 23] = "Digit2";
  KeyCode3[KeyCode3["Digit3"] = 24] = "Digit3";
  KeyCode3[KeyCode3["Digit4"] = 25] = "Digit4";
  KeyCode3[KeyCode3["Digit5"] = 26] = "Digit5";
  KeyCode3[KeyCode3["Digit6"] = 27] = "Digit6";
  KeyCode3[KeyCode3["Digit7"] = 28] = "Digit7";
  KeyCode3[KeyCode3["Digit8"] = 29] = "Digit8";
  KeyCode3[KeyCode3["Digit9"] = 30] = "Digit9";
  KeyCode3[KeyCode3["KeyA"] = 31] = "KeyA";
  KeyCode3[KeyCode3["KeyB"] = 32] = "KeyB";
  KeyCode3[KeyCode3["KeyC"] = 33] = "KeyC";
  KeyCode3[KeyCode3["KeyD"] = 34] = "KeyD";
  KeyCode3[KeyCode3["KeyE"] = 35] = "KeyE";
  KeyCode3[KeyCode3["KeyF"] = 36] = "KeyF";
  KeyCode3[KeyCode3["KeyG"] = 37] = "KeyG";
  KeyCode3[KeyCode3["KeyH"] = 38] = "KeyH";
  KeyCode3[KeyCode3["KeyI"] = 39] = "KeyI";
  KeyCode3[KeyCode3["KeyJ"] = 40] = "KeyJ";
  KeyCode3[KeyCode3["KeyK"] = 41] = "KeyK";
  KeyCode3[KeyCode3["KeyL"] = 42] = "KeyL";
  KeyCode3[KeyCode3["KeyM"] = 43] = "KeyM";
  KeyCode3[KeyCode3["KeyN"] = 44] = "KeyN";
  KeyCode3[KeyCode3["KeyO"] = 45] = "KeyO";
  KeyCode3[KeyCode3["KeyP"] = 46] = "KeyP";
  KeyCode3[KeyCode3["KeyQ"] = 47] = "KeyQ";
  KeyCode3[KeyCode3["KeyR"] = 48] = "KeyR";
  KeyCode3[KeyCode3["KeyS"] = 49] = "KeyS";
  KeyCode3[KeyCode3["KeyT"] = 50] = "KeyT";
  KeyCode3[KeyCode3["KeyU"] = 51] = "KeyU";
  KeyCode3[KeyCode3["KeyV"] = 52] = "KeyV";
  KeyCode3[KeyCode3["KeyW"] = 53] = "KeyW";
  KeyCode3[KeyCode3["KeyX"] = 54] = "KeyX";
  KeyCode3[KeyCode3["KeyY"] = 55] = "KeyY";
  KeyCode3[KeyCode3["KeyZ"] = 56] = "KeyZ";
  KeyCode3[KeyCode3["Meta"] = 57] = "Meta";
  KeyCode3[KeyCode3["ContextMenu"] = 58] = "ContextMenu";
  KeyCode3[KeyCode3["F1"] = 59] = "F1";
  KeyCode3[KeyCode3["F2"] = 60] = "F2";
  KeyCode3[KeyCode3["F3"] = 61] = "F3";
  KeyCode3[KeyCode3["F4"] = 62] = "F4";
  KeyCode3[KeyCode3["F5"] = 63] = "F5";
  KeyCode3[KeyCode3["F6"] = 64] = "F6";
  KeyCode3[KeyCode3["F7"] = 65] = "F7";
  KeyCode3[KeyCode3["F8"] = 66] = "F8";
  KeyCode3[KeyCode3["F9"] = 67] = "F9";
  KeyCode3[KeyCode3["F10"] = 68] = "F10";
  KeyCode3[KeyCode3["F11"] = 69] = "F11";
  KeyCode3[KeyCode3["F12"] = 70] = "F12";
  KeyCode3[KeyCode3["F13"] = 71] = "F13";
  KeyCode3[KeyCode3["F14"] = 72] = "F14";
  KeyCode3[KeyCode3["F15"] = 73] = "F15";
  KeyCode3[KeyCode3["F16"] = 74] = "F16";
  KeyCode3[KeyCode3["F17"] = 75] = "F17";
  KeyCode3[KeyCode3["F18"] = 76] = "F18";
  KeyCode3[KeyCode3["F19"] = 77] = "F19";
  KeyCode3[KeyCode3["F20"] = 78] = "F20";
  KeyCode3[KeyCode3["F21"] = 79] = "F21";
  KeyCode3[KeyCode3["F22"] = 80] = "F22";
  KeyCode3[KeyCode3["F23"] = 81] = "F23";
  KeyCode3[KeyCode3["F24"] = 82] = "F24";
  KeyCode3[KeyCode3["NumLock"] = 83] = "NumLock";
  KeyCode3[KeyCode3["ScrollLock"] = 84] = "ScrollLock";
  KeyCode3[KeyCode3["Semicolon"] = 85] = "Semicolon";
  KeyCode3[KeyCode3["Equal"] = 86] = "Equal";
  KeyCode3[KeyCode3["Comma"] = 87] = "Comma";
  KeyCode3[KeyCode3["Minus"] = 88] = "Minus";
  KeyCode3[KeyCode3["Period"] = 89] = "Period";
  KeyCode3[KeyCode3["Slash"] = 90] = "Slash";
  KeyCode3[KeyCode3["Backquote"] = 91] = "Backquote";
  KeyCode3[KeyCode3["BracketLeft"] = 92] = "BracketLeft";
  KeyCode3[KeyCode3["Backslash"] = 93] = "Backslash";
  KeyCode3[KeyCode3["BracketRight"] = 94] = "BracketRight";
  KeyCode3[KeyCode3["Quote"] = 95] = "Quote";
  KeyCode3[KeyCode3["OEM_8"] = 96] = "OEM_8";
  KeyCode3[KeyCode3["IntlBackslash"] = 97] = "IntlBackslash";
  KeyCode3[KeyCode3["Numpad0"] = 98] = "Numpad0";
  KeyCode3[KeyCode3["Numpad1"] = 99] = "Numpad1";
  KeyCode3[KeyCode3["Numpad2"] = 100] = "Numpad2";
  KeyCode3[KeyCode3["Numpad3"] = 101] = "Numpad3";
  KeyCode3[KeyCode3["Numpad4"] = 102] = "Numpad4";
  KeyCode3[KeyCode3["Numpad5"] = 103] = "Numpad5";
  KeyCode3[KeyCode3["Numpad6"] = 104] = "Numpad6";
  KeyCode3[KeyCode3["Numpad7"] = 105] = "Numpad7";
  KeyCode3[KeyCode3["Numpad8"] = 106] = "Numpad8";
  KeyCode3[KeyCode3["Numpad9"] = 107] = "Numpad9";
  KeyCode3[KeyCode3["NumpadMultiply"] = 108] = "NumpadMultiply";
  KeyCode3[KeyCode3["NumpadAdd"] = 109] = "NumpadAdd";
  KeyCode3[KeyCode3["NUMPAD_SEPARATOR"] = 110] = "NUMPAD_SEPARATOR";
  KeyCode3[KeyCode3["NumpadSubtract"] = 111] = "NumpadSubtract";
  KeyCode3[KeyCode3["NumpadDecimal"] = 112] = "NumpadDecimal";
  KeyCode3[KeyCode3["NumpadDivide"] = 113] = "NumpadDivide";
  KeyCode3[KeyCode3["KEY_IN_COMPOSITION"] = 114] = "KEY_IN_COMPOSITION";
  KeyCode3[KeyCode3["ABNT_C1"] = 115] = "ABNT_C1";
  KeyCode3[KeyCode3["ABNT_C2"] = 116] = "ABNT_C2";
  KeyCode3[KeyCode3["AudioVolumeMute"] = 117] = "AudioVolumeMute";
  KeyCode3[KeyCode3["AudioVolumeUp"] = 118] = "AudioVolumeUp";
  KeyCode3[KeyCode3["AudioVolumeDown"] = 119] = "AudioVolumeDown";
  KeyCode3[KeyCode3["BrowserSearch"] = 120] = "BrowserSearch";
  KeyCode3[KeyCode3["BrowserHome"] = 121] = "BrowserHome";
  KeyCode3[KeyCode3["BrowserBack"] = 122] = "BrowserBack";
  KeyCode3[KeyCode3["BrowserForward"] = 123] = "BrowserForward";
  KeyCode3[KeyCode3["MediaTrackNext"] = 124] = "MediaTrackNext";
  KeyCode3[KeyCode3["MediaTrackPrevious"] = 125] = "MediaTrackPrevious";
  KeyCode3[KeyCode3["MediaStop"] = 126] = "MediaStop";
  KeyCode3[KeyCode3["MediaPlayPause"] = 127] = "MediaPlayPause";
  KeyCode3[KeyCode3["LaunchMediaPlayer"] = 128] = "LaunchMediaPlayer";
  KeyCode3[KeyCode3["LaunchMail"] = 129] = "LaunchMail";
  KeyCode3[KeyCode3["LaunchApp2"] = 130] = "LaunchApp2";
  KeyCode3[KeyCode3["Clear"] = 131] = "Clear";
  KeyCode3[KeyCode3["MAX_VALUE"] = 132] = "MAX_VALUE";
})(KeyCode2 || (KeyCode2 = {}));
var MarkerSeverity2;
(function(MarkerSeverity3) {
  MarkerSeverity3[MarkerSeverity3["Hint"] = 1] = "Hint";
  MarkerSeverity3[MarkerSeverity3["Info"] = 2] = "Info";
  MarkerSeverity3[MarkerSeverity3["Warning"] = 4] = "Warning";
  MarkerSeverity3[MarkerSeverity3["Error"] = 8] = "Error";
})(MarkerSeverity2 || (MarkerSeverity2 = {}));
var MarkerTag2;
(function(MarkerTag3) {
  MarkerTag3[MarkerTag3["Unnecessary"] = 1] = "Unnecessary";
  MarkerTag3[MarkerTag3["Deprecated"] = 2] = "Deprecated";
})(MarkerTag2 || (MarkerTag2 = {}));
var MinimapPosition2;
(function(MinimapPosition3) {
  MinimapPosition3[MinimapPosition3["Inline"] = 1] = "Inline";
  MinimapPosition3[MinimapPosition3["Gutter"] = 2] = "Gutter";
})(MinimapPosition2 || (MinimapPosition2 = {}));
var MinimapSectionHeaderStyle2;
(function(MinimapSectionHeaderStyle3) {
  MinimapSectionHeaderStyle3[MinimapSectionHeaderStyle3["Normal"] = 1] = "Normal";
  MinimapSectionHeaderStyle3[MinimapSectionHeaderStyle3["Underlined"] = 2] = "Underlined";
})(MinimapSectionHeaderStyle2 || (MinimapSectionHeaderStyle2 = {}));
var MouseTargetType2;
(function(MouseTargetType3) {
  MouseTargetType3[MouseTargetType3["UNKNOWN"] = 0] = "UNKNOWN";
  MouseTargetType3[MouseTargetType3["TEXTAREA"] = 1] = "TEXTAREA";
  MouseTargetType3[MouseTargetType3["GUTTER_GLYPH_MARGIN"] = 2] = "GUTTER_GLYPH_MARGIN";
  MouseTargetType3[MouseTargetType3["GUTTER_LINE_NUMBERS"] = 3] = "GUTTER_LINE_NUMBERS";
  MouseTargetType3[MouseTargetType3["GUTTER_LINE_DECORATIONS"] = 4] = "GUTTER_LINE_DECORATIONS";
  MouseTargetType3[MouseTargetType3["GUTTER_VIEW_ZONE"] = 5] = "GUTTER_VIEW_ZONE";
  MouseTargetType3[MouseTargetType3["CONTENT_TEXT"] = 6] = "CONTENT_TEXT";
  MouseTargetType3[MouseTargetType3["CONTENT_EMPTY"] = 7] = "CONTENT_EMPTY";
  MouseTargetType3[MouseTargetType3["CONTENT_VIEW_ZONE"] = 8] = "CONTENT_VIEW_ZONE";
  MouseTargetType3[MouseTargetType3["CONTENT_WIDGET"] = 9] = "CONTENT_WIDGET";
  MouseTargetType3[MouseTargetType3["OVERVIEW_RULER"] = 10] = "OVERVIEW_RULER";
  MouseTargetType3[MouseTargetType3["SCROLLBAR"] = 11] = "SCROLLBAR";
  MouseTargetType3[MouseTargetType3["OVERLAY_WIDGET"] = 12] = "OVERLAY_WIDGET";
  MouseTargetType3[MouseTargetType3["OUTSIDE_EDITOR"] = 13] = "OUTSIDE_EDITOR";
})(MouseTargetType2 || (MouseTargetType2 = {}));
var NewSymbolNameTag3;
(function(NewSymbolNameTag4) {
  NewSymbolNameTag4[NewSymbolNameTag4["AIGenerated"] = 1] = "AIGenerated";
})(NewSymbolNameTag3 || (NewSymbolNameTag3 = {}));
var NewSymbolNameTriggerKind3;
(function(NewSymbolNameTriggerKind4) {
  NewSymbolNameTriggerKind4[NewSymbolNameTriggerKind4["Invoke"] = 0] = "Invoke";
  NewSymbolNameTriggerKind4[NewSymbolNameTriggerKind4["Automatic"] = 1] = "Automatic";
})(NewSymbolNameTriggerKind3 || (NewSymbolNameTriggerKind3 = {}));
var OverlayWidgetPositionPreference2;
(function(OverlayWidgetPositionPreference3) {
  OverlayWidgetPositionPreference3[OverlayWidgetPositionPreference3["TOP_RIGHT_CORNER"] = 0] = "TOP_RIGHT_CORNER";
  OverlayWidgetPositionPreference3[OverlayWidgetPositionPreference3["BOTTOM_RIGHT_CORNER"] = 1] = "BOTTOM_RIGHT_CORNER";
  OverlayWidgetPositionPreference3[OverlayWidgetPositionPreference3["TOP_CENTER"] = 2] = "TOP_CENTER";
})(OverlayWidgetPositionPreference2 || (OverlayWidgetPositionPreference2 = {}));
var OverviewRulerLane3;
(function(OverviewRulerLane4) {
  OverviewRulerLane4[OverviewRulerLane4["Left"] = 1] = "Left";
  OverviewRulerLane4[OverviewRulerLane4["Center"] = 2] = "Center";
  OverviewRulerLane4[OverviewRulerLane4["Right"] = 4] = "Right";
  OverviewRulerLane4[OverviewRulerLane4["Full"] = 7] = "Full";
})(OverviewRulerLane3 || (OverviewRulerLane3 = {}));
var PartialAcceptTriggerKind4;
(function(PartialAcceptTriggerKind5) {
  PartialAcceptTriggerKind5[PartialAcceptTriggerKind5["Word"] = 0] = "Word";
  PartialAcceptTriggerKind5[PartialAcceptTriggerKind5["Line"] = 1] = "Line";
  PartialAcceptTriggerKind5[PartialAcceptTriggerKind5["Suggest"] = 2] = "Suggest";
})(PartialAcceptTriggerKind4 || (PartialAcceptTriggerKind4 = {}));
var PositionAffinity2;
(function(PositionAffinity3) {
  PositionAffinity3[PositionAffinity3["Left"] = 0] = "Left";
  PositionAffinity3[PositionAffinity3["Right"] = 1] = "Right";
  PositionAffinity3[PositionAffinity3["None"] = 2] = "None";
  PositionAffinity3[PositionAffinity3["LeftOfInjectedText"] = 3] = "LeftOfInjectedText";
  PositionAffinity3[PositionAffinity3["RightOfInjectedText"] = 4] = "RightOfInjectedText";
})(PositionAffinity2 || (PositionAffinity2 = {}));
var RenderLineNumbersType2;
(function(RenderLineNumbersType3) {
  RenderLineNumbersType3[RenderLineNumbersType3["Off"] = 0] = "Off";
  RenderLineNumbersType3[RenderLineNumbersType3["On"] = 1] = "On";
  RenderLineNumbersType3[RenderLineNumbersType3["Relative"] = 2] = "Relative";
  RenderLineNumbersType3[RenderLineNumbersType3["Interval"] = 3] = "Interval";
  RenderLineNumbersType3[RenderLineNumbersType3["Custom"] = 4] = "Custom";
})(RenderLineNumbersType2 || (RenderLineNumbersType2 = {}));
var RenderMinimap2;
(function(RenderMinimap3) {
  RenderMinimap3[RenderMinimap3["None"] = 0] = "None";
  RenderMinimap3[RenderMinimap3["Text"] = 1] = "Text";
  RenderMinimap3[RenderMinimap3["Blocks"] = 2] = "Blocks";
})(RenderMinimap2 || (RenderMinimap2 = {}));
var ScrollType2;
(function(ScrollType3) {
  ScrollType3[ScrollType3["Smooth"] = 0] = "Smooth";
  ScrollType3[ScrollType3["Immediate"] = 1] = "Immediate";
})(ScrollType2 || (ScrollType2 = {}));
var ScrollbarVisibility2;
(function(ScrollbarVisibility3) {
  ScrollbarVisibility3[ScrollbarVisibility3["Auto"] = 1] = "Auto";
  ScrollbarVisibility3[ScrollbarVisibility3["Hidden"] = 2] = "Hidden";
  ScrollbarVisibility3[ScrollbarVisibility3["Visible"] = 3] = "Visible";
})(ScrollbarVisibility2 || (ScrollbarVisibility2 = {}));
var SelectionDirection2;
(function(SelectionDirection3) {
  SelectionDirection3[SelectionDirection3["LTR"] = 0] = "LTR";
  SelectionDirection3[SelectionDirection3["RTL"] = 1] = "RTL";
})(SelectionDirection2 || (SelectionDirection2 = {}));
var ShowLightbulbIconMode2;
(function(ShowLightbulbIconMode3) {
  ShowLightbulbIconMode3["Off"] = "off";
  ShowLightbulbIconMode3["OnCode"] = "onCode";
  ShowLightbulbIconMode3["On"] = "on";
})(ShowLightbulbIconMode2 || (ShowLightbulbIconMode2 = {}));
var SignatureHelpTriggerKind3;
(function(SignatureHelpTriggerKind4) {
  SignatureHelpTriggerKind4[SignatureHelpTriggerKind4["Invoke"] = 1] = "Invoke";
  SignatureHelpTriggerKind4[SignatureHelpTriggerKind4["TriggerCharacter"] = 2] = "TriggerCharacter";
  SignatureHelpTriggerKind4[SignatureHelpTriggerKind4["ContentChange"] = 3] = "ContentChange";
})(SignatureHelpTriggerKind3 || (SignatureHelpTriggerKind3 = {}));
var SymbolKind4;
(function(SymbolKind5) {
  SymbolKind5[SymbolKind5["File"] = 0] = "File";
  SymbolKind5[SymbolKind5["Module"] = 1] = "Module";
  SymbolKind5[SymbolKind5["Namespace"] = 2] = "Namespace";
  SymbolKind5[SymbolKind5["Package"] = 3] = "Package";
  SymbolKind5[SymbolKind5["Class"] = 4] = "Class";
  SymbolKind5[SymbolKind5["Method"] = 5] = "Method";
  SymbolKind5[SymbolKind5["Property"] = 6] = "Property";
  SymbolKind5[SymbolKind5["Field"] = 7] = "Field";
  SymbolKind5[SymbolKind5["Constructor"] = 8] = "Constructor";
  SymbolKind5[SymbolKind5["Enum"] = 9] = "Enum";
  SymbolKind5[SymbolKind5["Interface"] = 10] = "Interface";
  SymbolKind5[SymbolKind5["Function"] = 11] = "Function";
  SymbolKind5[SymbolKind5["Variable"] = 12] = "Variable";
  SymbolKind5[SymbolKind5["Constant"] = 13] = "Constant";
  SymbolKind5[SymbolKind5["String"] = 14] = "String";
  SymbolKind5[SymbolKind5["Number"] = 15] = "Number";
  SymbolKind5[SymbolKind5["Boolean"] = 16] = "Boolean";
  SymbolKind5[SymbolKind5["Array"] = 17] = "Array";
  SymbolKind5[SymbolKind5["Object"] = 18] = "Object";
  SymbolKind5[SymbolKind5["Key"] = 19] = "Key";
  SymbolKind5[SymbolKind5["Null"] = 20] = "Null";
  SymbolKind5[SymbolKind5["EnumMember"] = 21] = "EnumMember";
  SymbolKind5[SymbolKind5["Struct"] = 22] = "Struct";
  SymbolKind5[SymbolKind5["Event"] = 23] = "Event";
  SymbolKind5[SymbolKind5["Operator"] = 24] = "Operator";
  SymbolKind5[SymbolKind5["TypeParameter"] = 25] = "TypeParameter";
})(SymbolKind4 || (SymbolKind4 = {}));
var SymbolTag4;
(function(SymbolTag5) {
  SymbolTag5[SymbolTag5["Deprecated"] = 1] = "Deprecated";
})(SymbolTag4 || (SymbolTag4 = {}));
var TextEditorCursorBlinkingStyle2;
(function(TextEditorCursorBlinkingStyle3) {
  TextEditorCursorBlinkingStyle3[TextEditorCursorBlinkingStyle3["Hidden"] = 0] = "Hidden";
  TextEditorCursorBlinkingStyle3[TextEditorCursorBlinkingStyle3["Blink"] = 1] = "Blink";
  TextEditorCursorBlinkingStyle3[TextEditorCursorBlinkingStyle3["Smooth"] = 2] = "Smooth";
  TextEditorCursorBlinkingStyle3[TextEditorCursorBlinkingStyle3["Phase"] = 3] = "Phase";
  TextEditorCursorBlinkingStyle3[TextEditorCursorBlinkingStyle3["Expand"] = 4] = "Expand";
  TextEditorCursorBlinkingStyle3[TextEditorCursorBlinkingStyle3["Solid"] = 5] = "Solid";
})(TextEditorCursorBlinkingStyle2 || (TextEditorCursorBlinkingStyle2 = {}));
var TextEditorCursorStyle2;
(function(TextEditorCursorStyle3) {
  TextEditorCursorStyle3[TextEditorCursorStyle3["Line"] = 1] = "Line";
  TextEditorCursorStyle3[TextEditorCursorStyle3["Block"] = 2] = "Block";
  TextEditorCursorStyle3[TextEditorCursorStyle3["Underline"] = 3] = "Underline";
  TextEditorCursorStyle3[TextEditorCursorStyle3["LineThin"] = 4] = "LineThin";
  TextEditorCursorStyle3[TextEditorCursorStyle3["BlockOutline"] = 5] = "BlockOutline";
  TextEditorCursorStyle3[TextEditorCursorStyle3["UnderlineThin"] = 6] = "UnderlineThin";
})(TextEditorCursorStyle2 || (TextEditorCursorStyle2 = {}));
var TrackedRangeStickiness2;
(function(TrackedRangeStickiness3) {
  TrackedRangeStickiness3[TrackedRangeStickiness3["AlwaysGrowsWhenTypingAtEdges"] = 0] = "AlwaysGrowsWhenTypingAtEdges";
  TrackedRangeStickiness3[TrackedRangeStickiness3["NeverGrowsWhenTypingAtEdges"] = 1] = "NeverGrowsWhenTypingAtEdges";
  TrackedRangeStickiness3[TrackedRangeStickiness3["GrowsOnlyWhenTypingBefore"] = 2] = "GrowsOnlyWhenTypingBefore";
  TrackedRangeStickiness3[TrackedRangeStickiness3["GrowsOnlyWhenTypingAfter"] = 3] = "GrowsOnlyWhenTypingAfter";
})(TrackedRangeStickiness2 || (TrackedRangeStickiness2 = {}));
var WrappingIndent2;
(function(WrappingIndent3) {
  WrappingIndent3[WrappingIndent3["None"] = 0] = "None";
  WrappingIndent3[WrappingIndent3["Same"] = 1] = "Same";
  WrappingIndent3[WrappingIndent3["Indent"] = 2] = "Indent";
  WrappingIndent3[WrappingIndent3["DeepIndent"] = 3] = "DeepIndent";
})(WrappingIndent2 || (WrappingIndent2 = {}));

// out-build/vs/editor/common/services/editorBaseApi.js
var $b0 = class {
  static {
    this.CtrlCmd = 2048;
  }
  static {
    this.Shift = 1024;
  }
  static {
    this.Alt = 512;
  }
  static {
    this.WinCtrl = 256;
  }
  static chord(firstPart, secondPart) {
    return $$e(firstPart, secondPart);
  }
};
function $c0() {
  return {
    editor: void 0,
    // undefined override expected here
    languages: void 0,
    // undefined override expected here
    CancellationTokenSource: $ad,
    Emitter: $ze,
    KeyCode: KeyCode2,
    KeyMod: $b0,
    Position: $8C,
    Range: $9C,
    Selection: $_D,
    SelectionDirection: SelectionDirection2,
    MarkerSeverity: MarkerSeverity2,
    MarkerTag: MarkerTag2,
    Uri: URI,
    Token: $NE
  };
}

// out-build/vs/editor/common/services/editorWorkerHost.js
var $d0 = class _$d0 {
  static {
    this.CHANNEL_NAME = "editorWorkerHost";
  }
  static getChannel(workerServer) {
    return workerServer.getChannel(_$d0.CHANNEL_NAME);
  }
  static setChannel(workerClient, obj) {
    workerClient.setChannel(_$d0.CHANNEL_NAME, obj);
  }
};

// out-build/vs/editor/common/diff/legacyLinesDiffComputer.js
var MINIMUM_MATCHING_CHARACTER_LENGTH = 3;
var $xD = class {
  computeDiff(originalLines, modifiedLines, options3) {
    const diffComputer = new $yD(originalLines, modifiedLines, {
      maxComputationTime: options3.maxComputationTimeMs,
      shouldIgnoreTrimWhitespace: options3.ignoreTrimWhitespace,
      shouldComputeCharChanges: true,
      shouldMakePrettyDiff: true,
      shouldPostProcessCharChanges: true
    });
    const result = diffComputer.computeDiff();
    const changes = [];
    let lastChange = null;
    for (const c of result.changes) {
      let originalRange;
      if (c.originalEndLineNumber === 0) {
        originalRange = new $_C(c.originalStartLineNumber + 1, c.originalStartLineNumber + 1);
      } else {
        originalRange = new $_C(c.originalStartLineNumber, c.originalEndLineNumber + 1);
      }
      let modifiedRange;
      if (c.modifiedEndLineNumber === 0) {
        modifiedRange = new $_C(c.modifiedStartLineNumber + 1, c.modifiedStartLineNumber + 1);
      } else {
        modifiedRange = new $_C(c.modifiedStartLineNumber, c.modifiedEndLineNumber + 1);
      }
      let change = new $qD(originalRange, modifiedRange, c.charChanges?.map((c2) => new $rD(new $9C(c2.originalStartLineNumber, c2.originalStartColumn, c2.originalEndLineNumber, c2.originalEndColumn), new $9C(c2.modifiedStartLineNumber, c2.modifiedStartColumn, c2.modifiedEndLineNumber, c2.modifiedEndColumn))));
      if (lastChange) {
        if (lastChange.modified.endLineNumberExclusive === change.modified.startLineNumber || lastChange.original.endLineNumberExclusive === change.original.startLineNumber) {
          change = new $qD(lastChange.original.join(change.original), lastChange.modified.join(change.modified), lastChange.innerChanges && change.innerChanges ? lastChange.innerChanges.concat(change.innerChanges) : void 0);
          changes.pop();
        }
      }
      changes.push(change);
      lastChange = change;
    }
    $kd(() => {
      return $ld(changes, (m1, m2) => m2.original.startLineNumber - m1.original.endLineNumberExclusive === m2.modified.startLineNumber - m1.modified.endLineNumberExclusive && // There has to be an unchanged line in between (otherwise both diffs should have been joined)
      m1.original.endLineNumberExclusive < m2.original.startLineNumber && m1.modified.endLineNumberExclusive < m2.modified.startLineNumber);
    });
    return new $vD(changes, [], result.quitEarly);
  }
};
function computeDiff(originalSequence, modifiedSequence, continueProcessingPredicate, pretty2) {
  const diffAlgo = new $7C(originalSequence, modifiedSequence, continueProcessingPredicate);
  return diffAlgo.ComputeDiff(pretty2);
}
var LineSequence = class {
  constructor(lines) {
    const startColumns = [];
    const endColumns = [];
    for (let i2 = 0, length = lines.length; i2 < length; i2++) {
      startColumns[i2] = getFirstNonBlankColumn(lines[i2], 1);
      endColumns[i2] = getLastNonBlankColumn(lines[i2], 1);
    }
    this.lines = lines;
    this.a = startColumns;
    this.b = endColumns;
  }
  getElements() {
    const elements = [];
    for (let i2 = 0, len = this.lines.length; i2 < len; i2++) {
      elements[i2] = this.lines[i2].substring(this.a[i2] - 1, this.b[i2] - 1);
    }
    return elements;
  }
  getStrictElement(index) {
    return this.lines[index];
  }
  getStartLineNumber(i2) {
    return i2 + 1;
  }
  getEndLineNumber(i2) {
    return i2 + 1;
  }
  createCharSequence(shouldIgnoreTrimWhitespace, startIndex, endIndex) {
    const charCodes = [];
    const lineNumbers = [];
    const columns = [];
    let len = 0;
    for (let index = startIndex; index <= endIndex; index++) {
      const lineContent = this.lines[index];
      const startColumn = shouldIgnoreTrimWhitespace ? this.a[index] : 1;
      const endColumn = shouldIgnoreTrimWhitespace ? this.b[index] : lineContent.length + 1;
      for (let col = startColumn; col < endColumn; col++) {
        charCodes[len] = lineContent.charCodeAt(col - 1);
        lineNumbers[len] = index + 1;
        columns[len] = col;
        len++;
      }
      if (!shouldIgnoreTrimWhitespace && index < endIndex) {
        charCodes[len] = 10;
        lineNumbers[len] = index + 1;
        columns[len] = lineContent.length + 1;
        len++;
      }
    }
    return new CharSequence(charCodes, lineNumbers, columns);
  }
};
var CharSequence = class {
  constructor(charCodes, lineNumbers, columns) {
    this.a = charCodes;
    this.b = lineNumbers;
    this.d = columns;
  }
  toString() {
    return "[" + this.a.map((s, idx) => (s === 10 ? "\\n" : String.fromCharCode(s)) + `-(${this.b[idx]},${this.d[idx]})`).join(", ") + "]";
  }
  e(index, arr) {
    if (index < 0 || index >= arr.length) {
      throw new Error(`Illegal index`);
    }
  }
  getElements() {
    return this.a;
  }
  getStartLineNumber(i2) {
    if (i2 > 0 && i2 === this.b.length) {
      return this.getEndLineNumber(i2 - 1);
    }
    this.e(i2, this.b);
    return this.b[i2];
  }
  getEndLineNumber(i2) {
    if (i2 === -1) {
      return this.getStartLineNumber(i2 + 1);
    }
    this.e(i2, this.b);
    if (this.a[i2] === 10) {
      return this.b[i2] + 1;
    }
    return this.b[i2];
  }
  getStartColumn(i2) {
    if (i2 > 0 && i2 === this.d.length) {
      return this.getEndColumn(i2 - 1);
    }
    this.e(i2, this.d);
    return this.d[i2];
  }
  getEndColumn(i2) {
    if (i2 === -1) {
      return this.getStartColumn(i2 + 1);
    }
    this.e(i2, this.d);
    if (this.a[i2] === 10) {
      return 1;
    }
    return this.d[i2] + 1;
  }
};
var CharChange = class _CharChange {
  constructor(originalStartLineNumber, originalStartColumn, originalEndLineNumber, originalEndColumn, modifiedStartLineNumber, modifiedStartColumn, modifiedEndLineNumber, modifiedEndColumn) {
    this.originalStartLineNumber = originalStartLineNumber;
    this.originalStartColumn = originalStartColumn;
    this.originalEndLineNumber = originalEndLineNumber;
    this.originalEndColumn = originalEndColumn;
    this.modifiedStartLineNumber = modifiedStartLineNumber;
    this.modifiedStartColumn = modifiedStartColumn;
    this.modifiedEndLineNumber = modifiedEndLineNumber;
    this.modifiedEndColumn = modifiedEndColumn;
  }
  static createFromDiffChange(diffChange, originalCharSequence, modifiedCharSequence) {
    const originalStartLineNumber = originalCharSequence.getStartLineNumber(diffChange.originalStart);
    const originalStartColumn = originalCharSequence.getStartColumn(diffChange.originalStart);
    const originalEndLineNumber = originalCharSequence.getEndLineNumber(diffChange.originalStart + diffChange.originalLength - 1);
    const originalEndColumn = originalCharSequence.getEndColumn(diffChange.originalStart + diffChange.originalLength - 1);
    const modifiedStartLineNumber = modifiedCharSequence.getStartLineNumber(diffChange.modifiedStart);
    const modifiedStartColumn = modifiedCharSequence.getStartColumn(diffChange.modifiedStart);
    const modifiedEndLineNumber = modifiedCharSequence.getEndLineNumber(diffChange.modifiedStart + diffChange.modifiedLength - 1);
    const modifiedEndColumn = modifiedCharSequence.getEndColumn(diffChange.modifiedStart + diffChange.modifiedLength - 1);
    return new _CharChange(originalStartLineNumber, originalStartColumn, originalEndLineNumber, originalEndColumn, modifiedStartLineNumber, modifiedStartColumn, modifiedEndLineNumber, modifiedEndColumn);
  }
};
function postProcessCharChanges(rawChanges) {
  if (rawChanges.length <= 1) {
    return rawChanges;
  }
  const result = [rawChanges[0]];
  let prevChange = result[0];
  for (let i2 = 1, len = rawChanges.length; i2 < len; i2++) {
    const currChange = rawChanges[i2];
    const originalMatchingLength = currChange.originalStart - (prevChange.originalStart + prevChange.originalLength);
    const modifiedMatchingLength = currChange.modifiedStart - (prevChange.modifiedStart + prevChange.modifiedLength);
    const matchingLength = Math.min(originalMatchingLength, modifiedMatchingLength);
    if (matchingLength < MINIMUM_MATCHING_CHARACTER_LENGTH) {
      prevChange.originalLength = currChange.originalStart + currChange.originalLength - prevChange.originalStart;
      prevChange.modifiedLength = currChange.modifiedStart + currChange.modifiedLength - prevChange.modifiedStart;
    } else {
      result.push(currChange);
      prevChange = currChange;
    }
  }
  return result;
}
var LineChange = class _LineChange {
  constructor(originalStartLineNumber, originalEndLineNumber, modifiedStartLineNumber, modifiedEndLineNumber, charChanges) {
    this.originalStartLineNumber = originalStartLineNumber;
    this.originalEndLineNumber = originalEndLineNumber;
    this.modifiedStartLineNumber = modifiedStartLineNumber;
    this.modifiedEndLineNumber = modifiedEndLineNumber;
    this.charChanges = charChanges;
  }
  static createFromDiffResult(shouldIgnoreTrimWhitespace, diffChange, originalLineSequence, modifiedLineSequence, continueCharDiff, shouldComputeCharChanges, shouldPostProcessCharChanges) {
    let originalStartLineNumber;
    let originalEndLineNumber;
    let modifiedStartLineNumber;
    let modifiedEndLineNumber;
    let charChanges = void 0;
    if (diffChange.originalLength === 0) {
      originalStartLineNumber = originalLineSequence.getStartLineNumber(diffChange.originalStart) - 1;
      originalEndLineNumber = 0;
    } else {
      originalStartLineNumber = originalLineSequence.getStartLineNumber(diffChange.originalStart);
      originalEndLineNumber = originalLineSequence.getEndLineNumber(diffChange.originalStart + diffChange.originalLength - 1);
    }
    if (diffChange.modifiedLength === 0) {
      modifiedStartLineNumber = modifiedLineSequence.getStartLineNumber(diffChange.modifiedStart) - 1;
      modifiedEndLineNumber = 0;
    } else {
      modifiedStartLineNumber = modifiedLineSequence.getStartLineNumber(diffChange.modifiedStart);
      modifiedEndLineNumber = modifiedLineSequence.getEndLineNumber(diffChange.modifiedStart + diffChange.modifiedLength - 1);
    }
    if (shouldComputeCharChanges && diffChange.originalLength > 0 && diffChange.originalLength < 20 && diffChange.modifiedLength > 0 && diffChange.modifiedLength < 20 && continueCharDiff()) {
      const originalCharSequence = originalLineSequence.createCharSequence(shouldIgnoreTrimWhitespace, diffChange.originalStart, diffChange.originalStart + diffChange.originalLength - 1);
      const modifiedCharSequence = modifiedLineSequence.createCharSequence(shouldIgnoreTrimWhitespace, diffChange.modifiedStart, diffChange.modifiedStart + diffChange.modifiedLength - 1);
      if (originalCharSequence.getElements().length > 0 && modifiedCharSequence.getElements().length > 0) {
        let rawChanges = computeDiff(originalCharSequence, modifiedCharSequence, continueCharDiff, true).changes;
        if (shouldPostProcessCharChanges) {
          rawChanges = postProcessCharChanges(rawChanges);
        }
        charChanges = [];
        for (let i2 = 0, length = rawChanges.length; i2 < length; i2++) {
          charChanges.push(CharChange.createFromDiffChange(rawChanges[i2], originalCharSequence, modifiedCharSequence));
        }
      }
    }
    return new _LineChange(originalStartLineNumber, originalEndLineNumber, modifiedStartLineNumber, modifiedEndLineNumber, charChanges);
  }
};
var $yD = class {
  constructor(originalLines, modifiedLines, opts) {
    this.a = opts.shouldComputeCharChanges;
    this.b = opts.shouldPostProcessCharChanges;
    this.d = opts.shouldIgnoreTrimWhitespace;
    this.e = opts.shouldMakePrettyDiff;
    this.f = originalLines;
    this.g = modifiedLines;
    this.h = new LineSequence(originalLines);
    this.j = new LineSequence(modifiedLines);
    this.k = createContinueProcessingPredicate(opts.maxComputationTime);
    this.l = createContinueProcessingPredicate(opts.maxComputationTime === 0 ? 0 : Math.min(opts.maxComputationTime, 5e3));
  }
  computeDiff() {
    if (this.h.lines.length === 1 && this.h.lines[0].length === 0) {
      if (this.j.lines.length === 1 && this.j.lines[0].length === 0) {
        return {
          quitEarly: false,
          changes: []
        };
      }
      return {
        quitEarly: false,
        changes: [{
          originalStartLineNumber: 1,
          originalEndLineNumber: 1,
          modifiedStartLineNumber: 1,
          modifiedEndLineNumber: this.j.lines.length,
          charChanges: void 0
        }]
      };
    }
    if (this.j.lines.length === 1 && this.j.lines[0].length === 0) {
      return {
        quitEarly: false,
        changes: [{
          originalStartLineNumber: 1,
          originalEndLineNumber: this.h.lines.length,
          modifiedStartLineNumber: 1,
          modifiedEndLineNumber: 1,
          charChanges: void 0
        }]
      };
    }
    const diffResult = computeDiff(this.h, this.j, this.k, this.e);
    const rawChanges = diffResult.changes;
    const quitEarly = diffResult.quitEarly;
    if (this.d) {
      const lineChanges = [];
      for (let i2 = 0, length = rawChanges.length; i2 < length; i2++) {
        lineChanges.push(LineChange.createFromDiffResult(this.d, rawChanges[i2], this.h, this.j, this.l, this.a, this.b));
      }
      return {
        quitEarly,
        changes: lineChanges
      };
    }
    const result = [];
    let originalLineIndex = 0;
    let modifiedLineIndex = 0;
    for (let i2 = -1, len = rawChanges.length; i2 < len; i2++) {
      const nextChange = i2 + 1 < len ? rawChanges[i2 + 1] : null;
      const originalStop = nextChange ? nextChange.originalStart : this.f.length;
      const modifiedStop = nextChange ? nextChange.modifiedStart : this.g.length;
      while (originalLineIndex < originalStop && modifiedLineIndex < modifiedStop) {
        const originalLine = this.f[originalLineIndex];
        const modifiedLine = this.g[modifiedLineIndex];
        if (originalLine !== modifiedLine) {
          {
            let originalStartColumn = getFirstNonBlankColumn(originalLine, 1);
            let modifiedStartColumn = getFirstNonBlankColumn(modifiedLine, 1);
            while (originalStartColumn > 1 && modifiedStartColumn > 1) {
              const originalChar = originalLine.charCodeAt(originalStartColumn - 2);
              const modifiedChar = modifiedLine.charCodeAt(modifiedStartColumn - 2);
              if (originalChar !== modifiedChar) {
                break;
              }
              originalStartColumn--;
              modifiedStartColumn--;
            }
            if (originalStartColumn > 1 || modifiedStartColumn > 1) {
              this.m(result, originalLineIndex + 1, 1, originalStartColumn, modifiedLineIndex + 1, 1, modifiedStartColumn);
            }
          }
          {
            let originalEndColumn = getLastNonBlankColumn(originalLine, 1);
            let modifiedEndColumn = getLastNonBlankColumn(modifiedLine, 1);
            const originalMaxColumn = originalLine.length + 1;
            const modifiedMaxColumn = modifiedLine.length + 1;
            while (originalEndColumn < originalMaxColumn && modifiedEndColumn < modifiedMaxColumn) {
              const originalChar = originalLine.charCodeAt(originalEndColumn - 1);
              const modifiedChar = originalLine.charCodeAt(modifiedEndColumn - 1);
              if (originalChar !== modifiedChar) {
                break;
              }
              originalEndColumn++;
              modifiedEndColumn++;
            }
            if (originalEndColumn < originalMaxColumn || modifiedEndColumn < modifiedMaxColumn) {
              this.m(result, originalLineIndex + 1, originalEndColumn, originalMaxColumn, modifiedLineIndex + 1, modifiedEndColumn, modifiedMaxColumn);
            }
          }
        }
        originalLineIndex++;
        modifiedLineIndex++;
      }
      if (nextChange) {
        result.push(LineChange.createFromDiffResult(this.d, nextChange, this.h, this.j, this.l, this.a, this.b));
        originalLineIndex += nextChange.originalLength;
        modifiedLineIndex += nextChange.modifiedLength;
      }
    }
    return {
      quitEarly,
      changes: result
    };
  }
  m(result, originalLineNumber, originalStartColumn, originalEndColumn, modifiedLineNumber, modifiedStartColumn, modifiedEndColumn) {
    if (this.n(result, originalLineNumber, originalStartColumn, originalEndColumn, modifiedLineNumber, modifiedStartColumn, modifiedEndColumn)) {
      return;
    }
    let charChanges = void 0;
    if (this.a) {
      charChanges = [new CharChange(originalLineNumber, originalStartColumn, originalLineNumber, originalEndColumn, modifiedLineNumber, modifiedStartColumn, modifiedLineNumber, modifiedEndColumn)];
    }
    result.push(new LineChange(originalLineNumber, originalLineNumber, modifiedLineNumber, modifiedLineNumber, charChanges));
  }
  n(result, originalLineNumber, originalStartColumn, originalEndColumn, modifiedLineNumber, modifiedStartColumn, modifiedEndColumn) {
    const len = result.length;
    if (len === 0) {
      return false;
    }
    const prevChange = result[len - 1];
    if (prevChange.originalEndLineNumber === 0 || prevChange.modifiedEndLineNumber === 0) {
      return false;
    }
    if (prevChange.originalEndLineNumber === originalLineNumber && prevChange.modifiedEndLineNumber === modifiedLineNumber) {
      if (this.a && prevChange.charChanges) {
        prevChange.charChanges.push(new CharChange(originalLineNumber, originalStartColumn, originalLineNumber, originalEndColumn, modifiedLineNumber, modifiedStartColumn, modifiedLineNumber, modifiedEndColumn));
      }
      return true;
    }
    if (prevChange.originalEndLineNumber + 1 === originalLineNumber && prevChange.modifiedEndLineNumber + 1 === modifiedLineNumber) {
      prevChange.originalEndLineNumber = originalLineNumber;
      prevChange.modifiedEndLineNumber = modifiedLineNumber;
      if (this.a && prevChange.charChanges) {
        prevChange.charChanges.push(new CharChange(originalLineNumber, originalStartColumn, originalLineNumber, originalEndColumn, modifiedLineNumber, modifiedStartColumn, modifiedLineNumber, modifiedEndColumn));
      }
      return true;
    }
    return false;
  }
};
function getFirstNonBlankColumn(txt, defaultValue) {
  const r2 = $Of(txt);
  if (r2 === -1) {
    return defaultValue;
  }
  return r2 + 1;
}
function getLastNonBlankColumn(txt, defaultValue) {
  const r2 = $Qf(txt);
  if (r2 === -1) {
    return defaultValue;
  }
  return r2 + 2;
}
function createContinueProcessingPredicate(maximumRuntime) {
  if (maximumRuntime === 0) {
    return () => true;
  }
  const startTime = Date.now();
  return () => {
    return Date.now() - startTime < maximumRuntime;
  };
}

// out-build/vs/editor/common/diff/linesDiffComputers.js
var $x0 = {
  getLegacy: () => new $xD(),
  getDefault: () => new $w0()
};

// out-build/vs/editor/common/languages/defaultDocumentColorsComputer.js
function _parseCaptureGroups(captureGroups) {
  const values = [];
  for (const captureGroup of captureGroups) {
    const parsedNumber = Number(captureGroup);
    if (parsedNumber || parsedNumber === 0 && captureGroup.replace(/\s/g, "") !== "") {
      values.push(parsedNumber);
    }
  }
  return values;
}
function _toIColor(r2, g, b, a) {
  return {
    red: r2 / 255,
    blue: b / 255,
    green: g / 255,
    alpha: a
  };
}
function _findRange(model, match) {
  const index = match.index;
  const length = match[0].length;
  if (!index) {
    return;
  }
  const startPosition = model.positionAt(index);
  const range = {
    startLineNumber: startPosition.lineNumber,
    startColumn: startPosition.column,
    endLineNumber: startPosition.lineNumber,
    endColumn: startPosition.column + length
  };
  return range;
}
function _findHexColorInformation(range, hexValue) {
  if (!range) {
    return;
  }
  const parsedHexColor = $Vn.Format.CSS.parseHex(hexValue);
  if (!parsedHexColor) {
    return;
  }
  return {
    range,
    color: _toIColor(parsedHexColor.rgba.r, parsedHexColor.rgba.g, parsedHexColor.rgba.b, parsedHexColor.rgba.a)
  };
}
function _findRGBColorInformation(range, matches, isAlpha) {
  if (!range || matches.length !== 1) {
    return;
  }
  const match = matches[0];
  const captureGroups = match.values();
  const parsedRegex = _parseCaptureGroups(captureGroups);
  return {
    range,
    color: _toIColor(parsedRegex[0], parsedRegex[1], parsedRegex[2], isAlpha ? parsedRegex[3] : 1)
  };
}
function _findHSLColorInformation(range, matches, isAlpha) {
  if (!range || matches.length !== 1) {
    return;
  }
  const match = matches[0];
  const captureGroups = match.values();
  const parsedRegex = _parseCaptureGroups(captureGroups);
  const colorEquivalent = new $Vn(new $Tn(parsedRegex[0], parsedRegex[1] / 100, parsedRegex[2] / 100, isAlpha ? parsedRegex[3] : 1));
  return {
    range,
    color: _toIColor(colorEquivalent.rgba.r, colorEquivalent.rgba.g, colorEquivalent.rgba.b, colorEquivalent.rgba.a)
  };
}
function _findMatches(model, regex) {
  if (typeof model === "string") {
    return [...model.matchAll(regex)];
  } else {
    return model.findMatches(regex);
  }
}
function computeColors(model) {
  const result = [];
  const initialValidationRegex = /\b(rgb|rgba|hsl|hsla)(\([0-9\s,.\%]*\))|\s+(#)([A-Fa-f0-9]{6})\b|\s+(#)([A-Fa-f0-9]{8})\b|^(#)([A-Fa-f0-9]{6})\b|^(#)([A-Fa-f0-9]{8})\b/gm;
  const initialValidationMatches = _findMatches(model, initialValidationRegex);
  if (initialValidationMatches.length > 0) {
    for (const initialMatch of initialValidationMatches) {
      const initialCaptureGroups = initialMatch.filter((captureGroup) => captureGroup !== void 0);
      const colorScheme = initialCaptureGroups[1];
      const colorParameters = initialCaptureGroups[2];
      if (!colorParameters) {
        continue;
      }
      let colorInformation;
      if (colorScheme === "rgb") {
        const regexParameters = /^\(\s*(25[0-5]|2[0-4][0-9]|1[0-9]{2}|[1-9][0-9]|[0-9])\s*,\s*(25[0-5]|2[0-4][0-9]|1[0-9]{2}|[1-9][0-9]|[0-9])\s*,\s*(25[0-5]|2[0-4][0-9]|1[0-9]{2}|[1-9][0-9]|[0-9])\s*\)$/gm;
        colorInformation = _findRGBColorInformation(_findRange(model, initialMatch), _findMatches(colorParameters, regexParameters), false);
      } else if (colorScheme === "rgba") {
        const regexParameters = /^\(\s*(25[0-5]|2[0-4][0-9]|1[0-9]{2}|[1-9][0-9]|[0-9])\s*,\s*(25[0-5]|2[0-4][0-9]|1[0-9]{2}|[1-9][0-9]|[0-9])\s*,\s*(25[0-5]|2[0-4][0-9]|1[0-9]{2}|[1-9][0-9]|[0-9])\s*,\s*(0[.][0-9]+|[.][0-9]+|[01][.]|[01])\s*\)$/gm;
        colorInformation = _findRGBColorInformation(_findRange(model, initialMatch), _findMatches(colorParameters, regexParameters), true);
      } else if (colorScheme === "hsl") {
        const regexParameters = /^\(\s*(36[0]|3[0-5][0-9]|[12][0-9][0-9]|[1-9]?[0-9])\s*,\s*(100|\d{1,2}[.]\d*|\d{1,2})%\s*,\s*(100|\d{1,2}[.]\d*|\d{1,2})%\s*\)$/gm;
        colorInformation = _findHSLColorInformation(_findRange(model, initialMatch), _findMatches(colorParameters, regexParameters), false);
      } else if (colorScheme === "hsla") {
        const regexParameters = /^\(\s*(36[0]|3[0-5][0-9]|[12][0-9][0-9]|[1-9]?[0-9])\s*,\s*(100|\d{1,2}[.]\d*|\d{1,2})%\s*,\s*(100|\d{1,2}[.]\d*|\d{1,2})%\s*,\s*(0[.][0-9]+|[.][0-9]+|[01][.]|[01])\s*\)$/gm;
        colorInformation = _findHSLColorInformation(_findRange(model, initialMatch), _findMatches(colorParameters, regexParameters), true);
      } else if (colorScheme === "#") {
        colorInformation = _findHexColorInformation(_findRange(model, initialMatch), colorScheme + colorParameters);
      }
      if (colorInformation) {
        result.push(colorInformation);
      }
    }
  }
  return result;
}
function $y0(model) {
  if (!model || typeof model.getValue !== "function" || typeof model.positionAt !== "function") {
    return [];
  }
  return computeColors(model);
}

// out-build/vs/editor/common/services/findSectionHeaders.js
var markRegex = new RegExp("\\bMARK:\\s*(.*)$", "d");
var trimDashesRegex = /^-+|-+$/g;
function $z0(model, options3) {
  let headers = [];
  if (options3.findRegionSectionHeaders && options3.foldingRules?.markers) {
    const regionHeaders = collectRegionHeaders(model, options3);
    headers = headers.concat(regionHeaders);
  }
  if (options3.findMarkSectionHeaders) {
    const markHeaders = collectMarkHeaders(model);
    headers = headers.concat(markHeaders);
  }
  return headers;
}
function collectRegionHeaders(model, options3) {
  const regionHeaders = [];
  const endLineNumber = model.getLineCount();
  for (let lineNumber = 1; lineNumber <= endLineNumber; lineNumber++) {
    const lineContent = model.getLineContent(lineNumber);
    const match = lineContent.match(options3.foldingRules.markers.start);
    if (match) {
      const range = { startLineNumber: lineNumber, startColumn: match[0].length + 1, endLineNumber: lineNumber, endColumn: lineContent.length + 1 };
      if (range.endColumn > range.startColumn) {
        const sectionHeader = {
          range,
          ...getHeaderText(lineContent.substring(match[0].length)),
          shouldBeInComments: false
        };
        if (sectionHeader.text || sectionHeader.hasSeparatorLine) {
          regionHeaders.push(sectionHeader);
        }
      }
    }
  }
  return regionHeaders;
}
function collectMarkHeaders(model) {
  const markHeaders = [];
  const endLineNumber = model.getLineCount();
  for (let lineNumber = 1; lineNumber <= endLineNumber; lineNumber++) {
    const lineContent = model.getLineContent(lineNumber);
    addMarkHeaderIfFound(lineContent, lineNumber, markHeaders);
  }
  return markHeaders;
}
function addMarkHeaderIfFound(lineContent, lineNumber, sectionHeaders) {
  markRegex.lastIndex = 0;
  const match = markRegex.exec(lineContent);
  if (match) {
    const column = match.indices[1][0] + 1;
    const endColumn = match.indices[1][1] + 1;
    const range = { startLineNumber: lineNumber, startColumn: column, endLineNumber: lineNumber, endColumn };
    if (range.endColumn > range.startColumn) {
      const sectionHeader = {
        range,
        ...getHeaderText(match[1]),
        shouldBeInComments: true
      };
      if (sectionHeader.text || sectionHeader.hasSeparatorLine) {
        sectionHeaders.push(sectionHeader);
      }
    }
  }
}
function getHeaderText(text2) {
  text2 = text2.trim();
  const hasSeparatorLine = text2.startsWith("-");
  text2 = text2.replace(trimDashesRegex, "");
  return { text: text2, hasSeparatorLine };
}

// out-build/vs/editor/common/services/editorSimpleWorker.js
var $F0 = class {
  constructor() {
    this.d = new $D0();
  }
  dispose() {
  }
  f(uri) {
    return this.d.getModel(uri);
  }
  g() {
    return this.d.getModels();
  }
  $acceptNewModel(data) {
    this.d.$acceptNewModel(data);
  }
  $acceptModelChanged(uri, e) {
    this.d.$acceptModelChanged(uri, e);
  }
  $acceptRemovedModel(uri) {
    this.d.$acceptRemovedModel(uri);
  }
  async $computeUnicodeHighlights(url, options3, range) {
    const model = this.f(url);
    if (!model) {
      return { ranges: [], hasMore: false, ambiguousCharacterCount: 0, invisibleCharacterCount: 0, nonBasicAsciiCharacterCount: 0 };
    }
    return $99.computeUnicodeHighlights(model, options3, range);
  }
  async $findSectionHeaders(url, options3) {
    const model = this.f(url);
    if (!model) {
      return [];
    }
    return $z0(model, options3);
  }
  // ---- BEGIN diff --------------------------------------------------------------------------
  async $computeDiff(originalUrl, modifiedUrl, options3, algorithm) {
    const original = this.f(originalUrl);
    const modified = this.f(modifiedUrl);
    if (!original || !modified) {
      return null;
    }
    const result = $G0.h(original, modified, options3, algorithm);
    return result;
  }
  static h(originalTextModel, modifiedTextModel, options3, algorithm) {
    const diffAlgorithm = algorithm === "advanced" ? $x0.getDefault() : $x0.getLegacy();
    const originalLines = originalTextModel.getLinesContent();
    const modifiedLines = modifiedTextModel.getLinesContent();
    const result = diffAlgorithm.computeDiff(originalLines, modifiedLines, options3);
    const identical = result.changes.length > 0 ? false : this.j(originalTextModel, modifiedTextModel);
    function getLineChanges(changes) {
      return changes.map((m) => [m.original.startLineNumber, m.original.endLineNumberExclusive, m.modified.startLineNumber, m.modified.endLineNumberExclusive, m.innerChanges?.map((m2) => [
        m2.originalRange.startLineNumber,
        m2.originalRange.startColumn,
        m2.originalRange.endLineNumber,
        m2.originalRange.endColumn,
        m2.modifiedRange.startLineNumber,
        m2.modifiedRange.startColumn,
        m2.modifiedRange.endLineNumber,
        m2.modifiedRange.endColumn
      ])]);
    }
    return {
      identical,
      quitEarly: result.hitTimeout,
      changes: getLineChanges(result.changes),
      moves: result.moves.map((m) => [
        m.lineRangeMapping.original.startLineNumber,
        m.lineRangeMapping.original.endLineNumberExclusive,
        m.lineRangeMapping.modified.startLineNumber,
        m.lineRangeMapping.modified.endLineNumberExclusive,
        getLineChanges(m.changes)
      ])
    };
  }
  static j(original, modified) {
    const originalLineCount = original.getLineCount();
    const modifiedLineCount = modified.getLineCount();
    if (originalLineCount !== modifiedLineCount) {
      return false;
    }
    for (let line = 1; line <= originalLineCount; line++) {
      const originalLine = original.getLineContent(line);
      const modifiedLine = modified.getLineContent(line);
      if (originalLine !== modifiedLine) {
        return false;
      }
    }
    return true;
  }
  async $computeDirtyDiff(originalUrl, modifiedUrl, ignoreTrimWhitespace) {
    const original = this.f(originalUrl);
    const modified = this.f(modifiedUrl);
    if (!original || !modified) {
      return null;
    }
    const originalLines = original.getLinesContent();
    const modifiedLines = modified.getLinesContent();
    const diffComputer = new $yD(originalLines, modifiedLines, {
      shouldComputeCharChanges: false,
      shouldPostProcessCharChanges: false,
      shouldIgnoreTrimWhitespace: ignoreTrimWhitespace,
      shouldMakePrettyDiff: true,
      maxComputationTime: 1e3
    });
    return diffComputer.computeDiff().changes;
  }
  static {
    this.k = 1e5;
  }
  async $computeMoreMinimalEdits(modelUrl, edits, pretty2) {
    const model = this.f(modelUrl);
    if (!model) {
      return edits;
    }
    const result = [];
    let lastEol = void 0;
    edits = edits.slice(0).sort((a, b) => {
      if (a.range && b.range) {
        return $9C.compareRangesUsingStarts(a.range, b.range);
      }
      const aRng = a.range ? 0 : 1;
      const bRng = b.range ? 0 : 1;
      return aRng - bRng;
    });
    let writeIndex = 0;
    for (let readIndex = 1; readIndex < edits.length; readIndex++) {
      if ($9C.getEndPosition(edits[writeIndex].range).equals($9C.getStartPosition(edits[readIndex].range))) {
        edits[writeIndex].range = $9C.fromPositions($9C.getStartPosition(edits[writeIndex].range), $9C.getEndPosition(edits[readIndex].range));
        edits[writeIndex].text += edits[readIndex].text;
      } else {
        writeIndex++;
        edits[writeIndex] = edits[readIndex];
      }
    }
    edits.length = writeIndex + 1;
    for (let { range, text: text2, eol } of edits) {
      if (typeof eol === "number") {
        lastEol = eol;
      }
      if ($9C.isEmpty(range) && !text2) {
        continue;
      }
      const original = model.getValueInRange(range);
      text2 = text2.replace(/\r\n|\n|\r/g, model.eol);
      if (original === text2) {
        continue;
      }
      if (Math.max(text2.length, original.length) > $G0.k) {
        result.push({ range, text: text2 });
        continue;
      }
      const changes = $6C(original, text2, pretty2);
      const editOffset = model.offsetAt($9C.lift(range).getStartPosition());
      for (const change of changes) {
        const start = model.positionAt(editOffset + change.originalStart);
        const end = model.positionAt(editOffset + change.originalStart + change.originalLength);
        const newEdit = {
          text: text2.substr(change.modifiedStart, change.modifiedLength),
          range: { startLineNumber: start.lineNumber, startColumn: start.column, endLineNumber: end.lineNumber, endColumn: end.column }
        };
        if (model.getValueInRange(newEdit.range) !== newEdit.text) {
          result.push(newEdit);
        }
      }
    }
    if (typeof lastEol === "number") {
      result.push({ eol: lastEol, text: "", range: { startLineNumber: 0, startColumn: 0, endLineNumber: 0, endColumn: 0 } });
    }
    return result;
  }
  $computeHumanReadableDiff(modelUrl, edits, options3) {
    const model = this.f(modelUrl);
    if (!model) {
      return edits;
    }
    const result = [];
    let lastEol = void 0;
    edits = edits.slice(0).sort((a, b) => {
      if (a.range && b.range) {
        return $9C.compareRangesUsingStarts(a.range, b.range);
      }
      const aRng = a.range ? 0 : 1;
      const bRng = b.range ? 0 : 1;
      return aRng - bRng;
    });
    for (let { range, text: text2, eol } of edits) {
      let addPositions2 = function(pos1, pos2) {
        return new $8C(pos1.lineNumber + pos2.lineNumber - 1, pos2.lineNumber === 1 ? pos1.column + pos2.column - 1 : pos2.column);
      }, getText2 = function(lines, range2) {
        const result2 = [];
        for (let i2 = range2.startLineNumber; i2 <= range2.endLineNumber; i2++) {
          const line = lines[i2 - 1];
          if (i2 === range2.startLineNumber && i2 === range2.endLineNumber) {
            result2.push(line.substring(range2.startColumn - 1, range2.endColumn - 1));
          } else if (i2 === range2.startLineNumber) {
            result2.push(line.substring(range2.startColumn - 1));
          } else if (i2 === range2.endLineNumber) {
            result2.push(line.substring(0, range2.endColumn - 1));
          } else {
            result2.push(line);
          }
        }
        return result2;
      };
      var addPositions = addPositions2, getText = getText2;
      if (typeof eol === "number") {
        lastEol = eol;
      }
      if ($9C.isEmpty(range) && !text2) {
        continue;
      }
      const original = model.getValueInRange(range);
      text2 = text2.replace(/\r\n|\n|\r/g, model.eol);
      if (original === text2) {
        continue;
      }
      if (Math.max(text2.length, original.length) > $G0.k) {
        result.push({ range, text: text2 });
        continue;
      }
      const originalLines = original.split(/\r\n|\n|\r/);
      const modifiedLines = text2.split(/\r\n|\n|\r/);
      const diff3 = $x0.getDefault().computeDiff(originalLines, modifiedLines, options3);
      const start = $9C.lift(range).getStartPosition();
      for (const c of diff3.changes) {
        if (c.innerChanges) {
          for (const x of c.innerChanges) {
            result.push({
              range: $9C.fromPositions(addPositions2(start, x.originalRange.getStartPosition()), addPositions2(start, x.originalRange.getEndPosition())),
              text: getText2(modifiedLines, x.modifiedRange).join(model.eol)
            });
          }
        } else {
          throw new $vb("The experimental diff algorithm always produces inner changes");
        }
      }
    }
    if (typeof lastEol === "number") {
      result.push({ eol: lastEol, text: "", range: { startLineNumber: 0, startColumn: 0, endLineNumber: 0, endColumn: 0 } });
    }
    return result;
  }
  // ---- END minimal edits ---------------------------------------------------------------
  async $computeLinks(modelUrl) {
    const model = this.f(modelUrl);
    if (!model) {
      return null;
    }
    return $_9(model);
  }
  // --- BEGIN default document colors -----------------------------------------------------------
  async $computeDefaultDocumentColors(modelUrl) {
    const model = this.f(modelUrl);
    if (!model) {
      return null;
    }
    return $y0(model);
  }
  static {
    this.l = 1e4;
  }
  async $textualSuggest(modelUrls, leadingWord, wordDef, wordDefFlags) {
    const sw = new $te();
    const wordDefRegExp = new RegExp(wordDef, wordDefFlags);
    const seen = /* @__PURE__ */ new Set();
    outer: for (const url of modelUrls) {
      const model = this.f(url);
      if (!model) {
        continue;
      }
      for (const word of model.words(wordDefRegExp)) {
        if (word === leadingWord || !isNaN(Number(word))) {
          continue;
        }
        seen.add(word);
        if (seen.size > $G0.l) {
          break outer;
        }
      }
    }
    return { words: Array.from(seen), duration: sw.elapsed() };
  }
  // ---- END suggest --------------------------------------------------------------------------
  //#region -- word ranges --
  async $computeWordRanges(modelUrl, range, wordDef, wordDefFlags) {
    const model = this.f(modelUrl);
    if (!model) {
      return /* @__PURE__ */ Object.create(null);
    }
    const wordDefRegExp = new RegExp(wordDef, wordDefFlags);
    const result = /* @__PURE__ */ Object.create(null);
    for (let line = range.startLineNumber; line < range.endLineNumber; line++) {
      const words = model.getLineWords(line, wordDefRegExp);
      for (const word of words) {
        if (!isNaN(Number(word.word))) {
          continue;
        }
        let array2 = result[word.word];
        if (!array2) {
          array2 = [];
          result[word.word] = array2;
        }
        array2.push({
          startLineNumber: line,
          startColumn: word.startColumn,
          endLineNumber: line,
          endColumn: word.endColumn
        });
      }
    }
    return result;
  }
  //#endregion
  async $navigateValueSet(modelUrl, range, up, wordDef, wordDefFlags) {
    const model = this.f(modelUrl);
    if (!model) {
      return null;
    }
    const wordDefRegExp = new RegExp(wordDef, wordDefFlags);
    if (range.startColumn === range.endColumn) {
      range = {
        startLineNumber: range.startLineNumber,
        startColumn: range.startColumn,
        endLineNumber: range.endLineNumber,
        endColumn: range.endColumn + 1
      };
    }
    const selectionText = model.getValueInRange(range);
    const wordRange = model.getWordAtPosition({ lineNumber: range.startLineNumber, column: range.startColumn }, wordDefRegExp);
    if (!wordRange) {
      return null;
    }
    const word = model.getValueInRange(wordRange);
    const result = $a0.INSTANCE.navigateValueSet(range, selectionText, wordRange, word, up);
    return result;
  }
};
var $G0 = class extends $F0 {
  constructor(o, p) {
    super();
    this.o = o;
    this.p = p;
    this.n = null;
  }
  async $ping() {
    return "pong";
  }
  // ---- BEGIN foreign module support --------------------------------------------------------------------------
  $loadForeignModule(moduleId, createData, foreignHostMethods) {
    const proxyMethodRequest = (method, args2) => {
      return this.o.$fhr(method, args2);
    };
    const foreignHost = $Wv(foreignHostMethods, proxyMethodRequest);
    const ctx = {
      host: foreignHost,
      getMirrorModels: () => {
        return this.g();
      }
    };
    if (this.p) {
      this.n = this.p(ctx, createData);
      return Promise.resolve($Vv(this.n));
    }
    return new Promise((resolve, reject) => {
      const onModuleCallback = (foreignModule) => {
        this.n = foreignModule.create(ctx, createData);
        resolve($Vv(this.n));
      };
      const url = $ih.asBrowserUri(`${moduleId}.js`).toString(true);
      import(`${url}`).then(onModuleCallback).catch(reject);
    });
  }
  // foreign method request
  $fmr(method, args2) {
    if (!this.n || typeof this.n[method] !== "function") {
      return Promise.reject(new Error("Missing requestHandler or method: " + method));
    }
    try {
      return Promise.resolve(this.n[method].apply(this.n, args2));
    } catch (e) {
      return Promise.reject(e);
    }
  }
};
if (typeof importScripts === "function") {
  globalThis.monaco = $c0();
}

// out-build/vs/editor/browser/services/editorWorkerService.js
var STOP_WORKER_DELTA_TIME_MS = 5 * 60 * 1e3;
function canSyncModel(modelService, resource) {
  const model = modelService.getModel(resource);
  if (!model) {
    return false;
  }
  if (model.isTooLargeForSyncing()) {
    return false;
  }
  return true;
}
var $vYb = class $vYb2 extends $3c {
  constructor(workerDescriptor, modelService, configurationService, logService, g, languageFeaturesService) {
    super();
    this.g = g;
    this.a = modelService;
    this.b = this.B(new WorkerManager(workerDescriptor, this.a));
    this.f = logService;
    this.B(languageFeaturesService.linkProvider.register({ language: "*", hasAccessToAllModels: true }, {
      provideLinks: async (model, token) => {
        if (!canSyncModel(this.a, model.uri)) {
          return Promise.resolve({ links: [] });
        }
        const worker = await this.h([model.uri]);
        const links = await worker.$computeLinks(model.uri.toString());
        return links && { links };
      }
    }));
    this.B(languageFeaturesService.completionProvider.register("*", new WordBasedCompletionItemProvider(this.b, configurationService, this.a, this.g)));
  }
  dispose() {
    super.dispose();
  }
  canComputeUnicodeHighlights(uri) {
    return canSyncModel(this.a, uri);
  }
  async computedUnicodeHighlights(uri, options3, range) {
    const worker = await this.h([uri]);
    return worker.$computeUnicodeHighlights(uri.toString(), options3, range);
  }
  async computeDiff(original, modified, options3, algorithm) {
    const worker = await this.h(
      [original, modified],
      /* forceLargeModels */
      true
    );
    const result = await worker.$computeDiff(original.toString(), modified.toString(), options3, algorithm);
    if (!result) {
      return null;
    }
    const diff3 = {
      identical: result.identical,
      quitEarly: result.quitEarly,
      changes: toLineRangeMappings(result.changes),
      moves: result.moves.map((m) => new $wD(new $pD(new $_C(m[0], m[1]), new $_C(m[2], m[3])), toLineRangeMappings(m[4])))
    };
    return diff3;
    function toLineRangeMappings(changes) {
      return changes.map((c) => new $qD(new $_C(c[0], c[1]), new $_C(c[2], c[3]), c[4]?.map((c2) => new $rD(new $9C(c2[0], c2[1], c2[2], c2[3]), new $9C(c2[4], c2[5], c2[6], c2[7])))));
    }
  }
  canComputeDirtyDiff(original, modified) {
    return canSyncModel(this.a, original) && canSyncModel(this.a, modified);
  }
  async computeDirtyDiff(original, modified, ignoreTrimWhitespace) {
    const worker = await this.h([original, modified]);
    return worker.$computeDirtyDiff(original.toString(), modified.toString(), ignoreTrimWhitespace);
  }
  async computeMoreMinimalEdits(resource, edits, pretty2 = false) {
    if ($Qb(edits)) {
      if (!canSyncModel(this.a, resource)) {
        return Promise.resolve(edits);
      }
      const sw = $te.create();
      const result = this.h([resource]).then((worker) => worker.$computeMoreMinimalEdits(resource.toString(), edits, pretty2));
      result.finally(() => this.f.trace("FORMAT#computeMoreMinimalEdits", resource.toString(true), sw.elapsed()));
      return Promise.race([result, $Wh(1e3).then(() => edits)]);
    } else {
      return Promise.resolve(void 0);
    }
  }
  computeHumanReadableDiff(resource, edits) {
    if ($Qb(edits)) {
      if (!canSyncModel(this.a, resource)) {
        return Promise.resolve(edits);
      }
      const sw = $te.create();
      const opts = { ignoreTrimWhitespace: false, maxComputationTimeMs: 1e3, computeMoves: false };
      const result = this.h([resource]).then((worker) => worker.$computeHumanReadableDiff(resource.toString(), edits, opts)).catch((err) => {
        $gb(err);
        return this.computeMoreMinimalEdits(resource, edits, true);
      });
      result.finally(() => this.f.trace("FORMAT#computeHumanReadableDiff", resource.toString(true), sw.elapsed()));
      return result;
    } else {
      return Promise.resolve(void 0);
    }
  }
  canNavigateValueSet(resource) {
    return canSyncModel(this.a, resource);
  }
  async navigateValueSet(resource, range, up) {
    const model = this.a.getModel(resource);
    if (!model) {
      return null;
    }
    const wordDefRegExp = this.g.getLanguageConfiguration(model.getLanguageId()).getWordDefinition();
    const wordDef = wordDefRegExp.source;
    const wordDefFlags = wordDefRegExp.flags;
    const worker = await this.h([resource]);
    return worker.$navigateValueSet(resource.toString(), range, up, wordDef, wordDefFlags);
  }
  canComputeWordRanges(resource) {
    return canSyncModel(this.a, resource);
  }
  async computeWordRanges(resource, range) {
    const model = this.a.getModel(resource);
    if (!model) {
      return Promise.resolve(null);
    }
    const wordDefRegExp = this.g.getLanguageConfiguration(model.getLanguageId()).getWordDefinition();
    const wordDef = wordDefRegExp.source;
    const wordDefFlags = wordDefRegExp.flags;
    const worker = await this.h([resource]);
    return worker.$computeWordRanges(resource.toString(), range, wordDef, wordDefFlags);
  }
  async findSectionHeaders(uri, options3) {
    const worker = await this.h([uri]);
    return worker.$findSectionHeaders(uri.toString(), options3);
  }
  async computeDefaultDocumentColors(uri) {
    const worker = await this.h([uri]);
    return worker.$computeDefaultDocumentColors(uri.toString());
  }
  async h(resources, forceLargeModels = false) {
    const worker = await this.b.withWorker();
    return await worker.workerWithSyncedResources(resources, forceLargeModels);
  }
};
$vYb = __decorate([
  __param(1, $sG),
  __param(2, $zG),
  __param(3, $wn),
  __param(4, $NF),
  __param(5, $mP)
], $vYb);
var WordBasedCompletionItemProvider = class {
  constructor(workerManager, configurationService, modelService, e) {
    this.e = e;
    this._debugDisplayName = "wordbasedCompletions";
    this.a = workerManager;
    this.b = configurationService;
    this.d = modelService;
  }
  async provideCompletionItems(model, position) {
    const config = this.b.getValue(model.uri, position, "editor");
    if (config.wordBasedSuggestions === "off") {
      return void 0;
    }
    const models = [];
    if (config.wordBasedSuggestions === "currentDocument") {
      if (canSyncModel(this.d, model.uri)) {
        models.push(model.uri);
      }
    } else {
      for (const candidate of this.d.getModels()) {
        if (!canSyncModel(this.d, candidate.uri)) {
          continue;
        }
        if (candidate === model) {
          models.unshift(candidate.uri);
        } else if (config.wordBasedSuggestions === "allDocuments" || candidate.getLanguageId() === model.getLanguageId()) {
          models.push(candidate.uri);
        }
      }
    }
    if (models.length === 0) {
      return void 0;
    }
    const wordDefRegExp = this.e.getLanguageConfiguration(model.getLanguageId()).getWordDefinition();
    const word = model.getWordAtPosition(position);
    const replace = !word ? $9C.fromPositions(position) : new $9C(position.lineNumber, word.startColumn, position.lineNumber, word.endColumn);
    const insert = replace.setEndPosition(position.lineNumber, position.column);
    const client = await this.a.withWorker();
    const data = await client.textualSuggest(models, word?.word, wordDefRegExp);
    if (!data) {
      return void 0;
    }
    return {
      duration: data.duration,
      suggestions: data.words.map((word2) => {
        return {
          kind: 18,
          label: word2,
          insertText: word2,
          range: { insert, replace }
        };
      })
    };
  }
};
var WorkerManager = class WorkerManager2 extends $3c {
  constructor(g, modelService) {
    super();
    this.g = g;
    this.a = modelService;
    this.b = null;
    this.f = (/* @__PURE__ */ new Date()).getTime();
    const stopWorkerInterval = this.B(new $lj());
    stopWorkerInterval.cancelAndSet(() => this.j(), Math.round(STOP_WORKER_DELTA_TIME_MS / 2), $Y);
    this.B(this.a.onModelRemoved((_) => this.h()));
  }
  dispose() {
    if (this.b) {
      this.b.dispose();
      this.b = null;
    }
    super.dispose();
  }
  /**
   * Check if the model service has no more models and stop the worker if that is the case.
   */
  h() {
    if (!this.b) {
      return;
    }
    const models = this.a.getModels();
    if (models.length === 0) {
      this.b.dispose();
      this.b = null;
    }
  }
  /**
   * Check if the worker has been idle for a while and then stop it.
   */
  j() {
    if (!this.b) {
      return;
    }
    const timeSinceLastWorkerUsedTime = (/* @__PURE__ */ new Date()).getTime() - this.f;
    if (timeSinceLastWorkerUsedTime > STOP_WORKER_DELTA_TIME_MS) {
      this.b.dispose();
      this.b = null;
    }
  }
  withWorker() {
    this.f = (/* @__PURE__ */ new Date()).getTime();
    if (!this.b) {
      this.b = new $wYb(this.g, false, this.a);
    }
    return Promise.resolve(this.b);
  }
};
WorkerManager = __decorate([
  __param(1, $sG)
], WorkerManager);
var SynchronousWorkerClient = class {
  constructor(instance2) {
    this.a = instance2;
    this.proxy = this.a;
  }
  dispose() {
    this.a.dispose();
  }
  setChannel(channel, handler) {
    throw new Error(`Not supported`);
  }
  getChannel(channel) {
    throw new Error(`Not supported`);
  }
};
var $wYb = class $wYb2 extends $3c {
  constructor(j, keepIdleModels, modelService) {
    super();
    this.j = j;
    this.h = false;
    this.a = modelService;
    this.b = keepIdleModels;
    this.f = null;
    this.g = null;
  }
  // foreign host request
  fhr(method, args2) {
    throw new Error(`Not implemented!`);
  }
  n() {
    if (!this.f) {
      try {
        this.f = this.B($412(this.j));
        $d0.setChannel(this.f, this.u());
      } catch (err) {
        $X1(err);
        this.f = this.t();
      }
    }
    return this.f;
  }
  async s() {
    try {
      const proxy = this.n().proxy;
      await proxy.$ping();
      return proxy;
    } catch (err) {
      $X1(err);
      this.f = this.t();
      return this.f.proxy;
    }
  }
  t() {
    return new SynchronousWorkerClient(new $G0(this.u(), null));
  }
  u() {
    return {
      $fhr: (method, args2) => this.fhr(method, args2)
    };
  }
  w(proxy) {
    if (!this.g) {
      this.g = this.B(new $C0(proxy, this.a, this.b));
    }
    return this.g;
  }
  async workerWithSyncedResources(resources, forceLargeModels = false) {
    if (this.h) {
      return Promise.reject($mb());
    }
    const proxy = await this.s();
    this.w(proxy).ensureSyncedResources(resources, forceLargeModels);
    return proxy;
  }
  async textualSuggest(resources, leadingWord, wordDefRegExp) {
    const proxy = await this.workerWithSyncedResources(resources);
    const wordDef = wordDefRegExp.source;
    const wordDefFlags = wordDefRegExp.flags;
    return proxy.$textualSuggest(resources.map((r2) => r2.toString()), leadingWord, wordDef, wordDefFlags);
  }
  dispose() {
    super.dispose();
    this.h = true;
  }
};
$wYb = __decorate([
  __param(2, $sG)
], $wYb);

// out-build/vs/workbench/contrib/codeEditor/browser/workbenchEditorWorkerService.js
var $xYb = class $xYb2 extends $vYb {
  constructor(modelService, configurationService, logService, languageConfigurationService, languageFeaturesService) {
    const workerDescriptor = new $312("vs/editor/common/services/editorSimpleWorker", "TextEditorWorker");
    super(workerDescriptor, modelService, configurationService, logService, languageConfigurationService, languageFeaturesService);
  }
};
$xYb = __decorate([
  __param(0, $sG),
  __param(1, $zG),
  __param(2, $wn),
  __param(3, $NF),
  __param(4, $mP)
], $xYb);

// out-build/vs/editor/common/services/markerDecorationsService.js
var $yYb = class $yYb2 extends $3c {
  constructor(modelService, f) {
    super();
    this.f = f;
    this.a = this.B(new $ze());
    this.onDidChangeMarker = this.a.event;
    this.b = new $Ec();
    this.c = new $Ec();
    modelService.getModels().forEach((model) => this.h(model));
    this.B(modelService.onModelAdded(this.h, this));
    this.B(modelService.onModelRemoved(this.j, this));
    this.B(this.f.onMarkerChanged(this.g, this));
  }
  dispose() {
    super.dispose();
    this.c.forEach((value) => value.dispose());
    this.c.clear();
  }
  getMarker(uri, decoration3) {
    const markerDecorations = this.c.get(uri);
    return markerDecorations ? markerDecorations.getMarker(decoration3) || null : null;
  }
  getLiveMarkers(uri) {
    const markerDecorations = this.c.get(uri);
    return markerDecorations ? markerDecorations.getMarkers() : [];
  }
  addMarkerSuppression(uri, range) {
    let suppressedRanges = this.b.get(uri);
    if (!suppressedRanges) {
      suppressedRanges = /* @__PURE__ */ new Set();
      this.b.set(uri, suppressedRanges);
    }
    suppressedRanges.add(range);
    this.g([uri]);
    return $1c(() => {
      const suppressedRanges2 = this.b.get(uri);
      if (suppressedRanges2) {
        suppressedRanges2.delete(range);
        if (suppressedRanges2.size === 0) {
          this.b.delete(uri);
        }
        this.g([uri]);
      }
    });
  }
  g(changedResources) {
    changedResources.forEach((resource) => {
      const markerDecorations = this.c.get(resource);
      if (markerDecorations) {
        this.m(markerDecorations);
      }
    });
  }
  h(model) {
    const markerDecorations = new MarkerDecorations(model);
    this.c.set(model.uri, markerDecorations);
    this.m(markerDecorations);
  }
  j(model) {
    const markerDecorations = this.c.get(model.uri);
    if (markerDecorations) {
      markerDecorations.dispose();
      this.c.delete(model.uri);
    }
    if (model.uri.scheme === Schemas.inMemory || model.uri.scheme === Schemas.internal || model.uri.scheme === Schemas.vscode) {
      this.f?.read({ resource: model.uri }).map((marker) => marker.owner).forEach((owner) => this.f.remove(owner, [model.uri]));
    }
  }
  m(markerDecorations) {
    let markers = this.f.read({ resource: markerDecorations.model.uri, take: 500 });
    const suppressedRanges = this.b.get(markerDecorations.model.uri);
    if (suppressedRanges) {
      markers = markers.filter((marker) => {
        return !Iterable.some(suppressedRanges, (candidate) => $9C.areIntersectingOrTouching(candidate, marker));
      });
    }
    if (markerDecorations.update(markers)) {
      this.a.fire(markerDecorations.model);
    }
  }
};
$yYb = __decorate([
  __param(0, $sG),
  __param(1, $DE)
], $yYb);
var MarkerDecorations = class extends $3c {
  constructor(model) {
    super();
    this.model = model;
    this.a = new $Kc();
    this.B($1c(() => {
      this.model.deltaDecorations([...this.a.values()], []);
      this.a.clear();
    }));
  }
  update(markers) {
    const { added, removed } = $b(new Set(this.a.keys()), new Set(markers));
    if (added.length === 0 && removed.length === 0) {
      return false;
    }
    const oldIds = removed.map((marker) => this.a.get(marker));
    const newDecorations = added.map((marker) => {
      return {
        range: this.b(this.model, marker),
        options: this.c(marker)
      };
    });
    const ids = this.model.deltaDecorations(oldIds, newDecorations);
    for (const removedMarker of removed) {
      this.a.delete(removedMarker);
    }
    for (let index = 0; index < ids.length; index++) {
      this.a.set(added[index], ids[index]);
    }
    return true;
  }
  getMarker(decoration3) {
    return this.a.getKey(decoration3.id);
  }
  getMarkers() {
    const res = [];
    this.a.forEach((id2, marker) => {
      const range = this.model.getDecorationRange(id2);
      if (range) {
        res.push([range, marker]);
      }
    });
    return res;
  }
  b(model, rawMarker) {
    let ret = $9C.lift(rawMarker);
    if (rawMarker.severity === MarkerSeverity.Hint && !this.f(
      rawMarker,
      1
      /* MarkerTag.Unnecessary */
    ) && !this.f(
      rawMarker,
      2
      /* MarkerTag.Deprecated */
    )) {
      ret = ret.setEndPosition(ret.startLineNumber, ret.startColumn + 2);
    }
    ret = model.validateRange(ret);
    if (ret.isEmpty()) {
      const maxColumn = model.getLineLastNonWhitespaceColumn(ret.startLineNumber) || model.getLineMaxColumn(ret.startLineNumber);
      if (maxColumn === 1 || ret.endColumn >= maxColumn) {
        return ret;
      }
      const word = model.getWordAtPosition(ret.getStartPosition());
      if (word) {
        ret = new $9C(ret.startLineNumber, word.startColumn, ret.endLineNumber, word.endColumn);
      }
    } else if (rawMarker.endColumn === Number.MAX_VALUE && rawMarker.startColumn === 1 && ret.startLineNumber === ret.endLineNumber) {
      const minColumn = model.getLineFirstNonWhitespaceColumn(rawMarker.startLineNumber);
      if (minColumn < ret.endColumn) {
        ret = new $9C(ret.startLineNumber, minColumn, ret.endLineNumber, ret.endColumn);
        rawMarker.startColumn = minColumn;
      }
    }
    return ret;
  }
  c(marker) {
    let className;
    let color2 = void 0;
    let zIndex;
    let inlineClassName = void 0;
    let minimap;
    switch (marker.severity) {
      case MarkerSeverity.Hint:
        if (this.f(
          marker,
          2
          /* MarkerTag.Deprecated */
        )) {
          className = void 0;
        } else if (this.f(
          marker,
          1
          /* MarkerTag.Unnecessary */
        )) {
          className = "squiggly-unnecessary";
        } else {
          className = "squiggly-hint";
        }
        zIndex = 0;
        break;
      case MarkerSeverity.Info:
        className = "squiggly-info";
        color2 = $hs($sH);
        zIndex = 10;
        minimap = {
          color: $hs($hq),
          position: 1
          /* MinimapPosition.Inline */
        };
        break;
      case MarkerSeverity.Warning:
        className = "squiggly-warning";
        color2 = $hs($rH);
        zIndex = 20;
        minimap = {
          color: $hs($iq),
          position: 1
          /* MinimapPosition.Inline */
        };
        break;
      case MarkerSeverity.Error:
      default:
        className = "squiggly-error";
        color2 = $hs($qH);
        zIndex = 30;
        minimap = {
          color: $hs($jq),
          position: 1
          /* MinimapPosition.Inline */
        };
        break;
    }
    if (marker.tags) {
      if (marker.tags.indexOf(
        1
        /* MarkerTag.Unnecessary */
      ) !== -1) {
        inlineClassName = "squiggly-inline-unnecessary";
      }
      if (marker.tags.indexOf(
        2
        /* MarkerTag.Deprecated */
      ) !== -1) {
        inlineClassName = "squiggly-inline-deprecated";
      }
    }
    return {
      description: "marker-decoration",
      stickiness: 1,
      className,
      showIfCollapsed: true,
      overviewRuler: {
        color: color2,
        position: OverviewRulerLane.Right
      },
      minimap,
      zIndex,
      inlineClassName
    };
  }
  f(marker, tag2) {
    if (marker.tags) {
      return marker.tags.indexOf(tag2) >= 0;
    }
    return false;
  }
};

// out-build/vs/platform/markers/common/markerService.js
var $zYb = /* @__PURE__ */ new Set([
  Schemas.inMemory,
  Schemas.vscodeSourceControl,
  Schemas.walkThrough,
  Schemas.walkThroughSnippet,
  Schemas.vscodeChatCodeBlock
]);
var DoubleResourceMap = class {
  constructor() {
    this.a = new $Ec();
    this.b = /* @__PURE__ */ new Map();
  }
  set(resource, owner, value) {
    let ownerMap = this.a.get(resource);
    if (!ownerMap) {
      ownerMap = /* @__PURE__ */ new Map();
      this.a.set(resource, ownerMap);
    }
    ownerMap.set(owner, value);
    let resourceMap = this.b.get(owner);
    if (!resourceMap) {
      resourceMap = new $Ec();
      this.b.set(owner, resourceMap);
    }
    resourceMap.set(resource, value);
  }
  get(resource, owner) {
    const ownerMap = this.a.get(resource);
    return ownerMap?.get(owner);
  }
  delete(resource, owner) {
    let removedA = false;
    let removedB = false;
    const ownerMap = this.a.get(resource);
    if (ownerMap) {
      removedA = ownerMap.delete(owner);
    }
    const resourceMap = this.b.get(owner);
    if (resourceMap) {
      removedB = resourceMap.delete(resource);
    }
    if (removedA !== removedB) {
      throw new Error("illegal state");
    }
    return removedA && removedB;
  }
  values(key2) {
    if (typeof key2 === "string") {
      return this.b.get(key2)?.values() ?? Iterable.empty();
    }
    if (URI.isUri(key2)) {
      return this.a.get(key2)?.values() ?? Iterable.empty();
    }
    return Iterable.map(Iterable.concat(...this.b.values()), (map) => map[1]);
  }
};
var MarkerStats = class {
  constructor(service) {
    this.errors = 0;
    this.infos = 0;
    this.warnings = 0;
    this.unknowns = 0;
    this.a = new $Ec();
    this.b = service;
    this.c = service.onMarkerChanged(this.d, this);
  }
  dispose() {
    this.c.dispose();
  }
  d(resources) {
    for (const resource of resources) {
      const oldStats = this.a.get(resource);
      if (oldStats) {
        this.f(oldStats);
      }
      const newStats = this.e(resource);
      this.g(newStats);
      this.a.set(resource, newStats);
    }
  }
  e(resource) {
    const result = { errors: 0, warnings: 0, infos: 0, unknowns: 0 };
    if ($zYb.has(resource.scheme)) {
      return result;
    }
    for (const { severity } of this.b.read({ resource })) {
      if (severity === MarkerSeverity.Error) {
        result.errors += 1;
      } else if (severity === MarkerSeverity.Warning) {
        result.warnings += 1;
      } else if (severity === MarkerSeverity.Info) {
        result.infos += 1;
      } else {
        result.unknowns += 1;
      }
    }
    return result;
  }
  f(op) {
    this.errors -= op.errors;
    this.warnings -= op.warnings;
    this.infos -= op.infos;
    this.unknowns -= op.unknowns;
  }
  g(op) {
    this.errors += op.errors;
    this.warnings += op.warnings;
    this.infos += op.infos;
    this.unknowns += op.unknowns;
  }
};
var $AYb = class _$AYb {
  constructor() {
    this.a = new $De({
      delay: 0,
      merge: _$AYb.f
    });
    this.onMarkerChanged = this.a.event;
    this.b = new DoubleResourceMap();
    this.c = new MarkerStats(this);
  }
  dispose() {
    this.c.dispose();
    this.a.dispose();
  }
  getStatistics() {
    return this.c;
  }
  remove(owner, resources) {
    for (const resource of resources || []) {
      this.changeOne(owner, resource, []);
    }
  }
  changeOne(owner, resource, markerData) {
    if ($Pb(markerData)) {
      const removed = this.b.delete(resource, owner);
      if (removed) {
        this.a.fire([resource]);
      }
    } else {
      const markers = [];
      for (const data of markerData) {
        const marker = _$AYb.d(owner, resource, data);
        if (marker) {
          markers.push(marker);
        }
      }
      this.b.set(resource, owner, markers);
      this.a.fire([resource]);
    }
  }
  static d(owner, resource, data) {
    let { code, severity, message, source, startLineNumber, startColumn, endLineNumber, endColumn, relatedInformation, tags } = data;
    if (!message) {
      return void 0;
    }
    startLineNumber = startLineNumber > 0 ? startLineNumber : 1;
    startColumn = startColumn > 0 ? startColumn : 1;
    endLineNumber = endLineNumber >= startLineNumber ? endLineNumber : startLineNumber;
    endColumn = endColumn > 0 ? endColumn : startColumn;
    return {
      resource,
      owner,
      code,
      severity,
      message,
      source,
      startLineNumber,
      startColumn,
      endLineNumber,
      endColumn,
      relatedInformation,
      tags
    };
  }
  changeAll(owner, data) {
    const changes = [];
    const existing = this.b.values(owner);
    if (existing) {
      for (const data2 of existing) {
        const first = Iterable.first(data2);
        if (first) {
          changes.push(first.resource);
          this.b.delete(first.resource, owner);
        }
      }
    }
    if ($Qb(data)) {
      const groups = new $Ec();
      for (const { resource, marker: markerData } of data) {
        const marker = _$AYb.d(owner, resource, markerData);
        if (!marker) {
          continue;
        }
        const array2 = groups.get(resource);
        if (!array2) {
          groups.set(resource, [marker]);
          changes.push(resource);
        } else {
          array2.push(marker);
        }
      }
      for (const [resource, value] of groups) {
        this.b.set(resource, owner, value);
      }
    }
    if (changes.length > 0) {
      this.a.fire(changes);
    }
  }
  read(filter = /* @__PURE__ */ Object.create(null)) {
    let { owner, resource, severities, take } = filter;
    if (!take || take < 0) {
      take = -1;
    }
    if (owner && resource) {
      const data = this.b.get(resource, owner);
      if (!data) {
        return [];
      } else {
        const result = [];
        for (const marker of data) {
          if (_$AYb.e(marker, severities)) {
            const newLen = result.push(marker);
            if (take > 0 && newLen === take) {
              break;
            }
          }
        }
        return result;
      }
    } else if (!owner && !resource) {
      const result = [];
      for (const markers of this.b.values()) {
        for (const data of markers) {
          if (_$AYb.e(data, severities)) {
            const newLen = result.push(data);
            if (take > 0 && newLen === take) {
              return result;
            }
          }
        }
      }
      return result;
    } else {
      const iterable = this.b.values(resource ?? owner);
      const result = [];
      for (const markers of iterable) {
        for (const data of markers) {
          if (_$AYb.e(data, severities)) {
            const newLen = result.push(data);
            if (take > 0 && newLen === take) {
              return result;
            }
          }
        }
      }
      return result;
    }
  }
  static e(marker, severities) {
    return severities === void 0 || (severities & marker.severity) === marker.severity;
  }
  // --- event debounce logic
  static f(all) {
    const set = new $Ec();
    for (const array2 of all) {
      for (const item of array2) {
        set.set(item, true);
      }
    }
    return Array.from(set.keys());
  }
};

// out-build/vs/platform/contextkey/browser/contextKeyService.js
var KEYBINDING_CONTEXT_ATTR = "data-keybinding-context";
var $_Tb = class {
  constructor(id2, parent) {
    this.f = id2;
    this.c = parent;
    this.d = /* @__PURE__ */ Object.create(null);
    this.d["_contextId"] = id2;
  }
  get value() {
    return { ...this.d };
  }
  setValue(key2, value) {
    if (this.d[key2] !== value) {
      this.d[key2] = value;
      return true;
    }
    return false;
  }
  removeValue(key2) {
    if (key2 in this.d) {
      delete this.d[key2];
      return true;
    }
    return false;
  }
  getValue(key2) {
    const ret = this.d[key2];
    if (typeof ret === "undefined" && this.c) {
      return this.c.getValue(key2);
    }
    return ret;
  }
  updateParent(parent) {
    this.c = parent;
  }
  collectAllValues() {
    let result = this.c ? this.c.collectAllValues() : /* @__PURE__ */ Object.create(null);
    result = { ...result, ...this.d };
    delete result["_contextId"];
    return result;
  }
};
var NullContext = class _NullContext extends $_Tb {
  static {
    this.INSTANCE = new _NullContext();
  }
  constructor() {
    super(-1, null);
  }
  setValue(key2, value) {
    return false;
  }
  removeValue(key2) {
    return false;
  }
  getValue(key2) {
    return void 0;
  }
  collectAllValues() {
    return /* @__PURE__ */ Object.create(null);
  }
};
var ConfigAwareContextValuesContainer = class _ConfigAwareContextValuesContainer extends $_Tb {
  static {
    this.g = "config.";
  }
  constructor(id2, j, emitter) {
    super(id2, null);
    this.j = j;
    this.h = $Wk.forConfigKeys();
    this.i = this.j.onDidChangeConfiguration((event) => {
      if (event.source === 7) {
        const allKeys = Array.from(this.h, ([k]) => k);
        this.h.clear();
        emitter.fire(new ArrayContextKeyChangeEvent(allKeys));
      } else {
        const changedKeys = [];
        for (const configKey of event.affectedKeys) {
          const contextKey = `config.${configKey}`;
          const cachedItems = this.h.findSuperstr(contextKey);
          if (cachedItems !== void 0) {
            changedKeys.push(...Iterable.map(cachedItems, ([key2]) => key2));
            this.h.deleteSuperstr(contextKey);
          }
          if (this.h.has(contextKey)) {
            changedKeys.push(contextKey);
            this.h.delete(contextKey);
          }
        }
        emitter.fire(new ArrayContextKeyChangeEvent(changedKeys));
      }
    });
  }
  dispose() {
    this.i.dispose();
  }
  getValue(key2) {
    if (key2.indexOf(_ConfigAwareContextValuesContainer.g) !== 0) {
      return super.getValue(key2);
    }
    if (this.h.has(key2)) {
      return this.h.get(key2);
    }
    const configKey = key2.substr(_ConfigAwareContextValuesContainer.g.length);
    const configValue = this.j.getValue(configKey);
    let value = void 0;
    switch (typeof configValue) {
      case "number":
      case "boolean":
      case "string":
        value = configValue;
        break;
      default:
        if (Array.isArray(configValue)) {
          value = JSON.stringify(configValue);
        } else {
          value = configValue;
        }
    }
    this.h.set(key2, value);
    return value;
  }
  setValue(key2, value) {
    return super.setValue(key2, value);
  }
  removeValue(key2) {
    return super.removeValue(key2);
  }
  collectAllValues() {
    const result = /* @__PURE__ */ Object.create(null);
    this.h.forEach((value, index) => result[index] = value);
    return { ...result, ...super.collectAllValues() };
  }
};
var ContextKey = class {
  constructor(service, key2, defaultValue) {
    this.c = service;
    this.d = key2;
    this.f = defaultValue;
    this.reset();
  }
  set(value) {
    this.c.setContext(this.d, value);
  }
  reset() {
    if (typeof this.f === "undefined") {
      this.c.removeContext(this.d);
    } else {
      this.c.setContext(this.d, this.f);
    }
  }
  get() {
    return this.c.getContextKeyValue(this.d);
  }
};
var SimpleContextKeyChangeEvent = class {
  constructor(key2) {
    this.key = key2;
  }
  affectsSome(keys) {
    return keys.has(this.key);
  }
  allKeysContainedIn(keys) {
    return this.affectsSome(keys);
  }
};
var ArrayContextKeyChangeEvent = class {
  constructor(keys) {
    this.keys = keys;
  }
  affectsSome(keys) {
    for (const key2 of this.keys) {
      if (keys.has(key2)) {
        return true;
      }
    }
    return false;
  }
  allKeysContainedIn(keys) {
    return this.keys.every((key2) => keys.has(key2));
  }
};
var CompositeContextKeyChangeEvent = class {
  constructor(events) {
    this.events = events;
  }
  affectsSome(keys) {
    for (const e of this.events) {
      if (e.affectsSome(keys)) {
        return true;
      }
    }
    return false;
  }
  allKeysContainedIn(keys) {
    return this.events.every((evt) => evt.allKeysContainedIn(keys));
  }
};
function allEventKeysInContext(event, context) {
  return event.allKeysContainedIn(new Set(Object.keys(context)));
}
var $aUb = class extends $3c {
  constructor(myContextId) {
    super();
    this.g = this.B(new $Ce({ merge: (input) => new CompositeContextKeyChangeEvent(input) }));
    this.onDidChangeContext = this.g.event;
    this.c = false;
    this.f = myContextId;
  }
  get contextId() {
    return this.f;
  }
  createKey(key2, defaultValue) {
    if (this.c) {
      throw new Error(`AbstractContextKeyService has been disposed`);
    }
    return new ContextKey(this, key2, defaultValue);
  }
  bufferChangeEvents(callback) {
    this.g.pause();
    try {
      callback();
    } finally {
      this.g.resume();
    }
  }
  createScoped(domNode) {
    if (this.c) {
      throw new Error(`AbstractContextKeyService has been disposed`);
    }
    return new ScopedContextKeyService(this, domNode);
  }
  createOverlay(overlay = Iterable.empty()) {
    if (this.c) {
      throw new Error(`AbstractContextKeyService has been disposed`);
    }
    return new OverlayContextKeyService(this, overlay);
  }
  contextMatchesRules(rules) {
    if (this.c) {
      throw new Error(`AbstractContextKeyService has been disposed`);
    }
    const context = this.getContextValuesContainer(this.f);
    const result = rules ? rules.evaluate(context) : true;
    return result;
  }
  getContextKeyValue(key2) {
    if (this.c) {
      return void 0;
    }
    return this.getContextValuesContainer(this.f).getValue(key2);
  }
  setContext(key2, value) {
    if (this.c) {
      return;
    }
    const myContext = this.getContextValuesContainer(this.f);
    if (!myContext) {
      return;
    }
    if (myContext.setValue(key2, value)) {
      this.g.fire(new SimpleContextKeyChangeEvent(key2));
    }
  }
  removeContext(key2) {
    if (this.c) {
      return;
    }
    if (this.getContextValuesContainer(this.f).removeValue(key2)) {
      this.g.fire(new SimpleContextKeyChangeEvent(key2));
    }
  }
  getContext(target) {
    if (this.c) {
      return NullContext.INSTANCE;
    }
    return this.getContextValuesContainer(findContextAttr(target));
  }
  dispose() {
    super.dispose();
    this.c = true;
  }
};
var $bUb = class $bUb2 extends $aUb {
  constructor(configurationService) {
    super(0);
    this.j = /* @__PURE__ */ new Map();
    this.h = 0;
    const myContext = this.B(new ConfigAwareContextValuesContainer(this.f, configurationService, this.g));
    this.j.set(this.f, myContext);
  }
  getContextValuesContainer(contextId) {
    if (this.c) {
      return NullContext.INSTANCE;
    }
    return this.j.get(contextId) || NullContext.INSTANCE;
  }
  createChildContext(parentContextId = this.f) {
    if (this.c) {
      throw new Error(`ContextKeyService has been disposed`);
    }
    const id2 = ++this.h;
    this.j.set(id2, new $_Tb(id2, this.getContextValuesContainer(parentContextId)));
    return id2;
  }
  disposeContext(contextId) {
    if (!this.c) {
      this.j.delete(contextId);
    }
  }
  updateParent(_parentContextKeyService) {
    throw new Error("Cannot update parent of root ContextKeyService");
  }
};
$bUb = __decorate([
  __param(0, $kl)
], $bUb);
var ScopedContextKeyService = class extends $aUb {
  constructor(parent, domNode) {
    super(parent.createChildContext());
    this.m = this.B(new $4c());
    this.h = parent;
    this.n();
    this.j = domNode;
    if (this.j.hasAttribute(KEYBINDING_CONTEXT_ATTR)) {
      let extraInfo = "";
      if (this.j.classList) {
        extraInfo = Array.from(this.j.classList.values()).join(", ");
      }
      console.error(`Element already has context attribute${extraInfo ? ": " + extraInfo : ""}`);
    }
    this.j.setAttribute(KEYBINDING_CONTEXT_ATTR, String(this.f));
  }
  n() {
    this.m.value = this.h.onDidChangeContext((e) => {
      const thisContainer = this.h.getContextValuesContainer(this.f);
      const thisContextValues = thisContainer.value;
      if (!allEventKeysInContext(e, thisContextValues)) {
        this.g.fire(e);
      }
    });
  }
  dispose() {
    if (this.c) {
      return;
    }
    this.h.disposeContext(this.f);
    this.j.removeAttribute(KEYBINDING_CONTEXT_ATTR);
    super.dispose();
  }
  getContextValuesContainer(contextId) {
    if (this.c) {
      return NullContext.INSTANCE;
    }
    return this.h.getContextValuesContainer(contextId);
  }
  createChildContext(parentContextId = this.f) {
    if (this.c) {
      throw new Error(`ScopedContextKeyService has been disposed`);
    }
    return this.h.createChildContext(parentContextId);
  }
  disposeContext(contextId) {
    if (this.c) {
      return;
    }
    this.h.disposeContext(contextId);
  }
  updateParent(parentContextKeyService) {
    if (this.h === parentContextKeyService) {
      return;
    }
    const thisContainer = this.h.getContextValuesContainer(this.f);
    const oldAllValues = thisContainer.collectAllValues();
    this.h = parentContextKeyService;
    this.n();
    const newParentContainer = this.h.getContextValuesContainer(this.h.contextId);
    thisContainer.updateParent(newParentContainer);
    const newAllValues = thisContainer.collectAllValues();
    const allValuesDiff = {
      ...$Rv(oldAllValues, newAllValues),
      ...$Rv(newAllValues, oldAllValues)
    };
    const changedKeys = Object.keys(allValuesDiff);
    this.g.fire(new ArrayContextKeyChangeEvent(changedKeys));
  }
};
var OverlayContext = class {
  constructor(c, d) {
    this.c = c;
    this.d = d;
  }
  getValue(key2) {
    return this.d.has(key2) ? this.d.get(key2) : this.c.getValue(key2);
  }
};
var OverlayContextKeyService = class _OverlayContextKeyService {
  get contextId() {
    return this.d.contextId;
  }
  get onDidChangeContext() {
    return this.d.onDidChangeContext;
  }
  constructor(d, overlay) {
    this.d = d;
    this.c = new Map(overlay);
  }
  bufferChangeEvents(callback) {
    this.d.bufferChangeEvents(callback);
  }
  createKey() {
    throw new Error("Not supported.");
  }
  getContext(target) {
    return new OverlayContext(this.d.getContext(target), this.c);
  }
  getContextValuesContainer(contextId) {
    const parentContext = this.d.getContextValuesContainer(contextId);
    return new OverlayContext(parentContext, this.c);
  }
  contextMatchesRules(rules) {
    const context = this.getContextValuesContainer(this.contextId);
    const result = rules ? rules.evaluate(context) : true;
    return result;
  }
  getContextKeyValue(key2) {
    return this.c.has(key2) ? this.c.get(key2) : this.d.getContextKeyValue(key2);
  }
  createScoped() {
    throw new Error("Not supported.");
  }
  createOverlay(overlay = Iterable.empty()) {
    return new _OverlayContextKeyService(this, overlay);
  }
  updateParent() {
    throw new Error("Not supported.");
  }
};
function findContextAttr(domNode) {
  while (domNode) {
    if (domNode.hasAttribute(KEYBINDING_CONTEXT_ATTR)) {
      const attr = domNode.getAttribute(KEYBINDING_CONTEXT_ATTR);
      if (attr) {
        return parseInt(attr, 10);
      }
      return NaN;
    }
    domNode = domNode.parentElement;
  }
  return 0;
}
function $cUb(accessor, contextKey, contextValue) {
  const contextKeyService = accessor.get($on);
  contextKeyService.createKey(String(contextKey), stringifyURIs(contextValue));
}
function stringifyURIs(contextValue) {
  return $Nv(contextValue, (obj) => {
    if (typeof obj === "object" && obj.$mid === 1) {
      return URI.revive(obj).toString();
    }
    if (obj instanceof URI) {
      return obj.toString();
    }
    return void 0;
  });
}
$tn.registerCommand("_setContext", $cUb);
$tn.registerCommand({
  id: "getContextKeyInfo",
  handler() {
    return [...$nn.all()].sort((a, b) => a.key.localeCompare(b.key));
  },
  metadata: {
    description: localize(1703, null),
    args: []
  }
});
$tn.registerCommand("_generateContextKeyInfo", function() {
  const result = [];
  const seen = /* @__PURE__ */ new Set();
  for (const info of $nn.all()) {
    if (!seen.has(info.key)) {
      seen.add(info.key);
      result.push(info);
    }
  }
  result.sort((a, b) => a.key.localeCompare(b.key));
  console.log(JSON.stringify(result, void 0, 2));
});

// out-build/vs/editor/common/services/textResourceConfigurationService.js
var $BYb = class $BYb2 extends $3c {
  constructor(b, c, f) {
    super();
    this.b = b;
    this.c = c;
    this.f = f;
    this.a = this.B(new $ze());
    this.onDidChangeConfiguration = this.a.event;
    this.B(this.b.onDidChangeConfiguration((e) => this.a.fire(this.m(e))));
  }
  getValue(resource, arg2, arg3) {
    if (typeof arg3 === "string") {
      return this.h(resource, $8C.isIPosition(arg2) ? arg2 : null, arg3);
    }
    return this.h(resource, null, typeof arg2 === "string" ? arg2 : void 0);
  }
  updateValue(resource, key2, value, configurationTarget) {
    const language = this.j(resource, null);
    const configurationValue = this.b.inspect(key2, { resource, overrideIdentifier: language });
    if (configurationTarget === void 0) {
      configurationTarget = this.g(configurationValue, language);
    }
    const overrideIdentifier = language && configurationValue.overrideIdentifiers?.includes(language) ? language : void 0;
    return this.b.updateValue(key2, value, { resource, overrideIdentifier }, configurationTarget);
  }
  g(configurationValue, language) {
    if (language) {
      if (configurationValue.memory?.override !== void 0) {
        return 8;
      }
      if (configurationValue.workspaceFolder?.override !== void 0) {
        return 6;
      }
      if (configurationValue.workspace?.override !== void 0) {
        return 5;
      }
      if (configurationValue.userRemote?.override !== void 0) {
        return 4;
      }
      if (configurationValue.userLocal?.override !== void 0) {
        return 3;
      }
    }
    if (configurationValue.memory?.value !== void 0) {
      return 8;
    }
    if (configurationValue.workspaceFolder?.value !== void 0) {
      return 6;
    }
    if (configurationValue.workspace?.value !== void 0) {
      return 5;
    }
    if (configurationValue.userRemote?.value !== void 0) {
      return 4;
    }
    return 3;
  }
  h(resource, position, section) {
    const language = resource ? this.j(resource, position) : void 0;
    if (typeof section === "undefined") {
      return this.b.getValue({ resource, overrideIdentifier: language });
    }
    return this.b.getValue(section, { resource, overrideIdentifier: language });
  }
  inspect(resource, position, section) {
    const language = resource ? this.j(resource, position) : void 0;
    return this.b.inspect(section, { resource, overrideIdentifier: language });
  }
  j(resource, position) {
    const model = this.c.getModel(resource);
    if (model) {
      return position ? model.getLanguageIdAtPosition(position.lineNumber, position.column) : model.getLanguageId();
    }
    return this.f.guessLanguageIdByFilepathOrFirstLine(resource);
  }
  m(configurationChangeEvent) {
    return {
      affectedKeys: configurationChangeEvent.affectedKeys,
      affectsConfiguration: (resource, configuration2) => {
        const overrideIdentifier = resource ? this.j(resource, null) : void 0;
        return configurationChangeEvent.affectsConfiguration(configuration2, { resource, overrideIdentifier });
      }
    };
  }
};
$BYb = __decorate([
  __param(0, $kl),
  __param(1, $sG),
  __param(2, $1E)
], $BYb);

// out-build/vs/platform/download/common/downloadService.js
var $eZ = class $eZ2 {
  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 options3 = { type: "GET", url: resource.toString(true) };
    const context = await this.a.request(options3, cancellationToken);
    if (context.res.statusCode === 200) {
      await this.b.writeFile(target, context.stream);
    } else {
      const message = await $bv(context);
      throw new Error(`Expected 200, got back ${context.res.statusCode} instead.

${message}`);
    }
  }
};
$eZ = __decorate([
  __param(0, $9u),
  __param(1, $km)
], $eZ);

// out-build/vs/editor/browser/services/openerService.js
var CommandOpener = class CommandOpener2 {
  constructor(a) {
    this.a = a;
  }
  async open(target, options3) {
    if (!$0g(target, Schemas.command)) {
      return false;
    }
    if (!options3?.allowCommands) {
      return true;
    }
    if (typeof target === "string") {
      target = URI.parse(target);
    }
    if (Array.isArray(options3.allowCommands)) {
      if (!options3.allowCommands.includes(target.path)) {
        return true;
      }
    }
    let args2 = [];
    try {
      args2 = $bu(decodeURIComponent(target.query));
    } catch {
      try {
        args2 = $bu(target.query);
      } catch {
      }
    }
    if (!Array.isArray(args2)) {
      args2 = [args2];
    }
    await this.a.executeCommand(target.path, ...args2);
    return true;
  }
};
CommandOpener = __decorate([
  __param(0, $sn)
], CommandOpener);
var EditorOpener = class EditorOpener2 {
  constructor(a) {
    this.a = a;
  }
  async open(target, options3) {
    if (typeof target === "string") {
      target = URI.parse(target);
    }
    const { selection, uri } = $Q4(target);
    target = uri;
    if (target.scheme === Schemas.file) {
      target = $wh(target);
    }
    await this.a.openCodeEditor({
      resource: target,
      options: {
        selection,
        source: options3?.fromUserGesture ? EditorOpenSource.USER : EditorOpenSource.API,
        ...options3?.editorOptions
      }
    }, this.a.getFocusedCodeEditor(), options3?.openToSide);
    return true;
  }
};
EditorOpener = __decorate([
  __param(0, $U5)
], EditorOpener);
var $CYb = class $CYb2 {
  constructor(editorService, commandService) {
    this.a = new $cd();
    this.b = new $cd();
    this.c = new $cd();
    this.d = new $Ec((uri) => uri.with({ path: null, fragment: null, query: null }).toString());
    this.f = new $cd();
    this.e = {
      openExternal: async (href) => {
        if ($$g(href, Schemas.http, Schemas.https)) {
          $nk(href);
        } else {
          $Y.location.href = href;
        }
        return true;
      }
    };
    this.a.push({
      open: async (target, options3) => {
        if (options3?.openExternal || $$g(target, Schemas.mailto, Schemas.http, Schemas.https, Schemas.vsls)) {
          await this.g(target, options3);
          return true;
        }
        return false;
      }
    });
    this.a.push(new CommandOpener(commandService));
    this.a.push(new EditorOpener(editorService));
  }
  registerOpener(opener) {
    const remove = this.a.unshift(opener);
    return { dispose: remove };
  }
  registerValidator(validator) {
    const remove = this.b.push(validator);
    return { dispose: remove };
  }
  registerExternalUriResolver(resolver) {
    const remove = this.c.push(resolver);
    return { dispose: remove };
  }
  setDefaultExternalOpener(externalOpener) {
    this.e = externalOpener;
  }
  registerExternalOpener(opener) {
    const remove = this.f.push(opener);
    return { dispose: remove };
  }
  async open(target, options3) {
    const targetURI = typeof target === "string" ? URI.parse(target) : target;
    const validationTarget = this.d.get(targetURI) ?? target;
    for (const validator of this.b) {
      if (!await validator.shouldOpen(validationTarget, options3)) {
        return false;
      }
    }
    for (const opener of this.a) {
      const handled = await opener.open(target, options3);
      if (handled) {
        return true;
      }
    }
    return false;
  }
  async resolveExternalUri(resource, options3) {
    for (const resolver of this.c) {
      try {
        const result = await resolver.resolveExternalUri(resource, options3);
        if (result) {
          if (!this.d.has(result.resolved)) {
            this.d.set(result.resolved, resource);
          }
          return result;
        }
      } catch {
      }
    }
    throw new Error("Could not resolve external URI: " + resource.toString());
  }
  async g(resource, options3) {
    const uri = typeof resource === "string" ? URI.parse(resource) : resource;
    let externalUri;
    try {
      externalUri = (await this.resolveExternalUri(uri, options3)).resolved;
    } catch {
      externalUri = uri;
    }
    let href;
    if (typeof resource === "string" && uri.toString() === externalUri.toString()) {
      href = resource;
    } else {
      href = encodeURI(externalUri.toString(true));
    }
    if (options3?.allowContributedOpeners) {
      const preferredOpenerId = typeof options3?.allowContributedOpeners === "string" ? options3?.allowContributedOpeners : void 0;
      for (const opener of this.f) {
        const didOpen = await opener.openExternal(href, {
          sourceUri: uri,
          preferredOpenerId
        }, CancellationToken.None);
        if (didOpen) {
          return true;
        }
      }
    }
    return this.e.openExternal(href, { sourceUri: uri }, CancellationToken.None);
  }
  dispose() {
    this.b.clear();
  }
};
$CYb = __decorate([
  __param(0, $U5),
  __param(1, $sn)
], $CYb);

// out-build/vs/platform/userDataSync/common/ignoredExtensions.js
var $DYb = $Qk("IIgnoredExtensionsManagementService");
var $EYb = class $EYb2 {
  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((i2) => i2.isMachineScoped).map((i2) => i2.identifier.id.toLowerCase());
    const value = this.b().map((id2) => id2.toLowerCase());
    const added = [], removed = [];
    if (Array.isArray(value)) {
      for (const key2 of value) {
        if (key2.startsWith("-")) {
          removed.push(key2.substring(1));
        } else {
          added.push(key2);
        }
      }
    }
    return $Rb([...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());
  }
};
$EYb = __decorate([
  __param(0, $kl)
], $EYb);

// out-build/vs/platform/userDataSync/common/userDataSyncLog.js
var $FYb = class $FYb2 extends $Bn {
  constructor(loggerService, environmentService) {
    super();
    this.h = this.B(loggerService.createLogger($vh(environmentService.logsHome, `${$_Bb}.log`), { id: $_Bb, name: localize(2507, null) }));
  }
  trace(message, ...args2) {
    this.h.trace(message, ...args2);
  }
  debug(message, ...args2) {
    this.h.debug(message, ...args2);
  }
  info(message, ...args2) {
    this.h.info(message, ...args2);
  }
  warn(message, ...args2) {
    this.h.warn(message, ...args2);
  }
  error(message, ...args2) {
    this.h.error(message, ...args2);
  }
  flush() {
    this.h.flush();
  }
};
$FYb = __decorate([
  __param(0, $xn),
  __param(1, $Xk)
], $FYb);

// out-build/vs/platform/telemetry/common/errorTelemetry.js
var ErrorEvent;
(function(ErrorEvent2) {
  function compare8(a, b) {
    if (a.callstack < b.callstack) {
      return -1;
    } else if (a.callstack > b.callstack) {
      return 1;
    }
    return 0;
  }
  ErrorEvent2.compare = compare8;
})(ErrorEvent || (ErrorEvent = {}));
var $DX = class _$DX {
  static {
    this.ERROR_FLUSH_TIMEOUT = 5 * 1e3;
  }
  constructor(telemetryService, flushDelay = _$DX.ERROR_FLUSH_TIMEOUT) {
    this.f = -1;
    this.g = [];
    this.h = new $2c();
    this.c = telemetryService;
    this.d = flushDelay;
    const unbind = $cb.addListener((err) => this.j(err));
    this.h.add($1c(unbind));
    this.i();
  }
  dispose() {
    clearTimeout(this.f);
    this.l();
    this.h.dispose();
  }
  i() {
  }
  j(err) {
    if (!err || err.code) {
      return;
    }
    if (err.detail && err.detail.stack) {
      err = err.detail;
    }
    if ($ub.isErrorNoTelemetry(err) || err instanceof $Fm || typeof err?.message === "string" && err.message.includes("Unable to read file")) {
      return;
    }
    const callstack = Array.isArray(err.stack) ? err.stack.join("\n") : err.stack;
    const msg = err.message ? err.message : $Qv(err);
    if (!callstack) {
      return;
    }
    this.k({ msg, callstack });
  }
  k(e) {
    const idx = $Bb(this.g, e, ErrorEvent.compare);
    if (idx < 0) {
      e.count = 1;
      this.g.splice(~idx, 0, e);
    } else {
      if (!this.g[idx].count) {
        this.g[idx].count = 0;
      }
      this.g[idx].count += 1;
    }
    if (this.f === -1) {
      this.f = setTimeout(() => {
        this.l();
        this.f = -1;
      }, this.d);
    }
  }
  l() {
    for (const error of this.g) {
      this.c.publicLogError2("UnhandledError", error);
    }
    this.g.length = 0;
  }
};

// out-build/vs/platform/telemetry/browser/errorTelemetry.js
var $GYb = class extends $DX {
  i() {
    let oldOnError;
    const that = this;
    if (typeof $Y.onerror === "function") {
      oldOnError = $Y.onerror;
    }
    $Y.onerror = function(message, filename, line, column, error) {
      that.n(message, filename, line, column, error);
      oldOnError?.apply(this, [message, filename, line, column, error]);
    };
    this.h.add($1c(() => {
      if (oldOnError) {
        $Y.onerror = oldOnError;
      }
    }));
  }
  n(msg, file, line, column, err) {
    const data = {
      callstack: msg,
      msg,
      file,
      line,
      column
    };
    if (err) {
      if ($ub.isErrorNoTelemetry(err)) {
        return;
      }
      const { name, message, stack } = err;
      data.uncaught_error_name = name;
      if (message) {
        data.uncaught_error_msg = message;
      }
      if (stack) {
        data.callstack = Array.isArray(err.stack) ? err.stack = err.stack.join("\n") : err.stack;
      }
    }
    this.k(data);
  }
};

// out-build/vs/workbench/contrib/telemetry/browser/telemetry.contribution.js
var $HYb_1;
var $HYb = class $HYb2 extends $3c {
  static {
    $HYb_1 = this;
  }
  static {
    this.a = ["package.json", "package-lock.json", "tsconfig.json", "jsconfig.json", "bower.json", ".eslintrc.json", "tslint.json", "composer.json"];
  }
  static {
    this.b = ["settings.json", "extensions.json", "tasks.json", "launch.json"];
  }
  constructor(c, f, lifecycleService, editorService, keybindingsService, themeService, environmentService, g, paneCompositeService, textFileService) {
    super();
    this.c = c;
    this.f = f;
    this.g = g;
    const { filesToOpenOrCreate, filesToDiff, filesToMerge } = environmentService;
    const activeViewlet = paneCompositeService.getActivePaneComposite(
      0
      /* ViewContainerLocation.Sidebar */
    );
    c.publicLog2("workspaceLoad", {
      windowSize: { innerHeight: $Y.innerHeight, innerWidth: $Y.innerWidth, outerHeight: $Y.outerHeight, outerWidth: $Y.outerWidth },
      emptyWorkbench: f.getWorkbenchState() === 1,
      "workbench.filesToOpenOrCreate": filesToOpenOrCreate && filesToOpenOrCreate.length || 0,
      "workbench.filesToDiff": filesToDiff && filesToDiff.length || 0,
      "workbench.filesToMerge": filesToMerge && filesToMerge.length || 0,
      customKeybindingsCount: keybindingsService.customKeybindingsCount(),
      theme: themeService.getColorTheme().id,
      language: $z,
      pinnedViewlets: paneCompositeService.getPinnedPaneCompositeIds(
        0
        /* ViewContainerLocation.Sidebar */
      ),
      restoredViewlet: activeViewlet ? activeViewlet.getId() : void 0,
      restoredEditors: editorService.visibleEditors.length,
      startupKind: lifecycleService.startupKind
    });
    this.B(new $GYb(c));
    this.B(textFileService.files.onDidResolve((e) => this.h(e)));
    this.B(textFileService.files.onDidSave((e) => this.j(e)));
    this.B(lifecycleService.onDidShutdown(() => this.dispose()));
  }
  h(e) {
    const settingsType = this.m(e.model.resource);
    if (settingsType) {
      this.c.publicLog2("settingsRead", { settingsType });
    } else {
      this.c.publicLog2("fileGet", this.n(e.model.resource, e.reason));
    }
  }
  j(e) {
    const settingsType = this.m(e.model.resource);
    if (settingsType) {
      this.c.publicLog2("settingsWritten", { settingsType });
    } else {
      this.c.publicLog2("filePUT", this.n(e.model.resource, e.reason));
    }
  }
  m(resource) {
    if ($th(resource) !== ".json") {
      return "";
    }
    if ($oh(resource, this.g.currentProfile.settingsResource)) {
      return "global-settings";
    }
    if ($oh(resource, this.g.currentProfile.keybindingsResource)) {
      return "keybindings";
    }
    if ($ph(resource, this.g.currentProfile.snippetsHome)) {
      return "snippets";
    }
    const folders = this.f.getWorkspace().folders;
    for (const folder of folders) {
      if ($ph(resource, folder.toResource(".vscode"))) {
        const filename = $sh(resource);
        if ($HYb_1.b.indexOf(filename) > -1) {
          return `.vscode/${filename}`;
        }
      }
    }
    return "";
  }
  n(resource, reason) {
    let ext = $th(resource);
    const queryStringLocation = ext.indexOf("?");
    ext = queryStringLocation !== -1 ? ext.substr(0, queryStringLocation) : ext;
    const fileName = $sh(resource);
    const path = resource.scheme === Schemas.file ? resource.fsPath : resource.path;
    const telemetryData = {
      mimeType: new $bw($Nsb(resource).join(", ")),
      ext,
      path: $Xi(path),
      reason,
      allowlistedjson: void 0
    };
    if (ext === ".json" && $HYb_1.a.indexOf(fileName) > -1) {
      telemetryData["allowlistedjson"] = fileName;
    }
    return telemetryData;
  }
};
$HYb = $HYb_1 = __decorate([
  __param(0, $zv),
  __param(1, $Zk),
  __param(2, $KL),
  __param(3, $mJ),
  __param(4, $Ty),
  __param(5, $rwb),
  __param(6, $US),
  __param(7, $gT),
  __param(8, $uqb),
  __param(9, $cK)
], $HYb);
var ConfigurationTelemetryContribution = class ConfigurationTelemetryContribution2 extends $3c {
  constructor(b, c, f) {
    super();
    this.b = b;
    this.c = c;
    this.f = f;
    this.a = $Wn.as($Ht.Configuration);
    const debouncedConfigService = Event2.debounce(b.onDidChangeConfiguration, (last, cur) => {
      const newAffectedKeys = last ? /* @__PURE__ */ new Set([...last.affectedKeys, ...cur.affectedKeys]) : cur.affectedKeys;
      return { ...cur, affectedKeys: newAffectedKeys };
    }, 1e3, true);
    this.B(debouncedConfigService((event) => {
      if (event.source !== 7) {
        f.publicLog2("updateConfiguration", {
          configurationSource: $nl(event.source),
          configurationKeys: Array.from(event.affectedKeys)
        });
      }
    }));
    const { user, workspace: workspace2 } = b.keys();
    for (const setting of user) {
      this.h(
        setting,
        3
        /* ConfigurationTarget.USER_LOCAL */
      );
    }
    for (const setting of workspace2) {
      this.h(
        setting,
        5
        /* ConfigurationTarget.WORKSPACE */
      );
    }
  }
  /**
   * Report value of a setting only if it is an enum, boolean, or number or an array of those.
   */
  g(key2, target) {
    const inpsectData = this.b.inspect(key2);
    const value = target === 3 ? inpsectData.user?.value : inpsectData.workspace?.value;
    if ($Dg(value) || $Fg(value)) {
      return value.toString();
    }
    const schema9 = this.a.getConfigurationProperties()[key2];
    if ($zg(value)) {
      if (schema9?.enum?.includes(value)) {
        return value;
      }
      return void 0;
    }
    if (Array.isArray(value)) {
      if (value.every((v) => $Dg(v) || $Fg(v) || $zg(v) && schema9?.enum?.includes(v))) {
        return JSON.stringify(value);
      }
    }
    return void 0;
  }
  h(key2, target) {
    const source = $nl(target);
    switch (key2) {
      case "workbench.activityBar.location":
        this.f.publicLog2("workbench.activityBar.location", { settingValue: this.g(key2, target), source });
        return;
      case $xzb:
        this.f.publicLog2("extensions.autoUpdate", { settingValue: this.g(key2, target), source });
        return;
      case "files.autoSave":
        this.f.publicLog2("files.autoSave", { settingValue: this.g(key2, target), source });
        return;
      case "editor.stickyScroll.enabled":
        this.f.publicLog2("editor.stickyScroll.enabled", { settingValue: this.g(key2, target), source });
        return;
      case $rO:
        this.f.publicLog2("accessibility.voice.keywordActivation", { settingValue: this.g(key2, target), source });
        return;
      case "window.zoomLevel":
        this.f.publicLog2("window.zoomLevel", { settingValue: this.g(key2, target), source });
        return;
      case "window.zoomPerWindow":
        this.f.publicLog2("window.zoomPerWindow", { settingValue: this.g(key2, target), source });
        return;
      case "window.titleBarStyle":
        this.f.publicLog2("window.titleBarStyle", { settingValue: this.g(key2, target), source });
        return;
      case "window.commandCenter":
        this.f.publicLog2("window.commandCenter", { settingValue: this.g(key2, target), source });
        return;
      case "chat.commandCenter.enabled":
        this.f.publicLog2("chat.commandCenter.enabled", { settingValue: this.g(key2, target), source });
        return;
      case "window.customTitleBarVisibility":
        this.f.publicLog2("window.customTitleBarVisibility", { settingValue: this.g(key2, target), source });
        return;
      case "window.nativeTabs":
        this.f.publicLog2("window.nativeTabs", { settingValue: this.g(key2, target), source });
        return;
      case "extensions.verifySignature":
        this.f.publicLog2("extensions.verifySignature", { settingValue: this.g(key2, target), source });
        return;
      case "window.systemColorTheme":
        this.f.publicLog2("window.systemColorTheme", { settingValue: this.g(key2, target), source });
        return;
      case "window.newWindowProfile": {
        const valueToReport = this.g(key2, target);
        const settingValue = valueToReport === null ? "null" : valueToReport === this.c.defaultProfile.name ? "default" : "custom";
        this.f.publicLog2("window.newWindowProfile", { settingValue, source });
        return;
      }
      case $Azb:
        this.f.publicLog2("extensions.autoRestart", { settingValue: this.g(key2, target), source });
        return;
    }
  }
};
ConfigurationTelemetryContribution = __decorate([
  __param(0, $kl),
  __param(1, $rs),
  __param(2, $zv)
], ConfigurationTelemetryContribution);
var workbenchContributionRegistry = $Wn.as(Extensions2.Workbench);
workbenchContributionRegistry.registerWorkbenchContribution(
  $HYb,
  3
  /* LifecyclePhase.Restored */
);
workbenchContributionRegistry.registerWorkbenchContribution(
  ConfigurationTelemetryContribution,
  4
  /* LifecyclePhase.Eventually */
);

// out-build/vs/workbench/contrib/preferences/browser/preferencesIcons.js
var $IYb = $9r("settings-folder-dropdown", $6l.triangleDown, localize(8818, null));
var $JYb = $9r("settings-more-action", $6l.gear, localize(8819, null));
var $KYb = $9r("keybindings-record-keys", $6l.recordKeys, localize(8820, null));
var $LYb = $9r("keybindings-sort", $6l.sortPrecedence, localize(8821, null));
var $MYb = $9r("keybindings-edit", $6l.edit, localize(8822, null));
var $NYb = $9r("keybindings-add", $6l.add, localize(8823, null));
var $OYb = $9r("settings-edit", $6l.edit, localize(8824, null));
var $PYb = $9r("settings-remove", $6l.close, localize(8825, null));
var $QYb = $9r("settings-discard", $6l.discard, localize(8826, null));
var $RYb = $9r("preferences-clear-input", $6l.clearAll, localize(8827, null));
var $SYb = $9r("preferences-filter", $6l.filter, localize(8828, null));
var $TYb = $9r("preferences-open-settings", $6l.goToFile, localize(8829, null));

// out-build/vs/workbench/contrib/preferences/browser/preferencesWidgets.js
var $UYb = class $UYb2 extends $T1 {
  constructor(action, t, y, L) {
    super(null, action);
    this.t = t;
    this.y = y;
    this.L = L;
    this.b = /* @__PURE__ */ new Map();
    const workspace2 = this.t.getWorkspace();
    this.a = workspace2.folders.length === 1 ? workspace2.folders[0] : null;
    this.B(this.t.onDidChangeWorkspaceFolders(() => this.P()));
  }
  get folder() {
    return this.a;
  }
  set folder(folder) {
    this.a = folder;
    this.Q();
  }
  setCount(settingsTarget, count) {
    const workspaceFolder = this.t.getWorkspaceFolder(settingsTarget);
    if (!workspaceFolder) {
      throw new Error("unknown folder");
    }
    const folder = workspaceFolder.uri;
    this.b.set(folder.toString(), count);
    this.Q();
  }
  render(container2) {
    this.element = container2;
    this.c = container2;
    this.m = $(".action-title");
    this.r = $(".action-details");
    this.s = $(".dropdown-icon.hide" + ThemeIcon.asCSSSelector($IYb));
    this.g = $("a.action-label.folder-settings", {
      role: "button",
      "aria-haspopup": "true",
      "tabindex": "0"
    }, this.m, this.r, this.s);
    this.h = this.B(this.L.setupManagedHover($JZ("mouse"), this.g, ""));
    this.B($_i(this.g, $7j.MOUSE_DOWN, (e) => $9j.stop(e)));
    this.B($_i(this.g, $7j.CLICK, (e) => this.onClick(e)));
    this.B($_i(this.c, $7j.KEY_UP, (e) => this.M(e)));
    $bk(this.c, this.g);
    this.Q();
  }
  M(event) {
    const keyboardEvent = new $if(event);
    switch (keyboardEvent.keyCode) {
      case 3:
      case 10:
        this.onClick(event);
        return;
    }
  }
  onClick(event) {
    $9j.stop(event, true);
    if (!this.folder || this._action.checked) {
      this.R();
    } else {
      this._action.run(this.a);
    }
  }
  z() {
    this.Q();
  }
  J() {
    this.Q();
  }
  P() {
    const oldFolder = this.a;
    const workspace2 = this.t.getWorkspace();
    if (oldFolder) {
      this.a = workspace2.folders.filter((folder) => $oh(folder.uri, oldFolder.uri))[0] || workspace2.folders[0];
    }
    this.a = this.a ? this.a : workspace2.folders.length === 1 ? workspace2.folders[0] : null;
    this.Q();
    if (this._action.checked) {
      this._action.run(this.a);
    }
  }
  Q() {
    let total = 0;
    this.b.forEach((n) => total += n);
    const workspace2 = this.t.getWorkspace();
    if (this.a) {
      this.m.textContent = this.a.name;
      this.h.update(this.a.name);
      const detailsText = this.U(this._action.label, total);
      this.r.textContent = detailsText;
      this.s.classList.toggle("hide", workspace2.folders.length === 1 || !this._action.checked);
    } else {
      const labelText = this.U(this._action.label, total);
      this.m.textContent = labelText;
      this.r.textContent = "";
      this.h.update(this._action.label);
      this.s.classList.remove("hide");
    }
    this.g.classList.toggle("checked", this._action.checked);
    this.c.classList.toggle("disabled", !this._action.enabled);
  }
  R() {
    this.y.showContextMenu({
      getAnchor: () => this.c,
      getActions: () => this.S(),
      getActionViewItem: () => void 0,
      onHide: () => {
        this.g.blur();
      }
    });
  }
  S() {
    const actions = [];
    const workspaceFolders = this.t.getWorkspace().folders;
    if (this.t.getWorkbenchState() === 3 && workspaceFolders.length > 0) {
      actions.push(...workspaceFolders.map((folder, index) => {
        const folderCount = this.b.get(folder.uri.toString());
        return {
          id: "folderSettingsTarget" + index,
          label: this.U(folder.name, folderCount),
          tooltip: this.U(folder.name, folderCount),
          checked: !!this.folder && $oh(this.folder.uri, folder.uri),
          enabled: true,
          class: void 0,
          run: () => this._action.run(folder)
        };
      }));
    }
    return actions;
  }
  U(label3, count) {
    if (count) {
      label3 += ` (${count})`;
    }
    return label3;
  }
};
$UYb = __decorate([
  __param(1, $Zk),
  __param(2, $50),
  __param(3, $5$)
], $UYb);
var $VYb = class $VYb2 extends $qZ {
  constructor(parent, options3, I, J, L, M, N) {
    super();
    this.I = I;
    this.J = J;
    this.L = L;
    this.M = M;
    this.N = N;
    this.y = null;
    this.H = this.B(new $ze());
    this.onDidTargetChange = this.H.event;
    this.w = options3 ?? {};
    this.P(parent);
    this.B(this.I.onDidChangeWorkbenchState(() => this.Q()));
    this.B(this.I.onDidChangeWorkspaceFolders(() => this.R()));
  }
  O() {
    const remoteAuthority = this.L.remoteAuthority;
    const hostLabel = remoteAuthority && this.M.getHostLabel(Schemas.vscodeRemote, remoteAuthority);
    this.c.label = localize(8848, null);
    this.g.label = localize(8849, null) + (hostLabel ? ` [${hostLabel}]` : "");
    this.h.label = localize(8850, null);
    this.r.label = localize(8851, null);
  }
  P(parent) {
    const settingsTabsWidget = $bk(parent, $(".settings-tabs-widget"));
    this.a = this.B(new $LZ(settingsTabsWidget, {
      orientation: 0,
      focusOnlyEnabledItems: true,
      ariaLabel: localize(8852, null),
      ariaRole: "tablist",
      actionViewItemProvider: (action, options3) => action.id === "folderSettings" ? this.t : void 0
    }));
    this.c = new $Um("userSettings", "", ".settings-tab", true, () => this.updateTarget(
      3
      /* ConfigurationTarget.USER_LOCAL */
    ));
    this.c.tooltip = localize(8853, null);
    this.g = new $Um("userSettingsRemote", "", ".settings-tab", true, () => this.updateTarget(
      4
      /* ConfigurationTarget.USER_REMOTE */
    ));
    const remoteAuthority = this.L.remoteAuthority;
    const hostLabel = remoteAuthority && this.M.getHostLabel(Schemas.vscodeRemote, remoteAuthority);
    this.g.tooltip = localize(8854, null) + (hostLabel ? ` [${hostLabel}]` : "");
    this.h = new $Um("workspaceSettings", "", ".settings-tab", false, () => this.updateTarget(
      5
      /* ConfigurationTarget.WORKSPACE */
    ));
    this.r = new $Um("folderSettings", "", ".settings-tab", false, async (folder) => {
      this.updateTarget(
        $9k(folder) ? folder.uri : 3
        /* ConfigurationTarget.USER_LOCAL */
      );
    });
    this.t = this.J.createInstance($UYb, this.r);
    this.O();
    this.R();
    this.a.push([this.c, this.g, this.h, this.r]);
  }
  get settingsTarget() {
    return this.y;
  }
  set settingsTarget(settingsTarget) {
    this.y = settingsTarget;
    this.c.checked = 3 === this.settingsTarget;
    this.g.checked = 4 === this.settingsTarget;
    this.h.checked = 5 === this.settingsTarget;
    if (this.settingsTarget instanceof URI) {
      this.t.action.checked = true;
      this.t.folder = this.I.getWorkspaceFolder(this.settingsTarget);
    } else {
      this.t.action.checked = false;
    }
  }
  setResultCount(settingsTarget, count) {
    if (settingsTarget === 5) {
      let label3 = localize(8855, null);
      if (count) {
        label3 += ` (${count})`;
      }
      this.h.label = label3;
    } else if (settingsTarget === 3) {
      let label3 = localize(8856, null);
      if (count) {
        label3 += ` (${count})`;
      }
      this.c.label = label3;
    } else if (settingsTarget instanceof URI) {
      this.t.setCount(settingsTarget, count);
    }
  }
  updateLanguageFilterIndicators(filter) {
    this.O();
    if (filter) {
      const languageToUse = this.N.getLanguageName(filter);
      if (languageToUse) {
        const languageSuffix = ` [${languageToUse}]`;
        this.c.label += languageSuffix;
        this.g.label += languageSuffix;
        this.h.label += languageSuffix;
        this.r.label += languageSuffix;
      }
    }
  }
  Q() {
    this.t.folder = null;
    this.R();
    if (this.settingsTarget === 5 && this.I.getWorkbenchState() === 3) {
      this.updateTarget(
        3
        /* ConfigurationTarget.USER_LOCAL */
      );
    }
  }
  updateTarget(settingsTarget) {
    const isSameTarget = this.settingsTarget === settingsTarget || settingsTarget instanceof URI && this.settingsTarget instanceof URI && $oh(this.settingsTarget, settingsTarget);
    if (!isSameTarget) {
      this.settingsTarget = settingsTarget;
      this.H.fire(this.settingsTarget);
    }
    return Promise.resolve(void 0);
  }
  async R() {
    this.a.domNode.classList.toggle(
      "empty-workbench",
      this.I.getWorkbenchState() === 1
      /* WorkbenchState.EMPTY */
    );
    this.g.enabled = !!(this.w.enableRemoteSettings && this.L.remoteAuthority);
    this.h.enabled = this.I.getWorkbenchState() !== 1;
    this.t.action.enabled = this.I.getWorkbenchState() === 3 && this.I.getWorkspace().folders.length > 0;
    this.h.tooltip = localize(8857, null);
  }
};
$VYb = __decorate([
  __param(2, $Zk),
  __param(3, $Pk),
  __param(4, $US),
  __param(5, $ZI),
  __param(6, $1E)
], $VYb);
var $WYb = class $WYb2 extends $qZ {
  constructor(parent, w, y, H, I, J) {
    super();
    this.w = w;
    this.y = y;
    this.H = H;
    this.I = I;
    this.J = J;
    this.r = this.B(new $ze());
    this.onDidChange = this.r.event;
    this.t = this.B(new $ze());
    this.onFocus = this.t.event;
    this.L(parent);
  }
  L(parent) {
    this.domNode = $bk(parent, $("div.settings-header-widget"));
    this.M($bk(this.domNode, $("div.settings-search-container")));
    this.h = $bk(this.domNode, $("div.settings-search-controls"));
    if (this.w.showResultCount) {
      this.a = $bk(this.h, $(".settings-count-widget"));
      this.a.style.backgroundColor = $Zn($wo);
      this.a.style.color = $Zn($xo);
      this.a.style.border = `1px solid ${$Zn($ko)}`;
    }
    this.inputBox.inputElement.setAttribute("aria-live", this.w.ariaLive || "off");
    if (this.w.ariaLabelledBy) {
      this.inputBox.inputElement.setAttribute("aria-labelledBy", this.w.ariaLabelledBy);
    }
    const focusTracker = this.B($_j(this.inputBox.inputElement));
    this.B(focusTracker.onDidFocus(() => this.t.fire()));
    const focusKey = this.w.focusKey;
    if (focusKey) {
      this.B(focusTracker.onDidFocus(() => focusKey.set(true)));
      this.B(focusTracker.onDidBlur(() => focusKey.set(false)));
    }
  }
  M(searchContainer) {
    this.g = searchContainer;
    const searchInput = $bk(this.g, $("div.settings-search-input"));
    this.inputBox = this.B(this.N(searchInput));
    this.B(this.inputBox.onDidChange((value) => this.r.fire(value)));
  }
  N(parent) {
    const showHistoryHint = () => $ggb(this.J);
    return new $9bb(parent, this.y, { ...this.w, showHistoryHint }, this.I);
  }
  showMessage(message) {
    if (this.a && message !== this.a.textContent) {
      this.a.textContent = message;
      this.inputBox.inputElement.setAttribute("aria-label", message);
      this.inputBox.inputElement.style.paddingRight = this.O() + "px";
    }
  }
  layout(dimension) {
    if (dimension.width < 400) {
      this.a?.classList.add("hide");
      this.inputBox.inputElement.style.paddingRight = "0px";
    } else {
      this.a?.classList.remove("hide");
      this.inputBox.inputElement.style.paddingRight = this.O() + "px";
    }
  }
  O() {
    const countWidth = this.a ? $xj(this.a) : 0;
    return countWidth + 20;
  }
  focus() {
    this.inputBox.focus();
    if (this.getValue()) {
      this.inputBox.select();
    }
  }
  hasFocus() {
    return this.inputBox.hasFocus();
  }
  clear() {
    this.inputBox.value = "";
  }
  getValue() {
    return this.inputBox.value;
  }
  setValue(value) {
    return this.inputBox.value = value;
  }
  dispose() {
    this.w.focusKey?.set(false);
    super.dispose();
  }
};
$WYb = __decorate([
  __param(2, $40),
  __param(3, $Pk),
  __param(4, $on),
  __param(5, $Ty)
], $WYb);
var $XYb = class extends $3c {
  constructor(g) {
    super();
    this.g = g;
    this.a = -1;
    this.b = [];
    this.c = this.g.createDecorationsCollection();
    this.f = this.B(new $ze());
    this.onClick = this.f.event;
    this.B(this.g.onMouseDown((e) => {
      if (e.target.type !== 2 || e.target.detail.isAfterLines || !this.isVisible()) {
        return;
      }
      this.f.fire(e);
    }));
  }
  get preferences() {
    return this.b;
  }
  getLine() {
    return this.a;
  }
  show(line, hoverMessage, preferences) {
    this.b = preferences;
    const newDecoration = [];
    this.a = line;
    newDecoration.push({
      options: {
        description: "edit-preference-widget-decoration",
        glyphMarginClassName: ThemeIcon.asClassName($OYb),
        glyphMarginHoverMessage: new $bm().appendText(hoverMessage),
        stickiness: 1
      },
      range: {
        startLineNumber: line,
        startColumn: 1,
        endLineNumber: line,
        endColumn: 1
      }
    });
    this.c.set(newDecoration);
  }
  hide() {
    this.c.clear();
  }
  isVisible() {
    return this.c.length > 0;
  }
  dispose() {
    this.hide();
    super.dispose();
  }
};

// out-build/vs/workbench/contrib/preferences/browser/keybindingWidgets.js
var $ZYb_1;
var $1Yb_1;
var $YYb = class $YYb2 extends $WYb {
  constructor(parent, options3, contextViewService, instantiationService, contextKeyService, keybindingService) {
    super(parent, options3, contextViewService, instantiationService, contextKeyService, keybindingService);
    this.R = this.B(new $2c());
    this.S = this.B(new $ze());
    this.onKeybinding = this.S.event;
    this.U = this.B(new $ze());
    this.onEnter = this.U.event;
    this.W = this.B(new $ze());
    this.onEscape = this.W.event;
    this.X = this.B(new $ze());
    this.onBlur = this.X.event;
    this.B($1c(() => this.stopRecordingKeys()));
    this.P = null;
    this.Q = "";
  }
  clear() {
    this.P = null;
    super.clear();
  }
  startRecordingKeys() {
    this.R.add($_i(this.inputBox.inputElement, $7j.KEY_DOWN, (e) => this.Y(new $if(e))));
    this.R.add($_i(this.inputBox.inputElement, $7j.BLUR, () => this.X.fire()));
    this.R.add($_i(this.inputBox.inputElement, $7j.INPUT, () => {
      this.setInputValue(this.Q);
    }));
  }
  stopRecordingKeys() {
    this.P = null;
    this.R.clear();
  }
  setInputValue(value) {
    this.Q = value;
    this.inputBox.value = this.Q;
  }
  Y(keyboardEvent) {
    keyboardEvent.preventDefault();
    keyboardEvent.stopPropagation();
    const options3 = this.w;
    if (!options3.recordEnter && keyboardEvent.equals(
      3
      /* KeyCode.Enter */
    )) {
      this.U.fire();
      return;
    }
    if (keyboardEvent.equals(
      9
      /* KeyCode.Escape */
    )) {
      this.W.fire();
      return;
    }
    this.Z(keyboardEvent);
  }
  Z(keyboardEvent) {
    const keybinding = this.J.resolveKeyboardEvent(keyboardEvent);
    const info = `code: ${keyboardEvent.browserEvent.code}, keyCode: ${keyboardEvent.browserEvent.keyCode}, key: ${keyboardEvent.browserEvent.key} => UI: ${keybinding.getAriaLabel()}, user settings: ${keybinding.getUserSettingsLabel()}, dispatch: ${keybinding.getDispatchChords()[0]}`;
    const options3 = this.w;
    if (!this.P) {
      this.P = [];
    }
    const hasIncompleteChord = this.P.length > 0 && this.P[this.P.length - 1].getDispatchChords()[0] === null;
    if (hasIncompleteChord) {
      this.P[this.P.length - 1] = keybinding;
    } else {
      if (this.P.length === 2) {
        this.P = [];
      }
      this.P.push(keybinding);
    }
    const value = this.P.map((keybinding2) => keybinding2.getUserSettingsLabel() || "").join(" ");
    this.setInputValue(options3.quoteRecordedKeys ? `"${value}"` : value);
    this.inputBox.inputElement.title = info;
    this.S.fire(this.P);
  }
};
$YYb = __decorate([
  __param(2, $40),
  __param(3, $Pk),
  __param(4, $on),
  __param(5, $Ty)
], $YYb);
var $ZYb = class $ZYb2 extends $qZ {
  static {
    $ZYb_1 = this;
  }
  static {
    this.a = 400;
  }
  static {
    this.g = 110;
  }
  constructor(parent, M) {
    super();
    this.M = M;
    this.w = this.B(new $2c());
    this.y = null;
    this.H = false;
    this.I = this.B(new $ze());
    this.J = this.B(new $ze());
    this.onDidChange = this.J.event;
    this.L = this.B(new $ze());
    this.onShowExistingKeybidings = this.L.event;
    this.h = $oZ(document.createElement("div"));
    this.h.setDisplay("none");
    this.h.setClassName("defineKeybindingWidget");
    this.h.setWidth($ZYb_1.a);
    this.h.setHeight($ZYb_1.g);
    const message = localize(8754, null);
    $bk(this.h.domNode, $(".message", void 0, message));
    this.h.domNode.style.backgroundColor = $Zn($Qo);
    this.h.domNode.style.color = $Zn($Ro);
    this.h.domNode.style.boxShadow = `0 2px 8px ${$Zn($Rp)}`;
    this.n = this.B(this.M.createInstance($YYb, this.h.domNode, { ariaLabel: message, history: /* @__PURE__ */ new Set([]), inputBoxStyles: $B$ }));
    this.n.startRecordingKeys();
    this.B(this.n.onKeybinding((keybinding) => this.N(keybinding)));
    this.B(this.n.onEnter(() => this.R()));
    this.B(this.n.onEscape(() => this.Q()));
    this.B(this.n.onBlur(() => this.P()));
    this.r = $bk(this.h.domNode, $(".output"));
    this.t = $bk(this.h.domNode, $(".existing"));
    if (parent) {
      $bk(parent, this.h.domNode);
    }
  }
  get domNode() {
    return this.h.domNode;
  }
  define() {
    this.n.clear();
    return Promises.withAsyncBody(async (c) => {
      if (!this.H) {
        this.H = true;
        this.h.setDisplay("block");
        this.y = null;
        this.n.setInputValue("");
        $$i(this.r);
        $$i(this.t);
        await $Wh(0);
        this.n.focus();
      }
      const disposable = this.I.event(() => {
        c(this.O());
        disposable.dispose();
      });
    });
  }
  layout(layout) {
    const top2 = Math.round((layout.height - $ZYb_1.g) / 2);
    this.h.setTop(top2);
    const left = Math.round((layout.width - $ZYb_1.a) / 2);
    this.h.setLeft(left);
  }
  printExisting(numberOfExisting) {
    if (numberOfExisting > 0) {
      const existingElement = $("span.existingText");
      const text2 = numberOfExisting === 1 ? localize(8755, null, numberOfExisting) : localize(8756, null, numberOfExisting);
      $bk(existingElement, document.createTextNode(text2));
      $$Z(text2);
      this.t.appendChild(existingElement);
      existingElement.onmousedown = (e) => {
        e.preventDefault();
      };
      existingElement.onmouseup = (e) => {
        e.preventDefault();
      };
      existingElement.onclick = () => {
        this.L.fire(this.O());
      };
    }
  }
  N(keybinding) {
    this.w.clear();
    this.y = keybinding;
    $$i(this.r);
    $$i(this.t);
    const firstLabel = this.w.add(new $32(this.r, OS, $o$));
    firstLabel.set(this.y?.[0] ?? void 0);
    if (this.y) {
      for (let i2 = 1; i2 < this.y.length; i2++) {
        this.r.appendChild(document.createTextNode(localize(8757, null)));
        const chordLabel = this.w.add(new $32(this.r, OS, $o$));
        chordLabel.set(this.y[i2]);
      }
    }
    const label3 = this.O();
    if (label3) {
      this.J.fire(label3);
    }
  }
  O() {
    let label3 = null;
    if (this.y) {
      label3 = this.y.map((keybinding) => keybinding.getUserSettingsLabel()).join(" ");
    }
    return label3;
  }
  P() {
    this.y = null;
    this.R();
  }
  Q() {
    if (this.y === null) {
      this.R();
    } else {
      this.y = null;
      this.n.clear();
      $$i(this.r);
      $$i(this.t);
    }
  }
  R() {
    this.h.setDisplay("none");
    this.H = false;
    this.I.fire();
  }
};
$ZYb = $ZYb_1 = __decorate([
  __param(1, $Pk)
], $ZYb);
var $1Yb = class $1Yb2 extends $3c {
  static {
    $1Yb_1 = this;
  }
  static {
    this.a = "editor.contrib.defineKeybindingWidget";
  }
  constructor(f, instantiationService) {
    super();
    this.f = f;
    this.b = this.B(instantiationService.createInstance($ZYb, null));
    this.f.addOverlayWidget(this);
  }
  getId() {
    return $1Yb_1.a;
  }
  getDomNode() {
    return this.b.domNode;
  }
  getPosition() {
    return {
      preference: null
    };
  }
  dispose() {
    this.f.removeOverlayWidget(this);
    super.dispose();
  }
  start() {
    if (this.f.hasModel()) {
      this.f.revealPositionInCenterIfOutsideViewport(
        this.f.getPosition(),
        0
        /* ScrollType.Smooth */
      );
    }
    const layoutInfo = this.f.getLayoutInfo();
    this.b.layout(new $rj(layoutInfo.width, layoutInfo.height));
    return this.b.define();
  }
};
$1Yb = $1Yb_1 = __decorate([
  __param(1, $Pk)
], $1Yb);

// out-build/vs/workbench/contrib/preferences/common/preferences.js
var $2Yb = $Qk("preferencesSearchService");
var $3Yb = "settings.action.clearSearchResults";
var $4Yb = "settings.action.showContextMenu";
var $5Yb = "settings.action.suggestFilters";
var $6Yb = new $nn("inSettingsEditor", false);
var $7Yb = new $nn("inSettingsJSONEditor", false);
var $8Yb = new $nn("inSettingsSearch", false);
var $9Yb = new $nn("settingsTocRowFocus", false);
var $0Yb = new $nn("settingRowFocus", false);
var $$Yb = new $nn("inKeybindings", false);
var $_Yb = new $nn("inKeybindingsSearch", false);
var $aZb = new $nn("keybindingFocus", false);
var $bZb = new $nn("whenFocus", false);
var $cZb = "keybindings.editor.searchKeybindings";
var $dZb = "keybindings.editor.clearSearchResults";
var $eZb = "keybindings.editor.clearSearchHistory";
var $fZb = "keybindings.editor.recordSearchKeys";
var $gZb = "keybindings.editor.toggleSortByPrecedence";
var $hZb = "keybindings.editor.defineKeybinding";
var $iZb = "keybindings.editor.addKeybinding";
var $jZb = "keybindings.editor.defineWhenExpression";
var $kZb = "keybindings.editor.acceptWhenExpression";
var $lZb = "keybindings.editor.rejectWhenExpression";
var $mZb = "keybindings.editor.removeKeybinding";
var $nZb = "keybindings.editor.resetKeybinding";
var $oZb = "keybindings.editor.copyKeybindingEntry";
var $pZb = "keybindings.editor.copyCommandKeybindingEntry";
var $qZb = "keybindings.editor.copyCommandTitle";
var $rZb = "keybindings.editor.showConflicts";
var $sZb = "keybindings.editor.focusKeybindings";
var $tZb = "keybindings.editor.showDefaultKeybindings";
var $uZb = "keybindings.editor.showUserKeybindings";
var $vZb = "keybindings.editor.showExtensionKeybindings";
var $wZb = "modified";
var $xZb = "ext:";
var $yZb = "feature:";
var $zZb = "id:";
var $AZb = "lang:";
var $BZb = "tag:";
var $CZb = "hasPolicy";
var $DZb = "workspaceTrust";
var $EZb = "requireTrustedWorkspace";
var $FZb = "workbench.action.openKeyboardLayoutPicker";
var $GZb = true;
var $HZb = true;
var $IZb = 1e3;
var cachedExtensionToggleData;
async function $JZb(extensionGalleryService, productService) {
  if (!$HZb) {
    return void 0;
  }
  if (!extensionGalleryService.isEnabled()) {
    return void 0;
  }
  if (cachedExtensionToggleData) {
    return cachedExtensionToggleData;
  }
  if (productService.extensionRecommendations && productService.commonlyUsedSettings) {
    const settingsEditorRecommendedExtensions = {};
    Object.keys(productService.extensionRecommendations).forEach((extensionId) => {
      const extensionInfo = productService.extensionRecommendations[extensionId];
      if (extensionInfo.onSettingsEditorOpen) {
        settingsEditorRecommendedExtensions[extensionId] = extensionInfo;
      }
    });
    const recommendedExtensionsGalleryInfo = {};
    for (const key2 in settingsEditorRecommendedExtensions) {
      const extensionId = key2;
      const isStable = productService.quality === "stable";
      try {
        const extensions = await $Lh(extensionGalleryService.getExtensions([{ id: extensionId, preRelease: !isStable }], CancellationToken.None), $IZb);
        if (extensions?.length === 1) {
          recommendedExtensionsGalleryInfo[key2] = extensions[0];
        } else {
          return void 0;
        }
      } catch (e) {
        return void 0;
      }
    }
    cachedExtensionToggleData = {
      settingsEditorRecommendedExtensions,
      recommendedExtensionsGalleryInfo,
      commonlyUsed: productService.commonlyUsedSettings
    };
    return cachedExtensionToggleData;
  }
  return void 0;
}
function $KZb(a, b) {
  const aOrMax = a ?? Number.MAX_SAFE_INTEGER;
  const bOrMax = b ?? Number.MAX_SAFE_INTEGER;
  if (aOrMax < bOrMax) {
    return -1;
  } else if (aOrMax > bOrMax) {
    return 1;
  } else {
    return 0;
  }
}
var $LZb = localize(9044, null);
var $MZb = localize(9045, null);

// out-build/vs/workbench/contrib/codeEditor/browser/suggestEnabledInput/suggestEnabledInput.js
var $NZb = class $NZb2 extends $qZ {
  constructor(id2, parent, suggestionProvider, ariaLabel, resourceHandle, options3, defaultInstantiationService, modelService, contextKeyService, languageFeaturesService, configurationService) {
    super();
    this.c = new $ze();
    this.onShouldFocusResults = this.c.event;
    this.g = new $ze();
    this.onInputDidChange = this.g.event;
    this.h = this.B(new $ze());
    this.onDidFocus = this.h.event;
    this.n = this.B(new $ze());
    this.onDidBlur = this.n.event;
    this.t = $bk(parent, $(".suggest-input-container"));
    this.element = parent;
    this.w = $bk(this.t, $(".suggest-input-placeholder", void 0, options3.placeholderText || ""));
    const editorOptions2 = $Ov($Zsb(configurationService), getSuggestEnabledInputOptions(ariaLabel));
    editorOptions2.overflowWidgetsDomNode = options3.overflowWidgetsDomNode;
    const scopedContextKeyService = this.y(contextKeyService);
    const instantiationService = scopedContextKeyService ? this.B(defaultInstantiationService.createChild(new $Ok([$on, scopedContextKeyService]))) : defaultInstantiationService;
    this.inputWidget = this.B(instantiationService.createInstance($D9, this.t, editorOptions2, {
      contributions: EditorExtensionsRegistry.getSomeEditorContributions([
        $qdb.ID,
        $Dcb.ID,
        $Mfb.ID,
        $Esb.ID,
        $Fsb
      ]),
      isSimpleWidget: true
    }));
    this.B(configurationService.onDidChangeConfiguration((e) => {
      if (e.affectsConfiguration("editor.accessibilitySupport") || e.affectsConfiguration("editor.cursorBlinking")) {
        const accessibilitySupport = configurationService.getValue("editor.accessibilitySupport");
        const cursorBlinking = configurationService.getValue("editor.cursorBlinking");
        this.inputWidget.updateOptions({
          accessibilitySupport,
          cursorBlinking
        });
      }
    }));
    this.B(this.inputWidget.onDidFocusEditorText(() => this.h.fire()));
    this.B(this.inputWidget.onDidBlurEditorText(() => this.n.fire()));
    const scopeHandle = URI.parse(resourceHandle);
    this.r = modelService.createModel("", null, scopeHandle, true);
    this.B(this.r);
    this.inputWidget.setModel(this.r);
    this.B(this.inputWidget.onDidPaste(() => this.setValue(this.getValue())));
    this.B(this.inputWidget.onDidFocusEditorText(() => {
      if (options3.focusContextKey) {
        options3.focusContextKey.set(true);
      }
      this.t.classList.add("synthetic-focus");
    }));
    this.B(this.inputWidget.onDidBlurEditorText(() => {
      if (options3.focusContextKey) {
        options3.focusContextKey.set(false);
      }
      this.t.classList.remove("synthetic-focus");
    }));
    this.B(Event2.chain(this.inputWidget.onKeyDown, ($149) => $149.filter(
      (e) => e.keyCode === 3
      /* KeyCode.Enter */
    ))((e) => {
      e.preventDefault();
    }, this));
    this.B(Event2.chain(this.inputWidget.onKeyDown, ($149) => $149.filter((e) => e.keyCode === 18 && ($m ? e.metaKey : e.ctrlKey)))(() => this.c.fire(), this));
    let preexistingContent = this.getValue();
    const inputWidgetModel = this.inputWidget.getModel();
    if (inputWidgetModel) {
      this.B(inputWidgetModel.onDidChangeContent(() => {
        const content = this.getValue();
        this.w.style.visibility = content ? "hidden" : "visible";
        if (preexistingContent.trim() === content.trim()) {
          return;
        }
        this.g.fire(void 0);
        preexistingContent = content;
      }));
    }
    const validatedSuggestProvider = {
      provideResults: suggestionProvider.provideResults,
      sortKey: suggestionProvider.sortKey || ((a) => a),
      triggerCharacters: suggestionProvider.triggerCharacters || [],
      wordDefinition: suggestionProvider.wordDefinition ? $KD(suggestionProvider.wordDefinition) : void 0,
      alwaysShowSuggestions: !!suggestionProvider.alwaysShowSuggestions
    };
    this.setValue(options3.value || "");
    this.B(languageFeaturesService.completionProvider.register({ scheme: scopeHandle.scheme, pattern: "**/" + scopeHandle.path, hasAccessToAllModels: true }, {
      _debugDisplayName: `suggestEnabledInput/${id2}`,
      triggerCharacters: validatedSuggestProvider.triggerCharacters,
      provideCompletionItems: (model, position, _context) => {
        const query = model.getValue();
        const zeroIndexedColumn = position.column - 1;
        let alreadyTypedCount = 0, zeroIndexedWordStart = 0;
        if (validatedSuggestProvider.wordDefinition) {
          const wordAtText = $MD(position.column, validatedSuggestProvider.wordDefinition, query, 0);
          alreadyTypedCount = wordAtText?.word.length ?? 0;
          zeroIndexedWordStart = wordAtText ? wordAtText.startColumn - 1 : 0;
        } else {
          zeroIndexedWordStart = query.lastIndexOf(" ", zeroIndexedColumn - 1) + 1;
          alreadyTypedCount = zeroIndexedColumn - zeroIndexedWordStart;
        }
        if (!validatedSuggestProvider.alwaysShowSuggestions && alreadyTypedCount > 0 && validatedSuggestProvider.triggerCharacters?.indexOf(query[zeroIndexedWordStart]) === -1) {
          return { suggestions: [] };
        }
        return {
          suggestions: suggestionProvider.provideResults(query).map((result) => {
            let label3;
            let rest;
            if (typeof result === "string") {
              label3 = result;
            } else {
              label3 = result.label;
              rest = result;
            }
            return {
              label: label3,
              insertText: label3,
              range: $9C.fromPositions(position.delta(0, -alreadyTypedCount), position),
              sortText: validatedSuggestProvider.sortKey(label3),
              kind: 17,
              ...rest
            };
          })
        };
      }
    }));
    this.H(options3.styleOverrides || {});
  }
  y(_contextKeyService) {
    return void 0;
  }
  updateAriaLabel(label3) {
    this.inputWidget.updateOptions({ ariaLabel: label3 });
  }
  setValue(val) {
    val = val.replace(/\s/g, " ");
    const fullRange = this.r.getFullModelRange();
    this.inputWidget.executeEdits("suggestEnabledInput.setValue", [$bD.replace(fullRange, val)]);
    this.inputWidget.setScrollTop(0);
    this.inputWidget.setPosition(new $8C(1, val.length + 1));
  }
  getValue() {
    return this.inputWidget.getValue();
  }
  H(styleOverrides) {
    this.t.style.backgroundColor = $Zn(styleOverrides.inputBackground ?? $xq);
    this.t.style.color = $Zn(styleOverrides.inputForeground ?? $yq);
    this.w.style.color = $Zn(styleOverrides.inputPlaceholderForeground ?? $Eq);
    this.t.style.borderWidth = "1px";
    this.t.style.borderStyle = "solid";
    this.t.style.borderColor = $1n(styleOverrides.inputBorder ?? $zq, "transparent");
    const cursor = this.t.getElementsByClassName("cursor")[0];
    if (cursor) {
      cursor.style.backgroundColor = $Zn(styleOverrides.inputForeground ?? $yq);
    }
  }
  focus(selectAll) {
    this.inputWidget.focus();
    if (selectAll && this.inputWidget.getValue()) {
      this.I();
    }
  }
  onHide() {
    this.inputWidget.onHide();
  }
  layout(dimension) {
    this.inputWidget.layout(dimension);
    this.w.style.width = `${dimension.width - 2}px`;
  }
  I() {
    this.inputWidget.setSelection(new $9C(1, 1, 1, this.getValue().length + 1));
  }
};
$NZb = __decorate([
  __param(6, $Pk),
  __param(7, $sG),
  __param(8, $on),
  __param(9, $mP),
  __param(10, $kl)
], $NZb);
var $OZb = class $OZb2 extends $NZb {
  constructor({ id: id2, parent, ariaLabel, suggestionProvider, resourceHandle, suggestOptions, history }, instantiationService, modelService, contextKeyService, languageFeaturesService, configurationService) {
    super(id2, parent, suggestionProvider, ariaLabel, resourceHandle, suggestOptions, instantiationService, modelService, contextKeyService, languageFeaturesService, configurationService);
    this.J = new $F2(new Set(history), 100);
  }
  addToHistory() {
    const value = this.getValue();
    if (value && value !== this.L()) {
      this.J.add(value);
    }
  }
  getHistory() {
    return this.J.getHistory();
  }
  showNextValue() {
    if (!this.J.has(this.getValue())) {
      this.addToHistory();
    }
    let next = this.N();
    if (next) {
      next = next === this.getValue() ? this.N() : next;
    }
    this.setValue(next ?? "");
  }
  showPreviousValue() {
    if (!this.J.has(this.getValue())) {
      this.addToHistory();
    }
    let previous = this.M();
    if (previous) {
      previous = previous === this.getValue() ? this.M() : previous;
    }
    if (previous) {
      this.setValue(previous);
      this.inputWidget.setPosition({ lineNumber: 0, column: 0 });
    }
  }
  clearHistory() {
    this.J.clear();
  }
  L() {
    let currentValue = this.J.current();
    if (!currentValue) {
      currentValue = this.J.last();
      this.J.next();
    }
    return currentValue;
  }
  M() {
    return this.J.previous() || this.J.first();
  }
  N() {
    return this.J.next();
  }
};
$OZb = __decorate([
  __param(1, $Pk),
  __param(2, $sG),
  __param(3, $on),
  __param(4, $mP),
  __param(5, $kl)
], $OZb);
var $PZb = class $PZb2 extends $OZb {
  constructor(options3, instantiationService, modelService, contextKeyService, languageFeaturesService, configurationService) {
    super(options3, instantiationService, modelService, contextKeyService, languageFeaturesService, configurationService);
    const { historyNavigationBackwardsEnablement, historyNavigationForwardsEnablement } = this.O;
    this.B(this.inputWidget.onDidChangeCursorPosition(({ position }) => {
      const viewModel = this.inputWidget._getViewModel();
      const lastLineNumber = viewModel.getLineCount();
      const lastLineCol = viewModel.getLineLength(lastLineNumber) + 1;
      const viewPosition = viewModel.coordinatesConverter.convertModelPositionToViewPosition(position);
      historyNavigationBackwardsEnablement.set(viewPosition.lineNumber === 1 && viewPosition.column === 1);
      historyNavigationForwardsEnablement.set(viewPosition.lineNumber === lastLineNumber && viewPosition.column === lastLineCol);
    }));
  }
  y(contextKeyService) {
    const scopedContextKeyService = this.B(contextKeyService.createScoped(this.element));
    this.O = this.B($8bb(scopedContextKeyService, this));
    return scopedContextKeyService;
  }
};
$PZb = __decorate([
  __param(1, $Pk),
  __param(2, $sG),
  __param(3, $on),
  __param(4, $mP),
  __param(5, $kl)
], $PZb);
$2sb(".suggest-input-container");
function getSuggestEnabledInputOptions(ariaLabel) {
  return {
    fontSize: 13,
    lineHeight: 20,
    wordWrap: "off",
    scrollbar: { vertical: "hidden" },
    roundedSelection: false,
    guides: {
      indentation: false
    },
    cursorWidth: 1,
    fontFamily: $91,
    ariaLabel: ariaLabel || "",
    snippetSuggestions: "none",
    suggest: { filterGraceful: false, showIcons: false },
    autoClosingBrackets: "never"
  };
}

// out-build/vs/workbench/contrib/preferences/common/settingsEditorColorRegistry.js
var $QZb = $5n("settings.headerForeground", { light: "#444444", dark: "#e7e7e7", hcDark: "#ffffff", hcLight: "#292929" }, localize(9051, null));
var $RZb = $5n("settings.settingsHeaderHoverForeground", $0n($QZb, 0.7), localize(9052, null));
var $SZb = $5n("settings.modifiedItemIndicator", {
  light: new $Vn(new $Sn(102, 175, 224)),
  dark: new $Vn(new $Sn(12, 125, 157)),
  hcDark: new $Vn(new $Sn(0, 73, 122)),
  hcLight: new $Vn(new $Sn(102, 175, 224))
}, localize(9053, null));
var $TZb = $5n("settings.headerBorder", $Jmb, localize(9054, null));
var $UZb = $5n("settings.sashBorder", $Jmb, localize(9055, null));
var $VZb = $5n(`settings.dropdownBackground`, $Oq, localize(9056, null));
var $WZb = $5n("settings.dropdownForeground", $Qq, localize(9057, null));
var $XZb = $5n("settings.dropdownBorder", $Rq, localize(9058, null));
var $YZb = $5n("settings.dropdownListBorder", $So, localize(9059, null));
var $ZZb = $5n("settings.checkboxBackground", $8q, localize(9060, null));
var $1Zb = $5n("settings.checkboxForeground", $0q, localize(9061, null));
var $2Zb = $5n("settings.checkboxBorder", $$q, localize(9062, null));
var $3Zb = $5n("settings.textInputBackground", $xq, localize(9063, null));
var $4Zb = $5n("settings.textInputForeground", $yq, localize(9064, null));
var $5Zb = $5n("settings.textInputBorder", $zq, localize(9065, null));
var $6Zb = $5n("settings.numberInputBackground", $xq, localize(9066, null));
var $7Zb = $5n("settings.numberInputForeground", $yq, localize(9067, null));
var $8Zb = $5n("settings.numberInputBorder", $zq, localize(9068, null));
var $9Zb = $5n("settings.focusedRowBackground", {
  dark: $0n($qr, 0.6),
  light: $0n($qr, 0.6),
  hcDark: null,
  hcLight: null
}, localize(9069, null));
var $0Zb = $5n("settings.rowHoverBackground", {
  dark: $0n($qr, 0.3),
  light: $0n($qr, 0.3),
  hcDark: null,
  hcLight: null
}, localize(9070, null));
var $$Zb = $5n("settings.focusedRowBorder", $jo, localize(9071, null));

// out-build/vs/workbench/contrib/preferences/browser/keybindingsEditor.js
var $_Zb_1;
var ActionsColumnRenderer_1;
var CommandColumnRenderer_1;
var SourceColumnRenderer_1;
var WhenColumnRenderer_1;
var $115 = $;
var $_Zb = class $_Zb2 extends $5tb {
  static {
    $_Zb_1 = this;
  }
  static {
    this.ID = "workbench.editor.keybindings";
  }
  constructor(group2, telemetryService, themeService, qb, rb, sb, tb, ub, vb, wb, xb, storageService, yb, zb) {
    super($_Zb_1.ID, group2, telemetryService, themeService, storageService);
    this.qb = qb;
    this.rb = rb;
    this.sb = sb;
    this.tb = tb;
    this.ub = ub;
    this.vb = vb;
    this.wb = wb;
    this.xb = xb;
    this.yb = yb;
    this.zb = zb;
    this.a = this.B(new $ze());
    this.onDefineWhenExpression = this.a.event;
    this.b = this.B(new $ze());
    this.onRejectWhenExpression = this.b.event;
    this.c = this.B(new $ze());
    this.onAcceptWhenExpression = this.c.event;
    this.f = this.B(new $ze());
    this.onLayout = this.f.event;
    this.g = null;
    this.db = null;
    this.eb = [];
    this.hb = null;
    this.jb = [];
    this.ib = new $Sh(300);
    this.B(qb.onDidUpdateKeybindings(() => this.Lb(!!this.lb.get())));
    this.kb = $$Yb.bindTo(this.tb);
    this.mb = $_Yb.bindTo(this.tb);
    this.lb = $aZb.bindTo(this.tb);
    this.s = new $Sh(500);
    this.ob = new $Um($fZb, localize(8717, null), ThemeIcon.asClassName($KYb));
    this.ob.checked = false;
    this.nb = new $Um($gZb, localize(8718, null), ThemeIcon.asClassName($LYb));
    this.nb.checked = false;
    this.overflowWidgetsDomNode = $115(".keybindings-overflow-widgets-container.monaco-editor");
  }
  create(parent) {
    super.create(parent);
    this.B($iKb({
      name: "keybindingsEditor",
      focusNotifiers: [this],
      focusNextWidget: () => {
        if (this.r.hasFocus()) {
          this.focusKeybindings();
        }
      },
      focusPreviousWidget: () => {
        if (!this.r.hasFocus()) {
          this.focusSearch();
        }
      }
    }));
  }
  Y(parent) {
    const keybindingsEditorElement = $bk(parent, $115("div", { class: "keybindings-editor" }));
    this.Bb(keybindingsEditorElement);
    this.Cb(keybindingsEditorElement);
    this.Fb(keybindingsEditorElement);
    this.Jb(keybindingsEditorElement);
  }
  setInput(input, options3, context, token) {
    this.kb.set(true);
    return super.setInput(input, options3, context, token).then(() => this.Lb(!!(options3 && options3.preserveFocus)));
  }
  clearInput() {
    super.clearInput();
    this.kb.reset();
    this.lb.reset();
  }
  layout(dimension) {
    this.hb = dimension;
    this.Ib(dimension);
    this.u.style.width = dimension.width + "px";
    this.u.style.height = dimension.height + "px";
    this.cb.layout(this.hb);
    this.Qb();
    this.f.fire();
  }
  focus() {
    super.focus();
    const activeKeybindingEntry = this.activeKeybindingEntry;
    if (activeKeybindingEntry) {
      this.Tb(activeKeybindingEntry);
    } else if (!$u) {
      this.r.focus();
    }
  }
  get activeKeybindingEntry() {
    const focusedElement = this.gb.getFocusedElements()[0];
    return focusedElement && focusedElement.templateId === $BVb ? focusedElement : null;
  }
  async defineKeybinding(keybindingEntry, add) {
    this.Tb(keybindingEntry);
    this.Db();
    try {
      const key2 = await this.cb.define();
      if (key2) {
        await this.updateKeybinding(keybindingEntry, key2, keybindingEntry.keybindingItem.when, add);
      }
    } catch (error) {
      this.ec(error);
    } finally {
      this.Eb();
      this.Tb(keybindingEntry);
    }
  }
  defineWhenExpression(keybindingEntry) {
    if (keybindingEntry.keybindingItem.keybinding) {
      this.Tb(keybindingEntry);
      this.a.fire(keybindingEntry);
    }
  }
  rejectWhenExpression(keybindingEntry) {
    this.b.fire(keybindingEntry);
  }
  acceptWhenExpression(keybindingEntry) {
    this.c.fire(keybindingEntry);
  }
  async updateKeybinding(keybindingEntry, key2, when, add) {
    const currentKey = keybindingEntry.keybindingItem.keybinding ? keybindingEntry.keybindingItem.keybinding.getUserSettingsLabel() : "";
    if (currentKey !== key2 || keybindingEntry.keybindingItem.when !== when) {
      if (add) {
        await this.sb.addKeybinding(keybindingEntry.keybindingItem.keybindingItem, key2, when || void 0);
      } else {
        await this.sb.editKeybinding(keybindingEntry.keybindingItem.keybindingItem, key2, when || void 0);
      }
      if (!keybindingEntry.keybindingItem.keybinding) {
        this.db = keybindingEntry;
      }
    }
  }
  async removeKeybinding(keybindingEntry) {
    this.Tb(keybindingEntry);
    if (keybindingEntry.keybindingItem.keybinding) {
      try {
        await this.sb.removeKeybinding(keybindingEntry.keybindingItem.keybindingItem);
        this.focus();
      } catch (error) {
        this.ec(error);
        this.Tb(keybindingEntry);
      }
    }
  }
  async resetKeybinding(keybindingEntry) {
    this.Tb(keybindingEntry);
    try {
      await this.sb.resetKeybinding(keybindingEntry.keybindingItem.keybindingItem);
      if (!keybindingEntry.keybindingItem.keybinding) {
        this.db = keybindingEntry;
      }
      this.Tb(keybindingEntry);
    } catch (error) {
      this.ec(error);
      this.Tb(keybindingEntry);
    }
  }
  async copyKeybinding(keybinding) {
    this.Tb(keybinding);
    const userFriendlyKeybinding = {
      key: keybinding.keybindingItem.keybinding ? keybinding.keybindingItem.keybinding.getUserSettingsLabel() || "" : "",
      command: keybinding.keybindingItem.command
    };
    if (keybinding.keybindingItem.when) {
      userFriendlyKeybinding.when = keybinding.keybindingItem.when;
    }
    await this.vb.writeText(JSON.stringify(userFriendlyKeybinding, null, "  "));
  }
  async copyKeybindingCommand(keybinding) {
    this.Tb(keybinding);
    await this.vb.writeText(keybinding.keybindingItem.command);
  }
  async copyKeybindingCommandTitle(keybinding) {
    this.Tb(keybinding);
    await this.vb.writeText(keybinding.keybindingItem.commandLabel);
  }
  focusSearch() {
    this.r.focus();
  }
  search(filter) {
    this.focusSearch();
    this.r.setValue(filter);
    this.Tb(0);
  }
  clearSearchResults() {
    this.r.clear();
  }
  showSimilarKeybindings(keybindingEntry) {
    const value = `"${keybindingEntry.keybindingItem.keybinding.getAriaLabel()}"`;
    if (value !== this.r.getValue()) {
      this.r.setValue(value);
    }
  }
  Bb(parent) {
    this.pb = $bk(parent, $(""));
    this.pb.setAttribute("id", "keybindings-editor-aria-label-element");
    this.pb.setAttribute("aria-live", "assertive");
  }
  Cb(parent) {
    this.u = $bk(parent, $115(".overlay-container"));
    this.u.style.position = "absolute";
    this.u.style.zIndex = "40";
    this.cb = this.B(this.wb.createInstance($ZYb, this.u));
    this.B(this.cb.onDidChange((keybindingStr) => this.cb.printExisting(this.g.fetch(`"${keybindingStr}"`).length)));
    this.B(this.cb.onShowExistingKeybidings((keybindingStr) => this.r.setValue(`"${keybindingStr}"`)));
    this.Eb();
  }
  Db() {
    this.u.style.display = "block";
  }
  Eb() {
    this.u.style.display = "none";
  }
  Fb(parent) {
    this.j = $bk(parent, $115(".keybindings-header"));
    const fullTextSearchPlaceholder = localize(8719, null);
    const keybindingsSearchPlaceholder = localize(8720, null);
    const clearInputAction = new $Um($dZb, localize(8721, null), ThemeIcon.asClassName($RYb), false, async () => this.clearSearchResults());
    const searchContainer = $bk(this.j, $115(".search-container"));
    this.r = this.B(this.wb.createInstance($YYb, searchContainer, {
      ariaLabel: fullTextSearchPlaceholder,
      placeholder: fullTextSearchPlaceholder,
      focusKey: this.mb,
      ariaLabelledBy: "keybindings-editor-aria-label-element",
      recordEnter: true,
      quoteRecordedKeys: true,
      history: this.F(
        0,
        0
        /* StorageTarget.USER */
      )["searchHistory"] || [],
      inputBoxStyles: $C$({
        inputBorder: $5Zb
      })
    }));
    this.B(this.r.onDidChange((searchValue) => {
      clearInputAction.enabled = !!searchValue;
      this.ib.trigger(() => this.Nb());
      this.Gb();
    }));
    this.B(this.r.onEscape(() => this.ob.checked = false));
    this.m = $bk(searchContainer, $(".keybindings-search-actions-container"));
    const recordingBadge = this.Hb(this.m);
    this.B(this.nb.onDidChange((e) => {
      if (e.checked !== void 0) {
        this.Ob(false);
      }
      this.Gb();
    }));
    this.B(this.ob.onDidChange((e) => {
      if (e.checked !== void 0) {
        recordingBadge.classList.toggle("disabled", !e.checked);
        if (e.checked) {
          this.r.inputBox.setPlaceHolder(keybindingsSearchPlaceholder);
          this.r.inputBox.setAriaLabel(keybindingsSearchPlaceholder);
          this.r.startRecordingKeys();
          this.r.focus();
        } else {
          this.r.inputBox.setPlaceHolder(fullTextSearchPlaceholder);
          this.r.inputBox.setAriaLabel(fullTextSearchPlaceholder);
          this.r.stopRecordingKeys();
          this.r.focus();
        }
        this.Gb();
      }
    }));
    const actions = [this.ob, this.nb, clearInputAction];
    const toolBar = this.B(new $f3(this.m, this.rb, {
      actionViewItemProvider: (action, options3) => {
        if (action.id === this.nb.id || action.id === this.ob.id) {
          return new $P1(null, action, { ...options3, keybinding: this.qb.lookupKeybinding(action.id)?.getLabel(), toggleStyles: $u$ });
        }
        return void 0;
      },
      getKeyBinding: (action) => this.qb.lookupKeybinding(action.id)
    }));
    toolBar.setActions(actions);
    this.B(this.qb.onDidUpdateKeybindings(() => toolBar.setActions(actions)));
  }
  Gb() {
    const keybindingsEditorInput = this.input;
    if (keybindingsEditorInput) {
      keybindingsEditorInput.searchOptions = {
        searchValue: this.r.getValue(),
        recordKeybindings: !!this.ob.checked,
        sortByPrecedence: !!this.nb.checked
      };
    }
  }
  Hb(container2) {
    const recordingBadge = $bk(container2, $(".recording-badge.monaco-count-badge.long.disabled"));
    recordingBadge.textContent = localize(8722, null);
    recordingBadge.style.backgroundColor = $Zn($wo);
    recordingBadge.style.color = $Zn($xo);
    recordingBadge.style.border = `1px solid ${$Zn($ko)}`;
    return recordingBadge;
  }
  Ib(dimension) {
    this.r.layout(dimension);
    this.j.classList.toggle("small", dimension.width < 400);
    this.r.inputBox.inputElement.style.paddingRight = `${$xj(this.m) + 12}px`;
  }
  Jb(parent) {
    const bodyContainer = $bk(parent, $115(".keybindings-body"));
    this.Kb(bodyContainer);
  }
  Kb(parent) {
    this.fb = $bk(parent, $115(".keybindings-table-container"));
    this.gb = this.B(this.wb.createInstance($Yeb, "KeybindingsEditor", this.fb, new Delegate(), [
      {
        label: "",
        tooltip: "",
        weight: 0,
        minimumWidth: 40,
        maximumWidth: 40,
        templateId: ActionsColumnRenderer.TEMPLATE_ID,
        project(row) {
          return row;
        }
      },
      {
        label: localize(8723, null),
        tooltip: "",
        weight: 0.3,
        templateId: CommandColumnRenderer.TEMPLATE_ID,
        project(row) {
          return row;
        }
      },
      {
        label: localize(8724, null),
        tooltip: "",
        weight: 0.2,
        templateId: KeybindingColumnRenderer.TEMPLATE_ID,
        project(row) {
          return row;
        }
      },
      {
        label: localize(8725, null),
        tooltip: "",
        weight: 0.35,
        templateId: WhenColumnRenderer.TEMPLATE_ID,
        project(row) {
          return row;
        }
      },
      {
        label: localize(8726, null),
        tooltip: "",
        weight: 0.15,
        templateId: SourceColumnRenderer.TEMPLATE_ID,
        project(row) {
          return row;
        }
      }
    ], [
      this.wb.createInstance(ActionsColumnRenderer, this),
      this.wb.createInstance(CommandColumnRenderer),
      this.wb.createInstance(KeybindingColumnRenderer),
      this.wb.createInstance(WhenColumnRenderer, this),
      this.wb.createInstance(SourceColumnRenderer)
    ], {
      identityProvider: { getId: (e) => e.id },
      horizontalScrolling: false,
      accessibilityProvider: new AccessibilityProvider(this.yb),
      keyboardNavigationLabelProvider: { getKeyboardNavigationLabel: (e) => e.keybindingItem.commandLabel || e.keybindingItem.command },
      overrideStyles: {
        listBackground: $Ko
      },
      multipleSelectionSupport: false,
      setRowLineHeight: false,
      openOnSingleClick: false,
      transformOptimization: false
      // disable transform optimization as it causes the editor overflow widgets to be mispositioned
    }));
    this.B(this.gb.onContextMenu((e) => this.Ub(e)));
    this.B(this.gb.onDidChangeFocus((e) => this.Vb()));
    this.B(this.gb.onDidFocus(() => {
      this.gb.getHTMLElement().classList.add("focused");
      this.Vb();
    }));
    this.B(this.gb.onDidBlur(() => {
      this.gb.getHTMLElement().classList.remove("focused");
      this.lb.reset();
    }));
    this.B(this.gb.onDidOpen((e) => {
      if (e.browserEvent?.defaultPrevented) {
        return;
      }
      const activeKeybindingEntry = this.activeKeybindingEntry;
      if (activeKeybindingEntry) {
        this.defineKeybinding(activeKeybindingEntry, false);
      }
    }));
    $bk(this.fb, this.overflowWidgetsDomNode);
  }
  async Lb(preserveFocus) {
    if (this.input) {
      const input = this.input;
      this.g = await input.resolve();
      await this.g.resolve(this.Mb());
      this.Ob(false, preserveFocus);
      if (input.searchOptions) {
        this.ob.checked = input.searchOptions.recordKeybindings;
        this.nb.checked = input.searchOptions.sortByPrecedence;
        this.r.setValue(input.searchOptions.searchValue);
      } else {
        this.Gb();
      }
    }
  }
  Mb() {
    const actionsLabels = /* @__PURE__ */ new Map();
    for (const editorAction of EditorExtensionsRegistry.getEditorActions()) {
      actionsLabels.set(editorAction.id, editorAction.label);
    }
    for (const menuItem of $dJ.getMenuItems($bJ.CommandPalette)) {
      if ($_I(menuItem)) {
        const title = typeof menuItem.command.title === "string" ? menuItem.command.title : menuItem.command.title.value;
        const category8 = menuItem.command.category ? typeof menuItem.command.category === "string" ? menuItem.command.category : menuItem.command.category.value : void 0;
        actionsLabels.set(menuItem.command.id, category8 ? `${category8}: ${title}` : title);
      }
    }
    return actionsLabels;
  }
  Nb() {
    this.Ob(this.r.hasFocus());
    this.s.trigger(() => {
      this.r.inputBox.addToHistory();
      this.F(
        0,
        0
        /* StorageTarget.USER */
      )["searchHistory"] = this.r.inputBox.getHistory();
      this.I();
    });
  }
  clearKeyboardShortcutSearchHistory() {
    this.r.inputBox.clearHistory();
    this.F(
      0,
      0
      /* StorageTarget.USER */
    )["searchHistory"] = this.r.inputBox.getHistory();
    this.I();
  }
  Ob(reset, preserveFocus) {
    if (this.g) {
      const filter = this.r.getValue();
      const keybindingsEntries = this.g.fetch(filter, this.nb.checked);
      this.zb.alert(localize(8727, null, keybindingsEntries.length));
      this.pb.setAttribute("aria-label", this.Pb(keybindingsEntries));
      if (keybindingsEntries.length === 0) {
        this.jb.push(filter);
      }
      const currentSelectedIndex = this.gb.getSelection()[0];
      this.eb = keybindingsEntries;
      this.gb.splice(0, this.gb.length, this.eb);
      this.Qb();
      if (reset) {
        this.gb.setSelection([]);
        this.gb.setFocus([]);
      } else {
        if (this.db) {
          const index = this.Sb(this.db);
          if (index !== -1) {
            this.gb.reveal(index, 0.2);
            this.Tb(index);
          }
          this.db = null;
        } else if (currentSelectedIndex !== -1 && currentSelectedIndex < this.eb.length) {
          this.Tb(currentSelectedIndex, preserveFocus);
        } else if (this.xb.activeEditorPane === this && !preserveFocus) {
          this.focus();
        }
      }
    }
  }
  Pb(keybindingsEntries) {
    if (this.nb.checked) {
      return localize(8728, null, keybindingsEntries.length);
    } else {
      return localize(8729, null, keybindingsEntries.length);
    }
  }
  Qb() {
    if (!this.hb) {
      return;
    }
    const tableHeight = this.hb.height - ($vj(this.j).height + 12);
    this.fb.style.height = `${tableHeight}px`;
    this.gb.layout(tableHeight);
  }
  Rb(listEntry) {
    const index = this.eb.indexOf(listEntry);
    if (index === -1) {
      for (let i2 = 0; i2 < this.eb.length; i2++) {
        if (this.eb[i2].id === listEntry.id) {
          return i2;
        }
      }
    }
    return index;
  }
  Sb(unassignedKeybinding) {
    for (let index = 0; index < this.eb.length; index++) {
      const entry = this.eb[index];
      if (entry.templateId === $BVb) {
        const keybindingItemEntry = entry;
        if (keybindingItemEntry.keybindingItem.command === unassignedKeybinding.keybindingItem.command) {
          return index;
        }
      }
    }
    return -1;
  }
  Tb(keybindingItemEntry, focus = true) {
    const index = typeof keybindingItemEntry === "number" ? keybindingItemEntry : this.Rb(keybindingItemEntry);
    if (index !== -1 && index < this.gb.length) {
      if (focus) {
        this.gb.domFocus();
        this.gb.setFocus([index]);
      }
      this.gb.setSelection([index]);
    }
  }
  focusKeybindings() {
    this.gb.domFocus();
    const currentFocusIndices = this.gb.getFocus();
    this.gb.setFocus([currentFocusIndices.length ? currentFocusIndices[0] : 0]);
  }
  selectKeybinding(keybindingItemEntry) {
    this.Tb(keybindingItemEntry);
  }
  recordSearchKeys() {
    this.ob.checked = true;
  }
  toggleSortByPrecedence() {
    this.nb.checked = !this.nb.checked;
  }
  Ub(e) {
    if (!e.element) {
      return;
    }
    if (e.element.templateId === $BVb) {
      const keybindingItemEntry = e.element;
      this.Tb(keybindingItemEntry);
      this.rb.showContextMenu({
        getAnchor: () => e.anchor,
        getActions: () => [
          this.bc(keybindingItemEntry),
          this.cc(keybindingItemEntry),
          this.dc(keybindingItemEntry),
          new $Wm(),
          ...keybindingItemEntry.keybindingItem.keybinding ? [this.Wb(keybindingItemEntry), this.Xb(keybindingItemEntry)] : [this.Wb(keybindingItemEntry)],
          new $Wm(),
          this.Zb(keybindingItemEntry),
          this.$b(keybindingItemEntry),
          new $Wm(),
          this.Yb(keybindingItemEntry),
          new $Wm(),
          this.ac(keybindingItemEntry)
        ]
      });
    }
  }
  Vb() {
    this.lb.reset();
    const element = this.gb.getFocusedElements()[0];
    if (!element) {
      return;
    }
    if (element.templateId === $BVb) {
      this.lb.set(true);
    }
  }
  Wb(keybindingItemEntry) {
    return {
      label: keybindingItemEntry.keybindingItem.keybinding ? localize(8730, null) : localize(8731, null),
      enabled: true,
      id: $hZb,
      run: () => this.defineKeybinding(keybindingItemEntry, false)
    };
  }
  Xb(keybindingItemEntry) {
    return {
      label: localize(8732, null),
      enabled: true,
      id: $iZb,
      run: () => this.defineKeybinding(keybindingItemEntry, true)
    };
  }
  Yb(keybindingItemEntry) {
    return {
      label: localize(8733, null),
      enabled: !!keybindingItemEntry.keybindingItem.keybinding,
      id: $jZb,
      run: () => this.defineWhenExpression(keybindingItemEntry)
    };
  }
  Zb(keybindingItem) {
    return {
      label: localize(8734, null),
      enabled: !!keybindingItem.keybindingItem.keybinding,
      id: $mZb,
      run: () => this.removeKeybinding(keybindingItem)
    };
  }
  $b(keybindingItem) {
    return {
      label: localize(8735, null),
      enabled: !keybindingItem.keybindingItem.keybindingItem.isDefault,
      id: $nZb,
      run: () => this.resetKeybinding(keybindingItem)
    };
  }
  ac(keybindingItem) {
    return {
      label: localize(8736, null),
      enabled: !!keybindingItem.keybindingItem.keybinding,
      id: $rZb,
      run: () => this.showSimilarKeybindings(keybindingItem)
    };
  }
  bc(keybindingItem) {
    return {
      label: localize(8737, null),
      enabled: true,
      id: $oZb,
      run: () => this.copyKeybinding(keybindingItem)
    };
  }
  cc(keybinding) {
    return {
      label: localize(8738, null),
      enabled: true,
      id: $pZb,
      run: () => this.copyKeybindingCommand(keybinding)
    };
  }
  dc(keybinding) {
    return {
      label: localize(8739, null),
      enabled: !!keybinding.keybindingItem.commandLabel,
      id: $qZb,
      run: () => this.copyKeybindingCommandTitle(keybinding)
    };
  }
  ec(error) {
    this.ub.error(typeof error === "string" ? error : localize(8740, null, `${error}`));
  }
};
$_Zb = $_Zb_1 = __decorate([
  __param(1, $zv),
  __param(2, $gs),
  __param(3, $Ty),
  __param(4, $50),
  __param(5, $pVb),
  __param(6, $on),
  __param(7, $PJ),
  __param(8, $30),
  __param(9, $Pk),
  __param(10, $mJ),
  __param(11, $jv),
  __param(12, $kl),
  __param(13, $ND)
], $_Zb);
var Delegate = class {
  constructor() {
    this.headerRowHeight = 30;
  }
  getHeight(element) {
    if (element.templateId === $BVb) {
      const commandIdMatched = element.keybindingItem.commandLabel && element.commandIdMatches;
      const commandDefaultLabelMatched = !!element.commandDefaultLabelMatches;
      const extensionIdMatched = !!element.extensionIdMatches;
      if (commandIdMatched && commandDefaultLabelMatched) {
        return 60;
      }
      if (extensionIdMatched || commandIdMatched || commandDefaultLabelMatched) {
        return 40;
      }
    }
    return 24;
  }
};
var ActionsColumnRenderer = class ActionsColumnRenderer2 {
  static {
    ActionsColumnRenderer_1 = this;
  }
  static {
    this.TEMPLATE_ID = "actions";
  }
  constructor(a, b) {
    this.a = a;
    this.b = b;
    this.templateId = ActionsColumnRenderer_1.TEMPLATE_ID;
  }
  renderTemplate(container2) {
    const element = $bk(container2, $115(".actions"));
    const actionBar = new $LZ(element);
    return { actionBar };
  }
  renderElement(keybindingItemEntry, index, templateData, height) {
    templateData.actionBar.clear();
    const actions = [];
    if (keybindingItemEntry.keybindingItem.keybinding) {
      actions.push(this.c(keybindingItemEntry));
    } else {
      actions.push(this.d(keybindingItemEntry));
    }
    templateData.actionBar.push(actions, { icon: true });
  }
  c(keybindingItemEntry) {
    const keybinding = this.b.lookupKeybinding($hZb);
    return {
      class: ThemeIcon.asClassName($MYb),
      enabled: true,
      id: "editKeybinding",
      tooltip: keybinding ? localize(8741, null, `(${keybinding.getLabel()})`) : localize(8742, null),
      run: () => this.a.defineKeybinding(keybindingItemEntry, false)
    };
  }
  d(keybindingItemEntry) {
    const keybinding = this.b.lookupKeybinding($hZb);
    return {
      class: ThemeIcon.asClassName($NYb),
      enabled: true,
      id: "addKeybinding",
      tooltip: keybinding ? localize(8743, null, `(${keybinding.getLabel()})`) : localize(8744, null),
      run: () => this.a.defineKeybinding(keybindingItemEntry, false)
    };
  }
  disposeTemplate(templateData) {
    templateData.actionBar.dispose();
  }
};
ActionsColumnRenderer = ActionsColumnRenderer_1 = __decorate([
  __param(1, $Ty)
], ActionsColumnRenderer);
var CommandColumnRenderer = class CommandColumnRenderer2 {
  static {
    CommandColumnRenderer_1 = this;
  }
  static {
    this.TEMPLATE_ID = "commands";
  }
  constructor(a) {
    this.a = a;
    this.templateId = CommandColumnRenderer_1.TEMPLATE_ID;
  }
  renderTemplate(container2) {
    const commandColumn = $bk(container2, $115(".command"));
    const commandColumnHover = this.a.setupManagedHover($JZ("mouse"), commandColumn, "");
    const commandLabelContainer = $bk(commandColumn, $115(".command-label"));
    const commandLabel = new $S2(commandLabelContainer);
    const commandDefaultLabelContainer = $bk(commandColumn, $115(".command-default-label"));
    const commandDefaultLabel = new $S2(commandDefaultLabelContainer);
    const commandIdLabelContainer = $bk(commandColumn, $115(".command-id.code"));
    const commandIdLabel = new $S2(commandIdLabelContainer);
    return { commandColumn, commandColumnHover, commandLabelContainer, commandLabel, commandDefaultLabelContainer, commandDefaultLabel, commandIdLabelContainer, commandIdLabel };
  }
  renderElement(keybindingItemEntry, index, templateData, height) {
    const keybindingItem = keybindingItemEntry.keybindingItem;
    const commandIdMatched = !!(keybindingItem.commandLabel && keybindingItemEntry.commandIdMatches);
    const commandDefaultLabelMatched = !!keybindingItemEntry.commandDefaultLabelMatches;
    templateData.commandColumn.classList.toggle("vertical-align-column", commandIdMatched || commandDefaultLabelMatched);
    const title = keybindingItem.commandLabel ? localize(8745, null, keybindingItem.commandLabel, keybindingItem.command) : keybindingItem.command;
    templateData.commandColumn.setAttribute("aria-label", title);
    templateData.commandColumnHover.update(title);
    if (keybindingItem.commandLabel) {
      templateData.commandLabelContainer.classList.remove("hide");
      templateData.commandLabel.set(keybindingItem.commandLabel, keybindingItemEntry.commandLabelMatches);
    } else {
      templateData.commandLabelContainer.classList.add("hide");
      templateData.commandLabel.set(void 0);
    }
    if (keybindingItemEntry.commandDefaultLabelMatches) {
      templateData.commandDefaultLabelContainer.classList.remove("hide");
      templateData.commandDefaultLabel.set(keybindingItem.commandDefaultLabel, keybindingItemEntry.commandDefaultLabelMatches);
    } else {
      templateData.commandDefaultLabelContainer.classList.add("hide");
      templateData.commandDefaultLabel.set(void 0);
    }
    if (keybindingItemEntry.commandIdMatches || !keybindingItem.commandLabel) {
      templateData.commandIdLabelContainer.classList.remove("hide");
      templateData.commandIdLabel.set(keybindingItem.command, keybindingItemEntry.commandIdMatches);
    } else {
      templateData.commandIdLabelContainer.classList.add("hide");
      templateData.commandIdLabel.set(void 0);
    }
  }
  disposeTemplate(templateData) {
    templateData.commandColumnHover.dispose();
    templateData.commandDefaultLabel.dispose();
    templateData.commandIdLabel.dispose();
    templateData.commandLabel.dispose();
  }
};
CommandColumnRenderer = CommandColumnRenderer_1 = __decorate([
  __param(0, $5$)
], CommandColumnRenderer);
var KeybindingColumnRenderer = class _KeybindingColumnRenderer {
  static {
    this.TEMPLATE_ID = "keybindings";
  }
  constructor() {
    this.templateId = _KeybindingColumnRenderer.TEMPLATE_ID;
  }
  renderTemplate(container2) {
    const element = $bk(container2, $115(".keybinding"));
    const keybindingLabel = new $32($bk(element, $115("div.keybinding-label")), OS, $o$);
    return { keybindingLabel };
  }
  renderElement(keybindingItemEntry, index, templateData, height) {
    if (keybindingItemEntry.keybindingItem.keybinding) {
      templateData.keybindingLabel.set(keybindingItemEntry.keybindingItem.keybinding, keybindingItemEntry.keybindingMatches);
    } else {
      templateData.keybindingLabel.set(void 0, void 0);
    }
  }
  disposeTemplate(templateData) {
    templateData.keybindingLabel.dispose();
  }
};
function onClick(element, callback) {
  const disposables = new $2c();
  disposables.add($_i(element, $7j.CLICK, $kk(callback)));
  disposables.add($_i(element, $7j.KEY_UP, (e) => {
    const keyboardEvent = new $if(e);
    if (keyboardEvent.equals(
      10
      /* KeyCode.Space */
    ) || keyboardEvent.equals(
      3
      /* KeyCode.Enter */
    )) {
      e.preventDefault();
      e.stopPropagation();
      callback();
    }
  }));
  return disposables;
}
var SourceColumnRenderer = class SourceColumnRenderer2 {
  static {
    SourceColumnRenderer_1 = this;
  }
  static {
    this.TEMPLATE_ID = "source";
  }
  constructor(a, b) {
    this.a = a;
    this.b = b;
    this.templateId = SourceColumnRenderer_1.TEMPLATE_ID;
  }
  renderTemplate(container2) {
    const sourceColumn = $bk(container2, $115(".source"));
    const sourceColumnHover = this.b.setupManagedHover($JZ("mouse"), sourceColumn, "");
    const sourceLabel = new $S2($bk(sourceColumn, $115(".source-label")));
    const extensionContainer = $bk(sourceColumn, $115(".extension-container"));
    const extensionLabel = $bk(extensionContainer, $115("a.extension-label", { tabindex: 0 }));
    const extensionId = new $S2($bk(extensionContainer, $115(".extension-id-container.code")));
    return { sourceColumn, sourceColumnHover, sourceLabel, extensionLabel, extensionContainer, extensionId, disposables: new $2c() };
  }
  renderElement(keybindingItemEntry, index, templateData, height) {
    templateData.disposables.clear();
    if ($zg(keybindingItemEntry.keybindingItem.source)) {
      templateData.extensionContainer.classList.add("hide");
      templateData.sourceLabel.element.classList.remove("hide");
      templateData.sourceColumnHover.update("");
      templateData.sourceLabel.set(keybindingItemEntry.keybindingItem.source || "-", keybindingItemEntry.sourceMatches);
    } else {
      templateData.extensionContainer.classList.remove("hide");
      templateData.sourceLabel.element.classList.add("hide");
      const extension = keybindingItemEntry.keybindingItem.source;
      const extensionLabel = extension.displayName ?? extension.identifier.value;
      templateData.sourceColumnHover.update(localize(8746, null, extensionLabel));
      templateData.extensionLabel.textContent = extensionLabel;
      templateData.disposables.add(onClick(templateData.extensionLabel, () => {
        this.a.open(extension.identifier.value);
      }));
      if (keybindingItemEntry.extensionIdMatches) {
        templateData.extensionId.element.classList.remove("hide");
        templateData.extensionId.set(extension.identifier.value, keybindingItemEntry.extensionIdMatches);
      } else {
        templateData.extensionId.element.classList.add("hide");
        templateData.extensionId.set(void 0);
      }
    }
  }
  disposeTemplate(templateData) {
    templateData.sourceColumnHover.dispose();
    templateData.disposables.dispose();
    templateData.sourceLabel.dispose();
    templateData.extensionId.dispose();
  }
};
SourceColumnRenderer = SourceColumnRenderer_1 = __decorate([
  __param(0, $vzb),
  __param(1, $5$)
], SourceColumnRenderer);
var WhenInputWidget = class WhenInputWidget2 extends $3c {
  constructor(parent, keybindingsEditor, instantiationService, contextKeyService) {
    super();
    this.b = this.B(new $ze());
    this.onDidAccept = this.b.event;
    this.c = this.B(new $ze());
    this.onDidReject = this.c.event;
    const focusContextKey = $bZb.bindTo(contextKeyService);
    this.a = this.B(instantiationService.createInstance($NZb, "keyboardshortcutseditor#wheninput", parent, {
      provideResults: () => {
        const result = [];
        for (const contextKey of $nn.all()) {
          result.push({
            label: contextKey.key,
            documentation: contextKey.description,
            detail: contextKey.type,
            kind: 14
            /* CompletionItemKind.Constant */
          });
        }
        return result;
      },
      triggerCharacters: ["!", " "],
      wordDefinition: /[a-zA-Z.]+/,
      alwaysShowSuggestions: true
    }, "", `keyboardshortcutseditor#wheninput`, { focusContextKey, overflowWidgetsDomNode: keybindingsEditor.overflowWidgetsDomNode }));
    this.B($_i(this.a.element, $7j.DBLCLICK, (e) => $9j.stop(e)));
    this.B($1c(() => focusContextKey.reset()));
    this.B(keybindingsEditor.onAcceptWhenExpression(() => this.b.fire(this.a.getValue())));
    this.B(Event2.any(keybindingsEditor.onRejectWhenExpression, this.a.onDidBlur)(() => this.c.fire()));
  }
  layout(dimension) {
    this.a.layout(dimension);
  }
  show(value) {
    this.a.setValue(value);
    this.a.focus(true);
  }
};
WhenInputWidget = __decorate([
  __param(2, $Pk),
  __param(3, $on)
], WhenInputWidget);
var WhenColumnRenderer = class WhenColumnRenderer2 {
  static {
    WhenColumnRenderer_1 = this;
  }
  static {
    this.TEMPLATE_ID = "when";
  }
  constructor(a, b, c) {
    this.a = a;
    this.b = b;
    this.c = c;
    this.templateId = WhenColumnRenderer_1.TEMPLATE_ID;
  }
  renderTemplate(container2) {
    const element = $bk(container2, $115(".when"));
    const whenLabelContainer = $bk(element, $115("div.when-label"));
    const whenLabel = new $S2(whenLabelContainer);
    const whenInputContainer = $bk(element, $115("div.when-input-container"));
    return {
      element,
      whenLabelContainer,
      whenLabel,
      whenInputContainer,
      disposables: new $2c()
    };
  }
  renderElement(keybindingItemEntry, index, templateData, height) {
    templateData.disposables.clear();
    const whenInputDisposables = templateData.disposables.add(new $2c());
    templateData.disposables.add(this.a.onDefineWhenExpression((e) => {
      if (keybindingItemEntry === e) {
        templateData.element.classList.add("input-mode");
        const inputWidget = whenInputDisposables.add(this.c.createInstance(WhenInputWidget, templateData.whenInputContainer, this.a));
        inputWidget.layout(new $rj(templateData.element.parentElement.clientWidth, 18));
        inputWidget.show(keybindingItemEntry.keybindingItem.when || "");
        const hideInputWidget = () => {
          whenInputDisposables.clear();
          templateData.element.classList.remove("input-mode");
          templateData.element.parentElement.style.paddingLeft = "10px";
          $$i(templateData.whenInputContainer);
        };
        whenInputDisposables.add(inputWidget.onDidAccept((value) => {
          hideInputWidget();
          this.a.updateKeybinding(keybindingItemEntry, keybindingItemEntry.keybindingItem.keybinding ? keybindingItemEntry.keybindingItem.keybinding.getUserSettingsLabel() || "" : "", value);
          this.a.selectKeybinding(keybindingItemEntry);
        }));
        whenInputDisposables.add(inputWidget.onDidReject(() => {
          hideInputWidget();
          this.a.selectKeybinding(keybindingItemEntry);
        }));
        templateData.element.parentElement.style.paddingLeft = "0px";
      }
    }));
    templateData.whenLabelContainer.classList.toggle("code", !!keybindingItemEntry.keybindingItem.when);
    templateData.whenLabelContainer.classList.toggle("empty", !keybindingItemEntry.keybindingItem.when);
    if (keybindingItemEntry.keybindingItem.when) {
      templateData.whenLabel.set(keybindingItemEntry.keybindingItem.when, keybindingItemEntry.whenMatches, keybindingItemEntry.keybindingItem.when);
      templateData.disposables.add(this.b.setupManagedHover($JZ("mouse"), templateData.element, keybindingItemEntry.keybindingItem.when));
    } else {
      templateData.whenLabel.set("-");
    }
  }
  disposeTemplate(templateData) {
    templateData.disposables.dispose();
    templateData.whenLabel.dispose();
  }
};
WhenColumnRenderer = WhenColumnRenderer_1 = __decorate([
  __param(1, $5$),
  __param(2, $Pk)
], WhenColumnRenderer);
var AccessibilityProvider = class {
  constructor(a) {
    this.a = a;
  }
  getWidgetAriaLabel() {
    return localize(8747, null);
  }
  getAriaLabel({ keybindingItem }) {
    const ariaLabel = [
      keybindingItem.commandLabel ? keybindingItem.commandLabel : keybindingItem.command,
      keybindingItem.keybinding?.getAriaLabel() || localize(8748, null),
      keybindingItem.when ? keybindingItem.when : localize(8749, null),
      $zg(keybindingItem.source) ? keybindingItem.source : keybindingItem.source.description ?? keybindingItem.source.identifier.value
    ];
    if (this.a.getValue(
      "accessibility.verbosity.keybindingsEditor"
      /* AccessibilityVerbositySettingId.KeybindingsEditor */
    )) {
      const kbEditorAriaLabel = localize(8750, null);
      ariaLabel.push(kbEditorAriaLabel);
    }
    return ariaLabel.join(", ");
  }
};
$5n("keybindingTable.headerBackground", $Jr, "Background color for the keyboard shortcuts table header.");
$5n("keybindingTable.rowsBackground", $Jr, "Background color for the keyboard shortcuts table alternating rows.");
$ms((theme, collector) => {
  const foregroundColor = theme.getColor($eo);
  if (foregroundColor) {
    const whenForegroundColor = foregroundColor.transparent(0.8).makeOpaque($4lb(theme));
    collector.addRule(`.keybindings-editor > .keybindings-body > .keybindings-table-container .monaco-table .monaco-table-tr .monaco-table-td .code { color: ${whenForegroundColor}; }`);
  }
  const listActiveSelectionForegroundColor = theme.getColor($jr);
  const listActiveSelectionBackgroundColor = theme.getColor($ir);
  if (listActiveSelectionForegroundColor && listActiveSelectionBackgroundColor) {
    const whenForegroundColor = listActiveSelectionForegroundColor.transparent(0.8).makeOpaque(listActiveSelectionBackgroundColor);
    collector.addRule(`.keybindings-editor > .keybindings-body > .keybindings-table-container .monaco-table.focused .monaco-list-row.selected .monaco-table-tr .monaco-table-td .code { color: ${whenForegroundColor}; }`);
  }
  const listInactiveSelectionForegroundColor = theme.getColor($mr);
  const listInactiveSelectionBackgroundColor = theme.getColor($lr);
  if (listInactiveSelectionForegroundColor && listInactiveSelectionBackgroundColor) {
    const whenForegroundColor = listInactiveSelectionForegroundColor.transparent(0.8).makeOpaque(listInactiveSelectionBackgroundColor);
    collector.addRule(`.keybindings-editor > .keybindings-body > .keybindings-table-container .monaco-table .monaco-list-row.selected .monaco-table-tr .monaco-table-td .code { color: ${whenForegroundColor}; }`);
  }
  const listFocusForegroundColor = theme.getColor($fr);
  const listFocusBackgroundColor = theme.getColor($er);
  if (listFocusForegroundColor && listFocusBackgroundColor) {
    const whenForegroundColor = listFocusForegroundColor.transparent(0.8).makeOpaque(listFocusBackgroundColor);
    collector.addRule(`.keybindings-editor > .keybindings-body > .keybindings-table-container .monaco-table.focused .monaco-list-row.focused .monaco-table-tr .monaco-table-td .code { color: ${whenForegroundColor}; }`);
  }
  const listHoverForegroundColor = theme.getColor($rr);
  const listHoverBackgroundColor = theme.getColor($qr);
  if (listHoverForegroundColor && listHoverBackgroundColor) {
    const whenForegroundColor = listHoverForegroundColor.transparent(0.8).makeOpaque(listHoverBackgroundColor);
    collector.addRule(`.keybindings-editor > .keybindings-body > .keybindings-table-container .monaco-table.focused .monaco-list-row:hover:not(.focused):not(.selected) .monaco-table-tr .monaco-table-td .code { color: ${whenForegroundColor}; }`);
  }
});

// out-build/vs/workbench/contrib/preferences/browser/preferencesActions.js
var $a1b = class $a1b2 extends $Um {
  static {
    this.ID = "workbench.action.configureLanguageBasedSettings";
  }
  static {
    this.LABEL = localize2(8817, "Configure Language Specific Settings...");
  }
  constructor(id2, label3, a, b, c, f) {
    super(id2, label3);
    this.a = a;
    this.b = b;
    this.c = c;
    this.f = f;
  }
  async run() {
    const languages = this.b.getSortedRegisteredLanguageNames();
    const picks = languages.map(({ languageName, languageId }) => {
      const description = localize(8815, null, languageId);
      let fakeResource;
      const extensions = this.b.getExtensions(languageId);
      if (extensions.length) {
        fakeResource = URI.file(extensions[0]);
      } else {
        const filenames = this.b.getFilenames(languageId);
        if (filenames.length) {
          fakeResource = URI.file(filenames[0]);
        }
      }
      return {
        label: languageName,
        iconClasses: $gdb(this.a, this.b, fakeResource),
        description
      };
    });
    await this.c.pick(picks, { placeHolder: localize(8816, null) }).then((pick) => {
      if (pick) {
        const languageId = this.b.getLanguageIdByLanguageName(pick.label);
        if (typeof languageId === "string") {
          return this.f.openLanguageSpecificSettings(languageId);
        }
      }
      return void 0;
    });
  }
};
$a1b = __decorate([
  __param(2, $sG),
  __param(3, $1E),
  __param(4, $1M),
  __param(5, $TK)
], $a1b);
$tn.registerCommand({
  id: "_getAllSettings",
  handler: () => {
    const configRegistry = $Wn.as($Ht.Configuration);
    const allSettings = configRegistry.getConfigurationProperties();
    return allSettings;
  }
});
$tn.registerCommand("_getAllCommands", function(accessor, filterByPrecondition) {
  const keybindingService = accessor.get($Ty);
  const contextKeyService = accessor.get($on);
  const actions = [];
  for (const editorAction of EditorExtensionsRegistry.getEditorActions()) {
    const keybinding = keybindingService.lookupKeybinding(editorAction.id);
    if (filterByPrecondition && !contextKeyService.contextMatchesRules(editorAction.precondition)) {
      continue;
    }
    actions.push({
      command: editorAction.id,
      label: editorAction.label,
      description: $un(editorAction.metadata?.description) ? editorAction.metadata.description.value : editorAction.metadata?.description,
      precondition: editorAction.precondition?.serialize(),
      keybinding: keybinding?.getLabel() ?? "Not set"
    });
  }
  for (const menuItem of $dJ.getMenuItems($bJ.CommandPalette)) {
    if ($_I(menuItem)) {
      if (filterByPrecondition && !contextKeyService.contextMatchesRules(menuItem.when)) {
        continue;
      }
      const title = typeof menuItem.command.title === "string" ? menuItem.command.title : menuItem.command.title.value;
      const category8 = menuItem.command.category ? typeof menuItem.command.category === "string" ? menuItem.command.category : menuItem.command.category.value : void 0;
      const label3 = category8 ? `${category8}: ${title}` : title;
      const description = $un(menuItem.command.metadata?.description) ? menuItem.command.metadata.description.value : menuItem.command.metadata?.description;
      const keybinding = keybindingService.lookupKeybinding(menuItem.command.id);
      actions.push({
        command: menuItem.command.id,
        label: label3,
        description,
        precondition: menuItem.when?.serialize(),
        keybinding: keybinding?.getLabel() ?? "Not set"
      });
    }
  }
  return actions;
});

// out-build/vs/workbench/contrib/preferences/browser/preferencesRenderers.js
var WorkspaceConfigurationRenderer_1;
var $b1b = class $b1b2 extends $3c {
  constructor(h3, preferencesModel, j, m, n) {
    super();
    this.h = h3;
    this.preferencesModel = preferencesModel;
    this.j = j;
    this.m = m;
    this.n = n;
    this.c = new $Sh(200);
    this.a = this.B(n.createInstance(SettingHighlighter, h3));
    this.b = this.B(this.n.createInstance(EditSettingRenderer, this.h, this.preferencesModel, this.a));
    this.B(this.b.onUpdateSetting(({ key: key2, value, source }) => this.updatePreference(key2, value, source)));
    this.B(this.h.getModel().onDidChangeContent(() => this.c.trigger(() => this.r())));
    this.g = this.B(n.createInstance(UnsupportedSettingsRenderer, h3, preferencesModel));
  }
  render() {
    this.b.render(this.preferencesModel.settingsGroups, this.f);
    this.g.render();
  }
  updatePreference(key2, value, source) {
    const overrideIdentifiers = source.overrideOf ? $St(source.overrideOf.key) : null;
    const resource = this.preferencesModel.uri;
    this.m.updateValue(key2, value, { overrideIdentifiers, resource }, this.preferencesModel.configurationTarget).then(() => this.t(source));
  }
  r() {
    if (!this.h.hasModel()) {
      return;
    }
    this.render();
  }
  t(setting) {
    this.h.focus();
    setting = this.u(setting);
    if (setting) {
      this.h.setSelection(setting.valueRange);
      this.a.highlight(setting, true);
    }
  }
  u(setting) {
    const { key: key2, overrideOf } = setting;
    if (overrideOf) {
      const setting2 = this.u(overrideOf);
      for (const override of setting2.overrides) {
        if (override.key === key2) {
          return override;
        }
      }
      return void 0;
    }
    return this.preferencesModel.getPreference(key2);
  }
  focusPreference(setting) {
    const s = this.u(setting);
    if (s) {
      this.a.highlight(s, true);
      this.h.setPosition({ lineNumber: s.keyRange.startLineNumber, column: s.keyRange.startColumn });
    } else {
      this.a.clear(true);
    }
  }
  clearFocus(setting) {
    this.a.clear(true);
  }
  editPreference(setting) {
    const editableSetting = this.u(setting);
    return !!(editableSetting && this.b.activateOnSetting(editableSetting));
  }
};
$b1b = __decorate([
  __param(2, $TK),
  __param(3, $kl),
  __param(4, $Pk)
], $b1b);
var $c1b = class $c1b2 extends $b1b {
  constructor(editor, preferencesModel, preferencesService, configurationService, instantiationService) {
    super(editor, preferencesModel, preferencesService, configurationService, instantiationService);
    this.w = this.B(instantiationService.createInstance(WorkspaceConfigurationRenderer, editor, preferencesModel));
  }
  render() {
    super.render();
    this.w.render();
  }
};
$c1b = __decorate([
  __param(2, $TK),
  __param(3, $kl),
  __param(4, $Pk)
], $c1b);
var EditSettingRenderer = class EditSettingRenderer2 extends $3c {
  constructor(h3, j, m, n, r2, t) {
    super();
    this.h = h3;
    this.j = j;
    this.m = m;
    this.n = n;
    this.r = r2;
    this.t = t;
    this.c = [];
    this.g = new $ze();
    this.onUpdateSetting = this.g.event;
    this.a = this.B(this.r.createInstance($XYb, h3));
    this.b = this.B(this.r.createInstance($XYb, h3));
    this.f = new $Sh(75);
    this.B(this.a.onClick((e) => this.M(this.a, e)));
    this.B(this.b.onClick((e) => this.M(this.b, e)));
    this.B(this.h.onDidChangeCursorPosition((positionChangeEvent) => this.z(positionChangeEvent)));
    this.B(this.h.onMouseMove((mouseMoveEvent) => this.C(mouseMoveEvent)));
    this.B(this.h.onDidChangeConfiguration(() => this.w()));
  }
  render(settingsGroups, associatedPreferencesModel) {
    this.a.hide();
    this.b.hide();
    this.c = settingsGroups;
    this.associatedPreferencesModel = associatedPreferencesModel;
    const settings = this.I(this.h.getPosition().lineNumber);
    if (settings.length) {
      this.G(this.a, settings);
    }
  }
  u() {
    return this.j instanceof $OK;
  }
  w() {
    if (!this.h.getOption(
      59
      /* EditorOption.glyphMargin */
    )) {
      this.a.hide();
      this.b.hide();
    }
  }
  z(positionChangeEvent) {
    this.b.hide();
    const settings = this.I(positionChangeEvent.position.lineNumber);
    if (settings.length) {
      this.G(this.a, settings);
    } else {
      this.a.hide();
    }
  }
  C(mouseMoveEvent) {
    const editPreferenceWidget = this.D(mouseMoveEvent);
    if (editPreferenceWidget) {
      this.L(editPreferenceWidget);
      return;
    }
    this.m.clear();
    this.f.trigger(() => this.F(mouseMoveEvent));
  }
  D(mouseMoveEvent) {
    if (mouseMoveEvent.target.type === 2) {
      const line = mouseMoveEvent.target.position.lineNumber;
      if (this.b.getLine() === line && this.b.isVisible()) {
        return this.b;
      }
      if (this.a.getLine() === line && this.a.isVisible()) {
        return this.a;
      }
    }
    return void 0;
  }
  F(mouseMoveEvent) {
    const settings = mouseMoveEvent.target.position ? this.I(mouseMoveEvent.target.position.lineNumber) : null;
    if (settings && settings.length) {
      this.G(this.b, settings);
    } else {
      this.b.hide();
    }
  }
  G(editPreferencesWidget, settings) {
    const line = settings[0].valueRange.startLineNumber;
    if (this.h.getOption(
      59
      /* EditorOption.glyphMargin */
    ) && this.H(line)) {
      editPreferencesWidget.show(line, localize(8830, null), settings);
      const editPreferenceWidgetToHide = editPreferencesWidget === this.a ? this.b : this.a;
      editPreferenceWidgetToHide.hide();
    }
  }
  H(line) {
    const decorations = this.h.getLineDecorations(line);
    if (decorations) {
      for (const { options: options3 } of decorations) {
        if (options3.glyphMarginClassName && options3.glyphMarginClassName.indexOf(ThemeIcon.asClassName($OYb)) === -1) {
          return false;
        }
      }
    }
    return true;
  }
  I(lineNumber) {
    const configurationMap = this.O();
    return this.J(lineNumber).filter((setting) => {
      const configurationNode = configurationMap[setting.key];
      if (configurationNode) {
        if (configurationNode.policy && this.n.inspect(setting.key).policyValue !== void 0) {
          return false;
        }
        if (this.u()) {
          if (setting.key === "launch") {
            return false;
          }
          return true;
        }
        if (configurationNode.type === "boolean" || configurationNode.enum) {
          if (this.j.configurationTarget !== 6) {
            return true;
          }
          if (configurationNode.scope === 4 || configurationNode.scope === 5) {
            return true;
          }
        }
      }
      return false;
    });
  }
  J(lineNumber) {
    let index = 0;
    const settings = [];
    for (const group2 of this.c) {
      if (group2.range.startLineNumber > lineNumber) {
        break;
      }
      if (lineNumber >= group2.range.startLineNumber && lineNumber <= group2.range.endLineNumber) {
        for (const section of group2.sections) {
          for (const setting of section.settings) {
            if (setting.range.startLineNumber > lineNumber) {
              break;
            }
            if (lineNumber >= setting.range.startLineNumber && lineNumber <= setting.range.endLineNumber) {
              if (!this.u() && setting.overrides.length) {
                for (const overrideSetting of setting.overrides) {
                  if (lineNumber >= overrideSetting.range.startLineNumber && lineNumber <= overrideSetting.range.endLineNumber) {
                    settings.push({ ...overrideSetting, index, groupId: group2.id });
                  }
                }
              } else {
                settings.push({ ...setting, index, groupId: group2.id });
              }
            }
            index++;
          }
        }
      }
    }
    return settings;
  }
  L(editPreferenceWidget) {
    this.m.highlight(editPreferenceWidget.preferences[0]);
  }
  M(editPreferenceWidget, e) {
    $9j.stop(e.event, true);
    const actions = this.I(editPreferenceWidget.getLine()).length === 1 ? this.P(editPreferenceWidget.preferences[0], this.O()[editPreferenceWidget.preferences[0].key]) : editPreferenceWidget.preferences.map((setting) => new $Xm(`preferences.submenu.${setting.key}`, setting.key, this.P(setting, this.O()[setting.key])));
    this.t.showContextMenu({
      getAnchor: () => e.event,
      getActions: () => actions
    });
  }
  activateOnSetting(setting) {
    const startLine = setting.keyRange.startLineNumber;
    const settings = this.I(startLine);
    if (!settings.length) {
      return false;
    }
    this.b.show(startLine, "", settings);
    const actions = this.P(this.b.preferences[0], this.O()[this.b.preferences[0].key]);
    this.t.showContextMenu({
      getAnchor: () => this.N(new $8C(startLine, 1)),
      getActions: () => actions
    });
    return true;
  }
  N(position) {
    const positionCoords = this.h.getScrolledVisiblePosition(position);
    const editorCoords = $vj(this.h.getDomNode());
    const x = editorCoords.left + positionCoords.left;
    const y = editorCoords.top + positionCoords.top + positionCoords.height;
    return { x, y: y + 10 };
  }
  O() {
    return $Wn.as($Ht.Configuration).getConfigurationProperties();
  }
  P(setting, jsonSchema) {
    if (jsonSchema.type === "boolean") {
      return [{
        id: "truthyValue",
        label: "true",
        tooltip: "true",
        enabled: true,
        run: () => this.R(setting.key, true, setting),
        class: void 0
      }, {
        id: "falsyValue",
        label: "false",
        tooltip: "false",
        enabled: true,
        run: () => this.R(setting.key, false, setting),
        class: void 0
      }];
    }
    if (jsonSchema.enum) {
      return jsonSchema.enum.map((value) => {
        return {
          id: value,
          label: JSON.stringify(value),
          tooltip: JSON.stringify(value),
          enabled: true,
          run: () => this.R(setting.key, value, setting),
          class: void 0
        };
      });
    }
    return this.Q(setting);
  }
  Q(setting) {
    if (this.u()) {
      const settingInOtherModel = this.associatedPreferencesModel.getPreference(setting.key);
      return [{
        id: "setDefaultValue",
        label: settingInOtherModel ? localize(8831, null) : localize(8832, null),
        tooltip: settingInOtherModel ? localize(8833, null) : localize(8834, null),
        enabled: true,
        run: () => this.R(setting.key, setting.value, setting),
        class: void 0
      }];
    }
    return [];
  }
  R(key2, value, source) {
    this.g.fire({ key: key2, value, source });
  }
};
EditSettingRenderer = __decorate([
  __param(3, $kl),
  __param(4, $Pk),
  __param(5, $50)
], EditSettingRenderer);
var SettingHighlighter = class SettingHighlighter2 extends $3c {
  constructor(c, instantiationService) {
    super();
    this.c = c;
    this.a = this.B(instantiationService.createInstance($BLb));
    this.b = this.B(instantiationService.createInstance($BLb));
  }
  highlight(setting, fix = false) {
    this.b.removeHighlightRange();
    this.a.removeHighlightRange();
    const highlighter = fix ? this.a : this.b;
    highlighter.highlightRange({
      range: setting.valueRange,
      resource: this.c.getModel().uri
    }, this.c);
    this.c.revealLineInCenterIfOutsideViewport(
      setting.valueRange.startLineNumber,
      0
      /* editorCommon.ScrollType.Smooth */
    );
  }
  clear(fix = false) {
    this.b.removeHighlightRange();
    if (fix) {
      this.a.removeHighlightRange();
    }
  }
};
SettingHighlighter = __decorate([
  __param(1, $Pk)
], SettingHighlighter);
var UnsupportedSettingsRenderer = class UnsupportedSettingsRenderer2 extends $3c {
  constructor(c, f, g, h3, j, m, n, languageFeaturesService, r2, t) {
    super();
    this.c = c;
    this.f = f;
    this.g = g;
    this.h = h3;
    this.j = j;
    this.m = m;
    this.n = n;
    this.r = r2;
    this.t = t;
    this.a = new $Sh(200);
    this.b = new $Ec((uri) => this.n.extUri.getComparisonKey(uri));
    this.B(this.c.getModel().onDidChangeContent(() => this.u()));
    this.B(Event2.filter(
      this.j.onDidChangeConfiguration,
      (e) => e.source === 7
      /* ConfigurationTarget.DEFAULT */
    )(() => this.u()));
    this.B(languageFeaturesService.codeActionProvider.register({ pattern: f.uri.path }, this));
    this.B(r2.onDidChangeCurrentProfile(() => this.u()));
  }
  u() {
    this.a.trigger(() => this.render());
  }
  render() {
    this.b.clear();
    const markerData = this.w();
    if (markerData.length) {
      this.g.changeOne("UnsupportedSettingsRenderer", this.f.uri, markerData);
    } else {
      this.g.remove("UnsupportedSettingsRenderer", [this.f.uri]);
    }
  }
  async provideCodeActions(model, range, context, token) {
    const actions = [];
    const codeActionsByRange = this.b.get(model.uri);
    if (codeActionsByRange) {
      for (const [codeActionsRange, codeActions] of codeActionsByRange) {
        if (codeActionsRange.containsRange(range)) {
          actions.push(...codeActions);
        }
      }
    }
    return {
      actions,
      dispose: () => {
      }
    };
  }
  w() {
    const markerData = [];
    const configurationRegistry22 = $Wn.as($Ht.Configuration).getConfigurationProperties();
    for (const settingsGroup of this.f.settingsGroups) {
      for (const section of settingsGroup.sections) {
        for (const setting of section.settings) {
          if ($Rt.test(setting.key)) {
            if (setting.overrides) {
              this.C(setting.overrides, configurationRegistry22, markerData);
            }
            continue;
          }
          const configuration2 = configurationRegistry22[setting.key];
          if (configuration2) {
            this.I(setting, configuration2, markerData);
            if (this.z(setting, configuration2, markerData)) {
              continue;
            }
            switch (this.f.configurationTarget) {
              case 3:
                this.D(setting, configuration2, markerData);
                break;
              case 4:
                this.F(setting, configuration2, markerData);
                break;
              case 5:
                this.G(setting, configuration2, markerData);
                break;
              case 6:
                this.H(setting, configuration2, markerData);
                break;
            }
          } else {
            markerData.push(this.N(setting));
          }
        }
      }
    }
    return markerData;
  }
  z(setting, configuration2, markerData) {
    if (!configuration2.policy) {
      return false;
    }
    if (this.j.inspect(setting.key).policyValue === void 0) {
      return false;
    }
    if (this.f.configurationTarget === 7) {
      return false;
    }
    markerData.push({
      severity: MarkerSeverity.Hint,
      tags: [
        1
        /* MarkerTag.Unnecessary */
      ],
      ...setting.range,
      message: localize(8835, null)
    });
    return true;
  }
  C(overrides, configurationRegistry22, markerData) {
    for (const setting of overrides || []) {
      const configuration2 = configurationRegistry22[setting.key];
      if (configuration2) {
        if (configuration2.scope !== 5) {
          markerData.push({
            severity: MarkerSeverity.Hint,
            tags: [
              1
              /* MarkerTag.Unnecessary */
            ],
            ...setting.range,
            message: localize(8836, null)
          });
        }
      } else {
        markerData.push(this.N(setting));
      }
    }
  }
  D(setting, configuration2, markerData) {
    if (!this.r.currentProfile.isDefault && !this.r.currentProfile.useDefaultFlags?.settings) {
      if ($oh(this.t.defaultProfile.settingsResource, this.f.uri) && !this.j.isSettingAppliedForAllProfiles(setting.key)) {
        markerData.push({
          severity: MarkerSeverity.Hint,
          tags: [
            1
            /* MarkerTag.Unnecessary */
          ],
          ...setting.range,
          message: localize(8837, null)
        });
      } else if ($oh(this.r.currentProfile.settingsResource, this.f.uri)) {
        if (configuration2.scope === 1) {
          markerData.push(this.J(setting));
        } else if (this.j.isSettingAppliedForAllProfiles(setting.key)) {
          markerData.push({
            severity: MarkerSeverity.Hint,
            tags: [
              1
              /* MarkerTag.Unnecessary */
            ],
            ...setting.range,
            message: localize(8838, null, $GK)
          });
        }
      }
    }
    if (this.h.remoteAuthority && (configuration2.scope === 2 || configuration2.scope === 6)) {
      markerData.push({
        severity: MarkerSeverity.Hint,
        tags: [
          1
          /* MarkerTag.Unnecessary */
        ],
        ...setting.range,
        message: localize(8839, null)
      });
    }
  }
  F(setting, configuration2, markerData) {
    if (configuration2.scope === 1) {
      markerData.push(this.J(setting));
    }
  }
  G(setting, configuration2, markerData) {
    if (configuration2.scope === 1) {
      markerData.push(this.J(setting));
    }
    if (configuration2.scope === 2) {
      markerData.push(this.L(setting));
    }
    if (!this.m.isWorkspaceTrusted() && configuration2.restricted) {
      const marker = this.M(setting);
      markerData.push(marker);
      const codeActions = this.O([marker]);
      this.R(marker, codeActions);
    }
  }
  H(setting, configuration2, markerData) {
    if (configuration2.scope === 1) {
      markerData.push(this.J(setting));
    }
    if (configuration2.scope === 2) {
      markerData.push(this.L(setting));
    }
    if (configuration2.scope === 3) {
      markerData.push({
        severity: MarkerSeverity.Hint,
        tags: [
          1
          /* MarkerTag.Unnecessary */
        ],
        ...setting.range,
        message: localize(8840, null)
      });
    }
    if (!this.m.isWorkspaceTrusted() && configuration2.restricted) {
      const marker = this.M(setting);
      markerData.push(marker);
      const codeActions = this.O([marker]);
      this.R(marker, codeActions);
    }
  }
  I(setting, configuration2, markerData) {
    if (configuration2.tags?.includes("preview")) {
      markerData.push(this.P(setting));
    } else if (configuration2.tags?.includes("experimental")) {
      markerData.push(this.Q(setting));
    }
  }
  J(setting) {
    return {
      severity: MarkerSeverity.Hint,
      tags: [
        1
        /* MarkerTag.Unnecessary */
      ],
      ...setting.range,
      message: localize(8841, null)
    };
  }
  L(setting) {
    return {
      severity: MarkerSeverity.Hint,
      tags: [
        1
        /* MarkerTag.Unnecessary */
      ],
      ...setting.range,
      message: localize(8842, null)
    };
  }
  M(setting) {
    return {
      severity: MarkerSeverity.Warning,
      ...setting.range,
      message: localize(8843, null)
    };
  }
  N(setting) {
    return {
      severity: MarkerSeverity.Hint,
      tags: [
        1
        /* MarkerTag.Unnecessary */
      ],
      ...setting.range,
      message: localize(8844, null)
    };
  }
  O(diagnostics) {
    return [{
      title: localize(8845, null),
      command: {
        id: "workbench.trust.manage",
        title: localize(8846, null)
      },
      diagnostics,
      kind: $pab.QuickFix.value
    }];
  }
  P(setting) {
    return {
      severity: MarkerSeverity.Hint,
      ...setting.range,
      message: $LZb
    };
  }
  Q(setting) {
    return {
      severity: MarkerSeverity.Hint,
      ...setting.range,
      message: $MZb
    };
  }
  R(range, codeActions) {
    let actions = this.b.get(this.f.uri);
    if (!actions) {
      actions = [];
      this.b.set(this.f.uri, actions);
    }
    actions.push([$9C.lift(range), codeActions]);
  }
  dispose() {
    this.g.remove("UnsupportedSettingsRenderer", [this.f.uri]);
    this.b.clear();
    super.dispose();
  }
};
UnsupportedSettingsRenderer = __decorate([
  __param(2, $DE),
  __param(3, $US),
  __param(4, $EK),
  __param(5, $4M),
  __param(6, $vl),
  __param(7, $mP),
  __param(8, $gT),
  __param(9, $rs)
], UnsupportedSettingsRenderer);
var WorkspaceConfigurationRenderer = class WorkspaceConfigurationRenderer2 extends $3c {
  static {
    WorkspaceConfigurationRenderer_1 = this;
  }
  static {
    this.a = ["folders", "tasks", "launch", "extensions", "settings", "remoteAuthority", "transient"];
  }
  constructor(f, g, h3, j) {
    super();
    this.f = f;
    this.g = g;
    this.h = h3;
    this.j = j;
    this.b = this.f.createDecorationsCollection();
    this.c = new $Sh(200);
    this.B(this.f.getModel().onDidChangeContent(() => this.c.trigger(() => this.render())));
  }
  render() {
    const markerData = [];
    if (this.h.getWorkbenchState() === 3 && this.g instanceof $MK) {
      const ranges = [];
      for (const settingsGroup of this.g.configurationGroups) {
        for (const section of settingsGroup.sections) {
          for (const setting of section.settings) {
            if (!WorkspaceConfigurationRenderer_1.a.includes(setting.key)) {
              markerData.push({
                severity: MarkerSeverity.Hint,
                tags: [
                  1
                  /* MarkerTag.Unnecessary */
                ],
                ...setting.range,
                message: localize(8847, null)
              });
            }
          }
        }
      }
      this.b.set(ranges.map((range) => this.n(range)));
    }
    if (markerData.length) {
      this.j.changeOne("WorkspaceConfigurationRenderer", this.g.uri, markerData);
    } else {
      this.j.remove("WorkspaceConfigurationRenderer", [this.g.uri]);
    }
  }
  static {
    this.m = $WI.register({
      description: "dim-configuration",
      stickiness: 1,
      inlineClassName: "dim-configuration"
    });
  }
  n(range) {
    return {
      range,
      options: WorkspaceConfigurationRenderer_1.m
    };
  }
  dispose() {
    this.j.remove("WorkspaceConfigurationRenderer", [this.g.uri]);
    this.b.clear();
    super.dispose();
  }
};
WorkspaceConfigurationRenderer = WorkspaceConfigurationRenderer_1 = __decorate([
  __param(2, $Zk),
  __param(3, $DE)
], WorkspaceConfigurationRenderer);

// out-build/vs/workbench/contrib/preferences/browser/preferencesEditor.js
var $d1b = class $d1b2 extends $3c {
  static {
    this.ID = "editor.contrib.settings";
  }
  constructor(c, f, g, h3) {
    super();
    this.c = c;
    this.f = f;
    this.g = g;
    this.h = h3;
    this.b = this.B(new $2c());
    this.j();
    this.B(this.c.onDidChangeModel((e) => this.j()));
    this.B(this.h.onDidChangeWorkbenchState(() => this.j()));
  }
  async j() {
    this.b.clear();
    this.a = void 0;
    const model = this.c.getModel();
    if (model && /\.(json|code-workspace)$/.test(model.uri.path)) {
      const settingsModel = await this.g.createPreferencesEditorModel(model.uri);
      if (settingsModel instanceof $KK && this.c.getModel()) {
        this.b.add(settingsModel);
        switch (settingsModel.configurationTarget) {
          case 5:
            this.a = this.b.add(this.f.createInstance($c1b, this.c, settingsModel));
            break;
          default:
            this.a = this.b.add(this.f.createInstance($b1b, this.c, settingsModel));
            break;
        }
      }
      this.a?.render();
    }
  }
};
$d1b = __decorate([
  __param(1, $Pk),
  __param(2, $TK),
  __param(3, $Zk)
], $d1b);

// out-build/vs/workbench/contrib/preferences/browser/settingsLayout.js
var defaultCommonlyUsedSettings = [
  "files.autoSave",
  "editor.fontSize",
  "editor.fontFamily",
  "editor.tabSize",
  "editor.renderWhitespace",
  "editor.cursorStyle",
  "editor.multiCursorModifier",
  "editor.insertSpaces",
  "editor.wordWrap",
  "files.exclude",
  "files.associations",
  "workbench.editor.enablePreview"
];
function $e1b(toggleData) {
  return {
    id: "commonlyUsed",
    label: localize(8914, null),
    settings: toggleData?.commonlyUsed ?? defaultCommonlyUsedSettings
  };
}
var $f1b = {
  id: "root",
  label: "root",
  children: [
    {
      id: "editor",
      label: localize(8915, null),
      settings: ["editor.*"],
      children: [
        {
          id: "editor/cursor",
          label: localize(8916, null),
          settings: ["editor.cursor*"]
        },
        {
          id: "editor/find",
          label: localize(8917, null),
          settings: ["editor.find.*"]
        },
        {
          id: "editor/font",
          label: localize(8918, null),
          settings: ["editor.font*"]
        },
        {
          id: "editor/format",
          label: localize(8919, null),
          settings: ["editor.format*"]
        },
        {
          id: "editor/diffEditor",
          label: localize(8920, null),
          settings: ["diffEditor.*"]
        },
        {
          id: "editor/multiDiffEditor",
          label: localize(8921, null),
          settings: ["multiDiffEditor.*"]
        },
        {
          id: "editor/minimap",
          label: localize(8922, null),
          settings: ["editor.minimap.*"]
        },
        {
          id: "editor/suggestions",
          label: localize(8923, null),
          settings: ["editor.*suggest*"]
        },
        {
          id: "editor/files",
          label: localize(8924, null),
          settings: ["files.*"]
        }
      ]
    },
    {
      id: "workbench",
      label: localize(8925, null),
      settings: ["workbench.*"],
      children: [
        {
          id: "workbench/appearance",
          label: localize(8926, null),
          settings: ["workbench.activityBar.*", "workbench.*color*", "workbench.fontAliasing", "workbench.iconTheme", "workbench.sidebar.location", "workbench.*.visible", "workbench.tips.enabled", "workbench.tree.*", "workbench.view.*"]
        },
        {
          id: "workbench/breadcrumbs",
          label: localize(8927, null),
          settings: ["breadcrumbs.*"]
        },
        {
          id: "workbench/editor",
          label: localize(8928, null),
          settings: ["workbench.editor.*"]
        },
        {
          id: "workbench/settings",
          label: localize(8929, null),
          settings: ["workbench.settings.*"]
        },
        {
          id: "workbench/zenmode",
          label: localize(8930, null),
          settings: ["zenmode.*"]
        },
        {
          id: "workbench/screencastmode",
          label: localize(8931, null),
          settings: ["screencastMode.*"]
        }
      ]
    },
    {
      id: "window",
      label: localize(8932, null),
      settings: ["window.*"],
      children: [
        {
          id: "window/newWindow",
          label: localize(8933, null),
          settings: ["window.*newwindow*"]
        }
      ]
    },
    {
      id: "features",
      label: localize(8934, null),
      children: [
        {
          id: "features/accessibilitySignals",
          label: localize(8935, null),
          settings: ["accessibility.signal*"]
        },
        {
          id: "features/accessibility",
          label: localize(8936, null),
          settings: ["accessibility.*"]
        },
        {
          id: "features/explorer",
          label: localize(8937, null),
          settings: ["explorer.*", "outline.*"]
        },
        {
          id: "features/search",
          label: localize(8938, null),
          settings: ["search.*"]
        },
        {
          id: "features/debug",
          label: localize(8939, null),
          settings: ["debug.*", "launch"]
        },
        {
          id: "features/testing",
          label: localize(8940, null),
          settings: ["testing.*"]
        },
        {
          id: "features/scm",
          label: localize(8941, null),
          settings: ["scm.*"]
        },
        {
          id: "features/extensions",
          label: localize(8942, null),
          settings: ["extensions.*"]
        },
        {
          id: "features/terminal",
          label: localize(8943, null),
          settings: ["terminal.*"]
        },
        {
          id: "features/task",
          label: localize(8944, null),
          settings: ["task.*"]
        },
        {
          id: "features/problems",
          label: localize(8945, null),
          settings: ["problems.*"]
        },
        {
          id: "features/output",
          label: localize(8946, null),
          settings: ["output.*"]
        },
        {
          id: "features/comments",
          label: localize(8947, null),
          settings: ["comments.*"]
        },
        {
          id: "features/remote",
          label: localize(8948, null),
          settings: ["remote.*"]
        },
        {
          id: "features/timeline",
          label: localize(8949, null),
          settings: ["timeline.*"]
        },
        {
          id: "features/notebook",
          label: localize(8950, null),
          settings: ["notebook.*", "interactiveWindow.*"]
        },
        {
          id: "features/mergeEditor",
          label: localize(8951, null),
          settings: ["mergeEditor.*"]
        },
        {
          id: "features/chat",
          label: localize(8952, null),
          settings: ["chat.*", "inlineChat.*"]
        },
        {
          id: "features/issueReporter",
          label: localize(8953, null),
          settings: ["issueReporter.*"]
        }
      ]
    },
    {
      id: "application",
      label: localize(8954, null),
      children: [
        {
          id: "application/http",
          label: localize(8955, null),
          settings: ["http.*"]
        },
        {
          id: "application/keyboard",
          label: localize(8956, null),
          settings: ["keyboard.*"]
        },
        {
          id: "application/update",
          label: localize(8957, null),
          settings: ["update.*"]
        },
        {
          id: "application/telemetry",
          label: localize(8958, null),
          settings: ["telemetry.*"]
        },
        {
          id: "application/settingsSync",
          label: localize(8959, null),
          settings: ["settingsSync.*"]
        },
        {
          id: "application/experimental",
          label: localize(8960, null),
          settings: ["application.experimental.*"]
        },
        {
          id: "application/other",
          label: localize(8961, null),
          settings: ["application.*"]
        }
      ]
    },
    {
      id: "security",
      label: localize(8962, null),
      settings: ["security.*"],
      children: [
        {
          id: "security/workspace",
          label: localize(8963, null),
          settings: ["security.workspace.*"]
        }
      ]
    }
  ]
};
var $g1b = /* @__PURE__ */ new Set();
[
  "css",
  "html",
  "scss",
  "less",
  "json",
  "js",
  "ts",
  "ie",
  "id",
  "php",
  "scm"
].forEach((str) => $g1b.add(str));
var $h1b = /* @__PURE__ */ new Map();
$h1b.set("power shell", "PowerShell");
$h1b.set("powershell", "PowerShell");
$h1b.set("javascript", "JavaScript");
$h1b.set("typescript", "TypeScript");

// out-build/vs/workbench/contrib/preferences/browser/settingsEditorSettingIndicators.js
var $116 = $;
var cachedSyncIgnoredSettingsSet = /* @__PURE__ */ new Set();
var cachedSyncIgnoredSettings = [];
var $t1b = class $t1b2 {
  constructor(container2, m, n, o, p, q) {
    this.m = m;
    this.n = n;
    this.o = o;
    this.p = p;
    this.q = q;
    this.h = [];
    this.k = new $2c();
    this.l = 0;
    this.r = {
      trapFocus: true,
      position: {
        hoverPosition: 2
      },
      appearance: {
        showPointer: true,
        compact: false
      }
    };
    this.a = $bk(container2, $116(".setting-indicators-container"));
    this.a.style.display = "inline";
    this.b = this.x();
    this.h = [this.b];
    this.c = this.t();
    this.d = this.u();
    this.f = this.v();
    this.g = this.w();
    this.j = [this.c, this.d, this.f, this.g];
  }
  s(disposables, element, showHover) {
    disposables.clear();
    const scheduler = disposables.add(new $8h(() => {
      const hover = showHover(false);
      if (hover) {
        disposables.add(hover);
      }
    }, this.m.getValue("workbench.hover.delay")));
    disposables.add($_i(element, $7j.MOUSE_OVER, () => {
      if (!scheduler.isScheduled()) {
        scheduler.schedule();
      }
    }));
    disposables.add($_i(element, $7j.MOUSE_LEAVE, () => {
      scheduler.cancel();
    }));
    disposables.add($_i(element, $7j.KEY_DOWN, (e) => {
      const evt = new $if(e);
      if (evt.equals(
        10
        /* KeyCode.Space */
      ) || evt.equals(
        3
        /* KeyCode.Enter */
      )) {
        const hover = showHover(true);
        if (hover) {
          disposables.add(hover);
        }
        e.preventDefault();
      }
    }));
  }
  t() {
    const disposables = new $2c();
    const workspaceTrustElement = $116("span.setting-indicator.setting-item-workspace-trust");
    const workspaceTrustLabel = disposables.add(new $U2(workspaceTrustElement));
    workspaceTrustLabel.text = "$(warning) " + localize(8870, null);
    const content = localize(8871, null);
    const showHover = (focus) => {
      return this.n.showHover({
        ...this.r,
        content,
        target: workspaceTrustElement,
        actions: [{
          label: localize(8872, null),
          commandId: "workbench.trust.manage",
          run: (target) => {
            this.q.executeCommand("workbench.trust.manage");
          }
        }]
      }, focus);
    };
    this.s(disposables, workspaceTrustElement, showHover);
    return {
      element: workspaceTrustElement,
      label: workspaceTrustLabel,
      disposables
    };
  }
  u() {
    const disposables = new $2c();
    const otherOverridesElement = $116("span.setting-item-overrides");
    const otherOverridesLabel = disposables.add(new $U2(otherOverridesElement));
    return {
      element: otherOverridesElement,
      label: otherOverridesLabel,
      disposables
    };
  }
  v() {
    const disposables = new $2c();
    const syncIgnoredElement = $116("span.setting-indicator.setting-item-ignored");
    const syncIgnoredLabel = disposables.add(new $U2(syncIgnoredElement));
    syncIgnoredLabel.text = localize(8873, null);
    const syncIgnoredHoverContent = localize(8874, null);
    const showHover = (focus) => {
      return this.n.showHover({
        ...this.r,
        content: syncIgnoredHoverContent,
        target: syncIgnoredElement
      }, focus);
    };
    this.s(disposables, syncIgnoredElement, showHover);
    return {
      element: syncIgnoredElement,
      label: syncIgnoredLabel,
      disposables
    };
  }
  w() {
    const disposables = new $2c();
    const defaultOverrideIndicator = $116("span.setting-indicator.setting-item-default-overridden");
    const defaultOverrideLabel = disposables.add(new $U2(defaultOverrideIndicator));
    defaultOverrideLabel.text = localize(8875, null);
    return {
      element: defaultOverrideIndicator,
      label: defaultOverrideLabel,
      disposables
    };
  }
  x() {
    const disposables = new $2c();
    const previewIndicator = $116("span.setting-indicator.setting-item-preview");
    const previewLabel = disposables.add(new $U2(previewIndicator));
    return {
      element: previewIndicator,
      label: previewLabel,
      disposables
    };
  }
  y() {
    this.a.innerText = "";
    this.a.style.display = "none";
    const isolatedIndicatorsToShow = this.h.filter((indicator) => {
      return indicator.element.style.display !== "none";
    });
    if (isolatedIndicatorsToShow.length) {
      this.a.style.display = "inline";
      for (let i2 = 0; i2 < isolatedIndicatorsToShow.length; i2++) {
        $bk(this.a, isolatedIndicatorsToShow[i2].element);
      }
    }
    const parenthesizedIndicatorsToShow = this.j.filter((indicator) => {
      return indicator.element.style.display !== "none";
    });
    if (parenthesizedIndicatorsToShow.length) {
      this.a.style.display = "inline";
      $bk(this.a, $116("span", void 0, "("));
      for (let i2 = 0; i2 < parenthesizedIndicatorsToShow.length - 1; i2++) {
        $bk(this.a, parenthesizedIndicatorsToShow[i2].element);
        $bk(this.a, $116("span.comma", void 0, " \u2022 "));
      }
      $bk(this.a, parenthesizedIndicatorsToShow[parenthesizedIndicatorsToShow.length - 1].element);
      $bk(this.a, $116("span", void 0, ")"));
    }
    this.z([...isolatedIndicatorsToShow, ...parenthesizedIndicatorsToShow]);
  }
  z(indicators) {
    this.k.clear();
    this.a.role = indicators.length >= 1 ? "toolbar" : "button";
    if (!indicators.length) {
      return;
    }
    const firstElement = indicators[0].focusElement ?? indicators[0].element;
    firstElement.tabIndex = 0;
    this.k.add($_i(this.a, "keydown", (e) => {
      const ev = new $if(e);
      let handled = true;
      if (ev.equals(
        14
        /* KeyCode.Home */
      )) {
        this.A(indicators, 0);
      } else if (ev.equals(
        13
        /* KeyCode.End */
      )) {
        this.A(indicators, indicators.length - 1);
      } else if (ev.equals(
        17
        /* KeyCode.RightArrow */
      )) {
        const indexToFocus = (this.l + 1) % indicators.length;
        this.A(indicators, indexToFocus);
      } else if (ev.equals(
        15
        /* KeyCode.LeftArrow */
      )) {
        const indexToFocus = this.l ? this.l - 1 : indicators.length - 1;
        this.A(indicators, indexToFocus);
      } else {
        handled = false;
      }
      if (handled) {
        e.preventDefault();
        e.stopPropagation();
      }
    }));
  }
  A(indicators, index) {
    if (index === this.l) {
      return;
    }
    const indicator = indicators[index];
    const elementToFocus = indicator.focusElement ?? indicator.element;
    elementToFocus.tabIndex = 0;
    elementToFocus.focus();
    const currentlyFocusedIndicator = indicators[this.l];
    const previousFocusedElement = currentlyFocusedIndicator.focusElement ?? currentlyFocusedIndicator.element;
    previousFocusedElement.tabIndex = -1;
    this.l = index;
  }
  updateWorkspaceTrust(element) {
    this.c.element.style.display = element.isUntrusted ? "inline" : "none";
    this.y();
  }
  updateSyncIgnored(element, ignoredSettings) {
    this.f.element.style.display = this.o.isEnabled() && ignoredSettings.includes(element.setting.key) ? "inline" : "none";
    this.y();
    if (cachedSyncIgnoredSettings !== ignoredSettings) {
      cachedSyncIgnoredSettings = ignoredSettings;
      cachedSyncIgnoredSettingsSet = new Set(cachedSyncIgnoredSettings);
    }
  }
  updatePreviewIndicator(element) {
    const isPreviewSetting = element.tags?.has("preview");
    const isExperimentalSetting = element.tags?.has("experimental");
    this.b.element.style.display = isPreviewSetting || isExperimentalSetting ? "inline" : "none";
    this.b.label.text = isPreviewSetting ? localize(8876, null) : localize(8877, null);
    const content = isPreviewSetting ? $LZb : $MZb;
    const showHover = (focus) => {
      return this.n.showHover({
        ...this.r,
        content,
        target: this.b.element
      }, focus);
    };
    this.s(this.b.disposables, this.b.element, showHover);
    this.y();
  }
  B(completeScope) {
    const [scope, language] = completeScope.split(":");
    const localizedScope = scope === "user" ? localize(8878, null) : scope === "workspace" ? localize(8879, null) : localize(8880, null);
    if (language) {
      return `${this.p.getLanguageName(language)} > ${localizedScope}`;
    }
    return localizedScope;
  }
  dispose() {
    this.k.dispose();
    for (const indicator of this.h) {
      indicator.disposables.dispose();
    }
    for (const indicator of this.j) {
      indicator.disposables.dispose();
    }
  }
  updateScopeOverrides(element, onDidClickOverrideElement, onApplyFilter) {
    this.d.element.innerText = "";
    this.d.element.style.display = "none";
    this.d.focusElement = this.d.element;
    if (element.hasPolicyValue) {
      this.d.element.style.display = "inline";
      this.d.element.classList.add("setting-indicator");
      this.d.label.text = "$(warning) " + localize(8881, null);
      const content = localize(8882, null);
      const showHover = (focus) => {
        return this.n.showHover({
          ...this.r,
          content,
          actions: [{
            label: localize(8883, null),
            commandId: "_settings.action.viewPolicySettings",
            run: (_) => {
              onApplyFilter.fire(`@${$CZb}`);
            }
          }],
          target: this.d.element
        }, focus);
      };
      this.s(this.d.disposables, this.d.element, showHover);
    } else if (element.settingsTarget === 3 && this.m.isSettingAppliedForAllProfiles(element.setting.key)) {
      this.d.element.style.display = "inline";
      this.d.element.classList.add("setting-indicator");
      this.d.label.text = localize(8884, null);
      const content = localize(8885, null);
      const showHover = (focus) => {
        return this.n.showHover({
          ...this.r,
          content,
          target: this.d.element
        }, focus);
      };
      this.s(this.d.disposables, this.d.element, showHover);
    } else if (element.overriddenScopeList.length || element.overriddenDefaultsLanguageList.length) {
      if (element.overriddenScopeList.length === 1 && !element.overriddenDefaultsLanguageList.length) {
        this.d.element.style.display = "inline";
        this.d.element.classList.remove("setting-indicator");
        this.d.disposables.clear();
        const prefaceText = element.isConfigured ? localize(8886, null) : localize(8887, null);
        this.d.label.text = `${prefaceText} `;
        const overriddenScope = element.overriddenScopeList[0];
        const view = $bk(this.d.element, $116("a.modified-scope", void 0, this.B(overriddenScope)));
        view.tabIndex = -1;
        this.d.focusElement = view;
        const onClickOrKeydown = (e) => {
          const [scope, language] = overriddenScope.split(":");
          onDidClickOverrideElement.fire({
            settingKey: element.setting.key,
            scope,
            language
          });
          e.preventDefault();
          e.stopPropagation();
        };
        this.d.disposables.add($_i(view, $7j.CLICK, (e) => {
          onClickOrKeydown(e);
        }));
        this.d.disposables.add($_i(view, $7j.KEY_DOWN, (e) => {
          const ev = new $if(e);
          if (ev.equals(
            10
            /* KeyCode.Space */
          ) || ev.equals(
            3
            /* KeyCode.Enter */
          )) {
            onClickOrKeydown(e);
          }
        }));
      } else {
        this.d.element.style.display = "inline";
        this.d.element.classList.add("setting-indicator");
        const scopeOverridesLabelText = element.isConfigured ? localize(8888, null) : localize(8889, null);
        this.d.label.text = scopeOverridesLabelText;
        let contentMarkdownString = "";
        if (element.overriddenScopeList.length) {
          const prefaceText = element.isConfigured ? localize(8890, null) : localize(8891, null);
          contentMarkdownString = prefaceText;
          for (const scope of element.overriddenScopeList) {
            const scopeDisplayText = this.B(scope);
            contentMarkdownString += `
- [${scopeDisplayText}](${encodeURIComponent(scope)} "${getAccessibleScopeDisplayText(scope, this.p)}")`;
          }
        }
        if (element.overriddenDefaultsLanguageList.length) {
          if (contentMarkdownString) {
            contentMarkdownString += `

`;
          }
          const prefaceText = localize(8892, null);
          contentMarkdownString += prefaceText;
          for (const language of element.overriddenDefaultsLanguageList) {
            const scopeDisplayText = this.p.getLanguageName(language);
            contentMarkdownString += `
- [${scopeDisplayText}](${encodeURIComponent(`default:${language}`)} "${scopeDisplayText}")`;
          }
        }
        const content = {
          value: contentMarkdownString,
          isTrusted: false,
          supportHtml: false
        };
        this.d.disposables.add(this.n.setupDelayedHover(this.d.element, () => ({
          ...this.r,
          content,
          linkHandler: (url) => {
            const [scope, language] = decodeURIComponent(url).split(":");
            onDidClickOverrideElement.fire({
              settingKey: element.setting.key,
              scope,
              language
            });
          }
        }), { setupKeyboardEvents: true }));
      }
    }
    this.y();
  }
  updateDefaultOverrideIndicator(element) {
    this.g.element.style.display = "none";
    let sourceToDisplay = getDefaultValueSourceToDisplay(element);
    if (sourceToDisplay !== void 0) {
      this.g.element.style.display = "inline";
      this.g.disposables.clear();
      if (Array.isArray(sourceToDisplay) && sourceToDisplay.length === 1) {
        sourceToDisplay = sourceToDisplay[0];
      }
      let defaultOverrideHoverContent;
      if (!Array.isArray(sourceToDisplay)) {
        defaultOverrideHoverContent = localize(8893, null, sourceToDisplay);
      } else {
        sourceToDisplay = sourceToDisplay.map((source) => `\`${source}\``);
        defaultOverrideHoverContent = localize(8894, null, sourceToDisplay.slice(0, -1).join(", ") + " & " + sourceToDisplay.slice(-1));
      }
      const showHover = (focus) => {
        return this.n.showHover({
          content: new $bm().appendMarkdown(defaultOverrideHoverContent),
          target: this.g.element,
          position: {
            hoverPosition: 2
          },
          appearance: {
            showPointer: true,
            compact: false
          }
        }, focus);
      };
      this.s(this.g.disposables, this.g.element, showHover);
    }
    this.y();
  }
};
$t1b = __decorate([
  __param(1, $EK),
  __param(2, $5$),
  __param(3, $6Bb),
  __param(4, $1E),
  __param(5, $sn)
], $t1b);
function getDefaultValueSourceToDisplay(element) {
  let sourceToDisplay;
  const defaultValueSource = element.defaultValueSource;
  if (defaultValueSource) {
    if (defaultValueSource instanceof Map) {
      sourceToDisplay = [];
      for (const [, value] of defaultValueSource) {
        const newValue = typeof value !== "string" ? value.displayName ?? value.id : value;
        if (!sourceToDisplay.includes(newValue)) {
          sourceToDisplay.push(newValue);
        }
      }
    } else if (typeof defaultValueSource === "string") {
      sourceToDisplay = defaultValueSource;
    } else {
      sourceToDisplay = defaultValueSource.displayName ?? defaultValueSource.id;
    }
  }
  return sourceToDisplay;
}
function getAccessibleScopeDisplayText(completeScope, languageService) {
  const [scope, language] = completeScope.split(":");
  const localizedScope = scope === "user" ? localize(8895, null) : scope === "workspace" ? localize(8896, null) : localize(8897, null);
  if (language) {
    return localize(8898, null, localizedScope, languageService.getLanguageName(language));
  }
  return localizedScope;
}
function getAccessibleScopeDisplayMidSentenceText(completeScope, languageService) {
  const [scope, language] = completeScope.split(":");
  const localizedScope = scope === "user" ? localize(8899, null) : scope === "workspace" ? localize(8900, null) : localize(8901, null);
  if (language) {
    return localize(8902, null, localizedScope.toLowerCase(), languageService.getLanguageName(language));
  }
  return localizedScope;
}
function $u1b(element, configurationService, userDataProfilesService, languageService) {
  const ariaLabelSections = [];
  if (element.tags?.has("preview")) {
    ariaLabelSections.push(localize(8903, null));
  } else if (element.tags?.has("experimental")) {
    ariaLabelSections.push(localize(8904, null));
  }
  if (element.isUntrusted) {
    ariaLabelSections.push(localize(8905, null));
  }
  if (element.hasPolicyValue) {
    ariaLabelSections.push(localize(8906, null));
  } else if (element.settingsTarget === 3 && configurationService.isSettingAppliedForAllProfiles(element.setting.key)) {
    ariaLabelSections.push(localize(8907, null));
  } else {
    const otherOverridesStart = element.isConfigured ? localize(8908, null) : localize(8909, null);
    const otherOverridesList = element.overriddenScopeList.map((scope) => getAccessibleScopeDisplayMidSentenceText(scope, languageService)).join(", ");
    if (element.overriddenScopeList.length) {
      ariaLabelSections.push(`${otherOverridesStart} ${otherOverridesList}`);
    }
  }
  if (cachedSyncIgnoredSettingsSet.has(element.setting.key)) {
    ariaLabelSections.push(localize(8910, null));
  }
  let sourceToDisplay = getDefaultValueSourceToDisplay(element);
  if (sourceToDisplay !== void 0) {
    if (Array.isArray(sourceToDisplay) && sourceToDisplay.length === 1) {
      sourceToDisplay = sourceToDisplay[0];
    }
    let overriddenDetailsText;
    if (!Array.isArray(sourceToDisplay)) {
      overriddenDetailsText = localize(8911, null, sourceToDisplay);
    } else {
      overriddenDetailsText = localize(8912, null, sourceToDisplay.slice(0, -1).join(", ") + " & " + sourceToDisplay.slice(-1));
    }
    ariaLabelSections.push(overriddenDetailsText);
  }
  const otherLanguageOverridesList = element.overriddenDefaultsLanguageList.map((language) => languageService.getLanguageName(language)).join(", ");
  if (element.overriddenDefaultsLanguageList.length) {
    const otherLanguageOverridesText = localize(8913, null, otherLanguageOverridesList);
    ariaLabelSections.push(otherLanguageOverridesText);
  }
  const ariaLabel = ariaLabelSections.join(". ");
  return ariaLabel;
}

// out-build/vs/workbench/contrib/preferences/browser/settingsTreeModels.js
var $j1b = class extends $3c {
  constructor(_id) {
    super();
    this.c = false;
    this.f = new $ze();
    this.onDidChangeTabbable = this.f.event;
    this.id = _id;
  }
  get tabbable() {
    return this.c;
  }
  set tabbable(value) {
    this.c = value;
    this.f.fire();
  }
};
var $k1b = class extends $j1b {
  get children() {
    return this.h;
  }
  set children(newChildren) {
    this.h = newChildren;
    this.g = /* @__PURE__ */ new Set();
    this.h.forEach((child) => {
      if (child instanceof $m1b) {
        this.g.add(child.setting.key);
      }
    });
  }
  constructor(_id, count, label3, level, isFirstGroup) {
    super(_id);
    this.g = /* @__PURE__ */ new Set();
    this.h = [];
    this.count = count;
    this.label = label3;
    this.level = level;
    this.isFirstGroup = isFirstGroup;
  }
  /**
   * Returns whether this group contains the given child key (to a depth of 1 only)
   */
  containsSetting(key2) {
    return this.g.has(key2);
  }
};
var $l1b = class extends $j1b {
  constructor(_id, extensionIds) {
    super(_id);
    this.extensionIds = extensionIds;
  }
};
var $m1b = class _$m1b extends $j1b {
  static {
    this.g = 20;
  }
  constructor(setting, parent, settingsTarget, n, r2, u, w, y, z) {
    super(sanitizeId(parent.id + "_" + setting.key));
    this.settingsTarget = settingsTarget;
    this.n = n;
    this.r = r2;
    this.u = u;
    this.w = w;
    this.y = y;
    this.z = z;
    this.h = null;
    this.j = null;
    this.isConfigured = false;
    this.isUntrusted = false;
    this.hasPolicyValue = false;
    this.overriddenScopeList = [];
    this.overriddenDefaultsLanguageList = [];
    this.languageOverrideValues = /* @__PURE__ */ new Map();
    this.setting = setting;
    this.parent = parent;
    this.D();
    this.F();
  }
  get displayCategory() {
    if (!this.h) {
      this.C();
    }
    return this.h;
  }
  get displayLabel() {
    if (!this.j) {
      this.C();
    }
    return this.j;
  }
  C() {
    if (this.setting.title) {
      this.j = this.setting.title;
      this.h = this.setting.categoryLabel ?? null;
      return;
    }
    const displayKeyFormat = $p1b(this.setting.key, this.parent.id, this.setting.isLanguageTagSetting);
    this.j = displayKeyFormat.label;
    this.h = displayKeyFormat.category;
  }
  D() {
    if (this.setting.description.length > _$m1b.g) {
      const truncatedDescLines = this.setting.description.slice(0, _$m1b.g);
      truncatedDescLines.push("[...]");
      this.description = truncatedDescLines.join("\n");
    } else {
      this.description = this.setting.description.join("\n");
    }
  }
  F() {
    if (isExtensionToggleSetting(this.setting, this.w)) {
      this.valueType = SettingValueType.ExtensionToggle;
    } else if (this.setting.enum && (!this.setting.type || settingTypeEnumRenderable(this.setting.type))) {
      this.valueType = SettingValueType.Enum;
    } else if (this.setting.type === "string") {
      if (this.setting.editPresentation === EditPresentationTypes.Multiline) {
        this.valueType = SettingValueType.MultilineString;
      } else {
        this.valueType = SettingValueType.String;
      }
    } else if (isExcludeSetting(this.setting)) {
      this.valueType = SettingValueType.Exclude;
    } else if (isIncludeSetting(this.setting)) {
      this.valueType = SettingValueType.Include;
    } else if (this.setting.type === "integer") {
      this.valueType = SettingValueType.Integer;
    } else if (this.setting.type === "number") {
      this.valueType = SettingValueType.Number;
    } else if (this.setting.type === "boolean") {
      this.valueType = SettingValueType.Boolean;
    } else if (this.setting.type === "array" && this.setting.arrayItemType && ["string", "enum", "number", "integer"].includes(this.setting.arrayItemType)) {
      this.valueType = SettingValueType.Array;
    } else if (Array.isArray(this.setting.type) && this.setting.type.includes(SettingValueType.Null) && this.setting.type.length === 2) {
      if (this.setting.type.includes(SettingValueType.Integer)) {
        this.valueType = SettingValueType.NullableInteger;
      } else if (this.setting.type.includes(SettingValueType.Number)) {
        this.valueType = SettingValueType.NullableNumber;
      } else {
        this.valueType = SettingValueType.Complex;
      }
    } else {
      const schemaType = getObjectSettingSchemaType(this.setting);
      if (schemaType) {
        if (this.setting.allKeysAreBoolean) {
          this.valueType = SettingValueType.BooleanObject;
        } else if (schemaType === "simple") {
          this.valueType = SettingValueType.Object;
        } else {
          this.valueType = SettingValueType.ComplexObject;
        }
      } else if (this.setting.isLanguageTagSetting) {
        this.valueType = SettingValueType.LanguageTag;
      } else {
        this.valueType = SettingValueType.Complex;
      }
    }
  }
  inspectSelf() {
    const targetToInspect = this.G(this.setting);
    const inspectResult = $o1b(this.setting.key, targetToInspect, this.r, this.z);
    this.H(inspectResult, this.n);
  }
  G(setting) {
    if (!this.y.currentProfile.isDefault && !this.y.currentProfile.useDefaultFlags?.settings) {
      if (setting.scope === 1) {
        return 1;
      }
      if (this.z.isSettingAppliedForAllProfiles(setting.key) && this.settingsTarget === 3) {
        return 1;
      }
    }
    return this.settingsTarget;
  }
  H(inspectResult, isWorkspaceTrusted) {
    let { isConfigured, inspected, targetSelector, inspectedLanguageOverrides, languageSelector } = inspectResult;
    switch (targetSelector) {
      case "workspaceFolderValue":
      case "workspaceValue":
        this.isUntrusted = !!this.setting.restricted && !isWorkspaceTrusted;
        break;
    }
    let displayValue = isConfigured ? inspected[targetSelector] : inspected.defaultValue;
    const overriddenScopeList = [];
    const overriddenDefaultsLanguageList = [];
    if ((languageSelector || targetSelector !== "workspaceValue") && typeof inspected.workspaceValue !== "undefined") {
      overriddenScopeList.push("workspace:");
    }
    if ((languageSelector || targetSelector !== "userRemoteValue") && typeof inspected.userRemoteValue !== "undefined") {
      overriddenScopeList.push("remote:");
    }
    if ((languageSelector || targetSelector !== "userLocalValue") && typeof inspected.userLocalValue !== "undefined") {
      overriddenScopeList.push("user:");
    }
    if (inspected.overrideIdentifiers) {
      for (const overrideIdentifier of inspected.overrideIdentifiers) {
        const inspectedOverride = inspectedLanguageOverrides.get(overrideIdentifier);
        if (inspectedOverride) {
          if (this.u.isRegisteredLanguageId(overrideIdentifier)) {
            if (languageSelector !== overrideIdentifier && typeof inspectedOverride.default?.override !== "undefined") {
              overriddenDefaultsLanguageList.push(overrideIdentifier);
            }
            if ((languageSelector !== overrideIdentifier || targetSelector !== "workspaceValue") && typeof inspectedOverride.workspace?.override !== "undefined") {
              overriddenScopeList.push(`workspace:${overrideIdentifier}`);
            }
            if ((languageSelector !== overrideIdentifier || targetSelector !== "userRemoteValue") && typeof inspectedOverride.userRemote?.override !== "undefined") {
              overriddenScopeList.push(`remote:${overrideIdentifier}`);
            }
            if ((languageSelector !== overrideIdentifier || targetSelector !== "userLocalValue") && typeof inspectedOverride.userLocal?.override !== "undefined") {
              overriddenScopeList.push(`user:${overrideIdentifier}`);
            }
          }
          this.languageOverrideValues.set(overrideIdentifier, inspectedOverride);
        }
      }
    }
    this.overriddenScopeList = overriddenScopeList;
    this.overriddenDefaultsLanguageList = overriddenDefaultsLanguageList;
    this.defaultValueSource = this.setting.nonLanguageSpecificDefaultValueSource;
    if (inspected.policyValue) {
      this.hasPolicyValue = true;
      isConfigured = false;
      displayValue = inspected.policyValue;
      this.scopeValue = inspected.policyValue;
      this.defaultValue = inspected.defaultValue;
    } else if (languageSelector && this.languageOverrideValues.has(languageSelector)) {
      const overrideValues = this.languageOverrideValues.get(languageSelector);
      displayValue = (isConfigured ? overrideValues[targetSelector] : overrideValues.defaultValue) ?? displayValue;
      this.scopeValue = isConfigured && overrideValues[targetSelector];
      this.defaultValue = overrideValues.defaultValue ?? inspected.defaultValue;
      const registryValues = $Wn.as($Ht.Configuration).getConfigurationDefaultsOverrides();
      const source = registryValues.get(`[${languageSelector}]`)?.source;
      const overrideValueSource = source instanceof Map ? source.get(this.setting.key) : void 0;
      if (overrideValueSource) {
        this.defaultValueSource = overrideValueSource;
      }
    } else {
      this.scopeValue = isConfigured && inspected[targetSelector];
      this.defaultValue = inspected.defaultValue;
    }
    this.value = displayValue;
    this.isConfigured = isConfigured;
    if (isConfigured || this.setting.tags || this.tags || this.setting.restricted || this.hasPolicyValue) {
      this.tags = /* @__PURE__ */ new Set();
      if (isConfigured) {
        this.tags.add($wZb);
      }
      this.setting.tags?.forEach((tag2) => this.tags.add(tag2));
      if (this.setting.restricted) {
        this.tags.add($EZb);
      }
      if (this.hasPolicyValue) {
        this.tags.add($CZb);
      }
    }
  }
  matchesAllTags(tagFilters) {
    if (!tagFilters?.size) {
      return true;
    }
    if (!this.tags) {
      this.inspectSelf();
    }
    return !!this.tags?.size && Array.from(tagFilters).every((tag2) => this.tags.has(tag2));
  }
  matchesScope(scope, isRemote) {
    const configTarget = URI.isUri(scope) ? 6 : scope;
    if (!this.setting.scope) {
      return true;
    }
    if (configTarget === 1) {
      return $tK.includes(this.setting.scope);
    }
    if (configTarget === 6) {
      return $zK.includes(this.setting.scope);
    }
    if (configTarget === 5) {
      return $yK.includes(this.setting.scope);
    }
    if (configTarget === 4) {
      return $xK.includes(this.setting.scope);
    }
    if (configTarget === 3) {
      if (isRemote) {
        return $wK.includes(this.setting.scope);
      }
    }
    return true;
  }
  matchesAnyExtension(extensionFilters) {
    if (!extensionFilters || !extensionFilters.size) {
      return true;
    }
    if (!this.setting.extensionInfo) {
      return false;
    }
    return Array.from(extensionFilters).some((extensionId) => extensionId.toLowerCase() === this.setting.extensionInfo.id.toLowerCase());
  }
  matchesAnyFeature(featureFilters) {
    if (!featureFilters || !featureFilters.size) {
      return true;
    }
    const features = $f1b.children.find((child) => child.id === "features");
    return Array.from(featureFilters).some((filter) => {
      if (features && features.children) {
        const feature = features.children.find((feature2) => "features/" + filter === feature2.id);
        if (feature) {
          const patterns = feature.settings?.map((setting) => createSettingMatchRegExp(setting));
          return patterns && !this.setting.extensionInfo && patterns.some((pattern) => pattern.test(this.setting.key.toLowerCase()));
        } else {
          return false;
        }
      } else {
        return false;
      }
    });
  }
  matchesAnyId(idFilters) {
    if (!idFilters || !idFilters.size) {
      return true;
    }
    return idFilters.has(this.setting.key);
  }
  matchesAllLanguages(languageFilter) {
    if (!languageFilter) {
      return true;
    }
    if (!this.u.isRegisteredLanguageId(languageFilter)) {
      return false;
    }
    if (this.setting.scope === 5) {
      return true;
    }
    return false;
  }
};
function createSettingMatchRegExp(pattern) {
  pattern = $Af(pattern).replace(/\\\*/g, ".*");
  return new RegExp(`^${pattern}$`, "i");
}
var $n1b = class $n1b2 {
  constructor(f, g, h3, i2, j, l) {
    this.f = f;
    this.g = g;
    this.h = h3;
    this.i = i2;
    this.j = j;
    this.l = l;
    this.e = /* @__PURE__ */ new Map();
  }
  get root() {
    return this.c;
  }
  update(newTocRoot = this.d) {
    this.e.clear();
    const newRoot = this.r(newTocRoot);
    if (newRoot.children[0] instanceof $k1b) {
      newRoot.children[0].isFirstGroup = true;
    }
    if (this.c) {
      this.n(this.c.children);
      this.c.children = newRoot.children;
    } else {
      this.c = newRoot;
    }
  }
  updateWorkspaceTrust(workspaceTrusted) {
    this.g = workspaceTrusted;
    this.p();
  }
  n(children) {
    for (const child of children) {
      this.o(child);
    }
  }
  o(element) {
    if (element instanceof $k1b) {
      this.n(element.children);
    }
    element.dispose();
  }
  getElementsByName(name) {
    return this.e.get(name) ?? null;
  }
  updateElementsByName(name) {
    if (!this.e.has(name)) {
      return;
    }
    this.q(this.e.get(name));
  }
  p() {
    this.q([...this.e.values()].flat().filter((s) => s.isUntrusted));
  }
  q(settings) {
    for (const element of settings) {
      element.inspectSelf();
    }
  }
  r(tocEntry, parent) {
    const depth = parent ? this.u(parent) + 1 : 0;
    const element = new $k1b(tocEntry.id, void 0, tocEntry.label, depth, false);
    element.parent = parent;
    const children = [];
    if (tocEntry.settings) {
      const settingChildren = tocEntry.settings.map((s) => this.w(s, element)).filter((el) => el.setting.deprecationMessage ? el.isConfigured : true);
      children.push(...settingChildren);
    }
    if (tocEntry.children) {
      const groupChildren = tocEntry.children.map((child) => this.r(child, element));
      children.push(...groupChildren);
    }
    element.children = children;
    return element;
  }
  u(element) {
    if (element.parent) {
      return 1 + this.u(element.parent);
    } else {
      return 0;
    }
  }
  w(setting, parent) {
    const element = new $m1b(setting, parent, this.f.settingsTarget, this.g, this.f.languageFilter, this.i, this.l, this.j, this.h);
    const nameElements = this.e.get(setting.key) || [];
    nameElements.push(element);
    this.e.set(setting.key, nameElements);
    return element;
  }
};
$n1b = __decorate([
  __param(2, $EK),
  __param(3, $1E),
  __param(4, $gT),
  __param(5, $Vu)
], $n1b);
function $o1b(key2, target, languageFilter, configurationService) {
  const inspectOverrides = URI.isUri(target) ? { resource: target } : void 0;
  const inspected = configurationService.inspect(key2, inspectOverrides);
  const targetSelector = target === 1 ? "applicationValue" : target === 3 ? "userLocalValue" : target === 4 ? "userRemoteValue" : target === 5 ? "workspaceValue" : "workspaceFolderValue";
  const targetOverrideSelector = target === 1 ? "application" : target === 3 ? "userLocal" : target === 4 ? "userRemote" : target === 5 ? "workspace" : "workspaceFolder";
  let isConfigured = typeof inspected[targetSelector] !== "undefined";
  const overrideIdentifiers = inspected.overrideIdentifiers;
  const inspectedLanguageOverrides = /* @__PURE__ */ new Map();
  if (languageFilter) {
    isConfigured = false;
  }
  if (overrideIdentifiers) {
    for (const overrideIdentifier of overrideIdentifiers) {
      inspectedLanguageOverrides.set(overrideIdentifier, configurationService.inspect(key2, { overrideIdentifier }));
    }
    if (languageFilter) {
      if (inspectedLanguageOverrides.has(languageFilter)) {
        const overrideValue = inspectedLanguageOverrides.get(languageFilter)[targetOverrideSelector]?.override;
        if (typeof overrideValue !== "undefined") {
          isConfigured = true;
        }
      }
    }
  }
  return { isConfigured, inspected, targetSelector, inspectedLanguageOverrides, languageSelector: languageFilter };
}
function sanitizeId(id2) {
  return id2.replace(/[\.\/]/, "_");
}
function $p1b(key2, groupId = "", isLanguageTagSetting = false) {
  const lastDotIdx = key2.lastIndexOf(".");
  let category8 = "";
  if (lastDotIdx >= 0) {
    category8 = key2.substring(0, lastDotIdx);
    key2 = key2.substring(lastDotIdx + 1);
  }
  groupId = groupId.replace(/\//g, ".");
  category8 = trimCategoryForGroup(category8, groupId);
  category8 = wordifyKey(category8);
  if (isLanguageTagSetting) {
    key2 = key2.replace(/[\[\]]/g, "");
    key2 = "$(bracket) " + key2;
  }
  const label3 = wordifyKey(key2);
  return { category: category8, label: label3 };
}
function wordifyKey(key2) {
  key2 = key2.replace(/\.([a-z0-9])/g, (_, p1) => ` \u203A ${p1.toUpperCase()}`).replace(/([a-z0-9])([A-Z])/g, "$1 $2").replace(/^[a-z]/g, (match) => match.toUpperCase()).replace(/\b\w+\b/g, (match) => {
    return $g1b.has(match.toLowerCase()) ? match.toUpperCase() : match;
  });
  for (const [k, v] of $h1b) {
    key2 = key2.replace(new RegExp(`\\b${k}\\b`, "gi"), v);
  }
  return key2;
}
function trimCategoryForGroup(category8, groupId) {
  const doTrim = (forward) => {
    if (!/insiders$/i.test(category8)) {
      groupId = groupId.replace(/-?insiders$/i, "");
    }
    const parts = groupId.split(".").map((part) => {
      if (part.replace(/-/g, "").toLowerCase() === category8.toLowerCase()) {
        return part.replace(/-/g, "");
      } else {
        return part;
      }
    });
    while (parts.length) {
      const reg2 = new RegExp(`^${parts.join("\\.")}(\\.|$)`, "i");
      if (reg2.test(category8)) {
        return category8.replace(reg2, "");
      }
      if (forward) {
        parts.pop();
      } else {
        parts.shift();
      }
    }
    return null;
  };
  let trimmed = doTrim(true);
  if (trimmed === null) {
    trimmed = doTrim(false);
  }
  if (trimmed === null) {
    trimmed = category8;
  }
  return trimmed;
}
function isExtensionToggleSetting(setting, productService) {
  return $HZb && !!productService.extensionRecommendations && !!setting.displayExtensionId;
}
function isExcludeSetting(setting) {
  return setting.key === "files.exclude" || setting.key === "search.exclude" || setting.key === "workbench.localHistory.exclude" || setting.key === "explorer.autoRevealExclude" || setting.key === "files.readonlyExclude" || setting.key === "files.watcherExclude";
}
function isIncludeSetting(setting) {
  return setting.key === "files.readonlyInclude";
}
function $q1b(key2) {
  return key2 === "workbench.editor.customLabels.patterns";
}
function isSimpleType(type) {
  return type === "string" || type === "boolean" || type === "integer" || type === "number";
}
function getObjectRenderableSchemaType(schema9, key2) {
  const { type } = schema9;
  if (Array.isArray(type)) {
    if ($q1b(key2) && type.length === 2) {
      if (type.includes("null") && (type.includes("string") || type.includes("boolean") || type.includes("integer") || type.includes("number"))) {
        return "simple";
      }
    }
    for (const t of type) {
      if (!isSimpleType(t)) {
        return false;
      }
    }
    return "complex";
  }
  if (isSimpleType(type)) {
    return "simple";
  }
  if (type === "array") {
    if (schema9.items) {
      const itemSchemas = Array.isArray(schema9.items) ? schema9.items : [schema9.items];
      for (const { type: type2 } of itemSchemas) {
        if (Array.isArray(type2)) {
          for (const t of type2) {
            if (!isSimpleType(t)) {
              return false;
            }
          }
          return "complex";
        }
        if (!isSimpleType(type2)) {
          return false;
        }
        return "complex";
      }
    }
    return false;
  }
  return false;
}
function getObjectSettingSchemaType({ key: key2, type, objectProperties, objectPatternProperties, objectAdditionalProperties }) {
  if (type !== "object") {
    return false;
  }
  if ($Ig(objectProperties) && $Ig(objectPatternProperties) && $Ig(objectAdditionalProperties)) {
    return false;
  }
  if ((objectAdditionalProperties === true || objectAdditionalProperties === void 0) && !Object.keys(objectPatternProperties ?? {}).includes(".*")) {
    return false;
  }
  const schemas2 = [...Object.values(objectProperties ?? {}), ...Object.values(objectPatternProperties ?? {})];
  if (objectAdditionalProperties && typeof objectAdditionalProperties === "object") {
    schemas2.push(objectAdditionalProperties);
  }
  let schemaType = "simple";
  for (const schema9 of schemas2) {
    for (const subSchema of Array.isArray(schema9.anyOf) ? schema9.anyOf : [schema9]) {
      const subSchemaType = getObjectRenderableSchemaType(subSchema, key2);
      if (subSchemaType === false) {
        return false;
      }
      if (subSchemaType === "complex") {
        schemaType = "complex";
      }
    }
  }
  return schemaType;
}
function settingTypeEnumRenderable(_type) {
  const enumRenderableSettingTypes = ["string", "boolean", "null", "integer", "number"];
  const type = Array.isArray(_type) ? _type : [_type];
  return type.every((type2) => enumRenderableSettingTypes.includes(type2));
}
var SearchResultIdx;
(function(SearchResultIdx2) {
  SearchResultIdx2[SearchResultIdx2["Local"] = 0] = "Local";
  SearchResultIdx2[SearchResultIdx2["Remote"] = 1] = "Remote";
  SearchResultIdx2[SearchResultIdx2["NewExtensions"] = 2] = "NewExtensions";
})(SearchResultIdx || (SearchResultIdx = {}));
var $r1b = class $r1b2 extends $n1b {
  constructor(viewState, settingsOrderByTocIndex, isWorkspaceTrusted, configurationService, C, languageService, userDataProfileService, productService) {
    super(viewState, isWorkspaceTrusted, configurationService, languageService, userDataProfileService, productService);
    this.C = C;
    this.x = null;
    this.y = null;
    this.z = null;
    this.A = null;
    this.id = "searchResultModel";
    this.B = settingsOrderByTocIndex;
    this.update({ id: "searchResultModel", label: "" });
  }
  D(filterMatches) {
    if (this.B) {
      for (const match of filterMatches) {
        match.setting.internalOrder = this.B.get(match.setting.key);
      }
    }
    if (!this.f.query) {
      return filterMatches.sort((a, b) => $KZb(a.setting.internalOrder, b.setting.internalOrder));
    }
    filterMatches.sort((a, b) => {
      if (a.matchType !== b.matchType) {
        return b.matchType - a.matchType;
      } else if (a.matchType === SettingMatchType.RemoteMatch) {
        return b.score - a.score;
      } else {
        return $KZb(a.setting.internalOrder, b.setting.internalOrder);
      }
    });
    return $Rb(filterMatches, (match) => match.setting.key);
  }
  getUniqueResults() {
    if (this.y) {
      return this.y;
    }
    if (!this.x) {
      return null;
    }
    let combinedFilterMatches = [];
    const localMatchKeys = /* @__PURE__ */ new Set();
    const localResult = this.x[
      0
      /* SearchResultIdx.Local */
    ];
    if (localResult) {
      localResult.filterMatches.forEach((m) => localMatchKeys.add(m.setting.key));
      combinedFilterMatches = localResult.filterMatches;
    }
    const remoteResult = this.x[
      1
      /* SearchResultIdx.Remote */
    ];
    if (remoteResult) {
      remoteResult.filterMatches = remoteResult.filterMatches.filter((m) => !localMatchKeys.has(m.setting.key));
      combinedFilterMatches = combinedFilterMatches.concat(remoteResult.filterMatches);
      this.z = this.x[
        2
        /* SearchResultIdx.NewExtensions */
      ];
    }
    combinedFilterMatches = this.D(combinedFilterMatches);
    this.y = {
      filterMatches: combinedFilterMatches,
      exactMatch: localResult?.exactMatch || remoteResult?.exactMatch
    };
    return this.y;
  }
  getRawResults() {
    return this.x || [];
  }
  setResult(order, result) {
    this.y = null;
    this.z = null;
    this.x = this.x || [];
    if (!result) {
      delete this.x[order];
      return;
    }
    if (result.exactMatch) {
      this.x = [];
    }
    this.x[order] = result;
    this.updateChildren();
  }
  updateChildren() {
    this.update({
      id: "searchResultModel",
      label: "searchResultModel",
      settings: this.E()
    });
    const isRemote = !!this.C.remoteAuthority;
    this.root.children = this.root.children.filter((child) => child instanceof $m1b && child.matchesAllTags(this.f.tagFilters) && child.matchesScope(this.f.settingsTarget, isRemote) && child.matchesAnyExtension(this.f.extensionFilters) && child.matchesAnyId(this.f.idFilters) && child.matchesAnyFeature(this.f.featureFilters) && child.matchesAllLanguages(this.f.languageFilter));
    this.A = this.root.children.length;
    if (this.z?.filterMatches.length) {
      let resultExtensionIds = this.z.filterMatches.map((result) => result.setting).filter((setting) => setting.extensionName && setting.extensionPublisher).map((setting) => `${setting.extensionPublisher}.${setting.extensionName}`);
      resultExtensionIds = $Rb(resultExtensionIds);
      if (resultExtensionIds.length) {
        const newExtElement = new $l1b("newExtensions", resultExtensionIds);
        newExtElement.parent = this.c;
        this.c.children.push(newExtElement);
      }
    }
  }
  getUniqueResultsCount() {
    return this.A ?? 0;
  }
  E() {
    return this.getUniqueResults()?.filterMatches.map((m) => m.setting) ?? [];
  }
};
$r1b = __decorate([
  __param(3, $EK),
  __param(4, $US),
  __param(5, $1E),
  __param(6, $gT),
  __param(7, $Vu)
], $r1b);
var tagRegex = /(^|\s)@tag:("([^"]*)"|[^"]\S*)/g;
var extensionRegex = /(^|\s)@ext:("([^"]*)"|[^"]\S*)?/g;
var featureRegex = /(^|\s)@feature:("([^"]*)"|[^"]\S*)?/g;
var idRegex = /(^|\s)@id:("([^"]*)"|[^"]\S*)?/g;
var languageRegex = /(^|\s)@lang:("([^"]*)"|[^"]\S*)?/g;
function $s1b(query) {
  function getTagsForType(query2, filterRegex, parsedParts) {
    return query2.replace(filterRegex, (_, __, quotedParsedElement, unquotedParsedElement) => {
      const parsedElement = unquotedParsedElement || quotedParsedElement;
      if (parsedElement) {
        parsedParts.push(...parsedElement.split(",").map((s) => s.trim()).filter((s) => !$vf(s)));
      }
      return "";
    });
  }
  const tags = [];
  query = query.replace(tagRegex, (_, __, quotedTag, tag2) => {
    tags.push(tag2 || quotedTag);
    return "";
  });
  query = query.replace(`@${$wZb}`, () => {
    tags.push($wZb);
    return "";
  });
  query = query.replace(`@${$CZb}`, () => {
    tags.push($CZb);
    return "";
  });
  const extensions = [];
  const features = [];
  const ids = [];
  const langs = [];
  query = getTagsForType(query, extensionRegex, extensions);
  query = getTagsForType(query, featureRegex, features);
  query = getTagsForType(query, idRegex, ids);
  if ($GZb) {
    query = getTagsForType(query, languageRegex, langs);
  }
  query = query.trim();
  return {
    tags,
    extensionFilters: extensions,
    featureFilters: features,
    idFilters: ids,
    languageFilter: langs.length ? langs[0] : void 0,
    query
  };
}

// out-build/vs/workbench/contrib/preferences/browser/settingsWidgets.js
var $117 = $;
var $v1b = class {
  get items() {
    const items = this.a.map((item, i2) => {
      const editing = typeof this.b === "number" && this.b === i2;
      return {
        ...item,
        editing,
        selected: i2 === this.d || editing
      };
    });
    if (this.b === "create") {
      items.push({
        editing: true,
        selected: true,
        ...this.f
      });
    }
    return items;
  }
  constructor(newItem) {
    this.a = [];
    this.b = null;
    this.d = null;
    this.f = newItem;
  }
  setEditKey(key2) {
    this.b = key2;
  }
  setValue(listData) {
    this.a = listData;
  }
  select(idx) {
    this.d = idx;
  }
  getSelected() {
    return this.d;
  }
  selectNext() {
    if (typeof this.d === "number") {
      this.d = Math.min(this.d + 1, this.a.length - 1);
    } else {
      this.d = 0;
    }
  }
  selectPrevious() {
    if (typeof this.d === "number") {
      this.d = Math.max(this.d - 1, 0);
    } else {
      this.d = 0;
    }
  }
};
var $w1b = class $w1b2 extends $3c {
  get domNode() {
    return this.a;
  }
  get items() {
    return this.g.items;
  }
  get j() {
    return false;
  }
  constructor(m, n, r2) {
    super();
    this.m = m;
    this.n = n;
    this.r = r2;
    this.b = [];
    this.f = this.B(new $ze());
    this.g = new $v1b(this.s());
    this.h = this.B(new $2c());
    this.onDidChangeList = this.f.event;
    this.a = $bk(m, $117("div"));
    this.a.setAttribute("role", "list");
    this.t().forEach((c) => this.a.classList.add(c));
    $bk(m, this.N());
    this.G();
    this.B($_i(this.a, $7j.POINTER_DOWN, (e) => this.O(e)));
    this.B($_i(this.a, $7j.DBLCLICK, (e) => this.P(e)));
    this.B($aj(this.a, "keydown", (e) => {
      if (e.equals(
        16
        /* KeyCode.UpArrow */
      )) {
        this.U();
      } else if (e.equals(
        18
        /* KeyCode.DownArrow */
      )) {
        this.S();
      } else {
        return;
      }
      e.preventDefault();
      e.stopPropagation();
    }));
  }
  setValue(listData) {
    this.g.setValue(listData);
    this.G();
  }
  D() {
    return;
  }
  F() {
    return true;
  }
  G() {
    const focused = $Nj(this.a);
    $$i(this.a);
    this.h.clear();
    const newMode = this.g.items.some((item) => !!(item.editing && this.isItemNew(item)));
    this.m.classList.toggle("setting-list-hide-add-button", !this.F() || newMode);
    if (this.g.items.length) {
      this.a.tabIndex = 0;
    } else {
      this.a.removeAttribute("tabIndex");
    }
    const header = this.D();
    if (header) {
      this.a.appendChild(header);
    }
    this.b = this.g.items.map((item, i2) => this.L(item, i2, focused));
    this.b.forEach((rowElement) => this.a.appendChild(rowElement));
  }
  H(value) {
    const selectBoxOptions = value.options.map(({ value: value2, description }) => ({ text: value2, description }));
    const selected = value.options.findIndex((option) => value.data === option.value);
    const styles = $L$({
      selectBackground: $VZb,
      selectForeground: $WZb,
      selectBorder: $XZb,
      selectListBorder: $YZb
    });
    const selectBox = new $N1(selectBoxOptions, selected, this.r, styles, {
      useCustomDrawn: !($u && $5e.pointerEvents)
    });
    return selectBox;
  }
  I(idx) {
    this.g.setEditKey(idx);
    this.G();
  }
  cancelEdit() {
    this.g.setEditKey("none");
    this.G();
  }
  J(originalItem, changedItem, idx) {
    this.g.setEditKey("none");
    if (this.isItemNew(originalItem)) {
      this.f.fire({
        type: "add",
        newItem: changedItem,
        targetIndex: idx
      });
    } else {
      this.f.fire({
        type: "change",
        originalItem,
        newItem: changedItem,
        targetIndex: idx
      });
    }
    this.G();
  }
  L(item, idx, listFocused) {
    const rowElement = item.editing ? this.y(item, idx) : this.M(item, idx, listFocused);
    rowElement.setAttribute("role", "listitem");
    return rowElement;
  }
  M(item, idx, listFocused) {
    const rowElementGroup = this.w(item, idx);
    const rowElement = rowElementGroup.rowElement;
    rowElement.setAttribute("data-index", idx + "");
    rowElement.setAttribute("tabindex", item.selected ? "0" : "-1");
    rowElement.classList.toggle("selected", item.selected);
    const actionBar = new $LZ(rowElement);
    this.h.add(actionBar);
    actionBar.push(this.u(item, idx), { icon: true, label: true });
    this.z(rowElementGroup, item);
    if (item.selected && listFocused) {
      $Xh(() => rowElement.focus(), void 0, this.h);
    }
    this.h.add($_i(rowElement, "click", (e) => {
      e.stopPropagation();
    }));
    return rowElement;
  }
  N() {
    const rowElement = $117(".setting-list-new-row");
    const startAddButton = this.B(new $k2(rowElement, $q$));
    startAddButton.label = this.C().addButtonLabel;
    startAddButton.element.classList.add("setting-list-addButton");
    this.B(startAddButton.onDidClick(() => {
      this.g.setEditKey("create");
      this.G();
    }));
    return rowElement;
  }
  O(e) {
    const targetIdx = this.Q(e);
    if (targetIdx < 0) {
      return;
    }
    e.preventDefault();
    e.stopImmediatePropagation();
    if (this.g.getSelected() === targetIdx) {
      return;
    }
    this.R(targetIdx);
  }
  P(e) {
    const targetIdx = this.Q(e);
    if (targetIdx < 0) {
      return;
    }
    if (this.j) {
      return;
    }
    const item = this.g.items[targetIdx];
    if (item) {
      this.I(targetIdx);
      e.preventDefault();
      e.stopPropagation();
    }
  }
  Q(e) {
    if (!e.target) {
      return -1;
    }
    const actionbar = $Gj(e.target, "monaco-action-bar");
    if (actionbar) {
      return -1;
    }
    const element = $Gj(e.target, "setting-list-row");
    if (!element) {
      return -1;
    }
    const targetIdxStr = element.getAttribute("data-index");
    if (!targetIdxStr) {
      return -1;
    }
    const targetIdx = parseInt(targetIdxStr);
    return targetIdx;
  }
  R(idx) {
    this.g.select(idx);
    this.b.forEach((row) => row.classList.remove("selected"));
    const selectedRow = this.b[this.g.getSelected()];
    selectedRow.classList.add("selected");
    selectedRow.focus();
  }
  S() {
    this.g.selectNext();
    this.R(this.g.getSelected());
  }
  U() {
    this.g.selectPrevious();
    this.R(this.g.getSelected());
  }
};
$w1b = __decorate([
  __param(1, $gs),
  __param(2, $40)
], $w1b);
var $x1b = class $x1b2 extends $w1b {
  setValue(listData, options3) {
    this.W = options3?.keySuggester;
    this.X = options3?.showAddButton ?? true;
    super.setValue(listData);
  }
  constructor(container2, themeService, contextViewService, Y) {
    super(container2, themeService, contextViewService);
    this.Y = Y;
    this.X = true;
  }
  s() {
    return {
      value: {
        type: "string",
        data: ""
      }
    };
  }
  F() {
    return this.X;
  }
  t() {
    return ["setting-list-widget"];
  }
  u(item, idx) {
    if (this.j) {
      return [];
    }
    return [
      {
        class: ThemeIcon.asClassName($OYb),
        enabled: true,
        id: "workbench.action.editListItem",
        tooltip: this.C().editActionTooltip,
        run: () => this.I(idx)
      },
      {
        class: ThemeIcon.asClassName($PYb),
        enabled: true,
        id: "workbench.action.removeListItem",
        tooltip: this.C().deleteActionTooltip,
        run: () => this.f.fire({ type: "remove", originalItem: item, targetIndex: idx })
      }
    ];
  }
  eb(item) {
    const dragImage = $117(".monaco-drag-image");
    dragImage.textContent = item.value.data;
    return dragImage;
  }
  w(item, idx) {
    const rowElement = $117(".setting-list-row");
    const valueElement = $bk(rowElement, $117(".setting-list-value"));
    const siblingElement = $bk(rowElement, $117(".setting-list-sibling"));
    valueElement.textContent = item.value.data.toString();
    siblingElement.textContent = item.sibling ? `when: ${item.sibling}` : null;
    this.gb(rowElement, item, idx);
    return { rowElement, keyElement: valueElement, valueElement: siblingElement };
  }
  gb(rowElement, item, idx) {
    if (this.g.items.every((item2) => !item2.editing)) {
      rowElement.draggable = true;
      rowElement.classList.add("draggable");
    } else {
      rowElement.draggable = false;
      rowElement.classList.remove("draggable");
    }
    this.h.add($_i(rowElement, $7j.DRAG_START, (ev) => {
      this.db = {
        element: rowElement,
        item,
        itemIndex: idx
      };
      if (ev.dataTransfer) {
        ev.dataTransfer.dropEffect = "move";
        const dragImage = this.eb(item);
        rowElement.ownerDocument.body.appendChild(dragImage);
        ev.dataTransfer.setDragImage(dragImage, -10, -10);
        setTimeout(() => dragImage.remove(), 0);
      }
    }));
    this.h.add($_i(rowElement, $7j.DRAG_OVER, (ev) => {
      if (!this.db) {
        return false;
      }
      ev.preventDefault();
      if (ev.dataTransfer) {
        ev.dataTransfer.dropEffect = "move";
      }
      return true;
    }));
    let counter = 0;
    this.h.add($_i(rowElement, $7j.DRAG_ENTER, (ev) => {
      counter++;
      rowElement.classList.add("drag-hover");
    }));
    this.h.add($_i(rowElement, $7j.DRAG_LEAVE, (ev) => {
      counter--;
      if (!counter) {
        rowElement.classList.remove("drag-hover");
      }
    }));
    this.h.add($_i(rowElement, $7j.DROP, (ev) => {
      if (!this.db) {
        return false;
      }
      ev.preventDefault();
      counter = 0;
      if (this.db.element !== rowElement) {
        this.f.fire({
          type: "move",
          originalItem: this.db.item,
          sourceIndex: this.db.itemIndex,
          newItem: item,
          targetIndex: idx
        });
      }
      return true;
    }));
    this.h.add($_i(rowElement, $7j.DRAG_END, (ev) => {
      counter = 0;
      rowElement.classList.remove("drag-hover");
      ev.dataTransfer?.clearData();
      if (this.db) {
        this.db = void 0;
      }
    }));
  }
  y(item, idx) {
    const rowElement = $117(".setting-list-edit-row");
    let valueInput;
    let currentDisplayValue;
    let currentEnumOptions;
    if (this.W) {
      const enumData = this.W(this.g.items.map(({ value: { data } }) => data), idx);
      item = {
        ...item,
        value: {
          type: "enum",
          data: item.value.data,
          options: enumData ? enumData.options : []
        }
      };
    }
    switch (item.value.type) {
      case "string":
        valueInput = this.kb(item.value, rowElement);
        break;
      case "enum":
        valueInput = this.lb(item.value, rowElement);
        currentEnumOptions = item.value.options;
        if (item.value.options.length) {
          currentDisplayValue = this.isItemNew(item) ? currentEnumOptions[0].value : item.value.data;
        }
        break;
    }
    const updatedInputBoxItem = () => {
      const inputBox = valueInput;
      return {
        value: {
          type: "string",
          data: inputBox.value
        },
        sibling: siblingInput?.value
      };
    };
    const updatedSelectBoxItem = (selectedValue) => {
      return {
        value: {
          type: "enum",
          data: selectedValue,
          options: currentEnumOptions ?? []
        }
      };
    };
    const onKeyDown = (e) => {
      if (e.equals(
        3
        /* KeyCode.Enter */
      )) {
        this.J(item, updatedInputBoxItem(), idx);
      } else if (e.equals(
        9
        /* KeyCode.Escape */
      )) {
        this.cancelEdit();
        e.preventDefault();
      }
      rowElement?.focus();
    };
    if (item.value.type !== "string") {
      const selectBox = valueInput;
      this.h.add(selectBox.onDidSelect(({ selected }) => {
        currentDisplayValue = selected;
      }));
    } else {
      const inputBox = valueInput;
      this.h.add($aj(inputBox.inputElement, $7j.KEY_DOWN, onKeyDown));
    }
    let siblingInput;
    if (!$Ig(item.sibling)) {
      siblingInput = new $I2(rowElement, this.r, {
        placeholder: this.C().siblingInputPlaceholder,
        inputBoxStyles: $C$({
          inputBackground: $3Zb,
          inputForeground: $4Zb,
          inputBorder: $5Zb
        })
      });
      siblingInput.element.classList.add("setting-list-siblingInput");
      this.h.add(siblingInput);
      siblingInput.value = item.sibling;
      this.h.add($aj(siblingInput.inputElement, $7j.KEY_DOWN, onKeyDown));
    } else if (valueInput instanceof $I2) {
      valueInput.element.classList.add("no-sibling");
    }
    const okButton = this.h.add(new $k2(rowElement, $q$));
    okButton.label = localize(8998, null);
    okButton.element.classList.add("setting-list-ok-button");
    this.h.add(okButton.onDidClick(() => {
      if (item.value.type === "string") {
        this.J(item, updatedInputBoxItem(), idx);
      } else {
        this.J(item, updatedSelectBoxItem(currentDisplayValue), idx);
      }
    }));
    const cancelButton = this.h.add(new $k2(rowElement, { secondary: true, ...$q$ }));
    cancelButton.label = localize(8999, null);
    cancelButton.element.classList.add("setting-list-cancel-button");
    this.h.add(cancelButton.onDidClick(() => this.cancelEdit()));
    this.h.add($Xh(() => {
      valueInput.focus();
      if (valueInput instanceof $I2) {
        valueInput.select();
      }
    }));
    return rowElement;
  }
  isItemNew(item) {
    return item.value.data === "";
  }
  z(rowElementGroup, { value, sibling }) {
    const title = $Ig(sibling) ? localize(9e3, null, value.data) : localize(9001, null, value.data, sibling);
    const { rowElement } = rowElementGroup;
    this.h.add(this.Y.setupManagedHover($JZ("mouse"), rowElement, title));
    rowElement.setAttribute("aria-label", title);
  }
  C() {
    return {
      deleteActionTooltip: localize(9002, null),
      editActionTooltip: localize(9003, null),
      addButtonLabel: localize(9004, null),
      inputPlaceholder: localize(9005, null),
      siblingInputPlaceholder: localize(9006, null)
    };
  }
  kb(value, rowElement) {
    const valueInput = new $I2(rowElement, this.r, {
      placeholder: this.C().inputPlaceholder,
      inputBoxStyles: $C$({
        inputBackground: $3Zb,
        inputForeground: $4Zb,
        inputBorder: $5Zb
      })
    });
    valueInput.element.classList.add("setting-list-valueInput");
    this.h.add(valueInput);
    valueInput.value = value.data.toString();
    return valueInput;
  }
  lb(value, rowElement) {
    if (value.type !== "enum") {
      throw new Error("Valuetype must be enum.");
    }
    const selectBox = this.H(value);
    const wrapper = $117(".setting-list-object-list-row");
    selectBox.render(wrapper);
    rowElement.appendChild(wrapper);
    return selectBox;
  }
};
$x1b = __decorate([
  __param(1, $gs),
  __param(2, $40),
  __param(3, $5$)
], $x1b);
var $y1b = class extends $x1b {
  t() {
    return ["setting-list-include-exclude-widget"];
  }
  gb(rowElement, item, idx) {
    return;
  }
  z(rowElementGroup, item) {
    let title = $Ig(item.sibling) ? localize(9007, null, item.value.data) : localize(9008, null, item.value.data, item.sibling);
    if (item.source) {
      title += localize(9009, null, item.source);
    }
    const markdownTitle = new $bm().appendMarkdown(title);
    const { rowElement } = rowElementGroup;
    this.h.add(this.Y.setupManagedHover($JZ("mouse"), rowElement, { markdown: markdownTitle, markdownNotSupportedFallback: title }));
    rowElement.setAttribute("aria-label", title);
  }
  C() {
    return {
      deleteActionTooltip: localize(9010, null),
      editActionTooltip: localize(9011, null),
      addButtonLabel: localize(9012, null),
      inputPlaceholder: localize(9013, null),
      siblingInputPlaceholder: localize(9014, null)
    };
  }
};
var $z1b = class extends $x1b {
  t() {
    return ["setting-list-include-exclude-widget"];
  }
  gb(rowElement, item, idx) {
    return;
  }
  z(rowElementGroup, item) {
    let title = $Ig(item.sibling) ? localize(9015, null, item.value.data) : localize(9016, null, item.value.data, item.sibling);
    if (item.source) {
      title += localize(9017, null, item.source);
    }
    const markdownTitle = new $bm().appendMarkdown(title);
    const { rowElement } = rowElementGroup;
    this.h.add(this.Y.setupManagedHover($JZ("mouse"), rowElement, { markdown: markdownTitle, markdownNotSupportedFallback: title }));
    rowElement.setAttribute("aria-label", title);
  }
  C() {
    return {
      deleteActionTooltip: localize(9018, null),
      editActionTooltip: localize(9019, null),
      addButtonLabel: localize(9020, null),
      inputPlaceholder: localize(9021, null),
      siblingInputPlaceholder: localize(9022, null)
    };
  }
};
var $A1b = class $A1b2 extends $w1b {
  constructor(container2, themeService, contextViewService, bb) {
    super(container2, themeService, contextViewService);
    this.bb = bb;
    this.W = true;
    this.X = "";
    this.Y = true;
    this.Z = () => void 0;
    this.ab = () => void 0;
  }
  setValue(listData, options3) {
    this.W = !options3?.isReadOnly;
    this.Y = options3?.showAddButton ?? this.Y;
    this.Z = options3?.keySuggester ?? this.Z;
    this.ab = options3?.valueSuggester ?? this.ab;
    if ($Hg(options3) && options3.settingKey !== this.X) {
      this.g.setEditKey("none");
      this.g.select(null);
      this.X = options3.settingKey;
    }
    super.setValue(listData);
  }
  isItemNew(item) {
    return item.key.data === "" && item.value.data === "";
  }
  F() {
    return this.Y;
  }
  get j() {
    return !this.W;
  }
  s() {
    return {
      key: { type: "string", data: "" },
      value: { type: "string", data: "" },
      removable: true,
      resetable: false
    };
  }
  t() {
    return ["setting-list-object-widget"];
  }
  u(item, idx) {
    if (this.j) {
      return [];
    }
    const actions = [
      {
        class: ThemeIcon.asClassName($OYb),
        enabled: true,
        id: "workbench.action.editListItem",
        label: "",
        tooltip: this.C().editActionTooltip,
        run: () => this.I(idx)
      }
    ];
    if (item.resetable) {
      actions.push({
        class: ThemeIcon.asClassName($QYb),
        enabled: true,
        id: "workbench.action.resetListItem",
        label: "",
        tooltip: this.C().resetActionTooltip,
        run: () => this.f.fire({ type: "reset", originalItem: item, targetIndex: idx })
      });
    }
    if (item.removable) {
      actions.push({
        class: ThemeIcon.asClassName($PYb),
        enabled: true,
        id: "workbench.action.removeListItem",
        label: "",
        tooltip: this.C().deleteActionTooltip,
        run: () => this.f.fire({ type: "remove", originalItem: item, targetIndex: idx })
      });
    }
    return actions;
  }
  D() {
    const header = $117(".setting-list-row-header");
    const keyHeader = $bk(header, $117(".setting-list-object-key"));
    const valueHeader = $bk(header, $117(".setting-list-object-value"));
    const { keyHeaderText, valueHeaderText } = this.C();
    keyHeader.textContent = keyHeaderText;
    valueHeader.textContent = valueHeaderText;
    return header;
  }
  w(item, idx) {
    const rowElement = $117(".setting-list-row");
    rowElement.classList.add("setting-list-object-row");
    const keyElement = $bk(rowElement, $117(".setting-list-object-key"));
    const valueElement = $bk(rowElement, $117(".setting-list-object-value"));
    keyElement.textContent = item.key.data;
    valueElement.textContent = item.value.data.toString();
    return { rowElement, keyElement, valueElement };
  }
  y(item, idx) {
    const rowElement = $117(".setting-list-edit-row.setting-list-object-row");
    const changedItem = { ...item };
    const onKeyChange = (key2) => {
      changedItem.key = key2;
      okButton.enabled = key2.data !== "";
      const suggestedValue = this.ab(key2.data) ?? item.value;
      if (this.nb(item.value, changedItem.value, suggestedValue)) {
        onValueChange(suggestedValue);
        renderLatestValue();
      }
    };
    const onValueChange = (value) => {
      changedItem.value = value;
    };
    let keyWidget;
    let keyElement;
    if (this.Y) {
      if (this.isItemNew(item)) {
        const suggestedKey = this.Z(this.g.items.map(({ key: { data } }) => data));
        if ($Hg(suggestedKey)) {
          changedItem.key = suggestedKey;
          const suggestedValue = this.ab(changedItem.key.data);
          onValueChange(suggestedValue ?? changedItem.value);
        }
      }
      const { widget, element } = this.kb(changedItem.key, {
        idx,
        isKey: true,
        originalItem: item,
        changedItem,
        update: onKeyChange
      });
      keyWidget = widget;
      keyElement = element;
    } else {
      keyElement = $117(".setting-list-object-key");
      keyElement.textContent = item.key.data;
    }
    let valueWidget;
    const valueContainer = $117(".setting-list-object-value-container");
    const renderLatestValue = () => {
      const { widget, element } = this.kb(changedItem.value, {
        idx,
        isKey: false,
        originalItem: item,
        changedItem,
        update: onValueChange
      });
      valueWidget = widget;
      $$i(valueContainer);
      valueContainer.append(element);
    };
    renderLatestValue();
    rowElement.append(keyElement, valueContainer);
    const okButton = this.h.add(new $k2(rowElement, $q$));
    okButton.enabled = changedItem.key.data !== "";
    okButton.label = localize(9023, null);
    okButton.element.classList.add("setting-list-ok-button");
    this.h.add(okButton.onDidClick(() => this.J(item, changedItem, idx)));
    const cancelButton = this.h.add(new $k2(rowElement, { secondary: true, ...$q$ }));
    cancelButton.label = localize(9024, null);
    cancelButton.element.classList.add("setting-list-cancel-button");
    this.h.add(cancelButton.onDidClick(() => this.cancelEdit()));
    this.h.add($Xh(() => {
      const widget = keyWidget ?? valueWidget;
      widget.focus();
      if (widget instanceof $I2) {
        widget.select();
      }
    }));
    return rowElement;
  }
  kb(keyOrValue, options3) {
    switch (keyOrValue.type) {
      case "string":
        return this.lb(keyOrValue, options3);
      case "enum":
        return this.mb(keyOrValue, options3);
      case "boolean":
        return this.mb({
          type: "enum",
          data: keyOrValue.data.toString(),
          options: [{ value: "true" }, { value: "false" }]
        }, options3);
    }
  }
  lb(keyOrValue, { idx, isKey, originalItem, changedItem, update }) {
    const wrapper = $117(isKey ? ".setting-list-object-input-key" : ".setting-list-object-input-value");
    const inputBox = new $I2(wrapper, this.r, {
      placeholder: isKey ? localize(9025, null) : localize(9026, null),
      inputBoxStyles: $C$({
        inputBackground: $3Zb,
        inputForeground: $4Zb,
        inputBorder: $5Zb
      })
    });
    inputBox.element.classList.add("setting-list-object-input");
    this.h.add(inputBox);
    inputBox.value = keyOrValue.data;
    this.h.add(inputBox.onDidChange((value) => update({ ...keyOrValue, data: value })));
    const onKeyDown = (e) => {
      if (e.equals(
        3
        /* KeyCode.Enter */
      )) {
        this.J(originalItem, changedItem, idx);
      } else if (e.equals(
        9
        /* KeyCode.Escape */
      )) {
        this.cancelEdit();
        e.preventDefault();
      }
    };
    this.h.add($aj(inputBox.inputElement, $7j.KEY_DOWN, onKeyDown));
    return { widget: inputBox, element: wrapper };
  }
  mb(keyOrValue, { isKey, changedItem, update }) {
    const selectBox = this.H(keyOrValue);
    const changedKeyOrValue = isKey ? changedItem.key : changedItem.value;
    this.h.add(selectBox.onDidSelect(({ selected: selected2 }) => update(changedKeyOrValue.type === "boolean" ? { ...changedKeyOrValue, data: selected2 === "true" ? true : false } : { ...changedKeyOrValue, data: selected2 })));
    const wrapper = $117(".setting-list-object-input");
    wrapper.classList.add(isKey ? "setting-list-object-input-key" : "setting-list-object-input-value");
    selectBox.render(wrapper);
    const selected = keyOrValue.options.findIndex((option) => keyOrValue.data === option.value);
    if (selected === -1 && keyOrValue.options.length) {
      update(changedKeyOrValue.type === "boolean" ? { ...changedKeyOrValue, data: true } : { ...changedKeyOrValue, data: keyOrValue.options[0].value });
    } else if (changedKeyOrValue.type === "boolean") {
      update({ ...changedKeyOrValue, data: keyOrValue.data === "true" });
    }
    return { widget: selectBox, element: wrapper };
  }
  nb(originalValue, previousValue, newValue) {
    if (newValue.type !== "enum" && newValue.type === previousValue.type && newValue.data === previousValue.data) {
      return false;
    }
    if (originalValue.data === "") {
      return true;
    }
    if (previousValue.type === newValue.type && newValue.type !== "enum") {
      return false;
    }
    if (previousValue.type === "enum" && newValue.type === "enum") {
      const previousEnums = new Set(previousValue.options.map(({ value }) => value));
      newValue.options.forEach(({ value }) => previousEnums.delete(value));
      if (previousEnums.size === 0) {
        return false;
      }
    }
    return true;
  }
  z(rowElementGroup, item) {
    const { keyElement, valueElement, rowElement } = rowElementGroup;
    let accessibleDescription;
    if (item.source) {
      accessibleDescription = localize(9027, null, item.key.data, item.value.data, item.source);
    } else {
      accessibleDescription = localize(9028, null, item.key.data, item.value.data);
    }
    const markdownString = { markdown: new $bm().appendMarkdown(accessibleDescription), markdownNotSupportedFallback: accessibleDescription };
    const keyDescription = this.pb(item.key) ?? item.keyDescription ?? markdownString;
    this.h.add(this.bb.setupManagedHover($JZ("mouse"), keyElement, keyDescription));
    const valueDescription = this.pb(item.value) ?? markdownString;
    this.h.add(this.bb.setupManagedHover($JZ("mouse"), valueElement, valueDescription));
    rowElement.setAttribute("aria-label", accessibleDescription);
  }
  pb(keyOrValue) {
    const enumDescription = keyOrValue.type === "enum" ? keyOrValue.options.find(({ value }) => keyOrValue.data === value)?.description : void 0;
    return enumDescription;
  }
  C() {
    return {
      deleteActionTooltip: localize(9029, null),
      resetActionTooltip: localize(9030, null),
      editActionTooltip: localize(9031, null),
      addButtonLabel: localize(9032, null),
      keyHeaderText: localize(9033, null),
      valueHeaderText: localize(9034, null)
    };
  }
};
$A1b = __decorate([
  __param(1, $gs),
  __param(2, $40),
  __param(3, $5$)
], $A1b);
var $B1b = class $B1b2 extends $w1b {
  constructor(container2, themeService, contextViewService, X) {
    super(container2, themeService, contextViewService);
    this.X = X;
    this.W = "";
  }
  setValue(listData, options3) {
    if ($Hg(options3) && options3.settingKey !== this.W) {
      this.g.setEditKey("none");
      this.g.select(null);
      this.W = options3.settingKey;
    }
    super.setValue(listData);
  }
  isItemNew(item) {
    return !item.key.data && !item.value.data;
  }
  s() {
    return {
      key: { type: "string", data: "" },
      value: { type: "boolean", data: false },
      removable: false,
      resetable: true
    };
  }
  t() {
    return ["setting-list-object-widget"];
  }
  u(item, idx) {
    return [];
  }
  F() {
    return false;
  }
  D() {
    return void 0;
  }
  L(item, idx, listFocused) {
    const rowElement = this.y(item, idx);
    rowElement.setAttribute("role", "listitem");
    return rowElement;
  }
  w(item, idx) {
    const rowElement = $117(".blank-row");
    const keyElement = $117(".blank-row-key");
    return { rowElement, keyElement };
  }
  y(item, idx) {
    const rowElement = $117(".setting-list-edit-row.setting-list-object-row.setting-item-bool");
    const changedItem = { ...item };
    const onValueChange = (newValue) => {
      changedItem.value.data = newValue;
      this.J(item, changedItem, idx);
    };
    const checkboxDescription = item.keyDescription ? `${item.keyDescription} (${item.key.data})` : item.key.data;
    const { element, widget: checkbox } = this.gb(changedItem.value.data, checkboxDescription, onValueChange);
    rowElement.appendChild(element);
    const valueElement = $bk(rowElement, $117(".setting-list-object-value"));
    valueElement.textContent = checkboxDescription;
    const rowElementGroup = { rowElement, keyElement: valueElement, valueElement: checkbox.domNode };
    this.z(rowElementGroup, item);
    this.B($_i(valueElement, $7j.MOUSE_DOWN, (e) => {
      const targetElement = e.target;
      if (targetElement.tagName.toLowerCase() !== "a") {
        checkbox.checked = !checkbox.checked;
        onValueChange(checkbox.checked);
      }
      $9j.stop(e);
    }));
    return rowElement;
  }
  gb(value, checkboxDescription, onValueChange) {
    const checkbox = new $Q1({
      icon: $6l.check,
      actionClassName: "setting-value-checkbox",
      isChecked: value,
      title: checkboxDescription,
      ...$O1
    });
    this.h.add(checkbox);
    const wrapper = $117(".setting-list-object-input");
    wrapper.classList.add("setting-list-object-input-key-checkbox");
    checkbox.domNode.classList.add("setting-value-checkbox");
    wrapper.appendChild(checkbox.domNode);
    this.B($_i(wrapper, $7j.MOUSE_DOWN, (e) => {
      checkbox.checked = !checkbox.checked;
      onValueChange(checkbox.checked);
      e.stopImmediatePropagation();
    }));
    return { widget: checkbox, element: wrapper };
  }
  z(rowElementGroup, item) {
    const accessibleDescription = localize(9035, null, item.key.data, item.value.data);
    const title = item.keyDescription ?? accessibleDescription;
    const { rowElement, keyElement, valueElement } = rowElementGroup;
    this.h.add(this.X.setupManagedHover($JZ("mouse"), keyElement, title));
    valueElement.setAttribute("aria-label", accessibleDescription);
    rowElement.setAttribute("aria-label", accessibleDescription);
  }
  C() {
    return {
      deleteActionTooltip: localize(9036, null),
      resetActionTooltip: localize(9037, null),
      editActionTooltip: localize(9038, null),
      addButtonLabel: localize(9039, null),
      keyHeaderText: localize(9040, null),
      valueHeaderText: localize(9041, null)
    };
  }
};
$B1b = __decorate([
  __param(1, $gs),
  __param(2, $40),
  __param(3, $5$)
], $B1b);

// out-build/vs/workbench/contrib/preferences/browser/settingsTree.js
var $G1b_1;
var CopySettingIdAction_1;
var CopySettingAsJSONAction_1;
var CopySettingAsURLAction_1;
var SyncSettingAction_1;
var ApplySettingToAllProfilesAction_1;
var $118 = $;
function getIncludeExcludeDisplayValue(element) {
  const elementDefaultValue = typeof element.defaultValue === "object" ? element.defaultValue ?? {} : {};
  const data = element.isConfigured ? { ...elementDefaultValue, ...element.scopeValue } : elementDefaultValue;
  return Object.keys(data).filter((key2) => !!data[key2]).map((key2) => {
    const defaultValue = elementDefaultValue[key2];
    let source;
    if (defaultValue === data[key2] && element.setting.type === "object" && element.defaultValueSource instanceof Map) {
      const defaultSource = element.defaultValueSource.get(`${element.setting.key}.${key2}`);
      source = typeof defaultSource === "string" ? defaultSource : defaultSource?.displayName;
    }
    const value = data[key2];
    const sibling = typeof value === "boolean" ? void 0 : value.when;
    return {
      value: {
        type: "string",
        data: key2
      },
      sibling,
      elementType: element.valueType,
      source
    };
  });
}
function areAllPropertiesDefined(properties, itemsToDisplay) {
  const staticProperties = new Set(properties);
  itemsToDisplay.forEach(({ key: key2 }) => staticProperties.delete(key2.data));
  return staticProperties.size === 0;
}
function getEnumOptionsFromSchema(schema9) {
  if (schema9.anyOf) {
    return schema9.anyOf.map(getEnumOptionsFromSchema).flat();
  }
  const enumDescriptions = schema9.enumDescriptions ?? [];
  return (schema9.enum ?? []).map((value, idx) => {
    const description = idx < enumDescriptions.length ? enumDescriptions[idx] : void 0;
    return { value, description };
  });
}
function getObjectValueType(schema9) {
  if (schema9.anyOf) {
    const subTypes = schema9.anyOf.map(getObjectValueType);
    if (subTypes.some((type) => type === "enum")) {
      return "enum";
    }
    return "string";
  }
  if (schema9.type === "boolean") {
    return "boolean";
  } else if (schema9.type === "string" && $Hg(schema9.enum) && schema9.enum.length > 0) {
    return "enum";
  } else {
    return "string";
  }
}
function getObjectEntryValueDisplayValue(type, data, options3) {
  if (type === "boolean") {
    return { type, data: !!data };
  } else if (type === "enum") {
    return { type, data: "" + data, options: options3 };
  } else {
    return { type, data: "" + data };
  }
}
function getObjectDisplayValue(element) {
  const elementDefaultValue = typeof element.defaultValue === "object" ? element.defaultValue ?? {} : {};
  const elementScopeValue = typeof element.scopeValue === "object" ? element.scopeValue ?? {} : {};
  const data = element.isConfigured ? { ...elementDefaultValue, ...elementScopeValue } : element.hasPolicyValue ? element.scopeValue : elementDefaultValue;
  const { objectProperties, objectPatternProperties, objectAdditionalProperties } = element.setting;
  const patternsAndSchemas = Object.entries(objectPatternProperties ?? {}).map(([pattern, schema9]) => ({
    pattern: new RegExp(pattern),
    schema: schema9
  }));
  const wellDefinedKeyEnumOptions = Object.entries(objectProperties ?? {}).map(([key2, schema9]) => ({ value: key2, description: schema9.description }));
  return Object.keys(data).map((key2) => {
    const defaultValue = elementDefaultValue[key2];
    let source;
    if (defaultValue === data[key2] && element.setting.type === "object" && element.defaultValueSource instanceof Map) {
      const defaultSource = element.defaultValueSource.get(`${element.setting.key}.${key2}`);
      source = typeof defaultSource === "string" ? defaultSource : defaultSource?.displayName;
    }
    if ($Hg(objectProperties) && key2 in objectProperties) {
      const valueEnumOptions = getEnumOptionsFromSchema(objectProperties[key2]);
      return {
        key: {
          type: "enum",
          data: key2,
          options: wellDefinedKeyEnumOptions
        },
        value: getObjectEntryValueDisplayValue(getObjectValueType(objectProperties[key2]), data[key2], valueEnumOptions),
        keyDescription: objectProperties[key2].description,
        removable: $Ig(defaultValue),
        resetable: !$Ig(defaultValue),
        source
      };
    }
    const removable = defaultValue === void 0 || $q1b(element.setting.key);
    const resetable = !!defaultValue && defaultValue !== data[key2];
    const schema9 = patternsAndSchemas.find(({ pattern }) => pattern.test(key2))?.schema;
    if (schema9) {
      const valueEnumOptions = getEnumOptionsFromSchema(schema9);
      return {
        key: { type: "string", data: key2 },
        value: getObjectEntryValueDisplayValue(getObjectValueType(schema9), data[key2], valueEnumOptions),
        keyDescription: schema9.description,
        removable,
        resetable,
        source
      };
    }
    const additionalValueEnums = getEnumOptionsFromSchema(typeof objectAdditionalProperties === "boolean" ? {} : objectAdditionalProperties ?? {});
    return {
      key: { type: "string", data: key2 },
      value: getObjectEntryValueDisplayValue(typeof objectAdditionalProperties === "object" ? getObjectValueType(objectAdditionalProperties) : "string", data[key2], additionalValueEnums),
      keyDescription: typeof objectAdditionalProperties === "object" ? objectAdditionalProperties.description : void 0,
      removable,
      resetable,
      source
    };
  }).filter((item) => !$Ig(item.value.data));
}
function getBoolObjectDisplayValue(element) {
  const elementDefaultValue = typeof element.defaultValue === "object" ? element.defaultValue ?? {} : {};
  const elementScopeValue = typeof element.scopeValue === "object" ? element.scopeValue ?? {} : {};
  const data = element.isConfigured ? { ...elementDefaultValue, ...elementScopeValue } : elementDefaultValue;
  const { objectProperties } = element.setting;
  const displayValues = [];
  for (const key2 in objectProperties) {
    const defaultValue = elementDefaultValue[key2];
    let source;
    if (defaultValue === data[key2] && element.setting.type === "object" && element.defaultValueSource instanceof Map) {
      const defaultSource = element.defaultValueSource.get(key2);
      source = typeof defaultSource === "string" ? defaultSource : defaultSource?.displayName;
    }
    displayValues.push({
      key: {
        type: "string",
        data: key2
      },
      value: {
        type: "boolean",
        data: !!data[key2]
      },
      keyDescription: objectProperties[key2].description,
      removable: false,
      resetable: true,
      source
    });
  }
  return displayValues;
}
function createArraySuggester(element) {
  return (keys, idx) => {
    const enumOptions = [];
    if (element.setting.enum) {
      element.setting.enum.forEach((key2, i2) => {
        if (!element.setting.uniqueItems || idx !== void 0 && key2 === keys[idx] || !keys.includes(key2)) {
          const description = element.setting.enumDescriptions?.[i2];
          enumOptions.push({ value: key2, description });
        }
      });
    }
    return enumOptions.length > 0 ? { type: "enum", data: enumOptions[0].value, options: enumOptions } : void 0;
  };
}
function createObjectKeySuggester(element) {
  const { objectProperties } = element.setting;
  const allStaticKeys = Object.keys(objectProperties ?? {});
  return (keys) => {
    const existingKeys = new Set(keys);
    const enumOptions = [];
    allStaticKeys.forEach((staticKey) => {
      if (!existingKeys.has(staticKey)) {
        enumOptions.push({ value: staticKey, description: objectProperties[staticKey].description });
      }
    });
    return enumOptions.length > 0 ? { type: "enum", data: enumOptions[0].value, options: enumOptions } : void 0;
  };
}
function createObjectValueSuggester(element) {
  const { objectProperties, objectPatternProperties, objectAdditionalProperties } = element.setting;
  const patternsAndSchemas = Object.entries(objectPatternProperties ?? {}).map(([pattern, schema9]) => ({
    pattern: new RegExp(pattern),
    schema: schema9
  }));
  return (key2) => {
    let suggestedSchema;
    if ($Hg(objectProperties) && key2 in objectProperties) {
      suggestedSchema = objectProperties[key2];
    }
    const patternSchema = suggestedSchema ?? patternsAndSchemas.find(({ pattern }) => pattern.test(key2))?.schema;
    if ($Hg(patternSchema)) {
      suggestedSchema = patternSchema;
    } else if ($Hg(objectAdditionalProperties) && typeof objectAdditionalProperties === "object") {
      suggestedSchema = objectAdditionalProperties;
    }
    if ($Hg(suggestedSchema)) {
      const type = getObjectValueType(suggestedSchema);
      if (type === "boolean") {
        return { type, data: suggestedSchema.default ?? true };
      } else if (type === "enum") {
        const options3 = getEnumOptionsFromSchema(suggestedSchema);
        return { type, data: suggestedSchema.default ?? options3[0].value, options: options3 };
      } else {
        return { type, data: suggestedSchema.default ?? "" };
      }
    }
    return;
  };
}
function isNonNullableNumericType(type) {
  return type === "number" || type === "integer";
}
function parseNumericObjectValues(dataElement, v) {
  const newRecord = {};
  for (const key2 in v) {
    let keyMatchesNumericProperty;
    const patternProperties = dataElement.setting.objectPatternProperties;
    const properties = dataElement.setting.objectProperties;
    const additionalProperties = dataElement.setting.objectAdditionalProperties;
    if (properties) {
      for (const propKey in properties) {
        if (propKey === key2) {
          keyMatchesNumericProperty = isNonNullableNumericType(properties[propKey].type);
          break;
        }
      }
    }
    if (keyMatchesNumericProperty === void 0 && patternProperties) {
      for (const patternKey in patternProperties) {
        if (key2.match(patternKey)) {
          keyMatchesNumericProperty = isNonNullableNumericType(patternProperties[patternKey].type);
          break;
        }
      }
    }
    if (keyMatchesNumericProperty === void 0 && additionalProperties && typeof additionalProperties !== "boolean") {
      if (isNonNullableNumericType(additionalProperties.type)) {
        keyMatchesNumericProperty = true;
      }
    }
    newRecord[key2] = keyMatchesNumericProperty ? Number(v[key2]) : v[key2];
  }
  return newRecord;
}
function getListDisplayValue(element) {
  if (!element.value || !Array.isArray(element.value)) {
    return [];
  }
  if (element.setting.arrayItemType === "enum") {
    let enumOptions = [];
    if (element.setting.enum) {
      enumOptions = element.setting.enum.map((setting, i2) => {
        return {
          value: setting,
          description: element.setting.enumDescriptions?.[i2]
        };
      });
    }
    return element.value.map((key2) => {
      return {
        value: {
          type: "enum",
          data: key2,
          options: enumOptions
        }
      };
    });
  } else {
    return element.value.map((key2) => {
      return {
        value: {
          type: "string",
          data: key2
        }
      };
    });
  }
}
function getShowAddButtonList(dataElement, listDisplayValue) {
  if (dataElement.setting.enum && dataElement.setting.uniqueItems) {
    return dataElement.setting.enum.length - listDisplayValue.length > 0;
  } else {
    return true;
  }
}
function $C1b(tocData, coreSettingsGroups, logService) {
  const allSettings = getFlatSettings(coreSettingsGroups);
  return {
    tree: _resolveSettingsTree(tocData, allSettings, logService),
    leftoverSettings: allSettings
  };
}
function $D1b(groups, target, languageFilter, configurationService) {
  const allSettings = getFlatSettings(groups);
  return [...allSettings].filter((setting) => setting.restricted && $o1b(setting.key, target, languageFilter, configurationService).isConfigured);
}
async function $E1b(extensionService, groups) {
  const extGroupTree = /* @__PURE__ */ new Map();
  const addEntryToTree = (extensionId, extensionName, childEntry) => {
    if (!extGroupTree.has(extensionId)) {
      const rootEntry = {
        id: extensionId,
        label: extensionName,
        children: []
      };
      extGroupTree.set(extensionId, rootEntry);
    }
    extGroupTree.get(extensionId).children.push(childEntry);
  };
  const processGroupEntry = async (group2) => {
    const flatSettings = group2.sections.map((section) => section.settings).flat();
    const extensionId = group2.extensionInfo.id;
    const extension = await extensionService.getExtension(extensionId);
    const extensionName = extension?.displayName ?? extension?.name ?? extensionId;
    const childEntry = {
      id: group2.id || group2.title,
      label: group2.title,
      order: group2.order,
      settings: flatSettings
    };
    addEntryToTree(extensionId, extensionName, childEntry);
  };
  const processPromises = groups.map((g) => processGroupEntry(g));
  return Promise.all(processPromises).then(() => {
    const extGroups = [];
    for (const extensionRootEntry of extGroupTree.values()) {
      for (const child of extensionRootEntry.children) {
        child.settings?.sort((a, b) => {
          return $KZb(a.order, b.order);
        });
      }
      if (extensionRootEntry.children.length === 1) {
        extGroups.push({
          id: extensionRootEntry.id,
          label: extensionRootEntry.children[0].label,
          settings: extensionRootEntry.children[0].settings
        });
      } else {
        extensionRootEntry.children.sort((a, b) => {
          return $KZb(a.order, b.order);
        });
        const ungroupedChild = extensionRootEntry.children.find((child) => child.label === extensionRootEntry.label);
        if (ungroupedChild && !ungroupedChild.children) {
          const groupedChildren = extensionRootEntry.children.filter((child) => child !== ungroupedChild);
          extGroups.push({
            id: extensionRootEntry.id,
            label: extensionRootEntry.label,
            settings: ungroupedChild.settings,
            children: groupedChildren
          });
        } else {
          extGroups.push(extensionRootEntry);
        }
      }
    }
    extGroups.sort((a, b) => a.label.localeCompare(b.label));
    return {
      id: "extensions",
      label: localize(8978, null),
      children: extGroups
    };
  });
}
function _resolveSettingsTree(tocData, allSettings, logService) {
  let children;
  if (tocData.children) {
    children = tocData.children.map((child) => _resolveSettingsTree(child, allSettings, logService)).filter((child) => child.children?.length || child.settings?.length);
  }
  let settings;
  if (tocData.settings) {
    settings = tocData.settings.map((pattern) => getMatchingSettings(allSettings, pattern, logService)).flat();
  }
  if (!children && !settings) {
    throw new Error(`TOC node has no child groups or settings: ${tocData.id}`);
  }
  return {
    id: tocData.id,
    label: tocData.label,
    children,
    settings
  };
}
var knownDynamicSettingGroups = [
  /^settingsSync\..*/,
  /^sync\..*/,
  /^workbench.fontAliasing$/
];
function getMatchingSettings(allSettings, pattern, logService) {
  const result = [];
  allSettings.forEach((s) => {
    if (settingMatches(s, pattern)) {
      result.push(s);
      allSettings.delete(s);
    }
  });
  if (!result.length && !knownDynamicSettingGroups.some((r2) => r2.test(pattern))) {
    logService.warn(`Settings pattern "${pattern}" doesn't match any settings`);
  }
  return result.sort((a, b) => a.key.localeCompare(b.key));
}
var settingPatternCache = /* @__PURE__ */ new Map();
function $F1b(pattern) {
  pattern = $Af(pattern).replace(/\\\*/g, ".*");
  return new RegExp(`^${pattern}$`, "i");
}
function settingMatches(s, pattern) {
  let regExp = settingPatternCache.get(pattern);
  if (!regExp) {
    regExp = $F1b(pattern);
    settingPatternCache.set(pattern, regExp);
  }
  return regExp.test(s.key);
}
function getFlatSettings(settingsGroups) {
  const result = /* @__PURE__ */ new Set();
  for (const group2 of settingsGroups) {
    for (const section of group2.sections) {
      for (const s of section.settings) {
        if (!s.overrides || !s.overrides.length) {
          result.add(s);
        }
      }
    }
  }
  return result;
}
var SETTINGS_TEXT_TEMPLATE_ID = "settings.text.template";
var SETTINGS_MULTILINE_TEXT_TEMPLATE_ID = "settings.multilineText.template";
var SETTINGS_NUMBER_TEMPLATE_ID = "settings.number.template";
var SETTINGS_ENUM_TEMPLATE_ID = "settings.enum.template";
var SETTINGS_BOOL_TEMPLATE_ID = "settings.bool.template";
var SETTINGS_ARRAY_TEMPLATE_ID = "settings.array.template";
var SETTINGS_EXCLUDE_TEMPLATE_ID = "settings.exclude.template";
var SETTINGS_INCLUDE_TEMPLATE_ID = "settings.include.template";
var SETTINGS_OBJECT_TEMPLATE_ID = "settings.object.template";
var SETTINGS_BOOL_OBJECT_TEMPLATE_ID = "settings.boolObject.template";
var SETTINGS_COMPLEX_TEMPLATE_ID = "settings.complex.template";
var SETTINGS_COMPLEX_OBJECT_TEMPLATE_ID = "settings.complexObject.template";
var SETTINGS_NEW_EXTENSIONS_TEMPLATE_ID = "settings.newExtensions.template";
var SETTINGS_ELEMENT_TEMPLATE_ID = "settings.group.template";
var SETTINGS_EXTENSION_TOGGLE_TEMPLATE_ID = "settings.extensionToggle.template";
function removeChildrenFromTabOrder(node) {
  const focusableElements = node.querySelectorAll(`
		[tabindex="0"],
		input:not([tabindex="-1"]),
		select:not([tabindex="-1"]),
		textarea:not([tabindex="-1"]),
		a:not([tabindex="-1"]),
		button:not([tabindex="-1"]),
		area:not([tabindex="-1"])
	`);
  focusableElements.forEach((element) => {
    element.setAttribute($G1b.ELEMENT_FOCUSABLE_ATTR, "true");
    element.setAttribute("tabindex", "-1");
  });
}
function addChildrenToTabOrder(node) {
  const focusableElements = node.querySelectorAll(`[${$G1b.ELEMENT_FOCUSABLE_ATTR}="true"]`);
  focusableElements.forEach((element) => {
    element.removeAttribute($G1b.ELEMENT_FOCUSABLE_ATTR);
    element.setAttribute("tabindex", "0");
  });
}
var $G1b = class $G1b2 extends $3c {
  static {
    $G1b_1 = this;
  }
  static {
    this.CONTROL_CLASS = "setting-control-focus-target";
  }
  static {
    this.CONTROL_SELECTOR = "." + this.CONTROL_CLASS;
  }
  static {
    this.CONTENTS_CLASS = "setting-item-contents";
  }
  static {
    this.CONTENTS_SELECTOR = "." + this.CONTENTS_CLASS;
  }
  static {
    this.ALL_ROWS_SELECTOR = ".monaco-list-row";
  }
  static {
    this.SETTING_KEY_ATTR = "data-key";
  }
  static {
    this.SETTING_ID_ATTR = "data-id";
  }
  static {
    this.ELEMENT_FOCUSABLE_ATTR = "data-focusable";
  }
  constructor(z, C, D, F, G, H, I, J, L, M, N, O, P, Q, R) {
    super();
    this.z = z;
    this.C = C;
    this.D = D;
    this.F = F;
    this.G = G;
    this.H = H;
    this.I = I;
    this.J = J;
    this.L = L;
    this.M = M;
    this.N = N;
    this.O = O;
    this.P = P;
    this.Q = Q;
    this.R = R;
    this.c = this.B(new $ze());
    this.onDidClickOverrideElement = this.c.event;
    this.f = this.B(new $ze());
    this.onDidChangeSetting = this.f.event;
    this.h = this.B(new $ze());
    this.onDidOpenSettings = this.h.event;
    this.j = this.B(new $ze());
    this.onDidClickSettingLink = this.j.event;
    this.m = this.B(new $ze());
    this.onDidFocusSetting = this.m.event;
    this.t = this.B(new $ze());
    this.onDidChangeIgnoredSettings = this.t.event;
    this.u = this.B(new $ze());
    this.onDidChangeSettingHeight = this.u.event;
    this.w = this.B(new $ze());
    this.onApplyFilter = this.w.event;
    this.y = this.B(H.createInstance($Q_, {}));
    this.n = $uWb($LBb(), this.M);
    this.B(this.M.onDidChangeConfiguration((e) => {
      this.n = $uWb($LBb(), this.M);
      this.t.fire();
    }));
  }
  S(tree, _container, typeClass) {
    _container.classList.add("setting-item");
    _container.classList.add("setting-item-" + typeClass);
    const toDispose = new $2c();
    const container2 = $bk(_container, $118($G1b_1.CONTENTS_SELECTOR));
    container2.classList.add("settings-row-inner-container");
    const titleElement = $bk(container2, $118(".setting-item-title"));
    const labelCategoryContainer = $bk(titleElement, $118(".setting-item-cat-label-container"));
    const categoryElement = $bk(labelCategoryContainer, $118("span.setting-item-category"));
    const labelElementContainer = $bk(labelCategoryContainer, $118("span.setting-item-label"));
    const labelElement = toDispose.add(new $U2(labelElementContainer));
    const indicatorsLabel = this.H.createInstance($t1b, titleElement);
    toDispose.add(indicatorsLabel);
    const descriptionElement = $bk(container2, $118(".setting-item-description"));
    const modifiedIndicatorElement = $bk(container2, $118(".setting-item-modified-indicator"));
    toDispose.add(this.R.setupManagedHover($JZ("mouse"), modifiedIndicatorElement, () => localize(8979, null)));
    const valueElement = $bk(container2, $118(".setting-item-value"));
    const controlElement = $bk(valueElement, $118("div.setting-item-control"));
    const deprecationWarningElement = $bk(container2, $118(".setting-item-deprecation-message"));
    const toolbarContainer = $bk(container2, $118(".setting-toolbar-container"));
    const toolbar = this.W(toolbarContainer);
    const template = {
      toDispose,
      elementDisposables: toDispose.add(new $2c()),
      containerElement: container2,
      categoryElement,
      labelElement,
      descriptionElement,
      controlElement,
      deprecationWarningElement,
      indicatorsLabel,
      toolbar
    };
    toDispose.add($_i(controlElement, $7j.MOUSE_DOWN, (e) => e.stopPropagation()));
    toDispose.add($_i(titleElement, $7j.MOUSE_ENTER, (e) => container2.classList.add("mouseover")));
    toDispose.add($_i(titleElement, $7j.MOUSE_LEAVE, (e) => container2.classList.remove("mouseover")));
    return template;
  }
  U(template) {
    const focusTracker = $_j(template.containerElement);
    template.toDispose.add(focusTracker);
    focusTracker.onDidBlur(() => {
      if (template.containerElement.classList.contains("focused")) {
        template.containerElement.classList.remove("focused");
      }
    });
    focusTracker.onDidFocus(() => {
      template.containerElement.classList.add("focused");
      if (template.context) {
        this.m.fire(template.context);
      }
    });
  }
  W(container2) {
    const toggleMenuKeybinding = this.L.lookupKeybinding($4Yb);
    let toggleMenuTitle = localize(8980, null);
    if (toggleMenuKeybinding) {
      toggleMenuTitle += ` (${toggleMenuKeybinding && toggleMenuKeybinding.getLabel()})`;
    }
    const toolbar = new $f3(container2, this.J, {
      toggleMenuTitle,
      renderDropdownAsChildElement: !$u,
      moreIcon: $JYb
    });
    return toolbar;
  }
  X(node, index, template) {
    const element = node.element;
    element.inspectSelf();
    template.context = element;
    template.toolbar.context = element;
    const actions = this.C(element.setting, element.settingsTarget);
    actions.forEach((a) => $Wc(a) && template.elementDisposables.add(a));
    template.toolbar.setActions([], [...this.z, ...actions]);
    const setting = element.setting;
    template.containerElement.classList.toggle("is-configured", element.isConfigured);
    template.containerElement.setAttribute($G1b_1.SETTING_KEY_ATTR, element.setting.key);
    template.containerElement.setAttribute($G1b_1.SETTING_ID_ATTR, element.id);
    const titleTooltip = setting.key + (element.isConfigured ? " - Modified" : "");
    template.categoryElement.textContent = element.displayCategory ? element.displayCategory + ": " : "";
    template.elementDisposables.add(this.R.setupManagedHover($JZ("mouse"), template.categoryElement, titleTooltip));
    template.labelElement.text = element.displayLabel;
    template.labelElement.title = titleTooltip;
    template.descriptionElement.innerText = "";
    if (element.setting.descriptionIsMarkdown) {
      const renderedDescription = this.Z(element, template.containerElement, element.description, template.elementDisposables);
      template.descriptionElement.appendChild(renderedDescription);
    } else {
      template.descriptionElement.innerText = element.description;
    }
    template.indicatorsLabel.updateScopeOverrides(element, this.c, this.w);
    template.elementDisposables.add(this.M.onDidChangeConfiguration((e) => {
      if (e.affectsConfiguration($GK)) {
        template.indicatorsLabel.updateScopeOverrides(element, this.c, this.w);
      }
    }));
    const onChange = (value) => this.f.fire({
      key: element.setting.key,
      value,
      type: template.context.valueType,
      manualReset: false,
      scope: element.setting.scope
    });
    const deprecationText = element.setting.deprecationMessage || "";
    if (deprecationText && element.setting.deprecationMessageIsMarkdown) {
      template.deprecationWarningElement.innerText = "";
      template.deprecationWarningElement.appendChild(this.Z(element, template.containerElement, element.setting.deprecationMessage, template.elementDisposables));
    } else {
      template.deprecationWarningElement.innerText = deprecationText;
    }
    template.deprecationWarningElement.prepend($118(".codicon.codicon-error"));
    template.containerElement.classList.toggle("is-deprecated", !!deprecationText);
    this.ab(element, template, onChange);
    template.indicatorsLabel.updateWorkspaceTrust(element);
    template.indicatorsLabel.updateSyncIgnored(element, this.n);
    template.indicatorsLabel.updateDefaultOverrideIndicator(element);
    template.indicatorsLabel.updatePreviewIndicator(element);
    template.elementDisposables.add(this.onDidChangeIgnoredSettings(() => {
      template.indicatorsLabel.updateSyncIgnored(element, this.n);
    }));
    this.Y(element, template);
    template.elementDisposables.add(element.onDidChangeTabbable(() => {
      this.Y(element, template);
    }));
  }
  Y(element, template) {
    if (element.tabbable) {
      addChildrenToTabOrder(template.containerElement);
    } else {
      removeChildrenFromTabOrder(template.containerElement);
    }
  }
  Z(element, container2, text2, disposables) {
    text2 = fixSettingLinks(text2);
    const renderedMarkdown = this.y.render({ value: text2, isTrusted: true }, {
      actionHandler: {
        callback: (content) => {
          if (content.startsWith("#")) {
            const e = {
              source: element,
              targetKey: content.substring(1)
            };
            this.j.fire(e);
          } else {
            this.G.open(content, { allowCommands: true }).catch($gb);
          }
        },
        disposables
      },
      asyncRenderCallback: () => {
        const height = container2.clientHeight;
        if (height) {
          this.u.fire({ element, height });
        }
      }
    });
    disposables.add(renderedMarkdown);
    renderedMarkdown.element.classList.add("setting-item-markdown");
    cleanRenderedMarkdown(renderedMarkdown.element);
    return renderedMarkdown.element;
  }
  disposeTemplate(template) {
    template.toDispose.dispose();
  }
  disposeElement(_element, _index, template, _height) {
    template.elementDisposables?.clear();
  }
};
$G1b = $G1b_1 = __decorate([
  __param(2, $gs),
  __param(3, $40),
  __param(4, $O4),
  __param(5, $Pk),
  __param(6, $sn),
  __param(7, $50),
  __param(8, $Ty),
  __param(9, $kl),
  __param(10, $wN),
  __param(11, $vzb),
  __param(12, $Vu),
  __param(13, $zv),
  __param(14, $5$)
], $G1b);
var SettingGroupRenderer = class {
  constructor() {
    this.templateId = SETTINGS_ELEMENT_TEMPLATE_ID;
  }
  renderTemplate(container2) {
    container2.classList.add("group-title");
    const template = {
      parent: container2,
      toDispose: new $2c()
    };
    return template;
  }
  renderElement(element, index, templateData) {
    templateData.parent.innerText = "";
    const labelElement = $bk(templateData.parent, $118("div.settings-group-title-label.settings-row-inner-container"));
    labelElement.classList.add(`settings-group-level-${element.element.level}`);
    labelElement.textContent = element.element.label;
    if (element.element.isFirstGroup) {
      labelElement.classList.add("settings-group-first");
    }
  }
  disposeTemplate(templateData) {
  }
};
var $H1b = class $H1b2 {
  constructor(c) {
    this.c = c;
    this.templateId = SETTINGS_NEW_EXTENSIONS_TEMPLATE_ID;
  }
  renderTemplate(container2) {
    const toDispose = new $2c();
    container2.classList.add("setting-item-new-extensions");
    const button = new $k2(container2, { title: true, ...$q$ });
    toDispose.add(button);
    toDispose.add(button.onDidClick(() => {
      if (template.context) {
        this.c.executeCommand("workbench.extensions.action.showExtensionsWithIds", template.context.extensionIds);
      }
    }));
    button.label = localize(8981, null);
    button.element.classList.add("settings-new-extensions-button");
    const template = {
      button,
      toDispose
    };
    return template;
  }
  renderElement(element, index, templateData) {
    templateData.context = element.element;
  }
  disposeTemplate(template) {
    $Xc(template.toDispose);
  }
};
$H1b = __decorate([
  __param(0, $sn)
], $H1b);
var $I1b = class _$I1b extends $G1b {
  constructor() {
    super(...arguments);
    this.templateId = SETTINGS_COMPLEX_TEMPLATE_ID;
  }
  static {
    this.bb = localize(8982, null);
  }
  renderTemplate(container2) {
    const common = this.S(null, container2, "complex");
    const openSettingsButton = $bk(common.controlElement, $118("a.edit-in-settings-button"));
    openSettingsButton.classList.add($G1b.CONTROL_CLASS);
    openSettingsButton.role = "button";
    const validationErrorMessageElement = $118(".setting-item-validation-message");
    common.containerElement.appendChild(validationErrorMessageElement);
    const template = {
      ...common,
      button: openSettingsButton,
      validationErrorMessageElement
    };
    this.U(template);
    return template;
  }
  renderElement(element, index, templateData) {
    super.X(element, index, templateData);
  }
  ab(dataElement, template, onChange) {
    const plainKey = $ul(dataElement.setting.key);
    const editLanguageSettingLabel = localize(8983, null, plainKey);
    const isLanguageTagSetting = dataElement.setting.isLanguageTagSetting;
    template.button.textContent = isLanguageTagSetting ? editLanguageSettingLabel : _$I1b.bb;
    const onClickOrKeydown = (e) => {
      if (isLanguageTagSetting) {
        this.w.fire(`@${$AZb}${plainKey}`);
      } else {
        this.h.fire(dataElement.setting.key);
      }
      e.preventDefault();
      e.stopPropagation();
    };
    template.elementDisposables.add($_i(template.button, $7j.CLICK, (e) => {
      onClickOrKeydown(e);
    }));
    template.elementDisposables.add($_i(template.button, $7j.KEY_DOWN, (e) => {
      const ev = new $if(e);
      if (ev.equals(
        10
        /* KeyCode.Space */
      ) || ev.equals(
        3
        /* KeyCode.Enter */
      )) {
        onClickOrKeydown(e);
      }
    }));
    this.db(dataElement, template);
    if (isLanguageTagSetting) {
      template.button.setAttribute("aria-label", editLanguageSettingLabel);
    } else {
      template.button.setAttribute("aria-label", `${_$I1b.bb}: ${dataElement.setting.key}`);
    }
  }
  db(dataElement, template) {
    const errMsg = dataElement.isConfigured && $IK(dataElement.value, dataElement.setting.type);
    if (errMsg) {
      template.containerElement.classList.add("invalid-input");
      template.validationErrorMessageElement.innerText = errMsg;
      return;
    }
    template.containerElement.classList.remove("invalid-input");
  }
};
var SettingComplexObjectRenderer = class extends $I1b {
  constructor() {
    super(...arguments);
    this.templateId = SETTINGS_COMPLEX_OBJECT_TEMPLATE_ID;
  }
  renderTemplate(container2) {
    const common = this.S(null, container2, "list");
    const objectSettingWidget = common.toDispose.add(this.H.createInstance($A1b, common.controlElement));
    objectSettingWidget.domNode.classList.add($G1b.CONTROL_CLASS);
    const openSettingsButton = $bk($bk(common.controlElement, $118(".complex-object-edit-in-settings-button-container")), $118("a.complex-object.edit-in-settings-button"));
    openSettingsButton.classList.add($G1b.CONTROL_CLASS);
    openSettingsButton.role = "button";
    const validationErrorMessageElement = $118(".setting-item-validation-message");
    common.containerElement.appendChild(validationErrorMessageElement);
    const template = {
      ...common,
      button: openSettingsButton,
      validationErrorMessageElement,
      objectSettingWidget
    };
    this.U(template);
    return template;
  }
  ab(dataElement, template, onChange) {
    const items = getObjectDisplayValue(dataElement);
    template.objectSettingWidget.setValue(items, {
      settingKey: dataElement.setting.key,
      showAddButton: false,
      isReadOnly: true
    });
    template.button.parentElement?.classList.toggle("hide", dataElement.hasPolicyValue);
    super.ab(dataElement, template, onChange);
  }
};
var SettingArrayRenderer = class extends $G1b {
  constructor() {
    super(...arguments);
    this.templateId = SETTINGS_ARRAY_TEMPLATE_ID;
  }
  renderTemplate(container2) {
    const common = this.S(null, container2, "list");
    const descriptionElement = common.containerElement.querySelector(".setting-item-description");
    const validationErrorMessageElement = $118(".setting-item-validation-message");
    descriptionElement.after(validationErrorMessageElement);
    const listWidget = this.H.createInstance($x1b, common.controlElement);
    listWidget.domNode.classList.add($G1b.CONTROL_CLASS);
    common.toDispose.add(listWidget);
    const template = {
      ...common,
      listWidget,
      validationErrorMessageElement
    };
    this.U(template);
    common.toDispose.add(listWidget.onDidChangeList((e) => {
      const newList = this.bb(template, e);
      template.onChange?.(newList);
    }));
    return template;
  }
  bb(template, e) {
    if (template.context) {
      let newValue = [];
      if (Array.isArray(template.context.scopeValue)) {
        newValue = [...template.context.scopeValue];
      } else if (Array.isArray(template.context.value)) {
        newValue = [...template.context.value];
      }
      if (e.type === "move") {
        const sourceIndex = e.sourceIndex;
        const targetIndex = e.targetIndex;
        const splicedElem = newValue.splice(sourceIndex, 1)[0];
        newValue.splice(targetIndex, 0, splicedElem);
      } else if (e.type === "remove" || e.type === "reset") {
        newValue.splice(e.targetIndex, 1);
      } else if (e.type === "change") {
        const itemValueData = e.newItem.value.data.toString();
        if (e.targetIndex > -1) {
          newValue[e.targetIndex] = itemValueData;
        } else {
          newValue.push(itemValueData);
        }
      } else if (e.type === "add") {
        newValue.push(e.newItem.value.data.toString());
      }
      if (template.context.defaultValue && Array.isArray(template.context.defaultValue) && template.context.defaultValue.length === newValue.length && template.context.defaultValue.join() === newValue.join()) {
        return void 0;
      }
      return newValue;
    }
    return void 0;
  }
  renderElement(element, index, templateData) {
    super.X(element, index, templateData);
  }
  ab(dataElement, template, onChange) {
    const value = getListDisplayValue(dataElement);
    const keySuggester = dataElement.setting.enum ? createArraySuggester(dataElement) : void 0;
    template.listWidget.setValue(value, {
      showAddButton: getShowAddButtonList(dataElement, value),
      keySuggester
    });
    template.context = dataElement;
    template.elementDisposables.add($1c(() => {
      template.listWidget.cancelEdit();
    }));
    template.onChange = (v) => {
      if (v && !renderArrayValidations(dataElement, template, v, false)) {
        const itemType = dataElement.setting.arrayItemType;
        const arrToSave = isNonNullableNumericType(itemType) ? v.map((a) => +a) : v;
        onChange(arrToSave);
      } else {
        onChange(v);
      }
    };
    renderArrayValidations(dataElement, template, value.map((v) => v.value.data.toString()), true);
  }
};
var AbstractSettingObjectRenderer = class extends $G1b {
  bb(common, widget) {
    widget.domNode.classList.add($G1b.CONTROL_CLASS);
    common.toDispose.add(widget);
    const descriptionElement = common.containerElement.querySelector(".setting-item-description");
    const validationErrorMessageElement = $118(".setting-item-validation-message");
    descriptionElement.after(validationErrorMessageElement);
    const template = {
      ...common,
      validationErrorMessageElement
    };
    if (widget instanceof $B1b) {
      template.objectCheckboxWidget = widget;
    } else {
      template.objectDropdownWidget = widget;
    }
    this.U(template);
    return template;
  }
  renderElement(element, index, templateData) {
    super.X(element, index, templateData);
  }
};
var SettingObjectRenderer = class extends AbstractSettingObjectRenderer {
  constructor() {
    super(...arguments);
    this.templateId = SETTINGS_OBJECT_TEMPLATE_ID;
  }
  renderTemplate(container2) {
    const common = this.S(null, container2, "list");
    const widget = this.H.createInstance($A1b, common.controlElement);
    const template = this.bb(common, widget);
    common.toDispose.add(widget.onDidChangeList((e) => {
      this.cb(template, e);
    }));
    return template;
  }
  cb(template, e) {
    const widget = template.objectDropdownWidget;
    if (template.context) {
      const settingSupportsRemoveDefault = $q1b(template.context.setting.key);
      const defaultValue = typeof template.context.defaultValue === "object" ? template.context.defaultValue ?? {} : {};
      const scopeValue = typeof template.context.scopeValue === "object" ? template.context.scopeValue ?? {} : {};
      const newValue = { ...template.context.scopeValue };
      const newItems = [];
      widget.items.forEach((item, idx) => {
        if ((e.type === "change" || e.type === "move") && e.targetIndex === idx) {
          if (e.originalItem.key.data !== e.newItem.key.data && settingSupportsRemoveDefault && e.originalItem.key.data in defaultValue) {
            newValue[e.originalItem.key.data] = null;
          } else {
            delete newValue[e.originalItem.key.data];
          }
          newValue[e.newItem.key.data] = e.newItem.value.data;
          newItems.push(e.newItem);
        } else if (e.type !== "change" && e.type !== "move" || e.newItem.key.data !== item.key.data) {
          newValue[item.key.data] = item.value.data;
          newItems.push(item);
        }
      });
      if (e.type === "remove" || e.type === "reset") {
        const objectKey = e.originalItem.key.data;
        const removingDefaultValue = e.type === "remove" && settingSupportsRemoveDefault && defaultValue[objectKey] === e.originalItem.value.data;
        if (removingDefaultValue) {
          newValue[objectKey] = null;
        } else {
          delete newValue[objectKey];
        }
        const itemToDelete = newItems.findIndex((item) => item.key.data === objectKey);
        const defaultItemValue = defaultValue[objectKey];
        if (removingDefaultValue || $Ig(defaultValue[objectKey]) && itemToDelete > -1) {
          newItems.splice(itemToDelete, 1);
        } else if (!removingDefaultValue && itemToDelete > -1) {
          newItems[itemToDelete].value.data = defaultItemValue;
        }
      } else if (e.type === "add") {
        newValue[e.newItem.key.data] = e.newItem.value.data;
        newItems.push(e.newItem);
      }
      Object.entries(newValue).forEach(([key2, value]) => {
        if (scopeValue[key2] !== value && defaultValue[key2] === value && !(settingSupportsRemoveDefault && value === null)) {
          delete newValue[key2];
        }
      });
      const newObject = Object.keys(newValue).length === 0 ? void 0 : newValue;
      template.objectDropdownWidget.setValue(newItems);
      template.onChange?.(newObject);
    }
  }
  ab(dataElement, template, onChange) {
    const items = getObjectDisplayValue(dataElement);
    const { key: key2, objectProperties, objectPatternProperties, objectAdditionalProperties } = dataElement.setting;
    template.objectDropdownWidget.setValue(items, {
      settingKey: key2,
      showAddButton: objectAdditionalProperties === false ? !areAllPropertiesDefined(Object.keys(objectProperties ?? {}), items) || $Hg(objectPatternProperties) : true,
      keySuggester: createObjectKeySuggester(dataElement),
      valueSuggester: createObjectValueSuggester(dataElement)
    });
    template.context = dataElement;
    template.elementDisposables.add($1c(() => {
      template.objectDropdownWidget.cancelEdit();
    }));
    template.onChange = (v) => {
      if (v && !renderArrayValidations(dataElement, template, v, false)) {
        const parsedRecord = parseNumericObjectValues(dataElement, v);
        onChange(parsedRecord);
      } else {
        onChange(v);
      }
    };
    renderArrayValidations(dataElement, template, dataElement.value, true);
  }
};
var SettingBoolObjectRenderer = class extends AbstractSettingObjectRenderer {
  constructor() {
    super(...arguments);
    this.templateId = SETTINGS_BOOL_OBJECT_TEMPLATE_ID;
  }
  renderTemplate(container2) {
    const common = this.S(null, container2, "list");
    const widget = this.H.createInstance($B1b, common.controlElement);
    const template = this.bb(common, widget);
    common.toDispose.add(widget.onDidChangeList((e) => {
      this.cb(template, e);
    }));
    return template;
  }
  cb(template, e) {
    if (template.context) {
      const widget = template.objectCheckboxWidget;
      const defaultValue = typeof template.context.defaultValue === "object" ? template.context.defaultValue ?? {} : {};
      const scopeValue = typeof template.context.scopeValue === "object" ? template.context.scopeValue ?? {} : {};
      const newValue = { ...template.context.scopeValue };
      const newItems = [];
      if (e.type !== "change") {
        console.warn("Unexpected event type", e.type, "for bool object setting", template.context.setting.key);
        return;
      }
      widget.items.forEach((item, idx) => {
        if (e.targetIndex === idx) {
          newValue[e.newItem.key.data] = e.newItem.value.data;
          newItems.push(e.newItem);
        } else if (e.newItem.key.data !== item.key.data) {
          newValue[item.key.data] = item.value.data;
          newItems.push(item);
        }
      });
      Object.entries(newValue).forEach(([key2, value]) => {
        if (scopeValue[key2] !== value && defaultValue[key2] === value) {
          delete newValue[key2];
        }
      });
      const newObject = Object.keys(newValue).length === 0 ? void 0 : newValue;
      template.objectCheckboxWidget.setValue(newItems);
      template.onChange?.(newObject);
      this.m.fire(template.context);
    }
  }
  ab(dataElement, template, onChange) {
    const items = getBoolObjectDisplayValue(dataElement);
    const { key: key2 } = dataElement.setting;
    template.objectCheckboxWidget.setValue(items, {
      settingKey: key2
    });
    template.context = dataElement;
    template.onChange = (v) => {
      onChange(v);
    };
  }
};
var SettingIncludeExcludeRenderer = class extends $G1b {
  renderTemplate(container2) {
    const common = this.S(null, container2, "list");
    const includeExcludeWidget = this.H.createInstance(this.bb() ? $y1b : $z1b, common.controlElement);
    includeExcludeWidget.domNode.classList.add($G1b.CONTROL_CLASS);
    common.toDispose.add(includeExcludeWidget);
    const template = {
      ...common,
      includeExcludeWidget
    };
    this.U(template);
    common.toDispose.add(includeExcludeWidget.onDidChangeList((e) => this.cb(template, e)));
    return template;
  }
  cb(template, e) {
    if (template.context) {
      let sortKeys2 = function(obj) {
        const sortedKeys = Object.keys(obj).sort((a, b) => a.localeCompare(b));
        const retVal = {};
        for (const key2 of sortedKeys) {
          retVal[key2] = obj[key2];
        }
        return retVal;
      };
      var sortKeys = sortKeys2;
      const newValue = { ...template.context.scopeValue };
      if (e.type !== "add") {
        if (e.originalItem.value.data.toString() in template.context.defaultValue) {
          newValue[e.originalItem.value.data.toString()] = false;
        } else {
          delete newValue[e.originalItem.value.data.toString()];
        }
      }
      if (e.type === "change" || e.type === "add" || e.type === "move") {
        if (e.newItem.value.data.toString() in template.context.defaultValue && !e.newItem.sibling) {
          delete newValue[e.newItem.value.data.toString()];
        } else {
          newValue[e.newItem.value.data.toString()] = e.newItem.sibling ? { when: e.newItem.sibling } : true;
        }
      }
      this.f.fire({
        key: template.context.setting.key,
        value: Object.keys(newValue).length === 0 ? void 0 : sortKeys2(newValue),
        type: template.context.valueType,
        manualReset: false,
        scope: template.context.setting.scope
      });
    }
  }
  renderElement(element, index, templateData) {
    super.X(element, index, templateData);
  }
  ab(dataElement, template, onChange) {
    const value = getIncludeExcludeDisplayValue(dataElement);
    template.includeExcludeWidget.setValue(value);
    template.context = dataElement;
    template.elementDisposables.add($1c(() => {
      template.includeExcludeWidget.cancelEdit();
    }));
  }
};
var SettingExcludeRenderer = class extends SettingIncludeExcludeRenderer {
  constructor() {
    super(...arguments);
    this.templateId = SETTINGS_EXCLUDE_TEMPLATE_ID;
  }
  bb() {
    return true;
  }
};
var SettingIncludeRenderer = class extends SettingIncludeExcludeRenderer {
  constructor() {
    super(...arguments);
    this.templateId = SETTINGS_INCLUDE_TEMPLATE_ID;
  }
  bb() {
    return false;
  }
};
var settingsInputBoxStyles = $C$({
  inputBackground: $3Zb,
  inputForeground: $4Zb,
  inputBorder: $5Zb
});
var AbstractSettingTextRenderer = class extends $G1b {
  constructor() {
    super(...arguments);
    this.bb = 150;
  }
  renderTemplate(_container, useMultiline) {
    const common = this.S(null, _container, "text");
    const validationErrorMessageElement = $bk(common.containerElement, $118(".setting-item-validation-message"));
    const inputBoxOptions = {
      flexibleHeight: useMultiline,
      flexibleWidth: false,
      flexibleMaxHeight: this.bb,
      inputBoxStyles: settingsInputBoxStyles
    };
    const inputBox = new $I2(common.controlElement, this.F, inputBoxOptions);
    common.toDispose.add(inputBox);
    common.toDispose.add(inputBox.onDidChange((e) => {
      template.onChange?.(e);
    }));
    common.toDispose.add(inputBox);
    inputBox.inputElement.classList.add($G1b.CONTROL_CLASS);
    inputBox.inputElement.tabIndex = 0;
    const template = {
      ...common,
      inputBox,
      validationErrorMessageElement
    };
    this.U(template);
    return template;
  }
  renderElement(element, index, templateData) {
    super.X(element, index, templateData);
  }
  ab(dataElement, template, onChange) {
    template.onChange = void 0;
    template.inputBox.value = dataElement.value;
    template.inputBox.setAriaLabel(dataElement.setting.key);
    template.onChange = (value) => {
      if (!renderValidations(dataElement, template, false)) {
        onChange(value);
      }
    };
    renderValidations(dataElement, template, true);
  }
};
var SettingTextRenderer = class extends AbstractSettingTextRenderer {
  constructor() {
    super(...arguments);
    this.templateId = SETTINGS_TEXT_TEMPLATE_ID;
  }
  renderTemplate(_container) {
    const template = super.renderTemplate(_container, false);
    template.toDispose.add($aj(template.inputBox.inputElement, $7j.KEY_DOWN, (e) => {
      if (e.equals(
        16
        /* KeyCode.UpArrow */
      ) || e.equals(
        18
        /* KeyCode.DownArrow */
      )) {
        e.preventDefault();
      }
    }));
    return template;
  }
};
var SettingMultilineTextRenderer = class extends AbstractSettingTextRenderer {
  constructor() {
    super(...arguments);
    this.templateId = SETTINGS_MULTILINE_TEXT_TEMPLATE_ID;
  }
  renderTemplate(_container) {
    return super.renderTemplate(_container, true);
  }
  ab(dataElement, template, onChange) {
    const onChangeOverride = (value) => {
      dataElement.value = value;
      onChange(value);
    };
    super.ab(dataElement, template, onChangeOverride);
    template.elementDisposables.add(template.inputBox.onDidHeightChange((e) => {
      const height = template.containerElement.clientHeight;
      if (height) {
        this.u.fire({
          element: dataElement,
          height: template.containerElement.clientHeight
        });
      }
    }));
    template.inputBox.layout();
  }
};
var SettingEnumRenderer = class extends $G1b {
  constructor() {
    super(...arguments);
    this.templateId = SETTINGS_ENUM_TEMPLATE_ID;
  }
  renderTemplate(container2) {
    const common = this.S(null, container2, "enum");
    const styles = $L$({
      selectBackground: $VZb,
      selectForeground: $WZb,
      selectBorder: $XZb,
      selectListBorder: $YZb
    });
    const selectBox = new $N1([], 0, this.F, styles, {
      useCustomDrawn: !($u && $5e.pointerEvents)
    });
    common.toDispose.add(selectBox);
    selectBox.render(common.controlElement);
    const selectElement2 = common.controlElement.querySelector("select");
    if (selectElement2) {
      selectElement2.classList.add($G1b.CONTROL_CLASS);
      selectElement2.tabIndex = 0;
    }
    common.toDispose.add(selectBox.onDidSelect((e) => {
      template.onChange?.(e.index);
    }));
    const enumDescriptionElement = common.containerElement.insertBefore($118(".setting-item-enumDescription"), common.descriptionElement.nextSibling);
    const template = {
      ...common,
      selectBox,
      selectElement: selectElement2,
      enumDescriptionElement
    };
    this.U(template);
    return template;
  }
  renderElement(element, index, templateData) {
    super.X(element, index, templateData);
  }
  ab(dataElement, template, onChange) {
    const enumItemLabels = dataElement.setting.enumItemLabels ? [...dataElement.setting.enumItemLabels] : [];
    const enumDescriptions = dataElement.setting.enumDescriptions ? [...dataElement.setting.enumDescriptions] : [];
    const settingEnum = [...dataElement.setting.enum];
    const enumDescriptionsAreMarkdown = dataElement.setting.enumDescriptionsAreMarkdown;
    const disposables = new $2c();
    template.elementDisposables.add(disposables);
    let createdDefault = false;
    if (!settingEnum.includes(dataElement.defaultValue)) {
      settingEnum.unshift(dataElement.defaultValue);
      enumDescriptions.unshift("");
      enumItemLabels.unshift("");
      createdDefault = true;
    }
    const stringifiedDefaultValue = escapeInvisibleChars2(String(dataElement.defaultValue));
    const displayOptions = settingEnum.map(String).map(escapeInvisibleChars2).map((data, index) => {
      const description = enumDescriptions[index] && (enumDescriptionsAreMarkdown ? fixSettingLinks(enumDescriptions[index], false) : enumDescriptions[index]);
      return {
        text: enumItemLabels[index] ? enumItemLabels[index] : data,
        detail: enumItemLabels[index] ? data : "",
        description,
        descriptionIsMarkdown: enumDescriptionsAreMarkdown,
        descriptionMarkdownActionHandler: {
          callback: (content) => {
            this.G.open(content).catch($gb);
          },
          disposables
        },
        decoratorRight: data === stringifiedDefaultValue || createdDefault && index === 0 ? localize(8984, null) : ""
      };
    });
    template.selectBox.setOptions(displayOptions);
    template.selectBox.setAriaLabel(dataElement.setting.key);
    let idx = settingEnum.indexOf(dataElement.value);
    if (idx === -1) {
      idx = 0;
    }
    template.onChange = void 0;
    template.selectBox.select(idx);
    template.onChange = (idx2) => {
      if (createdDefault && idx2 === 0) {
        onChange(dataElement.defaultValue);
      } else {
        onChange(settingEnum[idx2]);
      }
    };
    template.enumDescriptionElement.innerText = "";
  }
};
var settingsNumberInputBoxStyles = $C$({
  inputBackground: $6Zb,
  inputForeground: $7Zb,
  inputBorder: $8Zb
});
var SettingNumberRenderer = class extends $G1b {
  constructor() {
    super(...arguments);
    this.templateId = SETTINGS_NUMBER_TEMPLATE_ID;
  }
  renderTemplate(_container) {
    const common = super.S(null, _container, "number");
    const validationErrorMessageElement = $bk(common.containerElement, $118(".setting-item-validation-message"));
    const inputBox = new $I2(common.controlElement, this.F, { type: "number", inputBoxStyles: settingsNumberInputBoxStyles });
    common.toDispose.add(inputBox);
    common.toDispose.add(inputBox.onDidChange((e) => {
      template.onChange?.(e);
    }));
    common.toDispose.add(inputBox);
    inputBox.inputElement.classList.add($G1b.CONTROL_CLASS);
    inputBox.inputElement.tabIndex = 0;
    const template = {
      ...common,
      inputBox,
      validationErrorMessageElement
    };
    this.U(template);
    return template;
  }
  renderElement(element, index, templateData) {
    super.X(element, index, templateData);
  }
  ab(dataElement, template, onChange) {
    const numParseFn = dataElement.valueType === "integer" || dataElement.valueType === "nullable-integer" ? parseInt : parseFloat;
    const nullNumParseFn = dataElement.valueType === "nullable-integer" || dataElement.valueType === "nullable-number" ? (v) => v === "" ? null : numParseFn(v) : numParseFn;
    template.onChange = void 0;
    template.inputBox.value = typeof dataElement.value === "number" ? dataElement.value.toString() : "";
    template.inputBox.step = dataElement.valueType.includes("integer") ? "1" : "any";
    template.inputBox.setAriaLabel(dataElement.setting.key);
    template.onChange = (value) => {
      if (!renderValidations(dataElement, template, false)) {
        onChange(nullNumParseFn(value));
      }
    };
    renderValidations(dataElement, template, true);
  }
};
var SettingBoolRenderer = class extends $G1b {
  constructor() {
    super(...arguments);
    this.templateId = SETTINGS_BOOL_TEMPLATE_ID;
  }
  renderTemplate(_container) {
    _container.classList.add("setting-item");
    _container.classList.add("setting-item-bool");
    const toDispose = new $2c();
    const container2 = $bk(_container, $118($G1b.CONTENTS_SELECTOR));
    container2.classList.add("settings-row-inner-container");
    const titleElement = $bk(container2, $118(".setting-item-title"));
    const categoryElement = $bk(titleElement, $118("span.setting-item-category"));
    const labelElementContainer = $bk(titleElement, $118("span.setting-item-label"));
    const labelElement = toDispose.add(new $U2(labelElementContainer));
    const indicatorsLabel = this.H.createInstance($t1b, titleElement);
    const descriptionAndValueElement = $bk(container2, $118(".setting-item-value-description"));
    const controlElement = $bk(descriptionAndValueElement, $118(".setting-item-bool-control"));
    const descriptionElement = $bk(descriptionAndValueElement, $118(".setting-item-description"));
    const modifiedIndicatorElement = $bk(container2, $118(".setting-item-modified-indicator"));
    toDispose.add(this.R.setupManagedHover($JZ("mouse"), modifiedIndicatorElement, localize(8985, null)));
    const deprecationWarningElement = $bk(container2, $118(".setting-item-deprecation-message"));
    const checkbox = new $Q1({ icon: $6l.check, actionClassName: "setting-value-checkbox", isChecked: true, title: "", ...$O1 });
    controlElement.appendChild(checkbox.domNode);
    toDispose.add(checkbox);
    toDispose.add(checkbox.onChange(() => {
      template.onChange(checkbox.checked);
    }));
    toDispose.add($_i(descriptionElement, $7j.MOUSE_DOWN, (e) => {
      const targetElement = e.target;
      if (targetElement.tagName.toLowerCase() !== "a") {
        template.checkbox.checked = !template.checkbox.checked;
        template.onChange(checkbox.checked);
      }
      $9j.stop(e);
    }));
    checkbox.domNode.classList.add($G1b.CONTROL_CLASS);
    const toolbarContainer = $bk(container2, $118(".setting-toolbar-container"));
    const toolbar = this.W(toolbarContainer);
    toDispose.add(toolbar);
    const template = {
      toDispose,
      elementDisposables: toDispose.add(new $2c()),
      containerElement: container2,
      categoryElement,
      labelElement,
      controlElement,
      checkbox,
      descriptionElement,
      deprecationWarningElement,
      indicatorsLabel,
      toolbar
    };
    this.U(template);
    toDispose.add($_i(controlElement, "mousedown", (e) => e.stopPropagation()));
    toDispose.add($_i(titleElement, $7j.MOUSE_ENTER, (e) => container2.classList.add("mouseover")));
    toDispose.add($_i(titleElement, $7j.MOUSE_LEAVE, (e) => container2.classList.remove("mouseover")));
    return template;
  }
  renderElement(element, index, templateData) {
    super.X(element, index, templateData);
  }
  ab(dataElement, template, onChange) {
    template.onChange = void 0;
    template.checkbox.checked = dataElement.value;
    template.checkbox.setTitle(dataElement.setting.key);
    template.onChange = onChange;
  }
};
var SettingsExtensionToggleRenderer = class extends $G1b {
  constructor() {
    super(...arguments);
    this.templateId = SETTINGS_EXTENSION_TOGGLE_TEMPLATE_ID;
    this.bb = this.B(new $ze());
    this.onDidDismissExtensionSetting = this.bb.event;
  }
  renderTemplate(_container) {
    const common = super.S(null, _container, "extension-toggle");
    const actionButton = new $k2(common.containerElement, {
      title: false,
      ...$q$
    });
    actionButton.element.classList.add("setting-item-extension-toggle-button");
    actionButton.label = localize(8986, null);
    const dismissButton = new $k2(common.containerElement, {
      title: false,
      secondary: true,
      ...$q$
    });
    dismissButton.element.classList.add("setting-item-extension-dismiss-button");
    dismissButton.label = localize(8987, null);
    const template = {
      ...common,
      actionButton,
      dismissButton
    };
    this.U(template);
    return template;
  }
  renderElement(element, index, templateData) {
    super.X(element, index, templateData);
  }
  ab(dataElement, template, onChange) {
    template.elementDisposables.clear();
    const extensionId = dataElement.setting.displayExtensionId;
    template.elementDisposables.add(template.actionButton.onDidClick(async () => {
      this.Q.publicLog2("ManageExtensionClick", { extensionId });
      this.I.executeCommand("extension.open", extensionId);
    }));
    template.elementDisposables.add(template.dismissButton.onDidClick(async () => {
      this.Q.publicLog2("DismissExtensionClick", { extensionId });
      this.bb.fire(extensionId);
    }));
  }
};
var $J1b = class $J1b2 extends $3c {
  constructor(h3, j, m, n) {
    super();
    this.h = h3;
    this.j = j;
    this.m = m;
    this.n = n;
    this.c = this.B(new $ze());
    this.f = [
      new $Um("settings.resetSetting", localize(8988, null), void 0, void 0, async (context) => {
        if (context instanceof $m1b) {
          if (!context.isUntrusted) {
            this.c.fire({
              key: context.setting.key,
              value: void 0,
              type: context.setting.type,
              manualReset: true,
              scope: context.setting.scope
            });
          }
        }
      }),
      new $Wm(),
      this.h.createInstance(CopySettingIdAction),
      this.h.createInstance(CopySettingAsJSONAction),
      this.h.createInstance(CopySettingAsURLAction)
    ];
    const actionFactory = (setting, settingTarget) => this.t(setting, settingTarget);
    const emptyActionFactory = (_) => [];
    const extensionRenderer = this.h.createInstance(SettingsExtensionToggleRenderer, [], emptyActionFactory);
    const settingRenderers = [
      this.h.createInstance(SettingBoolRenderer, this.f, actionFactory),
      this.h.createInstance(SettingNumberRenderer, this.f, actionFactory),
      this.h.createInstance(SettingArrayRenderer, this.f, actionFactory),
      this.h.createInstance($I1b, this.f, actionFactory),
      this.h.createInstance(SettingComplexObjectRenderer, this.f, actionFactory),
      this.h.createInstance(SettingTextRenderer, this.f, actionFactory),
      this.h.createInstance(SettingMultilineTextRenderer, this.f, actionFactory),
      this.h.createInstance(SettingExcludeRenderer, this.f, actionFactory),
      this.h.createInstance(SettingIncludeRenderer, this.f, actionFactory),
      this.h.createInstance(SettingEnumRenderer, this.f, actionFactory),
      this.h.createInstance(SettingObjectRenderer, this.f, actionFactory),
      this.h.createInstance(SettingBoolObjectRenderer, this.f, actionFactory),
      extensionRenderer
    ];
    this.onDidClickOverrideElement = Event2.any(...settingRenderers.map((r2) => r2.onDidClickOverrideElement));
    this.onDidChangeSetting = Event2.any(...settingRenderers.map((r2) => r2.onDidChangeSetting), this.c.event);
    this.onDidDismissExtensionSetting = extensionRenderer.onDidDismissExtensionSetting;
    this.onDidOpenSettings = Event2.any(...settingRenderers.map((r2) => r2.onDidOpenSettings));
    this.onDidClickSettingLink = Event2.any(...settingRenderers.map((r2) => r2.onDidClickSettingLink));
    this.onDidFocusSetting = Event2.any(...settingRenderers.map((r2) => r2.onDidFocusSetting));
    this.onDidChangeSettingHeight = Event2.any(...settingRenderers.map((r2) => r2.onDidChangeSettingHeight));
    this.onApplyFilter = Event2.any(...settingRenderers.map((r2) => r2.onApplyFilter));
    this.allRenderers = [
      ...settingRenderers,
      this.h.createInstance(SettingGroupRenderer),
      this.h.createInstance($H1b)
    ];
  }
  t(setting, settingTarget) {
    const actions = [];
    if (setting.scope !== 1 && settingTarget === 3) {
      actions.push(this.h.createInstance(ApplySettingToAllProfilesAction, setting));
    }
    if (this.n.isEnabled() && !setting.disallowSyncIgnore) {
      actions.push(this.h.createInstance(SyncSettingAction, setting));
    }
    if (actions.length) {
      actions.splice(0, 0, new $Wm());
    }
    return actions;
  }
  cancelSuggesters() {
    this.m.hideContextView();
  }
  showContextMenu(element, settingDOMElement) {
    const toolbarElement = settingDOMElement.querySelector(".monaco-toolbar");
    if (toolbarElement) {
      this.j.showContextMenu({
        getActions: () => this.f,
        getAnchor: () => toolbarElement,
        getActionsContext: () => element
      });
    }
  }
  getSettingDOMElementForDOMElement(domElement) {
    const parent = $Gj(domElement, $G1b.CONTENTS_CLASS);
    if (parent) {
      return parent;
    }
    return null;
  }
  getDOMElementsForSettingKey(treeContainer, key2) {
    return treeContainer.querySelectorAll(`[${$G1b.SETTING_KEY_ATTR}="${key2}"]`);
  }
  getKeyForDOMElementInSetting(element) {
    const settingElement = this.getSettingDOMElementForDOMElement(element);
    return settingElement && settingElement.getAttribute($G1b.SETTING_KEY_ATTR);
  }
  getIdForDOMElementInSetting(element) {
    const settingElement = this.getSettingDOMElementForDOMElement(element);
    return settingElement && settingElement.getAttribute($G1b.SETTING_ID_ATTR);
  }
  dispose() {
    super.dispose();
    this.f.forEach((action) => {
      if ($Wc(action)) {
        action.dispose();
      }
    });
    this.allRenderers.forEach((renderer) => {
      if ($Wc(renderer)) {
        renderer.dispose();
      }
    });
  }
};
$J1b = __decorate([
  __param(0, $Pk),
  __param(1, $50),
  __param(2, $40),
  __param(3, $6Bb)
], $J1b);
function renderValidations(dataElement, template, calledOnStartup) {
  if (dataElement.setting.validator) {
    const errMsg = dataElement.setting.validator(template.inputBox.value);
    if (errMsg) {
      template.containerElement.classList.add("invalid-input");
      template.validationErrorMessageElement.innerText = errMsg;
      const validationError = localize(8989, null);
      template.inputBox.inputElement.parentElement.setAttribute("aria-label", [validationError, errMsg].join(" "));
      if (!calledOnStartup) {
        $_Z(validationError + " " + errMsg);
      }
      return true;
    } else {
      template.inputBox.inputElement.parentElement.removeAttribute("aria-label");
    }
  }
  template.containerElement.classList.remove("invalid-input");
  return false;
}
function renderArrayValidations(dataElement, template, value, calledOnStartup) {
  template.containerElement.classList.add("invalid-input");
  if (dataElement.setting.validator) {
    const errMsg = dataElement.setting.validator(value);
    if (errMsg && errMsg !== "") {
      template.containerElement.classList.add("invalid-input");
      template.validationErrorMessageElement.innerText = errMsg;
      const validationError = localize(8990, null);
      template.containerElement.setAttribute("aria-label", [dataElement.setting.key, validationError, errMsg].join(" "));
      if (!calledOnStartup) {
        $_Z(validationError + " " + errMsg);
      }
      return true;
    } else {
      template.containerElement.setAttribute("aria-label", dataElement.setting.key);
      template.containerElement.classList.remove("invalid-input");
    }
  }
  return false;
}
function cleanRenderedMarkdown(element) {
  for (let i2 = 0; i2 < element.childNodes.length; i2++) {
    const child = element.childNodes.item(i2);
    const tagName = child.tagName && child.tagName.toLowerCase();
    if (tagName === "img") {
      child.remove();
    } else {
      cleanRenderedMarkdown(child);
    }
  }
}
function fixSettingLinks(text2, linkify = true) {
  return text2.replace(/`#([^#\s`]+)#`|'#([^#\s']+)#'/g, (match, backticksGroup, quotesGroup) => {
    const settingKey = backticksGroup ?? quotesGroup;
    const targetDisplayFormat = $p1b(settingKey);
    const targetName = `${targetDisplayFormat.category}: ${targetDisplayFormat.label}`;
    return linkify ? `[${targetName}](#${settingKey} "${settingKey}")` : `"${targetName}"`;
  });
}
function escapeInvisibleChars2(enumValue) {
  return enumValue && enumValue.replace(/\n/g, "\\n").replace(/\r/g, "\\r");
}
var $K1b = class $K1b2 {
  constructor(c, d) {
    this.c = c;
    this.d = d;
  }
  filter(element, parentVisibility) {
    if (this.c.filterToCategory && element instanceof $m1b) {
      if (!this.f(element.setting, this.c.filterToCategory)) {
        return false;
      }
    }
    if (element instanceof $m1b && this.c.settingsTarget !== 3) {
      const isRemote = !!this.d.remoteAuthority;
      if (!element.matchesScope(this.c.settingsTarget, isRemote)) {
        return false;
      }
    }
    if (element instanceof $k1b) {
      if (typeof element.count === "number") {
        return element.count > 0;
      }
      return 2;
    }
    if (element instanceof $l1b) {
      if (this.c.tagFilters?.size || this.c.filterToCategory) {
        return false;
      }
    }
    return true;
  }
  f(setting, group2) {
    return group2.children.some((child) => {
      if (child instanceof $k1b) {
        return this.f(setting, child);
      } else if (child instanceof $m1b) {
        return child.setting.key === setting.key;
      } else {
        return false;
      }
    });
  }
};
$K1b = __decorate([
  __param(1, $US)
], $K1b);
var SettingsTreeDelegate = class extends $m1 {
  getTemplateId(element) {
    if (element instanceof $k1b) {
      return SETTINGS_ELEMENT_TEMPLATE_ID;
    }
    if (element instanceof $m1b) {
      if (element.valueType === SettingValueType.ExtensionToggle) {
        return SETTINGS_EXTENSION_TOGGLE_TEMPLATE_ID;
      }
      const invalidTypeError = element.isConfigured && $IK(element.value, element.setting.type);
      if (invalidTypeError) {
        return SETTINGS_COMPLEX_TEMPLATE_ID;
      }
      if (element.valueType === SettingValueType.Boolean) {
        return SETTINGS_BOOL_TEMPLATE_ID;
      }
      if (element.valueType === SettingValueType.Integer || element.valueType === SettingValueType.Number || element.valueType === SettingValueType.NullableInteger || element.valueType === SettingValueType.NullableNumber) {
        return SETTINGS_NUMBER_TEMPLATE_ID;
      }
      if (element.valueType === SettingValueType.MultilineString) {
        return SETTINGS_MULTILINE_TEXT_TEMPLATE_ID;
      }
      if (element.valueType === SettingValueType.String) {
        return SETTINGS_TEXT_TEMPLATE_ID;
      }
      if (element.valueType === SettingValueType.Enum) {
        return SETTINGS_ENUM_TEMPLATE_ID;
      }
      if (element.valueType === SettingValueType.Array) {
        return SETTINGS_ARRAY_TEMPLATE_ID;
      }
      if (element.valueType === SettingValueType.Exclude) {
        return SETTINGS_EXCLUDE_TEMPLATE_ID;
      }
      if (element.valueType === SettingValueType.Include) {
        return SETTINGS_INCLUDE_TEMPLATE_ID;
      }
      if (element.valueType === SettingValueType.Object) {
        return SETTINGS_OBJECT_TEMPLATE_ID;
      }
      if (element.valueType === SettingValueType.BooleanObject) {
        return SETTINGS_BOOL_OBJECT_TEMPLATE_ID;
      }
      if (element.valueType === SettingValueType.ComplexObject) {
        return SETTINGS_COMPLEX_OBJECT_TEMPLATE_ID;
      }
      if (element.valueType === SettingValueType.LanguageTag) {
        return SETTINGS_COMPLEX_TEMPLATE_ID;
      }
      return SETTINGS_COMPLEX_TEMPLATE_ID;
    }
    if (element instanceof $l1b) {
      return SETTINGS_NEW_EXTENSIONS_TEMPLATE_ID;
    }
    throw new Error("unknown element type: " + element);
  }
  hasDynamicHeight(element) {
    return !(element instanceof $k1b);
  }
  d(element) {
    if (element instanceof $k1b) {
      return 42;
    }
    return element instanceof $m1b && element.valueType === SettingValueType.Boolean ? 78 : 104;
  }
};
var $L1b = class extends $w3 {
  isCollapsible(element) {
    return false;
  }
  setCollapsed(element, collapsed2, recursive) {
    return false;
  }
};
var SettingsTreeAccessibilityProvider = class {
  constructor(c, d, f) {
    this.c = c;
    this.d = d;
    this.f = f;
  }
  getAriaLabel(element) {
    if (element instanceof $m1b) {
      const ariaLabelSections = [];
      ariaLabelSections.push(`${element.displayCategory} ${element.displayLabel}.`);
      if (element.isConfigured) {
        const modifiedText = localize(8991, null);
        ariaLabelSections.push(modifiedText);
      }
      const indicatorsLabelAriaLabel = $u1b(element, this.c, this.f, this.d);
      if (indicatorsLabelAriaLabel.length) {
        ariaLabelSections.push(`${indicatorsLabelAriaLabel}.`);
      }
      const descriptionWithoutSettingLinks = $G1({ value: fixSettingLinks(element.description, false) });
      if (descriptionWithoutSettingLinks.length) {
        ariaLabelSections.push(descriptionWithoutSettingLinks);
      }
      return ariaLabelSections.join(" ");
    } else if (element instanceof $k1b) {
      return element.label;
    } else {
      return element.id;
    }
  }
  getWidgetAriaLabel() {
    return localize(8992, null);
  }
};
var $M1b = class $M1b2 extends $1eb {
  constructor(container2, viewState, renderers, contextKeyService, listService, configurationService, instantiationService, languageService, userDataProfilesService) {
    super("SettingsTree", container2, new SettingsTreeDelegate(), renderers, {
      horizontalScrolling: false,
      supportDynamicHeights: true,
      identityProvider: {
        getId(e) {
          return e.id;
        }
      },
      accessibilityProvider: new SettingsTreeAccessibilityProvider(configurationService, languageService, userDataProfilesService),
      styleController: (id2) => new $y1($VZ(container2), id2),
      filter: instantiationService.createInstance($K1b, viewState),
      smoothScrolling: configurationService.getValue("workbench.list.smoothScrolling"),
      multipleSelectionSupport: false,
      findWidgetEnabled: false,
      renderIndentGuides: RenderIndentGuides.None,
      transformOptimization: false
      // Disable transform optimization #177470
    }, instantiationService, contextKeyService, listService, configurationService);
    this.getHTMLElement().classList.add("settings-editor-tree");
    this.style($J$({
      listBackground: $Ko,
      listActiveSelectionBackground: $Ko,
      listActiveSelectionForeground: $eo,
      listFocusAndSelectionBackground: $Ko,
      listFocusAndSelectionForeground: $eo,
      listFocusBackground: $Ko,
      listFocusForeground: $eo,
      listHoverForeground: $eo,
      listHoverBackground: $Ko,
      listHoverOutline: $Ko,
      listFocusOutline: $Ko,
      listInactiveSelectionBackground: $Ko,
      listInactiveSelectionForeground: $eo,
      listInactiveFocusBackground: $Ko,
      listInactiveFocusOutline: $Ko,
      treeIndentGuidesStroke: void 0,
      treeInactiveIndentGuidesStroke: void 0
    }));
    this.E.add(configurationService.onDidChangeConfiguration((e) => {
      if (e.affectsConfiguration("workbench.list.smoothScrolling")) {
        this.updateOptions({
          smoothScrolling: configurationService.getValue("workbench.list.smoothScrolling")
        });
      }
    }));
  }
  V(user, options3) {
    return new $L1b(user, options3);
  }
};
$M1b = __decorate([
  __param(3, $on),
  __param(4, $Deb),
  __param(5, $EK),
  __param(6, $Pk),
  __param(7, $1E),
  __param(8, $rs)
], $M1b);
var CopySettingIdAction = class CopySettingIdAction2 extends $Um {
  static {
    CopySettingIdAction_1 = this;
  }
  static {
    this.ID = "settings.copySettingId";
  }
  static {
    this.LABEL = localize(8993, null);
  }
  constructor(c) {
    super(CopySettingIdAction_1.ID, CopySettingIdAction_1.LABEL);
    this.c = c;
  }
  async run(context) {
    if (context) {
      await this.c.writeText(context.setting.key);
    }
    return Promise.resolve(void 0);
  }
};
CopySettingIdAction = CopySettingIdAction_1 = __decorate([
  __param(0, $30)
], CopySettingIdAction);
var CopySettingAsJSONAction = class CopySettingAsJSONAction2 extends $Um {
  static {
    CopySettingAsJSONAction_1 = this;
  }
  static {
    this.ID = "settings.copySettingAsJSON";
  }
  static {
    this.LABEL = localize(8994, null);
  }
  constructor(c) {
    super(CopySettingAsJSONAction_1.ID, CopySettingAsJSONAction_1.LABEL);
    this.c = c;
  }
  async run(context) {
    if (context) {
      const jsonResult = `"${context.setting.key}": ${JSON.stringify(context.value, void 0, "  ")}`;
      await this.c.writeText(jsonResult);
    }
    return Promise.resolve(void 0);
  }
};
CopySettingAsJSONAction = CopySettingAsJSONAction_1 = __decorate([
  __param(0, $30)
], CopySettingAsJSONAction);
var CopySettingAsURLAction = class CopySettingAsURLAction2 extends $Um {
  static {
    CopySettingAsURLAction_1 = this;
  }
  static {
    this.ID = "settings.copySettingAsURL";
  }
  static {
    this.LABEL = localize(8995, null);
  }
  constructor(c, f) {
    super(CopySettingAsURLAction_1.ID, CopySettingAsURLAction_1.LABEL);
    this.c = c;
    this.f = f;
  }
  async run(context) {
    if (context) {
      const settingKey = context.setting.key;
      const product2 = this.f.urlProtocol;
      const uri = URI.from({ scheme: product2, authority: $YK, path: `/${settingKey}` }, true);
      await this.c.writeText(uri.toString());
    }
    return Promise.resolve(void 0);
  }
};
CopySettingAsURLAction = CopySettingAsURLAction_1 = __decorate([
  __param(0, $30),
  __param(1, $Vu)
], CopySettingAsURLAction);
var SyncSettingAction = class SyncSettingAction2 extends $Um {
  static {
    SyncSettingAction_1 = this;
  }
  static {
    this.ID = "settings.stopSyncingSetting";
  }
  static {
    this.LABEL = localize(8996, null);
  }
  constructor(c, f) {
    super(SyncSettingAction_1.ID, SyncSettingAction_1.LABEL);
    this.c = c;
    this.f = f;
    this.B(Event2.filter(f.onDidChangeConfiguration, (e) => e.affectsConfiguration("settingsSync.ignoredSettings"))(() => this.update()));
    this.update();
  }
  async update() {
    const ignoredSettings = $uWb($LBb(), this.f);
    this.checked = !ignoredSettings.includes(this.c.key);
  }
  async run() {
    let currentValue = [...this.f.getValue("settingsSync.ignoredSettings")];
    currentValue = currentValue.filter((v) => v !== this.c.key && v !== `-${this.c.key}`);
    const defaultIgnoredSettings = $LBb();
    const isDefaultIgnored = defaultIgnoredSettings.includes(this.c.key);
    const askedToSync = !this.checked;
    if (askedToSync && isDefaultIgnored) {
      currentValue.push(`-${this.c.key}`);
    }
    if (!askedToSync && !isDefaultIgnored) {
      currentValue.push(this.c.key);
    }
    this.f.updateValue(
      "settingsSync.ignoredSettings",
      currentValue.length ? currentValue : void 0,
      2
      /* ConfigurationTarget.USER */
    );
    return Promise.resolve(void 0);
  }
};
SyncSettingAction = SyncSettingAction_1 = __decorate([
  __param(1, $kl)
], SyncSettingAction);
var ApplySettingToAllProfilesAction = class ApplySettingToAllProfilesAction2 extends $Um {
  static {
    ApplySettingToAllProfilesAction_1 = this;
  }
  static {
    this.ID = "settings.applyToAllProfiles";
  }
  static {
    this.LABEL = localize(8997, null);
  }
  constructor(c, f) {
    super(ApplySettingToAllProfilesAction_1.ID, ApplySettingToAllProfilesAction_1.LABEL);
    this.c = c;
    this.f = f;
    this.B(Event2.filter(f.onDidChangeConfiguration, (e) => e.affectsConfiguration($GK))(() => this.update()));
    this.update();
  }
  update() {
    const allProfilesSettings = this.f.getValue($GK);
    this.checked = allProfilesSettings.includes(this.c.key);
  }
  async run() {
    const value = this.f.getValue($GK) ?? [];
    if (this.checked) {
      value.splice(value.indexOf(this.c.key), 1);
    } else {
      value.push(this.c.key);
    }
    const newValue = $Rb(value);
    if (this.checked) {
      await this.f.updateValue(
        this.c.key,
        this.f.inspect(this.c.key).application?.value,
        3
        /* ConfigurationTarget.USER_LOCAL */
      );
      await this.f.updateValue(
        $GK,
        newValue.length ? newValue : void 0,
        3
        /* ConfigurationTarget.USER_LOCAL */
      );
    } else {
      await this.f.updateValue(
        $GK,
        newValue.length ? newValue : void 0,
        3
        /* ConfigurationTarget.USER_LOCAL */
      );
      await this.f.updateValue(
        this.c.key,
        this.f.inspect(this.c.key).userLocal?.value,
        3
        /* ConfigurationTarget.USER_LOCAL */
      );
    }
  }
};
ApplySettingToAllProfilesAction = ApplySettingToAllProfilesAction_1 = __decorate([
  __param(1, $EK)
], ApplySettingToAllProfilesAction);

// out-build/vs/workbench/contrib/preferences/browser/tocTree.js
var $119 = $;
var $N1b = class $N1b2 {
  constructor(d, f) {
    this.d = d;
    this.f = f;
    this.a = null;
  }
  get settingsTreeRoot() {
    return this.b;
  }
  set settingsTreeRoot(value) {
    this.b = value;
    this.update();
  }
  get currentSearchModel() {
    return this.a;
  }
  set currentSearchModel(model) {
    this.a = model;
    this.update();
  }
  get children() {
    return this.b.children;
  }
  update() {
    if (this.b) {
      this.h(this.b);
    }
  }
  h(group2) {
    group2.children.forEach((child) => {
      if (child instanceof $k1b) {
        this.h(child);
      }
    });
    const childCount = group2.children.filter((child) => child instanceof $k1b).reduce((acc, cur) => acc + cur.count, 0);
    group2.count = childCount + this.j(group2);
  }
  j(group2) {
    return group2.children.filter((child) => {
      if (!(child instanceof $m1b)) {
        return false;
      }
      if (this.a && !this.a.root.containsSetting(child.setting.key)) {
        return false;
      }
      const isRemote = !!this.f.remoteAuthority;
      return child.matchesScope(this.d.settingsTarget, isRemote) && child.matchesAllTags(this.d.tagFilters) && child.matchesAnyFeature(this.d.featureFilters) && child.matchesAnyExtension(this.d.extensionFilters) && child.matchesAnyId(this.d.idFilters);
    }).length;
  }
};
$N1b = __decorate([
  __param(1, $US)
], $N1b);
var TOC_ENTRY_TEMPLATE_ID = "settings.toc.entry";
var $O1b = class {
  constructor(a) {
    this.a = a;
    this.templateId = TOC_ENTRY_TEMPLATE_ID;
  }
  renderTemplate(container2) {
    return {
      labelElement: $bk(container2, $119(".settings-toc-entry")),
      countElement: $bk(container2, $119(".settings-toc-count")),
      elementDisposables: new $2c()
    };
  }
  renderElement(node, index, template) {
    template.elementDisposables.clear();
    const element = node.element;
    const count = element.count;
    const label3 = element.label;
    template.labelElement.textContent = label3;
    template.elementDisposables.add(this.a.setupManagedHover($JZ("mouse"), template.labelElement, label3));
    if (count) {
      template.countElement.textContent = ` (${count})`;
    } else {
      template.countElement.textContent = "";
    }
  }
  disposeTemplate(templateData) {
    templateData.elementDisposables.dispose();
  }
};
var TOCTreeDelegate = class {
  getTemplateId(element) {
    return TOC_ENTRY_TEMPLATE_ID;
  }
  getHeight(element) {
    return 22;
  }
};
function $P1b(model, tree) {
  const groupChildren = model.children.filter((c) => c instanceof $k1b);
  return Iterable.map(groupChildren, (g) => {
    const hasGroupChildren = g.children.some((c) => c instanceof $k1b);
    return {
      element: g,
      collapsed: void 0,
      collapsible: hasGroupChildren,
      children: g instanceof $k1b ? $P1b(g, tree) : void 0
    };
  });
}
var SettingsAccessibilityProvider = class {
  getWidgetAriaLabel() {
    return localize(9042, null);
  }
  getAriaLabel(element) {
    if (!element) {
      return "";
    }
    if (element instanceof $k1b) {
      return localize(9043, null, element.label);
    }
    return "";
  }
  getAriaLevel(element) {
    let i2 = 1;
    while (element instanceof $k1b && element.parent) {
      i2++;
      element = element.parent;
    }
    return i2;
  }
};
var $Q1b = class $Q1b2 extends $1eb {
  constructor(container2, viewState, contextKeyService, listService, configurationService, hoverService, instantiationService) {
    const filter = instantiationService.createInstance($K1b, viewState);
    const options3 = {
      filter,
      multipleSelectionSupport: false,
      identityProvider: {
        getId(e) {
          return e.id;
        }
      },
      styleController: (id2) => new $y1($VZ(container2), id2),
      accessibilityProvider: instantiationService.createInstance(SettingsAccessibilityProvider),
      collapseByDefault: true,
      horizontalScrolling: false,
      hideTwistiesOfChildlessElements: true,
      renderIndentGuides: RenderIndentGuides.None
    };
    super("SettingsTOC", container2, new TOCTreeDelegate(), [new $O1b(hoverService)], options3, instantiationService, contextKeyService, listService, configurationService);
    this.style($J$({
      listBackground: $Ko,
      listFocusOutline: $jo,
      listActiveSelectionBackground: $Ko,
      listActiveSelectionForeground: $QZb,
      listFocusAndSelectionBackground: $Ko,
      listFocusAndSelectionForeground: $QZb,
      listFocusBackground: $Ko,
      listFocusForeground: $RZb,
      listHoverForeground: $RZb,
      listHoverBackground: $Ko,
      listInactiveSelectionBackground: $Ko,
      listInactiveSelectionForeground: $QZb,
      listInactiveFocusBackground: $Ko,
      listInactiveFocusOutline: $Ko,
      treeIndentGuidesStroke: void 0,
      treeInactiveIndentGuidesStroke: void 0
    }));
  }
};
$Q1b = __decorate([
  __param(2, $on),
  __param(3, $Deb),
  __param(4, $kl),
  __param(5, $5$),
  __param(6, $Pk)
], $Q1b);

// out-build/vs/workbench/contrib/preferences/browser/settingsSearchMenu.js
var $R1b = class $R1b2 extends $L2 {
  constructor(action, options3, actionRunner, g, contextMenuService) {
    super(action, { getActions: () => this.getActions() }, contextMenuService, {
      ...options3,
      actionRunner,
      classNames: action.class,
      anchorAlignmentProvider: () => 1,
      menuAsChild: true
    });
    this.g = g;
    this.a = $qdb.get(this.g.inputWidget);
  }
  render(container2) {
    super.render(container2);
  }
  r(queryToAppend, triggerSuggest) {
    this.g.setValue(this.g.getValue().trimEnd() + " " + queryToAppend);
    this.g.focus();
    if (triggerSuggest && this.a) {
      this.a.triggerSuggest();
    }
  }
  /**
   * The created action appends a query to the search widget search string. It optionally triggers suggestions.
   */
  O(id2, label3, tooltip, queryToAppend, triggerSuggest) {
    return {
      id: id2,
      label: label3,
      tooltip,
      class: void 0,
      enabled: true,
      run: () => {
        this.r(queryToAppend, triggerSuggest);
      }
    };
  }
  /**
   * The created action appends a query to the search widget search string, if the query does not exist.
   * Otherwise, it removes the query from the search widget search string.
   * The action does not trigger suggestions after adding or removing the query.
   */
  P(id2, label3, tooltip, queryToAppend) {
    const splitCurrentQuery = this.g.getValue().split(" ");
    const queryContainsQueryToAppend = splitCurrentQuery.includes(queryToAppend);
    return {
      id: id2,
      label: label3,
      tooltip,
      class: void 0,
      enabled: true,
      checked: queryContainsQueryToAppend,
      run: () => {
        if (!queryContainsQueryToAppend) {
          const trimmedCurrentQuery = this.g.getValue().trimEnd();
          const newQuery = trimmedCurrentQuery ? trimmedCurrentQuery + " " + queryToAppend : queryToAppend;
          this.g.setValue(newQuery);
        } else {
          const queryWithRemovedTags = this.g.getValue().split(" ").filter((word) => word !== queryToAppend).join(" ");
          this.g.setValue(queryWithRemovedTags);
        }
        this.g.focus();
      }
    };
  }
  getActions() {
    return [
      this.P("modifiedSettingsSearch", localize(8964, null), localize(8965, null), `@${$wZb}`),
      this.O("extSettingsSearch", localize(8966, null), localize(8967, null), `@${$xZb}`, true),
      this.O("featuresSettingsSearch", localize(8968, null), localize(8969, null), `@${$yZb}`, true),
      this.O("tagSettingsSearch", localize(8970, null), localize(8971, null), `@${$BZb}`, true),
      this.O("langSettingsSearch", localize(8972, null), localize(8973, null), `@${$AZb}`, true),
      this.P("onlineSettingsSearch", localize(8974, null), localize(8975, null), "@tag:usesOnlineServices"),
      this.P("policySettingsSearch", localize(8976, null), localize(8977, null), `@${$CZb}`)
    ];
  }
};
$R1b = __decorate([
  __param(4, $50)
], $R1b);

// out-build/vs/workbench/contrib/preferences/browser/settingsEditor2.js
var $T1b_1;
var SettingsFocusContext;
(function(SettingsFocusContext2) {
  SettingsFocusContext2[SettingsFocusContext2["Search"] = 0] = "Search";
  SettingsFocusContext2[SettingsFocusContext2["TableOfContents"] = 1] = "TableOfContents";
  SettingsFocusContext2[SettingsFocusContext2["SettingTree"] = 2] = "SettingTree";
  SettingsFocusContext2[SettingsFocusContext2["SettingControl"] = 3] = "SettingControl";
})(SettingsFocusContext || (SettingsFocusContext = {}));
function $S1b(group2) {
  return Iterable.map(group2.children, (g) => {
    return {
      element: g,
      children: g instanceof $k1b ? $S1b(g) : void 0
    };
  });
}
var $120 = $;
var searchBoxLabel = localize(8858, null);
var SEARCH_TOC_BEHAVIOR_KEY = "workbench.settings.settingsSearchTocBehavior";
var SETTINGS_EDITOR_STATE_KEY = "settingsEditorState";
var $T1b = class $T1b2 extends $5tb {
  static {
    $T1b_1 = this;
  }
  static {
    this.ID = "workbench.editor.settings2";
  }
  static {
    this.a = 0;
  }
  static {
    this.b = 200;
  }
  static {
    this.c = 200;
  }
  static {
    this.f = 1e3;
  }
  static {
    this.j = 500;
  }
  static {
    this.r = 100;
  }
  static {
    this.u = 200;
  }
  static {
    this.cb = 500;
  }
  static {
    this.db = this.u + this.cb;
  }
  static {
    this.eb = [
      `@${$wZb}`,
      "@tag:notebookLayout",
      "@tag:notebookOutputLayout",
      `@tag:${$EZb}`,
      `@tag:${$DZb}`,
      "@tag:sync",
      "@tag:usesOnlineServices",
      "@tag:telemetry",
      "@tag:accessibility",
      "@tag:preview",
      "@tag:experimental",
      `@${$zZb}`,
      `@${$xZb}`,
      `@${$yZb}scm`,
      `@${$yZb}explorer`,
      `@${$yZb}search`,
      `@${$yZb}debug`,
      `@${$yZb}extensions`,
      `@${$yZb}terminal`,
      `@${$yZb}task`,
      `@${$yZb}problems`,
      `@${$yZb}output`,
      `@${$yZb}comments`,
      `@${$yZb}remote`,
      `@${$yZb}timeline`,
      `@${$yZb}notebook`,
      `@${$CZb}`
    ];
  }
  static fb(type) {
    if (Array.isArray(type)) {
      return false;
    }
    return type === SettingValueType.Enum || type === SettingValueType.Array || type === SettingValueType.BooleanObject || type === SettingValueType.Object || type === SettingValueType.Complex || type === SettingValueType.Boolean || type === SettingValueType.Exclude || type === SettingValueType.Include;
  }
  constructor(group2, telemetryService, dc, textResourceConfigurationService, themeService, ec, fc, gc, hc, contextKeyService, ic, jc, kc, lc, mc, nc, oc, pc, qc, rc, sc, userDataProfileService) {
    super($T1b_1.ID, group2, telemetryService, themeService, ic);
    this.dc = dc;
    this.ec = ec;
    this.fc = fc;
    this.gc = gc;
    this.hc = hc;
    this.ic = ic;
    this.jc = jc;
    this.kc = kc;
    this.lc = lc;
    this.mc = mc;
    this.nc = nc;
    this.oc = oc;
    this.pc = pc;
    this.qc = qc;
    this.rc = rc;
    this.sc = sc;
    this.Bb = null;
    this.Gb = null;
    this.Ib = null;
    this.Jb = null;
    this.Kb = null;
    this.Lb = null;
    this.Rb = 0;
    this.Sb = false;
    this.Tb = false;
    this.Vb = null;
    this.Wb = null;
    this.Xb = 0;
    this.Zb = [];
    this.$b = [];
    this.ac = "settingsEditor2.dismissedExtensionSettings";
    this.bc = "	";
    this.zb = new $Sh(1e3);
    this.Ab = new $Sh(300);
    this.Hb = {
      settingsTarget: 3
      /* ConfigurationTarget.USER_LOCAL */
    };
    this.Eb = new $Sh($T1b_1.c);
    this.Fb = new $Sh($T1b_1.f);
    this.Cb = new $Sh($T1b_1.b);
    this.Db = new $Sh($T1b_1.j);
    this.Ob = $6Yb.bindTo(contextKeyService);
    this.Pb = $8Yb.bindTo(contextKeyService);
    this.Mb = $9Yb.bindTo(contextKeyService);
    this.Nb = $0Yb.bindTo(contextKeyService);
    this.Qb = /* @__PURE__ */ new Map();
    this.Ub = this.ab(jc, textResourceConfigurationService, SETTINGS_EDITOR_STATE_KEY);
    this.$b = this.ic.get(this.ac, 0, "").split(this.bc);
    this.B(dc.onDidChangeConfiguration((e) => {
      if (e.source !== 7) {
        this.Wc(e.affectedKeys);
      }
    }));
    this.B(userDataProfileService.onDidChangeCurrentProfile((e) => {
      e.join(this.tc());
    }));
    this.B(mc.onDidChangeTrust(() => {
      this.vc?.updateWorkspaceTrust(mc.isWorkspaceTrusted());
      if (this.ub) {
        this.ub.updateWorkspaceTrust(mc.isWorkspaceTrusted());
        this.Zc();
      }
    }));
    this.B(dc.onDidChangeRestrictedSettings((e) => {
      if (e.default.length && this.uc) {
        this.Xc(new Set(e.default));
      }
    }));
    this.B(pc.onDidInstallExtensions(() => {
      this.yc();
    }));
    this.B(pc.onDidUninstallExtension(() => {
      this.yc();
    }));
    this.hb = this.B(new $2c());
    if ($GZb && !$T1b_1.eb.includes(`@${$AZb}`)) {
      $T1b_1.eb.push(`@${$AZb}`);
    }
    this.cc = this.B(new $4c());
  }
  async tc() {
    this.Db.trigger(() => {
      this.$b = this.ic.get(this.ac, 0, "").split(this.bc);
      this.Wc(void 0, true);
    });
  }
  get minimumWidth() {
    return $T1b_1.cb;
  }
  get maximumWidth() {
    return Number.POSITIVE_INFINITY;
  }
  get minimumHeight() {
    return 180;
  }
  // these setters need to exist because this extends from EditorPane
  set minimumWidth(value) {
  }
  set maximumWidth(value) {
  }
  get uc() {
    return this.vc || this.ub;
  }
  get vc() {
    return this.Ib;
  }
  set vc(value) {
    this.Ib = value;
    this.ib.classList.toggle("search-mode", !!this.Ib);
  }
  get wc() {
    const focused = this.rb.getFocus()[0];
    if (!(focused instanceof $m1b)) {
      return;
    }
    return this.sb.getDOMElementsForSettingKey(this.rb.getHTMLElement(), focused.setting.key)[0];
  }
  get currentFocusContext() {
    return this.Rb;
  }
  Y(parent) {
    parent.setAttribute("tabindex", "-1");
    this.ib = $bk(parent, $120(".settings-editor", { tabindex: "-1" }));
    this.Dc(this.ib);
    this.Ic(this.ib);
    this.Jc(this.ib);
    this.updateStyles();
    this.B($iKb({
      name: "settingsEditor2",
      focusNotifiers: [this],
      focusNextWidget: () => {
        if (this.lb.inputWidget.hasWidgetFocus()) {
          this.focusTOC();
        }
      },
      focusPreviousWidget: () => {
        if (!this.lb.inputWidget.hasWidgetFocus()) {
          this.focusSearch();
        }
      }
    }));
  }
  async setInput(input, options3, context, token) {
    this.Ob.set(true);
    await super.setInput(input, options3, context, token);
    if (!this.input) {
      return;
    }
    const model = await this.input.resolve();
    if (token.isCancellationRequested || !(model instanceof $LK)) {
      return;
    }
    this.hb.clear();
    this.hb.add(model.onDidChangeGroups(() => {
      this.Db.trigger(() => {
        this.Wc(void 0, false, true);
      });
    }));
    this.gb = model;
    options3 = options3 || $SK({});
    if (!this.Hb.settingsTarget || !this.ob.settingsTarget) {
      const optionsHasViewStateTarget = options3.viewState && options3.viewState.settingsTarget;
      if (!options3.target && !optionsHasViewStateTarget) {
        options3.target = 3;
      }
    }
    this.Ac(options3);
    this.Wc(void 0, true).then(() => {
      this.cc.value = input.onWillDispose(() => {
        this.lb.setValue("");
      });
      this.Pc();
    });
    await this.yc();
  }
  async yc() {
    const installedExtensions = await this.pc.getInstalled();
    this.Zb = installedExtensions.filter((ext) => ext.manifest.contributes?.configuration).map((ext) => ext.identifier.id);
  }
  zc() {
    const cachedState = this.input && this.Ub.loadEditorState(this.group, this.input);
    if (cachedState && typeof cachedState.target === "object") {
      cachedState.target = URI.revive(cachedState.target);
    }
    if (cachedState) {
      const settingsTarget = cachedState.target;
      this.ob.settingsTarget = settingsTarget;
      this.Hb.settingsTarget = settingsTarget;
      if (!this.lb.getValue()) {
        this.lb.setValue(cachedState.searchQuery);
      }
    }
    if (this.input) {
      this.Ub.clearEditorState(this.input, this.group);
    }
    return cachedState ?? null;
  }
  getViewState() {
    return this.Hb;
  }
  setOptions(options3) {
    super.setOptions(options3);
    if (options3) {
      this.Ac(options3);
    }
  }
  Ac(options3) {
    if (options3.focusSearch && !$u) {
      this.focusSearch();
    }
    const recoveredViewState = options3.viewState ? options3.viewState : void 0;
    const query = recoveredViewState?.query ?? options3.query;
    if (query !== void 0) {
      this.lb.setValue(query);
      this.Hb.query = query;
    }
    const target = options3.folderUri ?? recoveredViewState?.settingsTarget ?? options3.target;
    if (target) {
      this.ob.updateTarget(target);
    }
  }
  clearInput() {
    this.Ob.set(false);
    super.clearInput();
  }
  layout(dimension) {
    this.Yb = dimension;
    if (!this.isVisible()) {
      return;
    }
    this.sd(dimension);
    const innerWidth = Math.min(this.jb.clientWidth, dimension.width) - 24 * 2;
    const monacoWidth = innerWidth - 10 - this.mb.clientWidth - this.nb.clientWidth - 12;
    this.lb.layout(new $rj(monacoWidth, 20));
    this.ib.classList.toggle("narrow-width", dimension.width < $T1b_1.db);
  }
  focus() {
    super.focus();
    if (this.Rb === 0) {
      if (!$u) {
        this.focusSearch();
      }
    } else if (this.Rb === 3) {
      const element = this.wc;
      if (element) {
        const control = element.querySelector($G1b.CONTROL_SELECTOR);
        if (control) {
          control.focus();
          return;
        }
      }
    } else if (this.Rb === 2) {
      this.rb.domFocus();
    } else if (this.Rb === 1) {
      this.yb.domFocus();
    }
  }
  Z(visible) {
    super.Z(visible);
    if (!visible) {
      setTimeout(() => {
        this.lb.onHide();
      }, 0);
    }
  }
  focusSettings(focusSettingInput = false) {
    const focused = this.rb.getFocus();
    if (!focused.length) {
      this.rb.focusFirst();
    }
    this.rb.domFocus();
    if (focusSettingInput) {
      const controlInFocusedRow = this.rb.getHTMLElement().querySelector(`.focused ${$G1b.CONTROL_SELECTOR}`);
      if (controlInFocusedRow) {
        controlInFocusedRow.focus();
      }
    }
  }
  focusTOC() {
    this.yb.domFocus();
  }
  showContextMenu() {
    const focused = this.rb.getFocus()[0];
    const rowElement = this.wc;
    if (rowElement && focused instanceof $m1b) {
      this.sb.showContextMenu(focused, rowElement);
    }
  }
  focusSearch(filter, selectAll = true) {
    if (filter && this.lb) {
      this.lb.setValue(filter);
    }
    this.lb.focus(selectAll && !this.Cb.isTriggered);
  }
  clearSearchResults() {
    this.lb.setValue("");
    this.focusSearch();
  }
  clearSearchFilters() {
    const query = this.lb.getValue();
    const splitQuery = query.split(" ").filter((word) => {
      return word.length && !$T1b_1.eb.some((suggestion) => word.startsWith(suggestion));
    });
    this.lb.setValue(splitQuery.join(" "));
  }
  Cc() {
    let label3 = searchBoxLabel;
    if (this.Jb) {
      label3 += `. ${this.Jb}`;
    }
    if (this.Kb) {
      label3 += `. ${this.Kb}`;
    }
    this.lb.updateAriaLabel(label3);
  }
  /**
   * Render the header of the Settings editor, which includes the content above the splitview.
   */
  Dc(parent) {
    this.jb = $bk(parent, $120(".settings-header"));
    const searchContainer = $bk(this.jb, $120(".search-container"));
    const clearInputAction = new $Um($3Yb, localize(8859, null), ThemeIcon.asClassName($RYb), false, async () => this.clearSearchResults());
    const filterAction = new $Um($5Yb, localize(8860, null), ThemeIcon.asClassName($SYb));
    this.lb = this.B(this.fc.createInstance($NZb, `${$T1b_1.ID}.searchbox`, searchContainer, {
      triggerCharacters: ["@", ":"],
      provideResults: (query) => {
        const queryParts = query.split(/\s/g);
        if (queryParts[queryParts.length - 1].startsWith(`@${$AZb}`)) {
          const sortedLanguages = this.oc.getRegisteredLanguageIds().map((languageId) => {
            return `@${$AZb}${languageId} `;
          }).sort();
          return sortedLanguages.filter((langFilter) => !query.includes(langFilter));
        } else if (queryParts[queryParts.length - 1].startsWith(`@${$xZb}`)) {
          const installedExtensionsTags = this.Zb.map((extensionId) => {
            return `@${$xZb}${extensionId} `;
          }).sort();
          return installedExtensionsTags.filter((extFilter) => !query.includes(extFilter));
        } else if (queryParts[queryParts.length - 1].startsWith("@")) {
          return $T1b_1.eb.filter((tag2) => !query.includes(tag2)).map((tag2) => tag2.endsWith(":") ? tag2 : tag2 + " ");
        }
        return [];
      }
    }, searchBoxLabel, "settingseditor:searchinput" + $T1b_1.a++, {
      placeholderText: searchBoxLabel,
      focusContextKey: this.Pb,
      styleOverrides: {
        inputBorder: $5Zb
      }
      // TODO: Aria-live
    }));
    this.B(this.lb.onDidFocus(() => {
      this.Rb = 0;
    }));
    this.mb = $bk(searchContainer, $(".settings-count-widget.monaco-count-badge.long"));
    this.mb.style.backgroundColor = $Zn($wo);
    this.mb.style.color = $Zn($xo);
    this.mb.style.border = `1px solid ${$Zn($ko)}`;
    this.B(this.lb.onInputDidChange(() => {
      const searchVal = this.lb.getValue();
      clearInputAction.enabled = !!searchVal;
      this.Cb.trigger(() => this.ed());
    }));
    const headerControlsContainer = $bk(this.jb, $120(".settings-header-controls"));
    headerControlsContainer.style.borderColor = $Zn($TZb);
    const targetWidgetContainer = $bk(headerControlsContainer, $120(".settings-target-container"));
    this.ob = this.B(this.fc.createInstance($VYb, targetWidgetContainer, { enableRemoteSettings: true }));
    this.ob.settingsTarget = 3;
    this.ob.onDidTargetChange((target) => this.Ec(target));
    this.B($_i(targetWidgetContainer, $7j.KEY_DOWN, (e) => {
      const event = new $if(e);
      if (event.keyCode === 18) {
        this.focusSettings();
      }
    }));
    if (this.kc.enabled && this.lc.canToggleEnablement()) {
      const syncControls = this.B(this.fc.createInstance(SyncControls, this.window, headerControlsContainer));
      this.B(syncControls.onDidChangeLastSyncedLabel((lastSyncedLabel) => {
        this.Kb = lastSyncedLabel;
        this.Cc();
      }));
    }
    this.nb = $bk(searchContainer, $(".settings-clear-widget"));
    const actionBar = this.B(new $LZ(this.nb, {
      actionViewItemProvider: (action, options3) => {
        if (action.id === filterAction.id) {
          return this.fc.createInstance($R1b, action, options3, this.N, this.lb);
        }
        return void 0;
      }
    }));
    actionBar.push([clearInputAction, filterAction], { label: false, icon: true });
  }
  Ec(target) {
    this.Hb.settingsTarget = target;
    this.Wc(void 0, true);
  }
  Fc(extensionId) {
    if (!this.$b.includes(extensionId)) {
      this.$b.push(extensionId);
    }
    this.ic.store(
      this.ac,
      this.$b.join(this.bc),
      0,
      0
      /* StorageTarget.USER */
    );
    this.Wc(void 0, true);
  }
  Gc(evt, recursed) {
    const targetElement = this.uc.getElementsByName(evt.targetKey)?.[0];
    let revealFailed = false;
    if (targetElement) {
      let sourceTop = 0.5;
      try {
        const _sourceTop = this.rb.getRelativeTop(evt.source);
        if (_sourceTop !== null) {
          sourceTop = _sourceTop;
        }
      } catch {
      }
      if (this.Hb.filterToCategory && evt.source.displayCategory !== targetElement.displayCategory) {
        this.yb.setFocus([]);
      }
      try {
        this.rb.reveal(targetElement, sourceTop);
      } catch (_) {
        revealFailed = true;
      }
      if (!revealFailed) {
        setTimeout(() => {
          this.rb.setFocus([targetElement]);
        }, 50);
        const domElements = this.sb.getDOMElementsForSettingKey(this.rb.getHTMLElement(), evt.targetKey);
        if (domElements && domElements[0]) {
          const control = domElements[0].querySelector($G1b.CONTROL_SELECTOR);
          if (control) {
            control.focus();
          }
        }
      }
    }
    if (!recursed && (!targetElement || revealFailed)) {
      const p = this.hd("");
      p.then(() => {
        this.lb.setValue("");
        this.Gc(evt, true);
      });
    }
  }
  switchToSettingsFile() {
    const query = $s1b(this.lb.getValue()).query;
    return this.Hc({ query });
  }
  async Hc(options3) {
    const currentSettingsTarget = this.ob.settingsTarget;
    const openOptions = { jsonEditor: true, ...options3 };
    if (currentSettingsTarget === 3) {
      if (options3?.revealSetting) {
        const configurationProperties = $Wn.as($Ht.Configuration).getConfigurationProperties();
        const configurationScope = configurationProperties[options3?.revealSetting.key]?.scope;
        if (configurationScope === 1) {
          return this.ec.openApplicationSettings(openOptions);
        }
      }
      return this.ec.openUserSettings(openOptions);
    } else if (currentSettingsTarget === 4) {
      return this.ec.openRemoteSettings(openOptions);
    } else if (currentSettingsTarget === 5) {
      return this.ec.openWorkspaceSettings(openOptions);
    } else if (URI.isUri(currentSettingsTarget)) {
      return this.ec.openFolderSettings({ folderUri: currentSettingsTarget, ...openOptions });
    }
    return void 0;
  }
  Ic(parent) {
    this.kb = $bk(parent, $120(".settings-body"));
    this.vb = $bk(this.kb, $120(".no-results-message"));
    this.vb.innerText = localize(8861, null);
    this.wb = $120("span.clear-search-filters");
    this.wb.textContent = " - ";
    const clearFilterLink = $bk(this.wb, $120("a.pointer.prominent", { tabindex: 0 }, localize(8862, null)));
    this.B($_i(clearFilterLink, $7j.CLICK, (e) => {
      $9j.stop(e, false);
      this.clearSearchFilters();
    }));
    $bk(this.vb, this.wb);
    this.vb.style.color = $Zn($Lo);
    this.xb = $120(".settings-toc-container");
    this.qb = $120(".settings-tree-container");
    this.Kc(this.xb);
    this.Nc(this.qb);
    this.pb = this.B(new $r2(this.kb, {
      orientation: 1,
      proportionalLayout: true
    }));
    const startingWidth = this.ic.getNumber("settingsEditor2.splitViewWidth", 0, $T1b_1.u);
    this.pb.addView({
      onDidChange: Event2.None,
      element: this.xb,
      minimumSize: $T1b_1.r,
      maximumSize: Number.POSITIVE_INFINITY,
      layout: (width2, _, height) => {
        this.xb.style.width = `${width2}px`;
        this.yb.layout(height, width2);
      }
    }, startingWidth, void 0, true);
    this.pb.addView({
      onDidChange: Event2.None,
      element: this.qb,
      minimumSize: $T1b_1.cb,
      maximumSize: Number.POSITIVE_INFINITY,
      layout: (width2, _, height) => {
        this.qb.style.width = `${width2}px`;
        this.rb.layout(height, width2);
      }
    }, Sizing.Distribute, void 0, true);
    this.B(this.pb.onDidSashReset(() => {
      const totalSize = this.pb.getViewSize(0) + this.pb.getViewSize(1);
      this.pb.resizeView(0, $T1b_1.u);
      this.pb.resizeView(1, totalSize - $T1b_1.u);
    }));
    this.B(this.pb.onDidSashChange(() => {
      const width2 = this.pb.getViewSize(0);
      this.ic.store(
        "settingsEditor2.splitViewWidth",
        width2,
        0,
        0
        /* StorageTarget.USER */
      );
    }));
    const borderColor = this.h.getColor($UZb);
    this.pb.style({ separatorBorder: borderColor });
  }
  Jc(container2) {
    this.B($aj(container2, $7j.KEY_DOWN, (e) => {
      if (e.keyCode === 31 && ($m ? e.metaKey : e.ctrlKey) && !$Fk(e.target)) {
        e.browserEvent.stopPropagation();
        e.browserEvent.preventDefault();
      }
    }));
  }
  Kc(container2) {
    this.tb = this.fc.createInstance($N1b, this.Hb);
    this.yb = this.B(this.fc.createInstance($Q1b, $bk(container2, $120(".settings-toc-wrapper", {
      "role": "navigation",
      "aria-label": localize(8863, null)
    })), this.Hb));
    this.Tb = false;
    this.B(this.yb.onDidFocus(() => {
      this.Rb = 1;
    }));
    this.B(this.yb.onDidChangeFocus((e) => {
      const element = e.elements?.[0] ?? null;
      if (this.Vb === element) {
        return;
      }
      this.Vb = element;
      this.yb.setSelection(element ? [element] : []);
      if (this.vc) {
        if (this.Hb.filterToCategory !== element) {
          this.Hb.filterToCategory = element ?? void 0;
          this.Zc(void 0, true);
          this.rb.scrollTop = 0;
        }
      } else if (element && (!e.browserEvent || !e.browserEvent.fromScroll)) {
        this.rb.reveal(element, 0);
        this.rb.setFocus([element]);
      }
    }));
    this.B(this.yb.onDidFocus(() => {
      this.Mb.set(true);
    }));
    this.B(this.yb.onDidBlur(() => {
      this.Mb.set(false);
    }));
    this.B(this.yb.onDidDispose(() => {
      this.Tb = true;
    }));
  }
  Lc(filter) {
    if (this.lb && !this.lb.getValue().includes(filter)) {
      const newQuery = `${filter} ${this.lb.getValue().trimStart()}`;
      this.focusSearch(newQuery, false);
    }
  }
  Mc() {
    if (this.lb && this.lb.getValue().includes(`@${$AZb}`)) {
      const query = this.lb.getValue().split(" ");
      const newQuery = query.filter((word) => !word.startsWith(`@${$AZb}`)).join(" ");
      this.focusSearch(newQuery, false);
    }
  }
  Nc(container2) {
    this.sb = this.B(this.fc.createInstance($J1b));
    this.B(this.sb.onDidChangeSetting((e) => this.Oc(e.key, e.value, e.type, e.manualReset, e.scope)));
    this.B(this.sb.onDidDismissExtensionSetting((e) => this.Fc(e)));
    this.B(this.sb.onDidOpenSettings((settingKey) => {
      this.Hc({ revealSetting: { key: settingKey, edit: true } });
    }));
    this.B(this.sb.onDidClickSettingLink((settingName) => this.Gc(settingName)));
    this.B(this.sb.onDidFocusSetting((element) => {
      this.rb.setFocus([element]);
      this.Rb = 3;
      this.Nb.set(false);
    }));
    this.B(this.sb.onDidChangeSettingHeight((params) => {
      const { element, height } = params;
      try {
        this.rb.updateElementHeight(element, height);
      } catch (e) {
      }
    }));
    this.B(this.sb.onApplyFilter((filter) => this.Lc(filter)));
    this.B(this.sb.onDidClickOverrideElement((element) => {
      this.Mc();
      if (element.language) {
        this.Lc(`@${$AZb}${element.language}`);
      }
      if (element.scope === "workspace") {
        this.ob.updateTarget(
          5
          /* ConfigurationTarget.WORKSPACE */
        );
      } else if (element.scope === "user") {
        this.ob.updateTarget(
          3
          /* ConfigurationTarget.USER_LOCAL */
        );
      } else if (element.scope === "remote") {
        this.ob.updateTarget(
          4
          /* ConfigurationTarget.USER_REMOTE */
        );
      }
      this.Lc(`@${$zZb}${element.settingKey}`);
    }));
    this.rb = this.B(this.fc.createInstance($M1b, container2, this.Hb, this.sb.allRenderers));
    this.B(this.rb.onDidScroll(() => {
      if (this.rb.scrollTop === this.Xb) {
        return;
      }
      this.Xb = this.rb.scrollTop;
      setTimeout(() => {
        this.Pc();
      }, 0);
    }));
    this.B(this.rb.onDidFocus(() => {
      const classList = container2.ownerDocument.activeElement?.classList;
      if (classList && classList.contains("monaco-list") && classList.contains("settings-editor-tree")) {
        this.Rb = 2;
        this.Nb.set(true);
        this.Wb ??= this.rb.firstVisibleElement ?? null;
        if (this.Wb) {
          this.Wb.tabbable = true;
        }
      }
    }));
    this.B(this.rb.onDidBlur(() => {
      this.Nb.set(false);
      this.Wb = null;
    }));
    this.B(this.rb.onDidChangeFocus((e) => {
      const element = e.elements[0];
      if (this.Wb === element) {
        return;
      }
      if (this.Wb) {
        this.Wb.tabbable = false;
      }
      this.Wb = element;
      if (this.Wb) {
        this.Wb.tabbable = true;
      }
      this.rb.setSelection(element ? [element] : []);
    }));
  }
  Oc(key2, value, type, manualReset, scope) {
    const parsedQuery = $s1b(this.lb.getValue());
    const languageFilter = parsedQuery.languageFilter;
    if (manualReset || this.Gb && this.Gb.key !== key2) {
      this.Rc(key2, value, manualReset, languageFilter, scope);
    }
    this.Gb = { key: key2, value, languageFilter };
    if ($T1b_1.fb(type)) {
      this.Eb.trigger(() => this.Rc(key2, value, manualReset, languageFilter, scope));
    } else {
      this.Fb.trigger(() => this.Rc(key2, value, manualReset, languageFilter, scope));
    }
  }
  Pc() {
    this.sb.cancelSuggesters();
    if (this.vc) {
      return;
    }
    if (!this.tb) {
      return;
    }
    const elementToSync = this.rb.firstVisibleElement;
    const element = elementToSync instanceof $m1b ? elementToSync.parent : elementToSync instanceof $k1b ? elementToSync : null;
    let nodeExists = true;
    try {
      this.yb.getNode(element);
    } catch (e) {
      nodeExists = false;
    }
    if (!nodeExists) {
      return;
    }
    if (element && this.yb.getSelection()[0] !== element) {
      const ancestors = this.Qc(element);
      ancestors.forEach((e) => this.yb.expand(e));
      this.yb.reveal(element);
      const elementTop = this.yb.getRelativeTop(element);
      if (typeof elementTop !== "number") {
        return;
      }
      this.yb.collapseAll();
      ancestors.forEach((e) => this.yb.expand(e));
      if (elementTop < 0 || elementTop > 1) {
        this.yb.reveal(element);
      } else {
        this.yb.reveal(element, elementTop);
      }
      this.yb.expand(element);
      this.yb.setSelection([element]);
      const fakeKeyboardEvent = new KeyboardEvent("keydown");
      fakeKeyboardEvent.fromScroll = true;
      this.yb.setFocus([element], fakeKeyboardEvent);
    }
  }
  Qc(element) {
    const ancestors = [];
    while (element.parent) {
      if (element.parent.id !== "root") {
        ancestors.push(element.parent);
      }
      element = element.parent;
    }
    return ancestors.reverse();
  }
  Rc(key2, value, manualReset, languageFilter, scope) {
    const settingsTarget = this.ob.settingsTarget;
    const resource = URI.isUri(settingsTarget) ? settingsTarget : void 0;
    const configurationTarget = (resource ? 6 : settingsTarget) ?? 3;
    const overrides = { resource, overrideIdentifiers: languageFilter ? [languageFilter] : void 0 };
    const configurationTargetIsWorkspace = configurationTarget === 5 || configurationTarget === 6;
    const userPassedInManualReset = configurationTargetIsWorkspace || !!languageFilter;
    const isManualReset = userPassedInManualReset ? manualReset : value === void 0;
    const inspected = this.dc.inspect(key2, overrides);
    if (!userPassedInManualReset && inspected.defaultValue === value) {
      value = void 0;
    }
    return this.dc.updateValue(key2, value, overrides, configurationTarget, { handleDirtyFile: "save" }).then(() => {
      const query = this.lb.getValue();
      if (query.includes(`@${$wZb}`)) {
        this.cd();
      }
      this.Zc(key2, isManualReset);
      const reportModifiedProps = {
        key: key2,
        query,
        searchResults: this.vc?.getUniqueResults() ?? null,
        rawResults: this.vc?.getRawResults() ?? null,
        showConfiguredOnly: !!this.Hb.tagFilters && this.Hb.tagFilters.has($wZb),
        isReset: typeof value === "undefined",
        settingsTarget: this.ob.settingsTarget
      };
      this.Gb = null;
      return this.Sc(reportModifiedProps);
    });
  }
  Sc(props) {
    let groupId = void 0;
    let nlpIndex = void 0;
    let displayIndex = void 0;
    if (props.searchResults) {
      displayIndex = props.searchResults.filterMatches.findIndex((m) => m.setting.key === props.key);
      if (this.vc) {
        const rawResults = this.vc.getRawResults();
        if (rawResults[
          0
          /* SearchResultIdx.Local */
        ] && displayIndex >= 0) {
          const settingInLocalResults = rawResults[
            0
            /* SearchResultIdx.Local */
          ].filterMatches.some((m) => m.setting.key === props.key);
          groupId = settingInLocalResults ? "local" : "remote";
        }
        if (rawResults[
          1
          /* SearchResultIdx.Remote */
        ]) {
          const _nlpIndex = rawResults[
            1
            /* SearchResultIdx.Remote */
          ].filterMatches.findIndex((m) => m.setting.key === props.key);
          nlpIndex = _nlpIndex >= 0 ? _nlpIndex : void 0;
        }
      }
    }
    const reportedTarget = props.settingsTarget === 3 ? "user" : props.settingsTarget === 4 ? "user_remote" : props.settingsTarget === 5 ? "workspace" : "folder";
    const data = {
      key: props.key,
      groupId,
      nlpIndex,
      displayIndex,
      showConfiguredOnly: props.showConfiguredOnly,
      isReset: props.isReset,
      target: reportedTarget
    };
    this.Q.publicLog2("settingsEditor.settingModified", data);
  }
  Tc(element, key2 = "") {
    if (key2 && this.Qb.has(key2)) {
      return;
    }
    if (!key2) {
      $Xc(this.Qb.values());
      this.Qb.clear();
    }
    const scheduledRefreshTracker = $_j(element);
    this.Qb.set(key2, scheduledRefreshTracker);
    scheduledRefreshTracker.onDidBlur(() => {
      scheduledRefreshTracker.dispose();
      this.Qb.delete(key2);
      this.Wc(/* @__PURE__ */ new Set([key2]));
    });
  }
  Uc(resolvedSettingsRoot) {
    const index = /* @__PURE__ */ new Map();
    function indexSettings(resolvedSettingsRoot2, counter = 0) {
      if (resolvedSettingsRoot2.settings) {
        for (const setting of resolvedSettingsRoot2.settings) {
          if (!index.has(setting.key)) {
            index.set(setting.key, counter++);
          }
        }
      }
      if (resolvedSettingsRoot2.children) {
        for (const child of resolvedSettingsRoot2.children) {
          counter = indexSettings(child, counter);
        }
      }
      return counter;
    }
    indexSettings(resolvedSettingsRoot);
    return index;
  }
  Vc(resolvedSettingsRoot) {
    this.ub.update(resolvedSettingsRoot);
    this.tb.settingsTreeRoot = this.ub.root;
    this.Lb = this.Uc(resolvedSettingsRoot);
  }
  async Wc(keys, forceRefresh = false, schemaChange = false) {
    if (keys && this.ub) {
      return this.Xc(keys);
    }
    if (!this.gb) {
      return;
    }
    const groups = this.gb.settingsGroups.slice(1);
    const coreSettings = groups.filter((g) => !g.extensionInfo);
    const settingsResult = $C1b($f1b, coreSettings, this.hc);
    const resolvedSettingsRoot = settingsResult.tree;
    if (settingsResult.leftoverSettings.size && !this.Sb) {
      const settingKeyList = [];
      settingsResult.leftoverSettings.forEach((s) => {
        settingKeyList.push(s.key);
      });
      this.hc.warn(`SettingsEditor2: Settings not included in settingsLayout.ts: ${settingKeyList.join(", ")}`);
      this.Sb = true;
    }
    const additionalGroups = [];
    let setAdditionalGroups = false;
    const toggleData = await $JZb(this.rc, this.qc);
    if (toggleData && groups.filter((g) => g.extensionInfo).length) {
      for (const key2 in toggleData.settingsEditorRecommendedExtensions) {
        const extension = toggleData.recommendedExtensionsGalleryInfo[key2];
        if (!extension) {
          continue;
        }
        const extensionId = extension.identifier.id;
        await this.yc();
        const extensionInstalled = this.Zb.includes(extensionId);
        const matchingGroupIndex = groups.findIndex((g) => g.extensionInfo && g.extensionInfo.id.toLowerCase() === extensionId.toLowerCase() && g.sections.length === 1 && g.sections[0].settings.length === 1 && g.sections[0].settings[0].displayExtensionId);
        if (extensionInstalled || this.$b.includes(extensionId)) {
          if (matchingGroupIndex !== -1) {
            groups.splice(matchingGroupIndex, 1);
            setAdditionalGroups = true;
          }
          continue;
        }
        if (matchingGroupIndex !== -1) {
          continue;
        }
        let manifest = null;
        try {
          manifest = await $Lh(this.rc.getManifest(extension, CancellationToken.None), $IZb) ?? null;
        } catch (e) {
          continue;
        }
        if (manifest === null) {
          continue;
        }
        const contributesConfiguration = manifest?.contributes?.configuration;
        let groupTitle;
        if (!Array.isArray(contributesConfiguration)) {
          groupTitle = contributesConfiguration?.title;
        } else if (contributesConfiguration.length === 1) {
          groupTitle = contributesConfiguration[0].title;
        }
        const recommendationInfo = toggleData.settingsEditorRecommendedExtensions[key2];
        const extensionName = extension.displayName ?? extension.name ?? extensionId;
        const settingKey = `${key2}.manageExtension`;
        const setting = {
          range: $JK,
          key: settingKey,
          keyRange: $JK,
          value: null,
          valueRange: $JK,
          description: [recommendationInfo.onSettingsEditorOpen?.descriptionOverride ?? extension.description],
          descriptionIsMarkdown: false,
          descriptionRanges: [],
          scope: 3,
          type: "null",
          displayExtensionId: extensionId,
          extensionGroupTitle: groupTitle ?? extensionName,
          categoryLabel: "Extensions",
          title: extensionName
        };
        const additionalGroup = {
          sections: [{
            settings: [setting]
          }],
          id: extensionId,
          title: setting.extensionGroupTitle,
          titleRange: $JK,
          range: $JK,
          extensionInfo: {
            id: extensionId,
            displayName: extension.displayName
          }
        };
        groups.push(additionalGroup);
        additionalGroups.push(additionalGroup);
        setAdditionalGroups = true;
      }
    }
    resolvedSettingsRoot.children.push(await $E1b(this.nc, groups.filter((g) => g.extensionInfo)));
    const commonlyUsedDataToUse = $e1b(toggleData);
    const commonlyUsed = $C1b(commonlyUsedDataToUse, groups, this.hc);
    resolvedSettingsRoot.children.unshift(commonlyUsed.tree);
    if (toggleData && setAdditionalGroups) {
      this.gb.setAdditionalGroups(additionalGroups);
    }
    if (!this.mc.isWorkspaceTrusted() && (this.Hb.settingsTarget instanceof URI || this.Hb.settingsTarget === 5)) {
      const configuredUntrustedWorkspaceSettings = $D1b(groups, this.Hb.settingsTarget, this.Hb.languageFilter, this.dc);
      if (configuredUntrustedWorkspaceSettings.length) {
        resolvedSettingsRoot.children.unshift({
          id: "workspaceTrust",
          label: localize(8864, null),
          settings: configuredUntrustedWorkspaceSettings
        });
      }
    }
    this.vc?.updateChildren();
    if (this.ub) {
      this.Vc(resolvedSettingsRoot);
      if (schemaChange && !!this.vc) {
        return await this.ed();
      }
      this.cd();
      this.Zc(void 0, forceRefresh);
    } else {
      this.ub = this.fc.createInstance($n1b, this.Hb, this.mc.isWorkspaceTrusted());
      this.Vc(resolvedSettingsRoot);
      const cachedState = !this.Hb.query ? this.zc() : void 0;
      if (cachedState?.searchQuery || this.lb.getValue()) {
        await this.ed();
      } else {
        this.cd();
        this.bd();
        this.yb.collapseAll();
      }
    }
  }
  Xc(keys) {
    if (keys.size) {
      if (this.vc) {
        keys.forEach((key2) => this.vc.updateElementsByName(key2));
      }
      if (this.ub) {
        keys.forEach((key2) => this.ub.updateElementsByName(key2));
      }
      keys.forEach((key2) => this.Zc(key2));
    } else {
      this.Zc();
    }
  }
  Yc() {
    const element = this.rb.getHTMLElement();
    const activeElement = element.ownerDocument.activeElement;
    return activeElement && $Nj(element) ? activeElement : null;
  }
  Zc(key2, force = false) {
    if (!force && key2 && this.Qb.has(key2)) {
      this.dd(key2);
      return;
    }
    if (this.$c()) {
      const element = this.window.document.querySelector(".context-view");
      if (element) {
        this.Tc(element, key2);
      }
      return;
    }
    const activeElement = this.Yc();
    const focusedSetting = activeElement && this.sb.getSettingDOMElementForDOMElement(activeElement);
    if (focusedSetting && !force) {
      if (key2) {
        const focusedKey = focusedSetting.getAttribute($G1b.SETTING_KEY_ATTR);
        if (focusedKey === key2 && // update `list`s live, as they have a separate "submit edit" step built in before this
        (focusedSetting.parentElement && !focusedSetting.parentElement.classList.contains("setting-item-list"))) {
          this.dd(key2);
          this.Tc(focusedSetting, key2);
          return;
        }
      } else {
        this.Tc(focusedSetting);
        return;
      }
    }
    this.qd();
    if (key2) {
      const elements = this.uc.getElementsByName(key2);
      if (elements && elements.length) {
        if (elements.length >= 2) {
          console.warn("More than one setting with key " + key2 + " found");
        }
        this.ad(elements[0]);
      } else {
        return;
      }
    } else {
      this.bd();
    }
    return;
  }
  $c() {
    return !!$Gj(this.ib.ownerDocument.activeElement, "context-view");
  }
  ad(element) {
    if (this.isVisible()) {
      this.rb.rerender(element);
    }
  }
  bd() {
    if (this.isVisible()) {
      this.rb.setChildren(null, $S1b(this.uc.root));
    }
  }
  cd() {
    if (this.isVisible()) {
      this.tb.update();
      this.yb.setChildren(null, $P1b(this.tb, this.yb));
    }
  }
  dd(key2) {
    const dataElements = this.uc.getElementsByName(key2);
    const isModified = dataElements && dataElements[0] && dataElements[0].isConfigured;
    const elements = this.sb.getDOMElementsForSettingKey(this.rb.getHTMLElement(), key2);
    if (elements && elements[0]) {
      elements[0].classList.toggle("is-configured", !!isModified);
    }
  }
  async ed() {
    if (!this.uc) {
      return;
    }
    const query = this.lb.getValue().trim();
    this.Hb.query = query;
    this.zb.cancel();
    await this.hd(query.replace(/\u203A/g, " "));
    if (query && this.vc) {
      this.zb.trigger(() => this.kd(this.vc));
    }
  }
  fd(query) {
    const match = query.match(/"([a-zA-Z.]+)": /);
    return match && match[1];
  }
  /**
   * Toggles the visibility of the Settings editor table of contents during a search
   * depending on the behavior.
   */
  gd() {
    const tocBehavior = this.dc.getValue(SEARCH_TOC_BEHAVIOR_KEY);
    const hideToc = tocBehavior === "hide";
    if (hideToc) {
      this.pb.setViewVisible(0, false);
      this.pb.style({
        separatorBorder: $Vn.transparent
      });
    } else {
      this.pb.setViewVisible(0, true);
      this.pb.style({
        separatorBorder: this.h.getColor($UZb)
      });
    }
  }
  async hd(query) {
    const progressRunner = this.sc.show(true);
    this.Hb.tagFilters = /* @__PURE__ */ new Set();
    this.Hb.extensionFilters = /* @__PURE__ */ new Set();
    this.Hb.featureFilters = /* @__PURE__ */ new Set();
    this.Hb.idFilters = /* @__PURE__ */ new Set();
    this.Hb.languageFilter = void 0;
    if (query) {
      const parsedQuery = $s1b(query);
      query = parsedQuery.query;
      parsedQuery.tags.forEach((tag2) => this.Hb.tagFilters.add(tag2));
      parsedQuery.extensionFilters.forEach((extensionId) => this.Hb.extensionFilters.add(extensionId));
      parsedQuery.featureFilters.forEach((feature) => this.Hb.featureFilters.add(feature));
      parsedQuery.idFilters.forEach((id2) => this.Hb.idFilters.add(id2));
      this.Hb.languageFilter = parsedQuery.languageFilter;
    }
    this.ob.updateLanguageFilterIndicators(this.Hb.languageFilter);
    if (query && query !== "@") {
      query = this.fd(query) || query;
      await this.ld(query);
      this.gd();
    } else {
      if (this.Hb.tagFilters.size || this.Hb.extensionFilters.size || this.Hb.featureFilters.size || this.Hb.idFilters.size || this.Hb.languageFilter) {
        this.vc = this.jd();
      } else {
        this.vc = null;
      }
      this.Ab.cancel();
      if (this.Bb) {
        this.Bb.cancel();
        this.Bb.dispose();
        this.Bb = null;
      }
      this.yb.setFocus([]);
      this.Hb.filterToCategory = void 0;
      this.tb.currentSearchModel = this.vc;
      if (this.vc) {
        this.yb.setSelection([]);
        this.yb.expandAll();
        this.cd();
        this.qd();
        this.bd();
        this.gd();
      } else if (!this.Tb) {
        this.yb.collapseAll();
        this.cd();
        this.qd();
        this.bd();
        this.pb.setViewVisible(0, true);
      }
    }
    progressRunner.done();
  }
  /**
   * Return a fake SearchResultModel which can hold a flat list of all settings, to be filtered (@modified etc)
   */
  jd() {
    const filterModel = this.fc.createInstance($r1b, this.Hb, this.Lb, this.mc.isWorkspaceTrusted());
    const fullResult = {
      filterMatches: []
    };
    for (const g of this.gb.settingsGroups.slice(1)) {
      for (const sect of g.sections) {
        for (const setting of sect.settings) {
          fullResult.filterMatches.push({ setting, matches: [], matchType: SettingMatchType.None, score: 0 });
        }
      }
    }
    filterModel.setResult(0, fullResult);
    return filterModel;
  }
  kd(searchResultModel) {
    if (!searchResultModel) {
      return;
    }
    const counts = {};
    const rawResults = searchResultModel.getRawResults();
    const filterResult = rawResults[
      0
      /* SearchResultIdx.Local */
    ];
    if (filterResult) {
      counts["filterResult"] = filterResult.filterMatches.length;
    }
    const nlpResult = rawResults[
      1
      /* SearchResultIdx.Remote */
    ];
    if (nlpResult) {
      counts["nlpResult"] = nlpResult.filterMatches.length;
    }
    const uniqueResults = searchResultModel.getUniqueResults();
    const data = {
      "counts.nlpResult": counts["nlpResult"],
      "counts.filterResult": counts["filterResult"],
      "counts.uniqueResultsCount": uniqueResults?.filterMatches.length
    };
    this.Q.publicLog2("settingsEditor.filter", data);
  }
  async ld(query) {
    if (this.Bb) {
      this.Bb.cancel();
      this.Bb = null;
    }
    const searchInProgress = this.Bb = new $ad();
    return this.Ab.trigger(async () => {
      if (!searchInProgress.token.isCancellationRequested) {
        const localResults = await this.nd(query, searchInProgress.token);
        if (localResults && !localResults.exactMatch && !searchInProgress.token.isCancellationRequested) {
          await this.od(query, searchInProgress.token);
        }
        this.md();
      }
    });
  }
  md() {
    this.tb.currentSearchModel = this.vc;
    this.tb.update();
    this.yb.setFocus([]);
    this.Hb.filterToCategory = void 0;
    this.yb.expandAll();
    this.rb.scrollTop = 0;
    this.cd();
    this.Zc(void 0, true);
  }
  nd(query, token) {
    const localSearchProvider = this.gc.getLocalSearchProvider(query);
    return this.pd(query, 0, localSearchProvider, token);
  }
  od(query, token) {
    const remoteSearchProvider = this.gc.getRemoteSearchProvider(query);
    return this.pd(query, 1, remoteSearchProvider, token);
  }
  async pd(query, type, searchProvider, token) {
    const result = await this.rd(query, this.gb, searchProvider, token);
    if (token?.isCancellationRequested) {
      return null;
    }
    this.vc ??= this.fc.createInstance($r1b, this.Hb, this.Lb, this.mc.isWorkspaceTrusted());
    this.vc.setResult(type, result);
    return result;
  }
  qd() {
    if (!this.uc) {
      return;
    }
    this.wb.style.display = this.Hb.tagFilters && this.Hb.tagFilters.size > 0 ? "initial" : "none";
    if (!this.vc) {
      if (this.mb.style.display !== "none") {
        this.Jb = null;
        this.Cc();
        this.mb.style.display = "none";
        this.mb.innerText = "";
        this.layout(this.Yb);
      }
      this.ib.classList.remove("no-results");
      this.pb.el.style.visibility = "visible";
      return;
    } else {
      const count = this.vc.getUniqueResultsCount();
      let resultString;
      switch (count) {
        case 0:
          resultString = localize(8865, null);
          break;
        case 1:
          resultString = localize(8866, null);
          break;
        default:
          resultString = localize(8867, null, count);
      }
      this.Jb = resultString;
      this.Cc();
      this.mb.innerText = resultString;
      $_Z(resultString);
      if (this.mb.style.display !== "block") {
        this.mb.style.display = "block";
        this.layout(this.Yb);
      }
      this.ib.classList.toggle("no-results", count === 0);
      this.pb.el.style.visibility = count === 0 ? "hidden" : "visible";
    }
  }
  rd(filter, model, provider, token) {
    const searchP = provider ? provider.searchModel(model, token) : Promise.resolve(null);
    return searchP.then(void 0, (err) => {
      if ($kb(err)) {
        return Promise.reject(err);
      } else {
        return null;
      }
    });
  }
  sd(dimension) {
    const listHeight = dimension.height - (72 + 11 + 14);
    this.pb.el.style.height = `${listHeight}px`;
    this.pb.layout(this.kb.clientWidth, listHeight);
    const tocBehavior = this.dc.getValue(SEARCH_TOC_BEHAVIOR_KEY);
    const hideTocForSearch = tocBehavior === "hide" && this.vc;
    if (!hideTocForSearch) {
      const firstViewWasVisible = this.pb.isViewVisible(0);
      const firstViewVisible = this.kb.clientWidth >= $T1b_1.db;
      this.pb.setViewVisible(0, firstViewVisible);
      if (!firstViewWasVisible && firstViewVisible && this.kb.clientWidth >= $T1b_1.cb + $T1b_1.u) {
        this.pb.resizeView(0, $T1b_1.u);
      }
      this.pb.style({
        separatorBorder: firstViewVisible ? this.h.getColor($UZb) : $Vn.transparent
      });
    }
  }
  I() {
    if (this.isVisible()) {
      const searchQuery = this.lb.getValue().trim();
      const target = this.ob.settingsTarget;
      if (this.input) {
        this.Ub.saveEditorState(this.group, this.input, { searchQuery, target });
      }
    } else if (this.input) {
      this.Ub.clearEditorState(this.input, this.group);
    }
    super.I();
  }
};
$T1b = $T1b_1 = __decorate([
  __param(1, $zv),
  __param(2, $EK),
  __param(3, $zG),
  __param(4, $gs),
  __param(5, $TK),
  __param(6, $Pk),
  __param(7, $2Yb),
  __param(8, $wn),
  __param(9, $on),
  __param(10, $jv),
  __param(11, $iJ),
  __param(12, $oXb),
  __param(13, $6Bb),
  __param(14, $4M),
  __param(15, $wN),
  __param(16, $1E),
  __param(17, $sA),
  __param(18, $Vu),
  __param(19, $pA),
  __param(20, $ZJ),
  __param(21, $gT)
], $T1b);
var SyncControls = class SyncControls2 extends $3c {
  constructor(window3, container2, f, h3, j, telemetryService) {
    super();
    this.f = f;
    this.h = h3;
    this.j = j;
    this.c = this.B(new $ze());
    this.onDidChangeLastSyncedLabel = this.c.event;
    const headerRightControlsContainer = $bk(container2, $120(".settings-right-controls"));
    const turnOnSyncButtonContainer = $bk(headerRightControlsContainer, $120(".turn-on-sync"));
    this.b = this.B(new $k2(turnOnSyncButtonContainer, { title: true, ...$q$ }));
    this.a = $bk(headerRightControlsContainer, $120(".last-synced-label"));
    $ik(this.a);
    this.b.enabled = true;
    this.b.label = localize(8868, null);
    $ik(this.b.element);
    this.B(this.b.onDidClick(async () => {
      telemetryService.publicLog2("sync/turnOnSyncFromSettings");
      await this.f.executeCommand("workbench.userDataSync.actions.turnOn");
    }));
    this.n();
    this.B(this.h.onDidChangeLastSyncTime(() => {
      this.n();
    }));
    const updateLastSyncedTimer = this.B(new $lj());
    updateLastSyncedTimer.cancelAndSet(() => this.n(), 60 * 1e3, window3);
    this.r();
    this.B(this.h.onDidChangeStatus(() => {
      this.r();
    }));
    this.B(this.j.onDidChangeEnablement(() => {
      this.r();
    }));
  }
  n() {
    const last = this.h.lastSyncTime;
    let label3;
    if (typeof last === "number") {
      const d = $Qu(last, true, void 0, true);
      label3 = localize(8869, null, d);
    } else {
      label3 = "";
    }
    this.a.textContent = label3;
    this.c.fire(label3);
  }
  r() {
    if (this.h.status === "uninitialized") {
      return;
    }
    if (this.j.isEnabled() || this.h.status !== "idle") {
      $hk(this.a);
      $ik(this.b.element);
    } else {
      $ik(this.a);
      $hk(this.b.element);
    }
  }
};
SyncControls = __decorate([
  __param(2, $sn),
  __param(3, $7Bb),
  __param(4, $6Bb),
  __param(5, $zv)
], SyncControls);

// out-build/vs/workbench/contrib/preferences/common/settingsFilesystemProvider.js
var $U1b_1;
var schemaRegistry6 = $Wn.as($Xn.JSONContribution);
var $U1b = class $U1b2 extends $3c {
  static {
    $U1b_1 = this;
  }
  static {
    this.SCHEMA = Schemas.vscode;
  }
  constructor(b, c) {
    super();
    this.b = b;
    this.c = c;
    this.a = this.B(new $ze());
    this.onDidChangeFile = this.a.event;
    this.capabilities = 2048 + 2;
    this.onDidChangeCapabilities = Event2.None;
    this.B(schemaRegistry6.onDidChangeSchema((schemaUri) => {
      this.a.fire([{
        resource: URI.parse(schemaUri),
        type: 0
        /* FileChangeType.UPDATED */
      }]);
    }));
    this.B(b.onDidDefaultSettingsContentChanged((uri) => {
      this.a.fire([{
        resource: uri,
        type: 0
        /* FileChangeType.UPDATED */
      }]);
    }));
  }
  async readFile(uri) {
    if (uri.scheme !== $U1b_1.SCHEMA) {
      throw new $sb();
    }
    let content;
    if (uri.authority === "schemas") {
      content = this.f(uri);
    } else if (uri.authority === "defaultsettings") {
      content = this.b.getDefaultSettingsContent(uri);
    }
    if (content) {
      return $Ci.fromString(content).buffer;
    }
    throw FileSystemProviderErrorCode.FileNotFound;
  }
  async stat(uri) {
    if (schemaRegistry6.hasSchemaContent(uri.toString()) || this.b.hasDefaultSettingsContent(uri)) {
      const currentTime = Date.now();
      return {
        type: FileType.File,
        permissions: FilePermission.Readonly,
        mtime: currentTime,
        ctime: currentTime,
        size: 0
      };
    }
    throw FileSystemProviderErrorCode.FileNotFound;
  }
  watch(resource, opts) {
    return $3c.None;
  }
  async mkdir(resource) {
  }
  async readdir(resource) {
    return [];
  }
  async rename(from, to, opts) {
  }
  async delete(resource, opts) {
  }
  async writeFile() {
    throw new $sb();
  }
  f(uri) {
    const startTime = Date.now();
    const content = schemaRegistry6.getSchemaContent(uri.toString()) ?? "{}";
    const logLevel = this.c.getLevel();
    if (logLevel === LogLevel.Debug || logLevel === LogLevel.Trace) {
      const endTime = Date.now();
      const uncompressed = JSON.stringify(schemaRegistry6.getSchemaContributions().schemas[uri.toString()]);
      this.c.debug(`${uri.toString()}: ${uncompressed.length} -> ${content.length} (${Math.round((uncompressed.length - content.length) / uncompressed.length * 100)}%) Took ${endTime - startTime}ms`);
    }
    return content;
  }
};
$U1b = $U1b_1 = __decorate([
  __param(0, $TK),
  __param(1, $wn)
], $U1b);

// out-build/vs/workbench/contrib/preferences/common/preferencesContribution.js
var $V1b = class $V1b2 extends $3c {
  static {
    this.ID = "workbench.contrib.preferences";
  }
  constructor(fileService, b, c, f, g, h3, j, m) {
    super();
    this.b = b;
    this.c = c;
    this.f = f;
    this.g = g;
    this.h = h3;
    this.j = j;
    this.m = m;
    this.B(this.h.onDidChangeConfiguration((e) => {
      if (e.affectsConfiguration($XK) || e.affectsConfiguration($WK)) {
        this.n();
      }
    }));
    this.n();
    const fileSystemProvider = this.B(this.b.createInstance($U1b));
    this.B(fileService.registerProvider($U1b.SCHEMA, fileSystemProvider));
  }
  n() {
    $Xc(this.a);
    if (!!this.h.getValue($XK) || !!this.h.getValue($WK)) {
      this.a = this.j.registerEditor("**/settings.json", {
        id: $1I.ID,
        label: localize(9046, null),
        priority: RegisteredEditorPriority.builtin
      }, {}, {
        createEditorInput: ({ resource, options: options3 }) => {
          if ($oh(resource, this.f.currentProfile.settingsResource)) {
            return { editor: this.c.createSplitJsonEditorInput(3, resource), options: options3 };
          }
          const state = this.g.getWorkbenchState();
          if (state === 2) {
            const folders = this.g.getWorkspace().folders;
            if ($oh(resource, folders[0].toResource($VK))) {
              return { editor: this.c.createSplitJsonEditorInput(5, resource), options: options3 };
            }
          } else if (state === 3) {
            const folders = this.g.getWorkspace().folders;
            for (const folder of folders) {
              if ($oh(resource, folder.toResource($VK))) {
                return { editor: this.c.createSplitJsonEditorInput(6, resource), options: options3 };
              }
            }
          }
          return { editor: this.m.createTextEditor({ resource }), options: options3 };
        }
      });
    }
  }
  dispose() {
    $Xc(this.a);
    super.dispose();
  }
};
$V1b = __decorate([
  __param(0, $km),
  __param(1, $Pk),
  __param(2, $TK),
  __param(3, $gT),
  __param(4, $Zk),
  __param(5, $kl),
  __param(6, $4L),
  __param(7, $YUb)
], $V1b);
var registry3 = $Wn.as($Ht.Configuration);
registry3.registerConfiguration({
  ...$UL,
  "properties": {
    "workbench.settings.enableNaturalLanguageSearch": {
      "type": "boolean",
      "description": localize(9047, null),
      "default": true,
      "scope": 3,
      "tags": ["usesOnlineServices"]
    },
    "workbench.settings.settingsSearchTocBehavior": {
      "type": "string",
      "enum": ["hide", "filter"],
      "enumDescriptions": [
        localize(9048, null),
        localize(9049, null)
      ],
      "description": localize(9050, null),
      "default": "filter",
      "scope": 3
      /* ConfigurationScope.WINDOW */
    }
  }
});

// out-build/vs/workbench/contrib/preferences/browser/preferences.contribution.js
var SETTINGS_EDITOR_COMMAND_SEARCH = "settings.action.search";
var SETTINGS_EDITOR_COMMAND_FOCUS_FILE = "settings.action.focusSettingsFile";
var SETTINGS_EDITOR_COMMAND_FOCUS_SETTINGS_FROM_SEARCH = "settings.action.focusSettingsFromSearch";
var SETTINGS_EDITOR_COMMAND_FOCUS_SETTINGS_LIST = "settings.action.focusSettingsList";
var SETTINGS_EDITOR_COMMAND_FOCUS_TOC = "settings.action.focusTOC";
var SETTINGS_EDITOR_COMMAND_FOCUS_CONTROL = "settings.action.focusSettingControl";
var SETTINGS_EDITOR_COMMAND_FOCUS_UP = "settings.action.focusLevelUp";
var SETTINGS_EDITOR_COMMAND_SWITCH_TO_JSON = "settings.switchToJSON";
var SETTINGS_EDITOR_COMMAND_FILTER_ONLINE = "settings.filterByOnline";
var SETTINGS_EDITOR_COMMAND_FILTER_UNTRUSTED = "settings.filterUntrusted";
var SETTINGS_COMMAND_OPEN_SETTINGS = "workbench.action.openSettings";
var SETTINGS_COMMAND_FILTER_TELEMETRY = "settings.filterByTelemetry";
$Wn.as($ZK.EditorPane).registerEditorPane($7tb.create($T1b, $T1b.ID, localize(8770, null)), [
  new $Nk($FVb)
]);
$Wn.as($ZK.EditorPane).registerEditorPane($7tb.create($_Zb, $_Zb.ID, localize(8771, null)), [
  new $Nk($EVb)
]);
var KeybindingsEditorInputSerializer = class {
  canSerialize(editorInput) {
    return true;
  }
  serialize(editorInput) {
    return "";
  }
  deserialize(instantiationService) {
    return instantiationService.createInstance($EVb);
  }
};
var SettingsEditor2InputSerializer = class {
  canSerialize(editorInput) {
    return true;
  }
  serialize(input) {
    return "";
  }
  deserialize(instantiationService) {
    return instantiationService.createInstance($FVb);
  }
};
$Wn.as($ZK.EditorFactory).registerEditorSerializer($EVb.ID, KeybindingsEditorInputSerializer);
$Wn.as($ZK.EditorFactory).registerEditorSerializer($FVb.ID, SettingsEditor2InputSerializer);
var OPEN_USER_SETTINGS_UI_TITLE = localize2(8785, "Open Settings (UI)");
var OPEN_USER_SETTINGS_JSON_TITLE = localize2(8786, "Open User Settings (JSON)");
var OPEN_APPLICATION_SETTINGS_JSON_TITLE = localize2(8787, "Open Application Settings (JSON)");
var category = $qn.Preferences;
function sanitizeBoolean(arg) {
  return $Fg(arg) ? arg : void 0;
}
function sanitizeString(arg) {
  return $zg(arg) ? arg : void 0;
}
function sanitizeOpenSettingsArgs(args2) {
  if (!$Bg(args2)) {
    args2 = {};
  }
  let sanitizedObject = {
    focusSearch: sanitizeBoolean(args2?.focusSearch),
    openToSide: sanitizeBoolean(args2?.openToSide),
    query: sanitizeString(args2?.query)
  };
  if ($zg(args2?.revealSetting?.key)) {
    sanitizedObject = {
      ...sanitizedObject,
      revealSetting: {
        key: args2.revealSetting.key,
        edit: sanitizeBoolean(args2.revealSetting?.edit)
      }
    };
  }
  return sanitizedObject;
}
var PreferencesActionsContribution = class PreferencesActionsContribution2 extends $3c {
  static {
    this.ID = "workbench.contrib.preferencesActions";
  }
  constructor(a, b, c, f, g, h3, j) {
    super();
    this.a = a;
    this.b = b;
    this.c = c;
    this.f = f;
    this.g = g;
    this.h = h3;
    this.j = j;
    this.m();
    this.r();
    this.t();
    this.B(f.onDidChangeWorkbenchState(() => this.t()));
    this.B(f.onDidChangeWorkspaceFolders(() => this.u()));
  }
  m() {
    this.B($hJ(class extends $gJ {
      constructor() {
        super({
          id: SETTINGS_COMMAND_OPEN_SETTINGS,
          title: {
            ...localize2(8788, "Settings"),
            mnemonicTitle: localize(8772, null)
          },
          keybinding: {
            weight: 200,
            when: null,
            primary: 2048 | 87
          },
          menu: [{
            id: $bJ.GlobalActivity,
            group: "2_configuration",
            order: 2
          }, {
            id: $bJ.MenubarPreferencesMenu,
            group: "2_configuration",
            order: 2
          }]
        });
      }
      run(accessor, args2) {
        const opts = typeof args2 === "string" ? { query: args2 } : sanitizeOpenSettingsArgs(args2);
        return accessor.get($TK).openSettings(opts);
      }
    }));
    this.B($hJ(class extends $gJ {
      constructor() {
        super({
          id: "workbench.action.openSettings2",
          title: localize2(8789, "Open Settings (UI)"),
          category,
          f1: true
        });
      }
      run(accessor, args2) {
        args2 = sanitizeOpenSettingsArgs(args2);
        return accessor.get($TK).openSettings({ jsonEditor: false, ...args2 });
      }
    }));
    this.B($hJ(class extends $gJ {
      constructor() {
        super({
          id: "workbench.action.openSettingsJson",
          title: OPEN_USER_SETTINGS_JSON_TITLE,
          metadata: {
            description: localize2(8790, "Opens the JSON file containing the current user profile settings")
          },
          category,
          f1: true
        });
      }
      run(accessor, args2) {
        args2 = sanitizeOpenSettingsArgs(args2);
        return accessor.get($TK).openSettings({ jsonEditor: true, ...args2 });
      }
    }));
    const that = this;
    this.B($hJ(class extends $gJ {
      constructor() {
        super({
          id: "workbench.action.openApplicationSettingsJson",
          title: OPEN_APPLICATION_SETTINGS_JSON_TITLE,
          category,
          menu: {
            id: $bJ.CommandPalette,
            when: $7m.notEquals($tT.key, that.j.defaultProfile.id)
          }
        });
      }
      run(accessor, args2) {
        args2 = sanitizeOpenSettingsArgs(args2);
        return accessor.get($TK).openApplicationSettings({ jsonEditor: true, ...args2 });
      }
    }));
    this.B($hJ(class extends $gJ {
      constructor() {
        super({
          id: "workbench.action.openGlobalSettings",
          title: localize2(8791, "Open User Settings"),
          category,
          f1: true
        });
      }
      run(accessor, args2) {
        args2 = sanitizeOpenSettingsArgs(args2);
        return accessor.get($TK).openUserSettings(args2);
      }
    }));
    this.B($hJ(class extends $gJ {
      constructor() {
        super({
          id: "workbench.action.openRawDefaultSettings",
          title: localize2(8792, "Open Default Settings (JSON)"),
          category,
          f1: true
        });
      }
      run(accessor) {
        return accessor.get($TK).openRawDefaultSettings();
      }
    }));
    this.B($hJ(class extends $gJ {
      constructor() {
        super({
          id: $a1b.ID,
          title: $a1b.LABEL,
          category,
          f1: true
        });
      }
      run(accessor) {
        return accessor.get($Pk).createInstance($a1b, $a1b.ID, $a1b.LABEL.value).run();
      }
    }));
    this.B($hJ(class extends $gJ {
      constructor() {
        super({
          id: "workbench.action.openWorkspaceSettings",
          title: localize2(8793, "Open Workspace Settings"),
          category,
          menu: {
            id: $bJ.CommandPalette,
            when: $epb.notEqualsTo("empty")
          }
        });
      }
      run(accessor, args2) {
        args2 = typeof args2 === "string" ? { query: args2 } : sanitizeOpenSettingsArgs(args2);
        return accessor.get($TK).openWorkspaceSettings(args2);
      }
    }));
    this.B($hJ(class extends $gJ {
      constructor() {
        super({
          id: "workbench.action.openAccessibilitySettings",
          title: localize2(8794, "Open Accessibility Settings"),
          category,
          menu: {
            id: $bJ.CommandPalette,
            when: $epb.notEqualsTo("empty")
          }
        });
      }
      async run(accessor) {
        await accessor.get($TK).openSettings({ jsonEditor: false, query: "@tag:accessibility" });
      }
    }));
    this.B($hJ(class extends $gJ {
      constructor() {
        super({
          id: "workbench.action.openWorkspaceSettingsFile",
          title: localize2(8795, "Open Workspace Settings (JSON)"),
          category,
          menu: {
            id: $bJ.CommandPalette,
            when: $epb.notEqualsTo("empty")
          }
        });
      }
      run(accessor, args2) {
        args2 = sanitizeOpenSettingsArgs(args2);
        return accessor.get($TK).openWorkspaceSettings({ jsonEditor: true, ...args2 });
      }
    }));
    this.B($hJ(class extends $gJ {
      constructor() {
        super({
          id: "workbench.action.openFolderSettings",
          title: localize2(8796, "Open Folder Settings"),
          category,
          menu: {
            id: $bJ.CommandPalette,
            when: $epb.isEqualTo("workspace")
          }
        });
      }
      async run(accessor, args2) {
        const commandService = accessor.get($sn);
        const preferencesService = accessor.get($TK);
        const workspaceFolder = await commandService.executeCommand($Wyb);
        if (workspaceFolder) {
          args2 = sanitizeOpenSettingsArgs(args2);
          await preferencesService.openFolderSettings({ folderUri: workspaceFolder.uri, ...args2 });
        }
      }
    }));
    this.B($hJ(class extends $gJ {
      constructor() {
        super({
          id: "workbench.action.openFolderSettingsFile",
          title: localize2(8797, "Open Folder Settings (JSON)"),
          category,
          menu: {
            id: $bJ.CommandPalette,
            when: $epb.isEqualTo("workspace")
          }
        });
      }
      async run(accessor, args2) {
        const commandService = accessor.get($sn);
        const preferencesService = accessor.get($TK);
        const workspaceFolder = await commandService.executeCommand($Wyb);
        if (workspaceFolder) {
          args2 = sanitizeOpenSettingsArgs(args2);
          await preferencesService.openFolderSettings({ folderUri: workspaceFolder.uri, jsonEditor: true, ...args2 });
        }
      }
    }));
    this.B($hJ(class extends $gJ {
      constructor() {
        super({
          id: "_workbench.action.openFolderSettings",
          title: localize(8773, null),
          category,
          menu: {
            id: $bJ.ExplorerContext,
            group: "2_workspace",
            order: 20,
            when: $7m.and($_sb, $7sb)
          }
        });
      }
      async run(accessor, resource) {
        if (URI.isUri(resource)) {
          await accessor.get($TK).openFolderSettings({ folderUri: resource });
        } else {
          const commandService = accessor.get($sn);
          const preferencesService = accessor.get($TK);
          const workspaceFolder = await commandService.executeCommand($Wyb);
          if (workspaceFolder) {
            await preferencesService.openFolderSettings({ folderUri: workspaceFolder.uri });
          }
        }
      }
    }));
    this.B($hJ(class extends $gJ {
      constructor() {
        super({
          id: SETTINGS_EDITOR_COMMAND_FILTER_ONLINE,
          title: localize(8774, null),
          menu: {
            id: $bJ.MenubarPreferencesMenu,
            group: "3_settings",
            order: 1
          }
        });
      }
      run(accessor) {
        const editorPane = accessor.get($mJ).activeEditorPane;
        if (editorPane instanceof $T1b) {
          editorPane.focusSearch(`@tag:usesOnlineServices`);
        } else {
          accessor.get($TK).openSettings({ jsonEditor: false, query: "@tag:usesOnlineServices" });
        }
      }
    }));
    this.B($hJ(class extends $gJ {
      constructor() {
        super({
          id: SETTINGS_EDITOR_COMMAND_FILTER_UNTRUSTED,
          title: localize2(8798, "Show untrusted workspace settings")
        });
      }
      run(accessor) {
        accessor.get($TK).openWorkspaceSettings({ jsonEditor: false, query: `@tag:${$EZb}` });
      }
    }));
    this.B($hJ(class extends $gJ {
      constructor() {
        super({
          id: SETTINGS_COMMAND_FILTER_TELEMETRY,
          title: localize(8775, null)
        });
      }
      run(accessor) {
        const editorPane = accessor.get($mJ).activeEditorPane;
        if (editorPane instanceof $T1b) {
          editorPane.focusSearch(`@tag:telemetry`);
        } else {
          accessor.get($TK).openSettings({ jsonEditor: false, query: "@tag:telemetry" });
        }
      }
    }));
    this.n();
    this.h.whenInstalledExtensionsRegistered().then(() => {
      const remoteAuthority = this.a.remoteAuthority;
      const hostLabel = this.g.getHostLabel(Schemas.vscodeRemote, remoteAuthority) || remoteAuthority;
      this.B($hJ(class extends $gJ {
        constructor() {
          super({
            id: "workbench.action.openRemoteSettings",
            title: localize2(8799, "Open Remote Settings ({0})", hostLabel),
            category,
            menu: {
              id: $bJ.CommandPalette,
              when: $kpb.notEqualsTo("")
            }
          });
        }
        run(accessor, args2) {
          args2 = sanitizeOpenSettingsArgs(args2);
          return accessor.get($TK).openRemoteSettings(args2);
        }
      }));
      this.B($hJ(class extends $gJ {
        constructor() {
          super({
            id: "workbench.action.openRemoteSettingsFile",
            title: localize2(8800, "Open Remote Settings (JSON) ({0})", hostLabel),
            category,
            menu: {
              id: $bJ.CommandPalette,
              when: $kpb.notEqualsTo("")
            }
          });
        }
        run(accessor, args2) {
          args2 = sanitizeOpenSettingsArgs(args2);
          return accessor.get($TK).openRemoteSettings({ jsonEditor: true, ...args2 });
        }
      }));
    });
  }
  n() {
    function getPreferencesEditor(accessor) {
      const activeEditorPane = accessor.get($mJ).activeEditorPane;
      if (activeEditorPane instanceof $T1b) {
        return activeEditorPane;
      }
      return null;
    }
    function settingsEditorFocusSearch(accessor) {
      const preferencesEditor = getPreferencesEditor(accessor);
      preferencesEditor?.focusSearch();
    }
    this.B($hJ(class extends $gJ {
      constructor() {
        super({
          id: SETTINGS_EDITOR_COMMAND_SEARCH,
          precondition: $6Yb,
          keybinding: {
            primary: 2048 | 36,
            weight: 100,
            when: null
          },
          category,
          f1: true,
          title: localize2(8801, "Focus Settings Search")
        });
      }
      run(accessor) {
        settingsEditorFocusSearch(accessor);
      }
    }));
    this.B($hJ(class extends $gJ {
      constructor() {
        super({
          id: $3Yb,
          precondition: $6Yb,
          keybinding: {
            primary: 9,
            weight: 100,
            when: $8Yb
          },
          category,
          f1: true,
          title: localize2(8802, "Clear Settings Search Results")
        });
      }
      run(accessor) {
        const preferencesEditor = getPreferencesEditor(accessor);
        preferencesEditor?.clearSearchResults();
      }
    }));
    this.B($hJ(class extends $gJ {
      constructor() {
        super({
          id: SETTINGS_EDITOR_COMMAND_FOCUS_FILE,
          precondition: $7m.and($8Yb, $_bb.Visible.toNegated()),
          keybinding: {
            primary: 18,
            weight: 100,
            when: null
          },
          title: localize(8776, null)
        });
      }
      run(accessor, args2) {
        const preferencesEditor = getPreferencesEditor(accessor);
        preferencesEditor?.focusSettings();
      }
    }));
    this.B($hJ(class extends $gJ {
      constructor() {
        super({
          id: SETTINGS_EDITOR_COMMAND_FOCUS_SETTINGS_FROM_SEARCH,
          precondition: $7m.and($8Yb, $_bb.Visible.toNegated()),
          keybinding: {
            primary: 18,
            weight: 200,
            when: null
          },
          title: localize(8777, null)
        });
      }
      run(accessor, args2) {
        const preferencesEditor = getPreferencesEditor(accessor);
        preferencesEditor?.focusSettings();
      }
    }));
    this.B($hJ(class extends $gJ {
      constructor() {
        super({
          id: SETTINGS_EDITOR_COMMAND_FOCUS_SETTINGS_LIST,
          precondition: $7m.and($6Yb, $9Yb),
          keybinding: {
            primary: 3,
            weight: 200,
            when: null
          },
          title: localize(8778, null)
        });
      }
      run(accessor) {
        const preferencesEditor = getPreferencesEditor(accessor);
        if (preferencesEditor instanceof $T1b) {
          preferencesEditor.focusSettings();
        }
      }
    }));
    this.B($hJ(class extends $gJ {
      constructor() {
        super({
          id: SETTINGS_EDITOR_COMMAND_FOCUS_TOC,
          precondition: $6Yb,
          f1: true,
          keybinding: [
            {
              primary: 15,
              weight: 200,
              when: $0Yb
            }
          ],
          category,
          title: localize2(8803, "Focus Settings Table of Contents")
        });
      }
      run(accessor) {
        const preferencesEditor = getPreferencesEditor(accessor);
        if (!(preferencesEditor instanceof $T1b)) {
          return;
        }
        preferencesEditor.focusTOC();
      }
    }));
    this.B($hJ(class extends $gJ {
      constructor() {
        super({
          id: SETTINGS_EDITOR_COMMAND_FOCUS_CONTROL,
          precondition: $7m.and($6Yb, $0Yb),
          keybinding: {
            primary: 3,
            weight: 200
          },
          title: localize(8779, null)
        });
      }
      run(accessor) {
        const preferencesEditor = getPreferencesEditor(accessor);
        if (!(preferencesEditor instanceof $T1b)) {
          return;
        }
        const activeElement = preferencesEditor.getContainer()?.ownerDocument.activeElement;
        if (activeElement?.classList.contains("monaco-list")) {
          preferencesEditor.focusSettings(true);
        }
      }
    }));
    this.B($hJ(class extends $gJ {
      constructor() {
        super({
          id: $4Yb,
          precondition: $6Yb,
          keybinding: {
            primary: 1024 | 67,
            weight: 200,
            when: null
          },
          f1: true,
          category,
          title: localize2(8804, "Show Setting Context Menu")
        });
      }
      run(accessor) {
        const preferencesEditor = getPreferencesEditor(accessor);
        if (preferencesEditor instanceof $T1b) {
          preferencesEditor.showContextMenu();
        }
      }
    }));
    this.B($hJ(class extends $gJ {
      constructor() {
        super({
          id: SETTINGS_EDITOR_COMMAND_FOCUS_UP,
          precondition: $7m.and($6Yb, $8Yb.toNegated(), $7Yb.toNegated()),
          keybinding: {
            primary: 9,
            weight: 200,
            when: null
          },
          f1: true,
          category,
          title: localize2(8805, "Move Focus Up One Level")
        });
      }
      run(accessor) {
        const preferencesEditor = getPreferencesEditor(accessor);
        if (!(preferencesEditor instanceof $T1b)) {
          return;
        }
        if (preferencesEditor.currentFocusContext === 3) {
          preferencesEditor.focusSettings();
        } else if (preferencesEditor.currentFocusContext === 2) {
          preferencesEditor.focusTOC();
        } else if (preferencesEditor.currentFocusContext === 1) {
          preferencesEditor.focusSearch();
        }
      }
    }));
  }
  r() {
    const that = this;
    const category8 = localize2(8806, "Preferences");
    const id2 = "workbench.action.openGlobalKeybindings";
    this.B($hJ(class extends $gJ {
      constructor() {
        super({
          id: id2,
          title: localize2(8807, "Open Keyboard Shortcuts"),
          shortTitle: localize(8780, null),
          category: category8,
          icon: $TYb,
          keybinding: {
            when: null,
            weight: 200,
            primary: $$e(
              2048 | 41,
              2048 | 49
              /* KeyCode.KeyS */
            )
          },
          menu: [
            { id: $bJ.CommandPalette },
            {
              id: $bJ.EditorTitle,
              when: $lqb.Resource.isEqualTo(that.b.currentProfile.keybindingsResource.toString()),
              group: "navigation",
              order: 1
            },
            {
              id: $bJ.GlobalActivity,
              group: "2_configuration",
              order: 4
            }
          ]
        });
      }
      run(accessor, args2) {
        const query = typeof args2 === "string" ? args2 : void 0;
        return accessor.get($TK).openGlobalKeybindingSettings(false, { query });
      }
    }));
    this.B($dJ.appendMenuItem($bJ.MenubarPreferencesMenu, {
      command: {
        id: id2,
        title: localize(8781, null)
      },
      group: "2_configuration",
      order: 4
    }));
    this.B($hJ(class extends $gJ {
      constructor() {
        super({
          id: "workbench.action.openDefaultKeybindingsFile",
          title: localize2(8808, "Open Default Keyboard Shortcuts (JSON)"),
          category: category8,
          menu: { id: $bJ.CommandPalette }
        });
      }
      run(accessor) {
        return accessor.get($TK).openDefaultKeybindingsFile();
      }
    }));
    this.B($hJ(class extends $gJ {
      constructor() {
        super({
          id: "workbench.action.openGlobalKeybindingsFile",
          title: localize2(8809, "Open Keyboard Shortcuts (JSON)"),
          category: category8,
          icon: $TYb,
          menu: [
            { id: $bJ.CommandPalette },
            {
              id: $bJ.EditorTitle,
              when: $7m.and($$Yb),
              group: "navigation"
            }
          ]
        });
      }
      run(accessor) {
        return accessor.get($TK).openGlobalKeybindingSettings(true);
      }
    }));
    this.B($hJ(class extends $gJ {
      constructor() {
        super({
          id: $tZb,
          title: localize2(8810, "Show System Keybindings"),
          menu: [
            {
              id: $bJ.EditorTitle,
              when: $7m.and($$Yb),
              group: "1_keyboard_preferences_actions"
            }
          ]
        });
      }
      run(accessor) {
        const editorPane = accessor.get($mJ).activeEditorPane;
        if (editorPane instanceof $_Zb) {
          editorPane.search("@source:system");
        }
      }
    }));
    this.B($hJ(class extends $gJ {
      constructor() {
        super({
          id: $vZb,
          title: localize2(8811, "Show Extension Keybindings"),
          menu: [
            {
              id: $bJ.EditorTitle,
              when: $7m.and($$Yb),
              group: "1_keyboard_preferences_actions"
            }
          ]
        });
      }
      run(accessor) {
        const editorPane = accessor.get($mJ).activeEditorPane;
        if (editorPane instanceof $_Zb) {
          editorPane.search("@source:extension");
        }
      }
    }));
    this.B($hJ(class extends $gJ {
      constructor() {
        super({
          id: $uZb,
          title: localize2(8812, "Show User Keybindings"),
          menu: [
            {
              id: $bJ.EditorTitle,
              when: $7m.and($$Yb),
              group: "1_keyboard_preferences_actions"
            }
          ]
        });
      }
      run(accessor) {
        const editorPane = accessor.get($mJ).activeEditorPane;
        if (editorPane instanceof $_Zb) {
          editorPane.search("@source:user");
        }
      }
    }));
    this.B($hJ(class extends $gJ {
      constructor() {
        super({
          id: $dZb,
          title: localize(8782, null),
          keybinding: {
            weight: 200,
            when: $7m.and($$Yb, $_Yb),
            primary: 9
          }
        });
      }
      run(accessor) {
        const editorPane = accessor.get($mJ).activeEditorPane;
        if (editorPane instanceof $_Zb) {
          editorPane.clearSearchResults();
        }
      }
    }));
    this.B($hJ(class extends $gJ {
      constructor() {
        super({
          id: $eZb,
          title: localize(8783, null),
          category: category8,
          menu: [
            {
              id: $bJ.CommandPalette,
              when: $7m.and($$Yb)
            }
          ]
        });
      }
      run(accessor) {
        const editorPane = accessor.get($mJ).activeEditorPane;
        if (editorPane instanceof $_Zb) {
          editorPane.clearKeyboardShortcutSearchHistory();
        }
      }
    }));
    this.s();
  }
  s() {
    const that = this;
    $0I.registerCommandAndKeybindingRule({
      id: $hZb,
      weight: 200,
      when: $7m.and($$Yb, $aZb, $bZb.toNegated()),
      primary: 3,
      handler: (accessor, args2) => {
        const editorPane = accessor.get($mJ).activeEditorPane;
        if (editorPane instanceof $_Zb) {
          editorPane.defineKeybinding(editorPane.activeKeybindingEntry, false);
        }
      }
    });
    $0I.registerCommandAndKeybindingRule({
      id: $iZb,
      weight: 200,
      when: $7m.and($$Yb, $aZb),
      primary: $$e(
        2048 | 41,
        2048 | 31
        /* KeyCode.KeyA */
      ),
      handler: (accessor, args2) => {
        const editorPane = accessor.get($mJ).activeEditorPane;
        if (editorPane instanceof $_Zb) {
          editorPane.defineKeybinding(editorPane.activeKeybindingEntry, true);
        }
      }
    });
    $0I.registerCommandAndKeybindingRule({
      id: $jZb,
      weight: 200,
      when: $7m.and($$Yb, $aZb),
      primary: $$e(
        2048 | 41,
        2048 | 35
        /* KeyCode.KeyE */
      ),
      handler: (accessor, args2) => {
        const editorPane = accessor.get($mJ).activeEditorPane;
        if (editorPane instanceof $_Zb && editorPane.activeKeybindingEntry.keybindingItem.keybinding) {
          editorPane.defineWhenExpression(editorPane.activeKeybindingEntry);
        }
      }
    });
    $0I.registerCommandAndKeybindingRule({
      id: $mZb,
      weight: 200,
      when: $7m.and($$Yb, $aZb, $Ceb.toNegated()),
      primary: 20,
      mac: {
        primary: 2048 | 1
        /* KeyCode.Backspace */
      },
      handler: (accessor, args2) => {
        const editorPane = accessor.get($mJ).activeEditorPane;
        if (editorPane instanceof $_Zb) {
          editorPane.removeKeybinding(editorPane.activeKeybindingEntry);
        }
      }
    });
    $0I.registerCommandAndKeybindingRule({
      id: $nZb,
      weight: 200,
      when: $7m.and($$Yb, $aZb),
      primary: 0,
      handler: (accessor, args2) => {
        const editorPane = accessor.get($mJ).activeEditorPane;
        if (editorPane instanceof $_Zb) {
          editorPane.resetKeybinding(editorPane.activeKeybindingEntry);
        }
      }
    });
    $0I.registerCommandAndKeybindingRule({
      id: $cZb,
      weight: 200,
      when: $7m.and($$Yb),
      primary: 2048 | 36,
      handler: (accessor, args2) => {
        const editorPane = accessor.get($mJ).activeEditorPane;
        if (editorPane instanceof $_Zb) {
          editorPane.focusSearch();
        }
      }
    });
    $0I.registerCommandAndKeybindingRule({
      id: $fZb,
      weight: 200,
      when: $7m.and($$Yb, $_Yb),
      primary: 512 | 41,
      mac: {
        primary: 2048 | 512 | 41
        /* KeyCode.KeyK */
      },
      handler: (accessor, args2) => {
        const editorPane = accessor.get($mJ).activeEditorPane;
        if (editorPane instanceof $_Zb) {
          editorPane.recordSearchKeys();
        }
      }
    });
    $0I.registerCommandAndKeybindingRule({
      id: $gZb,
      weight: 200,
      when: $7m.and($$Yb),
      primary: 512 | 46,
      mac: {
        primary: 2048 | 512 | 46
        /* KeyCode.KeyP */
      },
      handler: (accessor, args2) => {
        const editorPane = accessor.get($mJ).activeEditorPane;
        if (editorPane instanceof $_Zb) {
          editorPane.toggleSortByPrecedence();
        }
      }
    });
    $0I.registerCommandAndKeybindingRule({
      id: $rZb,
      weight: 200,
      when: $7m.and($$Yb, $aZb),
      primary: 0,
      handler: (accessor, args2) => {
        const editorPane = accessor.get($mJ).activeEditorPane;
        if (editorPane instanceof $_Zb) {
          editorPane.showSimilarKeybindings(editorPane.activeKeybindingEntry);
        }
      }
    });
    $0I.registerCommandAndKeybindingRule({
      id: $oZb,
      weight: 200,
      when: $7m.and($$Yb, $aZb, $bZb.negate()),
      primary: 2048 | 33,
      handler: async (accessor, args2) => {
        const editorPane = accessor.get($mJ).activeEditorPane;
        if (editorPane instanceof $_Zb) {
          await editorPane.copyKeybinding(editorPane.activeKeybindingEntry);
        }
      }
    });
    $0I.registerCommandAndKeybindingRule({
      id: $pZb,
      weight: 200,
      when: $7m.and($$Yb, $aZb),
      primary: 0,
      handler: async (accessor, args2) => {
        const editorPane = accessor.get($mJ).activeEditorPane;
        if (editorPane instanceof $_Zb) {
          await editorPane.copyKeybindingCommand(editorPane.activeKeybindingEntry);
        }
      }
    });
    $0I.registerCommandAndKeybindingRule({
      id: $qZb,
      weight: 200,
      when: $7m.and($$Yb, $aZb),
      primary: 0,
      handler: async (accessor, args2) => {
        const editorPane = accessor.get($mJ).activeEditorPane;
        if (editorPane instanceof $_Zb) {
          await editorPane.copyKeybindingCommandTitle(editorPane.activeKeybindingEntry);
        }
      }
    });
    $0I.registerCommandAndKeybindingRule({
      id: $sZb,
      weight: 200,
      when: $7m.and($$Yb, $_Yb),
      primary: 2048 | 18,
      handler: (accessor, args2) => {
        const editorPane = accessor.get($mJ).activeEditorPane;
        if (editorPane instanceof $_Zb) {
          editorPane.focusKeybindings();
        }
      }
    });
    $0I.registerCommandAndKeybindingRule({
      id: $lZb,
      weight: 200,
      when: $7m.and($$Yb, $bZb, $_bb.Visible.toNegated()),
      primary: 9,
      handler: async (accessor, args2) => {
        const editorPane = accessor.get($mJ).activeEditorPane;
        if (editorPane instanceof $_Zb) {
          editorPane.rejectWhenExpression(editorPane.activeKeybindingEntry);
        }
      }
    });
    $0I.registerCommandAndKeybindingRule({
      id: $kZb,
      weight: 200,
      when: $7m.and($$Yb, $bZb, $_bb.Visible.toNegated()),
      primary: 3,
      handler: async (accessor, args2) => {
        const editorPane = accessor.get($mJ).activeEditorPane;
        if (editorPane instanceof $_Zb) {
          editorPane.acceptWhenExpression(editorPane.activeKeybindingEntry);
        }
      }
    });
    const profileScopedActionDisposables = this.B(new $2c());
    const registerProfileScopedActions = () => {
      profileScopedActionDisposables.clear();
      profileScopedActionDisposables.add($hJ(class DefineKeybindingAction extends $gJ {
        constructor() {
          const when = $lqb.Resource.isEqualTo(that.b.currentProfile.keybindingsResource.toString());
          super({
            id: "editor.action.defineKeybinding",
            title: localize2(8813, "Define Keybinding"),
            f1: true,
            precondition: when,
            keybinding: {
              weight: 200,
              when,
              primary: $$e(
                2048 | 41,
                2048 | 41
                /* KeyCode.KeyK */
              )
            },
            menu: {
              id: $bJ.EditorContent,
              when
            }
          });
        }
        async run(accessor) {
          const codeEditor = accessor.get($mJ).activeTextEditorControl;
          if ($P5(codeEditor)) {
            codeEditor.getContribution($UK)?.showDefineKeybindingWidget();
          }
        }
      }));
    };
    registerProfileScopedActions();
    this.B(this.b.onDidChangeCurrentProfile(() => registerProfileScopedActions()));
  }
  t() {
    const commandId = "_workbench.openWorkspaceSettingsEditor";
    if (this.f.getWorkbenchState() === 3 && !$tn.getCommand(commandId)) {
      $tn.registerCommand(commandId, () => this.c.openWorkspaceSettings({ jsonEditor: false }));
      $dJ.appendMenuItem($bJ.EditorTitle, {
        command: {
          id: commandId,
          title: OPEN_USER_SETTINGS_UI_TITLE,
          icon: $TYb
        },
        when: $7m.and($lqb.Resource.isEqualTo(this.c.workspaceSettingsResource.toString()), $epb.isEqualTo("workspace"), $7m.not("isInDiffEditor")),
        group: "navigation",
        order: 1
      });
    }
    this.u();
  }
  u() {
    for (const folder of this.f.getWorkspace().folders) {
      const commandId = `_workbench.openFolderSettings.${folder.uri.toString()}`;
      if (!$tn.getCommand(commandId)) {
        $tn.registerCommand(commandId, () => {
          if (this.f.getWorkbenchState() === 2) {
            return this.c.openWorkspaceSettings({ jsonEditor: false });
          } else {
            return this.c.openFolderSettings({ folderUri: folder.uri, jsonEditor: false });
          }
        });
        $dJ.appendMenuItem($bJ.EditorTitle, {
          command: {
            id: commandId,
            title: OPEN_USER_SETTINGS_UI_TITLE,
            icon: $TYb
          },
          when: $7m.and($lqb.Resource.isEqualTo(this.c.getFolderSettingsResource(folder.uri).toString()), $7m.not("isInDiffEditor")),
          group: "navigation",
          order: 1
        });
      }
    }
  }
};
PreferencesActionsContribution = __decorate([
  __param(0, $US),
  __param(1, $gT),
  __param(2, $TK),
  __param(3, $Zk),
  __param(4, $ZI),
  __param(5, $wN),
  __param(6, $rs)
], PreferencesActionsContribution);
var SettingsEditorTitleContribution = class SettingsEditorTitleContribution2 extends $3c {
  constructor(a, b) {
    super();
    this.a = a;
    this.b = b;
    this.c();
  }
  c() {
    const registerOpenUserSettingsEditorFromJsonActionDisposables = this.B(new $4c());
    const openUserSettingsEditorWhen = $7m.and($7m.or($lqb.Resource.isEqualTo(this.a.currentProfile.settingsResource.toString()), $lqb.Resource.isEqualTo(this.b.defaultProfile.settingsResource.toString())), $7m.not("isInDiffEditor"));
    const registerOpenUserSettingsEditorFromJsonAction = () => {
      registerOpenUserSettingsEditorFromJsonActionDisposables.value = void 0;
      registerOpenUserSettingsEditorFromJsonActionDisposables.value = $hJ(class extends $gJ {
        constructor() {
          super({
            id: "_workbench.openUserSettingsEditor",
            title: OPEN_USER_SETTINGS_UI_TITLE,
            icon: $TYb,
            menu: [{
              id: $bJ.EditorTitle,
              when: openUserSettingsEditorWhen,
              group: "navigation",
              order: 1
            }]
          });
        }
        run(accessor, args2) {
          args2 = sanitizeOpenSettingsArgs(args2);
          return accessor.get($TK).openUserSettings({ jsonEditor: false, ...args2 });
        }
      });
    };
    registerOpenUserSettingsEditorFromJsonAction();
    this.B(this.a.onDidChangeCurrentProfile(() => {
      registerOpenUserSettingsEditorFromJsonAction();
    }));
    const openSettingsJsonWhen = $7m.and($6Yb, $7Yb.toNegated());
    this.B($hJ(class extends $gJ {
      constructor() {
        super({
          id: SETTINGS_EDITOR_COMMAND_SWITCH_TO_JSON,
          title: localize2(8814, "Open Settings (JSON)"),
          icon: $TYb,
          menu: [{
            id: $bJ.EditorTitle,
            when: openSettingsJsonWhen,
            group: "navigation",
            order: 1
          }]
        });
      }
      run(accessor) {
        const editorPane = accessor.get($mJ).activeEditorPane;
        if (editorPane instanceof $T1b) {
          return editorPane.switchToSettingsFile();
        }
        return null;
      }
    }));
  }
};
SettingsEditorTitleContribution = __decorate([
  __param(0, $gT),
  __param(1, $rs)
], SettingsEditorTitleContribution);
var workbenchContributionsRegistry = $Wn.as(Extensions2.Workbench);
$PL(
  PreferencesActionsContribution.ID,
  PreferencesActionsContribution,
  1
  /* WorkbenchPhase.BlockStartup */
);
$PL(
  $V1b.ID,
  $V1b,
  1
  /* WorkbenchPhase.BlockStartup */
);
workbenchContributionsRegistry.registerWorkbenchContribution(
  SettingsEditorTitleContribution,
  3
  /* LifecyclePhase.Restored */
);
$85(
  $d1b.ID,
  $d1b,
  1
  /* EditorContributionInstantiation.AfterFirstRender */
);
$dJ.appendMenuItem($bJ.MenubarFileMenu, {
  title: localize(8784, null),
  submenu: $bJ.MenubarPreferencesMenu,
  group: "5_autosave",
  order: 2,
  when: $web.toNegated()
  // on macOS native the preferences menu is separate under the application menu
});

// out-build/vs/workbench/contrib/preferences/common/smartSnippetInserter.js
var $W1b = class {
  static a(scanner) {
    while (scanner.scan() !== 17) {
      const kind = scanner.getToken();
      if (kind === 1) {
        return true;
      }
    }
    return false;
  }
  static b(model, offset) {
    let offsetBeforeLine = 0;
    const eolLength = model.getEOL().length;
    const lineCount = model.getLineCount();
    for (let lineNumber = 1; lineNumber <= lineCount; lineNumber++) {
      const lineTotalLength = model.getLineLength(lineNumber) + eolLength;
      const offsetAfterLine = offsetBeforeLine + lineTotalLength;
      if (offsetAfterLine > offset) {
        return new $8C(lineNumber, offset - offsetBeforeLine + 1);
      }
      offsetBeforeLine = offsetAfterLine;
    }
    return new $8C(lineCount, model.getLineMaxColumn(lineCount));
  }
  static insertSnippet(model, _position) {
    const desiredPosition = model.getValueLengthInRange(new $9C(1, 1, _position.lineNumber, _position.column));
    let State14;
    (function(State15) {
      State15[State15["INVALID"] = 0] = "INVALID";
      State15[State15["AFTER_OBJECT"] = 1] = "AFTER_OBJECT";
      State15[State15["BEFORE_OBJECT"] = 2] = "BEFORE_OBJECT";
    })(State14 || (State14 = {}));
    let currentState = State14.INVALID;
    let lastValidPos = -1;
    let lastValidState = State14.INVALID;
    const scanner = $ww(model.getValue());
    let arrayLevel = 0;
    let objLevel = 0;
    const checkRangeStatus = (pos, state) => {
      if (state !== State14.INVALID && arrayLevel === 1 && objLevel === 0) {
        currentState = state;
        lastValidPos = pos;
        lastValidState = state;
      } else {
        if (currentState !== State14.INVALID) {
          currentState = State14.INVALID;
          lastValidPos = scanner.getTokenOffset();
        }
      }
    };
    while (scanner.scan() !== 17) {
      const currentPos = scanner.getPosition();
      const kind = scanner.getToken();
      let goodKind = false;
      switch (kind) {
        case 3:
          goodKind = true;
          arrayLevel++;
          checkRangeStatus(currentPos, State14.BEFORE_OBJECT);
          break;
        case 4:
          goodKind = true;
          arrayLevel--;
          checkRangeStatus(currentPos, State14.INVALID);
          break;
        case 5:
          goodKind = true;
          checkRangeStatus(currentPos, State14.BEFORE_OBJECT);
          break;
        case 1:
          goodKind = true;
          objLevel++;
          checkRangeStatus(currentPos, State14.INVALID);
          break;
        case 2:
          goodKind = true;
          objLevel--;
          checkRangeStatus(currentPos, State14.AFTER_OBJECT);
          break;
        case 15:
        case 14:
          goodKind = true;
      }
      if (currentPos >= desiredPosition && (currentState !== State14.INVALID || lastValidPos !== -1)) {
        let acceptPosition;
        let acceptState;
        if (currentState !== State14.INVALID) {
          acceptPosition = goodKind ? currentPos : scanner.getTokenOffset();
          acceptState = currentState;
        } else {
          acceptPosition = lastValidPos;
          acceptState = lastValidState;
        }
        if (acceptState === State14.AFTER_OBJECT) {
          return {
            position: this.b(model, acceptPosition),
            prepend: ",",
            append: ""
          };
        } else {
          scanner.setPosition(acceptPosition);
          return {
            position: this.b(model, acceptPosition),
            prepend: "",
            append: this.a(scanner) ? "," : ""
          };
        }
      }
    }
    const modelLineCount = model.getLineCount();
    return {
      position: new $8C(modelLineCount, model.getLineMaxColumn(modelLineCount)),
      prepend: "\n[",
      append: "]"
    };
  }
};

// out-build/vs/platform/keybinding/common/baseResolvedKeybinding.js
var $X1b = class extends $ff {
  constructor(os, chords) {
    super();
    if (chords.length === 0) {
      throw $nb(`chords`);
    }
    this.c = os;
    this.d = chords;
  }
  getLabel() {
    return $X2.toLabel(this.c, this.d, (keybinding) => this.f(keybinding));
  }
  getAriaLabel() {
    return $Y2.toLabel(this.c, this.d, (keybinding) => this.g(keybinding));
  }
  getElectronAccelerator() {
    if (this.d.length > 1) {
      return null;
    }
    if (this.d[0].isDuplicateModifierCase()) {
      return null;
    }
    return $Z2.toLabel(this.c, this.d, (keybinding) => this.h(keybinding));
  }
  getUserSettingsLabel() {
    return $12.toLabel(this.c, this.d, (keybinding) => this.l(keybinding));
  }
  isWYSIWYG() {
    return this.d.every((keybinding) => this.m(keybinding));
  }
  hasMultipleChords() {
    return this.d.length > 1;
  }
  getChords() {
    return this.d.map((keybinding) => this.e(keybinding));
  }
  e(keybinding) {
    return new $ef(keybinding.ctrlKey, keybinding.shiftKey, keybinding.altKey, keybinding.metaKey, this.f(keybinding), this.g(keybinding));
  }
  getDispatchChords() {
    return this.d.map((keybinding) => this.n(keybinding));
  }
  getSingleModifierDispatchChords() {
    return this.d.map((keybinding) => this.o(keybinding));
  }
};

// out-build/vs/workbench/services/keybinding/common/windowsKeyboardMapper.js
var LOG = false;
function log3(str) {
  if (LOG) {
    console.info(str);
  }
}
var $Y1b = class extends $X1b {
  constructor(mapper, chords) {
    super(1, chords);
    this.b = mapper;
  }
  f(chord) {
    if (chord.isDuplicateModifierCase()) {
      return "";
    }
    return this.b.getUILabelForKeyCode(chord.keyCode);
  }
  k(chord) {
    if (chord.isDuplicateModifierCase()) {
      return "";
    }
    return KeyCodeUtils.toString(chord.keyCode);
  }
  getUSLabel() {
    return $X2.toLabel(this.c, this.d, (keybinding) => this.k(keybinding));
  }
  g(chord) {
    if (chord.isDuplicateModifierCase()) {
      return "";
    }
    return this.b.getAriaLabelForKeyCode(chord.keyCode);
  }
  h(chord) {
    return this.b.getElectronAcceleratorForKeyBinding(chord);
  }
  l(chord) {
    if (chord.isDuplicateModifierCase()) {
      return "";
    }
    const result = this.b.getUserSettingsLabelForKeyCode(chord.keyCode);
    return result ? result.toLowerCase() : result;
  }
  m(chord) {
    return this.t(chord.keyCode);
  }
  t(keyCode) {
    if (keyCode === 15 || keyCode === 16 || keyCode === 17 || keyCode === 18) {
      return true;
    }
    const ariaLabel = this.b.getAriaLabelForKeyCode(keyCode);
    const userSettingsLabel = this.b.getUserSettingsLabelForKeyCode(keyCode);
    return ariaLabel === userSettingsLabel;
  }
  n(chord) {
    if (chord.isModifierKey()) {
      return null;
    }
    let result = "";
    if (chord.ctrlKey) {
      result += "ctrl+";
    }
    if (chord.shiftKey) {
      result += "shift+";
    }
    if (chord.altKey) {
      result += "alt+";
    }
    if (chord.metaKey) {
      result += "meta+";
    }
    result += KeyCodeUtils.toString(chord.keyCode);
    return result;
  }
  o(chord) {
    if (chord.keyCode === 5 && !chord.shiftKey && !chord.altKey && !chord.metaKey) {
      return "ctrl";
    }
    if (chord.keyCode === 4 && !chord.ctrlKey && !chord.altKey && !chord.metaKey) {
      return "shift";
    }
    if (chord.keyCode === 6 && !chord.ctrlKey && !chord.shiftKey && !chord.metaKey) {
      return "alt";
    }
    if (chord.keyCode === 57 && !chord.ctrlKey && !chord.shiftKey && !chord.altKey) {
      return "meta";
    }
    return null;
  }
  static w(chord, mapping2) {
    if (!mapping2) {
      return null;
    }
    if (chord.ctrlKey && chord.shiftKey && chord.altKey) {
      return mapping2.withShiftAltGr;
    }
    if (chord.ctrlKey && chord.altKey) {
      return mapping2.withAltGr;
    }
    if (chord.shiftKey) {
      return mapping2.withShift;
    }
    return mapping2.value;
  }
  static getProducedChar(chord, mapping2) {
    const char = this.w(chord, mapping2);
    if (char === null || char.length === 0) {
      return " --- ";
    }
    return "  " + char + "  ";
  }
};
var $Z1b = class {
  constructor(f, rawMappings, g) {
    this.f = f;
    this.g = g;
    this.d = [];
    this.c = [];
    this.d = [];
    this.e = [];
    this.d[
      0
      /* KeyCode.Unknown */
    ] = KeyCodeUtils.toString(
      0
      /* KeyCode.Unknown */
    );
    for (let scanCode = 0; scanCode < 193; scanCode++) {
      const immutableKeyCode = $9e[scanCode];
      if (immutableKeyCode !== -1) {
        this.c[scanCode] = immutableKeyCode;
        this.d[immutableKeyCode] = KeyCodeUtils.toString(immutableKeyCode);
        this.e[immutableKeyCode] = true;
      }
    }
    const producesLetter = [];
    let producesLetters = false;
    this.b = [];
    for (const strCode in rawMappings) {
      if (rawMappings.hasOwnProperty(strCode)) {
        const scanCode = $8e.toEnum(strCode);
        if (scanCode === 0) {
          log3(`Unknown scanCode ${strCode} in mapping.`);
          continue;
        }
        const rawMapping = rawMappings[strCode];
        const immutableKeyCode = $9e[scanCode];
        if (immutableKeyCode !== -1) {
          const keyCode2 = $7e[rawMapping.vkey] || 0;
          if (keyCode2 === 0 || immutableKeyCode === keyCode2) {
            continue;
          }
          if (scanCode !== 134) {
            continue;
          }
        }
        const value = rawMapping.value;
        const withShift = rawMapping.withShift;
        const withAltGr = rawMapping.withAltGr;
        const withShiftAltGr = rawMapping.withShiftAltGr;
        const keyCode = $7e[rawMapping.vkey] || 0;
        const mapping2 = {
          scanCode,
          keyCode,
          value,
          withShift,
          withAltGr,
          withShiftAltGr
        };
        this.b[scanCode] = mapping2;
        this.c[scanCode] = keyCode;
        if (keyCode === 0) {
          continue;
        }
        this.e[keyCode] = true;
        if (value.length === 0) {
          this.d[keyCode] = null;
        } else if (value.length > 1) {
          this.d[keyCode] = value;
        } else {
          const charCode = value.charCodeAt(0);
          if (charCode >= 97 && charCode <= 122) {
            const upperCaseValue = 65 + (charCode - 97);
            producesLetter[upperCaseValue] = true;
            producesLetters = true;
            this.d[keyCode] = String.fromCharCode(65 + (charCode - 97));
          } else if (charCode >= 65 && charCode <= 90) {
            producesLetter[charCode] = true;
            producesLetters = true;
            this.d[keyCode] = value;
          } else {
            this.d[keyCode] = value;
          }
        }
      }
    }
    const _registerLetterIfMissing = (charCode, keyCode) => {
      if (!producesLetter[charCode]) {
        this.d[keyCode] = String.fromCharCode(charCode);
      }
    };
    _registerLetterIfMissing(
      65,
      31
      /* KeyCode.KeyA */
    );
    _registerLetterIfMissing(
      66,
      32
      /* KeyCode.KeyB */
    );
    _registerLetterIfMissing(
      67,
      33
      /* KeyCode.KeyC */
    );
    _registerLetterIfMissing(
      68,
      34
      /* KeyCode.KeyD */
    );
    _registerLetterIfMissing(
      69,
      35
      /* KeyCode.KeyE */
    );
    _registerLetterIfMissing(
      70,
      36
      /* KeyCode.KeyF */
    );
    _registerLetterIfMissing(
      71,
      37
      /* KeyCode.KeyG */
    );
    _registerLetterIfMissing(
      72,
      38
      /* KeyCode.KeyH */
    );
    _registerLetterIfMissing(
      73,
      39
      /* KeyCode.KeyI */
    );
    _registerLetterIfMissing(
      74,
      40
      /* KeyCode.KeyJ */
    );
    _registerLetterIfMissing(
      75,
      41
      /* KeyCode.KeyK */
    );
    _registerLetterIfMissing(
      76,
      42
      /* KeyCode.KeyL */
    );
    _registerLetterIfMissing(
      77,
      43
      /* KeyCode.KeyM */
    );
    _registerLetterIfMissing(
      78,
      44
      /* KeyCode.KeyN */
    );
    _registerLetterIfMissing(
      79,
      45
      /* KeyCode.KeyO */
    );
    _registerLetterIfMissing(
      80,
      46
      /* KeyCode.KeyP */
    );
    _registerLetterIfMissing(
      81,
      47
      /* KeyCode.KeyQ */
    );
    _registerLetterIfMissing(
      82,
      48
      /* KeyCode.KeyR */
    );
    _registerLetterIfMissing(
      83,
      49
      /* KeyCode.KeyS */
    );
    _registerLetterIfMissing(
      84,
      50
      /* KeyCode.KeyT */
    );
    _registerLetterIfMissing(
      85,
      51
      /* KeyCode.KeyU */
    );
    _registerLetterIfMissing(
      86,
      52
      /* KeyCode.KeyV */
    );
    _registerLetterIfMissing(
      87,
      53
      /* KeyCode.KeyW */
    );
    _registerLetterIfMissing(
      88,
      54
      /* KeyCode.KeyX */
    );
    _registerLetterIfMissing(
      89,
      55
      /* KeyCode.KeyY */
    );
    _registerLetterIfMissing(
      90,
      56
      /* KeyCode.KeyZ */
    );
    if (!producesLetters) {
      const _registerLabel = (keyCode, charCode) => {
        this.d[keyCode] = String.fromCharCode(charCode);
      };
      _registerLabel(
        85,
        59
        /* CharCode.Semicolon */
      );
      _registerLabel(
        86,
        61
        /* CharCode.Equals */
      );
      _registerLabel(
        87,
        44
        /* CharCode.Comma */
      );
      _registerLabel(
        88,
        45
        /* CharCode.Dash */
      );
      _registerLabel(
        89,
        46
        /* CharCode.Period */
      );
      _registerLabel(
        90,
        47
        /* CharCode.Slash */
      );
      _registerLabel(
        91,
        96
        /* CharCode.BackTick */
      );
      _registerLabel(
        92,
        91
        /* CharCode.OpenSquareBracket */
      );
      _registerLabel(
        93,
        92
        /* CharCode.Backslash */
      );
      _registerLabel(
        94,
        93
        /* CharCode.CloseSquareBracket */
      );
      _registerLabel(
        95,
        39
        /* CharCode.SingleQuote */
      );
    }
  }
  dumpDebugInfo() {
    const result = [];
    const immutableSamples = [
      88,
      104
      /* ScanCode.Numpad0 */
    ];
    let cnt = 0;
    result.push(`-----------------------------------------------------------------------------------------------------------------------------------------`);
    for (let scanCode = 0; scanCode < 193; scanCode++) {
      if ($9e[scanCode] !== -1) {
        if (immutableSamples.indexOf(scanCode) === -1) {
          continue;
        }
      }
      if (cnt % 6 === 0) {
        result.push(`|       HW Code combination      |  Key  |    KeyCode combination    |          UI label         |        User settings       | WYSIWYG |`);
        result.push(`-----------------------------------------------------------------------------------------------------------------------------------------`);
      }
      cnt++;
      const mapping2 = this.b[scanCode];
      const strCode = $8e.toString(scanCode);
      const mods = [0, 2, 5, 7];
      for (const mod of mods) {
        const ctrlKey = mod & 1 ? true : false;
        const shiftKey = mod & 2 ? true : false;
        const altKey = mod & 4 ? true : false;
        const scanCodeChord = new $cf(ctrlKey, shiftKey, altKey, false, scanCode);
        const keyCodeChord = this.j(scanCodeChord);
        const strKeyCode = keyCodeChord ? KeyCodeUtils.toString(keyCodeChord.keyCode) : null;
        const resolvedKb = keyCodeChord ? new $Y1b(this, [keyCodeChord]) : null;
        const outScanCode = `${ctrlKey ? "Ctrl+" : ""}${shiftKey ? "Shift+" : ""}${altKey ? "Alt+" : ""}${strCode}`;
        const ariaLabel = resolvedKb ? resolvedKb.getAriaLabel() : null;
        const outUILabel = ariaLabel ? ariaLabel.replace(/Control\+/, "Ctrl+") : null;
        const outUserSettings = resolvedKb ? resolvedKb.getUserSettingsLabel() : null;
        const outKey = $Y1b.getProducedChar(scanCodeChord, mapping2);
        const outKb = strKeyCode ? `${ctrlKey ? "Ctrl+" : ""}${shiftKey ? "Shift+" : ""}${altKey ? "Alt+" : ""}${strKeyCode}` : null;
        const isWYSIWYG = resolvedKb ? resolvedKb.isWYSIWYG() : false;
        const outWYSIWYG = isWYSIWYG ? "       " : "   NO  ";
        result.push(`| ${this.h(outScanCode, 30)} | ${outKey} | ${this.h(outKb, 25)} | ${this.h(outUILabel, 25)} |  ${this.h(outUserSettings, 25)} | ${outWYSIWYG} |`);
      }
      result.push(`-----------------------------------------------------------------------------------------------------------------------------------------`);
    }
    return result.join("\n");
  }
  h(str, cnt) {
    if (str === null) {
      str = "null";
    }
    while (str.length < cnt) {
      str = " " + str;
    }
    return str;
  }
  getUILabelForKeyCode(keyCode) {
    return this.i(keyCode);
  }
  getAriaLabelForKeyCode(keyCode) {
    return this.i(keyCode);
  }
  getUserSettingsLabelForKeyCode(keyCode) {
    if (this.f) {
      return KeyCodeUtils.toUserSettingsUS(keyCode);
    }
    return KeyCodeUtils.toUserSettingsGeneral(keyCode);
  }
  getElectronAcceleratorForKeyBinding(chord) {
    return KeyCodeUtils.toElectronAccelerator(chord.keyCode);
  }
  i(keyCode) {
    return this.d[keyCode] || KeyCodeUtils.toString(
      0
      /* KeyCode.Unknown */
    );
  }
  resolveKeyboardEvent(keyboardEvent) {
    const ctrlKey = keyboardEvent.ctrlKey || this.g && keyboardEvent.altGraphKey;
    const altKey = keyboardEvent.altKey || this.g && keyboardEvent.altGraphKey;
    const chord = new $bf(ctrlKey, keyboardEvent.shiftKey, altKey, keyboardEvent.metaKey, keyboardEvent.keyCode);
    return new $Y1b(this, [chord]);
  }
  j(chord) {
    if (!chord) {
      return null;
    }
    if (chord instanceof $bf) {
      if (!this.e[chord.keyCode]) {
        return null;
      }
      return chord;
    }
    const keyCode = this.c[chord.scanCode] || 0;
    if (keyCode === 0 || !this.e[keyCode]) {
      return null;
    }
    return new $bf(chord.ctrlKey, chord.shiftKey, chord.altKey, chord.metaKey, keyCode);
  }
  resolveKeybinding(keybinding) {
    const chords = $Qy(keybinding.chords.map((chord) => this.j(chord)));
    if (chords.length > 0) {
      return [new $Y1b(this, chords)];
    }
    return [];
  }
};

// out-build/vs/workbench/contrib/preferences/browser/keybindingsEditorContribution.js
var $11b_1;
var NLS_KB_LAYOUT_ERROR_MESSAGE = localize(8751, null);
var DefineKeybindingEditorContribution = class DefineKeybindingEditorContribution2 extends $3c {
  constructor(g, h3, j) {
    super();
    this.g = g;
    this.h = h3;
    this.j = j;
    this.c = this.B(new $4c());
    this.f = this.B(this.h.createInstance($1Yb, this.g));
    this.B(this.g.onDidChangeModel((e) => this.m()));
    this.m();
  }
  m() {
    this.c.value = isInterestingEditorModel(this.g, this.j) ? this.h.createInstance($11b, this.g) : void 0;
  }
  showDefineKeybindingWidget() {
    if (isInterestingEditorModel(this.g, this.j)) {
      this.f.start().then((keybinding) => this.n(keybinding));
    }
  }
  n(keybinding) {
    this.g.focus();
    if (keybinding && this.g.hasModel()) {
      const regexp = new RegExp(/\\/g);
      const backslash = regexp.test(keybinding);
      if (backslash) {
        keybinding = keybinding.slice(0, -1) + "\\\\";
      }
      let snippetText = [
        "{",
        '	"key": ' + JSON.stringify(keybinding) + ",",
        '	"command": "${1:commandId}",',
        '	"when": "${2:editorTextFocus}"',
        "}$0"
      ].join("\n");
      const smartInsertInfo = $W1b.insertSnippet(this.g.getModel(), this.g.getPosition());
      snippetText = smartInsertInfo.prepend + snippetText + smartInsertInfo.append;
      this.g.setPosition(smartInsertInfo.position);
      $Dcb.get(this.g)?.insert(snippetText, { overwriteBefore: 0, overwriteAfter: 0 });
    }
  }
};
DefineKeybindingEditorContribution = __decorate([
  __param(1, $Pk),
  __param(2, $gT)
], DefineKeybindingEditorContribution);
var $11b = $11b_1 = class $11b2 extends $3c {
  constructor(g, h3) {
    super();
    this.g = g;
    this.h = h3;
    this.f = this.g.createDecorationsCollection();
    this.c = this.B(new $8h(() => this.j(), 500));
    const model = $Kg(this.g.getModel());
    this.B(model.onDidChangeContent(() => this.c.schedule()));
    this.B(this.h.onDidUpdateKeybindings(() => this.c.schedule()));
    this.B({
      dispose: () => {
        this.f.clear();
        this.c.cancel();
      }
    });
    this.c.schedule();
  }
  j() {
    const model = $Kg(this.g.getModel());
    const newDecorations = [];
    const root = $zw(model.getValue());
    if (root && Array.isArray(root.children)) {
      for (let i2 = 0, len = root.children.length; i2 < len; i2++) {
        const entry = root.children[i2];
        const dec = this.m(model, entry);
        if (dec !== null) {
          newDecorations.push(dec);
        }
      }
    }
    this.f.set(newDecorations);
  }
  m(model, entry) {
    if (!Array.isArray(entry.children)) {
      return null;
    }
    for (let i2 = 0, len = entry.children.length; i2 < len; i2++) {
      const prop = entry.children[i2];
      if (prop.type !== "property") {
        continue;
      }
      if (!Array.isArray(prop.children) || prop.children.length !== 2) {
        continue;
      }
      const key2 = prop.children[0];
      if (key2.value !== "key") {
        continue;
      }
      const value = prop.children[1];
      if (value.type !== "string") {
        continue;
      }
      const resolvedKeybindings = this.h.resolveUserBinding(value.value);
      if (resolvedKeybindings.length === 0) {
        return this.n(true, null, null, model, value);
      }
      const resolvedKeybinding = resolvedKeybindings[0];
      let usLabel = null;
      if (resolvedKeybinding instanceof $Y1b) {
        usLabel = resolvedKeybinding.getUSLabel();
      }
      if (!resolvedKeybinding.isWYSIWYG()) {
        const uiLabel = resolvedKeybinding.getLabel();
        if (typeof uiLabel === "string" && value.value.toLowerCase() === uiLabel.toLowerCase()) {
          return null;
        }
        return this.n(false, resolvedKeybinding.getLabel(), usLabel, model, value);
      }
      if (/abnt_|oem_/.test(value.value)) {
        return this.n(false, resolvedKeybinding.getLabel(), usLabel, model, value);
      }
      const expectedUserSettingsLabel = resolvedKeybinding.getUserSettingsLabel();
      if (typeof expectedUserSettingsLabel === "string" && !$11b_1._userSettingsFuzzyEquals(value.value, expectedUserSettingsLabel)) {
        return this.n(false, resolvedKeybinding.getLabel(), usLabel, model, value);
      }
      return null;
    }
    return null;
  }
  static _userSettingsFuzzyEquals(a, b) {
    a = a.trim().toLowerCase();
    b = b.trim().toLowerCase();
    if (a === b) {
      return true;
    }
    const aKeybinding = $S3.parseKeybinding(a);
    const bKeybinding = $S3.parseKeybinding(b);
    if (aKeybinding === null && bKeybinding === null) {
      return true;
    }
    if (!aKeybinding || !bKeybinding) {
      return false;
    }
    return aKeybinding.equals(bKeybinding);
  }
  n(isError, uiLabel, usLabel, model, keyNode) {
    let msg;
    let className;
    let overviewRulerColor;
    if (isError) {
      msg = new $bm().appendText(NLS_KB_LAYOUT_ERROR_MESSAGE);
      className = "keybindingError";
      overviewRulerColor = $hs($qH);
    } else {
      if (usLabel && uiLabel !== usLabel) {
        msg = new $bm(localize(8752, null, uiLabel, usLabel));
      } else {
        msg = new $bm(localize(8753, null, uiLabel));
      }
      className = "keybindingInfo";
      overviewRulerColor = $hs($sH);
    }
    const startPosition = model.getPositionAt(keyNode.offset);
    const endPosition = model.getPositionAt(keyNode.offset + keyNode.length);
    const range = new $9C(startPosition.lineNumber, startPosition.column, endPosition.lineNumber, endPosition.column);
    return {
      range,
      options: {
        description: "keybindings-widget",
        stickiness: 1,
        className,
        hoverMessage: msg,
        overviewRuler: {
          color: overviewRulerColor,
          position: OverviewRulerLane.Right
        }
      }
    };
  }
};
$11b = $11b_1 = __decorate([
  __param(1, $Ty)
], $11b);
function isInterestingEditorModel(editor, userDataProfileService) {
  const model = editor.getModel();
  if (!model) {
    return false;
  }
  return $oh(model.uri, userDataProfileService.currentProfile.keybindingsResource);
}
$85(
  $UK,
  DefineKeybindingEditorContribution,
  1
  /* EditorContributionInstantiation.AfterFirstRender */
);

// out-build/vs/base/common/tfIdf.js
function countMapFrom(values) {
  const map = /* @__PURE__ */ new Map();
  for (const value of values) {
    map.set(value, (map.get(value) ?? 0) + 1);
  }
  return map;
}
var $W3 = class _$W3 {
  constructor() {
    this.e = 0;
    this.f = /* @__PURE__ */ new Map();
    this.g = /* @__PURE__ */ new Map();
  }
  calculateScores(query, token) {
    const embedding = this.i(query);
    const idfCache = /* @__PURE__ */ new Map();
    const scores = [];
    for (const [key2, doc] of this.g) {
      if (token.isCancellationRequested) {
        return [];
      }
      for (const chunk of doc.chunks) {
        const score2 = this.h(chunk, embedding, idfCache);
        if (score2 > 0) {
          scores.push({ key: key2, score: score2 });
        }
      }
    }
    return scores;
  }
  /**
   * Count how many times each term (word) appears in a string.
   */
  static c(input) {
    return countMapFrom(_$W3.d(input));
  }
  /**
   * Break a string into terms (words).
   */
  static *d(input) {
    const normalize = (word) => word.toLowerCase();
    for (const [word] of input.matchAll(/\b\p{Letter}[\p{Letter}\d]{2,}\b/gu)) {
      yield normalize(word);
      const camelParts = word.replace(/([a-z])([A-Z])/g, "$1 $2").split(/\s+/g);
      if (camelParts.length > 1) {
        for (const part of camelParts) {
          if (part.length > 2 && /\p{Letter}{3,}/gu.test(part)) {
            yield normalize(part);
          }
        }
      }
    }
  }
  updateDocuments(documents) {
    for (const { key: key2 } of documents) {
      this.deleteDocument(key2);
    }
    for (const doc of documents) {
      const chunks = [];
      for (const text2 of doc.textChunks) {
        const tf = _$W3.c(text2);
        for (const term of tf.keys()) {
          this.f.set(term, (this.f.get(term) ?? 0) + 1);
        }
        chunks.push({ text: text2, tf });
      }
      this.e += chunks.length;
      this.g.set(doc.key, { chunks });
    }
    return this;
  }
  deleteDocument(key2) {
    const doc = this.g.get(key2);
    if (!doc) {
      return;
    }
    this.g.delete(key2);
    this.e -= doc.chunks.length;
    for (const chunk of doc.chunks) {
      for (const term of chunk.tf.keys()) {
        const currentOccurrences = this.f.get(term);
        if (typeof currentOccurrences === "number") {
          const newOccurrences = currentOccurrences - 1;
          if (newOccurrences <= 0) {
            this.f.delete(term);
          } else {
            this.f.set(term, newOccurrences);
          }
        }
      }
    }
  }
  h(chunk, queryEmbedding, idfCache) {
    let sum = 0;
    for (const [term, termTfidf] of Object.entries(queryEmbedding)) {
      const chunkTf = chunk.tf.get(term);
      if (!chunkTf) {
        continue;
      }
      let chunkIdf = idfCache.get(term);
      if (typeof chunkIdf !== "number") {
        chunkIdf = this.j(term);
        idfCache.set(term, chunkIdf);
      }
      const chunkTfidf = chunkTf * chunkIdf;
      sum += chunkTfidf * termTfidf;
    }
    return sum;
  }
  i(input) {
    const tf = _$W3.c(input);
    return this.k(tf);
  }
  j(term) {
    const chunkOccurrences = this.f.get(term) ?? 0;
    return chunkOccurrences > 0 ? Math.log((this.e + 1) / chunkOccurrences) : 0;
  }
  k(termFrequencies) {
    const embedding = /* @__PURE__ */ Object.create(null);
    for (const [word, occurrences] of termFrequencies) {
      const idf = this.j(word);
      if (idf > 0) {
        embedding[word] = occurrences * idf;
      }
    }
    return embedding;
  }
};
function $X3(scores) {
  const result = scores.slice(0);
  result.sort((a, b) => b.score - a.score);
  const max = result[0]?.score ?? 0;
  if (max > 0) {
    for (const score2 of result) {
      score2.score /= max;
    }
  }
  return result;
}

// out-build/vs/workbench/contrib/preferences/browser/preferencesSearch.js
var $31b_1;
var AiRelatedInformationSearchProvider_1;
var $21b = class $21b2 extends $3c {
  constructor(g, h3, j, n) {
    super();
    this.g = g;
    this.h = h3;
    this.j = j;
    this.n = n;
    this.c = this.j.getInstalled(
      1
      /* ExtensionType.User */
    ).then((exts) => {
      return exts.filter((ext) => this.n.isEnabled(ext)).filter((ext) => ext.manifest && ext.manifest.contributes && ext.manifest.contributes.configuration).filter((ext) => !!ext.identifier.uuid);
    });
  }
  get r() {
    const workbenchSettings = this.h.getValue().workbench.settings;
    return workbenchSettings.enableNaturalLanguageSearch;
  }
  getRemoteSearchProvider(filter) {
    if (!this.r) {
      return void 0;
    }
    this.f ??= this.g.createInstance(RemoteSearchProvider2);
    this.f.setFilter(filter);
    return this.f;
  }
  getLocalSearchProvider(filter) {
    return this.g.createInstance($31b, filter);
  }
};
$21b = __decorate([
  __param(0, $Pk),
  __param(1, $kl),
  __param(2, $sA),
  __param(3, $qzb)
], $21b);
function cleanFilter(filter) {
  return filter.replace(/[":]/g, " ").replace(/  /g, " ").trim();
}
var $31b = class $31b2 {
  static {
    $31b_1 = this;
  }
  static {
    this.EXACT_MATCH_SCORE = 1e4;
  }
  static {
    this.START_SCORE = 1e3;
  }
  constructor(c, d) {
    this.c = c;
    this.d = d;
    this.c = cleanFilter(this.c);
  }
  searchModel(preferencesModel, token) {
    if (!this.c) {
      return Promise.resolve(null);
    }
    let orderedScore = $31b_1.START_SCORE;
    const settingMatcher = (setting) => {
      const { matches, matchType } = new $41b(this.c, setting, true, true, (filter, setting2) => preferencesModel.findValueMatches(filter, setting2), this.d);
      const score2 = this.c === setting.key ? $31b_1.EXACT_MATCH_SCORE : orderedScore--;
      return matches.length ? {
        matches,
        matchType,
        score: score2
      } : null;
    };
    const filterMatches = preferencesModel.filterSettings(this.c, this.e(this.c), settingMatcher);
    const exactMatch = filterMatches.find((m) => m.score === $31b_1.EXACT_MATCH_SCORE);
    if (exactMatch) {
      return Promise.resolve({
        filterMatches: [exactMatch],
        exactMatch: true
      });
    } else {
      return Promise.resolve({
        filterMatches
      });
    }
  }
  e(filter) {
    const regex = $Jf(filter, false, { global: true });
    return (group2) => {
      return group2.id !== "defaultOverrides" && regex.test(group2.title);
    };
  }
};
$31b = $31b_1 = __decorate([
  __param(1, $kl)
], $31b);
var $41b = class $41b2 {
  constructor(searchString, setting, requireFullQueryMatch, c, valuesMatcher, d) {
    this.c = c;
    this.d = d;
    this.matchType = SettingMatchType.None;
    this.matches = $Rb(this.e(searchString, setting), (match) => `${match.startLineNumber}_${match.startColumn}_${match.endLineNumber}_${match.endColumn}_`);
  }
  e(searchString, setting) {
    const result = this.g(searchString, setting);
    return result;
  }
  f(settingId) {
    const label3 = settingId.replace(/[-._]/g, " ").replace(/([a-z]+)([A-Z])/g, "$1 $2").replace(/([A-Za-z]+)(\d+)/g, "$1 $2").replace(/(\d+)([A-Za-z]+)/g, "$1 $2").toLowerCase();
    return label3;
  }
  g(searchString, setting) {
    const descriptionMatchingWords = /* @__PURE__ */ new Map();
    const keyMatchingWords = /* @__PURE__ */ new Map();
    const valueMatchingWords = /* @__PURE__ */ new Map();
    const words = new Set(searchString.split(" "));
    const settingKeyAsWords = this.f(setting.key);
    for (const word of words) {
      const keyMatches = $Ql(word, settingKeyAsWords, true);
      if (keyMatches?.length) {
        keyMatchingWords.set(word, keyMatches.map((match) => this.h(setting, match)));
      }
    }
    if (keyMatchingWords.size === words.size) {
      this.matchType |= SettingMatchType.KeyMatch;
    } else {
      keyMatchingWords.clear();
    }
    const keyIdMatches = $Ml(searchString, setting.key);
    if (keyIdMatches?.length) {
      keyMatchingWords.set(setting.key, keyIdMatches.map((match) => this.h(setting, match)));
      this.matchType |= SettingMatchType.KeyMatch;
    }
    if (setting.overrides?.length && this.matchType & SettingMatchType.KeyMatch) {
      this.matchType = SettingMatchType.LanguageTagSettingMatch;
      const keyRanges2 = keyMatchingWords.size ? Array.from(keyMatchingWords.values()).flat() : [];
      return [...keyRanges2];
    }
    if (this.c) {
      for (const word of words) {
        for (let lineIndex = 0; lineIndex < setting.description.length; lineIndex++) {
          const descriptionMatches = $Ml(word, setting.description[lineIndex]);
          if (descriptionMatches?.length) {
            descriptionMatchingWords.set(word, descriptionMatches.map((match) => this.i(setting, match, lineIndex)));
          }
        }
      }
      if (descriptionMatchingWords.size === words.size) {
        this.matchType |= SettingMatchType.DescriptionOrValueMatch;
      } else {
        descriptionMatchingWords.clear();
      }
    }
    if (setting.enum?.length) {
      for (const option of setting.enum) {
        if (typeof option !== "string") {
          continue;
        }
        valueMatchingWords.clear();
        for (const word of words) {
          const valueMatches = $Ml(word, option);
          if (valueMatches?.length) {
            valueMatchingWords.set(word, valueMatches.map((match) => this.j(setting, match)));
          }
        }
        if (valueMatchingWords.size === words.size) {
          this.matchType |= SettingMatchType.DescriptionOrValueMatch;
          break;
        } else {
          valueMatchingWords.clear();
        }
      }
    } else {
      const settingValue = this.d.getValue(setting.key);
      if (typeof settingValue === "string") {
        for (const word of words) {
          const valueMatches = $Ml(word, settingValue);
          if (valueMatches?.length) {
            valueMatchingWords.set(word, valueMatches.map((match) => this.j(setting, match)));
          }
        }
        if (valueMatchingWords.size === words.size) {
          this.matchType |= SettingMatchType.DescriptionOrValueMatch;
        } else {
          valueMatchingWords.clear();
        }
      }
    }
    const descriptionRanges = descriptionMatchingWords.size ? Array.from(descriptionMatchingWords.values()).flat() : [];
    const keyRanges = keyMatchingWords.size ? Array.from(keyMatchingWords.values()).flat() : [];
    const valueRanges = valueMatchingWords.size ? Array.from(valueMatchingWords.values()).flat() : [];
    return [...descriptionRanges, ...keyRanges, ...valueRanges];
  }
  h(setting, match) {
    return {
      startLineNumber: setting.keyRange.startLineNumber,
      startColumn: setting.keyRange.startColumn + match.start,
      endLineNumber: setting.keyRange.startLineNumber,
      endColumn: setting.keyRange.startColumn + match.end
    };
  }
  i(setting, match, lineIndex) {
    const descriptionRange = setting.descriptionRanges[lineIndex];
    if (!descriptionRange) {
      return $JK;
    }
    return {
      startLineNumber: descriptionRange.startLineNumber,
      startColumn: descriptionRange.startColumn + match.start,
      endLineNumber: descriptionRange.endLineNumber,
      endColumn: descriptionRange.startColumn + match.end
    };
  }
  j(setting, match) {
    return {
      startLineNumber: setting.valueRange.startLineNumber,
      startColumn: setting.valueRange.startColumn + match.start + 1,
      endLineNumber: setting.valueRange.startLineNumber,
      endColumn: setting.valueRange.startColumn + match.end + 1
    };
  }
};
$41b = __decorate([
  __param(5, $kl)
], $41b);
var AiRelatedInformationSearchKeysProvider = class {
  constructor(f) {
    this.f = f;
    this.c = [];
    this.d = {};
  }
  updateModel(preferencesModel) {
    if (preferencesModel === this.e) {
      return;
    }
    this.e = preferencesModel;
    this.g();
  }
  g() {
    this.c = [];
    this.d = {};
    if (!this.e || !this.f.isEnabled()) {
      return;
    }
    for (const group2 of this.e.settingsGroups) {
      if (group2.id === "mostCommonlyUsed") {
        continue;
      }
      for (const section of group2.sections) {
        for (const setting of section.settings) {
          this.c.push(setting.key);
          this.d[setting.key] = setting;
        }
      }
    }
  }
  getSettingKeys() {
    return this.c;
  }
  getSettingsRecord() {
    return this.d;
  }
};
var AiRelatedInformationSearchProvider = class AiRelatedInformationSearchProvider2 {
  static {
    AiRelatedInformationSearchProvider_1 = this;
  }
  static {
    this.c = 5;
  }
  constructor(f) {
    this.f = f;
    this.e = "";
    this.d = new AiRelatedInformationSearchKeysProvider(f);
  }
  setFilter(filter) {
    this.e = cleanFilter(filter);
  }
  async searchModel(preferencesModel, token) {
    if (!this.e || !this.f.isEnabled()) {
      return null;
    }
    this.d.updateModel(preferencesModel);
    return {
      filterMatches: await this.g(token)
    };
  }
  async g(token) {
    const settingsRecord = this.d.getSettingsRecord();
    const filterMatches = [];
    const relatedInformation = await this.f.getRelatedInformation(this.e, [RelatedInformationType2.SettingInformation], token ?? CancellationToken.None);
    relatedInformation.sort((a, b) => b.weight - a.weight);
    for (const info of relatedInformation) {
      if (filterMatches.length === AiRelatedInformationSearchProvider_1.c) {
        break;
      }
      const pick = info.setting;
      filterMatches.push({
        setting: settingsRecord[pick],
        matches: [settingsRecord[pick].range],
        matchType: SettingMatchType.RemoteMatch,
        score: info.weight
      });
    }
    return filterMatches;
  }
};
AiRelatedInformationSearchProvider = AiRelatedInformationSearchProvider_1 = __decorate([
  __param(0, $vS)
], AiRelatedInformationSearchProvider);
var TfIdfSearchProvider = class _TfIdfSearchProvider {
  static {
    this.c = 50;
  }
  static {
    this.d = 0.7;
  }
  static {
    this.e = 5;
  }
  constructor() {
    this.g = "";
    this.h = [];
    this.i = {};
  }
  setFilter(filter) {
    this.g = cleanFilter(filter);
  }
  keyToLabel(settingId) {
    const label3 = settingId.replace(/[-._]/g, " ").replace(/([a-z]+)([A-Z])/g, "$1 $2").replace(/([A-Za-z]+)(\d+)/g, "$1 $2").replace(/(\d+)([A-Za-z]+)/g, "$1 $2").toLowerCase();
    return label3;
  }
  settingItemToEmbeddingString(item) {
    let result = `Setting Id: ${item.key}
`;
    result += `Label: ${this.keyToLabel(item.key)}
`;
    result += `Description: ${item.description}
`;
    return result;
  }
  async searchModel(preferencesModel, token) {
    if (!this.g) {
      return null;
    }
    if (this.f !== preferencesModel) {
      this.f = preferencesModel;
      this.h = [];
      this.i = {};
      for (const group2 of preferencesModel.settingsGroups) {
        if (group2.id === "mostCommonlyUsed") {
          continue;
        }
        for (const section of group2.sections) {
          for (const setting of section.settings) {
            this.h.push({
              key: setting.key,
              textChunks: [this.settingItemToEmbeddingString(setting)]
            });
            this.i[setting.key] = setting;
          }
        }
      }
    }
    return {
      filterMatches: await this.j(token)
    };
  }
  async j(token) {
    const filterMatches = [];
    const tfIdfCalculator = new $W3();
    tfIdfCalculator.updateDocuments(this.h);
    const tfIdfRankings = tfIdfCalculator.calculateScores(this.g, token ?? CancellationToken.None);
    tfIdfRankings.sort((a, b) => b.score - a.score);
    const maxScore = tfIdfRankings[0].score;
    if (maxScore < _TfIdfSearchProvider.c) {
      return [];
    }
    for (const info of tfIdfRankings) {
      if (info.score / maxScore < _TfIdfSearchProvider.d || filterMatches.length === _TfIdfSearchProvider.e) {
        break;
      }
      const pick = info.key;
      filterMatches.push({
        setting: this.i[pick],
        matches: [this.i[pick].range],
        matchType: SettingMatchType.RemoteMatch,
        score: info.score
      });
    }
    return filterMatches;
  }
};
var RemoteSearchProvider2 = class RemoteSearchProvider3 {
  constructor(f) {
    this.f = f;
    this.e = "";
  }
  g() {
    if (this.f.isEnabled()) {
      this.c ??= new AiRelatedInformationSearchProvider(this.f);
    }
    this.d ??= new TfIdfSearchProvider();
  }
  setFilter(filter) {
    this.g();
    this.e = filter;
    if (this.c) {
      this.c.setFilter(filter);
    }
    this.d.setFilter(filter);
  }
  searchModel(preferencesModel, token) {
    if (!this.e) {
      return Promise.resolve(null);
    }
    if (!this.c) {
      return this.d.searchModel(preferencesModel, token);
    }
    return this.c.searchModel(preferencesModel, token).then((results) => {
      return results?.filterMatches.length ? results : this.d.searchModel(preferencesModel, token);
    });
  }
};
RemoteSearchProvider2 = __decorate([
  __param(0, $vS)
], RemoteSearchProvider2);
$SC(
  $2Yb,
  $21b,
  1
  /* InstantiationType.Delayed */
);

// out-build/vs/workbench/contrib/codeEditor/browser/toggleWordWrap.js
var transientWordWrapState = "transientWordWrapState";
var isWordWrapMinifiedKey = "isWordWrapMinified";
var isDominatedByLongLinesKey = "isDominatedByLongLines";
var CAN_TOGGLE_WORD_WRAP = new $nn("canToggleWordWrap", false, true);
var EDITOR_WORD_WRAP = new $nn("editorWordWrap", false, localize(5237, null));
function $TIb(model, state, codeEditorService) {
  codeEditorService.setTransientModelProperty(model, transientWordWrapState, state);
}
function $UIb(model, codeEditorService) {
  return codeEditorService.getTransientModelProperty(model, transientWordWrapState);
}
var TOGGLE_WORD_WRAP_ID = "editor.action.toggleWordWrap";
var ToggleWordWrapAction = class extends $Z5 {
  constructor() {
    super({
      id: TOGGLE_WORD_WRAP_ID,
      label: localize2(5241, "View: Toggle Word Wrap"),
      precondition: void 0,
      kbOpts: {
        kbExpr: null,
        primary: 512 | 56,
        weight: 100
        /* KeybindingWeight.EditorContrib */
      }
    });
  }
  run(accessor, editor) {
    const codeEditorService = accessor.get($U5);
    if (!canToggleWordWrap(codeEditorService, editor)) {
      return;
    }
    const model = editor.getModel();
    const transientState = $UIb(model, codeEditorService);
    let newState;
    if (transientState) {
      newState = null;
    } else {
      const actualWrappingInfo = editor.getOption(
        152
        /* EditorOption.wrappingInfo */
      );
      const wordWrapOverride = actualWrappingInfo.wrappingColumn === -1 ? "on" : "off";
      newState = { wordWrapOverride };
    }
    $TIb(model, newState, codeEditorService);
    const diffEditor = findDiffEditorContainingCodeEditor(editor, codeEditorService);
    if (diffEditor) {
      const originalEditor = diffEditor.getOriginalEditor();
      const modifiedEditor = diffEditor.getModifiedEditor();
      const otherEditor = originalEditor === editor ? modifiedEditor : originalEditor;
      if (canToggleWordWrap(codeEditorService, otherEditor)) {
        $TIb(otherEditor.getModel(), newState, codeEditorService);
        diffEditor.updateOptions({});
      }
    }
  }
};
function findDiffEditorContainingCodeEditor(editor, codeEditorService) {
  if (!editor.getOption(
    63
    /* EditorOption.inDiffEditor */
  )) {
    return null;
  }
  for (const diffEditor of codeEditorService.listDiffEditors()) {
    const originalEditor = diffEditor.getOriginalEditor();
    const modifiedEditor = diffEditor.getModifiedEditor();
    if (originalEditor === editor || modifiedEditor === editor) {
      return diffEditor;
    }
  }
  return null;
}
var ToggleWordWrapController = class ToggleWordWrapController2 extends $3c {
  static {
    this.ID = "editor.contrib.toggleWordWrapController";
  }
  constructor(a, b, c) {
    super();
    this.a = a;
    this.b = b;
    this.c = c;
    const options3 = this.a.getOptions();
    const wrappingInfo = options3.get(
      152
      /* EditorOption.wrappingInfo */
    );
    const isWordWrapMinified = this.b.createKey(isWordWrapMinifiedKey, wrappingInfo.isWordWrapMinified);
    const isDominatedByLongLines = this.b.createKey(isDominatedByLongLinesKey, wrappingInfo.isDominatedByLongLines);
    let currentlyApplyingEditorConfig = false;
    this.B(a.onDidChangeConfiguration((e) => {
      if (!e.hasChanged(
        152
        /* EditorOption.wrappingInfo */
      )) {
        return;
      }
      const options4 = this.a.getOptions();
      const wrappingInfo2 = options4.get(
        152
        /* EditorOption.wrappingInfo */
      );
      isWordWrapMinified.set(wrappingInfo2.isWordWrapMinified);
      isDominatedByLongLines.set(wrappingInfo2.isDominatedByLongLines);
      if (!currentlyApplyingEditorConfig) {
        ensureWordWrapSettings();
      }
    }));
    this.B(a.onDidChangeModel((e) => {
      ensureWordWrapSettings();
    }));
    this.B(c.onDidChangeTransientModelProperty(() => {
      ensureWordWrapSettings();
    }));
    const ensureWordWrapSettings = () => {
      if (!canToggleWordWrap(this.c, this.a)) {
        return;
      }
      const transientState = $UIb(this.a.getModel(), this.c);
      try {
        currentlyApplyingEditorConfig = true;
        this.f(transientState);
      } finally {
        currentlyApplyingEditorConfig = false;
      }
    };
  }
  f(state) {
    const wordWrapOverride2 = state ? state.wordWrapOverride : "inherit";
    this.a.updateOptions({
      wordWrapOverride2
    });
  }
};
ToggleWordWrapController = __decorate([
  __param(1, $on),
  __param(2, $U5)
], ToggleWordWrapController);
var DiffToggleWordWrapController = class DiffToggleWordWrapController2 extends $3c {
  static {
    this.ID = "diffeditor.contrib.toggleWordWrapController";
  }
  constructor(a, b) {
    super();
    this.a = a;
    this.b = b;
    this.B(this.a.onDidChangeModel(() => {
      this.c();
    }));
  }
  c() {
    const originalEditor = this.a.getOriginalEditor();
    const modifiedEditor = this.a.getModifiedEditor();
    if (!originalEditor.hasModel() || !modifiedEditor.hasModel()) {
      return;
    }
    const originalTransientState = $UIb(originalEditor.getModel(), this.b);
    const modifiedTransientState = $UIb(modifiedEditor.getModel(), this.b);
    if (originalTransientState && !modifiedTransientState && canToggleWordWrap(this.b, originalEditor)) {
      $TIb(modifiedEditor.getModel(), originalTransientState, this.b);
      this.a.updateOptions({});
    }
    if (!originalTransientState && modifiedTransientState && canToggleWordWrap(this.b, modifiedEditor)) {
      $TIb(originalEditor.getModel(), modifiedTransientState, this.b);
      this.a.updateOptions({});
    }
  }
};
DiffToggleWordWrapController = __decorate([
  __param(1, $U5)
], DiffToggleWordWrapController);
function canToggleWordWrap(codeEditorService, editor) {
  if (!editor) {
    return false;
  }
  if (editor.isSimpleWidget) {
    return false;
  }
  const model = editor.getModel();
  if (!model) {
    return false;
  }
  if (editor.getOption(
    63
    /* EditorOption.inDiffEditor */
  )) {
    for (const diffEditor of codeEditorService.listDiffEditors()) {
      if (diffEditor.getOriginalEditor() === editor && !diffEditor.renderSideBySide) {
        return false;
      }
    }
  }
  return true;
}
var EditorWordWrapContextKeyTracker = class EditorWordWrapContextKeyTracker2 extends $3c {
  static {
    this.ID = "workbench.contrib.editorWordWrapContextKeyTracker";
  }
  constructor(g, h3, j) {
    super();
    this.g = g;
    this.h = h3;
    this.j = j;
    this.B(Event2.runAndSubscribe(onDidRegisterWindow, ({ window: window3, disposables }) => {
      disposables.add($_i(window3, "focus", () => this.m(), true));
      disposables.add($_i(window3, "blur", () => this.m(), true));
    }, { window: $Y, disposables: this.q }));
    this.B(this.g.onDidActiveEditorChange(() => this.m()));
    this.a = CAN_TOGGLE_WORD_WRAP.bindTo(this.j);
    this.b = EDITOR_WORD_WRAP.bindTo(this.j);
    this.c = null;
    this.f = new $2c();
    this.m();
  }
  m() {
    const activeEditor = this.h.getFocusedCodeEditor() || this.h.getActiveCodeEditor();
    if (this.c === activeEditor) {
      return;
    }
    this.f.clear();
    this.c = activeEditor;
    if (activeEditor) {
      this.f.add(activeEditor.onDidChangeModel(() => this.n()));
      this.f.add(activeEditor.onDidChangeConfiguration((e) => {
        if (e.hasChanged(
          152
          /* EditorOption.wrappingInfo */
        )) {
          this.n();
        }
      }));
      this.n();
    }
  }
  n() {
    if (!canToggleWordWrap(this.h, this.c)) {
      return this.r(false, false);
    } else {
      const wrappingInfo = this.c.getOption(
        152
        /* EditorOption.wrappingInfo */
      );
      this.r(true, wrappingInfo.wrappingColumn !== -1);
    }
  }
  r(canToggleWordWrap2, isWordWrap) {
    this.a.set(canToggleWordWrap2);
    this.b.set(isWordWrap);
  }
};
EditorWordWrapContextKeyTracker = __decorate([
  __param(0, $mJ),
  __param(1, $U5),
  __param(2, $on)
], EditorWordWrapContextKeyTracker);
$PL(
  EditorWordWrapContextKeyTracker.ID,
  EditorWordWrapContextKeyTracker,
  3
  /* WorkbenchPhase.AfterRestored */
);
$85(
  ToggleWordWrapController.ID,
  ToggleWordWrapController,
  0
  /* EditorContributionInstantiation.Eager */
);
$95(DiffToggleWordWrapController.ID, DiffToggleWordWrapController);
$55(ToggleWordWrapAction);
$dJ.appendMenuItem($bJ.EditorTitle, {
  command: {
    id: TOGGLE_WORD_WRAP_ID,
    title: localize(5238, null),
    icon: $6l.wordWrap
  },
  group: "navigation",
  order: 1,
  when: $7m.and($7m.has(isDominatedByLongLinesKey), $7m.has(isWordWrapMinifiedKey))
});
$dJ.appendMenuItem($bJ.EditorTitle, {
  command: {
    id: TOGGLE_WORD_WRAP_ID,
    title: localize(5239, null),
    icon: $6l.wordWrap
  },
  group: "navigation",
  order: 1,
  when: $7m.and(EditorContextKeys.inDiffEditor.negate(), $7m.has(isDominatedByLongLinesKey), $7m.not(isWordWrapMinifiedKey))
});
$dJ.appendMenuItem($bJ.MenubarViewMenu, {
  command: {
    id: TOGGLE_WORD_WRAP_ID,
    title: localize(5240, null),
    toggled: EDITOR_WORD_WRAP,
    precondition: CAN_TOGGLE_WORD_WRAP
  },
  order: 1,
  group: "6_editor"
});

// out-build/vs/workbench/contrib/performance/browser/perfviewEditor.js
var $51b_1;
var $61b_1;
var $51b = class $51b2 {
  static {
    $51b_1 = this;
  }
  static get() {
    return $QL($51b_1.ID);
  }
  static {
    this.ID = "workbench.contrib.perfview";
  }
  constructor(d, textModelResolverService) {
    this.d = d;
    this.a = URI.from({ scheme: "perf", path: "Startup Performance" });
    this.b = textModelResolverService.registerTextModelContentProvider("perf", d.createInstance(PerfModelContentProvider));
  }
  dispose() {
    this.b.dispose();
  }
  getInputUri() {
    return this.a;
  }
  getEditorInput() {
    return this.d.createInstance($61b);
  }
};
$51b = $51b_1 = __decorate([
  __param(0, $Pk),
  __param(1, $oG)
], $51b);
var $61b = class $61b2 extends $6vb {
  static {
    $61b_1 = this;
  }
  static {
    this.Id = "PerfviewInput";
  }
  get typeId() {
    return $61b_1.Id;
  }
  constructor(textModelResolverService, textFileService, editorService, fileService, labelService, filesConfigurationService, textResourceConfigurationService, customEditorLabelService) {
    super($51b.get().getInputUri(), localize(8708, null), void 0, void 0, void 0, textModelResolverService, textFileService, editorService, fileService, labelService, filesConfigurationService, textResourceConfigurationService, customEditorLabelService);
  }
};
$61b = $61b_1 = __decorate([
  __param(0, $oG),
  __param(1, $cK),
  __param(2, $mJ),
  __param(3, $km),
  __param(4, $ZI),
  __param(5, $4J),
  __param(6, $zG),
  __param(7, $qrb)
], $61b);
var PerfModelContentProvider = class PerfModelContentProvider2 {
  constructor(d, f, g, h3, i2, j, k, l, m) {
    this.d = d;
    this.f = f;
    this.g = g;
    this.h = h3;
    this.i = i2;
    this.j = j;
    this.k = k;
    this.l = l;
    this.m = m;
    this.b = [];
  }
  provideTextContent(resource) {
    if (!this.a || this.a.isDisposed()) {
      $Xc(this.b);
      const langId = this.f.createById("markdown");
      this.a = this.d.getModel(resource) || this.d.createModel("Loading...", langId, resource);
      this.b.push(langId.onDidChange((e) => {
        this.a?.setLanguage(e);
      }));
      this.b.push(this.j.onDidChangeExtensionsStatus(this.n, this));
      $TIb(this.a, { wordWrapOverride: "off" }, this.g);
    }
    this.n();
    return Promise.resolve(this.a);
  }
  n() {
    Promise.all([
      this.i.whenReady(),
      this.h.when(
        4
        /* LifecyclePhase.Eventually */
      ),
      this.j.whenInstalledExtensionsRegistered(),
      // The terminal service never connects to the pty host on the web
      $r && !this.l.getConnection()?.remoteAuthority ? Promise.resolve() : this.m.whenConnected
    ]).then(() => {
      if (this.a && !this.a.isDisposed()) {
        const md = new MarkdownBuilder();
        this.o(md);
        md.blank();
        this.q(md);
        md.blank();
        this.r(md);
        md.blank();
        this.s("Terminal Stats", md, this.i.getPerformanceMarks().find((e) => e[0] === "renderer")?.[1].filter((e) => e.name.startsWith("code/terminal/")));
        md.blank();
        this.t(md);
        md.blank();
        this.u(md);
        md.blank();
        this.v(md);
        this.a.setValue(md.value);
      }
    });
  }
  o(md) {
    const metrics = this.i.startupMetrics;
    md.heading(2, "System Info");
    md.li(`${this.k.nameShort}: ${this.k.version} (${this.k.commit || "0000000"})`);
    md.li(`OS: ${metrics.platform}(${metrics.release})`);
    if (metrics.cpus) {
      md.li(`CPUs: ${metrics.cpus.model}(${metrics.cpus.count} x ${metrics.cpus.speed})`);
    }
    if (typeof metrics.totalmem === "number" && typeof metrics.freemem === "number") {
      md.li(`Memory(System): ${(metrics.totalmem / $Sm.GB).toFixed(2)} GB(${(metrics.freemem / $Sm.GB).toFixed(2)}GB free)`);
    }
    if (metrics.meminfo) {
      md.li(`Memory(Process): ${(metrics.meminfo.workingSetSize / $Sm.KB).toFixed(2)} MB working set(${(metrics.meminfo.privateBytes / $Sm.KB).toFixed(2)}MB private, ${(metrics.meminfo.sharedBytes / $Sm.KB).toFixed(2)}MB shared)`);
    }
    md.li(`VM(likelihood): ${metrics.isVMLikelyhood}%`);
    md.li(`Initial Startup: ${metrics.initialStartup}`);
    md.li(`Has ${metrics.windowCount - 1} other windows`);
    md.li(`Screen Reader Active: ${metrics.hasAccessibilitySupport}`);
    md.li(`Empty Workspace: ${metrics.emptyWorkbench}`);
  }
  q(md) {
    const metrics = this.i.startupMetrics;
    const contribTimings = $Wn.as(Extensions2.Workbench).timings;
    const table = [];
    table.push(["start => app.isReady", metrics.timers.ellapsedAppReady, "[main]", `initial startup: ${metrics.initialStartup}`]);
    table.push(["nls:start => nls:end", metrics.timers.ellapsedNlsGeneration, "[main]", `initial startup: ${metrics.initialStartup}`]);
    table.push(["import(main.js)", metrics.timers.ellapsedLoadMainBundle, "[main]", `initial startup: ${metrics.initialStartup}`]);
    table.push(["run main.js", metrics.timers.ellapsedRunMainBundle, "[main]", `initial startup: ${metrics.initialStartup}`]);
    table.push(["start crash reporter", metrics.timers.ellapsedCrashReporter, "[main]", `initial startup: ${metrics.initialStartup}`]);
    table.push(["serve main IPC handle", metrics.timers.ellapsedMainServer, "[main]", `initial startup: ${metrics.initialStartup}`]);
    table.push(["create window", metrics.timers.ellapsedWindowCreate, "[main]", `initial startup: ${metrics.initialStartup}, ${metrics.initialStartup ? `state: ${metrics.timers.ellapsedWindowRestoreState}ms, widget: ${metrics.timers.ellapsedBrowserWindowCreate}ms, show: ${metrics.timers.ellapsedWindowMaximize}ms` : ""}`]);
    table.push(["app.isReady => window.loadUrl()", metrics.timers.ellapsedWindowLoad, "[main]", `initial startup: ${metrics.initialStartup}`]);
    table.push(["window.loadUrl() => begin to import(workbench.desktop.main.js)", metrics.timers.ellapsedWindowLoadToRequire, "[main->renderer]", $LL(metrics.windowKind)]);
    table.push(["import(workbench.desktop.main.js)", metrics.timers.ellapsedRequire, "[renderer]", `cached data: ${metrics.didUseCachedData ? "YES" : "NO"}`]);
    table.push(["wait for window config", metrics.timers.ellapsedWaitForWindowConfig, "[renderer]", void 0]);
    table.push(["init storage (global & workspace)", metrics.timers.ellapsedStorageInit, "[renderer]", void 0]);
    table.push(["init workspace service", metrics.timers.ellapsedWorkspaceServiceInit, "[renderer]", void 0]);
    if ($r) {
      table.push(["init settings and global state from settings sync service", metrics.timers.ellapsedRequiredUserDataInit, "[renderer]", void 0]);
      table.push(["init keybindings, snippets & extensions from settings sync service", metrics.timers.ellapsedOtherUserDataInit, "[renderer]", void 0]);
    }
    table.push(["register extensions & spawn extension host", metrics.timers.ellapsedExtensions, "[renderer]", void 0]);
    table.push(["restore viewlet", metrics.timers.ellapsedViewletRestore, "[renderer]", metrics.viewletId]);
    table.push(["restore panel", metrics.timers.ellapsedPanelRestore, "[renderer]", metrics.panelId]);
    table.push(["restore & resolve visible editors", metrics.timers.ellapsedEditorRestore, "[renderer]", `${metrics.editorIds.length}: ${metrics.editorIds.join(", ")}`]);
    table.push(["create workbench contributions", metrics.timers.ellapsedWorkbenchContributions, "[renderer]", `${(contribTimings.get(
      1
      /* LifecyclePhase.Starting */
    )?.length ?? 0) + (contribTimings.get(
      1
      /* LifecyclePhase.Starting */
    )?.length ?? 0)} blocking startup`]);
    table.push(["overall workbench load", metrics.timers.ellapsedWorkbench, "[renderer]", void 0]);
    table.push(["workbench ready", metrics.ellapsed, "[main->renderer]", void 0]);
    table.push(["renderer ready", metrics.timers.ellapsedRenderer, "[renderer]", void 0]);
    table.push(["shared process connection ready", metrics.timers.ellapsedSharedProcesConnected, "[renderer->sharedprocess]", void 0]);
    table.push(["extensions registered", metrics.timers.ellapsedExtensionsReady, "[renderer]", void 0]);
    md.heading(2, "Performance Marks");
    md.table(["What", "Duration", "Process", "Info"], table);
  }
  r(md) {
    const eager = [];
    const normal = [];
    const extensionsStatus = this.j.getExtensionsStatus();
    for (const id2 in extensionsStatus) {
      const { activationTimes: times } = extensionsStatus[id2];
      if (!times) {
        continue;
      }
      if (times.activationReason.startup) {
        eager.push([id2, times.activationReason.startup, times.codeLoadingTime, times.activateCallTime, times.activateResolvedTime, times.activationReason.activationEvent, times.activationReason.extensionId.value]);
      } else {
        normal.push([id2, times.activationReason.startup, times.codeLoadingTime, times.activateCallTime, times.activateResolvedTime, times.activationReason.activationEvent, times.activationReason.extensionId.value]);
      }
    }
    const table = eager.concat(normal);
    if (table.length > 0) {
      md.heading(2, "Extension Activation Stats");
      md.table(["Extension", "Eager", "Load Code", "Call Activate", "Finish Activate", "Event", "By"], table);
    }
  }
  s(name, md, marks) {
    if (!marks) {
      return;
    }
    const table = [];
    let lastStartTime = -1;
    let total = 0;
    for (const { name: name2, startTime } of marks) {
      const delta = lastStartTime !== -1 ? startTime - lastStartTime : 0;
      total += delta;
      table.push([name2, Math.round(startTime), Math.round(delta), Math.round(total)]);
      lastStartTime = startTime;
    }
    if (name) {
      md.heading(2, name);
    }
    md.table(["Name", "Timestamp", "Delta", "Total"], table);
  }
  t(md) {
    md.heading(2, "Workbench Contributions Blocking Restore");
    const timings = $Wn.as(Extensions2.Workbench).timings;
    md.li(`Total (LifecyclePhase.Starting): ${timings.get(
      1
      /* LifecyclePhase.Starting */
    )?.length} (${timings.get(
      1
      /* LifecyclePhase.Starting */
    )?.reduce((p, c) => p + c[1], 0)}ms)`);
    md.li(`Total (LifecyclePhase.Ready): ${timings.get(
      2
      /* LifecyclePhase.Ready */
    )?.length} (${timings.get(
      2
      /* LifecyclePhase.Ready */
    )?.reduce((p, c) => p + c[1], 0)}ms)`);
    md.blank();
    const marks = this.i.getPerformanceMarks().find((e) => e[0] === "renderer")?.[1].filter((e) => e.name.startsWith("code/willCreateWorkbenchContribution/1") || e.name.startsWith("code/didCreateWorkbenchContribution/1") || e.name.startsWith("code/willCreateWorkbenchContribution/2") || e.name.startsWith("code/didCreateWorkbenchContribution/2"));
    this.s(void 0, md, marks);
  }
  u(md) {
    for (const [source, marks] of this.i.getPerformanceMarks()) {
      md.heading(2, `Raw Perf Marks: ${source}`);
      md.value += "```\n";
      md.value += `Name	Timestamp	Delta	Total
`;
      let lastStartTime = -1;
      let total = 0;
      for (const { name, startTime } of marks) {
        const delta = lastStartTime !== -1 ? startTime - lastStartTime : 0;
        total += delta;
        md.value += `${name}	${startTime}	${delta}	${total}
`;
        lastStartTime = startTime;
      }
      md.value += "```\n";
    }
  }
  v(md) {
    const stats = performance.getEntriesByType("resource").map((entry) => {
      return [entry.name, entry.duration];
    });
    if (!stats.length) {
      return;
    }
    md.heading(2, "Resource Timing Stats");
    md.table(["Name", "Duration"], stats);
  }
};
PerfModelContentProvider = __decorate([
  __param(0, $sG),
  __param(1, $1E),
  __param(2, $U5),
  __param(3, $KL),
  __param(4, $iQb),
  __param(5, $wN),
  __param(6, $Vu),
  __param(7, $RL),
  __param(8, $4Pb)
], PerfModelContentProvider);
var MarkdownBuilder = class {
  constructor() {
    this.value = "";
  }
  heading(level, value) {
    this.value += `${"#".repeat(level)} ${value}

`;
    return this;
  }
  blank() {
    this.value += "\n";
    return this;
  }
  li(value) {
    this.value += `* ${value}
`;
    return this;
  }
  table(header, rows) {
    this.value += this.a(header, rows);
  }
  a(header, rows) {
    let result = "";
    const lengths = [];
    header.forEach((cell, ci) => {
      lengths[ci] = cell.length;
    });
    rows.forEach((row) => {
      row.forEach((cell, ci) => {
        if (typeof cell === "undefined") {
          cell = row[ci] = "-";
        }
        const len = cell.toString().length;
        lengths[ci] = Math.max(len, lengths[ci]);
      });
    });
    header.forEach((cell, ci) => {
      result += `| ${cell + " ".repeat(lengths[ci] - cell.toString().length)} `;
    });
    result += "|\n";
    header.forEach((_cell, ci) => {
      result += `| ${"-".repeat(lengths[ci])} `;
    });
    result += "|\n";
    rows.forEach((row) => {
      row.forEach((cell, ci) => {
        if (typeof cell !== "undefined") {
          result += `| ${cell + " ".repeat(lengths[ci] - cell.toString().length)} `;
        }
      });
      result += "|\n";
    });
    return result;
  }
};

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

// out-build/vs/platform/instantiation/common/instantiationService.js
var _enableAllTracing = false;
var CyclicDependencyError = class extends Error {
  constructor(graph) {
    super("cyclic dependency between services");
    this.message = graph.findCycleSlow() ?? `UNABLE to detect cycle, dumping graph: 
${graph.toString()}`;
  }
};
var $0B = class _$0B {
  constructor(i2 = new $Ok(), j = false, k, l = _enableAllTracing) {
    this.i = i2;
    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($Pk, this);
    this._globalGraph = l ? k?._globalGraph ?? new $9B((e) => e) : void 0;
  }
  dispose() {
    if (!this.f) {
      this.f = true;
      $Xc(this.h);
      this.h.clear();
      for (const candidate of this.g) {
        if ($Wc(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 _$0B {
      dispose() {
        that.h.delete(result);
        super.dispose();
      }
    }(services, this.j, this, this.l);
    this.h.add(result);
    store?.add(result);
    return result;
  }
  invokeFunction(fn, ...args2) {
    this.m();
    const _trace = $$B.traceInvocation(this.l, fn);
    let _done = false;
    try {
      const accessor = {
        get: (id2) => {
          if (_done) {
            throw $ob("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, ...args2);
    } finally {
      _done = true;
      _trace.stop();
    }
  }
  createInstance(ctorOrDescriptor, ...rest) {
    this.m();
    let _trace;
    let result;
    if (ctorOrDescriptor instanceof $Nk) {
      _trace = $$B.traceCreation(this.l, ctorOrDescriptor.ctor);
      result = this.o(ctorOrDescriptor.ctor, ctorOrDescriptor.staticArguments.concat(rest), _trace);
    } else {
      _trace = $$B.traceCreation(this.l, ctorOrDescriptor);
      result = this.o(ctorOrDescriptor, rest, _trace);
    }
    _trace.stop();
    return result;
  }
  o(ctor, args2 = [], _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 : args2.length;
    if (args2.length !== firstServiceArgPos) {
      console.trace(`[createInstance] First service dependency of ${ctor.name} at position ${firstServiceArgPos + 1} conflicts with ${args2.length} static arguments`);
      const delta = firstServiceArgPos - args2.length;
      if (delta > 0) {
        args2 = args2.concat(new Array(delta));
      } else {
        args2 = args2.slice(0, firstServiceArgPos);
      }
    }
    return Reflect.construct(ctor, args2.concat(serviceArgs));
  }
  q(id2, instance2) {
    if (this.i.get(id2) instanceof $Nk) {
      this.i.set(id2, instance2);
    } else if (this.k) {
      this.k.q(id2, instance2);
    } 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 $Nk) {
      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 $9B((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 $Nk) {
          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 $Nk) {
          const instance2 = this.w(data.id, data.desc.ctor, data.desc.staticArguments, data.desc.supportsDelayedInstantiation, data._trace);
          this.q(data.id, instance2);
        }
        graph.removeNode(data);
      }
    }
    return this.r(id2);
  }
  w(id2, ctor, args2 = [], supportsDelayedInstantiation, _trace) {
    if (this.i.get(id2) instanceof $Nk) {
      return this.x(id2, ctor, args2, supportsDelayedInstantiation, _trace, this.g);
    } else if (this.k) {
      return this.k.w(id2, ctor, args2, supportsDelayedInstantiation, _trace);
    } else {
      throw new Error(`illegalState - creating UNKNOWN service instance ${ctor.name}`);
    }
  }
  x(id2, ctor, args2 = [], supportsDelayedInstantiation, _trace, disposeBucket) {
    if (!supportsDelayedInstantiation) {
      const result = this.o(ctor, args2, _trace);
      disposeBucket.add(result);
      return result;
    } else {
      const child = new _$0B(void 0, this.j, this, this.l);
      child.c = String(id2);
      const earlyListeners = /* @__PURE__ */ new Map();
      const idle = new $ci(() => {
        const result = child.o(ctor, args2, _trace);
        for (const [key2, values] of earlyListeners) {
          const candidate = result[key2];
          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, key2) {
          if (!idle.isInitialized) {
            if (typeof key2 === "string" && (key2.startsWith("onDid") || key2.startsWith("onWill"))) {
              let list2 = earlyListeners.get(key2);
              if (!list2) {
                list2 = new $cd();
                earlyListeners.set(key2, list2);
              }
              const event = (callback, thisArg, disposables) => {
                if (idle.isInitialized) {
                  return idle.value[key2](callback, thisArg, disposables);
                } else {
                  const entry = { listener: [callback, thisArg, disposables], disposable: void 0 };
                  const rm = list2.push(entry);
                  const result = $1c(() => {
                    rm();
                    entry.disposable?.dispose();
                  });
                  return result;
                }
              };
              return event;
            }
          }
          if (key2 in target) {
            return target[key2];
          }
          const obj = idle.value;
          let prop = obj[key2];
          if (typeof prop !== "function") {
            return prop;
          }
          prop = prop.bind(obj);
          target[key2] = 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 $$B = class _$$B {
  static {
    this.all = /* @__PURE__ */ new Set();
  }
  static {
    this.c = new class extends _$$B {
      constructor() {
        super(0, null);
      }
      stop() {
      }
      branch() {
        return this;
      }
    }();
  }
  static traceInvocation(_enableTracing, ctor) {
    return !_enableTracing ? _$$B.c : new _$$B(2, ctor.name || new Error().stack.split("\n").slice(3, 4).join("\n"));
  }
  static traceCreation(_enableTracing, ctor) {
    return !_enableTracing ? _$$B.c : new _$$B(1, ctor.name);
  }
  static {
    this.f = 0;
  }
  constructor(type, name) {
    this.type = type;
    this.name = name;
    this.g = Date.now();
    this.h = [];
  }
  branch(id2, first) {
    const child = new _$$B(3, id2.toString());
    this.h.push([id2, first, child]);
    return child;
  }
  stop() {
    const dur = Date.now() - this.g;
    _$$B.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 ${_$$B.f.toFixed(2)}ms)`
    ];
    if (dur > 2 || causedCreation) {
      _$$B.all.add(lines.join("\n"));
    }
  }
};

// out-build/vs/workbench/contrib/performance/browser/inputLatencyContrib.js
var $71b = class $71b2 extends $3c {
  constructor(c, f) {
    super();
    this.c = c;
    this.f = f;
    this.a = this.B(new $4c());
    this.b = this.B(new $8h(() => {
      this.h();
      this.g();
    }, 6e4));
    if (Math.random() <= 0.01) {
      this.g();
    }
  }
  g() {
    this.a.value = Event2.once(this.c.onDidActiveEditorChange)(() => this.b.schedule());
  }
  h() {
    const measurements = inputLatency.getAndClearMeasurements();
    if (!measurements) {
      return;
    }
    this.f.publicLog2("performance.inputLatency", {
      keydown: measurements.keydown,
      input: measurements.input,
      render: measurements.render,
      total: measurements.total,
      sampleCount: measurements.sampleCount
    });
  }
};
$71b = __decorate([
  __param(0, $mJ),
  __param(1, $zv)
], $71b);

// out-build/vs/workbench/contrib/performance/browser/performance.contribution.js
$PL($51b.ID, $51b, { lazy: true });
$Wn.as($ZK.EditorFactory).registerEditorSerializer($61b.Id, class {
  canSerialize() {
    return true;
  }
  serialize() {
    return "";
  }
  deserialize(instantiationService) {
    return instantiationService.createInstance($61b);
  }
});
$hJ(class extends $gJ {
  constructor() {
    super({
      id: "perfview.show",
      title: localize2(8704, "Startup Performance"),
      category: $qn.Developer,
      f1: true
    });
  }
  run(accessor) {
    const editorService = accessor.get($mJ);
    const contrib = $51b.get();
    return editorService.openEditor(contrib.getEditorInput(), { pinned: true });
  }
});
$hJ(class PrintServiceCycles extends $gJ {
  constructor() {
    super({
      id: "perf.insta.printAsyncCycles",
      title: localize2(8705, "Print Service Cycles"),
      category: $qn.Developer,
      f1: true
    });
  }
  run(accessor) {
    const instaService = accessor.get($Pk);
    if (instaService instanceof $0B) {
      const cycle = instaService._globalGraph?.findCycleSlow();
      if (cycle) {
        console.warn(`CYCLE`, cycle);
      } else {
        console.warn(`YEAH, no more cycles`);
      }
    }
  }
});
$hJ(class PrintServiceTraces extends $gJ {
  constructor() {
    super({
      id: "perf.insta.printTraces",
      title: localize2(8706, "Print Service Traces"),
      category: $qn.Developer,
      f1: true
    });
  }
  run() {
    if ($$B.all.size === 0) {
      console.log("Enable via `instantiationService.ts#_enableAllTracing`");
      return;
    }
    for (const item of $$B.all) {
      console.log(item);
    }
  }
});
$hJ(class PrintEventProfiling extends $gJ {
  constructor() {
    super({
      id: "perf.event.profiling",
      title: localize2(8707, "Print Emitter Profiles"),
      category: $qn.Developer,
      f1: true
    });
  }
  run() {
    if ($ve.all.size === 0) {
      console.log("USE `EmitterOptions._profName` to enable profiling");
      return;
    }
    for (const item of $ve.all) {
      console.log(`${item.name}: ${item.invocationCount} invocations COST ${item.elapsedOverall}ms, ${item.listenerCount} listeners, avg cost is ${item.durations.reduce((a, b) => a + b, 0) / item.durations.length}ms`);
    }
  }
});
$Wn.as(Extensions2.Workbench).registerWorkbenchContribution(
  $71b,
  4
  /* LifecyclePhase.Eventually */
);

// out-build/vs/workbench/contrib/contextmenu/browser/contextmenu.contribution.js
var ContextMenuContribution = class ContextMenuContribution2 extends $3c {
  constructor(layoutService, contextMenuService) {
    super();
    const update = (visible) => layoutService.activeContainer.classList.toggle("context-menu-visible", visible);
    this.B(contextMenuService.onDidShowContextMenu(() => update(true)));
    this.B(contextMenuService.onDidHideContextMenu(() => update(false)));
  }
};
ContextMenuContribution = __decorate([
  __param(0, $Ulb),
  __param(1, $50)
], ContextMenuContribution);
$Wn.as(Extensions2.Workbench).registerWorkbenchContribution(
  ContextMenuContribution,
  4
  /* LifecyclePhase.Eventually */
);

// out-build/vs/workbench/contrib/notebook/browser/controller/coreActions.js
var $wIb = "_notebook.selectKernel";
var $xIb = localize2(8249, "Notebook");
var $yIb = "inline/cell";
var $zIb = "inline/output";
var $AIb = 100;
var $BIb = 200 + 1;
var CellToolbarOrder;
(function(CellToolbarOrder2) {
  CellToolbarOrder2[CellToolbarOrder2["RunSection"] = 0] = "RunSection";
  CellToolbarOrder2[CellToolbarOrder2["EditCell"] = 1] = "EditCell";
  CellToolbarOrder2[CellToolbarOrder2["ExecuteAboveCells"] = 2] = "ExecuteAboveCells";
  CellToolbarOrder2[CellToolbarOrder2["ExecuteCellAndBelow"] = 3] = "ExecuteCellAndBelow";
  CellToolbarOrder2[CellToolbarOrder2["SaveCell"] = 4] = "SaveCell";
  CellToolbarOrder2[CellToolbarOrder2["SplitCell"] = 5] = "SplitCell";
  CellToolbarOrder2[CellToolbarOrder2["ClearCellOutput"] = 6] = "ClearCellOutput";
})(CellToolbarOrder || (CellToolbarOrder = {}));
var CellOverflowToolbarGroups;
(function(CellOverflowToolbarGroups2) {
  CellOverflowToolbarGroups2["Copy"] = "1_copy";
  CellOverflowToolbarGroups2["Insert"] = "2_insert";
  CellOverflowToolbarGroups2["Edit"] = "3_edit";
  CellOverflowToolbarGroups2["Share"] = "4_share";
})(CellOverflowToolbarGroups || (CellOverflowToolbarGroups = {}));
function $CIb(editorService) {
  const editor = $Qrb(editorService.activeEditorPane);
  if (!editor || !editor.hasModel()) {
    return;
  }
  const activeCell = editor.getActiveCell();
  const selectedCells = editor.getSelectionViewModels();
  return {
    cell: activeCell,
    selectedCells,
    notebookEditor: editor
  };
}
function getWidgetFromUri(accessor, uri) {
  const notebookEditorService = accessor.get($yMb);
  const widget = notebookEditorService.listNotebookEditors().find((widget2) => widget2.hasModel() && widget2.textModel.uri.toString() === uri.toString());
  if (widget && widget.hasModel()) {
    return widget;
  }
  return void 0;
}
function $DIb(accessor, context) {
  const uri = URI.revive(context);
  if (uri) {
    const widget = getWidgetFromUri(accessor, uri);
    if (widget) {
      return {
        notebookEditor: widget
      };
    }
  }
  return void 0;
}
function $EIb(context, targetCell) {
  let foundEditor = void 0;
  for (const [, codeEditor] of context.notebookEditor.codeEditors) {
    if ($oh(codeEditor.getModel()?.uri, targetCell.uri)) {
      foundEditor = codeEditor;
      break;
    }
  }
  return foundEditor;
}
var $FIb = class extends $gJ {
  constructor(desc) {
    if (desc.f1 !== false) {
      desc.f1 = false;
      const f1Menu = {
        id: $bJ.CommandPalette,
        when: $7m.or($SAb, $TAb, $UAb)
      };
      if (!desc.menu) {
        desc.menu = [];
      } else if (!Array.isArray(desc.menu)) {
        desc.menu = [desc.menu];
      }
      desc.menu = [
        ...desc.menu,
        f1Menu
      ];
    }
    desc.category = $xIb;
    super(desc);
  }
  async run(accessor, context, ...additionalArgs) {
    sendEntryTelemetry(accessor, this.desc.id, context);
    if (!this.c(context)) {
      context = this.getEditorContextFromArgsOrActive(accessor, context, ...additionalArgs);
      if (!context) {
        return;
      }
    }
    return this.runWithContext(accessor, context);
  }
  c(context) {
    return !!context && !!context.notebookEditor;
  }
  getEditorContextFromArgsOrActive(accessor, context, ...additionalArgs) {
    return $CIb(accessor.get($mJ));
  }
};
var $GIb = class extends $gJ {
  constructor(desc) {
    if (desc.f1 !== false) {
      desc.f1 = false;
      const f1Menu = {
        id: $bJ.CommandPalette,
        when: $SAb
      };
      if (!desc.menu) {
        desc.menu = [];
      } else if (!Array.isArray(desc.menu)) {
        desc.menu = [desc.menu];
      }
      desc.menu = [
        ...desc.menu,
        f1Menu
      ];
    }
    desc.category = $xIb;
    super(desc);
  }
  parseArgs(accessor, ...args2) {
    return void 0;
  }
  /**
   * The action/command args are resolved in following order
   * `run(accessor, cellToolbarContext)` from cell toolbar
   * `run(accessor, ...args)` from command service with arguments
   * `run(accessor, undefined)` from keyboard shortcuts, command palatte, etc
   */
  async run(accessor, ...additionalArgs) {
    const context = additionalArgs[0];
    sendEntryTelemetry(accessor, this.desc.id, context);
    const isFromCellToolbar = isCellToolbarContext(context);
    if (isFromCellToolbar) {
      return this.runWithContext(accessor, context);
    }
    const parsedArgs = this.parseArgs(accessor, ...additionalArgs);
    if (parsedArgs) {
      return this.runWithContext(accessor, parsedArgs);
    }
    const editor = $JIb(accessor);
    if (editor) {
      const selectedCellRange = editor.getSelections().length === 0 ? [editor.getFocus()] : editor.getSelections();
      return this.runWithContext(accessor, {
        ui: false,
        notebookEditor: editor,
        selectedCells: $Srb(editor, selectedCellRange)
      });
    }
  }
};
var $HIb = class extends $FIb {
  d(context) {
    return !!context && !!context.notebookEditor && !!context.cell;
  }
  g(accessor, context, ...additionalArgs) {
    return void 0;
  }
  async run(accessor, context, ...additionalArgs) {
    sendEntryTelemetry(accessor, this.desc.id, context);
    if (this.d(context)) {
      return this.runWithContext(accessor, context);
    }
    const contextFromArgs = this.g(accessor, context, ...additionalArgs);
    if (contextFromArgs) {
      return this.runWithContext(accessor, contextFromArgs);
    }
    const activeEditorContext = this.getEditorContextFromArgsOrActive(accessor);
    if (this.d(activeEditorContext)) {
      return this.runWithContext(accessor, activeEditorContext);
    }
  }
};
var $IIb = $7m.or($7m.greater($oBb.key, 0), $7m.greater($pBb.key, 0));
function sendEntryTelemetry(accessor, id2, context) {
  if (context) {
    const telemetryService = accessor.get($zv);
    if (context.source) {
      telemetryService.publicLog2("workbenchActionExecuted", { id: id2, from: context.source });
    } else if (URI.isUri(context)) {
      telemetryService.publicLog2("workbenchActionExecuted", { id: id2, from: "cellEditorContextMenu" });
    } else if (context && "from" in context && context.from === "cellContainer") {
      telemetryService.publicLog2("workbenchActionExecuted", { id: id2, from: "cellContainer" });
    } else {
      const from = isCellToolbarContext(context) ? "cellToolbar" : $kL(context) ? "editorToolbar" : "other";
      telemetryService.publicLog2("workbenchActionExecuted", { id: id2, from });
    }
  }
}
function isCellToolbarContext(context) {
  return !!context && !!context.notebookEditor && context.$mid === 13;
}
function isMultiCellArgs(arg) {
  if (arg === void 0) {
    return false;
  }
  const ranges = arg.ranges;
  if (!ranges) {
    return false;
  }
  if (!Array.isArray(ranges) || ranges.some((range) => !$EL(range))) {
    return false;
  }
  if (arg.document) {
    const uri = URI.revive(arg.document);
    if (!uri) {
      return false;
    }
  }
  return true;
}
function $JIb(accessor, context) {
  const editorFromUri = $DIb(accessor, context)?.notebookEditor;
  if (editorFromUri) {
    return editorFromUri;
  }
  const editor = $Qrb(accessor.get($mJ).activeEditorPane);
  if (!editor || !editor.hasModel()) {
    return;
  }
  return editor;
}
function $KIb(accessor, ...args2) {
  const firstArg = args2[0];
  if (isMultiCellArgs(firstArg)) {
    const editor = $JIb(accessor, firstArg.document);
    if (!editor) {
      return;
    }
    const ranges = firstArg.ranges;
    const selectedCells = ranges.map((range) => editor.getCellsInRange(range).slice(0)).flat();
    const autoReveal = firstArg.autoReveal;
    return {
      ui: false,
      notebookEditor: editor,
      selectedCells,
      autoReveal
    };
  }
  if ($EL(firstArg)) {
    const secondArg = args2[1];
    const editor = $JIb(accessor, secondArg);
    if (!editor) {
      return;
    }
    return {
      ui: false,
      notebookEditor: editor,
      selectedCells: editor.getCellsInRange(firstArg)
    };
  }
  const context = $CIb(accessor.get($mJ));
  return context ? {
    ui: false,
    notebookEditor: context.notebookEditor,
    selectedCells: context.selectedCells ?? [],
    cell: context.cell
  } : void 0;
}
var $LIb = [
  {
    isOptional: true,
    name: "options",
    description: "The cell range options",
    schema: {
      "type": "object",
      "required": ["ranges"],
      "properties": {
        "ranges": {
          "type": "array",
          items: [
            {
              "type": "object",
              "required": ["start", "end"],
              "properties": {
                "start": {
                  "type": "number"
                },
                "end": {
                  "type": "number"
                }
              }
            }
          ]
        },
        "document": {
          "type": "object",
          "description": "The document uri"
        },
        "autoReveal": {
          "type": "boolean",
          "description": "Whether the cell should be revealed into view automatically"
        }
      }
    }
  }
];
$dJ.appendMenuItem($bJ.NotebookCellTitle, {
  submenu: $bJ.NotebookCellInsert,
  title: localize(8246, null),
  group: "2_insert",
  when: $1Ab.isEqualTo(true)
});
$dJ.appendMenuItem($bJ.EditorContext, {
  submenu: $bJ.NotebookCellTitle,
  title: localize(8247, null),
  group: "2_insert",
  when: $WAb
});
$dJ.appendMenuItem($bJ.NotebookCellTitle, {
  title: localize(8248, null),
  submenu: $bJ.EditorContextShare,
  group: "4_share"
  /* CellOverflowToolbarGroups.Share */
});

// out-build/vs/workbench/contrib/notebook/browser/notebookIcons.js
var $BKb = $9r("notebook-kernel-select", $6l.serverEnvironment, localize(8542, null));
var $CKb = $9r("notebook-execute", $6l.play, localize(8543, null));
var $DKb = $9r("notebook-execute-above", $6l.runAbove, localize(8544, null));
var $EKb = $9r("notebook-execute-below", $6l.runBelow, localize(8545, null));
var $FKb = $9r("notebook-stop", $6l.primitiveSquare, localize(8546, null));
var $GKb = $9r("notebook-delete-cell", $6l.trash, localize(8547, null));
var $HKb = $9r("notebook-execute-all", $6l.runAll, localize(8548, null));
var $IKb = $9r("notebook-edit", $6l.pencil, localize(8549, null));
var $JKb = $9r("notebook-stop-edit", $6l.check, localize(8550, null));
var $KKb = $9r("notebook-move-up", $6l.arrowUp, localize(8551, null));
var $LKb = $9r("notebook-move-down", $6l.arrowDown, localize(8552, null));
var $MKb = $9r("notebook-clear", $6l.clearAll, localize(8553, null));
var $NKb = $9r("notebook-split-cell", $6l.splitVertical, localize(8554, null));
var $OKb = $9r("notebook-state-success", $6l.check, localize(8555, null));
var $PKb = $9r("notebook-state-error", $6l.error, localize(8556, null));
var $QKb = $9r("notebook-state-pending", $6l.clock, localize(8557, null));
var $RKb = $9r("notebook-state-executing", $6l.sync, localize(8558, null));
var $SKb = $9r("notebook-collapsed", $6l.chevronRight, localize(8559, null));
var $TKb = $9r("notebook-expanded", $6l.chevronDown, localize(8560, null));
var $UKb = $9r("notebook-open-as-text", $6l.fileCode, localize(8561, null));
var $VKb = $9r("notebook-revert", $6l.discard, localize(8562, null));
var $WKb = $9r("notebook-diff-cell-toggle-whitespace", $6l.whitespace, localize(8563, null));
var $XKb = $9r("notebook-render-output", $6l.preview, localize(8564, null));
var $YKb = $9r("notebook-mimetype", $6l.code, localize(8565, null));
var $ZKb = $9r("notebook-copy", $6l.copy, localize(8566, null));
var $1Kb = $9r("notebook-diff-editor-previous-change", $6l.arrowUp, localize(8567, null));
var $2Kb = $9r("notebook-diff-editor-next-change", $6l.arrowDown, localize(8568, null));
var $3Kb = $9r("variables-view-icon", $6l.variableGroup, localize(8569, null));

// out-build/vs/workbench/contrib/notebook/browser/viewParts/notebookKernelQuickPickStrategy.js
function isKernelPick(item) {
  return "kernel" in item;
}
function isGroupedKernelsPick(item) {
  return "kernels" in item;
}
function isSourcePick(item) {
  return "action" in item;
}
function isInstallExtensionPick(item) {
  return item.id === "installSuggested" && "extensionIds" in item;
}
function isSearchMarketplacePick(item) {
  return item.id === "install";
}
function isKernelSourceQuickPickItem(item) {
  return "command" in item;
}
function supportAutoRun(item) {
  return "autoRun" in item && !!item.autoRun;
}
var KERNEL_PICKER_UPDATE_DEBOUNCE = 200;
function toKernelQuickPick(kernel, selected) {
  const res = {
    kernel,
    picked: kernel.id === selected?.id,
    label: kernel.label,
    description: kernel.description,
    detail: kernel.detail
  };
  if (kernel.id === selected?.id) {
    if (!res.description) {
      res.description = localize(8609, null);
    } else {
      res.description = localize(8610, null, res.description);
    }
  }
  return res;
}
var KernelPickerStrategyBase = class {
  constructor(c, d, f, g, h3, i2, j, l) {
    this.c = c;
    this.d = d;
    this.f = f;
    this.g = g;
    this.h = h3;
    this.i = i2;
    this.j = j;
    this.l = l;
  }
  async showQuickPick(editor, wantedId, skipAutoRun) {
    const notebook = editor.textModel;
    const scopedContextKeyService = editor.scopedContextKeyService;
    const matchResult = this.m(notebook);
    const { selected, all } = matchResult;
    let newKernel;
    if (wantedId) {
      for (const candidate of all) {
        if (candidate.id === wantedId) {
          newKernel = candidate;
          break;
        }
      }
      if (!newKernel) {
        this.h.warn(`wanted kernel DOES NOT EXIST, wanted: ${wantedId}, all: ${all.map((k) => k.id)}`);
        return false;
      }
    }
    if (newKernel) {
      this.p(notebook, newKernel);
      return true;
    }
    const localDisposableStore = new $2c();
    const quickPick = localDisposableStore.add(this.f.createQuickPick({ useSeparators: true }));
    const quickPickItems = this.n(notebook, matchResult, this.c, scopedContextKeyService);
    if (quickPickItems.length === 1 && supportAutoRun(quickPickItems[0]) && !skipAutoRun) {
      const picked = await this.o(editor, quickPickItems[0], quickPickItems);
      localDisposableStore.dispose();
      return picked;
    }
    quickPick.items = quickPickItems;
    quickPick.canSelectMany = false;
    quickPick.placeholder = selected ? localize(8611, null, this.g.getUriLabel(notebook.uri, { relative: true })) : localize(8612, null, this.g.getUriLabel(notebook.uri, { relative: true }));
    quickPick.busy = this.c.getKernelDetectionTasks(notebook).length > 0;
    const kernelDetectionTaskListener = this.c.onDidChangeKernelDetectionTasks(() => {
      quickPick.busy = this.c.getKernelDetectionTasks(notebook).length > 0;
    });
    const extensionRecommendataionPromise = quickPickItems.length === 0 ? $Hh((token) => this.r(notebook, quickPick, this.i, token)) : void 0;
    const kernelChangeEventListener = Event2.debounce(Event2.any(this.c.onDidChangeSourceActions, this.c.onDidAddKernel, this.c.onDidRemoveKernel, this.c.onDidChangeNotebookAffinity), (last, _current) => last, KERNEL_PICKER_UPDATE_DEBOUNCE)(async () => {
      quickPick.busy = false;
      extensionRecommendataionPromise?.cancel();
      const currentActiveItems = quickPick.activeItems;
      const matchResult2 = this.m(notebook);
      const quickPickItems2 = this.n(notebook, matchResult2, this.c, scopedContextKeyService);
      quickPick.keepScrollPosition = true;
      const activeItems = [];
      for (const item of currentActiveItems) {
        if (isKernelPick(item)) {
          const kernelId = item.kernel.id;
          const sameItem = quickPickItems2.find((pi) => isKernelPick(pi) && pi.kernel.id === kernelId);
          if (sameItem) {
            activeItems.push(sameItem);
          }
        } else if (isSourcePick(item)) {
          const sameItem = quickPickItems2.find((pi) => isSourcePick(pi) && pi.action.action.id === item.action.action.id);
          if (sameItem) {
            activeItems.push(sameItem);
          }
        }
      }
      quickPick.items = quickPickItems2;
      quickPick.activeItems = activeItems;
    }, this);
    const pick = await new Promise((resolve, reject) => {
      localDisposableStore.add(quickPick.onDidAccept(() => {
        const item = quickPick.selectedItems[0];
        if (item) {
          resolve({ selected: item, items: quickPick.items });
        } else {
          resolve({ selected: void 0, items: quickPick.items });
        }
        quickPick.hide();
      }));
      localDisposableStore.add(quickPick.onDidHide(() => {
        kernelDetectionTaskListener.dispose();
        kernelChangeEventListener.dispose();
        quickPick.dispose();
        resolve({ selected: void 0, items: quickPick.items });
      }));
      quickPick.show();
    });
    localDisposableStore.dispose();
    if (pick.selected) {
      return await this.o(editor, pick.selected, pick.items);
    }
    return false;
  }
  m(notebook) {
    return this.c.getMatchingKernel(notebook);
  }
  async o(editor, pick, quickPickItems) {
    if (isKernelPick(pick)) {
      const newKernel = pick.kernel;
      this.p(editor.textModel, newKernel);
      return true;
    }
    if (isSearchMarketplacePick(pick)) {
      await this.q(this.i, this.j, editor.textModel.viewType, []);
    } else if (isInstallExtensionPick(pick)) {
      await this.q(this.i, this.j, editor.textModel.viewType, pick.extensionIds, this.d.quality !== "stable");
    } else if (isSourcePick(pick)) {
      pick.action.runAction();
    }
    return true;
  }
  p(notebook, kernel) {
    this.c.selectKernelForNotebook(kernel, notebook);
  }
  async q(extensionWorkbenchService, extensionService, viewType, extIds, isInsiders) {
    const extensionsToInstall = [];
    const extensionsToEnable = [];
    for (const extId of extIds) {
      const extension = (await extensionWorkbenchService.getExtensions([{ id: extId }], CancellationToken.None))[0];
      if (extension.enablementState === 8 || extension.enablementState === 9 || extension.enablementState === 2) {
        extensionsToEnable.push(extension);
      } else {
        const canInstall = await extensionWorkbenchService.canInstall(extension);
        if (canInstall === true) {
          extensionsToInstall.push(extension);
        }
      }
    }
    if (extensionsToInstall.length || extensionsToEnable.length) {
      await Promise.all([...extensionsToInstall.map(async (extension) => {
        await extensionWorkbenchService.install(
          extension,
          {
            installPreReleaseVersion: isInsiders ?? false,
            context: { skipWalkthrough: true }
          },
          15
          /* ProgressLocation.Notification */
        );
      }), ...extensionsToEnable.map(async (extension) => {
        switch (extension.enablementState) {
          case 9:
            await extensionWorkbenchService.setEnablement(
              [extension],
              11
              /* EnablementState.EnabledWorkspace */
            );
            return;
          case 8:
            await extensionWorkbenchService.setEnablement(
              [extension],
              10
              /* EnablementState.EnabledGlobally */
            );
            return;
          case 2:
            await extensionWorkbenchService.setEnablement(
              [extension],
              3
              /* EnablementState.EnabledByEnvironment */
            );
            return;
          default:
            break;
        }
      })]);
      await extensionService.activateByEvent(`onNotebook:${viewType}`);
      return;
    }
    const pascalCased = viewType.split(/[^a-z0-9]/ig).map($rg).join("");
    await extensionWorkbenchService.openSearch(`@tag:notebookKernel${pascalCased}`);
  }
  async r(notebookTextModel, quickPick, extensionWorkbenchService, token) {
    quickPick.busy = true;
    const newQuickPickItems = await this.s(notebookTextModel, extensionWorkbenchService);
    quickPick.busy = false;
    if (token.isCancellationRequested) {
      return;
    }
    if (newQuickPickItems && quickPick.items.length === 0) {
      quickPick.items = newQuickPickItems;
    }
  }
  async s(notebookTextModel, extensionWorkbenchService) {
    const quickPickItems = [];
    const language = this.t(notebookTextModel);
    const suggestedExtension = language ? this.u(notebookTextModel.viewType, language) : void 0;
    if (suggestedExtension) {
      await extensionWorkbenchService.queryLocal();
      const extensions = extensionWorkbenchService.installed.filter((e) => (e.enablementState === 3 || e.enablementState === 10 || e.enablementState === 11) && suggestedExtension.extensionIds.includes(e.identifier.id));
      if (extensions.length === suggestedExtension.extensionIds.length) {
        return void 0;
      }
      quickPickItems.push({
        id: "installSuggested",
        description: suggestedExtension.displayName ?? suggestedExtension.extensionIds.join(", "),
        label: `$(${$6l.lightbulb.id}) ` + localize(8613, null),
        extensionIds: suggestedExtension.extensionIds
      });
    }
    quickPickItems.push({
      id: "install",
      label: localize(8614, null)
    });
    return quickPickItems;
  }
  /**
   * Examine the most common language in the notebook
   * @param notebookTextModel The notebook text model
   * @returns What the suggested language is for the notebook. Used for kernal installing
   */
  t(notebookTextModel) {
    const metaData = notebookTextModel.metadata;
    let suggestedKernelLanguage = metaData?.metadata?.language_info?.name;
    if (!suggestedKernelLanguage) {
      const cellLanguages = notebookTextModel.cells.map((cell) => cell.language).filter((language) => language !== "markdown");
      if (cellLanguages.length > 1) {
        const firstLanguage = cellLanguages[0];
        if (cellLanguages.every((language) => language === firstLanguage)) {
          suggestedKernelLanguage = firstLanguage;
        }
      }
    }
    return suggestedKernelLanguage;
  }
  /**
   * Given a language and notebook view type suggest a kernel for installation
   * @param language The language to find a suggested kernel extension for
   * @returns A recommednation object for the recommended extension, else undefined
   */
  u(viewType, language) {
    const recommendation = $Prb.get(viewType)?.get(language);
    return recommendation;
  }
};
var $oLb = class $oLb2 extends KernelPickerStrategyBase {
  constructor(_notebookKernelService, _productService, _quickInputService, _labelService, _logService, _extensionWorkbenchService, _extensionService, _commandService, v, w) {
    super(_notebookKernelService, _productService, _quickInputService, _labelService, _logService, _extensionWorkbenchService, _extensionService, _commandService);
    this.v = v;
    this.w = w;
  }
  n(notebookTextModel, matchResult, notebookKernelService, scopedContextKeyService) {
    const quickPickItems = [];
    if (matchResult.selected) {
      const kernelItem = toKernelQuickPick(matchResult.selected, matchResult.selected);
      quickPickItems.push(kernelItem);
    }
    matchResult.suggestions.filter((kernel) => kernel.id !== matchResult.selected?.id).map((kernel) => toKernelQuickPick(kernel, matchResult.selected)).forEach((kernel) => {
      quickPickItems.push(kernel);
    });
    const shouldAutoRun = quickPickItems.length === 0;
    if (quickPickItems.length > 0) {
      quickPickItems.push({
        type: "separator"
      });
    }
    quickPickItems.push({
      id: "selectAnother",
      label: localize(8615, null),
      autoRun: shouldAutoRun
    });
    return quickPickItems;
  }
  p(notebook, kernel) {
    const currentInfo = this.c.getMatchingKernel(notebook);
    if (currentInfo.selected) {
      this.v.addMostRecentKernel(currentInfo.selected);
    }
    super.p(notebook, kernel);
    this.v.addMostRecentKernel(kernel);
  }
  m(notebook) {
    const { selected, all } = this.v.getKernels(notebook);
    const matchingResult = this.c.getMatchingKernel(notebook);
    return {
      selected,
      all: matchingResult.all,
      suggestions: all,
      hidden: []
    };
  }
  async o(editor, pick, items) {
    if (pick.id === "selectAnother") {
      return this.B(editor, items.length === 1 && items[0] === pick);
    }
    return super.o(editor, pick, items);
  }
  async B(editor, kernelListEmpty) {
    const notebook = editor.textModel;
    const disposables = new $2c();
    const quickPick = disposables.add(this.f.createQuickPick({ useSeparators: true }));
    const quickPickItem = await new Promise((resolve) => {
      quickPick.title = kernelListEmpty ? localize(8616, null) : localize(8617, null);
      quickPick.placeholder = localize(8618, null);
      quickPick.busy = true;
      quickPick.buttons = [this.f.backButton];
      quickPick.show();
      disposables.add(quickPick.onDidTriggerButton((button) => {
        if (button === this.f.backButton) {
          resolve(button);
        }
      }));
      disposables.add(quickPick.onDidTriggerItemButton(async (e) => {
        if (isKernelSourceQuickPickItem(e.item) && e.item.documentation !== void 0) {
          const uri = URI.isUri(e.item.documentation) ? URI.parse(e.item.documentation) : await this.l.executeCommand(e.item.documentation);
          void this.w.open(uri, { openExternal: true });
        }
      }));
      disposables.add(quickPick.onDidAccept(async () => {
        resolve(quickPick.selectedItems[0]);
      }));
      disposables.add(quickPick.onDidHide(() => {
        resolve(void 0);
      }));
      this.C(editor).then((quickPickItems) => {
        quickPick.items = quickPickItems;
        if (quickPick.items.length > 0) {
          quickPick.busy = false;
        }
      });
      disposables.add(Event2.debounce(Event2.any(this.c.onDidChangeSourceActions, this.c.onDidAddKernel, this.c.onDidRemoveKernel), (last, _current) => last, KERNEL_PICKER_UPDATE_DEBOUNCE)(async () => {
        quickPick.busy = true;
        const quickPickItems = await this.C(editor);
        quickPick.items = quickPickItems;
        quickPick.busy = false;
      }));
    });
    quickPick.hide();
    disposables.dispose();
    if (quickPickItem === this.f.backButton) {
      return this.showQuickPick(editor, void 0, true);
    }
    if (quickPickItem) {
      const selectedKernelPickItem = quickPickItem;
      if (isKernelSourceQuickPickItem(selectedKernelPickItem)) {
        try {
          const selectedKernelId = await this.E(notebook, selectedKernelPickItem.command);
          if (selectedKernelId) {
            const { all } = await this.m(notebook);
            const kernel = all.find((kernel2) => kernel2.id === `ms-toolsai.jupyter/${selectedKernelId}`);
            if (kernel) {
              await this.p(notebook, kernel);
              return true;
            }
            return true;
          } else {
            return this.B(editor, false);
          }
        } catch (ex) {
          return false;
        }
      } else if (isKernelPick(selectedKernelPickItem)) {
        await this.p(notebook, selectedKernelPickItem.kernel);
        return true;
      } else if (isGroupedKernelsPick(selectedKernelPickItem)) {
        await this.D(notebook, selectedKernelPickItem.label, selectedKernelPickItem.kernels);
        return true;
      } else if (isSourcePick(selectedKernelPickItem)) {
        try {
          await selectedKernelPickItem.action.runAction();
          return true;
        } catch (ex) {
          return false;
        }
      } else if (isSearchMarketplacePick(selectedKernelPickItem)) {
        await this.q(this.i, this.j, editor.textModel.viewType, []);
        return true;
      } else if (isInstallExtensionPick(selectedKernelPickItem)) {
        await this.q(this.i, this.j, editor.textModel.viewType, selectedKernelPickItem.extensionIds, this.d.quality !== "stable");
        return this.B(editor, false);
      }
    }
    return false;
  }
  async C(editor) {
    const notebook = editor.textModel;
    const sourceActionCommands = this.c.getSourceActions(notebook, editor.scopedContextKeyService);
    const actions = await this.c.getKernelSourceActions2(notebook);
    const matchResult = this.m(notebook);
    if (sourceActionCommands.length === 0 && matchResult.all.length === 0 && actions.length === 0) {
      return await this.s(notebook, this.i) ?? [];
    }
    const others = matchResult.all.filter((item) => item.extension.value !== $Nrb);
    const quickPickItems = [];
    for (const group2 of $Eb(others, (a, b) => a.extension.value === b.extension.value ? 0 : 1)) {
      const extension = this.j.extensions.find((extension2) => extension2.identifier.value === group2[0].extension.value);
      const source = extension?.displayName ?? extension?.description ?? group2[0].extension.value;
      if (group2.length > 1) {
        quickPickItems.push({
          label: source,
          kernels: group2
        });
      } else {
        quickPickItems.push({
          label: group2[0].label,
          kernel: group2[0]
        });
      }
    }
    const validActions = actions.filter((action) => action.command);
    quickPickItems.push(...validActions.map((action) => {
      const buttons = action.documentation ? [{
        iconClass: ThemeIcon.asClassName($6l.info),
        tooltip: localize(8619, null)
      }] : [];
      return {
        id: typeof action.command === "string" ? action.command : action.command.id,
        label: action.label,
        description: action.description,
        command: action.command,
        documentation: action.documentation,
        buttons
      };
    }));
    for (const sourceAction of sourceActionCommands) {
      const res = {
        action: sourceAction,
        picked: false,
        label: sourceAction.action.label,
        tooltip: sourceAction.action.tooltip
      };
      quickPickItems.push(res);
    }
    return quickPickItems;
  }
  async D(notebook, source, kernels) {
    const quickPickItems = kernels.map((kernel) => toKernelQuickPick(kernel, void 0));
    const localDisposableStore = new $2c();
    const quickPick = localDisposableStore.add(this.f.createQuickPick({ useSeparators: true }));
    quickPick.items = quickPickItems;
    quickPick.canSelectMany = false;
    quickPick.title = localize(8620, null, source);
    localDisposableStore.add(quickPick.onDidAccept(async () => {
      if (quickPick.selectedItems && quickPick.selectedItems.length > 0 && isKernelPick(quickPick.selectedItems[0])) {
        await this.p(notebook, quickPick.selectedItems[0].kernel);
      }
      quickPick.hide();
      quickPick.dispose();
    }));
    localDisposableStore.add(quickPick.onDidHide(() => {
      localDisposableStore.dispose();
    }));
    quickPick.show();
  }
  async E(notebook, command4) {
    const id2 = typeof command4 === "string" ? command4 : command4.id;
    const args2 = typeof command4 === "string" ? [] : command4.arguments ?? [];
    if (typeof command4 === "string" || !command4.arguments || !Array.isArray(command4.arguments) || command4.arguments.length === 0) {
      args2.unshift({
        uri: notebook.uri,
        $mid: 14
        /* MarshalledId.NotebookActionContext */
      });
    }
    if (typeof command4 === "string") {
      return this.l.executeCommand(id2);
    } else {
      return this.l.executeCommand(id2, ...args2);
    }
  }
  static updateKernelStatusAction(notebook, action, notebookKernelService, notebookKernelHistoryService) {
    const detectionTasks = notebookKernelService.getKernelDetectionTasks(notebook);
    if (detectionTasks.length) {
      const info = notebookKernelService.getMatchingKernel(notebook);
      action.enabled = true;
      action.class = ThemeIcon.asClassName(ThemeIcon.modify($RKb, "spin"));
      if (info.selected) {
        action.label = info.selected.label;
        const kernelInfo = info.selected.description ?? info.selected.detail;
        action.tooltip = kernelInfo ? localize(8621, null, kernelInfo) : localize(8622, null);
      } else {
        action.label = localize(8623, null);
      }
      return;
    }
    const runningActions = notebookKernelService.getRunningSourceActions(notebook);
    const updateActionFromSourceAction = (sourceAction, running) => {
      const sAction = sourceAction.action;
      action.class = running ? ThemeIcon.asClassName(ThemeIcon.modify($RKb, "spin")) : ThemeIcon.asClassName($BKb);
      action.label = sAction.label;
      action.enabled = true;
    };
    if (runningActions.length) {
      return updateActionFromSourceAction(runningActions[0], true);
    }
    const { selected } = notebookKernelHistoryService.getKernels(notebook);
    if (selected) {
      action.label = selected.label;
      action.class = ThemeIcon.asClassName($BKb);
      action.tooltip = selected.description ?? selected.detail ?? "";
    } else {
      action.label = localize(8624, null);
      action.class = ThemeIcon.asClassName($BKb);
      action.tooltip = "";
    }
  }
  static async resolveKernel(notebook, notebookKernelService, notebookKernelHistoryService, commandService) {
    const alreadySelected = notebookKernelHistoryService.getKernels(notebook);
    if (alreadySelected.selected) {
      return alreadySelected.selected;
    }
    await commandService.executeCommand($wIb);
    const { selected } = notebookKernelHistoryService.getKernels(notebook);
    return selected;
  }
};
$oLb = __decorate([
  __param(0, $CL),
  __param(1, $Vu),
  __param(2, $1M),
  __param(3, $ZI),
  __param(4, $wn),
  __param(5, $vzb),
  __param(6, $wN),
  __param(7, $sn),
  __param(8, $DL),
  __param(9, $O4)
], $oLb);

// out-build/vs/workbench/contrib/notebook/browser/viewParts/notebookKernelView.js
function getEditorFromContext(editorService, context) {
  let editor;
  if (context !== void 0 && "notebookEditorId" in context) {
    const editorId = context.notebookEditorId;
    const matchingEditor = editorService.visibleEditorPanes.find((editorPane) => {
      const notebookEditor = $Qrb(editorPane);
      return notebookEditor?.getId() === editorId;
    });
    editor = $Qrb(matchingEditor);
  } else if (context !== void 0 && "notebookEditor" in context) {
    editor = context?.notebookEditor;
  } else {
    editor = $Qrb(editorService.activeEditorPane);
  }
  return editor;
}
$hJ(class extends $gJ {
  constructor() {
    super({
      id: $wIb,
      category: $xIb,
      title: localize2(8626, "Select Notebook Kernel"),
      icon: $BKb,
      f1: true,
      precondition: $SAb,
      menu: [{
        id: $bJ.EditorTitle,
        when: $7m.and($SAb, $7m.notEquals("config.notebook.globalToolbar", true)),
        group: "navigation",
        order: -10
      }, {
        id: $bJ.NotebookToolbar,
        when: $7m.equals("config.notebook.globalToolbar", true),
        group: "status",
        order: -10
      }, {
        id: $bJ.InteractiveToolbar,
        when: $oBb.notEqualsTo(0),
        group: "status",
        order: -10
      }],
      metadata: {
        description: localize(8625, null),
        args: [
          {
            name: "kernelInfo",
            description: "The kernel info",
            schema: {
              "type": "object",
              "required": ["id", "extension"],
              "properties": {
                "id": {
                  "type": "string"
                },
                "extension": {
                  "type": "string"
                },
                "notebookEditorId": {
                  "type": "string"
                }
              }
            }
          }
        ]
      }
    });
  }
  async run(accessor, context) {
    const instantiationService = accessor.get($Pk);
    const editorService = accessor.get($mJ);
    const editor = getEditorFromContext(editorService, context);
    if (!editor || !editor.hasModel()) {
      return false;
    }
    let controllerId = context && "id" in context ? context.id : void 0;
    let extensionId = context && "extension" in context ? context.extension : void 0;
    if (controllerId && (typeof controllerId !== "string" || typeof extensionId !== "string")) {
      controllerId = void 0;
      extensionId = void 0;
    }
    const notebook = editor.textModel;
    const notebookKernelService = accessor.get($CL);
    const matchResult = notebookKernelService.getMatchingKernel(notebook);
    const { selected } = matchResult;
    if (selected && controllerId && selected.id === controllerId && $5z.equals(selected.extension, extensionId)) {
      return true;
    }
    const wantedKernelId = controllerId ? `${extensionId}/${controllerId}` : void 0;
    const strategy = instantiationService.createInstance($oLb);
    return strategy.showQuickPick(editor, wantedKernelId);
  }
});
var $pLb = class $pLb2 extends $U1 {
  constructor(actualAction, b, options3, c, g) {
    super(void 0, new $Um("fakeAction", void 0, ThemeIcon.asClassName($BKb), true, (event) => actualAction.run(event)), { ...options3, label: false, icon: true });
    this.b = b;
    this.c = c;
    this.g = g;
    this.B(b.onDidChangeModel(this.m, this));
    this.B(c.onDidAddKernel(this.m, this));
    this.B(c.onDidRemoveKernel(this.m, this));
    this.B(c.onDidChangeNotebookAffinity(this.m, this));
    this.B(c.onDidChangeSelectedNotebooks(this.m, this));
    this.B(c.onDidChangeSourceActions(this.m, this));
    this.B(c.onDidChangeKernelDetectionTasks(this.m, this));
  }
  render(container2) {
    this.m();
    super.render(container2);
    container2.classList.add("kernel-action-view-item");
    this.a = document.createElement("a");
    container2.appendChild(this.a);
    this.C();
  }
  C() {
    if (this.a) {
      this.a.classList.add("kernel-label");
      this.a.innerText = this._action.label;
    }
  }
  m() {
    const notebook = this.b.textModel;
    if (!notebook) {
      this.n();
      return;
    }
    $oLb.updateKernelStatusAction(notebook, this._action, this.c, this.g);
    this.I();
  }
  n() {
    this._action.enabled = false;
    this._action.label = "";
    this._action.class = "";
  }
};
$pLb = __decorate([
  __param(3, $CL),
  __param(4, $DL)
], $pLb);

// out-build/vs/workbench/contrib/notebook/common/notebookPerformance.js
var $srb = class {
  constructor() {
    this.a = {};
  }
  get value() {
    return { ...this.a };
  }
  mark(name) {
    if (this.a[name]) {
      console.error(`Skipping overwrite of notebook perf value: ${name}`);
      return;
    }
    this.a[name] = Date.now();
  }
};

// out-build/vs/workbench/contrib/notebook/browser/notebookEditor.js
var $ILb_1;
var NOTEBOOK_EDITOR_VIEW_STATE_PREFERENCE_KEY = "NotebookEditorViewState";
var $ILb = class $ILb2 extends $5tb {
  static {
    $ILb_1 = this;
  }
  static {
    this.ID = $bM;
  }
  get onDidFocus() {
    return this.r.event;
  }
  get onDidBlur() {
    return this.s.event;
  }
  constructor(group2, telemetryService, themeService, eb, storageService, fb, gb, hb, ib, jb, configurationService, kb, lb, mb, nb, ob, pb, qb) {
    super($ILb_1.ID, group2, telemetryService, themeService, storageService);
    this.eb = eb;
    this.fb = fb;
    this.gb = gb;
    this.hb = hb;
    this.ib = ib;
    this.jb = jb;
    this.kb = kb;
    this.lb = lb;
    this.mb = mb;
    this.nb = nb;
    this.ob = ob;
    this.pb = pb;
    this.qb = qb;
    this.b = this.B(new $2c());
    this.c = this.B(new $2c());
    this.f = { value: void 0 };
    this.m = this.B(new $4c());
    this.r = this.B(new $ze());
    this.s = this.B(new $ze());
    this.u = this.B(new $ze());
    this.onDidChangeModel = this.u.event;
    this.cb = this.B(new $ze());
    this.onDidChangeSelection = this.cb.event;
    this.db = this.B(new $ze());
    this.onDidChangeScroll = this.db.event;
    this.a = this.ab(gb, configurationService, NOTEBOOK_EDITOR_VIEW_STATE_PREFERENCE_KEY);
    this.B(this.jb.onDidChangeFileSystemProviderCapabilities((e) => this.rb(e.scheme)));
    this.B(this.jb.onDidChangeFileSystemProviderRegistrations((e) => this.rb(e.scheme)));
  }
  rb(scheme) {
    if (this.input instanceof $trb && this.input.resource?.scheme === scheme) {
      this.tb(this.input);
    }
  }
  sb(input) {
    if (this.input === input) {
      this.tb(input);
    }
  }
  tb(input) {
    this.f.value?.setOptions({ isReadOnly: !!input.isReadonly() });
  }
  get textModel() {
    return this.f.value?.textModel;
  }
  get minimumWidth() {
    return 220;
  }
  get maximumWidth() {
    return Number.POSITIVE_INFINITY;
  }
  // these setters need to exist because this extends from EditorPane
  set minimumWidth(value) {
  }
  set maximumWidth(value) {
  }
  //#region Editor Core
  get scopedContextKeyService() {
    return this.f.value?.scopedContextKeyService;
  }
  Y(parent) {
    this.g = $bk(parent, $(".notebook-editor"));
    this.g.id = `notebook-editor-element-${$ps()}`;
  }
  getActionViewItem(action, options3) {
    if (action.id === $wIb) {
      return this.eb.createInstance($pLb, action, this, options3);
    }
    return void 0;
  }
  getControl() {
    return this.f.value;
  }
  setVisible(visible) {
    super.setVisible(visible);
    if (!visible) {
      this.f.value?.onWillHide();
    }
  }
  Z(visible) {
    super.Z(visible);
    this.b.clear();
    this.b.add(this.group.onWillCloseEditor((e) => this.zb(e.editor)));
    this.b.add(this.group.onDidModelChange(() => {
      if (this.gb.activeGroup !== this.group) {
        this.f?.value?.updateEditorFocus();
      }
    }));
    if (!visible) {
      this.zb(this.input);
      if (this.input && this.f.value) {
        this.f.value.onWillHide();
      }
    }
  }
  focus() {
    super.focus();
    this.f.value?.focus();
  }
  hasFocus() {
    const value = this.f.value;
    if (!value) {
      return false;
    }
    return !!value && $Nj(value.getDomNode() || $Nj(value.getOverflowContainerDomNode()));
  }
  async setInput(input, options3, context, token, noRetry) {
    try {
      let perfMarksCaptured = false;
      const fileOpenMonitor = $Wh(1e4);
      fileOpenMonitor.then(() => {
        perfMarksCaptured = true;
        this.wb(perf2, input);
      });
      const perf2 = new $srb();
      perf2.mark("startTime");
      this.m.value = input.onDidChangeCapabilities(() => this.sb(input));
      this.c.clear();
      this.f.value?.onWillHide();
      this.f = this.eb.invokeFunction(this.hb.retrieveWidget, this.group.id, input, void 0, this.j?.dimension, this.window);
      if (this.g && this.f.value.getDomNode()) {
        this.g.setAttribute("aria-flowto", this.f.value.getDomNode().id || "");
        $Ej(this.f.value.getDomNode(), this.g);
      }
      this.c.add(this.f.value.onDidChangeModel(() => this.u.fire()));
      this.c.add(this.f.value.onDidChangeActiveCell(() => this.cb.fire({
        reason: 2
        /* EditorPaneSelectionChangeReason.USER */
      })));
      if (this.j) {
        this.f.value.layout(this.j.dimension, this.g, this.j.position);
      }
      await super.setInput(input, options3, context, token);
      const model = await input.resolve(options3, perf2);
      perf2.mark("inputLoaded");
      if (token.isCancellationRequested) {
        return void 0;
      }
      if (!this.f.value) {
        if (noRetry) {
          return void 0;
        }
        return this.setInput(input, options3, context, token, true);
      }
      if (model === null) {
        const knownProvider = this.lb.getViewTypeProvider(input.viewType);
        if (!knownProvider) {
          throw new Error(localize(8477, null, input.viewType));
        }
        await this.mb.whenInitialized;
        const extensionInfo = this.mb.local.find((e) => e.identifier.id === knownProvider);
        throw $qL(new Error(localize(8478, null, input.viewType)), [
          $Zm({
            id: "workbench.notebook.action.installOrEnableMissing",
            label: extensionInfo ? localize(8479, null, input.viewType) : localize(8480, null, input.viewType),
            run: async () => {
              const d = this.lb.onAddViewType((viewType) => {
                if (viewType === input.viewType) {
                  this.fb.openEditor({ resource: input.resource });
                  d.dispose();
                }
              });
              const extensionInfo2 = this.mb.local.find((e) => e.identifier.id === knownProvider);
              try {
                if (extensionInfo2) {
                  await this.mb.setEnablement(
                    extensionInfo2,
                    extensionInfo2.enablementState === 9 ? 11 : 10
                    /* EnablementState.EnabledGlobally */
                  );
                } else {
                  await this.eb.createInstance($sDb, knownProvider).run();
                }
              } catch (ex) {
                this.ob.error(`Failed to install or enable extension ${knownProvider}`, ex);
                d.dispose();
              }
            }
          }),
          $Zm({
            id: "workbench.notebook.action.openAsText",
            label: localize(8481, null),
            run: async () => {
              const backup = await this.nb.resolve({ resource: input.resource, typeId: $sM.create(input.viewType) });
              if (backup) {
                const contents = await $Oi(backup.value);
                this.fb.openEditor({ resource: void 0, contents: contents.toString() });
              } else {
                this.fb.openEditor({ resource: input.resource, options: { override: $1K.id, pinned: true } });
              }
            }
          })
        ], { allowDialog: true });
      }
      this.c.add(model.notebook.onDidChangeContent(() => this.cb.fire({
        reason: 3
        /* EditorPaneSelectionChangeReason.EDIT */
      })));
      const viewState = options3?.viewState ?? this.Ab(input);
      this.f.value.setParentContextKeyService(this.ib);
      this.f.value.setEditorProgressService(this.kb);
      await this.f.value.setModel(model.notebook, viewState, perf2);
      const isReadOnly2 = !!input.isReadonly();
      await this.f.value.setOptions({ ...options3, isReadOnly: isReadOnly2 });
      this.c.add(this.f.value.onDidFocusWidget(() => this.r.fire()));
      this.c.add(this.f.value.onDidBlurWidget(() => this.s.fire()));
      this.c.add(this.gb.createEditorDropTarget(this.f.value.getDomNode(), {
        containsGroup: (group2) => this.group.id === group2.id
      }));
      this.c.add(this.f.value.onDidScroll(() => {
        this.db.fire();
      }));
      perf2.mark("editorLoaded");
      fileOpenMonitor.cancel();
      if (perfMarksCaptured) {
        return;
      }
      this.wb(perf2, input, model.notebook);
      this.xb(model.notebook);
    } catch (e) {
      this.ob.warn("NotebookEditorWidget#setInput failed", e);
      if ($pL(e)) {
        throw e;
      }
      if (e.fileOperationResult === 7) {
        let message;
        if (e instanceof $Gm) {
          message = localize(8482, null, $Sm.formatSize(e.size));
        } else {
          message = localize(8483, null);
        }
        throw $gL(this.group, input, options3, message, this.qb);
      }
      const error = $qL(e instanceof Error ? e : new Error(e ? e.message : ""), [
        $Zm({
          id: "workbench.notebook.action.openInTextEditor",
          label: localize(8484, null),
          run: async () => {
            const activeEditorPane = this.fb.activeEditorPane;
            if (!activeEditorPane) {
              return;
            }
            const activeEditorResource = $mL.getCanonicalUri(activeEditorPane.input);
            if (!activeEditorResource) {
              return;
            }
            if (activeEditorResource.toString() === input.resource?.toString()) {
              return this.fb.openEditor({
                resource: activeEditorResource,
                options: {
                  override: $1K.id,
                  pinned: true
                  // new file gets pinned by default
                }
              });
            }
            return;
          }
        })
      ], { allowDialog: true });
      throw error;
    }
  }
  wb(perf2, input, notebook) {
    const perfMarks = perf2.value;
    const startTime = perfMarks["startTime"];
    const extensionActivated = perfMarks["extensionActivated"];
    const inputLoaded = perfMarks["inputLoaded"];
    const webviewCommLoaded = perfMarks["webviewCommLoaded"];
    const customMarkdownLoaded = perfMarks["customMarkdownLoaded"];
    const editorLoaded = perfMarks["editorLoaded"];
    let extensionActivationTimespan = -1;
    let inputLoadingTimespan = -1;
    let webviewCommLoadingTimespan = -1;
    let customMarkdownLoadingTimespan = -1;
    let editorLoadingTimespan = -1;
    if (startTime !== void 0 && extensionActivated !== void 0) {
      extensionActivationTimespan = extensionActivated - startTime;
      if (inputLoaded !== void 0) {
        inputLoadingTimespan = inputLoaded - extensionActivated;
      }
      if (webviewCommLoaded !== void 0) {
        webviewCommLoadingTimespan = webviewCommLoaded - extensionActivated;
      }
      if (customMarkdownLoaded !== void 0) {
        customMarkdownLoadingTimespan = customMarkdownLoaded - startTime;
      }
      if (editorLoaded !== void 0) {
        editorLoadingTimespan = editorLoaded - startTime;
      }
    }
    let codeCellCount = void 0;
    let mdCellCount = void 0;
    let outputCount = void 0;
    let outputBytes = void 0;
    let codeLength = void 0;
    let markdownLength = void 0;
    let notebookStatsLoaded = void 0;
    if (notebook) {
      const stopWatch = new $te();
      for (const cell of notebook.cells) {
        if (cell.cellKind === CellKind.Code) {
          codeCellCount = (codeCellCount || 0) + 1;
          codeLength = (codeLength || 0) + cell.getTextLength();
          outputCount = (outputCount || 0) + cell.outputs.length;
          outputBytes = (outputBytes || 0) + cell.outputs.reduce((prev, cur) => prev + cur.outputs.reduce((size, item) => size + item.data.byteLength, 0), 0);
        } else {
          mdCellCount = (mdCellCount || 0) + 1;
          markdownLength = (codeLength || 0) + cell.getTextLength();
        }
      }
      notebookStatsLoaded = stopWatch.elapsed();
    }
    this.ob.trace(`[NotebookEditor] open notebook perf ${notebook?.uri.toString() ?? ""} - extensionActivation: ${extensionActivationTimespan}, inputLoad: ${inputLoadingTimespan}, webviewComm: ${webviewCommLoadingTimespan}, customMarkdown: ${customMarkdownLoadingTimespan}, editorLoad: ${editorLoadingTimespan}`);
    this.Q.publicLog2("notebook/editorOpenPerf", {
      scheme: input.resource.scheme,
      ext: $th(input.resource),
      viewType: input.viewType,
      extensionActivated: extensionActivationTimespan,
      inputLoaded: inputLoadingTimespan,
      webviewCommLoaded: webviewCommLoadingTimespan,
      customMarkdownLoaded: customMarkdownLoadingTimespan,
      editorLoaded: editorLoadingTimespan,
      codeCellCount,
      mdCellCount,
      outputCount,
      outputBytes,
      codeLength,
      markdownLength,
      notebookStatsLoaded
    });
  }
  xb(model) {
    this.pb.canPromptRecommendation(model.uri).then((shouldPrompt) => {
      this.Q.publicLog2("notebook/shouldPromptRecommendation", {
        shouldPrompt
      });
    });
  }
  clearInput() {
    this.m.clear();
    if (this.f.value) {
      this.zb(this.input);
      this.f.value.onWillHide();
    }
    super.clearInput();
  }
  setOptions(options3) {
    this.f.value?.setOptions(options3);
    super.setOptions(options3);
  }
  I() {
    this.zb(this.input);
    super.I();
  }
  getViewState() {
    const input = this.input;
    if (!(input instanceof $trb)) {
      return void 0;
    }
    this.zb(input);
    return this.Ab(input);
  }
  getSelection() {
    if (this.f.value) {
      const activeCell = this.f.value.getActiveCell();
      if (activeCell) {
        const cellUri = activeCell.uri;
        return new NotebookEditorSelection(cellUri, activeCell.getSelections());
      }
    }
    return void 0;
  }
  getScrollPosition() {
    const widget = this.getControl();
    if (!widget) {
      throw new Error("Notebook widget has not yet been initialized");
    }
    return {
      scrollTop: widget.scrollTop,
      scrollLeft: 0
    };
  }
  setScrollPosition(scrollPosition) {
    const editor = this.getControl();
    if (!editor) {
      throw new Error("Control has not yet been initialized");
    }
    editor.setScrollTop(scrollPosition.scrollTop);
  }
  zb(input) {
    if (this.f.value && input instanceof $trb) {
      if (this.f.value.isDisposed) {
        return;
      }
      const state = this.f.value.getEditorViewState();
      this.a.saveEditorState(this.group, input.resource, state);
    }
  }
  Ab(input) {
    const result = this.a.loadEditorState(this.group, input.resource);
    if (result) {
      return result;
    }
    for (const group2 of this.gb.getGroups(
      1
      /* GroupsOrder.MOST_RECENTLY_ACTIVE */
    )) {
      if (group2.activeEditorPane !== this && group2.activeEditorPane instanceof $ILb_1 && group2.activeEditor?.matches(input)) {
        return group2.activeEditorPane.f.value?.getEditorViewState();
      }
    }
    return;
  }
  layout(dimension, position) {
    this.g.classList.toggle("mid-width", dimension.width < 1e3 && dimension.width >= 600);
    this.g.classList.toggle("narrow-width", dimension.width < 600);
    this.j = { dimension, position };
    if (!this.f.value || !(this.input instanceof $trb)) {
      return;
    }
    if (this.input.resource.toString() !== this.textModel?.uri.toString() && this.f.value?.hasModel()) {
      return;
    }
    if (this.isVisible()) {
      this.f.value.layout(dimension, this.g, position);
    }
  }
};
$ILb = $ILb_1 = __decorate([
  __param(1, $zv),
  __param(2, $gs),
  __param(3, $Pk),
  __param(4, $jv),
  __param(5, $mJ),
  __param(6, $iJ),
  __param(7, $yMb),
  __param(8, $on),
  __param(9, $km),
  __param(10, $zG),
  __param(11, $ZJ),
  __param(12, $mrb),
  __param(13, $vzb),
  __param(14, $yG),
  __param(15, $wn),
  __param(16, $uEb),
  __param(17, $TK)
], $ILb);
var NotebookEditorSelection = class _NotebookEditorSelection {
  constructor(a, b) {
    this.a = a;
    this.b = b;
  }
  compare(other) {
    if (!(other instanceof _NotebookEditorSelection)) {
      return 3;
    }
    if ($oh(this.a, other.a)) {
      return 1;
    }
    return 3;
  }
  restore(options3) {
    const notebookOptions = {
      cellOptions: {
        resource: this.a,
        options: {
          selection: this.b[0]
        }
      }
    };
    Object.assign(notebookOptions, options3);
    return notebookOptions;
  }
  log() {
    return this.a.fragment;
  }
};

// out-build/vs/workbench/contrib/notebook/browser/notebookExtensionPoint.js
var NotebookEditorContribution = Object.freeze({
  type: "type",
  displayName: "displayName",
  selector: "selector",
  priority: "priority"
});
var NotebookRendererContribution = Object.freeze({
  id: "id",
  displayName: "displayName",
  mimeTypes: "mimeTypes",
  entrypoint: "entrypoint",
  hardDependencies: "dependencies",
  optionalDependencies: "optionalDependencies",
  requiresMessaging: "requiresMessaging"
});
var NotebookPreloadContribution = Object.freeze({
  type: "type",
  entrypoint: "entrypoint",
  localResourceRoots: "localResourceRoots"
});
var notebookProviderContribution = {
  description: localize(8509, null),
  type: "array",
  defaultSnippets: [{ body: [{ type: "", displayName: "", "selector": [{ "filenamePattern": "" }] }] }],
  items: {
    type: "object",
    required: [
      NotebookEditorContribution.type,
      NotebookEditorContribution.displayName,
      NotebookEditorContribution.selector
    ],
    properties: {
      [NotebookEditorContribution.type]: {
        type: "string",
        description: localize(8510, null)
      },
      [NotebookEditorContribution.displayName]: {
        type: "string",
        description: localize(8511, null)
      },
      [NotebookEditorContribution.selector]: {
        type: "array",
        description: localize(8512, null),
        items: {
          type: "object",
          properties: {
            filenamePattern: {
              type: "string",
              description: localize(8513, null)
            },
            excludeFileNamePattern: {
              type: "string",
              description: localize(8514, null)
            }
          }
        }
      },
      [NotebookEditorContribution.priority]: {
        type: "string",
        markdownDeprecationMessage: localize(8515, null),
        enum: [
          NotebookEditorPriority.default,
          NotebookEditorPriority.option
        ],
        markdownEnumDescriptions: [
          localize(8516, null),
          localize(8517, null)
        ],
        default: "default"
      }
    }
  }
};
var defaultRendererSnippet = Object.freeze({ id: "", displayName: "", mimeTypes: [""], entrypoint: "" });
var notebookRendererContribution = {
  description: localize(8518, null),
  type: "array",
  defaultSnippets: [{ body: [defaultRendererSnippet] }],
  items: {
    defaultSnippets: [{ body: defaultRendererSnippet }],
    allOf: [
      {
        type: "object",
        required: [
          NotebookRendererContribution.id,
          NotebookRendererContribution.displayName
        ],
        properties: {
          [NotebookRendererContribution.id]: {
            type: "string",
            description: localize(8519, null)
          },
          [NotebookRendererContribution.displayName]: {
            type: "string",
            description: localize(8520, null)
          },
          [NotebookRendererContribution.hardDependencies]: {
            type: "array",
            uniqueItems: true,
            items: { type: "string" },
            markdownDescription: localize(8521, null)
          },
          [NotebookRendererContribution.optionalDependencies]: {
            type: "array",
            uniqueItems: true,
            items: { type: "string" },
            markdownDescription: localize(8522, null)
          },
          [NotebookRendererContribution.requiresMessaging]: {
            default: "never",
            enum: [
              "always",
              "optional",
              "never"
            ],
            enumDescriptions: [
              localize(8523, null),
              localize(8524, null),
              localize(8525, null)
            ],
            description: localize(8526, null)
          }
        }
      },
      {
        oneOf: [
          {
            required: [
              NotebookRendererContribution.entrypoint,
              NotebookRendererContribution.mimeTypes
            ],
            properties: {
              [NotebookRendererContribution.mimeTypes]: {
                type: "array",
                description: localize(8527, null),
                items: {
                  type: "string"
                }
              },
              [NotebookRendererContribution.entrypoint]: {
                description: localize(8528, null),
                type: "string"
              }
            }
          },
          {
            required: [
              NotebookRendererContribution.entrypoint
            ],
            properties: {
              [NotebookRendererContribution.entrypoint]: {
                description: localize(8529, null),
                type: "object",
                required: ["extends", "path"],
                properties: {
                  extends: {
                    type: "string",
                    description: localize(8530, null)
                  },
                  path: {
                    type: "string",
                    description: localize(8531, null)
                  }
                }
              }
            }
          }
        ]
      }
    ]
  }
};
var notebookPreloadContribution = {
  description: localize(8532, null),
  type: "array",
  defaultSnippets: [{ body: [{ type: "", entrypoint: "" }] }],
  items: {
    type: "object",
    required: [
      NotebookPreloadContribution.type,
      NotebookPreloadContribution.entrypoint
    ],
    properties: {
      [NotebookPreloadContribution.type]: {
        type: "string",
        description: localize(8533, null)
      },
      [NotebookPreloadContribution.entrypoint]: {
        type: "string",
        description: localize(8534, null)
      },
      [NotebookPreloadContribution.localResourceRoots]: {
        type: "array",
        items: { type: "string" },
        description: localize(8535, null)
      }
    }
  }
};
var $81b = $tN.registerExtensionPoint({
  extensionPoint: "notebooks",
  jsonSchema: notebookProviderContribution,
  activationEventsGenerator: (contribs, result) => {
    for (const contrib of contribs) {
      if (contrib.type) {
        result.push(`onNotebookSerializer:${contrib.type}`);
      }
    }
  }
});
var $91b = $tN.registerExtensionPoint({
  extensionPoint: "notebookRenderer",
  jsonSchema: notebookRendererContribution,
  activationEventsGenerator: (contribs, result) => {
    for (const contrib of contribs) {
      if (contrib.id) {
        result.push(`onRenderer:${contrib.id}`);
      }
    }
  }
});
var $01b = $tN.registerExtensionPoint({
  extensionPoint: "notebookPreload",
  jsonSchema: notebookPreloadContribution
});
var NotebooksDataRenderer = class extends $3c {
  constructor() {
    super(...arguments);
    this.type = "table";
  }
  shouldRender(manifest) {
    return !!manifest.contributes?.notebooks;
  }
  render(manifest) {
    const contrib = manifest.contributes?.notebooks || [];
    if (!contrib.length) {
      return { data: { headers: [], rows: [] }, dispose: () => {
      } };
    }
    const headers = [
      localize(8536, null),
      localize(8537, null)
    ];
    const rows = contrib.sort((a, b) => a.type.localeCompare(b.type)).map((notebook) => {
      return [
        notebook.type,
        notebook.displayName
      ];
    });
    return {
      data: {
        headers,
        rows
      },
      dispose: () => {
      }
    };
  }
};
var NotebookRenderersDataRenderer = class extends $3c {
  constructor() {
    super(...arguments);
    this.type = "table";
  }
  shouldRender(manifest) {
    return !!manifest.contributes?.notebookRenderer;
  }
  render(manifest) {
    const contrib = manifest.contributes?.notebookRenderer || [];
    if (!contrib.length) {
      return { data: { headers: [], rows: [] }, dispose: () => {
      } };
    }
    const headers = [
      localize(8538, null),
      localize(8539, null)
    ];
    const rows = contrib.sort((a, b) => a.displayName.localeCompare(b.displayName)).map((notebookRenderer) => {
      return [
        notebookRenderer.displayName,
        notebookRenderer.mimeTypes.join(",")
      ];
    });
    return {
      data: {
        headers,
        rows
      },
      dispose: () => {
      }
    };
  }
};
$Wn.as(Extensions3.ExtensionFeaturesRegistry).registerExtensionFeature({
  id: "notebooks",
  label: localize(8540, null),
  access: {
    canToggle: false
  },
  renderer: new $Nk(NotebooksDataRenderer)
});
$Wn.as(Extensions3.ExtensionFeaturesRegistry).registerExtensionFeature({
  id: "notebookRenderer",
  label: localize(8541, null),
  access: {
    canToggle: false
  },
  renderer: new $Nk(NotebookRenderersDataRenderer)
});

// out-build/vs/workbench/contrib/notebook/common/notebookDiffEditorInput.js
var $$1b_1;
var NotebookDiffEditorModel = class extends $rG {
  constructor(original, modified) {
    super();
    this.original = original;
    this.modified = modified;
  }
};
var $$1b = class $$1b2 extends $fub {
  static {
    $$1b_1 = this;
  }
  static create(instantiationService, resource, name, description, originalResource, viewType) {
    const original = $trb.getOrCreate(instantiationService, originalResource, void 0, viewType);
    const modified = $trb.getOrCreate(instantiationService, resource, void 0, viewType);
    return instantiationService.createInstance($$1b_1, name, description, original, modified, viewType);
  }
  static {
    this.ID = "workbench.input.diffNotebookInput";
  }
  get resource() {
    return this.modified.resource;
  }
  get editorId() {
    return this.viewType;
  }
  constructor(name, description, original, modified, viewType, editorService) {
    super(name, description, original, modified, void 0, editorService);
    this.original = original;
    this.modified = modified;
    this.viewType = viewType;
    this.D = null;
    this.F = null;
    this.G = void 0;
  }
  get typeId() {
    return $$1b_1.ID;
  }
  async resolve() {
    const [originalEditorModel, modifiedEditorModel] = await Promise.all([
      this.original.resolve(),
      this.modified.resolve()
    ]);
    this.G?.dispose();
    if (!modifiedEditorModel) {
      throw new Error(`Fail to resolve modified editor model for resource ${this.modified.resource} with notebookType ${this.viewType}`);
    }
    if (!originalEditorModel) {
      throw new Error(`Fail to resolve original editor model for resource ${this.original.resource} with notebookType ${this.viewType}`);
    }
    this.F = originalEditorModel;
    this.D = modifiedEditorModel;
    this.G = new NotebookDiffEditorModel(this.F, this.D);
    return this.G;
  }
  toUntyped() {
    const original = { resource: this.original.resource };
    const modified = { resource: this.resource };
    return {
      original,
      modified,
      primary: modified,
      secondary: original,
      options: {
        override: this.viewType
      }
    };
  }
  matches(otherInput) {
    if (this === otherInput) {
      return true;
    }
    if (otherInput instanceof $$1b_1) {
      return this.modified.matches(otherInput.modified) && this.original.matches(otherInput.original) && this.viewType === otherInput.viewType;
    }
    if ($9K(otherInput)) {
      return this.modified.matches(otherInput.modified) && this.original.matches(otherInput.original) && this.editorId !== void 0 && (this.editorId === otherInput.options?.override || otherInput.options?.override === void 0);
    }
    return false;
  }
  dispose() {
    super.dispose();
    this.G?.dispose();
    this.G = void 0;
    this.original.dispose();
    this.modified.dispose();
    this.F = null;
    this.D = null;
  }
};
$$1b = $$1b_1 = __decorate([
  __param(5, $mJ)
], $$1b);

// out-build/vs/workbench/contrib/notebook/common/model/cellEdit.js
var $xL = class {
  get label() {
    return this.b === 1 ? "Move Cell" : "Move Cells";
  }
  constructor(resource, a, b, c, d, e, f) {
    this.resource = resource;
    this.a = a;
    this.b = b;
    this.c = c;
    this.d = d;
    this.e = e;
    this.f = f;
    this.type = 0;
    this.code = "undoredo.textBufferEdit";
  }
  undo() {
    if (!this.d.moveCell) {
      throw new Error("Notebook Move Cell not implemented for Undo/Redo");
    }
    this.d.moveCell(this.c, this.b, this.a, this.f, this.e);
  }
  redo() {
    if (!this.d.moveCell) {
      throw new Error("Notebook Move Cell not implemented for Undo/Redo");
    }
    this.d.moveCell(this.a, this.b, this.c, this.e, this.f);
  }
};
var $yL = class {
  get label() {
    if (this.a.length === 1 && this.a[0][1].length === 0) {
      return this.a[0][2].length > 1 ? "Insert Cells" : "Insert Cell";
    }
    if (this.a.length === 1 && this.a[0][2].length === 0) {
      return this.a[0][1].length > 1 ? "Delete Cells" : "Delete Cell";
    }
    return "Insert Cell";
  }
  constructor(resource, a, b, c, d) {
    this.resource = resource;
    this.a = a;
    this.b = b;
    this.c = c;
    this.d = d;
    this.type = 0;
    this.code = "undoredo.textBufferEdit";
  }
  undo() {
    if (!this.b.replaceCell) {
      throw new Error("Notebook Replace Cell not implemented for Undo/Redo");
    }
    this.a.forEach((diff3) => {
      this.b.replaceCell(diff3[0], diff3[2].length, diff3[1], this.c);
    });
  }
  redo() {
    if (!this.b.replaceCell) {
      throw new Error("Notebook Replace Cell not implemented for Undo/Redo");
    }
    this.a.reverse().forEach((diff3) => {
      this.b.replaceCell(diff3[0], diff3[1].length, diff3[2], this.d);
    });
  }
};
var $zL = class {
  constructor(resource, index, oldMetadata, newMetadata, a) {
    this.resource = resource;
    this.index = index;
    this.oldMetadata = oldMetadata;
    this.newMetadata = newMetadata;
    this.a = a;
    this.type = 0;
    this.label = "Update Cell Metadata";
    this.code = "undoredo.textBufferEdit";
  }
  undo() {
    if (!this.a.updateCellMetadata) {
      return;
    }
    this.a.updateCellMetadata(this.index, this.oldMetadata);
  }
  redo() {
    if (!this.a.updateCellMetadata) {
      return;
    }
    this.a.updateCellMetadata(this.index, this.newMetadata);
  }
};

// out-build/vs/workbench/contrib/notebook/common/model/notebookTextModel.js
var $AL_1;
var StackOperation = class {
  get code() {
    return this.d.length === 1 ? this.d[0].code : "undoredo.notebooks.stackOperation";
  }
  get label() {
    return this.d.length === 1 ? this.d[0].label : "edit";
  }
  constructor(textModel, undoRedoGroup, l, m, selectionState, beginAlternativeVersionId) {
    this.textModel = textModel;
    this.undoRedoGroup = undoRedoGroup;
    this.l = l;
    this.m = m;
    this.d = [];
    this.f = void 0;
    this.g = void 0;
    this.type = 1;
    this.f = selectionState;
    this.h = beginAlternativeVersionId;
    this.j = beginAlternativeVersionId;
  }
  get resources() {
    return [this.textModel.uri];
  }
  get isEmpty() {
    return this.d.length === 0;
  }
  pushEndState(alternativeVersionId, selectionState) {
    this.j = alternativeVersionId;
    this.g = selectionState || this.g;
  }
  pushEditOperation(element, beginSelectionState, resultSelectionState, alternativeVersionId) {
    if (this.d.length === 0) {
      this.f = this.f ?? beginSelectionState;
    }
    this.d.push(element);
    this.g = resultSelectionState;
    this.j = alternativeVersionId;
  }
  async undo() {
    this.l.pause();
    try {
      for (let i2 = this.d.length - 1; i2 >= 0; i2--) {
        await this.d[i2].undo();
      }
      this.m(this.h);
      this.l.fire({
        rawEvents: [],
        synchronous: void 0,
        versionId: this.textModel.versionId,
        endSelectionState: this.f
      });
    } finally {
      this.l.resume();
    }
  }
  async redo() {
    this.l.pause();
    try {
      for (let i2 = 0; i2 < this.d.length; i2++) {
        await this.d[i2].redo();
      }
      this.m(this.j);
      this.l.fire({
        rawEvents: [],
        synchronous: void 0,
        versionId: this.textModel.versionId,
        endSelectionState: this.g
      });
    } finally {
      this.l.resume();
    }
  }
};
var NotebookOperationManager = class {
  constructor(f, g, h3, j) {
    this.f = f;
    this.g = g;
    this.h = h3;
    this.j = j;
    this.d = null;
  }
  isUndoStackEmpty() {
    return this.d === null || this.d.isEmpty;
  }
  pushStackElement(alternativeVersionId, selectionState) {
    if (this.d && !this.d.isEmpty) {
      this.d.pushEndState(alternativeVersionId, selectionState);
      this.g.pushElement(this.d, this.d.undoRedoGroup);
    }
    this.d = null;
  }
  l(beginSelectionState, undoRedoGroup, alternativeVersionId) {
    return this.d ??= new StackOperation(this.f, undoRedoGroup, this.h, this.j, beginSelectionState, alternativeVersionId || "");
  }
  pushEditOperation(element, beginSelectionState, resultSelectionState, alternativeVersionId, undoRedoGroup) {
    const pendingStackOperation = this.l(beginSelectionState, undoRedoGroup, alternativeVersionId);
    pendingStackOperation.pushEditOperation(element, beginSelectionState, resultSelectionState, alternativeVersionId);
  }
};
var NotebookEventEmitter = class extends $Ce {
  get isEmpty() {
    return this.s.isEmpty();
  }
  isDirtyEvent() {
    for (const e of this.s) {
      for (let i2 = 0; i2 < e.rawEvents.length; i2++) {
        if (!e.rawEvents[i2].transient) {
          return true;
        }
      }
    }
    return false;
  }
};
var $AL = $AL_1 = class $AL2 extends $3c {
  get length() {
    return this.r.length;
  }
  get cells() {
    return this.r;
  }
  get versionId() {
    return this.t;
  }
  get alternativeVersionId() {
    return this.w;
  }
  get notebookType() {
    return this.viewType;
  }
  constructor(viewType, uri, cells, metadata, options3, C, D, F, G, H) {
    super();
    this.viewType = viewType;
    this.uri = uri;
    this.C = C;
    this.D = D;
    this.F = F;
    this.G = G;
    this.H = H;
    this.f = false;
    this.g = this.B(new $ze());
    this.h = this.B(new $ze());
    this.j = this.B(new $ze());
    this.onWillDispose = this.g.event;
    this.onWillAddRemoveCells = this.h.event;
    this.onDidChangeContent = this.j.event;
    this.m = 0;
    this.n = /* @__PURE__ */ new Map();
    this.r = [];
    this.metadata = {};
    this.transientOptions = { transientCellMetadata: {}, transientDocumentMetadata: {}, transientOutputs: false, cellContentMetadata: {} };
    this.t = 0;
    this.u = 0;
    this.w = "1";
    this.transientOptions = options3;
    this.metadata = metadata;
    this._initialize(cells);
    const maybeUpdateCellTextModel = (textModel) => {
      if (textModel.uri.scheme === Schemas.vscodeNotebookCell && textModel instanceof $QI) {
        const cellUri = CellUri.parse(textModel.uri);
        if (cellUri && $oh(cellUri.notebook, this.uri)) {
          const cellIdx = this.L(cellUri.handle);
          if (cellIdx >= 0) {
            const cell = this.cells[cellIdx];
            if (cell) {
              cell.textModel = textModel;
            }
          }
        }
      }
    };
    this.B(D.onModelAdded((e) => maybeUpdateCellTextModel(e)));
    this.z = new NotebookEventEmitter({
      merge: (events) => {
        const first = events[0];
        const rawEvents = first.rawEvents;
        let versionId = first.versionId;
        let endSelectionState = first.endSelectionState;
        let synchronous = first.synchronous;
        for (let i2 = 1; i2 < events.length; i2++) {
          rawEvents.push(...events[i2].rawEvents);
          versionId = events[i2].versionId;
          endSelectionState = events[i2].endSelectionState !== void 0 ? events[i2].endSelectionState : endSelectionState;
          synchronous = events[i2].synchronous !== void 0 ? events[i2].synchronous : synchronous;
        }
        return { rawEvents, versionId, endSelectionState, synchronous };
      }
    });
    this.B(this.z.event((e) => {
      if (e.rawEvents.length) {
        this.j.fire(e);
      }
    }));
    this.y = new NotebookOperationManager(this, this.C, this.z, (alternativeVersionId) => {
      this.X(true);
      this.Y(alternativeVersionId);
    });
  }
  setCellCollapseDefault(collapseConfig) {
    this.s = collapseConfig;
  }
  _initialize(cells, triggerDirty) {
    this.r = [];
    this.t = 0;
    this.u = 0;
    const mainCells = cells.map((cell) => {
      const cellHandle = this.m++;
      const cellUri = CellUri.generate(this.uri, cellHandle);
      const collapseState = this.U(cell);
      return new $sL(cellUri, cellHandle, cell.source, cell.language, cell.mime, cell.cellKind, cell.outputs, cell.metadata, cell.internalMetadata, collapseState, this.transientOptions, this.F, this.G);
    });
    for (let i2 = 0; i2 < mainCells.length; i2++) {
      const dirtyStateListener = mainCells[i2].onDidChangeContent((e) => {
        this.I(mainCells[i2], e);
      });
      this.n.set(mainCells[i2].handle, dirtyStateListener);
      this.B(mainCells[i2]);
    }
    this.r.splice(0, 0, ...mainCells);
    this.w = this.J();
    if (triggerDirty) {
      this.z.fire({
        rawEvents: [{ kind: NotebookCellsChangeType.Unknown, transient: false }],
        versionId: this.versionId,
        synchronous: true,
        endSelectionState: void 0
      });
    }
  }
  I(cell, e) {
    this.X(e === "content" || typeof e === "object" && e.type === "model");
    switch (e) {
      case "content":
        this.z.fire({
          rawEvents: [{ kind: NotebookCellsChangeType.ChangeCellContent, index: this.L(cell.handle), transient: false }],
          versionId: this.versionId,
          synchronous: true,
          endSelectionState: void 0
        });
        break;
      case "language":
        this.z.fire({
          rawEvents: [{ kind: NotebookCellsChangeType.ChangeCellLanguage, index: this.L(cell.handle), language: cell.language, transient: false }],
          versionId: this.versionId,
          synchronous: true,
          endSelectionState: void 0
        });
        break;
      case "mime":
        this.z.fire({
          rawEvents: [{ kind: NotebookCellsChangeType.ChangeCellMime, index: this.L(cell.handle), mime: cell.mime, transient: false }],
          versionId: this.versionId,
          synchronous: true,
          endSelectionState: void 0
        });
        break;
      default:
        if (typeof e === "object" && e.type === "model") {
          this.z.fire({
            rawEvents: [{ kind: NotebookCellsChangeType.ChangeCellContent, index: this.L(cell.handle), transient: false }],
            versionId: this.versionId,
            synchronous: true,
            endSelectionState: void 0
          });
        }
        break;
    }
  }
  J() {
    return `${this.u}_` + this.cells.map((cell) => cell.handle + "," + cell.alternativeId).join(";");
  }
  dispose() {
    if (this.f) {
      return;
    }
    this.f = true;
    this.g.fire();
    this.C.removeElements(this.uri);
    $Xc(this.n.values());
    this.n.clear();
    $Xc(this.r);
    this.r = [];
    super.dispose();
  }
  pushStackElement() {
  }
  L(handle2) {
    return this.cells.findIndex((c) => c.handle === handle2);
  }
  M(outputId, rawEdits) {
    const edit3 = rawEdits.find((e) => "outputs" in e && e.outputs.some((o) => o.outputId === outputId));
    if (edit3) {
      if ("index" in edit3) {
        return edit3.index;
      } else if ("handle" in edit3) {
        const cellIndex = this.L(edit3.handle);
        this.ob(cellIndex);
        return cellIndex;
      }
    }
    return -1;
  }
  N(outputId) {
    return this.cells.findIndex((c) => !!c.outputs.find((o) => o.outputId === outputId));
  }
  reset(cells, metadata, transientOptions) {
    this.transientOptions = transientOptions;
    const executions = this.H.getCellExecutionsForNotebook(this.uri);
    const executingCellHandles = executions.filter((exe) => exe.state === NotebookCellExecutionState.Executing).map((exe) => exe.cellHandle);
    const edits = $AL_1.computeEdits(this, cells, executingCellHandles);
    this.applyEdits([
      ...edits,
      { editType: 5, metadata }
    ], true, void 0, () => void 0, void 0, false);
  }
  createSnapshot(options3) {
    const transientOptions = options3.transientOptions ?? this.transientOptions;
    const data = {
      metadata: $Tv(this.metadata, (key2) => !transientOptions.transientDocumentMetadata[key2]),
      cells: []
    };
    let outputSize = 0;
    for (const cell of this.cells) {
      const cellData = {
        cellKind: cell.cellKind,
        language: cell.language,
        mime: cell.mime,
        source: cell.getValue(),
        outputs: [],
        internalMetadata: cell.internalMetadata
      };
      if (options3.context === 2 && options3.outputSizeLimit > 0) {
        cell.outputs.forEach((output) => {
          output.outputs.forEach((item) => {
            outputSize += item.data.byteLength;
          });
        });
        if (outputSize > options3.outputSizeLimit) {
          throw new Error("Notebook too large to backup");
        }
      }
      cellData.outputs = !transientOptions.transientOutputs ? cell.outputs : [];
      cellData.metadata = $Tv(cell.metadata, (key2) => !transientOptions.transientCellMetadata[key2]);
      data.cells.push(cellData);
    }
    return data;
  }
  restoreSnapshot(snapshot, transientOptions) {
    this.reset(snapshot.cells, snapshot.metadata, transientOptions ?? this.transientOptions);
  }
  static computeEdits(model, cells, executingHandles = []) {
    const edits = [];
    const isExecuting = (cell) => executingHandles.includes(cell.handle);
    const commonPrefix = this.P(model.cells, model.cells.length, 0, cells, cells.length, 0, isExecuting);
    if (commonPrefix > 0) {
      for (let i2 = 0; i2 < commonPrefix; i2++) {
        edits.push({
          editType: 3,
          index: i2,
          metadata: cells[i2].metadata ?? {}
        }, ...this.O(i2, model.cells[i2].outputs, cells[i2].outputs));
      }
    }
    if (model.cells.length === cells.length && commonPrefix === model.cells.length) {
      return edits;
    }
    const commonSuffix = this.Q(model.cells, model.cells.length - commonPrefix, commonPrefix, cells, cells.length - commonPrefix, commonPrefix, isExecuting);
    if (commonSuffix > 0) {
      edits.push({ editType: 1, index: commonPrefix, count: model.cells.length - commonPrefix - commonSuffix, cells: cells.slice(commonPrefix, cells.length - commonSuffix) });
    } else if (commonPrefix > 0) {
      edits.push({ editType: 1, index: commonPrefix, count: model.cells.length - commonPrefix, cells: cells.slice(commonPrefix) });
    } else {
      edits.push({ editType: 1, index: 0, count: model.cells.length, cells });
    }
    if (commonSuffix > 0) {
      for (let i2 = commonSuffix; i2 > 0; i2--) {
        edits.push({
          editType: 3,
          index: model.cells.length - i2,
          metadata: cells[cells.length - i2].metadata ?? {}
        }, ...this.O(model.cells.length - i2, model.cells[model.cells.length - i2].outputs, cells[cells.length - i2].outputs));
      }
    }
    return edits;
  }
  static O(index, a, b) {
    if (a.length !== b.length) {
      return [
        {
          editType: 2,
          index,
          outputs: b,
          append: false
        }
      ];
    }
    if (a.length === 0) {
      return [];
    }
    return b.map((output, i2) => {
      return {
        editType: 7,
        outputId: a[i2].outputId,
        items: output.outputs,
        append: false
      };
    });
  }
  static P(a, aLen, aDelta, b, bLen, bDelta, isExecuting) {
    const maxResult = Math.min(aLen, bLen);
    let result = 0;
    for (let i2 = 0; i2 < maxResult && a[aDelta + i2].fastEqual(b[bDelta + i2], isExecuting(a[aDelta + i2])); i2++) {
      result++;
    }
    return result;
  }
  static Q(a, aLen, aDelta, b, bLen, bDelta, isExecuting) {
    const maxResult = Math.min(aLen, bLen);
    let result = 0;
    for (let i2 = 0; i2 < maxResult && a[aDelta + aLen - i2 - 1].fastEqual(b[bDelta + bLen - i2 - 1], isExecuting(a[aDelta + aLen - i2 - 1])); i2++) {
      result++;
    }
    return result;
  }
  applyEdits(rawEdits, synchronous, beginSelectionState, endSelectionsComputer, undoRedoGroup, computeUndoRedo) {
    this.z.pause();
    this.y.pushStackElement(this.w, void 0);
    try {
      this.R(rawEdits, synchronous, computeUndoRedo, beginSelectionState, undoRedoGroup);
      return true;
    } finally {
      if (!this.z.isEmpty) {
        const endSelections = endSelectionsComputer();
        this.X(this.y.isUndoStackEmpty() && !this.z.isDirtyEvent());
        this.y.pushStackElement(this.w, endSelections);
        this.z.fire({ rawEvents: [], versionId: this.versionId, synchronous, endSelectionState: endSelections });
      }
      this.z.resume();
    }
  }
  R(rawEdits, synchronous, computeUndoRedo, beginSelectionState, undoRedoGroup) {
    const editsWithDetails = rawEdits.map((edit3, index) => {
      let cellIndex = -1;
      if ("index" in edit3) {
        cellIndex = edit3.index;
      } else if ("handle" in edit3) {
        cellIndex = this.L(edit3.handle);
        this.ob(cellIndex);
      } else if ("outputId" in edit3) {
        cellIndex = this.N(edit3.outputId);
        if (this.pb(cellIndex)) {
          cellIndex = this.M(edit3.outputId, rawEdits.slice(0, index));
        }
        if (this.pb(cellIndex)) {
          return null;
        }
      } else if (edit3.editType !== 5) {
        throw new Error("Invalid cell edit");
      }
      return {
        edit: edit3,
        cellIndex,
        end: edit3.editType === 5 ? void 0 : edit3.editType === 1 ? edit3.index + edit3.count : cellIndex,
        originalIndex: index
      };
    }).filter($Hg);
    const edits = this.S(editsWithDetails).sort((a, b) => {
      if (a.end === void 0) {
        return -1;
      }
      if (b.end === void 0) {
        return -1;
      }
      return b.end - a.end || b.originalIndex - a.originalIndex;
    }).reduce((prev, curr) => {
      if (!prev.length) {
        prev.push([curr]);
      } else {
        const last = prev[prev.length - 1];
        const index = last[0].cellIndex;
        if (curr.cellIndex === index) {
          last.push(curr);
        } else {
          prev.push([curr]);
        }
      }
      return prev;
    }, []).map((editsOnSameIndex) => {
      const replaceEdits = [];
      const otherEdits = [];
      editsOnSameIndex.forEach((edit3) => {
        if (edit3.edit.editType === 1) {
          replaceEdits.push(edit3);
        } else {
          otherEdits.push(edit3);
        }
      });
      return [...otherEdits.reverse(), ...replaceEdits];
    });
    const flattenEdits = edits.flat();
    for (const { edit: edit3, cellIndex } of flattenEdits) {
      switch (edit3.editType) {
        case 1:
          this.W(edit3.index, edit3.count, edit3.cells, synchronous, computeUndoRedo, beginSelectionState, undoRedoGroup);
          break;
        case 2: {
          this.ob(cellIndex);
          const cell = this.r[cellIndex];
          if (edit3.append) {
            this.kb(cell, { start: cell.outputs.length, deleteCount: 0, newOutputs: edit3.outputs.map((op) => new $rL(op)) }, true, computeUndoRedo);
          } else {
            this.jb(cell, edit3.outputs, computeUndoRedo);
          }
          break;
        }
        case 7:
          {
            this.ob(cellIndex);
            const cell = this.r[cellIndex];
            if (edit3.append) {
              this.lb(cell, edit3.outputId, edit3.items);
            } else {
              this.mb(cell, edit3.outputId, edit3.items);
            }
          }
          break;
        case 3:
          this.ob(edit3.index);
          this.gb(this.r[edit3.index], edit3.metadata, computeUndoRedo, beginSelectionState, undoRedoGroup);
          break;
        case 8:
          this.ob(cellIndex);
          this.fb(this.r[cellIndex], edit3.metadata, computeUndoRedo, beginSelectionState, undoRedoGroup);
          break;
        case 9:
          this.ob(cellIndex);
          this.hb(this.r[cellIndex], edit3.internalMetadata);
          break;
        case 4:
          this.ob(edit3.index);
          this.ib(this.r[edit3.index], edit3.language, computeUndoRedo, beginSelectionState, undoRedoGroup);
          break;
        case 5:
          this.Z(edit3.metadata, computeUndoRedo, beginSelectionState, undoRedoGroup);
          break;
        case 6:
          this.nb(edit3.index, edit3.length, edit3.newIdx, synchronous, computeUndoRedo, beginSelectionState, void 0, undoRedoGroup);
          break;
      }
    }
  }
  S(rawEdits) {
    const mergedEdits = [];
    rawEdits.forEach((edit3) => {
      if (mergedEdits.length) {
        const last = mergedEdits[mergedEdits.length - 1];
        if (last.edit.editType === 2 && last.edit.append && edit3.edit.editType === 2 && edit3.edit.append && last.cellIndex === edit3.cellIndex) {
          last.edit.outputs = [...last.edit.outputs, ...edit3.edit.outputs];
        } else if (last.edit.editType === 2 && !last.edit.append && last.edit.outputs.length === 0 && edit3.edit.editType === 2 && edit3.edit.append && last.cellIndex === edit3.cellIndex) {
          last.edit.append = false;
          last.edit.outputs = edit3.edit.outputs;
        } else {
          mergedEdits.push(edit3);
        }
      } else {
        mergedEdits.push(edit3);
      }
    });
    return mergedEdits;
  }
  U(cellDto) {
    const defaultConfig2 = cellDto.cellKind === CellKind.Code ? this.s?.codeCell : this.s?.markupCell;
    return cellDto.collapseState ?? (defaultConfig2 ?? void 0);
  }
  W(index, count, cellDtos, synchronous, computeUndoRedo, beginSelectionState, undoRedoGroup) {
    if (count === 0 && cellDtos.length === 0) {
      return;
    }
    const oldViewCells = this.r.slice(0);
    const oldSet = /* @__PURE__ */ new Set();
    oldViewCells.forEach((cell) => {
      oldSet.add(cell.handle);
    });
    for (let i2 = index; i2 < Math.min(index + count, this.r.length); i2++) {
      const cell = this.r[i2];
      this.n.get(cell.handle)?.dispose();
      this.n.delete(cell.handle);
    }
    const cells = cellDtos.map((cellDto) => {
      const cellHandle = this.m++;
      const cellUri = CellUri.generate(this.uri, cellHandle);
      const collapseState = this.U(cellDto);
      const cell = new $sL(cellUri, cellHandle, cellDto.source, cellDto.language, cellDto.mime, cellDto.cellKind, cellDto.outputs || [], cellDto.metadata, cellDto.internalMetadata, collapseState, this.transientOptions, this.F, this.G);
      const textModel = this.D.getModel(cellUri);
      if (textModel && textModel instanceof $QI) {
        cell.textModel = textModel;
        cell.language = cellDto.language;
        cell.textModel.setValue(cellDto.source);
        cell.resetTextBuffer(cell.textModel.getTextBuffer());
      }
      const dirtyStateListener = cell.onDidChangeContent((e) => {
        this.I(cell, e);
      });
      this.n.set(cell.handle, dirtyStateListener);
      this.B(cell);
      return cell;
    });
    const cellsCopy = this.r.slice(0);
    cellsCopy.splice(index, count, ...cells);
    const diffs = $mM(this.r, cellsCopy, (cell) => {
      return oldSet.has(cell.handle);
    }).map((diff3) => {
      return [diff3.start, diff3.deleteCount, diff3.toInsert];
    });
    this.h.fire({ rawEvent: { kind: NotebookCellsChangeType.ModelChange, changes: diffs } });
    this.r = cellsCopy;
    const undoDiff = diffs.map((diff3) => {
      const deletedCells = oldViewCells.slice(diff3[0], diff3[0] + diff3[1]);
      return [diff3[0], deletedCells, diff3[2]];
    });
    if (computeUndoRedo) {
      this.y.pushEditOperation(new $yL(this.uri, undoDiff, {
        insertCell: (index2, cell, endSelections) => {
          this.$(index2, [cell], true, endSelections);
        },
        deleteCell: (index2, endSelections) => {
          this.ab(index2, 1, true, endSelections);
        },
        replaceCell: (index2, count2, cells2, endSelections) => {
          this.bb(index2, count2, cells2, true, endSelections);
        }
      }, void 0, void 0), beginSelectionState, void 0, this.w, undoRedoGroup);
    }
    this.z.fire({
      rawEvents: [{ kind: NotebookCellsChangeType.ModelChange, changes: diffs, transient: false }],
      versionId: this.versionId,
      synchronous,
      endSelectionState: void 0
    });
  }
  X(transient) {
    this.t = this.t + 1;
    if (!transient) {
      this.u = this.t;
    }
    this.w = this.J();
  }
  Y(newAlternativeVersionId) {
    this.w = newAlternativeVersionId;
    this.u = Number(newAlternativeVersionId.substring(0, newAlternativeVersionId.indexOf("_")));
  }
  Z(metadata, computeUndoRedo, beginSelectionState, undoRedoGroup) {
    const oldMetadata = this.metadata;
    const triggerDirtyChange = this.cb(this.metadata, metadata);
    if (triggerDirtyChange) {
      if (computeUndoRedo) {
        const that = this;
        this.y.pushEditOperation(new class {
          constructor() {
            this.type = 0;
            this.label = "Update Cell Metadata";
            this.code = "undoredo.textBufferEdit";
          }
          get resource() {
            return that.uri;
          }
          undo() {
            that.Z(oldMetadata, false, beginSelectionState, undoRedoGroup);
          }
          redo() {
            that.Z(metadata, false, beginSelectionState, undoRedoGroup);
          }
        }(), beginSelectionState, void 0, this.w, undoRedoGroup);
      }
    }
    this.metadata = metadata;
    this.z.fire({
      rawEvents: [{ kind: NotebookCellsChangeType.ChangeDocumentMetadata, metadata: this.metadata, transient: !triggerDirtyChange }],
      versionId: this.versionId,
      synchronous: true,
      endSelectionState: void 0
    });
  }
  $(index, cells, synchronous, endSelections) {
    for (let i2 = 0; i2 < cells.length; i2++) {
      const dirtyStateListener = cells[i2].onDidChangeContent((e) => {
        this.I(cells[i2], e);
      });
      this.n.set(cells[i2].handle, dirtyStateListener);
    }
    const changes = [[index, 0, cells]];
    this.h.fire({ rawEvent: { kind: NotebookCellsChangeType.ModelChange, changes } });
    this.r.splice(index, 0, ...cells);
    this.z.fire({
      rawEvents: [{ kind: NotebookCellsChangeType.ModelChange, changes, transient: false }],
      versionId: this.versionId,
      synchronous,
      endSelectionState: endSelections
    });
    return;
  }
  ab(index, count, synchronous, endSelections) {
    for (let i2 = index; i2 < index + count; i2++) {
      const cell = this.r[i2];
      this.n.get(cell.handle)?.dispose();
      this.n.delete(cell.handle);
    }
    const changes = [[index, count, []]];
    this.h.fire({ rawEvent: { kind: NotebookCellsChangeType.ModelChange, changes } });
    this.r.splice(index, count);
    this.z.fire({
      rawEvents: [{ kind: NotebookCellsChangeType.ModelChange, changes, transient: false }],
      versionId: this.versionId,
      synchronous,
      endSelectionState: endSelections
    });
  }
  bb(index, count, cells, synchronous, endSelections) {
    for (let i2 = index; i2 < index + count; i2++) {
      const cell = this.r[i2];
      this.n.get(cell.handle)?.dispose();
      this.n.delete(cell.handle);
    }
    for (let i2 = 0; i2 < cells.length; i2++) {
      const dirtyStateListener = cells[i2].onDidChangeContent((e) => {
        this.I(cells[i2], e);
      });
      this.n.set(cells[i2].handle, dirtyStateListener);
    }
    const changes = [[index, count, cells]];
    this.h.fire({ rawEvent: { kind: NotebookCellsChangeType.ModelChange, changes } });
    this.r.splice(index, count, ...cells);
    this.z.fire({
      rawEvents: [{ kind: NotebookCellsChangeType.ModelChange, changes, transient: false }],
      versionId: this.versionId,
      synchronous,
      endSelectionState: endSelections
    });
  }
  cb(a, b) {
    const keys = /* @__PURE__ */ new Set([...Object.keys(a || {}), ...Object.keys(b || {})]);
    for (const key2 of keys) {
      if (key2 === "custom") {
        if (!this.eb(a[key2], b[key2]) && !this.transientOptions.transientDocumentMetadata[key2]) {
          return true;
        }
      } else if (a[key2] !== b[key2] && !this.transientOptions.transientDocumentMetadata[key2]) {
        return true;
      }
    }
    return false;
  }
  db(a, b) {
    const keys = /* @__PURE__ */ new Set([...Object.keys(a || {}), ...Object.keys(b || {})]);
    for (const key2 of keys) {
      if (a[key2] !== b[key2] && !this.transientOptions.transientCellMetadata[key2]) {
        return true;
      }
    }
    return false;
  }
  eb(a, b) {
    if (!a && !b) {
      return true;
    }
    if (!a || !b) {
      return false;
    }
    const aProps = Object.getOwnPropertyNames(a);
    const bProps = Object.getOwnPropertyNames(b);
    if (aProps.length !== bProps.length) {
      return false;
    }
    for (let i2 = 0; i2 < aProps.length; i2++) {
      const propName = aProps[i2];
      if (a[propName] !== b[propName]) {
        return false;
      }
    }
    return true;
  }
  fb(cell, metadata, computeUndoRedo, beginSelectionState, undoRedoGroup) {
    const newMetadata = {
      ...cell.metadata
    };
    let k;
    for (k in metadata) {
      const value = metadata[k] ?? void 0;
      newMetadata[k] = value;
    }
    return this.gb(cell, newMetadata, computeUndoRedo, beginSelectionState, undoRedoGroup);
  }
  gb(cell, metadata, computeUndoRedo, beginSelectionState, undoRedoGroup) {
    const triggerDirtyChange = this.db(cell.metadata, metadata);
    if (triggerDirtyChange) {
      if (computeUndoRedo) {
        const index = this.r.indexOf(cell);
        this.y.pushEditOperation(new $zL(this.uri, index, Object.freeze(cell.metadata), Object.freeze(metadata), {
          updateCellMetadata: (index2, newMetadata) => {
            const cell2 = this.r[index2];
            if (!cell2) {
              return;
            }
            this.gb(cell2, newMetadata, false, beginSelectionState, undoRedoGroup);
          }
        }), beginSelectionState, void 0, this.w, undoRedoGroup);
      }
    }
    cell.metadata = metadata;
    this.z.fire({
      rawEvents: [{ kind: NotebookCellsChangeType.ChangeCellMetadata, index: this.r.indexOf(cell), metadata: cell.metadata, transient: !triggerDirtyChange }],
      versionId: this.versionId,
      synchronous: true,
      endSelectionState: void 0
    });
  }
  hb(cell, internalMetadata) {
    const newInternalMetadata = {
      ...cell.internalMetadata
    };
    let k;
    for (k in internalMetadata) {
      const value = internalMetadata[k] ?? void 0;
      newInternalMetadata[k] = value;
    }
    cell.internalMetadata = newInternalMetadata;
    this.z.fire({
      rawEvents: [{ kind: NotebookCellsChangeType.ChangeCellInternalMetadata, index: this.r.indexOf(cell), internalMetadata: cell.internalMetadata, transient: true }],
      versionId: this.versionId,
      synchronous: true,
      endSelectionState: void 0
    });
  }
  ib(cell, languageId, computeUndoRedo, beginSelectionState, undoRedoGroup) {
    if (cell.language === languageId) {
      return;
    }
    const oldLanguage = cell.language;
    cell.language = languageId;
    if (computeUndoRedo) {
      const that = this;
      this.y.pushEditOperation(new class {
        constructor() {
          this.type = 0;
          this.label = "Update Cell Language";
          this.code = "undoredo.textBufferEdit";
        }
        get resource() {
          return that.uri;
        }
        undo() {
          that.ib(cell, oldLanguage, false, beginSelectionState, undoRedoGroup);
        }
        redo() {
          that.ib(cell, languageId, false, beginSelectionState, undoRedoGroup);
        }
      }(), beginSelectionState, void 0, this.w, undoRedoGroup);
    }
    this.z.fire({
      rawEvents: [{ kind: NotebookCellsChangeType.ChangeCellLanguage, index: this.r.indexOf(cell), language: languageId, transient: false }],
      versionId: this.versionId,
      synchronous: true,
      endSelectionState: void 0
    });
  }
  jb(cell, outputs, computeUndoRedo) {
    if (outputs.length === 0 && cell.outputs.length === 0) {
      return;
    }
    if (outputs.length <= 1) {
      this.kb(cell, { start: 0, deleteCount: cell.outputs.length, newOutputs: outputs.map((op) => new $rL(op)) }, false, computeUndoRedo);
      return;
    }
    const diff3 = new $7C(new OutputSequence(cell.outputs), new OutputSequence(outputs));
    const diffResult = diff3.ComputeDiff(false);
    const splices = diffResult.changes.map((change) => ({
      start: change.originalStart,
      deleteCount: change.originalLength,
      // create cell output text model only when it's inserted into the notebook document
      newOutputs: outputs.slice(change.modifiedStart, change.modifiedStart + change.modifiedLength).map((op) => new $rL(op))
    }));
    splices.reverse().forEach((splice2) => {
      this.kb(cell, splice2, false, computeUndoRedo);
    });
  }
  kb(cell, splice2, append2, computeUndoRedo) {
    cell.spliceNotebookCellOutputs(splice2);
    this.z.fire({
      rawEvents: [{
        kind: NotebookCellsChangeType.Output,
        index: this.r.indexOf(cell),
        outputs: cell.outputs.map((output) => output.asDto()) ?? [],
        append: append2,
        transient: this.transientOptions.transientOutputs
      }],
      versionId: this.versionId,
      synchronous: true,
      endSelectionState: void 0
    });
  }
  lb(cell, outputId, items) {
    if (cell.changeOutputItems(outputId, true, items)) {
      this.z.fire({
        rawEvents: [{
          kind: NotebookCellsChangeType.OutputItem,
          index: this.r.indexOf(cell),
          outputId,
          outputItems: items,
          append: true,
          transient: this.transientOptions.transientOutputs
        }],
        versionId: this.versionId,
        synchronous: true,
        endSelectionState: void 0
      });
    }
  }
  mb(cell, outputId, items) {
    if (cell.changeOutputItems(outputId, false, items)) {
      this.z.fire({
        rawEvents: [{
          kind: NotebookCellsChangeType.OutputItem,
          index: this.r.indexOf(cell),
          outputId,
          outputItems: items,
          append: false,
          transient: this.transientOptions.transientOutputs
        }],
        versionId: this.versionId,
        synchronous: true,
        endSelectionState: void 0
      });
    }
  }
  nb(index, length, newIdx, synchronous, pushedToUndoStack, beforeSelections, endSelections, undoRedoGroup) {
    if (pushedToUndoStack) {
      this.y.pushEditOperation(new $xL(this.uri, index, length, newIdx, {
        moveCell: (fromIndex, length2, toIndex, beforeSelections2, endSelections2) => {
          this.nb(fromIndex, length2, toIndex, true, false, beforeSelections2, endSelections2, undoRedoGroup);
        }
      }, beforeSelections, endSelections), beforeSelections, endSelections, this.w, undoRedoGroup);
    }
    this.ob(index);
    this.ob(newIdx);
    const cells = this.r.splice(index, length);
    this.r.splice(newIdx, 0, ...cells);
    this.z.fire({
      rawEvents: [{ kind: NotebookCellsChangeType.Move, index, length, newIdx, cells, transient: false }],
      versionId: this.versionId,
      synchronous,
      endSelectionState: endSelections
    });
    return true;
  }
  ob(index) {
    if (this.pb(index)) {
      throw new Error(`model index out of range ${index}`);
    }
  }
  pb(index) {
    return index < 0 || index >= this.r.length;
  }
  //#region Find
  findNextMatch(searchString, searchStart, isRegex, matchCase, wordSeparators2, searchEnd) {
    this.ob(searchStart.cellIndex);
    const searchParams = new $fI(searchString, isRegex, matchCase, wordSeparators2);
    const searchData = searchParams.parseSearchRequest();
    if (!searchData) {
      return null;
    }
    let cellIndex = searchStart.cellIndex;
    let searchStartPosition = searchStart.position;
    let searchEndCell = this.r.length;
    while (cellIndex < searchEndCell) {
      const cell = this.r[cellIndex];
      const wrapFlag = searchEnd && cellIndex === searchEnd.cellIndex && searchStartPosition.isBefore(searchEnd.position);
      const searchRange = new $9C(searchStartPosition.lineNumber, searchStartPosition.column, wrapFlag ? searchEnd.position.lineNumber : cell.textBuffer.getLineCount(), wrapFlag ? searchEnd.position.column : cell.textBuffer.getLineMaxColumn(cell.textBuffer.getLineCount()));
      const result = cell.textBuffer.findMatchesLineByLine(searchRange, searchData, false, 1);
      if (result.length > 0) {
        return { cell, match: result[0] };
      } else if (wrapFlag) {
        break;
      }
      cellIndex++;
      if (searchEnd && cellIndex >= this.r.length) {
        cellIndex = 0;
        searchEndCell = searchEnd.cellIndex + 1;
      }
      searchStartPosition = new $8C(1, 1);
    }
    return null;
  }
  findMatches(searchString, isRegex, matchCase, wordSeparators2) {
    const searchParams = new $fI(searchString, isRegex, matchCase, wordSeparators2);
    const searchData = searchParams.parseSearchRequest();
    if (!searchData) {
      return [];
    }
    const results = [];
    for (const cell of this.r) {
      const searchRange = new $9C(1, 1, cell.textBuffer.getLineCount(), cell.textBuffer.getLineMaxColumn(cell.textBuffer.getLineCount()));
      const matches = cell.textBuffer.findMatchesLineByLine(searchRange, searchData, false, 1e3);
      if (matches.length > 0) {
        results.push({ cell, matches });
      }
    }
    return results;
  }
};
$AL = $AL_1 = __decorate([
  __param(5, $_F),
  __param(6, $sG),
  __param(7, $1E),
  __param(8, $tG),
  __param(9, $wL)
], $AL);
var OutputSequence = class {
  constructor(outputs) {
    this.outputs = outputs;
  }
  getElements() {
    return this.outputs.map((output) => {
      return $Xi(output.outputs.map((output2) => ({
        mime: output2.mime,
        data: output2.data
      })));
    });
  }
};

// out-build/vs/workbench/contrib/notebook/common/notebookOutputRenderer.js
var DependencyList = class {
  constructor(value) {
    this.a = new Set(value);
    this.defined = this.a.size > 0;
  }
  /** Gets whether any of the 'available' dependencies match the ones in this list */
  matches(available) {
    return available.some((v) => this.a.has(v));
  }
};
var $_1b = class {
  constructor(descriptor) {
    this.id = descriptor.id;
    this.extensionId = descriptor.extension.identifier;
    this.extensionLocation = descriptor.extension.extensionLocation;
    this.isBuiltin = descriptor.extension.isBuiltin;
    if (typeof descriptor.entrypoint === "string") {
      this.entrypoint = {
        extends: void 0,
        path: $vh(this.extensionLocation, descriptor.entrypoint)
      };
    } else {
      this.entrypoint = {
        extends: descriptor.entrypoint.extends,
        path: $vh(this.extensionLocation, descriptor.entrypoint.path)
      };
    }
    this.displayName = descriptor.displayName;
    this.mimeTypes = descriptor.mimeTypes;
    this.a = this.mimeTypes.map((pattern) => $Dl(pattern));
    this.hardDependencies = new DependencyList(descriptor.dependencies ?? Iterable.empty());
    this.optionalDependencies = new DependencyList(descriptor.optionalDependencies ?? Iterable.empty());
    this.messaging = descriptor.requiresMessaging ?? "never";
  }
  matchesWithoutKernel(mimeType) {
    if (!this.b(mimeType)) {
      return 3;
    }
    if (this.hardDependencies.defined) {
      return 0;
    }
    if (this.optionalDependencies.defined) {
      return 1;
    }
    return 2;
  }
  matches(mimeType, kernelProvides) {
    if (!this.b(mimeType)) {
      return 3;
    }
    if (this.hardDependencies.defined) {
      return this.hardDependencies.matches(kernelProvides) ? 0 : 3;
    }
    return this.optionalDependencies.matches(kernelProvides) ? 1 : 2;
  }
  b(mimeType) {
    if (this.entrypoint.extends) {
      return false;
    }
    return this.a.some((pattern) => pattern(mimeType)) || this.mimeTypes.some((pattern) => pattern === mimeType);
  }
};
var $a2b = class {
  constructor(descriptor) {
    this.type = descriptor.type;
    this.entrypoint = $vh(descriptor.extension.extensionLocation, descriptor.entrypoint);
    this.extensionLocation = descriptor.extension.extensionLocation;
    this.localResourceRoots = descriptor.localResourceRoots.map((root) => $vh(descriptor.extension.extensionLocation, root));
  }
};

// out-build/vs/workbench/contrib/notebook/common/notebookProvider.js
var $lrb = class _$lrb {
  get selectors() {
    return this.a;
  }
  get options() {
    return this.b;
  }
  constructor(descriptor) {
    this.extension = descriptor.extension;
    this.id = descriptor.id;
    this.displayName = descriptor.displayName;
    this.a = descriptor.selectors?.map((selector) => ({
      include: selector.filenamePattern,
      exclude: selector.excludeFileNamePattern || ""
    })) || [];
    this.priority = descriptor.priority;
    this.providerDisplayName = descriptor.providerDisplayName;
    this.b = {
      transientCellMetadata: {},
      transientDocumentMetadata: {},
      transientOutputs: false,
      cellContentMetadata: {}
    };
  }
  update(args2) {
    if (args2.selectors) {
      this.a = args2.selectors;
    }
    if (args2.options) {
      this.b = args2.options;
    }
  }
  matches(resource) {
    return this.selectors?.some((selector) => _$lrb.selectorMatches(selector, resource));
  }
  static selectorMatches(selector, resource) {
    if (typeof selector === "string") {
      if ($Cl(selector.toLowerCase(), $rc(resource.fsPath).toLowerCase())) {
        return true;
      }
    }
    if ($El(selector)) {
      if ($Cl(selector, $rc(resource.fsPath).toLowerCase())) {
        return true;
      }
    }
    if (!$pM(selector)) {
      return false;
    }
    const filenamePattern = selector.include;
    const excludeFilenamePattern = selector.exclude;
    if ($Cl(filenamePattern, $rc(resource.fsPath).toLowerCase())) {
      if (excludeFilenamePattern) {
        if ($Cl(excludeFilenamePattern, $rc(resource.fsPath).toLowerCase())) {
          return false;
        }
      }
      return true;
    }
    return false;
  }
  static possibleFileEnding(selectors) {
    for (const selector of selectors) {
      const ending = _$lrb.c(selector);
      if (ending) {
        return ending;
      }
    }
    return void 0;
  }
  static c(selector) {
    const pattern = /^.*(\.[a-zA-Z0-9_-]+)$/;
    let candidate;
    if (typeof selector === "string") {
      candidate = selector;
    } else if ($El(selector)) {
      candidate = selector.pattern;
    } else if (selector.include) {
      return _$lrb.c(selector.include);
    }
    if (candidate) {
      const match = pattern.exec(candidate);
      if (match) {
        return match[1];
      }
    }
    return void 0;
  }
};

// out-build/vs/workbench/contrib/notebook/browser/diff/notebookMultiDiffEditorInput.js
var $d2b_1;
var $b2b = "multi-cell-notebook-diff-editor";
var $c2b = class _$c2b extends $$1b {
  static {
    this.ID = "workbench.input.multiDiffNotebookInput";
  }
  static create(instantiationService, resource, name, description, originalResource, viewType) {
    const original = $trb.getOrCreate(instantiationService, originalResource, void 0, viewType);
    const modified = $trb.getOrCreate(instantiationService, resource, void 0, viewType);
    return instantiationService.createInstance(_$c2b, name, description, original, modified, viewType);
  }
};
var $d2b = $d2b_1 = class $d2b2 extends $_Eb {
  static createInput(notebookDiffViewModel, instantiationService) {
    const multiDiffSource = URI.parse(`${$b2b}:${(/* @__PURE__ */ new Date()).getMilliseconds().toString() + Math.random().toString()}`);
    return instantiationService.createInstance($d2b_1, multiDiffSource, notebookDiffViewModel);
  }
  constructor(multiDiffSource, H, _textModelService, _textResourceConfigurationService, _instantiationService, _multiDiffSourceResolverService, _textFileService) {
    super(multiDiffSource, void 0, void 0, true, _textModelService, _textResourceConfigurationService, _instantiationService, _multiDiffSourceResolverService, _textFileService);
    this.H = H;
    this.B(_multiDiffSourceResolverService.registerResolver(this));
  }
  canHandleUri(uri) {
    return uri.toString() === this.multiDiffSource.toString();
  }
  async resolveDiffSource(_) {
    return { resources: this.H };
  }
};
$d2b = $d2b_1 = __decorate([
  __param(2, $oG),
  __param(3, $zG),
  __param(4, $Pk),
  __param(5, $TDb),
  __param(6, $cK)
], $d2b);

// out-build/vs/workbench/contrib/notebook/browser/services/notebookServiceImpl.js
var $e2b_1;
var $g2b_1;
var $e2b = class $e2b2 extends $3c {
  static {
    $e2b_1 = this;
  }
  static {
    this.c = "notebookEditors";
  }
  static {
    this.f = "editors";
  }
  constructor(storageService, extensionService, 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 = false;
    this.j = /* @__PURE__ */ new Map();
    this.m = this.B(new $2c());
    this.g = new $Slb($e2b_1.c, storageService);
    const mementoObject = this.g.getMemento(
      0,
      1
      /* StorageTarget.MACHINE */
    );
    this.n.bufferChangeEvents(() => {
      for (const info of mementoObject[$e2b_1.f] || []) {
        this.add(new $lrb(info), false);
      }
    });
    this.B(extensionService.onDidRegisterExtensions(() => {
      if (!this.h) {
        this.G();
        mementoObject[$e2b_1.f] = [];
        this.g.saveMemento();
      }
    }));
    $81b.setHandler((extensions) => this.C(extensions));
  }
  dispose() {
    this.G();
    super.dispose();
  }
  C(extensions) {
    this.h = true;
    const builtins = [...this.j.values()].filter((info) => !info.extension);
    this.G();
    const builtinProvidersFromCache = /* @__PURE__ */ new Map();
    builtins.forEach((builtin) => {
      builtinProvidersFromCache.set(builtin.id, this.add(builtin));
    });
    for (const extension of extensions) {
      for (const notebookContribution of extension.value) {
        if (!notebookContribution.type) {
          extension.collector.error(`Notebook does not specify type-property`);
          continue;
        }
        const existing = this.get(notebookContribution.type);
        if (existing) {
          if (!existing.extension && extension.description.isBuiltin && builtins.find((builtin) => builtin.id === notebookContribution.type)) {
            builtinProvidersFromCache.get(notebookContribution.type)?.dispose();
          } else {
            extension.collector.error(`Notebook type '${notebookContribution.type}' already used`);
            continue;
          }
        }
        this.add(new $lrb({
          extension: extension.description.identifier,
          id: notebookContribution.type,
          displayName: notebookContribution.displayName,
          selectors: notebookContribution.selector || [],
          priority: this.D(notebookContribution.priority),
          providerDisplayName: extension.description.displayName ?? extension.description.identifier.value
        }));
      }
    }
    const mementoObject = this.g.getMemento(
      0,
      1
      /* StorageTarget.MACHINE */
    );
    mementoObject[$e2b_1.f] = Array.from(this.j.values());
    this.g.saveMemento();
  }
  clearEditorCache() {
    const mementoObject = this.g.getMemento(
      0,
      1
      /* StorageTarget.MACHINE */
    );
    mementoObject[$e2b_1.f] = [];
    this.g.saveMemento();
  }
  D(priority) {
    if (!priority) {
      return RegisteredEditorPriority.default;
    }
    if (priority === NotebookEditorPriority.default) {
      return RegisteredEditorPriority.default;
    }
    return RegisteredEditorPriority.option;
  }
  F(notebookProviderInfo) {
    const disposables = new $2c();
    for (const selector of notebookProviderInfo.selectors) {
      const globPattern = selector.include || selector;
      const notebookEditorInfo = {
        id: notebookProviderInfo.id,
        label: notebookProviderInfo.displayName,
        detail: notebookProviderInfo.providerDisplayName,
        priority: notebookProviderInfo.priority
      };
      const notebookEditorOptions = {
        canHandleDiff: () => !!this.s.getValue($rM.textDiffEditorPreview) && !this.t.isScreenReaderOptimized(),
        canSupportResource: (resource) => resource.scheme === Schemas.untitled || resource.scheme === Schemas.vscodeNotebookCell || this.w.hasProvider(resource)
      };
      const notebookEditorInputFactory = ({ resource, options: options3 }) => {
        const data = CellUri.parse(resource);
        let notebookUri;
        let cellOptions;
        let preferredResource = resource;
        if (data) {
          notebookUri = this.z.asCanonicalUri(data.notebook);
          preferredResource = data.notebook;
          cellOptions = { resource, options: options3 };
        } else {
          notebookUri = this.z.asCanonicalUri(resource);
        }
        if (!cellOptions) {
          cellOptions = options3?.cellOptions;
        }
        const notebookOptions = { ...options3, cellOptions, viewState: void 0 };
        const editor = $trb.getOrCreate(this.u, notebookUri, preferredResource, notebookProviderInfo.id);
        return { editor, options: notebookOptions };
      };
      const notebookUntitledEditorFactory = async ({ resource, options: options3 }) => {
        const ref = await this.y.resolve({ untitledResource: resource }, notebookProviderInfo.id);
        ref.object.notebook.onWillDispose(() => {
          ref.dispose();
        });
        return { editor: $trb.getOrCreate(this.u, ref.object.resource, void 0, notebookProviderInfo.id), options: options3 };
      };
      const notebookDiffEditorInputFactory = (diffEditorInput, group2) => {
        const { modified, original, label: label3, description } = diffEditorInput;
        if (this.s.getValue("notebook.experimental.enableNewDiffEditor")) {
          return { editor: $c2b.create(this.u, modified.resource, label3, description, original.resource, notebookProviderInfo.id) };
        }
        return { editor: $$1b.create(this.u, modified.resource, label3, description, original.resource, notebookProviderInfo.id) };
      };
      const mergeEditorInputFactory = (mergeEditor) => {
        return {
          editor: this.u.createInstance($7Ob, mergeEditor.base.resource, {
            uri: mergeEditor.input1.resource,
            title: mergeEditor.input1.label ?? $sh(mergeEditor.input1.resource),
            description: mergeEditor.input1.description ?? "",
            detail: mergeEditor.input1.detail
          }, {
            uri: mergeEditor.input2.resource,
            title: mergeEditor.input2.label ?? $sh(mergeEditor.input2.resource),
            description: mergeEditor.input2.description ?? "",
            detail: mergeEditor.input2.detail
          }, mergeEditor.result.resource)
        };
      };
      const notebookFactoryObject = {
        createEditorInput: notebookEditorInputFactory,
        createDiffEditorInput: notebookDiffEditorInputFactory,
        createUntitledEditorInput: notebookUntitledEditorFactory,
        createMergeEditorInput: mergeEditorInputFactory
      };
      const notebookCellFactoryObject = {
        createEditorInput: notebookEditorInputFactory,
        createDiffEditorInput: notebookDiffEditorInputFactory
      };
      disposables.add(this.s.onDidChangeConfiguration((e) => {
        if (e.affectsConfiguration($rM.textDiffEditorPreview)) {
          const canHandleDiff = !!this.s.getValue($rM.textDiffEditorPreview) && !this.t.isScreenReaderOptimized();
          if (canHandleDiff) {
            notebookFactoryObject.createDiffEditorInput = notebookDiffEditorInputFactory;
            notebookCellFactoryObject.createDiffEditorInput = notebookDiffEditorInputFactory;
          } else {
            notebookFactoryObject.createDiffEditorInput = void 0;
            notebookCellFactoryObject.createDiffEditorInput = void 0;
          }
        }
      }));
      disposables.add(this.t.onDidChangeScreenReaderOptimized(() => {
        const canHandleDiff = !!this.s.getValue($rM.textDiffEditorPreview) && !this.t.isScreenReaderOptimized();
        if (canHandleDiff) {
          notebookFactoryObject.createDiffEditorInput = notebookDiffEditorInputFactory;
          notebookCellFactoryObject.createDiffEditorInput = notebookDiffEditorInputFactory;
        } else {
          notebookFactoryObject.createDiffEditorInput = void 0;
          notebookCellFactoryObject.createDiffEditorInput = void 0;
        }
      }));
      disposables.add(this.n.registerEditor(globPattern, notebookEditorInfo, notebookEditorOptions, notebookFactoryObject));
      disposables.add(this.n.registerEditor(`${Schemas.vscodeNotebookCell}:/**/${globPattern}`, { ...notebookEditorInfo, priority: RegisteredEditorPriority.exclusive }, notebookEditorOptions, notebookCellFactoryObject));
    }
    return disposables;
  }
  G() {
    this.j.clear();
    this.m.clear();
  }
  get(viewType) {
    return this.j.get(viewType);
  }
  add(info, saveMemento = true) {
    if (this.j.has(info.id)) {
      throw new Error(`notebook type '${info.id}' ALREADY EXISTS`);
    }
    this.j.set(info.id, info);
    let editorRegistration;
    if (info.extension) {
      editorRegistration = this.F(info);
      this.m.add(editorRegistration);
    }
    if (saveMemento) {
      const mementoObject = this.g.getMemento(
        0,
        1
        /* StorageTarget.MACHINE */
      );
      mementoObject[$e2b_1.f] = Array.from(this.j.values());
      this.g.saveMemento();
    }
    return this.B($1c(() => {
      const mementoObject = this.g.getMemento(
        0,
        1
        /* StorageTarget.MACHINE */
      );
      mementoObject[$e2b_1.f] = Array.from(this.j.values());
      this.g.saveMemento();
      editorRegistration?.dispose();
      this.j.delete(info.id);
    }));
  }
  getContributedNotebook(resource) {
    const result = [];
    for (const info of this.j.values()) {
      if (info.matches(resource)) {
        result.push(info);
      }
    }
    if (result.length === 0 && resource.scheme === Schemas.untitled) {
      return Array.from(this.j.values());
    }
    return result;
  }
  [Symbol.iterator]() {
    return this.j.values();
  }
};
$e2b = $e2b_1 = __decorate([
  __param(0, $jv),
  __param(1, $wN),
  __param(2, $4L),
  __param(3, $kl),
  __param(4, $ND),
  __param(5, $Pk),
  __param(6, $km),
  __param(7, $orb),
  __param(8, $vl)
], $e2b);
var $f2b = class $f2b2 {
  constructor(storageService) {
    this.c = /* @__PURE__ */ new Map();
    this.f = new $sf(() => this.d.getMemento(
      1,
      1
      /* StorageTarget.MACHINE */
    ));
    this.d = new $Slb("workbench.editor.notebook.preferredRenderer2", storageService);
  }
  clear() {
    this.c.clear();
  }
  get(rendererId) {
    return this.c.get(rendererId);
  }
  getAll() {
    return Array.from(this.c.values());
  }
  add(info) {
    if (this.c.has(info.id)) {
      return;
    }
    this.c.set(info.id, info);
  }
  /** Update and remember the preferred renderer for the given mimetype in this workspace */
  setPreferred(notebookProviderInfo, mimeType, rendererId) {
    const mementoObj = this.f.value;
    const forNotebook = mementoObj[notebookProviderInfo.id];
    if (forNotebook) {
      forNotebook[mimeType] = rendererId;
    } else {
      mementoObj[notebookProviderInfo.id] = { [mimeType]: rendererId };
    }
    this.d.saveMemento();
  }
  findBestRenderers(notebookProviderInfo, mimeType, kernelProvides) {
    let ReuseOrder;
    (function(ReuseOrder2) {
      ReuseOrder2[ReuseOrder2["PreviouslySelected"] = 256] = "PreviouslySelected";
      ReuseOrder2[ReuseOrder2["SameExtensionAsNotebook"] = 512] = "SameExtensionAsNotebook";
      ReuseOrder2[ReuseOrder2["OtherRenderer"] = 768] = "OtherRenderer";
      ReuseOrder2[ReuseOrder2["BuiltIn"] = 1024] = "BuiltIn";
    })(ReuseOrder || (ReuseOrder = {}));
    const preferred = notebookProviderInfo && this.f.value[notebookProviderInfo.id]?.[mimeType];
    const notebookExtId = notebookProviderInfo?.extension?.value;
    const notebookId = notebookProviderInfo?.id;
    const renderers = Array.from(this.c.values()).map((renderer) => {
      const ownScore = kernelProvides === void 0 ? renderer.matchesWithoutKernel(mimeType) : renderer.matches(mimeType, kernelProvides);
      if (ownScore === 3) {
        return void 0;
      }
      const rendererExtId = renderer.extensionId.value;
      const reuseScore = preferred === renderer.id ? 256 : rendererExtId === notebookExtId || $jM.get(rendererExtId)?.has(notebookId) ? 512 : renderer.isBuiltin ? 1024 : 768;
      return {
        ordered: { mimeType, rendererId: renderer.id, isTrusted: true },
        score: reuseScore | ownScore
      };
    }).filter($Hg);
    if (renderers.length === 0) {
      return [{ mimeType, rendererId: $kM, isTrusted: true }];
    }
    return renderers.sort((a, b) => a.score - b.score).map((r2) => r2.ordered);
  }
};
$f2b = __decorate([
  __param(0, $jv)
], $f2b);
var ModelData3 = class {
  get uri() {
    return this.model.uri;
  }
  constructor(model, onWillDispose) {
    this.model = model;
    this.c = new $2c();
    this.c.add(model.onWillDispose(() => onWillDispose(model)));
  }
  getCellIndex(cellUri) {
    return this.model.cells.findIndex((cell) => $oh(cell.uri, cellUri));
  }
  dispose() {
    this.c.dispose();
  }
};
var $g2b = class $g2b2 extends $3c {
  static {
    $g2b_1 = this;
  }
  static {
    this.c = "notebook.viewTypeProvider";
  }
  get m() {
    if (!this.j) {
      this.j = this.B(this.O.createInstance($e2b));
    }
    return this.j;
  }
  constructor(L, M, N, O, P, Q) {
    super();
    this.L = L;
    this.M = M;
    this.N = N;
    this.O = O;
    this.P = P;
    this.Q = Q;
    this.h = /* @__PURE__ */ new Map();
    this.j = void 0;
    this.n = this.O.createInstance($f2b);
    this.s = this.B(new $ze());
    this.onDidChangeOutputRenderers = this.s.event;
    this.t = /* @__PURE__ */ new Set();
    this.u = new $Ec();
    this.w = this.B(new $ze());
    this.y = this.B(new $ze());
    this.z = this.B(new $ze());
    this.C = this.B(new $ze());
    this.onWillAddNotebookDocument = this.w.event;
    this.onDidAddNotebookDocument = this.y.event;
    this.onDidRemoveNotebookDocument = this.C.event;
    this.onWillRemoveNotebookDocument = this.z.event;
    this.D = this.B(new $ze());
    this.onAddViewType = this.D.event;
    this.F = this.B(new $ze());
    this.onWillRemoveViewType = this.F.event;
    this.G = this.B(new $ze());
    this.onDidChangeEditorTypes = this.G.event;
    this.I = true;
    $91b.setHandler((renderers) => {
      this.n.clear();
      for (const extension of renderers) {
        for (const notebookContribution of extension.value) {
          if (!notebookContribution.entrypoint) {
            extension.collector.error(`Notebook renderer does not specify entry point`);
            continue;
          }
          const id2 = notebookContribution.id;
          if (!id2) {
            extension.collector.error(`Notebook renderer does not specify id-property`);
            continue;
          }
          this.n.add(new $_1b({
            id: id2,
            extension: extension.description,
            entrypoint: notebookContribution.entrypoint,
            displayName: notebookContribution.displayName,
            mimeTypes: notebookContribution.mimeTypes || [],
            dependencies: notebookContribution.dependencies,
            optionalDependencies: notebookContribution.optionalDependencies,
            requiresMessaging: notebookContribution.requiresMessaging
          }));
        }
      }
      this.s.fire();
    });
    $01b.setHandler((extensions) => {
      this.t.clear();
      for (const extension of extensions) {
        if (!$zN(extension.description, "contribNotebookStaticPreloads")) {
          continue;
        }
        for (const notebookContribution of extension.value) {
          if (!notebookContribution.entrypoint) {
            extension.collector.error(`Notebook preload does not specify entry point`);
            continue;
          }
          const type = notebookContribution.type;
          if (!type) {
            extension.collector.error(`Notebook preload does not specify type-property`);
            continue;
          }
          this.t.add(new $a2b({
            type,
            extension: extension.description,
            entrypoint: notebookContribution.entrypoint,
            localResourceRoots: notebookContribution.localResourceRoots ?? []
          }));
        }
      }
    });
    const updateOrder = () => {
      this.J = new $lM(this.M.getValue($rM.displayOrder) || [], this.N.isScreenReaderOptimized() ? $iM : $hM);
    };
    updateOrder();
    this.B(this.M.onDidChangeConfiguration((e) => {
      if (e.affectsConfiguration($rM.displayOrder)) {
        updateOrder();
      }
    }));
    this.B(this.N.onDidChangeScreenReaderOptimized(() => {
      updateOrder();
    }));
    this.f = new $Slb($g2b_1.c, this.P);
    this.g = this.f.getMemento(
      1,
      1
      /* StorageTarget.MACHINE */
    );
  }
  getEditorTypes() {
    return [...this.m].map((info) => ({
      id: info.id,
      displayName: info.displayName,
      providerDisplayName: info.providerDisplayName
    }));
  }
  clearEditorCache() {
    this.m.clearEditorCache();
  }
  R(viewType) {
    this.L.activateByEvent(`onNotebook:${viewType}`);
    this.L.activateByEvent(`onNotebook:*`);
  }
  async canResolve(viewType) {
    if (this.h.has(viewType)) {
      return true;
    }
    await this.L.whenInstalledExtensionsRegistered();
    await this.L.activateByEvent(`onNotebookSerializer:${viewType}`);
    return this.h.has(viewType);
  }
  registerContributedNotebookType(viewType, data) {
    const info = new $lrb({
      extension: data.extension,
      id: viewType,
      displayName: data.displayName,
      providerDisplayName: data.providerDisplayName,
      priority: data.priority || RegisteredEditorPriority.default,
      selectors: []
    });
    info.update({ selectors: data.filenamePattern });
    const reg2 = this.m.add(info);
    this.G.fire();
    return $1c(() => {
      reg2.dispose();
      this.G.fire();
    });
  }
  S(viewType, data) {
    if (this.h.has(viewType)) {
      throw new Error(`notebook provider for viewtype '${viewType}' already exists`);
    }
    this.h.set(viewType, data);
    this.D.fire(viewType);
    return $1c(() => {
      this.F.fire(viewType);
      this.h.delete(viewType);
    });
  }
  registerNotebookSerializer(viewType, extensionData, serializer) {
    this.m.get(viewType)?.update({ options: serializer.options });
    this.g[viewType] = extensionData.id.value;
    this.U();
    return this.S(viewType, new $nrb(viewType, serializer, extensionData));
  }
  async withNotebookDataProvider(viewType) {
    const selected = this.m.get(viewType);
    if (!selected) {
      const knownProvider = this.getViewTypeProvider(viewType);
      const actions = knownProvider ? [
        $Zm({
          id: "workbench.notebook.action.installMissingViewType",
          label: localize(8576, null, viewType),
          run: async () => {
            await this.O.createInstance($sDb, knownProvider).run();
          }
        })
      ] : [];
      throw $3m(`UNKNOWN notebook type '${viewType}'`, actions);
    }
    await this.canResolve(selected.id);
    const result = this.h.get(selected.id);
    if (!result) {
      throw new Error(`NO provider registered for view type: '${selected.id}'`);
    }
    return result;
  }
  tryGetDataProviderSync(viewType) {
    const selected = this.m.get(viewType);
    if (!selected) {
      return void 0;
    }
    return this.h.get(selected.id);
  }
  U() {
    this.f.saveMemento();
  }
  getViewTypeProvider(viewType) {
    return this.g[viewType];
  }
  getRendererInfo(rendererId) {
    return this.n.get(rendererId);
  }
  updateMimePreferredRenderer(viewType, mimeType, rendererId, otherMimetypes) {
    const info = this.m.get(viewType);
    if (info) {
      this.n.setPreferred(info, mimeType, rendererId);
    }
    this.J.prioritize(mimeType, otherMimetypes);
  }
  saveMimeDisplayOrder(target) {
    this.M.updateValue($rM.displayOrder, this.J.toArray(), target);
  }
  getRenderers() {
    return this.n.getAll();
  }
  *getStaticPreloads(viewType) {
    for (const preload of this.t) {
      if (preload.type === viewType) {
        yield preload;
      }
    }
  }
  // --- notebook documents: create, destory, retrieve, enumerate
  async createNotebookTextModel(viewType, uri, stream) {
    if (this.u.has(uri)) {
      throw new Error(`notebook for ${uri} already exists`);
    }
    const info = await this.withNotebookDataProvider(viewType);
    if (!(info instanceof $nrb)) {
      throw new Error("CANNOT open file notebook with this provider");
    }
    const bytes = stream ? await $Oi(stream) : $Ci.fromByteArray([]);
    const data = await info.serializer.dataToNotebook(bytes);
    const notebookModel = this.O.createInstance($AL, info.viewType, uri, data.cells, data.metadata, info.serializer.options);
    const modelData = new ModelData3(notebookModel, this.W.bind(this));
    this.u.set(uri, modelData);
    this.Q.addNotebookDocument(modelData);
    this.w.fire(notebookModel);
    this.y.fire(notebookModel);
    this.R(info.viewType);
    return notebookModel;
  }
  async createNotebookTextDocumentSnapshot(uri, context, token) {
    const model = this.getNotebookTextModel(uri);
    if (!model) {
      throw new Error(`notebook for ${uri} doesn't exist`);
    }
    const info = await this.withNotebookDataProvider(model.viewType);
    if (!(info instanceof $nrb)) {
      throw new Error("CANNOT open file notebook with this provider");
    }
    const serializer = info.serializer;
    const outputSizeLimit = this.M.getValue($rM.outputBackupSizeLimit) * 1024;
    const data = model.createSnapshot({ context, outputSizeLimit, transientOptions: serializer.options });
    const indentAmount = model.metadata.indentAmount;
    if (typeof indentAmount === "string" && indentAmount) {
      data.metadata.indentAmount = indentAmount;
    }
    const bytes = await serializer.notebookToData(data);
    if (token.isCancellationRequested) {
      throw new $lb();
    }
    return $Qi(bytes);
  }
  async restoreNotebookTextModelFromSnapshot(uri, viewType, snapshot) {
    const model = this.getNotebookTextModel(uri);
    if (!model) {
      throw new Error(`notebook for ${uri} doesn't exist`);
    }
    const info = await this.withNotebookDataProvider(model.viewType);
    if (!(info instanceof $nrb)) {
      throw new Error("CANNOT open file notebook with this provider");
    }
    const serializer = info.serializer;
    const bytes = await $Oi(snapshot);
    const data = await info.serializer.dataToNotebook(bytes);
    model.restoreSnapshot(data, serializer.options);
    return model;
  }
  getNotebookTextModel(uri) {
    return this.u.get(uri)?.model;
  }
  getNotebookTextModels() {
    return Iterable.map(this.u.values(), (data) => data.model);
  }
  listNotebookDocuments() {
    return [...this.u].map((e) => e[1].model);
  }
  W(model) {
    const modelData = this.u.get(model.uri);
    if (modelData) {
      this.z.fire(modelData.model);
      this.u.delete(model.uri);
      this.Q.removeNotebookDocument(modelData);
      modelData.dispose();
      this.C.fire(modelData.model);
    }
  }
  getOutputMimeTypeInfo(textModel, kernelProvides, output) {
    const sorted = this.J.sort(new Set(output.outputs.map((op) => op.mime)));
    const notebookProviderInfo = this.m.get(textModel.viewType);
    return sorted.flatMap((mimeType) => this.n.findBestRenderers(notebookProviderInfo, mimeType, kernelProvides)).sort((a, b) => (a.rendererId === $kM ? 1 : 0) - (b.rendererId === $kM ? 1 : 0));
  }
  getContributedNotebookTypes(resource) {
    if (resource) {
      return this.m.getContributedNotebook(resource);
    }
    return [...this.m];
  }
  hasSupportedNotebooks(resource) {
    const contribution = this.m.getContributedNotebook(resource);
    if (!contribution.length) {
      return false;
    }
    return contribution.some((info) => info.matches(resource) && (info.priority === RegisteredEditorPriority.default || info.priority === RegisteredEditorPriority.exclusive));
  }
  getContributedNotebookType(viewType) {
    return this.m.get(viewType);
  }
  getNotebookProviderResourceRoots() {
    const ret = [];
    this.h.forEach((val) => {
      if (val.extensionData.location) {
        ret.push(URI.revive(val.extensionData.location));
      }
    });
    return ret;
  }
  // --- copy & paste
  setToCopy(items, isCopy) {
    this.H = items;
    this.I = isCopy;
  }
  getToCopy() {
    if (this.H) {
      return { items: this.H, isCopy: this.I };
    }
    return void 0;
  }
};
$g2b = $g2b_1 = __decorate([
  __param(0, $wN),
  __param(1, $kl),
  __param(2, $ND),
  __param(3, $Pk),
  __param(4, $jv),
  __param(5, $8L)
], $g2b);

// out-build/vs/platform/layout/browser/zIndexRegistry.js
var ZIndex;
(function(ZIndex2) {
  ZIndex2[ZIndex2["Base"] = 0] = "Base";
  ZIndex2[ZIndex2["Sash"] = 35] = "Sash";
  ZIndex2[ZIndex2["SuggestWidget"] = 40] = "SuggestWidget";
  ZIndex2[ZIndex2["Hover"] = 50] = "Hover";
  ZIndex2[ZIndex2["DragImage"] = 1e3] = "DragImage";
  ZIndex2[ZIndex2["MenubarMenuItemsHolder"] = 2e3] = "MenubarMenuItemsHolder";
  ZIndex2[ZIndex2["ContextView"] = 2500] = "ContextView";
  ZIndex2[ZIndex2["ModalDialog"] = 2600] = "ModalDialog";
  ZIndex2[ZIndex2["PaneDropOverlay"] = 1e4] = "PaneDropOverlay";
})(ZIndex || (ZIndex = {}));
var ZIndexValues = Object.keys(ZIndex).filter((key2) => !isNaN(Number(key2))).map((key2) => Number(key2)).sort((a, b) => b - a);
function findBase(z) {
  for (const zi of ZIndexValues) {
    if (z >= zi) {
      return zi;
    }
  }
  return -1;
}
var ZIndexRegistry = class {
  constructor() {
    this.c = $VZ();
    this.d = /* @__PURE__ */ new Map();
    this.e = new $8h(() => this.g(), 200);
  }
  registerZIndex(relativeLayer, z, name) {
    if (this.d.get(name)) {
      throw new Error(`z-index with name ${name} has already been registered.`);
    }
    const proposedZValue = relativeLayer + z;
    if (findBase(proposedZValue) !== relativeLayer) {
      throw new Error(`Relative layer: ${relativeLayer} + z-index: ${z} exceeds next layer ${proposedZValue}.`);
    }
    this.d.set(name, proposedZValue);
    this.e.schedule();
    return this.f(name);
  }
  f(name) {
    return `--z-index-${name}`;
  }
  g() {
    $$i(this.c);
    let ruleBuilder = "";
    this.d.forEach((zIndex, name) => {
      ruleBuilder += `${this.f(name)}: ${zIndex};
`;
    });
    $XZ(":root", ruleBuilder, this.c);
  }
};
var zIndexRegistry = new ZIndexRegistry();
function $uFb(relativeLayer, z, name) {
  return zIndexRegistry.registerZIndex(relativeLayer, z, name);
}

// out-build/vs/workbench/contrib/debug/browser/debugIcons.js
var $vFb = $9r("debug-console-view-icon", $6l.debugConsole, localize(5837, null));
var $wFb = $9r("run-view-icon", $6l.debugAlt, localize(5838, null));
var $xFb = $9r("variables-view-icon", $6l.debugAlt, localize(5839, null));
var $yFb = $9r("watch-view-icon", $6l.debugAlt, localize(5840, null));
var $zFb = $9r("callstack-view-icon", $6l.debugAlt, localize(5841, null));
var $AFb = $9r("breakpoints-view-icon", $6l.debugAlt, localize(5842, null));
var $BFb = $9r("loaded-scripts-view-icon", $6l.debugAlt, localize(5843, null));
var $CFb = {
  regular: $9r("debug-breakpoint", $6l.debugBreakpoint, localize(5844, null)),
  disabled: $9r("debug-breakpoint-disabled", $6l.debugBreakpointDisabled, localize(5845, null)),
  unverified: $9r("debug-breakpoint-unverified", $6l.debugBreakpointUnverified, localize(5846, null)),
  pending: $9r("debug-breakpoint-pending", $6l.debugBreakpointPending, localize(5847, null))
};
var $DFb = {
  regular: $9r("debug-breakpoint-function", $6l.debugBreakpointFunction, localize(5848, null)),
  disabled: $9r("debug-breakpoint-function-disabled", $6l.debugBreakpointFunctionDisabled, localize(5849, null)),
  unverified: $9r("debug-breakpoint-function-unverified", $6l.debugBreakpointFunctionUnverified, localize(5850, null))
};
var $EFb = {
  regular: $9r("debug-breakpoint-conditional", $6l.debugBreakpointConditional, localize(5851, null)),
  disabled: $9r("debug-breakpoint-conditional-disabled", $6l.debugBreakpointConditionalDisabled, localize(5852, null)),
  unverified: $9r("debug-breakpoint-conditional-unverified", $6l.debugBreakpointConditionalUnverified, localize(5853, null))
};
var $FFb = {
  regular: $9r("debug-breakpoint-data", $6l.debugBreakpointData, localize(5854, null)),
  disabled: $9r("debug-breakpoint-data-disabled", $6l.debugBreakpointDataDisabled, localize(5855, null)),
  unverified: $9r("debug-breakpoint-data-unverified", $6l.debugBreakpointDataUnverified, localize(5856, null))
};
var $GFb = {
  regular: $9r("debug-breakpoint-log", $6l.debugBreakpointLog, localize(5857, null)),
  disabled: $9r("debug-breakpoint-log-disabled", $6l.debugBreakpointLogDisabled, localize(5858, null)),
  unverified: $9r("debug-breakpoint-log-unverified", $6l.debugBreakpointLogUnverified, localize(5859, null))
};
var $HFb = $9r("debug-hint", $6l.debugHint, localize(5860, null));
var $IFb = $9r("debug-breakpoint-unsupported", $6l.debugBreakpointUnsupported, localize(5861, null));
var $JFb = [$CFb, $DFb, $EFb, $FFb, $GFb];
var $KFb = $9r("debug-stackframe", $6l.debugStackframe, localize(5862, null));
var $LFb = $9r("debug-stackframe-focused", $6l.debugStackframeFocused, localize(5863, null));
var $MFb = $9r("debug-gripper", $6l.gripper, localize(5864, null));
var $NFb = $9r("debug-restart-frame", $6l.debugRestartFrame, localize(5865, null));
var $OFb = $9r("debug-stop", $6l.debugStop, localize(5866, null));
var $PFb = $9r("debug-disconnect", $6l.debugDisconnect, localize(5867, null));
var $QFb = $9r("debug-restart", $6l.debugRestart, localize(5868, null));
var $RFb = $9r("debug-step-over", $6l.debugStepOver, localize(5869, null));
var $SFb = $9r("debug-step-into", $6l.debugStepInto, localize(5870, null));
var $TFb = $9r("debug-step-out", $6l.debugStepOut, localize(5871, null));
var $UFb = $9r("debug-step-back", $6l.debugStepBack, localize(5872, null));
var $VFb = $9r("debug-pause", $6l.debugPause, localize(5873, null));
var $WFb = $9r("debug-continue", $6l.debugContinue, localize(5874, null));
var $XFb = $9r("debug-reverse-continue", $6l.debugReverseContinue, localize(5875, null));
var $YFb = $9r("debug-run", $6l.run, localize(5876, null));
var $ZFb = $9r("debug-start", $6l.debugStart, localize(5877, null));
var $1Fb = $9r("debug-configure", $6l.gear, localize(5878, null));
var $2Fb = $9r("debug-console", $6l.gear, localize(5879, null));
var $3Fb = $9r("debug-remove-config", $6l.trash, localize(5880, null));
var $4Fb = $9r("debug-collapse-all", $6l.collapseAll, localize(5881, null));
var $5Fb = $9r("callstack-view-session", $6l.bug, localize(5882, null));
var $6Fb = $9r("debug-console-clear-all", $6l.clearAll, localize(5883, null));
var $7Fb = $9r("watch-expressions-remove-all", $6l.closeAll, localize(5884, null));
var $8Fb = $9r("watch-expression-remove", $6l.removeClose, localize(5885, null));
var $9Fb = $9r("watch-expressions-add", $6l.add, localize(5886, null));
var $0Fb = $9r("watch-expressions-add-function-breakpoint", $6l.add, localize(5887, null));
var $$Fb = $9r("watch-expressions-add-data-breakpoint", $6l.variableGroup, localize(5888, null));
var $_Fb = $9r("breakpoints-remove-all", $6l.closeAll, localize(5889, null));
var $aGb = $9r("breakpoints-activate", $6l.activateBreakpoints, localize(5890, null));
var $bGb = $9r("debug-console-evaluation-input", $6l.arrowSmallRight, localize(5891, null));
var $cGb = $9r("debug-console-evaluation-prompt", $6l.chevronRight, localize(5892, null));
var $dGb = $9r("debug-inspect-memory", $6l.fileBinary, localize(5893, null));

// out-build/vs/workbench/contrib/debug/browser/debugColors.js
var $eGb = $5n("debugToolBar.background", {
  dark: "#333333",
  light: "#F3F3F3",
  hcDark: "#000000",
  hcLight: "#FFFFFF"
}, localize(5756, null));
var $fGb = $5n("debugToolBar.border", null, localize(5757, null));
var $gGb = $5n("debugIcon.startForeground", {
  dark: "#89D185",
  light: "#388A34",
  hcDark: "#89D185",
  hcLight: "#388A34"
}, localize(5758, null));
function $hGb() {
  const debugTokenExpressionName = $5n("debugTokenExpression.name", { dark: "#c586c0", light: "#9b46b0", hcDark: $eo, hcLight: $eo }, "Foreground color for the token names shown in the debug views (ie. the Variables or Watch view).");
  const debugTokenExpressionType = $5n("debugTokenExpression.type", { dark: "#4A90E2", light: "#4A90E2", hcDark: $eo, hcLight: $eo }, "Foreground color for the token types shown in the debug views (ie. the Variables or Watch view).");
  const debugTokenExpressionValue = $5n("debugTokenExpression.value", { dark: "#cccccc99", light: "#6c6c6ccc", hcDark: $eo, hcLight: $eo }, "Foreground color for the token values shown in the debug views (ie. the Variables or Watch view).");
  const debugTokenExpressionString = $5n("debugTokenExpression.string", { dark: "#ce9178", light: "#a31515", hcDark: "#f48771", hcLight: "#a31515" }, "Foreground color for strings in the debug views (ie. the Variables or Watch view).");
  const debugTokenExpressionBoolean = $5n("debugTokenExpression.boolean", { dark: "#4e94ce", light: "#0000ff", hcDark: "#75bdfe", hcLight: "#0000ff" }, "Foreground color for booleans in the debug views (ie. the Variables or Watch view).");
  const debugTokenExpressionNumber = $5n("debugTokenExpression.number", { dark: "#b5cea8", light: "#098658", hcDark: "#89d185", hcLight: "#098658" }, "Foreground color for numbers in the debug views (ie. the Variables or Watch view).");
  const debugTokenExpressionError = $5n("debugTokenExpression.error", { dark: "#f48771", light: "#e51400", hcDark: "#f48771", hcLight: "#e51400" }, "Foreground color for expression errors in the debug views (ie. the Variables or Watch view) and for error logs shown in the debug console.");
  const debugViewExceptionLabelForeground = $5n("debugView.exceptionLabelForeground", { dark: $eo, light: "#FFF", hcDark: $eo, hcLight: $eo }, "Foreground color for a label shown in the CALL STACK view when the debugger breaks on an exception.");
  const debugViewExceptionLabelBackground = $5n("debugView.exceptionLabelBackground", { dark: "#6C2022", light: "#A31515", hcDark: "#6C2022", hcLight: "#A31515" }, "Background color for a label shown in the CALL STACK view when the debugger breaks on an exception.");
  const debugViewStateLabelForeground = $5n("debugView.stateLabelForeground", $eo, "Foreground color for a label in the CALL STACK view showing the current session's or thread's state.");
  const debugViewStateLabelBackground = $5n("debugView.stateLabelBackground", "#88888844", "Background color for a label in the CALL STACK view showing the current session's or thread's state.");
  const debugViewValueChangedHighlight = $5n("debugView.valueChangedHighlight", "#569CD6", "Color used to highlight value changes in the debug views (ie. in the Variables view).");
  const debugConsoleInfoForeground = $5n("debugConsole.infoForeground", { dark: $2o, light: $2o, hcDark: $eo, hcLight: $eo }, "Foreground color for info messages in debug REPL console.");
  const debugConsoleWarningForeground = $5n("debugConsole.warningForeground", { dark: $Yo, light: $Yo, hcDark: "#008000", hcLight: $Yo }, "Foreground color for warning messages in debug REPL console.");
  const debugConsoleErrorForeground = $5n("debugConsole.errorForeground", $go, "Foreground color for error messages in debug REPL console.");
  const debugConsoleSourceForeground = $5n("debugConsole.sourceForeground", $eo, "Foreground color for source filenames in debug REPL console.");
  const debugConsoleInputIconForeground = $5n("debugConsoleInputIcon.foreground", $eo, "Foreground color for debug console input marker icon.");
  const debugIconPauseForeground = $5n("debugIcon.pauseForeground", {
    dark: "#75BEFF",
    light: "#007ACC",
    hcDark: "#75BEFF",
    hcLight: "#007ACC"
  }, localize(5759, null));
  const debugIconStopForeground = $5n("debugIcon.stopForeground", {
    dark: "#F48771",
    light: "#A1260D",
    hcDark: "#F48771",
    hcLight: "#A1260D"
  }, localize(5760, null));
  const debugIconDisconnectForeground = $5n("debugIcon.disconnectForeground", {
    dark: "#F48771",
    light: "#A1260D",
    hcDark: "#F48771",
    hcLight: "#A1260D"
  }, localize(5761, null));
  const debugIconRestartForeground = $5n("debugIcon.restartForeground", {
    dark: "#89D185",
    light: "#388A34",
    hcDark: "#89D185",
    hcLight: "#388A34"
  }, localize(5762, null));
  const debugIconStepOverForeground = $5n("debugIcon.stepOverForeground", {
    dark: "#75BEFF",
    light: "#007ACC",
    hcDark: "#75BEFF",
    hcLight: "#007ACC"
  }, localize(5763, null));
  const debugIconStepIntoForeground = $5n("debugIcon.stepIntoForeground", {
    dark: "#75BEFF",
    light: "#007ACC",
    hcDark: "#75BEFF",
    hcLight: "#007ACC"
  }, localize(5764, null));
  const debugIconStepOutForeground = $5n("debugIcon.stepOutForeground", {
    dark: "#75BEFF",
    light: "#007ACC",
    hcDark: "#75BEFF",
    hcLight: "#007ACC"
  }, localize(5765, null));
  const debugIconContinueForeground = $5n("debugIcon.continueForeground", {
    dark: "#75BEFF",
    light: "#007ACC",
    hcDark: "#75BEFF",
    hcLight: "#007ACC"
  }, localize(5766, null));
  const debugIconStepBackForeground = $5n("debugIcon.stepBackForeground", {
    dark: "#75BEFF",
    light: "#007ACC",
    hcDark: "#75BEFF",
    hcLight: "#007ACC"
  }, localize(5767, null));
  $ms((theme, collector) => {
    const badgeBackgroundColor = theme.getColor($wo);
    const badgeForegroundColor = theme.getColor($xo);
    const listDeemphasizedForegroundColor = theme.getColor($Fr);
    const debugViewExceptionLabelForegroundColor = theme.getColor(debugViewExceptionLabelForeground);
    const debugViewExceptionLabelBackgroundColor = theme.getColor(debugViewExceptionLabelBackground);
    const debugViewStateLabelForegroundColor = theme.getColor(debugViewStateLabelForeground);
    const debugViewStateLabelBackgroundColor = theme.getColor(debugViewStateLabelBackground);
    const debugViewValueChangedHighlightColor = theme.getColor(debugViewValueChangedHighlight);
    const toolbarHoverBackgroundColor = theme.getColor($Tp);
    collector.addRule(`
			/* Text colour of the call stack row's filename */
			.debug-pane .debug-call-stack .monaco-list-row:not(.selected) .stack-frame > .file .file-name {
				color: ${listDeemphasizedForegroundColor}
			}

			/* Line & column number "badge" for selected call stack row */
			.debug-pane .monaco-list-row.selected .line-number {
				background-color: ${badgeBackgroundColor};
				color: ${badgeForegroundColor};
			}

			/* Line & column number "badge" for unselected call stack row (basically all other rows) */
			.debug-pane .line-number {
				background-color: ${badgeBackgroundColor.transparent(0.6)};
				color: ${badgeForegroundColor.transparent(0.6)};
			}

			/* State "badge" displaying the active session's current state.
			* Only visible when there are more active debug sessions/threads running.
			*/
			.debug-pane .debug-call-stack .thread > .state.label,
			.debug-pane .debug-call-stack .session > .state.label {
				background-color: ${debugViewStateLabelBackgroundColor};
				color: ${debugViewStateLabelForegroundColor};
			}

			/* State "badge" displaying the active session's current state.
			* Only visible when there are more active debug sessions/threads running
			* and thread paused due to a thrown exception.
			*/
			.debug-pane .debug-call-stack .thread > .state.label.exception,
			.debug-pane .debug-call-stack .session > .state.label.exception {
				background-color: ${debugViewExceptionLabelBackgroundColor};
				color: ${debugViewExceptionLabelForegroundColor};
			}

			/* Info "badge" shown when the debugger pauses due to a thrown exception. */
			.debug-pane .call-stack-state-message > .label.exception {
				background-color: ${debugViewExceptionLabelBackgroundColor};
				color: ${debugViewExceptionLabelForegroundColor};
			}

			/* Animation of changed values in Debug viewlet */
			@keyframes debugViewletValueChanged {
				0%   { background-color: ${debugViewValueChangedHighlightColor.transparent(0)} }
				5%   { background-color: ${debugViewValueChangedHighlightColor.transparent(0.9)} }
				100% { background-color: ${debugViewValueChangedHighlightColor.transparent(0.3)} }
			}

			.debug-pane .monaco-list-row .expression .value.changed {
				background-color: ${debugViewValueChangedHighlightColor.transparent(0.3)};
				animation-name: debugViewletValueChanged;
				animation-duration: 1s;
				animation-fill-mode: forwards;
			}

			.monaco-list-row .expression .lazy-button:hover {
				background-color: ${toolbarHoverBackgroundColor}
			}
		`);
    const contrastBorderColor = theme.getColor($ko);
    if (contrastBorderColor) {
      collector.addRule(`
			.debug-pane .line-number {
				border: 1px solid ${contrastBorderColor};
			}
			`);
    }
    if ($es(theme.type)) {
      collector.addRule(`
			.debug-pane .line-number {
				background-color: ${badgeBackgroundColor};
				color: ${badgeForegroundColor};
			}`);
    }
    const tokenNameColor = theme.getColor(debugTokenExpressionName);
    const tokenTypeColor = theme.getColor(debugTokenExpressionType);
    const tokenValueColor = theme.getColor(debugTokenExpressionValue);
    const tokenStringColor = theme.getColor(debugTokenExpressionString);
    const tokenBooleanColor = theme.getColor(debugTokenExpressionBoolean);
    const tokenErrorColor = theme.getColor(debugTokenExpressionError);
    const tokenNumberColor = theme.getColor(debugTokenExpressionNumber);
    collector.addRule(`
			.monaco-workbench .monaco-list-row .expression .name {
				color: ${tokenNameColor};
			}

			.monaco-workbench .monaco-list-row .expression .type {
				color: ${tokenTypeColor};
			}

			.monaco-workbench .monaco-list-row .expression .value,
			.monaco-workbench .debug-hover-widget .value {
				color: ${tokenValueColor};
			}

			.monaco-workbench .monaco-list-row .expression .value.string,
			.monaco-workbench .debug-hover-widget .value.string {
				color: ${tokenStringColor};
			}

			.monaco-workbench .monaco-list-row .expression .value.boolean,
			.monaco-workbench .debug-hover-widget .value.boolean {
				color: ${tokenBooleanColor};
			}

			.monaco-workbench .monaco-list-row .expression .error,
			.monaco-workbench .debug-hover-widget .error,
			.monaco-workbench .debug-pane .debug-variables .scope .error {
				color: ${tokenErrorColor};
			}

			.monaco-workbench .monaco-list-row .expression .value.number,
			.monaco-workbench .debug-hover-widget .value.number {
				color: ${tokenNumberColor};
			}
		`);
    const debugConsoleInputBorderColor = theme.getColor($zq) || $Vn.fromHex("#80808060");
    const debugConsoleInfoForegroundColor = theme.getColor(debugConsoleInfoForeground);
    const debugConsoleWarningForegroundColor = theme.getColor(debugConsoleWarningForeground);
    const debugConsoleErrorForegroundColor = theme.getColor(debugConsoleErrorForeground);
    const debugConsoleSourceForegroundColor = theme.getColor(debugConsoleSourceForeground);
    const debugConsoleInputIconForegroundColor = theme.getColor(debugConsoleInputIconForeground);
    collector.addRule(`
			.repl .repl-input-wrapper {
				border-top: 1px solid ${debugConsoleInputBorderColor};
			}

			.monaco-workbench .repl .repl-tree .output .expression .value.info {
				color: ${debugConsoleInfoForegroundColor};
			}

			.monaco-workbench .repl .repl-tree .output .expression .value.warn {
				color: ${debugConsoleWarningForegroundColor};
			}

			.monaco-workbench .repl .repl-tree .output .expression .value.error {
				color: ${debugConsoleErrorForegroundColor};
			}

			.monaco-workbench .repl .repl-tree .output .expression .source {
				color: ${debugConsoleSourceForegroundColor};
			}

			.monaco-workbench .repl .repl-tree .monaco-tl-contents .arrow {
				color: ${debugConsoleInputIconForegroundColor};
			}
		`);
    if (!theme.defines(debugConsoleInputIconForeground)) {
      collector.addRule(`
				.monaco-workbench.vs .repl .repl-tree .monaco-tl-contents .arrow {
					opacity: 0.25;
				}

				.monaco-workbench.vs-dark .repl .repl-tree .monaco-tl-contents .arrow {
					opacity: 0.4;
				}

				.monaco-workbench.hc-black .repl .repl-tree .monaco-tl-contents .arrow,
				.monaco-workbench.hc-light .repl .repl-tree .monaco-tl-contents .arrow {
					opacity: 1;
				}
			`);
    }
    const debugIconStartColor = theme.getColor($gGb);
    if (debugIconStartColor) {
      collector.addRule(`.monaco-workbench ${ThemeIcon.asCSSSelector($ZFb)} { color: ${debugIconStartColor}; }`);
    }
    const debugIconPauseColor = theme.getColor(debugIconPauseForeground);
    if (debugIconPauseColor) {
      collector.addRule(`.monaco-workbench .part > .title > .title-actions .action-label${ThemeIcon.asCSSSelector($VFb)}, .monaco-workbench ${ThemeIcon.asCSSSelector($VFb)} { color: ${debugIconPauseColor}; }`);
    }
    const debugIconStopColor = theme.getColor(debugIconStopForeground);
    if (debugIconStopColor) {
      collector.addRule(`.monaco-workbench .part > .title > .title-actions .action-label${ThemeIcon.asCSSSelector($OFb)},.monaco-workbench ${ThemeIcon.asCSSSelector($OFb)} { color: ${debugIconStopColor}; }`);
    }
    const debugIconDisconnectColor = theme.getColor(debugIconDisconnectForeground);
    if (debugIconDisconnectColor) {
      collector.addRule(`.monaco-workbench .part > .title > .title-actions .action-label${ThemeIcon.asCSSSelector($PFb)},.monaco-workbench .debug-view-content ${ThemeIcon.asCSSSelector($PFb)}, .monaco-workbench .debug-toolbar ${ThemeIcon.asCSSSelector($PFb)}, .monaco-workbench .command-center-center ${ThemeIcon.asCSSSelector($PFb)} { color: ${debugIconDisconnectColor}; }`);
    }
    const debugIconRestartColor = theme.getColor(debugIconRestartForeground);
    if (debugIconRestartColor) {
      collector.addRule(`.monaco-workbench ${ThemeIcon.asCSSSelector($QFb)}, .monaco-workbench ${ThemeIcon.asCSSSelector($NFb)}, .monaco-workbench .part > .title > .title-actions .action-label${ThemeIcon.asCSSSelector($QFb)}, .monaco-workbench .part > .title > .title-actions .action-label${ThemeIcon.asCSSSelector($NFb)} { color: ${debugIconRestartColor}; }`);
    }
    const debugIconStepOverColor = theme.getColor(debugIconStepOverForeground);
    if (debugIconStepOverColor) {
      collector.addRule(`.monaco-workbench .part > .title > .title-actions .action-label${ThemeIcon.asCSSSelector($RFb)}, .monaco-workbench ${ThemeIcon.asCSSSelector($RFb)} { color: ${debugIconStepOverColor}; }`);
    }
    const debugIconStepIntoColor = theme.getColor(debugIconStepIntoForeground);
    if (debugIconStepIntoColor) {
      collector.addRule(`.monaco-workbench .part > .title > .title-actions .action-label${ThemeIcon.asCSSSelector($SFb)}, .monaco-workbench .part > .title > .title-actions .action-label${ThemeIcon.asCSSSelector($SFb)}, .monaco-workbench ${ThemeIcon.asCSSSelector($SFb)} { color: ${debugIconStepIntoColor}; }`);
    }
    const debugIconStepOutColor = theme.getColor(debugIconStepOutForeground);
    if (debugIconStepOutColor) {
      collector.addRule(`.monaco-workbench .part > .title > .title-actions .action-label${ThemeIcon.asCSSSelector($TFb)}, .monaco-workbench .part > .title > .title-actions .action-label${ThemeIcon.asCSSSelector($TFb)}, .monaco-workbench ${ThemeIcon.asCSSSelector($TFb)} { color: ${debugIconStepOutColor}; }`);
    }
    const debugIconContinueColor = theme.getColor(debugIconContinueForeground);
    if (debugIconContinueColor) {
      collector.addRule(`.monaco-workbench .part > .title > .title-actions .action-label${ThemeIcon.asCSSSelector($WFb)}, .monaco-workbench ${ThemeIcon.asCSSSelector($WFb)}, .monaco-workbench .part > .title > .title-actions .action-label${ThemeIcon.asCSSSelector($XFb)}, .monaco-workbench ${ThemeIcon.asCSSSelector($XFb)} { color: ${debugIconContinueColor}; }`);
    }
    const debugIconStepBackColor = theme.getColor(debugIconStepBackForeground);
    if (debugIconStepBackColor) {
      collector.addRule(`.monaco-workbench .part > .title > .title-actions .action-label${ThemeIcon.asCSSSelector($UFb)}, .monaco-workbench ${ThemeIcon.asCSSSelector($UFb)} { color: ${debugIconStepBackColor}; }`);
    }
  });
}

// out-build/vs/workbench/contrib/notebook/browser/notebookLogger.js
var NotebookLogger = class {
  constructor() {
    this.a = 0;
    this.b();
  }
  b() {
  }
  debug(...args2) {
    const date = /* @__PURE__ */ new Date();
    console.log(`${date.getSeconds()}:${date.getMilliseconds().toString().padStart(3, "0")}`, `frame #${this.a}: `, ...args2);
  }
};
var instance = new NotebookLogger();
function $jGb(...args2) {
  instance.debug(...args2);
}

// out-build/vs/workbench/contrib/notebook/browser/notebookViewEvents.js
var NotebookViewEventType;
(function(NotebookViewEventType2) {
  NotebookViewEventType2[NotebookViewEventType2["LayoutChanged"] = 1] = "LayoutChanged";
  NotebookViewEventType2[NotebookViewEventType2["MetadataChanged"] = 2] = "MetadataChanged";
  NotebookViewEventType2[NotebookViewEventType2["CellStateChanged"] = 3] = "CellStateChanged";
})(NotebookViewEventType || (NotebookViewEventType = {}));
var $irb = class {
  constructor(source, value) {
    this.source = source;
    this.value = value;
    this.type = NotebookViewEventType.LayoutChanged;
  }
};
var $jrb = class {
  constructor(source) {
    this.source = source;
    this.type = NotebookViewEventType.MetadataChanged;
  }
};
var $krb = class {
  constructor(source, cell) {
    this.source = source;
    this.cell = cell;
    this.type = NotebookViewEventType.CellStateChanged;
  }
};

// out-build/vs/workbench/contrib/notebook/browser/controller/cellOperations.js
async function $2Ib(kind, context, language, mime) {
  const { notebookEditor } = context;
  if (!notebookEditor.hasModel()) {
    return;
  }
  if (notebookEditor.isReadOnly) {
    return;
  }
  if (context.ui && context.cell) {
    const { cell } = context;
    if (cell.cellKind === kind) {
      return;
    }
    const text2 = cell.getText();
    const idx = notebookEditor.getCellIndex(cell);
    if (language === void 0) {
      const availableLanguages = notebookEditor.activeKernel?.supportedLanguages ?? [];
      language = availableLanguages[0] ?? $KF;
    }
    notebookEditor.textModel.applyEdits([
      {
        editType: 1,
        index: idx,
        count: 1,
        cells: [{
          cellKind: kind,
          source: text2,
          language,
          mime: mime ?? cell.mime,
          outputs: cell.model.outputs,
          metadata: cell.metadata
        }]
      }
    ], true, {
      kind: SelectionStateType.Index,
      focus: notebookEditor.getFocus(),
      selections: notebookEditor.getSelections()
    }, () => {
      return {
        kind: SelectionStateType.Index,
        focus: notebookEditor.getFocus(),
        selections: notebookEditor.getSelections()
      };
    }, void 0, true);
    const newCell = notebookEditor.cellAt(idx);
    await notebookEditor.focusNotebookCell(newCell, cell.getEditState() === CellEditState.Editing ? "editor" : "container");
  } else if (context.selectedCells) {
    const selectedCells = context.selectedCells;
    const rawEdits = [];
    selectedCells.forEach((cell) => {
      if (cell.cellKind === kind) {
        return;
      }
      const text2 = cell.getText();
      const idx = notebookEditor.getCellIndex(cell);
      if (language === void 0) {
        const availableLanguages = notebookEditor.activeKernel?.supportedLanguages ?? [];
        language = availableLanguages[0] ?? $KF;
      }
      rawEdits.push({
        editType: 1,
        index: idx,
        count: 1,
        cells: [{
          cellKind: kind,
          source: text2,
          language,
          mime: mime ?? cell.mime,
          outputs: cell.model.outputs,
          metadata: cell.metadata
        }]
      });
    });
    notebookEditor.textModel.applyEdits(rawEdits, true, {
      kind: SelectionStateType.Index,
      focus: notebookEditor.getFocus(),
      selections: notebookEditor.getSelections()
    }, () => {
      return {
        kind: SelectionStateType.Index,
        focus: notebookEditor.getFocus(),
        selections: notebookEditor.getSelections()
      };
    }, void 0, true);
  }
}
function $3Ib(editor, cell) {
  const textModel = editor.textModel;
  const selections = editor.getSelections();
  const targetCellIndex = editor.getCellIndex(cell);
  const containingSelection = selections.find((selection) => selection.start <= targetCellIndex && targetCellIndex < selection.end);
  const computeUndoRedo = !editor.isReadOnly || textModel.viewType === "interactive";
  if (containingSelection) {
    const edits = selections.reverse().map((selection) => ({
      editType: 1,
      index: selection.start,
      count: selection.end - selection.start,
      cells: []
    }));
    const nextCellAfterContainingSelection = containingSelection.end >= editor.getLength() ? void 0 : editor.cellAt(containingSelection.end);
    textModel.applyEdits(edits, true, { kind: SelectionStateType.Index, focus: editor.getFocus(), selections: editor.getSelections() }, () => {
      if (nextCellAfterContainingSelection) {
        const cellIndex = textModel.cells.findIndex((cell2) => cell2.handle === nextCellAfterContainingSelection.handle);
        return { kind: SelectionStateType.Index, focus: { start: cellIndex, end: cellIndex + 1 }, selections: [{ start: cellIndex, end: cellIndex + 1 }] };
      } else {
        if (textModel.length) {
          const lastCellIndex = textModel.length - 1;
          return { kind: SelectionStateType.Index, focus: { start: lastCellIndex, end: lastCellIndex + 1 }, selections: [{ start: lastCellIndex, end: lastCellIndex + 1 }] };
        } else {
          return { kind: SelectionStateType.Index, focus: { start: 0, end: 0 }, selections: [{ start: 0, end: 0 }] };
        }
      }
    }, void 0, computeUndoRedo);
  } else {
    const focus = editor.getFocus();
    const edits = [{
      editType: 1,
      index: targetCellIndex,
      count: 1,
      cells: []
    }];
    const finalSelections = [];
    for (let i2 = 0; i2 < selections.length; i2++) {
      const selection = selections[i2];
      if (selection.end <= targetCellIndex) {
        finalSelections.push(selection);
      } else if (selection.start > targetCellIndex) {
        finalSelections.push({ start: selection.start - 1, end: selection.end - 1 });
      } else {
        finalSelections.push({ start: targetCellIndex, end: targetCellIndex + 1 });
      }
    }
    if (editor.cellAt(focus.start) === cell) {
      const newFocus = focus.end === textModel.length ? { start: focus.start - 1, end: focus.end - 1 } : focus;
      textModel.applyEdits(edits, true, { kind: SelectionStateType.Index, focus: editor.getFocus(), selections: editor.getSelections() }, () => ({
        kind: SelectionStateType.Index,
        focus: newFocus,
        selections: finalSelections
      }), void 0, computeUndoRedo);
    } else {
      const newFocus = focus.start > targetCellIndex ? { start: focus.start - 1, end: focus.end - 1 } : focus;
      textModel.applyEdits(edits, true, { kind: SelectionStateType.Index, focus: editor.getFocus(), selections: editor.getSelections() }, () => ({
        kind: SelectionStateType.Index,
        focus: newFocus,
        selections: finalSelections
      }), void 0, computeUndoRedo);
    }
  }
}
async function $4Ib(context, direction) {
  if (!context.notebookEditor.hasModel()) {
    return;
  }
  const editor = context.notebookEditor;
  const textModel = editor.textModel;
  if (editor.isReadOnly) {
    return;
  }
  let range = void 0;
  if (context.cell) {
    const idx = editor.getCellIndex(context.cell);
    range = { start: idx, end: idx + 1 };
  } else {
    const selections = editor.getSelections();
    const modelRanges = $Rrb(editor, selections);
    range = modelRanges[0];
  }
  if (!range || range.start === range.end) {
    return;
  }
  if (direction === "up") {
    if (range.start === 0) {
      return;
    }
    const indexAbove = range.start - 1;
    const finalSelection = { start: range.start - 1, end: range.end - 1 };
    const focus = context.notebookEditor.getFocus();
    const newFocus = $JL(range, focus) ? { start: focus.start - 1, end: focus.end - 1 } : { start: range.start - 1, end: range.start };
    textModel.applyEdits([
      {
        editType: 6,
        index: indexAbove,
        length: 1,
        newIdx: range.end - 1
      }
    ], true, {
      kind: SelectionStateType.Index,
      focus: editor.getFocus(),
      selections: editor.getSelections()
    }, () => ({ kind: SelectionStateType.Index, focus: newFocus, selections: [finalSelection] }), void 0, true);
    const focusRange = editor.getSelections()[0] ?? editor.getFocus();
    editor.revealCellRangeInView(focusRange);
  } else {
    if (range.end >= textModel.length) {
      return;
    }
    const indexBelow = range.end;
    const finalSelection = { start: range.start + 1, end: range.end + 1 };
    const focus = editor.getFocus();
    const newFocus = $JL(range, focus) ? { start: focus.start + 1, end: focus.end + 1 } : { start: range.start + 1, end: range.start + 2 };
    textModel.applyEdits([
      {
        editType: 6,
        index: indexBelow,
        length: 1,
        newIdx: range.start
      }
    ], true, {
      kind: SelectionStateType.Index,
      focus: editor.getFocus(),
      selections: editor.getSelections()
    }, () => ({ kind: SelectionStateType.Index, focus: newFocus, selections: [finalSelection] }), void 0, true);
    const focusRange = editor.getSelections()[0] ?? editor.getFocus();
    editor.revealCellRangeInView(focusRange);
  }
}
async function $5Ib(context, direction) {
  const editor = context.notebookEditor;
  if (!editor.hasModel()) {
    return;
  }
  const textModel = editor.textModel;
  if (editor.isReadOnly) {
    return;
  }
  let range = void 0;
  if (context.ui) {
    const targetCell = context.cell;
    const targetCellIndex = editor.getCellIndex(targetCell);
    range = { start: targetCellIndex, end: targetCellIndex + 1 };
  } else {
    const selections = editor.getSelections();
    const modelRanges = $Rrb(editor, selections);
    range = modelRanges[0];
  }
  if (!range || range.start === range.end) {
    return;
  }
  if (direction === "up") {
    const focus = editor.getFocus();
    const selections = editor.getSelections();
    textModel.applyEdits([
      {
        editType: 1,
        index: range.end,
        count: 0,
        cells: $GL([range]).map((index) => $tL(editor.cellAt(index).model))
      }
    ], true, {
      kind: SelectionStateType.Index,
      focus,
      selections
    }, () => ({ kind: SelectionStateType.Index, focus, selections }), void 0, true);
  } else {
    const focus = editor.getFocus();
    const selections = editor.getSelections();
    const newCells = $GL([range]).map((index) => $tL(editor.cellAt(index).model));
    const countDelta = newCells.length;
    const newFocus = context.ui ? focus : { start: focus.start + countDelta, end: focus.end + countDelta };
    const newSelections = context.ui ? selections : [{ start: range.start + countDelta, end: range.end + countDelta }];
    textModel.applyEdits([
      {
        editType: 1,
        index: range.end,
        count: 0,
        cells: $GL([range]).map((index) => $tL(editor.cellAt(index).model))
      }
    ], true, {
      kind: SelectionStateType.Index,
      focus,
      selections
    }, () => ({ kind: SelectionStateType.Index, focus: newFocus, selections: newSelections }), void 0, true);
    const focusRange = editor.getSelections()[0] ?? editor.getFocus();
    editor.revealCellRangeInView(focusRange);
  }
}
async function $6Ib(bulkEditService, notificationService, context) {
  const editor = context.notebookEditor;
  if (editor.isReadOnly) {
    return;
  }
  const edits = [];
  const cells = [];
  for (const selection of editor.getSelections()) {
    cells.push(...editor.getCellsInRange(selection));
  }
  if (cells.length <= 1) {
    return;
  }
  const cellKind = cells[0].cellKind;
  const isSameKind = cells.every((cell) => cell.cellKind === cellKind);
  if (!isSameKind) {
    const message = localize(8206, null);
    return notificationService.warn(message);
  }
  const firstCell = cells[0];
  const insertContent = cells.map((cell) => cell.getText()).join(firstCell.textBuffer.getEOL());
  const firstSelection = editor.getSelections()[0];
  edits.push(new $Trb(editor.textModel.uri, {
    editType: 1,
    index: firstSelection.start,
    count: firstSelection.end - firstSelection.start,
    cells: [{
      cellKind: firstCell.cellKind,
      source: insertContent,
      language: firstCell.language,
      mime: firstCell.mime,
      outputs: firstCell.model.outputs,
      metadata: firstCell.metadata
    }]
  }));
  for (const selection of editor.getSelections().slice(1)) {
    edits.push(new $Trb(editor.textModel.uri, {
      editType: 1,
      index: selection.start,
      count: selection.end - selection.start,
      cells: []
    }));
  }
  if (edits.length) {
    await bulkEditService.apply(edits, { quotableLabel: localize(8207, null) });
  }
}
async function $7Ib(editor, range, direction, constraint) {
  if (editor.isReadOnly) {
    return null;
  }
  const textModel = editor.textModel;
  const cells = editor.getCellsInRange(range);
  if (!cells.length) {
    return null;
  }
  if (range.start === 0 && direction === "above") {
    return null;
  }
  if (range.end === textModel.length && direction === "below") {
    return null;
  }
  for (let i2 = 0; i2 < cells.length; i2++) {
    const cell = cells[i2];
    if (constraint && cell.cellKind !== constraint) {
      return null;
    }
  }
  if (direction === "above") {
    const above = editor.cellAt(range.start - 1);
    if (constraint && above.cellKind !== constraint) {
      return null;
    }
    const insertContent = cells.map((cell) => (cell.textBuffer.getEOL() ?? "") + cell.getText()).join("");
    const aboveCellLineCount = above.textBuffer.getLineCount();
    const aboveCellLastLineEndColumn = above.textBuffer.getLineLength(aboveCellLineCount);
    return {
      edits: [
        new $J_(above.uri, { range: new $9C(aboveCellLineCount, aboveCellLastLineEndColumn + 1, aboveCellLineCount, aboveCellLastLineEndColumn + 1), text: insertContent }),
        new $Trb(textModel.uri, {
          editType: 1,
          index: range.start,
          count: range.end - range.start,
          cells: []
        })
      ],
      cell: above,
      endFocus: { start: range.start - 1, end: range.start },
      endSelections: [{ start: range.start - 1, end: range.start }]
    };
  } else {
    const below = editor.cellAt(range.end);
    if (constraint && below.cellKind !== constraint) {
      return null;
    }
    const cell = cells[0];
    const restCells = [...cells.slice(1), below];
    const insertContent = restCells.map((cl) => (cl.textBuffer.getEOL() ?? "") + cl.getText()).join("");
    const cellLineCount = cell.textBuffer.getLineCount();
    const cellLastLineEndColumn = cell.textBuffer.getLineLength(cellLineCount);
    return {
      edits: [
        new $J_(cell.uri, { range: new $9C(cellLineCount, cellLastLineEndColumn + 1, cellLineCount, cellLastLineEndColumn + 1), text: insertContent }),
        new $Trb(textModel.uri, {
          editType: 1,
          index: range.start + 1,
          count: range.end - range.start,
          cells: []
        })
      ],
      cell,
      endFocus: { start: range.start, end: range.start + 1 },
      endSelections: [{ start: range.start, end: range.start + 1 }]
    };
  }
}
async function $8Ib(bulkEditService, context, direction) {
  const editor = context.notebookEditor;
  const textModel = editor.textModel;
  const viewModel = editor.getViewModel();
  let ret = null;
  if (context.ui) {
    const focusMode = context.cell.focusMode;
    const cellIndex = editor.getCellIndex(context.cell);
    ret = await $7Ib(editor, { start: cellIndex, end: cellIndex + 1 }, direction);
    if (!ret) {
      return;
    }
    await bulkEditService.apply(ret?.edits, { quotableLabel: "Join Notebook Cells" });
    viewModel.updateSelectionsState({ kind: SelectionStateType.Index, focus: ret.endFocus, selections: ret.endSelections });
    ret.cell.updateEditState(CellEditState.Editing, "joinCellsWithSurrounds");
    editor.revealCellRangeInView(editor.getFocus());
    if (focusMode === CellFocusMode.Editor) {
      ret.cell.focusMode = CellFocusMode.Editor;
    }
  } else {
    const selections = editor.getSelections();
    if (!selections.length) {
      return;
    }
    const focus = editor.getFocus();
    const focusMode = editor.cellAt(focus.start)?.focusMode;
    const edits = [];
    let cell = null;
    const cells = [];
    for (let i2 = selections.length - 1; i2 >= 0; i2--) {
      const selection = selections[i2];
      const containFocus = $JL(selection, focus);
      if (selection.end >= textModel.length && direction === "below" || selection.start === 0 && direction === "above") {
        if (containFocus) {
          cell = editor.cellAt(focus.start);
        }
        cells.push(...editor.getCellsInRange(selection));
        continue;
      }
      const singleRet = await $7Ib(editor, selection, direction);
      if (!singleRet) {
        return;
      }
      edits.push(...singleRet.edits);
      cells.push(singleRet.cell);
      if (containFocus) {
        cell = singleRet.cell;
      }
    }
    if (!edits.length) {
      return;
    }
    if (!cell || !cells.length) {
      return;
    }
    await bulkEditService.apply(edits, { quotableLabel: "Join Notebook Cells" });
    cells.forEach((cell2) => {
      cell2.updateEditState(CellEditState.Editing, "joinCellsWithSurrounds");
    });
    viewModel.updateSelectionsState({ kind: SelectionStateType.Handle, primary: cell.handle, selections: cells.map((cell2) => cell2.handle) });
    editor.revealCellRangeInView(editor.getFocus());
    const newFocusedCell = editor.cellAt(editor.getFocus().start);
    if (focusMode === CellFocusMode.Editor && newFocusedCell) {
      newFocusedCell.focusMode = CellFocusMode.Editor;
    }
  }
}
function _splitPointsToBoundaries(splitPoints, textBuffer) {
  const boundaries = [];
  const lineCnt = textBuffer.getLineCount();
  const getLineLen = (lineNumber) => {
    return textBuffer.getLineLength(lineNumber);
  };
  splitPoints = splitPoints.sort((l, r2) => {
    const lineDiff = l.lineNumber - r2.lineNumber;
    const columnDiff = l.column - r2.column;
    return lineDiff !== 0 ? lineDiff : columnDiff;
  });
  for (let sp of splitPoints) {
    if (getLineLen(sp.lineNumber) + 1 === sp.column && sp.column !== 1 && sp.lineNumber < lineCnt) {
      sp = new $8C(sp.lineNumber + 1, 1);
    }
    _pushIfAbsent(boundaries, sp);
  }
  if (boundaries.length === 0) {
    return null;
  }
  const modelStart = new $8C(1, 1);
  const modelEnd = new $8C(lineCnt, getLineLen(lineCnt) + 1);
  return [modelStart, ...boundaries, modelEnd];
}
function _pushIfAbsent(positions, p) {
  const last = positions.length > 0 ? positions[positions.length - 1] : void 0;
  if (!last || last.lineNumber !== p.lineNumber || last.column !== p.column) {
    positions.push(p);
  }
}
function $9Ib(cell, splitPoints) {
  const rangeBoundaries = _splitPointsToBoundaries(splitPoints, cell.textBuffer);
  if (!rangeBoundaries) {
    return null;
  }
  const newLineModels = [];
  for (let i2 = 1; i2 < rangeBoundaries.length; i2++) {
    const start = rangeBoundaries[i2 - 1];
    const end = rangeBoundaries[i2];
    newLineModels.push(cell.textBuffer.getValueInRange(
      new $9C(start.lineNumber, start.column, end.lineNumber, end.column),
      0
      /* EndOfLinePreference.TextDefined */
    ));
  }
  return newLineModels;
}
function $0Ib(languageService, editor, index, type, direction = "above", initialText = "", ui = false) {
  const viewModel = editor.getViewModel();
  const activeKernel = editor.activeKernel;
  if (viewModel.options.isReadOnly) {
    return null;
  }
  const cell = editor.cellAt(index);
  const nextIndex = ui ? viewModel.getNextVisibleCellIndex(index) : index + 1;
  let language;
  if (type === CellKind.Code) {
    const supportedLanguages = activeKernel?.supportedLanguages ?? languageService.getRegisteredLanguageIds();
    const defaultLanguage = supportedLanguages[0] || $KF;
    if (cell?.cellKind === CellKind.Code) {
      language = cell.language;
    } else if (cell?.cellKind === CellKind.Markup) {
      const nearestCodeCellIndex = viewModel.nearestCodeCellIndex(index);
      if (nearestCodeCellIndex > -1) {
        language = viewModel.cellAt(nearestCodeCellIndex).language;
      } else {
        language = defaultLanguage;
      }
    } else {
      if (cell === void 0 && direction === "above") {
        language = viewModel.viewCells.find((cell2) => cell2.cellKind === CellKind.Code)?.language || defaultLanguage;
      } else {
        language = defaultLanguage;
      }
    }
    if (!supportedLanguages.includes(language)) {
      language = defaultLanguage;
    }
  } else {
    language = "markdown";
  }
  const insertIndex = cell ? direction === "above" ? index : nextIndex : index;
  return $$Ib(viewModel, insertIndex, initialText, language, type, void 0, [], true, true);
}
function $$Ib(viewModel, index, source, language, type, metadata, outputs, synchronous, pushUndoStop) {
  const endSelections = { kind: SelectionStateType.Index, focus: { start: index, end: index + 1 }, selections: [{ start: index, end: index + 1 }] };
  viewModel.notebookDocument.applyEdits([
    {
      editType: 1,
      index,
      count: 0,
      cells: [
        {
          cellKind: type,
          language,
          mime: void 0,
          outputs,
          metadata,
          source
        }
      ]
    }
  ], synchronous, { kind: SelectionStateType.Index, focus: viewModel.getFocus(), selections: viewModel.getSelections() }, () => endSelections, void 0, pushUndoStop && !viewModel.options.isReadOnly);
  return viewModel.cellAt(index);
}

// out-build/vs/workbench/contrib/notebook/browser/controller/chat/notebookChatContext.js
var $_Ib = new $nn("notebookCellChatFocused", false, localize(8239, null));
var $aJb = new $nn("notebookChatHasActiveRequest", false, localize(8240, null));
var $bJb = new $nn("notebookChatUserDidEdit", false, localize(8241, null));
var $cJb = new $nn("notebookChatOuterFocusPosition", "", localize(8242, null));
var $dJb = $bJ.for("cellChatInput");
var $eJb = $bJ.for("cellChatWidget");
var $fJb = $bJ.for("cellChatWidget.status");
var $gJb = $bJ.for("cellChatWidget.feedback");
var $hJb = $bJ.for("cellChatWidget.toolbar");
var $iJb = new $nn("notebookChatAgentRegistered", false, localize(8243, null));

// out-build/vs/workbench/contrib/notebook/browser/controller/chat/notebookChatController.js
var $jJb_1;
var NotebookChatWidget = class extends $3c {
  set afterModelPosition(afterModelPosition) {
    this.notebookViewZone.afterModelPosition = afterModelPosition;
  }
  get afterModelPosition() {
    return this.notebookViewZone.afterModelPosition;
  }
  set heightInPx(heightInPx) {
    this.notebookViewZone.heightInPx = heightInPx;
  }
  get heightInPx() {
    return this.notebookViewZone.heightInPx;
  }
  get editingCell() {
    return this.a;
  }
  constructor(b, id2, notebookViewZone, domNode, widgetContainer, inlineChatWidget, parentEditor, c) {
    super();
    this.b = b;
    this.id = id2;
    this.notebookViewZone = notebookViewZone;
    this.domNode = domNode;
    this.widgetContainer = widgetContainer;
    this.inlineChatWidget = inlineChatWidget;
    this.parentEditor = parentEditor;
    this.c = c;
    this.a = null;
    const updateHeight = () => {
      if (this.heightInPx === inlineChatWidget.contentHeight) {
        return;
      }
      this.heightInPx = inlineChatWidget.contentHeight;
      this.b.changeViewZones((accessor) => {
        accessor.layoutZone(id2);
      });
      this.f(inlineChatWidget, widgetContainer);
    };
    this.B(inlineChatWidget.onDidChangeHeight(() => {
      updateHeight();
    }));
    this.B(inlineChatWidget.chatWidget.onDidChangeHeight(() => {
      updateHeight();
    }));
    this.heightInPx = inlineChatWidget.contentHeight;
    this.f(inlineChatWidget, widgetContainer);
  }
  layout() {
    this.f(this.inlineChatWidget, this.widgetContainer);
  }
  restoreEditingCell(initEditingCell) {
    this.a = initEditingCell;
    const decorationIds = this.b.deltaCellDecorations([], [{
      handle: this.a.handle,
      options: { className: "nb-chatGenerationHighlight", outputClassName: "nb-chatGenerationHighlight" }
    }]);
    this.B($1c(() => {
      this.b.deltaCellDecorations(decorationIds, []);
    }));
  }
  hasFocus() {
    return this.inlineChatWidget.hasFocus();
  }
  focus() {
    this.updateNotebookEditorFocusNSelections();
    this.inlineChatWidget.focus();
  }
  updateNotebookEditorFocusNSelections() {
    this.b.focusContainer(true);
    this.b.setFocus({ start: this.afterModelPosition, end: this.afterModelPosition });
    this.b.setSelections([{
      start: this.afterModelPosition,
      end: this.afterModelPosition
    }]);
  }
  getEditingCell() {
    return this.a;
  }
  async getOrCreateEditingCell() {
    if (this.a) {
      const codeEditor2 = this.b.codeEditors.find((ce) => ce[0] === this.a)?.[1];
      if (codeEditor2?.hasModel()) {
        return {
          cell: this.a,
          editor: codeEditor2
        };
      } else {
        return void 0;
      }
    }
    if (!this.b.hasModel()) {
      return void 0;
    }
    const widgetHasFocus = this.inlineChatWidget.hasFocus();
    this.a = $0Ib(this.c, this.b, this.afterModelPosition, CellKind.Code, "above");
    if (!this.a) {
      return void 0;
    }
    await this.b.revealFirstLineIfOutsideViewport(this.a);
    const decorationIds = this.b.deltaCellDecorations([], [{
      handle: this.a.handle,
      options: { className: "nb-chatGenerationHighlight", outputClassName: "nb-chatGenerationHighlight" }
    }]);
    this.B($1c(() => {
      this.b.deltaCellDecorations(decorationIds, []);
    }));
    if (widgetHasFocus) {
      this.focus();
    }
    const codeEditor = this.b.codeEditors.find((ce) => ce[0] === this.a)?.[1];
    if (codeEditor?.hasModel()) {
      return {
        cell: this.a,
        editor: codeEditor
      };
    }
    return void 0;
  }
  async discardChange() {
    if (this.b.hasModel() && this.a) {
      $3Ib(this.b, this.a);
    }
  }
  f(inlineChatWidget, widgetContainer) {
    const layoutConfiguration = this.b.notebookOptions.getLayoutConfiguration();
    const rightMargin = layoutConfiguration.cellRightMargin;
    const leftMargin = this.b.notebookOptions.getCellEditorContainerLeftMargin();
    const maxWidth = 640;
    const width2 = Math.min(maxWidth, this.b.getLayoutInfo().width - leftMargin - rightMargin);
    inlineChatWidget.layout(new $rj(width2, this.heightInPx));
    inlineChatWidget.domNode.style.width = `${width2}px`;
    widgetContainer.style.left = `${leftMargin}px`;
  }
  dispose() {
    this.b.changeViewZones((accessor) => {
      accessor.removeZone(this.id);
    });
    this.domNode.remove();
    super.dispose();
  }
};
var NotebookCellTextModelLikeId = class {
  static str(k) {
    return `${k.viewType}/${k.uri.toString()}`;
  }
  static obj(s) {
    const idx = s.indexOf("/");
    return {
      viewType: s.substring(0, idx),
      uri: URI.parse(s.substring(idx + 1))
    };
  }
};
var $jJb = class $jJb2 extends $3c {
  static {
    $jJb_1 = this;
  }
  static {
    this.id = "workbench.notebook.chatController";
  }
  static {
    this.counter = 0;
  }
  static get(editor) {
    return editor.getContribution($jJb_1.id);
  }
  static {
    this.a = "inline-chat-history";
  }
  static {
    this.b = [];
  }
  constructor(H, I, J, L, M, N, O, P, Q) {
    super();
    this.H = H;
    this.I = I;
    this.J = J;
    this.L = L;
    this.M = M;
    this.N = N;
    this.O = O;
    this.P = P;
    this.Q = Q;
    this.c = -1;
    this.f = "";
    this.h = new $Hc(1e3, 0.7);
    this.j = this.B(new $ze());
    this.onDidChangePromptCache = this.j.event;
    this.z = this.B(new $2c());
    this.C = this.B(new $2c());
    this.G = this.B(new $4c());
    this.t = $aJb.bindTo(this.J);
    this.u = $_Ib.bindTo(this.J);
    this.w = $bJb.bindTo(this.J);
    this.y = $cJb.bindTo(this.J);
    this.R();
    $jJb_1.b = JSON.parse(this.P.get($jJb_1.a, 0, "[]"));
    this.g = (prompt) => {
      const idx = $jJb_1.b.indexOf(prompt);
      if (idx >= 0) {
        $jJb_1.b.splice(idx, 1);
      }
      $jJb_1.b.unshift(prompt);
      this.c = -1;
      this.f = "";
      this.P.store(
        $jJb_1.a,
        JSON.stringify($jJb_1.b),
        0,
        0
        /* StorageTarget.USER */
      );
    };
  }
  R() {
    this.B(this.H.onDidChangeFocus(() => {
      if (!this.F) {
        this.y.set("");
        return;
      }
      const widgetIndex = this.F.afterModelPosition;
      const focus = this.H.getFocus().start;
      if (focus + 1 === widgetIndex) {
        this.y.set("above");
      } else if (focus === widgetIndex) {
        this.y.set("below");
      } else {
        this.y.set("");
      }
    }));
  }
  run(index, input, autoSend) {
    if (this.F) {
      if (this.F.afterModelPosition !== index) {
        const window3 = getWindow(this.F.domNode);
        this.S();
        $jj(window3, () => {
          this.U(index, input, autoSend, void 0);
        });
      }
      return;
    }
    this.U(index, input, autoSend, void 0);
  }
  restore(editingCell, input) {
    if (!this.H.hasModel()) {
      return;
    }
    const index = this.H.textModel.cells.indexOf(editingCell.model);
    if (index < 0) {
      return;
    }
    if (this.F) {
      if (this.F.afterModelPosition !== index) {
        this.S();
        const window3 = getWindow(this.F.domNode);
        $jj(window3, () => {
          this.U(index, input, false, editingCell);
        });
      }
      return;
    }
    this.U(index, input, false, editingCell);
  }
  S() {
    this.F?.dispose();
    this.F = void 0;
    this.C.clear();
    this.c = -1;
    this.f = "";
  }
  U(index, input, autoSend, initEditingCell) {
    if (!this.H.hasModel()) {
      return;
    }
    this.C.clear();
    const viewZoneContainer = document.createElement("div");
    viewZoneContainer.classList.add("monaco-editor");
    const widgetContainer = document.createElement("div");
    widgetContainer.style.position = "absolute";
    viewZoneContainer.appendChild(widgetContainer);
    this.D = this.C.add($_j(viewZoneContainer));
    this.C.add(this.D.onDidFocus(() => {
      this.Z();
    }));
    const fakeParentEditorElement = document.createElement("div");
    const fakeParentEditor = this.C.add(this.I.createInstance($D9, fakeParentEditorElement, {}, { isSimpleWidget: true }));
    const inputBoxFragment = `notebook-chat-input-${$jJb_1.counter++}`;
    const notebookUri = this.H.textModel.uri;
    const inputUri = notebookUri.with({ scheme: Schemas.untitled, fragment: inputBoxFragment });
    const result = this.M.createModel("", null, inputUri, false);
    fakeParentEditor.setModel(result);
    const inlineChatWidget = this.C.add(this.I.createInstance($wGb, {
      location: ChatAgentLocation.Notebook,
      resolveData: () => {
        const sessionInputUri = this.getSessionInputUri();
        if (!sessionInputUri) {
          return void 0;
        }
        return {
          type: ChatAgentLocation.Notebook,
          sessionInputUri
        };
      }
    }, {
      statusMenuId: $fJb,
      chatWidgetViewOptions: {
        rendererOptions: {
          renderTextEditsAsSummary: (uri) => {
            return $oh(uri, this.F?.parentEditor.getModel()?.uri) || $oh(uri, this.H.textModel?.uri);
          }
        },
        menus: {
          telemetrySource: "notebook-generate-cell"
        }
      }
    }));
    inlineChatWidget.placeholder = localize(8244, null);
    inlineChatWidget.updateInfo(localize(8245, null));
    widgetContainer.appendChild(inlineChatWidget.domNode);
    this.H.changeViewZones((accessor) => {
      const notebookViewZone = {
        afterModelPosition: index,
        heightInPx: 80,
        domNode: viewZoneContainer
      };
      const id2 = accessor.addZone(notebookViewZone);
      this.X(index);
      this.F = new NotebookChatWidget(this.H, id2, notebookViewZone, viewZoneContainer, widgetContainer, inlineChatWidget, fakeParentEditor, this.N);
      if (initEditingCell) {
        this.F.restoreEditingCell(initEditingCell);
        this.ab();
      }
      this.u.set(true);
      $Xh(() => {
        this.Y();
      }, 0, this.q);
      this.n = $Hh(async (token) => {
        await this.W(token);
        $Jg(this.G.value);
        const model = this.G.value;
        this.F?.inlineChatWidget.setChatModel(model);
        if (fakeParentEditor.hasModel()) {
          if (this.F) {
            this.Y();
          }
          if (this.F && input) {
            this.F.inlineChatWidget.value = input;
            if (autoSend) {
              this.acceptInput();
            }
          }
        }
      });
    });
  }
  async W(token) {
    if (!this.G.value) {
      this.G.value = this.Q.startSession(ChatAgentLocation.Editor, token);
      if (!this.G.value) {
        throw new Error("Failed to start chat session");
      }
    }
    this.m = new $kJb();
  }
  X(index) {
    if (index === 0 || this.H.getLength() === 0) {
      this.H.revealOffsetInCenterIfOutsideViewport(0);
    } else {
      const previousCell = this.H.cellAt(Math.min(index - 1, this.H.getLength() - 1));
      if (previousCell) {
        const cellTop = this.H.getAbsoluteTopOfElement(previousCell);
        const cellHeight = this.H.getHeightOfElement(previousCell);
        this.H.revealOffsetInCenterIfOutsideViewport(
          cellTop + cellHeight + 48
          /** center of the dialog */
        );
      }
    }
  }
  Y() {
    if (!this.F) {
      return;
    }
    this.Z();
    this.F.focus();
  }
  Z() {
    if (!this.F) {
      return;
    }
    this.F.updateNotebookEditorFocusNSelections();
  }
  hasSession(chatModel) {
    return this.G.value === chatModel;
  }
  getSessionInputUri() {
    return this.F?.parentEditor.getModel()?.uri;
  }
  async acceptInput() {
    $Jg(this.F);
    await this.n;
    $Jg(this.G.value);
    $Jg(this.m);
    const lastInput = this.F.inlineChatWidget.value;
    this.g(lastInput);
    const editor = this.F.parentEditor;
    const textModel = editor.getModel();
    if (!editor.hasModel() || !textModel) {
      return;
    }
    if (this.F.editingCell && this.F.editingCell.textBuffer.getLength() > 0) {
      const ref = await this.F.editingCell.resolveTextModel();
      ref.setValue("");
    }
    const editingCellIndex = this.F.editingCell ? this.H.getCellIndex(this.F.editingCell) : void 0;
    if (editingCellIndex !== void 0) {
      this.H.setSelections([{
        start: editingCellIndex,
        end: editingCellIndex + 1
      }]);
    } else {
      this.H.setSelections([{
        start: this.F.afterModelPosition,
        end: this.F.afterModelPosition
      }]);
    }
    this.t.set(true);
    this.r?.cancel();
    this.r = new $ad();
    const store = new $2c();
    try {
      this.t.set(true);
      const progressiveEditsQueue = new $3h();
      const progressiveEditsClock = $te.create();
      const progressiveEditsAvgDuration = new $7i();
      const progressiveEditsCts = new $ad(this.r.token);
      const responsePromise = new $gi();
      const response = await this.F.inlineChatWidget.chatWidget.acceptInput();
      if (response) {
        let lastLength = 0;
        store.add(response.onDidChange((e) => {
          if (response.isCanceled) {
            progressiveEditsCts.cancel();
            responsePromise.complete();
            return;
          }
          if (response.isComplete) {
            responsePromise.complete();
            return;
          }
          const edits = response.response.value.map((part) => {
            if (part.kind === "textEditGroup") {
              return part.edits;
            } else {
              return [];
            }
          }).flat();
          const newEdits = edits.slice(lastLength);
          if (newEdits.length === 0) {
            return;
          }
          lastLength = edits.length;
          progressiveEditsAvgDuration.update(progressiveEditsClock.elapsed());
          progressiveEditsClock.reset();
          progressiveEditsQueue.queue(async () => {
            for (const edits2 of newEdits) {
              await this.$(edits2, {
                duration: progressiveEditsAvgDuration.value,
                token: progressiveEditsCts.token
              });
            }
          });
        }));
      }
      await responsePromise.p;
      await progressiveEditsQueue.whenIdle();
      this.z.clear();
      const editingCell = this.F.getEditingCell();
      if (editingCell) {
        this.z.add(editingCell.model.onDidChangeContent(() => this.ab()));
        this.z.add(editingCell.model.onDidChangeLanguage(() => this.ab()));
        this.z.add(editingCell.model.onDidChangeMetadata(() => this.ab()));
        this.z.add(editingCell.model.onDidChangeInternalMetadata(() => this.ab()));
        this.z.add(editingCell.model.onDidChangeOutputs(() => this.ab()));
        this.z.add(this.O.onDidChangeExecution((e) => {
          if (e.type === NotebookExecutionType.cell && e.affectsCell(editingCell.uri)) {
            this.ab();
          }
        }));
      }
    } catch (e) {
    } finally {
      store.dispose();
      this.t.set(false);
      this.F.inlineChatWidget.updateInfo("");
      this.F.inlineChatWidget.updateToolbar(true);
    }
  }
  async $(edits, opts) {
    $Jg(this.m);
    $Jg(this.F);
    const editingCell = await this.F.getOrCreateEditingCell();
    if (!editingCell) {
      return;
    }
    const editor = editingCell.editor;
    const moreMinimalEdits = await this.L.computeMoreMinimalEdits(editor.getModel().uri, edits);
    if (moreMinimalEdits?.length === 0) {
      return;
    }
    const actualEdits = !opts && moreMinimalEdits ? moreMinimalEdits : edits;
    const editOperations = actualEdits.map($VE.asEditOperation);
    try {
      if (opts) {
        await this.m.makeProgressiveChanges(editor, editOperations, opts);
      } else {
        await this.m.makeChanges(editor, editOperations);
      }
    } finally {
    }
  }
  ab() {
    this.w.set(true);
  }
  async acceptSession() {
    $Jg(this.G);
    $Jg(this.m);
    const editor = this.F?.parentEditor;
    if (!editor?.hasModel()) {
      return;
    }
    const editingCell = this.F?.getEditingCell();
    if (editingCell && this.H.hasModel()) {
      const cellId = NotebookCellTextModelLikeId.str({ uri: editingCell.uri, viewType: this.H.textModel.viewType });
      if (this.F?.inlineChatWidget.value) {
        this.h.set(cellId, this.F.inlineChatWidget.value);
      }
      this.j.fire({ cell: editingCell.uri });
    }
    try {
      this.G.clear();
    } catch (_err) {
    }
    this.dismiss(false);
  }
  async focusAbove() {
    if (!this.F) {
      return;
    }
    const index = this.F.afterModelPosition;
    const prev = index - 1;
    if (prev < 0) {
      return;
    }
    const cell = this.H.cellAt(prev);
    if (!cell) {
      return;
    }
    await this.H.focusNotebookCell(cell, "editor");
  }
  async focusNext() {
    if (!this.F) {
      return;
    }
    const index = this.F.afterModelPosition;
    const cell = this.H.cellAt(index);
    if (!cell) {
      return;
    }
    await this.H.focusNotebookCell(cell, "editor");
  }
  hasFocus() {
    return this.F?.hasFocus() ?? false;
  }
  focus() {
    this.Y();
  }
  focusNearestWidget(index, direction) {
    switch (direction) {
      case "above":
        if (this.F?.afterModelPosition === index) {
          this.Y();
        }
        break;
      case "below":
        if (this.F?.afterModelPosition === index + 1) {
          this.Y();
        }
        break;
      default:
        break;
    }
  }
  populateHistory(up) {
    if (!this.F) {
      return;
    }
    const len = $jJb_1.b.length;
    if (len === 0) {
      return;
    }
    if (this.c === -1) {
      this.f = this.F.inlineChatWidget.value;
    }
    const newIdx = this.c + (up ? 1 : -1);
    if (newIdx >= len) {
      return;
    }
    let entry;
    if (newIdx < 0) {
      entry = this.f;
      this.c = -1;
    } else {
      entry = $jJb_1.b[newIdx];
      this.c = newIdx;
    }
    this.F.inlineChatWidget.value = entry;
    this.F.inlineChatWidget.selectAll();
  }
  async cancelCurrentRequest(discard) {
    this.r?.cancel();
  }
  getEditingCell() {
    return this.F?.getEditingCell();
  }
  discard() {
    this.r?.cancel();
    this.F?.discardChange();
    this.dismiss(true);
  }
  dismiss(discard) {
    const widget = this.F;
    const widgetIndex = widget?.afterModelPosition;
    const currentFocus = this.H.getFocus();
    const isWidgetFocused = currentFocus.start === widgetIndex && currentFocus.end === widgetIndex;
    if (widget && isWidgetFocused) {
      const editingCell = widget.getEditingCell();
      const shouldFocusEditingCell = editingCell && !discard;
      const shouldFocusTopCell = widgetIndex === 0 && this.H.getLength() > 0;
      const shouldFocusAboveCell = widgetIndex !== 0 && this.H.cellAt(widgetIndex - 1);
      if (shouldFocusEditingCell) {
        this.H.focusNotebookCell(editingCell, "container");
      } else if (shouldFocusTopCell) {
        this.H.focusNotebookCell(this.H.cellAt(0), "container");
      } else if (shouldFocusAboveCell) {
        this.H.focusNotebookCell(this.H.cellAt(widgetIndex - 1), "container");
      }
    }
    this.u.set(false);
    this.w.set(false);
    this.n?.cancel();
    this.n = void 0;
    this.G.clear();
    this.F?.dispose();
    this.F = void 0;
    this.C.clear();
  }
  // check if a cell is generated by prompt by checking prompt cache
  isCellGeneratedByChat(cell) {
    if (!this.H.hasModel()) {
      return false;
    }
    const cellId = NotebookCellTextModelLikeId.str({ uri: cell.uri, viewType: this.H.textModel.viewType });
    return this.h.has(cellId);
  }
  // get prompt from cache
  getPromptFromCache(cell) {
    if (!this.H.hasModel()) {
      return void 0;
    }
    const cellId = NotebookCellTextModelLikeId.str({ uri: cell.uri, viewType: this.H.textModel.viewType });
    return this.h.get(cellId);
  }
  dispose() {
    this.dismiss(false);
    super.dispose();
  }
};
$jJb = $jJb_1 = __decorate([
  __param(1, $Pk),
  __param(2, $on),
  __param(3, $I0),
  __param(4, $sG),
  __param(5, $1E),
  __param(6, $wL),
  __param(7, $jv),
  __param(8, $qO)
], $jJb);
var $kJb = class {
  constructor() {
    this.a = 0;
  }
  async makeProgressiveChanges(editor, edits, opts) {
    if (++this.a === 1) {
      editor.pushUndoStop();
    }
    const durationInSec = opts.duration / 1e3;
    for (const edit3 of edits) {
      const wordCount = $0rb(edit3.text ?? "");
      const speed = wordCount / durationInSec;
      await $zGb(editor.getModel(), $AGb(new $lj(), edit3, speed, opts.token));
    }
  }
  async makeChanges(editor, edits) {
    const cursorStateComputerAndInlineDiffCollection = (undoEdits) => {
      let last = null;
      for (const edit3 of undoEdits) {
        last = !last || last.isBefore(edit3.range.getEndPosition()) ? edit3.range.getEndPosition() : last;
      }
      return last && [$_D.fromPositions(last)];
    };
    if (++this.a === 1) {
      editor.pushUndoStop();
    }
    editor.executeEdits("inline-chat-live", edits, cursorStateComputerAndInlineDiffCollection);
  }
};
$iGb($jJb.id, $jJb);

// out-build/vs/workbench/contrib/notebook/browser/view/cellPart.js
var $lJb = class extends $3c {
  constructor() {
    super();
    this.f = this.B(new $2c());
  }
  /**
   * Prepare model for cell part rendering
   * No DOM operations recommended within this operation
   */
  prepareRenderCell(element) {
  }
  /**
   * Update the DOM for the cell `element`
   */
  renderCell(element) {
    this.c = element;
    safeInvokeNoArg2(() => this.didRenderCell(element));
  }
  didRenderCell(element) {
  }
  /**
   * Dispose any disposables generated from `didRenderCell`
   */
  unrenderCell(element) {
    this.c = void 0;
    this.f.clear();
  }
  /**
   * Perform DOM read operations to prepare for the list/cell layout update.
   */
  prepareLayout() {
  }
  /**
   * Update internal DOM (top positions) per cell layout info change
   * Note that a cell part doesn't need to call `DOM.scheduleNextFrame`,
   * the list view will ensure that layout call is invoked in the right frame
   */
  updateInternalLayoutNow(element) {
  }
  /**
   * Update per cell state change
   */
  updateState(element, e) {
  }
  /**
   * Update per execution state change.
   */
  updateForExecutionState(element, e) {
  }
};
var $mJb = class extends $3c {
  constructor() {
    super();
    this.b = this.B(new $2c());
  }
  /**
   * Prepare model for cell part rendering
   * No DOM operations recommended within this operation
   */
  prepareRenderCell(element) {
  }
  /**
   * Update the DOM for the cell `element`
   */
  renderCell(element) {
    this.a = element;
    this.didRenderCell(element);
  }
  didRenderCell(element) {
  }
  /**
   * Dispose any disposables generated from `didRenderCell`
   */
  unrenderCell(element) {
    this.a = void 0;
    this.b.clear();
  }
  /**
   * Update internal DOM (top positions) per cell layout info change
   * Note that a cell part doesn't need to call `DOM.scheduleNextFrame`,
   * the list view will ensure that layout call is invoked in the right frame
   */
  updateInternalLayoutNow(element) {
  }
  /**
   * Update per cell state change
   */
  updateState(element, e) {
  }
  /**
   * Update per execution state change.
   */
  updateForExecutionState(element, e) {
  }
};
function safeInvokeNoArg2(func) {
  try {
    return func();
  } catch (e) {
    $gb(e);
    return null;
  }
}
var $nJb = class _$nJb extends $3c {
  constructor(f, g, h3) {
    super();
    this.f = f;
    this.g = g;
    this.h = h3;
    this.a = this.B(new $4c());
    this.b = this.B(new $4c());
    this.c = this.B(new $4c());
  }
  concatContentPart(other, targetWindow) {
    return new _$nJb(targetWindow, this.g.concat(other), this.h);
  }
  concatOverlayPart(other, targetWindow) {
    return new _$nJb(targetWindow, this.g, this.h.concat(other));
  }
  scheduleRenderCell(element) {
    for (const part of this.g) {
      safeInvokeNoArg2(() => part.prepareRenderCell(element));
    }
    for (const part of this.h) {
      safeInvokeNoArg2(() => part.prepareRenderCell(element));
    }
    for (const part of this.g) {
      safeInvokeNoArg2(() => part.renderCell(element));
    }
    this.a.value = $nj(this.f, () => {
      for (const part of this.h) {
        safeInvokeNoArg2(() => part.renderCell(element));
      }
    });
  }
  unrenderCell(element) {
    for (const part of this.g) {
      safeInvokeNoArg2(() => part.unrenderCell(element));
    }
    this.a.value = void 0;
    this.b.value = void 0;
    this.c.value = void 0;
    for (const part of this.h) {
      safeInvokeNoArg2(() => part.unrenderCell(element));
    }
  }
  updateInternalLayoutNow(viewCell) {
    for (const part of this.g) {
      safeInvokeNoArg2(() => part.updateInternalLayoutNow(viewCell));
    }
    for (const part of this.h) {
      safeInvokeNoArg2(() => part.updateInternalLayoutNow(viewCell));
    }
  }
  prepareLayout() {
    for (const part of this.g) {
      safeInvokeNoArg2(() => part.prepareLayout());
    }
  }
  updateState(viewCell, e) {
    for (const part of this.g) {
      safeInvokeNoArg2(() => part.updateState(viewCell, e));
    }
    this.b.value = $nj(this.f, () => {
      for (const part of this.h) {
        safeInvokeNoArg2(() => part.updateState(viewCell, e));
      }
    });
  }
  updateForExecutionState(viewCell, e) {
    for (const part of this.g) {
      safeInvokeNoArg2(() => part.updateForExecutionState(viewCell, e));
    }
    this.c.value = $nj(this.f, () => {
      for (const part of this.h) {
        safeInvokeNoArg2(() => part.updateForExecutionState(viewCell, e));
      }
    });
  }
};

// out-build/vs/workbench/contrib/notebook/browser/viewModel/baseCellViewModel.js
var $VIb = class extends $3c {
  get handle() {
    return this.model.handle;
  }
  get uri() {
    return this.model.uri;
  }
  get lineCount() {
    return this.model.textBuffer.getLineCount();
  }
  get metadata() {
    return this.model.metadata;
  }
  get internalMetadata() {
    return this.model.internalMetadata;
  }
  get language() {
    return this.model.language;
  }
  get mime() {
    if (typeof this.model.mime === "string") {
      return this.model.mime;
    }
    switch (this.language) {
      case "markdown":
        return $YC.markdown;
      default:
        return $YC.text;
    }
  }
  get lineNumbers() {
    return this.f;
  }
  set lineNumbers(lineNumbers) {
    if (lineNumbers === this.f) {
      return;
    }
    this.f = lineNumbers;
    this.b.fire({ cellLineNumberChanged: true });
  }
  get commentOptions() {
    return this.g;
  }
  set commentOptions(newOptions) {
    this.g = newOptions;
  }
  get focusMode() {
    return this.h;
  }
  set focusMode(newMode) {
    if (this.h !== newMode) {
      this.h = newMode;
      this.b.fire({ focusModeChanged: true });
    }
  }
  get editorAttached() {
    return !!this.j;
  }
  get textModel() {
    return this.model.textModel;
  }
  hasModel() {
    return !!this.textModel;
  }
  get dragging() {
    return this.G;
  }
  set dragging(v) {
    this.G = v;
    this.b.fire({ dragStateChanged: true });
  }
  get isInputCollapsed() {
    return this.I;
  }
  set isInputCollapsed(v) {
    this.I = v;
    this.b.fire({ inputCollapsedChanged: true });
  }
  get isOutputCollapsed() {
    return this.J;
  }
  set isOutputCollapsed(v) {
    this.J = v;
    this.b.fire({ outputCollapsedChanged: true });
  }
  set commentHeight(height) {
    if (this.L === height) {
      return;
    }
    this.L = height;
    this.layoutChange({ commentHeight: true }, "BaseCellViewModel#commentHeight");
  }
  constructor(viewType, model, id2, O, P, Q, R, S) {
    super();
    this.viewType = viewType;
    this.model = model;
    this.id = id2;
    this.O = O;
    this.P = P;
    this.Q = Q;
    this.R = R;
    this.S = S;
    this.a = this.B(new $ze());
    this.onDidChangeEditorAttachState = this.a.event;
    this.b = this.B(new $ze());
    this.onDidChangeState = this.b.event;
    this.c = CellEditState.Preview;
    this.f = "inherit";
    this.h = CellFocusMode.Container;
    this.m = [];
    this.n = null;
    this.r = null;
    this.t = /* @__PURE__ */ new Map();
    this.u = this.B(new $4c());
    this.w = this.B(new $ze());
    this.onCellDecorationsChanged = this.w.event;
    this.y = /* @__PURE__ */ new Map();
    this.z = 0;
    this.C = /* @__PURE__ */ new Map();
    this.D = this.B(new $ze());
    this.onDidChangeCellStatusBarItems = this.D.event;
    this.F = 0;
    this.G = false;
    this.I = false;
    this.J = false;
    this.L = 0;
    this.M = false;
    this.N = false;
    this.$ = "";
    this.B(model.onDidChangeMetadata(() => {
      this.b.fire({ metadataChanged: true });
    }));
    this.B(model.onDidChangeInternalMetadata((e) => {
      this.b.fire({ internalMetadataChanged: true });
      if (e.lastRunSuccessChanged) {
        this.layoutChange({});
      }
    }));
    this.B(this.P.onDidChangeConfiguration((e) => {
      if (e.affectsConfiguration("notebook.lineNumbers")) {
        this.lineNumbers = "inherit";
      }
    }));
    if (this.model.collapseState?.inputCollapsed) {
      this.I = true;
    }
    if (this.model.collapseState?.outputCollapsed) {
      this.J = true;
    }
    this.g = this.P.getValue("editor.comments", { overrideIdentifier: this.language });
    this.B(this.P.onDidChangeConfiguration((e) => {
      if (e.affectsConfiguration("editor.comments")) {
        this.g = this.P.getValue("editor.comments", { overrideIdentifier: this.language });
      }
    }));
  }
  updateOptions(e) {
    if (this.j && typeof e.readonly === "boolean") {
      this.j.updateOptions({ readOnly: e.readonly });
    }
    if (typeof e.readonly === "boolean") {
      this.N = e.readonly;
    }
  }
  assertTextModelAttached() {
    if (this.textModel && this.j && this.j.getModel() === this.textModel) {
      return true;
    }
    return false;
  }
  // private handleKeyDown(e: IKeyboardEvent) {
  // 	if (this.viewType === IPYNB_VIEW_TYPE && isWindows && e.ctrlKey && e.keyCode === KeyCode.Enter) {
  // 		this._keymapService.promptKeymapRecommendation();
  // 	}
  // }
  attachTextEditor(editor, estimatedHasHorizontalScrolling) {
    if (!editor.hasModel()) {
      throw new Error("Invalid editor: model is missing");
    }
    if (this.j === editor) {
      if (this.m.length === 0) {
        this.m.push(this.j.onDidChangeCursorSelection(() => {
          this.b.fire({ selectionChanged: true });
        }));
        this.b.fire({ selectionChanged: true });
      }
      return;
    }
    this.j = editor;
    if (this.N) {
      editor.updateOptions({ readOnly: this.N });
    }
    if (this.n) {
      this.X(this.n);
    } else {
      if (estimatedHasHorizontalScrolling) {
        this.X({
          contributionsState: {},
          cursorState: [],
          viewState: {
            scrollLeft: 0,
            firstPosition: { lineNumber: 1, column: 1 },
            firstPositionDeltaTop: this.O.notebookOptions.getLayoutConfiguration().editorTopPadding
          }
        });
      }
    }
    if (this.r) {
      $TIb(editor.getModel(), this.r, this.S);
    }
    if (this.M) {
      return;
    }
    editor.changeDecorations((accessor) => {
      this.y.forEach((value, key2) => {
        if (key2.startsWith("_lazy_")) {
          const ret = accessor.addDecoration(value.options.range, value.options.options);
          this.y.get(key2).id = ret;
        } else {
          const ret = accessor.addDecoration(value.options.range, value.options.options);
          this.y.get(key2).id = ret;
        }
      });
    });
    this.m.push(editor.onDidChangeCursorSelection(() => {
      this.b.fire({ selectionChanged: true });
    }));
    const inlineChatController = $cHb.get(this.j);
    if (inlineChatController) {
      this.m.push(inlineChatController.onWillStartSession(() => {
        if (this.textBuffer.getLength() === 0) {
          this.enableAutoLanguageDetection();
        }
      }));
    }
    this.b.fire({ selectionChanged: true });
    this.a.fire();
  }
  detachTextEditor() {
    this.U();
    this.W();
    this.j?.changeDecorations((accessor) => {
      this.y.forEach((value) => {
        const resolvedid = value.id;
        if (resolvedid) {
          accessor.removeDecoration(resolvedid);
        }
      });
    });
    this.j = void 0;
    $Xc(this.m);
    this.m = [];
    this.a.fire();
    if (this.H) {
      this.H.dispose();
      this.H = void 0;
    }
    this.u.clear();
  }
  getText() {
    return this.model.getValue();
  }
  getAlternativeId() {
    return this.model.alternativeId;
  }
  getTextLength() {
    return this.model.getTextLength();
  }
  enableAutoLanguageDetection() {
    this.model.enableAutoLanguageDetection();
  }
  U() {
    if (!this.j) {
      return;
    }
    this.n = this.j.saveViewState();
  }
  W() {
    if (!this.j || !this.j.hasModel()) {
      return;
    }
    this.r = $UIb(this.j.getModel(), this.S);
  }
  saveEditorViewState() {
    if (this.j) {
      this.n = this.j.saveViewState();
    }
    return this.n;
  }
  restoreEditorViewState(editorViewStates, totalHeight) {
    this.n = editorViewStates;
  }
  X(state) {
    if (state) {
      this.j?.restoreViewState(state);
    }
  }
  addModelDecoration(decoration3) {
    if (!this.j) {
      const id3 = ++this.z;
      const decorationId = `_lazy_${this.id};${id3}`;
      this.y.set(decorationId, { options: decoration3 });
      return decorationId;
    }
    let id2;
    this.j.changeDecorations((accessor) => {
      id2 = accessor.addDecoration(decoration3.range, decoration3.options);
      this.y.set(id2, { id: id2, options: decoration3 });
    });
    return id2;
  }
  removeModelDecoration(decorationId) {
    const realDecorationId = this.y.get(decorationId);
    if (this.j && realDecorationId && realDecorationId.id !== void 0) {
      this.j.changeDecorations((accessor) => {
        accessor.removeDecoration(realDecorationId.id);
      });
    }
    this.y.delete(decorationId);
  }
  deltaModelDecorations(oldDecorations, newDecorations) {
    oldDecorations.forEach((id2) => {
      this.removeModelDecoration(id2);
    });
    const ret = newDecorations.map((option) => {
      return this.addModelDecoration(option);
    });
    return ret;
  }
  Y(decorationId) {
    const options3 = this.t.get(decorationId);
    this.t.delete(decorationId);
    if (options3) {
      for (const existingOptions of this.t.values()) {
        if (options3.className === existingOptions.className) {
          options3.className = void 0;
        }
        if (options3.outputClassName === existingOptions.outputClassName) {
          options3.outputClassName = void 0;
        }
        if (options3.gutterClassName === existingOptions.gutterClassName) {
          options3.gutterClassName = void 0;
        }
        if (options3.topClassName === existingOptions.topClassName) {
          options3.topClassName = void 0;
        }
      }
      this.w.fire({ added: [], removed: [options3] });
    }
  }
  Z(options3) {
    const id2 = ++this.z;
    const decorationId = `_cell_${this.id};${id2}`;
    this.t.set(decorationId, options3);
    this.w.fire({ added: [options3], removed: [] });
    return decorationId;
  }
  getCellDecorations() {
    return [...this.t.values()];
  }
  getCellDecorationRange(decorationId) {
    if (this.j) {
      return this.j.getModel()?.getDecorationRange(decorationId) ?? null;
    }
    return null;
  }
  deltaCellDecorations(oldDecorations, newDecorations) {
    oldDecorations.forEach((id2) => {
      this.Y(id2);
    });
    const ret = newDecorations.map((option) => {
      return this.Z(option);
    });
    return ret;
  }
  deltaCellStatusBarItems(oldItems, newItems) {
    oldItems.forEach((id2) => {
      const item = this.C.get(id2);
      if (item) {
        this.C.delete(id2);
      }
    });
    const newIds = newItems.map((item) => {
      const id2 = ++this.F;
      const itemId = `_cell_${this.id};${id2}`;
      this.C.set(itemId, item);
      return itemId;
    });
    this.D.fire();
    return newIds;
  }
  getCellStatusBarItems() {
    return Array.from(this.C.values());
  }
  revealRangeInCenter(range) {
    this.j?.revealRangeInCenter(
      range,
      1
      /* editorCommon.ScrollType.Immediate */
    );
  }
  setSelection(range) {
    this.j?.setSelection(range);
  }
  setSelections(selections) {
    if (selections.length) {
      if (this.j) {
        this.j?.setSelections(selections);
      } else if (this.n) {
        this.n.cursorState = selections.map((selection) => {
          return {
            inSelectionMode: !selection.isEmpty(),
            selectionStart: selection.getStartPosition(),
            position: selection.getEndPosition()
          };
        });
      }
    }
  }
  getSelections() {
    return this.j?.getSelections() ?? this.n?.cursorState.map((state) => new $_D(state.selectionStart.lineNumber, state.selectionStart.column, state.position.lineNumber, state.position.column)) ?? [];
  }
  getSelectionsStartPosition() {
    if (this.j) {
      const selections = this.j.getSelections();
      return selections?.map((s) => s.getStartPosition());
    } else {
      const selections = this.n?.cursorState;
      return selections?.map((s) => s.selectionStart);
    }
  }
  getLineScrollTopOffset(line) {
    if (!this.j) {
      return 0;
    }
    const editorPadding = this.O.notebookOptions.computeEditorPadding(this.internalMetadata, this.uri);
    return this.j.getTopForLineNumber(line) + editorPadding.top;
  }
  getPositionScrollTopOffset(range) {
    if (!this.j) {
      return 0;
    }
    const position = range instanceof $_D ? range.getPosition() : range.getStartPosition();
    const editorPadding = this.O.notebookOptions.computeEditorPadding(this.internalMetadata, this.uri);
    return this.j.getTopForPosition(position.lineNumber, position.column) + editorPadding.top;
  }
  cursorAtLineBoundary() {
    if (!this.j || !this.textModel || !this.j.hasTextFocus()) {
      return CursorAtLineBoundary.None;
    }
    const selection = this.j.getSelection();
    if (!selection || !selection.isEmpty()) {
      return CursorAtLineBoundary.None;
    }
    const currentLineLength = this.textModel.getLineLength(selection.startLineNumber);
    if (currentLineLength === 0) {
      return CursorAtLineBoundary.Both;
    }
    switch (selection.startColumn) {
      case 1:
        return CursorAtLineBoundary.Start;
      case currentLineLength + 1:
        return CursorAtLineBoundary.End;
      default:
        return CursorAtLineBoundary.None;
    }
  }
  cursorAtBoundary() {
    if (!this.j) {
      return CursorAtBoundary.None;
    }
    if (!this.textModel) {
      return CursorAtBoundary.None;
    }
    const selection = this.j.getSelection();
    if (!selection || !selection.isEmpty()) {
      return CursorAtBoundary.None;
    }
    const firstViewLineTop = this.j.getTopForPosition(1, 1);
    const lastViewLineTop = this.j.getTopForPosition(this.textModel.getLineCount(), this.textModel.getLineLength(this.textModel.getLineCount()));
    const selectionTop = this.j.getTopForPosition(selection.startLineNumber, selection.startColumn);
    if (selectionTop === lastViewLineTop) {
      if (selectionTop === firstViewLineTop) {
        return CursorAtBoundary.Both;
      } else {
        return CursorAtBoundary.Bottom;
      }
    } else {
      if (selectionTop === firstViewLineTop) {
        return CursorAtBoundary.Top;
      } else {
        return CursorAtBoundary.None;
      }
    }
  }
  get editStateSource() {
    return this.$;
  }
  updateEditState(newState, source) {
    this.$ = source;
    if (newState === this.c) {
      return;
    }
    this.c = newState;
    this.b.fire({ editStateChanged: true });
    if (this.c === CellEditState.Preview) {
      this.focusMode = CellFocusMode.Container;
    }
  }
  getEditState() {
    return this.c;
  }
  get textBuffer() {
    return this.model.textBuffer;
  }
  /**
   * Text model is used for editing.
   */
  async resolveTextModel() {
    if (!this.H || !this.textModel) {
      this.H = await this.Q.createModelReference(this.uri);
      if (this.M) {
        return this.textModel;
      }
      if (!this.H) {
        throw new Error(`Cannot resolve text model for ${this.uri}`);
      }
      this.u.value = this.textModel.onDidChangeContent(() => this.ab());
    }
    return this.textModel;
  }
  bb(value, options3) {
    let cellMatches = [];
    const lineCount = this.textBuffer.getLineCount();
    const findRange2 = options3.findScope?.selectedTextRanges ?? [new $9C(1, 1, lineCount, this.textBuffer.getLineLength(lineCount) + 1)];
    if (this.assertTextModelAttached()) {
      cellMatches = this.textModel.findMatches(value, findRange2, options3.regex || false, options3.caseSensitive || false, options3.wholeWord ? options3.wordSeparators || null : null, options3.regex || false);
    } else {
      const searchParams = new $fI(value, options3.regex || false, options3.caseSensitive || false, options3.wholeWord ? options3.wordSeparators || null : null);
      const searchData = searchParams.parseSearchRequest();
      if (!searchData) {
        return null;
      }
      findRange2.forEach((range) => {
        cellMatches.push(...this.textBuffer.findMatchesLineByLine(new $9C(range.startLineNumber, range.startColumn, range.endLineNumber, range.endColumn), searchData, options3.regex || false, 1e3));
      });
    }
    return cellMatches;
  }
  dispose() {
    this.M = true;
    super.dispose();
    $Xc(this.m);
    if (this.R.getUriComparisonKey(this.uri) === this.uri.toString()) {
      this.R.removeElements(this.uri);
    }
    this.H?.dispose();
  }
  toJSON() {
    return {
      handle: this.handle
    };
  }
};

// out-build/vs/workbench/contrib/notebook/browser/viewModel/codeCellViewModel.js
var $WIb = 500;
var $XIb = class $XIb2 extends $VIb {
  set editorHeight(height) {
    if (this.kb === height) {
      return;
    }
    this.kb = height;
    this.layoutChange({ editorHeight: true }, "CodeCellViewModel#editorHeight");
  }
  get editorHeight() {
    throw new Error("editorHeight is write-only");
  }
  set chatHeight(height) {
    if (this.lb === height) {
      return;
    }
    this.lb = height;
    this.layoutChange({ chatHeight: true }, "CodeCellViewModel#chatHeight");
  }
  get chatHeight() {
    return this.lb;
  }
  get outputIsHovered() {
    return this.mb;
  }
  set outputIsHovered(v) {
    this.mb = v;
    this.b.fire({ outputIsHoveredChanged: true });
  }
  get outputIsFocused() {
    return this.nb;
  }
  set outputIsFocused(v) {
    this.nb = v;
    this.b.fire({ outputIsFocusedChanged: true });
  }
  get inputInOutputIsFocused() {
    return this.ob;
  }
  set inputInOutputIsFocused(v) {
    this.ob = v;
  }
  get qb() {
    return this.pb;
  }
  /**
   * The minimum height of the output region. It's only set to non-zero temporarily when replacing an output with a new one.
   * It's reset to 0 when the new output is rendered, or in one second.
   */
  set qb(newMin) {
    this.pb = newMin;
  }
  get layoutInfo() {
    return this.rb;
  }
  get outputsViewModels() {
    return this.sb;
  }
  constructor(viewType, model, initialNotebookLayoutInfo, viewContext, configurationService, tb, modelService, undoRedoService, codeEditorService) {
    super(viewType, model, $ps(), viewContext, configurationService, modelService, undoRedoService, codeEditorService);
    this.viewContext = viewContext;
    this.tb = tb;
    this.cellKind = CellKind.Code;
    this.cb = this.B(new $ze());
    this.onLayoutInfoRead = this.cb.event;
    this.db = this.B(new $ze());
    this.onDidStartExecution = this.db.event;
    this.eb = this.B(new $ze());
    this.onDidStopExecution = this.eb.event;
    this.fb = this.B(new $ze());
    this.onDidChangeOutputs = this.fb.event;
    this.gb = this.B(new $ze());
    this.onDidRemoveOutputs = this.gb.event;
    this.hb = [];
    this.ib = null;
    this.jb = this.B(new $Ce());
    this.onDidChangeLayout = this.jb.event;
    this.kb = 0;
    this.lb = 0;
    this.mb = false;
    this.nb = false;
    this.ob = false;
    this.pb = 0;
    this.executionErrorDiagnostic = $he("excecutionError", void 0);
    this.zb = this.B(new $ze());
    this.hasFindResult = this.zb.event;
    this.sb = this.model.outputs.map((output) => new $_Db(this, output, this.tb));
    this.B(this.model.onDidChangeOutputs((splice2) => {
      const removedOutputs = [];
      let outputLayoutChange = false;
      for (let i2 = splice2.start; i2 < splice2.start + splice2.deleteCount; i2++) {
        if (this.hb[i2] !== void 0 && this.hb[i2] !== 0) {
          outputLayoutChange = true;
        }
      }
      this.hb.splice(splice2.start, splice2.deleteCount, ...splice2.newOutputs.map(() => 0));
      removedOutputs.push(...this.sb.splice(splice2.start, splice2.deleteCount, ...splice2.newOutputs.map((output) => new $_Db(this, output, this.tb))));
      this.ib = null;
      this.fb.fire(splice2);
      this.gb.fire(removedOutputs);
      if (outputLayoutChange) {
        this.layoutChange({ outputHeight: true }, "CodeCellViewModel#model.onDidChangeOutputs");
      }
      if (!this.hb.length) {
        this.executionErrorDiagnostic.set(void 0, void 0);
      }
      $Xc(removedOutputs);
    }));
    this.hb = new Array(this.model.outputs.length);
    this.rb = {
      fontInfo: initialNotebookLayoutInfo?.fontInfo || null,
      editorHeight: 0,
      editorWidth: initialNotebookLayoutInfo ? this.viewContext.notebookOptions.computeCodeCellEditorWidth(initialNotebookLayoutInfo.width) : 0,
      chatHeight: 0,
      statusBarHeight: 0,
      commentOffset: 0,
      commentHeight: 0,
      outputContainerOffset: 0,
      outputTotalHeight: 0,
      outputShowMoreContainerHeight: 0,
      outputShowMoreContainerOffset: 0,
      totalHeight: this.wb(17, 0, 0, 0),
      codeIndicatorHeight: 0,
      outputIndicatorHeight: 0,
      bottomToolbarOffset: 0,
      layoutState: CellLayoutState.Uninitialized,
      estimatedHasHorizontalScrolling: false
    };
  }
  updateExecutionState(e) {
    if (e.changed) {
      this.executionErrorDiagnostic.set(void 0, void 0);
      this.db.fire(e);
    } else {
      this.eb.fire(e);
    }
  }
  updateOptions(e) {
    super.updateOptions(e);
    if (e.cellStatusBarVisibility || e.insertToolbarPosition || e.cellToolbarLocation) {
      this.layoutChange({});
    }
  }
  pauseLayout() {
    this.jb.pause();
  }
  resumeLayout() {
    this.jb.resume();
  }
  layoutChange(state, source) {
    this.yb();
    const notebookLayoutConfiguration = this.viewContext.notebookOptions.getLayoutConfiguration();
    const bottomToolbarDimensions = this.viewContext.notebookOptions.computeBottomToolbarDimensions(this.viewType);
    const outputShowMoreContainerHeight = state.outputShowMoreContainerHeight ? state.outputShowMoreContainerHeight : this.rb.outputShowMoreContainerHeight;
    const outputTotalHeight = Math.max(this.pb, this.isOutputCollapsed ? notebookLayoutConfiguration.collapsedIndicatorHeight : this.ib.getTotalSum());
    const commentHeight = state.commentHeight ? this.L : this.rb.commentHeight;
    const originalLayout = this.layoutInfo;
    if (!this.isInputCollapsed) {
      let newState;
      let editorHeight;
      let totalHeight;
      let hasHorizontalScrolling = false;
      const chatHeight = state.chatHeight ? this.lb : this.rb.chatHeight;
      if (!state.editorHeight && this.rb.layoutState === CellLayoutState.FromCache && !state.outputHeight) {
        const estimate = this.vb(state.font?.lineHeight ?? this.rb.fontInfo?.lineHeight);
        editorHeight = estimate.editorHeight;
        hasHorizontalScrolling = estimate.hasHorizontalScrolling;
        totalHeight = this.rb.totalHeight;
        newState = CellLayoutState.FromCache;
      } else if (state.editorHeight || this.rb.layoutState === CellLayoutState.Measured) {
        editorHeight = this.kb;
        totalHeight = this.wb(this.kb, outputTotalHeight, outputShowMoreContainerHeight, chatHeight);
        newState = CellLayoutState.Measured;
        hasHorizontalScrolling = this.rb.estimatedHasHorizontalScrolling;
      } else {
        const estimate = this.vb(state.font?.lineHeight ?? this.rb.fontInfo?.lineHeight);
        editorHeight = estimate.editorHeight;
        hasHorizontalScrolling = estimate.hasHorizontalScrolling;
        totalHeight = this.wb(editorHeight, outputTotalHeight, outputShowMoreContainerHeight, chatHeight);
        newState = CellLayoutState.Estimated;
      }
      const statusBarHeight = this.viewContext.notebookOptions.computeEditorStatusbarHeight(this.internalMetadata, this.uri);
      const codeIndicatorHeight = editorHeight + statusBarHeight;
      const outputIndicatorHeight = outputTotalHeight + outputShowMoreContainerHeight;
      const outputContainerOffset = notebookLayoutConfiguration.editorToolbarHeight + notebookLayoutConfiguration.cellTopMargin + chatHeight + editorHeight + statusBarHeight;
      const outputShowMoreContainerOffset = totalHeight - bottomToolbarDimensions.bottomToolbarGap - bottomToolbarDimensions.bottomToolbarHeight / 2 - outputShowMoreContainerHeight;
      const bottomToolbarOffset = this.viewContext.notebookOptions.computeBottomToolbarOffset(totalHeight, this.viewType);
      const editorWidth = state.outerWidth !== void 0 ? this.viewContext.notebookOptions.computeCodeCellEditorWidth(state.outerWidth) : this.rb?.editorWidth;
      this.rb = {
        fontInfo: state.font ?? this.rb.fontInfo ?? null,
        chatHeight,
        editorHeight,
        editorWidth,
        statusBarHeight,
        outputContainerOffset,
        outputTotalHeight,
        outputShowMoreContainerHeight,
        outputShowMoreContainerOffset,
        commentOffset: outputContainerOffset + outputTotalHeight,
        commentHeight,
        totalHeight,
        codeIndicatorHeight,
        outputIndicatorHeight,
        bottomToolbarOffset,
        layoutState: newState,
        estimatedHasHorizontalScrolling: hasHorizontalScrolling
      };
    } else {
      const codeIndicatorHeight = notebookLayoutConfiguration.collapsedIndicatorHeight;
      const outputIndicatorHeight = outputTotalHeight + outputShowMoreContainerHeight;
      const chatHeight = state.chatHeight ? this.lb : this.rb.chatHeight;
      const outputContainerOffset = notebookLayoutConfiguration.cellTopMargin + notebookLayoutConfiguration.collapsedIndicatorHeight;
      const totalHeight = notebookLayoutConfiguration.cellTopMargin + notebookLayoutConfiguration.collapsedIndicatorHeight + notebookLayoutConfiguration.cellBottomMargin + bottomToolbarDimensions.bottomToolbarGap + chatHeight + commentHeight + outputTotalHeight + outputShowMoreContainerHeight;
      const outputShowMoreContainerOffset = totalHeight - bottomToolbarDimensions.bottomToolbarGap - bottomToolbarDimensions.bottomToolbarHeight / 2 - outputShowMoreContainerHeight;
      const bottomToolbarOffset = this.viewContext.notebookOptions.computeBottomToolbarOffset(totalHeight, this.viewType);
      const editorWidth = state.outerWidth !== void 0 ? this.viewContext.notebookOptions.computeCodeCellEditorWidth(state.outerWidth) : this.rb?.editorWidth;
      this.rb = {
        fontInfo: state.font ?? this.rb.fontInfo ?? null,
        editorHeight: this.rb.editorHeight,
        editorWidth,
        chatHeight,
        statusBarHeight: 0,
        outputContainerOffset,
        outputTotalHeight,
        outputShowMoreContainerHeight,
        outputShowMoreContainerOffset,
        commentOffset: outputContainerOffset + outputTotalHeight,
        commentHeight,
        totalHeight,
        codeIndicatorHeight,
        outputIndicatorHeight,
        bottomToolbarOffset,
        layoutState: this.rb.layoutState,
        estimatedHasHorizontalScrolling: false
      };
    }
    this.ub({
      ...state,
      totalHeight: this.layoutInfo.totalHeight !== originalLayout.totalHeight,
      source
    });
  }
  ub(state) {
    this.jb.fire(state);
  }
  restoreEditorViewState(editorViewStates, totalHeight) {
    super.restoreEditorViewState(editorViewStates);
    if (totalHeight !== void 0 && this.rb.layoutState !== CellLayoutState.Measured) {
      this.rb = {
        ...this.rb,
        totalHeight,
        layoutState: CellLayoutState.FromCache
      };
    }
  }
  getDynamicHeight() {
    this.cb.fire();
    return this.rb.totalHeight;
  }
  getHeight(lineHeight) {
    if (this.rb.layoutState === CellLayoutState.Uninitialized) {
      const estimate = this.vb(lineHeight);
      return this.wb(estimate.editorHeight, 0, 0, 0);
    } else {
      return this.rb.totalHeight;
    }
  }
  vb(lineHeight = 20) {
    let hasHorizontalScrolling = false;
    const cellEditorOptions = this.viewContext.getBaseCellEditorOptions(this.language);
    if (this.layoutInfo.fontInfo && cellEditorOptions.value.wordWrap === "off") {
      for (let i2 = 0; i2 < this.lineCount; i2++) {
        const max = this.textBuffer.getLineLastNonWhitespaceColumn(i2 + 1);
        const estimatedWidth = max * (this.layoutInfo.fontInfo.typicalHalfwidthCharacterWidth + this.layoutInfo.fontInfo.letterSpacing);
        if (estimatedWidth > this.layoutInfo.editorWidth) {
          hasHorizontalScrolling = true;
          break;
        }
      }
    }
    const verticalScrollbarHeight = hasHorizontalScrolling ? 12 : 0;
    const editorPadding = this.viewContext.notebookOptions.computeEditorPadding(this.internalMetadata, this.uri);
    const editorHeight = this.lineCount * lineHeight + editorPadding.top + editorPadding.bottom + verticalScrollbarHeight;
    return {
      editorHeight,
      hasHorizontalScrolling
    };
  }
  wb(editorHeight, outputsTotalHeight, outputShowMoreContainerHeight, chatHeight) {
    const layoutConfiguration = this.viewContext.notebookOptions.getLayoutConfiguration();
    const { bottomToolbarGap } = this.viewContext.notebookOptions.computeBottomToolbarDimensions(this.viewType);
    return layoutConfiguration.editorToolbarHeight + layoutConfiguration.cellTopMargin + chatHeight + editorHeight + this.viewContext.notebookOptions.computeEditorStatusbarHeight(this.internalMetadata, this.uri) + this.L + outputsTotalHeight + outputShowMoreContainerHeight + bottomToolbarGap + layoutConfiguration.cellBottomMargin;
  }
  ab() {
    if (this.getEditState() !== CellEditState.Editing) {
      this.updateEditState(CellEditState.Editing, "onDidChangeTextModelContent");
      this.b.fire({ contentChanged: true });
    }
  }
  onDeselect() {
    this.updateEditState(CellEditState.Preview, "onDeselect");
  }
  updateOutputShowMoreContainerHeight(height) {
    this.layoutChange({ outputShowMoreContainerHeight: height }, "CodeCellViewModel#updateOutputShowMoreContainerHeight");
  }
  updateOutputMinHeight(height) {
    this.qb = height;
  }
  unlockOutputHeight() {
    this.qb = 0;
    this.layoutChange({ outputHeight: true });
  }
  updateOutputHeight(index, height, source) {
    if (index >= this.hb.length) {
      throw new Error("Output index out of range!");
    }
    this.yb();
    try {
      if (index === 0 || height > 0) {
        this.sb[index].setVisible(true);
      } else if (height === 0) {
        this.sb[index].setVisible(false);
      }
    } catch (e) {
      const errorMessage = `Failed to update output height for cell ${this.handle}, output ${index}. this.outputCollection.length: ${this.hb.length}, this._outputViewModels.length: ${this.sb.length}`;
      throw new Error(`${errorMessage}.
 Error: ${e.message}`);
    }
    if (this.sb[index].visible.get() && height < 28) {
      height = 28;
    }
    this.hb[index] = height;
    if (this.ib.setValue(index, height)) {
      this.layoutChange({ outputHeight: true }, source);
    }
  }
  getOutputOffsetInContainer(index) {
    this.yb();
    if (index >= this.hb.length) {
      throw new Error("Output index out of range!");
    }
    return this.ib.getPrefixSum(index - 1);
  }
  getOutputOffset(index) {
    return this.layoutInfo.outputContainerOffset + this.getOutputOffsetInContainer(index);
  }
  spliceOutputHeights(start, deleteCnt, heights) {
    this.yb();
    this.ib.removeValues(start, deleteCnt);
    if (heights.length) {
      const values = new Uint32Array(heights.length);
      for (let i2 = 0; i2 < heights.length; i2++) {
        values[i2] = heights[i2];
      }
      this.ib.insertValues(start, values);
    }
    this.layoutChange({ outputHeight: true }, "CodeCellViewModel#spliceOutputs");
  }
  yb() {
    if (!this.ib) {
      const values = new Uint32Array(this.hb.length);
      for (let i2 = 0; i2 < this.hb.length; i2++) {
        values[i2] = this.hb[i2];
      }
      this.ib = new $wM(values);
    }
  }
  startFind(value, options3) {
    const matches = super.bb(value, options3);
    if (matches === null) {
      return null;
    }
    return {
      cell: this,
      contentMatches: matches
    };
  }
  dispose() {
    super.dispose();
    this.hb = [];
    this.ib = null;
    $Xc(this.sb);
  }
};
$XIb = __decorate([
  __param(4, $kl),
  __param(5, $mrb),
  __param(6, $oG),
  __param(7, $_F),
  __param(8, $U5)
], $XIb);

// out-build/vs/workbench/contrib/notebook/browser/viewModel/markupCellViewModel.js
var $YIb = class $YIb2 extends $VIb {
  get renderedHtml() {
    return this.db;
  }
  set renderedHtml(value) {
    if (this.db !== value) {
      this.db = value;
      this.b.fire({ contentChanged: true });
    }
  }
  get layoutInfo() {
    return this.cb;
  }
  set renderedMarkdownHeight(newHeight) {
    this.eb = newHeight;
    this.ob(this.mb());
  }
  set chatHeight(newHeight) {
    this.fb = newHeight;
    this.ob(this.mb());
  }
  get chatHeight() {
    return this.fb;
  }
  set editorHeight(newHeight) {
    this.gb = newHeight;
    this.hb = this.viewContext.notebookOptions.computeStatusBarHeight();
    this.ob(this.mb());
  }
  get editorHeight() {
    throw new Error("MarkdownCellViewModel.editorHeight is write only");
  }
  get foldingState() {
    return this.foldingDelegate.getFoldingState(this.foldingDelegate.getCellIndex(this));
  }
  get outputIsHovered() {
    return this.jb;
  }
  set outputIsHovered(v) {
    this.jb = v;
  }
  get outputIsFocused() {
    return this.kb;
  }
  set outputIsFocused(v) {
    this.kb = v;
  }
  get inputInOutputIsFocused() {
    return false;
  }
  set inputInOutputIsFocused(_) {
  }
  get cellIsHovered() {
    return this.lb;
  }
  set cellIsHovered(v) {
    this.lb = v;
    this.b.fire({ cellIsHoveredChanged: true });
  }
  constructor(viewType, model, initialNotebookLayoutInfo, foldingDelegate, viewContext, configurationService, textModelService, undoRedoService, codeEditorService) {
    super(viewType, model, $ps(), viewContext, configurationService, textModelService, undoRedoService, codeEditorService);
    this.foldingDelegate = foldingDelegate;
    this.viewContext = viewContext;
    this.cellKind = CellKind.Markup;
    this.eb = 0;
    this.fb = 0;
    this.gb = 0;
    this.hb = 0;
    this.ib = this.B(new $ze());
    this.onDidChangeLayout = this.ib.event;
    this.jb = false;
    this.kb = false;
    this.lb = false;
    this.outputsViewModels = [];
    this.qb = this.B(new $ze());
    this.hasFindResult = this.qb.event;
    const { bottomToolbarGap } = this.viewContext.notebookOptions.computeBottomToolbarDimensions(this.viewType);
    this.cb = {
      chatHeight: 0,
      editorHeight: 0,
      previewHeight: 0,
      fontInfo: initialNotebookLayoutInfo?.fontInfo || null,
      editorWidth: initialNotebookLayoutInfo?.width ? this.viewContext.notebookOptions.computeMarkdownCellEditorWidth(initialNotebookLayoutInfo.width) : 0,
      commentOffset: 0,
      commentHeight: 0,
      bottomToolbarOffset: bottomToolbarGap,
      totalHeight: 100,
      layoutState: CellLayoutState.Uninitialized,
      foldHintHeight: 0,
      statusBarHeight: 0
    };
    this.B(this.onDidChangeState((e) => {
      this.viewContext.eventDispatcher.emit([new $krb(e, this.model)]);
      if (e.foldingStateChanged) {
        this.ob(this.mb(), CellLayoutContext.Fold);
      }
    }));
  }
  mb() {
    const layoutConfiguration = this.viewContext.notebookOptions.getLayoutConfiguration();
    const { bottomToolbarGap } = this.viewContext.notebookOptions.computeBottomToolbarDimensions(this.viewType);
    const foldHintHeight = this.nb();
    if (this.getEditState() === CellEditState.Editing) {
      return this.gb + layoutConfiguration.markdownCellTopMargin + layoutConfiguration.markdownCellBottomMargin + bottomToolbarGap + this.hb + this.L;
    } else {
      return Math.max(1, this.eb + bottomToolbarGap + foldHintHeight + this.L);
    }
  }
  nb() {
    return this.getEditState() === CellEditState.Editing || this.foldingState !== 2 ? 0 : this.viewContext.notebookOptions.getLayoutConfiguration().markdownFoldHintHeight;
  }
  updateOptions(e) {
    super.updateOptions(e);
    if (e.cellStatusBarVisibility || e.insertToolbarPosition || e.cellToolbarLocation) {
      this.ob(this.mb());
    }
  }
  getOutputOffset(index) {
    return -1;
  }
  updateOutputHeight(index, height) {
  }
  triggerFoldingStateChange() {
    this.b.fire({ foldingStateChanged: true });
  }
  ob(newHeight, context) {
    if (newHeight !== this.layoutInfo.totalHeight) {
      this.layoutChange({ totalHeight: newHeight, context });
    }
  }
  layoutChange(state) {
    let totalHeight;
    let foldHintHeight;
    if (!this.isInputCollapsed) {
      totalHeight = state.totalHeight === void 0 ? this.cb.layoutState === CellLayoutState.Uninitialized ? 100 : this.cb.totalHeight : state.totalHeight;
      foldHintHeight = this.nb();
    } else {
      totalHeight = this.viewContext.notebookOptions.computeCollapsedMarkdownCellHeight(this.viewType);
      state.totalHeight = totalHeight;
      foldHintHeight = 0;
    }
    let commentOffset;
    if (this.getEditState() === CellEditState.Editing) {
      const notebookLayoutConfiguration = this.viewContext.notebookOptions.getLayoutConfiguration();
      commentOffset = notebookLayoutConfiguration.editorToolbarHeight + notebookLayoutConfiguration.cellTopMargin + this.fb + this.gb + this.hb;
    } else {
      commentOffset = this.eb;
    }
    this.cb = {
      fontInfo: state.font || this.cb.fontInfo,
      editorWidth: state.outerWidth !== void 0 ? this.viewContext.notebookOptions.computeMarkdownCellEditorWidth(state.outerWidth) : this.cb.editorWidth,
      chatHeight: this.fb,
      editorHeight: this.gb,
      statusBarHeight: this.hb,
      previewHeight: this.eb,
      bottomToolbarOffset: this.viewContext.notebookOptions.computeBottomToolbarOffset(totalHeight, this.viewType),
      totalHeight,
      layoutState: CellLayoutState.Measured,
      foldHintHeight,
      commentOffset,
      commentHeight: state.commentHeight ? this.L : this.cb.commentHeight
    };
    this.ib.fire(state);
  }
  restoreEditorViewState(editorViewStates, totalHeight) {
    super.restoreEditorViewState(editorViewStates);
    if (totalHeight !== void 0 && this.layoutInfo.layoutState === CellLayoutState.Uninitialized) {
      this.cb = {
        ...this.layoutInfo,
        totalHeight,
        chatHeight: this.fb,
        editorHeight: this.gb,
        statusBarHeight: this.hb,
        layoutState: CellLayoutState.FromCache
      };
      this.layoutChange({});
    }
  }
  getDynamicHeight() {
    return null;
  }
  getHeight(lineHeight) {
    if (this.cb.layoutState === CellLayoutState.Uninitialized) {
      return 100;
    } else {
      return this.cb.totalHeight;
    }
  }
  ab() {
    this.b.fire({ contentChanged: true });
  }
  onDeselect() {
  }
  startFind(value, options3) {
    const matches = super.bb(value, options3);
    if (matches === null) {
      return null;
    }
    return {
      cell: this,
      contentMatches: matches
    };
  }
  dispose() {
    super.dispose();
    this.foldingDelegate = null;
  }
};
$YIb = __decorate([
  __param(5, $kl),
  __param(6, $oG),
  __param(7, $_F),
  __param(8, $U5)
], $YIb);

// out-build/vs/workbench/contrib/notebook/browser/view/cellParts/cellContextKeys.js
var $oJb = class $oJb2 extends $lJb {
  constructor(notebookEditor, b) {
    super();
    this.b = b;
    this.a = this.B(this.b.createInstance($pJb, notebookEditor, void 0));
  }
  didRenderCell(element) {
    this.a.updateForElement(element);
  }
};
$oJb = __decorate([
  __param(1, $Pk)
], $oJb);
var $pJb = class $pJb2 extends $3c {
  constructor(z, C, D, F) {
    super();
    this.z = z;
    this.C = C;
    this.D = D;
    this.F = F;
    this.y = this.B(new $2c());
    this.D.bufferChangeEvents(() => {
      this.a = $0Ab.bindTo(this.D);
      this.b = $$Ab.bindTo(this.D);
      this.c = $_Ab.bindTo(this.D);
      this.f = $aBb.bindTo(this.D);
      this.w = $bBb.bindTo(this.D);
      this.g = $dBb.bindTo(this.D);
      this.h = $eBb.bindTo(this.D);
      this.j = $fBb.bindTo(this.D);
      this.m = $iBb.bindTo(this.D);
      this.n = $jBb.bindTo(this.D);
      this.r = $cBb.bindTo(this.D);
      this.t = $lBb.bindTo(this.D);
      this.s = $kBb.bindTo(this.D);
      this.u = $mBb.bindTo(this.D);
      if (C) {
        this.updateForElement(C);
      }
    });
    this.B(this.F.onDidChangeExecution((e) => {
      if (e.type === NotebookExecutionType.cell && this.C && e.affectsCell(this.C.uri)) {
        this.I();
      }
    }));
  }
  updateForElement(element) {
    this.y.clear();
    this.C = element;
    if (!element) {
      return;
    }
    this.y.add(element.onDidChangeState((e) => this.G(e)));
    if (element instanceof $XIb) {
      this.y.add(element.onDidChangeOutputs(() => this.M()));
      this.y.add($td((reader) => {
        this.u.set(!!reader.readObservable(element.executionErrorDiagnostic));
      }));
    }
    this.y.add(this.z.onDidChangeActiveCell(() => this.H()));
    if (this.C instanceof $YIb) {
      this.a.set("markup");
    } else if (this.C instanceof $XIb) {
      this.a.set("code");
    }
    this.D.bufferChangeEvents(() => {
      this.H();
      this.I();
      this.J();
      this.L();
      this.M();
      this.N();
      this.r.set(this.C.lineNumbers);
      this.s.set(this.C.uri.toString());
    });
    const chatController = $jJb.get(this.z);
    if (chatController) {
      this.y.add(chatController.onDidChangePromptCache((e) => {
        if (e.cell.toString() === this.C.uri.toString()) {
          this.N();
        }
      }));
    }
  }
  G(e) {
    this.D.bufferChangeEvents(() => {
      if (e.internalMetadataChanged) {
        this.I();
      }
      if (e.editStateChanged) {
        this.J();
      }
      if (e.focusModeChanged) {
        this.H();
      }
      if (e.cellLineNumberChanged) {
        this.r.set(this.C.lineNumbers);
      }
      if (e.inputCollapsedChanged || e.outputCollapsedChanged) {
        this.L();
      }
    });
  }
  H() {
    if (!this.C) {
      return;
    }
    const activeCell = this.z.getActiveCell();
    this.c.set(this.z.getActiveCell() === this.C);
    if (activeCell === this.C) {
      this.f.set(this.C.focusMode === CellFocusMode.Editor);
    } else {
      this.f.set(false);
    }
  }
  I() {
    if (!this.C) {
      return;
    }
    const internalMetadata = this.C.internalMetadata;
    this.b.set(!this.z.isReadOnly);
    const exeState = this.F.getCellExecution(this.C.uri);
    if (this.C instanceof $YIb) {
      this.g.reset();
      this.h.reset();
    } else if (exeState?.state === NotebookCellExecutionState.Executing) {
      this.g.set("executing");
      this.h.set(true);
    } else if (exeState?.state === NotebookCellExecutionState.Pending || exeState?.state === NotebookCellExecutionState.Unconfirmed) {
      this.g.set("pending");
      this.h.set(true);
    } else if (internalMetadata.lastRunSuccess === true) {
      this.g.set("succeeded");
      this.h.set(false);
    } else if (internalMetadata.lastRunSuccess === false) {
      this.g.set("failed");
      this.h.set(false);
    } else {
      this.g.set("idle");
      this.h.set(false);
    }
  }
  J() {
    if (!this.C) {
      return;
    }
    if (this.C instanceof $YIb) {
      this.w.set(this.C.getEditState() === CellEditState.Editing);
    } else {
      this.w.set(false);
    }
  }
  L() {
    if (!this.C) {
      return;
    }
    this.m.set(!!this.C.isInputCollapsed);
    this.n.set(!!this.C.isOutputCollapsed);
  }
  M() {
    if (this.C instanceof $XIb) {
      this.j.set(this.C.outputsViewModels.length > 0);
    } else {
      this.j.set(false);
    }
  }
  N() {
    const chatController = $jJb.get(this.z);
    if (!chatController || !this.C) {
      this.t.set(false);
      return;
    }
    this.t.set(chatController.isCellGeneratedByChat(this.C));
  }
};
$pJb = __decorate([
  __param(2, $on),
  __param(3, $wL)
], $pJb);

// out-build/vs/workbench/contrib/notebook/browser/view/cellParts/cellDnd.js
var $121 = $;
var DRAGGING_CLASS = "cell-dragging";
var GLOBAL_DRAG_CLASS = "global-drag-active";
var $qJb = class extends $lJb {
  constructor(g) {
    super();
    this.g = g;
  }
  didRenderCell(element) {
    this.h(element);
  }
  updateState(element, e) {
    if (e.dragStateChanged) {
      this.h(element);
    }
  }
  h(element) {
    this.g.classList.toggle(DRAGGING_CLASS, element.dragging);
  }
};
var $rJb = class extends $3c {
  constructor(r2, t) {
    super();
    this.r = r2;
    this.t = t;
    this.f = [];
    this.j = false;
    this.n = this.B(new $4c());
    this.g = $bk(t, $121(".cell-list-insertion-indicator"));
    this.B($_i(t.ownerDocument.body, $7j.DRAG_START, this.y.bind(this), true));
    this.B($_i(t.ownerDocument.body, $7j.DRAG_END, this.z.bind(this), true));
    const addCellDragListener = (eventType, handler, useCapture = false) => {
      this.B($_i(r2.getDomNode(), eventType, (e) => {
        const cellDragEvent = this.w(e);
        if (cellDragEvent) {
          handler(cellDragEvent);
        }
      }, useCapture));
    };
    addCellDragListener($7j.DRAG_OVER, (event) => {
      if (!this.c) {
        return;
      }
      event.browserEvent.preventDefault();
      this.C(event);
    }, true);
    addCellDragListener($7j.DROP, (event) => {
      if (!this.c) {
        return;
      }
      event.browserEvent.preventDefault();
      this.G(event);
    });
    addCellDragListener($7j.DRAG_LEAVE, (event) => {
      event.browserEvent.preventDefault();
      this.J(event);
    });
    this.m = this.B(new $Sh(200));
  }
  setList(value) {
    this.h = value;
    this.n.value = this.h.onWillScroll((e) => {
      if (!e.scrollTopChanged) {
        return;
      }
      this.u(false);
      this.j = true;
      this.m.trigger(() => {
        this.j = false;
      });
    });
  }
  u(visible) {
    this.g.style.opacity = visible ? "1" : "0";
  }
  w(event) {
    const targetTop = this.t.getBoundingClientRect().top;
    const dragOffset = this.h.scrollTop + event.clientY - targetTop;
    const draggedOverCell = this.h.elementAt(dragOffset);
    if (!draggedOverCell) {
      return void 0;
    }
    const cellTop = this.h.getCellViewScrollTop(draggedOverCell);
    const cellHeight = this.h.elementHeight(draggedOverCell);
    const dragPosInElement = dragOffset - cellTop;
    const dragPosRatio = dragPosInElement / cellHeight;
    return {
      browserEvent: event,
      draggedOverCell,
      cellTop,
      cellHeight,
      dragPosRatio
    };
  }
  clearGlobalDragState() {
    this.r.getDomNode().classList.remove(GLOBAL_DRAG_CLASS);
  }
  y() {
    this.r.getDomNode().classList.add(GLOBAL_DRAG_CLASS);
  }
  z() {
    this.r.getDomNode().classList.remove(GLOBAL_DRAG_CLASS);
  }
  C(event) {
    if (!event.browserEvent.dataTransfer) {
      return;
    }
    if (!this.c) {
      event.browserEvent.dataTransfer.dropEffect = "none";
      return;
    }
    if (this.j || this.c === event.draggedOverCell) {
      this.u(false);
      return;
    }
    const dropDirection = this.F(event.dragPosRatio);
    const insertionIndicatorAbsolutePos = dropDirection === "above" ? event.cellTop : event.cellTop + event.cellHeight;
    this.D(dropDirection, insertionIndicatorAbsolutePos);
  }
  D(dropDirection, insertionIndicatorAbsolutePos) {
    const { bottomToolbarGap } = this.r.notebookOptions.computeBottomToolbarDimensions(this.r.textModel?.viewType);
    const insertionIndicatorTop = insertionIndicatorAbsolutePos - this.h.scrollTop + bottomToolbarGap / 2;
    if (insertionIndicatorTop >= 0) {
      this.g.style.top = `${insertionIndicatorTop}px`;
      this.u(true);
    } else {
      this.u(false);
    }
  }
  F(dragPosRatio) {
    return dragPosRatio < 0.5 ? "above" : "below";
  }
  G(event) {
    const draggedCell = this.c;
    if (this.j || this.c === event.draggedOverCell) {
      return;
    }
    this.L();
    const dropDirection = this.F(event.dragPosRatio);
    this.I(draggedCell, dropDirection, event.browserEvent, event.draggedOverCell);
  }
  H(draggedCellIndex) {
    const selections = this.r.getSelections();
    const modelRanges = $Rrb(this.r, selections);
    const nearestRange = modelRanges.find((range) => range.start <= draggedCellIndex && draggedCellIndex < range.end);
    if (nearestRange) {
      return nearestRange;
    } else {
      return { start: draggedCellIndex, end: draggedCellIndex + 1 };
    }
  }
  I(draggedCell, dropDirection, ctx, draggedOverCell) {
    const cellTop = this.h.getCellViewScrollTop(draggedOverCell);
    const cellHeight = this.h.elementHeight(draggedOverCell);
    const insertionIndicatorAbsolutePos = dropDirection === "above" ? cellTop : cellTop + cellHeight;
    const { bottomToolbarGap } = this.r.notebookOptions.computeBottomToolbarDimensions(this.r.textModel?.viewType);
    const insertionIndicatorTop = insertionIndicatorAbsolutePos - this.h.scrollTop + bottomToolbarGap / 2;
    const editorHeight = this.r.getDomNode().getBoundingClientRect().height;
    if (insertionIndicatorTop < 0 || insertionIndicatorTop > editorHeight) {
      return;
    }
    const isCopy = ctx.ctrlKey && !$m || ctx.altKey && $m;
    if (!this.r.hasModel()) {
      return;
    }
    const textModel = this.r.textModel;
    if (isCopy) {
      const draggedCellIndex = this.r.getCellIndex(draggedCell);
      const range = this.H(draggedCellIndex);
      let originalToIdx = this.r.getCellIndex(draggedOverCell);
      if (dropDirection === "below") {
        const relativeToIndex = this.r.getCellIndex(draggedOverCell);
        const newIdx = this.r.getNextVisibleCellIndex(relativeToIndex);
        originalToIdx = newIdx;
      }
      let finalSelection;
      let finalFocus;
      if (originalToIdx <= range.start) {
        finalSelection = { start: originalToIdx, end: originalToIdx + range.end - range.start };
        finalFocus = { start: originalToIdx + draggedCellIndex - range.start, end: originalToIdx + draggedCellIndex - range.start + 1 };
      } else {
        const delta = originalToIdx - range.start;
        finalSelection = { start: range.start + delta, end: range.end + delta };
        finalFocus = { start: draggedCellIndex + delta, end: draggedCellIndex + delta + 1 };
      }
      textModel.applyEdits([
        {
          editType: 1,
          index: originalToIdx,
          count: 0,
          cells: $GL([range]).map((index) => $tL(this.r.cellAt(index).model))
        }
      ], true, { kind: SelectionStateType.Index, focus: this.r.getFocus(), selections: this.r.getSelections() }, () => ({ kind: SelectionStateType.Index, focus: finalFocus, selections: [finalSelection] }), void 0, true);
      this.r.revealCellRangeInView(finalSelection);
    } else {
      $sJb(this.r, draggedCell, dropDirection, draggedOverCell);
    }
  }
  J(event) {
    if (!event.browserEvent.relatedTarget || !$Dj(event.browserEvent.relatedTarget, this.r.getDomNode())) {
      this.u(false);
    }
  }
  L() {
    if (this.c) {
      this.f.forEach((cell) => cell.dragging = false);
      this.c = void 0;
      this.f = [];
    }
    this.u(false);
  }
  registerDragHandle(templateData, cellRoot, dragHandles, dragImageProvider) {
    const container2 = templateData.container;
    for (const dragHandle of dragHandles) {
      dragHandle.setAttribute("draggable", "true");
    }
    const onDragEnd = () => {
      if (!this.r.notebookOptions.getDisplayOptions().dragAndDropEnabled || !!this.r.isReadOnly) {
        return;
      }
      container2.classList.remove(DRAGGING_CLASS);
      this.L();
    };
    for (const dragHandle of dragHandles) {
      templateData.templateDisposables.add($_i(dragHandle, $7j.DRAG_END, onDragEnd));
    }
    const onDragStart = (event) => {
      if (!event.dataTransfer) {
        return;
      }
      if (!this.r.notebookOptions.getDisplayOptions().dragAndDropEnabled || !!this.r.isReadOnly) {
        return;
      }
      this.c = templateData.currentRenderedCell;
      this.f = this.r.getSelections().map((range) => this.r.getCellsInRange(range)).flat();
      this.f.forEach((cell) => cell.dragging = true);
      const dragImage = dragImageProvider();
      cellRoot.parentElement.appendChild(dragImage);
      event.dataTransfer.setDragImage(dragImage, 0, 0);
      setTimeout(() => dragImage.remove(), 0);
    };
    for (const dragHandle of dragHandles) {
      templateData.templateDisposables.add($_i(dragHandle, $7j.DRAG_START, onDragStart));
    }
  }
  startExplicitDrag(cell, _dragOffsetY) {
    if (!this.r.notebookOptions.getDisplayOptions().dragAndDropEnabled || !!this.r.isReadOnly) {
      return;
    }
    this.c = cell;
    this.u(true);
  }
  explicitDrag(cell, dragOffsetY) {
    if (!this.r.notebookOptions.getDisplayOptions().dragAndDropEnabled || !!this.r.isReadOnly) {
      return;
    }
    const target = this.h.elementAt(dragOffsetY);
    if (target && target !== cell) {
      const cellTop = this.h.getCellViewScrollTop(target);
      const cellHeight = this.h.elementHeight(target);
      const dropDirection = this.M(dragOffsetY, cellTop, cellHeight);
      const insertionIndicatorAbsolutePos = dropDirection === "above" ? cellTop : cellTop + cellHeight;
      this.D(dropDirection, insertionIndicatorAbsolutePos);
    }
    if (this.c !== cell) {
      return;
    }
    const notebookViewRect = this.r.getDomNode().getBoundingClientRect();
    const eventPositionInView = dragOffsetY - this.h.scrollTop;
    const notebookViewScrollMargins = 0.2;
    const maxScrollDeltaPerFrame = 20;
    const eventPositionRatio = eventPositionInView / notebookViewRect.height;
    if (eventPositionRatio < notebookViewScrollMargins) {
      this.h.scrollTop -= maxScrollDeltaPerFrame * (1 - eventPositionRatio / notebookViewScrollMargins);
    } else if (eventPositionRatio > 1 - notebookViewScrollMargins) {
      this.h.scrollTop += maxScrollDeltaPerFrame * (1 - (1 - eventPositionRatio) / notebookViewScrollMargins);
    }
  }
  endExplicitDrag(_cell) {
    this.u(false);
  }
  explicitDrop(cell, ctx) {
    this.c = void 0;
    this.u(false);
    const target = this.h.elementAt(ctx.dragOffsetY);
    if (!target || target === cell) {
      return;
    }
    const cellTop = this.h.getCellViewScrollTop(target);
    const cellHeight = this.h.elementHeight(target);
    const dropDirection = this.M(ctx.dragOffsetY, cellTop, cellHeight);
    this.I(cell, dropDirection, ctx, target);
  }
  M(clientY, cellTop, cellHeight) {
    const dragPosInElement = clientY - cellTop;
    const dragPosRatio = dragPosInElement / cellHeight;
    return this.F(dragPosRatio);
  }
  dispose() {
    this.r = null;
    super.dispose();
  }
};
function $sJb(editor, draggedCell, dropDirection, draggedOverCell) {
  const draggedCellIndex = editor.getCellIndex(draggedCell);
  let originalToIdx = editor.getCellIndex(draggedOverCell);
  if (typeof draggedCellIndex !== "number" || typeof originalToIdx !== "number") {
    return;
  }
  if (dropDirection === "below") {
    const newIdx = editor.getNextVisibleCellIndex(originalToIdx) ?? originalToIdx;
    originalToIdx = newIdx;
  }
  let selections = editor.getSelections();
  if (!selections.length) {
    selections = [editor.getFocus()];
  }
  let originalFocusIdx = editor.getFocus().start;
  if (!selections.some((s) => s.start <= draggedCellIndex && s.end > draggedCellIndex)) {
    selections = [{ start: draggedCellIndex, end: draggedCellIndex + 1 }];
    originalFocusIdx = draggedCellIndex;
  }
  const droppedInSelection = selections.find((range) => range.start <= originalToIdx && range.end > originalToIdx);
  if (droppedInSelection) {
    originalToIdx = droppedInSelection.start;
  }
  let numCells = 0;
  let focusNewIdx = originalToIdx;
  let newInsertionIdx = originalToIdx;
  selections.sort((a, b) => b.start - a.start);
  const edits = selections.map((range) => {
    const length = range.end - range.start;
    let toIndexDelta = 0;
    if (range.end <= newInsertionIdx) {
      toIndexDelta = -length;
    }
    const newIdx = newInsertionIdx + toIndexDelta;
    if (originalFocusIdx >= range.start && originalFocusIdx <= range.end) {
      const offset = originalFocusIdx - range.start;
      focusNewIdx = newIdx + offset;
    }
    const fromIndexDelta = range.start >= originalToIdx ? numCells : 0;
    const edit3 = {
      editType: 6,
      index: range.start + fromIndexDelta,
      length,
      newIdx
    };
    numCells += length;
    if (range.end < newInsertionIdx) {
      newInsertionIdx -= length;
    }
    return edit3;
  });
  const lastEdit = edits[edits.length - 1];
  const finalSelection = { start: lastEdit.newIdx, end: lastEdit.newIdx + numCells };
  const finalFocus = { start: focusNewIdx, end: focusNewIdx + 1 };
  editor.textModel.applyEdits(edits, true, { kind: SelectionStateType.Index, focus: editor.getFocus(), selections: editor.getSelections() }, () => ({ kind: SelectionStateType.Index, focus: finalFocus, selections: [finalSelection] }), void 0, true);
  editor.revealCellRangeInView(finalSelection);
}

// out-build/vs/workbench/contrib/notebook/browser/view/notebookCellListView.js
var $tJb = class {
  get paddingTop() {
    return this.g;
  }
  set paddingTop(paddingTop) {
    this.f = this.f + paddingTop - this.g;
    this.g = paddingTop;
  }
  get count() {
    return this.c.length;
  }
  /**
   * Returns the sum of the sizes of all items in the range map.
   */
  get size() {
    return this.f;
  }
  constructor(topPadding) {
    this.c = [];
    this.d = [];
    this.e = new $xM([]);
    this.f = 0;
    this.g = 0;
    this.g = topPadding ?? 0;
    this.f = this.g;
  }
  getWhitespaces() {
    return this.d;
  }
  restoreWhitespace(items) {
    this.d = items;
    this.f = this.g + this.c.reduce((total, item) => total + item.size, 0) + this.d.reduce((total, ws) => total + ws.size, 0);
  }
  /**
   */
  splice(index, deleteCount, items) {
    const inserts = items ?? [];
    this.c.splice(index, deleteCount, ...inserts);
    this.f = this.g + this.c.reduce((total, item) => total + item.size, 0) + this.d.reduce((total, ws) => total + ws.size, 0);
    this.e.removeValues(index, deleteCount);
    const newSizes = [];
    for (let i2 = 0; i2 < inserts.length; i2++) {
      const insertIndex = i2 + index;
      const existingWhitespaces = this.d.filter((ws) => ws.afterPosition === insertIndex + 1);
      if (existingWhitespaces.length > 0) {
        newSizes.push(inserts[i2].size + existingWhitespaces.reduce((acc, ws) => acc + ws.size, 0));
      } else {
        newSizes.push(inserts[i2].size);
      }
    }
    this.e.insertValues(index, newSizes);
    for (let i2 = index; i2 < this.c.length; i2++) {
      const existingWhitespaces = this.d.filter((ws) => ws.afterPosition === i2 + 1);
      if (existingWhitespaces.length > 0) {
        this.e.setValue(i2, this.c[i2].size + existingWhitespaces.reduce((acc, ws) => acc + ws.size, 0));
      } else {
        this.e.setValue(i2, this.c[i2].size);
      }
    }
  }
  insertWhitespace(id2, afterPosition, size) {
    let priority = 0;
    const existingWhitespaces = this.d.filter((ws) => ws.afterPosition === afterPosition);
    if (existingWhitespaces.length > 0) {
      priority = Math.max(...existingWhitespaces.map((ws) => ws.priority)) + 1;
    }
    this.d.push({ id: id2, afterPosition, size, priority });
    this.f += size;
    this.d.sort((a, b) => {
      if (a.afterPosition === b.afterPosition) {
        return a.priority - b.priority;
      }
      return a.afterPosition - b.afterPosition;
    });
    if (afterPosition > 0) {
      const index = afterPosition - 1;
      const itemSize = this.c[index].size;
      const accSize = itemSize + size;
      this.e.setValue(index, accSize);
    }
  }
  changeOneWhitespace(id2, afterPosition, size) {
    const whitespaceIndex = this.d.findIndex((ws) => ws.id === id2);
    if (whitespaceIndex !== -1) {
      const whitespace = this.d[whitespaceIndex];
      const oldAfterPosition = whitespace.afterPosition;
      whitespace.afterPosition = afterPosition;
      const oldSize = whitespace.size;
      const delta = size - oldSize;
      whitespace.size = size;
      this.f += delta;
      if (oldAfterPosition > 0 && oldAfterPosition <= this.c.length) {
        const index = oldAfterPosition - 1;
        const itemSize = this.c[index].size;
        const accSize = itemSize;
        this.e.setValue(index, accSize);
      }
      if (afterPosition > 0 && afterPosition <= this.c.length) {
        const index = afterPosition - 1;
        const itemSize = this.c[index].size;
        const accSize = itemSize + size;
        this.e.setValue(index, accSize);
      }
    }
  }
  removeWhitespace(id2) {
    const whitespaceIndex = this.d.findIndex((ws) => ws.id === id2);
    if (whitespaceIndex !== -1) {
      const whitespace = this.d[whitespaceIndex];
      this.d.splice(whitespaceIndex, 1);
      this.f -= whitespace.size;
      if (whitespace.afterPosition > 0) {
        const index = whitespace.afterPosition - 1;
        const itemSize = this.c[index].size;
        const remainingWhitespaces = this.d.filter((ws) => ws.afterPosition === whitespace.afterPosition);
        const accSize = itemSize + remainingWhitespaces.reduce((acc, ws) => acc + ws.size, 0);
        this.e.setValue(index, accSize);
      }
    }
  }
  /**
   * find position of whitespace
   * @param id: id of the whitespace
   * @returns: position in the list view
   */
  getWhitespacePosition(id2) {
    const whitespace = this.d.find((ws) => ws.id === id2);
    if (!whitespace) {
      throw new Error("Whitespace not found");
    }
    const afterPosition = whitespace.afterPosition;
    if (afterPosition === 0) {
      const whitespaces = this.d.filter((ws) => ws.afterPosition === afterPosition && ws.priority < whitespace.priority);
      return whitespaces.reduce((acc, ws) => acc + ws.size, 0) + this.paddingTop;
    }
    const whitespaceBeforeFirstItem = this.d.filter((ws) => ws.afterPosition === 0).reduce((acc, ws) => acc + ws.size, 0);
    const index = afterPosition - 1;
    const previousItemPosition = this.e.getPrefixSum(index);
    const previousItemSize = this.c[index].size;
    const previousWhitespace = this.d.filter((ws) => ws.afterPosition <= afterPosition - 1 && ws.afterPosition > 0);
    const whitespaceBefore = previousWhitespace.reduce((acc, ws) => acc + ws.size, 0);
    return previousItemPosition + previousItemSize + whitespaceBeforeFirstItem + this.paddingTop + whitespaceBefore;
  }
  indexAt(position) {
    if (position < 0) {
      return -1;
    }
    const whitespaceBeforeFirstItem = this.d.filter((ws) => ws.afterPosition === 0).reduce((acc, ws) => acc + ws.size, 0);
    const offset = position - (this.g + whitespaceBeforeFirstItem);
    if (offset <= 0) {
      return 0;
    }
    if (offset >= this.f - this.g - whitespaceBeforeFirstItem) {
      return this.count;
    }
    return this.e.getIndexOf(Math.trunc(offset)).index;
  }
  indexAfter(position) {
    const index = this.indexAt(position);
    return Math.min(index + 1, this.c.length);
  }
  positionAt(index) {
    if (index < 0) {
      return -1;
    }
    if (this.count === 0) {
      return -1;
    }
    if (index >= this.count) {
      return -1;
    }
    const whitespaceBeforeFirstItem = this.d.filter((ws) => ws.afterPosition === 0).reduce((acc, ws) => acc + ws.size, 0);
    return this.e.getPrefixSum(
      index
      /** count */
    ) + this.g + whitespaceBeforeFirstItem;
  }
};
var $uJb = class extends $j1 {
  constructor() {
    super(...arguments);
    this.yb = 0;
    this.zb = 0;
  }
  get inRenderingTransaction() {
    return this.zb > 0;
  }
  get notebookRangeMap() {
    return this.g;
  }
  Y(previousRenderRange, renderTop, renderHeight, renderLeft, scrollWidth, updateItemsInDOM) {
    this.zb++;
    super.Y(previousRenderRange, renderTop, renderHeight, renderLeft, scrollWidth, updateItemsInDOM);
    this.zb--;
  }
  wb(renderTop, renderHeight, inSmoothScrolling) {
    this.zb++;
    super.wb(renderTop, renderHeight, inSmoothScrolling);
    this.zb--;
  }
  S(paddingTop) {
    const existingMap = this.g;
    if (existingMap) {
      const layout = new $tJb(paddingTop);
      layout.restoreWhitespace(existingMap.getWhitespaces());
      return layout;
    } else {
      return new $tJb(paddingTop);
    }
  }
  insertWhitespace(afterPosition, size) {
    const scrollTop = this.scrollTop;
    const id2 = `${++this.yb}`;
    const previousRenderRange = this.vb(this.k, this.m);
    const elementPosition = this.elementTop(afterPosition);
    const aboveScrollTop = scrollTop > elementPosition;
    this.notebookRangeMap.insertWhitespace(id2, afterPosition, size);
    const newScrolltop = aboveScrollTop ? scrollTop + size : scrollTop;
    this.Y(previousRenderRange, newScrolltop, this.m, void 0, void 0, false);
    this.wb(newScrolltop, this.renderHeight, false);
    this.V();
    return id2;
  }
  changeOneWhitespace(id2, newAfterPosition, newSize) {
    const scrollTop = this.scrollTop;
    const previousRenderRange = this.vb(this.k, this.m);
    const currentPosition = this.notebookRangeMap.getWhitespacePosition(id2);
    if (currentPosition > scrollTop) {
      this.notebookRangeMap.changeOneWhitespace(id2, newAfterPosition, newSize);
      this.Y(previousRenderRange, scrollTop, this.m, void 0, void 0, false);
      this.wb(scrollTop, this.renderHeight, false);
      this.V();
    } else {
      this.notebookRangeMap.changeOneWhitespace(id2, newAfterPosition, newSize);
      this.V();
    }
  }
  removeWhitespace(id2) {
    const scrollTop = this.scrollTop;
    const previousRenderRange = this.vb(this.k, this.m);
    const currentPosition = this.notebookRangeMap.getWhitespacePosition(id2);
    if (currentPosition > scrollTop) {
      this.notebookRangeMap.removeWhitespace(id2);
      this.Y(previousRenderRange, scrollTop, this.m, void 0, void 0, false);
      this.wb(scrollTop, this.renderHeight, false);
      this.V();
    } else {
      this.notebookRangeMap.removeWhitespace(id2);
      this.V();
    }
  }
  getWhitespacePosition(id2) {
    return this.notebookRangeMap.getWhitespacePosition(id2);
  }
};

// out-build/vs/workbench/contrib/notebook/browser/view/notebookCellAnchor.js
var $vJb = class {
  constructor(d, e, f) {
    this.d = d;
    this.e = e;
    this.f = f;
    this.a = false;
  }
  shouldAnchor(cellListView, focusedIndex, heightDelta, executingCellUri) {
    if (cellListView.element(focusedIndex).focusMode === CellFocusMode.Editor) {
      return true;
    }
    if (this.a) {
      return false;
    }
    const newFocusBottom = cellListView.elementTop(focusedIndex) + cellListView.elementHeight(focusedIndex) + heightDelta;
    const viewBottom = cellListView.renderHeight + cellListView.getScrollTop();
    const focusStillVisible = viewBottom > newFocusBottom;
    const allowScrolling = this.e.getValue($rM.scrollToRevealCell) !== "none";
    const growing = heightDelta > 0;
    const autoAnchor = allowScrolling && growing && !focusStillVisible;
    if (autoAnchor) {
      this.watchAchorDuringExecution(executingCellUri);
      return true;
    }
    return false;
  }
  watchAchorDuringExecution(executingCell) {
    if (!this.b && executingCell.cellKind === CellKind.Code) {
      const executionState = this.d.getCellExecution(executingCell.uri);
      if (executionState && executionState.state === NotebookCellExecutionState.Executing) {
        this.b = executingCell.onDidStopExecution(() => {
          this.b?.dispose();
          this.b = void 0;
          this.c?.dispose();
          this.a = false;
        });
        this.c = this.f((scrollEvent) => {
          if (scrollEvent.scrollTop < scrollEvent.oldScrollTop) {
            this.a = true;
            this.c?.dispose();
          }
        });
      }
    }
  }
  dispose() {
    this.b?.dispose();
    this.c?.dispose();
  }
};

// out-build/vs/workbench/contrib/notebook/browser/viewParts/notebookViewZones.js
var invalidFunc3 = () => {
  throw new Error(`Invalid notebook view zone change accessor`);
};
var $wJb = class extends $3c {
  constructor(b, c) {
    super();
    this.b = b;
    this.c = c;
    this.domNode = $oZ(document.createElement("div"));
    this.domNode.setClassName("view-zones");
    this.domNode.setPosition("absolute");
    this.domNode.setAttribute("role", "presentation");
    this.domNode.setAttribute("aria-hidden", "true");
    this.domNode.setWidth("100%");
    this.a = {};
    this.b.containerDomNode.appendChild(this.domNode.domNode);
  }
  changeViewZones(callback) {
    let zonesHaveChanged = false;
    const changeAccessor = {
      addZone: (zone) => {
        zonesHaveChanged = true;
        return this.g(zone);
      },
      removeZone: (id2) => {
        zonesHaveChanged = true;
        this.h(id2);
      },
      layoutZone: (id2) => {
        zonesHaveChanged = true;
        this.j(id2);
      }
    };
    safeInvoke1Arg2(callback, changeAccessor);
    changeAccessor.addZone = invalidFunc3;
    changeAccessor.removeZone = invalidFunc3;
    changeAccessor.layoutZone = invalidFunc3;
    return zonesHaveChanged;
  }
  onCellsChanged(e) {
    const splices = e.splices.slice().reverse();
    splices.forEach((splice2) => {
      const [start, deleted, newCells] = splice2;
      const fromIndex = start;
      const toIndex = start + deleted;
      for (const id2 in this.a) {
        const zone = this.a[id2].zone;
        const cellBeforeWhitespaceIndex = zone.afterModelPosition - 1;
        if (cellBeforeWhitespaceIndex >= fromIndex && cellBeforeWhitespaceIndex < toIndex) {
          zone.afterModelPosition = fromIndex;
          this.f(this.a[id2]);
        } else if (cellBeforeWhitespaceIndex >= toIndex) {
          const insertLength = newCells.length;
          const offset = insertLength - deleted;
          zone.afterModelPosition += offset;
          this.f(this.a[id2]);
        }
      }
    });
  }
  onHiddenRangesChange() {
    for (const id2 in this.a) {
      this.f(this.a[id2]);
    }
  }
  f(zone) {
    const whitespaceId = zone.whitespaceId;
    const viewPosition = this.c.convertModelIndexToViewIndex(zone.zone.afterModelPosition);
    const isInHiddenArea = this.m(zone.zone);
    zone.isInHiddenArea = isInHiddenArea;
    this.b.changeOneWhitespace(whitespaceId, viewPosition, isInHiddenArea ? 0 : zone.zone.heightInPx);
  }
  layout() {
    for (const id2 in this.a) {
      this.j(id2);
    }
  }
  g(zone) {
    const viewPosition = this.c.convertModelIndexToViewIndex(zone.afterModelPosition);
    const whitespaceId = this.b.insertWhitespace(viewPosition, zone.heightInPx);
    const isInHiddenArea = this.m(zone);
    const myZone = {
      whitespaceId,
      zone,
      domNode: $oZ(zone.domNode),
      isInHiddenArea
    };
    this.a[whitespaceId] = myZone;
    myZone.domNode.setPosition("absolute");
    myZone.domNode.domNode.style.width = "100%";
    myZone.domNode.setDisplay("none");
    myZone.domNode.setAttribute("notebook-view-zone", whitespaceId);
    this.domNode.appendChild(myZone.domNode);
    return whitespaceId;
  }
  h(id2) {
    this.b.removeWhitespace(id2);
    delete this.a[id2];
  }
  j(id2) {
    const zoneWidget = this.a[id2];
    if (!zoneWidget) {
      return;
    }
    this.f(this.a[id2]);
    const isInHiddenArea = this.m(zoneWidget.zone);
    if (isInHiddenArea) {
      zoneWidget.domNode.setDisplay("none");
    } else {
      const top2 = this.b.getWhitespacePosition(zoneWidget.whitespaceId);
      zoneWidget.domNode.setTop(top2);
      zoneWidget.domNode.setDisplay("block");
      zoneWidget.domNode.setHeight(zoneWidget.zone.heightInPx);
    }
  }
  m(zone) {
    const afterIndex = zone.afterModelPosition;
    return !this.c.modelIndexIsVisible(afterIndex);
  }
  dispose() {
    super.dispose();
    this.a = {};
  }
};
function safeInvoke1Arg2(func, arg1) {
  try {
    func(arg1);
  } catch (e) {
    $gb(e);
  }
}

// out-build/vs/workbench/contrib/notebook/browser/view/notebookCellList.js
var CellRevealPosition;
(function(CellRevealPosition2) {
  CellRevealPosition2[CellRevealPosition2["Top"] = 0] = "Top";
  CellRevealPosition2[CellRevealPosition2["Center"] = 1] = "Center";
  CellRevealPosition2[CellRevealPosition2["Bottom"] = 2] = "Bottom";
  CellRevealPosition2[CellRevealPosition2["NearTop"] = 3] = "NearTop";
})(CellRevealPosition || (CellRevealPosition = {}));
function getVisibleCells(cells, hiddenRanges) {
  if (!hiddenRanges.length) {
    return cells;
  }
  let start = 0;
  let hiddenRangeIndex = 0;
  const result = [];
  while (start < cells.length && hiddenRangeIndex < hiddenRanges.length) {
    if (start < hiddenRanges[hiddenRangeIndex].start) {
      result.push(...cells.slice(start, hiddenRanges[hiddenRangeIndex].start));
    }
    start = hiddenRanges[hiddenRangeIndex].end + 1;
    hiddenRangeIndex++;
  }
  if (start < cells.length) {
    result.push(...cells.slice(start));
  }
  return result;
}
var $xJb = 5e3;
function validateWebviewBoundary(element) {
  const webviewTop = 0 - (parseInt(element.style.top, 10) || 0);
  return webviewTop >= 0 && webviewTop <= $xJb * 2;
}
var $yJb = class $yJb2 extends $Web {
  get onWillScroll() {
    return this.o.onWillScroll;
  }
  get rowsContainer() {
    return this.o.containerDomNode;
  }
  get scrollableElement() {
    return this.o.scrollableElementDomNode;
  }
  get viewModel() {
    return this.ab;
  }
  get visibleRanges() {
    return this.eb;
  }
  set visibleRanges(ranges) {
    if ($IL(this.eb, ranges)) {
      return;
    }
    this.eb = ranges;
    this.db.fire();
  }
  get isDisposed() {
    return this.fb;
  }
  get webviewElement() {
    return this.hb;
  }
  get inRenderingTransaction() {
    return this.o.inRenderingTransaction;
  }
  constructor(ib, container2, jb, delegate, renderers, contextKeyService, options3, listService, configurationService, instantiationService, notebookExecutionStateService) {
    super(ib, container2, delegate, renderers, options3, contextKeyService, listService, configurationService, instantiationService);
    this.ib = ib;
    this.jb = jb;
    this.s = [];
    this.S = new $2c();
    this.U = new $2c();
    this.X = this.S.add(new $ze());
    this.onDidRemoveOutputs = this.X.event;
    this.Y = this.S.add(new $ze());
    this.onDidHideOutputs = this.Y.event;
    this.Z = this.S.add(new $ze());
    this.onDidRemoveCellsFromView = this.Z.event;
    this.ab = null;
    this.bb = [];
    this.cb = null;
    this.db = this.S.add(new $ze());
    this.onDidChangeVisibleRanges = this.db.event;
    this.eb = [];
    this.fb = false;
    this.gb = false;
    this.hb = null;
    $XAb.bindTo(this.contextKeyService).set(true);
    this.s = this.getFocusedElements();
    this.S.add(this.onDidChangeFocus((e) => {
      this.s.forEach((element) => {
        if (e.elements.indexOf(element) < 0) {
          element.onDeselect();
        }
      });
      this.s = e.elements;
    }));
    const notebookEditorCursorAtBoundaryContext = $nM.bindTo(contextKeyService);
    notebookEditorCursorAtBoundaryContext.set("none");
    const notebookEditorCursorAtLineBoundaryContext = $oM.bindTo(contextKeyService);
    notebookEditorCursorAtLineBoundaryContext.set("none");
    const cursorSelectionListener = this.S.add(new $4c());
    const textEditorAttachListener = this.S.add(new $4c());
    this.W = new $vJb(notebookExecutionStateService, configurationService, this.onDidScroll);
    const recomputeContext = (element) => {
      switch (element.cursorAtBoundary()) {
        case CursorAtBoundary.Both:
          notebookEditorCursorAtBoundaryContext.set("both");
          break;
        case CursorAtBoundary.Top:
          notebookEditorCursorAtBoundaryContext.set("top");
          break;
        case CursorAtBoundary.Bottom:
          notebookEditorCursorAtBoundaryContext.set("bottom");
          break;
        default:
          notebookEditorCursorAtBoundaryContext.set("none");
          break;
      }
      switch (element.cursorAtLineBoundary()) {
        case CursorAtLineBoundary.Both:
          notebookEditorCursorAtLineBoundaryContext.set("both");
          break;
        case CursorAtLineBoundary.Start:
          notebookEditorCursorAtLineBoundaryContext.set("start");
          break;
        case CursorAtLineBoundary.End:
          notebookEditorCursorAtLineBoundaryContext.set("end");
          break;
        default:
          notebookEditorCursorAtLineBoundaryContext.set("none");
          break;
      }
      return;
    };
    this.S.add(this.onDidChangeFocus((e) => {
      if (e.elements.length) {
        const focusedElement = e.elements[0];
        cursorSelectionListener.value = focusedElement.onDidChangeState((e2) => {
          if (e2.selectionChanged) {
            recomputeContext(focusedElement);
          }
        });
        textEditorAttachListener.value = focusedElement.onDidChangeEditorAttachState(() => {
          if (focusedElement.editorAttached) {
            recomputeContext(focusedElement);
          }
        });
        recomputeContext(focusedElement);
        return;
      }
      notebookEditorCursorAtBoundaryContext.set("none");
    }));
    const updateVisibleRanges = () => {
      if (!this.o.length) {
        return;
      }
      const top2 = this.getViewScrollTop();
      const bottom = this.getViewScrollBottom();
      if (top2 >= bottom) {
        return;
      }
      const topViewIndex = $4i(this.o.indexAt(top2), 0, this.o.length - 1);
      const topElement = this.o.element(topViewIndex);
      const topModelIndex = this.ab.getCellIndex(topElement);
      const bottomViewIndex = $4i(this.o.indexAt(bottom), 0, this.o.length - 1);
      const bottomElement = this.o.element(bottomViewIndex);
      const bottomModelIndex = this.ab.getCellIndex(bottomElement);
      if (bottomModelIndex - topModelIndex === bottomViewIndex - topViewIndex) {
        this.visibleRanges = [{ start: topModelIndex, end: bottomModelIndex + 1 }];
      } else {
        this.visibleRanges = this.nb(topViewIndex, topModelIndex, bottomViewIndex, bottomModelIndex);
      }
    };
    this.S.add(this.o.onDidChangeContentHeight(() => {
      if (this.gb) {
        $jj(getWindow(container2), () => {
          updateVisibleRanges();
        });
      }
      updateVisibleRanges();
    }));
    this.S.add(this.o.onDidScroll(() => {
      if (this.gb) {
        $jj(getWindow(container2), () => {
          updateVisibleRanges();
        });
      }
      updateVisibleRanges();
    }));
  }
  D(container2, virtualDelegate, renderers, viewOptions) {
    const listView = new $uJb(container2, virtualDelegate, renderers, viewOptions);
    this.p = new $wJb(listView, this);
    return listView;
  }
  /**
   * Test Only
   */
  _getView() {
    return this.o;
  }
  attachWebview(element) {
    element.style.top = `-${$xJb}px`;
    this.rowsContainer.insertAdjacentElement("afterbegin", element);
    this.hb = new $nZ(element);
  }
  elementAt(position) {
    if (!this.o.length) {
      return void 0;
    }
    const idx = this.o.indexAt(position);
    const clamped = $4i(idx, 0, this.o.length - 1);
    return this.element(clamped);
  }
  elementHeight(element) {
    const index = this.ob(element);
    if (index === void 0 || index < 0 || index >= this.length) {
      this.ob(element);
      throw new $l1(this.ib, `Invalid index ${index}`);
    }
    return this.o.elementHeight(index);
  }
  detachViewModel() {
    this.U.clear();
    this.ab = null;
    this.cb = null;
  }
  attachViewModel(model) {
    this.ab = model;
    this.U.add(model.onDidChangeViewCells((e) => {
      if (this.fb) {
        return;
      }
      this.p.onCellsChanged(e);
      const currentRanges = this.bb.map((id2) => this.ab.getTrackedRange(id2)).filter((range) => range !== null);
      const newVisibleViewCells = getVisibleCells(this.ab.viewCells, currentRanges);
      const oldVisibleViewCells = [];
      const oldViewCellMapping = /* @__PURE__ */ new Set();
      for (let i2 = 0; i2 < this.length; i2++) {
        oldVisibleViewCells.push(this.element(i2));
        oldViewCellMapping.add(this.element(i2).uri.toString());
      }
      const viewDiffs = $mM(oldVisibleViewCells, newVisibleViewCells, (a) => {
        return oldViewCellMapping.has(a.uri.toString());
      });
      if (e.synchronous) {
        this.lb(viewDiffs);
      } else {
        this.U.add($jj(getWindow(this.rowsContainer), () => {
          if (this.fb) {
            return;
          }
          this.lb(viewDiffs);
        }));
      }
    }));
    this.U.add(model.onDidChangeSelection((e) => {
      if (e === "view") {
        return;
      }
      const viewSelections = $GL(model.getSelections()).map((index) => model.cellAt(index)).filter((cell) => !!cell).map((cell) => this.ob(cell));
      this.setSelection(viewSelections, void 0, true);
      const primary = $GL([model.getFocus()]).map((index) => model.cellAt(index)).filter((cell) => !!cell).map((cell) => this.ob(cell));
      if (primary.length) {
        this.setFocus(primary, void 0, true);
      }
    }));
    const hiddenRanges = model.getHiddenRanges();
    this.setHiddenAreas(hiddenRanges, false);
    const newRanges = $HL(hiddenRanges);
    const viewCells = model.viewCells.slice(0);
    newRanges.reverse().forEach((range) => {
      const removedCells = viewCells.splice(range.start, range.end - range.start + 1);
      this.Z.fire(removedCells);
    });
    this.splice2(0, 0, viewCells);
  }
  lb(viewDiffs) {
    viewDiffs.reverse().forEach((diff3) => {
      const hiddenOutputs = [];
      const deletedOutputs = [];
      const removedMarkdownCells = [];
      for (let i2 = diff3.start; i2 < diff3.start + diff3.deleteCount; i2++) {
        const cell = this.element(i2);
        if (cell.cellKind === CellKind.Code) {
          if (this.ab.hasCell(cell)) {
            hiddenOutputs.push(...cell?.outputsViewModels);
          } else {
            deletedOutputs.push(...cell?.outputsViewModels);
          }
        } else {
          removedMarkdownCells.push(cell);
        }
      }
      this.splice2(diff3.start, diff3.deleteCount, diff3.toInsert);
      this.Y.fire(hiddenOutputs);
      this.X.fire(deletedOutputs);
      this.Z.fire(removedMarkdownCells);
    });
  }
  clear() {
    super.splice(0, this.length);
  }
  setHiddenAreas(_ranges, triggerViewUpdate) {
    if (!this.ab) {
      return false;
    }
    const newRanges = $HL(_ranges);
    const oldRanges = this.bb.map((id2) => this.ab.getTrackedRange(id2)).filter((range) => range !== null);
    if (newRanges.length === oldRanges.length) {
      let hasDifference = false;
      for (let i2 = 0; i2 < newRanges.length; i2++) {
        if (!(newRanges[i2].start === oldRanges[i2].start && newRanges[i2].end === oldRanges[i2].end)) {
          hasDifference = true;
          break;
        }
      }
      if (!hasDifference) {
        this.mb(newRanges);
        this.p.onHiddenRangesChange();
        this.p.layout();
        return false;
      }
    }
    this.bb.forEach((id2) => this.ab.setTrackedRange(
      id2,
      null,
      3
      /* TrackedRangeStickiness.GrowsOnlyWhenTypingAfter */
    ));
    const hiddenAreaIds = newRanges.map((range) => this.ab.setTrackedRange(
      null,
      range,
      3
      /* TrackedRangeStickiness.GrowsOnlyWhenTypingAfter */
    )).filter((id2) => id2 !== null);
    this.bb = hiddenAreaIds;
    this.mb(newRanges);
    this.p.onHiddenRangesChange();
    if (triggerViewUpdate) {
      this.updateHiddenAreasInView(oldRanges, newRanges);
    }
    this.p.layout();
    return true;
  }
  mb(newRanges) {
    let start = 0;
    let index = 0;
    const ret = [];
    while (index < newRanges.length) {
      for (let j = start; j < newRanges[index].start - 1; j++) {
        ret.push(1);
      }
      ret.push(newRanges[index].end - newRanges[index].start + 1 + 1);
      start = newRanges[index].end + 1;
      index++;
    }
    for (let i2 = start; i2 < this.ab.length; i2++) {
      ret.push(1);
    }
    const values = new Uint32Array(ret.length);
    for (let i2 = 0; i2 < ret.length; i2++) {
      values[i2] = ret[i2];
    }
    this.cb = new $wM(values);
  }
  /**
   * oldRanges and newRanges are all reduced and sorted.
   */
  updateHiddenAreasInView(oldRanges, newRanges) {
    const oldViewCellEntries = getVisibleCells(this.ab.viewCells, oldRanges);
    const oldViewCellMapping = /* @__PURE__ */ new Set();
    oldViewCellEntries.forEach((cell) => {
      oldViewCellMapping.add(cell.uri.toString());
    });
    const newViewCellEntries = getVisibleCells(this.ab.viewCells, newRanges);
    const viewDiffs = $mM(oldViewCellEntries, newViewCellEntries, (a) => {
      return oldViewCellMapping.has(a.uri.toString());
    });
    this.lb(viewDiffs);
  }
  splice2(start, deleteCount, elements = []) {
    if (start < 0 || start > this.o.length) {
      return;
    }
    const focusInside = $Nj(this.rowsContainer);
    super.splice(start, deleteCount, elements);
    if (focusInside) {
      this.domFocus();
    }
    const selectionsLeft = [];
    this.getSelectedElements().forEach((el) => {
      if (this.ab.hasCell(el)) {
        selectionsLeft.push(el.handle);
      }
    });
    if (!selectionsLeft.length && this.ab.viewCells.length) {
      this.ab.updateSelectionsState({ kind: SelectionStateType.Index, focus: { start: 0, end: 1 }, selections: [{ start: 0, end: 1 }] });
    }
    this.p.layout();
  }
  getModelIndex(cell) {
    const viewIndex = this.indexOf(cell);
    return this.getModelIndex2(viewIndex);
  }
  getModelIndex2(viewIndex) {
    if (!this.cb) {
      return viewIndex;
    }
    const modelIndex = this.cb.getPrefixSum(viewIndex - 1);
    return modelIndex;
  }
  getViewIndex(cell) {
    const modelIndex = this.ab.getCellIndex(cell);
    return this.getViewIndex2(modelIndex);
  }
  getViewIndex2(modelIndex) {
    if (!this.cb) {
      return modelIndex;
    }
    const viewIndexInfo = this.cb.getIndexOf(modelIndex);
    if (viewIndexInfo.remainder !== 0) {
      if (modelIndex >= this.cb.getTotalSum()) {
        return modelIndex - (this.cb.getTotalSum() - this.cb.getCount());
      }
      return void 0;
    } else {
      return viewIndexInfo.index;
    }
  }
  convertModelIndexToViewIndex(modelIndex) {
    if (!this.cb) {
      return modelIndex;
    }
    if (modelIndex >= this.cb.getTotalSum()) {
      return Math.min(this.length, this.cb.getTotalSum());
    }
    return this.cb.getIndexOf(modelIndex).index;
  }
  modelIndexIsVisible(modelIndex) {
    if (!this.cb) {
      return true;
    }
    const viewIndexInfo = this.cb.getIndexOf(modelIndex);
    if (viewIndexInfo.remainder !== 0) {
      if (modelIndex >= this.cb.getTotalSum()) {
        return true;
      }
      return false;
    } else {
      return true;
    }
  }
  nb(topViewIndex, topModelIndex, bottomViewIndex, bottomModelIndex) {
    const stack = [];
    const ranges = [];
    let index = topViewIndex;
    let modelIndex = topModelIndex;
    while (index <= bottomViewIndex) {
      const accu = this.cb.getPrefixSum(index);
      if (accu === modelIndex + 1) {
        if (stack.length) {
          if (stack[stack.length - 1] === modelIndex - 1) {
            ranges.push({ start: stack[stack.length - 1], end: modelIndex + 1 });
          } else {
            ranges.push({ start: stack[stack.length - 1], end: stack[stack.length - 1] + 1 });
          }
        }
        stack.push(modelIndex);
        index++;
        modelIndex++;
      } else {
        if (stack.length) {
          if (stack[stack.length - 1] === modelIndex - 1) {
            ranges.push({ start: stack[stack.length - 1], end: modelIndex + 1 });
          } else {
            ranges.push({ start: stack[stack.length - 1], end: stack[stack.length - 1] + 1 });
          }
        }
        stack.push(modelIndex);
        index++;
        modelIndex = accu;
      }
    }
    if (stack.length) {
      ranges.push({ start: stack[stack.length - 1], end: stack[stack.length - 1] + 1 });
    }
    return $HL(ranges);
  }
  getVisibleRangesPlusViewportAboveAndBelow() {
    if (this.o.length <= 0) {
      return [];
    }
    const top2 = Math.max(this.getViewScrollTop() - this.renderHeight, 0);
    const topViewIndex = this.o.indexAt(top2);
    const topElement = this.o.element(topViewIndex);
    const topModelIndex = this.ab.getCellIndex(topElement);
    const bottom = $4i(this.getViewScrollBottom() + this.renderHeight, 0, this.scrollHeight);
    const bottomViewIndex = $4i(this.o.indexAt(bottom), 0, this.o.length - 1);
    const bottomElement = this.o.element(bottomViewIndex);
    const bottomModelIndex = this.ab.getCellIndex(bottomElement);
    if (bottomModelIndex - topModelIndex === bottomViewIndex - topViewIndex) {
      return [{ start: topModelIndex, end: bottomModelIndex }];
    } else {
      return this.nb(topViewIndex, topModelIndex, bottomViewIndex, bottomModelIndex);
    }
  }
  ob(cell) {
    if (!this.ab) {
      return -1;
    }
    const modelIndex = this.ab.getCellIndex(cell);
    if (modelIndex === -1) {
      return -1;
    }
    if (!this.cb) {
      return modelIndex;
    }
    const viewIndexInfo = this.cb.getIndexOf(modelIndex);
    if (viewIndexInfo.remainder !== 0) {
      if (modelIndex >= this.cb.getTotalSum()) {
        return modelIndex - (this.cb.getTotalSum() - this.cb.getCount());
      }
    }
    return viewIndexInfo.index;
  }
  pb(modelIndex) {
    if (!this.cb) {
      return modelIndex;
    }
    const viewIndexInfo = this.cb.getIndexOf(modelIndex);
    if (viewIndexInfo.remainder !== 0) {
      if (modelIndex >= this.cb.getTotalSum()) {
        return modelIndex - (this.cb.getTotalSum() - this.cb.getCount());
      }
    }
    return viewIndexInfo.index;
  }
  focusElement(cell) {
    const index = this.ob(cell);
    if (index >= 0 && this.ab) {
      const focusedElementHandle = this.element(index).handle;
      this.ab.updateSelectionsState({
        kind: SelectionStateType.Handle,
        primary: focusedElementHandle,
        selections: [focusedElementHandle]
      }, "view");
      this.setFocus([index], void 0, false);
    }
  }
  selectElements(elements) {
    const indices = elements.map((cell) => this.ob(cell)).filter((index) => index >= 0);
    this.setSelection(indices);
  }
  getCellViewScrollTop(cell) {
    const index = this.ob(cell);
    if (index === void 0 || index < 0 || index >= this.length) {
      throw new $l1(this.ib, `Invalid index ${index}`);
    }
    return this.o.elementTop(index);
  }
  getCellViewScrollBottom(cell) {
    const index = this.ob(cell);
    if (index === void 0 || index < 0 || index >= this.length) {
      throw new $l1(this.ib, `Invalid index ${index}`);
    }
    const top2 = this.o.elementTop(index);
    const height = this.o.elementHeight(index);
    return top2 + height;
  }
  setFocus(indexes, browserEvent, ignoreTextModelUpdate) {
    if (ignoreTextModelUpdate) {
      super.setFocus(indexes, browserEvent);
      return;
    }
    if (!indexes.length) {
      if (this.ab) {
        if (this.length) {
          return;
        }
        this.ab.updateSelectionsState({
          kind: SelectionStateType.Handle,
          primary: null,
          selections: []
        }, "view");
      }
    } else {
      if (this.ab) {
        const focusedElementHandle = this.element(indexes[0]).handle;
        this.ab.updateSelectionsState({
          kind: SelectionStateType.Handle,
          primary: focusedElementHandle,
          selections: this.getSelection().map((selection) => this.element(selection).handle)
        }, "view");
      }
    }
    super.setFocus(indexes, browserEvent);
  }
  setSelection(indexes, browserEvent, ignoreTextModelUpdate) {
    if (ignoreTextModelUpdate) {
      super.setSelection(indexes, browserEvent);
      return;
    }
    if (!indexes.length) {
      if (this.ab) {
        this.ab.updateSelectionsState({
          kind: SelectionStateType.Handle,
          primary: this.getFocusedElements()[0]?.handle ?? null,
          selections: []
        }, "view");
      }
    } else {
      if (this.ab) {
        this.ab.updateSelectionsState({
          kind: SelectionStateType.Handle,
          primary: this.getFocusedElements()[0]?.handle ?? null,
          selections: indexes.map((index) => this.element(index)).map((cell) => cell.handle)
        }, "view");
      }
    }
    super.setSelection(indexes, browserEvent);
  }
  /**
   * The range will be revealed with as little scrolling as possible.
   */
  revealCells(range) {
    const startIndex = this.pb(range.start);
    if (startIndex < 0) {
      return;
    }
    const endIndex = this.pb(range.end - 1);
    const scrollTop = this.getViewScrollTop();
    const wrapperBottom = this.getViewScrollBottom();
    const elementTop = this.o.elementTop(startIndex);
    if (elementTop >= scrollTop && elementTop < wrapperBottom) {
      const endElementTop = this.o.elementTop(endIndex);
      const endElementHeight = this.o.elementHeight(endIndex);
      if (endElementTop + endElementHeight <= wrapperBottom) {
        return;
      }
      if (endElementTop >= wrapperBottom) {
        return this.rb(
          endIndex,
          false,
          2
          /* CellRevealPosition.Bottom */
        );
      }
      if (endElementTop < wrapperBottom) {
        if (endElementTop + endElementHeight - wrapperBottom < elementTop - scrollTop) {
          return this.o.setScrollTop(scrollTop + endElementTop + endElementHeight - wrapperBottom);
        } else {
          return this.rb(
            startIndex,
            false,
            0
            /* CellRevealPosition.Top */
          );
        }
      }
    }
    this.qb(startIndex);
  }
  qb(viewIndex, firstLine3) {
    const firstIndex = this.o.firstMostlyVisibleIndex;
    const elementHeight = this.o.elementHeight(viewIndex);
    if (viewIndex <= firstIndex || !firstLine3 && elementHeight >= this.o.renderHeight) {
      this.rb(
        viewIndex,
        true,
        0
        /* CellRevealPosition.Top */
      );
    } else {
      this.rb(viewIndex, true, 2, firstLine3);
    }
  }
  scrollToBottom() {
    const scrollHeight = this.o.scrollHeight;
    const scrollTop = this.getViewScrollTop();
    const wrapperBottom = this.getViewScrollBottom();
    this.o.setScrollTop(scrollHeight - (wrapperBottom - scrollTop));
  }
  /**
   * Reveals the given cell in the notebook cell list. The cell will come into view syncronously
   * but the cell's editor will be attached asyncronously if it was previously out of view.
   * @returns The promise to await for the cell editor to be attached
   */
  async revealCell(cell, revealType) {
    const index = this.ob(cell);
    if (index < 0) {
      return;
    }
    switch (revealType) {
      case 2:
        this.rb(
          index,
          false,
          0
          /* CellRevealPosition.Top */
        );
        break;
      case 3:
        this.rb(
          index,
          false,
          1
          /* CellRevealPosition.Center */
        );
        break;
      case 4:
        this.rb(
          index,
          true,
          1
          /* CellRevealPosition.Center */
        );
        break;
      case 5:
        this.rb(
          index,
          true,
          3
          /* CellRevealPosition.NearTop */
        );
        break;
      case 6:
        this.qb(index, true);
        break;
      case 1:
        this.qb(index);
        break;
    }
    if (
      // wait for the editor to be created if the cell is in editing mode
      (cell.getEditState() === CellEditState.Editing || revealType === 6 && cell.cellKind === CellKind.Code) && !cell.editorAttached
    ) {
      return getEditorAttachedPromise(cell);
    }
    return;
  }
  rb(viewIndex, ignoreIfInsideViewport, revealPosition, firstLine3) {
    if (viewIndex >= this.o.length) {
      return;
    }
    const scrollTop = this.getViewScrollTop();
    const wrapperBottom = this.getViewScrollBottom();
    const elementTop = this.o.elementTop(viewIndex);
    const elementBottom = this.o.elementHeight(viewIndex) + elementTop;
    if (ignoreIfInsideViewport) {
      if (elementTop >= scrollTop && elementBottom < wrapperBottom) {
        return;
      }
    }
    switch (revealPosition) {
      case 0:
        this.o.setScrollTop(elementTop);
        this.o.setScrollTop(this.o.elementTop(viewIndex));
        break;
      case 1:
      case 3:
        {
          this.o.setScrollTop(elementTop - this.o.renderHeight / 2);
          const newElementTop = this.o.elementTop(viewIndex);
          const newElementHeight = this.o.elementHeight(viewIndex);
          const renderHeight = this.getViewScrollBottom() - this.getViewScrollTop();
          if (newElementHeight >= renderHeight) {
            this.o.setScrollTop(newElementTop);
          } else if (revealPosition === 1) {
            this.o.setScrollTop(newElementTop + newElementHeight / 2 - renderHeight / 2);
          } else if (revealPosition === 3) {
            this.o.setScrollTop(newElementTop - renderHeight / 5);
          }
        }
        break;
      case 2:
        if (firstLine3) {
          const lineHeight = this.viewModel?.layoutInfo?.fontInfo.lineHeight ?? 15;
          const padding = this.jb.getLayoutConfiguration().cellTopMargin + this.jb.getLayoutConfiguration().editorTopPadding;
          const firstLineLocation = elementTop + lineHeight + padding;
          if (firstLineLocation < wrapperBottom) {
            return;
          }
          this.o.setScrollTop(this.scrollTop + (firstLineLocation - wrapperBottom));
          break;
        }
        this.o.setScrollTop(this.scrollTop + (elementBottom - wrapperBottom));
        this.o.setScrollTop(this.scrollTop + (this.o.elementTop(viewIndex) + this.o.elementHeight(viewIndex) - this.getViewScrollBottom()));
        break;
      default:
        break;
    }
  }
  //#region Reveal Cell Editor Range asynchronously
  async revealRangeInCell(cell, range, revealType) {
    const index = this.ob(cell);
    if (index < 0) {
      return;
    }
    switch (revealType) {
      case CellRevealRangeType.Default:
        return this.sb(index, range);
      case CellRevealRangeType.Center:
        return this.tb(index, range);
      case CellRevealRangeType.CenterIfOutsideViewport:
        return this.ub(index, range);
    }
  }
  // List items have real dynamic heights, which means after we set `scrollTop` based on the `elementTop(index)`, the element at `index` might still be removed from the view once all relayouting tasks are done.
  // For example, we scroll item 10 into the view upwards, in the first round, items 7, 8, 9, 10 are all in the viewport. Then item 7 and 8 resize themselves to be larger and finally item 10 is removed from the view.
  // To ensure that item 10 is always there, we need to scroll item 10 to the top edge of the viewport.
  async sb(viewIndex, range) {
    const scrollTop = this.getViewScrollTop();
    const wrapperBottom = this.getViewScrollBottom();
    const elementTop = this.o.elementTop(viewIndex);
    const element = this.o.element(viewIndex);
    if (element.editorAttached) {
      this.vb(viewIndex, range);
    } else {
      const elementHeight = this.o.elementHeight(viewIndex);
      let alignHint = void 0;
      if (elementTop + elementHeight <= scrollTop) {
        this.o.setScrollTop(elementTop);
        alignHint = "top";
      } else if (elementTop >= wrapperBottom) {
        this.o.setScrollTop(elementTop - this.o.renderHeight / 2);
        alignHint = "bottom";
      }
      const editorAttachedPromise = new Promise((resolve, reject) => {
        element.onDidChangeEditorAttachState(() => {
          element.editorAttached ? resolve() : reject();
        });
      });
      return editorAttachedPromise.then(() => {
        this.vb(viewIndex, range, alignHint);
      });
    }
  }
  async tb(viewIndex, range) {
    const reveal = (viewIndex2, range2) => {
      const element2 = this.o.element(viewIndex2);
      const positionOffset = element2.getPositionScrollTopOffset(range2);
      const positionOffsetInView = this.o.elementTop(viewIndex2) + positionOffset;
      this.o.setScrollTop(positionOffsetInView - this.o.renderHeight / 2);
      element2.revealRangeInCenter(range2);
    };
    const elementTop = this.o.elementTop(viewIndex);
    const viewItemOffset = elementTop;
    this.o.setScrollTop(viewItemOffset - this.o.renderHeight / 2);
    const element = this.o.element(viewIndex);
    if (!element.editorAttached) {
      return getEditorAttachedPromise(element).then(() => reveal(viewIndex, range));
    } else {
      reveal(viewIndex, range);
    }
  }
  async ub(viewIndex, range) {
    const reveal = (viewIndex2, range2) => {
      const element2 = this.o.element(viewIndex2);
      const positionOffset2 = element2.getPositionScrollTopOffset(range2);
      const positionOffsetInView = this.o.elementTop(viewIndex2) + positionOffset2;
      this.o.setScrollTop(positionOffsetInView - this.o.renderHeight / 2);
      element2.revealRangeInCenter(range2);
    };
    const scrollTop = this.getViewScrollTop();
    const wrapperBottom = this.getViewScrollBottom();
    const elementTop = this.o.elementTop(viewIndex);
    const viewItemOffset = elementTop;
    const element = this.o.element(viewIndex);
    const positionOffset = viewItemOffset + element.getPositionScrollTopOffset(range);
    if (positionOffset < scrollTop || positionOffset > wrapperBottom) {
      this.o.setScrollTop(positionOffset - this.o.renderHeight / 2);
      const newPositionOffset = this.o.elementTop(viewIndex) + element.getPositionScrollTopOffset(range);
      this.o.setScrollTop(newPositionOffset - this.o.renderHeight / 2);
      if (!element.editorAttached) {
        return getEditorAttachedPromise(element).then(() => reveal(viewIndex, range));
      } else {
      }
    } else {
      if (element.editorAttached) {
        element.revealRangeInCenter(range);
      } else {
        return getEditorAttachedPromise(element).then(() => reveal(viewIndex, range));
      }
    }
  }
  vb(viewIndex, range, alignHint) {
    const element = this.o.element(viewIndex);
    const scrollTop = this.getViewScrollTop();
    const wrapperBottom = this.getViewScrollBottom();
    const positionOffset = element.getPositionScrollTopOffset(range);
    const elementOriginalHeight = this.o.elementHeight(viewIndex);
    if (positionOffset >= elementOriginalHeight) {
      const newTotalHeight = element.layoutInfo.totalHeight;
      this.updateElementHeight(viewIndex, newTotalHeight);
    }
    const elementTop = this.o.elementTop(viewIndex);
    const positionTop = elementTop + positionOffset;
    if (positionTop < scrollTop) {
      this.o.setScrollTop(positionTop - 30);
    } else if (positionTop > wrapperBottom) {
      this.o.setScrollTop(scrollTop + positionTop - wrapperBottom + 30);
    } else if (alignHint === "bottom") {
      this.o.setScrollTop(scrollTop + positionTop - wrapperBottom + 30);
    } else if (alignHint === "top") {
      this.o.setScrollTop(positionTop - 30);
    }
  }
  //#endregion
  /**
   * Reveals the specified offset of the given cell in the center of the viewport.
   * This enables revealing locations in the output as well as the input.
   */
  revealCellOffsetInCenter(cell, offset) {
    const viewIndex = this.ob(cell);
    if (viewIndex >= 0) {
      const element = this.o.element(viewIndex);
      const elementTop = this.o.elementTop(viewIndex);
      if (element instanceof $YIb) {
        return this.wb(viewIndex);
      } else {
        const rangeOffset = element.layoutInfo.outputContainerOffset + Math.min(offset, element.layoutInfo.outputTotalHeight);
        this.o.setScrollTop(elementTop - this.o.renderHeight / 2);
        this.o.setScrollTop(elementTop + rangeOffset - this.o.renderHeight / 2);
      }
    }
  }
  revealOffsetInCenterIfOutsideViewport(offset) {
    const scrollTop = this.getViewScrollTop();
    const wrapperBottom = this.getViewScrollBottom();
    if (offset < scrollTop || offset > wrapperBottom) {
      this.o.setScrollTop(offset - this.o.renderHeight / 2);
    }
  }
  wb(viewIndex) {
    this.rb(
      viewIndex,
      true,
      1
      /* CellRevealPosition.Center */
    );
  }
  domElementOfElement(element) {
    const index = this.ob(element);
    if (index >= 0 && index < this.length) {
      return this.o.domElement(index);
    }
    return null;
  }
  focusView() {
    this.o.domNode.focus();
  }
  triggerScrollFromMouseWheelEvent(browserEvent) {
    this.o.delegateScrollFromMouseWheelEvent(browserEvent);
  }
  delegateVerticalScrollbarPointerDown(browserEvent) {
    this.o.delegateVerticalScrollbarPointerDown(browserEvent);
  }
  xb(index) {
    const elementTop = this.o.elementTop(index);
    const elementBottom = elementTop + this.o.elementHeight(index);
    return elementBottom < this.scrollTop;
  }
  updateElementHeight2(element, size, anchorElementIndex = null) {
    const index = this.ob(element);
    if (index === void 0 || index < 0 || index >= this.length) {
      return;
    }
    if (this.xb(index)) {
      const oldHeight = this.elementHeight(element);
      const delta = oldHeight - size;
      if (this.hb) {
        Event2.once(this.o.onWillScroll)(() => {
          const webviewTop = parseInt(this.hb.domNode.style.top, 10);
          if (validateWebviewBoundary(this.hb.domNode)) {
            this.hb.setTop(webviewTop - delta);
          } else {
            this.hb.setTop(-$xJb);
          }
        });
      }
      this.o.updateElementHeight(index, size, anchorElementIndex);
      this.p.layout();
      return;
    }
    if (anchorElementIndex !== null) {
      this.o.updateElementHeight(index, size, anchorElementIndex);
      this.p.layout();
      return;
    }
    const focused = this.getFocus();
    const focus = focused.length ? focused[0] : null;
    if (focus) {
      const heightDelta = size - this.o.elementHeight(index);
      if (this.W.shouldAnchor(this.o, focus, heightDelta, this.element(index))) {
        this.o.updateElementHeight(index, size, focus);
        this.p.layout();
        return;
      }
    }
    this.o.updateElementHeight(index, size, null);
    this.p.layout();
    return;
  }
  changeViewZones(callback) {
    if (this.p.changeViewZones(callback)) {
      this.p.layout();
    }
  }
  // override
  domFocus() {
    const focused = this.getFocusedElements()[0];
    const focusedDomElement = focused && this.domElementOfElement(focused);
    if (this.o.domNode.ownerDocument.activeElement && focusedDomElement && focusedDomElement.contains(this.o.domNode.ownerDocument.activeElement)) {
      return;
    }
    if (!$m && this.o.domNode.ownerDocument.activeElement && !!$Gj(this.o.domNode.ownerDocument.activeElement, "context-view")) {
      return;
    }
    super.domFocus();
  }
  focusContainer(clearSelection) {
    if (clearSelection) {
      this.ab?.updateSelectionsState({
        kind: SelectionStateType.Handle,
        primary: null,
        selections: []
      }, "view");
      this.setFocus([], void 0, true);
      this.setSelection([], void 0, true);
    }
    super.domFocus();
  }
  getViewScrollTop() {
    return this.o.getScrollTop();
  }
  getViewScrollBottom() {
    return this.getViewScrollTop() + this.o.renderHeight;
  }
  setCellEditorSelection(cell, range) {
    const element = cell;
    if (element.editorAttached) {
      element.setSelection(range);
    } else {
      getEditorAttachedPromise(element).then(() => {
        element.setSelection(range);
      });
    }
  }
  style(styles) {
    const selectorSuffix = this.o.domId;
    if (!this.V) {
      this.V = $VZ(this.o.domNode);
    }
    const suffix = selectorSuffix && `.${selectorSuffix}`;
    const content = [];
    if (styles.listBackground) {
      content.push(`.monaco-list${suffix} > div.monaco-scrollable-element > .monaco-list-rows { background: ${styles.listBackground}; }`);
    }
    if (styles.listFocusBackground) {
      content.push(`.monaco-list${suffix}:focus > div.monaco-scrollable-element > .monaco-list-rows > .monaco-list-row.focused { background-color: ${styles.listFocusBackground}; }`);
      content.push(`.monaco-list${suffix}:focus > div.monaco-scrollable-element > .monaco-list-rows > .monaco-list-row.focused:hover { background-color: ${styles.listFocusBackground}; }`);
    }
    if (styles.listFocusForeground) {
      content.push(`.monaco-list${suffix}:focus > div.monaco-scrollable-element > .monaco-list-rows > .monaco-list-row.focused { color: ${styles.listFocusForeground}; }`);
    }
    if (styles.listActiveSelectionBackground) {
      content.push(`.monaco-list${suffix}:focus > div.monaco-scrollable-element > .monaco-list-rows > .monaco-list-row.selected { background-color: ${styles.listActiveSelectionBackground}; }`);
      content.push(`.monaco-list${suffix}:focus > div.monaco-scrollable-element > .monaco-list-rows > .monaco-list-row.selected:hover { background-color: ${styles.listActiveSelectionBackground}; }`);
    }
    if (styles.listActiveSelectionForeground) {
      content.push(`.monaco-list${suffix}:focus > div.monaco-scrollable-element > .monaco-list-rows > .monaco-list-row.selected { color: ${styles.listActiveSelectionForeground}; }`);
    }
    if (styles.listFocusAndSelectionBackground) {
      content.push(`
				.monaco-drag-image,
				.monaco-list${suffix}:focus > div.monaco-scrollable-element > .monaco-list-rows > .monaco-list-row.selected.focused { background-color: ${styles.listFocusAndSelectionBackground}; }
			`);
    }
    if (styles.listFocusAndSelectionForeground) {
      content.push(`
				.monaco-drag-image,
				.monaco-list${suffix}:focus > div.monaco-scrollable-element > .monaco-list-rows > .monaco-list-row.selected.focused { color: ${styles.listFocusAndSelectionForeground}; }
			`);
    }
    if (styles.listInactiveFocusBackground) {
      content.push(`.monaco-list${suffix} > div.monaco-scrollable-element > .monaco-list-rows > .monaco-list-row.focused { background-color:  ${styles.listInactiveFocusBackground}; }`);
      content.push(`.monaco-list${suffix} > div.monaco-scrollable-element > .monaco-list-rows > .monaco-list-row.focused:hover { background-color:  ${styles.listInactiveFocusBackground}; }`);
    }
    if (styles.listInactiveSelectionBackground) {
      content.push(`.monaco-list${suffix} > div.monaco-scrollable-element > .monaco-list-rows > .monaco-list-row.selected { background-color:  ${styles.listInactiveSelectionBackground}; }`);
      content.push(`.monaco-list${suffix} > div.monaco-scrollable-element > .monaco-list-rows > .monaco-list-row.selected:hover { background-color:  ${styles.listInactiveSelectionBackground}; }`);
    }
    if (styles.listInactiveSelectionForeground) {
      content.push(`.monaco-list${suffix} > div.monaco-scrollable-element > .monaco-list-rows > .monaco-list-row.selected { color: ${styles.listInactiveSelectionForeground}; }`);
    }
    if (styles.listHoverBackground) {
      content.push(`.monaco-list${suffix}:not(.drop-target) > div.monaco-scrollable-element > .monaco-list-rows > .monaco-list-row:hover:not(.selected):not(.focused) { background-color:  ${styles.listHoverBackground}; }`);
    }
    if (styles.listHoverForeground) {
      content.push(`.monaco-list${suffix} > div.monaco-scrollable-element > .monaco-list-rows > .monaco-list-row:hover:not(.selected):not(.focused) { color:  ${styles.listHoverForeground}; }`);
    }
    if (styles.listSelectionOutline) {
      content.push(`.monaco-list${suffix} > div.monaco-scrollable-element > .monaco-list-rows > .monaco-list-row.selected { outline: 1px dotted ${styles.listSelectionOutline}; outline-offset: -1px; }`);
    }
    if (styles.listFocusOutline) {
      content.push(`
				.monaco-drag-image,
				.monaco-list${suffix}:focus > div.monaco-scrollable-element > .monaco-list-rows > .monaco-list-row.focused { outline: 1px solid ${styles.listFocusOutline}; outline-offset: -1px; }
			`);
    }
    if (styles.listInactiveFocusOutline) {
      content.push(`.monaco-list${suffix} > div.monaco-scrollable-element > .monaco-list-rows > .monaco-list-row.focused { outline: 1px dotted ${styles.listInactiveFocusOutline}; outline-offset: -1px; }`);
    }
    if (styles.listHoverOutline) {
      content.push(`.monaco-list${suffix} > div.monaco-scrollable-element > .monaco-list-rows > .monaco-list-row:hover { outline: 1px dashed ${styles.listHoverOutline}; outline-offset: -1px; }`);
    }
    if (styles.listDropOverBackground) {
      content.push(`
				.monaco-list${suffix}.drop-target,
				.monaco-list${suffix} > div.monaco-scrollable-element > .monaco-list-rows.drop-target,
				.monaco-list${suffix} > div.monaco-scrollable-element > .monaco-list-row.drop-target { background-color: ${styles.listDropOverBackground} !important; color: inherit !important; }
			`);
    }
    const newStyles = content.join("\n");
    if (newStyles !== this.V.textContent) {
      this.V.textContent = newStyles;
    }
  }
  getRenderHeight() {
    return this.o.renderHeight;
  }
  getScrollHeight() {
    return this.o.scrollHeight;
  }
  layout(height, width2) {
    this.gb = true;
    super.layout(height, width2);
    if (this.renderHeight === 0) {
      this.o.domNode.style.visibility = "hidden";
    } else {
      this.o.domNode.style.visibility = "initial";
    }
    this.gb = false;
  }
  dispose() {
    this.fb = true;
    this.U.dispose();
    this.S.dispose();
    this.W.dispose();
    this.p.dispose();
    super.dispose();
    this.s = [];
    this.ab = null;
    this.bb = [];
    this.cb = null;
    this.eb = [];
  }
};
$yJb = __decorate([
  __param(7, $Deb),
  __param(8, $kl),
  __param(9, $Pk),
  __param(10, $wL)
], $yJb);
var $zJb = class extends $3c {
  constructor(list2) {
    super();
    this.list = list2;
  }
  getViewIndex(cell) {
    return this.list.getViewIndex(cell) ?? -1;
  }
  getViewHeight(cell) {
    if (!this.list.viewModel) {
      return -1;
    }
    return this.list.elementHeight(cell);
  }
  getCellRangeFromViewRange(startIndex, endIndex) {
    if (!this.list.viewModel) {
      return void 0;
    }
    const modelIndex = this.list.getModelIndex2(startIndex);
    if (modelIndex === void 0) {
      throw new Error(`startIndex ${startIndex} out of boundary`);
    }
    if (endIndex >= this.list.length) {
      const endModelIndex = this.list.viewModel.length;
      return { start: modelIndex, end: endModelIndex };
    } else {
      const endModelIndex = this.list.getModelIndex2(endIndex);
      if (endModelIndex === void 0) {
        throw new Error(`endIndex ${endIndex} out of boundary`);
      }
      return { start: modelIndex, end: endModelIndex };
    }
  }
  getCellsFromViewRange(startIndex, endIndex) {
    if (!this.list.viewModel) {
      return [];
    }
    const range = this.getCellRangeFromViewRange(startIndex, endIndex);
    if (!range) {
      return [];
    }
    return this.list.viewModel.getCellsInRange(range);
  }
  getCellsInRange(range) {
    return this.list.viewModel?.getCellsInRange(range) ?? [];
  }
  getVisibleRangesPlusViewportAboveAndBelow() {
    return this.list?.getVisibleRangesPlusViewportAboveAndBelow() ?? [];
  }
};
function getEditorAttachedPromise(element) {
  return new Promise((resolve, reject) => {
    Event2.once(element.onDidChangeEditorAttachState)(() => element.editorAttached ? resolve() : reject());
  });
}

// out-build/vs/workbench/contrib/notebook/browser/view/renderers/webviewPreloads.js
async function webviewPreloads(ctx) {
  const userAgent2 = navigator.userAgent;
  const isChrome = userAgent2.indexOf("Chrome") >= 0;
  const textEncoder2 = new TextEncoder();
  const textDecoder3 = new TextDecoder();
  function promiseWithResolvers() {
    let resolve;
    let reject;
    const promise = new Promise((res, rej) => {
      resolve = res;
      reject = rej;
    });
    return { promise, resolve, reject };
  }
  let currentOptions = ctx.options;
  const isWorkspaceTrusted = ctx.isWorkspaceTrusted;
  let currentRenderOptions = ctx.renderOptions;
  const settingChange = createEmitter();
  const acquireVsCodeApi = globalThis.acquireVsCodeApi;
  const vscode = acquireVsCodeApi();
  delete globalThis.acquireVsCodeApi;
  const tokenizationStyle = new CSSStyleSheet();
  tokenizationStyle.replaceSync(ctx.style.tokenizationCss);
  const runWhenIdle = typeof requestIdleCallback !== "function" || typeof cancelIdleCallback !== "function" ? (runner) => {
    setTimeout(() => {
      if (disposed) {
        return;
      }
      const end = Date.now() + 15;
      runner(Object.freeze({
        didTimeout: true,
        timeRemaining() {
          return Math.max(0, end - Date.now());
        }
      }));
    });
    let disposed = false;
    return {
      dispose() {
        if (disposed) {
          return;
        }
        disposed = true;
      }
    };
  } : (runner, timeout) => {
    const handle2 = requestIdleCallback(runner, typeof timeout === "number" ? { timeout } : void 0);
    let disposed = false;
    return {
      dispose() {
        if (disposed) {
          return;
        }
        disposed = true;
        cancelIdleCallback(handle2);
      }
    };
  };
  function getOutputContainer(event) {
    for (const node of event.composedPath()) {
      if (node instanceof HTMLElement && node.classList.contains("output")) {
        return {
          id: node.id
        };
      }
    }
    return;
  }
  let lastFocusedOutput = void 0;
  const handleOutputFocusOut = (event) => {
    const outputFocus = event && getOutputContainer(event);
    if (!outputFocus) {
      return;
    }
    lastFocusedOutput = void 0;
    setTimeout(() => {
      if (lastFocusedOutput?.id === outputFocus.id) {
        return;
      }
      postNotebookMessage("outputBlur", outputFocus);
    }, 0);
  };
  const isEditableElement = (element) => {
    return element.tagName.toLowerCase() === "input" || element.tagName.toLowerCase() === "textarea" || "editContext" in element;
  };
  const checkOutputInputFocus = (e) => {
    lastFocusedOutput = getOutputContainer(e);
    const activeElement = window.document.activeElement;
    if (!activeElement) {
      return;
    }
    const id2 = lastFocusedOutput?.id;
    if (id2 && (isEditableElement(activeElement) || activeElement.tagName === "SELECT")) {
      postNotebookMessage("outputInputFocus", { inputFocused: true, id: id2 });
      activeElement.addEventListener("blur", () => {
        postNotebookMessage("outputInputFocus", { inputFocused: false, id: id2 });
      }, { once: true });
    }
  };
  const handleInnerClick = (event) => {
    if (!event || !event.view || !event.view.document) {
      return;
    }
    const outputFocus = lastFocusedOutput = getOutputContainer(event);
    for (const node of event.composedPath()) {
      if (node instanceof HTMLAnchorElement && node.href) {
        if (node.href.startsWith("blob:")) {
          if (outputFocus) {
            postNotebookMessage("outputFocus", outputFocus);
          }
          handleBlobUrlClick(node.href, node.download);
        } else if (node.href.startsWith("data:")) {
          if (outputFocus) {
            postNotebookMessage("outputFocus", outputFocus);
          }
          handleDataUrl(node.href, node.download);
        } else if (node.getAttribute("href")?.trim().startsWith("#")) {
          if (!node.hash) {
            postNotebookMessage("scroll-to-reveal", { scrollTop: 0 });
            return;
          }
          const targetId = node.hash.substring(1);
          let scrollTarget = event.view.document.getElementById(targetId);
          if (!scrollTarget) {
            for (const preview of event.view.document.querySelectorAll(".preview")) {
              scrollTarget = preview.shadowRoot?.getElementById(targetId);
              if (scrollTarget) {
                break;
              }
            }
          }
          if (scrollTarget) {
            const scrollTop = scrollTarget.getBoundingClientRect().top + event.view.scrollY;
            postNotebookMessage("scroll-to-reveal", { scrollTop });
            return;
          }
        } else {
          const href = node.getAttribute("href");
          if (href) {
            if (href.startsWith("command:") && outputFocus) {
              postNotebookMessage("outputFocus", outputFocus);
            }
            postNotebookMessage("clicked-link", { href });
          }
        }
        event.preventDefault();
        event.stopPropagation();
        return;
      }
    }
    if (outputFocus) {
      postNotebookMessage("outputFocus", outputFocus);
    }
  };
  const blurOutput = () => {
    const selection = window.getSelection();
    if (!selection) {
      return;
    }
    selection.removeAllRanges();
  };
  const selectOutputContents = (cellOrOutputId) => {
    const selection = window.getSelection();
    if (!selection) {
      return;
    }
    const cellOutputContainer = window.document.getElementById(cellOrOutputId);
    if (!cellOutputContainer) {
      return;
    }
    selection.removeAllRanges();
    const range = document.createRange();
    range.selectNode(cellOutputContainer);
    selection.addRange(range);
  };
  const selectInputContents = (cellOrOutputId) => {
    const cellOutputContainer = window.document.getElementById(cellOrOutputId);
    if (!cellOutputContainer) {
      return;
    }
    const activeElement = window.document.activeElement;
    if (activeElement && isEditableElement(activeElement)) {
      activeElement.select();
    }
  };
  const onPageUpDownSelectionHandler = (e) => {
    if (!lastFocusedOutput?.id || !e.shiftKey) {
      return;
    }
    if (e.shiftKey && (e.code === "ArrowUp" || e.code === "ArrowDown")) {
      e.stopPropagation();
      return;
    }
    if (!(e.code === "PageUp" || e.code === "PageDown") && !(e.metaKey && (e.code === "ArrowDown" || e.code === "ArrowUp"))) {
      return;
    }
    const outputContainer = window.document.getElementById(lastFocusedOutput.id);
    const selection = window.getSelection();
    if (!outputContainer || !selection?.anchorNode) {
      return;
    }
    const activeElement = window.document.activeElement;
    if (activeElement && isEditableElement(activeElement)) {
      return;
    }
    e.stopPropagation();
    e.preventDefault();
    const { anchorNode, anchorOffset } = selection;
    const range = document.createRange();
    if (e.code === "PageDown" || e.code === "ArrowDown") {
      range.setStart(anchorNode, anchorOffset);
      range.setEnd(outputContainer, 1);
    } else {
      range.setStart(outputContainer, 0);
      range.setEnd(anchorNode, anchorOffset);
    }
    selection.removeAllRanges();
    selection.addRange(range);
  };
  const disableNativeSelectAll = (e) => {
    if (!lastFocusedOutput?.id) {
      return;
    }
    const activeElement = window.document.activeElement;
    if (activeElement && isEditableElement(activeElement)) {
      return;
    }
    if (e.key === "a" && e.ctrlKey || e.metaKey && e.key === "a") {
      e.preventDefault();
      return;
    }
  };
  const handleDataUrl = async (data, downloadName) => {
    postNotebookMessage("clicked-data-url", {
      data,
      downloadName
    });
  };
  const handleBlobUrlClick = async (url, downloadName) => {
    try {
      const response = await fetch(url);
      const blob = await response.blob();
      const reader = new FileReader();
      reader.addEventListener("load", () => {
        handleDataUrl(reader.result, downloadName);
      });
      reader.readAsDataURL(blob);
    } catch (e) {
      console.error(e.message);
    }
  };
  window.document.body.addEventListener("click", handleInnerClick);
  window.document.body.addEventListener("focusin", checkOutputInputFocus);
  window.document.body.addEventListener("focusout", handleOutputFocusOut);
  window.document.body.addEventListener("keydown", onPageUpDownSelectionHandler);
  window.document.body.addEventListener("keydown", disableNativeSelectAll);
  function createKernelContext() {
    return Object.freeze({
      onDidReceiveKernelMessage: onDidReceiveKernelMessage.event,
      postKernelMessage: (data) => postNotebookMessage("customKernelMessage", { message: data })
    });
  }
  async function runKernelPreload(url) {
    try {
      return await activateModuleKernelPreload(url);
    } catch (e) {
      console.error(e);
      throw e;
    }
  }
  async function activateModuleKernelPreload(url) {
    const module2 = await __import(url);
    if (!module2.activate) {
      console.error(`Notebook preload '${url}' was expected to be a module but it does not export an 'activate' function`);
      return;
    }
    return module2.activate(createKernelContext());
  }
  const dimensionUpdater = new class {
    constructor() {
      this.c = /* @__PURE__ */ new Map();
    }
    updateHeight(id2, height, options3) {
      if (!this.c.size) {
        setTimeout(() => {
          this.updateImmediately();
        }, 0);
      }
      const update = this.c.get(id2);
      if (update && update.isOutput) {
        this.c.set(id2, {
          id: id2,
          height,
          init: update.init,
          isOutput: update.isOutput
        });
      } else {
        this.c.set(id2, {
          id: id2,
          height,
          ...options3
        });
      }
    }
    updateImmediately() {
      if (!this.c.size) {
        return;
      }
      postNotebookMessage("dimension", {
        updates: Array.from(this.c.values())
      });
      this.c.clear();
    }
  }();
  function elementHasContent(height) {
    return height > 2.1;
  }
  const resizeObserver = new class {
    constructor() {
      this.f = /* @__PURE__ */ new WeakMap();
      this.c = new ResizeObserver((entries2) => {
        for (const entry of entries2) {
          if (!window.document.body.contains(entry.target)) {
            continue;
          }
          const observedElementInfo = this.f.get(entry.target);
          if (!observedElementInfo) {
            continue;
          }
          this.j(observedElementInfo.cellId);
          if (entry.target.id !== observedElementInfo.id) {
            continue;
          }
          if (!entry.contentRect) {
            continue;
          }
          if (!observedElementInfo.output) {
            this.h(observedElementInfo, entry.target.offsetHeight);
            continue;
          }
          const hasContent = elementHasContent(entry.contentRect.height);
          const shouldUpdatePadding = hasContent && observedElementInfo.lastKnownPadding === 0 || !hasContent && observedElementInfo.lastKnownPadding !== 0;
          if (shouldUpdatePadding) {
            window.requestAnimationFrame(() => {
              if (hasContent) {
                entry.target.style.padding = `${ctx.style.outputNodePadding}px ${ctx.style.outputNodePadding}px ${ctx.style.outputNodePadding}px ${ctx.style.outputNodeLeftPadding}px`;
              } else {
                entry.target.style.padding = `0px`;
              }
              this.h(observedElementInfo, hasContent ? entry.target.offsetHeight : 0);
            });
          } else {
            this.h(observedElementInfo, hasContent ? entry.target.offsetHeight : 0);
          }
        }
      });
    }
    h(observedElementInfo, offsetHeight) {
      if (observedElementInfo.lastKnownHeight !== offsetHeight) {
        observedElementInfo.lastKnownHeight = offsetHeight;
        dimensionUpdater.updateHeight(observedElementInfo.id, offsetHeight, {
          isOutput: observedElementInfo.output
        });
      }
    }
    observe(container2, id2, output, cellId) {
      if (this.f.has(container2)) {
        return;
      }
      this.f.set(container2, { id: id2, output, lastKnownPadding: ctx.style.outputNodePadding, lastKnownHeight: -1, cellId });
      this.c.observe(container2);
    }
    j(cellId) {
      clearTimeout(this.g);
      this.g = setTimeout(() => {
        postNotebookMessage("outputResized", {
          cellId
        });
      }, 250);
    }
  }();
  let previousDelta;
  let scrollTimeout;
  let scrolledElement;
  let lastTimeScrolled;
  function flagRecentlyScrolled(node, deltaY) {
    scrolledElement = node;
    if (deltaY === void 0) {
      lastTimeScrolled = Date.now();
      previousDelta = void 0;
      node.setAttribute("recentlyScrolled", "true");
      clearTimeout(scrollTimeout);
      scrollTimeout = setTimeout(() => {
        scrolledElement?.removeAttribute("recentlyScrolled");
      }, 300);
      return true;
    }
    if (node.hasAttribute("recentlyScrolled")) {
      if (lastTimeScrolled && Date.now() - lastTimeScrolled > 400) {
        if (!!previousDelta && deltaY < 0 && deltaY < previousDelta - 8) {
          clearTimeout(scrollTimeout);
          scrolledElement?.removeAttribute("recentlyScrolled");
          return false;
        } else if (!!previousDelta && deltaY > 0 && deltaY > previousDelta + 8) {
          clearTimeout(scrollTimeout);
          scrolledElement?.removeAttribute("recentlyScrolled");
          return false;
        }
        clearTimeout(scrollTimeout);
        scrollTimeout = setTimeout(() => {
          scrolledElement?.removeAttribute("recentlyScrolled");
        }, 50);
      } else {
        clearTimeout(scrollTimeout);
        scrollTimeout = setTimeout(() => {
          scrolledElement?.removeAttribute("recentlyScrolled");
        }, 300);
      }
      previousDelta = deltaY;
      return true;
    }
    return false;
  }
  function eventTargetShouldHandleScroll(event) {
    for (let node = event.target; node; node = node.parentNode) {
      if (!(node instanceof Element) || node.id === "container" || node.classList.contains("cell_container") || node.classList.contains("markup") || node.classList.contains("output_container")) {
        return false;
      }
      if (event.deltaY < 0 && node.scrollTop > 0) {
        flagRecentlyScrolled(node);
        return true;
      }
      if (event.deltaY > 0 && node.scrollTop + node.clientHeight < node.scrollHeight) {
        if (node.scrollHeight - node.scrollTop - node.clientHeight < 2) {
          continue;
        }
        if (window.getComputedStyle(node).overflowY === "hidden" || window.getComputedStyle(node).overflowY === "visible") {
          continue;
        }
        flagRecentlyScrolled(node);
        return true;
      }
      if (flagRecentlyScrolled(node, event.deltaY)) {
        return true;
      }
    }
    return false;
  }
  const handleWheel = (event) => {
    if (event.defaultPrevented || eventTargetShouldHandleScroll(event)) {
      return;
    }
    postNotebookMessage("did-scroll-wheel", {
      payload: {
        deltaMode: event.deltaMode,
        deltaX: event.deltaX,
        deltaY: event.deltaY,
        deltaZ: event.deltaZ,
        // Refs https://github.com/microsoft/vscode/issues/146403#issuecomment-1854538928
        wheelDelta: event.wheelDelta && isChrome ? event.wheelDelta / window.devicePixelRatio : event.wheelDelta,
        wheelDeltaX: event.wheelDeltaX && isChrome ? event.wheelDeltaX / window.devicePixelRatio : event.wheelDeltaX,
        wheelDeltaY: event.wheelDeltaY && isChrome ? event.wheelDeltaY / window.devicePixelRatio : event.wheelDeltaY,
        detail: event.detail,
        shiftKey: event.shiftKey,
        type: event.type
      }
    });
  };
  function focusFirstFocusableOrContainerInOutput(cellOrOutputId, alternateId) {
    const cellOutputContainer = window.document.getElementById(cellOrOutputId) ?? (alternateId ? window.document.getElementById(alternateId) : void 0);
    if (cellOutputContainer) {
      if (cellOutputContainer.contains(window.document.activeElement)) {
        return;
      }
      const id2 = cellOutputContainer.id;
      let focusableElement = cellOutputContainer.querySelector('[tabindex="0"], [href], button, input, option, select, textarea');
      if (!focusableElement) {
        focusableElement = cellOutputContainer;
        focusableElement.tabIndex = -1;
        postNotebookMessage("outputInputFocus", { inputFocused: false, id: id2 });
      } else {
        const inputFocused = isEditableElement(focusableElement);
        postNotebookMessage("outputInputFocus", { inputFocused, id: id2 });
      }
      lastFocusedOutput = cellOutputContainer;
      postNotebookMessage("outputFocus", { id: cellOutputContainer.id });
      focusableElement.focus();
    }
  }
  function createFocusSink(cellId, focusNext) {
    const element = document.createElement("div");
    element.id = `focus-sink-${cellId}`;
    element.tabIndex = 0;
    element.addEventListener("focus", () => {
      postNotebookMessage("focus-editor", {
        cellId,
        focusNext
      });
    });
    return element;
  }
  function _internalHighlightRange(range, tagName = "mark", attributes = {}) {
    function _textNodesInRange(range2) {
      if (!range2.startContainer.ownerDocument) {
        return [];
      }
      if (range2.startContainer.nodeType === Node.TEXT_NODE && range2.startOffset > 0) {
        const startContainer = range2.startContainer;
        const endOffset = range2.endOffset;
        const createdNode = startContainer.splitText(range2.startOffset);
        if (range2.endContainer === startContainer) {
          range2.setEnd(createdNode, endOffset - range2.startOffset);
        }
        range2.setStart(createdNode, 0);
      }
      if (range2.endContainer.nodeType === Node.TEXT_NODE && range2.endOffset < range2.endContainer.length) {
        range2.endContainer.splitText(range2.endOffset);
      }
      const walker = range2.startContainer.ownerDocument.createTreeWalker(range2.commonAncestorContainer, NodeFilter.SHOW_TEXT, (node) => range2.intersectsNode(node) ? NodeFilter.FILTER_ACCEPT : NodeFilter.FILTER_REJECT);
      walker.currentNode = range2.startContainer;
      const nodes2 = [];
      if (walker.currentNode.nodeType === Node.TEXT_NODE) {
        nodes2.push(walker.currentNode);
      }
      while (walker.nextNode() && range2.comparePoint(walker.currentNode, 0) !== 1) {
        if (walker.currentNode.nodeType === Node.TEXT_NODE) {
          nodes2.push(walker.currentNode);
        }
      }
      return nodes2;
    }
    function wrapNodeInHighlight(node, tagName2, attributes2) {
      const highlightElement = node.ownerDocument.createElement(tagName2);
      Object.keys(attributes2).forEach((key2) => {
        highlightElement.setAttribute(key2, attributes2[key2]);
      });
      const tempRange = node.ownerDocument.createRange();
      tempRange.selectNode(node);
      tempRange.surroundContents(highlightElement);
      return highlightElement;
    }
    if (range.collapsed) {
      return {
        remove: () => {
        },
        update: () => {
        }
      };
    }
    const nodes = _textNodesInRange(range);
    const highlightElements = [];
    for (const nodeIdx in nodes) {
      const highlightElement = wrapNodeInHighlight(nodes[nodeIdx], tagName, attributes);
      highlightElements.push(highlightElement);
    }
    function _removeHighlight(highlightElement) {
      if (highlightElement.childNodes.length === 1) {
        highlightElement.parentNode?.replaceChild(highlightElement.firstChild, highlightElement);
      } else {
        while (highlightElement.firstChild) {
          highlightElement.parentNode?.insertBefore(highlightElement.firstChild, highlightElement);
        }
        highlightElement.remove();
      }
    }
    function _removeHighlights() {
      for (const highlightIdx in highlightElements) {
        _removeHighlight(highlightElements[highlightIdx]);
      }
    }
    function _updateHighlight(highlightElement, attributes2 = {}) {
      Object.keys(attributes2).forEach((key2) => {
        highlightElement.setAttribute(key2, attributes2[key2]);
      });
    }
    function updateHighlights(attributes2) {
      for (const highlightIdx in highlightElements) {
        _updateHighlight(highlightElements[highlightIdx], attributes2);
      }
    }
    return {
      remove: _removeHighlights,
      update: updateHighlights
    };
  }
  function selectRange(_range) {
    const sel = window.getSelection();
    if (sel) {
      try {
        sel.removeAllRanges();
        const r2 = document.createRange();
        r2.setStart(_range.startContainer, _range.startOffset);
        r2.setEnd(_range.endContainer, _range.endOffset);
        sel.addRange(r2);
      } catch (e) {
        console.log(e);
      }
    }
  }
  function highlightRange2(range, useCustom, tagName = "mark", attributes = {}) {
    if (useCustom) {
      const ret = _internalHighlightRange(range, tagName, attributes);
      return {
        range,
        dispose: ret.remove,
        update: (color2, className) => {
          if (className === void 0) {
            ret.update({
              "style": `background-color: ${color2}`
            });
          } else {
            ret.update({
              "class": className
            });
          }
        }
      };
    } else {
      window.document.execCommand("hiliteColor", false, matchColor);
      const cloneRange = window.getSelection().getRangeAt(0).cloneRange();
      const _range = {
        collapsed: cloneRange.collapsed,
        commonAncestorContainer: cloneRange.commonAncestorContainer,
        endContainer: cloneRange.endContainer,
        endOffset: cloneRange.endOffset,
        startContainer: cloneRange.startContainer,
        startOffset: cloneRange.startOffset
      };
      return {
        range: _range,
        dispose: () => {
          selectRange(_range);
          try {
            document.designMode = "On";
            window.document.execCommand("removeFormat", false, void 0);
            document.designMode = "Off";
            window.getSelection()?.removeAllRanges();
          } catch (e) {
            console.log(e);
          }
        },
        update: (color2, className) => {
          selectRange(_range);
          try {
            document.designMode = "On";
            window.document.execCommand("removeFormat", false, void 0);
            window.document.execCommand("hiliteColor", false, color2);
            document.designMode = "Off";
            window.getSelection()?.removeAllRanges();
          } catch (e) {
            console.log(e);
          }
        }
      };
    }
  }
  function createEmitter(listenerChange = () => void 0) {
    const listeners = /* @__PURE__ */ new Set();
    return {
      fire(data) {
        for (const listener of [...listeners]) {
          listener.fn.call(listener.thisArg, data);
        }
      },
      event(fn, thisArg, disposables) {
        const listenerObj = { fn, thisArg };
        const disposable = {
          dispose: () => {
            listeners.delete(listenerObj);
            listenerChange(listeners);
          }
        };
        listeners.add(listenerObj);
        listenerChange(listeners);
        if (disposables instanceof Array) {
          disposables.push(disposable);
        } else if (disposables) {
          disposables.add(disposable);
        }
        return disposable;
      }
    };
  }
  function showRenderError(errorText, outputNode, errors) {
    outputNode.innerText = errorText;
    const errList = document.createElement("ul");
    for (const result of errors) {
      console.error(result);
      const item = document.createElement("li");
      item.innerText = result.message;
      errList.appendChild(item);
    }
    outputNode.appendChild(errList);
  }
  const outputItemRequests = new class {
    constructor() {
      this.c = 0;
      this.f = /* @__PURE__ */ new Map();
    }
    getOutputItem(outputId, mime) {
      const requestId = this.c++;
      const { promise, resolve } = promiseWithResolvers();
      this.f.set(requestId, { resolve });
      postNotebookMessage("getOutputItem", { requestId, outputId, mime });
      return promise;
    }
    resolveOutputItem(requestId, output) {
      const request = this.f.get(requestId);
      if (!request) {
        return;
      }
      this.f.delete(requestId);
      request.resolve(output);
    }
  }();
  let hasWarnedAboutAllOutputItemsProposal = false;
  function createOutputItem(id2, mime, metadata, valueBytes, allOutputItemData, appended) {
    function create2(id3, mime2, metadata2, valueBytes2, appended2) {
      return Object.freeze({
        id: id3,
        mime: mime2,
        metadata: metadata2,
        appendedText() {
          if (appended2) {
            return textDecoder3.decode(appended2.valueBytes);
          }
          return void 0;
        },
        data() {
          return valueBytes2;
        },
        text() {
          return textDecoder3.decode(valueBytes2);
        },
        json() {
          return JSON.parse(this.text());
        },
        blob() {
          return new Blob([valueBytes2], { type: this.mime });
        },
        get _allOutputItems() {
          if (!hasWarnedAboutAllOutputItemsProposal) {
            hasWarnedAboutAllOutputItemsProposal = true;
            console.warn(`'_allOutputItems' is proposed API. DO NOT ship an extension that depends on it!`);
          }
          return allOutputItemList;
        }
      });
    }
    const allOutputItemCache = /* @__PURE__ */ new Map();
    const allOutputItemList = Object.freeze(allOutputItemData.map((outputItem) => {
      const mime2 = outputItem.mime;
      return Object.freeze({
        mime: mime2,
        getItem() {
          const existingTask = allOutputItemCache.get(mime2);
          if (existingTask) {
            return existingTask;
          }
          const task = outputItemRequests.getOutputItem(id2, mime2).then((item2) => {
            return item2 ? create2(id2, item2.mime, metadata, item2.valueBytes) : void 0;
          });
          allOutputItemCache.set(mime2, task);
          return task;
        }
      });
    }));
    const item = create2(id2, mime, metadata, valueBytes, appended);
    allOutputItemCache.set(mime, Promise.resolve(item));
    return item;
  }
  const onDidReceiveKernelMessage = createEmitter();
  const ttPolicy5 = window.trustedTypes?.createPolicy("notebookRenderer", {
    createHTML: (value) => value,
    // CodeQL [SM03712] The rendered content is provided by renderer extensions, which are responsible for sanitizing their content themselves. The notebook webview is also sandboxed.
    createScript: (value) => value
    // CodeQL [SM03712] The rendered content is provided by renderer extensions, which are responsible for sanitizing their content themselves. The notebook webview is also sandboxed.
  });
  window.addEventListener("wheel", handleWheel);
  const matchColor = window.getComputedStyle(window.document.getElementById("_defaultColorPalatte")).color;
  const currentMatchColor = window.getComputedStyle(window.document.getElementById("_defaultColorPalatte")).backgroundColor;
  class JSHighlighter {
    constructor() {
      this.c = /* @__PURE__ */ new Map();
    }
    addHighlights(matches, ownerID) {
      for (let i2 = matches.length - 1; i2 >= 0; i2--) {
        const match = matches[i2];
        const ret = highlightRange2(match.originalRange, true, "mark", match.isShadow ? {
          "style": "background-color: " + matchColor + ";"
        } : {
          "class": "find-match"
        });
        match.highlightResult = ret;
      }
      const highlightInfo = {
        matches,
        currentMatchIndex: -1
      };
      this.c.set(ownerID, highlightInfo);
    }
    removeHighlights(ownerID) {
      this.c.get(ownerID)?.matches.forEach((match) => {
        match.highlightResult?.dispose();
      });
      this.c.delete(ownerID);
    }
    highlightCurrentMatch(index, ownerID) {
      const highlightInfo = this.c.get(ownerID);
      if (!highlightInfo) {
        console.error("Modified current highlight match before adding highlight list.");
        return;
      }
      const oldMatch = highlightInfo.matches[highlightInfo.currentMatchIndex];
      oldMatch?.highlightResult?.update(matchColor, oldMatch.isShadow ? void 0 : "find-match");
      const match = highlightInfo.matches[index];
      highlightInfo.currentMatchIndex = index;
      const sel = window.getSelection();
      if (!!match && !!sel && match.highlightResult) {
        let offset = 0;
        try {
          const outputOffset = window.document.getElementById(match.id).getBoundingClientRect().top;
          const tempRange = document.createRange();
          tempRange.selectNode(match.highlightResult.range.startContainer);
          match.highlightResult.range.startContainer.parentElement?.scrollIntoView({ behavior: "auto", block: "end", inline: "nearest" });
          const rangeOffset = tempRange.getBoundingClientRect().top;
          tempRange.detach();
          offset = rangeOffset - outputOffset;
        } catch (e) {
          console.error(e);
        }
        match.highlightResult?.update(currentMatchColor, match.isShadow ? void 0 : "current-find-match");
        window.document.getSelection()?.removeAllRanges();
        postNotebookMessage("didFindHighlightCurrent", {
          offset
        });
      }
    }
    unHighlightCurrentMatch(index, ownerID) {
      const highlightInfo = this.c.get(ownerID);
      if (!highlightInfo) {
        return;
      }
      const oldMatch = highlightInfo.matches[index];
      if (oldMatch && oldMatch.highlightResult) {
        oldMatch.highlightResult.update(matchColor, oldMatch.isShadow ? void 0 : "find-match");
      }
    }
    dispose() {
      window.document.getSelection()?.removeAllRanges();
      this.c.forEach((highlightInfo) => {
        highlightInfo.matches.forEach((match) => {
          match.highlightResult?.dispose();
        });
      });
    }
  }
  class CSSHighlighter {
    constructor() {
      this.c = /* @__PURE__ */ new Map();
      this.f = new Highlight();
      this.f.priority = 1;
      this.g = new Highlight();
      this.g.priority = 2;
      CSS.highlights?.set(`find-highlight`, this.f);
      CSS.highlights?.set(`current-find-highlight`, this.g);
    }
    _refreshRegistry(updateMatchesHighlight = true) {
      if (updateMatchesHighlight) {
        this.f.clear();
      }
      this.g.clear();
      this.c.forEach((highlightInfo) => {
        if (updateMatchesHighlight) {
          for (let i2 = 0; i2 < highlightInfo.matches.length; i2++) {
            this.f.add(highlightInfo.matches[i2].originalRange);
          }
        }
        if (highlightInfo.currentMatchIndex < highlightInfo.matches.length && highlightInfo.currentMatchIndex >= 0) {
          this.g.add(highlightInfo.matches[highlightInfo.currentMatchIndex].originalRange);
        }
      });
    }
    addHighlights(matches, ownerID) {
      for (let i2 = 0; i2 < matches.length; i2++) {
        this.f.add(matches[i2].originalRange);
      }
      const newEntry = {
        matches,
        currentMatchIndex: -1
      };
      this.c.set(ownerID, newEntry);
    }
    highlightCurrentMatch(index, ownerID) {
      const highlightInfo = this.c.get(ownerID);
      if (!highlightInfo) {
        console.error("Modified current highlight match before adding highlight list.");
        return;
      }
      highlightInfo.currentMatchIndex = index;
      const match = highlightInfo.matches[index];
      if (match) {
        let offset = 0;
        try {
          const outputOffset = window.document.getElementById(match.id).getBoundingClientRect().top;
          match.originalRange.startContainer.parentElement?.scrollIntoView({ behavior: "auto", block: "end", inline: "nearest" });
          const rangeOffset = match.originalRange.getBoundingClientRect().top;
          offset = rangeOffset - outputOffset;
          postNotebookMessage("didFindHighlightCurrent", {
            offset
          });
        } catch (e) {
          console.error(e);
        }
      }
      this._refreshRegistry(false);
    }
    unHighlightCurrentMatch(index, ownerID) {
      const highlightInfo = this.c.get(ownerID);
      if (!highlightInfo) {
        return;
      }
      highlightInfo.currentMatchIndex = -1;
    }
    removeHighlights(ownerID) {
      this.c.delete(ownerID);
      this._refreshRegistry();
    }
    dispose() {
      window.document.getSelection()?.removeAllRanges();
      this.g.clear();
      this.f.clear();
    }
  }
  const _highlighter = CSS.highlights ? new CSSHighlighter() : new JSHighlighter();
  function extractSelectionLine(selection) {
    const range = selection.getRangeAt(0);
    const oldRange = range.cloneRange();
    const captureLength = selection.toString().length;
    selection.collapseToStart();
    selection.modify("move", "backward", "lineboundary");
    selection.modify("extend", "forward", "lineboundary");
    const line = selection.toString();
    const rangeStart = getStartOffset(selection.getRangeAt(0), oldRange);
    const lineRange = {
      start: rangeStart,
      end: rangeStart + captureLength
    };
    selection.removeAllRanges();
    selection.addRange(oldRange);
    return { line, range: lineRange };
  }
  function getStartOffset(lineRange, originalRange) {
    const firstCommonAncestor = findFirstCommonAncestor(lineRange.startContainer, originalRange.startContainer);
    const selectionOffset = getSelectionOffsetRelativeTo(firstCommonAncestor, lineRange.startContainer) + lineRange.startOffset;
    const textOffset = getSelectionOffsetRelativeTo(firstCommonAncestor, originalRange.startContainer) + originalRange.startOffset;
    return textOffset - selectionOffset;
  }
  function findFirstCommonAncestor(nodeA, nodeB) {
    const range = new Range();
    range.setStart(nodeA, 0);
    range.setEnd(nodeB, 0);
    return range.commonAncestorContainer;
  }
  function getTextContentLength(node) {
    let length = 0;
    if (node.nodeType === Node.TEXT_NODE) {
      length += node.textContent?.length || 0;
    } else {
      for (const childNode of node.childNodes) {
        length += getTextContentLength(childNode);
      }
    }
    return length;
  }
  function getSelectionOffsetRelativeTo(parentElement, currentNode) {
    if (!currentNode) {
      return 0;
    }
    let offset = 0;
    if (currentNode === parentElement || !parentElement.contains(currentNode)) {
      return offset;
    }
    let prevSibling = currentNode.previousSibling;
    while (prevSibling) {
      offset += getTextContentLength(prevSibling);
      prevSibling = prevSibling.previousSibling;
    }
    return offset + getSelectionOffsetRelativeTo(parentElement, currentNode.parentNode);
  }
  const find2 = (query, options3) => {
    let find3 = true;
    let matches = [];
    const range = document.createRange();
    range.selectNodeContents(window.document.getElementById("findStart"));
    const sel = window.getSelection();
    sel?.removeAllRanges();
    sel?.addRange(range);
    viewModel.toggleDragDropEnabled(false);
    try {
      document.designMode = "On";
      while (find3 && matches.length < 500) {
        find3 = window.find(
          query,
          /* caseSensitive*/
          !!options3.caseSensitive,
          /* backwards*/
          false,
          /* wrapAround*/
          false,
          /* wholeWord */
          !!options3.wholeWord,
          /* searchInFrames*/
          true,
          false
        );
        if (find3) {
          const selection = window.getSelection();
          if (!selection) {
            console.log("no selection");
            break;
          }
          if (options3.includeMarkup && selection.rangeCount > 0 && selection.getRangeAt(0).startContainer.nodeType === 1 && selection.getRangeAt(0).startContainer.classList.contains("markup")) {
            const preview = selection.anchorNode?.firstChild;
            const root = preview.shadowRoot;
            const shadowSelection = root?.getSelection ? root?.getSelection() : null;
            if (shadowSelection && shadowSelection.anchorNode) {
              matches.push({
                type: "preview",
                id: preview.id,
                cellId: preview.id,
                container: preview,
                isShadow: true,
                originalRange: shadowSelection.getRangeAt(0),
                searchPreviewInfo: options3.shouldGetSearchPreviewInfo ? extractSelectionLine(shadowSelection) : void 0
              });
            }
          }
          if (options3.includeOutput && selection.rangeCount > 0 && selection.getRangeAt(0).startContainer.nodeType === 1 && selection.getRangeAt(0).startContainer.classList.contains("output_container")) {
            const cellId = selection.getRangeAt(0).startContainer.parentElement.id;
            const outputNode = selection.anchorNode?.firstChild;
            const root = outputNode.shadowRoot;
            const shadowSelection = root?.getSelection ? root?.getSelection() : null;
            if (shadowSelection && shadowSelection.anchorNode) {
              matches.push({
                type: "output",
                id: outputNode.id,
                cellId,
                container: outputNode,
                isShadow: true,
                originalRange: shadowSelection.getRangeAt(0),
                searchPreviewInfo: options3.shouldGetSearchPreviewInfo ? extractSelectionLine(shadowSelection) : void 0
              });
            }
          }
          const anchorNode = selection.anchorNode?.parentElement;
          if (anchorNode) {
            const lastEl = matches.length ? matches[matches.length - 1] : null;
            if (lastEl && lastEl.container.contains(anchorNode) && options3.includeOutput) {
              matches.push({
                type: lastEl.type,
                id: lastEl.id,
                cellId: lastEl.cellId,
                container: lastEl.container,
                isShadow: false,
                originalRange: selection.getRangeAt(0),
                searchPreviewInfo: options3.shouldGetSearchPreviewInfo ? extractSelectionLine(selection) : void 0
              });
            } else {
              for (let node = anchorNode; node; node = node.parentElement) {
                if (!(node instanceof Element)) {
                  break;
                }
                if (node.classList.contains("output") && options3.includeOutput) {
                  const cellId = node.parentElement?.parentElement?.id;
                  if (cellId) {
                    matches.push({
                      type: "output",
                      id: node.id,
                      cellId,
                      container: node,
                      isShadow: false,
                      originalRange: selection.getRangeAt(0),
                      searchPreviewInfo: options3.shouldGetSearchPreviewInfo ? extractSelectionLine(selection) : void 0
                    });
                  }
                  break;
                }
                if (node.id === "container" || node === window.document.body) {
                  break;
                }
              }
            }
          } else {
            break;
          }
        }
      }
    } catch (e) {
      console.log(e);
    }
    matches = matches.filter((match) => options3.findIds.length ? options3.findIds.includes(match.cellId) : true);
    _highlighter.addHighlights(matches, options3.ownerID);
    window.document.getSelection()?.removeAllRanges();
    viewModel.toggleDragDropEnabled(currentOptions.dragAndDropEnabled);
    document.designMode = "Off";
    postNotebookMessage("didFind", {
      matches: matches.map((match, index) => ({
        type: match.type,
        id: match.id,
        cellId: match.cellId,
        index,
        searchPreviewInfo: match.searchPreviewInfo
      }))
    });
  };
  const copyOutputImage = async (outputId, altOutputId, retries = 5) => {
    if (!window.document.hasFocus() && retries > 0) {
      setTimeout(() => {
        copyOutputImage(outputId, altOutputId, retries - 1);
      }, 50);
      return;
    }
    try {
      const outputElement = window.document.getElementById(outputId) ?? window.document.getElementById(altOutputId);
      let image = outputElement?.querySelector("img");
      if (!image) {
        const svgImage = outputElement?.querySelector("svg.output-image") ?? outputElement?.querySelector("div.svgContainerStyle > svg");
        if (svgImage) {
          image = new Image();
          image.src = "data:image/svg+xml," + encodeURIComponent(svgImage.outerHTML);
        }
      }
      if (image) {
        const imageToCopy = image;
        await navigator.clipboard.write([new ClipboardItem({
          "image/png": new Promise((resolve) => {
            const canvas = document.createElement("canvas");
            canvas.width = imageToCopy.naturalWidth;
            canvas.height = imageToCopy.naturalHeight;
            const context = canvas.getContext("2d");
            context.drawImage(imageToCopy, 0, 0);
            canvas.toBlob((blob) => {
              if (blob) {
                resolve(blob);
              } else {
                console.error("No blob data to write to clipboard");
              }
              canvas.remove();
            }, "image/png");
          })
        })]);
      } else {
        console.error("Could not find image element to copy for output with id", outputId);
      }
    } catch (e) {
      console.error("Could not copy image:", e);
    }
  };
  window.addEventListener("message", async (rawEvent) => {
    const event = rawEvent;
    switch (event.data.type) {
      case "initializeMarkup": {
        try {
          await Promise.all(event.data.cells.map((info) => viewModel.ensureMarkupCell(info)));
        } finally {
          dimensionUpdater.updateImmediately();
          postNotebookMessage("initializedMarkup", { requestId: event.data.requestId });
        }
        break;
      }
      case "createMarkupCell":
        viewModel.ensureMarkupCell(event.data.cell);
        break;
      case "showMarkupCell":
        viewModel.showMarkupCell(event.data.id, event.data.top, event.data.content, event.data.metadata);
        break;
      case "hideMarkupCells":
        for (const id2 of event.data.ids) {
          viewModel.hideMarkupCell(id2);
        }
        break;
      case "unhideMarkupCells":
        for (const id2 of event.data.ids) {
          viewModel.unhideMarkupCell(id2);
        }
        break;
      case "deleteMarkupCell":
        for (const id2 of event.data.ids) {
          viewModel.deleteMarkupCell(id2);
        }
        break;
      case "updateSelectedMarkupCells":
        viewModel.updateSelectedCells(event.data.selectedCellIds);
        break;
      case "html": {
        const data = event.data;
        if (data.createOnIdle) {
          outputRunner.enqueueIdle(data.outputId, (signal) => {
            return viewModel.renderOutputCell(data, signal);
          });
        } else {
          outputRunner.enqueue(data.outputId, (signal) => {
            return viewModel.renderOutputCell(data, signal);
          });
        }
        break;
      }
      case "view-scroll": {
        event.data.widgets.forEach((widget) => {
          outputRunner.enqueue(widget.outputId, () => {
            viewModel.updateOutputsScroll([widget]);
          });
        });
        viewModel.updateMarkupScrolls(event.data.markupCells);
        break;
      }
      case "clear":
        renderers.clearAll();
        viewModel.clearAll();
        window.document.getElementById("container").innerText = "";
        break;
      case "clearOutput": {
        const { cellId, rendererId, outputId } = event.data;
        outputRunner.cancelOutput(outputId);
        viewModel.clearOutput(cellId, outputId, rendererId);
        break;
      }
      case "hideOutput": {
        const { cellId, outputId } = event.data;
        outputRunner.enqueue(outputId, () => {
          viewModel.hideOutput(cellId);
        });
        break;
      }
      case "showOutput": {
        const { outputId, cellTop, cellId, content } = event.data;
        outputRunner.enqueue(outputId, () => {
          viewModel.showOutput(cellId, outputId, cellTop);
          if (content) {
            viewModel.updateAndRerender(cellId, outputId, content);
          }
        });
        break;
      }
      case "copyImage": {
        await copyOutputImage(event.data.outputId, event.data.altOutputId);
        break;
      }
      case "ack-dimension": {
        for (const { cellId, outputId, height } of event.data.updates) {
          viewModel.updateOutputHeight(cellId, outputId, height);
        }
        break;
      }
      case "preload": {
        const resources = event.data.resources;
        for (const { uri } of resources) {
          kernelPreloads.load(uri);
        }
        break;
      }
      case "updateRenderers": {
        const { rendererData } = event.data;
        renderers.updateRendererData(rendererData);
        break;
      }
      case "focus-output":
        focusFirstFocusableOrContainerInOutput(event.data.cellOrOutputId, event.data.alternateId);
        break;
      case "blur-output":
        blurOutput();
        break;
      case "select-output-contents":
        selectOutputContents(event.data.cellOrOutputId);
        break;
      case "select-input-contents":
        selectInputContents(event.data.cellOrOutputId);
        break;
      case "decorations": {
        let outputContainer = window.document.getElementById(event.data.cellId);
        if (!outputContainer) {
          viewModel.ensureOutputCell(event.data.cellId, -1e5, true);
          outputContainer = window.document.getElementById(event.data.cellId);
        }
        outputContainer?.classList.add(...event.data.addedClassNames);
        outputContainer?.classList.remove(...event.data.removedClassNames);
        break;
      }
      case "customKernelMessage":
        onDidReceiveKernelMessage.fire(event.data.message);
        break;
      case "customRendererMessage":
        renderers.getRenderer(event.data.rendererId)?.receiveMessage(event.data.message);
        break;
      case "notebookStyles": {
        const documentStyle = window.document.documentElement.style;
        for (let i2 = documentStyle.length - 1; i2 >= 0; i2--) {
          const property = documentStyle[i2];
          if (property && property.startsWith("--notebook-")) {
            documentStyle.removeProperty(property);
          }
        }
        for (const [name, value] of Object.entries(event.data.styles)) {
          documentStyle.setProperty(`--${name}`, value);
        }
        break;
      }
      case "notebookOptions":
        currentOptions = event.data.options;
        viewModel.toggleDragDropEnabled(currentOptions.dragAndDropEnabled);
        currentRenderOptions = event.data.renderOptions;
        settingChange.fire(currentRenderOptions);
        break;
      case "tokenizedCodeBlock": {
        const { codeBlockId, html: html3 } = event.data;
        MarkdownCodeBlock.highlightCodeBlock(codeBlockId, html3);
        break;
      }
      case "tokenizedStylesChanged": {
        tokenizationStyle.replaceSync(event.data.css);
        break;
      }
      case "find": {
        _highlighter.removeHighlights(event.data.options.ownerID);
        find2(event.data.query, event.data.options);
        break;
      }
      case "findHighlightCurrent": {
        _highlighter?.highlightCurrentMatch(event.data.index, event.data.ownerID);
        break;
      }
      case "findUnHighlightCurrent": {
        _highlighter?.unHighlightCurrentMatch(event.data.index, event.data.ownerID);
        break;
      }
      case "findStop": {
        _highlighter.removeHighlights(event.data.ownerID);
        break;
      }
      case "returnOutputItem": {
        outputItemRequests.resolveOutputItem(event.data.requestId, event.data.output);
      }
    }
  });
  const renderFallbackErrorName = "vscode.fallbackToNextRenderer";
  class Renderer {
    constructor(data) {
      this.data = data;
      this.c = createEmitter();
    }
    receiveMessage(message) {
      this.c.fire(message);
    }
    async renderOutputItem(item, element, signal) {
      try {
        await this.j();
      } catch (e) {
        if (!signal.aborted) {
          showRenderError(`Error loading renderer '${this.data.id}'`, element, e instanceof Error ? [e] : []);
        }
        return;
      }
      if (!this.g) {
        if (!signal.aborted) {
          showRenderError(`Renderer '${this.data.id}' does not implement renderOutputItem`, element, []);
        }
        return;
      }
      try {
        const renderStart = performance.now();
        await this.g.renderOutputItem(item, element, signal);
        this.l("Rendered output item", { id: item.id, duration: `${performance.now() - renderStart}ms` });
      } catch (e) {
        if (signal.aborted) {
          return;
        }
        if (e instanceof Error && e.name === renderFallbackErrorName) {
          throw e;
        }
        showRenderError(`Error rendering output item using '${this.data.id}'`, element, e instanceof Error ? [e] : []);
        this.l("Rendering output item failed", { id: item.id, error: e + "" });
      }
    }
    disposeOutputItem(id2) {
      this.g?.disposeOutputItem?.(id2);
    }
    h() {
      const { id: id2, messaging } = this.data;
      const context = {
        setState: (newState) => vscode.setState({ ...vscode.getState(), [id2]: newState }),
        getState: () => {
          const state = vscode.getState();
          return typeof state === "object" && state ? state[id2] : void 0;
        },
        getRenderer: async (id3) => {
          const renderer = renderers.getRenderer(id3);
          if (!renderer) {
            return void 0;
          }
          if (renderer.g) {
            return renderer.g;
          }
          return renderer.j();
        },
        workspace: {
          get isTrusted() {
            return isWorkspaceTrusted;
          }
        },
        settings: {
          get lineLimit() {
            return currentRenderOptions.lineLimit;
          },
          get outputScrolling() {
            return currentRenderOptions.outputScrolling;
          },
          get outputWordWrap() {
            return currentRenderOptions.outputWordWrap;
          },
          get linkifyFilePaths() {
            return currentRenderOptions.linkifyFilePaths;
          },
          get minimalError() {
            return currentRenderOptions.minimalError;
          }
        },
        get onDidChangeSettings() {
          return settingChange.event;
        }
      };
      if (messaging) {
        context.onDidReceiveMessage = this.c.event;
        context.postMessage = (message) => postNotebookMessage("customRendererMessage", { rendererId: id2, message });
      }
      return Object.freeze(context);
    }
    j() {
      this.f ??= this.k();
      return this.f;
    }
    /** Inner function cached in the _loadPromise(). */
    async k() {
      this.l("Start loading renderer");
      try {
        await kernelPreloads.waitForAllCurrent();
        const importStart = performance.now();
        const module2 = await __import(this.data.entrypoint.path);
        this.l("Imported renderer", { duration: `${performance.now() - importStart}ms` });
        if (!module2) {
          return;
        }
        this.g = await module2.activate(this.h());
        this.l("Activated renderer", { duration: `${performance.now() - importStart}ms` });
        const dependantRenderers = ctx.rendererData.filter((d) => d.entrypoint.extends === this.data.id);
        if (dependantRenderers.length) {
          this.l("Activating dependant renderers", { dependents: dependantRenderers.map((x) => x.id).join(", ") });
        }
        await Promise.all(dependantRenderers.map(async (d) => {
          const renderer = renderers.getRenderer(d.id);
          if (!renderer) {
            throw new Error(`Could not find extending renderer: ${d.id}`);
          }
          try {
            return await renderer.j();
          } catch (e) {
            console.error(e);
            this.l("Activating dependant renderer failed", { dependent: d.id, error: e + "" });
            return void 0;
          }
        }));
        return this.g;
      } catch (e) {
        this.l("Loading renderer failed");
        throw e;
      }
    }
    l(msg, data) {
      postNotebookMessage("logRendererDebugMessage", {
        message: `[renderer ${this.data.id}] - ${msg}`,
        data
      });
    }
  }
  const kernelPreloads = new class {
    constructor() {
      this.c = /* @__PURE__ */ new Map();
    }
    /**
     * Returns a promise that resolves when the given preload is activated.
     */
    waitFor(uri) {
      return this.c.get(uri) || Promise.resolve(new Error(`Preload not ready: ${uri}`));
    }
    /**
     * Loads a preload.
     * @param uri URI to load from
     * @param originalUri URI to show in an error message if the preload is invalid.
     */
    load(uri) {
      const promise = Promise.all([
        runKernelPreload(uri),
        this.waitForAllCurrent()
      ]);
      this.c.set(uri, promise);
      return promise;
    }
    /**
     * Returns a promise that waits for all currently-registered preloads to
     * activate before resolving.
     */
    waitForAllCurrent() {
      return Promise.all([...this.c.values()].map((p) => p.catch((err) => err)));
    }
  }();
  const outputRunner = new class {
    constructor() {
      this.c = /* @__PURE__ */ new Map();
      this.f = /* @__PURE__ */ new Map();
    }
    /**
     * Pushes the action onto the list of actions for the given output ID,
     * ensuring that it's run in-order.
     */
    enqueue(outputId, action) {
      this.f.get(outputId)?.dispose();
      this.f.delete(outputId);
      const record = this.c.get(outputId);
      if (!record) {
        const controller = new AbortController();
        this.c.set(outputId, { abort: controller, queue: new Promise((r2) => r2(action(controller.signal))) });
      } else {
        record.queue = record.queue.then(async (r2) => {
          if (!record.abort.signal.aborted) {
            await action(record.abort.signal);
          }
        });
      }
    }
    enqueueIdle(outputId, action) {
      this.f.get(outputId)?.dispose();
      outputRunner.f.set(outputId, runWhenIdle(() => {
        outputRunner.enqueue(outputId, action);
        outputRunner.f.delete(outputId);
      }));
    }
    /**
     * Cancels the rendering of all outputs.
     */
    cancelAll() {
      this.f.forEach((r2) => r2.dispose());
      this.f.clear();
      for (const { abort } of this.c.values()) {
        abort.abort();
      }
      this.c.clear();
    }
    /**
     * Cancels any ongoing rendering out an output.
     */
    cancelOutput(outputId) {
      this.f.get(outputId)?.dispose();
      this.f.delete(outputId);
      const output = this.c.get(outputId);
      if (output) {
        output.abort.abort();
        this.c.delete(outputId);
      }
    }
  }();
  const renderers = new class {
    constructor() {
      this.c = /* @__PURE__ */ new Map();
      for (const renderer of ctx.rendererData) {
        this.g(renderer);
      }
    }
    getRenderer(id2) {
      return this.c.get(id2);
    }
    f(a, b) {
      if (a.id !== b.id || a.entrypoint.path !== b.entrypoint.path || a.entrypoint.extends !== b.entrypoint.extends || a.messaging !== b.messaging) {
        return false;
      }
      if (a.mimeTypes.length !== b.mimeTypes.length) {
        return false;
      }
      for (let i2 = 0; i2 < a.mimeTypes.length; i2++) {
        if (a.mimeTypes[i2] !== b.mimeTypes[i2]) {
          return false;
        }
      }
      return true;
    }
    updateRendererData(rendererData) {
      const oldKeys = new Set(this.c.keys());
      const newKeys = new Set(rendererData.map((d) => d.id));
      for (const renderer of rendererData) {
        const existing = this.c.get(renderer.id);
        if (existing && this.f(existing.data, renderer)) {
          continue;
        }
        this.g(renderer);
      }
      for (const key2 of oldKeys) {
        if (!newKeys.has(key2)) {
          this.c.delete(key2);
        }
      }
    }
    g(renderer) {
      this.c.set(renderer.id, new Renderer(renderer));
    }
    clearAll() {
      outputRunner.cancelAll();
      for (const renderer of this.c.values()) {
        renderer.disposeOutputItem();
      }
    }
    clearOutput(rendererId, outputId) {
      outputRunner.cancelOutput(outputId);
      this.c.get(rendererId)?.disposeOutputItem(outputId);
    }
    async render(item, preferredRendererId, element, signal) {
      const primaryRenderer = this.j(preferredRendererId, item);
      if (!primaryRenderer) {
        const errorMessage2 = (window.document.documentElement.style.getPropertyValue("--notebook-cell-renderer-not-found-error") || "").replace("$0", () => item.mime);
        this.k(item, element, errorMessage2);
        return;
      }
      if (!(await this.h(item, element, primaryRenderer, signal)).continue) {
        return;
      }
      for (const additionalItemData of item._allOutputItems) {
        if (additionalItemData.mime === item.mime) {
          continue;
        }
        const additionalItem = await additionalItemData.getItem();
        if (signal.aborted) {
          return;
        }
        if (additionalItem) {
          const renderer = this.j(void 0, additionalItem);
          if (renderer) {
            if (!(await this.h(additionalItem, element, renderer, signal)).continue) {
              return;
            }
          }
        }
      }
      const errorMessage = (window.document.documentElement.style.getPropertyValue("--notebook-cell-renderer-fallbacks-exhausted") || "").replace("$0", () => item.mime);
      this.k(item, element, errorMessage);
    }
    async h(item, element, renderer, signal) {
      try {
        await renderer.renderOutputItem(item, element, signal);
        return { continue: false };
      } catch (e) {
        if (signal.aborted) {
          return { continue: false };
        }
        if (e instanceof Error && e.name === renderFallbackErrorName) {
          return { continue: true };
        } else {
          throw e;
        }
      }
    }
    j(preferredRendererId, info) {
      let renderer;
      if (typeof preferredRendererId === "string") {
        renderer = Array.from(this.c.values()).find((renderer2) => renderer2.data.id === preferredRendererId);
      } else {
        const renderers2 = Array.from(this.c.values()).filter((renderer2) => renderer2.data.mimeTypes.includes(info.mime) && !renderer2.data.entrypoint.extends);
        if (renderers2.length) {
          renderers2.sort((a, b) => +a.data.isBuiltin - +b.data.isBuiltin);
          renderer = renderers2[0];
        }
      }
      return renderer;
    }
    k(info, element, errorMessage) {
      const errorContainer = document.createElement("div");
      const error = document.createElement("div");
      error.className = "no-renderer-error";
      error.innerText = errorMessage;
      const cellText = document.createElement("div");
      cellText.innerText = info.text();
      errorContainer.appendChild(error);
      errorContainer.appendChild(cellText);
      element.innerText = "";
      element.appendChild(errorContainer);
    }
  }();
  const viewModel = new class ViewModel {
    constructor() {
      this.c = /* @__PURE__ */ new Map();
      this.f = /* @__PURE__ */ new Map();
    }
    clearAll() {
      for (const cell of this.c.values()) {
        cell.dispose();
      }
      this.c.clear();
      for (const output of this.f.values()) {
        output.dispose();
      }
      this.f.clear();
    }
    async g(init, top2, visible) {
      const existing = this.c.get(init.cellId);
      if (existing) {
        console.error(`Trying to create markup that already exists: ${init.cellId}`);
        return existing;
      }
      const cell = new MarkupCell(init.cellId, init.mime, init.content, top2, init.metadata);
      cell.element.style.visibility = visible ? "" : "hidden";
      this.c.set(init.cellId, cell);
      await cell.ready;
      return cell;
    }
    async ensureMarkupCell(info) {
      let cell = this.c.get(info.cellId);
      if (cell) {
        cell.element.style.visibility = info.visible ? "" : "hidden";
        await cell.updateContentAndRender(info.content, info.metadata);
      } else {
        cell = await this.g(info, info.offset, info.visible);
      }
    }
    deleteMarkupCell(id2) {
      const cell = this.h(id2);
      if (cell) {
        cell.remove();
        cell.dispose();
        this.c.delete(id2);
      }
    }
    async updateMarkupContent(id2, newContent, metadata) {
      const cell = this.h(id2);
      await cell?.updateContentAndRender(newContent, metadata);
    }
    showMarkupCell(id2, top2, newContent, metadata) {
      const cell = this.h(id2);
      cell?.show(top2, newContent, metadata);
    }
    hideMarkupCell(id2) {
      const cell = this.h(id2);
      cell?.hide();
    }
    unhideMarkupCell(id2) {
      const cell = this.h(id2);
      cell?.unhide();
    }
    h(id2) {
      const cell = this.c.get(id2);
      if (!cell) {
        console.log(`Could not find markup cell '${id2}'`);
        return void 0;
      }
      return cell;
    }
    updateSelectedCells(selectedCellIds) {
      const selectedCellSet = new Set(selectedCellIds);
      for (const cell of this.c.values()) {
        cell.setSelected(selectedCellSet.has(cell.id));
      }
    }
    toggleDragDropEnabled(dragAndDropEnabled) {
      for (const cell of this.c.values()) {
        cell.toggleDragDropEnabled(dragAndDropEnabled);
      }
    }
    updateMarkupScrolls(markupCells) {
      for (const { id: id2, top: top2 } of markupCells) {
        const cell = this.c.get(id2);
        if (cell) {
          cell.element.style.top = `${top2}px`;
        }
      }
    }
    async renderOutputCell(data, signal) {
      const preloadErrors = await Promise.all(data.requiredPreloads.map((p) => kernelPreloads.waitFor(p.uri).then(() => void 0, (err) => err)));
      if (signal.aborted) {
        return;
      }
      const cellOutput = this.ensureOutputCell(data.cellId, data.cellTop, false);
      return cellOutput.renderOutputElement(data, preloadErrors, signal);
    }
    ensureOutputCell(cellId, cellTop, skipCellTopUpdateIfExist) {
      let cell = this.f.get(cellId);
      const existed = !!cell;
      if (!cell) {
        cell = new OutputCell(cellId);
        this.f.set(cellId, cell);
      }
      if (existed && skipCellTopUpdateIfExist) {
        return cell;
      }
      cell.element.style.top = cellTop + "px";
      return cell;
    }
    clearOutput(cellId, outputId, rendererId) {
      const cell = this.f.get(cellId);
      cell?.clearOutput(outputId, rendererId);
    }
    showOutput(cellId, outputId, top2) {
      const cell = this.f.get(cellId);
      cell?.show(outputId, top2);
    }
    updateAndRerender(cellId, outputId, content) {
      const cell = this.f.get(cellId);
      cell?.updateContentAndRerender(outputId, content);
    }
    hideOutput(cellId) {
      const cell = this.f.get(cellId);
      cell?.hide();
    }
    updateOutputHeight(cellId, outputId, height) {
      const cell = this.f.get(cellId);
      cell?.updateOutputHeight(outputId, height);
    }
    updateOutputsScroll(updates) {
      for (const request of updates) {
        const cell = this.f.get(request.cellId);
        cell?.updateScroll(request);
      }
    }
  }();
  class MarkdownCodeBlock {
    static {
      this.c = /* @__PURE__ */ new Map();
    }
    static highlightCodeBlock(id2, html3) {
      const el = MarkdownCodeBlock.c.get(id2);
      if (!el) {
        return;
      }
      const trustedHtml = ttPolicy5?.createHTML(html3) ?? html3;
      el.innerHTML = trustedHtml;
      const root = el.getRootNode();
      if (root instanceof ShadowRoot) {
        if (!root.adoptedStyleSheets.includes(tokenizationStyle)) {
          root.adoptedStyleSheets.push(tokenizationStyle);
        }
      }
    }
    static requestHighlightCodeBlock(root) {
      const codeBlocks = [];
      let i2 = 0;
      for (const el of root.querySelectorAll(".vscode-code-block")) {
        const lang = el.getAttribute("data-vscode-code-block-lang");
        if (el.textContent && lang) {
          const id2 = `${Date.now()}-${i2++}`;
          codeBlocks.push({ value: el.textContent, lang, id: id2 });
          MarkdownCodeBlock.c.set(id2, el);
        }
      }
      return codeBlocks;
    }
  }
  class MarkupCell {
    constructor(id2, mime, content, top2, metadata) {
      this.g = false;
      const self2 = this;
      this.id = id2;
      this.f = { value: content, version: 0, metadata };
      const { promise, resolve, reject } = promiseWithResolvers();
      this.ready = promise;
      let cachedData;
      this.c = Object.freeze({
        id: id2,
        mime,
        get metadata() {
          return self2.f.metadata;
        },
        text: () => {
          return this.f.value;
        },
        json: () => {
          return void 0;
        },
        data: () => {
          if (cachedData?.version === this.f.version) {
            return cachedData.value;
          }
          const data = textEncoder2.encode(this.f.value);
          cachedData = { version: this.f.version, value: data };
          return data;
        },
        blob() {
          return new Blob([this.data()], { type: this.mime });
        },
        _allOutputItems: [{
          mime,
          getItem: async () => this.c
        }]
      });
      const root = window.document.getElementById("container");
      const markupCell = document.createElement("div");
      markupCell.className = "markup";
      markupCell.style.position = "absolute";
      markupCell.style.width = "100%";
      this.element = document.createElement("div");
      this.element.id = this.id;
      this.element.classList.add("preview");
      this.element.style.position = "absolute";
      this.element.style.top = top2 + "px";
      this.toggleDragDropEnabled(currentOptions.dragAndDropEnabled);
      markupCell.appendChild(this.element);
      root.appendChild(markupCell);
      this.j();
      this.updateContentAndRender(this.f.value, this.f.metadata).then(() => {
        if (!this.g) {
          resizeObserver.observe(this.element, this.id, false, this.id);
        }
        resolve();
      }, () => reject());
    }
    dispose() {
      this.g = true;
      this.h?.abort();
      this.h = void 0;
    }
    j() {
      this.element.addEventListener("dblclick", () => {
        postNotebookMessage("toggleMarkupPreview", { cellId: this.id });
      });
      this.element.addEventListener("click", (e) => {
        postNotebookMessage("clickMarkupCell", {
          cellId: this.id,
          altKey: e.altKey,
          ctrlKey: e.ctrlKey,
          metaKey: e.metaKey,
          shiftKey: e.shiftKey
        });
      });
      this.element.addEventListener("contextmenu", (e) => {
        postNotebookMessage("contextMenuMarkupCell", {
          cellId: this.id,
          clientX: e.clientX,
          clientY: e.clientY
        });
      });
      this.element.addEventListener("mouseenter", () => {
        postNotebookMessage("mouseEnterMarkupCell", { cellId: this.id });
      });
      this.element.addEventListener("mouseleave", () => {
        postNotebookMessage("mouseLeaveMarkupCell", { cellId: this.id });
      });
      this.element.addEventListener("dragstart", (e) => {
        markupCellDragManager.startDrag(e, this.id);
      });
      this.element.addEventListener("drag", (e) => {
        markupCellDragManager.updateDrag(e, this.id);
      });
      this.element.addEventListener("dragend", (e) => {
        markupCellDragManager.endDrag(e, this.id);
      });
    }
    async updateContentAndRender(newContent, metadata) {
      this.f = { value: newContent, version: this.f.version + 1, metadata };
      this.h?.abort();
      const controller = new AbortController();
      this.h = controller;
      try {
        await renderers.render(this.c, void 0, this.element, this.h.signal);
      } finally {
        if (this.h === controller) {
          this.h = void 0;
        }
      }
      const root = this.element.shadowRoot ?? this.element;
      const html3 = [];
      for (const child of root.children) {
        switch (child.tagName) {
          case "LINK":
          case "SCRIPT":
          case "STYLE":
            break;
          default:
            html3.push(child.outerHTML);
            break;
        }
      }
      const codeBlocks = MarkdownCodeBlock.requestHighlightCodeBlock(root);
      postNotebookMessage("renderedMarkup", {
        cellId: this.id,
        html: html3.join(""),
        codeBlocks
      });
      dimensionUpdater.updateHeight(this.id, this.element.offsetHeight, {
        isOutput: false
      });
    }
    show(top2, newContent, metadata) {
      this.element.style.visibility = "";
      this.element.style.top = `${top2}px`;
      if (typeof newContent === "string" || metadata) {
        this.updateContentAndRender(newContent ?? this.f.value, metadata ?? this.f.metadata);
      } else {
        this.k();
      }
    }
    hide() {
      this.element.style.visibility = "hidden";
    }
    unhide() {
      this.element.style.visibility = "";
      this.k();
    }
    remove() {
      this.element.remove();
    }
    async k() {
      dimensionUpdater.updateHeight(this.id, this.element.offsetHeight, {
        isOutput: false
      });
    }
    setSelected(selected) {
      this.element.classList.toggle("selected", selected);
    }
    toggleDragDropEnabled(enabled) {
      if (enabled) {
        this.element.classList.add("draggable");
        this.element.setAttribute("draggable", "true");
      } else {
        this.element.classList.remove("draggable");
        this.element.removeAttribute("draggable");
      }
    }
  }
  class OutputCell {
    constructor(cellId) {
      this.c = /* @__PURE__ */ new Map();
      const container2 = window.document.getElementById("container");
      const upperWrapperElement = createFocusSink(cellId);
      container2.appendChild(upperWrapperElement);
      this.element = document.createElement("div");
      this.element.style.position = "absolute";
      this.element.style.outline = "0";
      this.element.id = cellId;
      this.element.classList.add("cell_container");
      container2.appendChild(this.element);
      this.element = this.element;
      const lowerWrapperElement = createFocusSink(cellId, true);
      container2.appendChild(lowerWrapperElement);
    }
    dispose() {
      for (const output of this.c.values()) {
        output.dispose();
      }
      this.c.clear();
    }
    f(data) {
      let outputContainer = this.c.get(data.outputId);
      if (!outputContainer) {
        outputContainer = new OutputContainer(data.outputId);
        this.element.appendChild(outputContainer.element);
        this.c.set(data.outputId, outputContainer);
      }
      return outputContainer.createOutputElement(data.outputId, data.outputOffset, data.left, data.cellId);
    }
    async renderOutputElement(data, preloadErrors, signal) {
      const startTime = Date.now();
      const outputElement = this.f(data);
      await outputElement.render(data.content, data.rendererId, preloadErrors, signal);
      outputElement.element.style.visibility = data.initiallyHidden ? "hidden" : "";
      if (!!data.executionId && !!data.rendererId) {
        let outputSize = void 0;
        let mimeType = void 0;
        if (data.content.type === 1) {
          outputSize = data.content.output.valueBytes.length;
          mimeType = data.content.output.mime;
        }
        postNotebookMessage("notebookPerformanceMessage", {
          cellId: data.cellId,
          executionId: data.executionId,
          duration: Date.now() - startTime,
          rendererId: data.rendererId,
          outputSize,
          mimeType
        });
      }
    }
    clearOutput(outputId, rendererId) {
      const output = this.c.get(outputId);
      output?.clear(rendererId);
      output?.dispose();
      this.c.delete(outputId);
    }
    show(outputId, top2) {
      const outputContainer = this.c.get(outputId);
      if (!outputContainer) {
        return;
      }
      this.element.style.visibility = "";
      this.element.style.top = `${top2}px`;
    }
    hide() {
      this.element.style.visibility = "hidden";
    }
    updateContentAndRerender(outputId, content) {
      this.c.get(outputId)?.updateContentAndRender(content);
    }
    updateOutputHeight(outputId, height) {
      this.c.get(outputId)?.updateHeight(height);
    }
    updateScroll(request) {
      this.element.style.top = `${request.cellTop}px`;
      const outputElement = this.c.get(request.outputId);
      if (outputElement) {
        outputElement.updateScroll(request.outputOffset);
        if (request.forceDisplay && outputElement.outputNode) {
          outputElement.outputNode.element.style.visibility = "";
        }
      }
      if (request.forceDisplay) {
        this.element.style.visibility = "";
      }
    }
  }
  class OutputContainer {
    get outputNode() {
      return this.c;
    }
    constructor(f) {
      this.f = f;
      this.element = document.createElement("div");
      this.element.classList.add("output_container");
      this.element.setAttribute("data-vscode-context", JSON.stringify({ "preventDefaultContextMenuItems": true }));
      this.element.style.position = "absolute";
      this.element.style.overflow = "hidden";
    }
    dispose() {
      this.c?.dispose();
    }
    clear(rendererId) {
      if (rendererId) {
        renderers.clearOutput(rendererId, this.f);
      }
      this.element.remove();
    }
    updateHeight(height) {
      this.element.style.maxHeight = `${height}px`;
      this.element.style.height = `${height}px`;
    }
    updateScroll(outputOffset) {
      this.element.style.top = `${outputOffset}px`;
    }
    createOutputElement(outputId, outputOffset, left, cellId) {
      this.element.innerText = "";
      this.element.style.maxHeight = "0px";
      this.element.style.top = `${outputOffset}px`;
      this.c?.dispose();
      this.c = new OutputElement(outputId, left, cellId);
      this.element.appendChild(this.c.element);
      return this.c;
    }
    updateContentAndRender(content) {
      this.c?.updateAndRerender(content);
    }
  }
  vscode.postMessage({
    __vscode_notebook_message: true,
    type: "initialized"
  });
  for (const preload of ctx.staticPreloadsData) {
    kernelPreloads.load(preload.entrypoint);
  }
  function postNotebookMessage(type, properties) {
    vscode.postMessage({
      __vscode_notebook_message: true,
      type,
      ...properties
    });
  }
  class OutputElement {
    constructor(h3, left, cellId) {
      this.h = h3;
      this.cellId = cellId;
      this.f = false;
      this.element = document.createElement("div");
      this.element.id = h3;
      this.element.classList.add("output");
      this.element.style.position = "absolute";
      this.element.style.top = `0px`;
      this.element.style.left = left + "px";
      this.element.style.padding = `${ctx.style.outputNodePadding}px ${ctx.style.outputNodePadding}px ${ctx.style.outputNodePadding}px ${ctx.style.outputNodeLeftPadding}`;
      this.element.addEventListener("mouseenter", () => {
        postNotebookMessage("mouseenter", { id: h3 });
      });
      this.element.addEventListener("mouseleave", () => {
        postNotebookMessage("mouseleave", { id: h3 });
      });
    }
    dispose() {
      this.g?.abort();
      this.g = void 0;
    }
    async render(content, preferredRendererId, preloadErrors, signal) {
      this.g?.abort();
      this.g = void 0;
      this.c = { preferredRendererId, preloadErrors };
      if (content.type === 0) {
        const trustedHtml = ttPolicy5?.createHTML(content.htmlContent) ?? content.htmlContent;
        this.element.innerHTML = trustedHtml;
      } else if (preloadErrors.some((e) => e instanceof Error)) {
        const errors = preloadErrors.filter((e) => e instanceof Error);
        showRenderError(`Error loading preloads`, this.element, errors);
      } else {
        const item = createOutputItem(this.h, content.output.mime, content.metadata, content.output.valueBytes, content.allOutputs, content.output.appended);
        const controller = new AbortController();
        this.g = controller;
        signal?.addEventListener("abort", () => controller.abort());
        try {
          await renderers.render(item, preferredRendererId, this.element, controller.signal);
        } finally {
          if (this.g === controller) {
            this.g = void 0;
          }
        }
      }
      if (!this.f) {
        this.f = true;
        resizeObserver.observe(this.element, this.h, true, this.cellId);
      }
      const offsetHeight = this.element.offsetHeight;
      const cps = document.defaultView.getComputedStyle(this.element);
      const verticalPadding = parseFloat(cps.paddingTop) + parseFloat(cps.paddingBottom);
      const contentHeight = offsetHeight - verticalPadding;
      if (elementHasContent(contentHeight) && cps.padding === "0px") {
        dimensionUpdater.updateHeight(this.h, offsetHeight + ctx.style.outputNodePadding * 2, {
          isOutput: true,
          init: true
        });
        this.element.style.padding = `${ctx.style.outputNodePadding}px ${ctx.style.outputNodePadding}px ${ctx.style.outputNodePadding}px ${ctx.style.outputNodeLeftPadding}`;
      } else if (elementHasContent(contentHeight)) {
        dimensionUpdater.updateHeight(this.h, this.element.offsetHeight, {
          isOutput: true,
          init: true
        });
        this.element.style.padding = `0 ${ctx.style.outputNodePadding}px 0 ${ctx.style.outputNodeLeftPadding}`;
      } else {
        dimensionUpdater.updateHeight(this.h, 0, {
          isOutput: true,
          init: true
        });
      }
      const root = this.element.shadowRoot ?? this.element;
      const codeBlocks = MarkdownCodeBlock.requestHighlightCodeBlock(root);
      if (codeBlocks.length > 0) {
        postNotebookMessage("renderedCellOutput", {
          codeBlocks
        });
      }
    }
    updateAndRerender(content) {
      if (this.c) {
        this.render(content, this.c.preferredRendererId, this.c.preloadErrors);
      }
    }
  }
  const markupCellDragManager = new class MarkupCellDragManager {
    constructor() {
      window.document.addEventListener("dragover", (e) => {
        e.preventDefault();
      });
      window.document.addEventListener("drop", (e) => {
        e.preventDefault();
        const drag = this.c;
        if (!drag) {
          return;
        }
        this.c = void 0;
        postNotebookMessage("cell-drop", {
          cellId: drag.cellId,
          ctrlKey: e.ctrlKey,
          altKey: e.altKey,
          dragOffsetY: e.clientY
        });
      });
    }
    startDrag(e, cellId) {
      if (!e.dataTransfer) {
        return;
      }
      if (!currentOptions.dragAndDropEnabled) {
        return;
      }
      this.c = { cellId, clientY: e.clientY };
      const overlayZIndex = 9999;
      if (!this.f) {
        this.f = document.createElement("div");
        this.f.style.position = "absolute";
        this.f.style.top = "0";
        this.f.style.left = "0";
        this.f.style.zIndex = `${overlayZIndex}`;
        this.f.style.width = "100%";
        this.f.style.height = "100%";
        this.f.style.background = "transparent";
        window.document.body.appendChild(this.f);
      }
      e.target.style.zIndex = `${overlayZIndex + 1}`;
      e.target.classList.add("dragging");
      postNotebookMessage("cell-drag-start", {
        cellId,
        dragOffsetY: e.clientY
      });
      const trySendDragUpdate = () => {
        if (this.c?.cellId !== cellId) {
          return;
        }
        postNotebookMessage("cell-drag", {
          cellId,
          dragOffsetY: this.c.clientY
        });
        window.requestAnimationFrame(trySendDragUpdate);
      };
      window.requestAnimationFrame(trySendDragUpdate);
    }
    updateDrag(e, cellId) {
      if (cellId !== this.c?.cellId) {
        this.c = void 0;
      } else {
        this.c = { cellId, clientY: e.clientY };
      }
    }
    endDrag(e, cellId) {
      this.c = void 0;
      e.target.classList.remove("dragging");
      postNotebookMessage("cell-drag-end", {
        cellId
      });
      if (this.f) {
        this.f.remove();
        this.f = void 0;
      }
      e.target.style.zIndex = "";
    }
  }();
}
function $AJb(styleValues, options3, renderOptions, renderers, preloads, isWorkspaceTrusted, nonce) {
  const ctx = {
    style: styleValues,
    options: options3,
    renderOptions,
    rendererData: renderers,
    staticPreloadsData: preloads,
    isWorkspaceTrusted,
    nonce
  };
  return `
		const __import = (x) => import(x);
		(${webviewPreloads})(
			JSON.parse(decodeURIComponent("${encodeURIComponent(JSON.stringify(ctx))}"))
		)
//# sourceURL=notebookWebviewPreloads.js
`;
}

// out-build/vs/workbench/contrib/notebook/browser/view/renderers/webviewThemeMapping.js
var mapping = /* @__PURE__ */ new Map([
  ["theme-font-family", "vscode-font-family"],
  ["theme-font-weight", "vscode-font-weight"],
  ["theme-font-size", "vscode-font-size"],
  ["theme-code-font-family", "vscode-editor-font-family"],
  ["theme-code-font-weight", "vscode-editor-font-weight"],
  ["theme-code-font-size", "vscode-editor-font-size"],
  ["theme-scrollbar-background", "vscode-scrollbarSlider-background"],
  ["theme-scrollbar-hover-background", "vscode-scrollbarSlider-hoverBackground"],
  ["theme-scrollbar-active-background", "vscode-scrollbarSlider-activeBackground"],
  ["theme-quote-background", "vscode-textBlockQuote-background"],
  ["theme-quote-border", "vscode-textBlockQuote-border"],
  ["theme-code-foreground", "vscode-textPreformat-foreground"],
  // Editor
  ["theme-background", "vscode-editor-background"],
  ["theme-foreground", "vscode-editor-foreground"],
  ["theme-ui-foreground", "vscode-foreground"],
  ["theme-link", "vscode-textLink-foreground"],
  ["theme-link-active", "vscode-textLink-activeForeground"],
  // Buttons
  ["theme-button-background", "vscode-button-background"],
  ["theme-button-hover-background", "vscode-button-hoverBackground"],
  ["theme-button-foreground", "vscode-button-foreground"],
  ["theme-button-secondary-background", "vscode-button-secondaryBackground"],
  ["theme-button-secondary-hover-background", "vscode-button-secondaryHoverBackground"],
  ["theme-button-secondary-foreground", "vscode-button-secondaryForeground"],
  ["theme-button-hover-foreground", "vscode-button-foreground"],
  ["theme-button-focus-foreground", "vscode-button-foreground"],
  ["theme-button-secondary-hover-foreground", "vscode-button-secondaryForeground"],
  ["theme-button-secondary-focus-foreground", "vscode-button-secondaryForeground"],
  // Inputs
  ["theme-input-background", "vscode-input-background"],
  ["theme-input-foreground", "vscode-input-foreground"],
  ["theme-input-placeholder-foreground", "vscode-input-placeholderForeground"],
  ["theme-input-focus-border-color", "vscode-focusBorder"],
  // Menus
  ["theme-menu-background", "vscode-menu-background"],
  ["theme-menu-foreground", "vscode-menu-foreground"],
  ["theme-menu-hover-background", "vscode-menu-selectionBackground"],
  ["theme-menu-focus-background", "vscode-menu-selectionBackground"],
  ["theme-menu-hover-foreground", "vscode-menu-selectionForeground"],
  ["theme-menu-focus-foreground", "vscode-menu-selectionForeground"],
  // Errors
  ["theme-error-background", "vscode-inputValidation-errorBackground"],
  ["theme-error-foreground", "vscode-foreground"],
  ["theme-warning-background", "vscode-inputValidation-warningBackground"],
  ["theme-warning-foreground", "vscode-foreground"],
  ["theme-info-background", "vscode-inputValidation-infoBackground"],
  ["theme-info-foreground", "vscode-foreground"],
  // Notebook:
  ["theme-notebook-output-background", "vscode-notebook-outputContainerBackgroundColor"],
  ["theme-notebook-output-border", "vscode-notebook-outputContainerBorderColor"],
  ["theme-notebook-cell-selected-background", "vscode-notebook-selectedCellBackground"],
  ["theme-notebook-symbol-highlight-background", "vscode-notebook-symbolHighlightBackground"],
  ["theme-notebook-diff-removed-background", "vscode-diffEditor-removedTextBackground"],
  ["theme-notebook-diff-inserted-background", "vscode-diffEditor-insertedTextBackground"]
]);
var constants = {
  "theme-input-border-width": "1px",
  "theme-button-primary-hover-shadow": "none",
  "theme-button-secondary-hover-shadow": "none",
  "theme-input-border-color": "transparent"
};
var $BJb = (s) => {
  const result = { ...s, ...constants };
  for (const [target, src] of mapping) {
    result[target] = s[src];
  }
  return result;
};

// out-build/vs/workbench/contrib/webview/common/webview.js
var $EJb = "vscode-cdn.net";
var $FJb = `vscode-resource.${$EJb}`;
var $GJb = `'self' https://*.${$EJb}`;
function $HJb(resource, remoteInfo) {
  if (resource.scheme === Schemas.http || resource.scheme === Schemas.https) {
    return resource;
  }
  if (remoteInfo && remoteInfo.authority && remoteInfo.isRemote && resource.scheme === Schemas.file) {
    resource = URI.from({
      scheme: Schemas.vscodeRemote,
      authority: remoteInfo.authority,
      path: resource.path
    });
  }
  return URI.from({
    scheme: Schemas.https,
    authority: `${resource.scheme}+${encodeAuthority(resource.authority)}.${$FJb}`,
    path: resource.path,
    fragment: resource.fragment,
    query: resource.query
  });
}
function encodeAuthority(authority) {
  return authority.replace(/./g, (char) => {
    const code = char.charCodeAt(0);
    if (code >= 97 && code <= 122 || code >= 65 && code <= 90 || code >= 48 && code <= 57) {
      return char;
    }
    return "-" + code.toString(16).padStart(4, "0");
  });
}
function $IJb(authority) {
  return authority.replace(/-([0-9a-f]{4})/g, (_, code) => String.fromCharCode(parseInt(code, 16)));
}

// out-build/vs/workbench/contrib/notebook/browser/view/renderers/backLayerWebView.js
var $JJb_1;
var LINE_COLUMN_REGEX = /:([\d]+)(?::([\d]+))?$/;
var LineQueryRegex = /line=(\d+)$/;
var FRAGMENT_REGEX = /^(.*)#([^#]*)$/;
var $JJb = class $JJb2 extends $ns {
  static {
    $JJb_1 = this;
  }
  static b(storageService) {
    this.a ??= new $Erb("notebook.backlayerWebview.origins", storageService);
    return this.a;
  }
  constructor(notebookEditor, F, notebookViewType, documentUri, G, H, I, J, L, M, N, O, P, Q, R, S, U, W, X, Y, Z, $149, ab, themeService, bb) {
    super(themeService);
    this.notebookEditor = notebookEditor;
    this.F = F;
    this.notebookViewType = notebookViewType;
    this.documentUri = documentUri;
    this.G = G;
    this.H = H;
    this.I = I;
    this.J = J;
    this.L = L;
    this.M = M;
    this.N = N;
    this.O = O;
    this.P = P;
    this.Q = Q;
    this.R = R;
    this.S = S;
    this.U = U;
    this.W = W;
    this.X = X;
    this.Y = Y;
    this.Z = Z;
    this.$ = $149;
    this.ab = ab;
    this.bb = bb;
    this.webview = void 0;
    this.insetMapping = /* @__PURE__ */ new Map();
    this.pendingWebviewIdleCreationRequest = /* @__PURE__ */ new Map();
    this.pendingWebviewIdleInsetMapping = /* @__PURE__ */ new Map();
    this.c = /* @__PURE__ */ new Map();
    this.markupPreviewMapping = /* @__PURE__ */ new Map();
    this.f = /* @__PURE__ */ new Set();
    this.g = /* @__PURE__ */ new Map();
    this.j = void 0;
    this.m = this.B(new $ze());
    this.r = /* @__PURE__ */ new Set();
    this.onMessage = this.m.event;
    this.s = false;
    this.u = true;
    this.D = $ps();
    this.cb("Creating backlayer webview for notebook");
    this.element = document.createElement("div");
    this.element.style.height = "1400px";
    this.element.style.position = "absolute";
    if (H) {
      this.B(H);
      H.receiveMessageHandler = (rendererId, message) => {
        if (!this.webview || this.s) {
          return Promise.resolve(false);
        }
        this.Eb({
          __vscode_notebook_message: true,
          type: "customRendererMessage",
          rendererId,
          message
        });
        return Promise.resolve(true);
      };
    }
    this.B(S.onDidChangeTrust((e) => {
      const baseUrl = this.jb(this.lb(), void 0);
      const htmlContent = this.gb(baseUrl.toString());
      this.webview?.setHtml(htmlContent);
    }));
    this.B($YE.onDidChange(() => {
      this.Eb({
        type: "tokenizedStylesChanged",
        css: getTokenizationCss()
      });
    }));
  }
  updateOptions(options3) {
    this.G = options3;
    this.db();
    this.eb();
  }
  cb(msg) {
    this.ab.debug("BacklayerWebview", `${this.documentUri} (${this.F}) - ${msg}`);
  }
  db() {
    this.Eb({
      type: "notebookStyles",
      styles: this.fb()
    });
  }
  eb() {
    this.Eb({
      type: "notebookOptions",
      options: {
        dragAndDropEnabled: this.G.dragAndDropEnabled
      },
      renderOptions: {
        lineLimit: this.G.outputLineLimit,
        outputScrolling: this.G.outputScrolling,
        outputWordWrap: this.G.outputWordWrap,
        linkifyFilePaths: this.G.outputLinkifyFilePaths,
        minimalError: this.G.minimalError
      }
    });
  }
  fb() {
    return {
      "notebook-output-left-margin": `${this.G.leftMargin + this.G.runGutter}px`,
      "notebook-output-width": `calc(100% - ${this.G.leftMargin + this.G.rightMargin + this.G.runGutter}px)`,
      "notebook-output-node-padding": `${this.G.outputNodePadding}px`,
      "notebook-run-gutter": `${this.G.runGutter}px`,
      "notebook-preview-node-padding": `${this.G.previewNodePadding}px`,
      "notebook-markdown-left-margin": `${this.G.markdownLeftMargin}px`,
      "notebook-output-node-left-padding": `${this.G.outputNodeLeftPadding}px`,
      "notebook-markdown-min-height": `${this.G.previewNodePadding * 2}px`,
      "notebook-markup-font-size": typeof this.G.markupFontSize === "number" && this.G.markupFontSize > 0 ? `${this.G.markupFontSize}px` : `calc(${this.G.fontSize}px * 1.2)`,
      "notebook-markdown-line-height": typeof this.G.markdownLineHeight === "number" && this.G.markdownLineHeight > 0 ? `${this.G.markdownLineHeight}px` : `normal`,
      "notebook-cell-output-font-size": `${this.G.outputFontSize || this.G.fontSize}px`,
      "notebook-cell-output-line-height": `${this.G.outputLineHeight}px`,
      "notebook-cell-output-max-height": `${this.G.outputLineHeight * this.G.outputLineLimit + 2}px`,
      "notebook-cell-output-font-family": this.G.outputFontFamily || this.G.fontFamily,
      "notebook-cell-markup-empty-content": localize(8603, null),
      "notebook-cell-renderer-not-found-error": localize(8604, null),
      "notebook-cell-renderer-fallbacks-exhausted": localize(8605, null)
    };
  }
  gb(baseUrl) {
    const renderersData = this.hb();
    const preloadsData = this.ib();
    const renderOptions = {
      lineLimit: this.G.outputLineLimit,
      outputScrolling: this.G.outputScrolling,
      outputWordWrap: this.G.outputWordWrap,
      linkifyFilePaths: this.G.outputLinkifyFilePaths,
      minimalError: this.G.minimalError
    };
    const preloadScript = $AJb({
      ...this.G,
      tokenizationCss: getTokenizationCss()
    }, { dragAndDropEnabled: this.G.dragAndDropEnabled }, renderOptions, renderersData, preloadsData, this.S.isWorkspaceTrusted(), this.D);
    const enableCsp = this.U.getValue("notebook.experimental.enableCsp");
    const currentHighlight = this.z($ap);
    const findMatchHighlight = this.z($cp);
    return (
      /* html */
      `
		<html lang="en">
			<head>
				<meta charset="UTF-8">
				<base href="${baseUrl}/" />
				${enableCsp ? `<meta http-equiv="Content-Security-Policy" content="
					default-src 'none';
					script-src ${$GJb} 'unsafe-inline' 'unsafe-eval';
					style-src ${$GJb} 'unsafe-inline';
					img-src ${$GJb} https: http: data:;
					font-src ${$GJb} https:;
					connect-src https:;
					child-src https: data:;
				">` : ""}
				<style nonce="${this.D}">
					::highlight(find-highlight) {
						background-color: var(--vscode-editor-findMatchBackground, ${findMatchHighlight});
					}

					::highlight(current-find-highlight) {
						background-color: var(--vscode-editor-findMatchHighlightBackground, ${currentHighlight});
					}

					#container .cell_container {
						width: 100%;
					}

					#container .output_container {
						width: 100%;
					}

					#container > div > div > div.output {
						font-size: var(--notebook-cell-output-font-size);
						width: var(--notebook-output-width);
						margin-left: var(--notebook-output-left-margin);
						background-color: var(--theme-notebook-output-background);
						padding-top: var(--notebook-output-node-padding);
						padding-right: var(--notebook-output-node-padding);
						padding-bottom: var(--notebook-output-node-padding);
						padding-left: var(--notebook-output-node-left-padding);
						box-sizing: border-box;
						border-top: none;
					}

					/* markdown */
					#container div.preview {
						width: 100%;
						padding-right: var(--notebook-preview-node-padding);
						padding-left: var(--notebook-markdown-left-margin);
						padding-top: var(--notebook-preview-node-padding);
						padding-bottom: var(--notebook-preview-node-padding);

						box-sizing: border-box;
						white-space: nowrap;
						overflow: hidden;
						white-space: initial;

						font-size: var(--notebook-markup-font-size);
						line-height: var(--notebook-markdown-line-height);
						color: var(--theme-ui-foreground);
					}

					#container div.preview.draggable {
						user-select: none;
						-webkit-user-select: none;
						-ms-user-select: none;
						cursor: grab;
					}

					#container div.preview.selected {
						background: var(--theme-notebook-cell-selected-background);
					}

					#container div.preview.dragging {
						background-color: var(--theme-background);
						opacity: 0.5 !important;
					}

					.monaco-workbench.vs-dark .notebookOverlay .cell.markdown .latex img,
					.monaco-workbench.vs-dark .notebookOverlay .cell.markdown .latex-block img {
						filter: brightness(0) invert(1)
					}

					#container .markup > div.nb-symbolHighlight {
						background-color: var(--theme-notebook-symbol-highlight-background);
					}

					#container .nb-symbolHighlight .output_container .output {
						background-color: var(--theme-notebook-symbol-highlight-background);
					}

					#container .markup > div.nb-multiCellHighlight {
						background-color: var(--theme-notebook-symbol-highlight-background);
					}

					#container .nb-multiCellHighlight .output_container .output {
						background-color: var(--theme-notebook-symbol-highlight-background);
					}

					#container .nb-chatGenerationHighlight .output_container .output {
						background-color: var(--vscode-notebook-selectedCellBackground);
					}

					#container > div.nb-cellDeleted .output_container {
						background-color: var(--theme-notebook-diff-removed-background);
					}

					#container > div.nb-cellAdded .output_container {
						background-color: var(--theme-notebook-diff-inserted-background);
					}

					#container > div > div:not(.preview) > div {
						overflow-x: auto;
					}

					#container .no-renderer-error {
						color: var(--vscode-editorError-foreground);
					}

					body {
						padding: 0px;
						height: 100%;
						width: 100%;
					}

					table, thead, tr, th, td, tbody {
						border: none;
						border-color: transparent;
						border-spacing: 0;
						border-collapse: collapse;
					}

					table, th, tr {
						vertical-align: middle;
						text-align: right;
					}

					thead {
						font-weight: bold;
						background-color: rgba(130, 130, 130, 0.16);
					}

					th, td {
						padding: 4px 8px;
					}

					tr:nth-child(even) {
						background-color: rgba(130, 130, 130, 0.08);
					}

					tbody th {
						font-weight: normal;
					}

					.find-match {
						background-color: var(--vscode-editor-findMatchHighlightBackground);
					}

					.current-find-match {
						background-color: var(--vscode-editor-findMatchBackground);
					}

					#_defaultColorPalatte {
						color: var(--vscode-editor-findMatchHighlightBackground);
						background-color: var(--vscode-editor-findMatchBackground);
					}
				</style>
			</head>
			<body style="overflow: hidden;">
				<div id='findStart' tabIndex=-1></div>
				<div id='container' class="widgetarea" style="position: absolute;width:100%;top: 0px"></div>
				<div id="_defaultColorPalatte"></div>
				<script type="module">${preloadScript}</script>
			</body>
		</html>`
    );
  }
  hb() {
    return this.L.getRenderers().map((renderer) => {
      const entrypoint = {
        extends: renderer.entrypoint.extends,
        path: this.jb(renderer.entrypoint.path, renderer.extensionLocation).toString()
      };
      return {
        id: renderer.id,
        entrypoint,
        mimeTypes: renderer.mimeTypes,
        messaging: renderer.messaging !== "never" && !!this.H,
        isBuiltin: renderer.isBuiltin
      };
    });
  }
  ib() {
    return Array.from(this.L.getStaticPreloads(this.notebookViewType), (preload) => {
      return { entrypoint: this.jb(preload.entrypoint, preload.extensionLocation).toString().toString() };
    });
  }
  jb(uri, fromExtension) {
    return $HJb(uri, fromExtension?.scheme === Schemas.vscodeRemote ? { isRemote: true, authority: fromExtension.authority } : void 0);
  }
  postKernelMessage(message) {
    this.Eb({
      __vscode_notebook_message: true,
      type: "customKernelMessage",
      message
    });
  }
  kb(id2) {
    const output = this.g.get(id2);
    if (!output) {
      return;
    }
    const cellInfo = this.insetMapping.get(output).cellInfo;
    return { cellInfo, output };
  }
  isResolved() {
    return !!this.webview;
  }
  createWebview(targetWindow) {
    const baseUrl = this.jb(this.lb(), void 0);
    const htmlContent = this.gb(baseUrl.toString());
    return this.nb(htmlContent, targetWindow);
  }
  lb() {
    if (this.documentUri.scheme === Schemas.untitled) {
      const folder = this.X.getWorkspaceFolder(this.documentUri);
      if (folder) {
        return folder.uri;
      }
      const folders = this.X.getWorkspace().folders;
      if (folders.length) {
        return folders[0].uri;
      }
    }
    return $uh(this.documentUri);
  }
  mb() {
    if (!this.documentUri.path.toLowerCase().endsWith(".ipynb")) {
      return [];
    }
    if ($r) {
      return [];
    }
    return [
      $uh($ih.asFileUri("vs/nls.js"))
    ];
  }
  nb(content, targetWindow) {
    if (!getWindow(this.element).document.body.contains(this.element)) {
      throw new Error("Element is already detached from the DOM tree");
    }
    this.webview = this.ub(this.I, content);
    this.webview.mountTo(this.element, targetWindow);
    this.B(this.webview);
    this.B(new $DJb(targetWindow, () => this.webview));
    const initializePromise = new $gi();
    this.B(this.webview.onFatalError((e) => {
      initializePromise.error(new Error(`Could not initialize webview: ${e.message}}`));
    }));
    this.B(this.webview.onMessage(async (message) => {
      const data = message.message;
      if (this.s) {
        return;
      }
      if (!data.__vscode_notebook_message) {
        return;
      }
      switch (data.type) {
        case "initialized": {
          initializePromise.complete();
          this.wb();
          break;
        }
        case "initializedMarkup": {
          if (this.C?.requestId === data.requestId) {
            this.C?.p.complete();
            this.C = void 0;
          }
          break;
        }
        case "dimension": {
          for (const update of data.updates) {
            const height = update.height;
            if (update.isOutput) {
              const resolvedResult = this.kb(update.id);
              if (resolvedResult) {
                const { cellInfo, output } = resolvedResult;
                this.notebookEditor.updateOutputHeight(cellInfo, output, height, !!update.init, "webview#dimension");
                this.notebookEditor.scheduleOutputHeightAck(cellInfo, update.id, height);
              } else if (update.init) {
                const outputRequest = this.c.get(update.id);
                if (outputRequest) {
                  const inset = this.pendingWebviewIdleInsetMapping.get(outputRequest);
                  this.pendingWebviewIdleCreationRequest.delete(outputRequest);
                  this.pendingWebviewIdleCreationRequest.delete(outputRequest);
                  const cellInfo = inset.cellInfo;
                  this.g.set(update.id, outputRequest);
                  this.insetMapping.set(outputRequest, inset);
                  this.notebookEditor.updateOutputHeight(cellInfo, outputRequest, height, !!update.init, "webview#dimension");
                  this.notebookEditor.scheduleOutputHeightAck(cellInfo, update.id, height);
                }
                this.c.delete(update.id);
              }
              {
                if (!update.init) {
                  continue;
                }
                const output = this.g.get(update.id);
                if (!output) {
                  continue;
                }
                const inset = this.insetMapping.get(output);
                inset.initialized = true;
              }
            } else {
              this.notebookEditor.updateMarkupCellHeight(update.id, height, !!update.init);
            }
          }
          break;
        }
        case "mouseenter": {
          const resolvedResult = this.kb(data.id);
          if (resolvedResult) {
            const latestCell = this.notebookEditor.getCellByInfo(resolvedResult.cellInfo);
            if (latestCell) {
              latestCell.outputIsHovered = true;
            }
          }
          break;
        }
        case "mouseleave": {
          const resolvedResult = this.kb(data.id);
          if (resolvedResult) {
            const latestCell = this.notebookEditor.getCellByInfo(resolvedResult.cellInfo);
            if (latestCell) {
              latestCell.outputIsHovered = false;
            }
          }
          break;
        }
        case "outputFocus": {
          const resolvedResult = this.kb(data.id);
          if (resolvedResult) {
            const latestCell = this.notebookEditor.getCellByInfo(resolvedResult.cellInfo);
            if (latestCell) {
              latestCell.outputIsFocused = true;
              this.notebookEditor.focusNotebookCell(latestCell, "output", { outputId: resolvedResult.output.model.outputId, skipReveal: true, outputWebviewFocused: true });
            }
          }
          break;
        }
        case "outputBlur": {
          const resolvedResult = this.kb(data.id);
          if (resolvedResult) {
            const latestCell = this.notebookEditor.getCellByInfo(resolvedResult.cellInfo);
            if (latestCell) {
              latestCell.outputIsFocused = false;
              latestCell.inputInOutputIsFocused = false;
            }
          }
          break;
        }
        case "scroll-ack": {
          break;
        }
        case "scroll-to-reveal": {
          this.notebookEditor.setScrollTop(data.scrollTop - $xJb);
          break;
        }
        case "did-scroll-wheel": {
          this.notebookEditor.triggerScroll({
            ...data.payload,
            preventDefault: () => {
            },
            stopPropagation: () => {
            }
          });
          break;
        }
        case "focus-editor": {
          const cell = this.notebookEditor.getCellById(data.cellId);
          if (cell) {
            if (data.focusNext) {
              this.notebookEditor.focusNextNotebookCell(cell, "editor");
            } else {
              await this.notebookEditor.focusNotebookCell(cell, "editor");
            }
          }
          break;
        }
        case "clicked-data-url": {
          this.tb(data);
          break;
        }
        case "clicked-link": {
          if ($0g(data.href, Schemas.command)) {
            const uri = URI.parse(data.href);
            if (uri.path === "workbench.action.openLargeOutput") {
              const outputId = uri.query;
              const group2 = this.Y.activeGroup;
              if (group2) {
                if (group2.activeEditor) {
                  group2.pinEditor(group2.activeEditor);
                }
              }
              this.J.open(CellUri.generateCellOutputUri(this.documentUri, outputId));
              return;
            }
            if (uri.path === "cellOutput.enableScrolling") {
              const outputId = uri.query;
              const cell = this.g.get(outputId);
              if (cell) {
                this.bb.publicLog2("workbenchActionExecuted", { id: "notebook.cell.toggleOutputScrolling", from: "inlineLink" });
                cell.cellViewModel.outputsViewModels.forEach((vm) => {
                  if (vm.model.metadata) {
                    vm.model.metadata["scrollable"] = true;
                    vm.resetRenderer();
                  }
                });
              }
              return;
            }
            this.J.open(data.href, {
              fromUserGesture: true,
              fromWorkspace: true,
              allowCommands: [
                "github-issues.authNow",
                "workbench.extensions.search",
                "workbench.action.openSettings",
                "_notebook.selectKernel",
                // TODO@rebornix explore open output channel with name command
                "jupyter.viewOutput"
              ]
            });
            return;
          }
          if ($$g(data.href, Schemas.http, Schemas.https, Schemas.mailto)) {
            this.J.open(data.href, { fromUserGesture: true, fromWorkspace: true });
          } else if ($0g(data.href, Schemas.vscodeNotebookCell)) {
            const uri = URI.parse(data.href);
            await this.pb(uri);
          } else if (!/^[\w\-]+:/.test(data.href)) {
            await this.qb(tryDecodeURIComponent(data.href));
          } else {
            if ($mc(data.href)) {
              this.rb(URI.file(data.href));
            } else {
              this.rb(URI.parse(data.href));
            }
          }
          break;
        }
        case "customKernelMessage": {
          this.m.fire({ message: data.message });
          break;
        }
        case "customRendererMessage": {
          this.H?.postMessage(data.rendererId, data.message);
          break;
        }
        case "clickMarkupCell": {
          const cell = this.notebookEditor.getCellById(data.cellId);
          if (cell) {
            if (data.shiftKey || ($m ? data.metaKey : data.ctrlKey)) {
              this.notebookEditor.toggleNotebookCellSelection(
                cell,
                /* fromPrevious */
                data.shiftKey
              );
            } else {
              await this.notebookEditor.focusNotebookCell(cell, "container", { skipReveal: true });
            }
          }
          break;
        }
        case "contextMenuMarkupCell": {
          const cell = this.notebookEditor.getCellById(data.cellId);
          if (cell) {
            await this.notebookEditor.focusNotebookCell(cell, "container", { skipReveal: true });
            const webviewRect = this.element.getBoundingClientRect();
            this.Q.showContextMenu({
              menuId: $bJ.NotebookCellTitle,
              contextKeyService: this.R,
              getAnchor: () => ({
                x: webviewRect.x + data.clientX,
                y: webviewRect.y + data.clientY
              })
            });
          }
          break;
        }
        case "toggleMarkupPreview": {
          const cell = this.notebookEditor.getCellById(data.cellId);
          if (cell && !this.notebookEditor.creationOptions.isReadOnly) {
            this.notebookEditor.setMarkupCellEditState(data.cellId, CellEditState.Editing);
            await this.notebookEditor.focusNotebookCell(cell, "editor", { skipReveal: true });
          }
          break;
        }
        case "mouseEnterMarkupCell": {
          const cell = this.notebookEditor.getCellById(data.cellId);
          if (cell instanceof $YIb) {
            cell.cellIsHovered = true;
          }
          break;
        }
        case "mouseLeaveMarkupCell": {
          const cell = this.notebookEditor.getCellById(data.cellId);
          if (cell instanceof $YIb) {
            cell.cellIsHovered = false;
          }
          break;
        }
        case "cell-drag-start": {
          this.notebookEditor.didStartDragMarkupCell(data.cellId, data);
          break;
        }
        case "cell-drag": {
          this.notebookEditor.didDragMarkupCell(data.cellId, data);
          break;
        }
        case "cell-drop": {
          this.notebookEditor.didDropMarkupCell(data.cellId, {
            dragOffsetY: data.dragOffsetY,
            ctrlKey: data.ctrlKey,
            altKey: data.altKey
          });
          break;
        }
        case "cell-drag-end": {
          this.notebookEditor.didEndDragMarkupCell(data.cellId);
          break;
        }
        case "renderedMarkup": {
          const cell = this.notebookEditor.getCellById(data.cellId);
          if (cell instanceof $YIb) {
            cell.renderedHtml = data.html;
          }
          this.sb(data.codeBlocks);
          break;
        }
        case "renderedCellOutput": {
          this.sb(data.codeBlocks);
          break;
        }
        case "outputResized": {
          this.notebookEditor.didResizeOutput(data.cellId);
          break;
        }
        case "getOutputItem": {
          const resolvedResult = this.kb(data.outputId);
          const output = resolvedResult?.output.model.outputs.find((output2) => output2.mime === data.mime);
          this.Eb({
            type: "returnOutputItem",
            requestId: data.requestId,
            output: output ? { mime: output.mime, valueBytes: output.data.buffer } : void 0
          });
          break;
        }
        case "logRendererDebugMessage": {
          this.cb(`${data.message}${data.data ? " " + JSON.stringify(data.data, null, 4) : ""}`);
          break;
        }
        case "notebookPerformanceMessage": {
          this.notebookEditor.updatePerformanceMetadata(data.cellId, data.executionId, data.duration, data.rendererId);
          if (data.mimeType && data.outputSize && data.rendererId === "vscode.builtin-renderer") {
            this.ob(data.mimeType, data.outputSize, data.duration);
          }
          break;
        }
        case "outputInputFocus": {
          const resolvedResult = this.kb(data.id);
          if (resolvedResult) {
            const latestCell = this.notebookEditor.getCellByInfo(resolvedResult.cellInfo);
            if (latestCell) {
              latestCell.inputInOutputIsFocused = data.inputFocused;
            }
          }
          this.notebookEditor.didFocusOutputInputChange(data.inputFocused);
        }
      }
    }));
    return initializePromise.p;
  }
  ob(mimeType, outputSize, renderTime) {
    const telemetryData = {
      mimeType,
      outputSize,
      renderTime
    };
    this.bb.publicLog2("NotebookCellOutputRender", telemetryData);
  }
  pb(uri) {
    const notebookResource = uri.path.length > 0 ? uri : this.documentUri;
    const lineMatch = /(?:^|&)line=([^&]+)/.exec(uri.query);
    let editorOptions2 = void 0;
    if (lineMatch) {
      const parsedLineNumber = parseInt(lineMatch[1], 10);
      if (!isNaN(parsedLineNumber)) {
        const lineNumber = parsedLineNumber;
        editorOptions2 = {
          selection: { startLineNumber: lineNumber, startColumn: 1 }
        };
      }
    }
    const executionMatch = /(?:^|&)execution_count=([^&]+)/.exec(uri.query);
    if (executionMatch) {
      const executionCount = parseInt(executionMatch[1], 10);
      if (!isNaN(executionCount)) {
        const notebookModel = this.L.getNotebookTextModel(notebookResource);
        const cell = notebookModel?.cells.slice().reverse().find((cell2) => {
          return cell2.internalMetadata.executionOrder === executionCount;
        });
        if (cell?.uri) {
          return this.J.open(cell.uri, {
            fromUserGesture: true,
            fromWorkspace: true,
            editorOptions: editorOptions2
          });
        }
      }
    }
    const fragmentLineMatch = /\?line=(\d+)$/.exec(uri.fragment);
    if (fragmentLineMatch) {
      const parsedLineNumber = parseInt(fragmentLineMatch[1], 10);
      if (!isNaN(parsedLineNumber)) {
        const lineNumber = parsedLineNumber + 1;
        const fragment = uri.fragment.substring(0, fragmentLineMatch.index);
        const editorOptions3 = {
          selection: { startLineNumber: lineNumber, startColumn: 1, endLineNumber: lineNumber, endColumn: 1 }
        };
        return this.J.open(notebookResource.with({ fragment }), {
          fromUserGesture: true,
          fromWorkspace: true,
          editorOptions: editorOptions3
        });
      }
    }
    return this.J.open(notebookResource, { fromUserGesture: true, fromWorkspace: true });
  }
  async qb(href) {
    let linkToOpen = void 0;
    let fragment = void 0;
    const hrefWithFragment = FRAGMENT_REGEX.exec(href);
    if (hrefWithFragment) {
      href = hrefWithFragment[1];
      fragment = hrefWithFragment[2];
    }
    if (href.startsWith("/")) {
      linkToOpen = await this.$.fileURI(href);
      const folders = this.X.getWorkspace().folders;
      if (folders.length) {
        linkToOpen = linkToOpen.with({
          scheme: folders[0].uri.scheme,
          authority: folders[0].uri.authority
        });
      }
    } else if (href.startsWith("~")) {
      const userHome = await this.$.userHome();
      if (userHome) {
        linkToOpen = URI.joinPath(userHome, href.substring(2));
      }
    } else {
      if (this.documentUri.scheme === Schemas.untitled) {
        const folders = this.X.getWorkspace().folders;
        if (!folders.length) {
          return;
        }
        linkToOpen = URI.joinPath(folders[0].uri, href);
      } else {
        linkToOpen = URI.joinPath($uh(this.documentUri), href);
      }
    }
    if (linkToOpen) {
      if (fragment) {
        linkToOpen = linkToOpen.with({ fragment });
      }
      this.rb(linkToOpen);
    }
  }
  rb(uri) {
    let lineNumber = void 0;
    let column = void 0;
    const lineCol = LINE_COLUMN_REGEX.exec(uri.path);
    if (lineCol) {
      uri = uri.with({
        path: uri.path.slice(0, lineCol.index),
        fragment: `L${lineCol[0].slice(1)}`
      });
      lineNumber = parseInt(lineCol[1], 10);
      column = parseInt(lineCol[2], 10);
    }
    const lineMatch = LineQueryRegex.exec(uri.query);
    if (lineMatch) {
      const parsedLineNumber = parseInt(lineMatch[1], 10);
      if (!isNaN(parsedLineNumber)) {
        lineNumber = parsedLineNumber + 1;
        column = 1;
        uri = uri.with({ fragment: `L${lineNumber}` });
      }
    }
    uri = uri.with({
      query: null
    });
    let match = void 0;
    for (const group2 of this.Y.groups) {
      const editorInput = group2.editors.find((editor) => editor.resource && $oh(editor.resource, uri, true));
      if (editorInput) {
        match = { group: group2, editor: editorInput };
        break;
      }
    }
    if (match) {
      const selection = lineNumber !== void 0 && column !== void 0 ? { startLineNumber: lineNumber, startColumn: column } : void 0;
      const textEditorOptions = { selection };
      match.group.openEditor(match.editor, selection ? textEditorOptions : void 0);
    } else {
      this.J.open(uri, { fromUserGesture: true, fromWorkspace: true });
    }
  }
  sb(codeBlocks) {
    for (const { id: id2, value, lang } of codeBlocks) {
      const languageId = this.W.getLanguageIdByLanguageName(lang);
      if (!languageId) {
        continue;
      }
      $o9(this.W, value, languageId).then((html3) => {
        if (this.s) {
          return;
        }
        this.Eb({
          type: "tokenizedCodeBlock",
          html: html3,
          codeBlockId: id2
        });
      });
    }
  }
  async tb(event) {
    if (typeof event.data !== "string") {
      return;
    }
    const [splitStart, splitData] = event.data.split(";base64,");
    if (!splitData || !splitStart) {
      return;
    }
    const defaultDir = $th(this.documentUri) === ".interactive" ? this.X.getWorkspace().folders[0]?.uri ?? await this.O.defaultFilePath() : $uh(this.documentUri);
    let defaultName;
    if (event.downloadName) {
      defaultName = event.downloadName;
    } else {
      const mimeType = splitStart.replace(/^data:/, "");
      const candidateExtension = mimeType && $2C(mimeType);
      defaultName = candidateExtension ? `download${candidateExtension}` : "download";
    }
    const defaultUri = $vh(defaultDir, defaultName);
    const newFileUri = await this.O.showSaveDialog({
      defaultUri
    });
    if (!newFileUri) {
      return;
    }
    const buff = $Vi(splitData);
    await this.P.writeFile(newFileUri, buff);
    await this.J.open(newFileUri);
  }
  ub(webviewService, content) {
    this.j = this.vb();
    const webview = webviewService.createWebviewElement({
      origin: $JJb_1.b(this.Z).getOrigin(this.notebookViewType, void 0),
      title: localize(8606, null),
      options: {
        purpose: "notebookRenderer",
        enableFindWidget: false,
        transformCssVariables: $BJb
      },
      contentOptions: {
        allowMultipleAPIAcquire: true,
        allowScripts: true,
        localResourceRoots: this.j
      },
      extension: void 0,
      providedViewType: "notebook.output"
    });
    webview.setHtml(content);
    webview.setContextKeyService(this.R);
    return webview;
  }
  vb() {
    const workspaceFolders = this.M.getWorkspace().folders.map((x) => x.uri);
    const notebookDir = this.lb();
    return [
      this.L.getNotebookProviderResourceRoots(),
      this.L.getRenderers().map((x) => $uh(x.entrypoint.path)),
      ...Array.from(this.L.getStaticPreloads(this.notebookViewType), (x) => [
        $uh(x.entrypoint),
        ...x.localResourceRoots
      ]),
      workspaceFolders,
      notebookDir,
      this.mb()
    ].flat();
  }
  wb() {
    this.r.clear();
    if (this.t) {
      this.Cb(this.t);
    }
    for (const [output, inset] of this.insetMapping.entries()) {
      this.Eb({ ...inset.cachedCreation, initiallyHidden: this.f.has(output) });
    }
    if (this.C?.isFirstInit) {
    } else {
      const mdCells = [...this.markupPreviewMapping.values()];
      this.markupPreviewMapping.clear();
      this.initializeMarkup(mdCells);
    }
    this.db();
    this.eb();
  }
  xb(cell, output, cellTop, outputOffset) {
    if (this.s) {
      return false;
    }
    if ("isOutputCollapsed" in cell && cell.isOutputCollapsed) {
      return false;
    }
    if (this.f.has(output)) {
      return true;
    }
    const outputCache = this.insetMapping.get(output);
    if (!outputCache) {
      return false;
    }
    if (outputOffset === outputCache.cachedCreation.outputOffset && cellTop === outputCache.cachedCreation.cellTop) {
      return false;
    }
    return true;
  }
  ackHeight(updates) {
    this.Eb({
      type: "ack-dimension",
      updates
    });
  }
  updateScrollTops(outputRequests, markupPreviews) {
    if (this.s) {
      return;
    }
    const widgets2 = $Mb(outputRequests.map((request) => {
      const outputCache = this.insetMapping.get(request.output);
      if (!outputCache) {
        return;
      }
      if (!request.forceDisplay && !this.xb(request.cell, request.output, request.cellTop, request.outputOffset)) {
        return;
      }
      const id2 = outputCache.outputId;
      outputCache.cachedCreation.cellTop = request.cellTop;
      outputCache.cachedCreation.outputOffset = request.outputOffset;
      this.f.delete(request.output);
      return {
        cellId: request.cell.id,
        outputId: id2,
        cellTop: request.cellTop,
        outputOffset: request.outputOffset,
        forceDisplay: request.forceDisplay
      };
    }));
    if (!widgets2.length && !markupPreviews.length) {
      return;
    }
    this.Eb({
      type: "view-scroll",
      widgets: widgets2,
      markupCells: markupPreviews
    });
  }
  async yb(initialization) {
    if (this.s) {
      return;
    }
    if (this.markupPreviewMapping.has(initialization.cellId)) {
      console.error("Trying to create markup preview that already exists");
      return;
    }
    this.markupPreviewMapping.set(initialization.cellId, initialization);
    this.Eb({
      type: "createMarkupCell",
      cell: initialization
    });
  }
  async showMarkupPreview(newContent) {
    if (this.s) {
      return;
    }
    const entry = this.markupPreviewMapping.get(newContent.cellId);
    if (!entry) {
      return this.yb(newContent);
    }
    const sameContent = newContent.content === entry.content;
    const sameMetadata = $Pv(newContent.metadata, entry.metadata);
    if (!sameContent || !sameMetadata || !entry.visible) {
      this.Eb({
        type: "showMarkupCell",
        id: newContent.cellId,
        handle: newContent.cellHandle,
        // If the content has not changed, we still want to make sure the
        // preview is visible but don't need to send anything over
        content: sameContent ? void 0 : newContent.content,
        top: newContent.offset,
        metadata: sameMetadata ? void 0 : newContent.metadata
      });
    }
    entry.metadata = newContent.metadata;
    entry.content = newContent.content;
    entry.offset = newContent.offset;
    entry.visible = true;
  }
  async hideMarkupPreviews(cellIds) {
    if (this.s) {
      return;
    }
    const cellsToHide = [];
    for (const cellId of cellIds) {
      const entry = this.markupPreviewMapping.get(cellId);
      if (entry) {
        if (entry.visible) {
          cellsToHide.push(cellId);
          entry.visible = false;
        }
      }
    }
    if (cellsToHide.length) {
      this.Eb({
        type: "hideMarkupCells",
        ids: cellsToHide
      });
    }
  }
  async unhideMarkupPreviews(cellIds) {
    if (this.s) {
      return;
    }
    const toUnhide = [];
    for (const cellId of cellIds) {
      const entry = this.markupPreviewMapping.get(cellId);
      if (entry) {
        if (!entry.visible) {
          entry.visible = true;
          toUnhide.push(cellId);
        }
      } else {
        console.error(`Trying to unhide a preview that does not exist: ${cellId}`);
      }
    }
    this.Eb({
      type: "unhideMarkupCells",
      ids: toUnhide
    });
  }
  async deleteMarkupPreviews(cellIds) {
    if (this.s) {
      return;
    }
    for (const id2 of cellIds) {
      if (!this.markupPreviewMapping.has(id2)) {
        console.error(`Trying to delete a preview that does not exist: ${id2}`);
      }
      this.markupPreviewMapping.delete(id2);
    }
    if (cellIds.length) {
      this.Eb({
        type: "deleteMarkupCell",
        ids: cellIds
      });
    }
  }
  async updateMarkupPreviewSelections(selectedCellsIds) {
    if (this.s) {
      return;
    }
    this.Eb({
      type: "updateSelectedMarkupCells",
      selectedCellIds: selectedCellsIds.filter((id2) => this.markupPreviewMapping.has(id2))
    });
  }
  async initializeMarkup(cells) {
    if (this.s) {
      return;
    }
    this.C?.p.complete();
    const requestId = $ps();
    this.C = { p: new $gi(), requestId, isFirstInit: this.u };
    this.u = false;
    for (const cell of cells) {
      this.markupPreviewMapping.set(cell.cellId, cell);
    }
    this.Eb({
      type: "initializeMarkup",
      cells,
      requestId
    });
    return this.C.p.p;
  }
  /**
   * Validate if cached inset is out of date and require a rerender
   * Note that it doesn't account for output content change.
   */
  zb(cachedInset, content) {
    if (content.type === 1) {
      return cachedInset.renderer?.id === content.renderer.id;
    } else {
      return cachedInset.cachedCreation.type === "html";
    }
  }
  requestCreateOutputWhenWebviewIdle(cellInfo, content, cellTop, offset) {
    if (this.s) {
      return;
    }
    if (this.insetMapping.has(content.source)) {
      return;
    }
    if (this.pendingWebviewIdleCreationRequest.has(content.source)) {
      return;
    }
    if (this.pendingWebviewIdleInsetMapping.has(content.source)) {
      return;
    }
    this.pendingWebviewIdleCreationRequest.set(content.source, $_h(() => {
      const { message, renderer, transfer: transferable } = this.Bb(cellInfo, content, cellTop, offset, true, true);
      this.Eb(message, transferable);
      this.pendingWebviewIdleInsetMapping.set(content.source, { outputId: message.outputId, versionId: content.source.model.versionId, cellInfo, renderer, cachedCreation: message });
      this.c.set(message.outputId, content.source);
      this.pendingWebviewIdleCreationRequest.delete(content.source);
    }));
  }
  createOutput(cellInfo, content, cellTop, offset) {
    if (this.s) {
      return;
    }
    const cachedInset = this.insetMapping.get(content.source);
    this.pendingWebviewIdleCreationRequest.get(content.source)?.dispose();
    this.pendingWebviewIdleCreationRequest.delete(content.source);
    this.pendingWebviewIdleInsetMapping.delete(content.source);
    if (cachedInset) {
      this.c.delete(cachedInset.outputId);
    }
    if (cachedInset && this.zb(cachedInset, content)) {
      this.f.delete(content.source);
      this.Eb({
        type: "showOutput",
        cellId: cachedInset.cellInfo.cellId,
        outputId: cachedInset.outputId,
        cellTop,
        outputOffset: offset
      });
      return;
    }
    const { message, renderer, transfer: transferable } = this.Bb(cellInfo, content, cellTop, offset, false, false);
    this.Eb(message, transferable);
    this.insetMapping.set(content.source, { outputId: message.outputId, versionId: content.source.model.versionId, cellInfo, renderer, cachedCreation: message });
    this.f.delete(content.source);
    this.g.set(message.outputId, content.source);
  }
  Ab(output, mimeType) {
    if (mimeType.startsWith("image")) {
      const buffer = output.outputs.find((out) => out.mime === "text/plain")?.data.buffer;
      if (buffer?.length && buffer?.length > 0) {
        const altText = new TextDecoder().decode(buffer);
        return { ...output.metadata, vscode_altText: altText };
      }
    }
    return output.metadata;
  }
  Bb(cellInfo, content, cellTop, offset, createOnIdle, initiallyHidden) {
    const messageBase = {
      type: "html",
      executionId: cellInfo.executionId,
      cellId: cellInfo.cellId,
      cellTop,
      outputOffset: offset,
      left: 0,
      requiredPreloads: [],
      createOnIdle
    };
    const transfer = [];
    let message;
    let renderer;
    if (content.type === 1) {
      const output = content.source.model;
      renderer = content.renderer;
      const first = output.outputs.find((op) => op.mime === content.mimeType);
      const metadata = this.Ab(output, content.mimeType);
      const valueBytes = copyBufferIfNeeded(first.data.buffer, transfer);
      message = {
        ...messageBase,
        outputId: output.outputId,
        rendererId: content.renderer.id,
        content: {
          type: 1,
          outputId: output.outputId,
          metadata,
          output: {
            mime: first.mime,
            valueBytes
          },
          allOutputs: output.outputs.map((output2) => ({ mime: output2.mime }))
        },
        initiallyHidden
      };
    } else {
      message = {
        ...messageBase,
        outputId: $ps(),
        content: {
          type: content.type,
          htmlContent: content.htmlContent
        },
        initiallyHidden
      };
    }
    return {
      message,
      renderer,
      transfer
    };
  }
  updateOutput(cellInfo, content, cellTop, offset) {
    if (this.s) {
      return;
    }
    if (!this.insetMapping.has(content.source)) {
      this.createOutput(cellInfo, content, cellTop, offset);
      return;
    }
    const outputCache = this.insetMapping.get(content.source);
    if (outputCache.versionId === content.source.model.versionId) {
      return;
    }
    this.f.delete(content.source);
    let updatedContent = void 0;
    const transfer = [];
    if (content.type === 1) {
      const output = content.source.model;
      const firstBuffer = output.outputs.find((op) => op.mime === content.mimeType);
      const appenededData = output.appendedSinceVersion(outputCache.versionId, content.mimeType);
      const appended = appenededData ? { valueBytes: appenededData.buffer, previousVersion: outputCache.versionId } : void 0;
      const valueBytes = copyBufferIfNeeded(firstBuffer.data.buffer, transfer);
      updatedContent = {
        type: 1,
        outputId: outputCache.outputId,
        metadata: output.metadata,
        output: {
          mime: content.mimeType,
          valueBytes,
          appended
        },
        allOutputs: output.outputs.map((output2) => ({ mime: output2.mime }))
      };
    }
    this.Eb({
      type: "showOutput",
      cellId: outputCache.cellInfo.cellId,
      outputId: outputCache.outputId,
      cellTop,
      outputOffset: offset,
      content: updatedContent
    }, transfer);
    outputCache.versionId = content.source.model.versionId;
    return;
  }
  async copyImage(output) {
    this.Eb({
      type: "copyImage",
      outputId: output.model.outputId,
      altOutputId: output.model.alternativeOutputId
    });
  }
  removeInsets(outputs) {
    if (this.s) {
      return;
    }
    for (const output of outputs) {
      const outputCache = this.insetMapping.get(output);
      if (!outputCache) {
        continue;
      }
      const id2 = outputCache.outputId;
      this.Eb({
        type: "clearOutput",
        rendererId: outputCache.cachedCreation.rendererId,
        cellUri: outputCache.cellInfo.cellUri.toString(),
        outputId: id2,
        cellId: outputCache.cellInfo.cellId
      });
      this.insetMapping.delete(output);
      this.pendingWebviewIdleCreationRequest.get(output)?.dispose();
      this.pendingWebviewIdleCreationRequest.delete(output);
      this.pendingWebviewIdleInsetMapping.delete(output);
      this.c.delete(id2);
      this.g.delete(id2);
    }
  }
  hideInset(output) {
    if (this.s) {
      return;
    }
    const outputCache = this.insetMapping.get(output);
    if (!outputCache) {
      return;
    }
    this.f.add(output);
    this.Eb({
      type: "hideOutput",
      outputId: outputCache.outputId,
      cellId: outputCache.cellInfo.cellId
    });
  }
  focusWebview() {
    if (this.s) {
      return;
    }
    this.webview?.focus();
  }
  selectOutputContents(cell) {
    if (this.s) {
      return;
    }
    const output = cell.outputsViewModels.find((o) => o.model.outputId === cell.focusedOutputId);
    const outputId = output ? this.insetMapping.get(output)?.outputId : void 0;
    this.Eb({
      type: "select-output-contents",
      cellOrOutputId: outputId || cell.id
    });
  }
  selectInputContents(cell) {
    if (this.s) {
      return;
    }
    const output = cell.outputsViewModels.find((o) => o.model.outputId === cell.focusedOutputId);
    const outputId = output ? this.insetMapping.get(output)?.outputId : void 0;
    this.Eb({
      type: "select-input-contents",
      cellOrOutputId: outputId || cell.id
    });
  }
  focusOutput(cellOrOutputId, alternateId, viewFocused) {
    if (this.s) {
      return;
    }
    if (!viewFocused) {
      this.webview?.focus();
    }
    this.Eb({
      type: "focus-output",
      cellOrOutputId,
      alternateId
    });
  }
  blurOutput() {
    if (this.s) {
      return;
    }
    this.Eb({
      type: "blur-output"
    });
  }
  async find(query, options3) {
    if (query === "") {
      this.Eb({
        type: "findStop",
        ownerID: options3.ownerID
      });
      return [];
    }
    const p = new Promise((resolve) => {
      const sub = this.webview?.onMessage((e) => {
        if (e.message.type === "didFind") {
          resolve(e.message.matches);
          sub?.dispose();
        }
      });
    });
    this.Eb({
      type: "find",
      query,
      options: options3
    });
    const ret = await p;
    return ret;
  }
  findStop(ownerID) {
    this.Eb({
      type: "findStop",
      ownerID
    });
  }
  async findHighlightCurrent(index, ownerID) {
    const p = new Promise((resolve) => {
      const sub = this.webview?.onMessage((e) => {
        if (e.message.type === "didFindHighlightCurrent") {
          resolve(e.message.offset);
          sub?.dispose();
        }
      });
    });
    this.Eb({
      type: "findHighlightCurrent",
      index,
      ownerID
    });
    const ret = await p;
    return ret;
  }
  async findUnHighlightCurrent(index, ownerID) {
    this.Eb({
      type: "findUnHighlightCurrent",
      index,
      ownerID
    });
  }
  deltaCellContainerClassNames(cellId, added, removed) {
    this.Eb({
      type: "decorations",
      cellId,
      addedClassNames: added,
      removedClassNames: removed
    });
  }
  updateOutputRenderers() {
    if (!this.webview) {
      return;
    }
    const renderersData = this.hb();
    this.j = this.vb();
    const mixedResourceRoots = [
      ...this.j || [],
      ...this.t ? [this.t.localResourceRoot] : []
    ];
    this.webview.localResourcesRoot = mixedResourceRoots;
    this.Eb({
      type: "updateRenderers",
      rendererData: renderersData
    });
  }
  async updateKernelPreloads(kernel) {
    if (this.s || kernel === this.t) {
      return;
    }
    const previousKernel = this.t;
    this.t = kernel;
    if (previousKernel && previousKernel.preloadUris.length > 0) {
      this.webview?.reload();
    } else if (kernel) {
      this.Cb(kernel);
    }
  }
  Cb(kernel) {
    const resources = [];
    for (const preload of kernel.preloadUris) {
      const uri = this.N.isExtensionDevelopment && (preload.scheme === "http" || preload.scheme === "https") ? preload : this.jb(preload, void 0);
      if (!this.r.has(uri.toString())) {
        resources.push({ uri: uri.toString(), originalUri: preload.toString() });
        this.r.add(uri.toString());
      }
    }
    if (!resources.length) {
      return;
    }
    this.Db(resources);
  }
  Db(resources) {
    if (!this.webview) {
      return;
    }
    const mixedResourceRoots = [
      ...this.j || [],
      ...this.t ? [this.t.localResourceRoot] : []
    ];
    this.webview.localResourcesRoot = mixedResourceRoots;
    this.Eb({
      type: "preload",
      resources
    });
  }
  Eb(message, transfer) {
    if (this.s) {
      return;
    }
    this.webview?.postMessage(message, transfer);
  }
  dispose() {
    this.s = true;
    this.webview?.dispose();
    this.webview = void 0;
    this.notebookEditor = null;
    this.insetMapping.clear();
    this.pendingWebviewIdleCreationRequest.clear();
    super.dispose();
  }
};
$JJb = $JJb_1 = __decorate([
  __param(6, $Crb),
  __param(7, $O4),
  __param(8, $mrb),
  __param(9, $Zk),
  __param(10, $US),
  __param(11, $1v),
  __param(12, $km),
  __param(13, $50),
  __param(14, $on),
  __param(15, $4M),
  __param(16, $kl),
  __param(17, $1E),
  __param(18, $Zk),
  __param(19, $iJ),
  __param(20, $jv),
  __param(21, $aT),
  __param(22, $qFb),
  __param(23, $gs),
  __param(24, $zv)
], $JJb);
function copyBufferIfNeeded(buffer, transfer) {
  if (buffer.byteLength === buffer.buffer.byteLength) {
    return buffer;
  } else {
    const valueBytes = new Uint8Array(buffer);
    transfer.push(valueBytes.buffer);
    return valueBytes;
  }
}
function getTokenizationCss() {
  const colorMap = $YE.getColorMap();
  const tokenizationCss = colorMap ? $4Gb(colorMap) : "";
  return tokenizationCss;
}
function tryDecodeURIComponent(uri) {
  try {
    return decodeURIComponent(uri);
  } catch {
    return uri;
  }
}

// out-build/vs/workbench/contrib/notebook/browser/view/cellParts/chat/cellChatPart.js
var $KJb = class extends $lJb {
  // private _controller: NotebookCellChatController | undefined;
  get activeCell() {
    return this.c;
  }
  constructor(_notebookEditor, _partContainer) {
    super();
  }
  didRenderCell(element) {
    super.didRenderCell(element);
  }
  unrenderCell(element) {
    super.unrenderCell(element);
  }
  updateInternalLayoutNow(element) {
  }
  dispose() {
    super.dispose();
  }
};

// out-build/vs/workbench/contrib/notebook/browser/view/cellParts/cellComments.js
var $lKb = class $lKb2 extends $lJb {
  constructor(g, h3, j, m, n, r2, s) {
    super();
    this.g = g;
    this.h = h3;
    this.j = j;
    this.m = m;
    this.n = n;
    this.r = r2;
    this.s = s;
    this.h.classList.add("review-widget");
    this.B(this.a = new $_c());
    this.B(this.m.onDidColorThemeChange(this.F, this));
    this.F();
  }
  async t(element) {
    if (this.b === element) {
      return;
    }
    this.b = element;
    await this.y();
  }
  async u(owner, commentThread) {
    const widgetDisposables = new $2c();
    const widget = this.s.createInstance($kKb, this.h, this.g, owner, this.g.textModel.uri, this.j, this.s, commentThread, void 0, void 0, {
      codeBlockFontFamily: this.r.getValue("editor").fontFamily || EDITOR_FONT_DEFAULTS.fontFamily
    }, void 0, {
      actionRunner: () => {
      },
      collapse: () => {
      }
    });
    widgetDisposables.add(widget);
    this.a.set(commentThread.threadId, { widget, dispose: () => widgetDisposables.dispose() });
    const layoutInfo = this.g.getLayoutInfo();
    await widget.display(layoutInfo.fontInfo.lineHeight, true);
    this.F();
    widgetDisposables.add(widget.onDidResize(() => {
      if (this.b) {
        this.b.commentHeight = this.z(widget.getDimensions().height);
      }
    }));
  }
  w() {
    this.f.add(this.n.onDidUpdateCommentThreads(async () => this.y()));
  }
  async y() {
    if (!this.b) {
      return;
    }
    const infos = await this.D(this.b);
    const widgetsToDelete = new Set(this.a.keys());
    const layoutInfo = this.b.layoutInfo;
    this.h.style.top = `${layoutInfo.commentOffset}px`;
    for (const info of infos) {
      if (!info) {
        continue;
      }
      for (const thread of info.threads) {
        widgetsToDelete.delete(thread.threadId);
        const widget = this.a.get(thread.threadId)?.widget;
        if (widget) {
          await widget.updateCommentThread(thread);
        } else {
          await this.u(info.uniqueOwner, thread);
        }
      }
    }
    for (const threadId of widgetsToDelete) {
      this.a.deleteAndDispose(threadId);
    }
    this.C();
  }
  z(bodyHeight) {
    const layoutInfo = this.g.getLayoutInfo();
    const headHeight = Math.ceil(layoutInfo.fontInfo.lineHeight * 1.2);
    const lineHeight = layoutInfo.fontInfo.lineHeight;
    const arrowHeight = Math.round(lineHeight / 3);
    const frameThickness = Math.round(lineHeight / 9) * 2;
    const computedHeight = headHeight + bodyHeight + arrowHeight + frameThickness + 8;
    return computedHeight;
  }
  C() {
    if (!this.b) {
      return;
    }
    let height = 0;
    for (const { widget } of this.a.values()) {
      height += this.z(widget.getDimensions().height);
    }
    this.b.commentHeight = height;
  }
  async D(element) {
    if (this.g.hasModel()) {
      return $Mb(await this.n.getNotebookComments(element.uri));
    }
    return [];
  }
  F() {
    const theme = this.m.getColorTheme();
    const fontInfo = this.g.getLayoutInfo().fontInfo;
    for (const { widget } of this.a.values()) {
      widget.applyTheme(theme, fontInfo);
    }
  }
  didRenderCell(element) {
    this.t(element);
    this.w();
  }
  prepareLayout() {
    this.C();
  }
  updateInternalLayoutNow(element) {
    if (this.b) {
      this.h.style.top = `${element.layoutInfo.commentOffset}px`;
    }
  }
};
$lKb = __decorate([
  __param(2, $on),
  __param(3, $gs),
  __param(4, $RJb),
  __param(5, $kl),
  __param(6, $Pk)
], $lKb);

// out-build/vs/workbench/contrib/notebook/browser/view/cellParts/cellDecorations.js
var $mKb = class extends $lJb {
  constructor(notebookEditor, rootContainer, decorationContainer) {
    super();
    this.notebookEditor = notebookEditor;
    this.rootContainer = rootContainer;
    this.decorationContainer = decorationContainer;
  }
  didRenderCell(element) {
    const removedClassNames = [];
    this.rootContainer.classList.forEach((className) => {
      if (/^nb\-.*$/.test(className)) {
        removedClassNames.push(className);
      }
    });
    removedClassNames.forEach((className) => {
      this.rootContainer.classList.remove(className);
    });
    this.decorationContainer.innerText = "";
    const generateCellTopDecorations = () => {
      this.decorationContainer.innerText = "";
      element.getCellDecorations().filter((options3) => options3.topClassName !== void 0).forEach((options3) => {
        this.decorationContainer.append($(`.${options3.topClassName}`));
      });
    };
    this.f.add(element.onCellDecorationsChanged((e) => {
      const modified = e.added.find((e2) => e2.topClassName) || e.removed.find((e2) => e2.topClassName);
      if (modified) {
        generateCellTopDecorations();
      }
    }));
    generateCellTopDecorations();
    this.a();
  }
  a() {
    if (!this.c) {
      return;
    }
    this.f.add(this.c.onCellDecorationsChanged((e) => {
      e.added.forEach((options3) => {
        if (options3.className && this.c) {
          this.rootContainer.classList.add(options3.className);
          this.notebookEditor.deltaCellContainerClassNames(this.c.id, [options3.className], []);
        }
        if (options3.outputClassName && this.c) {
          this.notebookEditor.deltaCellContainerClassNames(this.c.id, [options3.outputClassName], []);
        }
      });
      e.removed.forEach((options3) => {
        if (options3.className && this.c) {
          this.rootContainer.classList.remove(options3.className);
          this.notebookEditor.deltaCellContainerClassNames(this.c.id, [], [options3.className]);
        }
        if (options3.outputClassName && this.c) {
          this.notebookEditor.deltaCellContainerClassNames(this.c.id, [], [options3.outputClassName]);
        }
      });
    }));
    this.c.getCellDecorations().forEach((options3) => {
      if (options3.className && this.c) {
        this.rootContainer.classList.add(options3.className);
        this.notebookEditor.deltaCellContainerClassNames(this.c.id, [options3.className], []);
      }
      if (options3.outputClassName && this.c) {
        this.notebookEditor.deltaCellContainerClassNames(this.c.id, [options3.outputClassName], []);
      }
    });
  }
};

// out-build/vs/workbench/contrib/notebook/browser/view/cellParts/cellDragRenderer.js
var EditorTextRenderer = class _EditorTextRenderer {
  static {
    this.a = $W1("cellRendererEditorText", {
      createHTML(input) {
        return input;
      }
    });
  }
  getRichText(editor, modelRange) {
    const model = editor.getModel();
    if (!model) {
      return null;
    }
    const colorMap = this.d();
    const fontInfo = editor.getOptions().get(
      52
      /* EditorOption.fontInfo */
    );
    const fontFamilyVar = "--notebook-editor-font-family";
    const fontSizeVar = "--notebook-editor-font-size";
    const fontWeightVar = "--notebook-editor-font-weight";
    const style = `color: ${colorMap[
      1
      /* ColorId.DefaultForeground */
    ]};background-color: ${colorMap[
      2
      /* ColorId.DefaultBackground */
    ]};font-family: var(${fontFamilyVar});font-weight: var(${fontWeightVar});font-size: var(${fontSizeVar});line-height: ${fontInfo.lineHeight}px;white-space: pre;`;
    const element = $("div", { style });
    const fontSize = fontInfo.fontSize;
    const fontWeight = fontInfo.fontWeight;
    element.style.setProperty(fontFamilyVar, fontInfo.fontFamily);
    element.style.setProperty(fontSizeVar, `${fontSize}px`);
    element.style.setProperty(fontWeightVar, fontWeight);
    const linesHtml = this.b(model, modelRange, colorMap);
    element.innerHTML = linesHtml;
    return element;
  }
  b(model, modelRange, colorMap) {
    const startLineNumber = modelRange.startLineNumber;
    const startColumn = modelRange.startColumn;
    const endLineNumber = modelRange.endLineNumber;
    const endColumn = modelRange.endColumn;
    const tabSize = model.getOptions().tabSize;
    let result = "";
    for (let lineNumber = startLineNumber; lineNumber <= endLineNumber; lineNumber++) {
      const lineTokens = model.tokenization.getLineTokens(lineNumber);
      const lineContent = lineTokens.getLineContent();
      const startOffset = lineNumber === startLineNumber ? startColumn - 1 : 0;
      const endOffset = lineNumber === endLineNumber ? endColumn - 1 : lineContent.length;
      if (lineContent === "") {
        result += "<br>";
      } else {
        result += $p9(lineContent, lineTokens.inflate(), colorMap, startOffset, endOffset, tabSize, $l);
      }
    }
    return _EditorTextRenderer.a?.createHTML(result) ?? result;
  }
  d() {
    const colorMap = $YE.getColorMap();
    const result = ["#000000"];
    if (colorMap) {
      for (let i2 = 1, len = colorMap.length; i2 < len; i2++) {
        result[i2] = $Vn.Format.CSS.formatHex(colorMap[i2]);
      }
    }
    return result;
  }
};
var $nKb = class {
  getDragImage(templateData, editor, type) {
    let dragImage = this.a(templateData, editor, type);
    if (!dragImage) {
      dragImage = document.createElement("div");
      dragImage.textContent = "1 cell";
    }
    return dragImage;
  }
  a(templateData, editor, type) {
    const dragImageContainer = templateData.container.cloneNode(true);
    dragImageContainer.classList.forEach((c) => dragImageContainer.classList.remove(c));
    dragImageContainer.classList.add("cell-drag-image", "monaco-list-row", "focused", `${type}-cell-row`);
    const editorContainer = dragImageContainer.querySelector(".cell-editor-container");
    if (!editorContainer) {
      return null;
    }
    const richEditorText = new EditorTextRenderer().getRichText(editor, new $9C(1, 1, 1, 1e3));
    if (!richEditorText) {
      return null;
    }
    $dk(editorContainer, richEditorText);
    return dragImageContainer;
  }
};

// out-build/vs/workbench/contrib/notebook/browser/view/cellParts/cellEditorOptions.js
var $oKb = class extends $lJb {
  set tabSize(value) {
    if (this.b !== value) {
      this.b = value;
      this.j.fire();
    }
  }
  get tabSize() {
    return this.b;
  }
  set indentSize(value) {
    if (this.g !== value) {
      this.g = value;
      this.j.fire();
    }
  }
  get indentSize() {
    return this.g;
  }
  set insertSpaces(value) {
    if (this.h !== value) {
      this.h = value;
      this.j.fire();
    }
  }
  get insertSpaces() {
    return this.h;
  }
  constructor(n, notebookOptions, configurationService) {
    super();
    this.n = n;
    this.notebookOptions = notebookOptions;
    this.configurationService = configurationService;
    this.a = "inherit";
    this.j = this.B(new $ze());
    this.onDidChange = this.j.event;
    this.B(n.onDidChange(() => {
      this.r();
    }));
    this.m = this.s();
  }
  updateState(element, e) {
    if (e.cellLineNumberChanged) {
      this.setLineNumbers(element.lineNumbers);
    }
  }
  r() {
    this.m = this.s();
    this.j.fire();
  }
  s() {
    const value = this.n.value;
    const cellEditorOverridesRaw = this.notebookOptions.getDisplayOptions().editorOptionsCustomizations;
    const indentSize = cellEditorOverridesRaw?.["editor.indentSize"];
    if (indentSize !== void 0) {
      this.indentSize = indentSize;
    }
    const insertSpaces = cellEditorOverridesRaw?.["editor.insertSpaces"];
    if (insertSpaces !== void 0) {
      this.insertSpaces = insertSpaces;
    }
    const tabSize = cellEditorOverridesRaw?.["editor.tabSize"];
    if (tabSize !== void 0) {
      this.tabSize = tabSize;
    }
    let cellRenderLineNumber = value.lineNumbers;
    switch (this.a) {
      case "inherit":
        if (this.configurationService.getValue("notebook.lineNumbers") === "on") {
          if (value.lineNumbers === "off") {
            cellRenderLineNumber = "on";
          }
        } else {
          cellRenderLineNumber = "off";
        }
        break;
      case "on":
        if (value.lineNumbers === "off") {
          cellRenderLineNumber = "on";
        }
        break;
      case "off":
        cellRenderLineNumber = "off";
        break;
    }
    if (value.lineNumbers !== cellRenderLineNumber) {
      return {
        ...value,
        ...{ lineNumbers: cellRenderLineNumber }
      };
    } else {
      return Object.assign({}, value);
    }
  }
  getUpdatedValue(internalMetadata, cellUri) {
    const options3 = this.getValue(internalMetadata, cellUri);
    delete options3.hover;
    return options3;
  }
  getValue(internalMetadata, cellUri) {
    return {
      ...this.m,
      ...{
        padding: this.notebookOptions.computeEditorPadding(internalMetadata, cellUri)
      }
    };
  }
  getDefaultValue() {
    return {
      ...this.m,
      ...{
        padding: { top: 12, bottom: 12 }
      }
    };
  }
  setLineNumbers(lineNumbers) {
    this.a = lineNumbers;
    this.r();
  }
};
$Wn.as($Ht.Configuration).registerConfiguration({
  id: "notebook",
  order: 100,
  type: "object",
  "properties": {
    "notebook.lineNumbers": {
      type: "string",
      enum: ["off", "on"],
      default: "off",
      markdownDescription: localize(8577, null)
    }
  }
});
$hJ(class ToggleLineNumberAction extends $gJ {
  constructor() {
    super({
      id: "notebook.toggleLineNumbers",
      title: localize2(8580, "Toggle Notebook Line Numbers"),
      precondition: $WAb,
      menu: [
        {
          id: $bJ.NotebookToolbar,
          group: "notebookLayout",
          order: 2,
          when: $7m.equals("config.notebook.globalToolbar", true)
        }
      ],
      category: $xIb,
      f1: true,
      toggled: {
        condition: $7m.notEquals("config.notebook.lineNumbers", "off"),
        title: localize(8578, null)
      }
    });
  }
  async run(accessor) {
    const configurationService = accessor.get($kl);
    const renderLiNumbers = configurationService.getValue("notebook.lineNumbers") === "on";
    if (renderLiNumbers) {
      configurationService.updateValue("notebook.lineNumbers", "off");
    } else {
      configurationService.updateValue("notebook.lineNumbers", "on");
    }
  }
});
$hJ(class ToggleActiveLineNumberAction extends $GIb {
  constructor() {
    super({
      id: "notebook.cell.toggleLineNumbers",
      title: localize(8579, null),
      precondition: $Dpb.isEqualTo($bM),
      menu: [{
        id: $bJ.NotebookCellTitle,
        group: "View",
        order: 1
      }],
      toggled: $7m.or($cBb.isEqualTo("on"), $7m.and($cBb.isEqualTo("inherit"), $7m.equals("config.notebook.lineNumbers", "on")))
    });
  }
  async runWithContext(accessor, context) {
    if (context.ui) {
      this.a(accessor.get($kl), context.cell);
    } else {
      const configurationService = accessor.get($kl);
      context.selectedCells.forEach((cell) => {
        this.a(configurationService, cell);
      });
    }
  }
  a(configurationService, cell) {
    const renderLineNumbers = configurationService.getValue("notebook.lineNumbers") === "on";
    const cellLineNumbers = cell.lineNumbers;
    const currentLineNumberIsOn = cellLineNumbers === "on" || cellLineNumbers === "inherit" && renderLineNumbers;
    if (currentLineNumberIsOn) {
      cell.lineNumbers = "off";
    } else {
      cell.lineNumbers = "on";
    }
  }
});

// out-build/vs/workbench/contrib/notebook/browser/view/cellParts/cellExecution.js
var UPDATE_EXECUTION_ORDER_GRACE_PERIOD = 200;
var $pKb = class $pKb2 extends $lJb {
  constructor(b, g, h3) {
    super();
    this.b = b;
    this.g = g;
    this.h = h3;
    this.a = this.B(new $2c());
    this.B(this.b.onDidChangeActiveKernel(() => {
      if (this.c) {
        this.a.clear();
        if (this.b.activeKernel) {
          this.a.add(this.b.activeKernel.onDidChange(() => {
            if (this.c) {
              this.j(this.c.internalMetadata);
            }
          }));
        }
        this.j(this.c.internalMetadata);
      }
    }));
    this.B(this.b.onDidScroll(() => {
      this.m();
    }));
  }
  didRenderCell(element) {
    this.j(element.internalMetadata, true);
  }
  j(internalMetadata, forceClear = false) {
    if (this.b.activeKernel?.implementsExecutionOrder || !this.b.activeKernel && typeof internalMetadata.executionOrder === "number") {
      if (typeof internalMetadata.executionOrder !== "number" && !forceClear && !!this.h.getCellExecution(this.c.uri)) {
        const renderingCell = this.c;
        $Xh(() => {
          if (this.c === renderingCell) {
            this.j(this.c.internalMetadata, true);
          }
        }, UPDATE_EXECUTION_ORDER_GRACE_PERIOD, this.f);
        return;
      }
      const executionOrderLabel = typeof internalMetadata.executionOrder === "number" ? `[${internalMetadata.executionOrder}]` : "[ ]";
      this.g.innerText = executionOrderLabel;
    } else {
      this.g.innerText = "";
    }
  }
  updateState(element, e) {
    if (e.internalMetadataChanged) {
      this.j(element.internalMetadata);
    }
  }
  updateInternalLayoutNow(element) {
    this.m();
  }
  m() {
    if (this.c) {
      if (this.c.isInputCollapsed) {
        $ik(this.g);
      } else {
        $hk(this.g);
        let top2 = this.c.layoutInfo.editorHeight - 22 + this.c.layoutInfo.statusBarHeight;
        if (this.c instanceof $XIb) {
          const elementTop = this.b.getAbsoluteTopOfElement(this.c);
          const editorBottom = elementTop + this.c.layoutInfo.outputContainerOffset;
          const scrollBottom = this.b.scrollBottom;
          const lineHeight = 22;
          if (scrollBottom <= editorBottom) {
            const offset = editorBottom - scrollBottom;
            top2 -= offset;
            top2 = $4i(
              top2,
              lineHeight + 12,
              // line height + padding for single line
              this.c.layoutInfo.editorHeight - lineHeight + this.c.layoutInfo.statusBarHeight
            );
          }
        }
        this.g.style.top = `${top2}px`;
      }
    }
  }
};
$pKb = __decorate([
  __param(2, $wL)
], $pKb);

// out-build/vs/workbench/contrib/notebook/browser/view/cellParts/cellFocus.js
var $qKb = class extends $lJb {
  constructor(containerElement, focusSinkElement, notebookEditor) {
    super();
    this.B($_i(containerElement, $7j.FOCUS, () => {
      if (this.c) {
        notebookEditor.focusElement(this.c);
      }
    }, true));
    if (focusSinkElement) {
      this.B($_i(focusSinkElement, $7j.FOCUS, () => {
        if (this.c && this.c.outputsViewModels.length) {
          notebookEditor.focusNotebookCell(this.c, "output");
        }
      }));
    }
  }
};

// out-build/vs/workbench/contrib/notebook/browser/view/cellParts/cellFocusIndicator.js
var $xKb = class extends $lJb {
  constructor(notebookEditor, titleToolbar, top2, left, right, bottom) {
    super();
    this.notebookEditor = notebookEditor;
    this.titleToolbar = titleToolbar;
    this.top = top2;
    this.left = left;
    this.right = right;
    this.bottom = bottom;
    this.codeFocusIndicator = new $nZ($bk(this.left.domNode, $(".codeOutput-focus-indicator-container", void 0, $(".codeOutput-focus-indicator.code-focus-indicator"))));
    this.outputFocusIndicator = new $nZ($bk(this.left.domNode, $(".codeOutput-focus-indicator-container", void 0, $(".codeOutput-focus-indicator.output-focus-indicator"))));
    this.B($_i(this.codeFocusIndicator.domNode, $7j.CLICK, () => {
      if (this.c) {
        this.c.isInputCollapsed = !this.c.isInputCollapsed;
      }
    }));
    this.B($_i(this.outputFocusIndicator.domNode, $7j.CLICK, () => {
      if (this.c) {
        this.c.isOutputCollapsed = !this.c.isOutputCollapsed;
      }
    }));
    this.B($_i(this.left.domNode, $7j.DBLCLICK, (e) => {
      if (!this.c || !this.notebookEditor.hasModel()) {
        return;
      }
      if (e.target !== this.left.domNode) {
        return;
      }
      const clickedOnInput = e.offsetY < this.c.layoutInfo.outputContainerOffset;
      if (clickedOnInput) {
        this.c.isInputCollapsed = !this.c.isInputCollapsed;
      } else {
        this.c.isOutputCollapsed = !this.c.isOutputCollapsed;
      }
    }));
    this.B(this.titleToolbar.onDidUpdateActions(() => {
      this.a();
    }));
  }
  updateInternalLayoutNow(element) {
    if (element.cellKind === CellKind.Markup) {
      const indicatorPostion = this.notebookEditor.notebookOptions.computeIndicatorPosition(element.layoutInfo.totalHeight, element.layoutInfo.foldHintHeight, this.notebookEditor.textModel?.viewType);
      this.bottom.domNode.style.transform = `translateY(${indicatorPostion.bottomIndicatorTop + 6}px)`;
      this.left.setHeight(indicatorPostion.verticalIndicatorHeight);
      this.right.setHeight(indicatorPostion.verticalIndicatorHeight);
      this.codeFocusIndicator.setHeight(indicatorPostion.verticalIndicatorHeight - this.b() * 2 - element.layoutInfo.chatHeight);
    } else {
      const cell = element;
      const layoutInfo = this.notebookEditor.notebookOptions.getLayoutConfiguration();
      const bottomToolbarDimensions = this.notebookEditor.notebookOptions.computeBottomToolbarDimensions(this.notebookEditor.textModel?.viewType);
      const indicatorHeight = cell.layoutInfo.codeIndicatorHeight + cell.layoutInfo.outputIndicatorHeight + cell.layoutInfo.commentHeight;
      this.left.setHeight(indicatorHeight);
      this.right.setHeight(indicatorHeight);
      this.codeFocusIndicator.setHeight(cell.layoutInfo.codeIndicatorHeight);
      this.outputFocusIndicator.setHeight(Math.max(cell.layoutInfo.outputIndicatorHeight - cell.viewContext.notebookOptions.getLayoutConfiguration().focusIndicatorGap, 0));
      this.bottom.domNode.style.transform = `translateY(${cell.layoutInfo.totalHeight - bottomToolbarDimensions.bottomToolbarGap - layoutInfo.cellBottomMargin}px)`;
    }
    this.a();
  }
  a() {
    const y = (this.c?.layoutInfo.chatHeight ?? 0) + this.b();
    this.left.domNode.style.transform = `translateY(${y}px)`;
    this.right.domNode.style.transform = `translateY(${y}px)`;
  }
  b() {
    const layoutInfo = this.notebookEditor.notebookOptions.getLayoutConfiguration();
    if (this.titleToolbar.hasActions) {
      return layoutInfo.editorToolbarHeight + layoutInfo.cellTopMargin;
    } else {
      return layoutInfo.cellTopMargin;
    }
  }
};

// out-build/vs/workbench/contrib/notebook/browser/view/cellParts/cellProgressBar.js
var $yKb = class $yKb2 extends $lJb {
  constructor(editorContainer, collapsedInputContainer, g) {
    super();
    this.g = g;
    this.a = this.B(new $02(editorContainer, $s$));
    this.a.hide();
    this.b = this.B(new $02(collapsedInputContainer, $s$));
    this.b.hide();
  }
  didRenderCell(element) {
    this.h(element);
  }
  updateForExecutionState(element, e) {
    this.h(element, e);
  }
  updateState(element, e) {
    if (e.metadataChanged || e.internalMetadataChanged) {
      this.h(element);
    }
    if (e.inputCollapsedChanged) {
      const exeState = this.g.getCellExecution(element.uri);
      if (element.isInputCollapsed) {
        this.a.hide();
        if (exeState?.state === NotebookCellExecutionState.Executing) {
          this.h(element);
        }
      } else {
        this.b.hide();
        if (exeState?.state === NotebookCellExecutionState.Executing) {
          this.h(element);
        }
      }
    }
  }
  h(element, e) {
    const exeState = e?.changed ?? this.g.getCellExecution(element.uri);
    const progressBar = element.isInputCollapsed ? this.b : this.a;
    if (exeState?.state === NotebookCellExecutionState.Executing && (!exeState.didPause || element.isInputCollapsed)) {
      showProgressBar(progressBar);
    } else {
      progressBar.hide();
    }
  }
};
$yKb = __decorate([
  __param(2, $wL)
], $yKb);
function showProgressBar(progressBar) {
  progressBar.infinite().show(500);
}

// out-build/vs/workbench/contrib/notebook/browser/view/cellParts/cellStatusPart.js
var $122 = $;
var $zKb = class $zKb2 extends $lJb {
  constructor(t, u, editorPart, w, y, hoverService, configurationService, z) {
    super();
    this.t = t;
    this.u = u;
    this.w = w;
    this.y = y;
    this.z = z;
    this.h = [];
    this.j = [];
    this.m = 0;
    this.r = this.B(new $ze());
    this.onDidClick = this.r.event;
    this.statusBarContainer = $bk(editorPart, $122(".cell-statusbar-container"));
    this.statusBarContainer.tabIndex = -1;
    const leftItemsContainer = $bk(this.statusBarContainer, $122(".cell-status-left"));
    const rightItemsContainer = $bk(this.statusBarContainer, $122(".cell-status-right"));
    this.a = $bk(leftItemsContainer, $122(".cell-contributed-items.cell-contributed-items-left"));
    this.b = $bk(rightItemsContainer, $122(".cell-contributed-items.cell-contributed-items-right"));
    this.g = this.B(new $2c());
    this.s = new class {
      constructor() {
        this.a = 0;
        this.showHover = (options3) => {
          options3.position = options3.position ?? {};
          options3.position.hoverPosition = 3;
          return hoverService.showHover(options3);
        };
        this.placement = "element";
      }
      get delay() {
        return Date.now() - this.a < 200 ? 0 : configurationService.getValue("workbench.hover.delay");
      }
      onDidHideHover() {
        this.a = Date.now();
      }
    }();
    this.B(this.z.onDidColorThemeChange(() => this.n && this.updateContext(this.n)));
    this.B($_i(this.statusBarContainer, $7j.CLICK, (e) => {
      if (e.target === leftItemsContainer || e.target === rightItemsContainer || e.target === this.statusBarContainer) {
        this.r.fire({
          type: 0,
          event: e
        });
      } else {
        const target = e.target;
        let itemHasCommand = false;
        if (target && $Uj(target)) {
          const targetElement = target;
          if (targetElement.classList.contains("cell-status-item-has-command")) {
            itemHasCommand = true;
          } else if (targetElement.parentElement && targetElement.parentElement.classList.contains("cell-status-item-has-command")) {
            itemHasCommand = true;
          }
        }
        if (itemHasCommand) {
          this.r.fire({
            type: 2,
            event: e
          });
        } else {
          this.r.fire({
            type: 1,
            event: e
          });
        }
      }
    }));
  }
  didRenderCell(element) {
    if (this.t.hasModel()) {
      const context = {
        ui: true,
        cell: element,
        notebookEditor: this.t,
        $mid: 13
        /* MarshalledId.NotebookCellActionContext */
      };
      this.updateContext(context);
    }
    if (this.w) {
      const updateFocusModeForEditorEvent = () => {
        if (this.w && (this.w.hasWidgetFocus() || this.statusBarContainer.ownerDocument.activeElement && this.statusBarContainer.contains(this.statusBarContainer.ownerDocument.activeElement))) {
          element.focusMode = CellFocusMode.Editor;
        } else {
          const currentMode = element.focusMode;
          if (currentMode === CellFocusMode.ChatInput) {
            element.focusMode = CellFocusMode.ChatInput;
          } else if (currentMode === CellFocusMode.Output && this.t.hasWebviewFocus()) {
            element.focusMode = CellFocusMode.Output;
          } else {
            element.focusMode = CellFocusMode.Container;
          }
        }
      };
      this.f.add(this.w.onDidFocusEditorWidget(() => {
        updateFocusModeForEditorEvent();
      }));
      this.f.add(this.w.onDidBlurEditorWidget(() => {
        if (this.t.hasEditorFocus() && !(this.statusBarContainer.ownerDocument.activeElement && this.statusBarContainer.contains(this.statusBarContainer.ownerDocument.activeElement))) {
          updateFocusModeForEditorEvent();
        }
      }));
      this.f.add(this.onDidClick((e) => {
        if (this.c instanceof $XIb && e.type !== 2 && this.w) {
          const target = this.w.getTargetAtClientPoint(e.event.clientX, e.event.clientY - this.t.notebookOptions.computeEditorStatusbarHeight(this.c.internalMetadata, this.c.uri));
          if (target?.position) {
            this.w.setPosition(target.position);
            this.w.focus();
          }
        }
      }));
    }
  }
  updateInternalLayoutNow(element) {
    this.u.classList.toggle("cell-statusbar-hidden", this.t.notebookOptions.computeEditorStatusbarHeight(element.internalMetadata, element.uri) === 0);
    const layoutInfo = element.layoutInfo;
    const width2 = layoutInfo.editorWidth;
    if (!width2) {
      return;
    }
    this.m = width2;
    this.statusBarContainer.style.width = `${width2}px`;
    const maxItemWidth = this.C();
    this.h.forEach((item) => item.maxWidth = maxItemWidth);
    this.j.forEach((item) => item.maxWidth = maxItemWidth);
  }
  C() {
    return this.m / 2;
  }
  updateContext(context) {
    this.n = context;
    this.g.clear();
    if (!this.n) {
      return;
    }
    this.g.add(this.n.cell.onDidChangeLayout(() => {
      if (this.n) {
        this.updateInternalLayoutNow(this.n.cell);
      }
    }));
    this.g.add(this.n.cell.onDidChangeCellStatusBarItems(() => this.F()));
    this.g.add(this.n.notebookEditor.onDidChangeActiveCell(() => this.D()));
    this.updateInternalLayoutNow(this.n.cell);
    this.D();
    this.F();
  }
  D() {
    const isActiveCell = this.n.notebookEditor.getActiveCell() === this.n?.cell;
    this.statusBarContainer.classList.toggle("is-active-cell", isActiveCell);
  }
  F() {
    const items = this.n.cell.getCellStatusBarItems();
    items.sort((itemA, itemB) => {
      return (itemB.priority ?? 0) - (itemA.priority ?? 0);
    });
    const maxItemWidth = this.C();
    const newLeftItems = items.filter(
      (item) => item.alignment === 1
      /* CellStatusbarAlignment.Left */
    );
    const newRightItems = items.filter(
      (item) => item.alignment === 2
      /* CellStatusbarAlignment.Right */
    ).reverse();
    const updateItems = (renderedItems, newItems, container2) => {
      if (renderedItems.length > newItems.length) {
        const deleted = renderedItems.splice(newItems.length, renderedItems.length - newItems.length);
        for (const deletedItem of deleted) {
          deletedItem.container.remove();
          deletedItem.dispose();
        }
      }
      newItems.forEach((newLeftItem, i2) => {
        const existingItem = renderedItems[i2];
        if (existingItem) {
          existingItem.updateItem(newLeftItem, maxItemWidth);
        } else {
          const item = this.y.createInstance(CellStatusBarItem, this.n, this.s, this.w, newLeftItem, maxItemWidth);
          renderedItems.push(item);
          container2.appendChild(item.container);
        }
      });
    };
    updateItems(this.h, newLeftItems, this.a);
    updateItems(this.j, newRightItems, this.b);
  }
  dispose() {
    super.dispose();
    $Xc(this.h);
    $Xc(this.j);
  }
};
$zKb = __decorate([
  __param(4, $Pk),
  __param(5, $5$),
  __param(6, $kl),
  __param(7, $gs)
], $zKb);
var CellStatusBarItem = class CellStatusBarItem2 extends $3c {
  set maxWidth(v) {
    this.container.style.maxWidth = v + "px";
  }
  constructor(c, f, g, itemModel, maxWidth, h3, j, m, n, r2) {
    super();
    this.c = c;
    this.f = f;
    this.g = g;
    this.h = h3;
    this.j = j;
    this.m = m;
    this.n = n;
    this.r = r2;
    this.container = $122(".cell-status-item");
    this.b = this.B(new $2c());
    this.updateItem(itemModel, maxWidth);
  }
  updateItem(item, maxWidth) {
    this.b.clear();
    if (!this.a || this.a.text !== item.text) {
      this.b.add(new $U2(this.container)).text = item.text.replace(/\n/g, " ");
    }
    const resolveColor = (color2) => {
      return isThemeColor(color2) ? this.n.getColorTheme().getColor(color2.id)?.toString() || "" : color2;
    };
    this.container.style.color = item.color ? resolveColor(item.color) : "";
    this.container.style.backgroundColor = item.backgroundColor ? resolveColor(item.backgroundColor) : "";
    this.container.style.opacity = item.opacity ? item.opacity : "";
    this.container.classList.toggle("cell-status-item-show-when-active", !!item.onlyShowWhenActive);
    if (typeof maxWidth === "number") {
      this.maxWidth = maxWidth;
    }
    let ariaLabel;
    let role;
    if (item.accessibilityInformation) {
      ariaLabel = item.accessibilityInformation.label;
      role = item.accessibilityInformation.role;
    } else {
      ariaLabel = item.text ? $0l(item.text).trim() : "";
    }
    this.container.setAttribute("aria-label", ariaLabel);
    this.container.setAttribute("role", role || "");
    if (item.tooltip) {
      const hoverContent = typeof item.tooltip === "string" ? item.tooltip : { markdown: item.tooltip, markdownNotSupportedFallback: void 0 };
      this.b.add(this.r.setupManagedHover(this.f, this.container, hoverContent));
    }
    this.container.classList.toggle("cell-status-item-has-command", !!item.command);
    if (item.command) {
      this.container.tabIndex = 0;
      this.b.add($_i(this.container, $7j.CLICK, (_e) => {
        this.s();
      }));
      this.b.add($_i(this.container, $7j.KEY_DOWN, (e) => {
        const event = new $if(e);
        if (event.equals(
          10
          /* KeyCode.Space */
        ) || event.equals(
          3
          /* KeyCode.Enter */
        )) {
          this.s();
        }
      }));
    } else {
      this.container.removeAttribute("tabIndex");
    }
    this.a = item;
  }
  async s() {
    const command4 = this.a.command;
    if (!command4) {
      return;
    }
    const id2 = typeof command4 === "string" ? command4 : command4.id;
    const args2 = typeof command4 === "string" ? [] : command4.arguments ?? [];
    if (typeof command4 === "string" || !command4.arguments || !Array.isArray(command4.arguments) || command4.arguments.length === 0) {
      args2.unshift(this.c);
    }
    this.h.publicLog2("workbenchActionExecuted", { id: id2, from: "cell status bar" });
    try {
      this.g?.focus();
      await this.j.executeCommand(id2, ...args2);
    } catch (error) {
      this.m.error($1m(error));
    }
  }
};
CellStatusBarItem = __decorate([
  __param(5, $zv),
  __param(6, $sn),
  __param(7, $PJ),
  __param(8, $gs),
  __param(9, $5$)
], CellStatusBarItem);

// out-build/vs/workbench/contrib/notebook/browser/view/cellParts/cellActionView.js
var $rKb = class extends $T$ {
  C() {
    if (this.u.label && this.L) {
      $dk(this.L, ...$B1(this.eb.label ?? ""));
    }
  }
};
var $sKb = class extends $T$ {
  render(container2) {
    super.render(container2);
    container2.classList.add("notebook-action-view-item");
    this.b = document.createElement("a");
    container2.appendChild(this.b);
    this.C();
  }
  C() {
    if (this.b) {
      this.b.classList.add("notebook-label");
      this.b.innerText = this._action.label;
    }
  }
};
var $tKb = class $tKb2 extends $V$ {
  constructor(action, options3, renderLabel, subActionProvider, subActionViewItemProvider, _keybindingService, _contextMenuService, _themeService, S) {
    super(action, { ...options3, hoverDelegate: options3?.hoverDelegate ?? $JZ("element") }, _keybindingService, _contextMenuService, _themeService);
    this.renderLabel = renderLabel;
    this.subActionProvider = subActionProvider;
    this.subActionViewItemProvider = subActionViewItemProvider;
    this.S = S;
  }
  render(container2) {
    super.render(container2);
    container2.classList.add("notebook-action-view-item");
    container2.classList.add("notebook-action-view-item-unified");
    this.P = document.createElement("a");
    container2.appendChild(this.P);
    this.Q = this.B(this.S.setupManagedHover(this.u.hoverDelegate ?? $JZ("element"), this.P, ""));
    this.C();
    for (const event of [$7j.CLICK, $7j.MOUSE_DOWN, EventType.Tap]) {
      this.B($_i(container2, event, (e) => this.onClick(e, true)));
    }
  }
  onClick(event, preserveFocus = false) {
    $9j.stop(event, true);
    const context = $Ig(this._context) ? this.u?.useEventAsContext ? event : { preserveFocus } : this._context;
    this.actionRunner.run(this.R ?? this._action, context);
  }
  C() {
    const actions = this.subActionProvider.getActions();
    if (this.P) {
      const primaryAction = actions[0];
      this.R = primaryAction;
      if (primaryAction && primaryAction instanceof $fJ) {
        const element = this.element;
        if (element && primaryAction.item.icon && ThemeIcon.isThemeIcon(primaryAction.item.icon)) {
          const iconClasses = ThemeIcon.asClassNameArray(primaryAction.item.icon);
          element.classList.forEach((cl) => {
            if (cl.startsWith("codicon-")) {
              element.classList.remove(cl);
            }
          });
          element.classList.add(...iconClasses);
        }
        if (this.renderLabel) {
          this.P.classList.add("notebook-label");
          this.P.innerText = this._action.label;
          this.Q?.update(primaryAction.tooltip.length ? primaryAction.tooltip : primaryAction.label);
        }
      } else {
        if (this.renderLabel) {
          this.P.classList.add("notebook-label");
          this.P.innerText = this._action.label;
          this.Q?.update(this._action.tooltip.length ? this._action.tooltip : this._action.label);
        }
      }
    }
  }
};
$tKb = __decorate([
  __param(5, $Ty),
  __param(6, $50),
  __param(7, $gs),
  __param(8, $5$)
], $tKb);

// out-build/vs/workbench/contrib/notebook/browser/view/cellParts/cellToolbarStickyScroll.js
function $uKb(notebookEditor, cell, element, opts) {
  const extraOffset = opts?.extraOffset ?? 0;
  const min = opts?.min ?? 0;
  const updateForScroll = () => {
    if (cell.isInputCollapsed) {
      element.style.top = "";
    } else {
      const scrollTop = notebookEditor.scrollTop;
      const elementTop = notebookEditor.getAbsoluteTopOfElement(cell);
      const diff3 = scrollTop - elementTop + extraOffset;
      const maxTop = cell.layoutInfo.editorHeight + cell.layoutInfo.statusBarHeight - 45;
      const top2 = maxTop > 20 ? (
        // Don't move the run button if it can only move a very short distance
        $4i(min, diff3, maxTop)
      ) : min;
      element.style.top = `${top2}px`;
    }
  };
  updateForScroll();
  return notebookEditor.onDidScroll(() => updateForScroll());
}

// out-build/vs/workbench/contrib/notebook/browser/view/cellParts/cellToolbars.js
var $vKb = class $vKb2 extends $mJb {
  constructor(f, _titleToolbarContainer, h3, j, m, n, r2) {
    super();
    this.f = f;
    this.h = h3;
    this.j = j;
    this.m = m;
    this.n = n;
    this.r = r2;
  }
  s() {
    if (this.c) {
      return this.c;
    }
    const betweenCellToolbar = this.B(new $f3(this.h, this.m, {
      actionViewItemProvider: (action, options3) => {
        if (action instanceof $fJ) {
          if (this.f.notebookOptions.getDisplayOptions().insertToolbarAlignment === "center") {
            return this.j.createInstance($rKb, action, { hoverDelegate: options3.hoverDelegate });
          } else {
            return this.j.createInstance($T$, action, { hoverDelegate: options3.hoverDelegate });
          }
        }
        return void 0;
      }
    }));
    this.c = betweenCellToolbar;
    const menu = this.B(this.r.createMenu(this.f.creationOptions.menuIds.cellInsertToolbar, this.n));
    const updateActions = () => {
      const actions = getCellToolbarActions(menu);
      betweenCellToolbar.setActions(actions.primary, actions.secondary);
    };
    this.B(menu.onDidChange(() => updateActions()));
    this.B(this.f.notebookOptions.onDidChangeOptions((e) => {
      if (e.insertToolbarAlignment) {
        updateActions();
      }
    }));
    updateActions();
    return betweenCellToolbar;
  }
  didRenderCell(element) {
    const betweenCellToolbar = this.s();
    if (this.f.hasModel()) {
      betweenCellToolbar.context = {
        ui: true,
        cell: element,
        notebookEditor: this.f,
        source: "insertToolbar",
        $mid: 13
        /* MarshalledId.NotebookCellActionContext */
      };
    }
    this.updateInternalLayoutNow(element);
  }
  updateInternalLayoutNow(element) {
    const bottomToolbarOffset = element.layoutInfo.bottomToolbarOffset;
    this.h.style.transform = `translateY(${bottomToolbarOffset}px)`;
  }
};
$vKb = __decorate([
  __param(3, $Pk),
  __param(4, $50),
  __param(5, $on),
  __param(6, $cJ)
], $vKb);
var $wKb = class $wKb2 extends $mJb {
  get hasActions() {
    if (!this.c) {
      return false;
    }
    return this.c.actions.primary.length + this.c.actions.secondary.length + this.c.deleteActions.primary.length + this.c.deleteActions.secondary.length > 0;
  }
  constructor(j, m, n, r2, s, t, u, w) {
    super();
    this.j = j;
    this.m = m;
    this.n = n;
    this.r = r2;
    this.s = s;
    this.t = t;
    this.u = u;
    this.w = w;
    this.h = this.B(new $ze());
    this.onDidUpdateActions = this.h.event;
  }
  y() {
    if (this.c) {
      return this.c;
    }
    const titleMenu = this.B(this.u.createMenu(this.n, this.t));
    const deleteMenu = this.B(this.u.createMenu(this.r, this.t));
    const actions = getCellToolbarActions(titleMenu);
    const deleteActions = getCellToolbarActions(deleteMenu);
    this.c = {
      titleMenu,
      actions,
      deleteMenu,
      deleteActions
    };
    return this.c;
  }
  z(model, element) {
    if (this.f) {
      return this.f;
    }
    const hoverDelegate = this.B($KZ());
    const toolbar = this.B(this.w.createInstance($3$, this.j, {
      actionViewItemProvider: (action, options3) => {
        return $X$(this.w, action, options3);
      },
      renderDropdownAsChildElement: true,
      hoverDelegate
    }));
    const deleteToolbar = this.B(this.w.invokeFunction((accessor) => createDeleteToolbar(accessor, this.j, hoverDelegate, "cell-delete-toolbar")));
    if (model.deleteActions.primary.length !== 0 || model.deleteActions.secondary.length !== 0) {
      deleteToolbar.setActions(model.deleteActions.primary, model.deleteActions.secondary);
    }
    this.D(toolbar, model.titleMenu, model.actions);
    this.D(deleteToolbar, model.deleteMenu, model.deleteActions);
    this.f = {
      toolbar,
      deleteToolbar
    };
    return this.f;
  }
  prepareRenderCell(element) {
    this.y();
  }
  didRenderCell(element) {
    const model = this.y();
    const view = this.z(model, element);
    this.b.add($uKb(this.s, element, this.j, { extraOffset: 4, min: -14 }));
    if (this.s.hasModel()) {
      const toolbarContext = {
        ui: true,
        cell: element,
        notebookEditor: this.s,
        source: "cellToolbar",
        $mid: 13
        /* MarshalledId.NotebookCellActionContext */
      };
      this.C(view, toolbarContext);
    }
  }
  C(view, toolbarContext) {
    view.toolbar.context = toolbarContext;
    view.deleteToolbar.context = toolbarContext;
  }
  D(toolbar, menu, initActions) {
    let dropdownIsVisible = false;
    let deferredUpdate;
    this.F(toolbar, initActions);
    this.B(menu.onDidChange(() => {
      if (dropdownIsVisible) {
        const actions2 = getCellToolbarActions(menu);
        deferredUpdate = () => this.F(toolbar, actions2);
        return;
      }
      const actions = getCellToolbarActions(menu);
      this.F(toolbar, actions);
    }));
    this.m.toggle("cell-toolbar-dropdown-active", false);
    this.B(toolbar.onDidChangeDropdownVisibility((visible) => {
      dropdownIsVisible = visible;
      this.m.toggle("cell-toolbar-dropdown-active", visible);
      if (deferredUpdate && !visible) {
        $Xh(() => {
          deferredUpdate?.();
        }, 0, this.q);
        deferredUpdate = void 0;
      }
    }));
  }
  F(toolbar, actions) {
    const hadFocus = $Nj(toolbar.getElement());
    toolbar.setActions(actions.primary, actions.secondary);
    if (hadFocus) {
      this.s.focus();
    }
    if (actions.primary.length || actions.secondary.length) {
      this.m.toggle("cell-has-toolbar-actions", true);
      this.h.fire();
    } else {
      this.m.toggle("cell-has-toolbar-actions", false);
      this.h.fire();
    }
  }
};
$wKb = __decorate([
  __param(5, $on),
  __param(6, $cJ),
  __param(7, $Pk)
], $wKb);
function getCellToolbarActions(menu) {
  return $Q$(menu.getActions({ shouldForwardArgs: true }), (g) => /^inline/.test(g));
}
function createDeleteToolbar(accessor, container2, hoverDelegate, elementClass) {
  const contextMenuService = accessor.get($50);
  const keybindingService = accessor.get($Ty);
  const instantiationService = accessor.get($Pk);
  const toolbar = new $f3(container2, contextMenuService, {
    getKeyBinding: (action) => keybindingService.lookupKeybinding(action.id),
    actionViewItemProvider: (action, options3) => {
      return $X$(instantiationService, action, options3);
    },
    renderDropdownAsChildElement: true,
    hoverDelegate
  });
  if (elementClass) {
    toolbar.getElement().classList.add(elementClass);
  }
  return toolbar;
}

// out-build/vs/workbench/contrib/notebook/browser/viewModel/cellOutputTextHelper.js
function $4Kb(notebook, viewCell, shortErrors = false) {
  const outputText = [];
  for (let i2 = 0; i2 < viewCell.outputsViewModels.length; i2++) {
    const outputViewModel = viewCell.outputsViewModels[i2];
    const outputTextModel = viewCell.model.outputs[i2];
    const [mimeTypes, pick] = outputViewModel.resolveMimeTypes(notebook, void 0);
    const mimeType = mimeTypes[pick].mimeType;
    let buffer = outputTextModel.outputs.find((output) => output.mime === mimeType);
    if (!buffer || mimeType.startsWith("image")) {
      buffer = outputTextModel.outputs.find((output) => !output.mime.startsWith("image"));
    }
    if (!buffer) {
      continue;
    }
    let text2 = "";
    if ($tM(mimeType)) {
      const { text: stream, count } = $5Kb(outputViewModel);
      text2 = stream;
      if (count > 1) {
        i2 += count - 1;
      }
    } else {
      text2 = $6Kb(mimeType, buffer, shortErrors);
    }
    outputText.push(text2);
  }
  let outputContent;
  if (outputText.length > 1) {
    outputContent = outputText.map((output, i2) => {
      return `Cell output ${i2 + 1} of ${outputText.length}
${output}`;
    }).join("\n");
  } else {
    outputContent = outputText[0] ?? "";
  }
  return outputContent;
}
function $5Kb(output) {
  let text2 = "";
  const cellViewModel = output.cellViewModel;
  let index = cellViewModel.outputsViewModels.indexOf(output);
  let count = 0;
  while (index < cellViewModel.model.outputs.length) {
    const nextCellOutput = cellViewModel.model.outputs[index];
    const nextOutput = nextCellOutput.outputs.find((output2) => $tM(output2.mime));
    if (!nextOutput) {
      break;
    }
    text2 = text2 + decoder.decode(nextOutput.data.buffer);
    index = index + 1;
    count++;
  }
  return { text: text2.trim(), count };
}
var decoder = new TextDecoder();
function $6Kb(mimeType, buffer, shortError = false) {
  let text2 = `${mimeType}`;
  const charLimit = 1e5;
  text2 = decoder.decode(buffer.data.slice(0, charLimit).buffer);
  if (buffer.data.byteLength > charLimit) {
    text2 = text2 + "...(truncated)";
  } else if (mimeType === "application/vnd.code.notebook.error") {
    text2 = text2.replace(/\\u001b\[[0-9;]*m/gi, "");
    try {
      const error = JSON.parse(text2);
      if (!error.stack || shortError) {
        text2 = `${error.name}: ${error.message}`;
      } else {
        text2 = error.stack;
      }
    } catch {
    }
  }
  return text2.trim();
}
async function $7Kb(mimeType, outputViewModel, clipboardService, logService) {
  const cellOutput = outputViewModel.model;
  const output = mimeType && $8Kb.includes(mimeType) ? cellOutput.outputs.find((output2) => output2.mime === mimeType) : cellOutput.outputs.find((output2) => $8Kb.includes(output2.mime));
  mimeType = output?.mime;
  if (!mimeType || !output) {
    return;
  }
  const text2 = $tM(mimeType) ? $5Kb(outputViewModel).text : $6Kb(mimeType, output);
  try {
    await clipboardService.writeText(text2);
  } catch (e) {
    logService.error(`Failed to copy content: ${e}`);
  }
}
var $8Kb = [
  "text/latex",
  "text/html",
  "application/vnd.code.notebook.error",
  "application/vnd.code.notebook.stdout",
  "application/x.notebook.stdout",
  "application/x.notebook.stream",
  "application/vnd.code.notebook.stderr",
  "application/x.notebook.stderr",
  "text/plain",
  "text/markdown",
  "application/json"
];

// out-build/vs/workbench/contrib/notebook/browser/controller/cellOutputActions.js
var $9Kb = "notebook.cellOutput.copy";
$hJ(class ShowAllOutputsAction extends $gJ {
  constructor() {
    super({
      id: "notebook.cellOuput.showEmptyOutputs",
      title: localize(8208, null),
      menu: {
        id: $bJ.NotebookOutputToolbar,
        when: $7m.and($fBb, $hBb)
      },
      f1: false,
      category: $xIb
    });
  }
  run(accessor, context) {
    const cell = context.cell;
    if (cell && cell.cellKind === CellKind.Code) {
      for (let i2 = 1; i2 < cell.outputsViewModels.length; i2++) {
        if (!cell.outputsViewModels[i2].visible.get()) {
          cell.outputsViewModels[i2].setVisible(true, true);
          cell.updateOutputHeight(i2, 1, "command");
        }
      }
    }
  }
});
$hJ(class CopyCellOutputAction extends $gJ {
  constructor() {
    super({
      id: $9Kb,
      title: localize(8209, null),
      menu: {
        id: $bJ.NotebookOutputToolbar,
        when: $fBb
      },
      category: $xIb,
      icon: $ZKb
    });
  }
  a(editorService, outputContext) {
    if (outputContext && "notebookEditor" in outputContext) {
      return outputContext.notebookEditor;
    }
    return $Qrb(editorService.activeEditorPane);
  }
  async run(accessor, outputContext) {
    const notebookEditor = this.a(accessor.get($mJ), outputContext);
    if (!notebookEditor) {
      return;
    }
    let outputViewModel;
    if (outputContext && "outputId" in outputContext && typeof outputContext.outputId === "string") {
      outputViewModel = getOutputViewModelFromId(outputContext.outputId, notebookEditor);
    } else if (outputContext && "outputViewModel" in outputContext) {
      outputViewModel = outputContext.outputViewModel;
    }
    if (!outputViewModel) {
      const activeCell = notebookEditor.getActiveCell();
      if (!activeCell) {
        return;
      }
      if (activeCell.focusedOutputId !== void 0) {
        outputViewModel = activeCell.outputsViewModels.find((output) => {
          return output.model.outputId === activeCell.focusedOutputId;
        });
      } else {
        outputViewModel = activeCell.outputsViewModels.find((output) => output.pickedMimeType?.isTrusted);
      }
    }
    if (!outputViewModel) {
      return;
    }
    const mimeType = outputViewModel.pickedMimeType?.mimeType;
    if (mimeType?.startsWith("image/")) {
      const focusOptions = { skipReveal: true, outputId: outputViewModel.model.outputId, altOutputId: outputViewModel.model.alternativeOutputId };
      await notebookEditor.focusNotebookCell(outputViewModel.cellViewModel, "output", focusOptions);
      notebookEditor.copyOutputImage(outputViewModel);
    } else {
      const clipboardService = accessor.get($30);
      const logService = accessor.get($wn);
      $7Kb(mimeType, outputViewModel, clipboardService, logService);
    }
  }
});
function getOutputViewModelFromId(outputId, notebookEditor) {
  const notebookViewModel = notebookEditor.getViewModel();
  if (notebookViewModel) {
    const codeCells = notebookViewModel.viewCells.filter((cell) => cell.cellKind === CellKind.Code);
    for (const cell of codeCells) {
      const output = cell.outputsViewModels.find((output2) => output2.model.outputId === outputId || output2.model.alternativeOutputId === outputId);
      if (output) {
        return output;
      }
    }
  }
  return void 0;
}
var $0Kb = "notebook.cellOutput.openInTextEditor";
$hJ(class OpenCellOutputInEditorAction extends $gJ {
  constructor() {
    super({
      id: $0Kb,
      title: localize(8210, null),
      f1: false,
      category: $xIb,
      icon: $ZKb
    });
  }
  a(editorService, outputContext) {
    if (outputContext && "notebookEditor" in outputContext) {
      return outputContext.notebookEditor;
    }
    return $Qrb(editorService.activeEditorPane);
  }
  async run(accessor, outputContext) {
    const notebookEditor = this.a(accessor.get($mJ), outputContext);
    const notebookModelService = accessor.get($orb);
    if (!notebookEditor) {
      return;
    }
    let outputViewModel;
    if (outputContext && "outputId" in outputContext && typeof outputContext.outputId === "string") {
      outputViewModel = getOutputViewModelFromId(outputContext.outputId, notebookEditor);
    } else if (outputContext && "outputViewModel" in outputContext) {
      outputViewModel = outputContext.outputViewModel;
    }
    const openerService = accessor.get($O4);
    if (outputViewModel?.model.outputId && notebookEditor.textModel?.uri) {
      const ref = await notebookModelService.resolve(notebookEditor.textModel.uri);
      await openerService.open(CellUri.generateCellOutputUri(notebookEditor.textModel.uri, outputViewModel.model.outputId));
      ref.dispose();
    }
  }
});

// out-build/vs/workbench/contrib/notebook/browser/view/cellParts/cellOutput.js
var CellOutputElement = class CellOutputElement2 extends $3c {
  constructor(g, h3, j, n, output, r2, s, parentContextKeyService, t, u, w) {
    super();
    this.g = g;
    this.h = h3;
    this.j = j;
    this.n = n;
    this.output = output;
    this.r = r2;
    this.s = s;
    this.t = t;
    this.u = u;
    this.w = w;
    this.b = this.B(new $2c());
    this.f = false;
    this.L = null;
    this.c = parentContextKeyService;
    this.B(this.output.model.onDidChangeData(() => {
      this.rerender();
    }));
    this.B(this.output.onDidResetRenderer(() => {
      this.rerender();
    }));
  }
  detach() {
    this.renderedOutputContainer?.remove();
    let count = 0;
    if (this.innerContainer) {
      for (let i2 = 0; i2 < this.innerContainer.childNodes.length; i2++) {
        if (this.innerContainer.childNodes[i2].className === "rendered-output") {
          count++;
        }
        if (count > 1) {
          break;
        }
      }
      if (count === 0) {
        this.innerContainer.remove();
      }
    }
    this.g.removeInset(this.output);
  }
  updateDOMTop(top2) {
    if (this.innerContainer) {
      this.innerContainer.style.top = `${top2}px`;
    }
  }
  rerender() {
    if (this.g.hasModel() && this.innerContainer && this.renderResult && this.renderResult.type === 1) {
      const [mimeTypes, pick] = this.output.resolveMimeTypes(this.g.textModel, this.g.activeKernel?.preloadProvides);
      const pickedMimeType = mimeTypes[pick];
      if (pickedMimeType.mimeType === this.renderResult.mimeType && pickedMimeType.rendererId === this.renderResult.renderer.id) {
        const index = this.h.outputsViewModels.indexOf(this.output);
        this.g.updateOutput(this.h, this.renderResult, this.h.getOutputOffset(index));
        return;
      }
    }
    if (!this.innerContainer) {
      const currOutputIndex = this.j.renderedOutputEntries.findIndex((entry) => entry.element === this);
      const previousSibling = currOutputIndex > 0 && !!this.j.renderedOutputEntries[currOutputIndex - 1].element.innerContainer?.parentElement ? this.j.renderedOutputEntries[currOutputIndex - 1].element.innerContainer : void 0;
      this.render(previousSibling);
    } else {
      const nextElement = this.innerContainer.nextElementSibling;
      this.b.clear();
      const element = this.innerContainer;
      if (element) {
        element.remove();
        this.g.removeInset(this.output);
      }
      this.render(nextElement);
    }
    this.N();
  }
  // insert after previousSibling
  y(previousSibling, pickedMimeTypeRenderer) {
    this.innerContainer = $(".output-inner-container");
    if (previousSibling && previousSibling.nextElementSibling) {
      this.n.domNode.insertBefore(this.innerContainer, previousSibling.nextElementSibling);
    } else {
      this.n.domNode.appendChild(this.innerContainer);
    }
    this.innerContainer.setAttribute("output-mime-type", pickedMimeTypeRenderer.mimeType);
    return this.innerContainer;
  }
  render(previousSibling) {
    const index = this.h.outputsViewModels.indexOf(this.output);
    if (this.h.isOutputCollapsed || !this.g.hasModel()) {
      this.j.flagAsStale();
      return void 0;
    }
    const notebookUri = CellUri.parse(this.h.uri)?.notebook;
    if (!notebookUri) {
      return void 0;
    }
    const notebookTextModel = this.g.textModel;
    const [mimeTypes, pick] = this.output.resolveMimeTypes(notebookTextModel, this.g.activeKernel?.preloadProvides);
    if (!mimeTypes.find((mimeType) => mimeType.isTrusted) || mimeTypes.length === 0) {
      this.h.updateOutputHeight(index, 0, "CellOutputElement#noMimeType");
      return void 0;
    }
    const selectedPresentation = mimeTypes[pick];
    let renderer = this.r.getRendererInfo(selectedPresentation.rendererId);
    if (!renderer && selectedPresentation.mimeType.indexOf("text/") > -1) {
      renderer = this.r.getRendererInfo("vscode.builtin-renderer");
    }
    const innerContainer = this.y(previousSibling, selectedPresentation);
    if (index === 0 || this.output.visible.get()) {
      this.G(innerContainer, notebookTextModel, this.g.activeKernel, index, mimeTypes);
    } else {
      this.B($td((reader) => {
        const visible = reader.readObservable(this.output.visible);
        if (visible && !this.f) {
          this.G(innerContainer, notebookTextModel, this.g.activeKernel, index, mimeTypes);
        } else if (!visible) {
          this.b.clear();
        }
        this.j.checkForHiddenOutputs();
      }));
      this.j.hasHiddenOutputs.set(true, void 0);
    }
    this.renderedOutputContainer = $bk(innerContainer, $(".rendered-output"));
    this.renderResult = renderer ? { type: 1, renderer, source: this.output, mimeType: selectedPresentation.mimeType } : this.z(this.output, selectedPresentation.mimeType);
    this.output.pickedMimeType = selectedPresentation;
    if (!this.renderResult) {
      this.h.updateOutputHeight(index, 0, "CellOutputElement#renderResultUndefined");
      return void 0;
    }
    this.g.createOutput(this.h, this.renderResult, this.h.getOutputOffset(index), false);
    innerContainer.classList.add("background");
    return { initRenderIsSynchronous: false };
  }
  z(viewModel, preferredMimeType) {
    if (!viewModel.model.outputs.length) {
      return this.D(viewModel, localize(8581, null));
    }
    if (!preferredMimeType) {
      const mimeTypes = viewModel.model.outputs.map((op) => op.mime);
      const mimeTypesMessage = mimeTypes.join(", ");
      return this.D(viewModel, localize(8582, null, mimeTypesMessage));
    }
    return this.C(viewModel, preferredMimeType);
  }
  C(viewModel, mimeType) {
    const query = `@tag:notebookRenderer ${mimeType}`;
    const p = $("p", void 0, `No renderer could be found for mimetype "${mimeType}", but one might be available on the Marketplace.`);
    const a = $("a", { href: `command:workbench.extensions.search?%22${query}%22`, class: "monaco-button monaco-text-button", tabindex: 0, role: "button", style: "padding: 8px; text-decoration: none; color: rgb(255, 255, 255); background-color: rgb(14, 99, 156); max-width: 200px;" }, `Search Marketplace`);
    return {
      type: 0,
      source: viewModel,
      htmlContent: p.outerHTML + a.outerHTML
    };
  }
  D(viewModel, message) {
    const el = $("p", void 0, message);
    return { type: 0, source: viewModel, htmlContent: el.outerHTML };
  }
  F(mimeTypes) {
    if (!mimeTypes.find((mimeType) => $8Kb.indexOf(mimeType.mimeType) || mimeType.mimeType.startsWith("image/"))) {
      return false;
    }
    if ($tM(mimeTypes[0].mimeType)) {
      const cellViewModel = this.output.cellViewModel;
      const index = cellViewModel.outputsViewModels.indexOf(this.output);
      if (index > 0) {
        const previousOutput = cellViewModel.model.outputs[index - 1];
        return !$tM(previousOutput.outputs[0].mime);
      }
    }
    return true;
  }
  async G(outputItemDiv, notebookTextModel, kernel, index, mimeTypes) {
    const hasMultipleMimeTypes = mimeTypes.filter((mimeType) => mimeType.isTrusted).length > 1;
    const isCopyEnabled = this.F(mimeTypes);
    if (index > 0 && !hasMultipleMimeTypes && !isCopyEnabled) {
      return;
    }
    if (!this.g.hasModel()) {
      return;
    }
    outputItemDiv.style.position = "relative";
    const mimeTypePicker = $(".cell-output-toolbar");
    outputItemDiv.appendChild(mimeTypePicker);
    const toolbar = this.b.add(this.w.createInstance($3$, mimeTypePicker, {
      renderDropdownAsChildElement: false
    }));
    toolbar.context = {
      ui: true,
      cell: this.output.cellViewModel,
      outputViewModel: this.output,
      notebookEditor: this.g,
      $mid: 13
      /* MarshalledId.NotebookCellActionContext */
    };
    const pickAction = this.b.add(new $Um("notebook.output.pickMimetype", localize(8583, null), ThemeIcon.asClassName($YKb), void 0, async (_context) => this.H(outputItemDiv, notebookTextModel, kernel, this.output)));
    const menuContextKeyService = this.b.add(this.c.createScoped(outputItemDiv));
    const hasHiddenOutputs = $hBb.bindTo(menuContextKeyService);
    const isFirstCellOutput = $gBb.bindTo(menuContextKeyService);
    isFirstCellOutput.set(index === 0);
    this.b.add($td((reader) => {
      hasHiddenOutputs.set(reader.readObservable(this.j.hasHiddenOutputs));
    }));
    const menu = this.b.add(this.t.createMenu($bJ.NotebookOutputToolbar, menuContextKeyService));
    const updateMenuToolbar = () => {
      let { secondary } = $Q$(menu.getActions({ shouldForwardArgs: true }), () => false);
      if (!isCopyEnabled) {
        secondary = secondary.filter((action) => action.id !== $9Kb);
      }
      if (hasMultipleMimeTypes) {
        secondary = [pickAction, ...secondary];
      }
      toolbar.setActions([], secondary);
    };
    updateMenuToolbar();
    this.b.add(menu.onDidChange(updateMenuToolbar));
  }
  async H(outputItemDiv, notebookTextModel, kernel, viewModel) {
    const [mimeTypes, currIndex] = viewModel.resolveMimeTypes(notebookTextModel, kernel?.preloadProvides);
    const items = [];
    const unsupportedItems = [];
    mimeTypes.forEach((mimeType2, index) => {
      if (mimeType2.isTrusted) {
        const arr = mimeType2.rendererId === $kM ? unsupportedItems : items;
        arr.push({
          label: mimeType2.mimeType,
          id: mimeType2.mimeType,
          index,
          picked: index === currIndex,
          detail: this.J(mimeType2.rendererId),
          description: index === currIndex ? localize(8584, null) : void 0
        });
      }
    });
    if (unsupportedItems.some((m) => JUPYTER_RENDERER_MIMETYPES.includes(m.id))) {
      unsupportedItems.push({
        label: localize(8585, null),
        id: "installRenderers",
        index: mimeTypes.length
      });
    }
    const disposables = new $2c();
    const picker = disposables.add(this.s.createQuickPick({ useSeparators: true }));
    picker.items = [
      ...items,
      { type: "separator" },
      ...unsupportedItems
    ];
    picker.activeItems = items.filter((item) => !!item.picked);
    picker.placeholder = items.length !== mimeTypes.length ? localize(8586, null) : localize(8587, null);
    const pick = await new Promise((resolve) => {
      disposables.add(picker.onDidAccept(() => {
        resolve(picker.selectedItems.length === 1 ? picker.selectedItems[0] : void 0);
        disposables.dispose();
      }));
      picker.show();
    });
    if (pick === void 0 || pick.index === currIndex) {
      return;
    }
    if (pick.id === "installRenderers") {
      this.I();
      return;
    }
    const nextElement = outputItemDiv.nextElementSibling;
    this.b.clear();
    const element = this.innerContainer;
    if (element) {
      element.remove();
      this.g.removeInset(viewModel);
    }
    viewModel.pickedMimeType = mimeTypes[pick.index];
    this.h.updateOutputMinHeight(this.h.layoutInfo.outputTotalHeight);
    const { mimeType, rendererId } = mimeTypes[pick.index];
    this.r.updateMimePreferredRenderer(notebookTextModel.viewType, mimeType, rendererId, mimeTypes.map((m) => m.mimeType));
    this.render(nextElement);
    this.M(false);
    this.N();
  }
  async I() {
    await this.u.openSearch(`@id:${$Nrb}`);
  }
  J(renderId) {
    const renderInfo = this.r.getRendererInfo(renderId);
    if (renderInfo) {
      const displayName = renderInfo.displayName !== "" ? renderInfo.displayName : renderInfo.id;
      return `${displayName} (${renderInfo.extensionId.value})`;
    }
    return localize(8588, null);
  }
  M(synchronous) {
    if (this.L !== null) {
      clearTimeout(this.L);
    }
    if (synchronous) {
      this.h.unlockOutputHeight();
    } else {
      this.L = setTimeout(() => {
        this.h.unlockOutputHeight();
      }, 1e3);
    }
  }
  N() {
    this.g.layoutNotebookCell(this.h, this.h.layoutInfo.totalHeight);
  }
  dispose() {
    if (this.L) {
      this.h.unlockOutputHeight();
      clearTimeout(this.L);
    }
    super.dispose();
  }
};
CellOutputElement = __decorate([
  __param(5, $mrb),
  __param(6, $1M),
  __param(7, $on),
  __param(8, $cJ),
  __param(9, $vzb),
  __param(10, $Pk)
], CellOutputElement);
var OutputEntryViewHandler = class {
  constructor(model, element) {
    this.model = model;
    this.element = element;
  }
};
var CellOutputUpdateContext;
(function(CellOutputUpdateContext2) {
  CellOutputUpdateContext2[CellOutputUpdateContext2["Execution"] = 1] = "Execution";
  CellOutputUpdateContext2[CellOutputUpdateContext2["Other"] = 2] = "Other";
})(CellOutputUpdateContext || (CellOutputUpdateContext = {}));
var $$Kb = class $$Kb2 extends $lJb {
  checkForHiddenOutputs() {
    if (this.b.find((entry) => {
      return entry.model.visible;
    })) {
      this.hasHiddenOutputs.set(true, void 0);
    } else {
      this.hasHiddenOutputs.set(false, void 0);
    }
  }
  get renderedOutputEntries() {
    return this.b;
  }
  constructor(h3, j, n, r2, s, t, u) {
    super();
    this.h = h3;
    this.j = j;
    this.n = n;
    this.r = r2;
    this.s = s;
    this.t = t;
    this.u = u;
    this.b = [];
    this.g = false;
    this.hasHiddenOutputs = $he("hasHiddenOutputs", false);
    this.y = null;
    this.B(j.onDidStartExecution(() => {
      j.updateOutputMinHeight(j.layoutInfo.outputTotalHeight);
    }));
    this.B(j.onDidStopExecution(() => {
      this.z(false);
    }));
    this.B(j.onDidChangeOutputs((splice2) => {
      const executionState = this.t.getCellExecution(j.uri);
      const context = executionState ? 1 : 2;
      this.C(splice2, context);
    }));
    this.B(j.onDidChangeLayout(() => {
      this.updateInternalLayoutNow(j);
    }));
  }
  updateInternalLayoutNow(viewCell) {
    this.n.outputContainer.setTop(viewCell.layoutInfo.outputContainerOffset);
    this.n.outputShowMoreContainer.setTop(viewCell.layoutInfo.outputShowMoreContainerOffset);
    this.b.forEach((entry) => {
      const index = this.j.outputsViewModels.indexOf(entry.model);
      if (index >= 0) {
        const top2 = this.j.getOutputOffsetInContainer(index);
        entry.element.updateDOMTop(top2);
      }
    });
  }
  render() {
    try {
      this.w();
    } finally {
      this.G();
    }
  }
  /**
   * Notify that an output may have been swapped out without the model getting rendered.
   */
  flagAsStale() {
    this.g = true;
  }
  w() {
    if (this.j.outputsViewModels.length > 0) {
      if (this.j.layoutInfo.outputTotalHeight !== 0) {
        this.j.updateOutputMinHeight(this.j.layoutInfo.outputTotalHeight);
      }
      $hk(this.n.outputContainer.domNode);
      for (let index = 0; index < Math.min(this.r.limit, this.j.outputsViewModels.length); index++) {
        const currOutput = this.j.outputsViewModels[index];
        const entry = this.u.createInstance(CellOutputElement, this.h, this.j, this, this.n.outputContainer, currOutput);
        this.b.push(new OutputEntryViewHandler(currOutput, entry));
        entry.render(void 0);
      }
      if (this.j.outputsViewModels.length > this.r.limit) {
        $hk(this.n.outputShowMoreContainer.domNode);
        this.j.updateOutputShowMoreContainerHeight(46);
      }
      this.z(false);
    } else {
      $ik(this.n.outputContainer.domNode);
    }
    this.n.outputShowMoreContainer.domNode.innerText = "";
    if (this.j.outputsViewModels.length > this.r.limit) {
      this.n.outputShowMoreContainer.domNode.appendChild(this.F(this.n.templateDisposables));
    } else {
      $ik(this.n.outputShowMoreContainer.domNode);
      this.j.updateOutputShowMoreContainerHeight(0);
    }
  }
  viewUpdateShowOutputs(initRendering) {
    if (this.g) {
      this.g = false;
      this.b.forEach((entry) => {
        entry.element.rerender();
      });
    }
    for (let index = 0; index < this.b.length; index++) {
      const viewHandler = this.b[index];
      const outputEntry = viewHandler.element;
      if (outputEntry.renderResult) {
        this.h.createOutput(this.j, outputEntry.renderResult, this.j.getOutputOffset(index), false);
      } else {
        outputEntry.render(void 0);
      }
    }
    this.G();
  }
  viewUpdateHideOuputs() {
    for (let index = 0; index < this.b.length; index++) {
      this.h.hideInset(this.b[index].model);
    }
  }
  z(synchronous) {
    if (this.y !== null) {
      clearTimeout(this.y);
    }
    const executionState = this.t.getCellExecution(this.j.uri);
    if (synchronous) {
      this.j.unlockOutputHeight();
    } else if (executionState?.state !== NotebookCellExecutionState.Executing) {
      this.y = setTimeout(() => {
        this.j.unlockOutputHeight();
      }, 200);
    }
  }
  C(splice2, context = 2) {
    const previousOutputHeight = this.j.layoutInfo.outputTotalHeight;
    this.j.updateOutputMinHeight(previousOutputHeight);
    if (this.j.outputsViewModels.length) {
      $hk(this.n.outputContainer.domNode);
    } else {
      $ik(this.n.outputContainer.domNode);
    }
    this.j.spliceOutputHeights(splice2.start, splice2.deleteCount, splice2.newOutputs.map((_) => 0));
    this.D(splice2, context);
  }
  D(splice2, context) {
    if (splice2.start >= this.r.limit) {
      return;
    }
    const firstGroupEntries = this.b.slice(0, splice2.start);
    const deletedEntries = this.b.slice(splice2.start, splice2.start + splice2.deleteCount);
    const secondGroupEntries = this.b.slice(splice2.start + splice2.deleteCount);
    let newlyInserted = this.j.outputsViewModels.slice(splice2.start, splice2.start + splice2.newOutputs.length);
    if (firstGroupEntries.length + newlyInserted.length + secondGroupEntries.length > this.r.limit) {
      if (firstGroupEntries.length + newlyInserted.length > this.r.limit) {
        [...deletedEntries, ...secondGroupEntries].forEach((entry) => {
          entry.element.detach();
          entry.element.dispose();
        });
        newlyInserted = newlyInserted.slice(0, this.r.limit - firstGroupEntries.length);
        const newlyInsertedEntries = newlyInserted.map((insert) => {
          return new OutputEntryViewHandler(insert, this.u.createInstance(CellOutputElement, this.h, this.j, this, this.n.outputContainer, insert));
        });
        this.b = [...firstGroupEntries, ...newlyInsertedEntries];
        for (let i2 = firstGroupEntries.length; i2 < this.b.length; i2++) {
          this.b[i2].element.render(void 0);
        }
      } else {
        const elementsPushedOutOfView = secondGroupEntries.slice(this.r.limit - firstGroupEntries.length - newlyInserted.length);
        [...deletedEntries, ...elementsPushedOutOfView].forEach((entry) => {
          entry.element.detach();
          entry.element.dispose();
        });
        const reRenderRightBoundary = firstGroupEntries.length + newlyInserted.length;
        const newlyInsertedEntries = newlyInserted.map((insert) => {
          return new OutputEntryViewHandler(insert, this.u.createInstance(CellOutputElement, this.h, this.j, this, this.n.outputContainer, insert));
        });
        this.b = [...firstGroupEntries, ...newlyInsertedEntries, ...secondGroupEntries.slice(0, this.r.limit - firstGroupEntries.length - newlyInserted.length)];
        for (let i2 = firstGroupEntries.length; i2 < reRenderRightBoundary; i2++) {
          const previousSibling = i2 - 1 >= 0 && this.b[i2 - 1] && !!this.b[i2 - 1].element.innerContainer?.parentElement ? this.b[i2 - 1].element.innerContainer : void 0;
          this.b[i2].element.render(previousSibling);
        }
      }
    } else {
      deletedEntries.forEach((entry) => {
        entry.element.detach();
        entry.element.dispose();
      });
      const reRenderRightBoundary = firstGroupEntries.length + newlyInserted.length;
      const newlyInsertedEntries = newlyInserted.map((insert) => {
        return new OutputEntryViewHandler(insert, this.u.createInstance(CellOutputElement, this.h, this.j, this, this.n.outputContainer, insert));
      });
      let outputsNewlyAvailable = [];
      if (firstGroupEntries.length + newlyInsertedEntries.length + secondGroupEntries.length < this.j.outputsViewModels.length) {
        const last = Math.min(this.r.limit, this.j.outputsViewModels.length);
        outputsNewlyAvailable = this.j.outputsViewModels.slice(firstGroupEntries.length + newlyInsertedEntries.length + secondGroupEntries.length, last).map((output) => {
          return new OutputEntryViewHandler(output, this.u.createInstance(CellOutputElement, this.h, this.j, this, this.n.outputContainer, output));
        });
      }
      this.b = [...firstGroupEntries, ...newlyInsertedEntries, ...secondGroupEntries, ...outputsNewlyAvailable];
      for (let i2 = firstGroupEntries.length; i2 < reRenderRightBoundary; i2++) {
        const previousSibling = i2 - 1 >= 0 && this.b[i2 - 1] && !!this.b[i2 - 1].element.innerContainer?.parentElement ? this.b[i2 - 1].element.innerContainer : void 0;
        this.b[i2].element.render(previousSibling);
      }
      for (let i2 = 0; i2 < outputsNewlyAvailable.length; i2++) {
        this.b[firstGroupEntries.length + newlyInserted.length + secondGroupEntries.length + i2].element.render(void 0);
      }
    }
    if (this.j.outputsViewModels.length > this.r.limit) {
      $hk(this.n.outputShowMoreContainer.domNode);
      if (!this.n.outputShowMoreContainer.domNode.hasChildNodes()) {
        this.n.outputShowMoreContainer.domNode.appendChild(this.F(this.n.templateDisposables));
      }
      this.j.updateOutputShowMoreContainerHeight(46);
    } else {
      $ik(this.n.outputShowMoreContainer.domNode);
    }
    this.G();
    this.z(context === 2 && this.j.outputsViewModels.length === 0);
  }
  F(disposables) {
    const md = {
      value: `There are more than ${this.r.limit} outputs, [show more (open the raw output data in a text editor) ...](command:workbench.action.openLargeOutput)`,
      isTrusted: true,
      supportThemeIcons: true
    };
    const rendered = $D1(md, {
      actionHandler: {
        callback: (content) => {
          if (content === "command:workbench.action.openLargeOutput") {
            this.s.open(CellUri.generateCellOutputUri(this.h.textModel.uri));
          }
          return;
        },
        disposables
      }
    });
    disposables.add(rendered);
    rendered.element.classList.add("output-show-more");
    return rendered.element;
  }
  G() {
    this.h.layoutNotebookCell(this.j, this.j.layoutInfo.totalHeight);
  }
  dispose() {
    this.j.updateOutputMinHeight(0);
    if (this.y) {
      clearTimeout(this.y);
    }
    this.b.forEach((entry) => {
      entry.element.dispose();
    });
    super.dispose();
  }
};
$$Kb = __decorate([
  __param(4, $O4),
  __param(5, $wL),
  __param(6, $Pk)
], $$Kb);
var JUPYTER_RENDERER_MIMETYPES = [
  "application/geo+json",
  "application/vdom.v1+json",
  "application/vnd.dataresource+json",
  "application/vnd.plotly.v1+json",
  "application/vnd.vega.v2+json",
  "application/vnd.vega.v3+json",
  "application/vnd.vega.v4+json",
  "application/vnd.vega.v5+json",
  "application/vnd.vegalite.v1+json",
  "application/vnd.vegalite.v2+json",
  "application/vnd.vegalite.v3+json",
  "application/vnd.vegalite.v4+json",
  "application/x-nteract-model-debug+json",
  "image/svg+xml",
  "text/latex",
  "text/vnd.plotly.v1+html",
  "application/vnd.jupyter.widget-view+json",
  "application/vnd.code.notebook.error"
];

// out-build/vs/workbench/contrib/notebook/browser/view/cellParts/codeCellExecutionIcon.js
var $_Kb = class $_Kb2 extends $3c {
  constructor(_notebookEditor, b, c, f) {
    super();
    this.b = b;
    this.c = c;
    this.f = f;
    this.a = false;
    this.g();
    this.B(this.f.onDidChangeExecution((e) => {
      if (e.type === NotebookExecutionType.cell && e.affectsCell(this.b.uri)) {
        this.g();
      }
    }));
    this.B(this.b.model.onDidChangeInternalMetadata(() => this.g()));
  }
  setVisibility(visible) {
    this.a = visible;
    this.g();
  }
  g() {
    if (!this.a) {
      return;
    }
    const runState = this.f.getCellExecution(this.b.uri);
    const item = this.h(runState, this.b.model.internalMetadata);
    if (item) {
      this.c.style.display = "";
      $dk(this.c, ...$B1(item.text));
      this.c.title = item.tooltip ?? "";
    } else {
      this.c.style.display = "none";
      $dk(this.c);
    }
  }
  h(runState, internalMetadata) {
    const state = runState?.state;
    const { lastRunSuccess } = internalMetadata;
    if (!state && lastRunSuccess) {
      return {
        text: `$(${$OKb.id})`,
        tooltip: localize(8591, null)
      };
    } else if (!state && lastRunSuccess === false) {
      return {
        text: `$(${$PKb.id})`,
        tooltip: localize(8592, null)
      };
    } else if (state === NotebookCellExecutionState.Pending || state === NotebookCellExecutionState.Unconfirmed) {
      return {
        text: `$(${$QKb.id})`,
        tooltip: localize(8593, null)
      };
    } else if (state === NotebookCellExecutionState.Executing) {
      const icon2 = ThemeIcon.modify($RKb, "spin");
      return {
        text: `$(${icon2.id})`,
        tooltip: localize(8594, null)
      };
    }
    return;
  }
};
$_Kb = __decorate([
  __param(3, $wL)
], $_Kb);

// out-build/vs/workbench/contrib/notebook/browser/view/cellParts/codeCell.js
var $aLb = class $aLb2 extends $3c {
  constructor(r2, s, t, u, w, y, openerService, z, C, notebookExecutionStateService) {
    super();
    this.r = r2;
    this.s = s;
    this.t = t;
    this.u = u;
    this.w = w;
    this.y = y;
    this.z = z;
    this.C = C;
    this.g = false;
    this.n = this.B(new $oKb(this.r.getBaseCellEditorOptions(s.language), this.r.notebookOptions, this.C));
    this.a = this.w.createInstance($$Kb, r2, s, t, { limit: $WIb });
    this.h = this.B(t.cellParts.concatContentPart([this.n, this.a], getWindow(r2.getDomNode())));
    const editorHeight = this.J();
    this.L(editorHeight);
    this.c = false;
    this.O();
    this.Q();
    this.R();
    this.U();
    this.B(Event2.any(this.s.onDidStartExecution, this.s.onDidStopExecution)((e) => {
      this.h.updateForExecutionState(this.s, e);
    }));
    this.B(this.s.onDidChangeState((e) => {
      this.h.updateState(this.s, e);
      if (e.outputIsHoveredChanged) {
        this.H();
      }
      if (e.outputIsFocusedChanged) {
        this.I();
      }
      if (e.metadataChanged || e.internalMetadataChanged) {
        this.N();
      }
      if (e.inputCollapsedChanged || e.outputCollapsedChanged) {
        this.s.pauseLayout();
        const updated = this.Y();
        this.s.resumeLayout();
        if (updated) {
          this.relayoutCell();
        }
      }
      if (e.focusModeChanged) {
        this.X(true);
      }
    }));
    this.h.scheduleRenderCell(this.s);
    this.B($1c(() => {
      this.h.unrenderCell(this.s);
    }));
    this.N();
    this.X(false);
    this.H();
    this.I();
    this.s.editorHeight = editorHeight;
    this.a.render();
    this.f = false;
    this.ib();
    this.B(this.s.onLayoutInfoRead(() => {
      this.h.prepareLayout();
    }));
    const executionItemElement = $bk(this.t.cellInputCollapsedContainer, $(".collapsed-execution-icon"));
    this.B($1c(() => {
      executionItemElement.remove();
    }));
    this.m = this.B(this.w.createInstance($_Kb, this.r, this.s, executionItemElement));
    this.Y();
    this.B(Event2.runAndSubscribe(s.onDidChangeOutputs, this.M.bind(this)));
    this.B(Event2.runAndSubscribe(s.onDidChangeLayout, this.G.bind(this)));
    this.n.setLineNumbers(this.s.lineNumbers);
    t.editor.updateOptions(this.n.getUpdatedValue(this.s.internalMetadata, this.s.uri));
  }
  D(templateData) {
    templateData.editor.updateOptions(this.n.getUpdatedValue(this.s.internalMetadata, this.s.uri));
    const cts = new $ad();
    this.B({ dispose() {
      cts.dispose(true);
    } });
    $Ih(this.s.resolveTextModel(), cts.token).then((model) => {
      if (this.g) {
        return;
      }
      if (model) {
        model.updateOptions({
          indentSize: this.n.indentSize,
          tabSize: this.n.tabSize,
          insertSpaces: this.n.insertSpaces
        });
      }
    });
  }
  G() {
    this.F?.dispose();
    this.F = $nj(getWindow(this.r.getDomNode()), () => {
      this.h.updateInternalLayoutNow(this.s);
    });
  }
  H() {
    this.t.container.classList.toggle("cell-output-hover", this.s.outputIsHovered);
  }
  I() {
    this.t.container.classList.toggle("cell-output-focus", this.s.outputIsFocused);
  }
  J() {
    const lineNum = this.s.lineCount;
    const lineHeight = this.s.layoutInfo.fontInfo?.lineHeight || 17;
    const editorPadding = this.r.notebookOptions.computeEditorPadding(this.s.internalMetadata, this.s.uri);
    const editorHeight = this.s.layoutInfo.editorHeight === 0 ? lineNum * lineHeight + editorPadding.top + editorPadding.bottom : this.s.layoutInfo.editorHeight;
    return editorHeight;
  }
  L(initEditorHeight) {
    const width2 = this.s.layoutInfo.editorWidth;
    this.jb({
      width: width2,
      height: initEditorHeight
    });
    const cts = new $ad();
    this.B({ dispose() {
      cts.dispose(true);
    } });
    $Ih(this.s.resolveTextModel(), cts.token).then((model) => {
      if (this.g) {
        return;
      }
      if (model && this.t.editor) {
        this.S(model);
        this.t.editor.setModel(model);
        if (this.g) {
          return;
        }
        model.updateOptions({
          indentSize: this.n.indentSize,
          tabSize: this.n.tabSize,
          insertSpaces: this.n.insertSpaces
        });
        this.s.attachTextEditor(this.t.editor, this.s.layoutInfo.estimatedHasHorizontalScrolling);
        const focusEditorIfNeeded = () => {
          if (this.r.getActiveCell() === this.s && this.s.focusMode === CellFocusMode.Editor && (this.r.hasEditorFocus() || this.r.getDomNode().ownerDocument.activeElement === this.r.getDomNode().ownerDocument.body)) {
            this.t.editor?.focus();
          }
        };
        focusEditorIfNeeded();
        const realContentHeight = this.t.editor?.getContentHeight();
        if (realContentHeight !== void 0 && realContentHeight !== initEditorHeight) {
          this.lb(realContentHeight);
        }
        if (this.g) {
          return;
        }
        focusEditorIfNeeded();
      }
      this.B(this.n.onDidChange(() => this.D(this.t)));
    });
  }
  M() {
    $gk(this.s.outputsViewModels.length > 0, this.t.focusSinkElement);
  }
  N() {
    const editor = this.t.editor;
    if (!editor) {
      return;
    }
    const isReadonly = this.r.isReadOnly;
    const padding = this.r.notebookOptions.computeEditorPadding(this.s.internalMetadata, this.s.uri);
    const options3 = editor.getOptions();
    if (options3.get(
      96
      /* EditorOption.readOnly */
    ) !== isReadonly || options3.get(
      88
      /* EditorOption.padding */
    ) !== padding) {
      editor.updateOptions({ readOnly: this.r.isReadOnly, padding: this.r.notebookOptions.computeEditorPadding(this.s.internalMetadata, this.s.uri) });
    }
  }
  O() {
    this.B(this.r.onDidScroll(() => {
      this.P();
    }));
    this.B(this.r.onDidChangeLayout(() => {
      this.P();
      this.kb();
    }));
  }
  P() {
    const extraOffset = -6 - 1;
    const min = 0;
    const scrollTop = this.r.scrollTop;
    const elementTop = this.r.getAbsoluteTopOfElement(this.s);
    const diff3 = scrollTop - elementTop + extraOffset;
    const notebookEditorLayout = this.r.getLayoutInfo();
    const editorMaxHeight = notebookEditorLayout.height - notebookEditorLayout.stickyHeight - 26;
    const maxTop = this.s.layoutInfo.editorHeight - editorMaxHeight;
    const top2 = maxTop > 20 ? $4i(min, diff3, maxTop) : min;
    this.t.editorPart.style.top = `${top2}px`;
    this.t.editor?.setScrollTop(top2);
  }
  Q() {
    this.B(this.s.onDidChangeLayout((e) => {
      if (e.outerWidth !== void 0) {
        const layoutInfo = this.t.editor.getLayoutInfo();
        if (layoutInfo.width !== this.s.layoutInfo.editorWidth) {
          this.kb();
          this.P();
        }
      }
    }));
  }
  R() {
    this.B(this.t.editor.onDidContentSizeChange((e) => {
      if (e.contentHeightChanged) {
        if (this.s.layoutInfo.editorHeight !== e.contentHeight) {
          this.lb(e.contentHeight);
          this.P();
        }
      }
    }));
    this.B(this.t.editor.onDidChangeCursorSelection((e) => {
      if (e.source === "restoreState" || e.oldModelVersionId === 0) {
        return;
      }
      const selections = this.t.editor.getSelections();
      if (selections?.length) {
        const contentHeight = this.t.editor.getContentHeight();
        const layoutContentHeight = this.s.layoutInfo.editorHeight;
        if (contentHeight !== layoutContentHeight) {
          this.lb(contentHeight);
          if (this.g) {
            return;
          }
        }
        const lastSelection = selections[selections.length - 1];
        this.r.revealRangeInViewAsync(this.s, lastSelection);
      }
    }));
    this.B(this.t.editor.onDidBlurEditorWidget(() => {
      $fbb.get(this.t.editor)?.hideCodeActions();
      $fbb.get(this.t.editor)?.hideLightBulbWidget();
    }));
  }
  S(model) {
    this.B(model.onDidChangeTokens(() => {
      if (this.s.isInputCollapsed && this.b) {
        const content = this.db(model);
        $wk(this.b, content);
        this.ab(this.b);
      }
    }));
  }
  U() {
    this.B(this.t.editor.onMouseDown((e) => {
      if (e.event.rightButton) {
        e.event.preventDefault();
      }
    }));
  }
  W() {
    return this.r.getActiveCell() === this.s && this.s.focusMode === CellFocusMode.Editor && (this.r.hasEditorFocus() || this.r.getDomNode().ownerDocument.activeElement === this.r.getDomNode().ownerDocument.body);
  }
  X(sync) {
    if (this.W()) {
      if (sync) {
        this.t.editor?.focus();
      } else {
        this.B($ij(getWindow(this.t.container), () => {
          this.t.editor?.focus();
        }));
      }
    }
    this.t.container.classList.toggle("cell-editor-focus", this.s.focusMode === CellFocusMode.Editor);
    this.t.container.classList.toggle("cell-output-focus", this.s.focusMode === CellFocusMode.Output);
  }
  Y() {
    if (this.s.isOutputCollapsed === this.f && this.s.isInputCollapsed === this.c) {
      return false;
    }
    this.s.layoutChange({ editorHeight: true });
    if (this.s.isInputCollapsed) {
      this.Z();
    } else {
      this.bb();
    }
    if (this.s.isOutputCollapsed) {
      this.gb();
    } else {
      this.hb(false);
    }
    this.relayoutCell();
    this.f = this.s.isOutputCollapsed;
    this.c = this.s.isInputCollapsed;
    return true;
  }
  Z() {
    $ik(this.t.editorPart);
    this.t.container.classList.toggle("input-collapsed", true);
    this.eb();
    this.m.setVisibility(true);
    const richEditorText = this.t.editor.hasModel() ? this.db(this.t.editor.getModel()) : this.cb(this.s.textBuffer, this.s.language);
    const element = $("div.cell-collapse-preview");
    $wk(element, richEditorText);
    this.b = element;
    this.t.cellInputCollapsedContainer.appendChild(element);
    this.ab(element);
    $hk(this.t.cellInputCollapsedContainer);
  }
  ab(element) {
    const expandIcon2 = $("span.expandInputIcon");
    const keybinding = this.y.lookupKeybinding($Grb);
    if (keybinding) {
      element.title = localize(8589, null, keybinding.getLabel());
      expandIcon2.title = localize(8590, null, keybinding.getLabel());
    }
    expandIcon2.classList.add(...ThemeIcon.asClassNameArray($6l.more));
    element.appendChild(expandIcon2);
  }
  bb() {
    this.m.setVisibility(false);
    $hk(this.t.editorPart);
    $ik(this.t.cellInputCollapsedContainer);
  }
  cb(buffer, language) {
    return $n9(this.z, buffer.getLineContent(1), language);
  }
  db(model) {
    let result = `<div class="monaco-tokenized-source">`;
    const firstLineTokens = model.tokenization.getLineTokens(1);
    const viewLineTokens = firstLineTokens.inflate();
    const line = model.getLineContent(1);
    let startOffset = 0;
    for (let j = 0, lenJ = viewLineTokens.getCount(); j < lenJ; j++) {
      const type = viewLineTokens.getClassName(j);
      const endIndex = viewLineTokens.getEndOffset(j);
      result += `<span class="${type}">${$zf(line.substring(startOffset, endIndex))}</span>`;
      startOffset = endIndex;
    }
    result += `</div>`;
    return result;
  }
  eb() {
    const children = this.t.cellInputCollapsedContainer.children;
    const elements = [];
    for (let i2 = 0; i2 < children.length; i2++) {
      if (children[i2].classList.contains("cell-collapse-preview")) {
        elements.push(children[i2]);
      }
    }
    elements.forEach((element) => {
      element.remove();
    });
  }
  fb(hide3) {
    const children = this.t.outputContainer.domNode.children;
    for (let i2 = 0; i2 < children.length; i2++) {
      if (children[i2].classList.contains("output-inner-container")) {
        $gk(!hide3, children[i2]);
      }
    }
  }
  gb() {
    this.t.container.classList.toggle("output-collapsed", true);
    $hk(this.t.cellOutputCollapsedContainer);
    this.fb(true);
    this.a.viewUpdateHideOuputs();
  }
  hb(initRendering) {
    this.t.container.classList.toggle("output-collapsed", false);
    $ik(this.t.cellOutputCollapsedContainer);
    this.fb(false);
    this.a.viewUpdateShowOutputs(initRendering);
  }
  ib() {
    this.t.container.classList.toggle("input-collapsed", false);
    $hk(this.t.editorPart);
    $ik(this.t.cellInputCollapsedContainer);
    this.t.container.classList.toggle("output-collapsed", false);
    this.hb(true);
  }
  jb(dimension) {
    const editorLayout = this.r.getLayoutInfo();
    const maxHeight = Math.min(editorLayout.height - editorLayout.stickyHeight - 26, dimension.height);
    this.t.editor?.layout({
      width: dimension.width,
      height: maxHeight
    }, true);
  }
  kb() {
    if (!this.t.editor.hasModel()) {
      return;
    }
    const realContentHeight = this.t.editor.getContentHeight();
    this.s.editorHeight = realContentHeight;
    this.relayoutCell();
    this.jb({
      width: this.s.layoutInfo.editorWidth,
      height: realContentHeight
    });
  }
  lb(newHeight) {
    const viewLayout = this.t.editor.getLayoutInfo();
    this.s.editorHeight = newHeight;
    this.relayoutCell();
    this.jb({
      width: viewLayout.width,
      height: newHeight
    });
  }
  relayoutCell() {
    this.r.layoutNotebookCell(this.s, this.s.layoutInfo.totalHeight);
  }
  dispose() {
    this.g = true;
    if (this.W()) {
      this.u.preserveFocusedEditor(this.s);
    }
    this.s.detachTextEditor();
    this.eb();
    this.a.dispose();
    this.F?.dispose();
    super.dispose();
  }
};
$aLb = __decorate([
  __param(4, $Pk),
  __param(5, $Ty),
  __param(6, $O4),
  __param(7, $1E),
  __param(8, $kl),
  __param(9, $wL)
], $aLb);

// out-build/vs/workbench/contrib/notebook/browser/view/cellParts/codeCellRunToolbar.js
var $bLb = class $bLb2 extends $lJb {
  constructor(notebookEditor, contextKeyService, cellContainer, runButtonContainer, primaryMenuId, secondaryMenuId, menuService, j, m, n) {
    super();
    this.notebookEditor = notebookEditor;
    this.contextKeyService = contextKeyService;
    this.cellContainer = cellContainer;
    this.runButtonContainer = runButtonContainer;
    this.j = j;
    this.m = m;
    this.n = n;
    this.b = this.B(menuService.createMenu(primaryMenuId, contextKeyService));
    this.h = this.B(menuService.createMenu(secondaryMenuId, contextKeyService));
    this.r(runButtonContainer, cellContainer, contextKeyService);
    const updateActions = () => {
      const actions = this.getCellToolbarActions(this.b);
      const primary = actions.primary[0];
      this.a.setActions(primary ? [primary] : []);
    };
    updateActions();
    this.B(this.b.onDidChange(updateActions));
    this.B(this.h.onDidChange(updateActions));
    this.B(this.notebookEditor.notebookOptions.onDidChangeOptions(updateActions));
  }
  didRenderCell(element) {
    this.f.add($uKb(this.notebookEditor, element, this.runButtonContainer));
    if (this.notebookEditor.hasModel()) {
      const context = {
        ui: true,
        cell: element,
        notebookEditor: this.notebookEditor,
        $mid: 13
        /* MarshalledId.NotebookCellActionContext */
      };
      this.a.context = context;
    }
  }
  getCellToolbarActions(menu) {
    return $Q$(menu.getActions({ shouldForwardArgs: true }), (g) => /^inline/.test(g));
  }
  r(container2, cellContainer, contextKeyService) {
    const actionViewItemDisposables = this.B(new $2c());
    const dropdownAction = this.B(new $Um("notebook.moreRunActions", localize(8595, null), "codicon-chevron-down", true));
    const keybindingProvider = (action) => this.j.lookupKeybinding(action.id, executionContextKeyService);
    const executionContextKeyService = this.B($cLb(contextKeyService));
    this.a = this.B(new $f3(container2, this.m, {
      getKeyBinding: keybindingProvider,
      actionViewItemProvider: (_action, _options) => {
        actionViewItemDisposables.clear();
        const primary = this.getCellToolbarActions(this.b).primary[0];
        if (!(primary instanceof $fJ)) {
          return void 0;
        }
        const secondary = this.getCellToolbarActions(this.h).secondary;
        if (!secondary.length) {
          return void 0;
        }
        const item = this.n.createInstance($isb, primary, dropdownAction, secondary, "notebook-cell-run-toolbar", {
          ..._options,
          getKeyBinding: keybindingProvider
        });
        actionViewItemDisposables.add(item.onDidChangeDropdownVisibility((visible) => {
          cellContainer.classList.toggle("cell-run-toolbar-dropdown-active", visible);
        }));
        return item;
      },
      renderDropdownAsChildElement: true
    }));
  }
};
$bLb = __decorate([
  __param(6, $cJ),
  __param(7, $Ty),
  __param(8, $50),
  __param(9, $Pk)
], $bLb);
function $cLb(contextKeyService) {
  const executionContextKeyService = contextKeyService.createScoped(document.createElement("div"));
  $Ceb.bindTo(executionContextKeyService).set(true);
  EditorContextKeys.editorTextFocus.bindTo(executionContextKeyService).set(true);
  EditorContextKeys.focus.bindTo(executionContextKeyService).set(true);
  EditorContextKeys.textInputFocus.bindTo(executionContextKeyService).set(true);
  $dBb.bindTo(executionContextKeyService).set("idle");
  $XAb.bindTo(executionContextKeyService).set(true);
  $WAb.bindTo(executionContextKeyService).set(true);
  $0Ab.bindTo(executionContextKeyService).set("code");
  return executionContextKeyService;
}

// out-build/vs/workbench/contrib/notebook/browser/view/cellParts/collapsedCellInput.js
var $dLb = class extends $lJb {
  constructor(a, cellInputCollapsedContainer) {
    super();
    this.a = a;
    this.B($_i(cellInputCollapsedContainer, $7j.DBLCLICK, (e) => {
      if (!this.c || !this.a.hasModel()) {
        return;
      }
      if (this.c.isInputCollapsed) {
        this.c.isInputCollapsed = false;
      } else {
        this.c.isOutputCollapsed = false;
      }
    }));
    this.B($_i(cellInputCollapsedContainer, $7j.CLICK, (e) => {
      if (!this.c || !this.a.hasModel()) {
        return;
      }
      const element = e.target;
      if (element && element.classList && element.classList.contains("expandInputIcon")) {
        this.c.isInputCollapsed = false;
      }
    }));
  }
};

// out-build/vs/workbench/contrib/notebook/browser/view/cellParts/collapsedCellOutput.js
var $123 = $;
var $eLb = class $eLb2 extends $lJb {
  constructor(a, cellOutputCollapseContainer, keybindingService) {
    super();
    this.a = a;
    const placeholder = $bk(cellOutputCollapseContainer, $123("span.expandOutputPlaceholder"));
    placeholder.textContent = localize(8596, null);
    const expandIcon2 = $bk(cellOutputCollapseContainer, $123("span.expandOutputIcon"));
    expandIcon2.classList.add(...ThemeIcon.asClassNameArray($6l.more));
    const keybinding = keybindingService.lookupKeybinding($Lrb);
    if (keybinding) {
      placeholder.title = localize(8597, null, keybinding.getLabel());
      cellOutputCollapseContainer.title = localize(8598, null, keybinding.getLabel());
    }
    $ik(cellOutputCollapseContainer);
    this.B($_i(expandIcon2, $7j.CLICK, () => this.b()));
    this.B($_i(cellOutputCollapseContainer, $7j.DBLCLICK, () => this.b()));
  }
  b() {
    if (!this.c) {
      return;
    }
    if (!this.c) {
      return;
    }
    const textModel = this.a.textModel;
    const index = textModel.cells.indexOf(this.c.model);
    if (index < 0) {
      return;
    }
    this.c.isOutputCollapsed = !this.c.isOutputCollapsed;
  }
};
$eLb = __decorate([
  __param(2, $Ty)
], $eLb);

// out-build/vs/workbench/contrib/notebook/browser/viewModel/foldingModel.js
var foldingRangeLimit = {
  limit: 5e3,
  update: () => {
  }
};
var $fLb = class {
  get regions() {
    return this.c;
  }
  constructor() {
    this.a = null;
    this.b = new $2c();
    this.d = new $ze();
    this.onDidFoldingRegionChanged = this.d.event;
    this.e = [];
    this.c = new $Jgb(new Uint32Array(0), new Uint32Array(0));
  }
  dispose() {
    this.d.dispose();
    this.b.dispose();
  }
  detachViewModel() {
    this.b.clear();
    this.a = null;
  }
  attachViewModel(model) {
    this.a = model;
    this.b.add(this.a.onDidChangeViewCells(() => {
      this.recompute();
    }));
    this.b.add(this.a.onDidChangeSelection(() => {
      if (!this.a) {
        return;
      }
      const indexes = $GL(this.a.getSelections());
      let changed = false;
      indexes.forEach((index) => {
        let regionIndex = this.regions.findRange(index + 1);
        while (regionIndex !== -1) {
          if (this.c.isCollapsed(regionIndex) && index > this.c.getStartLineNumber(regionIndex) - 1) {
            this.c.setCollapsed(regionIndex, false);
            changed = true;
          }
          regionIndex = this.c.getParentIndex(regionIndex);
        }
      });
      if (changed) {
        this.d.fire();
      }
    }));
    this.recompute();
  }
  getRegionAtLine(lineNumber) {
    if (this.c) {
      const index = this.c.findRange(lineNumber);
      if (index >= 0) {
        return this.c.toRegion(index);
      }
    }
    return null;
  }
  getRegionsInside(region, filter) {
    const result = [];
    const index = region ? region.regionIndex + 1 : 0;
    const endLineNumber = region ? region.endLineNumber : Number.MAX_VALUE;
    if (filter && filter.length === 2) {
      const levelStack = [];
      for (let i2 = index, len = this.c.length; i2 < len; i2++) {
        const current = this.c.toRegion(i2);
        if (this.c.getStartLineNumber(i2) < endLineNumber) {
          while (levelStack.length > 0 && !current.containedBy(levelStack[levelStack.length - 1])) {
            levelStack.pop();
          }
          levelStack.push(current);
          if (filter(current, levelStack.length)) {
            result.push(current);
          }
        } else {
          break;
        }
      }
    } else {
      for (let i2 = index, len = this.c.length; i2 < len; i2++) {
        const current = this.c.toRegion(i2);
        if (this.c.getStartLineNumber(i2) < endLineNumber) {
          if (!filter || filter(current)) {
            result.push(current);
          }
        } else {
          break;
        }
      }
    }
    return result;
  }
  getAllRegionsAtLine(lineNumber, filter) {
    const result = [];
    if (this.c) {
      let index = this.c.findRange(lineNumber);
      let level = 1;
      while (index >= 0) {
        const current = this.c.toRegion(index);
        if (!filter || filter(current, level)) {
          result.push(current);
        }
        level++;
        index = current.parentIndex;
      }
    }
    return result;
  }
  setCollapsed(index, newState) {
    this.c.setCollapsed(index, newState);
  }
  recompute() {
    if (!this.a) {
      return;
    }
    const viewModel = this.a;
    const cells = viewModel.viewCells;
    const stack = [];
    for (let i3 = 0; i3 < cells.length; i3++) {
      const cell = cells[i3];
      if (cell.cellKind !== CellKind.Markup || cell.language !== "markdown") {
        continue;
      }
      const minDepth = Math.min(7, ...Array.from($hLb(cell.getText()), (header) => header.depth));
      if (minDepth < 7) {
        stack.push({ index: i3, level: minDepth, endIndex: 0 });
      }
    }
    const rawFoldingRanges = stack.map((entry, startIndex) => {
      let end = void 0;
      for (let i3 = startIndex + 1; i3 < stack.length; ++i3) {
        if (stack[i3].level <= entry.level) {
          end = stack[i3].index - 1;
          break;
        }
      }
      const endIndex = end !== void 0 ? end : cells.length - 1;
      return {
        start: entry.index + 1,
        end: endIndex + 1,
        rank: 1
      };
    }).filter((range) => range.start !== range.end);
    const newRegions = $8gb(rawFoldingRanges, foldingRangeLimit);
    let i2 = 0;
    const nextCollapsed = () => {
      while (i2 < this.c.length) {
        const isCollapsed = this.c.isCollapsed(i2);
        i2++;
        if (isCollapsed) {
          return i2 - 1;
        }
      }
      return -1;
    };
    let k = 0;
    let collapsedIndex = nextCollapsed();
    while (collapsedIndex !== -1 && k < newRegions.length) {
      const decRange = viewModel.getTrackedRange(this.e[collapsedIndex]);
      if (decRange) {
        const collasedStartIndex = decRange.start;
        while (k < newRegions.length) {
          const startIndex = newRegions.getStartLineNumber(k) - 1;
          if (collasedStartIndex >= startIndex) {
            newRegions.setCollapsed(k, collasedStartIndex === startIndex);
            k++;
          } else {
            break;
          }
        }
      }
      collapsedIndex = nextCollapsed();
    }
    while (k < newRegions.length) {
      newRegions.setCollapsed(k, false);
      k++;
    }
    const cellRanges = [];
    for (let i3 = 0; i3 < newRegions.length; i3++) {
      const region = newRegions.toRegion(i3);
      cellRanges.push({ start: region.startLineNumber - 1, end: region.endLineNumber - 1 });
    }
    this.e.forEach((id2) => viewModel.setTrackedRange(
      id2,
      null,
      3
      /* TrackedRangeStickiness.GrowsOnlyWhenTypingAfter */
    ));
    this.e = cellRanges.map((region) => viewModel.setTrackedRange(
      null,
      region,
      3
      /* TrackedRangeStickiness.GrowsOnlyWhenTypingAfter */
    )).filter((str) => str !== null);
    this.c = newRegions;
    this.d.fire();
  }
  getMemento() {
    const collapsedRanges = [];
    let i2 = 0;
    while (i2 < this.c.length) {
      const isCollapsed = this.c.isCollapsed(i2);
      if (isCollapsed) {
        const region = this.c.toRegion(i2);
        collapsedRanges.push({ start: region.startLineNumber - 1, end: region.endLineNumber - 1 });
      }
      i2++;
    }
    return collapsedRanges;
  }
  applyMemento(state) {
    if (!this.a) {
      return false;
    }
    let i2 = 0;
    let k = 0;
    while (k < state.length && i2 < this.c.length) {
      const decRange = this.a.getTrackedRange(this.e[i2]);
      if (decRange) {
        const collasedStartIndex = state[k].start;
        while (i2 < this.c.length) {
          const startIndex = this.c.getStartLineNumber(i2) - 1;
          if (collasedStartIndex >= startIndex) {
            this.c.setCollapsed(i2, collasedStartIndex === startIndex);
            i2++;
          } else {
            break;
          }
        }
      }
      k++;
    }
    while (i2 < this.c.length) {
      this.c.setCollapsed(i2, false);
      i2++;
    }
    return true;
  }
};
function* $hLb(cellContent) {
  for (const token of marked.lexer(cellContent, { gfm: true })) {
    if (token.type === "heading") {
      yield {
        depth: token.depth,
        text: $G1({ value: token.raw }).trim()
      };
    }
  }
}

// out-build/vs/workbench/contrib/notebook/browser/controller/foldingController.js
var $iLb = class extends $3c {
  static {
    this.id = "workbench.notebook.foldingController";
  }
  constructor(c) {
    super();
    this.c = c;
    this.a = null;
    this.b = this.B(new $2c());
    this.B(this.c.onMouseUp((e) => {
      this.onMouseUp(e);
    }));
    this.B(this.c.onDidChangeModel(() => {
      this.b.clear();
      if (!this.c.hasModel()) {
        return;
      }
      this.b.add(this.c.onDidChangeCellState((e) => {
        if (e.source.editStateChanged && e.cell.cellKind === CellKind.Markup) {
          this.a?.recompute();
        }
      }));
      this.a = new $fLb();
      this.b.add(this.a);
      this.a.attachViewModel(this.c.getViewModel());
      this.b.add(this.a.onDidFoldingRegionChanged(() => {
        this.f();
      }));
    }));
  }
  saveViewState() {
    return this.a?.getMemento() || [];
  }
  restoreViewState(state) {
    this.a?.applyMemento(state || []);
    this.f();
  }
  setFoldingStateDown(index, state, levels) {
    const doCollapse = state === 2;
    const region = this.a.getRegionAtLine(index + 1);
    const regions = [];
    if (region) {
      if (region.isCollapsed !== doCollapse) {
        regions.push(region);
      }
      if (levels > 1) {
        const regionsInside = this.a.getRegionsInside(region, (r2, level) => r2.isCollapsed !== doCollapse && level < levels);
        regions.push(...regionsInside);
      }
    }
    regions.forEach((r2) => this.a.setCollapsed(
      r2.regionIndex,
      state === 2
      /* CellFoldingState.Collapsed */
    ));
    this.f();
  }
  setFoldingStateUp(index, state, levels) {
    if (!this.a) {
      return;
    }
    const regions = this.a.getAllRegionsAtLine(index + 1, (region, level) => region.isCollapsed !== (state === 2) && level <= levels);
    regions.forEach((r2) => this.a.setCollapsed(
      r2.regionIndex,
      state === 2
      /* CellFoldingState.Collapsed */
    ));
    this.f();
  }
  f() {
    if (!this.a) {
      return;
    }
    if (!this.c.hasModel()) {
      return;
    }
    const vm = this.c.getViewModel();
    vm.updateFoldingRanges(this.a.regions);
    const hiddenRanges = vm.getHiddenRanges();
    this.c.setHiddenAreas(hiddenRanges);
  }
  onMouseUp(e) {
    if (!e.event.target) {
      return;
    }
    if (!this.c.hasModel()) {
      return;
    }
    const viewModel = this.c.getViewModel();
    const target = e.event.target;
    if (target.classList.contains("codicon-notebook-collapsed") || target.classList.contains("codicon-notebook-expanded")) {
      const parent = target.parentElement;
      if (!parent.classList.contains("notebook-folding-indicator")) {
        return;
      }
      const cellViewModel = e.target;
      const modelIndex = viewModel.getCellIndex(cellViewModel);
      const state = viewModel.getFoldingState(modelIndex);
      if (state === 0) {
        return;
      }
      this.setFoldingStateUp(modelIndex, state === 2 ? 1 : 2, 1);
      this.c.focusElement(cellViewModel);
    }
    return;
  }
  recompute() {
    this.a?.recompute();
  }
};
$iGb($iLb.id, $iLb);
var NOTEBOOK_FOLD_COMMAND_LABEL = localize(8296, null);
var NOTEBOOK_UNFOLD_COMMAND_LABEL = localize2(8297, "Unfold Cell");
var FOLDING_COMMAND_ARGS = {
  args: [{
    isOptional: true,
    name: "index",
    description: "The cell index",
    schema: {
      "type": "object",
      "required": ["index", "direction"],
      "properties": {
        "index": {
          "type": "number"
        },
        "direction": {
          "type": "string",
          "enum": ["up", "down"],
          "default": "down"
        },
        "levels": {
          "type": "number",
          "default": 1
        }
      }
    }
  }]
};
$hJ(class extends $gJ {
  constructor() {
    super({
      id: "notebook.fold",
      title: localize2(8298, "Fold Cell"),
      category: $xIb,
      keybinding: {
        when: $7m.and($WAb, $7m.not($Beb)),
        primary: 2048 | 1024 | 92,
        mac: {
          primary: 2048 | 512 | 92,
          secondary: [
            15
            /* KeyCode.LeftArrow */
          ]
        },
        secondary: [
          15
          /* KeyCode.LeftArrow */
        ],
        weight: 200
        /* KeybindingWeight.WorkbenchContrib */
      },
      metadata: {
        description: NOTEBOOK_FOLD_COMMAND_LABEL,
        args: FOLDING_COMMAND_ARGS.args
      },
      precondition: $SAb,
      f1: true
    });
  }
  async run(accessor, args2) {
    const editorService = accessor.get($mJ);
    const editor = $Qrb(editorService.activeEditorPane);
    if (!editor) {
      return;
    }
    if (!editor.hasModel()) {
      return;
    }
    const levels = args2 && args2.levels || 1;
    const direction = args2 && args2.direction === "up" ? "up" : "down";
    let index = void 0;
    if (args2) {
      index = args2.index;
    } else {
      const activeCell = editor.getActiveCell();
      if (!activeCell) {
        return;
      }
      index = editor.getCellIndex(activeCell);
    }
    const controller = editor.getContribution($iLb.id);
    if (index !== void 0) {
      const targetCell = index < 0 || index >= editor.getLength() ? void 0 : editor.cellAt(index);
      if (targetCell?.cellKind === CellKind.Code && direction === "down") {
        return;
      }
      if (direction === "up") {
        controller.setFoldingStateUp(index, 2, levels);
      } else {
        controller.setFoldingStateDown(index, 2, levels);
      }
      const viewIndex = editor.getViewModel().getNearestVisibleCellIndexUpwards(index);
      editor.focusElement(editor.cellAt(viewIndex));
    }
  }
});
$hJ(class extends $gJ {
  constructor() {
    super({
      id: "notebook.unfold",
      title: NOTEBOOK_UNFOLD_COMMAND_LABEL,
      category: $xIb,
      keybinding: {
        when: $7m.and($WAb, $7m.not($Beb)),
        primary: 2048 | 1024 | 94,
        mac: {
          primary: 2048 | 512 | 94,
          secondary: [
            17
            /* KeyCode.RightArrow */
          ]
        },
        secondary: [
          17
          /* KeyCode.RightArrow */
        ],
        weight: 200
        /* KeybindingWeight.WorkbenchContrib */
      },
      metadata: {
        description: NOTEBOOK_UNFOLD_COMMAND_LABEL,
        args: FOLDING_COMMAND_ARGS.args
      },
      precondition: $SAb,
      f1: true
    });
  }
  async run(accessor, args2) {
    const editorService = accessor.get($mJ);
    const editor = $Qrb(editorService.activeEditorPane);
    if (!editor) {
      return;
    }
    const levels = args2 && args2.levels || 1;
    const direction = args2 && args2.direction === "up" ? "up" : "down";
    let index = void 0;
    if (args2) {
      index = args2.index;
    } else {
      const activeCell = editor.getActiveCell();
      if (!activeCell) {
        return;
      }
      index = editor.getCellIndex(activeCell);
    }
    const controller = editor.getContribution($iLb.id);
    if (index !== void 0) {
      if (direction === "up") {
        controller.setFoldingStateUp(index, 1, levels);
      } else {
        controller.setFoldingStateDown(index, 1, levels);
      }
    }
  }
});

// out-build/vs/workbench/contrib/notebook/browser/view/cellParts/foldedCellHint.js
var $jLb = class $jLb2 extends $lJb {
  constructor(g, h3, j) {
    super();
    this.g = g;
    this.h = h3;
    this.j = j;
    this.a = this.B(new $4c());
    this.b = this.B(new $4c());
  }
  didRenderCell(element) {
    this.m(element);
  }
  m(element) {
    if (!this.g.hasModel()) {
      this.b.clear();
      this.a.clear();
      return;
    }
    if (element.isInputCollapsed || element.getEditState() === CellEditState.Editing) {
      this.b.clear();
      this.a.clear();
      $ik(this.h);
    } else if (element.foldingState === 2) {
      const idx = this.g.getViewModel().getCellIndex(element);
      const length = this.g.getViewModel().getFoldedLength(idx);
      const runSectionButton = this.s({ start: idx, end: idx + length + 1 });
      if (!runSectionButton) {
        $dk(this.h, this.n(length), this.r(element));
      } else {
        $dk(this.h, runSectionButton, this.n(length), this.r(element));
      }
      $hk(this.h);
      const foldHintTop = element.layoutInfo.previewHeight;
      this.h.style.top = `${foldHintTop}px`;
    } else {
      this.b.clear();
      this.a.clear();
      $ik(this.h);
    }
  }
  n(num) {
    const label3 = num === 1 ? localize(8599, null) : localize(8600, null, num);
    return $("span.notebook-folded-hint-label", void 0, label3);
  }
  r(element) {
    const expandIcon2 = $("span.cell-expand-part-button");
    expandIcon2.classList.add(...ThemeIcon.asClassNameArray($6l.more));
    this.B($_i(expandIcon2, $7j.CLICK, () => {
      const controller = this.g.getContribution($iLb.id);
      const idx = this.g.getCellIndex(element);
      if (typeof idx === "number") {
        controller.setFoldingStateDown(idx, 1, 1);
      }
    }));
    return expandIcon2;
  }
  s(range) {
    const runAllContainer = $("span.folded-cell-run-section-button");
    const cells = this.g.getCellsInRange(range);
    const hasCodeCells = cells.some((cell) => cell.cellKind === CellKind.Code);
    if (!hasCodeCells) {
      return void 0;
    }
    const isRunning = cells.some((cell) => {
      const cellExecution = this.j.getCellExecution(cell.uri);
      return cellExecution && cellExecution.state === NotebookCellExecutionState.Executing;
    });
    const runAllIcon = isRunning ? ThemeIcon.modify($RKb, "spin") : $6l.play;
    runAllContainer.classList.add(...ThemeIcon.asClassNameArray(runAllIcon));
    this.a.value = $_i(runAllContainer, $7j.CLICK, () => {
      this.g.executeNotebookCells(cells);
    });
    this.b.value = this.j.onDidChangeExecution(() => {
      const isRunning2 = cells.some((cell) => {
        const cellExecution = this.j.getCellExecution(cell.uri);
        return cellExecution && cellExecution.state === NotebookCellExecutionState.Executing;
      });
      const runAllIcon2 = isRunning2 ? ThemeIcon.modify($RKb, "spin") : $6l.play;
      runAllContainer.className = "";
      runAllContainer.classList.add("folded-cell-run-section-button", ...ThemeIcon.asClassNameArray(runAllIcon2));
    });
    return runAllContainer;
  }
  updateInternalLayoutNow(element) {
    this.m(element);
  }
};
$jLb = __decorate([
  __param(2, $wL)
], $jLb);

// out-build/vs/workbench/contrib/notebook/browser/view/cellParts/markupCell.js
var $kLb = class $kLb2 extends $3c {
  constructor(s, t, u, w, y, z, C, D, F, G) {
    super();
    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 = G;
    this.a = null;
    this.f = this.B(new $2c());
    this.g = this.B(new $4c());
    this.h = this.B(new $2c());
    this.r = false;
    this.H();
    this.c = u.editorPart;
    this.m = this.B(new $oKb(this.s.getBaseCellEditorOptions(t.language), this.s.notebookOptions, this.F));
    this.m.setLineNumbers(this.t.lineNumbers);
    this.n = this.m.getValue(this.t.internalMetadata, this.t.uri);
    this.B($1c(() => w.delete(this.t)));
    this.I();
    this.u.cellParts.scheduleRenderCell(this.t);
    this.B($1c(() => {
      this.u.cellParts.unrenderCell(this.t);
    }));
    this.B(this.y.onDidChangeScreenReaderOptimized(() => {
      this.P();
    }));
    this.M();
    this.N();
    this.j = t.foldingState;
    this.Z();
    this.O();
    if (this.t.layoutInfo.totalHeight > 0) {
      this.relayoutCell();
    }
    this.P();
    this.layoutCellParts();
    this.B(this.t.onDidChangeLayout(() => {
      this.layoutCellParts();
    }));
  }
  layoutCellParts() {
    this.u.cellParts.updateInternalLayoutNow(this.t);
  }
  H() {
    const id2 = `aria-markup-cell-${this.t.id}`;
    this.b = this.u.cellContainer;
    this.b.id = id2;
    this.b.style.height = "1px";
    this.b.style.overflow = "hidden";
    this.b.style.position = "absolute";
    this.b.style.top = "100000px";
    this.b.style.left = "10000px";
    this.b.ariaHidden = "false";
    this.u.rootContainer.setAttribute("aria-describedby", id2);
    this.u.container.classList.toggle("webview-backed-markdown-cell", true);
  }
  I() {
    this.B(this.t.onDidChangeState((e) => {
      this.u.cellParts.updateState(this.t, e);
    }));
    this.B(this.t.model.onDidChangeMetadata(() => {
      this.P();
    }));
    this.B(this.t.onDidChangeState((e) => {
      if (e.editStateChanged || e.contentChanged) {
        this.P();
      }
      if (e.focusModeChanged) {
        this.N();
      }
      if (e.foldingStateChanged) {
        const foldingState = this.t.foldingState;
        if (foldingState !== this.j) {
          this.j = foldingState;
          this.Z();
        }
      }
      if (e.cellIsHoveredChanged) {
        this.M();
      }
      if (e.inputCollapsedChanged) {
        this.L();
        this.P();
      }
      if (e.cellLineNumberChanged) {
        this.m.setLineNumbers(this.t.lineNumbers);
      }
    }));
    this.B(this.s.notebookOptions.onDidChangeOptions((e) => {
      if (e.showFoldingControls) {
        this.O();
      }
    }));
    this.B(this.t.onDidChangeLayout((e) => {
      const layoutInfo = this.a?.getLayoutInfo();
      if (e.outerWidth && this.t.getEditState() === CellEditState.Editing && layoutInfo && layoutInfo.width !== this.t.layoutInfo.editorWidth) {
        this.Y();
      }
    }));
    this.B(this.m.onDidChange(() => this.J()));
  }
  J() {
    this.updateEditorOptions(this.m.getUpdatedValue(this.t.internalMetadata, this.t.uri));
    if (this.a) {
      this.a.updateOptions(this.m.getUpdatedValue(this.t.internalMetadata, this.t.uri));
      const cts = new $ad();
      this.B({ dispose() {
        cts.dispose(true);
      } });
      $Ih(this.t.resolveTextModel(), cts.token).then((model) => {
        if (this.r) {
          return;
        }
        if (model) {
          model.updateOptions({
            indentSize: this.m.indentSize,
            tabSize: this.m.tabSize,
            insertSpaces: this.m.insertSpaces
          });
        }
      });
    }
  }
  L() {
    if (this.t.isInputCollapsed) {
      this.s.hideMarkupPreviews([this.t]);
    } else {
      this.s.unhideMarkupPreviews([this.t]);
    }
  }
  M() {
    this.u.container.classList.toggle("markdown-cell-hover", this.t.cellIsHovered);
  }
  N() {
    if (this.t.focusMode === CellFocusMode.Editor) {
      this.W();
    }
    this.u.container.classList.toggle("cell-editor-focus", this.t.focusMode === CellFocusMode.Editor);
  }
  dispose() {
    this.r = true;
    if (this.s.getActiveCell() === this.t && this.t.focusMode === CellFocusMode.Editor && (this.s.hasEditorFocus() || this.s.getDomNode().ownerDocument.activeElement === this.s.getDomNode().ownerDocument.body)) {
      this.s.focusContainer();
    }
    this.t.detachTextEditor();
    super.dispose();
  }
  O() {
    const showFoldingIcon = this.s.notebookOptions.getDisplayOptions().showFoldingControls;
    this.u.foldingIndicator.classList.remove("mouseover", "always");
    this.u.foldingIndicator.classList.add(showFoldingIcon);
  }
  P() {
    if (this.t.isInputCollapsed) {
      this.Q();
    } else if (this.t.getEditState() === CellEditState.Editing) {
      this.S();
    } else {
      this.U();
    }
  }
  Q() {
    $hk(this.u.cellInputCollapsedContainer);
    $ik(this.c);
    this.u.cellInputCollapsedContainer.innerText = "";
    const markdownIcon = $bk(this.u.cellInputCollapsedContainer, $("span"));
    markdownIcon.classList.add(...ThemeIcon.asClassNameArray($6l.markdown));
    const element = $("div");
    element.classList.add("cell-collapse-preview");
    const richEditorText = this.R(this.t.textBuffer, this.t.language);
    $wk(element, richEditorText);
    this.u.cellInputCollapsedContainer.appendChild(element);
    const expandIcon2 = $bk(element, $("span.expandInputIcon"));
    expandIcon2.classList.add(...ThemeIcon.asClassNameArray($6l.more));
    const keybinding = this.G.lookupKeybinding($Grb);
    if (keybinding) {
      element.title = localize(8601, null, keybinding.getLabel());
      expandIcon2.title = localize(8602, null, keybinding.getLabel());
    }
    this.b.ariaHidden = "true";
    this.u.container.classList.toggle("input-collapsed", true);
    this.t.renderedMarkdownHeight = 0;
    this.t.layoutChange({});
  }
  R(buffer, language) {
    return $n9(this.D, buffer.getLineContent(1), language);
  }
  S() {
    let editorHeight;
    $hk(this.c);
    this.b.ariaHidden = "true";
    $ik(this.u.cellInputCollapsedContainer);
    this.s.hideMarkupPreviews([this.t]);
    this.u.container.classList.toggle("input-collapsed", false);
    this.u.container.classList.toggle("markdown-cell-edit-mode", true);
    if (this.a && this.a.hasModel()) {
      editorHeight = this.a.getContentHeight();
      this.t.attachTextEditor(this.a);
      this.W();
      this.ab(this.a);
      this.a.layout({
        width: this.t.layoutInfo.editorWidth,
        height: editorHeight
      });
    } else {
      this.h.clear();
      const width2 = this.s.notebookOptions.computeMarkdownCellEditorWidth(this.s.getLayoutInfo().width);
      const lineNum = this.t.lineCount;
      const lineHeight = this.t.layoutInfo.fontInfo?.lineHeight || 17;
      const editorPadding = this.s.notebookOptions.computeEditorPadding(this.t.internalMetadata, this.t.uri);
      editorHeight = Math.max(lineNum, 1) * lineHeight + editorPadding.top + editorPadding.bottom;
      this.u.editorContainer.innerText = "";
      const editorContextKeyService = this.z.createScoped(this.u.editorPart);
      EditorContextKeys.inCompositeEditor.bindTo(editorContextKeyService).set(true);
      const editorInstaService = this.h.add(this.C.createChild(new $Ok([$on, editorContextKeyService])));
      this.h.add(editorContextKeyService);
      this.a = this.h.add(editorInstaService.createInstance($D9, this.u.editorContainer, {
        ...this.n,
        dimension: {
          width: width2,
          height: editorHeight
        }
        // overflowWidgetsDomNode: this.notebookEditor.getOverflowContainerDomNode()
      }, {
        contributions: this.s.creationOptions.cellEditorContributions
      }));
      this.u.currentEditor = this.a;
      this.h.add(this.a.onDidBlurEditorWidget(() => {
        if (this.a) {
          $Vkb.get(this.a)?.stopHighlighting();
        }
      }));
      this.h.add(this.a.onDidFocusEditorWidget(() => {
        if (this.a) {
          $Vkb.get(this.a)?.restoreViewState(true);
        }
      }));
      const cts = new $ad();
      this.h.add({ dispose() {
        cts.dispose(true);
      } });
      $Ih(this.t.resolveTextModel(), cts.token).then((model) => {
        if (!model) {
          return;
        }
        this.a.setModel(model);
        model.updateOptions({
          indentSize: this.m.indentSize,
          tabSize: this.m.tabSize,
          insertSpaces: this.m.insertSpaces
        });
        const realContentHeight = this.a.getContentHeight();
        if (realContentHeight !== editorHeight) {
          this.a.layout({
            width: width2,
            height: realContentHeight
          });
          editorHeight = realContentHeight;
        }
        this.t.attachTextEditor(this.a);
        if (this.t.getEditState() === CellEditState.Editing) {
          this.W();
        }
        this.ab(this.a);
        this.t.editorHeight = editorHeight;
      });
    }
    this.t.editorHeight = editorHeight;
    this.W();
    this.w.set(this.t, this.a);
  }
  U() {
    this.t.detachTextEditor();
    $ik(this.c);
    $ik(this.u.cellInputCollapsedContainer);
    this.b.ariaHidden = "false";
    this.u.container.classList.toggle("input-collapsed", false);
    this.u.container.classList.toggle("markdown-cell-edit-mode", false);
    this.w.delete(this.t);
    this.b.innerText = "";
    if (this.t.renderedHtml) {
      if (this.y.isScreenReaderOptimized()) {
        $wk(this.b, this.t.renderedHtml);
      } else {
        $$i(this.b);
      }
    }
    this.s.createMarkupPreview(this.t);
  }
  W() {
    if (this.t.focusMode === CellFocusMode.Editor && (this.s.hasEditorFocus() || this.s.getDomNode().ownerDocument.activeElement === this.s.getDomNode().ownerDocument.body)) {
      if (!this.a) {
        return;
      }
      this.a.focus();
      const primarySelection = this.a.getSelection();
      if (!primarySelection) {
        return;
      }
      this.s.revealRangeInViewAsync(this.t, primarySelection);
    }
  }
  X(dimension) {
    this.a?.layout(dimension);
  }
  Y() {
    const realContentHeight = this.a.getContentHeight();
    this.X({
      width: this.t.layoutInfo.editorWidth,
      height: realContentHeight
    });
  }
  relayoutCell() {
    this.s.layoutNotebookCell(this.t, this.t.layoutInfo.totalHeight);
    this.Z();
  }
  updateEditorOptions(newValue) {
    this.n = newValue;
    this.a?.updateOptions(this.n);
  }
  Z() {
    switch (this.j) {
      case 0:
        this.u.foldingIndicator.style.display = "none";
        this.u.foldingIndicator.innerText = "";
        break;
      case 2:
        this.u.foldingIndicator.style.display = "";
        $dk(this.u.foldingIndicator, $C1($SKb));
        break;
      case 1:
        this.u.foldingIndicator.style.display = "";
        $dk(this.u.foldingIndicator, $C1($TKb));
        break;
      default:
        break;
    }
  }
  ab(editor) {
    this.f.clear();
    this.g.clear();
    this.f.add(editor.onDidContentSizeChange((e) => {
      if (e.contentHeightChanged) {
        this.bb(editor, e.contentHeight);
      }
    }));
    this.f.add(editor.onDidChangeCursorSelection((e) => {
      if (e.source === "restoreState") {
        return;
      }
      const selections = editor.getSelections();
      if (selections?.length) {
        const contentHeight = editor.getContentHeight();
        const layoutContentHeight = this.t.layoutInfo.editorHeight;
        if (contentHeight !== layoutContentHeight) {
          this.bb(editor, contentHeight);
        }
        const lastSelection = selections[selections.length - 1];
        this.s.revealRangeInViewAsync(this.t, lastSelection);
      }
    }));
    const updateFocusMode = () => this.t.focusMode = editor.hasWidgetFocus() ? CellFocusMode.Editor : CellFocusMode.Container;
    this.f.add(editor.onDidFocusEditorWidget(() => {
      updateFocusMode();
    }));
    this.f.add(editor.onDidBlurEditorWidget(() => {
      if (this.u.container.ownerDocument.activeElement?.contains(this.u.container)) {
        this.g.value = $Xh(() => updateFocusMode(), 300);
      } else {
        updateFocusMode();
      }
    }));
    updateFocusMode();
  }
  bb(editor, newHeight) {
    const viewLayout = editor.getLayoutInfo();
    this.t.editorHeight = newHeight;
    editor.layout({
      width: viewLayout.width,
      height: newHeight
    });
  }
};
$kLb = __decorate([
  __param(4, $ND),
  __param(5, $on),
  __param(6, $Pk),
  __param(7, $1E),
  __param(8, $kl),
  __param(9, $Ty)
], $kLb);

// out-build/vs/workbench/contrib/notebook/browser/view/renderers/cellRenderer.js
var $mLb_1;
var $nLb_1;
var $124 = $;
var $lLb = class $lLb2 extends $3c {
  constructor(targetWindow, b) {
    super();
    this.b = b;
    const editorOptions2 = this.b.getValue("editor");
    this.a = $ED.createFromRawSettings(editorOptions2, $_1.getInstance(targetWindow).value).lineHeight;
  }
  getHeight(element) {
    return element.getHeight(this.a);
  }
  getDynamicHeight(element) {
    return element.getDynamicHeight();
  }
  getTemplateId(element) {
    if (element.cellKind === CellKind.Markup) {
      return $mLb.TEMPLATE_ID;
    } else {
      return $nLb.TEMPLATE_ID;
    }
  }
};
$lLb = __decorate([
  __param(1, $kl)
], $lLb);
var AbstractCellRenderer = class {
  constructor(b, c, d, e, configurationService, f, g, h3, language, i2) {
    this.b = b;
    this.c = c;
    this.d = d;
    this.e = e;
    this.f = f;
    this.g = g;
    this.h = h3;
    this.i = i2;
    this.a = new $oKb(this.c.getBaseCellEditorOptions(language), this.c.notebookOptions, configurationService);
  }
  dispose() {
    this.a.dispose();
    this.i = void 0;
  }
};
var $mLb = class $mLb2 extends AbstractCellRenderer {
  static {
    $mLb_1 = this;
  }
  static {
    this.TEMPLATE_ID = "markdown_cell";
  }
  constructor(notebookEditor, dndController, k, contextKeyServiceProvider, configurationService, instantiationService, contextMenuService, menuService, keybindingService, notificationService, notebookExecutionStateService) {
    super(instantiationService, notebookEditor, contextMenuService, menuService, configurationService, keybindingService, notificationService, contextKeyServiceProvider, "markdown", dndController);
    this.k = k;
    this.j = notebookExecutionStateService;
  }
  get templateId() {
    return $mLb_1.TEMPLATE_ID;
  }
  renderTemplate(rootContainer) {
    rootContainer.classList.add("markdown-cell-row");
    const container2 = $bk(rootContainer, $(".cell-inner-container"));
    const templateDisposables = new $2c();
    const contextKeyService = templateDisposables.add(this.h(container2));
    const decorationContainer = $bk(rootContainer, $124(".cell-decoration"));
    const titleToolbarContainer = $bk(container2, $124(".cell-title-toolbar"));
    const focusIndicatorTop = new $nZ($bk(container2, $124(".cell-focus-indicator.cell-focus-indicator-top")));
    const focusIndicatorLeft = new $nZ($bk(container2, $(".cell-focus-indicator.cell-focus-indicator-side.cell-focus-indicator-left")));
    const foldingIndicator = $bk(focusIndicatorLeft.domNode, $(".notebook-folding-indicator"));
    const focusIndicatorRight = new $nZ($bk(container2, $(".cell-focus-indicator.cell-focus-indicator-side.cell-focus-indicator-right")));
    const codeInnerContent = $bk(container2, $124(".cell.code"));
    const editorPart = $bk(codeInnerContent, $124(".cell-editor-part"));
    const cellChatPart = $bk(editorPart, $124(".cell-chat-part"));
    const cellInputCollapsedContainer = $bk(codeInnerContent, $124(".input-collapse-container"));
    cellInputCollapsedContainer.style.display = "none";
    const editorContainer = $bk(editorPart, $124(".cell-editor-container"));
    editorPart.style.display = "none";
    const cellCommentPartContainer = $bk(container2, $124(".cell-comment-container"));
    const innerContent = $bk(container2, $124(".cell.markdown"));
    const bottomCellContainer = $bk(container2, $124(".cell-bottom-toolbar-container"));
    const scopedInstaService = templateDisposables.add(this.b.createChild(new $Ok([$on, contextKeyService])));
    const rootClassDelegate = {
      toggle: (className, force) => container2.classList.toggle(className, force)
    };
    const titleToolbar = templateDisposables.add(scopedInstaService.createInstance($wKb, titleToolbarContainer, rootClassDelegate, this.c.creationOptions.menuIds.cellTitleToolbar, this.c.creationOptions.menuIds.cellDeleteToolbar, this.c));
    const focusIndicatorBottom = new $nZ($bk(container2, $124(".cell-focus-indicator.cell-focus-indicator-bottom")));
    const cellParts = new $nJb(getWindow(rootContainer), [
      templateDisposables.add(scopedInstaService.createInstance($KJb, this.c, cellChatPart)),
      templateDisposables.add(scopedInstaService.createInstance($zKb, this.c, container2, editorPart, void 0)),
      templateDisposables.add(new $xKb(this.c, titleToolbar, focusIndicatorTop, focusIndicatorLeft, focusIndicatorRight, focusIndicatorBottom)),
      templateDisposables.add(new $jLb(this.c, $bk(container2, $124(".notebook-folded-hint")), this.j)),
      templateDisposables.add(new $mKb(this.c, rootContainer, decorationContainer)),
      templateDisposables.add(scopedInstaService.createInstance($lKb, this.c, cellCommentPartContainer)),
      templateDisposables.add(new $dLb(this.c, cellInputCollapsedContainer)),
      templateDisposables.add(new $qKb(container2, void 0, this.c)),
      templateDisposables.add(new $qJb(container2)),
      templateDisposables.add(scopedInstaService.createInstance($oJb, this.c))
    ], [
      titleToolbar,
      templateDisposables.add(scopedInstaService.createInstance($vKb, this.c, titleToolbarContainer, bottomCellContainer))
    ]);
    templateDisposables.add(cellParts);
    const templateData = {
      rootContainer,
      cellInputCollapsedContainer,
      instantiationService: scopedInstaService,
      container: container2,
      cellContainer: innerContent,
      editorPart,
      editorContainer,
      foldingIndicator,
      templateDisposables,
      elementDisposables: new $2c(),
      cellParts,
      toJSON: () => {
        return {};
      }
    };
    return templateData;
  }
  renderElement(element, index, templateData, height) {
    if (!this.c.hasModel()) {
      throw new Error("The notebook editor is not attached with view model yet.");
    }
    templateData.currentRenderedCell = element;
    templateData.currentEditor = void 0;
    templateData.editorPart.style.display = "none";
    templateData.cellContainer.innerText = "";
    if (height === void 0) {
      return;
    }
    templateData.elementDisposables.add(templateData.instantiationService.createInstance($kLb, this.c, element, templateData, this.k));
  }
  disposeTemplate(templateData) {
    templateData.elementDisposables.dispose();
    templateData.templateDisposables.dispose();
  }
  disposeElement(_element, _index, templateData) {
    templateData.elementDisposables.clear();
  }
};
$mLb = $mLb_1 = __decorate([
  __param(4, $kl),
  __param(5, $Pk),
  __param(6, $50),
  __param(7, $cJ),
  __param(8, $Ty),
  __param(9, $PJ),
  __param(10, $wL)
], $mLb);
var $nLb = class $nLb2 extends AbstractCellRenderer {
  static {
    $nLb_1 = this;
  }
  static {
    this.TEMPLATE_ID = "code_cell";
  }
  constructor(notebookEditor, j, k, dndController, contextKeyServiceProvider, configurationService, contextMenuService, menuService, instantiationService, keybindingService, notificationService) {
    super(instantiationService, notebookEditor, contextMenuService, menuService, configurationService, keybindingService, notificationService, contextKeyServiceProvider, $KF, dndController);
    this.j = j;
    this.k = k;
  }
  get templateId() {
    return $nLb_1.TEMPLATE_ID;
  }
  renderTemplate(rootContainer) {
    rootContainer.classList.add("code-cell-row");
    const container2 = $bk(rootContainer, $(".cell-inner-container"));
    const templateDisposables = new $2c();
    const contextKeyService = templateDisposables.add(this.h(container2));
    const decorationContainer = $bk(rootContainer, $124(".cell-decoration"));
    const focusIndicatorTop = new $nZ($bk(container2, $124(".cell-focus-indicator.cell-focus-indicator-top")));
    const titleToolbarContainer = $bk(container2, $124(".cell-title-toolbar"));
    const focusIndicatorLeft = new $nZ($bk(container2, $(".cell-focus-indicator.cell-focus-indicator-side.cell-focus-indicator-left")));
    const cellChatPart = $bk(container2, $124(".cell-chat-part"));
    const cellContainer = $bk(container2, $124(".cell.code"));
    const runButtonContainer = $bk(cellContainer, $124(".run-button-container"));
    const cellInputCollapsedContainer = $bk(cellContainer, $124(".input-collapse-container"));
    cellInputCollapsedContainer.style.display = "none";
    const executionOrderLabel = $bk(focusIndicatorLeft.domNode, $124("div.execution-count-label"));
    executionOrderLabel.title = localize(8607, null);
    const editorPart = $bk(cellContainer, $124(".cell-editor-part"));
    const editorContainer = $bk(editorPart, $124(".cell-editor-container"));
    const cellCommentPartContainer = $bk(container2, $124(".cell-comment-container"));
    const editorContextKeyService = templateDisposables.add(this.h(editorPart));
    const editorInstaService = templateDisposables.add(this.b.createChild(new $Ok([$on, editorContextKeyService])));
    EditorContextKeys.inCompositeEditor.bindTo(editorContextKeyService).set(true);
    const editor = editorInstaService.createInstance($D9, editorContainer, {
      ...this.a.getDefaultValue(),
      dimension: {
        width: 0,
        height: 0
      },
      scrollbar: {
        vertical: "hidden",
        horizontal: "auto",
        handleMouseWheel: false,
        useShadows: false
      }
    }, {
      contributions: this.c.creationOptions.cellEditorContributions
    });
    templateDisposables.add(editor);
    const outputContainer = new $nZ($bk(container2, $124(".output")));
    const cellOutputCollapsedContainer = $bk(outputContainer.domNode, $124(".output-collapse-container"));
    const outputShowMoreContainer = new $nZ($bk(container2, $124(".output-show-more-container")));
    const focusIndicatorRight = new $nZ($bk(container2, $(".cell-focus-indicator.cell-focus-indicator-side.cell-focus-indicator-right")));
    const focusSinkElement = $bk(container2, $124(".cell-editor-focus-sink"));
    focusSinkElement.setAttribute("tabindex", "0");
    const bottomCellToolbarContainer = $bk(container2, $124(".cell-bottom-toolbar-container"));
    const focusIndicatorBottom = new $nZ($bk(container2, $124(".cell-focus-indicator.cell-focus-indicator-bottom")));
    const scopedInstaService = templateDisposables.add(this.b.createChild(new $Ok([$on, contextKeyService])));
    const rootClassDelegate = {
      toggle: (className, force) => container2.classList.toggle(className, force)
    };
    const titleToolbar = templateDisposables.add(scopedInstaService.createInstance($wKb, titleToolbarContainer, rootClassDelegate, this.c.creationOptions.menuIds.cellTitleToolbar, this.c.creationOptions.menuIds.cellDeleteToolbar, this.c));
    const focusIndicatorPart = templateDisposables.add(new $xKb(this.c, titleToolbar, focusIndicatorTop, focusIndicatorLeft, focusIndicatorRight, focusIndicatorBottom));
    const contentParts = [
      focusIndicatorPart,
      templateDisposables.add(scopedInstaService.createInstance($KJb, this.c, cellChatPart)),
      templateDisposables.add(scopedInstaService.createInstance($zKb, this.c, container2, editorPart, editor)),
      templateDisposables.add(scopedInstaService.createInstance($yKb, editorPart, cellInputCollapsedContainer)),
      templateDisposables.add(new $mKb(this.c, rootContainer, decorationContainer)),
      templateDisposables.add(scopedInstaService.createInstance($lKb, this.c, cellCommentPartContainer)),
      templateDisposables.add(scopedInstaService.createInstance($pKb, this.c, executionOrderLabel)),
      templateDisposables.add(scopedInstaService.createInstance($eLb, this.c, cellOutputCollapsedContainer)),
      templateDisposables.add(new $dLb(this.c, cellInputCollapsedContainer)),
      templateDisposables.add(new $qKb(container2, focusSinkElement, this.c)),
      templateDisposables.add(new $qJb(container2)),
      templateDisposables.add(scopedInstaService.createInstance($oJb, this.c))
    ];
    const { cellExecutePrimary, cellExecuteToolbar } = this.c.creationOptions.menuIds;
    if (cellExecutePrimary && cellExecuteToolbar) {
      contentParts.push(templateDisposables.add(scopedInstaService.createInstance($bLb, this.c, contextKeyService, container2, runButtonContainer, cellExecutePrimary, cellExecuteToolbar)));
    }
    const cellParts = new $nJb(getWindow(rootContainer), contentParts, [
      titleToolbar,
      templateDisposables.add(scopedInstaService.createInstance($vKb, this.c, titleToolbarContainer, bottomCellToolbarContainer))
    ]);
    templateDisposables.add(cellParts);
    const templateData = {
      rootContainer,
      editorPart,
      cellInputCollapsedContainer,
      cellOutputCollapsedContainer,
      instantiationService: scopedInstaService,
      container: container2,
      cellContainer,
      focusSinkElement,
      outputContainer,
      outputShowMoreContainer,
      editor,
      templateDisposables,
      elementDisposables: new $2c(),
      cellParts,
      toJSON: () => {
        return {};
      }
    };
    const dragHandles = [focusIndicatorLeft.domNode, focusIndicatorPart.codeFocusIndicator.domNode, focusIndicatorPart.outputFocusIndicator.domNode];
    this.i?.registerDragHandle(templateData, rootContainer, dragHandles, () => new $nKb().getDragImage(templateData, templateData.editor, "code"));
    return templateData;
  }
  renderElement(element, index, templateData, height) {
    if (!this.c.hasModel()) {
      throw new Error("The notebook editor is not attached with view model yet.");
    }
    templateData.currentRenderedCell = element;
    if (height === void 0) {
      return;
    }
    templateData.outputContainer.domNode.innerText = "";
    templateData.outputContainer.domNode.appendChild(templateData.cellOutputCollapsedContainer);
    templateData.elementDisposables.add(templateData.instantiationService.createInstance($aLb, this.c, element, templateData, this.k));
    this.j.set(element, templateData.editor);
  }
  disposeTemplate(templateData) {
    templateData.templateDisposables.clear();
  }
  disposeElement(element, index, templateData, height) {
    templateData.elementDisposables.clear();
    this.j.delete(element);
  }
};
$nLb = $nLb_1 = __decorate([
  __param(5, $kl),
  __param(6, $50),
  __param(7, $cJ),
  __param(8, $Pk),
  __param(9, $Ty),
  __param(10, $PJ)
], $nLb);

// out-build/vs/workbench/contrib/notebook/browser/viewModel/eventDispatcher.js
var $RIb = class extends $3c {
  constructor() {
    super(...arguments);
    this.a = this.B(new $ze());
    this.onDidChangeLayout = this.a.event;
    this.b = this.B(new $ze());
    this.onDidChangeMetadata = this.b.event;
    this.c = this.B(new $ze());
    this.onDidChangeCellState = this.c.event;
  }
  emit(events) {
    for (let i2 = 0, len = events.length; i2 < len; i2++) {
      const e = events[i2];
      switch (e.type) {
        case NotebookViewEventType.LayoutChanged:
          this.a.fire(e);
          break;
        case NotebookViewEventType.MetadataChanged:
          this.b.fire(e);
          break;
        case NotebookViewEventType.CellStateChanged:
          this.c.fire(e);
          break;
      }
    }
  }
};

// out-build/vs/workbench/contrib/notebook/browser/contrib/find/findMatchDecorationModel.js
var $NIb = class extends $3c {
  constructor(g, h3) {
    super();
    this.g = g;
    this.h = h3;
    this.a = [];
    this.b = [];
    this.c = [];
    this.f = null;
  }
  get currentMatchDecorations() {
    return this.f;
  }
  j() {
    this.clearCurrentFindMatchDecoration();
    this.setAllFindMatchesDecorations([]);
  }
  async highlightCurrentFindMatchDecorationInCell(cell, cellRange) {
    this.clearCurrentFindMatchDecoration();
    this.g.changeModelDecorations((accessor) => {
      const findMatchesOptions = $Zfb._CURRENT_FIND_MATCH_DECORATION;
      const decorations = [
        { range: cellRange, options: findMatchesOptions }
      ];
      const deltaDecoration = {
        ownerId: cell.handle,
        decorations
      };
      this.f = {
        kind: "input",
        decorations: accessor.deltaDecorations(this.f?.kind === "input" ? this.f.decorations : [], [deltaDecoration])
      };
    });
    this.b = this.g.deltaCellDecorations(this.b, [{
      handle: cell.handle,
      options: {
        overviewRuler: {
          color: $aq,
          modelRanges: [cellRange],
          includeOutput: false,
          position: NotebookOverviewRulerLane.Center
        }
      }
    }]);
    return null;
  }
  async highlightCurrentFindMatchDecorationInWebview(cell, index) {
    this.clearCurrentFindMatchDecoration();
    const offset = await this.g.findHighlightCurrent(index, this.h);
    this.f = { kind: "output", index };
    this.b = this.g.deltaCellDecorations(this.b, [{
      handle: cell.handle,
      options: {
        overviewRuler: {
          color: $aq,
          modelRanges: [],
          includeOutput: true,
          position: NotebookOverviewRulerLane.Center
        }
      }
    }]);
    return offset;
  }
  clearCurrentFindMatchDecoration() {
    if (this.f?.kind === "input") {
      this.g.changeModelDecorations((accessor) => {
        accessor.deltaDecorations(this.f?.kind === "input" ? this.f.decorations : [], []);
        this.f = null;
      });
    } else if (this.f?.kind === "output") {
      this.g.findUnHighlightCurrent(this.f.index, this.h);
    }
    this.b = this.g.deltaCellDecorations(this.b, []);
  }
  setAllFindMatchesDecorations(cellFindMatches) {
    this.g.changeModelDecorations((accessor) => {
      const findMatchesOptions = $Zfb._FIND_MATCH_DECORATION;
      const deltaDecorations = cellFindMatches.map((cellFindMatch) => {
        const newFindMatchesDecorations = new Array(cellFindMatch.contentMatches.length);
        for (let i2 = 0; i2 < cellFindMatch.contentMatches.length; i2++) {
          newFindMatchesDecorations[i2] = {
            range: cellFindMatch.contentMatches[i2].range,
            options: findMatchesOptions
          };
        }
        return { ownerId: cellFindMatch.cell.handle, decorations: newFindMatchesDecorations };
      });
      this.a = accessor.deltaDecorations(this.a, deltaDecorations);
    });
    this.c = this.g.deltaCellDecorations(this.c, cellFindMatches.map((cellFindMatch) => {
      return {
        ownerId: cellFindMatch.cell.handle,
        handle: cellFindMatch.cell.handle,
        options: {
          overviewRuler: {
            color: $_p,
            modelRanges: cellFindMatch.contentMatches.map((match) => match.range),
            includeOutput: cellFindMatch.webviewMatches.length > 0,
            position: NotebookOverviewRulerLane.Center
          }
        }
      };
    }));
  }
  stopWebviewFind() {
    this.g.findStop(this.h);
  }
  dispose() {
    this.j();
    super.dispose();
  }
};

// out-build/vs/workbench/contrib/notebook/browser/contrib/find/findModel.js
var $OIb = class {
  get length() {
    return this.a.length + this.b.length;
  }
  get contentMatches() {
    return this.a;
  }
  get webviewMatches() {
    return this.b;
  }
  constructor(cell, index, contentMatches, webviewMatches) {
    this.cell = cell;
    this.index = index;
    this.a = contentMatches;
    this.b = webviewMatches;
  }
  getMatch(index) {
    if (index >= this.length) {
      throw new Error("NotebookCellFindMatch: index out of range");
    }
    if (index < this.a.length) {
      return this.a[index];
    }
    return this.b[index - this.a.length];
  }
};
var $PIb = class $PIb2 extends $3c {
  get findMatches() {
    return this.a;
  }
  get currentMatch() {
    return this.f;
  }
  constructor(r2, s, t) {
    super();
    this.r = r2;
    this.s = s;
    this.t = t;
    this.a = [];
    this.b = null;
    this.f = -1;
    this.h = null;
    this.j = this.B(new $2c());
    this.g = new $Sh(20);
    this.h = null;
    this.B(s.onFindReplaceStateChange((e) => {
      this.u(e);
      if (e.searchString || e.isRegex || e.matchCase || e.searchScope || e.wholeWord || e.isRevealed && this.s.isRevealed || e.filters || e.isReplaceRevealed) {
        this.research();
      }
      if (e.isRevealed && !this.s.isRevealed) {
        this.clear();
      }
    }));
    this.B(this.r.onDidChangeModel((e) => {
      this.y(e);
    }));
    this.B(this.r.onDidChangeCellState((e) => {
      if (e.cell.cellKind === CellKind.Markup && e.source.editStateChanged) {
        this.research();
      }
    }));
    if (this.r.hasModel()) {
      this.y(this.r.textModel);
    }
    this.n = new $NIb(this.r, this.r.getId());
  }
  u(e) {
    if (!this.s.filters?.markupInput || !this.s.filters?.markupPreview || !this.s.filters?.findScope) {
      return;
    }
    const updateEditingState = () => {
      const viewModel = this.r.getViewModel();
      if (!viewModel) {
        return;
      }
      const wordSeparators2 = this.t.inspect("editor.wordSeparators").value;
      const options3 = {
        regex: this.s.isRegex,
        wholeWord: this.s.wholeWord,
        caseSensitive: this.s.matchCase,
        wordSeparators: wordSeparators2,
        includeMarkupInput: true,
        includeCodeInput: false,
        includeMarkupPreview: false,
        includeOutput: false,
        findScope: this.s.filters?.findScope
      };
      const contentMatches = viewModel.find(this.s.searchString, options3);
      for (let i2 = 0; i2 < viewModel.length; i2++) {
        const cell = viewModel.cellAt(i2);
        if (cell && cell.cellKind === CellKind.Markup) {
          const foundContentMatch = contentMatches.find((m) => m.cell.handle === cell.handle && m.contentMatches.length > 0);
          const targetState = foundContentMatch ? CellEditState.Editing : CellEditState.Preview;
          const currentEditingState = cell.getEditState();
          if (currentEditingState === CellEditState.Editing && cell.editStateSource !== "find") {
            continue;
          }
          if (currentEditingState !== targetState) {
            cell.updateEditState(targetState, "find");
          }
        }
      }
    };
    if (e.isReplaceRevealed && !this.s.isReplaceRevealed) {
      const viewModel = this.r.getViewModel();
      if (!viewModel) {
        return;
      }
      for (let i2 = 0; i2 < viewModel.length; i2++) {
        const cell = viewModel.cellAt(i2);
        if (cell && cell.cellKind === CellKind.Markup) {
          if (cell.getEditState() === CellEditState.Editing && cell.editStateSource === "find") {
            cell.updateEditState(CellEditState.Preview, "find");
          }
        }
      }
      return;
    }
    if (e.isReplaceRevealed) {
      updateEditingState();
    } else if ((e.filters || e.isRevealed || e.searchString || e.replaceString) && this.s.isRevealed && this.s.isReplaceRevealed) {
      updateEditingState();
    }
  }
  ensureFindMatches() {
    if (!this.b) {
      this.z(this.a, true);
    }
  }
  getCurrentMatch() {
    const nextIndex = this.b.getIndexOf(this.f);
    const cell = this.a[nextIndex.index].cell;
    const match = this.a[nextIndex.index].getMatch(nextIndex.remainder);
    return {
      cell,
      match,
      isModelMatch: nextIndex.remainder < this.a[nextIndex.index].contentMatches.length
    };
  }
  refreshCurrentMatch(focus) {
    const findMatchIndex = this.findMatches.findIndex((match) => match.cell === focus.cell);
    if (findMatchIndex === -1) {
      return;
    }
    const findMatch = this.findMatches[findMatchIndex];
    const index = findMatch.contentMatches.findIndex((match) => match.range.intersectRanges(focus.range) !== null);
    if (index === void 0) {
      return;
    }
    const matchesBefore = findMatchIndex === 0 ? 0 : this.b?.getPrefixSum(findMatchIndex - 1) ?? 0;
    this.f = matchesBefore + index;
    this.H(findMatchIndex, index).then((offset) => {
      this.w(findMatchIndex, index, offset);
      this.s.changeMatchInfo(this.f, this.a.reduce((p, c) => p + c.length, 0), void 0);
    });
  }
  find(option) {
    if (!this.findMatches.length) {
      return;
    }
    if (!this.b) {
      this.z(this.a, true);
      if ("index" in option) {
        this.f = option.index;
      }
    } else {
      const totalVal = this.b.getTotalSum();
      if ("index" in option) {
        this.f = option.index;
      } else if (this.f === -1) {
        this.f = option.previous ? totalVal - 1 : 0;
      } else {
        const nextVal = (this.f + (option.previous ? -1 : 1) + totalVal) % totalVal;
        this.f = nextVal;
      }
    }
    const nextIndex = this.b.getIndexOf(this.f);
    this.H(nextIndex.index, nextIndex.remainder).then((offset) => {
      this.w(nextIndex.index, nextIndex.remainder, offset);
      this.s.changeMatchInfo(this.f, this.a.reduce((p, c) => p + c.length, 0), void 0);
    });
  }
  w(cellIndex, matchIndex, outputOffset) {
    const findMatch = this.a[cellIndex];
    if (matchIndex >= findMatch.contentMatches.length) {
      this.r.focusElement(findMatch.cell);
      const index = this.r.getCellIndex(findMatch.cell);
      if (index !== void 0) {
        this.r.revealCellOffsetInCenter(findMatch.cell, outputOffset ?? 0);
      }
    } else {
      const match = findMatch.getMatch(matchIndex);
      if (findMatch.cell.getEditState() !== CellEditState.Editing) {
        findMatch.cell.updateEditState(CellEditState.Editing, "find");
      }
      findMatch.cell.isInputCollapsed = false;
      this.r.focusElement(findMatch.cell);
      this.r.setCellEditorSelection(findMatch.cell, match.range);
      this.r.revealRangeInCenterIfOutsideViewportAsync(findMatch.cell, match.range);
    }
  }
  y(notebookTextModel) {
    this.j.clear();
    if (notebookTextModel) {
      this.j.add(notebookTextModel.onDidChangeContent((e) => {
        if (!e.rawEvents.some((event) => event.kind === NotebookCellsChangeType.ChangeCellContent || event.kind === NotebookCellsChangeType.ModelChange)) {
          return;
        }
        this.research();
      }));
    }
    this.research();
  }
  async research() {
    return this.g.trigger(async () => {
      this.s.change({ isSearching: true }, false);
      await this._research();
      this.s.change({ isSearching: false }, false);
    });
  }
  async _research() {
    this.h?.cancel();
    if (!this.s.isRevealed || !this.r.hasModel()) {
      this.z([], false);
      return;
    }
    this.h = $Hh((token) => this.C(token));
    const findMatches = await this.h;
    if (!findMatches) {
      this.z([], false);
      return;
    }
    if (findMatches.length === 0) {
      this.z([], false);
      return;
    }
    const findFirstMatchAfterCellIndex = (cellIndex) => {
      const matchAfterSelection = $6(findMatches.map((match) => match.index), (index) => index >= cellIndex);
      this.D(findMatches, this.F(findMatches, matchAfterSelection));
    };
    if (this.f === -1) {
      if (this.r.getLength() === 0) {
        this.z(findMatches, false);
        return;
      } else {
        const focus = this.r.getFocus().start;
        findFirstMatchAfterCellIndex(focus);
        this.z(findMatches, false);
        return;
      }
    }
    const oldCurrIndex = this.b.getIndexOf(this.f);
    const oldCurrCell = this.a[oldCurrIndex.index].cell;
    const oldCurrMatchCellIndex = this.r.getCellIndex(oldCurrCell);
    if (oldCurrMatchCellIndex < 0) {
      if (this.r.getLength() === 0) {
        this.z(findMatches, false);
        return;
      }
      findFirstMatchAfterCellIndex(oldCurrMatchCellIndex);
      return;
    }
    const cell = this.r.cellAt(oldCurrMatchCellIndex);
    if (cell.cellKind === CellKind.Markup && cell.getEditState() === CellEditState.Preview) {
      findFirstMatchAfterCellIndex(oldCurrMatchCellIndex);
      return;
    }
    if (!this.n.currentMatchDecorations) {
      findFirstMatchAfterCellIndex(oldCurrMatchCellIndex);
      return;
    }
    if (this.n.currentMatchDecorations.kind === "input") {
      const currentMatchDecorationId = this.n.currentMatchDecorations.decorations.find((decoration3) => decoration3.ownerId === cell.handle);
      if (!currentMatchDecorationId) {
        findFirstMatchAfterCellIndex(oldCurrMatchCellIndex);
        return;
      }
      const matchAfterSelection = $6(findMatches, (match) => match.index >= oldCurrMatchCellIndex) % findMatches.length;
      if (findMatches[matchAfterSelection].index > oldCurrMatchCellIndex) {
        this.D(findMatches, this.F(findMatches, matchAfterSelection));
        return;
      } else {
        let currMatchRangeInEditor = cell.editorAttached && currentMatchDecorationId.decorations[0] ? cell.getCellDecorationRange(currentMatchDecorationId.decorations[0]) : null;
        if (currMatchRangeInEditor === null && oldCurrIndex.remainder < this.a[oldCurrIndex.index].contentMatches.length) {
          currMatchRangeInEditor = this.a[oldCurrIndex.index].getMatch(oldCurrIndex.remainder).range;
        }
        if (currMatchRangeInEditor !== null) {
          const cellMatch = findMatches[matchAfterSelection];
          const matchAfterOldSelection = $6(cellMatch.contentMatches, (match) => $9C.compareRangesUsingStarts(match.range, currMatchRangeInEditor) >= 0);
          this.D(findMatches, this.F(findMatches, matchAfterSelection) + matchAfterOldSelection);
        } else {
          this.D(findMatches, this.F(findMatches, matchAfterSelection));
          return;
        }
      }
    } else {
      const matchAfterSelection = $6(findMatches.map((match) => match.index), (index) => index >= oldCurrMatchCellIndex) % findMatches.length;
      this.D(findMatches, this.F(findMatches, matchAfterSelection));
    }
  }
  z(cellFindMatches, autoStart) {
    if (!cellFindMatches || !cellFindMatches.length) {
      this.a = [];
      this.n.setAllFindMatchesDecorations([]);
      this.G();
      this.f = -1;
      this.n.clearCurrentFindMatchDecoration();
      this.s.changeMatchInfo(this.f, this.a.reduce((p, c) => p + c.length, 0), void 0);
      return;
    }
    this.a = cellFindMatches;
    this.n.setAllFindMatchesDecorations(cellFindMatches || []);
    this.G();
    if (autoStart) {
      this.f = 0;
      this.H(0, 0);
    }
    this.s.changeMatchInfo(this.f, this.a.reduce((p, c) => p + c.length, 0), void 0);
  }
  async C(token) {
    if (!this.r.hasModel()) {
      return null;
    }
    let ret = null;
    const val = this.s.searchString;
    const wordSeparators2 = this.t.inspect("editor.wordSeparators").value;
    const options3 = {
      regex: this.s.isRegex,
      wholeWord: this.s.wholeWord,
      caseSensitive: this.s.matchCase,
      wordSeparators: wordSeparators2,
      includeMarkupInput: this.s.filters?.markupInput ?? true,
      includeCodeInput: this.s.filters?.codeInput ?? true,
      includeMarkupPreview: !!this.s.filters?.markupPreview,
      includeOutput: !!this.s.filters?.codeOutput,
      findScope: this.s.filters?.findScope
    };
    ret = await this.r.find(val, options3, token);
    if (token.isCancellationRequested) {
      return null;
    }
    return ret;
  }
  D(findMatches, currentMatchesPosition) {
    this.f = currentMatchesPosition % findMatches.length;
    this.z(findMatches, false);
    const nextIndex = this.b.getIndexOf(this.f);
    this.H(nextIndex.index, nextIndex.remainder);
    this.s.changeMatchInfo(this.f, this.a.reduce((p, c) => p + c.length, 0), void 0);
  }
  F(findMatches, index) {
    let prevMatchesCount = 0;
    for (let i2 = 0; i2 < index; i2++) {
      prevMatchesCount += findMatches[i2].length;
    }
    return prevMatchesCount;
  }
  G() {
    if (this.a && this.a.length) {
      const values = new Uint32Array(this.a.length);
      for (let i2 = 0; i2 < this.a.length; i2++) {
        values[i2] = this.a[i2].length;
      }
      this.b = new $wM(values);
    } else {
      this.b = null;
    }
  }
  async H(cellIndex, matchIndex) {
    const cell = this.a[cellIndex].cell;
    const match = this.a[cellIndex].getMatch(matchIndex);
    if (matchIndex < this.a[cellIndex].contentMatches.length) {
      return this.n.highlightCurrentFindMatchDecorationInCell(cell, match.range);
    } else {
      return this.n.highlightCurrentFindMatchDecorationInWebview(cell, match.index);
    }
  }
  clear() {
    this.h?.cancel();
    this.g.cancel();
    this.z([], false);
  }
  dispose() {
    this.n.dispose();
    super.dispose();
  }
};
$PIb = __decorate([
  __param(2, $kl)
], $PIb);

// out-build/vs/workbench/contrib/notebook/browser/viewModel/cellSelectionCollection.js
function rangesEqual(a, b) {
  if (a.length !== b.length) {
    return false;
  }
  for (let i2 = 0; i2 < a.length; i2++) {
    if (a[i2].start !== b[i2].start || a[i2].end !== b[i2].end) {
      return false;
    }
  }
  return true;
}
var $QIb = class extends $3c {
  constructor() {
    super(...arguments);
    this.c = this.B(new $ze());
    this.f = null;
    this.g = [];
  }
  get onDidChangeSelection() {
    return this.c.event;
  }
  get selections() {
    return this.g;
  }
  get focus() {
    return this.f ?? { start: 0, end: 0 };
  }
  setState(primary, selections, forceEventEmit, source) {
    const changed = primary !== this.f || !rangesEqual(this.g, selections);
    this.f = primary;
    this.g = selections;
    if (changed || forceEventEmit) {
      this.c.fire(source);
    }
  }
  setSelections(selections, forceEventEmit, source) {
    this.setState(this.f, selections, forceEventEmit, source);
  }
};

// out-build/vs/workbench/contrib/notebook/browser/viewModel/notebookViewModelImpl.js
var invalidFunc4 = () => {
  throw new Error(`Invalid change accessor`);
};
var DecorationsTree = class {
  constructor() {
    this.a = new $4H();
  }
  intervalSearch(start, end, filterOwnerId, filterOutValidation, cachedVersionId, onlyMarginDecorations = false) {
    const r1 = this.a.intervalSearch(start, end, filterOwnerId, filterOutValidation, cachedVersionId, onlyMarginDecorations);
    return r1;
  }
  search(filterOwnerId, filterOutValidation, overviewRulerOnly, cachedVersionId, onlyMarginDecorations) {
    return this.a.search(filterOwnerId, filterOutValidation, cachedVersionId, onlyMarginDecorations);
  }
  collectNodesFromOwner(ownerId2) {
    const r1 = this.a.collectNodesFromOwner(ownerId2);
    return r1;
  }
  collectNodesPostOrder() {
    const r1 = this.a.collectNodesPostOrder();
    return r1;
  }
  insert(node) {
    this.a.insert(node);
  }
  delete(node) {
    this.a.delete(node);
  }
  resolveNode(node, cachedVersionId) {
    this.a.resolveNode(node, cachedVersionId);
  }
  acceptReplace(offset, length, textLength, forceMoveMarkers) {
    this.a.acceptReplace(offset, length, textLength, forceMoveMarkers);
  }
};
var TRACKED_RANGE_OPTIONS2 = [
  $WI.register({
    description: "notebook-view-model-tracked-range-always-grows-when-typing-at-edges",
    stickiness: 0
    /* TrackedRangeStickiness.AlwaysGrowsWhenTypingAtEdges */
  }),
  $WI.register({
    description: "notebook-view-model-tracked-range-never-grows-when-typing-at-edges",
    stickiness: 1
    /* TrackedRangeStickiness.NeverGrowsWhenTypingAtEdges */
  }),
  $WI.register({
    description: "notebook-view-model-tracked-range-grows-only-when-typing-before",
    stickiness: 2
    /* TrackedRangeStickiness.GrowsOnlyWhenTypingBefore */
  }),
  $WI.register({
    description: "notebook-view-model-tracked-range-grows-only-when-typing-after",
    stickiness: 3
    /* TrackedRangeStickiness.GrowsOnlyWhenTypingAfter */
  })
];
function _normalizeOptions2(options3) {
  if (options3 instanceof $WI) {
    return options3;
  }
  return $WI.createDynamic(options3);
}
var MODEL_ID3 = 0;
var $ZIb = class $ZIb2 extends $3c {
  get options() {
    return this.L;
  }
  get onDidChangeOptions() {
    return this.c.event;
  }
  get viewCells() {
    return this.f;
  }
  get length() {
    return this.f.length;
  }
  get notebookDocument() {
    return this.H;
  }
  get uri() {
    return this.H.uri;
  }
  get metadata() {
    return this.H.metadata;
  }
  get g() {
    return this.viewType === "repl";
  }
  get onDidChangeViewCells() {
    return this.h.event;
  }
  get lastNotebookEditResource() {
    if (this.j.length) {
      return this.j[this.j.length - 1];
    }
    return null;
  }
  get layoutInfo() {
    return this.J;
  }
  get onDidChangeSelection() {
    return this.m.event;
  }
  get r() {
    const handlesSet = /* @__PURE__ */ new Set();
    const handles = [];
    $GL(this.n.selections).map((index) => index < this.length ? this.cellAt(index) : void 0).forEach((cell) => {
      if (cell && !handlesSet.has(cell.handle)) {
        handles.push(cell.handle);
      }
    });
    return handles;
  }
  set r(selectionHandles) {
    const indexes = selectionHandles.map((handle2) => this.f.findIndex((cell) => cell.handle === handle2));
    this.n.setSelections($FL(indexes), true, "model");
  }
  get focused() {
    return this.D;
  }
  constructor(viewType, H, I, J, L, M, N, O, P, Q) {
    super();
    this.viewType = viewType;
    this.H = H;
    this.I = I;
    this.J = J;
    this.L = L;
    this.M = M;
    this.N = N;
    this.O = O;
    this.P = P;
    this.Q = Q;
    this.a = this.B(new $2c());
    this.b = /* @__PURE__ */ new Map();
    this.c = this.B(new $ze());
    this.f = [];
    this.h = this.B(new $ze());
    this.j = [];
    this.m = this.B(new $ze());
    this.n = this.B(new $QIb());
    this.s = new DecorationsTree();
    this.t = /* @__PURE__ */ Object.create(null);
    this.u = 0;
    this.y = null;
    this.z = new $ze();
    this.onDidFoldingStateChanged = this.z.event;
    this.C = [];
    this.D = true;
    this.F = /* @__PURE__ */ new Map();
    this.G = /* @__PURE__ */ new Map();
    MODEL_ID3++;
    this.id = "$notebookViewModel" + MODEL_ID3;
    this.w = $tg(MODEL_ID3);
    const compute = (changes, synchronous) => {
      const diffs = changes.map((splice2) => {
        return [splice2[0], splice2[1], splice2[2].map((cell) => {
          return $1Ib(this.M, this, cell, this.I);
        })];
      });
      diffs.reverse().forEach((diff3) => {
        const deletedCells = this.f.splice(diff3[0], diff3[1], ...diff3[2]);
        this.s.acceptReplace(diff3[0], diff3[1], diff3[2].length, true);
        deletedCells.forEach((cell) => {
          this.b.delete(cell.handle);
          cell.dispose();
        });
        diff3[2].forEach((cell) => {
          this.b.set(cell.handle, cell);
          this.a.add(cell);
        });
      });
      const selectionHandles = this.r;
      this.h.fire({
        synchronous,
        splices: diffs
      });
      let endSelectionHandles = [];
      if (selectionHandles.length) {
        const primaryHandle = selectionHandles[0];
        const primarySelectionIndex = this.f.indexOf(this.getCellByHandle(primaryHandle));
        endSelectionHandles = [primaryHandle];
        let delta = 0;
        for (let i2 = 0; i2 < diffs.length; i2++) {
          const diff3 = diffs[0];
          if (diff3[0] + diff3[1] <= primarySelectionIndex) {
            delta += diff3[2].length - diff3[1];
            continue;
          }
          if (diff3[0] > primarySelectionIndex) {
            endSelectionHandles = [primaryHandle];
            break;
          }
          if (diff3[0] + diff3[1] > primarySelectionIndex) {
            endSelectionHandles = [this.f[diff3[0] + delta].handle];
            break;
          }
        }
      }
      const selectionIndexes = endSelectionHandles.map((handle2) => this.f.findIndex((cell) => cell.handle === handle2));
      this.n.setState($FL([selectionIndexes[0]])[0], $FL(selectionIndexes), true, "model");
    };
    this.B(this.H.onDidChangeContent((e) => {
      for (let i2 = 0; i2 < e.rawEvents.length; i2++) {
        const change = e.rawEvents[i2];
        let changes = [];
        const synchronous = e.synchronous ?? true;
        if (change.kind === NotebookCellsChangeType.ModelChange || change.kind === NotebookCellsChangeType.Initialize) {
          changes = change.changes;
          compute(changes, synchronous);
          continue;
        } else if (change.kind === NotebookCellsChangeType.Move) {
          compute([[change.index, change.length, []]], synchronous);
          compute([[change.newIdx, 0, change.cells]], synchronous);
        } else {
          continue;
        }
      }
    }));
    this.B(this.H.onDidChangeContent((contentChanges) => {
      contentChanges.rawEvents.forEach((e) => {
        if (e.kind === NotebookCellsChangeType.ChangeDocumentMetadata) {
          this.I.eventDispatcher.emit([new $jrb(this.H.metadata)]);
        }
      });
      if (contentChanges.endSelectionState) {
        this.updateSelectionsState(contentChanges.endSelectionState);
      }
    }));
    this.B(this.I.eventDispatcher.onDidChangeLayout((e) => {
      this.J = e.value;
      this.f.forEach((cell) => {
        if (cell.cellKind === CellKind.Markup) {
          if (e.source.width || e.source.fontInfo) {
            cell.layoutChange({ outerWidth: e.value.width, font: e.value.fontInfo });
          }
        } else {
          if (e.source.width !== void 0) {
            cell.layoutChange({ outerWidth: e.value.width, font: e.value.fontInfo });
          }
        }
      });
    }));
    this.B(this.I.notebookOptions.onDidChangeOptions((e) => {
      for (let i2 = 0; i2 < this.length; i2++) {
        const cell = this.f[i2];
        cell.updateOptions(e);
      }
    }));
    this.B(Q.onDidChangeExecution((e) => {
      if (e.type !== NotebookExecutionType.cell) {
        return;
      }
      const cell = this.getCellByHandle(e.cellHandle);
      if (cell instanceof $XIb) {
        cell.updateExecutionState(e);
      }
    }));
    this.B(this.n.onDidChangeSelection((e) => {
      this.m.fire(e);
    }));
    const viewCellCount = this.g ? this.H.cells.length - 1 : this.H.cells.length;
    for (let i2 = 0; i2 < viewCellCount; i2++) {
      this.f.push($1Ib(this.M, this, this.H.cells[i2], this.I));
    }
    this.f.forEach((cell) => {
      this.b.set(cell.handle, cell);
    });
  }
  updateOptions(newOptions) {
    this.L = { ...this.L, ...newOptions };
    this.f.forEach((cell) => cell.updateOptions({ readonly: this.L.isReadOnly }));
    this.c.fire();
  }
  getFocus() {
    return this.n.focus;
  }
  getSelections() {
    return this.n.selections;
  }
  getMostRecentlyExecutedCell() {
    const handle2 = this.Q.getLastCompletedCellForNotebook(this.H.uri);
    return handle2 !== void 0 ? this.getCellByHandle(handle2) : void 0;
  }
  setEditorFocus(focused) {
    this.D = focused;
  }
  validateRange(cellRange) {
    if (!cellRange) {
      return null;
    }
    const start = $4i(cellRange.start, 0, this.length);
    const end = $4i(cellRange.end, 0, this.length);
    if (start <= end) {
      return { start, end };
    } else {
      return { start: end, end: start };
    }
  }
  // selection change from list view's `setFocus` and `setSelection` should always use `source: view` to prevent events breaking the list view focus/selection change transaction
  updateSelectionsState(state, source = "model") {
    if (this.D || source === "model") {
      if (state.kind === SelectionStateType.Handle) {
        const primaryIndex = state.primary !== null ? this.getCellIndexByHandle(state.primary) : null;
        const primarySelection = primaryIndex !== null ? this.validateRange({ start: primaryIndex, end: primaryIndex + 1 }) : null;
        const selections = $FL(state.selections.map((sel) => this.getCellIndexByHandle(sel))).map((range) => this.validateRange(range)).filter((range) => range !== null);
        this.n.setState(primarySelection, $HL(selections), true, source);
      } else {
        const primarySelection = this.validateRange(state.focus);
        const selections = state.selections.map((range) => this.validateRange(range)).filter((range) => range !== null);
        this.n.setState(primarySelection, $HL(selections), true, source);
      }
    }
  }
  getFoldingStartIndex(index) {
    if (!this.y) {
      return -1;
    }
    const range = this.y.findRange(index + 1);
    const startIndex = this.y.getStartLineNumber(range) - 1;
    return startIndex;
  }
  getFoldingState(index) {
    if (!this.y) {
      return 0;
    }
    const range = this.y.findRange(index + 1);
    const startIndex = this.y.getStartLineNumber(range) - 1;
    if (startIndex !== index) {
      return 0;
    }
    return this.y.isCollapsed(range) ? 2 : 1;
  }
  getFoldedLength(index) {
    if (!this.y) {
      return 0;
    }
    const range = this.y.findRange(index + 1);
    const startIndex = this.y.getStartLineNumber(range) - 1;
    const endIndex = this.y.getEndLineNumber(range) - 1;
    return endIndex - startIndex;
  }
  updateFoldingRanges(ranges) {
    this.y = ranges;
    let updateHiddenAreas = false;
    const newHiddenAreas = [];
    let i2 = 0;
    let k = 0;
    let lastCollapsedStart = Number.MAX_VALUE;
    let lastCollapsedEnd = -1;
    for (; i2 < ranges.length; i2++) {
      if (!ranges.isCollapsed(i2)) {
        continue;
      }
      const startLineNumber = ranges.getStartLineNumber(i2) + 1;
      const endLineNumber = ranges.getEndLineNumber(i2);
      if (lastCollapsedStart <= startLineNumber && endLineNumber <= lastCollapsedEnd) {
        continue;
      }
      if (!updateHiddenAreas && k < this.C.length && this.C[k].start + 1 === startLineNumber && this.C[k].end + 1 === endLineNumber) {
        newHiddenAreas.push(this.C[k]);
        k++;
      } else {
        updateHiddenAreas = true;
        newHiddenAreas.push({ start: startLineNumber - 1, end: endLineNumber - 1 });
      }
      lastCollapsedStart = startLineNumber;
      lastCollapsedEnd = endLineNumber;
    }
    if (updateHiddenAreas || k < this.C.length) {
      this.C = newHiddenAreas;
      this.z.fire();
    }
    this.f.forEach((cell) => {
      if (cell.cellKind === CellKind.Markup) {
        cell.triggerFoldingStateChange();
      }
    });
  }
  getHiddenRanges() {
    return this.C;
  }
  getCellByHandle(handle2) {
    return this.b.get(handle2);
  }
  getCellIndexByHandle(handle2) {
    return this.f.findIndex((cell) => cell.handle === handle2);
  }
  getCellIndex(cell) {
    return this.f.indexOf(cell);
  }
  cellAt(index) {
    return this.f[index];
  }
  getCellsInRange(range) {
    if (!range) {
      return this.f.slice(0);
    }
    const validatedRange = this.validateRange(range);
    if (validatedRange) {
      const result = [];
      for (let i2 = validatedRange.start; i2 < validatedRange.end; i2++) {
        result.push(this.f[i2]);
      }
      return result;
    }
    return [];
  }
  /**
   * If this._viewCells[index] is visible then return index
   */
  getNearestVisibleCellIndexUpwards(index) {
    for (let i2 = this.C.length - 1; i2 >= 0; i2--) {
      const cellRange = this.C[i2];
      const foldStart = cellRange.start - 1;
      const foldEnd = cellRange.end;
      if (foldStart > index) {
        continue;
      }
      if (foldStart <= index && foldEnd >= index) {
        return index;
      }
      break;
    }
    return index;
  }
  getNextVisibleCellIndex(index) {
    for (let i2 = 0; i2 < this.C.length; i2++) {
      const cellRange = this.C[i2];
      const foldStart = cellRange.start - 1;
      const foldEnd = cellRange.end;
      if (foldEnd < index) {
        continue;
      }
      if (foldStart <= index) {
        return foldEnd + 1;
      }
      break;
    }
    return index + 1;
  }
  getPreviousVisibleCellIndex(index) {
    for (let i2 = this.C.length - 1; i2 >= 0; i2--) {
      const cellRange = this.C[i2];
      const foldStart = cellRange.start - 1;
      const foldEnd = cellRange.end;
      if (foldEnd < index) {
        return index;
      }
      if (foldStart <= index) {
        return foldStart;
      }
    }
    return index;
  }
  hasCell(cell) {
    return this.b.has(cell.handle);
  }
  getVersionId() {
    return this.H.versionId;
  }
  getAlternativeId() {
    return this.H.alternativeVersionId;
  }
  getTrackedRange(id2) {
    return this.R(id2);
  }
  R(decorationId) {
    const node = this.t[decorationId];
    if (!node) {
      return null;
    }
    const versionId = this.getVersionId();
    if (node.cachedVersionId !== versionId) {
      this.s.resolveNode(node, versionId);
    }
    if (node.range === null) {
      return { start: node.cachedAbsoluteStart - 1, end: node.cachedAbsoluteEnd - 1 };
    }
    return { start: node.range.startLineNumber - 1, end: node.range.endLineNumber - 1 };
  }
  setTrackedRange(id2, newRange, newStickiness) {
    const node = id2 ? this.t[id2] : null;
    if (!node) {
      if (!newRange) {
        return null;
      }
      return this.S(0, [], [{ range: new $9C(newRange.start + 1, 1, newRange.end + 1, 1), options: TRACKED_RANGE_OPTIONS2[newStickiness] }])[0];
    }
    if (!newRange) {
      this.s.delete(node);
      delete this.t[node.id];
      return null;
    }
    this.s.delete(node);
    node.reset(this.getVersionId(), newRange.start, newRange.end + 1, new $9C(newRange.start + 1, 1, newRange.end + 1, 1));
    node.setOptions(TRACKED_RANGE_OPTIONS2[newStickiness]);
    this.s.insert(node);
    return node.id;
  }
  S(ownerId2, oldDecorationsIds, newDecorations) {
    const versionId = this.getVersionId();
    const oldDecorationsLen = oldDecorationsIds.length;
    let oldDecorationIndex = 0;
    const newDecorationsLen = newDecorations.length;
    let newDecorationIndex = 0;
    const result = new Array(newDecorationsLen);
    while (oldDecorationIndex < oldDecorationsLen || newDecorationIndex < newDecorationsLen) {
      let node = null;
      if (oldDecorationIndex < oldDecorationsLen) {
        do {
          node = this.t[oldDecorationsIds[oldDecorationIndex++]];
        } while (!node && oldDecorationIndex < oldDecorationsLen);
        if (node) {
          this.s.delete(node);
        }
      }
      if (newDecorationIndex < newDecorationsLen) {
        if (!node) {
          const internalDecorationId = ++this.u;
          const decorationId = `${this.w};${internalDecorationId}`;
          node = new $2H(decorationId, 0, 0);
          this.t[decorationId] = node;
        }
        const newDecoration = newDecorations[newDecorationIndex];
        const range = newDecoration.range;
        const options3 = _normalizeOptions2(newDecoration.options);
        node.ownerId = ownerId2;
        node.reset(versionId, range.startLineNumber, range.endLineNumber, $9C.lift(range));
        node.setOptions(options3);
        this.s.insert(node);
        result[newDecorationIndex] = node.id;
        newDecorationIndex++;
      } else {
        if (node) {
          delete this.t[node.id];
        }
      }
    }
    return result;
  }
  deltaCellDecorations(oldDecorations, newDecorations) {
    oldDecorations.forEach((id2) => {
      const handle2 = this.F.get(id2);
      if (handle2 !== void 0) {
        const cell = this.getCellByHandle(handle2);
        cell?.deltaCellDecorations([id2], []);
        this.F.delete(id2);
      }
    });
    const result = [];
    newDecorations.forEach((decoration3) => {
      const cell = this.getCellByHandle(decoration3.handle);
      const ret = cell?.deltaCellDecorations([], [decoration3.options]) || [];
      ret.forEach((id2) => {
        this.F.set(id2, decoration3.handle);
      });
      result.push(...ret);
    });
    return result;
  }
  deltaCellStatusBarItems(oldItems, newItems) {
    const deletesByHandle = $a(oldItems, (id2) => this.G.get(id2) ?? -1);
    const result = [];
    newItems.forEach((itemDelta) => {
      const cell = this.getCellByHandle(itemDelta.handle);
      const deleted = deletesByHandle[itemDelta.handle] ?? [];
      delete deletesByHandle[itemDelta.handle];
      deleted.forEach((id2) => this.G.delete(id2));
      const ret = cell?.deltaCellStatusBarItems(deleted, itemDelta.items) || [];
      ret.forEach((id2) => {
        this.G.set(id2, itemDelta.handle);
      });
      result.push(...ret);
    });
    for (const _handle in deletesByHandle) {
      const handle2 = parseInt(_handle);
      const ids = deletesByHandle[handle2];
      const cell = this.getCellByHandle(handle2);
      cell?.deltaCellStatusBarItems(ids, []);
      ids.forEach((id2) => this.G.delete(id2));
    }
    return result;
  }
  nearestCodeCellIndex(index) {
    const nearest = this.viewCells.slice(0, index).reverse().findIndex((cell) => cell.cellKind === CellKind.Code);
    if (nearest > -1) {
      return index - nearest - 1;
    } else {
      const nearestCellTheOtherDirection = this.viewCells.slice(index + 1).findIndex((cell) => cell.cellKind === CellKind.Code);
      if (nearestCellTheOtherDirection > -1) {
        return index + 1 + nearestCellTheOtherDirection;
      }
      return -1;
    }
  }
  getEditorViewState() {
    const editingCells = {};
    const collapsedInputCells = {};
    const collapsedOutputCells = {};
    const cellLineNumberStates = {};
    this.f.forEach((cell, i2) => {
      if (cell.getEditState() === CellEditState.Editing) {
        editingCells[i2] = true;
      }
      if (cell.isInputCollapsed) {
        collapsedInputCells[i2] = true;
      }
      if (cell instanceof $XIb && cell.isOutputCollapsed) {
        collapsedOutputCells[i2] = true;
      }
      if (cell.lineNumbers !== "inherit") {
        cellLineNumberStates[i2] = cell.lineNumbers;
      }
    });
    const editorViewStates = {};
    this.f.map((cell) => ({ handle: cell.model.handle, state: cell.saveEditorViewState() })).forEach((viewState, i2) => {
      if (viewState.state) {
        editorViewStates[i2] = viewState.state;
      }
    });
    return {
      editingCells,
      editorViewStates,
      cellLineNumberStates,
      collapsedInputCells,
      collapsedOutputCells
    };
  }
  restoreEditorViewState(viewState) {
    if (!viewState) {
      return;
    }
    this.f.forEach((cell, index) => {
      const isEditing = viewState.editingCells && viewState.editingCells[index];
      const editorViewState = viewState.editorViewStates && viewState.editorViewStates[index];
      cell.updateEditState(isEditing ? CellEditState.Editing : CellEditState.Preview, "viewState");
      const cellHeight = viewState.cellTotalHeights ? viewState.cellTotalHeights[index] : void 0;
      cell.restoreEditorViewState(editorViewState, cellHeight);
      if (viewState.collapsedInputCells && viewState.collapsedInputCells[index]) {
        cell.isInputCollapsed = true;
      }
      if (viewState.collapsedOutputCells && viewState.collapsedOutputCells[index] && cell instanceof $XIb) {
        cell.isOutputCollapsed = true;
      }
      if (viewState.cellLineNumberStates && viewState.cellLineNumberStates[index]) {
        cell.lineNumbers = viewState.cellLineNumberStates[index];
      }
    });
  }
  /**
   * Editor decorations across cells. For example, find decorations for multiple code cells
   * The reason that we can't completely delegate this to CodeEditorWidget is most of the time, the editors for cells are not created yet but we already have decorations for them.
   */
  changeModelDecorations(callback) {
    const changeAccessor = {
      deltaDecorations: (oldDecorations, newDecorations) => {
        return this.U(oldDecorations, newDecorations);
      }
    };
    let result = null;
    try {
      result = callback(changeAccessor);
    } catch (e) {
      $gb(e);
    }
    changeAccessor.deltaDecorations = invalidFunc4;
    return result;
  }
  U(oldDecorations, newDecorations) {
    const mapping2 = /* @__PURE__ */ new Map();
    oldDecorations.forEach((oldDecoration) => {
      const ownerId2 = oldDecoration.ownerId;
      if (!mapping2.has(ownerId2)) {
        const cell = this.f.find((cell2) => cell2.handle === ownerId2);
        if (cell) {
          mapping2.set(ownerId2, { cell, oldDecorations: [], newDecorations: [] });
        }
      }
      const data = mapping2.get(ownerId2);
      if (data) {
        data.oldDecorations = oldDecoration.decorations;
      }
    });
    newDecorations.forEach((newDecoration) => {
      const ownerId2 = newDecoration.ownerId;
      if (!mapping2.has(ownerId2)) {
        const cell = this.f.find((cell2) => cell2.handle === ownerId2);
        if (cell) {
          mapping2.set(ownerId2, { cell, oldDecorations: [], newDecorations: [] });
        }
      }
      const data = mapping2.get(ownerId2);
      if (data) {
        data.newDecorations = newDecoration.decorations;
      }
    });
    const ret = [];
    mapping2.forEach((value, ownerId2) => {
      const cellRet = value.cell.deltaModelDecorations(value.oldDecorations, value.newDecorations);
      ret.push({
        ownerId: ownerId2,
        decorations: cellRet
      });
    });
    return ret;
  }
  //#region Find
  find(value, options3) {
    const matches = [];
    let findCells = [];
    if (options3.findScope && (options3.findScope.findScopeType === NotebookFindScopeType.Cells || options3.findScope.findScopeType === NotebookFindScopeType.Text)) {
      const selectedRanges = options3.findScope.selectedCellRanges?.map((range) => this.validateRange(range)).filter((range) => !!range) ?? [];
      const selectedIndexes = $GL(selectedRanges);
      findCells = selectedIndexes.map((index) => this.f[index]);
    } else {
      findCells = this.f;
    }
    findCells.forEach((cell, index) => {
      const cellMatches = cell.startFind(value, options3);
      if (cellMatches) {
        matches.push(new $OIb(cellMatches.cell, index, cellMatches.contentMatches, []));
      }
    });
    return matches.filter((match) => {
      if (match.cell.cellKind === CellKind.Code) {
        return options3.includeCodeInput;
      }
      if (match.cell.getEditState() === CellEditState.Editing) {
        return options3.includeMarkupInput;
      } else {
        return !options3.includeMarkupPreview && options3.includeMarkupInput;
      }
    });
  }
  replaceOne(cell, range, text2) {
    const viewCell = cell;
    this.j.push(viewCell.uri);
    return viewCell.resolveTextModel().then(() => {
      this.N.apply([new $J_(cell.uri, { range, text: text2 })], { quotableLabel: "Notebook Replace" });
    });
  }
  async replaceAll(matches, texts) {
    if (!matches.length) {
      return;
    }
    const textEdits = [];
    this.j.push(matches[0].cell.uri);
    matches.forEach((match) => {
      match.contentMatches.forEach((singleMatch, index) => {
        textEdits.push({
          versionId: void 0,
          textEdit: { range: singleMatch.range, text: texts[index] },
          resource: match.cell.uri
        });
      });
    });
    return Promise.all(matches.map((match) => {
      return match.cell.resolveTextModel();
    })).then(async () => {
      this.N.apply({ edits: textEdits }, { quotableLabel: "Notebook Replace All" });
      return;
    });
  }
  //#endregion
  //#region Undo/Redo
  async W(element, callback) {
    const viewCells = this.f.filter((cell) => element.matchesResource(cell.uri));
    const refs = await Promise.all(viewCells.map((cell) => this.P.createModelReference(cell.uri)));
    await callback();
    refs.forEach((ref) => ref.dispose());
  }
  async undo() {
    const editStack = this.O.getElements(this.uri);
    const element = editStack.past.length ? editStack.past[editStack.past.length - 1] : void 0;
    if (element && element instanceof $QH || element instanceof $RH) {
      await this.W(element, async () => {
        await this.O.undo(this.uri);
      });
      return element instanceof $QH ? [element.resource] : element.resources;
    }
    await this.O.undo(this.uri);
    return [];
  }
  async redo() {
    const editStack = this.O.getElements(this.uri);
    const element = editStack.future[0];
    if (element && element instanceof $QH || element instanceof $RH) {
      await this.W(element, async () => {
        await this.O.redo(this.uri);
      });
      return element instanceof $QH ? [element.resource] : element.resources;
    }
    await this.O.redo(this.uri);
    return [];
  }
  //#endregion
  equal(notebook) {
    return this.H === notebook;
  }
  dispose() {
    this.a.clear();
    this.f.forEach((cell) => {
      cell.dispose();
    });
    super.dispose();
  }
};
$ZIb = __decorate([
  __param(5, $Pk),
  __param(6, $H_),
  __param(7, $_F),
  __param(8, $oG),
  __param(9, $wL)
], $ZIb);
function $1Ib(instantiationService, notebookViewModel, cell, viewContext) {
  if (cell.cellKind === CellKind.Code) {
    return instantiationService.createInstance($XIb, notebookViewModel.viewType, cell, notebookViewModel.layoutInfo, viewContext);
  } else {
    return instantiationService.createInstance($YIb, notebookViewModel.viewType, cell, notebookViewModel.layoutInfo, notebookViewModel, viewContext);
  }
}

// out-build/vs/workbench/contrib/notebook/browser/viewModel/viewContext.js
var $SIb = class {
  constructor(notebookOptions, eventDispatcher, getBaseCellEditorOptions) {
    this.notebookOptions = notebookOptions;
    this.eventDispatcher = eventDispatcher;
    this.getBaseCellEditorOptions = getBaseCellEditorOptions;
  }
};

// out-build/vs/workbench/contrib/notebook/browser/viewParts/notebookEditorToolbar.js
var RenderLabel;
(function(RenderLabel2) {
  RenderLabel2[RenderLabel2["Always"] = 0] = "Always";
  RenderLabel2[RenderLabel2["Never"] = 1] = "Never";
  RenderLabel2[RenderLabel2["Dynamic"] = 2] = "Dynamic";
})(RenderLabel || (RenderLabel = {}));
var ICON_ONLY_ACTION_WIDTH = 21;
var TOGGLE_MORE_ACTION_WIDTH = 21;
var ACTION_PADDING = 8;
var WorkbenchAlwaysLabelStrategy = class {
  constructor(notebookEditor, editorToolbar, goToMenu, instantiationService) {
    this.notebookEditor = notebookEditor;
    this.editorToolbar = editorToolbar;
    this.goToMenu = goToMenu;
    this.instantiationService = instantiationService;
  }
  actionProvider(action, options3) {
    if (action.id === $wIb) {
      return this.instantiationService.createInstance($pLb, action, this.notebookEditor, options3);
    }
    if (action instanceof $fJ) {
      return this.instantiationService.createInstance($sKb, action, { hoverDelegate: options3.hoverDelegate });
    }
    if (action instanceof $eJ && action.item.submenu.id === $bJ.NotebookCellExecuteGoTo.id) {
      return this.instantiationService.createInstance($tKb, action, { hoverDelegate: options3.hoverDelegate }, true, {
        getActions: () => {
          return this.goToMenu.getActions().find(([group2]) => group2 === "navigation/execute")?.[1] ?? [];
        }
      }, this.actionProvider.bind(this));
    }
    return void 0;
  }
  calculateActions(leftToolbarContainerMaxWidth) {
    const initialPrimaryActions = this.editorToolbar.primaryActions;
    const initialSecondaryActions = this.editorToolbar.secondaryActions;
    const actionOutput = $sLb(initialPrimaryActions, initialSecondaryActions, leftToolbarContainerMaxWidth);
    return {
      primaryActions: actionOutput.primaryActions.map((a) => a.action),
      secondaryActions: actionOutput.secondaryActions
    };
  }
};
var WorkbenchNeverLabelStrategy = class {
  constructor(notebookEditor, editorToolbar, goToMenu, instantiationService) {
    this.notebookEditor = notebookEditor;
    this.editorToolbar = editorToolbar;
    this.goToMenu = goToMenu;
    this.instantiationService = instantiationService;
  }
  actionProvider(action, options3) {
    if (action.id === $wIb) {
      return this.instantiationService.createInstance($pLb, action, this.notebookEditor, options3);
    }
    if (action instanceof $fJ) {
      return this.instantiationService.createInstance($T$, action, { hoverDelegate: options3.hoverDelegate });
    }
    if (action instanceof $eJ) {
      if (action.item.submenu.id === $bJ.NotebookCellExecuteGoTo.id) {
        return this.instantiationService.createInstance($tKb, action, { hoverDelegate: options3.hoverDelegate }, false, {
          getActions: () => {
            return this.goToMenu.getActions().find(([group2]) => group2 === "navigation/execute")?.[1] ?? [];
          }
        }, this.actionProvider.bind(this));
      } else {
        return this.instantiationService.createInstance($V$, action, { hoverDelegate: options3.hoverDelegate });
      }
    }
    return void 0;
  }
  calculateActions(leftToolbarContainerMaxWidth) {
    const initialPrimaryActions = this.editorToolbar.primaryActions;
    const initialSecondaryActions = this.editorToolbar.secondaryActions;
    const actionOutput = $sLb(initialPrimaryActions, initialSecondaryActions, leftToolbarContainerMaxWidth);
    return {
      primaryActions: actionOutput.primaryActions.map((a) => a.action),
      secondaryActions: actionOutput.secondaryActions
    };
  }
};
var WorkbenchDynamicLabelStrategy = class {
  constructor(notebookEditor, editorToolbar, goToMenu, instantiationService) {
    this.notebookEditor = notebookEditor;
    this.editorToolbar = editorToolbar;
    this.goToMenu = goToMenu;
    this.instantiationService = instantiationService;
  }
  actionProvider(action, options3) {
    if (action.id === $wIb) {
      return this.instantiationService.createInstance($pLb, action, this.notebookEditor, options3);
    }
    const a = this.editorToolbar.primaryActions.find((a2) => a2.action.id === action.id);
    if (!a || a.renderLabel) {
      if (action instanceof $fJ) {
        return this.instantiationService.createInstance($sKb, action, { hoverDelegate: options3.hoverDelegate });
      }
      if (action instanceof $eJ && action.item.submenu.id === $bJ.NotebookCellExecuteGoTo.id) {
        return this.instantiationService.createInstance($tKb, action, { hoverDelegate: options3.hoverDelegate }, true, {
          getActions: () => {
            return this.goToMenu.getActions().find(([group2]) => group2 === "navigation/execute")?.[1] ?? [];
          }
        }, this.actionProvider.bind(this));
      }
      return void 0;
    } else {
      if (action instanceof $fJ) {
        this.instantiationService.createInstance($T$, action, { hoverDelegate: options3.hoverDelegate });
      }
      if (action instanceof $eJ) {
        if (action.item.submenu.id === $bJ.NotebookCellExecuteGoTo.id) {
          return this.instantiationService.createInstance($tKb, action, { hoverDelegate: options3.hoverDelegate }, false, {
            getActions: () => {
              return this.goToMenu.getActions().find(([group2]) => group2 === "navigation/execute")?.[1] ?? [];
            }
          }, this.actionProvider.bind(this));
        } else {
          return this.instantiationService.createInstance($V$, action, { hoverDelegate: options3.hoverDelegate });
        }
      }
      return void 0;
    }
  }
  calculateActions(leftToolbarContainerMaxWidth) {
    const initialPrimaryActions = this.editorToolbar.primaryActions;
    const initialSecondaryActions = this.editorToolbar.secondaryActions;
    const actionOutput = $tLb(initialPrimaryActions, initialSecondaryActions, leftToolbarContainerMaxWidth);
    return {
      primaryActions: actionOutput.primaryActions.map((a) => a.action),
      secondaryActions: actionOutput.secondaryActions
    };
  }
};
var $rLb = class $rLb2 extends $3c {
  get primaryActions() {
    return this.n;
  }
  get secondaryActions() {
    return this.r;
  }
  set visible(visible) {
    if (this.y !== visible) {
      this.y = visible;
      this.z.fire(visible);
    }
  }
  get useGlobalToolbar() {
    return this.t;
  }
  constructor(notebookEditor, contextKeyService, notebookOptions, domNode, F, G, H, I, J, L, M) {
    super();
    this.notebookEditor = notebookEditor;
    this.contextKeyService = contextKeyService;
    this.notebookOptions = notebookOptions;
    this.domNode = domNode;
    this.F = F;
    this.G = G;
    this.H = H;
    this.I = I;
    this.J = J;
    this.L = L;
    this.M = M;
    this.t = false;
    this.w = RenderLabel.Always;
    this.y = false;
    this.z = this.B(new $ze());
    this.onDidChangeVisibility = this.z.event;
    this.C = null;
    this.n = [];
    this.r = [];
    this.N();
    this.B(Event2.debounce(this.J.onDidActiveEditorChange, (last, _current) => last, 200)(this.O, this));
    this.P();
  }
  N() {
    this.f = document.createElement("div");
    this.f.classList.add("notebook-toolbar-left");
    this.c = new $CZ(this.f, {
      vertical: 2,
      horizontal: 3,
      horizontalScrollbarSize: 3,
      useShadows: false,
      scrollYToX: true
    });
    this.B(this.c);
    $bk(this.domNode, this.c.getDomNode());
    this.g = document.createElement("div");
    this.g.classList.add("notebook-toolbar-right");
    $bk(this.domNode, this.g);
  }
  O() {
    if (this.J.activeEditorPane?.getId() === $bM) {
      const notebookEditor = this.J.activeEditorPane.getControl();
      if (notebookEditor === this.notebookEditor) {
        this.S();
        return;
      }
    }
  }
  P() {
    this.h = this.B(this.I.createMenu(this.notebookEditor.creationOptions.menuIds.notebookToolbar, this.contextKeyService));
    this.j = this.B(this.I.createMenu($bJ.NotebookCellExecuteGoTo, this.contextKeyService));
    this.t = this.notebookOptions.getDisplayOptions().globalToolbar;
    this.w = this.R(this.G.getValue($rM.globalToolbarShowLabel));
    this.Q();
    const context = {
      ui: true,
      notebookEditor: this.notebookEditor,
      source: "notebookToolbar"
    };
    const actionProvider = (action, options3) => {
      if (action.id === $wIb) {
        return this.F.createInstance($pLb, action, this.notebookEditor, options3);
      }
      if (this.w !== RenderLabel.Never) {
        const a = this.n.find((a2) => a2.action.id === action.id);
        if (a && a.renderLabel) {
          return action instanceof $fJ ? this.F.createInstance($sKb, action, { hoverDelegate: options3.hoverDelegate }) : void 0;
        } else {
          return action instanceof $fJ ? this.F.createInstance($T$, action, { hoverDelegate: options3.hoverDelegate }) : void 0;
        }
      } else {
        return action instanceof $fJ ? this.F.createInstance($T$, action, { hoverDelegate: options3.hoverDelegate }) : void 0;
      }
    };
    const hoverDelegate = this.B(this.F.createInstance($6$, "element", true, {}));
    hoverDelegate.setInstantHoverTimeLimit(600);
    const leftToolbarOptions = {
      hiddenItemStrategy: 1,
      resetMenu: $bJ.NotebookToolbar,
      actionViewItemProvider: (action, options3) => {
        return this.u.actionProvider(action, options3);
      },
      getKeyBinding: (action) => this.L.lookupKeybinding(action.id),
      renderDropdownAsChildElement: true,
      hoverDelegate
    };
    this.m = this.F.createInstance($3$, this.f, leftToolbarOptions);
    this.B(this.m);
    this.m.context = context;
    this.s = new $f3(this.g, this.H, {
      getKeyBinding: (action) => this.L.lookupKeybinding(action.id),
      actionViewItemProvider: actionProvider,
      renderDropdownAsChildElement: true,
      hoverDelegate
    });
    this.B(this.s);
    this.s.context = context;
    this.S();
    let dropdownIsVisible = false;
    let deferredUpdate;
    this.B(this.h.onDidChange(() => {
      if (dropdownIsVisible) {
        deferredUpdate = () => this.S();
        return;
      }
      if (this.notebookEditor.isVisible) {
        this.S();
      }
    }));
    this.B(this.m.onDidChangeDropdownVisibility((visible) => {
      dropdownIsVisible = visible;
      if (deferredUpdate && !visible) {
        setTimeout(() => {
          deferredUpdate?.();
        }, 0);
        deferredUpdate = void 0;
      }
    }));
    this.B(this.notebookOptions.onDidChangeOptions((e) => {
      if (e.globalToolbar !== void 0) {
        this.t = this.notebookOptions.getDisplayOptions().globalToolbar;
        this.S();
      }
    }));
    this.B(this.G.onDidChangeConfiguration((e) => {
      if (e.affectsConfiguration($rM.globalToolbarShowLabel)) {
        this.w = this.R(this.G.getValue($rM.globalToolbarShowLabel));
        this.Q();
        const oldElement = this.m.getElement();
        oldElement.remove();
        this.m.dispose();
        this.m = this.F.createInstance($3$, this.f, leftToolbarOptions);
        this.B(this.m);
        this.m.context = context;
        this.S();
        return;
      }
    }));
    if (this.M) {
      this.M.getTreatment("nbtoolbarineditor").then((treatment) => {
        if (treatment === void 0) {
          return;
        }
        if (this.t !== treatment) {
          this.t = treatment;
          this.S();
        }
      });
    }
  }
  Q() {
    switch (this.w) {
      case RenderLabel.Always:
        this.u = new WorkbenchAlwaysLabelStrategy(this.notebookEditor, this, this.j, this.F);
        break;
      case RenderLabel.Never:
        this.u = new WorkbenchNeverLabelStrategy(this.notebookEditor, this, this.j, this.F);
        break;
      case RenderLabel.Dynamic:
        this.u = new WorkbenchDynamicLabelStrategy(this.notebookEditor, this, this.j, this.F);
        break;
    }
  }
  R(value) {
    switch (value) {
      case true:
        return RenderLabel.Always;
      case false:
        return RenderLabel.Never;
      case "always":
        return RenderLabel.Always;
      case "never":
        return RenderLabel.Never;
      case "dynamic":
        return RenderLabel.Dynamic;
    }
  }
  S() {
    if (!this.notebookEditor.hasModel()) {
      this.D?.dispose();
      this.D = void 0;
      this.visible = false;
      return;
    }
    if (this.D) {
      return;
    }
    if (!this.t) {
      this.domNode.style.display = "none";
      this.D = void 0;
      this.visible = false;
    } else {
      this.D = $Xh(async () => {
        await this.U();
        this.visible = true;
        this.D = void 0;
      }, 50);
    }
  }
  async U() {
    const groups = this.h.getActions({ shouldForwardArgs: true, renderShortTitle: true });
    this.domNode.style.display = "flex";
    const primaryLeftGroups = groups.filter((group2) => /^navigation/.test(group2[0]));
    const primaryActions = [];
    primaryLeftGroups.sort((a, b) => {
      if (a[0] === "navigation") {
        return 1;
      }
      if (b[0] === "navigation") {
        return -1;
      }
      return 0;
    }).forEach((group2, index) => {
      primaryActions.push(...group2[1]);
      if (index < primaryLeftGroups.length - 1) {
        primaryActions.push(new $Wm());
      }
    });
    const primaryRightGroup = groups.find((group2) => /^status/.test(group2[0]));
    const primaryRightActions = primaryRightGroup ? primaryRightGroup[1] : [];
    const secondaryActions = groups.filter((group2) => !/^navigation/.test(group2[0]) && !/^status/.test(group2[0])).reduce((prev, curr) => {
      prev.push(...curr[1]);
      return prev;
    }, []);
    this.m.setActions([], []);
    this.n = primaryActions.map((action) => ({
      action,
      size: action instanceof $Wm ? 1 : 0,
      renderLabel: true,
      visible: true
    }));
    this.m.setActions(primaryActions, secondaryActions);
    this.r = secondaryActions;
    this.s.setActions(primaryRightActions, []);
    this.r = secondaryActions;
    if (this.C && this.C.width >= 0 && this.C.height >= 0) {
      this.W(this.m);
    }
    this.X();
  }
  W(toolbar) {
    for (let i2 = 0; i2 < toolbar.getItemsLength(); i2++) {
      const action = toolbar.getItemAction(i2);
      if (action && action.id !== "toolbar.toggle.more") {
        const existing = this.n.find((a) => a.action.id === action.id);
        if (existing) {
          existing.size = toolbar.getItemWidth(i2);
        }
      }
    }
  }
  X() {
    const toolbar = this.m;
    const rightToolbar = this.s;
    if (toolbar && rightToolbar && this.C && this.C.height >= 0 && this.C.width >= 0) {
      if (this.n.length === 0 && toolbar.getItemsLength() !== this.n.length) {
        this.W(this.m);
      }
      if (this.n.length === 0) {
        return;
      }
      const kernelWidth = (rightToolbar.getItemsLength() ? rightToolbar.getItemWidth(0) : 0) + ACTION_PADDING;
      const leftToolbarContainerMaxWidth = this.C.width - kernelWidth - (ACTION_PADDING + TOGGLE_MORE_ACTION_WIDTH) - /** toolbar left margin */
      ACTION_PADDING - /** toolbar right margin */
      ACTION_PADDING;
      const calculatedActions = this.u.calculateActions(leftToolbarContainerMaxWidth);
      this.m.setActions(calculatedActions.primaryActions, calculatedActions.secondaryActions);
    }
  }
  layout(dimension) {
    this.C = dimension;
    if (!this.t) {
      this.domNode.style.display = "none";
    } else {
      this.domNode.style.display = "flex";
    }
    this.X();
  }
  dispose() {
    this.m.context = void 0;
    this.s.context = void 0;
    this.m.dispose();
    this.s.dispose();
    this.m = null;
    this.s = null;
    this.D?.dispose();
    this.D = void 0;
    super.dispose();
  }
};
$rLb = __decorate([
  __param(4, $Pk),
  __param(5, $kl),
  __param(6, $50),
  __param(7, $cJ),
  __param(8, $mJ),
  __param(9, $Ty),
  __param(10, $hFb)
], $rLb);
function $sLb(initialPrimaryActions, initialSecondaryActions, leftToolbarContainerMaxWidth) {
  return actionOverflowHelper(initialPrimaryActions, initialSecondaryActions, leftToolbarContainerMaxWidth, false);
}
function $tLb(initialPrimaryActions, initialSecondaryActions, leftToolbarContainerMaxWidth) {
  if (initialPrimaryActions.length === 0) {
    return { primaryActions: [], secondaryActions: initialSecondaryActions };
  }
  const visibleActionLength = initialPrimaryActions.filter((action) => action.size !== 0).length;
  const totalWidthWithLabels = initialPrimaryActions.map((action) => action.size).reduce((a, b) => a + b, 0) + (visibleActionLength - 1) * ACTION_PADDING;
  if (totalWidthWithLabels <= leftToolbarContainerMaxWidth) {
    initialPrimaryActions.forEach((action) => {
      action.renderLabel = true;
    });
    return actionOverflowHelper(initialPrimaryActions, initialSecondaryActions, leftToolbarContainerMaxWidth, false);
  }
  if (visibleActionLength * ICON_ONLY_ACTION_WIDTH + (visibleActionLength - 1) * ACTION_PADDING > leftToolbarContainerMaxWidth) {
    initialPrimaryActions.forEach((action) => {
      action.renderLabel = false;
    });
    return actionOverflowHelper(initialPrimaryActions, initialSecondaryActions, leftToolbarContainerMaxWidth, true);
  }
  let sum = 0;
  let lastActionWithLabel = -1;
  for (let i2 = 0; i2 < initialPrimaryActions.length; i2++) {
    sum += initialPrimaryActions[i2].size + ACTION_PADDING;
    if (initialPrimaryActions[i2].action instanceof $Wm) {
      const remainingItems = initialPrimaryActions.slice(i2 + 1).filter((action) => action.size !== 0);
      const newTotalSum = sum + (remainingItems.length === 0 ? 0 : remainingItems.length * ICON_ONLY_ACTION_WIDTH + (remainingItems.length - 1) * ACTION_PADDING);
      if (newTotalSum <= leftToolbarContainerMaxWidth) {
        lastActionWithLabel = i2;
      }
    } else {
      continue;
    }
  }
  if (lastActionWithLabel < 0) {
    initialPrimaryActions.forEach((action) => {
      action.renderLabel = false;
    });
    return actionOverflowHelper(initialPrimaryActions, initialSecondaryActions, leftToolbarContainerMaxWidth, true);
  }
  initialPrimaryActions.slice(0, lastActionWithLabel + 1).forEach((action) => {
    action.renderLabel = true;
  });
  initialPrimaryActions.slice(lastActionWithLabel + 1).forEach((action) => {
    action.renderLabel = false;
  });
  return {
    primaryActions: initialPrimaryActions,
    secondaryActions: initialSecondaryActions
  };
}
function actionOverflowHelper(initialPrimaryActions, initialSecondaryActions, leftToolbarContainerMaxWidth, iconOnly) {
  const renderActions = [];
  const overflow = [];
  let currentSize = 0;
  let nonZeroAction = false;
  let containerFull = false;
  if (initialPrimaryActions.length === 0) {
    return { primaryActions: [], secondaryActions: initialSecondaryActions };
  }
  for (let i2 = 0; i2 < initialPrimaryActions.length; i2++) {
    const actionModel = initialPrimaryActions[i2];
    const itemSize = iconOnly ? actionModel.size === 0 ? 0 : ICON_ONLY_ACTION_WIDTH : actionModel.size;
    if (actionModel.action instanceof $Wm && renderActions.length > 0 && renderActions[renderActions.length - 1].action instanceof $Wm) {
      continue;
    }
    if (actionModel.action instanceof $Wm && !nonZeroAction) {
      continue;
    }
    if (currentSize + itemSize <= leftToolbarContainerMaxWidth && !containerFull) {
      currentSize += ACTION_PADDING + itemSize;
      renderActions.push(actionModel);
      if (itemSize !== 0) {
        nonZeroAction = true;
      }
      if (actionModel.action instanceof $Wm) {
        nonZeroAction = false;
      }
    } else {
      containerFull = true;
      if (itemSize === 0) {
        renderActions.push(actionModel);
      } else {
        if (actionModel.action instanceof $Wm) {
          continue;
        }
        overflow.push(actionModel.action);
      }
    }
  }
  for (let i2 = renderActions.length - 1; i2 > 0; i2--) {
    const temp = renderActions[i2];
    if (temp.size === 0) {
      continue;
    }
    if (temp.action instanceof $Wm) {
      renderActions.splice(i2, 1);
    }
    break;
  }
  if (renderActions.length && renderActions[renderActions.length - 1].action instanceof $Wm) {
    renderActions.pop();
  }
  if (overflow.length !== 0) {
    overflow.push(new $Wm());
  }
  if (iconOnly) {
    const markdownIndex = renderActions.findIndex((a) => a.action.id === "notebook.cell.insertMarkdownCellBelow");
    if (markdownIndex !== -1) {
      renderActions.splice(markdownIndex, 1);
    }
  }
  return {
    primaryActions: renderActions,
    secondaryActions: [...overflow, ...initialSecondaryActions]
  };
}

// out-build/vs/workbench/contrib/notebook/browser/viewParts/notebookEditorWidgetContextKeys.js
var $uLb = class $uLb2 {
  constructor(v, w, contextKeyService, x, y) {
    this.v = v;
    this.w = w;
    this.x = x;
    this.y = y;
    this.r = new $2c();
    this.s = new $2c();
    this.t = [];
    this.u = new $2c();
    this.a = $nBb.bindTo(contextKeyService);
    this.b = $oBb.bindTo(contextKeyService);
    this.f = $qBb.bindTo(contextKeyService);
    this.g = $rBb.bindTo(contextKeyService);
    this.h = $uBb.bindTo(contextKeyService);
    this.j = $2Ab.bindTo(contextKeyService);
    this.k = $3Ab.bindTo(contextKeyService);
    this.m = $4Ab.bindTo(contextKeyService);
    this.l = $tBb.bindTo(contextKeyService);
    this.n = $9Ab.bindTo(contextKeyService);
    this.o = $sBb.bindTo(contextKeyService);
    this.d = $pBb.bindTo(contextKeyService);
    this.p = $6Ab.bindTo(contextKeyService);
    this.q = $8Ab.bindTo(contextKeyService);
    this.z();
    this.E();
    this.r.add(v.onDidChangeModel(this.z, this));
    this.r.add(w.onDidAddKernel(this.D, this));
    this.r.add(w.onDidChangeSelectedNotebooks(this.D, this));
    this.r.add(w.onDidChangeSourceActions(this.D, this));
    this.r.add(v.notebookOptions.onDidChangeOptions(this.E, this));
    this.r.add(x.onDidChangeExtensions(this.C, this));
    this.r.add(y.onDidChangeExecution(this.A, this));
    this.r.add(y.onDidChangeLastRunFailState(this.B, this));
  }
  dispose() {
    this.r.dispose();
    this.s.dispose();
    this.b.reset();
    this.d.reset();
    this.g.reset();
    this.h.reset();
    this.j.reset();
    this.k.reset();
    this.n.reset();
    $Xc(this.t);
    this.t.length = 0;
  }
  z() {
    this.D();
    this.E();
    this.s.clear();
    $Xc(this.t);
    this.t.length = 0;
    if (!this.v.hasModel()) {
      return;
    }
    const recomputeOutputsExistence = () => {
      let hasOutputs = false;
      if (this.v.hasModel()) {
        for (let i2 = 0; i2 < this.v.getLength(); i2++) {
          if (this.v.cellAt(i2).outputsViewModels.length > 0) {
            hasOutputs = true;
            break;
          }
        }
      }
      this.l.set(hasOutputs);
    };
    const layoutDisposable = this.s.add(new $2c());
    const addCellOutputsListener = (c) => {
      return c.model.onDidChangeOutputs(() => {
        layoutDisposable.clear();
        layoutDisposable.add($jj(getWindow(this.v.getDomNode()), () => {
          recomputeOutputsExistence();
        }));
      });
    };
    for (let i2 = 0; i2 < this.v.getLength(); i2++) {
      const cell = this.v.cellAt(i2);
      this.t.push(addCellOutputsListener(cell));
    }
    recomputeOutputsExistence();
    this.C();
    this.s.add(this.v.onDidChangeViewCells((e) => {
      [...e.splices].reverse().forEach((splice2) => {
        const [start, deleted, newCells] = splice2;
        const deletedCellOutputStates = this.t.splice(start, deleted, ...newCells.map(addCellOutputsListener));
        $Xc(deletedCellOutputStates);
      });
    }));
    this.n.set(this.v.textModel.viewType);
  }
  A(e) {
    if (this.v.textModel) {
      const notebookExe = this.y.getExecution(this.v.textModel.uri);
      const notebookCellExe = this.y.getCellExecutionsForNotebook(this.v.textModel.uri);
      this.k.set(notebookCellExe.length > 0 || !!notebookExe);
      if (e.type === NotebookExecutionType.cell) {
        this.j.set(notebookCellExe.length > 0);
      }
    } else {
      this.k.set(false);
      if (e.type === NotebookExecutionType.cell) {
        this.j.set(false);
      }
    }
  }
  B(e) {
    if (e.notebook === this.v.textModel?.uri) {
      this.q.set(e.visible);
    }
  }
  async C() {
    if (!this.v.hasModel()) {
      return;
    }
    const viewType = this.v.textModel.viewType;
    const kernelExtensionId = $Orb.get(viewType);
    this.o.set(!!kernelExtensionId && !await this.x.getExtension(kernelExtensionId));
  }
  D() {
    if (!this.v.hasModel()) {
      this.b.reset();
      this.d.reset();
      this.g.reset();
      this.h.reset();
      return;
    }
    const { selected, all } = this.w.getMatchingKernel(this.v.textModel);
    const sourceActions = this.w.getSourceActions(this.v.textModel, this.v.scopedContextKeyService);
    this.b.set(all.length);
    this.d.set(sourceActions.length);
    this.g.set(selected?.implementsInterrupt ?? false);
    this.h.set(selected?.hasVariableProvider ?? false);
    this.f.set(Boolean(selected));
    this.a.set(selected?.id ?? "");
    this.u.clear();
    if (selected) {
      this.u.add(selected.onDidChange(() => {
        this.g.set(selected?.implementsInterrupt ?? false);
      }));
    }
  }
  E() {
    const layout = this.v.notebookOptions.getDisplayOptions();
    this.m.set(layout.consolidatedOutputButton);
    this.p.set(this.v.notebookOptions.computeCellToolbarLocation(this.v.textModel?.viewType));
  }
};
$uLb = __decorate([
  __param(1, $CL),
  __param(2, $on),
  __param(3, $wN),
  __param(4, $wL)
], $uLb);

// out-build/vs/workbench/contrib/notebook/browser/viewParts/notebookOverviewRuler.js
var $vLb = class $vLb2 extends $ns {
  constructor(notebookEditor, container2, themeService) {
    super(themeService);
    this.notebookEditor = notebookEditor;
    this.b = 3;
    this.a = $oZ(document.createElement("canvas"));
    this.a.setPosition("relative");
    this.a.setLayerHinting(true);
    this.a.setContain("strict");
    container2.appendChild(this.a.domNode);
    this.B(notebookEditor.onDidChangeDecorations(() => {
      this.layout();
    }));
    this.B($_1.getInstance(getWindow(this.a.domNode)).onDidChange(() => {
      this.layout();
    }));
  }
  layout() {
    const width2 = 10;
    const layoutInfo = this.notebookEditor.getLayoutInfo();
    const scrollHeight = layoutInfo.scrollHeight;
    const height = layoutInfo.height;
    const ratio = $_1.getInstance(getWindow(this.a.domNode)).value;
    this.a.setWidth(width2);
    this.a.setHeight(height);
    this.a.domNode.width = width2 * ratio;
    this.a.domNode.height = height * ratio;
    const ctx = this.a.domNode.getContext("2d");
    ctx.clearRect(0, 0, width2 * ratio, height * ratio);
    this.c(ctx, width2 * ratio, height * ratio, scrollHeight * ratio, ratio);
  }
  c(ctx, width2, height, scrollHeight, ratio) {
    const viewModel = this.notebookEditor.getViewModel();
    const fontInfo = this.notebookEditor.getLayoutInfo().fontInfo;
    const laneWidth = width2 / this.b;
    let currentFrom = 0;
    if (viewModel) {
      for (let i2 = 0; i2 < viewModel.viewCells.length; i2++) {
        const viewCell = viewModel.viewCells[i2];
        const textBuffer = viewCell.textBuffer;
        const decorations = viewCell.getCellDecorations();
        const cellHeight = viewCell.layoutInfo.totalHeight / scrollHeight * ratio * height;
        decorations.filter((decoration3) => decoration3.overviewRuler).forEach((decoration3) => {
          const overviewRuler = decoration3.overviewRuler;
          const fillStyle = this.z(overviewRuler.color) ?? "#000000";
          const lineHeight = Math.min(fontInfo.lineHeight, viewCell.layoutInfo.editorHeight / scrollHeight / textBuffer.getLineCount() * ratio * height);
          const lineNumbers = overviewRuler.modelRanges.map((range) => range.startLineNumber).reduce((previous, current) => {
            if (previous.length === 0) {
              previous.push(current);
            } else {
              const last = previous[previous.length - 1];
              if (last !== current) {
                previous.push(current);
              }
            }
            return previous;
          }, []);
          let x = 0;
          switch (overviewRuler.position) {
            case NotebookOverviewRulerLane.Left:
              x = 0;
              break;
            case NotebookOverviewRulerLane.Center:
              x = laneWidth;
              break;
            case NotebookOverviewRulerLane.Right:
              x = laneWidth * 2;
              break;
            default:
              break;
          }
          const width3 = overviewRuler.position === NotebookOverviewRulerLane.Full ? laneWidth * 3 : laneWidth;
          for (let i3 = 0; i3 < lineNumbers.length; i3++) {
            ctx.fillStyle = fillStyle;
            const lineNumber = lineNumbers[i3];
            const offset = (lineNumber - 1) * lineHeight;
            ctx.fillRect(x, currentFrom + offset, width3, lineHeight);
          }
          if (overviewRuler.includeOutput) {
            ctx.fillStyle = fillStyle;
            const outputOffset = viewCell.layoutInfo.editorHeight / scrollHeight * ratio * height;
            const decorationHeight = fontInfo.lineHeight / scrollHeight * ratio * height;
            ctx.fillRect(laneWidth, currentFrom + outputOffset, laneWidth, decorationHeight);
          }
        });
        currentFrom += cellHeight;
      }
    }
  }
};
$vLb = __decorate([
  __param(2, $gs)
], $vLb);

// out-build/vs/workbench/contrib/notebook/browser/viewParts/notebookTopCellToolbar.js
var $wLb = class $wLb2 extends $3c {
  constructor(h3, j, m, n, r2) {
    super();
    this.h = h3;
    this.j = j;
    this.m = m;
    this.n = n;
    this.r = r2;
    this.c = this.B(new $4c());
    this.f = this.B(new $2c());
    this.a = $("div");
    this.b = $(".cell-list-top-cell-toolbar-container");
    this.a.appendChild(this.b);
    this.B(this.h.onDidAttachViewModel(() => {
      this.s();
    }));
    this.B(this.j.onDidChangeOptions((e) => {
      if (e.insertToolbarAlignment || e.insertToolbarPosition || e.cellToolbarLocation) {
        this.s();
      }
    }));
  }
  s() {
    const layoutInfo = this.j.getLayoutConfiguration();
    this.c.value = new $2c();
    if (layoutInfo.insertToolbarPosition === "hidden" || layoutInfo.insertToolbarPosition === "notebookToolbar") {
      const height = this.j.computeTopInsertToolbarHeight(this.h.textModel?.viewType);
      if (height !== 0) {
        this.h.changeViewZones((accessor) => {
          const id2 = accessor.addZone({
            afterModelPosition: 0,
            heightInPx: height,
            domNode: $("div")
          });
          accessor.layoutZone(id2);
          this.c.value?.add({
            dispose: () => {
              if (!this.h.isDisposed) {
                this.h.changeViewZones((accessor2) => {
                  accessor2.removeZone(id2);
                });
              }
            }
          });
        });
      }
      return;
    }
    this.h.changeViewZones((accessor) => {
      const height = this.j.computeTopInsertToolbarHeight(this.h.textModel?.viewType);
      const id2 = accessor.addZone({
        afterModelPosition: 0,
        heightInPx: height,
        domNode: this.a
      });
      accessor.layoutZone(id2);
      this.c.value?.add({
        dispose: () => {
          if (!this.h.isDisposed) {
            this.h.changeViewZones((accessor2) => {
              accessor2.removeZone(id2);
            });
          }
        }
      });
      $$i(this.b);
      const toolbar = this.m.createInstance($4$, this.b, this.h.creationOptions.menuIds.cellTopInsertToolbar, {
        actionViewItemProvider: (action, options3) => {
          if (action instanceof $fJ) {
            const item = this.m.createInstance($rKb, action, { hoverDelegate: options3.hoverDelegate });
            return item;
          }
          return void 0;
        },
        menuOptions: {
          shouldForwardArgs: true
        },
        toolbarOptions: {
          primaryGroup: (g) => /^inline/.test(g)
        },
        hiddenItemStrategy: 0
      });
      if (this.h.hasModel()) {
        toolbar.context = {
          notebookEditor: this.h
        };
      }
      this.c.value?.add(toolbar);
      this.c.value?.add(this.h.onDidChangeModel(() => {
        this.f.clear();
        if (this.h.hasModel()) {
          this.f.add(this.h.onDidChangeViewCells(() => {
            this.t();
          }));
          this.t();
        }
      }));
      this.t();
    });
  }
  t() {
    if (this.h.hasModel() && this.h.getLength() === 0) {
      this.b.classList.add("emptyNotebook");
    } else {
      this.b.classList.remove("emptyNotebook");
    }
  }
};
$wLb = __decorate([
  __param(2, $Pk),
  __param(3, $50),
  __param(4, $cJ)
], $wLb);

// out-build/vs/workbench/contrib/notebook/browser/notebookOptions.js
var SCROLLABLE_ELEMENT_PADDING_TOP = 18;
var $wrb = 4;
var defaultConfigConstants = Object.freeze({
  codeCellLeftMargin: 28,
  cellRunGutter: 32,
  markdownCellTopMargin: 8,
  markdownCellBottomMargin: 8,
  markdownCellLeftMargin: 0,
  markdownCellGutter: 32,
  focusIndicatorLeftMargin: 4
});
var compactConfigConstants = Object.freeze({
  codeCellLeftMargin: 8,
  cellRunGutter: 36,
  markdownCellTopMargin: 6,
  markdownCellBottomMargin: 6,
  markdownCellLeftMargin: 8,
  markdownCellGutter: 36,
  focusIndicatorLeftMargin: 4
});
var $xrb = class $xrb2 extends $3c {
  constructor(targetWindow, f, g, h3, j, m) {
    super();
    this.targetWindow = targetWindow;
    this.f = f;
    this.g = g;
    this.h = h3;
    this.j = j;
    this.m = m;
    this.b = this.B(new $ze());
    this.onDidChangeOptions = this.b.event;
    this.c = 12;
    const showCellStatusBar = this.h.getValue($rM.showCellStatusBar);
    const globalToolbar = g?.globalToolbar ?? this.h.getValue($rM.globalToolbar) ?? true;
    const stickyScrollEnabled = g?.stickyScrollEnabled ?? this.h.getValue($rM.stickyScrollEnabled) ?? false;
    const stickyScrollMode = this.C();
    const consolidatedOutputButton = this.h.getValue($rM.consolidatedOutputButton) ?? true;
    const consolidatedRunButton = this.h.getValue($rM.consolidatedRunButton) ?? false;
    const dragAndDropEnabled = g?.dragAndDropEnabled ?? this.h.getValue($rM.dragAndDropEnabled) ?? true;
    const cellToolbarLocation = this.h.getValue($rM.cellToolbarLocation) ?? { "default": "right" };
    const cellToolbarInteraction = g?.cellToolbarInteraction ?? this.h.getValue($rM.cellToolbarVisibility);
    const compactView = this.h.getValue($rM.compactView) ?? true;
    const focusIndicator = this.z();
    const insertToolbarPosition = this.u(this.f);
    const insertToolbarAlignment = this.w();
    const showFoldingControls = this.y();
    const fontSize = this.h.getValue("editor.fontSize");
    const markupFontSize = this.h.getValue($rM.markupFontSize);
    const markdownLineHeight = this.h.getValue($rM.markdownLineHeight);
    let editorOptionsCustomizations = this.h.getValue($rM.cellEditorOptionsCustomizations) ?? {};
    editorOptionsCustomizations = $Bg(editorOptionsCustomizations) ? editorOptionsCustomizations : {};
    const interactiveWindowCollapseCodeCells = this.h.getValue($rM.interactiveWindowCollapseCodeCells);
    let outputLineHeightSettingValue;
    const deprecatedOutputLineHeightSetting = this.h.getValue($rM.outputLineHeightDeprecated);
    if (deprecatedOutputLineHeightSetting !== void 0) {
      this.r($rM.outputLineHeightDeprecated, $rM.outputLineHeight);
      outputLineHeightSettingValue = deprecatedOutputLineHeightSetting;
    } else {
      outputLineHeightSettingValue = this.h.getValue($rM.outputLineHeight);
    }
    let outputFontSize;
    const deprecatedOutputFontSizeSetting = this.h.getValue($rM.outputFontSizeDeprecated);
    if (deprecatedOutputFontSizeSetting !== void 0) {
      this.r($rM.outputFontSizeDeprecated, $rM.outputFontSize);
      outputFontSize = deprecatedOutputFontSizeSetting;
    } else {
      outputFontSize = this.h.getValue($rM.outputFontSize) || fontSize;
    }
    let outputFontFamily;
    const deprecatedOutputFontFamilySetting = this.h.getValue($rM.outputFontFamilyDeprecated);
    if (deprecatedOutputFontFamilySetting !== void 0) {
      this.r($rM.outputFontFamilyDeprecated, $rM.outputFontFamily);
      outputFontFamily = deprecatedOutputFontFamilySetting;
    } else {
      outputFontFamily = this.h.getValue($rM.outputFontFamily);
    }
    let outputScrolling;
    const deprecatedOutputScrollingSetting = this.h.getValue($rM.outputScrollingDeprecated);
    if (deprecatedOutputScrollingSetting !== void 0) {
      this.r($rM.outputScrollingDeprecated, $rM.outputScrolling);
      outputScrolling = deprecatedOutputScrollingSetting;
    } else {
      outputScrolling = this.h.getValue($rM.outputScrolling);
    }
    const outputLineHeight = this.s(outputLineHeightSettingValue, outputFontSize);
    const outputWordWrap = this.h.getValue($rM.outputWordWrap);
    const outputLineLimit = this.h.getValue($rM.textOutputLineLimit) ?? 30;
    const linkifyFilePaths = this.h.getValue($rM.LinkifyOutputFilePaths) ?? true;
    const minimalErrors = this.h.getValue($rM.minimalErrorRendering);
    const editorTopPadding = this.n();
    this.a = {
      ...compactView ? compactConfigConstants : defaultConfigConstants,
      cellTopMargin: 6,
      cellBottomMargin: 6,
      cellRightMargin: 16,
      cellStatusBarHeight: 22,
      cellOutputPadding: 8,
      markdownPreviewPadding: 8,
      // bottomToolbarHeight: bottomToolbarHeight,
      // bottomToolbarGap: bottomToolbarGap,
      editorToolbarHeight: 0,
      editorTopPadding,
      editorBottomPadding: 4,
      editorBottomPaddingWithoutStatusBar: 12,
      collapsedIndicatorHeight: 28,
      showCellStatusBar,
      globalToolbar,
      stickyScrollEnabled,
      stickyScrollMode,
      consolidatedOutputButton,
      consolidatedRunButton,
      dragAndDropEnabled,
      cellToolbarLocation,
      cellToolbarInteraction,
      compactView,
      focusIndicator,
      insertToolbarPosition,
      insertToolbarAlignment,
      showFoldingControls,
      fontSize,
      outputFontSize,
      outputFontFamily,
      outputLineHeight,
      markupFontSize,
      markdownLineHeight,
      editorOptionsCustomizations,
      focusIndicatorGap: 3,
      interactiveWindowCollapseCodeCells,
      markdownFoldHintHeight: 22,
      outputScrolling,
      outputWordWrap,
      outputLineLimit,
      outputLinkifyFilePaths: linkifyFilePaths,
      outputMinimalError: minimalErrors
    };
    this.B(this.h.onDidChangeConfiguration((e) => {
      this.t(e);
    }));
  }
  updateOptions(isReadonly) {
    if (this.f !== isReadonly) {
      this.f = isReadonly;
      this.t({
        affectsConfiguration(configuration2) {
          return configuration2 === $rM.insertToolbarLocation;
        },
        source: 7,
        affectedKeys: /* @__PURE__ */ new Set([$rM.insertToolbarLocation]),
        change: { keys: [$rM.insertToolbarLocation], overrides: [] }
      });
    }
  }
  n() {
    let decorationTriggeredAdjustment = false;
    const updateEditorTopPadding = (top2) => {
      this.c = top2;
      const configuration2 = Object.assign({}, this.a);
      configuration2.editorTopPadding = this.c;
      this.a = configuration2;
      this.b.fire({ editorTopPadding: true });
    };
    const decorationCheckSet = /* @__PURE__ */ new Set();
    const onDidAddDecorationType = (e) => {
      if (decorationTriggeredAdjustment) {
        return;
      }
      if (decorationCheckSet.has(e)) {
        return;
      }
      try {
        const options3 = this.m.resolveDecorationOptions(e, true);
        if (options3.afterContentClassName || options3.beforeContentClassName) {
          const cssRules = this.m.resolveDecorationCSSRules(e);
          if (cssRules !== null) {
            for (let i2 = 0; i2 < cssRules.length; i2++) {
              if ((cssRules[i2].selectorText.endsWith("::after") || cssRules[i2].selectorText.endsWith("::after")) && cssRules[i2].cssText.indexOf("top:") > -1) {
                const editorOptions2 = this.h.getValue("editor");
                updateEditorTopPadding($ED.createFromRawSettings(editorOptions2, $_1.getInstance(this.targetWindow).value).lineHeight + 2);
                decorationTriggeredAdjustment = true;
                break;
              }
            }
          }
        }
        decorationCheckSet.add(e);
      } catch (_ex) {
      }
    };
    this.B(this.m.onDecorationTypeRegistered(onDidAddDecorationType));
    this.m.listDecorationTypes().forEach(onDidAddDecorationType);
    return this.c;
  }
  r(deprecatedKey, key2) {
    const deprecatedSetting = this.h.inspect(deprecatedKey);
    if (deprecatedSetting.application !== void 0) {
      this.h.updateValue(
        deprecatedKey,
        void 0,
        1
        /* ConfigurationTarget.APPLICATION */
      );
      this.h.updateValue(
        key2,
        deprecatedSetting.application.value,
        1
        /* ConfigurationTarget.APPLICATION */
      );
    }
    if (deprecatedSetting.user !== void 0) {
      this.h.updateValue(
        deprecatedKey,
        void 0,
        2
        /* ConfigurationTarget.USER */
      );
      this.h.updateValue(
        key2,
        deprecatedSetting.user.value,
        2
        /* ConfigurationTarget.USER */
      );
    }
    if (deprecatedSetting.userLocal !== void 0) {
      this.h.updateValue(
        deprecatedKey,
        void 0,
        3
        /* ConfigurationTarget.USER_LOCAL */
      );
      this.h.updateValue(
        key2,
        deprecatedSetting.userLocal.value,
        3
        /* ConfigurationTarget.USER_LOCAL */
      );
    }
    if (deprecatedSetting.userRemote !== void 0) {
      this.h.updateValue(
        deprecatedKey,
        void 0,
        4
        /* ConfigurationTarget.USER_REMOTE */
      );
      this.h.updateValue(
        key2,
        deprecatedSetting.userRemote.value,
        4
        /* ConfigurationTarget.USER_REMOTE */
      );
    }
    if (deprecatedSetting.workspace !== void 0) {
      this.h.updateValue(
        deprecatedKey,
        void 0,
        5
        /* ConfigurationTarget.WORKSPACE */
      );
      this.h.updateValue(
        key2,
        deprecatedSetting.workspace.value,
        5
        /* ConfigurationTarget.WORKSPACE */
      );
    }
    if (deprecatedSetting.workspaceFolder !== void 0) {
      this.h.updateValue(
        deprecatedKey,
        void 0,
        6
        /* ConfigurationTarget.WORKSPACE_FOLDER */
      );
      this.h.updateValue(
        key2,
        deprecatedSetting.workspaceFolder.value,
        6
        /* ConfigurationTarget.WORKSPACE_FOLDER */
      );
    }
  }
  s(lineHeight, outputFontSize) {
    const minimumLineHeight = 9;
    if (lineHeight === 0) {
      const editorOptions2 = this.h.getValue("editor");
      const fontInfo = $64.readFontInfo(this.targetWindow, $ED.createFromRawSettings(editorOptions2, $_1.getInstance(this.targetWindow).value));
      lineHeight = fontInfo.lineHeight;
    } else if (lineHeight < minimumLineHeight) {
      let fontSize = outputFontSize;
      if (fontSize === 0) {
        fontSize = this.h.getValue("editor.fontSize");
      }
      lineHeight = lineHeight * fontSize;
    }
    lineHeight = Math.round(lineHeight);
    if (lineHeight < minimumLineHeight) {
      lineHeight = minimumLineHeight;
    }
    return lineHeight;
  }
  t(e) {
    const cellStatusBarVisibility = e.affectsConfiguration($rM.showCellStatusBar);
    const cellToolbarLocation = e.affectsConfiguration($rM.cellToolbarLocation);
    const cellToolbarInteraction = e.affectsConfiguration($rM.cellToolbarVisibility);
    const compactView = e.affectsConfiguration($rM.compactView);
    const focusIndicator = e.affectsConfiguration($rM.focusIndicator);
    const insertToolbarPosition = e.affectsConfiguration($rM.insertToolbarLocation);
    const insertToolbarAlignment = e.affectsConfiguration($rM.experimentalInsertToolbarAlignment);
    const globalToolbar = e.affectsConfiguration($rM.globalToolbar);
    const stickyScrollEnabled = e.affectsConfiguration($rM.stickyScrollEnabled);
    const stickyScrollMode = e.affectsConfiguration($rM.stickyScrollMode);
    const consolidatedOutputButton = e.affectsConfiguration($rM.consolidatedOutputButton);
    const consolidatedRunButton = e.affectsConfiguration($rM.consolidatedRunButton);
    const showFoldingControls = e.affectsConfiguration($rM.showFoldingControls);
    const dragAndDropEnabled = e.affectsConfiguration($rM.dragAndDropEnabled);
    const fontSize = e.affectsConfiguration("editor.fontSize");
    const outputFontSize = e.affectsConfiguration($rM.outputFontSize);
    const markupFontSize = e.affectsConfiguration($rM.markupFontSize);
    const markdownLineHeight = e.affectsConfiguration($rM.markdownLineHeight);
    const fontFamily = e.affectsConfiguration("editor.fontFamily");
    const outputFontFamily = e.affectsConfiguration($rM.outputFontFamily);
    const editorOptionsCustomizations = e.affectsConfiguration($rM.cellEditorOptionsCustomizations);
    const interactiveWindowCollapseCodeCells = e.affectsConfiguration($rM.interactiveWindowCollapseCodeCells);
    const outputLineHeight = e.affectsConfiguration($rM.outputLineHeight);
    const outputScrolling = e.affectsConfiguration($rM.outputScrolling);
    const outputWordWrap = e.affectsConfiguration($rM.outputWordWrap);
    const outputLinkifyFilePaths = e.affectsConfiguration($rM.LinkifyOutputFilePaths);
    const minimalError = e.affectsConfiguration($rM.minimalErrorRendering);
    if (!cellStatusBarVisibility && !cellToolbarLocation && !cellToolbarInteraction && !compactView && !focusIndicator && !insertToolbarPosition && !insertToolbarAlignment && !globalToolbar && !stickyScrollEnabled && !stickyScrollMode && !consolidatedOutputButton && !consolidatedRunButton && !showFoldingControls && !dragAndDropEnabled && !fontSize && !outputFontSize && !markupFontSize && !markdownLineHeight && !fontFamily && !outputFontFamily && !editorOptionsCustomizations && !interactiveWindowCollapseCodeCells && !outputLineHeight && !outputScrolling && !outputWordWrap && !outputLinkifyFilePaths && !minimalError) {
      return;
    }
    let configuration2 = Object.assign({}, this.a);
    if (cellStatusBarVisibility) {
      configuration2.showCellStatusBar = this.h.getValue($rM.showCellStatusBar);
    }
    if (cellToolbarLocation) {
      configuration2.cellToolbarLocation = this.h.getValue($rM.cellToolbarLocation) ?? { "default": "right" };
    }
    if (cellToolbarInteraction && !this.g?.cellToolbarInteraction) {
      configuration2.cellToolbarInteraction = this.h.getValue($rM.cellToolbarVisibility);
    }
    if (focusIndicator) {
      configuration2.focusIndicator = this.z();
    }
    if (compactView) {
      const compactViewValue = this.h.getValue($rM.compactView) ?? true;
      configuration2 = Object.assign(configuration2, {
        ...compactViewValue ? compactConfigConstants : defaultConfigConstants
      });
      configuration2.compactView = compactViewValue;
    }
    if (insertToolbarAlignment) {
      configuration2.insertToolbarAlignment = this.w();
    }
    if (insertToolbarPosition) {
      configuration2.insertToolbarPosition = this.u(this.f);
    }
    if (globalToolbar && this.g?.globalToolbar === void 0) {
      configuration2.globalToolbar = this.h.getValue($rM.globalToolbar) ?? true;
    }
    if (stickyScrollEnabled && this.g?.stickyScrollEnabled === void 0) {
      configuration2.stickyScrollEnabled = this.h.getValue($rM.stickyScrollEnabled) ?? false;
    }
    if (stickyScrollMode) {
      configuration2.stickyScrollMode = this.h.getValue($rM.stickyScrollMode) ?? "flat";
    }
    if (consolidatedOutputButton) {
      configuration2.consolidatedOutputButton = this.h.getValue($rM.consolidatedOutputButton) ?? true;
    }
    if (consolidatedRunButton) {
      configuration2.consolidatedRunButton = this.h.getValue($rM.consolidatedRunButton) ?? true;
    }
    if (showFoldingControls) {
      configuration2.showFoldingControls = this.y();
    }
    if (dragAndDropEnabled) {
      configuration2.dragAndDropEnabled = this.h.getValue($rM.dragAndDropEnabled) ?? true;
    }
    if (fontSize) {
      configuration2.fontSize = this.h.getValue("editor.fontSize");
    }
    if (outputFontSize || fontSize) {
      configuration2.outputFontSize = this.h.getValue($rM.outputFontSize) || configuration2.fontSize;
    }
    if (markupFontSize) {
      configuration2.markupFontSize = this.h.getValue($rM.markupFontSize);
    }
    if (markdownLineHeight) {
      configuration2.markdownLineHeight = this.h.getValue($rM.markdownLineHeight);
    }
    if (outputFontFamily) {
      configuration2.outputFontFamily = this.h.getValue($rM.outputFontFamily);
    }
    if (editorOptionsCustomizations) {
      configuration2.editorOptionsCustomizations = this.h.getValue($rM.cellEditorOptionsCustomizations);
    }
    if (interactiveWindowCollapseCodeCells) {
      configuration2.interactiveWindowCollapseCodeCells = this.h.getValue($rM.interactiveWindowCollapseCodeCells);
    }
    if (outputLineHeight || fontSize || outputFontSize) {
      const lineHeight = this.h.getValue($rM.outputLineHeight);
      configuration2.outputLineHeight = this.s(lineHeight, configuration2.outputFontSize);
    }
    if (outputWordWrap) {
      configuration2.outputWordWrap = this.h.getValue($rM.outputWordWrap);
    }
    if (outputScrolling) {
      configuration2.outputScrolling = this.h.getValue($rM.outputScrolling);
    }
    if (outputLinkifyFilePaths) {
      configuration2.outputLinkifyFilePaths = this.h.getValue($rM.LinkifyOutputFilePaths);
    }
    if (minimalError) {
      configuration2.outputMinimalError = this.h.getValue($rM.minimalErrorRendering);
    }
    this.a = Object.freeze(configuration2);
    this.b.fire({
      cellStatusBarVisibility,
      cellToolbarLocation,
      cellToolbarInteraction,
      compactView,
      focusIndicator,
      insertToolbarPosition,
      insertToolbarAlignment,
      globalToolbar,
      stickyScrollEnabled,
      stickyScrollMode,
      showFoldingControls,
      consolidatedOutputButton,
      consolidatedRunButton,
      dragAndDropEnabled,
      fontSize,
      outputFontSize,
      markupFontSize,
      markdownLineHeight,
      fontFamily,
      outputFontFamily,
      editorOptionsCustomizations,
      interactiveWindowCollapseCodeCells,
      outputLineHeight,
      outputScrolling,
      outputWordWrap,
      outputLinkifyFilePaths,
      minimalError
    });
  }
  u(isReadOnly2) {
    return isReadOnly2 ? "hidden" : this.h.getValue($rM.insertToolbarLocation) ?? "both";
  }
  w() {
    return this.h.getValue($rM.experimentalInsertToolbarAlignment) ?? "center";
  }
  y() {
    return this.h.getValue($rM.showFoldingControls) ?? "mouseover";
  }
  z() {
    return this.h.getValue($rM.focusIndicator) ?? "gutter";
  }
  C() {
    return this.h.getValue($rM.stickyScrollMode) ?? "flat";
  }
  getCellCollapseDefault() {
    return this.a.interactiveWindowCollapseCodeCells === "never" ? {
      codeCell: {
        inputCollapsed: false
      }
    } : {
      codeCell: {
        inputCollapsed: true
      }
    };
  }
  getLayoutConfiguration() {
    return this.a;
  }
  getDisplayOptions() {
    return this.a;
  }
  getCellEditorContainerLeftMargin() {
    const { codeCellLeftMargin, cellRunGutter } = this.a;
    return codeCellLeftMargin + cellRunGutter;
  }
  computeCollapsedMarkdownCellHeight(viewType) {
    const { bottomToolbarGap } = this.computeBottomToolbarDimensions(viewType);
    return this.a.markdownCellTopMargin + this.a.collapsedIndicatorHeight + bottomToolbarGap + this.a.markdownCellBottomMargin;
  }
  computeBottomToolbarOffset(totalHeight, viewType) {
    const { bottomToolbarGap, bottomToolbarHeight } = this.computeBottomToolbarDimensions(viewType);
    return totalHeight - bottomToolbarGap - bottomToolbarHeight / 2;
  }
  computeCodeCellEditorWidth(outerWidth) {
    return outerWidth - (this.a.codeCellLeftMargin + this.a.cellRunGutter + this.a.cellRightMargin);
  }
  computeMarkdownCellEditorWidth(outerWidth) {
    return outerWidth - this.a.markdownCellGutter - this.a.markdownCellLeftMargin - this.a.cellRightMargin;
  }
  computeStatusBarHeight() {
    return this.a.cellStatusBarHeight;
  }
  D(compactView, insertToolbarPosition, insertToolbarAlignment, cellToolbar) {
    if (insertToolbarAlignment === "left" || cellToolbar !== "hidden") {
      return {
        bottomToolbarGap: 18,
        bottomToolbarHeight: 18
      };
    }
    if (insertToolbarPosition === "betweenCells" || insertToolbarPosition === "both") {
      return compactView ? {
        bottomToolbarGap: 12,
        bottomToolbarHeight: 20
      } : {
        bottomToolbarGap: 20,
        bottomToolbarHeight: 20
      };
    } else {
      return {
        bottomToolbarGap: 0,
        bottomToolbarHeight: 0
      };
    }
  }
  computeBottomToolbarDimensions(viewType) {
    const configuration2 = this.a;
    const cellToolbarPosition = this.computeCellToolbarLocation(viewType);
    const { bottomToolbarGap, bottomToolbarHeight } = this.D(configuration2.compactView, configuration2.insertToolbarPosition, configuration2.insertToolbarAlignment, cellToolbarPosition);
    return {
      bottomToolbarGap,
      bottomToolbarHeight
    };
  }
  computeCellToolbarLocation(viewType) {
    const cellToolbarLocation = this.a.cellToolbarLocation;
    if (typeof cellToolbarLocation === "string") {
      if (cellToolbarLocation === "left" || cellToolbarLocation === "right" || cellToolbarLocation === "hidden") {
        return cellToolbarLocation;
      }
    } else {
      if (viewType) {
        const notebookSpecificSetting = cellToolbarLocation[viewType] ?? cellToolbarLocation["default"];
        let cellToolbarLocationForCurrentView = "right";
        switch (notebookSpecificSetting) {
          case "left":
            cellToolbarLocationForCurrentView = "left";
            break;
          case "right":
            cellToolbarLocationForCurrentView = "right";
            break;
          case "hidden":
            cellToolbarLocationForCurrentView = "hidden";
            break;
          default:
            cellToolbarLocationForCurrentView = "right";
            break;
        }
        return cellToolbarLocationForCurrentView;
      }
    }
    return "right";
  }
  computeTopInsertToolbarHeight(viewType) {
    if (this.a.insertToolbarPosition === "betweenCells" || this.a.insertToolbarPosition === "both") {
      return SCROLLABLE_ELEMENT_PADDING_TOP;
    }
    const cellToolbarLocation = this.computeCellToolbarLocation(viewType);
    if (cellToolbarLocation === "left" || cellToolbarLocation === "right") {
      return SCROLLABLE_ELEMENT_PADDING_TOP;
    }
    return 0;
  }
  computeEditorPadding(internalMetadata, cellUri) {
    return {
      top: this.c,
      bottom: this.F(internalMetadata, cellUri) ? this.a.editorBottomPadding : this.a.editorBottomPaddingWithoutStatusBar
    };
  }
  computeEditorStatusbarHeight(internalMetadata, cellUri) {
    return this.F(internalMetadata, cellUri) ? this.computeStatusBarHeight() : 0;
  }
  F(internalMetadata, cellUri) {
    const exe = this.j.getCellExecution(cellUri);
    if (this.a.showCellStatusBar === "visible") {
      return true;
    } else if (this.a.showCellStatusBar === "visibleAfterExecute") {
      return typeof internalMetadata.lastRunSuccess === "boolean" || exe !== void 0;
    } else {
      return false;
    }
  }
  computeWebviewOptions() {
    return {
      outputNodePadding: this.a.cellOutputPadding,
      outputNodeLeftPadding: this.a.cellOutputPadding,
      previewNodePadding: this.a.markdownPreviewPadding,
      markdownLeftMargin: this.a.markdownCellGutter + this.a.markdownCellLeftMargin,
      leftMargin: this.a.codeCellLeftMargin,
      rightMargin: this.a.cellRightMargin,
      runGutter: this.a.cellRunGutter,
      dragAndDropEnabled: this.a.dragAndDropEnabled,
      fontSize: this.a.fontSize,
      outputFontSize: this.a.outputFontSize,
      outputFontFamily: this.a.outputFontFamily,
      markupFontSize: this.a.markupFontSize,
      markdownLineHeight: this.a.markdownLineHeight,
      outputLineHeight: this.a.outputLineHeight,
      outputScrolling: this.a.outputScrolling,
      outputWordWrap: this.a.outputWordWrap,
      outputLineLimit: this.a.outputLineLimit,
      outputLinkifyFilePaths: this.a.outputLinkifyFilePaths,
      minimalError: this.a.outputMinimalError
    };
  }
  computeDiffWebviewOptions() {
    return {
      outputNodePadding: this.a.cellOutputPadding,
      outputNodeLeftPadding: 0,
      previewNodePadding: this.a.markdownPreviewPadding,
      markdownLeftMargin: 0,
      leftMargin: 32,
      rightMargin: 0,
      runGutter: 0,
      dragAndDropEnabled: false,
      fontSize: this.a.fontSize,
      outputFontSize: this.a.outputFontSize,
      outputFontFamily: this.a.outputFontFamily,
      markupFontSize: this.a.markupFontSize,
      markdownLineHeight: this.a.markdownLineHeight,
      outputLineHeight: this.a.outputLineHeight,
      outputScrolling: this.a.outputScrolling,
      outputWordWrap: this.a.outputWordWrap,
      outputLineLimit: this.a.outputLineLimit,
      outputLinkifyFilePaths: false,
      minimalError: false
    };
  }
  computeIndicatorPosition(totalHeight, foldHintHeight, viewType) {
    const { bottomToolbarGap } = this.computeBottomToolbarDimensions(viewType);
    return {
      bottomIndicatorTop: totalHeight - bottomToolbarGap - this.a.cellBottomMargin - foldHintHeight,
      verticalIndicatorHeight: totalHeight - bottomToolbarGap - foldHintHeight
    };
  }
};
$xrb = __decorate([
  __param(3, $kl),
  __param(4, $wL),
  __param(5, $U5)
], $xrb);

// out-build/vs/workbench/contrib/notebook/browser/viewModel/cellEditorOptions.js
var $xLb = class _$xLb extends $3c {
  static {
    this.a = {
      scrollBeyondLastLine: false,
      scrollbar: {
        verticalScrollbarSize: 14,
        horizontal: "auto",
        useShadows: true,
        verticalHasArrows: false,
        horizontalHasArrows: false,
        alwaysConsumeMouseWheel: false
      },
      renderLineHighlightOnlyWhenFocus: true,
      overviewRulerLanes: 0,
      lineDecorationsWidth: 0,
      folding: true,
      fixedOverflowWidgets: true,
      minimap: { enabled: false },
      renderValidationDecorations: "on",
      lineNumbersMinChars: 3
    };
  }
  get value() {
    return this.f;
  }
  constructor(notebookEditor, notebookOptions, configurationService, language) {
    super();
    this.notebookEditor = notebookEditor;
    this.notebookOptions = notebookOptions;
    this.configurationService = configurationService;
    this.language = language;
    this.b = this.B(new $2c());
    this.c = this.B(new $ze());
    this.onDidChange = this.c.event;
    this.B(configurationService.onDidChangeConfiguration((e) => {
      if (e.affectsConfiguration("editor") || e.affectsConfiguration("notebook")) {
        this.g();
      }
    }));
    this.B(notebookOptions.onDidChangeOptions((e) => {
      if (e.cellStatusBarVisibility || e.editorTopPadding || e.editorOptionsCustomizations) {
        this.g();
      }
    }));
    this.B(this.notebookEditor.onDidChangeModel(() => {
      this.b.clear();
      if (this.notebookEditor.hasModel()) {
        this.b.add(this.notebookEditor.onDidChangeOptions(() => {
          this.g();
        }));
        this.g();
      }
    }));
    if (this.notebookEditor.hasModel()) {
      this.b.add(this.notebookEditor.onDidChangeOptions(() => {
        this.g();
      }));
    }
    this.f = this.h();
  }
  g() {
    this.f = this.h();
    this.c.fire();
  }
  h() {
    const editorOptions2 = $Lv(this.configurationService.getValue("editor", { overrideIdentifier: this.language }));
    const editorOptionsOverrideRaw = this.notebookOptions.getDisplayOptions().editorOptionsCustomizations;
    const editorOptionsOverride = {};
    if (editorOptionsOverrideRaw) {
      for (const key2 in editorOptionsOverrideRaw) {
        if (key2.indexOf("editor.") === 0) {
          editorOptionsOverride[key2.substring(7)] = editorOptionsOverrideRaw[key2];
        }
      }
    }
    const computed = Object.freeze({
      ...editorOptions2,
      ..._$xLb.a,
      ...editorOptionsOverride,
      ...{ padding: { top: 12, bottom: 12 } },
      readOnly: this.notebookEditor.isReadOnly
    });
    return computed;
  }
};

// out-build/vs/workbench/contrib/notebook/browser/viewModel/OutlineEntry.js
var $ELb = class {
  get icon() {
    if (this.symbolKind) {
      return SymbolKinds.toIcon(this.symbolKind);
    }
    return this.isExecuting && this.isPaused ? $RKb : this.isExecuting ? ThemeIcon.modify($RKb, "spin") : this.cell.cellKind === CellKind.Markup ? $6l.markdown : $6l.code;
  }
  constructor(index, level, cell, label3, isExecuting, isPaused, range, symbolKind) {
    this.index = index;
    this.level = level;
    this.cell = cell;
    this.label = label3;
    this.isExecuting = isExecuting;
    this.isPaused = isPaused;
    this.range = range;
    this.symbolKind = symbolKind;
    this.b = [];
  }
  addChild(entry) {
    this.b.push(entry);
    entry.c = this;
  }
  get parent() {
    return this.c;
  }
  get children() {
    return this.b;
  }
  get markerInfo() {
    return this.d;
  }
  get position() {
    if (this.range) {
      return { startLineNumber: this.range.startLineNumber, startColumn: this.range.startColumn };
    }
    return void 0;
  }
  updateMarkers(markerService) {
    if (this.cell.cellKind === CellKind.Code) {
      const marker = markerService.read({ resource: this.cell.uri, severities: MarkerSeverity.Error | MarkerSeverity.Warning });
      if (marker.length === 0) {
        this.d = void 0;
      } else {
        const topSev = marker.find((a) => a.severity === MarkerSeverity.Error)?.severity ?? MarkerSeverity.Warning;
        this.d = { topSev, count: marker.length };
      }
    } else {
      let topChild;
      for (const child of this.children) {
        child.updateMarkers(markerService);
        if (child.markerInfo) {
          topChild = !topChild ? child.markerInfo.topSev : Math.max(child.markerInfo.topSev, topChild);
        }
      }
      this.d = topChild && { topSev: topChild, count: 0 };
    }
  }
  clearMarkers() {
    this.d = void 0;
    for (const child of this.children) {
      child.clearMarkers();
    }
  }
  find(cell, parents) {
    if (cell.id === this.cell.id) {
      return this;
    }
    parents.push(this);
    for (const child of this.children) {
      const result = child.find(cell, parents);
      if (result) {
        return result;
      }
    }
    parents.pop();
    return void 0;
  }
  asFlatList(bucket) {
    bucket.push(this);
    for (const child of this.children) {
      child.asFlatList(bucket);
    }
  }
};

// out-build/vs/workbench/contrib/notebook/browser/viewModel/notebookOutlineEntryFactory.js
var NotebookOutlineConstants;
(function(NotebookOutlineConstants2) {
  NotebookOutlineConstants2[NotebookOutlineConstants2["NonHeaderOutlineLevel"] = 7] = "NonHeaderOutlineLevel";
})(NotebookOutlineConstants || (NotebookOutlineConstants = {}));
function getMarkdownHeadersInCellFallbackToHtmlTags(fullContent) {
  const headers = Array.from($hLb(fullContent));
  if (headers.length) {
    return headers;
  }
  const match = fullContent.match(/<h([1-6]).*>(.*)<\/h\1>/i);
  if (match) {
    const level = parseInt(match[1]);
    const text2 = match[2].trim();
    headers.push({ depth: level, text: text2 });
  }
  return headers;
}
var $FLb = $Qk("INotebookOutlineEntryFactory");
var $GLb = class $GLb2 {
  constructor(c, d, e) {
    this.c = c;
    this.d = d;
    this.e = e;
    this.a = {};
    this.b = /* @__PURE__ */ new WeakMap();
  }
  getOutlineEntries(cell, index) {
    const entries2 = [];
    const isMarkdown = cell.cellKind === CellKind.Markup;
    let content = getCellFirstNonEmptyLine(cell);
    let hasHeader = false;
    if (isMarkdown) {
      const fullContent = cell.getText().substring(0, 1e4);
      const cache2 = this.b.get(cell);
      const headers = cache2?.alternativeId === cell.getAlternativeId() ? cache2.headers : Array.from(getMarkdownHeadersInCellFallbackToHtmlTags(fullContent));
      this.b.set(cell, { alternativeId: cell.getAlternativeId(), headers });
      for (const { depth, text: text2 } of headers) {
        hasHeader = true;
        entries2.push(new $ELb(index++, depth, cell, text2, false, false));
      }
      if (!hasHeader) {
        content = $G1({ value: content });
      }
    }
    if (!hasHeader) {
      const exeState = !isMarkdown && this.c.getCellExecution(cell.uri);
      let preview = content.trim();
      if (!isMarkdown) {
        const cached = this.a[cell.id];
        if (cached) {
          entries2.push(new $ELb(index++, 7, cell, preview, !!exeState, exeState ? exeState.isPaused : false));
          cached.forEach((entry) => {
            entries2.push(new $ELb(index++, entry.level, cell, entry.name, false, false, entry.range, entry.kind));
          });
        }
      }
      if (entries2.length === 0) {
        if (preview.length === 0) {
          preview = localize(8608, null);
        }
        entries2.push(new $ELb(index++, 7, cell, preview, !!exeState, exeState ? exeState.isPaused : false));
      }
    }
    return entries2;
  }
  async cacheSymbols(cell, cancelToken) {
    if (cell.cellKind === CellKind.Markup) {
      return;
    }
    const ref = await this.e.createModelReference(cell.uri);
    try {
      const textModel = ref.object.textEditorModel;
      const outlineModel = await this.d.getOrCreate(textModel, cancelToken);
      const entries2 = createOutlineEntries(outlineModel.getTopLevelSymbols(), 8);
      this.a[cell.id] = entries2;
    } finally {
      ref.dispose();
    }
  }
};
$GLb = __decorate([
  __param(0, $wL),
  __param(1, $phb),
  __param(2, $oG)
], $GLb);
function createOutlineEntries(symbols, level) {
  const entries2 = [];
  symbols.forEach((symbol) => {
    entries2.push({ name: symbol.name, range: symbol.range, level, kind: symbol.kind });
    if (symbol.children) {
      entries2.push(...createOutlineEntries(symbol.children, level + 1));
    }
  });
  return entries2;
}
function getCellFirstNonEmptyLine(cell) {
  const textBuffer = cell.textBuffer;
  for (let i2 = 0; i2 < textBuffer.getLineCount(); i2++) {
    const firstNonWhitespace = textBuffer.getLineFirstNonWhitespaceColumn(i2 + 1);
    const lineLength = textBuffer.getLineLength(i2 + 1);
    if (firstNonWhitespace < lineLength) {
      return textBuffer.getLineContent(i2 + 1);
    }
  }
  return cell.getText().substring(0, 100);
}

// out-build/vs/workbench/contrib/notebook/browser/viewModel/notebookOutlineDataSource.js
var $HLb = class $HLb2 {
  constructor(g, h3, j, k) {
    this.g = g;
    this.h = h3;
    this.j = j;
    this.k = k;
    this.a = new $2c();
    this.b = new $ze();
    this.onDidChange = this.b.event;
    this.d = [];
    this.recomputeState();
  }
  get activeElement() {
    return this.f;
  }
  get entries() {
    return this.d;
  }
  get isEmpty() {
    return this.d.length === 0;
  }
  get uri() {
    return this.c;
  }
  async computeFullSymbols(cancelToken) {
    const notebookEditorWidget = this.g;
    const notebookCells = notebookEditorWidget?.getViewModel()?.viewCells.filter((cell) => cell.cellKind === CellKind.Code);
    if (notebookCells) {
      const promises = [];
      for (const cell of notebookCells.slice(0, 50)) {
        promises.push(this.k.cacheSymbols(cell, cancelToken));
      }
      await Promise.allSettled(promises);
    }
    this.recomputeState();
  }
  recomputeState() {
    this.a.clear();
    this.f = void 0;
    this.c = void 0;
    if (!this.g.hasModel()) {
      return;
    }
    this.c = this.g.textModel.uri;
    const notebookEditorWidget = this.g;
    if (notebookEditorWidget.getLength() === 0) {
      return;
    }
    const notebookCells = notebookEditorWidget.getViewModel().viewCells;
    const entries2 = [];
    for (const cell of notebookCells) {
      entries2.push(...this.k.getOutlineEntries(cell, entries2.length));
    }
    if (entries2.length > 0) {
      const result = [entries2[0]];
      const parentStack = [entries2[0]];
      for (let i2 = 1; i2 < entries2.length; i2++) {
        const entry = entries2[i2];
        while (true) {
          const len = parentStack.length;
          if (len === 0) {
            result.push(entry);
            parentStack.push(entry);
            break;
          } else {
            const parentCandidate = parentStack[len - 1];
            if (parentCandidate.level < entry.level) {
              parentCandidate.addChild(entry);
              parentStack.push(entry);
              break;
            } else {
              parentStack.pop();
            }
          }
        }
      }
      this.d = result;
    }
    const markerServiceListener = new $4c();
    this.a.add(markerServiceListener);
    const updateMarkerUpdater = () => {
      if (notebookEditorWidget.isDisposed) {
        return;
      }
      const doUpdateMarker = (clear) => {
        for (const entry of this.d) {
          if (clear) {
            entry.clearMarkers();
          } else {
            entry.updateMarkers(this.h);
          }
        }
      };
      const problem = this.j.getValue("problems.visibility");
      if (problem === void 0) {
        return;
      }
      const config = this.j.getValue(
        "outline.problems.enabled"
        /* OutlineConfigKeys.problemsEnabled */
      );
      if (problem && config) {
        markerServiceListener.value = this.h.onMarkerChanged((e) => {
          if (notebookEditorWidget.isDisposed) {
            console.error("notebook editor is disposed");
            return;
          }
          if (e.some((uri) => notebookEditorWidget.getCellsInRange().some((cell) => $oh(cell.uri, uri)))) {
            doUpdateMarker(false);
            this.b.fire({});
          }
        });
        doUpdateMarker(false);
      } else {
        markerServiceListener.clear();
        doUpdateMarker(true);
      }
    };
    updateMarkerUpdater();
    this.a.add(this.j.onDidChangeConfiguration((e) => {
      if (e.affectsConfiguration("problems.visibility") || e.affectsConfiguration(
        "outline.problems.enabled"
        /* OutlineConfigKeys.problemsEnabled */
      )) {
        updateMarkerUpdater();
        this.b.fire({});
      }
    }));
    const { changeEventTriggered } = this.recomputeActive();
    if (!changeEventTriggered) {
      this.b.fire({});
    }
  }
  recomputeActive() {
    let newActive;
    const notebookEditorWidget = this.g;
    if (notebookEditorWidget) {
      if (notebookEditorWidget.hasModel() && notebookEditorWidget.getLength() > 0) {
        const cell = notebookEditorWidget.cellAt(notebookEditorWidget.getFocus().start);
        if (cell) {
          for (const entry of this.d) {
            newActive = entry.find(cell, []);
            if (newActive) {
              break;
            }
          }
        }
      }
    }
    if (newActive !== this.f) {
      this.f = newActive;
      this.b.fire({ affectOnlyActiveElement: true });
      return { changeEventTriggered: true };
    }
    return { changeEventTriggered: false };
  }
  dispose() {
    this.d.length = 0;
    this.f = void 0;
    this.a.dispose();
  }
};
$HLb = __decorate([
  __param(1, $DE),
  __param(2, $kl),
  __param(3, $FLb)
], $HLb);

// out-build/vs/workbench/contrib/notebook/browser/viewModel/notebookOutlineDataSourceFactory.js
var NotebookCellOutlineDataSourceReferenceCollection = class NotebookCellOutlineDataSourceReferenceCollection2 extends $8c {
  constructor(f) {
    super();
    this.f = f;
  }
  b(_key, editor) {
    return this.f.createInstance($HLb, editor);
  }
  c(_key, object) {
    object.dispose();
  }
};
NotebookCellOutlineDataSourceReferenceCollection = __decorate([
  __param(0, $Pk)
], NotebookCellOutlineDataSourceReferenceCollection);
var $OLb = $Qk("INotebookCellOutlineDataSourceFactory");
var $PLb = class $PLb2 {
  constructor(instantiationService) {
    this.a = instantiationService.createInstance(NotebookCellOutlineDataSourceReferenceCollection);
  }
  getOrCreate(editor) {
    return this.a.acquire(editor.getId(), editor);
  }
};
$PLb = __decorate([
  __param(0, $Pk)
], $PLb);

// out-build/vs/workbench/contrib/notebook/browser/viewParts/notebookEditorStickyScroll.js
var $5Lb_1;
var $4Lb = class _$4Lb extends $3c {
  constructor(element, foldingIcon, header, entry, notebookEditor) {
    super();
    this.element = element;
    this.foldingIcon = foldingIcon;
    this.header = header;
    this.entry = entry;
    this.notebookEditor = notebookEditor;
    this.B($_i(this.header, $7j.CLICK || EventType.Tap, () => {
      this.b();
    }));
    this.B($_i(this.foldingIcon.domNode, $7j.CLICK || EventType.Tap, () => {
      if (this.entry.cell.cellKind === CellKind.Markup) {
        const currentFoldingState = this.entry.cell.foldingState;
        this.a(currentFoldingState);
      }
    }));
  }
  a(currentState) {
    const foldingController = this.notebookEditor.getContribution($iLb.id);
    const index = this.entry.index;
    const headerLevel = this.entry.level;
    const newFoldingState = currentState === 2 ? 1 : 2;
    foldingController.setFoldingStateDown(index, newFoldingState, headerLevel);
    this.b();
  }
  b() {
    this.notebookEditor.focusNotebookCell(this.entry.cell, "container");
    const cellScrollTop = this.notebookEditor.getAbsoluteTopOfElement(this.entry.cell);
    const parentCount = _$4Lb.getParentCount(this.entry);
    this.notebookEditor.setScrollTop(cellScrollTop - (parentCount + 1.1) * 22);
  }
  static getParentCount(entry) {
    let count = 0;
    while (entry.parent) {
      count++;
      entry = entry.parent;
    }
    return count;
  }
};
var StickyFoldingIcon2 = class {
  constructor(isCollapsed, dimension) {
    this.isCollapsed = isCollapsed;
    this.dimension = dimension;
    this.domNode = document.createElement("div");
    this.domNode.style.width = `${dimension}px`;
    this.domNode.style.height = `${dimension}px`;
    this.domNode.className = ThemeIcon.asClassName(isCollapsed ? $3gb : $2gb);
  }
  setVisible(visible) {
    this.domNode.style.cursor = visible ? "pointer" : "default";
    this.domNode.style.opacity = visible ? "1" : "0";
  }
};
var $5Lb = $5Lb_1 = class $5Lb2 extends $3c {
  getDomNode() {
    return this.m;
  }
  getCurrentStickyHeight() {
    let height = 0;
    this.b.forEach((value) => {
      if (value.rendered) {
        height += 22;
      }
    });
    return height;
  }
  h(newStickyLines) {
    this.b = newStickyLines;
  }
  j(mapA, mapB) {
    if (mapA.size !== mapB.size) {
      return false;
    }
    for (const [key2, value] of mapA) {
      const otherValue = mapB.get(key2);
      if (!otherValue || value.rendered !== otherValue.rendered) {
        return false;
      }
    }
    return true;
  }
  constructor(m, n, r2, s, t, u) {
    super();
    this.m = m;
    this.n = n;
    this.r = r2;
    this.s = s;
    this.t = t;
    this.u = u;
    this.a = new $2c();
    this.b = /* @__PURE__ */ new Map();
    this.c = this.B(new $ze());
    this.onDidChangeNotebookStickyScroll = this.c.event;
    this.g = this.B(new $2c());
    if (this.n.notebookOptions.getDisplayOptions().stickyScrollEnabled) {
      this.z();
    }
    this.B(this.n.notebookOptions.onDidChangeOptions((e) => {
      if (e.stickyScrollEnabled || e.stickyScrollMode) {
        this.y(e);
      }
    }));
    this.B($_i(this.m, $7j.CONTEXT_MENU, async (event) => {
      this.w(event);
    }));
  }
  w(e) {
    const event = new $lf(getWindow(this.m), e);
    const selectedElement = event.target.parentElement;
    const selectedOutlineEntry = Array.from(this.b.values()).find((entry) => entry.line.element.contains(selectedElement))?.line.entry;
    if (!selectedOutlineEntry) {
      return;
    }
    const args2 = {
      outlineEntry: selectedOutlineEntry,
      notebookEditor: this.n
    };
    this.t.showContextMenu({
      menuId: $bJ.NotebookStickyScrollContext,
      getAnchor: () => event,
      menuActionOptions: { shouldForwardArgs: true, arg: args2 }
    });
  }
  y(e) {
    if (e.stickyScrollEnabled) {
      if (this.n.notebookOptions.getDisplayOptions().stickyScrollEnabled) {
        this.z();
      } else {
        this.a.clear();
        this.f?.dispose();
        this.G();
        $$i(this.m);
        this.D();
      }
    } else if (e.stickyScrollMode && this.n.notebookOptions.getDisplayOptions().stickyScrollEnabled && this.f?.object) {
      this.C($6Lb(this.n, this.r, this.f?.object?.entries, this.getCurrentStickyHeight()));
    }
  }
  z() {
    const { object: notebookCellOutline } = this.f = this.u.invokeFunction((accessor) => accessor.get($OLb).getOrCreate(this.n));
    this.B(this.f);
    this.C($6Lb(this.n, this.r, notebookCellOutline.entries, this.getCurrentStickyHeight()));
    this.a.add(notebookCellOutline.onDidChange(() => {
      const recompute = $6Lb(this.n, this.r, notebookCellOutline.entries, this.getCurrentStickyHeight());
      if (!this.j(recompute, this.b)) {
        this.C(recompute);
      }
    }));
    this.a.add(this.n.onDidAttachViewModel(() => {
      this.C($6Lb(this.n, this.r, notebookCellOutline.entries, this.getCurrentStickyHeight()));
    }));
    this.a.add(this.n.onDidScroll(() => {
      const d = new $Sh(100);
      d.trigger(() => {
        d.dispose();
        const recompute = $6Lb(this.n, this.r, notebookCellOutline.entries, this.getCurrentStickyHeight());
        if (!this.j(recompute, this.b)) {
          this.C(recompute);
        }
      });
    }));
  }
  // take in an cell index, and get the corresponding outline entry
  static getVisibleOutlineEntry(visibleIndex, notebookOutlineEntries) {
    let left = 0;
    let right = notebookOutlineEntries.length - 1;
    let bucket = -1;
    while (left <= right) {
      const mid = Math.floor((left + right) / 2);
      if (notebookOutlineEntries[mid].index === visibleIndex) {
        bucket = mid;
        break;
      } else if (notebookOutlineEntries[mid].index < visibleIndex) {
        bucket = mid;
        left = mid + 1;
      } else {
        right = mid - 1;
      }
    }
    if (bucket !== -1) {
      const rootEntry = notebookOutlineEntries[bucket];
      const flatList = [];
      rootEntry.asFlatList(flatList);
      return flatList.find((entry) => entry.index === visibleIndex);
    }
    return void 0;
  }
  C(newMap) {
    $$i(this.m);
    this.G();
    this.F(newMap, this.m);
    const oldStickyHeight = this.getCurrentStickyHeight();
    this.h(newMap);
    const sizeDelta = this.getCurrentStickyHeight() - oldStickyHeight;
    if (sizeDelta !== 0) {
      this.c.fire(sizeDelta);
      const d = this.g.add($jj(getWindow(this.getDomNode()), () => {
        this.s(sizeDelta);
        this.D();
        this.g.delete(d);
      }));
    } else {
      this.D();
    }
  }
  D() {
    const hasSticky = this.getCurrentStickyHeight() > 0;
    if (!hasSticky) {
      this.m.style.display = "none";
    } else {
      this.m.style.display = "block";
    }
  }
  static computeStickyHeight(entry) {
    let height = 0;
    if (entry.cell.cellKind === CellKind.Markup && entry.level < 7) {
      height += 22;
    }
    while (entry.parent) {
      height += 22;
      entry = entry.parent;
    }
    return height;
  }
  static checkCollapsedStickyLines(entry, numLinesToRender, notebookEditor) {
    let currentEntry = entry;
    const newMap = /* @__PURE__ */ new Map();
    const elementsToRender = [];
    while (currentEntry) {
      if (currentEntry.level >= 7) {
        currentEntry = currentEntry.parent;
        continue;
      }
      const lineToRender = $5Lb_1.createStickyElement(currentEntry, notebookEditor);
      newMap.set(currentEntry, { line: lineToRender, rendered: false });
      elementsToRender.unshift(lineToRender);
      currentEntry = currentEntry.parent;
    }
    for (let i2 = 0; i2 < elementsToRender.length; i2++) {
      if (i2 >= numLinesToRender) {
        break;
      }
      newMap.set(elementsToRender[i2].entry, { line: elementsToRender[i2], rendered: true });
    }
    return newMap;
  }
  F(stickyMap, containerElement) {
    const reversedEntries = Array.from(stickyMap.entries()).reverse();
    for (const [, value] of reversedEntries) {
      if (!value.rendered) {
        continue;
      }
      containerElement.append(value.line.element);
    }
  }
  static createStickyElement(entry, notebookEditor) {
    const stickyElement = document.createElement("div");
    stickyElement.classList.add("notebook-sticky-scroll-element");
    const indentMode = notebookEditor.notebookOptions.getLayoutConfiguration().stickyScrollMode;
    if (indentMode === "indented") {
      stickyElement.style.paddingLeft = $4Lb.getParentCount(entry) * 10 + "px";
    }
    let isCollapsed = false;
    if (entry.cell.cellKind === CellKind.Markup) {
      isCollapsed = entry.cell.foldingState === 2;
    }
    const stickyFoldingIcon = new StickyFoldingIcon2(isCollapsed, 16);
    stickyFoldingIcon.domNode.classList.add("notebook-sticky-scroll-folding-icon");
    stickyFoldingIcon.setVisible(true);
    const stickyHeader = document.createElement("div");
    stickyHeader.classList.add("notebook-sticky-scroll-header");
    stickyHeader.innerText = entry.label;
    stickyElement.append(stickyFoldingIcon.domNode, stickyHeader);
    return new $4Lb(stickyElement, stickyFoldingIcon, stickyHeader, entry, notebookEditor);
  }
  G() {
    this.b.forEach((value) => {
      value.line.dispose();
    });
  }
  dispose() {
    this.a.dispose();
    this.G();
    this.f?.dispose();
    super.dispose();
  }
};
$5Lb = $5Lb_1 = __decorate([
  __param(4, $50),
  __param(5, $Pk)
], $5Lb);
function $6Lb(notebookEditor, notebookCellList, notebookOutlineEntries, renderedStickyHeight) {
  const editorScrollTop = notebookEditor.scrollTop - renderedStickyHeight;
  const visibleRange = notebookEditor.visibleRanges[0];
  if (!visibleRange) {
    return /* @__PURE__ */ new Map();
  }
  if (visibleRange.start === 0) {
    const firstCell = notebookEditor.cellAt(0);
    const firstCellEntry = $5Lb.getVisibleOutlineEntry(0, notebookOutlineEntries);
    if (firstCell && firstCellEntry && firstCell.cellKind === CellKind.Markup && firstCellEntry.level < 7) {
      if (notebookEditor.scrollTop > 22) {
        const newMap2 = $5Lb.checkCollapsedStickyLines(firstCellEntry, 100, notebookEditor);
        return newMap2;
      }
    }
  }
  let cell;
  let cellEntry;
  const startIndex = visibleRange.start - 1;
  for (let currentIndex = startIndex; currentIndex < visibleRange.end; currentIndex++) {
    cell = notebookEditor.cellAt(currentIndex);
    if (!cell) {
      return /* @__PURE__ */ new Map();
    }
    cellEntry = $5Lb.getVisibleOutlineEntry(currentIndex, notebookOutlineEntries);
    if (!cellEntry) {
      continue;
    }
    const nextCell = notebookEditor.cellAt(currentIndex + 1);
    if (!nextCell) {
      const sectionBottom2 = notebookEditor.getLayoutInfo().scrollHeight;
      const linesToRender2 = Math.floor(sectionBottom2 / 22);
      const newMap2 = $5Lb.checkCollapsedStickyLines(cellEntry, linesToRender2, notebookEditor);
      return newMap2;
    }
    const nextCellEntry = $5Lb.getVisibleOutlineEntry(currentIndex + 1, notebookOutlineEntries);
    if (!nextCellEntry) {
      continue;
    }
    if (nextCell.cellKind === CellKind.Markup && nextCellEntry.level < 7) {
      const sectionBottom2 = notebookCellList.getCellViewScrollTop(nextCell);
      const currentSectionStickyHeight = $5Lb.computeStickyHeight(cellEntry);
      const nextSectionStickyHeight = $5Lb.computeStickyHeight(nextCellEntry);
      if (editorScrollTop + currentSectionStickyHeight < sectionBottom2) {
        const linesToRender2 = Math.floor((sectionBottom2 - editorScrollTop) / 22);
        const newMap2 = $5Lb.checkCollapsedStickyLines(cellEntry, linesToRender2, notebookEditor);
        return newMap2;
      } else if (nextSectionStickyHeight >= currentSectionStickyHeight) {
        const newMap2 = $5Lb.checkCollapsedStickyLines(nextCellEntry, 100, notebookEditor);
        return newMap2;
      } else if (nextSectionStickyHeight < currentSectionStickyHeight) {
        const availableSpace = sectionBottom2 - editorScrollTop;
        if (availableSpace >= nextSectionStickyHeight) {
          const linesToRender2 = Math.floor(availableSpace / 22);
          const newMap2 = $5Lb.checkCollapsedStickyLines(cellEntry, linesToRender2, notebookEditor);
          return newMap2;
        } else {
          const newMap2 = $5Lb.checkCollapsedStickyLines(nextCellEntry, 100, notebookEditor);
          return newMap2;
        }
      }
    }
  }
  const sectionBottom = notebookEditor.getLayoutInfo().scrollHeight;
  const linesToRender = Math.floor((sectionBottom - editorScrollTop) / 22);
  const newMap = $5Lb.checkCollapsedStickyLines(cellEntry, linesToRender, notebookEditor);
  return newMap;
}

// out-build/vs/workbench/contrib/webview/browser/webview.contribution.js
var PRIORITY = 100;
function overrideCommandForWebview(command4, f) {
  command4?.addImplementation(PRIORITY, "webview", (accessor) => {
    const webviewService = accessor.get($Crb);
    const webview = webviewService.activeWebview;
    if (webview?.isFocused) {
      f(webview);
      return true;
    }
    if ($Lj()?.classList.contains("action-menu-item")) {
      const editorService = accessor.get($mJ);
      if (editorService.activeEditor instanceof $8Lb) {
        f(editorService.activeEditor.webview);
        return true;
      }
    }
    return false;
  });
}
overrideCommandForWebview($05, (webview) => webview.undo());
overrideCommandForWebview($$5, (webview) => webview.redo());
overrideCommandForWebview($_5, (webview) => webview.selectAll());
overrideCommandForWebview($kab, (webview) => webview.copy());
overrideCommandForWebview($lab, (webview) => webview.paste());
overrideCommandForWebview($jab, (webview) => webview.cut());
var $9Lb = "preventDefaultContextMenuItems";
if ($jab) {
  $dJ.appendMenuItem($bJ.WebviewContext, {
    command: {
      id: $jab.id,
      title: localize(11794, null)
    },
    group: "5_cutcopypaste",
    order: 1,
    when: $7m.not($9Lb)
  });
}
if ($kab) {
  $dJ.appendMenuItem($bJ.WebviewContext, {
    command: {
      id: $kab.id,
      title: localize(11795, null)
    },
    group: "5_cutcopypaste",
    order: 2,
    when: $7m.not($9Lb)
  });
}
if ($lab) {
  $dJ.appendMenuItem($bJ.WebviewContext, {
    command: {
      id: $lab.id,
      title: localize(11796, null)
    },
    group: "5_cutcopypaste",
    order: 3,
    when: $7m.not($9Lb)
  });
}

// out-build/vs/workbench/contrib/notebook/browser/notebookAccessibilityProvider.js
var $0Lb = class $0Lb2 extends $3c {
  constructor(c, f, g, h3, j, m) {
    super();
    this.c = c;
    this.f = f;
    this.g = g;
    this.h = h3;
    this.j = j;
    this.m = m;
    this.a = new $ze();
    this.b = this.a.event;
    this.B(Event2.debounce(this.g.onDidChangeExecution, (last, e) => this.u(last, e), 100)((updates) => {
      if (!updates.length) {
        return;
      }
      const viewModel = this.c();
      if (viewModel) {
        for (const update of updates) {
          const cellModel = viewModel.getCellByHandle(update.cellHandle);
          if (cellModel) {
            this.a.fire(cellModel);
          }
        }
        const lastUpdate = updates[updates.length - 1];
        if (this.n(lastUpdate.state)) {
          const cell = viewModel.getCellByHandle(lastUpdate.cellHandle);
          if (cell && cell.outputsViewModels.length) {
            const text2 = $4Kb(viewModel.notebookDocument, cell, true);
            $$Z(text2);
          }
        }
      }
    }, this));
  }
  n(state) {
    return state === void 0 && this.f && this.m.isScreenReaderOptimized() && this.j.getValue("accessibility.replEditor.readLastExecutionOutput");
  }
  get verbositySettingId() {
    return this.f ? "accessibility.verbosity.replEditor" : "accessibility.verbosity.notebook";
  }
  getAriaLabel(element) {
    const event = Event2.filter(this.b, (e) => e === element);
    return $Dd(this, event, () => {
      const viewModel = this.c();
      if (!viewModel) {
        return "";
      }
      const index = viewModel.getCellIndex(element);
      if (index >= 0) {
        return this.s(element);
      }
      return "";
    });
  }
  r(executionLabel, cellKind) {
    return this.f ? `cell${executionLabel}` : `${cellKind === CellKind.Markup ? "markdown" : "code"} cell${executionLabel}`;
  }
  s(element) {
    const executionState = this.g.getCellExecution(element.uri)?.state;
    const executionLabel = executionState === NotebookCellExecutionState.Executing ? ", executing" : executionState === NotebookCellExecutionState.Pending ? ", pending" : "";
    return this.r(executionLabel, element.cellKind);
  }
  get t() {
    return this.f ? localize(8473, null) : localize(8474, null);
  }
  getWidgetAriaLabel() {
    const keybinding = this.h.lookupKeybinding(
      "editor.action.accessibilityHelp"
      /* AccessibilityCommandId.OpenAccessibilityHelp */
    )?.getLabel();
    if (this.j.getValue(this.verbositySettingId)) {
      return keybinding ? localize(8475, null, this.t, keybinding) : localize(8476, null, this.t);
    }
    return this.t;
  }
  u(last, e) {
    const viewModel = this.c();
    const result = last || [];
    if (viewModel && e.type === NotebookExecutionType.cell && e.affectsNotebook(viewModel.uri)) {
      const index = result.findIndex((update) => update.cellHandle === e.cellHandle);
      if (index >= 0) {
        result.splice(index, 1);
      }
      result.push({ cellHandle: e.cellHandle, state: e.changed?.state });
    }
    return result;
  }
};
$0Lb = __decorate([
  __param(2, $wL),
  __param(3, $Ty),
  __param(4, $kl),
  __param(5, $ND)
], $0Lb);

// out-build/vs/workbench/contrib/notebook/browser/viewParts/notebookHorizontalTracker.js
var $$Lb = class extends $3c {
  constructor(a, b) {
    super();
    this.a = a;
    this.b = b;
    this.B($_i(this.b, $7j.MOUSE_WHEEL, (event) => {
      let deltaX = event.deltaX;
      let deltaY = event.deltaY;
      let wheelDeltaX = event.wheelDeltaX;
      let wheelDeltaY = event.wheelDeltaY;
      const wheelDelta = event.wheelDelta;
      const shiftConvert = !$m && event.shiftKey;
      if (shiftConvert && !deltaX) {
        deltaX = deltaY;
        deltaY = 0;
        wheelDeltaX = wheelDeltaY;
        wheelDeltaY = 0;
      }
      if (deltaX === 0) {
        return;
      }
      const hoveringOnEditor = this.a.codeEditors.find((editor) => {
        const editorLayout = editor[1].getLayoutInfo();
        if (editorLayout.contentWidth === editorLayout.width) {
          return false;
        }
        const editorDOM = editor[1].getDomNode();
        if (editorDOM && editorDOM.contains(event.target)) {
          return true;
        }
        return false;
      });
      if (!hoveringOnEditor) {
        return;
      }
      const targetWindow = getWindow(event);
      const evt = {
        deltaMode: event.deltaMode,
        deltaX,
        deltaY: 0,
        deltaZ: 0,
        wheelDelta: wheelDelta && $H ? wheelDelta / targetWindow.devicePixelRatio : wheelDelta,
        wheelDeltaX: wheelDeltaX && $H ? wheelDeltaX / targetWindow.devicePixelRatio : wheelDeltaX,
        wheelDeltaY: 0,
        detail: event.detail,
        shiftKey: event.shiftKey,
        type: event.type,
        defaultPrevented: false,
        preventDefault: () => {
        },
        stopPropagation: () => {
        }
      };
      hoveringOnEditor[1].delegateScrollFromMouseWheelEvent(evt);
    }));
  }
};

// out-build/vs/workbench/contrib/notebook/browser/view/notebookCellEditorPool.js
var $AKb = class $AKb2 extends $3c {
  constructor(notebookEditor, m, n, r2, s) {
    super();
    this.notebookEditor = notebookEditor;
    this.m = m;
    this.n = n;
    this.r = r2;
    this.s = s;
    this.b = this.B(new $4c());
    this.h = false;
    this.j = false;
    this.a = this.notebookEditor.getDomNode().appendChild($(".cell-editor-part-cache"));
    this.a.style.position = "absolute";
    this.a.style.top = "-50000px";
    this.a.style.width = "1px";
    this.a.style.height = "1px";
  }
  t(cell) {
    this.c = this.B(this.m(this.a));
    const editorContainer = $ck(this.a, $(".cell-editor-container"));
    const editorInstaService = this.B(this.s.createChild(new $Ok([$on, this.c])));
    EditorContextKeys.inCompositeEditor.bindTo(this.c).set(true);
    const editorOptions2 = new $oKb(this.notebookEditor.getBaseCellEditorOptions(cell.language), this.notebookEditor.notebookOptions, this.r);
    this.f = this.B(editorInstaService.createInstance($D9, editorContainer, {
      ...editorOptions2.getDefaultValue(),
      dimension: {
        width: 0,
        height: 0
      },
      scrollbar: {
        vertical: "hidden",
        horizontal: "auto",
        handleMouseWheel: false,
        useShadows: false
      }
    }, {
      contributions: this.notebookEditor.creationOptions.cellEditorContributions
    }));
    this.h = true;
  }
  preserveFocusedEditor(cell) {
    if (!this.h) {
      this.t(cell);
    }
    this.b.clear();
    this.g?.cancel();
    this.g = $Hh(async (token) => {
      const ref = await this.n.createModelReference(cell.uri);
      if (this.j || token.isCancellationRequested) {
        ref.dispose();
        return;
      }
      const editorDisposable = new $2c();
      editorDisposable.add(ref);
      this.f.setModel(ref.object.textEditorModel);
      this.f.setSelections(cell.getSelections());
      this.f.focus();
      const _update = () => {
        const editorSelections = this.f.getSelections();
        if (editorSelections) {
          cell.setSelections(editorSelections);
        }
        this.notebookEditor.revealInView(cell);
        this.f.setModel(null);
        ref.dispose();
      };
      editorDisposable.add(this.f.onDidChangeModelContent((e) => {
        _update();
      }));
      editorDisposable.add(this.f.onDidChangeCursorSelection((e) => {
        if (e.source === "keyboard" || e.source === "mouse") {
          _update();
        }
      }));
      editorDisposable.add(this.notebookEditor.onDidChangeActiveEditor(() => {
        const latestActiveCell = this.notebookEditor.getActiveCell();
        if (latestActiveCell !== cell || latestActiveCell.focusMode !== CellFocusMode.Editor) {
          this.b.clear();
          this.f.setModel(null);
          ref.dispose();
        }
      }));
      this.b.value = editorDisposable;
    });
  }
  dispose() {
    this.j = true;
    this.g?.cancel();
    super.dispose();
  }
};
$AKb = __decorate([
  __param(2, $oG),
  __param(3, $kl),
  __param(4, $Pk)
], $AKb);

// out-build/vs/workbench/contrib/notebook/browser/notebookEditorWidget.js
var $125 = $;
function $_Lb() {
  const skipContributions = [
    "editor.contrib.review",
    $DLb.ID,
    "editor.contrib.dirtydiff",
    "editor.contrib.testingOutputPeek",
    "editor.contrib.testingDecorations",
    "store.contrib.stickyScrollController",
    "editor.contrib.findController",
    "editor.contrib.emptyTextEditorHint"
  ];
  const contributions = EditorExtensionsRegistry.getEditorContributions().filter((c) => skipContributions.indexOf(c.id) === -1);
  return {
    menuIds: {
      notebookToolbar: $bJ.NotebookToolbar,
      cellTitleToolbar: $bJ.NotebookCellTitle,
      cellDeleteToolbar: $bJ.NotebookCellDelete,
      cellInsertToolbar: $bJ.NotebookCellBetween,
      cellTopInsertToolbar: $bJ.NotebookCellListTop,
      cellExecuteToolbar: $bJ.NotebookCellExecute,
      cellExecutePrimary: $bJ.NotebookCellExecutePrimary
    },
    cellEditorContributions: contributions
  };
}
var $aMb = class $aMb2 extends $3c {
  get isVisible() {
    return this.Ib;
  }
  get isDisposed() {
    return this.Jb;
  }
  set viewModel(newModel) {
    this.h.fire(this.ob?.notebookDocument);
    this.ob = newModel;
    this.j.fire(newModel?.notebookDocument);
  }
  get viewModel() {
    return this.ob;
  }
  get textModel() {
    return this.ob?.notebookDocument;
  }
  get isReadOnly() {
    return this.ob?.options.isReadOnly ?? false;
  }
  get activeCodeEditor() {
    if (this.Jb) {
      return;
    }
    const [focused] = this.hb.getFocusedElements();
    return this.lb.get(focused);
  }
  get activeCellAndCodeEditor() {
    if (this.Jb) {
      return;
    }
    const [focused] = this.hb.getFocusedElements();
    const editor = this.lb.get(focused);
    if (!editor) {
      return;
    }
    return [focused, editor];
  }
  get codeEditors() {
    return [...this.lb];
  }
  get visibleRanges() {
    return this.hb.visibleRanges || [];
  }
  get notebookOptions() {
    return this.Nb;
  }
  constructor(creationOptions, dimension, instantiationService, editorGroupsService, Pb, Qb, Rb, Sb, Tb, contextKeyService, Ub, Vb, Wb, Xb, Yb, Zb) {
    super();
    this.creationOptions = creationOptions;
    this.Pb = Pb;
    this.Qb = Qb;
    this.Rb = Rb;
    this.Sb = Sb;
    this.Tb = Tb;
    this.Ub = Ub;
    this.Vb = Vb;
    this.Wb = Wb;
    this.Xb = Xb;
    this.Yb = Yb;
    this.Zb = Zb;
    this.f = this.B(new $ze());
    this.onDidChangeCellState = this.f.event;
    this.g = this.B(new $ze());
    this.onDidChangeViewCells = this.g.event;
    this.h = this.B(new $ze());
    this.onWillChangeModel = this.h.event;
    this.j = this.B(new $ze());
    this.onDidChangeModel = this.j.event;
    this.m = this.B(new $ze());
    this.onDidAttachViewModel = this.m.event;
    this.n = this.B(new $ze());
    this.onDidChangeOptions = this.n.event;
    this.r = this.B(new $ze());
    this.onDidChangeDecorations = this.r.event;
    this.t = this.B(new $ze());
    this.onDidScroll = this.t.event;
    this.u = this.B(new $ze());
    this.onDidChangeLayout = this.u.event;
    this.w = this.B(new $ze());
    this.onDidChangeActiveCell = this.w.event;
    this.y = this.B(new $ze());
    this.onDidChangeFocus = this.y.event;
    this.z = this.B(new $ze());
    this.onDidChangeSelection = this.z.event;
    this.C = this.B(new $ze());
    this.onDidChangeVisibleRanges = this.C.event;
    this.D = this.B(new $ze());
    this.onDidFocusWidget = this.D.event;
    this.F = this.B(new $ze());
    this.onDidBlurWidget = this.F.event;
    this.G = this.B(new $ze());
    this.onDidChangeActiveEditor = this.G.event;
    this.H = this.B(new $ze());
    this.onDidChangeActiveKernel = this.H.event;
    this.I = this.B(new $ze());
    this.onMouseUp = this.I.event;
    this.J = this.B(new $ze());
    this.onMouseDown = this.J.event;
    this.L = this.B(new $ze());
    this.onDidReceiveMessage = this.L.event;
    this.M = this.B(new $ze());
    this.N = this.M.event;
    this.O = this.B(new $ze());
    this.P = this.O.event;
    this.Q = this.B(new $ze());
    this.onDidResizeOutput = this.Q.event;
    this.db = null;
    this.eb = null;
    this.fb = null;
    this.gb = null;
    this.jb = null;
    this.kb = null;
    this.lb = /* @__PURE__ */ new Map();
    this.pb = this.B(new $2c());
    this.qb = [];
    this.vb = null;
    this.Bb = /* @__PURE__ */ new Map();
    this.Db = new $Rh();
    this.Eb = null;
    this.Fb = $ps();
    this.Hb = false;
    this.Ib = false;
    this.Jb = false;
    this.Kb = /* @__PURE__ */ new Map();
    this.$b = false;
    this.mc = false;
    this.yc = null;
    this.Nc = /* @__PURE__ */ new WeakMap();
    this.Wc = /* @__PURE__ */ new Map();
    this.sb = dimension;
    this.isReplHistory = creationOptions.isReplHistory ?? false;
    this.Lb = creationOptions.isReadOnly ?? false;
    this.R = document.createElement("div");
    this.scopedContextKeyService = this.B(contextKeyService.createScoped(this.R));
    this.Mb = this.B(instantiationService.createChild(new $Ok([$on, this.scopedContextKeyService])));
    this.Nb = creationOptions.options ?? this.Mb.createInstance($xrb, this.creationOptions?.codeWindow ?? $Y, this.Lb, void 0);
    this.B(this.Nb);
    const eventDispatcher = this.B(new $RIb());
    this.nb = new $SIb(this.Nb, eventDispatcher, (language) => this.getBaseCellEditorOptions(language));
    this.B(this.nb.eventDispatcher.onDidChangeLayout(() => {
      this.u.fire();
    }));
    this.B(this.nb.eventDispatcher.onDidChangeCellState((e) => {
      this.f.fire(e);
    }));
    this.B(Sb.onDidChangeOutputRenderers(() => {
      this.lc();
    }));
    this.B(this.Mb.createInstance($uLb, this));
    this.B(Rb.onDidChangeSelectedNotebooks((e) => {
      if ($oh(e.notebook, this.viewModel?.uri)) {
        this.Mc();
        this.H.fire();
      }
    }));
    this.Cb = this.Tb.getValue("editor.scrollBeyondLastLine");
    this.B(this.Tb.onDidChangeConfiguration((e) => {
      if (e.affectsConfiguration("editor.scrollBeyondLastLine")) {
        this.Cb = this.Tb.getValue("editor.scrollBeyondLastLine");
        if (this.sb && this.Ib) {
          this.layout(this.sb);
        }
      }
    }));
    this.B(this.Nb.onDidChangeOptions((e) => {
      if (e.cellStatusBarVisibility || e.cellToolbarLocation || e.cellToolbarInteraction) {
        this.bc();
      }
      if (e.fontFamily) {
        this.cc();
      }
      if (e.compactView || e.focusIndicator || e.insertToolbarPosition || e.cellToolbarLocation || e.dragAndDropEnabled || e.fontSize || e.markupFontSize || e.markdownLineHeight || e.fontFamily || e.insertToolbarAlignment || e.outputFontSize || e.outputLineHeight || e.outputFontFamily || e.outputWordWrap || e.outputScrolling || e.outputLinkifyFilePaths || e.minimalError) {
        this.bb?.remove();
        this.fc();
        this.db?.updateOptions({
          ...this.notebookOptions.computeWebviewOptions(),
          fontFamily: this.ec()
        });
      }
      if (this.sb && this.Ib) {
        this.layout(this.sb);
      }
    }));
    const container2 = creationOptions.codeWindow ? this.Ub.getContainer(creationOptions.codeWindow) : this.Ub.mainContainer;
    this.B(editorGroupsService.getPart(container2).onDidScroll((e) => {
      if (!this.ub || !this.Ib) {
        return;
      }
      this.Hc(this.ub, this.sb);
      this.Ic(this.sb, this.tb);
    }));
    this.Qb.addNotebookEditor(this);
    const id2 = $ps();
    this.R.id = `notebook-${id2}`;
    this.R.className = "notebookOverlay";
    this.R.classList.add("notebook-editor");
    this.R.inert = true;
    this.R.style.visibility = "hidden";
    container2.appendChild(this.R);
    this.dc(this.R);
    this.cc();
    this.Ib = true;
    this.wb = $WAb.bindTo(this.scopedContextKeyService);
    this.xb = $YAb.bindTo(this.scopedContextKeyService);
    this.Ab = $ZAb.bindTo(this.scopedContextKeyService);
    this.yb = $1Ab.bindTo(this.scopedContextKeyService);
    this.zb = $7Ab.bindTo(this.scopedContextKeyService);
    new $nn($9Lb, false).bindTo(this.scopedContextKeyService).set(true);
    this.yb.set(!creationOptions.isReadOnly);
    let contributions;
    if (Array.isArray(this.creationOptions.contributions)) {
      contributions = this.creationOptions.contributions;
    } else {
      contributions = NotebookEditorExtensionsRegistry.getEditorContributions();
    }
    for (const desc of contributions) {
      let contribution;
      try {
        contribution = this.Mb.createInstance(desc.ctor, this);
      } catch (err) {
        $gb(err);
      }
      if (contribution) {
        if (!this.Bb.has(desc.id)) {
          this.Bb.set(desc.id, contribution);
        } else {
          contribution.dispose();
          throw new Error(`DUPLICATE notebook editor contribution: '${desc.id}'`);
        }
      }
    }
    this.bc();
  }
  ac(...args2) {
    if (!this.$b) {
      return;
    }
    $jGb(...args2);
  }
  /**
   * EditorId
   */
  getId() {
    return this.Fb;
  }
  getViewModel() {
    return this.viewModel;
  }
  getLength() {
    return this.viewModel?.length ?? 0;
  }
  getSelections() {
    return this.viewModel?.getSelections() ?? [];
  }
  setSelections(selections) {
    if (!this.viewModel) {
      return;
    }
    const focus = this.viewModel.getFocus();
    this.viewModel.updateSelectionsState({
      kind: SelectionStateType.Index,
      focus,
      selections
    });
  }
  getFocus() {
    return this.viewModel?.getFocus() ?? { start: 0, end: 0 };
  }
  setFocus(focus) {
    if (!this.viewModel) {
      return;
    }
    const selections = this.viewModel.getSelections();
    this.viewModel.updateSelectionsState({
      kind: SelectionStateType.Index,
      focus,
      selections
    });
  }
  getSelectionViewModels() {
    if (!this.viewModel) {
      return [];
    }
    const cellsSet = /* @__PURE__ */ new Set();
    return this.viewModel.getSelections().map((range) => this.viewModel.viewCells.slice(range.start, range.end)).reduce((a, b) => {
      b.forEach((cell) => {
        if (!cellsSet.has(cell.handle)) {
          cellsSet.add(cell.handle);
          a.push(cell);
        }
      });
      return a;
    }, []);
  }
  hasModel() {
    return !!this.ob;
  }
  showProgress() {
    this.Ob = this.Yb.show(true);
  }
  hideProgress() {
    if (this.Ob) {
      this.Ob.done();
      this.Ob = void 0;
    }
  }
  //#region Editor Core
  getBaseCellEditorOptions(language) {
    const existingOptions = this.Kb.get(language);
    if (existingOptions) {
      return existingOptions;
    } else {
      const options3 = new $xLb(this, this.notebookOptions, this.Tb, language);
      this.Kb.set(language, options3);
      return options3;
    }
  }
  bc() {
    if (!this.R) {
      return;
    }
    this.R.classList.remove("cell-title-toolbar-left");
    this.R.classList.remove("cell-title-toolbar-right");
    this.R.classList.remove("cell-title-toolbar-hidden");
    const cellToolbarLocation = this.Nb.computeCellToolbarLocation(this.viewModel?.viewType);
    this.R.classList.add(`cell-title-toolbar-${cellToolbarLocation}`);
    const cellToolbarInteraction = this.Nb.getDisplayOptions().cellToolbarInteraction;
    let cellToolbarInteractionState = "hover";
    this.R.classList.remove("cell-toolbar-hover");
    this.R.classList.remove("cell-toolbar-click");
    if (cellToolbarInteraction === "hover" || cellToolbarInteraction === "click") {
      cellToolbarInteractionState = cellToolbarInteraction;
    }
    this.R.classList.add(`cell-toolbar-${cellToolbarInteractionState}`);
  }
  cc() {
    const editorOptions2 = this.Tb.getValue("editor");
    const targetWindow = getWindow(this.getDomNode());
    this.rb = $64.readFontInfo(targetWindow, $ED.createFromRawSettings(editorOptions2, $_1.getInstance(targetWindow).value));
  }
  dc(parent) {
    this.S = document.createElement("div");
    this.S.classList.add("notebook-toolbar-container");
    this.S.style.display = "none";
    $bk(parent, this.S);
    this.W = document.createElement("div");
    this.W.classList.add("notebook-sticky-scroll-container");
    $bk(parent, this.W);
    this.ab = document.createElement("div");
    $bk(parent, this.ab);
    this.ab.classList.add("cell-list-container");
    this.fc();
    this.gc();
    this.Y = document.createElement("div");
    this.Y.classList.add("notebook-overview-ruler-container");
    this.hb.scrollableElement.appendChild(this.Y);
    this.ic();
    this.B(this.Mb.createInstance($$Lb, this, this.hb.scrollableElement));
    this.cb = document.createElement("div");
    this.cb.classList.add("notebook-overflow-widget-container", "monaco-editor");
    $bk(parent, this.cb);
  }
  ec() {
    return this.rb?.fontFamily ?? `"SF Mono", Monaco, Menlo, Consolas, "Ubuntu Mono", "Liberation Mono", "DejaVu Sans Mono", "Courier New", monospace`;
  }
  fc() {
    this.bb = $VZ(this.ab);
    const { cellRightMargin, cellTopMargin, cellRunGutter, cellBottomMargin, codeCellLeftMargin, markdownCellGutter, markdownCellLeftMargin, markdownCellBottomMargin, markdownCellTopMargin, collapsedIndicatorHeight, focusIndicator, insertToolbarPosition, outputFontSize, focusIndicatorLeftMargin, focusIndicatorGap } = this.Nb.getLayoutConfiguration();
    const { insertToolbarAlignment, compactView, fontSize } = this.Nb.getDisplayOptions();
    const getCellEditorContainerLeftMargin = this.Nb.getCellEditorContainerLeftMargin();
    const { bottomToolbarGap, bottomToolbarHeight } = this.Nb.computeBottomToolbarDimensions(this.viewModel?.viewType);
    const styleSheets = [];
    if (!this.rb) {
      this.cc();
    }
    const fontFamily = this.ec();
    styleSheets.push(`
		.notebook-editor {
			--notebook-cell-output-font-size: ${outputFontSize}px;
			--notebook-cell-input-preview-font-size: ${fontSize}px;
			--notebook-cell-input-preview-font-family: ${fontFamily};
		}
		`);
    if (compactView) {
      styleSheets.push(`.notebookOverlay .cell-list-container > .monaco-list > .monaco-scrollable-element > .monaco-list-rows > .markdown-cell-row div.cell.code { margin-left: ${getCellEditorContainerLeftMargin}px; }`);
    } else {
      styleSheets.push(`.notebookOverlay .cell-list-container > .monaco-list > .monaco-scrollable-element > .monaco-list-rows > .markdown-cell-row div.cell.code { margin-left: ${codeCellLeftMargin}px; }`);
    }
    if (focusIndicator === "border") {
      styleSheets.push(`
			.monaco-workbench .notebookOverlay .monaco-list .monaco-list-row .cell-focus-indicator-top:before,
			.monaco-workbench .notebookOverlay .monaco-list .monaco-list-row .cell-focus-indicator-bottom:before,
			.monaco-workbench .notebookOverlay .monaco-list .markdown-cell-row .cell-inner-container:before,
			.monaco-workbench .notebookOverlay .monaco-list .markdown-cell-row .cell-inner-container:after {
				content: "";
				position: absolute;
				width: 100%;
				height: 1px;
			}

			.monaco-workbench .notebookOverlay .monaco-list .monaco-list-row .cell-focus-indicator-left:before,
			.monaco-workbench .notebookOverlay .monaco-list .monaco-list-row .cell-focus-indicator-right:before {
				content: "";
				position: absolute;
				width: 1px;
				height: 100%;
				z-index: 10;
			}

			/* top border */
			.monaco-workbench .notebookOverlay .monaco-list .monaco-list-row .cell-focus-indicator-top:before {
				border-top: 1px solid transparent;
			}

			/* left border */
			.monaco-workbench .notebookOverlay .monaco-list .monaco-list-row .cell-focus-indicator-left:before {
				border-left: 1px solid transparent;
			}

			/* bottom border */
			.monaco-workbench .notebookOverlay .monaco-list .monaco-list-row .cell-focus-indicator-bottom:before {
				border-bottom: 1px solid transparent;
			}

			/* right border */
			.monaco-workbench .notebookOverlay .monaco-list .monaco-list-row .cell-focus-indicator-right:before {
				border-right: 1px solid transparent;
			}
			`);
      styleSheets.push(`
			.monaco-workbench .notebookOverlay .monaco-list .monaco-list-row.code-cell-row.focused .cell-focus-indicator-left:before,
			.monaco-workbench .notebookOverlay .monaco-list .monaco-list-row.code-cell-row.focused .cell-focus-indicator-right:before,
			.monaco-workbench .notebookOverlay .monaco-list.selection-multiple .monaco-list-row.code-cell-row.selected .cell-focus-indicator-left:before,
			.monaco-workbench .notebookOverlay .monaco-list.selection-multiple .monaco-list-row.code-cell-row.selected .cell-focus-indicator-right:before {
				top: -${cellTopMargin}px; height: calc(100% + ${cellTopMargin + cellBottomMargin}px)
			}`);
    } else {
      styleSheets.push(`
			.monaco-workbench .notebookOverlay .monaco-list .monaco-list-row .cell-focus-indicator-left .codeOutput-focus-indicator {
				border-left: 3px solid transparent;
				border-radius: 4px;
				width: 0px;
				margin-left: ${focusIndicatorLeftMargin}px;
				border-color: var(--vscode-notebook-inactiveFocusedCellBorder) !important;
			}

			.monaco-workbench .notebookOverlay .monaco-list .monaco-list-row.focused .cell-focus-indicator-left .codeOutput-focus-indicator-container,
			.monaco-workbench .notebookOverlay .monaco-list .monaco-list-row .cell-output-hover .cell-focus-indicator-left .codeOutput-focus-indicator-container,
			.monaco-workbench .notebookOverlay .monaco-list .monaco-list-row .markdown-cell-hover .cell-focus-indicator-left .codeOutput-focus-indicator-container,
			.monaco-workbench .notebookOverlay .monaco-list .monaco-list-row:hover .cell-focus-indicator-left .codeOutput-focus-indicator-container {
				display: block;
			}

			.monaco-workbench .notebookOverlay .monaco-list .monaco-list-row .cell-focus-indicator-left .codeOutput-focus-indicator-container:hover .codeOutput-focus-indicator {
				border-left: 5px solid transparent;
				margin-left: ${focusIndicatorLeftMargin - 1}px;
			}
			`);
      styleSheets.push(`
			.monaco-workbench .notebookOverlay .monaco-list .monaco-list-row.focused .cell-inner-container.cell-output-focus .cell-focus-indicator-left .codeOutput-focus-indicator,
			.monaco-workbench .notebookOverlay .monaco-list:focus-within .monaco-list-row.focused .cell-inner-container .cell-focus-indicator-left .codeOutput-focus-indicator {
				border-color: var(--vscode-notebook-focusedCellBorder) !important;
			}

			.monaco-workbench .notebookOverlay .monaco-list .monaco-list-row .cell-inner-container .cell-focus-indicator-left .output-focus-indicator {
				margin-top: ${focusIndicatorGap}px;
			}
			`);
    }
    if (insertToolbarPosition === "betweenCells" || insertToolbarPosition === "both") {
      styleSheets.push(`.monaco-workbench .notebookOverlay > .cell-list-container > .monaco-list > .monaco-scrollable-element > .monaco-list-rows > .monaco-list-row .cell-bottom-toolbar-container { display: flex; }`);
      styleSheets.push(`.monaco-workbench .notebookOverlay > .cell-list-container > .monaco-list > .monaco-scrollable-element > .monaco-list-rows > .view-zones .cell-list-top-cell-toolbar-container { display: flex; }`);
    } else {
      styleSheets.push(`.monaco-workbench .notebookOverlay > .cell-list-container > .monaco-list > .monaco-scrollable-element > .monaco-list-rows > .monaco-list-row .cell-bottom-toolbar-container { display: none; }`);
      styleSheets.push(`.monaco-workbench .notebookOverlay > .cell-list-container > .monaco-list > .monaco-scrollable-element > .monaco-list-rows > .view-zones .cell-list-top-cell-toolbar-container { display: none; }`);
    }
    if (insertToolbarAlignment === "left") {
      styleSheets.push(`
			.monaco-workbench .notebookOverlay .cell-list-top-cell-toolbar-container .action-item:first-child,
			.monaco-workbench .notebookOverlay .cell-list-top-cell-toolbar-container .action-item:first-child, .monaco-workbench .notebookOverlay > .cell-list-container > .monaco-list > .monaco-scrollable-element > .monaco-list-rows > .monaco-list-row .cell-bottom-toolbar-container .action-item:first-child {
				margin-right: 0px !important;
			}`);
      styleSheets.push(`
			.monaco-workbench .notebookOverlay .cell-list-top-cell-toolbar-container .monaco-toolbar .action-label,
			.monaco-workbench .notebookOverlay .cell-list-top-cell-toolbar-container .monaco-toolbar .action-label, .monaco-workbench .notebookOverlay > .cell-list-container > .monaco-list > .monaco-scrollable-element > .monaco-list-rows > .monaco-list-row .cell-bottom-toolbar-container .monaco-toolbar .action-label {
				padding: 0px !important;
				justify-content: center;
				border-radius: 4px;
			}`);
      styleSheets.push(`
			.monaco-workbench .notebookOverlay .cell-list-top-cell-toolbar-container,
			.monaco-workbench .notebookOverlay .cell-list-top-cell-toolbar-container, .monaco-workbench .notebookOverlay > .cell-list-container > .monaco-list > .monaco-scrollable-element > .monaco-list-rows > .monaco-list-row .cell-bottom-toolbar-container {
				align-items: flex-start;
				justify-content: left;
				margin: 0 16px 0 ${8 + codeCellLeftMargin}px;
			}`);
      styleSheets.push(`
			.monaco-workbench .notebookOverlay .cell-list-top-cell-toolbar-container,
			.notebookOverlay .cell-bottom-toolbar-container .action-item {
				border: 0px;
			}`);
    }
    styleSheets.push(`.notebookOverlay .cell-list-container > .monaco-list > .monaco-scrollable-element > .monaco-list-rows > .code-cell-row div.cell.code { margin-left: ${getCellEditorContainerLeftMargin}px; }`);
    styleSheets.push(`.notebookOverlay .cell-list-container > .monaco-list > .monaco-scrollable-element > .monaco-list-rows > .view-zones .code-cell-row div.cell.code { margin-left: ${getCellEditorContainerLeftMargin}px; }`);
    styleSheets.push(`.notebookOverlay .cell-list-container > .monaco-list > .monaco-scrollable-element > .monaco-list-rows > .view-zones .code-cell-row div.cell { margin-right: ${cellRightMargin}px; }`);
    styleSheets.push(`.notebookOverlay .cell-list-container > .monaco-list > .monaco-scrollable-element > .monaco-list-rows > .monaco-list-row div.cell { margin-right: ${cellRightMargin}px; }`);
    styleSheets.push(`.notebookOverlay .cell-list-container > .monaco-list > .monaco-scrollable-element > .monaco-list-rows > .monaco-list-row > .cell-inner-container { padding-top: ${cellTopMargin}px; }`);
    styleSheets.push(`.notebookOverlay .cell-list-container > .monaco-list > .monaco-scrollable-element > .monaco-list-rows > .markdown-cell-row > .cell-inner-container { padding-bottom: ${markdownCellBottomMargin}px; padding-top: ${markdownCellTopMargin}px; }`);
    styleSheets.push(`.notebookOverlay .cell-list-container > .monaco-list > .monaco-scrollable-element > .monaco-list-rows > .markdown-cell-row > .cell-inner-container.webview-backed-markdown-cell { padding: 0; }`);
    styleSheets.push(`.notebookOverlay .cell-list-container > .monaco-list > .monaco-scrollable-element > .monaco-list-rows > .markdown-cell-row > .webview-backed-markdown-cell.markdown-cell-edit-mode .cell.code { padding-bottom: ${markdownCellBottomMargin}px; padding-top: ${markdownCellTopMargin}px; }`);
    styleSheets.push(`.notebookOverlay .output { margin: 0px ${cellRightMargin}px 0px ${getCellEditorContainerLeftMargin}px; }`);
    styleSheets.push(`.notebookOverlay .output { width: calc(100% - ${getCellEditorContainerLeftMargin + cellRightMargin}px); }`);
    styleSheets.push(`.notebookOverlay .cell-list-container > .monaco-list > .monaco-scrollable-element > .monaco-list-rows > .monaco-list-row .cell-comment-container { left: ${getCellEditorContainerLeftMargin}px; }`);
    styleSheets.push(`.notebookOverlay .cell-list-container > .monaco-list > .monaco-scrollable-element > .monaco-list-rows > .monaco-list-row .cell-comment-container { width: calc(100% - ${getCellEditorContainerLeftMargin + cellRightMargin}px); }`);
    styleSheets.push(`.monaco-workbench .notebookOverlay .output .output-collapse-container .expandButton { left: -${cellRunGutter}px; }`);
    styleSheets.push(`.monaco-workbench .notebookOverlay .output .output-collapse-container .expandButton {
			position: absolute;
			width: ${cellRunGutter}px;
			padding: 6px 0px;
		}`);
    styleSheets.push(`.notebookOverlay .output-show-more-container { margin: 0px ${cellRightMargin}px 0px ${getCellEditorContainerLeftMargin}px; }`);
    styleSheets.push(`.notebookOverlay .output-show-more-container { width: calc(100% - ${getCellEditorContainerLeftMargin + cellRightMargin}px); }`);
    styleSheets.push(`.notebookOverlay .cell-list-container > .monaco-list > .monaco-scrollable-element > .monaco-list-rows > .monaco-list-row div.cell.markdown { padding-left: ${cellRunGutter}px; }`);
    styleSheets.push(`.monaco-workbench .notebookOverlay > .cell-list-container .notebook-folding-indicator { left: ${(markdownCellGutter - 20) / 2 + markdownCellLeftMargin}px; }`);
    styleSheets.push(`.notebookOverlay > .cell-list-container .notebook-folded-hint { left: ${markdownCellGutter + markdownCellLeftMargin + 8}px; }`);
    styleSheets.push(`.notebookOverlay .monaco-list .monaco-list-row :not(.webview-backed-markdown-cell) .cell-focus-indicator-top { height: ${cellTopMargin}px; }`);
    styleSheets.push(`.notebookOverlay .monaco-list .monaco-list-row .cell-focus-indicator-side { bottom: ${bottomToolbarGap}px; }`);
    styleSheets.push(`.notebookOverlay .monaco-list .monaco-list-row.code-cell-row .cell-focus-indicator-left { width: ${getCellEditorContainerLeftMargin}px; }`);
    styleSheets.push(`.notebookOverlay .monaco-list .monaco-list-row.markdown-cell-row .cell-focus-indicator-left { width: ${codeCellLeftMargin}px; }`);
    styleSheets.push(`.notebookOverlay .monaco-list .monaco-list-row .cell-focus-indicator.cell-focus-indicator-right { width: ${cellRightMargin}px; }`);
    styleSheets.push(`.notebookOverlay .monaco-list .monaco-list-row .cell-focus-indicator-bottom { height: ${cellBottomMargin}px; }`);
    styleSheets.push(`.notebookOverlay .monaco-list .monaco-list-row .cell-shadow-container-bottom { top: ${cellBottomMargin}px; }`);
    styleSheets.push(`
			.notebookOverlay .monaco-list .monaco-list-row:has(+ .monaco-list-row.selected) .cell-focus-indicator-bottom {
				height: ${bottomToolbarGap + cellBottomMargin}px;
			}
		`);
    styleSheets.push(`
			.notebookOverlay .monaco-list .monaco-list-row.code-cell-row.nb-multiCellHighlight:has(+ .monaco-list-row.nb-multiCellHighlight) .cell-focus-indicator-bottom {
				height: ${bottomToolbarGap + cellBottomMargin}px;
				background-color: var(--vscode-notebook-symbolHighlightBackground) !important;
			}

			.notebookOverlay .monaco-list .monaco-list-row.markdown-cell-row.nb-multiCellHighlight:has(+ .monaco-list-row.nb-multiCellHighlight) .cell-focus-indicator-bottom {
				height: ${bottomToolbarGap + cellBottomMargin - 6}px;
				background-color: var(--vscode-notebook-symbolHighlightBackground) !important;
			}
		`);
    styleSheets.push(`
			.monaco-workbench .notebookOverlay > .cell-list-container > .monaco-list > .monaco-scrollable-element > .monaco-list-rows > .monaco-list-row .input-collapse-container .cell-collapse-preview {
				line-height: ${collapsedIndicatorHeight}px;
			}

			.monaco-workbench .notebookOverlay > .cell-list-container > .monaco-list > .monaco-scrollable-element > .monaco-list-rows > .monaco-list-row .input-collapse-container .cell-collapse-preview .monaco-tokenized-source {
				max-height: ${collapsedIndicatorHeight}px;
			}
		`);
    styleSheets.push(`.monaco-workbench .notebookOverlay > .cell-list-container > .monaco-list > .monaco-scrollable-element > .monaco-list-rows > .monaco-list-row .cell-bottom-toolbar-container .monaco-toolbar { height: ${bottomToolbarHeight}px }`);
    styleSheets.push(`.monaco-workbench .notebookOverlay > .cell-list-container > .monaco-list > .monaco-scrollable-element > .monaco-list-rows > .view-zones .cell-list-top-cell-toolbar-container .monaco-toolbar { height: ${bottomToolbarHeight}px }`);
    styleSheets.push(`.monaco-workbench .notebookOverlay.cell-title-toolbar-right > .cell-list-container > .monaco-list > .monaco-scrollable-element > .monaco-list-rows > .monaco-list-row .cell-title-toolbar {
			right: ${cellRightMargin + 26}px;
		}
		.monaco-workbench .notebookOverlay.cell-title-toolbar-left > .cell-list-container > .monaco-list > .monaco-scrollable-element > .monaco-list-rows > .monaco-list-row .cell-title-toolbar {
			left: ${getCellEditorContainerLeftMargin + 16}px;
		}
		.monaco-workbench .notebookOverlay.cell-title-toolbar-hidden > .cell-list-container > .monaco-list > .monaco-scrollable-element > .monaco-list-rows > .monaco-list-row .cell-title-toolbar {
			display: none;
		}`);
    styleSheets.push(`
		.monaco-workbench .notebookOverlay .output > div.foreground.output-inner-container {
			padding: ${$wrb}px 8px;
		}
		.monaco-workbench .notebookOverlay > .cell-list-container > .monaco-list > .monaco-scrollable-element > .monaco-list-rows > .monaco-list-row .output-collapse-container {
			padding: ${$wrb}px 8px;
		}
		`);
    styleSheets.push(`
		.monaco-workbench .notebookOverlay .cell-chat-part {
			margin: 0 ${cellRightMargin}px 6px 4px;
		}
		`);
    this.bb.textContent = styleSheets.join("\n");
  }
  gc() {
    this.ab.classList.add("cell-list-container");
    this.jb = this.B(new $rJb(this, this.ab));
    const getScopedContextKeyService = (container2) => this.hb.contextKeyService.createScoped(container2);
    this.mb = this.B(this.Mb.createInstance($AKb, this, getScopedContextKeyService));
    const renderers = [
      this.Mb.createInstance($nLb, this, this.lb, this.mb, this.jb, getScopedContextKeyService),
      this.Mb.createInstance($mLb, this, this.jb, this.lb, getScopedContextKeyService)
    ];
    renderers.forEach((renderer) => {
      this.B(renderer);
    });
    this.gb = this.Mb.createInstance($lLb, getWindow(this.getDomNode()));
    this.B(this.gb);
    const accessibilityProvider = this.Mb.createInstance($0Lb, () => this.viewModel, this.isReplHistory);
    this.B(accessibilityProvider);
    this.hb = this.Mb.createInstance($yJb, "NotebookCellList", this.ab, this.nb.notebookOptions, this.gb, renderers, this.scopedContextKeyService, {
      setRowLineHeight: false,
      setRowHeight: false,
      supportDynamicHeights: true,
      horizontalScrolling: false,
      keyboardSupport: false,
      mouseSupport: true,
      multipleSelectionSupport: true,
      selectionNavigation: true,
      typeNavigationEnabled: true,
      paddingTop: 0,
      paddingBottom: 0,
      transformOptimization: false,
      //(isMacintosh && isNative) || getTitleBarStyle(this.configurationService, this.environmentService) === 'native',
      initialSize: this.sb,
      styleController: (_suffix) => {
        return this.hb;
      },
      overrideStyles: {
        listBackground: notebookEditorBackground,
        listActiveSelectionBackground: notebookEditorBackground,
        listActiveSelectionForeground: $eo,
        listFocusAndSelectionBackground: notebookEditorBackground,
        listFocusAndSelectionForeground: $eo,
        listFocusBackground: notebookEditorBackground,
        listFocusForeground: $eo,
        listHoverForeground: $eo,
        listHoverBackground: notebookEditorBackground,
        listHoverOutline: $jo,
        listFocusOutline: $jo,
        listInactiveSelectionBackground: notebookEditorBackground,
        listInactiveSelectionForeground: $eo,
        listInactiveFocusBackground: notebookEditorBackground,
        listInactiveFocusOutline: notebookEditorBackground
      },
      accessibilityProvider
    });
    this.jb.setList(this.hb);
    this.B(this.hb);
    this.ib = new $zJb(this.hb);
    this.B(this.ib);
    this.B($Zc(...renderers));
    this.kb = this.B(this.Mb.createInstance($wLb, this, this.notebookOptions));
    this.fb = $bk(this.hb.rowsContainer, $125(".webview-cover"));
    this.fb.style.display = "none";
    this.B($bj(this.R, (e) => {
      if (e.target.classList.contains("slider") && this.fb) {
        this.fb.style.display = "block";
      }
    }));
    this.B($cj(this.R, () => {
      if (this.fb) {
        this.fb.style.display = "none";
      }
    }));
    this.B(this.hb.onMouseDown((e) => {
      if (e.element) {
        this.J.fire({ event: e.browserEvent, target: e.element });
      }
    }));
    this.B(this.hb.onMouseUp((e) => {
      if (e.element) {
        this.I.fire({ event: e.browserEvent, target: e.element });
      }
    }));
    this.B(this.hb.onDidChangeFocus((_e) => {
      this.G.fire(this);
      this.w.fire();
      this.y.fire();
      this.zb.set(false);
    }));
    this.B(this.hb.onContextMenu((e) => {
      this.hc(e);
    }));
    this.B(this.hb.onDidChangeVisibleRanges(() => {
      this.C.fire();
    }));
    this.B(this.hb.onDidScroll((e) => {
      if (e.scrollTop !== e.oldScrollTop) {
        this.t.fire();
        this.Kc();
      }
    }));
    this.Gb = this.B($_j(this.getDomNode()));
    this.B(this.Gb.onDidBlur(() => {
      this.wb.set(false);
      this.viewModel?.setEditorFocus(false);
      this.F.fire();
    }));
    this.B(this.Gb.onDidFocus(() => {
      this.wb.set(true);
      this.viewModel?.setEditorFocus(true);
      this.D.fire();
    }));
    this.jc();
    this.kc();
    this.B(this.Tb.onDidChangeConfiguration((e) => {
      if (e.affectsConfiguration(accessibilityProvider.verbositySettingId)) {
        this.hb.ariaLabel = accessibilityProvider?.getWidgetAriaLabel();
      }
    }));
  }
  hc(e) {
    this.Vb.showContextMenu({
      menuId: $bJ.NotebookCellTitle,
      menuActionOptions: {
        shouldForwardArgs: true
      },
      contextKeyService: this.scopedContextKeyService,
      getAnchor: () => e.anchor,
      getActionsContext: () => {
        return {
          from: "cellContainer"
        };
      }
    });
  }
  ic() {
    this.Z = this.B(this.Mb.createInstance($vLb, this, this.Y));
  }
  jc() {
    this.U = this.B(this.Mb.createInstance($rLb, this, this.scopedContextKeyService, this.Nb, this.S));
    this.B(this.U.onDidChangeVisibility(() => {
      if (this.sb && this.Ib) {
        this.layout(this.sb);
      }
    }));
  }
  kc() {
    this.X = this.B(this.Mb.createInstance($5Lb, this.W, this, this.hb, (sizeDelta) => {
      if (this.isDisposed) {
        return;
      }
      if (this.sb && this.Ib) {
        if (sizeDelta > 0) {
          this.layout(this.sb);
          this.setScrollTop(this.scrollTop + sizeDelta);
        } else if (sizeDelta < 0) {
          this.setScrollTop(this.scrollTop + sizeDelta);
          this.layout(this.sb);
        }
      }
      this.t.fire();
    }));
  }
  lc() {
    if (!this.viewModel || !this.db) {
      return;
    }
    this.db.updateOutputRenderers();
    this.viewModel.viewCells.forEach((cell) => {
      cell.outputsViewModels.forEach((output) => {
        if (output.pickedMimeType?.rendererId === $kM) {
          output.resetRenderer();
        }
      });
    });
  }
  getDomNode() {
    return this.R;
  }
  getOverflowContainerDomNode() {
    return this.cb;
  }
  getInnerWebview() {
    return this.db?.webview;
  }
  setEditorProgressService(editorProgressService) {
    this.Yb = editorProgressService;
  }
  setParentContextKeyService(parentContextKeyService) {
    this.scopedContextKeyService.updateParent(parentContextKeyService);
  }
  async setModel(textModel, viewState, perf2, viewType) {
    if (this.viewModel === void 0 || !this.viewModel.equal(textModel)) {
      const oldBottomToolbarDimensions = this.Nb.computeBottomToolbarDimensions(this.viewModel?.viewType);
      this.rc();
      await this.wc(textModel, viewType ?? textModel.viewType, viewState, perf2);
      const newBottomToolbarDimensions = this.Nb.computeBottomToolbarDimensions(this.viewModel?.viewType);
      if (oldBottomToolbarDimensions.bottomToolbarGap !== newBottomToolbarDimensions.bottomToolbarGap || oldBottomToolbarDimensions.bottomToolbarHeight !== newBottomToolbarDimensions.bottomToolbarHeight) {
        this.bb?.remove();
        this.fc();
        this.db?.updateOptions({
          ...this.notebookOptions.computeWebviewOptions(),
          fontFamily: this.ec()
        });
      }
      this.Wb.publicLog2("notebook/editorOpened", {
        scheme: textModel.uri.scheme,
        ext: $th(textModel.uri),
        viewType: textModel.viewType,
        isRepl: this.isReplHistory
      });
    } else {
      this.restoreListViewState(viewState);
    }
    this.Dc(viewState);
    this.Mc();
    this.jb?.clearGlobalDragState();
    this.pb.add(this.hb.onDidChangeFocus(() => {
      this.pc();
    }));
    this.pc();
    this.nc();
  }
  nc() {
    if (this.mc) {
      return;
    }
    this.mc = true;
    $gj(getWindow(this.getDomNode()), (deadline) => {
      this.oc(deadline);
    });
  }
  oc(deadline) {
    const endTime = Date.now() + deadline.timeRemaining();
    const execute = () => {
      try {
        this.mc = true;
        if (this.Jb) {
          return;
        }
        if (!this.viewModel) {
          return;
        }
        const firstMarkupCell = this.viewModel.viewCells.find((cell) => cell.cellKind === CellKind.Markup && !this.db?.markupPreviewMapping.has(cell.id) && !this.Sc(cell));
        if (!firstMarkupCell) {
          return;
        }
        this.createMarkupPreview(firstMarkupCell);
      } finally {
        this.mc = false;
      }
      if (Date.now() < endTime) {
        $E(execute);
      } else {
        this.nc();
      }
    };
    execute();
  }
  pc() {
    if (!this.viewModel) {
      return;
    }
    const focused = this.hb.getFocusedElements()[0];
    if (focused) {
      if (!this.Eb) {
        this.Eb = this.pb.add(this.Mb.createInstance($pJb, this, focused));
      }
      this.Eb.updateForElement(focused);
    }
  }
  async setOptions(options3) {
    if (options3?.isReadOnly !== void 0) {
      this.Lb = options3?.isReadOnly;
    }
    if (!this.viewModel) {
      return;
    }
    this.viewModel.updateOptions({ isReadOnly: this.Lb });
    this.notebookOptions.updateOptions(this.Lb);
    const cellOptions = options3?.cellOptions ?? this.qc(options3);
    if (cellOptions) {
      const cell = this.viewModel.viewCells.find((cell2) => cell2.uri.toString() === cellOptions.resource.toString());
      if (cell) {
        this.focusElement(cell);
        const selection = cellOptions.options?.selection;
        if (selection) {
          cell.updateEditState(CellEditState.Editing, "setOptions");
          cell.focusMode = CellFocusMode.Editor;
          await this.revealRangeInCenterIfOutsideViewportAsync(cell, new $9C(selection.startLineNumber, selection.startColumn, selection.endLineNumber || selection.startLineNumber, selection.endColumn || selection.startColumn));
        } else {
          this.hb.revealCell(
            cell,
            options3?.cellRevealType ?? 4
            /* CellRevealType.CenterIfOutsideViewport */
          );
        }
        const editor = this.lb.get(cell);
        if (editor) {
          if (cellOptions.options?.selection) {
            const { selection: selection2 } = cellOptions.options;
            const editorSelection = new $9C(selection2.startLineNumber, selection2.startColumn, selection2.endLineNumber || selection2.startLineNumber, selection2.endColumn || selection2.startColumn);
            editor.setSelection(editorSelection);
            editor.revealPositionInCenterIfOutsideViewport({
              lineNumber: selection2.startLineNumber,
              column: selection2.startColumn
            });
            await this.revealRangeInCenterIfOutsideViewportAsync(cell, editorSelection);
          }
          if (!cellOptions.options?.preserveFocus) {
            editor.focus();
          }
        }
      }
    }
    if (options3?.cellSelections) {
      const focusCellIndex = options3.cellSelections[0].start;
      const focusedCell = this.viewModel.cellAt(focusCellIndex);
      if (focusedCell) {
        this.viewModel.updateSelectionsState({
          kind: SelectionStateType.Index,
          focus: { start: focusCellIndex, end: focusCellIndex + 1 },
          selections: options3.cellSelections
        });
        this.revealInCenterIfOutsideViewport(focusedCell);
      }
    }
    this.sc();
    this.n.fire();
  }
  qc(options3) {
    if (options3?.indexedCellOptions) {
      const cell = this.cellAt(options3.indexedCellOptions.index);
      if (cell) {
        return {
          resource: cell.uri,
          options: {
            selection: options3.indexedCellOptions.selection,
            preserveFocus: false
          }
        };
      }
    }
    return void 0;
  }
  rc() {
    this.pb.clear();
    $Xc(this.qb);
    this.hb.detachViewModel();
    this.viewModel?.dispose();
    this.viewModel = void 0;
    this.db?.dispose();
    this.db?.element.remove();
    this.db = null;
    this.hb.clear();
  }
  sc() {
    if (!this.viewModel) {
      return;
    }
    this.yb.set(!this.viewModel.options.isReadOnly);
    this.cb.classList.toggle("notebook-editor-editable", !this.viewModel.options.isReadOnly);
    this.getDomNode().classList.toggle("notebook-editor-editable", !this.viewModel.options.isReadOnly);
  }
  async tc() {
    if (!this.textModel) {
      return null;
    }
    if (this.eb) {
      return this.eb;
    }
    if (!this.db) {
      this.uc(this.getId(), this.textModel.viewType, this.textModel.uri);
    }
    this.eb = (async () => {
      if (!this.db) {
        throw new Error("Notebook output webview object is not created successfully.");
      }
      await this.db.createWebview(this.creationOptions.codeWindow ?? $Y);
      if (!this.db.webview) {
        throw new Error("Notebook output webview element was not created successfully.");
      }
      this.pb.add(this.db.webview.onDidBlur(() => {
        this.xb.set(false);
        this.Hb = false;
        this.updateEditorFocus();
        this.updateCellFocusMode();
      }));
      this.pb.add(this.db.webview.onDidFocus(() => {
        this.xb.set(true);
        this.updateEditorFocus();
        this.Hb = true;
      }));
      this.pb.add(this.db.onMessage((e) => {
        this.L.fire(e);
      }));
      return this.db;
    })();
    return this.eb;
  }
  uc(id2, viewType, resource) {
    if (this.db) {
      return;
    }
    const that = this;
    this.db = this.Mb.createInstance($JJb, {
      get creationOptions() {
        return that.creationOptions;
      },
      setScrollTop(scrollTop) {
        that.hb.scrollTop = scrollTop;
      },
      triggerScroll(event) {
        that.hb.triggerScrollFromMouseWheelEvent(event);
      },
      getCellByInfo: that.getCellByInfo.bind(that),
      getCellById: that.Yc.bind(that),
      toggleNotebookCellSelection: that.Oc.bind(that),
      focusNotebookCell: that.focusNotebookCell.bind(that),
      focusNextNotebookCell: that.focusNextNotebookCell.bind(that),
      updateOutputHeight: that.Vc.bind(that),
      scheduleOutputHeightAck: that.Xc.bind(that),
      updateMarkupCellHeight: that.Zc.bind(that),
      setMarkupCellEditState: that.$c.bind(that),
      didStartDragMarkupCell: that.ad.bind(that),
      didDragMarkupCell: that.bd.bind(that),
      didDropMarkupCell: that.cd.bind(that),
      didEndDragMarkupCell: that.dd.bind(that),
      didResizeOutput: that.ed.bind(that),
      updatePerformanceMetadata: that.fd.bind(that),
      didFocusOutputInputChange: that._didFocusOutputInputChange.bind(that)
    }, id2, viewType, resource, {
      ...this.Nb.computeWebviewOptions(),
      fontFamily: this.ec()
    }, this.Pb.getScoped(this.Fb));
    this.db.element.style.width = "100%";
    this.hb.attachWebview(this.db.element);
  }
  async wc(textModel, viewType, viewState, perf2) {
    this.uc(this.getId(), textModel.viewType, textModel.uri);
    this.viewModel = this.Mb.createInstance($ZIb, viewType, textModel, this.nb, this.getLayoutInfo(), { isReadOnly: this.Lb });
    this.nb.eventDispatcher.emit([new $irb({ width: true, fontInfo: true }, this.getLayoutInfo())]);
    this.notebookOptions.updateOptions(this.Lb);
    this.sc();
    this.bc();
    {
      this.viewModel.restoreEditorViewState(viewState);
      const contributionsState = viewState?.contributionsState || {};
      for (const [id2, contribution] of this.Bb) {
        if (typeof contribution.restoreViewState === "function") {
          contribution.restoreViewState(contributionsState[id2]);
        }
      }
    }
    this.pb.add(this.viewModel.onDidChangeViewCells((e) => {
      this.g.fire(e);
    }));
    this.pb.add(this.viewModel.onDidChangeSelection(() => {
      this.z.fire();
      this.Tc();
    }));
    this.pb.add(this.hb.onWillScroll((e) => {
      if (this.db?.isResolved()) {
        this.fb.style.transform = `translateY(${e.scrollTop})`;
      }
    }));
    let hasPendingChangeContentHeight = false;
    this.pb.add(this.hb.onDidChangeContentHeight(() => {
      if (hasPendingChangeContentHeight) {
        return;
      }
      hasPendingChangeContentHeight = true;
      this.pb.add($jj(getWindow(this.getDomNode()), () => {
        hasPendingChangeContentHeight = false;
        this.Uc();
      }, 100));
    }));
    this.pb.add(this.hb.onDidRemoveOutputs((outputs) => {
      outputs.forEach((output) => this.removeInset(output));
    }));
    this.pb.add(this.hb.onDidHideOutputs((outputs) => {
      outputs.forEach((output) => this.hideInset(output));
    }));
    this.pb.add(this.hb.onDidRemoveCellsFromView((cells) => {
      const hiddenCells = [];
      const deletedCells = [];
      for (const cell of cells) {
        if (cell.cellKind === CellKind.Markup) {
          const mdCell = cell;
          if (this.viewModel?.viewCells.find((cell2) => cell2.handle === mdCell.handle)) {
            hiddenCells.push(mdCell);
          } else {
            deletedCells.push(mdCell);
          }
        }
      }
      this.hideMarkupPreviews(hiddenCells);
      this.deleteMarkupPreviews(deletedCells);
    }));
    await this.Ac(this.viewModel, viewState, perf2);
    perf2?.mark("customMarkdownLoaded");
    this.qb = this.viewModel.viewCells.map((cell) => this.xc(cell));
    this.yc = this.viewModel.viewCells.find((viewCell) => this.getActiveCell() === viewCell && viewCell.focusMode === CellFocusMode.Editor) ?? null;
    this.pb.add(this.viewModel.onDidChangeViewCells((e) => {
      if (this.Jb) {
        return;
      }
      [...e.splices].reverse().forEach((splice2) => {
        const [start, deleted, newCells] = splice2;
        const deletedCells = this.qb.splice(start, deleted, ...newCells.map((cell) => this.xc(cell)));
        $Xc(deletedCells);
      });
      if (e.splices.some((s) => s[2].some((cell) => cell.cellKind === CellKind.Markup))) {
        this.nc();
      }
    }));
    if (this.sb) {
      this.hb.layout(this.Fc(this.sb.height), this.sb.width);
    } else {
      this.hb.layout();
    }
    this.jb?.clearGlobalDragState();
    this.restoreListViewState(viewState);
  }
  xc(cell) {
    const store = new $2c();
    store.add(cell.onDidChangeLayout((e) => {
      if (e.totalHeight || e.outerWidth) {
        this.layoutNotebookCell(cell, cell.layoutInfo.totalHeight, e.context);
      }
    }));
    if (cell.cellKind === CellKind.Code) {
      store.add(cell.onDidRemoveOutputs((outputs) => {
        outputs.forEach((output) => this.removeInset(output));
      }));
    }
    store.add(cell.onDidChangeState((e) => {
      if (e.inputCollapsedChanged && cell.isInputCollapsed && cell.cellKind === CellKind.Markup) {
        this.hideMarkupPreviews([cell]);
      }
      if (e.outputCollapsedChanged && cell.isOutputCollapsed && cell.cellKind === CellKind.Code) {
        cell.outputsViewModels.forEach((output) => this.hideInset(output));
      }
      if (e.focusModeChanged) {
        this.zc(cell);
      }
    }));
    return store;
  }
  zc(cell) {
    if (cell.focusMode !== CellFocusMode.Editor) {
      return;
    }
    if (this.yc && this.yc !== cell) {
      this.yc.focusMode = CellFocusMode.Container;
    }
    this.yc = cell;
  }
  async Ac(viewModel, viewState, perf2) {
    this.Zb.debug("NotebookEditorWidget", "warmup " + this.viewModel?.uri.toString());
    await this.tc();
    perf2?.mark("webviewCommLoaded");
    this.Zb.debug("NotebookEditorWidget", "warmup - webview resolved");
    this.db.element.style.visibility = "hidden";
    await this.Bc(viewModel, viewState);
    this.Zb.debug("NotebookEditorWidget", "warmup - viewport warmed up");
    this.hb.layout(0, 0);
    this.hb.attachViewModel(viewModel);
    this.hb.scrollTop = viewState?.scrollPosition?.top ?? 0;
    this.ac("finish initial viewport warmup and view state restore.");
    this.db.element.style.visibility = "visible";
    this.Zb.debug("NotebookEditorWidget", "warmup - list view model attached, set to visible");
    this.m.fire();
  }
  async Bc(viewModel, viewState) {
    if (viewState && viewState.cellTotalHeights) {
      const totalHeightCache = viewState.cellTotalHeights;
      const scrollTop = viewState.scrollPosition?.top ?? 0;
      const scrollBottom = scrollTop + Math.max(this.sb?.height ?? 0, 1080);
      let offset = 0;
      const requests = [];
      for (let i2 = 0; i2 < viewModel.length; i2++) {
        const cell = viewModel.cellAt(i2);
        const cellHeight = totalHeightCache[i2] ?? 0;
        if (offset + cellHeight < scrollTop) {
          offset += cellHeight;
          continue;
        }
        if (cell.cellKind === CellKind.Markup) {
          requests.push([cell, offset]);
        }
        offset += cellHeight;
        if (offset > scrollBottom) {
          break;
        }
      }
      await this.db.initializeMarkup(requests.map(([model, offset2]) => this.Cc(model, offset2)));
    } else {
      const initRequests = viewModel.viewCells.filter((cell) => cell.cellKind === CellKind.Markup).slice(0, 5).map((cell) => this.Cc(cell, -1e4));
      await this.db.initializeMarkup(initRequests);
      let offset = 0;
      const offsetUpdateRequests = [];
      const scrollBottom = Math.max(this.sb?.height ?? 0, 1080);
      for (const cell of viewModel.viewCells) {
        if (cell.cellKind === CellKind.Markup) {
          offsetUpdateRequests.push({ id: cell.id, top: offset });
        }
        offset += cell.getHeight(this.getLayoutInfo().fontInfo.lineHeight);
        if (offset > scrollBottom) {
          break;
        }
      }
      this.db?.updateScrollTops([], offsetUpdateRequests);
    }
  }
  Cc(model, offset) {
    return {
      mime: model.mime,
      cellId: model.id,
      cellHandle: model.handle,
      content: model.getText(),
      offset,
      visible: false,
      metadata: model.metadata
    };
  }
  restoreListViewState(viewState) {
    if (!this.viewModel) {
      return;
    }
    if (viewState?.scrollPosition !== void 0) {
      this.hb.scrollTop = viewState.scrollPosition.top;
      this.hb.scrollLeft = viewState.scrollPosition.left;
    } else {
      this.hb.scrollTop = 0;
      this.hb.scrollLeft = 0;
    }
    const focusIdx = typeof viewState?.focus === "number" ? viewState.focus : 0;
    if (focusIdx < this.viewModel.length) {
      const element = this.viewModel.cellAt(focusIdx);
      if (element) {
        this.viewModel?.updateSelectionsState({
          kind: SelectionStateType.Handle,
          primary: element.handle,
          selections: [element.handle]
        });
      }
    } else if (this.hb.length > 0) {
      this.viewModel.updateSelectionsState({
        kind: SelectionStateType.Index,
        focus: { start: 0, end: 1 },
        selections: [{ start: 0, end: 1 }]
      });
    }
    if (viewState?.editorFocused) {
      const cell = this.viewModel.cellAt(focusIdx);
      if (cell) {
        cell.focusMode = CellFocusMode.Editor;
      }
    }
  }
  Dc(viewState) {
    if (viewState?.selectedKernelId && this.textModel) {
      const matching = this.Rb.getMatchingKernel(this.textModel);
      const kernel = matching.all.find((k) => k.id === viewState.selectedKernelId);
      if (kernel && !matching.selected) {
        this.Rb.selectKernelForNotebook(kernel, this.textModel);
      }
    }
  }
  getEditorViewState() {
    const state = this.viewModel?.getEditorViewState();
    if (!state) {
      return {
        editingCells: {},
        cellLineNumberStates: {},
        editorViewStates: {},
        collapsedInputCells: {},
        collapsedOutputCells: {}
      };
    }
    if (this.hb) {
      state.scrollPosition = { left: this.hb.scrollLeft, top: this.hb.scrollTop };
      const cellHeights = {};
      for (let i2 = 0; i2 < this.viewModel.length; i2++) {
        const elm = this.viewModel.cellAt(i2);
        cellHeights[i2] = elm.layoutInfo.totalHeight;
      }
      state.cellTotalHeights = cellHeights;
      if (this.viewModel) {
        const focusRange = this.viewModel.getFocus();
        const element = this.viewModel.cellAt(focusRange.start);
        if (element) {
          const itemDOM = this.hb.domElementOfElement(element);
          const editorFocused = element.getEditState() === CellEditState.Editing && !!(itemDOM && itemDOM.ownerDocument.activeElement && itemDOM.contains(itemDOM.ownerDocument.activeElement));
          state.editorFocused = editorFocused;
          state.focus = focusRange.start;
        }
      }
    }
    const contributionsState = {};
    for (const [id2, contribution] of this.Bb) {
      if (typeof contribution.saveViewState === "function") {
        contributionsState[id2] = contribution.saveViewState();
      }
    }
    state.contributionsState = contributionsState;
    if (this.textModel?.uri.scheme === Schemas.untitled) {
      state.selectedKernelId = this.activeKernel?.id;
    }
    return state;
  }
  Ec() {
    return this.Cb && !this.isReplHistory;
  }
  Fc(dimensionHeight) {
    return Math.max(dimensionHeight - (this.U?.useGlobalToolbar ? (
      /** Toolbar height */
      26
    ) : 0), 0);
  }
  layout(dimension, shadowElement, position) {
    if (!shadowElement && this.vb === null) {
      this.sb = dimension;
      this.tb = position;
      return;
    }
    if (dimension.width <= 0 || dimension.height <= 0) {
      this.onWillHide();
      return;
    }
    const whenContainerStylesLoaded = this.Ub.whenContainerStylesLoaded(getWindow(this.getDomNode()));
    if (whenContainerStylesLoaded) {
      whenContainerStylesLoaded.then(() => this.Gc(dimension, shadowElement, position));
    } else {
      this.Gc(dimension, shadowElement, position);
    }
  }
  Gc(dimension, shadowElement, position) {
    if (shadowElement) {
      this.Hc(shadowElement, dimension, position);
    }
    if (this.vb && this.vb.width <= 0 && this.vb.height <= 0) {
      this.onWillHide();
      return;
    }
    this.sb = dimension;
    this.tb = position;
    const newBodyHeight = this.Fc(dimension.height) - this.getLayoutInfo().stickyHeight;
    $tj(this.ab, dimension.width, newBodyHeight);
    const newCellListHeight = newBodyHeight;
    if (this.hb.getRenderHeight() < newCellListHeight) {
      this.hb.updateOptions({ paddingBottom: this.Ec() ? Math.max(0, newCellListHeight - 50) : 0, paddingTop: 0 });
      this.hb.layout(newCellListHeight, dimension.width);
    } else {
      this.hb.layout(newCellListHeight, dimension.width);
      this.hb.updateOptions({ paddingBottom: this.Ec() ? Math.max(0, newCellListHeight - 50) : 0, paddingTop: 0 });
    }
    this.R.inert = false;
    this.R.style.visibility = "visible";
    this.R.style.display = "block";
    this.R.style.position = "absolute";
    this.R.style.overflow = "hidden";
    this.Ic(dimension, position);
    if (this.fb) {
      this.fb.style.height = `${dimension.height}px`;
      this.fb.style.width = `${dimension.width}px`;
    }
    this.U.layout(this.sb);
    this.Z.layout();
    this.nb?.eventDispatcher.emit([new $irb({ width: true, fontInfo: true }, this.getLayoutInfo())]);
  }
  Hc(shadowElement, dimension, position) {
    this.ub = shadowElement;
    if (dimension && position) {
      this.vb = {
        height: dimension.height,
        width: dimension.width,
        top: position.top,
        left: position.left
      };
    } else {
      const containerRect = shadowElement.getBoundingClientRect();
      this.vb = {
        height: containerRect.height,
        width: containerRect.width,
        top: containerRect.top,
        left: containerRect.left
      };
    }
  }
  Ic(dimension, position) {
    if (dimension && position) {
      this.R.style.top = `${position.top}px`;
      this.R.style.left = `${position.left}px`;
      this.R.style.width = `${dimension.width}px`;
      this.R.style.height = `${dimension.height}px`;
      return;
    }
    if (!this.vb) {
      return;
    }
    const elementContainerRect = this.R.parentElement?.getBoundingClientRect();
    this.R.style.top = `${this.vb.top - (elementContainerRect?.top || 0)}px`;
    this.R.style.left = `${this.vb.left - (elementContainerRect?.left || 0)}px`;
    this.R.style.width = `${dimension ? dimension.width : this.vb.width}px`;
    this.R.style.height = `${dimension ? dimension.height : this.vb.height}px`;
  }
  //#endregion
  //#region Focus tracker
  focus() {
    this.Ib = true;
    this.wb.set(true);
    if (this.Hb) {
      this.db?.focusWebview();
    } else {
      if (this.viewModel) {
        const focusRange = this.viewModel.getFocus();
        const element = this.viewModel.cellAt(focusRange.start);
        if (!this.hasEditorFocus()) {
          this.focusContainer();
          this.updateEditorFocus();
        }
        if (element && element.focusMode === CellFocusMode.Editor) {
          element.updateEditState(CellEditState.Editing, "editorWidget.focus");
          element.focusMode = CellFocusMode.Editor;
          this.Jc(element);
          return;
        }
      }
      this.hb.domFocus();
    }
    if (this.Ob) {
      this.showProgress();
    }
  }
  onShow() {
    this.Ib = true;
  }
  Jc(activeElement) {
    for (const [element, editor] of this.lb.entries()) {
      if (element === activeElement) {
        editor.focus();
        return;
      }
    }
  }
  focusContainer(clearSelection = false) {
    if (this.Hb) {
      this.db?.focusWebview();
    } else {
      this.hb.focusContainer(clearSelection);
    }
  }
  selectOutputContent(cell) {
    this.db?.selectOutputContents(cell);
  }
  selectInputContents(cell) {
    this.db?.selectInputContents(cell);
  }
  onWillHide() {
    this.Ib = false;
    this.wb.set(false);
    this.R.inert = true;
    this.R.style.visibility = "hidden";
    this.R.style.left = "-50000px";
    this.S.style.display = "none";
    this.Kc();
  }
  Kc() {
    this.lb.forEach((editor, cell) => {
      if (this.getActiveCell() === cell && editor) {
        $qdb.get(editor)?.cancelSuggestWidget();
        $Yfb.get(editor)?.clearWidgets();
        $iab.get(editor)?.clearWidgets();
      }
    });
  }
  Lc() {
    return $Nj(this.getDomNode());
  }
  updateEditorFocus() {
    this.Gb.refreshState();
    const focused = this.Lc();
    this.wb.set(focused);
    this.viewModel?.setEditorFocus(focused);
  }
  updateCellFocusMode() {
    const activeCell = this.getActiveCell();
    if (activeCell?.focusMode === CellFocusMode.Output && !this.Hb) {
      activeCell.focusMode = CellFocusMode.Container;
    }
  }
  hasEditorFocus() {
    this.updateEditorFocus();
    return this.Lc();
  }
  hasWebviewFocus() {
    return this.Hb;
  }
  hasOutputTextSelection() {
    if (!this.hasEditorFocus()) {
      return false;
    }
    const windowSelection = getWindow(this.getDomNode()).getSelection();
    if (windowSelection?.rangeCount !== 1) {
      return false;
    }
    const activeSelection = windowSelection.getRangeAt(0);
    if (activeSelection.startContainer === activeSelection.endContainer && activeSelection.endOffset - activeSelection.startOffset === 0) {
      return false;
    }
    let container2 = activeSelection.commonAncestorContainer;
    if (!this.ab.contains(container2)) {
      return false;
    }
    while (container2 && container2 !== this.ab) {
      if (container2.classList && container2.classList.contains("output")) {
        return true;
      }
      container2 = container2.parentNode;
    }
    return false;
  }
  _didFocusOutputInputChange(hasFocus) {
    this.Ab.set(hasFocus);
  }
  //#endregion
  //#region Editor Features
  focusElement(cell) {
    this.viewModel?.updateSelectionsState({
      kind: SelectionStateType.Handle,
      primary: cell.handle,
      selections: [cell.handle]
    });
  }
  get scrollTop() {
    return this.hb.scrollTop;
  }
  get scrollBottom() {
    return this.hb.scrollTop + this.hb.getRenderHeight();
  }
  getAbsoluteTopOfElement(cell) {
    return this.hb.getCellViewScrollTop(cell);
  }
  getHeightOfElement(cell) {
    return this.hb.elementHeight(cell);
  }
  scrollToBottom() {
    this.hb.scrollToBottom();
  }
  setScrollTop(scrollTop) {
    this.hb.scrollTop = scrollTop;
  }
  revealCellRangeInView(range) {
    return this.hb.revealCells(range);
  }
  revealInView(cell) {
    return this.hb.revealCell(
      cell,
      1
      /* CellRevealType.Default */
    );
  }
  revealInViewAtTop(cell) {
    this.hb.revealCell(
      cell,
      2
      /* CellRevealType.Top */
    );
  }
  revealInCenter(cell) {
    this.hb.revealCell(
      cell,
      3
      /* CellRevealType.Center */
    );
  }
  async revealInCenterIfOutsideViewport(cell) {
    await this.hb.revealCell(
      cell,
      4
      /* CellRevealType.CenterIfOutsideViewport */
    );
  }
  async revealFirstLineIfOutsideViewport(cell) {
    await this.hb.revealCell(
      cell,
      6
      /* CellRevealType.FirstLineIfOutsideViewport */
    );
  }
  async revealLineInViewAsync(cell, line) {
    return this.hb.revealRangeInCell(cell, new $9C(line, 1, line, 1), CellRevealRangeType.Default);
  }
  async revealLineInCenterAsync(cell, line) {
    return this.hb.revealRangeInCell(cell, new $9C(line, 1, line, 1), CellRevealRangeType.Center);
  }
  async revealLineInCenterIfOutsideViewportAsync(cell, line) {
    return this.hb.revealRangeInCell(cell, new $9C(line, 1, line, 1), CellRevealRangeType.CenterIfOutsideViewport);
  }
  async revealRangeInViewAsync(cell, range) {
    return this.hb.revealRangeInCell(cell, range, CellRevealRangeType.Default);
  }
  async revealRangeInCenterAsync(cell, range) {
    return this.hb.revealRangeInCell(cell, range, CellRevealRangeType.Center);
  }
  async revealRangeInCenterIfOutsideViewportAsync(cell, range) {
    return this.hb.revealRangeInCell(cell, range, CellRevealRangeType.CenterIfOutsideViewport);
  }
  revealCellOffsetInCenter(cell, offset) {
    return this.hb.revealCellOffsetInCenter(cell, offset);
  }
  revealOffsetInCenterIfOutsideViewport(offset) {
    return this.hb.revealOffsetInCenterIfOutsideViewport(offset);
  }
  getViewIndexByModelIndex(index) {
    if (!this.ib) {
      return -1;
    }
    const cell = this.viewModel?.viewCells[index];
    if (!cell) {
      return -1;
    }
    return this.ib.getViewIndex(cell);
  }
  getViewHeight(cell) {
    if (!this.ib) {
      return -1;
    }
    return this.ib.getViewHeight(cell);
  }
  getCellRangeFromViewRange(startIndex, endIndex) {
    return this.ib.getCellRangeFromViewRange(startIndex, endIndex);
  }
  getCellsInRange(range) {
    return this.ib.getCellsInRange(range);
  }
  setCellEditorSelection(cell, range) {
    this.hb.setCellEditorSelection(cell, range);
  }
  setHiddenAreas(_ranges) {
    return this.hb.setHiddenAreas(_ranges, true);
  }
  getVisibleRangesPlusViewportAboveAndBelow() {
    return this.ib.getVisibleRangesPlusViewportAboveAndBelow();
  }
  //#endregion
  //#region Decorations
  deltaCellDecorations(oldDecorations, newDecorations) {
    const ret = this.viewModel?.deltaCellDecorations(oldDecorations, newDecorations) || [];
    this.r.fire();
    return ret;
  }
  deltaCellContainerClassNames(cellId, added, removed) {
    this.db?.deltaCellContainerClassNames(cellId, added, removed);
  }
  changeModelDecorations(callback) {
    return this.viewModel?.changeModelDecorations(callback) || null;
  }
  //#endregion
  //#region View Zones
  changeViewZones(callback) {
    this.hb.changeViewZones(callback);
  }
  //#endregion
  //#region Kernel/Execution
  async Mc() {
    if (!this.hasModel()) {
      return;
    }
    const { selected } = this.Rb.getMatchingKernel(this.textModel);
    if (!this.db?.isResolved()) {
      await this.tc();
    }
    this.db?.updateKernelPreloads(selected);
  }
  get activeKernel() {
    return this.textModel && this.Rb.getSelectedOrSuggestedKernel(this.textModel);
  }
  async cancelNotebookCells(cells) {
    if (!this.viewModel || !this.hasModel()) {
      return;
    }
    if (!cells) {
      cells = this.viewModel.viewCells;
    }
    return this.Xb.cancelNotebookCellHandles(this.textModel, Array.from(cells).map((cell) => cell.handle));
  }
  async executeNotebookCells(cells) {
    if (!this.viewModel || !this.hasModel()) {
      this.Zb.info("notebookEditorWidget", "No NotebookViewModel, cannot execute cells");
      return;
    }
    if (!cells) {
      cells = this.viewModel.viewCells;
    }
    return this.Xb.executeNotebookCells(this.textModel, Array.from(cells).map((c) => c.model), this.scopedContextKeyService);
  }
  async layoutNotebookCell(cell, height, context) {
    this.ac("layout cell", cell.handle, height);
    const viewIndex = this.hb.getViewIndex(cell);
    if (viewIndex === void 0) {
      return;
    }
    if (this.Nc?.has(cell)) {
      this.Nc?.get(cell).dispose();
    }
    const deferred = new $gi();
    const doLayout = () => {
      if (this.Jb) {
        return;
      }
      if (!this.viewModel?.hasCell(cell)) {
        return;
      }
      if (this.hb.getViewIndex(cell) === void 0) {
        return;
      }
      if (this.hb.elementHeight(cell) === height) {
        return;
      }
      this.Nc?.delete(cell);
      if (!this.hasEditorFocus()) {
        const cellIndex = this.viewModel?.getCellIndex(cell);
        const visibleRanges = this.visibleRanges;
        if (cellIndex !== void 0 && visibleRanges && visibleRanges.length && visibleRanges[0].start === cellIndex && this.hb.scrollTop > this.getAbsoluteTopOfElement(cell)) {
          return this.hb.updateElementHeight2(cell, height, Math.min(cellIndex + 1, this.getLength() - 1));
        }
      }
      this.hb.updateElementHeight2(cell, height);
      deferred.complete(void 0);
    };
    if (this.hb.inRenderingTransaction) {
      const layoutDisposable = $jj(getWindow(this.getDomNode()), doLayout);
      this.Nc?.set(cell, $1c(() => {
        layoutDisposable.dispose();
        deferred.complete(void 0);
      }));
    } else {
      doLayout();
    }
    return deferred.p;
  }
  getActiveCell() {
    const elements = this.hb.getFocusedElements();
    if (elements && elements.length) {
      return elements[0];
    }
    return void 0;
  }
  Oc(selectedCell, selectFromPrevious) {
    const currentSelections = this.hb.getSelectedElements();
    const isSelected = currentSelections.includes(selectedCell);
    const previousSelection = selectFromPrevious ? currentSelections[currentSelections.length - 1] ?? selectedCell : selectedCell;
    const selectedIndex = this.hb.getViewIndex(selectedCell);
    const previousIndex = this.hb.getViewIndex(previousSelection);
    const cellsInSelectionRange = this.Pc(selectedIndex, previousIndex);
    if (isSelected) {
      this.hb.selectElements(currentSelections.filter((current) => !cellsInSelectionRange.includes(current)));
    } else {
      this.focusElement(selectedCell);
      this.hb.selectElements([...currentSelections.filter((current) => !cellsInSelectionRange.includes(current)), ...cellsInSelectionRange]);
    }
  }
  Pc(fromInclusive, toInclusive) {
    const selectedCellsInRange = [];
    for (let index = 0; index < this.hb.length; ++index) {
      const cell = this.hb.element(index);
      if (cell) {
        if (index >= fromInclusive && index <= toInclusive || index >= toInclusive && index <= fromInclusive) {
          selectedCellsInRange.push(cell);
        }
      }
    }
    return selectedCellsInRange;
  }
  async focusNotebookCell(cell, focusItem, options3) {
    if (this.Jb) {
      return;
    }
    cell.focusedOutputId = void 0;
    if (focusItem === "editor") {
      cell.isInputCollapsed = false;
      this.focusElement(cell);
      this.hb.focusView();
      cell.updateEditState(CellEditState.Editing, "focusNotebookCell");
      cell.focusMode = CellFocusMode.Editor;
      if (!options3?.skipReveal) {
        if (typeof options3?.focusEditorLine === "number") {
          this.zb.set(true);
          await this.revealLineInViewAsync(cell, options3.focusEditorLine);
          const editor = this.lb.get(cell);
          const focusEditorLine = options3.focusEditorLine;
          editor?.setSelection({
            startLineNumber: focusEditorLine,
            startColumn: 1,
            endLineNumber: focusEditorLine,
            endColumn: 1
          });
        } else {
          const selectionsStartPosition = cell.getSelectionsStartPosition();
          if (selectionsStartPosition?.length) {
            const firstSelectionPosition = selectionsStartPosition[0];
            await this.revealRangeInViewAsync(cell, $9C.fromPositions(firstSelectionPosition, firstSelectionPosition));
          } else {
            await this.revealInView(cell);
          }
        }
      }
    } else if (focusItem === "output") {
      this.focusElement(cell);
      if (!this.hasEditorFocus()) {
        this.hb.focusView();
      }
      if (!this.db) {
        return;
      }
      const firstOutputId = cell.outputsViewModels.find((o) => o.model.alternativeOutputId)?.model.alternativeOutputId;
      const focusElementId = options3?.outputId ?? firstOutputId ?? cell.id;
      this.db.focusOutput(focusElementId, options3?.altOutputId, options3?.outputWebviewFocused || this.Hb);
      cell.updateEditState(CellEditState.Preview, "focusNotebookCell");
      cell.focusMode = CellFocusMode.Output;
      cell.focusedOutputId = options3?.outputId;
      this.xb.set(true);
      if (!options3?.skipReveal) {
        this.revealInCenterIfOutsideViewport(cell);
      }
    } else {
      const itemDOM = this.hb.domElementOfElement(cell);
      if (itemDOM && itemDOM.ownerDocument.activeElement && itemDOM.contains(itemDOM.ownerDocument.activeElement)) {
        itemDOM.ownerDocument.activeElement.blur();
      }
      this.db?.blurOutput();
      cell.updateEditState(CellEditState.Preview, "focusNotebookCell");
      cell.focusMode = CellFocusMode.Container;
      this.focusElement(cell);
      if (!options3?.skipReveal) {
        if (typeof options3?.focusEditorLine === "number") {
          this.zb.set(true);
          await this.revealInView(cell);
        } else if (options3?.revealBehavior === ScrollToRevealBehavior.firstLine) {
          await this.revealFirstLineIfOutsideViewport(cell);
        } else if (options3?.revealBehavior === ScrollToRevealBehavior.fullCell) {
          await this.revealInView(cell);
        } else {
          await this.revealInCenterIfOutsideViewport(cell);
        }
      }
      this.hb.focusView();
      this.updateEditorFocus();
    }
  }
  async focusNextNotebookCell(cell, focusItem) {
    const idx = this.viewModel?.getCellIndex(cell);
    if (typeof idx !== "number") {
      return;
    }
    const newCell = this.viewModel?.cellAt(idx + 1);
    if (!newCell) {
      return;
    }
    await this.focusNotebookCell(newCell, focusItem);
  }
  //#endregion
  //#region Find
  async Qc(viewCell) {
    if (viewCell.isOutputCollapsed) {
      return;
    }
    const outputs = viewCell.outputsViewModels;
    for (const output of outputs.slice(0, $WIb)) {
      const [mimeTypes, pick] = output.resolveMimeTypes(this.textModel, void 0);
      if (!mimeTypes.find((mimeType) => mimeType.isTrusted) || mimeTypes.length === 0) {
        continue;
      }
      const pickedMimeTypeRenderer = mimeTypes[pick];
      if (!pickedMimeTypeRenderer) {
        return;
      }
      const renderer = this.Sb.getRendererInfo(pickedMimeTypeRenderer.rendererId);
      if (!renderer) {
        return;
      }
      const result = { type: 1, renderer, source: output, mimeType: pickedMimeTypeRenderer.mimeType };
      const inset = this.db?.insetMapping.get(result.source);
      if (!inset || !inset.initialized) {
        const p = new Promise((resolve) => {
          this.B(Event2.any(this.N, this.P)((e) => {
            if (e.model === result.source.model) {
              resolve();
            }
          }));
        });
        this.createOutput(viewCell, result, 0, false);
        await p;
      } else {
        this.createOutput(viewCell, result, 0, false);
      }
      return;
    }
  }
  async Rc(includeOutput) {
    if (!this.hasModel() || !this.viewModel) {
      return;
    }
    const cells = this.viewModel.viewCells;
    const requests = [];
    for (let i2 = 0; i2 < cells.length; i2++) {
      if (cells[i2].cellKind === CellKind.Markup && !this.db.markupPreviewMapping.has(cells[i2].id)) {
        requests.push(this.createMarkupPreview(cells[i2]));
      }
    }
    if (includeOutput && this.hb) {
      for (let i2 = 0; i2 < this.hb.length; i2++) {
        const cell = this.hb.element(i2);
        if (cell?.cellKind === CellKind.Code) {
          requests.push(this.Qc(cell));
        }
      }
    }
    return Promise.all(requests);
  }
  async find(query, options3, token, skipWarmup = false, shouldGetSearchPreviewInfo = false, ownerID) {
    if (!this.ob) {
      return [];
    }
    if (!ownerID) {
      ownerID = this.getId();
    }
    const findMatches = this.ob.find(query, options3).filter((match) => match.length > 0);
    if (!options3.includeMarkupPreview && !options3.includeOutput || options3.findScope?.findScopeType === NotebookFindScopeType.Text) {
      this.db?.findStop(ownerID);
      return findMatches;
    }
    const matchMap = {};
    findMatches.forEach((match) => {
      matchMap[match.cell.id] = match;
    });
    if (this.db) {
      const start = Date.now();
      await this.Rc(!!options3.includeOutput);
      const end = Date.now();
      this.Zb.debug("Find", `Warmup time: ${end - start}ms`);
      if (token.isCancellationRequested) {
        return [];
      }
      let findIds = [];
      if (options3.findScope && options3.findScope.findScopeType === NotebookFindScopeType.Cells && options3.findScope.selectedCellRanges) {
        const selectedIndexes = $GL(options3.findScope.selectedCellRanges);
        findIds = selectedIndexes.map((index) => this.ob?.viewCells[index].id ?? "");
      }
      const webviewMatches = await this.db.find(query, { caseSensitive: options3.caseSensitive, wholeWord: options3.wholeWord, includeMarkup: !!options3.includeMarkupPreview, includeOutput: !!options3.includeOutput, shouldGetSearchPreviewInfo, ownerID, findIds });
      if (token.isCancellationRequested) {
        return [];
      }
      webviewMatches.forEach((match) => {
        const cell = this.ob.viewCells.find((cell2) => cell2.id === match.cellId);
        if (!cell) {
          return;
        }
        if (match.type === "preview") {
          if (cell.getEditState() === CellEditState.Preview && !options3.includeMarkupPreview) {
            return;
          }
          if (cell.getEditState() === CellEditState.Editing && options3.includeMarkupInput) {
            return;
          }
        } else {
          if (!options3.includeOutput) {
            return;
          }
        }
        const exisitingMatch = matchMap[match.cellId];
        if (exisitingMatch) {
          exisitingMatch.webviewMatches.push(match);
        } else {
          matchMap[match.cellId] = new $OIb(this.ob.viewCells.find((cell2) => cell2.id === match.cellId), this.ob.viewCells.findIndex((cell2) => cell2.id === match.cellId), [], [match]);
        }
      });
    }
    const ret = [];
    this.ob.viewCells.forEach((cell, index) => {
      if (matchMap[cell.id]) {
        ret.push(new $OIb(cell, index, matchMap[cell.id].contentMatches, matchMap[cell.id].webviewMatches));
      }
    });
    return ret;
  }
  async findHighlightCurrent(matchIndex, ownerID) {
    if (!this.db) {
      return 0;
    }
    return this.db?.findHighlightCurrent(matchIndex, ownerID ?? this.getId());
  }
  async findUnHighlightCurrent(matchIndex, ownerID) {
    if (!this.db) {
      return;
    }
    return this.db?.findUnHighlightCurrent(matchIndex, ownerID ?? this.getId());
  }
  findStop(ownerID) {
    this.db?.findStop(ownerID ?? this.getId());
  }
  //#endregion
  //#region MISC
  getLayoutInfo() {
    if (!this.hb) {
      throw new Error("Editor is not initalized successfully");
    }
    if (!this.rb) {
      this.cc();
    }
    return {
      width: this.sb?.width ?? 0,
      height: this.sb?.height ?? 0,
      scrollHeight: this.hb?.getScrollHeight() ?? 0,
      fontInfo: this.rb,
      stickyHeight: this.X?.getCurrentStickyHeight() ?? 0
    };
  }
  async createMarkupPreview(cell) {
    if (!this.db) {
      return;
    }
    if (!this.db.isResolved()) {
      await this.tc();
    }
    if (!this.db || !this.hb.webviewElement) {
      return;
    }
    if (!this.viewModel || !this.hb.viewModel) {
      return;
    }
    if (this.viewModel.getCellIndex(cell) === -1) {
      return;
    }
    if (this.Sc(cell)) {
      return;
    }
    const webviewTop = parseInt(this.hb.webviewElement.domNode.style.top, 10);
    const top2 = !!webviewTop ? 0 - webviewTop : 0;
    const cellTop = this.hb.getCellViewScrollTop(cell);
    await this.db.showMarkupPreview({
      mime: cell.mime,
      cellHandle: cell.handle,
      cellId: cell.id,
      content: cell.getText(),
      offset: cellTop + top2,
      visible: true,
      metadata: cell.metadata
    });
  }
  Sc(cell) {
    const modelIndex = this.viewModel.getCellIndex(cell);
    const foldedRanges = this.viewModel.getHiddenRanges();
    return foldedRanges.some((range) => modelIndex >= range.start && modelIndex <= range.end);
  }
  async unhideMarkupPreviews(cells) {
    if (!this.db) {
      return;
    }
    if (!this.db.isResolved()) {
      await this.tc();
    }
    await this.db?.unhideMarkupPreviews(cells.map((cell) => cell.id));
  }
  async hideMarkupPreviews(cells) {
    if (!this.db || !cells.length) {
      return;
    }
    if (!this.db.isResolved()) {
      await this.tc();
    }
    await this.db?.hideMarkupPreviews(cells.map((cell) => cell.id));
  }
  async deleteMarkupPreviews(cells) {
    if (!this.db) {
      return;
    }
    if (!this.db.isResolved()) {
      await this.tc();
    }
    await this.db?.deleteMarkupPreviews(cells.map((cell) => cell.id));
  }
  async Tc() {
    if (!this.db) {
      return;
    }
    if (!this.db.isResolved()) {
      await this.tc();
    }
    const selectedCells = this.getSelectionViewModels().map((cell) => cell.id);
    await this.db?.updateMarkupPreviewSelections(selectedCells.length > 1 ? selectedCells : []);
  }
  async createOutput(cell, output, offset, createWhenIdle) {
    this.Db.queue(output.source.model.outputId, async () => {
      if (this.Jb || !this.db) {
        return;
      }
      if (!this.db.isResolved()) {
        await this.tc();
      }
      if (!this.db) {
        return;
      }
      if (!this.hb.webviewElement) {
        return;
      }
      if (output.type === 1) {
        this.Pb.prepare(output.renderer.id);
      }
      const webviewTop = parseInt(this.hb.webviewElement.domNode.style.top, 10);
      const top2 = !!webviewTop ? 0 - webviewTop : 0;
      const cellTop = this.hb.getCellViewScrollTop(cell) + top2;
      const existingOutput = this.db.insetMapping.get(output.source);
      if (!existingOutput || !existingOutput.renderer && output.type === 1) {
        if (createWhenIdle) {
          this.db.requestCreateOutputWhenWebviewIdle({ cellId: cell.id, cellHandle: cell.handle, cellUri: cell.uri, executionId: cell.internalMetadata.executionId }, output, cellTop, offset);
        } else {
          this.db.createOutput({ cellId: cell.id, cellHandle: cell.handle, cellUri: cell.uri, executionId: cell.internalMetadata.executionId }, output, cellTop, offset);
        }
      } else if (existingOutput.renderer && output.type === 1 && existingOutput.renderer.id !== output.renderer.id) {
        this.db.removeInsets([output.source]);
        this.db.createOutput({ cellId: cell.id, cellHandle: cell.handle, cellUri: cell.uri }, output, cellTop, offset);
      } else if (existingOutput.versionId !== output.source.model.versionId) {
        this.db.updateOutput({ cellId: cell.id, cellHandle: cell.handle, cellUri: cell.uri, executionId: cell.internalMetadata.executionId }, output, cellTop, offset);
      } else {
        const outputIndex = cell.outputsViewModels.indexOf(output.source);
        const outputOffset = cell.getOutputOffset(outputIndex);
        this.db.updateScrollTops([{
          cell,
          output: output.source,
          cellTop,
          outputOffset,
          forceDisplay: !cell.isOutputCollapsed
        }], []);
      }
    });
  }
  async updateOutput(cell, output, offset) {
    this.Db.queue(output.source.model.outputId, async () => {
      if (this.Jb || !this.db || cell.isOutputCollapsed) {
        return;
      }
      if (!this.db.isResolved()) {
        await this.tc();
      }
      if (!this.db || !this.hb.webviewElement) {
        return;
      }
      if (!this.db.insetMapping.has(output.source)) {
        return this.createOutput(cell, output, offset, false);
      }
      if (output.type === 1) {
        this.Pb.prepare(output.renderer.id);
      }
      const webviewTop = parseInt(this.hb.webviewElement.domNode.style.top, 10);
      const top2 = !!webviewTop ? 0 - webviewTop : 0;
      const cellTop = this.hb.getCellViewScrollTop(cell) + top2;
      this.db.updateOutput({ cellId: cell.id, cellHandle: cell.handle, cellUri: cell.uri }, output, cellTop, offset);
    });
  }
  async copyOutputImage(cellOutput) {
    this.db?.copyImage(cellOutput);
  }
  removeInset(output) {
    this.Db.queue(output.model.outputId, async () => {
      if (this.Jb || !this.db) {
        return;
      }
      if (this.db?.isResolved()) {
        this.db.removeInsets([output]);
      }
      this.O.fire(output);
    });
  }
  hideInset(output) {
    this.Db.queue(output.model.outputId, async () => {
      if (this.Jb || !this.db) {
        return;
      }
      if (this.db?.isResolved()) {
        this.db.hideInset(output);
      }
    });
  }
  //#region --- webview IPC ----
  postMessage(message) {
    if (this.db?.isResolved()) {
      this.db.postKernelMessage(message);
    }
  }
  //#endregion
  addClassName(className) {
    this.R.classList.add(className);
  }
  removeClassName(className) {
    this.R.classList.remove(className);
  }
  cellAt(index) {
    return this.viewModel?.cellAt(index);
  }
  getCellByInfo(cellInfo) {
    const { cellHandle } = cellInfo;
    return this.viewModel?.viewCells.find((vc) => vc.handle === cellHandle);
  }
  getCellByHandle(handle2) {
    return this.viewModel?.getCellByHandle(handle2);
  }
  getCellIndex(cell) {
    return this.viewModel?.getCellIndexByHandle(cell.handle);
  }
  getNextVisibleCellIndex(index) {
    return this.viewModel?.getNextVisibleCellIndex(index);
  }
  getPreviousVisibleCellIndex(index) {
    return this.viewModel?.getPreviousVisibleCellIndex(index);
  }
  Uc() {
    if (this.Jb || !this.db?.isResolved()) {
      return;
    }
    if (!this.hb.webviewElement) {
      return;
    }
    const scrollHeight = this.hb.scrollHeight;
    this.db.element.style.height = `${scrollHeight + $xJb * 2}px`;
    const webviewTop = parseInt(this.hb.webviewElement.domNode.style.top, 10);
    const top2 = !!webviewTop ? 0 - webviewTop : 0;
    const updateItems = [];
    const removedItems = [];
    this.db?.insetMapping.forEach((value, key2) => {
      const cell = this.viewModel?.getCellByHandle(value.cellInfo.cellHandle);
      if (!cell || !(cell instanceof $XIb)) {
        return;
      }
      this.viewModel?.viewCells.find((cell2) => cell2.handle === value.cellInfo.cellHandle);
      const viewIndex = this.hb.getViewIndex(cell);
      if (viewIndex === void 0) {
        return;
      }
      if (cell.outputsViewModels.indexOf(key2) < 0) {
        removedItems.push(key2);
      }
      const cellTop = this.hb.getCellViewScrollTop(cell);
      const outputIndex = cell.outputsViewModels.indexOf(key2);
      const outputOffset = cell.getOutputOffset(outputIndex);
      updateItems.push({
        cell,
        output: key2,
        cellTop: cellTop + top2,
        outputOffset,
        forceDisplay: false
      });
    });
    this.db.removeInsets(removedItems);
    const markdownUpdateItems = [];
    for (const cellId of this.db.markupPreviewMapping.keys()) {
      const cell = this.viewModel?.viewCells.find((cell2) => cell2.id === cellId);
      if (cell) {
        const cellTop = this.hb.getCellViewScrollTop(cell);
        markdownUpdateItems.push({ id: cellId, top: cellTop + top2 });
      }
    }
    if (markdownUpdateItems.length || updateItems.length) {
      this.ac("_list.onDidChangeContentHeight/markdown", markdownUpdateItems);
      this.db?.updateScrollTops(updateItems, markdownUpdateItems);
    }
  }
  //#endregion
  //#region BacklayerWebview delegate
  Vc(cellInfo, output, outputHeight, isInit, source) {
    const cell = this.viewModel?.viewCells.find((vc) => vc.handle === cellInfo.cellHandle);
    if (cell && cell instanceof $XIb) {
      const outputIndex = cell.outputsViewModels.indexOf(output);
      if (outputIndex > -1) {
        this.ac("update cell output", cell.handle, outputHeight);
        cell.updateOutputHeight(outputIndex, outputHeight, source);
        this.layoutNotebookCell(cell, cell.layoutInfo.totalHeight);
        if (isInit) {
          this.M.fire(output);
        }
      } else {
        this.ac("tried to update cell output that does not exist");
      }
    }
  }
  Xc(cellInfo, outputId, height) {
    const wasEmpty = this.Wc.size === 0;
    this.Wc.set(outputId, { cellId: cellInfo.cellId, outputId, height });
    if (wasEmpty) {
      $jj(getWindow(this.getDomNode()), () => {
        this.ac("ack height");
        this.Uc();
        this.db?.ackHeight([...this.Wc.values()]);
        this.Wc.clear();
      }, -1);
    }
  }
  Yc(cellId) {
    return this.viewModel?.viewCells.find((vc) => vc.id === cellId);
  }
  Zc(cellId, height, isInit) {
    const cell = this.Yc(cellId);
    if (cell && cell instanceof $YIb) {
      const { bottomToolbarGap } = this.Nb.computeBottomToolbarDimensions(this.viewModel?.viewType);
      this.ac("updateMarkdownCellHeight", cell.handle, height + bottomToolbarGap, isInit);
      cell.renderedMarkdownHeight = height;
    }
  }
  $c(cellId, editState) {
    const cell = this.Yc(cellId);
    if (cell instanceof $YIb) {
      this.revealInView(cell);
      cell.updateEditState(editState, "setMarkdownCellEditState");
    }
  }
  ad(cellId, event) {
    const cell = this.Yc(cellId);
    if (cell instanceof $YIb) {
      const webviewOffset = this.hb.webviewElement ? -parseInt(this.hb.webviewElement.domNode.style.top, 10) : 0;
      this.jb?.startExplicitDrag(cell, event.dragOffsetY - webviewOffset);
    }
  }
  bd(cellId, event) {
    const cell = this.Yc(cellId);
    if (cell instanceof $YIb) {
      const webviewOffset = this.hb.webviewElement ? -parseInt(this.hb.webviewElement.domNode.style.top, 10) : 0;
      this.jb?.explicitDrag(cell, event.dragOffsetY - webviewOffset);
    }
  }
  cd(cellId, event) {
    const cell = this.Yc(cellId);
    if (cell instanceof $YIb) {
      const webviewOffset = this.hb.webviewElement ? -parseInt(this.hb.webviewElement.domNode.style.top, 10) : 0;
      event.dragOffsetY -= webviewOffset;
      this.jb?.explicitDrop(cell, event);
    }
  }
  dd(cellId) {
    const cell = this.Yc(cellId);
    if (cell instanceof $YIb) {
      this.jb?.endExplicitDrag(cell);
    }
  }
  ed(cellId) {
    const cell = this.Yc(cellId);
    if (cell) {
      this.Q.fire(cell);
    }
  }
  fd(cellId, executionId, duration, rendererId) {
    if (!this.hasModel()) {
      return;
    }
    const cell = this.Yc(cellId);
    const cellIndex = !cell ? void 0 : this.getCellIndex(cell);
    if (cell?.internalMetadata.executionId === executionId && cellIndex !== void 0) {
      const renderDurationMap = cell.internalMetadata.renderDuration || {};
      renderDurationMap[rendererId] = (renderDurationMap[rendererId] ?? 0) + duration;
      this.textModel.applyEdits([
        {
          editType: 9,
          index: cellIndex,
          internalMetadata: {
            executionId,
            renderDuration: renderDurationMap
          }
        }
      ], true, void 0, () => void 0, void 0, false);
    }
  }
  //#endregion
  //#region Editor Contributions
  getContribution(id2) {
    return this.Bb.get(id2) || null;
  }
  //#endregion
  dispose() {
    this.Jb = true;
    this.db?.dispose();
    this.db = null;
    this.Qb.removeNotebookEditor(this);
    $Xc(this.Bb.values());
    this.Bb.clear();
    this.pb.clear();
    $Xc(this.qb);
    this.hb.dispose();
    this.kb?.dispose();
    this.R.remove();
    this.viewModel?.dispose();
    this.lb.clear();
    this.Kb.forEach((v) => v.dispose());
    this.Kb.clear();
    this.Y.remove();
    super.dispose();
    this.db = null;
    this.eb = null;
    this.fb = null;
    this.jb = null;
    this.kb = null;
    this.ob = void 0;
    this.Eb = null;
    this.U = null;
    this.hb = null;
    this.ib = null;
    this.Nc = null;
    this.gb = null;
  }
  toJSON() {
    return {
      notebookUri: this.viewModel?.uri
    };
  }
};
$aMb = __decorate([
  __param(2, $Pk),
  __param(3, $iJ),
  __param(4, $CJb),
  __param(5, $yMb),
  __param(6, $CL),
  __param(7, $mrb),
  __param(8, $kl),
  __param(9, $on),
  __param(10, $Ulb),
  __param(11, $50),
  __param(12, $zv),
  __param(13, $vL),
  __param(14, $ZJ),
  __param(15, $qFb)
], $aMb);
$uFb(ZIndex.Base, 5, "notebook-progress-bar");
$uFb(ZIndex.Base, 10, "notebook-list-insertion-indicator");
$uFb(ZIndex.Base, 20, "notebook-cell-editor-outline");
$uFb(ZIndex.Base, 25, "notebook-scrollbar");
$uFb(ZIndex.Base, 26, "notebook-cell-status");
$uFb(ZIndex.Base, 26, "notebook-folding-indicator");
$uFb(ZIndex.Base, 27, "notebook-output");
$uFb(ZIndex.Base, 28, "notebook-cell-bottom-toolbar-container");
$uFb(ZIndex.Base, 29, "notebook-run-button-container");
$uFb(ZIndex.Base, 29, "notebook-input-collapse-condicon");
$uFb(ZIndex.Base, 30, "notebook-cell-output-toolbar");
$uFb(ZIndex.Sash, 1, "notebook-cell-expand-part-button");
$uFb(ZIndex.Sash, 2, "notebook-cell-toolbar");
$uFb(ZIndex.Sash, 3, "notebook-cell-toolbar-dropdown-active");
var $bMb = $5n("notebook.cellBorderColor", {
  dark: $0n($lr, 1),
  light: $0n($lr, 1),
  hcDark: $Jmb,
  hcLight: $Jmb
}, localize(8485, null));
var $cMb = $5n("notebook.focusedEditorBorder", $jo, localize(8486, null));
var $dMb = $5n("notebookStatusSuccessIcon.foreground", $gGb, localize(8487, null));
var $eMb = $5n("notebookEditorOverviewRuler.runningCellForeground", $gGb, localize(8488, null));
var $fMb = $5n("notebookStatusErrorIcon.foreground", $go, localize(8489, null));
var $gMb = $5n("notebookStatusRunningIcon.foreground", $eo, localize(8490, null));
var $hMb = $5n("notebook.outputContainerBorderColor", null, localize(8491, null));
var $iMb = $5n("notebook.outputContainerBackgroundColor", null, localize(8492, null));
var $jMb = $5n("notebook.cellToolbarSeparator", {
  dark: $Vn.fromHex("#808080").transparent(0.35),
  light: $Vn.fromHex("#808080").transparent(0.35),
  hcDark: $ko,
  hcLight: $ko
}, localize(8493, null));
var $kMb = $5n("notebook.focusedCellBackground", null, localize(8494, null));
var $lMb = $5n("notebook.selectedCellBackground", {
  dark: $lr,
  light: $lr,
  hcDark: null,
  hcLight: null
}, localize(8495, null));
var $mMb = $5n("notebook.cellHoverBackground", {
  dark: $0n($kMb, 0.5),
  light: $0n($kMb, 0.7),
  hcDark: null,
  hcLight: null
}, localize(8496, null));
var $nMb = $5n("notebook.selectedCellBorder", {
  dark: $bMb,
  light: $bMb,
  hcDark: $ko,
  hcLight: $ko
}, localize(8497, null));
var $oMb = $5n("notebook.inactiveSelectedCellBorder", {
  dark: null,
  light: null,
  hcDark: $jo,
  hcLight: $jo
}, localize(8498, null));
var $pMb = $5n("notebook.focusedCellBorder", $jo, localize(8499, null));
var $qMb = $5n("notebook.inactiveFocusedCellBorder", $bMb, localize(8500, null));
var $rMb = $5n("notebook.cellStatusBarItemHoverBackground", {
  light: new $Vn(new $Sn(0, 0, 0, 0.08)),
  dark: new $Vn(new $Sn(255, 255, 255, 0.15)),
  hcDark: new $Vn(new $Sn(255, 255, 255, 0.15)),
  hcLight: new $Vn(new $Sn(0, 0, 0, 0.08))
}, localize(8501, null));
var $sMb = $5n("notebook.cellInsertionIndicator", $jo, localize(8502, null));
var $tMb = $5n("notebookScrollbarSlider.background", $Do, localize(8503, null));
var $uMb = $5n("notebookScrollbarSlider.hoverBackground", $Eo, localize(8504, null));
var $vMb = $5n("notebookScrollbarSlider.activeBackground", $Fo, localize(8505, null));
var $wMb = $5n("notebook.symbolHighlightBackground", {
  dark: $Vn.fromHex("#ffffff0b"),
  light: $Vn.fromHex("#fdff0033"),
  hcDark: null,
  hcLight: null
}, localize(8506, null));
var $xMb = $5n("notebook.cellEditorBackground", {
  light: $Pnb,
  dark: $Pnb,
  hcDark: null,
  hcLight: null
}, localize(8507, null));
var notebookEditorBackground = $5n("notebook.editorBackground", {
  light: $umb,
  dark: $umb,
  hcDark: null,
  hcLight: null
}, localize(8508, null));

// out-build/vs/workbench/contrib/notebook/browser/diff/diffElementOutputs.js
var $h2b = class extends $3c {
  constructor(b, c, f, g, h3, j, m, n, output) {
    super();
    this.b = b;
    this.c = c;
    this.f = f;
    this.g = g;
    this.h = h3;
    this.j = j;
    this.m = m;
    this.n = n;
    this.output = output;
    this.resizeListener = this.B(new $2c());
  }
  render(index, beforeElement) {
    const outputItemDiv = document.createElement("div");
    let result = void 0;
    const [mimeTypes, pick] = this.output.resolveMimeTypes(this.c, void 0);
    const pickedMimeTypeRenderer = this.output.pickedMimeType || mimeTypes[pick];
    if (mimeTypes.length > 1) {
      outputItemDiv.style.position = "relative";
      const mimeTypePicker = $(".multi-mimetype-output");
      mimeTypePicker.classList.add(...ThemeIcon.asClassNameArray($YKb));
      mimeTypePicker.tabIndex = 0;
      mimeTypePicker.title = localize(8364, null, mimeTypes.map((mimeType) => mimeType.mimeType).join(", "));
      outputItemDiv.appendChild(mimeTypePicker);
      this.resizeListener.add($aj(mimeTypePicker, "mousedown", async (e) => {
        if (e.leftButton) {
          e.preventDefault();
          e.stopPropagation();
          await this.u(this.c, this.output);
        }
      }));
      this.resizeListener.add($_i(mimeTypePicker, $7j.KEY_DOWN, async (e) => {
        const event = new $if(e);
        if (event.equals(
          3
          /* KeyCode.Enter */
        ) || event.equals(
          10
          /* KeyCode.Space */
        )) {
          e.preventDefault();
          e.stopPropagation();
          await this.u(this.c, this.output);
        }
      }));
    }
    const innerContainer = $(".output-inner-container");
    $bk(outputItemDiv, innerContainer);
    if (mimeTypes.length !== 0) {
      const renderer = this.f.getRendererInfo(pickedMimeTypeRenderer.rendererId);
      result = renderer ? { type: 1, renderer, source: this.output, mimeType: pickedMimeTypeRenderer.mimeType } : this.r(this.output, pickedMimeTypeRenderer.mimeType);
      this.output.pickedMimeType = pickedMimeTypeRenderer;
    }
    this.domNode = outputItemDiv;
    this.renderResult = result;
    if (!result) {
      return;
    }
    if (beforeElement) {
      this.n.insertBefore(outputItemDiv, beforeElement);
    } else {
      this.n.appendChild(outputItemDiv);
    }
    this.b.createOutput(this.h, this.m, result, () => this.getOutputOffsetInCell(index), this.h instanceof $oEb ? this.j : this.h.type === "insert" ? DiffSide.Modified : DiffSide.Original);
  }
  r(viewModel, preferredMimeType) {
    if (!viewModel.model.outputs.length) {
      return this.t(viewModel, localize(8365, null));
    }
    if (!preferredMimeType) {
      const mimeTypes = viewModel.model.outputs.map((op) => op.mime);
      const mimeTypesMessage = mimeTypes.join(", ");
      return this.t(viewModel, localize(8366, null, mimeTypesMessage));
    }
    return this.s(viewModel, preferredMimeType);
  }
  s(viewModel, mimeType) {
    const query = `@tag:notebookRenderer ${mimeType}`;
    const p = $("p", void 0, `No renderer could be found for mimetype "${mimeType}", but one might be available on the Marketplace.`);
    const a = $("a", { href: `command:workbench.extensions.search?%22${query}%22`, class: "monaco-button monaco-text-button", tabindex: 0, role: "button", style: "padding: 8px; text-decoration: none; color: rgb(255, 255, 255); background-color: rgb(14, 99, 156); max-width: 200px;" }, `Search Marketplace`);
    return {
      type: 0,
      source: viewModel,
      htmlContent: p.outerHTML + a.outerHTML
    };
  }
  t(viewModel, message) {
    const el = $("p", void 0, message);
    return { type: 0, source: viewModel, htmlContent: el.outerHTML };
  }
  async u(notebookTextModel, viewModel) {
    const [mimeTypes, currIndex] = viewModel.resolveMimeTypes(notebookTextModel, void 0);
    const items = mimeTypes.filter((mimeType) => mimeType.isTrusted).map((mimeType, index) => ({
      label: mimeType.mimeType,
      id: mimeType.mimeType,
      index,
      picked: index === currIndex,
      detail: this.w(mimeType.rendererId),
      description: index === currIndex ? localize(8367, null) : void 0
    }));
    const disposables = new $2c();
    const picker = disposables.add(this.g.createQuickPick());
    picker.items = items;
    picker.activeItems = items.filter((item) => !!item.picked);
    picker.placeholder = items.length !== mimeTypes.length ? localize(8368, null) : localize(8369, null);
    const pick = await new Promise((resolve) => {
      disposables.add(picker.onDidAccept(() => {
        resolve(picker.selectedItems.length === 1 ? picker.selectedItems[0].index : void 0);
        disposables.dispose();
      }));
      picker.show();
    });
    if (pick === void 0) {
      return;
    }
    if (pick !== currIndex) {
      const index = this.m.outputsViewModels.indexOf(viewModel);
      const nextElement = this.domNode.nextElementSibling;
      this.resizeListener.clear();
      const element = this.domNode;
      if (element) {
        element.remove();
        this.b.removeInset(this.h, this.m, viewModel, this.j);
      }
      viewModel.pickedMimeType = mimeTypes[pick];
      this.render(index, nextElement);
    }
  }
  w(renderId) {
    const renderInfo = this.f.getRendererInfo(renderId);
    if (renderInfo) {
      const displayName = renderInfo.displayName !== "" ? renderInfo.displayName : renderInfo.id;
      return `${displayName} (${renderInfo.extensionId.value})`;
    }
    return localize(8370, null);
  }
  getCellOutputCurrentIndex() {
    return this.h.getNestedCellViewModel(this.j).outputs.indexOf(this.output.model);
  }
  updateHeight(index, height) {
    this.h.updateOutputHeight(this.j, index, height);
  }
  getOutputOffsetInContainer(index) {
    return this.h.getOutputOffsetInContainer(this.j, index);
  }
  getOutputOffsetInCell(index) {
    return this.h.getOutputOffsetInCell(this.j, index);
  }
};
var $i2b = class $i2b2 extends $3c {
  constructor(c, f, g, h3, j, m, n, r2) {
    super();
    this.c = c;
    this.f = f;
    this.g = g;
    this.h = h3;
    this.j = j;
    this.m = m;
    this.n = n;
    this.r = r2;
    this.b = /* @__PURE__ */ new Map();
    this.B(this.g.onDidLayoutChange(() => {
      this.b.forEach((value, key2) => {
        const index = h3.outputs.indexOf(key2.model);
        if (index >= 0) {
          const top2 = this.g.getOutputOffsetInContainer(this.j, index);
          value.domNode.style.top = `${top2}px`;
        }
      });
    }));
    this.B(this.h.textModel.onDidChangeOutputs((splice2) => {
      this.s(splice2);
    }));
  }
  s(splice2) {
    const removedKeys = [];
    this.b.forEach((value, key2) => {
      if (this.h.outputsViewModels.indexOf(key2) < 0) {
        removedKeys.push(key2);
        value.domNode.remove();
        this.c.removeInset(this.g, this.h, key2, this.j);
      }
    });
    removedKeys.forEach((key2) => {
      this.b.get(key2)?.dispose();
      this.b.delete(key2);
    });
    let prevElement = void 0;
    const outputsToRender = this.h.outputsViewModels;
    outputsToRender.reverse().forEach((output) => {
      if (this.b.has(output)) {
        prevElement = this.b.get(output).domNode;
        return;
      }
      const currIndex = this.h.outputsViewModels.indexOf(output);
      this.t(output, currIndex, prevElement);
      prevElement = this.b.get(output)?.domNode;
    });
  }
  render() {
    for (let index = 0; index < this.h.outputsViewModels.length; index++) {
      const currOutput = this.h.outputsViewModels[index];
      this.t(currOutput, index, void 0);
    }
  }
  showOutputs() {
    for (let index = 0; index < this.h.outputsViewModels.length; index++) {
      const currOutput = this.h.outputsViewModels[index];
      this.c.showInset(this.g, currOutput.cellViewModel, currOutput, this.j);
    }
  }
  hideOutputs() {
    this.b.forEach((outputElement, cellOutputViewModel) => {
      this.c.hideInset(this.g, this.h, cellOutputViewModel);
    });
  }
  t(currOutput, index, beforeElement) {
    if (!this.b.has(currOutput)) {
      this.b.set(currOutput, new $h2b(this.c, this.f, this.n, this.r, this.g, this.j, this.h, this.m, currOutput));
    }
    const renderElement = this.b.get(currOutput);
    renderElement.render(index, beforeElement);
  }
};
$i2b = __decorate([
  __param(6, $mrb),
  __param(7, $1M)
], $i2b);

// out-build/vs/workbench/contrib/notebook/browser/diff/unchangedEditorRegions.js
function $j2b(configurationService) {
  return createHideUnchangedRegionOptions(configurationService);
}
function createHideUnchangedRegionOptions(configurationService) {
  const disposables = new $2c();
  const unchangedRegionsEnablementEmitter = disposables.add(new $ze());
  const result = {
    options: {
      enabled: configurationService.getValue("diffEditor.hideUnchangedRegions.enabled"),
      minimumLineCount: configurationService.getValue("diffEditor.hideUnchangedRegions.minimumLineCount"),
      contextLineCount: configurationService.getValue("diffEditor.hideUnchangedRegions.contextLineCount"),
      revealLineCount: configurationService.getValue("diffEditor.hideUnchangedRegions.revealLineCount")
    },
    // We only care about enable/disablement.
    // If user changes counters when a diff editor is open, we do not care, might as well ask user to reload.
    // Simpler and almost never going to happen.
    onDidChangeEnablement: unchangedRegionsEnablementEmitter.event.bind(unchangedRegionsEnablementEmitter),
    dispose: () => disposables.dispose()
  };
  disposables.add(configurationService.onDidChangeConfiguration((e) => {
    if (e.affectsConfiguration("diffEditor.hideUnchangedRegions.minimumLineCount")) {
      result.options.minimumLineCount = configurationService.getValue("diffEditor.hideUnchangedRegions.minimumLineCount");
    }
    if (e.affectsConfiguration("diffEditor.hideUnchangedRegions.contextLineCount")) {
      result.options.contextLineCount = configurationService.getValue("diffEditor.hideUnchangedRegions.contextLineCount");
    }
    if (e.affectsConfiguration("diffEditor.hideUnchangedRegions.revealLineCount")) {
      result.options.revealLineCount = configurationService.getValue("diffEditor.hideUnchangedRegions.revealLineCount");
    }
    if (e.affectsConfiguration("diffEditor.hideUnchangedRegions.enabled")) {
      result.options.enabled = configurationService.getValue("diffEditor.hideUnchangedRegions.enabled");
      unchangedRegionsEnablementEmitter.fire(result.options.enabled);
    }
  }));
  return result;
}

// out-build/vs/workbench/contrib/notebook/browser/diff/diffComponents.js
function $k2b() {
  return {
    isSimpleWidget: false,
    contributions: EditorExtensionsRegistry.getSomeEditorContributions([
      $Esb.ID,
      $Fsb,
      $Mfb.ID,
      $qdb.ID,
      $Dcb.ID,
      $Ysb.ID
    ])
  };
}
var $l2b = class extends $3c {
  constructor(placeholder, templateData) {
    super();
    templateData.body.classList.remove("left", "right", "full");
    const text2 = placeholder.hiddenCells.length === 1 ? localize(8360, null, placeholder.hiddenCells.length) : localize(8361, null, placeholder.hiddenCells.length);
    templateData.placeholder.innerText = text2;
    this.B($_i(templateData.placeholder, "dblclick", (e) => {
      if (e.button !== 0) {
        return;
      }
      e.preventDefault();
      placeholder.showHiddenCells();
    }));
    this.B(templateData.marginOverlay.onAction(() => placeholder.showHiddenCells()));
    templateData.marginOverlay.show();
  }
};
var PropertyHeader = class PropertyHeader2 extends $3c {
  constructor(cell, propertyHeaderContainer, notebookEditor, accessor, n, r2, s, t, u, w, y, z, C) {
    super();
    this.cell = cell;
    this.propertyHeaderContainer = propertyHeaderContainer;
    this.notebookEditor = notebookEditor;
    this.accessor = accessor;
    this.n = n;
    this.r = r2;
    this.s = s;
    this.t = t;
    this.u = u;
    this.w = w;
    this.y = y;
    this.z = z;
    this.C = C;
  }
  buildHeader() {
    this.a = $bk(this.propertyHeaderContainer, $(".property-folding-indicator"));
    this.a.classList.add(this.accessor.prefix);
    const metadataStatus = $bk(this.propertyHeaderContainer, $("div.property-status"));
    this.b = $bk(metadataStatus, $("span"));
    this.c = $bk(metadataStatus, $("span.property-description"));
    const cellToolbarContainer = $bk(this.propertyHeaderContainer, $("div.property-toolbar"));
    this.f = this.B(new $3$(cellToolbarContainer, {
      actionViewItemProvider: (action, options3) => {
        if (action instanceof $fJ) {
          const item = new $rKb(action, { hoverDelegate: options3.hoverDelegate }, this.r, this.t, this.w, this.y, this.n, this.C);
          return item;
        }
        return void 0;
      }
    }, this.u, this.w, this.n, this.r, this.s, this.z));
    this.f.context = this.cell;
    const scopedContextKeyService = this.w.createScoped(cellToolbarContainer);
    this.B(scopedContextKeyService);
    this.m = $5Db.bindTo(scopedContextKeyService);
    this.j = $6Db.bindTo(scopedContextKeyService);
    this.g = this.B(this.u.createMenu(this.accessor.menuId, scopedContextKeyService));
    this.B(this.g.onDidChange(() => this.D()));
    this.B(this.notebookEditor.onMouseUp((e) => {
      if (!e.event.target || e.target !== this.cell) {
        return;
      }
      const target = e.event.target;
      if (target === this.propertyHeaderContainer || target === this.a || this.a.contains(target) || target === metadataStatus || metadataStatus.contains(target)) {
        const oldFoldingState = this.accessor.getFoldingState();
        this.accessor.updateFoldingState(oldFoldingState === PropertyFoldingState.Expanded ? PropertyFoldingState.Collapsed : PropertyFoldingState.Expanded);
        this.F();
        this.accessor.updateInfoRendering(this.cell.renderOutput);
      }
    }));
    this.refresh();
    this.accessor.updateInfoRendering(this.cell.renderOutput);
  }
  refresh() {
    this.D();
    this.F();
    const metadataChanged = this.accessor.checkIfModified();
    if (this.m) {
      this.m.set(!!metadataChanged);
    }
    if (metadataChanged) {
      this.b.textContent = this.accessor.changedLabel;
      this.b.style.fontWeight = "bold";
      if (metadataChanged.reason) {
        this.c.textContent = metadataChanged.reason;
      }
      this.propertyHeaderContainer.classList.add("modified");
    } else {
      this.b.textContent = this.accessor.unChangedLabel;
      this.b.style.fontWeight = "normal";
      this.c.textContent = "";
      this.propertyHeaderContainer.classList.remove("modified");
    }
  }
  D() {
    const metadataChanged = this.accessor.checkIfModified();
    if (metadataChanged) {
      const actions = $R$(this.g.getActions({ shouldForwardArgs: true }));
      this.f.setActions(actions);
    } else {
      this.f.setActions([]);
    }
  }
  F() {
    if (this.accessor.getFoldingState() === PropertyFoldingState.Collapsed) {
      $dk(this.a, $C1($SKb));
      this.j?.set(false);
    } else {
      $dk(this.a, $C1($TKb));
      this.j?.set(true);
    }
  }
};
PropertyHeader = __decorate([
  __param(4, $50),
  __param(5, $Ty),
  __param(6, $sn),
  __param(7, $PJ),
  __param(8, $cJ),
  __param(9, $on),
  __param(10, $gs),
  __param(11, $zv),
  __param(12, $ND)
], PropertyHeader);
var $m2b = class $m2b2 extends $3c {
  constructor(notebookEditor, viewModel, templateData, n, r2, s, t, u, w) {
    super();
    this.notebookEditor = notebookEditor;
    this.viewModel = viewModel;
    this.templateData = templateData;
    this.n = n;
    this.r = r2;
    this.s = s;
    this.t = t;
    this.u = u;
    this.w = w;
    this.a = templateData.sourceEditor;
    this.f = this.templateData.cellHeaderContainer;
    this.g = this.templateData.editorContainer;
    this.m = this.templateData.diffEditorContainer;
    this.b = false;
    this.B(viewModel.onDidLayoutChange((e) => {
      this.layout(e);
      this.updateBorders();
    }));
    this.buildBody();
    this.updateBorders();
  }
  buildBody() {
    const body = this.templateData.body;
    body.classList.remove("full");
    body.classList.add("full");
    this.updateSourceEditor();
    if (this.viewModel instanceof $mEb) {
      this.B(this.viewModel.modifiedMetadata.onDidChange((e) => {
        this.j.refresh();
      }));
    }
  }
  y() {
    this.notebookEditor.layoutNotebookCell(this.viewModel, this.viewModel.layoutInfo.totalHeight);
  }
  updateBorders() {
    this.templateData.leftBorder.style.height = `${this.viewModel.layoutInfo.totalHeight - 32}px`;
    this.templateData.rightBorder.style.height = `${this.viewModel.layoutInfo.totalHeight - 32}px`;
    this.templateData.bottomBorder.style.top = `${this.viewModel.layoutInfo.totalHeight - 32}px`;
  }
  updateSourceEditor() {
    this.f.style.display = "flex";
    this.f.innerText = "";
    this.g.classList.add("diff");
    const updateSourceEditor = () => {
      if (this.viewModel.cellFoldingState === PropertyFoldingState.Collapsed) {
        this.g.style.display = "none";
        this.viewModel.editorHeight = 0;
        return;
      }
      const lineHeight = this.notebookEditor.getLayoutInfo().fontInfo.lineHeight || 17;
      const editorHeight = this.viewModel.layoutInfo.editorHeight !== 0 ? this.viewModel.layoutInfo.editorHeight : this.viewModel.computeInputEditorHeight(lineHeight);
      this.g.style.height = `${editorHeight}px`;
      this.g.style.display = "block";
      const contentHeight = this.a.getContentHeight();
      if (contentHeight >= 0) {
        this.viewModel.editorHeight = contentHeight;
      }
      return editorHeight;
    };
    const renderSourceEditor = () => {
      const editorHeight = updateSourceEditor();
      if (!editorHeight) {
        return;
      }
      const lineCount = this.viewModel.modifiedMetadata.textBuffer.getLineCount();
      const options3 = {
        padding: $WDb(lineCount)
      };
      const unchangedRegions = this.B($j2b(this.w));
      if (unchangedRegions.options.enabled) {
        options3.hideUnchangedRegions = unchangedRegions.options;
      }
      this.a.updateOptions(options3);
      this.B(unchangedRegions.onDidChangeEnablement(() => {
        options3.hideUnchangedRegions = unchangedRegions.options;
        this.a.updateOptions(options3);
      }));
      this.a.layout({
        width: this.notebookEditor.getLayoutInfo().width - 2 * $ZDb,
        height: editorHeight
      });
      this.B(this.a.onDidContentSizeChange((e) => {
        if (this.viewModel.cellFoldingState === PropertyFoldingState.Expanded && e.contentHeightChanged && this.viewModel.layoutInfo.editorHeight !== e.contentHeight) {
          this.viewModel.editorHeight = e.contentHeight;
        }
      }));
      this.z();
    };
    this.j = this.B(this.n.createInstance(PropertyHeader, this.viewModel, this.f, this.notebookEditor, {
      updateInfoRendering: () => renderSourceEditor(),
      checkIfModified: () => {
        return this.viewModel.originalMetadata.getHash() !== this.viewModel.modifiedMetadata.getHash() ? { reason: void 0 } : false;
      },
      getFoldingState: () => this.viewModel.cellFoldingState,
      updateFoldingState: (state) => this.viewModel.cellFoldingState = state,
      unChangedLabel: "Notebook Metadata",
      changedLabel: "Notebook Metadata changed",
      prefix: "metadata",
      menuId: $bJ.NotebookDiffDocumentMetadata
    }));
    this.j.buildHeader();
    renderSourceEditor();
    const scopedContextKeyService = this.t.createScoped(this.templateData.inputToolbarContainer);
    this.B(scopedContextKeyService);
    const inputChanged = $2Db.bindTo(scopedContextKeyService);
    inputChanged.set(this.viewModel.originalMetadata.getHash() !== this.viewModel.modifiedMetadata.getHash());
    this.c = this.templateData.toolbar;
    this.c.context = this.viewModel;
    const refreshToolbar = () => {
      const hasChanges = this.viewModel.originalMetadata.getHash() !== this.viewModel.modifiedMetadata.getHash();
      inputChanged.set(hasChanges);
      if (hasChanges) {
        const menu = this.s.getMenuActions($bJ.NotebookDiffDocumentMetadata, scopedContextKeyService, { shouldForwardArgs: true });
        const actions = $R$(menu);
        this.c.setActions(actions);
      } else {
        this.c.setActions([]);
      }
    };
    this.B(this.viewModel.modifiedMetadata.onDidChange(() => {
      refreshToolbar();
    }));
    refreshToolbar();
  }
  async z() {
    const [originalRef, modifiedRef] = await Promise.all([
      this.r.createModelReference(this.viewModel.originalMetadata.uri),
      this.r.createModelReference(this.viewModel.modifiedMetadata.uri)
    ]);
    if (this.q.isDisposed) {
      originalRef.dispose();
      modifiedRef.dispose();
      return;
    }
    this.B(originalRef);
    this.B(modifiedRef);
    const vm = this.B(this.a.createViewModel({
      original: originalRef.object.textEditorModel,
      modified: modifiedRef.object.textEditorModel
    }));
    await vm.waitForDiff();
    this.a.setModel(vm);
    const handleViewStateChange = () => {
      this.b = true;
    };
    const handleScrollChange = (e) => {
      if (e.scrollTopChanged || e.scrollLeftChanged) {
        this.b = true;
      }
    };
    this.C();
    this.B(this.a.getOriginalEditor().onDidChangeCursorSelection(handleViewStateChange));
    this.B(this.a.getOriginalEditor().onDidScrollChange(handleScrollChange));
    this.B(this.a.getModifiedEditor().onDidChangeCursorSelection(handleViewStateChange));
    this.B(this.a.getModifiedEditor().onDidScrollChange(handleScrollChange));
    const editorViewState = this.viewModel.getSourceEditorViewState();
    if (editorViewState) {
      this.a.restoreViewState(editorViewState);
    }
    const contentHeight = this.a.getContentHeight();
    this.viewModel.editorHeight = contentHeight;
  }
  C() {
    const editor = this.a;
    const uri = editor.getModel()?.modified.uri || editor.getModel()?.original.uri;
    if (!uri) {
      return;
    }
    const ignoreTrimWhitespace = this.u.getValue(uri, "diffEditor.ignoreTrimWhitespace");
    editor.updateOptions({ ignoreTrimWhitespace });
    this.B(this.u.onDidChangeConfiguration((e) => {
      if (e.affectsConfiguration(uri, "diffEditor") && e.affectedKeys.has("diffEditor.ignoreTrimWhitespace")) {
        const ignoreTrimWhitespace2 = this.u.getValue(uri, "diffEditor.ignoreTrimWhitespace");
        editor.updateOptions({ ignoreTrimWhitespace: ignoreTrimWhitespace2 });
      }
    }));
  }
  layout(state) {
    $jj(getWindow(this.m), () => {
      if (state.editorHeight) {
        this.g.style.height = `${this.viewModel.layoutInfo.editorHeight}px`;
        this.a.layout({
          width: this.a.getViewWidth(),
          height: this.viewModel.layoutInfo.editorHeight
        });
      }
      if (state.outerWidth) {
        this.g.style.height = `${this.viewModel.layoutInfo.editorHeight}px`;
        this.a.layout();
      }
      this.y();
    });
  }
  dispose() {
    this.a.setModel(null);
    if (this.b) {
      this.viewModel.saveSpirceEditorViewState(this.a.saveViewState());
    }
    super.dispose();
  }
};
$m2b = __decorate([
  __param(3, $Pk),
  __param(4, $oG),
  __param(5, $cJ),
  __param(6, $on),
  __param(7, $zG),
  __param(8, $kl)
], $m2b);
var AbstractElementRenderer = class extends $3c {
  constructor(notebookEditor, cell, templateData, style, U, W, X, Y, Z, ab, bb, cb, db, eb, fb) {
    super();
    this.notebookEditor = notebookEditor;
    this.cell = cell;
    this.templateData = templateData;
    this.style = style;
    this.U = U;
    this.W = W;
    this.X = X;
    this.Y = Y;
    this.Z = Z;
    this.ab = ab;
    this.bb = bb;
    this.cb = cb;
    this.db = db;
    this.eb = eb;
    this.fb = fb;
    this.a = this.B(new $2c());
    this.b = this.B(new $2c());
    this.c = false;
    this.f = false;
    this.S = false;
    this.u = this.B(new $2c());
    this.N = this.B(new $2c());
    this.B(cell.onDidLayoutChange((e) => {
      this.layout(e);
    }));
    this.B(cell.onDidLayoutChange((e) => this.updateBorders()));
    this.init();
    this.buildBody();
    this.B(cell.onDidStateChange(() => {
      this.updateOutputRendering(this.cell.renderOutput);
    }));
  }
  buildBody() {
    const body = this.templateData.body;
    this.Q = this.templateData.diffEditorContainer;
    body.classList.remove("left", "right", "full");
    switch (this.style) {
      case "left":
        body.classList.add("left");
        break;
      case "right":
        body.classList.add("right");
        break;
      default:
        body.classList.add("full");
        break;
    }
    this.styleContainer(this.Q);
    this.updateSourceEditor();
    if (this.cell.modified) {
      this.B(this.cell.modified.textModel.onDidChangeContent(() => this.m.refresh()));
    }
    this.c = this.eb.getValue("notebook.diff.ignoreMetadata");
    if (this.c) {
      this._disposeMetadata();
    } else {
      this._buildMetadata();
    }
    this.f = this.eb.getValue("notebook.diff.ignoreOutputs") || !!this.notebookEditor.textModel?.transientOptions.transientOutputs;
    if (this.f) {
      this._disposeOutput();
    } else {
      this._buildOutput();
    }
    this.B(this.eb.onDidChangeConfiguration((e) => {
      let metadataLayoutChange = false;
      let outputLayoutChange = false;
      if (e.affectsConfiguration("notebook.diff.ignoreMetadata")) {
        const newValue = this.eb.getValue("notebook.diff.ignoreMetadata");
        if (newValue !== void 0 && this.c !== newValue) {
          this.c = newValue;
          this.a.clear();
          if (this.eb.getValue("notebook.diff.ignoreMetadata")) {
            this._disposeMetadata();
          } else {
            this.cell.metadataStatusHeight = 25;
            this._buildMetadata();
            this.updateMetadataRendering();
            metadataLayoutChange = true;
          }
        }
      }
      if (e.affectsConfiguration("notebook.diff.ignoreOutputs")) {
        const newValue = this.eb.getValue("notebook.diff.ignoreOutputs");
        if (newValue !== void 0 && this.f !== (newValue || this.notebookEditor.textModel?.transientOptions.transientOutputs)) {
          this.f = newValue || !!this.notebookEditor.textModel?.transientOptions.transientOutputs;
          this.b.clear();
          if (this.f) {
            this._disposeOutput();
            this.cell.layoutChange();
          } else {
            this.cell.outputStatusHeight = 25;
            this._buildOutput();
            outputLayoutChange = true;
          }
        }
      }
      if (metadataLayoutChange || outputLayoutChange) {
        this.layout({ metadataHeight: metadataLayoutChange, outputTotalHeight: outputLayoutChange });
      }
    }));
  }
  updateMetadataRendering() {
    if (this.cell.metadataFoldingState === PropertyFoldingState.Expanded) {
      this.s.style.display = "block";
      if (!this.t || !this.w) {
        this.t = $bk(this.s, $(".metadata-editor-container"));
        this.mb();
      } else {
        this.cell.metadataHeight = this.w.getContentHeight();
      }
    } else {
      this.s.style.display = "none";
      this.cell.metadataHeight = 0;
    }
  }
  updateOutputRendering(renderRichOutput) {
    if (this.cell.outputFoldingState === PropertyFoldingState.Expanded) {
      this.C.style.display = "block";
      if (renderRichOutput) {
        this.jb();
        this._buildOutputRendererContainer();
        this._showOutputsRenderer();
        this.ib();
      } else {
        this._hideOutputsRenderer();
        this.gb();
        this.hb();
      }
    } else {
      this.C.style.display = "none";
      this.jb();
      this._hideOutputsRenderer();
      this.kb();
    }
  }
  gb() {
    if (!this.D) {
      this.D = $bk(this.C, $(".output-editor-container"));
      this.nb();
    }
  }
  hb() {
    if (this.D) {
      this.D.style.display = "block";
      this.cell.rawOutputHeight = this.O.getContentHeight();
    }
  }
  ib() {
    this.cell.layoutChange();
  }
  jb() {
    if (this.D) {
      this.D.style.display = "none";
      this.cell.rawOutputHeight = 0;
    }
  }
  kb() {
    this.cell.layoutChange();
  }
  lb(currentMetadata, newMetadata) {
    const result = {};
    try {
      const newMetadataObj = JSON.parse(newMetadata);
      const keys = /* @__PURE__ */ new Set([...Object.keys(newMetadataObj)]);
      for (const key2 of keys) {
        switch (key2) {
          case "inputCollapsed":
          case "outputCollapsed":
            if (typeof newMetadataObj[key2] === "boolean") {
              result[key2] = newMetadataObj[key2];
            } else {
              result[key2] = currentMetadata[key2];
            }
            break;
          default:
            result[key2] = newMetadataObj[key2];
            break;
        }
      }
      const index = this.notebookEditor.textModel.cells.indexOf(this.cell.modified.textModel);
      if (index < 0) {
        return;
      }
      this.notebookEditor.textModel.applyEdits([
        { editType: 3, index, metadata: result }
      ], true, void 0, () => void 0, void 0, true);
    } catch {
    }
  }
  async mb() {
    this.u.clear();
    if (this.cell instanceof $oEb) {
      this.w = this.U.createInstance($c_, this.t, {
        ...$YDb,
        overflowWidgetsDomNode: this.notebookEditor.getOverflowContainerDomNode(),
        readOnly: false,
        originalEditable: false,
        ignoreTrimWhitespace: false,
        automaticLayout: false,
        dimension: {
          height: this.cell.layoutInfo.metadataHeight,
          width: this.cell.getComputedCellContainerWidth(this.notebookEditor.getLayoutInfo(), true, true)
        }
      }, {
        originalEditor: $k2b(),
        modifiedEditor: $k2b()
      });
      const unchangedRegions = this.B($j2b(this.eb));
      if (unchangedRegions.options.enabled) {
        this.w.updateOptions({ hideUnchangedRegions: unchangedRegions.options });
      }
      this.u.add(unchangedRegions.onDidChangeEnablement(() => {
        if (this.w) {
          this.w.updateOptions({ hideUnchangedRegions: unchangedRegions.options });
        }
      }));
      this.layout({ metadataHeight: true });
      this.u.add(this.w);
      this.t?.classList.add("diff");
      const [originalMetadataModel, modifiedMetadataModel] = await Promise.all([
        this.Y.createModelReference(CellUri.generateCellPropertyUri(this.cell.originalDocument.uri, this.cell.original.handle, Schemas.vscodeNotebookCellMetadata)),
        this.Y.createModelReference(CellUri.generateCellPropertyUri(this.cell.modifiedDocument.uri, this.cell.modified.handle, Schemas.vscodeNotebookCellMetadata))
      ]);
      if (this.S) {
        originalMetadataModel.dispose();
        modifiedMetadataModel.dispose();
        return;
      }
      this.u.add(originalMetadataModel);
      this.u.add(modifiedMetadataModel);
      const vm = this.w.createViewModel({
        original: originalMetadataModel.object.textEditorModel,
        modified: modifiedMetadataModel.object.textEditorModel
      });
      this.w.setModel(vm);
      await vm.waitForDiff();
      if (this.S) {
        return;
      }
      this.cell.metadataHeight = this.w.getContentHeight();
      this.u.add(this.w.onDidContentSizeChange((e) => {
        if (e.contentHeightChanged && this.cell.metadataFoldingState === PropertyFoldingState.Expanded) {
          this.cell.metadataHeight = e.contentHeight;
        }
      }));
      let respondingToContentChange = false;
      this.u.add(modifiedMetadataModel.object.textEditorModel.onDidChangeContent(() => {
        respondingToContentChange = true;
        const value = modifiedMetadataModel.object.textEditorModel.getValue();
        this.lb(this.cell.modified.metadata, value);
        this.r.refresh();
        respondingToContentChange = false;
      }));
      this.u.add(this.cell.modified.textModel.onDidChangeMetadata(() => {
        if (respondingToContentChange) {
          return;
        }
        const modifiedMetadataSource = $uL(this.notebookEditor.textModel?.transientOptions.transientCellMetadata, this.cell.modified?.metadata || {}, this.cell.modified?.language);
        modifiedMetadataModel.object.textEditorModel.setValue(modifiedMetadataSource);
      }));
      return;
    } else {
      this.w = this.U.createInstance($D9, this.t, {
        ...$XDb,
        dimension: {
          width: this.cell.getComputedCellContainerWidth(this.notebookEditor.getLayoutInfo(), false, true),
          height: this.cell.layoutInfo.metadataHeight
        },
        overflowWidgetsDomNode: this.notebookEditor.getOverflowContainerDomNode(),
        readOnly: false
      }, {});
      this.layout({ metadataHeight: true });
      this.u.add(this.w);
      const mode = this.W.createById("jsonc");
      const originalMetadataSource = $uL(this.notebookEditor.textModel?.transientOptions.transientCellMetadata, this.cell.type === "insert" ? this.cell.modified.metadata || {} : this.cell.original.metadata || {});
      const uri = this.cell.type === "insert" ? this.cell.modified.uri : this.cell.original.uri;
      const handle2 = this.cell.type === "insert" ? this.cell.modified.handle : this.cell.original.handle;
      const modelUri = CellUri.generateCellPropertyUri(uri, handle2, Schemas.vscodeNotebookCellMetadata);
      const metadataModel = this.X.createModel(originalMetadataSource, mode, modelUri, false);
      this.w.setModel(metadataModel);
      this.u.add(metadataModel);
      this.cell.metadataHeight = this.w.getContentHeight();
      this.u.add(this.w.onDidContentSizeChange((e) => {
        if (e.contentHeightChanged && this.cell.metadataFoldingState === PropertyFoldingState.Expanded) {
          this.cell.metadataHeight = e.contentHeight;
        }
      }));
    }
  }
  nb() {
    this.N.clear();
    if ((this.cell.type === "modified" || this.cell.type === "unchanged") && !this.notebookEditor.textModel.transientOptions.transientOutputs) {
      const originalOutputsSource = $sEb(this.cell.original?.outputs || []);
      const modifiedOutputsSource = $sEb(this.cell.modified?.outputs || []);
      if (originalOutputsSource !== modifiedOutputsSource) {
        const mode2 = this.W.createById("json");
        const originalModel = this.X.createModel(originalOutputsSource, mode2, void 0, true);
        const modifiedModel = this.X.createModel(modifiedOutputsSource, mode2, void 0, true);
        this.N.add(originalModel);
        this.N.add(modifiedModel);
        const lineHeight = this.notebookEditor.getLayoutInfo().fontInfo.lineHeight || 17;
        const lineCount = Math.max(originalModel.getLineCount(), modifiedModel.getLineCount());
        this.O = this.U.createInstance($c_, this.D, {
          ...$YDb,
          overflowWidgetsDomNode: this.notebookEditor.getOverflowContainerDomNode(),
          readOnly: true,
          ignoreTrimWhitespace: false,
          automaticLayout: false,
          dimension: {
            height: Math.min($jEb, this.cell.layoutInfo.rawOutputHeight || lineHeight * lineCount),
            width: this.cell.getComputedCellContainerWidth(this.notebookEditor.getLayoutInfo(), false, true)
          },
          accessibilityVerbose: this.eb.getValue(
            "accessibility.verbosity.diffEditor"
            /* AccessibilityVerbositySettingId.DiffEditor */
          ) ?? false
        }, {
          originalEditor: $k2b(),
          modifiedEditor: $k2b()
        });
        this.N.add(this.O);
        this.D?.classList.add("diff");
        this.O.setModel({
          original: originalModel,
          modified: modifiedModel
        });
        this.O.restoreViewState(this.cell.getOutputEditorViewState());
        this.cell.rawOutputHeight = this.O.getContentHeight();
        this.N.add(this.O.onDidContentSizeChange((e) => {
          if (e.contentHeightChanged && this.cell.outputFoldingState === PropertyFoldingState.Expanded) {
            this.cell.rawOutputHeight = e.contentHeight;
          }
        }));
        this.N.add(this.cell.modified.textModel.onDidChangeOutputs(() => {
          const modifiedOutputsSource2 = $sEb(this.cell.modified?.outputs || []);
          modifiedModel.setValue(modifiedOutputsSource2);
          this.z.refresh();
        }));
        return;
      }
    }
    this.O = this.U.createInstance($D9, this.D, {
      ...$XDb,
      dimension: {
        width: Math.min($jEb, this.cell.getComputedCellContainerWidth(this.notebookEditor.getLayoutInfo(), false, this.cell.type === "unchanged" || this.cell.type === "modified") - 32),
        height: this.cell.layoutInfo.rawOutputHeight
      },
      overflowWidgetsDomNode: this.notebookEditor.getOverflowContainerDomNode()
    }, {});
    this.N.add(this.O);
    const mode = this.W.createById("json");
    const originaloutputSource = $sEb(this.notebookEditor.textModel.transientOptions.transientOutputs ? [] : this.cell.type === "insert" ? this.cell.modified?.outputs || [] : this.cell.original?.outputs || []);
    const outputModel = this.X.createModel(originaloutputSource, mode, void 0, true);
    this.N.add(outputModel);
    this.O.setModel(outputModel);
    this.O.restoreViewState(this.cell.getOutputEditorViewState());
    this.cell.rawOutputHeight = this.O.getContentHeight();
    this.N.add(this.O.onDidContentSizeChange((e) => {
      if (e.contentHeightChanged && this.cell.outputFoldingState === PropertyFoldingState.Expanded) {
        this.cell.rawOutputHeight = e.contentHeight;
      }
    }));
  }
  ob() {
    this.notebookEditor.layoutNotebookCell(this.cell, this.cell.layoutInfo.totalHeight);
  }
  updateBorders() {
    this.templateData.leftBorder.style.height = `${this.cell.layoutInfo.totalHeight - 32}px`;
    this.templateData.rightBorder.style.height = `${this.cell.layoutInfo.totalHeight - 32}px`;
    this.templateData.bottomBorder.style.top = `${this.cell.layoutInfo.totalHeight - 32}px`;
  }
  dispose() {
    if (this.O) {
      this.cell.saveOutputEditorViewState(this.O.saveViewState());
    }
    if (this.w) {
      this.cell.saveMetadataEditorViewState(this.w.saveViewState());
    }
    this.u.dispose();
    this.N.dispose();
    this.S = true;
    super.dispose();
  }
};
var SingleSideDiffElement = class extends AbstractElementRenderer {
  constructor(notebookEditor, cell, templateData, style, instantiationService, languageService, modelService, textModelService, contextMenuService, keybindingService, notificationService, menuService, contextKeyService, configurationService, textConfigurationService) {
    super(notebookEditor, cell, templateData, style, instantiationService, languageService, modelService, textModelService, contextMenuService, keybindingService, notificationService, menuService, contextKeyService, configurationService, textConfigurationService);
    this.cell = cell;
    this.templateData = templateData;
    this.updateBorders();
  }
  init() {
    this.R = this.templateData.diagonalFill;
  }
  buildBody() {
    const body = this.templateData.body;
    this.Q = this.templateData.diffEditorContainer;
    body.classList.remove("left", "right", "full");
    switch (this.style) {
      case "left":
        body.classList.add("left");
        break;
      case "right":
        body.classList.add("right");
        break;
      default:
        body.classList.add("full");
        break;
    }
    this.styleContainer(this.Q);
    this.updateSourceEditor();
    if (this.eb.getValue("notebook.diff.ignoreMetadata")) {
      this._disposeMetadata();
    } else {
      this._buildMetadata();
    }
    if (this.eb.getValue("notebook.diff.ignoreOutputs") || this.notebookEditor.textModel?.transientOptions.transientOutputs) {
      this._disposeOutput();
    } else {
      this._buildOutput();
    }
    this.B(this.eb.onDidChangeConfiguration((e) => {
      let metadataLayoutChange = false;
      let outputLayoutChange = false;
      if (e.affectsConfiguration("notebook.diff.ignoreMetadata")) {
        this.a.clear();
        if (this.eb.getValue("notebook.diff.ignoreMetadata")) {
          this._disposeMetadata();
        } else {
          this.cell.metadataStatusHeight = 25;
          this._buildMetadata();
          this.updateMetadataRendering();
          metadataLayoutChange = true;
        }
      }
      if (e.affectsConfiguration("notebook.diff.ignoreOutputs")) {
        this.b.clear();
        if (this.eb.getValue("notebook.diff.ignoreOutputs") || this.notebookEditor.textModel?.transientOptions.transientOutputs) {
          this._disposeOutput();
        } else {
          this.cell.outputStatusHeight = 25;
          this._buildOutput();
          outputLayoutChange = true;
        }
      }
      if (metadataLayoutChange || outputLayoutChange) {
        this.layout({ metadataHeight: metadataLayoutChange, outputTotalHeight: outputLayoutChange });
      }
    }));
  }
  updateSourceEditor() {
    this.g = this.templateData.cellHeaderContainer;
    this.g.style.display = "flex";
    this.g.innerText = "";
    this.j = this.templateData.editorContainer;
    this.j.classList.add("diff");
    const renderSourceEditor = () => {
      if (this.cell.cellFoldingState === PropertyFoldingState.Collapsed) {
        this.j.style.display = "none";
        this.cell.editorHeight = 0;
        return;
      }
      const lineHeight = this.notebookEditor.getLayoutInfo().fontInfo.lineHeight || 17;
      const editorHeight = this.cell.computeInputEditorHeight(lineHeight);
      this.j.style.height = `${editorHeight}px`;
      this.j.style.display = "block";
      if (this.pb) {
        const contentHeight = this.pb.getContentHeight();
        if (contentHeight >= 0) {
          this.cell.editorHeight = contentHeight;
        }
        return;
      }
      this.pb = this.templateData.sourceEditor;
      this.pb.layout({
        width: (this.notebookEditor.getLayoutInfo().width - 2 * $ZDb) / 2 - 18,
        height: editorHeight
      });
      this.pb.updateOptions({ readOnly: this.readonly });
      this.cell.editorHeight = editorHeight;
      this.B(this.pb.onDidContentSizeChange((e) => {
        if (this.cell.cellFoldingState === PropertyFoldingState.Expanded && e.contentHeightChanged && this.cell.layoutInfo.editorHeight !== e.contentHeight) {
          this.cell.editorHeight = e.contentHeight;
        }
      }));
      this.rb(this.nestedCellViewModel);
    };
    this.m = this.B(this.U.createInstance(PropertyHeader, this.cell, this.g, this.notebookEditor, {
      updateInfoRendering: () => renderSourceEditor(),
      checkIfModified: () => ({ reason: void 0 }),
      getFoldingState: () => this.cell.cellFoldingState,
      updateFoldingState: (state) => this.cell.cellFoldingState = state,
      unChangedLabel: "Input",
      changedLabel: "Input",
      prefix: "input",
      menuId: $bJ.NotebookDiffCellInputTitle
    }));
    this.m.buildHeader();
    renderSourceEditor();
    this.rb(this.nestedCellViewModel);
  }
  qb() {
    return this.cell.layoutInfo.cellStatusHeight + this.cell.layoutInfo.editorHeight + this.cell.layoutInfo.editorMargin + this.cell.layoutInfo.metadataStatusHeight + this.cell.layoutInfo.metadataHeight + this.cell.layoutInfo.outputTotalHeight + this.cell.layoutInfo.outputStatusHeight;
  }
  async rb(modifiedCell) {
    const modifiedRef = await this.Y.createModelReference(modifiedCell.uri);
    if (this.S) {
      return;
    }
    const modifiedTextModel = modifiedRef.object.textEditorModel;
    this.B(modifiedRef);
    this.pb.setModel(modifiedTextModel);
    const editorViewState = this.cell.getSourceEditorViewState();
    if (editorViewState) {
      this.pb.restoreViewState(editorViewState);
    }
    const contentHeight = this.pb.getContentHeight();
    this.cell.editorHeight = contentHeight;
    const height = `${this.qb()}px`;
    if (this.R.style.height !== height) {
      this.R.style.height = height;
    }
  }
  _disposeMetadata() {
    this.cell.metadataStatusHeight = 0;
    this.cell.metadataHeight = 0;
    this.templateData.cellHeaderContainer.style.display = "none";
    this.templateData.metadataHeaderContainer.style.display = "none";
    this.templateData.metadataInfoContainer.style.display = "none";
    this.w = void 0;
  }
  _buildMetadata() {
    this.n = this.templateData.metadataHeaderContainer;
    this.s = this.templateData.metadataInfoContainer;
    this.n.style.display = "flex";
    this.s.style.display = "block";
    this.n.innerText = "";
    this.s.innerText = "";
    this.r = this.U.createInstance(PropertyHeader, this.cell, this.n, this.notebookEditor, {
      updateInfoRendering: this.updateMetadataRendering.bind(this),
      checkIfModified: () => {
        return this.cell.checkMetadataIfModified();
      },
      getFoldingState: () => {
        return this.cell.metadataFoldingState;
      },
      updateFoldingState: (state) => {
        this.cell.metadataFoldingState = state;
      },
      unChangedLabel: "Metadata",
      changedLabel: "Metadata changed",
      prefix: "metadata",
      menuId: $bJ.NotebookDiffCellMetadataTitle
    });
    this.a.add(this.r);
    this.r.buildHeader();
  }
  _buildOutput() {
    this.templateData.outputHeaderContainer.style.display = "flex";
    this.templateData.outputInfoContainer.style.display = "block";
    this.y = this.templateData.outputHeaderContainer;
    this.C = this.templateData.outputInfoContainer;
    this.y.innerText = "";
    this.C.innerText = "";
    this.z = this.U.createInstance(PropertyHeader, this.cell, this.y, this.notebookEditor, {
      updateInfoRendering: this.updateOutputRendering.bind(this),
      checkIfModified: () => {
        return this.cell.checkIfOutputsModified();
      },
      getFoldingState: () => {
        return this.cell.outputFoldingState;
      },
      updateFoldingState: (state) => {
        this.cell.outputFoldingState = state;
      },
      unChangedLabel: "Outputs",
      changedLabel: "Outputs changed",
      prefix: "output",
      menuId: $bJ.NotebookDiffCellOutputsTitle
    });
    this.b.add(this.z);
    this.z.buildHeader();
  }
  _disposeOutput() {
    this.jb();
    this._hideOutputsRenderer();
    this.kb();
    this.cell.rawOutputHeight = 0;
    this.cell.outputMetadataHeight = 0;
    this.cell.outputStatusHeight = 0;
    this.templateData.outputHeaderContainer.style.display = "none";
    this.templateData.outputInfoContainer.style.display = "none";
    this.F = void 0;
  }
};
var $n2b = class $n2b2 extends SingleSideDiffElement {
  constructor(notebookEditor, cell, templateData, languageService, modelService, textModelService, instantiationService, contextMenuService, keybindingService, notificationService, menuService, contextKeyService, configurationService, textConfigurationService) {
    super(notebookEditor, cell, templateData, "left", instantiationService, languageService, modelService, textModelService, contextMenuService, keybindingService, notificationService, menuService, contextKeyService, configurationService, textConfigurationService);
  }
  get nestedCellViewModel() {
    return this.cell.original;
  }
  get readonly() {
    return true;
  }
  styleContainer(container2) {
    container2.classList.remove("inserted");
    container2.classList.add("removed");
  }
  layout(state) {
    $jj(getWindow(this.Q), () => {
      if ((state.editorHeight || state.outerWidth) && this.pb) {
        this.j.style.height = `${this.cell.layoutInfo.editorHeight}px`;
        this.pb.layout({
          width: this.cell.getComputedCellContainerWidth(this.notebookEditor.getLayoutInfo(), false, false),
          height: this.cell.layoutInfo.editorHeight
        });
      }
      if (state.outerWidth && this.pb) {
        this.j.style.height = `${this.cell.layoutInfo.editorHeight}px`;
        this.pb.layout();
      }
      if (state.metadataHeight || state.outerWidth) {
        this.w?.layout({
          width: this.cell.getComputedCellContainerWidth(this.notebookEditor.getLayoutInfo(), false, false),
          height: this.cell.layoutInfo.metadataHeight
        });
      }
      if (state.outputTotalHeight || state.outerWidth) {
        this.O?.layout({
          width: this.cell.getComputedCellContainerWidth(this.notebookEditor.getLayoutInfo(), false, false),
          height: this.cell.layoutInfo.outputTotalHeight
        });
      }
      if (this.R) {
        this.R.style.height = `${this.qb()}px`;
      }
      this.ob();
    });
  }
  _buildOutputRendererContainer() {
    if (!this.F) {
      this.F = $bk(this.C, $(".output-view-container"));
      this.J = $bk(this.F, $(".output-empty-view"));
      const span = $bk(this.J, $("span"));
      span.innerText = "No outputs to render";
      if (!this.cell.original?.outputs.length) {
        this.J.style.display = "block";
      } else {
        this.J.style.display = "none";
      }
      this.cell.layoutChange();
      this.L = this.U.createInstance($i2b, this.notebookEditor, this.notebookEditor.textModel, this.cell, this.cell.original, DiffSide.Original, this.F);
      this.B(this.L);
      this.L.render();
      const removedOutputRenderListener = this.notebookEditor.onDidDynamicOutputRendered((e) => {
        if (e.cell.uri.toString() === this.cell.original.uri.toString()) {
          this.notebookEditor.deltaCellOutputContainerClassNames(DiffSide.Original, this.cell.original.id, ["nb-cellDeleted"], []);
          removedOutputRenderListener.dispose();
        }
      });
      this.B(removedOutputRenderListener);
    }
    this.F.style.display = "block";
  }
  _decorate() {
    this.notebookEditor.deltaCellOutputContainerClassNames(DiffSide.Original, this.cell.original.id, ["nb-cellDeleted"], []);
  }
  _showOutputsRenderer() {
    if (this.F) {
      this.F.style.display = "block";
      this.L?.showOutputs();
      this._decorate();
    }
  }
  _hideOutputsRenderer() {
    if (this.F) {
      this.F.style.display = "none";
      this.L?.hideOutputs();
    }
  }
  dispose() {
    if (this.pb) {
      this.cell.saveSpirceEditorViewState(this.pb.saveViewState());
    }
    super.dispose();
  }
};
$n2b = __decorate([
  __param(3, $1E),
  __param(4, $sG),
  __param(5, $oG),
  __param(6, $Pk),
  __param(7, $50),
  __param(8, $Ty),
  __param(9, $PJ),
  __param(10, $cJ),
  __param(11, $on),
  __param(12, $kl),
  __param(13, $zG)
], $n2b);
var $o2b = class $o2b2 extends SingleSideDiffElement {
  constructor(notebookEditor, cell, templateData, instantiationService, languageService, modelService, textModelService, contextMenuService, keybindingService, notificationService, menuService, contextKeyService, configurationService, textConfigurationService) {
    super(notebookEditor, cell, templateData, "right", instantiationService, languageService, modelService, textModelService, contextMenuService, keybindingService, notificationService, menuService, contextKeyService, configurationService, textConfigurationService);
  }
  get nestedCellViewModel() {
    return this.cell.modified;
  }
  get readonly() {
    return false;
  }
  styleContainer(container2) {
    container2.classList.remove("removed");
    container2.classList.add("inserted");
  }
  _buildOutputRendererContainer() {
    if (!this.F) {
      this.F = $bk(this.C, $(".output-view-container"));
      this.J = $bk(this.F, $(".output-empty-view"));
      this.J.innerText = "No outputs to render";
      if (!this.cell.modified?.outputs.length) {
        this.J.style.display = "block";
      } else {
        this.J.style.display = "none";
      }
      this.cell.layoutChange();
      this.M = this.U.createInstance($i2b, this.notebookEditor, this.notebookEditor.textModel, this.cell, this.cell.modified, DiffSide.Modified, this.F);
      this.B(this.M);
      this.M.render();
      const insertOutputRenderListener = this.notebookEditor.onDidDynamicOutputRendered((e) => {
        if (e.cell.uri.toString() === this.cell.modified.uri.toString()) {
          this.notebookEditor.deltaCellOutputContainerClassNames(DiffSide.Modified, this.cell.modified.id, ["nb-cellAdded"], []);
          insertOutputRenderListener.dispose();
        }
      });
      this.B(insertOutputRenderListener);
    }
    this.F.style.display = "block";
  }
  _decorate() {
    this.notebookEditor.deltaCellOutputContainerClassNames(DiffSide.Modified, this.cell.modified.id, ["nb-cellAdded"], []);
  }
  _showOutputsRenderer() {
    if (this.F) {
      this.F.style.display = "block";
      this.M?.showOutputs();
      this._decorate();
    }
  }
  _hideOutputsRenderer() {
    if (this.F) {
      this.F.style.display = "none";
      this.M?.hideOutputs();
    }
  }
  layout(state) {
    $jj(getWindow(this.Q), () => {
      if ((state.editorHeight || state.outerWidth) && this.pb) {
        this.j.style.height = `${this.cell.layoutInfo.editorHeight}px`;
        this.pb.layout({
          width: this.cell.getComputedCellContainerWidth(this.notebookEditor.getLayoutInfo(), false, false),
          height: this.cell.layoutInfo.editorHeight
        });
      }
      if (state.outerWidth && this.pb) {
        this.j.style.height = `${this.cell.layoutInfo.editorHeight}px`;
        this.pb.layout();
      }
      if (state.metadataHeight || state.outerWidth) {
        this.w?.layout({
          width: this.cell.getComputedCellContainerWidth(this.notebookEditor.getLayoutInfo(), false, true),
          height: this.cell.layoutInfo.metadataHeight
        });
      }
      if (state.outputTotalHeight || state.outerWidth) {
        this.O?.layout({
          width: this.cell.getComputedCellContainerWidth(this.notebookEditor.getLayoutInfo(), false, false),
          height: this.cell.layoutInfo.outputTotalHeight
        });
      }
      this.ob();
      if (this.R) {
        this.R.style.height = `${this.qb()}px`;
      }
    });
  }
  dispose() {
    if (this.pb) {
      this.cell.saveSpirceEditorViewState(this.pb.saveViewState());
    }
    super.dispose();
  }
};
$o2b = __decorate([
  __param(3, $Pk),
  __param(4, $1E),
  __param(5, $sG),
  __param(6, $oG),
  __param(7, $50),
  __param(8, $Ty),
  __param(9, $PJ),
  __param(10, $cJ),
  __param(11, $on),
  __param(12, $kl),
  __param(13, $zG)
], $o2b);
var $p2b = class $p2b2 extends AbstractElementRenderer {
  constructor(notebookEditor, cell, templateData, instantiationService, languageService, modelService, textModelService, contextMenuService, keybindingService, notificationService, menuService, contextKeyService, configurationService, textConfigurationService) {
    super(notebookEditor, cell, templateData, "full", instantiationService, languageService, modelService, textModelService, contextMenuService, keybindingService, notificationService, menuService, contextKeyService, configurationService, textConfigurationService);
    this.cell = cell;
    this.templateData = templateData;
    this.qb = false;
    this.updateBorders();
  }
  init() {
  }
  styleContainer(container2) {
    container2.classList.remove("inserted", "removed");
  }
  buildBody() {
    super.buildBody();
    if (this.cell.displayIconToHideUnmodifiedCells) {
      this.B(this.templateData.marginOverlay.onAction(() => this.cell.hideUnchangedCells()));
      this.templateData.marginOverlay.show();
    } else {
      this.templateData.marginOverlay.hide();
    }
  }
  _disposeMetadata() {
    this.cell.metadataStatusHeight = 0;
    this.cell.metadataHeight = 0;
    this.templateData.metadataHeaderContainer.style.display = "none";
    this.templateData.metadataInfoContainer.style.display = "none";
    this.w = void 0;
  }
  _buildMetadata() {
    this.n = this.templateData.metadataHeaderContainer;
    this.s = this.templateData.metadataInfoContainer;
    this.n.style.display = "flex";
    this.s.style.display = "block";
    this.n.innerText = "";
    this.s.innerText = "";
    this.r = this.U.createInstance(PropertyHeader, this.cell, this.n, this.notebookEditor, {
      updateInfoRendering: this.updateMetadataRendering.bind(this),
      checkIfModified: () => {
        return this.cell.checkMetadataIfModified();
      },
      getFoldingState: () => {
        return this.cell.metadataFoldingState;
      },
      updateFoldingState: (state) => {
        this.cell.metadataFoldingState = state;
      },
      unChangedLabel: "Metadata",
      changedLabel: "Metadata changed",
      prefix: "metadata",
      menuId: $bJ.NotebookDiffCellMetadataTitle
    });
    this.a.add(this.r);
    this.r.buildHeader();
  }
  _disposeOutput() {
    this.jb();
    this._hideOutputsRenderer();
    this.kb();
    this.cell.rawOutputHeight = 0;
    this.cell.outputMetadataHeight = 0;
    this.cell.outputStatusHeight = 0;
    this.templateData.outputHeaderContainer.style.display = "none";
    this.templateData.outputInfoContainer.style.display = "none";
    this.F = void 0;
  }
  _buildOutput() {
    this.templateData.outputHeaderContainer.style.display = "flex";
    this.templateData.outputInfoContainer.style.display = "block";
    this.y = this.templateData.outputHeaderContainer;
    this.C = this.templateData.outputInfoContainer;
    this.y.innerText = "";
    this.C.innerText = "";
    if (this.cell.checkIfOutputsModified()) {
      this.C.classList.add("modified");
    } else {
      this.C.classList.remove("modified");
    }
    this.z = this.U.createInstance(PropertyHeader, this.cell, this.y, this.notebookEditor, {
      updateInfoRendering: this.updateOutputRendering.bind(this),
      checkIfModified: () => {
        return this.cell.checkIfOutputsModified();
      },
      getFoldingState: () => {
        return this.cell.outputFoldingState;
      },
      updateFoldingState: (state) => {
        this.cell.outputFoldingState = state;
      },
      unChangedLabel: "Outputs",
      changedLabel: "Outputs changed",
      prefix: "output",
      menuId: $bJ.NotebookDiffCellOutputsTitle
    });
    this.b.add(this.z);
    this.z.buildHeader();
  }
  _buildOutputRendererContainer() {
    if (!this.F) {
      this.F = $bk(this.C, $(".output-view-container"));
      this.J = $bk(this.F, $(".output-empty-view"));
      this.J.innerText = "No outputs to render";
      if (!this.cell.checkIfOutputsModified() && this.cell.modified.outputs.length === 0) {
        this.J.style.display = "block";
      } else {
        this.J.style.display = "none";
      }
      this.cell.layoutChange();
      this.B(this.cell.modified.textModel.onDidChangeOutputs(() => {
        if (!this.cell.checkIfOutputsModified() && this.cell.modified.outputs.length === 0) {
          this.J.style.display = "block";
        } else {
          this.J.style.display = "none";
        }
        this._decorate();
      }));
      this.G = $bk(this.F, $(".output-view-container-left"));
      this.H = $bk(this.F, $(".output-view-container-right"));
      this.I = $bk(this.F, $(".output-view-container-metadata"));
      const outputModified = this.cell.checkIfOutputsModified();
      const outputMetadataChangeOnly = outputModified && outputModified.kind === 1 && this.cell.original.outputs.length === 1 && this.cell.modified.outputs.length === 1 && $qEb(this.cell.original.outputs[0], this.cell.modified.outputs[0]) === 1;
      if (outputModified && !outputMetadataChangeOnly) {
        const originalOutputRenderListener = this.notebookEditor.onDidDynamicOutputRendered((e) => {
          if (e.cell.uri.toString() === this.cell.original.uri.toString() && this.cell.checkIfOutputsModified()) {
            this.notebookEditor.deltaCellOutputContainerClassNames(DiffSide.Original, this.cell.original.id, ["nb-cellDeleted"], []);
            originalOutputRenderListener.dispose();
          }
        });
        const modifiedOutputRenderListener = this.notebookEditor.onDidDynamicOutputRendered((e) => {
          if (e.cell.uri.toString() === this.cell.modified.uri.toString() && this.cell.checkIfOutputsModified()) {
            this.notebookEditor.deltaCellOutputContainerClassNames(DiffSide.Modified, this.cell.modified.id, ["nb-cellAdded"], []);
            modifiedOutputRenderListener.dispose();
          }
        });
        this.B(originalOutputRenderListener);
        this.B(modifiedOutputRenderListener);
      }
      this.L = this.U.createInstance($i2b, this.notebookEditor, this.notebookEditor.textModel, this.cell, this.cell.original, DiffSide.Original, this.G);
      this.L.render();
      this.B(this.L);
      this.M = this.U.createInstance($i2b, this.notebookEditor, this.notebookEditor.textModel, this.cell, this.cell.modified, DiffSide.Modified, this.H);
      this.M.render();
      this.B(this.M);
      if (outputModified && !outputMetadataChangeOnly) {
        this._decorate();
      }
      if (outputMetadataChangeOnly) {
        this.I.style.top = `${this.cell.layoutInfo.rawOutputHeight}px`;
        this.P = this.U.createInstance($c_, this.I, {
          ...$YDb,
          overflowWidgetsDomNode: this.notebookEditor.getOverflowContainerDomNode(),
          readOnly: true,
          ignoreTrimWhitespace: false,
          automaticLayout: false,
          dimension: {
            height: $jEb,
            width: this.cell.getComputedCellContainerWidth(this.notebookEditor.getLayoutInfo(), false, true)
          }
        }, {
          originalEditor: $k2b(),
          modifiedEditor: $k2b()
        });
        this.B(this.P);
        const originalOutputMetadataSource = JSON.stringify(this.cell.original.outputs[0].metadata ?? {}, void 0, "	");
        const modifiedOutputMetadataSource = JSON.stringify(this.cell.modified.outputs[0].metadata ?? {}, void 0, "	");
        const mode = this.W.createById("json");
        const originalModel = this.X.createModel(originalOutputMetadataSource, mode, void 0, true);
        const modifiedModel = this.X.createModel(modifiedOutputMetadataSource, mode, void 0, true);
        this.P.setModel({
          original: originalModel,
          modified: modifiedModel
        });
        this.cell.outputMetadataHeight = this.P.getContentHeight();
        this.B(this.P.onDidContentSizeChange((e) => {
          this.cell.outputMetadataHeight = e.contentHeight;
        }));
      }
    }
    this.F.style.display = "block";
  }
  _decorate() {
    if (this.cell.checkIfOutputsModified()) {
      this.notebookEditor.deltaCellOutputContainerClassNames(DiffSide.Original, this.cell.original.id, ["nb-cellDeleted"], []);
      this.notebookEditor.deltaCellOutputContainerClassNames(DiffSide.Modified, this.cell.modified.id, ["nb-cellAdded"], []);
    } else {
      this.notebookEditor.deltaCellOutputContainerClassNames(DiffSide.Original, this.cell.original.id, [], ["nb-cellDeleted"]);
      this.notebookEditor.deltaCellOutputContainerClassNames(DiffSide.Modified, this.cell.modified.id, [], ["nb-cellAdded"]);
    }
  }
  _showOutputsRenderer() {
    if (this.F) {
      this.F.style.display = "block";
      this.L?.showOutputs();
      this.M?.showOutputs();
      this.P?.layout({
        width: this.pb?.getViewWidth() || this.cell.getComputedCellContainerWidth(this.notebookEditor.getLayoutInfo(), false, true),
        height: this.cell.layoutInfo.outputMetadataHeight
      });
      this._decorate();
    }
  }
  _hideOutputsRenderer() {
    if (this.F) {
      this.F.style.display = "none";
      this.L?.hideOutputs();
      this.M?.hideOutputs();
    }
  }
  updateSourceEditor() {
    this.g = this.templateData.cellHeaderContainer;
    this.g.style.display = "flex";
    this.g.innerText = "";
    const modifiedCell = this.cell.modified;
    this.j = this.templateData.editorContainer;
    this.j.classList.add("diff");
    const renderSourceEditor = () => {
      if (this.cell.cellFoldingState === PropertyFoldingState.Collapsed) {
        this.j.style.display = "none";
        this.cell.editorHeight = 0;
        return;
      }
      const lineCount = modifiedCell.textModel.textBuffer.getLineCount();
      const lineHeight = this.notebookEditor.getLayoutInfo().fontInfo.lineHeight || 17;
      const editorHeight = this.cell.layoutInfo.editorHeight !== 0 ? this.cell.layoutInfo.editorHeight : this.cell.computeInputEditorHeight(lineHeight);
      this.j.style.height = `${editorHeight}px`;
      this.j.style.display = "block";
      if (this.pb) {
        const contentHeight = this.pb.getContentHeight();
        if (contentHeight >= 0) {
          this.cell.editorHeight = contentHeight;
        }
        return;
      }
      this.pb = this.templateData.sourceEditor;
      const options3 = {
        padding: $WDb(lineCount)
      };
      const unchangedRegions = this.B($j2b(this.eb));
      if (unchangedRegions.options.enabled) {
        options3.hideUnchangedRegions = unchangedRegions.options;
      }
      this.pb.updateOptions(options3);
      this.B(unchangedRegions.onDidChangeEnablement(() => {
        options3.hideUnchangedRegions = unchangedRegions.options;
        this.pb?.updateOptions(options3);
      }));
      this.pb.layout({
        width: this.notebookEditor.getLayoutInfo().width - 2 * $ZDb,
        height: editorHeight
      });
      this.B(this.pb.onDidContentSizeChange((e) => {
        if (this.cell.cellFoldingState === PropertyFoldingState.Expanded && e.contentHeightChanged && this.cell.layoutInfo.editorHeight !== e.contentHeight) {
          this.cell.editorHeight = e.contentHeight;
        }
      }));
      this.tb();
    };
    this.m = this.B(this.U.createInstance(PropertyHeader, this.cell, this.g, this.notebookEditor, {
      updateInfoRendering: () => renderSourceEditor(),
      checkIfModified: () => {
        return this.cell.modified?.textModel.getTextBufferHash() !== this.cell.original?.textModel.getTextBufferHash() ? { reason: void 0 } : false;
      },
      getFoldingState: () => this.cell.cellFoldingState,
      updateFoldingState: (state) => this.cell.cellFoldingState = state,
      unChangedLabel: "Input",
      changedLabel: "Input changed",
      prefix: "input",
      menuId: $bJ.NotebookDiffCellInputTitle
    }));
    this.m.buildHeader();
    renderSourceEditor();
    const scopedContextKeyService = this.db.createScoped(this.templateData.inputToolbarContainer);
    this.B(scopedContextKeyService);
    const inputChanged = $1Db.bindTo(scopedContextKeyService);
    inputChanged.set(this.cell.modified.textModel.getTextBufferHash() !== this.cell.original.textModel.getTextBufferHash());
    const ignoreWhitespace = $4Db.bindTo(scopedContextKeyService);
    const ignore = this.fb.getValue(this.cell.modified.uri, "diffEditor.ignoreTrimWhitespace");
    ignoreWhitespace.set(ignore);
    this.rb = this.templateData.toolbar;
    this.rb.context = this.cell;
    const refreshToolbar = () => {
      const ignore2 = this.fb.getValue(this.cell.modified.uri, "diffEditor.ignoreTrimWhitespace");
      ignoreWhitespace.set(ignore2);
      const hasChanges = this.cell.modified.textModel.getTextBufferHash() !== this.cell.original.textModel.getTextBufferHash();
      inputChanged.set(hasChanges);
      if (hasChanges) {
        const menu = this.cb.getMenuActions($bJ.NotebookDiffCellInputTitle, scopedContextKeyService, { shouldForwardArgs: true });
        const actions = $R$(menu);
        this.rb.setActions(actions);
      } else {
        this.rb.setActions([]);
      }
    };
    this.B(this.cell.modified.textModel.onDidChangeContent(() => refreshToolbar()));
    this.B(this.fb.onDidChangeConfiguration((e) => {
      if (e.affectsConfiguration(this.cell.modified.uri, "diffEditor") && e.affectedKeys.has("diffEditor.ignoreTrimWhitespace")) {
        refreshToolbar();
      }
    }));
    refreshToolbar();
  }
  async tb() {
    const [originalRef, modifiedRef] = await Promise.all([
      this.Y.createModelReference(this.cell.original.uri),
      this.Y.createModelReference(this.cell.modified.uri)
    ]);
    this.B(originalRef);
    this.B(modifiedRef);
    if (this.S) {
      originalRef.dispose();
      modifiedRef.dispose();
      return;
    }
    const vm = this.B(this.pb.createViewModel({
      original: originalRef.object.textEditorModel,
      modified: modifiedRef.object.textEditorModel
    }));
    await vm.waitForDiff();
    this.pb.setModel(vm);
    const handleViewStateChange = () => {
      this.qb = true;
    };
    const handleScrollChange = (e) => {
      if (e.scrollTopChanged || e.scrollLeftChanged) {
        this.qb = true;
      }
    };
    this.ub();
    this.B(this.pb.getOriginalEditor().onDidChangeCursorSelection(handleViewStateChange));
    this.B(this.pb.getOriginalEditor().onDidScrollChange(handleScrollChange));
    this.B(this.pb.getModifiedEditor().onDidChangeCursorSelection(handleViewStateChange));
    this.B(this.pb.getModifiedEditor().onDidScrollChange(handleScrollChange));
    const editorViewState = this.cell.getSourceEditorViewState();
    if (editorViewState) {
      this.pb.restoreViewState(editorViewState);
    }
    const contentHeight = this.pb.getContentHeight();
    this.cell.editorHeight = contentHeight;
  }
  ub() {
    const editor = this.pb;
    if (!editor) {
      return;
    }
    const uri = editor.getModel()?.modified.uri || editor.getModel()?.original.uri;
    if (!uri) {
      return;
    }
    const ignoreTrimWhitespace = this.fb.getValue(uri, "diffEditor.ignoreTrimWhitespace");
    editor.updateOptions({ ignoreTrimWhitespace });
    this.B(this.fb.onDidChangeConfiguration((e) => {
      if (e.affectsConfiguration(uri, "diffEditor") && e.affectedKeys.has("diffEditor.ignoreTrimWhitespace")) {
        const ignoreTrimWhitespace2 = this.fb.getValue(uri, "diffEditor.ignoreTrimWhitespace");
        editor.updateOptions({ ignoreTrimWhitespace: ignoreTrimWhitespace2 });
      }
    }));
  }
  layout(state) {
    $jj(getWindow(this.Q), () => {
      if (state.editorHeight && this.pb) {
        this.j.style.height = `${this.cell.layoutInfo.editorHeight}px`;
        this.pb.layout({
          width: this.pb.getViewWidth(),
          height: this.cell.layoutInfo.editorHeight
        });
      }
      if (state.outerWidth && this.pb) {
        this.j.style.height = `${this.cell.layoutInfo.editorHeight}px`;
        this.pb.layout();
      }
      if (state.metadataHeight || state.outerWidth) {
        if (this.t) {
          this.t.style.height = `${this.cell.layoutInfo.metadataHeight}px`;
          this.w?.layout({
            width: this.pb?.getViewWidth() || this.cell.getComputedCellContainerWidth(this.notebookEditor.getLayoutInfo(), false, true),
            height: this.cell.layoutInfo.metadataHeight
          });
        }
      }
      if (state.outputTotalHeight || state.outerWidth) {
        if (this.D) {
          this.D.style.height = `${this.cell.layoutInfo.outputTotalHeight}px`;
          this.O?.layout({
            width: this.pb?.getViewWidth() || this.cell.getComputedCellContainerWidth(this.notebookEditor.getLayoutInfo(), false, true),
            height: this.cell.layoutInfo.outputTotalHeight
          });
        }
        if (this.I) {
          this.I.style.height = `${this.cell.layoutInfo.outputMetadataHeight}px`;
          this.I.style.top = `${this.cell.layoutInfo.outputTotalHeight - this.cell.layoutInfo.outputMetadataHeight}px`;
          this.P?.layout({
            width: this.pb?.getViewWidth() || this.cell.getComputedCellContainerWidth(this.notebookEditor.getLayoutInfo(), false, true),
            height: this.cell.layoutInfo.outputMetadataHeight
          });
        }
      }
      this.ob();
    });
  }
  dispose() {
    if (this.pb) {
      this.pb.setModel(null);
    }
    if (this.pb && this.qb) {
      this.cell.saveSpirceEditorViewState(this.pb.saveViewState());
    }
    super.dispose();
  }
};
$p2b = __decorate([
  __param(3, $Pk),
  __param(4, $1E),
  __param(5, $sG),
  __param(6, $oG),
  __param(7, $50),
  __param(8, $Ty),
  __param(9, $PJ),
  __param(10, $cJ),
  __param(11, $on),
  __param(12, $kl),
  __param(13, $zG)
], $p2b);
var $q2b = class extends $3c {
  constructor(c) {
    super();
    this.c = c;
    this.a = h("div.diff-hidden-cells", [
      h("div.center@content", { style: { display: "flex" } }, [
        $("a", {
          title: localize(8362, null),
          role: "button",
          onclick: () => {
            this.b.fire();
          }
        }, ...$B1("$(unfold)"))
      ])
    ]);
    this.b = this.B(new $ze());
    this.onAction = this.b.event;
    this.a.root.style.display = "none";
    c.appendChild(this.a.root);
  }
  show() {
    this.a.root.style.display = "block";
  }
  hide() {
    this.a.root.style.display = "none";
  }
  dispose() {
    this.hide();
    this.c.removeChild(this.a.root);
    $dk(this.a.root);
    super.dispose();
  }
};
var $r2b = class extends $3c {
  constructor(c) {
    super();
    this.c = c;
    this.a = h("div.diff-hidden-cells", [
      h("div.center@content", { style: { display: "flex" } }, [
        $("a", {
          title: localize(8363, null),
          role: "button",
          onclick: () => {
            this.b.fire();
          }
        }, ...$B1("$(fold)"))
      ])
    ]);
    this.b = this.B(new $ze());
    this.onAction = this.b.event;
    this.a.root.style.display = "none";
    c.appendChild(this.a.root);
  }
  show() {
    this.a.root.style.display = "block";
  }
  hide() {
    this.a.root.style.display = "none";
  }
  dispose() {
    this.hide();
    this.c.removeChild(this.a.root);
    $dk(this.a.root);
    super.dispose();
  }
};

// out-build/vs/workbench/contrib/notebook/browser/diff/notebookDiffList.js
var $t2b_1;
var $u2b_1;
var $v2b_1;
var $w2b_1;
var $s2b = class $s2b2 {
  constructor(targetWindow, b) {
    this.b = b;
    const editorOptions2 = this.b.getValue("editor");
    this.a = $ED.createFromRawSettings(editorOptions2, $_1.getInstance(targetWindow).value).lineHeight;
  }
  getHeight(element) {
    return element.getHeight(this.a);
  }
  hasDynamicHeight(element) {
    return false;
  }
  getTemplateId(element) {
    switch (element.type) {
      case "delete":
      case "insert":
        return $v2b.TEMPLATE_ID;
      case "modified":
      case "unchanged":
        return $w2b.TEMPLATE_ID;
      case "placeholder":
        return $t2b.TEMPLATE_ID;
      case "modifiedMetadata":
      case "unchangedMetadata":
        return $u2b.TEMPLATE_ID;
    }
  }
};
$s2b = __decorate([
  __param(1, $kl)
], $s2b);
var $t2b = class $t2b2 {
  static {
    $t2b_1 = this;
  }
  static {
    this.TEMPLATE_ID = "cell_diff_placeholder";
  }
  constructor(notebookEditor, a) {
    this.notebookEditor = notebookEditor;
    this.a = a;
  }
  get templateId() {
    return $t2b_1.TEMPLATE_ID;
  }
  renderTemplate(container2) {
    const body = $(".cell-placeholder-body");
    $bk(container2, body);
    const elementDisposables = new $2c();
    const marginOverlay = new $q2b(body);
    const contents = $bk(body, $(".contents"));
    const placeholder = $bk(contents, $("span.text", { title: localize(8396, null) }));
    return {
      body,
      container: container2,
      placeholder,
      marginOverlay,
      elementDisposables
    };
  }
  renderElement(element, index, templateData, height) {
    templateData.body.classList.remove("left", "right", "full");
    templateData.elementDisposables.add(this.a.createInstance($l2b, element, templateData));
  }
  disposeTemplate(templateData) {
    templateData.container.innerText = "";
  }
  disposeElement(element, index, templateData) {
    templateData.elementDisposables.clear();
  }
};
$t2b = $t2b_1 = __decorate([
  __param(1, $Pk)
], $t2b);
var $u2b = class $u2b2 {
  static {
    $u2b_1 = this;
  }
  static {
    this.TEMPLATE_ID = "notebook_metadata_diff_side_by_side";
  }
  constructor(notebookEditor, a, b, d, f, g, h3, i2, j) {
    this.notebookEditor = notebookEditor;
    this.a = a;
    this.b = b;
    this.d = d;
    this.f = f;
    this.g = g;
    this.h = h3;
    this.i = i2;
    this.j = j;
  }
  get templateId() {
    return $u2b_1.TEMPLATE_ID;
  }
  renderTemplate(container2) {
    const body = $(".cell-body");
    $bk(container2, body);
    const diffEditorContainer = $(".cell-diff-editor-container");
    $bk(body, diffEditorContainer);
    const cellHeaderContainer = $bk(diffEditorContainer, $(".input-header-container"));
    const sourceContainer = $bk(diffEditorContainer, $(".source-container"));
    const { editor, editorContainer } = this.k(sourceContainer);
    const inputToolbarContainer = $bk(sourceContainer, $(".editor-input-toolbar-container"));
    const cellToolbarContainer = $bk(inputToolbarContainer, $("div.property-toolbar"));
    const toolbar = this.a.createInstance($3$, cellToolbarContainer, {
      actionViewItemProvider: (action, options3) => {
        if (action instanceof $fJ) {
          const item = new $rKb(action, { hoverDelegate: options3.hoverDelegate }, this.d, this.h, this.g, this.i, this.b, this.j);
          return item;
        }
        return void 0;
      },
      highlightToggledItems: true
    });
    const borderContainer = $bk(body, $(".border-container"));
    const leftBorder = $bk(borderContainer, $(".left-border"));
    const rightBorder = $bk(borderContainer, $(".right-border"));
    const topBorder = $bk(borderContainer, $(".top-border"));
    const bottomBorder = $bk(borderContainer, $(".bottom-border"));
    const marginOverlay = new $r2b(body);
    const elementDisposables = new $2c();
    return {
      body,
      container: container2,
      diffEditorContainer,
      cellHeaderContainer,
      sourceEditor: editor,
      editorContainer,
      inputToolbarContainer,
      toolbar,
      leftBorder,
      rightBorder,
      topBorder,
      bottomBorder,
      marginOverlay,
      elementDisposables
    };
  }
  k(sourceContainer) {
    return buildDiffEditorWidget(this.a, this.notebookEditor, sourceContainer, { readOnly: true });
  }
  renderElement(element, index, templateData, height) {
    templateData.body.classList.remove("full");
    templateData.elementDisposables.add(this.a.createInstance($m2b, this.notebookEditor, element, templateData));
  }
  disposeTemplate(templateData) {
    templateData.container.innerText = "";
    templateData.sourceEditor.dispose();
    templateData.toolbar?.dispose();
    templateData.elementDisposables.dispose();
  }
  disposeElement(element, index, templateData) {
    if (templateData.toolbar) {
      templateData.toolbar.context = void 0;
    }
    templateData.elementDisposables.clear();
  }
};
$u2b = $u2b_1 = __decorate([
  __param(1, $Pk),
  __param(2, $50),
  __param(3, $Ty),
  __param(4, $cJ),
  __param(5, $on),
  __param(6, $PJ),
  __param(7, $gs),
  __param(8, $ND)
], $u2b);
var $v2b = class $v2b2 {
  static {
    $v2b_1 = this;
  }
  static {
    this.TEMPLATE_ID = "cell_diff_single";
  }
  constructor(notebookEditor, a) {
    this.notebookEditor = notebookEditor;
    this.a = a;
  }
  get templateId() {
    return $v2b_1.TEMPLATE_ID;
  }
  renderTemplate(container2) {
    const body = $(".cell-body");
    $bk(container2, body);
    const diffEditorContainer = $(".cell-diff-editor-container");
    $bk(body, diffEditorContainer);
    const diagonalFill = $bk(body, $(".diagonal-fill"));
    const cellHeaderContainer = $bk(diffEditorContainer, $(".input-header-container"));
    const sourceContainer = $bk(diffEditorContainer, $(".source-container"));
    const { editor, editorContainer } = this.b(sourceContainer);
    const metadataHeaderContainer = $bk(diffEditorContainer, $(".metadata-header-container"));
    const metadataInfoContainer = $bk(diffEditorContainer, $(".metadata-info-container"));
    const outputHeaderContainer = $bk(diffEditorContainer, $(".output-header-container"));
    const outputInfoContainer = $bk(diffEditorContainer, $(".output-info-container"));
    const borderContainer = $bk(body, $(".border-container"));
    const leftBorder = $bk(borderContainer, $(".left-border"));
    const rightBorder = $bk(borderContainer, $(".right-border"));
    const topBorder = $bk(borderContainer, $(".top-border"));
    const bottomBorder = $bk(borderContainer, $(".bottom-border"));
    return {
      body,
      container: container2,
      editorContainer,
      diffEditorContainer,
      diagonalFill,
      cellHeaderContainer,
      sourceEditor: editor,
      metadataHeaderContainer,
      metadataInfoContainer,
      outputHeaderContainer,
      outputInfoContainer,
      leftBorder,
      rightBorder,
      topBorder,
      bottomBorder,
      elementDisposables: new $2c()
    };
  }
  b(sourceContainer) {
    return buildSourceEditor(this.a, this.notebookEditor, sourceContainer);
  }
  renderElement(element, index, templateData, height) {
    templateData.body.classList.remove("left", "right", "full");
    switch (element.type) {
      case "delete":
        templateData.elementDisposables.add(this.a.createInstance($n2b, this.notebookEditor, element, templateData));
        return;
      case "insert":
        templateData.elementDisposables.add(this.a.createInstance($o2b, this.notebookEditor, element, templateData));
        return;
      default:
        break;
    }
  }
  disposeTemplate(templateData) {
    templateData.container.innerText = "";
    templateData.sourceEditor.dispose();
    templateData.elementDisposables.dispose();
  }
  disposeElement(element, index, templateData) {
    templateData.elementDisposables.clear();
  }
};
$v2b = $v2b_1 = __decorate([
  __param(1, $Pk)
], $v2b);
var $w2b = class $w2b2 {
  static {
    $w2b_1 = this;
  }
  static {
    this.TEMPLATE_ID = "cell_diff_side_by_side";
  }
  constructor(notebookEditor, a, b, d, f, g, h3, i2, j) {
    this.notebookEditor = notebookEditor;
    this.a = a;
    this.b = b;
    this.d = d;
    this.f = f;
    this.g = g;
    this.h = h3;
    this.i = i2;
    this.j = j;
  }
  get templateId() {
    return $w2b_1.TEMPLATE_ID;
  }
  renderTemplate(container2) {
    const body = $(".cell-body");
    $bk(container2, body);
    const diffEditorContainer = $(".cell-diff-editor-container");
    $bk(body, diffEditorContainer);
    const cellHeaderContainer = $bk(diffEditorContainer, $(".input-header-container"));
    const sourceContainer = $bk(diffEditorContainer, $(".source-container"));
    const { editor, editorContainer } = this.k(sourceContainer);
    const inputToolbarContainer = $bk(sourceContainer, $(".editor-input-toolbar-container"));
    const cellToolbarContainer = $bk(inputToolbarContainer, $("div.property-toolbar"));
    const toolbar = this.a.createInstance($3$, cellToolbarContainer, {
      actionViewItemProvider: (action, options3) => {
        if (action instanceof $fJ) {
          const item = new $rKb(action, { hoverDelegate: options3.hoverDelegate }, this.d, this.h, this.g, this.i, this.b, this.j);
          return item;
        }
        return void 0;
      },
      highlightToggledItems: true
    });
    const metadataHeaderContainer = $bk(diffEditorContainer, $(".metadata-header-container"));
    const metadataInfoContainer = $bk(diffEditorContainer, $(".metadata-info-container"));
    const outputHeaderContainer = $bk(diffEditorContainer, $(".output-header-container"));
    const outputInfoContainer = $bk(diffEditorContainer, $(".output-info-container"));
    const borderContainer = $bk(body, $(".border-container"));
    const leftBorder = $bk(borderContainer, $(".left-border"));
    const rightBorder = $bk(borderContainer, $(".right-border"));
    const topBorder = $bk(borderContainer, $(".top-border"));
    const bottomBorder = $bk(borderContainer, $(".bottom-border"));
    const marginOverlay = new $r2b(body);
    const elementDisposables = new $2c();
    return {
      body,
      container: container2,
      diffEditorContainer,
      cellHeaderContainer,
      sourceEditor: editor,
      editorContainer,
      inputToolbarContainer,
      toolbar,
      metadataHeaderContainer,
      metadataInfoContainer,
      outputHeaderContainer,
      outputInfoContainer,
      leftBorder,
      rightBorder,
      topBorder,
      bottomBorder,
      marginOverlay,
      elementDisposables
    };
  }
  k(sourceContainer) {
    return buildDiffEditorWidget(this.a, this.notebookEditor, sourceContainer);
  }
  renderElement(element, index, templateData, height) {
    templateData.body.classList.remove("left", "right", "full");
    switch (element.type) {
      case "unchanged":
        templateData.elementDisposables.add(this.a.createInstance($p2b, this.notebookEditor, element, templateData));
        return;
      case "modified":
        templateData.elementDisposables.add(this.a.createInstance($p2b, this.notebookEditor, element, templateData));
        return;
      default:
        break;
    }
  }
  disposeTemplate(templateData) {
    templateData.container.innerText = "";
    templateData.sourceEditor.dispose();
    templateData.toolbar?.dispose();
    templateData.elementDisposables.dispose();
  }
  disposeElement(element, index, templateData) {
    if (templateData.toolbar) {
      templateData.toolbar.context = void 0;
    }
    templateData.elementDisposables.clear();
  }
};
$w2b = $w2b_1 = __decorate([
  __param(1, $Pk),
  __param(2, $50),
  __param(3, $Ty),
  __param(4, $cJ),
  __param(5, $on),
  __param(6, $PJ),
  __param(7, $gs),
  __param(8, $ND)
], $w2b);
var $x2b = class extends $x1 {
  v(e) {
    if ($n1(e.browserEvent.target)) {
      const focus = typeof e.index === "undefined" ? [] : [e.index];
      this.o.setFocus(focus, e.browserEvent);
    } else {
      super.v(e);
    }
  }
};
var $y2b = class $y2b2 extends $Web {
  get rowsContainer() {
    return this.o.containerDomNode;
  }
  constructor(listUser, container2, delegate, renderers, contextKeyService, options3, listService, configurationService, instantiationService) {
    super(listUser, container2, delegate, renderers, options3, contextKeyService, listService, configurationService, instantiationService);
  }
  E(options3) {
    return new $x2b(this);
  }
  getCellViewScrollTop(element) {
    const index = this.indexOf(element);
    return this.o.elementTop(index);
  }
  getScrollHeight() {
    return this.o.scrollHeight;
  }
  triggerScrollFromMouseWheelEvent(browserEvent) {
    this.o.delegateScrollFromMouseWheelEvent(browserEvent);
  }
  delegateVerticalScrollbarPointerDown(browserEvent) {
    this.o.delegateVerticalScrollbarPointerDown(browserEvent);
  }
  clear() {
    super.splice(0, this.length);
  }
  updateElementHeight2(element, size) {
    const viewIndex = this.indexOf(element);
    const focused = this.getFocus();
    this.o.updateElementHeight(viewIndex, size, focused.length ? focused[0] : null);
  }
  style(styles) {
    const selectorSuffix = this.o.domId;
    if (!this.p) {
      this.p = $VZ(this.o.domNode);
    }
    const suffix = selectorSuffix && `.${selectorSuffix}`;
    const content = [];
    if (styles.listBackground) {
      content.push(`.monaco-list${suffix} > div.monaco-scrollable-element > .monaco-list-rows { background: ${styles.listBackground}; }`);
    }
    if (styles.listFocusBackground) {
      content.push(`.monaco-list${suffix}:focus > div.monaco-scrollable-element > .monaco-list-rows > .monaco-list-row.focused { background-color: ${styles.listFocusBackground}; }`);
      content.push(`.monaco-list${suffix}:focus > div.monaco-scrollable-element > .monaco-list-rows > .monaco-list-row.focused:hover { background-color: ${styles.listFocusBackground}; }`);
    }
    if (styles.listFocusForeground) {
      content.push(`.monaco-list${suffix}:focus > div.monaco-scrollable-element > .monaco-list-rows > .monaco-list-row.focused { color: ${styles.listFocusForeground}; }`);
    }
    if (styles.listActiveSelectionBackground) {
      content.push(`.monaco-list${suffix}:focus > div.monaco-scrollable-element > .monaco-list-rows > .monaco-list-row.selected { background-color: ${styles.listActiveSelectionBackground}; }`);
      content.push(`.monaco-list${suffix}:focus > div.monaco-scrollable-element > .monaco-list-rows > .monaco-list-row.selected:hover { background-color: ${styles.listActiveSelectionBackground}; }`);
    }
    if (styles.listActiveSelectionForeground) {
      content.push(`.monaco-list${suffix}:focus > div.monaco-scrollable-element > .monaco-list-rows > .monaco-list-row.selected { color: ${styles.listActiveSelectionForeground}; }`);
    }
    if (styles.listFocusAndSelectionBackground) {
      content.push(`
				.monaco-drag-image,
				.monaco-list${suffix}:focus > div.monaco-scrollable-element > .monaco-list-rows > .monaco-list-row.selected.focused { background-color: ${styles.listFocusAndSelectionBackground}; }
			`);
    }
    if (styles.listFocusAndSelectionForeground) {
      content.push(`
				.monaco-drag-image,
				.monaco-list${suffix}:focus > div.monaco-scrollable-element > .monaco-list-rows > .monaco-list-row.selected.focused { color: ${styles.listFocusAndSelectionForeground}; }
			`);
    }
    if (styles.listInactiveFocusBackground) {
      content.push(`.monaco-list${suffix} > div.monaco-scrollable-element > .monaco-list-rows > .monaco-list-row.focused { background-color:  ${styles.listInactiveFocusBackground}; }`);
      content.push(`.monaco-list${suffix} > div.monaco-scrollable-element > .monaco-list-rows > .monaco-list-row.focused:hover { background-color:  ${styles.listInactiveFocusBackground}; }`);
    }
    if (styles.listInactiveSelectionBackground) {
      content.push(`.monaco-list${suffix} > div.monaco-scrollable-element > .monaco-list-rows > .monaco-list-row.selected { background-color:  ${styles.listInactiveSelectionBackground}; }`);
      content.push(`.monaco-list${suffix} > div.monaco-scrollable-element > .monaco-list-rows > .monaco-list-row.selected:hover { background-color:  ${styles.listInactiveSelectionBackground}; }`);
    }
    if (styles.listInactiveSelectionForeground) {
      content.push(`.monaco-list${suffix} > div.monaco-scrollable-element > .monaco-list-rows > .monaco-list-row.selected { color: ${styles.listInactiveSelectionForeground}; }`);
    }
    if (styles.listHoverBackground) {
      content.push(`.monaco-list${suffix}:not(.drop-target) > div.monaco-scrollable-element > .monaco-list-rows > .monaco-list-row:hover:not(.selected):not(.focused) { background-color:  ${styles.listHoverBackground}; }`);
    }
    if (styles.listHoverForeground) {
      content.push(`.monaco-list${suffix} > div.monaco-scrollable-element > .monaco-list-rows > .monaco-list-row:hover:not(.selected):not(.focused) { color:  ${styles.listHoverForeground}; }`);
    }
    if (styles.listSelectionOutline) {
      content.push(`.monaco-list${suffix} > div.monaco-scrollable-element > .monaco-list-rows > .monaco-list-row.selected { outline: 1px dotted ${styles.listSelectionOutline}; outline-offset: -1px; }`);
    }
    if (styles.listFocusOutline) {
      content.push(`
				.monaco-drag-image,
				.monaco-list${suffix}:focus > div.monaco-scrollable-element > .monaco-list-rows > .monaco-list-row.focused { outline: 1px solid ${styles.listFocusOutline}; outline-offset: -1px; }
			`);
    }
    if (styles.listInactiveFocusOutline) {
      content.push(`.monaco-list${suffix} > div.monaco-scrollable-element > .monaco-list-rows > .monaco-list-row.focused { outline: 1px dotted ${styles.listInactiveFocusOutline}; outline-offset: -1px; }`);
    }
    if (styles.listHoverOutline) {
      content.push(`.monaco-list${suffix} > div.monaco-scrollable-element > .monaco-list-rows > .monaco-list-row:hover { outline: 1px dashed ${styles.listHoverOutline}; outline-offset: -1px; }`);
    }
    if (styles.listDropOverBackground) {
      content.push(`
				.monaco-list${suffix}.drop-target,
				.monaco-list${suffix} > div.monaco-scrollable-element > .monaco-list-rows.drop-target,
				.monaco-list${suffix} > div.monaco-scrollable-element > .monaco-list-row.drop-target { background-color: ${styles.listDropOverBackground} !important; color: inherit !important; }
			`);
    }
    const newStyles = content.join("\n");
    if (newStyles !== this.p.textContent) {
      this.p.textContent = newStyles;
    }
  }
};
$y2b = __decorate([
  __param(6, $Deb),
  __param(7, $kl),
  __param(8, $Pk)
], $y2b);
function buildDiffEditorWidget(instantiationService, notebookEditor, sourceContainer, options3 = {}) {
  const editorContainer = $bk(sourceContainer, $(".editor-container"));
  const editor = instantiationService.createInstance($c_, editorContainer, {
    ...$YDb,
    overflowWidgetsDomNode: notebookEditor.getOverflowContainerDomNode(),
    originalEditable: false,
    ignoreTrimWhitespace: false,
    automaticLayout: false,
    dimension: {
      height: 0,
      width: 0
    },
    renderSideBySide: true,
    useInlineViewWhenSpaceIsLimited: false,
    ...options3
  }, {
    originalEditor: $k2b(),
    modifiedEditor: $k2b()
  });
  return {
    editor,
    editorContainer
  };
}
function buildSourceEditor(instantiationService, notebookEditor, sourceContainer, options3 = {}) {
  const editorContainer = $bk(sourceContainer, $(".editor-container"));
  const skipContributions = [
    "editor.contrib.emptyTextEditorHint"
  ];
  const editor = instantiationService.createInstance($D9, editorContainer, {
    ...$XDb,
    glyphMargin: false,
    dimension: {
      width: (notebookEditor.getLayoutInfo().width - 2 * $ZDb) / 2 - 18,
      height: 0
    },
    automaticLayout: false,
    overflowWidgetsDomNode: notebookEditor.getOverflowContainerDomNode(),
    readOnly: true
  }, {
    contributions: EditorExtensionsRegistry.getEditorContributions().filter((c) => skipContributions.indexOf(c.id) === -1)
  });
  return { editor, editorContainer };
}

// out-build/vs/workbench/contrib/notebook/browser/diff/notebookDiffOverviewRuler.js
var MINIMUM_SLIDER_SIZE2 = 20;
var $z2b = class $z2b2 extends $ns {
  constructor(notebookEditor, width2, container2, themeService) {
    super(themeService);
    this.notebookEditor = notebookEditor;
    this.width = width2;
    this.g = [];
    this.j = 2;
    this.m = null;
    this.s = null;
    this.r = null;
    this.t = null;
    this.u = this.B(new $2c());
    this.y = null;
    this.c = $oZ(document.createElement("canvas"));
    this.c.setPosition("relative");
    this.c.setLayerHinting(true);
    this.c.setContain("strict");
    container2.appendChild(this.c.domNode);
    this.f = $oZ(document.createElement("div"));
    this.f.setClassName("diffViewport");
    this.f.setPosition("absolute");
    this.f.setWidth(width2);
    container2.appendChild(this.f.domNode);
    this.B($_1.getInstance(getWindow(this.c.domNode)).onDidChange(() => {
      this.D();
    }));
    this.B(this.n.onDidColorThemeChange((e) => {
      const colorChanged = this.C(e);
      if (colorChanged) {
        this.D();
      }
    }));
    this.C(this.n.getColorTheme());
    this.B(this.notebookEditor.onDidScroll(() => {
      this.H();
    }));
    this.B($aj(container2, $7j.POINTER_DOWN, (e) => {
      this.notebookEditor.delegateVerticalScrollbarPointerDown(e);
    }));
  }
  C(theme) {
    const newInsertColor = theme.getColor($Ip) || (theme.getColor($Cp) || $Ap).transparent(2);
    const newRemoveColor = theme.getColor($Jp) || (theme.getColor($Dp) || $Bp).transparent(2);
    const hasChanges = !newInsertColor.equals(this.m) || !newRemoveColor.equals(this.s);
    this.m = newInsertColor;
    this.s = newRemoveColor;
    if (this.m) {
      this.r = $Vn.Format.CSS.formatHexA(this.m);
    }
    if (this.s) {
      this.t = $Vn.Format.CSS.formatHexA(this.s);
    }
    return hasChanges;
  }
  layout() {
    this.G();
  }
  updateViewModels(elements, eventDispatcher) {
    this.u.clear();
    this.g = elements;
    if (eventDispatcher) {
      this.u.add(eventDispatcher.onDidChangeLayout(() => {
        this.D();
      }));
      this.u.add(eventDispatcher.onDidChangeCellLayout(() => {
        this.D();
      }));
    }
    this.D();
  }
  D() {
    if (this.y === null) {
      this.y = $ij(getWindow(this.c.domNode), this.F.bind(this), 16);
    }
  }
  F() {
    this.y = null;
    this.G();
  }
  G() {
    const layoutInfo = this.notebookEditor.getLayoutInfo();
    const height = layoutInfo.height;
    const contentHeight = this.g.map((view) => view.totalHeight).reduce((a, b) => a + b, 0);
    const ratio = $_1.getInstance(getWindow(this.c.domNode)).value;
    this.c.setWidth(this.width);
    this.c.setHeight(height);
    this.c.domNode.width = this.width * ratio;
    this.c.domNode.height = height * ratio;
    const ctx = this.c.domNode.getContext("2d");
    ctx.clearRect(0, 0, this.width * ratio, height * ratio);
    this.J(ctx, this.width * ratio, height * ratio, contentHeight * ratio, ratio);
    this.H();
  }
  H() {
    const layout = this.I();
    if (!layout) {
      this.f.setTop(0);
      this.f.setHeight(0);
    } else {
      this.f.setTop(layout.top);
      this.f.setHeight(layout.height);
    }
  }
  I() {
    const layoutInfo = this.notebookEditor.getLayoutInfo();
    if (!layoutInfo) {
      return null;
    }
    const scrollTop = this.notebookEditor.getScrollTop();
    const scrollHeight = this.notebookEditor.getScrollHeight();
    const computedAvailableSize = Math.max(0, layoutInfo.height);
    const computedRepresentableSize = Math.max(0, computedAvailableSize - 2 * 0);
    const visibleSize = layoutInfo.height;
    const computedSliderSize = Math.round(Math.max(MINIMUM_SLIDER_SIZE2, Math.floor(visibleSize * computedRepresentableSize / scrollHeight)));
    const computedSliderRatio = (computedRepresentableSize - computedSliderSize) / (scrollHeight - visibleSize);
    const computedSliderPosition = Math.round(scrollTop * computedSliderRatio);
    return {
      height: computedSliderSize,
      top: computedSliderPosition
    };
  }
  J(ctx, width2, height, scrollHeight, ratio) {
    if (!this.r || !this.t) {
      return;
    }
    const laneWidth = width2 / this.j;
    let currentFrom = 0;
    for (let i2 = 0; i2 < this.g.length; i2++) {
      const element = this.g[i2];
      const cellHeight = Math.round(element.totalHeight / scrollHeight * ratio * height);
      switch (element.type) {
        case "insert":
          ctx.fillStyle = this.r;
          ctx.fillRect(laneWidth, currentFrom, laneWidth, cellHeight);
          break;
        case "delete":
          ctx.fillStyle = this.t;
          ctx.fillRect(0, currentFrom, laneWidth, cellHeight);
          break;
        case "unchanged":
        case "unchangedMetadata":
          break;
        case "modified":
        case "modifiedMetadata":
          ctx.fillStyle = this.t;
          ctx.fillRect(0, currentFrom, laneWidth, cellHeight);
          ctx.fillStyle = this.r;
          ctx.fillRect(laneWidth, currentFrom, laneWidth, cellHeight);
          break;
      }
      currentFrom += cellHeight;
    }
  }
  dispose() {
    if (this.y !== null) {
      this.y.dispose();
      this.y = null;
    }
    super.dispose();
  }
};
$z2b = __decorate([
  __param(3, $gs)
], $z2b);

// out-build/vs/workbench/contrib/notebook/browser/diff/editorHeightCalculator.js
var $eEb = class $eEb2 {
  constructor(a, b, c, d) {
    this.a = a;
    this.b = b;
    this.c = c;
    this.d = d;
  }
  async diffAndComputeHeight(original, modified) {
    const [originalModel, modifiedModel] = await Promise.all([this.b.createModelReference(original), this.b.createModelReference(modified)]);
    try {
      const diffChanges = await this.c.computeDiff(original, modified, {
        ignoreTrimWhitespace: true,
        maxComputationTimeMs: 0,
        computeMoves: false
      }, "advanced").then((diff3) => diff3?.changes || []);
      const unchangedRegionFeatureEnabled = this.d.getValue("diffEditor.hideUnchangedRegions.enabled");
      const minimumLineCount = this.d.getValue("diffEditor.hideUnchangedRegions.minimumLineCount");
      const contextLineCount = this.d.getValue("diffEditor.hideUnchangedRegions.contextLineCount");
      const originalLineCount = originalModel.object.textEditorModel.getLineCount();
      const modifiedLineCount = modifiedModel.object.textEditorModel.getLineCount();
      const unchanged = unchangedRegionFeatureEnabled ? $e$.fromDiffs(diffChanges, originalLineCount, modifiedLineCount, minimumLineCount ?? 3, contextLineCount ?? 3) : [];
      const numberOfNewLines = diffChanges.reduce((prev, curr) => {
        if (curr.original.isEmpty && !curr.modified.isEmpty) {
          return prev + curr.modified.length;
        }
        if (!curr.original.isEmpty && !curr.modified.isEmpty && curr.modified.length > curr.original.length) {
          return prev + curr.modified.length - curr.original.length;
        }
        return prev;
      }, 0);
      const orginalNumberOfLines = originalModel.object.textEditorModel.getLineCount();
      const numberOfHiddenLines = unchanged.reduce((prev, curr) => prev + curr.lineCount, 0);
      const numberOfHiddenSections = unchanged.length;
      const unchangeRegionsHeight = numberOfHiddenSections * $hEb;
      const visibleLineCount = orginalNumberOfLines + numberOfNewLines - numberOfHiddenLines;
      return visibleLineCount * this.a + $WDb(visibleLineCount).top + $WDb(visibleLineCount).bottom + unchangeRegionsHeight;
    } finally {
      originalModel.dispose();
      modifiedModel.dispose();
    }
  }
  computeHeightFromLines(lineCount) {
    return lineCount * this.a + $WDb(lineCount).top + $WDb(lineCount).bottom;
  }
};
$eEb = __decorate([
  __param(1, $oG),
  __param(2, $I0),
  __param(3, $kl)
], $eEb);

// out-build/vs/workbench/contrib/notebook/browser/diff/notebookDiffEditor.js
var $A2b_1;
var $126 = $;
var NotebookDiffEditorSelection = class _NotebookDiffEditorSelection {
  constructor(a) {
    this.a = a;
  }
  compare(other) {
    if (!(other instanceof _NotebookDiffEditorSelection)) {
      return 3;
    }
    if (this.a.length !== other.a.length) {
      return 3;
    }
    for (let i2 = 0; i2 < this.a.length; i2++) {
      if (this.a[i2] !== other.a[i2]) {
        return 3;
      }
    }
    return 1;
  }
  restore(options3) {
    const notebookOptions = {
      cellSelections: $FL(this.a)
    };
    Object.assign(notebookOptions, options3);
    return notebookOptions;
  }
};
var $A2b = class $A2b2 extends $5tb {
  static {
    $A2b_1 = this;
  }
  static {
    this.ENTIRE_DIFF_OVERVIEW_WIDTH = 30;
  }
  static {
    this.ID = $cM;
  }
  get textModel() {
    return this.jb?.modified.notebook;
  }
  get notebookOptions() {
    return this.pb;
  }
  get isDisposed() {
    return this.tb;
  }
  constructor(group2, ub, themeService, vb, wb, xb, telemetryService, storageService, yb, zb) {
    super($A2b_1.ID, group2, telemetryService, themeService, storageService);
    this.ub = ub;
    this.vb = vb;
    this.wb = wb;
    this.xb = xb;
    this.yb = yb;
    this.zb = zb;
    this.creationOptions = $_Lb();
    this.j = null;
    this.u = null;
    this.cb = null;
    this.db = null;
    this.fb = this.B(new $ze());
    this.onMouseUp = this.fb.event;
    this.gb = this.B(new $ze());
    this.onDidScroll = this.gb.event;
    this.onDidChangeScroll = this.gb.event;
    this.jb = null;
    this.lb = this.B(new $2c());
    this.nb = new $Rh();
    this.ob = this.B(new $ze());
    this.onDidDynamicOutputRendered = this.ob.event;
    this.qb = this.B(new $2c());
    this.sb = this.B(new $ze());
    this.onDidChangeSelection = this.sb.event;
    this.tb = false;
    this.Kb = /* @__PURE__ */ new WeakMap();
    this.kb = this.ub.createInstance($eEb, this.Ab.lineHeight);
    this.pb = ub.createInstance($xrb, this.window, false, void 0);
    this.B(this.pb);
    this.mb = true;
  }
  get Ab() {
    if (!this.eb) {
      this.eb = this.Bb();
    }
    return this.eb;
  }
  Bb() {
    const editorOptions2 = this.xb.getValue("editor");
    return $64.readFontInfo(this.window, $ED.createFromRawSettings(editorOptions2, $_1.getInstance(this.window).value));
  }
  Cb() {
    return this.xb.getValue($rM.diffOverviewRuler) ?? false;
  }
  getSelection() {
    const selections = this.s.getFocus();
    return new NotebookDiffEditorSelection(selections);
  }
  toggleNotebookCellSelection(cell) {
  }
  updatePerformanceMetadata(cellId, executionId, duration, rendererId) {
  }
  async focusNotebookCell(cell, focus) {
  }
  async focusNextNotebookCell(cell, focus) {
  }
  didFocusOutputInputChange(inputFocused) {
  }
  getScrollTop() {
    return this.s?.scrollTop ?? 0;
  }
  getScrollHeight() {
    return this.s?.scrollHeight ?? 0;
  }
  getScrollPosition() {
    return {
      scrollTop: this.getScrollTop(),
      scrollLeft: this.s?.scrollLeft ?? 0
    };
  }
  setScrollPosition(scrollPosition) {
    if (!this.s) {
      return;
    }
    this.s.scrollTop = scrollPosition.scrollTop;
    if (scrollPosition.scrollLeft !== void 0) {
      this.s.scrollLeft = scrollPosition.scrollLeft;
    }
  }
  delegateVerticalScrollbarPointerDown(browserEvent) {
    this.s?.delegateVerticalScrollbarPointerDown(browserEvent);
  }
  updateOutputHeight(cellInfo, output, outputHeight, isInit) {
    const diffElement = cellInfo.diffElement;
    const cell = this.getCellByInfo(cellInfo);
    const outputIndex = cell.outputsViewModels.indexOf(output);
    if (diffElement instanceof $oEb) {
      const info = CellUri.parse(cellInfo.cellUri);
      if (!info) {
        return;
      }
      diffElement.updateOutputHeight(info.notebook.toString() === this.jb?.original.resource.toString() ? DiffSide.Original : DiffSide.Modified, outputIndex, outputHeight);
    } else {
      diffElement.updateOutputHeight(diffElement.type === "insert" ? DiffSide.Modified : DiffSide.Original, outputIndex, outputHeight);
    }
    if (isInit) {
      this.ob.fire({ cell, output });
    }
  }
  setMarkupCellEditState(cellId, editState) {
  }
  didStartDragMarkupCell(cellId, event) {
  }
  didDragMarkupCell(cellId, event) {
  }
  didEndDragMarkupCell(cellId) {
  }
  didDropMarkupCell(cellId) {
  }
  didResizeOutput(cellId) {
  }
  Y(parent) {
    this.a = $bk(parent, $(".notebook-text-diff-editor"));
    this.c = document.createElement("div");
    this.c.classList.add("notebook-overflow-widget-container", "monaco-editor");
    $bk(parent, this.c);
    const renderers = [
      this.ub.createInstance($v2b, this),
      this.ub.createInstance($w2b, this),
      this.ub.createInstance($t2b, this),
      this.ub.createInstance($u2b, this)
    ];
    this.b = $bk(this.a, $(".notebook-diff-list-view"));
    this.s = this.ub.createInstance($y2b, "NotebookTextDiff", this.b, this.ub.createInstance($s2b, this.window), renderers, this.vb, {
      setRowLineHeight: false,
      setRowHeight: false,
      supportDynamicHeights: true,
      horizontalScrolling: false,
      keyboardSupport: false,
      mouseSupport: true,
      multipleSelectionSupport: false,
      typeNavigationEnabled: true,
      paddingBottom: 0,
      // transformOptimization: (isMacintosh && isNative) || getTitleBarStyle(this.configurationService, this.environmentService) === 'native',
      styleController: (_suffix) => {
        return this.s;
      },
      overrideStyles: {
        listBackground: $Ko,
        listActiveSelectionBackground: $Ko,
        listActiveSelectionForeground: $eo,
        listFocusAndSelectionBackground: $Ko,
        listFocusAndSelectionForeground: $eo,
        listFocusBackground: $Ko,
        listFocusForeground: $eo,
        listHoverForeground: $eo,
        listHoverBackground: $Ko,
        listHoverOutline: $jo,
        listFocusOutline: $jo,
        listInactiveSelectionBackground: $Ko,
        listInactiveSelectionForeground: $eo,
        listInactiveFocusBackground: $Ko,
        listInactiveFocusOutline: $Ko
      },
      accessibilityProvider: {
        getAriaLabel() {
          return null;
        },
        getWidgetAriaLabel() {
          return localize(8390, null);
        }
      }
      // focusNextPreviousDelegate: {
      // 	onFocusNext: (applyFocusNext: () => void) => this._updateForCursorNavigationMode(applyFocusNext),
      // 	onFocusPrevious: (applyFocusPrevious: () => void) => this._updateForCursorNavigationMode(applyFocusPrevious),
      // }
    });
    this.B(this.s);
    this.B(this.s.onMouseUp((e) => {
      if (e.element) {
        if (typeof e.index === "number") {
          this.s.setFocus([e.index]);
        }
        this.fb.fire({ event: e.browserEvent, target: e.element });
      }
    }));
    this.B(this.s.onDidScroll(() => {
      this.gb.fire();
    }));
    this.B(this.s.onDidChangeFocus(() => this.sb.fire({
      reason: 2
      /* EditorPaneSelectionChangeReason.USER */
    })));
    this.f = document.createElement("div");
    this.f.classList.add("notebook-overview-ruler-container");
    this.a.appendChild(this.f);
    this.Eb();
    this.db = $bk(this.s.rowsContainer, $126(".webview-cover"));
    this.db.style.display = "none";
    this.B($bj(this.c, (e) => {
      if (e.target.classList.contains("slider") && this.db) {
        this.db.style.display = "block";
      }
    }));
    this.B($cj(this.c, () => {
      if (this.db) {
        this.db.style.display = "none";
      }
    }));
    this.B(this.s.onDidScroll((e) => {
      this.db.style.top = `${e.scrollTop}px`;
    }));
  }
  Eb() {
    this.g = this.B(this.ub.createInstance($z2b, this, $A2b_1.ENTIRE_DIFF_OVERVIEW_WIDTH, this.f));
  }
  Fb(scrollTop, scrollHeight, activeWebview, getActiveNestedCell, diffSide) {
    activeWebview.element.style.height = `${scrollHeight}px`;
    if (activeWebview.insetMapping) {
      const updateItems = [];
      const removedItems = [];
      activeWebview.insetMapping.forEach((value, key2) => {
        const cell = getActiveNestedCell(value.cellInfo.diffElement);
        if (!cell) {
          return;
        }
        const viewIndex = this.s.indexOf(value.cellInfo.diffElement);
        if (viewIndex === void 0) {
          return;
        }
        if (cell.outputsViewModels.indexOf(key2) < 0) {
          removedItems.push(key2);
        } else {
          const cellTop = this.s.getCellViewScrollTop(value.cellInfo.diffElement);
          const outputIndex = cell.outputsViewModels.indexOf(key2);
          const outputOffset = value.cellInfo.diffElement.getOutputOffsetInCell(diffSide, outputIndex);
          updateItems.push({
            cell,
            output: key2,
            cellTop,
            outputOffset,
            forceDisplay: false
          });
        }
      });
      activeWebview.removeInsets(removedItems);
      if (updateItems.length) {
        activeWebview.updateScrollTops(updateItems, []);
      }
    }
  }
  async setInput(input, options3, context, token) {
    await super.setInput(input, options3, context, token);
    const model = await input.resolve();
    if (this.jb !== model) {
      this.Gb();
      this.Hb(model);
    }
    this.jb = model;
    if (this.jb === null) {
      return;
    }
    this.mb = true;
    this.lb.clear();
    this.rb = new $ad();
    this.lb.add(Event2.any(this.jb.original.notebook.onDidChangeContent, this.jb.modified.notebook.onDidChangeContent)((e) => {
      if (this.jb !== null && this.zb.activeEditor !== input) {
        this.rb?.dispose();
        this.rb = new $ad();
        this.updateLayout(this.rb.token);
      }
    }));
    await this.Jb($ps(), this.jb.original.viewType, this.jb.original.resource);
    if (this.cb) {
      this.lb.add(this.cb);
    }
    await this.Ib($ps(), this.jb.modified.viewType, this.jb.modified.resource);
    if (this.u) {
      this.lb.add(this.u);
    }
    await this.updateLayout(this.rb.token, options3?.cellSelections ? $GL(options3.cellSelections) : void 0);
  }
  Gb() {
    this.qb.clear();
    this.cb?.dispose();
    this.cb?.element.remove();
    this.cb = null;
    this.u?.dispose();
    this.u?.element.remove();
    this.u = null;
    this.m?.dispose();
    this.m = void 0;
    this.lb.clear();
    this.s.clear();
  }
  Hb(model) {
    this.jb = model;
    this.hb = new $dEb();
    const updateInsets = () => {
      $jj(this.window, () => {
        if (this.tb) {
          return;
        }
        if (this.u) {
          this.Fb(this.s.scrollTop, this.s.scrollHeight, this.u, (diffElement) => {
            return diffElement.modified;
          }, DiffSide.Modified);
        }
        if (this.cb) {
          this.Fb(this.s.scrollTop, this.s.scrollHeight, this.cb, (diffElement) => {
            return diffElement.original;
          }, DiffSide.Original);
        }
      });
    };
    this.qb.add(this.s.onDidChangeContentHeight(() => {
      updateInsets();
    }));
    this.qb.add(this.hb.onDidChangeCellLayout(() => {
      updateInsets();
    }));
    const vm = this.m = this.B(new $vEb(this.jb, this.wb, this.xb, this.hb, this.yb, this.kb, this.Ab, void 0));
    this.qb.add(this.m.onDidChangeItems((e) => {
      this.cb?.removeInsets([...this.cb?.insetMapping.keys()]);
      this.u?.removeInsets([...this.u?.insetMapping.keys()]);
      if (this.mb && typeof e.firstChangeIndex === "number" && e.firstChangeIndex > -1 && e.firstChangeIndex < this.s.length) {
        this.mb = false;
        this.s.setFocus([e.firstChangeIndex]);
        this.s.reveal(e.firstChangeIndex, 0.3);
      }
      this.s.splice(e.start, e.deleteCount, e.elements);
      if (this.Cb()) {
        this.g.updateViewModels(vm.items, this.hb);
      }
    }));
  }
  async Ib(id2, viewType, resource) {
    this.u?.dispose();
    this.u = this.ub.createInstance($JJb, this, id2, viewType, resource, {
      ...this.pb.computeDiffWebviewOptions(),
      fontFamily: this._generateFontFamily()
    }, void 0);
    this.s.rowsContainer.insertAdjacentElement("afterbegin", this.u.element);
    this.u.createWebview(this.window);
    this.u.element.style.width = `calc(50% - 16px)`;
    this.u.element.style.left = `calc(50%)`;
  }
  _generateFontFamily() {
    return this.Ab.fontFamily ?? `"SF Mono", Monaco, Menlo, Consolas, "Ubuntu Mono", "Liberation Mono", "DejaVu Sans Mono", "Courier New", monospace`;
  }
  async Jb(id2, viewType, resource) {
    this.cb?.dispose();
    this.cb = this.ub.createInstance($JJb, this, id2, viewType, resource, {
      ...this.pb.computeDiffWebviewOptions(),
      fontFamily: this._generateFontFamily()
    }, void 0);
    this.s.rowsContainer.insertAdjacentElement("afterbegin", this.cb.element);
    this.cb.createWebview(this.window);
    this.cb.element.style.width = `calc(50% - 16px)`;
    this.cb.element.style.left = `16px`;
  }
  setOptions(options3) {
    const selections = options3?.cellSelections ? $GL(options3.cellSelections) : void 0;
    if (selections) {
      this.s.setFocus(selections);
    }
  }
  async updateLayout(token, selections) {
    if (!this.jb || !this.m) {
      return;
    }
    await this.m.computeDiff(token);
    if (token.isCancellationRequested) {
      return;
    }
    if (selections) {
      this.s.setFocus(selections);
    }
  }
  scheduleOutputHeightAck(cellInfo, outputId, height) {
    const diffElement = cellInfo.diffElement;
    let diffSide = DiffSide.Original;
    if (diffElement instanceof $oEb) {
      const info = CellUri.parse(cellInfo.cellUri);
      if (!info) {
        return;
      }
      diffSide = info.notebook.toString() === this.jb?.original.resource.toString() ? DiffSide.Original : DiffSide.Modified;
    } else {
      diffSide = diffElement.type === "insert" ? DiffSide.Modified : DiffSide.Original;
    }
    const webview = diffSide === DiffSide.Modified ? this.u : this.cb;
    $jj(this.window, () => {
      webview?.ackHeight([{ cellId: cellInfo.cellId, outputId, height }]);
    }, 10);
  }
  layoutNotebookCell(cell, height) {
    const relayout = (cell2, height2) => {
      this.s.updateElementHeight2(cell2, height2);
    };
    if (this.Kb.has(cell)) {
      this.Kb.get(cell).dispose();
    }
    let r2;
    const layoutDisposable = $jj(this.window, () => {
      this.Kb.delete(cell);
      relayout(cell, height);
      r2();
    });
    this.Kb.set(cell, $1c(() => {
      layoutDisposable.dispose();
      r2();
    }));
    return new Promise((resolve) => {
      r2 = resolve;
    });
  }
  setScrollTop(scrollTop) {
    this.s.scrollTop = scrollTop;
  }
  triggerScroll(event) {
    this.s.triggerScrollFromMouseWheelEvent(event);
  }
  previousChange() {
    if (!this.m) {
      return;
    }
    let currFocus = this.s.getFocus()[0];
    if (isNaN(currFocus) || currFocus < 0) {
      currFocus = 0;
    }
    let prevChangeIndex = currFocus - 1;
    const currentViewModels = this.m.items;
    while (prevChangeIndex >= 0) {
      const vm = currentViewModels[prevChangeIndex];
      if (vm.type !== "unchanged" && vm.type !== "placeholder") {
        break;
      }
      prevChangeIndex--;
    }
    if (prevChangeIndex >= 0) {
      this.s.setFocus([prevChangeIndex]);
      this.s.reveal(prevChangeIndex);
    } else {
      const index = $2(currentViewModels, (vm) => vm.type !== "unchanged" && vm.type !== "placeholder");
      if (index >= 0) {
        this.s.setFocus([index]);
        this.s.reveal(index);
      }
    }
  }
  nextChange() {
    if (!this.m) {
      return;
    }
    let currFocus = this.s.getFocus()[0];
    if (isNaN(currFocus) || currFocus < 0) {
      currFocus = 0;
    }
    let nextChangeIndex = currFocus + 1;
    const currentViewModels = this.m.items;
    while (nextChangeIndex < currentViewModels.length) {
      const vm = currentViewModels[nextChangeIndex];
      if (vm.type !== "unchanged" && vm.type !== "placeholder") {
        break;
      }
      nextChangeIndex++;
    }
    if (nextChangeIndex < currentViewModels.length) {
      this.s.setFocus([nextChangeIndex]);
      this.s.reveal(nextChangeIndex);
    } else {
      const index = currentViewModels.findIndex((vm) => vm.type !== "unchanged" && vm.type !== "placeholder");
      if (index >= 0) {
        this.s.setFocus([index]);
        this.s.reveal(index);
      }
    }
  }
  createOutput(cellDiffViewModel, cellViewModel, output, getOffset, diffSide) {
    this.nb.queue(output.source.model.outputId + (diffSide === DiffSide.Modified ? "-right" : "left"), async () => {
      const activeWebview = diffSide === DiffSide.Modified ? this.u : this.cb;
      if (!activeWebview) {
        return;
      }
      if (!activeWebview.insetMapping.has(output.source)) {
        const cellTop = this.s.getCellViewScrollTop(cellDiffViewModel);
        await activeWebview.createOutput({ diffElement: cellDiffViewModel, cellHandle: cellViewModel.handle, cellId: cellViewModel.id, cellUri: cellViewModel.uri }, output, cellTop, getOffset());
      } else {
        const cellTop = this.s.getCellViewScrollTop(cellDiffViewModel);
        const outputIndex = cellViewModel.outputsViewModels.indexOf(output.source);
        const outputOffset = cellDiffViewModel.getOutputOffsetInCell(diffSide, outputIndex);
        activeWebview.updateScrollTops([{
          cell: cellViewModel,
          output: output.source,
          cellTop,
          outputOffset,
          forceDisplay: true
        }], []);
      }
    });
  }
  updateMarkupCellHeight() {
  }
  getCellByInfo(cellInfo) {
    return cellInfo.diffElement.getCellByUri(cellInfo.cellUri);
  }
  getCellById(cellId) {
    throw new Error("Not implemented");
  }
  removeInset(cellDiffViewModel, cellViewModel, displayOutput, diffSide) {
    this.nb.queue(displayOutput.model.outputId + (diffSide === DiffSide.Modified ? "-right" : "left"), async () => {
      const activeWebview = diffSide === DiffSide.Modified ? this.u : this.cb;
      if (!activeWebview) {
        return;
      }
      if (!activeWebview.insetMapping.has(displayOutput)) {
        return;
      }
      activeWebview.removeInsets([displayOutput]);
    });
  }
  showInset(cellDiffViewModel, cellViewModel, displayOutput, diffSide) {
    this.nb.queue(displayOutput.model.outputId + (diffSide === DiffSide.Modified ? "-right" : "left"), async () => {
      const activeWebview = diffSide === DiffSide.Modified ? this.u : this.cb;
      if (!activeWebview) {
        return;
      }
      if (!activeWebview.insetMapping.has(displayOutput)) {
        return;
      }
      const cellTop = this.s.getCellViewScrollTop(cellDiffViewModel);
      const outputIndex = cellViewModel.outputsViewModels.indexOf(displayOutput);
      const outputOffset = cellDiffViewModel.getOutputOffsetInCell(diffSide, outputIndex);
      activeWebview.updateScrollTops([{
        cell: cellViewModel,
        output: displayOutput,
        cellTop,
        outputOffset,
        forceDisplay: true
      }], []);
    });
  }
  hideInset(cellDiffViewModel, cellViewModel, output) {
    this.u?.hideInset(output);
    this.cb?.hideInset(output);
  }
  // private async _resolveWebview(rightEditor: boolean): Promise<BackLayerWebView | null> {
  // 	if (rightEditor) {
  // 	}
  // }
  getDomNode() {
    return this.a;
  }
  getOverflowContainerDomNode() {
    return this.c;
  }
  getControl() {
    return this;
  }
  clearInput() {
    super.clearInput();
    this.lb.clear();
    this.s?.splice(0, this.s?.length || 0);
    this.jb = null;
    this.m?.dispose();
    this.m = void 0;
  }
  deltaCellOutputContainerClassNames(diffSide, cellId, added, removed) {
    if (diffSide === DiffSide.Original) {
      this.cb?.deltaCellContainerClassNames(cellId, added, removed);
    } else {
      this.u?.deltaCellContainerClassNames(cellId, added, removed);
    }
  }
  getLayoutInfo() {
    if (!this.s) {
      throw new Error("Editor is not initalized successfully");
    }
    return {
      width: this.j.width,
      height: this.j.height,
      fontInfo: this.Ab,
      scrollHeight: this.s?.getScrollHeight() ?? 0,
      stickyHeight: 0
    };
  }
  layout(dimension, _position) {
    this.a.classList.toggle("mid-width", dimension.width < 1e3 && dimension.width >= 600);
    this.a.classList.toggle("narrow-width", dimension.width < 600);
    const overviewRulerEnabled = this.Cb();
    this.j = dimension.with(dimension.width - (overviewRulerEnabled ? $A2b_1.ENTIRE_DIFF_OVERVIEW_WIDTH : 0));
    this.b.style.height = `${dimension.height}px`;
    this.b.style.width = `${this.j.width}px`;
    this.s?.layout(this.j.height, this.j.width);
    if (this.u) {
      this.u.element.style.width = `calc(50% - 16px)`;
      this.u.element.style.left = `calc(50%)`;
    }
    if (this.cb) {
      this.cb.element.style.width = `calc(50% - 16px)`;
      this.cb.element.style.left = `16px`;
    }
    if (this.db) {
      this.db.style.height = `${this.j.height}px`;
      this.db.style.width = `${this.j.width}px`;
    }
    if (overviewRulerEnabled) {
      this.g.layout();
    }
    this.hb?.emit([new $bEb({ width: true, fontInfo: true }, this.getLayoutInfo())]);
  }
  dispose() {
    this.tb = true;
    this.rb?.dispose();
    this.Gb();
    super.dispose();
  }
};
$A2b = $A2b_1 = __decorate([
  __param(1, $Pk),
  __param(2, $gs),
  __param(3, $on),
  __param(4, $uEb),
  __param(5, $kl),
  __param(6, $zv),
  __param(7, $jv),
  __param(8, $mrb),
  __param(9, $mJ)
], $A2b);
$uFb(ZIndex.Base, 10, "notebook-diff-view-viewport-slider");
$ms((theme, collector) => {
  const diffDiagonalFillColor = theme.getColor($Np);
  collector.addRule(`
	.notebook-text-diff-editor .diagonal-fill {
		background-image: linear-gradient(
			-45deg,
			${diffDiagonalFillColor} 12.5%,
			#0000 12.5%, #0000 50%,
			${diffDiagonalFillColor} 50%, ${diffDiagonalFillColor} 62.5%,
			#0000 62.5%, #0000 100%
		);
		background-size: 8px 8px;
	}
	`);
  collector.addRule(`.notebook-text-diff-editor .cell-body { margin: ${$ZDb}px; }`);
  collector.addRule(`.notebook-text-diff-editor .cell-placeholder-body { margin: ${$ZDb}px 0; }`);
});

// out-build/vs/workbench/contrib/notebook/browser/services/notebookWorkerServiceImpl.js
var $D2b = class $D2b2 extends $3c {
  constructor(notebookService, modelService) {
    super();
    this.a = this.B(new WorkerManager3(notebookService, modelService));
  }
  canComputeDiff(original, modified) {
    throw new Error("Method not implemented.");
  }
  computeDiff(original, modified) {
    return this.a.withWorker().then((client) => {
      return client.computeDiff(original, modified);
    });
  }
  canPromptRecommendation(model) {
    return this.a.withWorker().then((client) => {
      return client.canPromptRecommendation(model);
    });
  }
};
$D2b = __decorate([
  __param(0, $mrb),
  __param(1, $sG)
], $D2b);
var WorkerManager3 = class extends $3c {
  // private _lastWorkerUsedTime: number;
  constructor(b, c) {
    super();
    this.b = b;
    this.c = c;
    this.a = null;
  }
  withWorker() {
    if (!this.a) {
      this.a = new NotebookWorkerClient(this.b, this.c);
    }
    return Promise.resolve(this.a);
  }
};
var NotebookEditorModelManager = class extends $3c {
  constructor(c, f, g) {
    super();
    this.c = c;
    this.f = f;
    this.g = g;
    this.a = /* @__PURE__ */ Object.create(null);
    this.b = /* @__PURE__ */ Object.create(null);
  }
  ensureSyncedResources(resources) {
    for (const resource of resources) {
      const resourceStr = resource.toString();
      if (!this.a[resourceStr]) {
        this.h(resource);
      }
      if (this.a[resourceStr]) {
        this.b[resourceStr] = (/* @__PURE__ */ new Date()).getTime();
      }
    }
  }
  h(resource) {
    const model = this.f.listNotebookDocuments().find((document2) => document2.uri.toString() === resource.toString());
    if (!model) {
      return;
    }
    const modelUrl = resource.toString();
    this.c.$acceptNewModel(model.uri.toString(), model.metadata, model.transientOptions.transientDocumentMetadata, model.cells.map((cell) => ({
      handle: cell.handle,
      url: cell.uri.toString(),
      source: cell.textBuffer.getLinesContent(),
      eol: cell.textBuffer.getEOL(),
      versionId: cell.textModel?.getVersionId() ?? 0,
      language: cell.language,
      mime: cell.mime,
      cellKind: cell.cellKind,
      outputs: cell.outputs.map((op) => ({ outputId: op.outputId, outputs: op.outputs })),
      metadata: cell.metadata,
      internalMetadata: cell.internalMetadata
    })));
    const toDispose = new $2c();
    const cellToDto = (cell) => {
      return {
        handle: cell.handle,
        url: cell.uri.toString(),
        source: cell.textBuffer.getLinesContent(),
        eol: cell.textBuffer.getEOL(),
        versionId: 0,
        language: cell.language,
        cellKind: cell.cellKind,
        outputs: cell.outputs.map((op) => ({ outputId: op.outputId, outputs: op.outputs })),
        metadata: cell.metadata,
        internalMetadata: cell.internalMetadata
      };
    };
    const cellHandlers = /* @__PURE__ */ new Set();
    const addCellContentChangeHandler = (cell) => {
      cellHandlers.add(cell);
      toDispose.add(cell.onDidChangeContent((e) => {
        if (typeof e === "object" && e.type === "model") {
          this.c.$acceptCellModelChanged(modelUrl, cell.handle, e.event);
        }
      }));
    };
    model.cells.forEach((cell) => addCellContentChangeHandler(cell));
    if (model.cells.length !== cellHandlers.size) {
      toDispose.add(this.g.onModelAdded((textModel) => {
        if (textModel.uri.scheme !== Schemas.vscodeNotebookCell || !(textModel instanceof $QI)) {
          return;
        }
        const cellUri = CellUri.parse(textModel.uri);
        if (!cellUri || !$oh(cellUri.notebook, model.uri)) {
          return;
        }
        const cell = model.cells.find((cell2) => cell2.handle === cellUri.handle);
        if (cell) {
          addCellContentChangeHandler(cell);
        }
      }));
    }
    toDispose.add(model.onDidChangeContent((event) => {
      const dto = [];
      event.rawEvents.forEach((e) => {
        switch (e.kind) {
          case NotebookCellsChangeType.ModelChange:
          case NotebookCellsChangeType.Initialize: {
            dto.push({
              kind: e.kind,
              changes: e.changes.map((diff3) => [diff3[0], diff3[1], diff3[2].map((cell) => cellToDto(cell))])
            });
            for (const change of e.changes) {
              for (const cell of change[2]) {
                addCellContentChangeHandler(cell);
              }
            }
            break;
          }
          case NotebookCellsChangeType.Move: {
            dto.push({
              kind: NotebookCellsChangeType.Move,
              index: e.index,
              length: e.length,
              newIdx: e.newIdx,
              cells: e.cells.map((cell) => cellToDto(cell))
            });
            break;
          }
          case NotebookCellsChangeType.ChangeCellContent:
            break;
          case NotebookCellsChangeType.ChangeDocumentMetadata:
            dto.push({
              kind: e.kind,
              metadata: e.metadata
            });
          default:
            dto.push(e);
        }
      });
      this.c.$acceptModelChanged(modelUrl.toString(), {
        rawEvents: dto,
        versionId: event.versionId
      });
    }));
    toDispose.add(model.onWillDispose(() => {
      this.j(modelUrl);
    }));
    toDispose.add($1c(() => {
      this.c.$acceptRemovedModel(modelUrl);
    }));
    this.a[modelUrl] = toDispose;
  }
  j(modelUrl) {
    const toDispose = this.a[modelUrl];
    delete this.a[modelUrl];
    delete this.b[modelUrl];
    $Xc(toDispose);
  }
};
var NotebookWorkerClient = class extends $3c {
  constructor(c, f) {
    super();
    this.c = c;
    this.f = f;
    this.a = null;
    this.b = null;
  }
  computeDiff(original, modified) {
    const proxy = this.h([original, modified]);
    return proxy.$computeDiff(original.toString(), modified.toString());
  }
  canPromptRecommendation(modelUri) {
    const proxy = this.h([modelUri]);
    return proxy.$canPromptRecommendation(modelUri.toString());
  }
  g(proxy) {
    if (!this.b) {
      this.b = this.B(new NotebookEditorModelManager(proxy, this.c, this.f));
    }
    return this.b;
  }
  h(resources) {
    const proxy = this.j().proxy;
    this.g(proxy).ensureSyncedResources(resources);
    return proxy;
  }
  j() {
    if (!this.a) {
      try {
        this.a = this.B($412("vs/workbench/contrib/notebook/common/services/notebookSimpleWorker", "NotebookEditorWorker"));
      } catch (err) {
        throw err;
      }
    }
    return this.a;
  }
};

// out-build/vs/workbench/contrib/notebook/browser/services/notebookCellStatusBarServiceImpl.js
var $E2b = class extends $3c {
  constructor() {
    super(...arguments);
    this.a = this.B(new $ze());
    this.onDidChangeProviders = this.a.event;
    this.b = this.B(new $ze());
    this.onDidChangeItems = this.b.event;
    this.c = [];
  }
  registerCellStatusBarItemProvider(provider) {
    this.c.push(provider);
    let changeListener;
    if (provider.onDidChangeStatusBarItems) {
      changeListener = provider.onDidChangeStatusBarItems(() => this.b.fire());
    }
    this.a.fire();
    return $1c(() => {
      changeListener?.dispose();
      const idx = this.c.findIndex((p) => p === provider);
      this.c.splice(idx, 1);
    });
  }
  async getStatusBarItemsForCell(docUri, cellIndex, viewType, token) {
    const providers2 = this.c.filter((p) => p.viewType === viewType || p.viewType === "*");
    return await Promise.all(providers2.map(async (p) => {
      try {
        return await p.provideCellStatusBarItems(docUri, cellIndex, token) ?? { items: [] };
      } catch (e) {
        $hb(e);
        return { items: [] };
      }
    }));
  }
};

// out-build/vs/workbench/contrib/notebook/browser/services/notebookEditorServiceImpl.js
var $F2b = class $F2b2 {
  constructor(j, editorService, contextKeyService, k) {
    this.j = j;
    this.k = k;
    this.a = 1;
    this.b = new $2c();
    this.c = /* @__PURE__ */ new Map();
    this.d = /* @__PURE__ */ new Map();
    this.f = new $ze();
    this.g = new $ze();
    this.onDidAddNotebookEditor = this.f.event;
    this.onDidRemoveNotebookEditor = this.g.event;
    this.i = /* @__PURE__ */ new Map();
    const onNewGroup = (group2) => {
      const { id: id2 } = group2;
      const listeners = [];
      listeners.push(group2.onDidCloseEditor((e) => {
        const widgetMap = this.i.get(group2.id);
        if (!widgetMap) {
          return;
        }
        const inputs = e.editor instanceof $trb ? [e.editor] : $urb(e.editor) ? e.editor.editorInputs : [];
        inputs.forEach((input) => {
          const widgets2 = widgetMap.get(input.resource);
          const index = widgets2?.findIndex((widget) => widget.editorType === input.typeId);
          if (!widgets2 || index === void 0 || index === -1) {
            return;
          }
          const value = widgets2.splice(index, 1)[0];
          value.token = void 0;
          this.l(value.widget);
          value.disposableStore.dispose();
          value.widget = void 0;
        });
      }));
      listeners.push(group2.onWillMoveEditor((e) => {
        if ($vrb(e.editor)) {
          this.m(e.editor, e.groupId, e.target);
        }
        if ($urb(e.editor)) {
          e.editor.editorInputs.forEach((input) => {
            this.m(input, e.groupId, e.target);
          });
        }
      }));
      this.d.set(id2, listeners);
    };
    this.b.add(j.onDidAddGroup(onNewGroup));
    j.whenReady.then(() => j.groups.forEach(onNewGroup));
    this.b.add(j.onDidRemoveGroup((group2) => {
      const listeners = this.d.get(group2.id);
      if (listeners) {
        listeners.forEach((listener) => listener.dispose());
        this.d.delete(group2.id);
      }
      const widgets2 = this.i.get(group2.id);
      this.i.delete(group2.id);
      if (widgets2) {
        for (const values of widgets2.values()) {
          for (const value of values) {
            value.token = void 0;
            this.l(value.widget);
            value.disposableStore.dispose();
          }
        }
      }
    }));
    this.h = $RAb.bindTo(contextKeyService);
    const interactiveWindowOpen = $QAb.bindTo(contextKeyService);
    this.b.add(editorService.onDidEditorsChange((e) => {
      if (e.event.kind === 5 && !interactiveWindowOpen.get()) {
        if (editorService.editors.find((editor) => $urb(editor))) {
          interactiveWindowOpen.set(true);
        }
      } else if (e.event.kind === 6 && interactiveWindowOpen.get()) {
        if (!editorService.editors.find((editor) => $urb(editor))) {
          interactiveWindowOpen.set(false);
        }
      }
    }));
  }
  dispose() {
    this.b.dispose();
    this.f.dispose();
    this.g.dispose();
    this.d.forEach((listeners) => {
      listeners.forEach((listener) => listener.dispose());
    });
    this.d.clear();
    this.i.forEach((widgetMap) => {
      widgetMap.forEach((widgets2) => {
        widgets2.forEach((widget) => widget.disposableStore.dispose());
      });
    });
  }
  // --- group-based editor borrowing...
  l(widget) {
    widget.onWillHide();
    const domNode = widget.getDomNode();
    widget.dispose();
    domNode.remove();
  }
  m(input, sourceID, targetID) {
    const sourcePart = this.j.getPart(sourceID);
    const targetPart = this.j.getPart(targetID);
    if (sourcePart.windowId !== targetPart.windowId) {
      return;
    }
    const target = this.i.get(targetID)?.get(input.resource)?.findIndex((widget2) => widget2.editorType === input.typeId);
    if (target !== void 0 && target !== -1) {
      return;
    }
    const widget = this.i.get(sourceID)?.get(input.resource)?.find((widget2) => widget2.editorType === input.typeId);
    if (!widget) {
      throw new Error("no widget at source group");
    }
    const sourceWidgets = this.i.get(sourceID)?.get(input.resource);
    if (sourceWidgets) {
      const indexToRemove = sourceWidgets.findIndex((widget2) => widget2.editorType === input.typeId);
      if (indexToRemove !== -1) {
        sourceWidgets.splice(indexToRemove, 1);
      }
    }
    let targetMap = this.i.get(targetID);
    if (!targetMap) {
      targetMap = new $Ec();
      this.i.set(targetID, targetMap);
    }
    const widgetsAtTarget = targetMap.get(input.resource) ?? [];
    widgetsAtTarget?.push(widget);
    targetMap.set(input.resource, widgetsAtTarget);
  }
  retrieveExistingWidgetFromURI(resource) {
    for (const widgetInfo of this.i.values()) {
      const widgets2 = widgetInfo.get(resource);
      if (widgets2 && widgets2.length > 0) {
        return this.o(widgets2[0].token, widgets2[0]);
      }
    }
    return void 0;
  }
  retrieveAllExistingWidgets() {
    const ret = [];
    for (const widgetInfo of this.i.values()) {
      for (const widgets2 of widgetInfo.values()) {
        for (const widget of widgets2) {
          ret.push(this.o(widget.token, widget));
        }
      }
    }
    return ret;
  }
  retrieveWidget(accessor, groupId, input, creationOptions, initialDimension, codeWindow) {
    let value = this.i.get(groupId)?.get(input.resource)?.find((widget) => widget.editorType === input.typeId);
    if (!value) {
      const editorGroupContextKeyService = accessor.get($on);
      const editorGroupEditorProgressService = accessor.get($ZJ);
      const widgetDisposeStore = new $2c();
      const widget = this.n(editorGroupContextKeyService, widgetDisposeStore, editorGroupEditorProgressService, creationOptions, codeWindow, initialDimension);
      const token = this.a++;
      value = { widget, editorType: input.typeId, token, disposableStore: widgetDisposeStore };
      let map = this.i.get(groupId);
      if (!map) {
        map = new $Ec();
        this.i.set(groupId, map);
      }
      const values = map.get(input.resource) ?? [];
      values.push(value);
      map.set(input.resource, values);
    } else {
      value.token = this.a++;
    }
    return this.o(value.token, value);
  }
  // protected for unit testing overrides
  n(editorGroupContextKeyService, widgetDisposeStore, editorGroupEditorProgressService, creationOptions, codeWindow, initialDimension) {
    const notebookInstantiationService = widgetDisposeStore.add(this.k.createChild(new $Ok([$on, editorGroupContextKeyService], [$ZJ, editorGroupEditorProgressService])));
    const ctorOptions = creationOptions ?? $_Lb();
    const widget = notebookInstantiationService.createInstance($aMb, {
      ...ctorOptions,
      codeWindow: codeWindow ?? ctorOptions.codeWindow
    }, initialDimension);
    return widget;
  }
  o(myToken, widget) {
    return {
      get value() {
        return widget.token === myToken ? widget.widget : void 0;
      }
    };
  }
  // --- editor management
  addNotebookEditor(editor) {
    this.c.set(editor.getId(), editor);
    this.f.fire(editor);
  }
  removeNotebookEditor(editor) {
    const notebookUri = editor.getViewModel()?.notebookDocument.uri;
    if (this.c.has(editor.getId())) {
      this.c.delete(editor.getId());
      this.g.fire(editor);
    }
    if (this.h.get() === notebookUri?.toString()) {
      this.h.reset();
    }
  }
  getNotebookEditor(editorId) {
    return this.c.get(editorId);
  }
  listNotebookEditors() {
    return [...this.c].map((e) => e[1]);
  }
  updateReplContextKey(uri) {
    this.h.set(uri);
  }
};
$F2b = __decorate([
  __param(0, $iJ),
  __param(1, $mJ),
  __param(2, $on),
  __param(3, $Pk)
], $F2b);

// out-build/vs/workbench/services/files/common/elevatedFileService.js
var $8J = $Qk("elevatedFileService");

// out-build/vs/workbench/services/workingCopy/common/storedFileWorkingCopy.js
var $$J_1;
var StoredFileWorkingCopyState;
(function(StoredFileWorkingCopyState2) {
  StoredFileWorkingCopyState2[StoredFileWorkingCopyState2["SAVED"] = 0] = "SAVED";
  StoredFileWorkingCopyState2[StoredFileWorkingCopyState2["DIRTY"] = 1] = "DIRTY";
  StoredFileWorkingCopyState2[StoredFileWorkingCopyState2["PENDING_SAVE"] = 2] = "PENDING_SAVE";
  StoredFileWorkingCopyState2[StoredFileWorkingCopyState2["CONFLICT"] = 3] = "CONFLICT";
  StoredFileWorkingCopyState2[StoredFileWorkingCopyState2["ORPHAN"] = 4] = "ORPHAN";
  StoredFileWorkingCopyState2[StoredFileWorkingCopyState2["ERROR"] = 5] = "ERROR";
})(StoredFileWorkingCopyState || (StoredFileWorkingCopyState = {}));
function $0J(e) {
  const candidate = e;
  return !!candidate.stat;
}
var $$J = class $$J2 extends $9J {
  static {
    $$J_1 = this;
  }
  get model() {
    return this.j;
  }
  //#endregion
  constructor(typeId2, resource, name, y, z, fileService, C, D, F, G, workingCopyService, H, I, J, L, N) {
    super(resource, fileService);
    this.typeId = typeId2;
    this.name = name;
    this.y = y;
    this.z = z;
    this.C = C;
    this.D = D;
    this.F = F;
    this.G = G;
    this.H = H;
    this.I = I;
    this.J = J;
    this.L = L;
    this.N = N;
    this.capabilities = 0;
    this.j = void 0;
    this.m = this.B(new $ze());
    this.onDidChangeContent = this.m.event;
    this.n = this.B(new $ze());
    this.onDidResolve = this.n.event;
    this.r = this.B(new $ze());
    this.onDidChangeDirty = this.r.event;
    this.s = this.B(new $ze());
    this.onDidSaveError = this.s.event;
    this.t = this.B(new $ze());
    this.onDidSave = this.t.event;
    this.u = this.B(new $ze());
    this.onDidRevert = this.u.event;
    this.w = this.B(new $ze());
    this.onDidChangeReadonly = this.w.event;
    this.P = false;
    this.bb = false;
    this.gb = 0;
    this.ib = void 0;
    this.jb = new $ei();
    this.kb = false;
    this.rb = false;
    this.sb = false;
    this.B(workingCopyService.registerWorkingCopy(this));
    this.O();
  }
  O() {
    this.B(this.F.onDidChangeReadonly(() => this.w.fire()));
  }
  isDirty() {
    return this.P;
  }
  markModified() {
    this.R(true);
  }
  R(dirty) {
    if (!this.isResolved()) {
      return;
    }
    const wasDirty = this.P;
    this.S(dirty);
    if (dirty !== wasDirty) {
      this.r.fire();
    }
  }
  S(dirty) {
    const wasDirty = this.P;
    const wasInConflictMode = this.rb;
    const wasInErrorMode = this.sb;
    const oldSavedVersionId = this.Q;
    if (!dirty) {
      this.P = false;
      this.rb = false;
      this.sb = false;
      if (this.isResolved()) {
        this.Q = this.model.versionId;
      }
    } else {
      this.P = true;
    }
    return () => {
      this.P = wasDirty;
      this.rb = wasInConflictMode;
      this.sb = wasInErrorMode;
      this.Q = oldSavedVersionId;
    };
  }
  isResolved() {
    return !!this.model;
  }
  async resolve(options3) {
    this.tb("resolve() - enter");
    if (this.isDisposed()) {
      this.tb("resolve() - exit - without resolving because file working copy is disposed");
      return;
    }
    if (!options3?.contents && (this.P || this.jb.isRunning())) {
      this.tb("resolve() - exit - without resolving because file working copy is dirty or being saved");
      return;
    }
    return this.U(options3);
  }
  async U(options3) {
    if (options3?.contents) {
      return this.W(options3.contents);
    }
    const isNew = !this.isResolved();
    if (isNew) {
      const resolvedFromBackup = await this.X();
      if (resolvedFromBackup) {
        return;
      }
    }
    return this.Z(options3);
  }
  async W(buffer) {
    this.tb("resolveFromBuffer()");
    let mtime;
    let ctime;
    let size;
    let etag;
    try {
      const metadata = await this.a.stat(this.resource);
      mtime = metadata.mtime;
      ctime = metadata.ctime;
      size = metadata.size;
      etag = metadata.etag;
      this.g(false);
    } catch (error) {
      mtime = Date.now();
      ctime = Date.now();
      size = 0;
      etag = $Pm;
      this.g(
        error.fileOperationResult === 1
        /* FileOperationResult.FILE_NOT_FOUND */
      );
    }
    return this.$(
      {
        resource: this.resource,
        name: this.name,
        mtime,
        ctime,
        size,
        etag,
        value: buffer,
        readonly: false,
        locked: false
      },
      true
      /* dirty (resolved from buffer) */
    );
  }
  async X() {
    const backup = await this.G.resolve(this);
    const isNew = !this.isResolved();
    if (!isNew) {
      this.tb("resolveFromBackup() - exit - withoutresolving because previously new file working copy got created meanwhile");
      return true;
    }
    if (backup) {
      await this.Y(backup);
      return true;
    }
    return false;
  }
  async Y(backup) {
    this.tb("doResolveFromBackup()");
    await this.$(
      {
        resource: this.resource,
        name: this.name,
        mtime: backup.meta ? backup.meta.mtime : Date.now(),
        ctime: backup.meta ? backup.meta.ctime : Date.now(),
        size: backup.meta ? backup.meta.size : 0,
        etag: backup.meta ? backup.meta.etag : $Pm,
        // etag disabled if unknown!
        value: backup.value,
        readonly: false,
        locked: false
      },
      true
      /* dirty (resolved from backup) */
    );
    if (backup.meta && backup.meta.orphaned) {
      this.g(true);
    }
  }
  async Z(options3) {
    this.tb("resolveFromFile()");
    const forceReadFromFile = options3?.forceReadFromFile;
    let etag;
    if (forceReadFromFile) {
      etag = $Pm;
    } else if (this.lastResolvedFileStat) {
      etag = this.lastResolvedFileStat.etag;
    }
    const currentVersionId = this.gb;
    try {
      const content = await this.a.readFileStream(this.resource, {
        etag,
        limits: options3?.limits
      });
      this.g(false);
      if (currentVersionId !== this.gb) {
        this.tb("resolveFromFile() - exit - without resolving because file working copy content changed");
        return;
      }
      await this.$(
        content,
        false
        /* not dirty (resolved from file) */
      );
    } catch (error) {
      const result = error.fileOperationResult;
      this.g(
        result === 1
        /* FileOperationResult.FILE_NOT_FOUND */
      );
      if (this.isResolved() && result === 2) {
        if (error instanceof $Hm) {
          this.qb(error.stat);
        }
        return;
      }
      if (this.isResolved() && result === 1 && !forceReadFromFile) {
        return;
      }
      throw error;
    }
  }
  async $(content, dirty) {
    this.tb("resolveFromContent() - enter");
    if (this.isDisposed()) {
      this.tb("resolveFromContent() - exit - because working copy is disposed");
      return;
    }
    this.qb({
      resource: this.resource,
      name: content.name,
      mtime: content.mtime,
      ctime: content.ctime,
      size: content.size,
      etag: content.etag,
      readonly: content.readonly,
      locked: content.locked,
      isFile: true,
      isDirectory: false,
      isSymbolicLink: false,
      children: void 0
    });
    if (this.isResolved()) {
      await this.cb(content.value);
    } else {
      await this.ab(content.value);
    }
    this.R(!!dirty);
    this.n.fire();
  }
  async ab(contents) {
    this.tb("doCreateModel()");
    this.j = this.B(await this.y.createModel(this.resource, contents, CancellationToken.None));
    this.db(this.j);
  }
  async cb(contents) {
    this.tb("doUpdateModel()");
    this.bb = true;
    try {
      await this.model?.update(contents, CancellationToken.None);
    } finally {
      this.bb = false;
    }
  }
  db(model) {
    this.B(model.onDidChangeContent((e) => this.eb(model, e.isUndoing || e.isRedoing)));
    this.B(model.onWillDispose(() => this.dispose()));
  }
  eb(model, isUndoingOrRedoing) {
    this.tb(`onModelContentChanged() - enter`);
    this.gb++;
    this.tb(`onModelContentChanged() - new versionId ${this.gb}`);
    if (isUndoingOrRedoing) {
      this.ib = Date.now();
    }
    if (!this.bb && !this.isReadonly()) {
      if (model.versionId === this.Q) {
        this.tb("onModelContentChanged() - model content changed back to last saved version");
        const wasDirty = this.P;
        this.R(false);
        if (wasDirty) {
          this.u.fire();
        }
      } else {
        this.tb("onModelContentChanged() - model content changed and marked as dirty");
        this.R(true);
      }
    }
    this.m.fire();
  }
  async fb() {
    if (this.isDisposed()) {
      return;
    }
    await this.z({
      forceReadFromFile: true
    });
  }
  //#endregion
  //#region Backup
  get backupDelay() {
    return this.model?.configuration?.backupDelay;
  }
  async backup(token) {
    let meta = void 0;
    if (this.lastResolvedFileStat) {
      meta = {
        mtime: this.lastResolvedFileStat.mtime,
        ctime: this.lastResolvedFileStat.ctime,
        size: this.lastResolvedFileStat.size,
        etag: this.lastResolvedFileStat.etag,
        orphaned: this.isOrphaned()
      };
    }
    let content = void 0;
    if (this.isResolved()) {
      content = await $Ih(this.model.snapshot(2, token), token);
    }
    return { meta, content };
  }
  static {
    this.hb = 500;
  }
  async save(options3 = /* @__PURE__ */ Object.create(null)) {
    if (!this.isResolved()) {
      return false;
    }
    if (this.isReadonly()) {
      this.tb("save() - ignoring request for readonly resource");
      return false;
    }
    if ((this.hasState(
      3
      /* StoredFileWorkingCopyState.CONFLICT */
    ) || this.hasState(
      5
      /* StoredFileWorkingCopyState.ERROR */
    )) && (options3.reason === 2 || options3.reason === 3 || options3.reason === 4)) {
      this.tb("save() - ignoring auto save request for file working copy that is in conflict or error");
      return false;
    }
    this.tb("save() - enter");
    await this.lb(options3);
    this.tb("save() - exit");
    return this.hasState(
      0
      /* StoredFileWorkingCopyState.SAVED */
    );
  }
  async lb(options3) {
    if (typeof options3.reason !== "number") {
      options3.reason = 1;
    }
    const versionId = this.gb;
    this.tb(`doSave(${versionId}) - enter with versionId ${versionId}`);
    if (this.kb) {
      this.tb(`doSave(${versionId}) - exit - refusing to save() recursively from save participant`);
      return;
    }
    if (this.jb.isRunning(versionId)) {
      this.tb(`doSave(${versionId}) - exit - found a running save for versionId ${versionId}`);
      return this.jb.running;
    }
    if (!options3.force && !this.P) {
      this.tb(`doSave(${versionId}) - exit - because not dirty and/or versionId is different (this.isDirty: ${this.P}, this.versionId: ${this.gb})`);
      return;
    }
    if (this.jb.isRunning()) {
      this.tb(`doSave(${versionId}) - exit - because busy saving`);
      this.jb.cancelRunning();
      return this.jb.queue(() => this.lb(options3));
    }
    if (this.isResolved()) {
      this.model.pushStackElement();
    }
    const saveCancellation = new $ad();
    return this.N.withProgress({
      title: localize(13594, null, this.name),
      location: 10,
      cancellable: true,
      delay: this.isDirty() ? 3e3 : 5e3
    }, (progress) => {
      return this.mb(versionId, options3, progress, saveCancellation);
    }, () => {
      saveCancellation.cancel();
    }).finally(() => {
      saveCancellation.dispose();
    });
  }
  mb(versionId, options3, progress, saveCancellation) {
    return this.jb.run(versionId, (async () => {
      if (this.isResolved() && !options3.skipSaveParticipants && this.D.hasSaveParticipants) {
        try {
          if (options3.reason === 2 && typeof this.ib === "number") {
            const timeFromUndoRedoToSave = Date.now() - this.ib;
            if (timeFromUndoRedoToSave < $$J_1.hb) {
              await $Wh($$J_1.hb - timeFromUndoRedoToSave);
            }
          }
          if (!saveCancellation.token.isCancellationRequested) {
            this.kb = true;
            try {
              await this.D.runSaveParticipants(this, { reason: options3.reason ?? 1, savedFrom: options3.from }, progress, saveCancellation.token);
            } catch (err) {
              if ($kb(err) && !saveCancellation.token.isCancellationRequested) {
                saveCancellation.cancel();
              }
            } finally {
              this.kb = false;
            }
          }
        } catch (error) {
          this.C.error(`[stored file working copy] runSaveParticipants(${versionId}) - resulted in an error: ${error.toString()}`, this.resource.toString(), this.typeId);
        }
      }
      if (saveCancellation.token.isCancellationRequested) {
        return;
      }
      if (this.isDisposed()) {
        return;
      }
      if (!this.isResolved()) {
        return;
      }
      versionId = this.gb;
      this.sb = false;
      progress.report({ message: localize(13595, null) });
      this.tb(`doSave(${versionId}) - before write()`);
      const lastResolvedFileStat = $Kg(this.lastResolvedFileStat);
      const resolvedFileWorkingCopy = this;
      return this.jb.run(versionId, (async () => {
        try {
          const writeFileOptions = {
            mtime: lastResolvedFileStat.mtime,
            etag: options3.ignoreModifiedSince || !this.F.preventSaveConflicts(lastResolvedFileStat.resource) ? $Pm : lastResolvedFileStat.etag,
            unlock: options3.writeUnlock
          };
          let stat;
          if (typeof resolvedFileWorkingCopy.model.save === "function") {
            try {
              stat = await resolvedFileWorkingCopy.model.save(writeFileOptions, saveCancellation.token);
            } catch (error) {
              if (saveCancellation.token.isCancellationRequested) {
                return void 0;
              }
              throw error;
            }
          } else {
            const snapshot = await $Ih(resolvedFileWorkingCopy.model.snapshot(1, saveCancellation.token), saveCancellation.token);
            if (saveCancellation.token.isCancellationRequested) {
              return;
            } else {
              saveCancellation.dispose();
            }
            if (options3?.writeElevated && this.L.isSupported(lastResolvedFileStat.resource)) {
              stat = await this.L.writeFileElevated(lastResolvedFileStat.resource, $Kg(snapshot), writeFileOptions);
            } else {
              stat = await this.a.writeFile(lastResolvedFileStat.resource, $Kg(snapshot), writeFileOptions);
            }
          }
          this.nb(stat, versionId, options3);
        } catch (error) {
          this.ob(error, versionId, options3);
        }
      })(), () => saveCancellation.cancel());
    })(), () => saveCancellation.cancel());
  }
  nb(stat, versionId, options3) {
    this.qb(stat);
    if (versionId === this.gb) {
      this.tb(`handleSaveSuccess(${versionId}) - setting dirty to false because versionId did not change`);
      this.R(false);
    } else {
      this.tb(`handleSaveSuccess(${versionId}) - not setting dirty to false because versionId did change meanwhile`);
    }
    this.g(false);
    this.t.fire({ reason: options3.reason, stat, source: options3.source });
  }
  ob(error, versionId, options3) {
    (options3.ignoreErrorHandler ? this.C.trace : this.C.error).apply(this.C, [`[stored file working copy] handleSaveError(${versionId}) - exit - resulted in a save error: ${error.toString()}`, this.resource.toString(), this.typeId]);
    if (options3.ignoreErrorHandler) {
      throw error;
    }
    this.R(true);
    this.sb = true;
    if (error.fileOperationResult === 3) {
      this.rb = true;
    }
    this.pb(error, options3);
    this.s.fire();
  }
  pb(error, options3) {
    const fileOperationError = error;
    const primaryActions = [];
    let message;
    if (fileOperationError.fileOperationResult === 3) {
      message = localize(13596, null, this.name);
      primaryActions.push($Zm({ id: "fileWorkingCopy.overwrite", label: localize(13597, null), run: () => this.save({
        ...options3,
        ignoreModifiedSince: true,
        reason: 1
        /* SaveReason.EXPLICIT */
      }) }));
      primaryActions.push($Zm({ id: "fileWorkingCopy.revert", label: localize(13598, null), run: () => this.revert() }));
    } else {
      const isWriteLocked = fileOperationError.fileOperationResult === 5;
      const triedToUnlock = isWriteLocked && fileOperationError.options?.unlock;
      const isPermissionDenied = fileOperationError.fileOperationResult === 6;
      const canSaveElevated = this.L.isSupported(this.resource);
      if ($2m(error)) {
        primaryActions.push(...error.actions);
      }
      if (canSaveElevated && (isPermissionDenied || triedToUnlock)) {
        primaryActions.push($Zm({
          id: "fileWorkingCopy.saveElevated",
          label: triedToUnlock ? $l ? localize(13599, null) : localize(13600, null) : $l ? localize(13601, null) : localize(13602, null),
          run: () => {
            this.save({
              ...options3,
              writeElevated: true,
              writeUnlock: triedToUnlock,
              reason: 1
              /* SaveReason.EXPLICIT */
            });
          }
        }));
      } else if (isWriteLocked) {
        primaryActions.push($Zm({ id: "fileWorkingCopy.unlock", label: localize(13603, null), run: () => this.save({
          ...options3,
          writeUnlock: true,
          reason: 1
          /* SaveReason.EXPLICIT */
        }) }));
      } else {
        primaryActions.push($Zm({ id: "fileWorkingCopy.retry", label: localize(13604, null), run: () => this.save({
          ...options3,
          reason: 1
          /* SaveReason.EXPLICIT */
        }) }));
      }
      primaryActions.push($Zm({
        id: "fileWorkingCopy.saveAs",
        label: localize(13605, null),
        run: async () => {
          const editor = this.I.findEditor(this);
          if (editor) {
            const result = await this.J.save(editor, {
              saveAs: true,
              reason: 1
              /* SaveReason.EXPLICIT */
            });
            if (!result.success) {
              this.pb(error, options3);
            }
          }
        }
      }));
      primaryActions.push($Zm({ id: "fileWorkingCopy.revert", label: localize(13606, null), run: () => this.revert() }));
      if (isWriteLocked) {
        if (triedToUnlock && canSaveElevated) {
          message = $l ? localize(13607, null, this.name) : localize(13608, null, this.name);
        } else {
          message = localize(13609, null, this.name);
        }
      } else if (canSaveElevated && isPermissionDenied) {
        message = $l ? localize(13610, null, this.name) : localize(13611, null, this.name);
      } else {
        message = localize(13612, null, this.name, $1m(error, false));
      }
    }
    const handle2 = this.H.notify({ id: `${$Xi(this.resource.toString())}`, severity: Severity2.Error, message, actions: { primary: primaryActions } });
    const listener = this.B(Event2.once(Event2.any(this.onDidSave, this.onDidRevert))(() => handle2.close()));
    this.B(Event2.once(handle2.onDidClose)(() => listener.dispose()));
  }
  qb(newFileStat) {
    const oldReadonly = this.isReadonly();
    if (!this.lastResolvedFileStat) {
      this.lastResolvedFileStat = newFileStat;
    } else if (this.lastResolvedFileStat.mtime <= newFileStat.mtime) {
      this.lastResolvedFileStat = newFileStat;
    } else {
      this.lastResolvedFileStat = { ...this.lastResolvedFileStat, readonly: newFileStat.readonly, locked: newFileStat.locked };
    }
    if (this.isReadonly() !== oldReadonly) {
      this.w.fire();
    }
  }
  //#endregion
  //#region Revert
  async revert(options3) {
    if (!this.isResolved() || !this.P && !options3?.force) {
      return;
    }
    this.tb("revert()");
    const wasDirty = this.P;
    const undoSetDirty = this.S(false);
    const softUndo = options3?.soft;
    if (!softUndo) {
      try {
        await this.fb();
      } catch (error) {
        if (error.fileOperationResult !== 1) {
          undoSetDirty();
          throw error;
        }
      }
    }
    this.u.fire();
    if (wasDirty) {
      this.r.fire();
    }
  }
  hasState(state) {
    switch (state) {
      case 3:
        return this.rb;
      case 1:
        return this.P;
      case 5:
        return this.sb;
      case 4:
        return this.isOrphaned();
      case 2:
        return this.jb.isRunning();
      case 0:
        return !this.P;
    }
  }
  async joinState(state) {
    return this.jb.running;
  }
  //#endregion
  //#region Utilities
  isReadonly() {
    return this.F.isReadonly(this.resource, this.lastResolvedFileStat);
  }
  tb(msg) {
    this.C.trace(`[stored file working copy] ${msg}`, this.resource.toString(), this.typeId);
  }
  //#endregion
  //#region Dispose
  dispose() {
    this.tb("dispose()");
    this.rb = false;
    this.sb = false;
    this.j = void 0;
    super.dispose();
  }
};
$$J = $$J_1 = __decorate([
  __param(5, $km),
  __param(6, $wn),
  __param(7, $aK),
  __param(8, $4J),
  __param(9, $yG),
  __param(10, $XI),
  __param(11, $PJ),
  __param(12, $6J),
  __param(13, $mJ),
  __param(14, $8J),
  __param(15, $TJ)
], $$J);

// out-build/vs/workbench/services/workingCopy/common/abstractFileWorkingCopyManager.js
var $KSb = class $KSb2 extends $3c {
  constructor(f, g, h3) {
    super();
    this.f = f;
    this.g = g;
    this.h = h3;
    this.a = this.B(new $ze());
    this.onDidCreate = this.a.event;
    this.b = new $Ec();
    this.c = new $Ec();
  }
  j(resource) {
    return this.b.has(resource);
  }
  m(resource, workingCopy) {
    const knownWorkingCopy = this.get(resource);
    if (knownWorkingCopy === workingCopy) {
      return;
    }
    this.b.set(resource, workingCopy);
    this.c.get(resource)?.dispose();
    this.c.set(resource, workingCopy.onWillDispose(() => this.n(resource)));
    this.a.fire(workingCopy);
  }
  n(resource) {
    const disposeListener = this.c.get(resource);
    if (disposeListener) {
      $Xc(disposeListener);
      this.c.delete(resource);
    }
    return this.b.delete(resource);
  }
  //#region Get / Get all
  get workingCopies() {
    return [...this.b.values()];
  }
  get(resource) {
    return this.b.get(resource);
  }
  //#endregion
  //#region Lifecycle
  dispose() {
    super.dispose();
    this.b.clear();
    $Xc(this.c.values());
    this.c.clear();
  }
  async destroy() {
    try {
      await Promises.settled(this.workingCopies.map(async (workingCopy) => {
        if (workingCopy.isDirty()) {
          await this.r(workingCopy);
        }
      }));
    } catch (error) {
      this.g.error(error);
    }
    $Xc(this.b.values());
    this.dispose();
  }
  async r(workingCopy) {
    let saveSuccess = false;
    try {
      saveSuccess = await workingCopy.save();
    } catch (error) {
    }
    if (!saveSuccess || workingCopy.isDirty()) {
      const backup = await this.h.resolve(workingCopy);
      if (backup) {
        await this.f.writeFile(workingCopy.resource, backup.value, { unlock: true });
      }
    }
  }
};
$KSb = __decorate([
  __param(0, $km),
  __param(1, $wn),
  __param(2, $yG)
], $KSb);

// out-build/vs/workbench/services/workingCopy/common/storedFileWorkingCopyManager.js
var $LSb = class $LSb2 extends $KSb {
  constructor(I, J, fileService, L, N, logService, O, workingCopyBackupService, P, Q, R, S, U, X, Y, Z) {
    super(fileService, logService, workingCopyBackupService);
    this.I = I;
    this.J = J;
    this.L = L;
    this.N = N;
    this.O = O;
    this.P = P;
    this.Q = Q;
    this.R = R;
    this.S = S;
    this.U = U;
    this.X = X;
    this.Y = Y;
    this.Z = Z;
    this.s = this.B(new $ze());
    this.onDidResolve = this.s.event;
    this.t = this.B(new $ze());
    this.onDidChangeDirty = this.t.event;
    this.u = this.B(new $ze());
    this.onDidChangeReadonly = this.u.event;
    this.w = this.B(new $ze());
    this.onDidChangeOrphaned = this.w.event;
    this.y = this.B(new $ze());
    this.onDidSaveError = this.y.event;
    this.z = this.B(new $ze());
    this.onDidSave = this.z.event;
    this.C = this.B(new $ze());
    this.onDidRevert = this.C.event;
    this.D = this.B(new $ze());
    this.onDidRemove = this.D.event;
    this.F = new $Ec();
    this.G = new $Ec();
    this.H = this.B(new $5h());
    this.hb = /* @__PURE__ */ new Map();
    this.$();
  }
  $() {
    this.B(this.f.onDidFilesChange((e) => this.eb(e)));
    this.B(this.f.onDidChangeFileSystemProviderCapabilities((e) => this.cb(e)));
    this.B(this.f.onDidChangeFileSystemProviderRegistrations((e) => this.db(e)));
    this.B(this.O.onWillRunWorkingCopyFileOperation((e) => this.ib(e)));
    this.B(this.O.onDidFailWorkingCopyFileOperation((e) => this.jb(e)));
    this.B(this.O.onDidRunWorkingCopyFileOperation((e) => this.kb(e)));
    if ($r) {
      this.B(this.L.onBeforeShutdown((event) => event.veto(this.ab(), "veto.fileWorkingCopyManager")));
    } else {
      this.B(this.L.onWillShutdown((event) => event.join(this.bb(), { id: "join.fileWorkingCopyManager", label: localize(13613, null) })));
    }
  }
  ab() {
    if (this.workingCopies.some((workingCopy) => workingCopy.hasState(
      2
      /* StoredFileWorkingCopyState.PENDING_SAVE */
    ))) {
      return true;
    }
    return false;
  }
  async bb() {
    let pendingSavedWorkingCopies;
    while ((pendingSavedWorkingCopies = this.workingCopies.filter((workingCopy) => workingCopy.hasState(
      2
      /* StoredFileWorkingCopyState.PENDING_SAVE */
    ))).length > 0) {
      await Promises.settled(pendingSavedWorkingCopies.map((workingCopy) => workingCopy.joinState(
        2
        /* StoredFileWorkingCopyState.PENDING_SAVE */
      )));
    }
  }
  //#region Resolve from file or file provider changes
  cb(e) {
    this.fb(e.scheme);
  }
  db(e) {
    if (!e.added) {
      return;
    }
    this.fb(e.scheme);
  }
  eb(e) {
    this.fb(e);
  }
  fb(schemeOrEvent) {
    for (const workingCopy of this.workingCopies) {
      if (workingCopy.isDirty()) {
        continue;
      }
      let resolveWorkingCopy = false;
      if (typeof schemeOrEvent === "string") {
        resolveWorkingCopy = schemeOrEvent === workingCopy.resource.scheme;
      } else {
        resolveWorkingCopy = schemeOrEvent.contains(
          workingCopy.resource,
          0,
          1
          /* FileChangeType.ADDED */
        );
      }
      if (resolveWorkingCopy) {
        this.gb(workingCopy);
      }
    }
  }
  gb(workingCopy) {
    const queueSize = this.H.queueSize(workingCopy.resource);
    if (queueSize <= 1) {
      this.H.queueFor(workingCopy.resource, async () => {
        try {
          await this.lb(workingCopy);
        } catch (error) {
          this.g.error(error);
        }
      });
    }
  }
  ib(e) {
    if (e.operation === 2 || e.operation === 3) {
      e.waitUntil((async () => {
        const workingCopiesToRestore = [];
        for (const { source, target } of e.files) {
          if (source) {
            if (this.P.extUri.isEqual(source, target)) {
              continue;
            }
            const sourceWorkingCopies = [];
            for (const workingCopy of this.workingCopies) {
              if (this.P.extUri.isEqualOrParent(workingCopy.resource, source)) {
                sourceWorkingCopies.push(workingCopy);
              }
            }
            for (const sourceWorkingCopy of sourceWorkingCopies) {
              const sourceResource = sourceWorkingCopy.resource;
              let targetResource;
              if (this.P.extUri.isEqual(sourceResource, source)) {
                targetResource = target;
              } else {
                targetResource = $vh(target, sourceResource.path.substr(source.path.length + 1));
              }
              workingCopiesToRestore.push({
                source: sourceResource,
                target: targetResource,
                snapshot: sourceWorkingCopy.isDirty() ? await sourceWorkingCopy.model?.snapshot(1, CancellationToken.None) : void 0
              });
            }
          }
        }
        this.hb.set(e.correlationId, workingCopiesToRestore);
      })());
    }
  }
  jb(e) {
    if (e.operation === 2 || e.operation === 3) {
      const workingCopiesToRestore = this.hb.get(e.correlationId);
      if (workingCopiesToRestore) {
        this.hb.delete(e.correlationId);
        for (const workingCopy of workingCopiesToRestore) {
          if (workingCopy.snapshot) {
            this.get(workingCopy.source)?.markModified();
          }
        }
      }
    }
  }
  kb(e) {
    switch (e.operation) {
      case 0:
        e.waitUntil((async () => {
          for (const { target } of e.files) {
            const workingCopy = this.get(target);
            if (workingCopy && !workingCopy.isDisposed()) {
              await workingCopy.revert();
            }
          }
        })());
        break;
      case 2:
      case 3:
        e.waitUntil((async () => {
          const workingCopiesToRestore = this.hb.get(e.correlationId);
          if (workingCopiesToRestore) {
            this.hb.delete(e.correlationId);
            await Promises.settled(workingCopiesToRestore.map(async (workingCopyToRestore) => {
              const target = this.P.asCanonicalUri(workingCopyToRestore.target);
              await this.resolve(target, {
                reload: { async: false },
                // enforce a reload
                contents: workingCopyToRestore.snapshot
              });
            }));
          }
        })());
        break;
    }
  }
  //#endregion
  //#region Reload & Resolve
  async lb(workingCopy) {
    await this.nb(workingCopy.resource);
    if (workingCopy.isDirty() || workingCopy.isDisposed() || !this.j(workingCopy.resource)) {
      return;
    }
    await this.mb(workingCopy, { reload: { async: false } });
  }
  async resolve(resource, options3) {
    const pendingResolve = this.nb(resource);
    if (pendingResolve) {
      await pendingResolve;
    }
    return this.mb(resource, options3);
  }
  async mb(resourceOrWorkingCopy, options3) {
    let workingCopy;
    let resource;
    if (URI.isUri(resourceOrWorkingCopy)) {
      resource = resourceOrWorkingCopy;
      workingCopy = this.get(resource);
    } else {
      resource = resourceOrWorkingCopy.resource;
      workingCopy = resourceOrWorkingCopy;
    }
    let workingCopyResolve;
    let didCreateWorkingCopy = false;
    const resolveOptions3 = {
      contents: options3?.contents,
      forceReadFromFile: options3?.reload?.force,
      limits: options3?.limits
    };
    if (workingCopy) {
      if (options3?.contents) {
        workingCopyResolve = workingCopy.resolve(resolveOptions3);
      } else if (options3?.reload) {
        if (options3.reload.async) {
          workingCopyResolve = Promise.resolve();
          (async () => {
            try {
              await workingCopy.resolve(resolveOptions3);
            } catch (error) {
              $gb(error);
            }
          })();
        } else {
          workingCopyResolve = workingCopy.resolve(resolveOptions3);
        }
      } else {
        workingCopyResolve = Promise.resolve();
      }
    } else {
      didCreateWorkingCopy = true;
      workingCopy = new $$J(this.I, resource, this.N.getUriBasenameLabel(resource), this.J, async (options4) => {
        await this.resolve(resource, { ...options4, reload: { async: false } });
      }, this.f, this.g, this.O, this.Q, this.h, this.R, this.S, this.U, this.X, this.Y, this.Z);
      workingCopyResolve = workingCopy.resolve(resolveOptions3);
      this.pb(workingCopy);
    }
    this.G.set(resource, workingCopyResolve);
    this.m(resource, workingCopy);
    if (didCreateWorkingCopy) {
      if (workingCopy.isDirty()) {
        this.t.fire(workingCopy);
      }
    }
    try {
      await workingCopyResolve;
    } catch (error) {
      if (didCreateWorkingCopy) {
        workingCopy.dispose();
      }
      throw error;
    } finally {
      this.G.delete(resource);
    }
    if (didCreateWorkingCopy && workingCopy.isDirty()) {
      this.t.fire(workingCopy);
    }
    return workingCopy;
  }
  nb(resource) {
    const pendingWorkingCopyResolve = this.G.get(resource);
    if (!pendingWorkingCopyResolve) {
      return;
    }
    return this.ob(resource);
  }
  async ob(resource) {
    let currentWorkingCopyResolve;
    while (this.G.has(resource)) {
      const nextPendingWorkingCopyResolve = this.G.get(resource);
      if (nextPendingWorkingCopyResolve === currentWorkingCopyResolve) {
        return;
      }
      currentWorkingCopyResolve = nextPendingWorkingCopyResolve;
      try {
        await nextPendingWorkingCopyResolve;
      } catch (error) {
      }
    }
  }
  pb(workingCopy) {
    const workingCopyListeners = new $2c();
    workingCopyListeners.add(workingCopy.onDidResolve(() => this.s.fire(workingCopy)));
    workingCopyListeners.add(workingCopy.onDidChangeDirty(() => this.t.fire(workingCopy)));
    workingCopyListeners.add(workingCopy.onDidChangeReadonly(() => this.u.fire(workingCopy)));
    workingCopyListeners.add(workingCopy.onDidChangeOrphaned(() => this.w.fire(workingCopy)));
    workingCopyListeners.add(workingCopy.onDidSaveError(() => this.y.fire(workingCopy)));
    workingCopyListeners.add(workingCopy.onDidSave((e) => this.z.fire({ workingCopy, ...e })));
    workingCopyListeners.add(workingCopy.onDidRevert(() => this.C.fire(workingCopy)));
    this.F.set(workingCopy.resource, workingCopyListeners);
  }
  n(resource) {
    const removed = super.n(resource);
    const workingCopyListener = this.F.get(resource);
    if (workingCopyListener) {
      $Xc(workingCopyListener);
      this.F.delete(resource);
    }
    if (removed) {
      this.D.fire(resource);
    }
    return removed;
  }
  //#endregion
  //#region Lifecycle
  canDispose(workingCopy) {
    if (workingCopy.isDisposed() || !this.G.has(workingCopy.resource) && !workingCopy.isDirty()) {
      return true;
    }
    return this.rb(workingCopy);
  }
  async rb(workingCopy) {
    const pendingResolve = this.nb(workingCopy.resource);
    if (pendingResolve) {
      await pendingResolve;
      return this.canDispose(workingCopy);
    }
    if (workingCopy.isDirty()) {
      await Event2.toPromise(workingCopy.onDidChangeDirty);
      return this.canDispose(workingCopy);
    }
    return true;
  }
  dispose() {
    super.dispose();
    this.G.clear();
    $Xc(this.F.values());
    this.F.clear();
  }
};
$LSb = __decorate([
  __param(2, $km),
  __param(3, $KL),
  __param(4, $ZI),
  __param(5, $wn),
  __param(6, $aK),
  __param(7, $yG),
  __param(8, $vl),
  __param(9, $4J),
  __param(10, $XI),
  __param(11, $PJ),
  __param(12, $6J),
  __param(13, $mJ),
  __param(14, $8J),
  __param(15, $TJ)
], $LSb);

// out-build/vs/workbench/services/workingCopy/common/untitledFileWorkingCopy.js
var $MSb = class $MSb2 extends $3c {
  get model() {
    return this.a;
  }
  //#endregion
  constructor(typeId2, resource, name, hasAssociatedFilePath, j, m, n, r2, workingCopyService, s, t) {
    super();
    this.typeId = typeId2;
    this.resource = resource;
    this.name = name;
    this.hasAssociatedFilePath = hasAssociatedFilePath;
    this.j = j;
    this.m = m;
    this.n = n;
    this.r = r2;
    this.s = s;
    this.t = t;
    this.capabilities = this.j ? 2 | 4 : 2;
    this.a = void 0;
    this.b = this.B(new $ze());
    this.onDidChangeContent = this.b.event;
    this.c = this.B(new $ze());
    this.onDidChangeDirty = this.c.event;
    this.f = this.B(new $ze());
    this.onDidSave = this.f.event;
    this.g = this.B(new $ze());
    this.onDidRevert = this.g.event;
    this.h = this.B(new $ze());
    this.onWillDispose = this.h.event;
    this.u = this.hasAssociatedFilePath || Boolean(this.m && this.m.markModified !== false);
    this.B(workingCopyService.registerWorkingCopy(this));
  }
  isDirty() {
    return this.u && !this.j;
  }
  isModified() {
    return this.u;
  }
  w(modified) {
    if (this.u === modified) {
      return;
    }
    this.u = modified;
    if (!this.j) {
      this.c.fire();
    }
  }
  //#endregion
  //#region Resolve
  async resolve() {
    this.D("resolve()");
    if (this.isResolved()) {
      this.D("resolve() - exit (already resolved)");
      return;
    }
    let untitledContents;
    const backup = await this.s.resolve(this);
    if (backup) {
      this.D("resolve() - with backup");
      untitledContents = backup.value;
    } else if (this.m?.value) {
      this.D("resolve() - with initial contents");
      untitledContents = this.m.value;
    } else {
      this.D("resolve() - empty");
      untitledContents = $xi();
    }
    await this.y(untitledContents);
    this.w(this.hasAssociatedFilePath || !!backup || Boolean(this.m && this.m.markModified !== false));
    if (!!backup || this.m) {
      this.b.fire();
    }
  }
  async y(contents) {
    this.D("doCreateModel()");
    this.a = this.B(await this.n.createModel(this.resource, contents, CancellationToken.None));
    this.z(this.a);
  }
  z(model) {
    this.B(model.onDidChangeContent((e) => this.C(e)));
    this.B(model.onWillDispose(() => this.dispose()));
  }
  C(e) {
    if (!this.hasAssociatedFilePath && e.isInitial) {
      this.w(false);
    } else {
      this.w(true);
    }
    this.b.fire();
  }
  isResolved() {
    return !!this.model;
  }
  //#endregion
  //#region Backup
  get backupDelay() {
    return this.model?.configuration?.backupDelay;
  }
  async backup(token) {
    let content = void 0;
    if (this.isResolved()) {
      content = await $Ih(this.model.snapshot(2, token), token);
    } else if (this.m) {
      content = this.m.value;
    }
    return { content };
  }
  //#endregion
  //#region Save
  async save(options3) {
    this.D("save()");
    const result = await this.r(this, options3);
    if (result) {
      this.f.fire({ reason: options3?.reason, source: options3?.source });
    }
    return result;
  }
  //#endregion
  //#region Revert
  async revert() {
    this.D("revert()");
    this.w(false);
    this.g.fire();
    this.dispose();
  }
  //#endregion
  dispose() {
    this.D("dispose()");
    this.h.fire();
    super.dispose();
  }
  D(msg) {
    this.t.trace(`[untitled file working copy] ${msg}`, this.resource.toString(), this.typeId);
  }
};
$MSb = __decorate([
  __param(8, $XI),
  __param(9, $yG),
  __param(10, $wn)
], $MSb);

// out-build/vs/workbench/services/workingCopy/common/untitledFileWorkingCopyManager.js
var $NSb = class $NSb2 extends $KSb {
  constructor(w, y, z, fileService, C, logService, workingCopyBackupService, D) {
    super(fileService, logService, workingCopyBackupService);
    this.w = w;
    this.y = y;
    this.z = z;
    this.C = C;
    this.D = D;
    this.s = this.B(new $ze());
    this.onDidChangeDirty = this.s.event;
    this.t = this.B(new $ze());
    this.onWillDispose = this.t.event;
    this.u = new $Ec();
  }
  async resolve(options3) {
    const workingCopy = this.F(options3);
    await workingCopy.resolve();
    return workingCopy;
  }
  F(options3 = /* @__PURE__ */ Object.create(null)) {
    const massagedOptions = this.G(options3);
    if (massagedOptions.untitledResource) {
      const existingWorkingCopy = this.get(massagedOptions.untitledResource);
      if (existingWorkingCopy) {
        return existingWorkingCopy;
      }
    }
    return this.H(massagedOptions);
  }
  G(options3) {
    const massagedOptions = /* @__PURE__ */ Object.create(null);
    if (options3.associatedResource) {
      massagedOptions.untitledResource = URI.from({
        scheme: Schemas.untitled,
        authority: options3.associatedResource.authority,
        fragment: options3.associatedResource.fragment,
        path: options3.associatedResource.path,
        query: options3.associatedResource.query
      });
      massagedOptions.associatedResource = options3.associatedResource;
    } else {
      if (options3.untitledResource?.scheme === Schemas.untitled) {
        massagedOptions.untitledResource = options3.untitledResource;
      }
      massagedOptions.isScratchpad = options3.isScratchpad;
    }
    massagedOptions.contents = options3.contents;
    return massagedOptions;
  }
  H(options3) {
    let untitledResource = options3.untitledResource;
    if (!untitledResource) {
      let counter = 1;
      do {
        untitledResource = URI.from({
          scheme: Schemas.untitled,
          path: options3.isScratchpad ? `Scratchpad-${counter}` : `Untitled-${counter}`,
          query: this.w ? `typeId=${this.w}` : (
            // distinguish untitled resources among others by encoding the `typeId` as query param
            void 0
          )
          // keep untitled resources for text files as they are (when `typeId === ''`)
        });
        counter++;
      } while (this.j(untitledResource));
    }
    const workingCopy = new $MSb(this.w, untitledResource, this.C.getUriBasenameLabel(untitledResource), !!options3.associatedResource, !!options3.isScratchpad, options3.contents, this.y, this.z, this.D, this.h, this.g);
    this.I(workingCopy);
    return workingCopy;
  }
  I(workingCopy) {
    const workingCopyListeners = new $2c();
    workingCopyListeners.add(workingCopy.onDidChangeDirty(() => this.s.fire(workingCopy)));
    workingCopyListeners.add(workingCopy.onWillDispose(() => this.t.fire(workingCopy)));
    this.u.set(workingCopy.resource, workingCopyListeners);
    this.m(workingCopy.resource, workingCopy);
    if (workingCopy.isDirty()) {
      this.s.fire(workingCopy);
    }
  }
  n(resource) {
    const removed = super.n(resource);
    const workingCopyListener = this.u.get(resource);
    if (workingCopyListener) {
      $Xc(workingCopyListener);
      this.u.delete(resource);
    }
    return removed;
  }
  //#endregion
  //#region Lifecycle
  dispose() {
    super.dispose();
    $Xc(this.u.values());
    this.u.clear();
  }
};
$NSb = __decorate([
  __param(3, $km),
  __param(4, $ZI),
  __param(5, $wn),
  __param(6, $yG),
  __param(7, $XI)
], $NSb);

// out-build/vs/workbench/services/workingCopy/common/fileWorkingCopyManager.js
var $OSb_1;
var $OSb = class $OSb2 extends $3c {
  static {
    $OSb_1 = this;
  }
  static {
    this.a = $bL.registerSource("fileWorkingCopyCreate.source", localize(13582, null));
  }
  static {
    this.b = $bL.registerSource("fileWorkingCopyReplace.source", localize(13583, null));
  }
  constructor(c, f, g, h3, lifecycleService, labelService, j, m, workingCopyBackupService, n, r2, s, workingCopyService, notificationService, workingCopyEditorService, editorService, elevatedFileService, t, u, w, y, progressService) {
    super();
    this.c = c;
    this.f = f;
    this.g = g;
    this.h = h3;
    this.j = j;
    this.m = m;
    this.n = n;
    this.r = r2;
    this.s = s;
    this.t = t;
    this.u = u;
    this.w = w;
    this.y = y;
    this.stored = this.B(new $LSb(this.c, this.f, h3, lifecycleService, labelService, j, m, workingCopyBackupService, n, s, workingCopyService, notificationService, workingCopyEditorService, editorService, elevatedFileService, progressService));
    this.untitled = this.B(new $NSb(this.c, this.g, async (workingCopy, options3) => {
      const result = await this.saveAs(workingCopy.resource, void 0, options3);
      return result ? true : false;
    }, h3, labelService, j, workingCopyBackupService, workingCopyService));
    this.onDidCreate = Event2.any(this.stored.onDidCreate, this.untitled.onDidCreate);
    this.z();
  }
  //#region decorations
  z() {
    const provider = this.B(new class extends $3c {
      constructor(b) {
        super();
        this.b = b;
        this.label = localize(13584, null);
        this.a = this.B(new $ze());
        this.onDidChange = this.a.event;
        this.c();
      }
      c() {
        this.B(this.b.onDidResolve((workingCopy) => {
          if (workingCopy.isReadonly() || workingCopy.hasState(
            4
            /* StoredFileWorkingCopyState.ORPHAN */
          )) {
            this.a.fire([workingCopy.resource]);
          }
        }));
        this.B(this.b.onDidRemove((workingCopyUri) => this.a.fire([workingCopyUri])));
        this.B(this.b.onDidChangeReadonly((workingCopy) => this.a.fire([workingCopy.resource])));
        this.B(this.b.onDidChangeOrphaned((workingCopy) => this.a.fire([workingCopy.resource])));
      }
      provideDecorations(uri) {
        const workingCopy = this.b.get(uri);
        if (!workingCopy || workingCopy.isDisposed()) {
          return void 0;
        }
        const isReadonly = workingCopy.isReadonly();
        const isOrphaned = workingCopy.hasState(
          4
          /* StoredFileWorkingCopyState.ORPHAN */
        );
        if (isReadonly && isOrphaned) {
          return {
            color: $xr,
            letter: $6l.lockSmall,
            strikethrough: true,
            tooltip: localize(13585, null)
          };
        } else if (isReadonly) {
          return {
            letter: $6l.lockSmall,
            tooltip: localize(13586, null)
          };
        } else if (isOrphaned) {
          return {
            color: $xr,
            strikethrough: true,
            tooltip: localize(13587, null)
          };
        }
        return void 0;
      }
    }(this.stored));
    this.B(this.y.registerDecorationsProvider(provider));
  }
  //#endregin
  //#region get / get all
  get workingCopies() {
    return [...this.stored.workingCopies, ...this.untitled.workingCopies];
  }
  get(resource) {
    return this.stored.get(resource) ?? this.untitled.get(resource);
  }
  resolve(arg1, arg2) {
    if (URI.isUri(arg1)) {
      if (arg1.scheme === Schemas.untitled) {
        return this.untitled.resolve({ untitledResource: arg1 });
      } else {
        return this.stored.resolve(arg1, arg2);
      }
    }
    return this.untitled.resolve(arg1);
  }
  //#endregion
  //#region Save
  async saveAs(source, target, options3) {
    if (!target) {
      const workingCopy = this.get(source);
      if (workingCopy instanceof $MSb && workingCopy.hasAssociatedFilePath) {
        target = await this.I(source);
      } else {
        target = await this.r.pickFileToSave(await this.I(options3?.suggestedTarget ?? source), options3?.availableFileSystems);
      }
    }
    if (!target) {
      return;
    }
    if (this.s.isReadonly(target)) {
      const confirmed = await this.H(target);
      if (!confirmed) {
        return;
      } else {
        this.s.updateReadonly(target, false);
      }
    }
    if (this.h.hasProvider(source) && $oh(source, target)) {
      return this.C(source, {
        ...options3,
        force: true
        /* force to save, even if not dirty (https://github.com/microsoft/vscode/issues/99619) */
      });
    }
    if (this.h.hasProvider(source) && this.n.extUri.isEqual(source, target) && await this.h.exists(source)) {
      await this.m.move([{ file: { source, target } }], CancellationToken.None);
      return await this.C(source, options3) ?? await this.C(target, options3);
    }
    return this.D(source, target, options3);
  }
  async C(resource, options3) {
    const storedFileWorkingCopy = this.stored.get(resource);
    if (storedFileWorkingCopy) {
      const success = await storedFileWorkingCopy.save(options3);
      if (success) {
        return storedFileWorkingCopy;
      }
    }
    return void 0;
  }
  async D(source, target, options3) {
    let sourceContents;
    const sourceWorkingCopy = this.get(source);
    if (sourceWorkingCopy?.isResolved()) {
      sourceContents = await sourceWorkingCopy.model.snapshot(1, CancellationToken.None);
    } else {
      sourceContents = (await this.h.readFileStream(source)).value;
    }
    const { targetFileExists, targetStoredFileWorkingCopy } = await this.F(source, target);
    if (sourceWorkingCopy instanceof $MSb && sourceWorkingCopy.hasAssociatedFilePath && targetFileExists && this.n.extUri.isEqual(target, $Fh(sourceWorkingCopy.resource, this.u.remoteAuthority, this.t.defaultUriScheme))) {
      const overwrite = await this.G(target);
      if (!overwrite) {
        return void 0;
      }
    }
    await targetStoredFileWorkingCopy.model?.update(sourceContents, CancellationToken.None);
    if (!options3?.source) {
      options3 = {
        ...options3,
        source: targetFileExists ? $OSb_1.b : $OSb_1.a
      };
    }
    const success = await targetStoredFileWorkingCopy.save({
      ...options3,
      from: source,
      force: true
      /* force to save, even if not dirty (https://github.com/microsoft/vscode/issues/99619) */
    });
    if (!success) {
      return void 0;
    }
    try {
      await sourceWorkingCopy?.revert();
    } catch (error) {
      this.j.error(error);
    }
    return targetStoredFileWorkingCopy;
  }
  async F(source, target) {
    let targetFileExists = false;
    let targetStoredFileWorkingCopy = this.stored.get(target);
    if (targetStoredFileWorkingCopy?.isResolved()) {
      targetFileExists = true;
    } else {
      targetFileExists = await this.h.exists(target);
      if (!targetFileExists) {
        await this.m.create([{ resource: target }], CancellationToken.None);
      }
      if (this.n.extUri.isEqual(source, target) && this.get(source)) {
        targetStoredFileWorkingCopy = await this.stored.resolve(source);
      } else {
        targetStoredFileWorkingCopy = await this.stored.resolve(target);
      }
    }
    return { targetFileExists, targetStoredFileWorkingCopy };
  }
  async G(resource) {
    const { confirmed } = await this.w.confirm({
      type: "warning",
      message: localize(13588, null, $sh(resource)),
      detail: localize(13589, null, $sh(resource), $sh($uh(resource))),
      primaryButton: localize(13590, null)
    });
    return confirmed;
  }
  async H(resource) {
    const { confirmed } = await this.w.confirm({
      type: "warning",
      message: localize(13591, null, $sh(resource)),
      detail: localize(13592, null),
      primaryButton: localize(13593, null)
    });
    return confirmed;
  }
  async I(resource) {
    if (this.h.hasProvider(resource)) {
      return resource;
    }
    const workingCopy = this.get(resource);
    if (workingCopy instanceof $MSb && workingCopy.hasAssociatedFilePath) {
      return $Fh(resource, this.u.remoteAuthority, this.t.defaultUriScheme);
    }
    const defaultFilePath = await this.r.defaultFilePath();
    if (workingCopy) {
      const candidatePath = $vh(defaultFilePath, workingCopy.name);
      if (await this.t.hasValidBasename(candidatePath, workingCopy.name)) {
        return candidatePath;
      }
    }
    return $vh(defaultFilePath, $sh(resource));
  }
  //#endregion
  //#region Lifecycle
  async destroy() {
    await Promises.settled([
      this.stored.destroy(),
      this.untitled.destroy()
    ]);
  }
};
$OSb = $OSb_1 = __decorate([
  __param(3, $km),
  __param(4, $KL),
  __param(5, $ZI),
  __param(6, $wn),
  __param(7, $aK),
  __param(8, $yG),
  __param(9, $vl),
  __param(10, $1v),
  __param(11, $4J),
  __param(12, $XI),
  __param(13, $PJ),
  __param(14, $6J),
  __param(15, $mJ),
  __param(16, $8J),
  __param(17, $aT),
  __param(18, $US),
  __param(19, $Yv),
  __param(20, $jsb),
  __param(21, $TJ)
], $OSb);

// out-build/vs/workbench/contrib/notebook/common/notebookEditorModelResolverServiceImpl.js
var NotebookModelReferenceCollection = class NotebookModelReferenceCollection2 extends $8c {
  constructor(r2, s, t, u, w) {
    super();
    this.r = r2;
    this.s = s;
    this.t = t;
    this.u = u;
    this.w = w;
    this.f = new $2c();
    this.g = /* @__PURE__ */ new Map();
    this.h = /* @__PURE__ */ new Map();
    this.j = new $ze();
    this.onDidSaveNotebook = this.j.event;
    this.m = new $ze();
    this.onDidChangeDirty = this.m.event;
    this.n = new $Ec();
    this.q = /* @__PURE__ */ new Set();
  }
  dispose() {
    this.f.dispose();
    this.j.dispose();
    this.m.dispose();
    $Xc(this.h.values());
    $Xc(this.g.values());
  }
  isDirty(resource) {
    return this.n.get(resource) ?? false;
  }
  async b(key2, notebookType, hasAssociatedFilePath, limits, isScratchpad, viewType) {
    this.q.delete(key2);
    const uri = URI.parse(key2);
    const workingCopyTypeId = $sM.create(notebookType, viewType);
    let workingCopyManager = this.g.get(workingCopyTypeId);
    if (!workingCopyManager) {
      const factory = new $SSb(notebookType, this.s, this.t, this.u, this.w);
      workingCopyManager = this.r.createInstance($OSb, workingCopyTypeId, factory, factory);
      this.g.set(workingCopyTypeId, workingCopyManager);
    }
    const isScratchpadView = isScratchpad || notebookType === "interactive" && this.t.getValue($rM.InteractiveWindowPromptToSave) !== true;
    const model = this.r.createInstance($QSb, uri, hasAssociatedFilePath, notebookType, workingCopyManager, isScratchpadView);
    const result = await model.load({ limits });
    let onDirtyAutoReference;
    this.h.set(result, $Zc(result.onDidSave(() => this.j.fire(result.resource)), result.onDidChangeDirty(() => {
      const isDirty = result.isDirty();
      this.n.set(result.resource, isDirty);
      if (isDirty && !onDirtyAutoReference) {
        onDirtyAutoReference = this.acquire(key2, notebookType);
      } else if (onDirtyAutoReference) {
        onDirtyAutoReference.dispose();
        onDirtyAutoReference = void 0;
      }
      this.m.fire(result);
    }), $1c(() => onDirtyAutoReference?.dispose())));
    return result;
  }
  c(key2, object) {
    this.q.add(key2);
    (async () => {
      try {
        const model = await object;
        if (!this.q.has(key2)) {
          return;
        }
        if (model instanceof $QSb) {
          await model.canDispose();
        }
        if (!this.q.has(key2)) {
          return;
        }
        this.h.get(model)?.dispose();
        this.h.delete(model);
        model.dispose();
      } catch (err) {
        this.w.error("NotebookModelCollection", "FAILED to destory notebook - " + err);
      } finally {
        this.q.delete(key2);
      }
    })();
  }
};
NotebookModelReferenceCollection = __decorate([
  __param(0, $Pk),
  __param(1, $mrb),
  __param(2, $kl),
  __param(3, $zv),
  __param(4, $qFb)
], NotebookModelReferenceCollection);
var $G2b = class $G2b2 {
  constructor(instantiationService, c, d, e) {
    this.c = c;
    this.d = d;
    this.e = e;
    this.b = new $Be();
    this.onWillFailWithConflict = this.b.event;
    this.a = instantiationService.createInstance(NotebookModelReferenceCollection);
    this.onDidSaveNotebook = this.a.onDidSaveNotebook;
    this.onDidChangeDirty = this.a.onDidChangeDirty;
  }
  dispose() {
    this.a.dispose();
  }
  isDirty(resource) {
    return this.a.isDirty(resource);
  }
  f(notebookType) {
    const info = this.c.getContributedNotebookType($Kg(notebookType));
    if (!info) {
      throw new Error("UNKNOWN notebook type: " + notebookType);
    }
    const suffix = $lrb.possibleFileEnding(info.selectors) ?? "";
    for (let counter = 1; ; counter++) {
      const candidate = URI.from({ scheme: Schemas.untitled, path: `Untitled-${counter}${suffix}`, query: notebookType });
      if (!this.c.getNotebookTextModel(candidate)) {
        return candidate;
      }
    }
  }
  async g(uri, viewType) {
    if (!uri && !viewType) {
      throw new Error("Must provide at least one of resource or viewType");
    }
    if (uri?.scheme === CellUri.scheme) {
      throw new Error(`CANNOT open a cell-uri as notebook. Tried with ${uri.toString()}`);
    }
    const resource = this.e.asCanonicalUri(uri ?? this.f(viewType));
    const existingNotebook = this.c.getNotebookTextModel(resource);
    if (!viewType) {
      if (existingNotebook) {
        viewType = existingNotebook.viewType;
      } else {
        await this.d.whenInstalledExtensionsRegistered();
        const providers2 = this.c.getContributedNotebookTypes(resource);
        viewType = providers2.find((provider) => provider.priority === "exclusive")?.id ?? providers2.find((provider) => provider.priority === "default")?.id ?? providers2[0]?.id;
      }
    }
    if (!viewType) {
      throw new Error(`Missing viewType for '${resource}'`);
    }
    if (existingNotebook && existingNotebook.viewType !== viewType) {
      await this.b.fireAsync({ resource, viewType }, CancellationToken.None);
      const existingViewType2 = this.c.getNotebookTextModel(resource)?.viewType;
      if (existingViewType2 && existingViewType2 !== viewType) {
        throw new Error(`A notebook with view type '${existingViewType2}' already exists for '${resource}', CANNOT create another notebook with view type ${viewType}`);
      }
    }
    return { resource, viewType };
  }
  async createUntitledNotebookTextModel(viewType) {
    const resource = this.e.asCanonicalUri(this.f(viewType));
    return await this.c.createNotebookTextModel(viewType, resource);
  }
  async resolve(arg0, viewType, options3) {
    let resource;
    let hasAssociatedFilePath;
    if (URI.isUri(arg0)) {
      resource = arg0;
    } else if (arg0.untitledResource) {
      if (arg0.untitledResource.scheme === Schemas.untitled) {
        resource = arg0.untitledResource;
      } else {
        resource = arg0.untitledResource.with({ scheme: Schemas.untitled });
        hasAssociatedFilePath = true;
      }
    }
    const validated = await this.g(resource, viewType);
    const reference = this.a.acquire(validated.resource.toString(), validated.viewType, hasAssociatedFilePath, options3?.limits, options3?.scratchpad, options3?.viewType);
    try {
      const model = await reference.object;
      return {
        object: model,
        dispose() {
          reference.dispose();
        }
      };
    } catch (err) {
      reference.dispose();
      throw err;
    }
  }
};
$G2b = __decorate([
  __param(0, $Pk),
  __param(1, $mrb),
  __param(2, $wN),
  __param(3, $vl)
], $G2b);

// out-build/vs/workbench/contrib/notebook/browser/services/notebookKernelServiceImpl.js
var $H2b_1;
var KernelInfo = class _KernelInfo {
  static {
    this.c = 0;
  }
  constructor(kernel) {
    this.notebookPriorities = new $Ec();
    this.kernel = kernel;
    this.score = -1;
    this.time = _KernelInfo.c++;
  }
};
var NotebookTextModelLikeId = class {
  static str(k) {
    return `${k.notebookType}/${k.uri.toString()}`;
  }
  static obj(s) {
    const idx = s.indexOf("/");
    return {
      notebookType: s.substring(0, idx),
      uri: URI.parse(s.substring(idx + 1))
    };
  }
};
var SourceAction = class extends $3c {
  constructor(action, model, isPrimary) {
    super();
    this.action = action;
    this.model = model;
    this.isPrimary = isPrimary;
    this.c = this.B(new $ze());
    this.onDidChangeState = this.c.event;
  }
  async runAction() {
    if (this.execution) {
      return this.execution;
    }
    this.execution = this.f();
    this.c.fire();
    await this.execution;
    this.execution = void 0;
    this.c.fire();
  }
  async f() {
    try {
      await this.action.run({
        uri: this.model.uri,
        $mid: 14
        /* MarshalledId.NotebookActionContext */
      });
    } catch (error) {
      console.warn(`Kernel source command failed: ${error}`);
    }
  }
};
var $H2b = class $H2b2 extends $3c {
  static {
    $H2b_1 = this;
  }
  static {
    this.C = "notebook.controller2NotebookBindings";
  }
  constructor(D, F, G, H) {
    super();
    this.D = D;
    this.F = F;
    this.G = G;
    this.H = H;
    this.c = /* @__PURE__ */ new Map();
    this.f = new $Hc(1e3, 0.7);
    this.g = this.B(new $ze());
    this.h = this.B(new $ze());
    this.j = this.B(new $ze());
    this.m = this.B(new $ze());
    this.n = this.B(new $ze());
    this.r = this.B(new $ze());
    this.t = /* @__PURE__ */ new Map();
    this.u = /* @__PURE__ */ new Map();
    this.w = /* @__PURE__ */ new Map();
    this.y = this.B(new $ze());
    this.z = /* @__PURE__ */ new Map();
    this.onDidChangeSelectedNotebooks = this.g.event;
    this.onDidAddKernel = this.h.event;
    this.onDidRemoveKernel = this.j.event;
    this.onDidChangeNotebookAffinity = this.m.event;
    this.onDidChangeSourceActions = this.n.event;
    this.onDidChangeKernelDetectionTasks = this.y.event;
    this.onDidNotebookVariablesUpdate = this.r.event;
    this.B(D.onDidAddNotebookDocument(this.M, this));
    this.B(D.onWillRemoveNotebookDocument((notebook) => {
      const id2 = NotebookTextModelLikeId.str(notebook);
      const kernelId = this.f.get(id2);
      if (kernelId && notebook.uri.scheme === Schemas.untitled) {
        this.selectKernelForNotebook(void 0, notebook);
      }
      this.u.get(id2)?.dispose();
      this.u.delete(id2);
    }));
    try {
      const data = JSON.parse(this.F.get($H2b_1.C, 1, "[]"));
      this.f.fromJSON(data);
    } catch {
    }
  }
  dispose() {
    this.c.clear();
    this.t.forEach((v) => {
      v.menu.dispose();
      v.actions.forEach((a) => a[1].dispose());
    });
    this.u.forEach((v) => {
      v.dispose();
    });
    this.u.clear();
    super.dispose();
  }
  J() {
    this.I?.dispose();
    this.I = $gj($Qj(), () => {
      this.F.store(
        $H2b_1.C,
        JSON.stringify(this.f),
        1,
        1
        /* StorageTarget.MACHINE */
      );
    }, 100);
  }
  static L(kernel, notebook) {
    if (kernel.viewType === "*") {
      return 5;
    } else if (kernel.viewType === notebook.notebookType) {
      return 10;
    } else {
      return 0;
    }
  }
  M(notebook, onlyThisKernel) {
    const id2 = this.f.get(NotebookTextModelLikeId.str(notebook));
    if (!id2) {
      return;
    }
    const existingKernel = this.c.get(id2);
    if (!existingKernel || !$H2b_1.L(existingKernel.kernel, notebook)) {
      return;
    }
    if (!onlyThisKernel || existingKernel.kernel === onlyThisKernel) {
      this.g.fire({ notebook: notebook.uri, oldKernel: void 0, newKernel: existingKernel.kernel.id });
    }
  }
  notifyVariablesChange(notebookUri) {
    this.r.fire(notebookUri);
  }
  registerKernel(kernel) {
    if (this.c.has(kernel.id)) {
      throw new Error(`NOTEBOOK CONTROLLER with id '${kernel.id}' already exists`);
    }
    this.c.set(kernel.id, new KernelInfo(kernel));
    this.h.fire(kernel);
    for (const notebook of this.D.getNotebookTextModels()) {
      this.M(notebook, kernel);
    }
    return $1c(() => {
      if (this.c.delete(kernel.id)) {
        this.j.fire(kernel);
      }
      for (const [key2, candidate] of Array.from(this.f)) {
        if (candidate === kernel.id) {
          this.g.fire({ notebook: NotebookTextModelLikeId.obj(key2).uri, oldKernel: kernel.id, newKernel: void 0 });
        }
      }
    });
  }
  getMatchingKernel(notebook) {
    const kernels = [];
    for (const info of this.c.values()) {
      const score2 = $H2b_1.L(info.kernel, notebook);
      if (score2) {
        kernels.push({
          score: score2,
          kernel: info.kernel,
          instanceAffinity: info.notebookPriorities.get(notebook.uri) ?? 1
        });
      }
    }
    kernels.sort((a, b) => b.instanceAffinity - a.instanceAffinity || a.score - b.score || a.kernel.label.localeCompare(b.kernel.label));
    const all = kernels.map((obj) => obj.kernel);
    const selectedId = this.f.get(NotebookTextModelLikeId.str(notebook));
    const selected = selectedId ? this.c.get(selectedId)?.kernel : void 0;
    const suggestions = kernels.filter((item) => item.instanceAffinity > 1).map((item) => item.kernel);
    const hidden = kernels.filter((item) => item.instanceAffinity < 0).map((item) => item.kernel);
    return { all, selected, suggestions, hidden };
  }
  getSelectedOrSuggestedKernel(notebook) {
    const info = this.getMatchingKernel(notebook);
    if (info.selected) {
      return info.selected;
    }
    const preferred = info.all.filter(
      (kernel) => this.c.get(kernel.id)?.notebookPriorities.get(notebook.uri) === 2
      /* vscode.NotebookControllerPriority.Preferred */
    );
    if (preferred.length === 1) {
      return preferred[0];
    }
    return info.all.length === 1 ? info.all[0] : void 0;
  }
  // a notebook has one kernel, a kernel has N notebooks
  // notebook <-1----N-> kernel
  selectKernelForNotebook(kernel, notebook) {
    const key2 = NotebookTextModelLikeId.str(notebook);
    const oldKernel = this.f.get(key2);
    if (oldKernel !== kernel?.id) {
      if (kernel) {
        this.f.set(key2, kernel.id);
      } else {
        this.f.delete(key2);
      }
      this.g.fire({ notebook: notebook.uri, oldKernel, newKernel: kernel?.id });
      this.J();
    }
  }
  preselectKernelForNotebook(kernel, notebook) {
    const key2 = NotebookTextModelLikeId.str(notebook);
    const oldKernel = this.f.get(key2);
    if (oldKernel !== kernel?.id) {
      this.f.set(key2, kernel.id);
      this.J();
    }
  }
  updateKernelNotebookAffinity(kernel, notebook, preference) {
    const info = this.c.get(kernel.id);
    if (!info) {
      throw new Error(`UNKNOWN kernel '${kernel.id}'`);
    }
    if (preference === void 0) {
      info.notebookPriorities.delete(notebook);
    } else {
      info.notebookPriorities.set(notebook, preference);
    }
    this.m.fire();
  }
  getRunningSourceActions(notebook) {
    const id2 = NotebookTextModelLikeId.str(notebook);
    const existingInfo = this.t.get(id2);
    if (existingInfo) {
      return existingInfo.actions.filter((action) => action[0].execution).map((action) => action[0]);
    }
    return [];
  }
  getSourceActions(notebook, contextKeyService) {
    contextKeyService = contextKeyService ?? this.H;
    const id2 = NotebookTextModelLikeId.str(notebook);
    const existingInfo = this.t.get(id2);
    if (existingInfo) {
      return existingInfo.actions.map((a) => a[0]);
    }
    const sourceMenu = this.B(this.G.createMenu($bJ.NotebookKernelSource, contextKeyService));
    const info = { menu: sourceMenu, actions: [] };
    const loadActionsFromMenu = (menu, document2) => {
      const groups = menu.getActions({ shouldForwardArgs: true });
      const sourceActions = [];
      groups.forEach((group2) => {
        const isPrimary = /^primary/.test(group2[0]);
        group2[1].forEach((action) => {
          const sourceAction = new SourceAction(action, document2, isPrimary);
          const stateChangeListener = sourceAction.onDidChangeState(() => {
            this.n.fire({
              notebook: document2.uri,
              viewType: document2.notebookType
            });
          });
          sourceActions.push([sourceAction, stateChangeListener]);
        });
      });
      info.actions = sourceActions;
      this.t.set(id2, info);
      this.n.fire({ notebook: document2.uri, viewType: document2.notebookType });
    };
    this.u.get(id2)?.dispose();
    this.u.set(id2, sourceMenu.onDidChange(() => {
      loadActionsFromMenu(sourceMenu, notebook);
    }));
    loadActionsFromMenu(sourceMenu, notebook);
    return info.actions.map((a) => a[0]);
  }
  registerNotebookKernelDetectionTask(task) {
    const notebookType = task.notebookType;
    const all = this.w.get(notebookType) ?? [];
    all.push(task);
    this.w.set(notebookType, all);
    this.y.fire(notebookType);
    return $1c(() => {
      const all2 = this.w.get(notebookType) ?? [];
      const idx = all2.indexOf(task);
      if (idx >= 0) {
        all2.splice(idx, 1);
        this.w.set(notebookType, all2);
        this.y.fire(notebookType);
      }
    });
  }
  getKernelDetectionTasks(notebook) {
    return this.w.get(notebook.notebookType) ?? [];
  }
  registerKernelSourceActionProvider(viewType, provider) {
    const providers2 = this.z.get(viewType) ?? [];
    providers2.push(provider);
    this.z.set(viewType, providers2);
    this.n.fire({ viewType });
    const eventEmitterDisposable = provider.onDidChangeSourceActions?.(() => {
      this.n.fire({ viewType });
    });
    return $1c(() => {
      const providers3 = this.z.get(viewType) ?? [];
      const idx = providers3.indexOf(provider);
      if (idx >= 0) {
        providers3.splice(idx, 1);
        this.z.set(viewType, providers3);
      }
      eventEmitterDisposable?.dispose();
    });
  }
  /**
   * Get kernel source actions from providers
   */
  getKernelSourceActions2(notebook) {
    const viewType = notebook.notebookType;
    const providers2 = this.z.get(viewType) ?? [];
    const promises = providers2.map((provider) => provider.provideKernelSourceActions());
    return Promise.all(promises).then((actions) => {
      return actions.reduce((a, b) => a.concat(b), []);
    });
  }
};
$H2b = $H2b_1 = __decorate([
  __param(0, $mrb),
  __param(1, $jv),
  __param(2, $cJ),
  __param(3, $on)
], $H2b);

// out-build/vs/workbench/contrib/notebook/browser/services/notebookRendererMessagingServiceImpl.js
var $I2b = class $I2b2 extends $3c {
  constructor(f) {
    super();
    this.f = f;
    this.a = /* @__PURE__ */ new Map();
    this.b = /* @__PURE__ */ new Map();
    this.c = this.B(new $ze());
    this.onShouldPostMessage = this.c.event;
  }
  /** @inheritdoc */
  receiveMessage(editorId, rendererId, message) {
    if (editorId === void 0) {
      const sends = [...this.b.values()].map((e) => e.receiveMessageHandler?.(rendererId, message));
      return Promise.all(sends).then((s) => s.some((s2) => !!s2));
    }
    return this.b.get(editorId)?.receiveMessageHandler?.(rendererId, message) ?? Promise.resolve(false);
  }
  /** @inheritdoc */
  prepare(rendererId) {
    if (this.a.has(rendererId)) {
      return;
    }
    const queue = [];
    this.a.set(rendererId, queue);
    this.f.activateByEvent(`onRenderer:${rendererId}`).then(() => {
      for (const message of queue) {
        this.c.fire(message);
      }
      this.a.set(rendererId, void 0);
    });
  }
  /** @inheritdoc */
  getScoped(editorId) {
    const existing = this.b.get(editorId);
    if (existing) {
      return existing;
    }
    const messaging = {
      postMessage: (rendererId, message) => this.g(editorId, rendererId, message),
      dispose: () => this.b.delete(editorId)
    };
    this.b.set(editorId, messaging);
    return messaging;
  }
  g(editorId, rendererId, message) {
    if (!this.a.has(rendererId)) {
      this.prepare(rendererId);
    }
    const activation = this.a.get(rendererId);
    const toSend = { rendererId, editorId, message };
    if (activation === void 0) {
      this.c.fire(toSend);
    } else {
      activation.push(toSend);
    }
  }
};
$I2b = __decorate([
  __param(0, $wN)
], $I2b);

// out-build/vs/workbench/contrib/notebook/browser/controller/insertCellActions.js
var INSERT_CODE_CELL_ABOVE_COMMAND_ID = "notebook.cell.insertCodeCellAbove";
var INSERT_CODE_CELL_BELOW_COMMAND_ID = "notebook.cell.insertCodeCellBelow";
var INSERT_CODE_CELL_ABOVE_AND_FOCUS_CONTAINER_COMMAND_ID = "notebook.cell.insertCodeCellAboveAndFocusContainer";
var INSERT_CODE_CELL_BELOW_AND_FOCUS_CONTAINER_COMMAND_ID = "notebook.cell.insertCodeCellBelowAndFocusContainer";
var INSERT_CODE_CELL_AT_TOP_COMMAND_ID = "notebook.cell.insertCodeCellAtTop";
var INSERT_MARKDOWN_CELL_ABOVE_COMMAND_ID = "notebook.cell.insertMarkdownCellAbove";
var INSERT_MARKDOWN_CELL_BELOW_COMMAND_ID = "notebook.cell.insertMarkdownCellBelow";
var INSERT_MARKDOWN_CELL_AT_TOP_COMMAND_ID = "notebook.cell.insertMarkdownCellAtTop";
function $J2b(accessor, context, kind, direction, focusEditor) {
  let newCell = null;
  if (context.ui) {
    context.notebookEditor.focus();
  }
  const languageService = accessor.get($1E);
  if (context.cell) {
    const idx = context.notebookEditor.getCellIndex(context.cell);
    newCell = $0Ib(languageService, context.notebookEditor, idx, kind, direction, void 0, true);
  } else {
    const focusRange = context.notebookEditor.getFocus();
    const next = Math.max(focusRange.end - 1, 0);
    newCell = $0Ib(languageService, context.notebookEditor, next, kind, direction, void 0, true);
  }
  return newCell;
}
var $K2b = class extends $FIb {
  constructor(desc, a, b, d) {
    super(desc);
    this.a = a;
    this.b = b;
    this.d = d;
  }
  async runWithContext(accessor, context) {
    const newCell = await $J2b(accessor, context, this.a, this.b, this.d);
    if (newCell) {
      await context.notebookEditor.focusNotebookCell(newCell, this.d ? "editor" : "container");
    }
  }
};
$hJ(class InsertCodeCellAboveAction extends $K2b {
  constructor() {
    super({
      id: INSERT_CODE_CELL_ABOVE_COMMAND_ID,
      title: localize(8299, null),
      keybinding: {
        primary: 2048 | 1024 | 3,
        when: $7m.and($XAb, $Ceb.toNegated()),
        weight: 200
        /* KeybindingWeight.WorkbenchContrib */
      },
      menu: {
        id: $bJ.NotebookCellInsert,
        order: 0
      }
    }, CellKind.Code, "above", true);
  }
});
$hJ(class InsertCodeCellAboveAndFocusContainerAction extends $K2b {
  constructor() {
    super({
      id: INSERT_CODE_CELL_ABOVE_AND_FOCUS_CONTAINER_COMMAND_ID,
      title: localize(8300, null)
    }, CellKind.Code, "above", false);
  }
});
$hJ(class InsertCodeCellBelowAction extends $K2b {
  constructor() {
    super({
      id: INSERT_CODE_CELL_BELOW_COMMAND_ID,
      title: localize(8301, null),
      keybinding: {
        primary: 2048 | 3,
        when: $7m.and($XAb, $Ceb.toNegated(), $cJb.isEqualTo("")),
        weight: 200
        /* KeybindingWeight.WorkbenchContrib */
      },
      menu: {
        id: $bJ.NotebookCellInsert,
        order: 1
      }
    }, CellKind.Code, "below", true);
  }
});
$hJ(class InsertCodeCellBelowAndFocusContainerAction extends $K2b {
  constructor() {
    super({
      id: INSERT_CODE_CELL_BELOW_AND_FOCUS_CONTAINER_COMMAND_ID,
      title: localize(8302, null)
    }, CellKind.Code, "below", false);
  }
});
$hJ(class InsertMarkdownCellAboveAction extends $K2b {
  constructor() {
    super({
      id: INSERT_MARKDOWN_CELL_ABOVE_COMMAND_ID,
      title: localize(8303, null),
      menu: {
        id: $bJ.NotebookCellInsert,
        order: 2
      }
    }, CellKind.Markup, "above", true);
  }
});
$hJ(class InsertMarkdownCellBelowAction extends $K2b {
  constructor() {
    super({
      id: INSERT_MARKDOWN_CELL_BELOW_COMMAND_ID,
      title: localize(8304, null),
      menu: {
        id: $bJ.NotebookCellInsert,
        order: 3
      }
    }, CellKind.Markup, "below", true);
  }
});
$hJ(class InsertCodeCellAtTopAction extends $FIb {
  constructor() {
    super({
      id: INSERT_CODE_CELL_AT_TOP_COMMAND_ID,
      title: localize(8305, null),
      f1: false
    });
  }
  async run(accessor, context) {
    context = context ?? this.getEditorContextFromArgsOrActive(accessor);
    if (context) {
      this.runWithContext(accessor, context);
    }
  }
  async runWithContext(accessor, context) {
    const languageService = accessor.get($1E);
    const newCell = $0Ib(languageService, context.notebookEditor, 0, CellKind.Code, "above", void 0, true);
    if (newCell) {
      await context.notebookEditor.focusNotebookCell(newCell, "editor");
    }
  }
});
$hJ(class InsertMarkdownCellAtTopAction extends $FIb {
  constructor() {
    super({
      id: INSERT_MARKDOWN_CELL_AT_TOP_COMMAND_ID,
      title: localize(8306, null),
      f1: false
    });
  }
  async run(accessor, context) {
    context = context ?? this.getEditorContextFromArgsOrActive(accessor);
    if (context) {
      this.runWithContext(accessor, context);
    }
  }
  async runWithContext(accessor, context) {
    const languageService = accessor.get($1E);
    const newCell = $0Ib(languageService, context.notebookEditor, 0, CellKind.Markup, "above", void 0, true);
    if (newCell) {
      await context.notebookEditor.focusNotebookCell(newCell, "editor");
    }
  }
});
$dJ.appendMenuItem($bJ.NotebookCellBetween, {
  command: {
    id: INSERT_CODE_CELL_BELOW_COMMAND_ID,
    title: "$(add) " + localize(8307, null),
    tooltip: localize(8308, null)
  },
  order: 0,
  group: "inline",
  when: $7m.and($1Ab.isEqualTo(true), $7m.notEquals("config.notebook.experimental.insertToolbarAlignment", "left"))
});
$dJ.appendMenuItem($bJ.NotebookCellBetween, {
  command: {
    id: INSERT_CODE_CELL_BELOW_COMMAND_ID,
    title: localize(8309, null),
    icon: $6l.add,
    tooltip: localize(8310, null)
  },
  order: 0,
  group: "inline",
  when: $7m.and($1Ab.isEqualTo(true), $7m.equals("config.notebook.experimental.insertToolbarAlignment", "left"))
});
$dJ.appendMenuItem($bJ.NotebookToolbar, {
  command: {
    id: INSERT_CODE_CELL_BELOW_COMMAND_ID,
    icon: $6l.add,
    title: localize(8311, null),
    tooltip: localize(8312, null)
  },
  order: -5,
  group: "navigation/add",
  when: $7m.and($1Ab.isEqualTo(true), $7m.notEquals("config.notebook.insertToolbarLocation", "betweenCells"), $7m.notEquals("config.notebook.insertToolbarLocation", "hidden"))
});
$dJ.appendMenuItem($bJ.NotebookCellListTop, {
  command: {
    id: INSERT_CODE_CELL_AT_TOP_COMMAND_ID,
    title: "$(add) " + localize(8313, null),
    tooltip: localize(8314, null)
  },
  order: 0,
  group: "inline",
  when: $7m.and($1Ab.isEqualTo(true), $7m.notEquals("config.notebook.experimental.insertToolbarAlignment", "left"))
});
$dJ.appendMenuItem($bJ.NotebookCellListTop, {
  command: {
    id: INSERT_CODE_CELL_AT_TOP_COMMAND_ID,
    title: localize(8315, null),
    icon: $6l.add,
    tooltip: localize(8316, null)
  },
  order: 0,
  group: "inline",
  when: $7m.and($1Ab.isEqualTo(true), $7m.equals("config.notebook.experimental.insertToolbarAlignment", "left"))
});
$dJ.appendMenuItem($bJ.NotebookCellBetween, {
  command: {
    id: INSERT_MARKDOWN_CELL_BELOW_COMMAND_ID,
    title: "$(add) " + localize(8317, null),
    tooltip: localize(8318, null)
  },
  order: 1,
  group: "inline",
  when: $7m.and($1Ab.isEqualTo(true), $7m.notEquals("config.notebook.experimental.insertToolbarAlignment", "left"))
});
$dJ.appendMenuItem($bJ.NotebookToolbar, {
  command: {
    id: INSERT_MARKDOWN_CELL_BELOW_COMMAND_ID,
    icon: $6l.add,
    title: localize(8319, null),
    tooltip: localize(8320, null)
  },
  order: -5,
  group: "navigation/add",
  when: $7m.and($1Ab.isEqualTo(true), $7m.notEquals("config.notebook.insertToolbarLocation", "betweenCells"), $7m.notEquals("config.notebook.insertToolbarLocation", "hidden"), $7m.notEquals(`config.${$rM.globalToolbarShowLabel}`, false), $7m.notEquals(`config.${$rM.globalToolbarShowLabel}`, "never"))
});
$dJ.appendMenuItem($bJ.NotebookCellListTop, {
  command: {
    id: INSERT_MARKDOWN_CELL_AT_TOP_COMMAND_ID,
    title: "$(add) " + localize(8321, null),
    tooltip: localize(8322, null)
  },
  order: 1,
  group: "inline",
  when: $7m.and($1Ab.isEqualTo(true), $7m.notEquals("config.notebook.experimental.insertToolbarAlignment", "left"))
});

// out-build/vs/workbench/contrib/notebook/browser/controller/executeActions.js
var EXECUTE_NOTEBOOK_COMMAND_ID = "notebook.execute";
var CANCEL_NOTEBOOK_COMMAND_ID = "notebook.cancelExecution";
var INTERRUPT_NOTEBOOK_COMMAND_ID = "notebook.interruptExecution";
var CANCEL_CELL_COMMAND_ID = "notebook.cell.cancelExecution";
var EXECUTE_CELL_FOCUS_CONTAINER_COMMAND_ID = "notebook.cell.executeAndFocusContainer";
var EXECUTE_CELL_SELECT_BELOW = "notebook.cell.executeAndSelectBelow";
var EXECUTE_CELL_INSERT_BELOW = "notebook.cell.executeAndInsertBelow";
var EXECUTE_CELL_AND_BELOW = "notebook.cell.executeCellAndBelow";
var EXECUTE_CELLS_ABOVE = "notebook.cell.executeCellsAbove";
var RENDER_ALL_MARKDOWN_CELLS = "notebook.renderAllMarkdownCells";
var REVEAL_RUNNING_CELL = "notebook.revealRunningCell";
var REVEAL_LAST_FAILED_CELL = "notebook.revealLastFailedCell";
var $WLb = $7m.and($0Ab.isEqualTo("code"), $7m.or($7m.greater($oBb.key, 0), $7m.greater($pBb.key, 0), $sBb));
var $XLb = $7m.and($WLb, $eBb.toNegated());
var $YLb = $7m.and($0Ab.isEqualTo("markup"));
function renderAllMarkdownCells(context) {
  for (let i2 = 0; i2 < context.notebookEditor.getLength(); i2++) {
    const cell = context.notebookEditor.cellAt(i2);
    if (cell.cellKind === CellKind.Markup) {
      cell.updateEditState(CellEditState.Preview, "renderAllMarkdownCells");
    }
  }
}
async function runCell(editorGroupsService, context) {
  const group2 = editorGroupsService.activeGroup;
  if (group2) {
    if (group2.activeEditor) {
      group2.pinEditor(group2.activeEditor);
    }
  }
  if (context.ui && context.cell) {
    await context.notebookEditor.executeNotebookCells(Iterable.single(context.cell));
    if (context.autoReveal) {
      const cellIndex = context.notebookEditor.getCellIndex(context.cell);
      context.notebookEditor.revealCellRangeInView({ start: cellIndex, end: cellIndex + 1 });
    }
  } else if (context.selectedCells?.length || context.cell) {
    const selectedCells = context.selectedCells?.length ? context.selectedCells : [context.cell];
    await context.notebookEditor.executeNotebookCells(selectedCells);
    const firstCell = selectedCells[0];
    if (firstCell && context.autoReveal) {
      const cellIndex = context.notebookEditor.getCellIndex(firstCell);
      context.notebookEditor.revealCellRangeInView({ start: cellIndex, end: cellIndex + 1 });
    }
  }
  let foundEditor = void 0;
  for (const [, codeEditor] of context.notebookEditor.codeEditors) {
    if ($oh(codeEditor.getModel()?.uri, (context.cell ?? context.selectedCells?.[0])?.uri)) {
      foundEditor = codeEditor;
      break;
    }
  }
  if (!foundEditor) {
    return;
  }
}
$hJ(class RenderAllMarkdownCellsAction extends $FIb {
  constructor() {
    super({
      id: RENDER_ALL_MARKDOWN_CELLS,
      title: localize(8274, null)
    });
  }
  async runWithContext(accessor, context) {
    renderAllMarkdownCells(context);
  }
});
$hJ(class ExecuteNotebookAction extends $FIb {
  constructor() {
    super({
      id: EXECUTE_NOTEBOOK_COMMAND_ID,
      title: localize(8275, null),
      icon: $HKb,
      metadata: {
        description: localize(8276, null),
        args: [
          {
            name: "uri",
            description: "The document uri"
          }
        ]
      },
      menu: [
        {
          id: $bJ.EditorTitle,
          order: -1,
          group: "navigation",
          when: $7m.and($SAb, $IIb, $7m.or($rBb.toNegated(), $3Ab.toNegated()), $7m.notEquals("config.notebook.globalToolbar", true))
        },
        {
          id: $bJ.NotebookToolbar,
          order: -1,
          group: "navigation/execute",
          when: $7m.and($IIb, $7m.or($rBb.toNegated(), $3Ab.toNegated()), $7m.and($3Ab, $rBb.toNegated())?.negate(), $7m.equals("config.notebook.globalToolbar", true))
        }
      ]
    });
  }
  getEditorContextFromArgsOrActive(accessor, context) {
    return $DIb(accessor, context) ?? $CIb(accessor.get($mJ));
  }
  async runWithContext(accessor, context) {
    renderAllMarkdownCells(context);
    const editorService = accessor.get($mJ);
    const editor = editorService.getEditors(
      0
      /* EditorsOrder.MOST_RECENTLY_ACTIVE */
    ).find((editor2) => editor2.editor instanceof $trb && editor2.editor.viewType === context.notebookEditor.textModel.viewType && editor2.editor.resource.toString() === context.notebookEditor.textModel.uri.toString());
    const editorGroupService = accessor.get($iJ);
    if (editor) {
      const group2 = editorGroupService.getGroup(editor.groupId);
      group2?.pinEditor(editor.editor);
    }
    return context.notebookEditor.executeNotebookCells();
  }
});
$hJ(class ExecuteCell extends $GIb {
  constructor() {
    super({
      id: $Hrb,
      precondition: $XLb,
      title: localize(8277, null),
      keybinding: {
        when: $XAb,
        primary: 256 | 3,
        win: {
          primary: 2048 | 512 | 3
          /* KeyCode.Enter */
        },
        weight: $AIb
      },
      menu: {
        id: $bJ.NotebookCellExecutePrimary,
        when: $XLb,
        group: "inline"
      },
      metadata: {
        description: localize(8278, null),
        args: $LIb
      },
      icon: $CKb
    });
  }
  parseArgs(accessor, ...args2) {
    return $KIb(accessor, ...args2);
  }
  async runWithContext(accessor, context) {
    const editorGroupsService = accessor.get($iJ);
    if (context.ui) {
      await context.notebookEditor.focusNotebookCell(context.cell, "container", { skipReveal: true });
    }
    const chatController = $jJb.get(context.notebookEditor);
    const editingCell = chatController?.getEditingCell();
    if (chatController?.hasFocus() && editingCell) {
      const group2 = editorGroupsService.activeGroup;
      if (group2) {
        if (group2.activeEditor) {
          group2.pinEditor(group2.activeEditor);
        }
      }
      await context.notebookEditor.executeNotebookCells([editingCell]);
      return;
    }
    await runCell(editorGroupsService, context);
  }
});
$hJ(class ExecuteAboveCells extends $GIb {
  constructor() {
    super({
      id: EXECUTE_CELLS_ABOVE,
      precondition: $WLb,
      title: localize(8279, null),
      menu: [
        {
          id: $bJ.NotebookCellExecute,
          when: $7m.and($WLb, $7m.equals(`config.${$rM.consolidatedRunButton}`, true))
        },
        {
          id: $bJ.NotebookCellTitle,
          order: 2,
          group: $yIb,
          when: $7m.and($WLb, $7m.equals(`config.${$rM.consolidatedRunButton}`, false))
        }
      ],
      icon: $DKb
    });
  }
  parseArgs(accessor, ...args2) {
    return $KIb(accessor, ...args2);
  }
  async runWithContext(accessor, context) {
    let endCellIdx = void 0;
    if (context.ui) {
      endCellIdx = context.notebookEditor.getCellIndex(context.cell);
      await context.notebookEditor.focusNotebookCell(context.cell, "container", { skipReveal: true });
    } else {
      endCellIdx = Math.min(...context.selectedCells.map((cell) => context.notebookEditor.getCellIndex(cell)));
    }
    if (typeof endCellIdx === "number") {
      const range = { start: 0, end: endCellIdx };
      const cells = context.notebookEditor.getCellsInRange(range);
      context.notebookEditor.executeNotebookCells(cells);
    }
  }
});
$hJ(class ExecuteCellAndBelow extends $GIb {
  constructor() {
    super({
      id: EXECUTE_CELL_AND_BELOW,
      precondition: $WLb,
      title: localize(8280, null),
      menu: [
        {
          id: $bJ.NotebookCellExecute,
          when: $7m.and($WLb, $7m.equals(`config.${$rM.consolidatedRunButton}`, true))
        },
        {
          id: $bJ.NotebookCellTitle,
          order: 3,
          group: $yIb,
          when: $7m.and($WLb, $7m.equals(`config.${$rM.consolidatedRunButton}`, false))
        }
      ],
      icon: $EKb
    });
  }
  parseArgs(accessor, ...args2) {
    return $KIb(accessor, ...args2);
  }
  async runWithContext(accessor, context) {
    let startCellIdx = void 0;
    if (context.ui) {
      startCellIdx = context.notebookEditor.getCellIndex(context.cell);
      await context.notebookEditor.focusNotebookCell(context.cell, "container", { skipReveal: true });
    } else {
      startCellIdx = Math.min(...context.selectedCells.map((cell) => context.notebookEditor.getCellIndex(cell)));
    }
    if (typeof startCellIdx === "number") {
      const range = { start: startCellIdx, end: context.notebookEditor.getLength() };
      const cells = context.notebookEditor.getCellsInRange(range);
      context.notebookEditor.executeNotebookCells(cells);
    }
  }
});
$hJ(class ExecuteCellFocusContainer extends $GIb {
  constructor() {
    super({
      id: EXECUTE_CELL_FOCUS_CONTAINER_COMMAND_ID,
      precondition: $XLb,
      title: localize(8281, null),
      metadata: {
        description: localize(8282, null),
        args: $LIb
      },
      icon: $CKb
    });
  }
  parseArgs(accessor, ...args2) {
    return $KIb(accessor, ...args2);
  }
  async runWithContext(accessor, context) {
    const editorGroupsService = accessor.get($iJ);
    if (context.ui) {
      await context.notebookEditor.focusNotebookCell(context.cell, "container", { skipReveal: true });
    } else {
      const firstCell = context.selectedCells[0];
      if (firstCell) {
        await context.notebookEditor.focusNotebookCell(firstCell, "container", { skipReveal: true });
      }
    }
    await runCell(editorGroupsService, context);
  }
});
var cellCancelCondition = $7m.or($7m.equals($dBb.key, "executing"), $7m.equals($dBb.key, "pending"));
$hJ(class CancelExecuteCell extends $GIb {
  constructor() {
    super({
      id: CANCEL_CELL_COMMAND_ID,
      precondition: cellCancelCondition,
      title: localize(8283, null),
      icon: $FKb,
      menu: {
        id: $bJ.NotebookCellExecutePrimary,
        when: cellCancelCondition,
        group: "inline"
      },
      metadata: {
        description: localize(8284, null),
        args: [
          {
            name: "options",
            description: "The cell range options",
            schema: {
              "type": "object",
              "required": ["ranges"],
              "properties": {
                "ranges": {
                  "type": "array",
                  items: [
                    {
                      "type": "object",
                      "required": ["start", "end"],
                      "properties": {
                        "start": {
                          "type": "number"
                        },
                        "end": {
                          "type": "number"
                        }
                      }
                    }
                  ]
                },
                "document": {
                  "type": "object",
                  "description": "The document uri"
                }
              }
            }
          }
        ]
      }
    });
  }
  parseArgs(accessor, ...args2) {
    return $KIb(accessor, ...args2);
  }
  async runWithContext(accessor, context) {
    if (context.ui) {
      await context.notebookEditor.focusNotebookCell(context.cell, "container", { skipReveal: true });
      return context.notebookEditor.cancelNotebookCells(Iterable.single(context.cell));
    } else {
      return context.notebookEditor.cancelNotebookCells(context.selectedCells);
    }
  }
});
$hJ(class ExecuteCellSelectBelow extends $HIb {
  constructor() {
    super({
      id: EXECUTE_CELL_SELECT_BELOW,
      precondition: $7m.or($XLb, $0Ab.isEqualTo("markup")),
      title: localize(8285, null),
      keybinding: {
        when: $7m.and($XAb, $aAb.negate()),
        primary: 1024 | 3,
        weight: $AIb
      }
    });
  }
  async runWithContext(accessor, context) {
    const editorGroupsService = accessor.get($iJ);
    const idx = context.notebookEditor.getCellIndex(context.cell);
    if (typeof idx !== "number") {
      return;
    }
    const languageService = accessor.get($1E);
    const config = accessor.get($kl);
    const scrollBehavior = config.getValue($rM.scrollToRevealCell);
    let focusOptions;
    if (scrollBehavior === "none") {
      focusOptions = { skipReveal: true };
    } else {
      focusOptions = {
        revealBehavior: scrollBehavior === "fullCell" ? ScrollToRevealBehavior.fullCell : ScrollToRevealBehavior.firstLine
      };
    }
    if (context.cell.cellKind === CellKind.Markup) {
      const nextCell = context.notebookEditor.cellAt(idx + 1);
      context.cell.updateEditState(CellEditState.Preview, EXECUTE_CELL_SELECT_BELOW);
      if (nextCell) {
        await context.notebookEditor.focusNotebookCell(nextCell, "container", focusOptions);
      } else {
        const newCell = $0Ib(languageService, context.notebookEditor, idx, CellKind.Markup, "below");
        if (newCell) {
          await context.notebookEditor.focusNotebookCell(newCell, "editor", focusOptions);
        }
      }
      return;
    } else {
      const nextCell = context.notebookEditor.cellAt(idx + 1);
      if (nextCell) {
        await context.notebookEditor.focusNotebookCell(nextCell, "container", focusOptions);
      } else {
        const newCell = $0Ib(languageService, context.notebookEditor, idx, CellKind.Code, "below");
        if (newCell) {
          await context.notebookEditor.focusNotebookCell(newCell, "editor", focusOptions);
        }
      }
      return runCell(editorGroupsService, context);
    }
  }
});
$hJ(class ExecuteCellInsertBelow extends $HIb {
  constructor() {
    super({
      id: EXECUTE_CELL_INSERT_BELOW,
      precondition: $7m.or($XLb, $0Ab.isEqualTo("markup")),
      title: localize(8286, null),
      keybinding: {
        when: $XAb,
        primary: 512 | 3,
        weight: $AIb
      }
    });
  }
  async runWithContext(accessor, context) {
    const editorGroupsService = accessor.get($iJ);
    const idx = context.notebookEditor.getCellIndex(context.cell);
    const languageService = accessor.get($1E);
    const newFocusMode = context.cell.focusMode === CellFocusMode.Editor ? "editor" : "container";
    const newCell = $0Ib(languageService, context.notebookEditor, idx, context.cell.cellKind, "below");
    if (newCell) {
      await context.notebookEditor.focusNotebookCell(newCell, newFocusMode);
    }
    if (context.cell.cellKind === CellKind.Markup) {
      context.cell.updateEditState(CellEditState.Preview, EXECUTE_CELL_INSERT_BELOW);
    } else {
      runCell(editorGroupsService, context);
    }
  }
});
var CancelNotebook = class extends $FIb {
  getEditorContextFromArgsOrActive(accessor, context) {
    return $DIb(accessor, context) ?? $CIb(accessor.get($mJ));
  }
  async runWithContext(accessor, context) {
    return context.notebookEditor.cancelNotebookCells();
  }
};
$hJ(class CancelAllNotebook extends CancelNotebook {
  constructor() {
    super({
      id: CANCEL_NOTEBOOK_COMMAND_ID,
      title: localize2(8294, "Stop Execution"),
      icon: $FKb,
      menu: [
        {
          id: $bJ.EditorTitle,
          order: -1,
          group: "navigation",
          when: $7m.and($SAb, $3Ab, $rBb.toNegated(), $7m.notEquals("config.notebook.globalToolbar", true))
        },
        {
          id: $bJ.NotebookToolbar,
          order: -1,
          group: "navigation/execute",
          when: $7m.and($3Ab, $rBb.toNegated(), $7m.equals("config.notebook.globalToolbar", true))
        }
      ]
    });
  }
});
$hJ(class InterruptNotebook extends CancelNotebook {
  constructor() {
    super({
      id: INTERRUPT_NOTEBOOK_COMMAND_ID,
      title: localize2(8295, "Interrupt"),
      precondition: $7m.and($3Ab, $rBb),
      icon: $FKb,
      menu: [
        {
          id: $bJ.EditorTitle,
          order: -1,
          group: "navigation",
          when: $7m.and($SAb, $3Ab, $rBb, $7m.notEquals("config.notebook.globalToolbar", true))
        },
        {
          id: $bJ.NotebookToolbar,
          order: -1,
          group: "navigation/execute",
          when: $7m.and($3Ab, $rBb, $7m.equals("config.notebook.globalToolbar", true))
        },
        {
          id: $bJ.InteractiveToolbar,
          group: "navigation/execute"
        }
      ]
    });
  }
});
$dJ.appendMenuItem($bJ.NotebookToolbar, {
  title: localize(8287, null),
  submenu: $bJ.NotebookCellExecuteGoTo,
  group: "navigation/execute",
  order: 20,
  icon: ThemeIcon.modify($RKb, "spin")
});
$hJ(class RevealRunningCellAction extends $FIb {
  constructor() {
    super({
      id: REVEAL_RUNNING_CELL,
      title: localize(8288, null),
      tooltip: localize(8289, null),
      shortTitle: localize(8290, null),
      precondition: $2Ab,
      menu: [
        {
          id: $bJ.EditorTitle,
          when: $7m.and($SAb, $2Ab, $7m.notEquals("config.notebook.globalToolbar", true)),
          group: "navigation",
          order: 0
        },
        {
          id: $bJ.NotebookCellExecuteGoTo,
          when: $7m.and($SAb, $2Ab, $7m.equals("config.notebook.globalToolbar", true)),
          group: "navigation/execute",
          order: 20
        },
        {
          id: $bJ.InteractiveToolbar,
          when: $7m.and($2Ab, $7m.equals("activeEditor", "workbench.editor.interactive")),
          group: "navigation",
          order: 10
        }
      ],
      icon: ThemeIcon.modify($RKb, "spin")
    });
  }
  async runWithContext(accessor, context) {
    const notebookExecutionStateService = accessor.get($wL);
    const notebook = context.notebookEditor.textModel.uri;
    const executingCells = notebookExecutionStateService.getCellExecutionsForNotebook(notebook);
    if (executingCells[0]) {
      const topStackFrameCell = this.a(accessor, notebook);
      const focusHandle = topStackFrameCell ?? executingCells[0].cellHandle;
      const cell = context.notebookEditor.getCellByHandle(focusHandle);
      if (cell) {
        context.notebookEditor.focusNotebookCell(cell, "container");
      }
    }
  }
  a(accessor, notebook) {
    const debugService = accessor.get($0R);
    for (const session of debugService.getModel().getSessions()) {
      for (const thread of session.getAllThreads()) {
        const sf = thread.getTopStackFrame();
        if (sf) {
          const parsed = CellUri.parse(sf.source.uri);
          if (parsed && parsed.notebook.toString() === notebook.toString()) {
            return parsed.handle;
          }
        }
      }
    }
    return void 0;
  }
});
$hJ(class RevealLastFailedCellAction extends $FIb {
  constructor() {
    super({
      id: REVEAL_LAST_FAILED_CELL,
      title: localize(8291, null),
      tooltip: localize(8292, null),
      shortTitle: localize(8293, null),
      precondition: $8Ab,
      menu: [
        {
          id: $bJ.EditorTitle,
          when: $7m.and($SAb, $8Ab, $2Ab.toNegated(), $7m.notEquals("config.notebook.globalToolbar", true)),
          group: "navigation",
          order: 0
        },
        {
          id: $bJ.NotebookCellExecuteGoTo,
          when: $7m.and($SAb, $8Ab, $2Ab.toNegated(), $7m.equals("config.notebook.globalToolbar", true)),
          group: "navigation/execute",
          order: 20
        }
      ],
      icon: $PKb
    });
  }
  async runWithContext(accessor, context) {
    const notebookExecutionStateService = accessor.get($wL);
    const notebook = context.notebookEditor.textModel.uri;
    const lastFailedCellHandle = notebookExecutionStateService.getLastFailedCellForNotebook(notebook);
    if (lastFailedCellHandle !== void 0) {
      const lastFailedCell = context.notebookEditor.getCellByHandle(lastFailedCellHandle);
      if (lastFailedCell) {
        context.notebookEditor.focusNotebookCell(lastFailedCell, "container");
      }
    }
  }
});

// out-build/vs/workbench/contrib/outline/browser/outline.js
var OutlineSortOrder;
(function(OutlineSortOrder2) {
  OutlineSortOrder2[OutlineSortOrder2["ByPosition"] = 0] = "ByPosition";
  OutlineSortOrder2[OutlineSortOrder2["ByName"] = 1] = "ByName";
  OutlineSortOrder2[OutlineSortOrder2["ByKind"] = 2] = "ByKind";
})(OutlineSortOrder || (OutlineSortOrder = {}));
var IOutlinePane;
(function(IOutlinePane2) {
  IOutlinePane2.Id = "outline";
})(IOutlinePane || (IOutlinePane = {}));
var $JLb = new $nn("outlineFollowsCursor", false);
var $KLb = new $nn("outlineFiltersOnType", false);
var $LLb = new $nn(
  "outlineSortMode",
  0
  /* OutlineSortOrder.ByPosition */
);
var $MLb = new $nn("outlineAllCollapsed", false);
var $NLb = new $nn("outlineFocused", true);

// out-build/vs/workbench/contrib/notebook/browser/contrib/outline/notebookOutline.js
var NotebookOutlineTemplate = class {
  static {
    this.templateId = "NotebookOutlineRenderer";
  }
  constructor(container2, iconClass, iconLabel, decoration3, actionMenu, elementDisposables) {
    this.container = container2;
    this.iconClass = iconClass;
    this.iconLabel = iconLabel;
    this.decoration = decoration3;
    this.actionMenu = actionMenu;
    this.elementDisposables = elementDisposables;
  }
};
var NotebookOutlineRenderer = class NotebookOutlineRenderer2 {
  constructor(d, f, h3, j, k, l, m, n) {
    this.d = d;
    this.f = f;
    this.h = h3;
    this.j = j;
    this.k = k;
    this.l = l;
    this.m = m;
    this.n = n;
    this.templateId = NotebookOutlineTemplate.templateId;
  }
  renderTemplate(container2) {
    const elementDisposables = new $2c();
    container2.classList.add("notebook-outline-element", "show-file-icons");
    const iconClass = document.createElement("div");
    container2.append(iconClass);
    const iconLabel = new $T2(container2, { supportHighlights: true });
    const decoration3 = document.createElement("div");
    decoration3.className = "element-decoration";
    container2.append(decoration3);
    const actionMenu = document.createElement("div");
    actionMenu.className = "action-menu";
    container2.append(actionMenu);
    return new NotebookOutlineTemplate(container2, iconClass, iconLabel, decoration3, actionMenu, elementDisposables);
  }
  renderElement(node, _index, template, _height) {
    const extraClasses = [];
    const options3 = {
      matches: $Ul(node.filterData),
      labelEscapeNewLines: true,
      extraClasses
    };
    const isCodeCell = node.element.cell.cellKind === CellKind.Code;
    if (node.element.level >= 8) {
      template.iconClass.className = "element-icon " + ThemeIcon.asClassNameArray(node.element.icon).join(" ");
    } else if (isCodeCell && this.h.getFileIconTheme().hasFileIcons && !node.element.isExecuting) {
      template.iconClass.className = "";
      extraClasses.push(...$hdb(node.element.cell.language ?? ""));
    } else {
      template.iconClass.className = "element-icon " + ThemeIcon.asClassNameArray(node.element.icon).join(" ");
    }
    template.iconLabel.setLabel(" " + node.element.label, void 0, options3);
    const { markerInfo } = node.element;
    template.container.style.removeProperty("--outline-element-color");
    template.decoration.innerText = "";
    if (markerInfo) {
      const problem = this.j.getValue("problems.visibility");
      const useBadges = this.j.getValue(
        "outline.problems.badges"
        /* OutlineConfigKeys.problemsBadges */
      );
      if (!useBadges || !problem) {
        template.decoration.classList.remove("bubble");
        template.decoration.innerText = "";
      } else if (markerInfo.count === 0) {
        template.decoration.classList.add("bubble");
        template.decoration.innerText = "\uEA71";
      } else {
        template.decoration.classList.remove("bubble");
        template.decoration.innerText = markerInfo.count > 9 ? "9+" : String(markerInfo.count);
      }
      const color2 = this.h.getColorTheme().getColor(markerInfo.topSev === MarkerSeverity.Error ? $xr : $yr);
      if (problem === void 0) {
        return;
      }
      const useColors = this.j.getValue(
        "outline.problems.colors"
        /* OutlineConfigKeys.problemsColors */
      );
      if (!useColors || !problem) {
        template.container.style.removeProperty("--outline-element-color");
        template.decoration.style.setProperty("--outline-element-color", color2?.toString() ?? "inherit");
      } else {
        template.container.style.setProperty("--outline-element-color", color2?.toString() ?? "inherit");
      }
    }
    if (this.f === 1) {
      if (!this.d) {
        return;
      }
      const nbCell = node.element.cell;
      const nbViewModel = this.d.getViewModel();
      if (!nbViewModel) {
        return;
      }
      const idx = nbViewModel.getCellIndex(nbCell);
      const length = isCodeCell ? 0 : nbViewModel.getFoldedLength(idx);
      const scopedContextKeyService = template.elementDisposables.add(this.l.createScoped(template.container));
      $VLb.CellKind.bindTo(scopedContextKeyService).set(isCodeCell ? CellKind.Code : CellKind.Markup);
      $VLb.CellHasChildren.bindTo(scopedContextKeyService).set(length > 0);
      $VLb.CellHasHeader.bindTo(scopedContextKeyService).set(
        node.element.level !== 7
        /* NotebookOutlineConstants.NonHeaderOutlineLevel */
      );
      $VLb.OutlineElementTarget.bindTo(scopedContextKeyService).set(this.f);
      this.o(isCodeCell, nbViewModel, scopedContextKeyService, template, nbCell);
      const outlineEntryToolbar = template.elementDisposables.add(new $f3(template.actionMenu, this.k, {
        actionViewItemProvider: (action) => {
          if (action instanceof $fJ) {
            return this.n.createInstance($T$, action, void 0);
          }
          return void 0;
        }
      }));
      const menu = template.elementDisposables.add(this.m.createMenu($bJ.NotebookOutlineActionMenu, scopedContextKeyService));
      const actions = getOutlineToolbarActions(menu, { notebookEditor: this.d, outlineEntry: node.element });
      outlineEntryToolbar.setActions(actions.primary, actions.secondary);
      this.p(this.d, outlineEntryToolbar, menu, actions, node.element, template);
      template.actionMenu.style.padding = "0 0.8em 0 0.4em";
    }
  }
  disposeTemplate(templateData) {
    templateData.iconLabel.dispose();
    templateData.elementDisposables.clear();
  }
  disposeElement(element, index, templateData, height) {
    templateData.elementDisposables.clear();
    $$i(templateData.actionMenu);
  }
  o(isCodeCell, nbViewModel, scopedContextKeyService, template, nbCell) {
    const foldingState = isCodeCell ? 0 : nbCell.foldingState;
    const foldingStateCtx = $VLb.CellFoldingState.bindTo(scopedContextKeyService);
    foldingStateCtx.set(foldingState);
    if (!isCodeCell) {
      template.elementDisposables.add(nbViewModel.onDidFoldingStateChanged(() => {
        const foldingState2 = nbCell.foldingState;
        $VLb.CellFoldingState.bindTo(scopedContextKeyService).set(foldingState2);
        foldingStateCtx.set(foldingState2);
      }));
    }
  }
  p(editor, toolbar, menu, initActions, entry, templateData) {
    let dropdownIsVisible = false;
    let deferredUpdate;
    toolbar.setActions(initActions.primary, initActions.secondary);
    templateData.elementDisposables.add(menu.onDidChange(() => {
      if (dropdownIsVisible) {
        const actions2 = getOutlineToolbarActions(menu, { notebookEditor: editor, outlineEntry: entry });
        deferredUpdate = () => toolbar.setActions(actions2.primary, actions2.secondary);
        return;
      }
      const actions = getOutlineToolbarActions(menu, { notebookEditor: editor, outlineEntry: entry });
      toolbar.setActions(actions.primary, actions.secondary);
    }));
    templateData.container.classList.remove("notebook-outline-toolbar-dropdown-active");
    templateData.elementDisposables.add(toolbar.onDidChangeDropdownVisibility((visible) => {
      dropdownIsVisible = visible;
      if (visible) {
        templateData.container.classList.add("notebook-outline-toolbar-dropdown-active");
      } else {
        templateData.container.classList.remove("notebook-outline-toolbar-dropdown-active");
      }
      if (deferredUpdate && !visible) {
        $Xh(() => {
          deferredUpdate?.();
        }, 0, templateData.elementDisposables);
        deferredUpdate = void 0;
      }
    }));
  }
};
NotebookOutlineRenderer = __decorate([
  __param(2, $gs),
  __param(3, $kl),
  __param(4, $50),
  __param(5, $on),
  __param(6, $cJ),
  __param(7, $Pk)
], NotebookOutlineRenderer);
function getOutlineToolbarActions(menu, args2) {
  return $Q$(menu.getActions({ shouldForwardArgs: true, arg: args2 }), (g) => /^inline/.test(g));
}
var NotebookOutlineAccessibility = class {
  getAriaLabel(element) {
    return element.label;
  }
  getWidgetAriaLabel() {
    return "";
  }
};
var NotebookNavigationLabelProvider = class {
  getKeyboardNavigationLabel(element) {
    return element.label;
  }
};
var NotebookOutlineVirtualDelegate = class {
  getHeight(_element) {
    return 22;
  }
  getTemplateId(_element) {
    return NotebookOutlineTemplate.templateId;
  }
};
var $QLb = class $QLb2 {
  constructor(h3, j, k) {
    this.h = h3;
    this.j = j;
    this.k = k;
    this.d = new $2c();
    this.f = this.j.getValue($rM.gotoSymbolsAllSymbols);
    this.d.add(this.j.onDidChangeConfiguration((e) => {
      if (e.affectsConfiguration($rM.gotoSymbolsAllSymbols)) {
        this.f = this.j.getValue($rM.gotoSymbolsAllSymbols);
      }
    }));
  }
  getQuickPickElements() {
    const bucket = [];
    for (const entry of this.h?.object?.entries ?? []) {
      entry.asFlatList(bucket);
    }
    const result = [];
    const { hasFileIcons } = this.k.getFileIconTheme();
    const isSymbol = (element) => !!element.symbolKind;
    const isCodeCell = (element) => element.cell.cellKind === CellKind.Code && element.level === 7;
    for (let i2 = 0; i2 < bucket.length; i2++) {
      const element = bucket[i2];
      const nextElement = bucket[i2 + 1];
      if (!this.f && isSymbol(element)) {
        continue;
      }
      if (this.f && isCodeCell(element) && nextElement && isSymbol(nextElement)) {
        continue;
      }
      const useFileIcon = hasFileIcons && !element.symbolKind;
      result.push({
        element,
        label: useFileIcon ? element.label : `$(${element.icon.id}) ${element.label}`,
        ariaLabel: element.label,
        iconClasses: useFileIcon ? $hdb(element.cell.language ?? "") : void 0
      });
    }
    return result;
  }
  dispose() {
    this.d.dispose();
  }
};
$QLb = __decorate([
  __param(1, $kl),
  __param(2, $gs)
], $QLb);
var $RLb = class $RLb2 {
  constructor(k, l) {
    this.k = k;
    this.l = l;
    this.d = new $2c();
    this.f = this.l.getValue($rM.outlineShowCodeCells);
    this.h = this.l.getValue($rM.outlineShowCodeCellSymbols);
    this.j = this.l.getValue($rM.outlineShowMarkdownHeadersOnly);
    this.d.add(this.l.onDidChangeConfiguration((e) => {
      if (e.affectsConfiguration($rM.outlineShowCodeCells)) {
        this.f = this.l.getValue($rM.outlineShowCodeCells);
      }
      if (e.affectsConfiguration($rM.outlineShowCodeCellSymbols)) {
        this.h = this.l.getValue($rM.outlineShowCodeCellSymbols);
      }
      if (e.affectsConfiguration($rM.outlineShowMarkdownHeadersOnly)) {
        this.j = this.l.getValue($rM.outlineShowMarkdownHeadersOnly);
      }
    }));
  }
  getActiveEntry() {
    const newActive = this.k?.object?.activeElement;
    if (!newActive) {
      return void 0;
    }
    if (!this.m(newActive)) {
      return newActive;
    }
    let parent = newActive.parent;
    while (parent) {
      if (this.m(parent)) {
        parent = parent.parent;
      } else {
        return parent;
      }
    }
    return void 0;
  }
  /**
   * Checks if the given outline entry should be filtered out of the outlinePane
   *
   * @param entry the OutlineEntry to check
   * @returns true if the entry should be filtered out of the outlinePane
   */
  m(entry) {
    if (this.j && entry.cell.cellKind === CellKind.Markup && entry.level === 7 || // show headers only   + cell is mkdn + is level 7 (not header)
    !this.f && entry.cell.cellKind === CellKind.Code || // show code cells off + cell is code
    !this.h && entry.cell.cellKind === CellKind.Code && entry.level > 7) {
      return true;
    }
    return false;
  }
  *getChildren(element) {
    const isOutline = element instanceof $TLb;
    const entries2 = isOutline ? this.k?.object?.entries ?? [] : element.children;
    for (const entry of entries2) {
      if (entry.cell.cellKind === CellKind.Markup) {
        if (!this.j) {
          yield entry;
        } else if (entry.level < 7) {
          yield entry;
        }
      } else if (this.f && entry.cell.cellKind === CellKind.Code) {
        if (this.h) {
          yield entry;
        } else if (entry.level === 7) {
          yield entry;
        }
      }
    }
  }
  dispose() {
    this.d.dispose();
  }
};
$RLb = __decorate([
  __param(1, $kl)
], $RLb);
var $SLb = class $SLb2 {
  constructor(h3, j) {
    this.h = h3;
    this.j = j;
    this.d = new $2c();
    this.f = this.j.getValue($rM.breadcrumbsShowCodeCells);
    this.d.add(this.j.onDidChangeConfiguration((e) => {
      if (e.affectsConfiguration($rM.breadcrumbsShowCodeCells)) {
        this.f = this.j.getValue($rM.breadcrumbsShowCodeCells);
      }
    }));
  }
  getBreadcrumbElements() {
    const result = [];
    let candidate = this.h?.object?.activeElement;
    while (candidate) {
      if (this.f || candidate.cell.cellKind !== CellKind.Code) {
        result.unshift(candidate);
      }
      candidate = candidate.parent;
    }
    return result;
  }
  dispose() {
    this.d.dispose();
  }
};
$SLb = __decorate([
  __param(1, $kl)
], $SLb);
var NotebookComparator = class {
  constructor() {
    this.d = new $hj($Y, () => new Intl.Collator(void 0, { numeric: true }));
  }
  compareByPosition(a, b) {
    return a.index - b.index;
  }
  compareByType(a, b) {
    return a.cell.cellKind - b.cell.cellKind || this.d.value.compare(a.label, b.label);
  }
  compareByName(a, b) {
    return this.d.value.compare(a.label, b.label);
  }
};
var $TLb = class $TLb2 {
  // getters
  get activeElement() {
    this.s();
    if (this.u === 1) {
      return this.config.treeDataSource.getActiveEntry();
    } else {
      console.error("activeElement should not be called outside of the OutlinePane");
      return void 0;
    }
  }
  get entries() {
    this.s();
    return this.n?.object?.entries ?? [];
  }
  get uri() {
    return this.n?.object?.uri;
  }
  get isEmpty() {
    return this.n?.object?.isEmpty ?? true;
  }
  s() {
    if (this.k.isTriggered()) {
      this.k.cancel();
      this.G();
    }
  }
  constructor(t, u, v, w, x, y, z, A) {
    this.t = t;
    this.u = u;
    this.v = v;
    this.w = w;
    this.x = x;
    this.y = y;
    this.z = z;
    this.A = A;
    this.outlineKind = "notebookCells";
    this.d = new $2c();
    this.f = new $2c();
    this.h = new $2c();
    this.j = new $ze();
    this.onDidChange = this.j.event;
    this.k = this.d.add(new $Sh(300));
    this.l = this.d.add(new $Sh(200));
    this.m = this.d.add(new $Sh(2e3));
    this.r = this.y.getValue($rM.outlineShowCodeCellSymbols);
    this.B();
    const delegate = new NotebookOutlineVirtualDelegate();
    const renderers = [this.x.createInstance(NotebookOutlineRenderer, this.t.getControl(), this.u)];
    const comparator = new NotebookComparator();
    const options3 = {
      collapseByDefault: this.u === 2 || this.u === 1 && this.y.getValue(
        "outline.collapseItems"
        /* OutlineConfigKeys.collapseItems */
      ) === "alwaysCollapse",
      expandOnlyOnTwistieClick: true,
      multipleSelectionSupport: false,
      accessibilityProvider: new NotebookOutlineAccessibility(),
      identityProvider: { getId: (element) => element.cell.uri.toString() },
      keyboardNavigationLabelProvider: new NotebookNavigationLabelProvider()
    };
    this.config = {
      treeDataSource: this.o,
      quickPickDataSource: this.p,
      breadcrumbsDataSource: this.q,
      delegate,
      renderers,
      comparator,
      options: options3
    };
  }
  B() {
    this.C();
    this.D();
    this.d.add(this.t.onDidChangeModel(() => {
      this.C();
      this.D();
      this.E();
    }));
    this.d.add(this.z.documentSymbolProvider.onDidChange(() => {
      this.F();
    }));
    this.d.add(this.t.onDidChangeSelection(() => {
      this.J();
    }));
    this.d.add(this.y.onDidChangeConfiguration((e) => {
      if (e.affectsConfiguration($rM.outlineShowMarkdownHeadersOnly) || e.affectsConfiguration($rM.outlineShowCodeCells) || e.affectsConfiguration($rM.outlineShowCodeCellSymbols) || e.affectsConfiguration($rM.breadcrumbsShowCodeCells)) {
        this.H();
      }
    }));
    this.d.add(this.A.onDidChangeExecution((e) => {
      if (e.type === NotebookExecutionType.cell && !!this.t.textModel && e.affectsNotebook(this.t.textModel?.uri)) {
        this.H();
      }
    }));
    this.d.add(this.y.onDidChangeConfiguration((e) => {
      if (e.affectsConfiguration($rM.outlineShowCodeCellSymbols)) {
        this.r = this.y.getValue($rM.outlineShowCodeCellSymbols);
        this.E();
      }
    }));
    this.d.add(this.v.onDidFileIconThemeChange(() => {
      this.j.fire({});
    }));
    this.G();
  }
  /**
   * set up the primary data source + three viewing sources for the various outline views
   */
  C() {
    const notebookEditor = this.t.getControl();
    this.n?.dispose();
    this.h.clear();
    if (!notebookEditor?.hasModel()) {
      this.n = void 0;
    } else {
      this.n = this.h.add(this.x.invokeFunction((accessor) => accessor.get($OLb).getOrCreate(notebookEditor)));
      this.h.add(this.n.object.onDidChange(() => {
        this.j.fire({});
      }));
    }
    this.o = this.h.add(this.x.createInstance($RLb, this.n));
    this.p = this.h.add(this.x.createInstance($QLb, this.n));
    this.q = this.h.add(this.x.createInstance($SLb, this.n));
  }
  /**
   * set up the listeners for the outline content, these respond to model changes in the notebook
   */
  D() {
    this.f.clear();
    if (!this.t.textModel) {
      return;
    }
    if (!this.entries.length) {
      this.E();
    }
    this.f.add(this.t.textModel.onDidChangeContent((contentChanges) => {
      if (contentChanges.rawEvents.some((c) => c.kind === NotebookCellsChangeType.ChangeCellContent || c.kind === NotebookCellsChangeType.ChangeCellInternalMetadata || c.kind === NotebookCellsChangeType.Move || c.kind === NotebookCellsChangeType.ModelChange)) {
        this.H();
      }
    }));
  }
  async E(cancelToken = CancellationToken.None) {
    if (this.u === 1 && this.r) {
      void this.doComputeSymbols(cancelToken);
    }
  }
  async doComputeSymbols(cancelToken) {
    await this.n?.object?.computeFullSymbols(cancelToken);
  }
  async F() {
    this.k.cancel();
    this.l.cancel();
    this.m.trigger(() => {
      this.E();
    });
  }
  G() {
    this.n?.object?.recomputeState();
  }
  H() {
    this.l.cancel();
    this.k.trigger(() => {
      this.G();
    });
  }
  I() {
    this.n?.object?.recomputeActive();
  }
  J() {
    this.l.trigger(() => {
      this.I();
    });
  }
  async reveal(entry, options3, sideBySide) {
    const notebookEditorOptions = {
      ...options3,
      override: this.t.input?.editorId,
      cellRevealType: 5,
      selection: entry.position,
      viewState: void 0
    };
    await this.w.openEditor({
      resource: entry.cell.uri,
      options: notebookEditorOptions
    }, sideBySide ? $oJ : void 0);
  }
  preview(entry) {
    const widget = this.t.getControl();
    if (!widget) {
      return $3c.None;
    }
    if (entry.range) {
      const range = $9C.lift(entry.range);
      widget.revealRangeInCenterIfOutsideViewportAsync(entry.cell, range);
    } else {
      widget.revealInCenterIfOutsideViewport(entry.cell);
    }
    const ids = widget.deltaCellDecorations([], [{
      handle: entry.cell.handle,
      options: { className: "nb-symbolHighlight", outputClassName: "nb-symbolHighlight" }
    }]);
    let editorDecorations;
    widget.changeModelDecorations((accessor) => {
      if (entry.range) {
        const decorations = [
          {
            range: entry.range,
            options: {
              description: "document-symbols-outline-range-highlight",
              className: "rangeHighlight",
              isWholeLine: true
            }
          }
        ];
        const deltaDecoration = {
          ownerId: entry.cell.handle,
          decorations
        };
        editorDecorations = accessor.deltaDecorations([], [deltaDecoration]);
      }
    });
    return $1c(() => {
      widget.deltaCellDecorations(ids, []);
      if (editorDecorations?.length) {
        widget.changeModelDecorations((accessor) => {
          accessor.deltaDecorations(editorDecorations, []);
        });
      }
    });
  }
  captureViewState() {
    const widget = this.t.getControl();
    const viewState = widget?.getEditorViewState();
    return $1c(() => {
      if (viewState) {
        widget?.restoreListViewState(viewState);
      }
    });
  }
  dispose() {
    this.j.dispose();
    this.d.dispose();
    this.f.dispose();
    this.h.dispose();
    this.n?.dispose();
  }
};
$TLb = __decorate([
  __param(2, $gs),
  __param(3, $mJ),
  __param(4, $Pk),
  __param(5, $kl),
  __param(6, $mP),
  __param(7, $wL)
], $TLb);
var $ULb = class $ULb2 {
  constructor(outlineService, d) {
    this.d = d;
    const reg2 = outlineService.registerOutlineCreator(this);
    this.dispose = () => reg2.dispose();
  }
  matches(candidate) {
    return candidate.getId() === $ILb.ID;
  }
  async createOutline(editor, target, cancelToken) {
    const outline = this.d.createInstance($TLb, editor, target);
    if (target === 4) {
      await outline.doComputeSymbols(cancelToken);
    }
    return outline;
  }
};
$ULb = __decorate([
  __param(0, $vyb),
  __param(1, $Pk)
], $ULb);
var $VLb = {
  CellKind: new $nn("notebookCellKind", void 0),
  CellHasChildren: new $nn("notebookCellHasChildren", false),
  CellHasHeader: new $nn("notebookCellHasHeader", false),
  CellFoldingState: new $nn(
    "notebookCellFoldingState",
    0
    /* CellFoldingState.None */
  ),
  OutlineElementTarget: new $nn("notebookOutlineElementTarget", void 0)
};
$Wn.as(Extensions2.Workbench).registerWorkbenchContribution(
  $ULb,
  4
  /* LifecyclePhase.Eventually */
);
$Wn.as($Ht.Configuration).registerConfiguration({
  id: "notebook",
  order: 100,
  type: "object",
  "properties": {
    [$rM.outlineShowMarkdownHeadersOnly]: {
      type: "boolean",
      default: true,
      markdownDescription: localize(8181, null)
    },
    [$rM.outlineShowCodeCells]: {
      type: "boolean",
      default: false,
      markdownDescription: localize(8182, null)
    },
    [$rM.outlineShowCodeCellSymbols]: {
      type: "boolean",
      default: true,
      markdownDescription: localize(8183, null)
    },
    [$rM.breadcrumbsShowCodeCells]: {
      type: "boolean",
      default: true,
      markdownDescription: localize(8184, null)
    },
    [$rM.gotoSymbolsAllSymbols]: {
      type: "boolean",
      default: true,
      markdownDescription: localize(8185, null)
    }
  }
});
$dJ.appendMenuItem($bJ.ViewTitle, {
  submenu: $bJ.NotebookOutlineFilter,
  title: localize(8186, null),
  icon: $6l.filter,
  group: "navigation",
  order: -1,
  when: $7m.and($7m.equals("view", IOutlinePane.Id), $SAb)
});
$hJ(class ToggleShowMarkdownHeadersOnly extends $gJ {
  constructor() {
    super({
      id: "notebook.outline.toggleShowMarkdownHeadersOnly",
      title: localize(8187, null),
      f1: false,
      toggled: {
        condition: $7m.equals("config.notebook.outline.showMarkdownHeadersOnly", true)
      },
      menu: {
        id: $bJ.NotebookOutlineFilter,
        group: "0_markdown_cells"
      }
    });
  }
  run(accessor, ...args2) {
    const configurationService = accessor.get($kl);
    const showMarkdownHeadersOnly = configurationService.getValue($rM.outlineShowMarkdownHeadersOnly);
    configurationService.updateValue($rM.outlineShowMarkdownHeadersOnly, !showMarkdownHeadersOnly);
  }
});
$hJ(class ToggleCodeCellEntries extends $gJ {
  constructor() {
    super({
      id: "notebook.outline.toggleCodeCells",
      title: localize(8188, null),
      f1: false,
      toggled: {
        condition: $7m.equals("config.notebook.outline.showCodeCells", true)
      },
      menu: {
        id: $bJ.NotebookOutlineFilter,
        order: 1,
        group: "1_code_cells"
      }
    });
  }
  run(accessor, ...args2) {
    const configurationService = accessor.get($kl);
    const showCodeCells = configurationService.getValue($rM.outlineShowCodeCells);
    configurationService.updateValue($rM.outlineShowCodeCells, !showCodeCells);
  }
});
$hJ(class ToggleCodeCellSymbolEntries extends $gJ {
  constructor() {
    super({
      id: "notebook.outline.toggleCodeCellSymbols",
      title: localize(8189, null),
      f1: false,
      toggled: {
        condition: $7m.equals("config.notebook.outline.showCodeCellSymbols", true)
      },
      menu: {
        id: $bJ.NotebookOutlineFilter,
        order: 2,
        group: "1_code_cells"
      }
    });
  }
  run(accessor, ...args2) {
    const configurationService = accessor.get($kl);
    const showCodeCellSymbols = configurationService.getValue($rM.outlineShowCodeCellSymbols);
    configurationService.updateValue($rM.outlineShowCodeCellSymbols, !showCodeCellSymbols);
  }
});

// out-build/vs/workbench/contrib/notebook/browser/controller/sectionActions.js
var $ZLb = class extends $gJ {
  constructor() {
    super({
      id: "notebook.section.runSingleCell",
      title: {
        ...localize2(8355, "Run Cell"),
        mnemonicTitle: localize(8347, null)
      },
      shortTitle: localize(8348, null),
      icon: $CKb,
      menu: [
        {
          id: $bJ.NotebookOutlineActionMenu,
          group: "inline",
          order: 1,
          when: $7m.and($VLb.CellKind.isEqualTo(CellKind.Code), $VLb.OutlineElementTarget.isEqualTo(
            1
            /* OutlineTarget.OutlinePane */
          ), $VLb.CellHasChildren.toNegated(), $VLb.CellHasHeader.toNegated())
        }
      ]
    });
  }
  async run(_accessor, context) {
    if (!checkOutlineEntryContext(context)) {
      return;
    }
    context.notebookEditor.executeNotebookCells([context.outlineEntry.cell]);
  }
};
var $1Lb = class extends $gJ {
  constructor() {
    super({
      id: "notebook.section.runCells",
      title: {
        ...localize2(8356, "Run Cells In Section"),
        mnemonicTitle: localize(8349, null)
      },
      shortTitle: localize(8350, null),
      icon: $CKb,
      // TODO @Yoyokrazy replace this with new icon later
      menu: [
        {
          id: $bJ.NotebookStickyScrollContext,
          group: "notebookExecution",
          order: 1
        },
        {
          id: $bJ.NotebookOutlineActionMenu,
          group: "inline",
          order: 1,
          when: $7m.and($VLb.CellKind.isEqualTo(CellKind.Markup), $VLb.OutlineElementTarget.isEqualTo(
            1
            /* OutlineTarget.OutlinePane */
          ), $VLb.CellHasChildren, $VLb.CellHasHeader)
        },
        {
          id: $bJ.NotebookCellTitle,
          order: 0,
          group: $yIb,
          when: $YLb
        }
      ]
    });
  }
  async run(_accessor, context) {
    let cell;
    if (checkOutlineEntryContext(context)) {
      cell = context.outlineEntry.cell;
    } else if (checkNotebookCellContext(context)) {
      cell = context.cell;
    } else {
      return;
    }
    if (cell.getEditState() === CellEditState.Editing) {
      const foldingController = context.notebookEditor.getContribution($iLb.id);
      foldingController.recompute();
    }
    const cellIdx = context.notebookEditor.getViewModel()?.getCellIndex(cell);
    if (cellIdx === void 0) {
      return;
    }
    const sectionIdx = context.notebookEditor.getViewModel()?.getFoldingStartIndex(cellIdx);
    if (sectionIdx === void 0) {
      return;
    }
    const length = context.notebookEditor.getViewModel()?.getFoldedLength(sectionIdx);
    if (length === void 0) {
      return;
    }
    const cells = context.notebookEditor.getCellsInRange({ start: sectionIdx, end: sectionIdx + length + 1 });
    context.notebookEditor.executeNotebookCells(cells);
  }
};
var $2Lb = class extends $gJ {
  constructor() {
    super({
      id: "notebook.section.foldSection",
      title: {
        ...localize2(8357, "Fold Section"),
        mnemonicTitle: localize(8351, null)
      },
      shortTitle: localize(8352, null),
      menu: [
        {
          id: $bJ.NotebookOutlineActionMenu,
          group: "notebookFolding",
          order: 2,
          when: $7m.and($VLb.CellKind.isEqualTo(CellKind.Markup), $VLb.OutlineElementTarget.isEqualTo(
            1
            /* OutlineTarget.OutlinePane */
          ), $VLb.CellHasChildren, $VLb.CellHasHeader, $VLb.CellFoldingState.isEqualTo(
            1
            /* CellFoldingState.Expanded */
          ))
        }
      ]
    });
  }
  async run(_accessor, context) {
    if (!checkOutlineEntryContext(context)) {
      return;
    }
    this.a(context.outlineEntry, context.notebookEditor);
  }
  a(entry, notebookEditor) {
    const foldingController = notebookEditor.getContribution($iLb.id);
    const index = entry.index;
    const headerLevel = entry.level;
    const newFoldingState = 2;
    foldingController.setFoldingStateDown(index, newFoldingState, headerLevel);
  }
};
var $3Lb = class extends $gJ {
  constructor() {
    super({
      id: "notebook.section.expandSection",
      title: {
        ...localize2(8358, "Expand Section"),
        mnemonicTitle: localize(8353, null)
      },
      shortTitle: localize(8354, null),
      menu: [
        {
          id: $bJ.NotebookOutlineActionMenu,
          group: "notebookFolding",
          order: 2,
          when: $7m.and($VLb.CellKind.isEqualTo(CellKind.Markup), $VLb.OutlineElementTarget.isEqualTo(
            1
            /* OutlineTarget.OutlinePane */
          ), $VLb.CellHasChildren, $VLb.CellHasHeader, $VLb.CellFoldingState.isEqualTo(
            2
            /* CellFoldingState.Collapsed */
          ))
        }
      ]
    });
  }
  async run(_accessor, context) {
    if (!checkOutlineEntryContext(context)) {
      return;
    }
    this.a(context.outlineEntry, context.notebookEditor);
  }
  a(entry, notebookEditor) {
    const foldingController = notebookEditor.getContribution($iLb.id);
    const index = entry.index;
    const headerLevel = entry.level;
    const newFoldingState = 1;
    foldingController.setFoldingStateDown(index, newFoldingState, headerLevel);
  }
};
function checkOutlineEntryContext(context) {
  return !!(context && context.notebookEditor && context.outlineEntry);
}
function checkNotebookCellContext(context) {
  return !!(context && context.notebookEditor && context.cell);
}
$hJ($ZLb);
$hJ($1Lb);
$hJ($2Lb);
$hJ($3Lb);

// out-build/vs/workbench/contrib/notebook/browser/controller/layoutActions.js
$hJ(class NotebookConfigureLayoutAction extends $gJ {
  constructor() {
    super({
      id: "workbench.notebook.layout.select",
      title: localize2(8330, "Select between Notebook Layouts"),
      f1: true,
      precondition: $7m.equals(`config.${$rM.openGettingStarted}`, true),
      category: $xIb,
      menu: [
        {
          id: $bJ.EditorTitle,
          group: "notebookLayout",
          when: $7m.and($SAb, $7m.notEquals("config.notebook.globalToolbar", true), $7m.equals(`config.${$rM.openGettingStarted}`, true)),
          order: 0
        },
        {
          id: $bJ.NotebookToolbar,
          group: "notebookLayout",
          when: $7m.and($7m.equals("config.notebook.globalToolbar", true), $7m.equals(`config.${$rM.openGettingStarted}`, true)),
          order: 0
        }
      ]
    });
  }
  run(accessor) {
    accessor.get($sn).executeCommand("workbench.action.openWalkthrough", { category: "notebooks", step: "notebookProfile" }, true);
  }
});
$hJ(class NotebookConfigureLayoutAction2 extends $gJ {
  constructor() {
    super({
      id: "workbench.notebook.layout.configure",
      title: localize2(8331, "Customize Notebook Layout"),
      f1: true,
      category: $xIb,
      menu: [
        {
          id: $bJ.NotebookToolbar,
          group: "notebookLayout",
          when: $7m.equals("config.notebook.globalToolbar", true),
          order: 1
        }
      ]
    });
  }
  run(accessor) {
    accessor.get($TK).openSettings({ jsonEditor: false, query: "@tag:notebookLayout" });
  }
});
$hJ(class NotebookConfigureLayoutFromEditorTitle extends $gJ {
  constructor() {
    super({
      id: "workbench.notebook.layout.configure.editorTitle",
      title: localize2(8332, "Customize Notebook Layout"),
      f1: false,
      category: $xIb,
      menu: [
        {
          id: $bJ.NotebookEditorLayoutConfigure,
          group: "notebookLayout",
          when: $SAb,
          order: 1
        }
      ]
    });
  }
  run(accessor) {
    accessor.get($TK).openSettings({ jsonEditor: false, query: "@tag:notebookLayout" });
  }
});
$dJ.appendMenuItem($bJ.EditorTitle, {
  submenu: $bJ.NotebookEditorLayoutConfigure,
  rememberDefaultAction: false,
  title: localize2(8333, "Customize Notebook..."),
  icon: $6l.gear,
  group: "navigation",
  order: -1,
  when: $SAb
});
$hJ(class ToggleLineNumberFromEditorTitle extends $gJ {
  constructor() {
    super({
      id: "notebook.toggleLineNumbersFromEditorTitle",
      title: localize2(8334, "Toggle Notebook Line Numbers"),
      precondition: $WAb,
      menu: [
        {
          id: $bJ.NotebookEditorLayoutConfigure,
          group: "notebookLayoutDetails",
          order: 1,
          when: $SAb
        }
      ],
      category: $xIb,
      f1: true,
      toggled: {
        condition: $7m.notEquals("config.notebook.lineNumbers", "off"),
        title: localize(8323, null)
      }
    });
  }
  async run(accessor) {
    return accessor.get($sn).executeCommand("notebook.toggleLineNumbers");
  }
});
$hJ(class ToggleCellToolbarPositionFromEditorTitle extends $gJ {
  constructor() {
    super({
      id: "notebook.toggleCellToolbarPositionFromEditorTitle",
      title: localize2(8335, "Toggle Cell Toolbar Position"),
      menu: [{
        id: $bJ.NotebookEditorLayoutConfigure,
        group: "notebookLayoutDetails",
        order: 3
      }],
      category: $xIb,
      f1: false
    });
  }
  async run(accessor, ...args2) {
    return accessor.get($sn).executeCommand("notebook.toggleCellToolbarPosition", ...args2);
  }
});
$hJ(class ToggleBreadcrumbFromEditorTitle extends $gJ {
  constructor() {
    super({
      id: "breadcrumbs.toggleFromEditorTitle",
      title: localize2(8336, "Toggle Breadcrumbs"),
      menu: [{
        id: $bJ.NotebookEditorLayoutConfigure,
        group: "notebookLayoutDetails",
        order: 2
      }],
      f1: false
    });
  }
  async run(accessor) {
    return accessor.get($sn).executeCommand("breadcrumbs.toggle");
  }
});
$hJ(class SaveMimeTypeDisplayOrder extends $gJ {
  constructor() {
    super({
      id: "notebook.saveMimeTypeOrder",
      title: localize2(8337, "Save Mimetype Display Order"),
      f1: true,
      category: $xIb,
      precondition: $SAb
    });
  }
  run(accessor) {
    const service = accessor.get($mrb);
    const disposables = new $2c();
    const qp = disposables.add(accessor.get($1M).createQuickPick());
    qp.placeholder = localize(8324, null);
    qp.items = [
      { target: 2, label: localize(8325, null) },
      { target: 5, label: localize(8326, null) }
    ];
    disposables.add(qp.onDidAccept(() => {
      const target = qp.selectedItems[0]?.target;
      if (target !== void 0) {
        service.saveMimeDisplayOrder(target);
      }
      qp.dispose();
    }));
    disposables.add(qp.onDidHide(() => disposables.dispose()));
    qp.show();
  }
});
$hJ(class NotebookWebviewResetAction extends $gJ {
  constructor() {
    super({
      id: "workbench.notebook.layout.webview.reset",
      title: localize2(8338, "Reset Notebook Webview"),
      f1: false,
      category: $xIb
    });
  }
  run(accessor, args2) {
    const editorService = accessor.get($mJ);
    if (args2) {
      const uri = URI.revive(args2);
      const notebookEditorService = accessor.get($yMb);
      const widgets2 = notebookEditorService.listNotebookEditors().filter((widget) => widget.hasModel() && widget.textModel.uri.toString() === uri.toString());
      for (const widget of widgets2) {
        if (widget.hasModel()) {
          widget.getInnerWebview()?.reload();
        }
      }
    } else {
      const editor = $Qrb(editorService.activeEditorPane);
      if (!editor) {
        return;
      }
      editor.getInnerWebview()?.reload();
    }
  }
});
$hJ(class ToggleNotebookStickyScroll extends $gJ {
  constructor() {
    super({
      id: "notebook.action.toggleNotebookStickyScroll",
      title: {
        ...localize2(8339, "Toggle Notebook Sticky Scroll"),
        mnemonicTitle: localize(8327, null)
      },
      category: $qn.View,
      toggled: {
        condition: $7m.equals("config.notebook.stickyScroll.enabled", true),
        title: localize(8328, null),
        mnemonicTitle: localize(8329, null)
      },
      menu: [
        { id: $bJ.CommandPalette },
        {
          id: $bJ.NotebookStickyScrollContext,
          group: "notebookView",
          order: 2
        }
      ]
    });
  }
  async run(accessor) {
    const configurationService = accessor.get($kl);
    const newValue = !configurationService.getValue("notebook.stickyScroll.enabled");
    return configurationService.updateValue("notebook.stickyScroll.enabled", newValue);
  }
});

// out-build/vs/workbench/contrib/notebook/browser/controller/notebookIndentationActions.js
var $L2b = class _$L2b extends $gJ {
  static {
    this.ID = "notebook.action.indentUsingTabs";
  }
  constructor() {
    super({
      id: _$L2b.ID,
      title: localize(8340, null),
      precondition: void 0
    });
  }
  run(accessor, ...args2) {
    changeNotebookIndentation(accessor, false, false);
  }
};
var $M2b = class _$M2b extends $gJ {
  static {
    this.ID = "notebook.action.indentUsingSpaces";
  }
  constructor() {
    super({
      id: _$M2b.ID,
      title: localize(8341, null),
      precondition: void 0
    });
  }
  run(accessor, ...args2) {
    changeNotebookIndentation(accessor, true, false);
  }
};
var $N2b = class _$N2b extends $gJ {
  static {
    this.ID = "notebook.action.changeTabDisplaySize";
  }
  constructor() {
    super({
      id: _$N2b.ID,
      title: localize(8342, null),
      precondition: void 0
    });
  }
  run(accessor, ...args2) {
    changeNotebookIndentation(accessor, true, true);
  }
};
var $O2b = class _$O2b extends $gJ {
  static {
    this.ID = "notebook.action.convertIndentationToSpaces";
  }
  constructor() {
    super({
      id: _$O2b.ID,
      title: localize(8343, null),
      precondition: void 0
    });
  }
  run(accessor, ...args2) {
    convertNotebookIndentation(accessor, true);
  }
};
var $P2b = class _$P2b extends $gJ {
  static {
    this.ID = "notebook.action.convertIndentationToTabs";
  }
  constructor() {
    super({
      id: _$P2b.ID,
      title: localize(8344, null),
      precondition: void 0
    });
  }
  run(accessor, ...args2) {
    convertNotebookIndentation(accessor, false);
  }
};
function changeNotebookIndentation(accessor, insertSpaces, displaySizeOnly) {
  const editorService = accessor.get($mJ);
  const configurationService = accessor.get($kl);
  const notebookEditorService = accessor.get($yMb);
  const quickInputService = accessor.get($1M);
  const activeInput = editorService.activeEditorPane?.input;
  const isNotebook = $vrb(activeInput);
  if (!isNotebook) {
    return;
  }
  const notebookEditor = notebookEditorService.retrieveExistingWidgetFromURI(activeInput.resource)?.value;
  if (!notebookEditor) {
    return;
  }
  const picks = [1, 2, 3, 4, 5, 6, 7, 8].map((n) => ({
    id: n.toString(),
    label: n.toString()
  }));
  const initialConfig = configurationService.getValue($rM.cellEditorOptionsCustomizations);
  const initialInsertSpaces = initialConfig["editor.insertSpaces"];
  delete initialConfig["editor.indentSize"];
  delete initialConfig["editor.tabSize"];
  delete initialConfig["editor.insertSpaces"];
  setTimeout(
    () => {
      quickInputService.pick(picks, { placeHolder: localize(8345, null) }).then((pick) => {
        if (pick) {
          const pickedVal = parseInt(pick.label, 10);
          if (displaySizeOnly) {
            configurationService.updateValue($rM.cellEditorOptionsCustomizations, {
              ...initialConfig,
              "editor.tabSize": pickedVal,
              "editor.indentSize": pickedVal,
              "editor.insertSpaces": initialInsertSpaces
            });
          } else {
            configurationService.updateValue($rM.cellEditorOptionsCustomizations, {
              ...initialConfig,
              "editor.tabSize": pickedVal,
              "editor.indentSize": pickedVal,
              "editor.insertSpaces": insertSpaces
            });
          }
        }
      });
    },
    50
    /* quick input is sensitive to being opened so soon after another */
  );
}
function convertNotebookIndentation(accessor, tabsToSpaces) {
  const editorService = accessor.get($mJ);
  const configurationService = accessor.get($kl);
  const logService = accessor.get($wn);
  const textModelService = accessor.get($oG);
  const notebookEditorService = accessor.get($yMb);
  const bulkEditService = accessor.get($H_);
  const activeInput = editorService.activeEditorPane?.input;
  const isNotebook = $vrb(activeInput);
  if (!isNotebook) {
    return;
  }
  const notebookTextModel = notebookEditorService.retrieveExistingWidgetFromURI(activeInput.resource)?.value?.textModel;
  if (!notebookTextModel) {
    return;
  }
  const disposable = new $2c();
  try {
    Promise.all(notebookTextModel.cells.map(async (cell) => {
      const ref = await textModelService.createModelReference(cell.uri);
      disposable.add(ref);
      const textEditorModel = ref.object.textEditorModel;
      const modelOpts = cell.textModel?.getOptions();
      if (!modelOpts) {
        return;
      }
      const edits = getIndentationEditOperations2(textEditorModel, modelOpts.tabSize, tabsToSpaces);
      bulkEditService.apply(edits, { label: localize(8346, null), code: "undoredo.convertIndentation" });
    })).then(() => {
      const initialConfig = configurationService.getValue($rM.cellEditorOptionsCustomizations);
      const initialIndentSize = initialConfig["editor.indentSize"];
      const initialTabSize = initialConfig["editor.tabSize"];
      delete initialConfig["editor.indentSize"];
      delete initialConfig["editor.tabSize"];
      delete initialConfig["editor.insertSpaces"];
      configurationService.updateValue($rM.cellEditorOptionsCustomizations, {
        ...initialConfig,
        "editor.tabSize": initialTabSize,
        "editor.indentSize": initialIndentSize,
        "editor.insertSpaces": tabsToSpaces
      });
      disposable.dispose();
    });
  } catch {
    logService.error("Failed to convert indentation to spaces for notebook cells.");
  }
}
function getIndentationEditOperations2(model, tabSize, tabsToSpaces) {
  if (model.getLineCount() === 1 && model.getLineMaxColumn(1) === 1) {
    return [];
  }
  let spaces2 = "";
  for (let i2 = 0; i2 < tabSize; i2++) {
    spaces2 += " ";
  }
  const spacesRegExp = new RegExp(spaces2, "gi");
  const edits = [];
  for (let lineNumber = 1, lineCount = model.getLineCount(); lineNumber <= lineCount; lineNumber++) {
    let lastIndentationColumn = model.getLineFirstNonWhitespaceColumn(lineNumber);
    if (lastIndentationColumn === 0) {
      lastIndentationColumn = model.getLineMaxColumn(lineNumber);
    }
    if (lastIndentationColumn === 1) {
      continue;
    }
    const originalIndentationRange = new $9C(lineNumber, 1, lineNumber, lastIndentationColumn);
    const originalIndentation = model.getValueInRange(originalIndentationRange);
    const newIndentation = tabsToSpaces ? originalIndentation.replace(/\t/ig, spaces2) : originalIndentation.replace(spacesRegExp, "	");
    edits.push(new $J_(model.uri, { range: originalIndentationRange, text: newIndentation }));
  }
  return edits;
}
$hJ($M2b);
$hJ($L2b);
$hJ($N2b);
$hJ($O2b);
$hJ($P2b);

// out-build/vs/workbench/contrib/notebook/browser/controller/editActions.js
var CLEAR_ALL_CELLS_OUTPUTS_COMMAND_ID = "notebook.clearAllCellsOutputs";
var EDIT_CELL_COMMAND_ID = "notebook.cell.edit";
var DELETE_CELL_COMMAND_ID = "notebook.cell.delete";
var $Q2b = "notebook.cell.clearOutputs";
var $R2b = "notebook.selectIndentation";
var $S2b = "notebook.commentSelectedCells";
$hJ(class EditCellAction extends $HIb {
  constructor() {
    super({
      id: EDIT_CELL_COMMAND_ID,
      title: localize(8250, null),
      keybinding: {
        when: $7m.and($XAb, $7m.not($Beb), EditorContextKeys.hoverFocused.toNegated(), $ZAb.toNegated()),
        primary: 3,
        weight: 200
        /* KeybindingWeight.WorkbenchContrib */
      },
      menu: {
        id: $bJ.NotebookCellTitle,
        when: $7m.and($1Ab.isEqualTo(true), $0Ab.isEqualTo("markup"), $bBb.toNegated(), $$Ab),
        order: 1,
        group: $yIb
      },
      icon: $IKb
    });
  }
  async runWithContext(accessor, context) {
    if (!context.notebookEditor.hasModel()) {
      return;
    }
    await context.notebookEditor.focusNotebookCell(context.cell, "editor");
    const foundEditor = context.cell ? $EIb(context, context.cell) : void 0;
    if (foundEditor && foundEditor.hasTextFocus() && $cHb.get(foundEditor)?.getWidgetPosition()?.lineNumber === foundEditor.getPosition()?.lineNumber) {
      $cHb.get(foundEditor)?.focus();
    }
  }
});
var quitEditCondition = $7m.and($WAb, $Ceb, $aAb.toNegated());
$hJ(class QuitEditCellAction extends $HIb {
  constructor() {
    super({
      id: $Krb,
      title: localize(8251, null),
      menu: {
        id: $bJ.NotebookCellTitle,
        when: $7m.and($0Ab.isEqualTo("markup"), $bBb, $$Ab),
        order: 4,
        group: $yIb
      },
      icon: $JKb,
      keybinding: [
        {
          when: $7m.and(quitEditCondition, EditorContextKeys.hoverVisible.toNegated(), EditorContextKeys.hasNonEmptySelection.toNegated(), EditorContextKeys.hasMultipleSelections.toNegated()),
          primary: 9,
          weight: $AIb - 5
        },
        {
          when: $7m.and($WAb, $YAb),
          primary: 9,
          weight: 200 + 5
        },
        {
          when: $7m.and(quitEditCondition, $0Ab.isEqualTo("markup")),
          primary: 256 | 3,
          win: {
            primary: 2048 | 512 | 3
            /* KeyCode.Enter */
          },
          weight: $AIb - 5
        }
      ]
    });
  }
  async runWithContext(accessor, context) {
    if (context.cell.cellKind === CellKind.Markup) {
      context.cell.updateEditState(CellEditState.Preview, $Krb);
    }
    await context.notebookEditor.focusNotebookCell(context.cell, "container", { skipReveal: true });
  }
});
$hJ(class DeleteCellAction extends $HIb {
  constructor() {
    super({
      id: DELETE_CELL_COMMAND_ID,
      title: localize(8252, null),
      keybinding: {
        primary: 20,
        mac: {
          primary: 2048 | 1
          /* KeyCode.Backspace */
        },
        when: $7m.and($WAb, $7m.not($Beb), $ZAb.toNegated()),
        weight: 200
        /* KeybindingWeight.WorkbenchContrib */
      },
      menu: [
        {
          id: $bJ.NotebookCellDelete,
          when: $1Ab,
          group: $yIb
        },
        {
          id: $bJ.InteractiveCellDelete,
          group: $yIb
        }
      ],
      icon: $GKb
    });
  }
  async runWithContext(accessor, context) {
    if (!context.notebookEditor.hasModel()) {
      return;
    }
    let confirmation;
    const notebookExecutionStateService = accessor.get($wL);
    const runState = notebookExecutionStateService.getCellExecution(context.cell.uri)?.state;
    const configService = accessor.get($kl);
    if (runState === NotebookCellExecutionState.Executing && configService.getValue($rM.confirmDeleteRunningCell)) {
      const dialogService = accessor.get($Yv);
      const primaryButton = localize(8253, null);
      confirmation = await dialogService.confirm({
        type: "question",
        message: localize(8254, null),
        primaryButton,
        checkbox: {
          label: localize(8255, null)
        }
      });
    } else {
      confirmation = { confirmed: true };
    }
    if (!confirmation.confirmed) {
      return;
    }
    if (confirmation.checkboxChecked === true) {
      await configService.updateValue($rM.confirmDeleteRunningCell, false);
    }
    $3Ib(context.notebookEditor, context.cell);
  }
});
$hJ(class ClearCellOutputsAction extends $HIb {
  constructor() {
    super({
      id: $Q2b,
      title: localize(8256, null),
      menu: [
        {
          id: $bJ.NotebookCellTitle,
          when: $7m.and($0Ab.isEqualTo("code"), $IIb, $fBb, $1Ab, $$Ab, $4Ab.toNegated()),
          order: 6,
          group: $zIb
        },
        {
          id: $bJ.NotebookOutputToolbar,
          when: $7m.and($fBb, $1Ab, $$Ab, $gBb, $4Ab)
        }
      ],
      keybinding: {
        when: $7m.and($WAb, $7m.not($Beb), $fBb, $1Ab, $$Ab),
        primary: 512 | 20,
        weight: 200
        /* KeybindingWeight.WorkbenchContrib */
      },
      icon: $MKb
    });
  }
  async runWithContext(accessor, context) {
    const notebookExecutionStateService = accessor.get($wL);
    const editor = context.notebookEditor;
    if (!editor.hasModel() || !editor.textModel.length) {
      return;
    }
    const cell = context.cell;
    const index = editor.textModel.cells.indexOf(cell.model);
    if (index < 0) {
      return;
    }
    const computeUndoRedo = !editor.isReadOnly;
    editor.textModel.applyEdits([{ editType: 2, index, outputs: [] }], true, void 0, () => void 0, void 0, computeUndoRedo);
    const runState = notebookExecutionStateService.getCellExecution(context.cell.uri)?.state;
    if (runState !== NotebookCellExecutionState.Executing) {
      context.notebookEditor.textModel.applyEdits([{
        editType: 9,
        index,
        internalMetadata: {
          runStartTime: null,
          runStartTimeAdjustment: null,
          runEndTime: null,
          executionOrder: null,
          lastRunSuccess: null
        }
      }], true, void 0, () => void 0, void 0, computeUndoRedo);
    }
  }
});
$hJ(class ClearAllCellOutputsAction extends $FIb {
  constructor() {
    super({
      id: CLEAR_ALL_CELLS_OUTPUTS_COMMAND_ID,
      title: localize(8257, null),
      precondition: $tBb,
      menu: [
        {
          id: $bJ.EditorTitle,
          when: $7m.and($SAb, $7m.notEquals("config.notebook.globalToolbar", true)),
          group: "navigation",
          order: 0
        },
        {
          id: $bJ.NotebookToolbar,
          when: $7m.and($IIb, $7m.equals("config.notebook.globalToolbar", true)),
          group: "navigation/execute",
          order: 10
        }
      ],
      icon: $MKb
    });
  }
  async runWithContext(accessor, context) {
    const notebookExecutionStateService = accessor.get($wL);
    const editor = context.notebookEditor;
    if (!editor.hasModel() || !editor.textModel.length) {
      return;
    }
    const computeUndoRedo = !editor.isReadOnly;
    editor.textModel.applyEdits(editor.textModel.cells.map((cell, index) => ({
      editType: 2,
      index,
      outputs: []
    })), true, void 0, () => void 0, void 0, computeUndoRedo);
    const clearExecutionMetadataEdits = editor.textModel.cells.map((cell, index) => {
      const runState = notebookExecutionStateService.getCellExecution(cell.uri)?.state;
      if (runState !== NotebookCellExecutionState.Executing) {
        return {
          editType: 9,
          index,
          internalMetadata: {
            runStartTime: null,
            runStartTimeAdjustment: null,
            runEndTime: null,
            executionOrder: null,
            lastRunSuccess: null
          }
        };
      } else {
        return void 0;
      }
    }).filter((edit3) => !!edit3);
    if (clearExecutionMetadataEdits.length) {
      context.notebookEditor.textModel.applyEdits(clearExecutionMetadataEdits, true, void 0, () => void 0, void 0, computeUndoRedo);
    }
  }
});
$hJ(class ChangeCellLanguageAction extends $HIb {
  constructor() {
    super({
      id: $Jrb,
      title: localize(8258, null),
      metadata: {
        description: localize(8259, null),
        args: [
          {
            name: "range",
            description: "The cell range",
            schema: {
              "type": "object",
              "required": ["start", "end"],
              "properties": {
                "start": {
                  "type": "number"
                },
                "end": {
                  "type": "number"
                }
              }
            }
          },
          {
            name: "language",
            description: "The target cell language",
            schema: {
              "type": "string"
            }
          }
        ]
      }
    });
  }
  g(accessor, context, ...additionalArgs) {
    if (!context || typeof context.start !== "number" || typeof context.end !== "number" || context.start >= context.end) {
      return;
    }
    const language = additionalArgs.length && typeof additionalArgs[0] === "string" ? additionalArgs[0] : void 0;
    const activeEditorContext = this.getEditorContextFromArgsOrActive(accessor);
    if (!activeEditorContext || !activeEditorContext.notebookEditor.hasModel() || context.start >= activeEditorContext.notebookEditor.getLength()) {
      return;
    }
    return {
      notebookEditor: activeEditorContext.notebookEditor,
      cell: activeEditorContext.notebookEditor.cellAt(context.start),
      language
    };
  }
  async runWithContext(accessor, context) {
    if (context.language) {
      await this.h(context, context.language);
    } else {
      await this.f(accessor, context);
    }
  }
  async f(accessor, context) {
    const topItems = [];
    const mainItems = [];
    const languageService = accessor.get($1E);
    const modelService = accessor.get($sG);
    const quickInputService = accessor.get($1M);
    const languageDetectionService = accessor.get($tG);
    const kernelService = accessor.get($CL);
    let languages = context.notebookEditor.activeKernel?.supportedLanguages;
    if (!languages) {
      const matchResult = kernelService.getMatchingKernel(context.notebookEditor.textModel);
      const allSupportedLanguages = matchResult.all.flatMap((kernel) => kernel.supportedLanguages);
      languages = allSupportedLanguages.length > 0 ? allSupportedLanguages : languageService.getRegisteredLanguageIds();
    }
    const providerLanguages = /* @__PURE__ */ new Set([
      ...languages,
      "markdown"
    ]);
    providerLanguages.forEach((languageId2) => {
      let description;
      if (context.cell.cellKind === CellKind.Markup ? languageId2 === "markdown" : languageId2 === context.cell.language) {
        description = localize(8260, null, languageId2);
      } else {
        description = localize(8261, null, languageId2);
      }
      const languageName = languageService.getLanguageName(languageId2);
      if (!languageName) {
        return;
      }
      const item = {
        label: languageName,
        iconClasses: $gdb(modelService, languageService, this.j(languageName, languageService)),
        description,
        languageId: languageId2
      };
      if (languageId2 === "markdown" || languageId2 === context.cell.language) {
        topItems.push(item);
      } else {
        mainItems.push(item);
      }
    });
    mainItems.sort((a, b) => {
      return a.description.localeCompare(b.description);
    });
    const autoDetectMode = {
      label: localize(8262, null)
    };
    const picks = [
      autoDetectMode,
      { type: "separator", label: localize(8263, null) },
      ...topItems,
      { type: "separator" },
      ...mainItems
    ];
    const selection = await quickInputService.pick(picks, { placeHolder: localize(8264, null) });
    const languageId = selection === autoDetectMode ? await languageDetectionService.detectLanguage(context.cell.uri) : selection?.languageId;
    if (languageId) {
      await this.h(context, languageId);
    }
  }
  async h(context, languageId) {
    await setCellToLanguage(languageId, context);
  }
  /**
   * Copied from editorStatus.ts
   */
  j(lang, languageService) {
    let fakeResource;
    const languageId = languageService.getLanguageIdByLanguageName(lang);
    if (languageId) {
      const extensions = languageService.getExtensions(languageId);
      if (extensions.length) {
        fakeResource = URI.file(extensions[0]);
      } else {
        const filenames = languageService.getFilenames(languageId);
        if (filenames.length) {
          fakeResource = URI.file(filenames[0]);
        }
      }
    }
    return fakeResource;
  }
});
$hJ(class DetectCellLanguageAction extends $HIb {
  constructor() {
    super({
      id: $Irb,
      title: localize2(8272, "Accept Detected Language for Cell"),
      f1: true,
      precondition: $7m.and($1Ab, $$Ab),
      keybinding: {
        primary: 34 | 512 | 1024,
        weight: 200
        /* KeybindingWeight.WorkbenchContrib */
      }
    });
  }
  async runWithContext(accessor, context) {
    const languageDetectionService = accessor.get($tG);
    const notificationService = accessor.get($PJ);
    const kernelService = accessor.get($CL);
    const kernel = kernelService.getSelectedOrSuggestedKernel(context.notebookEditor.textModel);
    const providerLanguages = [...kernel?.supportedLanguages ?? []];
    providerLanguages.push("markdown");
    const detection = await languageDetectionService.detectLanguage(context.cell.uri, providerLanguages);
    if (detection) {
      setCellToLanguage(detection, context);
    } else {
      notificationService.warn(localize(8265, null));
    }
  }
});
async function setCellToLanguage(languageId, context) {
  if (languageId === "markdown" && context.cell?.language !== "markdown") {
    const idx = context.notebookEditor.getCellIndex(context.cell);
    await $2Ib(CellKind.Markup, { cell: context.cell, notebookEditor: context.notebookEditor, ui: true }, "markdown", $YC.markdown);
    const newCell = context.notebookEditor.cellAt(idx);
    if (newCell) {
      await context.notebookEditor.focusNotebookCell(newCell, "editor");
    }
  } else if (languageId !== "markdown" && context.cell?.cellKind === CellKind.Markup) {
    await $2Ib(CellKind.Code, { cell: context.cell, notebookEditor: context.notebookEditor, ui: true }, languageId);
  } else {
    const index = context.notebookEditor.textModel.cells.indexOf(context.cell.model);
    context.notebookEditor.textModel.applyEdits([{ editType: 4, index, language: languageId }], true, void 0, () => void 0, void 0, !context.notebookEditor.isReadOnly);
  }
}
$hJ(class SelectNotebookIndentation extends $FIb {
  constructor() {
    super({
      id: $R2b,
      title: localize2(8273, "Select Indentation"),
      f1: true,
      precondition: $7m.and($SAb, $1Ab, $$Ab)
    });
  }
  async runWithContext(accessor, context) {
    await this.d(accessor, context);
  }
  async d(accessor, context) {
    const quickInputService = accessor.get($1M);
    const editorService = accessor.get($mJ);
    const instantiationService = accessor.get($Pk);
    const activeNotebook = $Qrb(editorService.activeEditorPane);
    if (!activeNotebook || activeNotebook.isDisposed) {
      return quickInputService.pick([{ label: localize(8266, null) }]);
    }
    if (activeNotebook.isReadOnly) {
      return quickInputService.pick([{ label: localize(8267, null) }]);
    }
    const picks = [
      new $L2b(),
      // indent using tabs
      new $M2b(),
      // indent using spaces
      new $N2b(),
      // change tab size
      new $P2b(),
      // convert indentation to tabs
      new $O2b()
      // convert indentation to spaces
    ].map((item) => {
      return {
        id: item.desc.id,
        label: item.desc.title.toString(),
        run: () => {
          instantiationService.invokeFunction(item.run);
        }
      };
    });
    picks.splice(3, 0, { type: "separator", label: localize(8268, null) });
    picks.unshift({ type: "separator", label: localize(8269, null) });
    const action = await quickInputService.pick(picks, { placeHolder: localize(8270, null), matchOnDetail: true });
    if (!action) {
      return;
    }
    action.run();
    context.notebookEditor.focus();
    return;
  }
});
$hJ(class CommentSelectedCellsAction extends $GIb {
  constructor() {
    super({
      id: $S2b,
      title: localize(8271, null),
      keybinding: {
        when: $7m.and($WAb, $1Ab, $7m.not($Beb)),
        primary: 2048 | 90,
        weight: 200
        /* KeybindingWeight.WorkbenchContrib */
      }
    });
  }
  async runWithContext(accessor, context) {
    const languageConfigurationService = accessor.get($NF);
    context.selectedCells.forEach(async (cellViewModel) => {
      const textModel = await cellViewModel.resolveTextModel();
      const commentsOptions = cellViewModel.commentOptions;
      const cellCommentCommand = new $Lfb(
        languageConfigurationService,
        new $_D(1, 1, textModel.getLineCount(), textModel.getLineMaxColumn(textModel.getLineCount())),
        // comment the entire cell
        textModel.getOptions().tabSize,
        0,
        commentsOptions.insertSpace ?? true,
        commentsOptions.ignoreEmptyLines ?? true,
        false
      );
      const cellEditorSelections = cellViewModel.getSelections();
      const initialTrackedRangesIDs = cellEditorSelections.map((selection) => {
        return textModel._setTrackedRange(
          null,
          selection,
          1
          /* TrackedRangeStickiness.NeverGrowsWhenTypingAtEdges */
        );
      });
      $m9.executeCommands(textModel, cellEditorSelections, [cellCommentCommand]);
      const newTrackedSelections = initialTrackedRangesIDs.map((i2) => {
        return textModel._getTrackedRange(i2);
      }).filter((r2) => !!r2).map((range) => {
        return new $_D(range.startLineNumber, range.startColumn, range.endLineNumber, range.endColumn);
      });
      cellViewModel.setSelections(newTrackedSelections ?? []);
    });
  }
});

// out-build/vs/workbench/contrib/notebook/browser/controller/apiActions.js
$tn.registerCommand("_resolveNotebookContentProvider", (accessor) => {
  const notebookService = accessor.get($mrb);
  const contentProviders = notebookService.getContributedNotebookTypes();
  return contentProviders.map((provider) => {
    const filenamePatterns = provider.selectors.map((selector) => {
      if (typeof selector === "string") {
        return selector;
      }
      if ($El(selector)) {
        return selector;
      }
      if ($pM(selector)) {
        return {
          include: selector.include,
          exclude: selector.exclude
        };
      }
      return null;
    }).filter((pattern) => pattern !== null);
    return {
      viewType: provider.id,
      displayName: provider.displayName,
      filenamePattern: filenamePatterns,
      options: {
        transientCellMetadata: provider.options.transientCellMetadata,
        transientDocumentMetadata: provider.options.transientDocumentMetadata,
        transientOutputs: provider.options.transientOutputs
      }
    };
  });
});
$tn.registerCommand("_resolveNotebookKernels", async (accessor, args2) => {
  const notebookKernelService = accessor.get($CL);
  const uri = URI.revive(args2.uri);
  const kernels = notebookKernelService.getMatchingKernel({ uri, notebookType: args2.viewType });
  return kernels.all.map((provider) => ({
    id: provider.id,
    label: provider.label,
    description: provider.description,
    detail: provider.detail,
    isPreferred: false,
    // todo@jrieken,@rebornix
    preloads: provider.preloadUris
  }));
});

// out-build/vs/workbench/contrib/chat/browser/contrib/chatInputCompletions.js
var BuiltinDynamicCompletions_1;
var VariableCompletions_1;
var SlashCommandCompletions = class SlashCommandCompletions2 extends $3c {
  constructor(b, f, g) {
    super();
    this.b = b;
    this.f = f;
    this.g = g;
    this.B(this.b.completionProvider.register({ scheme: $1Nb.INPUT_SCHEME, hasAccessToAllModels: true }, {
      _debugDisplayName: "globalSlashCommands",
      triggerCharacters: ["/"],
      provideCompletionItems: async (model, position, _context, _token) => {
        const widget = this.f.getWidgetByInputUri(model.uri);
        if (!widget || !widget.viewModel) {
          return null;
        }
        const range = $T2b(model, position, /\/\w*/g);
        if (!range) {
          return null;
        }
        if (!isEmptyUpToCompletionWord(model, range)) {
          return;
        }
        const parsedRequest = widget.parsedInput.parts;
        const usedAgent = parsedRequest.find((p) => p instanceof $BO);
        if (usedAgent) {
          return;
        }
        const slashCommands = this.g.getCommands(widget.location);
        if (!slashCommands) {
          return null;
        }
        return {
          suggestions: slashCommands.map((c, i2) => {
            const withSlash = `/${c.command}`;
            return {
              label: withSlash,
              insertText: c.executeImmediately ? "" : `${withSlash} `,
              detail: c.detail,
              range,
              sortText: c.sortText ?? "a".repeat(i2 + 1),
              kind: 18,
              // The icons are disabled here anyway,
              command: c.executeImmediately ? { id: widget.location === ChatAgentLocation.EditingSession ? $INb.ID : $HNb.ID, title: withSlash, arguments: [{ widget, inputValue: `${withSlash} ` }] } : void 0
            };
          })
        };
      }
    }));
    this.B(this.b.completionProvider.register({ scheme: $1Nb.INPUT_SCHEME, hasAccessToAllModels: true }, {
      _debugDisplayName: "globalSlashCommandsAt",
      triggerCharacters: [$xO],
      provideCompletionItems: async (model, position, _context, _token) => {
        const widget = this.f.getWidgetByInputUri(model.uri);
        if (!widget || !widget.viewModel) {
          return null;
        }
        const range = $T2b(model, position, /@\w*/g);
        if (!range) {
          return null;
        }
        if (!isEmptyUpToCompletionWord(model, range)) {
          return;
        }
        const slashCommands = this.g.getCommands(widget.location);
        if (!slashCommands) {
          return null;
        }
        return {
          suggestions: slashCommands.map((c, i2) => {
            const withSlash = `${$yO}${c.command}`;
            return {
              label: withSlash,
              insertText: c.executeImmediately ? "" : `${withSlash} `,
              detail: c.detail,
              range,
              filterText: `${$xO}${c.command}`,
              sortText: c.sortText ?? "z".repeat(i2 + 1),
              kind: 18,
              // The icons are disabled here anyway,
              command: c.executeImmediately ? { id: widget.location === ChatAgentLocation.EditingSession ? $INb.ID : $HNb.ID, title: withSlash, arguments: [{ widget, inputValue: `${withSlash} ` }] } : void 0
            };
          })
        };
      }
    }));
  }
};
SlashCommandCompletions = __decorate([
  __param(0, $mP),
  __param(1, $2Nb),
  __param(2, $sO)
], SlashCommandCompletions);
$Wn.as(Extensions2.Workbench).registerWorkbenchContribution(
  SlashCommandCompletions,
  4
  /* LifecyclePhase.Eventually */
);
var AgentCompletions = class AgentCompletions2 extends $3c {
  constructor(b, f, g, h3) {
    super();
    this.b = b;
    this.f = f;
    this.g = g;
    this.h = h3;
    const subCommandProvider = {
      _debugDisplayName: "chatAgentSubcommand",
      triggerCharacters: ["/"],
      provideCompletionItems: async (model, position, _context, token) => {
        const widget = this.f.getWidgetByInputUri(model.uri);
        if (!widget || !widget.viewModel) {
          return;
        }
        const range = $T2b(model, position, /\/\w*/g);
        if (!range) {
          return null;
        }
        const parsedRequest = widget.parsedInput.parts;
        const usedAgentIdx = parsedRequest.findIndex((p) => p instanceof $BO);
        if (usedAgentIdx < 0) {
          return;
        }
        const usedSubcommand = parsedRequest.find((p) => p instanceof $CO);
        if (usedSubcommand) {
          return;
        }
        for (const partAfterAgent of parsedRequest.slice(usedAgentIdx + 1)) {
          if (!(partAfterAgent instanceof $vO) || !partAfterAgent.text.trim().match(/^(\/\w*)?$/)) {
            return;
          }
        }
        const usedAgent = parsedRequest[usedAgentIdx];
        return {
          suggestions: usedAgent.agent.slashCommands.map((c, i2) => {
            const withSlash = `/${c.name}`;
            return {
              label: withSlash,
              insertText: `${withSlash} `,
              detail: c.description,
              range,
              kind: 18
              // The icons are disabled here anyway
            };
          })
        };
      }
    };
    this.B(this.b.completionProvider.register({ scheme: $1Nb.INPUT_SCHEME, hasAccessToAllModels: true }, subCommandProvider));
    this.B(this.b.completionProvider.register({ scheme: $1Nb.INPUT_SCHEME, hasAccessToAllModels: true }, {
      _debugDisplayName: "chatAgentAndSubcommand",
      triggerCharacters: [$xO],
      provideCompletionItems: async (model, position, _context, token) => {
        const widget = this.f.getWidgetByInputUri(model.uri);
        const viewModel = widget?.viewModel;
        if (!widget || !viewModel) {
          return;
        }
        const range = $T2b(model, position, /(@|\/)\w*/g);
        if (!range) {
          return null;
        }
        if (!isEmptyUpToCompletionWord(model, range)) {
          return;
        }
        const agents = this.g.getAgents().filter((a) => a.locations.includes(widget.location));
        const getFilterText = (agent, command4) => {
          const dummyPrefix = agent.id === "github.copilot.terminalPanel" ? `0000` : ``;
          return `${$xO}${dummyPrefix}${agent.name}.${command4}`;
        };
        const justAgents = agents.filter((a) => !a.isDefault).map((agent) => {
          const { label: agentLabel, isDupe } = this.j(agent);
          const detail2 = agent.description;
          return {
            label: isDupe ? { label: agentLabel, description: agent.description, detail: ` (${agent.publisherDisplayName})` } : agentLabel,
            detail: detail2,
            filterText: `${$xO}${agent.name}`,
            insertText: `${agentLabel} `,
            range,
            kind: 18,
            sortText: `${$xO}${agent.name}`,
            command: { id: AssignSelectedAgentAction.ID, title: AssignSelectedAgentAction.ID, arguments: [{ agent, widget }] }
          };
        });
        return {
          suggestions: justAgents.concat(agents.flatMap((agent) => agent.slashCommands.map((c, i2) => {
            const { label: agentLabel, isDupe } = this.j(agent);
            const label3 = `${agentLabel} ${$yO}${c.name}`;
            const item = {
              label: isDupe ? { label: label3, description: c.description, detail: isDupe ? ` (${agent.publisherDisplayName})` : void 0 } : label3,
              detail: c.description,
              filterText: getFilterText(agent, c.name),
              commitCharacters: [" "],
              insertText: label3 + " ",
              range,
              kind: 18,
              // The icons are disabled here anyway
              sortText: `x${$xO}${agent.name}${c.name}`,
              command: { id: AssignSelectedAgentAction.ID, title: AssignSelectedAgentAction.ID, arguments: [{ agent, widget }] }
            };
            if (agent.isDefault) {
              const label4 = `${$yO}${c.name}`;
              item.label = label4;
              item.insertText = `${label4} `;
              item.detail = c.description;
            }
            return item;
          })))
        };
      }
    }));
    this.B(this.b.completionProvider.register({ scheme: $1Nb.INPUT_SCHEME, hasAccessToAllModels: true }, {
      _debugDisplayName: "chatAgentAndSubcommand",
      triggerCharacters: [$yO],
      provideCompletionItems: async (model, position, _context, token) => {
        const widget = this.f.getWidgetByInputUri(model.uri);
        const viewModel = widget?.viewModel;
        if (!widget || !viewModel) {
          return;
        }
        const range = $T2b(model, position, /(@|\/)\w*/g);
        if (!range) {
          return null;
        }
        if (!isEmptyUpToCompletionWord(model, range)) {
          return;
        }
        const agents = this.g.getAgents().filter((a) => a.locations.includes(widget.location));
        return {
          suggestions: agents.flatMap((agent) => agent.slashCommands.map((c, i2) => {
            const { label: agentLabel, isDupe } = this.j(agent);
            const withSlash = `${$yO}${c.name}`;
            const extraSortText = agent.id === "github.copilot.terminalPanel" ? `z` : ``;
            const sortText = `${$yO}${extraSortText}${agent.name}${c.name}`;
            const item = {
              label: { label: withSlash, description: agentLabel, detail: isDupe ? ` (${agent.publisherDisplayName})` : void 0 },
              commitCharacters: [" "],
              insertText: `${agentLabel} ${withSlash} `,
              detail: `(${agentLabel}) ${c.description ?? ""}`,
              range,
              kind: 18,
              // The icons are disabled here anyway
              sortText,
              command: { id: AssignSelectedAgentAction.ID, title: AssignSelectedAgentAction.ID, arguments: [{ agent, widget }] }
            };
            if (agent.isDefault) {
              const label3 = `${$yO}${c.name}`;
              item.label = label3;
              item.insertText = `${label3} `;
              item.detail = c.description;
            }
            return item;
          }))
        };
      }
    }));
    this.B(this.b.completionProvider.register({ scheme: $1Nb.INPUT_SCHEME, hasAccessToAllModels: true }, {
      _debugDisplayName: "installChatExtensions",
      triggerCharacters: [$xO],
      provideCompletionItems: async (model, position, _context, token) => {
        if (!model.getLineContent(1).startsWith($xO)) {
          return;
        }
        const widget = this.f.getWidgetByInputUri(model.uri);
        if (widget?.location !== ChatAgentLocation.Panel) {
          return;
        }
        const range = $T2b(model, position, /(@|\/)\w*/g);
        if (!range) {
          return;
        }
        if (!isEmptyUpToCompletionWord(model, range)) {
          return;
        }
        const label3 = localize(5055, null);
        const item = {
          label: label3,
          insertText: "",
          range,
          kind: 18,
          // The icons are disabled here anyway
          command: { id: "workbench.extensions.search", title: "", arguments: ["@tag:chat-participant"] },
          filterText: $xO + label3,
          sortText: "zzz"
        };
        return {
          suggestions: [item]
        };
      }
    }));
  }
  j(agent) {
    const isAllowed = this.h.getAgentNameRestriction(agent);
    const agentLabel = `${$xO}${isAllowed ? agent.name : $5O(agent)}`;
    const isDupe = isAllowed && this.g.agentHasDupeName(agent.id);
    return { label: agentLabel, isDupe };
  }
};
AgentCompletions = __decorate([
  __param(0, $mP),
  __param(1, $2Nb),
  __param(2, $ZO),
  __param(3, $3O)
], AgentCompletions);
$Wn.as(Extensions2.Workbench).registerWorkbenchContribution(
  AgentCompletions,
  4
  /* LifecyclePhase.Eventually */
);
var AssignSelectedAgentAction = class _AssignSelectedAgentAction extends $gJ {
  static {
    this.ID = "workbench.action.chat.assignSelectedAgent";
  }
  constructor() {
    super({
      id: _AssignSelectedAgentAction.ID,
      title: ""
      // not displayed
    });
  }
  async run(accessor, ...args2) {
    const arg = args2[0];
    if (!arg || !arg.widget || !arg.agent) {
      return;
    }
    arg.widget.lastSelectedAgent = arg.agent;
  }
};
$hJ(AssignSelectedAgentAction);
var ReferenceArgument = class {
  constructor(widget, variable) {
    this.widget = widget;
    this.variable = variable;
  }
};
var BuiltinDynamicCompletions = class BuiltinDynamicCompletions2 extends $3c {
  static {
    BuiltinDynamicCompletions_1 = this;
  }
  static {
    this.b = "_addReferenceCmd";
  }
  static {
    this.f = new RegExp(`${$wO}\\w*`, "g");
  }
  // MUST be using `g`-flag
  constructor(h3, j, m, n, r2, s, u, w, y) {
    super();
    this.h = h3;
    this.j = j;
    this.m = m;
    this.n = n;
    this.r = r2;
    this.s = s;
    this.u = u;
    this.w = w;
    this.y = y;
    this.B(this.r.completionProvider.register({ scheme: $1Nb.INPUT_SCHEME, hasAccessToAllModels: true }, {
      _debugDisplayName: "chatDynamicFileCompletions",
      triggerCharacters: [$wO],
      provideCompletionItems: async (model, position, _context, token) => {
        const widget = this.s.getWidgetByInputUri(model.uri);
        if (!widget || !widget.supportsFileReferences) {
          return null;
        }
        const result = { suggestions: [] };
        const range = $T2b(model, position, BuiltinDynamicCompletions_1.f, true);
        if (range) {
          const afterRange = new $9C(position.lineNumber, range.replace.startColumn, position.lineNumber, range.replace.startColumn + "#file:".length);
          result.suggestions.push({
            label: `${$wO}file`,
            insertText: `${$wO}file:`,
            detail: localize(5056, null),
            range,
            kind: 18,
            command: { id: $bOb.ID, title: $bOb.ID, arguments: [{ widget, range: afterRange }] },
            sortText: "z"
          });
        }
        const range2 = $T2b(model, position, new RegExp(`${$wO}[^\\s]*`, "g"), true);
        if (range2) {
          await this.C(widget, result, range2, token);
        }
        return result;
      }
    }));
    this.B(this.r.completionProvider.register({ scheme: $1Nb.INPUT_SCHEME, hasAccessToAllModels: true }, {
      _debugDisplayName: "chatDynamicSymbolCompletions",
      triggerCharacters: [$wO],
      provideCompletionItems: async (model, position, _context, token) => {
        const widget = this.s.getWidgetByInputUri(model.uri);
        if (!widget || !widget.supportsFileReferences) {
          return null;
        }
        const result = { suggestions: [] };
        const range = $T2b(model, position, BuiltinDynamicCompletions_1.f, true);
        if (range) {
          const afterRangeSym = new $9C(position.lineNumber, range.replace.startColumn, position.lineNumber, range.replace.startColumn + "#sym:".length);
          result.suggestions.push({
            label: `${$wO}sym`,
            insertText: `${$wO}sym:`,
            detail: localize(5057, null),
            range,
            kind: 18,
            command: { id: $cOb.ID, title: $cOb.ID, arguments: [{ widget, range: afterRangeSym }] },
            sortText: "z"
          });
        }
        const range2 = $T2b(model, position, new RegExp(`${$wO}[^\\s]*`, "g"), true);
        if (range2) {
          this.D(widget, result, range2, token);
        }
        return result;
      }
    }));
    this.B($tn.registerCommand(BuiltinDynamicCompletions_1.b, (_services, arg) => this.F(arg)));
    this.g = this.w.createInstance($eT);
  }
  async C(widget, result, info, token) {
    const makeFileCompletionItem = (resource, description) => {
      const basename = this.n.getUriBasenameLabel(resource);
      const text2 = `${$wO}file:${basename}`;
      const uriLabel = this.n.getUriLabel(resource, { relative: true });
      const labelDescription = description ? localize(5058, null, uriLabel, description) : uriLabel;
      const sortText = description ? "z" : "{";
      return {
        label: { label: basename, description: labelDescription },
        filterText: `${$wO}${basename}`,
        insertText: info.varWord?.endColumn === info.replace.endColumn ? `${text2} ` : text2,
        range: info,
        kind: 20,
        sortText,
        command: {
          id: BuiltinDynamicCompletions_1.b,
          title: "",
          arguments: [new ReferenceArgument(widget, {
            id: "vscode.file",
            prefix: "file",
            isFile: true,
            range: { startLineNumber: info.replace.startLineNumber, startColumn: info.replace.startColumn, endLineNumber: info.replace.endLineNumber, endColumn: info.replace.startColumn + text2.length },
            data: resource
          })]
        }
      };
    };
    let pattern;
    if (info.varWord?.word && info.varWord.word.startsWith($wO)) {
      pattern = info.varWord.word.toLowerCase().slice(1);
    }
    const seen = new $Fc();
    const len = result.suggestions.length;
    if (widget.location === ChatAgentLocation.EditingSession && widget.viewModel && this.u.currentEditingSessionObs.get()?.chatSessionId === widget.viewModel?.sessionId) {
      const relatedFiles = await $Lh(this.u.getRelatedFiles(widget.viewModel.sessionId, widget.getInput(), token), 1e3) ?? [];
      for (const relatedFileGroup of relatedFiles) {
        for (const relatedFile of relatedFileGroup.files) {
          if (seen.has(relatedFile.uri)) {
            continue;
          }
          seen.add(relatedFile.uri);
          result.suggestions.push(makeFileCompletionItem(relatedFile.uri, relatedFile.description));
        }
      }
    }
    for (const item of this.h.getHistory()) {
      if (!item.resource || !this.j.getWorkspaceFolder(item.resource)) {
        continue;
      }
      if (pattern) {
        const basename = this.n.getUriBasenameLabel(item.resource).toLowerCase();
        if (!$Vl(pattern, 0, pattern.length, basename, 0, basename.length)) {
          continue;
        }
      }
      seen.add(item.resource);
      const newLen = result.suggestions.push(makeFileCompletionItem(item.resource));
      if (newLen - len >= 5) {
        break;
      }
    }
    if (pattern) {
      if (this.z && Date.now() - this.z.time > 6e4) {
        this.m.clearCache(this.z.key);
        this.z = void 0;
      }
      if (!this.z) {
        this.z = {
          key: $ps(),
          time: Date.now()
        };
      }
      this.z.time = Date.now();
      const query = this.g.file(this.j.getWorkspace().folders, {
        filePattern: pattern,
        sortByScore: true,
        maxResults: 250,
        cacheKey: this.z.key
      });
      const data = await this.m.fileSearch(query, token);
      for (const match of data.results) {
        if (seen.has(match.resource)) {
          continue;
        }
        result.suggestions.push(makeFileCompletionItem(match.resource));
      }
    }
    result.incomplete = true;
  }
  D(widget, result, info, token) {
    const makeSymbolCompletionItem = (symbolItem, pattern2) => {
      const text2 = `${$wO}sym:${symbolItem.name}`;
      const resource = symbolItem.location.uri;
      const symbolLabelWithIcon = `$(${SymbolKinds.toIcon(symbolItem.kind).id}) ${symbolItem.name}`;
      const uriLabel = this.n.getUriLabel(resource, { relative: true });
      const sortText = pattern2 ? "{" : "|";
      return {
        label: { label: symbolLabelWithIcon, description: uriLabel },
        filterText: `${$wO}${symbolItem.name}`,
        insertText: info.varWord?.endColumn === info.replace.endColumn ? `${text2} ` : text2,
        range: info,
        kind: SymbolKinds.toCompletionKind(symbolItem.kind),
        sortText,
        command: {
          id: BuiltinDynamicCompletions_1.b,
          title: "",
          arguments: [new ReferenceArgument(widget, {
            id: "vscode.symbol",
            prefix: "sym",
            fullName: symbolLabelWithIcon,
            range: { startLineNumber: info.replace.startLineNumber, startColumn: info.replace.startColumn, endLineNumber: info.replace.endLineNumber, endColumn: info.replace.startColumn + text2.length },
            data: symbolItem.location
          })]
        }
      };
    };
    let pattern;
    if (info.varWord?.word && info.varWord.word.startsWith($wO)) {
      pattern = info.varWord.word.toLowerCase().slice(1);
    }
    const symbolsToAdd = [];
    for (const outlineModel of this.y.getCachedModels()) {
      if (pattern) {
        symbolsToAdd.push(...outlineModel.asListOfDocumentSymbols().map((symbol) => ({ symbol, uri: outlineModel.uri })));
      } else {
        symbolsToAdd.push(...outlineModel.getTopLevelSymbols().map((symbol) => ({ symbol, uri: outlineModel.uri })));
      }
    }
    const symbolsToAddFiltered = symbolsToAdd.filter((fileSymbol) => {
      switch (fileSymbol.symbol.kind) {
        case 9:
        case 4:
        case 5:
        case 11:
        case 2:
        case 1:
        case 10:
          return true;
        default:
          return false;
      }
    });
    for (const symbol of symbolsToAddFiltered) {
      result.suggestions.push(makeSymbolCompletionItem({ ...symbol.symbol, location: { uri: symbol.uri, range: symbol.symbol.range } }, pattern ?? ""));
    }
    result.incomplete = !!pattern;
  }
  F(arg) {
    arg.widget.getContrib($aOb.ID)?.addReference(arg.variable);
  }
};
BuiltinDynamicCompletions = BuiltinDynamicCompletions_1 = __decorate([
  __param(0, $tY),
  __param(1, $Zk),
  __param(2, $TN),
  __param(3, $ZI),
  __param(4, $mP),
  __param(5, $2Nb),
  __param(6, $$O),
  __param(7, $Pk),
  __param(8, $phb)
], BuiltinDynamicCompletions);
$Wn.as(Extensions2.Workbench).registerWorkbenchContribution(
  BuiltinDynamicCompletions,
  4
  /* LifecyclePhase.Eventually */
);
function $T2b(model, position, reg2, onlyOnWordStart = false) {
  const varWord = $MD(position.column, reg2, model.getLineContent(position.lineNumber), 0);
  if (!varWord && model.getWordUntilPosition(position).word) {
    return;
  }
  if (!varWord && position.column > 1) {
    const textBefore = model.getValueInRange(new $9C(position.lineNumber, position.column - 1, position.lineNumber, position.column));
    if (textBefore !== " ") {
      return;
    }
  }
  if (varWord && onlyOnWordStart) {
    const wordBefore = model.getWordUntilPosition({ lineNumber: position.lineNumber, column: varWord.startColumn });
    if (wordBefore.word) {
      return;
    }
  }
  let insert;
  let replace;
  if (!varWord) {
    insert = replace = $9C.fromPositions(position);
  } else {
    insert = new $9C(position.lineNumber, varWord.startColumn, position.lineNumber, position.column);
    replace = new $9C(position.lineNumber, varWord.startColumn, position.lineNumber, varWord.endColumn);
  }
  return { insert, replace, varWord };
}
function isEmptyUpToCompletionWord(model, rangeResult) {
  const startToCompletionWordStart = new $9C(1, 1, rangeResult.replace.startLineNumber, rangeResult.replace.startColumn);
  return !!model.getValueInRange(startToCompletionWordStart).match(/^\s*$/);
}
var VariableCompletions = class VariableCompletions2 extends $3c {
  static {
    VariableCompletions_1 = this;
  }
  static {
    this.b = new RegExp(`(?<=^|\\s)${$wO}\\w*`, "g");
  }
  // MUST be using `g`-flag
  constructor(f, g, h3, configService, toolsService) {
    super();
    this.f = f;
    this.g = g;
    this.h = h3;
    this.B(this.f.completionProvider.register({ scheme: $1Nb.INPUT_SCHEME, hasAccessToAllModels: true }, {
      _debugDisplayName: "chatVariables",
      triggerCharacters: [$wO],
      provideCompletionItems: async (model, position, _context, _token) => {
        const widget = this.g.getWidgetByInputUri(model.uri);
        if (!widget) {
          return null;
        }
        const range = $T2b(model, position, VariableCompletions_1.b, true);
        if (!range) {
          return null;
        }
        const usedAgent = widget.parsedInput.parts.find((p) => p instanceof $BO);
        const slowSupported = usedAgent ? usedAgent.agent.metadata.supportsSlowVariables : true;
        const usedVariables = widget.parsedInput.parts.filter((p) => p instanceof $zO);
        const usedVariableNames = new Set(usedVariables.map((v) => v.variableName));
        const variableItems = Array.from(this.h.getVariables(widget.location)).filter((v) => !usedVariableNames.has(v.name)).filter((v) => !v.isSlow || slowSupported).map((v) => {
          const withLeader = `${$wO}${v.name}`;
          return {
            label: withLeader,
            range,
            insertText: withLeader + " ",
            detail: v.description,
            kind: 18,
            // The icons are disabled here anyway
            sortText: "z"
          };
        });
        const usedTools = widget.parsedInput.parts.filter((p) => p instanceof $AO);
        const usedToolNames = new Set(usedTools.map((v) => v.toolName));
        const toolItems = [];
        toolItems.push(...Array.from(toolsService.getTools()).filter((t) => t.canBeReferencedInPrompt).filter((t) => !usedToolNames.has(t.toolReferenceName ?? "")).map((t) => {
          const withLeader = `${$wO}${t.toolReferenceName}`;
          return {
            label: withLeader,
            range,
            insertText: withLeader + " ",
            detail: t.userDescription,
            kind: 18,
            sortText: "z"
          };
        }));
        return {
          suggestions: [...variableItems, ...toolItems]
        };
      }
    }));
  }
};
VariableCompletions = VariableCompletions_1 = __decorate([
  __param(0, $mP),
  __param(1, $2Nb),
  __param(2, $kO),
  __param(3, $kl),
  __param(4, $mO)
], VariableCompletions);
$Wn.as(Extensions2.Workbench).registerWorkbenchContribution(
  VariableCompletions,
  4
  /* LifecyclePhase.Eventually */
);

// out-build/vs/workbench/contrib/inlineChat/browser/inlineChatActions.js
$tn.registerCommandAlias("interactiveEditor.start", "inlineChat.start");
$tn.registerCommandAlias("interactive.acceptChanges", $sAb);
var $U2b = $9r("start-inline-chat", $6l.sparkle, localize(7468, null));
var _holdForSpeech = void 0;
var $W2b = class extends $gJ {
  constructor() {
    super({
      id: $rAb,
      title: localize2(7476, "Editor Inline Chat"),
      category: $Y2b.category,
      f1: true,
      precondition: $7m.and($$zb, $0zb, EditorContextKeys.writable, EditorContextKeys.editorSimpleInput.negate()),
      keybinding: {
        when: EditorContextKeys.focus,
        weight: 200,
        primary: 2048 | 39
        /* KeyCode.KeyI */
      },
      icon: $U2b,
      menu: {
        id: $bJ.ChatCommandCenter,
        group: "d_inlineChat",
        order: 10
      }
    });
  }
  run(accessor, ...args2) {
    const codeEditorService = accessor.get($U5);
    const editor = codeEditorService.getActiveCodeEditor();
    if (!editor || editor.isSimpleWidget) {
      return;
    }
    return editor.invokeWithinContext((editorAccessor) => {
      const kbService = editorAccessor.get($on);
      const logService = editorAccessor.get($wn);
      const enabled = kbService.contextMatchesRules(this.desc.precondition ?? void 0);
      if (!enabled) {
        logService.debug(`[EditorAction2] NOT running command because its precondition is FALSE`, this.desc.id, this.desc.precondition?.serialize());
        return;
      }
      return this.a(editorAccessor, editor, ...args2);
    });
  }
  a(accessor, editor, ..._args) {
    const ctrl = $cHb.get(editor);
    if (!ctrl) {
      return;
    }
    if (_holdForSpeech) {
      accessor.get($Pk).invokeFunction(_holdForSpeech, ctrl, this);
    }
    let options3;
    const arg = _args[0];
    if (arg && $bHb.isInlineChatRunOptions(arg)) {
      options3 = arg;
    }
    $cHb.get(editor)?.run({ ...options3 });
  }
};
var $X2b = class extends $25 {
  constructor() {
    super({
      id: "inlineChat.unstash",
      title: localize2(7477, "Resume Last Dismissed Inline Chat"),
      category: $Y2b.category,
      precondition: $7m.and($jAb, EditorContextKeys.writable),
      keybinding: {
        weight: 200,
        primary: 2048 | 56
      }
    });
  }
  async runEditorCommand(_accessor, editor, ..._args) {
    const ctrl = $cHb.get(editor);
    if (ctrl) {
      const session = ctrl.unstashLastSession();
      if (session) {
        ctrl.run({
          existingSession: session,
          isUnstashed: true
        });
      }
    }
  }
};
var $Y2b = class _$Y2b extends $25 {
  static {
    this.category = localize2(7478, "Inline Chat");
  }
  constructor(desc) {
    super({
      ...desc,
      category: _$Y2b.category,
      precondition: $7m.and($$zb, desc.precondition)
    });
  }
  runEditorCommand(accessor, editor, ..._args) {
    const editorService = accessor.get($mJ);
    const logService = accessor.get($wn);
    let ctrl = $cHb.get(editor);
    if (!ctrl) {
      const { activeTextEditorControl } = editorService;
      if ($P5(activeTextEditorControl)) {
        editor = activeTextEditorControl;
      } else if ($Q5(activeTextEditorControl)) {
        editor = activeTextEditorControl.getModifiedEditor();
      }
      ctrl = $cHb.get(editor);
    }
    if (!ctrl) {
      logService.warn("[IE] NO controller found for action", this.desc.id, editor.getModel()?.uri);
      return;
    }
    if (editor instanceof $bdb) {
      editor = editor.getParentEditor();
    }
    if (!ctrl) {
      for (const diffEditor of accessor.get($U5).listDiffEditors()) {
        if (diffEditor.getOriginalEditor() === editor || diffEditor.getModifiedEditor() === editor) {
          if (diffEditor instanceof $zEb) {
            this.runEditorCommand(accessor, diffEditor.getParentEditor(), ..._args);
          }
        }
      }
      return;
    }
    this.runInlineChatCommand(accessor, ctrl, editor, ..._args);
  }
};
var $Z2b = class extends $Y2b {
  constructor() {
    super({
      id: "inlineChat.arrowOutUp",
      title: localize(7469, null),
      precondition: $7m.and($aAb, $eAb, EditorContextKeys.isEmbeddedDiffEditor.negate(), $OD.negate()),
      keybinding: {
        weight: 0,
        primary: 2048 | 16
        /* KeyCode.UpArrow */
      }
    });
  }
  runInlineChatCommand(_accessor, ctrl, _editor, ..._args) {
    ctrl.arrowOut(true);
  }
};
var $12b = class extends $Y2b {
  constructor() {
    super({
      id: "inlineChat.arrowOutDown",
      title: localize(7470, null),
      precondition: $7m.and($aAb, $fAb, EditorContextKeys.isEmbeddedDiffEditor.negate(), $OD.negate()),
      keybinding: {
        weight: 0,
        primary: 2048 | 18
        /* KeyCode.DownArrow */
      }
    });
  }
  runInlineChatCommand(_accessor, ctrl, _editor, ..._args) {
    ctrl.arrowOut(false);
  }
};
var $22b = class extends $25 {
  constructor() {
    super({
      id: "inlineChat.focus",
      title: localize2(7479, "Focus Input"),
      f1: true,
      category: $Y2b.category,
      precondition: $7m.and(EditorContextKeys.editorTextFocus, $_zb, $aAb.negate(), $OD.negate()),
      keybinding: [{
        weight: 0 + 10,
        // win against core_command
        when: $7m.and($iAb.isEqualTo("above"), EditorContextKeys.isEmbeddedDiffEditor.negate()),
        primary: 2048 | 18
      }, {
        weight: 0 + 10,
        // win against core_command
        when: $7m.and($iAb.isEqualTo("below"), EditorContextKeys.isEmbeddedDiffEditor.negate()),
        primary: 2048 | 16
      }]
    });
  }
  runEditorCommand(_accessor, editor, ..._args) {
    $cHb.get(editor)?.focus();
  }
};
var $32b = class extends $Y2b {
  constructor() {
    super({
      id: $sAb,
      title: localize2(7480, "Accept Changes"),
      shortTitle: localize(7471, null),
      icon: $6l.check,
      f1: true,
      precondition: $7m.and($_zb, $7m.or($lAb.toNegated(), $oAb.notEqualsTo(
        "preview"
        /* EditMode.Preview */
      ))),
      keybinding: [{
        weight: 200 + 10,
        primary: 2048 | 3
      }],
      menu: [{
        id: $yAb,
        group: "0_main",
        order: 1,
        when: $7m.and(ChatContextKeys.inputHasText.toNegated(), $pAb.toNegated(), $qAb.isEqualTo(
          "messagesAndEdits"
          /* InlineChatResponseType.MessagesAndEdits */
        ))
      }, {
        id: $AAb,
        group: "navigation",
        order: 1
      }]
    });
  }
  async runInlineChatCommand(_accessor, ctrl, _editor, hunk) {
    ctrl.acceptHunk(hunk);
  }
};
var $42b = class extends $Y2b {
  constructor() {
    super({
      id: $tAb,
      title: localize(7472, null),
      icon: $6l.chromeClose,
      precondition: $_zb,
      menu: [{
        id: $yAb,
        group: "0_main",
        order: 2,
        when: $7m.and(ChatContextKeys.inputHasText.toNegated(), $pAb.negate(), $qAb.isEqualTo(
          "messagesAndEdits"
          /* InlineChatResponseType.MessagesAndEdits */
        ), $oAb.isEqualTo(
          "live"
          /* EditMode.Live */
        ))
      }, {
        id: $AAb,
        group: "navigation",
        order: 2
      }],
      keybinding: {
        weight: 100,
        primary: 9,
        when: $qAb.isEqualTo(
          "messagesAndEdits"
          /* InlineChatResponseType.MessagesAndEdits */
        )
      }
    });
  }
  async runInlineChatCommand(_accessor, ctrl, _editor, hunk) {
    return ctrl.discardHunk(hunk);
  }
};
var $52b = class extends $Y2b {
  constructor() {
    super({
      id: $uAb,
      title: localize2(7481, "Rerun Request"),
      shortTitle: localize(7473, null),
      f1: false,
      icon: $6l.refresh,
      precondition: $_zb,
      menu: {
        id: $yAb,
        group: "0_main",
        order: 5,
        when: $7m.and(ChatContextKeys.inputHasText.toNegated(), $pAb.negate(), $qAb.notEqualsTo(
          "none"
          /* InlineChatResponseType.None */
        ))
      },
      keybinding: {
        weight: 200,
        primary: 2048 | 48
        /* KeyCode.KeyR */
      }
    });
  }
  async runInlineChatCommand(accessor, ctrl, _editor, ..._args) {
    const chatService = accessor.get($qO);
    const chatWidgetService = accessor.get($2Nb);
    const model = ctrl.chatWidget.viewModel?.model;
    if (!model) {
      return;
    }
    const lastRequest2 = model.getRequests().at(-1);
    if (lastRequest2) {
      const widget = chatWidgetService.getWidgetBySessionId(model.sessionId);
      await chatService.resendRequest(lastRequest2, {
        noCommandDetection: false,
        attempt: lastRequest2.attempt + 1,
        location: ctrl.chatWidget.location,
        userSelectedModelId: widget?.input.currentLanguageModel
      });
    }
  }
};
var $62b = class extends $Y2b {
  constructor() {
    super({
      id: "inlineChat.close",
      title: localize(7474, null),
      icon: $6l.close,
      precondition: $_zb,
      keybinding: {
        weight: 100 + 1,
        primary: 9
      },
      menu: [{
        id: $yAb,
        group: "0_main",
        order: 1,
        when: $7m.and($pAb.negate(), $7m.or($qAb.isEqualTo(
          "messages"
          /* InlineChatResponseType.Messages */
        ), $oAb.isEqualTo(
          "preview"
          /* EditMode.Preview */
        )))
      }]
    });
  }
  async runInlineChatCommand(_accessor, ctrl, _editor, ..._args) {
    ctrl.cancelSession();
  }
};
var $72b = class extends $Y2b {
  constructor() {
    super({
      id: "inlineChat.configure",
      title: localize2(7482, "Configure Inline Chat"),
      icon: $6l.settingsGear,
      precondition: $_zb,
      f1: true,
      menu: {
        id: $yAb,
        group: "zzz",
        order: 5
      }
    });
  }
  async runInlineChatCommand(accessor, ctrl, _editor, ..._args) {
    accessor.get($TK).openSettings({ query: "inlineChat" });
  }
};
var $82b = class extends $Y2b {
  constructor() {
    super({
      id: "inlineChat.moveToNextHunk",
      title: localize2(7483, "Move to Next Change"),
      precondition: $_zb,
      f1: true,
      keybinding: {
        weight: 200,
        primary: 65
        /* KeyCode.F7 */
      }
    });
  }
  runInlineChatCommand(accessor, ctrl, editor, ...args2) {
    ctrl.moveHunk(true);
  }
};
var $92b = class extends $Y2b {
  constructor() {
    super({
      id: "inlineChat.moveToPreviousHunk",
      title: localize2(7484, "Move to Previous Change"),
      f1: true,
      precondition: $_zb,
      keybinding: {
        weight: 200,
        primary: 1024 | 65
        /* KeyCode.F7 */
      }
    });
  }
  runInlineChatCommand(accessor, ctrl, editor, ...args2) {
    ctrl.moveHunk(false);
  }
};
var $02b = class extends $Y2b {
  constructor() {
    super({
      id: $vAb,
      title: localize(7475, null),
      icon: $6l.commentDiscussion,
      precondition: $_zb,
      menu: [{
        id: $yAb,
        group: "more",
        order: 1,
        when: $qAb.notEqualsTo(
          "messages"
          /* InlineChatResponseType.Messages */
        )
      }, {
        id: $yAb,
        group: "0_main",
        order: 1,
        when: $7m.and(ChatContextKeys.inputHasText.toNegated(), $qAb.isEqualTo(
          "messages"
          /* InlineChatResponseType.Messages */
        ), $pAb.negate())
      }],
      keybinding: {
        weight: 200,
        primary: 2048 | 18,
        when: ChatContextKeys.inChatInput
      }
    });
  }
  runInlineChatCommand(_accessor, ctrl, _editor, ..._args) {
    return ctrl.viewInChat();
  }
};
var $$2b = class extends $Y2b {
  constructor() {
    super({
      id: $wAb,
      precondition: $7m.and($_zb, $oAb.isEqualTo(
        "live"
        /* EditMode.Live */
      ), $mAb),
      title: localize2(7485, "Toggle Changes"),
      icon: $6l.diffSingle,
      toggled: {
        condition: $nAb
      },
      menu: [{
        id: $yAb,
        group: "zzz",
        when: $7m.and($oAb.isEqualTo(
          "live"
          /* EditMode.Live */
        )),
        order: 1
      }, {
        id: $AAb,
        group: "navigation",
        when: $mAb,
        order: 2
      }]
    });
  }
  runInlineChatCommand(_accessor, ctrl, _editor, hunkInfo) {
    ctrl.toggleDiff(hunkInfo);
  }
};

// out-build/vs/workbench/contrib/notebook/browser/controller/chat/cellChatActions.js
$hJ(class extends $FIb {
  constructor() {
    super({
      id: "notebook.cell.chat.accept",
      title: localize2(8230, "Make Request"),
      icon: $6l.send,
      keybinding: {
        when: $7m.and($_Ib, $aAb, $aBb.negate()),
        weight: 200,
        primary: 3
        /* KeyCode.Enter */
      },
      menu: {
        id: $dJb,
        group: "navigation",
        order: 1,
        when: $aJb.negate()
      },
      f1: false
    });
  }
  async runWithContext(accessor, context) {
    $jJb.get(context.notebookEditor)?.acceptInput();
  }
});
$hJ(class extends $HIb {
  constructor() {
    super({
      id: "notebook.cell.chat.arrowOutUp",
      title: localize(8211, null),
      keybinding: {
        when: $7m.and($_Ib, $aAb, $eAb, $aBb.negate(), $OD.negate()),
        weight: 0 + 7,
        primary: 2048 | 16
        /* KeyCode.UpArrow */
      },
      f1: false
    });
  }
  async runWithContext(accessor, context) {
    const editor = context.notebookEditor;
    const activeCell = context.cell;
    const idx = editor.getCellIndex(activeCell);
    if (typeof idx !== "number") {
      return;
    }
    if (idx < 1 || editor.getLength() === 0) {
      return;
    }
    const newCell = editor.cellAt(idx - 1);
    const newFocusMode = newCell.cellKind === CellKind.Markup && newCell.getEditState() === CellEditState.Preview ? "container" : "editor";
    const focusEditorLine = newCell.textBuffer.getLineCount();
    await editor.focusNotebookCell(newCell, newFocusMode, { focusEditorLine });
  }
});
$hJ(class extends $FIb {
  constructor() {
    super({
      id: "notebook.cell.chat.arrowOutDown",
      title: localize(8212, null),
      keybinding: {
        when: $7m.and($_Ib, $aAb, $fAb, $aBb.negate(), $OD.negate()),
        weight: 0 + 7,
        primary: 2048 | 18
        /* KeyCode.DownArrow */
      },
      f1: false
    });
  }
  async runWithContext(accessor, context) {
    await $jJb.get(context.notebookEditor)?.focusNext();
  }
});
$hJ(class extends $HIb {
  constructor() {
    super({
      id: "notebook.cell.focusChatWidget",
      title: localize(8213, null),
      keybinding: {
        when: $7m.and($WAb, $OD.negate(), $7m.and($7m.has($Beb), EditorContextKeys.editorTextFocus, $nM.notEqualsTo("bottom"), $nM.notEqualsTo("none")), EditorContextKeys.isEmbeddedDiffEditor.negate()),
        weight: 0 + 7,
        primary: 2048 | 16
        /* KeyCode.UpArrow */
      },
      f1: false
    });
  }
  async runWithContext(accessor, context) {
    const index = context.notebookEditor.getCellIndex(context.cell);
    await $jJb.get(context.notebookEditor)?.focusNearestWidget(index, "above");
  }
});
$hJ(class extends $HIb {
  constructor() {
    super({
      id: "notebook.cell.focusNextChatWidget",
      title: localize(8214, null),
      keybinding: {
        when: $7m.and($OD.negate(), $7m.and($7m.has($Beb), EditorContextKeys.editorTextFocus, $nM.notEqualsTo("top"), $nM.notEqualsTo("none")), EditorContextKeys.isEmbeddedDiffEditor.negate()),
        weight: 0 + 7,
        primary: 2048 | 18
        /* KeyCode.DownArrow */
      },
      f1: false,
      precondition: $7m.or($7m.and($VAb.negate(), $aBb), $7m.and($VAb, $aBb.negate()))
    });
  }
  async runWithContext(accessor, context) {
    const index = context.notebookEditor.getCellIndex(context.cell);
    await $jJb.get(context.notebookEditor)?.focusNearestWidget(index, "below");
  }
});
$hJ(class extends $FIb {
  constructor() {
    super({
      id: "notebook.cell.chat.stop",
      title: localize2(8231, "Stop Request"),
      icon: $6l.debugStop,
      menu: {
        id: $dJb,
        group: "navigation",
        order: 1,
        when: $aJb
      },
      f1: false
    });
  }
  async runWithContext(accessor, context) {
    $jJb.get(context.notebookEditor)?.cancelCurrentRequest(false);
  }
});
$hJ(class extends $FIb {
  constructor() {
    super({
      id: "notebook.cell.chat.close",
      title: localize2(8232, "Close Chat"),
      icon: $6l.close,
      menu: {
        id: $eJb,
        group: "navigation",
        order: 2
      },
      f1: false
    });
  }
  async runWithContext(accessor, context) {
    $jJb.get(context.notebookEditor)?.dismiss(false);
  }
});
$hJ(class extends $FIb {
  constructor() {
    super({
      id: "notebook.cell.chat.acceptChanges",
      title: localize2(8233, "Accept Changes"),
      shortTitle: localize(8215, null),
      icon: $6l.check,
      tooltip: localize(8216, null),
      keybinding: [
        {
          when: $7m.and($_Ib, $aAb, $aBb.negate()),
          weight: 100 + 10,
          primary: 2048 | 3
        },
        {
          when: $7m.and($_Ib, $aAb, $bJb, $aBb.negate()),
          weight: 0 + 10,
          primary: 9
          /* KeyCode.Escape */
        },
        {
          when: $7m.and($WAb, $7m.not($Beb), $aBb.negate(), $cJb.isEqualTo("below")),
          primary: 2048 | 3,
          weight: 200
          /* KeybindingWeight.WorkbenchContrib */
        }
      ],
      menu: [
        {
          id: $fJb,
          group: "0_main",
          order: 0,
          when: $qAb.notEqualsTo(
            "messages"
            /* InlineChatResponseType.Messages */
          )
        }
      ],
      f1: false
    });
  }
  async runWithContext(accessor, context) {
    $jJb.get(context.notebookEditor)?.acceptSession();
  }
});
$hJ(class extends $FIb {
  constructor() {
    super({
      id: "notebook.cell.chat.discard",
      title: localize(8217, null),
      icon: $6l.discard,
      keybinding: {
        when: $7m.and($_Ib, $aAb, $bJb.negate(), $aBb.negate()),
        weight: 100,
        primary: 9
        /* KeyCode.Escape */
      },
      menu: {
        id: $fJb,
        group: "0_main",
        order: 1
      },
      f1: false
    });
  }
  async runWithContext(accessor, context) {
    $jJb.get(context.notebookEditor)?.discard();
  }
});
async function startChat(accessor, context, index, input, autoSend, source) {
  const configurationService = accessor.get($kl);
  const commandService = accessor.get($sn);
  if (configurationService.getValue($rM.cellGenerate) || configurationService.getValue($rM.cellChat)) {
    const activeCell = context.notebookEditor.getActiveCell();
    const targetCell = activeCell?.getTextLength() === 0 && source !== "insertToolbar" ? activeCell : await $J2b(accessor, context, CellKind.Code, "below", true);
    if (targetCell) {
      targetCell.enableAutoLanguageDetection();
      await context.notebookEditor.revealFirstLineIfOutsideViewport(targetCell);
      const codeEditor = context.notebookEditor.codeEditors.find((ce) => ce[0] === targetCell)?.[1];
      if (codeEditor) {
        codeEditor.focus();
        commandService.executeCommand("inlineChat.start");
      }
    }
  }
}
$hJ(class extends $FIb {
  constructor() {
    super({
      id: "notebook.cell.chat.start",
      title: {
        value: "$(sparkle) " + localize(8218, null),
        original: "$(sparkle) Generate"
      },
      tooltip: localize(8219, null),
      metadata: {
        description: localize(8220, null),
        args: [
          {
            name: "args",
            schema: {
              type: "object",
              required: ["index"],
              properties: {
                "index": {
                  type: "number"
                },
                "input": {
                  type: "string"
                },
                "autoSend": {
                  type: "boolean"
                }
              }
            }
          }
        ]
      },
      f1: false,
      keybinding: {
        when: $7m.and($WAb, $1Ab.isEqualTo(true), $7m.not($Beb), $iJb, $7m.or($7m.equals(`config.${$rM.cellChat}`, true), $7m.equals(`config.${$rM.cellGenerate}`, true))),
        weight: 200,
        primary: 2048 | 39,
        secondary: [$$e(
          2048 | 41,
          39
          /* KeyCode.KeyI */
        )]
      },
      menu: [
        {
          id: $bJ.NotebookCellBetween,
          group: "inline",
          order: -1,
          when: $7m.and($1Ab.isEqualTo(true), $iJb, $7m.or($7m.equals(`config.${$rM.cellChat}`, true), $7m.equals(`config.${$rM.cellGenerate}`, true)))
        }
      ]
    });
  }
  getEditorContextFromArgsOrActive(accessor, ...args2) {
    const [firstArg] = args2;
    if (!firstArg) {
      const notebookEditor2 = $JIb(accessor);
      if (!notebookEditor2) {
        return void 0;
      }
      const activeCell = notebookEditor2.getActiveCell();
      if (!activeCell) {
        return void 0;
      }
      return {
        cell: activeCell,
        notebookEditor: notebookEditor2,
        input: void 0,
        autoSend: void 0
      };
    }
    if (typeof firstArg !== "object" || typeof firstArg.index !== "number") {
      return void 0;
    }
    const notebookEditor = $JIb(accessor);
    if (!notebookEditor) {
      return void 0;
    }
    const cell = firstArg.index <= 0 ? void 0 : notebookEditor.cellAt(firstArg.index - 1);
    return {
      cell,
      notebookEditor,
      input: firstArg.input,
      autoSend: firstArg.autoSend
    };
  }
  async runWithContext(accessor, context) {
    const index = Math.max(0, context.cell ? context.notebookEditor.getCellIndex(context.cell) + 1 : 0);
    await startChat(accessor, context, index, context.input, context.autoSend, context.source);
  }
});
$hJ(class extends $FIb {
  constructor() {
    super({
      id: "notebook.cell.chat.startAtTop",
      title: {
        value: "$(sparkle) " + localize(8221, null),
        original: "$(sparkle) Generate"
      },
      tooltip: localize(8222, null),
      f1: false,
      menu: [
        {
          id: $bJ.NotebookCellListTop,
          group: "inline",
          order: -1,
          when: $7m.and($1Ab.isEqualTo(true), $iJb, $7m.or($7m.equals(`config.${$rM.cellChat}`, true), $7m.equals(`config.${$rM.cellGenerate}`, true)))
        }
      ]
    });
  }
  async runWithContext(accessor, context) {
    await startChat(accessor, context, 0, "", false);
  }
});
$dJ.appendMenuItem($bJ.NotebookToolbar, {
  command: {
    id: "notebook.cell.chat.start",
    icon: $6l.sparkle,
    title: localize(8223, null),
    tooltip: localize(8224, null)
  },
  order: -10,
  group: "navigation/add",
  when: $7m.and($1Ab.isEqualTo(true), $7m.notEquals("config.notebook.insertToolbarLocation", "betweenCells"), $7m.notEquals("config.notebook.insertToolbarLocation", "hidden"), $iJb, $7m.or($7m.equals(`config.${$rM.cellChat}`, true), $7m.equals(`config.${$rM.cellGenerate}`, true)))
});
$hJ(class extends $FIb {
  constructor() {
    super({
      id: "notebook.cell.chat.focus",
      title: localize(8225, null),
      keybinding: [
        {
          when: $7m.and($WAb, $7m.not($Beb), $cJb.isEqualTo("above")),
          primary: 2048 | 18,
          weight: 200
          /* KeybindingWeight.WorkbenchContrib */
        },
        {
          when: $7m.and($WAb, $7m.not($Beb), $cJb.isEqualTo("below")),
          primary: 2048 | 16,
          weight: 200
          /* KeybindingWeight.WorkbenchContrib */
        }
      ],
      f1: false
    });
  }
  async runWithContext(accessor, context) {
    $jJb.get(context.notebookEditor)?.focus();
  }
});
$hJ(class extends $FIb {
  constructor() {
    super({
      id: "notebook.cell.chat.focusNextCell",
      title: localize(8226, null),
      keybinding: [
        {
          when: $7m.and($_Ib, $aAb),
          primary: 2048 | 18,
          weight: 200
          /* KeybindingWeight.WorkbenchContrib */
        }
      ],
      f1: false
    });
  }
  async runWithContext(accessor, context) {
    $jJb.get(context.notebookEditor)?.focusNext();
  }
});
$hJ(class extends $FIb {
  constructor() {
    super({
      id: "notebook.cell.chat.focusPreviousCell",
      title: localize(8227, null),
      keybinding: [
        {
          when: $7m.and($_Ib, $aAb),
          primary: 2048 | 16,
          weight: 200
          /* KeybindingWeight.WorkbenchContrib */
        }
      ],
      f1: false
    });
  }
  async runWithContext(accessor, context) {
    $jJb.get(context.notebookEditor)?.focusAbove();
  }
});
$hJ(class extends $FIb {
  constructor() {
    super({
      id: "notebook.cell.chat.previousFromHistory",
      title: localize2(8234, "Previous From History"),
      precondition: $7m.and($_Ib, $aAb),
      keybinding: {
        when: $7m.and($_Ib, $aAb),
        weight: 0 + 10,
        primary: 16
      },
      f1: false
    });
  }
  async runWithContext(accessor, context) {
    $jJb.get(context.notebookEditor)?.populateHistory(true);
  }
});
$hJ(class extends $FIb {
  constructor() {
    super({
      id: "notebook.cell.chat.nextFromHistory",
      title: localize2(8235, "Next From History"),
      precondition: $7m.and($_Ib, $aAb),
      keybinding: {
        when: $7m.and($_Ib, $aAb),
        weight: 0 + 10,
        primary: 18
        /* KeyCode.DownArrow */
      },
      f1: false
    });
  }
  async runWithContext(accessor, context) {
    $jJb.get(context.notebookEditor)?.populateHistory(false);
  }
});
$hJ(class extends $HIb {
  constructor() {
    super({
      id: "notebook.cell.chat.restore",
      title: localize2(8236, "Generate"),
      icon: $6l.sparkle,
      menu: {
        id: $bJ.NotebookCellTitle,
        group: $yIb,
        order: 0,
        when: $7m.and($1Ab.isEqualTo(true), $iJb, $lBb, $7m.equals(`config.${$rM.cellChat}`, true))
      },
      f1: false
    });
  }
  async runWithContext(accessor, context) {
    const cell = context.cell;
    if (!cell) {
      return;
    }
    const notebookEditor = context.notebookEditor;
    const controller = $jJb.get(notebookEditor);
    if (!controller) {
      return;
    }
    const prompt = controller.getPromptFromCache(cell);
    if (prompt) {
      controller.restore(cell, prompt);
    }
  }
});
var $_2b = class extends $Y2b {
  constructor() {
    super({
      id: "notebook.inlineChat.acceptChangesAndRun",
      title: localize2(8237, "Accept and Run"),
      shortTitle: localize(8228, null),
      tooltip: localize(8229, null),
      icon: $6l.check,
      f1: true,
      precondition: $7m.and($1Ab.isEqualTo(true), $_zb, $7m.or($lAb.toNegated(), $oAb.notEqualsTo(
        "preview"
        /* EditMode.Preview */
      ))),
      keybinding: void 0,
      menu: [{
        id: $yAb,
        group: "0_main",
        order: 2,
        when: $7m.and($1Ab.isEqualTo(true), ChatContextKeys.inputHasText.toNegated(), $pAb.toNegated(), $qAb.isEqualTo(
          "messagesAndEdits"
          /* InlineChatResponseType.MessagesAndEdits */
        ))
      }]
    });
  }
  async runInlineChatCommand(accessor, ctrl, codeEditor, hunk) {
    const editor = $CIb(accessor.get($mJ));
    if (!editor) {
      return;
    }
    const matchedCell = editor.notebookEditor.codeEditors.find((e) => e[1] === codeEditor);
    const cell = matchedCell?.[0];
    if (!cell) {
      return;
    }
    ctrl.acceptSession();
    return editor.notebookEditor.executeNotebookCells(Iterable.single(cell));
  }
};
$hJ($_2b);

// out-build/vs/workbench/contrib/notebook/browser/controller/chat/notebook.chat.contribution.js
var NotebookKernelVariableKey = "kernelVariable";
var NotebookChatContribution = class NotebookChatContribution2 extends $3c {
  static {
    this.ID = "workbench.contrib.notebookChatContribution";
  }
  constructor(contextKeyService, chatAgentService, b, c, f, g) {
    super();
    this.b = b;
    this.c = c;
    this.f = f;
    this.g = g;
    this.a = $iJb.bindTo(contextKeyService);
    const updateNotebookAgentStatus = () => {
      const hasNotebookAgent = Boolean(chatAgentService.getDefaultAgent(ChatAgentLocation.Notebook));
      this.a.set(hasNotebookAgent);
    };
    updateNotebookAgentStatus();
    this.B(chatAgentService.onDidChangeAgents(updateNotebookAgentStatus));
    this.B(this.g.completionProvider.register({ scheme: $1Nb.INPUT_SCHEME, hasAccessToAllModels: true }, {
      _debugDisplayName: "chatKernelDynamicCompletions",
      triggerCharacters: [$wO],
      provideCompletionItems: async (model, position, _context, token) => {
        const widget = this.c.getWidgetByInputUri(model.uri);
        if (!widget || !widget.supportsFileReferences) {
          return null;
        }
        if (widget.location !== ChatAgentLocation.Notebook) {
          return null;
        }
        const variableNameDef = new RegExp(`${$wO}\\w*`, "g");
        const range = $T2b(model, position, variableNameDef, true);
        if (!range) {
          return null;
        }
        const result = { suggestions: [] };
        const afterRange = new $9C(position.lineNumber, range.replace.startColumn, position.lineNumber, range.replace.startColumn + `${$wO}${NotebookKernelVariableKey}:`.length);
        result.suggestions.push({
          label: `${$wO}${NotebookKernelVariableKey}`,
          insertText: `${$wO}${NotebookKernelVariableKey}:`,
          detail: localize(8238, null),
          range,
          kind: 18,
          command: { id: $a3b.ID, title: $a3b.ID, arguments: [{ widget, range: afterRange }] },
          sortText: "z"
        });
        await this.h(widget, result, range, token);
        return result;
      }
    }));
  }
  async h(widget, result, info, token) {
    let pattern;
    if (info.varWord?.word && info.varWord.word.startsWith($wO)) {
      pattern = info.varWord.word.toLowerCase().slice(1);
    }
    const notebook = $Qrb(this.b.activeEditorPane)?.getViewModel()?.notebookDocument;
    if (!notebook) {
      return;
    }
    const selectedKernel = this.f.getMatchingKernel(notebook).selected;
    const hasVariableProvider = selectedKernel?.hasVariableProvider;
    if (!hasVariableProvider) {
      return;
    }
    const variables = await selectedKernel.provideVariables(notebook.uri, void 0, "named", 0, CancellationToken.None);
    for await (const variable of variables) {
      if (pattern && !variable.name.toLowerCase().includes(pattern)) {
        continue;
      }
      result.suggestions.push({
        label: { label: variable.name, description: variable.type },
        insertText: `${$wO}${NotebookKernelVariableKey}:${variable.name} `,
        filterText: `${$wO}${variable.name}`,
        range: info,
        kind: 4,
        sortText: "z",
        command: { id: $a3b.ID, title: $a3b.ID, arguments: [{ widget, range: info.insert, variable: variable.name }] },
        detail: variable.type,
        documentation: variable.value
      });
    }
  }
};
NotebookChatContribution = __decorate([
  __param(0, $on),
  __param(1, $ZO),
  __param(2, $mJ),
  __param(3, $2Nb),
  __param(4, $CL),
  __param(5, $mP)
], NotebookChatContribution);
var $a3b = class _$a3b extends $gJ {
  constructor() {
    super({
      id: _$a3b.ID,
      title: ""
      // not displayed
    });
  }
  static {
    this.ID = "notebook.chat.selectAndInsertKernelVariable";
  }
  async run(accessor, ...args2) {
    const editorService = accessor.get($mJ);
    const notebookKernelService = accessor.get($CL);
    const quickInputService = accessor.get($1M);
    const notebook = $Qrb(editorService.activeEditorPane)?.getViewModel()?.notebookDocument;
    if (!notebook) {
      return;
    }
    const context = args2[0];
    if (!context || !("widget" in context) || !("range" in context)) {
      return;
    }
    const widget = context.widget;
    const range = context.range;
    const variable = context.variable;
    if (variable !== void 0) {
      this.a(widget, variable, range, false);
      return;
    }
    const selectedKernel = notebookKernelService.getMatchingKernel(notebook).selected;
    const hasVariableProvider = selectedKernel?.hasVariableProvider;
    if (!hasVariableProvider) {
      return;
    }
    const variables = await selectedKernel.provideVariables(notebook.uri, void 0, "named", 0, CancellationToken.None);
    const quickPickItems = [];
    for await (const variable2 of variables) {
      quickPickItems.push({
        label: variable2.name,
        description: variable2.value,
        detail: variable2.type
      });
    }
    const pickedVariable = await quickInputService.pick(quickPickItems, { placeHolder: "Select a kernel variable" });
    if (!pickedVariable) {
      return;
    }
    this.a(widget, pickedVariable.label, range, true);
  }
  a(widget, variableName, range, updateText) {
    if (range) {
      const text2 = `#kernelVariable:${variableName}`;
      if (updateText) {
        const editor = widget.inputEditor;
        const success = editor.executeEdits("chatInsertFile", [{ range, text: text2 + " " }]);
        if (!success) {
          return;
        }
      }
      widget.getContrib($aOb.ID)?.addReference({
        id: "vscode.notebook.variable",
        range: { startLineNumber: range.startLineNumber, startColumn: range.startColumn, endLineNumber: range.endLineNumber, endColumn: range.startColumn + text2.length },
        data: variableName,
        fullName: variableName,
        icon: $3l.variable
      });
    } else {
      widget.attachmentModel.addContext({
        id: "vscode.notebook.variable",
        name: variableName,
        value: variableName,
        icon: $3l.variable,
        isDynamic: true
      });
    }
  }
};
$hJ($a3b);
$PL(
  NotebookChatContribution.ID,
  NotebookChatContribution,
  2
  /* WorkbenchPhase.BlockRestore */
);

// out-build/vs/workbench/contrib/notebook/browser/contrib/notebookVariables/notebookVariableContextKeys.js
var $b3b = new $nn("notebookVariableViewEnabled", false);

// out-build/vs/workbench/contrib/notebook/browser/controller/variablesActions.js
var OPEN_VARIABLES_VIEW_COMMAND_ID = "notebook.openVariablesView";
$hJ(class OpenVariablesViewAction extends $FIb {
  constructor() {
    super({
      id: OPEN_VARIABLES_VIEW_COMMAND_ID,
      title: localize2(8359, "Variables"),
      icon: $3Kb,
      menu: [
        {
          id: $bJ.InteractiveToolbar,
          group: "navigation",
          when: $7m.and(
            $uBb,
            // jupyter extension currently contributes their own goto variables button
            $7m.notEquals("jupyter.kernel.isjupyter", true),
            $b3b
          )
        },
        {
          id: $bJ.EditorTitle,
          order: -1,
          group: "navigation",
          when: $7m.and(
            $uBb,
            // jupyter extension currently contributes their own goto variables button
            $7m.notEquals("jupyter.kernel.isjupyter", true),
            $7m.notEquals("config.notebook.globalToolbar", true),
            $b3b
          )
        },
        {
          id: $bJ.NotebookToolbar,
          order: -1,
          group: "navigation",
          when: $7m.and(
            $uBb,
            // jupyter extension currently contributes their own goto variables button
            $7m.notEquals("jupyter.kernel.isjupyter", true),
            $7m.equals("config.notebook.globalToolbar", true),
            $b3b
          )
        }
      ]
    });
  }
  async runWithContext(accessor, context) {
    const variableViewId = "workbench.notebook.variables";
    accessor.get($uob).openView(variableViewId, true);
  }
});

// out-build/vs/workbench/contrib/snippets/browser/commands/abstractSnippetsActions.js
var defaultOptions3 = {
  category: localize2(9836, "Snippets")
};
var $c3b = class extends $gJ {
  constructor(desc) {
    super({ ...defaultOptions3, ...desc });
  }
};
var $d3b = class extends $25 {
  constructor(desc) {
    super({ ...defaultOptions3, ...desc });
  }
};

// out-build/vs/workbench/contrib/snippets/browser/commands/fileTemplateSnippets.js
var $e3b = class _$e3b extends $c3b {
  static {
    this.Id = "workbench.action.populateFileFromSnippet";
  }
  constructor() {
    super({
      id: _$e3b.Id,
      title: localize2(9856, "Fill File with Snippet"),
      f1: true
    });
  }
  async run(accessor) {
    const snippetService = accessor.get($Isb);
    const quickInputService = accessor.get($1M);
    const editorService = accessor.get($mJ);
    const langService = accessor.get($1E);
    const editor = $S5(editorService.activeTextEditorControl);
    if (!editor || !editor.hasModel()) {
      return;
    }
    const snippets = await snippetService.getSnippets(void 0, { fileTemplateSnippets: true, noRecencySort: true, includeNoPrefixSnippets: true });
    if (snippets.length === 0) {
      return;
    }
    const selection = await this.c(quickInputService, langService, snippets);
    if (!selection) {
      return;
    }
    if (editor.hasModel()) {
      $Dcb.get(editor)?.apply([{
        range: editor.getModel().getFullModelRange(),
        template: selection.snippet.body
      }]);
      editor.getModel().setLanguage(langService.createById(selection.langId), _$e3b.Id);
      editor.focus();
    }
  }
  async c(quickInputService, langService, snippets) {
    const all = [];
    for (const snippet of snippets) {
      if ($Pb(snippet.scopes)) {
        all.push({ langId: "", snippet });
      } else {
        for (const langId of snippet.scopes) {
          all.push({ langId, snippet });
        }
      }
    }
    const picks = [];
    const groups = $Eb(all, (a, b) => $Tf(a.langId, b.langId));
    for (const group2 of groups) {
      let first = true;
      for (const item of group2) {
        if (first) {
          picks.push({
            type: "separator",
            label: langService.getLanguageName(item.langId) ?? item.langId
          });
          first = false;
        }
        picks.push({
          snippet: item,
          label: item.snippet.prefix || item.snippet.name,
          detail: item.snippet.description
        });
      }
    }
    const pick = await quickInputService.pick(picks, {
      placeHolder: localize(9855, null),
      matchOnDetail: true
    });
    return pick?.snippet;
  }
};

// out-build/vs/workbench/contrib/codeEditor/browser/emptyTextEditorHint/emptyTextEditorHint.js
var $127 = $;
var $f3b = "workbench.editor.empty.hint";
var $g3b = class $g3b2 {
  static {
    this.ID = "editor.contrib.emptyTextEditorHint";
  }
  constructor(c, f, g, h3, i2, j, k, l, m, n, o) {
    this.c = c;
    this.f = f;
    this.g = g;
    this.h = h3;
    this.i = i2;
    this.j = j;
    this.k = k;
    this.l = l;
    this.m = m;
    this.n = n;
    this.o = o;
    this.a = [];
    this.a.push(this.c.onDidChangeModel(() => this.r()));
    this.a.push(this.c.onDidChangeModelLanguage(() => this.r()));
    this.a.push(this.c.onDidChangeModelContent(() => this.r()));
    this.a.push(this.l.onDidChangeAgents(() => this.r()));
    this.a.push(this.c.onDidChangeModelDecorations(() => this.r()));
    this.a.push(this.c.onDidChangeConfiguration((e) => {
      if (e.hasChanged(
        96
        /* EditorOption.readOnly */
      )) {
        this.r();
      }
    }));
    this.a.push(this.h.onDidChangeConfiguration((e) => {
      if (e.affectsConfiguration($f3b)) {
        this.r();
      }
    }));
    this.a.push(k.onWillStartSession((editor) => {
      if (this.c === editor) {
        this.b?.dispose();
      }
    }));
    this.a.push(k.onDidEndSession((e) => {
      if (this.c === e.editor) {
        this.r();
      }
    }));
  }
  p() {
    return { clickable: true };
  }
  q() {
    const configValue = this.h.getValue($f3b);
    if (configValue === "hidden") {
      return false;
    }
    if (this.c.getOption(
      96
      /* EditorOption.readOnly */
    )) {
      return false;
    }
    const model = this.c.getModel();
    const languageId = model?.getLanguageId();
    if (!model || languageId === $HS || languageId === $JS || languageId === $QN) {
      return false;
    }
    if (this.k.getSession(this.c, model.uri)) {
      return false;
    }
    if (this.c.getModel()?.getValueLength()) {
      return false;
    }
    const hasConflictingDecorations = Boolean(this.c.getLineDecorations(1)?.find((d) => d.options.beforeContentClassName || d.options.afterContentClassName || d.options.before?.content || d.options.after?.content));
    if (hasConflictingDecorations) {
      return false;
    }
    const hasEditorAgents = Boolean(this.l.getDefaultAgent(ChatAgentLocation.Editor));
    const shouldRenderDefaultHint = model?.uri.scheme === Schemas.untitled && languageId === $KF;
    return hasEditorAgents || shouldRenderDefaultHint;
  }
  r() {
    const shouldRenderHint = this.q();
    if (shouldRenderHint && !this.b) {
      this.b = new EmptyTextEditorHintContentWidget(this.c, this.p(), this.f, this.g, this.h, this.i, this.j, this.l, this.m, this.n, this.o);
    } else if (!shouldRenderHint && this.b) {
      this.b.dispose();
      this.b = void 0;
    }
  }
  dispose() {
    $Xc(this.a);
    this.b?.dispose();
  }
};
$g3b = __decorate([
  __param(1, $iJ),
  __param(2, $sn),
  __param(3, $kl),
  __param(4, $5$),
  __param(5, $Ty),
  __param(6, $kGb),
  __param(7, $ZO),
  __param(8, $zv),
  __param(9, $Vu),
  __param(10, $50)
], $g3b);
var EmptyTextEditorHintContentWidget = class _EmptyTextEditorHintContentWidget {
  static {
    this.a = "editor.widget.emptyHint";
  }
  constructor(h3, i2, j, k, l, m, n, o, p, q, r2) {
    this.h = h3;
    this.i = i2;
    this.j = j;
    this.k = k;
    this.l = l;
    this.m = m;
    this.n = n;
    this.o = o;
    this.p = p;
    this.q = q;
    this.r = r2;
    this.f = false;
    this.g = "";
    this.c = new $2c();
    this.c.add(this.h.onDidChangeConfiguration((e) => {
      if (this.b && e.hasChanged(
        52
        /* EditorOption.fontInfo */
      )) {
        this.h.applyFontInfo(this.b);
      }
    }));
    const onDidFocusEditorText = Event2.debounce(this.h.onDidFocusEditorText, () => void 0, 500);
    this.c.add(onDidFocusEditorText(() => {
      if (this.h.hasTextFocus() && this.f && this.g && this.l.getValue(
        "accessibility.verbosity.emptyEditorHint"
        /* AccessibilityVerbositySettingId.EmptyEditorHint */
      )) {
        $_Z(this.g);
      }
    }));
    this.h.addContentWidget(this);
  }
  getId() {
    return _EmptyTextEditorHintContentWidget.a;
  }
  s(e) {
    const disableHint = () => {
      this.l.updateValue($f3b, "hidden");
      this.dispose();
      this.h.focus();
    };
    if (!e) {
      disableHint();
      return;
    }
    this.r.showContextMenu({
      getAnchor: () => {
        return new $lf($Qj(), e);
      },
      getActions: () => {
        return [
          {
            id: "workench.action.disableEmptyEditorHint",
            label: localize(5182, null),
            tooltip: localize(5183, null),
            enabled: true,
            class: void 0,
            run: () => {
              disableHint();
            }
          }
        ];
      }
    });
  }
  t(providers2) {
    const providerName = (providers2.length === 1 ? providers2[0].fullName : void 0) ?? this.q.nameShort;
    const inlineChatId = "inlineChat.start";
    let ariaLabel = `Ask ${providerName} something or start typing to dismiss.`;
    const handleClick = () => {
      this.p.publicLog2("workbenchActionExecuted", {
        id: "inlineChat.hintAction",
        from: "hint"
      });
      this.k.executeCommand(inlineChatId, { from: "hint" });
    };
    const hintHandler = {
      disposables: this.c,
      callback: (index, _event) => {
        switch (index) {
          case "0":
            handleClick();
            break;
        }
      }
    };
    const hintElement = $127("empty-hint-text");
    hintElement.style.display = "block";
    const keybindingHint = this.n.lookupKeybinding(inlineChatId);
    const keybindingHintLabel = keybindingHint?.getLabel();
    if (keybindingHint && keybindingHintLabel) {
      const actionPart = localize(5184, null, keybindingHintLabel, providerName);
      const [before, after] = actionPart.split(keybindingHintLabel).map((fragment) => {
        if (this.i.clickable) {
          const hintPart = $127("a", void 0, fragment);
          hintPart.style.fontStyle = "italic";
          hintPart.style.cursor = "pointer";
          this.c.add($_i(hintPart, $7j.CONTEXT_MENU, (e) => this.s(e)));
          this.c.add($_i(hintPart, $7j.CLICK, handleClick));
          return hintPart;
        } else {
          const hintPart = $127("span", void 0, fragment);
          hintPart.style.fontStyle = "italic";
          return hintPart;
        }
      });
      hintElement.appendChild(before);
      const label3 = hintHandler.disposables.add(new $32(hintElement, OS));
      label3.set(keybindingHint);
      label3.element.style.width = "min-content";
      label3.element.style.display = "inline";
      if (this.i.clickable) {
        label3.element.style.cursor = "pointer";
        this.c.add($_i(label3.element, $7j.CONTEXT_MENU, (e) => this.s(e)));
        this.c.add($_i(label3.element, $7j.CLICK, handleClick));
      }
      hintElement.appendChild(after);
      const typeToDismiss = localize(5185, null);
      const textHint2 = $127("span", void 0, typeToDismiss);
      textHint2.style.fontStyle = "italic";
      hintElement.appendChild(textHint2);
      ariaLabel = actionPart.concat(typeToDismiss);
    } else {
      const hintMsg = localize(5186, null, providerName);
      const rendered = $RZ(hintMsg, { actionHandler: hintHandler });
      hintElement.appendChild(rendered);
    }
    return { ariaLabel, hintElement };
  }
  u() {
    const hintHandler = {
      disposables: this.c,
      callback: (index, event) => {
        switch (index) {
          case "0":
            languageOnClickOrTap(event.browserEvent);
            break;
          case "1":
            snippetOnClickOrTap(event.browserEvent);
            break;
          case "2":
            chooseEditorOnClickOrTap(event.browserEvent);
            break;
          case "3":
            this.s();
            break;
        }
      }
    };
    const languageOnClickOrTap = async (e) => {
      e.stopPropagation();
      this.h.focus();
      this.p.publicLog2("workbenchActionExecuted", {
        id: $UUb.ID,
        from: "hint"
      });
      await this.k.executeCommand($UUb.ID);
      this.h.focus();
    };
    const snippetOnClickOrTap = async (e) => {
      e.stopPropagation();
      this.p.publicLog2("workbenchActionExecuted", {
        id: $e3b.Id,
        from: "hint"
      });
      await this.k.executeCommand($e3b.Id);
    };
    const chooseEditorOnClickOrTap = async (e) => {
      e.stopPropagation();
      const activeEditorInput = this.j.activeGroup.activeEditor;
      this.p.publicLog2("workbenchActionExecuted", {
        id: "welcome.showNewFileEntries",
        from: "hint"
      });
      const newEditorSelected = await this.k.executeCommand("welcome.showNewFileEntries", { from: "hint" });
      if (newEditorSelected && activeEditorInput !== null && activeEditorInput.resource?.scheme === Schemas.untitled) {
        this.j.activeGroup.closeEditor(activeEditorInput, { preserveFocus: true });
      }
    };
    const hintMsg = localize(5187, null);
    const hintElement = $RZ(hintMsg, {
      actionHandler: hintHandler,
      renderCodeSegments: false
    });
    hintElement.style.fontStyle = "italic";
    const keybindingsLookup = [$UUb.ID, $e3b.Id, "welcome.showNewFileEntries"];
    const keybindingLabels = keybindingsLookup.map((id2) => this.n.lookupKeybinding(id2)?.getLabel() ?? id2);
    const ariaLabel = localize(5188, null, ...keybindingLabels);
    for (const anchor of hintElement.querySelectorAll("a")) {
      anchor.style.cursor = "pointer";
      const id2 = keybindingsLookup.shift();
      const title = id2 && this.n.lookupKeybinding(id2)?.getLabel();
      hintHandler.disposables.add(this.m.setupManagedHover($JZ("mouse"), anchor, title ?? ""));
    }
    return { hintElement, ariaLabel };
  }
  getDomNode() {
    if (!this.b) {
      this.b = $127(".empty-editor-hint");
      this.b.style.width = "max-content";
      this.b.style.paddingLeft = "4px";
      const inlineChatProviders = this.o.getActivatedAgents().filter((candidate) => candidate.locations.includes(ChatAgentLocation.Editor));
      const { hintElement, ariaLabel } = !inlineChatProviders.length ? this.u() : this.t(inlineChatProviders);
      this.b.append(hintElement);
      this.g = ariaLabel.concat(localize(
        5189,
        null,
        "accessibility.verbosity.emptyEditorHint"
        /* AccessibilityVerbositySettingId.EmptyEditorHint */
      ));
      this.c.add($_i(this.b, "click", () => {
        this.h.focus();
      }));
      this.h.applyFontInfo(this.b);
    }
    return this.b;
  }
  getPosition() {
    return {
      position: { lineNumber: 1, column: 1 },
      preference: [
        0
        /* ContentWidgetPositionPreference.EXACT */
      ]
    };
  }
  dispose() {
    this.h.removeContentWidget(this);
    $Xc(this.c);
  }
};
$85(
  $g3b.ID,
  $g3b,
  0
  /* EditorContributionInstantiation.Eager */
);

// out-build/vs/workbench/contrib/notebook/browser/contrib/editorHint/emptyCellEditorHint.js
var $h3b = class $h3b2 extends $g3b {
  static {
    this.CONTRIB_ID = "notebook.editor.contrib.emptyCellEditorHint";
  }
  constructor(editor, s, editorGroupsService, commandService, configurationService, hoverService, keybindingService, inlineChatSessionService, chatAgentService, telemetryService, productService, contextMenuService) {
    super(editor, editorGroupsService, commandService, configurationService, hoverService, keybindingService, inlineChatSessionService, chatAgentService, telemetryService, productService, contextMenuService);
    this.s = s;
    const activeEditor = $Qrb(this.s.activeEditorPane);
    if (!activeEditor) {
      return;
    }
    this.a.push(activeEditor.onDidChangeActiveCell(() => this.r()));
  }
  p() {
    return { clickable: false };
  }
  q() {
    const model = this.c.getModel();
    if (!model) {
      return false;
    }
    const isNotebookCell = model?.uri.scheme === Schemas.vscodeNotebookCell;
    if (!isNotebookCell) {
      return false;
    }
    const activeEditor = $Qrb(this.s.activeEditorPane);
    if (!activeEditor || !activeEditor.isDisposed) {
      return false;
    }
    const shouldRenderHint = super.q();
    if (!shouldRenderHint) {
      return false;
    }
    const activeCell = activeEditor.getActiveCell();
    if (activeCell?.uri.fragment !== model.uri.fragment) {
      return false;
    }
    return true;
  }
};
$h3b = __decorate([
  __param(1, $mJ),
  __param(2, $iJ),
  __param(3, $sn),
  __param(4, $kl),
  __param(5, $5$),
  __param(6, $Ty),
  __param(7, $kGb),
  __param(8, $ZO),
  __param(9, $zv),
  __param(10, $Vu),
  __param(11, $50)
], $h3b);
$85(
  $h3b.CONTRIB_ID,
  $h3b,
  0
  /* EditorContributionInstantiation.Eager */
);

// out-build/vs/workbench/contrib/notebook/browser/contrib/clipboard/notebookClipboard.js
var _logging = false;
function toggleLogging() {
  _logging = !_logging;
}
function _log(loggerService, str) {
  if (_logging) {
    loggerService.info(`[NotebookClipboard]: ${str}`);
  }
}
function getFocusedEditor(accessor) {
  const loggerService = accessor.get($wn);
  const editorService = accessor.get($mJ);
  const editor = $Qrb(editorService.activeEditorPane);
  if (!editor) {
    _log(loggerService, "[Revive Webview] No notebook editor found for active editor pane, bypass");
    return;
  }
  if (!editor.hasEditorFocus()) {
    _log(loggerService, "[Revive Webview] Notebook editor is not focused, bypass");
    return;
  }
  if (!editor.hasWebviewFocus()) {
    _log(loggerService, "[Revive Webview] Notebook editor backlayer webview is not focused, bypass");
    return;
  }
  const view = editor.getViewModel();
  if (view && view.viewCells.every((cell) => !cell.outputIsFocused && !cell.outputIsHovered)) {
    return;
  }
  return { editor, loggerService };
}
function getFocusedWebviewDelegate(accessor) {
  const result = getFocusedEditor(accessor);
  if (!result) {
    return;
  }
  const webview = result.editor.getInnerWebview();
  _log(result.loggerService, "[Revive Webview] Notebook editor backlayer webview is focused");
  return webview;
}
function withWebview(accessor, f) {
  const webview = getFocusedWebviewDelegate(accessor);
  if (webview) {
    f(webview);
    return true;
  }
  return false;
}
function withEditor(accessor, f) {
  const result = getFocusedEditor(accessor);
  return result ? f(result.editor) : false;
}
var PRIORITY2 = 105;
$05.addImplementation(PRIORITY2, "notebook-webview", (accessor) => {
  return withWebview(accessor, (webview) => webview.undo());
});
$$5.addImplementation(PRIORITY2, "notebook-webview", (accessor) => {
  return withWebview(accessor, (webview) => webview.redo());
});
$kab?.addImplementation(PRIORITY2, "notebook-webview", (accessor) => {
  return withWebview(accessor, (webview) => webview.copy());
});
$lab?.addImplementation(PRIORITY2, "notebook-webview", (accessor) => {
  return withWebview(accessor, (webview) => webview.paste());
});
$jab?.addImplementation(PRIORITY2, "notebook-webview", (accessor) => {
  return withWebview(accessor, (webview) => webview.cut());
});
function $i3b(editor, activeCell, pasteCells) {
  if (!editor.hasModel()) {
    return false;
  }
  const textModel = editor.textModel;
  if (editor.isReadOnly) {
    return false;
  }
  const originalState = {
    kind: SelectionStateType.Index,
    focus: editor.getFocus(),
    selections: editor.getSelections()
  };
  if (activeCell) {
    const currCellIndex = editor.getCellIndex(activeCell);
    const newFocusIndex = typeof currCellIndex === "number" ? currCellIndex + 1 : 0;
    textModel.applyEdits([
      {
        editType: 1,
        index: newFocusIndex,
        count: 0,
        cells: pasteCells.items.map((cell) => $tL(cell))
      }
    ], true, originalState, () => ({
      kind: SelectionStateType.Index,
      focus: { start: newFocusIndex, end: newFocusIndex + 1 },
      selections: [{ start: newFocusIndex, end: newFocusIndex + pasteCells.items.length }]
    }), void 0, true);
  } else {
    if (editor.getLength() !== 0) {
      return false;
    }
    textModel.applyEdits([
      {
        editType: 1,
        index: 0,
        count: 0,
        cells: pasteCells.items.map((cell) => $tL(cell))
      }
    ], true, originalState, () => ({
      kind: SelectionStateType.Index,
      focus: { start: 0, end: 1 },
      selections: [{ start: 1, end: pasteCells.items.length + 1 }]
    }), void 0, true);
  }
  return true;
}
function $j3b(accessor, editor, targetCell) {
  if (!editor.hasModel()) {
    return false;
  }
  if (editor.hasOutputTextSelection()) {
    getWindow(editor.getDomNode()).document.execCommand("copy");
    return true;
  }
  const clipboardService = accessor.get($30);
  const notebookService = accessor.get($mrb);
  const selections = editor.getSelections();
  if (targetCell) {
    const targetCellIndex = editor.getCellIndex(targetCell);
    const containingSelection = selections.find((selection) => selection.start <= targetCellIndex && targetCellIndex < selection.end);
    if (!containingSelection) {
      clipboardService.writeText(targetCell.getText());
      notebookService.setToCopy([targetCell.model], true);
      return true;
    }
  }
  const selectionRanges = $Rrb(editor, editor.getSelections());
  const selectedCells = $Srb(editor, selectionRanges);
  if (!selectedCells.length) {
    return false;
  }
  clipboardService.writeText(selectedCells.map((cell) => cell.getText()).join("\n"));
  notebookService.setToCopy(selectedCells.map((cell) => cell.model), true);
  return true;
}
function $k3b(accessor, editor, targetCell) {
  if (!editor.hasModel() || editor.isReadOnly) {
    return false;
  }
  const textModel = editor.textModel;
  const clipboardService = accessor.get($30);
  const notebookService = accessor.get($mrb);
  const selections = editor.getSelections();
  if (targetCell) {
    const targetCellIndex = editor.getCellIndex(targetCell);
    const containingSelection2 = selections.find((selection) => selection.start <= targetCellIndex && targetCellIndex < selection.end);
    if (!containingSelection2) {
      clipboardService.writeText(targetCell.getText());
      const focus2 = editor.getFocus();
      const newFocus = focus2.end <= targetCellIndex ? focus2 : { start: focus2.start - 1, end: focus2.end - 1 };
      const newSelections = selections.map((selection) => selection.end <= targetCellIndex ? selection : { start: selection.start - 1, end: selection.end - 1 });
      textModel.applyEdits([
        { editType: 1, index: targetCellIndex, count: 1, cells: [] }
      ], true, { kind: SelectionStateType.Index, focus: editor.getFocus(), selections }, () => ({ kind: SelectionStateType.Index, focus: newFocus, selections: newSelections }), void 0, true);
      notebookService.setToCopy([targetCell.model], false);
      return true;
    }
  }
  const focus = editor.getFocus();
  const containingSelection = selections.find((selection) => selection.start <= focus.start && focus.end <= selection.end);
  if (!containingSelection) {
    const targetCell2 = editor.cellAt(focus.start);
    clipboardService.writeText(targetCell2.getText());
    const newFocus = focus.end === editor.getLength() ? { start: focus.start - 1, end: focus.end - 1 } : focus;
    const newSelections = selections.map((selection) => selection.end <= focus.start ? selection : { start: selection.start - 1, end: selection.end - 1 });
    textModel.applyEdits([
      { editType: 1, index: focus.start, count: 1, cells: [] }
    ], true, { kind: SelectionStateType.Index, focus: editor.getFocus(), selections }, () => ({ kind: SelectionStateType.Index, focus: newFocus, selections: newSelections }), void 0, true);
    notebookService.setToCopy([targetCell2.model], false);
    return true;
  }
  const selectionRanges = $Rrb(editor, editor.getSelections());
  const selectedCells = $Srb(editor, selectionRanges);
  if (!selectedCells.length) {
    return false;
  }
  clipboardService.writeText(selectedCells.map((cell) => cell.getText()).join("\n"));
  const edits = selectionRanges.map((range) => ({ editType: 1, index: range.start, count: range.end - range.start, cells: [] }));
  const firstSelectIndex = selectionRanges[0].start;
  const newFocusedCellIndex = firstSelectIndex < textModel.cells.length - 1 ? firstSelectIndex : Math.max(textModel.cells.length - 2, 0);
  textModel.applyEdits(edits, true, { kind: SelectionStateType.Index, focus: editor.getFocus(), selections: selectionRanges }, () => {
    return {
      kind: SelectionStateType.Index,
      focus: { start: newFocusedCellIndex, end: newFocusedCellIndex + 1 },
      selections: [{ start: newFocusedCellIndex, end: newFocusedCellIndex + 1 }]
    };
  }, void 0, true);
  notebookService.setToCopy(selectedCells.map((cell) => cell.model), false);
  return true;
}
var $l3b = class $l3b2 extends $3c {
  static {
    this.ID = "workbench.contrib.notebookClipboard";
  }
  constructor(a) {
    super();
    this.a = a;
    const PRIORITY3 = 105;
    if ($kab) {
      this.B($kab.addImplementation(PRIORITY3, "notebook-clipboard", (accessor) => {
        return this.runCopyAction(accessor);
      }));
    }
    if ($lab) {
      this.B($lab.addImplementation(PRIORITY3, "notebook-clipboard", (accessor) => {
        return this.runPasteAction(accessor);
      }));
    }
    if ($jab) {
      this.B($jab.addImplementation(PRIORITY3, "notebook-clipboard", (accessor) => {
        return this.runCutAction(accessor);
      }));
    }
  }
  b() {
    const editor = $Qrb(this.a.activeEditorPane);
    const activeCell = editor?.getActiveCell();
    return {
      editor,
      activeCell
    };
  }
  c(editor) {
    const windowSelection = getWindow(editor.getDomNode()).getSelection();
    if (windowSelection?.rangeCount !== 1) {
      return false;
    }
    const activeSelection = windowSelection.getRangeAt(0);
    if (activeSelection.startContainer === activeSelection.endContainer && activeSelection.endOffset - activeSelection.startOffset === 0) {
      return false;
    }
    let container2 = activeSelection.commonAncestorContainer;
    const body = editor.getDomNode();
    if (!body.contains(container2)) {
      return false;
    }
    while (container2 && container2 !== body) {
      if (container2.classList && container2.classList.contains("monaco-editor")) {
        return true;
      }
      container2 = container2.parentNode;
    }
    return false;
  }
  runCopyAction(accessor) {
    const loggerService = accessor.get($wn);
    const activeElement = $Lj();
    if ($Uj(activeElement) && $Fk(activeElement)) {
      _log(loggerService, "[NotebookEditor] focus is on input or textarea element, bypass");
      return false;
    }
    const { editor } = this.b();
    if (!editor) {
      _log(loggerService, "[NotebookEditor] no active notebook editor, bypass");
      return false;
    }
    if (!$Dj(activeElement, editor.getDomNode())) {
      _log(loggerService, "[NotebookEditor] focus is outside of the notebook editor, bypass");
      return false;
    }
    if (this.c(editor)) {
      _log(loggerService, "[NotebookEditor] focus is on embed monaco editor, bypass");
      return false;
    }
    _log(loggerService, "[NotebookEditor] run copy actions on notebook model");
    return $j3b(accessor, editor, void 0);
  }
  runPasteAction(accessor) {
    const activeElement = $Lj();
    if (activeElement && $Fk(activeElement)) {
      return false;
    }
    const notebookService = accessor.get($mrb);
    const pasteCells = notebookService.getToCopy();
    if (!pasteCells) {
      return false;
    }
    const { editor, activeCell } = this.b();
    if (!editor) {
      return false;
    }
    return $i3b(editor, activeCell, pasteCells);
  }
  runCutAction(accessor) {
    const activeElement = $Lj();
    if (activeElement && $Fk(activeElement)) {
      return false;
    }
    const { editor } = this.b();
    if (!editor) {
      return false;
    }
    return $k3b(accessor, editor, void 0);
  }
};
$l3b = __decorate([
  __param(0, $mJ)
], $l3b);
$PL(
  $l3b.ID,
  $l3b,
  2
  /* WorkbenchPhase.BlockRestore */
);
var COPY_CELL_COMMAND_ID = "notebook.cell.copy";
var CUT_CELL_COMMAND_ID = "notebook.cell.cut";
var PASTE_CELL_COMMAND_ID = "notebook.cell.paste";
var PASTE_CELL_ABOVE_COMMAND_ID = "notebook.cell.pasteAbove";
$hJ(class extends $HIb {
  constructor() {
    super({
      id: COPY_CELL_COMMAND_ID,
      title: localize(8111, null),
      menu: {
        id: $bJ.NotebookCellTitle,
        when: $WAb,
        group: "1_copy",
        order: 2
      },
      keybinding: $p ? void 0 : {
        primary: 2048 | 33,
        win: { primary: 2048 | 33, secondary: [
          2048 | 19
          /* KeyCode.Insert */
        ] },
        when: $7m.and($WAb, $7m.not($Beb)),
        weight: 200
        /* KeybindingWeight.WorkbenchContrib */
      }
    });
  }
  async runWithContext(accessor, context) {
    $j3b(accessor, context.notebookEditor, context.cell);
  }
});
$hJ(class extends $HIb {
  constructor() {
    super({
      id: CUT_CELL_COMMAND_ID,
      title: localize(8112, null),
      menu: {
        id: $bJ.NotebookCellTitle,
        when: $7m.and($WAb, $1Ab, $$Ab),
        group: "1_copy",
        order: 1
      },
      keybinding: $p ? void 0 : {
        when: $7m.and($WAb, $7m.not($Beb)),
        primary: 2048 | 54,
        win: { primary: 2048 | 54, secondary: [
          1024 | 20
          /* KeyCode.Delete */
        ] },
        weight: 200
        /* KeybindingWeight.WorkbenchContrib */
      }
    });
  }
  async runWithContext(accessor, context) {
    $k3b(accessor, context.notebookEditor, context.cell);
  }
});
$hJ(class extends $FIb {
  constructor() {
    super({
      id: PASTE_CELL_COMMAND_ID,
      title: localize(8113, null),
      menu: {
        id: $bJ.NotebookCellTitle,
        when: $7m.and($WAb, $1Ab),
        group: "1_copy",
        order: 3
      },
      keybinding: $p ? void 0 : {
        when: $7m.and($WAb, $7m.not($Beb)),
        primary: 2048 | 52,
        win: { primary: 2048 | 52, secondary: [
          1024 | 19
          /* KeyCode.Insert */
        ] },
        linux: { primary: 2048 | 52, secondary: [
          1024 | 19
          /* KeyCode.Insert */
        ] },
        weight: 100
        /* KeybindingWeight.EditorContrib */
      }
    });
  }
  async runWithContext(accessor, context) {
    const notebookService = accessor.get($mrb);
    const pasteCells = notebookService.getToCopy();
    if (!context.notebookEditor.hasModel() || context.notebookEditor.isReadOnly) {
      return;
    }
    if (!pasteCells) {
      return;
    }
    $i3b(context.notebookEditor, context.cell, pasteCells);
  }
});
$hJ(class extends $HIb {
  constructor() {
    super({
      id: PASTE_CELL_ABOVE_COMMAND_ID,
      title: localize(8114, null),
      keybinding: {
        when: $7m.and($WAb, $7m.not($Beb)),
        primary: 2048 | 1024 | 52,
        weight: $AIb
      }
    });
  }
  async runWithContext(accessor, context) {
    const notebookService = accessor.get($mrb);
    const pasteCells = notebookService.getToCopy();
    const editor = context.notebookEditor;
    const textModel = editor.textModel;
    if (editor.isReadOnly) {
      return;
    }
    if (!pasteCells) {
      return;
    }
    const originalState = {
      kind: SelectionStateType.Index,
      focus: editor.getFocus(),
      selections: editor.getSelections()
    };
    const currCellIndex = context.notebookEditor.getCellIndex(context.cell);
    const newFocusIndex = currCellIndex;
    textModel.applyEdits([
      {
        editType: 1,
        index: currCellIndex,
        count: 0,
        cells: pasteCells.items.map((cell) => $tL(cell))
      }
    ], true, originalState, () => ({
      kind: SelectionStateType.Index,
      focus: { start: newFocusIndex, end: newFocusIndex + 1 },
      selections: [{ start: newFocusIndex, end: newFocusIndex + pasteCells.items.length }]
    }), void 0, true);
  }
});
$hJ(class extends $gJ {
  constructor() {
    super({
      id: "workbench.action.toggleNotebookClipboardLog",
      title: localize2(8116, "Toggle Notebook Clipboard Troubleshooting"),
      category: $qn.Developer,
      f1: true
    });
  }
  run(accessor) {
    toggleLogging();
    if (_logging) {
      const commandService = accessor.get($sn);
      commandService.executeCommand($QCb);
    }
  }
});
$hJ(class extends $HIb {
  constructor() {
    super({
      id: "notebook.cell.output.selectAll",
      title: localize(8115, null),
      keybinding: {
        primary: 2048 | 31,
        when: $7m.and($WAb, $YAb),
        weight: $BIb
      }
    });
  }
  async runWithContext(accessor, _context) {
    withEditor(accessor, (editor) => {
      if (!editor.hasEditorFocus()) {
        return false;
      }
      if (editor.hasEditorFocus() && !editor.hasWebviewFocus()) {
        return true;
      }
      const cell = editor.getActiveCell();
      if (!cell || !cell.outputIsFocused || !editor.hasWebviewFocus()) {
        return true;
      }
      if (cell.inputInOutputIsFocused) {
        editor.selectInputContents(cell);
      } else {
        editor.selectOutputContent(cell);
      }
      return true;
    });
  }
});

// out-build/vs/workbench/contrib/notebook/browser/contrib/find/findFilters.js
var $MIb = class extends $3c {
  get markupInput() {
    return this.b;
  }
  set markupInput(value) {
    if (this.b !== value) {
      this.b = value;
      this.a.fire({ markupInput: value });
    }
  }
  get markupPreview() {
    return this.c;
  }
  set markupPreview(value) {
    if (this.c !== value) {
      this.c = value;
      this.a.fire({ markupPreview: value });
    }
  }
  get codeInput() {
    return this.f;
  }
  set codeInput(value) {
    if (this.f !== value) {
      this.f = value;
      this.a.fire({ codeInput: value });
    }
  }
  get codeOutput() {
    return this.g;
  }
  set codeOutput(value) {
    if (this.g !== value) {
      this.g = value;
      this.a.fire({ codeOutput: value });
    }
  }
  get findScope() {
    return this.h;
  }
  set findScope(value) {
    if (this.h !== value) {
      this.h = value;
      this.a.fire({ findScope: true });
    }
  }
  constructor(markupInput, markupPreview, codeInput, codeOutput, findScope) {
    super();
    this.a = this.B(new $ze());
    this.onDidChange = this.a.event;
    this.b = true;
    this.c = true;
    this.f = true;
    this.g = true;
    this.h = { findScopeType: NotebookFindScopeType.None };
    this.b = markupInput;
    this.c = markupPreview;
    this.f = codeInput;
    this.g = codeOutput;
    this.h = findScope;
    this.j = markupInput;
    this.m = markupPreview;
    this.n = codeInput;
    this.r = codeOutput;
  }
  isModified() {
    return this.b !== this.j || this.c !== this.m || this.f !== this.n || this.g !== this.r;
  }
  update(v) {
    this.b = v.markupInput;
    this.c = v.markupPreview;
    this.f = v.codeInput;
    this.g = v.codeOutput;
    this.h = v.findScope;
  }
};

// out-build/vs/workbench/contrib/notebook/browser/contrib/find/notebookFindReplaceWidget.js
var NLS_FIND_INPUT_LABEL2 = localize(8129, null);
var NLS_FIND_INPUT_PLACEHOLDER2 = localize(8130, null);
var NLS_PREVIOUS_MATCH_BTN_LABEL2 = localize(8131, null);
var NLS_NEXT_MATCH_BTN_LABEL2 = localize(8132, null);
var NLS_TOGGLE_SELECTION_FIND_TITLE2 = localize(8133, null);
var NLS_CLOSE_BTN_LABEL2 = localize(8134, null);
var NLS_TOGGLE_REPLACE_MODE_BTN_LABEL2 = localize(8135, null);
var NLS_REPLACE_INPUT_LABEL2 = localize(8136, null);
var NLS_REPLACE_INPUT_PLACEHOLDER2 = localize(8137, null);
var NLS_REPLACE_BTN_LABEL2 = localize(8138, null);
var NLS_REPLACE_ALL_BTN_LABEL2 = localize(8139, null);
var $m3b = $9r("find-filter", $6l.filter, localize(8140, null));
var NOTEBOOK_FIND_FILTERS = localize(8141, null);
var NOTEBOOK_FIND_IN_MARKUP_INPUT = localize(8142, null);
var NOTEBOOK_FIND_IN_MARKUP_PREVIEW = localize(8143, null);
var NOTEBOOK_FIND_IN_CODE_INPUT = localize(8144, null);
var NOTEBOOK_FIND_IN_CODE_OUTPUT = localize(8145, null);
var NOTEBOOK_FIND_WIDGET_INITIAL_WIDTH = 419;
var NOTEBOOK_FIND_WIDGET_INITIAL_HORIZONTAL_PADDING = 4;
var NotebookFindFilterActionViewItem = class NotebookFindFilterActionViewItem2 extends $L2 {
  constructor(filters2, action, options3, actionRunner, contextMenuService) {
    super(action, { getActions: () => this.a() }, contextMenuService, {
      ...options3,
      actionRunner,
      classNames: action.class,
      anchorAlignmentProvider: () => 1
      /* AnchorAlignment.RIGHT */
    });
    this.filters = filters2;
  }
  render(container2) {
    super.render(container2);
    this.J();
  }
  a() {
    const markdownInput = {
      checked: this.filters.markupInput,
      class: void 0,
      enabled: true,
      id: "findInMarkdownInput",
      label: NOTEBOOK_FIND_IN_MARKUP_INPUT,
      run: async () => {
        this.filters.markupInput = !this.filters.markupInput;
      },
      tooltip: ""
    };
    const markdownPreview = {
      checked: this.filters.markupPreview,
      class: void 0,
      enabled: true,
      id: "findInMarkdownInput",
      label: NOTEBOOK_FIND_IN_MARKUP_PREVIEW,
      run: async () => {
        this.filters.markupPreview = !this.filters.markupPreview;
      },
      tooltip: ""
    };
    const codeInput = {
      checked: this.filters.codeInput,
      class: void 0,
      enabled: true,
      id: "findInCodeInput",
      label: NOTEBOOK_FIND_IN_CODE_INPUT,
      run: async () => {
        this.filters.codeInput = !this.filters.codeInput;
      },
      tooltip: ""
    };
    const codeOutput = {
      checked: this.filters.codeOutput,
      class: void 0,
      enabled: true,
      id: "findInCodeOutput",
      label: NOTEBOOK_FIND_IN_CODE_OUTPUT,
      run: async () => {
        this.filters.codeOutput = !this.filters.codeOutput;
      },
      tooltip: "",
      dispose: () => null
    };
    if ($J) {
      return [
        markdownInput,
        codeInput
      ];
    } else {
      return [
        markdownInput,
        markdownPreview,
        new $Wm(),
        codeInput,
        codeOutput
      ];
    }
  }
  J() {
    this.element.classList.toggle("checked", this._action.checked);
  }
};
NotebookFindFilterActionViewItem = __decorate([
  __param(4, $50)
], NotebookFindFilterActionViewItem);
var $n3b = class extends $3c {
  constructor(filters2, contextMenuService, instantiationService, options3, tooltip = NOTEBOOK_FIND_FILTERS) {
    super();
    this.filters = filters2;
    this.contextMenuService = contextMenuService;
    this.instantiationService = instantiationService;
    this.b = null;
    this.f = options3.toggleStyles;
    this.c = new $Um("notebookFindFilterAction", tooltip, "notebook-filters " + ThemeIcon.asClassName($gCb));
    this.c.checked = false;
    this.a = $(".find-filter-button");
    this.a.classList.add("monaco-custom-toggle");
    this.h(this.a);
  }
  get container() {
    return this.a;
  }
  width() {
    return 2 + 2 + 2 + 16;
  }
  enable() {
    this.container.setAttribute("aria-disabled", String(false));
  }
  disable() {
    this.container.setAttribute("aria-disabled", String(true));
  }
  set visible(visible) {
    this.a.style.display = visible ? "" : "none";
  }
  get visible() {
    return this.a.style.display !== "none";
  }
  applyStyles(filterChecked) {
    const toggleStyles = this.f;
    this.a.style.border = "1px solid transparent";
    this.a.style.borderRadius = "3px";
    this.a.style.borderColor = filterChecked && toggleStyles.inputActiveOptionBorder || "";
    this.a.style.color = filterChecked && toggleStyles.inputActiveOptionForeground || "inherit";
    this.a.style.backgroundColor = filterChecked && toggleStyles.inputActiveOptionBackground || "";
  }
  h(container2) {
    this.b = this.B(new $LZ(container2, {
      actionViewItemProvider: (action, options3) => {
        if (action.id === this.c.id) {
          return this.instantiationService.createInstance(NotebookFindFilterActionViewItem, this.filters, action, options3, new $Vm());
        }
        return void 0;
      }
    }));
    this.b.push(this.c, { icon: true, label: false });
  }
};
var $o3b = class extends $Q2 {
  constructor(filters2, contextKeyService, contextMenuService, instantiationService, parent, contextViewProvider, options3) {
    super(parent, contextViewProvider, options3);
    this.filters = filters2;
    this.contextMenuService = contextMenuService;
    this.instantiationService = instantiationService;
    this.bb = false;
    this.B($8bb(contextKeyService, this.inputBox));
    this.ab = this.B(new $n3b(filters2, contextMenuService, instantiationService, options3));
    this.inputBox.paddingRight = (this.M?.width() ?? 0) + (this.L?.width() ?? 0) + (this.J?.width() ?? 0) + this.ab.width();
    this.I.appendChild(this.ab.container);
  }
  setEnabled(enabled) {
    super.setEnabled(enabled);
    if (enabled && !this.bb) {
      this.J?.enable();
    } else {
      this.J?.disable();
    }
  }
  updateFilterState(changed) {
    this.bb = changed;
    if (this.J) {
      if (this.bb) {
        this.J.disable();
        this.J.domNode.tabIndex = -1;
        this.J.domNode.classList.toggle("disabled", true);
      } else {
        this.J.enable();
        this.J.domNode.tabIndex = 0;
        this.J.domNode.classList.toggle("disabled", false);
      }
    }
    this.ab.applyStyles(this.bb);
  }
  getCellToolbarActions(menu) {
    return $Q$(menu.getActions({ shouldForwardArgs: true }), (g) => /^inline/.test(g));
  }
};
var $p3b = class $p3b2 extends $qZ {
  constructor(cb, contextKeyService, db, eb, fb, hoverService, gb = new $1fb(), hb) {
    super();
    this.cb = cb;
    this.db = db;
    this.eb = eb;
    this.fb = fb;
    this.gb = gb;
    this.hb = hb;
    this.Q = NOTEBOOK_FIND_WIDGET_INITIAL_WIDTH;
    this.R = false;
    this.S = false;
    this.U = false;
    this.ab = [];
    this.bb = [];
    const findFilters = this.db.getValue($rM.findFilters) ?? { markupSource: true, markupPreview: true, codeSource: true, codeOutput: true };
    this.Y = new $MIb(findFilters.markupSource, findFilters.markupPreview, findFilters.codeSource, findFilters.codeOutput, { findScopeType: NotebookFindScopeType.None });
    this.gb.change({ filters: this.Y }, false);
    this.Y.onDidChange(() => {
      this.gb.change({ filters: this.Y }, false);
    });
    this.c = document.createElement("div");
    this.c.classList.add("simple-fr-find-part-wrapper");
    this.B(this.gb.onFindReplaceStateChange((e) => this.xb(e)));
    this.X = contextKeyService.createScoped(this.c);
    const progressContainer = $(".find-replace-progress");
    this.W = new $02(progressContainer, $s$);
    this.c.appendChild(progressContainer);
    const isInteractiveWindow = contextKeyService.getContextKeyValue("notebookType") === "interactive";
    this.L = this.B(new $qgb({
      label: NLS_TOGGLE_REPLACE_MODE_BTN_LABEL2,
      className: "codicon toggle left",
      onTrigger: isInteractiveWindow ? () => {
      } : () => {
        this.S = !this.S;
        this.gb.change({ isReplaceRevealed: this.S }, false);
        this.Eb();
      }
    }, hoverService));
    this.L.setEnabled(!isInteractiveWindow);
    this.L.setExpanded(this.S);
    this.c.appendChild(this.L.domNode);
    this.h = document.createElement("div");
    this.h.classList.add("simple-fr-find-part");
    this.a = this.B(new $o3b(this.Y, this.X, this.eb, this.fb, null, this.cb, {
      // width:FIND_INPUT_AREA_WIDTH,
      label: NLS_FIND_INPUT_LABEL2,
      placeholder: NLS_FIND_INPUT_PLACEHOLDER2,
      validation: (value) => {
        if (value.length === 0 || !this.a.getRegex()) {
          return null;
        }
        try {
          new RegExp(value);
          return null;
        } catch (e) {
          this.U = false;
          this.Kb(this.U);
          return { content: e.message };
        }
      },
      flexibleWidth: true,
      showCommonFindToggles: true,
      inputBoxStyles: $B$,
      toggleStyles: $u$
    }));
    this.t = new $Sh(500);
    this.z(this.a.domNode, (e) => {
      this.U = this.kb();
      this.Kb(this.U);
      this.Fb();
    });
    this.B(this.a.inputBox.onDidChange(() => {
      this.gb.change({ searchString: this.a.getValue() }, true);
    }));
    this.a.setRegex(!!this.gb.isRegex);
    this.a.setCaseSensitive(!!this.gb.matchCase);
    this.a.setWholeWords(!!this.gb.wholeWord);
    this.B(this.a.onDidOptionChange(() => {
      this.gb.change({
        isRegex: this.a.getRegex(),
        wholeWord: this.a.getWholeWords(),
        matchCase: this.a.getCaseSensitive()
      }, true);
    }));
    this.B(this.gb.onFindReplaceStateChange(() => {
      this.a.setRegex(this.gb.isRegex);
      this.a.setWholeWords(this.gb.wholeWord);
      this.a.setCaseSensitive(this.gb.matchCase);
      this.I.setPreserveCase(this.gb.preserveCase);
    }));
    this.w = document.createElement("div");
    this.w.className = "matchesCount";
    this.Db();
    this.y = this.B(new $qgb({
      label: NLS_PREVIOUS_MATCH_BTN_LABEL2,
      icon: $kgb,
      onTrigger: () => {
        this.lb(true);
      }
    }, hoverService));
    this.H = this.B(new $qgb({
      label: NLS_NEXT_MATCH_BTN_LABEL2,
      icon: $lgb,
      onTrigger: () => {
        this.lb(false);
      }
    }, hoverService));
    this.Z = this.B(new $Q1({
      icon: $hgb,
      title: NLS_TOGGLE_SELECTION_FIND_TITLE2,
      isChecked: false,
      inputActiveOptionBackground: $Zn($Cq),
      inputActiveOptionBorder: $Zn($Aq),
      inputActiveOptionForeground: $Zn($Dq)
    }));
    this.Z.domNode.style.display = "inline";
    this.Z.onChange(() => {
      const checked = this.Z.checked;
      if (checked) {
        const cellSelection = this.hb.getSelections();
        const textSelection = this.hb.getSelectionViewModels()[0].getSelections();
        if (cellSelection.length > 1 || cellSelection.some((range) => range.end - range.start > 1)) {
          this.Y.findScope = {
            findScopeType: NotebookFindScopeType.Cells,
            selectedCellRanges: cellSelection
          };
          this.zb();
        } else if (textSelection.length > 1 || textSelection.some((range) => range.endLineNumber - range.startLineNumber >= 1)) {
          this.Y.findScope = {
            findScopeType: NotebookFindScopeType.Text,
            selectedCellRanges: cellSelection,
            selectedTextRanges: textSelection
          };
          this.Bb(textSelection, this.hb.getSelectionViewModels()[0]);
        } else {
          this.Y.findScope = {
            findScopeType: NotebookFindScopeType.Cells,
            selectedCellRanges: cellSelection
          };
          this.zb();
        }
      } else {
        this.Y.findScope = {
          findScopeType: NotebookFindScopeType.None
        };
        this.Ab();
        this.Cb();
      }
    });
    const closeBtn = this.B(new $qgb({
      label: NLS_CLOSE_BTN_LABEL2,
      icon: $_r,
      onTrigger: () => {
        this.hide();
      }
    }, hoverService));
    this.h.appendChild(this.a.domNode);
    this.h.appendChild(this.w);
    this.h.appendChild(this.y.domNode);
    this.h.appendChild(this.H.domNode);
    this.h.appendChild(this.Z.domNode);
    this.h.appendChild(closeBtn.domNode);
    this.c.appendChild(this.h);
    this.u(this.h, (e) => {
      if (e.equals(
        9
        /* KeyCode.Escape */
      )) {
        this.hide();
        e.preventDefault();
        return;
      }
    });
    this.n = this.B($_j(this.c));
    this.B(this.n.onDidFocus(this.ob.bind(this)));
    this.B(this.n.onDidBlur(this.pb.bind(this)));
    this.r = this.B($_j(this.a.domNode));
    this.B(this.r.onDidFocus(this.qb.bind(this)));
    this.B(this.r.onDidBlur(this.rb.bind(this)));
    this.B($_i(this.h, "click", (event) => {
      event.stopPropagation();
    }));
    this.J = document.createElement("div");
    this.J.classList.add("simple-fr-replace-part");
    this.I = this.B(new $$bb(null, void 0, {
      label: NLS_REPLACE_INPUT_LABEL2,
      placeholder: NLS_REPLACE_INPUT_PLACEHOLDER2,
      history: [],
      inputBoxStyles: $B$,
      toggleStyles: $u$
    }, contextKeyService, false));
    this.J.appendChild(this.I.domNode);
    this.M = this.B($_j(this.I.domNode));
    this.B(this.M.onDidFocus(this.sb.bind(this)));
    this.B(this.M.onDidBlur(this.tb.bind(this)));
    this.B(this.I.inputBox.onDidChange(() => {
      this.gb.change({ replaceString: this.I.getValue() }, true);
    }));
    this.c.appendChild(this.J);
    this.Eb();
    this.N = this.B(new $qgb({
      label: NLS_REPLACE_BTN_LABEL2,
      icon: $igb,
      onTrigger: () => {
        this.mb();
      }
    }, hoverService));
    this.O = this.B(new $qgb({
      label: NLS_REPLACE_ALL_BTN_LABEL2,
      icon: $jgb,
      onTrigger: () => {
        this.nb();
      }
    }, hoverService));
    this.J.appendChild(this.N.domNode);
    this.J.appendChild(this.O.domNode);
    this.P = this.B(new $q2(this.c, { getVerticalSashLeft: () => 0 }, { orientation: 0, size: 2 }));
    this.B(this.P.onDidStart(() => {
      this.Q = this.jb();
    }));
    this.B(this.P.onDidChange((evt) => {
      let width2 = this.Q + evt.startX - evt.currentX;
      if (width2 < NOTEBOOK_FIND_WIDGET_INITIAL_WIDTH) {
        width2 = NOTEBOOK_FIND_WIDGET_INITIAL_WIDTH;
      }
      const maxWidth = this.ib();
      if (width2 > maxWidth) {
        width2 = maxWidth;
      }
      this.c.style.width = `${width2}px`;
      if (this.S) {
        this.I.width = $xj(this.a.domNode);
      }
      this.a.inputBox.layout();
    }));
    this.B(this.P.onDidReset(() => {
      const currentWidth = this.jb();
      let width2 = NOTEBOOK_FIND_WIDGET_INITIAL_WIDTH;
      if (currentWidth <= NOTEBOOK_FIND_WIDGET_INITIAL_WIDTH) {
        width2 = this.ib();
      }
      this.c.style.width = `${width2}px`;
      if (this.S) {
        this.I.width = $xj(this.a.domNode);
      }
      this.a.inputBox.layout();
    }));
  }
  ib() {
    return this.hb.getLayoutInfo().width - 64;
  }
  jb() {
    return $xj(this.c) - NOTEBOOK_FIND_WIDGET_INITIAL_HORIZONTAL_PADDING * 2;
  }
  getCellToolbarActions(menu) {
    return $Q$(menu.getActions({ shouldForwardArgs: true }), (g) => /^inline/.test(g));
  }
  get ub() {
    return this.a.getValue();
  }
  get vb() {
    return this.I.getValue();
  }
  get wb() {
    if (this.gb.isRegex) {
      return $5fb(this.vb);
    }
    return $3fb.fromStaticValue(this.vb);
  }
  get focusTracker() {
    return this.n;
  }
  get isVisible() {
    return this.R;
  }
  xb(e) {
    this.yb();
    this.Db();
  }
  yb() {
    this.a.setEnabled(this.R);
    this.I.setEnabled(this.R && this.S);
    const findInputIsNonEmpty = this.gb.searchString.length > 0;
    this.N.setEnabled(this.R && this.S && findInputIsNonEmpty);
    this.O.setEnabled(this.R && this.S && findInputIsNonEmpty);
    this.c.classList.toggle("replaceToggled", this.S);
    this.L.setExpanded(this.S);
    this.U = this.gb.matchesCount > 0;
    this.Kb(this.U);
  }
  zb() {
    const cellHandles = [];
    this.hb.getSelectionViewModels().forEach((viewModel) => {
      cellHandles.push(viewModel.handle);
    });
    const decorations = [];
    for (const handle2 of cellHandles) {
      decorations.push({
        handle: handle2,
        options: { className: "nb-multiCellHighlight", outputClassName: "nb-multiCellHighlight" }
      });
    }
    this.ab = this.hb.deltaCellDecorations([], decorations);
  }
  Ab() {
    this.hb.deltaCellDecorations(this.ab, []);
  }
  Bb(textRanges, cell) {
    this.hb.changeModelDecorations((changeAccessor) => {
      const decorations = [];
      for (const range of textRanges) {
        decorations.push({
          ownerId: cell.handle,
          decorations: [{
            range,
            options: {
              description: "text search range for notebook search scope",
              isWholeLine: true,
              className: "nb-findScope"
            }
          }]
        });
      }
      this.bb = changeAccessor.deltaDecorations([], decorations);
    });
  }
  Cb() {
    this.hb.changeModelDecorations((changeAccessor) => {
      changeAccessor.deltaDecorations(this.bb, []);
    });
  }
  Db() {
  }
  dispose() {
    super.dispose();
    this.c.remove();
  }
  getDomNode() {
    return this.c;
  }
  reveal(initialInput) {
    if (initialInput) {
      this.a.setValue(initialInput);
    }
    if (this.R) {
      this.a.select();
      return;
    }
    this.R = true;
    this.Kb(this.U);
    setTimeout(() => {
      this.c.classList.add("visible", "visible-transition");
      this.c.setAttribute("aria-hidden", "false");
      this.a.select();
    }, 0);
  }
  focus() {
    this.a.focus();
  }
  show(initialInput, options3) {
    if (initialInput) {
      this.a.setValue(initialInput);
    }
    this.R = true;
    setTimeout(() => {
      this.c.classList.add("visible", "visible-transition");
      this.c.setAttribute("aria-hidden", "false");
      if (options3?.focus ?? true) {
        this.focus();
      }
    }, 0);
  }
  showWithReplace(initialInput, replaceInput) {
    if (initialInput) {
      this.a.setValue(initialInput);
    }
    if (replaceInput) {
      this.I.setValue(replaceInput);
    }
    this.R = true;
    this.S = true;
    this.gb.change({ isReplaceRevealed: this.S }, false);
    this.Eb();
    setTimeout(() => {
      this.c.classList.add("visible", "visible-transition");
      this.c.setAttribute("aria-hidden", "false");
      this.yb();
      this.I.focus();
    }, 0);
  }
  Eb() {
    if (this.S) {
      this.J.style.display = "flex";
    } else {
      this.J.style.display = "none";
    }
    this.I.width = $xj(this.a.domNode);
  }
  hide() {
    if (this.R) {
      this.Z.checked = false;
      this.hb.deltaCellDecorations(this.ab, []);
      this.hb.changeModelDecorations((changeAccessor) => {
        changeAccessor.deltaDecorations(this.bb, []);
      });
      this.c.classList.remove("visible-transition");
      this.c.setAttribute("aria-hidden", "true");
      setTimeout(() => {
        this.R = false;
        this.Kb(this.U);
        this.c.classList.remove("visible");
      }, 200);
    }
  }
  Fb() {
    this.t.trigger(this.Gb.bind(this));
  }
  Gb() {
    this.a.inputBox.addToHistory();
  }
  Hb() {
    return this.a.getRegex();
  }
  Ib() {
    return this.a.getWholeWords();
  }
  Jb() {
    return this.a.getCaseSensitive();
  }
  Kb(foundMatch) {
    const hasInput = this.ub.length > 0;
    this.y.setEnabled(this.R && hasInput && foundMatch);
    this.H.setEnabled(this.R && hasInput && foundMatch);
  }
};
$p3b = __decorate([
  __param(0, $40),
  __param(1, $on),
  __param(2, $kl),
  __param(3, $50),
  __param(4, $Pk),
  __param(5, $5$)
], $p3b);
$ms((theme, collector) => {
  collector.addRule(`
	.notebook-editor {
		--notebook-find-width: ${NOTEBOOK_FIND_WIDGET_INITIAL_WIDTH}px;
		--notebook-find-horizontal-padding: ${NOTEBOOK_FIND_WIDGET_INITIAL_HORIZONTAL_PADDING}px;
	}
	`);
});

// out-build/vs/workbench/contrib/notebook/browser/contrib/find/notebookFindWidget.js
var FIND_HIDE_TRANSITION = "find-hide-transition";
var FIND_SHOW_TRANSITION = "find-show-transition";
var MAX_MATCHES_COUNT_WIDTH2 = 69;
var PROGRESS_BAR_DELAY = 200;
var $q3b = class $q3b2 extends $3c {
  static {
    this.id = "workbench.notebook.find";
  }
  constructor(b, c) {
    super();
    this.b = b;
    this.c = c;
    this.a = new $sf(() => this.B(this.c.createInstance(NotebookFindWidget, this.b)));
  }
  get widget() {
    return this.a.value;
  }
  show(initialInput, options3) {
    return this.a.value.show(initialInput, options3);
  }
  hide() {
    this.a.rawValue?.hide();
  }
  replace(searchString) {
    return this.a.value.replace(searchString);
  }
};
$q3b = __decorate([
  __param(1, $Pk)
], $q3b);
var NotebookFindWidget = class NotebookFindWidget2 extends $p3b {
  constructor(_notebookEditor, contextViewService, contextKeyService, configurationService, contextMenuService, hoverService, instantiationService) {
    super(contextViewService, contextKeyService, configurationService, contextMenuService, instantiationService, hoverService, new $1fb(), _notebookEditor);
    this.Mb = false;
    this.Nb = null;
    this.Ob = null;
    this.Qb = new $PIb(this.hb, this.gb, this.db);
    $bk(this.hb.getDomNode(), this.getDomNode());
    this.Lb = $PAb.bindTo(contextKeyService);
    this.B(this.a.onKeyDown((e) => this.Rb(e)));
    this.B(this.I.onKeyDown((e) => this.Sb(e)));
    this.B(this.gb.onFindReplaceStateChange((e) => {
      this.kb();
      if (e.isSearching) {
        if (this.gb.isSearching) {
          this.W.infinite().show(PROGRESS_BAR_DELAY);
        } else {
          this.W.stop().hide();
        }
      }
      if (this.Qb.currentMatch >= 0) {
        const currentMatch = this.Qb.getCurrentMatch();
        this.N.setEnabled(currentMatch.isModelMatch);
      }
      const matches = this.Qb.findMatches;
      this.O.setEnabled(matches.length > 0 && matches.find((match) => match.webviewMatches.length > 0) === void 0);
      if (e.filters) {
        this.a.updateFilterState(this.gb.filters?.isModified() ?? false);
      }
    }));
    this.B($_i(this.getDomNode(), $7j.FOCUS, (e) => {
      this.Pb = $Uj(e.relatedTarget) ? e.relatedTarget : void 0;
    }, true));
  }
  get findModel() {
    return this.Qb;
  }
  get isFocused() {
    return this.Mb;
  }
  Rb(e) {
    if (e.equals(
      3
      /* KeyCode.Enter */
    )) {
      this.lb(false);
      e.preventDefault();
      return;
    } else if (e.equals(
      1024 | 3
      /* KeyCode.Enter */
    )) {
      this.lb(true);
      e.preventDefault();
      return;
    }
  }
  Sb(e) {
    if (e.equals(
      3
      /* KeyCode.Enter */
    )) {
      this.mb();
      e.preventDefault();
      return;
    }
  }
  kb() {
    this.gb.change({ searchString: this.ub }, false);
    const findMatches = this.Qb.findMatches;
    if (findMatches && findMatches.length) {
      return true;
    }
    return false;
  }
  Ub(index) {
    this.Qb.find({ index });
  }
  lb(previous) {
    this.Qb.find({ previous });
  }
  mb() {
    if (!this.hb.hasModel()) {
      return;
    }
    if (!this.Qb.findMatches.length) {
      return;
    }
    this.Qb.ensureFindMatches();
    if (this.Qb.currentMatch < 0) {
      this.Qb.find({ previous: false });
    }
    const currentMatch = this.Qb.getCurrentMatch();
    const cell = currentMatch.cell;
    if (currentMatch.isModelMatch) {
      const match = currentMatch.match;
      this.W.infinite().show(PROGRESS_BAR_DELAY);
      const replacePattern = this.wb;
      const replaceString = replacePattern.buildReplaceString(match.matches, this.gb.preserveCase);
      const viewModel = this.hb.getViewModel();
      viewModel.replaceOne(cell, match.range, replaceString).then(() => {
        this.W.stop();
      });
    } else {
      console.error("Replace does not work for output match");
    }
  }
  nb() {
    if (!this.hb.hasModel()) {
      return;
    }
    this.W.infinite().show(PROGRESS_BAR_DELAY);
    const replacePattern = this.wb;
    const cellFindMatches = this.Qb.findMatches;
    const replaceStrings = [];
    cellFindMatches.forEach((cellFindMatch) => {
      cellFindMatch.contentMatches.forEach((match) => {
        const matches = match.matches;
        replaceStrings.push(replacePattern.buildReplaceString(matches, this.gb.preserveCase));
      });
    });
    const viewModel = this.hb.getViewModel();
    viewModel.replaceAll(this.Qb.findMatches, replaceStrings).then(() => {
      this.W.stop();
    });
  }
  Yb() {
  }
  ob() {
    this.Lb.set(true);
    this.Mb = true;
  }
  pb() {
    this.Pb = void 0;
    this.Lb.reset();
    this.Mb = false;
  }
  sb() {
  }
  tb() {
  }
  qb() {
  }
  rb() {
  }
  async show(initialInput, options3) {
    const searchStringUpdate = this.gb.searchString !== initialInput;
    super.show(initialInput, options3);
    this.gb.change({ searchString: initialInput ?? this.gb.searchString, isRevealed: true }, false);
    if (typeof options3?.matchIndex === "number") {
      if (!this.Qb.findMatches.length) {
        await this.Qb.research();
      }
      this.Ub(options3.matchIndex);
    } else {
      this.a.select();
    }
    if (!searchStringUpdate && options3?.searchStringSeededFrom) {
      this.Qb.refreshCurrentMatch(options3.searchStringSeededFrom);
    }
    if (this.Nb === null) {
      if (this.Ob !== null) {
        getWindow(this.getDomNode()).clearTimeout(this.Ob);
        this.Ob = null;
        this.hb.removeClassName(FIND_HIDE_TRANSITION);
      }
      this.hb.addClassName(FIND_SHOW_TRANSITION);
      this.Nb = getWindow(this.getDomNode()).setTimeout(() => {
        this.hb.removeClassName(FIND_SHOW_TRANSITION);
        this.Nb = null;
      }, 200);
    } else {
    }
  }
  replace(initialFindInput, initialReplaceInput) {
    super.showWithReplace(initialFindInput, initialReplaceInput);
    this.gb.change({ searchString: initialFindInput ?? "", replaceString: initialReplaceInput ?? "", isRevealed: true }, false);
    this.I.select();
    if (this.Nb === null) {
      if (this.Ob !== null) {
        getWindow(this.getDomNode()).clearTimeout(this.Ob);
        this.Ob = null;
        this.hb.removeClassName(FIND_HIDE_TRANSITION);
      }
      this.hb.addClassName(FIND_SHOW_TRANSITION);
      this.Nb = getWindow(this.getDomNode()).setTimeout(() => {
        this.hb.removeClassName(FIND_SHOW_TRANSITION);
        this.Nb = null;
      }, 200);
    } else {
    }
  }
  hide() {
    super.hide();
    this.gb.change({ isRevealed: false }, false);
    this.Qb.clear();
    this.hb.findStop();
    this.W.stop();
    if (this.Ob === null) {
      if (this.Nb !== null) {
        getWindow(this.getDomNode()).clearTimeout(this.Nb);
        this.Nb = null;
        this.hb.removeClassName(FIND_SHOW_TRANSITION);
      }
      this.hb.addClassName(FIND_HIDE_TRANSITION);
      this.Ob = getWindow(this.getDomNode()).setTimeout(() => {
        this.hb.removeClassName(FIND_HIDE_TRANSITION);
      }, 200);
    } else {
    }
    if (this.Pb && this.Pb.offsetParent) {
      this.Pb.focus();
      this.Pb = void 0;
    }
    if (this.hb.hasModel()) {
      for (let i2 = 0; i2 < this.hb.getLength(); i2++) {
        const cell = this.hb.cellAt(i2);
        if (cell.getEditState() === CellEditState.Editing && cell.editStateSource === "find") {
          cell.updateEditState(CellEditState.Preview, "closeFind");
        }
      }
    }
  }
  Db() {
    if (!this.Qb || !this.Qb.findMatches) {
      return;
    }
    this.w.style.width = MAX_MATCHES_COUNT_WIDTH2 + "px";
    this.w.title = "";
    this.w.firstChild?.remove();
    let label3;
    if (this.gb.matchesCount > 0) {
      let matchesCount = String(this.gb.matchesCount);
      if (this.gb.matchesCount >= $dgb) {
        matchesCount += "+";
      }
      const matchesPosition = this.Qb.currentMatch < 0 ? "?" : String(this.Qb.currentMatch + 1);
      label3 = $wf($mgb, matchesPosition, matchesCount);
    } else {
      label3 = $ngb;
    }
    this.w.appendChild(document.createTextNode(label3));
    $$Z(this.fc(label3, this.gb.currentMatch, this.gb.searchString));
    MAX_MATCHES_COUNT_WIDTH2 = Math.max(MAX_MATCHES_COUNT_WIDTH2, this.w.clientWidth);
  }
  fc(label3, currentMatch, searchString) {
    if (label3 === $ngb) {
      return searchString === "" ? localize(8146, null, label3) : localize(8147, null, label3, searchString);
    }
    return localize(8148, null, label3, searchString);
  }
  dispose() {
    this.hb?.removeClassName(FIND_SHOW_TRANSITION);
    this.hb?.removeClassName(FIND_HIDE_TRANSITION);
    this.Qb.dispose();
    super.dispose();
  }
};
NotebookFindWidget = __decorate([
  __param(1, $40),
  __param(2, $on),
  __param(3, $kl),
  __param(4, $50),
  __param(5, $5$),
  __param(6, $Pk)
], NotebookFindWidget);

// out-build/vs/workbench/contrib/notebook/browser/contrib/find/notebookFind.js
$iGb($q3b.id, $q3b);
$hJ(class extends $gJ {
  constructor() {
    super({
      id: "notebook.hideFind",
      title: localize2(8127, "Hide Find in Notebook"),
      keybinding: {
        when: $7m.and($WAb, $PAb),
        primary: 9,
        weight: 200
        /* KeybindingWeight.WorkbenchContrib */
      }
    });
  }
  async run(accessor) {
    const editorService = accessor.get($mJ);
    const editor = $Qrb(editorService.activeEditorPane);
    if (!editor) {
      return;
    }
    const controller = editor.getContribution($q3b.id);
    controller.hide();
    editor.focus();
  }
});
$hJ(class extends $GIb {
  constructor() {
    super({
      id: "notebook.find",
      title: localize2(8128, "Find in Notebook"),
      keybinding: {
        when: $7m.and($WAb, $7m.or($SAb, $TAb), EditorContextKeys.focus.toNegated()),
        primary: 36 | 2048,
        weight: 200
        /* KeybindingWeight.WorkbenchContrib */
      }
    });
  }
  async runWithContext(accessor, context) {
    const editorService = accessor.get($mJ);
    const editor = $Qrb(editorService.activeEditorPane);
    if (!editor) {
      return;
    }
    const controller = editor.getContribution($q3b.id);
    controller.show(void 0, { findScope: { findScopeType: NotebookFindScopeType.None } });
  }
});
function notebookContainsTextModel(uri, textModel) {
  if (textModel.uri.scheme === Schemas.vscodeNotebookCell) {
    const cellUri = CellUri.parse(textModel.uri);
    if (cellUri && $oh(cellUri.notebook, uri)) {
      return true;
    }
  }
  return false;
}
function getSearchStringOptions(editor, opts) {
  if (opts.seedSearchStringFromSelection === "single") {
    const selectionSearchString = $sgb(editor, opts.seedSearchStringFromSelection, opts.seedSearchStringFromNonEmptySelection);
    if (selectionSearchString) {
      return {
        searchString: selectionSearchString,
        selection: editor.getSelection()
      };
    }
  } else if (opts.seedSearchStringFromSelection === "multiple" && !opts.updateSearchScope) {
    const selectionSearchString = $sgb(editor, opts.seedSearchStringFromSelection);
    if (selectionSearchString) {
      return {
        searchString: selectionSearchString,
        selection: editor.getSelection()
      };
    }
  }
  return void 0;
}
$vgb.addImplementation(100, (accessor, codeEditor, args2) => {
  const editorService = accessor.get($mJ);
  const editor = $Qrb(editorService.activeEditorPane);
  if (!editor) {
    return false;
  }
  if (!codeEditor.hasModel()) {
    return false;
  }
  if (!editor.hasEditorFocus() && !editor.hasWebviewFocus()) {
    const codeEditorService = accessor.get($U5);
    const textEditor = codeEditorService.getFocusedCodeEditor() || codeEditorService.getActiveCodeEditor();
    if (editor.hasModel() && textEditor && textEditor.hasModel() && notebookContainsTextModel(editor.textModel.uri, textEditor.getModel())) {
    } else {
      return false;
    }
  }
  const controller = editor.getContribution($q3b.id);
  const searchStringOptions = getSearchStringOptions(codeEditor, {
    forceRevealReplace: false,
    seedSearchStringFromSelection: codeEditor.getOption(
      43
      /* EditorOption.find */
    ).seedSearchStringFromSelection !== "never" ? "single" : "none",
    seedSearchStringFromNonEmptySelection: codeEditor.getOption(
      43
      /* EditorOption.find */
    ).seedSearchStringFromSelection === "selection",
    seedSearchStringFromGlobalClipboard: codeEditor.getOption(
      43
      /* EditorOption.find */
    ).globalFindClipboard,
    shouldFocus: 1,
    shouldAnimate: true,
    updateSearchScope: false,
    loop: codeEditor.getOption(
      43
      /* EditorOption.find */
    ).loop
  });
  let options3 = void 0;
  const uri = codeEditor.getModel().uri;
  const data = CellUri.parse(uri);
  if (searchStringOptions?.selection && data) {
    const cell = editor.getCellByHandle(data.handle);
    if (cell) {
      options3 = {
        searchStringSeededFrom: { cell, range: searchStringOptions.selection }
      };
    }
  }
  controller.show(searchStringOptions?.searchString, options3);
  return true;
});
$Fgb.addImplementation(100, (accessor, codeEditor, args2) => {
  const editorService = accessor.get($mJ);
  const editor = $Qrb(editorService.activeEditorPane);
  if (!editor) {
    return false;
  }
  if (!codeEditor.hasModel()) {
    return false;
  }
  const controller = editor.getContribution($q3b.id);
  const searchStringOptions = getSearchStringOptions(codeEditor, {
    forceRevealReplace: false,
    seedSearchStringFromSelection: codeEditor.getOption(
      43
      /* EditorOption.find */
    ).seedSearchStringFromSelection !== "never" ? "single" : "none",
    seedSearchStringFromNonEmptySelection: codeEditor.getOption(
      43
      /* EditorOption.find */
    ).seedSearchStringFromSelection === "selection",
    seedSearchStringFromGlobalClipboard: codeEditor.getOption(
      43
      /* EditorOption.find */
    ).globalFindClipboard,
    shouldFocus: 1,
    shouldAnimate: true,
    updateSearchScope: false,
    loop: codeEditor.getOption(
      43
      /* EditorOption.find */
    ).loop
  });
  if (controller) {
    controller.replace(searchStringOptions?.searchString);
    return true;
  }
  return false;
});

// out-build/vs/workbench/contrib/notebook/browser/contrib/multicursor/notebookMulticursor.js
var NOTEBOOK_ADD_FIND_MATCH_TO_SELECTION_ID = "notebook.addFindMatchToSelection";
var NOTEBOOK_SELECT_ALL_FIND_MATCHES_ID = "notebook.selectAllFindMatches";
var NotebookMultiCursorState;
(function(NotebookMultiCursorState2) {
  NotebookMultiCursorState2[NotebookMultiCursorState2["Idle"] = 0] = "Idle";
  NotebookMultiCursorState2[NotebookMultiCursorState2["Selecting"] = 1] = "Selecting";
  NotebookMultiCursorState2[NotebookMultiCursorState2["Editing"] = 2] = "Editing";
})(NotebookMultiCursorState || (NotebookMultiCursorState = {}));
var $r3b = {
  IsNotebookMultiCursor: new $nn("isNotebookMultiSelect", false),
  NotebookMultiSelectCursorState: new $nn("notebookMultiSelectCursorState", NotebookMultiCursorState.Idle)
};
var $s3b = class $s3b2 extends $3c {
  static {
    this.id = "notebook.multiCursorController";
  }
  getState() {
    return this.n;
  }
  constructor(t, u, w, y, z, C, D) {
    super();
    this.t = t;
    this.u = u;
    this.w = w;
    this.y = y;
    this.z = z;
    this.C = C;
    this.D = D;
    this.a = "";
    this.c = [];
    this.f = this.B(new $ze());
    this.onDidChangeAnchorCell = this.f.event;
    this.h = this.B(new $2c());
    this.j = this.B(new $2c());
    this.m = new $Ec();
    this.n = NotebookMultiCursorState.Idle;
    this.r = $r3b.IsNotebookMultiCursor.bindTo(this.u);
    this.s = $r3b.NotebookMultiSelectCursorState.bindTo(this.u);
    this.g = this.t.activeCellAndCodeEditor;
    this.B(this.onDidChangeAnchorCell(async () => {
      await this.G();
      this.F();
    }));
  }
  F() {
    this.h.clear();
    if (!this.g) {
      throw new Error("Anchor cell is undefined");
    }
    this.h.add(this.g[1].onWillType((input) => {
      const collector = new $08();
      this.c.forEach((cell) => {
        const controller = this.m.get(cell.cellViewModel.uri);
        if (!controller) {
          return;
        }
        if (cell.cellViewModel.handle !== this.g?.[0].handle) {
          controller.type(collector, input, "keyboard");
        }
      });
    }));
    this.h.add(this.g[1].onDidType(() => {
      this.n = NotebookMultiCursorState.Editing;
      this.s.set(NotebookMultiCursorState.Editing);
      const anchorController = this.m.get(this.g[0].uri);
      if (!anchorController) {
        return;
      }
      const activeSelections = this.t.activeCodeEditor?.getSelections();
      if (!activeSelections) {
        return;
      }
      anchorController.setSelections(
        new $08(),
        "keyboard",
        activeSelections,
        3
        /* CursorChangeReason.Explicit */
      );
      this.c.forEach((cell) => {
        const controller = this.m.get(cell.cellViewModel.uri);
        if (!controller) {
          return;
        }
        cell.initialSelection = controller.getSelection();
        cell.matchSelections = [];
      });
      this.W();
    }));
    this.h.add(this.g[1].onDidChangeCursorSelection((e) => {
      if (e.source === "mouse") {
        this.resetToIdleState();
        return;
      }
      if (!e.oldSelections || e.reason === 0 || e.reason === 2) {
        return;
      }
      const translation = {
        deltaStartCol: e.selection.startColumn - e.oldSelections[0].startColumn,
        deltaStartLine: e.selection.startLineNumber - e.oldSelections[0].startLineNumber,
        deltaEndCol: e.selection.endColumn - e.oldSelections[0].endColumn,
        deltaEndLine: e.selection.endLineNumber - e.oldSelections[0].endLineNumber
      };
      const translationDir = e.selection.getDirection();
      this.c.forEach((cell) => {
        const controller = this.m.get(cell.cellViewModel.uri);
        if (!controller) {
          return;
        }
        const newSelections = controller.getSelections().map((selection) => {
          const newStartCol = selection.startColumn + translation.deltaStartCol;
          const newStartLine = selection.startLineNumber + translation.deltaStartLine;
          const newEndCol = selection.endColumn + translation.deltaEndCol;
          const newEndLine = selection.endLineNumber + translation.deltaEndLine;
          return $_D.createWithDirection(newStartLine, newStartCol, newEndLine, newEndCol, translationDir);
        });
        controller.setSelections(
          new $08(),
          e.source,
          newSelections,
          3
          /* CursorChangeReason.Explicit */
        );
      });
      this.W();
    }));
    this.h.add(this.g[1].onWillTriggerEditorOperationEvent((e) => {
      this.L(e);
    }));
    this.h.add(this.g[1].onDidBlurEditorWidget(() => {
      if (this.n === NotebookMultiCursorState.Selecting || this.n === NotebookMultiCursorState.Editing) {
        this.resetToIdleState();
      }
    }));
  }
  async G() {
    this.j.clear();
    await Promise.all(this.c.map(async (cell) => {
      const controller = await this.H(cell);
      if (!controller) {
        return;
      }
      this.m.set(cell.cellViewModel.uri, controller);
      const selections = cell.matchSelections;
      controller.setSelections(
        new $08(),
        void 0,
        selections,
        3
        /* CursorChangeReason.Explicit */
      );
    }));
    this.W();
  }
  async H(cell) {
    const textModelRef = await this.w.createModelReference(cell.cellViewModel.uri);
    const textModel = textModelRef.object.textEditorModel;
    if (!textModel) {
      return void 0;
    }
    const cursorSimpleModel = this.J(cell.cellViewModel);
    const converter = this.I();
    const editorConfig = cell.editorConfig;
    const controller = this.j.add(new $l9(textModel, cursorSimpleModel, converter, new $d5(textModel.getLanguageId(), textModel.getOptions(), editorConfig, this.y)));
    controller.setSelections(
      new $08(),
      void 0,
      cell.matchSelections,
      3
      /* CursorChangeReason.Explicit */
    );
    return controller;
  }
  I() {
    return {
      convertViewPositionToModelPosition(viewPosition) {
        return viewPosition;
      },
      convertViewRangeToModelRange(viewRange) {
        return viewRange;
      },
      validateViewPosition(viewPosition, expectedModelPosition) {
        return viewPosition;
      },
      validateViewRange(viewRange, expectedModelRange) {
        return viewRange;
      },
      convertModelPositionToViewPosition(modelPosition, affinity, allowZeroLineNumber, belowHiddenRanges) {
        return modelPosition;
      },
      convertModelRangeToViewRange(modelRange, affinity) {
        return modelRange;
      },
      modelPositionIsVisible(modelPosition) {
        return true;
      },
      getModelLineViewLineCount(modelLineNumber) {
        return 1;
      },
      getViewLineNumberOfModelPosition(modelLineNumber, modelColumn) {
        return modelLineNumber;
      }
    };
  }
  J(cell) {
    return {
      getLineCount() {
        return cell.textBuffer.getLineCount();
      },
      getLineContent(lineNumber) {
        return cell.textBuffer.getLineContent(lineNumber);
      },
      getLineMinColumn(lineNumber) {
        return cell.textBuffer.getLineMinColumn(lineNumber);
      },
      getLineMaxColumn(lineNumber) {
        return cell.textBuffer.getLineMaxColumn(lineNumber);
      },
      getLineFirstNonWhitespaceColumn(lineNumber) {
        return cell.textBuffer.getLineFirstNonWhitespaceColumn(lineNumber);
      },
      getLineLastNonWhitespaceColumn(lineNumber) {
        return cell.textBuffer.getLineLastNonWhitespaceColumn(lineNumber);
      },
      normalizePosition(position, affinity) {
        return position;
      },
      getLineIndentColumn(lineNumber) {
        return $RI(cell.textBuffer.getLineContent(lineNumber)) + 1;
      }
    };
  }
  async L(e) {
    this.c.forEach((cell) => {
      if (cell.cellViewModel.handle === this.g?.[0].handle) {
        return;
      }
      const eventsCollector = new $08();
      const controller = this.m.get(cell.cellViewModel.uri);
      if (!controller) {
        return;
      }
      this.M(controller, eventsCollector, e);
    });
  }
  M(controller, eventsCollector, e) {
    switch (e.handlerId) {
      case "compositionStart":
        controller.startComposition(eventsCollector);
        break;
      case "compositionEnd":
        controller.endComposition(eventsCollector, e.source);
        break;
      case "replacePreviousChar": {
        const args2 = e.payload;
        controller.compositionType(eventsCollector, args2.text || "", args2.replaceCharCnt || 0, 0, 0, e.source);
        break;
      }
      case "compositionType": {
        const args2 = e.payload;
        controller.compositionType(eventsCollector, args2.text || "", args2.replacePrevCharCnt || 0, args2.replaceNextCharCnt || 0, args2.positionDelta || 0, e.source);
        break;
      }
      case "paste": {
        const args2 = e.payload;
        controller.paste(eventsCollector, args2.text || "", args2.pasteOnNewLine || false, args2.multicursorText || null, e.source);
        break;
      }
      case "cut":
        controller.cut(eventsCollector, e.source);
        break;
    }
  }
  N() {
    for (const cell of this.c) {
      const controller = this.m.get(cell.cellViewModel.uri);
      if (!controller) {
        return;
      }
      cell.cellViewModel.setSelections(controller.getSelections());
    }
  }
  O() {
    const anchorCellModel = this.g?.[1].getModel();
    if (!anchorCellModel) {
      return;
    }
    const newElementsMap = new $Ec();
    const resources = [];
    this.c.forEach((trackedMatch) => {
      const undoRedoState = trackedMatch.undoRedoHistory;
      if (!undoRedoState) {
        return;
      }
      resources.push(trackedMatch.cellViewModel.uri);
      const currentPastElements = this.D.getElements(trackedMatch.cellViewModel.uri).past.slice();
      const oldPastElements = trackedMatch.undoRedoHistory.past.slice();
      const newElements = currentPastElements.slice(oldPastElements.length);
      if (newElements.length === 0) {
        return;
      }
      newElementsMap.set(trackedMatch.cellViewModel.uri, newElements);
      this.D.removeElements(trackedMatch.cellViewModel.uri);
      oldPastElements.forEach((element) => {
        this.D.pushElement(element);
      });
    });
    this.D.pushElement({
      type: 1,
      resources,
      label: "Multi Cursor Edit",
      code: "multiCursorEdit",
      confirmBeforeUndo: false,
      undo: async () => {
        newElementsMap.forEach(async (value) => {
          value.reverse().forEach(async (element) => {
            await element.undo();
          });
        });
      },
      redo: async () => {
        newElementsMap.forEach(async (value) => {
          value.forEach(async (element) => {
            await element.redo();
          });
        });
      }
    });
  }
  resetToIdleState() {
    this.n = NotebookMultiCursorState.Idle;
    this.s.set(NotebookMultiCursorState.Idle);
    this.r.set(false);
    this.O();
    this.c.forEach((cell) => {
      this.X(cell);
      cell.cellViewModel.setSelections([cell.initialSelection]);
    });
    this.h.clear();
    this.g = void 0;
    this.j.clear();
    this.m.clear();
    this.c = [];
    this.b = void 0;
    this.a = "";
  }
  async findAndTrackNextSelection(focusedCell) {
    if (this.n === NotebookMultiCursorState.Idle) {
      const textModel = focusedCell.textModel;
      if (!textModel) {
        return;
      }
      const inputSelection = focusedCell.getSelections()[0];
      const word = this.Y(inputSelection, textModel);
      if (!word) {
        return;
      }
      this.a = word.word;
      const index = this.t.getCellIndex(focusedCell);
      if (index === void 0) {
        return;
      }
      this.b = {
        cellIndex: index,
        position: new $8C(inputSelection.startLineNumber, word.startColumn)
      };
      const newSelection = new $_D(inputSelection.startLineNumber, word.startColumn, inputSelection.startLineNumber, word.endColumn);
      focusedCell.setSelections([newSelection]);
      this.g = this.t.activeCellAndCodeEditor;
      if (!this.g || this.g[0].handle !== focusedCell.handle) {
        throw new Error("Active cell is not the same as the cell passed as context");
      }
      if (!(this.g[1] instanceof $D9)) {
        throw new Error("Active cell is not an instance of CodeEditorWidget");
      }
      await this.R(focusedCell, [newSelection]);
      this.r.set(true);
      this.n = NotebookMultiCursorState.Selecting;
      this.s.set(NotebookMultiCursorState.Selecting);
      this.f.fire();
    } else if (this.n === NotebookMultiCursorState.Selecting) {
      const notebookTextModel = this.t.textModel;
      if (!notebookTextModel) {
        return;
      }
      const index = this.t.getCellIndex(focusedCell);
      if (index === void 0) {
        return;
      }
      if (!this.b) {
        return;
      }
      const findResult = notebookTextModel.findNextMatch(this.a, { cellIndex: index, position: focusedCell.getSelections()[focusedCell.getSelections().length - 1].getEndPosition() }, false, true, $ID, this.b);
      if (!findResult) {
        return;
      }
      const findResultCellViewModel = this.t.getCellByHandle(findResult.cell.handle);
      if (!findResultCellViewModel) {
        return;
      }
      if (findResult.cell.handle === focusedCell.handle) {
        const selections = [...focusedCell.getSelections(), $_D.fromRange(
          findResult.match.range,
          0
          /* SelectionDirection.LTR */
        )];
        const trackedCell = await this.R(focusedCell, selections);
        findResultCellViewModel.setSelections(trackedCell.matchSelections);
      } else if (findResult.cell.handle !== focusedCell.handle) {
        await this.t.revealRangeInViewAsync(findResultCellViewModel, findResult.match.range);
        await this.t.focusNotebookCell(findResultCellViewModel, "editor");
        const trackedCell = await this.R(findResultCellViewModel, [$_D.fromRange(
          findResult.match.range,
          0
          /* SelectionDirection.LTR */
        )]);
        findResultCellViewModel.setSelections(trackedCell.matchSelections);
        this.g = this.t.activeCellAndCodeEditor;
        if (!this.g || !(this.g[1] instanceof $D9)) {
          throw new Error("Active cell is not an instance of CodeEditorWidget");
        }
        this.f.fire();
        this.U(this.c.find((trackedCell2) => trackedCell2.cellViewModel.handle === focusedCell.handle));
      }
    }
  }
  async selectAllMatches(focusedCell, matches) {
    const notebookTextModel = this.t.textModel;
    if (!notebookTextModel) {
      return;
    }
    if (matches) {
      await this.P(matches);
    } else {
      await this.Q(notebookTextModel, focusedCell);
    }
    await this.G();
    this.F();
    this.W();
  }
  async P(matches) {
    if (this.n !== NotebookMultiCursorState.Idle) {
      return;
    }
    if (!matches.length) {
      return;
    }
    await this.t.focusNotebookCell(matches[0].cell, "editor");
    this.g = this.t.activeCellAndCodeEditor;
    this.c = [];
    for (const match of matches) {
      this.R(match.cell, match.contentMatches.map((match2) => $_D.fromRange(
        match2.range,
        0
        /* SelectionDirection.LTR */
      )));
      if (this.g && match.cell.handle === this.g[0].handle) {
        match.cell.setSelections(match.contentMatches.map((match2) => $_D.fromRange(
          match2.range,
          0
          /* SelectionDirection.LTR */
        )));
      }
    }
    this.r.set(true);
    this.n = NotebookMultiCursorState.Selecting;
    this.s.set(NotebookMultiCursorState.Selecting);
  }
  async Q(notebookTextModel, focusedCell) {
    if (this.n === NotebookMultiCursorState.Idle) {
      const textModel = focusedCell.textModel;
      if (!textModel) {
        return;
      }
      const inputSelection = focusedCell.getSelections()[0];
      const word = this.Y(inputSelection, textModel);
      if (!word) {
        return;
      }
      this.a = word.word;
      const index = this.t.getCellIndex(focusedCell);
      if (index === void 0) {
        return;
      }
      this.b = {
        cellIndex: index,
        position: new $8C(inputSelection.startLineNumber, word.startColumn)
      };
      this.g = this.t.activeCellAndCodeEditor;
      if (!this.g || this.g[0].handle !== focusedCell.handle) {
        throw new Error("Active cell is not the same as the cell passed as context");
      }
      if (!(this.g[1] instanceof $D9)) {
        throw new Error("Active cell is not an instance of CodeEditorWidget");
      }
      const findResults = notebookTextModel.findMatches(this.a, false, true, $ID);
      this.c = [];
      for (const res of findResults) {
        await this.R(res.cell, res.matches.map((match) => $_D.fromRange(
          match.range,
          0
          /* SelectionDirection.LTR */
        )));
        if (res.cell.handle === focusedCell.handle) {
          const cellViewModel = this.t.getCellByHandle(res.cell.handle);
          if (cellViewModel) {
            cellViewModel.setSelections(res.matches.map((match) => $_D.fromRange(
              match.range,
              0
              /* SelectionDirection.LTR */
            )));
          }
        }
      }
      this.r.set(true);
      this.n = NotebookMultiCursorState.Selecting;
      this.s.set(NotebookMultiCursorState.Selecting);
    } else if (this.n === NotebookMultiCursorState.Selecting) {
      const findResults = notebookTextModel.findMatches(this.a, false, true, $ID);
      for (const res of findResults) {
        await this.R(res.cell, res.matches.map((match) => $_D.fromRange(
          match.range,
          0
          /* SelectionDirection.LTR */
        )));
      }
    }
  }
  async R(cell, selections) {
    const cellViewModel = cell instanceof $sL ? this.t.getCellByHandle(cell.handle) : cell;
    if (!cellViewModel) {
      throw new Error("Cell not found");
    }
    let trackedMatch = this.c.find((trackedCell) => trackedCell.cellViewModel.handle === cellViewModel.handle);
    if (trackedMatch) {
      this.X(trackedMatch);
      trackedMatch.matchSelections = selections;
    } else {
      const initialSelection = cellViewModel.getSelections()[0];
      const textModel = await cellViewModel.resolveTextModel();
      textModel.pushStackElement();
      const editorConfig = this.S(cellViewModel);
      const rawEditorOptions = editorConfig.getRawOptions();
      const cursorConfig = {
        cursorStyle: cursorStyleFromString(rawEditorOptions.cursorStyle),
        cursorBlinking: cursorBlinkingStyleFromString(rawEditorOptions.cursorBlinking),
        cursorSmoothCaretAnimation: rawEditorOptions.cursorSmoothCaretAnimation
      };
      trackedMatch = {
        cellViewModel,
        initialSelection,
        matchSelections: selections,
        editorConfig,
        cursorConfig,
        decorationIds: [],
        undoRedoHistory: this.D.getElements(cellViewModel.uri)
      };
      this.c.push(trackedMatch);
    }
    return trackedMatch;
  }
  async deleteLeft() {
    this.c.forEach((cell) => {
      const controller = this.m.get(cell.cellViewModel.uri);
      if (!controller) {
        return;
      }
      const [, commands2] = $l6.deleteLeft(controller.getPrevEditOperationType(), controller.context.cursorConfig, controller.context.model, controller.getSelections(), controller.getAutoClosedCharacters());
      const delSelections = $m9.executeCommands(controller.context.model, controller.getSelections(), commands2);
      if (!delSelections) {
        return;
      }
      controller.setSelections(
        new $08(),
        void 0,
        delSelections,
        3
        /* CursorChangeReason.Explicit */
      );
    });
    this.W();
  }
  async deleteRight() {
    this.c.forEach((cell) => {
      const controller = this.m.get(cell.cellViewModel.uri);
      if (!controller) {
        return;
      }
      const [, commands2] = $l6.deleteRight(controller.getPrevEditOperationType(), controller.context.cursorConfig, controller.context.model, controller.getSelections());
      if (cell.cellViewModel.handle !== this.g?.[0].handle) {
        const delSelections = $m9.executeCommands(controller.context.model, controller.getSelections(), commands2);
        if (!delSelections) {
          return;
        }
        controller.setSelections(
          new $08(),
          void 0,
          delSelections,
          3
          /* CursorChangeReason.Explicit */
        );
      } else {
        controller.setSelections(
          new $08(),
          void 0,
          cell.cellViewModel.getSelections(),
          3
          /* CursorChangeReason.Explicit */
        );
      }
    });
    this.W();
  }
  async undo() {
    const models = [];
    for (const cell of this.c) {
      const model = await cell.cellViewModel.resolveTextModel();
      if (model) {
        models.push(model);
      }
    }
    await Promise.all(models.map((model) => model.undo()));
    this.N();
    this.W();
  }
  async redo() {
    const models = [];
    for (const cell of this.c) {
      const model = await cell.cellViewModel.resolveTextModel();
      if (model) {
        models.push(model);
      }
    }
    await Promise.all(models.map((model) => model.redo()));
    this.N();
    this.W();
  }
  S(cell) {
    const cellEditorOptions = new $oKb(this.t.getBaseCellEditorOptions(cell.language), this.t.notebookOptions, this.C);
    const options3 = cellEditorOptions.getUpdatedValue(cell.internalMetadata, cell.uri);
    return new $$4(false, $bJ.EditorContent, options3, null, this.z);
  }
  /**
   * Updates the multicursor selection decorations for a specific matched cell
   *
   * @param cell -- match object containing the viewmodel + selections
   */
  U(cell) {
    if (!cell) {
      return;
    }
    const decorations = [];
    cell.matchSelections.forEach((selection) => {
      decorations.push({
        range: $_D.fromPositions(selection.getEndPosition()),
        options: {
          description: "",
          className: this.Z(cell.cursorConfig, true)
        }
      });
    });
    cell.decorationIds = cell.cellViewModel.deltaModelDecorations(cell.decorationIds, decorations);
  }
  W() {
    this.c.forEach((cell) => {
      if (cell.cellViewModel.handle === this.g?.[0].handle) {
        return;
      }
      const controller = this.m.get(cell.cellViewModel.uri);
      if (!controller) {
        return;
      }
      const selections = controller.getSelections();
      const newDecorations = [];
      selections?.map((selection) => {
        const isEmpty = selection.isEmpty();
        if (!isEmpty) {
          newDecorations.push({
            range: selection,
            options: {
              description: "",
              className: this.Z(cell.cursorConfig, false)
            }
          });
        }
        newDecorations.push({
          range: $_D.fromPositions(selection.getPosition()),
          options: {
            description: "",
            zIndex: 1e4,
            className: this.Z(cell.cursorConfig, true)
          }
        });
      });
      cell.decorationIds = cell.cellViewModel.deltaModelDecorations(cell.decorationIds, newDecorations);
      const matchingEditor = this.t.codeEditors.find((cellEditor) => cellEditor[0] === cell.cellViewModel);
      if (matchingEditor) {
        $Vkb.get(matchingEditor[1])?.wordHighlighter?.trigger();
      }
    });
  }
  X(cell) {
    cell.decorationIds = cell.cellViewModel.deltaModelDecorations(cell.decorationIds, []);
  }
  Y(selection, model) {
    const lineNumber = selection.startLineNumber;
    const startColumn = selection.startColumn;
    if (model.isDisposed()) {
      return null;
    }
    return model.getWordAtPosition({
      lineNumber,
      column: startColumn
    });
  }
  Z(cursorConfig, isCursor) {
    let result = isCursor ? ".nb-multicursor-cursor" : ".nb-multicursor-selection";
    if (isCursor) {
      switch (cursorConfig.cursorStyle) {
        case TextEditorCursorStyle.Line:
          break;
        case TextEditorCursorStyle.Block:
          result += ".nb-cursor-block-style";
          break;
        case TextEditorCursorStyle.Underline:
          result += ".nb-cursor-underline-style";
          break;
        case TextEditorCursorStyle.LineThin:
          result += ".nb-cursor-line-thin-style";
          break;
        case TextEditorCursorStyle.BlockOutline:
          result += ".nb-cursor-block-outline-style";
          break;
        case TextEditorCursorStyle.UnderlineThin:
          result += ".nb-cursor-underline-thin-style";
          break;
        default:
          break;
      }
      switch (cursorConfig.cursorBlinking) {
        case 1:
          result += ".nb-blink";
          break;
        case 2:
          result += ".nb-smooth";
          break;
        case 3:
          result += ".nb-phase";
          break;
        case 4:
          result += ".nb-expand";
          break;
        case 5:
          result += ".nb-solid";
          break;
        default:
          result += ".nb-solid";
          break;
      }
      if (cursorConfig.cursorSmoothCaretAnimation === "on" || cursorConfig.cursorSmoothCaretAnimation === "explicit") {
        result += ".nb-smooth-caret-animation";
      }
    }
    return result;
  }
  dispose() {
    super.dispose();
    this.h.dispose();
    this.j.dispose();
    this.c.forEach((cell) => {
      this.X(cell);
    });
    this.c = [];
  }
};
$s3b = __decorate([
  __param(1, $on),
  __param(2, $oG),
  __param(3, $NF),
  __param(4, $ND),
  __param(5, $kl),
  __param(6, $_F)
], $s3b);
var NotebookSelectAllFindMatches = class extends $FIb {
  constructor() {
    super({
      id: NOTEBOOK_SELECT_ALL_FIND_MATCHES_ID,
      title: localize(8155, null),
      precondition: $7m.and($7m.equals("config.notebook.multiCursor.enabled", true)),
      keybinding: {
        when: $7m.or($7m.and($7m.equals("config.notebook.multiCursor.enabled", true), $SAb, $aBb), $7m.and($7m.equals("config.notebook.multiCursor.enabled", true), $PAb)),
        primary: 2048 | 1024 | 42,
        weight: 200
        /* KeybindingWeight.WorkbenchContrib */
      }
    });
  }
  async runWithContext(accessor, context) {
    const editorService = accessor.get($mJ);
    const editor = $Qrb(editorService.activeEditorPane);
    if (!editor) {
      return;
    }
    if (!context.cell) {
      return;
    }
    const cursorController = editor.getContribution($s3b.id);
    const findController = editor.getContribution($q3b.id);
    if (findController.widget.isFocused) {
      const findModel = findController.widget.findModel;
      cursorController.selectAllMatches(context.cell, findModel.findMatches);
    } else {
      cursorController.selectAllMatches(context.cell);
    }
  }
};
var NotebookAddMatchToMultiSelectionAction = class extends $FIb {
  constructor() {
    super({
      id: NOTEBOOK_ADD_FIND_MATCH_TO_SELECTION_ID,
      title: localize(8156, null),
      precondition: $7m.and($7m.equals("config.notebook.multiCursor.enabled", true), $SAb, $aBb),
      keybinding: {
        when: $7m.and($7m.equals("config.notebook.multiCursor.enabled", true), $SAb, $aBb),
        primary: 2048 | 34,
        weight: 200
        /* KeybindingWeight.WorkbenchContrib */
      }
    });
  }
  async runWithContext(accessor, context) {
    const editorService = accessor.get($mJ);
    const editor = $Qrb(editorService.activeEditorPane);
    if (!editor) {
      return;
    }
    if (!context.cell) {
      return;
    }
    const controller = editor.getContribution($s3b.id);
    controller.findAndTrackNextSelection(context.cell);
  }
};
var NotebookExitMultiSelectionAction = class extends $FIb {
  constructor() {
    super({
      id: "noteMultiCursor.exit",
      title: localize(8157, null),
      precondition: $7m.and($7m.equals("config.notebook.multiCursor.enabled", true), $SAb, $r3b.IsNotebookMultiCursor),
      keybinding: {
        when: $7m.and($7m.equals("config.notebook.multiCursor.enabled", true), $SAb, $r3b.IsNotebookMultiCursor),
        primary: 9,
        weight: 200
        /* KeybindingWeight.WorkbenchContrib */
      }
    });
  }
  async runWithContext(accessor, context) {
    const editorService = accessor.get($mJ);
    const editor = $Qrb(editorService.activeEditorPane);
    if (!editor) {
      return;
    }
    const controller = editor.getContribution($s3b.id);
    controller.resetToIdleState();
  }
};
var NotebookDeleteLeftMultiSelectionAction = class extends $FIb {
  constructor() {
    super({
      id: "noteMultiCursor.deleteLeft",
      title: localize(8158, null),
      precondition: $7m.and($7m.equals("config.notebook.multiCursor.enabled", true), $SAb, $r3b.IsNotebookMultiCursor, $7m.or($r3b.NotebookMultiSelectCursorState.isEqualTo(NotebookMultiCursorState.Selecting), $r3b.NotebookMultiSelectCursorState.isEqualTo(NotebookMultiCursorState.Editing))),
      keybinding: {
        when: $7m.and($7m.equals("config.notebook.multiCursor.enabled", true), $SAb, $r3b.IsNotebookMultiCursor, $7m.or($r3b.NotebookMultiSelectCursorState.isEqualTo(NotebookMultiCursorState.Selecting), $r3b.NotebookMultiSelectCursorState.isEqualTo(NotebookMultiCursorState.Editing))),
        primary: 1,
        weight: 200
        /* KeybindingWeight.WorkbenchContrib */
      }
    });
  }
  async runWithContext(accessor, context) {
    const editorService = accessor.get($mJ);
    const editor = $Qrb(editorService.activeEditorPane);
    if (!editor) {
      return;
    }
    const controller = editor.getContribution($s3b.id);
    controller.deleteLeft();
  }
};
var NotebookDeleteRightMultiSelectionAction = class extends $FIb {
  constructor() {
    super({
      id: "noteMultiCursor.deleteRight",
      title: localize(8159, null),
      precondition: $7m.and($7m.equals("config.notebook.multiCursor.enabled", true), $SAb, $r3b.IsNotebookMultiCursor, $7m.or($r3b.NotebookMultiSelectCursorState.isEqualTo(NotebookMultiCursorState.Selecting), $r3b.NotebookMultiSelectCursorState.isEqualTo(NotebookMultiCursorState.Editing))),
      keybinding: {
        when: $7m.and($7m.equals("config.notebook.multiCursor.enabled", true), $SAb, $r3b.IsNotebookMultiCursor, $7m.or($r3b.NotebookMultiSelectCursorState.isEqualTo(NotebookMultiCursorState.Selecting), $r3b.NotebookMultiSelectCursorState.isEqualTo(NotebookMultiCursorState.Editing))),
        primary: 20,
        weight: 200
        /* KeybindingWeight.WorkbenchContrib */
      }
    });
  }
  async runWithContext(accessor, context) {
    const editorService = accessor.get($mJ);
    const nbEditor = $Qrb(editorService.activeEditorPane);
    if (!nbEditor) {
      return;
    }
    const cellEditor = nbEditor.activeCodeEditor;
    if (!cellEditor) {
      return;
    }
    CoreEditingCommands.DeleteRight.runEditorCommand(accessor, cellEditor, null);
    const controller = nbEditor.getContribution($s3b.id);
    controller.deleteRight();
  }
};
var NotebookMultiCursorUndoRedoContribution = class NotebookMultiCursorUndoRedoContribution2 extends $3c {
  static {
    this.ID = "workbench.contrib.notebook.multiCursorUndoRedo";
  }
  constructor(a, b) {
    super();
    this.a = a;
    this.b = b;
    if (!this.b.getValue("notebook.multiCursor.enabled")) {
      return;
    }
    const PRIORITY3 = 10005;
    this.B($05.addImplementation(PRIORITY3, "notebook-multicursor-undo-redo", () => {
      const editor = $Qrb(this.a.activeEditorPane);
      if (!editor) {
        return false;
      }
      if (!editor.hasModel()) {
        return false;
      }
      const controller = editor.getContribution($s3b.id);
      return controller.undo();
    }, $7m.and($7m.equals("config.notebook.multiCursor.enabled", true), $SAb, $r3b.IsNotebookMultiCursor)));
    this.B($$5.addImplementation(PRIORITY3, "notebook-multicursor-undo-redo", () => {
      const editor = $Qrb(this.a.activeEditorPane);
      if (!editor) {
        return false;
      }
      if (!editor.hasModel()) {
        return false;
      }
      const controller = editor.getContribution($s3b.id);
      return controller.redo();
    }, $7m.and($7m.equals("config.notebook.multiCursor.enabled", true), $SAb, $r3b.IsNotebookMultiCursor)));
  }
};
NotebookMultiCursorUndoRedoContribution = __decorate([
  __param(0, $mJ),
  __param(1, $kl)
], NotebookMultiCursorUndoRedoContribution);
$iGb($s3b.id, $s3b);
$PL(
  NotebookMultiCursorUndoRedoContribution.ID,
  NotebookMultiCursorUndoRedoContribution,
  2
  /* WorkbenchPhase.BlockRestore */
);
$hJ(NotebookSelectAllFindMatches);
$hJ(NotebookAddMatchToMultiSelectionAction);
$hJ(NotebookExitMultiSelectionAction);
$hJ(NotebookDeleteLeftMultiSelectionAction);
$hJ(NotebookDeleteRightMultiSelectionAction);

// out-build/vs/workbench/contrib/notebook/browser/contrib/saveParticipants/saveParticipants.js
var $t3b = class {
  constructor(c) {
    this.c = c;
  }
  d() {
    const editor = $Qrb(this.c.activeEditorPane);
    const controller = editor?.getContribution($s3b.id);
    if (!controller) {
      return true;
    }
    return controller.getState() !== NotebookMultiCursorState.Editing;
  }
};
var FormatOnSaveParticipant = class FormatOnSaveParticipant2 {
  constructor(c, d, e, f, g, h3) {
    this.c = c;
    this.d = d;
    this.e = e;
    this.f = f;
    this.g = g;
    this.h = h3;
  }
  async participate(workingCopy, context, progress, token) {
    if (!workingCopy.model || !(workingCopy.model instanceof $RSb)) {
      return;
    }
    if (context.reason === 2) {
      return void 0;
    }
    const enabled = this.h.getValue($rM.formatOnSave);
    if (!enabled) {
      return void 0;
    }
    progress.report({ message: localize(8191, null) });
    const notebook = workingCopy.model.notebookModel;
    const formatApplied = await this.e.invokeFunction($u3b.checkAndRunFormatCodeAction, notebook, progress, token);
    const disposable = new $2c();
    try {
      if (!formatApplied) {
        const allCellEdits = await Promise.all(notebook.cells.map(async (cell) => {
          const ref = await this.f.createModelReference(cell.uri);
          disposable.add(ref);
          const model = ref.object.textEditorModel;
          const formatEdits = await $ihb(this.c, this.d, model, 2, token);
          const edits = [];
          if (formatEdits) {
            edits.push(...formatEdits.map((edit3) => new $J_(model.uri, edit3, model.getVersionId())));
            return edits;
          }
          return [];
        }));
        await this.g.apply(
          /* edit */
          allCellEdits.flat(),
          { label: localize(8192, null), code: "undoredo.formatNotebook" }
        );
      }
    } finally {
      progress.report({ increment: 100 });
      disposable.dispose();
    }
  }
};
FormatOnSaveParticipant = __decorate([
  __param(0, $I0),
  __param(1, $mP),
  __param(2, $Pk),
  __param(3, $oG),
  __param(4, $H_),
  __param(5, $kl)
], FormatOnSaveParticipant);
var TrimWhitespaceParticipant = class TrimWhitespaceParticipant2 extends $t3b {
  constructor(e, f, g, h3) {
    super(f);
    this.e = e;
    this.f = f;
    this.g = g;
    this.h = h3;
  }
  async participate(workingCopy, context, progress, _token) {
    const trimTrailingWhitespaceOption = this.e.getValue("files.trimTrailingWhitespace");
    const trimInRegexAndStrings = this.e.getValue("files.trimTrailingWhitespaceInRegexAndStrings");
    if (trimTrailingWhitespaceOption && this.d()) {
      await this.i(workingCopy, context.reason === 2, trimInRegexAndStrings, progress);
    }
  }
  async i(workingCopy, isAutoSaved, trimInRegexesAndStrings, progress) {
    if (!workingCopy.model || !(workingCopy.model instanceof $RSb)) {
      return;
    }
    const disposable = new $2c();
    const notebook = workingCopy.model.notebookModel;
    const activeCellEditor = getActiveCellCodeEditor(this.f);
    let cursors = [];
    let prevSelection = [];
    try {
      const allCellEdits = await Promise.all(notebook.cells.map(async (cell) => {
        if (cell.cellKind !== CellKind.Code) {
          return [];
        }
        const ref = await this.g.createModelReference(cell.uri);
        disposable.add(ref);
        const model = ref.object.textEditorModel;
        const isActiveCell = activeCellEditor && cell.uri.toString() === activeCellEditor.getModel()?.uri.toString();
        if (isActiveCell) {
          prevSelection = activeCellEditor.getSelections() ?? [];
          if (isAutoSaved) {
            cursors = prevSelection.map((s) => s.getPosition());
            const snippetsRange = $Dcb.get(activeCellEditor)?.getSessionEnclosingRange();
            if (snippetsRange) {
              for (let lineNumber = snippetsRange.startLineNumber; lineNumber <= snippetsRange.endLineNumber; lineNumber++) {
                cursors.push(new $8C(lineNumber, model.getLineMaxColumn(lineNumber)));
              }
            }
          }
        }
        const ops = $5ib(model, cursors, trimInRegexesAndStrings);
        if (!ops.length) {
          return [];
        }
        return ops.map((op) => new $J_(model.uri, { ...op, text: op.text || "" }, model.getVersionId()));
      }));
      const filteredEdits = allCellEdits.flat().filter((edit3) => edit3 !== void 0);
      await this.h.apply(filteredEdits, { label: localize(8193, null), code: "undoredo.notebookTrimTrailingWhitespace" });
    } finally {
      progress.report({ increment: 100 });
      disposable.dispose();
    }
  }
};
TrimWhitespaceParticipant = __decorate([
  __param(0, $kl),
  __param(1, $mJ),
  __param(2, $oG),
  __param(3, $H_)
], TrimWhitespaceParticipant);
var TrimFinalNewLinesParticipant = class TrimFinalNewLinesParticipant2 extends $t3b {
  constructor(e, f, g) {
    super(f);
    this.e = e;
    this.f = f;
    this.g = g;
  }
  async participate(workingCopy, context, progress, _token) {
    if (this.e.getValue("files.trimFinalNewlines") && this.d()) {
      await this.i(workingCopy, context.reason === 2, progress);
    }
  }
  /**
   * returns 0 if the entire file is empty
   */
  h(textBuffer) {
    for (let lineNumber = textBuffer.getLineCount(); lineNumber >= 1; lineNumber--) {
      const lineLength = textBuffer.getLineLength(lineNumber);
      if (lineLength) {
        return lineNumber;
      }
    }
    return 0;
  }
  async i(workingCopy, isAutoSaved, progress) {
    if (!workingCopy.model || !(workingCopy.model instanceof $RSb)) {
      return;
    }
    const disposable = new $2c();
    const notebook = workingCopy.model.notebookModel;
    const activeCellEditor = getActiveCellCodeEditor(this.f);
    try {
      const allCellEdits = await Promise.all(notebook.cells.map(async (cell) => {
        if (cell.cellKind !== CellKind.Code) {
          return;
        }
        let cannotTouchLineNumber = 0;
        const isActiveCell = activeCellEditor && cell.uri.toString() === activeCellEditor.getModel()?.uri.toString();
        if (isAutoSaved && isActiveCell) {
          const selections = activeCellEditor.getSelections() ?? [];
          for (const sel of selections) {
            cannotTouchLineNumber = Math.max(cannotTouchLineNumber, sel.selectionStartLineNumber);
          }
        }
        const textBuffer = cell.textBuffer;
        const lastNonEmptyLine = this.h(textBuffer);
        const deleteFromLineNumber = Math.max(lastNonEmptyLine + 1, cannotTouchLineNumber + 1);
        if (deleteFromLineNumber > textBuffer.getLineCount()) {
          return;
        }
        const deletionRange = new $9C(deleteFromLineNumber, 1, textBuffer.getLineCount(), textBuffer.getLineLastNonWhitespaceColumn(textBuffer.getLineCount()));
        if (deletionRange.isEmpty()) {
          return;
        }
        return new $J_(cell.uri, { range: deletionRange, text: "" }, cell.textModel?.getVersionId());
      }));
      const filteredEdits = allCellEdits.flat().filter((edit3) => edit3 !== void 0);
      await this.g.apply(filteredEdits, { label: localize(8194, null), code: "undoredo.trimFinalNewLines" });
    } finally {
      progress.report({ increment: 100 });
      disposable.dispose();
    }
  }
};
TrimFinalNewLinesParticipant = __decorate([
  __param(0, $kl),
  __param(1, $mJ),
  __param(2, $H_)
], TrimFinalNewLinesParticipant);
var InsertFinalNewLineParticipant = class InsertFinalNewLineParticipant2 extends $t3b {
  constructor(e, f, g) {
    super(g);
    this.e = e;
    this.f = f;
    this.g = g;
  }
  async participate(workingCopy, context, progress, _token) {
    if (this.e.getValue($rM.insertFinalNewline) && this.d()) {
      await this.h(workingCopy, context.reason === 2, progress);
    }
  }
  async h(workingCopy, isAutoSaved, progress) {
    if (!workingCopy.model || !(workingCopy.model instanceof $RSb)) {
      return;
    }
    const disposable = new $2c();
    const notebook = workingCopy.model.notebookModel;
    const activeCellEditor = getActiveCellCodeEditor(this.g);
    let selections;
    if (activeCellEditor) {
      selections = activeCellEditor.getSelections() ?? [];
    }
    try {
      const allCellEdits = await Promise.all(notebook.cells.map(async (cell) => {
        if (cell.cellKind !== CellKind.Code) {
          return;
        }
        const lineCount = cell.textBuffer.getLineCount();
        const lastLineIsEmptyOrWhitespace = cell.textBuffer.getLineFirstNonWhitespaceColumn(lineCount) === 0;
        if (!lineCount || lastLineIsEmptyOrWhitespace) {
          return;
        }
        return new $J_(cell.uri, { range: new $9C(lineCount + 1, cell.textBuffer.getLineLength(lineCount), lineCount + 1, cell.textBuffer.getLineLength(lineCount)), text: cell.textBuffer.getEOL() }, cell.textModel?.getVersionId());
      }));
      const filteredEdits = allCellEdits.filter((edit3) => edit3 !== void 0);
      await this.f.apply(filteredEdits, { label: localize(8195, null), code: "undoredo.insertFinalNewLine" });
      if (activeCellEditor && selections) {
        activeCellEditor.setSelections(selections);
      }
    } finally {
      progress.report({ increment: 100 });
      disposable.dispose();
    }
  }
};
InsertFinalNewLineParticipant = __decorate([
  __param(0, $kl),
  __param(1, $H_),
  __param(2, $mJ)
], InsertFinalNewLineParticipant);
var CodeActionOnSaveParticipant = class CodeActionOnSaveParticipant2 {
  constructor(c, d, e, f, g) {
    this.c = c;
    this.d = d;
    this.e = e;
    this.f = f;
    this.g = g;
  }
  async participate(workingCopy, context, progress, token) {
    const isTrusted = this.e.isWorkspaceTrusted();
    if (!isTrusted) {
      return;
    }
    if (!workingCopy.model || !(workingCopy.model instanceof $RSb)) {
      return;
    }
    let saveTrigger = "";
    if (context.reason === 2) {
      return void 0;
    } else if (context.reason === 1) {
      saveTrigger = "explicit";
    } else {
      return void 0;
    }
    const notebookModel = workingCopy.model.notebookModel;
    const setting = this.c.getValue($rM.codeActionsOnSave);
    const settingItems = Array.isArray(setting) ? setting : Object.keys(setting).filter((x) => setting[x]);
    const allCodeActions = this.h(settingItems);
    const excludedActions = allCodeActions.filter((x) => setting[x.value] === "never" || setting[x.value] === false);
    const includedActions = allCodeActions.filter((x) => setting[x.value] === saveTrigger || setting[x.value] === true);
    const editorCodeActionsOnSave = includedActions.filter((x) => !$pab.Notebook.contains(x));
    const notebookCodeActionsOnSave = includedActions.filter((x) => $pab.Notebook.contains(x));
    if (notebookCodeActionsOnSave.length) {
      const nbDisposable = new $2c();
      progress.report({ message: localize(8196, null) });
      try {
        const cell = notebookModel.cells[0];
        const ref = await this.f.createModelReference(cell.uri);
        nbDisposable.add(ref);
        const textEditorModel = ref.object.textEditorModel;
        await this.g.invokeFunction($u3b.applyOnSaveGenericCodeActions, textEditorModel, notebookCodeActionsOnSave, excludedActions, progress, token);
      } catch {
        this.d.error("Failed to apply notebook code action on save");
      } finally {
        progress.report({ increment: 100 });
        nbDisposable.dispose();
      }
    }
    if (editorCodeActionsOnSave.length) {
      if (!Array.isArray(setting)) {
        editorCodeActionsOnSave.sort((a, b) => {
          if ($pab.SourceFixAll.contains(a)) {
            if ($pab.SourceFixAll.contains(b)) {
              return 0;
            }
            return -1;
          }
          if ($pab.SourceFixAll.contains(b)) {
            return 1;
          }
          return 0;
        });
      }
      const cellDisposable = new $2c();
      progress.report({ message: localize(8197, null) });
      try {
        await Promise.all(notebookModel.cells.map(async (cell) => {
          const ref = await this.f.createModelReference(cell.uri);
          cellDisposable.add(ref);
          const textEditorModel = ref.object.textEditorModel;
          await this.g.invokeFunction($u3b.applyOnSaveGenericCodeActions, textEditorModel, editorCodeActionsOnSave, excludedActions, progress, token);
        }));
      } catch {
        this.d.error("Failed to apply code action on save");
      } finally {
        progress.report({ increment: 100 });
        cellDisposable.dispose();
      }
    }
  }
  h(settingItems) {
    const kinds = settingItems.map((x) => new $oE(x));
    return kinds.filter((kind) => {
      return kinds.every((otherKind) => otherKind.equals(kind) || !otherKind.contains(kind));
    });
  }
};
CodeActionOnSaveParticipant = __decorate([
  __param(0, $kl),
  __param(1, $wn),
  __param(2, $4M),
  __param(3, $oG),
  __param(4, $Pk)
], CodeActionOnSaveParticipant);
var $u3b = class _$u3b {
  static async checkAndRunFormatCodeAction(accessor, notebookModel, progress, token) {
    const instantiationService = accessor.get($Pk);
    const textModelService = accessor.get($oG);
    const logService = accessor.get($wn);
    const configurationService = accessor.get($kl);
    const formatDisposable = new $2c();
    let formatResult = false;
    progress.report({ message: localize(8198, null) });
    try {
      const cell = notebookModel.cells[0];
      const ref = await textModelService.createModelReference(cell.uri);
      formatDisposable.add(ref);
      const textEditorModel = ref.object.textEditorModel;
      const defaultFormatterExtId = configurationService.getValue($rM.defaultFormatter);
      formatResult = await instantiationService.invokeFunction(_$u3b.applyOnSaveFormatCodeAction, textEditorModel, new $oE("notebook.format"), [], defaultFormatterExtId, progress, token);
    } catch {
      logService.error("Failed to apply notebook format action on save");
    } finally {
      progress.report({ increment: 100 });
      formatDisposable.dispose();
    }
    return formatResult;
  }
  static async applyOnSaveGenericCodeActions(accessor, model, codeActionsOnSave, excludes, progress, token) {
    const instantiationService = accessor.get($Pk);
    const languageFeaturesService = accessor.get($mP);
    const logService = accessor.get($wn);
    const getActionProgress = new class {
      constructor() {
        this.c = /* @__PURE__ */ new Set();
      }
      d() {
        progress.report({
          message: localize(8199, null, [...this.c].map((name) => `'${name}'`).join(", "), "command:workbench.action.openSettings?%5B%22notebook.codeActionsOnSave%22%5D")
        });
      }
      report(provider) {
        if (provider.displayName && !this.c.has(provider.displayName)) {
          this.c.add(provider.displayName);
          this.d();
        }
      }
    }();
    for (const codeActionKind of codeActionsOnSave) {
      const actionsToRun = await _$u3b.getActionsToRun(model, codeActionKind, excludes, languageFeaturesService, getActionProgress, token);
      if (token.isCancellationRequested) {
        actionsToRun.dispose();
        return;
      }
      try {
        for (const action of actionsToRun.validActions) {
          const codeActionEdits = action.action.edit?.edits;
          let breakFlag = false;
          if (!action.action.kind?.startsWith("notebook")) {
            for (const edit3 of codeActionEdits ?? []) {
              const workspaceTextEdit = edit3;
              if (workspaceTextEdit.resource && $oh(workspaceTextEdit.resource, model.uri)) {
                continue;
              } else {
                breakFlag = true;
                break;
              }
            }
          }
          if (breakFlag) {
            logService.warn("Failed to apply code action on save, applied to multiple resources.");
            continue;
          }
          progress.report({ message: localize(8200, null, action.action.title) });
          await instantiationService.invokeFunction($Dab, action, ApplyCodeActionReason.OnSave, {}, token);
          if (token.isCancellationRequested) {
            return;
          }
        }
      } catch {
      } finally {
        actionsToRun.dispose();
      }
    }
  }
  static async applyOnSaveFormatCodeAction(accessor, model, formatCodeActionOnSave, excludes, extensionId, progress, token) {
    const instantiationService = accessor.get($Pk);
    const languageFeaturesService = accessor.get($mP);
    const logService = accessor.get($wn);
    const getActionProgress = new class {
      constructor() {
        this.c = /* @__PURE__ */ new Set();
      }
      d() {
        progress.report({
          message: localize(8201, null, [...this.c].map((name) => `'${name}'`).join(", "), "command:workbench.action.openSettings?%5B%22notebook.defaultFormatter%22%5D")
        });
      }
      report(provider) {
        if (provider.displayName && !this.c.has(provider.displayName)) {
          this.c.add(provider.displayName);
          this.d();
        }
      }
    }();
    const providedActions = await _$u3b.getActionsToRun(model, formatCodeActionOnSave, excludes, languageFeaturesService, getActionProgress, token);
    if (providedActions.validActions.length > 1 && !extensionId) {
      logService.warn("More than one format code action is provided, the 0th one will be used. A default can be specified via `notebook.defaultFormatter` in your settings.");
    }
    if (token.isCancellationRequested) {
      providedActions.dispose();
      return false;
    }
    try {
      const action = extensionId ? providedActions.validActions.find((action2) => action2.provider?.extensionId === extensionId) : providedActions.validActions[0];
      if (!action) {
        return false;
      }
      progress.report({ message: localize(8202, null, action.action.title) });
      await instantiationService.invokeFunction($Dab, action, ApplyCodeActionReason.OnSave, {}, token);
      if (token.isCancellationRequested) {
        return false;
      }
    } catch {
      logService.error("Failed to apply notebook format code action on save");
      return false;
    } finally {
      providedActions.dispose();
    }
    return true;
  }
  // @Yoyokrazy this could likely be modified to leverage the extensionID, therefore not getting actions from providers unnecessarily -- future work
  static getActionsToRun(model, codeActionKind, excludes, languageFeaturesService, progress, token) {
    return $Cab(languageFeaturesService.codeActionProvider, model, model.getFullModelRange(), {
      type: 1,
      triggerAction: CodeActionTriggerSource.OnSave,
      filter: { include: codeActionKind, excludes, includeSourceActions: true }
    }, progress, token);
  }
};
function getActiveCellCodeEditor(editorService) {
  const activePane = editorService.activeEditorPane;
  const notebookEditor = $Qrb(activePane);
  const activeCodeEditor = notebookEditor?.activeCodeEditor;
  return activeCodeEditor;
}
var $v3b = class $v3b2 extends $3c {
  constructor(c, f) {
    super();
    this.c = c;
    this.f = f;
    this.g();
  }
  g() {
    this.B(this.f.addSaveParticipant(this.c.createInstance(TrimWhitespaceParticipant)));
    this.B(this.f.addSaveParticipant(this.c.createInstance(CodeActionOnSaveParticipant)));
    this.B(this.f.addSaveParticipant(this.c.createInstance(FormatOnSaveParticipant)));
    this.B(this.f.addSaveParticipant(this.c.createInstance(InsertFinalNewLineParticipant)));
    this.B(this.f.addSaveParticipant(this.c.createInstance(TrimFinalNewLinesParticipant)));
  }
};
$v3b = __decorate([
  __param(0, $Pk),
  __param(1, $aK)
], $v3b);
var workbenchContributionsRegistry2 = $Wn.as(Extensions2.Workbench);
workbenchContributionsRegistry2.registerWorkbenchContribution(
  $v3b,
  3
  /* LifecyclePhase.Restored */
);

// out-build/vs/workbench/contrib/notebook/browser/contrib/format/formatting.js
$hJ(class extends $gJ {
  constructor() {
    super({
      id: "notebook.format",
      title: localize2(8151, "Format Notebook"),
      category: $xIb,
      precondition: $7m.and($SAb, $1Ab),
      keybinding: {
        when: EditorContextKeys.editorTextFocus.toNegated(),
        primary: 1024 | 512 | 36,
        linux: {
          primary: 2048 | 1024 | 39
          /* KeyCode.KeyI */
        },
        weight: 200
        /* KeybindingWeight.WorkbenchContrib */
      },
      f1: true,
      menu: {
        id: $bJ.EditorContext,
        when: $7m.and(EditorContextKeys.inCompositeEditor, EditorContextKeys.hasDocumentFormattingProvider),
        group: "1_modification",
        order: 1.3
      }
    });
  }
  async run(accessor) {
    const editorService = accessor.get($mJ);
    const textModelService = accessor.get($oG);
    const editorWorkerService = accessor.get($I0);
    const languageFeaturesService = accessor.get($mP);
    const bulkEditService = accessor.get($H_);
    const instantiationService = accessor.get($Pk);
    const editor = $Qrb(editorService.activeEditorPane);
    if (!editor || !editor.hasModel()) {
      return;
    }
    const notebook = editor.textModel;
    const formatApplied = await instantiationService.invokeFunction($u3b.checkAndRunFormatCodeAction, notebook, $VJ.None, CancellationToken.None);
    const disposable = new $2c();
    try {
      if (!formatApplied) {
        const allCellEdits = await Promise.all(notebook.cells.map(async (cell) => {
          const ref = await textModelService.createModelReference(cell.uri);
          disposable.add(ref);
          const model = ref.object.textEditorModel;
          const formatEdits = await $ihb(editorWorkerService, languageFeaturesService, model, 1, CancellationToken.None);
          const edits = [];
          if (formatEdits) {
            for (const edit3 of formatEdits) {
              edits.push(new $J_(model.uri, edit3, model.getVersionId()));
            }
            return edits;
          }
          return [];
        }));
        await bulkEditService.apply(
          /* edit */
          allCellEdits.flat(),
          { label: localize(8149, null), code: "undoredo.formatNotebook" }
        );
      }
    } finally {
      disposable.dispose();
    }
  }
});
$55(class FormatCellAction extends $Z5 {
  constructor() {
    super({
      id: "notebook.formatCell",
      label: localize2(8152, "Format Cell"),
      precondition: $7m.and($SAb, $1Ab, EditorContextKeys.inCompositeEditor, EditorContextKeys.writable, EditorContextKeys.hasDocumentFormattingProvider),
      kbOpts: {
        kbExpr: $7m.and(EditorContextKeys.editorTextFocus),
        primary: 1024 | 512 | 36,
        linux: {
          primary: 2048 | 1024 | 39
          /* KeyCode.KeyI */
        },
        weight: 100
        /* KeybindingWeight.EditorContrib */
      },
      contextMenuOpts: {
        group: "1_modification",
        order: 1.301
      }
    });
  }
  async run(accessor, editor) {
    if (editor.hasModel()) {
      const instaService = accessor.get($Pk);
      await instaService.invokeFunction($ehb, editor, 1, $VJ.None, CancellationToken.None, true);
    }
  }
});
var FormatOnCellExecutionParticipant = class FormatOnCellExecutionParticipant2 {
  constructor(a, b, c, d, e, f) {
    this.a = a;
    this.b = b;
    this.c = c;
    this.d = d;
    this.e = e;
    this.f = f;
  }
  async onWillExecuteCell(executions) {
    const enabled = this.e.getValue($rM.formatOnCellExecution);
    if (!enabled) {
      return;
    }
    const disposable = new $2c();
    try {
      const allCellEdits = await Promise.all(executions.map(async (cellExecution) => {
        const nbModel = this.f.getNotebookTextModel(cellExecution.notebook);
        if (!nbModel) {
          return [];
        }
        let activeCell;
        for (const cell of nbModel.cells) {
          if (cell.handle === cellExecution.cellHandle) {
            activeCell = cell;
            break;
          }
        }
        if (!activeCell) {
          return [];
        }
        const ref = await this.c.createModelReference(activeCell.uri);
        disposable.add(ref);
        const model = ref.object.textEditorModel;
        const formatEdits = await $ihb(this.d, this.b, model, 2, CancellationToken.None);
        const edits = [];
        if (formatEdits) {
          edits.push(...formatEdits.map((edit3) => new $J_(model.uri, edit3, model.getVersionId())));
          return edits;
        }
        return [];
      }));
      await this.a.apply(
        /* edit */
        allCellEdits.flat(),
        { label: localize(8150, null), code: "undoredo.notebooks.onWillExecuteFormat" }
      );
    } finally {
      disposable.dispose();
    }
  }
};
FormatOnCellExecutionParticipant = __decorate([
  __param(0, $H_),
  __param(1, $mP),
  __param(2, $oG),
  __param(3, $I0),
  __param(4, $kl),
  __param(5, $mrb)
], FormatOnCellExecutionParticipant);
var $w3b = class $w3b2 extends $3c {
  constructor(a, b) {
    super();
    this.a = a;
    this.b = b;
    this.c();
  }
  c() {
    this.B(this.b.registerExecutionParticipant(this.a.createInstance(FormatOnCellExecutionParticipant)));
  }
};
$w3b = __decorate([
  __param(0, $Pk),
  __param(1, $vL)
], $w3b);
var workbenchContributionsRegistry3 = $Wn.as(Extensions2.Workbench);
workbenchContributionsRegistry3.registerWorkbenchContribution(
  $w3b,
  3
  /* LifecyclePhase.Restored */
);

// out-build/vs/workbench/contrib/notebook/browser/contrib/gettingStarted/notebookGettingStarted.js
var hasOpenedNotebookKey = "hasOpenedNotebook";
var hasShownGettingStartedKey = "hasShownNotebookGettingStarted";
var $x3b = class $x3b2 extends $3c {
  constructor(_editorService, _storageService, _contextKeyService, _commandService, _configurationService) {
    super();
    const hasOpenedNotebook = $OAb.bindTo(_contextKeyService);
    const memento = new $Slb("notebookGettingStarted2", _storageService);
    const storedValue = memento.getMemento(
      0,
      0
      /* StorageTarget.USER */
    );
    if (storedValue[hasOpenedNotebookKey]) {
      hasOpenedNotebook.set(true);
    }
    const needToShowGettingStarted = _configurationService.getValue($rM.openGettingStarted) && !storedValue[hasShownGettingStartedKey];
    if (!storedValue[hasOpenedNotebookKey] || needToShowGettingStarted) {
      const onDidOpenNotebook = () => {
        hasOpenedNotebook.set(true);
        storedValue[hasOpenedNotebookKey] = true;
        if (needToShowGettingStarted) {
          _commandService.executeCommand("workbench.action.openWalkthrough", { category: "notebooks", step: "notebookProfile" }, true);
          storedValue[hasShownGettingStartedKey] = true;
        }
        memento.saveMemento();
      };
      if (_editorService.activeEditor?.typeId === $trb.ID) {
        onDidOpenNotebook();
        return;
      }
      const listener = this.B(_editorService.onDidActiveEditorChange(() => {
        if (_editorService.activeEditor?.typeId === $trb.ID) {
          listener.dispose();
          onDidOpenNotebook();
        }
      }));
    }
  }
};
$x3b = __decorate([
  __param(0, $mJ),
  __param(1, $jv),
  __param(2, $on),
  __param(3, $sn),
  __param(4, $kl)
], $x3b);
$Wn.as(Extensions2.Workbench).registerWorkbenchContribution(
  $x3b,
  3
  /* LifecyclePhase.Restored */
);
$hJ(class NotebookClearNotebookLayoutAction extends $gJ {
  constructor() {
    super({
      id: "workbench.notebook.layout.gettingStarted",
      title: localize2(8153, "Reset notebook getting started"),
      f1: true,
      precondition: $7m.equals(`config.${$rM.openGettingStarted}`, true),
      category: $qn.Developer
    });
  }
  run(accessor) {
    const storageService = accessor.get($jv);
    const memento = new $Slb("notebookGettingStarted", storageService);
    const storedValue = memento.getMemento(
      0,
      0
      /* StorageTarget.USER */
    );
    storedValue[hasOpenedNotebookKey] = void 0;
    memento.saveMemento();
  }
});

// out-build/vs/workbench/contrib/notebook/browser/contrib/layout/layoutActions.js
var TOGGLE_CELL_TOOLBAR_POSITION = "notebook.toggleCellToolbarPosition";
var $y3b = class extends $gJ {
  constructor() {
    super({
      id: TOGGLE_CELL_TOOLBAR_POSITION,
      title: localize2(8154, "Toggle Cell Toolbar Position"),
      menu: [{
        id: $bJ.NotebookCellTitle,
        group: "View",
        order: 1
      }],
      category: $xIb,
      f1: false
    });
  }
  async run(accessor, context) {
    const editor = context && context.ui ? context.notebookEditor : void 0;
    if (editor && editor.hasModel()) {
      const viewType = editor.textModel.viewType;
      const configurationService = accessor.get($kl);
      const toolbarPosition = configurationService.getValue($rM.cellToolbarLocation);
      const newConfig = this.togglePosition(viewType, toolbarPosition);
      await configurationService.updateValue($rM.cellToolbarLocation, newConfig);
    }
  }
  togglePosition(viewType, toolbarPosition) {
    if (typeof toolbarPosition === "string") {
      if (["left", "right", "hidden"].indexOf(toolbarPosition) >= 0) {
        const newViewValue = toolbarPosition === "right" ? "left" : "right";
        const config = {
          default: toolbarPosition
        };
        config[viewType] = newViewValue;
        return config;
      } else {
        const config = {
          default: "right"
        };
        config[viewType] = "left";
        return config;
      }
    } else {
      const oldValue = toolbarPosition[viewType] ?? toolbarPosition["default"] ?? "right";
      const newViewValue = oldValue === "right" ? "left" : "right";
      const newConfig = {
        ...toolbarPosition
      };
      newConfig[viewType] = newViewValue;
      return newConfig;
    }
  }
};
$hJ($y3b);

// out-build/vs/workbench/contrib/notebook/browser/contrib/marker/markerProvider.js
var MarkerListProvider = class MarkerListProvider2 {
  static {
    this.ID = "workbench.contrib.markerListProvider";
  }
  constructor(b, markerNavigation, c) {
    this.b = b;
    this.c = c;
    this.a = markerNavigation.registerProvider(this);
  }
  dispose() {
    this.a.dispose();
  }
  getMarkerList(resource) {
    if (!resource) {
      return void 0;
    }
    const data = CellUri.parse(resource);
    if (!data) {
      return void 0;
    }
    return new $kib((uri) => {
      const otherData = CellUri.parse(uri);
      return otherData?.notebook.toString() === data.notebook.toString();
    }, this.b, this.c);
  }
};
MarkerListProvider = __decorate([
  __param(0, $DE),
  __param(1, $lib),
  __param(2, $kl)
], MarkerListProvider);
var NotebookMarkerDecorationContribution = class NotebookMarkerDecorationContribution2 extends $3c {
  static {
    this.id = "workbench.notebook.markerDecoration";
  }
  constructor(b, c) {
    super();
    this.b = b;
    this.c = c;
    this.a = [];
    this.f();
    this.B(this.b.onDidChangeModel(() => this.f()));
    this.B(this.c.onMarkerChanged((e) => {
      if (e.some((uri) => this.b.getCellsInRange().some((cell) => $oh(cell.uri, uri)))) {
        this.f();
      }
    }));
  }
  f() {
    if (!this.b.hasModel()) {
      return;
    }
    const cellDecorations = [];
    this.b.getCellsInRange().forEach((cell) => {
      const marker = this.c.read({ resource: cell.uri, severities: MarkerSeverity.Error | MarkerSeverity.Warning });
      marker.forEach((m) => {
        const color2 = m.severity === MarkerSeverity.Error ? $Vo : $Yo;
        const range = { startLineNumber: m.startLineNumber, startColumn: m.startColumn, endLineNumber: m.endLineNumber, endColumn: m.endColumn };
        cellDecorations.push({
          handle: cell.handle,
          options: {
            overviewRuler: {
              color: color2,
              modelRanges: [range],
              includeOutput: false,
              position: NotebookOverviewRulerLane.Right
            }
          }
        });
      });
    });
    this.a = this.b.deltaCellDecorations(this.a, cellDecorations);
  }
};
__decorate([
  $_t(100)
], NotebookMarkerDecorationContribution.prototype, "f", null);
NotebookMarkerDecorationContribution = __decorate([
  __param(1, $DE)
], NotebookMarkerDecorationContribution);
$PL(
  MarkerListProvider.ID,
  MarkerListProvider,
  2
  /* WorkbenchPhase.BlockRestore */
);
$iGb(NotebookMarkerDecorationContribution.id, NotebookMarkerDecorationContribution);

// out-build/vs/workbench/contrib/notebook/browser/contrib/navigation/arrow.js
var NOTEBOOK_FOCUS_TOP = "notebook.focusTop";
var NOTEBOOK_FOCUS_BOTTOM = "notebook.focusBottom";
var NOTEBOOK_FOCUS_PREVIOUS_EDITOR = "notebook.focusPreviousEditor";
var NOTEBOOK_FOCUS_NEXT_EDITOR = "notebook.focusNextEditor";
var FOCUS_IN_OUTPUT_COMMAND_ID = "notebook.cell.focusInOutput";
var FOCUS_OUT_OUTPUT_COMMAND_ID = "notebook.cell.focusOutOutput";
var $z3b = "notebook.centerActiveCell";
var NOTEBOOK_CURSOR_PAGEUP_COMMAND_ID = "notebook.cell.cursorPageUp";
var NOTEBOOK_CURSOR_PAGEUP_SELECT_COMMAND_ID = "notebook.cell.cursorPageUpSelect";
var NOTEBOOK_CURSOR_PAGEDOWN_COMMAND_ID = "notebook.cell.cursorPageDown";
var NOTEBOOK_CURSOR_PAGEDOWN_SELECT_COMMAND_ID = "notebook.cell.cursorPageDownSelect";
$hJ(class extends $gJ {
  constructor() {
    super({
      id: "notebook.cell.nullAction",
      title: localize(8160, null),
      keybinding: [{
        when: $ZAb,
        primary: 18,
        weight: 200 + 1
      }, {
        when: $ZAb,
        primary: 16,
        weight: 200 + 1
      }],
      f1: false
    });
  }
  run() {
    return;
  }
});
$hJ(class FocusNextCellAction extends $HIb {
  constructor() {
    super({
      id: NOTEBOOK_FOCUS_NEXT_EDITOR,
      title: localize(8161, null),
      keybinding: [
        {
          when: $7m.and($WAb, $OD.negate(), $7m.equals("config.notebook.navigation.allowNavigateToSurroundingCells", true), $7m.and($7m.has($Beb), EditorContextKeys.editorTextFocus, $nM.notEqualsTo("top"), $nM.notEqualsTo("none")), EditorContextKeys.isEmbeddedDiffEditor.negate()),
          primary: 18,
          weight: $AIb
          // code cell keybinding, focus inside editor: lower weight to not override suggest widget
        },
        {
          when: $7m.and($WAb, $OD.negate(), $7m.equals("config.notebook.navigation.allowNavigateToSurroundingCells", true), $7m.and($0Ab.isEqualTo("markup"), $bBb.isEqualTo(false), $7Ab), EditorContextKeys.isEmbeddedDiffEditor.negate()),
          primary: 18,
          weight: 200
          // markdown keybinding, focus on list: higher weight to override list.focusDown
        },
        {
          when: $7m.and($WAb, $YAb),
          primary: 2048 | 18,
          mac: { primary: 256 | 2048 | 18 },
          weight: 200
          /* KeybindingWeight.WorkbenchContrib */
        },
        {
          when: $7m.and($aBb, $OD),
          primary: 2048 | 12,
          mac: { primary: 256 | 11 },
          weight: 200 + 1
        }
      ]
    });
  }
  async runWithContext(accessor, context) {
    const editor = context.notebookEditor;
    const activeCell = context.cell;
    const idx = editor.getCellIndex(activeCell);
    if (typeof idx !== "number") {
      return;
    }
    if (idx >= editor.getLength() - 1) {
      return;
    }
    const focusEditorLine = activeCell.textBuffer.getLineCount();
    const targetCell = context.cell ?? context.selectedCells?.[0];
    const foundEditor = targetCell ? $EIb(context, targetCell) : void 0;
    if (foundEditor && foundEditor.hasTextFocus() && $cHb.get(foundEditor)?.getWidgetPosition()?.lineNumber === focusEditorLine) {
      $cHb.get(foundEditor)?.focus();
    } else {
      const newCell = editor.cellAt(idx + 1);
      const newFocusMode = newCell.cellKind === CellKind.Markup && newCell.getEditState() === CellEditState.Preview ? "container" : "editor";
      await editor.focusNotebookCell(newCell, newFocusMode, { focusEditorLine: 1 });
    }
  }
});
$hJ(class FocusPreviousCellAction extends $HIb {
  constructor() {
    super({
      id: NOTEBOOK_FOCUS_PREVIOUS_EDITOR,
      title: localize(8162, null),
      keybinding: [
        {
          when: $7m.and($WAb, $OD.negate(), $7m.equals("config.notebook.navigation.allowNavigateToSurroundingCells", true), $7m.and($7m.has($Beb), EditorContextKeys.editorTextFocus, $nM.notEqualsTo("bottom"), $nM.notEqualsTo("none")), EditorContextKeys.isEmbeddedDiffEditor.negate()),
          primary: 16,
          weight: $AIb
          // code cell keybinding, focus inside editor: lower weight to not override suggest widget
        },
        {
          when: $7m.and($WAb, $OD.negate(), $7m.equals("config.notebook.navigation.allowNavigateToSurroundingCells", true), $7m.and($0Ab.isEqualTo("markup"), $bBb.isEqualTo(false), $7Ab), EditorContextKeys.isEmbeddedDiffEditor.negate()),
          primary: 16,
          weight: 200
          // markdown keybinding, focus on list: higher weight to override list.focusDown
        },
        {
          when: $7m.and($aBb, $OD),
          primary: 2048 | 11,
          mac: { primary: 256 | 11 },
          weight: 200 + 1
        }
      ]
    });
  }
  async runWithContext(accessor, context) {
    const editor = context.notebookEditor;
    const activeCell = context.cell;
    const idx = editor.getCellIndex(activeCell);
    if (typeof idx !== "number") {
      return;
    }
    if (idx < 1 || editor.getLength() === 0) {
      return;
    }
    const newCell = editor.cellAt(idx - 1);
    const newFocusMode = newCell.cellKind === CellKind.Markup && newCell.getEditState() === CellEditState.Preview ? "container" : "editor";
    const focusEditorLine = newCell.textBuffer.getLineCount();
    await editor.focusNotebookCell(newCell, newFocusMode, { focusEditorLine });
    const foundEditor = $EIb(context, newCell);
    if (foundEditor && $cHb.get(foundEditor)?.getWidgetPosition()?.lineNumber === focusEditorLine) {
      $cHb.get(foundEditor)?.focus();
    }
  }
});
$hJ(class extends $FIb {
  constructor() {
    super({
      id: NOTEBOOK_FOCUS_TOP,
      title: localize(8163, null),
      keybinding: [
        {
          when: $7m.and($WAb, $7m.not($Beb)),
          primary: 2048 | 14,
          weight: 200
          /* KeybindingWeight.WorkbenchContrib */
        },
        {
          when: $7m.and($WAb, $7m.not($Beb), $cJb.isEqualTo("")),
          mac: {
            primary: 2048 | 16
            /* KeyCode.UpArrow */
          },
          weight: 200
          /* KeybindingWeight.WorkbenchContrib */
        }
      ]
    });
  }
  async runWithContext(accessor, context) {
    const editor = context.notebookEditor;
    if (editor.getLength() === 0) {
      return;
    }
    const firstCell = editor.cellAt(0);
    await editor.focusNotebookCell(firstCell, "container");
  }
});
$hJ(class extends $FIb {
  constructor() {
    super({
      id: NOTEBOOK_FOCUS_BOTTOM,
      title: localize(8164, null),
      keybinding: [
        {
          when: $7m.and($WAb, $7m.not($Beb)),
          primary: 2048 | 13,
          mac: void 0,
          weight: 200
          /* KeybindingWeight.WorkbenchContrib */
        },
        {
          when: $7m.and($WAb, $7m.not($Beb), $cJb.isEqualTo("")),
          mac: {
            primary: 2048 | 18
            /* KeyCode.DownArrow */
          },
          weight: 200
          /* KeybindingWeight.WorkbenchContrib */
        }
      ]
    });
  }
  async runWithContext(accessor, context) {
    const editor = context.notebookEditor;
    if (!editor.hasModel() || editor.getLength() === 0) {
      return;
    }
    const lastIdx = editor.getLength() - 1;
    const lastVisibleIdx = editor.getPreviousVisibleCellIndex(lastIdx);
    if (lastVisibleIdx) {
      const cell = editor.cellAt(lastVisibleIdx);
      await editor.focusNotebookCell(cell, "container");
    }
  }
});
$hJ(class extends $HIb {
  constructor() {
    super({
      id: FOCUS_IN_OUTPUT_COMMAND_ID,
      title: localize(8165, null),
      keybinding: [{
        when: $7m.and($VAb.negate(), $ueb),
        primary: 2048 | 18,
        weight: 200
        /* KeybindingWeight.WorkbenchContrib */
      }, {
        primary: 2048 | 1024 | 18,
        mac: { primary: 256 | 2048 | 18 },
        weight: 200
        /* KeybindingWeight.WorkbenchContrib */
      }],
      precondition: $7m.and($WAb, $fBb)
    });
  }
  async runWithContext(accessor, context) {
    const editor = context.notebookEditor;
    const activeCell = context.cell;
    return $Wh(0).then(() => editor.focusNotebookCell(activeCell, "output"));
  }
});
$hJ(class extends $HIb {
  constructor() {
    super({
      id: FOCUS_OUT_OUTPUT_COMMAND_ID,
      title: localize(8166, null),
      keybinding: {
        primary: 2048 | 1024 | 16,
        mac: { primary: 256 | 2048 | 16 },
        weight: 200
        /* KeybindingWeight.WorkbenchContrib */
      },
      precondition: $7m.and($WAb, $YAb)
    });
  }
  async runWithContext(accessor, context) {
    const editor = context.notebookEditor;
    const activeCell = context.cell;
    await editor.focusNotebookCell(activeCell, "editor");
  }
});
$hJ(class CenterActiveCellAction extends $HIb {
  constructor() {
    super({
      id: $z3b,
      title: localize(8167, null),
      keybinding: {
        when: $WAb,
        primary: 2048 | 42,
        mac: {
          primary: 256 | 42
        },
        weight: 200
        /* KeybindingWeight.WorkbenchContrib */
      }
    });
  }
  async runWithContext(accessor, context) {
    return context.notebookEditor.revealInCenter(context.cell);
  }
});
$hJ(class extends $HIb {
  constructor() {
    super({
      id: NOTEBOOK_CURSOR_PAGEUP_COMMAND_ID,
      title: localize(8168, null),
      keybinding: [
        {
          when: $7m.and($WAb, $7m.has($Beb), EditorContextKeys.editorTextFocus),
          primary: 11,
          weight: $AIb
        }
      ]
    });
  }
  async runWithContext(accessor, context) {
    EditorExtensionsRegistry.getEditorCommand("cursorPageUp").runCommand(accessor, { pageSize: getPageSize(context) });
  }
});
$hJ(class extends $HIb {
  constructor() {
    super({
      id: NOTEBOOK_CURSOR_PAGEUP_SELECT_COMMAND_ID,
      title: localize(8169, null),
      keybinding: [
        {
          when: $7m.and($WAb, $7m.has($Beb), EditorContextKeys.editorTextFocus, $YAb.negate()),
          primary: 1024 | 11,
          weight: $AIb
        }
      ]
    });
  }
  async runWithContext(accessor, context) {
    EditorExtensionsRegistry.getEditorCommand("cursorPageUpSelect").runCommand(accessor, { pageSize: getPageSize(context) });
  }
});
$hJ(class extends $HIb {
  constructor() {
    super({
      id: NOTEBOOK_CURSOR_PAGEDOWN_COMMAND_ID,
      title: localize(8170, null),
      keybinding: [
        {
          when: $7m.and($WAb, $7m.has($Beb), EditorContextKeys.editorTextFocus),
          primary: 12,
          weight: $AIb
        }
      ]
    });
  }
  async runWithContext(accessor, context) {
    EditorExtensionsRegistry.getEditorCommand("cursorPageDown").runCommand(accessor, { pageSize: getPageSize(context) });
  }
});
$hJ(class extends $HIb {
  constructor() {
    super({
      id: NOTEBOOK_CURSOR_PAGEDOWN_SELECT_COMMAND_ID,
      title: localize(8171, null),
      keybinding: [
        {
          when: $7m.and($WAb, $7m.has($Beb), EditorContextKeys.editorTextFocus, $YAb.negate()),
          primary: 1024 | 12,
          weight: $AIb
        }
      ]
    });
  }
  async runWithContext(accessor, context) {
    EditorExtensionsRegistry.getEditorCommand("cursorPageDownSelect").runCommand(accessor, { pageSize: getPageSize(context) });
  }
});
function getPageSize(context) {
  const editor = context.notebookEditor;
  const layoutInfo = editor.getViewModel().layoutInfo;
  const lineHeight = layoutInfo?.fontInfo.lineHeight || 17;
  return Math.max(1, Math.floor((layoutInfo?.height || 0) / lineHeight) - 2);
}
$Wn.as($Ht.Configuration).registerConfiguration({
  id: "notebook",
  order: 100,
  type: "object",
  "properties": {
    "notebook.navigation.allowNavigateToSurroundingCells": {
      type: "boolean",
      default: true,
      markdownDescription: localize(8172, null)
    }
  }
});

// out-build/vs/workbench/contrib/notebook/browser/contrib/profile/notebookProfile.js
var NotebookProfileType;
(function(NotebookProfileType2) {
  NotebookProfileType2["default"] = "default";
  NotebookProfileType2["jupyter"] = "jupyter";
  NotebookProfileType2["colab"] = "colab";
})(NotebookProfileType || (NotebookProfileType = {}));
var profiles = {
  [NotebookProfileType.default]: {
    [$rM.focusIndicator]: "gutter",
    [$rM.insertToolbarLocation]: "both",
    [$rM.globalToolbar]: true,
    [$rM.cellToolbarLocation]: { default: "right" },
    [$rM.compactView]: true,
    [$rM.showCellStatusBar]: "visible",
    [$rM.consolidatedRunButton]: true,
    [$rM.undoRedoPerCell]: false
  },
  [NotebookProfileType.jupyter]: {
    [$rM.focusIndicator]: "gutter",
    [$rM.insertToolbarLocation]: "notebookToolbar",
    [$rM.globalToolbar]: true,
    [$rM.cellToolbarLocation]: { default: "left" },
    [$rM.compactView]: true,
    [$rM.showCellStatusBar]: "visible",
    [$rM.consolidatedRunButton]: false,
    [$rM.undoRedoPerCell]: true
  },
  [NotebookProfileType.colab]: {
    [$rM.focusIndicator]: "border",
    [$rM.insertToolbarLocation]: "betweenCells",
    [$rM.globalToolbar]: false,
    [$rM.cellToolbarLocation]: { default: "right" },
    [$rM.compactView]: false,
    [$rM.showCellStatusBar]: "hidden",
    [$rM.consolidatedRunButton]: true,
    [$rM.undoRedoPerCell]: false
  }
};
async function applyProfile(configService, profile) {
  const promises = [];
  for (const settingKey in profile) {
    promises.push(configService.updateValue(settingKey, profile[settingKey]));
  }
  await Promise.all(promises);
}
$hJ(class extends $gJ {
  constructor() {
    super({
      id: "notebook.setProfile",
      title: localize(8190, null)
    });
  }
  async run(accessor, args2) {
    if (!isSetProfileArgs(args2)) {
      return;
    }
    const configService = accessor.get($kl);
    return applyProfile(configService, profiles[args2.profile]);
  }
});
function isSetProfileArgs(args2) {
  const setProfileArgs = args2;
  return setProfileArgs.profile === NotebookProfileType.colab || setProfileArgs.profile === NotebookProfileType.default || setProfileArgs.profile === NotebookProfileType.jupyter;
}

// out-build/vs/workbench/contrib/notebook/browser/contrib/cellStatusBar/statusBarProviders.js
var CellStatusBarLanguagePickerProvider = class CellStatusBarLanguagePickerProvider2 {
  constructor(a, b) {
    this.a = a;
    this.b = b;
    this.viewType = "*";
  }
  async provideCellStatusBarItems(uri, index, _token) {
    const doc = this.a.getNotebookTextModel(uri);
    const cell = doc?.cells[index];
    if (!cell) {
      return;
    }
    const statusBarItems = [];
    let displayLanguage = cell.language;
    if (cell.cellKind === CellKind.Markup) {
      displayLanguage = "markdown";
    } else {
      const registeredId = this.b.getLanguageIdByLanguageName(cell.language);
      if (registeredId) {
        displayLanguage = this.b.getLanguageName(displayLanguage) ?? displayLanguage;
      } else {
        const searchTooltip = localize(8107, null, cell.language);
        statusBarItems.push({
          text: `$(dialog-warning)`,
          command: { id: "workbench.extensions.search", arguments: [`@tag:${cell.language}`], title: "Search Extensions" },
          tooltip: searchTooltip,
          alignment: 2,
          priority: -Number.MAX_SAFE_INTEGER + 1
        });
      }
    }
    statusBarItems.push({
      text: displayLanguage,
      command: $Jrb,
      tooltip: localize(8108, null),
      alignment: 2,
      priority: -Number.MAX_SAFE_INTEGER
    });
    return {
      items: statusBarItems
    };
  }
};
CellStatusBarLanguagePickerProvider = __decorate([
  __param(0, $mrb),
  __param(1, $1E)
], CellStatusBarLanguagePickerProvider);
var CellStatusBarLanguageDetectionProvider = class CellStatusBarLanguageDetectionProvider2 {
  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.viewType = "*";
    this.a = new $Ec();
  }
  async provideCellStatusBarItems(uri, index, token) {
    const doc = this.b.getNotebookTextModel(uri);
    const cell = doc?.cells[index];
    if (!cell) {
      return;
    }
    const enablementConfig = this.e.getValue("workbench.editor.languageDetectionHints");
    const enabled = typeof enablementConfig === "object" && enablementConfig?.notebookEditors;
    if (!enabled) {
      return;
    }
    const cellUri = cell.uri;
    const contentVersion = cell.textModel?.getVersionId();
    if (!contentVersion) {
      return;
    }
    const currentLanguageId = cell.cellKind === CellKind.Markup ? "markdown" : this.d.getLanguageIdByLanguageName(cell.language) || cell.language;
    if (!this.a.has(cellUri)) {
      this.a.set(cellUri, {
        cellLanguage: currentLanguageId,
        // force a re-compute upon a change in configured language
        updateTimestamp: 0,
        // facilitates a disposable-free debounce operation
        contentVersion: 1
        // dont run for the initial contents, only on update
      });
    }
    const cached = this.a.get(cellUri);
    if (cached.cellLanguage !== currentLanguageId || cached.updateTimestamp < Date.now() - 1e3 && cached.contentVersion !== contentVersion) {
      cached.updateTimestamp = Date.now();
      cached.cellLanguage = currentLanguageId;
      cached.contentVersion = contentVersion;
      const kernel = this.c.getSelectedOrSuggestedKernel(doc);
      if (kernel) {
        const supportedLangs = [...kernel.supportedLanguages, "markdown"];
        cached.guess = await this.f.detectLanguage(cell.uri, supportedLangs);
      }
    }
    const items = [];
    if (cached.guess && currentLanguageId !== cached.guess) {
      const detectedName = this.d.getLanguageName(cached.guess) || cached.guess;
      let tooltip = localize(8109, null, detectedName);
      const keybinding = this.g.lookupKeybinding($Irb);
      const label3 = keybinding?.getLabel();
      if (label3) {
        tooltip += ` (${label3})`;
      }
      items.push({
        text: "$(lightbulb-autofix)",
        command: $Irb,
        tooltip,
        alignment: 2,
        priority: -Number.MAX_SAFE_INTEGER + 1
      });
    }
    return { items };
  }
};
CellStatusBarLanguageDetectionProvider = __decorate([
  __param(0, $mrb),
  __param(1, $CL),
  __param(2, $1E),
  __param(3, $kl),
  __param(4, $tG),
  __param(5, $Ty)
], CellStatusBarLanguageDetectionProvider);
var BuiltinCellStatusBarProviders = class BuiltinCellStatusBarProviders2 extends $3c {
  constructor(instantiationService, notebookCellStatusBarService) {
    super();
    const builtinProviders = [
      CellStatusBarLanguagePickerProvider,
      CellStatusBarLanguageDetectionProvider
    ];
    builtinProviders.forEach((p) => {
      this.B(notebookCellStatusBarService.registerCellStatusBarItemProvider(instantiationService.createInstance(p)));
    });
  }
};
BuiltinCellStatusBarProviders = __decorate([
  __param(0, $Pk),
  __param(1, $DSb)
], BuiltinCellStatusBarProviders);
$Wn.as(Extensions2.Workbench).registerWorkbenchContribution(
  BuiltinCellStatusBarProviders,
  3
  /* LifecyclePhase.Restored */
);

// out-build/vs/workbench/contrib/notebook/browser/contrib/cellStatusBar/notebookVisibleCellObserver.js
var $A3b = class extends $3c {
  get visibleCells() {
    return this.c;
  }
  constructor(f) {
    super();
    this.f = f;
    this.a = this.B(new $ze());
    this.onDidChangeVisibleCells = this.a.event;
    this.b = this.B(new $2c());
    this.c = [];
    this.B(this.f.onDidChangeVisibleRanges(this.j, this));
    this.B(this.f.onDidChangeModel(this.g, this));
    this.j();
  }
  g() {
    this.b.clear();
    if (this.f.hasModel()) {
      this.b.add(this.f.onDidChangeViewCells(() => this.h()));
    }
    this.h();
  }
  h() {
    this.a.fire({ added: [], removed: Array.from(this.c) });
    this.c = [];
    this.j();
  }
  j() {
    if (!this.f.hasModel()) {
      return;
    }
    const newVisibleCells = $GL(this.f.visibleRanges).map((index) => this.f.cellAt(index)).filter($Hg);
    const newVisibleHandles = new Set(newVisibleCells.map((cell) => cell.handle));
    const oldVisibleHandles = new Set(this.c.map((cell) => cell.handle));
    const diff3 = $b(oldVisibleHandles, newVisibleHandles);
    const added = diff3.added.map((handle2) => this.f.getCellByHandle(handle2)).filter($Hg);
    const removed = diff3.removed.map((handle2) => this.f.getCellByHandle(handle2)).filter($Hg);
    this.c = newVisibleCells;
    this.a.fire({
      added,
      removed
    });
  }
};

// out-build/vs/workbench/contrib/notebook/browser/contrib/cellStatusBar/contributedStatusBarItemController.js
var $B3b = class $B3b2 extends $3c {
  static {
    this.id = "workbench.notebook.statusBar.contributed";
  }
  constructor(c, f) {
    super();
    this.c = c;
    this.f = f;
    this.a = /* @__PURE__ */ new Map();
    this.b = this.B(new $A3b(this.c));
    this.B(this.b.onDidChangeVisibleCells(this.h, this));
    this.g();
    this.B(this.f.onDidChangeProviders(this.g, this));
    this.B(this.f.onDidChangeItems(this.g, this));
  }
  g() {
    const newCells = this.b.visibleCells.filter((cell) => !this.a.has(cell.handle));
    const visibleCellHandles = new Set(this.b.visibleCells.map((item) => item.handle));
    const currentCellHandles = Array.from(this.a.keys());
    const removedCells = currentCellHandles.filter((handle2) => !visibleCellHandles.has(handle2));
    const itemsToUpdate = currentCellHandles.filter((handle2) => visibleCellHandles.has(handle2));
    this.h({ added: newCells, removed: removedCells.map((handle2) => ({ handle: handle2 })) });
    itemsToUpdate.forEach((handle2) => this.a.get(handle2)?.update());
  }
  h(e) {
    const vm = this.c.getViewModel();
    if (!vm) {
      return;
    }
    for (const newCell of e.added) {
      const helper = new CellStatusBarHelper(vm, newCell, this.f);
      this.a.set(newCell.handle, helper);
    }
    for (const oldCell of e.removed) {
      this.a.get(oldCell.handle)?.dispose();
      this.a.delete(oldCell.handle);
    }
  }
  dispose() {
    super.dispose();
    this.a.forEach((cell) => cell.dispose());
    this.a.clear();
  }
};
$B3b = __decorate([
  __param(1, $DSb)
], $B3b);
var CellStatusBarHelper = class extends $3c {
  constructor(h3, j, m) {
    super();
    this.h = h3;
    this.j = j;
    this.m = m;
    this.a = [];
    this.b = [];
    this.f = false;
    this.g = this.B(new $Ph());
    this.B($1c(() => this.c?.dispose(true)));
    this.n();
    this.B(this.j.model.onDidChangeContent(() => this.n()));
    this.B(this.j.model.onDidChangeLanguage(() => this.n()));
    this.B(this.j.model.onDidChangeMetadata(() => this.n()));
    this.B(this.j.model.onDidChangeInternalMetadata(() => this.n()));
    this.B(this.j.model.onDidChangeOutputs(() => this.n()));
  }
  update() {
    this.n();
  }
  n() {
    setTimeout(() => {
      if (!this.f) {
        this.g.queue(() => this.r());
      }
    }, 0);
  }
  async r() {
    const cellIndex = this.h.getCellIndex(this.j);
    const docUri = this.h.notebookDocument.uri;
    const viewType = this.h.notebookDocument.viewType;
    this.c?.dispose(true);
    const tokenSource = this.c = new $ad();
    const itemLists = await this.m.getStatusBarItemsForCell(docUri, cellIndex, viewType, tokenSource.token);
    if (tokenSource.token.isCancellationRequested) {
      itemLists.forEach((itemList) => itemList.dispose && itemList.dispose());
      return;
    }
    const items = itemLists.map((itemList) => itemList.items).flat();
    const newIds = this.h.deltaCellStatusBarItems(this.a, [{ handle: this.j.handle, items }]);
    this.b.forEach((itemList) => itemList.dispose && itemList.dispose());
    this.b = itemLists;
    this.a = newIds;
  }
  dispose() {
    super.dispose();
    this.f = true;
    this.c?.dispose(true);
    this.h.deltaCellStatusBarItems(this.a, [{ handle: this.j.handle, items: [] }]);
    this.b.forEach((itemList) => itemList.dispose && itemList.dispose());
  }
};
$iGb($B3b.id, $B3b);

// out-build/vs/workbench/contrib/notebook/browser/contrib/cellStatusBar/executionStatusBarItemController.js
var ExecutionStateCellStatusBarItem_1;
var TimerCellStatusBarItem_1;
function $C3b(duration, showMilliseconds = true) {
  if (showMilliseconds && duration < 1e3) {
    return `${duration}ms`;
  }
  const minutes = Math.floor(duration / 1e3 / 60);
  const seconds = Math.floor(duration / 1e3) % 60;
  const tenths = Math.floor(duration % 1e3 / 100);
  if (minutes > 0) {
    return `${minutes}m ${seconds}.${tenths}s`;
  } else {
    return `${seconds}.${tenths}s`;
  }
}
var $D3b = class extends $3c {
  constructor(c, f) {
    super();
    this.c = c;
    this.f = f;
    this.a = /* @__PURE__ */ new Map();
    this.b = this.B(new $A3b(this.c));
    this.B(this.b.onDidChangeVisibleCells(this.h, this));
    this.g();
  }
  g() {
    this.a.forEach($Xc);
    this.a.clear();
    this.h({ added: this.b.visibleCells, removed: [] });
  }
  h(e) {
    const vm = this.c.getViewModel();
    if (!vm) {
      return;
    }
    for (const oldCell of e.removed) {
      this.a.get(oldCell.handle)?.dispose();
      this.a.delete(oldCell.handle);
    }
    for (const newCell of e.added) {
      this.a.set(newCell.handle, this.f(vm, newCell));
    }
  }
  dispose() {
    super.dispose();
    this.a.forEach($Xc);
    this.a.clear();
  }
};
var $E3b = class $E3b2 extends $3c {
  static {
    this.id = "workbench.notebook.statusBar.execState";
  }
  constructor(notebookEditor, instantiationService) {
    super();
    this.B(new $D3b(notebookEditor, (vm, cell) => instantiationService.createInstance(ExecutionStateCellStatusBarItem, vm, cell)));
  }
};
$E3b = __decorate([
  __param(1, $Pk)
], $E3b);
$iGb($E3b.id, $E3b);
var ExecutionStateCellStatusBarItem = class ExecutionStateCellStatusBarItem2 extends $3c {
  static {
    ExecutionStateCellStatusBarItem_1 = this;
  }
  static {
    this.a = 500;
  }
  constructor(g, h3, j) {
    super();
    this.g = g;
    this.h = h3;
    this.j = j;
    this.b = [];
    this.f = this.B(new $4c());
    this.m();
    this.B(this.j.onDidChangeExecution((e) => {
      if (e.type === NotebookExecutionType.cell && e.affectsCell(this.h.uri)) {
        this.m();
      }
    }));
    this.B(this.h.model.onDidChangeInternalMetadata(() => this.m()));
  }
  async m() {
    const items = this.n();
    if (Array.isArray(items)) {
      this.b = this.g.deltaCellStatusBarItems(this.b, [{ handle: this.h.handle, items }]);
    }
  }
  /**
   *	Returns undefined if there should be no change, and an empty array if all items should be removed.
   */
  n() {
    const runState = this.j.getCellExecution(this.h.uri);
    if (runState?.state === NotebookCellExecutionState.Executing && typeof this.c !== "number") {
      this.c = Date.now();
    } else if (runState?.state !== NotebookCellExecutionState.Executing && typeof this.c === "number") {
      const timeUntilMin = ExecutionStateCellStatusBarItem_1.a - (Date.now() - this.c);
      if (timeUntilMin > 0) {
        if (!this.f.value) {
          this.f.value = $Xh(() => {
            this.c = void 0;
            this.f.clear();
            this.m();
          }, timeUntilMin);
        }
        return void 0;
      } else {
        this.c = void 0;
      }
    }
    const items = this.r(runState, this.h.internalMetadata);
    return items;
  }
  r(runState, internalMetadata) {
    const state = runState?.state;
    const { lastRunSuccess } = internalMetadata;
    if (!state && lastRunSuccess) {
      return [{
        text: `$(${$OKb.id})`,
        color: $hs($dMb),
        tooltip: localize(8100, null),
        alignment: 1,
        priority: Number.MAX_SAFE_INTEGER
      }];
    } else if (!state && lastRunSuccess === false) {
      return [{
        text: `$(${$PKb.id})`,
        color: $hs($fMb),
        tooltip: localize(8101, null),
        alignment: 1,
        priority: Number.MAX_SAFE_INTEGER
      }];
    } else if (state === NotebookCellExecutionState.Pending || state === NotebookCellExecutionState.Unconfirmed) {
      return [{
        text: `$(${$QKb.id})`,
        tooltip: localize(8102, null),
        alignment: 1,
        priority: Number.MAX_SAFE_INTEGER
      }];
    } else if (state === NotebookCellExecutionState.Executing) {
      const icon2 = runState?.didPause ? $RKb : ThemeIcon.modify($RKb, "spin");
      return [{
        text: `$(${icon2.id})`,
        tooltip: localize(8103, null),
        alignment: 1,
        priority: Number.MAX_SAFE_INTEGER
      }];
    }
    return [];
  }
  dispose() {
    super.dispose();
    this.g.deltaCellStatusBarItems(this.b, [{ handle: this.h.handle, items: [] }]);
  }
};
ExecutionStateCellStatusBarItem = ExecutionStateCellStatusBarItem_1 = __decorate([
  __param(2, $wL)
], ExecutionStateCellStatusBarItem);
var $F3b = class $F3b2 extends $3c {
  static {
    this.id = "workbench.notebook.statusBar.execTimer";
  }
  constructor(notebookEditor, instantiationService) {
    super();
    this.B(new $D3b(notebookEditor, (vm, cell) => instantiationService.createInstance(TimerCellStatusBarItem, vm, cell)));
  }
};
$F3b = __decorate([
  __param(1, $Pk)
], $F3b);
$iGb($F3b.id, $F3b);
var UPDATE_TIMER_GRACE_PERIOD = 200;
var TimerCellStatusBarItem = class TimerCellStatusBarItem2 extends $3c {
  static {
    TimerCellStatusBarItem_1 = this;
  }
  static {
    this.a = 100;
  }
  constructor(h3, j, m, n, r2) {
    super();
    this.h = h3;
    this.j = j;
    this.m = m;
    this.n = n;
    this.r = r2;
    this.b = [];
    this.g = this.r.getValue($rM.cellExecutionTimeVerbosity) === "verbose";
    this.c = this.B(new $8h(() => this.s(), TimerCellStatusBarItem_1.a));
    this.s();
    this.B(this.j.model.onDidChangeInternalMetadata(() => this.s()));
    this.B(this.r.onDidChangeConfiguration((e) => {
      if (e.affectsConfiguration($rM.cellExecutionTimeVerbosity)) {
        this.g = this.r.getValue($rM.cellExecutionTimeVerbosity) === "verbose";
        this.s();
      }
    }));
  }
  async s() {
    let timerItem;
    const runState = this.m.getCellExecution(this.j.uri);
    const state = runState?.state;
    const startTime = this.j.internalMetadata.runStartTime;
    const adjustment = this.j.internalMetadata.runStartTimeAdjustment ?? 0;
    const endTime = this.j.internalMetadata.runEndTime;
    if (runState?.didPause) {
      timerItem = void 0;
    } else if (state === NotebookCellExecutionState.Executing) {
      if (typeof startTime === "number") {
        timerItem = this.t(startTime, Date.now(), adjustment);
        this.c.schedule();
      }
    } else if (!state) {
      if (typeof startTime === "number" && typeof endTime === "number") {
        const timerDuration = Date.now() - startTime + adjustment;
        const executionDuration = endTime - startTime;
        const renderDuration = this.j.internalMetadata.renderDuration ?? {};
        timerItem = this.t(startTime, endTime, void 0, {
          timerDuration,
          executionDuration,
          renderDuration
        });
      }
    }
    const items = timerItem ? [timerItem] : [];
    if (!items.length && !!runState) {
      if (!this.f) {
        this.f = $Xh(() => {
          this.f = void 0;
          this.b = this.h.deltaCellStatusBarItems(this.b, [{ handle: this.j.handle, items }]);
        }, UPDATE_TIMER_GRACE_PERIOD);
      }
    } else {
      this.f?.dispose();
      this.f = void 0;
      this.b = this.h.deltaCellStatusBarItems(this.b, [{ handle: this.j.handle, items }]);
    }
  }
  t(startTime, endTime, adjustment = 0, runtimeInformation) {
    const duration = endTime - startTime + adjustment;
    let tooltip;
    const lastExecution = new Date(endTime).toLocaleTimeString($z);
    if (runtimeInformation) {
      const { renderDuration, executionDuration, timerDuration } = runtimeInformation;
      let renderTimes = "";
      for (const key2 in renderDuration) {
        const rendererInfo = this.n.getRendererInfo(key2);
        const args2 = encodeURIComponent(JSON.stringify({
          extensionId: rendererInfo?.extensionId.value ?? "",
          issueBody: `Auto-generated text from notebook cell performance. The duration for the renderer, ${rendererInfo?.displayName ?? key2}, is slower than expected.
Execution Time: ${$C3b(executionDuration)}
Renderer Duration: ${$C3b(renderDuration[key2])}
`
        }));
        renderTimes += `- [${rendererInfo?.displayName ?? key2}](command:workbench.action.openIssueReporter?${args2}) ${$C3b(renderDuration[key2])}
`;
      }
      renderTimes += `
*${localize(8104, null)}*
`;
      tooltip = {
        value: localize(8105, null, lastExecution, $C3b(executionDuration), $C3b(timerDuration - executionDuration), renderTimes),
        isTrusted: true
      };
    }
    const executionText = this.g ? localize(8106, null, lastExecution, $C3b(duration, false)) : $C3b(duration, false);
    return {
      text: executionText,
      alignment: 1,
      priority: Number.MAX_SAFE_INTEGER - 5,
      tooltip
    };
  }
  dispose() {
    super.dispose();
    this.f?.dispose();
    this.h.deltaCellStatusBarItems(this.b, [{ handle: this.j.handle, items: [] }]);
  }
};
TimerCellStatusBarItem = TimerCellStatusBarItem_1 = __decorate([
  __param(2, $wL),
  __param(3, $mrb),
  __param(4, $kl)
], TimerCellStatusBarItem);

// out-build/vs/workbench/contrib/notebook/browser/contrib/editorStatusBar/editorStatusBar.js
var ImplictKernelSelector = class ImplictKernelSelector2 {
  constructor(notebook, suggested, notebookKernelService, languageFeaturesService, logService) {
    const disposables = new $2c();
    this.dispose = disposables.dispose.bind(disposables);
    const selectKernel = () => {
      disposables.clear();
      notebookKernelService.selectKernelForNotebook(suggested, notebook);
    };
    disposables.add(notebook.onDidChangeContent((e) => {
      for (const event of e.rawEvents) {
        switch (event.kind) {
          case NotebookCellsChangeType.ChangeCellContent:
          case NotebookCellsChangeType.ModelChange:
          case NotebookCellsChangeType.Move:
          case NotebookCellsChangeType.ChangeCellLanguage:
            logService.trace("IMPLICIT kernel selection because of change event", event.kind);
            selectKernel();
            break;
        }
      }
    }));
    disposables.add(languageFeaturesService.hoverProvider.register({ scheme: Schemas.vscodeNotebookCell, pattern: notebook.uri.path }, {
      provideHover() {
        logService.trace("IMPLICIT kernel selection because of hover");
        selectKernel();
        return void 0;
      }
    }));
  }
};
ImplictKernelSelector = __decorate([
  __param(2, $CL),
  __param(3, $mP),
  __param(4, $wn)
], ImplictKernelSelector);
var KernelStatus = class KernelStatus2 extends $3c {
  constructor(c, f, g, h3) {
    super();
    this.c = c;
    this.f = f;
    this.g = g;
    this.h = h3;
    this.a = this.B(new $2c());
    this.b = this.B(new $2c());
    this.B(this.c.onDidActiveEditorChange(() => this.j()));
    this.j();
  }
  j() {
    this.a.clear();
    const activeEditor = $Qrb(this.c.activeEditorPane);
    if (!activeEditor) {
      this.b.clear();
      return;
    }
    const updateStatus = () => {
      if (activeEditor.notebookOptions.getDisplayOptions().globalToolbar) {
        this.b.clear();
        return;
      }
      const notebook = activeEditor.textModel;
      if (notebook) {
        this.m(notebook);
      } else {
        this.b.clear();
      }
    };
    this.a.add(this.g.onDidAddKernel(updateStatus));
    this.a.add(this.g.onDidChangeSelectedNotebooks(updateStatus));
    this.a.add(this.g.onDidChangeNotebookAffinity(updateStatus));
    this.a.add(activeEditor.onDidChangeModel(updateStatus));
    this.a.add(activeEditor.notebookOptions.onDidChangeOptions(updateStatus));
    updateStatus();
  }
  m(notebook) {
    this.b.clear();
    const { selected, suggestions, all } = this.g.getMatchingKernel(notebook);
    const suggested = (suggestions.length === 1 ? suggestions[0] : void 0) ?? all.length === 1 ? all[0] : void 0;
    let isSuggested = false;
    if (all.length === 0) {
      return;
    } else if (selected || suggested) {
      let kernel = selected;
      if (!kernel) {
        kernel = suggested;
        isSuggested = true;
        this.b.add(this.h.createInstance(ImplictKernelSelector, notebook, kernel));
      }
      const tooltip = kernel.description ?? kernel.detail ?? kernel.label;
      this.b.add(this.f.addEntry({
        name: localize(8117, null),
        text: `$(notebook-kernel-select) ${kernel.label}`,
        ariaLabel: kernel.label,
        tooltip: isSuggested ? localize(8118, null, tooltip) : tooltip,
        command: $wIb
      }, $wIb, 1, 10));
      this.b.add(kernel.onDidChange(() => this.m(notebook)));
    } else {
      this.b.add(this.f.addEntry({
        name: localize(8119, null),
        text: localize(8120, null),
        ariaLabel: localize(8121, null),
        command: $wIb,
        kind: "prominent"
      }, $wIb, 1, 10));
    }
  }
};
KernelStatus = __decorate([
  __param(0, $mJ),
  __param(1, $$qb),
  __param(2, $CL),
  __param(3, $Pk)
], KernelStatus);
var ActiveCellStatus = class ActiveCellStatus2 extends $3c {
  constructor(c, f) {
    super();
    this.c = c;
    this.f = f;
    this.a = this.B(new $2c());
    this.b = this.B(new $4c());
    this.B(this.c.onDidActiveEditorChange(() => this.g()));
    this.g();
  }
  g() {
    this.a.clear();
    const activeEditor = $Qrb(this.c.activeEditorPane);
    if (activeEditor) {
      this.a.add(activeEditor.onDidChangeSelection(() => this.h(activeEditor)));
      this.a.add(activeEditor.onDidChangeActiveCell(() => this.h(activeEditor)));
      this.h(activeEditor);
    } else {
      this.b.clear();
    }
  }
  h(editor) {
    if (!editor.hasModel()) {
      this.b.clear();
      return;
    }
    const newText = this.j(editor);
    if (!newText) {
      this.b.clear();
      return;
    }
    const entry = {
      name: localize(8122, null),
      text: newText,
      ariaLabel: newText,
      command: $z3b
    };
    if (!this.b.value) {
      this.b.value = this.f.addEntry(entry, "notebook.activeCellStatus", 1, 100);
    } else {
      this.b.value.update(entry);
    }
  }
  j(editor) {
    if (!editor.hasModel()) {
      return void 0;
    }
    const activeCell = editor.getActiveCell();
    if (!activeCell) {
      return void 0;
    }
    const idxFocused = editor.getCellIndex(activeCell) + 1;
    const numSelected = editor.getSelections().reduce((prev, range) => prev + (range.end - range.start), 0);
    const totalCells = editor.getLength();
    return numSelected > 1 ? localize(8123, null, idxFocused, numSelected) : localize(8124, null, idxFocused, totalCells);
  }
};
ActiveCellStatus = __decorate([
  __param(0, $mJ),
  __param(1, $$qb)
], ActiveCellStatus);
var NotebookIndentationStatus = class NotebookIndentationStatus2 extends $3c {
  static {
    this.ID = "selectNotebookIndentation";
  }
  constructor(c, f, g) {
    super();
    this.c = c;
    this.f = f;
    this.g = g;
    this.a = this.B(new $2c());
    this.b = this.B(new $4c());
    this.B(this.c.onDidActiveEditorChange(() => this.h()));
    this.B(this.g.onDidChangeConfiguration((e) => {
      if (e.affectsConfiguration("editor") || e.affectsConfiguration("notebook")) {
        this.h();
      }
    }));
    this.h();
  }
  h() {
    this.a.clear();
    const activeEditor = $Qrb(this.c.activeEditorPane);
    if (activeEditor) {
      this.j(activeEditor);
      this.a.add(activeEditor.onDidChangeSelection(() => {
        this.b.clear();
        this.j(activeEditor);
      }));
    } else {
      this.b.clear();
    }
  }
  j(editor) {
    if (!editor.hasModel()) {
      this.b.clear();
      return;
    }
    const cellOptions = editor.getActiveCell()?.textModel?.getOptions();
    if (!cellOptions) {
      this.b.clear();
      return;
    }
    const cellEditorOverridesRaw = editor.notebookOptions.getDisplayOptions().editorOptionsCustomizations;
    const indentSize = cellEditorOverridesRaw?.["editor.indentSize"] ?? cellOptions?.indentSize;
    const insertSpaces = cellEditorOverridesRaw?.["editor.insertSpaces"] ?? cellOptions?.insertSpaces;
    const tabSize = cellEditorOverridesRaw?.["editor.tabSize"] ?? cellOptions?.tabSize;
    const width2 = typeof indentSize === "number" ? indentSize : tabSize;
    const message = insertSpaces ? `Spaces: ${width2}` : `Tab Size: ${width2}`;
    const newText = message;
    if (!newText) {
      this.b.clear();
      return;
    }
    const entry = {
      name: localize(8125, null),
      text: newText,
      ariaLabel: newText,
      tooltip: localize(8126, null),
      command: $R2b
    };
    if (!this.b.value) {
      this.b.value = this.f.addEntry(entry, "notebook.status.indentation", 1, 100.4);
    } else {
      this.b.value.update(entry);
    }
  }
};
NotebookIndentationStatus = __decorate([
  __param(0, $mJ),
  __param(1, $$qb),
  __param(2, $kl)
], NotebookIndentationStatus);
var NotebookEditorStatusContribution = class NotebookEditorStatusContribution2 extends $3c {
  static {
    this.ID = "notebook.contrib.editorStatus";
  }
  constructor(a) {
    super();
    this.a = a;
    for (const part of a.parts) {
      this.b(part);
    }
    this.B(a.onDidCreateAuxiliaryEditorPart((part) => this.b(part)));
  }
  b(part) {
    const disposables = new $2c();
    Event2.once(part.onWillDispose)(() => disposables.dispose());
    const scopedInstantiationService = this.a.getScopedInstantiationService(part);
    disposables.add(scopedInstantiationService.createInstance(KernelStatus));
    disposables.add(scopedInstantiationService.createInstance(ActiveCellStatus));
    disposables.add(scopedInstantiationService.createInstance(NotebookIndentationStatus));
  }
};
NotebookEditorStatusContribution = __decorate([
  __param(0, $iJ)
], NotebookEditorStatusContribution);
$PL(
  NotebookEditorStatusContribution.ID,
  NotebookEditorStatusContribution,
  3
  /* WorkbenchPhase.AfterRestored */
);

// out-build/vs/workbench/contrib/notebook/browser/contrib/undoRedo/notebookUndoRedo.js
var NotebookUndoRedoContribution = class NotebookUndoRedoContribution2 extends $3c {
  static {
    this.ID = "workbench.contrib.notebookUndoRedo";
  }
  constructor(a) {
    super();
    this.a = a;
    const PRIORITY3 = 105;
    this.B($05.addImplementation(PRIORITY3, "notebook-undo-redo", () => {
      const editor = $Qrb(this.a.activeEditorPane);
      const viewModel = editor?.getViewModel();
      if (editor && editor.hasModel() && viewModel) {
        return viewModel.undo().then((cellResources) => {
          if (cellResources?.length) {
            for (let i2 = 0; i2 < editor.getLength(); i2++) {
              const cell = editor.cellAt(i2);
              if (cell.cellKind === CellKind.Markup && cellResources.find((resource) => resource.fragment === cell.model.uri.fragment)) {
                cell.updateEditState(CellEditState.Editing, "undo");
              }
            }
            editor?.setOptions({ cellOptions: { resource: cellResources[0] }, preserveFocus: true });
          }
        });
      }
      return false;
    }));
    this.B($$5.addImplementation(PRIORITY3, "notebook-undo-redo", () => {
      const editor = $Qrb(this.a.activeEditorPane);
      const viewModel = editor?.getViewModel();
      if (editor && editor.hasModel() && viewModel) {
        return viewModel.redo().then((cellResources) => {
          if (cellResources?.length) {
            for (let i2 = 0; i2 < editor.getLength(); i2++) {
              const cell = editor.cellAt(i2);
              if (cell.cellKind === CellKind.Markup && cellResources.find((resource) => resource.fragment === cell.model.uri.fragment)) {
                cell.updateEditState(CellEditState.Editing, "redo");
              }
            }
            editor?.setOptions({ cellOptions: { resource: cellResources[0] }, preserveFocus: true });
          }
        });
      }
      return false;
    }));
  }
};
NotebookUndoRedoContribution = __decorate([
  __param(0, $mJ)
], NotebookUndoRedoContribution);
$PL(
  NotebookUndoRedoContribution.ID,
  NotebookUndoRedoContribution,
  2
  /* WorkbenchPhase.BlockRestore */
);

// out-build/vs/workbench/contrib/notebook/browser/contrib/cellCommands/cellCommands.js
var MOVE_CELL_UP_COMMAND_ID = "notebook.cell.moveUp";
var MOVE_CELL_DOWN_COMMAND_ID = "notebook.cell.moveDown";
var COPY_CELL_UP_COMMAND_ID = "notebook.cell.copyUp";
var COPY_CELL_DOWN_COMMAND_ID = "notebook.cell.copyDown";
$hJ(class extends $HIb {
  constructor() {
    super({
      id: MOVE_CELL_UP_COMMAND_ID,
      title: localize2(8075, "Move Cell Up"),
      icon: $KKb,
      keybinding: {
        primary: 512 | 16,
        when: $7m.and($WAb, $Ceb.toNegated()),
        weight: 200
        /* KeybindingWeight.WorkbenchContrib */
      },
      menu: {
        id: $bJ.NotebookCellTitle,
        when: $7m.equals("config.notebook.dragAndDropEnabled", false),
        group: "3_edit",
        order: 14
      }
    });
  }
  async runWithContext(accessor, context) {
    return $4Ib(context, "up");
  }
});
$hJ(class extends $HIb {
  constructor() {
    super({
      id: MOVE_CELL_DOWN_COMMAND_ID,
      title: localize2(8076, "Move Cell Down"),
      icon: $LKb,
      keybinding: {
        primary: 512 | 18,
        when: $7m.and($WAb, $Ceb.toNegated()),
        weight: 200
        /* KeybindingWeight.WorkbenchContrib */
      },
      menu: {
        id: $bJ.NotebookCellTitle,
        when: $7m.equals("config.notebook.dragAndDropEnabled", false),
        group: "3_edit",
        order: 14
      }
    });
  }
  async runWithContext(accessor, context) {
    return $4Ib(context, "down");
  }
});
$hJ(class extends $HIb {
  constructor() {
    super({
      id: COPY_CELL_UP_COMMAND_ID,
      title: localize2(8077, "Copy Cell Up"),
      keybinding: {
        primary: 512 | 1024 | 16,
        when: $7m.and($WAb, $Ceb.toNegated()),
        weight: 200
        /* KeybindingWeight.WorkbenchContrib */
      }
    });
  }
  async runWithContext(accessor, context) {
    return $5Ib(context, "up");
  }
});
$hJ(class extends $HIb {
  constructor() {
    super({
      id: COPY_CELL_DOWN_COMMAND_ID,
      title: localize2(8078, "Copy Cell Down"),
      keybinding: {
        primary: 512 | 1024 | 18,
        when: $7m.and($WAb, $Ceb.toNegated()),
        weight: 200
        /* KeybindingWeight.WorkbenchContrib */
      },
      menu: {
        id: $bJ.NotebookCellTitle,
        when: $7m.and($WAb, $1Ab, $$Ab),
        group: "3_edit",
        order: 13
      }
    });
  }
  async runWithContext(accessor, context) {
    return $5Ib(context, "down");
  }
});
var SPLIT_CELL_COMMAND_ID = "notebook.cell.split";
var JOIN_SELECTED_CELLS_COMMAND_ID = "notebook.cell.joinSelected";
var JOIN_CELL_ABOVE_COMMAND_ID = "notebook.cell.joinAbove";
var JOIN_CELL_BELOW_COMMAND_ID = "notebook.cell.joinBelow";
$hJ(class extends $HIb {
  constructor() {
    super({
      id: SPLIT_CELL_COMMAND_ID,
      title: localize2(8079, "Split Cell"),
      menu: {
        id: $bJ.NotebookCellTitle,
        when: $7m.and($1Ab, $$Ab, $iBb.toNegated()),
        order: 5,
        group: $yIb
      },
      icon: $NKb,
      keybinding: {
        when: $7m.and($WAb, $1Ab, $$Ab, EditorContextKeys.editorTextFocus),
        primary: $$e(
          2048 | 41,
          2048 | 1024 | 93
          /* KeyCode.Backslash */
        ),
        weight: 200
        /* KeybindingWeight.WorkbenchContrib */
      }
    });
  }
  async runWithContext(accessor, context) {
    if (context.notebookEditor.isReadOnly) {
      return;
    }
    const bulkEditService = accessor.get($H_);
    const cell = context.cell;
    const index = context.notebookEditor.getCellIndex(cell);
    const splitPoints = cell.focusMode === CellFocusMode.Container ? [{ lineNumber: 1, column: 1 }] : cell.getSelectionsStartPosition();
    if (splitPoints && splitPoints.length > 0) {
      await cell.resolveTextModel();
      if (!cell.hasModel()) {
        return;
      }
      const newLinesContents = $9Ib(cell, splitPoints);
      if (newLinesContents) {
        const language = cell.language;
        const kind = cell.cellKind;
        const mime = cell.mime;
        const textModel = await cell.resolveTextModel();
        await bulkEditService.apply([
          new $J_(cell.uri, { range: textModel.getFullModelRange(), text: newLinesContents[0] }),
          new $Trb(context.notebookEditor.textModel.uri, {
            editType: 1,
            index: index + 1,
            count: 0,
            cells: newLinesContents.slice(1).map((line) => ({
              cellKind: kind,
              language,
              mime,
              source: line,
              outputs: [],
              metadata: {}
            }))
          })
        ], { quotableLabel: "Split Notebook Cell" });
      }
    }
  }
});
$hJ(class extends $HIb {
  constructor() {
    super({
      id: JOIN_CELL_ABOVE_COMMAND_ID,
      title: localize2(8080, "Join With Previous Cell"),
      keybinding: {
        when: $WAb,
        primary: 256 | 512 | 1024 | 40,
        weight: 200
        /* KeybindingWeight.WorkbenchContrib */
      },
      menu: {
        id: $bJ.NotebookCellTitle,
        when: $7m.and($WAb, $1Ab),
        group: "3_edit",
        order: 10
      }
    });
  }
  async runWithContext(accessor, context) {
    const bulkEditService = accessor.get($H_);
    return $8Ib(bulkEditService, context, "above");
  }
});
$hJ(class extends $HIb {
  constructor() {
    super({
      id: JOIN_CELL_BELOW_COMMAND_ID,
      title: localize2(8081, "Join With Next Cell"),
      keybinding: {
        when: $WAb,
        primary: 256 | 512 | 40,
        weight: 200
        /* KeybindingWeight.WorkbenchContrib */
      },
      menu: {
        id: $bJ.NotebookCellTitle,
        when: $7m.and($WAb, $1Ab),
        group: "3_edit",
        order: 11
      }
    });
  }
  async runWithContext(accessor, context) {
    const bulkEditService = accessor.get($H_);
    return $8Ib(bulkEditService, context, "below");
  }
});
$hJ(class extends $HIb {
  constructor() {
    super({
      id: JOIN_SELECTED_CELLS_COMMAND_ID,
      title: localize2(8082, "Join Selected Cells"),
      menu: {
        id: $bJ.NotebookCellTitle,
        when: $7m.and($WAb, $1Ab),
        group: "3_edit",
        order: 12
      }
    });
  }
  async runWithContext(accessor, context) {
    const bulkEditService = accessor.get($H_);
    const notificationService = accessor.get($PJ);
    return $6Ib(bulkEditService, notificationService, context);
  }
});
var CHANGE_CELL_TO_CODE_COMMAND_ID = "notebook.cell.changeToCode";
var CHANGE_CELL_TO_MARKDOWN_COMMAND_ID = "notebook.cell.changeToMarkdown";
$hJ(class ChangeCellToCodeAction extends $GIb {
  constructor() {
    super({
      id: CHANGE_CELL_TO_CODE_COMMAND_ID,
      title: localize2(8083, "Change Cell to Code"),
      keybinding: {
        when: $7m.and($WAb, $7m.not($Beb), $YAb.toNegated()),
        primary: 55,
        weight: 200
        /* KeybindingWeight.WorkbenchContrib */
      },
      precondition: $7m.and($SAb, $0Ab.isEqualTo("markup")),
      menu: {
        id: $bJ.NotebookCellTitle,
        when: $7m.and($WAb, $1Ab, $$Ab, $0Ab.isEqualTo("markup")),
        group: "3_edit"
      }
    });
  }
  async runWithContext(accessor, context) {
    await $2Ib(CellKind.Code, context);
  }
});
$hJ(class ChangeCellToMarkdownAction extends $GIb {
  constructor() {
    super({
      id: CHANGE_CELL_TO_MARKDOWN_COMMAND_ID,
      title: localize2(8084, "Change Cell to Markdown"),
      keybinding: {
        when: $7m.and($WAb, $7m.not($Beb), $YAb.toNegated()),
        primary: 43,
        weight: 200
        /* KeybindingWeight.WorkbenchContrib */
      },
      precondition: $7m.and($SAb, $0Ab.isEqualTo("code")),
      menu: {
        id: $bJ.NotebookCellTitle,
        when: $7m.and($WAb, $1Ab, $$Ab, $0Ab.isEqualTo("code")),
        group: "3_edit"
      }
    });
  }
  async runWithContext(accessor, context) {
    await $2Ib(CellKind.Markup, context, "markdown", $YC.markdown);
  }
});
var COLLAPSE_CELL_INPUT_COMMAND_ID = "notebook.cell.collapseCellInput";
var COLLAPSE_CELL_OUTPUT_COMMAND_ID = "notebook.cell.collapseCellOutput";
var COLLAPSE_ALL_CELL_INPUTS_COMMAND_ID = "notebook.cell.collapseAllCellInputs";
var EXPAND_ALL_CELL_INPUTS_COMMAND_ID = "notebook.cell.expandAllCellInputs";
var COLLAPSE_ALL_CELL_OUTPUTS_COMMAND_ID = "notebook.cell.collapseAllCellOutputs";
var EXPAND_ALL_CELL_OUTPUTS_COMMAND_ID = "notebook.cell.expandAllCellOutputs";
var TOGGLE_CELL_OUTPUTS_COMMAND_ID = "notebook.cell.toggleOutputs";
var TOGGLE_CELL_OUTPUT_SCROLLING = "notebook.cell.toggleOutputScrolling";
$hJ(class CollapseCellInputAction extends $GIb {
  constructor() {
    super({
      id: COLLAPSE_CELL_INPUT_COMMAND_ID,
      title: localize2(8085, "Collapse Cell Input"),
      keybinding: {
        when: $7m.and($XAb, $iBb.toNegated(), $Ceb.toNegated()),
        primary: $$e(
          2048 | 41,
          2048 | 33
          /* KeyCode.KeyC */
        ),
        weight: 200
        /* KeybindingWeight.WorkbenchContrib */
      }
    });
  }
  parseArgs(accessor, ...args2) {
    return $KIb(accessor, ...args2);
  }
  async runWithContext(accessor, context) {
    if (context.ui) {
      context.cell.isInputCollapsed = true;
    } else {
      context.selectedCells.forEach((cell) => cell.isInputCollapsed = true);
    }
  }
});
$hJ(class ExpandCellInputAction extends $GIb {
  constructor() {
    super({
      id: $Grb,
      title: localize2(8086, "Expand Cell Input"),
      keybinding: {
        when: $7m.and($XAb, $iBb),
        primary: $$e(
          2048 | 41,
          2048 | 33
          /* KeyCode.KeyC */
        ),
        weight: 200
        /* KeybindingWeight.WorkbenchContrib */
      }
    });
  }
  parseArgs(accessor, ...args2) {
    return $KIb(accessor, ...args2);
  }
  async runWithContext(accessor, context) {
    if (context.ui) {
      context.cell.isInputCollapsed = false;
    } else {
      context.selectedCells.forEach((cell) => cell.isInputCollapsed = false);
    }
  }
});
$hJ(class CollapseCellOutputAction extends $GIb {
  constructor() {
    super({
      id: COLLAPSE_CELL_OUTPUT_COMMAND_ID,
      title: localize2(8087, "Collapse Cell Output"),
      keybinding: {
        when: $7m.and($XAb, $jBb.toNegated(), $Ceb.toNegated(), $fBb),
        primary: $$e(
          2048 | 41,
          50
          /* KeyCode.KeyT */
        ),
        weight: 200
        /* KeybindingWeight.WorkbenchContrib */
      }
    });
  }
  async runWithContext(accessor, context) {
    if (context.ui) {
      context.cell.isOutputCollapsed = true;
    } else {
      context.selectedCells.forEach((cell) => cell.isOutputCollapsed = true);
    }
  }
});
$hJ(class ExpandCellOuputAction extends $GIb {
  constructor() {
    super({
      id: $Lrb,
      title: localize2(8088, "Expand Cell Output"),
      keybinding: {
        when: $7m.and($XAb, $jBb),
        primary: $$e(
          2048 | 41,
          50
          /* KeyCode.KeyT */
        ),
        weight: 200
        /* KeybindingWeight.WorkbenchContrib */
      }
    });
  }
  async runWithContext(accessor, context) {
    if (context.ui) {
      context.cell.isOutputCollapsed = false;
    } else {
      context.selectedCells.forEach((cell) => cell.isOutputCollapsed = false);
    }
  }
});
$hJ(class extends $GIb {
  constructor() {
    super({
      id: TOGGLE_CELL_OUTPUTS_COMMAND_ID,
      precondition: $XAb,
      title: localize2(8089, "Toggle Outputs"),
      metadata: {
        description: localize(8074, null),
        args: $LIb
      }
    });
  }
  parseArgs(accessor, ...args2) {
    return $KIb(accessor, ...args2);
  }
  async runWithContext(accessor, context) {
    let cells = [];
    if (context.ui) {
      cells = [context.cell];
    } else if (context.selectedCells) {
      cells = context.selectedCells;
    }
    for (const cell of cells) {
      cell.isOutputCollapsed = !cell.isOutputCollapsed;
    }
  }
});
$hJ(class CollapseAllCellInputsAction extends $GIb {
  constructor() {
    super({
      id: COLLAPSE_ALL_CELL_INPUTS_COMMAND_ID,
      title: localize2(8090, "Collapse All Cell Inputs"),
      f1: true
    });
  }
  async runWithContext(accessor, context) {
    forEachCell(context.notebookEditor, (cell) => cell.isInputCollapsed = true);
  }
});
$hJ(class ExpandAllCellInputsAction extends $GIb {
  constructor() {
    super({
      id: EXPAND_ALL_CELL_INPUTS_COMMAND_ID,
      title: localize2(8091, "Expand All Cell Inputs"),
      f1: true
    });
  }
  async runWithContext(accessor, context) {
    forEachCell(context.notebookEditor, (cell) => cell.isInputCollapsed = false);
  }
});
$hJ(class CollapseAllCellOutputsAction extends $GIb {
  constructor() {
    super({
      id: COLLAPSE_ALL_CELL_OUTPUTS_COMMAND_ID,
      title: localize2(8092, "Collapse All Cell Outputs"),
      f1: true
    });
  }
  async runWithContext(accessor, context) {
    forEachCell(context.notebookEditor, (cell) => cell.isOutputCollapsed = true);
  }
});
$hJ(class ExpandAllCellOutputsAction extends $GIb {
  constructor() {
    super({
      id: EXPAND_ALL_CELL_OUTPUTS_COMMAND_ID,
      title: localize2(8093, "Expand All Cell Outputs"),
      f1: true
    });
  }
  async runWithContext(accessor, context) {
    forEachCell(context.notebookEditor, (cell) => cell.isOutputCollapsed = false);
  }
});
$hJ(class ToggleCellOutputScrolling extends $GIb {
  constructor() {
    super({
      id: TOGGLE_CELL_OUTPUT_SCROLLING,
      title: localize2(8094, "Toggle Scroll Cell Output"),
      keybinding: {
        when: $7m.and($XAb, $Ceb.toNegated(), $fBb),
        primary: $$e(
          2048 | 41,
          55
          /* KeyCode.KeyY */
        ),
        weight: 200
        /* KeybindingWeight.WorkbenchContrib */
      }
    });
  }
  a(viewModel, globalScrollSetting, collapsed2) {
    const cellMetadata = viewModel.model.metadata;
    if (cellMetadata) {
      const currentlyEnabled = cellMetadata["scrollable"] !== void 0 ? cellMetadata["scrollable"] : globalScrollSetting;
      const shouldEnableScrolling = collapsed2 || !currentlyEnabled;
      cellMetadata["scrollable"] = shouldEnableScrolling;
      viewModel.resetRenderer();
    }
  }
  async runWithContext(accessor, context) {
    const globalScrolling = accessor.get($kl).getValue($rM.outputScrolling);
    if (context.ui) {
      context.cell.outputsViewModels.forEach((viewModel) => {
        this.a(viewModel, globalScrolling, context.cell.isOutputCollapsed);
      });
      context.cell.isOutputCollapsed = false;
    } else {
      context.selectedCells.forEach((cell) => {
        cell.outputsViewModels.forEach((viewModel) => {
          this.a(viewModel, globalScrolling, cell.isOutputCollapsed);
        });
        cell.isOutputCollapsed = false;
      });
    }
  }
});
function forEachCell(editor, callback) {
  for (let i2 = 0; i2 < editor.getLength(); i2++) {
    const cell = editor.cellAt(i2);
    callback(cell, i2);
  }
}

// out-build/vs/workbench/contrib/notebook/browser/contrib/viewportWarmup/viewportWarmup.js
var NotebookViewportContribution = class NotebookViewportContribution2 extends $3c {
  static {
    this.id = "workbench.notebook.viewportWarmup";
  }
  constructor(c, f, accessibilityService) {
    super();
    this.c = c;
    this.f = f;
    this.b = null;
    this.a = new $8h(() => this.h(), 200);
    this.B(this.a);
    this.B(this.c.onDidScroll(() => {
      this.a.schedule();
    }));
    this.b = new $8h(() => this.g(), 200);
    this.B(this.b);
    this.B(this.c.onDidAttachViewModel(() => {
      if (this.c.hasModel()) {
        this.b?.schedule();
      }
    }));
    if (this.c.hasModel()) {
      this.b?.schedule();
    }
  }
  g() {
    if (this.c.hasModel()) {
      for (let i2 = 0; i2 < this.c.getLength(); i2++) {
        const cell = this.c.cellAt(i2);
        if (cell?.cellKind === CellKind.Markup && cell?.getEditState() === CellEditState.Preview && !cell.isInputCollapsed) {
        } else if (cell?.cellKind === CellKind.Code) {
          this.j(cell);
        }
      }
    }
  }
  h() {
    if (this.c.isDisposed) {
      return;
    }
    if (!this.c.hasModel()) {
      return;
    }
    const visibleRanges = this.c.getVisibleRangesPlusViewportAboveAndBelow();
    $GL(visibleRanges).forEach((index) => {
      const cell = this.c.cellAt(index);
      if (cell?.cellKind === CellKind.Markup && cell?.getEditState() === CellEditState.Preview && !cell.isInputCollapsed) {
        this.c.createMarkupPreview(cell);
      } else if (cell?.cellKind === CellKind.Code) {
        this.j(cell);
      }
    });
  }
  j(viewCell) {
    if (viewCell.isOutputCollapsed) {
      return;
    }
    const outputs = viewCell.outputsViewModels;
    for (const output of outputs.slice(0, $WIb)) {
      const [mimeTypes, pick] = output.resolveMimeTypes(this.c.textModel, void 0);
      if (!mimeTypes.find((mimeType) => mimeType.isTrusted) || mimeTypes.length === 0) {
        continue;
      }
      const pickedMimeTypeRenderer = mimeTypes[pick];
      if (!pickedMimeTypeRenderer) {
        return;
      }
      if (!this.c.hasModel()) {
        return;
      }
      const renderer = this.f.getRendererInfo(pickedMimeTypeRenderer.rendererId);
      if (!renderer) {
        return;
      }
      const result = { type: 1, renderer, source: output, mimeType: pickedMimeTypeRenderer.mimeType };
      this.c.createOutput(viewCell, result, 0, true);
    }
  }
};
NotebookViewportContribution = __decorate([
  __param(1, $mrb),
  __param(2, $ND)
], NotebookViewportContribution);
$iGb(NotebookViewportContribution.id, NotebookViewportContribution);

// out-build/vs/workbench/contrib/notebook/browser/contrib/troubleshoot/layout.js
var $G3b = class extends $3c {
  static {
    this.id = "workbench.notebook.troubleshoot";
  }
  constructor(g) {
    super();
    this.g = g;
    this.a = this.B(new $2c());
    this.b = [];
    this.c = false;
    this.f = [];
    this.B(this.g.onDidChangeModel(() => {
      this.h();
    }));
    this.h();
  }
  toggle() {
    this.c = !this.c;
    this.h();
  }
  h() {
    this.a.clear();
    this.b.forEach((listener) => listener.dispose());
    if (!this.g.hasModel()) {
      return;
    }
    this.m();
  }
  j(cell, e) {
    if (this.c) {
      const oldHeight = this.g.getViewHeight(cell);
      console.log(`cell#${cell.handle}`, e, `${oldHeight} -> ${cell.layoutInfo.totalHeight}`);
    }
  }
  m() {
    if (!this.g.hasModel()) {
      return;
    }
    for (let i2 = 0; i2 < this.g.getLength(); i2++) {
      const cell = this.g.cellAt(i2);
      this.b.push(cell.onDidChangeLayout((e) => {
        this.j(cell, e);
      }));
    }
    this.a.add(this.g.onDidChangeViewCells((e) => {
      [...e.splices].reverse().forEach((splice2) => {
        const [start, deleted, newCells] = splice2;
        const deletedCells = this.b.splice(start, deleted, ...newCells.map((cell) => {
          return cell.onDidChangeLayout((e2) => {
            this.j(cell, e2);
          });
        }));
        $Xc(deletedCells);
      });
    }));
    const vm = this.g.getViewModel();
    let items = [];
    if (this.c) {
      items = this.n();
    }
    this.f = vm.deltaCellStatusBarItems(this.f, items);
  }
  n() {
    const items = [];
    for (let i2 = 0; i2 < this.g.getLength(); i2++) {
      items.push({
        handle: i2,
        items: [
          {
            text: `index: ${i2}`,
            alignment: 1,
            priority: Number.MAX_SAFE_INTEGER
          }
        ]
      });
    }
    return items;
  }
  dispose() {
    $Xc(this.b);
    super.dispose();
  }
};
$iGb($G3b.id, $G3b);
$hJ(class extends $gJ {
  constructor() {
    super({
      id: "notebook.toggleLayoutTroubleshoot",
      title: localize2(8203, "Toggle Layout Troubleshoot"),
      category: $qn.Developer,
      f1: true
    });
  }
  async run(accessor) {
    const editorService = accessor.get($mJ);
    const editor = $Qrb(editorService.activeEditorPane);
    if (!editor) {
      return;
    }
    const controller = editor.getContribution($G3b.id);
    controller?.toggle();
  }
});
$hJ(class extends $gJ {
  constructor() {
    super({
      id: "notebook.inspectLayout",
      title: localize2(8204, "Inspect Notebook Layout"),
      category: $qn.Developer,
      f1: true
    });
  }
  async run(accessor) {
    const editorService = accessor.get($mJ);
    const editor = $Qrb(editorService.activeEditorPane);
    if (!editor || !editor.hasModel()) {
      return;
    }
    for (let i2 = 0; i2 < editor.getLength(); i2++) {
      const cell = editor.cellAt(i2);
      console.log(`cell#${cell.handle}`, cell.layoutInfo);
    }
  }
});
$hJ(class extends $gJ {
  constructor() {
    super({
      id: "notebook.clearNotebookEdtitorTypeCache",
      title: localize2(8205, "Clear Notebook Editor Type Cache"),
      category: $qn.Developer,
      f1: true
    });
  }
  async run(accessor) {
    const notebookService = accessor.get($mrb);
    notebookService.clearEditorCache();
  }
});

// out-build/vs/workbench/contrib/notebook/browser/contrib/debug/notebookBreakpoints.js
var NotebookBreakpoints = class NotebookBreakpoints2 extends $3c {
  constructor(a, _notebookService, b) {
    super();
    this.a = a;
    this.b = b;
    const listeners = new $Ec();
    this.B(_notebookService.onWillAddNotebookDocument((model) => {
      listeners.set(model.uri, model.onWillAddRemoveCells((e) => {
        const debugModel = this.a.getModel();
        if (!debugModel.getBreakpoints().length) {
          return;
        }
        if (e.rawEvent.kind !== NotebookCellsChangeType.ModelChange) {
          return;
        }
        for (const change of e.rawEvent.changes) {
          const [start, deleteCount] = change;
          if (deleteCount > 0) {
            const deleted = model.cells.slice(start, start + deleteCount);
            for (const deletedCell of deleted) {
              const cellBps = debugModel.getBreakpoints({ uri: deletedCell.uri });
              cellBps.forEach((cellBp) => this.a.removeBreakpoints(cellBp.getId()));
            }
          }
        }
      }));
    }));
    this.B(_notebookService.onWillRemoveNotebookDocument((model) => {
      this.c(model);
      listeners.get(model.uri)?.dispose();
      listeners.delete(model.uri);
    }));
    this.B(this.a.getModel().onDidChangeBreakpoints((e) => {
      const newCellBp = e?.added?.find((bp) => "uri" in bp && bp.uri.scheme === Schemas.vscodeNotebookCell);
      if (newCellBp) {
        const parsed = CellUri.parse(newCellBp.uri);
        if (!parsed) {
          return;
        }
        const editor = $Qrb(this.b.activeEditorPane);
        if (!editor || !editor.hasModel() || editor.textModel.uri.toString() !== parsed.notebook.toString()) {
          return;
        }
        const cell = editor.getCellByHandle(parsed.handle);
        if (!cell) {
          return;
        }
        editor.focusElement(cell);
      }
    }));
  }
  c(model) {
    const bps = this.a.getModel().getBreakpoints();
    if (!bps.length || !model.cells.length) {
      return;
    }
    const idxMap = new $Ec();
    model.cells.forEach((cell, i2) => {
      idxMap.set(cell.uri, i2);
    });
    bps.forEach((bp) => {
      const idx = idxMap.get(bp.uri);
      if (typeof idx !== "number") {
        return;
      }
      const notebook = CellUri.parse(bp.uri)?.notebook;
      if (!notebook) {
        return;
      }
      const newUri = CellUri.generate(notebook, idx);
      if ($oh(newUri, bp.uri)) {
        return;
      }
      this.a.removeBreakpoints(bp.getId());
      this.a.addBreakpoints(newUri, [
        {
          column: bp.column,
          condition: bp.condition,
          enabled: bp.enabled,
          hitCondition: bp.hitCondition,
          logMessage: bp.logMessage,
          lineNumber: bp.lineNumber
        }
      ]);
    });
  }
};
NotebookBreakpoints = __decorate([
  __param(0, $0R),
  __param(1, $mrb),
  __param(2, $mJ)
], NotebookBreakpoints);
$Wn.as(Extensions2.Workbench).registerWorkbenchContribution(
  NotebookBreakpoints,
  3
  /* LifecyclePhase.Restored */
);

// out-build/vs/workbench/contrib/notebook/browser/contrib/debug/notebookCellPausing.js
var NotebookCellPausing = class NotebookCellPausing2 extends $3c {
  constructor(c, f) {
    super();
    this.c = c;
    this.f = f;
    this.a = /* @__PURE__ */ new Set();
    this.B(c.getModel().onDidChangeCallStack(() => {
      this.g(true);
      this.b.schedule();
    }));
    this.b = this.B(new $8h(() => this.g(false), 2e3));
  }
  async g(fallBackOnStaleCallstack) {
    const newPausedCells = /* @__PURE__ */ new Set();
    for (const session of this.c.getModel().getSessions()) {
      for (const thread of session.getAllThreads()) {
        let callStack = thread.getCallStack();
        if (fallBackOnStaleCallstack && !callStack.length) {
          callStack = thread.getStaleCallStack();
        }
        callStack.forEach((sf) => {
          const parsed = CellUri.parse(sf.source.uri);
          if (parsed) {
            newPausedCells.add(sf.source.uri.toString());
            this.h(sf.source.uri, true);
          }
        });
      }
    }
    for (const uri of this.a) {
      if (!newPausedCells.has(uri)) {
        this.h(URI.parse(uri), false);
        this.a.delete(uri);
      }
    }
    newPausedCells.forEach((cell) => this.a.add(cell));
  }
  h(cellUri, isPaused) {
    const parsed = CellUri.parse(cellUri);
    if (parsed) {
      const exeState = this.f.getCellExecution(cellUri);
      if (exeState && (exeState.isPaused !== isPaused || !exeState.didPause)) {
        exeState.update([{
          editType: CellExecutionUpdateType.ExecutionState,
          didPause: true,
          isPaused
        }]);
      }
    }
  }
};
NotebookCellPausing = __decorate([
  __param(0, $0R),
  __param(1, $wL)
], NotebookCellPausing);
$Wn.as(Extensions2.Workbench).registerWorkbenchContribution(
  NotebookCellPausing,
  3
  /* LifecyclePhase.Restored */
);

// out-build/vs/workbench/contrib/codeEditor/browser/editorLineNumberMenu.js
var $H3b = class {
  constructor() {
    this.c = /* @__PURE__ */ new Set();
  }
  /**
   *
   * This exists solely to allow the debug and test contributions to add actions to the gutter context menu
   * which cannot be trivially expressed using when clauses and therefore cannot be statically registered.
   * If you want an action to show up in the gutter context menu, you should generally use MenuId.EditorLineNumberMenu instead.
   */
  registerGutterActionsGenerator(gutterActionsGenerator) {
    this.c.add(gutterActionsGenerator);
    return {
      dispose: () => {
        this.c.delete(gutterActionsGenerator);
      }
    };
  }
  getGutterActionsGenerators() {
    return Array.from(this.c.values());
  }
};
$Wn.add("gutterActionsRegistry", new $H3b());
var $I3b = $Wn.as("gutterActionsRegistry");
var $J3b = class $J3b2 extends $3c {
  static {
    this.ID = "workbench.contrib.editorLineNumberContextMenu";
  }
  constructor(c, f, g, h3, j) {
    super();
    this.c = c;
    this.f = f;
    this.g = g;
    this.h = h3;
    this.j = j;
    this.B(this.c.onMouseDown((e) => this.m(e, false)));
  }
  show(e) {
    this.m(e, true);
  }
  m(e, force) {
    const model = this.c.getModel();
    if (!e.event.rightButton && !($m && e.event.leftButton && e.event.ctrlKey) && !force || e.target.type !== 3 && e.target.type !== 2 || !e.target.position || !model) {
      return;
    }
    const lineNumber = e.target.position.lineNumber;
    const contextKeyService = this.h.createOverlay([["editorLineNumber", lineNumber]]);
    const menu = this.g.createMenu($bJ.EditorLineNumberContext, contextKeyService);
    const allActions = [];
    this.j.invokeFunction((accessor) => {
      for (const generator of $I3b.getGutterActionsGenerators()) {
        const collectedActions = /* @__PURE__ */ new Map();
        generator({ lineNumber, editor: this.c, accessor }, {
          push: (action, group2 = "navigation") => {
            const actions = collectedActions.get(group2) ?? [];
            actions.push(action);
            collectedActions.set(group2, actions);
          }
        });
        for (const [group2, actions] of collectedActions.entries()) {
          allActions.push([group2, actions]);
        }
      }
      allActions.sort((a, b) => a[0].localeCompare(b[0]));
      const menuActions = menu.getActions({ arg: { lineNumber, uri: model.uri }, shouldForwardArgs: true });
      allActions.push(...menuActions);
      if (e.target.type === 3) {
        const currentSelections = this.c.getSelections();
        const lineRange = {
          startLineNumber: lineNumber,
          endLineNumber: lineNumber,
          startColumn: 1,
          endColumn: model.getLineLength(lineNumber) + 1
        };
        const containsSelection = currentSelections?.some((selection) => !selection.isEmpty() && selection.intersectRanges(lineRange) !== null);
        if (!containsSelection) {
          this.c.setSelection(
            lineRange,
            "api"
            /* TextEditorSelectionSource.PROGRAMMATIC */
          );
        }
      }
      this.f.showContextMenu({
        getAnchor: () => e.event,
        getActions: () => $Wm.join(...allActions.map((a) => a[1])),
        onHide: () => menu.dispose()
      });
    });
  }
};
$J3b = __decorate([
  __param(1, $50),
  __param(2, $cJ),
  __param(3, $on),
  __param(4, $Pk)
], $J3b);
$85(
  $J3b.ID,
  $J3b,
  1
  /* EditorContributionInstantiation.AfterFirstRender */
);

// out-build/vs/workbench/contrib/debug/browser/breakpointsView.js
var BreakpointsRenderer_1;
var FunctionBreakpointsRenderer_1;
var DataBreakpointsRenderer_1;
var InstructionBreakpointsRenderer_1;
var $128 = $;
function createCheckbox(disposables) {
  const checkbox = $128("input");
  checkbox.type = "checkbox";
  checkbox.tabIndex = -1;
  disposables.add($mZ.ignoreTarget(checkbox));
  return checkbox;
}
var MAX_VISIBLE_BREAKPOINTS = 9;
function $T3b(model, sessionId, countLimit) {
  const length = model.getBreakpoints().length + model.getExceptionBreakpointsForSession(sessionId).length + model.getFunctionBreakpoints().length + model.getDataBreakpoints().length + model.getInstructionBreakpoints().length;
  return Math.min(countLimit, length) * 22;
}
var $U3b = class $U3b2 extends $_ob {
  constructor(options3, contextMenuService, bc, keybindingService, instantiationService, themeService, cc, dc, configurationService, viewDescriptorService, contextKeyService, openerService, telemetryService, ec, menuService, hoverService, fc) {
    super(options3, keybindingService, contextMenuService, configurationService, contextKeyService, viewDescriptorService, instantiationService, openerService, themeService, telemetryService, hoverService);
    this.bc = bc;
    this.cc = cc;
    this.dc = dc;
    this.ec = ec;
    this.fc = fc;
    this.c = false;
    this.f = false;
    this.g = false;
    this.ab = -1;
    this.h = menuService.createMenu($bJ.DebugBreakpointsContext, contextKeyService);
    this.B(this.h);
    this.j = $nR.bindTo(contextKeyService);
    this.m = $oR.bindTo(contextKeyService);
    this.s = $pR.bindTo(contextKeyService);
    this.t = $qR.bindTo(contextKeyService);
    this.breakpointInputFocused = $fR.bindTo(contextKeyService);
    this.B(this.bc.getModel().onDidChangeBreakpoints(() => this.mc()));
    this.B(this.bc.getViewModel().onDidFocusSession(() => this.mc()));
    this.B(this.bc.onDidChangeState(() => this.nc()));
    this.ac = this.B(new $8h(() => this.lc(true), 4e3));
  }
  W(container2) {
    super.W(container2);
    this.element.classList.add("debug-pane");
    container2.classList.add("debug-breakpoints");
    const delegate = new BreakpointsDelegate(this);
    this.b = this.Db.createInstance($Web, "Breakpoints", container2, delegate, [
      this.Db.createInstance(BreakpointsRenderer, this.h, this.s, this.t, this.j),
      new ExceptionBreakpointsRenderer(this.h, this.s, this.t, this.j, this.bc, this.Hb),
      new ExceptionBreakpointInputRenderer(this, this.bc, this.dc),
      this.Db.createInstance(FunctionBreakpointsRenderer, this.h, this.t, this.j),
      new FunctionBreakpointInputRenderer(this, this.bc, this.dc, this.Hb, this.ec),
      this.Db.createInstance(DataBreakpointsRenderer, this.h, this.s, this.t, this.j, this.m),
      new DataBreakpointInputRenderer(this, this.bc, this.dc, this.Hb, this.ec),
      this.Db.createInstance(InstructionBreakpointsRenderer)
    ], {
      identityProvider: { getId: (element) => element.getId() },
      multipleSelectionSupport: false,
      keyboardNavigationLabelProvider: { getKeyboardNavigationLabel: (e) => e },
      accessibilityProvider: new BreakpointsAccessibilityProvider(this.bc, this.ec),
      overrideStyles: this.Xb().listOverrideStyles
    });
    $aR.bindTo(this.b.contextKeyService);
    this.B(this.b.onContextMenu(this.jc, this));
    this.b.onMouseMiddleClick(async ({ element }) => {
      if (element instanceof $VP) {
        await this.bc.removeBreakpoints(element.getId());
      } else if (element instanceof $WP) {
        await this.bc.removeFunctionBreakpoints(element.getId());
      } else if (element instanceof $XP) {
        await this.bc.removeDataBreakpoints(element.getId());
      } else if (element instanceof $ZP) {
        await this.bc.removeInstructionBreakpoints(element.instructionReference, element.offset);
      }
    });
    this.B(this.b.onDidOpen(async (e) => {
      if (!e.element) {
        return;
      }
      if ($3j(e.browserEvent) && e.browserEvent.button === 1) {
        return;
      }
      if (e.element instanceof $VP) {
        $V3b(e.element, e.sideBySide, e.editorOptions.preserveFocus || false, e.editorOptions.pinned || !e.editorOptions.preserveFocus, this.bc, this.cc);
      }
      if (e.element instanceof $ZP) {
        const disassemblyView = await this.cc.openEditor($IP.instance);
        disassemblyView.goToInstructionAndOffset(e.element.instructionReference, e.element.offset, $3j(e.browserEvent) && e.browserEvent.detail === 2);
      }
      if ($3j(e.browserEvent) && e.browserEvent.detail === 2 && e.element instanceof $WP && e.element !== this.inputBoxData?.breakpoint) {
        this.renderInputBox({ breakpoint: e.element, type: "name" });
      }
    }));
    this.b.splice(0, this.b.length, this.oc);
    this.B(this.onDidChangeBodyVisibility((visible) => {
      if (visible) {
        if (this.c) {
          this.mc();
        }
        if (this.f) {
          this.nc();
        }
      }
    }));
    const containerModel = this.Cb.getViewContainerModel(this.Cb.getViewContainerByViewId(this.id));
    this.B(containerModel.onDidChangeAllViewDescriptors(() => {
      this.kc();
    }));
  }
  Ob(container2, title) {
    super.Ob(container2, title);
    const iconLabelContainer = $bk(container2, $128("span.breakpoint-warning"));
    this.sb = this.B(new $T2(iconLabelContainer, {
      supportIcons: true,
      hoverDelegate: {
        showHover: (options3, focus) => this.Hb.showHover({ content: options3.content, target: this.sb.element }, focus),
        delay: this.Ab.getValue("workbench.hover.delay")
      }
    }));
    $ik(this.sb.element);
  }
  focus() {
    super.focus();
    this.b?.domFocus();
  }
  renderInputBox(data) {
    this.L = data;
    this.mc();
    this.L = void 0;
  }
  get inputBoxData() {
    return this.L;
  }
  X(height, width2) {
    if (this.g) {
      return;
    }
    super.X(height, width2);
    this.b?.layout(height, width2);
    try {
      this.g = true;
      this.kc();
    } finally {
      this.g = false;
    }
  }
  jc(e) {
    const element = e.element;
    const type = element instanceof $VP ? "breakpoint" : element instanceof $YP ? "exceptionBreakpoint" : element instanceof $WP ? "functionBreakpoint" : element instanceof $XP ? "dataBreakpoint" : element instanceof $ZP ? "instructionBreakpoint" : void 0;
    this.j.set(type);
    const session = this.bc.getViewModel().focusedSession;
    const conditionSupported = element instanceof $YP ? element.supportsCondition : !session || !!session.capabilities.supportsConditionalBreakpoints;
    this.t.set(conditionSupported);
    this.m.set(
      element instanceof $XP && element.src.type === 1
      /* DataBreakpointSetType.Address */
    );
    const { secondary } = $O$(this.h.getActions({ arg: e.element, shouldForwardArgs: false }), "inline");
    this.zb.showContextMenu({
      getAnchor: () => e.anchor,
      getActions: () => secondary,
      getActionsContext: () => element
    });
  }
  kc() {
    const containerModel = this.Cb.getViewContainerModel(this.Cb.getViewContainerByViewId(this.id));
    const sessionId = this.bc.getViewModel().focusedSession?.getId();
    this.minimumBodySize = this.orientation === 0 ? $T3b(this.bc.getModel(), sessionId, MAX_VISIBLE_BREAKPOINTS) : 170;
    this.maximumBodySize = this.orientation === 0 && containerModel.visibleViewDescriptors.length > 1 ? $T3b(this.bc.getModel(), sessionId, Number.POSITIVE_INFINITY) : Number.POSITIVE_INFINITY;
  }
  lc(delayed = false) {
    if (!this.sb) {
      return;
    }
    const currentType = this.bc.getViewModel().focusedSession?.configuration.type;
    const dbg = currentType ? this.bc.getAdapterManager().getDebugger(currentType) : void 0;
    const message = dbg?.strings?.[DebuggerString.UnverifiedBreakpoints];
    const debuggerHasUnverifiedBps = message && this.bc.getModel().getBreakpoints().filter((bp) => {
      if (bp.verified || !bp.enabled) {
        return false;
      }
      const langId = this.fc.guessLanguageIdByFilepathOrFirstLine(bp.uri);
      return langId && dbg.interestedInLanguage(langId);
    });
    if (message && debuggerHasUnverifiedBps?.length && this.bc.getModel().areBreakpointsActivated()) {
      if (delayed) {
        const mdown = new $bm(void 0, { isTrusted: true }).appendMarkdown(message);
        this.sb.setLabel("$(warning)", void 0, { title: { markdown: mdown, markdownNotSupportedFallback: message } });
        $hk(this.sb.element);
      } else {
        this.ac.schedule();
      }
    } else {
      $ik(this.sb.element);
    }
  }
  mc() {
    if (this.isBodyVisible()) {
      this.kc();
      if (this.b) {
        const lastFocusIndex = this.b.getFocus()[0];
        const needsRefocus = lastFocusIndex && !this.oc.includes(this.b.element(lastFocusIndex));
        this.b.splice(0, this.b.length, this.oc);
        this.c = false;
        if (needsRefocus) {
          this.b.focusNth(Math.min(lastFocusIndex, this.b.length - 1));
        }
      }
      this.lc();
    } else {
      this.c = true;
    }
  }
  nc() {
    if (this.isBodyVisible()) {
      this.f = false;
      const thread = this.bc.getViewModel().focusedThread;
      let found = false;
      if (thread && thread.stoppedDetails && thread.stoppedDetails.hitBreakpointIds && thread.stoppedDetails.hitBreakpointIds.length > 0) {
        const hitBreakpointIds = thread.stoppedDetails.hitBreakpointIds;
        const elements = this.oc;
        const index = elements.findIndex((e) => {
          const id2 = e.getIdFromAdapter(thread.session.getId());
          return typeof id2 === "number" && hitBreakpointIds.indexOf(id2) !== -1;
        });
        if (index >= 0) {
          this.b.setFocus([index]);
          this.b.setSelection([index]);
          found = true;
          this.ab = index;
        }
      }
      if (!found) {
        const focus = this.b.getFocus();
        const selection = this.b.getSelection();
        if (this.ab >= 0 && $zb(focus, selection) && focus.indexOf(this.ab) >= 0) {
          this.b.setFocus([]);
          this.b.setSelection([]);
        }
        this.ab = -1;
      }
      this.lc();
    } else {
      this.f = true;
    }
  }
  get oc() {
    const model = this.bc.getModel();
    const sessionId = this.bc.getViewModel().focusedSession?.getId();
    const elements = model.getExceptionBreakpointsForSession(sessionId).concat(model.getFunctionBreakpoints()).concat(model.getDataBreakpoints()).concat(model.getBreakpoints()).concat(model.getInstructionBreakpoints());
    return elements;
  }
};
$U3b = __decorate([
  __param(1, $50),
  __param(2, $0R),
  __param(3, $Ty),
  __param(4, $Pk),
  __param(5, $gs),
  __param(6, $mJ),
  __param(7, $40),
  __param(8, $kl),
  __param(9, $$M),
  __param(10, $on),
  __param(11, $O4),
  __param(12, $zv),
  __param(13, $ZI),
  __param(14, $cJ),
  __param(15, $5$),
  __param(16, $1E)
], $U3b);
var BreakpointsDelegate = class {
  constructor(b) {
    this.b = b;
  }
  getHeight(_element) {
    return 22;
  }
  getTemplateId(element) {
    if (element instanceof $VP) {
      return BreakpointsRenderer.ID;
    }
    if (element instanceof $WP) {
      const inputBoxBreakpoint = this.b.inputBoxData?.breakpoint;
      if (!element.name || inputBoxBreakpoint && inputBoxBreakpoint.getId() === element.getId()) {
        return FunctionBreakpointInputRenderer.ID;
      }
      return FunctionBreakpointsRenderer.ID;
    }
    if (element instanceof $YP) {
      const inputBoxBreakpoint = this.b.inputBoxData?.breakpoint;
      if (inputBoxBreakpoint && inputBoxBreakpoint.getId() === element.getId()) {
        return ExceptionBreakpointInputRenderer.ID;
      }
      return ExceptionBreakpointsRenderer.ID;
    }
    if (element instanceof $XP) {
      const inputBoxBreakpoint = this.b.inputBoxData?.breakpoint;
      if (inputBoxBreakpoint && inputBoxBreakpoint.getId() === element.getId()) {
        return DataBreakpointInputRenderer.ID;
      }
      return DataBreakpointsRenderer.ID;
    }
    if (element instanceof $ZP) {
      return InstructionBreakpointsRenderer.ID;
    }
    return "";
  }
};
var breakpointIdToActionBarDomeNode = /* @__PURE__ */ new Map();
var BreakpointsRenderer = class BreakpointsRenderer2 {
  static {
    BreakpointsRenderer_1 = this;
  }
  constructor(b, c, d, f, g, h3, i2) {
    this.b = b;
    this.c = c;
    this.d = d;
    this.f = f;
    this.g = g;
    this.h = h3;
    this.i = i2;
  }
  static {
    this.ID = "breakpoints";
  }
  get templateId() {
    return BreakpointsRenderer_1.ID;
  }
  renderTemplate(container2) {
    const data = /* @__PURE__ */ Object.create(null);
    data.elementDisposables = new $2c();
    data.templateDisposables = new $2c();
    data.templateDisposables.add(data.elementDisposables);
    data.breakpoint = $bk(container2, $128(".breakpoint"));
    data.icon = $128(".icon");
    data.checkbox = createCheckbox(data.templateDisposables);
    data.templateDisposables.add($aj(data.checkbox, "change", (e) => {
      this.g.enableOrDisableBreakpoints(!data.context.enabled, data.context);
    }));
    $bk(data.breakpoint, data.icon);
    $bk(data.breakpoint, data.checkbox);
    data.name = $bk(data.breakpoint, $128("span.name"));
    data.filePath = $bk(data.breakpoint, $128("span.file-path"));
    data.actionBar = new $LZ(data.breakpoint);
    data.templateDisposables.add(data.actionBar);
    const badgeContainer = $bk(data.breakpoint, $128(".badge-container"));
    data.badge = $bk(badgeContainer, $128("span.line-number.monaco-count-badge"));
    return data;
  }
  renderElement(breakpoint, index, data) {
    data.context = breakpoint;
    data.breakpoint.classList.toggle("disabled", !this.g.getModel().areBreakpointsActivated());
    data.name.textContent = $rh(breakpoint.uri);
    let badgeContent = breakpoint.lineNumber.toString();
    if (breakpoint.column) {
      badgeContent += `:${breakpoint.column}`;
    }
    if (breakpoint.modeLabel) {
      badgeContent = `${breakpoint.modeLabel}: ${badgeContent}`;
    }
    data.badge.textContent = badgeContent;
    data.filePath.textContent = this.i.getUriLabel($uh(breakpoint.uri), { relative: true });
    data.checkbox.checked = breakpoint.enabled;
    const { message, icon: icon2 } = $W3b(this.g.state, this.g.getModel().areBreakpointsActivated(), breakpoint, this.i, this.g.getModel());
    data.icon.className = ThemeIcon.asClassName(icon2);
    data.elementDisposables.add(this.h.setupManagedHover($JZ("mouse"), data.breakpoint, breakpoint.message || message || ""));
    const debugActive = this.g.state === 3 || this.g.state === 2;
    if (debugActive && !breakpoint.verified) {
      data.breakpoint.classList.add("disabled");
    }
    const session = this.g.getViewModel().focusedSession;
    this.d.set(!session || !!session.capabilities.supportsConditionalBreakpoints);
    this.f.set("breakpoint");
    this.c.set(this.g.getModel().getBreakpointModes("source").length > 1);
    const { primary } = $Q$(this.b.getActions({ arg: breakpoint, shouldForwardArgs: true }), "inline");
    data.actionBar.clear();
    data.actionBar.push(primary, { icon: true, label: false });
    breakpointIdToActionBarDomeNode.set(breakpoint.getId(), data.actionBar.domNode);
  }
  disposeElement(a, index, template) {
    template.elementDisposables.clear();
  }
  disposeTemplate(templateData) {
    templateData.templateDisposables.dispose();
  }
};
BreakpointsRenderer = BreakpointsRenderer_1 = __decorate([
  __param(4, $0R),
  __param(5, $5$),
  __param(6, $ZI)
], BreakpointsRenderer);
var ExceptionBreakpointsRenderer = class _ExceptionBreakpointsRenderer {
  constructor(b, c, d, f, g, h3) {
    this.b = b;
    this.c = c;
    this.d = d;
    this.f = f;
    this.g = g;
    this.h = h3;
  }
  static {
    this.ID = "exceptionbreakpoints";
  }
  get templateId() {
    return _ExceptionBreakpointsRenderer.ID;
  }
  renderTemplate(container2) {
    const data = /* @__PURE__ */ Object.create(null);
    data.elementDisposables = new $2c();
    data.templateDisposables = new $2c();
    data.templateDisposables.add(data.elementDisposables);
    data.breakpoint = $bk(container2, $128(".breakpoint"));
    data.checkbox = createCheckbox(data.templateDisposables);
    data.templateDisposables.add($aj(data.checkbox, "change", (e) => {
      this.g.enableOrDisableBreakpoints(!data.context.enabled, data.context);
    }));
    $bk(data.breakpoint, data.checkbox);
    data.name = $bk(data.breakpoint, $128("span.name"));
    data.condition = $bk(data.breakpoint, $128("span.condition"));
    data.breakpoint.classList.add("exception");
    data.actionBar = new $LZ(data.breakpoint);
    data.templateDisposables.add(data.actionBar);
    const badgeContainer = $bk(data.breakpoint, $128(".badge-container"));
    data.badge = $bk(badgeContainer, $128("span.line-number.monaco-count-badge"));
    return data;
  }
  renderElement(exceptionBreakpoint, index, data) {
    data.context = exceptionBreakpoint;
    data.name.textContent = exceptionBreakpoint.label || `${exceptionBreakpoint.filter} exceptions`;
    const exceptionBreakpointtitle = exceptionBreakpoint.verified ? exceptionBreakpoint.description || data.name.textContent : exceptionBreakpoint.message || localize(5517, null);
    data.elementDisposables.add(this.h.setupManagedHover($JZ("mouse"), data.breakpoint, exceptionBreakpointtitle));
    data.breakpoint.classList.toggle("disabled", !exceptionBreakpoint.verified);
    data.checkbox.checked = exceptionBreakpoint.enabled;
    data.condition.textContent = exceptionBreakpoint.condition || "";
    data.elementDisposables.add(this.h.setupManagedHover($JZ("mouse"), data.condition, localize(5518, null, exceptionBreakpoint.condition)));
    if (exceptionBreakpoint.modeLabel) {
      data.badge.textContent = exceptionBreakpoint.modeLabel;
      data.badge.style.display = "block";
    } else {
      data.badge.style.display = "none";
    }
    this.d.set(exceptionBreakpoint.supportsCondition);
    this.f.set("exceptionBreakpoint");
    this.c.set(this.g.getModel().getBreakpointModes("exception").length > 1);
    const { primary } = $Q$(this.b.getActions({ arg: exceptionBreakpoint, shouldForwardArgs: true }), "inline");
    data.actionBar.clear();
    data.actionBar.push(primary, { icon: true, label: false });
    breakpointIdToActionBarDomeNode.set(exceptionBreakpoint.getId(), data.actionBar.domNode);
  }
  disposeElement(element, index, templateData, height) {
    templateData.elementDisposables.clear();
  }
  disposeTemplate(templateData) {
    templateData.templateDisposables.dispose();
  }
};
var FunctionBreakpointsRenderer = class FunctionBreakpointsRenderer2 {
  static {
    FunctionBreakpointsRenderer_1 = this;
  }
  constructor(b, c, d, f, g, h3) {
    this.b = b;
    this.c = c;
    this.d = d;
    this.f = f;
    this.g = g;
    this.h = h3;
  }
  static {
    this.ID = "functionbreakpoints";
  }
  get templateId() {
    return FunctionBreakpointsRenderer_1.ID;
  }
  renderTemplate(container2) {
    const data = /* @__PURE__ */ Object.create(null);
    data.elementDisposables = new $2c();
    data.templateDisposables = new $2c();
    data.templateDisposables.add(data.elementDisposables);
    data.breakpoint = $bk(container2, $128(".breakpoint"));
    data.icon = $128(".icon");
    data.checkbox = createCheckbox(data.templateDisposables);
    data.templateDisposables.add($aj(data.checkbox, "change", (e) => {
      this.f.enableOrDisableBreakpoints(!data.context.enabled, data.context);
    }));
    $bk(data.breakpoint, data.icon);
    $bk(data.breakpoint, data.checkbox);
    data.name = $bk(data.breakpoint, $128("span.name"));
    data.condition = $bk(data.breakpoint, $128("span.condition"));
    data.actionBar = new $LZ(data.breakpoint);
    data.templateDisposables.add(data.actionBar);
    const badgeContainer = $bk(data.breakpoint, $128(".badge-container"));
    data.badge = $bk(badgeContainer, $128("span.line-number.monaco-count-badge"));
    return data;
  }
  renderElement(functionBreakpoint, _index, data) {
    data.context = functionBreakpoint;
    data.name.textContent = functionBreakpoint.name;
    const { icon: icon2, message } = $W3b(this.f.state, this.f.getModel().areBreakpointsActivated(), functionBreakpoint, this.h, this.f.getModel());
    data.icon.className = ThemeIcon.asClassName(icon2);
    data.elementDisposables.add(this.g.setupManagedHover($JZ("mouse"), data.icon, message ? message : ""));
    data.checkbox.checked = functionBreakpoint.enabled;
    data.elementDisposables.add(this.g.setupManagedHover($JZ("mouse"), data.breakpoint, message ? message : ""));
    if (functionBreakpoint.condition && functionBreakpoint.hitCondition) {
      data.condition.textContent = localize(5519, null, functionBreakpoint.condition, functionBreakpoint.hitCondition);
    } else {
      data.condition.textContent = functionBreakpoint.condition || functionBreakpoint.hitCondition || "";
    }
    if (functionBreakpoint.modeLabel) {
      data.badge.textContent = functionBreakpoint.modeLabel;
      data.badge.style.display = "block";
    } else {
      data.badge.style.display = "none";
    }
    const session = this.f.getViewModel().focusedSession;
    data.breakpoint.classList.toggle("disabled", session && !session.capabilities.supportsFunctionBreakpoints || !this.f.getModel().areBreakpointsActivated());
    if (session && !session.capabilities.supportsFunctionBreakpoints) {
      data.elementDisposables.add(this.g.setupManagedHover($JZ("mouse"), data.breakpoint, localize(5520, null)));
    }
    this.c.set(!session || !!session.capabilities.supportsConditionalBreakpoints);
    this.d.set("functionBreakpoint");
    const { primary } = $Q$(this.b.getActions({ arg: functionBreakpoint, shouldForwardArgs: true }), "inline");
    data.actionBar.clear();
    data.actionBar.push(primary, { icon: true, label: false });
    breakpointIdToActionBarDomeNode.set(functionBreakpoint.getId(), data.actionBar.domNode);
  }
  disposeElement(element, index, templateData, height) {
    templateData.elementDisposables.clear();
  }
  disposeTemplate(templateData) {
    templateData.templateDisposables.dispose();
  }
};
FunctionBreakpointsRenderer = FunctionBreakpointsRenderer_1 = __decorate([
  __param(3, $0R),
  __param(4, $5$),
  __param(5, $ZI)
], FunctionBreakpointsRenderer);
var DataBreakpointsRenderer = class DataBreakpointsRenderer2 {
  static {
    DataBreakpointsRenderer_1 = this;
  }
  constructor(b, c, d, f, g, h3, i2, j) {
    this.b = b;
    this.c = c;
    this.d = d;
    this.f = f;
    this.g = g;
    this.h = h3;
    this.i = i2;
    this.j = j;
  }
  static {
    this.ID = "databreakpoints";
  }
  get templateId() {
    return DataBreakpointsRenderer_1.ID;
  }
  renderTemplate(container2) {
    const data = /* @__PURE__ */ Object.create(null);
    data.breakpoint = $bk(container2, $128(".breakpoint"));
    data.elementDisposables = new $2c();
    data.templateDisposables = new $2c();
    data.templateDisposables.add(data.elementDisposables);
    data.icon = $128(".icon");
    data.checkbox = createCheckbox(data.templateDisposables);
    data.templateDisposables.add($aj(data.checkbox, "change", (e) => {
      this.h.enableOrDisableBreakpoints(!data.context.enabled, data.context);
    }));
    $bk(data.breakpoint, data.icon);
    $bk(data.breakpoint, data.checkbox);
    data.name = $bk(data.breakpoint, $128("span.name"));
    data.accessType = $bk(data.breakpoint, $128("span.access-type"));
    data.condition = $bk(data.breakpoint, $128("span.condition"));
    data.actionBar = new $LZ(data.breakpoint);
    data.templateDisposables.add(data.actionBar);
    const badgeContainer = $bk(data.breakpoint, $128(".badge-container"));
    data.badge = $bk(badgeContainer, $128("span.line-number.monaco-count-badge"));
    return data;
  }
  renderElement(dataBreakpoint, _index, data) {
    data.context = dataBreakpoint;
    data.name.textContent = dataBreakpoint.description;
    const { icon: icon2, message } = $W3b(this.h.state, this.h.getModel().areBreakpointsActivated(), dataBreakpoint, this.j, this.h.getModel());
    data.icon.className = ThemeIcon.asClassName(icon2);
    data.elementDisposables.add(this.i.setupManagedHover($JZ("mouse"), data.icon, message ? message : ""));
    data.checkbox.checked = dataBreakpoint.enabled;
    data.elementDisposables.add(this.i.setupManagedHover($JZ("mouse"), data.breakpoint, message ? message : ""));
    if (dataBreakpoint.modeLabel) {
      data.badge.textContent = dataBreakpoint.modeLabel;
      data.badge.style.display = "block";
    } else {
      data.badge.style.display = "none";
    }
    const session = this.h.getViewModel().focusedSession;
    data.breakpoint.classList.toggle("disabled", session && !session.capabilities.supportsDataBreakpoints || !this.h.getModel().areBreakpointsActivated());
    if (session && !session.capabilities.supportsDataBreakpoints) {
      data.elementDisposables.add(this.i.setupManagedHover($JZ("mouse"), data.breakpoint, localize(5521, null)));
    }
    if (dataBreakpoint.accessType) {
      const accessType = dataBreakpoint.accessType === "read" ? localize(5522, null) : dataBreakpoint.accessType === "write" ? localize(5523, null) : localize(5524, null);
      data.accessType.textContent = accessType;
    } else {
      data.accessType.textContent = "";
    }
    if (dataBreakpoint.condition && dataBreakpoint.hitCondition) {
      data.condition.textContent = localize(5525, null, dataBreakpoint.condition, dataBreakpoint.hitCondition);
    } else {
      data.condition.textContent = dataBreakpoint.condition || dataBreakpoint.hitCondition || "";
    }
    this.d.set(!session || !!session.capabilities.supportsConditionalBreakpoints);
    this.c.set(this.h.getModel().getBreakpointModes("data").length > 1);
    this.f.set("dataBreakpoint");
    this.g.set(
      dataBreakpoint.src.type === 1
      /* DataBreakpointSetType.Address */
    );
    const { primary } = $Q$(this.b.getActions({ arg: dataBreakpoint, shouldForwardArgs: true }), "inline");
    data.actionBar.clear();
    data.actionBar.push(primary, { icon: true, label: false });
    breakpointIdToActionBarDomeNode.set(dataBreakpoint.getId(), data.actionBar.domNode);
    this.g.reset();
  }
  disposeElement(element, index, templateData, height) {
    templateData.elementDisposables.clear();
  }
  disposeTemplate(templateData) {
    templateData.templateDisposables.dispose();
  }
};
DataBreakpointsRenderer = DataBreakpointsRenderer_1 = __decorate([
  __param(5, $0R),
  __param(6, $5$),
  __param(7, $ZI)
], DataBreakpointsRenderer);
var InstructionBreakpointsRenderer = class InstructionBreakpointsRenderer2 {
  static {
    InstructionBreakpointsRenderer_1 = this;
  }
  constructor(b, c, d) {
    this.b = b;
    this.c = c;
    this.d = d;
  }
  static {
    this.ID = "instructionBreakpoints";
  }
  get templateId() {
    return InstructionBreakpointsRenderer_1.ID;
  }
  renderTemplate(container2) {
    const data = /* @__PURE__ */ Object.create(null);
    data.elementDisposables = new $2c();
    data.templateDisposables = new $2c();
    data.templateDisposables.add(data.elementDisposables);
    data.breakpoint = $bk(container2, $128(".breakpoint"));
    data.icon = $128(".icon");
    data.checkbox = createCheckbox(data.templateDisposables);
    data.templateDisposables.add($aj(data.checkbox, "change", (e) => {
      this.b.enableOrDisableBreakpoints(!data.context.enabled, data.context);
    }));
    $bk(data.breakpoint, data.icon);
    $bk(data.breakpoint, data.checkbox);
    data.name = $bk(data.breakpoint, $128("span.name"));
    data.address = $bk(data.breakpoint, $128("span.file-path"));
    data.actionBar = new $LZ(data.breakpoint);
    data.templateDisposables.add(data.actionBar);
    const badgeContainer = $bk(data.breakpoint, $128(".badge-container"));
    data.badge = $bk(badgeContainer, $128("span.line-number.monaco-count-badge"));
    return data;
  }
  renderElement(breakpoint, index, data) {
    data.context = breakpoint;
    data.breakpoint.classList.toggle("disabled", !this.b.getModel().areBreakpointsActivated());
    data.name.textContent = "0x" + breakpoint.address.toString(16);
    data.elementDisposables.add(this.c.setupManagedHover($JZ("mouse"), data.name, `Decimal address: breakpoint.address.toString()`));
    data.checkbox.checked = breakpoint.enabled;
    const { message, icon: icon2 } = $W3b(this.b.state, this.b.getModel().areBreakpointsActivated(), breakpoint, this.d, this.b.getModel());
    data.icon.className = ThemeIcon.asClassName(icon2);
    data.elementDisposables.add(this.c.setupManagedHover($JZ("mouse"), data.breakpoint, breakpoint.message || message || ""));
    const debugActive = this.b.state === 3 || this.b.state === 2;
    if (debugActive && !breakpoint.verified) {
      data.breakpoint.classList.add("disabled");
    }
    if (breakpoint.modeLabel) {
      data.badge.textContent = breakpoint.modeLabel;
      data.badge.style.display = "block";
    } else {
      data.badge.style.display = "none";
    }
  }
  disposeElement(element, index, templateData, height) {
    templateData.elementDisposables.clear();
  }
  disposeTemplate(templateData) {
    templateData.templateDisposables.dispose();
  }
};
InstructionBreakpointsRenderer = InstructionBreakpointsRenderer_1 = __decorate([
  __param(0, $0R),
  __param(1, $5$),
  __param(2, $ZI)
], InstructionBreakpointsRenderer);
var FunctionBreakpointInputRenderer = class _FunctionBreakpointInputRenderer {
  constructor(b, c, d, f, g) {
    this.b = b;
    this.c = c;
    this.d = d;
    this.f = f;
    this.g = g;
  }
  static {
    this.ID = "functionbreakpointinput";
  }
  get templateId() {
    return _FunctionBreakpointInputRenderer.ID;
  }
  renderTemplate(container2) {
    const template = /* @__PURE__ */ Object.create(null);
    const toDispose = new $2c();
    const breakpoint = $bk(container2, $128(".breakpoint"));
    template.icon = $128(".icon");
    template.checkbox = createCheckbox(toDispose);
    $bk(breakpoint, template.icon);
    $bk(breakpoint, template.checkbox);
    this.b.breakpointInputFocused.set(true);
    const inputBoxContainer = $bk(breakpoint, $128(".inputBoxContainer"));
    const inputBox = new $I2(inputBoxContainer, this.d, { inputBoxStyles: $B$ });
    toDispose.add(inputBox);
    const wrapUp = (success) => {
      template.updating = true;
      try {
        this.b.breakpointInputFocused.set(false);
        const id2 = template.breakpoint.getId();
        if (success) {
          if (template.type === "name") {
            this.c.updateFunctionBreakpoint(id2, { name: inputBox.value });
          }
          if (template.type === "condition") {
            this.c.updateFunctionBreakpoint(id2, { condition: inputBox.value });
          }
          if (template.type === "hitCount") {
            this.c.updateFunctionBreakpoint(id2, { hitCondition: inputBox.value });
          }
        } else {
          if (template.type === "name" && !template.breakpoint.name) {
            this.c.removeFunctionBreakpoints(id2);
          } else {
            this.b.renderInputBox(void 0);
          }
        }
      } finally {
        template.updating = false;
      }
    };
    toDispose.add($aj(inputBox.inputElement, "keydown", (e) => {
      const isEscape = e.equals(
        9
        /* KeyCode.Escape */
      );
      const isEnter = e.equals(
        3
        /* KeyCode.Enter */
      );
      if (isEscape || isEnter) {
        e.preventDefault();
        e.stopPropagation();
        wrapUp(isEnter);
      }
    }));
    toDispose.add($_i(inputBox.inputElement, "blur", () => {
      if (!template.updating) {
        wrapUp(!!inputBox.value);
      }
    }));
    template.inputBox = inputBox;
    template.elementDisposables = new $2c();
    template.templateDisposables = toDispose;
    template.templateDisposables.add(template.elementDisposables);
    return template;
  }
  renderElement(functionBreakpoint, _index, data) {
    data.breakpoint = functionBreakpoint;
    data.type = this.b.inputBoxData?.type || "name";
    const { icon: icon2, message } = $W3b(this.c.state, this.c.getModel().areBreakpointsActivated(), functionBreakpoint, this.g, this.c.getModel());
    data.icon.className = ThemeIcon.asClassName(icon2);
    data.elementDisposables.add(this.f.setupManagedHover($JZ("mouse"), data.icon, message ? message : ""));
    data.checkbox.checked = functionBreakpoint.enabled;
    data.checkbox.disabled = true;
    data.inputBox.value = functionBreakpoint.name || "";
    let placeholder = localize(5526, null);
    let ariaLabel = localize(5527, null);
    if (data.type === "condition") {
      data.inputBox.value = functionBreakpoint.condition || "";
      placeholder = localize(5528, null);
      ariaLabel = localize(5529, null);
    } else if (data.type === "hitCount") {
      data.inputBox.value = functionBreakpoint.hitCondition || "";
      placeholder = localize(5530, null);
      ariaLabel = localize(5531, null);
    }
    data.inputBox.setAriaLabel(ariaLabel);
    data.inputBox.setPlaceHolder(placeholder);
    setTimeout(() => {
      data.inputBox.focus();
      data.inputBox.select();
    }, 0);
  }
  disposeElement(element, index, templateData, height) {
    templateData.elementDisposables.clear();
  }
  disposeTemplate(templateData) {
    templateData.templateDisposables.dispose();
  }
};
var DataBreakpointInputRenderer = class _DataBreakpointInputRenderer {
  constructor(b, c, d, f, g) {
    this.b = b;
    this.c = c;
    this.d = d;
    this.f = f;
    this.g = g;
  }
  static {
    this.ID = "databreakpointinput";
  }
  get templateId() {
    return _DataBreakpointInputRenderer.ID;
  }
  renderTemplate(container2) {
    const template = /* @__PURE__ */ Object.create(null);
    const toDispose = new $2c();
    const breakpoint = $bk(container2, $128(".breakpoint"));
    template.icon = $128(".icon");
    template.checkbox = createCheckbox(toDispose);
    $bk(breakpoint, template.icon);
    $bk(breakpoint, template.checkbox);
    this.b.breakpointInputFocused.set(true);
    const inputBoxContainer = $bk(breakpoint, $128(".inputBoxContainer"));
    const inputBox = new $I2(inputBoxContainer, this.d, { inputBoxStyles: $B$ });
    toDispose.add(inputBox);
    const wrapUp = (success) => {
      template.updating = true;
      try {
        this.b.breakpointInputFocused.set(false);
        const id2 = template.breakpoint.getId();
        if (success) {
          if (template.type === "condition") {
            this.c.updateDataBreakpoint(id2, { condition: inputBox.value });
          }
          if (template.type === "hitCount") {
            this.c.updateDataBreakpoint(id2, { hitCondition: inputBox.value });
          }
        } else {
          this.b.renderInputBox(void 0);
        }
      } finally {
        template.updating = false;
      }
    };
    toDispose.add($aj(inputBox.inputElement, "keydown", (e) => {
      const isEscape = e.equals(
        9
        /* KeyCode.Escape */
      );
      const isEnter = e.equals(
        3
        /* KeyCode.Enter */
      );
      if (isEscape || isEnter) {
        e.preventDefault();
        e.stopPropagation();
        wrapUp(isEnter);
      }
    }));
    toDispose.add($_i(inputBox.inputElement, "blur", () => {
      if (!template.updating) {
        wrapUp(!!inputBox.value);
      }
    }));
    template.inputBox = inputBox;
    template.elementDisposables = new $2c();
    template.templateDisposables = toDispose;
    template.templateDisposables.add(template.elementDisposables);
    return template;
  }
  renderElement(dataBreakpoint, _index, data) {
    data.breakpoint = dataBreakpoint;
    data.type = this.b.inputBoxData?.type || "condition";
    const { icon: icon2, message } = $W3b(this.c.state, this.c.getModel().areBreakpointsActivated(), dataBreakpoint, this.g, this.c.getModel());
    data.icon.className = ThemeIcon.asClassName(icon2);
    data.elementDisposables.add(this.f.setupManagedHover($JZ("mouse"), data.icon, message ?? ""));
    data.checkbox.checked = dataBreakpoint.enabled;
    data.checkbox.disabled = true;
    data.inputBox.value = "";
    let placeholder = "";
    let ariaLabel = "";
    if (data.type === "condition") {
      data.inputBox.value = dataBreakpoint.condition || "";
      placeholder = localize(5532, null);
      ariaLabel = localize(5533, null);
    } else if (data.type === "hitCount") {
      data.inputBox.value = dataBreakpoint.hitCondition || "";
      placeholder = localize(5534, null);
      ariaLabel = localize(5535, null);
    }
    data.inputBox.setAriaLabel(ariaLabel);
    data.inputBox.setPlaceHolder(placeholder);
    setTimeout(() => {
      data.inputBox.focus();
      data.inputBox.select();
    }, 0);
  }
  disposeElement(element, index, templateData, height) {
    templateData.elementDisposables.clear();
  }
  disposeTemplate(templateData) {
    templateData.templateDisposables.dispose();
  }
};
var ExceptionBreakpointInputRenderer = class _ExceptionBreakpointInputRenderer {
  constructor(b, c, d) {
    this.b = b;
    this.c = c;
    this.d = d;
  }
  static {
    this.ID = "exceptionbreakpointinput";
  }
  get templateId() {
    return _ExceptionBreakpointInputRenderer.ID;
  }
  renderTemplate(container2) {
    const toDispose = new $2c();
    const breakpoint = $bk(container2, $128(".breakpoint"));
    breakpoint.classList.add("exception");
    const checkbox = createCheckbox(toDispose);
    $bk(breakpoint, checkbox);
    this.b.breakpointInputFocused.set(true);
    const inputBoxContainer = $bk(breakpoint, $128(".inputBoxContainer"));
    const inputBox = new $I2(inputBoxContainer, this.d, {
      ariaLabel: localize(5536, null),
      inputBoxStyles: $B$
    });
    toDispose.add(inputBox);
    const wrapUp = (success) => {
      if (!templateData.currentBreakpoint) {
        return;
      }
      this.b.breakpointInputFocused.set(false);
      let newCondition = templateData.currentBreakpoint.condition;
      if (success) {
        newCondition = inputBox.value !== "" ? inputBox.value : void 0;
      }
      this.c.setExceptionBreakpointCondition(templateData.currentBreakpoint, newCondition);
    };
    toDispose.add($aj(inputBox.inputElement, "keydown", (e) => {
      const isEscape = e.equals(
        9
        /* KeyCode.Escape */
      );
      const isEnter = e.equals(
        3
        /* KeyCode.Enter */
      );
      if (isEscape || isEnter) {
        e.preventDefault();
        e.stopPropagation();
        wrapUp(isEnter);
      }
    }));
    toDispose.add($_i(inputBox.inputElement, "blur", () => {
      setTimeout(() => {
        wrapUp(true);
      });
    }));
    const elementDisposables = new $2c();
    toDispose.add(elementDisposables);
    const templateData = {
      inputBox,
      checkbox,
      templateDisposables: toDispose,
      elementDisposables: new $2c()
    };
    return templateData;
  }
  renderElement(exceptionBreakpoint, _index, data) {
    const placeHolder = exceptionBreakpoint.conditionDescription || localize(5537, null);
    data.inputBox.setPlaceHolder(placeHolder);
    data.currentBreakpoint = exceptionBreakpoint;
    data.checkbox.checked = exceptionBreakpoint.enabled;
    data.checkbox.disabled = true;
    data.inputBox.value = exceptionBreakpoint.condition || "";
    setTimeout(() => {
      data.inputBox.focus();
      data.inputBox.select();
    }, 0);
  }
  disposeElement(element, index, templateData, height) {
    templateData.elementDisposables.clear();
  }
  disposeTemplate(templateData) {
    templateData.templateDisposables.dispose();
  }
};
var BreakpointsAccessibilityProvider = class {
  constructor(b, c) {
    this.b = b;
    this.c = c;
  }
  getWidgetAriaLabel() {
    return localize(5538, null);
  }
  getRole() {
    return "checkbox";
  }
  isChecked(breakpoint) {
    return breakpoint.enabled;
  }
  getAriaLabel(element) {
    if (element instanceof $YP) {
      return element.toString();
    }
    const { message } = $W3b(this.b.state, this.b.getModel().areBreakpointsActivated(), element, this.c, this.b.getModel());
    const toString = element.toString();
    return message ? `${toString}, ${message}` : toString;
  }
};
function $V3b(breakpoint, sideBySide, preserveFocus, pinned, debugService, editorService) {
  if (breakpoint.uri.scheme === $5R && debugService.state === 0) {
    return Promise.resolve(void 0);
  }
  const selection = breakpoint.endLineNumber ? {
    startLineNumber: breakpoint.lineNumber,
    endLineNumber: breakpoint.endLineNumber,
    startColumn: breakpoint.column || 1,
    endColumn: breakpoint.endColumn || 1073741824
    /* Constants.MAX_SAFE_SMALL_INTEGER */
  } : {
    startLineNumber: breakpoint.lineNumber,
    startColumn: breakpoint.column || 1,
    endLineNumber: breakpoint.lineNumber,
    endColumn: breakpoint.column || 1073741824
    /* Constants.MAX_SAFE_SMALL_INTEGER */
  };
  return editorService.openEditor({
    resource: breakpoint.uri,
    options: {
      preserveFocus,
      selection,
      revealIfOpened: true,
      selectionRevealType: 1,
      pinned
    }
  }, sideBySide ? $oJ : $nJ);
}
function $W3b(state, breakpointsActivated, breakpoint, labelService, debugModel) {
  const debugActive = state === 3 || state === 2;
  const breakpointIcon = breakpoint instanceof $XP ? $FFb : breakpoint instanceof $WP ? $DFb : breakpoint.logMessage ? $GFb : $CFb;
  if (!breakpoint.enabled || !breakpointsActivated) {
    return {
      icon: breakpointIcon.disabled,
      message: breakpoint.logMessage ? localize(5539, null) : localize(5540, null)
    };
  }
  const appendMessage = (text2) => {
    return "message" in breakpoint && breakpoint.message ? text2.concat(", " + breakpoint.message) : text2;
  };
  if (debugActive && breakpoint instanceof $VP && breakpoint.pending) {
    return {
      icon: $CFb.pending
    };
  }
  if (debugActive && !breakpoint.verified) {
    return {
      icon: breakpointIcon.unverified,
      message: "message" in breakpoint && breakpoint.message ? breakpoint.message : breakpoint.logMessage ? localize(5541, null) : localize(5542, null),
      showAdapterUnverifiedMessage: true
    };
  }
  if (breakpoint instanceof $XP) {
    if (!breakpoint.supported) {
      return {
        icon: breakpointIcon.unverified,
        message: localize(5543, null)
      };
    }
    return {
      icon: breakpointIcon.regular,
      message: breakpoint.message || localize(5544, null)
    };
  }
  if (breakpoint instanceof $WP) {
    if (!breakpoint.supported) {
      return {
        icon: breakpointIcon.unverified,
        message: localize(5545, null)
      };
    }
    const messages = [];
    messages.push(breakpoint.message || localize(5546, null));
    if (breakpoint.condition) {
      messages.push(localize(5547, null, breakpoint.condition));
    }
    if (breakpoint.hitCondition) {
      messages.push(localize(5548, null, breakpoint.hitCondition));
    }
    return {
      icon: breakpointIcon.regular,
      message: appendMessage(messages.join("\n"))
    };
  }
  if (breakpoint instanceof $ZP) {
    if (!breakpoint.supported) {
      return {
        icon: breakpointIcon.unverified,
        message: localize(5549, null)
      };
    }
    const messages = [];
    if (breakpoint.message) {
      messages.push(breakpoint.message);
    } else if (breakpoint.instructionReference) {
      messages.push(localize(5550, null, breakpoint.instructionReference));
    } else {
      messages.push(localize(5551, null));
    }
    if (breakpoint.hitCondition) {
      messages.push(localize(5552, null, breakpoint.hitCondition));
    }
    return {
      icon: breakpointIcon.regular,
      message: appendMessage(messages.join("\n"))
    };
  }
  let triggeringBreakpoint;
  if (breakpoint instanceof $VP && breakpoint.triggeredBy) {
    triggeringBreakpoint = debugModel.getBreakpoints().find((bp) => bp.getId() === breakpoint.triggeredBy);
  }
  if (breakpoint.logMessage || breakpoint.condition || breakpoint.hitCondition || triggeringBreakpoint) {
    const messages = [];
    let icon2 = breakpoint.logMessage ? $GFb.regular : $EFb.regular;
    if (!breakpoint.supported) {
      icon2 = $IFb;
      messages.push(localize(5553, null));
    }
    if (breakpoint.logMessage) {
      messages.push(localize(5554, null, breakpoint.logMessage));
    }
    if (breakpoint.condition) {
      messages.push(localize(5555, null, breakpoint.condition));
    }
    if (breakpoint.hitCondition) {
      messages.push(localize(5556, null, breakpoint.hitCondition));
    }
    if (triggeringBreakpoint) {
      messages.push(localize(5557, null, `${labelService.getUriLabel(triggeringBreakpoint.uri, { relative: true })}: ${triggeringBreakpoint.lineNumber}`));
    }
    return {
      icon: icon2,
      message: appendMessage(messages.join("\n"))
    };
  }
  const message = "message" in breakpoint && breakpoint.message ? breakpoint.message : breakpoint instanceof $VP && labelService ? labelService.getUriLabel(breakpoint.uri) : localize(5558, null);
  return {
    icon: breakpointIcon.regular,
    message
  };
}
$hJ(class extends $gJ {
  constructor() {
    super({
      id: "workbench.debug.viewlet.action.addFunctionBreakpointAction",
      title: {
        ...localize2(5578, "Add Function Breakpoint"),
        mnemonicTitle: localize(5559, null)
      },
      f1: true,
      icon: $0Fb,
      menu: [{
        id: $bJ.ViewTitle,
        group: "navigation",
        order: 10,
        when: $7m.equals("view", $YQ)
      }, {
        id: $bJ.MenubarNewBreakpointMenu,
        group: "1_breakpoints",
        order: 3,
        when: $BR
      }]
    });
  }
  async run(accessor) {
    const debugService = accessor.get($0R);
    const viewService = accessor.get($uob);
    await viewService.openView($YQ);
    debugService.addFunctionBreakpoint();
  }
});
var MemoryBreakpointAction = class extends $gJ {
  async run(accessor, existingBreakpoint) {
    const debugService = accessor.get($0R);
    const session = debugService.getViewModel().focusedSession;
    if (!session) {
      return;
    }
    let defaultValue = void 0;
    if (existingBreakpoint && existingBreakpoint.src.type === 1) {
      defaultValue = `${existingBreakpoint.src.address} + ${existingBreakpoint.src.bytes}`;
    }
    const quickInput = accessor.get($1M);
    const notifications = accessor.get($PJ);
    const range = await this.b(quickInput, defaultValue);
    if (!range) {
      return;
    }
    let info;
    try {
      info = await session.dataBytesBreakpointInfo(range.address, range.bytes);
    } catch (e) {
      notifications.error(localize(5560, null, range.address, e.message));
    }
    if (!info?.dataId) {
      return;
    }
    let accessType = "write";
    if (info.accessTypes && info.accessTypes?.length > 1) {
      const accessTypes = info.accessTypes.map((type) => ({ label: type }));
      const selectedAccessType = await quickInput.pick(accessTypes, { placeHolder: localize(5561, null) });
      if (!selectedAccessType) {
        return;
      }
      accessType = selectedAccessType.label;
    }
    const src = { type: 1, ...range };
    if (existingBreakpoint) {
      await debugService.removeDataBreakpoints(existingBreakpoint.getId());
    }
    await debugService.addDataBreakpoint({
      description: info.description,
      src,
      canPersist: true,
      accessTypes: info.accessTypes,
      accessType,
      initialSessionData: { session, dataId: info.dataId }
    });
  }
  b(quickInput, defaultValue) {
    return new Promise((resolve) => {
      const disposables = new $2c();
      const input = disposables.add(quickInput.createInputBox());
      input.prompt = localize(5562, null);
      input.placeholder = localize(5563, null);
      if (defaultValue) {
        input.value = defaultValue;
        input.valueSelection = [0, defaultValue.length];
      }
      disposables.add(input.onDidChangeValue((e) => {
        const err = this.c(e, false);
        input.validationMessage = err?.error;
      }));
      disposables.add(input.onDidAccept(() => {
        const r2 = this.c(input.value, true);
        if ("error" in r2) {
          input.validationMessage = r2.error;
        } else {
          resolve(r2);
        }
        input.dispose();
      }));
      disposables.add(input.onDidHide(() => {
        resolve(void 0);
        disposables.dispose();
      }));
      input.ignoreFocusOut = true;
      input.show();
    });
  }
  c(range, isFinal) {
    const parts = /^(\S+)\s*(?:([+-])\s*(\S+))?/.exec(range);
    if (!parts) {
      return { error: localize(5564, null) };
    }
    const isNum = (e) => isFinal ? /^0x[0-9a-f]*|[0-9]*$/i.test(e) : /^0x[0-9a-f]+|[0-9]+$/i.test(e);
    const [, startStr, sign = "+", endStr = "1"] = parts;
    for (const n of [startStr, endStr]) {
      if (!isNum(n)) {
        return { error: localize(5565, null, n) };
      }
    }
    if (!isFinal) {
      return;
    }
    const start = BigInt(startStr);
    const end = BigInt(endStr);
    const address = `0x${start.toString(16)}`;
    if (sign === "-") {
      return { address, bytes: Number(start - end) };
    }
    return { address, bytes: Number(end) };
  }
};
$hJ(class extends MemoryBreakpointAction {
  constructor() {
    super({
      id: "workbench.debug.viewlet.action.addDataBreakpointOnAddress",
      title: {
        ...localize2(5579, "Add Data Breakpoint at Address"),
        mnemonicTitle: localize(5566, null)
      },
      f1: true,
      icon: $$Fb,
      menu: [{
        id: $bJ.ViewTitle,
        group: "navigation",
        order: 11,
        when: $7m.and($FR, $7m.equals("view", $YQ))
      }, {
        id: $bJ.MenubarNewBreakpointMenu,
        group: "1_breakpoints",
        order: 4,
        when: $FR
      }]
    });
  }
});
$hJ(class extends MemoryBreakpointAction {
  constructor() {
    super({
      id: "workbench.debug.viewlet.action.editDataBreakpointOnAddress",
      title: localize2(5580, "Edit Address..."),
      menu: [{
        id: $bJ.DebugBreakpointsContext,
        when: $7m.and($FR, $oR),
        group: "navigation",
        order: 15
      }]
    });
  }
});
$hJ(class extends $gJ {
  constructor() {
    super({
      id: "workbench.debug.viewlet.action.toggleBreakpointsActivatedAction",
      title: localize2(5581, "Toggle Activate Breakpoints"),
      f1: true,
      icon: $aGb,
      menu: {
        id: $bJ.ViewTitle,
        group: "navigation",
        order: 20,
        when: $7m.equals("view", $YQ)
      }
    });
  }
  run(accessor) {
    const debugService = accessor.get($0R);
    debugService.setBreakpointsActivated(!debugService.getModel().areBreakpointsActivated());
  }
});
$hJ(class extends $gJ {
  constructor() {
    super({
      id: "workbench.debug.viewlet.action.removeBreakpoint",
      title: localize(5567, null),
      icon: $6l.removeClose,
      menu: [{
        id: $bJ.DebugBreakpointsContext,
        group: "3_modification",
        order: 10,
        when: $nR.notEqualsTo("exceptionBreakpoint")
      }, {
        id: $bJ.DebugBreakpointsContext,
        group: "inline",
        order: 20,
        when: $nR.notEqualsTo("exceptionBreakpoint")
      }]
    });
  }
  async run(accessor, breakpoint) {
    const debugService = accessor.get($0R);
    if (breakpoint instanceof $VP) {
      await debugService.removeBreakpoints(breakpoint.getId());
    } else if (breakpoint instanceof $WP) {
      await debugService.removeFunctionBreakpoints(breakpoint.getId());
    } else if (breakpoint instanceof $XP) {
      await debugService.removeDataBreakpoints(breakpoint.getId());
    } else if (breakpoint instanceof $ZP) {
      await debugService.removeInstructionBreakpoints(breakpoint.instructionReference, breakpoint.offset);
    }
  }
});
$hJ(class extends $gJ {
  constructor() {
    super({
      id: "workbench.debug.viewlet.action.removeAllBreakpoints",
      title: {
        ...localize2(5582, "Remove All Breakpoints"),
        mnemonicTitle: localize(5568, null)
      },
      f1: true,
      icon: $_Fb,
      menu: [{
        id: $bJ.ViewTitle,
        group: "navigation",
        order: 30,
        when: $7m.equals("view", $YQ)
      }, {
        id: $bJ.DebugBreakpointsContext,
        group: "3_modification",
        order: 20,
        when: $7m.and($AR, $nR.notEqualsTo("exceptionBreakpoint"))
      }, {
        id: $bJ.MenubarDebugMenu,
        group: "5_breakpoints",
        order: 3,
        when: $BR
      }]
    });
  }
  run(accessor) {
    const debugService = accessor.get($0R);
    debugService.removeBreakpoints();
    debugService.removeFunctionBreakpoints();
    debugService.removeDataBreakpoints();
    debugService.removeInstructionBreakpoints();
  }
});
$hJ(class extends $gJ {
  constructor() {
    super({
      id: "workbench.debug.viewlet.action.enableAllBreakpoints",
      title: {
        ...localize2(5583, "Enable All Breakpoints"),
        mnemonicTitle: localize(5569, null)
      },
      f1: true,
      precondition: $BR,
      menu: [{
        id: $bJ.DebugBreakpointsContext,
        group: "z_commands",
        order: 10,
        when: $7m.and($AR, $nR.notEqualsTo("exceptionBreakpoint"))
      }, {
        id: $bJ.MenubarDebugMenu,
        group: "5_breakpoints",
        order: 1,
        when: $BR
      }]
    });
  }
  async run(accessor) {
    const debugService = accessor.get($0R);
    await debugService.enableOrDisableBreakpoints(true);
  }
});
$hJ(class extends $gJ {
  constructor() {
    super({
      id: "workbench.debug.viewlet.action.disableAllBreakpoints",
      title: {
        ...localize2(5584, "Disable All Breakpoints"),
        mnemonicTitle: localize(5570, null)
      },
      f1: true,
      precondition: $BR,
      menu: [{
        id: $bJ.DebugBreakpointsContext,
        group: "z_commands",
        order: 20,
        when: $7m.and($AR, $nR.notEqualsTo("exceptionBreakpoint"))
      }, {
        id: $bJ.MenubarDebugMenu,
        group: "5_breakpoints",
        order: 2,
        when: $BR
      }]
    });
  }
  async run(accessor) {
    const debugService = accessor.get($0R);
    await debugService.enableOrDisableBreakpoints(false);
  }
});
$hJ(class extends $gJ {
  constructor() {
    super({
      id: "workbench.debug.viewlet.action.reapplyBreakpointsAction",
      title: localize2(5585, "Reapply All Breakpoints"),
      f1: true,
      precondition: $9Q,
      menu: [{
        id: $bJ.DebugBreakpointsContext,
        group: "z_commands",
        order: 30,
        when: $7m.and($AR, $nR.notEqualsTo("exceptionBreakpoint"))
      }]
    });
  }
  async run(accessor) {
    const debugService = accessor.get($0R);
    await debugService.setBreakpointsActivated(true);
  }
});
$hJ(class extends $cpb {
  constructor() {
    super({
      id: "debug.editBreakpoint",
      viewId: $YQ,
      title: localize(5571, null),
      icon: $6l.edit,
      precondition: $qR,
      menu: [{
        id: $bJ.DebugBreakpointsContext,
        when: $nR.notEqualsTo("functionBreakpoint"),
        group: "navigation",
        order: 10
      }, {
        id: $bJ.DebugBreakpointsContext,
        group: "inline",
        order: 10
      }]
    });
  }
  async runInView(accessor, view, breakpoint) {
    const debugService = accessor.get($0R);
    const editorService = accessor.get($mJ);
    if (breakpoint instanceof $VP) {
      const editor = await $V3b(breakpoint, false, false, true, debugService, editorService);
      if (editor) {
        const codeEditor = editor.getControl();
        if ($P5(codeEditor)) {
          codeEditor.getContribution($4R)?.showBreakpointWidget(breakpoint.lineNumber, breakpoint.column);
        }
      }
    } else if (breakpoint instanceof $WP) {
      const contextMenuService = accessor.get($50);
      const actions = [
        new $Um("breakpoint.editCondition", localize(5572, null), void 0, true, async () => view.renderInputBox({ breakpoint, type: "condition" })),
        new $Um("breakpoint.editCondition", localize(5573, null), void 0, true, async () => view.renderInputBox({ breakpoint, type: "hitCount" }))
      ];
      const domNode = breakpointIdToActionBarDomeNode.get(breakpoint.getId());
      if (domNode) {
        contextMenuService.showContextMenu({
          getActions: () => actions,
          getAnchor: () => domNode,
          onHide: () => $Xc(actions)
        });
      }
    } else {
      view.renderInputBox({ breakpoint, type: "condition" });
    }
  }
});
$hJ(class extends $cpb {
  constructor() {
    super({
      id: "debug.editFunctionBreakpoint",
      viewId: $YQ,
      title: localize(5574, null),
      menu: [{
        id: $bJ.DebugBreakpointsContext,
        group: "navigation",
        order: 10,
        when: $nR.isEqualTo("functionBreakpoint")
      }]
    });
  }
  runInView(_accessor, view, breakpoint) {
    view.renderInputBox({ breakpoint, type: "name" });
  }
});
$hJ(class extends $cpb {
  constructor() {
    super({
      id: "debug.editFunctionBreakpointHitCount",
      viewId: $YQ,
      title: localize(5575, null),
      precondition: $qR,
      menu: [{
        id: $bJ.DebugBreakpointsContext,
        group: "navigation",
        order: 20,
        when: $7m.or($nR.isEqualTo("functionBreakpoint"), $nR.isEqualTo("dataBreakpoint"))
      }]
    });
  }
  runInView(_accessor, view, breakpoint) {
    view.renderInputBox({ breakpoint, type: "hitCount" });
  }
});
$hJ(class extends $cpb {
  constructor() {
    super({
      id: "debug.editBreakpointMode",
      viewId: $YQ,
      title: localize(5576, null),
      menu: [{
        id: $bJ.DebugBreakpointsContext,
        group: "navigation",
        order: 20,
        when: $7m.and($pR, $7m.or($nR.isEqualTo("breakpoint"), $nR.isEqualTo("exceptionBreakpoint"), $nR.isEqualTo("instructionBreakpoint")))
      }]
    });
  }
  async runInView(accessor, view, breakpoint) {
    const kind = breakpoint instanceof $VP ? "source" : breakpoint instanceof $ZP ? "instruction" : "exception";
    const debugService = accessor.get($0R);
    const modes = debugService.getModel().getBreakpointModes(kind);
    const picked = await accessor.get($1M).pick(modes.map((mode) => ({ label: mode.label, description: mode.description, mode: mode.mode })), { placeHolder: localize(5577, null) });
    if (!picked) {
      return;
    }
    if (kind === "source") {
      const data = /* @__PURE__ */ new Map();
      data.set(breakpoint.getId(), { mode: picked.mode, modeLabel: picked.label });
      debugService.updateBreakpoints(breakpoint.originalUri, data, false);
    } else if (breakpoint instanceof $ZP) {
      debugService.removeInstructionBreakpoints(breakpoint.instructionReference, breakpoint.offset);
      debugService.addInstructionBreakpoint({ ...breakpoint.toJSON(), mode: picked.mode, modeLabel: picked.label });
    } else if (breakpoint instanceof $YP) {
      breakpoint.mode = picked.mode;
      breakpoint.modeLabel = picked.label;
      debugService.setExceptionBreakpointCondition(breakpoint, breakpoint.condition);
    }
  }
});

// out-build/vs/workbench/contrib/debug/browser/breakpointWidget.js
var $129 = $;
var IPrivateBreakpointWidgetService = $Qk("privateBreakpointWidgetService");
var DECORATION_KEY = "breakpointwidgetdecoration";
function isPositionInCurlyBracketBlock(input) {
  const model = input.getModel();
  const bracketPairs = model.bracketPairs.getBracketPairsInRange($9C.fromPositions(input.getPosition()));
  return bracketPairs.some((p) => p.openingBracketInfo.bracketText === "{");
}
function createDecorations(theme, placeHolder) {
  const transparentForeground = theme.getColor($Lo)?.transparent(0.4);
  return [{
    range: {
      startLineNumber: 0,
      endLineNumber: 0,
      startColumn: 0,
      endColumn: 1
    },
    renderOptions: {
      after: {
        contentText: placeHolder,
        color: transparentForeground ? transparentForeground.toString() : void 0
      }
    }
  }];
}
var $X3b = class $X3b2 extends $_db {
  constructor(editor, T, U, context, V, W, X, Y, Z, ab, bb, cb, db, eb, fb, gb, hb) {
    super(editor, { showFrame: true, showArrow: false, frameWidth: 1, isAccessible: true });
    this.T = T;
    this.U = U;
    this.V = V;
    this.W = W;
    this.X = X;
    this.Y = Y;
    this.Z = Z;
    this.ab = ab;
    this.bb = bb;
    this.cb = cb;
    this.db = db;
    this.eb = eb;
    this.fb = fb;
    this.gb = gb;
    this.hb = hb;
    this.L = "";
    this.M = "";
    this.N = "";
    this.K = [];
    const model = this.editor.getModel();
    if (model) {
      const uri = model.uri;
      const breakpoints = this.W.getModel().getBreakpoints({ lineNumber: this.T, column: this.U, uri });
      this.P = breakpoints.length ? breakpoints[0] : void 0;
    }
    if (context === void 0) {
      if (this.P && !this.P.condition && !this.P.hitCondition && this.P.logMessage) {
        this.Q = 2;
      } else if (this.P && !this.P.condition && this.P.hitCondition) {
        this.Q = 1;
      } else if (this.P && this.P.triggeredBy) {
        this.Q = 3;
      } else {
        this.Q = 0;
      }
    } else {
      this.Q = context;
    }
    this.K.push(this.W.getModel().onDidChangeBreakpoints((e) => {
      if (this.P && e && e.removed && e.removed.indexOf(this.P) >= 0) {
        this.dispose();
      }
    }));
    this.bb.registerDecorationType("breakpoint-widget", DECORATION_KEY, {});
    this.create();
  }
  get ib() {
    const acceptString = this.eb.lookupKeybinding(AcceptBreakpointWidgetInputAction.ID)?.getLabel() || "Enter";
    const closeString = this.eb.lookupKeybinding(CloseBreakpointWidgetCommand.ID)?.getLabel() || "Escape";
    switch (this.Q) {
      case 2:
        return localize(5586, null, acceptString, closeString);
      case 1:
        return localize(5587, null, acceptString, closeString);
      default:
        return localize(5588, null, acceptString, closeString);
    }
  }
  jb(breakpoint) {
    switch (this.Q) {
      case 2:
        return breakpoint && breakpoint.logMessage ? breakpoint.logMessage : this.N;
      case 1:
        return breakpoint && breakpoint.hitCondition ? breakpoint.hitCondition : this.M;
      default:
        return breakpoint && breakpoint.condition ? breakpoint.condition : this.L;
    }
  }
  kb() {
    if (this.Q !== 3) {
      const value = this.d.getModel().getValue();
      switch (this.Q) {
        case 2:
          this.N = value;
          break;
        case 1:
          this.M = value;
          break;
        default:
          this.L = value;
      }
    }
  }
  lb() {
    if (this.editor.hasModel()) {
      const languageId = this.Q === 2 ? $KF : this.editor.getModel().getLanguageId();
      this.d.getModel().setLanguage(languageId);
    }
  }
  show(rangeOrPos) {
    const lineNum = this.d.getModel().getLineCount();
    super.show(rangeOrPos, lineNum + 1);
  }
  fitHeightToContent() {
    const lineNum = this.d.getModel().getLineCount();
    this.E(lineNum + 1);
  }
  B(container2) {
    this.A("breakpoint-widget");
    const selectBox = new $N1([
      { text: localize(5589, null) },
      { text: localize(5590, null) },
      { text: localize(5591, null) },
      { text: localize(5592, null) }
    ], this.Q, this.V, $K$, { ariaLabel: localize(5593, null) });
    this.a = $129(".breakpoint-select-container");
    selectBox.render($bk(container2, this.a));
    selectBox.onDidSelect((e) => {
      this.kb();
      this.Q = e.index;
      this.pb();
    });
    this.nb(container2);
    this.b = $129(".inputContainer");
    this.K.push(this.hb.setupManagedHover($JZ("mouse"), this.b, this.ib));
    this.tb($bk(container2, this.b));
    this.d.getModel().setValue(this.jb(this.P));
    this.K.push(this.d.getModel().onDidChangeContent(() => {
      this.fitHeightToContent();
    }));
    this.d.setPosition({ lineNumber: 1, column: this.d.getModel().getLineMaxColumn(1) });
    this.ob(container2);
    this.pb();
    setTimeout(() => this.wb(), 150);
  }
  nb(container2) {
    const modes = this.W.getModel().getBreakpointModes("source");
    if (modes.length <= 1) {
      return;
    }
    const sb = this.J = new $N1([
      { text: localize(5594, null), isDisabled: true },
      ...modes.map((mode) => ({ text: mode.label, description: mode.description }))
    ], modes.findIndex((m) => m.mode === this.P?.mode) + 1, this.V, $K$);
    this.K.push(sb);
    this.K.push(sb.onDidSelect((e) => {
      this.O = modes[e.index - 1];
    }));
    const modeWrapper = $129(".select-mode-container");
    const selectionWrapper = $129(".select-box-container");
    $bk(modeWrapper, selectionWrapper);
    sb.render(selectionWrapper);
    $bk(container2, modeWrapper);
  }
  ob(container2) {
    const breakpoints = this.W.getModel().getBreakpoints().filter((bp) => bp !== this.P && !bp.logMessage);
    const breakpointOptions = [
      { text: localize(5595, null), isDisabled: true },
      ...breakpoints.map((bp) => ({
        text: `${this.fb.getUriLabel(bp.uri, { relative: true })}: ${bp.lineNumber}`,
        description: localize(5596, null)
      }))
    ];
    const index = breakpoints.findIndex((bp) => this.P?.triggeredBy === bp.getId());
    for (const [i2, bp] of breakpoints.entries()) {
      this.gb.createModelReference(bp.uri).then((ref) => {
        try {
          breakpointOptions[i2 + 1].description = ref.object.textEditorModel.getLineContent(bp.lineNumber).trim();
        } finally {
          ref.dispose();
        }
      }).catch(() => {
        breakpointOptions[i2 + 1].description = localize(5597, null);
      });
    }
    const selectBreakpointBox = this.r = new $N1(breakpointOptions, index + 1, this.V, $K$, { ariaLabel: localize(5598, null) });
    selectBreakpointBox.onDidSelect((e) => {
      if (e.index === 0) {
        this.S = void 0;
      } else {
        this.S = breakpoints[e.index - 1];
      }
    });
    this.K.push(selectBreakpointBox);
    this.c = $129(".select-breakpoint-container");
    this.K.push($_i(this.c, $7j.KEY_DOWN, (e) => {
      const event = new $if(e);
      if (event.equals(
        9
        /* KeyCode.Escape */
      )) {
        this.close(false);
      }
    }));
    const selectionWrapper = $129(".select-box-container");
    $bk(this.c, selectionWrapper);
    selectBreakpointBox.render(selectionWrapper);
    $bk(container2, this.c);
    const closeButton = new $k2(this.c, $q$);
    closeButton.label = localize(5599, null);
    this.K.push(closeButton.onDidClick(() => this.close(true)));
    this.K.push(closeButton);
  }
  pb() {
    if (this.Q === 3) {
      this.b.hidden = true;
      this.c.hidden = false;
    } else {
      this.b.hidden = false;
      this.c.hidden = true;
      this.lb();
      const value = this.jb(this.P);
      this.d.getModel().setValue(value);
      this.wb();
    }
  }
  D(heightInPixel, widthInPixel) {
    this.R = heightInPixel;
    this.d.layout({ height: heightInPixel, width: widthInPixel - 113 });
    this.vb();
  }
  C(widthInPixel) {
    if (typeof this.R === "number") {
      this.D(this.R, widthInPixel);
    }
  }
  tb(container2) {
    const scopedContextKeyService = this.Y.createScoped(container2);
    this.K.push(scopedContextKeyService);
    const scopedInstatiationService = this.Z.createChild(new $Ok([$on, scopedContextKeyService], [IPrivateBreakpointWidgetService, this]));
    this.K.push(scopedInstatiationService);
    const options3 = this.ub();
    const codeEditorWidgetOptions = $1sb();
    this.d = scopedInstatiationService.createInstance($D9, container2, options3, codeEditorWidgetOptions);
    $_Q.bindTo(scopedContextKeyService).set(true);
    const model = this.ab.createModel("", null, URI.parse(`${$5R}:${this.editor.getId()}:breakpointinput`), true);
    if (this.editor.hasModel()) {
      model.setLanguage(this.editor.getModel().getLanguageId());
    }
    this.d.setModel(model);
    this.lb();
    this.K.push(model);
    const setDecorations = () => {
      const value = this.d.getModel().getValue();
      const decorations = !!value ? [] : createDecorations(this.X.getColorTheme(), this.ib);
      this.d.setDecorationsByType("breakpoint-widget", DECORATION_KEY, decorations);
    };
    this.d.getModel().onDidChangeContent(() => setDecorations());
    this.X.onDidColorThemeChange(() => setDecorations());
    this.K.push(this.db.completionProvider.register({ scheme: $5R, hasAccessToAllModels: true }, {
      _debugDisplayName: "breakpointWidget",
      provideCompletionItems: (model2, position, _context, token) => {
        let suggestionsPromise;
        const underlyingModel = this.editor.getModel();
        if (underlyingModel && (this.Q === 0 || this.Q === 2 && isPositionInCurlyBracketBlock(this.d))) {
          suggestionsPromise = $gcb(this.db.completionProvider, underlyingModel, new $8C(this.T, 1), new $ccb(void 0, (/* @__PURE__ */ new Set()).add(
            27
            /* CompletionItemKind.Snippet */
          )), _context, token).then((suggestions) => {
            let overwriteBefore = 0;
            if (this.Q === 0) {
              overwriteBefore = position.column - 1;
            } else {
              const value = this.d.getModel().getValue();
              while (position.column - 2 - overwriteBefore >= 0 && value[position.column - 2 - overwriteBefore] !== "{" && value[position.column - 2 - overwriteBefore] !== " ") {
                overwriteBefore++;
              }
            }
            return {
              suggestions: suggestions.items.map((s) => {
                s.completion.range = $9C.fromPositions(position.delta(0, -overwriteBefore), position);
                return s.completion;
              })
            };
          });
        } else {
          suggestionsPromise = Promise.resolve({ suggestions: [] });
        }
        return suggestionsPromise;
      }
    }));
    this.K.push(this.cb.onDidChangeConfiguration((e) => {
      if (e.affectsConfiguration("editor.fontSize") || e.affectsConfiguration("editor.lineHeight")) {
        this.d.updateOptions(this.ub());
        this.vb();
      }
    }));
  }
  ub() {
    const editorConfig = this.cb.getValue("editor");
    const options3 = $Zsb(this.cb);
    options3.fontSize = editorConfig.fontSize;
    options3.fontFamily = editorConfig.fontFamily;
    options3.lineHeight = editorConfig.lineHeight;
    options3.fontLigatures = editorConfig.fontLigatures;
    options3.ariaLabel = this.ib;
    return options3;
  }
  vb() {
    if (this.container && typeof this.R === "number") {
      const lineHeight = this.d.getOption(
        68
        /* EditorOption.lineHeight */
      );
      const lineNum = this.d.getModel().getLineCount();
      const newTopMargin = (this.R - lineNum * lineHeight) / 2;
      this.b.style.marginTop = newTopMargin + "px";
    }
  }
  close(success) {
    if (success) {
      let condition = void 0;
      let hitCondition = void 0;
      let logMessage = void 0;
      let triggeredBy = void 0;
      let mode = void 0;
      let modeLabel = void 0;
      this.kb();
      if (this.L || this.Q === 0) {
        condition = this.L;
      }
      if (this.M || this.Q === 1) {
        hitCondition = this.M;
      }
      if (this.N || this.Q === 2) {
        logMessage = this.N;
      }
      if (this.J) {
        mode = this.O?.mode;
        modeLabel = this.O?.label;
      }
      if (this.Q === 3) {
        condition = void 0;
        hitCondition = void 0;
        logMessage = void 0;
        triggeredBy = this.S?.getId();
      }
      if (this.P) {
        const data = /* @__PURE__ */ new Map();
        data.set(this.P.getId(), {
          condition,
          hitCondition,
          logMessage,
          triggeredBy,
          mode,
          modeLabel
        });
        this.W.updateBreakpoints(this.P.originalUri, data, false).then(void 0, $gb);
      } else {
        const model = this.editor.getModel();
        if (model) {
          this.W.addBreakpoints(model.uri, [{
            lineNumber: this.T,
            column: this.U,
            enabled: true,
            condition,
            hitCondition,
            logMessage,
            triggeredBy,
            mode,
            modeLabel
          }]);
        }
      }
    }
    this.dispose();
  }
  wb() {
    if (this.Q === 3) {
      this.r.focus();
    } else {
      this.d.focus();
    }
  }
  dispose() {
    super.dispose();
    this.d.dispose();
    $Xc(this.K);
    setTimeout(() => this.editor.focus(), 0);
  }
};
$X3b = __decorate([
  __param(4, $40),
  __param(5, $0R),
  __param(6, $gs),
  __param(7, $on),
  __param(8, $Pk),
  __param(9, $sG),
  __param(10, $U5),
  __param(11, $kl),
  __param(12, $mP),
  __param(13, $Ty),
  __param(14, $ZI),
  __param(15, $oG),
  __param(16, $5$)
], $X3b);
var AcceptBreakpointWidgetInputAction = class _AcceptBreakpointWidgetInputAction extends $Y5 {
  static {
    this.ID = "breakpointWidget.action.acceptInput";
  }
  constructor() {
    super({
      id: _AcceptBreakpointWidgetInputAction.ID,
      precondition: $$Q,
      kbOpts: {
        kbExpr: $_Q,
        primary: 3,
        weight: 100
        /* KeybindingWeight.EditorContrib */
      }
    });
  }
  runEditorCommand(accessor, editor) {
    accessor.get(IPrivateBreakpointWidgetService).close(true);
  }
};
var CloseBreakpointWidgetCommand = class _CloseBreakpointWidgetCommand extends $Y5 {
  static {
    this.ID = "closeBreakpointWidget";
  }
  constructor() {
    super({
      id: _CloseBreakpointWidgetCommand.ID,
      precondition: $$Q,
      kbOpts: {
        kbExpr: EditorContextKeys.textInputFocus,
        primary: 9,
        secondary: [
          1024 | 9
          /* KeyCode.Escape */
        ],
        weight: 100
        /* KeybindingWeight.EditorContrib */
      }
    });
  }
  runEditorCommand(accessor, editor, args2) {
    const debugContribution = editor.getContribution($4R);
    if (debugContribution) {
      return debugContribution.closeBreakpointWidget();
    }
    accessor.get(IPrivateBreakpointWidgetService).close(false);
  }
};
$45(new AcceptBreakpointWidgetInputAction());
$45(new CloseBreakpointWidgetCommand());

// out-build/vs/workbench/contrib/debug/browser/breakpointEditorContribution.js
var $130 = $;
var breakpointHelperDecoration = {
  description: "breakpoint-helper-decoration",
  glyphMarginClassName: ThemeIcon.asClassName($HFb),
  glyphMargin: { position: GlyphMarginLane.Right },
  glyphMarginHoverMessage: new $bm().appendText(localize(5477, null)),
  stickiness: 1
  /* TrackedRangeStickiness.NeverGrowsWhenTypingAtEdges */
};
function $Y3b(accessor, model, breakpoints, state, breakpointsActivated, showBreakpointsInOverviewRuler) {
  const result = [];
  breakpoints.forEach((breakpoint) => {
    if (breakpoint.lineNumber > model.getLineCount()) {
      return;
    }
    const hasOtherBreakpointsOnLine = breakpoints.some((bp) => bp !== breakpoint && bp.lineNumber === breakpoint.lineNumber);
    const column = model.getLineFirstNonWhitespaceColumn(breakpoint.lineNumber);
    const range = model.validateRange(
      breakpoint.column ? new $9C(breakpoint.lineNumber, breakpoint.column, breakpoint.lineNumber, breakpoint.column + 1) : new $9C(breakpoint.lineNumber, column, breakpoint.lineNumber, column + 1)
      // Decoration has to have a width #20688
    );
    result.push({
      options: getBreakpointDecorationOptions(accessor, model, breakpoint, state, breakpointsActivated, showBreakpointsInOverviewRuler, hasOtherBreakpointsOnLine),
      range
    });
  });
  return result;
}
function getBreakpointDecorationOptions(accessor, model, breakpoint, state, breakpointsActivated, showBreakpointsInOverviewRuler, hasOtherBreakpointsOnLine) {
  const debugService = accessor.get($0R);
  const languageService = accessor.get($1E);
  const labelService = accessor.get($ZI);
  const { icon: icon2, message, showAdapterUnverifiedMessage } = $W3b(state, breakpointsActivated, breakpoint, labelService, debugService.getModel());
  let glyphMarginHoverMessage;
  let unverifiedMessage;
  if (showAdapterUnverifiedMessage) {
    let langId;
    unverifiedMessage = debugService.getModel().getSessions().map((s) => {
      const dbg = debugService.getAdapterManager().getDebugger(s.configuration.type);
      const message2 = dbg?.strings?.[DebuggerString.UnverifiedBreakpoints];
      if (message2) {
        if (!langId) {
          langId = languageService.guessLanguageIdByFilepathOrFirstLine(breakpoint.uri) ?? void 0;
        }
        return langId && dbg.interestedInLanguage(langId) ? message2 : void 0;
      }
      return void 0;
    }).find((messages) => !!messages);
  }
  if (message) {
    glyphMarginHoverMessage = new $bm(void 0, { isTrusted: true, supportThemeIcons: true });
    if (breakpoint.condition || breakpoint.hitCondition) {
      const languageId = model.getLanguageId();
      glyphMarginHoverMessage.appendCodeblock(languageId, message);
      if (unverifiedMessage) {
        glyphMarginHoverMessage.appendMarkdown("$(warning) " + unverifiedMessage);
      }
    } else {
      glyphMarginHoverMessage.appendText(message);
      if (unverifiedMessage) {
        glyphMarginHoverMessage.appendMarkdown("\n\n$(warning) " + unverifiedMessage);
      }
    }
  } else if (unverifiedMessage) {
    glyphMarginHoverMessage = new $bm(void 0, { isTrusted: true, supportThemeIcons: true }).appendMarkdown(unverifiedMessage);
  }
  let overviewRulerDecoration = null;
  if (showBreakpointsInOverviewRuler) {
    overviewRulerDecoration = {
      color: $hs($13b),
      position: OverviewRulerLane.Left
    };
  }
  const renderInline = breakpoint.column && (hasOtherBreakpointsOnLine || breakpoint.column > model.getLineFirstNonWhitespaceColumn(breakpoint.lineNumber));
  return {
    description: "breakpoint-decoration",
    glyphMargin: { position: GlyphMarginLane.Right },
    glyphMarginClassName: ThemeIcon.asClassName(icon2),
    glyphMarginHoverMessage,
    stickiness: 1,
    before: renderInline ? {
      content: $wg,
      inlineClassName: `debug-breakpoint-placeholder`,
      inlineClassNameAffectsLetterSpacing: true
    } : void 0,
    overviewRuler: overviewRulerDecoration,
    zIndex: 9999
  };
}
async function requestBreakpointCandidateLocations(model, lineNumbers, session) {
  if (!session.capabilities.supportsBreakpointLocationsRequest) {
    return [];
  }
  return await Promise.all($Rb(lineNumbers, (l) => l).map(async (lineNumber) => {
    try {
      return { lineNumber, positions: await session.breakpointsLocations(model.uri, lineNumber) };
    } catch {
      return { lineNumber, positions: [] };
    }
  }));
}
function createCandidateDecorations(model, breakpointDecorations, lineBreakpoints) {
  const result = [];
  for (const { positions, lineNumber } of lineBreakpoints) {
    if (positions.length === 0) {
      continue;
    }
    const firstColumn = model.getLineFirstNonWhitespaceColumn(lineNumber);
    const lastColumn = model.getLineLastNonWhitespaceColumn(lineNumber);
    positions.forEach((p) => {
      const range = new $9C(p.lineNumber, p.column, p.lineNumber, p.column + 1);
      if (p.column <= firstColumn && !breakpointDecorations.some((bp) => bp.range.startColumn > firstColumn && bp.range.startLineNumber === p.lineNumber) || p.column > lastColumn) {
        return;
      }
      const breakpointAtPosition = breakpointDecorations.find((bpd) => bpd.range.equalsRange(range));
      if (breakpointAtPosition && breakpointAtPosition.inlineWidget) {
        return;
      }
      result.push({
        range,
        options: {
          description: "breakpoint-placeholder-decoration",
          stickiness: 1,
          before: breakpointAtPosition ? void 0 : {
            content: $wg,
            inlineClassName: `debug-breakpoint-placeholder`,
            inlineClassNameAffectsLetterSpacing: true
          }
        },
        breakpoint: breakpointAtPosition ? breakpointAtPosition.breakpoint : void 0
      });
    });
  }
  return result;
}
var $Z3b = class $Z3b2 {
  constructor(q, r2, t, u, contextKeyService, w, x, y) {
    this.q = q;
    this.r = r2;
    this.t = t;
    this.u = u;
    this.w = w;
    this.x = x;
    this.y = y;
    this.a = null;
    this.h = [];
    this.j = false;
    this.k = false;
    this.m = [];
    this.n = [];
    this.g = $$Q.bindTo(contextKeyService);
    this.o = new $8h(() => this.D(), 30);
    this.o.schedule();
    this.z();
  }
  /**
   * Returns context menu actions at the line number if breakpoints can be
   * set. This is used by the {@link TestingDecorations} to allow breakpoint
   * setting on lines where breakpoint "run" actions are present.
   */
  getContextMenuActionsAtPosition(lineNumber, model) {
    if (!this.r.getAdapterManager().hasEnabledDebuggers()) {
      return [];
    }
    if (!this.r.canSetBreakpointsIn(model)) {
      return [];
    }
    const breakpoints = this.r.getModel().getBreakpoints({ lineNumber, uri: model.uri });
    return this.A(breakpoints, model.uri, lineNumber);
  }
  z() {
    this.h.push(this.q.onMouseDown(async (e) => {
      if (!this.r.getAdapterManager().hasEnabledDebuggers()) {
        return;
      }
      const model = this.q.getModel();
      if (!e.target.position || !model || e.target.type !== 2 || e.target.detail.isAfterLines || !this.B(e.target.position.lineNumber) && !e.target.element?.className.includes("breakpoint")) {
        return;
      }
      const canSetBreakpoints = this.r.canSetBreakpointsIn(model);
      const lineNumber = e.target.position.lineNumber;
      const uri = model.uri;
      if (e.event.rightButton || $m && e.event.leftButton && e.event.ctrlKey) {
        return;
      } else {
        const breakpoints = this.r.getModel().getBreakpoints({ uri, lineNumber });
        if (breakpoints.length) {
          const isShiftPressed = e.event.shiftKey;
          const enabled = breakpoints.some((bp) => bp.enabled);
          if (isShiftPressed) {
            breakpoints.forEach((bp) => this.r.enableOrDisableBreakpoints(!enabled, bp));
          } else if (!$n && breakpoints.some((bp) => !!bp.condition || !!bp.logMessage || !!bp.hitCondition || !!bp.triggeredBy)) {
            const logPoint = breakpoints.every((bp) => !!bp.logMessage);
            const breakpointType = logPoint ? localize(5478, null) : localize(5479, null);
            const disabledBreakpointDialogMessage = localize(5480, null, breakpointType.toLowerCase(), logPoint ? localize(5481, null) : localize(5482, null));
            const enabledBreakpointDialogMessage = localize(5483, null, breakpointType.toLowerCase(), logPoint ? localize(5484, null) : localize(5485, null));
            await this.w.prompt({
              type: severity_default.Info,
              message: enabled ? enabledBreakpointDialogMessage : disabledBreakpointDialogMessage,
              buttons: [
                {
                  label: localize(5486, null, breakpointType),
                  run: () => breakpoints.forEach((bp) => this.r.removeBreakpoints(bp.getId()))
                },
                {
                  label: localize(5487, null, enabled ? localize(5488, null) : localize(5489, null), breakpointType),
                  run: () => breakpoints.forEach((bp) => this.r.enableOrDisableBreakpoints(!enabled, bp))
                }
              ],
              cancelButton: true
            });
          } else {
            if (!enabled) {
              breakpoints.forEach((bp) => this.r.enableOrDisableBreakpoints(!enabled, bp));
            } else {
              breakpoints.forEach((bp) => this.r.removeBreakpoints(bp.getId()));
            }
          }
        } else if (canSetBreakpoints) {
          if (e.event.middleButton) {
            const action = this.x.getValue("debug").gutterMiddleClickAction;
            if (action !== "none") {
              let context;
              switch (action) {
                case "logpoint":
                  context = 2;
                  break;
                case "conditionalBreakpoint":
                  context = 0;
                  break;
                case "triggeredBreakpoint":
                  context = 3;
              }
              this.showBreakpointWidget(lineNumber, void 0, context);
            }
          } else {
            this.r.addBreakpoints(uri, [{ lineNumber }]);
          }
        }
      }
    }));
    if (!($5e.pointerEvents && $Xe)) {
      this.h.push(this.q.onMouseMove((e) => {
        if (!this.r.getAdapterManager().hasEnabledDebuggers()) {
          return;
        }
        let showBreakpointHintAtLineNumber = -1;
        const model = this.q.getModel();
        if (model && e.target.position && (e.target.type === 2 || e.target.type === 3) && this.r.canSetBreakpointsIn(model) && this.B(e.target.position.lineNumber)) {
          const data = e.target.detail;
          if (!data.isAfterLines) {
            showBreakpointHintAtLineNumber = e.target.position.lineNumber;
          }
        }
        this.C(showBreakpointHintAtLineNumber);
      }));
      this.h.push(this.q.onMouseLeave(() => {
        this.C(-1);
      }));
    }
    this.h.push(this.q.onDidChangeModel(async () => {
      this.closeBreakpointWidget();
      await this.D();
    }));
    this.h.push(this.r.getModel().onDidChangeBreakpoints(() => {
      if (!this.k && !this.o.isScheduled()) {
        this.o.schedule();
      }
    }));
    this.h.push(this.r.onDidChangeState(() => {
      if (!this.o.isScheduled()) {
        this.o.schedule();
      }
    }));
    this.h.push(this.q.onDidChangeModelDecorations(() => this.E()));
    this.h.push(this.x.onDidChangeConfiguration(async (e) => {
      if (e.affectsConfiguration("debug.showBreakpointsInOverviewRuler") || e.affectsConfiguration("debug.showInlineBreakpointCandidates")) {
        await this.D();
      }
    }));
  }
  A(breakpoints, uri, lineNumber, column) {
    const actions = [];
    if (breakpoints.length === 1) {
      const breakpointType = breakpoints[0].logMessage ? localize(5490, null) : localize(5491, null);
      actions.push(new $Um("debug.removeBreakpoint", localize(5492, null, breakpointType), void 0, true, async () => {
        await this.r.removeBreakpoints(breakpoints[0].getId());
      }));
      actions.push(new $Um("workbench.debug.action.editBreakpointAction", localize(5493, null, breakpointType), void 0, true, () => Promise.resolve(this.showBreakpointWidget(breakpoints[0].lineNumber, breakpoints[0].column))));
      actions.push(new $Um(`workbench.debug.viewlet.action.toggleBreakpoint`, breakpoints[0].enabled ? localize(5494, null, breakpointType) : localize(5495, null, breakpointType), void 0, true, () => this.r.enableOrDisableBreakpoints(!breakpoints[0].enabled, breakpoints[0])));
    } else if (breakpoints.length > 1) {
      const sorted = breakpoints.slice().sort((first, second) => first.column && second.column ? first.column - second.column : 1);
      actions.push(new $Xm("debug.removeBreakpoints", localize(5496, null), sorted.map((bp) => new $Um("removeInlineBreakpoint", bp.column ? localize(5497, null, bp.column) : localize(5498, null), void 0, true, () => this.r.removeBreakpoints(bp.getId())))));
      actions.push(new $Xm("debug.editBreakpoints", localize(5499, null), sorted.map((bp) => new $Um("editBreakpoint", bp.column ? localize(5500, null, bp.column) : localize(5501, null), void 0, true, () => Promise.resolve(this.showBreakpointWidget(bp.lineNumber, bp.column))))));
      actions.push(new $Xm("debug.enableDisableBreakpoints", localize(5502, null), sorted.map((bp) => new $Um(bp.enabled ? "disableColumnBreakpoint" : "enableColumnBreakpoint", bp.enabled ? bp.column ? localize(5503, null, bp.column) : localize(5504, null) : bp.column ? localize(5505, null, bp.column) : localize(5506, null), void 0, true, () => this.r.enableOrDisableBreakpoints(!bp.enabled, bp)))));
    } else {
      actions.push(new $Um("addBreakpoint", localize(5507, null), void 0, true, () => this.r.addBreakpoints(uri, [{ lineNumber, column }])));
      actions.push(new $Um("addConditionalBreakpoint", localize(5508, null), void 0, true, () => Promise.resolve(this.showBreakpointWidget(
        lineNumber,
        column,
        0
        /* BreakpointWidgetContext.CONDITION */
      ))));
      actions.push(new $Um("addLogPoint", localize(5509, null), void 0, true, () => Promise.resolve(this.showBreakpointWidget(
        lineNumber,
        column,
        2
        /* BreakpointWidgetContext.LOG_MESSAGE */
      ))));
      actions.push(new $Um("addTriggeredBreakpoint", localize(5510, null), void 0, true, () => Promise.resolve(this.showBreakpointWidget(
        lineNumber,
        column,
        3
        /* BreakpointWidgetContext.TRIGGER_POINT */
      ))));
    }
    if (this.r.state === 2) {
      actions.push(new $Wm());
      actions.push(new $Um("runToLine", localize(5511, null), void 0, true, () => this.r.runTo(uri, lineNumber).catch($gb)));
    }
    return actions;
  }
  B(line) {
    const decorations = this.q.getLineDecorations(line);
    if (decorations) {
      for (const { options: options3 } of decorations) {
        const clz = options3.glyphMarginClassName;
        if (!clz) {
          continue;
        }
        const hasSomeActionableCodicon = !(clz.includes("codicon-") || clz.startsWith("coverage-deco-")) || clz.includes("codicon-testing-") || clz.includes("codicon-merge-") || clz.includes("codicon-arrow-") || clz.includes("codicon-loading") || clz.includes("codicon-fold") || clz.includes("codicon-gutter-lightbulb") || clz.includes("codicon-lightbulb-sparkle");
        if (hasSomeActionableCodicon) {
          return false;
        }
      }
    }
    return true;
  }
  C(showBreakpointHintAtLineNumber) {
    this.q.changeDecorations((accessor) => {
      if (this.a) {
        accessor.removeDecoration(this.a);
        this.a = null;
      }
      if (showBreakpointHintAtLineNumber !== -1) {
        this.a = accessor.addDecoration({
          startLineNumber: showBreakpointHintAtLineNumber,
          startColumn: 1,
          endLineNumber: showBreakpointHintAtLineNumber,
          endColumn: 1
        }, breakpointHelperDecoration);
      }
    });
  }
  async D() {
    if (!this.q.hasModel()) {
      return;
    }
    const setCandidateDecorations = (changeAccessor, desiredCandidatePositions2) => {
      const desiredCandidateDecorations = createCandidateDecorations(model, this.m, desiredCandidatePositions2);
      const candidateDecorationIds = changeAccessor.deltaDecorations(this.n.map((c) => c.decorationId), desiredCandidateDecorations);
      this.n.forEach((candidate) => {
        candidate.inlineWidget.dispose();
      });
      this.n = candidateDecorationIds.map((decorationId, index) => {
        const candidate = desiredCandidateDecorations[index];
        const icon2 = candidate.breakpoint ? $W3b(this.r.state, this.r.getModel().areBreakpointsActivated(), candidate.breakpoint, this.y, this.r.getModel()).icon : $CFb.disabled;
        const contextMenuActions = () => this.A(candidate.breakpoint ? [candidate.breakpoint] : [], activeCodeEditor.getModel().uri, candidate.range.startLineNumber, candidate.range.startColumn);
        const inlineWidget = new InlineBreakpointWidget(activeCodeEditor, decorationId, ThemeIcon.asClassName(icon2), candidate.breakpoint, this.r, this.t, contextMenuActions);
        return {
          decorationId,
          inlineWidget
        };
      });
    };
    const activeCodeEditor = this.q;
    const model = activeCodeEditor.getModel();
    const breakpoints = this.r.getModel().getBreakpoints({ uri: model.uri });
    const debugSettings = this.x.getValue("debug");
    const desiredBreakpointDecorations = this.u.invokeFunction((accessor) => $Y3b(accessor, model, breakpoints, this.r.state, this.r.getModel().areBreakpointsActivated(), debugSettings.showBreakpointsInOverviewRuler));
    const session = this.r.getViewModel().focusedSession;
    const desiredCandidatePositions = debugSettings.showInlineBreakpointCandidates && session ? requestBreakpointCandidateLocations(this.q.getModel(), desiredBreakpointDecorations.map((bp) => bp.range.startLineNumber), session) : Promise.resolve([]);
    const desiredCandidatePositionsRaced = await Promise.race([desiredCandidatePositions, $Wh(500).then(() => void 0)]);
    if (desiredCandidatePositionsRaced === void 0) {
      desiredCandidatePositions.then((v) => activeCodeEditor.changeDecorations((d) => setCandidateDecorations(d, v)));
    }
    try {
      this.j = true;
      activeCodeEditor.changeDecorations((changeAccessor) => {
        const decorationIds = changeAccessor.deltaDecorations(this.m.map((bpd) => bpd.decorationId), desiredBreakpointDecorations);
        this.m.forEach((bpd) => {
          bpd.inlineWidget?.dispose();
        });
        this.m = decorationIds.map((decorationId, index) => {
          let inlineWidget = void 0;
          const breakpoint = breakpoints[index];
          if (desiredBreakpointDecorations[index].options.before) {
            const contextMenuActions = () => this.A([breakpoint], activeCodeEditor.getModel().uri, breakpoint.lineNumber, breakpoint.column);
            inlineWidget = new InlineBreakpointWidget(activeCodeEditor, decorationId, desiredBreakpointDecorations[index].options.glyphMarginClassName, breakpoint, this.r, this.t, contextMenuActions);
          }
          return {
            decorationId,
            breakpoint,
            range: desiredBreakpointDecorations[index].range,
            inlineWidget
          };
        });
        if (desiredCandidatePositionsRaced) {
          setCandidateDecorations(changeAccessor, desiredCandidatePositionsRaced);
        }
      });
    } finally {
      this.j = false;
    }
    for (const d of this.m) {
      if (d.inlineWidget) {
        this.q.layoutContentWidget(d.inlineWidget);
      }
    }
  }
  async E() {
    if (this.m.length === 0 || this.j || !this.q.hasModel()) {
      return;
    }
    let somethingChanged = false;
    const model = this.q.getModel();
    this.m.forEach((breakpointDecoration) => {
      if (somethingChanged) {
        return;
      }
      const newBreakpointRange = model.getDecorationRange(breakpointDecoration.decorationId);
      if (newBreakpointRange && !breakpointDecoration.range.equalsRange(newBreakpointRange)) {
        somethingChanged = true;
        breakpointDecoration.range = newBreakpointRange;
      }
    });
    if (!somethingChanged) {
      return;
    }
    const data = /* @__PURE__ */ new Map();
    for (let i2 = 0, len = this.m.length; i2 < len; i2++) {
      const breakpointDecoration = this.m[i2];
      const decorationRange = model.getDecorationRange(breakpointDecoration.decorationId);
      if (decorationRange) {
        if (breakpointDecoration.breakpoint) {
          data.set(breakpointDecoration.breakpoint.getId(), {
            lineNumber: decorationRange.startLineNumber,
            column: breakpointDecoration.breakpoint.column ? decorationRange.startColumn : void 0
          });
        }
      }
    }
    try {
      this.k = true;
      await this.r.updateBreakpoints(model.uri, data, true);
    } finally {
      this.k = false;
    }
  }
  // breakpoint widget
  showBreakpointWidget(lineNumber, column, context) {
    this.f?.dispose();
    this.f = this.u.createInstance($X3b, this.q, lineNumber, column, context);
    this.f.show({ lineNumber, column: 1 });
    this.g.set(true);
  }
  closeBreakpointWidget() {
    if (this.f) {
      this.f.dispose();
      this.f = void 0;
      this.g.reset();
      this.q.focus();
    }
  }
  dispose() {
    this.f?.dispose();
    this.q.removeDecorations(this.m.map((bpd) => bpd.decorationId));
    $Xc(this.h);
  }
};
$Z3b = __decorate([
  __param(1, $0R),
  __param(2, $50),
  __param(3, $Pk),
  __param(4, $on),
  __param(5, $Yv),
  __param(6, $kl),
  __param(7, $ZI)
], $Z3b);
$I3b.registerGutterActionsGenerator(({ lineNumber, editor, accessor }, result) => {
  const model = editor.getModel();
  const debugService = accessor.get($0R);
  if (!model || !debugService.getAdapterManager().hasEnabledDebuggers() || !debugService.canSetBreakpointsIn(model)) {
    return;
  }
  const breakpointEditorContribution = editor.getContribution($4R);
  if (!breakpointEditorContribution) {
    return;
  }
  const actions = breakpointEditorContribution.getContextMenuActionsAtPosition(lineNumber, model);
  for (const action of actions) {
    result.push(action, "2_debug");
  }
});
var InlineBreakpointWidget = class {
  constructor(h3, j, cssClass, k, m, n, o) {
    this.h = h3;
    this.j = j;
    this.k = k;
    this.m = m;
    this.n = n;
    this.o = o;
    this.allowEditorOverflow = false;
    this.suppressMouseDown = true;
    this.g = [];
    this.f = this.h.getModel().getDecorationRange(j);
    this.g.push(this.h.onDidChangeModelDecorations(() => {
      const model = this.h.getModel();
      const range = model.getDecorationRange(this.j);
      if (this.f && !this.f.equalsRange(range)) {
        this.f = range;
        this.h.layoutContentWidget(this);
      }
    }));
    this.q(cssClass);
    this.h.addContentWidget(this);
    this.h.layoutContentWidget(this);
  }
  q(cssClass) {
    this.a = $130(".inline-breakpoint-widget");
    if (cssClass) {
      this.a.classList.add(...cssClass.split(" "));
    }
    this.g.push($_i(this.a, $7j.CLICK, async (e) => {
      switch (this.k?.enabled) {
        case void 0:
          await this.m.addBreakpoints(this.h.getModel().uri, [{ lineNumber: this.f.startLineNumber, column: this.f.startColumn }]);
          break;
        case true:
          await this.m.removeBreakpoints(this.k.getId());
          break;
        case false:
          this.m.enableOrDisableBreakpoints(true, this.k);
          break;
      }
    }));
    this.g.push($_i(this.a, $7j.CONTEXT_MENU, (e) => {
      const event = new $lf(getWindow(this.a), e);
      const actions = this.o();
      this.n.showContextMenu({
        getAnchor: () => event,
        getActions: () => actions,
        getActionsContext: () => this.k,
        onHide: () => $Yc(actions)
      });
    }));
    const updateSize = () => {
      const lineHeight = this.h.getOption(
        68
        /* EditorOption.lineHeight */
      );
      this.a.style.height = `${lineHeight}px`;
      this.a.style.width = `${Math.ceil(0.8 * lineHeight)}px`;
      this.a.style.marginLeft = `4px`;
    };
    updateSize();
    this.g.push(this.h.onDidChangeConfiguration((c) => {
      if (c.hasChanged(
        54
        /* EditorOption.fontSize */
      ) || c.hasChanged(
        68
        /* EditorOption.lineHeight */
      )) {
        updateSize();
      }
    }));
  }
  getId() {
    return $ps();
  }
  getDomNode() {
    return this.a;
  }
  getPosition() {
    if (!this.f) {
      return null;
    }
    this.a.classList.toggle("line-start", this.f.startColumn === 1);
    return {
      position: { lineNumber: this.f.startLineNumber, column: this.f.startColumn - 1 },
      preference: [
        0
        /* ContentWidgetPositionPreference.EXACT */
      ]
    };
  }
  dispose() {
    this.h.removeContentWidget(this);
    $Xc(this.g);
  }
};
__decorate([
  $0t
], InlineBreakpointWidget.prototype, "getId", null);
$ms((theme, collector) => {
  const scope = ".monaco-editor .glyph-margin-widgets, .monaco-workbench .debug-breakpoints, .monaco-workbench .disassembly-view, .monaco-editor .contentWidgets";
  const debugIconBreakpointColor = theme.getColor($13b);
  if (debugIconBreakpointColor) {
    collector.addRule(`${scope} {
			${$JFb.map((b) => `${ThemeIcon.asCSSSelector(b.regular)}`).join(",\n		")},
			${ThemeIcon.asCSSSelector($IFb)},
			${ThemeIcon.asCSSSelector($HFb)}:not([class*='codicon-debug-breakpoint']):not([class*='codicon-debug-stackframe']),
			${ThemeIcon.asCSSSelector($CFb.regular)}${ThemeIcon.asCSSSelector($LFb)}::after,
			${ThemeIcon.asCSSSelector($CFb.regular)}${ThemeIcon.asCSSSelector($KFb)}::after {
				color: ${debugIconBreakpointColor} !important;
			}
		}`);
    collector.addRule(`${scope} {
			${ThemeIcon.asCSSSelector($CFb.pending)} {
				color: ${debugIconBreakpointColor} !important;
				font-size: 12px !important;
			}
		}`);
  }
  const debugIconBreakpointDisabledColor = theme.getColor(debugIconBreakpointDisabledForeground);
  if (debugIconBreakpointDisabledColor) {
    collector.addRule(`${scope} {
			${$JFb.map((b) => ThemeIcon.asCSSSelector(b.disabled)).join(",\n		")} {
				color: ${debugIconBreakpointDisabledColor};
			}
		}`);
  }
  const debugIconBreakpointUnverifiedColor = theme.getColor(debugIconBreakpointUnverifiedForeground);
  if (debugIconBreakpointUnverifiedColor) {
    collector.addRule(`${scope} {
			${$JFb.map((b) => ThemeIcon.asCSSSelector(b.unverified)).join(",\n		")} {
				color: ${debugIconBreakpointUnverifiedColor};
			}
		}`);
  }
  const debugIconBreakpointCurrentStackframeForegroundColor = theme.getColor(debugIconBreakpointCurrentStackframeForeground);
  if (debugIconBreakpointCurrentStackframeForegroundColor) {
    collector.addRule(`
		.monaco-editor .debug-top-stack-frame-column {
			color: ${debugIconBreakpointCurrentStackframeForegroundColor} !important;
		}
		${scope} {
			${ThemeIcon.asCSSSelector($KFb)} {
				color: ${debugIconBreakpointCurrentStackframeForegroundColor} !important;
			}
		}
		`);
  }
  const debugIconBreakpointStackframeFocusedColor = theme.getColor(debugIconBreakpointStackframeForeground);
  if (debugIconBreakpointStackframeFocusedColor) {
    collector.addRule(`${scope} {
			${ThemeIcon.asCSSSelector($LFb)} {
				color: ${debugIconBreakpointStackframeFocusedColor} !important;
			}
		}`);
  }
});
var $13b = $5n("debugIcon.breakpointForeground", "#E51400", localize(5512, null));
var debugIconBreakpointDisabledForeground = $5n("debugIcon.breakpointDisabledForeground", "#848484", localize(5513, null));
var debugIconBreakpointUnverifiedForeground = $5n("debugIcon.breakpointUnverifiedForeground", "#848484", localize(5514, null));
var debugIconBreakpointCurrentStackframeForeground = $5n("debugIcon.breakpointCurrentStackframeForeground", { dark: "#FFCC00", light: "#BE8700", hcDark: "#FFCC00", hcLight: "#BE8700" }, localize(5515, null));
var debugIconBreakpointStackframeForeground = $5n("debugIcon.breakpointStackframeForeground", "#89D185", localize(5516, null));

// out-build/vs/workbench/contrib/debug/browser/callStackEditorContribution.js
var $K3b = $5n("editor.stackFrameHighlightBackground", { dark: "#ffff0033", light: "#ffff6673", hcDark: "#ffff0033", hcLight: "#ffff6673" }, localize(5600, null));
var $L3b = $5n("editor.focusedStackFrameHighlightBackground", { dark: "#7abd7a4d", light: "#cee7ce73", hcDark: "#7abd7a4d", hcLight: "#cee7ce73" }, localize(5601, null));
var stickiness = 1;
var TOP_STACK_FRAME_MARGIN = {
  description: "top-stack-frame-margin",
  glyphMarginClassName: ThemeIcon.asClassName($KFb),
  glyphMargin: { position: GlyphMarginLane.Right },
  zIndex: 9999,
  stickiness,
  overviewRuler: {
    position: OverviewRulerLane.Full,
    color: $hs($K3b)
  }
};
var FOCUSED_STACK_FRAME_MARGIN = {
  description: "focused-stack-frame-margin",
  glyphMarginClassName: ThemeIcon.asClassName($LFb),
  glyphMargin: { position: GlyphMarginLane.Right },
  zIndex: 9999,
  stickiness,
  overviewRuler: {
    position: OverviewRulerLane.Full,
    color: $hs($L3b)
  }
};
var $M3b = {
  description: "top-stack-frame-decoration",
  isWholeLine: true,
  className: "debug-top-stack-frame-line",
  stickiness
};
var $N3b = {
  description: "focused-stack-frame-decoration",
  isWholeLine: true,
  className: "debug-focused-stack-frame-line",
  stickiness
};
var $O3b = (noCharactersBefore) => ({
  description: "top-stack-frame-inline-decoration",
  before: {
    content: "\uEB8B",
    inlineClassName: noCharactersBefore ? "debug-top-stack-frame-column start-of-line" : "debug-top-stack-frame-column",
    inlineClassNameAffectsLetterSpacing: true
  }
});
function $P3b(stackFrame, isFocusedSession, noCharactersBefore) {
  const result = [];
  const columnUntilEOLRange = new $9C(
    stackFrame.range.startLineNumber,
    stackFrame.range.startColumn,
    stackFrame.range.startLineNumber,
    1073741824
    /* Constants.MAX_SAFE_SMALL_INTEGER */
  );
  const range = new $9C(stackFrame.range.startLineNumber, stackFrame.range.startColumn, stackFrame.range.startLineNumber, stackFrame.range.startColumn + 1);
  const topStackFrame = stackFrame.thread.getTopStackFrame();
  if (stackFrame.getId() === topStackFrame?.getId()) {
    if (isFocusedSession) {
      result.push({
        options: TOP_STACK_FRAME_MARGIN,
        range
      });
    }
    result.push({
      options: $M3b,
      range: columnUntilEOLRange
    });
    if (stackFrame.range.startColumn > 1) {
      result.push({
        options: $O3b(noCharactersBefore),
        range: columnUntilEOLRange
      });
    }
  } else {
    if (isFocusedSession) {
      result.push({
        options: FOCUSED_STACK_FRAME_MARGIN,
        range
      });
    }
    result.push({
      options: $N3b,
      range: columnUntilEOLRange
    });
  }
  return result;
}
var $Q3b = class $Q3b2 extends $3c {
  constructor(b, c, f, g) {
    super();
    this.b = b;
    this.c = c;
    this.f = f;
    this.g = g;
    this.a = this.b.createDecorationsCollection();
    const setDecorations = () => this.a.set(this.h());
    this.B(Event2.any(this.c.getViewModel().onDidFocusStackFrame, this.c.getModel().onDidChangeCallStack)(() => {
      setDecorations();
    }));
    this.B(this.b.onDidChangeModel((e) => {
      if (e.newModelUrl) {
        setDecorations();
      }
    }));
    setDecorations();
  }
  h() {
    const editor = this.b;
    if (!editor.hasModel()) {
      return [];
    }
    const focusedStackFrame = this.c.getViewModel().focusedStackFrame;
    const decorations = [];
    this.c.getModel().getSessions().forEach((s) => {
      const isSessionFocused = s === focusedStackFrame?.thread.session;
      s.getAllThreads().forEach((t) => {
        if (t.stopped) {
          const callStack = t.getCallStack();
          const stackFrames = [];
          if (callStack.length > 0) {
            if (focusedStackFrame && !focusedStackFrame.equals(callStack[0])) {
              stackFrames.push(focusedStackFrame);
            }
            stackFrames.push(callStack[0]);
          }
          stackFrames.forEach((candidateStackFrame) => {
            if (candidateStackFrame && this.f.extUri.isEqual(candidateStackFrame.source.uri, editor.getModel()?.uri)) {
              if (candidateStackFrame.range.startLineNumber > editor.getModel()?.getLineCount() || candidateStackFrame.range.startLineNumber < 1) {
                this.g.warn(`CallStackEditorContribution: invalid stack frame line number: ${candidateStackFrame.range.startLineNumber}`);
                return;
              }
              const noCharactersBefore = editor.getModel().getLineFirstNonWhitespaceColumn(candidateStackFrame.range.startLineNumber) >= candidateStackFrame.range.startColumn;
              decorations.push(...$P3b(candidateStackFrame, isSessionFocused, noCharactersBefore));
            }
          });
        }
      });
    });
    return $Rb(decorations, (d) => `${d.options.className} ${d.options.glyphMarginClassName} ${d.range.startLineNumber} ${d.range.startColumn}`);
  }
  dispose() {
    super.dispose();
    this.a.clear();
  }
};
$Q3b = __decorate([
  __param(1, $0R),
  __param(2, $vl),
  __param(3, $wn)
], $Q3b);

// out-build/vs/workbench/contrib/notebook/browser/contrib/debug/notebookDebugDecorations.js
var $23b = class $23b2 extends $3c {
  static {
    this.id = "workbench.notebook.debug.pausedCellDecorations";
  }
  constructor(f, g, h3) {
    super();
    this.f = f;
    this.g = g;
    this.h = h3;
    this.a = [];
    this.b = [];
    this.c = [];
    const delayer4 = this.B(new $Sh(200));
    this.B(g.getModel().onDidChangeCallStack(() => this.j()));
    this.B(g.getViewModel().onDidFocusStackFrame(() => this.j()));
    this.B(h3.onDidChangeExecution((e) => {
      if (e.type === NotebookExecutionType.cell && this.f.textModel && e.affectsNotebook(this.f.textModel.uri)) {
        delayer4.trigger(() => this.j());
      }
    }));
  }
  j() {
    const exes = this.f.textModel ? this.h.getCellExecutionsByHandleForNotebook(this.f.textModel.uri) : void 0;
    const topFrameCellsAndRanges = [];
    let focusedFrameCellAndRange = void 0;
    const getNotebookCellAndRange = (sf) => {
      const parsed = CellUri.parse(sf.source.uri);
      if (parsed && parsed.notebook.toString() === this.f.textModel?.uri.toString()) {
        return { handle: parsed.handle, range: sf.range };
      }
      return void 0;
    };
    for (const session of this.g.getModel().getSessions()) {
      for (const thread of session.getAllThreads()) {
        const topFrame = thread.getTopStackFrame();
        if (topFrame) {
          const notebookCellAndRange = getNotebookCellAndRange(topFrame);
          if (notebookCellAndRange) {
            topFrameCellsAndRanges.push(notebookCellAndRange);
            exes?.delete(notebookCellAndRange.handle);
          }
        }
      }
    }
    const focusedFrame = this.g.getViewModel().focusedStackFrame;
    if (focusedFrame && focusedFrame.thread.stopped) {
      const thisFocusedFrameCellAndRange = getNotebookCellAndRange(focusedFrame);
      if (thisFocusedFrameCellAndRange && !topFrameCellsAndRanges.some((topFrame) => topFrame.handle === thisFocusedFrameCellAndRange?.handle && $9C.equalsRange(topFrame.range, thisFocusedFrameCellAndRange?.range))) {
        focusedFrameCellAndRange = thisFocusedFrameCellAndRange;
        exes?.delete(focusedFrameCellAndRange.handle);
      }
    }
    this.m(topFrameCellsAndRanges);
    this.n(focusedFrameCellAndRange);
    const exeHandles = exes ? Array.from(exes.entries()).filter(([_, exe]) => exe.state === NotebookCellExecutionState.Executing).map(([handle2]) => handle2) : [];
    this.r(exeHandles);
  }
  m(handlesAndRanges) {
    const newDecorations = handlesAndRanges.map(({ handle: handle2, range }) => {
      const options3 = {
        overviewRuler: {
          color: $K3b,
          includeOutput: false,
          modelRanges: [range],
          position: NotebookOverviewRulerLane.Full
        }
      };
      return { handle: handle2, options: options3 };
    });
    this.a = this.f.deltaCellDecorations(this.a, newDecorations);
  }
  n(focusedFrameCellAndRange) {
    let newDecorations = [];
    if (focusedFrameCellAndRange) {
      const options3 = {
        overviewRuler: {
          color: $L3b,
          includeOutput: false,
          modelRanges: [focusedFrameCellAndRange.range],
          position: NotebookOverviewRulerLane.Full
        }
      };
      newDecorations = [{ handle: focusedFrameCellAndRange.handle, options: options3 }];
    }
    this.b = this.f.deltaCellDecorations(this.b, newDecorations);
  }
  r(handles) {
    const newDecorations = handles.map((handle2) => {
      const options3 = {
        overviewRuler: {
          color: $eMb,
          includeOutput: false,
          modelRanges: [new $9C(0, 0, 0, 0)],
          position: NotebookOverviewRulerLane.Left
        }
      };
      return { handle: handle2, options: options3 };
    });
    this.c = this.f.deltaCellDecorations(this.c, newDecorations);
  }
};
$23b = __decorate([
  __param(1, $0R),
  __param(2, $wL)
], $23b);
$iGb($23b.id, $23b);
var $33b = class $33b2 extends $3c {
  static {
    this.id = "workbench.notebook.debug.notebookBreakpointDecorations";
  }
  constructor(b, c, f) {
    super();
    this.b = b;
    this.c = c;
    this.f = f;
    this.a = [];
    this.B(c.getModel().onDidChangeBreakpoints(() => this.g()));
    this.B(f.onDidChangeConfiguration((e) => e.affectsConfiguration("debug.showBreakpointsInOverviewRuler") && this.g()));
  }
  g() {
    const enabled = this.f.getValue("debug.showBreakpointsInOverviewRuler");
    const newDecorations = enabled ? this.c.getModel().getBreakpoints().map((breakpoint) => {
      const parsed = CellUri.parse(breakpoint.uri);
      if (!parsed || parsed.notebook.toString() !== this.b.textModel.uri.toString()) {
        return null;
      }
      const options3 = {
        overviewRuler: {
          color: $13b,
          includeOutput: false,
          modelRanges: [new $9C(breakpoint.lineNumber, 0, breakpoint.lineNumber, 0)],
          position: NotebookOverviewRulerLane.Left
        }
      };
      return { handle: parsed.handle, options: options3 };
    }).filter((x) => !!x) : [];
    this.a = this.b.deltaCellDecorations(this.a, newDecorations);
  }
};
$33b = __decorate([
  __param(1, $0R),
  __param(2, $kl)
], $33b);
$iGb($33b.id, $33b);

// out-build/vs/workbench/contrib/notebook/browser/contrib/execute/executionEditorProgress.js
var $43b = class $43b2 extends $3c {
  static {
    this.id = "workbench.notebook.executionEditorProgress";
  }
  constructor(b, c, f) {
    super();
    this.b = b;
    this.c = c;
    this.f = f;
    this.a = this.B(new $4c());
    this.B(b.onDidScroll(() => this.g()));
    this.B(c.onDidChangeExecution((e) => {
      if (e.notebook.toString() !== this.b.textModel?.uri.toString()) {
        return;
      }
      this.g();
    }));
    this.B(b.onDidChangeModel(() => this.g()));
  }
  g() {
    if (!this.b.hasModel()) {
      return;
    }
    const cellExecutions = this.c.getCellExecutionsForNotebook(this.b.textModel?.uri).filter((exe) => exe.state === NotebookCellExecutionState.Executing);
    const notebookExecution = this.c.getExecution(this.b.textModel?.uri);
    const executionIsVisible = (exe) => {
      for (const range of this.b.visibleRanges) {
        for (const cell of this.b.getCellsInRange(range)) {
          if (cell.handle === exe.cellHandle) {
            const top2 = this.b.getAbsoluteTopOfElement(cell);
            if (this.b.scrollTop < top2 + 5) {
              return true;
            }
          }
        }
      }
      return false;
    };
    const hasAnyExecution = cellExecutions.length || notebookExecution;
    if (hasAnyExecution && !this.a.value) {
      this.a.value = this.f.markActive();
    } else if (!hasAnyExecution && this.a.value) {
      this.a.clear();
    }
    const shouldShowEditorProgressbarForCellExecutions = cellExecutions.length && !cellExecutions.some(executionIsVisible) && !cellExecutions.some((e) => e.isPaused);
    const showEditorProgressBar = !!notebookExecution || shouldShowEditorProgressbarForCellExecutions;
    if (showEditorProgressBar) {
      this.b.showProgress();
    } else {
      this.b.hideProgress();
    }
  }
};
__decorate([
  $_t(100)
], $43b.prototype, "g", null);
$43b = __decorate([
  __param(1, $wL),
  __param(2, $QRb)
], $43b);
$iGb($43b.id, $43b);

// out-build/vs/workbench/contrib/notebook/browser/contrib/kernelDetection/notebookKernelDetection.js
var NotebookKernelDetection = class NotebookKernelDetection2 extends $3c {
  constructor(c, f, g) {
    super();
    this.c = c;
    this.f = f;
    this.g = g;
    this.a = /* @__PURE__ */ new Map();
    this.b = this.B(new $2c());
    this.h();
  }
  h() {
    this.b.clear();
    this.b.add(this.f.onWillActivateByEvent((e) => {
      if (e.event.startsWith("onNotebook:")) {
        if (this.f.activationEventIsDone(e.event)) {
          return;
        }
        const notebookType = e.event.substring("onNotebook:".length);
        if (notebookType === "*") {
          return;
        }
        let shouldStartDetection = false;
        const extensionStatus = this.f.getExtensionsStatus();
        this.f.extensions.forEach((extension) => {
          if (extensionStatus[extension.identifier.value].activationTimes) {
            return;
          }
          if (extension.activationEvents?.includes(e.event)) {
            shouldStartDetection = true;
          }
        });
        if (shouldStartDetection && !this.a.has(notebookType)) {
          this.g.debug("KernelDetection", `start extension activation for ${notebookType}`);
          const task = this.c.registerNotebookKernelDetectionTask({
            notebookType
          });
          this.a.set(notebookType, task);
        }
      }
    }));
    let timer = null;
    this.b.add(this.f.onDidChangeExtensionsStatus(() => {
      if (timer) {
        clearTimeout(timer);
      }
      timer = setTimeout(() => {
        const taskToDelete = [];
        for (const [notebookType, task] of this.a) {
          if (this.f.activationEventIsDone(`onNotebook:${notebookType}`)) {
            this.g.debug("KernelDetection", `finish extension activation for ${notebookType}`);
            taskToDelete.push(notebookType);
            task.dispose();
          }
        }
        taskToDelete.forEach((notebookType) => {
          this.a.delete(notebookType);
        });
      });
    }));
    this.b.add({
      dispose: () => {
        if (timer) {
          clearTimeout(timer);
        }
      }
    });
  }
};
NotebookKernelDetection = __decorate([
  __param(0, $CL),
  __param(1, $wN),
  __param(2, $qFb)
], NotebookKernelDetection);
$Wn.as(Extensions2.Workbench).registerWorkbenchContribution(
  NotebookKernelDetection,
  3
  /* LifecyclePhase.Restored */
);

// out-build/vs/workbench/contrib/notebook/browser/contrib/cellDiagnostics/cellDiagnosticEditorContrib.js
var $53b_1;
var $53b = class $53b2 extends $3c {
  static {
    $53b_1 = this;
  }
  static {
    this.ID = "workbench.notebook.cellDiagnostics";
  }
  constructor(f, g, h3, j, m) {
    super();
    this.f = f;
    this.g = g;
    this.h = h3;
    this.j = j;
    this.m = m;
    this.a = false;
    this.b = false;
    this.c = /* @__PURE__ */ new Map();
    this.n();
    this.B(j.onDidChangeAgents(() => this.n()));
    this.B(m.onDidChangeConfiguration((e) => {
      if (e.affectsConfiguration($rM.cellFailureDiagnostics)) {
        this.n();
      }
    }));
  }
  n() {
    const settingEnabled = this.m.getValue($rM.cellFailureDiagnostics);
    if (this.a && (!settingEnabled || Iterable.isEmpty(this.j.getAgents()))) {
      this.a = false;
      this.s();
    } else if (!this.a && settingEnabled && !Iterable.isEmpty(this.j.getAgents())) {
      this.a = true;
      if (!this.b) {
        this.b = true;
        this.B(Event2.accumulate(this.g.onDidChangeExecution, 200)((e) => this.r(e)));
      }
    }
  }
  r(changes) {
    if (!this.a) {
      return;
    }
    const handled = /* @__PURE__ */ new Set();
    for (const e of changes.reverse()) {
      const notebookUri = this.f.textModel?.uri;
      if (e.type === NotebookExecutionType.cell && notebookUri && e.affectsNotebook(notebookUri) && !handled.has(e.cellHandle)) {
        handled.add(e.cellHandle);
        if (!!e.changed) {
          this.clear(e.cellHandle);
        } else {
          this.t(e.cellHandle);
        }
      }
    }
  }
  s() {
    for (const handle2 of this.c.keys()) {
      this.clear(handle2);
    }
  }
  clear(cellHandle) {
    const disposables = this.c.get(cellHandle);
    if (disposables) {
      for (const disposable of disposables) {
        disposable.dispose();
      }
      this.c.delete(cellHandle);
    }
  }
  t(cellHandle) {
    if (this.c.has(cellHandle)) {
      return;
    }
    const cell = this.f.getCellByHandle(cellHandle);
    if (!cell || cell.cellKind !== CellKind.Code) {
      return;
    }
    const metadata = cell.model.internalMetadata;
    if (cell instanceof $XIb && !metadata.lastRunSuccess && metadata?.error?.location) {
      const disposables = [];
      const errorLabel = metadata.error.name ? `${metadata.error.name}: ${metadata.error.message}` : metadata.error.message;
      const marker = this.u(errorLabel, metadata.error.location);
      this.h.changeOne($53b_1.ID, cell.uri, [marker]);
      disposables.push($1c(() => this.h.changeOne($53b_1.ID, cell.uri, [])));
      cell.executionErrorDiagnostic.set(metadata.error, void 0);
      disposables.push($1c(() => cell.executionErrorDiagnostic.set(void 0, void 0)));
      disposables.push(cell.model.onDidChangeOutputs(() => {
        if (cell.model.outputs.length === 0) {
          this.clear(cellHandle);
        }
      }));
      disposables.push(cell.model.onDidChangeContent(() => {
        this.clear(cellHandle);
      }));
      this.c.set(cellHandle, disposables);
    }
  }
  u(message, location3) {
    return {
      severity: 8,
      message,
      startLineNumber: location3.startLineNumber + 1,
      startColumn: location3.startColumn + 1,
      endLineNumber: location3.endLineNumber + 1,
      endColumn: location3.endColumn + 1,
      source: "Cell Execution Error"
    };
  }
  dispose() {
    super.dispose();
    this.s();
  }
};
$53b = $53b_1 = __decorate([
  __param(1, $wL),
  __param(2, $DE),
  __param(3, $ZO),
  __param(4, $kl)
], $53b);
$iGb($53b.ID, $53b);

// out-build/vs/workbench/contrib/notebook/browser/contrib/cellDiagnostics/cellDiagnosticsActions.js
var $63b = "notebook.cell.openFailureActions";
var $73b = "notebook.cell.chat.fixError";
var $83b = "notebook.cell.chat.explainError";
$hJ(class extends $HIb {
  constructor() {
    super({
      id: $63b,
      title: localize2(8096, "Show Cell Failure Actions"),
      precondition: $7m.and($_Ab, $mBb, $aBb.toNegated()),
      f1: true,
      keybinding: {
        when: $7m.and($_Ab, $mBb, $aBb.toNegated()),
        primary: 2048 | 89,
        weight: 200
        /* KeybindingWeight.WorkbenchContrib */
      }
    });
  }
  async runWithContext(accessor, context) {
    if (context.cell instanceof $XIb) {
      const error = context.cell.executionErrorDiagnostic.get();
      if (error?.location) {
        const location3 = $9C.lift({
          startLineNumber: error.location.startLineNumber + 1,
          startColumn: error.location.startColumn + 1,
          endLineNumber: error.location.endLineNumber + 1,
          endColumn: error.location.endColumn + 1
        });
        context.notebookEditor.setCellEditorSelection(context.cell, $9C.lift(location3));
        const editor = $EIb(context, context.cell);
        if (editor) {
          const controller = $fbb.get(editor);
          controller?.manualTriggerAtCurrentPosition(localize(8095, null), CodeActionTriggerSource.Default, { include: $pab.QuickFix });
        }
      }
    }
  }
});
$hJ(class extends $HIb {
  constructor() {
    super({
      id: $73b,
      title: localize2(8097, "Fix Cell Error"),
      precondition: $7m.and($_Ab, $mBb, $aBb.toNegated()),
      f1: true
    });
  }
  async runWithContext(accessor, context) {
    if (context.cell instanceof $XIb) {
      const error = context.cell.executionErrorDiagnostic.get();
      if (error?.location) {
        const location3 = $9C.lift({
          startLineNumber: error.location.startLineNumber + 1,
          startColumn: error.location.startColumn + 1,
          endLineNumber: error.location.endLineNumber + 1,
          endColumn: error.location.endColumn + 1
        });
        context.notebookEditor.setCellEditorSelection(context.cell, $9C.lift(location3));
        const editor = $EIb(context, context.cell);
        if (editor) {
          const controller = $cHb.get(editor);
          const message = error.name ? `${error.name}: ${error.message}` : error.message;
          if (controller) {
            await controller.run({ message: "/fix " + message, initialRange: location3, autoSend: true });
          }
        }
      }
    }
  }
});
$hJ(class extends $HIb {
  constructor() {
    super({
      id: $83b,
      title: localize2(8098, "Explain Cell Error"),
      precondition: $7m.and($_Ab, $mBb, $aBb.toNegated()),
      f1: true
    });
  }
  async runWithContext(accessor, context) {
    if (context.cell instanceof $XIb) {
      const error = context.cell.executionErrorDiagnostic.get();
      if (error?.message) {
        const viewsService = accessor.get($uob);
        const chatWidget = await $3Nb(viewsService);
        const message = error.name ? `${error.name}: ${error.message}` : error.message;
        chatWidget?.acceptInput("@workspace /explain " + message);
      }
    }
  }
});

// out-build/vs/workbench/contrib/notebook/browser/contrib/cellDiagnostics/diagnosticCellStatusBarContrib.js
var $93b = class $93b2 extends $3c {
  static {
    this.id = "workbench.notebook.statusBar.diagtnostic";
  }
  constructor(notebookEditor, instantiationService) {
    super();
    this.B(new $D3b(notebookEditor, (vm, cell) => cell instanceof $XIb ? instantiationService.createInstance(DiagnosticCellStatusBarItem, vm, cell) : $3c.None));
  }
};
$93b = __decorate([
  __param(1, $Pk)
], $93b);
$iGb($93b.id, $93b);
var DiagnosticCellStatusBarItem = class DiagnosticCellStatusBarItem2 extends $3c {
  constructor(b, c, f, g) {
    super();
    this.b = b;
    this.c = c;
    this.f = f;
    this.g = g;
    this.a = [];
    this.B($td((reader) => this.h(reader.readObservable(c.executionErrorDiagnostic))));
  }
  async h(error) {
    let item;
    if (error?.location && !Iterable.isEmpty(this.g.getAgents())) {
      const keybinding = this.f.lookupKeybinding($63b)?.getLabel();
      const tooltip = localize(8099, null, `(${keybinding})`);
      item = {
        text: `$(sparkle)`,
        tooltip,
        alignment: 1,
        command: $63b,
        priority: Number.MAX_SAFE_INTEGER - 1
      };
    }
    const items = item ? [item] : [];
    this.a = this.b.deltaCellStatusBarItems(this.a, [{ handle: this.c.handle, items }]);
  }
  dispose() {
    super.dispose();
    this.b.deltaCellStatusBarItems(this.a, [{ handle: this.c.handle, items: [] }]);
  }
};
DiagnosticCellStatusBarItem = __decorate([
  __param(2, $Ty),
  __param(3, $ZO)
], DiagnosticCellStatusBarItem);

// out-build/vs/workbench/contrib/notebook/browser/contrib/multicursor/notebookSelectionHighlight.js
var NotebookSelectionHighlighter = class NotebookSelectionHighlighter2 extends $3c {
  static {
    this.id = "notebook.selectionHighlighter";
  }
  // right now this lets us mimic the more performant cache implementation of the text editor (doesn't need to be a delayer)
  // todo: in the future, implement caching and change to a 250ms delay upon recompute
  // private readonly runDelayer: Delayer<void> = this._register(new Delayer<void>(0));
  constructor(g, h3) {
    super();
    this.g = g;
    this.h = h3;
    this.a = false;
    this.b = /* @__PURE__ */ new Map();
    this.f = new $2c();
    this.a = this.h.getValue("editor.selectionHighlight");
    this.B(this.h.onDidChangeConfiguration((e) => {
      if (e.affectsConfiguration("editor.selectionHighlight")) {
        this.a = this.h.getValue("editor.selectionHighlight");
      }
    }));
    this.B(this.g.onDidChangeActiveCell(async () => {
      if (!this.a) {
        return;
      }
      this.c = this.g.activeCellAndCodeEditor;
      if (!this.c) {
        return;
      }
      const activeCell = this.g.getActiveCell();
      if (!activeCell) {
        return;
      }
      if (!activeCell.editorAttached) {
        await Event2.toPromise(activeCell.onDidChangeEditorAttachState);
      }
      this.r();
      this.f.clear();
      this.f.add(this.c[1].onDidChangeCursorPosition((e) => {
        if (e.reason !== 3) {
          return;
        }
        if (!this.c) {
          return;
        }
        if (this.g.hasModel()) {
          this.r();
          this.j(this.g);
        }
      }));
      if (this.g.getEditorViewState().editorFocused && this.g.hasModel()) {
        this.j(this.g);
      }
    }));
  }
  j(editor) {
    if (!this.c || !this.a) {
      return;
    }
    const textModel = this.c[0].textModel;
    if (!textModel || textModel.isTooLargeForTokenization()) {
      return;
    }
    const s = this.c[0].getSelections()[0];
    if (s.startLineNumber !== s.endLineNumber || s.isEmpty()) {
      return;
    }
    const searchText = this.t(s, textModel);
    if (!searchText) {
      return;
    }
    const results = editor.textModel.findMatches(searchText, false, true, null);
    for (const res of results) {
      const cell = editor.getCellByHandle(res.cell.handle);
      if (!cell) {
        continue;
      }
      this.n(cell, res.matches);
    }
  }
  n(cell, matches) {
    const selections = matches.map((m) => {
      return $_D.fromRange(
        m.range,
        0
        /* SelectionDirection.LTR */
      );
    });
    const newDecorations = [];
    selections?.map((selection) => {
      const isEmpty = selection.isEmpty();
      if (!isEmpty) {
        newDecorations.push({
          range: selection,
          options: {
            description: "",
            className: ".nb-selection-highlight"
          }
        });
      }
    });
    const oldDecorations = this.b.get(cell) ?? [];
    this.b.set(cell, cell.deltaModelDecorations(oldDecorations, newDecorations));
  }
  r() {
    this.b.forEach((_, cell) => {
      const cellDecorations = this.b.get(cell) ?? [];
      if (cellDecorations) {
        cell.deltaModelDecorations(cellDecorations, []);
        this.b.delete(cell);
      }
    });
  }
  t(selection, model) {
    return model.getValueInRange(selection).replace(/\r\n/g, "\n");
  }
  dispose() {
    super.dispose();
    this.f.dispose();
  }
};
NotebookSelectionHighlighter = __decorate([
  __param(1, $kl)
], NotebookSelectionHighlighter);
$iGb(NotebookSelectionHighlighter.id, NotebookSelectionHighlighter);

// out-build/vs/editor/browser/widget/multiDiffEditor/colors.js
var $1Eb = $5n("multiDiffEditor.headerBackground", { dark: "#262626", light: "tab.inactiveBackground", hcDark: "tab.inactiveBackground", hcLight: "tab.inactiveBackground" }, localize(253, null));
var $2Eb = $5n("multiDiffEditor.background", $Ko, localize(254, null));
var $3Eb = $5n("multiDiffEditor.border", { dark: "sideBarSectionHeader.border", light: "#cccccc", hcDark: "sideBarSectionHeader.border", hcLight: "#cccccc" }, localize(255, null));

// out-build/vs/editor/browser/widget/multiDiffEditor/diffEditorItemTemplate.js
var $7Eb = class {
  constructor(viewModel, deltaScrollVertical) {
    this.viewModel = viewModel;
    this.deltaScrollVertical = deltaScrollVertical;
  }
  getId() {
    return this.viewModel;
  }
};
var $8Eb = class $8Eb2 extends $3c {
  constructor(C, D, F, G, _parentContextKeyService) {
    super();
    this.C = C;
    this.D = D;
    this.F = F;
    this.G = G;
    this.a = $he(this, void 0);
    this.b = $2d(this, (reader) => this.a.read(reader)?.collapsed.read(reader));
    this.c = $he(this, 500);
    this.contentHeight = $2d(this, (reader) => {
      const h3 = this.b.read(reader) ? 0 : this.c.read(reader);
      return h3 + this.y;
    });
    this.f = $he(this, 0);
    this.j = $he(this, 0);
    this.m = $he(this, 0);
    this.n = $he(this, 0);
    this.maxScroll = $2d(this, (reader) => {
      const scroll1 = this.f.read(reader) - this.j.read(reader);
      const scroll2 = this.m.read(reader) - this.n.read(reader);
      if (scroll1 > scroll2) {
        return { maxScroll: scroll1, width: this.j.read(reader) };
      } else {
        return { maxScroll: scroll2, width: this.n.read(reader) };
      }
    });
    this.r = h("div.multiDiffEntry", [
      h("div.header@header", [
        h("div.header-content", [
          h("div.collapse-button@collapseButton"),
          h("div.file-path", [
            h("div.title.modified.show-file-icons@primaryPath", []),
            h("div.status.deleted@status", ["R"]),
            h("div.title.original.show-file-icons@secondaryPath", [])
          ]),
          h("div.actions@actions")
        ])
      ]),
      h("div.editorParent", [
        h("div.editorContainer@editor")
      ])
    ]);
    this.editor = this.B(this.G.createInstance($c_, this.r.editor, {
      overflowWidgetsDomNode: this.D
    }, {}));
    this.s = $79(this.editor.getModifiedEditor()).isFocused;
    this.t = $79(this.editor.getOriginalEditor()).isFocused;
    this.isFocused = $2d(this, (reader) => this.s.read(reader) || this.t.read(reader));
    this.u = this.F.createResourceLabel ? this.B(this.F.createResourceLabel(this.r.primaryPath)) : void 0;
    this.w = this.F.createResourceLabel ? this.B(this.F.createResourceLabel(this.r.secondaryPath)) : void 0;
    this.H = this.B(new $2c());
    this.J = 40;
    this.L = -1;
    this.M = false;
    const btn = new $k2(this.r.collapseButton, {});
    this.B($td((reader) => {
      btn.element.className = "";
      btn.icon = this.b.read(reader) ? $6l.chevronRight : $6l.chevronDown;
    }));
    this.B(btn.onDidClick(() => {
      this.a.get()?.collapsed.set(!this.b.get(), void 0);
    }));
    this.B($td((reader) => {
      this.r.editor.style.display = this.b.read(reader) ? "none" : "block";
    }));
    this.B(this.editor.getModifiedEditor().onDidLayoutChange((e) => {
      const width2 = this.editor.getModifiedEditor().getLayoutInfo().contentWidth;
      this.j.set(width2, void 0);
    }));
    this.B(this.editor.getOriginalEditor().onDidLayoutChange((e) => {
      const width2 = this.editor.getOriginalEditor().getLayoutInfo().contentWidth;
      this.n.set(width2, void 0);
    }));
    this.B(this.editor.onDidContentSizeChange((e) => {
      $de((tx) => {
        this.c.set(e.contentHeight, tx);
        this.f.set(this.editor.getModifiedEditor().getContentWidth(), tx);
        this.m.set(this.editor.getOriginalEditor().getContentWidth(), tx);
      });
    }));
    this.B(this.editor.getOriginalEditor().onDidScrollChange((e) => {
      if (this.M) {
        return;
      }
      if (!e.scrollTopChanged || !this.I) {
        return;
      }
      const delta = e.scrollTop - this.L;
      this.I.deltaScrollVertical(delta);
    }));
    this.B($td((reader) => {
      const isActive2 = this.a.read(reader)?.isActive.read(reader);
      this.r.root.classList.toggle("active", isActive2);
    }));
    this.C.appendChild(this.r.root);
    this.y = this.J;
    this.z = this.B(_parentContextKeyService.createScoped(this.r.actions));
    const instantiationService = this.B(this.G.createChild(new $Ok([$on, this.z])));
    this.B(instantiationService.createInstance($4$, this.r.actions, $bJ.MultiDiffEditorFileToolbar, {
      actionRunner: this.B(new $9$(() => this.a.get()?.modifiedUri)),
      menuOptions: {
        shouldForwardArgs: true
      },
      toolbarOptions: { primaryGroup: (g) => g.startsWith("navigation") },
      actionViewItemProvider: (action, options3) => $X$(instantiationService, action, options3)
    }));
  }
  setScrollLeft(left) {
    if (this.f.get() - this.j.get() > this.m.get() - this.n.get()) {
      this.editor.getModifiedEditor().setScrollLeft(left);
    } else {
      this.editor.getOriginalEditor().setScrollLeft(left);
    }
  }
  setData(data) {
    this.I = data;
    function updateOptions(options3) {
      return {
        ...options3,
        scrollBeyondLastLine: false,
        hideUnchangedRegions: {
          enabled: true
        },
        scrollbar: {
          vertical: "hidden",
          horizontal: "hidden",
          handleMouseWheel: false,
          useShadows: false
        },
        renderOverviewRuler: false,
        fixedOverflowWidgets: true,
        overviewRulerBorder: false
      };
    }
    if (!data) {
      $de((tx) => {
        this.a.set(void 0, tx);
        this.editor.setDiffModel(null, tx);
        this.H.clear();
      });
      return;
    }
    const value = data.viewModel.documentDiffItem;
    $de((tx) => {
      this.u?.setUri(data.viewModel.modifiedUri ?? data.viewModel.originalUri, { strikethrough: data.viewModel.modifiedUri === void 0 });
      let isRenamed = false;
      let isDeleted = false;
      let isAdded = false;
      let flag = "";
      if (data.viewModel.modifiedUri && data.viewModel.originalUri && data.viewModel.modifiedUri.path !== data.viewModel.originalUri.path) {
        flag = "R";
        isRenamed = true;
      } else if (!data.viewModel.modifiedUri) {
        flag = "D";
        isDeleted = true;
      } else if (!data.viewModel.originalUri) {
        flag = "A";
        isAdded = true;
      }
      this.r.status.classList.toggle("renamed", isRenamed);
      this.r.status.classList.toggle("deleted", isDeleted);
      this.r.status.classList.toggle("added", isAdded);
      this.r.status.innerText = flag;
      this.w?.setUri(isRenamed ? data.viewModel.originalUri : void 0, { strikethrough: true });
      this.H.clear();
      this.a.set(data.viewModel, tx);
      this.editor.setDiffModel(data.viewModel.diffEditorViewModelRef, tx);
      this.editor.updateOptions(updateOptions(value.options ?? {}));
    });
    if (value.onOptionsDidChange) {
      this.H.add(value.onOptionsDidChange(() => {
        this.editor.updateOptions(updateOptions(value.options ?? {}));
      }));
    }
    data.viewModel.isAlive.recomputeInitiallyAndOnChange(this.H, (value2) => {
      if (!value2) {
        this.setData(void 0);
      }
    });
    if (data.viewModel.documentDiffItem.contextKeys) {
      for (const [key2, value2] of Object.entries(data.viewModel.documentDiffItem.contextKeys)) {
        this.z.createKey(key2, value2);
      }
    }
  }
  render(verticalRange, width2, editorScroll, viewPort) {
    this.r.root.style.visibility = "visible";
    this.r.root.style.top = `${verticalRange.start}px`;
    this.r.root.style.height = `${verticalRange.length}px`;
    this.r.root.style.width = `${width2}px`;
    this.r.root.style.position = "absolute";
    const maxDelta = verticalRange.length - this.J;
    const delta = Math.max(0, Math.min(viewPort.start - verticalRange.start, maxDelta));
    this.r.header.style.transform = `translateY(${delta}px)`;
    $de((tx) => {
      this.editor.layout({
        width: width2 - 2 * 8 - 2 * 1,
        height: verticalRange.length - this.y
      });
    });
    try {
      this.M = true;
      this.L = editorScroll;
      this.editor.getOriginalEditor().setScrollTop(editorScroll);
    } finally {
      this.M = false;
    }
    this.r.header.classList.toggle("shadow", delta > 0 || editorScroll > 0);
    this.r.header.classList.toggle("collapsed", delta === maxDelta);
  }
  hide() {
    this.r.root.style.top = `-100000px`;
    this.r.root.style.visibility = "hidden";
  }
};
$8Eb = __decorate([
  __param(3, $Pk),
  __param(4, $on)
], $8Eb);

// out-build/vs/editor/browser/widget/multiDiffEditor/objectPool.js
var $6Eb = class {
  constructor(d) {
    this.d = d;
    this.a = /* @__PURE__ */ new Set();
    this.b = /* @__PURE__ */ new Set();
    this.c = /* @__PURE__ */ new Map();
  }
  getUnusedObj(data) {
    let obj;
    if (this.a.size === 0) {
      obj = this.d(data);
      this.c.set(obj, data);
    } else {
      const values = [...this.a.values()];
      obj = values.find((obj2) => this.c.get(obj2).getId() === data.getId()) ?? values[0];
      this.a.delete(obj);
      this.c.set(obj, data);
      obj.setData(data);
    }
    this.b.add(obj);
    return {
      object: obj,
      dispose: () => {
        this.b.delete(obj);
        if (this.a.size > 5) {
          obj.dispose();
        } else {
          this.a.add(obj);
        }
      }
    };
  }
  dispose() {
    for (const obj of this.b) {
      obj.dispose();
    }
    for (const obj of this.a) {
      obj.dispose();
    }
    this.b.clear();
    this.a.clear();
  }
};

// out-build/vs/editor/browser/widget/multiDiffEditor/multiDiffEditorWidgetImpl.js
var $9Eb = class $9Eb2 extends $3c {
  constructor(y, z, C, D, F, G) {
    super();
    this.y = y;
    this.z = z;
    this.C = C;
    this.D = D;
    this.F = F;
    this.G = G;
    this.a = h("div.scrollContent", [
      h("div@content", {
        style: {
          overflow: "hidden"
        }
      }),
      h("div.monaco-editor@overflowWidgetsDomNode", {})
    ]);
    this.b = this.B(new $AD({
      forceIntegerValues: false,
      scheduleAtNextAnimationFrame: (cb) => $jj(getWindow(this.y), cb),
      smoothScrollDuration: 100
    }));
    this.c = this.B(new $BZ(this.a.root, {
      vertical: 1,
      horizontal: 1,
      useShadows: false
    }, this.b));
    this.f = h("div.monaco-component.multiDiffEditor", {}, [
      h("div", {}, [this.c.getDomNode()]),
      h("div.placeholder@placeholder", {}, [h("div")])
    ]);
    this.g = this.B(new $U9(this.y, void 0));
    this.j = this.B(new $6Eb((data) => {
      const template = this.w.createInstance($8Eb, this.a.content, this.a.overflowWidgetsDomNode, this.D);
      template.setData(data);
      return template;
    }));
    this.scrollTop = $Dd(this, this.c.onScroll, () => (
      /** @description scrollTop */
      this.c.getScrollPosition().scrollTop
    ));
    this.scrollLeft = $Dd(this, this.c.onScroll, () => (
      /** @description scrollLeft */
      this.c.getScrollPosition().scrollLeft
    ));
    this.m = $6d(this, (reader, store) => {
      const vm = this.C.read(reader);
      if (!vm) {
        return { items: [], getItem: (_d) => {
          throw new $vb();
        } };
      }
      const viewModels = vm.items.read(reader);
      const map = /* @__PURE__ */ new Map();
      const items = viewModels.map((d) => {
        const item = store.add(new VirtualizedViewItem(d, this.j, this.scrollLeft, (delta) => {
          this.c.setScrollPosition({ scrollTop: this.c.getScrollPosition().scrollTop + delta });
        }));
        const data = this.H?.[item.getKey()];
        if (data) {
          $ce((tx) => {
            item.setViewState(data, tx);
          });
        }
        map.set(d, item);
        return item;
      });
      return { items, getItem: (d) => map.get(d) };
    });
    this.n = this.m.map(this, (items) => items.items);
    this.s = 0;
    this.t = this.n.map(this, (items, reader) => items.reduce((r2, i2) => r2 + i2.contentHeight.read(reader) + this.s, 0));
    this.activeControl = $2d(this, (reader) => {
      const activeDiffItem = this.C.read(reader)?.activeDiffItem.read(reader);
      if (!activeDiffItem) {
        return void 0;
      }
      const viewItem = this.m.read(reader).getItem(activeDiffItem);
      return viewItem.template.read(reader)?.editor;
    });
    this.u = this.B(this.F.createScoped(this.y));
    this.w = this.B(this.G.createChild(new $Ok([$on, this.u])));
    this.H = {};
    this.B($xd((reader, store) => {
      const viewModel = this.C.read(reader);
      if (viewModel && viewModel.contextKeys) {
        for (const [key2, value] of Object.entries(viewModel.contextKeys)) {
          const contextKey = this.u.createKey(key2, void 0);
          contextKey.set(value);
          store.add($1c(() => contextKey.reset()));
        }
      }
    }));
    const ctxAllCollapsed = this.F.createKey(EditorContextKeys.multiDiffEditorAllCollapsed.key, false);
    this.B($td((reader) => {
      const viewModel = this.C.read(reader);
      if (viewModel) {
        const allCollapsed = viewModel.items.read(reader).every((item) => item.collapsed.read(reader));
        ctxAllCollapsed.set(allCollapsed);
      }
    }));
    this.B($td((reader) => {
      const dimension = this.z.read(reader);
      this.g.observe(dimension);
    }));
    const placeholderMessage = $2d((reader) => {
      const items = this.n.read(reader);
      if (items.length > 0) {
        return void 0;
      }
      const vm = this.C.read(reader);
      return !vm || vm.isLoading.read(reader) ? localize(256, null) : localize(257, null);
    });
    this.B($td((reader) => {
      const message = placeholderMessage.read(reader);
      this.f.placeholder.innerText = message ?? "";
      this.f.placeholder.classList.toggle("visible", !!message);
    }));
    this.a.content.style.position = "relative";
    this.B($td((reader) => {
      const height = this.g.height.read(reader);
      this.a.root.style.height = `${height}px`;
      const totalHeight = this.t.read(reader);
      this.a.content.style.height = `${totalHeight}px`;
      const width2 = this.g.width.read(reader);
      let scrollWidth = width2;
      const viewItems = this.n.read(reader);
      const max = $9(viewItems, $9b((i2) => i2.maxScroll.read(reader).maxScroll, $$b));
      if (max) {
        const maxScroll = max.maxScroll.read(reader);
        scrollWidth = width2 + maxScroll.maxScroll;
      }
      this.c.setScrollDimensions({
        width: width2,
        height,
        scrollHeight: totalHeight,
        scrollWidth
      });
    }));
    y.replaceChildren(this.f.root);
    this.B($1c(() => {
      y.replaceChildren();
    }));
    this.B(this.B($td((reader) => {
      $de((tx) => {
        this.I(reader);
      });
    })));
  }
  setScrollState(scrollState) {
    this.c.setScrollPosition({ scrollLeft: scrollState.left, scrollTop: scrollState.top });
  }
  reveal(resource, options3) {
    const viewItems = this.n.get();
    const index = viewItems.findIndex((item) => item.viewModel.originalUri?.toString() === resource.original?.toString() && item.viewModel.modifiedUri?.toString() === resource.modified?.toString());
    if (index === -1) {
      throw new $vb("Resource not found in diff editor");
    }
    const viewItem = viewItems[index];
    this.C.get().activeDiffItem.setCache(viewItem.viewModel, void 0);
    let scrollTop = 0;
    for (let i2 = 0; i2 < index; i2++) {
      scrollTop += viewItems[i2].contentHeight.get() + this.s;
    }
    this.c.setScrollPosition({ scrollTop });
    const diffEditor = viewItem.template.get()?.editor;
    const editor = "original" in resource ? diffEditor?.getOriginalEditor() : diffEditor?.getModifiedEditor();
    if (editor && options3?.range) {
      editor.revealRangeInCenter(options3.range);
      highlightRange(editor, options3.range);
    }
  }
  getViewState() {
    return {
      scrollState: {
        top: this.scrollTop.get(),
        left: this.scrollLeft.get()
      },
      docStates: Object.fromEntries(this.n.get().map((i2) => [i2.getKey(), i2.getViewState()]))
    };
  }
  setViewState(viewState) {
    this.setScrollState(viewState.scrollState);
    this.H = viewState.docStates;
    $ce((tx) => {
      if (viewState.docStates) {
        for (const i2 of this.n.get()) {
          const state = viewState.docStates[i2.getKey()];
          if (state) {
            i2.setViewState(state, tx);
          }
        }
      }
    });
  }
  findDocumentDiffItem(resource) {
    const item = this.n.get().find((v) => v.viewModel.diffEditorViewModel.model.modified.uri.toString() === resource.toString() || v.viewModel.diffEditorViewModel.model.original.uri.toString() === resource.toString());
    return item?.viewModel.documentDiffItem;
  }
  tryGetCodeEditor(resource) {
    const item = this.n.get().find((v) => v.viewModel.diffEditorViewModel.model.modified.uri.toString() === resource.toString() || v.viewModel.diffEditorViewModel.model.original.uri.toString() === resource.toString());
    const editor = item?.template.get()?.editor;
    if (!editor) {
      return void 0;
    }
    if (item.viewModel.diffEditorViewModel.model.modified.uri.toString() === resource.toString()) {
      return { diffEditor: editor, editor: editor.getModifiedEditor() };
    } else {
      return { diffEditor: editor, editor: editor.getOriginalEditor() };
    }
  }
  I(reader) {
    const scrollTop = this.scrollTop.read(reader);
    let contentScrollOffsetToScrollOffset = 0;
    let itemHeightSumBefore = 0;
    let itemContentHeightSumBefore = 0;
    const viewPortHeight = this.g.height.read(reader);
    const contentViewPort = $0C.ofStartAndLength(scrollTop, viewPortHeight);
    const width2 = this.g.width.read(reader);
    for (const v of this.n.read(reader)) {
      const itemContentHeight = v.contentHeight.read(reader);
      const itemHeight = Math.min(itemContentHeight, viewPortHeight);
      const itemRange = $0C.ofStartAndLength(itemHeightSumBefore, itemHeight);
      const itemContentRange = $0C.ofStartAndLength(itemContentHeightSumBefore, itemContentHeight);
      if (itemContentRange.isBefore(contentViewPort)) {
        contentScrollOffsetToScrollOffset -= itemContentHeight - itemHeight;
        v.hide();
      } else if (itemContentRange.isAfter(contentViewPort)) {
        v.hide();
      } else {
        const scroll = Math.max(0, Math.min(contentViewPort.start - itemContentRange.start, itemContentHeight - itemHeight));
        contentScrollOffsetToScrollOffset -= scroll;
        const viewPort = $0C.ofStartAndLength(scrollTop + contentScrollOffsetToScrollOffset, viewPortHeight);
        v.render(itemRange, scroll, width2, viewPort);
      }
      itemHeightSumBefore += itemHeight + this.s;
      itemContentHeightSumBefore += itemContentHeight + this.s;
    }
    this.a.content.style.transform = `translateY(${-(scrollTop + contentScrollOffsetToScrollOffset)}px)`;
  }
};
$9Eb = __decorate([
  __param(4, $on),
  __param(5, $Pk)
], $9Eb);
function highlightRange(targetEditor, range) {
  const modelNow = targetEditor.getModel();
  const decorations = targetEditor.createDecorationsCollection([{ range, options: { description: "symbol-navigate-action-highlight", className: "symbolHighlight" } }]);
  setTimeout(() => {
    if (targetEditor.getModel() === modelNow) {
      decorations.clear();
    }
  }, 350);
}
var VirtualizedViewItem = class extends $3c {
  constructor(viewModel, f, g, j) {
    super();
    this.viewModel = viewModel;
    this.f = f;
    this.g = g;
    this.j = j;
    this.a = this.B($je(this, void 0));
    this.contentHeight = $2d(this, (reader) => this.a.read(reader)?.object.contentHeight?.read(reader) ?? this.viewModel.lastTemplateData.read(reader).contentHeight);
    this.maxScroll = $2d(this, (reader) => this.a.read(reader)?.object.maxScroll.read(reader) ?? { maxScroll: 0, scrollWidth: 0 });
    this.template = $2d(this, (reader) => this.a.read(reader)?.object);
    this.b = $he(this, false);
    this.c = $2d(this, (reader) => this.template.read(reader)?.isFocused.read(reader) ?? false);
    this.viewModel.setIsFocused(this.c, void 0);
    this.B($td((reader) => {
      const scrollLeft = this.g.read(reader);
      this.a.read(reader)?.object.setScrollLeft(scrollLeft);
    }));
    this.B($td((reader) => {
      const ref = this.a.read(reader);
      if (!ref) {
        return;
      }
      const isHidden = this.b.read(reader);
      if (!isHidden) {
        return;
      }
      const isFocused = ref.object.isFocused.read(reader);
      if (isFocused) {
        return;
      }
      this.n();
    }));
  }
  dispose() {
    this.n();
    super.dispose();
  }
  toString() {
    return `VirtualViewItem(${this.viewModel.documentDiffItem.modified?.uri.toString()})`;
  }
  getKey() {
    return this.viewModel.getKey();
  }
  getViewState() {
    $ce((tx) => {
      this.m(tx);
    });
    return {
      collapsed: this.viewModel.collapsed.get(),
      selections: this.viewModel.lastTemplateData.get().selections
    };
  }
  setViewState(viewState, tx) {
    this.viewModel.collapsed.set(viewState.collapsed, tx);
    this.m(tx);
    const data = this.viewModel.lastTemplateData.get();
    const selections = viewState.selections?.map($_D.liftSelection);
    this.viewModel.lastTemplateData.set({
      ...data,
      selections
    }, tx);
    const ref = this.a.get();
    if (ref) {
      if (selections) {
        ref.object.editor.setSelections(selections);
      }
    }
  }
  m(tx) {
    const ref = this.a.get();
    if (!ref) {
      return;
    }
    this.viewModel.lastTemplateData.set({
      contentHeight: ref.object.contentHeight.get(),
      selections: ref.object.editor.getSelections() ?? void 0
    }, tx);
  }
  n() {
    const ref = this.a.get();
    if (!ref) {
      return;
    }
    $ce((tx) => {
      this.m(tx);
      ref.object.hide();
      this.a.set(void 0, tx);
    });
  }
  hide() {
    this.b.set(true, void 0);
  }
  render(verticalSpace, offset, width2, viewPort) {
    this.b.set(false, void 0);
    let ref = this.a.get();
    if (!ref) {
      ref = this.f.getUnusedObj(new $7Eb(this.viewModel, this.j));
      this.a.set(ref, void 0);
      const selections = this.viewModel.lastTemplateData.get().selections;
      if (selections) {
        ref.object.editor.setSelections(selections);
      }
    }
    ref.object.render(verticalSpace, width2, offset, viewPort);
  }
};

// out-build/vs/editor/browser/widget/multiDiffEditor/multiDiffEditorWidget.js
var $0Eb = class $0Eb2 extends $3c {
  constructor(f, g, h3) {
    super();
    this.f = f;
    this.g = g;
    this.h = h3;
    this.a = $he(this, void 0);
    this.b = $he(this, void 0);
    this.c = $6d(this, (reader, store) => {
      $N3($8Eb, reader);
      return store.add(this.h.createInstance($N3($9Eb, reader), this.f, this.a, this.b, this.g));
    });
    this.j = $2d(this, (reader) => this.c.read(reader).activeControl.read(reader));
    this.onDidChangeActiveControl = Event2.fromObservableLight(this.j);
    this.B($Nd(this.c));
  }
  reveal(resource, options3) {
    this.c.get().reveal(resource, options3);
  }
  createViewModel(model) {
    return new $4Eb(model, this.h);
  }
  setViewModel(viewModel) {
    this.b.set(viewModel, void 0);
  }
  layout(dimension) {
    this.a.set(dimension, void 0);
  }
  getActiveControl() {
    return this.j.get();
  }
  getViewState() {
    return this.c.get().getViewState();
  }
  setViewState(viewState) {
    this.c.get().setViewState(viewState);
  }
  tryGetCodeEditor(resource) {
    return this.c.get().tryGetCodeEditor(resource);
  }
  findDocumentDiffItem(resource) {
    return this.c.get().findDocumentDiffItem(resource);
  }
};
$0Eb = __decorate([
  __param(2, $Pk)
], $0Eb);

// out-build/vs/workbench/contrib/notebook/browser/diff/notebookMultiDiffEditor.js
var $03b_1;
var $03b = class $03b2 extends $5tb {
  static {
    $03b_1 = this;
  }
  static {
    this.ID = $dM;
  }
  get textModel() {
    return this.j?.modified.notebook;
  }
  get notebookOptions() {
    return this.s;
  }
  constructor(group2, db, themeService, eb, fb, gb, telemetryService, storageService, hb) {
    super($03b_1.ID, group2, telemetryService, themeService, storageService);
    this.db = db;
    this.eb = eb;
    this.fb = fb;
    this.gb = gb;
    this.hb = hb;
    this.g = this.B(new $2c());
    this.u = this.eb.createKey($7Db.key, false);
    this.$ = this.eb.createKey($8Db.key, false);
    this.cb = this.eb.createKey($9Db.key, true);
    this.s = db.createInstance($xrb, this.window, false, void 0);
    this.B(this.s);
  }
  get ib() {
    if (!this.b) {
      this.b = this.jb();
    }
    return this.b;
  }
  layout(dimension, position) {
    this.a.layout(dimension);
  }
  jb() {
    const editorOptions2 = this.gb.getValue("editor");
    return $64.readFontInfo(this.window, $ED.createFromRawSettings(editorOptions2, $_1.getInstance(this.window).value));
  }
  Y(parent) {
    this.a = this.B(this.db.createInstance($0Eb, parent, this.db.createInstance(WorkbenchUIElementFactory)));
    this.B(this.a.onDidChangeActiveControl(() => {
      this.S.fire();
    }));
  }
  async setInput(input, options3, context, token) {
    super.setInput(input, options3, context, token);
    const model = await input.resolve();
    if (this.j !== model) {
      this.lb();
      this.j = model;
    }
    const eventDispatcher = this.g.add(new $dEb());
    const diffEditorHeightCalculator = this.db.createInstance($eEb, this.ib.lineHeight);
    this.m = this.g.add(new $vEb(model, this.fb, this.gb, eventDispatcher, this.hb, diffEditorHeightCalculator, void 0, true));
    await this.m.computeDiff(this.g.add(new $ad()).token);
    this.$.set(this.m.hasUnchangedCells);
    this.$.set(this.m.hasUnchangedCells);
    const widgetInput = this.g.add($d2b.createInput(this.m, this.db));
    this.r = this.g.add(await widgetInput.getViewModel());
    const itemsWeHaveSeen = /* @__PURE__ */ new WeakSet();
    this.g.add($td((reader) => {
      if (!this.r || !this.m) {
        return;
      }
      const items = this.r.items.read(reader);
      const diffItems = this.m.value;
      if (items.length !== diffItems.length) {
        return;
      }
      $ce((tx) => {
        items.forEach((item) => {
          if (itemsWeHaveSeen.has(item)) {
            return;
          }
          itemsWeHaveSeen.add(item);
          const diffItem = diffItems.find((d) => d.modifiedUri?.toString() === item.modifiedUri?.toString() && d.originalUri?.toString() === item.originalUri?.toString());
          if (diffItem && diffItem.type === "unchanged") {
            item.collapsed.set(true, tx);
          }
        });
      });
    }));
    this.a.setViewModel(this.r);
  }
  lb() {
    this.m = void 0;
    this.g.clear();
  }
  _generateFontFamily() {
    return this.ib.fontFamily ?? `"SF Mono", Monaco, Menlo, Consolas, "Ubuntu Mono", "Liberation Mono", "DejaVu Sans Mono", "Courier New", monospace`;
  }
  setOptions(options3) {
    super.setOptions(options3);
  }
  getControl() {
    return this.a.getActiveControl();
  }
  focus() {
    super.focus();
    this.a?.getActiveControl()?.focus();
  }
  hasFocus() {
    return this.a?.getActiveControl()?.hasTextFocus() || super.hasFocus();
  }
  clearInput() {
    super.clearInput();
    this.a.setViewModel(void 0);
    this.g.clear();
    this.m = void 0;
    this.r = void 0;
  }
  expandAll() {
    if (this.r) {
      this.r.expandAll();
      this.u.set(false);
    }
  }
  collapseAll() {
    if (this.r) {
      this.r.collapseAll();
      this.u.set(true);
    }
  }
  hideUnchanged() {
    if (this.m) {
      this.m.includeUnchanged = false;
      this.cb.set(true);
    }
  }
  showUnchanged() {
    if (this.m) {
      this.m.includeUnchanged = true;
      this.cb.set(false);
    }
  }
  getDiffElementViewModel(uri) {
    if (uri.scheme === Schemas.vscodeNotebookCellOutput || uri.scheme === Schemas.vscodeNotebookCellOutputDiff || uri.scheme === Schemas.vscodeNotebookCellMetadata || uri.scheme === Schemas.vscodeNotebookCellMetadataDiff) {
      const data = CellUri.parseCellPropertyUri(uri, uri.scheme);
      if (data) {
        uri = CellUri.generate(data.notebook, data.handle);
      }
    }
    if (uri.scheme === Schemas.vscodeNotebookMetadata) {
      return this.m?.items.find((item) => item.type === "modifiedMetadata" || item.type === "unchangedMetadata");
    }
    return this.m?.items.find((c) => {
      switch (c.type) {
        case "delete":
          return c.original?.uri.toString() === uri.toString();
        case "insert":
          return c.modified?.uri.toString() === uri.toString();
        case "modified":
        case "unchanged":
          return c.modified?.uri.toString() === uri.toString() || c.original?.uri.toString() === uri.toString();
        default:
          return;
      }
    });
  }
};
$03b = $03b_1 = __decorate([
  __param(1, $Pk),
  __param(2, $gs),
  __param(3, $on),
  __param(4, $uEb),
  __param(5, $kl),
  __param(6, $zv),
  __param(7, $jv),
  __param(8, $mrb)
], $03b);
var WorkbenchUIElementFactory = class WorkbenchUIElementFactory2 {
  constructor(a, b, e) {
    this.a = a;
    this.b = b;
    this.e = e;
  }
  createResourceLabel(element) {
    const label3 = this.a.createInstance($msb, element, {});
    const that = this;
    return {
      setUri(uri, options3 = {}) {
        if (!uri) {
          label3.element.clear();
        } else {
          let name = "";
          let description = "";
          let extraClasses = void 0;
          if (uri.scheme === Schemas.vscodeNotebookCell) {
            const notebookDocument = uri.scheme === Schemas.vscodeNotebookCell ? that.b.getNotebook(uri) : void 0;
            const cellIndex = Schemas.vscodeNotebookCell ? that.b.getNotebook(uri)?.getCellIndex(uri) : void 0;
            if (notebookDocument && cellIndex !== void 0) {
              name = localize(8397, null, `${cellIndex + 1}`);
              const nb = notebookDocument ? that.e.getNotebookTextModel(notebookDocument?.uri) : void 0;
              const cellLanguage = nb && cellIndex !== void 0 ? nb.cells[cellIndex].language : void 0;
              extraClasses = cellLanguage ? $hdb(cellLanguage) : void 0;
            }
          } else if (uri.scheme === Schemas.vscodeNotebookCellMetadata || uri.scheme === Schemas.vscodeNotebookCellMetadataDiff) {
            description = localize(8398, null);
          } else if (uri.scheme === Schemas.vscodeNotebookCellOutput || uri.scheme === Schemas.vscodeNotebookCellOutputDiff) {
            description = localize(8399, null);
          }
          label3.element.setResource({ name, description }, { strikethrough: options3.strikethrough, forceLabel: true, hideIcon: !extraClasses, extraClasses });
        }
      },
      dispose() {
        label3.dispose();
      }
    };
  }
};
WorkbenchUIElementFactory = __decorate([
  __param(0, $Pk),
  __param(1, $8L),
  __param(2, $mrb)
], WorkbenchUIElementFactory);

// out-build/vs/workbench/contrib/notebook/browser/diff/notebookDiffActions.js
$hJ(class extends $gJ {
  constructor() {
    super({
      id: "notebook.diff.openFile",
      icon: $6l.goToFile,
      title: localize2(8382, "Open File"),
      precondition: $7m.or($Dpb.isEqualTo($A2b.ID), $Dpb.isEqualTo($03b.ID)),
      menu: [{
        id: $bJ.EditorTitle,
        group: "navigation",
        when: $7m.or($Dpb.isEqualTo($A2b.ID), $Dpb.isEqualTo($03b.ID))
      }]
    });
  }
  async run(accessor) {
    const editorService = accessor.get($mJ);
    const activeEditor = editorService.activeEditorPane;
    if (!activeEditor) {
      return;
    }
    if (activeEditor instanceof $A2b || activeEditor instanceof $03b) {
      const diffEditorInput = activeEditor.input;
      const resource = diffEditorInput.modified.resource;
      await editorService.openEditor({ resource });
    }
  }
});
$hJ(class extends $gJ {
  constructor() {
    super({
      id: "notebook.diff.cell.toggleCollapseUnchangedRegions",
      title: localize2(8383, "Toggle Collapse Unchanged Regions"),
      icon: $6l.map,
      toggled: $7m.has("config.diffEditor.hideUnchangedRegions.enabled"),
      precondition: $Dpb.isEqualTo($A2b.ID),
      menu: {
        id: $bJ.EditorTitle,
        group: "navigation",
        when: $Dpb.isEqualTo($A2b.ID)
      }
    });
  }
  run(accessor, ...args2) {
    const configurationService = accessor.get($kl);
    const newValue = !configurationService.getValue("diffEditor.hideUnchangedRegions.enabled");
    configurationService.updateValue("diffEditor.hideUnchangedRegions.enabled", newValue);
  }
});
$hJ(class extends $gJ {
  constructor() {
    super({
      id: "notebook.diff.switchToText",
      icon: $UKb,
      title: localize2(8384, "Open Text Diff Editor"),
      precondition: $7m.or($Dpb.isEqualTo($A2b.ID), $Dpb.isEqualTo($03b.ID)),
      menu: [{
        id: $bJ.EditorTitle,
        group: "navigation",
        when: $7m.or($Dpb.isEqualTo($A2b.ID), $Dpb.isEqualTo($03b.ID))
      }]
    });
  }
  async run(accessor) {
    const editorService = accessor.get($mJ);
    const activeEditor = editorService.activeEditorPane;
    if (!activeEditor) {
      return;
    }
    if (activeEditor instanceof $A2b || activeEditor instanceof $03b) {
      const diffEditorInput = activeEditor.input;
      await editorService.openEditor({
        original: { resource: diffEditorInput.original.resource },
        modified: { resource: diffEditorInput.resource },
        label: diffEditorInput.getName(),
        options: {
          preserveFocus: false,
          override: $1K.id
        }
      });
    }
  }
});
$hJ(class extends $gJ {
  constructor() {
    super({
      id: "notebook.diffEditor.showUnchangedCells",
      title: localize2(8385, "Show Unchanged Cells"),
      icon: $6l.unfold,
      precondition: $7m.and($Dpb.isEqualTo($03b.ID), $7m.has($8Db.key)),
      menu: {
        when: $7m.and($Dpb.isEqualTo($03b.ID), $7m.has($8Db.key), $7m.equals($9Db.key, true)),
        id: $bJ.EditorTitle,
        order: 22,
        group: "navigation"
      }
    });
  }
  run(accessor, ...args2) {
    const activeEditor = accessor.get($mJ).activeEditorPane;
    if (!activeEditor) {
      return;
    }
    if (activeEditor instanceof $03b) {
      activeEditor.showUnchanged();
    }
  }
});
$hJ(class extends $gJ {
  constructor() {
    super({
      id: "notebook.diffEditor.hideUnchangedCells",
      title: localize2(8386, "Hide Unchanged Cells"),
      icon: $6l.fold,
      precondition: $7m.and($Dpb.isEqualTo($03b.ID), $7m.has($8Db.key)),
      menu: {
        when: $7m.and($Dpb.isEqualTo($03b.ID), $7m.has($8Db.key), $7m.equals($9Db.key, false)),
        id: $bJ.EditorTitle,
        order: 22,
        group: "navigation"
      }
    });
  }
  run(accessor, ...args2) {
    const activeEditor = accessor.get($mJ).activeEditorPane;
    if (!activeEditor) {
      return;
    }
    if (activeEditor instanceof $03b) {
      activeEditor.hideUnchanged();
    }
  }
});
$hJ(class GoToFileAction extends $gJ {
  constructor() {
    super({
      id: "notebook.diffEditor.2.goToCell",
      title: localize2(8387, "Go To Cell"),
      icon: $6l.goToFile,
      menu: {
        when: $7m.and($Dpb.isEqualTo($03b.ID), $7m.equals($0Db.key, "Cell"), $7m.notEquals($$Db.key, "delete")),
        id: $bJ.MultiDiffEditorFileToolbar,
        order: 0,
        group: "navigation"
      }
    });
  }
  async run(accessor, ...args2) {
    const uri = args2[0];
    const editorService = accessor.get($mJ);
    const activeEditorPane = editorService.activeEditorPane;
    if (!(activeEditorPane instanceof $03b)) {
      return;
    }
    await editorService.openEditor({
      resource: uri,
      options: {
        selectionRevealType: 1
      }
    });
  }
});
$hJ(class extends $gJ {
  constructor() {
    super({
      id: "notebook.diff.revertMetadata",
      title: localize(8371, null),
      icon: $VKb,
      f1: false,
      menu: {
        id: $bJ.NotebookDiffDocumentMetadata,
        when: $2Db
      },
      precondition: $2Db
    });
  }
  run(accessor, context) {
    if (!context) {
      return;
    }
    const editorService = accessor.get($mJ);
    const activeEditorPane = editorService.activeEditorPane;
    if (!(activeEditorPane instanceof $A2b)) {
      return;
    }
    context.modifiedDocumentTextModel.applyEdits([{
      editType: 5,
      metadata: context.originalMetadata.metadata
    }], true, void 0, () => void 0, void 0, true);
  }
});
var revertInput = localize(8372, null);
$hJ(class extends $gJ {
  constructor() {
    super({
      id: "notebook.diffEditor.2.cell.revertInput",
      title: revertInput,
      icon: $VKb,
      menu: {
        when: $7m.and($Dpb.isEqualTo($03b.ID), $7m.equals($0Db.key, "Cell"), $7m.equals($$Db.key, "modified")),
        id: $bJ.MultiDiffEditorFileToolbar,
        order: 2,
        group: "navigation"
      }
    });
  }
  async run(accessor, ...args2) {
    const uri = args2[0];
    const editorService = accessor.get($mJ);
    const activeEditorPane = editorService.activeEditorPane;
    if (!(activeEditorPane instanceof $03b)) {
      return;
    }
    const item = activeEditorPane.getDiffElementViewModel(uri);
    if (item && item instanceof $oEb) {
      const modified = item.modified;
      const original = item.original;
      if (!original || !modified) {
        return;
      }
      const bulkEditService = accessor.get($H_);
      await bulkEditService.apply([
        new $J_(modified.uri, { range: modified.textModel.getFullModelRange(), text: original.textModel.getValue() })
      ], { quotableLabel: "Revert Notebook Cell Content Change" });
    }
  }
});
var revertOutputs = localize(8373, null);
$hJ(class extends $gJ {
  constructor() {
    super({
      id: "notebook.diffEditor.2.cell.revertOutputs",
      title: revertOutputs,
      icon: $VKb,
      f1: false,
      menu: {
        when: $7m.and($Dpb.isEqualTo($03b.ID), $7m.equals($0Db.key, "Output"), $7m.equals($$Db.key, "modified")),
        id: $bJ.MultiDiffEditorFileToolbar,
        order: 2,
        group: "navigation"
      }
    });
  }
  async run(accessor, ...args2) {
    const uri = args2[0];
    const editorService = accessor.get($mJ);
    const activeEditorPane = editorService.activeEditorPane;
    if (!(activeEditorPane instanceof $03b)) {
      return;
    }
    const item = activeEditorPane.getDiffElementViewModel(uri);
    if (item && item instanceof $oEb) {
      const original = item.original;
      const modifiedCellIndex = item.modifiedDocument.cells.findIndex((cell) => cell.handle === item.modified.handle);
      if (modifiedCellIndex === -1) {
        return;
      }
      item.mainDocumentTextModel.applyEdits([{
        editType: 2,
        index: modifiedCellIndex,
        outputs: original.outputs
      }], true, void 0, () => void 0, void 0, true);
    }
  }
});
var revertMetadata = localize(8374, null);
$hJ(class extends $gJ {
  constructor() {
    super({
      id: "notebook.diffEditor.2.cell.revertMetadata",
      title: revertMetadata,
      icon: $VKb,
      f1: false,
      menu: {
        when: $7m.and($Dpb.isEqualTo($03b.ID), $7m.equals($0Db.key, "Metadata"), $7m.equals($$Db.key, "modified")),
        id: $bJ.MultiDiffEditorFileToolbar,
        order: 2,
        group: "navigation"
      }
    });
  }
  async run(accessor, ...args2) {
    const uri = args2[0];
    const editorService = accessor.get($mJ);
    const activeEditorPane = editorService.activeEditorPane;
    if (!(activeEditorPane instanceof $03b)) {
      return;
    }
    const item = activeEditorPane.getDiffElementViewModel(uri);
    if (item && item instanceof $oEb) {
      const original = item.original;
      const modifiedCellIndex = item.modifiedDocument.cells.findIndex((cell) => cell.handle === item.modified.handle);
      if (modifiedCellIndex === -1) {
        return;
      }
      item.mainDocumentTextModel.applyEdits([{
        editType: 3,
        index: modifiedCellIndex,
        metadata: original.metadata
      }], true, void 0, () => void 0, void 0, true);
    }
  }
});
$hJ(class extends $gJ {
  constructor() {
    super({
      id: "notebook.diff.cell.revertMetadata",
      title: revertMetadata,
      icon: $VKb,
      f1: false,
      menu: {
        id: $bJ.NotebookDiffCellMetadataTitle,
        when: $5Db
      },
      precondition: $5Db
    });
  }
  run(accessor, context) {
    if (!context) {
      return;
    }
    if (!(context instanceof $oEb)) {
      return;
    }
    const original = context.original;
    const modified = context.modified;
    const modifiedCellIndex = context.mainDocumentTextModel.cells.indexOf(modified.textModel);
    if (modifiedCellIndex === -1) {
      return;
    }
    const rawEdits = [{ editType: 3, index: modifiedCellIndex, metadata: original.metadata }];
    if (context.original.language && context.modified.language !== context.original.language) {
      rawEdits.push({ editType: 4, index: modifiedCellIndex, language: context.original.language });
    }
    context.modifiedDocument.applyEdits(rawEdits, true, void 0, () => void 0, void 0, true);
  }
});
$hJ(class extends $gJ {
  constructor() {
    super({
      id: "notebook.diff.cell.switchOutputRenderingStyleToText",
      title: localize(8375, null),
      icon: $XKb,
      f1: false,
      menu: {
        id: $bJ.NotebookDiffCellOutputsTitle,
        when: $6Db
      }
    });
  }
  run(accessor, context) {
    if (!context) {
      return;
    }
    context.renderOutput = !context.renderOutput;
  }
});
$hJ(class extends $gJ {
  constructor() {
    super({
      id: "notebook.diff.cell.revertOutputs",
      title: localize(8376, null),
      icon: $VKb,
      f1: false,
      menu: {
        id: $bJ.NotebookDiffCellOutputsTitle,
        when: $5Db
      },
      precondition: $5Db
    });
  }
  run(accessor, context) {
    if (!context) {
      return;
    }
    if (!(context instanceof $oEb)) {
      return;
    }
    const original = context.original;
    const modified = context.modified;
    const modifiedCellIndex = context.mainDocumentTextModel.cells.indexOf(modified.textModel);
    if (modifiedCellIndex === -1) {
      return;
    }
    context.mainDocumentTextModel.applyEdits([{
      editType: 2,
      index: modifiedCellIndex,
      outputs: original.outputs
    }], true, void 0, () => void 0, void 0, true);
  }
});
$hJ(class extends $gJ {
  constructor() {
    super({
      id: "notebook.toggle.diff.cell.ignoreTrimWhitespace",
      title: localize(8377, null),
      icon: $WKb,
      f1: false,
      menu: {
        id: $bJ.NotebookDiffCellInputTitle,
        when: $1Db,
        order: 1
      },
      precondition: $1Db,
      toggled: $7m.equals($3Db, false)
    });
  }
  run(accessor, context) {
    const cell = context;
    if (!cell?.modified) {
      return;
    }
    const uri = cell.modified.uri;
    const configService = accessor.get($zG);
    const key2 = "diffEditor.ignoreTrimWhitespace";
    const val = configService.getValue(uri, key2);
    configService.updateValue(uri, key2, !val);
  }
});
$hJ(class extends $gJ {
  constructor() {
    super({
      id: "notebook.diff.cell.revertInput",
      title: revertInput,
      icon: $VKb,
      f1: false,
      menu: {
        id: $bJ.NotebookDiffCellInputTitle,
        when: $1Db,
        order: 2
      },
      precondition: $1Db
    });
  }
  run(accessor, context) {
    if (!context) {
      return;
    }
    const original = context.original;
    const modified = context.modified;
    if (!original || !modified) {
      return;
    }
    const bulkEditService = accessor.get($H_);
    return bulkEditService.apply([
      new $J_(modified.uri, { range: modified.textModel.getFullModelRange(), text: original.textModel.getValue() })
    ], { quotableLabel: "Revert Notebook Cell Content Change" });
  }
});
var ToggleRenderAction = class extends $gJ {
  constructor(id2, title, precondition2, toggled, order, a, b) {
    super({
      id: id2,
      title,
      precondition: precondition2,
      menu: [{
        id: $bJ.EditorTitle,
        group: "notebook",
        when: precondition2,
        order
      }],
      toggled
    });
    this.a = a;
    this.b = b;
  }
  async run(accessor) {
    const configurationService = accessor.get($kl);
    if (this.a !== void 0) {
      const oldValue = configurationService.getValue("notebook.diff.ignoreOutputs");
      configurationService.updateValue("notebook.diff.ignoreOutputs", !oldValue);
    }
    if (this.b !== void 0) {
      const oldValue = configurationService.getValue("notebook.diff.ignoreMetadata");
      configurationService.updateValue("notebook.diff.ignoreMetadata", !oldValue);
    }
  }
};
$hJ(class extends ToggleRenderAction {
  constructor() {
    super("notebook.diff.showOutputs", localize2(8388, "Show Outputs Differences"), $7m.or($Dpb.isEqualTo($A2b.ID), $Dpb.isEqualTo($03b.ID)), $7m.notEquals("config.notebook.diff.ignoreOutputs", true), 2, true, void 0);
  }
});
$hJ(class extends ToggleRenderAction {
  constructor() {
    super("notebook.diff.showMetadata", localize2(8389, "Show Metadata Differences"), $7m.or($Dpb.isEqualTo($A2b.ID), $Dpb.isEqualTo($03b.ID)), $7m.notEquals("config.notebook.diff.ignoreMetadata", true), 1, void 0, true);
  }
});
$hJ(class extends $gJ {
  constructor() {
    super({
      id: "notebook.diff.action.previous",
      title: localize(8378, null),
      icon: $1Kb,
      f1: false,
      keybinding: {
        primary: 1024 | 512 | 61,
        weight: 200,
        when: $Dpb.isEqualTo($A2b.ID)
      },
      menu: {
        id: $bJ.EditorTitle,
        group: "navigation",
        when: $Dpb.isEqualTo($A2b.ID)
      }
    });
  }
  run(accessor) {
    const editorService = accessor.get($mJ);
    if (editorService.activeEditorPane?.getId() !== $cM) {
      return;
    }
    const editor = editorService.activeEditorPane.getControl();
    editor?.previousChange();
  }
});
$hJ(class extends $gJ {
  constructor() {
    super({
      id: "notebook.diff.action.next",
      title: localize(8379, null),
      icon: $2Kb,
      f1: false,
      keybinding: {
        primary: 512 | 61,
        weight: 200,
        when: $Dpb.isEqualTo($A2b.ID)
      },
      menu: {
        id: $bJ.EditorTitle,
        group: "navigation",
        when: $Dpb.isEqualTo($A2b.ID)
      }
    });
  }
  run(accessor) {
    const editorService = accessor.get($mJ);
    if (editorService.activeEditorPane?.getId() !== $cM) {
      return;
    }
    const editor = editorService.activeEditorPane.getControl();
    editor?.nextChange();
  }
});
$Wn.as($Ht.Configuration).registerConfiguration({
  id: "notebook",
  order: 100,
  type: "object",
  "properties": {
    "notebook.diff.ignoreMetadata": {
      type: "boolean",
      default: false,
      markdownDescription: localize(8380, null)
    },
    "notebook.diff.ignoreOutputs": {
      type: "boolean",
      default: false,
      markdownDescription: localize(8381, null)
    }
  }
});

// out-build/vs/workbench/contrib/notebook/browser/services/notebookExecutionStateServiceImpl.js
var $$3b = class $$3b2 extends $3c {
  constructor(s, t, w, y) {
    super();
    this.s = s;
    this.t = t;
    this.w = w;
    this.y = y;
    this.a = new $Ec();
    this.b = new $Ec();
    this.f = new $Ec();
    this.g = new $Ec();
    this.j = new $Ec();
    this.m = new $Ec();
    this.n = this.B(new $ze());
    this.onDidChangeExecution = this.n.event;
    this.r = this.B(new $ze());
    this.onDidChangeLastRunFailState = this.r.event;
  }
  getLastFailedCellForNotebook(notebook) {
    const failedCell = this.j.get(notebook);
    return failedCell?.visible ? failedCell.cellHandle : void 0;
  }
  getLastCompletedCellForNotebook(notebook) {
    return this.m.get(notebook);
  }
  forceCancelNotebookExecutions(notebookUri) {
    const notebookCellExecutions = this.a.get(notebookUri);
    if (notebookCellExecutions) {
      for (const exe of notebookCellExecutions.values()) {
        this.C(notebookUri, exe.cellHandle, exe);
      }
    }
    if (this.b.has(notebookUri)) {
      this.F(notebookUri);
    }
  }
  getCellExecution(cellUri) {
    const parsed = CellUri.parse(cellUri);
    if (!parsed) {
      throw new Error(`Not a cell URI: ${cellUri}`);
    }
    const exeMap = this.a.get(parsed.notebook);
    if (exeMap) {
      return exeMap.get(parsed.handle);
    }
    return void 0;
  }
  getExecution(notebook) {
    return this.b.get(notebook)?.[0];
  }
  getCellExecutionsForNotebook(notebook) {
    const exeMap = this.a.get(notebook);
    return exeMap ? Array.from(exeMap.values()) : [];
  }
  getCellExecutionsByHandleForNotebook(notebook) {
    const exeMap = this.a.get(notebook);
    return exeMap ? new Map(exeMap.entries()) : void 0;
  }
  z(notebookUri, cellHandle, exe) {
    this.n.fire(new NotebookCellExecutionEvent(notebookUri, cellHandle, exe));
  }
  C(notebookUri, cellHandle, exe, lastRunSuccess) {
    const notebookExecutions = this.a.get(notebookUri);
    if (!notebookExecutions) {
      this.t.debug(`NotebookExecutionStateService#_onCellExecutionDidComplete - unknown notebook ${notebookUri.toString()}`);
      return;
    }
    exe.dispose();
    const cellUri = CellUri.generate(notebookUri, cellHandle);
    this.g.get(cellUri)?.dispose();
    this.g.delete(cellUri);
    notebookExecutions.delete(cellHandle);
    if (notebookExecutions.size === 0) {
      this.a.delete(notebookUri);
      this.f.get(notebookUri)?.dispose();
      this.f.delete(notebookUri);
    }
    if (lastRunSuccess !== void 0) {
      if (lastRunSuccess) {
        if (this.a.size === 0) {
          this.y.playSignal($N9.notebookCellCompleted);
        }
        this.L(notebookUri);
      } else {
        this.y.playSignal($N9.notebookCellFailed);
        this.I(notebookUri, cellHandle);
      }
      this.m.set(notebookUri, cellHandle);
    }
    this.n.fire(new NotebookCellExecutionEvent(notebookUri, cellHandle));
  }
  D(notebookUri, exe) {
    this.n.fire(new NotebookExecutionEvent(notebookUri, exe));
  }
  F(notebookUri) {
    const disposables = this.b.get(notebookUri);
    if (!Array.isArray(disposables)) {
      this.t.debug(`NotebookExecutionStateService#_onCellExecutionDidComplete - unknown notebook ${notebookUri.toString()}`);
      return;
    }
    this.b.delete(notebookUri);
    this.n.fire(new NotebookExecutionEvent(notebookUri));
    disposables.forEach((d) => d.dispose());
  }
  createCellExecution(notebookUri, cellHandle) {
    const notebook = this.w.getNotebookTextModel(notebookUri);
    if (!notebook) {
      throw new Error(`Notebook not found: ${notebookUri.toString()}`);
    }
    let notebookExecutionMap = this.a.get(notebookUri);
    if (!notebookExecutionMap) {
      const listeners = this.s.createInstance(NotebookExecutionListeners, notebookUri);
      this.f.set(notebookUri, listeners);
      notebookExecutionMap = /* @__PURE__ */ new Map();
      this.a.set(notebookUri, notebookExecutionMap);
    }
    let exe = notebookExecutionMap.get(cellHandle);
    if (!exe) {
      exe = this.G(notebook, cellHandle);
      notebookExecutionMap.set(cellHandle, exe);
      exe.initialize();
      this.n.fire(new NotebookCellExecutionEvent(notebookUri, cellHandle, exe));
    }
    return exe;
  }
  createExecution(notebookUri) {
    const notebook = this.w.getNotebookTextModel(notebookUri);
    if (!notebook) {
      throw new Error(`Notebook not found: ${notebookUri.toString()}`);
    }
    if (!this.f.has(notebookUri)) {
      const listeners = this.s.createInstance(NotebookExecutionListeners, notebookUri);
      this.f.set(notebookUri, listeners);
    }
    let info = this.b.get(notebookUri);
    if (!info) {
      info = this.H(notebook);
      this.b.set(notebookUri, info);
      this.n.fire(new NotebookExecutionEvent(notebookUri, info[0]));
    }
    return info[0];
  }
  G(notebook, cellHandle) {
    const notebookUri = notebook.uri;
    const exe = this.s.createInstance(CellExecution, cellHandle, notebook);
    const disposable = $Zc(exe.onDidUpdate(() => this.z(notebookUri, cellHandle, exe)), exe.onDidComplete((lastRunSuccess) => this.C(notebookUri, cellHandle, exe, lastRunSuccess)));
    this.g.set(CellUri.generate(notebookUri, cellHandle), disposable);
    return exe;
  }
  H(notebook) {
    const notebookUri = notebook.uri;
    const exe = this.s.createInstance(NotebookExecution, notebook);
    const disposable = $Zc(exe.onDidUpdate(() => this.D(notebookUri, exe)), exe.onDidComplete(() => this.F(notebookUri)));
    return [exe, disposable];
  }
  I(notebookURI, cellHandle) {
    const prevLastFailedCellInfo = this.j.get(notebookURI);
    const notebook = this.w.getNotebookTextModel(notebookURI);
    if (!notebook) {
      return;
    }
    const newLastFailedCellInfo = {
      cellHandle,
      disposable: prevLastFailedCellInfo ? prevLastFailedCellInfo.disposable : this.M(notebook),
      visible: true
    };
    this.j.set(notebookURI, newLastFailedCellInfo);
    this.r.fire({ visible: true, notebook: notebookURI });
  }
  J(notebookURI, visible) {
    const lastFailedCellInfo = this.j.get(notebookURI);
    if (lastFailedCellInfo) {
      this.j.set(notebookURI, {
        cellHandle: lastFailedCellInfo.cellHandle,
        disposable: lastFailedCellInfo.disposable,
        visible
      });
    }
    this.r.fire({ visible, notebook: notebookURI });
  }
  L(notebookURI) {
    const lastFailedCellInfo = this.j.get(notebookURI);
    if (lastFailedCellInfo) {
      lastFailedCellInfo.disposable?.dispose();
      this.j.delete(notebookURI);
    }
    this.r.fire({ visible: false, notebook: notebookURI });
  }
  M(notebook) {
    return notebook.onWillAddRemoveCells((e) => {
      const lastFailedCell = this.j.get(notebook.uri)?.cellHandle;
      if (lastFailedCell !== void 0) {
        const lastFailedCellPos = notebook.cells.findIndex((c) => c.handle === lastFailedCell);
        e.rawEvent.changes.forEach(([start, deleteCount, addedCells]) => {
          if (deleteCount) {
            if (lastFailedCellPos >= start && lastFailedCellPos < start + deleteCount) {
              this.J(notebook.uri, false);
            }
          }
          if (addedCells.some((cell) => cell.handle === lastFailedCell)) {
            this.J(notebook.uri, true);
          }
        });
      }
    });
  }
  dispose() {
    super.dispose();
    this.a.forEach((executionMap) => {
      executionMap.forEach((execution) => execution.dispose());
      executionMap.clear();
    });
    this.a.clear();
    this.b.forEach((disposables) => {
      disposables.forEach((d) => d.dispose());
    });
    this.b.clear();
    this.g.forEach((disposable) => disposable.dispose());
    this.f.forEach((disposable) => disposable.dispose());
    this.j.forEach((elem) => elem.disposable.dispose());
  }
};
$$3b = __decorate([
  __param(0, $Pk),
  __param(1, $wn),
  __param(2, $mrb),
  __param(3, $I9)
], $$3b);
var NotebookCellExecutionEvent = class {
  constructor(notebook, cellHandle, changed) {
    this.notebook = notebook;
    this.cellHandle = cellHandle;
    this.changed = changed;
    this.type = NotebookExecutionType.cell;
  }
  affectsCell(cell) {
    const parsedUri = CellUri.parse(cell);
    return !!parsedUri && $oh(this.notebook, parsedUri.notebook) && this.cellHandle === parsedUri.handle;
  }
  affectsNotebook(notebook) {
    return $oh(this.notebook, notebook);
  }
};
var NotebookExecutionEvent = class {
  constructor(notebook, changed) {
    this.notebook = notebook;
    this.changed = changed;
    this.type = NotebookExecutionType.notebook;
  }
  affectsNotebook(notebook) {
    return $oh(this.notebook, notebook);
  }
};
var NotebookExecutionListeners = class NotebookExecutionListeners2 extends $3c {
  constructor(notebook, b, f, g, j, m) {
    super();
    this.b = b;
    this.f = f;
    this.g = g;
    this.j = j;
    this.m = m;
    this.m.debug(`NotebookExecution#ctor ${notebook.toString()}`);
    const notebookModel = this.b.getNotebookTextModel(notebook);
    if (!notebookModel) {
      throw new Error("Notebook not found: " + notebook);
    }
    this.a = notebookModel;
    this.B(this.a.onWillAddRemoveCells((e) => this.s(e)));
    this.B(this.a.onWillDispose(() => this.r()));
  }
  n() {
    this.m.debug(`NotebookExecutionListeners#cancelAll`);
    const exes = this.j.getCellExecutionsForNotebook(this.a.uri);
    this.g.cancelNotebookCellHandles(this.a, exes.map((exe) => exe.cellHandle));
  }
  r() {
    this.m.debug(`NotebookExecution#onWillDisposeDocument`);
    this.n();
  }
  s(e) {
    const notebookExes = this.j.getCellExecutionsByHandleForNotebook(this.a.uri);
    const executingDeletedHandles = /* @__PURE__ */ new Set();
    const pendingDeletedHandles = /* @__PURE__ */ new Set();
    if (notebookExes) {
      e.rawEvent.changes.forEach(([start, deleteCount]) => {
        if (deleteCount) {
          const deletedHandles = this.a.cells.slice(start, start + deleteCount).map((c) => c.handle);
          deletedHandles.forEach((h3) => {
            const exe = notebookExes.get(h3);
            if (exe?.state === NotebookCellExecutionState.Executing) {
              executingDeletedHandles.add(h3);
            } else if (exe) {
              pendingDeletedHandles.add(h3);
            }
          });
        }
      });
    }
    if (executingDeletedHandles.size || pendingDeletedHandles.size) {
      const kernel = this.f.getSelectedOrSuggestedKernel(this.a);
      if (kernel) {
        const implementsInterrupt = kernel.implementsInterrupt;
        const handlesToCancel = implementsInterrupt ? [...executingDeletedHandles] : [...executingDeletedHandles, ...pendingDeletedHandles];
        this.m.debug(`NotebookExecution#onWillAddRemoveCells, ${JSON.stringify([...handlesToCancel])}`);
        if (handlesToCancel.length) {
          kernel.cancelNotebookCellExecution(this.a.uri, handlesToCancel);
        }
      }
    }
  }
};
NotebookExecutionListeners = __decorate([
  __param(1, $mrb),
  __param(2, $CL),
  __param(3, $vL),
  __param(4, $wL),
  __param(5, $wn)
], NotebookExecutionListeners);
function updateToEdit(update, cellHandle) {
  if (update.editType === CellExecutionUpdateType.Output) {
    return {
      editType: 2,
      handle: update.cellHandle,
      append: update.append,
      outputs: update.outputs
    };
  } else if (update.editType === CellExecutionUpdateType.OutputItems) {
    return {
      editType: 7,
      items: update.items,
      append: update.append,
      outputId: update.outputId
    };
  } else if (update.editType === CellExecutionUpdateType.ExecutionState) {
    const newInternalMetadata = {};
    if (typeof update.executionOrder !== "undefined") {
      newInternalMetadata.executionOrder = update.executionOrder;
    }
    if (typeof update.runStartTime !== "undefined") {
      newInternalMetadata.runStartTime = update.runStartTime;
    }
    return {
      editType: 9,
      handle: cellHandle,
      internalMetadata: newInternalMetadata
    };
  }
  throw new Error("Unknown cell update type");
}
var CellExecution = class CellExecution2 extends $3c {
  get state() {
    return this.f;
  }
  get notebook() {
    return this.m.uri;
  }
  get didPause() {
    return this.g;
  }
  get isPaused() {
    return this.j;
  }
  constructor(cellHandle, m, n) {
    super();
    this.cellHandle = cellHandle;
    this.m = m;
    this.n = n;
    this.a = this.B(new $ze());
    this.onDidUpdate = this.a.event;
    this.b = this.B(new $ze());
    this.onDidComplete = this.b.event;
    this.f = NotebookCellExecutionState.Unconfirmed;
    this.g = false;
    this.j = false;
    this.n.debug(`CellExecution#ctor ${this.r()}`);
  }
  initialize() {
    const startExecuteEdit = {
      editType: 9,
      handle: this.cellHandle,
      internalMetadata: {
        executionId: $ps(),
        runStartTime: null,
        runEndTime: null,
        lastRunSuccess: null,
        executionOrder: null,
        renderDuration: null
      }
    };
    this.t([startExecuteEdit]);
  }
  r() {
    return `${this.m.uri.toString()}, ${this.cellHandle}`;
  }
  s(updates) {
    const updateTypes = updates.map((u) => CellExecutionUpdateType[u.editType]).join(", ");
    this.n.debug(`CellExecution#updateExecution ${this.r()}, [${updateTypes}]`);
  }
  confirm() {
    this.n.debug(`CellExecution#confirm ${this.r()}`);
    this.f = NotebookCellExecutionState.Pending;
    this.a.fire();
  }
  update(updates) {
    this.s(updates);
    if (updates.some((u) => u.editType === CellExecutionUpdateType.ExecutionState)) {
      this.f = NotebookCellExecutionState.Executing;
    }
    if (!this.g && updates.some((u) => u.editType === CellExecutionUpdateType.ExecutionState && u.didPause)) {
      this.g = true;
    }
    const lastIsPausedUpdate = [...updates].reverse().find((u) => u.editType === CellExecutionUpdateType.ExecutionState && typeof u.isPaused === "boolean");
    if (lastIsPausedUpdate) {
      this.j = lastIsPausedUpdate.isPaused;
    }
    const cellModel = this.m.cells.find((c) => c.handle === this.cellHandle);
    if (!cellModel) {
      this.n.debug(`CellExecution#update, updating cell not in notebook: ${this.m.uri.toString()}, ${this.cellHandle}`);
    } else {
      const edits = updates.map((update) => updateToEdit(update, this.cellHandle));
      this.t(edits);
    }
    if (updates.some((u) => u.editType === CellExecutionUpdateType.ExecutionState)) {
      this.a.fire();
    }
  }
  complete(completionData) {
    const cellModel = this.m.cells.find((c) => c.handle === this.cellHandle);
    if (!cellModel) {
      this.n.debug(`CellExecution#complete, completing cell not in notebook: ${this.m.uri.toString()}, ${this.cellHandle}`);
    } else {
      const edit3 = {
        editType: 9,
        handle: this.cellHandle,
        internalMetadata: {
          lastRunSuccess: completionData.lastRunSuccess,
          runStartTime: this.g ? null : cellModel.internalMetadata.runStartTime,
          runEndTime: this.g ? null : completionData.runEndTime,
          error: completionData.error
        }
      };
      this.t([edit3]);
    }
    this.b.fire(completionData.lastRunSuccess);
  }
  t(edits) {
    this.m.applyEdits(edits, true, void 0, () => void 0, void 0, false);
  }
};
CellExecution = __decorate([
  __param(2, $wn)
], CellExecution);
var NotebookExecution = class NotebookExecution2 extends $3c {
  get state() {
    return this.f;
  }
  get notebook() {
    return this.g.uri;
  }
  constructor(g, j) {
    super();
    this.g = g;
    this.j = j;
    this.a = this.B(new $ze());
    this.onDidUpdate = this.a.event;
    this.b = this.B(new $ze());
    this.onDidComplete = this.b.event;
    this.f = NotebookExecutionState.Unconfirmed;
    this.j.debug(`NotebookExecution#ctor`);
  }
  m(message) {
    this.j.debug(`${message} ${this.g.uri.toString()}`);
  }
  confirm() {
    this.m(`Execution#confirm`);
    this.f = NotebookExecutionState.Pending;
    this.a.fire();
  }
  begin() {
    this.m(`Execution#begin`);
    this.f = NotebookExecutionState.Executing;
    this.a.fire();
  }
  complete() {
    this.m(`Execution#begin`);
    this.f = NotebookExecutionState.Unconfirmed;
    this.b.fire();
  }
};
NotebookExecution = __decorate([
  __param(1, $wn)
], NotebookExecution);

// out-build/vs/workbench/contrib/notebook/browser/services/notebookExecutionServiceImpl.js
var $_3b = class $_3b2 {
  constructor(b, d, e, f, g, h3) {
    this.b = b;
    this.d = d;
    this.e = e;
    this.f = f;
    this.g = g;
    this.h = h3;
    this.i = /* @__PURE__ */ new Set();
  }
  async executeNotebookCells(notebook, cells, contextKeyService) {
    const cellsArr = Array.from(cells).filter((c) => c.cellKind === CellKind.Code);
    if (!cellsArr.length) {
      return;
    }
    this.g.debug(`Execution`, `${JSON.stringify(cellsArr.map((c) => c.handle))}`);
    const message = localize(8570, null);
    const trust = await this.f.requestWorkspaceTrust({ message });
    if (!trust) {
      return;
    }
    const cellExecutions = [];
    for (const cell of cellsArr) {
      const cellExe = this.h.getCellExecution(cell.uri);
      if (!!cellExe) {
        continue;
      }
      cellExecutions.push([cell, this.h.createCellExecution(notebook.uri, cell.handle)]);
    }
    const kernel = await $oLb.resolveKernel(notebook, this.d, this.e, this.b);
    if (!kernel) {
      cellExecutions.forEach((cellExe) => cellExe[1].complete({}));
      return;
    }
    this.e.addMostRecentKernel(kernel);
    const validCellExecutions = [];
    for (const [cell, cellExecution] of cellExecutions) {
      if (!kernel.supportedLanguages.includes(cell.language)) {
        cellExecution.complete({});
      } else {
        validCellExecutions.push(cellExecution);
      }
    }
    if (validCellExecutions.length > 0) {
      await this.j(validCellExecutions);
      this.d.selectKernelForNotebook(kernel, notebook);
      await kernel.executeNotebookCellsRequest(notebook.uri, validCellExecutions.map((c) => c.cellHandle));
      const unconfirmed = validCellExecutions.filter((exe) => exe.state === NotebookCellExecutionState.Unconfirmed);
      if (unconfirmed.length) {
        this.g.debug(`Execution`, `Completing unconfirmed executions ${JSON.stringify(unconfirmed.map((exe) => exe.cellHandle))}`);
        unconfirmed.forEach((exe) => exe.complete({}));
      }
      this.g.debug(`Execution`, `Completed executions ${JSON.stringify(validCellExecutions.map((exe) => exe.cellHandle))}`);
    }
  }
  async cancelNotebookCellHandles(notebook, cells) {
    const cellsArr = Array.from(cells);
    this.g.debug(`Execution`, `CancelNotebookCellHandles ${JSON.stringify(cellsArr)}`);
    const kernel = this.d.getSelectedOrSuggestedKernel(notebook);
    if (kernel) {
      await kernel.cancelNotebookCellExecution(notebook.uri, cellsArr);
    }
  }
  async cancelNotebookCells(notebook, cells) {
    this.cancelNotebookCellHandles(notebook, Array.from(cells, (cell) => cell.handle));
  }
  registerExecutionParticipant(participant) {
    this.i.add(participant);
    return $1c(() => this.i.delete(participant));
  }
  async j(executions) {
    for (const participant of this.i) {
      await participant.onWillExecuteCell(executions);
    }
    return;
  }
  dispose() {
    this.a?.dispose(true);
  }
};
$_3b = __decorate([
  __param(0, $sn),
  __param(1, $CL),
  __param(2, $DL),
  __param(3, $5M),
  __param(4, $qFb),
  __param(5, $wL)
], $_3b);

// out-build/vs/workbench/contrib/notebook/common/notebookKeymapService.js
var $a4b = $Qk("notebookKeymapService");

// out-build/vs/workbench/contrib/extensions/common/extensionsUtils.js
var $b4b = class $b4b2 extends $3c {
  constructor(a, b, c, lifecycleService, f) {
    super();
    this.a = a;
    this.b = b;
    this.c = c;
    this.f = f;
    this.B(lifecycleService.onDidShutdown(() => this.dispose()));
    this.B(a.invokeFunction(onExtensionChanged)((identifiers2) => {
      Promise.all(identifiers2.map((identifier2) => this.g(identifier2))).then(void 0, $gb);
    }));
  }
  g(extensionIdentifier) {
    return this.a.invokeFunction($c4b).then((extensions) => {
      const keymaps = extensions.filter((extension2) => isKeymapExtension(this.c, extension2));
      const extension = keymaps.find((extension2) => $DA(extension2.identifier, extensionIdentifier));
      if (extension && extension.globallyEnabled) {
        const otherKeymaps = keymaps.filter((extension2) => !$DA(extension2.identifier, extensionIdentifier) && extension2.globallyEnabled);
        if (otherKeymaps.length) {
          return this.h(extension, otherKeymaps);
        }
      }
      return void 0;
    });
  }
  h(newKeymap, oldKeymaps) {
    const onPrompt = (confirmed) => {
      if (confirmed) {
        this.b.setEnablement(
          oldKeymaps.map((keymap) => keymap.local),
          8
          /* EnablementState.DisabledGlobally */
        );
      }
    };
    this.f.prompt(Severity2.Info, localize(6980, null, oldKeymaps.map((k) => `'${k.local.manifest.displayName}'`).join(", ")), [{
      label: localize(6981, null),
      run: () => onPrompt(true)
    }, {
      label: localize(6982, null),
      run: () => onPrompt(false)
    }]);
  }
};
$b4b = __decorate([
  __param(0, $Pk),
  __param(1, $qzb),
  __param(2, $ABb),
  __param(3, $KL),
  __param(4, $PJ)
], $b4b);
function onExtensionChanged(accessor) {
  const extensionService = accessor.get($sA);
  const extensionEnablementService = accessor.get($qzb);
  const onDidInstallExtensions = Event2.chain(extensionService.onDidInstallExtensions, ($149) => $149.filter((e) => e.some(
    ({ operation }) => operation === 2
    /* InstallOperation.Install */
  )).map((e) => e.map(({ identifier: identifier2 }) => identifier2)));
  return Event2.debounce(Event2.any(Event2.any(onDidInstallExtensions, Event2.map(extensionService.onDidUninstallExtension, (e) => [e.identifier])), Event2.map(extensionEnablementService.onEnablementChanged, (extensions) => extensions.map((e) => e.identifier))), (result, identifiers2) => {
    result = result || [];
    for (const identifier2 of identifiers2) {
      if (result.some((l) => !$DA(l, identifier2))) {
        result.push(identifier2);
      }
    }
    return result;
  });
}
async function $c4b(accessor) {
  const extensionService = accessor.get($sA);
  const extensionEnablementService = accessor.get($qzb);
  const extensions = await extensionService.getInstalled();
  return extensions.map((extension) => {
    return {
      identifier: extension.identifier,
      local: extension,
      globallyEnabled: extensionEnablementService.isEnabled(extension)
    };
  });
}
function isKeymapExtension(tipsService, extension) {
  const cats = extension.local.manifest.categories;
  return cats && cats.indexOf("Keymaps") !== -1 || tipsService.getKeymapRecommendations().some((extensionId) => $DA({ id: extensionId }, extension.local.identifier));
}

// out-build/vs/workbench/contrib/notebook/browser/services/notebookKeymapServiceImpl.js
function onExtensionChanged2(accessor) {
  const extensionService = accessor.get($sA);
  const extensionEnablementService = accessor.get($qzb);
  const onDidInstallExtensions = Event2.chain(extensionService.onDidInstallExtensions, ($149) => $149.filter((e) => e.some(
    ({ operation }) => operation === 2
    /* InstallOperation.Install */
  )).map((e) => e.map(({ identifier: identifier2 }) => identifier2)));
  return Event2.debounce(Event2.any(Event2.any(onDidInstallExtensions, Event2.map(extensionService.onDidUninstallExtension, (e) => [e.identifier])), Event2.map(extensionEnablementService.onEnablementChanged, (extensions) => extensions.map((e) => e.identifier))), (result, identifiers2) => {
    result = result || (identifiers2.length ? [identifiers2[0]] : []);
    for (const identifier2 of identifiers2) {
      if (result.some((l) => !$DA(l, identifier2))) {
        result.push(identifier2);
      }
    }
    return result;
  });
}
var hasRecommendedKeymapKey = "hasRecommendedKeymap";
var $d4b = class $d4b2 extends $3c {
  constructor(c, f, g, storageService, lifecycleService) {
    super();
    this.c = c;
    this.f = f;
    this.g = g;
    this.a = new $Slb("notebookKeymap", storageService);
    this.b = this.a.getMemento(
      0,
      0
      /* StorageTarget.USER */
    );
    this.B(lifecycleService.onDidShutdown(() => this.dispose()));
    this.B(this.c.invokeFunction(onExtensionChanged2)((identifiers2) => {
      Promise.all(identifiers2.map((identifier2) => this.h(identifier2))).then(void 0, $gb);
    }));
  }
  h(extensionIdentifier) {
    return this.c.invokeFunction($c4b).then((extensions) => {
      const keymaps = extensions.filter((extension2) => $e4b(extension2));
      const extension = keymaps.find((extension2) => $DA(extension2.identifier, extensionIdentifier));
      if (extension && extension.globallyEnabled) {
        this.b[hasRecommendedKeymapKey] = true;
        this.a.saveMemento();
        const otherKeymaps = keymaps.filter((extension2) => !$DA(extension2.identifier, extensionIdentifier) && extension2.globallyEnabled);
        if (otherKeymaps.length) {
          return this.j(extension, otherKeymaps);
        }
      }
      return void 0;
    });
  }
  j(newKeymap, oldKeymaps) {
    const onPrompt = (confirmed) => {
      if (confirmed) {
        this.f.setEnablement(
          oldKeymaps.map((keymap) => keymap.local),
          8
          /* EnablementState.DisabledGlobally */
        );
      }
    };
    this.g.prompt(Severity2.Info, localize(8572, null, $Rb(oldKeymaps.map((k) => k.local.manifest.displayName)).map((name) => `'${name}'`).join(", ")), [{
      label: localize(8573, null),
      run: () => onPrompt(true)
    }, {
      label: localize(8574, null),
      run: () => onPrompt(false)
    }]);
  }
};
$d4b = __decorate([
  __param(0, $Pk),
  __param(1, $qzb),
  __param(2, $PJ),
  __param(3, $jv),
  __param(4, $KL)
], $d4b);
function $e4b(extension) {
  if (extension.local.manifest.extensionPack) {
    return false;
  }
  const keywords = extension.local.manifest.keywords;
  if (!keywords) {
    return false;
  }
  return keywords.indexOf("notebook-keymap") !== -1;
}

// out-build/vs/workbench/contrib/notebook/browser/services/notebookKernelHistoryServiceImpl.js
var $f4b_1;
var MAX_KERNELS_IN_HISTORY = 5;
var $f4b = class $f4b2 extends $3c {
  static {
    $f4b_1 = this;
  }
  static {
    this.a = "notebook.kernelHistory";
  }
  constructor(c, f, g) {
    super();
    this.c = c;
    this.f = f;
    this.g = g;
    this.b = {};
    this.j();
    this.B(this.c.onWillSaveState(() => this.h()));
    this.B(this.c.onDidChangeValue(1, $f4b_1.a, this.q)(() => {
      this.j();
    }));
  }
  getKernels(notebook) {
    const allAvailableKernels = this.f.getMatchingKernel(notebook);
    const allKernels = allAvailableKernels.all;
    const selectedKernel = allAvailableKernels.selected;
    const suggested = allAvailableKernels.all.length === 1 ? allAvailableKernels.all[0] : void 0;
    this.g.debug("History", `getMatchingKernels: ${allAvailableKernels.all.length} kernels available for ${notebook.uri.path}. Selected: ${allAvailableKernels.selected?.label}. Suggested: ${suggested?.label}`);
    const mostRecentKernelIds = this.b[notebook.notebookType] ? [...this.b[notebook.notebookType].values()] : [];
    const all = mostRecentKernelIds.map((kernelId) => allKernels.find((kernel) => kernel.id === kernelId)).filter((kernel) => !!kernel);
    this.g.debug("History", `mru: ${mostRecentKernelIds.length} kernels in history, ${all.length} registered already.`);
    return {
      selected: selectedKernel ?? suggested,
      all
    };
  }
  addMostRecentKernel(kernel) {
    const key2 = kernel.id;
    const viewType = kernel.viewType;
    const recentKeynels = this.b[viewType] ?? new $Gc();
    recentKeynels.set(
      key2,
      key2,
      1
      /* Touch.AsOld */
    );
    if (recentKeynels.size > MAX_KERNELS_IN_HISTORY) {
      const reserved = [...recentKeynels.entries()].slice(0, MAX_KERNELS_IN_HISTORY);
      recentKeynels.fromJSON(reserved);
    }
    this.b[viewType] = recentKeynels;
  }
  h() {
    let notEmpty = false;
    for (const [_, kernels] of Object.entries(this.b)) {
      notEmpty = notEmpty || kernels.size > 0;
    }
    if (notEmpty) {
      const serialized = this.m();
      this.c.store(
        $f4b_1.a,
        JSON.stringify(serialized),
        1,
        0
        /* StorageTarget.USER */
      );
    } else {
      this.c.remove(
        $f4b_1.a,
        1
        /* StorageScope.WORKSPACE */
      );
    }
  }
  j() {
    const serialized = this.c.get(
      $f4b_1.a,
      1
      /* StorageScope.WORKSPACE */
    );
    if (serialized) {
      try {
        this.n(JSON.parse(serialized));
      } catch (e) {
        this.b = {};
      }
    } else {
      this.b = {};
    }
  }
  m() {
    const result = /* @__PURE__ */ Object.create(null);
    for (const [viewType, kernels] of Object.entries(this.b)) {
      result[viewType] = {
        entries: [...kernels.values()]
      };
    }
    return result;
  }
  n(serialized) {
    this.b = {};
    for (const [viewType, kernels] of Object.entries(serialized)) {
      const linkedMap = new $Gc();
      const mapValues = [];
      for (const entry of kernels.entries) {
        mapValues.push([entry, entry]);
      }
      linkedMap.fromJSON(mapValues);
      this.b[viewType] = linkedMap;
    }
  }
  _clear() {
    this.b = {};
    this.h();
  }
};
$f4b = $f4b_1 = __decorate([
  __param(0, $jv),
  __param(1, $CL),
  __param(2, $qFb)
], $f4b);
$hJ(class extends $gJ {
  constructor() {
    super({
      id: "notebook.clearNotebookKernelsMRUCache",
      title: localize2(8571, "Clear Notebook Kernels MRU Cache"),
      category: $qn.Developer,
      f1: true
    });
  }
  async run(accessor) {
    const historyService = accessor.get($DL);
    historyService._clear();
  }
});

// out-build/vs/workbench/contrib/notebook/browser/services/notebookLoggingServiceImpl.js
var logChannelId = "notebook.rendering";
var $g4b = class $g4b2 extends $3c {
  static {
    this.ID = "notebook";
  }
  constructor(loggerService) {
    super();
    this.a = this.B(loggerService.createLogger(logChannelId, { name: localize(8575, null) }));
  }
  debug(category8, output) {
    this.a.debug(`[${category8}] ${output}`);
  }
  info(category8, output) {
    this.a.info(`[${category8}] ${output}`);
  }
  warn(category8, output) {
    this.a.warn(`[${category8}] ${output}`);
  }
  error(category8, output) {
    this.a.error(`[${category8}] ${output}`);
  }
};
$g4b = __decorate([
  __param(0, $xn)
], $g4b);

// out-build/vs/workbench/contrib/notebook/browser/contrib/notebookVariables/notebookVariablesDataSource.js
var $h4b = class {
  constructor(b) {
    this.b = b;
    this.a = new $ad();
  }
  hasChildren(element) {
    return element.kind === "root" || element.hasNamedChildren || element.indexedChildrenCount > 0;
  }
  cancel() {
    this.a.cancel();
    this.a.dispose();
    this.a = new $ad();
  }
  async getChildren(element) {
    if (element.kind === "empty") {
      return [];
    } else if (element.kind === "root") {
      return this.e(element.notebook);
    } else {
      return this.c(element);
    }
  }
  async c(parent) {
    const selectedKernel = this.b.getMatchingKernel(parent.notebook).selected;
    if (selectedKernel && selectedKernel.hasVariableProvider) {
      let children = [];
      if (parent.hasNamedChildren) {
        const variables = selectedKernel.provideVariables(parent.notebook.uri, parent.extHostId, "named", 0, this.a.token);
        const childNodes = await variables.map((variable) => {
          return this.f(variable, parent.notebook);
        }).toPromise();
        children = children.concat(childNodes);
      }
      if (parent.indexedChildrenCount > 0) {
        const childNodes = await this.d(parent, selectedKernel);
        children = children.concat(childNodes);
      }
      return children;
    }
    return [];
  }
  async d(parent, kernel) {
    const childNodes = [];
    if (parent.indexedChildrenCount > $BL) {
      const nestedPageSize = Math.floor(Math.max(parent.indexedChildrenCount / $BL, 100));
      const indexedChildCountLimit = 1e6;
      let start = parent.indexStart ?? 0;
      const last = start + Math.min(parent.indexedChildrenCount, indexedChildCountLimit);
      for (; start < last; start += nestedPageSize) {
        let end = start + nestedPageSize;
        if (end > last) {
          end = last;
        }
        childNodes.push({
          kind: "variable",
          notebook: parent.notebook,
          id: parent.id + `${start}`,
          extHostId: parent.extHostId,
          name: `[${start}..${end - 1}]`,
          value: "",
          indexedChildrenCount: end - start,
          indexStart: start,
          hasNamedChildren: false
        });
      }
      if (parent.indexedChildrenCount > indexedChildCountLimit) {
        childNodes.push({
          kind: "variable",
          notebook: parent.notebook,
          id: parent.id + `${last + 1}`,
          extHostId: parent.extHostId,
          name: localize(8176, null),
          value: "",
          indexedChildrenCount: 0,
          hasNamedChildren: false
        });
      }
    } else if (parent.indexedChildrenCount > 0) {
      const variables = kernel.provideVariables(parent.notebook.uri, parent.extHostId, "indexed", parent.indexStart ?? 0, this.a.token);
      for await (const variable of variables) {
        childNodes.push(this.f(variable, parent.notebook));
        if (childNodes.length >= $BL) {
          break;
        }
      }
    }
    return childNodes;
  }
  async e(notebook) {
    const selectedKernel = this.b.getMatchingKernel(notebook).selected;
    if (selectedKernel && selectedKernel.hasVariableProvider) {
      const variables = selectedKernel.provideVariables(notebook.uri, void 0, "named", 0, this.a.token);
      return await variables.map((variable) => {
        return this.f(variable, notebook);
      }).toPromise();
    }
    return [];
  }
  f(variable, notebook) {
    return {
      ...variable,
      kind: "variable",
      notebook,
      extHostId: variable.id,
      id: `${variable.id}`
    };
  }
};

// out-build/vs/workbench/contrib/debug/common/replModel.js
var MAX_REPL_LENGTH = 1e4;
var topReplElementCounter = 0;
var getUniqueId = () => `topReplElement:${topReplElementCounter++}`;
var $i4b = class {
  constructor(session, c, value, severity, sourceData, expression) {
    this.session = session;
    this.c = c;
    this.value = value;
    this.severity = severity;
    this.sourceData = sourceData;
    this.expression = expression;
    this.a = 1;
    this.b = new $ze();
  }
  toString(includeSource = false) {
    let valueRespectCount = this.value;
    for (let i2 = 1; i2 < this.count; i2++) {
      valueRespectCount += (valueRespectCount.endsWith("\n") ? "" : "\n") + this.value;
    }
    const sourceStr = this.sourceData && includeSource ? ` ${this.sourceData.source.name}` : "";
    return valueRespectCount + sourceStr;
  }
  getId() {
    return this.c;
  }
  getChildren() {
    return this.expression?.getChildren() || Promise.resolve([]);
  }
  set count(value) {
    this.a = value;
    this.b.fire();
  }
  get count() {
    return this.a;
  }
  get onDidChangeCount() {
    return this.b.event;
  }
  get hasChildren() {
    return !!this.expression?.hasChildren;
  }
};
var $j4b = class {
  constructor(b, expression, severity, sourceData) {
    this.b = b;
    this.expression = expression;
    this.severity = severity;
    this.sourceData = sourceData;
    this.a = $ps();
    this.hasChildren = expression.hasChildren;
  }
  getSession() {
    return this.b;
  }
  getChildren() {
    return this.expression.getChildren();
  }
  toString() {
    return this.expression.toString();
  }
  getId() {
    return this.a;
  }
};
var $k4b = class _$k4b {
  static {
    this.a = 1e3;
  }
  // upper bound of children per value
  constructor(b, name, valueObj, sourceData, annotation) {
    this.b = b;
    this.name = name;
    this.valueObj = valueObj;
    this.sourceData = sourceData;
    this.annotation = annotation;
  }
  getId() {
    return this.b;
  }
  getSession() {
    return void 0;
  }
  get value() {
    if (this.valueObj === null) {
      return "null";
    } else if (Array.isArray(this.valueObj)) {
      return `Array[${this.valueObj.length}]`;
    } else if ($Bg(this.valueObj)) {
      return "Object";
    } else if ($zg(this.valueObj)) {
      return `"${this.valueObj}"`;
    }
    return String(this.valueObj) || "";
  }
  get hasChildren() {
    return Array.isArray(this.valueObj) && this.valueObj.length > 0 || $Bg(this.valueObj) && Object.getOwnPropertyNames(this.valueObj).length > 0;
  }
  evaluateLazy() {
    throw new Error("Method not implemented.");
  }
  getChildren() {
    let result = [];
    if (Array.isArray(this.valueObj)) {
      result = this.valueObj.slice(0, _$k4b.a).map((v, index) => new _$k4b(`${this.b}:${index}`, String(index), v));
    } else if ($Bg(this.valueObj)) {
      result = Object.getOwnPropertyNames(this.valueObj).slice(0, _$k4b.a).map((key2, index) => new _$k4b(`${this.b}:${index}`, key2, this.valueObj[key2]));
    }
    return Promise.resolve(result);
  }
  toString() {
    return `${this.name}
${this.value}`;
  }
};
var $l4b = class {
  constructor(value) {
    this.value = value;
    this.a = $ps();
  }
  toString() {
    return this.value;
  }
  getId() {
    return this.a;
  }
};
var $m4b = class extends $JP {
  get available() {
    return this.t;
  }
  constructor(originalExpression) {
    super(void 0, void 0, 0, $ps());
    this.originalExpression = originalExpression;
    this.t = true;
  }
  async evaluateExpression(expression, session, stackFrame, context) {
    const result = await super.evaluateExpression(expression, session, stackFrame, context);
    this.t = result;
    return result;
  }
  toString() {
    return `${this.value}`;
  }
};
var $n4b = class _$n4b {
  static {
    this.COUNTER = 0;
  }
  constructor(session, name, autoExpand, sourceData) {
    this.session = session;
    this.name = name;
    this.autoExpand = autoExpand;
    this.sourceData = sourceData;
    this.a = [];
    this.c = false;
    this.b = `replGroup:${_$n4b.COUNTER++}`;
  }
  get hasChildren() {
    return true;
  }
  getId() {
    return this.b;
  }
  toString(includeSource = false) {
    const sourceStr = includeSource && this.sourceData ? ` ${this.sourceData.source.name}` : "";
    return this.name + sourceStr;
  }
  addChild(child) {
    const lastElement = this.a.length ? this.a[this.a.length - 1] : void 0;
    if (lastElement instanceof _$n4b && !lastElement.hasEnded) {
      lastElement.addChild(child);
    } else {
      this.a.push(child);
    }
  }
  getChildren() {
    return this.a;
  }
  end() {
    const lastElement = this.a.length ? this.a[this.a.length - 1] : void 0;
    if (lastElement instanceof _$n4b && !lastElement.hasEnded) {
      lastElement.end();
    } else {
      this.c = true;
    }
  }
  get hasEnded() {
    return this.c;
  }
};
function areSourcesEqual(first, second) {
  if (!first && !second) {
    return true;
  }
  if (first && second) {
    return first.column === second.column && first.lineNumber === second.lineNumber && first.source.uri.toString() === second.source.uri.toString();
  }
  return false;
}
var $o4b = class _$o4b {
  constructor(c) {
    this.c = c;
    this.a = [];
    this.b = new $ze();
    this.onDidChangeElements = this.b.event;
  }
  getReplElements() {
    return this.a;
  }
  async addReplExpression(session, stackFrame, expression) {
    this.d(new $l4b(expression));
    const result = new $m4b(expression);
    await result.evaluateExpression(expression, session, stackFrame, "repl");
    this.d(result);
  }
  appendToRepl(session, { output, expression, sev, source }) {
    const clearAnsiSequence = "\x1B[2J";
    const clearAnsiIndex = output.lastIndexOf(clearAnsiSequence);
    if (clearAnsiIndex !== -1) {
      this.removeReplExpressions();
      this.appendToRepl(session, { output: localize(6239, null), sev: severity_default.Ignore });
      output = output.substring(clearAnsiIndex + clearAnsiSequence.length);
    }
    if (expression) {
      this.d(output ? new $i4b(session, getUniqueId(), output, sev, source, expression) : new $j4b(session, expression, sev, source));
      return;
    }
    const previousElement = this.a.length ? this.a[this.a.length - 1] : void 0;
    if (previousElement instanceof $i4b && previousElement.severity === sev) {
      const config = this.c.getValue("debug");
      if (previousElement.value === output && areSourcesEqual(previousElement.sourceData, source) && config.console.collapseIdenticalLines) {
        previousElement.count++;
        return;
      }
      if (!previousElement.value.endsWith("\n") && !previousElement.value.endsWith("\r\n") && previousElement.count === 1) {
        this.a[this.a.length - 1] = new $i4b(session, getUniqueId(), previousElement.value + output, sev, source);
        this.b.fire(void 0);
        return;
      }
    }
    const element = new $i4b(session, getUniqueId(), output, sev, source);
    this.d(element);
  }
  startGroup(session, name, autoExpand, sourceData) {
    const group2 = new $n4b(session, name, autoExpand, sourceData);
    this.d(group2);
  }
  endGroup() {
    const lastElement = this.a[this.a.length - 1];
    if (lastElement instanceof $n4b) {
      lastElement.end();
    }
  }
  d(newElement) {
    const lastElement = this.a.length ? this.a[this.a.length - 1] : void 0;
    if (lastElement instanceof $n4b && !lastElement.hasEnded) {
      lastElement.addChild(newElement);
    } else {
      this.a.push(newElement);
      if (this.a.length > MAX_REPL_LENGTH) {
        this.a.splice(0, this.a.length - MAX_REPL_LENGTH);
      }
    }
    this.b.fire(newElement);
  }
  removeReplExpressions() {
    if (this.a.length > 0) {
      this.a = [];
      this.b.fire(void 0);
    }
  }
  /** Returns a new REPL model that's a copy of this one. */
  clone() {
    const newRepl = new _$o4b(this.c);
    newRepl.a = this.a.slice();
    return newRepl;
  }
};

// out-build/vs/workbench/contrib/debug/browser/debugANSIHandling.js
function $t4b(text2, linkDetector, workspaceFolder) {
  const root = document.createElement("span");
  const textLength = text2.length;
  let styleNames = [];
  let customFgColor;
  let customBgColor;
  let customUnderlineColor;
  let colorsInverted = false;
  let currentPos = 0;
  let buffer = "";
  while (currentPos < textLength) {
    let sequenceFound = false;
    if (text2.charCodeAt(currentPos) === 27 && text2.charAt(currentPos + 1) === "[") {
      const startPos = currentPos;
      currentPos += 2;
      let ansiSequence = "";
      while (currentPos < textLength) {
        const char = text2.charAt(currentPos);
        ansiSequence += char;
        currentPos++;
        if (char.match(/^[ABCDHIJKfhmpsu]$/)) {
          sequenceFound = true;
          break;
        }
      }
      if (sequenceFound) {
        $u4b(root, buffer, styleNames, linkDetector, workspaceFolder, customFgColor, customBgColor, customUnderlineColor);
        buffer = "";
        if (ansiSequence.match(/^(?:[34][0-8]|9[0-7]|10[0-7]|[0-9]|2[1-5,7-9]|[34]9|5[8,9]|1[0-9])(?:;[349][0-7]|10[0-7]|[013]|[245]|[34]9)?(?:;[012]?[0-9]?[0-9])*;?m$/)) {
          const styleCodes = ansiSequence.slice(0, -1).split(";").filter((elem) => elem !== "").map((elem) => parseInt(elem, 10));
          if (styleCodes[0] === 38 || styleCodes[0] === 48 || styleCodes[0] === 58) {
            const colorType = styleCodes[0] === 38 ? "foreground" : styleCodes[0] === 48 ? "background" : "underline";
            if (styleCodes[1] === 5) {
              set8BitColor(styleCodes, colorType);
            } else if (styleCodes[1] === 2) {
              set24BitColor(styleCodes, colorType);
            }
          } else {
            setBasicFormatters(styleCodes);
          }
        } else {
        }
      } else {
        currentPos = startPos;
      }
    }
    if (sequenceFound === false) {
      buffer += text2.charAt(currentPos);
      currentPos++;
    }
  }
  if (buffer) {
    $u4b(root, buffer, styleNames, linkDetector, workspaceFolder, customFgColor, customBgColor, customUnderlineColor);
  }
  return root;
  function changeColor(colorType, color2) {
    if (colorType === "foreground") {
      customFgColor = color2;
    } else if (colorType === "background") {
      customBgColor = color2;
    } else if (colorType === "underline") {
      customUnderlineColor = color2;
    }
    styleNames = styleNames.filter((style) => style !== `code-${colorType}-colored`);
    if (color2 !== void 0) {
      styleNames.push(`code-${colorType}-colored`);
    }
  }
  function reverseForegroundAndBackgroundColors() {
    const oldFgColor = customFgColor;
    changeColor("foreground", customBgColor);
    changeColor("background", oldFgColor);
  }
  function setBasicFormatters(styleCodes) {
    for (const code of styleCodes) {
      switch (code) {
        case 0: {
          styleNames = [];
          customFgColor = void 0;
          customBgColor = void 0;
          break;
        }
        case 1: {
          styleNames = styleNames.filter((style) => style !== `code-bold`);
          styleNames.push("code-bold");
          break;
        }
        case 2: {
          styleNames = styleNames.filter((style) => style !== `code-dim`);
          styleNames.push("code-dim");
          break;
        }
        case 3: {
          styleNames = styleNames.filter((style) => style !== `code-italic`);
          styleNames.push("code-italic");
          break;
        }
        case 4: {
          styleNames = styleNames.filter((style) => style !== `code-underline` && style !== `code-double-underline`);
          styleNames.push("code-underline");
          break;
        }
        case 5: {
          styleNames = styleNames.filter((style) => style !== `code-blink`);
          styleNames.push("code-blink");
          break;
        }
        case 6: {
          styleNames = styleNames.filter((style) => style !== `code-rapid-blink`);
          styleNames.push("code-rapid-blink");
          break;
        }
        case 7: {
          if (!colorsInverted) {
            colorsInverted = true;
            reverseForegroundAndBackgroundColors();
          }
          break;
        }
        case 8: {
          styleNames = styleNames.filter((style) => style !== `code-hidden`);
          styleNames.push("code-hidden");
          break;
        }
        case 9: {
          styleNames = styleNames.filter((style) => style !== `code-strike-through`);
          styleNames.push("code-strike-through");
          break;
        }
        case 10: {
          styleNames = styleNames.filter((style) => !style.startsWith("code-font"));
          break;
        }
        case 11:
        case 12:
        case 13:
        case 14:
        case 15:
        case 16:
        case 17:
        case 18:
        case 19:
        case 20: {
          styleNames = styleNames.filter((style) => !style.startsWith("code-font"));
          styleNames.push(`code-font-${code - 10}`);
          break;
        }
        case 21: {
          styleNames = styleNames.filter((style) => style !== `code-underline` && style !== `code-double-underline`);
          styleNames.push("code-double-underline");
          break;
        }
        case 22: {
          styleNames = styleNames.filter((style) => style !== `code-bold` && style !== `code-dim`);
          break;
        }
        case 23: {
          styleNames = styleNames.filter((style) => style !== `code-italic` && style !== `code-font-10`);
          break;
        }
        case 24: {
          styleNames = styleNames.filter((style) => style !== `code-underline` && style !== `code-double-underline`);
          break;
        }
        case 25: {
          styleNames = styleNames.filter((style) => style !== `code-blink` && style !== `code-rapid-blink`);
          break;
        }
        case 27: {
          if (colorsInverted) {
            colorsInverted = false;
            reverseForegroundAndBackgroundColors();
          }
          break;
        }
        case 28: {
          styleNames = styleNames.filter((style) => style !== `code-hidden`);
          break;
        }
        case 29: {
          styleNames = styleNames.filter((style) => style !== `code-strike-through`);
          break;
        }
        case 53: {
          styleNames = styleNames.filter((style) => style !== `code-overline`);
          styleNames.push("code-overline");
          break;
        }
        case 55: {
          styleNames = styleNames.filter((style) => style !== `code-overline`);
          break;
        }
        case 39: {
          changeColor("foreground", void 0);
          break;
        }
        case 49: {
          changeColor("background", void 0);
          break;
        }
        case 59: {
          changeColor("underline", void 0);
          break;
        }
        case 73: {
          styleNames = styleNames.filter((style) => style !== `code-superscript` && style !== `code-subscript`);
          styleNames.push("code-superscript");
          break;
        }
        case 74: {
          styleNames = styleNames.filter((style) => style !== `code-superscript` && style !== `code-subscript`);
          styleNames.push("code-subscript");
          break;
        }
        case 75: {
          styleNames = styleNames.filter((style) => style !== `code-superscript` && style !== `code-subscript`);
          break;
        }
        default: {
          setBasicColor(code);
          break;
        }
      }
    }
  }
  function set24BitColor(styleCodes, colorType) {
    if (styleCodes.length >= 5 && styleCodes[2] >= 0 && styleCodes[2] <= 255 && styleCodes[3] >= 0 && styleCodes[3] <= 255 && styleCodes[4] >= 0 && styleCodes[4] <= 255) {
      const customColor = new $Sn(styleCodes[2], styleCodes[3], styleCodes[4]);
      changeColor(colorType, customColor);
    }
  }
  function set8BitColor(styleCodes, colorType) {
    let colorNumber = styleCodes[2];
    const color2 = $v4b(colorNumber);
    if (color2) {
      changeColor(colorType, color2);
    } else if (colorNumber >= 0 && colorNumber <= 15) {
      if (colorType === "underline") {
        const colorName = $0Ob[colorNumber];
        changeColor(colorType, `--vscode-debug-ansi-${colorName}`);
        return;
      }
      colorNumber += 30;
      if (colorNumber >= 38) {
        colorNumber += 52;
      }
      if (colorType === "background") {
        colorNumber += 10;
      }
      setBasicColor(colorNumber);
    }
  }
  function setBasicColor(styleCode) {
    let colorType;
    let colorIndex;
    if (styleCode >= 30 && styleCode <= 37) {
      colorIndex = styleCode - 30;
      colorType = "foreground";
    } else if (styleCode >= 90 && styleCode <= 97) {
      colorIndex = styleCode - 90 + 8;
      colorType = "foreground";
    } else if (styleCode >= 40 && styleCode <= 47) {
      colorIndex = styleCode - 40;
      colorType = "background";
    } else if (styleCode >= 100 && styleCode <= 107) {
      colorIndex = styleCode - 100 + 8;
      colorType = "background";
    }
    if (colorIndex !== void 0 && colorType) {
      const colorName = $0Ob[colorIndex];
      changeColor(colorType, `--vscode-debug-ansi-${colorName.replaceAll(".", "-")}`);
    }
  }
}
function $u4b(root, stringContent, cssClasses, linkDetector, workspaceFolder, customTextColor, customBackgroundColor, customUnderlineColor) {
  if (!root || !stringContent) {
    return;
  }
  const container2 = linkDetector.linkify(stringContent, true, workspaceFolder);
  container2.className = cssClasses.join(" ");
  if (customTextColor) {
    container2.style.color = typeof customTextColor === "string" ? `var(${customTextColor})` : $Vn.Format.CSS.formatRGB(new $Vn(customTextColor));
  }
  if (customBackgroundColor) {
    container2.style.backgroundColor = typeof customBackgroundColor === "string" ? `var(${customBackgroundColor})` : $Vn.Format.CSS.formatRGB(new $Vn(customBackgroundColor));
  }
  if (customUnderlineColor) {
    container2.style.textDecorationColor = typeof customUnderlineColor === "string" ? `var(${customUnderlineColor})` : $Vn.Format.CSS.formatRGB(new $Vn(customUnderlineColor));
  }
  root.appendChild(container2);
}
function $v4b(colorNumber) {
  if (colorNumber % 1 !== 0) {
    return;
  }
  if (colorNumber >= 16 && colorNumber <= 231) {
    colorNumber -= 16;
    let blue = colorNumber % 6;
    colorNumber = (colorNumber - blue) / 6;
    let green = colorNumber % 6;
    colorNumber = (colorNumber - green) / 6;
    let red = colorNumber;
    const convFactor = 255 / 5;
    blue = Math.round(blue * convFactor);
    green = Math.round(green * convFactor);
    red = Math.round(red * convFactor);
    return new $Sn(red, green, blue);
  } else if (colorNumber >= 232 && colorNumber <= 255) {
    colorNumber -= 232;
    const colorLevel = Math.round(colorNumber / 23 * 255);
    return new $Sn(colorLevel, colorLevel, colorLevel);
  } else {
    return;
  }
}
$ms((theme, collector) => {
  const areas = [
    { selector: ".monaco-workbench .sidebar, .monaco-workbench .auxiliarybar", bg: theme.getColor($Pnb) },
    { selector: ".monaco-workbench .panel", bg: theme.getColor($Imb) },
    { selector: ".monaco-workbench .monaco-list-row.selected", bg: theme.getColor($lr) },
    { selector: ".monaco-workbench .monaco-list-row.focused", bg: theme.getColor($or) },
    { selector: ".monaco-workbench .monaco-list:focus .monaco-list-row.focused", bg: theme.getColor($er) },
    { selector: ".monaco-workbench .monaco-list:focus .monaco-list-row.selected", bg: theme.getColor($ir) },
    { selector: ".debug-hover-widget", bg: theme.getColor($jp) }
  ];
  for (const { selector, bg } of areas) {
    const content = $0Ob.map((color2) => {
      const actual = theme.getColor(color2);
      if (!actual) {
        return void 0;
      }
      return `--vscode-debug-ansi-${color2.replaceAll(".", "-")}:${bg ? bg.ensureConstrast(actual, 4) : actual}`;
    }).filter($Hg);
    collector.addRule(`${selector} { ${content.join(";")} }`);
  }
});

// out-build/vs/workbench/contrib/debug/common/loadedScriptsPicker.js
async function $w4b(accessor) {
  const quickInputService = accessor.get($1M);
  const debugService = accessor.get($0R);
  const editorService = accessor.get($mJ);
  const sessions = debugService.getModel().getSessions(false);
  const modelService = accessor.get($sG);
  const languageService = accessor.get($1E);
  const labelService = accessor.get($ZI);
  const localDisposableStore = new $2c();
  const quickPick = quickInputService.createQuickPick({ useSeparators: true });
  localDisposableStore.add(quickPick);
  quickPick.matchOnLabel = quickPick.matchOnDescription = quickPick.matchOnDetail = quickPick.sortByLabel = false;
  quickPick.placeholder = localize(6238, null);
  quickPick.items = await _getPicks(quickPick.value, sessions, editorService, modelService, languageService, labelService);
  localDisposableStore.add(quickPick.onDidChangeValue(async () => {
    quickPick.items = await _getPicks(quickPick.value, sessions, editorService, modelService, languageService, labelService);
  }));
  localDisposableStore.add(quickPick.onDidAccept(() => {
    const selectedItem = quickPick.selectedItems[0];
    selectedItem.accept();
    quickPick.hide();
    localDisposableStore.dispose();
  }));
  quickPick.show();
}
async function _getPicksFromSession(session, filter, editorService, modelService, languageService, labelService) {
  const items = [];
  items.push({ type: "separator", label: session.name });
  const sources = await session.getLoadedSources();
  sources.forEach((element) => {
    const pick = _createPick(element, filter, editorService, modelService, languageService, labelService);
    if (pick) {
      items.push(pick);
    }
  });
  return items;
}
async function _getPicks(filter, sessions, editorService, modelService, languageService, labelService) {
  const loadedScriptPicks = [];
  const picks = await Promise.all(sessions.map((session) => _getPicksFromSession(session, filter, editorService, modelService, languageService, labelService)));
  for (const row of picks) {
    for (const elem of row) {
      loadedScriptPicks.push(elem);
    }
  }
  return loadedScriptPicks;
}
function _createPick(source, filter, editorService, modelService, languageService, labelService) {
  const label3 = labelService.getUriBasenameLabel(source.uri);
  const desc = labelService.getUriLabel($uh(source.uri));
  const labelHighlights = $Rl(filter, label3, true);
  const descHighlights = $Rl(filter, desc, true);
  if (labelHighlights || descHighlights) {
    return {
      label: label3,
      description: desc === "." ? void 0 : desc,
      highlights: { label: labelHighlights ?? void 0, description: descHighlights ?? void 0 },
      iconClasses: $gdb(modelService, languageService, source.uri),
      accept: () => {
        if (source.available) {
          source.openInEditor(editorService, { startLineNumber: 0, startColumn: 0, endLineNumber: 0, endColumn: 0 });
        }
      }
    };
  }
  return void 0;
}

// out-build/vs/workbench/contrib/debug/browser/debugSessionPicker.js
async function $x4b(accessor, selectAndStartID) {
  const quickInputService = accessor.get($1M);
  const debugService = accessor.get($0R);
  const viewsService = accessor.get($uob);
  const commandService = accessor.get($sn);
  const localDisposableStore = new $2c();
  const quickPick = quickInputService.createQuickPick({ useSeparators: true });
  localDisposableStore.add(quickPick);
  quickPick.matchOnLabel = quickPick.matchOnDescription = quickPick.matchOnDetail = quickPick.sortByLabel = false;
  quickPick.placeholder = localize(5967, null);
  const pickItems = _getPicksAndActiveItem(quickPick.value, selectAndStartID, debugService, viewsService, commandService);
  quickPick.items = pickItems.picks;
  quickPick.activeItems = pickItems.activeItems;
  localDisposableStore.add(quickPick.onDidChangeValue(async () => {
    quickPick.items = _getPicksAndActiveItem(quickPick.value, selectAndStartID, debugService, viewsService, commandService).picks;
  }));
  localDisposableStore.add(quickPick.onDidAccept(() => {
    const selectedItem = quickPick.selectedItems[0];
    selectedItem.accept();
    quickPick.hide();
    localDisposableStore.dispose();
  }));
  quickPick.show();
}
function _getPicksAndActiveItem(filter, selectAndStartID, debugService, viewsService, commandService) {
  const debugConsolePicks = [];
  const headerSessions = [];
  const currSession = debugService.getViewModel().focusedSession;
  const sessions = debugService.getModel().getSessions(false);
  const activeItems = [];
  sessions.forEach((session) => {
    if (session.compact && session.parentSession) {
      headerSessions.push(session.parentSession);
    }
  });
  sessions.forEach((session) => {
    const isHeader = headerSessions.includes(session);
    if (!session.parentSession) {
      debugConsolePicks.push({ type: "separator", label: isHeader ? session.name : void 0 });
    }
    if (!isHeader) {
      const pick = _createPick2(session, filter, debugService, viewsService, commandService);
      if (pick) {
        debugConsolePicks.push(pick);
        if (session.getId() === currSession?.getId()) {
          activeItems.push(pick);
        }
      }
    }
  });
  if (debugConsolePicks.length) {
    debugConsolePicks.push({ type: "separator" });
  }
  const createDebugSessionLabel = localize(5968, null);
  debugConsolePicks.push({
    label: `$(plus) ${createDebugSessionLabel}`,
    ariaLabel: createDebugSessionLabel,
    accept: () => commandService.executeCommand(selectAndStartID)
  });
  return { picks: debugConsolePicks, activeItems };
}
function _getSessionInfo(session) {
  const label3 = !session.configuration.name.length ? session.name : session.configuration.name;
  const parentName = session.compact ? void 0 : session.parentSession?.configuration.name;
  let description = "";
  let ariaLabel = "";
  if (parentName) {
    ariaLabel = localize(5969, null, label3, parentName);
    description = parentName;
  }
  return { label: label3, description, ariaLabel };
}
function _createPick2(session, filter, debugService, viewsService, commandService) {
  const pickInfo = _getSessionInfo(session);
  const highlights = $Rl(filter, pickInfo.label, true);
  if (highlights) {
    return {
      label: pickInfo.label,
      description: pickInfo.description,
      ariaLabel: pickInfo.ariaLabel,
      highlights: { label: highlights },
      accept: () => {
        debugService.focusStackFrame(void 0, void 0, session, { explicit: true });
        if (!viewsService.isViewVisible($2Q)) {
          viewsService.openView($2Q, true);
        }
      }
    };
  }
  return void 0;
}

// out-build/vs/workbench/contrib/debug/browser/debugCommands.js
var $y4b = "debug.addConfiguration";
var $z4b = "editor.debug.action.toggleInlineBreakpoint";
var $A4b = "debug.copyStackTrace";
var $B4b = "workbench.action.debug.reverseContinue";
var $C4b = "workbench.action.debug.stepBack";
var $D4b = "workbench.action.debug.restart";
var $E4b = "workbench.action.debug.terminateThread";
var $F4b = "workbench.action.debug.stepOver";
var $G4b = "workbench.action.debug.stepInto";
var $H4b = "workbench.action.debug.stepIntoTarget";
var $I4b = "workbench.action.debug.stepOut";
var $J4b = "workbench.action.debug.pause";
var $K4b = "workbench.action.debug.disconnect";
var $L4b = "workbench.action.debug.disconnectAndSuspend";
var $M4b = "workbench.action.debug.stop";
var $N4b = "workbench.action.debug.restartFrame";
var $O4b = "workbench.action.debug.continue";
var $P4b = "workbench.debug.action.focusRepl";
var $Q4b = "debug.jumpToCursor";
var $R4b = "workbench.action.debug.focusProcess";
var $S4b = "workbench.action.debug.selectandstart";
var $T4b = "workbench.action.debug.selectDebugConsole";
var $U4b = "workbench.action.debug.selectDebugSession";
var $V4b = "workbench.action.debug.configure";
var $W4b = "workbench.action.debug.start";
var $X4b = "workbench.action.debug.run";
var $Y4b = "debug.renameWatchExpression";
var $Z4b = "debug.setWatchExpression";
var $14b = "debug.removeWatchExpression";
var $24b = "workbench.action.debug.nextConsole";
var $34b = "workbench.action.debug.prevConsole";
var $44b = "workbench.action.debug.showLoadedScripts";
var $54b = "workbench.action.debug.callStackTop";
var $64b = "workbench.action.debug.callStackBottom";
var $74b = "workbench.action.debug.callStackUp";
var $84b = "workbench.action.debug.callStackDown";
var $94b = "debug.addToWatchExpressions";
var $04b = "debug.copyEvaluatePath";
var $$4b = "workbench.debug.viewlet.action.copyValue";
var $_4b = localize2(5774, "Debug");
var $a5b = localize2(5775, "Restart");
var $b5b = localize2(5776, "Step Over");
var $c5b = localize2(5777, "Step Into");
var $d5b = localize2(5778, "Step Into Target");
var $e5b = localize2(5779, "Step Out");
var $f5b = localize2(5780, "Pause");
var $g5b = localize2(5781, "Disconnect");
var $h5b = localize2(5782, "Disconnect and Suspend");
var $i5b = localize2(5783, "Stop");
var $j5b = localize2(5784, "Continue");
var $k5b = localize2(5785, "Focus Session");
var $l5b = localize2(5786, "Select and Start Debugging");
var $m5b = localize(5768, null, "launch.json");
var $n5b = localize2(5787, "Start Debugging");
var $o5b = localize2(5788, "Start Without Debugging");
var $p5b = localize2(5789, "Focus Next Debug Console");
var $q5b = localize2(5790, "Focus Previous Debug Console");
var $r5b = localize2(5791, "Open Loaded Script...");
var $s5b = localize2(5792, "Navigate to Top of Call Stack");
var $t5b = localize2(5793, "Navigate to Bottom of Call Stack");
var $u5b = localize2(5794, "Navigate Up Call Stack");
var $v5b = localize2(5795, "Navigate Down Call Stack");
var $w5b = localize2(5796, "Copy as Expression");
var $x5b = localize2(5797, "Copy Value");
var $y5b = localize2(5798, "Add to Watch");
var $z5b = localize2(5799, "Select Debug Console");
var $A5b = localize2(5800, "Select Debug Session");
var $B5b = "debug ";
var $C5b = "debug consoles ";
function isThreadContext(obj) {
  return obj && typeof obj.sessionId === "string" && typeof obj.threadId === "string";
}
async function getThreadAndRun(accessor, sessionAndThreadId, run) {
  const debugService = accessor.get($0R);
  let thread;
  if (isThreadContext(sessionAndThreadId)) {
    const session = debugService.getModel().getSession(sessionAndThreadId.sessionId);
    if (session) {
      thread = session.getAllThreads().find((t) => t.getId() === sessionAndThreadId.threadId);
    }
  } else if (isSessionContext(sessionAndThreadId)) {
    const session = debugService.getModel().getSession(sessionAndThreadId.sessionId);
    if (session) {
      const threads = session.getAllThreads();
      thread = threads.length > 0 ? threads[0] : void 0;
    }
  }
  if (!thread) {
    thread = debugService.getViewModel().focusedThread;
    if (!thread) {
      const focusedSession = debugService.getViewModel().focusedSession;
      const threads = focusedSession ? focusedSession.getAllThreads() : void 0;
      thread = threads && threads.length ? threads[0] : void 0;
    }
  }
  if (thread) {
    await run(thread);
  }
}
function isStackFrameContext(obj) {
  return obj && typeof obj.sessionId === "string" && typeof obj.threadId === "string" && typeof obj.frameId === "string";
}
function getFrame(debugService, context) {
  if (isStackFrameContext(context)) {
    const session = debugService.getModel().getSession(context.sessionId);
    if (session) {
      const thread = session.getAllThreads().find((t) => t.getId() === context.threadId);
      if (thread) {
        return thread.getCallStack().find((sf) => sf.getId() === context.frameId);
      }
    }
  } else {
    return debugService.getViewModel().focusedStackFrame;
  }
  return void 0;
}
function isSessionContext(obj) {
  return obj && typeof obj.sessionId === "string";
}
async function changeDebugConsoleFocus(accessor, next) {
  const debugService = accessor.get($0R);
  const viewsService = accessor.get($uob);
  const sessions = debugService.getModel().getSessions(true).filter((s) => s.hasSeparateRepl());
  let currSession = debugService.getViewModel().focusedSession;
  let nextIndex = 0;
  if (sessions.length > 0 && currSession) {
    while (currSession && !currSession.hasSeparateRepl()) {
      currSession = currSession.parentSession;
    }
    if (currSession) {
      const currIndex = sessions.indexOf(currSession);
      if (next) {
        nextIndex = currIndex === sessions.length - 1 ? 0 : currIndex + 1;
      } else {
        nextIndex = currIndex === 0 ? sessions.length - 1 : currIndex - 1;
      }
    }
  }
  await debugService.focusStackFrame(void 0, void 0, sessions[nextIndex], { explicit: true });
  if (!viewsService.isViewVisible($2Q)) {
    await viewsService.openView($2Q, true);
  }
}
async function navigateCallStack(debugService, down) {
  const frame = debugService.getViewModel().focusedStackFrame;
  if (frame) {
    let callStack = frame.thread.getCallStack();
    let index = callStack.findIndex((elem) => elem.frameId === frame.frameId);
    let nextVisibleFrame;
    if (down) {
      if (index >= callStack.length - 1) {
        if (frame.thread.reachedEndOfCallStack) {
          goToTopOfCallStack(debugService);
          return;
        } else {
          await debugService.getModel().fetchCallstack(frame.thread, 20);
          callStack = frame.thread.getCallStack();
          index = callStack.findIndex((elem) => elem.frameId === frame.frameId);
        }
      }
      nextVisibleFrame = findNextVisibleFrame(true, callStack, index);
    } else {
      if (index <= 0) {
        goToBottomOfCallStack(debugService);
        return;
      }
      nextVisibleFrame = findNextVisibleFrame(false, callStack, index);
    }
    if (nextVisibleFrame) {
      debugService.focusStackFrame(nextVisibleFrame, void 0, void 0, { preserveFocus: false });
    }
  }
}
async function goToBottomOfCallStack(debugService) {
  const thread = debugService.getViewModel().focusedThread;
  if (thread) {
    await debugService.getModel().fetchCallstack(thread);
    const callStack = thread.getCallStack();
    if (callStack.length > 0) {
      const nextVisibleFrame = findNextVisibleFrame(false, callStack, 0);
      if (nextVisibleFrame) {
        debugService.focusStackFrame(nextVisibleFrame, void 0, void 0, { preserveFocus: false });
      }
    }
  }
}
function goToTopOfCallStack(debugService) {
  const thread = debugService.getViewModel().focusedThread;
  if (thread) {
    debugService.focusStackFrame(thread.getTopStackFrame(), void 0, void 0, { preserveFocus: false });
  }
}
function findNextVisibleFrame(down, callStack, startIndex) {
  if (startIndex >= callStack.length) {
    startIndex = callStack.length - 1;
  } else if (startIndex < 0) {
    startIndex = 0;
  }
  let index = startIndex;
  let currFrame;
  do {
    if (down) {
      if (index === callStack.length - 1) {
        index = 0;
      } else {
        index++;
      }
    } else {
      if (index === 0) {
        index = callStack.length - 1;
      } else {
        index--;
      }
    }
    currFrame = callStack[index];
    if (!$9R(currFrame)) {
      return currFrame;
    }
  } while (index !== startIndex);
  return void 0;
}
$tn.registerCommand({
  id: $A4b,
  handler: async (accessor, _, context) => {
    const textResourcePropertiesService = accessor.get($AG);
    const clipboardService = accessor.get($30);
    const debugService = accessor.get($0R);
    const frame = getFrame(debugService, context);
    if (frame) {
      const eol = textResourcePropertiesService.getEOL(frame.source.uri);
      await clipboardService.writeText(frame.thread.getCallStack().map((sf) => sf.toString()).join(eol));
    }
  }
});
$tn.registerCommand({
  id: $B4b,
  handler: async (accessor, _, context) => {
    await getThreadAndRun(accessor, context, (thread) => thread.reverseContinue());
  }
});
$tn.registerCommand({
  id: $C4b,
  handler: async (accessor, _, context) => {
    const contextKeyService = accessor.get($on);
    if ($YR.getValue(contextKeyService)) {
      await getThreadAndRun(accessor, context, (thread) => thread.stepBack("instruction"));
    } else {
      await getThreadAndRun(accessor, context, (thread) => thread.stepBack());
    }
  }
});
$tn.registerCommand({
  id: $E4b,
  handler: async (accessor, _, context) => {
    await getThreadAndRun(accessor, context, (thread) => thread.terminate());
  }
});
$tn.registerCommand({
  id: $Q4b,
  handler: async (accessor) => {
    const debugService = accessor.get($0R);
    const stackFrame = debugService.getViewModel().focusedStackFrame;
    const editorService = accessor.get($mJ);
    const activeEditorControl = editorService.activeTextEditorControl;
    const notificationService = accessor.get($PJ);
    const quickInputService = accessor.get($1M);
    if (stackFrame && $P5(activeEditorControl) && activeEditorControl.hasModel()) {
      const position = activeEditorControl.getPosition();
      const resource = activeEditorControl.getModel().uri;
      const source = stackFrame.thread.session.getSourceForUri(resource);
      if (source) {
        const response = await stackFrame.thread.session.gotoTargets(source.raw, position.lineNumber, position.column);
        const targets = response?.body.targets;
        if (targets && targets.length) {
          let id2 = targets[0].id;
          if (targets.length > 1) {
            const picks = targets.map((t) => ({ label: t.label, _id: t.id }));
            const pick = await quickInputService.pick(picks, { placeHolder: localize(5769, null) });
            if (!pick) {
              return;
            }
            id2 = pick._id;
          }
          return await stackFrame.thread.session.goto(stackFrame.thread.threadId, id2).catch((e) => notificationService.warn(e));
        }
      }
    }
    return notificationService.warn(localize(5770, null));
  }
});
$tn.registerCommand({
  id: $54b,
  handler: async (accessor, _, context) => {
    const debugService = accessor.get($0R);
    goToTopOfCallStack(debugService);
  }
});
$tn.registerCommand({
  id: $64b,
  handler: async (accessor, _, context) => {
    const debugService = accessor.get($0R);
    await goToBottomOfCallStack(debugService);
  }
});
$tn.registerCommand({
  id: $74b,
  handler: async (accessor, _, context) => {
    const debugService = accessor.get($0R);
    navigateCallStack(debugService, false);
  }
});
$tn.registerCommand({
  id: $84b,
  handler: async (accessor, _, context) => {
    const debugService = accessor.get($0R);
    navigateCallStack(debugService, true);
  }
});
$dJ.appendMenuItem($bJ.EditorContext, {
  command: {
    id: $Q4b,
    title: localize(5771, null),
    category: $_4b
  },
  when: $7m.and($yR, EditorContextKeys.editorTextFocus),
  group: "debug",
  order: 3
});
$0I.registerCommandAndKeybindingRule({
  id: $24b,
  weight: 200 + 1,
  when: $0Q,
  primary: 2048 | 12,
  mac: {
    primary: 1024 | 2048 | 94
    /* KeyCode.BracketRight */
  },
  handler: async (accessor, _, context) => {
    changeDebugConsoleFocus(accessor, true);
  }
});
$0I.registerCommandAndKeybindingRule({
  id: $34b,
  weight: 200 + 1,
  when: $0Q,
  primary: 2048 | 11,
  mac: {
    primary: 1024 | 2048 | 92
    /* KeyCode.BracketLeft */
  },
  handler: async (accessor, _, context) => {
    changeDebugConsoleFocus(accessor, false);
  }
});
$0I.registerCommandAndKeybindingRule({
  id: $D4b,
  weight: 200,
  primary: 1024 | 2048 | 63,
  when: $9Q,
  handler: async (accessor, _, context) => {
    const debugService = accessor.get($0R);
    const configurationService = accessor.get($kl);
    let session;
    if (isSessionContext(context)) {
      session = debugService.getModel().getSession(context.sessionId);
    } else {
      session = debugService.getViewModel().focusedSession;
    }
    if (!session) {
      const { launch, name } = debugService.getConfigurationManager().selectedConfiguration;
      await debugService.startDebugging(launch, name, { noDebug: false, startedByUser: true });
    } else {
      const showSubSessions = configurationService.getValue("debug").showSubSessionsInToolBar;
      while (!showSubSessions && session.lifecycleManagedByParent && session.parentSession) {
        session = session.parentSession;
      }
      session.removeReplExpressions();
      await debugService.restartSession(session);
    }
  }
});
$0I.registerCommandAndKeybindingRule({
  id: $F4b,
  weight: 200,
  primary: 68,
  when: $5Q.isEqualTo("stopped"),
  handler: async (accessor, _, context) => {
    const contextKeyService = accessor.get($on);
    if ($YR.getValue(contextKeyService)) {
      await getThreadAndRun(accessor, context, (thread) => thread.next("instruction"));
    } else {
      await getThreadAndRun(accessor, context, (thread) => thread.next());
    }
  }
});
var STEP_INTO_KEYBINDING = $r && $l ? 512 | 69 : 69;
$0I.registerCommandAndKeybindingRule({
  id: $G4b,
  weight: 200 + 10,
  // Have a stronger weight to have priority over full screen when debugging
  primary: STEP_INTO_KEYBINDING,
  // Use a more flexible when clause to not allow full screen command to take over when F11 pressed a lot of times
  when: $5Q.notEqualsTo("inactive"),
  handler: async (accessor, _, context) => {
    const contextKeyService = accessor.get($on);
    if ($YR.getValue(contextKeyService)) {
      await getThreadAndRun(accessor, context, (thread) => thread.stepIn("instruction"));
    } else {
      await getThreadAndRun(accessor, context, (thread) => thread.stepIn());
    }
  }
});
$0I.registerCommandAndKeybindingRule({
  id: $I4b,
  weight: 200,
  primary: 1024 | 69,
  when: $5Q.isEqualTo("stopped"),
  handler: async (accessor, _, context) => {
    const contextKeyService = accessor.get($on);
    if ($YR.getValue(contextKeyService)) {
      await getThreadAndRun(accessor, context, (thread) => thread.stepOut("instruction"));
    } else {
      await getThreadAndRun(accessor, context, (thread) => thread.stepOut());
    }
  }
});
$0I.registerCommandAndKeybindingRule({
  id: $J4b,
  weight: 200 + 2,
  // take priority over focus next part while we are debugging
  primary: 64,
  when: $5Q.isEqualTo("running"),
  handler: async (accessor, _, context) => {
    await getThreadAndRun(accessor, context, (thread) => thread.pause());
  }
});
$0I.registerCommandAndKeybindingRule({
  id: $H4b,
  primary: STEP_INTO_KEYBINDING | 2048,
  when: $7m.and($zR, $9Q, $5Q.isEqualTo("stopped")),
  weight: 200,
  handler: async (accessor, _, context) => {
    const quickInputService = accessor.get($1M);
    const debugService = accessor.get($0R);
    const session = debugService.getViewModel().focusedSession;
    const frame = debugService.getViewModel().focusedStackFrame;
    if (!frame || !session) {
      return;
    }
    const editor = await accessor.get($mJ).openEditor({
      resource: frame.source.uri,
      options: { revealIfOpened: true }
    });
    let codeEditor;
    if (editor) {
      const ctrl = editor?.getControl();
      if ($P5(ctrl)) {
        codeEditor = ctrl;
      }
    }
    const disposables = new $2c();
    const qp = disposables.add(quickInputService.createQuickPick());
    qp.busy = true;
    qp.show();
    disposables.add(qp.onDidChangeActive(([item]) => {
      if (codeEditor && item && item.target.line !== void 0) {
        codeEditor.revealLineInCenterIfOutsideViewport(item.target.line);
        codeEditor.setSelection({
          startLineNumber: item.target.line,
          startColumn: item.target.column || 1,
          endLineNumber: item.target.endLine || item.target.line,
          endColumn: item.target.endColumn || item.target.column || 1
        });
      }
    }));
    disposables.add(qp.onDidAccept(() => {
      if (qp.activeItems.length) {
        session.stepIn(frame.thread.threadId, qp.activeItems[0].target.id);
      }
    }));
    disposables.add(qp.onDidHide(() => disposables.dispose()));
    session.stepInTargets(frame.frameId).then((targets) => {
      qp.busy = false;
      if (targets?.length) {
        qp.items = targets?.map((target) => ({ target, label: target.label }));
      } else {
        qp.placeholder = localize(5772, null);
      }
    });
  }
});
async function stopHandler(accessor, _, context, disconnect, suspend) {
  const debugService = accessor.get($0R);
  let session;
  if (isSessionContext(context)) {
    session = debugService.getModel().getSession(context.sessionId);
  } else {
    session = debugService.getViewModel().focusedSession;
  }
  const configurationService = accessor.get($kl);
  const showSubSessions = configurationService.getValue("debug").showSubSessionsInToolBar;
  while (!showSubSessions && session && session.lifecycleManagedByParent && session.parentSession) {
    session = session.parentSession;
  }
  await debugService.stopSession(session, disconnect, suspend);
}
$0I.registerCommandAndKeybindingRule({
  id: $K4b,
  weight: 200,
  primary: 1024 | 63,
  when: $7m.and($tR, $9Q),
  handler: (accessor, _, context) => stopHandler(accessor, _, context, true)
});
$tn.registerCommand({
  id: $L4b,
  handler: (accessor, _, context) => stopHandler(accessor, _, context, true, true)
});
$0I.registerCommandAndKeybindingRule({
  id: $M4b,
  weight: 200,
  primary: 1024 | 63,
  when: $7m.and($tR.toNegated(), $9Q),
  handler: (accessor, _, context) => stopHandler(accessor, _, context, false)
});
$tn.registerCommand({
  id: $N4b,
  handler: async (accessor, _, context) => {
    const debugService = accessor.get($0R);
    const notificationService = accessor.get($PJ);
    const frame = getFrame(debugService, context);
    if (frame) {
      try {
        await frame.restart();
      } catch (e) {
        notificationService.error(e);
      }
    }
  }
});
$0I.registerCommandAndKeybindingRule({
  id: $O4b,
  weight: 200 + 10,
  // Use a stronger weight to get priority over start debugging F5 shortcut
  primary: 63,
  when: $5Q.isEqualTo("stopped"),
  handler: async (accessor, _, context) => {
    await getThreadAndRun(accessor, context, (thread) => thread.continue());
  }
});
$tn.registerCommand({
  id: $44b,
  handler: async (accessor) => {
    await $w4b(accessor);
  }
});
$tn.registerCommand({
  id: $P4b,
  handler: async (accessor) => {
    const viewsService = accessor.get($uob);
    await viewsService.openView($2Q, true);
  }
});
$tn.registerCommand({
  id: "debug.startFromConfig",
  handler: async (accessor, config) => {
    const debugService = accessor.get($0R);
    await debugService.startDebugging(void 0, config);
  }
});
$tn.registerCommand({
  id: $R4b,
  handler: async (accessor, session) => {
    const debugService = accessor.get($0R);
    const editorService = accessor.get($mJ);
    const stoppedChildSession = debugService.getModel().getSessions().find(
      (s) => s.parentSession === session && s.state === 2
      /* State.Stopped */
    );
    if (stoppedChildSession && session.state !== 2) {
      session = stoppedChildSession;
    }
    await debugService.focusStackFrame(void 0, void 0, session, { explicit: true });
    const stackFrame = debugService.getViewModel().focusedStackFrame;
    if (stackFrame) {
      await stackFrame.openInEditor(editorService, true);
    }
  }
});
$tn.registerCommand({
  id: $S4b,
  handler: async (accessor, debugType, debugStartOptions) => {
    const quickInputService = accessor.get($1M);
    const debugService = accessor.get($0R);
    if (debugType) {
      const configManager = debugService.getConfigurationManager();
      const dynamicProviders = await configManager.getDynamicProviders();
      for (const provider of dynamicProviders) {
        if (provider.type === debugType) {
          const pick = await provider.pick();
          if (pick) {
            await configManager.selectConfiguration(pick.launch, pick.config.name, pick.config, { type: provider.type });
            debugService.startDebugging(pick.launch, pick.config, { noDebug: debugStartOptions?.noDebug, startedByUser: true });
            return;
          }
        }
      }
    }
    quickInputService.quickAccess.show($B5b);
  }
});
$tn.registerCommand({
  id: $T4b,
  handler: async (accessor) => {
    const quickInputService = accessor.get($1M);
    quickInputService.quickAccess.show($C5b);
  }
});
$tn.registerCommand({
  id: $U4b,
  handler: async (accessor) => {
    $x4b(accessor, $S4b);
  }
});
$0I.registerCommandAndKeybindingRule({
  id: $W4b,
  weight: 200,
  primary: 63,
  when: $7m.and($BR, $5Q.isEqualTo("inactive")),
  handler: async (accessor, debugStartOptions) => {
    const debugService = accessor.get($0R);
    await $yP(accessor.get($kl), accessor.get($mJ));
    const { launch, name, getConfig } = debugService.getConfigurationManager().selectedConfiguration;
    const config = await getConfig();
    const configOrName = config ? Object.assign($Lv(config), debugStartOptions?.config) : name;
    await debugService.startDebugging(launch, configOrName, { noDebug: debugStartOptions?.noDebug, startedByUser: true }, false);
  }
});
$0I.registerCommandAndKeybindingRule({
  id: $X4b,
  weight: 200,
  primary: 2048 | 63,
  mac: {
    primary: 256 | 63
    /* KeyCode.F5 */
  },
  when: $7m.and($BR, $5Q.notEqualsTo($7R(
    1
    /* State.Initializing */
  ))),
  handler: async (accessor) => {
    const commandService = accessor.get($sn);
    await commandService.executeCommand($W4b, { noDebug: true });
  }
});
$0I.registerCommandAndKeybindingRule({
  id: "debug.toggleBreakpoint",
  weight: 200 + 5,
  when: $7m.and($aR, $Ceb.toNegated()),
  primary: 10,
  handler: (accessor) => {
    const listService = accessor.get($Deb);
    const debugService = accessor.get($0R);
    const list2 = listService.lastFocusedList;
    if (list2 instanceof $A1) {
      const focused = list2.getFocusedElements();
      if (focused && focused.length) {
        debugService.enableOrDisableBreakpoints(!focused[0].enabled, focused[0]);
      }
    }
  }
});
$0I.registerCommandAndKeybindingRule({
  id: "debug.enableOrDisableBreakpoint",
  weight: 200,
  primary: void 0,
  when: EditorContextKeys.editorTextFocus,
  handler: (accessor) => {
    const debugService = accessor.get($0R);
    const editorService = accessor.get($mJ);
    const control = editorService.activeTextEditorControl;
    if ($P5(control)) {
      const model = control.getModel();
      if (model) {
        const position = control.getPosition();
        if (position) {
          const bps = debugService.getModel().getBreakpoints({ uri: model.uri, lineNumber: position.lineNumber });
          if (bps.length) {
            debugService.enableOrDisableBreakpoints(!bps[0].enabled, bps[0]);
          }
        }
      }
    }
  }
});
$0I.registerCommandAndKeybindingRule({
  id: $Y4b,
  weight: 200 + 5,
  when: $bR,
  primary: 60,
  mac: {
    primary: 3
    /* KeyCode.Enter */
  },
  handler: (accessor, expression) => {
    const debugService = accessor.get($0R);
    if (!(expression instanceof $LP)) {
      const listService = accessor.get($Deb);
      const focused = listService.lastFocusedList;
      if (focused) {
        const elements = focused.getFocus();
        if (Array.isArray(elements) && elements[0] instanceof $LP) {
          expression = elements[0];
        }
      }
    }
    if (expression instanceof $LP) {
      debugService.getViewModel().setSelectedExpression(expression, false);
    }
  }
});
$tn.registerCommand({
  id: $Z4b,
  handler: async (accessor, expression) => {
    const debugService = accessor.get($0R);
    if (expression instanceof $LP || expression instanceof $MP) {
      debugService.getViewModel().setSelectedExpression(expression, true);
    }
  }
});
$0I.registerCommandAndKeybindingRule({
  id: "debug.setVariable",
  weight: 200 + 5,
  when: $dR,
  primary: 60,
  mac: {
    primary: 3
    /* KeyCode.Enter */
  },
  handler: (accessor) => {
    const listService = accessor.get($Deb);
    const debugService = accessor.get($0R);
    const focused = listService.lastFocusedList;
    if (focused) {
      const elements = focused.getFocus();
      if (Array.isArray(elements) && elements[0] instanceof $MP) {
        debugService.getViewModel().setSelectedExpression(elements[0], false);
      }
    }
  }
});
$0I.registerCommandAndKeybindingRule({
  id: $14b,
  weight: 200,
  when: $7m.and($bR, $eR.toNegated()),
  primary: 20,
  mac: {
    primary: 2048 | 1
    /* KeyCode.Backspace */
  },
  handler: (accessor, expression) => {
    const debugService = accessor.get($0R);
    if (expression instanceof $LP) {
      debugService.removeWatchExpressions(expression.getId());
      return;
    }
    const listService = accessor.get($Deb);
    const focused = listService.lastFocusedList;
    if (focused) {
      let elements = focused.getFocus();
      if (Array.isArray(elements) && elements[0] instanceof $LP) {
        const selection = focused.getSelection();
        if (selection && selection.indexOf(elements[0]) >= 0) {
          elements = selection;
        }
        elements.forEach((e) => debugService.removeWatchExpressions(e.getId()));
      }
    }
  }
});
$0I.registerCommandAndKeybindingRule({
  id: "debug.removeBreakpoint",
  weight: 200,
  when: $7m.and($aR, $fR.toNegated()),
  primary: 20,
  mac: {
    primary: 2048 | 1
    /* KeyCode.Backspace */
  },
  handler: (accessor) => {
    const listService = accessor.get($Deb);
    const debugService = accessor.get($0R);
    const list2 = listService.lastFocusedList;
    if (list2 instanceof $A1) {
      const focused = list2.getFocusedElements();
      const element = focused.length ? focused[0] : void 0;
      if (element instanceof $VP) {
        debugService.removeBreakpoints(element.getId());
      } else if (element instanceof $WP) {
        debugService.removeFunctionBreakpoints(element.getId());
      } else if (element instanceof $XP) {
        debugService.removeDataBreakpoints(element.getId());
      }
    }
  }
});
$0I.registerCommandAndKeybindingRule({
  id: "debug.installAdditionalDebuggers",
  weight: 200,
  when: void 0,
  primary: void 0,
  handler: async (accessor, query) => {
    const extensionsWorkbenchService = accessor.get($vzb);
    let searchFor = `@category:debuggers`;
    if (typeof query === "string") {
      searchFor += ` ${query}`;
    }
    return extensionsWorkbenchService.openSearch(searchFor);
  }
});
$hJ(class AddConfigurationAction extends $gJ {
  constructor() {
    super({
      id: $y4b,
      title: localize2(5801, "Add Configuration..."),
      category: $_4b,
      f1: true,
      menu: {
        id: $bJ.EditorContent,
        when: $7m.and($7m.regex($lqb.Path.key, /\.vscode[/\\]launch\.json$/), $Dpb.isEqualTo($mtb))
      }
    });
  }
  async run(accessor, launchUri) {
    const manager = accessor.get($0R).getConfigurationManager();
    const launch = manager.getLaunches().find((l) => l.uri.toString() === launchUri) || manager.selectedConfiguration.launch;
    if (launch) {
      const { editor, created: created2 } = await launch.openConfigFile({ preserveFocus: false });
      if (editor && !created2) {
        const codeEditor = editor.getControl();
        if (codeEditor) {
          await codeEditor.getContribution($3R)?.addLaunchConfiguration();
        }
      }
    }
  }
});
var inlineBreakpointHandler = (accessor) => {
  const debugService = accessor.get($0R);
  const editorService = accessor.get($mJ);
  const control = editorService.activeTextEditorControl;
  if ($P5(control)) {
    const position = control.getPosition();
    if (position && control.hasModel() && debugService.canSetBreakpointsIn(control.getModel())) {
      const modelUri = control.getModel().uri;
      const breakpointAlreadySet = debugService.getModel().getBreakpoints({ lineNumber: position.lineNumber, uri: modelUri }).some((bp) => bp.sessionAgnosticData.column === position.column || !bp.column && position.column <= 1);
      if (!breakpointAlreadySet) {
        debugService.addBreakpoints(modelUri, [{ lineNumber: position.lineNumber, column: position.column > 1 ? position.column : void 0 }]);
      }
    }
  }
};
$0I.registerCommandAndKeybindingRule({
  weight: 200,
  primary: 1024 | 67,
  when: EditorContextKeys.editorTextFocus,
  id: $z4b,
  handler: inlineBreakpointHandler
});
$dJ.appendMenuItem($bJ.EditorContext, {
  command: {
    id: $z4b,
    title: localize(5773, null),
    category: $_4b
  },
  when: $7m.and($9Q, $eqb.toNegated(), EditorContextKeys.editorTextFocus, ChatContextKeys.inChatSession.toNegated()),
  group: "debug",
  order: 1
});
$0I.registerCommandAndKeybindingRule({
  id: "debug.openBreakpointToSide",
  weight: 200,
  when: $aR,
  primary: 2048 | 3,
  secondary: [
    512 | 3
    /* KeyCode.Enter */
  ],
  handler: (accessor) => {
    const listService = accessor.get($Deb);
    const list2 = listService.lastFocusedList;
    if (list2 instanceof $A1) {
      const focus = list2.getFocusedElements();
      if (focus.length && focus[0] instanceof $VP) {
        return $V3b(focus[0], true, false, true, accessor.get($0R), accessor.get($mJ));
      }
    }
    return void 0;
  }
});
$0I.registerCommandAndKeybindingRule({
  id: "debug.openView",
  weight: 200,
  when: $BR.toNegated(),
  primary: 63,
  secondary: [
    2048 | 63
    /* KeyCode.F5 */
  ],
  handler: async (accessor) => {
    const paneCompositeService = accessor.get($uqb);
    await paneCompositeService.openPaneComposite($TQ, 0, true);
  }
});

// out-build/vs/workbench/contrib/debug/browser/linkDetector.js
var CONTROL_CODES = "\\u0000-\\u0020\\u007f-\\u009f";
var WEB_LINK_REGEX = new RegExp("(?:[a-zA-Z][a-zA-Z0-9+.-]{2,}:\\/\\/|data:|www\\.)[^\\s" + CONTROL_CODES + '"]{2,}[^\\s' + CONTROL_CODES + `"')}\\],:;.!?]`, "ug");
var WIN_ABSOLUTE_PATH = /(?:[a-zA-Z]:(?:(?:\\|\/)[\w\.-]*)+)/;
var WIN_RELATIVE_PATH = /(?:(?:\~|\.)(?:(?:\\|\/)[\w\.-]*)+)/;
var WIN_PATH = new RegExp(`(${WIN_ABSOLUTE_PATH.source}|${WIN_RELATIVE_PATH.source})`);
var POSIX_PATH = /((?:\~|\.)?(?:\/[\w\.-]*)+)/;
var LINE_COLUMN = /(?:\:([\d]+))?(?:\:([\d]+))?/;
var PATH_LINK_REGEX = new RegExp(`${$l ? WIN_PATH.source : POSIX_PATH.source}${LINE_COLUMN.source}`, "g");
var LINE_COLUMN_REGEX2 = /:([\d]+)(?::([\d]+))?$/;
var MAX_LENGTH = 2e3;
var DebugLinkHoverBehavior;
(function(DebugLinkHoverBehavior2) {
  DebugLinkHoverBehavior2[DebugLinkHoverBehavior2["Rich"] = 0] = "Rich";
  DebugLinkHoverBehavior2[DebugLinkHoverBehavior2["Basic"] = 1] = "Basic";
  DebugLinkHoverBehavior2[DebugLinkHoverBehavior2["None"] = 2] = "None";
})(DebugLinkHoverBehavior || (DebugLinkHoverBehavior = {}));
var $p4b = class $p4b2 {
  constructor(a, b, c, d, f, g, h3, j) {
    this.a = a;
    this.b = b;
    this.c = c;
    this.d = d;
    this.f = f;
    this.g = g;
    this.h = h3;
    this.j = j;
  }
  /**
   * Matches and handles web urls, absolute and relative file links in the string provided.
   * Returns <span/> element that wraps the processed string, where matched links are replaced by <a/>.
   * 'onclick' event is attached to all anchored links that opens them in the editor.
   * When splitLines is true, each line of the text, even if it contains no links, is wrapped in a <span>
   * and added as a child of the returned <span>.
   * If a `hoverBehavior` is passed, hovers may be added using the workbench hover service.
   * This should be preferred for new code where hovers are desirable.
   */
  linkify(text2, splitLines, workspaceFolder, includeFulltext, hoverBehavior) {
    return this.k(text2, splitLines, workspaceFolder, includeFulltext, hoverBehavior);
  }
  k(text2, splitLines, workspaceFolder, includeFulltext, hoverBehavior, defaultRef) {
    if (splitLines) {
      const lines = text2.split("\n");
      for (let i2 = 0; i2 < lines.length - 1; i2++) {
        lines[i2] = lines[i2] + "\n";
      }
      if (!lines[lines.length - 1]) {
        lines.pop();
      }
      const elements = lines.map((line) => this.k(line, false, workspaceFolder, includeFulltext, hoverBehavior, defaultRef));
      if (elements.length === 1) {
        return elements[0];
      }
      const container3 = document.createElement("span");
      elements.forEach((e) => container3.appendChild(e));
      return container3;
    }
    const container2 = document.createElement("span");
    for (const part of this.p(text2)) {
      try {
        switch (part.kind) {
          case "text":
            container2.appendChild(defaultRef ? this.linkifyLocation(part.value, defaultRef.locationReference, defaultRef.session, hoverBehavior) : document.createTextNode(part.value));
            break;
          case "web":
            container2.appendChild(this.l(includeFulltext ? text2 : void 0, part.value, hoverBehavior));
            break;
          case "path": {
            const path = part.captures[0];
            const lineNumber = part.captures[1] ? Number(part.captures[1]) : 0;
            const columnNumber = part.captures[2] ? Number(part.captures[2]) : 0;
            container2.appendChild(this.m(includeFulltext ? text2 : void 0, part.value, path, lineNumber, columnNumber, workspaceFolder, hoverBehavior));
            break;
          }
        }
      } catch (e) {
        container2.appendChild(document.createTextNode(part.value));
      }
    }
    return container2;
  }
  /**
   * Linkifies a location reference.
   */
  linkifyLocation(text2, locationReference, session, hoverBehavior) {
    const link2 = this.n(text2);
    this.o(link2, void 0, text2, hoverBehavior, async (preserveFocus) => {
      const location3 = await session.resolveLocationReference(locationReference);
      await location3.source.openInEditor(this.a, {
        startLineNumber: location3.line,
        startColumn: location3.column,
        endLineNumber: location3.endLine ?? location3.line,
        endColumn: location3.endColumn ?? location3.column
      }, preserveFocus);
    });
    return link2;
  }
  /**
   * Makes an {@link ILinkDetector} that links everything in the output to the
   * reference if they don't have other explicit links.
   */
  makeReferencedLinkDetector(locationReference, session) {
    return {
      linkify: (text2, splitLines, workspaceFolder, includeFulltext, hoverBehavior) => this.k(text2, splitLines, workspaceFolder, includeFulltext, hoverBehavior, { locationReference, session }),
      linkifyLocation: this.linkifyLocation.bind(this)
    };
  }
  l(fulltext, url, hoverBehavior) {
    const link2 = this.n(url);
    let uri = URI.parse(url);
    const lineCol = LINE_COLUMN_REGEX2.exec(uri.path);
    if (lineCol) {
      uri = uri.with({
        path: uri.path.slice(0, lineCol.index),
        fragment: `L${lineCol[0].slice(1)}`
      });
    }
    this.o(link2, uri, fulltext, hoverBehavior, async () => {
      if (uri.scheme === Schemas.file) {
        const fsPath = uri.fsPath;
        const path = await this.d.path;
        const fileUrl = $lc(path.sep === $kc.sep && $l ? fsPath.replace(/\\/g, $kc.sep) : fsPath);
        const fileUri = URI.parse(fileUrl);
        const exists = await this.b.exists(fileUri);
        if (!exists) {
          return;
        }
        await this.a.openEditor({
          resource: fileUri,
          options: {
            pinned: true,
            selection: lineCol ? { startLineNumber: +lineCol[1], startColumn: +lineCol[2] } : void 0
          }
        });
        return;
      }
      this.c.open(url, { allowTunneling: !!this.g.remoteAuthority && this.h.getValue("remote.forwardOnOpen") });
    });
    return link2;
  }
  m(fulltext, text2, path, lineNumber, columnNumber, workspaceFolder, hoverBehavior) {
    if (path[0] === "/" && path[1] === "/") {
      return document.createTextNode(text2);
    }
    const options3 = { selection: { startLineNumber: lineNumber, startColumn: columnNumber } };
    if (path[0] === ".") {
      if (!workspaceFolder) {
        return document.createTextNode(text2);
      }
      const uri2 = workspaceFolder.toResource(path);
      const link3 = this.n(text2);
      this.o(link3, uri2, fulltext, hoverBehavior, (preserveFocus) => this.a.openEditor({ resource: uri2, options: { ...options3, preserveFocus } }));
      return link3;
    }
    if (path[0] === "~") {
      const userHome = this.d.resolvedUserHome;
      if (userHome) {
        path = $nc(userHome.fsPath, path.substring(1));
      }
    }
    const link2 = this.n(text2);
    link2.tabIndex = 0;
    const uri = URI.file($lc(path));
    this.b.stat(uri).then((stat) => {
      if (stat.isDirectory) {
        return;
      }
      this.o(link2, uri, fulltext, hoverBehavior, (preserveFocus) => this.a.openEditor({ resource: uri, options: { ...options3, preserveFocus } }));
    }).catch(() => {
    });
    return link2;
  }
  n(text2) {
    const link2 = document.createElement("a");
    link2.textContent = text2;
    return link2;
  }
  o(link2, uri, fulltext, hoverBehavior, onClick2) {
    link2.classList.add("link");
    const followLink = uri && this.f.canTunnel(uri) ? localize(6010, null) : localize(6011, null);
    const title = link2.ariaLabel = fulltext ? $m ? localize(6012, null, followLink, fulltext) : localize(6013, null, followLink, fulltext) : $m ? localize(6014, null, followLink) : localize(6015, null, followLink);
    if (hoverBehavior?.type === 0) {
      hoverBehavior.store.add(this.j.setupManagedHover($JZ("element"), link2, title));
    } else if (hoverBehavior?.type !== 2) {
      link2.title = title;
    }
    link2.onmousemove = (event) => {
      link2.classList.toggle("pointer", $m ? event.metaKey : event.ctrlKey);
    };
    link2.onmouseleave = () => link2.classList.remove("pointer");
    link2.onclick = (event) => {
      const selection = getWindow(link2).getSelection();
      if (!selection || selection.type === "Range") {
        return;
      }
      if (!($m ? event.metaKey : event.ctrlKey)) {
        return;
      }
      event.preventDefault();
      event.stopImmediatePropagation();
      onClick2(false);
    };
    link2.onkeydown = (e) => {
      const event = new $if(e);
      if (event.keyCode === 3 || event.keyCode === 10) {
        event.preventDefault();
        event.stopPropagation();
        onClick2(
          event.keyCode === 10
          /* KeyCode.Space */
        );
      }
    };
  }
  p(text2) {
    if (text2.length > MAX_LENGTH) {
      return [{ kind: "text", value: text2, captures: [] }];
    }
    const regexes = [WEB_LINK_REGEX, PATH_LINK_REGEX];
    const kinds = ["web", "path"];
    const result = [];
    const splitOne = (text3, regexIndex) => {
      if (regexIndex >= regexes.length) {
        result.push({ value: text3, kind: "text", captures: [] });
        return;
      }
      const regex = regexes[regexIndex];
      let currentIndex = 0;
      let match;
      regex.lastIndex = 0;
      while ((match = regex.exec(text3)) !== null) {
        const stringBeforeMatch = text3.substring(currentIndex, match.index);
        if (stringBeforeMatch) {
          splitOne(stringBeforeMatch, regexIndex + 1);
        }
        const value = match[0];
        result.push({
          value,
          kind: kinds[regexIndex],
          captures: match.slice(1)
        });
        currentIndex = match.index + value.length;
      }
      const stringAfterMatches = text3.substring(currentIndex);
      if (stringAfterMatches) {
        splitOne(stringAfterMatches, regexIndex + 1);
      }
    };
    splitOne(text2, 0);
    return result;
  }
};
$p4b = __decorate([
  __param(0, $mJ),
  __param(1, $km),
  __param(2, $O4),
  __param(3, $aT),
  __param(4, $tC),
  __param(5, $US),
  __param(6, $kl),
  __param(7, $5$)
], $p4b);

// out-build/vs/workbench/contrib/debug/browser/debugExpressionRenderer.js
var MAX_VALUE_RENDER_LENGTH_IN_VIEWLET = 1024;
var booleanRegex = /^(true|false)$/i;
var stringRegex = /^(['"]).*\1$/;
var Cls;
(function(Cls2) {
  Cls2["Value"] = "value";
  Cls2["Unavailable"] = "unavailable";
  Cls2["Error"] = "error";
  Cls2["Changed"] = "changed";
  Cls2["Boolean"] = "boolean";
  Cls2["String"] = "string";
  Cls2["Number"] = "number";
})(Cls || (Cls = {}));
var allClasses = Object.keys({
  [
    "value"
    /* Cls.Value */
  ]: 0,
  [
    "unavailable"
    /* Cls.Unavailable */
  ]: 0,
  [
    "error"
    /* Cls.Error */
  ]: 0,
  [
    "changed"
    /* Cls.Changed */
  ]: 0,
  [
    "boolean"
    /* Cls.Boolean */
  ]: 0,
  [
    "string"
    /* Cls.String */
  ]: 0,
  [
    "number"
    /* Cls.Number */
  ]: 0
});
var $D5b = class $D5b2 {
  constructor(c, configurationService, instantiationService, d) {
    this.c = c;
    this.d = d;
    this.b = instantiationService.createInstance($p4b);
    this.a = $G9("debug.showVariableTypes", false, configurationService);
  }
  renderVariable(data, variable, options3 = {}) {
    const displayType = this.a.get();
    if (variable.available) {
      data.type.textContent = "";
      let text2 = variable.name;
      if (variable.value && typeof variable.name === "string") {
        if (variable.type && displayType) {
          text2 += ": ";
          data.type.textContent = variable.type + " =";
        } else {
          text2 += " =";
        }
      }
      data.label.set(text2, options3.highlights, variable.type && !displayType ? variable.type : variable.name);
      data.name.classList.toggle("virtual", variable.presentationHint?.kind === "virtual");
      data.name.classList.toggle("internal", variable.presentationHint?.visibility === "internal");
    } else if (variable.value && typeof variable.name === "string" && variable.name) {
      data.label.set(":");
    }
    data.expression.classList.toggle("lazy", !!variable.presentationHint?.lazy);
    const commands2 = [
      { id: $$4b, args: [variable, [variable]] }
    ];
    if (variable.evaluateName) {
      commands2.push({ id: $04b, args: [{ variable }] });
    }
    return this.renderValue(data.value, variable, {
      showChanged: options3.showChanged,
      maxValueLength: MAX_VALUE_RENDER_LENGTH_IN_VIEWLET,
      hover: { commands: commands2 },
      colorize: true,
      session: variable.getSession()
    });
  }
  renderValue(container2, expressionOrValue, options3 = {}) {
    const store = new $2c();
    const supportsANSI = options3.session?.rememberedCapabilities?.supportsANSIStyling ?? options3.wasANSI ?? false;
    let value = typeof expressionOrValue === "string" ? expressionOrValue : expressionOrValue.value;
    for (const cls of allClasses) {
      container2.classList.remove(cls);
    }
    container2.classList.add(
      "value"
      /* Cls.Value */
    );
    if (value === null || (expressionOrValue instanceof $LP || expressionOrValue instanceof $MP || expressionOrValue instanceof $m4b) && !expressionOrValue.available) {
      container2.classList.add(
        "unavailable"
        /* Cls.Unavailable */
      );
      if (value !== $LP.DEFAULT_VALUE) {
        container2.classList.add(
          "error"
          /* Cls.Error */
        );
      }
    } else {
      if (typeof expressionOrValue !== "string" && options3.showChanged && expressionOrValue.valueChanged && value !== $LP.DEFAULT_VALUE) {
        container2.classList.add(
          "changed"
          /* Cls.Changed */
        );
        expressionOrValue.valueChanged = false;
      }
      if (options3.colorize && typeof expressionOrValue !== "string") {
        if (expressionOrValue.type === "number" || expressionOrValue.type === "boolean" || expressionOrValue.type === "string") {
          container2.classList.add(expressionOrValue.type);
        } else if (!isNaN(+value)) {
          container2.classList.add(
            "number"
            /* Cls.Number */
          );
        } else if (booleanRegex.test(value)) {
          container2.classList.add(
            "boolean"
            /* Cls.Boolean */
          );
        } else if (stringRegex.test(value)) {
          container2.classList.add(
            "string"
            /* Cls.String */
          );
        }
      }
    }
    if (options3.maxValueLength && value && value.length > options3.maxValueLength) {
      value = value.substring(0, options3.maxValueLength) + "...";
    }
    if (!value) {
      value = "";
    }
    const session = options3.session ?? (expressionOrValue instanceof $JP ? expressionOrValue.getSession() : void 0);
    const hoverBehavior = options3.hover === false ? { type: 0, store } : {
      type: 2
      /* DebugLinkHoverBehavior.None */
    };
    $$i(container2);
    const locationReference = options3.locationReference ?? (expressionOrValue instanceof $JP && expressionOrValue.valueLocationReference);
    let linkDetector = this.b;
    if (locationReference && session) {
      linkDetector = this.b.makeReferencedLinkDetector(locationReference, session);
    }
    if (supportsANSI) {
      container2.appendChild($t4b(value, linkDetector, session ? session.root : void 0));
    } else {
      container2.appendChild(linkDetector.linkify(value, false, session?.root, true, hoverBehavior));
    }
    if (options3.hover !== false) {
      const { commands: commands2 = [] } = options3.hover || {};
      store.add(this.d.setupManagedHover($JZ("mouse"), container2, () => {
        const container3 = $("div");
        const markdownHoverElement = $("div.hover-row");
        const hoverContentsElement = $bk(markdownHoverElement, $("div.hover-contents"));
        const hoverContentsPre = $bk(hoverContentsElement, $("pre.debug-var-hover-pre"));
        if (supportsANSI) {
          hoverContentsPre.appendChild($t4b(value, this.b, session ? session.root : void 0));
        } else {
          hoverContentsPre.textContent = value;
        }
        container3.appendChild(markdownHoverElement);
        return container3;
      }, {
        actions: commands2.map(({ id: id2, args: args2 }) => {
          const description = $tn.getCommand(id2)?.metadata?.description;
          return {
            label: typeof description === "string" ? description : description ? description.value : id2,
            commandId: id2,
            run: () => this.c.executeCommand(id2, ...args2)
          };
        })
      }));
    }
    return store;
  }
};
$D5b = __decorate([
  __param(0, $sn),
  __param(1, $kl),
  __param(2, $Pk),
  __param(3, $5$)
], $D5b);

// out-build/vs/workbench/contrib/notebook/browser/contrib/notebookVariables/notebookVariablesTree.js
var $G5b_1;
var $131 = $;
var MAX_VALUE_RENDER_LENGTH_IN_VIEWLET2 = 1024;
var $F5b = class {
  getHeight(element) {
    return 22;
  }
  getTemplateId(element) {
    return $G5b.ID;
  }
};
var $G5b = class $G5b2 {
  static {
    $G5b_1 = this;
  }
  static {
    this.ID = "variableElement";
  }
  get templateId() {
    return $G5b_1.ID;
  }
  constructor(instantiationService) {
    this.a = instantiationService.createInstance($D5b);
  }
  renderTemplate(container2) {
    const expression = $bk(container2, $131(".expression"));
    const name = $bk(expression, $131("span.name"));
    const value = $bk(expression, $131("span.value"));
    const template = { expression, name, value, elementDisposables: new $2c() };
    return template;
  }
  renderElement(element, _index, data) {
    const text2 = element.element.value.trim() !== "" ? `${element.element.name}:` : element.element.name;
    data.name.textContent = text2;
    data.name.title = element.element.type ?? "";
    data.elementDisposables.add(this.a.renderValue(data.value, element.element, {
      colorize: true,
      maxValueLength: MAX_VALUE_RENDER_LENGTH_IN_VIEWLET2,
      session: void 0
    }));
  }
  disposeElement(element, index, templateData, height) {
    templateData.elementDisposables.clear();
  }
  disposeTemplate(templateData) {
    templateData.elementDisposables.dispose();
  }
};
$G5b = $G5b_1 = __decorate([
  __param(0, $Pk)
], $G5b);
var $H5b = class {
  getWidgetAriaLabel() {
    return localize(8177, null);
  }
  getAriaLabel(element) {
    return localize(8178, null, element.name, element.value);
  }
};

// out-build/vs/workbench/contrib/notebook/browser/contrib/notebookVariables/notebookVariablesView.js
var $I5b_1;
var $I5b = class $I5b2 extends $_ob {
  static {
    $I5b_1 = this;
  }
  static {
    this.ID = "notebookVariablesView";
  }
  static {
    this.NOTEBOOK_TITLE = localize2(8179, "Notebook Variables");
  }
  static {
    this.REPL_TITLE = localize2(8180, "REPL Variables");
  }
  constructor(options3, g, h3, j, keybindingService, contextMenuService, contextKeyService, configurationService, instantiationService, viewDescriptorService, openerService, m, n, themeService, telemetryService, hoverService, r2) {
    super(options3, keybindingService, contextMenuService, configurationService, contextKeyService, viewDescriptorService, instantiationService, openerService, themeService, telemetryService, hoverService);
    this.g = g;
    this.h = h3;
    this.j = j;
    this.m = m;
    this.n = n;
    this.r = r2;
    this.B(this.g.onDidActiveEditorChange(() => this.bc()));
    this.B(this.h.onDidNotebookVariablesUpdate(this.dc.bind(this)));
    this.B(this.j.onDidChangeExecution(this.cc.bind(this)));
    this.B(this.g.onDidCloseEditor((e) => this.ac(e)));
    this.bc(false);
    this.c = new $h4b(this.h);
    this.f = new $8h(() => this.a?.updateChildren(), 100);
  }
  W(container2) {
    super.W(container2);
    this.element.classList.add("debug-pane");
    this.a = this.Db.createInstance($4eb, "notebookVariablesTree", container2, new $F5b(), [this.Db.createInstance($G5b)], this.c, {
      accessibilityProvider: new $H5b(),
      identityProvider: { getId: (e) => e.id }
    });
    this.a.layout();
    if (this.b) {
      this.a.setInput({ kind: "root", notebook: this.b });
    }
    this.B(this.a.onContextMenu((e) => this.t(e)));
  }
  t(e) {
    if (!e.element) {
      return;
    }
    const element = e.element;
    const arg = {
      source: element.notebook.uri.toString(),
      name: element.name,
      value: element.value,
      type: element.type,
      expression: element.expression,
      language: element.language,
      extensionId: element.extensionId
    };
    const overlayedContext = this.Bb.createOverlay([
      [$RR.key, element.name],
      [$OR.key, element.value],
      [$PR.key, element.type],
      [$QR.key, element.interfaces],
      [$SR.key, element.language],
      [$TR.key, element.extensionId]
    ]);
    const menuActions = this.r.getMenuActions($bJ.NotebookVariablesContext, overlayedContext, { arg, shouldForwardArgs: true });
    const actions = $P$(menuActions);
    this.zb.showContextMenu({
      getAnchor: () => e.anchor,
      getActions: () => actions
    });
  }
  focus() {
    super.focus();
    this.a?.domFocus();
  }
  X(height, width2) {
    super.X(height, width2);
    this.a?.layout(height, width2);
  }
  ab(notebookDocument, editor, doUpdate = true) {
    this.b = notebookDocument;
    if ($urb(editor.input)) {
      this.Qb($I5b_1.REPL_TITLE.value);
    } else {
      this.Qb($I5b_1.NOTEBOOK_TITLE.value);
    }
    if (doUpdate) {
      this.a?.setInput({ kind: "root", notebook: notebookDocument });
      this.f.schedule();
    }
  }
  sb() {
    const notebookEditor = this.g.activeEditorPane;
    const notebookDocument = $Qrb(notebookEditor)?.textModel;
    return notebookDocument && notebookEditor ? { notebookDocument, notebookEditor } : void 0;
  }
  ac(e) {
    if (e.editor.resource && e.editor.resource.toString() === this.b?.uri.toString()) {
      this.a?.setInput({ kind: "empty" });
      this.f.schedule();
    }
  }
  bc(doUpdate = true) {
    const found = this.sb();
    if (found && found.notebookDocument !== this.b) {
      this.ab(found.notebookDocument, found.notebookEditor, doUpdate);
    }
  }
  cc(event) {
    if (this.b && event.affectsNotebook(this.b.uri)) {
      this.c.cancel();
      if (event.changed === void 0) {
        this.f.schedule();
      } else {
        this.f.cancel();
      }
    } else if (!this.sb()) {
      this.g.visibleEditorPanes.forEach((editor) => {
        const notebookDocument = $Qrb(editor)?.textModel;
        if (notebookDocument && event.affectsNotebook(notebookDocument.uri)) {
          this.ab(notebookDocument, editor);
        }
      });
    }
  }
  dc(notebookUri) {
    if (this.b && notebookUri.toString() === this.b.uri.toString()) {
      this.f.schedule();
    } else if (!this.sb()) {
      this.g.visibleEditorPanes.forEach((editor) => {
        const notebookDocument = $Qrb(editor)?.textModel;
        if (notebookDocument && notebookDocument.uri.toString() === notebookUri.toString()) {
          this.ab(notebookDocument, editor);
        }
      });
    }
  }
};
$I5b = $I5b_1 = __decorate([
  __param(1, $mJ),
  __param(2, $CL),
  __param(3, $wL),
  __param(4, $Ty),
  __param(5, $50),
  __param(6, $on),
  __param(7, $kl),
  __param(8, $Pk),
  __param(9, $$M),
  __param(10, $O4),
  __param(11, $1M),
  __param(12, $sn),
  __param(13, $gs),
  __param(14, $zv),
  __param(15, $5$),
  __param(16, $cJ)
], $I5b);

// out-build/vs/workbench/contrib/notebook/browser/contrib/notebookVariables/notebookVariables.js
var $J5b = class $J5b2 extends $3c {
  constructor(contextKeyService, g, h3, j, m, n, r2) {
    super();
    this.g = g;
    this.h = h3;
    this.j = j;
    this.m = m;
    this.n = n;
    this.r = r2;
    this.a = [];
    this.c = false;
    this.f = $b3b.bindTo(contextKeyService);
    this.a.push(this.h.onDidActiveEditorChange(() => this.t()));
    this.a.push(this.j.onDidChangeExecution((e) => this.t(e.notebook)));
    this.b = g.onDidChangeConfiguration((e) => this.s(e));
  }
  s(e) {
    if (e.affectsConfiguration($rM.notebookVariablesView)) {
      this.t();
    }
  }
  t(notebook) {
    const enabled = this.h.activeEditorPane?.getId() === "workbench.editor.repl" || this.g.getValue($rM.notebookVariablesView) || // old setting key
    this.g.getValue("notebook.experimental.variablesView");
    if (enabled && (!!notebook || this.h.activeEditorPane?.getId() === "workbench.editor.notebook")) {
      if (this.u(notebook) && !this.c && this.w()) {
        this.f.set(true);
        this.c = true;
        this.a.forEach((listener) => listener.dispose());
      }
    }
  }
  u(notebookUri) {
    const notebook = notebookUri ? this.n.getNotebookTextModel(notebookUri) : $Qrb(this.h.activeEditorPane)?.getViewModel()?.notebookDocument;
    return notebook && this.m.getMatchingKernel(notebook).selected?.hasVariableProvider;
  }
  w() {
    const debugViewContainer = this.r.getViewContainerById($TQ);
    if (debugViewContainer) {
      const viewsRegistry8 = $Wn.as(Extensions5.ViewsRegistry);
      const viewDescriptor3 = {
        id: "workbench.notebook.variables",
        name: localize2(8175, "Notebook Variables"),
        containerIcon: $3Kb,
        ctorDescriptor: new $Nk($I5b),
        order: 50,
        weight: 5,
        canToggleVisibility: true,
        canMoveView: true,
        collapsed: false,
        when: $b3b
      };
      viewsRegistry8.registerViews([viewDescriptor3], debugViewContainer);
      return true;
    }
    return false;
  }
  dispose() {
    super.dispose();
    this.a.forEach((listener) => listener.dispose());
    this.b.dispose();
  }
};
$J5b = __decorate([
  __param(0, $on),
  __param(1, $kl),
  __param(2, $mJ),
  __param(3, $wL),
  __param(4, $CL),
  __param(5, $mrb),
  __param(6, $$M)
], $J5b);

// out-build/vs/workbench/contrib/notebook/browser/notebookAccessibilityHelp.js
var $K5b = class {
  constructor() {
    this.priority = 105;
    this.name = "notebook";
    this.when = $7m.and($WAb, $VAb.negate());
    this.type = "help";
  }
  getProvider(accessor) {
    const activeEditor = accessor.get($U5).getActiveCodeEditor() || accessor.get($U5).getFocusedCodeEditor() || accessor.get($mJ).activeEditorPane;
    if (!activeEditor) {
      return;
    }
    return getAccessibilityHelpProvider(accessor, activeEditor);
  }
};
function getAccessibilityHelpText() {
  return [
    localize(8463, null),
    localize(8464, null, "<keybinding:notebook.cell.edit>"),
    localize(8465, null, "<keybinding:notebook.cell.quitEdit>"),
    localize(8466, null, "<keybinding:notebook.cell.focusInOutput>"),
    localize(8467, null, "<keybinding:notebook.focusNextEditor>"),
    localize(8468, null, "<keybinding:notebook.focusPreviousEditor>"),
    localize(8469, null),
    localize(8470, null, "<keybinding:notebook.cell.executeAndFocusContainer>"),
    localize(8471, null, "<keybinding:notebook.cell.insertCodeCellAbove>", "<keybinding:notebook.cell.insertCodeCellBelow>"),
    localize(8472, null)
  ].join("\n");
}
function getAccessibilityHelpProvider(accessor, editor) {
  const helpText = getAccessibilityHelpText();
  return new $thb(
    "notebook",
    {
      type: "help"
      /* AccessibleViewType.Help */
    },
    () => helpText,
    () => editor.focus(),
    "accessibility.verbosity.notebook"
    /* AccessibilityVerbositySettingId.Notebook */
  );
}

// out-build/vs/workbench/contrib/notebook/browser/notebookAccessibleView.js
var $L5b = class {
  constructor() {
    this.priority = 100;
    this.name = "notebook";
    this.type = "view";
    this.when = $7m.and($XAb, $Ceb.toNegated());
  }
  getProvider(accessor) {
    const editorService = accessor.get($mJ);
    return $M5b(editorService);
  }
};
function $M5b(editorService) {
  const activePane = editorService.activeEditorPane;
  const notebookEditor = $Qrb(activePane);
  const notebookViewModel = notebookEditor?.getViewModel();
  const selections = notebookViewModel?.getSelections();
  const notebookDocument = notebookViewModel?.notebookDocument;
  if (!selections || !notebookDocument || !notebookEditor?.textModel) {
    return;
  }
  const viewCell = notebookViewModel.viewCells[selections[0].start];
  const outputContent = $4Kb(notebookDocument, viewCell);
  if (!outputContent) {
    return;
  }
  return new $thb(
    "notebook",
    {
      type: "view"
      /* AccessibleViewType.View */
    },
    () => {
      return outputContent;
    },
    () => {
      notebookEditor?.setFocus(selections[0]);
      notebookEditor.focus();
    },
    "accessibility.verbosity.notebook"
    /* AccessibilityVerbositySettingId.Notebook */
  );
}

// out-build/vs/workbench/contrib/format/browser/formatActionsMultiple.js
var $N5b_1;
var $N5b = class $N5b2 extends $3c {
  static {
    $N5b_1 = this;
  }
  static {
    this.configName = "editor.defaultFormatter";
  }
  static {
    this.extensionIds = [];
  }
  static {
    this.extensionItemLabels = [];
  }
  static {
    this.extensionDescriptions = [];
  }
  constructor(f, g, h3, j, m, n, r2, t, u, w) {
    super();
    this.f = f;
    this.g = g;
    this.h = h3;
    this.j = j;
    this.m = m;
    this.n = n;
    this.r = r2;
    this.t = t;
    this.u = u;
    this.w = w;
    this.c = this.q.add(new $2c());
    this.q.add(this.f.onDidChangeExtensions(this.y, this));
    this.q.add($bhb.setFormatterSelector((formatter, document2, mode, kind) => this.C(formatter, document2, mode, kind)));
    this.q.add(w.onDidActiveEditorChange(this.F, this));
    this.q.add(t.documentFormattingEditProvider.onDidChange(this.F, this));
    this.q.add(t.documentRangeFormattingEditProvider.onDidChange(this.F, this));
    this.q.add(h3.onDidChangeConfiguration((e) => e.affectsConfiguration($N5b_1.configName) && this.F()));
    this.y();
  }
  async y() {
    await this.f.whenInstalledExtensionsRegistered();
    let extensions = [...this.f.extensions];
    extensions = extensions.sort((a, b) => {
      const boostA = a.categories?.find((cat) => cat === "Formatters" || cat === "Programming Languages");
      const boostB = b.categories?.find((cat) => cat === "Formatters" || cat === "Programming Languages");
      if (boostA && !boostB) {
        return -1;
      } else if (!boostA && boostB) {
        return 1;
      } else {
        return a.name.localeCompare(b.name);
      }
    });
    $N5b_1.extensionIds.length = 0;
    $N5b_1.extensionItemLabels.length = 0;
    $N5b_1.extensionDescriptions.length = 0;
    $N5b_1.extensionIds.push(null);
    $N5b_1.extensionItemLabels.push(localize(7435, null));
    $N5b_1.extensionDescriptions.push(localize(7436, null));
    for (const extension of extensions) {
      if (extension.main || extension.browser) {
        $N5b_1.extensionIds.push(extension.identifier.value);
        $N5b_1.extensionItemLabels.push(extension.displayName ?? "");
        $N5b_1.extensionDescriptions.push(extension.description ?? "");
      }
    }
  }
  static _maybeQuotes(s) {
    return s.match(/\s/) ? `'${s}'` : s;
  }
  async z(kind, formatter, document2) {
    const defaultFormatterId = this.h.getValue($N5b_1.configName, {
      resource: document2.uri,
      overrideIdentifier: document2.getLanguageId()
    });
    if (defaultFormatterId) {
      const defaultFormatter = formatter.find((formatter2) => $5z.equals(formatter2.extensionId, defaultFormatterId));
      if (defaultFormatter) {
        return defaultFormatter;
      }
      const extension = await this.f.getExtension(defaultFormatterId);
      if (extension && this.g.isEnabled($DN(extension))) {
        const langName2 = this.r.getLanguageName(document2.getLanguageId()) || document2.getLanguageId();
        const detail2 = kind === 1 ? localize(7437, null, extension.displayName || extension.name, langName2) : localize(7438, null, extension.displayName || extension.name, langName2);
        return detail2;
      }
    } else if (formatter.length === 1) {
      return formatter[0];
    }
    const langName = this.r.getLanguageName(document2.getLanguageId()) || document2.getLanguageId();
    const message = !defaultFormatterId ? localize(7439, null, $N5b_1._maybeQuotes(langName)) : localize(7440, null, defaultFormatterId);
    return message;
  }
  async C(formatter, document2, mode, kind) {
    const formatterOrMessage = await this.z(kind, formatter, document2);
    if (typeof formatterOrMessage !== "string") {
      return formatterOrMessage;
    }
    if (mode !== 2) {
      const { confirmed } = await this.m.confirm({
        message: localize(7441, null),
        detail: formatterOrMessage,
        primaryButton: localize(7442, null)
      });
      if (confirmed) {
        return this.D(formatter, document2);
      }
    } else {
      this.j.prompt(Severity2.Info, formatterOrMessage, [{ label: localize(7443, null), run: () => this.D(formatter, document2) }], { priority: NotificationPriority.SILENT });
    }
    return void 0;
  }
  async D(formatter, document2) {
    const picks = formatter.map((formatter2, index) => {
      return {
        index,
        label: formatter2.displayName || (formatter2.extensionId ? formatter2.extensionId.value : "?"),
        description: formatter2.extensionId && formatter2.extensionId.value
      };
    });
    const langName = this.r.getLanguageName(document2.getLanguageId()) || document2.getLanguageId();
    const pick = await this.n.pick(picks, { placeHolder: localize(7444, null, $N5b_1._maybeQuotes(langName)) });
    if (!pick || !formatter[pick.index].extensionId) {
      return void 0;
    }
    this.h.updateValue($N5b_1.configName, formatter[pick.index].extensionId.value, {
      resource: document2.uri,
      overrideIdentifier: document2.getLanguageId()
    });
    return formatter[pick.index];
  }
  // --- status item
  F() {
    this.c.clear();
    const editor = $S5(this.w.activeTextEditorControl);
    if (!editor || !editor.hasModel()) {
      return;
    }
    const document2 = editor.getModel();
    const formatter = $ahb(this.t.documentFormattingEditProvider, this.t.documentRangeFormattingEditProvider, document2);
    if (formatter.length === 0) {
      return;
    }
    const cts = new $ad();
    this.c.add($1c(() => cts.dispose(true)));
    this.z(1, formatter, document2).then((result) => {
      if (cts.token.isCancellationRequested) {
        return;
      }
      if (typeof result !== "string") {
        return;
      }
      const command4 = { id: `formatter/configure/dfl/${$ps()}`, title: localize(7445, null) };
      this.c.add($tn.registerCommand(command4.id, () => this.D(formatter, document2)));
      this.c.add(this.u.addStatus({
        id: "formatter.conflict",
        name: localize(7446, null),
        selector: { language: document2.getLanguageId(), pattern: document2.uri.fsPath },
        severity: Severity2.Error,
        label: localize(7447, null),
        detail: result,
        busy: false,
        source: "",
        command: command4,
        accessibilityInfo: void 0
      }));
    });
  }
};
$N5b = $N5b_1 = __decorate([
  __param(0, $wN),
  __param(1, $qzb),
  __param(2, $kl),
  __param(3, $PJ),
  __param(4, $Yv),
  __param(5, $1M),
  __param(6, $1E),
  __param(7, $mP),
  __param(8, $FS),
  __param(9, $mJ)
], $N5b);
$Wn.as(Extensions2.Workbench).registerWorkbenchContribution(
  $N5b,
  3
  /* LifecyclePhase.Restored */
);
$Wn.as($Ht.Configuration).registerConfiguration({
  ...$mab,
  properties: {
    [$N5b.configName]: {
      description: localize(7448, null),
      type: ["string", "null"],
      default: null,
      enum: $N5b.extensionIds,
      enumItemLabels: $N5b.extensionItemLabels,
      markdownEnumDescriptions: $N5b.extensionDescriptions
    }
  }
});
function logFormatterTelemetry(telemetryService, mode, options3, pick) {
  function extKey(obj) {
    return obj.extensionId ? $5z.toKey(obj.extensionId) : "unknown";
  }
  telemetryService.publicLog2("formatterpick", {
    mode,
    extensions: options3.map(extKey),
    pick: pick ? extKey(pick) : "none"
  });
}
async function showFormatterPick(accessor, model, formatters) {
  const quickPickService = accessor.get($1M);
  const configService = accessor.get($kl);
  const languageService = accessor.get($1E);
  const overrides = { resource: model.uri, overrideIdentifier: model.getLanguageId() };
  const defaultFormatter = configService.getValue($N5b.configName, overrides);
  let defaultFormatterPick;
  const picks = formatters.map((provider, index) => {
    const isDefault = $5z.equals(provider.extensionId, defaultFormatter);
    const pick2 = {
      index,
      label: provider.displayName || "",
      description: isDefault ? localize(7449, null) : void 0
    };
    if (isDefault) {
      defaultFormatterPick = pick2;
    }
    return pick2;
  });
  const configurePick = {
    label: localize(7450, null)
  };
  const pick = await quickPickService.pick([...picks, { type: "separator" }, configurePick], {
    placeHolder: localize(7451, null),
    activeItem: defaultFormatterPick
  });
  if (!pick) {
    return void 0;
  } else if (pick === configurePick) {
    const langName = languageService.getLanguageName(model.getLanguageId()) || model.getLanguageId();
    const pick2 = await quickPickService.pick(picks, { placeHolder: localize(7452, null, $N5b._maybeQuotes(langName)) });
    if (pick2 && formatters[pick2.index].extensionId) {
      configService.updateValue($N5b.configName, formatters[pick2.index].extensionId.value, overrides);
    }
    return void 0;
  } else {
    return pick.index;
  }
}
$55(class FormatDocumentMultipleAction extends $Z5 {
  constructor() {
    super({
      id: "editor.action.formatDocument.multiple",
      label: localize(7453, null),
      alias: "Format Document...",
      precondition: $7m.and(EditorContextKeys.writable, EditorContextKeys.hasMultipleDocumentFormattingProvider),
      contextMenuOpts: {
        group: "1_modification",
        order: 1.3
      }
    });
  }
  async run(accessor, editor, args2) {
    if (!editor.hasModel()) {
      return;
    }
    const instaService = accessor.get($Pk);
    const telemetryService = accessor.get($zv);
    const languageFeaturesService = accessor.get($mP);
    const model = editor.getModel();
    const provider = $ahb(languageFeaturesService.documentFormattingEditProvider, languageFeaturesService.documentRangeFormattingEditProvider, model);
    const pick = await instaService.invokeFunction(showFormatterPick, model, provider);
    if (typeof pick === "number") {
      await instaService.invokeFunction($fhb, provider[pick], editor, 1, CancellationToken.None);
    }
    logFormatterTelemetry(telemetryService, "document", provider, typeof pick === "number" && provider[pick] || void 0);
  }
});
$55(class FormatSelectionMultipleAction extends $Z5 {
  constructor() {
    super({
      id: "editor.action.formatSelection.multiple",
      label: localize(7454, null),
      alias: "Format Code...",
      precondition: $7m.and($7m.and(EditorContextKeys.writable), EditorContextKeys.hasMultipleDocumentSelectionFormattingProvider),
      contextMenuOpts: {
        when: $7m.and(EditorContextKeys.hasNonEmptySelection),
        group: "1_modification",
        order: 1.31
      }
    });
  }
  async run(accessor, editor) {
    if (!editor.hasModel()) {
      return;
    }
    const instaService = accessor.get($Pk);
    const languageFeaturesService = accessor.get($mP);
    const telemetryService = accessor.get($zv);
    const model = editor.getModel();
    let range = editor.getSelection();
    if (range.isEmpty()) {
      range = new $9C(range.startLineNumber, 1, range.startLineNumber, model.getLineMaxColumn(range.startLineNumber));
    }
    const provider = languageFeaturesService.documentRangeFormattingEditProvider.ordered(model);
    const pick = await instaService.invokeFunction(showFormatterPick, model, provider);
    if (typeof pick === "number") {
      await instaService.invokeFunction($dhb, provider[pick], editor, range, CancellationToken.None, true);
    }
    logFormatterTelemetry(telemetryService, "range", provider, typeof pick === "number" && provider[pick] || void 0);
  }
});

// out-build/vs/workbench/contrib/chat/browser/chatEditing/chatEditingModifiedNotebookEntry.js
var $lFb = class $lFb2 extends $pFb {
  constructor(resourceRef, _multiDiffEntryDelegate, _telemetryInfo, kind, initialContent, modelService, textModelService, languageService, _chatService, _editorWorkerService, _undoRedoService, _fileService) {
    super(resourceRef, _multiDiffEntryDelegate, _telemetryInfo, kind, initialContent, modelService, textModelService, languageService, _chatService, _editorWorkerService, _undoRedoService, _fileService);
    this.Y = resourceRef.object;
  }
  async saveMirrorDocument() {
    await this.Y.save({ reason: 1, ignoreModifiedSince: true });
  }
  async revertMirrorDocument() {
    await this.Y.revert({ soft: true });
  }
};
$lFb = __decorate([
  __param(5, $sG),
  __param(6, $oG),
  __param(7, $1E),
  __param(8, $qO),
  __param(9, $I0),
  __param(10, $_F),
  __param(11, $km)
], $lFb);

// out-build/vs/workbench/contrib/notebook/browser/contrib/chatEdit/notebookSynchronizerService.js
var NotebookSynchronizerSaveParticipant = class NotebookSynchronizerSaveParticipant2 extends $t3b {
  constructor(editorService, e, f) {
    super(editorService);
    this.e = e;
    this.f = f;
  }
  async participate(workingCopy, context, progress, token) {
    console.log("notebook synchronizer participate");
    const session = this.e.currentEditingSessionObs.get();
    if (!session) {
      return;
    }
    const entry = session.getEntry(workingCopy.resource);
    if (entry && entry instanceof $lFb) {
      await entry.saveMirrorDocument();
    }
    const inWorkingSet = session.workingSet.has(workingCopy.resource);
    if (!(entry && entry instanceof $lFb) && !inWorkingSet) {
      return;
    }
    if (workingCopy instanceof $$J) {
      const metadata = await this.f.stat(workingCopy.resource);
      if (workingCopy.lastResolvedFileStat) {
        workingCopy.lastResolvedFileStat = {
          ...workingCopy.lastResolvedFileStat,
          ...metadata
        };
      }
    }
  }
};
NotebookSynchronizerSaveParticipant = __decorate([
  __param(0, $mJ),
  __param(1, $$O),
  __param(2, $km)
], NotebookSynchronizerSaveParticipant);
var $O5b = class $O5b2 extends $3c {
  constructor(a, b, c, f) {
    super();
    this.a = a;
    this.b = b;
    this.c = c;
    this.f = f;
    this.B(this.f.addSaveParticipant(this.c.createInstance(NotebookSynchronizerSaveParticipant)));
  }
  async revert(workingCopy) {
    const resource = workingCopy.resource;
    const session = this.a.currentEditingSessionObs.get();
    if (session) {
      const entry = session.getEntry(resource);
      if (entry instanceof $lFb) {
        await entry.revertMirrorDocument();
      }
    }
  }
};
$O5b = __decorate([
  __param(0, $$O),
  __param(1, $km),
  __param(2, $Pk),
  __param(3, $aK)
], $O5b);

// out-build/vs/workbench/contrib/notebook/browser/notebook.contribution.js
var $P5b_1;
$Wn.as($ZK.EditorPane).registerEditorPane($7tb.create($ILb, $ILb.ID, "Notebook Editor"), [
  new $Nk($trb)
]);
$Wn.as($ZK.EditorPane).registerEditorPane($7tb.create($A2b, $A2b.ID, "Notebook Diff Editor"), [
  new $Nk($$1b)
]);
$Wn.as($ZK.EditorPane).registerEditorPane($7tb.create($03b, $03b.ID, "Notebook Diff Editor"), [
  new $Nk($c2b)
]);
var NotebookDiffEditorSerializer = class NotebookDiffEditorSerializer2 {
  constructor(a) {
    this.a = a;
  }
  canSerialize() {
    return true;
  }
  serialize(input) {
    $Jg(input instanceof $$1b);
    return JSON.stringify({
      resource: input.resource,
      originalResource: input.original.resource,
      name: input.getName(),
      originalName: input.original.getName(),
      textDiffName: input.getName(),
      viewType: input.viewType
    });
  }
  deserialize(instantiationService, raw) {
    const data = $bu(raw);
    if (!data) {
      return void 0;
    }
    const { resource, originalResource, name, viewType } = data;
    if (!data || !URI.isUri(resource) || !URI.isUri(originalResource) || typeof name !== "string" || typeof viewType !== "string") {
      return void 0;
    }
    if (this.a.getValue("notebook.experimental.enableNewDiffEditor")) {
      return $c2b.create(instantiationService, resource, name, void 0, originalResource, viewType);
    } else {
      return $$1b.create(instantiationService, resource, name, void 0, originalResource, viewType);
    }
  }
  static canResolveBackup(editorInput, backupResource) {
    return false;
  }
};
NotebookDiffEditorSerializer = __decorate([
  __param(0, $kl)
], NotebookDiffEditorSerializer);
var NotebookEditorSerializer = class {
  canSerialize(input) {
    return input.typeId === $trb.ID;
  }
  serialize(input) {
    $Jg(input instanceof $trb);
    const data = {
      resource: input.resource,
      preferredResource: input.preferredResource,
      viewType: input.viewType,
      options: input.options
    };
    return JSON.stringify(data);
  }
  deserialize(instantiationService, raw) {
    const data = $bu(raw);
    if (!data) {
      return void 0;
    }
    const { resource, preferredResource, viewType, options: options3 } = data;
    if (!data || !URI.isUri(resource) || typeof viewType !== "string") {
      return void 0;
    }
    const input = $trb.getOrCreate(instantiationService, resource, preferredResource, viewType, options3);
    return input;
  }
};
$Wn.as($ZK.EditorFactory).registerEditorSerializer($trb.ID, NotebookEditorSerializer);
$Wn.as($ZK.EditorFactory).registerEditorSerializer($$1b.ID, NotebookDiffEditorSerializer);
var $P5b = class $P5b2 extends $3c {
  static {
    $P5b_1 = this;
  }
  static {
    this.ID = "workbench.contrib.notebook";
  }
  constructor(undoRedoService, configurationService, b) {
    super();
    this.b = b;
    this.c(configurationService, undoRedoService);
    this.B(configurationService.onDidChangeConfiguration((e) => {
      if (e.affectsConfiguration($rM.undoRedoPerCell)) {
        this.c(configurationService, undoRedoService);
      }
    }));
    this.b.registerDecorationType("comment-controller", $4Jb, {});
  }
  // Add or remove the cell undo redo comparison key based on the user setting
  c(configurationService, undoRedoService) {
    const undoRedoPerCell = configurationService.getValue($rM.undoRedoPerCell);
    if (!undoRedoPerCell) {
      if (!this.a) {
        this.a = undoRedoService.registerUriComparisonKeyComputer(CellUri.scheme, {
          getComparisonKey: (uri) => {
            if (undoRedoPerCell) {
              return uri.toString();
            }
            return $P5b_1.f(uri);
          }
        });
      }
    } else {
      this.a?.dispose();
      this.a = void 0;
    }
  }
  static f(uri) {
    const data = CellUri.parse(uri);
    if (!data) {
      return uri.toString();
    }
    return data.notebook.toString();
  }
  dispose() {
    super.dispose();
    this.a?.dispose();
  }
};
$P5b = $P5b_1 = __decorate([
  __param(0, $_F),
  __param(1, $kl),
  __param(2, $U5)
], $P5b);
var CellContentProvider = class CellContentProvider2 {
  static {
    this.ID = "workbench.contrib.cellContentProvider";
  }
  constructor(textModelService, b, c, d) {
    this.b = b;
    this.c = c;
    this.d = d;
    this.a = textModelService.registerTextModelContentProvider(CellUri.scheme, this);
  }
  dispose() {
    this.a.dispose();
  }
  async provideTextContent(resource) {
    const existing = this.b.getModel(resource);
    if (existing) {
      return existing;
    }
    const data = CellUri.parse(resource);
    if (!data) {
      return null;
    }
    const ref = await this.d.resolve(data.notebook);
    let result = null;
    if (!ref.object.isResolved()) {
      return null;
    }
    for (const cell of ref.object.notebook.cells) {
      if (cell.uri.toString() === resource.toString()) {
        const bufferFactory = {
          create: (defaultEOL) => {
            const newEOL = defaultEOL === 2 ? "\r\n" : "\n";
            cell.textBuffer.setEOL(newEOL);
            return { textBuffer: cell.textBuffer, disposable: $3c.None };
          },
          getFirstLineText: (limit) => {
            return cell.textBuffer.getLineContent(1).substring(0, limit);
          }
        };
        const languageId = this.c.getLanguageIdByLanguageName(cell.language);
        const languageSelection = languageId ? this.c.createById(languageId) : cell.cellKind === CellKind.Markup ? this.c.createById("markdown") : this.c.createByFilepathOrFirstLine(resource, cell.textBuffer.getLineContent(1));
        result = this.b.createModel(bufferFactory, languageSelection, resource);
        break;
      }
    }
    if (!result) {
      ref.dispose();
      return null;
    }
    const once = Event2.any(result.onWillDispose, ref.object.notebook.onWillDispose)(() => {
      once.dispose();
      ref.dispose();
    });
    return result;
  }
};
CellContentProvider = __decorate([
  __param(0, $oG),
  __param(1, $sG),
  __param(2, $1E),
  __param(3, $orb)
], CellContentProvider);
var CellInfoContentProvider = class CellInfoContentProvider2 {
  static {
    this.ID = "workbench.contrib.cellInfoContentProvider";
  }
  constructor(textModelService, b, c, d, f) {
    this.b = b;
    this.c = c;
    this.d = d;
    this.f = f;
    this.a = [];
    this.a.push(textModelService.registerTextModelContentProvider(Schemas.vscodeNotebookCellMetadata, {
      provideTextContent: this.provideMetadataTextContent.bind(this)
    }));
    this.a.push(textModelService.registerTextModelContentProvider(Schemas.vscodeNotebookCellOutput, {
      provideTextContent: this.provideOutputTextContent.bind(this)
    }));
    this.a.push(this.d.registerFormatter({
      scheme: Schemas.vscodeNotebookCellMetadata,
      formatting: {
        label: "${path} (metadata)",
        separator: "/"
      }
    }));
    this.a.push(this.d.registerFormatter({
      scheme: Schemas.vscodeNotebookCellOutput,
      formatting: {
        label: "${path} (output)",
        separator: "/"
      }
    }));
  }
  dispose() {
    $Xc(this.a);
  }
  async provideMetadataTextContent(resource) {
    const existing = this.b.getModel(resource);
    if (existing) {
      return existing;
    }
    const data = CellUri.parseCellPropertyUri(resource, Schemas.vscodeNotebookCellMetadata);
    if (!data) {
      return null;
    }
    const ref = await this.f.resolve(data.notebook);
    let result = null;
    const mode = this.c.createById("json");
    const disposables = new $2c();
    for (const cell of ref.object.notebook.cells) {
      if (cell.handle === data.handle) {
        const cellIndex = ref.object.notebook.cells.indexOf(cell);
        const metadataSource = $uL(ref.object.notebook.transientOptions.transientCellMetadata, cell.metadata, cell.language);
        result = this.b.createModel(metadataSource, mode, resource);
        this.a.push(disposables.add(ref.object.notebook.onDidChangeContent((e) => {
          if (result && e.rawEvents.some((event) => (event.kind === NotebookCellsChangeType.ChangeCellMetadata || event.kind === NotebookCellsChangeType.ChangeCellLanguage) && event.index === cellIndex)) {
            const value = $uL(ref.object.notebook.transientOptions.transientCellMetadata, cell.metadata, cell.language);
            if (result.getValue() !== value) {
              result.setValue($uL(ref.object.notebook.transientOptions.transientCellMetadata, cell.metadata, cell.language));
            }
          }
        })));
        break;
      }
    }
    if (!result) {
      ref.dispose();
      return null;
    }
    const once = result.onWillDispose(() => {
      disposables.dispose();
      once.dispose();
      ref.dispose();
    });
    return result;
  }
  g(op) {
    if (!op) {
      return;
    }
    const streamOutputData = $rEb(op.outputs);
    if (streamOutputData) {
      return {
        content: streamOutputData,
        mode: this.c.createById($KF)
      };
    }
    return;
  }
  h(data, cell) {
    let result = void 0;
    const mode = this.c.createById("json");
    const op = cell.outputs.find((op2) => op2.outputId === data.outputId || op2.alternativeOutputId === data.outputId);
    const streamOutputData = this.g(op);
    if (streamOutputData) {
      result = streamOutputData;
      return result;
    }
    const obj = cell.outputs.map((output) => ({
      metadata: output.metadata,
      outputItems: output.outputs.map((opit) => ({
        mimeType: opit.mime,
        data: opit.data.toString()
      }))
    }));
    const outputSource = $Tw(obj, {});
    result = {
      content: outputSource,
      mode
    };
    return result;
  }
  async provideOutputsTextContent(resource) {
    const existing = this.b.getModel(resource);
    if (existing) {
      return existing;
    }
    const data = CellUri.parseCellPropertyUri(resource, Schemas.vscodeNotebookCellOutput);
    if (!data) {
      return null;
    }
    const ref = await this.f.resolve(data.notebook);
    const cell = ref.object.notebook.cells.find((cell2) => cell2.handle === data.handle);
    if (!cell) {
      ref.dispose();
      return null;
    }
    const mode = this.c.createById("json");
    const model = this.b.createModel($sEb(cell.outputs || []), mode, resource, true);
    const cellModelListener = Event2.any(cell.onDidChangeOutputs ?? Event2.None, cell.onDidChangeOutputItems ?? Event2.None)(() => {
      model.setValue($sEb(cell.outputs || []));
    });
    const once = model.onWillDispose(() => {
      once.dispose();
      cellModelListener.dispose();
      ref.dispose();
    });
    return model;
  }
  async provideOutputTextContent(resource) {
    const existing = this.b.getModel(resource);
    if (existing) {
      return existing;
    }
    const data = CellUri.parseCellOutputUri(resource);
    if (!data) {
      return this.provideOutputsTextContent(resource);
    }
    const ref = await this.f.resolve(data.notebook);
    const cell = ref.object.notebook.cells.find((cell2) => !!cell2.outputs.find((op) => op.outputId === data.outputId || op.alternativeOutputId === data.outputId));
    if (!cell) {
      ref.dispose();
      return null;
    }
    const result = this.h(data, cell);
    if (!result) {
      ref.dispose();
      return null;
    }
    const model = this.b.createModel(result.content, result.mode, resource);
    const cellModelListener = Event2.any(cell.onDidChangeOutputs ?? Event2.None, cell.onDidChangeOutputItems ?? Event2.None)(() => {
      const newResult = this.h(data, cell);
      if (!newResult) {
        return;
      }
      model.setValue(newResult.content);
      model.setLanguage(newResult.mode.languageId);
    });
    const once = model.onWillDispose(() => {
      once.dispose();
      cellModelListener.dispose();
      ref.dispose();
    });
    return model;
  }
};
CellInfoContentProvider = __decorate([
  __param(0, $oG),
  __param(1, $sG),
  __param(2, $1E),
  __param(3, $ZI),
  __param(4, $orb)
], CellInfoContentProvider);
var NotebookMetadataContentProvider = class NotebookMetadataContentProvider2 {
  static {
    this.ID = "workbench.contrib.notebookMetadataContentProvider";
  }
  constructor(textModelService, b, c, d, f) {
    this.b = b;
    this.c = c;
    this.d = d;
    this.f = f;
    this.a = [];
    this.a.push(textModelService.registerTextModelContentProvider(Schemas.vscodeNotebookMetadata, {
      provideTextContent: this.provideMetadataTextContent.bind(this)
    }));
    this.a.push(this.d.registerFormatter({
      scheme: Schemas.vscodeNotebookMetadata,
      formatting: {
        label: "${path} (metadata)",
        separator: "/"
      }
    }));
  }
  dispose() {
    $Xc(this.a);
  }
  async provideMetadataTextContent(resource) {
    const existing = this.b.getModel(resource);
    if (existing) {
      return existing;
    }
    const data = NotebookMetadataUri.parse(resource);
    if (!data) {
      return null;
    }
    const ref = await this.f.resolve(data);
    let result = null;
    const mode = this.c.createById("json");
    const disposables = new $2c();
    const metadataSource = $fEb(ref.object.notebook.transientOptions.transientDocumentMetadata, ref.object.notebook.metadata);
    result = this.b.createModel(metadataSource, mode, resource);
    if (!result) {
      ref.dispose();
      return null;
    }
    this.a.push(disposables.add(ref.object.notebook.onDidChangeContent((e) => {
      if (result && e.rawEvents.some((event) => event.kind === NotebookCellsChangeType.ChangeCellContent || event.kind === NotebookCellsChangeType.ChangeDocumentMetadata || event.kind === NotebookCellsChangeType.ModelChange)) {
        const value = $fEb(ref.object.notebook.transientOptions.transientDocumentMetadata, ref.object.notebook.metadata);
        if (result.getValue() !== value) {
          result.setValue(value);
        }
      }
    })));
    const once = result.onWillDispose(() => {
      disposables.dispose();
      once.dispose();
      ref.dispose();
    });
    return result;
  }
};
NotebookMetadataContentProvider = __decorate([
  __param(0, $oG),
  __param(1, $sG),
  __param(2, $1E),
  __param(3, $ZI),
  __param(4, $orb)
], NotebookMetadataContentProvider);
var RegisterSchemasContribution = class extends $3c {
  static {
    this.ID = "workbench.contrib.registerCellSchemas";
  }
  constructor() {
    super();
    this.a();
  }
  a() {
    const jsonRegistry6 = $Wn.as($Xn.JSONContribution);
    const metadataSchema = {
      properties: {
        ["language"]: {
          type: "string",
          description: "The language for the cell"
        }
      },
      // patternProperties: allSettings.patternProperties,
      additionalProperties: true,
      allowTrailingCommas: true,
      allowComments: true
    };
    jsonRegistry6.registerSchema("vscode://schemas/notebook/cellmetadata", metadataSchema);
  }
};
var NotebookEditorManager = class NotebookEditorManager2 {
  static {
    this.ID = "workbench.contrib.notebookEditorManager";
  }
  constructor(b, c, editorGroups) {
    this.b = b;
    this.c = c;
    this.a = new $2c();
    this.a.add(Event2.debounce(this.c.onDidChangeDirty, (last, current) => !last ? [current] : [...last, current], 100)(this.d, this));
    this.a.add(c.onWillFailWithConflict((e) => {
      for (const group2 of editorGroups.groups) {
        const conflictInputs = group2.editors.filter((input) => input instanceof $trb && input.viewType !== e.viewType && $oh(input.resource, e.resource));
        const p = group2.closeEditors(conflictInputs);
        e.waitUntil(p);
      }
    }));
  }
  dispose() {
    this.a.dispose();
  }
  d(models) {
    const result = [];
    for (const model of models) {
      if (model.isDirty() && !this.b.isOpened({ resource: model.resource, typeId: $trb.ID, editorId: model.viewType }) && $th(model.resource) !== ".interactive") {
        result.push({
          resource: model.resource,
          options: { inactive: true, preserveFocus: true, pinned: true, override: model.viewType }
        });
      }
    }
    if (result.length > 0) {
      this.b.openEditors(result);
    }
  }
};
NotebookEditorManager = __decorate([
  __param(0, $mJ),
  __param(1, $orb),
  __param(2, $iJ)
], NotebookEditorManager);
var SimpleNotebookWorkingCopyEditorHandler = class SimpleNotebookWorkingCopyEditorHandler2 extends $3c {
  static {
    this.ID = "workbench.contrib.simpleNotebookWorkingCopyEditorHandler";
  }
  constructor(a, b, c, f) {
    super();
    this.a = a;
    this.b = b;
    this.c = c;
    this.f = f;
    this.h();
  }
  async handles(workingCopy) {
    const viewType = this.g(workingCopy);
    if (!viewType) {
      return false;
    }
    return this.f.canResolve(viewType);
  }
  g(workingCopy) {
    const viewType = this.j(workingCopy);
    if (!viewType || viewType === "interactive") {
      return void 0;
    }
    return viewType;
  }
  isOpen(workingCopy, editor) {
    if (!this.g(workingCopy)) {
      return false;
    }
    return editor instanceof $trb && editor.viewType === this.j(workingCopy) && $oh(workingCopy.resource, editor.resource);
  }
  createEditor(workingCopy) {
    return $trb.getOrCreate(this.a, workingCopy.resource, void 0, this.j(workingCopy));
  }
  async h() {
    await this.c.whenInstalledExtensionsRegistered();
    this.B(this.b.registerHandler(this));
  }
  j(workingCopy) {
    const notebookType = $sM.parse(workingCopy.typeId);
    if (notebookType && notebookType.viewType === notebookType.notebookType) {
      return notebookType?.viewType;
    }
    return void 0;
  }
};
SimpleNotebookWorkingCopyEditorHandler = __decorate([
  __param(0, $Pk),
  __param(1, $6J),
  __param(2, $wN),
  __param(3, $mrb)
], SimpleNotebookWorkingCopyEditorHandler);
var NotebookLanguageSelectorScoreRefine = class NotebookLanguageSelectorScoreRefine2 {
  static {
    this.ID = "workbench.contrib.notebookLanguageSelectorScoreRefine";
  }
  constructor(a, languageFeaturesService) {
    this.a = a;
    languageFeaturesService.setNotebookTypeResolver(this.b.bind(this));
  }
  b(uri) {
    const cellUri = CellUri.parse(uri);
    if (!cellUri) {
      return void 0;
    }
    const notebook = this.a.getNotebookTextModel(cellUri.notebook);
    if (!notebook) {
      return void 0;
    }
    return {
      uri: notebook.uri,
      type: notebook.viewType
    };
  }
};
NotebookLanguageSelectorScoreRefine = __decorate([
  __param(0, $mrb),
  __param(1, $mP)
], NotebookLanguageSelectorScoreRefine);
var workbenchContributionsRegistry4 = $Wn.as(Extensions2.Workbench);
$PL(
  $P5b.ID,
  $P5b,
  1
  /* WorkbenchPhase.BlockStartup */
);
$PL(
  CellContentProvider.ID,
  CellContentProvider,
  1
  /* WorkbenchPhase.BlockStartup */
);
$PL(
  CellInfoContentProvider.ID,
  CellInfoContentProvider,
  1
  /* WorkbenchPhase.BlockStartup */
);
$PL(
  NotebookMetadataContentProvider.ID,
  NotebookMetadataContentProvider,
  1
  /* WorkbenchPhase.BlockStartup */
);
$PL(
  RegisterSchemasContribution.ID,
  RegisterSchemasContribution,
  1
  /* WorkbenchPhase.BlockStartup */
);
$PL(
  NotebookEditorManager.ID,
  NotebookEditorManager,
  2
  /* WorkbenchPhase.BlockRestore */
);
$PL(
  NotebookLanguageSelectorScoreRefine.ID,
  NotebookLanguageSelectorScoreRefine,
  2
  /* WorkbenchPhase.BlockRestore */
);
$PL(
  SimpleNotebookWorkingCopyEditorHandler.ID,
  SimpleNotebookWorkingCopyEditorHandler,
  2
  /* WorkbenchPhase.BlockRestore */
);
workbenchContributionsRegistry4.registerWorkbenchContribution(
  $J5b,
  4
  /* LifecyclePhase.Eventually */
);
$vhb.register(new $L5b());
$vhb.register(new $K5b());
$SC(
  $mrb,
  $g2b,
  1
  /* InstantiationType.Delayed */
);
$SC(
  $uEb,
  $D2b,
  1
  /* InstantiationType.Delayed */
);
$SC(
  $orb,
  $G2b,
  1
  /* InstantiationType.Delayed */
);
$SC(
  $DSb,
  $E2b,
  1
  /* InstantiationType.Delayed */
);
$SC(
  $yMb,
  $F2b,
  1
  /* InstantiationType.Delayed */
);
$SC(
  $CL,
  $H2b,
  1
  /* InstantiationType.Delayed */
);
$SC(
  $DL,
  $f4b,
  1
  /* InstantiationType.Delayed */
);
$SC(
  $vL,
  $_3b,
  1
  /* InstantiationType.Delayed */
);
$SC(
  $wL,
  $$3b,
  1
  /* InstantiationType.Delayed */
);
$SC(
  $CJb,
  $I2b,
  1
  /* InstantiationType.Delayed */
);
$SC(
  $a4b,
  $d4b,
  1
  /* InstantiationType.Delayed */
);
$SC(
  $qFb,
  $g4b,
  1
  /* InstantiationType.Delayed */
);
$SC(
  $OLb,
  $PLb,
  1
  /* InstantiationType.Delayed */
);
$SC(
  $FLb,
  $GLb,
  1
  /* InstantiationType.Delayed */
);
$SC(
  $PSb,
  $O5b,
  1
  /* InstantiationType.Delayed */
);
var schemas = {};
function isConfigurationPropertySchema2(x) {
  return typeof x.type !== "undefined" || typeof x.anyOf !== "undefined";
}
for (const editorOption of editorOptionsRegistry) {
  const schema9 = editorOption.schema;
  if (schema9) {
    if (isConfigurationPropertySchema2(schema9)) {
      schemas[`editor.${editorOption.name}`] = schema9;
    } else {
      for (const key2 in schema9) {
        if (Object.hasOwnProperty.call(schema9, key2)) {
          schemas[key2] = schema9[key2];
        }
      }
    }
  }
}
var editorOptionsCustomizationSchema = {
  description: localize(8400, null),
  default: {},
  allOf: [
    {
      properties: schemas
    }
    // , {
    // 	patternProperties: {
    // 		'^\\[.*\\]$': {
    // 			type: 'object',
    // 			default: {},
    // 			properties: schemas
    // 		}
    // 	}
    // }
  ],
  tags: ["notebookLayout"]
};
var configurationRegistry8 = $Wn.as($Ht.Configuration);
configurationRegistry8.registerConfiguration({
  id: "notebook",
  order: 100,
  title: localize(8401, null),
  type: "object",
  properties: {
    [$rM.displayOrder]: {
      description: localize(8402, null),
      type: "array",
      items: {
        type: "string"
      },
      default: []
    },
    [$rM.cellToolbarLocation]: {
      description: localize(8403, null),
      type: "object",
      additionalProperties: {
        markdownDescription: localize(8404, null),
        type: "string",
        enum: ["left", "right", "hidden"]
      },
      default: {
        "default": "right"
      },
      tags: ["notebookLayout"]
    },
    [$rM.showCellStatusBar]: {
      description: localize(8405, null),
      type: "string",
      enum: ["hidden", "visible", "visibleAfterExecute"],
      enumDescriptions: [
        localize(8406, null),
        localize(8407, null),
        localize(8408, null)
      ],
      default: "visible",
      tags: ["notebookLayout"]
    },
    [$rM.cellExecutionTimeVerbosity]: {
      description: localize(8409, null),
      type: "string",
      enum: ["default", "verbose"],
      enumDescriptions: [
        localize(8410, null),
        localize(8411, null)
      ],
      default: "default",
      tags: ["notebookLayout"]
    },
    [$rM.textDiffEditorPreview]: {
      description: localize(8412, null),
      type: "boolean",
      default: true,
      tags: ["notebookLayout"]
    },
    [$rM.diffOverviewRuler]: {
      description: localize(8413, null),
      type: "boolean",
      default: false,
      tags: ["notebookLayout"]
    },
    [$rM.cellToolbarVisibility]: {
      markdownDescription: localize(8414, null),
      type: "string",
      enum: ["hover", "click"],
      default: "click",
      tags: ["notebookLayout"]
    },
    [$rM.undoRedoPerCell]: {
      description: localize(8415, null),
      type: "boolean",
      default: true,
      tags: ["notebookLayout"]
    },
    [$rM.compactView]: {
      description: localize(8416, null),
      type: "boolean",
      default: true,
      tags: ["notebookLayout"]
    },
    [$rM.focusIndicator]: {
      description: localize(8417, null),
      type: "string",
      enum: ["border", "gutter"],
      default: "gutter",
      tags: ["notebookLayout"]
    },
    [$rM.insertToolbarLocation]: {
      description: localize(8418, null),
      type: "string",
      enum: ["betweenCells", "notebookToolbar", "both", "hidden"],
      enumDescriptions: [
        localize(8419, null),
        localize(8420, null),
        localize(8421, null),
        localize(8422, null)
      ],
      default: "both",
      tags: ["notebookLayout"]
    },
    [$rM.globalToolbar]: {
      description: localize(8423, null),
      type: "boolean",
      default: true,
      tags: ["notebookLayout"]
    },
    [$rM.stickyScrollEnabled]: {
      description: localize(8424, null),
      type: "boolean",
      default: false,
      tags: ["notebookLayout"]
    },
    [$rM.stickyScrollMode]: {
      description: localize(8425, null),
      type: "string",
      enum: ["flat", "indented"],
      enumDescriptions: [
        localize(8426, null),
        localize(8427, null)
      ],
      default: "indented",
      tags: ["notebookLayout"]
    },
    [$rM.consolidatedOutputButton]: {
      description: localize(8428, null),
      type: "boolean",
      default: true,
      tags: ["notebookLayout"]
    },
    [$rM.showFoldingControls]: {
      description: localize(8429, null),
      type: "string",
      enum: ["always", "never", "mouseover"],
      enumDescriptions: [
        localize(8430, null),
        localize(8431, null),
        localize(8432, null)
      ],
      default: "mouseover",
      tags: ["notebookLayout"]
    },
    [$rM.dragAndDropEnabled]: {
      description: localize(8433, null),
      type: "boolean",
      default: true,
      tags: ["notebookLayout"]
    },
    [$rM.consolidatedRunButton]: {
      description: localize(8434, null),
      type: "boolean",
      default: false,
      tags: ["notebookLayout"]
    },
    [$rM.globalToolbarShowLabel]: {
      description: localize(8435, null),
      type: "string",
      enum: ["always", "never", "dynamic"],
      default: "always",
      tags: ["notebookLayout"]
    },
    [$rM.textOutputLineLimit]: {
      markdownDescription: localize(8436, null, "`#notebook.output.scrolling#`"),
      type: "number",
      default: 30,
      tags: ["notebookLayout", "notebookOutputLayout"],
      minimum: 1
    },
    [$rM.LinkifyOutputFilePaths]: {
      description: localize(8437, null),
      type: "boolean",
      default: true,
      tags: ["notebookOutputLayout"]
    },
    [$rM.minimalErrorRendering]: {
      description: localize(8438, null),
      type: "boolean",
      default: false,
      tags: ["notebookOutputLayout"]
    },
    [$rM.markupFontSize]: {
      markdownDescription: localize(8439, null, "`0`", "`#editor.fontSize#`"),
      type: "number",
      default: 0,
      tags: ["notebookLayout"]
    },
    [$rM.markdownLineHeight]: {
      markdownDescription: localize(8440, null, "`0`", "`normal`"),
      type: "number",
      default: 0,
      tags: ["notebookLayout"]
    },
    [$rM.cellEditorOptionsCustomizations]: editorOptionsCustomizationSchema,
    [$rM.interactiveWindowCollapseCodeCells]: {
      markdownDescription: localize(8441, null),
      type: "string",
      enum: ["always", "never", "fromEditor"],
      default: "fromEditor"
    },
    [$rM.outputLineHeight]: {
      markdownDescription: localize(8442, null),
      type: "number",
      default: 0,
      tags: ["notebookLayout", "notebookOutputLayout"]
    },
    [$rM.outputFontSize]: {
      markdownDescription: localize(8443, null, "`#editor.fontSize#`"),
      type: "number",
      default: 0,
      tags: ["notebookLayout", "notebookOutputLayout"]
    },
    [$rM.outputFontFamily]: {
      markdownDescription: localize(8444, null, "`#editor.fontFamily#`"),
      type: "string",
      tags: ["notebookLayout", "notebookOutputLayout"]
    },
    [$rM.outputScrolling]: {
      markdownDescription: localize(8445, null),
      type: "boolean",
      tags: ["notebookLayout", "notebookOutputLayout"],
      default: typeof product_default.quality === "string" && product_default.quality !== "stable"
      // only enable as default in insiders
    },
    [$rM.outputWordWrap]: {
      markdownDescription: localize(8446, null),
      type: "boolean",
      tags: ["notebookLayout", "notebookOutputLayout"],
      default: false
    },
    [$rM.defaultFormatter]: {
      description: localize(8447, null),
      type: ["string", "null"],
      default: null,
      enum: $N5b.extensionIds,
      enumItemLabels: $N5b.extensionItemLabels,
      markdownEnumDescriptions: $N5b.extensionDescriptions
    },
    [$rM.formatOnSave]: {
      markdownDescription: localize(8448, null, "`#files.autoSave#`"),
      type: "boolean",
      tags: ["notebookLayout"],
      default: false
    },
    [$rM.insertFinalNewline]: {
      markdownDescription: localize(8449, null),
      type: "boolean",
      tags: ["notebookLayout"],
      default: false
    },
    [$rM.formatOnCellExecution]: {
      markdownDescription: localize(8450, null),
      type: "boolean",
      default: false
    },
    [$rM.confirmDeleteRunningCell]: {
      markdownDescription: localize(8451, null),
      type: "boolean",
      default: true
    },
    [$rM.findFilters]: {
      markdownDescription: localize(8452, null),
      type: "object",
      properties: {
        markupSource: {
          type: "boolean",
          default: true
        },
        markupPreview: {
          type: "boolean",
          default: true
        },
        codeSource: {
          type: "boolean",
          default: true
        },
        codeOutput: {
          type: "boolean",
          default: true
        }
      },
      default: {
        markupSource: true,
        markupPreview: true,
        codeSource: true,
        codeOutput: true
      },
      tags: ["notebookLayout"]
    },
    [$rM.remoteSaving]: {
      markdownDescription: localize(8453, null),
      type: "boolean",
      default: typeof product_default.quality === "string" && product_default.quality !== "stable",
      // only enable as default in insiders
      tags: ["experimental"]
    },
    [$rM.scrollToRevealCell]: {
      markdownDescription: localize(8454, null, "notebook.cell.executeAndSelectBelow"),
      type: "string",
      enum: ["fullCell", "firstLine", "none"],
      markdownEnumDescriptions: [
        localize(8455, null),
        localize(8456, null),
        localize(8457, null)
      ],
      default: "fullCell"
    },
    [$rM.cellGenerate]: {
      markdownDescription: localize(8458, null),
      type: "boolean",
      default: true
    },
    [$rM.notebookVariablesView]: {
      markdownDescription: localize(8459, null),
      type: "boolean",
      default: false
    },
    [$rM.cellFailureDiagnostics]: {
      markdownDescription: localize(8460, null),
      type: "boolean",
      default: true
    },
    [$rM.outputBackupSizeLimit]: {
      markdownDescription: localize(8461, null),
      type: "number",
      default: 1e4
    },
    [$rM.multiCursor]: {
      markdownDescription: localize(8462, null),
      type: "boolean",
      default: false
    }
  }
});

// out-build/vs/workbench/contrib/speech/browser/speechService.js
var speechProvidersExtensionPoint = $tN.registerExtensionPoint({
  extensionPoint: "speechProviders",
  jsonSchema: {
    description: localize(9895, null),
    type: "array",
    items: {
      additionalProperties: false,
      type: "object",
      defaultSnippets: [{ body: { name: "", description: "" } }],
      required: ["name"],
      properties: {
        name: {
          description: localize(9896, null),
          type: "string"
        },
        description: {
          description: localize(9897, null),
          type: "string"
        }
      }
    }
  }
});
var $Q5b = class $Q5b2 extends $3c {
  get hasSpeechProvider() {
    return this.c.size > 0 || this.b.size > 0;
  }
  constructor(g, h3, j, m, n, r2) {
    super();
    this.g = g;
    this.h = h3;
    this.j = j;
    this.m = m;
    this.n = n;
    this.r = r2;
    this.a = this.B(new $ze());
    this.onDidChangeHasSpeechProvider = this.a.event;
    this.b = /* @__PURE__ */ new Map();
    this.c = /* @__PURE__ */ new Map();
    this.f = $kS.bindTo(this.h);
    this.u = this.B(new $ze());
    this.onDidStartSpeechToTextSession = this.u.event;
    this.w = this.B(new $ze());
    this.onDidEndSpeechToTextSession = this.w.event;
    this.y = 0;
    this.z = $lS.bindTo(this.h);
    this.D = this.B(new $ze());
    this.onDidStartTextToSpeechSession = this.D.event;
    this.F = this.B(new $ze());
    this.onDidEndTextToSpeechSession = this.F.event;
    this.G = 0;
    this.H = $mS.bindTo(this.h);
    this.I = this.B(new $ze());
    this.onDidStartKeywordRecognition = this.I.event;
    this.J = this.B(new $ze());
    this.onDidEndKeywordRecognition = this.J.event;
    this.L = 0;
    this.s();
  }
  s() {
    speechProvidersExtensionPoint.setHandler((extensions, delta) => {
      const oldHasSpeechProvider = this.hasSpeechProvider;
      for (const extension of delta.removed) {
        for (const descriptor of extension.value) {
          this.c.delete(descriptor.name);
        }
      }
      for (const extension of delta.added) {
        for (const descriptor of extension.value) {
          this.c.set(descriptor.name, descriptor);
        }
      }
      if (oldHasSpeechProvider !== this.hasSpeechProvider) {
        this.t();
      }
    });
  }
  registerSpeechProvider(identifier2, provider) {
    if (this.b.has(identifier2)) {
      throw new Error(`Speech provider with identifier ${identifier2} is already registered.`);
    }
    const oldHasSpeechProvider = this.hasSpeechProvider;
    this.b.set(identifier2, provider);
    if (oldHasSpeechProvider !== this.hasSpeechProvider) {
      this.t();
    }
    return $1c(() => {
      const oldHasSpeechProvider2 = this.hasSpeechProvider;
      this.b.delete(identifier2);
      if (oldHasSpeechProvider2 !== this.hasSpeechProvider) {
        this.t();
      }
    });
  }
  t() {
    this.f.set(this.hasSpeechProvider);
    this.a.fire();
  }
  get hasActiveSpeechToTextSession() {
    return this.y > 0;
  }
  async createSpeechToTextSession(token, context = "speech") {
    const provider = await this.C();
    const language = $pS(this.n.getValue($nS));
    const session = provider.createSpeechToTextSession(token, typeof language === "string" ? { language } : void 0);
    const sessionStart = Date.now();
    let sessionRecognized = false;
    let sessionError = false;
    let sessionContentLength = 0;
    const disposables = new $2c();
    const onSessionStoppedOrCanceled = () => {
      this.y = Math.max(0, this.y - 1);
      if (!this.hasActiveSpeechToTextSession) {
        this.z.reset();
      }
      this.w.fire();
      this.m.publicLog2("speechToTextSession", {
        context,
        sessionDuration: Date.now() - sessionStart,
        sessionRecognized,
        sessionError,
        sessionContentLength,
        sessionLanguage: language
      });
      disposables.dispose();
    };
    disposables.add(token.onCancellationRequested(() => onSessionStoppedOrCanceled()));
    if (token.isCancellationRequested) {
      onSessionStoppedOrCanceled();
    }
    disposables.add(session.onDidChange((e) => {
      switch (e.status) {
        case SpeechToTextStatus2.Started:
          this.y++;
          this.z.set(true);
          this.u.fire();
          break;
        case SpeechToTextStatus2.Recognizing:
          sessionRecognized = true;
          break;
        case SpeechToTextStatus2.Recognized:
          if (typeof e.text === "string") {
            sessionContentLength += e.text.length;
          }
          break;
        case SpeechToTextStatus2.Stopped:
          onSessionStoppedOrCanceled();
          break;
        case SpeechToTextStatus2.Error:
          this.g.error(`Speech provider error in speech to text session: ${e.text}`);
          sessionError = true;
          break;
      }
    }));
    return session;
  }
  async C() {
    await this.r.activateByEvent("onSpeech");
    const provider = Array.from(this.b.values()).at(0);
    if (!provider) {
      throw new Error(`No Speech provider is registered.`);
    } else if (this.b.size > 1) {
      this.g.warn(`Multiple speech providers registered. Picking first one: ${provider.metadata.displayName}`);
    }
    return provider;
  }
  get hasActiveTextToSpeechSession() {
    return this.G > 0;
  }
  async createTextToSpeechSession(token, context = "speech") {
    const provider = await this.C();
    const language = $pS(this.n.getValue($nS));
    const session = provider.createTextToSpeechSession(token, typeof language === "string" ? { language } : void 0);
    const sessionStart = Date.now();
    let sessionError = false;
    const disposables = new $2c();
    const onSessionStoppedOrCanceled = (dispose) => {
      this.G = Math.max(0, this.G - 1);
      if (!this.hasActiveTextToSpeechSession) {
        this.H.reset();
      }
      this.F.fire();
      this.m.publicLog2("textToSpeechSession", {
        context,
        sessionDuration: Date.now() - sessionStart,
        sessionError,
        sessionLanguage: language
      });
      if (dispose) {
        disposables.dispose();
      }
    };
    disposables.add(token.onCancellationRequested(() => onSessionStoppedOrCanceled(true)));
    if (token.isCancellationRequested) {
      onSessionStoppedOrCanceled(true);
    }
    disposables.add(session.onDidChange((e) => {
      switch (e.status) {
        case TextToSpeechStatus2.Started:
          this.G++;
          this.H.set(true);
          this.D.fire();
          break;
        case TextToSpeechStatus2.Stopped:
          onSessionStoppedOrCanceled(false);
          break;
        case TextToSpeechStatus2.Error:
          this.g.error(`Speech provider error in text to speech session: ${e.text}`);
          sessionError = true;
          break;
      }
    }));
    return session;
  }
  get hasActiveKeywordRecognition() {
    return this.L > 0;
  }
  async recognizeKeyword(token) {
    const result = new $gi();
    const disposables = new $2c();
    disposables.add(token.onCancellationRequested(() => {
      disposables.dispose();
      result.complete(KeywordRecognitionStatus2.Canceled);
    }));
    const recognizeKeywordDisposables = disposables.add(new $2c());
    let activeRecognizeKeywordSession = void 0;
    const recognizeKeyword = () => {
      recognizeKeywordDisposables.clear();
      const cts = new $ad(token);
      recognizeKeywordDisposables.add($1c(() => cts.dispose(true)));
      const currentRecognizeKeywordSession = activeRecognizeKeywordSession = this.M(cts.token).then((status2) => {
        if (currentRecognizeKeywordSession === activeRecognizeKeywordSession) {
          result.complete(status2);
        }
      }, (error) => {
        if (currentRecognizeKeywordSession === activeRecognizeKeywordSession) {
          result.error(error);
        }
      });
    };
    disposables.add(this.j.onDidChangeFocus((focused) => {
      if (!focused && activeRecognizeKeywordSession) {
        recognizeKeywordDisposables.clear();
        activeRecognizeKeywordSession = void 0;
      } else if (!activeRecognizeKeywordSession) {
        recognizeKeyword();
      }
    }));
    if (this.j.hasFocus) {
      recognizeKeyword();
    }
    let status;
    try {
      status = await result.p;
    } finally {
      disposables.dispose();
    }
    this.m.publicLog2("keywordRecognition", {
      keywordRecognized: status === KeywordRecognitionStatus2.Recognized
    });
    return status;
  }
  async M(token) {
    const provider = await this.C();
    const session = provider.createKeywordRecognitionSession(token);
    this.L++;
    this.I.fire();
    const disposables = new $2c();
    const onSessionStoppedOrCanceled = () => {
      this.L = Math.max(0, this.L - 1);
      this.J.fire();
      disposables.dispose();
    };
    disposables.add(token.onCancellationRequested(() => onSessionStoppedOrCanceled()));
    if (token.isCancellationRequested) {
      onSessionStoppedOrCanceled();
    }
    disposables.add(session.onDidChange((e) => {
      if (e.status === KeywordRecognitionStatus2.Stopped) {
        onSessionStoppedOrCanceled();
      }
    }));
    try {
      return (await Event2.toPromise(session.onDidChange)).status;
    } finally {
      onSessionStoppedOrCanceled();
    }
  }
};
$Q5b = __decorate([
  __param(0, $wn),
  __param(1, $on),
  __param(2, $S4),
  __param(3, $zv),
  __param(4, $kl),
  __param(5, $wN)
], $Q5b);

// out-build/vs/workbench/contrib/speech/browser/speech.contribution.js
$SC(
  $jS,
  $Q5b,
  0
  /* InstantiationType.Eager */
);

// out-build/vs/workbench/contrib/chat/common/chatServiceTelemetry.js
var $R5b = class $R5b2 {
  constructor(a) {
    this.a = a;
  }
  notifyUserAction(action) {
    if (action.action.kind === "vote") {
      this.a.publicLog2("interactiveSessionVote", {
        direction: action.action.direction === ChatAgentVoteDirection.Up ? "up" : "down",
        agentId: action.agentId ?? "",
        command: action.command,
        reason: action.action.reason
      });
    } else if (action.action.kind === "copy") {
      this.a.publicLog2("interactiveSessionCopy", {
        copyKind: action.action.copyKind === ChatCopyKind2.Action ? "action" : "toolbar",
        agentId: action.agentId ?? "",
        command: action.command
      });
    } else if (action.action.kind === "insert") {
      this.a.publicLog2("interactiveSessionInsert", {
        newFile: !!action.action.newFile,
        agentId: action.agentId ?? "",
        command: action.command
      });
    } else if (action.action.kind === "apply") {
      this.a.publicLog2("interactiveSessionApply", {
        newFile: !!action.action.newFile,
        codeMapper: action.action.codeMapper,
        agentId: action.agentId ?? "",
        command: action.command,
        editsProposed: !!action.action.editsProposed
      });
    } else if (action.action.kind === "command") {
      const command4 = $tn.getCommand(action.action.commandButton.command.id);
      const commandId = command4 ? action.action.commandButton.command.id : "INVALID";
      this.a.publicLog2("interactiveSessionCommand", {
        commandId,
        agentId: action.agentId ?? "",
        command: action.command
      });
    } else if (action.action.kind === "runInTerminal") {
      this.a.publicLog2("interactiveSessionRunInTerminal", {
        languageId: action.action.languageId ?? "",
        agentId: action.agentId ?? "",
        command: action.command
      });
    } else if (action.action.kind === "followUp") {
      this.a.publicLog2("chatFollowupClicked", {
        agentId: action.agentId ?? "",
        command: action.command
      });
    }
  }
  retrievedFollowups(agentId, command4, numFollowups) {
    this.a.publicLog2("chatFollowupsRetrieved", {
      agentId,
      command: command4,
      numFollowups
    });
  }
};
$R5b = __decorate([
  __param(0, $zv)
], $R5b);

// out-build/vs/workbench/contrib/chat/common/chatServiceImpl.js
var serializedChatKey = "interactive.sessions";
var globalChatKey = "chat.workspaceTransfer";
var SESSION_TRANSFER_EXPIRATION_IN_MILLISECONDS = 1e3 * 60;
var maxPersistedSessions = 25;
var CancellableRequest = class {
  constructor(cancellationTokenSource, requestId) {
    this.cancellationTokenSource = cancellationTokenSource;
    this.requestId = requestId;
  }
  dispose() {
    this.cancellationTokenSource.dispose();
  }
  cancel() {
    this.cancellationTokenSource.cancel();
  }
};
var $S5b = class $S5b2 extends $3c {
  get transferredSessionData() {
    return this.j;
  }
  constructor(u, w, y, z, C, D, F, G, H, I) {
    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.I = I;
    this.c = this.B(new $_c());
    this.f = this.B(new $_c());
    this.h = /* @__PURE__ */ new Set();
    this.m = this.B(new $ze());
    this.onDidPerformUserAction = this.m.event;
    this.n = this.B(new $ze());
    this.onDidDisposeSession = this.n.event;
    this.s = this.B(new $_c());
    this.t = this.z.createInstance($R5b);
    const isEmptyWindow = !D.getWorkspace().folders.length;
    const sessionData = u.get(serializedChatKey, isEmptyWindow ? -1 : 1, "");
    if (sessionData) {
      this.g = this.O(sessionData);
      const countsForLog = Object.keys(this.g).length;
      if (countsForLog > 0) {
        this.M("constructor", `Restored ${countsForLog} persisted sessions`);
      }
    } else {
      this.g = {};
    }
    const transferredData = this.P();
    const transferredChat = transferredData?.chat;
    if (transferredChat) {
      this.M("constructor", `Transferred session ${transferredChat.sessionId}`);
      this.g[transferredChat.sessionId] = transferredChat;
      this.j = { sessionId: transferredChat.sessionId, inputValue: transferredData.inputValue };
    }
    this.B(u.onWillSaveState(() => this.J()));
  }
  isEnabled(location3) {
    return this.H.getContributedDefaultAgent(location3) !== void 0;
  }
  J() {
    const liveChats = Array.from(this.c.values()).filter((session) => session.initialLocation === ChatAgentLocation.Panel || session.initialLocation === ChatAgentLocation.EditingSession).filter((session) => session.getRequests().length > 0);
    const isEmptyWindow = !this.D.getWorkspace().folders.length;
    if (isEmptyWindow) {
      this.L(liveChats);
    } else {
      let allSessions = liveChats;
      allSessions = allSessions.concat(Object.values(this.g).filter((session) => !this.c.has(session.sessionId)).filter((session) => session.requests.length));
      allSessions.sort((a, b) => (b.creationDate ?? 0) - (a.creationDate ?? 0));
      allSessions = allSessions.slice(0, maxPersistedSessions);
      if (allSessions.length) {
        this.M("onWillSaveState", `Persisting ${allSessions.length} sessions`);
      }
      const serialized = JSON.stringify(allSessions);
      if (allSessions.length) {
        this.M("onWillSaveState", `Persisting ${serialized.length} chars`);
      }
      this.u.store(
        serializedChatKey,
        serialized,
        1,
        1
        /* StorageTarget.MACHINE */
      );
    }
    this.h.clear();
  }
  L(thisWindowChats) {
    const sessionData = this.u.get(serializedChatKey, -1, "");
    const originalPersistedSessions = this.g;
    let persistedSessions;
    if (sessionData) {
      persistedSessions = this.O(sessionData);
      const countsForLog = Object.keys(persistedSessions).length;
      if (countsForLog > 0) {
        this.M("constructor", `Restored ${countsForLog} persisted sessions`);
      }
    } else {
      persistedSessions = {};
    }
    this.h.forEach((id2) => delete persistedSessions[id2]);
    Object.values(originalPersistedSessions).forEach((session) => {
      const persistedSession = persistedSessions[session.sessionId];
      if (persistedSession && session.requests.length > persistedSession.requests.length) {
        persistedSessions[session.sessionId] = session;
      } else if (!persistedSession && session.isNew) {
        session.isNew = false;
        persistedSessions[session.sessionId] = session;
      }
    });
    this.g = persistedSessions;
    const allSessions = { ...this.g };
    for (const chat of thisWindowChats) {
      allSessions[chat.sessionId] = chat;
    }
    let sessionsList = Object.values(allSessions);
    sessionsList.sort((a, b) => (b.creationDate ?? 0) - (a.creationDate ?? 0));
    sessionsList = sessionsList.slice(0, maxPersistedSessions);
    const data = JSON.stringify(sessionsList);
    this.u.store(
      serializedChatKey,
      data,
      -1,
      1
      /* StorageTarget.MACHINE */
    );
  }
  notifyUserAction(action) {
    this.t.notifyUserAction(action);
    this.m.fire(action);
  }
  setChatSessionTitle(sessionId, title) {
    const model = this.c.get(sessionId);
    if (model) {
      model.setCustomTitle(title);
      return;
    }
    const session = this.g[sessionId];
    if (session) {
      session.customTitle = title;
    }
  }
  M(method, message) {
    if (message) {
      this.w.trace(`ChatService#${method}: ${message}`);
    } else {
      this.w.trace(`ChatService#${method}`);
    }
  }
  N(method, message) {
    this.w.error(`ChatService#${method} ${message}`);
  }
  O(sessionData) {
    try {
      const arrayOfSessions = $cu(JSON.parse(sessionData));
      if (!Array.isArray(arrayOfSessions)) {
        throw new Error("Expected array");
      }
      const sessions = arrayOfSessions.reduce((acc, session) => {
        for (const request of session.requests) {
          if (Array.isArray(request.response)) {
            request.response = request.response.map((response) => {
              if (typeof response === "string") {
                return new $bm(response);
              }
              return response;
            });
          } else if (typeof request.response === "string") {
            request.response = [new $bm(request.response)];
          }
        }
        acc[session.sessionId] = $PO(session);
        return acc;
      }, {});
      return sessions;
    } catch (err) {
      this.N("deserializeChats", `Malformed session data: ${err}. [${sessionData.substring(0, 20)}${sessionData.length > 20 ? "..." : ""}]`);
      return {};
    }
  }
  P() {
    const data = this.u.getObject(globalChatKey, 0, []);
    const workspaceUri = this.D.getWorkspace().folders[0]?.uri;
    if (!workspaceUri) {
      return;
    }
    const thisWorkspace = workspaceUri.toString();
    const currentTime = Date.now();
    const transferred = data.find((item) => URI.revive(item.toWorkspace).toString() === thisWorkspace && currentTime - item.timestampInMilliseconds < SESSION_TRANSFER_EXPIRATION_IN_MILLISECONDS);
    const filtered = data.filter((item) => URI.revive(item.toWorkspace).toString() !== thisWorkspace && currentTime - item.timestampInMilliseconds < SESSION_TRANSFER_EXPIRATION_IN_MILLISECONDS);
    this.u.store(
      globalChatKey,
      JSON.stringify(filtered),
      0,
      1
      /* StorageTarget.MACHINE */
    );
    return transferred;
  }
  /**
   * Returns an array of chat details for all persisted chat sessions that have at least one request.
   * The array is sorted by creation date in descending order.
   * Chat sessions that have already been loaded into the chat view are excluded from the result.
   * Imported chat sessions are also excluded from the result.
   */
  getHistory() {
    const persistedSessions = Object.values(this.g).filter((session) => session.requests.length > 0).filter((session) => !this.c.has(session.sessionId));
    const persistedSessionItems = persistedSessions.filter((session) => !session.isImported && session.initialLocation !== ChatAgentLocation.EditingSession).map((session) => {
      const title = session.customTitle ?? $SO.getDefaultTitle(session.requests);
      return {
        sessionId: session.sessionId,
        title,
        lastMessageDate: session.lastMessageDate,
        isActive: false
      };
    });
    const liveSessionItems = Array.from(this.c.values()).filter((session) => !session.isImported && session.initialLocation !== ChatAgentLocation.EditingSession).map((session) => {
      const title = session.title || localize(5104, null);
      return {
        sessionId: session.sessionId,
        title,
        lastMessageDate: session.lastMessageDate,
        isActive: true
      };
    });
    return [...liveSessionItems, ...persistedSessionItems];
  }
  removeHistoryEntry(sessionId) {
    if (this.g[sessionId]) {
      this.h.add(sessionId);
      delete this.g[sessionId];
      this.J();
    }
  }
  clearAllHistoryEntries() {
    Object.values(this.g).forEach((session) => this.h.add(session.sessionId));
    this.g = {};
    this.J();
  }
  startSession(location3, token) {
    this.M("startSession");
    return this.Q(void 0, location3, token);
  }
  Q(someSessionHistory, location3, token) {
    const model = this.z.createInstance($SO, someSessionHistory, location3);
    this.c.set(model.sessionId, model);
    this.R(model, token);
    return model;
  }
  async R(model, token) {
    try {
      this.M("initializeSession", `Initialize session ${model.sessionId}`);
      model.startInitialize();
      await this.y.whenInstalledExtensionsRegistered();
      const defaultAgentData = this.H.getContributedDefaultAgent(model.initialLocation) ?? this.H.getContributedDefaultAgent(ChatAgentLocation.Panel);
      if (!defaultAgentData) {
        throw new $ub("No default agent contributed");
      }
      await this.y.activateByEvent(`onChatParticipant:${defaultAgentData.id}`);
      const defaultAgent = this.H.getActivatedAgents().find((agent) => agent.id === defaultAgentData.id);
      if (!defaultAgent) {
        throw new $ub("No default agent registered");
      }
      const welcomeMessage = await defaultAgent.provideWelcomeMessage?.(token) ?? void 0;
      const sampleQuestions = await defaultAgent.provideSampleQuestions?.(model.initialLocation, token) ?? void 0;
      model.initialize(welcomeMessage, sampleQuestions);
    } catch (err) {
      this.M("startSession", `initializeSession failed: ${err}`);
      model.setInitializationError(err);
      this.c.deleteAndDispose(model.sessionId);
      this.n.fire({ sessionId: model.sessionId, reason: "initializationFailed" });
    }
  }
  getSession(sessionId) {
    return this.c.get(sessionId);
  }
  getOrRestoreSession(sessionId) {
    this.M("getOrRestoreSession", `sessionId: ${sessionId}`);
    const model = this.c.get(sessionId);
    if (model) {
      return model;
    }
    const sessionData = $cu(this.g[sessionId]);
    if (!sessionData) {
      return void 0;
    }
    if (sessionId === this.transferredSessionData?.sessionId) {
      this.j = void 0;
    }
    return this.Q(sessionData, sessionData.initialLocation ?? ChatAgentLocation.Panel, CancellationToken.None);
  }
  loadSessionFromContent(data) {
    return this.Q(data, data.initialLocation ?? ChatAgentLocation.Panel, CancellationToken.None);
  }
  async resendRequest(request, options3) {
    const model = this.c.get(request.session.sessionId);
    if (!model && model !== request.session) {
      throw new Error(`Unknown session: ${request.session.sessionId}`);
    }
    await model.waitForInitialization();
    const cts = this.f.get(request.session.sessionId);
    if (cts) {
      this.M("resendRequest", `Session ${request.session.sessionId} already has a pending request, cancelling...`);
      cts.cancel();
    }
    const location3 = options3?.location ?? model.initialLocation;
    const attempt = options3?.attempt ?? 0;
    const enableCommandDetection = !options3?.noCommandDetection;
    const defaultAgent = this.H.getDefaultAgent(location3);
    model.removeRequest(
      request.id,
      1
      /* ChatRequestRemovalReason.Resend */
    );
    const resendOptions = {
      ...options3,
      locationData: request.locationData,
      attachedContext: request.attachedContext,
      workingSet: request.workingSet
    };
    await this.W(model, model.sessionId, request.message, attempt, enableCommandDetection, defaultAgent, location3, resendOptions).responseCompletePromise;
  }
  async sendRequest(sessionId, request, options3) {
    this.M("sendRequest", `sessionId: ${sessionId}, message: ${request.substring(0, 20)}${request.length > 20 ? "[...]" : ""}}`);
    if (!request.trim() && !options3?.slashCommand && !options3?.agentId) {
      this.M("sendRequest", "Rejected empty message");
      return;
    }
    const model = this.c.get(sessionId);
    if (!model) {
      throw new Error(`Unknown session: ${sessionId}`);
    }
    await model.waitForInitialization();
    if (this.f.has(sessionId)) {
      this.M("sendRequest", `Session ${sessionId} already has a pending request`);
      return;
    }
    const location3 = options3?.location ?? model.initialLocation;
    const attempt = options3?.attempt ?? 0;
    const defaultAgent = this.H.getDefaultAgent(location3);
    const parsedRequest = this.S(sessionId, request, location3, options3);
    const agent = parsedRequest.parts.find((r2) => r2 instanceof $BO)?.agent ?? defaultAgent;
    const agentSlashCommandPart = parsedRequest.parts.find((r2) => r2 instanceof $CO);
    return {
      ...this.W(model, sessionId, parsedRequest, attempt, !options3?.noCommandDetection, defaultAgent, location3, options3),
      agent,
      slashCommand: agentSlashCommandPart?.command
    };
  }
  S(sessionId, request, location3, options3) {
    let parserContext = options3?.parserContext;
    if (options3?.agentId) {
      const agent = this.H.getAgent(options3.agentId);
      if (!agent) {
        throw new Error(`Unknown agent: ${options3.agentId}`);
      }
      parserContext = { selectedAgent: agent };
      const commandPart = options3.slashCommand ? ` ${$yO}${options3.slashCommand}` : "";
      request = `${$xO}${agent.name}${commandPart} ${request}`;
    }
    const parsedRequest = this.z.createInstance($nO).parseChatRequest(sessionId, request, location3, parserContext);
    return parsedRequest;
  }
  U(sessionId) {
    this.s.get(sessionId)?.cancel();
    const newTokenSource = new $ad();
    this.s.set(sessionId, newTokenSource);
    return newTokenSource.token;
  }
  W(model, sessionId, parsedRequest, attempt, enableCommandDetection, defaultAgent, location3, options3) {
    const followupsCancelToken = this.U(sessionId);
    let request;
    const agentPart = "kind" in parsedRequest ? void 0 : parsedRequest.parts.find((r2) => r2 instanceof $BO);
    const agentSlashCommandPart = "kind" in parsedRequest ? void 0 : parsedRequest.parts.find((r2) => r2 instanceof $CO);
    const commandPart = "kind" in parsedRequest ? void 0 : parsedRequest.parts.find((r2) => r2 instanceof $DO);
    const requests = [...model.getRequests()];
    let gotProgress = false;
    const requestType = commandPart ? "slashCommand" : "string";
    const responseCreated = new $gi();
    let responseCreatedComplete = false;
    function completeResponseCreated() {
      if (!responseCreatedComplete && request?.response) {
        responseCreated.complete(request.response);
        responseCreatedComplete = true;
      }
    }
    const source = new $ad();
    const token = source.token;
    const sendRequestInternal = async () => {
      const progressCallback = (progress) => {
        if (token.isCancellationRequested) {
          return;
        }
        gotProgress = true;
        if (progress.kind === "markdownContent") {
          this.M("sendRequest", `Provider returned progress for session ${model.sessionId}, ${progress.content.value.length} chars`);
        } else {
          this.M("sendRequest", `Provider returned progress: ${JSON.stringify(progress)}`);
        }
        model.acceptResponseProgress(request, progress);
        completeResponseCreated();
      };
      let detectedAgent;
      let detectedCommand;
      const stopWatch = new $te(false);
      const listener = token.onCancellationRequested(() => {
        this.M("sendRequest", `Request for session ${model.sessionId} was cancelled`);
        this.C.publicLog2("interactiveSessionProviderInvoked", {
          timeToFirstProgress: void 0,
          // Normally timings happen inside the EH around the actual provider. For cancellation we can measure how long the user waited before cancelling
          totalTime: stopWatch.elapsed(),
          result: "cancelled",
          requestType,
          agent: detectedAgent?.id ?? agentPart?.agent.id ?? "",
          agentExtensionId: detectedAgent?.extensionId.value ?? agentPart?.agent.extensionId.value ?? "",
          slashCommand: agentSlashCommandPart ? agentSlashCommandPart.command.name : commandPart?.slashCommand.command,
          chatSessionId: model.sessionId,
          location: location3,
          citations: request?.response?.codeCitations.length ?? 0,
          numCodeBlocks: getCodeBlocks(request.response?.response.toString() ?? "").length,
          isParticipantDetected: !!detectedAgent,
          enableCommandDetection,
          attachmentKinds: this.X(request.variableData)
        });
        model.cancelRequest(request);
      });
      try {
        let rawResult;
        let agentOrCommandFollowups = void 0;
        let chatTitlePromise;
        if (agentPart || defaultAgent && !commandPart) {
          const prepareChatAgentRequest = async (agent2, command5, enableCommandDetection2, chatRequest, isParticipantDetected) => {
            const initVariableData = { variables: [] };
            request = chatRequest ?? model.addRequest(parsedRequest, initVariableData, attempt, agent2, command5, options3?.confirmation, options3?.locationData, options3?.attachedContext, options3?.workingSet);
            let variableData;
            let message;
            if (chatRequest) {
              variableData = chatRequest.variableData;
              message = $uO(request.message).message;
            } else {
              variableData = await this.G.resolveVariables(parsedRequest, request.attachedContext, model, progressCallback, token);
              for (const variable of variableData.variables) {
                if (request.workingSet && variable.isFile && URI.isUri(variable.value)) {
                  request.workingSet.push(variable.value);
                }
              }
              model.updateRequest(request, variableData);
              const promptTextResult = $uO(request.message);
              variableData = $TO(variableData, promptTextResult.diff);
              message = promptTextResult.message;
            }
            return {
              sessionId,
              requestId: request.id,
              agentId: agent2.id,
              message,
              command: command5?.name,
              variables: variableData,
              enableCommandDetection: enableCommandDetection2,
              isParticipantDetected,
              attempt,
              location: location3,
              locationData: request.locationData,
              acceptedConfirmationData: options3?.acceptedConfirmationData,
              rejectedConfirmationData: options3?.rejectedConfirmationData,
              userSelectedModelId: options3?.userSelectedModelId
            };
          };
          if (this.I.getValue("chat.detectParticipant.enabled") !== false && this.H.hasChatParticipantDetectionProviders() && !agentPart && !commandPart && enableCommandDetection) {
            const defaultAgentHistory = this.Y(requests, model.sessionId, location3, defaultAgent.id);
            const chatAgentRequest = await prepareChatAgentRequest(defaultAgent, agentSlashCommandPart?.command, enableCommandDetection, void 0, false);
            const result = await this.H.detectAgentOrCommand(chatAgentRequest, defaultAgentHistory, { location: location3 }, token);
            if (result && this.H.getAgent(result.agent.id)?.locations?.includes(location3)) {
              request.response?.setAgent(result.agent, result.command);
              detectedAgent = result.agent;
              detectedCommand = result.command;
            }
          }
          const agent = detectedAgent ?? agentPart?.agent ?? defaultAgent;
          const command4 = detectedCommand ?? agentSlashCommandPart?.command;
          await this.y.activateByEvent(`onChatParticipant:${agent.id}`);
          const history = this.Y(requests, model.sessionId, location3, agent.id);
          const requestProps = await prepareChatAgentRequest(agent, command4, enableCommandDetection, request, !!detectedAgent);
          const pendingRequest = this.f.get(sessionId);
          if (pendingRequest && !pendingRequest.requestId) {
            pendingRequest.requestId = requestProps.requestId;
          }
          completeResponseCreated();
          const agentResult = await this.H.invokeAgent(agent.id, requestProps, progressCallback, history, token);
          rawResult = agentResult;
          agentOrCommandFollowups = this.H.getFollowups(agent.id, requestProps, agentResult, history, followupsCancelToken);
          chatTitlePromise = model.getRequests().length === 1 && !model.customTitle ? this.H.getChatTitle(defaultAgent.id, this.Y(model.getRequests(), model.sessionId, location3, agent.id), CancellationToken.None) : void 0;
        } else if (commandPart && this.F.hasCommand(commandPart.slashCommand.command)) {
          request = model.addRequest(parsedRequest, { variables: [] }, attempt);
          completeResponseCreated();
          const history = [];
          for (const request2 of model.getRequests()) {
            if (!request2.response) {
              continue;
            }
            history.push({ role: 1, content: [{ type: "text", value: request2.message.text }] });
            history.push({ role: 2, content: [{ type: "text", value: request2.response.response.toString() }] });
          }
          const message = parsedRequest.text;
          const commandResult = await this.F.executeCommand(commandPart.slashCommand.command, message.substring(commandPart.slashCommand.command.length + 1).trimStart(), new $VJ((p) => {
            progressCallback(p);
          }), history, location3, token);
          agentOrCommandFollowups = Promise.resolve(commandResult?.followUp);
          rawResult = {};
        } else {
          throw new Error(`Cannot handle request`);
        }
        if (token.isCancellationRequested) {
          return;
        } else {
          if (!rawResult) {
            this.M("sendRequest", `Provider returned no response for session ${model.sessionId}`);
            rawResult = { errorDetails: { message: localize(5105, null) } };
          }
          const result = rawResult.errorDetails?.responseIsFiltered ? "filtered" : rawResult.errorDetails && gotProgress ? "errorWithOutput" : rawResult.errorDetails ? "error" : "success";
          const commandForTelemetry = agentSlashCommandPart ? agentSlashCommandPart.command.name : commandPart?.slashCommand.command;
          this.C.publicLog2("interactiveSessionProviderInvoked", {
            timeToFirstProgress: rawResult.timings?.firstProgress,
            totalTime: rawResult.timings?.totalElapsed,
            result,
            requestType,
            agent: detectedAgent?.id ?? agentPart?.agent.id ?? "",
            agentExtensionId: detectedAgent?.extensionId.value ?? agentPart?.agent.extensionId.value ?? "",
            slashCommand: commandForTelemetry,
            chatSessionId: model.sessionId,
            enableCommandDetection,
            isParticipantDetected: !!detectedAgent,
            location: location3,
            citations: request.response?.codeCitations.length ?? 0,
            numCodeBlocks: getCodeBlocks(request.response?.response.toString() ?? "").length,
            attachmentKinds: this.X(request.variableData)
          });
          model.setResponse(request, rawResult);
          completeResponseCreated();
          this.M("sendRequest", `Provider returned response for session ${model.sessionId}`);
          model.completeResponse(request);
          if (agentOrCommandFollowups) {
            agentOrCommandFollowups.then((followups) => {
              model.setFollowups(request, followups);
              this.t.retrievedFollowups(agentPart?.agent.id ?? "", commandForTelemetry, followups?.length ?? 0);
            });
          }
          chatTitlePromise?.then((title) => {
            if (title) {
              model.setCustomTitle(title);
            }
          });
        }
      } catch (err) {
        const result = "error";
        this.C.publicLog2("interactiveSessionProviderInvoked", {
          timeToFirstProgress: void 0,
          totalTime: void 0,
          result,
          requestType,
          agent: detectedAgent?.id ?? agentPart?.agent.id ?? "",
          agentExtensionId: detectedAgent?.extensionId.value ?? agentPart?.agent.extensionId.value ?? "",
          slashCommand: agentSlashCommandPart ? agentSlashCommandPart.command.name : commandPart?.slashCommand.command,
          chatSessionId: model.sessionId,
          location: location3,
          citations: 0,
          numCodeBlocks: 0,
          enableCommandDetection,
          isParticipantDetected: !!detectedAgent,
          attachmentKinds: this.X(request.variableData)
        });
        this.w.error(`Error while handling chat request: ${$1m(err, true)}`);
        if (request) {
          const rawResult = { errorDetails: { message: err.message } };
          model.setResponse(request, rawResult);
          completeResponseCreated();
          model.completeResponse(request);
        }
      } finally {
        listener.dispose();
      }
    };
    const rawResponsePromise = sendRequestInternal();
    this.f.set(model.sessionId, new CancellableRequest(source));
    rawResponsePromise.finally(() => {
      this.f.deleteAndDispose(model.sessionId);
    });
    return {
      responseCreatedPromise: responseCreated.p,
      responseCompletePromise: rawResponsePromise
    };
  }
  X(variableData) {
    return variableData.variables.map((v) => {
      if (v.kind === "implicit") {
        return "implicit";
      } else if (v.range) {
        if (v.isTool) {
          return "toolInPrompt";
        } else if (v.isDynamic) {
          return "fileInPrompt";
        } else {
          return "variableInPrompt";
        }
      } else if (v.kind === "command") {
        return "command";
      } else if (v.kind === "symbol") {
        return "symbol";
      } else if (v.isImage) {
        return "image";
      } else if (v.isDirectory) {
        return "directory";
      } else if (v.isTool) {
        return "tool";
      } else if (v.isDynamic) {
        if (URI.isUri(v.value)) {
          return "file";
        } else if ($SE(v.value)) {
          return "location";
        } else {
          return "otherAttachment";
        }
      } else {
        return "variableAttachment";
      }
    });
  }
  Y(requests, sessionId, location3, forAgentId) {
    const history = [];
    for (const request of requests) {
      if (!request.response) {
        continue;
      }
      const defaultAgentId = this.H.getDefaultAgent(location3)?.id;
      if (forAgentId !== request.response.agent?.id && forAgentId !== defaultAgentId) {
        continue;
      }
      const promptTextResult = $uO(request.message);
      const historyRequest = {
        sessionId,
        requestId: request.id,
        agentId: request.response.agent?.id ?? "",
        message: promptTextResult.message,
        command: request.response.slashCommand?.name,
        variables: $TO(request.variableData, promptTextResult.diff),
        // TODO bit of a hack
        location: ChatAgentLocation.Panel
      };
      history.push({ request: historyRequest, response: $LO(request.response.response.value), result: request.response.result ?? {} });
    }
    return history;
  }
  async removeRequest(sessionId, requestId) {
    const model = this.c.get(sessionId);
    if (!model) {
      throw new Error(`Unknown session: ${sessionId}`);
    }
    await model.waitForInitialization();
    const pendingRequest = this.f.get(sessionId);
    if (pendingRequest?.requestId === requestId) {
      pendingRequest.cancel();
      this.f.deleteAndDispose(sessionId);
    }
    model.removeRequest(requestId);
  }
  async adoptRequest(sessionId, request) {
    if (!(request instanceof $MO)) {
      throw new TypeError("Can only adopt requests of type ChatRequestModel");
    }
    const target = this.c.get(sessionId);
    if (!target) {
      throw new Error(`Unknown session: ${sessionId}`);
    }
    await target.waitForInitialization();
    const oldOwner = request.session;
    target.adoptRequest(request);
    if (request.response && !request.response.isComplete) {
      const cts = this.f.deleteAndLeak(oldOwner.sessionId);
      if (cts) {
        cts.requestId = request.id;
        this.f.set(target.sessionId, cts);
      }
    }
  }
  async addCompleteRequest(sessionId, message, variableData, attempt, response) {
    this.M("addCompleteRequest", `message: ${message}`);
    const model = this.c.get(sessionId);
    if (!model) {
      throw new Error(`Unknown session: ${sessionId}`);
    }
    await model.waitForInitialization();
    const parsedRequest = typeof message === "string" ? this.z.createInstance($nO).parseChatRequest(sessionId, message) : message;
    const request = model.addRequest(parsedRequest, variableData || { variables: [] }, attempt ?? 0, void 0, void 0, void 0, void 0, void 0, void 0, true);
    if (typeof response.message === "string") {
      model.acceptResponseProgress(request, { content: new $bm(response.message), kind: "markdownContent" });
    } else {
      for (const part of response.message) {
        model.acceptResponseProgress(request, part, true);
      }
    }
    model.setResponse(request, response.result || {});
    if (response.followups !== void 0) {
      model.setFollowups(request, response.followups);
    }
    model.completeResponse(request);
  }
  cancelCurrentRequestForSession(sessionId) {
    this.M("cancelCurrentRequestForSession", `sessionId: ${sessionId}`);
    this.f.get(sessionId)?.cancel();
    this.f.deleteAndDispose(sessionId);
  }
  clearSession(sessionId) {
    this.M("clearSession", `sessionId: ${sessionId}`);
    const model = this.c.get(sessionId);
    if (!model) {
      throw new Error(`Unknown session: ${sessionId}`);
    }
    if (model.initialLocation === ChatAgentLocation.Panel) {
      const sessionData = JSON.parse(JSON.stringify(model));
      sessionData.isNew = true;
      this.g[sessionId] = sessionData;
    }
    this.c.deleteAndDispose(sessionId);
    this.f.get(sessionId)?.cancel();
    this.f.deleteAndDispose(sessionId);
    this.n.fire({ sessionId, reason: "cleared" });
  }
  hasSessions() {
    return Object.values(this.g).length > 0;
  }
  transferChatSession(transferredSessionData, toWorkspace) {
    const model = Iterable.find(this.c.values(), (model2) => model2.sessionId === transferredSessionData.sessionId);
    if (!model) {
      throw new Error(`Failed to transfer session. Unknown session ID: ${transferredSessionData.sessionId}`);
    }
    const existingRaw = this.u.getObject(globalChatKey, 0, []);
    existingRaw.push({
      chat: model.toJSON(),
      timestampInMilliseconds: Date.now(),
      toWorkspace,
      inputValue: transferredSessionData.inputValue
    });
    this.u.store(
      globalChatKey,
      JSON.stringify(existingRaw),
      0,
      1
      /* StorageTarget.MACHINE */
    );
    this.M("transferChatSession", `Transferred session ${model.sessionId} to workspace ${toWorkspace.toString()}`);
  }
};
$S5b = __decorate([
  __param(0, $jv),
  __param(1, $wn),
  __param(2, $wN),
  __param(3, $Pk),
  __param(4, $zv),
  __param(5, $Zk),
  __param(6, $sO),
  __param(7, $kO),
  __param(8, $ZO),
  __param(9, $kl)
], $S5b);
function getCodeBlocks(text2) {
  const lines = text2.split("\n");
  const codeBlockLanguages = [];
  let codeBlockState;
  for (let i2 = 0; i2 < lines.length; i2++) {
    const line = lines[i2];
    if (codeBlockState) {
      if (new RegExp(`^\\s*${codeBlockState.delimiter}\\s*$`).test(line)) {
        codeBlockLanguages.push(codeBlockState.languageId);
        codeBlockState = void 0;
      }
    } else {
      const match = line.match(/^(\s*)(`{3,}|~{3,})(\w*)/);
      if (match) {
        codeBlockState = { delimiter: match[2], languageId: match[3] };
      }
    }
  }
  return codeBlockLanguages;
}

// out-build/vs/workbench/contrib/chat/common/tools/languageModelToolsParametersSchema.js
var $T5b = "vscode://schemas/toolsParameters";
var toolsParametersSchemaSchema = {
  definitions: {
    schemaArray: {
      type: "array",
      minItems: 1,
      items: {
        $ref: "#"
      }
    },
    nonNegativeInteger: {
      type: "integer",
      minimum: 0
    },
    nonNegativeIntegerDefault0: {
      allOf: [
        {
          $ref: "#/definitions/nonNegativeInteger"
        },
        {
          default: 0
        }
      ]
    },
    simpleTypes: {
      enum: [
        "array",
        "boolean",
        "integer",
        "null",
        "number",
        "object",
        "string"
      ]
    },
    stringArray: {
      type: "array",
      items: {
        type: "string"
      },
      uniqueItems: true,
      default: []
    }
  },
  type: ["object"],
  properties: {
    $id: {
      type: "string",
      format: "uri-reference"
    },
    $schema: {
      type: "string",
      format: "uri"
    },
    $ref: {
      type: "string",
      format: "uri-reference"
    },
    $comment: {
      type: "string"
    },
    title: {
      type: "string"
    },
    description: {
      type: "string"
    },
    readOnly: {
      type: "boolean",
      default: false
    },
    writeOnly: {
      type: "boolean",
      default: false
    },
    multipleOf: {
      type: "number",
      exclusiveMinimum: 0
    },
    maximum: {
      type: "number"
    },
    exclusiveMaximum: {
      type: "number"
    },
    minimum: {
      type: "number"
    },
    exclusiveMinimum: {
      type: "number"
    },
    maxLength: {
      $ref: "#/definitions/nonNegativeInteger"
    },
    minLength: {
      $ref: "#/definitions/nonNegativeIntegerDefault0"
    },
    pattern: {
      type: "string",
      format: "regex"
    },
    additionalItems: {
      $ref: "#"
    },
    items: {
      anyOf: [
        {
          $ref: "#"
        },
        {
          $ref: "#/definitions/schemaArray"
        }
      ],
      default: true
    },
    maxItems: {
      $ref: "#/definitions/nonNegativeInteger"
    },
    minItems: {
      $ref: "#/definitions/nonNegativeIntegerDefault0"
    },
    uniqueItems: {
      type: "boolean",
      default: false
    },
    contains: {
      $ref: "#"
    },
    maxProperties: {
      $ref: "#/definitions/nonNegativeInteger"
    },
    minProperties: {
      $ref: "#/definitions/nonNegativeIntegerDefault0"
    },
    required: {
      $ref: "#/definitions/stringArray"
    },
    additionalProperties: {
      $ref: "#"
    },
    definitions: {
      type: "object",
      additionalProperties: {
        $ref: "#"
      },
      default: {}
    },
    properties: {
      type: "object",
      additionalProperties: {
        $ref: "#"
      },
      default: {}
    },
    patternProperties: {
      type: "object",
      additionalProperties: {
        $ref: "#"
      },
      propertyNames: {
        format: "regex"
      },
      default: {}
    },
    dependencies: {
      type: "object",
      additionalProperties: {
        anyOf: [
          {
            $ref: "#"
          },
          {
            $ref: "#/definitions/stringArray"
          }
        ]
      }
    },
    propertyNames: {
      $ref: "#"
    },
    enum: {
      type: "array",
      minItems: 1,
      uniqueItems: true
    },
    type: {
      anyOf: [
        {
          $ref: "#/definitions/simpleTypes"
        },
        {
          type: "array",
          items: {
            $ref: "#/definitions/simpleTypes"
          },
          minItems: 1,
          uniqueItems: true
        }
      ]
    },
    format: {
      type: "string"
    },
    contentMediaType: {
      type: "string"
    },
    contentEncoding: {
      type: "string"
    },
    if: {
      $ref: "#"
    },
    then: {
      $ref: "#"
    },
    else: {
      $ref: "#"
    },
    allOf: {
      $ref: "#/definitions/schemaArray"
    },
    anyOf: {
      $ref: "#/definitions/schemaArray"
    },
    oneOf: {
      $ref: "#/definitions/schemaArray"
    },
    not: {
      $ref: "#"
    }
  },
  defaultSnippets: [{
    body: {
      type: "object",
      properties: {
        "${1:paramName}": {
          type: "string",
          description: "${2:description}"
        }
      }
    }
  }]
};
var contributionRegistry2 = $Wn.as($Xn.JSONContribution);
contributionRegistry2.registerSchema($T5b, toolsParametersSchemaSchema);

// out-build/vs/workbench/contrib/chat/common/tools/languageModelToolsContribution.js
var languageModelToolsExtensionPoint = $tN.registerExtensionPoint({
  extensionPoint: "languageModelTools",
  activationEventsGenerator: (contributions, result) => {
    for (const contrib of contributions) {
      result.push(`onLanguageModelTool:${contrib.name}`);
    }
  },
  jsonSchema: {
    description: localize(5115, null),
    type: "array",
    items: {
      additionalProperties: false,
      type: "object",
      defaultSnippets: [{
        body: {
          name: "${1}",
          modelDescription: "${2}",
          inputSchema: {
            type: "object",
            properties: {
              "${3:name}": {
                type: "string",
                description: "${4:description}"
              }
            }
          }
        }
      }],
      required: ["name", "displayName", "modelDescription"],
      properties: {
        name: {
          description: localize(5116, null),
          type: "string",
          // Borrow OpenAI's requirement for tool names
          pattern: "^[\\w-]+$"
        },
        toolReferenceName: {
          markdownDescription: localize(5117, null, "`canBeReferencedInPrompt`"),
          type: "string",
          pattern: "^[\\w-]+$"
        },
        displayName: {
          description: localize(5118, null),
          type: "string"
        },
        userDescription: {
          description: localize(5119, null),
          type: "string"
        },
        modelDescription: {
          description: localize(5120, null),
          type: "string"
        },
        inputSchema: {
          description: localize(5121, null),
          $ref: $T5b
        },
        canBeReferencedInPrompt: {
          markdownDescription: localize(5122, null, "`ChatRequest#toolReferences`"),
          type: "boolean"
        },
        icon: {
          markdownDescription: localize(5123, null),
          anyOf: [
            {
              type: "string"
            },
            {
              type: "object",
              properties: {
                light: {
                  description: localize(5124, null),
                  type: "string"
                },
                dark: {
                  description: localize(5125, null),
                  type: "string"
                }
              }
            }
          ]
        },
        when: {
          markdownDescription: localize(5126, null),
          type: "string"
        },
        tags: {
          description: localize(5127, null),
          type: "array",
          items: {
            type: "string"
          }
        }
      }
    }
  }
});
function toToolKey(extensionIdentifier, toolName) {
  return `${extensionIdentifier.value}/${toolName}`;
}
var $U5b = class $U5b2 {
  static {
    this.ID = "workbench.contrib.toolsExtensionPointHandler";
  }
  constructor(languageModelToolsService, logService) {
    this.a = new $_c();
    languageModelToolsExtensionPoint.setHandler((extensions, delta) => {
      for (const extension of delta.added) {
        for (const rawTool of extension.value) {
          if (!rawTool.name || !rawTool.modelDescription || !rawTool.displayName) {
            logService.error(`Extension '${extension.description.identifier.value}' CANNOT register tool without name, modelDescription, and displayName: ${JSON.stringify(rawTool)}`);
            continue;
          }
          if (!rawTool.name.match(/^[\w-]+$/)) {
            logService.error(`Extension '${extension.description.identifier.value}' CANNOT register tool with invalid id: ${rawTool.name}. The id must match /^[\\w-]+$/.`);
            continue;
          }
          if (rawTool.canBeReferencedInPrompt && !rawTool.toolReferenceName) {
            logService.error(`Extension '${extension.description.identifier.value}' CANNOT register tool with 'canBeReferencedInPrompt' set without a 'toolReferenceName': ${JSON.stringify(rawTool)}`);
            continue;
          }
          const rawIcon = rawTool.icon;
          let icon2;
          if (typeof rawIcon === "string") {
            icon2 = ThemeIcon.fromString(rawIcon) ?? {
              dark: $vh(extension.description.extensionLocation, rawIcon),
              light: $vh(extension.description.extensionLocation, rawIcon)
            };
          } else if (rawIcon) {
            icon2 = {
              dark: $vh(extension.description.extensionLocation, rawIcon.dark),
              light: $vh(extension.description.extensionLocation, rawIcon.light)
            };
          }
          const tool = {
            ...rawTool,
            extensionId: extension.description.identifier,
            inputSchema: rawTool.inputSchema,
            id: rawTool.name,
            icon: icon2,
            when: rawTool.when ? $7m.deserialize(rawTool.when) : void 0
          };
          const disposable = languageModelToolsService.registerToolData(tool);
          this.a.set(toToolKey(extension.description.identifier, rawTool.name), disposable);
        }
      }
      for (const extension of delta.removed) {
        for (const tool of extension.value) {
          this.a.deleteAndDispose(toToolKey(extension.description.identifier, tool.name));
        }
      }
    });
  }
};
$U5b = __decorate([
  __param(0, $mO),
  __param(1, $wn)
], $U5b);

// out-build/vs/workbench/contrib/chat/common/voiceChatService.js
var $X5b_1;
var $V5b = $Qk("voiceChatService");
var PhraseTextType;
(function(PhraseTextType2) {
  PhraseTextType2[PhraseTextType2["AGENT"] = 1] = "AGENT";
  PhraseTextType2[PhraseTextType2["COMMAND"] = 2] = "COMMAND";
  PhraseTextType2[PhraseTextType2["AGENT_AND_COMMAND"] = 3] = "AGENT_AND_COMMAND";
})(PhraseTextType || (PhraseTextType = {}));
var $W5b = new $nn("voiceChatInProgress", false, { type: "boolean", description: localize(5128, null) });
var $X5b = class $X5b2 extends $3c {
  static {
    $X5b_1 = this;
  }
  static {
    this.a = $xO;
  }
  static {
    this.b = $yO;
  }
  static {
    this.c = {
      [this.a]: "at",
      [this.b]: "slash"
    };
  }
  static {
    this.f = {
      [this.a]: "At",
      [this.b]: "Slash"
    };
  }
  static {
    this.g = /* @__PURE__ */ new Map([["vscode", "code"]]);
  }
  constructor(m, n, r2) {
    super();
    this.m = m;
    this.n = n;
    this.r = r2;
    this.h = $W5b.bindTo(this.r);
    this.j = 0;
  }
  s(model) {
    const phrases = /* @__PURE__ */ new Map();
    for (const agent of this.n.getActivatedAgents()) {
      const agentPhrase = `${$X5b_1.c[$X5b_1.a]} ${$X5b_1.g.get(agent.name) ?? agent.name}`.toLowerCase();
      phrases.set(agentPhrase, { agent: agent.name });
      for (const slashCommand of agent.slashCommands) {
        const slashCommandPhrase = `${$X5b_1.c[$X5b_1.b]} ${slashCommand.name}`.toLowerCase();
        phrases.set(slashCommandPhrase, { agent: agent.name, command: slashCommand.name });
        const agentSlashCommandPhrase = `${agentPhrase} ${slashCommandPhrase}`.toLowerCase();
        phrases.set(agentSlashCommandPhrase, { agent: agent.name, command: slashCommand.name });
      }
    }
    return phrases;
  }
  t(value, type) {
    switch (type) {
      case PhraseTextType.AGENT:
        return `${$X5b_1.a}${value.agent}`;
      case PhraseTextType.COMMAND:
        return `${$X5b_1.b}${value.command}`;
      case PhraseTextType.AGENT_AND_COMMAND:
        return `${$X5b_1.a}${value.agent} ${$X5b_1.b}${value.command}`;
    }
  }
  async createVoiceChatSession(token, options3) {
    const disposables = new $2c();
    const onSessionStoppedOrCanceled = (dispose) => {
      this.j = Math.max(0, this.j - 1);
      if (this.j === 0) {
        this.h.reset();
      }
      if (dispose) {
        disposables.dispose();
      }
    };
    disposables.add(token.onCancellationRequested(() => onSessionStoppedOrCanceled(true)));
    let detectedAgent = false;
    let detectedSlashCommand = false;
    const emitter = disposables.add(new $ze());
    const session = await this.m.createSpeechToTextSession(token, "chat");
    if (token.isCancellationRequested) {
      onSessionStoppedOrCanceled(true);
    }
    const phrases = this.s(options3.model);
    disposables.add(session.onDidChange((e) => {
      switch (e.status) {
        case SpeechToTextStatus2.Recognizing:
        case SpeechToTextStatus2.Recognized: {
          let massagedEvent = e;
          if (e.text) {
            const startsWithAgent = e.text.startsWith($X5b_1.f[$X5b_1.a]) || e.text.startsWith($X5b_1.c[$X5b_1.a]);
            const startsWithSlashCommand = e.text.startsWith($X5b_1.f[$X5b_1.b]) || e.text.startsWith($X5b_1.c[$X5b_1.b]);
            if (startsWithAgent || startsWithSlashCommand) {
              const originalWords = e.text.split(" ");
              let transformedWords;
              let waitingForInput = false;
              if (options3.usesAgents && startsWithAgent && !detectedAgent && !detectedSlashCommand && originalWords.length >= 4) {
                const phrase = phrases.get(originalWords.slice(0, 4).map((word) => this.u(word)).join(" "));
                if (phrase) {
                  transformedWords = [this.t(phrase, PhraseTextType.AGENT_AND_COMMAND), ...originalWords.slice(4)];
                  waitingForInput = originalWords.length === 4;
                  if (e.status === SpeechToTextStatus2.Recognized) {
                    detectedAgent = true;
                    detectedSlashCommand = true;
                  }
                }
              }
              if (options3.usesAgents && startsWithAgent && !detectedAgent && !transformedWords && originalWords.length >= 2) {
                const phrase = phrases.get(originalWords.slice(0, 2).map((word) => this.u(word)).join(" "));
                if (phrase) {
                  transformedWords = [this.t(phrase, PhraseTextType.AGENT), ...originalWords.slice(2)];
                  waitingForInput = originalWords.length === 2;
                  if (e.status === SpeechToTextStatus2.Recognized) {
                    detectedAgent = true;
                  }
                }
              }
              if (startsWithSlashCommand && !detectedSlashCommand && !transformedWords && originalWords.length >= 2) {
                const phrase = phrases.get(originalWords.slice(0, 2).map((word) => this.u(word)).join(" "));
                if (phrase) {
                  transformedWords = [this.t(
                    phrase,
                    options3.usesAgents && !detectedAgent ? PhraseTextType.AGENT_AND_COMMAND : (
                      // rewrite `/fix` to `@workspace /foo` in this case
                      PhraseTextType.COMMAND
                    )
                    // when we have not yet detected an agent before
                  ), ...originalWords.slice(2)];
                  waitingForInput = originalWords.length === 2;
                  if (e.status === SpeechToTextStatus2.Recognized) {
                    detectedSlashCommand = true;
                  }
                }
              }
              massagedEvent = {
                status: e.status,
                text: (transformedWords ?? originalWords).join(" "),
                waitingForInput
              };
            }
          }
          emitter.fire(massagedEvent);
          break;
        }
        case SpeechToTextStatus2.Started:
          this.j++;
          this.h.set(true);
          emitter.fire(e);
          break;
        case SpeechToTextStatus2.Stopped:
          onSessionStoppedOrCanceled(false);
          emitter.fire(e);
          break;
        case SpeechToTextStatus2.Error:
          emitter.fire(e);
          break;
      }
    }));
    return {
      onDidChange: emitter.event
    };
  }
  u(word) {
    word = $Gf(word, ".");
    word = $Gf(word, ",");
    word = $Gf(word, "?");
    return word.toLowerCase();
  }
};
$X5b = $X5b_1 = __decorate([
  __param(0, $jS),
  __param(1, $ZO),
  __param(2, $on)
], $X5b);

// out-build/vs/workbench/contrib/chat/browser/actions/chatAccessibilityHelp.js
var $Y5b = class {
  constructor() {
    this.priority = 107;
    this.name = "panelChat";
    this.type = "help";
    this.when = $7m.and(ChatContextKeys.location.isEqualTo(ChatAgentLocation.Panel), ChatContextKeys.inQuickChat.negate(), $7m.or(ChatContextKeys.inChatSession, ChatContextKeys.isResponse, ChatContextKeys.isRequest));
  }
  getProvider(accessor) {
    const codeEditor = accessor.get($U5).getActiveCodeEditor() || accessor.get($U5).getFocusedCodeEditor();
    return $25b(accessor, codeEditor ?? void 0, "panelChat");
  }
};
var $Z5b = class {
  constructor() {
    this.priority = 107;
    this.name = "quickChat";
    this.type = "help";
    this.when = $7m.and(ChatContextKeys.inQuickChat, $7m.or(ChatContextKeys.inChatSession, ChatContextKeys.isResponse, ChatContextKeys.isRequest));
  }
  getProvider(accessor) {
    const codeEditor = accessor.get($U5).getActiveCodeEditor() || accessor.get($U5).getFocusedCodeEditor();
    return $25b(accessor, codeEditor ?? void 0, "quickChat");
  }
};
function $15b(type, keybindingService) {
  const content = [];
  if (type === "panelChat" || type === "quickChat") {
    if (type === "quickChat") {
      content.push(localize(4604, null));
      content.push(localize(4605, null));
    }
    if (type === "panelChat") {
      content.push(localize(4606, null));
      content.push(localize(4607, null));
    }
    content.push(localize(4608, null));
    content.push(localize(4609, null, "<keybinding:editor.action.accessibleView>"));
    content.push(localize(4610, null));
    content.push(localize(4611, null, getChatFocusKeybindingLabel(keybindingService, type, false)));
    content.push(localize(4612, null, getChatFocusKeybindingLabel(keybindingService, type, true)));
    content.push(localize(4613, null, "<keybinding:workbench.action.chat.nextCodeBlock>"));
    if (type === "panelChat") {
      content.push(localize(4614, null, "<keybinding:workbench.action.chat.new>"));
    }
  } else {
    content.push(localize(4615, null));
    content.push(localize(4616, null, "<keybinding:inlineChat.start>"));
    content.push(localize(4617, null, "<keybinding:history.showPrevious>", "<keybinding:history.showNext>"));
    content.push(localize(4618, null, "<keybinding:editor.action.accessibleView>"));
    content.push(localize(4619, null));
    content.push(localize(4620, null));
    content.push(localize(4621, null, $m_.id));
    content.push(localize(4622, null));
  }
  content.push(localize(4623, null));
  return content.join("\n");
}
function $25b(accessor, editor, type) {
  const widgetService = accessor.get($2Nb);
  const keybindingService = accessor.get($Ty);
  const inputEditor = type === "panelChat" || type === "quickChat" ? widgetService.lastFocusedWidget?.inputEditor : editor;
  if (!inputEditor) {
    return;
  }
  const domNode = inputEditor.getDomNode() ?? void 0;
  if (!domNode) {
    return;
  }
  const cachedPosition = inputEditor.getPosition();
  inputEditor.getSupportedActions();
  const helpText = $15b(type, keybindingService);
  return new $thb(
    type === "panelChat" ? "panelChat" : type === "inlineChat" ? "inlineChat" : "quickChat",
    {
      type: "help"
      /* AccessibleViewType.Help */
    },
    () => helpText,
    () => {
      if (type === "panelChat" && cachedPosition) {
        inputEditor.setPosition(cachedPosition);
        inputEditor.focus();
      } else if (type === "inlineChat") {
        const ctrl = editor?.getContribution($8zb);
        ctrl?.focus();
      }
    },
    type === "panelChat" ? "accessibility.verbosity.panelChat" : "accessibility.verbosity.inlineChat"
    /* AccessibilityVerbositySettingId.InlineChat */
  );
}
function getChatFocusKeybindingLabel(keybindingService, type, focusInput) {
  let kbs;
  const fallback2 = " (unassigned keybinding)";
  if (focusInput) {
    kbs = keybindingService.lookupKeybindings("workbench.action.chat.focusInput");
  } else {
    kbs = keybindingService.lookupKeybindings("chat.action.focus");
  }
  if (!kbs?.length) {
    return fallback2;
  }
  let kb;
  if (type === "panelChat") {
    if (focusInput) {
      kb = kbs.find((kb2) => kb2.getAriaLabel()?.includes("DownArrow"))?.getAriaLabel();
    } else {
      kb = kbs.find((kb2) => kb2.getAriaLabel()?.includes("UpArrow"))?.getAriaLabel();
    }
  } else {
    if (focusInput) {
      kb = kbs.find((kb2) => kb2.getAriaLabel()?.includes("UpArrow"))?.getAriaLabel();
    } else {
      kb = kbs.find((kb2) => kb2.getAriaLabel()?.includes("DownArrow"))?.getAriaLabel();
    }
  }
  return !!kb ? ` (${kb})` : fallback2;
}

// out-build/vs/workbench/contrib/chat/common/chatActions.js
function $lzb(obj) {
  return !!obj && typeof obj.sessionId === "string" && obj.$mid === 19;
}

// out-build/vs/workbench/contrib/chat/browser/actions/chatClearActions.js
var $35b = `workbench.action.chat.newChat`;
var $45b = `workbench.action.chat.newEditSession`;
function $55b() {
  $hJ(class NewChatEditorAction extends $gJ {
    constructor() {
      super({
        id: "workbench.action.chatEditor.newChat",
        title: localize2(4654, "New Chat"),
        icon: $6l.plus,
        f1: false,
        precondition: ChatContextKeys.enabled,
        menu: [{
          id: $bJ.EditorTitle,
          group: "navigation",
          order: 0,
          when: $Dpb.isEqualTo($Zzb.EditorID)
        }]
      });
    }
    async run(accessor, ...args2) {
      announceChatCleared(accessor.get($I9));
      await $3zb(accessor);
    }
  });
  $hJ(class GlobalClearChatAction extends $gJ {
    constructor() {
      super({
        id: $35b,
        title: localize2(4655, "New Chat"),
        category: $vNb,
        icon: $6l.plus,
        precondition: $7m.and(ChatContextKeys.enabled, ChatContextKeys.location.notEqualsTo(ChatAgentLocation.EditingSession)),
        f1: true,
        keybinding: {
          weight: 200,
          primary: 2048 | 42,
          mac: {
            primary: 256 | 42
            /* KeyCode.KeyL */
          },
          when: ChatContextKeys.inChatSession
        },
        menu: [
          {
            id: $bJ.ChatContext,
            group: "z_clear"
          },
          {
            id: $bJ.ViewTitle,
            when: $7m.equals("view", $9Nb),
            group: "navigation",
            order: -1
          }
        ]
      });
    }
    async run(accessor, ...args2) {
      const context = args2[0];
      const accessibilitySignalService = accessor.get($I9);
      const widgetService = accessor.get($2Nb);
      let widget = widgetService.lastFocusedWidget;
      if ($lzb(context)) {
        widget = widgetService.getWidgetBySessionId(context.sessionId);
      }
      if (widget) {
        announceChatCleared(accessibilitySignalService);
        widget.clear();
        widget.focusInput();
      }
    }
  });
  $hJ(class NewEditSessionAction extends $gJ {
    constructor() {
      super({
        id: $45b,
        title: localize2(4656, "New Edit Session"),
        category: $vNb,
        icon: $6l.plus,
        precondition: $7m.and(ChatContextKeys.enabled, ChatContextKeys.editingParticipantRegistered),
        f1: true,
        menu: [
          {
            id: $bJ.ChatContext,
            group: "z_clear"
          },
          {
            id: $bJ.ViewTitle,
            when: $7m.equals("view", $0Nb),
            group: "navigation",
            order: -1
          }
        ],
        keybinding: {
          weight: 200,
          primary: 2048 | 42,
          mac: {
            primary: 256 | 42
            /* KeyCode.KeyL */
          },
          when: $7m.and(ChatContextKeys.inChatSession, ChatContextKeys.location.isEqualTo(ChatAgentLocation.EditingSession))
        }
      });
    }
    /**
     *
     * @returns false if the user had edits and did not action the dialog to take action on them, true otherwise
     */
    async a(chatEditingService, dialogService) {
      const currentEditingSession = chatEditingService.currentEditingSessionObs.get();
      const currentEdits = currentEditingSession?.entries.get();
      const currentEditCount = currentEdits?.length;
      if (currentEditingSession && currentEditCount) {
        const undecidedEdits = currentEdits.filter(
          (edit3) => edit3.state.get() === 0
          /* WorkingSetEntryState.Modified */
        );
        if (undecidedEdits.length) {
          const { result } = await dialogService.prompt({
            title: localize(4650, null),
            message: localize(4651, null, undecidedEdits.length),
            type: "info",
            cancelButton: true,
            buttons: [
              {
                label: localize(4652, null),
                run: async () => {
                  await currentEditingSession.accept();
                  return true;
                }
              },
              {
                label: localize(4653, null),
                run: async () => {
                  await currentEditingSession.reject();
                  return true;
                }
              }
            ]
          });
          return Boolean(result);
        }
      }
      return true;
    }
    async run(accessor, ...args2) {
      const context = args2[0];
      const accessibilitySignalService = accessor.get($I9);
      const widgetService = accessor.get($2Nb);
      const chatEditingService = accessor.get($$O);
      const dialogService = accessor.get($Yv);
      const viewsService = accessor.get($uob);
      if (!await this.a(chatEditingService, dialogService)) {
        return;
      }
      if ($lzb(context)) {
        announceChatCleared(accessibilitySignalService);
        const widget = widgetService.getWidgetBySessionId(context.sessionId);
        if (widget) {
          chatEditingService.currentEditingSessionObs.get()?.stop(true);
          widget.clear();
          widget.attachmentModel.clear();
          widget.focusInput();
        }
      } else {
        const chatView = await viewsService.openView($0Nb);
        const widget = chatView.widget;
        announceChatCleared(accessibilitySignalService);
        chatEditingService.currentEditingSessionObs.get()?.stop(true);
        widget.clear();
        widget.attachmentModel.clear();
        widget.focusInput();
      }
    }
  });
  $hJ(class GlobalEditsDoneAction extends $gJ {
    constructor() {
      super({
        id: "workbench.action.chat.done",
        title: localize2(4657, "Done"),
        category: $vNb,
        precondition: $7m.and(ChatContextKeys.enabled, ChatContextKeys.editingParticipantRegistered),
        f1: false,
        menu: [{
          id: $bJ.ChatEditingWidgetToolbar,
          when: $7m.and($fP.negate(), $gP, ChatContextKeys.editingParticipantRegistered, ChatContextKeys.location.isEqualTo(ChatAgentLocation.EditingSession)),
          group: "navigation",
          order: 0
        }]
      });
    }
    async run(accessor, ...args2) {
      const context = args2[0];
      const accessibilitySignalService = accessor.get($I9);
      const widgetService = accessor.get($2Nb);
      if ($lzb(context)) {
        announceChatCleared(accessibilitySignalService);
        const widget = widgetService.getWidgetBySessionId(context.sessionId);
        if (widget) {
          widget.clear();
          widget.attachmentModel.clear();
          widget.focusInput();
        }
      } else {
        const viewsService = accessor.get($uob);
        const chatView = await viewsService.openView($0Nb);
        const widget = chatView.widget;
        announceChatCleared(accessibilitySignalService);
        widget.clear();
        widget.attachmentModel.clear();
        widget.focusInput();
      }
    }
  });
  $hJ(class UndoChatEditInteractionAction extends $gJ {
    constructor() {
      super({
        id: "workbench.action.chat.undoEdit",
        title: localize2(4658, "Undo Last Edit"),
        category: $vNb,
        icon: $6l.discard,
        precondition: $7m.and(ChatContextKeys.chatEditingCanUndo, ChatContextKeys.enabled, ChatContextKeys.editingParticipantRegistered),
        f1: true,
        menu: [{
          id: $bJ.ViewTitle,
          when: $7m.equals("view", $0Nb),
          group: "navigation",
          order: -3
        }]
      });
    }
    async run(accessor, ...args2) {
      const chatEditingService = accessor.get($$O);
      const currentEditingSession = chatEditingService.currentEditingSession;
      if (!currentEditingSession) {
        return;
      }
      await currentEditingSession.undoInteraction();
    }
  });
  $hJ(class RedoChatEditInteractionAction extends $gJ {
    constructor() {
      super({
        id: "workbench.action.chat.redoEdit",
        title: localize2(4659, "Redo Last Edit"),
        category: $vNb,
        icon: $6l.redo,
        precondition: $7m.and(ChatContextKeys.chatEditingCanRedo, ChatContextKeys.enabled, ChatContextKeys.editingParticipantRegistered),
        f1: true,
        menu: [{
          id: $bJ.ViewTitle,
          when: $7m.equals("view", $0Nb),
          group: "navigation",
          order: -2
        }]
      });
    }
    async run(accessor, ...args2) {
      const chatEditingService = accessor.get($$O);
      const currentEditingSession = chatEditingService.currentEditingSession;
      if (!currentEditingSession) {
        return;
      }
      await chatEditingService.currentEditingSession?.redoInteraction();
    }
  });
  $hJ(class GlobalOpenEditsAction extends $gJ {
    constructor() {
      super({
        id: "workbench.action.chat.openEditSession",
        title: localize2(4660, "Open {0}", "Copilot Edits"),
        category: $vNb,
        icon: $6l.goToEditingSession,
        precondition: $7m.and(ChatContextKeys.enabled, ChatContextKeys.editingParticipantRegistered),
        f1: true,
        menu: [{
          id: $bJ.ViewTitle,
          when: $7m.and($7m.equals("view", $9Nb), ChatContextKeys.editingParticipantRegistered, $7m.equals(`view.${$0Nb}.visible`, false), $7m.or($7m.and($7m.equals(`workbench.panel.chat.defaultViewContainerLocation`, true), $7m.equals(`workbench.panel.chatEditing.defaultViewContainerLocation`, false)), $7m.and($7m.equals(`workbench.panel.chat.defaultViewContainerLocation`, false), $7m.equals(`workbench.panel.chatEditing.defaultViewContainerLocation`, true)))),
          group: "navigation",
          order: 1
        }, {
          id: $bJ.ChatCommandCenter,
          group: "a_open",
          order: 2
        }, {
          id: $bJ.ChatEditingEditorContent,
          group: "navigate",
          order: 4
        }],
        keybinding: {
          weight: 200,
          primary: 2048 | 1024 | 39,
          linux: {
            primary: 2048 | 512 | 1024 | 39
            /* KeyCode.KeyI */
          },
          when: $7m.and($7m.notEquals("view", $0Nb), ChatContextKeys.editingParticipantRegistered)
        }
      });
    }
    async run(accessor, ...args2) {
      const viewsService = accessor.get($uob);
      const chatView = await viewsService.openView($0Nb);
      chatView.widget.focusInput();
    }
  });
}
function announceChatCleared(accessibilitySignalService) {
  accessibilitySignalService.playSignal($N9.clear);
}

// out-build/vs/workbench/contrib/chat/browser/actions/codeBlockOperations.js
var $65b = class $65b2 {
  constructor(a, b, c, d, f, g, h3) {
    this.a = a;
    this.b = b;
    this.c = c;
    this.d = d;
    this.f = f;
    this.g = g;
    this.h = h3;
  }
  async run(context) {
    const activeEditorControl = getEditableActiveCodeEditor(this.a);
    if (activeEditorControl) {
      await this.k(activeEditorControl, context);
    } else {
      const activeNotebookEditor = getActiveNotebookEditor(this.a);
      if (activeNotebookEditor) {
        await this.j(activeNotebookEditor, context);
      } else {
        this.l(localize(4739, null));
      }
    }
    notifyUserAction(this.f, context, {
      kind: "insert",
      codeBlockIndex: context.codeBlockIndex,
      totalCharacters: context.code.length
    });
  }
  async j(notebookEditor, codeBlockContext) {
    if (notebookEditor.isReadOnly) {
      this.l(localize(4740, null));
      return false;
    }
    const focusRange = notebookEditor.getFocus();
    const next = Math.max(focusRange.end - 1, 0);
    $0Ib(this.g, notebookEditor, next, CellKind.Code, "below", codeBlockContext.code, true);
    return true;
  }
  async k(codeEditor, codeBlockContext) {
    const activeModel = codeEditor.getModel();
    if (isReadOnly(activeModel, this.b)) {
      this.l(localize(4741, null));
      return false;
    }
    const range = codeEditor.getSelection() ?? new $9C(activeModel.getLineCount(), 1, activeModel.getLineCount(), 1);
    const text2 = reindent(codeBlockContext.code, activeModel, range.startLineNumber);
    const edits = [new $J_(activeModel.uri, { range, text: text2 })];
    await this.c.apply(edits);
    this.d.listCodeEditors().find((editor) => editor.getModel()?.uri.toString() === activeModel.uri.toString())?.focus();
    return true;
  }
  l(message) {
    this.h.info(message);
  }
};
$65b = __decorate([
  __param(0, $mJ),
  __param(1, $cK),
  __param(2, $H_),
  __param(3, $U5),
  __param(4, $qO),
  __param(5, $1E),
  __param(6, $Yv)
], $65b);
var $75b = class $75b2 {
  constructor(b, c, d, f, g, h3, j, k, l, m, n) {
    this.b = b;
    this.c = c;
    this.d = d;
    this.f = f;
    this.g = g;
    this.h = h3;
    this.j = j;
    this.k = k;
    this.l = l;
    this.m = m;
    this.n = n;
  }
  async run(context) {
    if (this.a && this.a.isOpen()) {
      await this.m.info(localize(4742, null));
      return;
    }
    let activeEditorControl = getEditableActiveCodeEditor(this.b);
    if (context.codemapperUri && !$oh(activeEditorControl?.getModel().uri, context.codemapperUri)) {
      try {
        if (!await this.l.exists(context.codemapperUri)) {
          await this.l.writeFile(context.codemapperUri, $Ci.fromString(""));
        }
        await this.b.openEditor({ resource: context.codemapperUri });
        activeEditorControl = getEditableActiveCodeEditor(this.b);
        if (activeEditorControl) {
          this.s(activeEditorControl, context.code);
        }
      } catch (e) {
        this.n.info("[ApplyCodeBlockOperation] error opening code mapper file", context.codemapperUri, e);
      }
    }
    let result = void 0;
    if (activeEditorControl) {
      await this.p(activeEditorControl, context);
    } else {
      const activeNotebookEditor = getActiveNotebookEditor(this.b);
      if (activeNotebookEditor) {
        result = await this.o(activeNotebookEditor, context);
      } else {
        this.t(localize(4743, null));
      }
    }
    notifyUserAction(this.g, context, {
      kind: "apply",
      codeBlockIndex: context.codeBlockIndex,
      totalCharacters: context.code.length,
      codeMapper: result?.codeMapper,
      editsProposed: !!result?.edits
    });
  }
  async o(notebookEditor, codeBlockContext) {
    if (notebookEditor.isReadOnly) {
      this.t(localize(4744, null));
      return void 0;
    }
    const focusRange = notebookEditor.getFocus();
    const next = Math.max(focusRange.end - 1, 0);
    $0Ib(this.k, notebookEditor, next, CellKind.Code, "below", codeBlockContext.code, true);
    return void 0;
  }
  async p(codeEditor, codeBlockContext) {
    if (isReadOnly(codeEditor.getModel(), this.c)) {
      this.t(localize(4745, null));
      return void 0;
    }
    const result = await this.q(codeEditor, codeBlockContext);
    if (result.edits) {
      const showWithPreview = await this.r(result.edits, codeEditor);
      if (!showWithPreview) {
        await this.d.apply(result.edits, { showPreview: true });
        const activeModel = codeEditor.getModel();
        this.f.listCodeEditors().find((editor) => editor.getModel()?.uri.toString() === activeModel.uri.toString())?.focus();
      }
    }
    return result;
  }
  async q(codeEditor, codeBlockActionContext) {
    const activeModel = codeEditor.getModel();
    const mappedEditsProviders = this.h.mappedEditsProvider.ordered(activeModel);
    if (mappedEditsProviders.length > 0) {
      const docRefs = [];
      collectDocumentContextFromSelections(codeEditor, docRefs);
      collectDocumentContextFromContext(codeBlockActionContext, docRefs);
      const cancellationTokenSource = new $ad();
      let codeMapper;
      try {
        const result = await this.j.withProgress({ location: 15, delay: 500, sticky: true, cancellable: true }, async (progress) => {
          for (const provider of mappedEditsProviders) {
            codeMapper = provider.displayName;
            progress.report({ message: localize(4746, null, codeMapper) });
            const mappedEdits = await provider.provideMappedEdits(activeModel, [codeBlockActionContext.code], {
              documents: docRefs,
              conversation: getChatConversation(codeBlockActionContext)
            }, cancellationTokenSource.token);
            if (mappedEdits) {
              return { edits: mappedEdits.edits, codeMapper };
            }
          }
          return void 0;
        }, () => cancellationTokenSource.cancel());
        if (result) {
          return result;
        }
      } catch (e) {
        if (!$kb(e)) {
          this.t(localize(4747, null, e.message));
        }
      } finally {
        cancellationTokenSource.dispose();
      }
      return { edits: [], codeMapper };
    }
    return { edits: [], codeMapper: void 0 };
  }
  async r(edits, codeEditor) {
    const firstEdit = edits[0];
    if (!$J_.is(firstEdit)) {
      return false;
    }
    const resource = firstEdit.resource;
    const textEdits = $Mb(edits.map((edit3) => $J_.is(edit3) && $oh(resource, edit3.resource) ? edit3.textEdit : void 0));
    if (textEdits.length !== edits.length) {
      return false;
    }
    const editorToApply = await this.f.openCodeEditor({ resource }, codeEditor);
    if (editorToApply) {
      const inlineChatController = $cHb.get(editorToApply);
      if (inlineChatController) {
        const tokenSource = new $ad();
        let isOpen = true;
        const firstEdit2 = textEdits[0];
        editorToApply.revealLineInCenterIfOutsideViewport(firstEdit2.range.startLineNumber);
        const promise = inlineChatController.reviewEdits(textEdits[0].range, $ji.fromArray([textEdits]), tokenSource.token);
        promise.finally(() => {
          isOpen = false;
          tokenSource.dispose();
        });
        this.a = {
          promise,
          isOpen: () => isOpen,
          cancel: () => tokenSource.cancel()
        };
        return true;
      }
    }
    return false;
  }
  s(codeEditor, codeBlock) {
    const match = codeBlock.match(/(\S[^\n]*)\n/);
    if (match && match[1].length > 10) {
      const findMatch = codeEditor.getModel().findNextMatch(match[1], { lineNumber: 1, column: 1 }, false, false, null, false);
      if (findMatch) {
        codeEditor.revealRangeInCenter(findMatch.range);
      }
    }
  }
  t(message) {
    this.m.info(message);
  }
};
$75b = __decorate([
  __param(0, $mJ),
  __param(1, $cK),
  __param(2, $H_),
  __param(3, $U5),
  __param(4, $qO),
  __param(5, $mP),
  __param(6, $TJ),
  __param(7, $1E),
  __param(8, $km),
  __param(9, $Yv),
  __param(10, $wn)
], $75b);
function notifyUserAction(chatService, context, action) {
  if ($asb(context.element)) {
    chatService.notifyUserAction({
      agentId: context.element.agent?.id,
      command: context.element.slashCommand?.name,
      sessionId: context.element.sessionId,
      requestId: context.element.requestId,
      result: context.element.result,
      action
    });
  }
}
function getActiveNotebookEditor(editorService) {
  const activeEditorPane = editorService.activeEditorPane;
  if (activeEditorPane?.getId() === $bM) {
    const notebookEditor = activeEditorPane.getControl();
    if (notebookEditor.hasModel()) {
      return notebookEditor;
    }
  }
  return void 0;
}
function getEditableActiveCodeEditor(editorService) {
  const activeCodeEditorInNotebook = getActiveNotebookEditor(editorService)?.activeCodeEditor;
  if (activeCodeEditorInNotebook && activeCodeEditorInNotebook.hasTextFocus() && activeCodeEditorInNotebook.hasModel()) {
    return activeCodeEditorInNotebook;
  }
  let activeEditorControl = editorService.activeTextEditorControl;
  if ($Q5(activeEditorControl)) {
    activeEditorControl = activeEditorControl.getOriginalEditor().hasTextFocus() ? activeEditorControl.getOriginalEditor() : activeEditorControl.getModifiedEditor();
  }
  if (!$P5(activeEditorControl)) {
    return void 0;
  }
  if (!activeEditorControl.hasModel()) {
    return void 0;
  }
  return activeEditorControl;
}
function isReadOnly(model, textFileService) {
  const activeTextModel = textFileService.files.get(model.uri) ?? textFileService.untitled.get(model.uri);
  return !!activeTextModel?.isReadonly();
}
function collectDocumentContextFromSelections(codeEditor, result) {
  const activeModel = codeEditor.getModel();
  const currentDocUri = activeModel.uri;
  const currentDocVersion = activeModel.getVersionId();
  const selections = codeEditor.getSelections();
  if (selections.length > 0) {
    result.push([
      {
        uri: currentDocUri,
        version: currentDocVersion,
        ranges: selections
      }
    ]);
  }
}
function collectDocumentContextFromContext(context, result) {
  if ($asb(context.element) && context.element.usedContext?.documents) {
    result.push(context.element.usedContext.documents);
  }
}
function getChatConversation(context) {
  if ($asb(context.element)) {
    return [{
      type: "response",
      message: context.element.response.getMarkdown(),
      references: $9O(context.element.contentReferences)
    }];
  } else if ($_rb(context.element)) {
    return [{
      type: "request",
      message: context.element.messageText
    }];
  } else {
    return [];
  }
}
function reindent(codeBlockContent, model, seletionStartLine) {
  const newContent = $Mf(codeBlockContent);
  if (newContent.length === 0) {
    return codeBlockContent;
  }
  const formattingOptions = model.getFormattingOptions();
  const codeIndentLevel = $85b(model.getLineContent(seletionStartLine), formattingOptions.tabSize).level;
  const indents = newContent.map((line) => $85b(line, formattingOptions.tabSize));
  const newContentIndentLevel = indents.reduce((min, indent, index) => {
    if (indent.length !== newContent[index].length) {
      return Math.min(indent.level, min);
    }
    return min;
  }, Number.MAX_VALUE);
  if (newContentIndentLevel === Number.MAX_VALUE || newContentIndentLevel === codeIndentLevel) {
    return codeBlockContent;
  }
  const newLines = [];
  for (let i2 = 0; i2 < newContent.length; i2++) {
    const { level, length } = indents[i2];
    const newLevel = Math.max(0, codeIndentLevel + level - newContentIndentLevel);
    const newIndentation = formattingOptions.insertSpaces ? " ".repeat(formattingOptions.tabSize * newLevel) : "	".repeat(newLevel);
    newLines.push(newIndentation + newContent[i2].substring(length));
  }
  return newLines.join("\n");
}
function $85b(line, tabSize) {
  let nSpaces = 0;
  let level = 0;
  let i2 = 0;
  let length = 0;
  const len = line.length;
  while (i2 < len) {
    const chCode = line.charCodeAt(i2);
    if (chCode === 32) {
      nSpaces++;
      if (nSpaces === tabSize) {
        level++;
        nSpaces = 0;
        length = i2 + 1;
      }
    } else if (chCode === 9) {
      level++;
      nSpaces = 0;
      length = i2 + 1;
    } else {
      break;
    }
    i2++;
  }
  return { level, length };
}

// out-build/vs/workbench/contrib/chat/browser/actions/chatCodeblockActions.js
var shellLangIds = [
  "fish",
  "ps1",
  "pwsh",
  "powershell",
  "sh",
  "shellscript",
  "zsh"
];
function $95b(thing) {
  return typeof thing === "object" && thing !== null && "code" in thing && "element" in thing;
}
function $05b(thing) {
  return typeof thing === "object" && thing !== null && "element" in thing;
}
function isResponseFiltered(context) {
  return $asb(context.element) && context.element.errorDetails?.responseIsFiltered;
}
var ChatCodeBlockAction = class extends $gJ {
  run(accessor, ...args2) {
    let context = args2[0];
    if (!$95b(context)) {
      const codeEditorService = accessor.get($U5);
      const editor = codeEditorService.getFocusedCodeEditor() || codeEditorService.getActiveCodeEditor();
      if (!editor) {
        return;
      }
      context = getContextFromEditor(editor, accessor);
      if (!$95b(context)) {
        return;
      }
    }
    return this.runWithContext(accessor, context);
  }
};
function $$5b() {
  $hJ(class CopyCodeBlockAction extends $gJ {
    constructor() {
      super({
        id: "workbench.action.chat.copyCodeBlock",
        title: localize2(4661, "Copy"),
        f1: false,
        category: $vNb,
        icon: $6l.copy,
        menu: {
          id: $bJ.ChatCodeBlock,
          group: "navigation",
          order: 30
        }
      });
    }
    run(accessor, ...args2) {
      const context = args2[0];
      if (!$95b(context) || isResponseFiltered(context)) {
        return;
      }
      const clipboardService = accessor.get($30);
      clipboardService.writeText(context.code);
      if ($asb(context.element)) {
        const chatService = accessor.get($qO);
        chatService.notifyUserAction({
          agentId: context.element.agent?.id,
          command: context.element.slashCommand?.name,
          sessionId: context.element.sessionId,
          requestId: context.element.requestId,
          result: context.element.result,
          action: {
            kind: "copy",
            codeBlockIndex: context.codeBlockIndex,
            copyKind: ChatCopyKind2.Toolbar,
            copiedCharacters: context.code.length,
            totalCharacters: context.code.length,
            copiedText: context.code
          }
        });
      }
    }
  });
  $kab?.addImplementation(5e4, "chat-codeblock", (accessor) => {
    const editor = accessor.get($U5).getFocusedCodeEditor();
    if (!editor) {
      return false;
    }
    const editorModel = editor.getModel();
    if (!editorModel) {
      return false;
    }
    const context = getContextFromEditor(editor, accessor);
    if (!context) {
      return false;
    }
    const noSelection = editor.getSelections()?.length === 1 && editor.getSelection()?.isEmpty();
    const copiedText = noSelection ? editorModel.getValue() : editor.getSelections()?.reduce((acc, selection) => acc + editorModel.getValueInRange(selection), "") ?? "";
    const totalCharacters = editorModel.getValueLength();
    const chatService = accessor.get($qO);
    const element = context.element;
    if (element) {
      chatService.notifyUserAction({
        agentId: element.agent?.id,
        command: element.slashCommand?.name,
        sessionId: element.sessionId,
        requestId: element.requestId,
        result: element.result,
        action: {
          kind: "copy",
          codeBlockIndex: context.codeBlockIndex,
          copyKind: ChatCopyKind2.Action,
          copiedText,
          copiedCharacters: copiedText.length,
          totalCharacters
        }
      });
    }
    if (noSelection) {
      accessor.get($30).writeText(context.code);
      return true;
    }
    return false;
  });
  $hJ(class SmartApplyInEditorAction extends ChatCodeBlockAction {
    constructor() {
      super({
        id: "workbench.action.chat.applyInEditor",
        title: localize2(4662, "Apply in Editor"),
        precondition: ChatContextKeys.enabled,
        f1: true,
        category: $vNb,
        icon: $6l.gitPullRequestGoToChanges,
        menu: [
          {
            id: $bJ.ChatCodeBlock,
            group: "navigation",
            when: $7m.and(...shellLangIds.map((e) => $7m.notEquals(EditorContextKeys.languageId.key, e))),
            order: 10
          },
          {
            id: $bJ.ChatCodeBlock,
            when: $7m.or(...shellLangIds.map((e) => $7m.equals(EditorContextKeys.languageId.key, e)))
          }
        ],
        keybinding: {
          when: $7m.or($7m.and(ChatContextKeys.inChatSession, ChatContextKeys.inChatInput.negate()), $usb),
          primary: 2048 | 3,
          mac: {
            primary: 256 | 3
            /* KeyCode.Enter */
          },
          weight: 400 + 1
        }
      });
    }
    runWithContext(accessor, context) {
      if (!this.a) {
        this.a = accessor.get($Pk).createInstance($75b);
      }
      return this.a.run(context);
    }
  });
  $hJ(class SmartApplyInEditorAction extends ChatCodeBlockAction {
    constructor() {
      super({
        id: "workbench.action.chat.insertCodeBlock",
        title: localize2(4663, "Insert At Cursor"),
        precondition: ChatContextKeys.enabled,
        f1: true,
        category: $vNb,
        icon: $6l.insert,
        menu: [{
          id: $bJ.ChatCodeBlock,
          group: "navigation",
          when: $7m.and(ChatContextKeys.inChatSession, ChatContextKeys.location.notEqualsTo(ChatAgentLocation.Terminal)),
          order: 20
        }, {
          id: $bJ.ChatCodeBlock,
          group: "navigation",
          when: $7m.and(ChatContextKeys.inChatSession, ChatContextKeys.location.isEqualTo(ChatAgentLocation.Terminal)),
          isHiddenByDefault: true,
          order: 20
        }],
        keybinding: {
          when: $7m.or($7m.and(ChatContextKeys.inChatSession, ChatContextKeys.inChatInput.negate()), $usb),
          primary: 2048 | 3,
          mac: {
            primary: 256 | 3
            /* KeyCode.Enter */
          },
          weight: 400 + 1
        }
      });
    }
    runWithContext(accessor, context) {
      const operation = accessor.get($Pk).createInstance($65b);
      return operation.run(context);
    }
  });
  $hJ(class InsertIntoNewFileAction extends ChatCodeBlockAction {
    constructor() {
      super({
        id: "workbench.action.chat.insertIntoNewFile",
        title: localize2(4664, "Insert into New File"),
        precondition: ChatContextKeys.enabled,
        f1: true,
        category: $vNb,
        icon: $6l.newFile,
        menu: {
          id: $bJ.ChatCodeBlock,
          group: "navigation",
          isHiddenByDefault: true,
          order: 40
        }
      });
    }
    async runWithContext(accessor, context) {
      if (isResponseFiltered(context)) {
        return;
      }
      const editorService = accessor.get($mJ);
      const chatService = accessor.get($qO);
      editorService.openEditor({ contents: context.code, languageId: context.languageId, resource: void 0 });
      if ($asb(context.element)) {
        chatService.notifyUserAction({
          agentId: context.element.agent?.id,
          command: context.element.slashCommand?.name,
          sessionId: context.element.sessionId,
          requestId: context.element.requestId,
          result: context.element.result,
          action: {
            kind: "insert",
            codeBlockIndex: context.codeBlockIndex,
            totalCharacters: context.code.length,
            newFile: true
          }
        });
      }
    }
  });
  $hJ(class RunInTerminalAction extends ChatCodeBlockAction {
    constructor() {
      super({
        id: "workbench.action.chat.runInTerminal",
        title: localize2(4665, "Insert into Terminal"),
        precondition: ChatContextKeys.enabled,
        f1: true,
        category: $vNb,
        icon: $6l.terminal,
        menu: [
          {
            id: $bJ.ChatCodeBlock,
            group: "navigation",
            when: $7m.and(ChatContextKeys.inChatSession, $7m.or(...shellLangIds.map((e) => $7m.equals(EditorContextKeys.languageId.key, e))))
          },
          {
            id: $bJ.ChatCodeBlock,
            group: "navigation",
            isHiddenByDefault: true,
            when: $7m.and(ChatContextKeys.inChatSession, ...shellLangIds.map((e) => $7m.notEquals(EditorContextKeys.languageId.key, e)))
          }
        ],
        keybinding: [{
          primary: 2048 | 512 | 3,
          mac: {
            primary: 256 | 512 | 3
            /* KeyCode.Enter */
          },
          weight: 100,
          when: $7m.or(ChatContextKeys.inChatSession, $usb)
        }]
      });
    }
    async runWithContext(accessor, context) {
      if (isResponseFiltered(context)) {
        return;
      }
      const chatService = accessor.get($qO);
      const terminalService = accessor.get($4Pb);
      const editorService = accessor.get($mJ);
      const terminalEditorService = accessor.get($6Pb);
      const terminalGroupService = accessor.get($7Pb);
      let terminal2 = await terminalService.getActiveOrCreateInstance();
      const unusableTerminal = terminal2.xterm?.isStdinDisabled || terminal2.shellLaunchConfig.isFeatureTerminal;
      terminal2 = unusableTerminal ? await terminalService.createTerminal() : terminal2;
      terminalService.setActiveInstance(terminal2);
      await terminal2.focusWhenReady(true);
      if (terminal2.target === TerminalLocation2.Editor) {
        const existingEditors = editorService.findEditors(terminal2.resource);
        terminalEditorService.openEditor(terminal2, { viewColumn: existingEditors?.[0].groupId });
      } else {
        terminalGroupService.showPanel(true);
      }
      terminal2.runCommand(context.code, false);
      if ($asb(context.element)) {
        chatService.notifyUserAction({
          agentId: context.element.agent?.id,
          command: context.element.slashCommand?.name,
          sessionId: context.element.sessionId,
          requestId: context.element.requestId,
          result: context.element.result,
          action: {
            kind: "runInTerminal",
            codeBlockIndex: context.codeBlockIndex,
            languageId: context.languageId
          }
        });
      }
    }
  });
  function navigateCodeBlocks(accessor, reverse) {
    const codeEditorService = accessor.get($U5);
    const chatWidgetService = accessor.get($2Nb);
    const widget = chatWidgetService.lastFocusedWidget;
    if (!widget) {
      return;
    }
    const editor = codeEditorService.getFocusedCodeEditor();
    const editorUri = editor?.getModel()?.uri;
    const curCodeBlockInfo = editorUri ? widget.getCodeBlockInfoForEditor(editorUri) : void 0;
    const focused = !widget.inputEditor.hasWidgetFocus() && widget.getFocus();
    const focusedResponse = $asb(focused) ? focused : void 0;
    const currentResponse = curCodeBlockInfo ? curCodeBlockInfo.element : focusedResponse ?? widget.viewModel?.getItems().reverse().find((item) => $asb(item));
    if (!currentResponse || !$asb(currentResponse)) {
      return;
    }
    widget.reveal(currentResponse);
    const responseCodeblocks = widget.getCodeBlockInfosForResponse(currentResponse);
    const focusIdx = curCodeBlockInfo ? (curCodeBlockInfo.codeBlockIndex + (reverse ? -1 : 1) + responseCodeblocks.length) % responseCodeblocks.length : reverse ? responseCodeblocks.length - 1 : 0;
    responseCodeblocks[focusIdx]?.focus();
  }
  $hJ(class NextCodeBlockAction extends $gJ {
    constructor() {
      super({
        id: "workbench.action.chat.nextCodeBlock",
        title: localize2(4666, "Next Code Block"),
        keybinding: {
          primary: 2048 | 512 | 12,
          mac: { primary: 2048 | 512 | 12 },
          weight: 200,
          when: ChatContextKeys.inChatSession
        },
        precondition: ChatContextKeys.enabled,
        f1: true,
        category: $vNb
      });
    }
    run(accessor, ...args2) {
      navigateCodeBlocks(accessor);
    }
  });
  $hJ(class PreviousCodeBlockAction extends $gJ {
    constructor() {
      super({
        id: "workbench.action.chat.previousCodeBlock",
        title: localize2(4667, "Previous Code Block"),
        keybinding: {
          primary: 2048 | 512 | 11,
          mac: { primary: 2048 | 512 | 11 },
          weight: 200,
          when: ChatContextKeys.inChatSession
        },
        precondition: ChatContextKeys.enabled,
        f1: true,
        category: $vNb
      });
    }
    run(accessor, ...args2) {
      navigateCodeBlocks(accessor, true);
    }
  });
}
function getContextFromEditor(editor, accessor) {
  const chatWidgetService = accessor.get($2Nb);
  const chatCodeBlockContextProviderService = accessor.get($8Nb);
  const model = editor.getModel();
  if (!model) {
    return;
  }
  const widget = chatWidgetService.lastFocusedWidget;
  const codeBlockInfo = widget?.getCodeBlockInfoForEditor(model.uri);
  if (!codeBlockInfo) {
    for (const provider of chatCodeBlockContextProviderService.providers) {
      const context = provider.getCodeBlockContext(editor);
      if (context) {
        return context;
      }
    }
    return;
  }
  return {
    element: codeBlockInfo.element,
    codeBlockIndex: codeBlockInfo.codeBlockIndex,
    code: editor.getValue(),
    languageId: editor.getModel().getLanguageId(),
    codemapperUri: codeBlockInfo.codemapperUri
  };
}
function $_5b() {
  class ChatCompareCodeBlockAction extends $gJ {
    run(accessor, ...args2) {
      const context = args2[0];
      if (!$05b(context)) {
        return;
      }
      return this.runWithContext(accessor, context);
    }
  }
  $hJ(class ApplyEditsCompareBlockAction extends ChatCompareCodeBlockAction {
    constructor() {
      super({
        id: "workbench.action.chat.applyCompareEdits",
        title: localize2(4668, "Apply Edits"),
        f1: false,
        category: $vNb,
        icon: $6l.gitPullRequestGoToChanges,
        precondition: $7m.and(EditorContextKeys.hasChanges, ChatContextKeys.editApplied.negate()),
        menu: {
          id: $bJ.ChatCompareBlock,
          group: "navigation",
          order: 1
        }
      });
    }
    async runWithContext(accessor, context) {
      const instaService = accessor.get($Pk);
      const editor = instaService.createInstance($iHb);
      await editor.preview(context.element, context.edit);
    }
  });
  $hJ(class DiscardEditsCompareBlockAction extends ChatCompareCodeBlockAction {
    constructor() {
      super({
        id: "workbench.action.chat.discardCompareEdits",
        title: localize2(4669, "Discard Edits"),
        f1: false,
        category: $vNb,
        icon: $6l.trash,
        precondition: $7m.and(EditorContextKeys.hasChanges, ChatContextKeys.editApplied.negate()),
        menu: {
          id: $bJ.ChatCompareBlock,
          group: "navigation",
          order: 2
        }
      });
    }
    async runWithContext(accessor, context) {
      const instaService = accessor.get($Pk);
      const editor = instaService.createInstance($iHb);
      editor.discard(context.element, context.edit);
    }
  });
}

// out-build/vs/editor/contrib/quickAccess/browser/editorNavigationQuickAccess.js
var $a6b = class {
  constructor(a) {
    this.a = a;
    this.j = void 0;
  }
  //#region Provider methods
  provide(picker, token, runOptions2) {
    const disposables = new $2c();
    picker.canAcceptInBackground = !!this.a?.canAcceptInBackground;
    picker.matchOnLabel = picker.matchOnDescription = picker.matchOnDetail = picker.sortByLabel = false;
    const pickerDisposable = disposables.add(new $4c());
    pickerDisposable.value = this.b(picker, token, runOptions2);
    disposables.add(this.h(() => {
      pickerDisposable.value = void 0;
      pickerDisposable.value = this.b(picker, token);
    }));
    return disposables;
  }
  b(picker, token, runOptions2) {
    const disposables = new $2c();
    const editor = this.i;
    if (editor && this.c(editor)) {
      const context = { editor };
      const codeEditor = $S5(editor);
      if (codeEditor) {
        let lastKnownEditorViewState = editor.saveViewState() ?? void 0;
        disposables.add(codeEditor.onDidChangeCursorPosition(() => {
          lastKnownEditorViewState = editor.saveViewState() ?? void 0;
        }));
        context.restoreViewState = () => {
          if (lastKnownEditorViewState && editor === this.i) {
            editor.restoreViewState(lastKnownEditorViewState);
          }
        };
        disposables.add($Qc(token.onCancellationRequested)(() => context.restoreViewState?.()));
      }
      disposables.add($1c(() => this.clearDecorations(editor)));
      disposables.add(this.d(context, picker, token, runOptions2));
    } else {
      disposables.add(this.e(picker, token));
    }
    return disposables;
  }
  /**
   * Subclasses to implement if they can operate on the text editor.
   */
  c(editor) {
    return true;
  }
  f({ editor }, options3) {
    editor.setSelection(
      options3.range,
      "code.jump"
      /* TextEditorSelectionSource.JUMP */
    );
    editor.revealRangeInCenter(
      options3.range,
      0
      /* ScrollType.Smooth */
    );
    if (!options3.preserveFocus) {
      editor.focus();
    }
    const model = editor.getModel();
    if (model && "getLineContent" in model) {
      $_Z(`${model.getLineContent(options3.range.startLineNumber)}`);
    }
  }
  g(editor) {
    return $Q5(editor) ? editor.getModel()?.modified : editor.getModel();
  }
  addDecorations(editor, range) {
    editor.changeDecorations((changeAccessor) => {
      const deleteDecorations = [];
      if (this.j) {
        deleteDecorations.push(this.j.overviewRulerDecorationId);
        deleteDecorations.push(this.j.rangeHighlightId);
        this.j = void 0;
      }
      const newDecorations = [
        // highlight the entire line on the range
        {
          range,
          options: {
            description: "quick-access-range-highlight",
            className: "rangeHighlight",
            isWholeLine: true
          }
        },
        // also add overview ruler highlight
        {
          range,
          options: {
            description: "quick-access-range-highlight-overview",
            overviewRuler: {
              color: $hs($pH),
              position: OverviewRulerLane.Full
            }
          }
        }
      ];
      const [rangeHighlightId, overviewRulerDecorationId] = changeAccessor.deltaDecorations(deleteDecorations, newDecorations);
      this.j = { rangeHighlightId, overviewRulerDecorationId };
    });
  }
  clearDecorations(editor) {
    const rangeHighlightDecorationId = this.j;
    if (rangeHighlightDecorationId) {
      editor.changeDecorations((changeAccessor) => {
        changeAccessor.deltaDecorations([
          rangeHighlightDecorationId.overviewRulerDecorationId,
          rangeHighlightDecorationId.rangeHighlightId
        ], []);
      });
      this.j = void 0;
    }
  }
};

// out-build/vs/editor/contrib/quickAccess/browser/gotoSymbolQuickAccess.js
var $b6b_1;
var $b6b = class $b6b2 extends $a6b {
  static {
    $b6b_1 = this;
  }
  static {
    this.PREFIX = "@";
  }
  static {
    this.SCOPE_PREFIX = ":";
  }
  static {
    this.PREFIX_BY_CATEGORY = `${this.PREFIX}${this.SCOPE_PREFIX}`;
  }
  constructor(l, m, options3 = /* @__PURE__ */ Object.create(null)) {
    super(options3);
    this.l = l;
    this.m = m;
    this.a = options3;
    this.a.canAcceptInBackground = true;
  }
  e(picker) {
    this.r(picker, localize(1383, null));
    return $3c.None;
  }
  d(context, picker, token, runOptions2) {
    const editor = context.editor;
    const model = this.g(editor);
    if (!model) {
      return $3c.None;
    }
    if (this.l.documentSymbolProvider.has(model)) {
      return this.t(context, model, picker, token, runOptions2);
    }
    return this.q(context, model, picker, token);
  }
  q(context, model, picker, token) {
    const disposables = new $2c();
    this.r(picker, localize(1384, null));
    (async () => {
      const result = await this.s(model, disposables);
      if (!result || token.isCancellationRequested) {
        return;
      }
      disposables.add(this.t(context, model, picker, token));
    })();
    return disposables;
  }
  r(picker, label3) {
    picker.items = [{
      label: label3,
      index: 0,
      kind: 14
      /* SymbolKind.String */
    }];
    picker.ariaLabel = label3;
  }
  async s(model, disposables) {
    if (this.l.documentSymbolProvider.has(model)) {
      return true;
    }
    const symbolProviderRegistryPromise = new $gi();
    const symbolProviderListener = disposables.add(this.l.documentSymbolProvider.onDidChange(() => {
      if (this.l.documentSymbolProvider.has(model)) {
        symbolProviderListener.dispose();
        symbolProviderRegistryPromise.complete(true);
      }
    }));
    disposables.add($1c(() => symbolProviderRegistryPromise.complete(false)));
    return symbolProviderRegistryPromise.p;
  }
  t(context, model, picker, token, runOptions2) {
    const editor = context.editor;
    const disposables = new $2c();
    disposables.add(picker.onDidAccept((event) => {
      const [item] = picker.selectedItems;
      if (item && item.range) {
        this.f(context, { range: item.range.selection, keyMods: picker.keyMods, preserveFocus: event.inBackground });
        runOptions2?.handleAccept?.(item, event.inBackground);
        if (!event.inBackground) {
          picker.hide();
        }
      }
    }));
    disposables.add(picker.onDidTriggerItemButton(({ item }) => {
      if (item && item.range) {
        this.f(context, { range: item.range.selection, keyMods: picker.keyMods, forceSideBySide: true });
        picker.hide();
      }
    }));
    const symbolsPromise = this.x(model, token);
    let picksCts = void 0;
    const updatePickerItems = async (positionToEnclose) => {
      picksCts?.dispose(true);
      picker.busy = false;
      picksCts = new $ad(token);
      picker.busy = true;
      try {
        const query = $VM(picker.value.substr($b6b_1.PREFIX.length).trim());
        const items = await this.u(symbolsPromise, query, void 0, picksCts.token, model);
        if (token.isCancellationRequested) {
          return;
        }
        if (items.length > 0) {
          picker.items = items;
          if (positionToEnclose && query.original.length === 0) {
            const candidate = $1(items, (item) => Boolean(item.type !== "separator" && item.range && $9C.containsPosition(item.range.decoration, positionToEnclose)));
            if (candidate) {
              picker.activeItems = [candidate];
            }
          }
        } else {
          if (query.original.length > 0) {
            this.r(picker, localize(1385, null));
          } else {
            this.r(picker, localize(1386, null));
          }
        }
      } finally {
        if (!token.isCancellationRequested) {
          picker.busy = false;
        }
      }
    };
    disposables.add(picker.onDidChangeValue(() => updatePickerItems(void 0)));
    updatePickerItems(editor.getSelection()?.getPosition());
    disposables.add(picker.onDidChangeActive(() => {
      const [item] = picker.activeItems;
      if (item && item.range) {
        editor.revealRangeInCenter(
          item.range.selection,
          0
          /* ScrollType.Smooth */
        );
        this.addDecorations(editor, item.range.decoration);
      }
    }));
    return disposables;
  }
  async u(symbolsPromise, query, options3, token, model) {
    const symbols = await symbolsPromise;
    if (token.isCancellationRequested) {
      return [];
    }
    const filterBySymbolKind = query.original.indexOf($b6b_1.SCOPE_PREFIX) === 0;
    const filterPos = filterBySymbolKind ? 1 : 0;
    let symbolQuery;
    let containerQuery;
    if (query.values && query.values.length > 1) {
      symbolQuery = $WM(query.values[0]);
      containerQuery = $WM(query.values.slice(1));
    } else {
      symbolQuery = query;
    }
    let buttons;
    const openSideBySideDirection = this.a?.openSideBySideDirection?.();
    if (openSideBySideDirection) {
      buttons = [{
        iconClass: openSideBySideDirection === "right" ? ThemeIcon.asClassName($6l.splitHorizontal) : ThemeIcon.asClassName($6l.splitVertical),
        tooltip: openSideBySideDirection === "right" ? localize(1387, null) : localize(1388, null)
      }];
    }
    const filteredSymbolPicks = [];
    for (let index = 0; index < symbols.length; index++) {
      const symbol = symbols[index];
      const symbolLabel = $Ef(symbol.name);
      const symbolLabelWithIcon = `$(${SymbolKinds.toIcon(symbol.kind).id}) ${symbolLabel}`;
      const symbolLabelIconOffset = symbolLabelWithIcon.length - symbolLabel.length;
      let containerLabel = symbol.containerName;
      if (options3?.extraContainerLabel) {
        if (containerLabel) {
          containerLabel = `${options3.extraContainerLabel} \u2022 ${containerLabel}`;
        } else {
          containerLabel = options3.extraContainerLabel;
        }
      }
      let symbolScore = void 0;
      let symbolMatches = void 0;
      let containerScore = void 0;
      let containerMatches = void 0;
      if (query.original.length > filterPos) {
        let skipContainerQuery = false;
        if (symbolQuery !== query) {
          [symbolScore, symbolMatches] = $SM(symbolLabelWithIcon, {
            ...query,
            values: void 0
            /* disable multi-query support */
          }, filterPos, symbolLabelIconOffset);
          if (typeof symbolScore === "number") {
            skipContainerQuery = true;
          }
        }
        if (typeof symbolScore !== "number") {
          [symbolScore, symbolMatches] = $SM(symbolLabelWithIcon, symbolQuery, filterPos, symbolLabelIconOffset);
          if (typeof symbolScore !== "number") {
            continue;
          }
        }
        if (!skipContainerQuery && containerQuery) {
          if (containerLabel && containerQuery.original.length > 0) {
            [containerScore, containerMatches] = $SM(containerLabel, containerQuery);
          }
          if (typeof containerScore !== "number") {
            continue;
          }
          if (typeof symbolScore === "number") {
            symbolScore += containerScore;
          }
        }
      }
      const deprecated = symbol.tags && symbol.tags.indexOf(
        1
        /* SymbolTag.Deprecated */
      ) >= 0;
      filteredSymbolPicks.push({
        index,
        kind: symbol.kind,
        score: symbolScore,
        label: symbolLabelWithIcon,
        ariaLabel: $UE(symbol.name, symbol.kind),
        description: containerLabel,
        highlights: deprecated ? void 0 : {
          label: symbolMatches,
          description: containerMatches
        },
        range: {
          selection: $9C.collapseToStart(symbol.selectionRange),
          decoration: symbol.range
        },
        uri: model.uri,
        symbolName: symbolLabel,
        strikethrough: deprecated,
        buttons
      });
    }
    const sortedFilteredSymbolPicks = filteredSymbolPicks.sort((symbolA, symbolB) => filterBySymbolKind ? this.w(symbolA, symbolB) : this.v(symbolA, symbolB));
    let symbolPicks = [];
    if (filterBySymbolKind) {
      let updateLastSeparatorLabel2 = function() {
        if (lastSeparator && typeof lastSymbolKind === "number" && lastSymbolKindCounter > 0) {
          lastSeparator.label = $wf(NLS_SYMBOL_KIND_CACHE[lastSymbolKind] || FALLBACK_NLS_SYMBOL_KIND, lastSymbolKindCounter);
        }
      };
      var updateLastSeparatorLabel = updateLastSeparatorLabel2;
      let lastSymbolKind = void 0;
      let lastSeparator = void 0;
      let lastSymbolKindCounter = 0;
      for (const symbolPick of sortedFilteredSymbolPicks) {
        if (lastSymbolKind !== symbolPick.kind) {
          updateLastSeparatorLabel2();
          lastSymbolKind = symbolPick.kind;
          lastSymbolKindCounter = 1;
          lastSeparator = { type: "separator" };
          symbolPicks.push(lastSeparator);
        } else {
          lastSymbolKindCounter++;
        }
        symbolPicks.push(symbolPick);
      }
      updateLastSeparatorLabel2();
    } else if (sortedFilteredSymbolPicks.length > 0) {
      symbolPicks = [
        { label: localize(1389, null, filteredSymbolPicks.length), type: "separator" },
        ...sortedFilteredSymbolPicks
      ];
    }
    return symbolPicks;
  }
  v(symbolA, symbolB) {
    if (typeof symbolA.score !== "number" && typeof symbolB.score === "number") {
      return 1;
    } else if (typeof symbolA.score === "number" && typeof symbolB.score !== "number") {
      return -1;
    }
    if (typeof symbolA.score === "number" && typeof symbolB.score === "number") {
      if (symbolA.score > symbolB.score) {
        return -1;
      } else if (symbolA.score < symbolB.score) {
        return 1;
      }
    }
    if (symbolA.index < symbolB.index) {
      return -1;
    } else if (symbolA.index > symbolB.index) {
      return 1;
    }
    return 0;
  }
  w(symbolA, symbolB) {
    const kindA = NLS_SYMBOL_KIND_CACHE[symbolA.kind] || FALLBACK_NLS_SYMBOL_KIND;
    const kindB = NLS_SYMBOL_KIND_CACHE[symbolB.kind] || FALLBACK_NLS_SYMBOL_KIND;
    const result = kindA.localeCompare(kindB);
    if (result === 0) {
      return this.v(symbolA, symbolB);
    }
    return result;
  }
  async x(document2, token) {
    const model = await this.m.getOrCreate(document2, token);
    return token.isCancellationRequested ? [] : model.asListOfDocumentSymbols();
  }
};
$b6b = $b6b_1 = __decorate([
  __param(0, $mP),
  __param(1, $phb)
], $b6b);
var FALLBACK_NLS_SYMBOL_KIND = localize(1390, null);
var NLS_SYMBOL_KIND_CACHE = {
  [
    5
    /* SymbolKind.Method */
  ]: localize(1391, null),
  [
    11
    /* SymbolKind.Function */
  ]: localize(1392, null),
  [
    8
    /* SymbolKind.Constructor */
  ]: localize(1393, null),
  [
    12
    /* SymbolKind.Variable */
  ]: localize(1394, null),
  [
    4
    /* SymbolKind.Class */
  ]: localize(1395, null),
  [
    22
    /* SymbolKind.Struct */
  ]: localize(1396, null),
  [
    23
    /* SymbolKind.Event */
  ]: localize(1397, null),
  [
    24
    /* SymbolKind.Operator */
  ]: localize(1398, null),
  [
    10
    /* SymbolKind.Interface */
  ]: localize(1399, null),
  [
    2
    /* SymbolKind.Namespace */
  ]: localize(1400, null),
  [
    3
    /* SymbolKind.Package */
  ]: localize(1401, null),
  [
    25
    /* SymbolKind.TypeParameter */
  ]: localize(1402, null),
  [
    1
    /* SymbolKind.Module */
  ]: localize(1403, null),
  [
    6
    /* SymbolKind.Property */
  ]: localize(1404, null),
  [
    9
    /* SymbolKind.Enum */
  ]: localize(1405, null),
  [
    21
    /* SymbolKind.EnumMember */
  ]: localize(1406, null),
  [
    14
    /* SymbolKind.String */
  ]: localize(1407, null),
  [
    0
    /* SymbolKind.File */
  ]: localize(1408, null),
  [
    17
    /* SymbolKind.Array */
  ]: localize(1409, null),
  [
    15
    /* SymbolKind.Number */
  ]: localize(1410, null),
  [
    16
    /* SymbolKind.Boolean */
  ]: localize(1411, null),
  [
    18
    /* SymbolKind.Object */
  ]: localize(1412, null),
  [
    19
    /* SymbolKind.Key */
  ]: localize(1413, null),
  [
    7
    /* SymbolKind.Field */
  ]: localize(1414, null),
  [
    13
    /* SymbolKind.Constant */
  ]: localize(1415, null)
};

// out-build/vs/workbench/contrib/search/common/cacheState.js
var LoadingPhase;
(function(LoadingPhase2) {
  LoadingPhase2[LoadingPhase2["Created"] = 1] = "Created";
  LoadingPhase2[LoadingPhase2["Loading"] = 2] = "Loading";
  LoadingPhase2[LoadingPhase2["Loaded"] = 3] = "Loaded";
  LoadingPhase2[LoadingPhase2["Errored"] = 4] = "Errored";
  LoadingPhase2[LoadingPhase2["Disposed"] = 5] = "Disposed";
})(LoadingPhase || (LoadingPhase = {}));
var $c6b = class {
  get cacheKey() {
    if (this.c === LoadingPhase.Loaded || !this.h) {
      return this.a;
    }
    return this.h.cacheKey;
  }
  get isLoaded() {
    const isLoaded = this.c === LoadingPhase.Loaded;
    return isLoaded || !this.h ? isLoaded : this.h.isLoaded;
  }
  get isUpdating() {
    const isUpdating = this.c === LoadingPhase.Loading;
    return isUpdating || !this.h ? isUpdating : this.h.isUpdating;
  }
  constructor(e, f, g, h3) {
    this.e = e;
    this.f = f;
    this.g = g;
    this.h = h3;
    this.a = $mW.nextId();
    this.b = this.e(this.a);
    this.c = LoadingPhase.Created;
    if (this.h) {
      const current = Object.assign({}, this.b, { cacheKey: null });
      const previous = Object.assign({}, this.h.b, { cacheKey: null });
      if (!$Pv(current, previous)) {
        this.h.dispose();
        this.h = void 0;
      }
    }
  }
  load() {
    if (this.isUpdating) {
      return this;
    }
    this.c = LoadingPhase.Loading;
    this.d = (async () => {
      try {
        await this.f(this.b);
        this.c = LoadingPhase.Loaded;
        if (this.h) {
          this.h.dispose();
          this.h = void 0;
        }
      } catch (error) {
        this.c = LoadingPhase.Errored;
        throw error;
      }
    })();
    return this;
  }
  dispose() {
    if (this.d) {
      (async () => {
        try {
          await this.d;
        } catch (error) {
        }
        this.c = LoadingPhase.Disposed;
        this.g(this.a);
      })();
    } else {
      this.c = LoadingPhase.Disposed;
    }
    if (this.h) {
      this.h.dispose();
      this.h = void 0;
    }
  }
};

// out-build/vs/workbench/contrib/search/browser/symbolsQuickAccess.js
var $$Nb_1;
var $$Nb = class $$Nb2 extends $rhb {
  static {
    $$Nb_1 = this;
  }
  static {
    this.PREFIX = "#";
  }
  static {
    this.a = 200;
  }
  static {
    this.b = /* @__PURE__ */ new Set([
      4,
      9,
      0,
      10,
      2,
      3,
      1
      /* SymbolKind.Module */
    ]);
  }
  get defaultFilterValue() {
    const editor = this.s.getFocusedCodeEditor();
    if (editor) {
      return $sgb(editor) ?? void 0;
    }
    return void 0;
  }
  constructor(j, m, n, r2, s) {
    super($$Nb_1.PREFIX, {
      canAcceptInBackground: true,
      noResultsPick: {
        label: localize(9784, null)
      }
    });
    this.j = j;
    this.m = m;
    this.n = n;
    this.r = r2;
    this.s = s;
    this.h = this.B(new $Th($$Nb_1.a));
  }
  get t() {
    const editorConfig = this.r.getValue().workbench?.editor;
    return {
      openEditorPinned: !editorConfig?.enablePreviewFromQuickOpen || !editorConfig?.enablePreview,
      openSideBySideDirection: editorConfig?.openSideBySideDirection
    };
  }
  g(filter, disposables, token) {
    return this.getSymbolPicks(filter, void 0, token);
  }
  async getSymbolPicks(filter, options3, token) {
    return this.h.trigger(async () => {
      if (token.isCancellationRequested) {
        return [];
      }
      return this.w($VM(filter), options3, token);
    }, options3?.delay);
  }
  async w(query, options3, token) {
    let symbolQuery;
    let containerQuery;
    if (query.values && query.values.length > 1) {
      symbolQuery = $WM(query.values[0]);
      containerQuery = $WM(query.values.slice(1));
    } else {
      symbolQuery = query;
    }
    const workspaceSymbols = await $gO(symbolQuery.original, token);
    if (token.isCancellationRequested) {
      return [];
    }
    const symbolPicks = [];
    const openSideBySideDirection = this.t.openSideBySideDirection;
    for (const { symbol, provider } of workspaceSymbols) {
      if (options3?.skipLocal && !$$Nb_1.b.has(symbol.kind) && !!symbol.containerName) {
        continue;
      }
      const symbolLabel = symbol.name;
      const symbolLabelWithIcon = `$(${SymbolKinds.toIcon(symbol.kind).id}) ${symbolLabel}`;
      const symbolLabelIconOffset = symbolLabelWithIcon.length - symbolLabel.length;
      let symbolScore = void 0;
      let symbolMatches = void 0;
      let skipContainerQuery = false;
      if (symbolQuery.original.length > 0) {
        if (symbolQuery !== query) {
          [symbolScore, symbolMatches] = $SM(symbolLabelWithIcon, {
            ...query,
            values: void 0
            /* disable multi-query support */
          }, 0, symbolLabelIconOffset);
          if (typeof symbolScore === "number") {
            skipContainerQuery = true;
          }
        }
        if (typeof symbolScore !== "number") {
          [symbolScore, symbolMatches] = $SM(symbolLabelWithIcon, symbolQuery, 0, symbolLabelIconOffset);
          if (typeof symbolScore !== "number") {
            continue;
          }
        }
      }
      const symbolUri = symbol.location.uri;
      let containerLabel = void 0;
      if (symbolUri) {
        const containerPath = this.j.getUriLabel(symbolUri, { relative: true });
        if (symbol.containerName) {
          containerLabel = `${symbol.containerName} \u2022 ${containerPath}`;
        } else {
          containerLabel = containerPath;
        }
      }
      let containerScore = void 0;
      let containerMatches = void 0;
      if (!skipContainerQuery && containerQuery && containerQuery.original.length > 0) {
        if (containerLabel) {
          [containerScore, containerMatches] = $SM(containerLabel, containerQuery);
        }
        if (typeof containerScore !== "number") {
          continue;
        }
        if (typeof symbolScore === "number") {
          symbolScore += containerScore;
        }
      }
      const deprecated = symbol.tags ? symbol.tags.indexOf(
        1
        /* SymbolTag.Deprecated */
      ) >= 0 : false;
      symbolPicks.push({
        symbol,
        resource: symbolUri,
        score: symbolScore,
        label: symbolLabelWithIcon,
        ariaLabel: symbolLabel,
        highlights: deprecated ? void 0 : {
          label: symbolMatches,
          description: containerMatches
        },
        description: containerLabel,
        strikethrough: deprecated,
        buttons: [
          {
            iconClass: openSideBySideDirection === "right" ? ThemeIcon.asClassName($6l.splitHorizontal) : ThemeIcon.asClassName($6l.splitVertical),
            tooltip: openSideBySideDirection === "right" ? localize(9785, null) : localize(9786, null)
          }
        ],
        trigger: (buttonIndex, keyMods) => {
          this.y(provider, symbol, token, { keyMods, forceOpenSideBySide: true });
          return TriggerAction.CLOSE_PICKER;
        },
        accept: async (keyMods, event) => this.y(provider, symbol, token, { keyMods, preserveFocus: event.inBackground, forcePinned: event.inBackground })
      });
    }
    if (!options3?.skipSorting) {
      symbolPicks.sort((symbolA, symbolB) => this.z(symbolA, symbolB));
    }
    return symbolPicks;
  }
  async y(provider, symbol, token, options3) {
    let symbolToOpen = symbol;
    if (typeof provider.resolveWorkspaceSymbol === "function") {
      symbolToOpen = await provider.resolveWorkspaceSymbol(symbol, token) || symbol;
      if (token.isCancellationRequested) {
        return;
      }
    }
    if (symbolToOpen.location.uri.scheme === Schemas.http || symbolToOpen.location.uri.scheme === Schemas.https) {
      await this.m.open(symbolToOpen.location.uri, { fromUserGesture: true, allowContributedOpeners: true });
    } else {
      await this.n.openEditor({
        resource: symbolToOpen.location.uri,
        options: {
          preserveFocus: options3?.preserveFocus,
          pinned: options3.keyMods.ctrlCmd || options3.forcePinned || this.t.openEditorPinned,
          selection: symbolToOpen.location.range ? $9C.collapseToStart(symbolToOpen.location.range) : void 0
        }
      }, options3.keyMods.alt || this.t.openEditorPinned && options3.keyMods.ctrlCmd || options3?.forceOpenSideBySide ? $oJ : $nJ);
    }
  }
  z(symbolA, symbolB) {
    if (typeof symbolA.score === "number" && typeof symbolB.score === "number") {
      if (symbolA.score > symbolB.score) {
        return -1;
      }
      if (symbolA.score < symbolB.score) {
        return 1;
      }
    }
    if (symbolA.symbol && symbolB.symbol) {
      const symbolAName = symbolA.symbol.name.toLowerCase();
      const symbolBName = symbolB.symbol.name.toLowerCase();
      const res = symbolAName.localeCompare(symbolBName);
      if (res !== 0) {
        return res;
      }
    }
    if (symbolA.symbol && symbolB.symbol) {
      const symbolAKind = SymbolKinds.toIcon(symbolA.symbol.kind).id;
      const symbolBKind = SymbolKinds.toIcon(symbolB.symbol.kind).id;
      return symbolAKind.localeCompare(symbolBKind);
    }
    return 0;
  }
};
$$Nb = $$Nb_1 = __decorate([
  __param(0, $ZI),
  __param(1, $O4),
  __param(2, $mJ),
  __param(3, $kl),
  __param(4, $U5)
], $$Nb);

// out-build/vs/workbench/contrib/codeEditor/browser/quickaccess/gotoSymbolQuickAccess.js
var $d6b_1;
var $d6b = class $d6b2 extends $b6b {
  static {
    $d6b_1 = this;
  }
  constructor(z, A, B, languageFeaturesService, C, outlineModelService) {
    super(languageFeaturesService, outlineModelService, {
      openSideBySideDirection: () => this.D.openSideBySideDirection
    });
    this.z = z;
    this.A = A;
    this.B = B;
    this.C = C;
    this.h = this.z.onDidActiveEditorChange;
  }
  //#region DocumentSymbols (text editor required)
  get D() {
    const editorConfig = this.B.getValue().workbench?.editor;
    return {
      openEditorPinned: !editorConfig?.enablePreviewFromQuickOpen || !editorConfig?.enablePreview,
      openSideBySideDirection: editorConfig?.openSideBySideDirection
    };
  }
  get i() {
    if ($R5(this.z.activeEditorPane?.getControl())) {
      return void 0;
    }
    return this.z.activeTextEditorControl;
  }
  f(context, options3) {
    if ((options3.keyMods.alt || this.D.openEditorPinned && options3.keyMods.ctrlCmd || options3.forceSideBySide) && this.z.activeEditor) {
      context.restoreViewState?.();
      const editorOptions2 = {
        selection: options3.range,
        pinned: options3.keyMods.ctrlCmd || this.D.openEditorPinned,
        preserveFocus: options3.preserveFocus
      };
      this.A.sideGroup.openEditor(this.z.activeEditor, editorOptions2);
    } else {
      super.f(context, options3);
    }
  }
  static {
    this.G = 8e3;
  }
  async getSymbolPicks(model, filter, options3, disposables, token) {
    const result = await Promise.race([
      this.s(model, disposables),
      $Wh($d6b_1.G)
    ]);
    if (!result || token.isCancellationRequested) {
      return [];
    }
    return this.u(this.x(model, token), $VM(filter), options3, token, model);
  }
  //#endregion
  e(picker) {
    if (this.I()) {
      return this.J(picker);
    }
    return super.e(picker);
  }
  I() {
    return this.z.activeEditorPane ? this.C.canCreateOutline(this.z.activeEditorPane) : false;
  }
  J(picker) {
    const pane = this.z.activeEditorPane;
    if (!pane) {
      return $3c.None;
    }
    const cts = new $ad();
    const disposables = new $2c();
    disposables.add($1c(() => cts.dispose(true)));
    picker.busy = true;
    this.C.createOutline(pane, 4, cts.token).then((outline) => {
      if (!outline) {
        return;
      }
      if (cts.token.isCancellationRequested) {
        outline.dispose();
        return;
      }
      disposables.add(outline);
      const viewState = outline.captureViewState();
      disposables.add($1c(() => {
        if (picker.selectedItems.length === 0) {
          viewState.dispose();
        }
      }));
      const entries2 = outline.config.quickPickDataSource.getQuickPickElements();
      const items = entries2.map((entry, idx) => {
        return {
          kind: 0,
          index: idx,
          score: 0,
          label: entry.label,
          description: entry.description,
          ariaLabel: entry.ariaLabel,
          iconClasses: entry.iconClasses
        };
      });
      disposables.add(picker.onDidAccept(() => {
        picker.hide();
        const [entry] = picker.selectedItems;
        if (entry && entries2[entry.index]) {
          outline.reveal(entries2[entry.index].element, {}, false, false);
        }
      }));
      const updatePickerItems = () => {
        const filteredItems = items.filter((item) => {
          if (picker.value === "@") {
            item.score = 0;
            item.highlights = void 0;
            return true;
          }
          const trimmedQuery = picker.value.substring($b6b.PREFIX.length).trim();
          const parsedLabel = $_l(item.label);
          const score2 = $Xl(trimmedQuery, trimmedQuery.toLowerCase(), 0, parsedLabel.text, parsedLabel.text.toLowerCase(), 0, { firstMatchCanBeWeak: true, boostFullMatch: true });
          if (!score2) {
            return false;
          }
          item.score = score2[1];
          item.highlights = { label: $am(trimmedQuery, parsedLabel) ?? void 0 };
          return true;
        });
        if (filteredItems.length === 0) {
          const label3 = localize(5215, null);
          picker.items = [{
            label: label3,
            index: -1,
            kind: 14
            /* SymbolKind.String */
          }];
          picker.ariaLabel = label3;
        } else {
          picker.items = filteredItems;
        }
      };
      updatePickerItems();
      disposables.add(picker.onDidChangeValue(updatePickerItems));
      const previewDisposable = new $4c();
      disposables.add(previewDisposable);
      disposables.add(picker.onDidChangeActive(() => {
        const [entry] = picker.activeItems;
        if (entry && entries2[entry.index]) {
          previewDisposable.value = outline.preview(entries2[entry.index].element);
        } else {
          previewDisposable.clear();
        }
      }));
    }).catch((err) => {
      $gb(err);
      picker.hide();
    }).finally(() => {
      picker.busy = false;
    });
    return disposables;
  }
};
$d6b = $d6b_1 = __decorate([
  __param(0, $mJ),
  __param(1, $iJ),
  __param(2, $kl),
  __param(3, $mP),
  __param(4, $vyb),
  __param(5, $phb)
], $d6b);
var GotoSymbolAction = class _GotoSymbolAction extends $gJ {
  static {
    this.ID = "workbench.action.gotoSymbol";
  }
  constructor() {
    super({
      id: _GotoSymbolAction.ID,
      title: {
        ...localize2(5220, "Go to Symbol in Editor..."),
        mnemonicTitle: localize(5216, null)
      },
      f1: true,
      keybinding: {
        when: $7m.and($osb.negate(), $nsb.negate()),
        weight: 200,
        primary: 2048 | 1024 | 45
        /* KeyCode.KeyO */
      },
      menu: [{
        id: $bJ.MenubarGoMenu,
        group: "4_symbol_nav",
        order: 1
      }]
    });
  }
  run(accessor) {
    accessor.get($1M).quickAccess.show($d6b.PREFIX, { itemActivation: ItemActivation.NONE });
  }
};
$hJ(GotoSymbolAction);
$Wn.as($CM.Quickaccess).registerQuickAccessProvider({
  ctor: $d6b,
  prefix: $b6b.PREFIX,
  contextKey: "inFileSymbolsPicker",
  placeholder: localize(5217, null),
  helpEntries: [
    {
      description: localize(5218, null),
      prefix: $b6b.PREFIX,
      commandId: GotoSymbolAction.ID,
      commandCenterOrder: 40
    },
    {
      description: localize(5219, null),
      prefix: $b6b.PREFIX_BY_CATEGORY
    }
  ]
});

// out-build/vs/workbench/contrib/chat/browser/actions/chatQuickInputActions.js
var $e6b = "workbench.action.quickchat.toggle";
function $f6b() {
  $hJ(QuickChatGlobalAction);
  $hJ(AskQuickChatAction);
  $hJ(class OpenInChatViewAction extends $gJ {
    constructor() {
      super({
        id: "workbench.action.quickchat.openInChatView",
        title: localize2(4717, "Open in Chat View"),
        f1: false,
        category: $vNb,
        icon: $6l.commentDiscussion,
        menu: {
          id: $bJ.ChatInputSide,
          group: "navigation",
          order: 10
        }
      });
    }
    run(accessor) {
      const quickChatService = accessor.get($6Nb);
      quickChatService.openInChatView();
    }
  });
  $hJ(class CloseQuickChatAction extends $gJ {
    constructor() {
      super({
        id: "workbench.action.quickchat.close",
        title: localize2(4718, "Close Quick Chat"),
        f1: false,
        category: $vNb,
        icon: $6l.close,
        menu: {
          id: $bJ.ChatInputSide,
          group: "navigation",
          order: 20
        }
      });
    }
    run(accessor) {
      const quickChatService = accessor.get($6Nb);
      quickChatService.close();
    }
  });
  $hJ(class LaunchInlineChatFromQuickChatAction extends $gJ {
    constructor() {
      super({
        id: "workbench.action.quickchat.launchInlineChat",
        title: localize2(4719, "Launch Inline Chat"),
        f1: false,
        category: $vNb
      });
    }
    async run(accessor) {
      const quickChatService = accessor.get($6Nb);
      const codeEditorService = accessor.get($U5);
      if (quickChatService.focused) {
        quickChatService.close();
      }
      const codeEditor = codeEditorService.getActiveCodeEditor();
      if (!codeEditor) {
        return;
      }
      const controller = $cHb.get(codeEditor);
      if (!controller) {
        return;
      }
      await controller.run();
      controller.focus();
    }
  });
}
var QuickChatGlobalAction = class extends $gJ {
  constructor() {
    super({
      id: $e6b,
      title: localize2(4720, "Quick Chat"),
      precondition: ChatContextKeys.enabled,
      icon: $6l.commentDiscussion,
      f1: false,
      category: $vNb,
      keybinding: {
        weight: 200,
        primary: 2048 | 1024 | 512 | 42
      },
      menu: {
        id: $bJ.ChatCommandCenter,
        group: "e_quickChat",
        order: 5
      },
      metadata: {
        description: localize(4713, null),
        args: [{
          name: "args",
          schema: {
            anyOf: [
              {
                type: "object",
                required: ["query"],
                properties: {
                  query: {
                    description: localize(4714, null),
                    type: "string"
                  },
                  isPartialQuery: {
                    description: localize(4715, null),
                    type: "boolean"
                  }
                }
              },
              {
                type: "string",
                description: localize(4716, null)
              }
            ]
          }
        }]
      }
    });
  }
  run(accessor, query) {
    const quickChatService = accessor.get($6Nb);
    let options3;
    switch (typeof query) {
      case "string":
        options3 = { query };
        break;
      case "object":
        options3 = query;
        break;
    }
    if (options3?.query) {
      options3.selection = new $_D(1, options3.query.length + 1, 1, options3.query.length + 1);
    }
    quickChatService.toggle(options3);
  }
};
var AskQuickChatAction = class extends $gJ {
  constructor() {
    super({
      id: `workbench.action.openQuickChat`,
      category: $vNb,
      title: localize2(4721, "Open Quick Chat"),
      f1: true
    });
  }
  run(accessor, query) {
    const quickChatService = accessor.get($6Nb);
    quickChatService.toggle(query ? {
      query,
      selection: new $_D(1, query.length + 1, 1, query.length + 1)
    } : void 0);
  }
};

// out-build/vs/workbench/contrib/search/browser/anythingQuickAccess.js
var $g6b_1;
function isEditorSymbolQuickPickItem(pick) {
  const candidate = pick;
  return !!candidate?.range && !!candidate.resource;
}
var $g6b = class $g6b2 extends $rhb {
  static {
    $g6b_1 = this;
  }
  static {
    this.PREFIX = "";
  }
  static {
    this.j = {
      label: localize(9539, null)
    };
  }
  static {
    this.m = 512;
  }
  static {
    this.n = 200;
  }
  static {
    this.r = 200;
  }
  // allow some time to merge fast and slow picks to reduce flickering
  get defaultFilterValue() {
    if (this.W.preserveInput) {
      return DefaultQuickAccessFilterValue.LAST;
    }
    return void 0;
  }
  constructor(t, u, w, y, z, C, D, F, G, H, I, J, L, M, N, O, P, Q, R, S, U) {
    super($g6b_1.PREFIX, {
      canAcceptInBackground: true,
      noResultsPick: $g6b_1.j
    });
    this.t = t;
    this.u = u;
    this.w = w;
    this.y = y;
    this.z = z;
    this.C = C;
    this.D = D;
    this.F = F;
    this.G = G;
    this.H = H;
    this.I = I;
    this.J = J;
    this.L = L;
    this.M = M;
    this.N = N;
    this.O = O;
    this.P = P;
    this.Q = Q;
    this.R = R;
    this.S = S;
    this.U = U;
    this.s = this.B(new class extends $3c {
      constructor(c, f) {
        super();
        this.c = c;
        this.f = f;
        this.picker = void 0;
        this.editorViewState = this.B(this.f.createInstance($0yb));
        this.scorerCache = /* @__PURE__ */ Object.create(null);
        this.fileQueryCache = void 0;
        this.lastOriginalFilter = void 0;
        this.lastFilter = void 0;
        this.lastRange = void 0;
        this.lastGlobalPicks = void 0;
        this.isQuickNavigating = void 0;
      }
      set(picker) {
        this.picker = picker;
        Event2.once(picker.onDispose)(() => {
          if (picker === this.picker) {
            this.picker = void 0;
          }
        });
        const isQuickNavigating = !!picker.quickNavigate;
        if (!isQuickNavigating) {
          this.fileQueryCache = this.c.eb();
          this.scorerCache = /* @__PURE__ */ Object.create(null);
        }
        this.isQuickNavigating = isQuickNavigating;
        this.lastOriginalFilter = void 0;
        this.lastFilter = void 0;
        this.lastRange = void 0;
        this.lastGlobalPicks = void 0;
        this.editorViewState.reset();
      }
    }(this, this.t));
    this.ab = new $YM({ skipDescription: true });
    this.cb = this.B(new $Th($g6b_1.n));
    this.db = this.t.createInstance($eT);
    this.mb = new $sf(() => $Wn.as($CM.Quickaccess));
    this.ob = this.B(this.t.createInstance($$Nb));
    this.qb = this.t.createInstance($d6b);
  }
  get W() {
    const editorConfig = this.I.getValue().workbench?.editor;
    const searchConfig = this.I.getValue().search;
    const quickAccessConfig = this.I.getValue().workbench.quickOpen;
    return {
      openEditorPinned: !editorConfig?.enablePreviewFromQuickOpen || !editorConfig?.enablePreview,
      openSideBySideDirection: editorConfig?.openSideBySideDirection,
      includeSymbols: searchConfig?.quickOpen.includeSymbols,
      includeHistory: searchConfig?.quickOpen.includeHistory,
      historyFilterSortOrder: searchConfig?.quickOpen.history.filterSortOrder,
      preserveInput: quickAccessConfig.preserveInput
    };
  }
  provide(picker, token, runOptions2) {
    const disposables = new $2c();
    this.s.set(picker);
    const editorDecorationsDisposable = disposables.add(new $4c());
    disposables.add(picker.onDidChangeActive(() => {
      editorDecorationsDisposable.value = void 0;
      const [item] = picker.activeItems;
      if (isEditorSymbolQuickPickItem(item)) {
        editorDecorationsDisposable.value = this.X(item);
      }
    }));
    disposables.add(Event2.once(picker.onDidHide)(({ reason }) => {
      if (reason === QuickInputHideReason.Gesture) {
        this.s.editorViewState.restore();
      }
    }));
    disposables.add(super.provide(picker, token, runOptions2));
    return disposables;
  }
  X(pick) {
    const activeEditor = this.J.activeEditor;
    if (!this.O.extUri.isEqual(pick.resource, activeEditor?.resource)) {
      return $3c.None;
    }
    const activeEditorControl = this.J.activeTextEditorControl;
    if (!activeEditorControl) {
      return $3c.None;
    }
    this.s.editorViewState.set();
    activeEditorControl.revealRangeInCenter(
      pick.range.selection,
      0
      /* ScrollType.Smooth */
    );
    this.addDecorations(activeEditorControl, pick.range.decoration);
    return $1c(() => this.clearDecorations(activeEditorControl));
  }
  g(originalFilter, disposables, token, runOptions2) {
    const filterWithRange = $iO(originalFilter, [$d6b.PREFIX]);
    let filter;
    if (filterWithRange) {
      filter = filterWithRange.filter;
    } else {
      filter = originalFilter;
    }
    this.s.lastRange = filterWithRange?.range;
    if (originalFilter !== this.s.lastOriginalFilter && filter === this.s.lastFilter) {
      return null;
    }
    const lastWasFiltering = !!this.s.lastOriginalFilter;
    this.s.lastOriginalFilter = originalFilter;
    this.s.lastFilter = filter;
    const picks = this.s.picker?.items;
    const activePick = this.s.picker?.activeItems[0];
    if (picks && activePick) {
      const activePickIsEditorSymbol = isEditorSymbolQuickPickItem(activePick);
      const activePickIsNoResultsInEditorSymbols = activePick === $g6b_1.j && filter.indexOf($d6b.PREFIX) >= 0;
      if (!activePickIsEditorSymbol && !activePickIsNoResultsInEditorSymbols) {
        this.s.lastGlobalPicks = {
          items: picks,
          active: activePick
        };
      }
    }
    return this.Z(filter, {
      ...runOptions2,
      enableEditorSymbolSearch: lastWasFiltering
    }, disposables, token);
  }
  Z(filter, options3, disposables, token) {
    const query = $VM(filter);
    if (options3.enableEditorSymbolSearch) {
      const editorSymbolPicks = this.rb(query, disposables, token);
      if (editorSymbolPicks) {
        return editorSymbolPicks;
      }
    }
    const activePick = this.s.picker?.activeItems[0];
    if (isEditorSymbolQuickPickItem(activePick) && this.s.lastGlobalPicks) {
      return this.s.lastGlobalPicks;
    }
    const historyEditorPicks = this.bb(query);
    let picks = new Array();
    if (options3.additionPicks) {
      for (const pick of options3.additionPicks) {
        if (pick.type === "separator") {
          picks.push(pick);
          continue;
        }
        if (!query.original) {
          pick.highlights = void 0;
          picks.push(pick);
          continue;
        }
        const { score: score2, labelMatch, descriptionMatch } = $TM(pick, query, true, $ZM, this.s.scorerCache);
        if (!score2) {
          continue;
        }
        pick.highlights = {
          label: labelMatch,
          description: descriptionMatch
        };
        picks.push(pick);
      }
    }
    if (this.s.isQuickNavigating) {
      if (picks.length > 0) {
        picks.push({ type: "separator", label: localize(9540, null) });
      }
      picks = historyEditorPicks;
    } else {
      if (options3.includeHelp) {
        picks.push(...this.nb(query, token, options3));
      }
      if (historyEditorPicks.length !== 0) {
        picks.push({ type: "separator", label: localize(9541, null) });
        picks.push(...historyEditorPicks);
      }
    }
    return {
      // Fast picks: help (if included) & editor history
      picks: options3.filter ? picks.filter((p) => options3.filter?.(p)) : picks,
      // Slow picks: files and symbols
      additionalPicks: (async () => {
        const additionalPicksExcludes = new $Ec();
        for (const historyEditorPick of historyEditorPicks) {
          if (historyEditorPick.resource) {
            additionalPicksExcludes.set(historyEditorPick.resource, true);
          }
        }
        let additionalPicks = await this.$(query, additionalPicksExcludes, this.W.includeSymbols, token);
        if (options3.filter) {
          additionalPicks = additionalPicks.filter((p) => options3.filter?.(p));
        }
        if (token.isCancellationRequested) {
          return [];
        }
        return additionalPicks.length > 0 ? [
          { type: "separator", label: this.W.includeSymbols ? localize(9542, null) : localize(9543, null) },
          ...additionalPicks
        ] : [];
      })(),
      // allow some time to merge files and symbols to reduce flickering
      mergeDelay: $g6b_1.r
    };
  }
  async $(query, excludes, includeSymbols, token) {
    const [filePicks, symbolPicks] = await Promise.all([
      this.fb(query, excludes, token),
      this.pb(query, includeSymbols, token)
    ]);
    if (token.isCancellationRequested) {
      return [];
    }
    const sortedAnythingPicks = top([...filePicks, ...symbolPicks], (anyPickA, anyPickB) => $UM(anyPickA, anyPickB, query, true, $ZM, this.s.scorerCache), $g6b_1.m);
    const filteredAnythingPicks = [];
    for (const anythingPick of sortedAnythingPicks) {
      if (anythingPick.highlights) {
        filteredAnythingPicks.push(anythingPick);
      } else {
        const { score: score2, labelMatch, descriptionMatch } = $TM(anythingPick, query, true, $ZM, this.s.scorerCache);
        if (!score2) {
          continue;
        }
        anythingPick.highlights = {
          label: labelMatch,
          description: descriptionMatch
        };
        filteredAnythingPicks.push(anythingPick);
      }
    }
    return filteredAnythingPicks;
  }
  bb(query) {
    const configuration2 = this.W;
    if (!query.normalized) {
      return this.L.getHistory().map((editor) => this.tb(editor, configuration2));
    }
    if (!this.W.includeHistory) {
      return [];
    }
    const editorHistoryScorerAccessor = query.containsPathSeparator ? $ZM : this.ab;
    const editorHistoryPicks = [];
    for (const editor of this.L.getHistory()) {
      const resource = editor.resource;
      if (!resource || !this.C.hasProvider(resource) && resource.scheme !== Schemas.untitled && resource.scheme !== Schemas.vscodeTerminal) {
        continue;
      }
      const editorHistoryPick = this.tb(editor, configuration2);
      const { score: score2, labelMatch, descriptionMatch } = $TM(editorHistoryPick, query, false, editorHistoryScorerAccessor, this.s.scorerCache);
      if (!score2) {
        continue;
      }
      editorHistoryPick.highlights = {
        label: labelMatch,
        description: descriptionMatch
      };
      editorHistoryPicks.push(editorHistoryPick);
    }
    if (this.W.historyFilterSortOrder === "recency") {
      return editorHistoryPicks;
    }
    return editorHistoryPicks.sort((editorA, editorB) => $UM(editorA, editorB, query, false, editorHistoryScorerAccessor, this.s.scorerCache));
  }
  eb() {
    return new $c6b((cacheKey) => this.db.file(this.w.getWorkspace().folders, this.jb({ cacheKey })), (query) => this.u.fileSearch(query), (cacheKey) => this.u.clearCache(cacheKey), this.s.fileQueryCache).load();
  }
  async fb(query, excludes, token) {
    if (!query.normalized) {
      return [];
    }
    const absolutePathResult = await this.kb(query, token);
    if (token.isCancellationRequested) {
      return [];
    }
    let fileMatches;
    if (absolutePathResult) {
      if (excludes.has(absolutePathResult)) {
        return [];
      }
      const absolutePathPick = this.tb(absolutePathResult, this.W);
      absolutePathPick.highlights = {
        label: [{ start: 0, end: absolutePathPick.label.length }],
        description: absolutePathPick.description ? [{ start: 0, end: absolutePathPick.description.length }] : void 0
      };
      return [absolutePathPick];
    }
    if (this.s.fileQueryCache?.isLoaded) {
      fileMatches = await this.gb(query, token);
    } else {
      fileMatches = await this.cb.trigger(async () => {
        if (token.isCancellationRequested) {
          return [];
        }
        return this.gb(query, token);
      });
    }
    if (token.isCancellationRequested) {
      return [];
    }
    const configuration2 = this.W;
    return fileMatches.filter((resource) => !excludes.has(resource)).map((resource) => this.tb(resource, configuration2));
  }
  async gb(query, token) {
    const [fileSearchResults, relativePathFileResults] = await Promise.all([
      // File search: this is a search over all files of the workspace using the provided pattern
      this.hb(query, token),
      // Relative path search: we also want to consider results that match files inside the workspace
      // by looking for relative paths that the user typed as query. This allows to return even excluded
      // results into the picker if found (e.g. helps for opening compilation results that are otherwise
      // excluded)
      this.lb(query, token)
    ]);
    if (token.isCancellationRequested) {
      return [];
    }
    if (!relativePathFileResults) {
      return fileSearchResults;
    }
    const relativePathFileResultsMap = new $Ec();
    for (const relativePathFileResult of relativePathFileResults) {
      relativePathFileResultsMap.set(relativePathFileResult, true);
    }
    return [
      ...fileSearchResults.filter((result) => !relativePathFileResultsMap.has(result)),
      ...relativePathFileResults
    ];
  }
  async hb(query, token) {
    let filePattern = "";
    if (query.values && query.values.length > 1) {
      filePattern = query.values[0].original;
    } else {
      filePattern = query.original;
    }
    const fileSearchResults = await this.ib(filePattern, token);
    if (token.isCancellationRequested) {
      return [];
    }
    if (fileSearchResults.limitHit && query.values && query.values.length > 1) {
      const additionalFileSearchResults = await this.ib(query.original, token);
      if (token.isCancellationRequested) {
        return [];
      }
      const existingFileSearchResultsMap = new $Ec();
      for (const fileSearchResult of fileSearchResults.results) {
        existingFileSearchResultsMap.set(fileSearchResult.resource, true);
      }
      for (const additionalFileSearchResult of additionalFileSearchResults.results) {
        if (!existingFileSearchResultsMap.has(additionalFileSearchResult.resource)) {
          fileSearchResults.results.push(additionalFileSearchResult);
        }
      }
    }
    return fileSearchResults.results.map((result) => result.resource);
  }
  ib(filePattern, token) {
    const start = Date.now();
    return this.u.fileSearch(this.db.file(this.w.getWorkspace().folders, this.jb({
      filePattern,
      cacheKey: this.s.fileQueryCache?.cacheKey,
      maxResults: $g6b_1.m
    })), token).finally(() => {
      this.S.trace(`QuickAccess fileSearch ${Date.now() - start}ms`);
    });
  }
  jb(input) {
    return {
      _reason: "openFileHandler",
      // used for telemetry - do not change
      extraFileResources: this.t.invokeFunction($hO),
      filePattern: input.filePattern || "",
      cacheKey: input.cacheKey,
      maxResults: input.maxResults || 0,
      sortByScore: true
    };
  }
  async kb(query, token) {
    if (!query.containsPathSeparator) {
      return;
    }
    const userHome = await this.y.userHome();
    const detildifiedQuery = $3t(query.original, userHome.scheme === Schemas.file ? userHome.fsPath : userHome.path);
    if (token.isCancellationRequested) {
      return;
    }
    const isAbsolutePathQuery = (await this.y.path).isAbsolute(detildifiedQuery);
    if (token.isCancellationRequested) {
      return;
    }
    if (isAbsolutePathQuery) {
      const resource = $Fh(await this.y.fileURI(detildifiedQuery), this.z.remoteAuthority, this.y.defaultUriScheme);
      if (token.isCancellationRequested) {
        return;
      }
      try {
        if ((await this.C.stat(resource)).isFile) {
          return resource;
        }
      } catch (error) {
      }
    }
    return;
  }
  async lb(query, token) {
    if (!query.containsPathSeparator) {
      return;
    }
    const isAbsolutePathQuery = (await this.y.path).isAbsolute(query.original);
    if (!isAbsolutePathQuery) {
      const resources = [];
      for (const folder of this.w.getWorkspace().folders) {
        if (token.isCancellationRequested) {
          break;
        }
        const resource = $Fh(folder.toResource(query.original), this.z.remoteAuthority, this.y.defaultUriScheme);
        try {
          if ((await this.C.stat(resource)).isFile) {
            resources.push(resource);
          }
        } catch (error) {
        }
      }
      return resources;
    }
    return;
  }
  nb(query, token, runOptions2) {
    if (query.normalized) {
      return [];
    }
    const providers2 = this.mb.value.getQuickAccessProviders().filter((p) => p.helpEntries.some((h3) => h3.commandCenterOrder !== void 0)).flatMap((provider) => provider.helpEntries.filter((h3) => h3.commandCenterOrder !== void 0).map((helpEntry) => {
      const providerSpecificOptions = {
        ...runOptions2,
        includeHelp: provider.prefix === $g6b_1.PREFIX ? false : runOptions2?.includeHelp
      };
      const label3 = helpEntry.commandCenterLabel ?? helpEntry.description;
      return {
        label: label3,
        description: helpEntry.prefix ?? provider.prefix,
        commandCenterOrder: helpEntry.commandCenterOrder,
        keybinding: helpEntry.commandId ? this.Q.lookupKeybinding(helpEntry.commandId) : void 0,
        ariaLabel: localize(9544, null, label3, helpEntry.description),
        accept: () => {
          this.P.quickAccess.show(provider.prefix, {
            preserveValue: true,
            providerOptions: providerSpecificOptions
          });
        }
      };
    }));
    if (this.R.enabled) {
      providers2.push({
        label: localize(9545, null),
        commandCenterOrder: 30,
        keybinding: this.Q.lookupKeybinding($e6b),
        accept: () => this.R.toggle()
      });
    }
    return providers2.sort((a, b) => a.commandCenterOrder - b.commandCenterOrder);
  }
  async pb(query, includeSymbols, token) {
    if (!query.normalized || // we need a value for search for
    !includeSymbols || // we need to enable symbols in search
    this.s.lastRange) {
      return [];
    }
    return this.ob.getSymbolPicks(query.original, {
      skipLocal: true,
      skipSorting: true,
      delay: $g6b_1.n
    }, token);
  }
  rb(query, disposables, token) {
    const filterSegments = query.original.split($d6b.PREFIX);
    const filter = filterSegments.length > 1 ? filterSegments[filterSegments.length - 1].trim() : void 0;
    if (typeof filter !== "string") {
      return null;
    }
    const activeGlobalPick = this.s.lastGlobalPicks?.active;
    if (!activeGlobalPick) {
      return null;
    }
    const activeGlobalResource = activeGlobalPick.resource;
    if (!activeGlobalResource || !this.C.hasProvider(activeGlobalResource) && activeGlobalResource.scheme !== Schemas.untitled) {
      return null;
    }
    if (activeGlobalPick.label.includes($d6b.PREFIX) || activeGlobalPick.description?.includes($d6b.PREFIX)) {
      if (filterSegments.length < 3) {
        return null;
      }
    }
    return this.sb(activeGlobalPick, activeGlobalResource, filter, disposables, token);
  }
  async sb(activeGlobalPick, activeGlobalResource, filter, disposables, token) {
    try {
      this.s.editorViewState.set();
      await this.s.editorViewState.openTransientEditor({
        resource: activeGlobalResource,
        options: { preserveFocus: true, revealIfOpened: true, ignoreError: true }
      });
    } catch (error) {
      return [];
    }
    if (token.isCancellationRequested) {
      return [];
    }
    let model = this.F.getModel(activeGlobalResource);
    if (!model) {
      try {
        const modelReference = disposables.add(await this.N.createModelReference(activeGlobalResource));
        if (token.isCancellationRequested) {
          return [];
        }
        model = modelReference.object.textEditorModel;
      } catch (error) {
        return [];
      }
    }
    const editorSymbolPicks = await this.qb.getSymbolPicks(model, filter, { extraContainerLabel: $0l(activeGlobalPick.label) }, disposables, token);
    if (token.isCancellationRequested) {
      return [];
    }
    return editorSymbolPicks.map((editorSymbolPick) => {
      if (editorSymbolPick.type === "separator") {
        return editorSymbolPick;
      }
      return {
        ...editorSymbolPick,
        resource: activeGlobalResource,
        description: editorSymbolPick.description,
        trigger: (buttonIndex, keyMods) => {
          this.ub(activeGlobalResource, { keyMods, range: editorSymbolPick.range?.selection, forceOpenSideBySide: true });
          return TriggerAction.CLOSE_PICKER;
        },
        accept: (keyMods, event) => this.ub(activeGlobalResource, { keyMods, range: editorSymbolPick.range?.selection, preserveFocus: event.inBackground, forcePinned: event.inBackground })
      };
    });
  }
  addDecorations(editor, range) {
    this.qb.addDecorations(editor, range);
  }
  clearDecorations(editor) {
    this.qb.clearDecorations(editor);
  }
  //#endregion
  //#region Helpers
  tb(resourceOrEditor, configuration2) {
    const isEditorHistoryEntry = !URI.isUri(resourceOrEditor);
    let resource;
    let label3;
    let description = void 0;
    let isDirty = void 0;
    let extraClasses;
    let icon2 = void 0;
    if ($dL(resourceOrEditor)) {
      resource = $mL.getOriginalUri(resourceOrEditor);
      label3 = resourceOrEditor.getName();
      description = resourceOrEditor.getDescription();
      isDirty = resourceOrEditor.isDirty() && !resourceOrEditor.isSaving();
      extraClasses = resourceOrEditor.getLabelExtraClasses();
      icon2 = resourceOrEditor.getIcon();
    } else {
      resource = URI.isUri(resourceOrEditor) ? resourceOrEditor : resourceOrEditor.resource;
      const customLabel = this.U.getName(resource);
      label3 = customLabel || $rh(resource);
      description = this.D.getUriLabel(!!customLabel ? resource : $uh(resource), { relative: true });
      isDirty = this.H.isDirty(resource) && !this.M.hasShortAutoSaveDelay(resource);
      extraClasses = [];
    }
    const labelAndDescription = description ? `${label3} ${description}` : label3;
    const iconClassesValue = new $sf(() => $gdb(this.F, this.G, resource, void 0, icon2).concat(extraClasses));
    const buttonsValue = new $sf(() => {
      const openSideBySideDirection = configuration2.openSideBySideDirection;
      const buttons = [];
      buttons.push({
        iconClass: openSideBySideDirection === "right" ? ThemeIcon.asClassName($6l.splitHorizontal) : ThemeIcon.asClassName($6l.splitVertical),
        tooltip: openSideBySideDirection === "right" ? localize(9546, null) : localize(9547, null)
      });
      if (isEditorHistoryEntry) {
        buttons.push({
          iconClass: isDirty ? "dirty-anything " + ThemeIcon.asClassName($6l.circleFilled) : ThemeIcon.asClassName($6l.close),
          tooltip: localize(9548, null),
          alwaysVisible: isDirty
        });
      }
      return buttons;
    });
    return {
      resource,
      label: label3,
      ariaLabel: isDirty ? localize(9549, null, labelAndDescription) : labelAndDescription,
      description,
      get iconClasses() {
        return iconClassesValue.value;
      },
      get buttons() {
        return buttonsValue.value;
      },
      trigger: (buttonIndex, keyMods) => {
        switch (buttonIndex) {
          case 0:
            this.ub(resourceOrEditor, { keyMods, range: this.s.lastRange, forceOpenSideBySide: true });
            return TriggerAction.CLOSE_PICKER;
          case 1:
            if (!URI.isUri(resourceOrEditor)) {
              this.L.removeFromHistory(resourceOrEditor);
              return TriggerAction.REMOVE_ITEM;
            }
        }
        return TriggerAction.NO_ACTION;
      },
      accept: (keyMods, event) => this.ub(resourceOrEditor, { keyMods, range: this.s.lastRange, preserveFocus: event.inBackground, forcePinned: event.inBackground })
    };
  }
  async ub(resourceOrEditor, options3) {
    const editorOptions2 = {
      preserveFocus: options3.preserveFocus,
      pinned: options3.keyMods?.ctrlCmd || options3.forcePinned || this.W.openEditorPinned,
      selection: options3.range ? $9C.collapseToStart(options3.range) : void 0
    };
    const targetGroup = options3.keyMods?.alt || this.W.openEditorPinned && options3.keyMods?.ctrlCmd || options3.forceOpenSideBySide ? $oJ : $nJ;
    if (targetGroup === $oJ) {
      await this.s.editorViewState.restore();
    }
    if ($dL(resourceOrEditor)) {
      await this.J.openEditor(resourceOrEditor, editorOptions2, targetGroup);
    } else {
      let resourceEditorInput;
      if (URI.isUri(resourceOrEditor)) {
        resourceEditorInput = {
          resource: resourceOrEditor,
          options: editorOptions2
        };
      } else {
        resourceEditorInput = {
          ...resourceOrEditor,
          options: {
            ...resourceOrEditor.options,
            ...editorOptions2
          }
        };
      }
      await this.J.openEditor(resourceEditorInput, targetGroup);
    }
  }
};
$g6b = $g6b_1 = __decorate([
  __param(0, $Pk),
  __param(1, $TN),
  __param(2, $Zk),
  __param(3, $aT),
  __param(4, $US),
  __param(5, $km),
  __param(6, $ZI),
  __param(7, $sG),
  __param(8, $1E),
  __param(9, $XI),
  __param(10, $kl),
  __param(11, $mJ),
  __param(12, $tY),
  __param(13, $4J),
  __param(14, $oG),
  __param(15, $vl),
  __param(16, $1M),
  __param(17, $Ty),
  __param(18, $6Nb),
  __param(19, $wn),
  __param(20, $qrb)
], $g6b);

// out-build/vs/workbench/contrib/search/browser/searchTreeModel/searchTreeCommon.js
function $j6b(element, testArray) {
  do {
    if (testArray.includes(element)) {
      return true;
    }
  } while (!$v6b(element.parent()) && (element = element.parent()));
  return false;
}
var SearchModelLocation;
(function(SearchModelLocation2) {
  SearchModelLocation2[SearchModelLocation2["PANEL"] = 0] = "PANEL";
  SearchModelLocation2[SearchModelLocation2["QUICK_ACCESS"] = 1] = "QUICK_ACCESS";
})(SearchModelLocation || (SearchModelLocation = {}));
var $k6b = "plainTextSearch";
var $l6b = "aiTextSearch";
function $m6b(element) {
  const parentArray = [];
  let currElement = element;
  while (!$w6b(currElement)) {
    parentArray.push(currElement);
    currElement = currElement.parent();
  }
  return parentArray;
}
var $n6b = "SEARCH_MODEL_";
var $o6b = "SEARCH_RESULT_";
var $p6b = "TEXT_SEARCH_HEADING_";
var $q6b = "FOLDER_MATCH_";
var $r6b = "FILE_MATCH_";
var $s6b = "MATCH_";
function $t6b(events) {
  const retEvent = {
    elements: [],
    added: false,
    removed: false
  };
  events.forEach((e) => {
    if (e.added) {
      retEvent.added = true;
    }
    if (e.removed) {
      retEvent.removed = true;
    }
    retEvent.elements = retEvent.elements.concat(e.elements);
  });
  return retEvent;
}
function $v6b(obj) {
  return typeof obj === "object" && obj !== null && typeof obj.id === "function" && obj.id().startsWith($o6b);
}
function $w6b(obj) {
  return typeof obj === "object" && obj !== null && typeof obj.id === "function" && obj.id().startsWith($p6b);
}
function $x6b(obj) {
  return $w6b(obj) && typeof obj.replace === "function" && typeof obj.replaceAll === "function";
}
function $y6b(obj) {
  return typeof obj === "object" && obj !== null && typeof obj.id === "function" && obj.id().startsWith($q6b);
}
function $z6b(obj) {
  return $y6b(obj) && obj.resource instanceof URI;
}
function $A6b(obj) {
  return $z6b(obj) && typeof obj.createAndConfigureFileMatch === "function";
}
function $B6b(obj) {
  return $y6b(obj) && typeof obj.createAndConfigureFileMatch === "function";
}
function $C6b(obj) {
  return typeof obj === "object" && obj !== null && typeof obj.id === "function" && obj.id().startsWith($r6b);
}
function $D6b(obj) {
  return typeof obj === "object" && obj !== null && typeof obj.id === "function" && obj.id().startsWith($s6b);
}
function $E6b(matches) {
  const folderMatches = [];
  const fileMatches = [];
  matches.forEach((e) => {
    if ($C6b(e)) {
      fileMatches.push(e);
    } else {
      folderMatches.push(e);
    }
  });
  return fileMatches.concat(folderMatches.map((e) => e.allDownstreamFileMatches()).flat());
}

// out-build/vs/workbench/contrib/chat/browser/chatPasteProviders.js
var COPY_MIME_TYPES = "application/vnd.code.additional-editor-data";
var $s8b = class {
  constructor(a, c) {
    this.a = a;
    this.c = c;
    this.kind = new $oE("chat.attach.image");
    this.providedPasteEditKinds = [this.kind];
    this.copyMimeTypes = [];
    this.pasteMimeTypes = ["image/*"];
  }
  async provideDocumentPasteEdits(model, ranges, dataTransfer, context, token) {
    if (!this.c.extensions.some((ext) => $zN(ext, "chatReferenceBinaryData"))) {
      return;
    }
    const supportedMimeTypes = [
      "image/png",
      "image/jpeg",
      "image/jpg",
      "image/bmp",
      "image/gif",
      "image/tiff"
    ];
    let mimeType;
    let imageItem;
    for (const type of supportedMimeTypes) {
      imageItem = dataTransfer.get(type);
      if (imageItem) {
        mimeType = type;
        break;
      }
    }
    if (!imageItem || !mimeType) {
      return;
    }
    const currClipboard = await imageItem.asFile()?.data();
    if (token.isCancellationRequested || !currClipboard) {
      return;
    }
    const widget = this.a.getWidgetByInputUri(model.uri);
    if (!widget) {
      return;
    }
    const attachedVariables = widget.attachmentModel.attachments;
    const displayName = localize(4987, null);
    let tempDisplayName = displayName;
    for (let appendValue = 2; attachedVariables.some((attachment) => attachment.name === tempDisplayName); appendValue++) {
      tempDisplayName = `${displayName} ${appendValue}`;
    }
    const imageContext = await getImageAttachContext2(currClipboard, mimeType, token, tempDisplayName);
    if (token.isCancellationRequested || !imageContext) {
      return;
    }
    const currentContextIds = widget.attachmentModel.getAttachmentIDs();
    if (currentContextIds.has(imageContext.id)) {
      return;
    }
    const edit3 = createCustomPasteEdit(model, imageContext, mimeType, this.kind, localize(4988, null), this.a);
    return createEditSession(edit3);
  }
};
async function getImageAttachContext2(data, mimeType, token, displayName) {
  const imageHash = await $t8b(data);
  if (token.isCancellationRequested) {
    return void 0;
  }
  return {
    value: data,
    id: imageHash,
    name: displayName,
    isImage: true,
    icon: $6l.fileMedia,
    isDynamic: true,
    mimeType
  };
}
async function $t8b(data) {
  const hashBuffer = await crypto.subtle.digest("SHA-256", data);
  const hashArray = Array.from(new Uint8Array(hashBuffer));
  return hashArray.map((b) => b.toString(16).padStart(2, "0")).join("");
}
function $u8b(array2) {
  if (array2.length < 4) {
    return false;
  }
  const identifier2 = {
    png: [137, 80, 78, 71, 13, 10, 26, 10],
    jpeg: [255, 216, 255],
    bmp: [66, 77],
    gif: [71, 73, 70, 56],
    tiff: [73, 73, 42, 0]
  };
  return Object.values(identifier2).some((signature) => signature.every((byte, index) => array2[index] === byte));
}
var $v8b = class {
  constructor() {
    this.providedPasteEditKinds = [];
    this.copyMimeTypes = [COPY_MIME_TYPES];
    this.pasteMimeTypes = [];
  }
  async prepareDocumentPaste(model, ranges, dataTransfer, token) {
    if (model.uri.scheme === $1Nb.INPUT_SCHEME) {
      return;
    }
    const customDataTransfer = new $lE();
    const data = { range: ranges[0], uri: model.uri.toJSON() };
    customDataTransfer.append(COPY_MIME_TYPES, $jE(JSON.stringify(data)));
    return customDataTransfer;
  }
};
var $w8b = class {
  constructor(a, c) {
    this.a = a;
    this.c = c;
    this.kind = new $oE("chat.attach.text");
    this.providedPasteEditKinds = [this.kind];
    this.copyMimeTypes = [];
    this.pasteMimeTypes = [COPY_MIME_TYPES];
  }
  async provideDocumentPasteEdits(model, ranges, dataTransfer, context, token) {
    if (model.uri.scheme !== $1Nb.INPUT_SCHEME) {
      return;
    }
    const text2 = dataTransfer.get($YC.text);
    const editorData = dataTransfer.get("vscode-editor-data");
    const additionalEditorData = dataTransfer.get(COPY_MIME_TYPES);
    if (!editorData || !text2 || !additionalEditorData) {
      return;
    }
    const textdata = await text2.asString();
    const metadata = JSON.parse(await editorData.asString());
    const additionalData = JSON.parse(await additionalEditorData.asString());
    const widget = this.a.getWidgetByInputUri(model.uri);
    if (!widget) {
      return;
    }
    const start = additionalData.range.startLineNumber;
    const end = additionalData.range.endLineNumber;
    if (start === end) {
      const textModel = this.c.getModel(URI.revive(additionalData.uri));
      if (!textModel) {
        return;
      }
      const lineContent = textModel.getLineContent(start);
      if (lineContent !== textdata) {
        return;
      }
    }
    const copiedContext = getCopiedContext(textdata, URI.revive(additionalData.uri), metadata.mode, additionalData.range);
    if (token.isCancellationRequested || !copiedContext) {
      return;
    }
    const currentContextIds = widget.attachmentModel.getAttachmentIDs();
    if (currentContextIds.has(copiedContext.id)) {
      return;
    }
    const edit3 = createCustomPasteEdit(model, copiedContext, $YC.text, this.kind, localize(4989, null), this.a);
    edit3.yieldTo = [{ kind: $oE.Empty.append("text", "plain") }];
    return createEditSession(edit3);
  }
};
function getCopiedContext(code, file, language, range) {
  const fileName = $sh(file);
  const start = range.startLineNumber;
  const end = range.endLineNumber;
  const resultText = `Copied Selection of Code: 


 From the file: ${fileName} From lines ${start} to ${end} 
 \`\`\`${code}\`\`\``;
  const pastedLines = start === end ? localize(4990, null) : localize(4991, null, end + 1 - start);
  return {
    kind: "paste",
    value: resultText,
    id: `${fileName}${start}${end}${range.startColumn}${range.endColumn}`,
    name: `${fileName} ${pastedLines}`,
    icon: $6l.code,
    isDynamic: true,
    pastedLines,
    language,
    fileName: file.toString(),
    copiedFrom: {
      uri: file,
      range
    },
    code,
    references: [{
      reference: file,
      kind: "reference"
    }]
  };
}
function createCustomPasteEdit(model, context, handledMimeType, kind, title, chatWidgetService) {
  const customEdit = {
    resource: model.uri,
    variable: context,
    undo: () => {
      const widget = chatWidgetService.getWidgetByInputUri(model.uri);
      if (!widget) {
        throw new Error("No widget found for undo");
      }
      widget.attachmentModel.delete(context.id);
    },
    redo: () => {
      const widget = chatWidgetService.getWidgetByInputUri(model.uri);
      if (!widget) {
        throw new Error("No widget found for redo");
      }
      widget.attachmentModel.addContext(context);
    },
    metadata: { needsConfirmation: false, label: context.name }
  };
  return {
    insertText: "",
    title,
    kind,
    handledMimeType,
    additionalEdit: {
      edits: [customEdit]
    }
  };
}
function createEditSession(edit3) {
  return {
    edits: [edit3],
    dispose: () => {
    }
  };
}
var $x8b = class $x8b2 extends $3c {
  constructor(languageFeaturesService, chatWidgetService, extensionService, modelService) {
    super();
    this.B(languageFeaturesService.documentPasteEditProvider.register({ scheme: $1Nb.INPUT_SCHEME, pattern: "*", hasAccessToAllModels: true }, new $s8b(chatWidgetService, extensionService)));
    this.B(languageFeaturesService.documentPasteEditProvider.register({ scheme: $1Nb.INPUT_SCHEME, pattern: "*", hasAccessToAllModels: true }, new $w8b(chatWidgetService, modelService)));
    this.B(languageFeaturesService.documentPasteEditProvider.register("*", new $v8b()));
  }
};
$x8b = __decorate([
  __param(0, $mP),
  __param(1, $2Nb),
  __param(2, $wN),
  __param(3, $sG)
], $x8b);

// out-build/vs/workbench/contrib/chat/browser/actions/chatContextActions.js
function $y8b() {
  $hJ($z8b);
  $hJ(AttachFileToChatAction);
  $hJ(AttachSelectionToChatAction);
  $hJ(AttachFileToEditingSessionAction);
  $hJ(AttachSelectionToEditingSessionAction);
}
function isIGotoSymbolQuickPickItem(obj) {
  return typeof obj === "object" && typeof obj.symbolName === "string" && !!obj.uri && !!obj.range;
}
function isISymbolQuickPickItem(obj) {
  return typeof obj === "object" && typeof obj.symbol === "object" && !!obj.symbol;
}
function isIQuickPickItemWithResource(obj) {
  return typeof obj === "object" && typeof obj.resource === "object" && URI.isUri(obj.resource);
}
function isIOpenEditorsQuickPickItem(obj) {
  return typeof obj === "object" && obj.id === "open-editors";
}
function isISearchResultsQuickPickItem(obj) {
  return typeof obj === "object" && obj.kind === "search-results";
}
function isScreenshotQuickPickItem(obj) {
  return typeof obj === "object" && obj.kind === "screenshot";
}
function isRelatedFileQuickPickItem(obj) {
  return typeof obj === "object" && obj.kind === "related-files";
}
var AttachFileAction = class extends $gJ {
  getFiles(accessor, ...args2) {
    const textEditorService = accessor.get($mJ);
    const contexts = Array.isArray(args2[1]) ? args2[1] : [args2[0]];
    const files = [];
    for (const context of contexts) {
      let uri;
      if (URI.isUri(context)) {
        uri = context;
      } else if ($C6b(context)) {
        uri = context.resource;
      } else if ($D6b(context)) {
        uri = context.parent().resource;
      } else if (!context && textEditorService.activeTextEditorControl?.getEditorType() === EditorType.ICodeEditor) {
        uri = textEditorService.activeEditor?.resource;
      }
      if (uri && [Schemas.file, Schemas.vscodeRemote, Schemas.untitled].includes(uri.scheme)) {
        files.push(uri);
      }
    }
    return files;
  }
};
var AttachFileToChatAction = class _AttachFileToChatAction extends AttachFileAction {
  static {
    this.ID = "workbench.action.chat.attachFile";
  }
  constructor() {
    super({
      id: _AttachFileToChatAction.ID,
      title: localize2(4684, "Add File to Chat"),
      category: $vNb,
      f1: false,
      precondition: ChatContextKeys.enabled,
      menu: [{
        id: $bJ.ChatCommandCenter,
        group: "b_chat_context",
        when: $Dpb.isEqualTo("workbench.editors.files.textFileEditor"),
        order: 10
      }, {
        id: $bJ.SearchContext,
        group: "z_chat",
        order: 1
      }]
    });
  }
  async run(accessor, ...args2) {
    const variablesService = accessor.get($kO);
    const files = this.getFiles(accessor, ...args2);
    if (files.length) {
      (await $3Nb(accessor.get($uob)))?.focusInput();
      for (const file of files) {
        variablesService.attachContext("file", file, ChatAgentLocation.Panel);
      }
    }
  }
};
var AttachSelectionToChatAction = class _AttachSelectionToChatAction extends $gJ {
  static {
    this.ID = "workbench.action.chat.attachSelection";
  }
  constructor() {
    super({
      id: _AttachSelectionToChatAction.ID,
      title: localize2(4685, "Add Selection to Chat"),
      category: $vNb,
      f1: false,
      precondition: ChatContextKeys.enabled,
      menu: [{
        id: $bJ.ChatCommandCenter,
        group: "b_chat_context",
        when: $Dpb.isEqualTo("workbench.editors.files.textFileEditor"),
        order: 15
      }, {
        id: $bJ.SearchContext,
        group: "z_chat",
        order: 2
      }]
    });
  }
  async run(accessor, ...args2) {
    const variablesService = accessor.get($kO);
    const textEditorService = accessor.get($mJ);
    const [_, matches] = args2;
    if (matches && matches.length > 0) {
      const uris = /* @__PURE__ */ new Map();
      for (const match of matches) {
        if ($C6b(match)) {
          uris.set(match.resource, void 0);
        } else {
          const context = { uri: match._parent.resource, range: match._range };
          const range = uris.get(context.uri);
          if (!range || range.startLineNumber !== context.range.startLineNumber && range.endLineNumber !== context.range.endLineNumber) {
            uris.set(context.uri, context.range);
            variablesService.attachContext("file", context, ChatAgentLocation.Panel);
          }
        }
      }
      for (const uri of uris) {
        const [resource, range] = uri;
        if (!range) {
          variablesService.attachContext("file", { uri: resource }, ChatAgentLocation.Panel);
        }
      }
    } else {
      const activeEditor = textEditorService.activeTextEditorControl;
      const activeUri = textEditorService.activeEditor?.resource;
      if (textEditorService.activeTextEditorControl?.getEditorType() === EditorType.ICodeEditor && activeUri && [Schemas.file, Schemas.vscodeRemote, Schemas.untitled].includes(activeUri.scheme)) {
        const selection = activeEditor?.getSelection();
        if (selection) {
          (await $3Nb(accessor.get($uob)))?.focusInput();
          variablesService.attachContext("file", { uri: activeUri, range: selection }, ChatAgentLocation.Panel);
        }
      }
    }
  }
};
var AttachFileToEditingSessionAction = class _AttachFileToEditingSessionAction extends AttachFileAction {
  static {
    this.ID = "workbench.action.edits.attachFile";
  }
  constructor() {
    super({
      id: _AttachFileToEditingSessionAction.ID,
      title: localize2(4686, "Add File to {0}", "Copilot Edits"),
      category: $vNb,
      f1: false,
      precondition: ChatContextKeys.enabled,
      menu: [{
        id: $bJ.ChatCommandCenter,
        group: "c_edits_context",
        when: $Dpb.isEqualTo("workbench.editors.files.textFileEditor"),
        order: 10
      }, {
        id: $bJ.SearchContext,
        group: "z_chat",
        order: 2
      }]
    });
  }
  async run(accessor, ...args2) {
    const variablesService = accessor.get($kO);
    const files = this.getFiles(accessor, ...args2);
    if (files.length) {
      (await $4Nb(accessor.get($uob)))?.focusInput();
      for (const file of files) {
        variablesService.attachContext("file", file, ChatAgentLocation.EditingSession);
      }
    }
  }
};
var AttachSelectionToEditingSessionAction = class _AttachSelectionToEditingSessionAction extends $gJ {
  static {
    this.ID = "workbench.action.edits.attachSelection";
  }
  constructor() {
    super({
      id: _AttachSelectionToEditingSessionAction.ID,
      title: localize2(4687, "Add Selection to {0}", "Copilot Edits"),
      category: $vNb,
      f1: false,
      precondition: $7m.and(ChatContextKeys.enabled, $Dpb.isEqualTo("workbench.editors.files.textFileEditor")),
      menu: {
        id: $bJ.ChatCommandCenter,
        group: "c_edits_context",
        order: 15
      }
    });
  }
  async run(accessor, ...args2) {
    const variablesService = accessor.get($kO);
    const textEditorService = accessor.get($mJ);
    const activeEditor = textEditorService.activeTextEditorControl;
    const activeUri = textEditorService.activeEditor?.resource;
    if (textEditorService.activeTextEditorControl?.getEditorType() === EditorType.ICodeEditor && activeUri && [Schemas.file, Schemas.vscodeRemote, Schemas.untitled].includes(activeUri.scheme)) {
      const selection = activeEditor?.getSelection();
      if (selection) {
        (await $4Nb(accessor.get($uob)))?.focusInput();
        variablesService.attachContext("file", { uri: activeUri, range: selection }, ChatAgentLocation.EditingSession);
      }
    }
  }
};
var $z8b = class _$z8b extends $gJ {
  static {
    this.ID = "workbench.action.chat.attachContext";
  }
  static {
    this.c = $7m.or($7m.and(ChatContextKeys.location.isEqualTo(ChatAgentLocation.Panel)), $7m.and(ChatContextKeys.location.isEqualTo(ChatAgentLocation.Editor)), $7m.and(ChatContextKeys.location.isEqualTo(ChatAgentLocation.Notebook)), $7m.and(ChatContextKeys.location.isEqualTo(ChatAgentLocation.Terminal)));
  }
  constructor(desc = {
    id: _$z8b.ID,
    title: localize2(4688, "Attach Context"),
    icon: $6l.attach,
    category: $vNb,
    precondition: $7m.or(_$z8b.c, $7m.and(ChatContextKeys.location.isEqualTo(ChatAgentLocation.EditingSession))),
    keybinding: {
      when: ChatContextKeys.inChatInput,
      primary: 2048 | 90,
      weight: 100
      /* KeybindingWeight.EditorContrib */
    },
    menu: [
      {
        when: $7m.or($7m.and(ChatContextKeys.location.isEqualTo(ChatAgentLocation.EditingSession)), $7m.and($7m.or(ChatContextKeys.location.isEqualTo(ChatAgentLocation.Panel), ChatContextKeys.location.isEqualTo(ChatAgentLocation.EditingSession)), _$z8b.c)),
        id: $bJ.ChatInput,
        group: "navigation",
        order: 2
      },
      {
        when: $7m.and(ChatContextKeys.location.isEqualTo(ChatAgentLocation.Panel).negate(), _$z8b.c),
        id: $bJ.ChatExecute,
        group: "navigation",
        order: 1
      }
    ]
  }) {
    super(desc);
  }
  d(item) {
    if ("resource" in item) {
      return item.resource.toString();
    }
    return item.uri.toString() + (item.range.startLineNumber !== item.range.endLineNumber ? `:${item.range.startLineNumber}-${item.range.endLineNumber}` : `:${item.range.startLineNumber}`);
  }
  async f(widget, quickInputService, commandService, clipboardService, editorService, labelService, viewsService, chatEditingService, hostService, isInBackground, ...picks) {
    const toAttach = [];
    for (const pick of picks) {
      if (isISymbolQuickPickItem(pick) && pick.symbol) {
        toAttach.push({
          kind: "symbol",
          id: this.d(pick.symbol.location),
          value: pick.symbol.location,
          symbolKind: pick.symbol.kind,
          fullName: pick.label,
          name: pick.symbol.name,
          isDynamic: true
        });
      } else if (isIQuickPickItemWithResource(pick) && pick.resource) {
        if (/\.(png|jpg|jpeg|bmp|gif|tiff)$/i.test(pick.resource.path)) {
          toAttach.push({
            id: pick.resource.toString(),
            name: pick.label,
            fullName: pick.label,
            value: pick.resource,
            isDynamic: true,
            isImage: true
          });
        } else {
          if (chatEditingService) {
            chatEditingService.currentEditingSessionObs.get()?.addFileToWorkingSet(pick.resource);
          } else {
            toAttach.push({
              id: this.d({ resource: pick.resource }),
              value: pick.resource,
              name: pick.label,
              isFile: true,
              isDynamic: true
            });
          }
        }
      } else if (isIGotoSymbolQuickPickItem(pick) && pick.uri && pick.range) {
        toAttach.push({
          range: void 0,
          id: this.d({ uri: pick.uri, range: pick.range.decoration }),
          value: { uri: pick.uri, range: pick.range.decoration },
          fullName: pick.label,
          name: pick.symbolName,
          isDynamic: true
        });
      } else if (isIOpenEditorsQuickPickItem(pick)) {
        for (const editor of editorService.editors.filter((e) => e instanceof $8vb || e instanceof $fub || e instanceof $0Gb || e instanceof $trb)) {
          const uri = editor instanceof $fub ? editor.modified.resource : editor.resource;
          if (uri) {
            if (chatEditingService) {
              chatEditingService.currentEditingSessionObs.get()?.addFileToWorkingSet(uri);
            } else {
              toAttach.push({
                id: this.d({ resource: uri }),
                value: uri,
                name: labelService.getUriBasenameLabel(uri),
                isFile: true,
                isDynamic: true
              });
            }
          }
        }
      } else if (isISearchResultsQuickPickItem(pick)) {
        const searchView = viewsService.getViewWithId($PN);
        for (const result of searchView.model.searchResult.matches()) {
          if (chatEditingService) {
            chatEditingService.currentEditingSessionObs.get()?.addFileToWorkingSet(result.resource);
          } else {
            toAttach.push({
              id: this.d({ resource: result.resource }),
              value: result.resource,
              name: labelService.getUriBasenameLabel(result.resource),
              isFile: true,
              isDynamic: true
            });
          }
        }
      } else if (isRelatedFileQuickPickItem(pick)) {
        const chatSessionId = widget.viewModel?.sessionId;
        if (!chatSessionId || !chatEditingService) {
          continue;
        }
        const relatedFiles = await chatEditingService.getRelatedFiles(chatSessionId, widget.getInput(), CancellationToken.None);
        if (!relatedFiles) {
          continue;
        }
        const attachments = widget.attachmentModel.getAttachmentIDs();
        const itemsPromise = chatEditingService.getRelatedFiles(chatSessionId, widget.getInput(), CancellationToken.None).then((files) => (files ?? []).reduce((acc, cur) => {
          acc.push({ type: "separator", label: cur.group });
          for (const file of cur.files) {
            acc.push({
              type: "item",
              label: labelService.getUriBasenameLabel(file.uri),
              description: labelService.getUriLabel($uh(file.uri), { relative: true }),
              value: file.uri,
              disabled: attachments.has(this.d({ resource: file.uri })),
              picked: true
            });
          }
          return acc;
        }, []));
        const selectedFiles = await quickInputService.pick(itemsPromise, { placeHolder: localize(4670, null), canPickMany: true });
        for (const file of selectedFiles ?? []) {
          chatEditingService?.currentEditingSessionObs.get()?.addFileToWorkingSet(file.value);
        }
      } else if (isScreenshotQuickPickItem(pick)) {
        const blob = await hostService.getScreenshot();
        if (blob) {
          toAttach.push($uNb(blob));
        }
      } else {
        const attachmentPick = pick;
        if (attachmentPick.kind === "command") {
          const selection = await commandService.executeCommand(attachmentPick.command.id, ...attachmentPick.command.arguments ?? []);
          if (!selection) {
            continue;
          }
          toAttach.push({
            ...attachmentPick,
            isDynamic: attachmentPick.isDynamic,
            value: attachmentPick.value,
            name: `${typeof attachmentPick.value === "string" && attachmentPick.value.startsWith("#") ? attachmentPick.value.slice(1) : ""}${selection}`,
            // Apply the original icon with the new name
            fullName: selection
          });
        } else if (attachmentPick.kind === "tool") {
          toAttach.push({
            id: attachmentPick.id,
            name: attachmentPick.label,
            fullName: attachmentPick.label,
            value: void 0,
            icon: attachmentPick.icon,
            isTool: true
          });
        } else if (attachmentPick.kind === "image") {
          const fileBuffer = await clipboardService.readImage();
          toAttach.push({
            id: await $t8b(fileBuffer),
            name: localize(4671, null),
            fullName: localize(4672, null),
            value: fileBuffer,
            isDynamic: true,
            isImage: true
          });
        } else if (attachmentPick.kind === "variable") {
          toAttach.push({
            range: void 0,
            id: pick.id ?? "",
            value: void 0,
            fullName: pick.label,
            name: attachmentPick.variable.name,
            icon: attachmentPick.variable.icon
          });
        }
      }
    }
    widget.attachmentModel.addContext(...toAttach);
    if (!isInBackground) {
      widget.focusInput();
    }
  }
  async run(accessor, ...args2) {
    const quickInputService = accessor.get($1M);
    const chatAgentService = accessor.get($ZO);
    const chatVariablesService = accessor.get($kO);
    const commandService = accessor.get($sn);
    const widgetService = accessor.get($2Nb);
    const languageModelToolsService = accessor.get($mO);
    const quickChatService = accessor.get($6Nb);
    const clipboardService = accessor.get($30);
    const editorService = accessor.get($mJ);
    const labelService = accessor.get($ZI);
    const contextKeyService = accessor.get($on);
    const viewsService = accessor.get($uob);
    const hostService = accessor.get($S4);
    const extensionService = accessor.get($wN);
    const context = args2[0];
    const widget = context?.widget ?? widgetService.lastFocusedWidget;
    if (!widget) {
      return;
    }
    const chatEditingService = widget.location === ChatAgentLocation.EditingSession ? accessor.get($$O) : void 0;
    const usedAgent = widget.parsedInput.parts.find((p) => p instanceof $BO);
    const slowSupported = usedAgent ? usedAgent.agent.metadata.supportsSlowVariables : true;
    const quickPickItems = [];
    if (!context || !context.showFilesOnly) {
      for (const variable of chatVariablesService.getVariables(widget.location)) {
        if (variable.fullName && (!variable.isSlow || slowSupported)) {
          quickPickItems.push({
            kind: "variable",
            variable,
            label: variable.fullName,
            id: variable.id,
            iconClass: variable.icon ? ThemeIcon.asClassName(variable.icon) : void 0
          });
        }
      }
      if (extensionService.extensions.some((ext) => $zN(ext, "chatReferenceBinaryData"))) {
        const imageData = await clipboardService.readImage();
        if ($u8b(imageData)) {
          quickPickItems.push({
            kind: "image",
            id: await $t8b(imageData),
            label: localize(4673, null),
            iconClass: ThemeIcon.asClassName($6l.fileMedia)
          });
        }
        quickPickItems.push({
          kind: "screenshot",
          id: $tNb,
          icon: ThemeIcon.fromId($6l.deviceCamera.id),
          iconClass: ThemeIcon.asClassName($6l.deviceCamera),
          label: $q ? localize(4674, null) : localize(4675, null)
        });
      }
      if (widget.viewModel?.sessionId) {
        const agentPart = widget.parsedInput.parts.find((part) => part instanceof $BO);
        if (agentPart) {
          const completions = await chatAgentService.getAgentCompletionItems(agentPart.agent.id, "", CancellationToken.None);
          for (const variable of completions) {
            if (variable.fullName && variable.command) {
              quickPickItems.push({
                kind: "command",
                label: variable.fullName,
                id: variable.id,
                command: variable.command,
                icon: variable.icon,
                iconClass: variable.icon ? ThemeIcon.asClassName(variable.icon) : void 0,
                value: variable.value,
                isDynamic: true,
                name: variable.name
              });
            } else {
            }
          }
        }
      }
      for (const tool of languageModelToolsService.getTools()) {
        if (tool.canBeReferencedInPrompt) {
          const item = {
            kind: "tool",
            label: tool.displayName ?? "",
            id: tool.id,
            icon: ThemeIcon.isThemeIcon(tool.icon) ? tool.icon : void 0
            // TODO need to support icon path?
          };
          if (ThemeIcon.isThemeIcon(tool.icon)) {
            item.iconClass = ThemeIcon.asClassName(tool.icon);
          } else if (tool.icon) {
            item.iconPath = tool.icon;
          }
          quickPickItems.push(item);
        }
      }
      quickPickItems.push({
        kind: "quickaccess",
        label: localize(4676, null),
        iconClass: ThemeIcon.asClassName($6l.symbolField),
        prefix: $$Nb.PREFIX,
        id: "symbol"
      });
      if (widget.location === ChatAgentLocation.Notebook) {
        quickPickItems.push({
          kind: "command",
          id: "chatContext.notebook.kernelVariable",
          isDynamic: true,
          icon: ThemeIcon.fromId($6l.serverEnvironment.id),
          iconClass: ThemeIcon.asClassName($6l.serverEnvironment),
          value: "kernelVariable",
          label: localize(4677, null),
          command: {
            id: "notebook.chat.selectAndInsertKernelVariable",
            title: localize(4678, null),
            arguments: [{ widget, range: void 0 }]
          }
        });
      }
    } else if (context.showFilesOnly) {
      if (chatEditingService?.hasRelatedFilesProviders() && (widget.getInput() || chatEditingService.currentEditingSessionObs.get()?.workingSet.size)) {
        quickPickItems.push({
          kind: "related-files",
          id: "related-files",
          label: localize(4679, null),
          iconClass: ThemeIcon.asClassName($6l.sparkle)
        });
      }
      if (editorService.editors.filter((e) => e instanceof $8vb || e instanceof $fub || e instanceof $0Gb).length > 0) {
        quickPickItems.push({
          kind: "open-editors",
          id: "open-editors",
          label: localize(4680, null),
          iconClass: ThemeIcon.asClassName($6l.files)
        });
      }
      if ($eRb.HasSearchResults.getValue(contextKeyService)) {
        quickPickItems.push({
          kind: "search-results",
          id: "search-results",
          label: localize(4681, null),
          iconClass: ThemeIcon.asClassName($6l.search)
        });
      }
    }
    function extractTextFromIconLabel(label3) {
      if (!label3) {
        return "";
      }
      const match = label3.match(/\$\([^\)]+\)\s*(.+)/);
      return match ? match[1] : label3;
    }
    this.g(quickInputService, commandService, widget, quickChatService, quickPickItems.sort(function(a, b) {
      const first = extractTextFromIconLabel(a.label).toUpperCase();
      const second = extractTextFromIconLabel(b.label).toUpperCase();
      return $Tf(first, second);
    }), clipboardService, editorService, labelService, viewsService, chatEditingService, hostService, "", context?.placeholder);
  }
  g(quickInputService, commandService, widget, quickChatService, quickPickItems, clipboardService, editorService, labelService, viewsService, chatEditingService, hostService, query = "", placeholder) {
    const providerOptions = {
      handleAccept: (item, isBackgroundAccept) => {
        if ("prefix" in item) {
          this.g(quickInputService, commandService, widget, quickChatService, quickPickItems, clipboardService, editorService, labelService, viewsService, chatEditingService, hostService, item.prefix, placeholder);
        } else {
          if (!clipboardService) {
            return;
          }
          this.f(widget, quickInputService, commandService, clipboardService, editorService, labelService, viewsService, chatEditingService, hostService, isBackgroundAccept, item);
          if ($pNb(widget)) {
            quickChatService.open();
          }
        }
      },
      additionPicks: quickPickItems,
      filter: (item) => {
        const attachedContext = widget.attachmentModel.getAttachmentIDs();
        if (chatEditingService) {
          for (const [file, state] of chatEditingService.currentEditingSessionObs.get()?.workingSet.entries() ?? []) {
            if (state.state !== 6) {
              attachedContext.add(this.d({ resource: file }));
            }
          }
        }
        if (isIOpenEditorsQuickPickItem(item)) {
          for (const editor of editorService.editors.filter((e) => e instanceof $8vb || e instanceof $fub || e instanceof $0Gb)) {
            if (editor.resource && !attachedContext.has(this.d({ resource: editor.resource }))) {
              return true;
            }
          }
          return false;
        }
        if ("kind" in item && item.kind === "image") {
          return !attachedContext.has(item.id);
        }
        if ("symbol" in item && item.symbol) {
          return !attachedContext.has(this.d(item.symbol.location));
        }
        if (item && typeof item === "object" && "resource" in item && URI.isUri(item.resource)) {
          return [Schemas.file, Schemas.vscodeRemote, Schemas.untitled].includes(item.resource.scheme) && !attachedContext.has(this.d({ resource: item.resource }));
        }
        if (item && typeof item === "object" && "uri" in item && item.uri && item.range) {
          return !attachedContext.has(this.d({ uri: item.uri, range: item.range.decoration }));
        }
        if (!("command" in item) && item.id) {
          return !attachedContext.has(item.id);
        }
        return true;
      }
    };
    quickInputService.quickAccess.show(query, {
      enabledProviderPrefixes: [
        $g6b.PREFIX,
        $$Nb.PREFIX,
        $b6b.PREFIX
      ],
      placeholder: placeholder ?? localize(4682, null),
      providerOptions
    });
  }
};
$hJ(class AttachFilesAction extends $z8b {
  constructor() {
    super({
      id: "workbench.action.chat.editing.attachFiles",
      title: localize2(4689, "Add Files to Working Set"),
      f1: false,
      category: $vNb,
      precondition: ChatContextKeys.location.isEqualTo(ChatAgentLocation.EditingSession)
    });
  }
  async run(accessor, ...args2) {
    const context = args2[0];
    const attachFilesContext = { ...context, showFilesOnly: true, placeholder: localize(4683, null) };
    return super.run(accessor, attachFilesContext);
  }
});

// out-build/vs/workbench/contrib/chat/browser/actions/chatCopyActions.js
function $A8b() {
  $hJ(class CopyAllAction extends $gJ {
    constructor() {
      super({
        id: "workbench.action.chat.copyAll",
        title: localize2(4690, "Copy All"),
        f1: false,
        category: $vNb,
        menu: {
          id: $bJ.ChatContext,
          when: ChatContextKeys.responseIsFiltered.toNegated(),
          group: "copy"
        }
      });
    }
    run(accessor, ...args2) {
      const clipboardService = accessor.get($30);
      const chatWidgetService = accessor.get($2Nb);
      const widget = chatWidgetService.lastFocusedWidget;
      if (widget) {
        const viewModel = widget.viewModel;
        const sessionAsText = viewModel?.getItems().filter((item) => $_rb(item) || $asb(item) && !item.errorDetails?.responseIsFiltered).map((item) => $yNb(item)).join("\n\n");
        if (sessionAsText) {
          clipboardService.writeText(sessionAsText);
        }
      }
    }
  });
  $hJ(class CopyItemAction extends $gJ {
    constructor() {
      super({
        id: "workbench.action.chat.copyItem",
        title: localize2(4691, "Copy"),
        f1: false,
        category: $vNb,
        menu: {
          id: $bJ.ChatContext,
          when: ChatContextKeys.responseIsFiltered.toNegated(),
          group: "copy"
        }
      });
    }
    run(accessor, ...args2) {
      const item = args2[0];
      if (!$_rb(item) && !$asb(item)) {
        return;
      }
      const clipboardService = accessor.get($30);
      const text2 = $yNb(item, false);
      clipboardService.writeText(text2);
    }
  });
}

// out-build/vs/workbench/contrib/chat/browser/actions/chatDeveloperActions.js
function $B8b() {
  $hJ(LogChatInputHistoryAction);
}
var LogChatInputHistoryAction = class _LogChatInputHistoryAction extends $gJ {
  static {
    this.ID = "workbench.action.chat.logInputHistory";
  }
  constructor() {
    super({
      id: _LogChatInputHistoryAction.ID,
      title: localize2(4692, "Log Chat Input History"),
      icon: $6l.attach,
      category: $qn.Developer,
      f1: true
    });
  }
  async run(accessor, ...args2) {
    const chatWidgetService = accessor.get($2Nb);
    chatWidgetService.lastFocusedWidget?.logInputHistory();
  }
};

// out-build/vs/workbench/contrib/chat/browser/actions/chatFileTreeActions.js
function $C8b() {
  $hJ(class NextFileTreeAction extends $gJ {
    constructor() {
      super({
        id: "workbench.action.chat.nextFileTree",
        title: localize2(4705, "Next File Tree"),
        keybinding: {
          primary: 2048 | 67,
          weight: 200,
          when: ChatContextKeys.inChatSession
        },
        precondition: ChatContextKeys.enabled,
        f1: true,
        category: $vNb
      });
    }
    run(accessor, ...args2) {
      navigateTrees(accessor, false);
    }
  });
  $hJ(class PreviousFileTreeAction extends $gJ {
    constructor() {
      super({
        id: "workbench.action.chat.previousFileTree",
        title: localize2(4706, "Previous File Tree"),
        keybinding: {
          primary: 2048 | 1024 | 67,
          weight: 200,
          when: ChatContextKeys.inChatSession
        },
        precondition: ChatContextKeys.enabled,
        f1: true,
        category: $vNb
      });
    }
    run(accessor, ...args2) {
      navigateTrees(accessor, true);
    }
  });
}
function navigateTrees(accessor, reverse) {
  const chatWidgetService = accessor.get($2Nb);
  const widget = chatWidgetService.lastFocusedWidget;
  if (!widget) {
    return;
  }
  const focused = !widget.inputEditor.hasWidgetFocus() && widget.getFocus();
  const focusedResponse = $asb(focused) ? focused : void 0;
  const currentResponse = focusedResponse ?? widget.viewModel?.getItems().reverse().find((item) => $asb(item));
  if (!currentResponse) {
    return;
  }
  widget.reveal(currentResponse);
  const responseFileTrees = widget.getFileTreeInfosForResponse(currentResponse);
  const lastFocusedFileTree = widget.getLastFocusedFileTreeForResponse(currentResponse);
  const focusIdx = lastFocusedFileTree ? (lastFocusedFileTree.treeIndex + (reverse ? -1 : 1) + responseFileTrees.length) % responseFileTrees.length : reverse ? responseFileTrees.length - 1 : 0;
  responseFileTrees[focusIdx]?.focus();
}

// out-build/vs/workbench/contrib/chat/browser/actions/chatImportExport.js
var defaultFileName = "chat.json";
var filters = [{ name: localize(4707, null), extensions: ["json"] }];
function $D8b() {
  $hJ(class ExportChatAction extends $gJ {
    constructor() {
      super({
        id: "workbench.action.chat.export",
        category: $vNb,
        title: localize2(4708, "Export Chat..."),
        precondition: ChatContextKeys.enabled,
        f1: true
      });
    }
    async run(accessor, ...args2) {
      const widgetService = accessor.get($2Nb);
      const fileDialogService = accessor.get($1v);
      const fileService = accessor.get($km);
      const chatService = accessor.get($qO);
      const widget = widgetService.lastFocusedWidget;
      if (!widget || !widget.viewModel) {
        return;
      }
      const defaultUri = $vh(await fileDialogService.defaultFilePath(), defaultFileName);
      const result = await fileDialogService.showSaveDialog({
        defaultUri,
        filters
      });
      if (!result) {
        return;
      }
      const model = chatService.getSession(widget.viewModel.sessionId);
      if (!model) {
        return;
      }
      const content = $Ci.fromString(JSON.stringify(model.toExport(), void 0, 2));
      await fileService.writeFile(result, content);
    }
  });
  $hJ(class ImportChatAction extends $gJ {
    constructor() {
      super({
        id: "workbench.action.chat.import",
        title: localize2(4709, "Import Chat..."),
        category: $vNb,
        precondition: ChatContextKeys.enabled,
        f1: true
      });
    }
    async run(accessor, ...args2) {
      const fileDialogService = accessor.get($1v);
      const fileService = accessor.get($km);
      const editorService = accessor.get($mJ);
      const defaultUri = $vh(await fileDialogService.defaultFilePath(), defaultFileName);
      const result = await fileDialogService.showOpenDialog({
        defaultUri,
        canSelectFiles: true,
        filters
      });
      if (!result) {
        return;
      }
      const content = await fileService.readFile(result[0]);
      try {
        const data = JSON.parse(content.value.toString());
        if (!$QO(data)) {
          throw new Error("Invalid chat session data");
        }
        const options3 = { target: { data }, pinned: true };
        await editorService.openEditor({ resource: $Zzb.getNewEditorUri(), options: options3 });
      } catch (err) {
        throw err;
      }
    }
  });
}

// out-build/vs/workbench/contrib/chat/browser/chatEditor.js
var $sNb = class $sNb2 extends $5tb {
  get scopedContextKeyService() {
    return this.b;
  }
  constructor(group2, telemetryService, themeService, g, j, m) {
    super($Zzb.EditorID, group2, telemetryService, themeService, j);
    this.g = g;
    this.j = j;
    this.m = m;
  }
  async r() {
    if (this.input) {
      return this.g.invokeFunction($3zb, this.input);
    }
  }
  Y(parent) {
    this.b = this.B(this.m.createScoped(parent));
    const scopedInstantiationService = this.B(this.g.createChild(new $Ok([$on, this.scopedContextKeyService])));
    this.a = this.B(scopedInstantiationService.createInstance($qNb, ChatAgentLocation.Panel, void 0, {
      supportsFileReferences: true,
      enableImplicitContext: true
    }, {
      listForeground: $Lo,
      listBackground: $Ko,
      overlayBackground: $Cmb,
      inputEditorBackground: $xq,
      resultEditorBackground: $Ko
    }));
    this.B(this.a.onDidClear(() => this.r()));
    this.a.render(parent);
    this.a.setVisible(true);
  }
  Z(visible) {
    super.Z(visible);
    this.a?.setVisible(visible);
  }
  focus() {
    super.focus();
    this.a?.focusInput();
  }
  clearInput() {
    this.I();
    super.clearInput();
  }
  async setInput(input, options3, context, token) {
    super.setInput(input, options3, context, token);
    const editorModel = await input.resolve();
    if (!editorModel) {
      throw new Error(`Failed to get model for chat editor. id: ${input.sessionId}`);
    }
    if (!this.a) {
      throw new Error("ChatEditor lifecycle issue: no editor widget");
    }
    this.$(editorModel.model, options3?.viewState ?? input.options.viewState);
  }
  $(model, viewState) {
    this.c = new $Slb("interactive-session-editor-" + $XO, this.j);
    this.f = viewState ?? this.c.getMemento(
      1,
      1
      /* StorageTarget.MACHINE */
    );
    this.a.setModel(model, { ...this.f });
  }
  I() {
    this.a?.saveState();
    if (this.c && this.f) {
      const widgetViewState = this.a.getViewState();
      this.f.inputValue = widgetViewState.inputValue;
      this.c.saveMemento();
    }
  }
  getViewState() {
    return { ...this.f };
  }
  layout(dimension, position) {
    if (this.a) {
      this.a.layout(dimension.height, dimension.width);
    }
  }
};
$sNb = __decorate([
  __param(1, $zv),
  __param(2, $gs),
  __param(3, $Pk),
  __param(4, $jv),
  __param(5, $on)
], $sNb);

// out-build/vs/workbench/contrib/chat/browser/actions/chatMoveActions.js
var MoveToNewLocation;
(function(MoveToNewLocation2) {
  MoveToNewLocation2["Editor"] = "Editor";
  MoveToNewLocation2["Window"] = "Window";
})(MoveToNewLocation || (MoveToNewLocation = {}));
function $E8b() {
  $hJ(class GlobalMoveToEditorAction extends $gJ {
    constructor() {
      super({
        id: `workbench.action.chat.openInEditor`,
        title: localize2(4710, "Open Chat in Editor"),
        category: $vNb,
        precondition: ChatContextKeys.enabled,
        f1: true,
        menu: {
          id: $bJ.ViewTitle,
          when: $7m.equals("view", $9Nb),
          order: 0,
          group: "1_open"
        }
      });
    }
    async run(accessor, ...args2) {
      const context = args2[0];
      executeMoveToAction(accessor, MoveToNewLocation.Editor, $lzb(context) ? context.sessionId : void 0);
    }
  });
  $hJ(class GlobalMoveToNewWindowAction extends $gJ {
    constructor() {
      super({
        id: `workbench.action.chat.openInNewWindow`,
        title: localize2(4711, "Open Chat in New Window"),
        category: $vNb,
        precondition: ChatContextKeys.enabled,
        f1: true,
        menu: {
          id: $bJ.ViewTitle,
          when: $7m.equals("view", $9Nb),
          order: 0,
          group: "1_open"
        }
      });
    }
    async run(accessor, ...args2) {
      const context = args2[0];
      executeMoveToAction(accessor, MoveToNewLocation.Window, $lzb(context) ? context.sessionId : void 0);
    }
  });
  $hJ(class GlobalMoveToSidebarAction extends $gJ {
    constructor() {
      super({
        id: `workbench.action.chat.openInSidebar`,
        title: localize2(4712, "Open Chat in Side Bar"),
        category: $vNb,
        precondition: ChatContextKeys.enabled,
        f1: true,
        menu: [{
          id: $bJ.EditorTitle,
          order: 0,
          when: $Dpb.isEqualTo($Zzb.EditorID)
        }]
      });
    }
    async run(accessor, ...args2) {
      return moveToSidebar(accessor);
    }
  });
}
async function executeMoveToAction(accessor, moveTo, _sessionId) {
  const widgetService = accessor.get($2Nb);
  const editorService = accessor.get($mJ);
  const widget = (_sessionId ? widgetService.getWidgetBySessionId(_sessionId) : void 0) ?? widgetService.lastFocusedWidget;
  if (!widget || !("viewId" in widget.viewContext)) {
    await editorService.openEditor({ resource: $Zzb.getNewEditorUri(), options: { pinned: true } }, moveTo === MoveToNewLocation.Window ? $pJ : $nJ);
    return;
  }
  const viewModel = widget.viewModel;
  if (!viewModel) {
    return;
  }
  const sessionId = viewModel.sessionId;
  const viewState = widget.getViewState();
  widget.clear();
  const options3 = { target: { sessionId }, pinned: true, viewState };
  await editorService.openEditor({ resource: $Zzb.getNewEditorUri(), options: options3 }, moveTo === MoveToNewLocation.Window ? $pJ : $nJ);
}
async function moveToSidebar(accessor) {
  const viewsService = accessor.get($uob);
  const editorService = accessor.get($mJ);
  const editorGroupService = accessor.get($iJ);
  const chatEditor = editorService.activeEditorPane;
  const chatEditorInput = chatEditor?.input;
  let view;
  if (chatEditor instanceof $sNb && chatEditorInput instanceof $Zzb && chatEditorInput.sessionId) {
    await editorService.closeEditor({ editor: chatEditor.input, groupId: editorGroupService.activeGroup.id });
    view = await viewsService.openView($9Nb);
    view.loadSession(chatEditorInput.sessionId, chatEditor.getViewState());
  } else {
    view = await viewsService.openView($9Nb);
  }
  view.focus();
}

// out-build/vs/platform/accessibilitySignal/browser/progressAccessibilitySignalScheduler.js
var PROGRESS_SIGNAL_LOOP_DELAY = 5e3;
var $F8b = class $F8b2 extends $3c {
  constructor(msDelayTime, msLoopTime, c) {
    super();
    this.c = c;
    this.a = new $8h(() => {
      this.b = this.c.playSignalLoop($N9.progress, msLoopTime ?? PROGRESS_SIGNAL_LOOP_DELAY);
    }, msDelayTime);
    this.a.schedule();
  }
  dispose() {
    super.dispose();
    this.b?.dispose();
    this.a.dispose();
  }
};
$F8b = __decorate([
  __param(2, $I9)
], $F8b);

// out-build/vs/workbench/contrib/chat/browser/chatAccessibilityService.js
var CHAT_RESPONSE_PENDING_ALLOWANCE_MS = 4e3;
var $G8b = class $G8b2 extends $3c {
  constructor(c, f, g) {
    super();
    this.c = c;
    this.f = f;
    this.g = g;
    this.a = this.B(new $_c());
    this.b = 0;
  }
  acceptRequest() {
    this.b++;
    this.c.playSignal($N9.chatRequestSent, { allowManyInParallel: true });
    this.a.set(this.b, this.f.createInstance($F8b, CHAT_RESPONSE_PENDING_ALLOWANCE_MS, void 0));
    return this.b;
  }
  acceptResponse(response, requestId, isVoiceInput) {
    this.a.deleteAndDispose(requestId);
    const isPanelChat = typeof response !== "string";
    const responseContent = typeof response === "string" ? response : response?.response.toString();
    this.c.playSignal($N9.chatResponseReceived, { allowManyInParallel: true });
    if (!response || !responseContent) {
      return;
    }
    const errorDetails = isPanelChat && response.errorDetails ? ` ${response.errorDetails.message}` : "";
    const plainTextResponse = $F1(new $bm(responseContent));
    if (!isVoiceInput || this.g.getValue(
      "accessibility.voice.autoSynthesize"
      /* AccessibilityVoiceSettingId.AutoSynthesize */
    ) !== "on") {
      $_Z(plainTextResponse + errorDetails);
    }
  }
};
$G8b = __decorate([
  __param(0, $I9),
  __param(1, $Pk),
  __param(2, $kl)
], $G8b);

// out-build/vs/workbench/contrib/chat/browser/chatEditing/chatEditingSession.js
var STORAGE_CONTENTS_FOLDER = "contents";
var STORAGE_STATE_FILE = "state.json";
var ThrottledSequencer = class extends $Qh {
  constructor(d, f) {
    super();
    this.d = d;
    this.f = f;
    this.b = 0;
  }
  queue(promiseTask) {
    this.b += 1;
    const noDelay = this.b * this.d > this.f;
    return super.queue(async () => {
      try {
        const p1 = promiseTask();
        const p2 = noDelay ? Promise.resolve(void 0) : $Wh(this.d);
        const [result] = await Promise.all([p1, p2]);
        return result;
      } finally {
        this.b -= 1;
      }
    });
  }
};
var $mFb = class $mFb2 extends $3c {
  get entries() {
    this.X();
    return this.j;
  }
  get workingSet() {
    this.X();
    const result = new $Ec(this.n);
    for (const entry of this.j.get()) {
      result.set(entry.modifiedURI, { state: entry.state.get() });
    }
    return result;
  }
  get state() {
    return this.a;
  }
  get onDidChange() {
    this.X();
    return this.w.event;
  }
  get onDidDispose() {
    this.X();
    return this.y.event;
  }
  get isVisible() {
    this.X();
    return Boolean(this.u && this.u.isVisible());
  }
  constructor(chatSessionId, z, C, D, F, G, _bulkEditService, H, I, J, L, M, N, O, P) {
    super();
    this.chatSessionId = chatSessionId;
    this.z = z;
    this.C = C;
    this.D = D;
    this.F = F;
    this.G = G;
    this._bulkEditService = _bulkEditService;
    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.a = $he(
      this,
      0
      /* ChatEditingSessionState.Initial */
    );
    this.b = $he(this, []);
    this.c = $he(this, 0);
    this.f = new $Ec();
    this.h = new $Fc();
    this.j = $he(this, []);
    this.m = new ThrottledSequencer(15, 1e3);
    this.n = new $Ec();
    this.t = new $Fc();
    this.canUndo = $2d((r2) => {
      if (this.state.read(r2) !== 2) {
        return false;
      }
      const linearHistoryIndex = this.c.read(r2);
      return linearHistoryIndex > 0;
    });
    this.canRedo = $2d((r2) => {
      if (this.state.read(r2) !== 2) {
        return false;
      }
      const linearHistory = this.b.read(r2);
      const linearHistoryIndex = this.c.read(r2);
      return linearHistoryIndex < linearHistory.length;
    });
    this.hiddenRequestIds = $2d((r2) => {
      const linearHistory = this.b.read(r2);
      const linearHistoryIndex = this.c.read(r2);
      return linearHistory.slice(linearHistoryIndex).map((s) => s.requestId).filter((r3) => !!r3);
    });
    this.w = new $ze();
    this.y = new $ze();
  }
  async init() {
    const restoredSessionState = await this.C.createInstance(ChatEditingSessionStorage, this.chatSessionId).restoreState();
    if (restoredSessionState) {
      for (const uri of restoredSessionState.filesToSkipCreating) {
        this.h.add(uri);
      }
      for (const [uri, content] of restoredSessionState.initialFileContents) {
        this.f.set(uri, content);
      }
      this.U = restoredSessionState.pendingSnapshot;
      await this.W(restoredSessionState.recentSnapshot);
      this.c.set(restoredSessionState.linearHistoryIndex, void 0);
      this.b.set(restoredSessionState.linearHistory, void 0);
      this.a.set(2, void 0);
    }
    this.Q();
    this.B(this.I.onDidVisibleEditorsChange(() => {
      this.Q();
    }));
    this.B($td((reader) => {
      const entries2 = this.entries.read(reader);
      entries2.forEach((entry) => {
        entry.state.read(reader);
      });
      this.w.fire(
        0
        /* ChatEditingSessionChangeType.WorkingSet */
      );
    }));
  }
  getEntry(uri) {
    return this.j.get().find((e) => $oh(e.modifiedURI, uri));
  }
  readEntry(uri, reader) {
    return this.j.read(reader).find((e) => $oh(e.modifiedURI, uri));
  }
  storeState() {
    const storage = this.C.createInstance(ChatEditingSessionStorage, this.chatSessionId);
    const state = {
      filesToSkipCreating: [...this.h],
      initialFileContents: this.f,
      pendingSnapshot: this.U,
      recentSnapshot: this.S(void 0),
      linearHistoryIndex: this.c.get(),
      linearHistory: this.b.get()
    };
    return storage.storeState(state);
  }
  Q(e) {
    const existingTransientEntries = new $Fc();
    for (const file of this.n.keys()) {
      if (this.n.get(file)?.state === 3) {
        existingTransientEntries.add(file);
      }
    }
    const activeEditors = new $Fc();
    this.H.groups.forEach((group2) => {
      if (!group2.activeEditorPane) {
        return;
      }
      let uri;
      if ($vrb(group2.activeEditorPane.input)) {
        uri = group2.activeEditorPane.input.resource;
      } else {
        let activeEditorControl = group2.activeEditorPane.getControl();
        if ($Q5(activeEditorControl)) {
          activeEditorControl = activeEditorControl.getOriginalEditor().hasTextFocus() ? activeEditorControl.getOriginalEditor() : activeEditorControl.getModifiedEditor();
        }
        if ($P5(activeEditorControl) && activeEditorControl.hasModel()) {
          uri = activeEditorControl.getModel().uri;
        }
      }
      if (!uri) {
        return;
      }
      if (existingTransientEntries.has(uri)) {
        existingTransientEntries.delete(uri);
      } else if (!this.n.has(uri) && !this.t.has(uri)) {
        activeEditors.add(uri);
      }
    });
    let didChange = false;
    for (const entry of existingTransientEntries) {
      didChange = this.n.delete(entry) || didChange;
    }
    for (const entry of activeEditors) {
      this.n.set(entry, { state: 3, description: localize(4866, null) });
      didChange = true;
    }
    if (didChange) {
      this.w.fire(
        0
        /* ChatEditingSessionChangeType.WorkingSet */
      );
    }
  }
  R(requestId) {
    return this.b.get().find((s) => s.requestId === requestId);
  }
  createSnapshot(requestId) {
    const snapshot = this.S(requestId);
    if (requestId) {
      for (const [uri, data] of this.n) {
        if (data.state !== 6) {
          this.n.set(uri, {
            state: 5
            /* WorkingSetEntryState.Sent */
          });
        }
      }
      const linearHistory = this.b.get();
      const linearHistoryIndex = this.c.get();
      const newLinearHistory = linearHistory.slice(0, linearHistoryIndex);
      newLinearHistory.push(snapshot);
      $ce((tx) => {
        this.b.set(newLinearHistory, tx);
        this.c.set(newLinearHistory.length, tx);
      });
    } else {
      this.U = snapshot;
    }
  }
  S(requestId) {
    const workingSet = new $Ec();
    for (const [file, state] of this.n) {
      workingSet.set(file, state);
    }
    const entries2 = new $Ec();
    for (const entry of this.j.get()) {
      entries2.set(entry.modifiedURI, entry.createSnapshot(requestId));
    }
    return {
      requestId,
      workingSet,
      entries: entries2
    };
  }
  async getSnapshotModel(requestId, snapshotUri) {
    const entries2 = this.R(requestId)?.entries;
    if (!entries2) {
      return null;
    }
    const snapshotEntry = [...entries2.values()].find((e) => $oh(e.snapshotUri, snapshotUri));
    if (!snapshotEntry) {
      return null;
    }
    return this.D.createModel(snapshotEntry.current, this.F.createById(snapshotEntry.languageId), snapshotUri, false);
  }
  getSnapshot(requestId, uri) {
    const snapshot = this.R(requestId);
    const snapshotEntries = snapshot?.entries;
    return snapshotEntries?.get(uri);
  }
  getSnapshotUri(requestId, uri) {
    return this.getSnapshot(requestId, uri)?.snapshotUri;
  }
  async restoreSnapshot(requestId) {
    if (requestId !== void 0) {
      const snapshot = this.R(requestId);
      if (snapshot) {
        if (!this.U) {
          this.createSnapshot(void 0);
        }
        await this.W(snapshot);
      }
    } else {
      if (!this.U) {
        return;
      }
      const snapshot = this.U;
      this.U = void 0;
      await this.W(snapshot);
    }
  }
  async W(snapshot) {
    this.n = new $Ec();
    snapshot.workingSet.forEach((state, uri) => this.n.set(uri, state));
    for (const entry of this.j.get()) {
      const snapshotEntry = snapshot.entries.get(entry.modifiedURI);
      if (!snapshotEntry) {
        entry.resetToInitialValue();
        entry.dispose();
      }
    }
    const entriesArr = [];
    for (const snapshotEntry of snapshot.entries.values()) {
      const entry = await this.cb(snapshotEntry.resource, snapshotEntry.telemetryInfo);
      entry.restoreFromSnapshot(snapshotEntry);
      entriesArr.push(entry);
    }
    this.j.set(entriesArr, void 0);
  }
  remove(reason, ...uris) {
    this.X();
    let didRemoveUris = false;
    for (const uri of uris) {
      const entry = this.j.get().find((e) => $oh(e.modifiedURI, uri));
      if (entry) {
        entry.dispose();
        const newEntries = this.j.get().filter((e) => !$oh(e.modifiedURI, uri));
        this.j.set(newEntries, void 0);
        didRemoveUris = true;
      }
      const state = this.n.get(uri);
      if (state !== void 0) {
        didRemoveUris = this.n.delete(uri) || didRemoveUris;
        if (reason === 0 && (state.state === 3 || state.state === 6)) {
          this.t.add(uri);
        }
      }
    }
    if (!didRemoveUris) {
      return;
    }
    this.w.fire(
      0
      /* ChatEditingSessionChangeType.WorkingSet */
    );
  }
  X() {
    if (this.a.get() === 3) {
      throw new $vb(`Cannot access a disposed editing session`);
    }
  }
  async accept(...uris) {
    this.X();
    if (uris.length === 0) {
      await Promise.all(this.j.get().map((entry) => entry.accept(void 0)));
    }
    for (const uri of uris) {
      const entry = this.j.get().find((e) => $oh(e.modifiedURI, uri));
      if (entry) {
        await entry.accept(void 0);
      }
    }
    this.w.fire(
      1
      /* ChatEditingSessionChangeType.Other */
    );
  }
  async reject(...uris) {
    this.X();
    if (uris.length === 0) {
      await Promise.all(this.j.get().map((entry) => entry.reject(void 0)));
    }
    for (const uri of uris) {
      const entry = this.j.get().find((e) => $oh(e.modifiedURI, uri));
      if (entry) {
        await entry.reject(void 0);
      }
    }
    this.w.fire(
      1
      /* ChatEditingSessionChangeType.Other */
    );
  }
  async show() {
    this.X();
    if (this.u) {
      if (this.u.isVisible()) {
        return;
      } else if (this.u.input) {
        await this.H.activeGroup.openEditor(this.u.input, { pinned: true, activation: EditorActivation.ACTIVATE });
        return;
      }
    }
    const input = $_Eb.fromResourceMultiDiffEditorInput({
      multiDiffSource: $kFb.getMultiDiffSourceUri(),
      label: localize(4867, null)
    }, this.C);
    this.u = await this.H.activeGroup.openEditor(input, { pinned: true, activation: EditorActivation.ACTIVATE });
  }
  async stop(clearState = false) {
    if (!this.Y) {
      this.Y = this._performStop();
    }
    await this.Y;
    if (clearState) {
      await this.C.createInstance(ChatEditingSessionStorage, this.chatSessionId).clearState();
    }
  }
  async _performStop() {
    const schemes = [$pFb.scheme, $nFb.scheme];
    await Promise.allSettled(this.H.groups.flatMap(async (g) => {
      return g.editors.map(async (e) => {
        if (e instanceof $_Eb && e.initialResources?.some((r2) => r2.originalUri && schemes.indexOf(r2.originalUri.scheme) !== -1) || e instanceof $fub && e.original.resource && schemes.indexOf(e.original.resource.scheme) !== -1) {
          await g.closeEditor(e);
        }
      });
    }));
    if (this.a.get() !== 3) {
      this.dispose();
    }
  }
  dispose() {
    this.X();
    for (const entry of this.j.get()) {
      entry.dispose();
    }
    super.dispose();
    this.a.set(3, void 0);
    this.y.fire();
  }
  getVirtualModel(documentId) {
    this.X();
    const entry = this.j.get().find((e) => e.entryId === documentId);
    return entry?.originalModel ?? null;
  }
  acceptStreamingEditsStart() {
    if (this.a.get() === 3) {
      return;
    }
    this.m.queue(() => this.$());
  }
  acceptTextEdits(resource, textEdits, isLastEdits, responseModel) {
    if (this.a.get() === 3) {
      return;
    }
    this.m.queue(() => this.ab(resource, textEdits, isLastEdits, responseModel));
  }
  resolve() {
    if (this.a.get() === 3) {
      return;
    }
    this.m.queue(() => this.bb());
  }
  addFileToWorkingSet(resource, description, proposedState) {
    const state = this.n.get(resource);
    if (proposedState === 6) {
      if (state !== void 0 || this.t.has(resource)) {
        return;
      }
      this.n.set(resource, {
        description,
        state: 6
        /* WorkingSetEntryState.Suggested */
      });
      this.w.fire(
        0
        /* ChatEditingSessionChangeType.WorkingSet */
      );
    } else if (state === void 0 || state.state === 3 || state.state === 6) {
      this.n.set(resource, {
        description,
        state: 4
        /* WorkingSetEntryState.Attached */
      });
      this.w.fire(
        0
        /* ChatEditingSessionChangeType.WorkingSet */
      );
    }
  }
  async undoInteraction() {
    const linearHistory = this.b.get();
    const newIndex = this.c.get() - 1;
    if (newIndex < 0) {
      return;
    }
    const previousSnapshot = linearHistory[newIndex];
    await this.restoreSnapshot(previousSnapshot.requestId);
    this.c.set(newIndex, void 0);
    this.Z();
  }
  async redoInteraction() {
    const linearHistory = this.b.get();
    const newIndex = this.c.get() + 1;
    if (newIndex > linearHistory.length) {
      return;
    }
    const nextSnapshot = newIndex < linearHistory.length ? linearHistory[newIndex] : this.U;
    if (!nextSnapshot) {
      return;
    }
    await this.restoreSnapshot(nextSnapshot.requestId);
    this.c.set(newIndex, void 0);
    this.Z();
  }
  Z() {
    const hiddenRequestIds = this.b.get().slice(this.c.get()).map((s) => s.requestId).filter((r2) => !!r2);
    this.O.getSession(this.chatSessionId)?.disableRequests(hiddenRequestIds);
  }
  async $() {
    $ce((tx) => {
      this.a.set(1, tx);
      for (const entry of this.j.get()) {
        entry.acceptStreamingEditsStart(tx);
      }
    });
  }
  async ab(resource, textEdits, isLastEdits, responseModel) {
    if (this.h.has(resource)) {
      return;
    }
    if (!this.j.get().find((e) => $oh(e.modifiedURI, resource)) && this.j.get().length >= await this.z) {
      return;
    }
    if (resource.scheme !== Schemas.untitled && !this.J.getWorkspaceFolder(resource) && !await this.L.exists(resource)) {
      const saveLocation = await this.M.showSaveDialog({ title: localize(4868, null, this.N.getDefaultAgent(ChatAgentLocation.EditingSession)?.fullName ?? "Chat") });
      if (!saveLocation) {
        this.h.add(resource);
        return;
      }
      resource = saveLocation;
    }
    const telemetryInfo = new class {
      get agentId() {
        return responseModel.agent?.id;
      }
      get command() {
        return responseModel.slashCommand?.name;
      }
      get sessionId() {
        return responseModel.session.sessionId;
      }
      get requestId() {
        return responseModel.requestId;
      }
      get result() {
        return responseModel.result;
      }
    }();
    const entry = await this.cb(resource, telemetryInfo);
    entry.acceptAgentEdits(textEdits, isLastEdits);
  }
  async bb() {
    $ce((tx) => {
      for (const entry of this.j.get()) {
        entry.acceptStreamingEditsEnd(tx);
      }
      this.a.set(2, tx);
    });
    this.w.fire(
      1
      /* ChatEditingSessionChangeType.Other */
    );
  }
  async cb(resource, responseModel) {
    const existingEntry = this.j.get().find((e) => $oh(e.modifiedURI, resource));
    if (existingEntry) {
      if (responseModel.requestId !== existingEntry.telemetryInfo.requestId) {
        existingEntry.updateTelemetryInfo(responseModel);
      }
      return existingEntry;
    }
    const initialContent = this.f.get(resource);
    const entry = await this.db(resource, responseModel, false, initialContent);
    if (!initialContent) {
      this.f.set(resource, entry.initialContent);
    }
    this.B(entry.onDidDelete(() => {
      const newEntries = this.j.get().filter((e) => !$oh(e.modifiedURI, entry.modifiedURI));
      this.j.set(newEntries, void 0);
      this.n.delete(entry.modifiedURI);
      this.I.closeEditors(this.I.findEditors(entry.modifiedURI));
      entry.dispose();
      this.w.fire(
        0
        /* ChatEditingSessionChangeType.WorkingSet */
      );
    }));
    const entriesArr = [...this.j.get(), entry];
    this.j.set(entriesArr, void 0);
    this.w.fire(
      0
      /* ChatEditingSessionChangeType.WorkingSet */
    );
    return entry;
  }
  async db(resource, responseModel, mustExist = false, initialContent) {
    try {
      const ref = await this.G.createModelReference(resource);
      if (this.P.hasSupportedNotebooks(resource)) {
        return this.C.createInstance($lFb, ref, { collapse: (transaction) => this.eb(resource, transaction) }, responseModel, mustExist ? 0 : 1, initialContent);
      }
      return this.C.createInstance($pFb, ref, { collapse: (transaction) => this.eb(resource, transaction) }, responseModel, mustExist ? 0 : 1, initialContent);
    } catch (err) {
      if (mustExist) {
        throw err;
      }
      await this._bulkEditService.apply({ edits: [{ newResource: resource }] });
      this.I.openEditor({ resource, options: { inactive: true, preserveFocus: true, pinned: true } });
      return this.db(resource, responseModel, true, initialContent);
    }
  }
  eb(resource, transaction) {
    const multiDiffItem = this.u?.findDocumentDiffItem(resource);
    if (multiDiffItem) {
      this.u?.viewModel?.items.get().find((documentDiffItem) => $oh(documentDiffItem.originalUri, multiDiffItem.originalUri) && $oh(documentDiffItem.modifiedUri, multiDiffItem.modifiedUri))?.collapsed.set(true, transaction);
    }
  }
};
$mFb = __decorate([
  __param(2, $Pk),
  __param(3, $sG),
  __param(4, $1E),
  __param(5, $oG),
  __param(6, $H_),
  __param(7, $iJ),
  __param(8, $mJ),
  __param(9, $Zk),
  __param(10, $km),
  __param(11, $1v),
  __param(12, $ZO),
  __param(13, $qO),
  __param(14, $mrb)
], $mFb);
var ChatEditingSessionStorage = class ChatEditingSessionStorage2 {
  constructor(a, b, c, d, f) {
    this.a = a;
    this.b = b;
    this.c = c;
    this.d = d;
    this.f = f;
  }
  h() {
    const workspaceId = this.f.getWorkspace().id;
    return $vh(this.c.workspaceStorageHome, workspaceId, "chatEditingSessions", this.a);
  }
  async restoreState() {
    const storageLocation = this.h();
    const getFileContent = (hash) => {
      return this.b.readFile($vh(storageLocation, STORAGE_CONTENTS_FOLDER, hash)).then((content) => content.value.toString());
    };
    const deserializeResourceMap = (resourceMap, deserialize, result) => {
      resourceMap.forEach(([resourceURI, value]) => {
        result.set(URI.parse(resourceURI), deserialize(value));
      });
      return result;
    };
    const deserializeChatEditingSessionSnapshot = async (snapshot) => {
      const entriesMap = new $Ec();
      for (const entryDTO of snapshot.entries) {
        const entry = await deserializeSnapshotEntry(entryDTO);
        entriesMap.set(entry.resource, entry);
      }
      return {
        requestId: snapshot.requestId,
        workingSet: deserializeResourceMap(snapshot.workingSet, (value) => value, new $Ec()),
        entries: entriesMap
      };
    };
    const deserializeSnapshotEntry = async (entry) => {
      return {
        resource: URI.parse(entry.resource),
        languageId: entry.languageId,
        original: await getFileContent(entry.originalHash),
        current: await getFileContent(entry.currentHash),
        originalToCurrentEdit: $cD.fromJson(entry.originalToCurrentEdit),
        state: entry.state,
        snapshotUri: URI.parse(entry.snapshotUri),
        telemetryInfo: { requestId: entry.telemetryInfo.requestId, agentId: entry.telemetryInfo.agentId, command: entry.telemetryInfo.command, sessionId: this.a, result: void 0 }
      };
    };
    try {
      const stateFilePath = $vh(storageLocation, STORAGE_STATE_FILE);
      if (!await this.b.exists(stateFilePath)) {
        this.d.debug(`chatEditingSession: No editing session state found at ${stateFilePath.toString()}`);
        return void 0;
      }
      this.d.debug(`chatEditingSession: Restoring editing session at ${stateFilePath.toString()}`);
      const stateFileContent = await this.b.readFile(stateFilePath);
      const data = JSON.parse(stateFileContent.value.toString());
      if (data.version !== STORAGE_VERSION) {
        return void 0;
      }
      const linearHistory = await Promise.all(data.linearHistory.map(deserializeChatEditingSessionSnapshot));
      const filesToSkipCreating = data.filesToSkipCreating.map((uriStr) => URI.parse(uriStr));
      const initialFileContents = new $Ec();
      for (const fileContentDTO of data.initialFileContents) {
        initialFileContents.set(URI.parse(fileContentDTO[0]), await getFileContent(fileContentDTO[1]));
      }
      const pendingSnapshot = data.pendingSnapshot ? await deserializeChatEditingSessionSnapshot(data.pendingSnapshot) : void 0;
      const recentSnapshot = await deserializeChatEditingSessionSnapshot(data.recentSnapshot);
      return {
        filesToSkipCreating,
        initialFileContents,
        pendingSnapshot,
        recentSnapshot,
        linearHistoryIndex: data.linearHistoryIndex,
        linearHistory
      };
    } catch (e) {
      this.d.error(`Error restoring chat editing session from ${storageLocation.toString()}`, e);
    }
    return void 0;
  }
  async storeState(state) {
    const storageFolder = this.h();
    const contentsFolder = URI.joinPath(storageFolder, STORAGE_CONTENTS_FOLDER);
    const existingContents = /* @__PURE__ */ new Set();
    try {
      const stat = await this.b.resolve(contentsFolder);
      stat.children?.forEach((child) => {
        if (child.isDirectory) {
          existingContents.add(child.name);
        }
      });
    } catch (e) {
      try {
        await this.b.createFolder(contentsFolder);
      } catch (e2) {
        this.d.error(`Error creating chat editing session content folder ${contentsFolder.toString()}`, e2);
        return;
      }
    }
    const fileContents = /* @__PURE__ */ new Map();
    const addFileContent = (content) => {
      const shaComputer = new $3i();
      shaComputer.update(content);
      const sha = shaComputer.digest().substring(0, 7);
      if (!existingContents.has(sha)) {
        fileContents.set(sha, content);
      }
      return sha;
    };
    const serializeResourceMap = (resourceMap, serialize) => {
      return Array.from(resourceMap.entries()).map(([resourceURI, value]) => [resourceURI.toString(), serialize(value)]);
    };
    const serializeChatEditingSessionSnapshot = (snapshot) => {
      return {
        requestId: snapshot.requestId,
        workingSet: serializeResourceMap(snapshot.workingSet, (value) => value),
        entries: Array.from(snapshot.entries.values()).map(serializeSnapshotEntry)
      };
    };
    const serializeSnapshotEntry = (entry) => {
      return {
        resource: entry.resource.toString(),
        languageId: entry.languageId,
        originalHash: addFileContent(entry.original),
        currentHash: addFileContent(entry.current),
        originalToCurrentEdit: entry.originalToCurrentEdit.edits.map((edit3) => ({ pos: edit3.replaceRange.start, len: edit3.replaceRange.length, txt: edit3.newText })),
        state: entry.state,
        snapshotUri: entry.snapshotUri.toString(),
        telemetryInfo: { requestId: entry.telemetryInfo.requestId, agentId: entry.telemetryInfo.agentId, command: entry.telemetryInfo.command }
      };
    };
    try {
      const data = {
        version: STORAGE_VERSION,
        sessionId: this.a,
        linearHistory: state.linearHistory.map(serializeChatEditingSessionSnapshot),
        linearHistoryIndex: state.linearHistoryIndex,
        initialFileContents: serializeResourceMap(state.initialFileContents, (value) => addFileContent(value)),
        pendingSnapshot: state.pendingSnapshot ? serializeChatEditingSessionSnapshot(state.pendingSnapshot) : void 0,
        recentSnapshot: serializeChatEditingSessionSnapshot(state.recentSnapshot),
        filesToSkipCreating: state.filesToSkipCreating.map((uri) => uri.toString())
      };
      this.d.debug(`chatEditingSession: Storing editing session at ${storageFolder.toString()}: ${fileContents.size} files`);
      for (const [hash, content] of fileContents) {
        await this.b.writeFile($vh(contentsFolder, hash), $Ci.fromString(content));
      }
      await this.b.writeFile($vh(storageFolder, STORAGE_STATE_FILE), $Ci.fromString(JSON.stringify(data, void 0, 2)));
    } catch (e) {
      this.d.debug(`Error storing chat editing session to ${storageFolder.toString()}`, e);
    }
  }
  async clearState() {
    const storageFolder = this.h();
    if (await this.b.exists(storageFolder)) {
      this.d.debug(`chatEditingSession: Clearing editing session at ${storageFolder.toString()}`);
      try {
        await this.b.del(storageFolder, { recursive: true });
      } catch (e) {
        this.d.debug(`Error clearing chat editing session from ${storageFolder.toString()}`, e);
      }
    }
  }
};
ChatEditingSessionStorage = __decorate([
  __param(1, $km),
  __param(2, $Xk),
  __param(3, $wn),
  __param(4, $Zk)
], ChatEditingSessionStorage);
var STORAGE_VERSION = 1;

// out-build/vs/workbench/contrib/chat/browser/chatEditing/chatEditingService.js
var $kFb_1;
var STORAGE_KEY_EDITING_SESSION = "chat.editingSession";
var $jFb = class $jFb2 extends $3c {
  get currentAutoApplyOperation() {
    return this.g.get();
  }
  get currentEditingSession() {
    return this.c.get();
  }
  get currentEditingSessionObs() {
    return this.c;
  }
  get onDidCreateEditingSession() {
    return this.h.event;
  }
  get editingSessionFileLimit() {
    return this.n ?? $jP;
  }
  constructor(w, multiDiffSourceResolverService, textModelService, contextKeyService, y, z, C, decorationsService, D, F, G, storageService) {
    super();
    this.w = w;
    this.y = y;
    this.z = z;
    this.C = C;
    this.D = D;
    this.F = F;
    this.G = G;
    this.c = $he(this, null);
    this.f = this.B(new $2c());
    this.g = $he(this, null);
    this.h = this.B(new $ze());
    this.j = this.B(new $ze());
    this.onDidChangeEditingSession = this.j.event;
    this.u = /* @__PURE__ */ new Map();
    this.t = $hP.bindTo(contextKeyService);
    this.t.set(false);
    this.B(decorationsService.registerDecorationsProvider(w.createInstance(ChatDecorationsProvider, this.c)));
    this.B(multiDiffSourceResolverService.registerResolver(w.createInstance($kFb, this.c)));
    textModelService.registerTextModelContentProvider($nFb.scheme, w.createInstance($nFb, this.c));
    textModelService.registerTextModelContentProvider($oFb.scheme, w.createInstance($oFb, this.c));
    this.B($H9($bP, contextKeyService, (reader) => {
      const currentSession = this.c.read(reader);
      if (!currentSession) {
        return;
      }
      const entries2 = currentSession.entries.read(reader);
      const decidedEntries = entries2.filter(
        (entry) => entry.state.read(reader) !== 0
        /* WorkingSetEntryState.Modified */
      );
      return decidedEntries.map((entry) => entry.entryId);
    }));
    this.B($H9($fP, contextKeyService, (reader) => {
      const currentSession = this.c.read(reader);
      if (!currentSession) {
        return;
      }
      const entries2 = currentSession.entries.read(reader);
      const decidedEntries = entries2.filter(
        (entry) => entry.state.read(reader) === 0
        /* WorkingSetEntryState.Modified */
      );
      return decidedEntries.length > 0;
    }));
    this.B($H9($gP, contextKeyService, (reader) => {
      const currentSession = this.c.read(reader);
      if (!currentSession) {
        return false;
      }
      const entries2 = currentSession.entries.read(reader);
      return entries2.length > 0;
    }));
    this.B($H9($dP, contextKeyService, (reader) => {
      return this.c.read(reader) !== null;
    }));
    this.B($H9($eP, contextKeyService, (reader) => {
      return this.g.read(reader) !== null;
    }));
    this.B($H9(ChatContextKeys.chatEditingCanUndo, contextKeyService, (r2) => {
      return this.c.read(r2)?.canUndo.read(r2) || false;
    }));
    this.B($H9(ChatContextKeys.chatEditingCanRedo, contextKeyService, (r2) => {
      return this.c.read(r2)?.canRedo.read(r2) || false;
    }));
    this.B(this.y.onDidDisposeSession((e) => {
      if (e.reason === "cleared" && this.c.get()?.chatSessionId === e.sessionId) {
        this.t.set(false);
        void this.c.get()?.stop();
      }
    }));
    this.B(this.F.onWillShutdown((e) => {
      const session = this.c.get();
      if (session) {
        storageService.store(
          STORAGE_KEY_EDITING_SESSION,
          session.chatSessionId,
          1,
          1
          /* StorageTarget.MACHINE */
        );
        e.join(session.storeState(), { id: "join.chatEditingSession", label: localize(4861, null) });
      }
    }));
    this.m = this.G.getTreatment($iP).then((value) => {
      this.n = value ?? $jP;
      return this.n;
    });
    void this.m;
    const sessionIdToRestore = storageService.get(
      STORAGE_KEY_EDITING_SESSION,
      1
      /* StorageScope.WORKSPACE */
    );
    if ($zg(sessionIdToRestore) && this.y.getOrRestoreSession(sessionIdToRestore)) {
      this.s = this.startOrContinueEditingSession(sessionIdToRestore);
      this.s.finally(() => {
        this.s = void 0;
      });
    }
  }
  async getOrRestoreEditingSession() {
    if (this.s) {
      await this.s;
    }
    return this.currentEditingSessionObs.get();
  }
  dispose() {
    this.c.get()?.dispose();
    super.dispose();
  }
  async startOrContinueEditingSession(chatSessionId) {
    await this.s;
    const session = this.c.get();
    if (session) {
      if (session.chatSessionId === chatSessionId) {
        return session;
      } else if (session.chatSessionId !== chatSessionId) {
        await session.stop(true);
      }
    }
    return this.H(chatSessionId);
  }
  async H(chatSessionId) {
    if (this.c.get()) {
      throw new $vb("Cannot have more than one active editing session");
    }
    this.f.clear();
    const session = this.w.createInstance($mFb, chatSessionId, this.m);
    await session.init();
    this.f.add(this.I(session));
    this.f.add(session.onDidDispose(() => {
      this.f.clear();
      this.c.set(null, void 0);
      this.j.fire();
    }));
    this.f.add(session.onDidChange(() => {
      this.j.fire();
    }));
    this.c.set(session, void 0);
    this.h.fire(session);
    this.j.fire();
    return session;
  }
  I(session) {
    const chatModel = this.y.getOrRestoreSession(session.chatSessionId);
    if (!chatModel) {
      throw new Error(`Edit session was created for a non-existing chat session: ${session.chatSessionId}`);
    }
    const observerDisposables = new $2c();
    let editsSource;
    let editsPromise;
    const editsSeen = new $Ec();
    const editedFilesExist = new $Ec();
    const onResponseComplete = (responseModel) => {
      if (responseModel.result?.errorDetails && !responseModel.result.errorDetails.responseIsIncomplete) {
        session.restoreSnapshot(responseModel.requestId);
        this.t.set(true);
      }
      editsSource?.resolve();
      editsSource = void 0;
      editsSeen.clear();
      editedFilesExist.clear();
    };
    const handleResponseParts = async (responseModel) => {
      for (const part of responseModel.response.value) {
        if (part.kind === "codeblockUri" || part.kind === "textEditGroup") {
          if (!editedFilesExist.get(part.uri)) {
            editedFilesExist.set(part.uri, this.D.exists(part.uri).then((e) => {
              if (e) {
                this.C.openEditor({ resource: part.uri, options: { inactive: true, preserveFocus: true, pinned: true } });
              }
              return e;
            }));
          }
          const first = editsSeen.size === 0;
          let entry = editsSeen.get(part.uri);
          if (!entry) {
            entry = { seen: 0 };
            editsSeen.set(part.uri, entry);
          }
          const allEdits = part.kind === "textEditGroup" ? part.edits : [];
          const newEdits = allEdits.slice(entry.seen);
          entry.seen += newEdits.length;
          if (newEdits.length > 0 || entry.seen === 0) {
            editsSource ??= new $mi();
            editsSource.emitOne({ uri: part.uri, edits: newEdits, kind: "textEditGroup", done: part.kind === "textEditGroup" && part.done });
          }
          if (first) {
            await editsPromise;
            editsPromise = this.J(session, async (builder, token) => {
              for await (const item of editsSource.asyncIterable) {
                if (token.isCancellationRequested) {
                  break;
                }
                if (item.edits.length === 0) {
                  builder.textEdits(item.uri, [], item.done ?? false, responseModel);
                  continue;
                }
                for (let i2 = 0; i2 < item.edits.length; i2++) {
                  const group2 = item.edits[i2];
                  const isLastGroup = i2 === item.edits.length - 1;
                  builder.textEdits(item.uri, group2, isLastGroup && (item.done ?? false), responseModel);
                }
              }
            }).finally(() => {
              editsPromise = void 0;
            });
          }
        }
      }
    };
    observerDisposables.add(chatModel.onDidChange(async (e) => {
      if (e.kind === "addRequest") {
        session.createSnapshot(e.request.id);
        this.t.set(false);
        const responseModel = e.request.response;
        if (responseModel) {
          if (responseModel.isComplete) {
            await handleResponseParts(responseModel);
            onResponseComplete(responseModel);
          } else {
            const disposable = responseModel.onDidChange(async () => {
              await handleResponseParts(responseModel);
              if (responseModel.isComplete) {
                onResponseComplete(responseModel);
                disposable.dispose();
              } else if (responseModel.isCanceled || responseModel.isStale) {
                disposable.dispose();
              }
            });
          }
        }
      }
    }));
    observerDisposables.add(chatModel.onDidDispose(() => observerDisposables.dispose()));
    return observerDisposables;
  }
  async J(session, builder) {
    if (session.state.get() === 1) {
      throw new $vb("Cannot continue session that is still streaming");
    }
    const stream = {
      textEdits: (resource, textEdits, isDone, responseModel) => {
        session.acceptTextEdits(resource, textEdits, isDone, responseModel);
      }
    };
    session.acceptStreamingEditsStart();
    const cancellationTokenSource = new $ad();
    this.g.set(cancellationTokenSource, void 0);
    try {
      await this.z.withProgress({
        location: 10,
        title: localize2(4865, "Generating edits...").value
      }, async () => {
        await builder(stream, cancellationTokenSource.token);
      }, () => cancellationTokenSource.cancel());
    } finally {
      cancellationTokenSource.dispose();
      this.g.set(null, void 0);
      session.resolve();
    }
  }
  hasRelatedFilesProviders() {
    return this.u.size > 0;
  }
  registerRelatedFilesProvider(handle2, provider) {
    this.u.set(handle2, provider);
    return $1c(() => {
      this.u.delete(handle2);
    });
  }
  async getRelatedFiles(chatSessionId, prompt, token) {
    const currentSession = this.c.get();
    if (!currentSession || chatSessionId !== currentSession.chatSessionId) {
      return void 0;
    }
    const userAddedWorkingSetEntries = [];
    for (const [uri, metadata] of currentSession.workingSet) {
      if (metadata.state !== 6) {
        userAddedWorkingSetEntries.push(uri);
      }
    }
    const providers2 = Array.from(this.u.values());
    const result = await Promise.all(providers2.map(async (provider) => {
      try {
        const relatedFiles = await provider.provideRelatedFiles({ prompt, files: userAddedWorkingSetEntries }, token);
        if (relatedFiles?.length) {
          return { group: provider.description, files: relatedFiles };
        }
        return void 0;
      } catch (e) {
        return void 0;
      }
    }));
    return $Mb(result);
  }
};
$jFb = __decorate([
  __param(0, $Pk),
  __param(1, $TDb),
  __param(2, $oG),
  __param(3, $on),
  __param(4, $qO),
  __param(5, $TJ),
  __param(6, $mJ),
  __param(7, $jsb),
  __param(8, $km),
  __param(9, $KL),
  __param(10, $hFb),
  __param(11, $jv)
], $jFb);
function observeArrayChanges(obs, compare8, store) {
  const emitter = store.add(new $ze());
  store.add($Wd(obs, (newArr, oldArr) => {
    const change = $Jb(oldArr || [], newArr, compare8);
    const changedElements = [].concat(change.added).concat(change.removed);
    emitter.fire(changedElements);
  }));
  return emitter.event;
}
var ChatDecorationsProvider = class ChatDecorationsProvider2 extends $3c {
  constructor(h3, j) {
    super();
    this.h = h3;
    this.j = j;
    this.label = localize(4862, null);
    this.c = $2d(this, (r2) => {
      const session = this.h.read(r2);
      if (!session) {
        return [];
      }
      const state = session.state.read(r2);
      if (state === 3) {
        return [];
      }
      return session.entries.read(r2);
    });
    this.f = $2d(this, (r2) => {
      const uri = this.c.read(r2);
      return uri.filter((entry) => entry.isCurrentlyBeingModified.read(r2)).map((entry) => entry.modifiedURI);
    });
    this.g = $2d(this, (r2) => {
      const uri = this.c.read(r2);
      return uri.filter(
        (entry) => !entry.isCurrentlyBeingModified.read(r2) && entry.state.read(r2) === 0
        /* WorkingSetEntryState.Modified */
      ).map((entry) => entry.modifiedURI);
    });
    this.onDidChange = Event2.any(observeArrayChanges(this.f, $9b((uri) => uri.toString(), $Tf), this.q), observeArrayChanges(this.g, $9b((uri) => uri.toString(), $Tf), this.q));
  }
  provideDecorations(uri, _token) {
    const isCurrentlyBeingModified = this.f.get().some((e) => e.toString() === uri.toString());
    if (isCurrentlyBeingModified) {
      return {
        weight: 1e3,
        letter: ThemeIcon.modify($6l.loading, "spin"),
        bubble: false
      };
    }
    const isModified = this.g.get().some((e) => e.toString() === uri.toString());
    if (isModified) {
      const defaultAgentName = this.j.getDefaultAgent(ChatAgentLocation.EditingSession)?.fullName;
      return {
        weight: 1e3,
        letter: $6l.diffModified,
        tooltip: defaultAgentName ? localize(4863, null, defaultAgentName) : localize(4864, null),
        bubble: true
      };
    }
    return void 0;
  }
};
ChatDecorationsProvider = __decorate([
  __param(1, $ZO)
], ChatDecorationsProvider);
var $kFb = class $kFb2 {
  static {
    $kFb_1 = this;
  }
  static {
    this.scheme = $_O;
  }
  static getMultiDiffSourceUri() {
    return URI.from({
      scheme: $kFb_1.scheme,
      path: ""
    });
  }
  constructor(c, d) {
    this.c = c;
    this.d = d;
  }
  canHandleUri(uri) {
    return uri.scheme === $kFb_1.scheme;
  }
  async resolveDiffSource(uri) {
    return this.d.createInstance(ChatEditingMultiDiffSource, this.c);
  }
};
$kFb = $kFb_1 = __decorate([
  __param(1, $Pk)
], $kFb);
var ChatEditingMultiDiffSource = class {
  constructor(d) {
    this.d = d;
    this.c = $2d(this, (reader) => {
      const currentSession = this.d.read(reader);
      if (!currentSession) {
        return [];
      }
      const entries2 = currentSession.entries.read(reader);
      return entries2.map((entry) => {
        return new $UDb(entry.originalURI, entry.modifiedURI, void 0, {
          [$cP.key]: entry.entryId
          // [inChatEditingSessionContextKey.key]: true
        });
      });
    });
    this.resources = new $Sd(this.c);
    this.contextKeys = {
      [$dP.key]: true
    };
  }
};

// out-build/vs/workbench/contrib/chat/browser/chatEdinputInputContentProvider.js
var $H8b = class $H8b2 extends $3c {
  constructor(textModelService, a, b) {
    super();
    this.a = a;
    this.b = b;
    this.B(textModelService.registerTextModelContentProvider($1Nb.INPUT_SCHEME, this));
  }
  async provideTextContent(resource) {
    const existing = this.a.getModel(resource);
    if (existing) {
      return existing;
    }
    return this.a.createModel("", this.b.createById("chatinput"), resource);
  }
};
$H8b = __decorate([
  __param(0, $oG),
  __param(1, $sG),
  __param(2, $1E)
], $H8b);

// out-build/vs/workbench/contrib/chat/browser/chatSetup.js
var ChatSetupContext_1;
var defaultChat2 = {
  extensionId: product_default.defaultChatAgent?.extensionId ?? "",
  chatExtensionId: product_default.defaultChatAgent?.chatExtensionId ?? "",
  documentationUrl: product_default.defaultChatAgent?.documentationUrl ?? "",
  termsStatementUrl: product_default.defaultChatAgent?.termsStatementUrl ?? "",
  privacyStatementUrl: product_default.defaultChatAgent?.privacyStatementUrl ?? "",
  skusDocumentationUrl: product_default.defaultChatAgent?.skusDocumentationUrl ?? "",
  upgradePlanUrl: product_default.defaultChatAgent?.upgradePlanUrl ?? "",
  providerId: product_default.defaultChatAgent?.providerId ?? "",
  providerName: product_default.defaultChatAgent?.providerName ?? "",
  providerScopes: product_default.defaultChatAgent?.providerScopes ?? [[]],
  entitlementUrl: product_default.defaultChatAgent?.entitlementUrl ?? "",
  entitlementSignupLimitedUrl: product_default.defaultChatAgent?.entitlementSignupLimitedUrl ?? ""
};
var ChatEntitlement;
(function(ChatEntitlement2) {
  ChatEntitlement2[ChatEntitlement2["Unknown"] = 1] = "Unknown";
  ChatEntitlement2[ChatEntitlement2["Unresolved"] = 2] = "Unresolved";
  ChatEntitlement2[ChatEntitlement2["Available"] = 3] = "Available";
  ChatEntitlement2[ChatEntitlement2["Unavailable"] = 4] = "Unavailable";
  ChatEntitlement2[ChatEntitlement2["Limited"] = 5] = "Limited";
  ChatEntitlement2[ChatEntitlement2["Pro"] = 6] = "Pro";
})(ChatEntitlement || (ChatEntitlement = {}));
var TRIGGER_SETUP_COMMAND_ID = "workbench.action.chat.triggerSetup";
var TRIGGER_SETUP_COMMAND_LABEL = localize2(5029, "Use AI Features with Copilot for Free...");
var $ANb = /* @__PURE__ */ new Set([ChatContextKeys.Setup.triggered.key, ChatContextKeys.Setup.installed.key, ChatContextKeys.Setup.signedOut.key, ChatContextKeys.Setup.canSignUp.key]);
var $BNb = $7m.and($7m.has("config.chat.experimental.offerSetup"), $7m.or($7m.and(ChatContextKeys.Setup.triggered, ChatContextKeys.Setup.installed.negate()), $7m.and(ChatContextKeys.Setup.canSignUp, ChatContextKeys.Setup.installed), $7m.and(ChatContextKeys.Setup.signedOut, ChatContextKeys.Setup.installed)));
var $CNb = class $CNb2 extends $3c {
  static {
    this.ID = "workbench.chat.setup";
  }
  constructor(f, g) {
    super();
    this.f = f;
    this.g = g;
    this.a = this.B(this.g.createInstance(ChatSetupContext));
    this.b = this.B(this.g.createInstance(ChatSetupRequests, this.a));
    this.c = new $sf(() => this.B(this.g.createInstance(ChatSetupController, this.a, this.b)));
    if (!this.f.defaultChatAgent) {
      return;
    }
    this.h();
    this.j();
  }
  h() {
    $Wn.as(
      "workbench.registry.chat.viewsWelcome"
      /* ChatViewsWelcomeExtensions.ChatViewsWelcomeRegistry */
    ).register({
      title: localize(5008, null),
      when: $BNb,
      icon: $6l.copilotLarge,
      content: (disposables) => disposables.add(this.g.createInstance(ChatSetupWelcomeContent, this.c.value, this.a)).element
    });
  }
  j() {
    const that = this;
    class ChatSetupTriggerAction extends $gJ {
      constructor() {
        super({
          id: TRIGGER_SETUP_COMMAND_ID,
          title: TRIGGER_SETUP_COMMAND_LABEL,
          category: $vNb,
          f1: true,
          precondition: $7m.and(ChatContextKeys.Setup.installed.negate(), $7m.has("config.chat.experimental.offerSetup")),
          menu: {
            id: $bJ.ChatCommandCenter,
            group: "a_last",
            order: 1,
            when: ChatContextKeys.Setup.installed.negate()
          }
        });
      }
      async run(accessor, startSetup) {
        const viewsService = accessor.get($uob);
        const viewDescriptorService = accessor.get($$M);
        const configurationService = accessor.get($kl);
        const layoutService = accessor.get($Vlb);
        await that.a.update({ triggered: true });
        showCopilotView(viewsService, layoutService);
        $5Nb(400, viewDescriptorService, layoutService);
        if (startSetup === true) {
          const controller = that.c.value;
          controller.setup();
        }
        configurationService.updateValue("chat.commandCenter.enabled", true);
      }
    }
    class ChatSetupHideAction extends $gJ {
      static {
        this.ID = "workbench.action.chat.hideSetup";
      }
      static {
        this.TITLE = localize2(5030, "Hide Copilot");
      }
      constructor() {
        super({
          id: ChatSetupHideAction.ID,
          title: ChatSetupHideAction.TITLE,
          f1: true,
          category: $vNb,
          precondition: $7m.and(ChatContextKeys.Setup.installed.negate(), $7m.has("config.chat.experimental.offerSetup")),
          menu: {
            id: $bJ.ChatCommandCenter,
            group: "z_hide",
            order: 1,
            when: ChatContextKeys.Setup.installed.negate()
          }
        });
      }
      async run(accessor) {
        const viewsDescriptorService = accessor.get($$M);
        const layoutService = accessor.get($Vlb);
        const configurationService = accessor.get($kl);
        const dialogService = accessor.get($Yv);
        const { confirmed } = await dialogService.confirm({
          message: localize(5009, null),
          detail: localize(5010, null, TRIGGER_SETUP_COMMAND_LABEL.value),
          primaryButton: localize(5011, null)
        });
        if (!confirmed) {
          return;
        }
        await hideSetupView(viewsDescriptorService, layoutService);
        configurationService.updateValue("chat.commandCenter.enabled", false);
      }
    }
    const windowFocusListener = this.B(new $4c());
    class UpgradePlanAction extends $gJ {
      constructor() {
        super({
          id: "workbench.action.chat.upgradePlan",
          title: localize2(5031, "Upgrade to Copilot Pro"),
          category: localize2(5032, "Chat"),
          f1: true,
          precondition: ChatContextKeys.enabled,
          menu: {
            id: $bJ.ChatCommandCenter,
            group: "a_first",
            order: 1,
            when: $7m.and(ChatContextKeys.Setup.installed, $7m.or(ChatContextKeys.chatQuotaExceeded, ChatContextKeys.completionsQuotaExceeded))
          }
        });
      }
      async run(accessor) {
        const openerService = accessor.get($O4);
        const telemetryService = accessor.get($zv);
        const hostService = accessor.get($S4);
        const commandService = accessor.get($sn);
        telemetryService.publicLog2("workbenchActionExecuted", { id: this.desc.id, from: "chat" });
        openerService.open(URI.parse(defaultChat2.upgradePlanUrl));
        const entitlement = that.a.state.entitlement;
        if (entitlement !== ChatEntitlement.Pro) {
          windowFocusListener.value = hostService.onDidChangeFocus((focus) => this.a(focus, commandService));
        }
      }
      async a(focus, commandService) {
        if (focus) {
          windowFocusListener.clear();
          const entitlement = await that.b.forceResolveEntitlement(void 0);
          if (entitlement === ChatEntitlement.Pro) {
            commandService.executeCommand("github.copilot.refreshToken");
          }
        }
      }
    }
    async function hideSetupView(viewsDescriptorService, layoutService) {
      const location3 = viewsDescriptorService.getViewLocationById($9Nb);
      await that.a.update({ triggered: false });
      if (location3 === 2) {
        const activeContainers = viewsDescriptorService.getViewContainersByLocation(location3).filter((container2) => viewsDescriptorService.getViewContainerModel(container2).activeViewDescriptors.length > 0);
        if (activeContainers.length === 0) {
          layoutService.setPartHidden(
            true,
            "workbench.parts.auxiliarybar"
            /* Parts.AUXILIARYBAR_PART */
          );
        }
      }
    }
    $hJ(ChatSetupTriggerAction);
    $hJ(ChatSetupHideAction);
    $hJ(UpgradePlanAction);
  }
};
$CNb = __decorate([
  __param(0, $Vu),
  __param(1, $Pk)
], $CNb);
var ChatSetupRequests = class ChatSetupRequests2 extends $3c {
  constructor(f, g, h3, j, m, n) {
    super();
    this.f = f;
    this.g = g;
    this.h = h3;
    this.j = j;
    this.m = m;
    this.n = n;
    this.a = { entitlement: this.f.state.entitlement };
    this.b = new $ad();
    this.c = false;
    this.r();
    this.s();
  }
  r() {
    this.B(this.h.onDidChangeDeclaredProviders(() => this.s()));
    this.B(this.h.onDidChangeSessions((e) => {
      if (e.providerId === defaultChat2.providerId) {
        this.s();
      }
    }));
    this.B(this.h.onDidRegisterAuthenticationProvider((e) => {
      if (e.id === defaultChat2.providerId) {
        this.s();
      }
    }));
    this.B(this.h.onDidUnregisterAuthenticationProvider((e) => {
      if (e.id === defaultChat2.providerId) {
        this.s();
      }
    }));
    this.B(this.f.onDidChange(() => {
      if (!this.f.state.installed || this.f.state.entitlement === ChatEntitlement.Unknown) {
        this.a = { entitlement: this.a.entitlement, quotas: void 0 };
        this.n.clearQuotas();
      }
    }));
  }
  async s() {
    this.b.dispose(true);
    const cts = this.b = new $ad();
    const session = await this.t(cts.token);
    if (cts.token.isCancellationRequested) {
      return;
    }
    let state = void 0;
    if (session) {
      if (this.a.entitlement === ChatEntitlement.Unknown) {
        state = { entitlement: ChatEntitlement.Unresolved };
      }
    } else {
      this.c = false;
      state = { entitlement: ChatEntitlement.Unknown };
    }
    if (state) {
      this.C(state);
    }
    if (session && !this.c) {
      await this.w(session, cts.token);
    }
  }
  async t(token) {
    const sessions = await this.h.getSessions(defaultChat2.providerId);
    if (token.isCancellationRequested) {
      return void 0;
    }
    for (const session of sessions) {
      for (const scopes of defaultChat2.providerScopes) {
        if (this.u(session.scopes, scopes)) {
          return session;
        }
      }
    }
    return void 0;
  }
  u(scopes, expectedScopes) {
    return scopes.length === expectedScopes.length && expectedScopes.every((scope) => scopes.includes(scope));
  }
  async w(session, token) {
    const entitlements = await this.y(session, token);
    if (typeof entitlements?.entitlement === "number" && !token.isCancellationRequested) {
      this.c = true;
      this.C(entitlements);
    }
    return entitlements?.entitlement;
  }
  async y(session, token) {
    if (token.isCancellationRequested) {
      return void 0;
    }
    const response = await this.z(defaultChat2.entitlementUrl, "GET", void 0, session, token);
    if (token.isCancellationRequested) {
      return void 0;
    }
    if (!response) {
      this.j.trace("[chat setup] entitlement: no response");
      return { entitlement: ChatEntitlement.Unresolved };
    }
    if (response.res.statusCode && response.res.statusCode !== 200) {
      this.j.trace(`[chat setup] entitlement: unexpected status code ${response.res.statusCode}`);
      return { entitlement: ChatEntitlement.Unresolved };
    }
    const responseText = await $av(response);
    if (token.isCancellationRequested) {
      return void 0;
    }
    if (!responseText) {
      this.j.trace("[chat setup] entitlement: response has no content");
      return { entitlement: ChatEntitlement.Unresolved };
    }
    let entitlementsResponse;
    try {
      entitlementsResponse = JSON.parse(responseText);
      this.j.trace(`[chat setup] entitlement: parsed result is ${JSON.stringify(entitlementsResponse)}`);
    } catch (err) {
      this.j.trace(`[chat setup] entitlement: error parsing response (${err})`);
      return { entitlement: ChatEntitlement.Unresolved };
    }
    let entitlement;
    if (entitlementsResponse.access_type_sku === "free_limited_copilot") {
      entitlement = ChatEntitlement.Limited;
    } else if (entitlementsResponse.can_signup_for_limited) {
      entitlement = ChatEntitlement.Available;
    } else if (entitlementsResponse.chat_enabled) {
      entitlement = ChatEntitlement.Pro;
    } else {
      entitlement = ChatEntitlement.Unavailable;
    }
    const entitlements = {
      entitlement,
      quotas: {
        chat: entitlementsResponse.limited_user_quotas?.chat,
        completions: entitlementsResponse.limited_user_quotas?.completions,
        resetDate: entitlementsResponse.limited_user_reset_date
      }
    };
    this.j.trace(`[chat setup] entitlement: resolved to ${entitlements.entitlement}, quotas: ${JSON.stringify(entitlements.quotas)}`);
    this.g.publicLog2("chatInstallEntitlement", {
      entitlement: entitlements.entitlement,
      quotaChat: entitlementsResponse.limited_user_quotas?.chat,
      quotaCompletions: entitlementsResponse.limited_user_quotas?.completions
    });
    return entitlements;
  }
  async z(url, type, body, session, token) {
    try {
      return await this.m.request({
        type,
        url,
        data: type === "POST" ? JSON.stringify(body) : void 0,
        disableCache: true,
        headers: {
          "Authorization": `Bearer ${session.accessToken}`
        }
      }, token);
    } catch (error) {
      this.j.error(`[chat setup] request: error ${error}`);
      return void 0;
    }
  }
  C(state) {
    this.a = state;
    this.f.update({ entitlement: this.a.entitlement });
    if (state.quotas) {
      this.n.acceptQuotas({
        chatQuotaExceeded: typeof state.quotas.chat === "number" ? state.quotas.chat <= 0 : false,
        completionsQuotaExceeded: typeof state.quotas.completions === "number" ? state.quotas.completions <= 0 : false,
        quotaResetDate: state.quotas.resetDate ? new Date(state.quotas.resetDate) : void 0
      });
    }
  }
  async forceResolveEntitlement(session) {
    if (!session) {
      session = await this.t(CancellationToken.None);
    }
    if (!session) {
      return void 0;
    }
    return this.w(session, CancellationToken.None);
  }
  async signUpLimited(session) {
    const body = {
      restricted_telemetry: "disabled",
      public_code_suggestions: "enabled"
    };
    const response = await this.z(defaultChat2.entitlementSignupLimitedUrl, "POST", body, session, CancellationToken.None);
    if (!response) {
      this.j.error("[chat setup] sign-up: no response");
      return false;
    }
    if (response.res.statusCode && response.res.statusCode !== 200) {
      this.j.error(`[chat setup] sign-up: unexpected status code ${response.res.statusCode}`);
      return false;
    }
    const responseText = await $av(response);
    if (!responseText) {
      this.j.error("[chat setup] sign-up: response has no content");
      return false;
    }
    let parsedResult = void 0;
    try {
      parsedResult = JSON.parse(responseText);
      this.j.trace(`[chat setup] sign-up: response is ${responseText}`);
    } catch (err) {
      this.j.error(`[chat setup] sign-up: error parsing response (${err})`);
    }
    const subscribed = Boolean(parsedResult?.subscribed);
    if (subscribed) {
      this.j.trace("[chat setup] sign-up: successfully subscribed");
    } else {
      this.j.error("[chat setup] sign-up: not subscribed");
    }
    if (subscribed) {
      this.C({ entitlement: ChatEntitlement.Limited });
    }
    return subscribed;
  }
  dispose() {
    this.b.dispose(true);
    super.dispose();
  }
};
ChatSetupRequests = __decorate([
  __param(1, $zv),
  __param(2, $xS),
  __param(3, $wn),
  __param(4, $9u),
  __param(5, $Uzb)
], ChatSetupRequests);
var ChatSetupStep;
(function(ChatSetupStep2) {
  ChatSetupStep2[ChatSetupStep2["Initial"] = 1] = "Initial";
  ChatSetupStep2[ChatSetupStep2["SigningIn"] = 2] = "SigningIn";
  ChatSetupStep2[ChatSetupStep2["Installing"] = 3] = "Installing";
})(ChatSetupStep || (ChatSetupStep = {}));
var ChatSetupController = class ChatSetupController2 extends $3c {
  get step() {
    return this.b;
  }
  constructor(c, f, g, h3, j, m, n, r2, s, t, u, w, y) {
    super();
    this.c = c;
    this.f = f;
    this.g = g;
    this.h = h3;
    this.j = j;
    this.m = m;
    this.n = n;
    this.r = r2;
    this.s = s;
    this.t = t;
    this.u = u;
    this.w = w;
    this.y = y;
    this.a = this.B(new $ze());
    this.onDidChange = this.a.event;
    this.b = ChatSetupStep.Initial;
    this.z();
  }
  z() {
    this.B(this.c.onDidChange(() => this.a.fire()));
  }
  C(step) {
    if (this.b === step) {
      return;
    }
    this.b = step;
    this.a.fire();
  }
  async setup() {
    const title = localize(5012, null);
    const badge = this.u.showViewContainerActivity(isCopilotEditsViewActive(this.j) ? $FNb : $ENb, {
      badge: new $yqb(() => title),
      priority: 100
    });
    try {
      await this.s.withProgress({
        location: 10,
        command: TRIGGER_SETUP_COMMAND_ID,
        title
      }, () => this.D());
    } finally {
      badge.dispose();
    }
  }
  async D() {
    this.c.suspend();
    let focusChatInput = false;
    try {
      let session;
      let entitlement;
      if (this.c.state.entitlement === ChatEntitlement.Unknown) {
        this.C(ChatSetupStep.SigningIn);
        const result = await this.F();
        if (!result.session) {
          return;
        }
        session = result.session;
        entitlement = result.entitlement;
      }
      if (!session) {
        session = (await this.h.getSessions(defaultChat2.providerId)).at(0);
        if (!session) {
          return;
        }
      }
      const activeElement = $Lj();
      this.C(ChatSetupStep.Installing);
      await this.G(session, entitlement ?? this.c.state.entitlement);
      const currentActiveElement = $Lj();
      focusChatInput = activeElement === currentActiveElement || currentActiveElement === $Y.document.body;
    } finally {
      this.C(ChatSetupStep.Initial);
      this.c.resume();
    }
    if (focusChatInput) {
      (await showCopilotView(this.j, this.y))?.focusInput();
    }
  }
  async F() {
    let session;
    let entitlement;
    try {
      showCopilotView(this.j, this.y);
      session = await this.h.createSession(defaultChat2.providerId, defaultChat2.providerScopes[0]);
      entitlement = await this.f.forceResolveEntitlement(session);
    } catch (error) {
    }
    if (!session) {
      this.g.publicLog2("commandCenter.chatInstall", { installResult: "failedNotSignedIn", signedIn: false });
    }
    return { session, entitlement };
  }
  async G(session, entitlement) {
    const signedIn = !!session;
    let installResult = void 0;
    const wasInstalled = this.c.state.installed;
    let didSignUp = false;
    try {
      showCopilotView(this.j, this.y);
      if (entitlement !== ChatEntitlement.Limited && entitlement !== ChatEntitlement.Pro && entitlement !== ChatEntitlement.Unavailable) {
        didSignUp = await this.f.signUpLimited(session);
      }
      await this.m.install(defaultChat2.extensionId, {
        enable: true,
        isMachineScoped: false,
        installEverywhere: true,
        installPreReleaseVersion: this.n.quality !== "stable"
      }, isCopilotEditsViewActive(this.j) ? $0Nb : $9Nb);
      installResult = "installed";
    } catch (error) {
      this.r.error(`[chat setup] install: error ${error}`);
      installResult = $kb(error) ? "cancelled" : "failedInstall";
    } finally {
      if (wasInstalled && didSignUp) {
        this.w.executeCommand("github.copilot.refreshToken");
      }
      if (installResult === "installed") {
        await Promise.race([
          $Wh(5e3),
          // helps prevent flicker with sign-in welcome view
          Event2.toPromise(this.t.onDidChangeAgents)
          // https://github.com/microsoft/vscode-copilot/issues/9274
        ]);
      }
    }
    this.g.publicLog2("commandCenter.chatInstall", { installResult, signedIn });
  }
};
ChatSetupController = __decorate([
  __param(2, $zv),
  __param(3, $xS),
  __param(4, $uob),
  __param(5, $vzb),
  __param(6, $Vu),
  __param(7, $wn),
  __param(8, $TJ),
  __param(9, $ZO),
  __param(10, $vqb),
  __param(11, $sn),
  __param(12, $Vlb)
], ChatSetupController);
var ChatSetupWelcomeContent = class ChatSetupWelcomeContent2 extends $3c {
  constructor(a, b, c, f, g) {
    super();
    this.a = a;
    this.b = b;
    this.c = c;
    this.f = f;
    this.g = g;
    this.element = $(".chat-setup-view");
    this.h();
  }
  h() {
    const markdown = this.B(this.c.createInstance($Q_, {}));
    {
      const header = localize(5013, null, this.b.state.installed ? "command:github.copilot.open.walkthrough" : defaultChat2.documentationUrl);
      this.element.appendChild($("p")).appendChild(this.B(markdown.render(new $bm(header, { isTrusted: true }))).element);
      const features = this.element.appendChild($("div.chat-features-container"));
      this.element.appendChild(features);
      const featureChatContainer = features.appendChild($("div.chat-feature-container"));
      featureChatContainer.appendChild($C1($6l.code));
      const featureChatLabel = featureChatContainer.appendChild($("span"));
      featureChatLabel.textContent = localize(5014, null);
      const featureEditsContainer = features.appendChild($("div.chat-feature-container"));
      featureEditsContainer.appendChild($C1($6l.editSession));
      const featureEditsLabel = featureEditsContainer.appendChild($("span"));
      featureEditsLabel.textContent = localize(5015, null);
      const featureExploreContainer = features.appendChild($("div.chat-feature-container"));
      featureExploreContainer.appendChild($C1($6l.commentDiscussion));
      const featureExploreLabel = featureExploreContainer.appendChild($("span"));
      featureExploreLabel.textContent = localize(5016, null);
    }
    const limitedSkuHeader = "$(sparkle-filled) " + localize(5017, null, defaultChat2.skusDocumentationUrl);
    const limitedSkuHeaderContainer = this.element.appendChild($("p"));
    limitedSkuHeaderContainer.appendChild(this.B(markdown.render(new $bm(limitedSkuHeader, { isTrusted: true, supportThemeIcons: true }))).element);
    const actions = [];
    if (this.b.state.installed) {
      actions.push($Zm({ id: "chatSetup.signInGh", label: localize(5018, null), run: () => this.g.executeCommand("github.copilotChat.signIn") }));
      actions.push($Zm({ id: "chatSetup.signInGhe", label: localize(5019, null), run: () => this.g.executeCommand("github.copilotChat.signInGHE") }));
    }
    const buttonContainer = this.element.appendChild($("p"));
    buttonContainer.classList.add("button-container");
    const button = this.B(actions.length === 0 ? new $k2(buttonContainer, {
      supportIcons: true,
      ...$q$
    }) : new $l2(buttonContainer, {
      actions,
      addPrimaryActionToDropdown: false,
      contextMenuProvider: this.f,
      supportIcons: true,
      ...$q$
    }));
    this.B(button.onDidClick(() => this.a.setup()));
    const terms = localize(5020, null, defaultChat2.termsStatementUrl, defaultChat2.privacyStatementUrl);
    this.element.appendChild($("p")).appendChild(this.B(markdown.render(new $bm(terms, { isTrusted: true }))).element);
    this.B(Event2.runAndSubscribe(this.a.onDidChange, () => this.j(limitedSkuHeaderContainer, button)));
  }
  j(limitedSkuHeaderContainer, button) {
    let showLimitedSkuHeader;
    let buttonLabel;
    switch (this.b.state.entitlement) {
      case ChatEntitlement.Unknown:
        showLimitedSkuHeader = true;
        buttonLabel = this.b.state.registered ? localize(5021, null) : localize(5022, null);
        break;
      case ChatEntitlement.Unresolved:
        showLimitedSkuHeader = true;
        buttonLabel = this.b.state.registered ? localize(5023, null) : localize(5024, null);
        break;
      case ChatEntitlement.Available:
      case ChatEntitlement.Limited:
        showLimitedSkuHeader = true;
        buttonLabel = localize(5025, null);
        break;
      case ChatEntitlement.Pro:
      case ChatEntitlement.Unavailable:
        showLimitedSkuHeader = false;
        buttonLabel = localize(5026, null);
        break;
    }
    switch (this.a.step) {
      case ChatSetupStep.SigningIn:
        buttonLabel = localize(5027, null, defaultChat2.providerName);
        break;
      case ChatSetupStep.Installing:
        buttonLabel = localize(5028, null);
        break;
    }
    $gk(showLimitedSkuHeader, limitedSkuHeaderContainer);
    button.label = buttonLabel;
    button.enabled = this.a.step === ChatSetupStep.Initial;
  }
};
ChatSetupWelcomeContent = __decorate([
  __param(2, $Pk),
  __param(3, $50),
  __param(4, $sn)
], ChatSetupWelcomeContent);
var ChatSetupContext = class ChatSetupContext2 extends $3c {
  static {
    ChatSetupContext_1 = this;
  }
  static {
    this.a = "chat.setupContext";
  }
  get state() {
    return this.m ?? this.j;
  }
  constructor(s, t, u, w, y, z, C) {
    super();
    this.s = s;
    this.t = t;
    this.u = u;
    this.w = w;
    this.y = y;
    this.z = z;
    this.C = C;
    this.b = ChatContextKeys.Setup.canSignUp.bindTo(this.s);
    this.c = ChatContextKeys.Setup.signedOut.bindTo(this.s);
    this.f = ChatContextKeys.Setup.limited.bindTo(this.s);
    this.g = ChatContextKeys.Setup.triggered.bindTo(this.s);
    this.h = ChatContextKeys.Setup.installed.bindTo(this.s);
    this.j = this.t.getObject(
      ChatSetupContext_1.a,
      0
      /* StorageScope.PROFILE */
    ) ?? { entitlement: ChatEntitlement.Unknown };
    this.m = void 0;
    this.n = this.B(new $ze());
    this.onDidChange = this.n.event;
    this.r = void 0;
    this.D();
    this.G();
  }
  async D() {
    this.B(this.w.onDidChangeExtensions((result) => {
      for (const extension of result.removed) {
        if ($5z.equals(defaultChat2.extensionId, extension.identifier)) {
          this.update({ installed: false });
          break;
        }
      }
      for (const extension of result.added) {
        if ($5z.equals(defaultChat2.extensionId, extension.identifier)) {
          this.update({ installed: true });
          break;
        }
      }
    }));
    const extensions = await this.y.getInstalled();
    const defaultChatExtension = extensions.find((value) => $5z.equals(value.identifier.id, defaultChat2.extensionId));
    this.update({ installed: !!defaultChatExtension && this.z.isEnabled(defaultChatExtension) });
  }
  update(context) {
    this.C.trace(`[chat setup] update(): ${JSON.stringify(context)}`);
    if (typeof context.installed === "boolean") {
      this.j.installed = context.installed;
      if (context.installed) {
        context.triggered = true;
      }
    }
    if (typeof context.triggered === "boolean") {
      this.j.triggered = context.triggered;
    }
    if (typeof context.entitlement === "number") {
      this.j.entitlement = context.entitlement;
      if (this.j.entitlement === ChatEntitlement.Limited || this.j.entitlement === ChatEntitlement.Pro) {
        this.j.registered = true;
      } else if (this.j.entitlement === ChatEntitlement.Available) {
        this.j.registered = false;
      }
    }
    this.t.store(
      ChatSetupContext_1.a,
      this.j,
      0,
      1
      /* StorageTarget.MACHINE */
    );
    return this.F();
  }
  async F() {
    await this.r?.wait();
    this.G();
  }
  G() {
    this.C.trace(`[chat setup] updateContext(): ${JSON.stringify(this.j)}`);
    if (this.j.triggered && !this.j.installed) {
      this.t.remove(
        "chat.welcomeMessageContent.panel",
        -1
        /* StorageScope.APPLICATION */
      );
      this.t.remove(
        "interactive.sessions",
        this.u.getWorkspace().folders.length ? 1 : -1
        /* StorageScope.APPLICATION */
      );
    }
    this.c.set(this.j.entitlement === ChatEntitlement.Unknown);
    this.b.set(this.j.entitlement === ChatEntitlement.Available);
    this.f.set(this.j.entitlement === ChatEntitlement.Limited);
    this.g.set(!!this.j.triggered);
    this.h.set(!!this.j.installed);
    this.n.fire();
  }
  suspend() {
    this.m = { ...this.j };
    this.r = new $Uh();
  }
  resume() {
    this.m = void 0;
    this.r?.open();
    this.r = void 0;
  }
};
ChatSetupContext = ChatSetupContext_1 = __decorate([
  __param(0, $on),
  __param(1, $jv),
  __param(2, $Zk),
  __param(3, $wN),
  __param(4, $sA),
  __param(5, $qzb),
  __param(6, $wn)
], ChatSetupContext);
function isCopilotEditsViewActive(viewsService) {
  return viewsService.getFocusedView()?.id === $0Nb;
}
function showCopilotView(viewsService, layoutService) {
  if (layoutService.activeContainer !== layoutService.mainContainer) {
    layoutService.mainContainer.focus();
  }
  if (isCopilotEditsViewActive(viewsService)) {
    return $4Nb(viewsService);
  } else {
    return $3Nb(viewsService);
  }
}

// out-build/vs/workbench/contrib/chat/browser/chatViewPane.js
var $ENb = "workbench.panel.chat";
var $FNb = "workbench.panel.chatEditing";
var $GNb = class $GNb2 extends $_ob {
  get widget() {
    return this.a;
  }
  constructor(j, options3, keybindingService, contextMenuService, configurationService, contextKeyService, viewDescriptorService, instantiationService, openerService, themeService, telemetryService, hoverService, m, n, r2, s, t) {
    super(options3, keybindingService, contextMenuService, configurationService, contextKeyService, viewDescriptorService, instantiationService, openerService, themeService, telemetryService, hoverService);
    this.j = j;
    this.m = m;
    this.n = n;
    this.r = r2;
    this.s = s;
    this.t = t;
    this.b = this.B(new $2c());
    this.g = false;
    this.h = false;
    this.c = new $Slb("interactive-session-view-" + $XO + (this.j.location === ChatAgentLocation.EditingSession ? `-edits` : ""), this.m);
    this.f = this.c.getMemento(
      1,
      1
      /* StorageTarget.MACHINE */
    );
    this.B(this.r.onDidChangeAgents(() => {
      if (this.r.getDefaultAgent(this.j?.location)) {
        if (!this.a?.viewModel) {
          const sessionId = this.ab();
          const model = sessionId ? this.n.getOrRestoreSession(sessionId) : void 0;
          const wasVisible = this.a.visible;
          try {
            this.a.setVisible(false);
            this.L(model);
            this.g = false;
            this.h = false;
            this.eb.fire();
          } finally {
            this.widget.setVisible(wasVisible);
          }
        }
      } else if (this.a?.viewModel?.initState === ChatModelInitState.Initialized) {
        this.h = true;
      }
      this.eb.fire();
    }));
    this.B(this.Bb.onDidChangeContext((e) => {
      if (e.affectsSome($ANb)) {
        this.eb.fire();
      }
    }));
  }
  getActionsContext() {
    return this.widget?.viewModel ? {
      sessionId: this.widget.viewModel.sessionId,
      $mid: 19
      /* MarshalledId.ChatViewContext */
    } : void 0;
  }
  L(model, viewState) {
    this.b.clear();
    model = model ?? (this.n.transferredSessionData?.sessionId ? this.n.getOrRestoreSession(this.n.transferredSessionData.sessionId) : this.n.startSession(this.j.location, CancellationToken.None));
    if (!model) {
      throw new Error("Could not start chat session");
    }
    if (viewState) {
      this.cc(viewState);
    }
    this.f.sessionId = model.sessionId;
    this.a.setModel(model, { ...this.f });
    this.$b();
  }
  shouldShowWelcome() {
    const showSetup = this.Bb.contextMatchesRules($BNb);
    const noPersistedSessions = !this.n.hasSessions();
    const shouldShow = this.h || !this.a?.viewModel && noPersistedSessions || this.g || showSetup;
    this.s.trace(`ChatViewPane#shouldShowWelcome(${this.j.location}) = ${shouldShow}: didUnregister=${this.h} || noViewModel:${!this.a?.viewModel} && noPersistedSessions=${noPersistedSessions} || defaultParticipantRegistrationFailed=${this.g} || showSetup=${showSetup}`);
    return !!shouldShow;
  }
  ab() {
    let sessionId;
    if (this.n.transferredSessionData) {
      sessionId = this.n.transferredSessionData.sessionId;
      this.f.inputValue = this.n.transferredSessionData.inputValue;
    } else {
      sessionId = this.f.sessionId;
    }
    return sessionId;
  }
  W(parent) {
    try {
      super.W(parent);
      this.B(this.Db.createInstance($nNb, parent, this, this.j.location));
      const scopedInstantiationService = this.B(this.Db.createChild(new $Ok([$on, this.xb])));
      const locationBasedColors = this.Xb();
      const editorOverflowNode = this.t.getContainer(getWindow(parent)).appendChild($(".chat-editor-overflow.monaco-editor"));
      this.B({ dispose: () => editorOverflowNode.remove() });
      this.a = this.B(scopedInstantiationService.createInstance($qNb, this.j.location, { viewId: this.id }, {
        autoScroll: this.j.location === ChatAgentLocation.EditingSession,
        renderFollowups: this.j.location === ChatAgentLocation.Panel,
        supportsFileReferences: true,
        supportsAdditionalParticipants: this.j.location === ChatAgentLocation.Panel,
        rendererOptions: {
          renderCodeBlockPills: this.j.location === ChatAgentLocation.EditingSession,
          renderTextEditsAsSummary: (uri) => {
            return this.j.location === ChatAgentLocation.EditingSession;
          }
        },
        enableImplicitContext: this.j.location === ChatAgentLocation.Panel,
        editorOverflowWidgetsDomNode: editorOverflowNode
      }, {
        listForeground: $Qnb,
        listBackground: locationBasedColors.background,
        overlayBackground: locationBasedColors.overlayBackground,
        inputEditorBackground: locationBasedColors.background,
        resultEditorBackground: $Ko
      }));
      this.B(this.onDidChangeBodyVisibility((visible) => {
        this.a.setVisible(visible);
      }));
      this.B(this.a.onDidClear(() => this.ac()));
      this.a.render(parent);
      const sessionId = this.ab();
      const disposeListener = this.B(this.n.onDidDisposeSession((e) => {
        if (e.reason === "initializationFailed") {
          this.g = true;
          disposeListener?.dispose();
          this.eb.fire();
        }
      }));
      const model = sessionId ? this.n.getOrRestoreSession(sessionId) : void 0;
      this.L(model);
    } catch (e) {
      this.s.error(e);
      throw e;
    }
  }
  acceptInput(query) {
    this.a.acceptInput(query);
  }
  ac() {
    if (this.widget.viewModel) {
      this.n.clearSession(this.widget.viewModel.sessionId);
    }
    this.cc();
    this.L(void 0);
    this.$b();
  }
  loadSession(sessionId, viewState) {
    if (this.widget.viewModel) {
      this.n.clearSession(this.widget.viewModel.sessionId);
    }
    const newModel = this.n.getOrRestoreSession(sessionId);
    this.L(newModel, viewState);
  }
  focusInput() {
    this.a.focusInput();
  }
  focus() {
    super.focus();
    this.a.focusInput();
  }
  X(height, width2) {
    super.X(height, width2);
    this.a.layout(height, width2);
  }
  saveState() {
    if (this.a) {
      this.a.saveState();
      this.cc();
      this.c.saveMemento();
    }
    super.saveState();
  }
  cc(viewState) {
    const newViewState = viewState ?? this.a.getViewState();
    for (const [key2, value] of Object.entries(newViewState)) {
      this.f[key2] = value;
    }
  }
};
$GNb = __decorate([
  __param(2, $Ty),
  __param(3, $50),
  __param(4, $kl),
  __param(5, $on),
  __param(6, $$M),
  __param(7, $Pk),
  __param(8, $O4),
  __param(9, $gs),
  __param(10, $zv),
  __param(11, $5$),
  __param(12, $jv),
  __param(13, $qO),
  __param(14, $ZO),
  __param(15, $wn),
  __param(16, $Ulb)
], $GNb);

// out-build/vs/workbench/contrib/chat/browser/chatParticipant.contribution.js
var chatParticipantExtensionPoint = $tN.registerExtensionPoint({
  extensionPoint: "chatParticipants",
  jsonSchema: {
    description: localize(4958, null),
    type: "array",
    items: {
      additionalProperties: false,
      type: "object",
      defaultSnippets: [{ body: { name: "", description: "" } }],
      required: ["name", "id"],
      properties: {
        id: {
          description: localize(4959, null),
          type: "string"
        },
        name: {
          description: localize(4960, null),
          type: "string",
          pattern: "^[\\w-]+$"
        },
        fullName: {
          markdownDescription: localize(4961, null, "`name`"),
          type: "string"
        },
        description: {
          description: localize(4962, null),
          type: "string"
        },
        isSticky: {
          description: localize(4963, null),
          type: "boolean"
        },
        sampleRequest: {
          description: localize(4964, null),
          type: "string"
        },
        when: {
          description: localize(4965, null),
          type: "string"
        },
        disambiguation: {
          description: localize(4966, null),
          type: "array",
          items: {
            additionalProperties: false,
            type: "object",
            defaultSnippets: [{ body: { category: "", description: "", examples: [] } }],
            required: ["category", "description", "examples"],
            properties: {
              category: {
                markdownDescription: localize(4967, null),
                type: "string"
              },
              description: {
                description: localize(4968, null),
                type: "string"
              },
              examples: {
                description: localize(4969, null),
                type: "array"
              }
            }
          }
        },
        commands: {
          markdownDescription: localize(4970, null),
          type: "array",
          items: {
            additionalProperties: false,
            type: "object",
            defaultSnippets: [{ body: { name: "", description: "" } }],
            required: ["name"],
            properties: {
              name: {
                description: localize(4971, null),
                type: "string"
              },
              description: {
                description: localize(4972, null),
                type: "string"
              },
              when: {
                description: localize(4973, null),
                type: "string"
              },
              sampleRequest: {
                description: localize(4974, null),
                type: "string"
              },
              isSticky: {
                description: localize(4975, null),
                type: "boolean"
              },
              disambiguation: {
                description: localize(4976, null),
                type: "array",
                items: {
                  additionalProperties: false,
                  type: "object",
                  defaultSnippets: [{ body: { category: "", description: "", examples: [] } }],
                  required: ["category", "description", "examples"],
                  properties: {
                    category: {
                      markdownDescription: localize(4977, null),
                      type: "string"
                    },
                    description: {
                      description: localize(4978, null),
                      type: "string"
                    },
                    examples: {
                      description: localize(4979, null),
                      type: "array"
                    }
                  }
                }
              }
            }
          }
        }
      }
    }
  },
  activationEventsGenerator: (contributions, result) => {
    for (const contrib of contributions) {
      result.push(`onChatParticipant:${contrib.id}`);
    }
  }
});
var $I8b = class $I8b2 {
  static {
    this.ID = "workbench.contrib.chatExtensionPointHandler";
  }
  constructor(c, f) {
    this.c = c;
    this.f = f;
    this.b = new $_c();
    this.a = this.h();
    this.i();
    this.j();
    this.g();
  }
  g() {
    chatParticipantExtensionPoint.setHandler((extensions, delta) => {
      for (const extension of delta.added) {
        for (const providerDescriptor of extension.value) {
          if (!providerDescriptor.name?.match(/^[\w-]+$/)) {
            this.f.error(`Extension '${extension.description.identifier.value}' CANNOT register participant with invalid name: ${providerDescriptor.name}. Name must match /^[\\w-]+$/.`);
            continue;
          }
          if (providerDescriptor.fullName && $xg.getInstance(/* @__PURE__ */ new Set()).containsAmbiguousCharacter(providerDescriptor.fullName)) {
            this.f.error(`Extension '${extension.description.identifier.value}' CANNOT register participant with fullName that contains ambiguous characters: ${providerDescriptor.fullName}.`);
            continue;
          }
          if (providerDescriptor.fullName && $yg.containsInvisibleCharacter(providerDescriptor.fullName.replace(/ /g, ""))) {
            this.f.error(`Extension '${extension.description.identifier.value}' CANNOT register participant with fullName that contains invisible characters: ${providerDescriptor.fullName}.`);
            continue;
          }
          if (providerDescriptor.isDefault && !$zN(extension.description, "defaultChatParticipant")) {
            this.f.error(`Extension '${extension.description.identifier.value}' CANNOT use API proposal: defaultChatParticipant.`);
            continue;
          }
          if ((providerDescriptor.defaultImplicitVariables || providerDescriptor.locations) && !$zN(extension.description, "chatParticipantAdditions")) {
            this.f.error(`Extension '${extension.description.identifier.value}' CANNOT use API proposal: chatParticipantAdditions.`);
            continue;
          }
          if (!providerDescriptor.id || !providerDescriptor.name) {
            this.f.error(`Extension '${extension.description.identifier.value}' CANNOT register participant without both id and name.`);
            continue;
          }
          const participantsDisambiguation = [];
          if (providerDescriptor.disambiguation?.length) {
            participantsDisambiguation.push(...providerDescriptor.disambiguation.map((d) => ({
              ...d,
              category: d.category ?? d.categoryName
            })));
          }
          try {
            const store = new $2c();
            store.add(this.c.registerAgent(providerDescriptor.id, {
              extensionId: extension.description.identifier,
              publisherDisplayName: extension.description.publisherDisplayName ?? extension.description.publisher,
              // May not be present in OSS
              extensionPublisherId: extension.description.publisher,
              extensionDisplayName: extension.description.displayName ?? extension.description.name,
              id: providerDescriptor.id,
              description: providerDescriptor.description,
              when: providerDescriptor.when,
              metadata: {
                isSticky: providerDescriptor.isSticky,
                sampleRequest: providerDescriptor.sampleRequest
              },
              name: providerDescriptor.name,
              fullName: providerDescriptor.fullName,
              isDefault: providerDescriptor.isDefault,
              locations: $Qb(providerDescriptor.locations) ? providerDescriptor.locations.map(ChatAgentLocation.fromRaw) : [ChatAgentLocation.Panel],
              slashCommands: providerDescriptor.commands ?? [],
              disambiguation: $Mb(participantsDisambiguation.flat())
            }));
            this.b.set(getParticipantKey(extension.description.identifier, providerDescriptor.id), store);
          } catch (e) {
            this.f.error(`Failed to register participant ${providerDescriptor.id}: ${$1m(e, true)}`);
          }
        }
      }
      for (const extension of delta.removed) {
        for (const providerDescriptor of extension.value) {
          this.b.deleteAndDispose(getParticipantKey(extension.description.identifier, providerDescriptor.id));
        }
      }
    });
  }
  h() {
    const title = localize2(4984, "Chat");
    const icon2 = $6l.commentDiscussion;
    const viewContainerId = $ENb;
    const viewContainer5 = $Wn.as(Extensions5.ViewContainersRegistry).registerViewContainer({
      id: viewContainerId,
      title,
      icon: icon2,
      ctorDescriptor: new $Nk($oqb, [viewContainerId, { mergeViewWithContainerWhenSingleView: true }]),
      storageId: viewContainerId,
      hideIfEmpty: true,
      order: 100
    }, 2, { doNotRegisterOpenCommand: true });
    return viewContainer5;
  }
  i() {
    const viewDescriptor3 = [{
      id: $9Nb,
      containerIcon: this.a.icon,
      containerTitle: this.a.title.value,
      singleViewPaneContainerTitle: this.a.title.value,
      name: localize2(4985, "Chat"),
      canToggleVisibility: false,
      canMoveView: true,
      openCommandActionDescriptor: {
        id: $ENb,
        title: this.a.title,
        mnemonicTitle: localize(4980, null),
        keybindings: {
          primary: 2048 | 512 | 39,
          mac: {
            primary: 2048 | 256 | 39
            /* KeyCode.KeyI */
          }
        },
        order: 1
      },
      ctorDescriptor: new $Nk($GNb, [{ location: ChatAgentLocation.Panel }]),
      when: $7m.or($7m.and($7m.has("config.chat.experimental.offerSetup"), ChatContextKeys.Setup.triggered), ChatContextKeys.Setup.installed, ChatContextKeys.panelParticipantRegistered, ChatContextKeys.extensionInvalid)
    }];
    $Wn.as(Extensions5.ViewsRegistry).registerViews(viewDescriptor3, this.a);
    return $1c(() => {
      $Wn.as(Extensions5.ViewsRegistry).deregisterViews(viewDescriptor3, this.a);
    });
  }
  j() {
    const title = localize2(4986, "Copilot Edits");
    const icon2 = $6l.editSession;
    const viewContainerId = $FNb;
    const viewContainer5 = $Wn.as(Extensions5.ViewContainersRegistry).registerViewContainer({
      id: viewContainerId,
      title,
      icon: icon2,
      ctorDescriptor: new $Nk($oqb, [viewContainerId, { mergeViewWithContainerWhenSingleView: true }]),
      storageId: viewContainerId,
      hideIfEmpty: true,
      order: 101
    }, 2, { doNotRegisterOpenCommand: true });
    const id2 = "workbench.panel.chat.view.edits";
    const viewDescriptor3 = [{
      id: id2,
      containerIcon: viewContainer5.icon,
      containerTitle: title.value,
      singleViewPaneContainerTitle: title.value,
      name: { value: title.value, original: title.value },
      canToggleVisibility: false,
      canMoveView: true,
      openCommandActionDescriptor: {
        id: viewContainerId,
        title,
        mnemonicTitle: localize(4981, null),
        keybindings: {
          primary: 2048 | 1024 | 39,
          linux: {
            primary: 2048 | 512 | 1024 | 39
            /* KeyCode.KeyI */
          }
        },
        order: 2
      },
      ctorDescriptor: new $Nk($GNb, [{ location: ChatAgentLocation.EditingSession }]),
      when: $7m.or(ChatContextKeys.Setup.installed, ChatContextKeys.editingParticipantRegistered)
    }];
    $Wn.as(Extensions5.ViewsRegistry).registerViews(viewDescriptor3, viewContainer5);
    return $1c(() => {
      $Wn.as(Extensions5.ViewContainersRegistry).deregisterViewContainer(viewContainer5);
      $Wn.as(Extensions5.ViewsRegistry).deregisterViews(viewDescriptor3, viewContainer5);
    });
  }
};
$I8b = __decorate([
  __param(0, $ZO),
  __param(1, $wn)
], $I8b);
function getParticipantKey(extensionId, participantName) {
  return `${extensionId.value}_${participantName}`;
}
var $J8b = class $J8b2 extends $3c {
  static {
    this.ID = "workbench.contrib.chatCompatNotifier";
  }
  constructor(extensionsWorkbenchService, contextKeyService, b) {
    super();
    this.b = b;
    this.a = false;
    const isInvalid = ChatContextKeys.extensionInvalid.bindTo(contextKeyService);
    this.B(Event2.runAndSubscribe(extensionsWorkbenchService.onDidChangeExtensionsNotification, () => {
      const notification = extensionsWorkbenchService.getExtensionsNotification();
      const chatExtension = notification?.extensions.find((ext) => $5z.equals(ext.identifier.id, this.b.defaultChatAgent?.chatExtensionId));
      if (chatExtension) {
        isInvalid.set(true);
        this.c(chatExtension);
      } else {
        isInvalid.set(false);
      }
    }));
  }
  c(chatExtension) {
    if (this.a) {
      return;
    }
    this.a = true;
    const showExtensionLabel = localize(4982, null);
    const mainMessage = localize(4983, null, this.b.nameLong);
    const commandButton = `[${showExtensionLabel}](command:${$GDb}?${encodeURIComponent(JSON.stringify([[this.b.defaultChatAgent?.chatExtensionId]]))})`;
    const versionMessage = `Copilot Chat version: ${chatExtension.version}`;
    const viewsRegistry8 = $Wn.as(Extensions5.ViewsRegistry);
    this.B(viewsRegistry8.registerViewWelcomeContent($9Nb, {
      content: [mainMessage, commandButton, versionMessage].join("\n\n"),
      when: ChatContextKeys.extensionInvalid
    }));
  }
};
$J8b = __decorate([
  __param(0, $vzb),
  __param(1, $on),
  __param(2, $Vu)
], $J8b);

// out-build/vs/workbench/contrib/chat/browser/chatQuick.js
var QuickChat_1;
var $K8b = class $K8b2 extends $3c {
  constructor(g, h3, j) {
    super();
    this.g = g;
    this.h = h3;
    this.j = j;
    this.a = this.B(new $ze());
    this.onDidClose = this.a.event;
  }
  get enabled() {
    return !!this.h.isEnabled(ChatAgentLocation.Panel);
  }
  get focused() {
    const widget = this.b?.widget;
    if (!widget) {
      return false;
    }
    return $Nj(widget);
  }
  toggle(options3) {
    if (this.focused && !options3?.query) {
      this.close();
    } else {
      this.open(options3);
      if (options3?.isPartialQuery) {
        const disposable = this.q.add(Event2.once(this.onDidClose)(() => {
          this.c?.clearValue();
          this.q.delete(disposable);
        }));
      }
    }
  }
  open(options3) {
    if (this.b) {
      if (this.c && options3?.query) {
        this.c.focus();
        this.c.setValue(options3.query, options3.selection);
        if (!options3.isPartialQuery) {
          this.c.acceptInput();
        }
        return;
      }
      return this.focus();
    }
    const disposableStore = new $2c();
    this.b = this.g.createQuickWidget();
    this.b.contextKey = "chatInputVisible";
    this.b.ignoreFocusOut = true;
    disposableStore.add(this.b);
    this.f ??= $(".interactive-session");
    this.b.widget = this.f;
    this.b.show();
    if (!this.c) {
      this.c = this.j.createInstance(QuickChat);
      this.c.render(this.f);
    } else {
      this.c.show();
    }
    disposableStore.add(this.b.onDidHide(() => {
      disposableStore.dispose();
      this.c.hide();
      this.b = void 0;
      this.a.fire();
    }));
    this.c.focus();
    if (options3?.query) {
      this.c.setValue(options3.query, options3.selection);
      if (!options3.isPartialQuery) {
        this.c.acceptInput();
      }
    }
  }
  focus() {
    this.c?.focus();
  }
  close() {
    this.b?.dispose();
    this.b = void 0;
  }
  async openInChatView() {
    await this.c?.openChatView();
    this.close();
  }
};
$K8b = __decorate([
  __param(0, $1M),
  __param(1, $qO),
  __param(2, $Pk)
], $K8b);
var QuickChat = class QuickChat2 extends $3c {
  static {
    QuickChat_1 = this;
  }
  static {
    this.DEFAULT_MIN_HEIGHT = 200;
  }
  static {
    this.a = 100;
  }
  constructor(m, n, r2, s, t) {
    super();
    this.m = m;
    this.n = n;
    this.r = r2;
    this.s = s;
    this.t = t;
    this.h = this.B(new $4c());
    this.j = false;
  }
  clear() {
    this.f?.dispose();
    this.f = void 0;
    this.y();
    this.b.inputEditor.setValue("");
  }
  focus(selection) {
    if (this.b) {
      this.b.focusInput();
      const value = this.b.inputEditor.getValue();
      if (value) {
        this.b.inputEditor.setSelection(selection ?? {
          startLineNumber: 1,
          startColumn: 1,
          endLineNumber: 1,
          endColumn: value.length + 1
        });
      }
    }
  }
  hide() {
    this.b.setVisible(false);
    this.h.value = $Xh(() => {
      this.h.clear();
    }, 30 * 1e3);
  }
  show() {
    this.b.setVisible(true);
    if (this.j) {
      this.j = false;
      this.b.updateDynamicChatTreeItemLayout(2, this.u);
    }
    if (!this.h.value) {
      this.b.layoutDynamicChatTreeItemMode();
    }
  }
  render(parent) {
    if (this.b) {
      throw new Error("Cannot render quick chat twice");
    }
    const scopedInstantiationService = this.B(this.m.createChild(new $Ok([
      $on,
      this.B(this.n.createScoped(parent))
    ])));
    this.b = this.B(scopedInstantiationService.createInstance($qNb, ChatAgentLocation.Panel, { isQuickChat: true }, { autoScroll: true, renderInputOnTop: true, renderStyle: "compact", menus: { inputSideToolbar: $bJ.ChatInputSide }, enableImplicitContext: true }, {
      listForeground: $Wr,
      listBackground: $Vr,
      overlayBackground: $Cmb,
      inputEditorBackground: $xq,
      resultEditorBackground: $Ko
    }));
    this.b.render(parent);
    this.b.setVisible(true);
    this.b.setDynamicChatTreeItemLayout(2, this.u);
    this.y();
    this.c = this.B(new $q2(parent, { getHorizontalSashTop: () => parent.offsetHeight }, {
      orientation: 1
      /* Orientation.HORIZONTAL */
    }));
    this.w(parent);
  }
  get u() {
    return this.s.mainContainerDimension.height - QuickChat_1.a;
  }
  w(parent) {
    this.B(this.s.onDidLayoutMainContainer(() => {
      if (this.b.visible) {
        this.b.updateDynamicChatTreeItemLayout(2, this.u);
      } else {
        this.j = true;
      }
    }));
    this.B(this.b.inputEditor.onDidChangeModelContent((e) => {
      this.g = this.b.inputEditor.getValue();
    }));
    this.B(this.b.onDidClear(() => this.clear()));
    this.B(this.b.onDidChangeHeight((e) => this.c.layout()));
    const width2 = parent.offsetWidth;
    this.B(this.c.onDidStart(() => {
      this.b.isDynamicChatTreeItemLayoutEnabled = false;
    }));
    this.B(this.c.onDidChange((e) => {
      if (e.currentY < QuickChat_1.DEFAULT_MIN_HEIGHT || e.currentY > this.u) {
        return;
      }
      this.b.layout(e.currentY, width2);
      this.c.layout();
    }));
    this.B(this.c.onDidReset(() => {
      this.b.isDynamicChatTreeItemLayoutEnabled = true;
      this.b.layoutDynamicChatTreeItemMode();
    }));
  }
  async acceptInput() {
    return this.b.acceptInput();
  }
  async openChatView() {
    const widget = await $3Nb(this.t);
    if (!widget?.viewModel || !this.f) {
      return;
    }
    for (const request of this.f.getRequests()) {
      if (request.response?.response.value || request.response?.result) {
        const message = [];
        for (const item of request.response.response.value) {
          if (item.kind === "textEditGroup") {
            for (const group2 of item.edits) {
              message.push({
                kind: "textEdit",
                edits: group2,
                uri: item.uri
              });
            }
          } else {
            message.push(item);
          }
        }
        this.r.addCompleteRequest(widget.viewModel.sessionId, request.message, request.variableData, request.attempt, {
          message,
          result: request.response.result,
          followups: request.response.followups
        });
      } else if (request.message) {
      }
    }
    const value = this.b.inputEditor.getValue();
    if (value) {
      widget.inputEditor.setValue(value);
    }
    widget.focusInput();
  }
  setValue(value, selection) {
    this.b.inputEditor.setValue(value);
    this.focus(selection);
  }
  clearValue() {
    this.b.inputEditor.setValue("");
  }
  y() {
    this.f ??= this.r.startSession(ChatAgentLocation.Panel, CancellationToken.None);
    if (!this.f) {
      throw new Error("Could not start chat session");
    }
    this.b.setModel(this.f, { inputValue: this.g });
  }
};
QuickChat = QuickChat_1 = __decorate([
  __param(0, $Pk),
  __param(1, $on),
  __param(2, $qO),
  __param(3, $Ulb),
  __param(4, $uob)
], QuickChat);

// out-build/vs/workbench/contrib/chat/browser/chatResponseAccessibleView.js
var $L8b = class {
  constructor() {
    this.priority = 100;
    this.name = "panelChat";
    this.type = "view";
    this.when = ChatContextKeys.inChatSession;
  }
  getProvider(accessor) {
    const widgetService = accessor.get($2Nb);
    const widget = widgetService.lastFocusedWidget;
    if (!widget) {
      return;
    }
    const chatInputFocused = widget.hasInputFocus();
    if (chatInputFocused) {
      widget.focusLastMessage();
    }
    const verifiedWidget = widget;
    const focusedItem = verifiedWidget.getFocus();
    if (!focusedItem) {
      return;
    }
    return new ChatResponseAccessibleProvider(verifiedWidget, focusedItem, chatInputFocused);
  }
};
var ChatResponseAccessibleProvider = class extends $3c {
  constructor(b, item, c) {
    super();
    this.b = b;
    this.c = c;
    this.id = "panelChat";
    this.verbositySettingKey = "accessibility.verbosity.panelChat";
    this.options = {
      type: "view"
      /* AccessibleViewType.View */
    };
    this.a = item;
  }
  provideContent() {
    return this.f(this.a);
  }
  f(item) {
    let responseContent = $asb(item) ? item.response.toString() : "";
    if (!responseContent && "errorDetails" in item && item.errorDetails) {
      responseContent = item.errorDetails.message;
    }
    return $G1(new $bm(responseContent), true);
  }
  onClose() {
    this.b.reveal(this.a);
    if (this.c) {
      this.b.focusInput();
    } else {
      this.b.focus(this.a);
    }
  }
  provideNextContent() {
    const next = this.b.getSibling(this.a, "next");
    if (next) {
      this.a = next;
      return this.f(next);
    }
    return;
  }
  providePreviousContent() {
    const previous = this.b.getSibling(this.a, "previous");
    if (previous) {
      this.a = previous;
      return this.f(previous);
    }
    return;
  }
};

// out-build/vs/workbench/contrib/chat/browser/chatVariables.js
var $M8b = class $M8b2 {
  constructor(d, e) {
    this.d = d;
    this.e = e;
    this.c = /* @__PURE__ */ new Map();
  }
  async resolveVariables(prompt, attachedContextVariables, model, progress, token) {
    let resolvedVariables = [];
    const jobs = [];
    prompt.parts.forEach((part, i2) => {
      if (part instanceof $zO) {
        const data = this.c.get(part.variableName.toLowerCase());
        if (data) {
          const references = [];
          const variableProgressCallback = (item) => {
            if (item.kind === "reference") {
              references.push(item);
              return;
            }
            progress(item);
          };
          jobs.push(data.resolver(prompt.text, part.variableArg, model, variableProgressCallback, token).then((value) => {
            if (value) {
              resolvedVariables[i2] = { id: data.data.id, modelDescription: data.data.modelDescription, name: part.variableName, range: part.range, value, references, fullName: data.data.fullName, icon: data.data.icon };
            }
          }).catch($hb));
        }
      } else if (part instanceof $EO) {
        resolvedVariables[i2] = { id: part.id, name: part.referenceText, range: part.range, value: part.data, fullName: part.fullName, icon: part.icon, isFile: part.isFile };
      } else if (part instanceof $AO) {
        resolvedVariables[i2] = { id: part.toolId, name: part.toolName, range: part.range, value: void 0, isTool: true, icon: ThemeIcon.isThemeIcon(part.icon) ? part.icon : void 0, fullName: part.displayName };
      }
    });
    const resolvedAttachedContext = [];
    attachedContextVariables?.forEach((attachment, i2) => {
      const data = this.c.get(attachment.name?.toLowerCase());
      if (data) {
        const references = [];
        const variableProgressCallback = (item) => {
          if (item.kind === "reference") {
            references.push(item);
            return;
          }
          progress(item);
        };
        jobs.push(data.resolver(prompt.text, "", model, variableProgressCallback, token).then((value) => {
          if (value) {
            resolvedAttachedContext[i2] = { id: data.data.id, modelDescription: data.data.modelDescription, name: attachment.name, fullName: attachment.fullName, range: attachment.range, value, references, icon: attachment.icon };
          }
        }).catch($hb));
      } else if (attachment.isDynamic || attachment.isTool) {
        resolvedAttachedContext[i2] = attachment;
      }
    });
    await Promise.allSettled(jobs);
    resolvedVariables = $Mb(resolvedVariables);
    resolvedVariables.sort((a, b) => b.range.start - a.range.start);
    resolvedVariables.push(...$Mb(resolvedAttachedContext));
    return {
      variables: resolvedVariables
    };
  }
  async resolveVariable(variableName, promptText, model, progress, token) {
    const data = this.c.get(variableName.toLowerCase());
    if (!data) {
      return void 0;
    }
    return await data.resolver(promptText, void 0, model, progress, token);
  }
  hasVariable(name) {
    return this.c.has(name.toLowerCase());
  }
  getVariable(name) {
    return this.c.get(name.toLowerCase())?.data;
  }
  getVariables(location3) {
    const all = Iterable.map(this.c.values(), (data) => data.data);
    return Iterable.filter(all, (data) => {
      return location3 !== ChatAgentLocation.Editor || !(/* @__PURE__ */ new Set(["selection", "editor"])).has(data.name);
    });
  }
  getDynamicVariables(sessionId) {
    const widget = this.d.getWidgetBySessionId(sessionId);
    if (!widget || !widget.viewModel || !widget.supportsFileReferences) {
      return [];
    }
    const model = widget.getContrib($aOb.ID);
    if (!model) {
      return [];
    }
    return model.variables;
  }
  registerVariable(data, resolver) {
    const key2 = data.name.toLowerCase();
    if (this.c.has(key2)) {
      throw new Error(`A chat variable with the name '${data.name}' already exists.`);
    }
    this.c.set(key2, { data, resolver });
    return $1c(() => {
      this.c.delete(key2);
    });
  }
  async attachContext(name, value, location3) {
    if (location3 !== ChatAgentLocation.Panel && location3 !== ChatAgentLocation.EditingSession) {
      return;
    }
    const widget = location3 === ChatAgentLocation.EditingSession ? await $4Nb(this.e) : this.d.lastFocusedWidget ?? await $3Nb(this.e);
    if (!widget || !widget.viewModel) {
      return;
    }
    const key2 = name.toLowerCase();
    if (key2 === "file" && typeof value !== "string") {
      const uri = URI.isUri(value) ? value : value.uri;
      const range = "range" in value ? value.range : void 0;
      widget.attachmentModel.addFile(uri, range);
      return;
    }
    const resolved = this.c.get(key2);
    if (!resolved) {
      return;
    }
    widget.attachmentModel.addContext({ ...resolved.data, value });
  }
};
$M8b = __decorate([
  __param(0, $2Nb),
  __param(1, $uob)
], $M8b);

// out-build/vs/workbench/contrib/chat/browser/codeBlockContextProviderService.js
var $N8b = class {
  constructor() {
    this.a = /* @__PURE__ */ new Map();
  }
  get providers() {
    return [...this.a.values()];
  }
  registerProvider(provider, id2) {
    this.a.set(id2, provider);
    return $1c(() => this.a.delete(id2));
  }
};

// out-build/vs/workbench/contrib/chat/browser/contrib/chatInputEditorContrib.js
var decorationDescription = "chat";
var placeholderDecorationType = "chat-session-detail";
var slashCommandTextDecorationType = "chat-session-text";
var variableTextDecorationType = "chat-variable-text";
function agentAndCommandToKey(agent, subcommand) {
  return subcommand ? `${agent.id}__${subcommand}` : agent.id;
}
var InputEditorDecorations = class InputEditorDecorations2 extends $3c {
  constructor(c, f, g, h3) {
    super();
    this.c = c;
    this.f = f;
    this.g = g;
    this.h = h3;
    this.id = "inputEditorDecorations";
    this.a = /* @__PURE__ */ new Set();
    this.b = this.B(new $4c());
    this.f.registerDecorationType(decorationDescription, placeholderDecorationType, {});
    this.B(this.g.onDidColorThemeChange(() => this.m()));
    this.m();
    this.r();
    this.B(this.c.inputEditor.onDidChangeModelContent(() => this.r()));
    this.B(this.c.onDidChangeParsedInput(() => this.r()));
    this.B(this.c.onDidChangeViewModel(() => {
      this.j();
      this.a.clear();
      this.r();
    }));
    this.B(this.c.onDidSubmitAgent((e) => {
      this.a.add(agentAndCommandToKey(e.agent, e.slashCommand?.name));
    }));
    this.B(this.h.onDidChangeAgents(() => this.r()));
    this.j();
  }
  j() {
    this.b.value = this.c.viewModel?.onDidChange((e) => {
      if (e?.kind === "changePlaceholder" || e?.kind === "initialize") {
        this.r();
      }
    });
  }
  m() {
    this.f.removeDecorationType(variableTextDecorationType);
    this.f.removeDecorationType($_Nb);
    this.f.removeDecorationType(slashCommandTextDecorationType);
    const theme = this.g.getColorTheme();
    this.f.registerDecorationType(decorationDescription, slashCommandTextDecorationType, {
      color: theme.getColor($sGb)?.toString(),
      backgroundColor: theme.getColor($rGb)?.toString(),
      borderRadius: "3px"
    });
    this.f.registerDecorationType(decorationDescription, variableTextDecorationType, {
      color: theme.getColor($sGb)?.toString(),
      backgroundColor: theme.getColor($rGb)?.toString(),
      borderRadius: "3px"
    });
    this.f.registerDecorationType(decorationDescription, $_Nb, {
      color: theme.getColor($sGb)?.toString(),
      backgroundColor: theme.getColor($rGb)?.toString(),
      borderRadius: "3px"
    });
    this.r();
  }
  n() {
    const theme = this.g.getColorTheme();
    const transparentForeground = theme.getColor($Eq);
    return transparentForeground?.toString();
  }
  async r() {
    const inputValue = this.c.inputEditor.getValue();
    const viewModel = this.c.viewModel;
    if (!viewModel) {
      return;
    }
    if (!inputValue) {
      const defaultAgent = this.h.getDefaultAgent(this.c.location);
      const decoration3 = [
        {
          range: {
            startLineNumber: 1,
            endLineNumber: 1,
            startColumn: 1,
            endColumn: 1e3
          },
          renderOptions: {
            after: {
              contentText: viewModel.inputPlaceholder || (defaultAgent?.description ?? ""),
              color: this.n()
            }
          }
        }
      ];
      this.c.inputEditor.setDecorationsByType(decorationDescription, placeholderDecorationType, decoration3);
      return;
    }
    const parsedRequest = this.c.parsedInput.parts;
    let placeholderDecoration;
    const agentPart = parsedRequest.find((p) => p instanceof $BO);
    const agentSubcommandPart = parsedRequest.find((p) => p instanceof $CO);
    const slashCommandPart = parsedRequest.find((p) => p instanceof $DO);
    const exactlyOneSpaceAfterPart = (part) => {
      const partIdx = parsedRequest.indexOf(part);
      if (parsedRequest.length > partIdx + 2) {
        return false;
      }
      const nextPart = parsedRequest[partIdx + 1];
      return nextPart && nextPart instanceof $vO && nextPart.text === " ";
    };
    const getRangeForPlaceholder = (part) => ({
      startLineNumber: part.editorRange.startLineNumber,
      endLineNumber: part.editorRange.endLineNumber,
      startColumn: part.editorRange.endColumn + 1,
      endColumn: 1e3
    });
    const onlyAgentAndWhitespace = agentPart && parsedRequest.every((p) => p instanceof $vO && !p.text.trim().length || p instanceof $BO);
    if (onlyAgentAndWhitespace) {
      const isFollowupSlashCommand = this.a.has(agentAndCommandToKey(agentPart.agent, void 0));
      const shouldRenderFollowupPlaceholder = isFollowupSlashCommand && agentPart.agent.metadata.followupPlaceholder;
      if (agentPart.agent.description && exactlyOneSpaceAfterPart(agentPart)) {
        placeholderDecoration = [{
          range: getRangeForPlaceholder(agentPart),
          renderOptions: {
            after: {
              contentText: shouldRenderFollowupPlaceholder ? agentPart.agent.metadata.followupPlaceholder : agentPart.agent.description,
              color: this.n()
            }
          }
        }];
      }
    }
    const onlyAgentAndAgentCommandAndWhitespace = agentPart && agentSubcommandPart && parsedRequest.every((p) => p instanceof $vO && !p.text.trim().length || p instanceof $BO || p instanceof $CO);
    if (onlyAgentAndAgentCommandAndWhitespace) {
      const isFollowupSlashCommand = this.a.has(agentAndCommandToKey(agentPart.agent, agentSubcommandPart.command.name));
      const shouldRenderFollowupPlaceholder = isFollowupSlashCommand && agentSubcommandPart.command.followupPlaceholder;
      if (agentSubcommandPart?.command.description && exactlyOneSpaceAfterPart(agentSubcommandPart)) {
        placeholderDecoration = [{
          range: getRangeForPlaceholder(agentSubcommandPart),
          renderOptions: {
            after: {
              contentText: shouldRenderFollowupPlaceholder ? agentSubcommandPart.command.followupPlaceholder : agentSubcommandPart.command.description,
              color: this.n()
            }
          }
        }];
      }
    }
    const onlyAgentCommandAndWhitespace = agentSubcommandPart && parsedRequest.every((p) => p instanceof $vO && !p.text.trim().length || p instanceof $CO);
    if (onlyAgentCommandAndWhitespace) {
      if (agentSubcommandPart?.command.description && exactlyOneSpaceAfterPart(agentSubcommandPart)) {
        placeholderDecoration = [{
          range: getRangeForPlaceholder(agentSubcommandPart),
          renderOptions: {
            after: {
              contentText: agentSubcommandPart.command.description,
              color: this.n()
            }
          }
        }];
      }
    }
    this.c.inputEditor.setDecorationsByType(decorationDescription, placeholderDecorationType, placeholderDecoration ?? []);
    const textDecorations = [];
    if (agentPart) {
      textDecorations.push({ range: agentPart.editorRange });
    }
    if (agentSubcommandPart) {
      textDecorations.push({ range: agentSubcommandPart.editorRange, hoverMessage: new $bm(agentSubcommandPart.command.description) });
    }
    if (slashCommandPart) {
      textDecorations.push({ range: slashCommandPart.editorRange });
    }
    this.c.inputEditor.setDecorationsByType(decorationDescription, slashCommandTextDecorationType, textDecorations);
    const varDecorations = [];
    const variableParts = parsedRequest.filter((p) => p instanceof $zO);
    for (const variable of variableParts) {
      varDecorations.push({ range: variable.editorRange });
    }
    const toolParts = parsedRequest.filter((p) => p instanceof $AO);
    for (const tool of toolParts) {
      varDecorations.push({ range: tool.editorRange });
    }
    this.c.inputEditor.setDecorationsByType(decorationDescription, variableTextDecorationType, varDecorations);
  }
};
InputEditorDecorations = __decorate([
  __param(1, $U5),
  __param(2, $gs),
  __param(3, $ZO)
], InputEditorDecorations);
var InputEditorSlashCommandMode = class extends $3c {
  constructor(a) {
    super();
    this.a = a;
    this.id = "InputEditorSlashCommandMode";
    this.B(this.a.onDidChangeAgent((e) => {
      if (e.slashCommand && e.slashCommand.isSticky || !e.slashCommand && e.agent.metadata.isSticky) {
        this.b(e.agent, e.slashCommand);
      }
    }));
    this.B(this.a.onDidSubmitAgent((e) => {
      this.b(e.agent, e.slashCommand);
    }));
  }
  async b(agent, slashCommand) {
    if (this.a.inputEditor.getValue().trim()) {
      return;
    }
    let value;
    if (slashCommand && slashCommand.isSticky) {
      value = `${$xO}${agent.name} ${$yO}${slashCommand.name} `;
    } else if (agent.metadata.isSticky) {
      value = `${$xO}${agent.name} `;
    }
    if (value) {
      this.a.inputEditor.setValue(value);
      this.a.inputEditor.setPosition({ lineNumber: 1, column: value.length + 1 });
    }
  }
};
$qNb.CONTRIBS.push(InputEditorDecorations, InputEditorSlashCommandMode);
var ChatTokenDeleter = class ChatTokenDeleter2 extends $3c {
  constructor(a, b) {
    super();
    this.a = a;
    this.b = b;
    this.id = "chatTokenDeleter";
    const parser2 = this.b.createInstance($nO);
    const inputValue = this.a.inputEditor.getValue();
    let previousInputValue;
    let previousSelectedAgent;
    this.B(this.a.inputEditor.onDidChangeModelContent((e) => {
      if (!previousInputValue) {
        previousInputValue = inputValue;
        previousSelectedAgent = this.a.lastSelectedAgent;
      }
      const change = e.changes[0];
      if (!change.text && this.a.viewModel) {
        const previousParsedValue = parser2.parseChatRequest(this.a.viewModel.sessionId, previousInputValue, a.location, { selectedAgent: previousSelectedAgent });
        const deletableTokens = previousParsedValue.parts.filter((p) => p instanceof $BO || p instanceof $CO || p instanceof $DO || p instanceof $zO || p instanceof $AO);
        deletableTokens.forEach((token) => {
          const deletedRangeOfToken = $9C.intersectRanges(token.editorRange, change.range);
          if (deletedRangeOfToken && $9C.compareRangesUsingStarts(token.editorRange, change.range) < 0) {
            const length = deletedRangeOfToken.endColumn - deletedRangeOfToken.startColumn;
            const rangeToDelete = new $9C(token.editorRange.startLineNumber, token.editorRange.startColumn, token.editorRange.endLineNumber, token.editorRange.endColumn - length);
            this.a.inputEditor.executeEdits(this.id, [{
              range: rangeToDelete,
              text: ""
            }]);
            this.a.refreshParsedInput();
          }
        });
      }
      previousInputValue = this.a.inputEditor.getValue();
      previousSelectedAgent = this.a.lastSelectedAgent;
    }));
  }
};
ChatTokenDeleter = __decorate([
  __param(1, $Pk)
], ChatTokenDeleter);
$qNb.CONTRIBS.push(ChatTokenDeleter);

// out-build/vs/workbench/contrib/chat/browser/contrib/editorHoverWrapper.js
var $133 = $;
var h2 = h;
var $O8b = class $O8b2 {
  constructor(hoverContentElement, actions, a) {
    this.a = a;
    const hoverElement = h2(".chat-editor-hover-wrapper@root", [h2(".chat-editor-hover-wrapper-content@content")]);
    this.domNode = hoverElement.root;
    hoverElement.content.appendChild(hoverContentElement);
    if (actions && actions.length > 0) {
      const statusBarElement = $133(".hover-row.status-bar");
      const actionsElement = $133(".actions");
      actions.forEach((action) => {
        const keybinding = this.a.lookupKeybinding(action.commandId);
        const keybindingLabel = keybinding ? keybinding.getLabel() : null;
        $EZ.render(actionsElement, {
          label: action.label,
          commandId: action.commandId,
          run: (e) => {
            action.run(e);
          },
          iconClass: action.iconClass
        }, keybindingLabel);
      });
      statusBarElement.appendChild(actionsElement);
      this.domNode.appendChild(statusBarElement);
    }
  }
};
$O8b = __decorate([
  __param(2, $Ty)
], $O8b);

// out-build/vs/workbench/contrib/chat/browser/contrib/chatInputEditorHover.js
var $P8b = class $P8b2 {
  constructor(a, b, c, d) {
    this.a = a;
    this.b = b;
    this.c = c;
    this.d = d;
    this.hoverOrdinal = 1;
  }
  computeSync(anchor, _lineDecorations) {
    if (!this.a.hasModel()) {
      return [];
    }
    const widget = this.c.getWidgetByInputUri(this.a.getModel().uri);
    if (!widget) {
      return [];
    }
    const { agentPart } = $GO(widget.parsedInput);
    if (!agentPart) {
      return [];
    }
    if ($9C.containsPosition(agentPart.editorRange, anchor.range.getStartPosition())) {
      return [new $Q8b(this, $9C.lift(agentPart.editorRange), agentPart.agent)];
    }
    return [];
  }
  renderHoverParts(context, hoverParts) {
    if (!hoverParts.length) {
      return new $Abb([]);
    }
    const disposables = new $2c();
    const hover = disposables.add(this.b.createInstance($IDb));
    disposables.add(hover.onDidChangeContents(() => context.onContentsChanged()));
    const hoverPart = hoverParts[0];
    const agent = hoverPart.agent;
    hover.setAgent(agent.id);
    const actions = $JDb(() => agent, this.d).actions;
    const wrapper = this.b.createInstance($O8b, hover.domNode, actions);
    const wrapperNode = wrapper.domNode;
    context.fragment.appendChild(wrapperNode);
    const renderedHoverPart = {
      hoverPart,
      hoverElement: wrapperNode,
      dispose() {
        disposables.dispose();
      }
    };
    return new $Abb([renderedHoverPart]);
  }
  getAccessibleContent(hoverPart) {
    return localize(5059, null);
  }
};
$P8b = __decorate([
  __param(1, $Pk),
  __param(2, $2Nb),
  __param(3, $sn)
], $P8b);
var $Q8b = class {
  constructor(owner, range, agent) {
    this.owner = owner;
    this.range = range;
    this.agent = agent;
  }
  isValidForHoverAnchor(anchor) {
    return anchor.type === 1 && this.range.startColumn <= anchor.range.startColumn && this.range.endColumn >= anchor.range.endColumn;
  }
};
$Bbb.register($P8b);

// out-build/vs/workbench/contrib/chat/common/chatProgressTypes/chatToolInvocation.js
var $R8b = class {
  get isComplete() {
    return this.a;
  }
  get isCompleteDeferred() {
    return this.b;
  }
  get isCanceled() {
    return this.c;
  }
  get confirmed() {
    return this.d;
  }
  get isConfirmed() {
    return this.e;
  }
  constructor(invocationMessage, f) {
    this.invocationMessage = invocationMessage;
    this.f = f;
    this.kind = "toolInvocation";
    this.a = false;
    this.b = new $gi();
    this.d = new $gi();
    if (!f) {
      this.e = true;
      this.d.complete(true);
    }
    this.d.p.then((confirmed) => {
      this.e = confirmed;
      this.f = void 0;
      if (!confirmed) {
        this.b.complete();
      }
    });
    this.b.p.then(() => {
      this.a = true;
    });
  }
  get confirmationMessages() {
    return this.f;
  }
  toJSON() {
    return {
      kind: "toolInvocationSerialized",
      invocationMessage: this.invocationMessage,
      isConfirmed: this.e ?? false,
      isComplete: this.a
    };
  }
};

// out-build/vs/workbench/contrib/chat/browser/languageModelToolsService.js
var $S8b = class $S8b2 extends $3c {
  constructor(g, h3, j, m, n) {
    super();
    this.g = g;
    this.h = h3;
    this.j = j;
    this.m = m;
    this.n = n;
    this.a = new $ze();
    this.onDidChangeTools = this.a.event;
    this.b = new $8h(() => this.a.fire(), 750);
    this.c = /* @__PURE__ */ new Map();
    this.f = /* @__PURE__ */ new Set();
    this.B(this.h.onDidChangeContext((e) => {
      if (e.affectsSome(this.f)) {
        this.b.schedule();
      }
    }));
  }
  registerToolData(toolData) {
    if (this.c.has(toolData.id)) {
      throw new Error(`Tool "${toolData.id}" is already registered.`);
    }
    this.c.set(toolData.id, { data: toolData });
    this.b.schedule();
    toolData.when?.keys().forEach((key2) => this.f.add(key2));
    return $1c(() => {
      this.c.delete(toolData.id);
      this.r();
      this.b.schedule();
    });
  }
  r() {
    this.f.clear();
    for (const tool of this.c.values()) {
      tool.data.when?.keys().forEach((key2) => this.f.add(key2));
    }
  }
  registerToolImplementation(id2, tool) {
    const entry = this.c.get(id2);
    if (!entry) {
      throw new Error(`Tool "${id2}" was not contributed.`);
    }
    if (entry.impl) {
      throw new Error(`Tool "${id2}" already has an implementation.`);
    }
    entry.impl = tool;
    return $1c(() => {
      entry.impl = void 0;
    });
  }
  getTools() {
    const toolDatas = Iterable.map(this.c.values(), (i2) => i2.data);
    return Iterable.filter(toolDatas, (toolData) => !toolData.when || this.h.contextMatchesRules(toolData.when));
  }
  getTool(id2) {
    return this.s(id2)?.data;
  }
  s(id2) {
    const entry = this.c.get(id2);
    if (entry && (!entry.data.when || this.h.contextMatchesRules(entry.data.when))) {
      return entry;
    } else {
      return void 0;
    }
  }
  getToolByName(name) {
    for (const toolData of this.getTools()) {
      if (toolData.toolReferenceName === name) {
        return toolData;
      }
    }
    return void 0;
  }
  async invokeTool(dto, countTokens, token) {
    let tool = this.c.get(dto.toolId);
    if (!tool) {
      throw new Error(`Tool ${dto.toolId} was not contributed`);
    }
    if (!tool.impl) {
      await this.g.activateByEvent(`onLanguageModelTool:${dto.toolId}`);
      tool = this.c.get(dto.toolId);
      if (!tool?.impl) {
        throw new Error(`Tool ${dto.toolId} does not have an implementation registered.`);
      }
    }
    let toolInvocation;
    try {
      if (dto.context) {
        const model = this.j.getSession(dto.context?.sessionId);
        const request = model.getRequests().at(-1);
        const prepared = tool.impl.prepareToolInvocation ? await tool.impl.prepareToolInvocation(dto.parameters, token) : void 0;
        const defaultMessage = localize(5062, null, `"${tool.data.displayName}"`);
        const invocationMessage = prepared?.invocationMessage ?? defaultMessage;
        toolInvocation = new $R8b(invocationMessage, prepared?.confirmationMessages);
        token.onCancellationRequested(() => {
          toolInvocation.confirmed.complete(false);
        });
        model.acceptResponseProgress(request, toolInvocation);
        if (prepared?.confirmationMessages) {
          const userConfirmed = await toolInvocation.confirmed.p;
          if (!userConfirmed) {
            throw new $lb();
          }
        }
      } else {
        const prepared = tool.impl.prepareToolInvocation ? await tool.impl.prepareToolInvocation(dto.parameters, token) : void 0;
        if (prepared?.confirmationMessages) {
          const result2 = await this.m.confirm({ message: prepared.confirmationMessages.title, detail: $F1(prepared.confirmationMessages.message) });
          if (!result2.confirmed) {
            throw new $lb();
          }
        }
      }
      const result = await tool.impl.invoke(dto, countTokens, token);
      this.n.publicLog2("languageModelToolInvoked", {
        result: "success",
        chatSessionId: dto.context?.sessionId,
        toolId: tool.data.id,
        toolExtensionId: tool.data.extensionId?.value
      });
      return result;
    } catch (err) {
      const result = $kb(err) ? "userCancelled" : "error";
      this.n.publicLog2("languageModelToolInvoked", {
        result,
        chatSessionId: dto.context?.sessionId,
        toolId: tool.data.id,
        toolExtensionId: tool.data.extensionId?.value
      });
      throw err;
    } finally {
      toolInvocation?.isCompleteDeferred.complete();
    }
  }
};
$S8b = __decorate([
  __param(0, $wN),
  __param(1, $on),
  __param(2, $qO),
  __param(3, $Yv),
  __param(4, $zv)
], $S8b);

// out-build/vs/workbench/contrib/chat/browser/viewsWelcome/chatViewsWelcomeHandler.js
var chatViewsWelcomeExtensionPoint = $tN.registerExtensionPoint({
  extensionPoint: "chatViewsWelcome",
  jsonSchema: {
    description: localize(5063, null),
    type: "array",
    items: {
      additionalProperties: false,
      type: "object",
      properties: {
        icon: {
          type: "string",
          description: localize(5064, null)
        },
        title: {
          type: "string",
          description: localize(5065, null)
        },
        content: {
          type: "string",
          description: localize(5066, null)
        },
        when: {
          type: "string",
          description: localize(5067, null)
        }
      }
    },
    required: ["icon", "title", "contents", "when"]
  }
});
var $T8b = class $T8b2 {
  static {
    this.ID = "workbench.contrib.chatViewsWelcomeHandler";
  }
  constructor(a) {
    this.a = a;
    chatViewsWelcomeExtensionPoint.setHandler((extensions, delta) => {
      for (const extension of delta.added) {
        for (const providerDescriptor of extension.value) {
          $AN(extension.description, "chatParticipantPrivate");
          const when = $7m.deserialize(providerDescriptor.when);
          if (!when) {
            this.a.error(`Could not deserialize 'when' clause for chatViewsWelcome contribution: ${providerDescriptor.when}`);
            continue;
          }
          const descriptor = {
            ...providerDescriptor,
            when,
            icon: ThemeIcon.fromString(providerDescriptor.icon),
            content: new $bm(providerDescriptor.content, { isTrusted: true })
            // private API with command links
          };
          $Wn.as(
            "workbench.registry.chat.viewsWelcome"
            /* ChatViewsWelcomeExtensions.ChatViewsWelcomeRegistry */
          ).register(descriptor);
        }
      }
    });
  }
};
$T8b = __decorate([
  __param(0, $wn)
], $T8b);

// out-build/vs/workbench/contrib/chat/browser/actions/chatGettingStarted.js
var $U8b_1;
var $U8b = class $U8b2 extends $3c {
  static {
    $U8b_1 = this;
  }
  static {
    this.ID = "workbench.contrib.chatGettingStarted";
  }
  static {
    this.b = "workbench.chat.hideWelcomeView";
  }
  constructor(c, f, g, h3, j, m, n) {
    super();
    this.c = c;
    this.f = f;
    this.g = g;
    this.h = h3;
    this.j = j;
    this.m = m;
    this.n = n;
    this.a = false;
    const defaultChatAgent = this.c.defaultChatAgent;
    const hideWelcomeView = this.j.getBoolean($U8b_1.b, -1, false);
    if (!defaultChatAgent || hideWelcomeView) {
      return;
    }
    this.r(defaultChatAgent);
  }
  r(defaultChatAgent) {
    this.B(this.h.onDidInstallExtensions(async (result) => {
      for (const e of result) {
        if ($5z.equals(defaultChatAgent.extensionId, e.identifier.id) && e.operation === 2) {
          this.a = true;
          return;
        }
      }
    }));
    this.B(this.f.onDidChangeExtensionsStatus(async (event) => {
      for (const ext of event) {
        if ($5z.equals(defaultChatAgent.extensionId, ext.value)) {
          const extensionStatus = this.f.getExtensionsStatus();
          if (extensionStatus[ext.value].activationTimes && this.a) {
            await this.g.executeCommand($wNb);
            $5Nb(400, this.m, this.n);
            this.j.store(
              $U8b_1.b,
              true,
              -1,
              1
              /* StorageTarget.MACHINE */
            );
            this.a = false;
            return;
          }
        }
      }
    }));
  }
};
$U8b = $U8b_1 = __decorate([
  __param(0, $Vu),
  __param(1, $wN),
  __param(2, $sn),
  __param(3, $sA),
  __param(4, $jv),
  __param(5, $$M),
  __param(6, $Vlb)
], $U8b);

// out-build/vs/workbench/contrib/chat/browser/contrib/chatInputRelatedFilesContrib.js
var $V8b = class $V8b2 extends $3c {
  static {
    this.ID = "chat.relatedFilesWorkingSet";
  }
  constructor(c, f) {
    super();
    this.c = c;
    this.f = f;
    this.a = new $2c();
    this.h();
    this.B(this.c.onDidCreateEditingSession(() => {
      this.a.clear();
      this.h();
    }));
  }
  g() {
    if (this.b) {
      return;
    }
    const currentEditingSession = this.c.currentEditingSessionObs.get();
    if (!currentEditingSession) {
      return;
    }
    const workingSetEntries = currentEditingSession.entries.get();
    if (workingSetEntries.length > 0) {
      return;
    }
    const widget = this.f.getWidgetBySessionId(currentEditingSession.chatSessionId);
    if (!widget) {
      return;
    }
    this.b = this.c.getRelatedFiles(currentEditingSession.chatSessionId, widget.getInput(), CancellationToken.None).then((files) => {
      if (!files?.length) {
        return;
      }
      const currentEditingSession2 = this.c.currentEditingSessionObs.get();
      if (!currentEditingSession2 || currentEditingSession2.chatSessionId !== widget.viewModel?.sessionId || currentEditingSession2.entries.get().length) {
        return;
      }
      const maximumRelatedFiles = Math.min(2, this.c.editingSessionFileLimit - widget.input.chatEditWorkingSetFiles.length);
      const newSuggestions = new $Ec();
      for (const group2 of files) {
        for (const file of group2.files) {
          if (newSuggestions.size >= maximumRelatedFiles) {
            break;
          }
          newSuggestions.set(file.uri, { group: group2.group, description: file.description });
        }
      }
      const existingSuggestedEntriesToRemove = [];
      for (const entry of currentEditingSession2.workingSet) {
        if (entry[1].state === 6 && !newSuggestions.has(entry[0])) {
          existingSuggestedEntriesToRemove.push(entry[0]);
        }
      }
      currentEditingSession2?.remove(1, ...existingSuggestedEntriesToRemove);
      for (const [uri, data] of newSuggestions) {
        currentEditingSession2.addFileToWorkingSet(
          uri,
          localize(5060, null, data.description),
          6
          /* WorkingSetEntryState.Suggested */
        );
      }
    }).finally(() => {
      this.b = void 0;
    });
  }
  h() {
    const currentEditingSession = this.c.currentEditingSessionObs.get();
    if (!currentEditingSession) {
      return;
    }
    const widget = this.f.getWidgetBySessionId(currentEditingSession.chatSessionId);
    if (!widget || widget.viewModel?.sessionId !== currentEditingSession.chatSessionId) {
      return;
    }
    this.a.add(currentEditingSession.onDidDispose(() => {
      this.a.clear();
    }));
    this.g();
    const onDebouncedType = Event2.debounce(widget.inputEditor.onDidChangeModelContent, () => null, 3e3);
    this.a.add(onDebouncedType(() => {
      this.g();
    }));
    this.a.add(currentEditingSession.onDidChange((e) => {
      if (e === 0) {
        this.g();
      }
    }));
  }
  dispose() {
    this.a.dispose();
    super.dispose();
  }
};
$V8b = __decorate([
  __param(0, $$O),
  __param(1, $2Nb)
], $V8b);

// out-build/vs/workbench/contrib/chat/browser/chat.contribution.js
var configurationRegistry9 = $Wn.as($Ht.Configuration);
configurationRegistry9.registerConfiguration({
  id: "chatSidebar",
  title: localize(4754, null),
  type: "object",
  properties: {
    "chat.editor.fontSize": {
      type: "number",
      description: localize(4755, null),
      default: $m ? 12 : 14
    },
    "chat.editor.fontFamily": {
      type: "string",
      description: localize(4756, null),
      default: "default"
    },
    "chat.editor.fontWeight": {
      type: "string",
      description: localize(4757, null),
      default: "default"
    },
    "chat.editor.wordWrap": {
      type: "string",
      description: localize(4758, null),
      default: "off",
      enum: ["on", "off"]
    },
    "chat.editor.lineHeight": {
      type: "number",
      description: localize(4759, null),
      default: 0
    },
    "chat.commandCenter.enabled": {
      type: "boolean",
      tags: ["preview"],
      markdownDescription: localize(4760, null, "`#window.commandCenter#`"),
      default: true
    },
    "chat.experimental.offerSetup": {
      type: "boolean",
      default: false,
      scope: 1,
      markdownDescription: localize(4761, null),
      tags: ["experimental", "onExP"],
      included: false
    },
    "chat.editing.alwaysSaveWithGeneratedChanges": {
      type: "boolean",
      scope: 1,
      markdownDescription: localize(4762, null),
      default: false
    },
    "chat.editing.confirmEditRequestRemoval": {
      type: "boolean",
      scope: 1,
      markdownDescription: localize(4763, null),
      default: true
    },
    "chat.editing.confirmEditRequestRetry": {
      type: "boolean",
      scope: 1,
      markdownDescription: localize(4764, null),
      default: true
    },
    "chat.experimental.detectParticipant.enabled": {
      type: "boolean",
      deprecationMessage: localize(4765, null),
      description: localize(4766, null),
      default: null
    },
    "chat.detectParticipant.enabled": {
      type: "boolean",
      description: localize(4767, null),
      default: true
    }
  }
});
$Wn.as($ZK.EditorPane).registerEditorPane($7tb.create($sNb, $Zzb.EditorID, localize(4768, null)), [
  new $Nk($Zzb)
]);
$Wn.as($YL.ConfigurationMigration).registerConfigurationMigrations([
  {
    key: "chat.experimental.detectParticipant.enabled",
    migrateFn: (value, _accessor) => [
      ["chat.experimental.detectParticipant.enabled", { value: void 0 }],
      ["chat.detectParticipant.enabled", { value: value !== false }]
    ]
  }
]);
var ChatResolverContribution = class ChatResolverContribution2 extends $3c {
  static {
    this.ID = "workbench.contrib.chatResolver";
  }
  constructor(editorResolverService, instantiationService) {
    super();
    this.B(editorResolverService.registerEditor(`${Schemas.vscodeChatSesssion}:**/**`, {
      id: $Zzb.EditorID,
      label: localize(4769, null),
      priority: RegisteredEditorPriority.builtin
    }, {
      singlePerResource: true,
      canSupportResource: (resource) => resource.scheme === Schemas.vscodeChatSesssion
    }, {
      createEditorInput: ({ resource, options: options3 }) => {
        return { editor: instantiationService.createInstance($Zzb, resource, options3), options: options3 };
      }
    }));
  }
};
ChatResolverContribution = __decorate([
  __param(0, $4L),
  __param(1, $Pk)
], ChatResolverContribution);
$vhb.register(new $L8b());
$vhb.register(new $Y5b());
$vhb.register(new $Z5b());
$T_($H8b);
var ChatSlashStaticSlashCommandsContribution = class ChatSlashStaticSlashCommandsContribution2 extends $3c {
  static {
    this.ID = "workbench.contrib.chatSlashStaticSlashCommands";
  }
  constructor(slashCommandService, commandService, chatAgentService, chatVariablesService, instantiationService) {
    super();
    this.q.add(slashCommandService.registerSlashCommand({
      command: "clear",
      detail: localize(4770, null),
      sortText: "z2_clear",
      executeImmediately: true,
      locations: [ChatAgentLocation.Panel]
    }, async () => {
      commandService.executeCommand($35b);
    }));
    this.q.add(slashCommandService.registerSlashCommand({
      command: "help",
      detail: "",
      sortText: "z1_help",
      executeImmediately: true,
      locations: [ChatAgentLocation.Panel]
    }, async (prompt, progress) => {
      const defaultAgent = chatAgentService.getDefaultAgent(ChatAgentLocation.Panel);
      const agents = chatAgentService.getAgents();
      if (defaultAgent?.metadata.helpTextPrefix) {
        if ($dm(defaultAgent.metadata.helpTextPrefix)) {
          progress.report({ content: defaultAgent.metadata.helpTextPrefix, kind: "markdownContent" });
        } else {
          progress.report({ content: new $bm(defaultAgent.metadata.helpTextPrefix), kind: "markdownContent" });
        }
        progress.report({ content: new $bm("\n\n"), kind: "markdownContent" });
      }
      const agentText = (await Promise.all(agents.filter((a) => a.id !== defaultAgent?.id).filter((a) => a.locations.includes(ChatAgentLocation.Panel)).map(async (a) => {
        const description = a.description ? `- ${a.description}` : "";
        const agentMarkdown = instantiationService.invokeFunction((accessor) => $TMb(a, true, accessor));
        const agentLine = `- ${agentMarkdown} ${description}`;
        const commandText = a.slashCommands.map((c) => {
          const description2 = c.description ? `- ${c.description}` : "";
          return `	* ${$UMb(a, c)} ${description2}`;
        }).join("\n");
        return (agentLine + "\n" + commandText).trim();
      }))).join("\n");
      progress.report({ content: new $bm(agentText, { isTrusted: { enabledCommands: [$HNb.ID] } }), kind: "markdownContent" });
      if (defaultAgent?.metadata.helpTextVariablesPrefix) {
        progress.report({ content: new $bm("\n\n"), kind: "markdownContent" });
        if ($dm(defaultAgent.metadata.helpTextVariablesPrefix)) {
          progress.report({ content: defaultAgent.metadata.helpTextVariablesPrefix, kind: "markdownContent" });
        } else {
          progress.report({ content: new $bm(defaultAgent.metadata.helpTextVariablesPrefix), kind: "markdownContent" });
        }
        const variables = [
          ...chatVariablesService.getVariables(ChatAgentLocation.Panel),
          { name: "file", description: localize(4771, null) }
        ];
        const variableText = variables.map((v) => `* \`${$wO}${v.name}\` - ${v.description}`).join("\n");
        progress.report({ content: new $bm("\n" + variableText), kind: "markdownContent" });
      }
      if (defaultAgent?.metadata.helpTextPostfix) {
        progress.report({ content: new $bm("\n\n"), kind: "markdownContent" });
        if ($dm(defaultAgent.metadata.helpTextPostfix)) {
          progress.report({ content: defaultAgent.metadata.helpTextPostfix, kind: "markdownContent" });
        } else {
          progress.report({ content: new $bm(defaultAgent.metadata.helpTextPostfix), kind: "markdownContent" });
        }
      }
      await $Wh(200);
    }));
  }
};
ChatSlashStaticSlashCommandsContribution = __decorate([
  __param(0, $sO),
  __param(1, $sn),
  __param(2, $ZO),
  __param(3, $kO),
  __param(4, $Pk)
], ChatSlashStaticSlashCommandsContribution);
$Wn.as($ZK.EditorFactory).registerEditorSerializer($Zzb.TypeID, $2zb);
$PL(
  ChatResolverContribution.ID,
  ChatResolverContribution,
  1
  /* WorkbenchPhase.BlockStartup */
);
$PL(
  ChatSlashStaticSlashCommandsContribution.ID,
  ChatSlashStaticSlashCommandsContribution,
  4
  /* WorkbenchPhase.Eventually */
);
$PL(
  $I8b.ID,
  $I8b,
  1
  /* WorkbenchPhase.BlockStartup */
);
$PL(
  $U5b.ID,
  $U5b,
  2
  /* WorkbenchPhase.BlockRestore */
);
$PL(
  $J8b.ID,
  $J8b,
  4
  /* WorkbenchPhase.Eventually */
);
$PL(
  $zNb.ID,
  $zNb,
  2
  /* WorkbenchPhase.BlockRestore */
);
$PL(
  $YNb.ID,
  $YNb,
  4
  /* WorkbenchPhase.Eventually */
);
$PL(
  $V8b.ID,
  $V8b,
  4
  /* WorkbenchPhase.Eventually */
);
$PL(
  $VNb.ID,
  $VNb,
  3
  /* WorkbenchPhase.AfterRestored */
);
$PL(
  $UNb.ID,
  $UNb,
  2
  /* WorkbenchPhase.BlockRestore */
);
$PL(
  $T8b.ID,
  $T8b,
  1
  /* WorkbenchPhase.BlockStartup */
);
$PL(
  $U8b.ID,
  $U8b,
  4
  /* WorkbenchPhase.Eventually */
);
$PL(
  $Xzb.ID,
  $Xzb,
  4
  /* WorkbenchPhase.Eventually */
);
$xNb();
$A8b();
$$5b();
$_5b();
$C8b();
$wBb();
$MNb();
$f6b();
$D8b();
$E8b();
$55b();
$y8b();
$B8b();
$HMb();
$T_($x8b);
$85(
  $EMb.ID,
  $EMb,
  3
  /* EditorContributionInstantiation.Eventually */
);
$85(
  $PMb.ID,
  $PMb,
  3
  /* EditorContributionInstantiation.Eventually */
);
$SC(
  $qO,
  $S5b,
  1
  /* InstantiationType.Delayed */
);
$SC(
  $2Nb,
  $rNb,
  1
  /* InstantiationType.Delayed */
);
$SC(
  $6Nb,
  $K8b,
  1
  /* InstantiationType.Delayed */
);
$SC(
  $7Nb,
  $G8b,
  1
  /* InstantiationType.Delayed */
);
$SC(
  $jzb,
  $kzb,
  1
  /* InstantiationType.Delayed */
);
$SC(
  $GN,
  $IN,
  1
  /* InstantiationType.Delayed */
);
$SC(
  $Zrb,
  $1rb,
  1
  /* InstantiationType.Delayed */
);
$SC(
  $sO,
  $tO,
  1
  /* InstantiationType.Delayed */
);
$SC(
  $ZO,
  $1O,
  1
  /* InstantiationType.Delayed */
);
$SC(
  $3O,
  $4O,
  1
  /* InstantiationType.Delayed */
);
$SC(
  $kO,
  $M8b,
  1
  /* InstantiationType.Delayed */
);
$SC(
  $mO,
  $S8b,
  1
  /* InstantiationType.Delayed */
);
$SC(
  $V5b,
  $X5b,
  1
  /* InstantiationType.Delayed */
);
$SC(
  $8Nb,
  $N8b,
  1
  /* InstantiationType.Delayed */
);
$SC(
  $7O,
  $8O,
  1
  /* InstantiationType.Delayed */
);
$SC(
  $$O,
  $jFb,
  1
  /* InstantiationType.Delayed */
);
$SC(
  $RMb,
  $SMb,
  1
  /* InstantiationType.Delayed */
);
$SC(
  $Xrb,
  $Yrb,
  1
  /* InstantiationType.Delayed */
);
$SC(
  $Uzb,
  $Wzb,
  1
  /* InstantiationType.Delayed */
);

// out-build/vs/workbench/contrib/inlineChat/browser/inlineChatNotebook.js
var $W8b = class $W8b2 {
  constructor(sessionService, editorService, notebookEditorService) {
    this.a = new $2c();
    this.a.add(sessionService.registerSessionKeyComputer(Schemas.vscodeNotebookCell, {
      getComparisonKey: (editor, uri) => {
        const data = CellUri.parse(uri);
        if (!data) {
          throw $ob("Expected notebook cell uri");
        }
        let fallback2;
        for (const notebookEditor of notebookEditorService.listNotebookEditors()) {
          if (notebookEditor.hasModel() && $oh(notebookEditor.textModel.uri, data.notebook)) {
            const candidate = `<notebook>${notebookEditor.getId()}#${uri}`;
            if (!fallback2) {
              fallback2 = candidate;
            }
            if (notebookEditor.codeEditors.find((tuple) => tuple[1] === editor)) {
              return candidate;
            }
          }
        }
        if (fallback2) {
          return fallback2;
        }
        const activeEditor = editorService.activeEditorPane;
        if (activeEditor && (activeEditor.getId() === $A2b.ID || activeEditor.getId() === $03b.ID)) {
          return `<notebook>${editor.getId()}#${uri}`;
        }
        throw $ob("Expected notebook editor");
      }
    }));
    this.a.add(sessionService.onWillStartSession((newSessionEditor) => {
      const candidate = CellUri.parse(newSessionEditor.getModel().uri);
      if (!candidate) {
        return;
      }
      for (const notebookEditor of notebookEditorService.listNotebookEditors()) {
        if ($oh(notebookEditor.textModel?.uri, candidate.notebook)) {
          let found = false;
          const editors = [];
          for (const [, codeEditor] of notebookEditor.codeEditors) {
            editors.push(codeEditor);
            found = codeEditor === newSessionEditor || found;
          }
          if (found) {
            for (const editor of editors) {
              if (editor !== newSessionEditor) {
                $cHb.get(editor)?.finishExistingSession();
              }
            }
            break;
          }
        }
      }
    }));
  }
  dispose() {
    this.a.dispose();
  }
};
$W8b = __decorate([
  __param(0, $kGb),
  __param(1, $mJ),
  __param(2, $yMb)
], $W8b);

// out-build/vs/workbench/contrib/inlineChat/browser/inlineChatSavingServiceImpl.js
var key = "chat.editing.alwaysSaveWithGeneratedChanges";
var $X8b = class $X8b2 {
  constructor(d, f, g, _inlineChatSessionService, h3, j, k, l) {
    this.d = d;
    this.f = f;
    this.g = g;
    this.h = h3;
    this.j = j;
    this.k = k;
    this.l = l;
    this.a = new $2c();
    this.b = this.a.add(new $4c());
    this.c = /* @__PURE__ */ new Map();
    this.a.add(Event2.any(_inlineChatSessionService.onDidEndSession, _inlineChatSessionService.onDidStashSession)((e) => {
      this.c.get(e.session)?.dispose();
    }));
    this.a.add(h3.onDidChangeConfiguration((e) => {
      if (!e.affectsConfiguration(key) && !e.affectsConfiguration(
        "inlineChat.acceptedOrDiscardBeforeSave"
        /* InlineChatConfigKeys.AcceptedOrDiscardBeforeSave */
      )) {
        return;
      }
      if (this.o()) {
        $Xc(this.c.values());
        this.c.clear();
      }
    }));
  }
  dispose() {
    this.a.dispose();
    $Xc(this.c.values());
  }
  markChanged(session) {
    if (this.o()) {
      return;
    }
    if (!this.c.has(session)) {
      let uri = session.targetUri;
      if (uri.scheme === Schemas.vscodeNotebookCell) {
        const data = CellUri.parse(uri);
        if (!data) {
          return;
        }
        uri = data?.notebook;
      }
      if (this.c.size === 0) {
        this.m();
      }
      const saveConfigOverride = this.d.disableAutoSave(uri);
      this.c.set(session, {
        resourceUri: uri,
        groupCandidate: this.f.activeGroup,
        session,
        dispose: () => {
          saveConfigOverride.dispose();
          this.c.delete(session);
          if (this.c.size === 0) {
            this.b.clear();
          }
        }
      });
    }
  }
  m() {
    const queue = new $3h();
    const d1 = this.g.files.addSaveParticipant({
      participate: (model, ctx, progress, token) => {
        return queue.queue(() => this.n(ctx.savedFrom ?? model.textEditorModel?.uri, ctx.reason, progress, token));
      }
    });
    const d2 = this.j.addSaveParticipant({
      participate: (workingCopy, ctx, progress, token) => {
        return queue.queue(() => this.n(ctx.savedFrom ?? workingCopy.resource, ctx.reason, progress, token));
      }
    });
    this.b.value = $Zc(d1, d2, queue);
  }
  async n(uri, reason, progress, token) {
    if (reason !== 1) {
      return;
    }
    if (this.o()) {
      return;
    }
    const sessions = /* @__PURE__ */ new Map();
    for (const [session, data] of this.c) {
      if (uri?.toString() === data.resourceUri.toString()) {
        sessions.set(session, data);
      }
    }
    if (sessions.size === 0) {
      return;
    }
    let message;
    if (sessions.size === 1) {
      const session = Iterable.first(sessions.values()).session;
      const agentName = session.agent.fullName;
      const filelabel = this.l.getUriBasenameLabel(session.textModelN.uri);
      message = localize(7499, null, agentName, filelabel);
    } else {
      const labels2 = Array.from(Iterable.map(sessions.values(), (i2) => this.l.getUriBasenameLabel(i2.session.textModelN.uri)));
      message = localize(7500, null, labels2.join(", "));
    }
    const result = await this.k.confirm({
      message,
      detail: localize(7501, null),
      primaryButton: localize(7502, null),
      cancelButton: localize(7503, null),
      checkbox: {
        label: localize(7504, null),
        checked: false
      }
    });
    if (!result.confirmed) {
      throw new $lb();
    }
    if (result.checkboxChecked) {
      this.h.updateValue(key, true);
    }
  }
  o() {
    return this.h.getValue(
      "inlineChat.acceptedOrDiscardBeforeSave"
      /* InlineChatConfigKeys.AcceptedOrDiscardBeforeSave */
    ) === true || this.h.getValue(key);
  }
};
$X8b = __decorate([
  __param(0, $4J),
  __param(1, $iJ),
  __param(2, $cK),
  __param(3, $kGb),
  __param(4, $kl),
  __param(5, $aK),
  __param(6, $Yv),
  __param(7, $ZI)
], $X8b);

// out-build/vs/workbench/contrib/inlineChat/browser/inlineChatAccessibleView.js
var $Y8b = class {
  constructor() {
    this.priority = 100;
    this.name = "inlineChat";
    this.when = $7m.or($aAb, $cAb);
    this.type = "view";
  }
  getProvider(accessor) {
    const codeEditorService = accessor.get($U5);
    const editor = codeEditorService.getActiveCodeEditor() || codeEditorService.getFocusedCodeEditor();
    if (!editor) {
      return;
    }
    const controller = $cHb.get(editor);
    if (!controller) {
      return;
    }
    const responseContent = controller?.getMessage();
    if (!responseContent) {
      return;
    }
    return new $thb(
      "inlineChat",
      {
        type: "view"
        /* AccessibleViewType.View */
      },
      () => $G1(new $bm(responseContent), true),
      () => controller.focus(),
      "accessibility.verbosity.inlineChat"
      /* AccessibilityVerbositySettingId.InlineChat */
    );
  }
};

// out-build/vs/workbench/contrib/inlineChat/browser/inlineChatAccessibilityHelp.js
var $Z8b = class {
  constructor() {
    this.priority = 106;
    this.name = "inlineChat";
    this.type = "help";
    this.when = $7m.or($cAb, ChatContextKeys.inputHasFocus);
  }
  getProvider(accessor) {
    const codeEditor = accessor.get($U5).getActiveCodeEditor() || accessor.get($U5).getFocusedCodeEditor();
    if (!codeEditor) {
      return;
    }
    return $25b(accessor, codeEditor, "inlineChat");
  }
};

// out-build/vs/workbench/contrib/inlineChat/browser/inlineChatCurrentLine.js
var $48b_1;
var $18b = new $nn("inlineChatShowingHint", false, localize(7491, null));
var _inlineChatActionId = "inlineChat.startWithCurrentLine";
var $28b = class extends $25 {
  constructor() {
    super({
      id: _inlineChatActionId,
      category: $Y2b.category,
      title: localize2(7496, "Start in Editor with Current Line"),
      f1: true,
      precondition: $7m.and($_zb.negate(), $$zb, EditorContextKeys.writable),
      keybinding: [{
        when: $18b,
        weight: 200 + 1,
        primary: 2048 | 39
        /* KeyCode.KeyI */
      }, {
        weight: 200,
        primary: $$e(
          2048 | 41,
          39
          /* KeyCode.KeyI */
        )
      }]
    });
  }
  async runEditorCommand(_accessor, editor) {
    const ctrl = $cHb.get(editor);
    if (!ctrl || !editor.hasModel()) {
      return;
    }
    const model = editor.getModel();
    const lineNumber = editor.getSelection().positionLineNumber;
    const lineContent = model.getLineContent(lineNumber);
    const startColumn = model.getLineFirstNonWhitespaceColumn(lineNumber);
    const endColumn = model.getLineMaxColumn(lineNumber);
    let undoEdits = [];
    model.pushEditOperations(null, [$bD.replace(new $9C(lineNumber, startColumn, lineNumber, endColumn), "")], (edits) => {
      undoEdits = edits;
      return null;
    });
    let lastState;
    const d = ctrl.onDidEnterState((e) => lastState = e);
    try {
      await ctrl.run({
        autoSend: true,
        message: lineContent.trim(),
        position: new $8C(lineNumber, startColumn)
      });
    } finally {
      d.dispose();
    }
    if (lastState === "CANCEL") {
      model.pushEditOperations(null, undoEdits, () => null);
    }
  }
};
var $38b = class extends $25 {
  constructor() {
    super({
      id: "inlineChat.showHint",
      category: $Y2b.category,
      title: localize2(7497, "Show Inline Chat Hint"),
      f1: false,
      precondition: $7m.and($_zb.negate(), $$zb, EditorContextKeys.writable)
    });
  }
  async runEditorCommand(_accessor, editor, ...args2) {
    if (!editor.hasModel()) {
      return;
    }
    const ctrl = $48b.get(editor);
    if (!ctrl) {
      return;
    }
    const [uri, position] = args2;
    if (!URI.isUri(uri) || !$8C.isIPosition(position)) {
      ctrl.hide();
      return;
    }
    const model = editor.getModel();
    if (!$oh(model.uri, uri)) {
      ctrl.hide();
      return;
    }
    model.tokenization.forceTokenization(position.lineNumber);
    const tokens = model.tokenization.getLineTokens(position.lineNumber);
    const tokenIndex = tokens.findTokenIndexAtOffset(position.column - 1);
    const tokenType = tokens.getStandardTokenType(tokenIndex);
    if (tokenType === 1) {
      ctrl.hide();
    } else {
      ctrl.show();
    }
  }
};
var $48b = class $48b2 extends $3c {
  static {
    $48b_1 = this;
  }
  static {
    this.ID = "editor.contrib.inlineChatHints";
  }
  static get(editor) {
    return editor.getContribution($48b_1.ID);
  }
  constructor(editor, contextKeyService, commandService, keybindingService, chatAgentService, markerDecorationService, f, g) {
    super();
    this.f = f;
    this.g = g;
    this.c = $he(this, false);
    this.a = editor;
    this.b = $18b.bindTo(contextKeyService);
    const ghostCtrl = $3hb.get(editor);
    this.q.add(commandService.onWillExecuteCommand((e) => {
      if (e.commandId === _inlineChatActionId || e.commandId === $rAb) {
        this.hide();
      }
    }));
    this.q.add(this.a.onMouseDown((e) => {
      if (e.target.type !== 6) {
        return;
      }
      if (!e.target.element?.classList.contains("inline-chat-hint-text")) {
        return;
      }
      if (e.event.leftButton) {
        commandService.executeCommand(_inlineChatActionId);
        this.hide();
      } else if (e.event.rightButton) {
        e.event.preventDefault();
        this.h(
          e.event,
          e.target.element?.classList.contains("whitespace") ? "inlineChat.lineEmptyHint" : "inlineChat.lineNaturalLanguageHint"
          /* InlineChatConfigKeys.LineNLHint */
        );
      }
    }));
    const markerSuppression = this.q.add(new $4c());
    const decos = this.a.createDecorationsCollection();
    const editorObs = $79(editor);
    const keyObs = $Dd(keybindingService.onDidUpdateKeybindings, (_) => keybindingService.lookupKeybinding($rAb)?.getLabel());
    const configSignal = $Dd(Event2.filter(g.onDidChangeConfiguration, (e) => e.affectsConfiguration(
      "inlineChat.lineEmptyHint"
      /* InlineChatConfigKeys.LineEmptyHint */
    ) || e.affectsConfiguration(
      "inlineChat.lineNaturalLanguageHint"
      /* InlineChatConfigKeys.LineNLHint */
    )), () => void 0);
    const showDataObs = $2d((r2) => {
      const ghostState = ghostCtrl?.model.read(r2)?.state.read(r2);
      const textFocus = editorObs.isTextFocused.read(r2);
      const position = editorObs.cursorPosition.read(r2);
      const model = editorObs.model.read(r2);
      const kb = keyObs.read(r2);
      configSignal.read(r2);
      if (ghostState !== void 0 || !kb || !position || !model || !textFocus) {
        return void 0;
      }
      if (model.getLanguageId() === $KF || model.getLanguageId() === "markdown") {
        return void 0;
      }
      const visible = this.c.read(r2);
      const isEol = model.getLineMaxColumn(position.lineNumber) === position.column;
      const isWhitespace3 = model.getLineLastNonWhitespaceColumn(position.lineNumber) === 0 && model.getValueLength() > 0 && position.column > 1;
      if (isWhitespace3) {
        return g.getValue(
          "inlineChat.lineEmptyHint"
          /* InlineChatConfigKeys.LineEmptyHint */
        ) ? { isEol, isWhitespace: isWhitespace3, kb, position, model } : void 0;
      }
      if (visible && isEol && g.getValue(
        "inlineChat.lineNaturalLanguageHint"
        /* InlineChatConfigKeys.LineNLHint */
      )) {
        return { isEol, isWhitespace: isWhitespace3, kb, position, model };
      }
      return void 0;
    });
    const style = $UZ();
    this.q.add(style);
    this.q.add($td((r2) => {
      const showData = showDataObs.read(r2);
      if (!showData) {
        decos.clear();
        markerSuppression.clear();
        this.b.reset();
        return;
      }
      const agentName = chatAgentService.getDefaultAgent(ChatAgentLocation.Editor)?.name ?? localize(7492, null);
      const { position, isEol, isWhitespace: isWhitespace3, kb, model } = showData;
      const inlineClassName = ["a", "inline-chat-hint", "inline-chat-hint-text"];
      let content;
      if (isWhitespace3) {
        content = "\xA0" + localize(7493, null, kb, agentName);
      } else if (isEol) {
        content = "\xA0" + localize(7494, null, kb, agentName);
      } else {
        content = "\u200A" + kb + "\u200A";
        inlineClassName.push("embedded");
      }
      style.setStyle(`.inline-chat-hint-text::after { content: ${$4Z(content)} }`);
      if (isWhitespace3) {
        inlineClassName.push("whitespace");
      }
      this.b.set(true);
      decos.set([{
        range: $9C.fromPositions(position),
        options: {
          description: "inline-chat-hint-line",
          showIfCollapsed: true,
          stickiness: 1,
          afterContentClassName: inlineClassName.join(" ")
        }
      }]);
      markerSuppression.value = markerDecorationService.addMarkerSuppression(model.uri, model.validateRange(new $9C(position.lineNumber, 1, position.lineNumber, Number.MAX_SAFE_INTEGER)));
    }));
  }
  h(event, setting) {
    this.f.showContextMenu({
      getAnchor: () => ({ x: event.posx, y: event.posy }),
      getActions: () => [
        $Zm({
          id: "inlineChat.disableHint",
          label: localize(7495, null),
          run: async () => {
            await this.g.updateValue(setting, false);
          }
        })
      ]
    });
  }
  show() {
    this.c.set(true, void 0);
  }
  hide() {
    this.c.set(false, void 0);
  }
};
$48b = $48b_1 = __decorate([
  __param(1, $on),
  __param(2, $sn),
  __param(3, $Ty),
  __param(4, $ZO),
  __param(5, $V6),
  __param(6, $50),
  __param(7, $kl)
], $48b);
var $58b = class extends $25 {
  constructor() {
    super({
      id: "inlineChat.hideHint",
      title: localize2(7498, "Hide Inline Chat Hint"),
      precondition: $18b,
      keybinding: {
        weight: 100 - 10,
        primary: 9
        /* KeyCode.Escape */
      }
    });
  }
  async runEditorCommand(_accessor, editor) {
    $48b.get(editor)?.hide();
  }
};

// out-build/vs/workbench/contrib/inlineChat/browser/inlineChat.contribution.js
$SC(
  $kGb,
  $_Gb,
  1
  /* InstantiationType.Delayed */
);
$SC(
  $9Gb,
  $X8b,
  1
  /* InstantiationType.Delayed */
);
$85(
  $8zb,
  $cHb,
  0
  /* EditorContributionInstantiation.Eager */
);
$hJ($28b);
$hJ($38b);
$hJ($58b);
$85(
  $48b.ID,
  $48b,
  3
  /* EditorContributionInstantiation.Eventually */
);
var editActionMenuItem = {
  group: "0_main",
  order: 0,
  command: {
    id: $HNb.ID,
    title: localize(7464, null)
  },
  when: $7m.and(ChatContextKeys.inputHasText, $pAb.toNegated(), $bAb)
};
var generateActionMenuItem = {
  group: "0_main",
  order: 0,
  command: {
    id: $HNb.ID,
    title: localize(7465, null)
  },
  when: $7m.and(ChatContextKeys.inputHasText, $pAb.toNegated(), $bAb.toNegated())
};
$dJ.appendMenuItem($yAb, editActionMenuItem);
$dJ.appendMenuItem($yAb, generateActionMenuItem);
var cancelActionMenuItem = {
  group: "0_main",
  order: 0,
  command: {
    id: $LNb.ID,
    title: localize(7466, null),
    shortTitle: localize(7467, null)
  },
  when: $7m.and($pAb)
};
$dJ.appendMenuItem($yAb, cancelActionMenuItem);
$hJ($W2b);
$hJ($62b);
$hJ($72b);
$hJ($X2b);
$hJ($42b);
$hJ($52b);
$hJ($82b);
$hJ($92b);
$hJ($Z2b);
$hJ($12b);
$hJ($22b);
$hJ($02b);
$hJ($$2b);
$hJ($32b);
var workbenchContributionsRegistry5 = $Wn.as(Extensions2.Workbench);
workbenchContributionsRegistry5.registerWorkbenchContribution(
  $W8b,
  3
  /* LifecyclePhase.Restored */
);
$PL(
  $aHb.Id,
  $aHb,
  3
  /* WorkbenchPhase.AfterRestored */
);
$vhb.register(new $Y8b());
$vhb.register(new $Z8b());

// out-build/vs/workbench/contrib/interactive/browser/interactiveCommon.js
var $68b = new $nn("interactiveInputCursorAtBoundary", "none");
var $78b = {
  interactiveWindowAlwaysScrollOnNewCell: "interactiveWindow.alwaysScrollOnNewCell",
  executeWithShiftEnter: "interactiveWindow.executeWithShiftEnter",
  showExecutionHint: "interactiveWindow.showExecutionHint"
};

// out-build/vs/workbench/contrib/interactive/browser/replInputHintContentWidget.js
var $88b_1;
var $88b = class $88b2 extends $3c {
  static {
    $88b_1 = this;
  }
  static {
    this.a = "replInput.widget.emptyHint";
  }
  constructor(f, g, h3) {
    super();
    this.f = f;
    this.g = g;
    this.h = h3;
    this.c = "";
    this.B(this.f.onDidChangeConfiguration((e) => {
      if (this.b && e.hasChanged(
        52
        /* EditorOption.fontInfo */
      )) {
        this.f.applyFontInfo(this.b);
      }
    }));
    const onDidFocusEditorText = Event2.debounce(this.f.onDidFocusEditorText, () => void 0, 500);
    this.B(onDidFocusEditorText(() => {
      if (this.f.hasTextFocus() && this.c && g.getValue(
        "accessibility.verbosity.replEditor"
        /* AccessibilityVerbositySettingId.ReplEditor */
      )) {
        $_Z(this.c);
      }
    }));
    this.B(g.onDidChangeConfiguration((e) => {
      if (e.affectsConfiguration($78b.executeWithShiftEnter)) {
        this.j();
      }
    }));
    this.f.addContentWidget(this);
  }
  getId() {
    return $88b_1.a;
  }
  getPosition() {
    return {
      position: { lineNumber: 1, column: 1 },
      preference: [
        0
        /* ContentWidgetPositionPreference.EXACT */
      ]
    };
  }
  getDomNode() {
    if (!this.b) {
      this.b = $(".empty-editor-hint");
      this.b.style.width = "max-content";
      this.b.style.paddingLeft = "4px";
      this.j();
      this.B($_i(this.b, "click", () => {
        this.f.focus();
      }));
      this.f.applyFontInfo(this.b);
    }
    return this.b;
  }
  j() {
    if (!this.b) {
      return;
    }
    while (this.b.firstChild) {
      this.b.removeChild(this.b.firstChild);
    }
    const hintElement = $("div.empty-hint-text");
    hintElement.style.cursor = "text";
    hintElement.style.whiteSpace = "nowrap";
    const keybinding = this.m();
    const keybindingHintLabel = keybinding?.getLabel();
    if (keybinding && keybindingHintLabel) {
      const actionPart = localize(7570, null, keybindingHintLabel);
      const [before, after] = actionPart.split(keybindingHintLabel).map((fragment) => {
        const hintPart = $("span", void 0, fragment);
        hintPart.style.fontStyle = "italic";
        return hintPart;
      });
      hintElement.appendChild(before);
      const label3 = new $32(hintElement, OS);
      label3.set(keybinding);
      label3.element.style.width = "min-content";
      label3.element.style.display = "inline";
      hintElement.appendChild(after);
      this.b.append(hintElement);
      const helpKeybinding = this.h.lookupKeybinding(
        "editor.action.accessibilityHelp"
        /* AccessibilityCommandId.OpenAccessibilityHelp */
      )?.getLabel();
      const helpInfo = helpKeybinding ? localize(7571, null, helpKeybinding) : localize(7572, null);
      this.c = actionPart.concat(helpInfo, localize(
        7573,
        null,
        "accessibility.verbosity.replEditor"
        /* AccessibilityVerbositySettingId.ReplEditor */
      ));
    }
  }
  m() {
    const keybindings = this.h.lookupKeybindings("interactive.execute");
    const shiftEnterConfig = this.g.getValue($78b.executeWithShiftEnter);
    const hasEnterChord = (kb, modifier = "") => {
      const chords = kb.getDispatchChords();
      const chord = modifier + "Enter";
      const chordAlt = modifier + "[Enter]";
      return chords.length === 1 && (chords[0] === chord || chords[0] === chordAlt);
    };
    if (shiftEnterConfig) {
      const keybinding = keybindings.find((kb) => hasEnterChord(kb, "shift+"));
      if (keybinding) {
        return keybinding;
      }
    } else {
      let keybinding = keybindings.find((kb) => hasEnterChord(kb));
      if (keybinding) {
        return keybinding;
      }
      keybinding = this.h.lookupKeybindings("python.execInREPLEnter").find((kb) => hasEnterChord(kb));
      if (keybinding) {
        return keybinding;
      }
    }
    return keybindings?.[0];
  }
  dispose() {
    super.dispose();
    this.f.removeContentWidget(this);
  }
};
$88b = $88b_1 = __decorate([
  __param(1, $kl),
  __param(2, $Ty)
], $88b);

// out-build/vs/workbench/contrib/interactive/browser/interactiveEditor.js
var DECORATION_KEY2 = "interactiveInputDecoration";
var INTERACTIVE_EDITOR_VIEW_STATE_PREFERENCE_KEY = "InteractiveEditorViewState";
var INPUT_CELL_VERTICAL_PADDING = 8;
var INPUT_CELL_HORIZONTAL_PADDING_RIGHT = 10;
var INPUT_EDITOR_PADDING = 8;
var $_8b = class $_8b2 extends $5tb {
  get onDidFocus() {
    return this.vb.event;
  }
  constructor(group2, telemetryService, themeService, storageService, instantiationService, notebookWidgetService, contextKeyService, codeEditorService, notebookKernelService, languageService, keybindingService, configurationService, menuService, contextMenuService, editorGroupService, textResourceConfigurationService, notebookExecutionStateService, extensionService) {
    super($eM, group2, telemetryService, themeService, storageService);
    this.f = { value: void 0 };
    this.nb = this.B(new $2c());
    this.sb = this.B(new $4c());
    this.vb = this.B(new $ze());
    this.wb = this.B(new $ze());
    this.onDidChangeSelection = this.wb.event;
    this.xb = this.B(new $ze());
    this.onDidChangeScroll = this.xb.event;
    this.u = notebookWidgetService;
    this.fb = configurationService;
    this.gb = notebookKernelService;
    this.db = languageService;
    this.hb = keybindingService;
    this.ib = menuService;
    this.jb = contextMenuService;
    this.kb = editorGroupService;
    this.lb = notebookExecutionStateService;
    this.mb = extensionService;
    this.a = $(".interactive-editor");
    this.eb = this.B(contextKeyService.createScoped(this.a));
    this.eb.createKey("isCompositeNotebook", true);
    this.cb = this.B(instantiationService.createChild(new $Ok([$on, this.eb])));
    this.pb = this.Db();
    this.B(this.fb.onDidChangeConfiguration((e) => {
      if (e.affectsConfiguration("editor") || e.affectsConfiguration("notebook")) {
        this.pb = this.Db();
      }
    }));
    this.qb = instantiationService.createInstance($xrb, this.window, true, { cellToolbarInteraction: "hover", globalToolbar: true, stickyScrollEnabled: false, dragAndDropEnabled: false });
    this.rb = this.ab(editorGroupService, textResourceConfigurationService, INTERACTIVE_EDITOR_VIEW_STATE_PREFERENCE_KEY);
    codeEditorService.registerDecorationType("interactive-decoration", DECORATION_KEY2, {});
    this.B(this.hb.onDidUpdateKeybindings(this.Ob, this));
    this.B(this.lb.onDidChangeExecution((e) => {
      if (e.type === NotebookExecutionType.cell && $oh(e.notebook, this.f.value?.viewModel?.notebookDocument.uri)) {
        const cell = this.f.value?.getCellByHandle(e.cellHandle);
        if (cell && e.changed?.state) {
          this.Jb(cell);
        }
      }
    }));
  }
  get yb() {
    return 19 + 2 + INPUT_CELL_VERTICAL_PADDING * 2 + INPUT_EDITOR_PADDING * 2;
  }
  get zb() {
    return 19 + INPUT_EDITOR_PADDING * 2;
  }
  Y(parent) {
    $bk(parent, this.a);
    this.a.style.position = "relative";
    this.c = $bk(this.a, $(".notebook-editor-container"));
    this.g = $bk(this.a, $(".input-cell-container"));
    this.g.style.position = "absolute";
    this.g.style.height = `${this.yb}px`;
    this.j = $bk(this.g, $(".input-focus-indicator"));
    this.m = $bk(this.g, $(".run-button-container"));
    this.Bb(this.m);
    this.r = $bk(this.g, $(".input-editor-container"));
    this.Cb();
  }
  Bb(runButtonContainer) {
    const menu = this.B(this.ib.createMenu($bJ.InteractiveInputExecute, this.eb));
    this.tb = this.B(new $f3(runButtonContainer, this.jb, {
      getKeyBinding: (action) => this.hb.lookupKeybinding(action.id),
      actionViewItemProvider: (action, options3) => {
        return $X$(this.cb, action, options3);
      },
      renderDropdownAsChildElement: true
    }));
    const { primary, secondary } = $Q$(menu.getActions({ shouldForwardArgs: true }));
    this.tb.setActions([...primary, ...secondary]);
  }
  Cb() {
    this.b = $VZ(this.a);
    const styleSheets = [];
    const { codeCellLeftMargin, cellRunGutter } = this.qb.getLayoutConfiguration();
    const { focusIndicator } = this.qb.getDisplayOptions();
    const leftMargin = this.qb.getCellEditorContainerLeftMargin();
    styleSheets.push(`
			.interactive-editor .input-cell-container {
				padding: ${INPUT_CELL_VERTICAL_PADDING}px ${INPUT_CELL_HORIZONTAL_PADDING_RIGHT}px ${INPUT_CELL_VERTICAL_PADDING}px ${leftMargin}px;
			}
		`);
    if (focusIndicator === "gutter") {
      styleSheets.push(`
				.interactive-editor .input-cell-container:focus-within .input-focus-indicator::before {
					border-color: var(--vscode-notebook-focusedCellBorder) !important;
				}
				.interactive-editor .input-focus-indicator::before {
					border-color: var(--vscode-notebook-inactiveFocusedCellBorder) !important;
				}
				.interactive-editor .input-cell-container .input-focus-indicator {
					display: block;
					top: ${INPUT_CELL_VERTICAL_PADDING}px;
				}
				.interactive-editor .input-cell-container {
					border-top: 1px solid var(--vscode-notebook-inactiveFocusedCellBorder);
				}
			`);
    } else {
      styleSheets.push(`
				.interactive-editor .input-cell-container {
					border-top: 1px solid var(--vscode-notebook-inactiveFocusedCellBorder);
				}
				.interactive-editor .input-cell-container .input-focus-indicator {
					display: none;
				}
			`);
    }
    styleSheets.push(`
			.interactive-editor .input-cell-container .run-button-container {
				width: ${cellRunGutter}px;
				left: ${codeCellLeftMargin}px;
				margin-top: ${INPUT_EDITOR_PADDING - 2}px;
			}
		`);
    this.b.textContent = styleSheets.join("\n");
  }
  Db() {
    let overrideIdentifier = void 0;
    if (this.s) {
      overrideIdentifier = this.s.getModel()?.getLanguageId();
    }
    const editorOptions2 = $Lv(this.fb.getValue("editor", { overrideIdentifier }));
    const editorOptionsOverride = $Zsb(this.fb);
    const computed = Object.freeze({
      ...editorOptions2,
      ...editorOptionsOverride,
      ...{
        glyphMargin: true,
        padding: {
          top: INPUT_EDITOR_PADDING,
          bottom: INPUT_EDITOR_PADDING
        },
        hover: {
          enabled: true
        }
      }
    });
    return computed;
  }
  I() {
    this.Fb(this.input);
    super.I();
  }
  getViewState() {
    const input = this.input;
    if (!(input instanceof $1Ob)) {
      return void 0;
    }
    this.Fb(input);
    return this.Gb(input);
  }
  Fb(input) {
    if (this.f.value && input instanceof $1Ob) {
      if (this.f.value.isDisposed) {
        return;
      }
      const state = this.f.value.getEditorViewState();
      const editorState = this.s.saveViewState();
      this.rb.saveEditorState(this.group, input.notebookEditorInput.resource, {
        notebook: state,
        input: editorState
      });
    }
  }
  Gb(input) {
    const result = this.rb.loadEditorState(this.group, input.notebookEditorInput.resource);
    if (result) {
      return result;
    }
    for (const group2 of this.kb.getGroups(
      1
      /* GroupsOrder.MOST_RECENTLY_ACTIVE */
    )) {
      if (group2.activeEditorPane !== this && group2.activeEditorPane === this && group2.activeEditor?.matches(input)) {
        const notebook = this.f.value?.getEditorViewState();
        const input2 = this.s.saveViewState();
        return {
          notebook,
          input: input2
        };
      }
    }
    return;
  }
  async setInput(input, options3, context, token) {
    const notebookInput = input.notebookEditorInput;
    this.f.value?.onWillHide();
    this.s?.dispose();
    this.nb.clear();
    this.f = this.cb.invokeFunction(this.u.retrieveWidget, this.group.id, notebookInput, {
      isReplHistory: true,
      isReadOnly: true,
      contributions: NotebookEditorExtensionsRegistry.getSomeEditorContributions([
        $E3b.id,
        $F3b.id,
        $q3b.id
      ]),
      menuIds: {
        notebookToolbar: $bJ.InteractiveToolbar,
        cellTitleToolbar: $bJ.InteractiveCellTitle,
        cellDeleteToolbar: $bJ.InteractiveCellDelete,
        cellInsertToolbar: $bJ.NotebookCellBetween,
        cellTopInsertToolbar: $bJ.NotebookCellListTop,
        cellExecuteToolbar: $bJ.InteractiveCellExecute,
        cellExecutePrimary: void 0
      },
      cellEditorContributions: EditorExtensionsRegistry.getSomeEditorContributions([
        $Fsb,
        $Mfb.ID,
        $Afb.ID,
        $Fib.ID,
        $nib.ID
      ]),
      options: this.qb,
      codeWindow: this.window
    }, void 0, this.window);
    this.s = this.cb.createInstance($D9, this.r, this.pb, {
      ...{
        isSimpleWidget: false,
        contributions: EditorExtensionsRegistry.getSomeEditorContributions([
          $Esb.ID,
          $Fsb,
          $Mfb.ID,
          $qdb.ID,
          $Wjb.ID,
          $Dcb.ID,
          $Ysb.ID,
          $Afb.ID,
          $Fib.ID,
          $nib.ID,
          $8zb
        ])
      }
    });
    if (this.ob) {
      this.c.style.height = `${this.ob.dimension.height - this.yb}px`;
      this.f.value.layout(new $rj(this.ob.dimension.width, this.ob.dimension.height - this.yb), this.c);
      const leftMargin = this.qb.getCellEditorContainerLeftMargin();
      const maxHeight = Math.min(this.ob.dimension.height / 2, this.zb);
      this.s.layout(this.Mb(this.ob.dimension.width - leftMargin - INPUT_CELL_HORIZONTAL_PADDING_RIGHT, maxHeight));
      this.j.style.height = `${this.zb}px`;
      this.g.style.top = `${this.ob.dimension.height - this.yb}px`;
      this.g.style.width = `${this.ob.dimension.width}px`;
    }
    await super.setInput(input, options3, context, token);
    const model = await input.resolve();
    if (this.tb) {
      this.tb.context = input.resource;
    }
    if (model === null) {
      throw new Error("The Interactive Window model could not be resolved");
    }
    this.f.value?.setParentContextKeyService(this.eb);
    const viewState = options3?.viewState ?? this.Gb(input);
    await this.mb.whenInstalledExtensionsRegistered();
    await this.f.value.setModel(model.notebook, viewState?.notebook);
    model.notebook.setCellCollapseDefault(this.qb.getCellCollapseDefault());
    this.f.value.setOptions({
      isReadOnly: true
    });
    this.nb.add(this.f.value.onDidResizeOutput((cvm) => {
      this.Jb(cvm);
    }));
    this.nb.add(this.f.value.onDidFocusWidget(() => this.vb.fire()));
    this.nb.add(this.qb.onDidChangeOptions((e) => {
      if (e.compactView || e.focusIndicator) {
        this.b?.remove();
        this.Cb();
      }
      if (this.ob && this.isVisible()) {
        this.layout(this.ob.dimension, this.ob.position);
      }
      if (e.interactiveWindowCollapseCodeCells) {
        model.notebook.setCellCollapseDefault(this.qb.getCellCollapseDefault());
      }
    }));
    const languageId = this.f.value?.activeKernel?.supportedLanguages[0] ?? input.language ?? $KF;
    const editorModel = await input.resolveInput(languageId);
    editorModel.setLanguage(languageId);
    this.s.setModel(editorModel);
    if (viewState?.input) {
      this.s.restoreViewState(viewState.input);
    }
    this.pb = this.Db();
    this.s.updateOptions(this.pb);
    this.nb.add(this.s.onDidFocusEditorWidget(() => this.vb.fire()));
    this.nb.add(this.s.onDidContentSizeChange((e) => {
      if (!e.contentHeightChanged) {
        return;
      }
      if (this.ob) {
        this.Lb(this.ob.dimension, this.ob.position);
      }
    }));
    this.nb.add(this.s.onDidChangeCursorPosition((e) => this.wb.fire({ reason: this.Hb(e) })));
    this.nb.add(this.s.onDidChangeModelContent(() => this.wb.fire({
      reason: 3
      /* EditorPaneSelectionChangeReason.EDIT */
    })));
    this.nb.add(this.gb.onDidChangeNotebookAffinity(this.Kb, this));
    this.nb.add(this.gb.onDidChangeSelectedNotebooks(this.Kb, this));
    this.nb.add(this.n.onDidColorThemeChange(() => {
      if (this.isVisible()) {
        this.Ob();
      }
    }));
    this.nb.add(this.s.onDidChangeModelContent(() => {
      if (this.isVisible()) {
        this.Ob();
      }
    }));
    this.s.onDidChangeModelDecorations(() => {
      if (this.isVisible()) {
        this.Ob();
      }
    });
    this.nb.add(this.s.onDidChangeModel(() => {
      this.Ob();
    }));
    this.fb.onDidChangeConfiguration((e) => {
      if (e.affectsConfiguration($78b.showExecutionHint)) {
        this.Ob();
      }
    });
    const cursorAtBoundaryContext = $68b.bindTo(this.eb);
    if (input.resource && input.historyService.has(input.resource)) {
      cursorAtBoundaryContext.set("top");
    } else {
      cursorAtBoundaryContext.set("none");
    }
    this.nb.add(this.s.onDidChangeCursorPosition(({ position }) => {
      const viewModel = this.s._getViewModel();
      const lastLineNumber = viewModel.getLineCount();
      const lastLineCol = viewModel.getLineLength(lastLineNumber) + 1;
      const viewPosition = viewModel.coordinatesConverter.convertModelPositionToViewPosition(position);
      const firstLine3 = viewPosition.lineNumber === 1 && viewPosition.column === 1;
      const lastLine = viewPosition.lineNumber === lastLineNumber && viewPosition.column === lastLineCol;
      if (firstLine3) {
        if (lastLine) {
          cursorAtBoundaryContext.set("both");
        } else {
          cursorAtBoundaryContext.set("top");
        }
      } else {
        if (lastLine) {
          cursorAtBoundaryContext.set("bottom");
        } else {
          cursorAtBoundaryContext.set("none");
        }
      }
    }));
    this.nb.add(editorModel.onDidChangeContent(() => {
      const value = editorModel.getValue();
      if (this.input?.resource) {
        const historyService = this.input.historyService;
        if (!historyService.matchesCurrent(this.input.resource, value)) {
          historyService.replaceLast(this.input.resource, value);
        }
      }
    }));
    this.nb.add(this.f.value.onDidScroll(() => this.xb.fire()));
    this.Kb();
    this.Ob();
  }
  setOptions(options3) {
    this.f.value?.setOptions(options3);
    super.setOptions(options3);
  }
  Hb(e) {
    switch (e.source) {
      case "api":
        return 1;
      case "code.navigation":
        return 4;
      case "code.jump":
        return 5;
      default:
        return 2;
    }
  }
  Ib(cell) {
    const visibleRanges = this.f.value?.visibleRanges || [];
    const cellIndex = this.f.value?.getCellIndex(cell);
    if (cellIndex === Math.max(...visibleRanges.map((range) => range.end - 1))) {
      return true;
    }
    return false;
  }
  Jb(cvm) {
    const index = this.f.value.getCellIndex(cvm);
    if (index === this.f.value.getLength() - 1) {
      if (this.fb.getValue($78b.interactiveWindowAlwaysScrollOnNewCell) || this.Ib(cvm)) {
        this.f.value.scrollToBottom();
      }
    }
  }
  Kb() {
    const notebook = this.f.value?.textModel;
    const textModel = this.s.getModel();
    if (notebook && textModel) {
      const info = this.gb.getMatchingKernel(notebook);
      const selectedOrSuggested = info.selected ?? (info.suggestions.length === 1 ? info.suggestions[0] : void 0) ?? (info.all.length === 1 ? info.all[0] : void 0);
      if (selectedOrSuggested) {
        const language = selectedOrSuggested.supportedLanguages[0];
        if (language && language !== "plaintext") {
          const newMode = this.db.createById(language).languageId;
          textModel.setLanguage(newMode);
        }
        $nBb.bindTo(this.eb).set(selectedOrSuggested.id);
      }
    }
  }
  layout(dimension, position) {
    this.a.classList.toggle("mid-width", dimension.width < 1e3 && dimension.width >= 600);
    this.a.classList.toggle("narrow-width", dimension.width < 600);
    const editorHeightChanged = dimension.height !== this.ob?.dimension.height;
    this.ob = { dimension, position };
    if (!this.f.value) {
      return;
    }
    if (editorHeightChanged && this.s) {
      $qdb.get(this.s)?.cancelSuggestWidget();
    }
    this.c.style.height = `${this.ob.dimension.height - this.yb}px`;
    this.Lb(dimension, position);
  }
  Lb(dimension, position) {
    const contentHeight = this.s.hasModel() ? this.s.getContentHeight() : this.zb;
    const maxHeight = Math.min(dimension.height / 2, contentHeight);
    const leftMargin = this.qb.getCellEditorContainerLeftMargin();
    const inputCellContainerHeight = maxHeight + INPUT_CELL_VERTICAL_PADDING * 2;
    this.c.style.height = `${dimension.height - inputCellContainerHeight}px`;
    this.f.value.layout(dimension.with(dimension.width, dimension.height - inputCellContainerHeight), this.c, position);
    this.s.layout(this.Mb(dimension.width - leftMargin - INPUT_CELL_HORIZONTAL_PADDING_RIGHT, maxHeight));
    this.j.style.height = `${contentHeight}px`;
    this.g.style.top = `${dimension.height - inputCellContainerHeight}px`;
    this.g.style.width = `${dimension.width}px`;
  }
  Mb(width2, height) {
    return new $rj(Math.max(0, width2), Math.max(0, height));
  }
  Nb() {
    return Boolean(this.s.getLineDecorations(1)?.find((d) => d.options.beforeContentClassName || d.options.afterContentClassName || d.options.before?.content || d.options.after?.content));
  }
  Ob() {
    if (!this.s) {
      return;
    }
    const shouldHide2 = !this.s.hasModel() || this.fb.getValue($78b.showExecutionHint) === false || this.s.getModel().getValueLength() !== 0 || this.Nb();
    if (!this.ub && !shouldHide2) {
      this.ub = this.cb.createInstance($88b, this.s);
    } else if (this.ub && shouldHide2) {
      this.ub.dispose();
      this.ub = void 0;
    }
  }
  getScrollPosition() {
    return {
      scrollTop: this.f.value?.scrollTop ?? 0,
      scrollLeft: 0
    };
  }
  setScrollPosition(position) {
    this.f.value?.setScrollTop(position.scrollTop);
  }
  focus() {
    super.focus();
    this.f.value?.onShow();
    this.s.focus();
  }
  focusHistory() {
    this.f.value.focus();
  }
  Z(visible) {
    super.Z(visible);
    this.sb.value = this.group.onWillCloseEditor((e) => this.Fb(e.editor));
    if (!visible) {
      this.Fb(this.input);
      if (this.input && this.f.value) {
        this.f.value.onWillHide();
      }
    }
    this.Ob();
  }
  clearInput() {
    if (this.f.value) {
      this.Fb(this.input);
      this.f.value.onWillHide();
    }
    this.s?.dispose();
    this.f = { value: void 0 };
    this.nb.clear();
    super.clearInput();
  }
  getControl() {
    return {
      notebookEditor: this.f.value,
      activeCodeEditor: this.s,
      onDidChangeActiveEditor: Event2.None
    };
  }
};
$_8b = __decorate([
  __param(1, $zv),
  __param(2, $gs),
  __param(3, $jv),
  __param(4, $Pk),
  __param(5, $yMb),
  __param(6, $on),
  __param(7, $U5),
  __param(8, $CL),
  __param(9, $1E),
  __param(10, $Ty),
  __param(11, $kl),
  __param(12, $cJ),
  __param(13, $50),
  __param(14, $iJ),
  __param(15, $zG),
  __param(16, $wL),
  __param(17, $wN)
], $_8b);

// out-build/vs/workbench/contrib/replNotebook/browser/replEditorInput.js
var $98b_1;
var replTabIcon = $9r("repl-editor-label-icon", $6l.debugLineByLine, localize(9364, null));
var $98b = class $98b2 extends $trb {
  static {
    $98b_1 = this;
  }
  static {
    this.ID = "workbench.editorinputs.replEditorInput";
  }
  constructor(resource, label3, _notebookService, _notebookModelResolverService, _fileDialogService, labelService, fileService, filesConfigurationService, extensionService, editorService, textResourceConfigurationService, customEditorLabelService, historyService, bb, configurationService) {
    super(resource, void 0, "jupyter-notebook", {}, _notebookService, _notebookModelResolverService, _fileDialogService, labelService, fileService, filesConfigurationService, extensionService, editorService, textResourceConfigurationService, customEditorLabelService);
    this.historyService = historyService;
    this.bb = bb;
    this.ab = false;
    this.Z = resource.scheme === "untitled" && configurationService.getValue($rM.InteractiveWindowPromptToSave) !== true;
    this.$ = label3 ?? this.cb(resource);
  }
  getIcon() {
    return replTabIcon;
  }
  cb(resource) {
    if (!resource) {
      return "REPL";
    }
    if (resource.scheme === "untitled") {
      const match = new RegExp("Untitled-(\\d+).").exec(resource.path);
      if (match?.length === 2) {
        return `REPL - ${match[1]}`;
      }
    }
    const filename = resource.path.split("/").pop();
    return filename ? `REPL - ${filename}` : "REPL";
  }
  get typeId() {
    return $98b_1.ID;
  }
  get editorId() {
    return "repl";
  }
  getName() {
    return this.$;
  }
  get editorInputs() {
    return [this];
  }
  get capabilities() {
    const capabilities = super.capabilities;
    const scratchPad = this.Z ? 512 : 0;
    return capabilities | 2 | scratchPad;
  }
  async resolve() {
    const model = await super.resolve();
    if (model) {
      this.db(model.notebook);
    }
    return model;
  }
  db(notebook) {
    const lastCell = notebook.cells[notebook.cells.length - 1];
    if (!lastCell || lastCell.cellKind === CellKind.Markup || lastCell.outputs.length > 0 || lastCell.internalMetadata.executionOrder !== void 0) {
      notebook.applyEdits([
        {
          editType: 1,
          index: notebook.cells.length,
          count: 0,
          cells: [
            {
              cellKind: CellKind.Code,
              language: "python",
              mime: void 0,
              outputs: [],
              source: ""
            }
          ]
        }
      ], true, void 0, () => void 0, void 0, false);
    }
  }
  async resolveInput(notebook) {
    if (this.Y) {
      return this.Y.object.textEditorModel;
    }
    const lastCell = notebook.cells[notebook.cells.length - 1];
    if (!lastCell) {
      throw new Error("The REPL editor requires at least one cell for the input box.");
    }
    this.Y = await this.bb.createModelReference(lastCell.uri);
    return this.Y.object.textEditorModel;
  }
  dispose() {
    if (!this.ab) {
      this.ab = true;
      this.c?.object.revert({ soft: true });
      this.Y?.dispose();
      super.dispose();
    }
  }
};
$98b = $98b_1 = __decorate([
  __param(2, $mrb),
  __param(3, $orb),
  __param(4, $1v),
  __param(5, $ZI),
  __param(6, $km),
  __param(7, $4J),
  __param(8, $wN),
  __param(9, $mJ),
  __param(10, $zG),
  __param(11, $qrb),
  __param(12, $YOb),
  __param(13, $oG),
  __param(14, $kl)
], $98b);

// out-build/vs/workbench/contrib/replNotebook/browser/replEditor.js
var INTERACTIVE_EDITOR_VIEW_STATE_PREFERENCE_KEY2 = "InteractiveEditorViewState";
var INPUT_CELL_VERTICAL_PADDING2 = 8;
var INPUT_CELL_HORIZONTAL_PADDING_RIGHT2 = 10;
var INPUT_EDITOR_PADDING2 = 8;
var $08b = class $08b2 extends $5tb {
  get onDidFocus() {
    return this.ub.event;
  }
  constructor(group2, telemetryService, themeService, storageService, instantiationService, notebookWidgetService, contextKeyService, notebookKernelService, languageService, keybindingService, configurationService, menuService, contextMenuService, editorGroupService, textResourceConfigurationService, notebookExecutionStateService, extensionService, xb) {
    super($fM, group2, telemetryService, themeService, storageService);
    this.xb = xb;
    this.f = { value: void 0 };
    this.mb = this.B(new $2c());
    this.rb = this.B(new $4c());
    this.ub = this.B(new $ze());
    this.vb = this.B(new $ze());
    this.onDidChangeSelection = this.vb.event;
    this.wb = this.B(new $ze());
    this.onDidChangeScroll = this.wb.event;
    this.u = notebookWidgetService;
    this.fb = configurationService;
    this.gb = notebookKernelService;
    this.db = languageService;
    this.hb = keybindingService;
    this.ib = menuService;
    this.jb = contextMenuService;
    this.kb = editorGroupService;
    this.lb = extensionService;
    this.a = $(".interactive-editor");
    this.eb = this.B(contextKeyService.createScoped(this.a));
    this.eb.createKey("isCompositeNotebook", true);
    this.cb = this.B(instantiationService.createChild(new $Ok([$on, this.eb])));
    this.ob = this.Db();
    this.B(this.fb.onDidChangeConfiguration((e) => {
      if (e.affectsConfiguration("editor") || e.affectsConfiguration("notebook")) {
        this.ob = this.Db();
      }
    }));
    this.pb = instantiationService.createInstance($xrb, this.window, true, { cellToolbarInteraction: "hover", globalToolbar: true, stickyScrollEnabled: false, dragAndDropEnabled: false });
    this.qb = this.ab(editorGroupService, textResourceConfigurationService, INTERACTIVE_EDITOR_VIEW_STATE_PREFERENCE_KEY2);
    this.B(this.hb.onDidUpdateKeybindings(this.Qb, this));
    this.B(notebookExecutionStateService.onDidChangeExecution((e) => {
      if (e.type === NotebookExecutionType.cell && $oh(e.notebook, this.f.value?.viewModel?.notebookDocument.uri)) {
        const cell = this.f.value?.getCellByHandle(e.cellHandle);
        if (cell && e.changed?.state) {
          this.Lb(cell);
        }
      }
    }));
  }
  get yb() {
    return 19 + 2 + INPUT_CELL_VERTICAL_PADDING2 * 2 + INPUT_EDITOR_PADDING2 * 2;
  }
  get zb() {
    return 19 + INPUT_EDITOR_PADDING2 * 2;
  }
  Y(parent) {
    $bk(parent, this.a);
    this.a.style.position = "relative";
    this.c = $bk(this.a, $(".notebook-editor-container"));
    this.g = $bk(this.a, $(".input-cell-container"));
    this.g.style.position = "absolute";
    this.g.style.height = `${this.yb}px`;
    this.j = $bk(this.g, $(".input-focus-indicator"));
    this.m = $bk(this.g, $(".run-button-container"));
    this.Bb(this.m);
    this.r = $bk(this.g, $(".input-editor-container"));
    this.Cb();
  }
  Bb(runButtonContainer) {
    const menu = this.B(this.ib.createMenu($bJ.ReplInputExecute, this.eb));
    this.sb = this.B(new $f3(runButtonContainer, this.jb, {
      getKeyBinding: (action) => this.hb.lookupKeybinding(action.id),
      actionViewItemProvider: (action, options3) => {
        return $X$(this.cb, action, options3);
      },
      renderDropdownAsChildElement: true
    }));
    const { primary, secondary } = $Q$(menu.getActions({ shouldForwardArgs: true }));
    this.sb.setActions([...primary, ...secondary]);
  }
  Cb() {
    this.b = $VZ(this.a);
    const styleSheets = [];
    const { codeCellLeftMargin, cellRunGutter } = this.pb.getLayoutConfiguration();
    const { focusIndicator } = this.pb.getDisplayOptions();
    const leftMargin = this.pb.getCellEditorContainerLeftMargin();
    styleSheets.push(`
			.interactive-editor .input-cell-container {
				padding: ${INPUT_CELL_VERTICAL_PADDING2}px ${INPUT_CELL_HORIZONTAL_PADDING_RIGHT2}px ${INPUT_CELL_VERTICAL_PADDING2}px ${leftMargin}px;
			}
		`);
    if (focusIndicator === "gutter") {
      styleSheets.push(`
				.interactive-editor .input-cell-container:focus-within .input-focus-indicator::before {
					border-color: var(--vscode-notebook-focusedCellBorder) !important;
				}
				.interactive-editor .input-focus-indicator::before {
					border-color: var(--vscode-notebook-inactiveFocusedCellBorder) !important;
				}
				.interactive-editor .input-cell-container .input-focus-indicator {
					display: block;
					top: ${INPUT_CELL_VERTICAL_PADDING2}px;
				}
				.interactive-editor .input-cell-container {
					border-top: 1px solid var(--vscode-notebook-inactiveFocusedCellBorder);
				}
			`);
    } else {
      styleSheets.push(`
				.interactive-editor .input-cell-container {
					border-top: 1px solid var(--vscode-notebook-inactiveFocusedCellBorder);
				}
				.interactive-editor .input-cell-container .input-focus-indicator {
					display: none;
				}
			`);
    }
    styleSheets.push(`
			.interactive-editor .input-cell-container .run-button-container {
				width: ${cellRunGutter}px;
				left: ${codeCellLeftMargin}px;
				margin-top: ${INPUT_EDITOR_PADDING2 - 2}px;
			}
		`);
    this.b.textContent = styleSheets.join("\n");
  }
  Db() {
    let overrideIdentifier = void 0;
    if (this.s) {
      overrideIdentifier = this.s.getModel()?.getLanguageId();
    }
    const editorOptions2 = $Lv(this.fb.getValue("editor", { overrideIdentifier }));
    const editorOptionsOverride = $Zsb(this.fb);
    const computed = Object.freeze({
      ...editorOptions2,
      ...editorOptionsOverride,
      ...{
        ariaLabel: localize(9349, null),
        glyphMargin: true,
        padding: {
          top: INPUT_EDITOR_PADDING2,
          bottom: INPUT_EDITOR_PADDING2
        },
        hover: {
          enabled: true
        }
      }
    });
    return computed;
  }
  I() {
    this.Fb(this.input);
    super.I();
  }
  getViewState() {
    const input = this.input;
    if (!(input instanceof $98b)) {
      return void 0;
    }
    this.Fb(input);
    return this.Gb(input);
  }
  Fb(input) {
    if (this.f.value && input instanceof $98b) {
      if (this.f.value.isDisposed) {
        return;
      }
      const state = this.f.value.getEditorViewState();
      const editorState = this.s.saveViewState();
      this.qb.saveEditorState(this.group, input.resource, {
        notebook: state,
        input: editorState
      });
    }
  }
  Gb(input) {
    const result = this.qb.loadEditorState(this.group, input.resource);
    if (result) {
      return result;
    }
    for (const group2 of this.kb.getGroups(
      1
      /* GroupsOrder.MOST_RECENTLY_ACTIVE */
    )) {
      if (group2.activeEditorPane !== this && group2.activeEditorPane === this && group2.activeEditor?.matches(input)) {
        const notebook = this.f.value?.getEditorViewState();
        const input2 = this.s.saveViewState();
        return {
          notebook,
          input: input2
        };
      }
    }
    return;
  }
  async setInput(input, options3, context, token) {
    this.f.value?.onWillHide();
    this.s?.dispose();
    this.mb.clear();
    this.f = this.cb.invokeFunction(this.u.retrieveWidget, this.group.id, input, {
      isReplHistory: true,
      isReadOnly: true,
      contributions: NotebookEditorExtensionsRegistry.getSomeEditorContributions([
        $E3b.id,
        $F3b.id,
        $q3b.id
      ]),
      menuIds: {
        notebookToolbar: $bJ.InteractiveToolbar,
        cellTitleToolbar: $bJ.InteractiveCellTitle,
        cellDeleteToolbar: $bJ.InteractiveCellDelete,
        cellInsertToolbar: $bJ.NotebookCellBetween,
        cellTopInsertToolbar: $bJ.NotebookCellListTop,
        cellExecuteToolbar: $bJ.InteractiveCellExecute,
        cellExecutePrimary: void 0
      },
      cellEditorContributions: EditorExtensionsRegistry.getSomeEditorContributions([
        $Fsb,
        $Mfb.ID,
        $Afb.ID,
        $Fib.ID,
        $nib.ID
      ]),
      options: this.pb,
      codeWindow: this.window
    }, void 0, this.window);
    this.s = this.cb.createInstance($D9, this.r, this.ob, {
      ...{
        isSimpleWidget: false,
        contributions: $_Lb().cellEditorContributions
      }
    });
    if (this.nb) {
      this.c.style.height = `${this.nb.dimension.height - this.yb}px`;
      this.f.value.layout(new $rj(this.nb.dimension.width, this.nb.dimension.height - this.yb), this.c);
      const leftMargin = this.pb.getCellEditorContainerLeftMargin();
      const maxHeight = Math.min(this.nb.dimension.height / 2, this.zb);
      this.s.layout(this.Ob(this.nb.dimension.width - leftMargin - INPUT_CELL_HORIZONTAL_PADDING_RIGHT2, maxHeight));
      this.j.style.height = `${this.zb}px`;
      this.g.style.top = `${this.nb.dimension.height - this.yb}px`;
      this.g.style.width = `${this.nb.dimension.width}px`;
    }
    await super.setInput(input, options3, context, token);
    const model = await input.resolve();
    if (this.sb) {
      this.sb.context = input.resource;
    }
    if (model === null) {
      throw new Error("The REPL model could not be resolved");
    }
    this.f.value?.setParentContextKeyService(this.eb);
    const viewState = options3?.viewState ?? this.Gb(input);
    await this.lb.whenInstalledExtensionsRegistered();
    await this.f.value.setModel(model.notebook, viewState?.notebook, void 0, "repl");
    model.notebook.setCellCollapseDefault(this.pb.getCellCollapseDefault());
    this.f.value.setOptions({
      isReadOnly: true
    });
    this.mb.add(this.f.value.onDidResizeOutput((cvm) => {
      this.Lb(cvm);
    }));
    this.mb.add(this.f.value.onDidFocusWidget(() => this.ub.fire()));
    this.mb.add(this.pb.onDidChangeOptions((e) => {
      if (e.compactView || e.focusIndicator) {
        this.b?.remove();
        this.Cb();
      }
      if (this.nb && this.isVisible()) {
        this.layout(this.nb.dimension, this.nb.position);
      }
      if (e.interactiveWindowCollapseCodeCells) {
        model.notebook.setCellCollapseDefault(this.pb.getCellCollapseDefault());
      }
    }));
    const editorModel = await input.resolveInput(model.notebook);
    this.s.setModel(editorModel);
    if (viewState?.input) {
      this.s.restoreViewState(viewState.input);
    }
    this.ob = this.Db();
    this.s.updateOptions(this.ob);
    this.mb.add(this.s.onDidFocusEditorWidget(() => this.ub.fire()));
    this.mb.add(this.s.onDidContentSizeChange((e) => {
      if (!e.contentHeightChanged) {
        return;
      }
      if (this.nb) {
        this.Nb(this.nb.dimension, this.nb.position);
      }
    }));
    this.mb.add(this.s.onDidChangeCursorPosition((e) => this.vb.fire({ reason: this.Jb(e) })));
    this.mb.add(this.s.onDidChangeModelContent(() => this.vb.fire({
      reason: 3
      /* EditorPaneSelectionChangeReason.EDIT */
    })));
    this.mb.add(this.gb.onDidChangeNotebookAffinity(this.Mb, this));
    this.mb.add(this.gb.onDidChangeSelectedNotebooks(this.Mb, this));
    this.mb.add(this.n.onDidColorThemeChange(() => {
      if (this.isVisible()) {
        this.Qb();
      }
    }));
    this.mb.add(this.s.onDidChangeModelContent(() => {
      if (this.isVisible()) {
        this.Qb();
      }
    }));
    this.s.onDidChangeModelDecorations(() => {
      if (this.isVisible()) {
        this.Qb();
      }
    });
    const cursorAtBoundaryContext = $68b.bindTo(this.eb);
    if (input.resource && input.historyService.has(input.resource)) {
      cursorAtBoundaryContext.set("top");
    } else {
      cursorAtBoundaryContext.set("none");
    }
    this.mb.add(this.s.onDidChangeCursorPosition(({ position }) => {
      const viewModel = this.s._getViewModel();
      const lastLineNumber = viewModel.getLineCount();
      const lastLineCol = viewModel.getLineLength(lastLineNumber) + 1;
      const viewPosition = viewModel.coordinatesConverter.convertModelPositionToViewPosition(position);
      const firstLine3 = viewPosition.lineNumber === 1 && viewPosition.column === 1;
      const lastLine = viewPosition.lineNumber === lastLineNumber && viewPosition.column === lastLineCol;
      if (firstLine3) {
        if (lastLine) {
          cursorAtBoundaryContext.set("both");
        } else {
          cursorAtBoundaryContext.set("top");
        }
      } else {
        if (lastLine) {
          cursorAtBoundaryContext.set("bottom");
        } else {
          cursorAtBoundaryContext.set("none");
        }
      }
    }));
    this.mb.add(editorModel.onDidChangeContent(() => {
      const value = editorModel.getValue();
      if (this.input?.resource && value !== "") {
        const historyService = this.input.historyService;
        if (!historyService.matchesCurrent(this.input.resource, value)) {
          historyService.replaceLast(this.input.resource, value);
        }
      }
    }));
    this.mb.add(this.f.value.onDidScroll(() => this.wb.fire()));
    this.mb.add(this.f.value.onDidChangeViewCells(this.Hb, this));
    this.Qb();
    this.Mb();
  }
  Hb(e) {
    const notebookWidget = this.f.value;
    if (!notebookWidget) {
      return;
    }
    for (const splice2 of e.splices) {
      const [_start, _delete, addedCells] = splice2;
      if (addedCells.length) {
        const viewModel = notebookWidget.viewModel;
        if (viewModel) {
          this.Ib(notebookWidget, viewModel);
          break;
        }
      }
    }
  }
  Ib(notebookWidget, viewModel) {
    this.u.updateReplContextKey(viewModel.notebookDocument.uri.toString());
    const navigateToCell = this.fb.getValue("accessibility.replEditor.autoFocusReplExecution");
    if (this.xb.isScreenReaderOptimized()) {
      if (navigateToCell === "lastExecution") {
        setTimeout(() => {
          const lastCellIndex = viewModel.length - 1;
          if (lastCellIndex >= 0) {
            const cell = viewModel.viewCells[lastCellIndex];
            notebookWidget.focusNotebookCell(cell, "container");
          }
        }, 0);
      } else if (navigateToCell === "input") {
        this.s.focus();
      }
    }
  }
  setOptions(options3) {
    this.f.value?.setOptions(options3);
    super.setOptions(options3);
  }
  Jb(e) {
    switch (e.source) {
      case "api":
        return 1;
      case "code.navigation":
        return 4;
      case "code.jump":
        return 5;
      default:
        return 2;
    }
  }
  Kb(cell) {
    const visibleRanges = this.f.value?.visibleRanges || [];
    const cellIndex = this.f.value?.getCellIndex(cell);
    if (cellIndex === Math.max(...visibleRanges.map((range) => range.end - 1))) {
      return true;
    }
    return false;
  }
  Lb(cvm) {
    const index = this.f.value.getCellIndex(cvm);
    if (index === this.f.value.getLength() - 1) {
      if (this.fb.getValue($78b.interactiveWindowAlwaysScrollOnNewCell) || this.Kb(cvm)) {
        this.f.value.scrollToBottom();
      }
    }
  }
  Mb() {
    const notebook = this.f.value?.textModel;
    const textModel = this.s.getModel();
    if (notebook && textModel) {
      const info = this.gb.getMatchingKernel(notebook);
      const selectedOrSuggested = info.selected ?? (info.suggestions.length === 1 ? info.suggestions[0] : void 0) ?? (info.all.length === 1 ? info.all[0] : void 0);
      if (selectedOrSuggested) {
        const language = selectedOrSuggested.supportedLanguages[0];
        if (language && language !== "plaintext") {
          const newMode = this.db.createById(language).languageId;
          textModel.setLanguage(newMode);
        }
        $nBb.bindTo(this.eb).set(selectedOrSuggested.id);
      }
    }
  }
  layout(dimension, position) {
    this.a.classList.toggle("mid-width", dimension.width < 1e3 && dimension.width >= 600);
    this.a.classList.toggle("narrow-width", dimension.width < 600);
    const editorHeightChanged = dimension.height !== this.nb?.dimension.height;
    this.nb = { dimension, position };
    if (!this.f.value) {
      return;
    }
    if (editorHeightChanged && this.s) {
      $qdb.get(this.s)?.cancelSuggestWidget();
    }
    this.c.style.height = `${this.nb.dimension.height - this.yb}px`;
    this.Nb(dimension, position);
  }
  Nb(dimension, position) {
    const contentHeight = this.s.hasModel() ? this.s.getContentHeight() : this.zb;
    const maxHeight = Math.min(dimension.height / 2, contentHeight);
    const leftMargin = this.pb.getCellEditorContainerLeftMargin();
    const inputCellContainerHeight = maxHeight + INPUT_CELL_VERTICAL_PADDING2 * 2;
    this.c.style.height = `${dimension.height - inputCellContainerHeight}px`;
    this.f.value.layout(dimension.with(dimension.width, dimension.height - inputCellContainerHeight), this.c, position);
    this.s.layout(this.Ob(dimension.width - leftMargin - INPUT_CELL_HORIZONTAL_PADDING_RIGHT2, maxHeight));
    this.j.style.height = `${contentHeight}px`;
    this.g.style.top = `${dimension.height - inputCellContainerHeight}px`;
    this.g.style.width = `${dimension.width}px`;
  }
  Ob(width2, height) {
    return new $rj(Math.max(0, width2), Math.max(0, height));
  }
  Pb() {
    return Boolean(this.s.getLineDecorations(1)?.find((d) => d.options.beforeContentClassName || d.options.afterContentClassName || d.options.before?.content || d.options.after?.content));
  }
  Qb() {
    if (!this.s) {
      return;
    }
    const shouldHide2 = !this.s.hasModel() || this.fb.getValue($78b.showExecutionHint) === false || this.s.getModel().getValueLength() !== 0 || this.Pb();
    if (!this.tb && !shouldHide2) {
      this.tb = this.cb.createInstance($88b, this.s);
    } else if (this.tb && shouldHide2) {
      this.tb.dispose();
      this.tb = void 0;
    }
  }
  getScrollPosition() {
    return {
      scrollTop: this.f.value?.scrollTop ?? 0,
      scrollLeft: 0
    };
  }
  setScrollPosition(position) {
    this.f.value?.setScrollTop(position.scrollTop);
  }
  focus() {
    super.focus();
    this.f.value?.onShow();
    this.s.focus();
  }
  focusHistory() {
    this.f.value.focus();
  }
  Z(visible) {
    super.Z(visible);
    this.rb.value = this.group.onWillCloseEditor((e) => this.Fb(e.editor));
    if (!visible) {
      this.Fb(this.input);
      if (this.input && this.f.value) {
        this.f.value.onWillHide();
      }
    }
    this.Qb();
  }
  clearInput() {
    if (this.f.value) {
      this.Fb(this.input);
      this.f.value.onWillHide();
    }
    this.s?.dispose();
    this.f = { value: void 0 };
    this.mb.clear();
    super.clearInput();
  }
  getControl() {
    return {
      notebookEditor: this.f.value,
      activeCodeEditor: this.Sb(),
      onDidChangeActiveEditor: Event2.None
    };
  }
  Sb() {
    if (!this.s) {
      return void 0;
    }
    return this.s.hasWidgetFocus() || !this.f.value?.activeCodeEditor ? this.s : this.f.value.activeCodeEditor;
  }
};
$08b = __decorate([
  __param(1, $zv),
  __param(2, $gs),
  __param(3, $jv),
  __param(4, $Pk),
  __param(5, $yMb),
  __param(6, $on),
  __param(7, $CL),
  __param(8, $1E),
  __param(9, $Ty),
  __param(10, $kl),
  __param(11, $cJ),
  __param(12, $50),
  __param(13, $iJ),
  __param(14, $zG),
  __param(15, $wL),
  __param(16, $wN),
  __param(17, $ND)
], $08b);
function $$8b(control) {
  const candidate = control;
  return candidate?.activeCodeEditor instanceof $D9 && candidate?.notebookEditor instanceof $aMb;
}

// out-build/vs/workbench/contrib/interactive/browser/interactive.contribution.js
var interactiveWindowCategory = localize2(7562, "Interactive Window");
$Wn.as($ZK.EditorPane).registerEditorPane($7tb.create($_8b, $eM, "Interactive Window"), [
  new $Nk($1Ob)
]);
var $a9b = class $a9b2 extends $3c {
  static {
    this.ID = "workbench.contrib.interactiveDocument";
  }
  constructor(notebookService, editorResolverService, editorService, a) {
    super();
    this.a = a;
    const info = notebookService.getContributedNotebookType("interactive");
    if (!info) {
      this.B(notebookService.registerContributedNotebookType("interactive", {
        providerDisplayName: "Interactive Notebook",
        displayName: "Interactive",
        filenamePattern: ["*.interactive"],
        priority: RegisteredEditorPriority.builtin
      }));
    }
    editorResolverService.registerEditor(`${Schemas.vscodeInteractiveInput}:/**`, {
      id: "vscode-interactive-input",
      label: "Interactive Editor",
      priority: RegisteredEditorPriority.exclusive
    }, {
      canSupportResource: (uri) => uri.scheme === Schemas.vscodeInteractiveInput,
      singlePerResource: true
    }, {
      createEditorInput: ({ resource }) => {
        const editorInput = editorService.getEditors(
          1
          /* EditorsOrder.SEQUENTIAL */
        ).find((editor) => editor.editor instanceof $1Ob && editor.editor.inputResource.toString() === resource.toString());
        return editorInput;
      }
    });
    editorResolverService.registerEditor(`*.interactive`, {
      id: "interactive",
      label: "Interactive Editor",
      priority: RegisteredEditorPriority.exclusive
    }, {
      canSupportResource: (uri) => uri.scheme === Schemas.untitled && $th(uri) === ".interactive" || uri.scheme === Schemas.vscodeNotebookCell && $th(uri) === ".interactive",
      singlePerResource: true
    }, {
      createEditorInput: ({ resource, options: options3 }) => {
        const data = CellUri.parse(resource);
        let cellOptions;
        let iwResource = resource;
        if (data) {
          cellOptions = { resource, options: options3 };
          iwResource = data.notebook;
        }
        const notebookOptions = {
          ...options3,
          cellOptions,
          cellRevealType: void 0,
          cellSelections: void 0,
          isReadOnly: void 0,
          viewState: void 0,
          indexedCellOptions: void 0
        };
        const editorInput = createEditor(iwResource, this.a);
        return {
          editor: editorInput,
          options: notebookOptions
        };
      },
      createUntitledEditorInput: ({ resource, options: options3 }) => {
        if (!resource) {
          throw new Error("Interactive window editors must have a resource name");
        }
        const data = CellUri.parse(resource);
        let cellOptions;
        if (data) {
          cellOptions = { resource, options: options3 };
        }
        const notebookOptions = {
          ...options3,
          cellOptions,
          cellRevealType: void 0,
          cellSelections: void 0,
          isReadOnly: void 0,
          viewState: void 0,
          indexedCellOptions: void 0
        };
        const editorInput = createEditor(resource, this.a);
        return {
          editor: editorInput,
          options: notebookOptions
        };
      }
    });
  }
};
$a9b = __decorate([
  __param(0, $mrb),
  __param(1, $4L),
  __param(2, $mJ),
  __param(3, $Pk)
], $a9b);
var InteractiveInputContentProvider = class InteractiveInputContentProvider2 {
  static {
    this.ID = "workbench.contrib.interactiveInputContentProvider";
  }
  constructor(textModelService, b) {
    this.b = b;
    this.a = textModelService.registerTextModelContentProvider(Schemas.vscodeInteractiveInput, this);
  }
  dispose() {
    this.a.dispose();
  }
  async provideTextContent(resource) {
    const existing = this.b.getModel(resource);
    if (existing) {
      return existing;
    }
    const result = this.b.createModel("", null, resource, false);
    return result;
  }
};
InteractiveInputContentProvider = __decorate([
  __param(0, $oG),
  __param(1, $sG)
], InteractiveInputContentProvider);
function createEditor(resource, instantiationService) {
  const counter = /\/Interactive-(\d+)/.exec(resource.path);
  const inputBoxPath = counter && counter[1] ? `/InteractiveInput-${counter[1]}` : "InteractiveInput";
  const inputUri = URI.from({ scheme: Schemas.vscodeInteractiveInput, path: inputBoxPath });
  const editorInput = $1Ob.create(instantiationService, resource, inputUri);
  return editorInput;
}
var InteractiveWindowWorkingCopyEditorHandler = class InteractiveWindowWorkingCopyEditorHandler2 extends $3c {
  static {
    this.ID = "workbench.contrib.interactiveWindowWorkingCopyEditorHandler";
  }
  constructor(a, b, c) {
    super();
    this.a = a;
    this.b = b;
    this.c = c;
    this.f();
  }
  handles(workingCopy) {
    const viewType = this.g(workingCopy);
    return !!viewType && viewType === "interactive";
  }
  isOpen(workingCopy, editor) {
    if (!this.handles(workingCopy)) {
      return false;
    }
    return editor instanceof $1Ob && $oh(workingCopy.resource, editor.resource);
  }
  createEditor(workingCopy) {
    return createEditor(workingCopy.resource, this.a);
  }
  async f() {
    await this.c.whenInstalledExtensionsRegistered();
    this.B(this.b.registerHandler(this));
  }
  g(workingCopy) {
    return $sM.parse(workingCopy.typeId)?.viewType;
  }
};
InteractiveWindowWorkingCopyEditorHandler = __decorate([
  __param(0, $Pk),
  __param(1, $6J),
  __param(2, $wN)
], InteractiveWindowWorkingCopyEditorHandler);
$PL(
  $a9b.ID,
  $a9b,
  2
  /* WorkbenchPhase.BlockRestore */
);
$PL(InteractiveInputContentProvider.ID, InteractiveInputContentProvider, {
  editorTypeId: $eM
});
$PL(InteractiveWindowWorkingCopyEditorHandler.ID, InteractiveWindowWorkingCopyEditorHandler, {
  editorTypeId: $eM
});
var $b9b = class {
  static {
    this.ID = $1Ob.ID;
  }
  canSerialize(editor) {
    if (!(editor instanceof $1Ob)) {
      return false;
    }
    return URI.isUri(editor.primary.resource) && URI.isUri(editor.inputResource);
  }
  serialize(input) {
    if (!this.canSerialize(input)) {
      return void 0;
    }
    return JSON.stringify({
      resource: input.primary.resource,
      inputResource: input.inputResource,
      name: input.getName(),
      language: input.language
    });
  }
  deserialize(instantiationService, raw) {
    const data = $bu(raw);
    if (!data) {
      return void 0;
    }
    const { resource, inputResource, name, language } = data;
    if (!URI.isUri(resource) || !URI.isUri(inputResource)) {
      return void 0;
    }
    const input = $1Ob.create(instantiationService, resource, inputResource, name, language);
    return input;
  }
};
$Wn.as($ZK.EditorFactory).registerEditorSerializer($b9b.ID, $b9b);
$SC(
  $YOb,
  $ZOb,
  1
  /* InstantiationType.Delayed */
);
$SC(
  $WOb,
  $XOb,
  1
  /* InstantiationType.Delayed */
);
$hJ(class extends $gJ {
  constructor() {
    super({
      id: "_interactive.open",
      title: localize2(7563, "Open Interactive Window"),
      f1: false,
      category: interactiveWindowCategory,
      metadata: {
        description: localize(7553, null),
        args: [
          {
            name: "showOptions",
            description: "Show Options",
            schema: {
              type: "object",
              properties: {
                "viewColumn": {
                  type: "number",
                  default: -1
                },
                "preserveFocus": {
                  type: "boolean",
                  default: true
                }
              }
            }
          },
          {
            name: "resource",
            description: "Interactive resource Uri",
            isOptional: true
          },
          {
            name: "controllerId",
            description: "Notebook controller Id",
            isOptional: true
          },
          {
            name: "title",
            description: "Notebook editor title",
            isOptional: true
          }
        ]
      }
    });
  }
  async run(accessor, showOptions, resource, id2, title) {
    const editorService = accessor.get($mJ);
    const editorGroupService = accessor.get($iJ);
    const historyService = accessor.get($YOb);
    const kernelService = accessor.get($CL);
    const logService = accessor.get($wn);
    const configurationService = accessor.get($kl);
    const group2 = $zS(editorGroupService, configurationService, typeof showOptions === "number" ? showOptions : showOptions?.viewColumn);
    const editorOptions2 = {
      activation: EditorActivation.PRESERVE,
      preserveFocus: typeof showOptions !== "number" ? showOptions?.preserveFocus ?? false : false
    };
    if (resource && $th(resource) === ".interactive") {
      logService.debug("Open interactive window from resource:", resource.toString());
      const resourceUri = URI.revive(resource);
      const editors = editorService.findEditors(resourceUri).filter((id3) => id3.editor instanceof $1Ob && id3.editor.resource?.toString() === resourceUri.toString());
      if (editors.length) {
        logService.debug("Find existing interactive window:", resource.toString());
        const editorInput2 = editors[0].editor;
        const currentGroup = editors[0].groupId;
        const editor = await editorService.openEditor(editorInput2, editorOptions2, currentGroup);
        const editorControl2 = editor?.getControl();
        return {
          notebookUri: editorInput2.resource,
          inputUri: editorInput2.inputResource,
          notebookEditorId: editorControl2?.notebookEditor?.getId()
        };
      }
    }
    const existingNotebookDocument = /* @__PURE__ */ new Set();
    editorService.getEditors(
      1
      /* EditorsOrder.SEQUENTIAL */
    ).forEach((editor) => {
      if (editor.editor.resource) {
        existingNotebookDocument.add(editor.editor.resource.toString());
      }
    });
    let notebookUri = void 0;
    let inputUri = void 0;
    let counter = 1;
    do {
      notebookUri = URI.from({ scheme: Schemas.untitled, path: `/Interactive-${counter}.interactive` });
      inputUri = URI.from({ scheme: Schemas.vscodeInteractiveInput, path: `/InteractiveInput-${counter}` });
      counter++;
    } while (existingNotebookDocument.has(notebookUri.toString()));
    $1Ob.setName(notebookUri, title);
    logService.debug("Open new interactive window:", notebookUri.toString(), inputUri.toString());
    if (id2) {
      const allKernels = kernelService.getMatchingKernel({ uri: notebookUri, notebookType: "interactive" }).all;
      const preferredKernel = allKernels.find((kernel) => kernel.id === id2);
      if (preferredKernel) {
        kernelService.preselectKernelForNotebook(preferredKernel, { uri: notebookUri, notebookType: "interactive" });
      }
    }
    historyService.clearHistory(notebookUri);
    const editorInput = { resource: notebookUri, options: editorOptions2 };
    const editorPane = await editorService.openEditor(editorInput, group2);
    const editorControl = editorPane?.getControl();
    logService.debug("New interactive window opened. Notebook editor id", editorControl?.notebookEditor?.getId());
    return { notebookUri, inputUri, notebookEditorId: editorControl?.notebookEditor?.getId() };
  }
});
$hJ(class extends $gJ {
  constructor() {
    super({
      id: "interactive.execute",
      title: localize2(7564, "Execute Code"),
      category: interactiveWindowCategory,
      keybinding: [{
        // when: NOTEBOOK_CELL_LIST_FOCUSED,
        when: $7m.and($VAb, $7m.equals("activeEditor", "workbench.editor.interactive")),
        primary: 2048 | 3,
        weight: $AIb
      }, {
        when: $7m.and($VAb, $7m.equals("activeEditor", "workbench.editor.interactive"), $7m.equals("config.interactiveWindow.executeWithShiftEnter", true)),
        primary: 1024 | 3,
        weight: $AIb
      }, {
        when: $7m.and($VAb, $7m.equals("activeEditor", "workbench.editor.interactive"), $7m.equals("config.interactiveWindow.executeWithShiftEnter", false)),
        primary: 3,
        weight: $AIb
      }],
      menu: [
        {
          id: $bJ.InteractiveInputExecute
        }
      ],
      icon: $CKb,
      f1: false,
      metadata: {
        description: "Execute the Contents of the Input Box",
        args: [
          {
            name: "resource",
            description: "Interactive resource Uri",
            isOptional: true
          }
        ]
      }
    });
  }
  async run(accessor, context) {
    const editorService = accessor.get($mJ);
    const bulkEditService = accessor.get($H_);
    const historyService = accessor.get($YOb);
    const notebookEditorService = accessor.get($yMb);
    let editorControl;
    if (context) {
      const resourceUri = URI.revive(context);
      const editors = editorService.findEditors(resourceUri);
      for (const found of editors) {
        if (found.editor.typeId === $1Ob.ID) {
          const editor = await editorService.openEditor(found.editor, found.groupId);
          editorControl = editor?.getControl();
          break;
        }
      }
    } else {
      editorControl = editorService.activeEditorPane?.getControl();
    }
    if (editorControl && $$8b(editorControl) && editorControl.notebookEditor) {
      const notebookDocument = editorControl.notebookEditor.textModel;
      const textModel = editorControl.activeCodeEditor?.getModel();
      const activeKernel = editorControl.notebookEditor.activeKernel;
      const language = activeKernel?.supportedLanguages[0] ?? $KF;
      if (notebookDocument && textModel && editorControl.activeCodeEditor) {
        const index = notebookDocument.length;
        const value = textModel.getValue();
        if ($vf(value)) {
          return;
        }
        const ctrl = $cHb.get(editorControl.activeCodeEditor);
        if (ctrl) {
          ctrl.acceptHunk();
        }
        historyService.replaceLast(notebookDocument.uri, value);
        historyService.addToHistory(notebookDocument.uri, "");
        textModel.setValue("");
        const collapseState = editorControl.notebookEditor.notebookOptions.getDisplayOptions().interactiveWindowCollapseCodeCells === "fromEditor" ? {
          inputCollapsed: false,
          outputCollapsed: false
        } : void 0;
        await bulkEditService.apply([
          new $Trb(notebookDocument.uri, {
            editType: 1,
            index,
            count: 0,
            cells: [{
              cellKind: CellKind.Code,
              mime: void 0,
              language,
              source: value,
              outputs: [],
              metadata: {},
              collapseState
            }]
          })
        ]);
        const range = { start: index, end: index + 1 };
        editorControl.notebookEditor.revealCellRangeInView(range);
        await editorControl.notebookEditor.executeNotebookCells(editorControl.notebookEditor.getCellsInRange({ start: index, end: index + 1 }));
        const editor = notebookEditorService.getNotebookEditor(editorControl.notebookEditor.getId());
        if (editor) {
          editor.setSelections([range]);
          editor.setFocus(range);
        }
      }
    }
  }
});
$hJ(class extends $gJ {
  constructor() {
    super({
      id: "interactive.input.clear",
      title: localize2(7565, "Clear the interactive window input editor contents"),
      category: interactiveWindowCategory,
      f1: false
    });
  }
  async run(accessor) {
    const editorService = accessor.get($mJ);
    const editorControl = editorService.activeEditorPane?.getControl();
    if (editorControl && $$8b(editorControl) && editorControl.notebookEditor) {
      const notebookDocument = editorControl.notebookEditor.textModel;
      const editor = editorControl.activeCodeEditor;
      const range = editor?.getModel()?.getFullModelRange();
      if (notebookDocument && editor && range) {
        editor.executeEdits("", [$bD.replace(range, null)]);
      }
    }
  }
});
$hJ(class extends $gJ {
  constructor() {
    super({
      id: "interactive.history.previous",
      title: localize2(7566, "Previous value in history"),
      category: interactiveWindowCategory,
      f1: false,
      keybinding: {
        when: $7m.and($68b.notEqualsTo("bottom"), $68b.notEqualsTo("none"), $_bb.Visible.toNegated()),
        primary: 16,
        weight: 200
        /* KeybindingWeight.WorkbenchContrib */
      },
      precondition: $7m.and($VAb, $WAb.negate())
    });
  }
  async run(accessor) {
    const editorService = accessor.get($mJ);
    const historyService = accessor.get($YOb);
    const editorControl = editorService.activeEditorPane?.getControl();
    if (editorControl && $$8b(editorControl) && editorControl.notebookEditor) {
      const notebookDocument = editorControl.notebookEditor.textModel;
      const textModel = editorControl.activeCodeEditor?.getModel();
      if (notebookDocument && textModel) {
        const previousValue = historyService.getPreviousValue(notebookDocument.uri);
        if (previousValue) {
          textModel.setValue(previousValue);
        }
      }
    }
  }
});
$hJ(class extends $gJ {
  constructor() {
    super({
      id: "interactive.history.next",
      title: localize2(7567, "Next value in history"),
      category: interactiveWindowCategory,
      f1: false,
      keybinding: {
        when: $7m.and($68b.notEqualsTo("top"), $68b.notEqualsTo("none"), $_bb.Visible.toNegated()),
        primary: 18,
        weight: 200
        /* KeybindingWeight.WorkbenchContrib */
      },
      precondition: $7m.and($VAb, $WAb.negate())
    });
  }
  async run(accessor) {
    const editorService = accessor.get($mJ);
    const historyService = accessor.get($YOb);
    const editorControl = editorService.activeEditorPane?.getControl();
    if (editorControl && $$8b(editorControl) && editorControl.notebookEditor) {
      const notebookDocument = editorControl.notebookEditor.textModel;
      const textModel = editorControl.activeCodeEditor?.getModel();
      if (notebookDocument && textModel) {
        const nextValue = historyService.getNextValue(notebookDocument.uri);
        if (nextValue !== null) {
          textModel.setValue(nextValue);
        }
      }
    }
  }
});
$hJ(class extends $gJ {
  constructor() {
    super({
      id: "interactive.scrollToTop",
      title: localize(7554, null),
      keybinding: {
        when: $7m.equals("activeEditor", "workbench.editor.interactive"),
        primary: 2048 | 14,
        mac: {
          primary: 2048 | 16
          /* KeyCode.UpArrow */
        },
        weight: 200
        /* KeybindingWeight.WorkbenchContrib */
      },
      category: interactiveWindowCategory
    });
  }
  async run(accessor) {
    const editorService = accessor.get($mJ);
    const editorControl = editorService.activeEditorPane?.getControl();
    if (editorControl && $$8b(editorControl) && editorControl.notebookEditor) {
      if (editorControl.notebookEditor.getLength() === 0) {
        return;
      }
      editorControl.notebookEditor.revealCellRangeInView({ start: 0, end: 1 });
    }
  }
});
$hJ(class extends $gJ {
  constructor() {
    super({
      id: "interactive.scrollToBottom",
      title: localize(7555, null),
      keybinding: {
        when: $7m.equals("activeEditor", "workbench.editor.interactive"),
        primary: 2048 | 13,
        mac: {
          primary: 2048 | 18
          /* KeyCode.DownArrow */
        },
        weight: 200
        /* KeybindingWeight.WorkbenchContrib */
      },
      category: interactiveWindowCategory
    });
  }
  async run(accessor) {
    const editorService = accessor.get($mJ);
    const editorControl = editorService.activeEditorPane?.getControl();
    if (editorControl && $$8b(editorControl) && editorControl.notebookEditor) {
      if (editorControl.notebookEditor.getLength() === 0) {
        return;
      }
      const len = editorControl.notebookEditor.getLength();
      editorControl.notebookEditor.revealCellRangeInView({ start: len - 1, end: len });
    }
  }
});
$hJ(class extends $gJ {
  constructor() {
    super({
      id: "interactive.input.focus",
      title: localize2(7568, "Focus Input Editor"),
      category: interactiveWindowCategory,
      menu: {
        id: $bJ.CommandPalette,
        when: $QAb
      }
    });
  }
  async run(accessor) {
    const editorService = accessor.get($mJ);
    const editorControl = editorService.activeEditorPane?.getControl();
    if (editorControl && $$8b(editorControl) && editorControl.notebookEditor) {
      editorService.activeEditorPane?.focus();
    } else {
      const openEditors = editorService.getEditors(
        0
        /* EditorsOrder.MOST_RECENTLY_ACTIVE */
      );
      const interactiveWindow = Iterable.find(openEditors, (identifier2) => {
        return identifier2.editor.typeId === $1Ob.ID;
      });
      if (interactiveWindow) {
        const editorInput = interactiveWindow.editor;
        const currentGroup = interactiveWindow.groupId;
        const editor = await editorService.openEditor(editorInput, currentGroup);
        const editorControl2 = editor?.getControl();
        if (editorControl2 && $$8b(editorControl2) && editorControl2.notebookEditor) {
          editorService.activeEditorPane?.focus();
        }
      }
    }
  }
});
$hJ(class extends $gJ {
  constructor() {
    super({
      id: "interactive.history.focus",
      title: localize2(7569, "Focus History"),
      category: interactiveWindowCategory,
      menu: {
        id: $bJ.CommandPalette,
        when: $7m.equals("activeEditor", "workbench.editor.interactive")
      },
      keybinding: [
        {
          // On mac, require that the cursor is at the top of the input, to avoid stealing cmd+up to move the cursor to the top
          when: $7m.and($68b.notEqualsTo("bottom"), $68b.notEqualsTo("none")),
          weight: 200 + 5,
          primary: 2048 | 16
          /* KeyCode.UpArrow */
        },
        {
          when: $7m.or($ueb, $teb),
          weight: 200,
          primary: 2048 | 16
        }
      ],
      precondition: $7m.and($VAb, $WAb.negate())
    });
  }
  async run(accessor) {
    const editorService = accessor.get($mJ);
    const editorControl = editorService.activeEditorPane?.getControl();
    if (editorControl && $$8b(editorControl) && editorControl.notebookEditor) {
      editorControl.notebookEditor.focus();
    }
  }
});
$5n("interactive.activeCodeBorder", {
  dark: $ao($geb, $geb, "#007acc"),
  light: $ao($geb, $geb, "#007acc"),
  hcDark: $ko,
  hcLight: $ko
}, localize(7556, null));
$5n("interactive.inactiveCodeBorder", {
  //dark: theme.getColor(listInactiveSelectionBackground) ?? transparent(listInactiveSelectionBackground, 1),
  dark: $ao($lr, $lr, "#37373D"),
  light: $ao($lr, $lr, "#E4E6F1"),
  hcDark: $Jmb,
  hcLight: $Jmb
}, localize(7557, null));
$Wn.as($Ht.Configuration).registerConfiguration({
  id: "interactiveWindow",
  order: 100,
  type: "object",
  "properties": {
    [$78b.interactiveWindowAlwaysScrollOnNewCell]: {
      type: "boolean",
      default: true,
      markdownDescription: localize(7558, null)
    },
    [$rM.InteractiveWindowPromptToSave]: {
      type: "boolean",
      default: false,
      markdownDescription: localize(7559, null)
    },
    [$78b.executeWithShiftEnter]: {
      type: "boolean",
      default: false,
      markdownDescription: localize(7560, null),
      tags: ["replExecute"]
    },
    [$78b.showExecutionHint]: {
      type: "boolean",
      default: true,
      markdownDescription: localize(7561, null),
      tags: ["replExecute"]
    }
  }
});

// out-build/vs/workbench/contrib/debug/browser/debugActionViewItems.js
var $c9b_1;
var $134 = $;
var $c9b = class $c9b2 extends $T1 {
  static {
    $c9b_1 = this;
  }
  static {
    this.a = "\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500";
  }
  constructor(t, action, options3, y, L, M, N, contextViewService, O, P, Q) {
    super(t, action, options3);
    this.t = t;
    this.y = y;
    this.L = L;
    this.M = M;
    this.N = N;
    this.O = O;
    this.P = P;
    this.Q = Q;
    this.h = [];
    this.n = 0;
    this.r = [];
    this.m = [];
    this.g = new $N1([], -1, contextViewService, $K$, { ariaLabel: localize(5736, null) });
    this.g.setFocusable(false);
    this.m.push(this.g);
    this.R();
  }
  R() {
    this.m.push(this.L.onDidChangeConfiguration((e) => {
      if (e.affectsConfiguration("launch")) {
        this.S();
      }
    }));
    this.m.push(this.y.getConfigurationManager().onDidSelectConfiguration(() => {
      this.S();
    }));
  }
  render(container2) {
    this.b = container2;
    container2.classList.add("start-debug-action-item");
    this.c = $bk(container2, $134(ThemeIcon.asCSSSelector($ZFb)));
    const keybinding = this.O.lookupKeybinding(this.action.id)?.getLabel();
    const keybindingLabel = keybinding ? ` (${keybinding})` : "";
    const title = this.action.label + keybindingLabel;
    this.m.push(this.P.setupManagedHover($JZ("mouse"), this.c, title));
    this.c.setAttribute("role", "button");
    this.U(title);
    this.m.push($_i(this.c, $7j.CLICK, () => {
      this.c.blur();
      if (this.y.state !== 1) {
        this.actionRunner.run(this.action, this.t);
      }
    }));
    this.m.push($_i(this.c, $7j.MOUSE_DOWN, (e) => {
      if (this.action.enabled && e.button === 0) {
        this.c.classList.add("active");
      }
    }));
    this.m.push($_i(this.c, $7j.MOUSE_UP, () => {
      this.c.classList.remove("active");
    }));
    this.m.push($_i(this.c, $7j.MOUSE_OUT, () => {
      this.c.classList.remove("active");
    }));
    this.m.push($_i(this.c, $7j.KEY_DOWN, (e) => {
      const event = new $if(e);
      if (event.equals(
        17
        /* KeyCode.RightArrow */
      )) {
        this.c.tabIndex = -1;
        this.g.focus();
        event.stopPropagation();
      }
    }));
    this.m.push(this.g.onDidSelect(async (e) => {
      const target = this.h[e.index];
      const shouldBeSelected = target.handler ? await target.handler() : false;
      if (shouldBeSelected) {
        this.n = e.index;
      } else {
        this.g.select(this.n);
      }
    }));
    const selectBoxContainer = $134(".configuration");
    this.g.render($bk(container2, selectBoxContainer));
    this.m.push($_i(selectBoxContainer, $7j.KEY_DOWN, (e) => {
      const event = new $if(e);
      if (event.equals(
        15
        /* KeyCode.LeftArrow */
      )) {
        this.g.setFocusable(false);
        this.c.tabIndex = 0;
        this.c.focus();
        event.stopPropagation();
      }
    }));
    this.b.style.border = `1px solid ${$Zn($Rq)}`;
    selectBoxContainer.style.borderLeft = `1px solid ${$Zn($Rq)}`;
    this.b.style.backgroundColor = $Zn($Oq);
    const configManager = this.y.getConfigurationManager();
    const updateDynamicConfigs = () => configManager.getDynamicProviders().then((providers2) => {
      if (providers2.length !== this.r.length) {
        this.r = providers2;
        this.S();
      }
    });
    this.m.push(configManager.onDidChangeConfigurationProviders(updateDynamicConfigs));
    updateDynamicConfigs();
    this.S();
  }
  setActionContext(context) {
    this.t = context;
  }
  isEnabled() {
    return true;
  }
  focus(fromRight) {
    if (fromRight) {
      this.g.focus();
    } else {
      this.c.tabIndex = 0;
      this.c.focus();
    }
  }
  blur() {
    this.c.tabIndex = -1;
    this.g.blur();
    this.b.blur();
  }
  setFocusable(focusable) {
    if (focusable) {
      this.c.tabIndex = 0;
    } else {
      this.c.tabIndex = -1;
      this.g.setFocusable(false);
    }
  }
  dispose() {
    this.m = $Xc(this.m);
    super.dispose();
  }
  S() {
    this.n = 0;
    this.h = [];
    const manager = this.y.getConfigurationManager();
    const inWorkspace = this.N.getWorkbenchState() === 3;
    let lastGroup;
    const disabledIdxs = [];
    manager.getAllConfigurations().forEach(({ launch, name, presentation: presentation2 }) => {
      if (lastGroup !== presentation2?.group) {
        lastGroup = presentation2?.group;
        if (this.h.length) {
          this.h.push({ label: $c9b_1.a, handler: () => Promise.resolve(false) });
          disabledIdxs.push(this.h.length - 1);
        }
      }
      if (name === manager.selectedConfiguration.name && launch === manager.selectedConfiguration.launch) {
        this.n = this.h.length;
      }
      const label3 = inWorkspace ? `${name} (${launch.name})` : name;
      this.h.push({
        label: label3,
        handler: async () => {
          await manager.selectConfiguration(launch, name);
          return true;
        }
      });
    });
    manager.getRecentDynamicConfigurations().slice(0, 3).forEach(({ name, type }) => {
      if (type === manager.selectedConfiguration.type && manager.selectedConfiguration.name === name) {
        this.n = this.h.length;
      }
      this.h.push({
        label: name,
        handler: async () => {
          await manager.selectConfiguration(void 0, name, void 0, { type });
          return true;
        }
      });
    });
    if (this.h.length === 0) {
      this.h.push({ label: localize(5737, null), handler: async () => false });
    }
    this.h.push({ label: $c9b_1.a, handler: () => Promise.resolve(false) });
    disabledIdxs.push(this.h.length - 1);
    this.r.forEach((p) => {
      this.h.push({
        label: `${p.label}...`,
        handler: async () => {
          const picked = await p.pick();
          if (picked) {
            await manager.selectConfiguration(picked.launch, picked.config.name, picked.config, { type: p.type });
            return true;
          }
          return false;
        }
      });
    });
    manager.getLaunches().filter((l) => !l.hidden).forEach((l) => {
      const label3 = inWorkspace ? localize(5738, null, l.name) : localize(5739, null);
      this.h.push({
        label: label3,
        handler: async () => {
          await this.M.executeCommand($y4b, l.uri.toString());
          return false;
        }
      });
    });
    this.g.setOptions(this.h.map((data, index) => ({ text: data.label, isDisabled: disabledIdxs.indexOf(index) !== -1 })), this.n);
  }
  U(title) {
    let ariaLabel = title;
    let keybinding;
    const verbose = this.L.getValue(
      "accessibility.verbosity.debug"
      /* AccessibilityVerbositySettingId.Debug */
    );
    if (verbose) {
      keybinding = this.O.lookupKeybinding("editor.action.accessibilityHelp", this.Q)?.getLabel() ?? void 0;
    }
    if (keybinding) {
      ariaLabel = localize(5740, null, ariaLabel, keybinding);
    } else {
      ariaLabel = localize(5741, null, ariaLabel);
    }
    this.c.ariaLabel = ariaLabel;
  }
};
$c9b = $c9b_1 = __decorate([
  __param(3, $0R),
  __param(4, $kl),
  __param(5, $sn),
  __param(6, $Zk),
  __param(7, $40),
  __param(8, $Ty),
  __param(9, $5$),
  __param(10, $on)
], $c9b);
var $d9b = class $d9b2 extends $V1 {
  constructor(action, session, a, contextViewService, r2) {
    super(null, action, [], -1, contextViewService, $K$, { ariaLabel: localize(5742, null) });
    this.a = a;
    this.r = r2;
    this.B(this.a.getViewModel().onDidFocusSession(() => {
      const session2 = this.L();
      if (session2) {
        const index = this.M().indexOf(session2);
        this.select(index);
      }
    }));
    this.B(this.a.onDidNewSession((session2) => {
      const sessionListeners = [];
      sessionListeners.push(session2.onDidChangeName(() => this.y()));
      sessionListeners.push(session2.onDidEndAdapter(() => $Xc(sessionListeners)));
      this.y();
    }));
    this.M().forEach((session2) => {
      this.B(session2.onDidChangeName(() => this.y()));
    });
    this.B(this.a.onDidEndSession(() => this.y()));
    const selectedSession = session ? this.N(session) : void 0;
    this.y(selectedSession);
  }
  n(_, index) {
    return this.M()[index];
  }
  y(session) {
    if (!session) {
      session = this.L();
    }
    const sessions = this.M();
    const names = sessions.map((s) => {
      const label3 = s.getLabel();
      if (s.parentSession) {
        return `\xA0\xA0${label3}`;
      }
      return label3;
    });
    this.setOptions(names.map((data) => ({ text: data })), session ? sessions.indexOf(session) : void 0);
  }
  L() {
    const session = this.a.getViewModel().focusedSession;
    return session ? this.N(session) : void 0;
  }
  M() {
    const showSubSessions = this.r.getValue("debug").showSubSessionsInToolBar;
    const sessions = this.a.getModel().getSessions();
    return showSubSessions ? sessions : sessions.filter((s) => !s.parentSession);
  }
  N(focusedSession) {
    const showSubSessions = this.r.getValue("debug").showSubSessionsInToolBar;
    while (focusedSession.parentSession && !showSubSessions) {
      focusedSession = focusedSession.parentSession;
    }
    return focusedSession;
  }
};
$d9b = __decorate([
  __param(2, $0R),
  __param(3, $40),
  __param(4, $kl)
], $d9b);

// out-build/vs/workbench/contrib/debug/browser/replFilter.js
var $e9b = class _$e9b {
  constructor() {
    this.a = [];
  }
  static {
    this.matchQuery = $Rl;
  }
  set filterQuery(query) {
    this.a = [];
    query = query.trim();
    if (query && query !== "") {
      const filters2 = $Bl(query, ",").map((s) => s.trim()).filter((s) => !!s.length);
      for (const f of filters2) {
        if (f.startsWith("\\")) {
          this.a.push({ type: "include", query: f.slice(1) });
        } else if (f.startsWith("!")) {
          this.a.push({ type: "exclude", query: f.slice(1) });
        } else {
          this.a.push({ type: "include", query: f });
        }
      }
    }
  }
  filter(element, parentVisibility) {
    if (element instanceof $l4b || element instanceof $m4b || element instanceof $MP) {
      return 1;
    }
    let includeQueryPresent = false;
    let includeQueryMatched = false;
    const text2 = element.toString(true);
    for (const { type, query } of this.a) {
      if (type === "exclude" && _$e9b.matchQuery(query, text2)) {
        return false;
      } else if (type === "include") {
        includeQueryPresent = true;
        if (_$e9b.matchQuery(query, text2)) {
          includeQueryMatched = true;
        }
      }
    }
    return includeQueryPresent ? includeQueryMatched : typeof parentVisibility !== "undefined" ? parentVisibility : 1;
  }
};

// out-build/vs/workbench/contrib/debug/browser/baseDebugView.js
var $135 = $;
function $q4b(container2) {
  const treeContainer = $135(".");
  treeContainer.classList.add("debug-view-content");
  container2.appendChild(treeContainer);
  return treeContainer;
}
var $r4b = class $r4b2 {
  constructor(a, b) {
    this.a = a;
    this.b = b;
  }
  async getChildren(element) {
    const vm = this.a.getViewModel();
    const children = await this.c(element);
    return Promise.all(children.map(async (r2) => {
      const vizOrTree = vm.getVisualizedExpression(r2);
      if (typeof vizOrTree === "string") {
        const viz = await this.b.getVisualizedNodeFor(vizOrTree, r2);
        if (viz) {
          vm.setVisualizedExpression(r2, viz);
          return viz;
        }
      } else if (vizOrTree) {
        return vizOrTree;
      }
      return r2;
    }));
  }
};
$r4b = __decorate([
  __param(0, $0R),
  __param(1, $FP)
], $r4b);
var $s4b = class $s4b2 {
  constructor(a, b, c) {
    this.a = a;
    this.b = b;
    this.c = c;
  }
  renderTemplate(container2) {
    const templateDisposable = new $2c();
    const expression = $bk(container2, $135(".expression"));
    const name = $bk(expression, $135("span.name"));
    const lazyButton = $bk(expression, $135("span.lazy-button"));
    lazyButton.classList.add(...ThemeIcon.asClassNameArray($6l.eye));
    templateDisposable.add(this.c.setupManagedHover($JZ("mouse"), lazyButton, localize(5476, null)));
    const type = $bk(expression, $135("span.type"));
    const value = $bk(expression, $135("span.value"));
    const label3 = templateDisposable.add(new $S2(name));
    const inputBoxContainer = $bk(expression, $135(".inputBoxContainer"));
    let actionBar;
    if (this.h) {
      $bk(expression, $135(".span.actionbar-spacer"));
      actionBar = templateDisposable.add(new $LZ(expression));
    }
    const template = { expression, name, type, value, label: label3, inputBoxContainer, actionBar, elementDisposable: new $2c(), templateDisposable, lazyButton, currentElement: void 0 };
    templateDisposable.add($_i(lazyButton, $7j.CLICK, () => {
      if (template.currentElement) {
        this.a.getViewModel().evaluateLazyExpression(template.currentElement);
      }
    }));
    return template;
  }
  d(element, node, data) {
    data.currentElement = element;
    this.f(node.element, data, $Ul(node.filterData));
    if (data.actionBar) {
      this.h(data.actionBar, element, data);
    }
    const selectedExpression = this.a.getViewModel().getSelectedExpression();
    if (element === selectedExpression?.expression || element instanceof $MP && element.errorMessage) {
      const options3 = this.g(element, !!selectedExpression?.settingWatch);
      if (options3) {
        data.elementDisposable.add(this.renderInputBox(data.name, data.value, data.inputBoxContainer, options3));
      }
    }
  }
  renderInputBox(nameElement, valueElement, inputBoxContainer, options3) {
    nameElement.style.display = "none";
    valueElement.style.display = "none";
    inputBoxContainer.style.display = "initial";
    $$i(inputBoxContainer);
    const inputBox = new $I2(inputBoxContainer, this.b, { ...options3, inputBoxStyles: $B$ });
    inputBox.value = options3.initialValue;
    inputBox.focus();
    inputBox.select();
    const done = $Qc((success, finishEditing) => {
      nameElement.style.display = "";
      valueElement.style.display = "";
      inputBoxContainer.style.display = "none";
      const value = inputBox.value;
      $Xc(toDispose);
      if (finishEditing) {
        this.a.getViewModel().setSelectedExpression(void 0, false);
        options3.onFinish(value, success);
      }
    });
    const toDispose = [
      inputBox,
      $aj(inputBox.inputElement, $7j.KEY_DOWN, (e) => {
        const isEscape = e.equals(
          9
          /* KeyCode.Escape */
        );
        const isEnter = e.equals(
          3
          /* KeyCode.Enter */
        );
        if (isEscape || isEnter) {
          e.preventDefault();
          e.stopPropagation();
          done(isEnter, true);
        }
      }),
      $_i(inputBox.inputElement, $7j.BLUR, () => {
        done(true, true);
      }),
      $_i(inputBox.inputElement, $7j.CLICK, (e) => {
        e.preventDefault();
        e.stopPropagation();
      })
    ];
    return $1c(() => {
      done(false, false);
    });
  }
  disposeElement(node, index, templateData) {
    templateData.elementDisposable.clear();
  }
  disposeTemplate(templateData) {
    templateData.elementDisposable.dispose();
    templateData.templateDisposable.dispose();
  }
};
$s4b = __decorate([
  __param(0, $0R),
  __param(1, $40),
  __param(2, $5$)
], $s4b);

// out-build/vs/workbench/contrib/debug/browser/replViewer.js
var $g9b_1;
var $i9b_1;
var $j9b_1;
var $136 = $;
var $f9b = class _$f9b {
  static {
    this.ID = "replEvaluationInput";
  }
  get templateId() {
    return _$f9b.ID;
  }
  renderTemplate(container2) {
    $bk(container2, $136("span.arrow" + ThemeIcon.asCSSSelector($bGb)));
    const input = $bk(container2, $136(".expression"));
    const label3 = new $S2(input);
    return { label: label3 };
  }
  renderElement(element, index, templateData) {
    const evaluation = element.element;
    templateData.label.set(evaluation.value, $Ul(element.filterData));
  }
  disposeTemplate(templateData) {
    templateData.label.dispose();
  }
};
var $g9b = class $g9b2 {
  static {
    $g9b_1 = this;
  }
  static {
    this.ID = "replGroup";
  }
  constructor(a, b) {
    this.a = a;
    this.b = b;
  }
  get templateId() {
    return $g9b_1.ID;
  }
  renderTemplate(container2) {
    container2.classList.add("group");
    const expression = $bk(container2, $136(".output.expression.value-and-source"));
    const label3 = $bk(expression, $136("span.label"));
    const source = this.b.createInstance(SourceWidget, expression);
    return { label: label3, source };
  }
  renderElement(element, _index, templateData) {
    templateData.elementDisposable?.dispose();
    const replGroup = element.element;
    $$i(templateData.label);
    templateData.elementDisposable = this.a.renderValue(templateData.label, replGroup.name, { wasANSI: true, session: element.element.session });
    templateData.source.setSource(replGroup.sourceData);
  }
  disposeTemplate(templateData) {
    templateData.elementDisposable?.dispose();
    templateData.source.dispose();
  }
};
$g9b = $g9b_1 = __decorate([
  __param(1, $Pk)
], $g9b);
var $h9b = class _$h9b {
  static {
    this.ID = "replEvaluationResult";
  }
  get templateId() {
    return _$h9b.ID;
  }
  constructor(a) {
    this.a = a;
  }
  renderTemplate(container2) {
    const output = $bk(container2, $136(".evaluation-result.expression"));
    const value = $bk(output, $136("span.value"));
    return { value, elementStore: new $2c() };
  }
  renderElement(element, index, templateData) {
    templateData.elementStore.clear();
    const expression = element.element;
    templateData.elementStore.add(this.a.renderValue(templateData.value, expression, {
      colorize: true,
      hover: false,
      session: element.element.getSession()
    }));
  }
  disposeTemplate(templateData) {
    templateData.elementStore.dispose();
  }
};
var $i9b = class $i9b2 {
  static {
    $i9b_1 = this;
  }
  static {
    this.ID = "outputReplElement";
  }
  constructor(a, b) {
    this.a = a;
    this.b = b;
  }
  get templateId() {
    return $i9b_1.ID;
  }
  renderTemplate(container2) {
    const data = /* @__PURE__ */ Object.create(null);
    container2.classList.add("output");
    const expression = $bk(container2, $136(".output.expression.value-and-source"));
    data.container = container2;
    data.countContainer = $bk(expression, $136(".count-badge-wrapper"));
    data.count = new $D2(data.countContainer, {}, $E$);
    data.value = $bk(expression, $136("span.value.label"));
    data.source = this.b.createInstance(SourceWidget, expression);
    data.elementDisposable = new $2c();
    return data;
  }
  renderElement({ element }, index, templateData) {
    templateData.elementDisposable.clear();
    this.c(element, templateData);
    templateData.elementDisposable.add(element.onDidChangeCount(() => this.c(element, templateData)));
    $$i(templateData.value);
    templateData.value.className = "value";
    const locationReference = element.expression?.valueLocationReference;
    templateData.elementDisposable.add(this.a.renderValue(templateData.value, element.value, {
      wasANSI: true,
      session: element.session,
      locationReference,
      hover: false
    }));
    templateData.value.classList.add(element.severity === severity_default.Warning ? "warn" : element.severity === severity_default.Error ? "error" : element.severity === severity_default.Ignore ? "ignore" : "info");
    templateData.source.setSource(element.sourceData);
    templateData.getReplElementSource = () => element.sourceData;
  }
  c(element, templateData) {
    if (element.count >= 2) {
      templateData.count.setCount(element.count);
      templateData.countContainer.hidden = false;
    } else {
      templateData.countContainer.hidden = true;
    }
  }
  disposeTemplate(templateData) {
    templateData.source.dispose();
    templateData.elementDisposable.dispose();
    templateData.count.dispose();
  }
  disposeElement(_element, _index, templateData) {
    templateData.elementDisposable.clear();
  }
};
$i9b = $i9b_1 = __decorate([
  __param(1, $Pk)
], $i9b);
var $j9b = class $j9b2 extends $s4b {
  static {
    $j9b_1 = this;
  }
  static {
    this.ID = "replVariable";
  }
  get templateId() {
    return $j9b_1.ID;
  }
  constructor(i2, debugService, contextViewService, hoverService) {
    super(debugService, contextViewService, hoverService);
    this.i = i2;
  }
  renderElement(node, _index, data) {
    const element = node.element;
    data.elementDisposable.clear();
    super.d(element instanceof $j4b ? element.expression : element, node, data);
  }
  f(expression, data, highlights) {
    const isReplVariable = expression instanceof $j4b;
    if (isReplVariable || !expression.name) {
      data.label.set("");
      const value = isReplVariable ? expression.expression : expression;
      data.elementDisposable.add(this.i.renderValue(data.value, value, { colorize: true, hover: false, session: expression.getSession() }));
      data.expression.classList.remove("nested-variable");
    } else {
      data.elementDisposable.add(this.i.renderVariable(data, expression, { showChanged: true, highlights }));
      data.expression.classList.toggle("nested-variable", isNestedVariable(expression));
    }
  }
  g(expression) {
    return void 0;
  }
};
$j9b = $j9b_1 = __decorate([
  __param(1, $0R),
  __param(2, $40),
  __param(3, $5$)
], $j9b);
var $k9b = class _$k9b {
  static {
    this.ID = "rawObject";
  }
  constructor(a) {
    this.a = a;
  }
  get templateId() {
    return _$k9b.ID;
  }
  renderTemplate(container2) {
    container2.classList.add("output");
    const expression = $bk(container2, $136(".output.expression"));
    const name = $bk(expression, $136("span.name"));
    const label3 = new $S2(name);
    const value = $bk(expression, $136("span.value"));
    return { container: container2, expression, name, label: label3, value, elementStore: new $2c() };
  }
  renderElement(node, index, templateData) {
    templateData.elementStore.clear();
    const element = node.element;
    templateData.label.set(element.name ? `${element.name}:` : "", $Ul(node.filterData));
    if (element.name) {
      templateData.name.textContent = `${element.name}:`;
    } else {
      templateData.name.textContent = "";
    }
    templateData.elementStore.add(this.a.renderValue(templateData.value, element.value, {
      hover: false,
      session: node.element.getSession()
    }));
  }
  disposeTemplate(templateData) {
    templateData.elementStore.dispose();
    templateData.label.dispose();
  }
};
function isNestedVariable(element) {
  return element instanceof $MP && (element.parent instanceof $m4b || element.parent instanceof $MP);
}
var $l9b = class extends $m1 {
  constructor(a, b) {
    super();
    this.a = a;
    this.b = b;
  }
  getHeight(element) {
    const config = this.a.getValue("debug");
    if (!config.console.wordWrap) {
      return this.d(element, true);
    }
    return super.getHeight(element);
  }
  /**
   * With wordWrap enabled, this is an estimate. With wordWrap disabled, this is the real height that the list will use.
   */
  d(element, ignoreValueLength = false) {
    const lineHeight = this.b.replConfiguration.lineHeight;
    const countNumberOfLines = (str) => str.match(/\n/g)?.length ?? 0;
    const hasValue = (e) => typeof e.value === "string";
    if (hasValue(element) && !isNestedVariable(element)) {
      const value = element.value;
      const valueRows = countNumberOfLines(value) + (ignoreValueLength ? 0 : Math.floor(value.length / 70)) + (element instanceof $i4b ? 0 : 1);
      return Math.max(valueRows, 1) * lineHeight;
    }
    return lineHeight;
  }
  getTemplateId(element) {
    if (element instanceof $MP || element instanceof $j4b) {
      return $j9b.ID;
    }
    if (element instanceof $m4b) {
      return $h9b.ID;
    }
    if (element instanceof $l4b) {
      return $f9b.ID;
    }
    if (element instanceof $i4b) {
      return $i9b.ID;
    }
    if (element instanceof $n4b) {
      return $g9b.ID;
    }
    return $k9b.ID;
  }
  hasDynamicHeight(element) {
    if (isNestedVariable(element)) {
      return false;
    }
    return element.toString().length > 0;
  }
};
function isDebugSession(obj) {
  return typeof obj.getReplElements === "function";
}
var $m9b = class {
  hasChildren(element) {
    if (isDebugSession(element)) {
      return true;
    }
    return !!element.hasChildren;
  }
  getChildren(element) {
    if (isDebugSession(element)) {
      return Promise.resolve(element.getReplElements());
    }
    return Promise.resolve(element.getChildren());
  }
};
var $n9b = class {
  getWidgetAriaLabel() {
    return localize(6053, null);
  }
  getAriaLabel(element) {
    if (element instanceof $MP) {
      return localize(6054, null, element.name, element.value);
    }
    if (element instanceof $i4b || element instanceof $l4b || element instanceof $m4b) {
      return element.value + (element instanceof $i4b && element.count > 1 ? localize(6055, null, element.count) : "");
    }
    if (element instanceof $k4b) {
      return localize(6056, null, element.name, element.value);
    }
    if (element instanceof $n4b) {
      return localize(6057, null, element.name);
    }
    return "";
  }
};
var SourceWidget = class SourceWidget2 extends $3c {
  constructor(container2, editorService, f, g) {
    super();
    this.f = f;
    this.g = g;
    this.a = $bk(container2, $136(".source"));
    this.B($_i(this.a, "click", (e) => {
      e.preventDefault();
      e.stopPropagation();
      if (this.b) {
        this.b.source.openInEditor(editorService, {
          startLineNumber: this.b.lineNumber,
          startColumn: this.b.column,
          endLineNumber: this.b.lineNumber,
          endColumn: this.b.column
        });
      }
    }));
  }
  setSource(source) {
    this.b = source;
    this.a.textContent = source ? `${$rc(source.source.name)}:${source.lineNumber}` : "";
    this.c ??= this.B(this.f.setupManagedHover($JZ("mouse"), this.a, ""));
    this.c.update(source ? `${this.g.getUriLabel(source.source.uri)}:${source.lineNumber}` : "");
  }
};
SourceWidget = __decorate([
  __param(1, $mJ),
  __param(2, $5$),
  __param(3, $ZI)
], SourceWidget);

// out-build/vs/workbench/contrib/debug/browser/repl.js
var Repl_1;
var ReplOptions_1;
var $137 = $;
var HISTORY_STORAGE_KEY = "debug.repl.history";
var FILTER_HISTORY_STORAGE_KEY = "debug.repl.filterHistory";
var FILTER_VALUE_STORAGE_KEY = "debug.repl.filterValue";
var DECORATION_KEY3 = "replinputdecoration";
function revealLastElement(tree) {
  tree.scrollTop = tree.scrollHeight - tree.renderHeight;
}
var sessionsToIgnore = /* @__PURE__ */ new Set();
var identityProvider2 = { getId: (element) => element.getId() };
var Repl = class Repl2 extends $apb {
  static {
    Repl_1 = this;
  }
  static {
    this.a = 50;
  }
  static {
    this.b = URI.parse(`${$5R}:replinput`);
  }
  constructor(options3, tc, instantiationService, uc, themeService, vc, contextKeyService, codeEditorService, viewDescriptorService, contextMenuService, Ab, xc, yc, yb, openerService, telemetryService, hoverService, menuService, Ac, Bc) {
    const filterText = uc.get(FILTER_VALUE_STORAGE_KEY, 1, "");
    super({
      ...options3,
      filterOptions: {
        placeholder: localize(6028, null),
        text: filterText,
        history: JSON.parse(uc.get(FILTER_HISTORY_STORAGE_KEY, 1, "[]"))
      }
    }, yb, contextMenuService, Ab, contextKeyService, viewDescriptorService, instantiationService, openerService, themeService, telemetryService, hoverService);
    this.tc = tc;
    this.uc = uc;
    this.vc = vc;
    this.Ab = Ab;
    this.xc = xc;
    this.yc = yc;
    this.yb = yb;
    this.Ac = Ac;
    this.Bc = Bc;
    this.ab = 0;
    this.fc = 1;
    this.lc = false;
    this.nc = $3c.None;
    this.sc = false;
    this.qc = menuService.createMenu($bJ.DebugConsoleContext, contextKeyService);
    this.B(this.qc);
    this.f = new $F2(new Set(JSON.parse(this.uc.get(HISTORY_STORAGE_KEY, 1, "[]"))), 100);
    this.oc = new $e9b();
    this.oc.filterQuery = filterText;
    this.pc = $VR.bindTo(contextKeyService);
    this.r = this.B(this.Db.createInstance(ReplOptions, this.id, () => this.Xb().background));
    this.B(this.r.onDidChange(() => this.Fc()));
    codeEditorService.registerDecorationType("repl-decoration", DECORATION_KEY3, {});
    this.pc.set(this.Ic);
    this.Cc();
  }
  Cc() {
    if (this.tc.getViewModel().focusedSession) {
      this.Dc(this.tc.getViewModel().focusedSession);
    }
    this.B(this.tc.getViewModel().onDidFocusSession(async (session) => this.Dc(session)));
    this.B(this.tc.getViewModel().onDidEvaluateLazyExpression(async (e) => {
      if (e instanceof $MP && this.m?.hasNode(e)) {
        await this.m.updateChildren(e, false, true);
        await this.m.expand(e);
      }
    }));
    this.B(this.tc.onWillNewSession(async (newSession) => {
      const input = this.m?.getInput();
      if (!input || input.state === 0) {
        await this.selectSession(newSession);
      }
      this.pc.set(this.Ic);
    }));
    this.B(this.tc.onDidEndSession(async () => {
      await Promise.resolve();
      this.pc.set(this.Ic);
    }));
    this.B(this.Fb.onDidColorThemeChange(() => {
      this.Pc(false);
      if (this.isVisible()) {
        this.Qc();
      }
    }));
    this.B(this.onDidChangeBodyVisibility((visible) => {
      if (visible) {
        if (!this.gc) {
          this.gc = this.vc.getModel(Repl_1.b) || this.vc.createModel("", null, Repl_1.b, true);
        }
        this.Ec();
        this.cc.setModel(this.gc);
        this.Qc();
        this.Pc(true);
        if (this.lc) {
          this.lc = false;
          this.m?.updateChildren(void 0, true, false);
          this.Fc();
        }
      }
    }));
    this.B(this.Ab.onDidChangeConfiguration((e) => {
      if (e.affectsConfiguration("debug.console.wordWrap") && this.m) {
        this.m.dispose();
        this.bc.innerText = "";
        $$i(this.bc);
        this.Lc();
      }
      if (e.affectsConfiguration("debug.console.acceptSuggestionOnEnter")) {
        const config = this.Ab.getValue("debug");
        this.cc.updateOptions({
          acceptSuggestionOnEnter: config.console.acceptSuggestionOnEnter === "on" ? "on" : "off"
        });
      }
    }));
    this.B(this.yc.onDidActiveEditorChange(() => {
      this.Ec();
    }));
    this.B(this.filterWidget.onDidChangeFilterText(() => {
      this.oc.filterQuery = this.filterWidget.getFilterText();
      if (this.m) {
        this.m.refilter();
        revealLastElement(this.m);
      }
    }));
  }
  async Dc(session) {
    if (session) {
      sessionsToIgnore.delete(session);
      this.mc?.dispose();
      if (session.capabilities.supportsCompletionsRequest) {
        this.mc = this.Ac.completionProvider.register({ scheme: $5R, pattern: "**/replinput", hasAccessToAllModels: true }, {
          _debugDisplayName: "debugConsole",
          triggerCharacters: session.capabilities.completionTriggerCharacters || ["."],
          provideCompletionItems: async (_, position, _context, token) => {
            this.hc(false);
            const model = this.cc.getModel();
            if (model) {
              const word = model.getWordAtPosition(position);
              const overwriteBefore = word ? word.word.length : 0;
              const text2 = model.getValue();
              const focusedStackFrame = this.tc.getViewModel().focusedStackFrame;
              const frameId = focusedStackFrame ? focusedStackFrame.frameId : void 0;
              const response = await session.completions(frameId, focusedStackFrame?.thread.threadId || 0, text2, position, overwriteBefore, token);
              const suggestions = [];
              const computeRange = (length) => $9C.fromPositions(position.delta(0, -length), position);
              if (response && response.body && response.body.targets) {
                response.body.targets.forEach((item) => {
                  if (item && item.label) {
                    let insertTextRules = void 0;
                    let insertText = item.text || item.label;
                    if (typeof item.selectionStart === "number") {
                      insertTextRules = 4;
                      const selectionLength = typeof item.selectionLength === "number" ? item.selectionLength : 0;
                      const placeholder = selectionLength > 0 ? "${1:" + insertText.substring(item.selectionStart, item.selectionStart + selectionLength) + "}$0" : "$0";
                      insertText = insertText.substring(0, item.selectionStart) + placeholder + insertText.substring(item.selectionStart + selectionLength);
                    }
                    suggestions.push({
                      label: item.label,
                      insertText,
                      detail: item.detail,
                      kind: CompletionItemKinds.fromString(item.type || "property"),
                      filterText: item.start && item.length ? text2.substring(item.start, item.start + item.length).concat(item.label) : void 0,
                      range: computeRange(item.length || overwriteBefore),
                      sortText: item.sortText,
                      insertTextRules
                    });
                  }
                });
              }
              if (this.Ab.getValue("debug").console.historySuggestions) {
                const history = this.f.getHistory();
                const idxLength = String(history.length).length;
                history.forEach((h3, i2) => suggestions.push({
                  label: h3,
                  insertText: h3,
                  kind: 18,
                  range: computeRange(h3.length),
                  sortText: "ZZZ" + String(history.length - i2).padStart(idxLength, "0")
                }));
              }
              return { suggestions };
            }
            return Promise.resolve({ suggestions: [] });
          }
        });
      }
    }
    await this.selectSession();
  }
  getFilterStats() {
    return {
      total: this.m?.getNode().children.length ?? 0,
      filtered: this.m?.getNode().children.filter((c) => c.visible).length ?? 0
    };
  }
  get isReadonly() {
    const session = this.m?.getInput();
    if (session && session.state !== 0) {
      return false;
    }
    return true;
  }
  showPreviousValue() {
    if (!this.isReadonly) {
      this.Gc(true);
    }
  }
  showNextValue() {
    if (!this.isReadonly) {
      this.Gc(false);
    }
  }
  focusFilter() {
    this.filterWidget.focus();
  }
  openFind() {
    this.m?.openFind();
  }
  Ec() {
    if (!this.isVisible()) {
      return;
    }
    const activeEditorControl = this.yc.activeTextEditorControl;
    if ($P5(activeEditorControl)) {
      this.nc.dispose();
      this.nc = activeEditorControl.onDidChangeModelLanguage(() => this.Ec());
      if (this.gc && activeEditorControl.hasModel()) {
        this.gc.setLanguage(activeEditorControl.getModel().getLanguageId());
      }
    }
  }
  Fc() {
    if (!this.isVisible()) {
      this.lc = true;
      return;
    }
    if (this.kc) {
      this.cc.updateOptions({
        fontSize: this.r.replConfiguration.fontSize,
        lineHeight: this.r.replConfiguration.lineHeight,
        fontFamily: this.r.replConfiguration.fontFamily === "default" ? EDITOR_FONT_DEFAULTS.fontFamily : this.r.replConfiguration.fontFamily
      });
      const replInputLineHeight = this.cc.getOption(
        68
        /* EditorOption.lineHeight */
      );
      this.kc.textContent = `
				.repl .repl-input-wrapper .repl-input-chevron {
					line-height: ${replInputLineHeight}px
				}

				.repl .repl-input-wrapper .monaco-editor .lines-content {
					background-color: ${this.r.replConfiguration.backgroundColor};
				}
			`;
      const cssFontFamily = this.r.replConfiguration.fontFamily === "default" ? "var(--monaco-monospace-font)" : this.r.replConfiguration.fontFamily;
      this.ac.style.setProperty(`--vscode-repl-font-family`, cssFontFamily);
      this.ac.style.setProperty(`--vscode-repl-font-size`, `${this.r.replConfiguration.fontSize}px`);
      this.ac.style.setProperty(`--vscode-repl-font-size-for-twistie`, `${this.r.replConfiguration.fontSizeForTwistie}px`);
      this.ac.style.setProperty(`--vscode-repl-line-height`, this.r.replConfiguration.cssLineHeight);
      this.m?.rerender();
      if (this.ec) {
        this.L(this.ec.height, this.ec.width);
      }
    }
  }
  Gc(previous) {
    const historyInput = (previous ? this.f.previous() ?? this.f.first() : this.f.next()) ?? "";
    this.cc.setValue(historyInput);
    $_Z(historyInput);
    this.cc.setPosition({ lineNumber: 1, column: historyInput.length + 1 });
    this.hc(true);
  }
  async selectSession(session) {
    const treeInput = this.m?.getInput();
    if (!session) {
      const focusedSession = this.tc.getViewModel().focusedSession;
      if (focusedSession) {
        session = focusedSession;
      } else if (!treeInput || sessionsToIgnore.has(treeInput)) {
        session = this.tc.getModel().getSessions(true).find((s) => !sessionsToIgnore.has(s));
      }
    }
    if (session) {
      this.jc?.dispose();
      this.jc = session.onDidChangeReplElements(() => {
        this.Pc(session.getReplElements().length === 0);
      });
      if (this.m && treeInput !== session) {
        try {
          await this.m.setInput(session);
        } catch (err) {
          this.Bc.error(err);
        }
        revealLastElement(this.m);
      }
    }
    this.cc?.updateOptions({ readOnly: this.isReadonly });
    this.Qc();
  }
  async clearRepl() {
    const session = this.m?.getInput();
    if (session) {
      session.removeReplExpressions();
      if (session.state === 0) {
        sessionsToIgnore.add(session);
        await this.selectSession();
        this.pc.set(this.Ic);
      }
    }
    this.cc.focus();
  }
  acceptReplInput() {
    const session = this.m?.getInput();
    if (session && !this.isReadonly) {
      session.addReplExpression(this.tc.getViewModel().focusedStackFrame, this.cc.getValue());
      revealLastElement(this.m);
      this.f.add(this.cc.getValue());
      this.cc.setValue("");
      const shouldRelayout = this.fc > 1;
      this.fc = 1;
      if (shouldRelayout && this.ec) {
        this.L(this.ec.height, this.ec.width);
      }
    }
  }
  sendReplInput(input) {
    const session = this.m?.getInput();
    if (session && !this.isReadonly) {
      session.addReplExpression(this.tc.getViewModel().focusedStackFrame, input);
      revealLastElement(this.m);
      this.f.add(input);
    }
  }
  getVisibleContent() {
    let text2 = "";
    if (this.gc && this.m) {
      const lineDelimiter2 = this.xc.getEOL(this.gc.uri);
      const traverseAndAppend = (node) => {
        node.children.forEach((child) => {
          if (child.visible) {
            text2 += child.element.toString().trimRight() + lineDelimiter2;
            if (!child.collapsed && child.children.length) {
              traverseAndAppend(child);
            }
          }
        });
      };
      traverseAndAppend(this.m.getNode());
    }
    return $kg(text2);
  }
  L(height, width2) {
    this.ec = new $rj(width2, height);
    const replInputHeight = Math.min(this.cc.getContentHeight(), height);
    if (this.m) {
      const lastElementVisible = this.m.scrollTop + this.m.renderHeight >= this.m.scrollHeight;
      const treeHeight = height - replInputHeight;
      this.m.getHTMLElement().style.height = `${treeHeight}px`;
      this.m.layout(treeHeight, width2);
      if (lastElementVisible) {
        revealLastElement(this.m);
      }
    }
    this.dc.style.height = `${replInputHeight}px`;
    this.cc.layout({ width: width2 - 30, height: replInputHeight });
  }
  collapseAll() {
    this.m?.collapseAll();
  }
  getDebugSession() {
    return this.m?.getInput();
  }
  getReplInput() {
    return this.cc;
  }
  getReplDataSource() {
    return this.rc;
  }
  getFocusedElement() {
    return this.m?.getFocus()?.[0];
  }
  focusTree() {
    this.m?.domFocus();
  }
  focus() {
    super.focus();
    setTimeout(() => this.cc.focus(), 0);
  }
  getActionViewItem(action) {
    if (action.id === selectReplCommandId) {
      const session = (this.m ? this.m.getInput() : void 0) ?? this.tc.getViewModel().focusedSession;
      return this.Db.createInstance(SelectReplActionViewItem, action, session);
    }
    return super.getActionViewItem(action);
  }
  get Ic() {
    return this.tc.getModel().getSessions(true).filter((s) => s.hasSeparateRepl() && !sessionsToIgnore.has(s)).length > 1;
  }
  // --- Cached locals
  get Jc() {
    const autoExpanded = /* @__PURE__ */ new Set();
    return new $8h(async () => {
      if (!this.m || !this.m.getInput() || !this.isVisible()) {
        return;
      }
      await this.m.updateChildren(void 0, true, false, { diffIdentityProvider: identityProvider2 });
      const session = this.m.getInput();
      if (session) {
        const autoExpandElements = async (elements) => {
          for (const element of elements) {
            if (element instanceof $n4b) {
              if (element.autoExpand && !autoExpanded.has(element.getId())) {
                autoExpanded.add(element.getId());
                await this.m.expand(element);
              }
              if (!this.m.isCollapsed(element)) {
                await autoExpandElements(element.getChildren());
              }
            }
          }
        };
        await autoExpandElements(session.getReplElements());
      }
      const { total, filtered } = this.getFilterStats();
      this.filterWidget.updateBadge(total === filtered || total === 0 ? void 0 : localize(6029, null, filtered, total));
    }, Repl_1.a);
  }
  // --- Creation
  render() {
    super.render();
    this.B($iKb({
      name: "repl",
      focusNotifiers: [this, this.filterWidget],
      focusNextWidget: () => {
        const element = this.m?.getHTMLElement();
        if (this.filterWidget.hasFocus()) {
          this.m?.domFocus();
        } else if (element && $Mj(element)) {
          this.focus();
        }
      },
      focusPreviousWidget: () => {
        const element = this.m?.getHTMLElement();
        if (this.cc.hasTextFocus()) {
          this.m?.domFocus();
        } else if (element && $Mj(element)) {
          this.focusFilter();
        }
      }
    }));
  }
  W(parent) {
    super.W(parent);
    this.ac = $bk(parent, $137(".repl"));
    this.bc = $bk(this.ac, $137(`.repl-tree.${$62}`));
    this.Mc(this.ac);
    this.Lc();
  }
  Lc() {
    this.sb = new $l9b(this.Ab, this.r);
    const wordWrap = this.Ab.getValue("debug").console.wordWrap;
    this.bc.classList.toggle("word-wrap", wordWrap);
    const expressionRenderer = this.Db.createInstance($D5b);
    this.rc = new $m9b();
    const tree = this.m = this.Db.createInstance($4eb, "DebugRepl", this.bc, this.sb, [
      this.Db.createInstance($j9b, expressionRenderer),
      this.Db.createInstance($i9b, expressionRenderer),
      new $f9b(),
      this.Db.createInstance($g9b, expressionRenderer),
      new $h9b(expressionRenderer),
      new $k9b(expressionRenderer)
    ], this.rc, {
      filter: this.oc,
      accessibilityProvider: new $n9b(),
      identityProvider: identityProvider2,
      mouseSupport: false,
      findWidgetEnabled: true,
      keyboardNavigationLabelProvider: { getKeyboardNavigationLabel: (e) => e.toString(true) },
      horizontalScrolling: !wordWrap,
      setRowLineHeight: false,
      supportDynamicHeights: wordWrap,
      overrideStyles: this.Xb().listOverrideStyles
    });
    this.B(tree.onDidChangeContentHeight(() => {
      if (tree.scrollHeight !== this.ab) {
        const lastElementWasVisible = tree.scrollTop + tree.renderHeight >= this.ab - 2;
        if (lastElementWasVisible) {
          setTimeout(() => {
            revealLastElement(tree);
          }, 0);
        }
      }
      this.ab = tree.scrollHeight;
    }));
    this.B(tree.onContextMenu((e) => this.Oc(e)));
    this.B(tree.onDidChangeFindOpenState((open2) => this.sc = open2));
    let lastSelectedString;
    this.B(tree.onMouseClick(() => {
      if (this.sc) {
        return;
      }
      const selection = getWindow(this.bc).getSelection();
      if (!selection || selection.type !== "Range" || lastSelectedString === selection.toString()) {
        this.cc.focus();
      }
      lastSelectedString = selection ? selection.toString() : "";
    }));
    this.selectSession();
    this.kc = $VZ(this.ac);
    this.Fc();
  }
  Mc(container2) {
    this.dc = $bk(container2, $137(".repl-input-wrapper"));
    $bk(this.dc, $137(".repl-input-chevron" + ThemeIcon.asCSSSelector($cGb)));
    const { historyNavigationBackwardsEnablement, historyNavigationForwardsEnablement } = this.B($8bb(this.xb, this));
    this.hc = (enabled) => {
      historyNavigationBackwardsEnablement.set(enabled);
      historyNavigationForwardsEnablement.set(enabled);
    };
    $0Q.bindTo(this.xb).set(true);
    this.ic = this.B(this.Db.createChild(new $Ok([$on, this.xb])));
    const options3 = $Zsb(this.Ab);
    options3.readOnly = true;
    options3.suggest = { showStatusBar: true };
    const config = this.Ab.getValue("debug");
    options3.acceptSuggestionOnEnter = config.console.acceptSuggestionOnEnter === "on" ? "on" : "off";
    options3.ariaLabel = this.Nc();
    this.cc = this.ic.createInstance($D9, this.dc, options3, $1sb());
    this.B(this.cc.onDidChangeModelContent(() => {
      const model = this.cc.getModel();
      this.hc(!!model && model.getValue() === "");
      const lineCount = model ? Math.min(10, model.getLineCount()) : 1;
      if (lineCount !== this.fc) {
        this.fc = lineCount;
        if (this.ec) {
          this.L(this.ec.height, this.ec.width);
        }
      }
    }));
    this.B(this.cc.onDidFocusEditorText(() => this.Qc()));
    this.B(this.cc.onDidBlurEditorText(() => this.Qc()));
    this.B($aj(this.dc, $7j.FOCUS, () => this.dc.classList.add("synthetic-focus")));
    this.B($aj(this.dc, $7j.BLUR, () => this.dc.classList.remove("synthetic-focus")));
  }
  Nc() {
    let ariaLabel = localize(6030, null);
    if (!this.Ab.getValue(
      "accessibility.verbosity.debug"
      /* AccessibilityVerbositySettingId.Debug */
    )) {
      return ariaLabel;
    }
    const keybinding = this.yb.lookupKeybinding(
      "editor.action.accessibilityHelp"
      /* AccessibilityCommandId.OpenAccessibilityHelp */
    )?.getAriaLabel();
    if (keybinding) {
      ariaLabel = localize(6031, null, ariaLabel, keybinding);
    } else {
      ariaLabel = localize(6032, null, ariaLabel);
    }
    return ariaLabel;
  }
  Oc(e) {
    const actions = $P$(this.qc.getActions({ arg: e.element, shouldForwardArgs: false }));
    this.zb.showContextMenu({
      getAnchor: () => e.anchor,
      getActions: () => actions,
      getActionsContext: () => e.element
    });
  }
  // --- Update
  Pc(noDelay) {
    if (this.m && this.isVisible()) {
      if (this.Jc.isScheduled()) {
        return;
      }
      this.Jc.schedule(noDelay ? 0 : void 0);
    }
  }
  Qc() {
    if (!this.cc) {
      return;
    }
    const decorations = [];
    if (this.isReadonly && this.cc.hasTextFocus() && !this.cc.getValue()) {
      const transparentForeground = $co($Lo, this.Fb.getColorTheme())?.transparent(0.4);
      decorations.push({
        range: {
          startLineNumber: 0,
          endLineNumber: 0,
          startColumn: 0,
          endColumn: 1
        },
        renderOptions: {
          after: {
            contentText: localize(6033, null),
            color: transparentForeground ? transparentForeground.toString() : void 0
          }
        }
      });
    }
    this.cc.setDecorationsByType("repl-decoration", DECORATION_KEY3, decorations);
  }
  saveState() {
    const replHistory = this.f.getHistory();
    if (replHistory.length) {
      this.uc.store(
        HISTORY_STORAGE_KEY,
        JSON.stringify(replHistory),
        1,
        1
        /* StorageTarget.MACHINE */
      );
    } else {
      this.uc.remove(
        HISTORY_STORAGE_KEY,
        1
        /* StorageScope.WORKSPACE */
      );
    }
    const filterHistory = this.filterWidget.getHistory();
    if (filterHistory.length) {
      this.uc.store(
        FILTER_HISTORY_STORAGE_KEY,
        JSON.stringify(filterHistory),
        1,
        1
        /* StorageTarget.MACHINE */
      );
    } else {
      this.uc.remove(
        FILTER_HISTORY_STORAGE_KEY,
        1
        /* StorageScope.WORKSPACE */
      );
    }
    const filterValue = this.filterWidget.getFilterText();
    if (filterValue) {
      this.uc.store(
        FILTER_VALUE_STORAGE_KEY,
        filterValue,
        1,
        1
        /* StorageTarget.MACHINE */
      );
    } else {
      this.uc.remove(
        FILTER_VALUE_STORAGE_KEY,
        1
        /* StorageScope.WORKSPACE */
      );
    }
    super.saveState();
  }
  dispose() {
    this.cc?.dispose();
    this.jc?.dispose();
    this.Jc.dispose();
    this.nc.dispose();
    super.dispose();
  }
};
__decorate([
  $0t
], Repl.prototype, "Jc", null);
Repl = Repl_1 = __decorate([
  __param(1, $0R),
  __param(2, $Pk),
  __param(3, $jv),
  __param(4, $gs),
  __param(5, $sG),
  __param(6, $on),
  __param(7, $U5),
  __param(8, $$M),
  __param(9, $50),
  __param(10, $kl),
  __param(11, $AG),
  __param(12, $mJ),
  __param(13, $Ty),
  __param(14, $O4),
  __param(15, $zv),
  __param(16, $5$),
  __param(17, $cJ),
  __param(18, $mP),
  __param(19, $wn)
], Repl);
var ReplOptions = class ReplOptions2 extends $3c {
  static {
    ReplOptions_1 = this;
  }
  static {
    this.a = 1.4;
  }
  get replConfiguration() {
    return this.f;
  }
  constructor(viewId, g, j, m, n) {
    super();
    this.g = g;
    this.j = j;
    this.m = m;
    this.n = n;
    this.b = this.B(new $ze());
    this.onDidChange = this.b.event;
    this.B(this.m.onDidColorThemeChange((e) => this.r()));
    this.B(this.n.onDidChangeLocation((e) => {
      if (e.views.some((v) => v.id === viewId)) {
        this.r();
      }
    }));
    this.B(this.j.onDidChangeConfiguration((e) => {
      if (e.affectsConfiguration("debug.console.lineHeight") || e.affectsConfiguration("debug.console.fontSize") || e.affectsConfiguration("debug.console.fontFamily")) {
        this.r();
      }
    }));
    this.r();
  }
  r() {
    const debugConsole = this.j.getValue("debug").console;
    this.f = {
      fontSize: debugConsole.fontSize,
      fontFamily: debugConsole.fontFamily,
      lineHeight: debugConsole.lineHeight ? debugConsole.lineHeight : ReplOptions_1.a * debugConsole.fontSize,
      cssLineHeight: debugConsole.lineHeight ? `${debugConsole.lineHeight}px` : `${ReplOptions_1.a}em`,
      backgroundColor: this.m.getColorTheme().getColor(this.g()),
      fontSizeForTwistie: debugConsole.fontSize * ReplOptions_1.a / 2 - 8
    };
    this.b.fire();
  }
};
ReplOptions = ReplOptions_1 = __decorate([
  __param(2, $kl),
  __param(3, $gs),
  __param(4, $$M)
], ReplOptions);
var AcceptReplInputAction = class extends $Z5 {
  constructor() {
    super({
      id: "repl.action.acceptInput",
      label: localize2(6042, "Debug Console: Accept Input"),
      precondition: $0Q,
      kbOpts: {
        kbExpr: EditorContextKeys.textInputFocus,
        primary: 3,
        weight: 100
        /* KeybindingWeight.EditorContrib */
      }
    });
  }
  run(accessor, editor) {
    $qdb.get(editor)?.cancelSuggestWidget();
    const repl = $p9b(accessor.get($uob));
    repl?.acceptReplInput();
  }
};
var FilterReplAction = class extends $cpb {
  constructor() {
    super({
      viewId: $2Q,
      id: "repl.action.filter",
      title: localize(6034, null),
      precondition: $0Q,
      keybinding: [{
        when: EditorContextKeys.textInputFocus,
        primary: 2048 | 36,
        weight: 100
        /* KeybindingWeight.EditorContrib */
      }]
    });
  }
  runInView(accessor, repl) {
    repl.focusFilter();
  }
};
var FindReplAction = class extends $cpb {
  constructor() {
    super({
      viewId: $2Q,
      id: "repl.action.find",
      title: localize(6035, null),
      precondition: $0Q,
      keybinding: [{
        when: $7m.or($0Q, $7m.equals("focusedView", "workbench.panel.repl.view")),
        primary: 2048 | 512 | 36,
        weight: 100
        /* KeybindingWeight.EditorContrib */
      }],
      icon: $6l.search,
      menu: [{
        id: $bJ.ViewTitle,
        group: "navigation",
        when: $7m.equals("view", $2Q),
        order: 15
      }, {
        id: $bJ.DebugConsoleContext,
        group: "z_commands",
        order: 25
      }]
    });
  }
  runInView(accessor, view) {
    view.openFind();
  }
};
var ReplCopyAllAction = class extends $Z5 {
  constructor() {
    super({
      id: "repl.action.copyAll",
      label: localize(6036, null),
      alias: "Debug Console Copy All",
      precondition: $0Q
    });
  }
  run(accessor, editor) {
    const clipboardService = accessor.get($30);
    const repl = $p9b(accessor.get($uob));
    if (repl) {
      return clipboardService.writeText(repl.getVisibleContent());
    }
  }
};
$55(AcceptReplInputAction);
$55(ReplCopyAllAction);
$hJ(FilterReplAction);
$hJ(FindReplAction);
var SelectReplActionViewItem = class extends $d9b {
  M() {
    return this.a.getModel().getSessions(true).filter((s) => s.hasSeparateRepl() && !sessionsToIgnore.has(s));
  }
  N(focusedSession) {
    while (focusedSession.parentSession && !focusedSession.hasSeparateRepl()) {
      focusedSession = focusedSession.parentSession;
    }
    return focusedSession;
  }
};
function $p9b(viewsService) {
  return viewsService.getActiveViewWithId($2Q) ?? void 0;
}
var selectReplCommandId = "workbench.action.debug.selectRepl";
$hJ(class extends $cpb {
  constructor() {
    super({
      id: selectReplCommandId,
      viewId: $2Q,
      title: localize(6037, null),
      f1: false,
      menu: {
        id: $bJ.ViewTitle,
        group: "navigation",
        when: $7m.and($7m.equals("view", $2Q), $VR),
        order: 20
      }
    });
  }
  async runInView(accessor, view, session) {
    const debugService = accessor.get($0R);
    if (session && session.state !== 0 && session !== debugService.getViewModel().focusedSession) {
      if (session.state !== 2) {
        const stopppedChildSession = debugService.getModel().getSessions().find(
          (s) => s.parentSession === session && s.state === 2
          /* State.Stopped */
        );
        if (stopppedChildSession) {
          session = stopppedChildSession;
        }
      }
      await debugService.focusStackFrame(void 0, void 0, session, { explicit: true });
    }
    await view.selectSession(session);
  }
});
$hJ(class extends $cpb {
  constructor() {
    super({
      id: "workbench.debug.panel.action.clearReplAction",
      viewId: $2Q,
      title: localize2(6043, "Clear Console"),
      metadata: {
        description: localize2(6044, "Clears all program output from your debug REPL")
      },
      f1: true,
      icon: $6Fb,
      menu: [{
        id: $bJ.ViewTitle,
        group: "navigation",
        when: $7m.equals("view", $2Q),
        order: 30
      }, {
        id: $bJ.DebugConsoleContext,
        group: "z_commands",
        order: 20
      }],
      keybinding: [{
        primary: 0,
        mac: {
          primary: 2048 | 41
          /* KeyCode.KeyK */
        },
        // Weight is higher than work workbench contributions so the keybinding remains
        // highest priority when chords are registered afterwards
        weight: 200 + 1,
        when: $7m.equals("focusedView", "workbench.panel.repl.view")
      }]
    });
  }
  runInView(_accessor, view) {
    const accessibilitySignalService = _accessor.get($I9);
    view.clearRepl();
    accessibilitySignalService.playSignal($N9.clear);
  }
});
$hJ(class extends $cpb {
  constructor() {
    super({
      id: "debug.collapseRepl",
      title: localize(6038, null),
      viewId: $2Q,
      menu: {
        id: $bJ.DebugConsoleContext,
        group: "z_commands",
        order: 10
      }
    });
  }
  runInView(_accessor, view) {
    view.collapseAll();
    view.focus();
  }
});
$hJ(class extends $cpb {
  constructor() {
    super({
      id: "debug.replPaste",
      title: localize(6039, null),
      viewId: $2Q,
      precondition: $5Q.notEqualsTo($7R(
        0
        /* State.Inactive */
      )),
      menu: {
        id: $bJ.DebugConsoleContext,
        group: "2_cutcopypaste",
        order: 30
      }
    });
  }
  async runInView(accessor, view) {
    const clipboardService = accessor.get($30);
    const clipboardText = await clipboardService.readText();
    if (clipboardText) {
      const replInput = view.getReplInput();
      replInput.setValue(replInput.getValue().concat(clipboardText));
      view.focus();
      const model = replInput.getModel();
      const lineNumber = model ? model.getLineCount() : 0;
      const column = model?.getLineMaxColumn(lineNumber);
      if (typeof lineNumber === "number" && typeof column === "number") {
        replInput.setPosition({ lineNumber, column });
      }
    }
  }
});
$hJ(class extends $cpb {
  constructor() {
    super({
      id: "workbench.debug.action.copyAll",
      title: localize(6040, null),
      viewId: $2Q,
      menu: {
        id: $bJ.DebugConsoleContext,
        group: "2_cutcopypaste",
        order: 20
      }
    });
  }
  async runInView(accessor, view) {
    const clipboardService = accessor.get($30);
    await clipboardService.writeText(view.getVisibleContent());
  }
});
$hJ(class extends $gJ {
  constructor() {
    super({
      id: "debug.replCopy",
      title: localize(6041, null),
      menu: {
        id: $bJ.DebugConsoleContext,
        group: "2_cutcopypaste",
        order: 10
      }
    });
  }
  async run(accessor, element) {
    const clipboardService = accessor.get($30);
    const debugService = accessor.get($0R);
    const nativeSelection = $Qj().getSelection();
    const selectedText = nativeSelection?.toString();
    if (selectedText && selectedText.length > 0) {
      return clipboardService.writeText(selectedText);
    } else if (element) {
      return clipboardService.writeText(await this.a(debugService, element) || element.toString());
    }
  }
  async a(debugService, element) {
    if (!(element instanceof $m4b)) {
      return;
    }
    const stackFrame = debugService.getViewModel().focusedStackFrame;
    const session = debugService.getViewModel().focusedSession;
    if (!stackFrame || !session || !session.capabilities.supportsClipboardContext) {
      return;
    }
    try {
      const evaluation = await session.evaluate(element.originalExpression, stackFrame.frameId, "clipboard");
      return evaluation?.body.result;
    } catch (e) {
      return;
    }
  }
});

// out-build/vs/workbench/contrib/notebook/browser/replEditorAccessibleView.js
var $q9b = class {
  constructor() {
    this.priority = 100;
    this.name = "replEditorInput";
    this.type = "view";
    this.when = $7m.and($VAb, $XAb.negate());
  }
  getProvider(accessor) {
    const editorService = accessor.get($mJ);
    return $r9b(editorService);
  }
};
function $r9b(editorService) {
  const editorControl = editorService.activeEditorPane?.getControl();
  if (editorControl && $$8b(editorControl) && editorControl.notebookEditor) {
    const notebookEditor = editorControl.notebookEditor;
    const viewModel = notebookEditor?.getViewModel();
    if (notebookEditor && viewModel) {
      const lastCellIndex = viewModel.length - 1;
      if (lastCellIndex >= 0) {
        const cell = viewModel.viewCells[lastCellIndex];
        const outputContent = $4Kb(viewModel.notebookDocument, cell);
        if (outputContent) {
          return new $thb(
            "notebook",
            {
              type: "view"
              /* AccessibleViewType.View */
            },
            () => {
              return outputContent;
            },
            () => {
              editorControl.activeCodeEditor?.focus();
            },
            "accessibility.verbosity.replEditor"
            /* AccessibilityVerbositySettingId.ReplEditor */
          );
        }
      }
    }
  }
  return;
}

// out-build/vs/workbench/contrib/replNotebook/browser/replEditorAccessibilityHelp.js
var $s9b = class {
  constructor() {
    this.priority = 105;
    this.name = "REPL Editor Input";
    this.when = $7m.and($VAb, $XAb.negate());
    this.type = "help";
  }
  getProvider(accessor) {
    return getAccessibilityHelpProvider2(accessor.get($U5), getAccessibilityInputHelpText());
  }
};
function getAccessibilityInputHelpText() {
  return [
    localize(9350, null),
    localize(9351, null, "<keybinding:repl.execute>"),
    localize(9352, null),
    localize(9353, null),
    localize(9354, null, "<keybinding:repl.focusLastItemExecuted>"),
    localize(9355, null, "<keybinding:editor.action.accessibleView>"),
    localize(9356, null, "<keybinding:repl.input.focus>")
  ].join("\n");
}
var $t9b = class {
  constructor() {
    this.priority = 105;
    this.name = "REPL Editor History";
    this.when = $7m.and($VAb, $XAb);
    this.type = "help";
  }
  getProvider(accessor) {
    return getAccessibilityHelpProvider2(accessor.get($U5), getAccessibilityHistoryHelpText());
  }
};
function getAccessibilityHistoryHelpText() {
  return [
    localize(9357, null),
    localize(9358, null, "<keybinding:notebook.cell.edit>"),
    localize(9359, null, "<keybinding:notebook.cell.quitEdit>"),
    localize(9360, null, "<keybinding:editor.action.accessibleView>"),
    localize(9361, null, "<keybinding:notebook.cell.focusInOutput>"),
    localize(9362, null, "<keybinding:repl.input.focus>"),
    localize(9363, null, "<keybinding:repl.focusLastItemExecuted>")
  ].join("\n");
}
function getAccessibilityHelpProvider2(editorService, helpText) {
  const activeEditor = editorService.getActiveCodeEditor() || editorService.getFocusedCodeEditor();
  if (!activeEditor) {
    return;
  }
  return new $thb(
    "replEditor",
    {
      type: "help"
      /* AccessibleViewType.Help */
    },
    () => helpText,
    () => activeEditor.focus(),
    "accessibility.verbosity.replEditor"
    /* AccessibilityVerbositySettingId.ReplEditor */
  );
}

// out-build/vs/workbench/contrib/replNotebook/browser/repl.contribution.js
var ReplEditorSerializer = class {
  canSerialize(input) {
    return input.typeId === $98b.ID;
  }
  serialize(input) {
    $Jg(input instanceof $98b);
    const data = {
      resource: input.resource,
      preferredResource: input.preferredResource,
      viewType: input.viewType,
      options: input.options,
      label: input.getName()
    };
    return JSON.stringify(data);
  }
  deserialize(instantiationService, raw) {
    const data = $bu(raw);
    if (!data) {
      return void 0;
    }
    const { resource, viewType } = data;
    if (!data || !URI.isUri(resource) || typeof viewType !== "string") {
      return void 0;
    }
    const input = instantiationService.createInstance($98b, resource, data.label);
    return input;
  }
};
$Wn.as($ZK.EditorPane).registerEditorPane($7tb.create($08b, $fM, "REPL Editor"), [
  new $Nk($98b)
]);
$Wn.as($ZK.EditorFactory).registerEditorSerializer($98b.ID, ReplEditorSerializer);
var $u9b = class $u9b2 extends $3c {
  static {
    this.ID = "workbench.contrib.replDocument";
  }
  constructor(notebookService, editorResolverService, b, c, f) {
    super();
    this.b = b;
    this.c = c;
    this.f = f;
    this.a = new $Ec();
    editorResolverService.registerEditor(
      // don't match anything, we don't need to support re-opening files as REPL editor at this point
      ` `,
      {
        id: "repl",
        label: "repl Editor",
        priority: RegisteredEditorPriority.option
      },
      {
        // We want to support all notebook types which could have any file extension,
        // so we just check if the resource corresponds to a notebook
        canSupportResource: (uri) => notebookService.getNotebookTextModel(uri) !== void 0,
        singlePerResource: true
      },
      {
        createUntitledEditorInput: async ({ resource, options: options3 }) => {
          if (resource) {
            const editor2 = this.a.get(resource);
            if (editor2 && !editor2.isDisposed()) {
              return { editor: editor2, options: options3 };
            } else if (editor2) {
              this.a.delete(resource);
            }
          }
          const scratchpad = this.f.getValue($rM.InteractiveWindowPromptToSave) !== true;
          const ref = await this.b.resolve({ untitledResource: resource }, "jupyter-notebook", { scratchpad, viewType: "repl" });
          const notebookUri = ref.object.notebook.uri;
          ref.object.notebook.onWillDispose(() => {
            ref.dispose();
          });
          const label3 = options3?.label ?? void 0;
          const editor = this.c.createInstance($98b, notebookUri, label3);
          this.a.set(notebookUri, editor);
          Event2.once(editor.onWillDispose)(() => this.a.delete(notebookUri));
          return { editor, options: options3 };
        },
        createEditorInput: async ({ resource, options: options3 }) => {
          if (this.a.has(resource)) {
            return { editor: this.a.get(resource), options: options3 };
          }
          const label3 = options3?.label ?? void 0;
          const editor = this.c.createInstance($98b, resource, label3);
          this.a.set(resource, editor);
          Event2.once(editor.onWillDispose)(() => this.a.delete(resource));
          return { editor, options: options3 };
        }
      }
    );
  }
};
$u9b = __decorate([
  __param(0, $mrb),
  __param(1, $4L),
  __param(2, $orb),
  __param(3, $Pk),
  __param(4, $kl)
], $u9b);
var ReplWindowWorkingCopyEditorHandler = class ReplWindowWorkingCopyEditorHandler2 extends $3c {
  static {
    this.ID = "workbench.contrib.replWorkingCopyEditorHandler";
  }
  constructor(a, b, c, f) {
    super();
    this.a = a;
    this.b = b;
    this.c = c;
    this.f = f;
    this.g();
  }
  async handles(workingCopy) {
    const notebookType = this.h(workingCopy);
    if (!notebookType) {
      return false;
    }
    return !!notebookType && notebookType.viewType === "repl" && await this.f.canResolve(notebookType.notebookType);
  }
  isOpen(workingCopy, editor) {
    if (!this.handles(workingCopy)) {
      return false;
    }
    return editor instanceof $98b && $oh(workingCopy.resource, editor.resource);
  }
  createEditor(workingCopy) {
    return this.a.createInstance($98b, workingCopy.resource, void 0);
  }
  async g() {
    await this.c.whenInstalledExtensionsRegistered();
    this.B(this.b.registerHandler(this));
  }
  h(workingCopy) {
    return $sM.parse(workingCopy.typeId);
  }
};
ReplWindowWorkingCopyEditorHandler = __decorate([
  __param(0, $Pk),
  __param(1, $6J),
  __param(2, $wN),
  __param(3, $mrb)
], ReplWindowWorkingCopyEditorHandler);
$PL(
  ReplWindowWorkingCopyEditorHandler.ID,
  ReplWindowWorkingCopyEditorHandler,
  2
  /* WorkbenchPhase.BlockRestore */
);
$PL(
  $u9b.ID,
  $u9b,
  2
  /* WorkbenchPhase.BlockRestore */
);
$vhb.register(new $s9b());
$vhb.register(new $t9b());
$hJ(class extends $gJ {
  constructor() {
    super({
      id: "repl.focusLastItemExecuted",
      title: localize2(9346, "Focus Most Recent REPL Execution"),
      category: "REPL",
      menu: {
        id: $bJ.CommandPalette,
        when: $RAb
      },
      keybinding: [{
        primary: $$e(
          512 | 13,
          512 | 13
          /* KeyCode.End */
        ),
        weight: $AIb,
        when: $7m.or($VAb, $XAb.negate())
      }],
      precondition: $RAb
    });
  }
  async run(accessor, context) {
    const editorService = accessor.get($mJ);
    const editorControl = editorService.activeEditorPane?.getControl();
    const contextKeyService = accessor.get($on);
    let notebookEditor;
    if (editorControl && $$8b(editorControl)) {
      notebookEditor = editorControl.notebookEditor;
    } else {
      const uriString = $RAb.getValue(contextKeyService);
      const uri = uriString ? URI.parse(uriString) : void 0;
      if (!uri) {
        return;
      }
      const replEditor = editorService.findEditors(uri)[0];
      if (replEditor) {
        const editor = await editorService.openEditor(replEditor.editor, replEditor.groupId);
        const editorControl2 = editor?.getControl();
        if (editorControl2 && $$8b(editorControl2)) {
          notebookEditor = editorControl2.notebookEditor;
        }
      }
    }
    const viewModel = notebookEditor?.getViewModel();
    if (notebookEditor && viewModel) {
      const lastCellIndex = viewModel.length - 1;
      if (lastCellIndex >= 0) {
        const cell = viewModel.viewCells[lastCellIndex];
        notebookEditor.focusNotebookCell(cell, "container");
      }
    }
  }
});
$hJ(class extends $gJ {
  constructor() {
    super({
      id: "repl.input.focus",
      title: localize2(9347, "Focus Input Editor"),
      category: "REPL",
      menu: {
        id: $bJ.CommandPalette,
        when: $RAb
      },
      keybinding: [{
        when: $7m.and($VAb, $WAb),
        weight: $AIb,
        primary: 2048 | 18
        /* KeyCode.DownArrow */
      }, {
        when: $7m.and($RAb),
        weight: 200 + 5,
        primary: $$e(
          512 | 14,
          512 | 14
          /* KeyCode.Home */
        )
      }]
    });
  }
  async run(accessor) {
    const editorService = accessor.get($mJ);
    const editorControl = editorService.activeEditorPane?.getControl();
    const contextKeyService = accessor.get($on);
    if (editorControl && $$8b(editorControl) && editorControl.notebookEditor) {
      editorService.activeEditorPane?.focus();
    } else {
      const uriString = $RAb.getValue(contextKeyService);
      const uri = uriString ? URI.parse(uriString) : void 0;
      if (!uri) {
        return;
      }
      const replEditor = editorService.findEditors(uri)[0];
      if (replEditor) {
        await editorService.openEditor({ resource: uri, options: { preserveFocus: false } }, replEditor.groupId);
      }
    }
  }
});
$hJ(class extends $gJ {
  constructor() {
    super({
      id: "repl.execute",
      title: localize2(9348, "Execute REPL input"),
      category: "REPL",
      keybinding: [{
        when: $7m.and($VAb, $7m.equals("activeEditor", "workbench.editor.repl")),
        primary: 2048 | 3,
        weight: $AIb
      }, {
        when: $7m.and($VAb, $7m.equals("activeEditor", "workbench.editor.repl"), $7m.equals("config.interactiveWindow.executeWithShiftEnter", true)),
        primary: 1024 | 3,
        weight: $AIb
      }, {
        when: $7m.and($VAb, $7m.equals("activeEditor", "workbench.editor.repl"), $7m.equals("config.interactiveWindow.executeWithShiftEnter", false)),
        primary: 3,
        weight: $AIb
      }],
      menu: [
        {
          id: $bJ.ReplInputExecute
        }
      ],
      icon: $CKb,
      f1: false,
      metadata: {
        description: "Execute the Contents of the Input Box",
        args: [
          {
            name: "resource",
            description: "Interactive resource Uri",
            isOptional: true
          }
        ]
      }
    });
  }
  async run(accessor, context) {
    const editorService = accessor.get($mJ);
    const bulkEditService = accessor.get($H_);
    const historyService = accessor.get($YOb);
    const notebookEditorService = accessor.get($yMb);
    let editorControl;
    if (context) {
      const resourceUri = URI.revive(context);
      const editors = editorService.findEditors(resourceUri);
      for (const found of editors) {
        if (found.editor.typeId === $98b.ID) {
          const editor = await editorService.openEditor(found.editor, found.groupId);
          editorControl = editor?.getControl();
          break;
        }
      }
    } else {
      editorControl = editorService.activeEditorPane?.getControl();
    }
    if ($$8b(editorControl)) {
      executeReplInput(bulkEditService, historyService, notebookEditorService, editorControl);
    }
  }
});
async function executeReplInput(bulkEditService, historyService, notebookEditorService, editorControl) {
  if (editorControl && editorControl.notebookEditor && editorControl.activeCodeEditor) {
    const notebookDocument = editorControl.notebookEditor.textModel;
    const textModel = editorControl.activeCodeEditor.getModel();
    const activeKernel = editorControl.notebookEditor.activeKernel;
    const language = activeKernel?.supportedLanguages[0] ?? $KF;
    if (notebookDocument && textModel) {
      const index = notebookDocument.length - 1;
      const value = textModel.getValue();
      if ($vf(value)) {
        return;
      }
      const ctrl = $cHb.get(editorControl.activeCodeEditor);
      if (ctrl) {
        ctrl.acceptHunk();
      }
      historyService.replaceLast(notebookDocument.uri, value);
      historyService.addToHistory(notebookDocument.uri, "");
      textModel.setValue("");
      notebookDocument.cells[index].resetTextBuffer(textModel.getTextBuffer());
      const collapseState = editorControl.notebookEditor.notebookOptions.getDisplayOptions().interactiveWindowCollapseCodeCells === "fromEditor" ? {
        inputCollapsed: false,
        outputCollapsed: false
      } : void 0;
      await bulkEditService.apply([
        new $Trb(notebookDocument.uri, {
          editType: 1,
          index,
          count: 0,
          cells: [{
            cellKind: CellKind.Code,
            mime: void 0,
            language,
            source: value,
            outputs: [],
            metadata: {},
            collapseState
          }]
        })
      ]);
      const range = { start: index, end: index + 1 };
      editorControl.notebookEditor.revealCellRangeInView(range);
      await editorControl.notebookEditor.executeNotebookCells(editorControl.notebookEditor.getCellsInRange({ start: index, end: index + 1 }));
      const editor = notebookEditorService.getNotebookEditor(editorControl.notebookEditor.getId());
      if (editor) {
        editor.setSelections([range]);
        editor.setFocus(range);
      }
    }
  }
}
$vhb.register(new $q9b());
$0I.registerCommandAndKeybindingRule({
  id: "list.find.replInputFocus",
  weight: 200 + 1,
  when: $7m.equals("view", $2Q),
  primary: 2048 | 512 | 36,
  secondary: [
    61
    /* KeyCode.F3 */
  ],
  handler: (accessor) => {
    $p9b(accessor.get($uob))?.openFind();
  }
});

// out-build/vs/workbench/contrib/testing/browser/codeCoverageDisplayUtils.js
var $C9b = (cc) => $4i(cc.total === 0 ? 1 : cc.covered / cc.total, 0, 1);
var colorThresholds = [
  { color: `var(${$Yn($rq)})`, key: "red" },
  { color: `var(${$Yn($tq)})`, key: "yellow" },
  { color: `var(${$Yn($vq)})`, key: "green" }
];
var $D9b = (pct, thresholds) => {
  let best = colorThresholds[0].color;
  let distance = pct;
  for (const { key: key2, color: color2 } of colorThresholds) {
    const t = thresholds[key2] / 100;
    if (t && pct >= t && pct - t < distance) {
      best = color2;
      distance = pct - t;
    }
  }
  return best;
};
var epsilon = 1e-7;
var $E9b = (value, precision = 2) => {
  const display = (value * 100).toFixed(precision);
  if (value < 1 - epsilon && display === "100") {
    return `${100 - 10 ** -precision}%`;
  }
  return `${display}%`;
};
var $F9b = (coverage, method) => {
  switch (method) {
    case "statement":
      return $C9b(coverage.statement);
    case "minimum": {
      let value = $C9b(coverage.statement);
      if (coverage.branch) {
        value = Math.min(value, $C9b(coverage.branch));
      }
      if (coverage.declaration) {
        value = Math.min(value, $C9b(coverage.declaration));
      }
      return value;
    }
    case "totalCoverage":
      return $IQ(coverage.statement, coverage.branch, coverage.declaration);
    default:
      $hd(method);
  }
};
function $G9b(result, testId, commonPrefixLen) {
  const parts = [];
  for (const id2 of testId.idsFromRoot()) {
    const item = result.getTestById(id2.toString());
    if (!item) {
      break;
    }
    parts.push(item.label);
  }
  return parts.slice(commonPrefixLen).join(" \u203A ");
}
var labels;
(function(labels2) {
  labels2.showingFilterFor = (label3) => localize(11031, null, label3);
  labels2.clickToChangeFiltering = localize(11032, null);
  labels2.percentCoverage = (percent, precision) => localize(11033, null, $E9b(percent, precision));
  labels2.allTests = localize(11034, null);
  labels2.pickShowCoverage = localize(11035, null);
})(labels || (labels = {}));

// out-build/vs/workbench/contrib/testing/browser/theme.js
var $H9b = $5n("testing.iconFailed", {
  dark: "#f14c4c",
  light: "#f14c4c",
  hcDark: "#f14c4c",
  hcLight: "#B5200D"
}, localize(11247, null));
var $I9b = $5n("testing.iconErrored", {
  dark: "#f14c4c",
  light: "#f14c4c",
  hcDark: "#f14c4c",
  hcLight: "#B5200D"
}, localize(11248, null));
var $J9b = $5n("testing.iconPassed", {
  dark: "#73c991",
  light: "#73c991",
  hcDark: "#73c991",
  hcLight: "#007100"
}, localize(11249, null));
var $K9b = $5n("testing.runAction", $J9b, localize(11250, null));
var $L9b = $5n("testing.iconQueued", "#cca700", localize(11251, null));
var $M9b = $5n("testing.iconUnset", "#848484", localize(11252, null));
var $N9b = $5n("testing.iconSkipped", "#848484", localize(11253, null));
var $O9b = $5n("testing.peekBorder", {
  dark: $Vo,
  light: $Vo,
  hcDark: $ko,
  hcLight: $ko
}, localize(11254, null));
var $P9b = $5n("testing.messagePeekBorder", {
  dark: $2o,
  light: $2o,
  hcDark: $ko,
  hcLight: $ko
}, localize(11255, null));
var $Q9b = $5n("testing.peekHeaderBackground", {
  dark: $0n($Vo, 0.1),
  light: $0n($Vo, 0.1),
  hcDark: null,
  hcLight: null
}, localize(11256, null));
var $R9b = $5n("testing.messagePeekHeaderBackground", {
  dark: $0n($2o, 0.1),
  light: $0n($2o, 0.1),
  hcDark: null,
  hcLight: null
}, localize(11257, null));
var $S9b = $5n("testing.coveredBackground", {
  dark: $Cp,
  light: $Cp,
  hcDark: null,
  hcLight: null
}, localize(11258, null));
var $T9b = $5n("testing.coveredBorder", {
  dark: $0n($S9b, 0.75),
  light: $0n($S9b, 0.75),
  hcDark: $ko,
  hcLight: $ko
}, localize(11259, null));
var $U9b = $5n("testing.coveredGutterBackground", {
  dark: $0n($Cp, 0.6),
  light: $0n($Cp, 0.6),
  hcDark: $vq,
  hcLight: $vq
}, localize(11260, null));
var $V9b = $5n("testing.uncoveredBranchBackground", {
  dark: $$n($0n($Dp, 2), $Ko),
  light: $$n($0n($Dp, 2), $Ko),
  hcDark: null,
  hcLight: null
}, localize(11261, null));
var $W9b = $5n("testing.uncoveredBackground", {
  dark: $Dp,
  light: $Dp,
  hcDark: null,
  hcLight: null
}, localize(11262, null));
var $X9b = $5n("testing.uncoveredBorder", {
  dark: $0n($W9b, 0.75),
  light: $0n($W9b, 0.75),
  hcDark: $ko,
  hcLight: $ko
}, localize(11263, null));
var $Y9b = $5n("testing.uncoveredGutterBackground", {
  dark: $0n($Dp, 1.5),
  light: $0n($Dp, 1.5),
  hcDark: $rq,
  hcLight: $rq
}, localize(11264, null));
var $Z9b = $5n("testing.coverCountBadgeBackground", $wo, localize(11265, null));
var $19b = $5n("testing.coverCountBadgeForeground", $xo, localize(11266, null));
var messageBadgeBackground = $5n("testing.message.error.badgeBackground", $Bo, localize(11267, null));
$5n("testing.message.error.badgeBorder", messageBadgeBackground, localize(11268, null));
$5n("testing.message.error.badgeForeground", $Ao, localize(11269, null));
$5n("testing.message.error.lineBackground", null, localize(11270, null));
$5n("testing.message.info.decorationForeground", $0n($Lo, 0.5), localize(11271, null));
$5n("testing.message.info.lineBackground", null, localize(11272, null));
var $29b = {
  [
    6
    /* TestResultState.Errored */
  ]: $I9b,
  [
    4
    /* TestResultState.Failed */
  ]: $H9b,
  [
    3
    /* TestResultState.Passed */
  ]: $J9b,
  [
    1
    /* TestResultState.Queued */
  ]: $L9b,
  [
    0
    /* TestResultState.Unset */
  ]: $M9b,
  [
    5
    /* TestResultState.Skipped */
  ]: $N9b
};
var $39b = $5n("testing.iconErrored.retired", $0n($I9b, 0.7), localize(11273, null));
var $49b = $5n("testing.iconFailed.retired", $0n($H9b, 0.7), localize(11274, null));
var $59b = $5n("testing.iconPassed.retired", $0n($J9b, 0.7), localize(11275, null));
var $69b = $5n("testing.iconQueued.retired", $0n($L9b, 0.7), localize(11276, null));
var $79b = $5n("testing.iconUnset.retired", $0n($M9b, 0.7), localize(11277, null));
var $89b = $5n("testing.iconSkipped.retired", $0n($N9b, 0.7), localize(11278, null));
var $99b = {
  [
    6
    /* TestResultState.Errored */
  ]: $39b,
  [
    4
    /* TestResultState.Failed */
  ]: $49b,
  [
    3
    /* TestResultState.Passed */
  ]: $59b,
  [
    1
    /* TestResultState.Queued */
  ]: $69b,
  [
    0
    /* TestResultState.Unset */
  ]: $79b,
  [
    5
    /* TestResultState.Skipped */
  ]: $89b
};
$ms((theme, collector) => {
  const editorBg = theme.getColor($Ko);
  const missBadgeBackground = editorBg && theme.getColor($W9b)?.transparent(2).makeOpaque(editorBg);
  collector.addRule(`
	.coverage-deco-inline.coverage-deco-hit.coverage-deco-hovered {
		background: ${theme.getColor($S9b)?.transparent(1.3)};
		outline-color: ${theme.getColor($T9b)?.transparent(2)};
	}
	.coverage-deco-inline.coverage-deco-miss.coverage-deco-hovered {
		background: ${theme.getColor($W9b)?.transparent(1.3)};
		outline-color: ${theme.getColor($X9b)?.transparent(2)};
	}
	.coverage-deco-branch-miss-indicator::before {
		border-color: ${missBadgeBackground?.transparent(1.3)};
		background-color: ${missBadgeBackground};
	}
	`);
});

// out-build/vs/workbench/contrib/testing/browser/icons.js
var $09b = $9r("test-view-icon", $6l.beaker, localize(11036, null));
var $$9b = $9r("test-results-icon", $6l.checklist, localize(11037, null));
var $_9b = $9r("testing-run-icon", $6l.run, localize(11038, null));
var $a0b = $9r("testing-rerun-icon", $6l.debugRerun, localize(11039, null));
var $b0b = $9r("testing-run-all-icon", $6l.runAll, localize(11040, null));
var $c0b = $9r("testing-debug-all-icon", $6l.debugAltSmall, localize(11041, null));
var $d0b = $9r("testing-debug-icon", $6l.debugAltSmall, localize(11042, null));
var $e0b = $9r("testing-coverage-icon", $6l.runCoverage, localize(11043, null));
var $f0b = $9r("testing-coverage-all-icon", $6l.runAllCoverage, localize(11044, null));
var $g0b = $9r("testing-cancel-icon", $6l.debugStop, localize(11045, null));
var $h0b = $9r("testing-filter", $6l.filter, localize(11046, null));
var $i0b = $9r("testing-hidden", $6l.eyeClosed, localize(11047, null));
var $j0b = $9r("testing-show-as-list-icon", $6l.listTree, localize(11048, null));
var $k0b = $9r("testing-show-as-list-icon", $6l.listFlat, localize(11049, null));
var $l0b = $9r("testing-update-profiles", $6l.gear, localize(11050, null));
var $m0b = $9r("testing-refresh-tests", $6l.refresh, localize(11051, null));
var $n0b = $9r("testing-turn-continuous-run-on", $6l.eye, localize(11052, null));
var $o0b = $9r("testing-turn-continuous-run-off", $6l.eyeClosed, localize(11053, null));
var $p0b = $9r("testing-continuous-is-on", $6l.eye, localize(11054, null));
var $q0b = $9r("testing-cancel-refresh-tests", $6l.stop, localize(11055, null));
var $r0b = $9r("testing-coverage", $6l.coverage, localize(11056, null));
var $s0b = $9r("testing-was-covered", $6l.check, localize(11057, null));
var $t0b = $9r("testing-missing-branch", $6l.question, localize(11058, null));
var $u0b = /* @__PURE__ */ new Map([
  [6, $9r("testing-error-icon", $6l.issues, localize(11059, null))],
  [4, $9r("testing-failed-icon", $6l.error, localize(11060, null))],
  [3, $9r("testing-passed-icon", $6l.pass, localize(11061, null))],
  [1, $9r("testing-queued-icon", $6l.history, localize(11062, null))],
  [2, $ds],
  [5, $9r("testing-skipped-icon", $6l.debugStepOver, localize(11063, null))],
  [0, $9r("testing-unset-icon", $6l.circleOutline, localize(11064, null))]
]);
$ms((theme, collector) => {
  for (const [state, icon2] of $u0b.entries()) {
    const color2 = $29b[state];
    const retiredColor = $99b[state];
    if (!color2) {
      continue;
    }
    collector.addRule(`.monaco-workbench ${ThemeIcon.asCSSSelector(icon2)} {
			color: ${theme.getColor(color2)} !important;
		}`);
    if (!retiredColor) {
      continue;
    }
    collector.addRule(`
			.test-explorer .computed-state.retired${ThemeIcon.asCSSSelector(icon2)},
			.testing-run-glyph.retired${ThemeIcon.asCSSSelector(icon2)}{
				color: ${theme.getColor(retiredColor)} !important;
			}
		`);
  }
  collector.addRule(`
		.monaco-editor .glyph-margin-widgets ${ThemeIcon.asCSSSelector($_9b)},
		.monaco-editor .glyph-margin-widgets ${ThemeIcon.asCSSSelector($b0b)},
		.monaco-editor .glyph-margin-widgets ${ThemeIcon.asCSSSelector($d0b)},
		.monaco-editor .glyph-margin-widgets ${ThemeIcon.asCSSSelector($c0b)} {
			color: ${theme.getColor($K9b)};
		}
	`);
});

// out-build/vs/workbench/contrib/testing/common/configuration.js
var TestingConfigKeys;
(function(TestingConfigKeys2) {
  TestingConfigKeys2["AutoOpenPeekView"] = "testing.automaticallyOpenPeekView";
  TestingConfigKeys2["AutoOpenPeekViewDuringContinuousRun"] = "testing.automaticallyOpenPeekViewDuringAutoRun";
  TestingConfigKeys2["OpenResults"] = "testing.automaticallyOpenTestResults";
  TestingConfigKeys2["FollowRunningTest"] = "testing.followRunningTest";
  TestingConfigKeys2["DefaultGutterClickAction"] = "testing.defaultGutterClickAction";
  TestingConfigKeys2["GutterEnabled"] = "testing.gutterEnabled";
  TestingConfigKeys2["SaveBeforeTest"] = "testing.saveBeforeTest";
  TestingConfigKeys2["AlwaysRevealTestOnStateChange"] = "testing.alwaysRevealTestOnStateChange";
  TestingConfigKeys2["CountBadge"] = "testing.countBadge";
  TestingConfigKeys2["ShowAllMessages"] = "testing.showAllMessages";
  TestingConfigKeys2["CoveragePercent"] = "testing.displayedCoveragePercent";
  TestingConfigKeys2["ShowCoverageInExplorer"] = "testing.showCoverageInExplorer";
  TestingConfigKeys2["CoverageBarThresholds"] = "testing.coverageBarThresholds";
  TestingConfigKeys2["CoverageToolbarEnabled"] = "testing.coverageToolbarEnabled";
})(TestingConfigKeys || (TestingConfigKeys = {}));
var AutoOpenTesting;
(function(AutoOpenTesting2) {
  AutoOpenTesting2["NeverOpen"] = "neverOpen";
  AutoOpenTesting2["OpenOnTestStart"] = "openOnTestStart";
  AutoOpenTesting2["OpenOnTestFailure"] = "openOnTestFailure";
  AutoOpenTesting2["OpenExplorerOnTestStart"] = "openExplorerOnTestStart";
})(AutoOpenTesting || (AutoOpenTesting = {}));
var AutoOpenPeekViewWhen;
(function(AutoOpenPeekViewWhen2) {
  AutoOpenPeekViewWhen2["FailureVisible"] = "failureInVisibleDocument";
  AutoOpenPeekViewWhen2["FailureAnywhere"] = "failureAnywhere";
  AutoOpenPeekViewWhen2["Never"] = "never";
})(AutoOpenPeekViewWhen || (AutoOpenPeekViewWhen = {}));
var DefaultGutterClickAction;
(function(DefaultGutterClickAction2) {
  DefaultGutterClickAction2["Run"] = "run";
  DefaultGutterClickAction2["Debug"] = "debug";
  DefaultGutterClickAction2["Coverage"] = "runWithCoverage";
  DefaultGutterClickAction2["ContextMenu"] = "contextMenu";
})(DefaultGutterClickAction || (DefaultGutterClickAction = {}));
var TestingCountBadge;
(function(TestingCountBadge2) {
  TestingCountBadge2["Failed"] = "failed";
  TestingCountBadge2["Off"] = "off";
  TestingCountBadge2["Passed"] = "passed";
  TestingCountBadge2["Skipped"] = "skipped";
})(TestingCountBadge || (TestingCountBadge = {}));
var TestingDisplayedCoveragePercent;
(function(TestingDisplayedCoveragePercent2) {
  TestingDisplayedCoveragePercent2["TotalCoverage"] = "totalCoverage";
  TestingDisplayedCoveragePercent2["Statement"] = "statement";
  TestingDisplayedCoveragePercent2["Minimum"] = "minimum";
})(TestingDisplayedCoveragePercent || (TestingDisplayedCoveragePercent = {}));
var $v9b = {
  id: "testing",
  order: 21,
  title: localize(11279, null),
  type: "object",
  properties: {
    [
      "testing.automaticallyOpenPeekView"
      /* TestingConfigKeys.AutoOpenPeekView */
    ]: {
      description: localize(11280, null),
      enum: [
        "failureAnywhere",
        "failureInVisibleDocument",
        "never"
      ],
      default: "never",
      enumDescriptions: [
        localize(11281, null),
        localize(11282, null),
        localize(11283, null)
      ]
    },
    [
      "testing.showAllMessages"
      /* TestingConfigKeys.ShowAllMessages */
    ]: {
      description: localize(11284, null),
      type: "boolean",
      default: false
    },
    [
      "testing.automaticallyOpenPeekViewDuringAutoRun"
      /* TestingConfigKeys.AutoOpenPeekViewDuringContinuousRun */
    ]: {
      description: localize(11285, null),
      type: "boolean",
      default: false
    },
    [
      "testing.countBadge"
      /* TestingConfigKeys.CountBadge */
    ]: {
      description: localize(11286, null),
      enum: [
        "failed",
        "off",
        "passed",
        "skipped"
      ],
      enumDescriptions: [
        localize(11287, null),
        localize(11288, null),
        localize(11289, null),
        localize(11290, null)
      ],
      default: "failed"
    },
    [
      "testing.followRunningTest"
      /* TestingConfigKeys.FollowRunningTest */
    ]: {
      description: localize(11291, null),
      type: "boolean",
      default: false
    },
    [
      "testing.defaultGutterClickAction"
      /* TestingConfigKeys.DefaultGutterClickAction */
    ]: {
      description: localize(11292, null),
      enum: [
        "run",
        "debug",
        "runWithCoverage",
        "contextMenu"
      ],
      enumDescriptions: [
        localize(11293, null),
        localize(11294, null),
        localize(11295, null),
        localize(11296, null)
      ],
      default: "run"
    },
    [
      "testing.gutterEnabled"
      /* TestingConfigKeys.GutterEnabled */
    ]: {
      description: localize(11297, null),
      type: "boolean",
      default: true
    },
    [
      "testing.saveBeforeTest"
      /* TestingConfigKeys.SaveBeforeTest */
    ]: {
      description: localize(11298, null),
      type: "boolean",
      default: true
    },
    [
      "testing.automaticallyOpenTestResults"
      /* TestingConfigKeys.OpenResults */
    ]: {
      enum: [
        "neverOpen",
        "openOnTestStart",
        "openOnTestFailure",
        "openExplorerOnTestStart"
      ],
      enumDescriptions: [
        localize(11299, null),
        localize(11300, null),
        localize(11301, null),
        localize(11302, null)
      ],
      default: "openOnTestStart",
      description: localize(11303, null)
    },
    [
      "testing.alwaysRevealTestOnStateChange"
      /* TestingConfigKeys.AlwaysRevealTestOnStateChange */
    ]: {
      markdownDescription: localize(11304, null, "`#testing.followRunningTest#`"),
      type: "boolean",
      default: false
    },
    [
      "testing.showCoverageInExplorer"
      /* TestingConfigKeys.ShowCoverageInExplorer */
    ]: {
      description: localize(11305, null),
      type: "boolean",
      default: true
    },
    [
      "testing.displayedCoveragePercent"
      /* TestingConfigKeys.CoveragePercent */
    ]: {
      markdownDescription: localize(11306, null),
      default: "totalCoverage",
      enum: [
        "totalCoverage",
        "statement",
        "minimum"
      ],
      enumDescriptions: [
        localize(11307, null),
        localize(11308, null),
        localize(11309, null)
      ]
    },
    [
      "testing.coverageBarThresholds"
      /* TestingConfigKeys.CoverageBarThresholds */
    ]: {
      markdownDescription: localize(11310, null),
      default: { red: 0, yellow: 60, green: 90 },
      properties: {
        red: { type: "number", minimum: 0, maximum: 100, default: 0 },
        yellow: { type: "number", minimum: 0, maximum: 100, default: 60 },
        green: { type: "number", minimum: 0, maximum: 100, default: 90 }
      }
    },
    [
      "testing.coverageToolbarEnabled"
      /* TestingConfigKeys.CoverageToolbarEnabled */
    ]: {
      description: localize(11311, null),
      type: "boolean",
      default: false
      // todo@connor4312: disabled by default until UI sync
    }
  }
};
$Wn.as($YL.ConfigurationMigration).registerConfigurationMigrations([{
  key: "testing.openTesting",
  migrateFn: (value) => {
    return [["testing.automaticallyOpenTestResults", { value }]];
  }
}, {
  key: "testing.automaticallyOpenResults",
  // insiders only during 1.96, remove after 1.97
  migrateFn: (value) => {
    return [["testing.automaticallyOpenTestResults", { value }]];
  }
}]);
var $w9b = (config, key2) => config.getValue(key2);
var $x9b = (config, key2) => $Dd(config.onDidChangeConfiguration, () => $w9b(config, key2));

// out-build/vs/workbench/contrib/testing/common/testCoverageService.js
var $y9b = $Qk("testCoverageService");
var $z9b = class $z9b2 extends $3c {
  constructor(contextKeyService, resultService, configService, b) {
    super();
    this.b = b;
    this.a = this.B(new $4c());
    this.selected = $he("testCoverage", void 0);
    this.filterToTest = $he("filterToTest", void 0);
    this.showInline = $he("inlineCoverage", false);
    const toolbarConfig = $G9("testing.coverageToolbarEnabled", true, configService);
    this.B($H9(TestingContextKeys.coverageToolbarEnabled, contextKeyService, (reader) => toolbarConfig.read(reader)));
    this.B($H9(TestingContextKeys.inlineCoverageEnabled, contextKeyService, (reader) => this.showInline.read(reader)));
    this.B($H9(TestingContextKeys.isTestCoverageOpen, contextKeyService, (reader) => !!this.selected.read(reader)));
    this.B($H9(TestingContextKeys.hasPerTestCoverage, contextKeyService, (reader) => !Iterable.isEmpty(this.selected.read(reader)?.allPerTestIDs())));
    this.B($H9(TestingContextKeys.isCoverageFilteredToTest, contextKeyService, (reader) => !!this.filterToTest.read(reader)));
    this.B(resultService.onResultsChanged((evt) => {
      if ("completed" in evt) {
        const coverage = evt.completed.tasks.find((t) => t.coverage.get());
        if (coverage) {
          this.openCoverage(coverage, false);
        } else {
          this.closeCoverage();
        }
      } else if ("removed" in evt && this.selected.get()) {
        const taskId = this.selected.get()?.fromTaskId;
        if (evt.removed.some((e) => e.tasks.some((t) => t.id === taskId))) {
          this.closeCoverage();
        }
      }
    }));
  }
  /** @inheritdoc */
  async openCoverage(task, focus = true) {
    this.a.value?.cancel();
    const cts = this.a.value = new $ad();
    const coverage = task.coverage.get();
    if (!coverage) {
      return;
    }
    $ce((tx) => {
      this.filterToTest.set(void 0, tx);
      this.selected.set(coverage, tx);
    });
    if (focus && !cts.token.isCancellationRequested) {
      this.b.openView("workbench.view.testCoverage", true);
    }
  }
  /** @inheritdoc */
  closeCoverage() {
    this.selected.set(void 0, void 0);
  }
};
$z9b = __decorate([
  __param(0, $on),
  __param(1, $FTb),
  __param(2, $kl),
  __param(3, $uob)
], $z9b);

// out-build/vs/workbench/contrib/testing/browser/testCoverageBars.js
var $B9b_1;
var $A9b = class $A9b2 extends $3c {
  /** Gets whether coverage is currently visible for the resource. */
  get visible() {
    return !!this.a;
  }
  constructor(j, m, n) {
    super();
    this.j = j;
    this.m = m;
    this.n = n;
    this.b = new $sf(() => {
      if (this.j.compact) {
        const el = h(".test-coverage-bars.compact", [
          h(".tpc@overall"),
          h(".bar@tpcBar")
        ]);
        this.r(el.tpcBar, getOverallHoverText);
        return el;
      } else {
        const el = h(".test-coverage-bars", [
          h(".tpc@overall"),
          h(".bar@statement"),
          h(".bar@function"),
          h(".bar@branch")
        ]);
        this.r(el.statement, stmtCoverageText);
        this.r(el.function, fnCoverageText);
        this.r(el.branch, branchCoverageText);
        return el;
      }
    });
    this.f = this.B(new $2c());
    this.g = [];
  }
  r(target, factory) {
    this.B(this.n.setupManagedHover($JZ("element"), target, () => this.a && factory(this.a)));
  }
  setCoverageInfo(coverage) {
    const ds = this.f;
    if (!coverage) {
      if (this.a) {
        this.a = void 0;
        this.g.forEach((c) => c.hide());
        ds.clear();
      }
      return;
    }
    if (!this.a) {
      const root = this.b.value.root;
      ds.add($1c(() => root.remove()));
      this.j.container.appendChild(root);
      ds.add(this.m.onDidChangeConfiguration((c) => {
        if (!this.a) {
          return;
        }
        if (c.affectsConfiguration(
          "testing.displayedCoveragePercent"
          /* TestingConfigKeys.CoveragePercent */
        ) || c.affectsConfiguration(
          "testing.coverageBarThresholds"
          /* TestingConfigKeys.CoverageBarThresholds */
        )) {
          this.s(this.a);
        }
      }));
    }
    this.a = coverage;
    this.s(coverage);
  }
  s(coverage) {
    const el = this.b.value;
    const precision = this.j.compact ? 0 : 2;
    const thresholds = $w9b(
      this.m,
      "testing.coverageBarThresholds"
      /* TestingConfigKeys.CoverageBarThresholds */
    );
    const overallStat = $F9b(coverage, $w9b(
      this.m,
      "testing.displayedCoveragePercent"
      /* TestingConfigKeys.CoveragePercent */
    ));
    if (this.j.overall !== false) {
      el.overall.textContent = $E9b(overallStat, precision);
    } else {
      el.overall.style.display = "none";
    }
    if ("tpcBar" in el) {
      renderBar(el.tpcBar, overallStat, false, thresholds);
    } else {
      renderBar(el.statement, $C9b(coverage.statement), coverage.statement.total === 0, thresholds);
      renderBar(el.function, coverage.declaration && $C9b(coverage.declaration), coverage.declaration?.total === 0, thresholds);
      renderBar(el.branch, coverage.branch && $C9b(coverage.branch), coverage.branch?.total === 0, thresholds);
    }
  }
};
$A9b = __decorate([
  __param(1, $kl),
  __param(2, $5$)
], $A9b);
var barWidth = 16;
var renderBar = (bar, pct, isZero, thresholds) => {
  if (pct === void 0) {
    bar.style.display = "none";
    return;
  }
  bar.style.display = "block";
  bar.style.width = `${barWidth}px`;
  bar.style.setProperty("--test-bar-width", `${Math.floor(pct * 16)}px`);
  if (isZero) {
    bar.style.color = "currentColor";
    bar.style.opacity = "0.5";
    return;
  }
  bar.style.color = $D9b(pct, thresholds);
  bar.style.opacity = "1";
};
var nf = new Intl.NumberFormat();
var stmtCoverageText = (coverage) => localize(11065, null, nf.format(coverage.statement.covered), nf.format(coverage.statement.total), $E9b($C9b(coverage.statement)));
var fnCoverageText = (coverage) => coverage.declaration && localize(11066, null, nf.format(coverage.declaration.covered), nf.format(coverage.declaration.total), $E9b($C9b(coverage.declaration)));
var branchCoverageText = (coverage) => coverage.branch && localize(11067, null, nf.format(coverage.branch.covered), nf.format(coverage.branch.total), $E9b($C9b(coverage.branch)));
var getOverallHoverText = (coverage) => {
  const str = [
    stmtCoverageText(coverage),
    fnCoverageText(coverage),
    branchCoverageText(coverage)
  ].filter($Hg).join("\n\n");
  return {
    markdown: new $bm().appendText(str),
    markdownNotSupportedFallback: str
  };
};
var $B9b = class $B9b2 extends $A9b {
  static {
    $B9b_1 = this;
  }
  static {
    this.u = false;
  }
  static register() {
    if (this.u) {
      return;
    }
    this.u = true;
    $Wn.as(
      "workbench.registry.explorer.fileContributions"
      /* ExplorerExtensions.FileContributionRegistry */
    ).register({
      create(insta, container2) {
        return insta.createInstance($B9b_1, { compact: true, container: container2 });
      }
    });
  }
  constructor(options3, configurationService, hoverService, testCoverageService) {
    super(options3, configurationService, hoverService);
    this.t = $he(this, void 0);
    const isEnabled = $x9b(
      configurationService,
      "testing.showCoverageInExplorer"
      /* TestingConfigKeys.ShowCoverageInExplorer */
    );
    this.B($td(async (reader) => {
      let info;
      const coverage = testCoverageService.selected.read(reader);
      if (coverage && isEnabled.read(reader)) {
        const resource = this.t.read(reader);
        if (resource) {
          info = coverage.getComputedForUri(resource);
        }
      }
      this.setCoverageInfo(info);
    }));
  }
  /** @inheritdoc */
  setResource(resource, transaction) {
    this.t.set(resource, transaction);
  }
  setCoverageInfo(coverage) {
    super.setCoverageInfo(coverage);
    this.j.container?.classList.toggle("explorer-item-with-test-coverage", this.visible);
  }
};
$B9b = $B9b_1 = __decorate([
  __param(1, $kl),
  __param(2, $5$),
  __param(3, $y9b)
], $B9b);

// out-build/vs/workbench/contrib/testing/browser/codeCoverageDecorations.js
var CLASS_HIT = "coverage-deco-hit";
var CLASS_MISS = "coverage-deco-miss";
var TOGGLE_INLINE_COMMAND_TEXT = localize(11014, null);
var TOGGLE_INLINE_COMMAND_ID = "testing.toggleInlineCoverage";
var BRANCH_MISS_INDICATOR_CHARS = 4;
var $v0b = class $v0b2 extends $3c {
  constructor(t, instantiationService, u, configurationService, w, contextKeyService) {
    super();
    this.t = t;
    this.u = u;
    this.w = w;
    this.g = this.B(new $2c());
    this.j = this.B(new $2c());
    this.n = /* @__PURE__ */ new Map();
    this.m = new $sf(() => this.B(instantiationService.createInstance(CoverageToolbarWidget, this.t)));
    const modelObs = $Dd(this, t.onDidChangeModel, () => t.getModel());
    const configObs = $Dd(this, t.onDidChangeConfiguration, (i2) => i2);
    const fileCoverage = $2d((reader) => {
      const report = u.selected.read(reader);
      if (!report) {
        return;
      }
      const model = modelObs.read(reader);
      if (!model) {
        return;
      }
      const file = report.getUri(model.uri);
      if (!file) {
        return;
      }
      report.didAddCoverage.read(reader);
      return { file, testId: u.filterToTest.read(reader) };
    });
    this.B($H9(TestingContextKeys.hasPerTestCoverage, contextKeyService, (reader) => !!fileCoverage.read(reader)?.file.perTestData?.size));
    this.B($td((reader) => {
      const c = fileCoverage.read(reader);
      if (c) {
        this.D(t.getModel(), c.file, c.testId, u.showInline.read(reader));
      } else {
        this.F();
      }
    }));
    const toolbarEnabled = $G9("testing.coverageToolbarEnabled", true, configurationService);
    this.B($td((reader) => {
      const c = fileCoverage.read(reader);
      if (c && toolbarEnabled.read(reader)) {
        this.m.value.setCoverage(c.file, c.testId);
      } else {
        this.m.rawValue?.clearCoverage();
      }
    }));
    this.B($td((reader) => {
      const c = fileCoverage.read(reader);
      if (c) {
        const evt = configObs.read(reader);
        if (evt?.hasChanged(
          68
          /* EditorOption.lineHeight */
        ) !== false) {
          this.y();
        }
      }
    }));
    this.B(t.onMouseMove((e) => {
      const model = t.getModel();
      if (e.target.type === 3 && model) {
        this.C(t.getModel());
      } else if (u.showInline.get() && e.target.type === 6 && model) {
        this.z(model, e.target.position);
      } else {
        this.j.clear();
      }
    }));
    this.B(t.onWillChangeModel(() => {
      const model = t.getModel();
      if (!this.s || !model) {
        return;
      }
      for (const decoration3 of model.getAllDecorations()) {
        const own = this.n.get(decoration3.id);
        if (own) {
          own.detail.range = decoration3.range;
        }
      }
    }));
  }
  y() {
    const lineHeight = this.t.getOption(
      68
      /* EditorOption.lineHeight */
    );
    const { style } = this.t.getContainerDomNode();
    style.setProperty("--vscode-testing-coverage-lineHeight", `${lineHeight}px`);
  }
  z(model, position) {
    const allDecorations = model.getDecorationsInRange($9C.fromPositions(position));
    const decoration3 = $ab(allDecorations, ({ id: id2 }) => this.n.has(id2) ? { id: id2, deco: this.n.get(id2) } : void 0);
    if (decoration3 === this.r) {
      return;
    }
    this.j.clear();
    this.r = decoration3;
    if (!decoration3) {
      return;
    }
    model.changeDecorations((e) => {
      e.changeDecorationOptions(decoration3.id, {
        ...decoration3.deco.options,
        className: `${decoration3.deco.options.className} coverage-deco-hovered`
      });
    });
    this.j.add($1c(() => {
      this.r = void 0;
      model.changeDecorations((e) => {
        e.changeDecorationOptions(decoration3.id, decoration3.deco.options);
      });
    }));
  }
  C(model) {
    if (this.r === "lineNo" || !this.s || this.u.showInline.get()) {
      return;
    }
    this.j.clear();
    this.r = "lineNo";
    model.changeDecorations((e) => {
      for (const [id2, decoration3] of this.n) {
        const { applyHoverOptions, options: options3 } = decoration3;
        const dup = { ...options3 };
        applyHoverOptions(dup);
        e.changeDecorationOptions(id2, dup);
      }
    });
    this.j.add(this.t.onMouseLeave(() => {
      this.j.clear();
    }));
    this.j.add($1c(() => {
      this.r = void 0;
      model.changeDecorations((e) => {
        for (const [id2, decoration3] of this.n) {
          e.changeDecorationOptions(id2, decoration3.options);
        }
      });
    }));
  }
  async D(model, coverage, testId, showInlineByDefault) {
    const details = this.s = await this.G(coverage, testId, model);
    if (!details) {
      return this.F();
    }
    this.g.clear();
    model.changeDecorations((e) => {
      for (const detailRange of details.ranges) {
        const { metadata: { detail: detail2, description }, range, primary } = detailRange;
        if (detail2.type === 2) {
          const hits = detail2.detail.branches[detail2.branch].count;
          const cls = hits ? CLASS_HIT : CLASS_MISS;
          const showMissIndicator = !hits && range.isEmpty() && detail2.detail.branches.some((b) => b.count);
          const options3 = {
            showIfCollapsed: showMissIndicator,
            // only avoid collapsing if we want to show the miss indicator
            description: "coverage-gutter",
            lineNumberClassName: `coverage-deco-gutter ${cls}`
          };
          const applyHoverOptions = (target) => {
            target.hoverMessage = description;
            if (showMissIndicator) {
              target.after = {
                content: "\xA0".repeat(BRANCH_MISS_INDICATOR_CHARS),
                // nbsp
                inlineClassName: `coverage-deco-branch-miss-indicator ${ThemeIcon.asClassName($t0b)}`,
                inlineClassNameAffectsLetterSpacing: true,
                cursorStops: InjectedTextCursorStops.None
              };
            } else {
              target.className = `coverage-deco-inline ${cls}`;
              if (primary && typeof hits === "number") {
                target.before = countBadge(hits);
              }
            }
          };
          if (showInlineByDefault) {
            applyHoverOptions(options3);
          }
          this.n.set(e.addDecoration(range, options3), { options: options3, applyHoverOptions, detail: detailRange });
        } else if (detail2.type === 1) {
          const cls = detail2.count ? CLASS_HIT : CLASS_MISS;
          const options3 = {
            showIfCollapsed: false,
            description: "coverage-inline",
            lineNumberClassName: `coverage-deco-gutter ${cls}`
          };
          const applyHoverOptions = (target) => {
            target.className = `coverage-deco-inline ${cls}`;
            target.hoverMessage = description;
            if (primary && typeof detail2.count === "number") {
              target.before = countBadge(detail2.count);
            }
          };
          if (showInlineByDefault) {
            applyHoverOptions(options3);
          }
          this.n.set(e.addDecoration(range, options3), { options: options3, applyHoverOptions, detail: detailRange });
        }
      }
    });
    this.g.add($1c(() => {
      model.changeDecorations((e) => {
        for (const decoration3 of this.n.keys()) {
          e.removeDecoration(decoration3);
        }
        this.n.clear();
      });
    }));
  }
  F() {
    this.f?.cancel();
    this.f = void 0;
    this.g.clear();
    this.j.clear();
  }
  async G(coverage, testId, textModel) {
    const cts = this.f = new $ad();
    this.g.add(this.f);
    try {
      const details = testId ? await coverage.detailsForTest(testId, this.f.token) : await coverage.details(this.f.token);
      if (cts.token.isCancellationRequested) {
        return;
      }
      return new $w0b(details, textModel);
    } catch (e) {
      this.w.error("Error loading coverage details", e);
    }
    return void 0;
  }
};
$v0b = __decorate([
  __param(1, $Pk),
  __param(2, $y9b),
  __param(3, $kl),
  __param(4, $wn),
  __param(5, $on)
], $v0b);
var countBadge = (count) => {
  if (count === 0) {
    return void 0;
  }
  return {
    content: `${count > 99 ? "99+" : count}x`,
    cursorStops: InjectedTextCursorStops.None,
    inlineClassName: `coverage-deco-inline-count`,
    inlineClassNameAffectsLetterSpacing: true
  };
};
var $w0b = class {
  constructor(details, textModel) {
    this.details = details;
    this.ranges = [];
    const detailRanges = details.map((detail2) => ({
      range: tidyLocation(detail2.location),
      primary: true,
      metadata: { detail: detail2, description: this.describe(detail2, textModel) }
    }));
    for (const { range, metadata: { detail: detail2 } } of detailRanges) {
      if (detail2.type === 1 && detail2.branches) {
        for (let i2 = 0; i2 < detail2.branches.length; i2++) {
          const branch = { type: 2, branch: i2, detail: detail2 };
          detailRanges.push({
            range: tidyLocation(detail2.branches[i2].location || $9C.fromPositions(range.getEndPosition())),
            primary: true,
            metadata: {
              detail: branch,
              description: this.describe(branch, textModel)
            }
          });
        }
      }
    }
    detailRanges.sort((a, b) => $9C.compareRangesUsingStarts(a.range, b.range) || a.metadata.detail.type - b.metadata.detail.type);
    const stack = [];
    const result = this.ranges = [];
    const pop = () => {
      const next = stack.pop();
      const prev = stack[stack.length - 1];
      if (prev) {
        prev.range = prev.range.setStartPosition(next.range.endLineNumber, next.range.endColumn);
      }
      result.push(next);
    };
    for (const item of detailRanges) {
      const start = item.range.getStartPosition();
      while (stack[stack.length - 1]?.range.containsPosition(start) === false) {
        pop();
      }
      if (item.range.isEmpty()) {
        result.push(item);
        continue;
      }
      const prev = stack[stack.length - 1];
      if (prev) {
        const primary = prev.primary;
        const si = prev.range.setEndPosition(start.lineNumber, start.column);
        prev.range = prev.range.setStartPosition(item.range.endLineNumber, item.range.endColumn);
        prev.primary = false;
        if (prev.range.isEmpty()) {
          stack.pop();
        }
        result.push({ range: si, primary, metadata: prev.metadata });
      }
      stack.push(item);
    }
    while (stack.length) {
      pop();
    }
  }
  /** Gets the markdown description for the given detail */
  describe(detail2, model) {
    if (detail2.type === 0) {
      return namedDetailLabel(detail2.name, detail2);
    } else if (detail2.type === 1) {
      const text2 = wrapName(model.getValueInRange(tidyLocation(detail2.location)).trim() || `<empty statement>`);
      if (detail2.branches?.length) {
        const covered = detail2.branches.filter((b) => !!b.count).length;
        return new $bm().appendMarkdown(localize(11015, null, covered, detail2.branches.length, text2));
      } else {
        return namedDetailLabel(text2, detail2);
      }
    } else if (detail2.type === 2) {
      const text2 = wrapName(model.getValueInRange(tidyLocation(detail2.detail.location)).trim() || `<empty statement>`);
      const { count, label: label3 } = detail2.detail.branches[detail2.branch];
      const label22 = label3 ? wrapInBackticks(label3) : `#${detail2.branch + 1}`;
      if (!count) {
        return new $bm().appendMarkdown(localize(11016, null, label22, text2));
      } else if (count === true) {
        return new $bm().appendMarkdown(localize(11017, null, label22, text2));
      } else {
        return new $bm().appendMarkdown(localize(11018, null, label22, text2, count));
      }
    }
    $hd(detail2);
  }
};
function namedDetailLabel(name, detail2) {
  return new $bm().appendMarkdown(!detail2.count ? localize(11019, null, name) : typeof detail2.count === "number" ? localize(11020, null, name, detail2.count) : localize(11021, null, name));
}
function tidyLocation(location3) {
  if (location3 instanceof $8C) {
    return $9C.fromPositions(location3, new $8C(location3.lineNumber, 2147483647));
  }
  return location3;
}
function wrapInBackticks(str) {
  return "`" + str.replace(/[\n\r`]/g, "") + "`";
}
function wrapName(functionNameOrCode) {
  if (functionNameOrCode.length > 50) {
    functionNameOrCode = functionNameOrCode.slice(0, 40) + "...";
  }
  return wrapInBackticks(functionNameOrCode);
}
var CoverageToolbarWidget = class CoverageToolbarWidget2 extends $3c {
  constructor(t, u, w, y, z, C, D, instaService) {
    super();
    this.t = t;
    this.u = u;
    this.w = w;
    this.y = y;
    this.z = z;
    this.C = C;
    this.D = D;
    this.g = false;
    this.j = false;
    this.m = this.B(new $2c());
    this.r = h("div.coverage-summary-widget", [
      h("div", [
        h("span.bars@bars"),
        h("span.toolbar@toolbar")
      ])
    ]);
    this.s = this.B(instaService.createInstance($A9b, {
      compact: false,
      overall: false,
      container: this.r.bars
    }));
    this.n = this.B(instaService.createInstance($LZ, this.r.toolbar, {
      orientation: 0,
      actionViewItemProvider: (action, options3) => {
        const vm = new CodiconActionViewItem(void 0, action, options3);
        if (action instanceof ActionWithIcon) {
          vm.themeIcon = action.icon;
        }
        return vm;
      }
    }));
    this.B($td((reader) => {
      D.showInline.read(reader);
      this.F();
    }));
    this.B($aj(this.r.root, $7j.CONTEXT_MENU, (e) => {
      this.w.showContextMenu({
        menuId: $bJ.StickyScrollContext,
        getAnchor: () => e
      });
    }));
  }
  /** @inheritdoc */
  getId() {
    return "coverage-summary-widget";
  }
  /** @inheritdoc */
  getDomNode() {
    return this.r.root;
  }
  /** @inheritdoc */
  getPosition() {
    return {
      preference: 2,
      stackOridinal: 9
    };
  }
  clearCoverage() {
    this.f = void 0;
    this.s.setCoverageInfo(void 0);
    this.I();
  }
  setCoverage(coverage, testId) {
    this.f = { coverage, testId };
    this.s.setCoverageInfo(coverage);
    if (!coverage) {
      this.I();
    } else {
      this.F();
      this.G();
    }
  }
  F() {
    this.n.clear();
    const current = this.f;
    if (!current) {
      return;
    }
    const toggleAction = new ActionWithIcon("toggleInline", this.D.showInline.get() ? localize(11022, null) : localize(11023, null), $r0b, void 0, () => this.D.showInline.set(!this.D.showInline.get(), void 0));
    const kb = this.z.lookupKeybinding(TOGGLE_INLINE_COMMAND_ID);
    if (kb) {
      toggleAction.tooltip = `${TOGGLE_INLINE_COMMAND_TEXT} (${kb.getLabel()})`;
    }
    this.n.push(toggleAction);
    if (current.testId) {
      const testItem = current.coverage.fromResult.getTestById(current.testId.toString());
      $id(!!testItem, "got coverage for an unreported test");
      this.n.push(new ActionWithIcon("perTestFilter", labels.showingFilterFor(testItem.label), $h0b, void 0, () => this.C.executeCommand("testing.coverageFilterToTestInEditor", this.f, this.t)));
    } else if (current.coverage.perTestData?.size) {
      this.n.push(new ActionWithIcon("perTestFilter", localize(11024, null, current.coverage.perTestData.size), $h0b, void 0, () => this.C.executeCommand("testing.coverageFilterToTestInEditor", this.f, this.t)));
    }
    this.n.push(new ActionWithIcon("rerun", localize(11025, null), $a0b, !this.j, () => this.H()));
  }
  G() {
    if (this.g) {
      return;
    }
    this.g = true;
    let viewZoneId;
    const ds = this.m;
    this.t.addOverlayWidget(this);
    this.t.changeViewZones((accessor) => {
      viewZoneId = accessor.addZone({
        afterLineNumber: 0,
        afterColumn: 0,
        domNode: document.createElement("div"),
        heightInPx: 30,
        ordinal: -1
        // show before code lenses
      });
    });
    ds.add($1c(() => {
      this.g = false;
      this.t.removeOverlayWidget(this);
      this.t.changeViewZones((accessor) => {
        accessor.removeZone(viewZoneId);
      });
    }));
    ds.add(this.u.onDidChangeConfiguration((e) => {
      if (this.f && (e.affectsConfiguration(
        "testing.coverageBarThresholds"
        /* TestingConfigKeys.CoverageBarThresholds */
      ) || e.affectsConfiguration(
        "testing.displayedCoveragePercent"
        /* TestingConfigKeys.CoveragePercent */
      ))) {
        this.setCoverage(this.f.coverage, this.f.testId);
      }
    }));
  }
  H() {
    const current = this.f;
    if (current) {
      this.j = true;
      this.F();
      this.y.runResolvedTests(current.coverage.fromResult.request).finally(() => {
        this.j = false;
        this.F();
      });
    }
  }
  I() {
    this.m.clear();
  }
};
CoverageToolbarWidget = __decorate([
  __param(1, $kl),
  __param(2, $50),
  __param(3, $nTb),
  __param(4, $Ty),
  __param(5, $sn),
  __param(6, $y9b),
  __param(7, $Pk)
], CoverageToolbarWidget);
$hJ(class ToggleInlineCoverage extends $gJ {
  constructor() {
    super({
      id: TOGGLE_INLINE_COMMAND_ID,
      // note: ideally this would be "show inline", but the command palette does
      // not use the 'toggled' titles, so we need to make this generic.
      title: localize2(11027, "Toggle Inline Coverage"),
      category: $qn.Test,
      keybinding: {
        weight: 200,
        primary: $$e(
          2048 | 85,
          2048 | 1024 | 39
          /* KeyCode.KeyI */
        )
      },
      toggled: {
        condition: TestingContextKeys.inlineCoverageEnabled,
        title: localize(11026, null)
      },
      icon: $r0b,
      menu: [
        { id: $bJ.CommandPalette, when: TestingContextKeys.isTestCoverageOpen },
        { id: $bJ.EditorTitle, when: $7m.and(TestingContextKeys.isTestCoverageOpen, TestingContextKeys.coverageToolbarEnabled.notEqualsTo(true)), group: "navigation" }
      ]
    });
  }
  run(accessor) {
    const coverage = accessor.get($y9b);
    coverage.showInline.set(!coverage.showInline.get(), void 0);
  }
});
$hJ(class ToggleCoverageToolbar extends $gJ {
  constructor() {
    super({
      id: "testing.coverageToggleToolbar",
      title: localize2(11028, "Test Coverage Toolbar"),
      metadata: {
        description: localize2(11029, "Toggle the sticky coverage bar in the editor.")
      },
      category: $qn.Test,
      toggled: {
        condition: TestingContextKeys.coverageToolbarEnabled
      },
      menu: [
        { id: $bJ.CommandPalette, when: TestingContextKeys.isTestCoverageOpen },
        { id: $bJ.StickyScrollContext, when: TestingContextKeys.isTestCoverageOpen },
        { id: $bJ.EditorTitle, when: TestingContextKeys.isTestCoverageOpen, group: "coverage@1" }
      ]
    });
  }
  run(accessor) {
    const config = accessor.get($kl);
    const value = $w9b(
      config,
      "testing.coverageToolbarEnabled"
      /* TestingConfigKeys.CoverageToolbarEnabled */
    );
    config.updateValue("testing.coverageToolbarEnabled", !value);
  }
});
$hJ(class FilterCoverageToTestInEditor extends $gJ {
  constructor() {
    super({
      id: "testing.coverageFilterToTestInEditor",
      title: localize2(11030, "Filter Coverage to Test"),
      category: $qn.Test,
      icon: $6l.filter,
      toggled: {
        icon: $6l.filterFilled,
        condition: TestingContextKeys.isCoverageFilteredToTest
      },
      menu: [
        {
          id: $bJ.EditorTitle,
          when: $7m.and(TestingContextKeys.isTestCoverageOpen, TestingContextKeys.coverageToolbarEnabled.notEqualsTo(true), TestingContextKeys.hasPerTestCoverage),
          group: "navigation"
        }
      ]
    });
  }
  run(accessor, coverageOrUri, editor) {
    const testCoverageService = accessor.get($y9b);
    const quickInputService = accessor.get($1M);
    const activeEditor = $P5(editor) ? editor : accessor.get($U5).getActiveCodeEditor();
    let coverage;
    if (coverageOrUri instanceof $MQ) {
      coverage = coverageOrUri;
    } else if ($zc(coverageOrUri)) {
      coverage = testCoverageService.selected.get()?.getUri(URI.from(coverageOrUri));
    } else {
      const uri = activeEditor?.getModel()?.uri;
      coverage = uri && testCoverageService.selected.get()?.getUri(uri);
    }
    if (!coverage || !coverage.perTestData?.size) {
      return;
    }
    const tests = [...coverage.perTestData].map($mQ.fromString);
    const commonPrefix = $mQ.getLengthOfCommonPrefix(tests.length, (i2) => tests[i2]);
    const result = coverage.fromResult;
    const previousSelection = testCoverageService.filterToTest.get();
    const items = [
      { label: labels.allTests, testId: void 0 },
      { type: "separator" },
      ...tests.map((id2) => ({ label: $G9b(result, id2, commonPrefix), testId: id2 }))
    ];
    const scrollTop = activeEditor?.getScrollTop() || 0;
    const revealScrollCts = new $4c();
    quickInputService.pick(items, {
      activeItem: items.find((item) => "item" in item && item.item === coverage),
      placeHolder: labels.pickShowCoverage,
      onDidFocus: (entry) => {
        if (!entry.testId) {
          revealScrollCts.clear();
          activeEditor?.setScrollTop(scrollTop);
          testCoverageService.filterToTest.set(void 0, void 0);
        } else {
          const cts = revealScrollCts.value = new $ad();
          coverage.detailsForTest(entry.testId, cts.token).then((details) => {
            const first = details.find(
              (d) => d.type === 1
              /* DetailType.Statement */
            );
            if (!cts.token.isCancellationRequested && first) {
              activeEditor?.revealLineNearTop(first.location instanceof $8C ? first.location.lineNumber : first.location.startLineNumber);
            }
          }, () => {
          });
          testCoverageService.filterToTest.set(entry.testId, void 0);
        }
      }
    }).then((selected) => {
      if (!selected) {
        activeEditor?.setScrollTop(scrollTop);
      }
      revealScrollCts.dispose();
      testCoverageService.filterToTest.set(selected ? selected.testId : previousSelection, void 0);
    });
  }
});
var ActionWithIcon = class extends $Um {
  constructor(id2, title, icon2, enabled, run) {
    super(id2, title, void 0, enabled, run);
    this.icon = icon2;
  }
};
var CodiconActionViewItem = class extends $U1 {
  C() {
    if (this.u.label && this.L && this.themeIcon) {
      $dk(this.L, $C1(this.themeIcon), this.action.label);
    }
  }
};

// out-build/vs/workbench/contrib/testing/common/observableUtils.js
function $x0b(observable, callback) {
  const o = {
    beginUpdate() {
    },
    endUpdate() {
    },
    handlePossibleChange(observable2) {
      observable2.reportChanges();
    },
    handleChange(_observable, change) {
      callback(change);
    }
  };
  observable.addObserver(o);
  return {
    dispose() {
      observable.removeObserver(o);
    }
  };
}

// out-build/vs/workbench/contrib/testing/browser/testCoverageView.js
var FileCoverageRenderer_1;
var DeclarationCoverageRenderer_1;
var CoverageSortOrder;
(function(CoverageSortOrder2) {
  CoverageSortOrder2[CoverageSortOrder2["Coverage"] = 0] = "Coverage";
  CoverageSortOrder2[CoverageSortOrder2["Location"] = 1] = "Location";
  CoverageSortOrder2[CoverageSortOrder2["Name"] = 2] = "Name";
})(CoverageSortOrder || (CoverageSortOrder = {}));
var $y0b = class $y0b2 extends $_ob {
  constructor(options3, keybindingService, contextMenuService, configurationService, contextKeyService, viewDescriptorService, instantiationService, openerService, themeService, telemetryService, hoverService, g) {
    super(options3, keybindingService, contextMenuService, configurationService, contextKeyService, viewDescriptorService, instantiationService, openerService, themeService, telemetryService, hoverService);
    this.g = g;
    this.f = new $4c();
    this.sortOrder = $he(
      "sortOrder",
      1
      /* CoverageSortOrder.Location */
    );
  }
  W(container2) {
    super.W(container2);
    const labels2 = this.B(this.Db.createInstance($lsb, { onDidChangeVisibility: this.onDidChangeBodyVisibility }));
    this.B($td((reader) => {
      const coverage = this.g.selected.read(reader);
      if (coverage) {
        const t = this.f.value ??= this.Db.createInstance(TestCoverageTree, container2, labels2, this.sortOrder);
        t.setInput(coverage, this.g.filterToTest.read(reader));
      } else {
        this.f.clear();
      }
    }));
    this.B($td((reader) => {
      this.element.classList.toggle("coverage-view-is-filtered", !!this.g.filterToTest.read(reader));
    }));
  }
  X(height, width2) {
    super.X(height, width2);
    this.f.value?.layout(height, width2);
  }
};
$y0b = __decorate([
  __param(1, $Ty),
  __param(2, $50),
  __param(3, $kl),
  __param(4, $on),
  __param(5, $$M),
  __param(6, $Pk),
  __param(7, $O4),
  __param(8, $gs),
  __param(9, $zv),
  __param(10, $5$),
  __param(11, $y9b)
], $y0b);
var fnNodeId = 0;
var DeclarationCoverageNode = class {
  get hits() {
    return this.d.count;
  }
  get label() {
    return this.d.name;
  }
  get location() {
    return this.d.location;
  }
  get tpc() {
    const attr = this.attributableCoverage();
    return attr && $IQ(attr.statement, attr.branch, void 0);
  }
  constructor(uri, d, details) {
    this.uri = uri;
    this.d = d;
    this.id = String(fnNodeId++);
    this.containedDetails = /* @__PURE__ */ new Set();
    this.children = [];
    if (d.location instanceof $9C) {
      for (const detail2 of details) {
        if (this.contains(detail2.location)) {
          this.containedDetails.add(detail2);
        }
      }
    }
  }
  /** Gets whether this function has a defined range and contains the given range. */
  contains(location3) {
    const own = this.d.location;
    return own instanceof $9C && (location3 instanceof $9C ? own.containsRange(location3) : own.containsPosition(location3));
  }
  /**
   * If the function defines a range, we can look at statements within the
   * function to get total coverage for the function, rather than a boolean
   * yes/no.
   */
  attributableCoverage() {
    const { location: location3, count } = this.d;
    if (!(location3 instanceof $9C) || !count) {
      return;
    }
    const statement = { covered: 0, total: 0 };
    const branch = { covered: 0, total: 0 };
    for (const detail2 of this.containedDetails) {
      if (detail2.type !== 1) {
        continue;
      }
      statement.covered += detail2.count ? 1 : 0;
      statement.total++;
      if (detail2.branches) {
        for (const { count: count2 } of detail2.branches) {
          branch.covered += count2 ? 1 : 0;
          branch.total++;
        }
      }
    }
    return { statement, branch };
  }
};
__decorate([
  $0t
], DeclarationCoverageNode.prototype, "attributableCoverage", null);
var RevealUncoveredDeclarations = class {
  get label() {
    return localize(11068, null, this.n);
  }
  constructor(n) {
    this.n = n;
    this.id = String(fnNodeId++);
  }
};
var LoadingDetails = class {
  constructor() {
    this.id = String(fnNodeId++);
    this.label = localize(11069, null);
  }
};
var isFileCoverage = (c) => typeof c === "object" && "value" in c;
var isDeclarationCoverage = (c) => c instanceof DeclarationCoverageNode;
var shouldShowDeclDetailsOnExpand = (c) => isFileCoverage(c) && c.value instanceof $MQ && !!c.value.declaration?.total;
var TestCoverageTree = class TestCoverageTree2 extends $3c {
  constructor(container2, labels2, sortOrder, instantiationService, editorService) {
    super();
    this.g = this.B(new $2c());
    this.f = instantiationService.createInstance($2eb, "TestCoverageView", container2, new TestCoverageTreeListDelegate(), [
      instantiationService.createInstance(FileCoverageRenderer, labels2),
      instantiationService.createInstance(DeclarationCoverageRenderer),
      instantiationService.createInstance(BasicRenderer)
    ], {
      expandOnlyOnTwistieClick: true,
      sorter: new Sorter(sortOrder),
      keyboardNavigationLabelProvider: {
        getCompressedNodeKeyboardNavigationLabel(elements) {
          return elements.map((e) => this.getKeyboardNavigationLabel(e)).join("/");
        },
        getKeyboardNavigationLabel(e) {
          return isFileCoverage(e) ? $rh(e.value.uri) : e.label;
        }
      },
      accessibilityProvider: {
        getAriaLabel(element) {
          if (isFileCoverage(element)) {
            const name = $rh(element.value.uri);
            return localize(11070, null, name, (element.value.tpc * 100).toFixed(2));
          } else {
            return element.label;
          }
        },
        getWidgetAriaLabel() {
          return localize(11071, null);
        }
      },
      identityProvider: new TestCoverageIdentityProvider()
    });
    this.B($td((reader) => {
      sortOrder.read(reader);
      this.f.resort(null, true);
    }));
    this.B(this.f);
    this.B(this.f.onDidChangeCollapseState((e) => {
      const el = e.node.element;
      if (!e.node.collapsed && !e.node.children.length && el && shouldShowDeclDetailsOnExpand(el)) {
        if (el.value.hasSynchronousDetails) {
          this.f.setChildren(el, [{ element: new LoadingDetails(), incompressible: true }]);
        }
        el.value.details().then((details) => this.h(el, details));
      }
    }));
    this.B(this.f.onDidOpen((e) => {
      let resource;
      let selection;
      if (e.element) {
        if (isFileCoverage(e.element) && !e.element.children?.size) {
          resource = e.element.value.uri;
        } else if (isDeclarationCoverage(e.element)) {
          resource = e.element.uri;
          selection = e.element.location;
        }
      }
      if (!resource) {
        return;
      }
      editorService.openEditor({
        resource,
        options: {
          selection: selection instanceof $8C ? $9C.fromPositions(selection, selection) : selection,
          revealIfOpened: true,
          selectionRevealType: 3,
          preserveFocus: e.editorOptions.preserveFocus,
          pinned: e.editorOptions.pinned,
          source: EditorOpenSource.USER
        }
      }, e.sideBySide ? $oJ : $nJ);
    }));
  }
  setInput(coverage, showOnlyTest) {
    this.g.clear();
    let tree = coverage.tree;
    if (showOnlyTest) {
      tree = coverage.filterTreeForTest(showOnlyTest);
    }
    const files = [];
    for (let node of tree.nodes) {
      while (!(node.value instanceof $MQ) && node.children?.size === 1) {
        node = Iterable.first(node.children.values());
      }
      files.push(node);
    }
    const toChild = (value) => {
      const isFile = !value.children?.size;
      return {
        element: value,
        incompressible: isFile,
        collapsed: isFile,
        // directories can be expanded, and items with function info can be expanded
        collapsible: !isFile || !!value.value?.declaration?.total,
        children: value.children && Iterable.map(value.children?.values(), toChild)
      };
    };
    this.g.add($x0b(coverage.didAddCoverage, (nodes) => {
      const toRender = $1(nodes, (n) => this.f.hasElement(n));
      if (toRender) {
        this.f.setChildren(toRender, Iterable.map(toRender.children?.values() || [], toChild), { diffIdentityProvider: { getId: (el) => el.value.id } });
      }
    }));
    this.f.setChildren(null, Iterable.map(files, toChild));
  }
  layout(height, width2) {
    this.f.layout(height, width2);
  }
  h(el, details) {
    if (!this.f.hasElement(el)) {
      return;
    }
    const decl = [];
    for (const fn of details) {
      if (fn.type !== 0) {
        continue;
      }
      let arr = decl;
      while (true) {
        const parent = arr.find((p) => p.containedDetails.has(fn));
        if (parent) {
          arr = parent.children;
        } else {
          break;
        }
      }
      arr.push(new DeclarationCoverageNode(el.value.uri, fn, details));
    }
    const makeChild = (fn) => ({
      element: fn,
      incompressible: true,
      collapsed: true,
      collapsible: fn.children.length > 0,
      children: fn.children.map(makeChild)
    });
    this.f.setChildren(el, decl.map(makeChild));
  }
};
TestCoverageTree = __decorate([
  __param(3, $Pk),
  __param(4, $mJ)
], TestCoverageTree);
var TestCoverageTreeListDelegate = class {
  getHeight(element) {
    return 22;
  }
  getTemplateId(element) {
    if (isFileCoverage(element)) {
      return FileCoverageRenderer.ID;
    }
    if (isDeclarationCoverage(element)) {
      return DeclarationCoverageRenderer.ID;
    }
    if (element instanceof LoadingDetails || element instanceof RevealUncoveredDeclarations) {
      return BasicRenderer.ID;
    }
    $hd(element);
  }
};
var Sorter = class {
  constructor(d) {
    this.d = d;
  }
  compare(a, b) {
    const order = this.d.get();
    if (isFileCoverage(a) && isFileCoverage(b)) {
      switch (order) {
        case 1:
        case 2:
          return a.value.uri.toString().localeCompare(b.value.uri.toString());
        case 0:
          return b.value.tpc - a.value.tpc;
      }
    } else if (isDeclarationCoverage(a) && isDeclarationCoverage(b)) {
      switch (order) {
        case 1:
          return $8C.compare(a.location instanceof $9C ? a.location.getStartPosition() : a.location, b.location instanceof $9C ? b.location.getStartPosition() : b.location);
        case 2:
          return a.label.localeCompare(b.label);
        case 0: {
          const attrA = a.tpc;
          const attrB = b.tpc;
          return attrA !== void 0 && attrB !== void 0 && attrB - attrA || +b.hits - +a.hits || a.label.localeCompare(b.label);
        }
      }
    } else {
      return 0;
    }
  }
};
var FileCoverageRenderer = class FileCoverageRenderer2 {
  static {
    FileCoverageRenderer_1 = this;
  }
  static {
    this.ID = "F";
  }
  constructor(d, f, g) {
    this.d = d;
    this.f = f;
    this.g = g;
    this.templateId = FileCoverageRenderer_1.ID;
  }
  /** @inheritdoc */
  renderTemplate(container2) {
    const templateDisposables = new $2c();
    container2.classList.add("test-coverage-list-item");
    return {
      container: container2,
      bars: templateDisposables.add(this.g.createInstance($A9b, { compact: false, container: container2 })),
      label: templateDisposables.add(this.d.create(container2, {
        supportHighlights: true
      })),
      elementsDisposables: templateDisposables.add(new $2c()),
      templateDisposables
    };
  }
  /** @inheritdoc */
  renderElement(node, _index, templateData) {
    this.h(node.element, templateData, node.filterData);
  }
  /** @inheritdoc */
  renderCompressedElements(node, _index, templateData) {
    this.h(node.element.elements, templateData, node.filterData);
  }
  disposeTemplate(templateData) {
    templateData.templateDisposables.dispose();
  }
  /** @inheritdoc */
  h(element, templateData, filterData) {
    templateData.elementsDisposables.clear();
    const stat = element instanceof Array ? element[element.length - 1] : element;
    const file = stat.value;
    const name = element instanceof Array ? element.map((e) => $rh(e.value.uri)) : $rh(file.uri);
    if (file instanceof $LQ) {
      templateData.bars.setCoverageInfo(void 0);
    } else {
      templateData.elementsDisposables.add($td((reader) => {
        stat.value?.didChange.read(reader);
        templateData.bars.setCoverageInfo(file);
      }));
      templateData.bars.setCoverageInfo(file);
    }
    templateData.label.setResource({ resource: file.uri, name }, {
      fileKind: stat.children?.size ? FileKind.FOLDER : FileKind.FILE,
      matches: $Ul(filterData),
      separator: this.f.getSeparator(file.uri.scheme, file.uri.authority),
      extraClasses: ["test-coverage-list-item-label"]
    });
  }
};
FileCoverageRenderer = FileCoverageRenderer_1 = __decorate([
  __param(1, $ZI),
  __param(2, $Pk)
], FileCoverageRenderer);
var DeclarationCoverageRenderer = class DeclarationCoverageRenderer2 {
  static {
    DeclarationCoverageRenderer_1 = this;
  }
  static {
    this.ID = "N";
  }
  constructor(d) {
    this.d = d;
    this.templateId = DeclarationCoverageRenderer_1.ID;
  }
  /** @inheritdoc */
  renderTemplate(container2) {
    const templateDisposables = new $2c();
    container2.classList.add("test-coverage-list-item");
    const icon2 = $bk(container2, $(".state"));
    const label3 = $bk(container2, $(".name"));
    return {
      container: container2,
      bars: templateDisposables.add(this.d.createInstance($A9b, { compact: false, container: container2 })),
      templateDisposables,
      icon: icon2,
      label: label3
    };
  }
  /** @inheritdoc */
  renderElement(node, _index, templateData) {
    this.f(node.element, templateData, node.filterData);
  }
  /** @inheritdoc */
  renderCompressedElements(node, _index, templateData) {
    this.f(node.element.elements[node.element.elements.length - 1], templateData, node.filterData);
  }
  disposeTemplate(templateData) {
    templateData.templateDisposables.dispose();
  }
  /** @inheritdoc */
  f(element, templateData, _filterData) {
    const covered = !!element.hits;
    const icon2 = covered ? $s0b : $u0b.get(
      0
      /* TestResultState.Unset */
    );
    templateData.container.classList.toggle("not-covered", !covered);
    templateData.icon.className = `computed-state ${ThemeIcon.asClassName(icon2)}`;
    templateData.label.innerText = element.label;
    templateData.bars.setCoverageInfo(element.attributableCoverage());
  }
};
DeclarationCoverageRenderer = DeclarationCoverageRenderer_1 = __decorate([
  __param(0, $Pk)
], DeclarationCoverageRenderer);
var BasicRenderer = class _BasicRenderer {
  constructor() {
    this.templateId = _BasicRenderer.ID;
  }
  static {
    this.ID = "B";
  }
  renderCompressedElements(node, _index, container2) {
    this.d(node.element.elements[node.element.elements.length - 1], container2);
  }
  renderTemplate(container2) {
    return container2;
  }
  renderElement(node, index, container2) {
    this.d(node.element, container2);
  }
  disposeTemplate() {
  }
  d(element, container2) {
    container2.innerText = element.label;
  }
};
var TestCoverageIdentityProvider = class {
  getId(element) {
    return isFileCoverage(element) ? element.value.uri.toString() : element.id;
  }
};
$hJ(class TestCoverageChangePerTestFilterAction extends $gJ {
  constructor() {
    super({
      id: "testing.coverageFilterToTest",
      category: $qn.Test,
      title: localize2(11079, "Filter Coverage by Test"),
      icon: $6l.filter,
      toggled: {
        icon: $6l.filterFilled,
        condition: TestingContextKeys.isCoverageFilteredToTest
      },
      menu: [
        { id: $bJ.CommandPalette, when: TestingContextKeys.hasPerTestCoverage },
        {
          id: $bJ.ViewTitle,
          when: $7m.and(TestingContextKeys.hasPerTestCoverage, $7m.equals(
            "view",
            "workbench.view.testCoverage"
            /* Testing.CoverageViewId */
          )),
          group: "navigation"
        }
      ]
    });
  }
  run(accessor) {
    const coverageService = accessor.get($y9b);
    const quickInputService = accessor.get($1M);
    const coverage = coverageService.selected.get();
    if (!coverage) {
      return;
    }
    const tests = [...coverage.allPerTestIDs()].map($mQ.fromString);
    const commonPrefix = $mQ.getLengthOfCommonPrefix(tests.length, (i2) => tests[i2]);
    const result = coverage.result;
    const previousSelection = coverageService.filterToTest.get();
    const previousSelectionStr = previousSelection?.toString();
    const items = [
      { label: labels.allTests, id: void 0 },
      { type: "separator" },
      ...tests.map((testId) => ({ label: $G9b(result, testId, commonPrefix), testId }))
    ];
    quickInputService.pick(items, {
      activeItem: items.find((item) => "testId" in item && item.testId?.toString() === previousSelectionStr),
      placeHolder: labels.pickShowCoverage,
      onDidFocus: (entry) => {
        coverageService.filterToTest.set(entry.testId, void 0);
      }
    }).then((selected) => {
      coverageService.filterToTest.set(selected ? selected.testId : previousSelection, void 0);
    });
  }
});
$hJ(class TestCoverageChangeSortingAction extends $cpb {
  constructor() {
    super({
      id: "testing.coverageViewChangeSorting",
      viewId: "workbench.view.testCoverage",
      title: localize2(11080, "Change Sort Order"),
      icon: $6l.sortPrecedence,
      menu: {
        id: $bJ.ViewTitle,
        when: $7m.equals(
          "view",
          "workbench.view.testCoverage"
          /* Testing.CoverageViewId */
        ),
        group: "navigation"
      }
    });
  }
  runInView(accessor, view) {
    const disposables = new $2c();
    const quickInput = disposables.add(accessor.get($1M).createQuickPick());
    const items = [
      { label: localize(11072, null), value: 1, description: localize(11073, null) },
      { label: localize(11074, null), value: 0, description: localize(11075, null) },
      { label: localize(11076, null), value: 2, description: localize(11077, null) }
    ];
    quickInput.placeholder = localize(11078, null);
    quickInput.items = items;
    quickInput.show();
    disposables.add(quickInput.onDidHide(() => disposables.dispose()));
    disposables.add(quickInput.onDidAccept(() => {
      const picked = quickInput.selectedItems[0]?.value;
      if (picked !== void 0) {
        view.sortOrder.set(picked, void 0);
        quickInput.dispose();
      }
    }));
  }
});

// out-build/vs/workbench/contrib/testing/common/constants.js
var Testing;
(function(Testing2) {
  Testing2["ViewletId"] = "workbench.view.extension.test";
  Testing2["ExplorerViewId"] = "workbench.view.testing";
  Testing2["OutputPeekContributionId"] = "editor.contrib.testingOutputPeek";
  Testing2["DecorationsContributionId"] = "editor.contrib.testingDecorations";
  Testing2["CoverageDecorationsContributionId"] = "editor.contrib.coverageDecorations";
  Testing2["CoverageViewId"] = "workbench.view.testCoverage";
  Testing2["ResultsPanelId"] = "workbench.panel.testResults";
  Testing2["ResultsViewId"] = "workbench.panel.testResults.view";
  Testing2["MessageLanguageId"] = "vscodeInternalTestMessage";
})(Testing || (Testing = {}));
var TestExplorerViewMode;
(function(TestExplorerViewMode2) {
  TestExplorerViewMode2["List"] = "list";
  TestExplorerViewMode2["Tree"] = "true";
})(TestExplorerViewMode || (TestExplorerViewMode = {}));
var TestExplorerViewSorting;
(function(TestExplorerViewSorting2) {
  TestExplorerViewSorting2["ByLocation"] = "location";
  TestExplorerViewSorting2["ByStatus"] = "status";
  TestExplorerViewSorting2["ByDuration"] = "duration";
})(TestExplorerViewSorting || (TestExplorerViewSorting = {}));
var testStateNames = {
  [
    6
    /* TestResultState.Errored */
  ]: localize(11312, null),
  [
    4
    /* TestResultState.Failed */
  ]: localize(11313, null),
  [
    3
    /* TestResultState.Passed */
  ]: localize(11314, null),
  [
    1
    /* TestResultState.Queued */
  ]: localize(11315, null),
  [
    2
    /* TestResultState.Running */
  ]: localize(11316, null),
  [
    5
    /* TestResultState.Skipped */
  ]: localize(11317, null),
  [
    0
    /* TestResultState.Unset */
  ]: localize(11318, null)
};
var $uTb = (label3, state) => localize(11319, null, $0l(label3), testStateNames[state]);
var $vTb = {
  [
    4
    /* TestRunProfileBitset.Debug */
  ]: localize(11320, null),
  [
    2
    /* TestRunProfileBitset.Run */
  ]: localize(11321, null),
  [
    8
    /* TestRunProfileBitset.Coverage */
  ]: localize(11322, null)
};
var TestCommandId;
(function(TestCommandId2) {
  TestCommandId2["CancelTestRefreshAction"] = "testing.cancelTestRefresh";
  TestCommandId2["CancelTestRunAction"] = "testing.cancelRun";
  TestCommandId2["ClearTestResultsAction"] = "testing.clearTestResults";
  TestCommandId2["CollapseAllAction"] = "testing.collapseAll";
  TestCommandId2["ConfigureTestProfilesAction"] = "testing.configureProfile";
  TestCommandId2["ContinousRunUsingForTest"] = "testing.continuousRunUsingForTest";
  TestCommandId2["CoverageAtCursor"] = "testing.coverageAtCursor";
  TestCommandId2["CoverageByUri"] = "testing.coverage.uri";
  TestCommandId2["CoverageClear"] = "testing.coverage.close";
  TestCommandId2["CoverageCurrentFile"] = "testing.coverageCurrentFile";
  TestCommandId2["CoverageFilterToTest"] = "testing.coverageFilterToTest";
  TestCommandId2["CoverageFilterToTestInEditor"] = "testing.coverageFilterToTestInEditor";
  TestCommandId2["CoverageLastRun"] = "testing.coverageLastRun";
  TestCommandId2["CoverageSelectedAction"] = "testing.coverageSelected";
  TestCommandId2["CoverageToggleToolbar"] = "testing.coverageToggleToolbar";
  TestCommandId2["CoverageViewChangeSorting"] = "testing.coverageViewChangeSorting";
  TestCommandId2["DebugAction"] = "testing.debug";
  TestCommandId2["DebugAllAction"] = "testing.debugAll";
  TestCommandId2["DebugAtCursor"] = "testing.debugAtCursor";
  TestCommandId2["DebugByUri"] = "testing.debug.uri";
  TestCommandId2["DebugCurrentFile"] = "testing.debugCurrentFile";
  TestCommandId2["DebugFailedTests"] = "testing.debugFailTests";
  TestCommandId2["DebugLastRun"] = "testing.debugLastRun";
  TestCommandId2["DebugSelectedAction"] = "testing.debugSelected";
  TestCommandId2["FilterAction"] = "workbench.actions.treeView.testExplorer.filter";
  TestCommandId2["GetExplorerSelection"] = "_testing.getExplorerSelection";
  TestCommandId2["GetSelectedProfiles"] = "testing.getSelectedProfiles";
  TestCommandId2["GoToTest"] = "testing.editFocusedTest";
  TestCommandId2["GoToRelatedTest"] = "testing.goToRelatedTest";
  TestCommandId2["PeekRelatedTest"] = "testing.peekRelatedTest";
  TestCommandId2["GoToRelatedCode"] = "testing.goToRelatedCode";
  TestCommandId2["PeekRelatedCode"] = "testing.peekRelatedCode";
  TestCommandId2["HideTestAction"] = "testing.hideTest";
  TestCommandId2["OpenCoverage"] = "testing.openCoverage";
  TestCommandId2["OpenOutputPeek"] = "testing.openOutputPeek";
  TestCommandId2["RefreshTestsAction"] = "testing.refreshTests";
  TestCommandId2["ReRunFailedTests"] = "testing.reRunFailTests";
  TestCommandId2["ReRunLastRun"] = "testing.reRunLastRun";
  TestCommandId2["RunAction"] = "testing.run";
  TestCommandId2["RunAllAction"] = "testing.runAll";
  TestCommandId2["RunAllWithCoverageAction"] = "testing.coverageAll";
  TestCommandId2["RunAtCursor"] = "testing.runAtCursor";
  TestCommandId2["RunByUri"] = "testing.run.uri";
  TestCommandId2["RunCurrentFile"] = "testing.runCurrentFile";
  TestCommandId2["RunSelectedAction"] = "testing.runSelected";
  TestCommandId2["RunUsingProfileAction"] = "testing.runUsing";
  TestCommandId2["RunWithCoverageAction"] = "testing.coverage";
  TestCommandId2["SearchForTestExtension"] = "testing.searchForTestExtension";
  TestCommandId2["SelectDefaultTestProfiles"] = "testing.selectDefaultTestProfiles";
  TestCommandId2["ShowMostRecentOutputAction"] = "testing.showMostRecentOutput";
  TestCommandId2["StartContinousRun"] = "testing.startContinuousRun";
  TestCommandId2["StartContinousRunFromExtension"] = "testing.startContinuousRunFromExtension";
  TestCommandId2["StopContinousRunFromExtension"] = "testing.stopContinuousRunFromExtension";
  TestCommandId2["StopContinousRun"] = "testing.stopContinuousRun";
  TestCommandId2["TestingSortByDurationAction"] = "testing.sortByDuration";
  TestCommandId2["TestingSortByLocationAction"] = "testing.sortByLocation";
  TestCommandId2["TestingSortByStatusAction"] = "testing.sortByStatus";
  TestCommandId2["TestingViewAsListAction"] = "testing.viewAsList";
  TestCommandId2["TestingViewAsTreeAction"] = "testing.viewAsTree";
  TestCommandId2["ToggleContinousRunForTest"] = "testing.toggleContinuousRunForTest";
  TestCommandId2["ToggleInlineTestOutput"] = "testing.toggleInlineTestOutput";
  TestCommandId2["UnhideAllTestsAction"] = "testing.unhideAllTests";
  TestCommandId2["UnhideTestAction"] = "testing.unhideTest";
})(TestCommandId || (TestCommandId = {}));

// out-build/vs/workbench/contrib/testing/common/testingDecorations.js
var $z0b = class {
  constructor() {
    this.value = [];
  }
  /**
   * Adds a new value to the decorations.
   */
  push(value) {
    const searchIndex = $Bb(this.value, value, (a, b) => a.line - b.line);
    this.value.splice(searchIndex < 0 ? ~searchIndex : searchIndex, 0, value);
  }
  /**
   * Gets decorations on each line.
   */
  *lines() {
    if (!this.value.length) {
      return;
    }
    let startIndex = 0;
    let startLine = this.value[0].line;
    for (let i2 = 1; i2 < this.value.length; i2++) {
      const v = this.value[i2];
      if (v.line !== startLine) {
        yield [startLine, this.value.slice(startIndex, i2)];
        startLine = v.line;
        startIndex = i2;
      }
    }
    yield [startLine, this.value.slice(startIndex)];
  }
};
var $A0b = $Qk("testingDecorationService");

// out-build/vs/workbench/contrib/testing/common/testingPeekOpener.js
var $B0b = $Qk("testingPeekOpener");

// out-build/vs/workbench/contrib/testing/common/testingUri.js
var $C0b = "vscode-test-data";
var TestUriType;
(function(TestUriType2) {
  TestUriType2[TestUriType2["TaskOutput"] = 0] = "TaskOutput";
  TestUriType2[TestUriType2["TestOutput"] = 1] = "TestOutput";
  TestUriType2[TestUriType2["ResultMessage"] = 2] = "ResultMessage";
  TestUriType2[TestUriType2["ResultActualOutput"] = 3] = "ResultActualOutput";
  TestUriType2[TestUriType2["ResultExpectedOutput"] = 4] = "ResultExpectedOutput";
})(TestUriType || (TestUriType = {}));
var TestUriParts;
(function(TestUriParts2) {
  TestUriParts2["Results"] = "results";
  TestUriParts2["AllOutput"] = "output";
  TestUriParts2["Messages"] = "message";
  TestUriParts2["Text"] = "TestFailureMessage";
  TestUriParts2["ActualOutput"] = "ActualOutput";
  TestUriParts2["ExpectedOutput"] = "ExpectedOutput";
})(TestUriParts || (TestUriParts = {}));
var $D0b = (uri) => {
  const type = uri.authority;
  const [resultId, ...request] = uri.path.slice(1).split("/");
  if (request[0] === "message") {
    const taskIndex = Number(request[1]);
    const testExtId = uri.query;
    const index = Number(request[2]);
    const part = request[3];
    if (type === "results") {
      switch (part) {
        case "TestFailureMessage":
          return {
            resultId,
            taskIndex,
            testExtId,
            messageIndex: index,
            type: 2
            /* TestUriType.ResultMessage */
          };
        case "ActualOutput":
          return {
            resultId,
            taskIndex,
            testExtId,
            messageIndex: index,
            type: 3
            /* TestUriType.ResultActualOutput */
          };
        case "ExpectedOutput":
          return {
            resultId,
            taskIndex,
            testExtId,
            messageIndex: index,
            type: 4
            /* TestUriType.ResultExpectedOutput */
          };
        case "message":
      }
    }
  }
  if (request[0] === "output") {
    const testExtId = uri.query;
    const taskIndex = Number(request[1]);
    return testExtId ? {
      resultId,
      taskIndex,
      testExtId,
      type: 1
      /* TestUriType.TestOutput */
    } : {
      resultId,
      taskIndex,
      type: 0
      /* TestUriType.TaskOutput */
    };
  }
  return void 0;
};
var $E0b = (parsed) => {
  const uriParts = {
    scheme: $C0b,
    authority: "results"
    /* TestUriParts.Results */
  };
  if (parsed.type === 0) {
    return URI.from({
      ...uriParts,
      path: ["", parsed.resultId, "output", parsed.taskIndex].join("/")
    });
  }
  const msgRef = (resultId, ...remaining) => URI.from({
    ...uriParts,
    query: parsed.testExtId,
    path: ["", resultId, "message", ...remaining].join("/")
  });
  switch (parsed.type) {
    case 3:
      return msgRef(
        parsed.resultId,
        parsed.taskIndex,
        parsed.messageIndex,
        "ActualOutput"
        /* TestUriParts.ActualOutput */
      );
    case 4:
      return msgRef(
        parsed.resultId,
        parsed.taskIndex,
        parsed.messageIndex,
        "ExpectedOutput"
        /* TestUriParts.ExpectedOutput */
      );
    case 2:
      return msgRef(
        parsed.resultId,
        parsed.taskIndex,
        parsed.messageIndex,
        "TestFailureMessage"
        /* TestUriParts.Text */
      );
    case 1:
      return URI.from({
        ...uriParts,
        query: parsed.testExtId,
        path: ["", parsed.resultId, "output", parsed.taskIndex].join("/")
      });
    default:
      $hd(parsed, "Invalid test uri");
  }
};

// out-build/vs/workbench/contrib/testing/browser/explorerProjections/testItemContextOverlay.js
var $F0b = (test, capabilities) => {
  if (!test) {
    return [];
  }
  const testId = $mQ.fromString(test.item.extId);
  return [
    [TestingContextKeys.testItemExtId.key, testId.localId],
    [TestingContextKeys.controllerId.key, test.controllerId],
    [TestingContextKeys.testItemHasUri.key, !!test.item.uri],
    ...$yTb(capabilities)
  ];
};

// out-build/vs/workbench/contrib/testing/browser/testMessageColorizer.js
var colorAttrRe = /^\x1b\[([0-9]+)m$/;
var Classes;
(function(Classes2) {
  Classes2["Prefix"] = "tstm-ansidec-";
  Classes2["ForegroundPrefix"] = "tstm-ansidec-fg";
  Classes2["BackgroundPrefix"] = "tstm-ansidec-bg";
  Classes2["Bold"] = "tstm-ansidec-1";
  Classes2["Faint"] = "tstm-ansidec-2";
  Classes2["Italic"] = "tstm-ansidec-3";
  Classes2["Underline"] = "tstm-ansidec-4";
})(Classes || (Classes = {}));
var $G0b = (tm) => typeof tm === "string" ? $kg(tm) : $F1(tm);
var $H0b = (message, editor) => {
  const decos = [];
  editor.changeDecorations((changeAccessor) => {
    let start = new $8C(1, 1);
    let cls = [];
    for (const part of $jg(message)) {
      if (part.isCode) {
        const colorAttr = colorAttrRe.exec(part.str)?.[1];
        if (!colorAttr) {
          continue;
        }
        const n = Number(colorAttr);
        if (n === 0) {
          cls.length = 0;
        } else if (n === 22) {
          cls = cls.filter(
            (c) => c !== "tstm-ansidec-1" && c !== "tstm-ansidec-3"
            /* Classes.Italic */
          );
        } else if (n === 23) {
          cls = cls.filter(
            (c) => c !== "tstm-ansidec-3"
            /* Classes.Italic */
          );
        } else if (n === 24) {
          cls = cls.filter(
            (c) => c !== "tstm-ansidec-4"
            /* Classes.Underline */
          );
        } else if (n >= 30 && n <= 39 || n >= 90 && n <= 99) {
          cls = cls.filter((c) => !c.startsWith(
            "tstm-ansidec-fg"
            /* Classes.ForegroundPrefix */
          ));
          cls.push("tstm-ansidec-fg" + colorAttr);
        } else if (n >= 40 && n <= 49 || n >= 100 && n <= 109) {
          cls = cls.filter((c) => !c.startsWith(
            "tstm-ansidec-bg"
            /* Classes.BackgroundPrefix */
          ));
          cls.push("tstm-ansidec-bg" + colorAttr);
        } else {
          cls.push("tstm-ansidec-" + colorAttr);
        }
      } else {
        let line = start.lineNumber;
        let col = start.column;
        const graphemes = new $0f(part.str);
        for (let i2 = 0; !graphemes.eol(); i2 += graphemes.nextGraphemeLength()) {
          if (part.str[i2] === "\n") {
            line++;
            col = 1;
          } else {
            col++;
          }
        }
        const end = new $8C(line, col);
        if (cls.length) {
          decos.push(changeAccessor.addDecoration($9C.fromPositions(start, end), {
            inlineClassName: cls.join(" "),
            description: "test-message-colorized"
          }));
        }
        start = end;
      }
    }
  });
  return $1c(() => editor.removeDecorations(decos));
};

// out-build/vs/workbench/contrib/testing/browser/testResultsView/testResultsSubject.js
var $I0b = (test, message) => ({
  $mid: 18,
  test: InternalTestItem.serialize(test),
  message: ITestMessage.serialize(message)
});
var $J0b = (subject) => subject instanceof $K0b && !!subject.stack?.length;
var $K0b = class {
  get controllerId() {
    return $mQ.root(this.test.extId);
  }
  get isDiffable() {
    return this.message.type === 0 && ITestMessage.isDiffable(this.message);
  }
  get contextValue() {
    return this.message.type === 0 ? this.message.contextValue : void 0;
  }
  get stack() {
    return this.message.type === 0 && this.message.stackTrace?.length ? this.message.stackTrace : void 0;
  }
  constructor(result, test, taskIndex, messageIndex) {
    this.result = result;
    this.taskIndex = taskIndex;
    this.messageIndex = messageIndex;
    this.test = test.item;
    const messages = test.tasks[taskIndex].messages;
    this.messageIndex = messageIndex;
    const parts = { messageIndex, resultId: result.id, taskIndex, testExtId: test.item.extId };
    this.expectedUri = $E0b({
      ...parts,
      type: 4
      /* TestUriType.ResultExpectedOutput */
    });
    this.actualUri = $E0b({
      ...parts,
      type: 3
      /* TestUriType.ResultActualOutput */
    });
    this.messageUri = $E0b({
      ...parts,
      type: 2
      /* TestUriType.ResultMessage */
    });
    const message = this.message = messages[this.messageIndex];
    this.context = $I0b(test, message);
    this.revealLocation = message.location ?? (test.item.uri && test.item.range ? { uri: test.item.uri, range: $9C.lift(test.item.range) } : void 0);
  }
};
var $L0b = class {
  get controllerId() {
    return this.result.tasks[this.taskIndex].ctrlId;
  }
  constructor(result, taskIndex) {
    this.result = result;
    this.taskIndex = taskIndex;
    this.outputUri = $E0b({
      resultId: result.id,
      taskIndex,
      type: 0
      /* TestUriType.TaskOutput */
    });
  }
};
var $M0b = class {
  get controllerId() {
    return $mQ.root(this.test.item.extId);
  }
  constructor(result, taskIndex, test) {
    this.result = result;
    this.taskIndex = taskIndex;
    this.test = test;
    this.outputUri = $E0b({
      resultId: this.result.id,
      taskIndex: this.taskIndex,
      testExtId: this.test.item.extId,
      type: 1
      /* TestUriType.TestOutput */
    });
    this.task = result.tasks[this.taskIndex];
  }
};
var $N0b = (a, b) => a instanceof $K0b && b instanceof $K0b && a.message === b.message || a instanceof $L0b && b instanceof $L0b && a.result === b.result && a.taskIndex === b.taskIndex || a instanceof $M0b && b instanceof $M0b && a.test === b.test && a.taskIndex === b.taskIndex;
var $O0b = (test, fn) => {
  for (let taskIndex = 0; taskIndex < test.tasks.length; taskIndex++) {
    const task = test.tasks[taskIndex];
    for (let messageIndex = 0; messageIndex < task.messages.length; messageIndex++) {
      const r2 = fn(task, task.messages[messageIndex], messageIndex, taskIndex);
      if (r2 !== void 0) {
        return r2;
      }
    }
  }
  return void 0;
};
var $P0b = (subject) => {
  if (subject instanceof $K0b) {
    return subject.test;
  }
  if (subject instanceof $L0b) {
    return void 0;
  }
  return subject.test.item;
};

// out-build/vs/workbench/contrib/testing/common/observableValue.js
var $kTb = (value) => ({
  onDidChange: Event2.None,
  value
});
var $lTb = class _$lTb extends $3c {
  get value() {
    return this.b;
  }
  set value(v) {
    if (v !== this.b) {
      this.b = v;
      this.a.fire(v);
    }
  }
  static stored(stored, defaultValue) {
    const o = new _$lTb(stored.get(defaultValue));
    o.B(stored);
    o.B(o.onDidChange((value) => stored.store(value)));
    return o;
  }
  constructor(b) {
    super();
    this.b = b;
    this.a = this.B(new $ze());
    this.onDidChange = this.a.event;
  }
};

// out-build/vs/workbench/contrib/debug/browser/callStackWidget.js
var FrameCodeRenderer_1;
var MissingCodeRenderer_1;
var SkippedRenderer_1;
var $Q0b = class {
  constructor(name, source, line = 1, column = 1) {
    this.name = name;
    this.source = source;
    this.line = line;
    this.column = column;
  }
};
var $R0b = class {
  constructor(label3, load) {
    this.label = label3;
    this.load = load;
  }
};
var $S0b = class {
  constructor() {
    this.showHeader = $he("CustomStackFrame.showHeader", true);
  }
};
var WrappedCallStackFrame = class extends $Q0b {
  constructor(original) {
    super(original.name, original.source, original.line, original.column);
    this.editorHeight = $he("WrappedCallStackFrame.height", this.source ? 100 : 0);
    this.collapsed = $he("WrappedCallStackFrame.collapsed", false);
    this.height = $2d((reader) => {
      return this.collapsed.read(reader) ? $U0b : $U0b + this.editorHeight.read(reader);
    });
  }
};
var WrappedCustomStackFrame = class {
  constructor(original) {
    this.original = original;
    this.collapsed = $he("WrappedCallStackFrame.collapsed", false);
    this.height = $2d((reader) => {
      const headerHeight = this.original.showHeader.read(reader) ? $U0b : 0;
      return this.collapsed.read(reader) ? headerHeight : headerHeight + this.original.height.read(reader);
    });
  }
};
var isFrameLike = (item) => item instanceof WrappedCallStackFrame || item instanceof WrappedCustomStackFrame;
var WIDGET_CLASS_NAME = "multiCallStackWidget";
var $T0b = class $T0b2 extends $3c {
  get onDidScroll() {
    return this.a.onDidScroll;
  }
  constructor(container2, containingEditor, instantiationService) {
    super();
    this.b = this.B(new $ze());
    this.c = this.B(new $2c());
    container2.classList.add(WIDGET_CLASS_NAME);
    this.B($1c(() => container2.classList.remove(WIDGET_CLASS_NAME)));
    this.a = this.B(instantiationService.createInstance($Web, "TestResultStackWidget", container2, new StackDelegate(), [
      instantiationService.createInstance(FrameCodeRenderer, containingEditor, this.b.event),
      instantiationService.createInstance(MissingCodeRenderer),
      instantiationService.createInstance(CustomRenderer),
      instantiationService.createInstance(SkippedRenderer, (i2) => this.g(i2))
    ], {
      multipleSelectionSupport: false,
      mouseSupport: false,
      keyboardSupport: false,
      setRowLineHeight: false,
      alwaysConsumeMouseWheel: false,
      accessibilityProvider: instantiationService.createInstance(StackAccessibilityProvider)
    }));
  }
  /** Replaces the call frames display in the view. */
  setFrames(frames) {
    this.c.clear();
    this.f = new $ad();
    this.B($1c(() => this.f.dispose(true)));
    this.a.splice(0, this.a.length, this.j(frames));
  }
  layout(height, width2) {
    this.a.layout(height, width2);
    this.b.fire();
  }
  collapseAll() {
    $ce((tx) => {
      for (let i2 = 0; i2 < this.a.length; i2++) {
        const frame = this.a.element(i2);
        if (isFrameLike(frame)) {
          frame.collapsed.set(true, tx);
        }
      }
    });
  }
  async g(replacing) {
    if (!this.f) {
      return;
    }
    const frames = await replacing.load(this.f.token);
    if (this.f.token.isCancellationRequested) {
      return;
    }
    const index = this.a.indexOf(replacing);
    this.a.splice(index, 1, this.j(frames));
  }
  j(frames) {
    const result = [];
    for (const frame of frames) {
      if (frame instanceof $R0b) {
        result.push(frame);
        continue;
      }
      const wrapped = frame instanceof $S0b ? new WrappedCustomStackFrame(frame) : new WrappedCallStackFrame(frame);
      result.push(wrapped);
      this.c.add($td((reader) => {
        const height = wrapped.height.read(reader);
        const idx = this.a.indexOf(wrapped);
        if (idx !== -1) {
          this.a.updateElementHeight(idx, height);
        }
      }));
    }
    return result;
  }
};
$T0b = __decorate([
  __param(2, $Pk)
], $T0b);
var StackAccessibilityProvider = class StackAccessibilityProvider2 {
  constructor(a) {
    this.a = a;
  }
  getAriaLabel(e) {
    if (e instanceof $R0b) {
      return e.label;
    }
    if (e instanceof WrappedCustomStackFrame) {
      return e.original.label;
    }
    if (e instanceof $Q0b) {
      if (e.source && e.line) {
        return localize(5619, null, e.name, e.line, this.a.getUriLabel(e.source, { relative: true }));
      }
      return e.name;
    }
    $hd(e);
  }
  getWidgetAriaLabel() {
    return localize(5620, null);
  }
};
StackAccessibilityProvider = __decorate([
  __param(0, $ZI)
], StackAccessibilityProvider);
var StackDelegate = class {
  getHeight(element) {
    if (element instanceof $Q0b || element instanceof WrappedCustomStackFrame) {
      return element.height.get();
    }
    if (element instanceof $R0b) {
      return $U0b;
    }
    $hd(element);
  }
  getTemplateId(element) {
    if (element instanceof $Q0b) {
      return element.source ? FrameCodeRenderer.templateId : MissingCodeRenderer.templateId;
    }
    if (element instanceof $R0b) {
      return SkippedRenderer.templateId;
    }
    if (element instanceof WrappedCustomStackFrame) {
      return CustomRenderer.templateId;
    }
    $hd(element);
  }
};
var editorOptions = {
  scrollBeyondLastLine: false,
  scrollbar: {
    vertical: "hidden",
    horizontal: "hidden",
    handleMouseWheel: false,
    useShadows: false
  },
  overviewRulerLanes: 0,
  fixedOverflowWidgets: true,
  overviewRulerBorder: false,
  stickyScroll: { enabled: false },
  minimap: { enabled: false },
  readOnly: true,
  automaticLayout: false
};
var makeFrameElements = () => h("div.multiCallStackFrame", [
  h("div.header@header", [
    h("div.collapse-button@collapseButton"),
    h("div.title.show-file-icons@title"),
    h("div.actions@actions")
  ]),
  h("div.editorParent", [
    h("div.editorContainer@editor")
  ])
]);
var $U0b = 24;
var AbstractFrameRenderer = class AbstractFrameRenderer2 {
  constructor(a) {
    this.a = a;
  }
  renderTemplate(container2) {
    const elements = makeFrameElements();
    container2.appendChild(elements.root);
    const templateStore = new $2c();
    container2.classList.add("multiCallStackFrameContainer");
    templateStore.add($1c(() => {
      container2.classList.remove("multiCallStackFrameContainer");
      elements.root.remove();
    }));
    const label3 = templateStore.add(this.a.createInstance($msb, elements.title, {}));
    const collapse = templateStore.add(new $k2(elements.collapseButton, {}));
    const contentId = $ps();
    elements.editor.id = contentId;
    elements.editor.role = "region";
    elements.collapseButton.setAttribute("aria-controls", contentId);
    return this.b({
      container: container2,
      decorations: [],
      elements,
      label: label3,
      collapse,
      elementStore: templateStore.add(new $2c()),
      templateStore
    });
  }
  renderElement(element, index, template, height) {
    const { elementStore } = template;
    elementStore.clear();
    const item = element;
    this.c(item, template);
  }
  c(item, { elementStore, elements, collapse }) {
    elementStore.add($td((reader) => {
      collapse.element.className = "";
      const collapsed2 = item.collapsed.read(reader);
      collapse.icon = collapsed2 ? $6l.chevronRight : $6l.chevronDown;
      collapse.element.ariaExpanded = String(!collapsed2);
      elements.root.classList.toggle("collapsed", collapsed2);
    }));
    const toggleCollapse = () => item.collapsed.set(!item.collapsed.get(), void 0);
    elementStore.add(collapse.onDidClick(toggleCollapse));
    elementStore.add($_i(elements.title, "click", toggleCollapse));
  }
  disposeElement(element, index, templateData, height) {
    templateData.elementStore.clear();
  }
  disposeTemplate(templateData) {
    templateData.templateStore.dispose();
  }
};
AbstractFrameRenderer = __decorate([
  __param(0, $Pk)
], AbstractFrameRenderer);
var CONTEXT_LINES = 2;
var FrameCodeRenderer = class FrameCodeRenderer2 extends AbstractFrameRenderer {
  static {
    FrameCodeRenderer_1 = this;
  }
  static {
    this.templateId = "f";
  }
  constructor(f, g, j, instantiationService) {
    super(instantiationService);
    this.f = f;
    this.g = g;
    this.j = j;
    this.templateId = FrameCodeRenderer_1.templateId;
  }
  b(data) {
    const contributions = [{
      id: ClickToLocationContribution.ID,
      instantiation: 2,
      ctor: ClickToLocationContribution
    }];
    const editor = this.f ? this.a.createInstance($bdb, data.elements.editor, editorOptions, { isSimpleWidget: true, contributions }, this.f) : this.a.createInstance($D9, data.elements.editor, editorOptions, { isSimpleWidget: true, contributions });
    data.templateStore.add(editor);
    const toolbar = data.templateStore.add(this.a.createInstance($4$, data.elements.actions, $bJ.DebugCallStackToolbar, {
      menuOptions: { shouldForwardArgs: true },
      actionViewItemProvider: (action, options3) => $X$(this.a, action, options3)
    }));
    return { ...data, editor, toolbar };
  }
  renderElement(element, index, template, height) {
    super.renderElement(element, index, template, height);
    const { elementStore, editor } = template;
    const item = element;
    const uri = item.source;
    template.label.element.setFile(uri);
    const cts = new $ad();
    elementStore.add($1c(() => cts.dispose(true)));
    this.j.createModelReference(uri).then((reference) => {
      if (cts.token.isCancellationRequested) {
        return reference.dispose();
      }
      elementStore.add(reference);
      editor.setModel(reference.object.textEditorModel);
      this.m(item, template);
      this.l(item, template);
    });
  }
  l(item, { elementStore, container: container2, editor }) {
    const layout = () => {
      const prev = editor.getContentHeight();
      editor.layout({ width: container2.clientWidth, height: prev });
      const next = editor.getContentHeight();
      if (next !== prev) {
        editor.layout({ width: container2.clientWidth, height: next });
      }
      item.editorHeight.set(next, void 0);
    };
    elementStore.add(editor.onDidChangeModelDecorations(layout));
    elementStore.add(editor.onDidChangeModelContent(layout));
    elementStore.add(editor.onDidChangeModelOptions(layout));
    elementStore.add(this.g(layout));
    layout();
  }
  m(item, template) {
    const range = $9C.fromPositions({
      column: item.column ?? 1,
      lineNumber: item.line ?? 1
    });
    template.toolbar.context = { uri: item.source, range };
    template.editor.setHiddenAreas([
      $9C.fromPositions({ column: 1, lineNumber: 1 }, { column: 1, lineNumber: Math.max(1, item.line - CONTEXT_LINES - 1) }),
      $9C.fromPositions({ column: 1, lineNumber: item.line + CONTEXT_LINES + 1 }, {
        column: 1,
        lineNumber: 1073741824
        /* Constants.MAX_SAFE_SMALL_INTEGER */
      })
    ]);
    template.editor.changeDecorations((accessor) => {
      for (const d of template.decorations) {
        accessor.removeDecoration(d);
      }
      template.decorations.length = 0;
      const beforeRange = range.setStartPosition(range.startLineNumber, 1);
      const hasCharactersBefore = !!template.editor.getModel()?.getValueInRange(beforeRange).trim();
      const decoRange = range.setEndPosition(
        range.startLineNumber,
        1073741824
        /* Constants.MAX_SAFE_SMALL_INTEGER */
      );
      template.decorations.push(accessor.addDecoration(decoRange, $O3b(!hasCharactersBefore)));
      template.decorations.push(accessor.addDecoration(decoRange, $M3b));
    });
    item.editorHeight.set(template.editor.getContentHeight(), void 0);
  }
};
FrameCodeRenderer = FrameCodeRenderer_1 = __decorate([
  __param(2, $oG),
  __param(3, $Pk)
], FrameCodeRenderer);
var MissingCodeRenderer = class MissingCodeRenderer2 {
  static {
    MissingCodeRenderer_1 = this;
  }
  static {
    this.templateId = "m";
  }
  constructor(a) {
    this.a = a;
    this.templateId = MissingCodeRenderer_1.templateId;
  }
  renderTemplate(container2) {
    const elements = makeFrameElements();
    elements.root.classList.add("missing");
    container2.appendChild(elements.root);
    const label3 = this.a.createInstance($msb, elements.title, {});
    return { elements, label: label3 };
  }
  renderElement(element, _index, templateData) {
    const cast = element;
    templateData.label.element.setResource({
      name: cast.name,
      description: localize(5621, null, cast.line, cast.column),
      range: { startLineNumber: cast.line, startColumn: cast.column, endColumn: cast.column, endLineNumber: cast.line }
    }, {
      icon: $6l.fileBinary
    });
  }
  disposeTemplate(templateData) {
    templateData.label.dispose();
    templateData.elements.root.remove();
  }
};
MissingCodeRenderer = MissingCodeRenderer_1 = __decorate([
  __param(0, $Pk)
], MissingCodeRenderer);
var CustomRenderer = class _CustomRenderer extends AbstractFrameRenderer {
  constructor() {
    super(...arguments);
    this.templateId = _CustomRenderer.templateId;
  }
  static {
    this.templateId = "c";
  }
  b(data) {
    return data;
  }
  renderElement(element, index, template, height) {
    super.renderElement(element, index, template, height);
    const item = element;
    const { elementStore, container: container2, label: label3 } = template;
    label3.element.setResource({ name: item.original.label }, { icon: item.original.icon });
    elementStore.add($td((reader) => {
      template.elements.header.style.display = item.original.showHeader.read(reader) ? "" : "none";
    }));
    elementStore.add($xd((reader, store) => {
      if (!item.collapsed.read(reader)) {
        store.add(item.original.render(container2));
      }
    }));
    const actions = item.original.renderActions?.(template.elements.actions);
    if (actions) {
      elementStore.add(actions);
    }
  }
};
var SkippedRenderer = class SkippedRenderer2 {
  static {
    SkippedRenderer_1 = this;
  }
  static {
    this.templateId = "s";
  }
  constructor(a, b) {
    this.a = a;
    this.b = b;
    this.templateId = SkippedRenderer_1.templateId;
  }
  renderTemplate(container2) {
    const store = new $2c();
    const button = new $k2(container2, { title: "", ...$q$ });
    const data = { button, store };
    store.add(button);
    store.add(button.onDidClick(() => {
      if (!data.current || !button.enabled) {
        return;
      }
      button.enabled = false;
      this.a(data.current).catch((e) => {
        this.b.error(localize(5622, null, e.message));
      });
    }));
    return data;
  }
  renderElement(element, index, templateData, height) {
    const cast = element;
    templateData.button.enabled = true;
    templateData.button.label = cast.label;
    templateData.current = cast;
  }
  disposeTemplate(templateData) {
    templateData.store.dispose();
  }
};
SkippedRenderer = SkippedRenderer_1 = __decorate([
  __param(1, $PJ)
], SkippedRenderer);
var ClickToLocationContribution = class ClickToLocationContribution2 extends $3c {
  static {
    this.ID = "clickToLocation";
  }
  constructor(c, editorService) {
    super();
    this.c = c;
    this.a = c.createDecorationsCollection();
    this.B($1c(() => this.a.clear()));
    const clickLinkGesture = this.B(new $6db(c));
    this.B(clickLinkGesture.onMouseMoveOrRelevantKeyDown(([mouseEvent, keyboardEvent]) => {
      this.f(mouseEvent);
    }));
    this.B(clickLinkGesture.onExecute((e) => {
      const model = this.c.getModel();
      if (!this.b || !model) {
        return;
      }
      editorService.openEditor({
        resource: model.uri,
        options: {
          selection: $9C.fromPositions(new $8C(this.b.line, this.b.word.startColumn)),
          selectionRevealType: 1
        }
      }, e.hasSideBySideModifier ? $oJ : void 0);
    }));
  }
  f(mouseEvent) {
    if (!mouseEvent.hasTriggerModifier) {
      return this.g();
    }
    const position = mouseEvent.target.position;
    const word = position && this.c.getModel()?.getWordAtPosition(position);
    if (!word) {
      return this.g();
    }
    const prev = this.b?.word;
    if (prev && prev.startColumn === word.startColumn && prev.endColumn === word.endColumn && prev.word === word.word) {
      return;
    }
    this.b = { word, line: position.lineNumber };
    this.a.set([{
      range: new $9C(position.lineNumber, word.startColumn, position.lineNumber, word.endColumn),
      options: {
        description: "call-stack-go-to-file-link",
        inlineClassName: "call-stack-go-to-file-link"
      }
    }]);
  }
  g() {
    this.a.clear();
    this.b = void 0;
  }
};
ClickToLocationContribution = __decorate([
  __param(1, $mJ)
], ClickToLocationContribution);
$hJ(class extends $gJ {
  constructor() {
    super({
      id: "callStackWidget.goToFile",
      title: localize2(5623, "Open File"),
      icon: $6l.goToFile,
      menu: {
        id: $bJ.DebugCallStackToolbar,
        order: 22,
        group: "navigation"
      }
    });
  }
  async run(accessor, { uri, range }) {
    const editorService = accessor.get($mJ);
    await editorService.openEditor({
      resource: uri,
      options: {
        selection: range,
        selectionRevealType: 1
      }
    });
  }
});

// out-build/vs/workbench/contrib/testing/browser/testResultsView/testMessageStack.js
var $V0b = class $V0b2 extends $3c {
  get onDidScroll() {
    return this.a.onDidScroll;
  }
  constructor(b, containingEditor, instantiationService) {
    super();
    this.b = b;
    this.a = this.B(instantiationService.createInstance($T0b, b, containingEditor));
  }
  collapseAll() {
    this.a.collapseAll();
  }
  update(messageFrame, stack) {
    this.a.setFrames([messageFrame, ...stack.map((frame) => new $Q0b(frame.label, frame.uri, frame.position?.lineNumber, frame.position?.column))]);
  }
  layout(height, width2) {
    this.a.layout(height ?? this.b.clientHeight, width2);
  }
};
$V0b = __decorate([
  __param(2, $Pk)
], $V0b);

// out-build/vs/platform/terminal/common/capabilities/terminalCapabilityStore.js
var $zPb = class extends $3c {
  constructor() {
    super(...arguments);
    this.a = /* @__PURE__ */ new Map();
    this.b = this.B(new $ze());
    this.onDidRemoveCapabilityType = this.b.event;
    this.f = this.B(new $ze());
    this.onDidAddCapabilityType = this.f.event;
    this.g = this.B(new $ze());
    this.onDidRemoveCapability = this.g.event;
    this.h = this.B(new $ze());
    this.onDidAddCapability = this.h.event;
  }
  get items() {
    return this.a.keys();
  }
  add(capability, impl) {
    this.a.set(capability, impl);
    this.f.fire(capability);
    this.h.fire({ id: capability, capability: impl });
  }
  get(capability) {
    return this.a.get(capability);
  }
  remove(capability) {
    const impl = this.a.get(capability);
    if (!impl) {
      return;
    }
    this.a.delete(capability);
    this.b.fire(capability);
    this.h.fire({ id: capability, capability: impl });
  }
  has(capability) {
    return this.a.has(capability);
  }
};
var $APb = class extends $3c {
  constructor() {
    super(...arguments);
    this._stores = [];
    this.a = this.B(new $ze());
    this.onDidRemoveCapabilityType = this.a.event;
    this.b = this.B(new $ze());
    this.onDidAddCapabilityType = this.b.event;
    this.f = this.B(new $ze());
    this.onDidRemoveCapability = this.f.event;
    this.g = this.B(new $ze());
    this.onDidAddCapability = this.g.event;
  }
  get items() {
    return this.h();
  }
  *h() {
    for (const store of this._stores) {
      for (const c of store.items) {
        yield c;
      }
    }
  }
  has(capability) {
    for (const store of this._stores) {
      for (const c of store.items) {
        if (c === capability) {
          return true;
        }
      }
    }
    return false;
  }
  get(capability) {
    for (const store of this._stores) {
      const c = store.get(capability);
      if (c) {
        return c;
      }
    }
    return void 0;
  }
  add(store) {
    this._stores.push(store);
    for (const capability of store.items) {
      this.b.fire(capability);
      this.g.fire({ id: capability, capability: store.get(capability) });
    }
    this.B(store.onDidAddCapabilityType((e) => this.b.fire(e)));
    this.B(store.onDidAddCapability((e) => this.g.fire(e)));
    this.B(store.onDidRemoveCapabilityType((e) => this.a.fire(e)));
    this.B(store.onDidRemoveCapability((e) => this.f.fire(e)));
  }
};

// out-build/vs/platform/terminal/common/terminalStrings.js
function $W0b(message, options3 = {}) {
  let result = "";
  if (!options3.excludeLeadingNewLine) {
    result += "\r\n";
  }
  result += "\x1B[0m\x1B[7m * ";
  if (options3.loudFormatting) {
    result += "\x1B[0;104m";
  } else {
    result += "\x1B[0m";
  }
  result += ` ${message} \x1B[0m
\r`;
  return result;
}

// out-build/vs/workbench/contrib/terminal/browser/terminalExtensions.js
function $Y0b(id2, ctor, canRunInDetachedTerminals = false) {
  TerminalContributionRegistry.INSTANCE.registerTerminalContribution({ id: id2, ctor, canRunInDetachedTerminals });
}
var TerminalExtensionsRegistry;
(function(TerminalExtensionsRegistry2) {
  function getTerminalContributions() {
    return TerminalContributionRegistry.INSTANCE.getTerminalContributions();
  }
  TerminalExtensionsRegistry2.getTerminalContributions = getTerminalContributions;
})(TerminalExtensionsRegistry || (TerminalExtensionsRegistry = {}));
var TerminalContributionRegistry = class _TerminalContributionRegistry {
  static {
    this.INSTANCE = new _TerminalContributionRegistry();
  }
  constructor() {
    this.a = [];
  }
  registerTerminalContribution(description) {
    this.a.push(description);
  }
  getTerminalContributions() {
    return this.a.slice(0);
  }
};
var Extensions6;
(function(Extensions9) {
  Extensions9["TerminalContributions"] = "terminal.contributions";
})(Extensions6 || (Extensions6 = {}));
$Wn.add("terminal.contributions", TerminalContributionRegistry.INSTANCE);

// out-build/vs/workbench/contrib/terminal/browser/widgets/widgetManager.js
var $X0b = class {
  constructor() {
    this.b = /* @__PURE__ */ new Map();
  }
  attachToElement(terminalWrapper) {
    if (!this.a) {
      this.a = document.createElement("div");
      this.a.classList.add("terminal-widget-container");
      terminalWrapper.appendChild(this.a);
    }
  }
  dispose() {
    if (this.a) {
      this.a.remove();
      this.a = void 0;
    }
  }
  attachWidget(widget) {
    if (!this.a) {
      return;
    }
    this.b.get(widget.id)?.dispose();
    widget.attach(this.a);
    this.b.set(widget.id, widget);
    return {
      dispose: () => {
        const current = this.b.get(widget.id);
        if (current === widget) {
          this.b.delete(widget.id);
          widget.dispose();
        }
      }
    };
  }
};

// out-build/vs/workbench/contrib/terminal/browser/detachedTerminal.js
var $Z0b = class $Z0b2 extends $3c {
  get xterm() {
    return this.c;
  }
  constructor(c, options3, instantiationService) {
    super();
    this.c = c;
    this.a = this.B(new $X0b());
    this.capabilities = new $zPb();
    this.b = /* @__PURE__ */ new Map();
    this.B(c);
    const contributionDescs = TerminalExtensionsRegistry.getTerminalContributions();
    for (const desc of contributionDescs) {
      if (this.b.has(desc.id)) {
        $gb(new Error(`Cannot have two terminal contributions with the same id ${desc.id}`));
        continue;
      }
      if (desc.canRunInDetachedTerminals === false) {
        continue;
      }
      let contribution;
      try {
        contribution = instantiationService.createInstance(desc.ctor, {
          instance: this,
          processManager: options3.processInfo,
          widgetManager: this.a
        });
        this.b.set(desc.id, contribution);
        this.B(contribution);
      } catch (err) {
        $gb(err);
      }
    }
    this.B(new $Sh($ue)).trigger(() => {
      for (const contr of this.b.values()) {
        contr.xtermReady?.(this.c);
      }
    });
  }
  get selection() {
    return this.c && this.hasSelection() ? this.c.raw.getSelection() : void 0;
  }
  hasSelection() {
    return this.c.hasSelection();
  }
  clearSelection() {
    this.c.clearSelection();
  }
  focus(force) {
    if (force || !$Qj().getSelection()?.toString()) {
      this.xterm.focus();
    }
  }
  attachToElement(container2, options3) {
    this.domElement = container2;
    const screenElement = this.c.attachToElement(container2, options3);
    this.a.attachToElement(screenElement);
  }
  forceScrollbarVisibility() {
    this.domElement?.classList.add("force-scrollbar");
  }
  resetScrollbarVisibility() {
    this.domElement?.classList.remove("force-scrollbar");
  }
  getContribution(id2) {
    return this.b.get(id2);
  }
};
$Z0b = __decorate([
  __param(2, $Pk)
], $Z0b);
var $10b = class {
  constructor(initialValues) {
    this.processState = 3;
    this.ptyProcessReady = Promise.resolve();
    this.initialCwd = "";
    this.shouldPersist = false;
    this.hasWrittenData = false;
    this.hasChildProcesses = false;
    this.capabilities = new $zPb();
    this.shellIntegrationNonce = "";
    Object.assign(this, initialValues);
  }
};

// out-build/vs/workbench/contrib/terminal/browser/xterm/markNavigationAddon.js
var Boundary;
(function(Boundary2) {
  Boundary2[Boundary2["Top"] = 0] = "Top";
  Boundary2[Boundary2["Bottom"] = 1] = "Bottom";
})(Boundary || (Boundary = {}));
var ScrollPosition;
(function(ScrollPosition2) {
  ScrollPosition2[ScrollPosition2["Top"] = 0] = "Top";
  ScrollPosition2[ScrollPosition2["Middle"] = 1] = "Middle";
})(ScrollPosition || (ScrollPosition = {}));
var $wPb = class $wPb2 extends $3c {
  activate(terminal2) {
    this.f = terminal2;
    this.B(this.f.onData(() => {
      this.a = Boundary.Bottom;
    }));
  }
  constructor(m, n, r2) {
    super();
    this.m = m;
    this.n = n;
    this.r = r2;
    this.a = Boundary.Bottom;
    this.b = null;
    this.c = false;
    this.j = this.B(new $4c());
  }
  s(skipEmptyCommands) {
    const commandCapability = this.m.get(
      2
      /* TerminalCapability.CommandDetection */
    );
    const partialCommandCapability = this.m.get(
      3
      /* TerminalCapability.PartialCommandDetection */
    );
    const markCapability = this.m.get(
      4
      /* TerminalCapability.BufferMarkDetection */
    );
    let markers = [];
    if (commandCapability) {
      markers = $Mb(commandCapability.commands.filter((e) => skipEmptyCommands ? e.exitCode !== void 0 : true).map((e) => e.promptStartMarker ?? e.marker));
      if (commandCapability.currentCommand?.promptStartMarker && commandCapability.currentCommand.commandExecutedMarker) {
        markers.push(commandCapability.currentCommand?.promptStartMarker);
      }
    } else if (partialCommandCapability) {
      markers.push(...partialCommandCapability.commands);
    }
    if (markCapability && !skipEmptyCommands) {
      let next = markCapability.markers().next()?.value;
      const arr = [];
      while (next) {
        arr.push(next);
        next = markCapability.markers().next()?.value;
      }
      markers = arr;
    }
    return markers;
  }
  t(marker) {
    const commandCapability = this.m.get(
      2
      /* TerminalCapability.CommandDetection */
    );
    if (commandCapability) {
      const command4 = commandCapability.commands.find((e) => e.marker?.line === marker.line || e.promptStartMarker?.line === marker.line);
      if (command4) {
        return command4;
      }
      if (commandCapability.currentCommand) {
        return commandCapability.currentCommand;
      }
    }
    return void 0;
  }
  clear() {
    this.a = Boundary.Bottom;
    this.u();
    this.b = null;
  }
  u() {
    if (this.g) {
      $Xc(this.g);
    }
    this.g = [];
  }
  w(marker) {
    if (marker === Boundary.Bottom) {
      return true;
    }
    if (marker === Boundary.Top) {
      return !this.s(true).map((e) => e.line).includes(0);
    }
    return !this.s(true).includes(marker);
  }
  scrollToPreviousMark(scrollPosition = 1, retainSelection = false, skipEmptyCommands = true) {
    if (!this.f) {
      return;
    }
    if (!retainSelection) {
      this.b = null;
    }
    let markerIndex;
    const currentLineY = typeof this.a === "object" ? this.getTargetScrollLine(this.a.line, scrollPosition) : Math.min($xPb(this.f, this.a), this.f.buffer.active.baseY);
    const viewportY = this.f.buffer.active.viewportY;
    if (typeof this.a === "object" ? !this.H(this.f, this.a) : currentLineY !== viewportY) {
      const markersBelowViewport = this.s(skipEmptyCommands).filter((e) => e.line >= viewportY).length;
      markerIndex = this.s(skipEmptyCommands).length - markersBelowViewport - 1;
    } else if (this.a === Boundary.Bottom) {
      markerIndex = this.s(skipEmptyCommands).length - 1;
    } else if (this.a === Boundary.Top) {
      markerIndex = -1;
    } else if (this.c) {
      markerIndex = this.L(skipEmptyCommands);
      this.a.dispose();
      this.c = false;
    } else {
      if (skipEmptyCommands && this.w(this.a)) {
        markerIndex = this.L(true);
      } else {
        markerIndex = this.s(skipEmptyCommands).indexOf(this.a) - 1;
      }
    }
    if (markerIndex < 0) {
      this.a = Boundary.Top;
      this.f.scrollToTop();
      this.u();
      return;
    }
    this.a = this.s(skipEmptyCommands)[markerIndex];
    this.z(this.a, scrollPosition);
  }
  scrollToNextMark(scrollPosition = 1, retainSelection = false, skipEmptyCommands = true) {
    if (!this.f) {
      return;
    }
    if (!retainSelection) {
      this.b = null;
    }
    let markerIndex;
    const currentLineY = typeof this.a === "object" ? this.getTargetScrollLine(this.a.line, scrollPosition) : Math.min($xPb(this.f, this.a), this.f.buffer.active.baseY);
    const viewportY = this.f.buffer.active.viewportY;
    if (typeof this.a === "object" ? !this.H(this.f, this.a) : currentLineY !== viewportY) {
      const markersAboveViewport = this.s(skipEmptyCommands).filter((e) => e.line <= viewportY).length;
      markerIndex = markersAboveViewport;
    } else if (this.a === Boundary.Bottom) {
      markerIndex = this.s(skipEmptyCommands).length;
    } else if (this.a === Boundary.Top) {
      markerIndex = 0;
    } else if (this.c) {
      markerIndex = this.M(skipEmptyCommands);
      this.a.dispose();
      this.c = false;
    } else {
      if (skipEmptyCommands && this.w(this.a)) {
        markerIndex = this.M(true);
      } else {
        markerIndex = this.s(skipEmptyCommands).indexOf(this.a) + 1;
      }
    }
    if (markerIndex >= this.s(skipEmptyCommands).length) {
      this.a = Boundary.Bottom;
      this.f.scrollToBottom();
      this.u();
      return;
    }
    this.a = this.s(skipEmptyCommands)[markerIndex];
    this.z(this.a, scrollPosition);
  }
  z(marker, position) {
    const command4 = this.t(marker);
    if (command4) {
      this.revealCommand(command4, position);
    } else {
      this.C(marker, position);
    }
  }
  C(start, position, end, options3) {
    if (!this.f) {
      return;
    }
    if (!this.H(this.f, start) || options3?.forceScroll) {
      const line = this.getTargetScrollLine(toLineIndex(start), position);
      this.f.scrollToLine(line);
    }
    if (!options3?.hideDecoration) {
      if (options3?.bufferRange) {
        this.G(options3.bufferRange);
      } else {
        this.registerTemporaryDecoration(start, end, true);
      }
    }
  }
  D(marker, offset) {
    if (offset === 0 && isMarker(marker)) {
      return marker;
    } else {
      const offsetMarker = this.f?.registerMarker(-this.f.buffer.active.cursorY + toLineIndex(marker) - this.f.buffer.active.baseY + offset);
      if (offsetMarker) {
        return offsetMarker;
      } else {
        throw new Error(`Could not register marker with offset ${toLineIndex(marker)}, ${offset}`);
      }
    }
  }
  revealCommand(command4, position = 1) {
    const marker = "getOutput" in command4 ? command4.marker : command4.commandStartMarker;
    if (!this.f || !marker) {
      return;
    }
    const line = toLineIndex(marker);
    const promptRowCount = command4.getPromptRowCount();
    const commandRowCount = command4.getCommandRowCount();
    this.C(line - (promptRowCount - 1), position, line + (commandRowCount - 1));
  }
  revealRange(range) {
    this.C(range.start.y - 1, 1, range.end.y - 1, {
      bufferRange: range,
      // Ensure scroll shows the line when sticky scroll is enabled
      forceScroll: !!this.n.getValue(
        "terminal.integrated.stickyScroll.enabled"
        /* TerminalContribSettingId.StickyScrollEnabled */
      )
    });
  }
  showCommandGuide(command4) {
    if (!this.f) {
      return;
    }
    if (!command4) {
      this.j.clear();
      this.h = void 0;
      return;
    }
    if (this.h === command4) {
      return;
    }
    if (command4.marker) {
      this.h = command4;
      const store = this.j.value = new $2c();
      if (!command4.executedMarker || !command4.endMarker) {
        return;
      }
      const startLine = command4.marker.line - (command4.getPromptRowCount() - 1);
      const decorationCount = toLineIndex(command4.endMarker) - startLine;
      if (decorationCount > 200) {
        return;
      }
      for (let i2 = 0; i2 < decorationCount; i2++) {
        const decoration3 = this.f.registerDecoration({
          marker: this.D(startLine, i2)
        });
        if (decoration3) {
          store.add(decoration3);
          let renderedElement;
          store.add(decoration3.onRender((element) => {
            if (!renderedElement) {
              renderedElement = element;
              element.classList.add("terminal-command-guide");
              if (i2 === 0) {
                element.classList.add("top");
              }
              if (i2 === decorationCount - 1) {
                element.classList.add("bottom");
              }
            }
            if (this.f?.element) {
              element.style.marginLeft = `-${getWindow(this.f.element).getComputedStyle(this.f.element).paddingLeft}`;
            }
          }));
        }
      }
    }
  }
  saveScrollState() {
    this.F = { viewportY: this.f?.buffer.active.viewportY ?? 0 };
  }
  restoreScrollState() {
    if (this.F && this.f) {
      this.f.scrollToLine(this.F.viewportY);
      this.F = void 0;
    }
  }
  G(range) {
    if (!this.f) {
      return;
    }
    this.u();
    const startLine = range.start.y;
    const decorationCount = range.end.y - range.start.y + 1;
    for (let i2 = 0; i2 < decorationCount; i2++) {
      const decoration3 = this.f.registerDecoration({
        marker: this.D(startLine - 1, i2),
        x: range.start.x - 1,
        width: range.end.x - 1 - (range.start.x - 1) + 1,
        overviewRulerOptions: void 0
      });
      if (decoration3) {
        this.g?.push(decoration3);
        let renderedElement;
        decoration3.onRender((element) => {
          if (!renderedElement) {
            renderedElement = element;
            element.classList.add("terminal-range-highlight");
          }
        });
        decoration3.onDispose(() => {
          this.g = this.g?.filter((d) => d !== decoration3);
        });
      }
    }
  }
  registerTemporaryDecoration(marker, endMarker, showOutline) {
    if (!this.f) {
      return;
    }
    this.u();
    const color2 = this.r.getColorTheme().getColor($iPb);
    const startLine = toLineIndex(marker);
    const decorationCount = endMarker ? toLineIndex(endMarker) - startLine + 1 : 1;
    for (let i2 = 0; i2 < decorationCount; i2++) {
      const decoration3 = this.f.registerDecoration({
        marker: this.D(marker, i2),
        width: this.f.cols,
        overviewRulerOptions: i2 === 0 ? {
          color: color2?.toString() || "#a0a0a0cc"
        } : void 0
      });
      if (decoration3) {
        this.g?.push(decoration3);
        let renderedElement;
        decoration3.onRender((element) => {
          if (!renderedElement) {
            renderedElement = element;
            element.classList.add("terminal-scroll-highlight");
            if (showOutline) {
              element.classList.add("terminal-scroll-highlight-outline");
            }
            if (i2 === 0) {
              element.classList.add("top");
            }
            if (i2 === decorationCount - 1) {
              element.classList.add("bottom");
            }
          } else {
            element.classList.add("terminal-scroll-highlight");
          }
          if (this.f?.element) {
            element.style.marginLeft = `-${getWindow(this.f.element).getComputedStyle(this.f.element).paddingLeft}`;
          }
        });
        decoration3.onDispose(() => {
          this.g = this.g?.filter((d) => d !== decoration3);
        });
        if (showOutline) {
          $Wh(350).then(() => {
            if (renderedElement) {
              renderedElement.classList.remove("terminal-scroll-highlight-outline");
            }
          });
        }
      }
    }
  }
  scrollToLine(line, position) {
    this.f?.scrollToLine(this.getTargetScrollLine(line, position));
  }
  getTargetScrollLine(line, position) {
    if (this.f && position === 1) {
      return Math.max(line - Math.floor(this.f.rows / 4), 0);
    }
    return line;
  }
  H(terminal2, marker) {
    const viewportY = terminal2.buffer.active.viewportY;
    const line = toLineIndex(marker);
    return line >= viewportY && line < viewportY + terminal2.rows;
  }
  scrollToClosestMarker(startMarkerId, endMarkerId, highlight) {
    const detectionCapability = this.m.get(
      4
      /* TerminalCapability.BufferMarkDetection */
    );
    if (!detectionCapability) {
      return;
    }
    const startMarker = detectionCapability.getMark(startMarkerId);
    if (!startMarker) {
      return;
    }
    const endMarker = endMarkerId ? detectionCapability.getMark(endMarkerId) : startMarker;
    this.C(startMarker, 0, endMarker, { hideDecoration: !highlight });
  }
  selectToPreviousMark() {
    if (!this.f) {
      return;
    }
    if (this.b === null) {
      this.b = this.a;
    }
    if (this.m.has(
      2
      /* TerminalCapability.CommandDetection */
    )) {
      this.scrollToPreviousMark(1, true, true);
    } else {
      this.scrollToPreviousMark(1, true, false);
    }
    $yPb(this.f, this.a, this.b);
  }
  selectToNextMark() {
    if (!this.f) {
      return;
    }
    if (this.b === null) {
      this.b = this.a;
    }
    if (this.m.has(
      2
      /* TerminalCapability.CommandDetection */
    )) {
      this.scrollToNextMark(1, true, true);
    } else {
      this.scrollToNextMark(1, true, false);
    }
    $yPb(this.f, this.a, this.b);
  }
  selectToPreviousLine() {
    if (!this.f) {
      return;
    }
    if (this.b === null) {
      this.b = this.a;
    }
    this.scrollToPreviousLine(this.f, 1, true);
    $yPb(this.f, this.a, this.b);
  }
  selectToNextLine() {
    if (!this.f) {
      return;
    }
    if (this.b === null) {
      this.b = this.a;
    }
    this.scrollToNextLine(this.f, 1, true);
    $yPb(this.f, this.a, this.b);
  }
  scrollToPreviousLine(xterm, scrollPosition = 1, retainSelection = false) {
    if (!retainSelection) {
      this.b = null;
    }
    if (this.a === Boundary.Top) {
      xterm.scrollToTop();
      return;
    }
    if (this.a === Boundary.Bottom) {
      this.a = this.I(xterm, this.J(xterm) - 1);
    } else {
      const offset = this.J(xterm);
      if (this.c) {
        this.a.dispose();
      }
      this.a = this.I(xterm, offset - 1);
    }
    this.c = true;
    this.C(this.a, scrollPosition);
  }
  scrollToNextLine(xterm, scrollPosition = 1, retainSelection = false) {
    if (!retainSelection) {
      this.b = null;
    }
    if (this.a === Boundary.Bottom) {
      xterm.scrollToBottom();
      return;
    }
    if (this.a === Boundary.Top) {
      this.a = this.I(xterm, this.J(xterm) + 1);
    } else {
      const offset = this.J(xterm);
      if (this.c) {
        this.a.dispose();
      }
      this.a = this.I(xterm, offset + 1);
    }
    this.c = true;
    this.C(this.a, scrollPosition);
  }
  I(xterm, cursorYOffset) {
    const marker = xterm.registerMarker(cursorYOffset);
    if (!marker) {
      throw new Error(`Could not create marker for ${cursorYOffset}`);
    }
    return marker;
  }
  J(xterm) {
    if (this.a === Boundary.Bottom) {
      return 0;
    } else if (this.a === Boundary.Top) {
      return 0 - (xterm.buffer.active.baseY + xterm.buffer.active.cursorY);
    } else {
      let offset = $xPb(xterm, this.a);
      offset -= xterm.buffer.active.baseY + xterm.buffer.active.cursorY;
      return offset;
    }
  }
  L(skipEmptyCommands = false) {
    if (this.a === Boundary.Top) {
      return 0;
    } else if (this.a === Boundary.Bottom) {
      return this.s(skipEmptyCommands).length - 1;
    }
    let i2;
    for (i2 = this.s(skipEmptyCommands).length - 1; i2 >= 0; i2--) {
      if (this.s(skipEmptyCommands)[i2].line < this.a.line) {
        return i2;
      }
    }
    return -1;
  }
  M(skipEmptyCommands = false) {
    if (this.a === Boundary.Top) {
      return 0;
    } else if (this.a === Boundary.Bottom) {
      return this.s(skipEmptyCommands).length - 1;
    }
    let i2;
    for (i2 = 0; i2 < this.s(skipEmptyCommands).length; i2++) {
      if (this.s(skipEmptyCommands)[i2].line > this.a.line) {
        return i2;
      }
    }
    return this.s(skipEmptyCommands).length;
  }
};
$wPb = __decorate([
  __param(1, $kl),
  __param(2, $gs)
], $wPb);
function $xPb(xterm, marker) {
  if (marker === Boundary.Bottom) {
    return xterm.buffer.active.baseY + xterm.rows - 1;
  }
  if (marker === Boundary.Top) {
    return 0;
  }
  return marker.line;
}
function $yPb(xterm, start, end) {
  if (end === null) {
    end = Boundary.Bottom;
  }
  let startLine = $xPb(xterm, start);
  let endLine = $xPb(xterm, end);
  if (startLine > endLine) {
    const temp = startLine;
    startLine = endLine;
    endLine = temp;
  }
  endLine -= 1;
  xterm.selectLines(startLine, endLine);
}
function isMarker(value) {
  return typeof value !== "number";
}
function toLineIndex(line) {
  return isMarker(line) ? line.line : line;
}

// out-build/vs/platform/terminal/common/capabilities/commandDetection/terminalCommand.js
var $1x = class _$1x {
  get command() {
    return this.b.command;
  }
  get commandLineConfidence() {
    return this.b.commandLineConfidence;
  }
  get isTrusted() {
    return this.b.isTrusted;
  }
  get timestamp() {
    return this.b.timestamp;
  }
  get duration() {
    return this.b.duration;
  }
  get promptStartMarker() {
    return this.b.promptStartMarker;
  }
  get marker() {
    return this.b.marker;
  }
  get endMarker() {
    return this.b.endMarker;
  }
  set endMarker(value) {
    this.b.endMarker = value;
  }
  get executedMarker() {
    return this.b.executedMarker;
  }
  get aliases() {
    return this.b.aliases;
  }
  get wasReplayed() {
    return this.b.wasReplayed;
  }
  get cwd() {
    return this.b.cwd;
  }
  get exitCode() {
    return this.b.exitCode;
  }
  get commandStartLineContent() {
    return this.b.commandStartLineContent;
  }
  get markProperties() {
    return this.b.markProperties;
  }
  get executedX() {
    return this.b.executedX;
  }
  get startX() {
    return this.b.startX;
  }
  constructor(a, b) {
    this.a = a;
    this.b = b;
  }
  static deserialize(xterm, serialized, isCommandStorageDisabled) {
    const buffer = xterm.buffer.normal;
    const marker = serialized.startLine !== void 0 ? xterm.registerMarker(serialized.startLine - (buffer.baseY + buffer.cursorY)) : void 0;
    if (!marker) {
      return void 0;
    }
    const promptStartMarker = serialized.promptStartLine !== void 0 ? xterm.registerMarker(serialized.promptStartLine - (buffer.baseY + buffer.cursorY)) : void 0;
    const endMarker = serialized.endLine !== void 0 ? xterm.registerMarker(serialized.endLine - (buffer.baseY + buffer.cursorY)) : void 0;
    const executedMarker = serialized.executedLine !== void 0 ? xterm.registerMarker(serialized.executedLine - (buffer.baseY + buffer.cursorY)) : void 0;
    const newCommand = new _$1x(xterm, {
      command: isCommandStorageDisabled ? "" : serialized.command,
      commandLineConfidence: serialized.commandLineConfidence ?? "low",
      isTrusted: serialized.isTrusted,
      promptStartMarker,
      marker,
      startX: serialized.startX,
      endMarker,
      executedMarker,
      executedX: serialized.executedX,
      timestamp: serialized.timestamp,
      duration: serialized.duration,
      cwd: serialized.cwd,
      commandStartLineContent: serialized.commandStartLineContent,
      exitCode: serialized.exitCode,
      markProperties: serialized.markProperties,
      aliases: void 0,
      wasReplayed: true
    });
    return newCommand;
  }
  serialize(isCommandStorageDisabled) {
    return {
      promptStartLine: this.promptStartMarker?.line,
      startLine: this.marker?.line,
      startX: void 0,
      endLine: this.endMarker?.line,
      executedLine: this.executedMarker?.line,
      executedX: this.executedX,
      command: isCommandStorageDisabled ? "" : this.command,
      commandLineConfidence: isCommandStorageDisabled ? "low" : this.commandLineConfidence,
      isTrusted: this.isTrusted,
      cwd: this.cwd,
      exitCode: this.exitCode,
      commandStartLineContent: this.commandStartLineContent,
      timestamp: this.timestamp,
      duration: this.duration,
      markProperties: this.markProperties
    };
  }
  extractCommandLine() {
    return extractCommandLine(this.a.buffer.active, this.a.cols, this.marker, this.startX, this.executedMarker, this.executedX);
  }
  getOutput() {
    if (!this.executedMarker || !this.endMarker) {
      return void 0;
    }
    const startLine = this.executedMarker.line;
    const endLine = this.endMarker.line;
    if (startLine === endLine) {
      return void 0;
    }
    let output = "";
    let line;
    for (let i2 = startLine; i2 < endLine; i2++) {
      line = this.a.buffer.active.getLine(i2);
      if (!line) {
        continue;
      }
      output += line.translateToString(!line.isWrapped) + (line.isWrapped ? "" : "\n");
    }
    return output === "" ? void 0 : output;
  }
  getOutputMatch(outputMatcher) {
    if (!this.executedMarker || !this.endMarker) {
      return void 0;
    }
    const endLine = this.endMarker.line;
    if (endLine === -1) {
      return void 0;
    }
    const buffer = this.a.buffer.active;
    const startLine = Math.max(this.executedMarker.line, 0);
    const matcher = outputMatcher.lineMatcher;
    const linesToCheck = typeof matcher === "string" ? 1 : outputMatcher.length || countNewLines(matcher);
    const lines = [];
    let match;
    if (outputMatcher.anchor === "bottom") {
      for (let i2 = endLine - (outputMatcher.offset || 0); i2 >= startLine; i2--) {
        let wrappedLineStart = i2;
        const wrappedLineEnd = i2;
        while (wrappedLineStart >= startLine && buffer.getLine(wrappedLineStart)?.isWrapped) {
          wrappedLineStart--;
        }
        i2 = wrappedLineStart;
        lines.unshift(getXtermLineContent(buffer, wrappedLineStart, wrappedLineEnd, this.a.cols));
        if (!match) {
          match = lines[0].match(matcher);
        }
        if (lines.length >= linesToCheck) {
          break;
        }
      }
    } else {
      for (let i2 = startLine + (outputMatcher.offset || 0); i2 < endLine; i2++) {
        const wrappedLineStart = i2;
        let wrappedLineEnd = i2;
        while (wrappedLineEnd + 1 < endLine && buffer.getLine(wrappedLineEnd + 1)?.isWrapped) {
          wrappedLineEnd++;
        }
        i2 = wrappedLineEnd;
        lines.push(getXtermLineContent(buffer, wrappedLineStart, wrappedLineEnd, this.a.cols));
        if (!match) {
          match = lines[lines.length - 1].match(matcher);
        }
        if (lines.length >= linesToCheck) {
          break;
        }
      }
    }
    return match ? { regexMatch: match, outputLines: lines } : void 0;
  }
  hasOutput() {
    return !this.executedMarker?.isDisposed && !this.endMarker?.isDisposed && !!(this.executedMarker && this.endMarker && this.executedMarker.line < this.endMarker.line);
  }
  getPromptRowCount() {
    return getPromptRowCount(this, this.a.buffer.active);
  }
  getCommandRowCount() {
    return getCommandRowCount(this);
  }
};
var $2x = class {
  constructor(c) {
    this.c = c;
  }
  serialize(cwd2) {
    if (!this.commandStartMarker) {
      return void 0;
    }
    return {
      promptStartLine: this.promptStartMarker?.line,
      startLine: this.commandStartMarker.line,
      startX: this.commandStartX,
      endLine: void 0,
      executedLine: void 0,
      executedX: void 0,
      command: "",
      commandLineConfidence: "low",
      isTrusted: true,
      cwd: cwd2,
      exitCode: void 0,
      commandStartLineContent: void 0,
      timestamp: 0,
      duration: 0,
      markProperties: void 0
    };
  }
  promoteToFullCommand(cwd2, exitCode, ignoreCommandLine, markProperties) {
    if (exitCode === void 0 && this.command === void 0) {
      this.command = "";
    }
    if (this.command !== void 0 && !this.command.startsWith("\\") || ignoreCommandLine) {
      return new $1x(this.c, {
        command: ignoreCommandLine ? "" : this.command || "",
        commandLineConfidence: ignoreCommandLine ? "low" : this.commandLineConfidence || "low",
        isTrusted: !!this.isTrusted,
        promptStartMarker: this.promptStartMarker,
        marker: this.commandStartMarker,
        startX: this.commandStartX,
        endMarker: this.commandFinishedMarker,
        executedMarker: this.commandExecutedMarker,
        executedX: this.commandExecutedX,
        timestamp: Date.now(),
        duration: this.b || 0,
        cwd: cwd2,
        exitCode,
        commandStartLineContent: this.commandStartLineContent,
        markProperties
      });
    }
    return void 0;
  }
  markExecutedTime() {
    if (this.a === void 0) {
      this.a = Date.now();
    }
  }
  markFinishedTime() {
    if (this.b === void 0 && this.a !== void 0) {
      this.b = Date.now() - this.a;
    }
  }
  extractCommandLine() {
    return extractCommandLine(this.c.buffer.active, this.c.cols, this.commandStartMarker, this.commandStartX, this.commandExecutedMarker, this.commandExecutedX);
  }
  getPromptRowCount() {
    return getPromptRowCount(this, this.c.buffer.active);
  }
  getCommandRowCount() {
    return getCommandRowCount(this);
  }
};
function extractCommandLine(buffer, cols, commandStartMarker, commandStartX, commandExecutedMarker, commandExecutedX) {
  if (!commandStartMarker || !commandExecutedMarker || commandStartX === void 0 || commandExecutedX === void 0) {
    return "";
  }
  let content = "";
  for (let i2 = commandStartMarker.line; i2 <= commandExecutedMarker.line; i2++) {
    const line = buffer.getLine(i2);
    if (line) {
      content += line.translateToString(true, i2 === commandStartMarker.line ? commandStartX : 0, i2 === commandExecutedMarker.line ? commandExecutedX : cols);
    }
  }
  return content;
}
function getXtermLineContent(buffer, lineStart, lineEnd, cols) {
  const maxLineLength = Math.max(2048 / cols * 2);
  lineEnd = Math.min(lineEnd, lineStart + maxLineLength);
  let content = "";
  for (let i2 = lineStart; i2 <= lineEnd; i2++) {
    const line = buffer.getLine(i2);
    if (line) {
      content += line.translateToString(true, 0, cols);
    }
  }
  return content;
}
function countNewLines(regex) {
  if (!regex.multiline) {
    return 1;
  }
  const source = regex.source;
  let count = 1;
  let i2 = source.indexOf("\\n");
  while (i2 !== -1) {
    count++;
    i2 = source.indexOf("\\n", i2 + 1);
  }
  return count;
}
function getPromptRowCount(command4, buffer) {
  const marker = "hasOutput" in command4 ? command4.marker : command4.commandStartMarker;
  if (!marker || !command4.promptStartMarker) {
    return 1;
  }
  let promptRowCount = 1;
  let promptStartLine = command4.promptStartMarker.line;
  while (promptStartLine < marker.line && (buffer.getLine(promptStartLine)?.translateToString(true) ?? "").length === 0) {
    promptStartLine++;
  }
  promptRowCount = marker.line - promptStartLine + 1;
  return promptRowCount;
}
function getCommandRowCount(command4) {
  const marker = "hasOutput" in command4 ? command4.marker : command4.commandStartMarker;
  const executedMarker = "hasOutput" in command4 ? command4.executedMarker : command4.commandExecutedMarker;
  if (!marker || !executedMarker) {
    return 1;
  }
  const commandExecutedLine = Math.max(executedMarker.line, marker.line);
  let commandRowCount = commandExecutedLine - marker.line + 1;
  const executedX = "hasOutput" in command4 ? command4.executedX : command4.commandExecutedX;
  if (executedX === 0) {
    commandRowCount--;
  }
  return commandRowCount;
}

// out-build/vs/platform/terminal/common/capabilities/commandDetection/promptInputModel.js
var PromptInputState;
(function(PromptInputState2) {
  PromptInputState2[PromptInputState2["Unknown"] = 0] = "Unknown";
  PromptInputState2[PromptInputState2["Input"] = 1] = "Input";
  PromptInputState2[PromptInputState2["Execute"] = 2] = "Execute";
})(PromptInputState || (PromptInputState = {}));
var $Zx = class $Zx2 extends $3c {
  get value() {
    return this.j;
  }
  get prefix() {
    return this.j.substring(0, this.m);
  }
  get suffix() {
    return this.j.substring(this.m, this.n === -1 ? void 0 : this.n);
  }
  get cursorIndex() {
    return this.m;
  }
  get ghostTextIndex() {
    return this.n;
  }
  constructor(w, onCommandStart, onCommandExecuted, z) {
    super();
    this.w = w;
    this.z = z;
    this.a = 0;
    this.c = 0;
    this.h = "";
    this.j = "";
    this.m = 0;
    this.n = -1;
    this.r = this.B(new $ze());
    this.onDidStartInput = this.r.event;
    this.s = this.B(new $ze());
    this.onDidChangeInput = this.s.event;
    this.t = this.B(new $ze());
    this.onDidFinishInput = this.t.event;
    this.u = this.B(new $ze());
    this.onDidInterrupt = this.u.event;
    this.B(Event2.any(this.w.onCursorMove, this.w.onData, this.w.onWriteParsed)(() => this.G()));
    this.B(this.w.onData((e) => this.I(e)));
    this.B(onCommandStart((e) => this.D(e)));
    this.B(onCommandExecuted(() => this.F()));
    this.B(this.onDidStartInput(() => this.C("PromptInputModel#onDidStartInput")));
    this.B(this.onDidChangeInput(() => this.C("PromptInputModel#onDidChangeInput")));
    this.B(this.onDidFinishInput(() => this.C("PromptInputModel#onDidFinishInput")));
    this.B(this.onDidInterrupt(() => this.C("PromptInputModel#onDidInterrupt")));
  }
  C(message) {
    if (this.z.getLevel() === LogLevel.Trace) {
      this.z.trace(message, this.getCombinedString());
    }
  }
  setContinuationPrompt(value) {
    this.g = value;
    this.G();
  }
  setLastPromptLine(value) {
    this.f = value;
    this.G();
  }
  setConfidentCommandLine(value) {
    if (this.j !== value) {
      this.j = value;
      this.m = -1;
      this.n = -1;
      this.s.fire(this.Q());
    }
  }
  getCombinedString(emptyStringWhenEmpty) {
    const value = this.j.replaceAll("\n", "\u23CE");
    if (this.m === -1) {
      return value;
    }
    let result = `${value.substring(0, this.cursorIndex)}|`;
    if (this.ghostTextIndex !== -1) {
      result += `${value.substring(this.cursorIndex, this.ghostTextIndex)}[`;
      result += `${value.substring(this.ghostTextIndex)}]`;
    } else {
      result += value.substring(this.cursorIndex);
    }
    if (result === "|" && emptyStringWhenEmpty) {
      return "";
    }
    return result;
  }
  serialize() {
    return {
      modelState: this.Q(),
      commandStartX: this.c,
      lastPromptLine: this.f,
      continuationPrompt: this.g,
      lastUserInput: this.h
    };
  }
  deserialize(serialized) {
    this.j = serialized.modelState.value;
    this.m = serialized.modelState.cursorIndex;
    this.n = serialized.modelState.ghostTextIndex;
    this.c = serialized.commandStartX;
    this.f = serialized.lastPromptLine;
    this.g = serialized.continuationPrompt;
    this.h = serialized.lastUserInput;
  }
  D(command4) {
    if (this.a === 1) {
      return;
    }
    this.a = 1;
    this.b = command4.marker;
    this.c = this.w.buffer.active.cursorX;
    this.j = "";
    this.m = 0;
    this.r.fire(this.Q());
    this.s.fire(this.Q());
    if (this.f) {
      if (this.c !== this.f.length) {
        const line = this.w.buffer.active.getLine(this.b.line);
        if (line?.translateToString(true).startsWith(this.f)) {
          this.c = this.f.length;
          this.G();
        }
      }
    }
  }
  F() {
    if (this.a === 2) {
      return;
    }
    this.m = -1;
    if (this.n !== -1) {
      this.j = this.j.substring(0, this.n);
      this.n = -1;
    }
    const event = this.Q();
    if (this.h === "") {
      this.h = "";
      this.u.fire(event);
    }
    this.a = 2;
    this.t.fire(event);
    this.s.fire(event);
  }
  G() {
    try {
      this.H();
    } catch (e) {
      this.z.error("Error while syncing prompt input model", e);
    }
  }
  H() {
    if (this.a !== 1) {
      return;
    }
    const commandStartY = this.b?.line;
    if (commandStartY === void 0) {
      return;
    }
    const buffer = this.w.buffer.active;
    let line = buffer.getLine(commandStartY);
    const commandLine = line?.translateToString(true, this.c);
    if (!line || commandLine === void 0) {
      this.z.trace(`PromptInputModel#_sync: no line`);
      return;
    }
    const absoluteCursorY = buffer.baseY + buffer.cursorY;
    let value = commandLine;
    let ghostTextIndex = -1;
    let cursorIndex;
    if (absoluteCursorY === commandStartY) {
      cursorIndex = this.O(this.c, buffer, line);
    } else {
      cursorIndex = commandLine.trimEnd().length;
    }
    if (absoluteCursorY === commandStartY && buffer.cursorX > 1) {
      ghostTextIndex = this.J(buffer, line, cursorIndex);
    }
    for (let y = commandStartY + 1; y <= absoluteCursorY; y++) {
      line = buffer.getLine(y);
      const lineText = line?.translateToString(true);
      if (lineText && line) {
        if (line.isWrapped) {
          value += lineText;
          const relativeCursorIndex = this.O(0, buffer, line);
          if (absoluteCursorY === y) {
            cursorIndex += relativeCursorIndex;
          } else {
            cursorIndex += lineText.length;
          }
        } else if (this.g === void 0 || this.M(lineText)) {
          const trimmedLineText = this.L(lineText);
          value += `
${trimmedLineText}`;
          if (absoluteCursorY === y) {
            const continuationCellWidth = this.N(line, lineText);
            const relativeCursorIndex = this.O(continuationCellWidth, buffer, line);
            cursorIndex += relativeCursorIndex + 1;
          } else {
            cursorIndex += trimmedLineText.length + 1;
          }
        } else {
          break;
        }
      }
    }
    for (let y = absoluteCursorY + 1; y < buffer.baseY + this.w.rows; y++) {
      line = buffer.getLine(y);
      const lineText = line?.translateToString(true);
      if (lineText && line) {
        if (this.g === void 0 || this.M(lineText)) {
          value += `
${this.L(lineText)}`;
        } else {
          break;
        }
      } else {
        break;
      }
    }
    if (this.z.getLevel() === LogLevel.Trace) {
      this.z.trace(`PromptInputModel#_sync: ${this.getCombinedString()}`);
    }
    {
      let trailingWhitespace = this.j.length - this.j.trimEnd().length;
      if (this.h === "\x7F") {
        this.h = "";
        if (cursorIndex === this.m - 1) {
          if (this.j.trimEnd().length > value.trimEnd().length && value.trimEnd().length <= cursorIndex) {
            trailingWhitespace = Math.max(this.j.length - 1 - value.trimEnd().length, 0);
          } else {
            trailingWhitespace = Math.max(trailingWhitespace - 1, 0);
          }
        }
      }
      if (this.h === "\x1B[3~") {
        this.h = "";
        if (cursorIndex === this.m) {
          trailingWhitespace = Math.max(trailingWhitespace - 1, 0);
        }
      }
      const valueLines = value.split("\n");
      const isMultiLine = valueLines.length > 1;
      const valueEndTrimmed = value.trimEnd();
      if (!isMultiLine) {
        if (valueEndTrimmed.length < value.length) {
          if (this.h === " ") {
            this.h = "";
            if (cursorIndex > valueEndTrimmed.length && cursorIndex > this.m) {
              trailingWhitespace++;
            }
          }
          trailingWhitespace = Math.max(cursorIndex - valueEndTrimmed.length, trailingWhitespace, 0);
        }
        const charBeforeCursor = cursorIndex === 0 ? "" : value[cursorIndex - 1];
        if (trailingWhitespace > 0 && cursorIndex === this.m + 1 && this.h !== "" && charBeforeCursor !== " ") {
          trailingWhitespace = this.j.length - this.m;
        }
      }
      if (isMultiLine) {
        valueLines[valueLines.length - 1] = valueLines.at(-1)?.trimEnd() ?? "";
        const continuationOffset = (valueLines.length - 1) * (this.g?.length ?? 0);
        trailingWhitespace = Math.max(0, cursorIndex - value.length - continuationOffset);
      }
      value = valueLines.map((e) => e.trimEnd()).join("\n") + " ".repeat(trailingWhitespace);
    }
    if (this.j !== value || this.m !== cursorIndex || this.n !== ghostTextIndex) {
      this.j = value;
      this.m = cursorIndex;
      this.n = ghostTextIndex;
      this.s.fire(this.Q());
    }
  }
  I(e) {
    this.h = e;
  }
  /**
   * Detect ghost text by looking for italic or dim text in or after the cursor and
   * non-italic/dim text in the cell closest non-whitespace cell before the cursor.
   */
  J(buffer, line, cursorIndex) {
    let ghostTextIndex = -1;
    let proceedWithGhostTextCheck = false;
    let x = buffer.cursorX;
    while (x > 0) {
      const cell = line.getCell(--x);
      if (!cell) {
        break;
      }
      if (cell.getChars().trim().length > 0) {
        proceedWithGhostTextCheck = !this.P(cell);
        break;
      }
    }
    if (proceedWithGhostTextCheck) {
      let potentialGhostIndexOffset = 0;
      let x2 = buffer.cursorX;
      while (x2 < line.length) {
        const cell = line.getCell(x2++);
        if (!cell || cell.getCode() === 0) {
          break;
        }
        if (this.P(cell)) {
          ghostTextIndex = cursorIndex + potentialGhostIndexOffset;
          break;
        }
        potentialGhostIndexOffset += cell.getChars().length;
      }
    }
    return ghostTextIndex;
  }
  L(lineText) {
    if (this.M(lineText)) {
      lineText = lineText.substring(this.g.length);
    }
    return lineText;
  }
  M(lineText) {
    return !!(this.g && lineText.startsWith(this.g));
  }
  N(line, lineText) {
    if (!this.g || !lineText.startsWith(this.g)) {
      return 0;
    }
    let buffer = "";
    let x = 0;
    while (buffer !== this.g) {
      buffer += line.getCell(x++).getChars();
    }
    return x;
  }
  O(startCellX, buffer, line) {
    return line?.translateToString(true, startCellX, buffer.cursorX).length ?? 0;
  }
  P(cell) {
    return !!(cell.isItalic() || cell.isDim());
  }
  Q() {
    return Object.freeze({
      value: this.j,
      prefix: this.prefix,
      suffix: this.suffix,
      cursorIndex: this.m,
      ghostTextIndex: this.n
    });
  }
};
__decorate([
  $_t(0)
], $Zx.prototype, "G", null);
$Zx = __decorate([
  __param(3, $wn)
], $Zx);

// out-build/vs/platform/terminal/common/capabilities/commandDetectionCapability.js
var $BPb = class $BPb2 extends $3c {
  get promptInputModel() {
    return this.c;
  }
  get commands() {
    return this.f;
  }
  get executingCommand() {
    return this.n.command;
  }
  get executingCommandObject() {
    if (this.n.commandStartMarker) {
      return this.n.promoteToFullCommand(this.g, void 0, this.u?.ignoreCommandLine ?? false, void 0);
    }
    return void 0;
  }
  get currentCommand() {
    return this.n;
  }
  get cwd() {
    return this.g;
  }
  get promptTerminator() {
    return this.h;
  }
  constructor(L, M) {
    super();
    this.L = L;
    this.M = M;
    this.type = 2;
    this.f = [];
    this.n = new $2x(this.L);
    this.r = [];
    this.t = false;
    this.D = this.B(new $ze());
    this.onCommandStarted = this.D.event;
    this.F = this.B(new $ze());
    this.onBeforeCommandFinished = this.F.event;
    this.G = this.B(new $ze());
    this.onCommandFinished = this.G.event;
    this.H = this.B(new $ze());
    this.onCommandExecuted = this.H.event;
    this.I = this.B(new $ze());
    this.onCommandInvalidated = this.I.event;
    this.J = this.B(new $ze());
    this.onCurrentCommandInvalidated = this.J.event;
    this.c = this.B(new $Zx(this.L, this.onCommandStarted, this.onCommandExecuted, this.M));
    this.B(this.onCommandExecuted((command4) => {
      if (command4.commandLineConfidence !== "high") {
        const typedCommand = command4;
        command4.command = typedCommand.extractCommandLine();
        command4.commandLineConfidence = "low";
        if ("getOutput" in typedCommand) {
          if (
            // Markers exist
            typedCommand.promptStartMarker && typedCommand.marker && typedCommand.executedMarker && // Single line command
            command4.command.indexOf("\n") === -1 && // Start marker is not on the left-most column
            typedCommand.startX !== void 0 && typedCommand.startX > 0
          ) {
            command4.commandLineConfidence = "medium";
          }
        } else {
          if (
            // Markers exist
            typedCommand.promptStartMarker && typedCommand.commandStartMarker && typedCommand.commandExecutedMarker && // Single line command
            command4.command.indexOf("\n") === -1 && // Start marker is not on the left-most column
            typedCommand.commandStartX !== void 0 && typedCommand.commandStartX > 0
          ) {
            command4.commandLineConfidence = "medium";
          }
        }
      }
    }));
    const that = this;
    this.z = new class {
      get onCurrentCommandInvalidatedEmitter() {
        return that.J;
      }
      get onCommandStartedEmitter() {
        return that.D;
      }
      get onCommandExecutedEmitter() {
        return that.H;
      }
      get dimensions() {
        return that.s;
      }
      get isCommandStorageDisabled() {
        return that.t;
      }
      get commandMarkers() {
        return that.r;
      }
      set commandMarkers(value) {
        that.r = value;
      }
      get clearCommandsInViewport() {
        return that.P.bind(that);
      }
      commitCommandFinished() {
        that.w?.flush();
        that.w = void 0;
      }
    }();
    this.C = this.B(new $5c(new UnixPtyHeuristics(this.L, this, this.z, this.M)));
    this.s = {
      cols: this.L.cols,
      rows: this.L.rows
    };
    this.B(this.L.onResize((e) => this.N(e)));
    this.B(this.L.onCursorMove(() => this.O()));
  }
  N(e) {
    this.C.value.preHandleResize?.(e);
    this.s.cols = e.cols;
    this.s.rows = e.rows;
  }
  O() {
    if (this.q.isDisposed) {
      return;
    }
    if (this.L.buffer.active === this.L.buffer.normal && this.n.commandStartMarker) {
      if (this.L.buffer.active.baseY + this.L.buffer.active.cursorY < this.n.commandStartMarker.line) {
        this.P();
        this.n.isInvalid = true;
        this.J.fire({
          reason: "windows"
          /* CommandInvalidationReason.Windows */
        });
      }
    }
  }
  P() {
    let count = 0;
    for (let i2 = this.f.length - 1; i2 >= 0; i2--) {
      const line = this.f[i2].marker?.line;
      if (line && line < this.L.buffer.active.baseY) {
        break;
      }
      count++;
    }
    if (count > 0) {
      this.I.fire(this.f.splice(this.f.length - count, count));
    }
  }
  setContinuationPrompt(value) {
    this.c.setContinuationPrompt(value);
  }
  // TODO: Simplify this, can everything work off the last line?
  setPromptTerminator(promptTerminator, lastPromptLine) {
    this.M.debug("CommandDetectionCapability#setPromptTerminator", promptTerminator);
    this.h = promptTerminator;
    this.c.setLastPromptLine(lastPromptLine);
  }
  setCwd(value) {
    this.g = value;
  }
  setIsWindowsPty(value) {
    if (value && !(this.C.value instanceof WindowsPtyHeuristics)) {
      const that = this;
      this.C.value = new WindowsPtyHeuristics(this.L, this, new class {
        get onCurrentCommandInvalidatedEmitter() {
          return that.J;
        }
        get onCommandStartedEmitter() {
          return that.D;
        }
        get onCommandExecutedEmitter() {
          return that.H;
        }
        get dimensions() {
          return that.s;
        }
        get isCommandStorageDisabled() {
          return that.t;
        }
        get commandMarkers() {
          return that.r;
        }
        set commandMarkers(value2) {
          that.r = value2;
        }
        get clearCommandsInViewport() {
          return that.P.bind(that);
        }
        commitCommandFinished() {
          that.w?.flush();
          that.w = void 0;
        }
      }(), this.M);
    } else if (!value && !(this.C.value instanceof UnixPtyHeuristics)) {
      this.C.value = new UnixPtyHeuristics(this.L, this, this.z, this.M);
    }
  }
  setIsCommandStorageDisabled() {
    this.t = true;
  }
  getCommandForLine(line) {
    if (this.n.promptStartMarker && line >= this.n.promptStartMarker?.line) {
      return this.n;
    }
    if (this.f.length === 0) {
      return void 0;
    }
    if ((this.f[0].promptStartMarker ?? this.f[0].marker).line > line) {
      return void 0;
    }
    for (let i2 = this.commands.length - 1; i2 >= 0; i2--) {
      if ((this.commands[i2].promptStartMarker ?? this.commands[i2].marker).line <= line) {
        return this.commands[i2];
      }
    }
    return void 0;
  }
  getCwdForLine(line) {
    if (this.n.promptStartMarker && line >= this.n.promptStartMarker?.line) {
      return this.g;
    }
    const command4 = this.getCommandForLine(line);
    if (command4 && "cwd" in command4) {
      return command4.cwd;
    }
    return void 0;
  }
  handlePromptStart(options3) {
    const lastCommand = this.commands.at(-1);
    if (lastCommand?.endMarker && lastCommand?.executedMarker && lastCommand.endMarker.line === lastCommand.executedMarker.line) {
      this.M.debug("CommandDetectionCapability#handlePromptStart adjusted commandFinished", `${lastCommand.endMarker.line} -> ${lastCommand.executedMarker.line + 1}`);
      lastCommand.endMarker = cloneMarker(this.L, lastCommand.executedMarker, 1);
    }
    this.n.promptStartMarker = options3?.marker || (lastCommand?.endMarker ? cloneMarker(this.L, lastCommand.endMarker) : this.L.registerMarker(0));
    this.M.debug("CommandDetectionCapability#handlePromptStart", this.L.buffer.active.cursorX, this.n.promptStartMarker?.line);
  }
  handleContinuationStart() {
    this.n.currentContinuationMarker = this.L.registerMarker(0);
    this.M.debug("CommandDetectionCapability#handleContinuationStart", this.n.currentContinuationMarker);
  }
  handleContinuationEnd() {
    if (!this.n.currentContinuationMarker) {
      this.M.warn("CommandDetectionCapability#handleContinuationEnd Received continuation end without start");
      return;
    }
    if (!this.n.continuations) {
      this.n.continuations = [];
    }
    this.n.continuations.push({
      marker: this.n.currentContinuationMarker,
      end: this.L.buffer.active.cursorX
    });
    this.n.currentContinuationMarker = void 0;
    this.M.debug("CommandDetectionCapability#handleContinuationEnd", this.n.continuations[this.n.continuations.length - 1]);
  }
  handleRightPromptStart() {
    this.n.commandRightPromptStartX = this.L.buffer.active.cursorX;
    this.M.debug("CommandDetectionCapability#handleRightPromptStart", this.n.commandRightPromptStartX);
  }
  handleRightPromptEnd() {
    this.n.commandRightPromptEndX = this.L.buffer.active.cursorX;
    this.M.debug("CommandDetectionCapability#handleRightPromptEnd", this.n.commandRightPromptEndX);
  }
  handleCommandStart(options3) {
    this.u = options3;
    this.n.cwd = this.g;
    this.n.commandStartMarker = options3?.marker || this.n.commandStartMarker;
    if (this.n.commandStartMarker?.line === this.L.buffer.active.cursorY) {
      this.n.commandStartX = this.L.buffer.active.cursorX;
      this.M.debug("CommandDetectionCapability#handleCommandStart", this.n.commandStartX, this.n.commandStartMarker?.line);
      return;
    }
    this.C.value.handleCommandStart(options3);
  }
  handleGenericCommand(options3) {
    if (options3?.markProperties?.disableCommandStorage) {
      this.setIsCommandStorageDisabled();
    }
    this.handlePromptStart(options3);
    this.handleCommandStart(options3);
    this.handleCommandExecuted(options3);
    this.handleCommandFinished(void 0, options3);
  }
  handleCommandExecuted(options3) {
    this.C.value.handleCommandExecuted(options3);
    this.n.markExecutedTime();
  }
  handleCommandFinished(exitCode, options3) {
    this.n.markFinishedTime();
    this.C.value.preHandleCommandFinished?.();
    this.M.debug("CommandDetectionCapability#handleCommandFinished", this.L.buffer.active.cursorX, options3?.marker?.line, this.n.command, this.n);
    if (exitCode === void 0) {
      const lastCommand = this.commands.length > 0 ? this.commands[this.commands.length - 1] : void 0;
      if (this.n.command && this.n.command.length > 0 && lastCommand?.command === this.n.command) {
        exitCode = lastCommand.exitCode;
      }
    }
    if (this.n.commandStartMarker === void 0 || !this.L.buffer.active) {
      return;
    }
    this.n.commandFinishedMarker = options3?.marker || this.L.registerMarker(0);
    this.C.value.postHandleCommandFinished?.();
    const newCommand = this.n.promoteToFullCommand(this.g, exitCode, this.u?.ignoreCommandLine ?? false, options3?.markProperties);
    if (newCommand) {
      this.f.push(newCommand);
      this.w = new $8h(() => {
        this.F.fire(newCommand);
        if (!this.n.isInvalid) {
          this.M.debug("CommandDetectionCapability#onCommandFinished", newCommand);
          this.G.fire(newCommand);
        }
      }, 50);
      this.w.schedule();
    }
    this.n = new $2x(this.L);
    this.u = void 0;
  }
  setCommandLine(commandLine, isTrusted) {
    this.M.debug("CommandDetectionCapability#setCommandLine", commandLine, isTrusted);
    this.n.command = commandLine;
    this.n.commandLineConfidence = "high";
    this.n.isTrusted = isTrusted;
    if (isTrusted) {
      this.c.setConfidentCommandLine(commandLine);
    }
  }
  serialize() {
    const commands2 = this.commands.map((e) => e.serialize(this.t));
    const partialCommand = this.n.serialize(this.g);
    if (partialCommand) {
      commands2.push(partialCommand);
    }
    return {
      isWindowsPty: this.C.value instanceof WindowsPtyHeuristics,
      commands: commands2,
      promptInputModel: this.c.serialize()
    };
  }
  deserialize(serialized) {
    if (serialized.isWindowsPty) {
      this.setIsWindowsPty(serialized.isWindowsPty);
    }
    const buffer = this.L.buffer.normal;
    for (const e of serialized.commands) {
      if (!e.endLine) {
        const marker = e.startLine !== void 0 ? this.L.registerMarker(e.startLine - (buffer.baseY + buffer.cursorY)) : void 0;
        if (!marker) {
          continue;
        }
        this.n.commandStartMarker = e.startLine !== void 0 ? this.L.registerMarker(e.startLine - (buffer.baseY + buffer.cursorY)) : void 0;
        this.n.commandStartX = e.startX;
        this.n.promptStartMarker = e.promptStartLine !== void 0 ? this.L.registerMarker(e.promptStartLine - (buffer.baseY + buffer.cursorY)) : void 0;
        this.g = e.cwd;
        this.D.fire({ marker });
        continue;
      }
      const newCommand = $1x.deserialize(this.L, e, this.t);
      if (!newCommand) {
        continue;
      }
      this.f.push(newCommand);
      this.M.debug("CommandDetectionCapability#onCommandFinished", newCommand);
      this.G.fire(newCommand);
    }
    if (serialized.promptInputModel) {
      this.c.deserialize(serialized.promptInputModel);
    }
  }
};
__decorate([
  $$t(500)
], $BPb.prototype, "O", null);
$BPb = __decorate([
  __param(1, $wn)
], $BPb);
var UnixPtyHeuristics = class extends $3c {
  constructor(c, f, g, h3) {
    super();
    this.c = c;
    this.f = f;
    this.g = g;
    this.h = h3;
    this.B(c.parser.registerCsiHandler({ final: "J" }, (params) => {
      if (params.length >= 1 && (params[0] === 2 || params[0] === 3)) {
        g.clearCommandsInViewport();
      }
      return false;
    }));
  }
  handleCommandStart(options3) {
    this.g.commitCommandFinished();
    const currentCommand = this.f.currentCommand;
    currentCommand.commandStartX = this.c.buffer.active.cursorX;
    currentCommand.commandStartMarker = options3?.marker || this.c.registerMarker(0);
    currentCommand.commandExecutedMarker?.dispose();
    currentCommand.commandExecutedMarker = void 0;
    currentCommand.commandExecutedX = void 0;
    for (const m of this.g.commandMarkers) {
      m.dispose();
    }
    this.g.commandMarkers.length = 0;
    this.g.onCommandStartedEmitter.fire({ marker: options3?.marker || currentCommand.commandStartMarker, markProperties: options3?.markProperties });
    this.h.debug("CommandDetectionCapability#handleCommandStart", currentCommand.commandStartX, currentCommand.commandStartMarker?.line);
  }
  handleCommandExecuted(options3) {
    const currentCommand = this.f.currentCommand;
    currentCommand.commandExecutedMarker = options3?.marker || this.c.registerMarker(0);
    currentCommand.commandExecutedX = this.c.buffer.active.cursorX;
    this.h.debug("CommandDetectionCapability#handleCommandExecuted", currentCommand.commandExecutedX, currentCommand.commandExecutedMarker?.line);
    if (!currentCommand.commandStartMarker || !currentCommand.commandExecutedMarker || currentCommand.commandStartX === void 0) {
      return;
    }
    currentCommand.command = this.g.isCommandStorageDisabled ? "" : this.c.buffer.active.getLine(currentCommand.commandStartMarker.line)?.translateToString(true, currentCommand.commandStartX, currentCommand.commandRightPromptStartX).trim();
    let y = currentCommand.commandStartMarker.line + 1;
    const commandExecutedLine = currentCommand.commandExecutedMarker.line;
    for (; y < commandExecutedLine; y++) {
      const line = this.c.buffer.active.getLine(y);
      if (line) {
        const continuation = currentCommand.continuations?.find((e) => e.marker.line === y);
        if (continuation) {
          currentCommand.command += "\n";
        }
        const startColumn = continuation?.end ?? 0;
        currentCommand.command += line.translateToString(true, startColumn);
      }
    }
    if (y === commandExecutedLine) {
      currentCommand.command += this.c.buffer.active.getLine(commandExecutedLine)?.translateToString(true, void 0, currentCommand.commandExecutedX) || "";
    }
    this.g.onCommandExecutedEmitter.fire(currentCommand);
  }
};
var AdjustCommandStartMarkerConstants;
(function(AdjustCommandStartMarkerConstants2) {
  AdjustCommandStartMarkerConstants2[AdjustCommandStartMarkerConstants2["MaxCheckLineCount"] = 10] = "MaxCheckLineCount";
  AdjustCommandStartMarkerConstants2[AdjustCommandStartMarkerConstants2["Interval"] = 20] = "Interval";
  AdjustCommandStartMarkerConstants2[AdjustCommandStartMarkerConstants2["MaximumPollCount"] = 10] = "MaximumPollCount";
})(AdjustCommandStartMarkerConstants || (AdjustCommandStartMarkerConstants = {}));
var WindowsPtyHeuristics = class WindowsPtyHeuristics2 extends $3c {
  constructor(n, r2, s, t) {
    super();
    this.n = n;
    this.r = r2;
    this.s = s;
    this.t = t;
    this.c = this.B(new $4c());
    this.g = 0;
    this.h = 0;
    this.B(n.parser.registerCsiHandler({ final: "J" }, (params) => {
      if (params.length >= 1 && (params[0] === 2 || params[0] === 3)) {
        this.s.clearCommandsInViewport();
      }
      return false;
    }));
    this.B(this.r.onBeforeCommandFinished((command4) => {
      if (command4.command.trim().toLowerCase() === "clear" || command4.command.trim().toLowerCase() === "cls") {
        this.f?.cancel();
        this.f = void 0;
        this.s.clearCommandsInViewport();
        this.r.currentCommand.isInvalid = true;
        this.s.onCurrentCommandInvalidatedEmitter.fire({
          reason: "windows"
          /* CommandInvalidationReason.Windows */
        });
      }
    }));
  }
  preHandleResize(e) {
    const baseY = this.n.buffer.active.baseY;
    const rowsDifference = e.rows - this.s.dimensions.rows;
    if (rowsDifference > 0) {
      this.D().then(() => {
        const potentialShiftedLineCount = Math.min(rowsDifference, baseY);
        for (let i2 = this.r.commands.length - 1; i2 >= 0; i2--) {
          const command4 = this.r.commands[i2];
          if (!command4.marker || command4.marker.line < baseY || command4.commandStartLineContent === void 0) {
            break;
          }
          const line = this.n.buffer.active.getLine(command4.marker.line);
          if (!line || line.translateToString(true) === command4.commandStartLineContent) {
            continue;
          }
          const shiftedY = command4.marker.line - potentialShiftedLineCount;
          const shiftedLine = this.n.buffer.active.getLine(shiftedY);
          if (shiftedLine?.translateToString(true) !== command4.commandStartLineContent) {
            continue;
          }
          this.n._core._bufferService.buffer.lines.onDeleteEmitter.fire({
            index: this.n.buffer.active.baseY,
            amount: potentialShiftedLineCount
          });
        }
      });
    }
  }
  handleCommandStart() {
    this.r.currentCommand.commandStartX = this.n.buffer.active.cursorX;
    this.s.commandMarkers.length = 0;
    const initialCommandStartMarker = this.r.currentCommand.commandStartMarker = this.r.currentCommand.promptStartMarker ? cloneMarker(this.n, this.r.currentCommand.promptStartMarker) : this.n.registerMarker(0);
    this.r.currentCommand.commandStartX = 0;
    this.g = 0;
    this.h = 0;
    this.f = new $8h(
      () => this.u(initialCommandStartMarker),
      20
      /* AdjustCommandStartMarkerConstants.Interval */
    );
    this.f.schedule();
  }
  u(start) {
    if (this.q.isDisposed) {
      return;
    }
    const buffer = this.n.buffer.active;
    let scannedLineCount = this.g;
    while (scannedLineCount < 10 && start.line + scannedLineCount < buffer.baseY + this.n.rows) {
      if (this.C()) {
        const prompt = this.F(start.line + scannedLineCount);
        if (prompt) {
          const adjustedPrompt = typeof prompt === "string" ? prompt : prompt.prompt;
          this.r.currentCommand.commandStartMarker = this.n.registerMarker(0);
          if (typeof prompt === "object" && prompt.likelySingleLine) {
            this.t.debug("CommandDetectionCapability#_tryAdjustCommandStartMarker adjusted promptStart", `${this.r.currentCommand.promptStartMarker?.line} -> ${this.r.currentCommand.commandStartMarker.line}`);
            this.r.currentCommand.promptStartMarker?.dispose();
            this.r.currentCommand.promptStartMarker = cloneMarker(this.n, this.r.currentCommand.commandStartMarker);
            const lastCommand = this.r.commands.at(-1);
            if (lastCommand && this.r.currentCommand.commandStartMarker.line !== lastCommand.endMarker?.line) {
              lastCommand.endMarker?.dispose();
              lastCommand.endMarker = cloneMarker(this.n, this.r.currentCommand.commandStartMarker);
            }
          }
          this.r.currentCommand.commandStartX = adjustedPrompt.length;
          this.t.debug("CommandDetectionCapability#_tryAdjustCommandStartMarker adjusted commandStart", `${start.line} -> ${this.r.currentCommand.commandStartMarker.line}:${this.r.currentCommand.commandStartX}`);
          this.w();
          return;
        }
      }
      scannedLineCount++;
    }
    if (scannedLineCount < 10) {
      this.g = scannedLineCount;
      if (++this.h < 10) {
        this.f?.schedule();
      } else {
        this.w();
      }
    } else {
      this.w();
    }
  }
  w() {
    if (this.f) {
      this.h = 10;
      this.f.flush();
      this.f = void 0;
    }
    this.s.commitCommandFinished();
    if (!this.r.currentCommand.commandExecutedMarker) {
      this.c.value = this.n.onCursorMove(() => {
        if (this.s.commandMarkers.length === 0 || this.s.commandMarkers[this.s.commandMarkers.length - 1].line !== this.n.buffer.active.cursorY) {
          const marker = this.n.registerMarker(0);
          if (marker) {
            this.s.commandMarkers.push(marker);
          }
        }
      });
    }
    if (this.r.currentCommand.commandStartMarker) {
      const line = this.n.buffer.active.getLine(this.r.currentCommand.commandStartMarker.line);
      if (line) {
        this.r.currentCommand.commandStartLineContent = line.translateToString(true);
      }
    }
    this.s.onCommandStartedEmitter.fire({ marker: this.r.currentCommand.commandStartMarker });
    this.t.debug("CommandDetectionCapability#_handleCommandStartWindows", this.r.currentCommand.commandStartX, this.r.currentCommand.commandStartMarker?.line);
  }
  handleCommandExecuted(options3) {
    if (this.f) {
      this.w();
    }
    this.c.clear();
    this.z();
    this.r.currentCommand.commandExecutedX = this.n.buffer.active.cursorX;
    this.s.onCommandExecutedEmitter.fire(this.r.currentCommand);
    this.t.debug("CommandDetectionCapability#handleCommandExecuted", this.r.currentCommand.commandExecutedX, this.r.currentCommand.commandExecutedMarker?.line);
  }
  preHandleCommandFinished() {
    if (this.r.currentCommand.commandExecutedMarker) {
      return;
    }
    if (this.s.commandMarkers.length === 0) {
      if (!this.r.currentCommand.commandStartMarker) {
        this.r.currentCommand.commandStartMarker = this.n.registerMarker(0);
      }
      if (this.r.currentCommand.commandStartMarker) {
        this.s.commandMarkers.push(this.r.currentCommand.commandStartMarker);
      }
    }
    this.z();
  }
  postHandleCommandFinished() {
    const currentCommand = this.r.currentCommand;
    const commandText = currentCommand.command;
    const commandLine = currentCommand.commandStartMarker?.line;
    const executedLine = currentCommand.commandExecutedMarker?.line;
    if (!commandText || commandText.length === 0 || commandLine === void 0 || commandLine === -1 || executedLine === void 0 || executedLine === -1) {
      return;
    }
    let current = 0;
    let found = false;
    for (let i2 = commandLine; i2 <= executedLine; i2++) {
      const line = this.n.buffer.active.getLine(i2);
      if (!line) {
        break;
      }
      const text2 = line.translateToString(true);
      for (let j = 0; j < text2.length; j++) {
        while (commandText.length < current && commandText[current] === " ") {
          current++;
        }
        if (text2[j] === commandText[current]) {
          current++;
        }
        if (current === commandText.length) {
          const wrapsToNextLine = j >= this.n.cols - 1;
          currentCommand.commandExecutedMarker = this.n.registerMarker(i2 - (this.n.buffer.active.baseY + this.n.buffer.active.cursorY) + (wrapsToNextLine ? 1 : 0));
          currentCommand.commandExecutedX = wrapsToNextLine ? 0 : j + 1;
          found = true;
          break;
        }
      }
      if (found) {
        break;
      }
    }
  }
  z() {
    if (this.s.commandMarkers.length === 0) {
      return;
    }
    this.s.commandMarkers = this.s.commandMarkers.sort((a, b) => a.line - b.line);
    this.r.currentCommand.commandStartMarker = this.s.commandMarkers[0];
    if (this.r.currentCommand.commandStartMarker) {
      const line = this.n.buffer.active.getLine(this.r.currentCommand.commandStartMarker.line);
      if (line) {
        this.r.currentCommand.commandStartLineContent = line.translateToString(true);
      }
    }
    this.r.currentCommand.commandExecutedMarker = this.s.commandMarkers[this.s.commandMarkers.length - 1];
    this.s.onCommandExecutedEmitter.fire(this.r.currentCommand);
  }
  C() {
    const lastCommand = this.r.commands.at(-1);
    if (!lastCommand) {
      return true;
    }
    const cursorYAbsolute = this.n.buffer.active.baseY + this.n.buffer.active.cursorY;
    const lastCommandYAbsolute = (lastCommand.endMarker ? lastCommand.endMarker.line : lastCommand.marker?.line) ?? -1;
    return cursorYAbsolute > lastCommandYAbsolute;
  }
  D() {
    const cursorX = this.n.buffer.active.cursorX;
    const cursorY = this.n.buffer.active.cursorY;
    let totalDelay = 0;
    return new Promise((resolve, reject) => {
      const interval = setInterval(() => {
        if (cursorX !== this.n.buffer.active.cursorX || cursorY !== this.n.buffer.active.cursorY) {
          resolve();
          clearInterval(interval);
          return;
        }
        totalDelay += 10;
        if (totalDelay > 1e3) {
          clearInterval(interval);
          resolve();
        }
      }, 10);
    });
  }
  F(y = this.n.buffer.active.baseY + this.n.buffer.active.cursorY) {
    const line = this.n.buffer.active.getLine(y);
    if (!line) {
      return;
    }
    const lineText = line.translateToString(true);
    if (!lineText) {
      return;
    }
    const pwshPrompt = lineText.match(/(?<prompt>(\(.+\)\s)?(?:PS.+>\s?))/)?.groups?.prompt;
    if (pwshPrompt) {
      const adjustedPrompt = this.G(pwshPrompt, lineText, ">");
      if (adjustedPrompt) {
        return {
          prompt: adjustedPrompt,
          likelySingleLine: true
        };
      }
    }
    const customPrompt = lineText.match(/.*\u276f(?=[^\u276f]*$)/g)?.[0];
    if (customPrompt) {
      const adjustedPrompt = this.G(customPrompt, lineText, "\u276F");
      if (adjustedPrompt) {
        return adjustedPrompt;
      }
    }
    const bashPrompt = lineText.match(/^(?<prompt>\$)/)?.groups?.prompt;
    if (bashPrompt) {
      const adjustedPrompt = this.G(bashPrompt, lineText, "$");
      if (adjustedPrompt) {
        return adjustedPrompt;
      }
    }
    const pythonPrompt = lineText.match(/^(?<prompt>>>> )/g)?.groups?.prompt;
    if (pythonPrompt) {
      return {
        prompt: pythonPrompt,
        likelySingleLine: true
      };
    }
    if (this.r.promptTerminator && lineText.trim().endsWith(this.r.promptTerminator)) {
      const adjustedPrompt = this.G(lineText, lineText, this.r.promptTerminator);
      if (adjustedPrompt) {
        return adjustedPrompt;
      }
    }
    const cmdMatch = lineText.match(/^(?<prompt>(\(.+\)\s)?(?:[A-Z]:\\.*>))/);
    return cmdMatch?.groups?.prompt ? {
      prompt: cmdMatch.groups.prompt,
      likelySingleLine: true
    } : void 0;
  }
  G(prompt, lineText, char) {
    if (!prompt) {
      return;
    }
    if (lineText === prompt && prompt.endsWith(char)) {
      prompt += " ";
    }
    return prompt;
  }
};
WindowsPtyHeuristics = __decorate([
  __param(3, $wn)
], WindowsPtyHeuristics);
function $CPb(buffer, command4, cols, outputMatcher) {
  if (!outputMatcher) {
    return void 0;
  }
  const executedMarker = command4.executedMarker;
  const endMarker = command4.endMarker;
  if (!executedMarker || !endMarker) {
    return void 0;
  }
  const startLine = executedMarker.line;
  const endLine = endMarker.line;
  const linesToCheck = outputMatcher.length;
  const lines = [];
  if (outputMatcher.anchor === "bottom") {
    for (let i2 = endLine - (outputMatcher.offset || 0); i2 >= startLine; i2--) {
      let wrappedLineStart = i2;
      const wrappedLineEnd = i2;
      while (wrappedLineStart >= startLine && buffer.getLine(wrappedLineStart)?.isWrapped) {
        wrappedLineStart--;
      }
      i2 = wrappedLineStart;
      lines.unshift(getXtermLineContent2(buffer, wrappedLineStart, wrappedLineEnd, cols));
      if (lines.length > linesToCheck) {
        lines.pop();
      }
    }
  } else {
    for (let i2 = startLine + (outputMatcher.offset || 0); i2 < endLine; i2++) {
      const wrappedLineStart = i2;
      let wrappedLineEnd = i2;
      while (wrappedLineEnd + 1 < endLine && buffer.getLine(wrappedLineEnd + 1)?.isWrapped) {
        wrappedLineEnd++;
      }
      i2 = wrappedLineEnd;
      lines.push(getXtermLineContent2(buffer, wrappedLineStart, wrappedLineEnd, cols));
      if (lines.length === linesToCheck) {
        lines.shift();
      }
    }
  }
  return lines;
}
function getXtermLineContent2(buffer, lineStart, lineEnd, cols) {
  const maxLineLength = Math.max(2048 / cols * 2);
  lineEnd = Math.min(lineEnd, lineStart + maxLineLength);
  let content = "";
  for (let i2 = lineStart; i2 <= lineEnd; i2++) {
    const line = buffer.getLine(i2);
    if (line) {
      content += line.translateToString(true, 0, cols);
    }
  }
  return content;
}
function cloneMarker(xterm, marker, offset = 0) {
  return xterm.registerMarker(marker.line - (xterm.buffer.active.baseY + xterm.buffer.active.cursorY) + offset);
}

// out-build/vs/platform/terminal/common/capabilities/cwdDetectionCapability.js
var $DPb = class extends $3c {
  constructor() {
    super(...arguments);
    this.type = 0;
    this.a = "";
    this.b = /* @__PURE__ */ new Map();
    this.c = this.B(new $ze());
    this.onDidChangeCwd = this.c.event;
  }
  /**
   * Gets the list of cwds seen in this session in order of last accessed.
   */
  get cwds() {
    return Array.from(this.b.keys());
  }
  getCwd() {
    return this.a;
  }
  updateCwd(cwd2) {
    const didChange = this.a !== cwd2;
    this.a = cwd2;
    const count = this.b.get(this.a) || 0;
    this.b.delete(this.a);
    this.b.set(this.a, count + 1);
    if (didChange) {
      this.c.fire(cwd2);
    }
  }
};

// out-build/vs/platform/terminal/common/capabilities/partialCommandDetectionCapability.js
var Constants12;
(function(Constants27) {
  Constants27[Constants27["MinimumPromptLength"] = 2] = "MinimumPromptLength";
})(Constants12 || (Constants12 = {}));
var $EPb = class extends $2c {
  get commands() {
    return this.a;
  }
  constructor(c) {
    super();
    this.c = c;
    this.type = 3;
    this.a = [];
    this.b = this.add(new $ze());
    this.onCommandFinished = this.b.event;
    this.add(this.c.onData((e) => this.h(e)));
    this.add(this.c.parser.registerCsiHandler({ final: "J" }, (params) => {
      if (params.length >= 1 && (params[0] === 2 || params[0] === 3)) {
        this.m();
      }
      return false;
    }));
  }
  h(data) {
    if (data === "\r") {
      this.j();
    }
  }
  j() {
    if (!this.c) {
      return;
    }
    if (this.c.buffer.active.cursorX >= 2) {
      const marker = this.c.registerMarker(0);
      if (marker) {
        this.a.push(marker);
        this.b.fire(marker);
      }
    }
  }
  m() {
    let count = 0;
    for (let i2 = this.a.length - 1; i2 >= 0; i2--) {
      if (this.a[i2].line < this.c.buffer.active.baseY) {
        break;
      }
      count++;
    }
    this.a.splice(this.a.length - count, count);
  }
};

// out-build/vs/platform/terminal/common/capabilities/bufferMarkCapability.js
var $FPb = class extends $3c {
  constructor(f) {
    super();
    this.f = f;
    this.type = 4;
    this.a = /* @__PURE__ */ new Map();
    this.b = /* @__PURE__ */ new Map();
    this.c = this.B(new $ze());
    this.onMarkAdded = this.c.event;
  }
  *markers() {
    for (const m of this.a.values()) {
      yield m;
    }
    for (const m of this.b.values()) {
      yield m;
    }
  }
  addMark(properties) {
    const marker = properties?.marker || this.f.registerMarker();
    const id2 = properties?.id;
    if (!marker) {
      return;
    }
    if (id2) {
      this.a.set(id2, marker);
      marker.onDispose(() => this.a.delete(id2));
    } else {
      this.b.set(marker.id, marker);
      marker.onDispose(() => this.b.delete(marker.id));
    }
    this.c.fire({ marker, id: id2, hidden: properties?.hidden, hoverMessage: properties?.hoverMessage });
  }
  getMark(id2) {
    return this.a.get(id2);
  }
};

// out-build/vs/platform/terminal/common/terminalEnvironment.js
function $pY(path) {
  let newPath = path;
  if (newPath.includes("\\")) {
    newPath = newPath.replace(/\\/g, "\\\\");
  }
  const bannedChars = /[\`\$\|\&\>\~\#\!\^\*\;\<\"\']/g;
  newPath = newPath.replace(bannedChars, "");
  return `'${newPath}'`;
}
function $qY(path, userHome, separator) {
  if (!path) {
    return "";
  }
  if (!userHome) {
    return path;
  }
  if (userHome.match(/[\/\\]$/)) {
    userHome = userHome.slice(0, userHome.length - 1);
  }
  const normalizedPath = path.replace(/\\/g, "/").toLowerCase();
  const normalizedUserHome = userHome.replace(/\\/g, "/").toLowerCase();
  if (!normalizedPath.includes(normalizedUserHome)) {
    return path;
  }
  return `~${separator}${path.slice(userHome.length + 1)}`;
}
function $rY(cwd2) {
  if (cwd2.match(/^['"].*['"]$/)) {
    cwd2 = cwd2.substring(1, cwd2.length - 1);
  }
  if (OS === 1 && cwd2 && cwd2[1] === ":") {
    return cwd2[0].toUpperCase() + cwd2.substring(1);
  }
  return cwd2;
}
function $sY(slc) {
  return !slc.strictEnv;
}

// out-build/vs/platform/terminal/common/xterm/shellIntegrationAddon.js
var ShellIntegrationOscPs;
(function(ShellIntegrationOscPs3) {
  ShellIntegrationOscPs3[ShellIntegrationOscPs3["FinalTerm"] = 133] = "FinalTerm";
  ShellIntegrationOscPs3[ShellIntegrationOscPs3["VSCode"] = 633] = "VSCode";
  ShellIntegrationOscPs3[ShellIntegrationOscPs3["ITerm"] = 1337] = "ITerm";
  ShellIntegrationOscPs3[ShellIntegrationOscPs3["SetCwd"] = 7] = "SetCwd";
  ShellIntegrationOscPs3[ShellIntegrationOscPs3["SetWindowsFriendlyCwd"] = 9] = "SetWindowsFriendlyCwd";
})(ShellIntegrationOscPs || (ShellIntegrationOscPs = {}));
var FinalTermOscPt;
(function(FinalTermOscPt2) {
  FinalTermOscPt2["PromptStart"] = "A";
  FinalTermOscPt2["CommandStart"] = "B";
  FinalTermOscPt2["CommandExecuted"] = "C";
  FinalTermOscPt2["CommandFinished"] = "D";
})(FinalTermOscPt || (FinalTermOscPt = {}));
var VSCodeOscPt;
(function(VSCodeOscPt3) {
  VSCodeOscPt3["PromptStart"] = "A";
  VSCodeOscPt3["CommandStart"] = "B";
  VSCodeOscPt3["CommandExecuted"] = "C";
  VSCodeOscPt3["CommandFinished"] = "D";
  VSCodeOscPt3["CommandLine"] = "E";
  VSCodeOscPt3["ContinuationStart"] = "F";
  VSCodeOscPt3["ContinuationEnd"] = "G";
  VSCodeOscPt3["RightPromptStart"] = "H";
  VSCodeOscPt3["RightPromptEnd"] = "I";
  VSCodeOscPt3["Property"] = "P";
  VSCodeOscPt3["SetMark"] = "SetMark";
})(VSCodeOscPt || (VSCodeOscPt = {}));
var ITermOscPt;
(function(ITermOscPt3) {
  ITermOscPt3["SetMark"] = "SetMark";
  ITermOscPt3["CurrentDir"] = "CurrentDir";
})(ITermOscPt || (ITermOscPt = {}));
var $GPb = class extends $3c {
  get status() {
    return this.g;
  }
  constructor(j, m, n, r2) {
    super();
    this.j = j;
    this.m = m;
    this.n = n;
    this.r = r2;
    this.capabilities = this.B(new $zPb());
    this.b = false;
    this.f = [];
    this.g = 0;
    this.h = new $ze();
    this.onDidChangeStatus = this.h.event;
    this.B($1c(() => {
      this.z();
      this.s();
    }));
  }
  s() {
    $Xc(this.f);
    this.f.length = 0;
  }
  activate(xterm) {
    this.a = xterm;
    this.capabilities.add(3, this.B(new $EPb(this.a)));
    this.B(xterm.parser.registerOscHandler(633, (data) => this.w(data)));
    this.B(xterm.parser.registerOscHandler(1337, (data) => this.H(data)));
    this.f.push(xterm.parser.registerOscHandler(133, (data) => this.t(data)));
    this.B(xterm.parser.registerOscHandler(7, (data) => this.J(data)));
    this.B(xterm.parser.registerOscHandler(9, (data) => this.I(data)));
    this.y();
  }
  getMarkerId(terminal2, vscodeMarkerId) {
    this.N(terminal2).getMark(vscodeMarkerId);
  }
  t(data) {
    const didHandle = this.u(data);
    if (this.g === 0) {
      this.g = 1;
      this.h.fire(this.g);
    }
    return didHandle;
  }
  u(data) {
    if (!this.a) {
      return false;
    }
    const [command4, ...args2] = data.split(";");
    switch (command4) {
      case "A":
        this.M(this.a).handlePromptStart();
        return true;
      case "B":
        this.M(this.a).handleCommandStart({ ignoreCommandLine: true });
        return true;
      case "C":
        this.M(this.a).handleCommandExecuted();
        return true;
      case "D": {
        const exitCode = args2.length === 1 ? parseInt(args2[0]) : void 0;
        this.M(this.a).handleCommandFinished(exitCode);
        return true;
      }
    }
    return false;
  }
  w(data) {
    const didHandle = this.C(data);
    if (!this.b && didHandle) {
      this.n?.publicLog2("terminal/shellIntegrationActivationSucceeded");
      this.b = true;
      this.z();
    }
    if (this.g !== 2) {
      this.g = 2;
      this.h.fire(this.g);
    }
    return didHandle;
  }
  async y() {
    if (!this.n || this.m) {
      return;
    }
    this.c = setTimeout(() => {
      if (!this.capabilities.get(
        2
        /* TerminalCapability.CommandDetection */
      ) && !this.capabilities.get(
        0
        /* TerminalCapability.CwdDetection */
      )) {
        this.n?.publicLog2("terminal/shellIntegrationActivationTimeout");
        this.r.warn("Shell integration failed to add capabilities within 10 seconds");
      }
      this.b = true;
    }, 1e4);
  }
  z() {
    if (this.c !== void 0) {
      clearTimeout(this.c);
      this.c = void 0;
    }
  }
  C(data) {
    if (!this.a) {
      return false;
    }
    const argsIndex = data.indexOf(";");
    const sequenceCommand = argsIndex === -1 ? data : data.substring(0, argsIndex);
    const args2 = argsIndex === -1 ? [] : data.substring(argsIndex + 1).split(";");
    switch (sequenceCommand) {
      case "A":
        this.M(this.a).handlePromptStart();
        return true;
      case "B":
        this.M(this.a).handleCommandStart();
        return true;
      case "C":
        this.M(this.a).handleCommandExecuted();
        return true;
      case "D": {
        const arg0 = args2[0];
        const exitCode = arg0 !== void 0 ? parseInt(arg0) : void 0;
        this.M(this.a).handleCommandFinished(exitCode);
        return true;
      }
      case "E": {
        const arg0 = args2[0];
        const arg1 = args2[1];
        let commandLine;
        if (arg0 !== void 0) {
          commandLine = $HPb(arg0);
        } else {
          commandLine = "";
        }
        this.M(this.a).setCommandLine(commandLine, arg1 === this.j);
        return true;
      }
      case "F": {
        this.M(this.a).handleContinuationStart();
        return true;
      }
      case "G": {
        this.M(this.a).handleContinuationEnd();
        return true;
      }
      case "H": {
        this.M(this.a).handleRightPromptStart();
        return true;
      }
      case "I": {
        this.M(this.a).handleRightPromptEnd();
        return true;
      }
      case "P": {
        const arg0 = args2[0];
        const deserialized = arg0 !== void 0 ? $HPb(arg0) : "";
        const { key: key2, value } = $IPb(deserialized);
        if (value === void 0) {
          return true;
        }
        switch (key2) {
          case "ContinuationPrompt": {
            this.D($lg(value));
            return true;
          }
          case "Cwd": {
            this.G(value);
            return true;
          }
          case "IsWindows": {
            this.M(this.a).setIsWindowsPty(value === "True" ? true : false);
            return true;
          }
          case "Prompt": {
            const sanitizedValue = value.replace(/\x1b\[[0-9;]*m/g, "");
            this.F(sanitizedValue);
            return true;
          }
          case "Task": {
            this.N(this.a);
            this.capabilities.get(
              2
              /* TerminalCapability.CommandDetection */
            )?.setIsCommandStorageDisabled();
            return true;
          }
        }
      }
      case "SetMark": {
        this.N(this.a).addMark($JPb(args2));
        return true;
      }
    }
    return false;
  }
  D(value) {
    if (!this.a) {
      return;
    }
    this.M(this.a).setContinuationPrompt(value);
  }
  F(prompt) {
    if (!this.a) {
      return;
    }
    const lastPromptLine = prompt.substring(prompt.lastIndexOf("\n") + 1);
    const promptTerminator = lastPromptLine.substring(lastPromptLine.lastIndexOf(" "));
    if (promptTerminator) {
      this.M(this.a).setPromptTerminator(promptTerminator, lastPromptLine);
    }
  }
  G(value) {
    value = $rY(value);
    this.L().updateCwd(value);
    const commandDetection = this.capabilities.get(
      2
      /* TerminalCapability.CommandDetection */
    );
    commandDetection?.setCwd(value);
  }
  H(data) {
    if (!this.a) {
      return false;
    }
    const [command4] = data.split(";");
    switch (command4) {
      case "SetMark": {
        this.N(this.a).addMark();
      }
      default: {
        const { key: key2, value } = $IPb(command4);
        if (value === void 0) {
          return true;
        }
        switch (key2) {
          case "CurrentDir":
            this.G(value);
            return true;
        }
      }
    }
    return false;
  }
  I(data) {
    if (!this.a) {
      return false;
    }
    const [command4, ...args2] = data.split(";");
    switch (command4) {
      case "9":
        if (args2.length) {
          this.G(args2[0]);
        }
        return true;
    }
    return false;
  }
  /**
   * Handles the sequence: `OSC 7 ; scheme://cwd ST`
   */
  J(data) {
    if (!this.a) {
      return false;
    }
    const [command4] = data.split(";");
    if (command4.match(/^file:\/\/.*\//)) {
      const uri = URI.parse(command4);
      if (uri.path && uri.path.length > 0) {
        this.G(uri.path);
        return true;
      }
    }
    return false;
  }
  serialize() {
    if (!this.a || !this.capabilities.has(
      2
      /* TerminalCapability.CommandDetection */
    )) {
      return {
        isWindowsPty: false,
        commands: [],
        promptInputModel: void 0
      };
    }
    const result = this.M(this.a).serialize();
    return result;
  }
  deserialize(serialized) {
    if (!this.a) {
      throw new Error("Cannot restore commands before addon is activated");
    }
    this.M(this.a).deserialize(serialized);
  }
  L() {
    let cwdDetection = this.capabilities.get(
      0
      /* TerminalCapability.CwdDetection */
    );
    if (!cwdDetection) {
      cwdDetection = this.B(new $DPb());
      this.capabilities.add(0, cwdDetection);
    }
    return cwdDetection;
  }
  M(terminal2) {
    let commandDetection = this.capabilities.get(
      2
      /* TerminalCapability.CommandDetection */
    );
    if (!commandDetection) {
      commandDetection = this.B(new $BPb(terminal2, this.r));
      this.capabilities.add(2, commandDetection);
    }
    return commandDetection;
  }
  N(terminal2) {
    let bufferMarkDetection = this.capabilities.get(
      4
      /* TerminalCapability.BufferMarkDetection */
    );
    if (!bufferMarkDetection) {
      bufferMarkDetection = this.B(new $FPb(terminal2));
      this.capabilities.add(4, bufferMarkDetection);
    }
    return bufferMarkDetection;
  }
};
function $HPb(message) {
  return message.replaceAll(
    // Backslash ('\') followed by an escape operator: either another '\', or 'x' and two hex chars.
    /\\(\\|x([0-9a-f]{2}))/gi,
    // If it's a hex value, parse it to a character.
    // Otherwise the operator is '\', which we return literally, now unescaped.
    (_match, op, hex) => hex ? String.fromCharCode(parseInt(hex, 16)) : op
  );
}
function $IPb(message) {
  const separatorIndex = message.indexOf("=");
  if (separatorIndex === -1) {
    return { key: message, value: void 0 };
  }
  return {
    key: message.substring(0, separatorIndex),
    value: message.substring(1 + separatorIndex)
  };
}
function $JPb(sequence) {
  let id2 = void 0;
  let hidden = false;
  for (const property of sequence) {
    if (property === void 0) {
      continue;
    }
    if (property === "Hidden") {
      hidden = true;
    }
    if (property.startsWith("Id=")) {
      id2 = property.substring(3);
    }
  }
  return { id: id2, hidden };
}

// out-build/vs/workbench/contrib/terminal/browser/terminalIcons.js
var $KPb = $9r("terminal-view-icon", $6l.terminal, localize(10447, null));
var $LPb = $9r("terminal-rename", $6l.edit, localize(10448, null));
var $MPb = $9r("terminal-kill", $6l.trash, localize(10449, null));
var $NPb = $9r("terminal-new", $6l.add, localize(10450, null));
var $OPb = $9r("terminal-configure-profile", $6l.gear, localize(10451, null));
var $PPb = $9r("terminal-decoration-mark", $6l.circleSmallFilled, localize(10452, null));
var $QPb = $9r("terminal-decoration-incomplete", $6l.circle, localize(10453, null));
var $RPb = $9r("terminal-decoration-error", $6l.errorSmall, localize(10454, null));
var $SPb = $9r("terminal-decoration-success", $6l.circleFilled, localize(10455, null));
var $TPb = $9r("terminal-command-history-remove", $6l.close, localize(10456, null));
var $UPb = $9r("terminal-command-history-output", $6l.output, localize(10457, null));
var $VPb = $9r("terminal-command-history-fuzzy-search", $6l.searchFuzzy, localize(10458, null));
var $WPb = $9r("terminal-command-history-open-file", $6l.symbolReference, localize(10459, null));

// out-build/vs/workbench/contrib/terminal/browser/xterm/decorationStyles.js
var DecorationStyles2;
(function(DecorationStyles3) {
  DecorationStyles3[DecorationStyles3["DefaultDimension"] = 16] = "DefaultDimension";
  DecorationStyles3[DecorationStyles3["MarginLeft"] = -17] = "MarginLeft";
})(DecorationStyles2 || (DecorationStyles2 = {}));
var DecorationSelector;
(function(DecorationSelector2) {
  DecorationSelector2["CommandDecoration"] = "terminal-command-decoration";
  DecorationSelector2["Hide"] = "hide";
  DecorationSelector2["ErrorColor"] = "error";
  DecorationSelector2["DefaultColor"] = "default-color";
  DecorationSelector2["Default"] = "default";
  DecorationSelector2["Codicon"] = "codicon";
  DecorationSelector2["XtermDecoration"] = "xterm-decoration";
  DecorationSelector2["OverviewRuler"] = ".xterm-decoration-overview-ruler";
})(DecorationSelector || (DecorationSelector = {}));
function $XPb(command4, hoverMessage) {
  let hoverContent = `${localize(10568, null)}`;
  hoverContent += "\n\n---\n\n";
  if (!command4) {
    if (hoverMessage) {
      hoverContent = hoverMessage;
    } else {
      return "";
    }
  } else if (command4.markProperties || hoverMessage) {
    if (command4.markProperties?.hoverMessage || hoverMessage) {
      hoverContent = command4.markProperties?.hoverMessage || hoverMessage || "";
    } else {
      return "";
    }
  } else {
    if (command4.duration) {
      const durationText = $Su(command4.duration);
      if (command4.exitCode) {
        if (command4.exitCode === -1) {
          hoverContent += localize(10569, null, $Qu(command4.timestamp, true), durationText);
        } else {
          hoverContent += localize(10570, null, $Qu(command4.timestamp, true), durationText, command4.exitCode);
        }
      } else {
        hoverContent += localize(10571, null, $Qu(command4.timestamp, true), durationText);
      }
    } else {
      if (command4.exitCode) {
        if (command4.exitCode === -1) {
          hoverContent += localize(10572, null, $Qu(command4.timestamp, true));
        } else {
          hoverContent += localize(10573, null, $Qu(command4.timestamp, true), command4.exitCode);
        }
      } else {
        hoverContent += localize(10574, null, $Qu(command4.timestamp, true));
      }
    }
  }
  return hoverContent;
}
function $YPb(configurationService, element) {
  if (!element) {
    return;
  }
  const fontSize = configurationService.inspect(
    "terminal.integrated.fontSize"
    /* TerminalSettingId.FontSize */
  ).value;
  const defaultFontSize = configurationService.inspect(
    "terminal.integrated.fontSize"
    /* TerminalSettingId.FontSize */
  ).defaultValue;
  const lineHeight = configurationService.inspect(
    "terminal.integrated.lineHeight"
    /* TerminalSettingId.LineHeight */
  ).value;
  if (typeof fontSize === "number" && typeof defaultFontSize === "number" && typeof lineHeight === "number") {
    const scalar = fontSize / defaultFontSize <= 1 ? fontSize / defaultFontSize : 1;
    element.style.width = `${scalar * 16}px`;
    element.style.height = `${scalar * 16 * lineHeight}px`;
    element.style.fontSize = `${scalar * 16}px`;
    element.style.marginLeft = `${scalar * -17}px`;
  }
}

// out-build/vs/workbench/contrib/terminal/browser/xterm/decorationAddon.js
var $ZPb = class $ZPb2 extends $3c {
  constructor(t, u, w, y, z, C, D, lifecycleService, F, G, H, I) {
    super();
    this.t = t;
    this.u = u;
    this.w = w;
    this.y = y;
    this.z = z;
    this.C = C;
    this.D = D;
    this.F = F;
    this.G = G;
    this.H = H;
    this.I = I;
    this.b = /* @__PURE__ */ new Map();
    this.f = /* @__PURE__ */ new Map();
    this.m = /* @__PURE__ */ new Map();
    this.n = this.B(new $ze());
    this.onDidRequestRunCommand = this.n.event;
    this.s = this.B(new $ze());
    this.onDidRequestCopyAsHtml = this.s.event;
    this.B($1c(() => this.R()));
    this.B(this.y.onDidChangeConfiguration((e) => {
      if (e.affectsConfiguration(
        "terminal.integrated.fontSize"
        /* TerminalSettingId.FontSize */
      ) || e.affectsConfiguration(
        "terminal.integrated.lineHeight"
        /* TerminalSettingId.LineHeight */
      )) {
        this.refreshLayouts();
      } else if (e.affectsConfiguration("workbench.colorCustomizations")) {
        this.Q(true);
      } else if (e.affectsConfiguration(
        "terminal.integrated.shellIntegration.decorationsEnabled"
        /* TerminalSettingId.ShellIntegrationDecorationsEnabled */
      )) {
        this.J(
          2
          /* TerminalCapability.CommandDetection */
        );
        this.M();
      }
    }));
    this.B(this.z.onDidColorThemeChange(() => this.Q(true)));
    this.M();
    this.B(this.t.onDidAddCapabilityType((c) => this.L(c)));
    this.B(this.t.onDidRemoveCapabilityType((c) => this.J(c)));
    this.B(lifecycleService.onWillShutdown(() => this.N()));
  }
  J(c) {
    const disposables = this.b.get(c);
    if (disposables) {
      $Xc(disposables);
    }
    this.b.delete(c);
  }
  L(c) {
    const store = new $2c();
    const capability = this.t.get(c);
    if (!capability || this.b.has(c)) {
      return;
    }
    switch (capability.type) {
      case 4:
        store.add(capability.onMarkAdded((mark) => this.registerMarkDecoration(mark)));
        break;
      case 2: {
        const disposables = this.W(capability);
        for (const d of disposables) {
          store.add(d);
        }
        break;
      }
    }
    this.b.set(c, store);
  }
  registerMarkDecoration(mark) {
    if (!this.a || !this.h && !this.j) {
      return void 0;
    }
    if (mark.hidden) {
      return void 0;
    }
    return this.registerCommandDecoration(void 0, void 0, mark);
  }
  M() {
    const showDecorations = this.y.getValue(
      "terminal.integrated.shellIntegration.decorationsEnabled"
      /* TerminalSettingId.ShellIntegrationDecorationsEnabled */
    );
    this.h = showDecorations === "both" || showDecorations === "gutter";
    this.j = showDecorations === "both" || showDecorations === "overviewRuler";
    this.N();
    if (this.h || this.j) {
      this.U();
      this.O();
    }
    const currentCommand = this.t.get(
      2
      /* TerminalCapability.CommandDetection */
    )?.executingCommandObject;
    if (currentCommand) {
      this.registerCommandDecoration(currentCommand, true);
    }
  }
  N() {
    this.g?.dispose();
    for (const value of this.f.values()) {
      value.decoration.dispose();
      $Xc(value.disposables);
    }
  }
  O() {
    const commandDecorationElements = this.a?.element?.querySelectorAll(
      "terminal-command-decoration"
      /* DecorationSelector.CommandDecoration */
    );
    if (commandDecorationElements) {
      for (const commandDecorationElement of commandDecorationElements) {
        this.P(commandDecorationElement);
      }
    }
  }
  P(commandDecorationElement) {
    if (this.h) {
      commandDecorationElement.classList.remove(
        "hide"
        /* DecorationSelector.Hide */
      );
    } else {
      commandDecorationElement.classList.add(
        "hide"
        /* DecorationSelector.Hide */
      );
    }
  }
  refreshLayouts() {
    $YPb(this.y, this.g?.element);
    for (const decoration3 of this.f) {
      $YPb(this.y, decoration3[1].decoration.element);
    }
  }
  Q(refreshOverviewRulerColors) {
    if (refreshOverviewRulerColors) {
      for (const decoration3 of this.f.values()) {
        const color2 = this.db(decoration3)?.toString() ?? "";
        if (decoration3.decoration.options?.overviewRulerOptions) {
          decoration3.decoration.options.overviewRulerOptions.color = color2;
        } else if (decoration3.decoration.options) {
          decoration3.decoration.options.overviewRulerOptions = { color: color2 };
        }
      }
    }
    this.Z(this.g?.element);
    for (const decoration3 of this.f.values()) {
      this.Z(decoration3.decoration.element, decoration3.exitCode, decoration3.markProperties);
    }
  }
  R() {
    for (const disposable of this.b.values()) {
      $Xc(disposable);
    }
    this.clearDecorations();
  }
  S() {
    this.g?.dispose();
    this.g = void 0;
  }
  clearDecorations() {
    this.g?.marker.dispose();
    this.S();
    this.N();
    this.f.clear();
  }
  U() {
    if (this.t.has(
      2
      /* TerminalCapability.CommandDetection */
    )) {
      const capability = this.t.get(
        2
        /* TerminalCapability.CommandDetection */
      );
      const disposables = this.W(capability);
      const store = new $2c();
      for (const d of disposables) {
        store.add(d);
      }
      this.b.set(2, store);
    }
  }
  W(capability) {
    if (this.b.has(
      2
      /* TerminalCapability.CommandDetection */
    )) {
      const disposables = this.b.get(
        2
        /* TerminalCapability.CommandDetection */
      );
      $Xc(disposables);
      this.b.delete(capability.type);
    }
    const commandDetectionListeners = [];
    if (capability.executingCommandObject?.marker) {
      this.registerCommandDecoration(capability.executingCommandObject, true);
    }
    commandDetectionListeners.push(capability.onCommandStarted((command4) => this.registerCommandDecoration(command4, true)));
    for (const command4 of capability.commands) {
      this.registerCommandDecoration(command4);
    }
    commandDetectionListeners.push(capability.onCommandFinished((command4) => {
      this.registerCommandDecoration(command4);
      if (command4.exitCode) {
        this.G.playSignal($N9.terminalCommandFailed);
      } else {
        this.G.playSignal($N9.terminalCommandSucceeded);
      }
    }));
    commandDetectionListeners.push(capability.onCommandInvalidated((commands2) => {
      for (const command4 of commands2) {
        const id2 = command4.marker?.id;
        if (id2) {
          const match = this.f.get(id2);
          if (match) {
            match.decoration.dispose();
            $Xc(match.disposables);
          }
        }
      }
    }));
    commandDetectionListeners.push(capability.onCurrentCommandInvalidated((request) => {
      if (request.reason === "noProblemsReported") {
        const lastDecoration = Array.from(this.f.entries())[this.f.size - 1];
        lastDecoration?.[1].decoration.dispose();
      } else if (request.reason === "windows") {
        this.S();
      }
    }));
    return commandDetectionListeners;
  }
  activate(terminal2) {
    this.a = terminal2;
    this.U();
  }
  registerCommandDecoration(command4, beforeCommandExecution, markProperties) {
    if (!this.a || beforeCommandExecution && !command4 || !this.h && !this.j) {
      return void 0;
    }
    const marker = command4?.marker || markProperties?.marker;
    if (!marker) {
      throw new Error(`cannot add a decoration for a command ${JSON.stringify(command4)} with no marker`);
    }
    this.S();
    const color2 = this.db(command4)?.toString() ?? "";
    const decoration3 = this.a.registerDecoration({
      marker,
      overviewRulerOptions: this.j ? beforeCommandExecution ? { color: color2, position: "left" } : { color: color2, position: command4?.exitCode ? "right" : "left" } : void 0
    });
    if (!decoration3) {
      return void 0;
    }
    if (beforeCommandExecution) {
      this.g = decoration3;
    }
    decoration3.onRender((element) => {
      if (element.classList.contains(
        ".xterm-decoration-overview-ruler"
        /* DecorationSelector.OverviewRuler */
      )) {
        return;
      }
      if (!this.f.get(decoration3.marker.id)) {
        decoration3.onDispose(() => this.f.delete(decoration3.marker.id));
        this.f.set(decoration3.marker.id, {
          decoration: decoration3,
          disposables: this.X(element, command4, markProperties),
          exitCode: command4?.exitCode,
          markProperties: command4?.markProperties
        });
      }
      if (!element.classList.contains(
        "codicon"
        /* DecorationSelector.Codicon */
      ) || command4?.marker?.line === 0) {
        $YPb(this.y, element);
        this.Z(element, command4?.exitCode, command4?.markProperties || markProperties);
      }
    });
    return decoration3;
  }
  registerMenuItems(command4, items) {
    const existingItems = this.m.get(command4);
    if (existingItems) {
      existingItems.push(...items);
    } else {
      this.m.set(command4, [...items]);
    }
    return $1c(() => {
      const commandItems = this.m.get(command4);
      if (commandItems) {
        for (const item of items.values()) {
          const index = commandItems.indexOf(item);
          if (index !== -1) {
            commandItems.splice(index, 1);
          }
        }
      }
    });
  }
  X(element, command4, markProperties) {
    if (command4?.exitCode === void 0 && !command4?.markProperties) {
      return [];
    } else if (command4?.markProperties || markProperties) {
      return [this.Y(element, command4 || markProperties, markProperties?.hoverMessage)];
    }
    return [...this.$(element, command4), this.Y(element, command4)];
  }
  Y(element, command4, hoverMessage) {
    return this.I.setupDelayedHover(element, () => ({
      content: new $bm($XPb(command4, hoverMessage))
    }));
  }
  Z(element, exitCode, markProperties) {
    if (!element) {
      return;
    }
    for (const classes2 of element.classList) {
      element.classList.remove(classes2);
    }
    element.classList.add(
      "terminal-command-decoration",
      "codicon",
      "xterm-decoration"
      /* DecorationSelector.XtermDecoration */
    );
    if (markProperties) {
      element.classList.add("default-color", ...ThemeIcon.asClassNameArray($PPb));
      if (!markProperties.hoverMessage) {
        element.classList.add(
          "default"
          /* DecorationSelector.Default */
        );
      }
    } else {
      this.P(element);
      if (exitCode === void 0) {
        element.classList.add(
          "default-color",
          "default"
          /* DecorationSelector.Default */
        );
        element.classList.add(...ThemeIcon.asClassNameArray($QPb));
      } else if (exitCode) {
        element.classList.add(
          "error"
          /* DecorationSelector.ErrorColor */
        );
        element.classList.add(...ThemeIcon.asClassNameArray($RPb));
      } else {
        element.classList.add(...ThemeIcon.asClassNameArray($SPb));
      }
    }
  }
  $(element, command4) {
    return [
      $_i(element, $7j.MOUSE_DOWN, async (e) => {
        e.stopImmediatePropagation();
      }),
      $_i(element, $7j.CLICK, async (e) => {
        e.stopImmediatePropagation();
        const actions = await this.bb(command4);
        this.w.showContextMenu({ getAnchor: () => element, getActions: () => actions });
      }),
      $_i(element, $7j.CONTEXT_MENU, async (e) => {
        e.stopImmediatePropagation();
        const actions = this.ab();
        this.w.showContextMenu({ getAnchor: () => element, getActions: () => actions });
      })
    ];
  }
  ab() {
    const label3 = localize(10553, null);
    return [
      {
        class: void 0,
        tooltip: label3,
        id: "terminal.toggleVisibility",
        label: label3,
        enabled: true,
        run: async () => {
          this.cb();
        }
      }
    ];
  }
  async bb(command4) {
    const actions = [];
    const registeredMenuItems = this.m.get(command4);
    if (registeredMenuItems?.length) {
      actions.push(...registeredMenuItems, new $Wm());
    }
    if (command4.command !== "") {
      const labelRun = localize(10554, null);
      actions.push({
        class: void 0,
        tooltip: labelRun,
        id: "terminal.rerunCommand",
        label: labelRun,
        enabled: true,
        run: async () => {
          if (command4.command === "") {
            return;
          }
          if (!command4.isTrusted) {
            const shouldRun = await new Promise((r2) => {
              this.H.prompt(Severity2.Info, localize(10555, null, command4.command), [{
                label: localize(10556, null),
                run: () => r2(true)
              }, {
                label: localize(10557, null),
                run: () => r2(false)
              }]);
            });
            if (!shouldRun) {
              return;
            }
          }
          this.n.fire({ command: command4 });
        }
      });
      actions.push(new $Wm());
      const labelCopy = localize(10558, null);
      actions.push({
        class: void 0,
        tooltip: labelCopy,
        id: "terminal.copyCommand",
        label: labelCopy,
        enabled: true,
        run: () => this.u.writeText(command4.command)
      });
    }
    if (command4.hasOutput()) {
      const labelCopyCommandAndOutput = localize(10559, null);
      actions.push({
        class: void 0,
        tooltip: labelCopyCommandAndOutput,
        id: "terminal.copyCommandAndOutput",
        label: labelCopyCommandAndOutput,
        enabled: true,
        run: () => {
          const output = command4.getOutput();
          if (typeof output === "string") {
            this.u.writeText(`${command4.command !== "" ? command4.command + "\n" : ""}${output}`);
          }
        }
      });
      const labelText = localize(10560, null);
      actions.push({
        class: void 0,
        tooltip: labelText,
        id: "terminal.copyOutput",
        label: labelText,
        enabled: true,
        run: () => {
          const text2 = command4.getOutput();
          if (typeof text2 === "string") {
            this.u.writeText(text2);
          }
        }
      });
      const labelHtml = localize(10561, null);
      actions.push({
        class: void 0,
        tooltip: labelHtml,
        id: "terminal.copyOutputAsHtml",
        label: labelHtml,
        enabled: true,
        run: () => this.s.fire({ command: command4 })
      });
    }
    if (actions.length > 0) {
      actions.push(new $Wm());
    }
    const labelRunRecent = localize(10562, null);
    actions.push({
      class: void 0,
      tooltip: labelRunRecent,
      id: "workbench.action.terminal.runRecentCommand",
      label: labelRunRecent,
      enabled: true,
      run: () => this.F.executeCommand("workbench.action.terminal.runRecentCommand")
    });
    const labelGoToRecent = localize(10563, null);
    actions.push({
      class: void 0,
      tooltip: labelRunRecent,
      id: "workbench.action.terminal.goToRecentDirectory",
      label: labelGoToRecent,
      enabled: true,
      run: () => this.F.executeCommand("workbench.action.terminal.goToRecentDirectory")
    });
    actions.push(new $Wm());
    const labelAbout = localize(10564, null);
    actions.push({
      class: void 0,
      tooltip: labelAbout,
      id: "terminal.learnShellIntegration",
      label: labelAbout,
      enabled: true,
      run: () => this.C.open("https://code.visualstudio.com/docs/terminal/shell-integration")
    });
    return actions;
  }
  cb() {
    const quickPick = this.B(this.D.createQuickPick());
    quickPick.hideInput = true;
    quickPick.hideCheckAll = true;
    quickPick.canSelectMany = true;
    quickPick.title = localize(10565, null);
    const configValue = this.y.getValue(
      "terminal.integrated.shellIntegration.decorationsEnabled"
      /* TerminalSettingId.ShellIntegrationDecorationsEnabled */
    );
    const gutterIcon = {
      label: localize(10566, null),
      picked: configValue !== "never" && configValue !== "overviewRuler"
    };
    const overviewRulerIcon = {
      label: localize(10567, null),
      picked: configValue !== "never" && configValue !== "gutter"
    };
    quickPick.items = [gutterIcon, overviewRulerIcon];
    const selectedItems = [];
    if (configValue !== "never") {
      if (configValue !== "gutter") {
        selectedItems.push(gutterIcon);
      }
      if (configValue !== "overviewRuler") {
        selectedItems.push(overviewRulerIcon);
      }
    }
    quickPick.selectedItems = selectedItems;
    this.B(quickPick.onDidChangeSelection(async (e) => {
      let newValue = "never";
      if (e.includes(gutterIcon)) {
        if (e.includes(overviewRulerIcon)) {
          newValue = "both";
        } else {
          newValue = "gutter";
        }
      } else if (e.includes(overviewRulerIcon)) {
        newValue = "overviewRuler";
      }
      await this.y.updateValue("terminal.integrated.shellIntegration.decorationsEnabled", newValue);
    }));
    quickPick.ok = false;
    quickPick.show();
  }
  db(decorationOrCommand) {
    let colorId;
    if (decorationOrCommand?.exitCode === void 0) {
      colorId = $fPb;
    } else {
      colorId = decorationOrCommand.exitCode ? $hPb : $gPb;
    }
    return this.z.getColorTheme().getColor(colorId)?.toString();
  }
};
$ZPb = __decorate([
  __param(1, $30),
  __param(2, $50),
  __param(3, $kl),
  __param(4, $gs),
  __param(5, $O4),
  __param(6, $1M),
  __param(7, $KL),
  __param(8, $sn),
  __param(9, $I9),
  __param(10, $PJ),
  __param(11, $5$)
], $ZPb);

// out-build/vs/workbench/contrib/terminal/browser/xterm/xtermAddonImporter.js
var importedAddons = /* @__PURE__ */ new Map();
var $1Pb = class {
  async importAddon(name) {
    let addon = importedAddons.get(name);
    if (!addon) {
      switch (name) {
        case "clipboard":
          addon = (await $sJ("@xterm/addon-clipboard", "lib/addon-clipboard.js")).ClipboardAddon;
          break;
        case "image":
          addon = (await $sJ("@xterm/addon-image", "lib/addon-image.js")).ImageAddon;
          break;
        case "ligatures":
          addon = (await $sJ("@xterm/addon-ligatures", "lib/addon-ligatures.js")).LigaturesAddon;
          break;
        case "search":
          addon = (await $sJ("@xterm/addon-search", "lib/addon-search.js")).SearchAddon;
          break;
        case "serialize":
          addon = (await $sJ("@xterm/addon-serialize", "lib/addon-serialize.js")).SerializeAddon;
          break;
        case "unicode11":
          addon = (await $sJ("@xterm/addon-unicode11", "lib/addon-unicode11.js")).Unicode11Addon;
          break;
        case "webgl":
          addon = (await $sJ("@xterm/addon-webgl", "lib/addon-webgl.js")).WebglAddon;
          break;
      }
      if (!addon) {
        throw new Error(`Could not load addon ${name}`);
      }
      importedAddons.set(name, addon);
    }
    return addon;
  }
};

// out-build/vs/workbench/contrib/terminal/browser/xterm/xtermTerminal.js
var $2Pb_1;
var RenderConstants;
(function(RenderConstants2) {
  RenderConstants2[RenderConstants2["SmoothScrollDuration"] = 125] = "SmoothScrollDuration";
})(RenderConstants || (RenderConstants = {}));
function getFullBufferLineAsString(lineIndex, buffer) {
  let line = buffer.getLine(lineIndex);
  if (!line) {
    return { lineData: void 0, lineIndex };
  }
  let lineData = line.translateToString(true);
  while (lineIndex > 0 && line.isWrapped) {
    line = buffer.getLine(--lineIndex);
    if (!line) {
      break;
    }
    lineData = line.translateToString(false) + lineData;
  }
  return { lineData, lineIndex };
}
var $2Pb = class $2Pb2 extends $3c {
  static {
    $2Pb_1 = this;
  }
  static {
    this.g = void 0;
  }
  static {
    this.h = false;
  }
  get findResult() {
    return this.J;
  }
  get isStdinDisabled() {
    return !!this.raw.options.disableStdin;
  }
  get isGpuAccelerated() {
    return !!this.z;
  }
  get markTracker() {
    return this.n;
  }
  get shellIntegration() {
    return this.r;
  }
  get decorationAddon() {
    return this.s;
  }
  get textureAtlas() {
    const canvas = this.z?.textureAtlas;
    if (!canvas) {
      return void 0;
    }
    return createImageBitmap(canvas);
  }
  get isFocused() {
    if (!this.raw.element) {
      return false;
    }
    return $Nj(this.raw.element);
  }
  /**
   * @param xtermCtor The xterm.js constructor, this is passed in so it can be fetched lazily
   * outside of this class such that {@link raw} is not nullable.
   */
  constructor(xtermCtor, options3, S, U, W, X, Y, Z, $149, ab, contextKeyService, bb, layoutService) {
    super();
    this.S = S;
    this.U = U;
    this.W = W;
    this.X = X;
    this.Y = Y;
    this.Z = Z;
    this.$ = $149;
    this.ab = ab;
    this.bb = bb;
    this.m = $yZ.INSTANCE.isPhysicalMouseWheel();
    this.F = this.B(new $4c());
    this.G = this.B(new $2c());
    this.L = this.B(new $ze());
    this.onDidRequestRunCommand = this.L.event;
    this.M = this.B(new $ze());
    this.onDidRequestCopyAsHtml = this.M.event;
    this.N = this.B(new $ze());
    this.onDidRequestRefreshDimensions = this.N.event;
    this.O = this.B(new $ze());
    this.onDidChangeFindResults = this.O.event;
    this.P = this.B(new $ze());
    this.onDidChangeSelection = this.P.event;
    this.Q = this.B(new $ze());
    this.onDidChangeFocus = this.Q.event;
    this.R = this.B(new $ze());
    this.onDidDispose = this.R.event;
    this.b = options3.xtermAddonImporter ?? new $1Pb();
    this.c = options3.xtermColorProvider;
    this.f = options3.capabilities;
    const font = this.$.getFont($Qj(), void 0, true);
    const config = this.$.config;
    const editorOptions2 = this.S.getValue("editor");
    this.raw = this.B(new xtermCtor({
      allowProposedApi: true,
      cols: options3.cols,
      rows: options3.rows,
      documentOverride: layoutService.mainContainer.ownerDocument,
      altClickMovesCursor: config.altClickMovesCursor && editorOptions2.multiCursorModifier === "alt",
      scrollback: config.scrollback,
      theme: this.getXtermTheme(),
      drawBoldTextInBrightColors: config.drawBoldTextInBrightColors,
      fontFamily: font.fontFamily,
      fontWeight: config.fontWeight,
      fontWeightBold: config.fontWeightBold,
      fontSize: font.fontSize,
      letterSpacing: font.letterSpacing,
      lineHeight: font.lineHeight,
      logLevel: vscodeToXtermLogLevel(this.W.getLevel()),
      logger: this.W,
      minimumContrastRatio: config.minimumContrastRatio,
      tabStopWidth: config.tabStopWidth,
      cursorBlink: config.cursorBlinking,
      cursorStyle: vscodeToXtermCursorStyle(config.cursorStyle),
      cursorInactiveStyle: vscodeToXtermCursorStyle(config.cursorStyleInactive),
      cursorWidth: config.cursorWidth,
      macOptionIsMeta: config.macOptionIsMeta,
      macOptionClickForcesSelection: config.macOptionClickForcesSelection,
      rightClickSelectsWord: config.rightClickBehavior === "selectWord",
      fastScrollModifier: "alt",
      fastScrollSensitivity: config.fastScrollSensitivity,
      scrollSensitivity: config.mouseWheelScrollSensitivity,
      wordSeparator: config.wordSeparators,
      overviewRuler: {
        width: 14,
        showTopBorder: true
      },
      ignoreBracketedPasteMode: config.ignoreBracketedPasteMode,
      rescaleOverlappingGlyphs: config.rescaleOverlappingGlyphs,
      windowOptions: {
        getWinSizePixels: true,
        getCellSizePixels: true,
        getWinSizeChars: true
      }
    }));
    this.db();
    this.a = this.raw._core;
    this.B(this.S.onDidChangeConfiguration(async (e) => {
      if (e.affectsConfiguration(
        "terminal.integrated.gpuAcceleration"
        /* TerminalSettingId.GpuAcceleration */
      )) {
        $2Pb_1.g = void 0;
      }
      if (e.affectsConfiguration("terminal.integrated") || e.affectsConfiguration("editor.fastScrollSensitivity") || e.affectsConfiguration("editor.mouseWheelScrollSensitivity") || e.affectsConfiguration("editor.multiCursorModifier")) {
        this.updateConfig();
      }
      if (e.affectsConfiguration(
        "terminal.integrated.unicodeVersion"
        /* TerminalSettingId.UnicodeVersion */
      )) {
        this.tb();
      }
      if (e.affectsConfiguration(
        "terminal.integrated.shellIntegration.decorationsEnabled"
        /* TerminalSettingId.ShellIntegrationDecorationsEnabled */
      )) {
        this.sb();
      }
    }));
    this.B(this.Y.onDidColorThemeChange((theme) => this.sb(theme)));
    this.B(this.W.onDidChangeLogLevel((e) => this.raw.options.logLevel = vscodeToXtermLogLevel(e)));
    this.B(this.raw.onSelectionChange(() => {
      this.P.fire();
      if (this.isFocused) {
        this.I.set(this.raw.hasSelection());
      }
    }));
    this.tb();
    this.n = this.U.createInstance($wPb, options3.capabilities);
    this.raw.loadAddon(this.n);
    this.s = this.U.createInstance($ZPb, this.f);
    this.B(this.s.onDidRequestRunCommand((e) => this.L.fire(e)));
    this.B(this.s.onDidRequestCopyAsHtml((e) => this.M.fire(e)));
    this.raw.loadAddon(this.s);
    this.r = new $GPb(options3.shellIntegrationNonce ?? "", options3.disableShellIntegrationReporting, this.Z, this.W);
    this.raw.loadAddon(this.r);
    this.b.importAddon("clipboard").then((ClipboardAddon) => {
      if (this.q.isDisposed) {
        return;
      }
      this.t = this.U.createInstance(ClipboardAddon, void 0, {
        async readText(type) {
          return ab.readText(type === "p" ? "selection" : "clipboard");
        },
        async writeText(type, text2) {
          return ab.writeText(text2, type === "p" ? "selection" : "clipboard");
        }
      });
      this.raw.loadAddon(this.t);
    });
    this.H = TerminalContextKeys.focusInAny.bindTo(contextKeyService);
    this.I = TerminalContextKeys.textSelectedInFocused.bindTo(contextKeyService);
  }
  *getBufferReverseIterator() {
    for (let i2 = this.raw.buffer.active.length; i2 >= 0; i2--) {
      const { lineData, lineIndex } = getFullBufferLineAsString(i2, this.raw.buffer.active);
      if (lineData) {
        i2 = lineIndex;
        yield lineData;
      }
    }
  }
  async getContentsAsHtml() {
    if (!this.C) {
      const Addon = await this.b.importAddon("serialize");
      this.C = new Addon();
      this.raw.loadAddon(this.C);
    }
    return this.C.serializeAsHTML();
  }
  async getSelectionAsHtml(command4) {
    if (!this.C) {
      const Addon = await this.b.importAddon("serialize");
      this.C = new Addon();
      this.raw.loadAddon(this.C);
    }
    if (command4) {
      const length = command4.getOutput()?.length;
      const row = command4.marker?.line;
      if (!length || !row) {
        throw new Error(`No row ${row} or output length ${length} for command ${command4}`);
      }
      this.raw.select(0, row + 1, length - Math.floor(length / this.raw.cols));
    }
    const result = this.C.serializeAsHTML({ onlySelection: true });
    if (command4) {
      this.raw.clearSelection();
    }
    return result;
  }
  attachToElement(container2, partialOptions) {
    const options3 = { enableGpu: true, ...partialOptions };
    if (!this.j) {
      this.raw.open(container2);
    }
    if (options3.enableGpu) {
      if (this.eb()) {
        this.nb();
      }
    }
    if (!this.raw.element || !this.raw.textarea) {
      throw new Error("xterm elements not set after open");
    }
    const ad = this.G;
    ad.clear();
    ad.add($_i(this.raw.textarea, "focus", () => this.cb(true)));
    ad.add($_i(this.raw.textarea, "blur", () => this.cb(false)));
    ad.add($_i(this.raw.textarea, "focusout", () => this.cb(false)));
    ad.add($_i(this.raw.element, $7j.MOUSE_WHEEL, (e) => {
      const classifier = $yZ.INSTANCE;
      classifier.acceptStandardWheelEvent(new $nf(e));
      const value = classifier.isPhysicalMouseWheel();
      if (value !== this.m) {
        this.m = value;
        this.db();
      }
    }, { passive: true }));
    this.pb();
    this.j = { container: container2, options: options3 };
    return this.j?.container.querySelector(".xterm-screen");
  }
  cb(isFocused) {
    this.Q.fire(isFocused);
    this.H.set(isFocused);
    this.I.set(isFocused && this.raw.hasSelection());
  }
  write(data, callback) {
    this.raw.write(data, callback);
  }
  resize(columns, rows) {
    this.raw.resize(columns, rows);
  }
  updateConfig() {
    const config = this.$.config;
    this.raw.options.altClickMovesCursor = config.altClickMovesCursor;
    this.jb(config.cursorBlinking);
    this.kb(config.cursorStyle);
    this.lb(config.cursorStyleInactive);
    this.mb(config.cursorWidth);
    this.raw.options.scrollback = config.scrollback;
    this.raw.options.drawBoldTextInBrightColors = config.drawBoldTextInBrightColors;
    this.raw.options.minimumContrastRatio = config.minimumContrastRatio;
    this.raw.options.tabStopWidth = config.tabStopWidth;
    this.raw.options.fastScrollSensitivity = config.fastScrollSensitivity;
    this.raw.options.scrollSensitivity = config.mouseWheelScrollSensitivity;
    this.raw.options.macOptionIsMeta = config.macOptionIsMeta;
    const editorOptions2 = this.S.getValue("editor");
    this.raw.options.altClickMovesCursor = config.altClickMovesCursor && editorOptions2.multiCursorModifier === "alt";
    this.raw.options.macOptionClickForcesSelection = config.macOptionClickForcesSelection;
    this.raw.options.rightClickSelectsWord = config.rightClickBehavior === "selectWord";
    this.raw.options.wordSeparator = config.wordSeparators;
    this.raw.options.customGlyphs = config.customGlyphs;
    this.raw.options.ignoreBracketedPasteMode = config.ignoreBracketedPasteMode;
    this.raw.options.rescaleOverlappingGlyphs = config.rescaleOverlappingGlyphs;
    this.raw.options.overviewRuler = {
      width: 14,
      showTopBorder: true
    };
    this.db();
    if (this.j) {
      if (this.j.options.enableGpu) {
        if (this.eb()) {
          this.nb();
        } else {
          this.rb();
        }
      }
      this.pb();
    }
  }
  db() {
    this.raw.options.smoothScrollDuration = this.$.config.smoothScrolling && this.m ? 125 : 0;
  }
  eb() {
    return this.$.config.gpuAcceleration === "auto" && $2Pb_1.g === void 0 || this.$.config.gpuAcceleration === "on";
  }
  forceRedraw() {
    this.raw.clearTextureAtlas();
  }
  clearDecorations() {
    this.s?.clearDecorations();
  }
  forceRefresh() {
    this.a.viewport?._innerRefresh();
  }
  async findNext(term, searchOptions) {
    this.fb(searchOptions);
    return (await this.hb()).findNext(term, searchOptions);
  }
  async findPrevious(term, searchOptions) {
    this.fb(searchOptions);
    return (await this.hb()).findPrevious(term, searchOptions);
  }
  fb(searchOptions) {
    const theme = this.Y.getColorTheme();
    const terminalBackground = theme.getColor($$Ob) || theme.getColor($Imb);
    const findMatchBackground = theme.getColor($lPb);
    const findMatchBorder = theme.getColor($nPb);
    const findMatchOverviewRuler = theme.getColor($iPb);
    const findMatchHighlightBackground = theme.getColor($oPb);
    const findMatchHighlightBorder = theme.getColor($pPb);
    const findMatchHighlightOverviewRuler = theme.getColor($qPb);
    searchOptions.decorations = {
      activeMatchBackground: findMatchBackground?.toString(),
      activeMatchBorder: findMatchBorder?.toString() || "transparent",
      activeMatchColorOverviewRuler: findMatchOverviewRuler?.toString() || "transparent",
      // decoration bgs don't support the alpha channel so blend it with the regular bg
      matchBackground: terminalBackground ? findMatchHighlightBackground?.blend(terminalBackground).toString() : void 0,
      matchBorder: findMatchHighlightBorder?.toString() || "transparent",
      matchOverviewRuler: findMatchHighlightOverviewRuler?.toString() || "transparent"
    };
  }
  hb() {
    if (!this.gb) {
      this.gb = this.b.importAddon("search").then((AddonCtor) => {
        if (this.q.isDisposed) {
          return Promise.reject("Could not create search addon, terminal is disposed");
        }
        this.u = new AddonCtor({
          highlightLimit: 2e4
          /* XtermTerminalConstants.SearchHighlightLimit */
        });
        this.raw.loadAddon(this.u);
        this.u.onDidChangeResults((results) => {
          this.J = results;
          this.O.fire(results);
        });
        return this.u;
      });
    }
    return this.gb;
  }
  clearSearchDecorations() {
    this.u?.clearDecorations();
  }
  clearActiveSearchDecoration() {
    this.u?.clearActiveDecoration();
  }
  getFont() {
    return this.$.getFont(getWindow(this.raw.element), this.a);
  }
  getLongestViewportWrappedLineLength() {
    let maxLineLength = 0;
    for (let i2 = this.raw.buffer.active.length - 1; i2 >= this.raw.buffer.active.viewportY; i2--) {
      const lineInfo = this.ib(i2, this.raw.buffer.active);
      maxLineLength = Math.max(maxLineLength, lineInfo.lineCount * this.raw.cols - lineInfo.endSpaces || 0);
      i2 = lineInfo.currentIndex;
    }
    return maxLineLength;
  }
  ib(index, buffer) {
    let line = buffer.getLine(index);
    if (!line) {
      throw new Error("Could not get line");
    }
    let currentIndex = index;
    let endSpaces = 0;
    for (let i2 = Math.min(line.length, this.raw.cols) - 1; i2 >= 0; i2--) {
      if (!line?.getCell(i2)?.getChars()) {
        endSpaces++;
      } else {
        break;
      }
    }
    while (line?.isWrapped && currentIndex > 0) {
      currentIndex--;
      line = buffer.getLine(currentIndex);
    }
    return { lineCount: index - currentIndex + 1, currentIndex, endSpaces };
  }
  scrollDownLine() {
    this.raw.scrollLines(1);
  }
  scrollDownPage() {
    this.raw.scrollPages(1);
  }
  scrollToBottom() {
    this.raw.scrollToBottom();
  }
  scrollUpLine() {
    this.raw.scrollLines(-1);
  }
  scrollUpPage() {
    this.raw.scrollPages(-1);
  }
  scrollToTop() {
    this.raw.scrollToTop();
  }
  scrollToLine(line, position = 0) {
    this.markTracker.scrollToLine(line, position);
  }
  clearBuffer() {
    this.raw.clear();
    this.f.get(
      2
      /* TerminalCapability.CommandDetection */
    )?.handlePromptStart();
    this.f.get(
      2
      /* TerminalCapability.CommandDetection */
    )?.handleCommandStart();
    this.bb.playSignal($N9.clear);
  }
  hasSelection() {
    return this.raw.hasSelection();
  }
  clearSelection() {
    this.raw.clearSelection();
  }
  selectMarkedRange(fromMarkerId, toMarkerId, scrollIntoView = false) {
    const detectionCapability = this.shellIntegration.capabilities.get(
      4
      /* TerminalCapability.BufferMarkDetection */
    );
    if (!detectionCapability) {
      return;
    }
    const start = detectionCapability.getMark(fromMarkerId);
    const end = detectionCapability.getMark(toMarkerId);
    if (start === void 0 || end === void 0) {
      return;
    }
    this.raw.selectLines(start.line, end.line);
    if (scrollIntoView) {
      this.raw.scrollToLine(start.line);
    }
  }
  selectAll() {
    this.raw.focus();
    this.raw.selectAll();
  }
  focus() {
    this.raw.focus();
  }
  async copySelection(asHtml, command4) {
    if (this.hasSelection() || asHtml && command4) {
      if (asHtml) {
        let listener2 = function(e) {
          if (!e.clipboardData.types.includes("text/plain")) {
            e.clipboardData.setData("text/plain", command4?.getOutput() ?? "");
          }
          e.clipboardData.setData("text/html", textAsHtml);
          e.preventDefault();
        };
        var listener = listener2;
        const textAsHtml = await this.getSelectionAsHtml(command4);
        const doc = getDocument(this.raw.element);
        doc.addEventListener("copy", listener2);
        doc.execCommand("copy");
        doc.removeEventListener("copy", listener2);
      } else {
        await this.ab.writeText(this.raw.getSelection());
      }
    } else {
      this.X.warn(localize(10575, null));
    }
  }
  jb(blink) {
    if (this.raw.options.cursorBlink !== blink) {
      this.raw.options.cursorBlink = blink;
      this.raw.refresh(0, this.raw.rows - 1);
    }
  }
  kb(style) {
    const mapped = vscodeToXtermCursorStyle(style);
    if (this.raw.options.cursorStyle !== mapped) {
      this.raw.options.cursorStyle = mapped;
    }
  }
  lb(style) {
    const mapped = vscodeToXtermCursorStyle(style);
    if (this.raw.options.cursorInactiveStyle !== mapped) {
      this.raw.options.cursorInactiveStyle = mapped;
    }
  }
  mb(width2) {
    if (this.raw.options.cursorWidth !== width2) {
      this.raw.options.cursorWidth = width2;
    }
  }
  async nb() {
    if (!this.raw.element || this.z) {
      return;
    }
    if (!$2Pb_1.h) {
      $2Pb_1.h = true;
      const checkCanvas = document.createElement("canvas");
      const checkGl = checkCanvas.getContext("webgl2");
      const debugInfo = checkGl?.getExtension("WEBGL_debug_renderer_info");
      if (checkGl && debugInfo) {
        const renderer = checkGl.getParameter(debugInfo.UNMASKED_RENDERER_WEBGL);
        if (renderer.startsWith("ANGLE (Google, Vulkan 1.3.0 (SwiftShader Device (Subzero)")) {
          this.ob();
          return;
        }
      }
    }
    const Addon = await this.b.importAddon("webgl");
    this.z = new Addon();
    try {
      this.raw.loadAddon(this.z);
      this.W.trace("Webgl was loaded");
      this.z.onContextLoss(() => {
        this.W.info(`Webgl lost context, disposing of webgl renderer`);
        this.rb();
      });
      this.qb();
      this.N.fire();
    } catch (e) {
      this.W.warn(`Webgl could not be loaded. Falling back to the DOM renderer`, e);
      this.ob();
    }
  }
  ob() {
    $2Pb_1.g = "dom";
    this.rb();
  }
  async pb() {
    if (!this.raw.element) {
      return;
    }
    if (this.$.config.fontLigatures) {
      if (!this.F.value) {
        this.b.importAddon("ligatures").then((LigaturesAddon) => {
          if (this.q.isDisposed) {
            return;
          }
          this.F.value = this.U.createInstance(LigaturesAddon);
          this.raw.loadAddon(this.F.value);
        });
      }
    } else {
      this.F.clear();
    }
  }
  async qb() {
    if (this.$.config.enableImages && this.z) {
      if (!this.D) {
        const AddonCtor = await this.b.importAddon("image");
        this.D = new AddonCtor();
        this.raw.loadAddon(this.D);
      }
    } else {
      try {
        this.D?.dispose();
      } catch {
      }
      this.D = void 0;
    }
  }
  rb() {
    try {
      this.z?.dispose();
    } catch {
    }
    this.z = void 0;
    this.qb();
    this.N.fire();
  }
  getXtermTheme(theme) {
    if (!theme) {
      theme = this.Y.getColorTheme();
    }
    const config = this.$.config;
    const hideOverviewRuler = ["never", "gutter"].includes(config.shellIntegration?.decorationsEnabled ?? "");
    const foregroundColor = theme.getColor($_Ob);
    const backgroundColor = this.c.getBackgroundColor(theme);
    const cursorColor = theme.getColor($aPb) || foregroundColor;
    const cursorAccentColor = theme.getColor($bPb) || backgroundColor;
    const selectionBackgroundColor = theme.getColor($cPb);
    const selectionInactiveBackgroundColor = theme.getColor($dPb);
    const selectionForegroundColor = theme.getColor($ePb) || void 0;
    return {
      background: backgroundColor?.toString(),
      foreground: foregroundColor?.toString(),
      cursor: cursorColor?.toString(),
      cursorAccent: cursorAccentColor?.toString(),
      selectionBackground: selectionBackgroundColor?.toString(),
      selectionInactiveBackground: selectionInactiveBackgroundColor?.toString(),
      selectionForeground: selectionForegroundColor?.toString(),
      overviewRulerBorder: hideOverviewRuler ? "#0000" : theme.getColor($kPb)?.toString(),
      scrollbarSliderActiveBackground: theme.getColor($Fo)?.toString(),
      scrollbarSliderBackground: theme.getColor($Do)?.toString(),
      scrollbarSliderHoverBackground: theme.getColor($Eo)?.toString(),
      black: theme.getColor($0Ob[0])?.toString(),
      red: theme.getColor($0Ob[1])?.toString(),
      green: theme.getColor($0Ob[2])?.toString(),
      yellow: theme.getColor($0Ob[3])?.toString(),
      blue: theme.getColor($0Ob[4])?.toString(),
      magenta: theme.getColor($0Ob[5])?.toString(),
      cyan: theme.getColor($0Ob[6])?.toString(),
      white: theme.getColor($0Ob[7])?.toString(),
      brightBlack: theme.getColor($0Ob[8])?.toString(),
      brightRed: theme.getColor($0Ob[9])?.toString(),
      brightGreen: theme.getColor($0Ob[10])?.toString(),
      brightYellow: theme.getColor($0Ob[11])?.toString(),
      brightBlue: theme.getColor($0Ob[12])?.toString(),
      brightMagenta: theme.getColor($0Ob[13])?.toString(),
      brightCyan: theme.getColor($0Ob[14])?.toString(),
      brightWhite: theme.getColor($0Ob[15])?.toString()
    };
  }
  sb(theme) {
    this.raw.options.theme = this.getXtermTheme(theme);
  }
  refresh() {
    this.sb();
    this.s.refreshLayouts();
  }
  async tb() {
    if (!this.y && this.$.config.unicodeVersion === "11") {
      const Addon = await this.b.importAddon("unicode11");
      this.y = new Addon();
      this.raw.loadAddon(this.y);
    }
    if (this.raw.unicode.activeVersion !== this.$.config.unicodeVersion) {
      this.raw.unicode.activeVersion = this.$.config.unicodeVersion;
    }
  }
  // eslint-disable-next-line @typescript-eslint/naming-convention
  _writeText(data) {
    this.raw.write(data);
  }
  dispose() {
    this.H.reset();
    this.I.reset();
    this.R.fire();
    super.dispose();
  }
};
__decorate([
  $$t(100)
], $2Pb.prototype, "pb", null);
__decorate([
  $$t(100)
], $2Pb.prototype, "qb", null);
$2Pb = $2Pb_1 = __decorate([
  __param(2, $kl),
  __param(3, $Pk),
  __param(4, $8x),
  __param(5, $PJ),
  __param(6, $gs),
  __param(7, $zv),
  __param(8, $5Pb),
  __param(9, $30),
  __param(10, $on),
  __param(11, $I9),
  __param(12, $Ulb)
], $2Pb);
function $3Pb(w, font, width2, height) {
  if (!font.charWidth || !font.charHeight) {
    return null;
  }
  const scaledWidthAvailable = width2 * w.devicePixelRatio;
  const scaledCharWidth = font.charWidth * w.devicePixelRatio + font.letterSpacing;
  const cols = Math.max(Math.floor(scaledWidthAvailable / scaledCharWidth), 1);
  const scaledHeightAvailable = height * w.devicePixelRatio;
  const scaledCharHeight = Math.ceil(font.charHeight * w.devicePixelRatio);
  const scaledLineHeight = Math.floor(scaledCharHeight * font.lineHeight);
  const rows = Math.max(Math.floor(scaledHeightAvailable / scaledLineHeight), 1);
  return { rows, cols };
}
function vscodeToXtermLogLevel(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";
    default:
      return "off";
  }
}
function vscodeToXtermCursorStyle(style) {
  if (style === "line") {
    return "bar";
  }
  return style;
}

// out-build/vs/workbench/contrib/testing/browser/testResultsView/testResultsOutput.js
var SimpleDiffEditorModel = class extends $rG {
  constructor(a, b) {
    super();
    this.a = a;
    this.b = b;
    this.original = this.a.object.textEditorModel;
    this.modified = this.b.object.textEditorModel;
  }
  dispose() {
    super.dispose();
    this.a.dispose();
    this.b.dispose();
  }
};
var commonEditorOptions = {
  scrollBeyondLastLine: false,
  links: true,
  lineNumbers: "off",
  glyphMargin: false,
  scrollbar: {
    vertical: "hidden",
    horizontal: "auto",
    useShadows: false,
    verticalHasArrows: false,
    horizontalHasArrows: false,
    handleMouseWheel: false
  },
  overviewRulerLanes: 0,
  fixedOverflowWidgets: true,
  readOnly: true,
  stickyScroll: { enabled: false },
  minimap: { enabled: false },
  automaticLayout: false
};
var diffEditorOptions = {
  ...commonEditorOptions,
  enableSplitViewResizing: true,
  isInEmbeddedEditor: true,
  renderOverviewRuler: false,
  ignoreTrimWhitespace: false,
  renderSideBySide: true,
  useInlineViewWhenSpaceIsLimited: false,
  originalAriaLabel: localize(11220, null),
  modifiedAriaLabel: localize(11221, null),
  diffAlgorithm: "advanced"
};
var $20b = class $20b2 extends $3c {
  get onDidContentSizeChange() {
    return this.a.value?.onDidContentSizeChange || Event2.None;
  }
  constructor(g, h3, j, m) {
    super();
    this.g = g;
    this.h = h3;
    this.j = j;
    this.m = m;
    this.a = this.B(new $4c());
    this.b = this.B(new $4c());
  }
  async update(subject) {
    if (!(subject instanceof $K0b)) {
      this.n();
      return false;
    }
    const message = subject.message;
    if (!ITestMessage.isDiffable(message)) {
      this.n();
      return false;
    }
    const [original, modified] = await Promise.all([
      this.m.createModelReference(subject.expectedUri),
      this.m.createModelReference(subject.actualUri)
    ]);
    const model = this.b.value = new SimpleDiffEditorModel(original, modified);
    if (!this.a.value) {
      this.a.value = this.g ? this.j.createInstance($zEb, this.h, diffEditorOptions, {}, this.g) : this.j.createInstance($c_, this.h, diffEditorOptions, {});
      if (this.c) {
        this.a.value.layout(this.c);
      }
    }
    this.a.value.setModel(model);
    this.a.value.updateOptions(this.r(isMultiline(message.expected) || isMultiline(message.actual)));
    return true;
  }
  n() {
    this.b.clear();
    this.a.clear();
  }
  layout(dimensions, hasMultipleFrames) {
    this.c = dimensions;
    const editor = this.a.value;
    if (!editor) {
      return;
    }
    editor.layout(dimensions);
    const height = Math.max(editor.getOriginalEditor().getContentHeight(), editor.getModifiedEditor().getContentHeight());
    this.f = new ScrollHelper(hasMultipleFrames, height, dimensions.height);
    return height;
  }
  onScrolled(evt) {
    this.f?.onScrolled(evt, this.a.value?.getDomNode(), this.a.value?.getOriginalEditor());
  }
  r(isMultiline2) {
    return isMultiline2 ? { ...diffEditorOptions, lineNumbers: "on" } : { ...diffEditorOptions, lineNumbers: "off" };
  }
};
$20b = __decorate([
  __param(2, $Pk),
  __param(3, $oG)
], $20b);
var $30b = class $30b2 extends $3c {
  constructor(f, g) {
    super();
    this.f = f;
    this.g = g;
    this.a = new $sf(() => this.B(this.g.createInstance($Q_, {})));
    this.b = this.B(new $2c());
    this.B($1c(() => this.h()));
  }
  async update(subject) {
    this.h();
    if (!(subject instanceof $K0b)) {
      return false;
    }
    const message = subject.message;
    if (ITestMessage.isDiffable(message) || typeof message.message === "string") {
      return false;
    }
    const rendered = this.b.add(this.a.value.render(message.message, {}));
    rendered.element.style.userSelect = "text";
    rendered.element.classList.add("preview-text");
    this.f.appendChild(rendered.element);
    this.c = rendered.element;
    this.b.add($1c(() => rendered.element.remove()));
    return true;
  }
  layout(dimension) {
    if (!this.c) {
      return void 0;
    }
    this.c.style.width = `${dimension.width - 32}px`;
    return this.c.clientHeight;
  }
  h() {
    this.b.clear();
    this.c = void 0;
  }
};
$30b = __decorate([
  __param(1, $Pk)
], $30b);
var ScrollHelper = class {
  constructor(a, b, c) {
    this.a = a;
    this.b = b;
    this.c = c;
  }
  onScrolled(evt, container2, editor) {
    if (!editor || !container2) {
      return;
    }
    let delta = Math.max(0, evt.scrollTop - (this.a ? $U0b : 0));
    delta = Math.min(Math.max(0, this.b - this.c), delta);
    editor.setScrollTop(delta);
    container2.style.transform = `translateY(${delta}px)`;
  }
};
var $40b = class $40b2 extends $3c {
  get onDidContentSizeChange() {
    return this.b.value?.onDidContentSizeChange || Event2.None;
  }
  constructor(h3, j, m, n) {
    super();
    this.h = h3;
    this.j = j;
    this.m = m;
    this.n = n;
    this.a = this.B(new $4c());
    this.b = this.B(new $4c());
    this.c = this.B(new $4c());
  }
  async update(subject) {
    if (!(subject instanceof $K0b)) {
      this.r();
      return false;
    }
    const message = subject.message;
    if (ITestMessage.isDiffable(message) || message.type === 1 || typeof message.message !== "string") {
      this.r();
      return false;
    }
    const modelRef = this.c.value = await this.n.createModelReference(subject.messageUri);
    if (!this.b.value) {
      this.b.value = this.h ? this.m.createInstance($bdb, this.j, commonEditorOptions, {}, this.h) : this.m.createInstance($D9, this.j, commonEditorOptions, { isSimpleWidget: true });
      if (this.f) {
        this.b.value.layout(this.f);
      }
    }
    this.b.value.setModel(modelRef.object.textEditorModel);
    this.b.value.updateOptions(commonEditorOptions);
    this.a.value = $H0b(message.message, this.b.value);
    return true;
  }
  r() {
    this.a.clear();
    this.b.clear();
    this.c.clear();
  }
  onScrolled(evt) {
    this.g?.onScrolled(evt, this.b.value?.getDomNode(), this.b.value);
  }
  layout(dimensions, hasMultipleFrames) {
    this.f = dimensions;
    const editor = this.b.value;
    if (!editor) {
      return;
    }
    editor.layout(dimensions);
    const height = editor.getContentHeight();
    this.g = new ScrollHelper(hasMultipleFrames, height, dimensions.height);
    return height;
  }
};
$40b = __decorate([
  __param(2, $Pk),
  __param(3, $oG)
], $40b);
var $50b = class $50b2 extends $3c {
  constructor(h3, j, m, n, r2) {
    super();
    this.h = h3;
    this.j = j;
    this.m = m;
    this.n = n;
    this.r = r2;
    this.b = this.B(new $lTb(""));
    this.c = this.B(new $Sh(50));
    this.f = this.B(new $4c());
    this.g = this.B(new $4c());
  }
  async u() {
    const prev = this.f.value;
    if (prev) {
      prev.xterm.clearBuffer();
      prev.xterm.clearSearchDecorations();
      prev.xterm.write(`\x1Bc`);
      return prev;
    }
    const capabilities = new $zPb();
    const cwd2 = this.b;
    capabilities.add(0, {
      type: 0,
      get cwds() {
        return [cwd2.value];
      },
      onDidChangeCwd: cwd2.onDidChange,
      getCwd: () => cwd2.value,
      updateCwd: () => {
      }
    });
    return this.f.value = await this.m.createDetachedTerminal({
      rows: 10,
      cols: 80,
      readonly: true,
      capabilities,
      processInfo: new $10b({ initialCwd: cwd2.value }),
      colorProvider: {
        getBackgroundColor: (theme) => {
          const terminalBackground = theme.getColor($$Ob);
          if (terminalBackground) {
            return terminalBackground;
          }
          if (this.j) {
            return theme.getColor($heb);
          }
          const location3 = this.n.getViewLocationById(
            "workbench.panel.testResults.view"
            /* Testing.ResultsViewId */
          );
          return location3 === 1 ? theme.getColor($Imb) : theme.getColor($Pnb);
        }
      }
    });
  }
  async update(subject) {
    this.g.clear();
    if (subject instanceof $L0b) {
      await this.y(subject);
    } else if (subject instanceof $M0b || subject instanceof $K0b && subject.message.type === 1) {
      await this.w(subject);
    } else {
      this.G();
      return false;
    }
    return true;
  }
  async w(subject) {
    const that = this;
    const testItem = subject instanceof $M0b ? subject.test.item : subject.test;
    const terminal2 = await this.z({
      subject,
      noOutputMessage: localize(11222, null),
      getTarget: (result) => result?.tasks[subject.taskIndex].output,
      *doInitialWrite(output, results) {
        that.C(testItem.uri);
        const state = subject instanceof $M0b ? subject.test : results.getStateById(testItem.extId);
        if (!state) {
          return;
        }
        for (const message of state.tasks[subject.taskIndex].messages) {
          if (message.type === 1) {
            yield* output.getRangeIter(message.offset, message.length);
          }
        }
      },
      doListenForMoreData: (output, result, write) => result.onChange((e) => {
        if (e.reason === 2 && e.item.item.extId === testItem.extId && e.message.type === 1) {
          for (const chunk of output.getRangeIter(e.message.offset, e.message.length)) {
            write(chunk.buffer);
          }
        }
      })
    });
    if (subject instanceof $K0b && subject.message.type === 1 && subject.message.marker !== void 0) {
      terminal2?.xterm.selectMarkedRange(
        $rQ(subject.message.marker, true),
        $rQ(subject.message.marker, false),
        /* scrollIntoView= */
        true
      );
    }
  }
  y(subject) {
    return this.z({
      subject,
      noOutputMessage: localize(11223, null),
      getTarget: (result) => result?.tasks[subject.taskIndex],
      doInitialWrite: (task, result) => {
        this.C(Iterable.find(result.tests, (t) => !!t.item.uri)?.item.uri);
        return task.output.buffers;
      },
      doListenForMoreData: (task, _result, write) => task.output.onDidWriteData((e) => write(e.buffer))
    });
  }
  async z(opts) {
    const result = opts.subject.result;
    const target = opts.getTarget(result);
    if (!target) {
      return this.G();
    }
    const terminal2 = await this.u();
    let didWriteData = false;
    const pendingWrites = new $lTb(0);
    if (result instanceof $RQ) {
      for (const chunk of opts.doInitialWrite(target, result)) {
        didWriteData ||= chunk.byteLength > 0;
        pendingWrites.value++;
        terminal2.xterm.write(chunk.buffer, () => pendingWrites.value--);
      }
    } else {
      didWriteData = true;
      this.D(terminal2, localize(11224, null));
    }
    this.F(terminal2);
    this.g.clear();
    if (result instanceof $RQ && !result.completedAt) {
      const l1 = result.onComplete(() => {
        if (!didWriteData) {
          this.D(terminal2, opts.noOutputMessage);
        }
      });
      const l2 = opts.doListenForMoreData(target, result, (data) => {
        terminal2.xterm.write(data);
        didWriteData ||= data.byteLength > 0;
      });
      this.g.value = $Zc(l1, l2);
    }
    if (!this.g.value && !didWriteData) {
      this.D(terminal2, opts.noOutputMessage);
    }
    if (pendingWrites.value > 0) {
      await new Promise((resolve) => {
        const l = pendingWrites.onDidChange(() => {
          if (pendingWrites.value === 0) {
            l.dispose();
            resolve();
          }
        });
      });
    }
    return terminal2;
  }
  C(testUri) {
    const wf = testUri && this.r.getWorkspaceFolder(testUri) || this.r.getWorkspace().folders[0];
    if (wf) {
      this.b.value = wf.uri.fsPath;
    }
  }
  D(terminal2, str) {
    terminal2.xterm.write($W0b(str));
  }
  F(terminal2) {
    terminal2.xterm.write("\x1B[?25l");
    $jj(getWindow(this.h), () => this.H(terminal2));
    terminal2.attachToElement(this.h, { enableGpu: false });
  }
  G() {
    this.g.clear();
    this.c.cancel();
    this.f.clear();
  }
  layout(dimensions) {
    this.a = dimensions;
    if (this.f.value) {
      this.H(this.f.value, dimensions.width, dimensions.height);
      return dimensions.height;
    }
    return void 0;
  }
  H({ xterm }, width2 = this.a?.width ?? this.h.clientWidth, height = this.a?.height ?? this.h.clientHeight) {
    width2 -= 10 + 20;
    this.c.trigger(() => {
      const scaled = $3Pb(getWindow(this.h), xterm.getFont(), width2, height);
      if (scaled) {
        xterm.resize(scaled.cols, scaled.rows);
      }
    });
  }
};
$50b = __decorate([
  __param(2, $4Pb),
  __param(3, $$M),
  __param(4, $Zk)
], $50b);
var isMultiline = (str) => !!str && str.includes("\n");

// out-build/vs/workbench/contrib/testing/common/testExplorerFilterState.js
var $60b = $Qk("testingFilterState");
var tagRe = /!?@([^ ,:]+)/g;
var trimExtraWhitespace = (str) => str.replace(/\s\s+/g, " ").trim();
var $70b = class $70b2 extends $3c {
  constructor(f) {
    super();
    this.f = f;
    this.a = new $ze();
    this.b = {};
    this.globList = [];
    this.includeTags = /* @__PURE__ */ new Set();
    this.excludeTags = /* @__PURE__ */ new Set();
    this.text = this.B(new $lTb(""));
    this.fuzzy = this.B($lTb.stored(new $jTb({
      key: "testHistoryFuzzy",
      scope: 0,
      target: 0
    }, this.f), false));
    this.reveal = $he("TestExplorerFilterState.reveal", void 0);
    this.onDidRequestInputFocus = this.a.event;
    this.c = this.B(new $ze());
    this.onDidSelectTestInExplorer = this.c.event;
  }
  /** @inheritdoc */
  didSelectTestInExplorer(testId) {
    this.c.fire(testId);
  }
  /** @inheritdoc */
  focusInput() {
    this.a.fire();
  }
  /** @inheritdoc */
  setText(text2) {
    if (text2 === this.text.value) {
      return;
    }
    this.b = {};
    this.globList = [];
    this.includeTags.clear();
    this.excludeTags.clear();
    let globText = "";
    let lastIndex = 0;
    for (const match of text2.matchAll(tagRe)) {
      let nextIndex = match.index + match[0].length;
      const tag2 = match[0];
      if (allTestFilterTerms.includes(tag2)) {
        this.b[tag2] = true;
      }
      if (text2[nextIndex] === ":") {
        nextIndex++;
        let delimiter = text2[nextIndex];
        if (delimiter !== `"` && delimiter !== `'`) {
          delimiter = " ";
        } else {
          nextIndex++;
        }
        let tagId = "";
        while (nextIndex < text2.length && text2[nextIndex] !== delimiter) {
          if (text2[nextIndex] === "\\") {
            tagId += text2[nextIndex + 1];
            nextIndex += 2;
          } else {
            tagId += text2[nextIndex];
            nextIndex++;
          }
        }
        if (match[0].startsWith("!")) {
          this.excludeTags.add($sQ(match[1], tagId));
        } else {
          this.includeTags.add($sQ(match[1], tagId));
        }
        nextIndex++;
      }
      globText += text2.slice(lastIndex, match.index);
      lastIndex = nextIndex;
    }
    globText += text2.slice(lastIndex).trim();
    if (globText.length) {
      for (const filter of $Bl(globText, ",").map((s) => s.trim()).filter((s) => !!s.length)) {
        if (filter.startsWith("!")) {
          this.globList.push({ include: false, text: filter.slice(1).toLowerCase() });
        } else {
          this.globList.push({ include: true, text: filter.toLowerCase() });
        }
      }
    }
    this.text.value = text2;
  }
  /** @inheritdoc */
  isFilteringFor(term) {
    return !!this.b[term];
  }
  /** @inheritdoc */
  toggleFilteringFor(term, shouldFilter) {
    const text2 = this.text.value.trim();
    if (shouldFilter !== false && !this.b[term]) {
      this.setText(text2 ? `${text2} ${term}` : term);
    } else if (shouldFilter !== true && this.b[term]) {
      this.setText(trimExtraWhitespace(text2.replace(term, "")));
    }
  }
};
$70b = __decorate([
  __param(0, $jv)
], $70b);
var TestFilterTerm;
(function(TestFilterTerm2) {
  TestFilterTerm2["Failed"] = "@failed";
  TestFilterTerm2["Executed"] = "@executed";
  TestFilterTerm2["CurrentDoc"] = "@doc";
  TestFilterTerm2["OpenedFiles"] = "@openedFiles";
  TestFilterTerm2["Hidden"] = "@hidden";
})(TestFilterTerm || (TestFilterTerm = {}));
var allTestFilterTerms = [
  "@failed",
  "@executed",
  "@doc",
  "@openedFiles",
  "@hidden"
];

// out-build/vs/workbench/contrib/testing/browser/testResultsView/testResultsTree.js
var TestRunElementRenderer_1;
var TestResultElement = class {
  get icon() {
    return $u0b.get(this.value.completedAt === void 0 ? 2 : $QQ(this.value.counts));
  }
  constructor(value) {
    this.value = value;
    this.changeEmitter = new $ze();
    this.onDidChange = this.changeEmitter.event;
    this.type = "result";
    this.context = this.value.id;
    this.id = this.value.id;
    this.label = this.value.name;
  }
};
var openCoverageLabel = localize(11225, null);
var closeCoverageLabel = localize(11226, null);
var CoverageElement = class {
  get label() {
    return this.isOpen ? closeCoverageLabel : openCoverageLabel;
  }
  get icon() {
    return this.isOpen ? $_r : $r0b;
  }
  get isOpen() {
    return this.f.selected.get()?.fromTaskId === this.task.id;
  }
  constructor(d, task, f) {
    this.d = d;
    this.task = task;
    this.f = f;
    this.type = "coverage";
    this.id = `coverage-${this.d.id}/${this.task.id}`;
    this.onDidChange = Event2.fromObservableLight(f.selected);
  }
};
var OlderResultsElement = class {
  constructor(d) {
    this.d = d;
    this.type = "older";
    this.id = `older-${this.d}`;
    this.onDidChange = Event2.None;
    this.label = localize(11227, null, d);
  }
};
var TestCaseElement = class {
  get onDidChange() {
    if (!(this.results instanceof $RQ)) {
      return Event2.None;
    }
    return Event2.filter(this.results.onChange, (e) => e.item.item.extId === this.test.item.extId);
  }
  get state() {
    return this.test.tasks[this.taskIndex].state;
  }
  get label() {
    return this.test.item.label;
  }
  get labelWithIcons() {
    return $B1(this.label);
  }
  get icon() {
    return $u0b.get(this.state);
  }
  get outputSubject() {
    return new $M0b(this.results, this.taskIndex, this.test);
  }
  constructor(results, test, taskIndex) {
    this.results = results;
    this.test = test;
    this.taskIndex = taskIndex;
    this.type = "test";
    this.context = {
      $mid: 16,
      tests: [InternalTestItem.serialize(this.test)]
    };
    this.id = `${this.results.id}/${this.test.item.extId}`;
  }
};
var TaskElement = class {
  get icon() {
    return this.results.tasks[this.index].running ? $u0b.get(
      2
      /* TestResultState.Running */
    ) : void 0;
  }
  constructor(results, task, index) {
    this.results = results;
    this.task = task;
    this.index = index;
    this.changeEmitter = new $ze();
    this.onDidChange = this.changeEmitter.event;
    this.type = "task";
    this.itemsCache = new CreationCache();
    this.id = `${results.id}/${index}`;
    this.task = results.tasks[index];
    this.context = { resultId: results.id, taskId: this.task.id };
    this.label = this.task.name;
  }
};
var TestMessageElement = class {
  get onDidChange() {
    if (!(this.result instanceof $RQ)) {
      return Event2.None;
    }
    return Event2.filter(this.result.onChange, (e) => e.item.item.extId === this.test.item.extId);
  }
  get context() {
    return $I0b(this.test, this.message);
  }
  get outputSubject() {
    return new $M0b(this.result, this.taskIndex, this.test);
  }
  constructor(result, test, taskIndex, messageIndex) {
    this.result = result;
    this.test = test;
    this.taskIndex = taskIndex;
    this.messageIndex = messageIndex;
    this.type = "message";
    const m = this.message = test.tasks[taskIndex].messages[messageIndex];
    this.location = m.location;
    this.contextValue = m.type === 0 ? m.contextValue : void 0;
    this.uri = $E0b({
      type: 2,
      messageIndex,
      resultId: result.id,
      taskIndex,
      testExtId: test.item.extId
    });
    this.id = this.uri.toString();
    const asPlaintext = $G0b(m.message);
    const lines = $Bf(asPlaintext.trimEnd(), "\n");
    this.label = firstLine(asPlaintext);
    if (lines > 0) {
      this.description = lines > 1 ? localize(11228, null, lines) : localize(11229, null);
    }
  }
};
var $80b = class $80b2 extends $3c {
  constructor(container2, onDidReveal, options3, r2, results, instantiationService, explorerFilter, coverageService, progressService, telemetryService) {
    super();
    this.r = r2;
    this.f = false;
    this.j = this.B(new $ze());
    this.onDidRequestReview = this.j.event;
    this.h = instantiationService.createInstance(TreeActionsProvider, options3.showRevealLocationOnMessages, this.j);
    const diffIdentityProvider = {
      getId(e) {
        return e.id;
      }
    };
    this.g = this.B(instantiationService.createInstance($2eb, "Test Output Peek", container2, {
      getHeight: () => 22,
      getTemplateId: () => TestRunElementRenderer.ID
    }, [instantiationService.createInstance(TestRunElementRenderer, this.h)], {
      compressionEnabled: true,
      hideTwistiesOfChildlessElements: true,
      identityProvider: diffIdentityProvider,
      alwaysConsumeMouseWheel: false,
      sorter: {
        compare(a, b) {
          if (a instanceof TestCaseElement && b instanceof TestCaseElement) {
            return $BQ(a.state, b.state);
          }
          return 0;
        }
      },
      accessibilityProvider: {
        getAriaLabel(element) {
          return element.ariaLabel || element.label;
        },
        getWidgetAriaLabel() {
          return localize(11230, null);
        }
      }
    }));
    const cc = new CreationCache();
    const getTaskChildren = (taskElem) => {
      const { results: results2, index, itemsCache, task } = taskElem;
      const tests = Iterable.filter(results2.tests, (test) => test.tasks[index].state >= 2 || test.tasks[index].messages.length > 0);
      let result = Iterable.map(tests, (test) => ({
        element: itemsCache.getOrCreate(test, () => new TestCaseElement(results2, test, index)),
        incompressible: true,
        children: getTestChildren(results2, test, index)
      }));
      if (task.coverage.get()) {
        result = Iterable.concat(Iterable.single({
          element: new CoverageElement(results2, task, coverageService),
          collapsible: true,
          incompressible: true
        }), result);
      }
      return result;
    };
    const getTestChildren = (result, test, taskIndex) => {
      return test.tasks[taskIndex].messages.map((m, messageIndex) => m.type === 0 ? { element: cc.getOrCreate(m, () => new TestMessageElement(result, test, taskIndex, messageIndex)), incompressible: false } : void 0).filter($Hg);
    };
    const getResultChildren = (result) => {
      return result.tasks.map((task, taskIndex) => {
        const taskElem = cc.getOrCreate(task, () => new TaskElement(result, task, taskIndex));
        return {
          element: taskElem,
          incompressible: false,
          collapsible: true,
          children: getTaskChildren(taskElem)
        };
      });
    };
    const getRootChildren = () => {
      let children = [];
      const older = [];
      for (const result of results.results) {
        if (!children.length && result.tasks.length) {
          children = getResultChildren(result);
        } else if (children) {
          const element = cc.getOrCreate(result, () => new TestResultElement(result));
          older.push({
            element,
            incompressible: true,
            collapsible: true,
            collapsed: this.g.hasElement(element) ? this.g.isCollapsed(element) : true,
            children: getResultChildren(result)
          });
        }
      }
      if (!children.length) {
        return older;
      }
      if (older.length) {
        children.push({
          element: new OlderResultsElement(older.length),
          incompressible: true,
          collapsible: true,
          collapsed: true,
          children: older
        });
      }
      return children;
    };
    const taskChildrenToUpdate = /* @__PURE__ */ new Set();
    const taskChildrenUpdate = this.B(new $8h(() => {
      for (const taskNode of taskChildrenToUpdate) {
        if (this.g.hasElement(taskNode)) {
          this.g.setChildren(taskNode, getTaskChildren(taskNode), { diffIdentityProvider });
        }
      }
      taskChildrenToUpdate.clear();
    }, 300));
    const queueTaskChildrenUpdate = (taskNode) => {
      taskChildrenToUpdate.add(taskNode);
      if (!taskChildrenUpdate.isScheduled()) {
        taskChildrenUpdate.schedule();
      }
    };
    const attachToResults = (result) => {
      const disposable = new $2c();
      disposable.add(result.onNewTask((i2) => {
        this.g.setChildren(null, getRootChildren(), { diffIdentityProvider });
        if (result.tasks.length === 1) {
          this.j.fire(new $L0b(result, 0));
        }
        const task = result.tasks[i2];
        disposable.add($td((reader) => {
          task.coverage.read(reader);
          queueTaskChildrenUpdate(cc.get(task));
        }));
      }));
      disposable.add(result.onEndTask((index) => {
        cc.get(result.tasks[index])?.changeEmitter.fire();
      }));
      disposable.add(result.onChange((e) => {
        for (const [index, task] of result.tasks.entries()) {
          const taskNode = cc.get(task);
          if (!this.g.hasElement(taskNode)) {
            continue;
          }
          const itemNode = taskNode.itemsCache.get(e.item);
          if (itemNode && this.g.hasElement(itemNode)) {
            if (e.reason === 2 && e.message.type === 0) {
              this.g.setChildren(itemNode, getTestChildren(result, e.item, index), { diffIdentityProvider });
            }
            return;
          }
          queueTaskChildrenUpdate(taskNode);
        }
      }));
      disposable.add(result.onComplete(() => {
        cc.get(result)?.changeEmitter.fire();
        disposable.dispose();
      }));
    };
    this.B(results.onResultsChanged((e) => {
      if (this.f) {
        return;
      }
      if ("completed" in e) {
        cc.get(e.completed)?.changeEmitter.fire();
      } else if ("started" in e) {
        attachToResults(e.started);
      } else {
        this.g.setChildren(null, getRootChildren(), { diffIdentityProvider });
      }
    }));
    const revealItem = (element, preserveFocus) => {
      this.g.setFocus([element]);
      this.g.setSelection([element]);
      if (!preserveFocus) {
        this.g.domFocus();
      }
    };
    this.B(onDidReveal(async ({ subject, preserveFocus = false }) => {
      if (subject instanceof $L0b) {
        const resultItem = this.g.getNode(null).children.find((c) => {
          if (c.element instanceof TaskElement) {
            return c.element.results.id === subject.result.id && c.element.index === subject.taskIndex;
          }
          if (c.element instanceof TestResultElement) {
            return c.element.id === subject.result.id;
          }
          return false;
        });
        if (resultItem) {
          revealItem(resultItem.element, preserveFocus);
        }
        return;
      }
      const revealElement = subject instanceof $M0b ? cc.get(subject.task)?.itemsCache.get(subject.test) : cc.get(subject.message);
      if (!revealElement || !this.g.hasElement(revealElement)) {
        return;
      }
      const parents = [];
      for (let parent = this.g.getParentElement(revealElement); parent; parent = this.g.getParentElement(parent)) {
        parents.unshift(parent);
      }
      for (const parent of parents) {
        this.g.expand(parent);
      }
      if (this.g.getRelativeTop(revealElement) === null) {
        this.g.reveal(revealElement, 0.5);
      }
      revealItem(revealElement, preserveFocus);
    }));
    this.B(this.g.onDidOpen(async (e) => {
      if (e.element instanceof TestMessageElement) {
        this.j.fire(new $K0b(e.element.result, e.element.test, e.element.taskIndex, e.element.messageIndex));
      } else if (e.element instanceof TestCaseElement) {
        const t = e.element;
        const message = $O0b(e.element.test, (_t, _m, mesasgeIndex, taskIndex) => new $K0b(t.results, t.test, taskIndex, mesasgeIndex));
        this.j.fire(message || new $M0b(t.results, 0, t.test));
      } else if (e.element instanceof CoverageElement) {
        const task = e.element.task;
        if (e.element.isOpen) {
          return coverageService.closeCoverage();
        }
        progressService.withProgress({ location: options3.locationForProgress }, () => coverageService.openCoverage(task, true));
      }
    }));
    this.B(this.g.onDidChangeSelection((evt) => {
      for (const element of evt.elements) {
        if (element && "test" in element) {
          explorerFilter.reveal.set(element.test.item.extId, void 0);
          break;
        }
      }
    }));
    this.B(explorerFilter.onDidSelectTestInExplorer((testId) => {
      if (this.g.getSelection().some((e) => e && "test" in e && e.test.item.extId === testId)) {
        return;
      }
      for (const node of this.g.getNode(null).children) {
        if (node.element instanceof TaskElement) {
          for (const testNode of node.children) {
            if (testNode.element instanceof TestCaseElement && testNode.element.test.item.extId === testId) {
              this.g.setSelection([testNode.element]);
              if (this.g.getRelativeTop(testNode.element) === null) {
                this.g.reveal(testNode.element, 0.5);
              }
              break;
            }
          }
        }
      }
    }));
    this.B(this.g.onContextMenu((e) => this.s(e)));
    this.B(this.g.onDidChangeCollapseState((e) => {
      if (e.node.element instanceof OlderResultsElement && !e.node.collapsed) {
        telemetryService.publicLog2("testing.expandOlderResults");
      }
    }));
    this.g.setChildren(null, getRootChildren());
    for (const result of results.results) {
      if (!result.completedAt && result instanceof $RQ) {
        attachToResults(result);
      }
    }
  }
  layout(height, width2) {
    this.g.layout(height, width2);
  }
  s(evt) {
    if (!evt.element) {
      return;
    }
    const actions = this.h.provideActionBar(evt.element);
    this.r.showContextMenu({
      getAnchor: () => evt.anchor,
      getActions: () => actions.secondary.length ? [...actions.primary, new $Wm(), ...actions.secondary] : actions.primary,
      getActionsContext: () => evt.element?.context
    });
  }
  dispose() {
    super.dispose();
    this.f = true;
  }
};
$80b = __decorate([
  __param(3, $50),
  __param(4, $FTb),
  __param(5, $Pk),
  __param(6, $60b),
  __param(7, $y9b),
  __param(8, $TJ),
  __param(9, $zv)
], $80b);
var TestRunElementRenderer = class TestRunElementRenderer2 {
  static {
    TestRunElementRenderer_1 = this;
  }
  static {
    this.ID = "testRunElementRenderer";
  }
  constructor(d, f) {
    this.d = d;
    this.f = f;
    this.templateId = TestRunElementRenderer_1.ID;
  }
  /** @inheritdoc */
  renderCompressedElements(node, _index, templateData) {
    const chain = node.element.elements;
    const lastElement = chain[chain.length - 1];
    if ((lastElement instanceof TaskElement || lastElement instanceof TestMessageElement) && chain.length >= 2) {
      this.g(chain[chain.length - 2], templateData, lastElement);
    } else {
      this.g(lastElement, templateData);
    }
  }
  /** @inheritdoc */
  renderTemplate(container2) {
    const templateDisposable = new $2c();
    const wrapper = $bk(container2, $(".test-peek-item"));
    const icon2 = $bk(wrapper, $(".state"));
    const label3 = $bk(wrapper, $(".name"));
    const actionBar = new $LZ(wrapper, {
      actionViewItemProvider: (action, options3) => action instanceof $fJ ? this.f.createInstance($T$, action, { hoverDelegate: options3.hoverDelegate }) : void 0
    });
    const elementDisposable = new $2c();
    templateDisposable.add(elementDisposable);
    templateDisposable.add(actionBar);
    return {
      icon: icon2,
      label: label3,
      actionBar,
      elementDisposable,
      templateDisposable
    };
  }
  /** @inheritdoc */
  renderElement(element, _index, templateData) {
    this.g(element.element, templateData);
  }
  /** @inheritdoc */
  disposeTemplate(templateData) {
    templateData.templateDisposable.dispose();
  }
  /** Called to render a new element */
  g(element, templateData, subjectElement) {
    templateData.elementDisposable.clear();
    templateData.elementDisposable.add(element.onDidChange(() => this.g(element, templateData, subjectElement)));
    this.h(element, templateData, subjectElement);
  }
  /** Called, and may be re-called, to render or re-render an element */
  h(element, templateData, subjectElement) {
    let { label: label3, labelWithIcons, description } = element;
    if (subjectElement instanceof TestMessageElement) {
      description = subjectElement.label;
    }
    const descriptionElement = description ? $("span.test-label-description", {}, description) : "";
    if (labelWithIcons) {
      $dk(templateData.label, ...labelWithIcons, descriptionElement);
    } else {
      $dk(templateData.label, label3, descriptionElement);
    }
    const icon2 = element.icon;
    templateData.icon.className = `computed-state ${icon2 ? ThemeIcon.asClassName(icon2) : ""}`;
    const actions = this.d.provideActionBar(element);
    templateData.actionBar.clear();
    templateData.actionBar.context = element.context;
    templateData.actionBar.push(actions.primary, { icon: true, label: false });
  }
};
TestRunElementRenderer = TestRunElementRenderer_1 = __decorate([
  __param(1, $Pk)
], TestRunElementRenderer);
var TreeActionsProvider = class TreeActionsProvider2 {
  constructor(d, f, g, h3, j, k, l) {
    this.d = d;
    this.f = f;
    this.g = g;
    this.h = h3;
    this.j = j;
    this.k = k;
    this.l = l;
  }
  provideActionBar(element) {
    const test = element instanceof TestCaseElement ? element.test : void 0;
    const capabilities = test ? this.k.capabilitiesForTest(test.item) : 0;
    const contextKeys = [
      [
        "peek",
        "editor.contrib.testingOutputPeek"
        /* Testing.OutputPeekContributionId */
      ],
      [TestingContextKeys.peekItemType.key, element.type]
    ];
    let id2 = $bJ.TestPeekElement;
    const primary = [];
    const secondary = [];
    if (element instanceof TaskElement) {
      primary.push(new $Um("testing.outputPeek.showResultOutput", localize(11231, null), ThemeIcon.asClassName($6l.terminal), void 0, () => this.f.fire(new $L0b(element.results, element.index))));
      if (element.task.running) {
        primary.push(new $Um("testing.outputPeek.cancel", localize(11232, null), ThemeIcon.asClassName($g0b), void 0, () => this.j.executeCommand("testing.cancelRun", element.results.id, element.task.id)));
      } else {
        primary.push(new $Um("testing.outputPeek.rerun", localize(11233, null), ThemeIcon.asClassName($a0b), void 0, () => this.j.executeCommand("testing.reRunLastRun", element.results.id)));
        primary.push(new $Um("testing.outputPeek.debug", localize(11234, null), ThemeIcon.asClassName($d0b), void 0, () => this.j.executeCommand("testing.debugLastRun", element.results.id)));
      }
    }
    if (element instanceof TestResultElement) {
      if (element.value.tasks.length === 1) {
        primary.push(new $Um("testing.outputPeek.showResultOutput", localize(11235, null), ThemeIcon.asClassName($6l.terminal), void 0, () => this.f.fire(new $L0b(element.value, 0))));
      }
      primary.push(new $Um("testing.outputPeek.reRunLastRun", localize(11236, null), ThemeIcon.asClassName($_9b), void 0, () => this.j.executeCommand("testing.reRunLastRun", element.value.id)));
      if (capabilities & 4) {
        primary.push(new $Um("testing.outputPeek.debugLastRun", localize(11237, null), ThemeIcon.asClassName($d0b), void 0, () => this.j.executeCommand("testing.debugLastRun", element.value.id)));
      }
    }
    if (element instanceof TestCaseElement || element instanceof TestMessageElement) {
      contextKeys.push([TestingContextKeys.testResultOutdated.key, element.test.retired], [TestingContextKeys.testResultState.key, $nQ[element.test.ownComputedState]], ...$F0b(element.test, capabilities));
      const extId = element.test.item.extId;
      if (element.test.tasks[element.taskIndex].messages.some(
        (m) => m.type === 1
        /* TestMessageType.Output */
      )) {
        primary.push(new $Um("testing.outputPeek.showResultOutput", localize(11238, null), ThemeIcon.asClassName($6l.terminal), void 0, () => this.f.fire(element.outputSubject)));
      }
      secondary.push(new $Um("testing.outputPeek.revealInExplorer", localize(11239, null), ThemeIcon.asClassName($6l.listTree), void 0, () => this.j.executeCommand("_revealTestInExplorer", extId)));
      if (capabilities & 2) {
        primary.push(new $Um("testing.outputPeek.runTest", localize(11240, null), ThemeIcon.asClassName($_9b), void 0, () => this.j.executeCommand("vscode.runTestsById", 2, extId)));
      }
      if (capabilities & 4) {
        primary.push(new $Um("testing.outputPeek.debugTest", localize(11241, null), ThemeIcon.asClassName($d0b), void 0, () => this.j.executeCommand("vscode.runTestsById", 4, extId)));
      }
    }
    if (element instanceof TestMessageElement) {
      id2 = $bJ.TestMessageContext;
      contextKeys.push([TestingContextKeys.testMessageContext.key, element.contextValue]);
      primary.push(new $Um("testing.outputPeek.goToTest", localize(11242, null), ThemeIcon.asClassName($6l.goToFile), void 0, () => this.j.executeCommand("vscode.revealTest", element.test.item.extId)));
      if (this.d && element.location) {
        primary.push(new $Um("testing.outputPeek.goToError", localize(11243, null), ThemeIcon.asClassName($6l.debugStackframe), void 0, () => this.l.openEditor({
          resource: element.location.uri,
          options: {
            selection: element.location.range,
            preserveFocus: true
          }
        })));
      }
    }
    const contextOverlay = this.g.createOverlay(contextKeys);
    const result = { primary, secondary };
    const menu = this.h.getMenuActions(id2, contextOverlay, { arg: element.context });
    $S$(menu, result, "inline");
    return result;
  }
};
TreeActionsProvider = __decorate([
  __param(2, $on),
  __param(3, $cJ),
  __param(4, $sn),
  __param(5, $wTb),
  __param(6, $mJ)
], TreeActionsProvider);
var CreationCache = class {
  constructor() {
    this.d = /* @__PURE__ */ new WeakMap();
  }
  get(key2) {
    return this.d.get(key2);
  }
  getOrCreate(ref, factory) {
    const existing = this.d.get(ref);
    if (existing) {
      return existing;
    }
    const fresh = factory();
    this.d.set(ref, fresh);
    return fresh;
  }
};
var firstLine = (str) => {
  const index = str.indexOf("\n");
  return index === -1 ? str : str.slice(0, index);
};

// out-build/vs/workbench/contrib/testing/browser/testResultsView/testResultsViewContent.js
var $90b_1;
var SubView;
(function(SubView2) {
  SubView2[SubView2["Diff"] = 0] = "Diff";
  SubView2[SubView2["History"] = 1] = "History";
})(SubView || (SubView = {}));
var MessageStackFrame = class MessageStackFrame2 extends $S0b {
  constructor(a, b, c, g, j, k) {
    super();
    this.a = a;
    this.b = b;
    this.c = c;
    this.g = g;
    this.j = j;
    this.k = k;
    this.height = $he("MessageStackFrame.height", 100);
    this.icon = $09b;
    this.label = c instanceof $K0b ? c.test.label : c instanceof $M0b ? c.test.item.label : c.result.name;
  }
  render(container2) {
    this.a.style.visibility = "visible";
    container2.appendChild(this.a);
    return $1c(() => this.a.remove());
  }
  renderActions(container2) {
    const store = new $2c();
    container2.appendChild(this.b.domNode);
    store.add($1c(() => this.b.domNode.remove()));
    const test = $P0b(this.c);
    const capabilities = test && this.k.capabilitiesForTest(test);
    let contextKeyService;
    if (capabilities) {
      contextKeyService = this.j.createOverlay($yTb(capabilities));
    } else {
      const profiles2 = this.k.getControllerProfiles(this.c.controllerId);
      contextKeyService = this.j.createOverlay([
        [TestingContextKeys.hasRunnableTests.key, profiles2.some(
          (p) => p.group & 2
          /* TestRunProfileBitset.Run */
        )],
        [TestingContextKeys.hasDebuggableTests.key, profiles2.some(
          (p) => p.group & 4
          /* TestRunProfileBitset.Debug */
        )]
      ]);
    }
    const instaService = store.add(this.g.createChild(new $Ok([$on, contextKeyService])));
    const toolbar = store.add(instaService.createInstance($4$, container2, $bJ.TestCallStack, {
      menuOptions: { shouldForwardArgs: true },
      actionViewItemProvider: (action, options3) => $X$(this.g, action, options3)
    }));
    toolbar.context = this.c;
    store.add(toolbar);
    return store;
  }
};
MessageStackFrame = __decorate([
  __param(3, $Pk),
  __param(4, $on),
  __param(5, $wTb)
], MessageStackFrame);
function runInLast(accessor, bitset, subject) {
  if (subject instanceof $L0b) {
    return accessor.get($sn).executeCommand(bitset === 4 ? "testing.debugLastRun" : "testing.reRunLastRun", subject.result.id);
  }
  const testService = accessor.get($nTb);
  const plainTest = subject instanceof $K0b ? subject.test : subject.test.item;
  const currentTest = testService.collection.getNodeById(plainTest.extId);
  if (!currentTest) {
    return;
  }
  return testService.runTests({
    group: bitset,
    tests: [currentTest]
  });
}
$hJ(class extends $gJ {
  constructor() {
    super({
      id: "testing.callStack.run",
      title: localize(11244, null),
      icon: $_9b,
      menu: {
        id: $bJ.TestCallStack,
        when: TestingContextKeys.hasRunnableTests,
        group: "navigation"
      }
    });
  }
  run(accessor, subject) {
    runInLast(accessor, 2, subject);
  }
});
$hJ(class extends $gJ {
  constructor() {
    super({
      id: "testing.callStack.debug",
      title: localize(11245, null),
      icon: $d0b,
      menu: {
        id: $bJ.TestCallStack,
        when: TestingContextKeys.hasDebuggableTests,
        group: "navigation"
      }
    });
  }
  run(accessor, subject) {
    runInLast(accessor, 4, subject);
  }
});
var $90b = class $90b2 extends $3c {
  static {
    $90b_1 = this;
  }
  get uiState() {
    return {
      splitViewWidths: Array.from({ length: this.C.length }, (_, i2) => this.C.getViewSize(i2))
    };
  }
  constructor(H, I, J, L, M, N) {
    super();
    this.H = H;
    this.I = I;
    this.J = J;
    this.L = L;
    this.M = M;
    this.N = N;
    this.b = this.B(new $ze());
    this.c = this.B(new $2c());
    this.g = this.B(new $Ie());
    this.G = this.B(new $2h(1));
    this.onClose = this.g.event;
  }
  fillBody(containerElement) {
    const initialSpitWidth = $90b_1.a;
    this.C = new $r2(containerElement, {
      orientation: 1
      /* Orientation.HORIZONTAL */
    });
    const { historyVisible, showRevealLocationOnMessages } = this.I;
    const isInPeekView = this.H !== void 0;
    const messageContainer = this.D = $(".test-output-peek-message-container");
    this.t = $bk(containerElement, $(".test-output-call-stack-container"));
    this.u = this.B(this.J.createInstance($V0b, this.t, this.H));
    this.j = this.B(this.J.createInstance(FollowupActionWidget, this.H));
    this.g.input = this.j.onClose;
    this.F = [
      this.B(this.J.createInstance($20b, this.H, messageContainer)),
      this.B(this.J.createInstance($30b, messageContainer)),
      this.B(this.J.createInstance($50b, messageContainer, isInPeekView)),
      this.B(this.J.createInstance($40b, this.H, messageContainer))
    ];
    this.m = this.B(this.M.createScoped(containerElement));
    this.n = TestingContextKeys.testMessageContext.bindTo(this.m);
    this.s = TestingContextKeys.testResultOutdated.bindTo(this.m);
    const treeContainer = $bk(containerElement, $(".test-output-peek-tree"));
    const tree = this.B(this.J.createInstance($80b, treeContainer, this.b.event, { showRevealLocationOnMessages, locationForProgress: this.I.locationForProgress }));
    this.onDidRequestReveal = tree.onDidRequestReview;
    this.C.addView({
      onDidChange: Event2.None,
      element: this.t,
      minimumSize: 200,
      maximumSize: Number.MAX_VALUE,
      layout: (width2) => {
        $90b_1.a = width2;
        if (this.z) {
          this.u?.layout(this.z.height, width2);
          this.Q(this.z, width2);
        }
      }
    }, Sizing.Distribute);
    this.C.addView({
      onDidChange: Event2.None,
      element: treeContainer,
      minimumSize: 100,
      maximumSize: Number.MAX_VALUE,
      layout: (width2) => {
        if (this.z) {
          tree.layout(this.z.height, width2);
        }
      }
    }, Sizing.Distribute);
    this.C.setViewVisible(1, historyVisible.value);
    this.B(historyVisible.onDidChange((visible) => {
      this.C.setViewVisible(1, visible);
    }));
    if (initialSpitWidth) {
      queueMicrotask(() => this.C.resizeView(0, initialSpitWidth));
    }
  }
  /**
   * Shows a message in-place without showing or changing the peek location.
   * This is mostly used if peeking a message without a location.
   */
  reveal(opts) {
    this.b.fire(opts);
    if (this.current && $N0b(this.current, opts.subject)) {
      return Promise.resolve();
    }
    this.current = opts.subject;
    return this.G.queue(async () => {
      this.c.clear();
      const callFrames = this.O(opts.subject) || [];
      const topFrame = await this.P(opts.subject, callFrames);
      this.u.update(topFrame, callFrames);
      this.j.show(opts.subject);
      this.R(opts.subject);
    });
  }
  /**
   * Collapses all displayed stack frames.
   */
  collapseStack() {
    this.u.collapseAll();
  }
  O(subject) {
    if (!(subject instanceof $K0b)) {
      return void 0;
    }
    const frames = subject.stack;
    if (!frames?.length || !this.H) {
      return frames;
    }
    const topFrame = frames[0];
    const peekLocation = subject.revealLocation;
    const isTopFrameSame = peekLocation && topFrame.position && topFrame.uri && topFrame.position.lineNumber === peekLocation.range.startLineNumber && topFrame.position.column === peekLocation.range.startColumn && this.N.extUri.isEqual(topFrame.uri, peekLocation.uri);
    return isTopFrameSame ? frames.slice(1) : frames;
  }
  async P(subject, callFrames) {
    this.D.style.visibility = "hidden";
    this.t.appendChild(this.D);
    const topFrame = this.w = this.J.createInstance(MessageStackFrame, this.D, this.j, subject);
    const hasMultipleFrames = callFrames.length > 0;
    topFrame.showHeader.set(hasMultipleFrames, void 0);
    const provider = await $ec(this.F, (p) => p.update(subject));
    if (provider) {
      const width2 = this.C.getViewSize(
        0
        /* SubView.Diff */
      );
      if (width2 !== -1 && this.z) {
        topFrame.height.set(provider.layout({ width: width2, height: this.z?.height }, hasMultipleFrames), void 0);
      }
      if (provider.onScrolled) {
        this.c.add(this.u.onDidScroll((evt) => {
          provider.onScrolled(evt);
        }));
      }
      if (provider.onDidContentSizeChange) {
        this.c.add(provider.onDidContentSizeChange(() => {
          if (this.z && !this.y) {
            this.y = true;
            topFrame.height.set(provider.layout(this.z, hasMultipleFrames), void 0);
            this.y = false;
          }
        }));
      }
    }
    return topFrame;
  }
  Q(dimension, width2 = this.C.getViewSize(
    0
    /* SubView.Diff */
  )) {
    this.y = true;
    for (const provider of this.F) {
      const frameHeight = provider.layout({ height: dimension.height, width: width2 }, !!this.w?.showHeader.get());
      if (frameHeight) {
        this.w?.height.set(frameHeight, void 0);
      }
    }
    this.y = false;
  }
  R(subject) {
    if (!(subject instanceof $K0b)) {
      return;
    }
    this.c.add($1c(() => {
      this.s.reset();
      this.n.reset();
    }));
    this.n.set(subject.contextValue || "");
    if (subject.result instanceof $RQ) {
      this.s.set(subject.result.getStateById(subject.test.extId)?.retired ?? false);
      this.c.add(subject.result.onChange((ev) => {
        if (ev.item.item.extId === subject.test.extId) {
          this.s.set(ev.item.retired ?? false);
        }
      }));
    } else {
      this.s.set(true);
    }
    const instaService = this.c.add(this.J.createChild(new $Ok([$on, this.m])));
    this.c.add(instaService.createInstance($ALb, {
      container: this.D,
      menuId: $bJ.TestMessageContent,
      getActionArg: () => subject.context
    }));
  }
  onLayoutBody(height, width2) {
    this.z = new $rj(width2, height);
    this.C.layout(width2);
  }
  onWidth(width2) {
    this.C.layout(width2);
  }
};
$90b = $90b_1 = __decorate([
  __param(2, $Pk),
  __param(3, $oG),
  __param(4, $on),
  __param(5, $vl)
], $90b);
var FOLLOWUP_ANIMATION_MIN_TIME = 500;
var FollowupActionWidget = class FollowupActionWidget2 extends $3c {
  get domNode() {
    return this.a.root;
  }
  constructor(g, j, m) {
    super();
    this.g = g;
    this.j = j;
    this.m = m;
    this.a = h("div.testing-followup-action", []);
    this.b = this.B(new $2c());
    this.c = this.B(new $ze());
    this.onClose = this.c.event;
  }
  show(subject) {
    this.b.clear();
    if (subject instanceof $K0b) {
      this.n(subject);
    }
  }
  async n(subject) {
    const cts = this.b.add(new $ad());
    const start = Date.now();
    if (subject.result instanceof $RQ && !subject.result.completedAt) {
      await new Promise((r2) => Event2.once(subject.result.onComplete)(r2));
    }
    const followups = await this.j.provideTestFollowups({
      extId: subject.test.extId,
      messageIndex: subject.messageIndex,
      resultId: subject.result.id,
      taskIndex: subject.taskIndex
    }, cts.token);
    if (!followups.followups.length || cts.token.isCancellationRequested) {
      followups.dispose();
      return;
    }
    this.b.add(followups);
    $$i(this.a.root);
    this.a.root.classList.toggle("animated", Date.now() - start > FOLLOWUP_ANIMATION_MIN_TIME);
    this.a.root.appendChild(this.s(followups.followups[0]));
    if (followups.followups.length > 1) {
      this.a.root.appendChild(this.t(followups.followups));
    }
    this.b.add($1c(() => {
      this.a.root.remove();
    }));
  }
  s(first) {
    const link2 = this.u(() => this.w(link2, first));
    $dk(link2, ...$B1(first.message));
    return link2;
  }
  t(followups) {
    const link2 = this.u(() => this.m.pick(followups.map((f, i2) => ({
      label: f.message,
      index: i2
    }))).then((picked) => {
      if (picked?.length) {
        followups[picked[0].index].execute();
      }
    }));
    link2.innerText = localize(11246, null, followups.length - 1);
    return link2;
  }
  u(onClick2) {
    const link2 = document.createElement("a");
    link2.tabIndex = 0;
    this.b.add($_i(link2, "click", onClick2));
    this.b.add($_i(link2, "keydown", (e) => {
      const event = new $if(e);
      if (event.equals(
        10
        /* KeyCode.Space */
      ) || event.equals(
        3
        /* KeyCode.Enter */
      )) {
        onClick2();
      }
    }));
    return link2;
  }
  w(link2, fu) {
    if (link2.ariaDisabled !== "true") {
      link2.ariaDisabled = "true";
      fu.execute();
      if (this.g) {
        this.c.fire();
      }
    }
  }
};
FollowupActionWidget = __decorate([
  __param(1, $nTb),
  __param(2, $1M)
], FollowupActionWidget);

// out-build/vs/workbench/contrib/testing/browser/testingOutputPeek.js
var $$0b_1;
var TestResultsPeek_1;
function* allMessages([result]) {
  if (!result) {
    return;
  }
  for (const test of result.tests) {
    for (let taskIndex = 0; taskIndex < test.tasks.length; taskIndex++) {
      const messages = test.tasks[taskIndex].messages;
      for (let messageIndex = 0; messageIndex < messages.length; messageIndex++) {
        if (messages[messageIndex].type === 0) {
          yield { result, test, taskIndex, messageIndex };
        }
      }
    }
  }
}
function messageItReferenceToUri({ result, test, taskIndex, messageIndex }) {
  return $E0b({
    type: 2,
    resultId: result.id,
    testExtId: test.item.extId,
    taskIndex,
    messageIndex
  });
}
var $00b = class $00b2 extends $3c {
  constructor(b, f, g, h3, j, n, s, t, u) {
    super();
    this.b = b;
    this.f = f;
    this.g = g;
    this.h = h3;
    this.j = j;
    this.n = n;
    this.s = s;
    this.t = t;
    this.u = u;
    this.historyVisible = this.B($lTb.stored(new $jTb({
      key: "testHistoryVisibleInPeek",
      scope: 0,
      target: 0
    }, this.n), false));
    this.B(h3.onTestChanged(this.z, this));
  }
  /** @inheritdoc */
  async open() {
    let uri;
    const active = this.f.activeTextEditorControl;
    if ($P5(active) && active.getModel()?.uri) {
      const modelUri = active.getModel()?.uri;
      if (modelUri) {
        uri = await this.C(modelUri, active.getPosition());
      }
    }
    if (!uri) {
      uri = this.a;
    }
    if (!uri) {
      uri = this.D();
    }
    if (!uri) {
      return false;
    }
    return this.y(uri);
  }
  /** @inheritdoc */
  tryPeekFirstError(result, test, options3) {
    const candidate = this.F(test);
    if (!candidate) {
      return false;
    }
    this.y({
      type: 2,
      documentUri: candidate.location.uri,
      taskIndex: candidate.taskId,
      messageIndex: candidate.index,
      resultId: result.id,
      testExtId: test.item.extId
    }, void 0, { selection: candidate.location.range, selectionRevealType: 3, ...options3 });
    return true;
  }
  /** @inheritdoc */
  peekUri(uri, options3 = {}) {
    const parsed = $D0b(uri);
    const result = parsed && this.h.getResult(parsed.resultId);
    if (!parsed || !result || !("testExtId" in parsed)) {
      return false;
    }
    if (!("messageIndex" in parsed)) {
      return false;
    }
    const message = result.getStateById(parsed.testExtId)?.tasks[parsed.taskIndex].messages[parsed.messageIndex];
    if (!message?.location) {
      return false;
    }
    this.y({
      type: 2,
      documentUri: message.location.uri,
      taskIndex: parsed.taskIndex,
      messageIndex: parsed.messageIndex,
      resultId: result.id,
      testExtId: parsed.testExtId
    }, options3.inEditor, { selection: message.location.range, ...options3.options });
    return true;
  }
  /** @inheritdoc */
  closeAllPeeks() {
    for (const editor of this.g.listCodeEditors()) {
      $$0b.get(editor)?.removePeek();
    }
  }
  openCurrentInEditor() {
    const current = this.w();
    if (!current) {
      return;
    }
    const options3 = { pinned: false, revealIfOpened: true };
    if (current instanceof $L0b || current instanceof $M0b) {
      this.f.openEditor({ resource: current.outputUri, options: options3 });
      return;
    }
    if (current instanceof $M0b) {
      this.f.openEditor({ resource: current.outputUri, options: options3 });
      return;
    }
    const message = current.message;
    if (current.isDiffable) {
      this.f.openEditor({
        original: { resource: current.expectedUri },
        modified: { resource: current.actualUri },
        options: options3
      });
    } else if (typeof message.message === "string") {
      this.f.openEditor({ resource: current.messageUri, options: options3 });
    } else {
      this.t.executeCommand("markdown.showPreview", current.messageUri).catch((err) => {
        this.u.error(localize(11203, null, err.message));
      });
    }
  }
  w() {
    const editor = getPeekedEditorFromFocus(this.g);
    const controller = editor && $$0b.get(editor);
    return controller?.subject.get() ?? this.s.getActiveViewWithId(
      "workbench.panel.testResults.view"
      /* Testing.ResultsViewId */
    )?.subject;
  }
  /** @inheritdoc */
  async y(uri, editor, options3) {
    if ($P5(editor)) {
      this.a = uri;
      $$0b.get(editor)?.show($E0b(this.a));
      return true;
    }
    const pane = await this.f.openEditor({
      resource: uri.documentUri,
      options: { revealIfOpened: true, ...options3 }
    });
    const control = pane?.getControl();
    if (!$P5(control)) {
      return false;
    }
    this.a = uri;
    $$0b.get(control)?.show($E0b(this.a));
    return true;
  }
  /**
   * Opens the peek view on a test failure, based on user preferences.
   */
  z(evt) {
    if (evt.reason !== 1) {
      return;
    }
    const candidate = this.F(evt.item);
    if (!candidate) {
      return;
    }
    if (evt.result.request.continuous && !$w9b(
      this.b,
      "testing.automaticallyOpenPeekViewDuringAutoRun"
      /* TestingConfigKeys.AutoOpenPeekViewDuringContinuousRun */
    )) {
      return;
    }
    const editors = this.g.listCodeEditors();
    const cfg = $w9b(
      this.b,
      "testing.automaticallyOpenPeekView"
      /* TestingConfigKeys.AutoOpenPeekView */
    );
    switch (cfg) {
      case "failureInVisibleDocument": {
        const visibleEditors = this.f.visibleTextEditorControls;
        const editorUris = new Set(visibleEditors.filter($P5).map((e) => e.getModel()?.uri.toString()));
        if (!Iterable.some($PQ(evt.result, evt.item), (i2) => i2.item.uri && editorUris.has(i2.item.uri.toString()))) {
          return;
        }
        break;
      }
      case "failureAnywhere":
        break;
      default:
        return;
    }
    const controllers = editors.map($$0b.get);
    if (controllers.some((c) => c?.subject.get())) {
      return;
    }
    this.tryPeekFirstError(evt.result, evt.item);
  }
  /**
   * Gets the message closest to the given position from a test in the file.
   */
  async C(uri, position) {
    let best;
    let bestDistance = Infinity;
    const demandedUriStr = uri.toString();
    for (const test of this.j.collection.all) {
      const result = this.h.getStateById(test.item.extId);
      if (!result) {
        continue;
      }
      $O0b(result[1], (_task, message, messageIndex, taskIndex) => {
        if (message.type !== 0 || !message.location || message.location.uri.toString() !== demandedUriStr) {
          return;
        }
        const distance = position ? Math.abs(position.lineNumber - message.location.range.startLineNumber) : 0;
        if (!best || distance <= bestDistance) {
          bestDistance = distance;
          best = {
            type: 2,
            testExtId: result[1].item.extId,
            resultId: result[0].id,
            taskIndex,
            messageIndex,
            documentUri: uri
          };
        }
      });
    }
    return best;
  }
  /**
   * Gets any possible still-relevant message from the results.
   */
  D() {
    const seen = /* @__PURE__ */ new Set();
    for (const result of this.h.results) {
      for (const test of result.tests) {
        if (seen.has(test.item.extId)) {
          continue;
        }
        seen.add(test.item.extId);
        const found = $O0b(test, (task, message, messageIndex, taskIndex) => message.location && {
          type: 2,
          testExtId: test.item.extId,
          resultId: result.id,
          taskIndex,
          messageIndex,
          documentUri: message.location.uri
        });
        if (found) {
          return found;
        }
      }
    }
    return void 0;
  }
  /**
   * Gets the first failed message that can be displayed from the result.
   */
  F(test) {
    const fallbackLocation = test.item.uri && test.item.range ? { uri: test.item.uri, range: test.item.range } : void 0;
    let best;
    $O0b(test, (task, message, messageIndex, taskId) => {
      const location3 = message.location || fallbackLocation;
      if (!$yQ(task.state) || !location3) {
        return;
      }
      if (best && message.type !== 0) {
        return;
      }
      best = { taskId, index: messageIndex, message, location: location3 };
    });
    return best;
  }
};
$00b = __decorate([
  __param(0, $kl),
  __param(1, $mJ),
  __param(2, $U5),
  __param(3, $FTb),
  __param(4, $nTb),
  __param(5, $jv),
  __param(6, $uob),
  __param(7, $sn),
  __param(8, $PJ)
], $00b);
var $$0b = $$0b_1 = class $$0b2 extends $3c {
  /**
   * Gets the controller associated with the given code editor.
   */
  static get(editor) {
    return editor.getContribution(
      "editor.contrib.testingOutputPeek"
      /* Testing.OutputPeekContributionId */
    );
  }
  constructor(f, g, h3, j, contextKeyService) {
    super();
    this.f = f;
    this.g = g;
    this.h = h3;
    this.j = j;
    this.a = this.B($je("TestingOutputPeek", void 0));
    this.subject = $2d((reader) => this.a.read(reader)?.current.read(reader));
    this.b = TestingContextKeys.isPeekVisible.bindTo(contextKeyService);
    this.B(f.onDidChangeModel(() => this.a.set(void 0, void 0)));
    this.B(j.onResultsChanged(this.s, this));
    this.B(j.onTestChanged(this.n, this));
  }
  /**
   * Shows a peek for the message in the editor.
   */
  async show(uri) {
    const subject = this.t(uri);
    if (subject) {
      this.showSubject(subject);
    }
  }
  /**
   * Shows a peek for the existing inspect subject.
   */
  async showSubject(subject) {
    if (!this.a.get()) {
      const peek = this.h.createInstance(TestResultsPeek, this.f);
      this.a.set(peek, void 0);
      peek.onDidClose(() => {
        this.b.set(false);
        this.a.set(void 0, void 0);
      });
      this.b.set(true);
      peek.create();
    }
    if (subject instanceof $K0b) {
      $$Z($G0b(subject.message.message));
    }
    this.a.get().setModel(subject);
  }
  async openAndShow(uri) {
    const subject = this.t(uri);
    if (!subject) {
      return;
    }
    if (!subject.revealLocation || subject.revealLocation.uri.toString() === this.f.getModel()?.uri.toString()) {
      return this.show(uri);
    }
    const otherEditor = await this.g.openCodeEditor({
      resource: subject.revealLocation.uri,
      options: { pinned: false, revealIfOpened: true }
    }, this.f);
    if (otherEditor) {
      $$0b_1.get(otherEditor)?.removePeek();
      return $$0b_1.get(otherEditor)?.show(uri);
    }
  }
  /**
   * Disposes the peek view, if any.
   */
  removePeek() {
    this.a.set(void 0, void 0);
  }
  /**
   * Collapses all displayed stack frames.
   */
  collapseStack() {
    this.a.get()?.collapseStack();
  }
  /**
   * Shows the next message in the peek, if possible.
   */
  next() {
    const subject = this.a.get()?.current.get();
    if (!subject) {
      return;
    }
    let first;
    let found = false;
    for (const m of allMessages(this.j.results)) {
      first ??= m;
      if (subject instanceof $L0b && m.result.id === subject.result.id) {
        found = true;
      }
      if (found) {
        this.openAndShow(messageItReferenceToUri(m));
        return;
      }
      if (subject instanceof $M0b && subject.test.item.extId === m.test.item.extId && subject.taskIndex === m.taskIndex && subject.result.id === m.result.id) {
        found = true;
      }
      if (subject instanceof $K0b && subject.test.extId === m.test.item.extId && subject.messageIndex === m.messageIndex && subject.taskIndex === m.taskIndex && subject.result.id === m.result.id) {
        found = true;
      }
    }
    if (first) {
      this.openAndShow(messageItReferenceToUri(first));
    }
  }
  /**
   * Shows the previous message in the peek, if possible.
   */
  previous() {
    const subject = this.subject.get();
    if (!subject) {
      return;
    }
    let previous;
    let previousLockedIn = false;
    let last;
    for (const m of allMessages(this.j.results)) {
      last = m;
      if (!previousLockedIn) {
        if (subject instanceof $L0b) {
          if (m.result.id === subject.result.id) {
            previousLockedIn = true;
          }
          continue;
        }
        if (subject instanceof $M0b) {
          if (m.test.item.extId === subject.test.item.extId && m.result.id === subject.result.id && m.taskIndex === subject.taskIndex) {
            previousLockedIn = true;
          }
          continue;
        }
        if (subject.test.extId === m.test.item.extId && subject.messageIndex === m.messageIndex && subject.taskIndex === m.taskIndex && subject.result.id === m.result.id) {
          previousLockedIn = true;
          continue;
        }
        previous = m;
      }
    }
    const target = previous || last;
    if (target) {
      this.openAndShow(messageItReferenceToUri(target));
    }
  }
  /**
   * Removes the peek view if it's being displayed on the given test ID.
   */
  removeIfPeekingForTest(testId) {
    const c = this.subject.get();
    if (c && c instanceof $K0b && c.test.extId === testId) {
      this.a.set(void 0, void 0);
    }
  }
  /**
   * If the test we're currently showing has its state change to something
   * else, then clear the peek.
   */
  n(evt) {
    if (evt.reason !== 1 || evt.previousState === evt.item.ownComputedState) {
      return;
    }
    this.removeIfPeekingForTest(evt.item.item.extId);
  }
  s(evt) {
    if ("started" in evt) {
      this.a.set(void 0, void 0);
    }
    if ("removed" in evt && this.j.results.length === 0) {
      this.a.set(void 0, void 0);
    }
  }
  t(uri) {
    const parts = $D0b(uri);
    if (!parts) {
      return void 0;
    }
    const result = this.j.results.find((r2) => r2.id === parts.resultId);
    if (!result) {
      return;
    }
    if (parts.type === 0) {
      return new $L0b(result, parts.taskIndex);
    }
    if (parts.type === 1) {
      const test2 = result.getStateById(parts.testExtId);
      if (!test2) {
        return;
      }
      return new $M0b(result, parts.taskIndex, test2);
    }
    const { testExtId, taskIndex, messageIndex } = parts;
    const test = result?.getStateById(testExtId);
    if (!test || !test.tasks[parts.taskIndex]) {
      return;
    }
    return new $K0b(result, test, taskIndex, messageIndex);
  }
};
$$0b = $$0b_1 = __decorate([
  __param(1, $U5),
  __param(2, $Pk),
  __param(3, $FTb),
  __param(4, $on)
], $$0b);
var TestResultsPeek = class TestResultsPeek2 extends $ceb {
  static {
    TestResultsPeek_1 = this;
  }
  constructor(editor, db, peekViewService, eb, fb, gb, instantiationService, hb, ib, jb) {
    super(editor, { showFrame: true, frameWidth: 1, showArrow: true, isResizeable: true, isAccessible: true, className: "test-output-peek" }, instantiationService);
    this.db = db;
    this.eb = eb;
    this.fb = fb;
    this.gb = gb;
    this.hb = hb;
    this.ib = ib;
    this.jb = jb;
    this.b = this.n.add(new $ze());
    this.current = $he("testPeekCurrent", void 0);
    this.n.add(db.onDidColorThemeChange(this.kb, this));
    this.n.add(this.onDidClose(() => this.b.fire(false)));
    peekViewService.addExclusiveWidget(editor, this);
  }
  kb() {
    const theme = this.db.getColorTheme();
    const current = this.current.get();
    const isError = current instanceof $K0b && current.message.type === 0;
    const borderColor = (isError ? theme.getColor($O9b) : theme.getColor($P9b)) || $Vn.transparent;
    const headerBg = (isError ? theme.getColor($Q9b) : theme.getColor($R9b)) || $Vn.transparent;
    const editorBg = theme.getColor($Ko);
    this.style({
      arrowColor: borderColor,
      frameColor: borderColor,
      headerBackgroundColor: editorBg && headerBg ? headerBg.makeOpaque(editorBg) : headerBg,
      primaryHeadingColor: theme.getColor($eeb),
      secondaryHeadingColor: theme.getColor($feb)
    });
  }
  B(container2) {
    if (!this.bb) {
      this.bb = this.n.add(this.fb.createScoped(container2));
      TestingContextKeys.isInPeek.bindTo(this.bb).set(true);
      const instaService = this.n.add(this.Q.createChild(new $Ok([$on, this.bb])));
      this.d = this.n.add(instaService.createInstance($90b, this.editor, {
        historyVisible: this.eb.historyVisible,
        showRevealLocationOnMessages: false,
        locationForProgress: "workbench.panel.testResults.view"
        /* Testing.ResultsViewId */
      }));
      this.n.add(this.d.onClose(() => {
        $$0b.get(this.editor)?.removePeek();
      }));
    }
    super.B(container2);
  }
  T(container2) {
    super.T(container2);
    const menuContextKeyService = this.n.add(this.fb.createScoped(container2));
    this.n.add($H9(TestingContextKeys.peekHasStack, menuContextKeyService, (reader) => $J0b(this.current.read(reader))));
    const menu = this.gb.createMenu($bJ.TestPeekTitle, menuContextKeyService);
    const actionBar = this.O;
    this.n.add(menu.onDidChange(() => {
      actions.length = 0;
      $S$(menu.getActions(), actions);
      while (actionBar.getAction(1)) {
        actionBar.pull(0);
      }
      actionBar.push(actions, { label: false, icon: true, index: 0 });
    }));
    const actions = [];
    $S$(menu.getActions(), actions);
    actionBar.push(actions, { label: false, icon: true, index: 0 });
  }
  X(containerElement) {
    this.d.fillBody(containerElement);
    this.n.add(this.d.onDidRequestReveal((sub) => {
      $$0b.get(this.editor)?.show(sub instanceof $K0b ? sub.messageUri : sub.outputUri);
    }));
  }
  /**
   * Updates the test to be shown.
   */
  setModel(subject) {
    if (subject instanceof $L0b || subject instanceof $M0b) {
      this.current.set(subject, void 0);
      return this.showInPlace(subject);
    }
    const message = subject.message;
    const previous = this.current;
    const revealLocation = subject.revealLocation?.range.getStartPosition();
    if (!revealLocation && !previous) {
      return Promise.resolve();
    }
    this.current.set(subject, void 0);
    if (!revealLocation) {
      return this.showInPlace(subject);
    }
    const peekLines = TestResultsPeek_1.a || Math.max($J0b(subject) ? Math.ceil(this.ob() / 2) : 0, hintMessagePeekHeight(message));
    this.show(revealLocation, peekLines);
    this.editor.revealRangeNearTopIfOutsideViewport(
      $9C.fromPositions(revealLocation),
      0
      /* ScrollType.Smooth */
    );
    return this.showInPlace(subject);
  }
  /**
   * Collapses all displayed stack frames.
   */
  collapseStack() {
    this.d.collapseStack();
  }
  ob() {
    return Math.round(this.editor.getDomNode().clientHeight / this.editor.getOption(
      68
      /* EditorOption.lineHeight */
    ));
  }
  /**
   * Shows a message in-place without showing or changing the peek location.
   * This is mostly used if peeking a message without a location.
   */
  async showInPlace(subject) {
    if (subject instanceof $K0b) {
      const message = subject.message;
      this.setTitle(firstLine2($G0b(message.message)), $0l(subject.test.label));
    } else {
      this.setTitle(localize(11204, null));
    }
    this.kb();
    await this.d.reveal({ subject, preserveFocus: false });
  }
  E(newHeightInLines) {
    super.E(newHeightInLines);
    TestResultsPeek_1.a = newHeightInLines;
  }
  /** @override */
  ab(height, width2) {
    super.ab(height, width2);
    this.d.onLayoutBody(height, width2);
  }
  /** @override */
  C(width2) {
    super.C(width2);
    if (this.cb) {
      this.cb = new $rj(width2, this.cb.height);
    }
    this.d.onWidth(width2);
  }
};
TestResultsPeek = TestResultsPeek_1 = __decorate([
  __param(1, $gs),
  __param(2, $aeb),
  __param(3, $B0b),
  __param(4, $on),
  __param(5, $cJ),
  __param(6, $Pk),
  __param(7, $oG),
  __param(8, $U5),
  __param(9, $vl)
], TestResultsPeek);
var $_0b = class $_0b2 extends $_ob {
  constructor(options3, keybindingService, contextMenuService, configurationService, contextKeyService, viewDescriptorService, instantiationService, openerService, themeService, telemetryService, hoverService, b) {
    super(options3, keybindingService, contextMenuService, configurationService, contextKeyService, viewDescriptorService, instantiationService, openerService, themeService, telemetryService, hoverService);
    this.b = b;
    this.a = new $sf(() => this.B(this.Db.createInstance($90b, void 0, {
      historyVisible: $kTb(true),
      showRevealLocationOnMessages: true,
      locationForProgress: "workbench.view.testing"
    })));
  }
  get subject() {
    return this.a.rawValue?.current;
  }
  showLatestRun(preserveFocus = false) {
    const result = this.b.results.find((r2) => r2.tasks.length);
    if (!result) {
      return;
    }
    this.a.rawValue?.reveal({ preserveFocus, subject: new $L0b(result, 0) });
  }
  W(container2) {
    super.W(container2);
    if (this.isBodyVisible()) {
      this.h(container2);
    } else {
      this.B(Event2.once(Event2.filter(this.onDidChangeBodyVisibility, Boolean))(() => this.h(container2)));
    }
  }
  X(height, width2) {
    super.X(height, width2);
    this.a.rawValue?.onLayoutBody(height, width2);
  }
  h(container2) {
    const content = this.a.value;
    content.fillBody(container2);
    this.B(content.onDidRequestReveal((subject) => content.reveal({ preserveFocus: true, subject })));
    const [lastResult] = this.b.results;
    if (lastResult && lastResult.tasks.length) {
      content.reveal({ preserveFocus: true, subject: new $L0b(lastResult, 0) });
    }
  }
};
$_0b = __decorate([
  __param(1, $Ty),
  __param(2, $50),
  __param(3, $kl),
  __param(4, $on),
  __param(5, $$M),
  __param(6, $Pk),
  __param(7, $O4),
  __param(8, $gs),
  __param(9, $zv),
  __param(10, $5$),
  __param(11, $FTb)
], $_0b);
var hintMessagePeekHeight = (msg) => {
  const msgHeight = ITestMessage.isDiffable(msg) ? Math.max(hintPeekStrHeight(msg.actual), hintPeekStrHeight(msg.expected)) : hintPeekStrHeight(typeof msg.message === "string" ? msg.message : msg.message.value);
  return msgHeight + 8;
};
var firstLine2 = (str) => {
  const index = str.indexOf("\n");
  return index === -1 ? str : str.slice(0, index);
};
var hintPeekStrHeight = (str) => Math.min($Bf(str, "\n"), 24);
function getOuterEditorFromDiffEditor2(codeEditorService) {
  const diffEditors = codeEditorService.listDiffEditors();
  for (const diffEditor of diffEditors) {
    if (diffEditor.hasTextFocus() && diffEditor instanceof $zEb) {
      return diffEditor.getParentEditor();
    }
  }
  return null;
}
var $a$b = class extends $25 {
  constructor() {
    super({
      id: "editor.closeTestPeek",
      title: localize2(11205, "Close"),
      icon: $6l.close,
      precondition: $7m.or(TestingContextKeys.isInPeek, TestingContextKeys.isPeekVisible),
      keybinding: {
        weight: 100 - 101,
        primary: 9,
        when: $7m.not("config.editor.stablePeek")
      }
    });
  }
  runEditorCommand(accessor, editor) {
    const parent = getPeekedEditorFromFocus(accessor.get($U5));
    $$0b.get(parent ?? editor)?.removePeek();
  }
};
var navWhen = $7m.and(EditorContextKeys.focus, TestingContextKeys.isPeekVisible);
var getPeekedEditorFromFocus = (codeEditorService) => {
  const editor = codeEditorService.getFocusedCodeEditor() || codeEditorService.getActiveCodeEditor();
  return editor && getPeekedEditor(codeEditorService, editor);
};
var getPeekedEditor = (codeEditorService, editor) => {
  if ($$0b.get(editor)?.subject.get()) {
    return editor;
  }
  if (editor instanceof $bdb) {
    return editor.getParentEditor();
  }
  const outer = getOuterEditorFromDiffEditor2(codeEditorService);
  if (outer) {
    return outer;
  }
  return editor;
};
var $b$b = class _$b$b extends $gJ {
  static {
    this.ID = "testing.goToNextMessage";
  }
  constructor() {
    super({
      id: _$b$b.ID,
      f1: true,
      title: localize2(11206, "Go to Next Test Failure"),
      metadata: {
        description: localize2(11207, "Shows the next failure message in your file")
      },
      icon: $6l.arrowDown,
      category: $qn.Test,
      keybinding: {
        primary: 512 | 66,
        weight: 100 + 1,
        when: navWhen
      },
      menu: [{
        id: $bJ.TestPeekTitle,
        group: "navigation",
        order: 2
      }, {
        id: $bJ.CommandPalette,
        when: navWhen
      }]
    });
  }
  run(accessor) {
    const editor = getPeekedEditorFromFocus(accessor.get($U5));
    if (editor) {
      $$0b.get(editor)?.next();
    }
  }
};
var $c$b = class _$c$b extends $gJ {
  static {
    this.ID = "testing.goToPreviousMessage";
  }
  constructor() {
    super({
      id: _$c$b.ID,
      f1: true,
      title: localize2(11208, "Go to Previous Test Failure"),
      metadata: {
        description: localize2(11209, "Shows the previous failure message in your file")
      },
      icon: $6l.arrowUp,
      category: $qn.Test,
      keybinding: {
        primary: 1024 | 512 | 66,
        weight: 100 + 1,
        when: navWhen
      },
      menu: [{
        id: $bJ.TestPeekTitle,
        group: "navigation",
        order: 1
      }, {
        id: $bJ.CommandPalette,
        when: navWhen
      }]
    });
  }
  run(accessor) {
    const editor = getPeekedEditorFromFocus(accessor.get($U5));
    if (editor) {
      $$0b.get(editor)?.previous();
    }
  }
};
var $d$b = class _$d$b extends $gJ {
  static {
    this.ID = "testing.collapsePeekStack";
  }
  constructor() {
    super({
      id: _$d$b.ID,
      title: localize2(11210, "Collapse Stack Frames"),
      icon: $6l.collapseAll,
      category: $qn.Test,
      menu: [{
        id: $bJ.TestPeekTitle,
        when: TestingContextKeys.peekHasStack,
        group: "navigation",
        order: 4
      }]
    });
  }
  run(accessor) {
    const editor = getPeekedEditorFromFocus(accessor.get($U5));
    if (editor) {
      $$0b.get(editor)?.collapseStack();
    }
  }
};
var $e$b = class _$e$b extends $gJ {
  static {
    this.ID = "testing.openMessageInEditor";
  }
  constructor() {
    super({
      id: _$e$b.ID,
      f1: false,
      title: localize2(11211, "Open in Editor"),
      icon: $6l.goToFile,
      category: $qn.Test,
      menu: [{ id: $bJ.TestPeekTitle }]
    });
  }
  run(accessor) {
    accessor.get($B0b).openCurrentInEditor();
  }
};
var $f$b = class _$f$b extends $gJ {
  static {
    this.ID = "testing.toggleTestingPeekHistory";
  }
  constructor() {
    super({
      id: _$f$b.ID,
      f1: true,
      title: localize2(11212, "Toggle Test History in Peek"),
      metadata: {
        description: localize2(11213, "Shows or hides the history of test runs in the peek view")
      },
      icon: $6l.history,
      category: $qn.Test,
      menu: [{
        id: $bJ.TestPeekTitle,
        group: "navigation",
        order: 3
      }],
      keybinding: {
        weight: 200,
        primary: 512 | 38,
        when: TestingContextKeys.isPeekVisible.isEqualTo(true)
      }
    });
  }
  run(accessor) {
    const opener = accessor.get($B0b);
    opener.historyVisible.value = !opener.historyVisible.value;
  }
};

// out-build/vs/workbench/contrib/testing/browser/testingDecorations.js
var $h$b_1;
var TestMessageDecoration_1;
var MAX_INLINE_MESSAGE_LENGTH = 128;
var MAX_TESTS_IN_SUBMENU = 30;
var GLYPH_MARGIN_LANE = GlyphMarginLane.Center;
function isOriginalInDiffEditor(codeEditorService, codeEditor) {
  const diffEditors = codeEditorService.listDiffEditors();
  for (const diffEditor of diffEditors) {
    if (diffEditor.getOriginalEditor() === codeEditor) {
      return true;
    }
  }
  return false;
}
var CachedDecorations = class {
  constructor() {
    this.g = /* @__PURE__ */ new Map();
  }
  get size() {
    return this.g.size;
  }
  /** Gets a test run decoration that contains exactly the given test IDs */
  getForExactTests(testIds) {
    const key2 = testIds.sort().join("\0\0");
    return this.g.get(key2);
  }
  /** Adds a new test run decroation */
  addTest(d) {
    const key2 = d.testIds.sort().join("\0\0");
    this.g.set(key2, d);
  }
  /** Finds an extension by VS Code event ID */
  getById(decorationId) {
    for (const d of this.g.values()) {
      if (d.id === decorationId) {
        return d;
      }
    }
    return void 0;
  }
  /** Iterate over all decorations */
  *[Symbol.iterator]() {
    for (const d of this.g.values()) {
      yield d;
    }
  }
};
var $g$b = class $g$b2 extends $3c {
  constructor(codeEditorService, u, w, y, z, C) {
    super();
    this.u = u;
    this.w = w;
    this.y = y;
    this.z = z;
    this.C = C;
    this.g = 0;
    this.j = new $ze();
    this.n = new $Ec();
    this.s = /* @__PURE__ */ new WeakSet();
    this.onDidChange = this.j.event;
    codeEditorService.registerDecorationType("test-message-decoration", TestMessageDecoration.decorationId, {}, void 0);
    this.B(C.onModelRemoved((e) => this.n.delete(e.uri)));
    const debounceInvalidate = this.B(new $8h(() => this.D(), 100));
    this.B(this.w.onWillProcessDiff((diff3) => {
      for (const entry of diff3) {
        if (entry.op !== 2) {
          continue;
        }
        const rec = this.n.get(entry.uri);
        if (rec) {
          rec.rangeUpdateVersionId = entry.docv;
        }
      }
      if (!debounceInvalidate.isScheduled()) {
        debounceInvalidate.schedule();
      }
    }));
    this.B(Event2.any(this.y.onResultsChanged, this.y.onTestChanged, this.w.excluded.onTestExclusionsChanged, Event2.filter(u.onDidChangeConfiguration, (e) => e.affectsConfiguration(
      "testing.gutterEnabled"
      /* TestingConfigKeys.GutterEnabled */
    )))(() => {
      if (!debounceInvalidate.isScheduled()) {
        debounceInvalidate.schedule();
      }
    }));
    this.B($I3b.registerGutterActionsGenerator((context, result) => {
      const model = context.editor.getModel();
      const testingDecorations = $h$b.get(context.editor);
      if (!model || !testingDecorations?.currentUri) {
        return;
      }
      const currentDecorations = this.syncDecorations(testingDecorations.currentUri);
      if (!currentDecorations.size) {
        return;
      }
      const modelDecorations = model.getLinesDecorations(context.lineNumber, context.lineNumber);
      for (const { id: id2 } of modelDecorations) {
        const decoration3 = currentDecorations.getById(id2);
        if (decoration3) {
          const { object: actions } = decoration3.getContextMenuActions();
          for (const action of actions) {
            result.push(action, "1_testing");
          }
        }
      }
    }));
  }
  /** @inheritdoc */
  invalidateResultMessage(message) {
    this.s.add(message);
    this.D();
  }
  /** @inheritdoc */
  syncDecorations(resource) {
    const model = this.C.getModel(resource);
    if (!model) {
      return new CachedDecorations();
    }
    const cached = this.n.get(resource);
    if (cached && cached.generation === this.g && (cached.rangeUpdateVersionId === void 0 || cached.rangeUpdateVersionId !== model.getVersionId())) {
      return cached.value;
    }
    return this.F(model);
  }
  /** @inheritdoc */
  getDecoratedTestPosition(resource, testId) {
    const model = this.C.getModel(resource);
    if (!model) {
      return void 0;
    }
    const decoration3 = Iterable.find(this.syncDecorations(resource), (v) => v instanceof RunTestDecoration && v.isForTest(testId));
    if (!decoration3) {
      return void 0;
    }
    return model.getDecorationRange(decoration3.id)?.getStartPosition();
  }
  D() {
    this.g++;
    this.j.fire();
  }
  /**
   * Sets whether alternate actions are shown for the model.
   */
  updateDecorationsAlternateAction(resource, isAlt) {
    const model = this.C.getModel(resource);
    const cached = this.n.get(resource);
    if (!model || !cached || cached.isAlt === isAlt) {
      return;
    }
    cached.isAlt = isAlt;
    model.changeDecorations((accessor) => {
      for (const decoration3 of cached.value) {
        if (decoration3 instanceof RunTestDecoration && decoration3.editorDecoration.alternate) {
          accessor.changeDecorationOptions(decoration3.id, isAlt ? decoration3.editorDecoration.alternate : decoration3.editorDecoration.options);
        }
      }
    });
  }
  /**
   * Applies the current set of test decorations to the given text model.
   */
  F(model) {
    const gutterEnabled = $w9b(
      this.u,
      "testing.gutterEnabled"
      /* TestingConfigKeys.GutterEnabled */
    );
    const cached = this.n.get(model.uri);
    const testRangesUpdated = cached?.rangeUpdateVersionId === model.getVersionId();
    const lastDecorations = cached?.value ?? new CachedDecorations();
    const newDecorations = model.changeDecorations((accessor) => {
      const newDecorations2 = new CachedDecorations();
      const runDecorations = new $z0b();
      for (const test of this.w.collection.getNodeByUrl(model.uri)) {
        if (!test.item.range) {
          continue;
        }
        const stateLookup = this.y.getStateById(test.item.extId);
        const line = test.item.range.startLineNumber;
        runDecorations.push({ line, id: "", test, resultItem: stateLookup?.[1] });
      }
      for (const [line, tests] of runDecorations.lines()) {
        const multi = tests.length > 1;
        let existing = lastDecorations.getForExactTests(tests.map((t) => t.test.item.extId));
        if (existing && testRangesUpdated && model.getDecorationRange(existing.id)?.startLineNumber !== line) {
          existing = void 0;
        }
        if (existing) {
          if (existing.replaceOptions(tests, gutterEnabled)) {
            accessor.changeDecorationOptions(existing.id, existing.editorDecoration.options);
          }
          newDecorations2.addTest(existing);
        } else {
          newDecorations2.addTest(multi ? this.z.createInstance(MultiRunTestDecoration, tests, gutterEnabled, model) : this.z.createInstance(RunSingleTestDecoration, tests[0].test, tests[0].resultItem, model, gutterEnabled));
        }
      }
      const saveFromRemoval = /* @__PURE__ */ new Set();
      for (const decoration3 of newDecorations2) {
        if (decoration3.id === "") {
          decoration3.id = accessor.addDecoration(decoration3.editorDecoration.range, decoration3.editorDecoration.options);
        } else {
          saveFromRemoval.add(decoration3.id);
        }
      }
      for (const decoration3 of lastDecorations) {
        if (!saveFromRemoval.has(decoration3.id)) {
          accessor.removeDecoration(decoration3.id);
        }
      }
      this.n.set(model.uri, {
        generation: this.g,
        rangeUpdateVersionId: cached?.rangeUpdateVersionId,
        value: newDecorations2
      });
      return newDecorations2;
    });
    return newDecorations || lastDecorations;
  }
};
$g$b = __decorate([
  __param(0, $U5),
  __param(1, $kl),
  __param(2, $nTb),
  __param(3, $FTb),
  __param(4, $Pk),
  __param(5, $sG)
], $g$b);
var $h$b = class $h$b2 extends $3c {
  static {
    $h$b_1 = this;
  }
  static {
    this.invalidatedTests = /* @__PURE__ */ new WeakSet();
  }
  /**
   * Gets the decorations associated with the given code editor.
   */
  static get(editor) {
    return editor.getContribution(
      "editor.contrib.testingDecorations"
      /* Testing.DecorationsContributionId */
    );
  }
  get currentUri() {
    return this.g;
  }
  constructor(w, y, z, C, D, F, G, H) {
    super();
    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.j = new $4c();
    this.n = new $4c();
    this.s = this.B(new $_c());
    this.u = /* @__PURE__ */ new Map();
    y.registerDecorationType("test-message-decoration", TestMessageDecoration.decorationId, {}, void 0, w);
    this.I(w.getModel()?.uri);
    this.B(C.onDidChange(() => {
      if (this.g) {
        C.syncDecorations(this.g);
      }
    }));
    this.B(Event2.any(this.F.onResultsChanged, w.onDidChangeModel, Event2.filter(
      this.F.onTestChanged,
      (c) => c.reason === 2
      /* TestResultItemChangeReason.NewMessage */
    ), this.z.showInlineOutput.onDidChange)(() => this.J()));
    const win = getWindow(w.getDomNode());
    this.B($_i(win, "keydown", (e) => {
      if (new $if(e).keyCode === 6 && this.g) {
        C.updateDecorationsAlternateAction(this.g, true);
      }
    }));
    this.B($_i(win, "keyup", (e) => {
      if (new $if(e).keyCode === 6 && this.g) {
        C.updateDecorationsAlternateAction(this.g, false);
      }
    }));
    this.B($_i(win, "blur", () => {
      if (this.g) {
        C.updateDecorationsAlternateAction(this.g, false);
      }
    }));
    this.B(this.w.onKeyUp((e) => {
      if (e.keyCode === 6 && this.g) {
        C.updateDecorationsAlternateAction(this.g, false);
      }
    }));
    this.B(this.w.onDidChangeModel((e) => this.I(e.newModelUrl || void 0)));
    this.B(this.w.onMouseDown((e) => {
      if (e.target.position && this.currentUri) {
        const modelDecorations = w.getModel()?.getLineDecorations(e.target.position.lineNumber) ?? [];
        if (!modelDecorations.length) {
          return;
        }
        const cache2 = C.syncDecorations(this.currentUri);
        for (const { id: id2 } of modelDecorations) {
          if (cache2.getById(id2)?.click(e)) {
            e.event.stopPropagation();
            return;
          }
        }
      }
    }));
    this.B(Event2.accumulate(this.w.onDidChangeModelContent, 0, this.q)((evts) => {
      const model = w.getModel();
      if (!this.g || !model) {
        return;
      }
      let changed = false;
      for (const [message, deco] of this.u) {
        const invalidate = evts.some((e) => e.changes.some((c) => c.range.startLineNumber <= deco.line && c.range.endLineNumber >= deco.line || deco.resultItem?.item.range && deco.resultItem.item.range.startLineNumber <= c.range.startLineNumber && deco.resultItem.item.range.endLineNumber >= c.range.endLineNumber));
        if (invalidate) {
          changed = true;
          $h$b_1.invalidatedTests.add(deco.resultItem || message);
        }
      }
      if (changed) {
        this.J();
      }
    }));
    const updateFontFamilyVar = () => {
      this.w.getContainerDomNode().style.setProperty("--testMessageDecorationFontFamily", w.getOption(
        51
        /* EditorOption.fontFamily */
      ));
      this.w.getContainerDomNode().style.setProperty("--testMessageDecorationFontSize", `${w.getOption(
        54
        /* EditorOption.fontSize */
      )}px`);
    };
    this.B(this.w.onDidChangeConfiguration((e) => {
      if (e.hasChanged(
        51
        /* EditorOption.fontFamily */
      )) {
        updateFontFamilyVar();
      }
    }));
    updateFontFamilyVar();
  }
  I(uri) {
    switch (uri && $D0b(uri)?.type) {
      case 4:
        this.j.value = new ExpectedLensContentWidget(this.w);
        this.n.clear();
        break;
      case 3:
        this.j.clear();
        this.n.value = new ActualLensContentWidget(this.w);
        break;
      default:
        this.j.clear();
        this.n.clear();
    }
    if (isOriginalInDiffEditor(this.y, this.w)) {
      uri = void 0;
    }
    this.g = uri;
    if (!uri) {
      return;
    }
    this.C.syncDecorations(uri);
    (async () => {
      for await (const _test of $rTb(this.z, this.D, uri, false)) {
        if (this.g !== uri) {
          break;
        }
      }
    })();
  }
  J() {
    const model = this.w.getModel();
    if (!model) {
      return this.L();
    }
    const uriStr = model.uri.toString();
    const seenLines = /* @__PURE__ */ new Set();
    this.N(uriStr, seenLines);
    this.P(uriStr, seenLines);
  }
  L() {
    this.s.clearAndDisposeAll();
  }
  M(message) {
    return $h$b_1.invalidatedTests.has(message);
  }
  N(uriStr, seenLines) {
    const seen = /* @__PURE__ */ new Set();
    if ($w9b(
      this.G,
      "testing.showAllMessages"
      /* TestingConfigKeys.ShowAllMessages */
    )) {
      this.F.results.forEach((lastResult) => this.O(lastResult, uriStr, seen, seenLines));
    } else if (this.F.results.length) {
      this.O(this.F.results[0], uriStr, seen, seenLines);
    }
    for (const message of this.s.keys()) {
      if (!seen.has(message)) {
        this.s.deleteAndDispose(message);
      }
    }
  }
  O(lastResult, uriStr, seen, seenLines) {
    for (const test of lastResult.tests) {
      if ($h$b_1.invalidatedTests.has(test)) {
        continue;
      }
      for (let taskId = 0; taskId < test.tasks.length; taskId++) {
        const state = test.tasks[taskId];
        for (let i2 = 0; i2 < state.messages.length; i2++) {
          const m = state.messages[i2];
          if (m.type !== 0 || this.M(m)) {
            continue;
          }
          const line = m.location?.uri.toString() === uriStr ? m.location.range.startLineNumber : m.stackTrace && $ab(m.stackTrace, (f) => f.position && f.uri?.toString() === uriStr ? f.position.lineNumber : void 0);
          if (line === void 0 || seenLines.has(line)) {
            continue;
          }
          seenLines.add(line);
          let deco = this.s.get(m);
          if (!deco) {
            const lineLength = this.w.getModel()?.getLineLength(line) ?? 100;
            deco = this.H.createInstance(TestErrorContentWidget, this.w, new $8C(line, lineLength + 1), m, test, $E0b({
              type: 3,
              messageIndex: i2,
              taskIndex: taskId,
              resultId: lastResult.id,
              testExtId: test.item.extId
            }));
            this.s.set(m, deco);
          }
          seen.add(m);
        }
      }
    }
  }
  P(uriStr, messageLines) {
    this.w.changeDecorations((accessor) => {
      const seen = /* @__PURE__ */ new Set();
      if ($w9b(
        this.G,
        "testing.showAllMessages"
        /* TestingConfigKeys.ShowAllMessages */
      )) {
        this.F.results.forEach((r2) => this.Q(r2, uriStr, seen, messageLines, accessor));
      } else if (this.F.results.length) {
        this.Q(this.F.results[0], uriStr, seen, messageLines, accessor);
      }
      for (const [message, { id: id2 }] of this.u) {
        if (!seen.has(message)) {
          accessor.removeDecoration(id2);
        }
      }
    });
  }
  Q(lastResult, uriStr, seen, messageLines, accessor) {
    if (!this.z.showInlineOutput.value || !(lastResult instanceof $RQ)) {
      return;
    }
    const tryAdd = (resultItem, m, uri) => {
      if (this.M(m) || m.location?.uri.toString() !== uriStr) {
        return;
      }
      seen.add(m);
      const line = m.location.range.startLineNumber;
      if (messageLines.has(line) || this.u.has(m)) {
        return;
      }
      const deco = this.H.createInstance(TestMessageDecoration, m, uri, this.w.getModel());
      messageLines.add(line);
      const id2 = accessor.addDecoration(deco.editorDecoration.range, deco.editorDecoration.options);
      this.u.set(m, { id: id2, line, resultItem });
    };
    for (const test of lastResult.tests) {
      if ($h$b_1.invalidatedTests.has(test)) {
        continue;
      }
      for (let taskId = 0; taskId < test.tasks.length; taskId++) {
        const state = test.tasks[taskId];
        for (let i2 = state.messages.length - 1; i2 >= 0; i2--) {
          const m = state.messages[i2];
          if (m.type === 1) {
            tryAdd(test, m, $E0b({
              type: 3,
              messageIndex: i2,
              taskIndex: taskId,
              resultId: lastResult.id,
              testExtId: test.item.extId
            }));
          }
        }
      }
    }
    for (const task of lastResult.tasks) {
      for (const m of task.otherMessages) {
        tryAdd(void 0, m);
      }
    }
  }
};
$h$b = $h$b_1 = __decorate([
  __param(1, $U5),
  __param(2, $nTb),
  __param(3, $A0b),
  __param(4, $vl),
  __param(5, $FTb),
  __param(6, $kl),
  __param(7, $Pk)
], $h$b);
var collapseRange = (originalRange) => ({
  startLineNumber: originalRange.startLineNumber,
  endLineNumber: originalRange.startLineNumber,
  startColumn: originalRange.startColumn,
  endColumn: originalRange.startColumn
});
var createRunTestDecoration = (tests, states, visible, defaultGutterAction) => {
  const range = tests[0]?.item.range;
  if (!range) {
    throw new Error("Test decorations can only be created for tests with a range");
  }
  if (!visible) {
    return {
      range: collapseRange(range),
      options: { isWholeLine: true, description: "run-test-decoration" }
    };
  }
  let computedState = 0;
  const hoverMessageParts = [];
  let testIdWithMessages;
  let retired = false;
  for (let i2 = 0; i2 < tests.length; i2++) {
    const test = tests[i2];
    const resultItem = states[i2];
    const state = resultItem?.computedState ?? 0;
    if (hoverMessageParts.length < 10) {
      hoverMessageParts.push($uTb(test.item.label, state));
    }
    computedState = $CQ(computedState, state);
    retired = retired || !!resultItem?.retired;
    if (!testIdWithMessages && resultItem?.tasks.some((t) => t.messages.length)) {
      testIdWithMessages = test.item.extId;
    }
  }
  const hasMultipleTests = tests.length > 1 || tests[0].children.size > 0;
  const primaryIcon = computedState === 0 ? hasMultipleTests ? $b0b : $_9b : $u0b.get(computedState);
  const alternateIcon = defaultGutterAction === "debug" ? hasMultipleTests ? $b0b : $_9b : hasMultipleTests ? $c0b : $d0b;
  let hoverMessage;
  let glyphMarginClassName = "testing-run-glyph";
  if (retired) {
    glyphMarginClassName += " retired";
  }
  const defaultOptions4 = {
    description: "run-test-decoration",
    showIfCollapsed: true,
    get hoverMessage() {
      if (!hoverMessage) {
        const building = hoverMessage = new $bm("", true).appendText(hoverMessageParts.join(", ") + ".");
        if (testIdWithMessages) {
          const args2 = encodeURIComponent(JSON.stringify([testIdWithMessages]));
          building.appendMarkdown(` [${localize(11160, null)}](command:vscode.peekTestError?${args2})`);
        }
      }
      return hoverMessage;
    },
    glyphMargin: { position: GLYPH_MARGIN_LANE },
    glyphMarginClassName: `${ThemeIcon.asClassName(primaryIcon)} ${glyphMarginClassName}`,
    stickiness: 1,
    zIndex: 1e4
  };
  const alternateOptions = {
    ...defaultOptions4,
    glyphMarginClassName: `${ThemeIcon.asClassName(alternateIcon)} ${glyphMarginClassName}`
  };
  return {
    range: collapseRange(range),
    options: defaultOptions4,
    alternate: alternateOptions
  };
};
var LensContentWidgetVars;
(function(LensContentWidgetVars2) {
  LensContentWidgetVars2["FontFamily"] = "testingDiffLensFontFamily";
  LensContentWidgetVars2["FontFeatures"] = "testingDiffLensFontFeatures";
})(LensContentWidgetVars || (LensContentWidgetVars = {}));
var TitleLensContentWidget = class {
  constructor(k) {
    this.k = k;
    this.allowEditorOverflow = false;
    this.suppressMouseDown = true;
    this.g = $("span");
    queueMicrotask(() => {
      this.l();
      this.k.addContentWidget(this);
    });
  }
  l() {
    let fontSize = this.k.getOption(
      19
      /* EditorOption.codeLensFontSize */
    );
    let height;
    if (!fontSize || fontSize < 5) {
      fontSize = this.k.getOption(
        54
        /* EditorOption.fontSize */
      ) * 0.9 | 0;
      height = this.k.getOption(
        68
        /* EditorOption.lineHeight */
      );
    } else {
      height = fontSize * Math.max(1.3, this.k.getOption(
        68
        /* EditorOption.lineHeight */
      ) / this.k.getOption(
        54
        /* EditorOption.fontSize */
      )) | 0;
    }
    const editorFontInfo = this.k.getOption(
      52
      /* EditorOption.fontInfo */
    );
    const node = this.g;
    node.classList.add("testing-diff-lens-widget");
    node.textContent = this.n();
    node.style.lineHeight = `${height}px`;
    node.style.fontSize = `${fontSize}px`;
    node.style.fontFamily = `var(--${"testingDiffLensFontFamily"})`;
    node.style.fontFeatureSettings = `var(--${"testingDiffLensFontFeatures"})`;
    const containerStyle = this.k.getContainerDomNode().style;
    containerStyle.setProperty("testingDiffLensFontFamily", this.k.getOption(
      18
      /* EditorOption.codeLensFontFamily */
    ) ?? "inherit");
    containerStyle.setProperty("testingDiffLensFontFeatures", editorFontInfo.fontFeatureSettings);
    this.k.changeViewZones((accessor) => {
      if (this.j) {
        accessor.removeZone(this.j);
      }
      this.j = accessor.addZone({
        afterLineNumber: 0,
        afterColumn: 1073741824,
        domNode: document.createElement("div"),
        heightInPx: 20
      });
    });
  }
  /** @inheritdoc */
  getDomNode() {
    return this.g;
  }
  /** @inheritdoc */
  dispose() {
    this.k.changeViewZones((accessor) => {
      if (this.j) {
        accessor.removeZone(this.j);
      }
    });
    this.k.removeContentWidget(this);
  }
  /** @inheritdoc */
  getPosition() {
    return {
      position: { column: 0, lineNumber: 0 },
      preference: [
        1
        /* ContentWidgetPositionPreference.ABOVE */
      ]
    };
  }
};
var ExpectedLensContentWidget = class extends TitleLensContentWidget {
  getId() {
    return "expectedTestingLens";
  }
  n() {
    return localize(11161, null);
  }
};
var ActualLensContentWidget = class extends TitleLensContentWidget {
  getId() {
    return "actualTestingLens";
  }
  n() {
    return localize(11162, null);
  }
};
var RunTestDecoration = class RunTestDecoration2 {
  get line() {
    return this.editorDecoration.range.startLineNumber;
  }
  get testIds() {
    return this.g.map((t) => t.test.item.extId);
  }
  constructor(g, j, k, l, n, o, p, q, s, u, w) {
    this.g = g;
    this.j = j;
    this.k = k;
    this.l = l;
    this.n = n;
    this.o = o;
    this.p = p;
    this.q = q;
    this.s = s;
    this.u = u;
    this.w = w;
    this.id = "";
    this.displayedStates = g.map((t) => t.resultItem?.computedState);
    this.editorDecoration = createRunTestDecoration(g.map((t) => t.test), g.map((t) => t.resultItem), j, $w9b(
      this.q,
      "testing.defaultGutterClickAction"
      /* TestingConfigKeys.DefaultGutterClickAction */
    ));
    this.editorDecoration.options.glyphMarginHoverMessage = new $bm().appendText(this.z());
  }
  /** @inheritdoc */
  click(e) {
    if (e.target.type !== 2 || e.target.detail.glyphMarginLane !== GLYPH_MARGIN_LANE || e.event.rightButton || $m && e.event.leftButton && e.event.ctrlKey) {
      return false;
    }
    const alternateAction = e.event.altKey;
    switch ($w9b(
      this.q,
      "testing.defaultGutterClickAction"
      /* TestingConfigKeys.DefaultGutterClickAction */
    )) {
      case "contextMenu":
        this.y(e);
        break;
      case "debug":
        this.x(
          alternateAction ? 2 : 4
          /* TestRunProfileBitset.Debug */
        );
        break;
      case "runWithCoverage":
        this.x(
          alternateAction ? 4 : 8
          /* TestRunProfileBitset.Coverage */
        );
        break;
      case "run":
      default:
        this.x(
          alternateAction ? 4 : 2
          /* TestRunProfileBitset.Run */
        );
        break;
    }
    return true;
  }
  /**
   * Updates the decoration to match the new set of tests.
   * @returns true if options were changed, false otherwise
   */
  replaceOptions(newTests, visible) {
    const displayedStates = newTests.map((t) => t.resultItem?.computedState);
    if (visible === this.j && $zb(this.displayedStates, displayedStates)) {
      return false;
    }
    this.g = newTests;
    this.displayedStates = displayedStates;
    this.j = visible;
    const { options: options3, alternate } = createRunTestDecoration(newTests.map((t) => t.test), newTests.map((t) => t.resultItem), visible, $w9b(
      this.q,
      "testing.defaultGutterClickAction"
      /* TestingConfigKeys.DefaultGutterClickAction */
    ));
    this.editorDecoration.options = options3;
    this.editorDecoration.alternate = alternate;
    this.editorDecoration.options.glyphMarginHoverMessage = new $bm().appendText(this.z());
    return true;
  }
  /**
   * Gets whether this decoration serves as the run button for the given test ID.
   */
  isForTest(testId) {
    return this.g.some((t) => t.test.item.extId === testId);
  }
  x(profile) {
    return this.n.runTests({
      tests: $tTb(this.n.collection, this.g.map(({ test }) => test)),
      group: profile
    });
  }
  y(e) {
    const editor = this.l.listCodeEditors().find((e2) => e2.getModel() === this.k);
    editor?.getContribution($J3b.ID)?.show(e);
  }
  z() {
    switch ($w9b(
      this.q,
      "testing.defaultGutterClickAction"
      /* TestingConfigKeys.DefaultGutterClickAction */
    )) {
      case "contextMenu":
        return localize(11163, null);
      case "debug":
        return localize(11164, null);
      case "runWithCoverage":
        return localize(11165, null);
      case "run":
      default:
        return localize(11166, null);
    }
  }
  /**
   * Gets context menu actions relevant for a singel test.
   */
  A(test, resultItem) {
    const testActions = [];
    const capabilities = this.s.capabilitiesForTest(test.item);
    [
      { bitset: 2, label: localize(11167, null) },
      { bitset: 4, label: localize(11168, null) },
      { bitset: 8, label: localize(11169, null) }
    ].forEach(({ bitset, label: label3 }) => {
      if (capabilities & bitset) {
        testActions.push(new $Um(`testing.gutter.${bitset}`, label3, void 0, void 0, () => this.n.runTests({ group: bitset, tests: [test] })));
      }
    });
    if (capabilities & 16) {
      testActions.push(new $Um("testing.runUsing", localize(11170, null), void 0, void 0, async () => {
        const profile = await this.p.executeCommand("vscode.pickTestProfile", { onlyForTest: test });
        if (!profile) {
          return;
        }
        this.n.runResolvedTests({
          group: profile.group,
          targets: [{
            profileId: profile.profileId,
            controllerId: profile.controllerId,
            testIds: [test.item.extId]
          }]
        });
      }));
    }
    if (resultItem && $yQ(resultItem.computedState)) {
      testActions.push(new $Um("testing.gutter.peekFailure", localize(11171, null), void 0, void 0, () => this.p.executeCommand("vscode.peekTestError", test.item.extId)));
    }
    testActions.push(new $Um("testing.gutter.reveal", localize(11172, null), void 0, void 0, () => this.p.executeCommand("_revealTestInExplorer", test.item.extId)));
    const contributed = this.B(test, capabilities);
    return { object: $Wm.join(testActions, contributed), dispose() {
    } };
  }
  B(test, capabilities) {
    const contextOverlay = this.u.createOverlay($F0b(test, capabilities));
    const arg = $pTb(this.n.collection, test.item.extId);
    const menu = this.w.getMenuActions($bJ.TestItemGutter, contextOverlay, { shouldForwardArgs: true, arg });
    return $P$(menu);
  }
};
RunTestDecoration = __decorate([
  __param(3, $U5),
  __param(4, $nTb),
  __param(5, $50),
  __param(6, $sn),
  __param(7, $kl),
  __param(8, $wTb),
  __param(9, $on),
  __param(10, $cJ)
], RunTestDecoration);
var MultiRunTestDecoration = class MultiRunTestDecoration2 extends RunTestDecoration {
  constructor(tests, visible, model, codeEditorService, testService, contextMenuService, commandService, configurationService, testProfileService, contextKeyService, menuService, C) {
    super(tests, visible, model, codeEditorService, testService, contextMenuService, commandService, configurationService, testProfileService, contextKeyService, menuService);
    this.C = C;
  }
  getContextMenuActions() {
    const allActions = [];
    [
      { bitset: 2, label: localize(11173, null) },
      { bitset: 8, label: localize(11174, null) },
      { bitset: 4, label: localize(11175, null) }
    ].forEach(({ bitset, label: label3 }, i2) => {
      const canRun = this.g.some(({ test }) => this.s.capabilitiesForTest(test.item) & bitset);
      if (canRun) {
        allActions.push(new $Um(`testing.gutter.run${i2}`, label3, void 0, void 0, () => this.x(bitset)));
      }
    });
    const testItems = this.g.map((testItem) => ({
      currentLabel: testItem.test.item.label,
      testItem,
      parent: $mQ.fromString(testItem.test.item.extId).parentId
    }));
    const getLabelConflicts = (tests) => {
      const labelCount = /* @__PURE__ */ new Map();
      for (const test of tests) {
        labelCount.set(test.currentLabel, (labelCount.get(test.currentLabel) || 0) + 1);
      }
      return tests.filter((e) => labelCount.get(e.currentLabel) > 1);
    };
    let conflicts, hasParent = true;
    while ((conflicts = getLabelConflicts(testItems)).length && hasParent) {
      for (const conflict of conflicts) {
        if (conflict.parent) {
          const parent = this.n.collection.getNodeById(conflict.parent.toString());
          conflict.currentLabel = parent?.item.label + " > " + conflict.currentLabel;
          conflict.parent = conflict.parent.parentId;
        } else {
          hasParent = false;
        }
      }
    }
    testItems.sort((a, b) => {
      const ai = a.testItem.test.item;
      const bi = b.testItem.test.item;
      return (ai.sortText || ai.label).localeCompare(bi.sortText || bi.label);
    });
    const disposable = new $2c();
    let testSubmenus = testItems.map(({ currentLabel, testItem }) => {
      const actions = this.A(testItem.test, testItem.resultItem);
      disposable.add(actions);
      let label3 = $0l(currentLabel);
      const lf = label3.indexOf("\n");
      if (lf !== -1) {
        label3 = label3.slice(0, lf);
      }
      return new $Xm(testItem.test.item.extId, label3, actions.object);
    });
    const overflow = testSubmenus.length - MAX_TESTS_IN_SUBMENU;
    if (overflow > 0) {
      testSubmenus = testSubmenus.slice(0, MAX_TESTS_IN_SUBMENU);
      testSubmenus.push(new $Um("testing.gutter.overflow", localize(11176, null, overflow), void 0, void 0, () => this.D(testItems)));
    }
    return { object: $Wm.join(allActions, testSubmenus), dispose: () => disposable.dispose() };
  }
  async D(testItems) {
    const doPick = (items, title) => new Promise((resolve) => {
      const disposables = new $2c();
      const pick = disposables.add(this.C.createQuickPick());
      pick.placeholder = title;
      pick.items = items;
      disposables.add(pick.onDidHide(() => {
        resolve(void 0);
        disposables.dispose();
      }));
      disposables.add(pick.onDidAccept(() => {
        resolve(pick.selectedItems[0]);
        disposables.dispose();
      }));
      pick.show();
    });
    const item = await doPick(testItems.map(({ currentLabel, testItem }) => ({ label: currentLabel, test: testItem.test, result: testItem.resultItem })), localize(11177, null));
    if (!item) {
      return;
    }
    const actions = this.A(item.test, item.result);
    try {
      (await doPick(actions.object, item.label))?.run();
    } finally {
      actions.dispose();
    }
  }
};
MultiRunTestDecoration = __decorate([
  __param(3, $U5),
  __param(4, $nTb),
  __param(5, $50),
  __param(6, $sn),
  __param(7, $kl),
  __param(8, $wTb),
  __param(9, $on),
  __param(10, $cJ),
  __param(11, $1M)
], MultiRunTestDecoration);
var RunSingleTestDecoration = class RunSingleTestDecoration2 extends RunTestDecoration {
  constructor(test, resultItem, model, visible, codeEditorService, testService, commandService, contextMenuService, configurationService, testProfiles, contextKeyService, menuService) {
    super([{ test, resultItem }], visible, model, codeEditorService, testService, contextMenuService, commandService, configurationService, testProfiles, contextKeyService, menuService);
  }
  getContextMenuActions() {
    return this.A(this.g[0].test, this.g[0].resultItem);
  }
};
RunSingleTestDecoration = __decorate([
  __param(4, $U5),
  __param(5, $nTb),
  __param(6, $sn),
  __param(7, $50),
  __param(8, $kl),
  __param(9, $wTb),
  __param(10, $on),
  __param(11, $cJ)
], RunSingleTestDecoration);
var lineBreakRe = /\r?\n\s*/g;
var TestMessageDecoration = class TestMessageDecoration2 {
  static {
    TestMessageDecoration_1 = this;
  }
  static {
    this.inlineClassName = "test-message-inline-content";
  }
  static {
    this.decorationId = `testmessage-${$ps()}`;
  }
  constructor(testMessage, j, textModel, k, editorService) {
    this.testMessage = testMessage;
    this.j = j;
    this.k = k;
    this.id = "";
    this.g = `test-message-inline-content-id${$ps()}`;
    const location3 = testMessage.location;
    this.line = $4i(location3.range.startLineNumber, 0, textModel.getLineCount());
    const severity = testMessage.type;
    const message = testMessage.message;
    const options3 = editorService.resolveDecorationOptions(TestMessageDecoration_1.decorationId, true);
    options3.hoverMessage = typeof message === "string" ? new $bm().appendText(message) : message;
    options3.zIndex = 10;
    options3.className = `testing-inline-message-severity-${severity}`;
    options3.isWholeLine = true;
    options3.stickiness = 1;
    options3.collapseOnReplaceEdit = true;
    let inlineText2 = $G0b(message).replace(lineBreakRe, " ");
    if (inlineText2.length > MAX_INLINE_MESSAGE_LENGTH) {
      inlineText2 = inlineText2.slice(0, MAX_INLINE_MESSAGE_LENGTH - 1) + "\u2026";
    }
    options3.after = {
      content: inlineText2,
      inlineClassName: `test-message-inline-content test-message-inline-content-s${severity} ${this.g} ${j ? "test-message-inline-content-clickable" : ""}`
    };
    options3.showIfCollapsed = true;
    const rulerColor = severity === 0 ? $qH : $sH;
    if (rulerColor) {
      options3.overviewRuler = { color: $hs(rulerColor), position: OverviewRulerLane.Right };
    }
    const lineLength = textModel.getLineLength(this.line);
    const column = lineLength ? lineLength + 1 : location3.range.endColumn;
    this.editorDecoration = {
      options: options3,
      range: {
        startLineNumber: this.line,
        startColumn: column,
        endColumn: column,
        endLineNumber: this.line
      }
    };
  }
  click(e) {
    if (e.event.rightButton) {
      return false;
    }
    if (!this.j) {
      return false;
    }
    if (e.target.element?.className.includes(this.g)) {
      this.k.peekUri(this.j);
    }
    return false;
  }
  getContextMenuActions() {
    return { object: [], dispose: () => {
    } };
  }
};
TestMessageDecoration = TestMessageDecoration_1 = __decorate([
  __param(3, $B0b),
  __param(4, $U5)
], TestMessageDecoration);
var ERROR_CONTENT_WIDGET_HEIGHT = 20;
var TestErrorContentWidget = class TestErrorContentWidget2 extends $3c {
  get line() {
    return this.s.lineNumber;
  }
  constructor(n, s, message, resultItem, uri, peekOpener) {
    super();
    this.n = n;
    this.s = s;
    this.message = message;
    this.resultItem = resultItem;
    this.peekOpener = peekOpener;
    this.g = $ps();
    this.allowEditorOverflow = false;
    this.j = h("div.test-error-content-widget", [
      h("div.inner@inner", [
        h("div.arrow@arrow"),
        h(`span${ThemeIcon.asCSSSelector($u0b.get(
          4
          /* TestResultState.Failed */
        ))}`),
        h("span.content@name")
      ])
    ]);
    const setMarginTop = () => {
      const lineHeight = n.getOption(
        68
        /* EditorOption.lineHeight */
      );
      this.j.root.style.marginTop = (lineHeight - ERROR_CONTENT_WIDGET_HEIGHT) / 2 + "px";
    };
    setMarginTop();
    this.B(n.onDidChangeConfiguration((e) => {
      if (e.hasChanged(
        68
        /* EditorOption.lineHeight */
      )) {
        setMarginTop();
      }
    }));
    let text2;
    if (message.expected !== void 0 && message.actual !== void 0) {
      text2 = `${$Df(message.actual.replace(/\s+/g, " "), 30)} != ${$Df(message.expected.replace(/\s+/g, " "), 30)}`;
    } else {
      const msg = $F1(message.message);
      const lf = msg.indexOf("\n");
      text2 = lf === -1 ? msg : msg.slice(0, lf);
    }
    this.j.root.addEventListener("click", (e) => {
      this.peekOpener.peekUri(uri);
      e.preventDefault();
    });
    const ctrl = $$0b.get(n);
    if (ctrl) {
      this.B($td((reader) => {
        const subject = ctrl.subject.read(reader);
        const isCurrent = subject instanceof $K0b && subject.message === message;
        this.j.root.classList.toggle("is-current", isCurrent);
      }));
    }
    this.j.name.innerText = text2 || "Test Failed";
    const svg2 = document.createElementNS("http://www.w3.org/2000/svg", "svg");
    svg2.setAttribute("width", "15");
    svg2.setAttribute("height", "10");
    svg2.setAttribute("preserveAspectRatio", "none");
    svg2.setAttribute("viewBox", "0 0 15 10");
    const leftArrow = document.createElementNS("http://www.w3.org/2000/svg", "path");
    leftArrow.setAttribute("d", "M15 0 L10 0 L0 5 L10 10 L15 10 Z");
    svg2.append(leftArrow);
    this.j.arrow.appendChild(svg2);
    this.B(n.onDidChangeModelContent((e) => {
      for (const c of e.changes) {
        if (c.range.startLineNumber > this.line) {
          continue;
        }
        if (c.range.startLineNumber <= this.line && c.range.endLineNumber >= this.line || resultItem.item.range && resultItem.item.range.startLineNumber <= c.range.startLineNumber && resultItem.item.range.endLineNumber >= c.range.endLineNumber) {
          $h$b.invalidatedTests.add(this.resultItem);
          this.dispose();
        }
        const adjust = $Bf(c.text, "\n") - (c.range.endLineNumber - c.range.startLineNumber);
        if (adjust !== 0) {
          this.s = this.s.delta(adjust);
          this.n.layoutContentWidget(this);
        }
      }
    }));
    n.addContentWidget(this);
    this.B($1c(() => n.removeContentWidget(this)));
  }
  getId() {
    return this.g;
  }
  getDomNode() {
    return this.j.root;
  }
  getPosition() {
    return {
      position: this.s,
      preference: [
        0
        /* ContentWidgetPositionPreference.EXACT */
      ]
    };
  }
  afterRender(_position, coordinate) {
    if (coordinate) {
      const { verticalScrollbarWidth } = this.n.getLayoutInfo();
      const scrollWidth = this.n.getScrollWidth();
      this.j.inner.style.maxWidth = `${scrollWidth - verticalScrollbarWidth - coordinate.left - 20}px`;
    }
  }
};
TestErrorContentWidget = __decorate([
  __param(5, $B0b)
], TestErrorContentWidget);

// out-build/vs/workbench/contrib/testing/common/testingContinuousRunService.js
var $i$b = $Qk("testingContinuousRunService");
var $j$b = class $j$b2 extends $3c {
  get lastRunProfileIds() {
    return this.c.get(/* @__PURE__ */ new Set());
  }
  constructor(f, storageService, contextKeyService, g) {
    super();
    this.f = f;
    this.g = g;
    this.a = new $ze();
    this.b = new $lQ();
    this.onDidChange = this.a.event;
    const isGloballyOn = TestingContextKeys.isContinuousModeOn.bindTo(contextKeyService);
    this.B(this.onDidChange(() => {
      isGloballyOn.set(!!this.b.root.value);
    }));
    this.c = this.B(new $jTb({
      key: "lastContinuousRunProfileIds",
      scope: 1,
      target: 1,
      serialization: {
        deserialize: (v) => new Set(JSON.parse(v)),
        serialize: (v) => JSON.stringify([...v])
      }
    }, storageService));
    this.B($1c(() => {
      for (const cts of this.b.values()) {
        cts.handle.dispose();
      }
    }));
  }
  /** @inheritdoc */
  isSpecificallyEnabledFor(testId) {
    return this.b.size > 0 && this.b.hasKey($mQ.fromString(testId).path);
  }
  /** @inheritdoc */
  isEnabledForAParentOf(testId) {
    return !!this.b.root.value || this.b.size > 0 && this.b.hasKeyOrParent($mQ.fromString(testId).path);
  }
  /** @inheritdoc */
  isEnabledForProfile({ profileId, controllerId }) {
    for (const node of this.b.values()) {
      if (node.profiles.get().some((p) => p.profileId === profileId && p.controllerId === controllerId)) {
        return true;
      }
    }
    return false;
  }
  /** @inheritdoc */
  isEnabledForAChildOf(testId) {
    return !!this.b.root.value || this.b.size > 0 && this.b.hasKeyOrChildren($mQ.fromString(testId).path);
  }
  /** @inheritdoc */
  isEnabled() {
    return !!this.b.root.value || this.b.size > 0;
  }
  /** @inheritdoc */
  start(profiles2, testId) {
    const store = new $2c();
    let actualProfiles;
    if (profiles2 instanceof Array) {
      actualProfiles = $he("crProfiles", profiles2);
    } else {
      const getRelevant = () => this.g.getGroupDefaultProfiles(profiles2).filter((p) => p.supportsContinuousRun && (!testId || $mQ.root(testId) === p.controllerId));
      actualProfiles = $he("crProfiles", getRelevant());
      store.add(this.g.onDidChange(() => {
        if (ref.autoSetDefault) {
          const newRelevant = getRelevant();
          if (!$zb(newRelevant, actualProfiles.get())) {
            actualProfiles.set(getRelevant(), void 0);
          }
        }
      }));
    }
    const path = testId ? $mQ.fromString(testId).path : [];
    const ref = { profiles: actualProfiles, handle: store, path, autoSetDefault: typeof profiles2 === "number" };
    const existing = this.b.find(path);
    if (existing) {
      store.dispose();
      ref.autoSetDefault = existing.autoSetDefault = false;
      existing.profiles.set([.../* @__PURE__ */ new Set([...actualProfiles.get(), ...existing.profiles.get()])], void 0);
      this.a.fire(testId);
      return;
    }
    this.b.insert(path, ref);
    const cancellationStores = new $_c();
    store.add($1c(() => {
      for (const cts of cancellationStores.values()) {
        cts.cancel();
      }
      cancellationStores.dispose();
    }));
    store.add($zd((reader) => actualProfiles.read(reader), ({ addedValues, removedValues }) => {
      for (const profile of addedValues) {
        const cts = new $ad();
        this.f.startContinuousRun({
          continuous: true,
          group: profile.group,
          targets: [{
            testIds: [testId ?? profile.controllerId],
            controllerId: profile.controllerId,
            profileId: profile.profileId
          }]
        }, cts.token);
        cancellationStores.set(profile, cts);
      }
      for (const profile of removedValues) {
        cancellationStores.get(profile)?.cancel();
        cancellationStores.deleteAndDispose(profile);
      }
      this.c.store(new Set([...cancellationStores.keys()].map((p) => p.profileId)));
    }));
    this.a.fire(testId);
  }
  /** Stops a continuous run for the profile across all test items that are running it. */
  stopProfile({ profileId, controllerId }) {
    const toDelete = [];
    for (const node of this.b.values()) {
      const profs = node.profiles.get();
      const filtered = profs.filter((p) => p.profileId !== profileId || p.controllerId !== controllerId);
      if (filtered.length === profs.length) {
        continue;
      } else if (filtered.length === 0) {
        toDelete.push(node);
      } else {
        node.profiles.set(filtered, void 0);
      }
    }
    for (let i2 = toDelete.length - 1; i2 >= 0; i2--) {
      toDelete[i2].handle.dispose();
      this.b.delete(toDelete[i2].path);
    }
    this.a.fire(void 0);
  }
  /** @inheritdoc */
  stop(testId) {
    const cancellations = [...this.b.deleteRecursive(testId ? $mQ.fromString(testId).path : [])];
    for (let i2 = cancellations.length - 1; i2 >= 0; i2--) {
      cancellations[i2].handle.dispose();
    }
    this.a.fire(testId);
  }
};
$j$b = __decorate([
  __param(0, $nTb),
  __param(1, $jv),
  __param(2, $on),
  __param(3, $wTb)
], $j$b);

// out-build/vs/workbench/contrib/testing/browser/explorerProjections/testingViewState.js
function $k$b(serialized, id2) {
  if (!(id2 instanceof $mQ)) {
    id2 = $mQ.fromString(id2);
  }
  let node = serialized;
  for (const part of id2.path) {
    if (!node.children?.hasOwnProperty(part)) {
      return void 0;
    }
    node = node.children[part];
  }
  return node.collapsed;
}

// out-build/vs/workbench/contrib/testing/browser/explorerProjections/index.js
var idCounter = 0;
var getId = () => String(idCounter++);
var $l$b = class {
  constructor(test, parent = null) {
    this.test = test;
    this.parent = parent;
    this.e = new $ze();
    this.onChange = this.e.event;
    this.children = /* @__PURE__ */ new Set();
    this.treeId = getId();
    this.depth = this.parent ? this.parent.depth + 1 : 0;
    this.retired = false;
    this.state = 0;
  }
  toJSON() {
    if (this.depth === 0) {
      return { controllerId: this.test.controllerId };
    }
    const context = {
      $mid: 16,
      tests: [InternalTestItem.serialize(this.test)]
    };
    for (let p = this.parent; p && p.depth > 0; p = p.parent) {
      context.tests.unshift(InternalTestItem.serialize(p.test));
    }
    return context;
  }
};
var $m$b = class {
  get description() {
    return typeof this.message === "string" ? this.message : this.message.value;
  }
  constructor(message, parent) {
    this.message = message;
    this.parent = parent;
    this.treeId = getId();
    this.children = /* @__PURE__ */ new Set();
  }
};
var $n$b = {
  getId(element) {
    const expandComponent = element instanceof $m$b ? "error" : element.test.expand === 0 ? !!element.children.size : element.test.expand;
    return element.treeId + "\0" + expandComponent;
  }
};
var $o$b = (serialized, rootsWithChildren, node) => {
  let it;
  if (node === null) {
    const rootsWithChildrenArr = [...rootsWithChildren];
    if (rootsWithChildrenArr.length === 1) {
      return $o$b(serialized, rootsWithChildrenArr, rootsWithChildrenArr[0]);
    }
    it = rootsWithChildrenArr;
  } else {
    it = node.children;
  }
  return Iterable.map(it, (element) => element instanceof $m$b ? { element } : {
    element,
    collapsible: element.test.expand !== 0,
    collapsed: element.test.item.error ? ObjectTreeElementCollapseState.PreserveOrExpanded : $k$b(serialized, element.test.item.extId) ?? element.depth > 0 ? ObjectTreeElementCollapseState.PreserveOrCollapsed : ObjectTreeElementCollapseState.PreserveOrExpanded,
    children: $o$b(serialized, rootsWithChildren, element)
  });
};

// out-build/vs/workbench/contrib/testing/browser/explorerProjections/display.js
var $p$b = " \u203A ";

// out-build/vs/workbench/contrib/testing/browser/explorerProjections/listProjection.js
var ListTestItemElement = class extends $l$b {
  get description() {
    return this.b.map((c) => c.item.label).join($p$b);
  }
  constructor(test, parent, b) {
    super({ ...test, item: { ...test.item } }, parent);
    this.b = b;
    this.descriptionParts = [];
    this.d();
  }
  update(patch2) {
    $uQ(this.test, patch2);
    this.d(patch2);
    this.fireChange();
  }
  fireChange() {
    this.e.fire();
  }
  d(patch2) {
    if (this.a && (!this.test.item.error || patch2?.item?.error)) {
      this.children.delete(this.a);
      this.a = void 0;
    }
    if (this.test.item.error && !this.a) {
      this.a = new $m$b(this.test.item.error, this);
      this.children.add(this.a);
    }
  }
};
var $q$b = class $q$b2 extends $3c {
  /**
   * Gets root elements of the tree.
   */
  get f() {
    const rootsIt = Iterable.map(this.g.collection.rootItems, (r2) => this.b.get(r2.item.extId));
    return Iterable.filter(rootsIt, (r2) => !!r2?.children.size);
  }
  constructor(lastState, g, h3) {
    super();
    this.lastState = lastState;
    this.g = g;
    this.h = h3;
    this.a = new $ze();
    this.b = /* @__PURE__ */ new Map();
    this.onUpdate = this.a.event;
    this.B(g.onDidProcessDiff((diff3) => this.j(diff3)));
    this.B(h3.onResultsChanged((evt) => {
      if (!("removed" in evt)) {
        return;
      }
      for (const inTree of this.b.values()) {
        const lookup = this.h.getStateById(inTree.test.item.extId)?.[1];
        inTree.duration = lookup?.ownDuration;
        inTree.state = lookup?.ownComputedState || 0;
        inTree.fireChange();
      }
    }));
    this.B(h3.onTestChanged((ev) => {
      if (ev.reason === 2) {
        return;
      }
      let result = ev.item;
      if (result.ownComputedState === 0 || ev.result !== h3.results[0]) {
        const fallback2 = h3.getStateById(result.item.extId);
        if (fallback2) {
          result = fallback2[1];
        }
      }
      const item = this.b.get(result.item.extId);
      if (!item) {
        return;
      }
      item.retired = !!result.retired;
      item.state = result.computedState;
      item.duration = result.ownDuration;
      item.fireChange();
    }));
    for (const test of g.collection.all) {
      this.s(test);
    }
  }
  /**
   * @inheritdoc
   */
  getElementByTestId(testId) {
    return this.b.get(testId);
  }
  /**
   * @inheritdoc
   */
  j(diff3) {
    for (const op of diff3) {
      switch (op.op) {
        case 0: {
          this.s(op.item);
          break;
        }
        case 1: {
          this.b.get(op.item.extId)?.update(op.item);
          break;
        }
        case 3: {
          for (const [id2, item] of this.b) {
            if (id2 === op.itemId || $mQ.isChild(op.itemId, id2)) {
              this.m(item);
            }
          }
          break;
        }
      }
    }
    if (diff3.length !== 0) {
      this.a.fire();
    }
  }
  /**
   * @inheritdoc
   */
  applyTo(tree) {
    tree.setChildren(null, $o$b(this.lastState, this.f, null), {
      diffIdentityProvider: $n$b,
      diffDepth: Infinity
    });
  }
  /**
   * @inheritdoc
   */
  expandElement(element, depth) {
    if (!(element instanceof ListTestItemElement)) {
      return;
    }
    if (element.test.expand === 0) {
      return;
    }
    this.g.collection.expand(element.test.item.extId, depth);
  }
  m(treeElement) {
    this.b.delete(treeElement.test.item.extId);
    treeElement.parent?.children.delete(treeElement);
    const parentId = $mQ.fromString(treeElement.test.item.extId).parentId;
    if (!parentId) {
      return;
    }
    for (const id2 of parentId.idsToRoot()) {
      const parentTest = this.g.collection.getNodeById(id2.toString());
      if (parentTest) {
        if (parentTest.children.size === 0 && !this.b.has(id2.toString())) {
          this.n(parentId, parentTest);
        }
        break;
      }
    }
  }
  n(testId, item) {
    const displayedParent = testId.isRoot ? null : this.b.get(item.controllerId);
    const chain = [...testId.idsFromRoot()].slice(1, -1).map((id2) => this.g.collection.getNodeById(id2.toString()));
    const treeElement = new ListTestItemElement(item, displayedParent, chain);
    displayedParent?.children.add(treeElement);
    this.b.set(treeElement.test.item.extId, treeElement);
    if (treeElement.depth === 0 || $k$b(this.lastState, treeElement.test.item.extId) === false) {
      this.expandElement(treeElement, Infinity);
    }
    const prevState = this.h.getStateById(treeElement.test.item.extId)?.[1];
    if (prevState) {
      treeElement.retired = !!prevState.retired;
      treeElement.state = prevState.computedState;
      treeElement.duration = prevState.ownDuration;
    }
  }
  s(item) {
    const testId = $mQ.fromString(item.item.extId);
    for (const parentId of testId.idsToRoot()) {
      if (!parentId.isRoot) {
        const prevParent = this.b.get(parentId.toString());
        if (prevParent) {
          this.m(prevParent);
          break;
        }
      }
    }
    this.n(testId, item);
  }
};
$q$b = __decorate([
  __param(1, $nTb),
  __param(2, $FTb)
], $q$b);

// out-build/vs/workbench/contrib/testing/browser/explorerProjections/testingObjectTree.js
var $r$b = class extends $1eb {
  /**
   * Gets a serialized view state for the tree, optimized for storage.
   *
   * @param updatePreviousState Optional previous state to mutate and update
   * instead of creating a new one.
   */
  getOptimizedViewState(updatePreviousState) {
    const root = updatePreviousState || {};
    const build = (node, parent) => {
      if (!(node.element instanceof $l$b)) {
        return false;
      }
      const localId = $mQ.localId(node.element.test.item.extId);
      const inTree = parent.children?.[localId] || {};
      inTree.collapsed = node.depth === 0 || !node.collapsed ? node.collapsed : void 0;
      let hasAnyNonDefaultValue = inTree.collapsed !== void 0;
      if (node.children.length) {
        for (const child of node.children) {
          hasAnyNonDefaultValue = build(child, inTree) || hasAnyNonDefaultValue;
        }
      }
      if (hasAnyNonDefaultValue) {
        parent.children ??= {};
        parent.children[localId] = inTree;
      } else if (parent.children?.hasOwnProperty(localId)) {
        delete parent.children[localId];
      }
      return hasAnyNonDefaultValue;
    };
    root.children ??= {};
    for (const node of this.getNode().children) {
      if (node.element instanceof $l$b) {
        if (node.element.test.controllerId === node.element.test.item.extId) {
          build(node, root);
        } else {
          const ctrlNode = root.children[node.element.test.controllerId] ??= { children: {} };
          build(node, ctrlNode);
        }
      }
    }
    return root;
  }
};

// out-build/vs/workbench/contrib/testing/browser/explorerProjections/treeProjection.js
var computedStateAccessor = {
  getOwnState: (i2) => i2 instanceof $l$b ? i2.ownState : 0,
  getCurrentComputedState: (i2) => i2.state,
  setComputedState: (i2, s) => i2.state = s,
  getCurrentComputedDuration: (i2) => i2.duration,
  getOwnDuration: (i2) => i2 instanceof $l$b ? i2.ownDuration : void 0,
  setComputedDuration: (i2, d) => i2.duration = d,
  getChildren: (i2) => Iterable.filter(i2.children.values(), (t) => t instanceof TreeTestItemElement),
  *getParents(i2) {
    for (let parent = i2.parent; parent; parent = parent.parent) {
      yield parent;
    }
  }
};
var TreeTestItemElement = class extends $l$b {
  get description() {
    return this.test.item.description;
  }
  constructor(test, parent, f) {
    super({ ...test, item: { ...test.item } }, parent);
    this.f = f;
    this.ownState = 0;
    this.g();
  }
  update(patch2) {
    $uQ(this.test, patch2);
    this.g(patch2);
    this.fireChange();
  }
  fireChange() {
    this.e.fire();
  }
  g(patch2) {
    if (this.c && (!this.test.item.error || patch2?.item?.error)) {
      this.f(this);
      this.children.delete(this.c);
      this.c = void 0;
    }
    if (this.test.item.error && !this.c) {
      this.c = new $m$b(this.test.item.error, this);
      this.children.add(this.c);
      this.f(this);
    }
  }
};
var $s$b = class $s$b2 extends $3c {
  /**
   * Gets root elements of the tree.
   */
  get m() {
    const rootsIt = Iterable.map(this.u.collection.rootItems, (r2) => this.j.get(r2.item.extId));
    return Iterable.filter(rootsIt, (r2) => !!r2?.children.size);
  }
  constructor(lastState, u, w) {
    super();
    this.lastState = lastState;
    this.u = u;
    this.w = w;
    this.f = new $ze();
    this.g = /* @__PURE__ */ new Set();
    this.h = /* @__PURE__ */ new Set();
    this.j = /* @__PURE__ */ new Map();
    this.onUpdate = this.f.event;
    this.B(u.onDidProcessDiff((diff3) => this.y(diff3)));
    this.B(w.onResultsChanged((evt) => {
      if (!("removed" in evt)) {
        return;
      }
      for (const inTree of [...this.j.values()].sort((a, b) => b.depth - a.depth)) {
        const lookup = this.w.getStateById(inTree.test.item.extId)?.[1];
        inTree.ownDuration = lookup?.ownDuration;
        $GQ(
          computedStateAccessor,
          inTree,
          lookup?.ownComputedState ?? 0
          /* TestResultState.Unset */
        ).forEach((i2) => i2.fireChange());
      }
    }));
    this.B(w.onTestChanged((ev) => {
      if (ev.reason === 2) {
        return;
      }
      let result = ev.item;
      if (result.ownComputedState === 0 || ev.result !== w.results[0]) {
        const fallback2 = w.getStateById(result.item.extId);
        if (fallback2) {
          result = fallback2[1];
        }
      }
      const item = this.j.get(result.item.extId);
      if (!item) {
        return;
      }
      const refreshDuration = ev.reason === 1 && ev.previousOwnDuration !== result.ownDuration;
      const explicitComputed = item.children.size ? void 0 : result.computedState;
      item.retired = !!result.retired;
      item.ownState = result.ownComputedState;
      item.ownDuration = result.ownDuration;
      item.fireChange();
      $GQ(computedStateAccessor, item, explicitComputed, refreshDuration).forEach((i2) => i2.fireChange());
    }));
    for (const test of u.collection.all) {
      this.D(this.z(test));
    }
  }
  /**
   * @inheritdoc
   */
  getElementByTestId(testId) {
    return this.j.get(testId);
  }
  /**
   * @inheritdoc
   */
  y(diff3) {
    for (const op of diff3) {
      switch (op.op) {
        case 0: {
          const item = this.z(op.item);
          this.D(item);
          break;
        }
        case 1: {
          const patch2 = op.item;
          const existing = this.j.get(patch2.extId);
          if (!existing) {
            break;
          }
          const needsParentUpdate = existing.test.expand === 0 && patch2.expand;
          existing.update(patch2);
          if (needsParentUpdate) {
            this.g.add(existing.parent);
          } else {
            this.h.add(existing.parent);
          }
          break;
        }
        case 3: {
          const toRemove = this.j.get(op.itemId);
          if (!toRemove) {
            break;
          }
          const parent = toRemove.parent;
          const affectsRootElement = toRemove.depth === 1 && (parent?.children.size === 1 || !Iterable.some(this.m, (_, i2) => i2 === 1));
          this.g.add(affectsRootElement ? null : parent);
          const queue = [[toRemove]];
          while (queue.length) {
            for (const item of queue.pop()) {
              if (item instanceof TreeTestItemElement) {
                queue.push(this.C(item));
              }
            }
          }
          if (parent instanceof TreeTestItemElement) {
            $GQ(computedStateAccessor, parent, void 0, !!parent.duration).forEach((i2) => i2.fireChange());
          }
        }
      }
    }
    if (diff3.length !== 0) {
      this.f.fire();
    }
  }
  /**
   * @inheritdoc
   */
  applyTo(tree) {
    for (const parent of this.g) {
      if (!parent || tree.hasElement(parent)) {
        tree.setChildren(parent, $o$b(this.lastState, this.m, parent), { diffIdentityProvider: $n$b });
      }
    }
    for (const parent of this.h) {
      if (!parent || tree.hasElement(parent)) {
        tree.resort(parent, false);
      }
    }
    this.g.clear();
    this.h.clear();
  }
  /**
   * @inheritdoc
   */
  expandElement(element, depth) {
    if (!(element instanceof TreeTestItemElement)) {
      return;
    }
    if (element.test.expand === 0) {
      return;
    }
    this.u.collection.expand(element.test.item.extId, depth);
  }
  z(item) {
    const parentId = $mQ.parentId(item.item.extId);
    const parent = parentId ? this.j.get(parentId) : null;
    return new TreeTestItemElement(item, parent, (n) => this.g.add(n));
  }
  C(treeElement) {
    const parent = treeElement.parent;
    parent?.children.delete(treeElement);
    this.j.delete(treeElement.test.item.extId);
    return treeElement.children;
  }
  D(treeElement) {
    treeElement.parent?.children.add(treeElement);
    this.j.set(treeElement.test.item.extId, treeElement);
    const affectsParent = treeElement.parent?.children.size === 1;
    const affectedParent = affectsParent ? treeElement.parent.parent : treeElement.parent;
    this.g.add(affectedParent);
    if (affectedParent?.depth === 0) {
      this.g.add(null);
    }
    if (treeElement.depth === 0 || $k$b(this.lastState, treeElement.test.item.extId) === false) {
      this.expandElement(treeElement, 0);
    }
    const prevState = this.w.getStateById(treeElement.test.item.extId)?.[1];
    if (prevState) {
      treeElement.retired = !!prevState.retired;
      treeElement.ownState = prevState.computedState;
      treeElement.ownDuration = prevState.ownDuration;
      $GQ(computedStateAccessor, treeElement, void 0, !!treeElement.ownDuration).forEach((i2) => i2.fireChange());
    }
  }
};
$s$b = __decorate([
  __param(1, $nTb),
  __param(2, $FTb)
], $s$b);

// out-build/vs/workbench/contrib/testing/browser/testExplorerActions.js
var category2 = $qn.Test;
var ActionOrder;
(function(ActionOrder2) {
  ActionOrder2[ActionOrder2["Refresh"] = 10] = "Refresh";
  ActionOrder2[ActionOrder2["Run"] = 11] = "Run";
  ActionOrder2[ActionOrder2["Debug"] = 12] = "Debug";
  ActionOrder2[ActionOrder2["Coverage"] = 13] = "Coverage";
  ActionOrder2[ActionOrder2["RunContinuous"] = 14] = "RunContinuous";
  ActionOrder2[ActionOrder2["RunUsing"] = 15] = "RunUsing";
  ActionOrder2[ActionOrder2["Collapse"] = 16] = "Collapse";
  ActionOrder2[ActionOrder2["ClearResults"] = 17] = "ClearResults";
  ActionOrder2[ActionOrder2["DisplayMode"] = 18] = "DisplayMode";
  ActionOrder2[ActionOrder2["Sort"] = 19] = "Sort";
  ActionOrder2[ActionOrder2["GoToTest"] = 20] = "GoToTest";
  ActionOrder2[ActionOrder2["HideTest"] = 21] = "HideTest";
  ActionOrder2[ActionOrder2["ContinuousRunTest"] = 2147483647] = "ContinuousRunTest";
})(ActionOrder || (ActionOrder = {}));
var hasAnyTestProvider = $fn.create(TestingContextKeys.providerCount.key, 0);
var LABEL_RUN_TESTS = localize2(11097, "Run Tests");
var LABEL_DEBUG_TESTS = localize2(11098, "Debug Tests");
var LABEL_COVERAGE_TESTS = localize2(11099, "Run Tests with Coverage");
var $t$b = class extends $gJ {
  constructor() {
    super({
      id: "testing.hideTest",
      title: localize2(11100, "Hide Test"),
      menu: {
        id: $bJ.TestItem,
        group: "builtin@2",
        when: TestingContextKeys.testItemIsHidden.isEqualTo(false)
      }
    });
  }
  run(accessor, ...elements) {
    const service = accessor.get($nTb);
    for (const element of elements) {
      service.excluded.toggle(element.test, true);
    }
    return Promise.resolve();
  }
};
var $u$b = class extends $gJ {
  constructor() {
    super({
      id: "testing.unhideTest",
      title: localize2(11101, "Unhide Test"),
      menu: {
        id: $bJ.TestItem,
        order: 21,
        when: TestingContextKeys.testItemIsHidden.isEqualTo(true)
      }
    });
  }
  run(accessor, ...elements) {
    const service = accessor.get($nTb);
    for (const element of elements) {
      if (element instanceof $l$b) {
        service.excluded.toggle(element.test, false);
      }
    }
    return Promise.resolve();
  }
};
var $v$b = class extends $gJ {
  constructor() {
    super({
      id: "testing.unhideAllTests",
      title: localize2(11102, "Unhide All Tests")
    });
  }
  run(accessor) {
    const service = accessor.get($nTb);
    service.excluded.clear();
    return Promise.resolve();
  }
};
var testItemInlineAndInContext = (order, when) => [
  {
    id: $bJ.TestItem,
    group: "inline",
    order,
    when
  },
  {
    id: $bJ.TestItem,
    group: "builtin@1",
    order,
    when
  }
];
var RunVisibleAction = class extends $cpb {
  constructor(c, desc) {
    super({
      ...desc,
      viewId: "workbench.view.testing"
    });
    this.c = c;
  }
  /**
   * @override
   */
  runInView(accessor, view, ...elements) {
    const { include, exclude } = view.getTreeIncludeExclude(this.c, elements.map((e) => e.test));
    return accessor.get($nTb).runTests({
      tests: include,
      exclude,
      group: this.c
    });
  }
};
var $w$b = class extends RunVisibleAction {
  constructor() {
    super(4, {
      id: "testing.debug",
      title: localize2(11103, "Debug Test"),
      icon: $d0b,
      menu: testItemInlineAndInContext(12, TestingContextKeys.hasDebuggableTests.isEqualTo(true))
    });
  }
};
var $x$b = class extends RunVisibleAction {
  constructor() {
    super(8, {
      id: "testing.coverage",
      title: localize2(11104, "Run Test with Coverage"),
      icon: $e0b,
      menu: testItemInlineAndInContext(13, TestingContextKeys.hasCoverableTests.isEqualTo(true))
    });
  }
};
var $y$b = class extends $gJ {
  constructor() {
    super({
      id: "testing.runUsing",
      title: localize2(11105, "Execute Using Profile..."),
      icon: $d0b,
      menu: {
        id: $bJ.TestItem,
        order: 15,
        group: "builtin@2",
        when: TestingContextKeys.hasNonDefaultProfile.isEqualTo(true)
      }
    });
  }
  async run(acessor, ...elements) {
    const commandService = acessor.get($sn);
    const testService = acessor.get($nTb);
    const profile = await commandService.executeCommand("vscode.pickTestProfile", {
      onlyForTest: elements[0].test
    });
    if (!profile) {
      return;
    }
    testService.runResolvedTests({
      group: profile.group,
      targets: [{
        profileId: profile.profileId,
        controllerId: profile.controllerId,
        testIds: elements.filter((t) => $xTb(profile, t.test)).map((t) => t.test.item.extId)
      }]
    });
  }
};
var $z$b = class extends RunVisibleAction {
  constructor() {
    super(2, {
      id: "testing.run",
      title: localize2(11106, "Run Test"),
      icon: $_9b,
      menu: testItemInlineAndInContext(11, TestingContextKeys.hasRunnableTests.isEqualTo(true))
    });
  }
};
var $A$b = class extends $gJ {
  constructor() {
    super({
      id: "testing.selectDefaultTestProfiles",
      title: localize2(11107, "Select Default Profile"),
      icon: $l0b,
      category: category2
    });
  }
  async run(acessor, onlyGroup) {
    const commands2 = acessor.get($sn);
    const testProfileService = acessor.get($wTb);
    const profiles2 = await commands2.executeCommand("vscode.pickMultipleTestProfiles", {
      showConfigureButtons: false,
      selected: testProfileService.getGroupDefaultProfiles(onlyGroup),
      onlyGroup
    });
    if (profiles2?.length) {
      testProfileService.setGroupDefaultProfiles(onlyGroup, profiles2);
    }
  }
};
var $B$b = class extends $gJ {
  constructor() {
    super({
      id: "testing.toggleContinuousRunForTest",
      title: localize2(11108, "Turn on Continuous Run"),
      icon: $n0b,
      precondition: $7m.or(TestingContextKeys.isContinuousModeOn.isEqualTo(true), TestingContextKeys.isParentRunningContinuously.isEqualTo(false)),
      toggled: {
        condition: TestingContextKeys.isContinuousModeOn.isEqualTo(true),
        icon: $p0b,
        title: localize(11081, null)
      },
      menu: testItemInlineAndInContext(2147483647, TestingContextKeys.supportsContinuousRun.isEqualTo(true))
    });
  }
  async run(accessor, ...elements) {
    const crService = accessor.get($i$b);
    for (const element of elements) {
      const id2 = element.test.item.extId;
      if (crService.isSpecificallyEnabledFor(id2)) {
        crService.stop(id2);
        continue;
      }
      crService.start(2, id2);
    }
  }
};
var $C$b = class extends $gJ {
  constructor() {
    super({
      id: "testing.continuousRunUsingForTest",
      title: localize2(11109, "Start Continous Run Using..."),
      icon: $d0b,
      menu: [
        {
          id: $bJ.TestItem,
          order: 14,
          group: "builtin@2",
          when: $7m.and(TestingContextKeys.supportsContinuousRun.isEqualTo(true), TestingContextKeys.isContinuousModeOn.isEqualTo(false))
        }
      ]
    });
  }
  async run(accessor, ...elements) {
    const crService = accessor.get($i$b);
    const profileService = accessor.get($wTb);
    const notificationService = accessor.get($PJ);
    const quickInputService = accessor.get($1M);
    for (const element of elements) {
      const selected = await selectContinuousRunProfiles(crService, notificationService, quickInputService, [{ profiles: profileService.getControllerProfiles(element.test.controllerId) }]);
      if (selected.length) {
        crService.start(selected, element.test.item.extId);
      }
    }
  }
};
var $D$b = class extends $gJ {
  constructor() {
    super({
      id: "testing.configureProfile",
      title: localize2(11110, "Configure Test Profiles"),
      icon: $l0b,
      f1: true,
      category: category2,
      menu: {
        id: $bJ.CommandPalette,
        when: TestingContextKeys.hasConfigurableProfile.isEqualTo(true)
      }
    });
  }
  async run(acessor, onlyGroup) {
    const commands2 = acessor.get($sn);
    const testProfileService = acessor.get($wTb);
    const profile = await commands2.executeCommand("vscode.pickTestProfile", {
      placeholder: localize(11082, null),
      showConfigureButtons: false,
      onlyConfigurable: true,
      onlyGroup
    });
    if (profile) {
      testProfileService.configure(profile.controllerId, profile.profileId);
    }
  }
};
var continuousMenus = (whenIsContinuousOn) => [
  {
    id: $bJ.ViewTitle,
    group: "navigation",
    order: 15,
    when: $7m.and($7m.equals(
      "view",
      "workbench.view.testing"
      /* Testing.ExplorerViewId */
    ), TestingContextKeys.supportsContinuousRun.isEqualTo(true), TestingContextKeys.isContinuousModeOn.isEqualTo(whenIsContinuousOn))
  },
  {
    id: $bJ.CommandPalette,
    when: TestingContextKeys.supportsContinuousRun.isEqualTo(true)
  }
];
var StopContinuousRunAction = class extends $gJ {
  constructor() {
    super({
      id: "testing.stopContinuousRun",
      title: localize2(11111, "Stop Continuous Run"),
      category: category2,
      icon: $o0b,
      menu: continuousMenus(true)
    });
  }
  run(accessor) {
    accessor.get($i$b).stop();
  }
};
function selectContinuousRunProfiles(crs, notificationService, quickInputService, profilesToPickFrom) {
  const items = [];
  for (const { controller, profiles: profiles2 } of profilesToPickFrom) {
    for (const profile of profiles2) {
      if (profile.supportsContinuousRun) {
        items.push({
          label: profile.label || controller?.label.get() || "",
          description: controller?.label.get(),
          profile
        });
      }
    }
  }
  if (items.length === 0) {
    notificationService.info(localize(11083, null));
    return Promise.resolve([]);
  }
  if (items.length === 1) {
    return Promise.resolve([items[0].profile]);
  }
  const qpItems = [];
  const selectedItems = [];
  const lastRun = crs.lastRunProfileIds;
  items.sort((a, b) => a.profile.group - b.profile.group || a.profile.controllerId.localeCompare(b.profile.controllerId) || a.label.localeCompare(b.label));
  for (let i2 = 0; i2 < items.length; i2++) {
    const item = items[i2];
    if (i2 === 0 || items[i2 - 1].profile.group !== item.profile.group) {
      qpItems.push({ type: "separator", label: $vTb[item.profile.group] });
    }
    qpItems.push(item);
    if (lastRun.has(item.profile.profileId)) {
      selectedItems.push(item);
    }
  }
  const disposables = new $2c();
  const quickpick = disposables.add(quickInputService.createQuickPick({ useSeparators: true }));
  quickpick.title = localize(11084, null);
  quickpick.canSelectMany = true;
  quickpick.items = qpItems;
  quickpick.selectedItems = selectedItems;
  quickpick.show();
  return new Promise((resolve) => {
    disposables.add(quickpick.onDidAccept(() => {
      resolve(quickpick.selectedItems.map((i2) => i2.profile));
      disposables.dispose();
    }));
    disposables.add(quickpick.onDidHide(() => {
      resolve([]);
      disposables.dispose();
    }));
  });
}
var StartContinuousRunAction = class extends $gJ {
  constructor() {
    super({
      id: "testing.startContinuousRun",
      title: localize2(11112, "Start Continuous Run"),
      category: category2,
      icon: $n0b,
      menu: continuousMenus(false)
    });
  }
  async run(accessor) {
    const crs = accessor.get($i$b);
    const profileService = accessor.get($wTb);
    const lastRunProfiles = [...profileService.all()].flatMap((p) => p.profiles.filter((p2) => crs.lastRunProfileIds.has(p2.profileId)));
    if (lastRunProfiles.length) {
      return crs.start(lastRunProfiles);
    }
    const selected = await selectContinuousRunProfiles(crs, accessor.get($PJ), accessor.get($1M), accessor.get($wTb).all());
    if (selected.length) {
      crs.start(selected);
    }
  }
};
var ExecuteSelectedAction = class extends $cpb {
  constructor(options3, c) {
    super({
      ...options3,
      menu: [{
        id: $bJ.ViewTitle,
        order: c === 2 ? 11 : c === 4 ? 12 : 13,
        group: "navigation",
        when: $7m.and($7m.equals(
          "view",
          "workbench.view.testing"
          /* Testing.ExplorerViewId */
        ), TestingContextKeys.isRunning.isEqualTo(false), TestingContextKeys.capabilityToContextKey[c].isEqualTo(true))
      }],
      category: category2,
      viewId: "workbench.view.testing"
    });
    this.c = c;
  }
  /**
   * @override
   */
  runInView(accessor, view) {
    const { include, exclude } = view.getTreeIncludeExclude(this.c);
    return accessor.get($nTb).runTests({ tests: include, exclude, group: this.c });
  }
};
var $E$b = class extends $gJ {
  constructor() {
    super({ id: "testing.getSelectedProfiles", title: localize2(11113, "Get Selected Profiles") });
  }
  /**
   * @override
   */
  run(accessor) {
    const profiles2 = accessor.get($wTb);
    return [
      ...profiles2.getGroupDefaultProfiles(
        2
        /* TestRunProfileBitset.Run */
      ),
      ...profiles2.getGroupDefaultProfiles(
        4
        /* TestRunProfileBitset.Debug */
      ),
      ...profiles2.getGroupDefaultProfiles(
        8
        /* TestRunProfileBitset.Coverage */
      )
    ].map((p) => ({
      controllerId: p.controllerId,
      label: p.label,
      kind: p.group & 8 ? 3 : p.group & 4 ? 2 : 1
    }));
  }
};
var $F$b = class extends $cpb {
  constructor() {
    super({
      id: "_testing.getExplorerSelection",
      title: localize2(11114, "Get Explorer Selection"),
      viewId: "workbench.view.testing"
      /* Testing.ExplorerViewId */
    });
  }
  /**
   * @override
   */
  runInView(_accessor, view) {
    const { include, exclude } = view.getTreeIncludeExclude(2, void 0, "selected");
    const mapper = (i2) => i2.item.extId;
    return { include: include.map(mapper), exclude: exclude.map(mapper) };
  }
};
var $G$b = class extends ExecuteSelectedAction {
  constructor() {
    super(
      {
        id: "testing.runSelected",
        title: LABEL_RUN_TESTS,
        icon: $b0b
      },
      2
      /* TestRunProfileBitset.Run */
    );
  }
};
var $H$b = class extends ExecuteSelectedAction {
  constructor() {
    super(
      {
        id: "testing.debugSelected",
        title: LABEL_DEBUG_TESTS,
        icon: $c0b
      },
      4
      /* TestRunProfileBitset.Debug */
    );
  }
};
var $I$b = class extends ExecuteSelectedAction {
  constructor() {
    super(
      {
        id: "testing.coverageSelected",
        title: LABEL_COVERAGE_TESTS,
        icon: $f0b
      },
      8
      /* TestRunProfileBitset.Coverage */
    );
  }
};
var showDiscoveringWhile = (progress, task) => {
  return progress.withProgress({
    location: 10,
    title: localize(11085, null)
  }, () => task);
};
var RunOrDebugAllTestsAction = class extends $gJ {
  constructor(options3, c, d) {
    super({
      ...options3,
      category: category2,
      menu: [{
        id: $bJ.CommandPalette,
        when: TestingContextKeys.capabilityToContextKey[c].isEqualTo(true)
      }]
    });
    this.c = c;
    this.d = d;
  }
  async run(accessor) {
    const testService = accessor.get($nTb);
    const notifications = accessor.get($PJ);
    const roots = [...testService.collection.rootItems].filter(
      (r2) => r2.children.size || r2.expand === 1 || r2.expand === 2
      /* TestItemExpandState.BusyExpanding */
    );
    if (!roots.length) {
      notifications.info(this.d);
      return;
    }
    await testService.runTests({ tests: roots, group: this.c });
  }
};
var $J$b = class extends RunOrDebugAllTestsAction {
  constructor() {
    super({
      id: "testing.runAll",
      title: localize2(11115, "Run All Tests"),
      icon: $b0b,
      keybinding: {
        weight: 200,
        primary: $$e(
          2048 | 85,
          31
          /* KeyCode.KeyA */
        )
      }
    }, 2, localize(11086, null));
  }
};
var $K$b = class extends RunOrDebugAllTestsAction {
  constructor() {
    super({
      id: "testing.debugAll",
      title: localize2(11116, "Debug All Tests"),
      icon: $d0b,
      keybinding: {
        weight: 200,
        primary: $$e(
          2048 | 85,
          2048 | 31
          /* KeyCode.KeyA */
        )
      }
    }, 4, localize(11087, null));
  }
};
var $L$b = class extends RunOrDebugAllTestsAction {
  constructor() {
    super({
      id: "testing.coverageAll",
      title: localize2(11117, "Run All Tests with Coverage"),
      icon: $e0b,
      keybinding: {
        weight: 200,
        primary: $$e(
          2048 | 85,
          2048 | 1024 | 31
          /* KeyCode.KeyA */
        )
      }
    }, 8, localize(11088, null));
  }
};
var $M$b = class extends $gJ {
  constructor() {
    super({
      id: "testing.cancelRun",
      title: localize2(11118, "Cancel Test Run"),
      icon: $g0b,
      keybinding: {
        weight: 200,
        primary: $$e(
          2048 | 85,
          2048 | 54
          /* KeyCode.KeyX */
        )
      },
      menu: [{
        id: $bJ.ViewTitle,
        order: 11,
        group: "navigation",
        when: $7m.and($7m.equals(
          "view",
          "workbench.view.testing"
          /* Testing.ExplorerViewId */
        ), $7m.equals(TestingContextKeys.isRunning.serialize(), true))
      }]
    });
  }
  /**
   * @override
   */
  async run(accessor, resultId, taskId) {
    const resultService = accessor.get($FTb);
    const testService = accessor.get($nTb);
    if (resultId) {
      testService.cancelTestRun(resultId, taskId);
    } else {
      for (const run of resultService.results) {
        if (!run.completedAt) {
          testService.cancelTestRun(run.id);
        }
      }
    }
  }
};
var $N$b = class extends $cpb {
  constructor() {
    super({
      id: "testing.viewAsList",
      viewId: "workbench.view.testing",
      title: localize2(11119, "View as List"),
      toggled: TestingContextKeys.viewMode.isEqualTo(
        "list"
        /* TestExplorerViewMode.List */
      ),
      menu: {
        id: $bJ.ViewTitle,
        order: 18,
        group: "viewAs",
        when: $7m.equals(
          "view",
          "workbench.view.testing"
          /* Testing.ExplorerViewId */
        )
      }
    });
  }
  /**
   * @override
   */
  runInView(_accessor, view) {
    view.viewModel.viewMode = "list";
  }
};
var $O$b = class extends $cpb {
  constructor() {
    super({
      id: "testing.viewAsTree",
      viewId: "workbench.view.testing",
      title: localize2(11120, "View as Tree"),
      toggled: TestingContextKeys.viewMode.isEqualTo(
        "true"
        /* TestExplorerViewMode.Tree */
      ),
      menu: {
        id: $bJ.ViewTitle,
        order: 18,
        group: "viewAs",
        when: $7m.equals(
          "view",
          "workbench.view.testing"
          /* Testing.ExplorerViewId */
        )
      }
    });
  }
  /**
   * @override
   */
  runInView(_accessor, view) {
    view.viewModel.viewMode = "true";
  }
};
var $P$b = class extends $cpb {
  constructor() {
    super({
      id: "testing.sortByStatus",
      viewId: "workbench.view.testing",
      title: localize2(11121, "Sort by Status"),
      toggled: TestingContextKeys.viewSorting.isEqualTo(
        "status"
        /* TestExplorerViewSorting.ByStatus */
      ),
      menu: {
        id: $bJ.ViewTitle,
        order: 19,
        group: "sortBy",
        when: $7m.equals(
          "view",
          "workbench.view.testing"
          /* Testing.ExplorerViewId */
        )
      }
    });
  }
  /**
   * @override
   */
  runInView(_accessor, view) {
    view.viewModel.viewSorting = "status";
  }
};
var $Q$b = class extends $cpb {
  constructor() {
    super({
      id: "testing.sortByLocation",
      viewId: "workbench.view.testing",
      title: localize2(11122, "Sort by Location"),
      toggled: TestingContextKeys.viewSorting.isEqualTo(
        "location"
        /* TestExplorerViewSorting.ByLocation */
      ),
      menu: {
        id: $bJ.ViewTitle,
        order: 19,
        group: "sortBy",
        when: $7m.equals(
          "view",
          "workbench.view.testing"
          /* Testing.ExplorerViewId */
        )
      }
    });
  }
  /**
   * @override
   */
  runInView(_accessor, view) {
    view.viewModel.viewSorting = "location";
  }
};
var $R$b = class extends $cpb {
  constructor() {
    super({
      id: "testing.sortByDuration",
      viewId: "workbench.view.testing",
      title: localize2(11123, "Sort by Duration"),
      toggled: TestingContextKeys.viewSorting.isEqualTo(
        "duration"
        /* TestExplorerViewSorting.ByDuration */
      ),
      menu: {
        id: $bJ.ViewTitle,
        order: 19,
        group: "sortBy",
        when: $7m.equals(
          "view",
          "workbench.view.testing"
          /* Testing.ExplorerViewId */
        )
      }
    });
  }
  /**
   * @override
   */
  runInView(_accessor, view) {
    view.viewModel.viewSorting = "duration";
  }
};
var $S$b = class extends $gJ {
  constructor() {
    super({
      id: "testing.showMostRecentOutput",
      title: localize2(11124, "Show Output"),
      category: category2,
      icon: $6l.terminal,
      keybinding: {
        weight: 200,
        primary: $$e(
          2048 | 85,
          2048 | 45
          /* KeyCode.KeyO */
        )
      },
      precondition: TestingContextKeys.hasAnyResults.isEqualTo(true),
      menu: [{
        id: $bJ.ViewTitle,
        order: 16,
        group: "navigation",
        when: $7m.equals(
          "view",
          "workbench.view.testing"
          /* Testing.ExplorerViewId */
        )
      }, {
        id: $bJ.CommandPalette,
        when: TestingContextKeys.hasAnyResults.isEqualTo(true)
      }]
    });
  }
  async run(accessor) {
    const viewService = accessor.get($uob);
    const testView = await viewService.openView("workbench.panel.testResults.view", true);
    testView?.showLatestRun();
  }
};
var $T$b = class extends $cpb {
  constructor() {
    super({
      id: "testing.collapseAll",
      viewId: "workbench.view.testing",
      title: localize2(11125, "Collapse All Tests"),
      icon: $6l.collapseAll,
      menu: {
        id: $bJ.ViewTitle,
        order: 16,
        group: "displayAction",
        when: $7m.equals(
          "view",
          "workbench.view.testing"
          /* Testing.ExplorerViewId */
        )
      }
    });
  }
  /**
   * @override
   */
  runInView(_accessor, view) {
    view.viewModel.collapseAll();
  }
};
var $U$b = class extends $gJ {
  constructor() {
    super({
      id: "testing.clearTestResults",
      title: localize2(11126, "Clear All Results"),
      category: category2,
      icon: $6l.clearAll,
      menu: [{
        id: $bJ.TestPeekTitle
      }, {
        id: $bJ.CommandPalette,
        when: TestingContextKeys.hasAnyResults.isEqualTo(true)
      }, {
        id: $bJ.ViewTitle,
        order: 17,
        group: "displayAction",
        when: $7m.equals(
          "view",
          "workbench.view.testing"
          /* Testing.ExplorerViewId */
        )
      }, {
        id: $bJ.ViewTitle,
        order: 17,
        group: "navigation",
        when: $7m.equals(
          "view",
          "workbench.panel.testResults.view"
          /* Testing.ResultsViewId */
        )
      }]
    });
  }
  /**
   * @override
   */
  run(accessor) {
    accessor.get($FTb).clear();
  }
};
var $V$b = class extends $gJ {
  constructor() {
    super({
      id: "testing.editFocusedTest",
      title: localize2(11127, "Go to Test"),
      icon: $6l.goToFile,
      menu: {
        id: $bJ.TestItem,
        group: "builtin@1",
        order: 20,
        when: TestingContextKeys.testItemHasUri.isEqualTo(true)
      },
      keybinding: {
        weight: 100 - 10,
        when: $jqb.isEqualTo(
          "workbench.view.testing"
          /* Testing.ExplorerViewId */
        ),
        primary: 3 | 512
      }
    });
  }
  async run(accessor, element, preserveFocus) {
    if (!element) {
      const view = accessor.get($uob).getActiveViewWithId(
        "workbench.view.testing"
        /* Testing.ExplorerViewId */
      );
      element = view?.focusedTreeElements[0];
    }
    if (element && element instanceof $l$b) {
      accessor.get($sn).executeCommand("vscode.revealTest", element.test.item.extId, preserveFocus);
    }
  }
};
async function getTestsAtCursor(testService, uriIdentityService, uri, position, filter) {
  let bestNodes = [];
  let bestRange;
  let bestNodesBefore = [];
  let bestRangeBefore;
  for await (const test of $rTb(testService, uriIdentityService, uri)) {
    if (!test.item.range || filter?.(test) === false) {
      continue;
    }
    const irange = $9C.lift(test.item.range);
    if (irange.containsPosition(position)) {
      if (bestRange && $9C.equalsRange(test.item.range, bestRange)) {
        if (!bestNodes.some((b) => $mQ.isChild(b.item.extId, test.item.extId))) {
          bestNodes.push(test);
        }
      } else {
        bestRange = irange;
        bestNodes = [test];
      }
    } else if ($8C.isBefore(irange.getStartPosition(), position)) {
      if (!bestRangeBefore || bestRangeBefore.getStartPosition().isBefore(irange.getStartPosition())) {
        bestRangeBefore = irange;
        bestNodesBefore = [test];
      } else if (irange.equalsRange(bestRangeBefore) && !bestNodesBefore.some((b) => $mQ.isChild(b.item.extId, test.item.extId))) {
        bestNodesBefore.push(test);
      }
    }
  }
  return bestNodes.length ? bestNodes : bestNodesBefore;
}
var EditorContextOrder;
(function(EditorContextOrder2) {
  EditorContextOrder2[EditorContextOrder2["RunAtCursor"] = 0] = "RunAtCursor";
  EditorContextOrder2[EditorContextOrder2["DebugAtCursor"] = 1] = "DebugAtCursor";
  EditorContextOrder2[EditorContextOrder2["RunInFile"] = 2] = "RunInFile";
  EditorContextOrder2[EditorContextOrder2["DebugInFile"] = 3] = "DebugInFile";
  EditorContextOrder2[EditorContextOrder2["GoToRelated"] = 4] = "GoToRelated";
  EditorContextOrder2[EditorContextOrder2["PeekRelated"] = 5] = "PeekRelated";
})(EditorContextOrder || (EditorContextOrder = {}));
var ExecuteTestAtCursor = class extends $gJ {
  constructor(options3, c) {
    super({
      ...options3,
      menu: [{
        id: $bJ.CommandPalette,
        when: hasAnyTestProvider
      }, {
        id: $bJ.EditorContext,
        group: "testing",
        order: c === 2 ? 0 : 1,
        when: $7m.and(TestingContextKeys.activeEditorHasTests, TestingContextKeys.capabilityToContextKey[c])
      }]
    });
    this.c = c;
  }
  /**
   * @override
   */
  async run(accessor) {
    const codeEditorService = accessor.get($U5);
    const editorService = accessor.get($mJ);
    const activeEditorPane = editorService.activeEditorPane;
    let editor = codeEditorService.getActiveCodeEditor();
    if (!activeEditorPane || !editor) {
      return;
    }
    if (editor instanceof $bdb) {
      editor = editor.getParentEditor();
    }
    const position = editor?.getPosition();
    const model = editor?.getModel();
    if (!position || !model || !("uri" in model)) {
      return;
    }
    const testService = accessor.get($nTb);
    const profileService = accessor.get($wTb);
    const uriIdentityService = accessor.get($vl);
    const progressService = accessor.get($TJ);
    const configurationService = accessor.get($kl);
    const saveBeforeTest = $w9b(
      configurationService,
      "testing.saveBeforeTest"
      /* TestingConfigKeys.SaveBeforeTest */
    );
    if (saveBeforeTest) {
      await editorService.save({ editor: activeEditorPane.input, groupId: activeEditorPane.group.id });
      await testService.syncTests();
    }
    const testsToRun = await showDiscoveringWhile(progressService, getTestsAtCursor(testService, uriIdentityService, model.uri, position, (test) => !!(profileService.capabilitiesForTest(test.item) & this.c)));
    if (testsToRun.length) {
      await testService.runTests({ group: this.c, tests: testsToRun });
      return;
    }
    const relatedTests = await testService.getTestsRelatedToCode(model.uri, position);
    if (relatedTests.length) {
      await testService.runTests({ group: this.c, tests: relatedTests });
      return;
    }
    if (editor) {
      $S_.get(editor)?.showMessage(localize(11089, null), position);
    }
  }
};
var $W$b = class extends ExecuteTestAtCursor {
  constructor() {
    super(
      {
        id: "testing.runAtCursor",
        title: localize2(11128, "Run Test at Cursor"),
        category: category2,
        keybinding: {
          weight: 200,
          when: EditorContextKeys.editorTextFocus,
          primary: $$e(
            2048 | 85,
            33
            /* KeyCode.KeyC */
          )
        }
      },
      2
      /* TestRunProfileBitset.Run */
    );
  }
};
var $X$b = class extends ExecuteTestAtCursor {
  constructor() {
    super(
      {
        id: "testing.debugAtCursor",
        title: localize2(11129, "Debug Test at Cursor"),
        category: category2,
        keybinding: {
          weight: 200,
          when: EditorContextKeys.editorTextFocus,
          primary: $$e(
            2048 | 85,
            2048 | 33
            /* KeyCode.KeyC */
          )
        }
      },
      4
      /* TestRunProfileBitset.Debug */
    );
  }
};
var $Y$b = class extends ExecuteTestAtCursor {
  constructor() {
    super(
      {
        id: "testing.coverageAtCursor",
        title: localize2(11130, "Run Test at Cursor with Coverage"),
        category: category2,
        keybinding: {
          weight: 200,
          when: EditorContextKeys.editorTextFocus,
          primary: $$e(
            2048 | 85,
            2048 | 1024 | 33
            /* KeyCode.KeyC */
          )
        }
      },
      8
      /* TestRunProfileBitset.Coverage */
    );
  }
};
var ExecuteTestsUnderUriAction = class extends $gJ {
  constructor(options3, c) {
    super({
      ...options3,
      menu: [{
        id: $bJ.ExplorerContext,
        when: TestingContextKeys.capabilityToContextKey[c].isEqualTo(true),
        group: "6.5_testing",
        order: (c === 2 ? 11 : 12) + 0.1
      }]
    });
    this.c = c;
  }
  async run(accessor, uri) {
    const testService = accessor.get($nTb);
    const notificationService = accessor.get($PJ);
    const tests = await Iterable.asyncToArray($sTb(testService, accessor.get($vl), uri));
    if (!tests.length) {
      notificationService.notify({ message: localize(11090, null), severity: Severity2.Info });
      return;
    }
    return testService.runTests({ tests, group: this.c });
  }
};
var RunTestsUnderUri = class extends ExecuteTestsUnderUriAction {
  constructor() {
    super(
      {
        id: "testing.run.uri",
        title: LABEL_RUN_TESTS,
        category: category2
      },
      2
      /* TestRunProfileBitset.Run */
    );
  }
};
var DebugTestsUnderUri = class extends ExecuteTestsUnderUriAction {
  constructor() {
    super(
      {
        id: "testing.debug.uri",
        title: LABEL_DEBUG_TESTS,
        category: category2
      },
      4
      /* TestRunProfileBitset.Debug */
    );
  }
};
var CoverageTestsUnderUri = class extends ExecuteTestsUnderUriAction {
  constructor() {
    super(
      {
        id: "testing.coverage.uri",
        title: LABEL_COVERAGE_TESTS,
        category: category2
      },
      8
      /* TestRunProfileBitset.Coverage */
    );
  }
};
var ExecuteTestsInCurrentFile = class extends $gJ {
  constructor(options3, c) {
    super({
      ...options3,
      menu: [{
        id: $bJ.CommandPalette,
        when: TestingContextKeys.capabilityToContextKey[c].isEqualTo(true)
      }, {
        id: $bJ.EditorContext,
        group: "testing",
        order: c === 2 ? 2 : 3,
        when: $7m.and(TestingContextKeys.activeEditorHasTests, TestingContextKeys.capabilityToContextKey[c])
      }]
    });
    this.c = c;
  }
  /**
   * @override
   */
  run(accessor) {
    let editor = accessor.get($U5).getActiveCodeEditor();
    if (!editor) {
      return;
    }
    if (editor instanceof $bdb) {
      editor = editor.getParentEditor();
    }
    const position = editor?.getPosition();
    const model = editor?.getModel();
    if (!position || !model || !("uri" in model)) {
      return;
    }
    const testService = accessor.get($nTb);
    const demandedUri = model.uri.toString();
    const queue = [testService.collection.rootIds];
    const discovered = [];
    while (queue.length) {
      for (const id2 of queue.pop()) {
        const node = testService.collection.getNodeById(id2);
        if (node.item.uri?.toString() === demandedUri) {
          discovered.push(node);
        } else {
          queue.push(node.children);
        }
      }
    }
    if (discovered.length) {
      return testService.runTests({
        tests: discovered,
        group: this.c
      });
    }
    if (editor) {
      $S_.get(editor)?.showMessage(localize(11091, null), position);
    }
    return void 0;
  }
};
var $Z$b = class extends ExecuteTestsInCurrentFile {
  constructor() {
    super(
      {
        id: "testing.runCurrentFile",
        title: localize2(11131, "Run Tests in Current File"),
        category: category2,
        keybinding: {
          weight: 200,
          when: EditorContextKeys.editorTextFocus,
          primary: $$e(
            2048 | 85,
            36
            /* KeyCode.KeyF */
          )
        }
      },
      2
      /* TestRunProfileBitset.Run */
    );
  }
};
var $1$b = class extends ExecuteTestsInCurrentFile {
  constructor() {
    super(
      {
        id: "testing.debugCurrentFile",
        title: localize2(11132, "Debug Tests in Current File"),
        category: category2,
        keybinding: {
          weight: 200,
          when: EditorContextKeys.editorTextFocus,
          primary: $$e(
            2048 | 85,
            2048 | 36
            /* KeyCode.KeyF */
          )
        }
      },
      4
      /* TestRunProfileBitset.Debug */
    );
  }
};
var $2$b = class extends ExecuteTestsInCurrentFile {
  constructor() {
    super(
      {
        id: "testing.coverageCurrentFile",
        title: localize2(11133, "Run Tests with Coverage in Current File"),
        category: category2,
        keybinding: {
          weight: 200,
          when: EditorContextKeys.editorTextFocus,
          primary: $$e(
            2048 | 85,
            2048 | 1024 | 36
            /* KeyCode.KeyF */
          )
        }
      },
      8
      /* TestRunProfileBitset.Coverage */
    );
  }
};
var $3$b = async (collection, progress, ids, runTests) => {
  const todo = Promise.all(ids.map((p) => $qTb(collection, p)));
  const tests = (await showDiscoveringWhile(progress, todo)).filter($Hg);
  return tests.length ? await runTests(tests) : void 0;
};
var RunOrDebugExtsByPath = class extends $gJ {
  /**
   * @override
   */
  async run(accessor, ...args2) {
    const testService = accessor.get($nTb);
    await $3$b(accessor.get($nTb).collection, accessor.get($TJ), [...this.c(accessor, ...args2)], (tests) => this.d(testService, tests));
  }
};
var RunOrDebugFailedTests = class extends RunOrDebugExtsByPath {
  constructor(options3) {
    super({
      ...options3,
      menu: {
        id: $bJ.CommandPalette,
        when: hasAnyTestProvider
      }
    });
  }
  /**
   * @inheritdoc
   */
  c(accessor) {
    const { results } = accessor.get($FTb);
    const ids = /* @__PURE__ */ new Set();
    for (let i2 = results.length - 1; i2 >= 0; i2--) {
      const resultSet = results[i2];
      for (const test of resultSet.tests) {
        if ($yQ(test.ownComputedState)) {
          ids.add(test.item.extId);
        } else {
          ids.delete(test.item.extId);
        }
      }
    }
    return ids;
  }
};
var RunOrDebugLastRun = class extends $gJ {
  constructor(options3) {
    super({
      ...options3,
      menu: {
        id: $bJ.CommandPalette,
        when: $7m.and(hasAnyTestProvider, TestingContextKeys.hasAnyResults.isEqualTo(true))
      }
    });
  }
  d(accessor, runId) {
    const resultService = accessor.get($FTb);
    const lastResult = runId ? resultService.results.find((r2) => r2.id === runId) : resultService.results[0];
    return lastResult?.request;
  }
  /** @inheritdoc */
  async run(accessor, runId) {
    const resultService = accessor.get($FTb);
    const lastResult = runId ? resultService.results.find((r2) => r2.id === runId) : resultService.results[0];
    if (!lastResult) {
      return;
    }
    const req = lastResult.request;
    const testService = accessor.get($nTb);
    const profileService = accessor.get($wTb);
    const profileExists = (t) => profileService.getControllerProfiles(t.controllerId).some((p) => p.profileId === t.profileId);
    await $3$b(testService.collection, accessor.get($TJ), req.targets.flatMap((t) => t.testIds), (tests) => {
      if (this.c() & req.group && req.targets.every(profileExists)) {
        return testService.runResolvedTests({
          targets: req.targets,
          group: req.group,
          exclude: req.exclude
        });
      } else {
        return testService.runTests({ tests, group: this.c() });
      }
    });
  }
};
var $4$b = class extends RunOrDebugFailedTests {
  constructor() {
    super({
      id: "testing.reRunFailTests",
      title: localize2(11134, "Rerun Failed Tests"),
      category: category2,
      keybinding: {
        weight: 200,
        primary: $$e(
          2048 | 85,
          35
          /* KeyCode.KeyE */
        )
      }
    });
  }
  d(service, internalTests) {
    return service.runTests({
      group: 2,
      tests: internalTests
    });
  }
};
var $5$b = class extends RunOrDebugFailedTests {
  constructor() {
    super({
      id: "testing.debugFailTests",
      title: localize2(11135, "Debug Failed Tests"),
      category: category2,
      keybinding: {
        weight: 200,
        primary: $$e(
          2048 | 85,
          2048 | 35
          /* KeyCode.KeyE */
        )
      }
    });
  }
  d(service, internalTests) {
    return service.runTests({
      group: 4,
      tests: internalTests
    });
  }
};
var $6$b = class extends RunOrDebugLastRun {
  constructor() {
    super({
      id: "testing.reRunLastRun",
      title: localize2(11136, "Rerun Last Run"),
      category: category2,
      keybinding: {
        weight: 200,
        primary: $$e(
          2048 | 85,
          42
          /* KeyCode.KeyL */
        )
      }
    });
  }
  c() {
    return 2;
  }
};
var $7$b = class extends RunOrDebugLastRun {
  constructor() {
    super({
      id: "testing.debugLastRun",
      title: localize2(11137, "Debug Last Run"),
      category: category2,
      keybinding: {
        weight: 200,
        primary: $$e(
          2048 | 85,
          2048 | 42
          /* KeyCode.KeyL */
        )
      }
    });
  }
  c() {
    return 4;
  }
};
var $8$b = class extends RunOrDebugLastRun {
  constructor() {
    super({
      id: "testing.coverageLastRun",
      title: localize2(11138, "Rerun Last Run with Coverage"),
      category: category2,
      keybinding: {
        weight: 200,
        primary: $$e(
          2048 | 85,
          2048 | 1024 | 42
          /* KeyCode.KeyL */
        )
      }
    });
  }
  c() {
    return 8;
  }
};
var $9$b = class extends $gJ {
  constructor() {
    super({
      id: "testing.searchForTestExtension",
      title: localize2(11139, "Search for Test Extension")
    });
  }
  async run(accessor) {
    accessor.get($vzb).openSearch('@category:"testing"');
  }
};
var $0$b = class extends $gJ {
  constructor() {
    super({
      id: "testing.openOutputPeek",
      title: localize2(11140, "Peek Output"),
      category: category2,
      keybinding: {
        weight: 200,
        primary: $$e(
          2048 | 85,
          2048 | 43
          /* KeyCode.KeyM */
        )
      },
      menu: {
        id: $bJ.CommandPalette,
        when: TestingContextKeys.hasAnyResults.isEqualTo(true)
      }
    });
  }
  async run(accessor) {
    accessor.get($B0b).open();
  }
};
var $$$b = class extends $gJ {
  constructor() {
    super({
      id: "testing.toggleInlineTestOutput",
      title: localize2(11141, "Toggle Inline Test Output"),
      category: category2,
      keybinding: {
        weight: 200,
        primary: $$e(
          2048 | 85,
          2048 | 39
          /* KeyCode.KeyI */
        )
      },
      menu: {
        id: $bJ.CommandPalette,
        when: TestingContextKeys.hasAnyResults.isEqualTo(true)
      }
    });
  }
  async run(accessor) {
    const testService = accessor.get($nTb);
    testService.showInlineOutput.value = !testService.showInlineOutput.value;
  }
};
var refreshMenus = (whenIsRefreshing) => [
  {
    id: $bJ.TestItem,
    group: "inline",
    order: 10,
    when: $7m.and(TestingContextKeys.canRefreshTests.isEqualTo(true), TestingContextKeys.isRefreshingTests.isEqualTo(whenIsRefreshing))
  },
  {
    id: $bJ.ViewTitle,
    group: "navigation",
    order: 10,
    when: $7m.and($7m.equals(
      "view",
      "workbench.view.testing"
      /* Testing.ExplorerViewId */
    ), TestingContextKeys.canRefreshTests.isEqualTo(true), TestingContextKeys.isRefreshingTests.isEqualTo(whenIsRefreshing))
  },
  {
    id: $bJ.CommandPalette,
    when: TestingContextKeys.canRefreshTests.isEqualTo(true)
  }
];
var $_$b = class extends $gJ {
  constructor() {
    super({
      id: "testing.refreshTests",
      title: localize2(11142, "Refresh Tests"),
      category: category2,
      icon: $m0b,
      keybinding: {
        weight: 200,
        primary: $$e(
          2048 | 85,
          2048 | 48
          /* KeyCode.KeyR */
        ),
        when: TestingContextKeys.canRefreshTests.isEqualTo(true)
      },
      menu: refreshMenus(false)
    });
  }
  async run(accessor, ...elements) {
    const testService = accessor.get($nTb);
    const progressService = accessor.get($TJ);
    const controllerIds = $Rb(elements.filter($Hg).map((e) => e.test.controllerId));
    return progressService.withProgress({
      location: "workbench.view.extension.test"
      /* Testing.ViewletId */
    }, async () => {
      if (controllerIds.length) {
        await Promise.all(controllerIds.map((id2) => testService.refreshTests(id2)));
      } else {
        await testService.refreshTests();
      }
    });
  }
};
var $a_b = class extends $gJ {
  constructor() {
    super({
      id: "testing.cancelTestRefresh",
      title: localize2(11143, "Cancel Test Refresh"),
      category: category2,
      icon: $q0b,
      menu: refreshMenus(true)
    });
  }
  async run(accessor) {
    accessor.get($nTb).cancelRefreshTests();
  }
};
var $b_b = class extends $gJ {
  constructor() {
    super({
      id: "testing.coverage.close",
      title: localize2(11144, "Clear Coverage"),
      icon: $_r,
      category: category2,
      menu: [{
        id: $bJ.ViewTitle,
        group: "navigation",
        order: 10,
        when: $7m.equals(
          "view",
          "workbench.view.testCoverage"
          /* Testing.CoverageViewId */
        )
      }, {
        id: $bJ.CommandPalette,
        when: TestingContextKeys.isTestCoverageOpen.isEqualTo(true)
      }]
    });
  }
  run(accessor) {
    accessor.get($y9b).closeCoverage();
  }
};
var $c_b = class extends $gJ {
  constructor() {
    super({
      id: "testing.openCoverage",
      title: localize2(11145, "Open Coverage"),
      category: category2,
      menu: [{
        id: $bJ.CommandPalette,
        when: TestingContextKeys.hasAnyResults.isEqualTo(true)
      }]
    });
  }
  run(accessor) {
    const results = accessor.get($FTb).results;
    const task = results.length && results[0].tasks.find((r2) => r2.coverage);
    if (!task) {
      const notificationService = accessor.get($PJ);
      notificationService.info(localize(11092, null));
      return;
    }
    accessor.get($y9b).openCoverage(task, true);
  }
};
var TestNavigationAction = class extends $qfb {
  runEditorCommand(accessor, editor, ...args2) {
    this.q = accessor.get($nTb);
    this.s = accessor.get($vl);
    return super.runEditorCommand(accessor, editor, ...args2);
  }
  k(editor) {
    return editor.getOption(
      60
      /* EditorOption.gotoLocation */
    ).alternativeTestsCommand;
  }
  l(editor) {
    return editor.getOption(
      60
      /* EditorOption.gotoLocation */
    ).multipleTests || "peek";
  }
};
var GoToRelatedTestAction = class extends TestNavigationAction {
  async h(_languageFeaturesService, model, position, token) {
    const tests = await this.q.getTestsRelatedToCode(model.uri, position, token);
    return new $9eb(tests.map((t) => t.item.uri && { uri: t.item.uri, range: t.item.range || new $9C(1, 1, 1, 1) }).filter($Hg), localize(11093, null));
  }
  j() {
    return localize(11094, null);
  }
};
var GoToRelatedTest = class extends GoToRelatedTestAction {
  constructor() {
    super({
      openToSide: false,
      openInPeek: false,
      muteMessage: false
    }, {
      id: "testing.goToRelatedTest",
      title: localize2(11146, "Go to Related Test"),
      category: category2,
      precondition: $7m.and(
        // todo@connor4312: make this more explicit based on cursor position
        $7m.not(TestingContextKeys.activeEditorHasTests.key),
        TestingContextKeys.canGoToRelatedTest
      ),
      menu: [{
        id: $bJ.EditorContext,
        group: "testing",
        order: 4
      }]
    });
  }
};
var PeekRelatedTest = class extends GoToRelatedTestAction {
  constructor() {
    super({
      openToSide: false,
      openInPeek: true,
      muteMessage: false
    }, {
      id: "testing.peekRelatedTest",
      title: localize2(11147, "Peek Related Test"),
      category: category2,
      precondition: $7m.and(
        TestingContextKeys.canGoToRelatedTest,
        // todo@connor4312: make this more explicit based on cursor position
        $7m.not(TestingContextKeys.activeEditorHasTests.key),
        PeekContext.notInPeekEditor,
        EditorContextKeys.isInEmbeddedEditor.toNegated()
      ),
      menu: [{
        id: $bJ.EditorContext,
        group: "testing",
        order: 5
      }]
    });
  }
};
var GoToRelatedCodeAction = class extends TestNavigationAction {
  async h(_languageFeaturesService, model, position, token) {
    const testsAtCursor = await getTestsAtCursor(this.q, this.s, model.uri, position);
    const code = await Promise.all(testsAtCursor.map((t) => this.q.getCodeRelatedToTest(t)));
    return new $9eb(code.flat(), localize(11095, null));
  }
  j() {
    return localize(11096, null);
  }
};
var GoToRelatedCode = class extends GoToRelatedCodeAction {
  constructor() {
    super({
      openToSide: false,
      openInPeek: false,
      muteMessage: false
    }, {
      id: "testing.goToRelatedCode",
      title: localize2(11148, "Go to Related Code"),
      category: category2,
      precondition: $7m.and(TestingContextKeys.activeEditorHasTests, TestingContextKeys.canGoToRelatedCode),
      menu: [{
        id: $bJ.EditorContext,
        group: "testing",
        order: 4
      }]
    });
  }
};
var PeekRelatedCode = class extends GoToRelatedCodeAction {
  constructor() {
    super({
      openToSide: false,
      openInPeek: true,
      muteMessage: false
    }, {
      id: "testing.peekRelatedCode",
      title: localize2(11149, "Peek Related Code"),
      category: category2,
      precondition: $7m.and(TestingContextKeys.activeEditorHasTests, TestingContextKeys.canGoToRelatedCode, PeekContext.notInPeekEditor, EditorContextKeys.isInEmbeddedEditor.toNegated()),
      menu: [{
        id: $bJ.EditorContext,
        group: "testing",
        order: 5
      }]
    });
  }
};
var $d_b = [
  $a_b,
  $M$b,
  $b_b,
  $U$b,
  $T$b,
  $D$b,
  $B$b,
  $C$b,
  $x$b,
  $L$b,
  $Y$b,
  $2$b,
  $8$b,
  $I$b,
  CoverageTestsUnderUri,
  $w$b,
  $K$b,
  $X$b,
  $1$b,
  $5$b,
  $7$b,
  $H$b,
  DebugTestsUnderUri,
  $F$b,
  $E$b,
  GoToRelatedCode,
  GoToRelatedTest,
  $V$b,
  $t$b,
  $c_b,
  $0$b,
  PeekRelatedCode,
  PeekRelatedTest,
  $_$b,
  $4$b,
  $6$b,
  $z$b,
  $J$b,
  $W$b,
  $Z$b,
  $G$b,
  RunTestsUnderUri,
  $y$b,
  $9$b,
  $A$b,
  $S$b,
  StartContinuousRunAction,
  StopContinuousRunAction,
  $R$b,
  $Q$b,
  $P$b,
  $N$b,
  $O$b,
  $$$b,
  $v$b,
  $u$b
];

// out-build/vs/workbench/contrib/testing/browser/testingExplorerFilter.js
var testFilterDescriptions = {
  [
    "@failed"
    /* TestFilterTerm.Failed */
  ]: localize(11178, null),
  [
    "@executed"
    /* TestFilterTerm.Executed */
  ]: localize(11179, null),
  [
    "@doc"
    /* TestFilterTerm.CurrentDoc */
  ]: localize(11180, null),
  [
    "@openedFiles"
    /* TestFilterTerm.OpenedFiles */
  ]: localize(11181, null),
  [
    "@hidden"
    /* TestFilterTerm.Hidden */
  ]: localize(11182, null)
};
var $e_b = class $e_b2 extends $T1 {
  constructor(action, options3, m, n, s) {
    super(null, action, options3);
    this.m = m;
    this.n = n;
    this.s = s;
    this.c = this.B(new $ze());
    this.onDidFocus = this.c.event;
    this.g = this.B(this.n.createInstance($jTb, {
      key: "testing.filterHistory2",
      scope: 1,
      target: 1
      /* StorageTarget.MACHINE */
    }));
    this.h = new $Um("markersFiltersAction", localize(11183, null), "testing-filter-button " + ThemeIcon.asClassName($h0b));
    this.t();
    this.B(s.excluded.onTestExclusionsChanged(this.t, this));
  }
  /**
   * @override
   */
  render(container2) {
    container2.classList.add("testing-filter-action-item");
    const updateDelayer = this.B(new $Sh(400));
    const wrapper = this.b = $(".testing-filter-wrapper");
    container2.appendChild(wrapper);
    let history = this.g.get({ lastValue: "", values: [] });
    if (history instanceof Array) {
      history = { lastValue: "", values: history };
    }
    if (history.lastValue) {
      this.m.setText(history.lastValue);
    }
    const input = this.a = this.B(this.n.createInstance($PZb, {
      id: "testing.explorer.filter",
      ariaLabel: localize(11184, null),
      parent: wrapper,
      suggestionProvider: {
        triggerCharacters: ["@"],
        provideResults: () => [
          ...Object.entries(testFilterDescriptions).map(([label3, detail2]) => ({ label: label3, detail: detail2 })),
          ...Iterable.map(this.s.collection.tags.values(), (tag2) => {
            const { ctrlId, tagId } = $tQ(tag2.id);
            const insertText = `@${ctrlId}:${tagId}`;
            return {
              label: `@${ctrlId}:${tagId}`,
              detail: this.s.collection.getNodeById(ctrlId)?.item.label,
              insertText: tagId.includes(" ") ? `@${ctrlId}:"${tagId.replace(/(["\\])/g, "\\$1")}"` : insertText
            };
          })
        ].filter((r2) => !this.m.text.value.includes(r2.label))
      },
      resourceHandle: "testing:filter",
      suggestOptions: {
        value: this.m.text.value,
        placeholderText: localize(11185, null)
      },
      history: history.values
    }));
    this.B(this.m.text.onDidChange((newValue) => {
      if (input.getValue() !== newValue) {
        input.setValue(newValue);
      }
    }));
    this.B(this.m.onDidRequestInputFocus(() => {
      input.focus();
    }));
    this.B(input.onDidFocus(() => {
      this.c.fire();
    }));
    this.B(input.onInputDidChange(() => updateDelayer.trigger(() => {
      input.addToHistory();
      this.m.setText(input.getValue());
    })));
    const actionbar = this.B(new $LZ(container2, {
      actionViewItemProvider: (action, options3) => {
        if (action.id === this.h.id) {
          return this.n.createInstance(FiltersDropdownMenuActionViewItem, action, options3, this.m, this.actionRunner);
        }
        return void 0;
      }
    }));
    actionbar.push(this.h, { icon: true, label: false });
    this.layout(this.b.clientWidth);
  }
  layout(width2) {
    this.a.layout(new $rj(width2 - /* horizontal padding */
    24 - /* editor padding */
    8 - /* filter button padding */
    22, 20));
  }
  /**
   * Focuses the filter input.
   */
  focus() {
    this.a.focus();
  }
  /**
   * Persists changes to the input history.
   */
  saveState() {
    this.g.store({ lastValue: this.a.getValue(), values: this.a.getHistory() });
  }
  /**
   * @override
   */
  dispose() {
    this.saveState();
    super.dispose();
  }
  /**
   * Updates the 'checked' state of the filter submenu.
   */
  t() {
    this.h.checked = this.s.excluded.hasAny;
  }
};
$e_b = __decorate([
  __param(2, $60b),
  __param(3, $Pk),
  __param(4, $nTb)
], $e_b);
var FiltersDropdownMenuActionViewItem = class FiltersDropdownMenuActionViewItem2 extends $L2 {
  constructor(action, options3, a, actionRunner, contextMenuService, g) {
    super(action, { getActions: () => this.O() }, contextMenuService, {
      actionRunner,
      classNames: action.class,
      anchorAlignmentProvider: () => 1,
      menuAsChild: true
    });
    this.a = a;
    this.g = g;
  }
  render(container2) {
    super.render(container2);
    this.J();
  }
  O() {
    return [
      ...[
        "@failed",
        "@executed",
        "@doc",
        "@openedFiles"
        /* TestFilterTerm.OpenedFiles */
      ].map((term) => ({
        checked: this.a.isFilteringFor(term),
        class: void 0,
        enabled: true,
        id: term,
        label: testFilterDescriptions[term],
        run: () => this.a.toggleFilteringFor(term),
        tooltip: "",
        dispose: () => null
      })),
      new $Wm(),
      {
        checked: this.a.fuzzy.value,
        class: void 0,
        enabled: true,
        id: "fuzzy",
        label: localize(11186, null),
        run: () => this.a.fuzzy.value = !this.a.fuzzy.value,
        tooltip: ""
      },
      new $Wm(),
      {
        checked: this.a.isFilteringFor(
          "@hidden"
          /* TestFilterTerm.Hidden */
        ),
        class: void 0,
        enabled: this.g.excluded.hasAny,
        id: "showExcluded",
        label: localize(11187, null),
        run: () => this.a.toggleFilteringFor(
          "@hidden"
          /* TestFilterTerm.Hidden */
        ),
        tooltip: ""
      },
      {
        class: void 0,
        enabled: this.g.excluded.hasAny,
        id: "removeExcluded",
        label: localize(11188, null),
        run: async () => this.g.excluded.clear(),
        tooltip: ""
      }
    ];
  }
  J() {
    this.element.classList.toggle("checked", this._action.checked);
  }
};
FiltersDropdownMenuActionViewItem = __decorate([
  __param(4, $50),
  __param(5, $nTb)
], FiltersDropdownMenuActionViewItem);

// out-build/vs/workbench/contrib/testing/browser/testingProgressUiService.js
var $f_b = class $f_b2 extends $3c {
  constructor(resultService, testCoverageService, a, b) {
    super();
    this.a = a;
    this.b = b;
    this.B(resultService.onResultsChanged((e) => {
      if ("started" in e) {
        this.c(e.started);
      }
    }));
    const barContributionRegistration = $td((reader) => {
      const hasCoverage = !!testCoverageService.selected.read(reader);
      if (!hasCoverage) {
        return;
      }
      barContributionRegistration.dispose();
      $B9b.register();
    });
    this.B(barContributionRegistration);
  }
  c(result) {
    if (result.request.preserveFocus === true) {
      return;
    }
    const cfg = $w9b(
      this.a,
      "testing.automaticallyOpenTestResults"
      /* TestingConfigKeys.OpenResults */
    );
    if (cfg === "neverOpen") {
      return;
    }
    if (cfg === "openExplorerOnTestStart") {
      return this.f();
    }
    if (cfg === "openOnTestStart") {
      return this.g();
    }
    const disposable = new $2c();
    disposable.add(result.onComplete(() => disposable.dispose()));
    disposable.add(result.onChange((e) => {
      if (e.reason === 1 && $yQ(e.item.ownComputedState)) {
        this.g();
        disposable.dispose();
      }
    }));
  }
  f() {
    this.b.openView("workbench.view.testing", false);
  }
  g() {
    this.b.openView("workbench.panel.testResults.view", false);
  }
};
$f_b = __decorate([
  __param(0, $FTb),
  __param(1, $y9b),
  __param(2, $kl),
  __param(3, $uob)
], $f_b);
var $g_b = (isRunning, results) => {
  let passed = 0;
  let failed = 0;
  let skipped = 0;
  let running = 0;
  let queued = 0;
  for (const result of results) {
    const count = result.counts;
    failed += count[
      6
      /* TestResultState.Errored */
    ] + count[
      4
      /* TestResultState.Failed */
    ];
    passed += count[
      3
      /* TestResultState.Passed */
    ];
    skipped += count[
      5
      /* TestResultState.Skipped */
    ];
    running += count[
      2
      /* TestResultState.Running */
    ];
    queued += count[
      1
      /* TestResultState.Queued */
    ];
  }
  return {
    isRunning,
    passed,
    failed,
    runSoFar: passed + failed,
    totalWillBeRun: passed + failed + queued + running,
    skipped
  };
};
var $h_b = ({ isRunning, passed, runSoFar, totalWillBeRun, skipped, failed }) => {
  let percent = passed / runSoFar * 100;
  if (failed > 0) {
    percent = Math.min(percent, 99.9);
  } else if (runSoFar === 0) {
    percent = 0;
  }
  if (isRunning) {
    if (runSoFar === 0) {
      return localize(11214, null);
    } else if (skipped === 0) {
      return localize(11215, null, passed, totalWillBeRun, percent.toPrecision(3));
    } else {
      return localize(11216, null, passed, totalWillBeRun, percent.toPrecision(3), skipped);
    }
  } else {
    if (skipped === 0) {
      return localize(11217, null, passed, runSoFar, percent.toPrecision(3));
    } else {
      return localize(11218, null, passed, runSoFar, percent.toPrecision(3), skipped);
    }
  }
};

// out-build/vs/workbench/contrib/testing/browser/testingExplorerView.js
var ErrorRenderer_1;
var TestItemRenderer_1;
var LastFocusState;
(function(LastFocusState2) {
  LastFocusState2[LastFocusState2["Input"] = 0] = "Input";
  LastFocusState2[LastFocusState2["Tree"] = 1] = "Tree";
})(LastFocusState || (LastFocusState = {}));
var $i_b = class $i_b2 extends $_ob {
  get focusedTreeElements() {
    return this.viewModel.tree.getFocus().filter($Hg);
  }
  constructor(options3, contextMenuService, keybindingService, configurationService, instantiationService, viewDescriptorService, contextKeyService, openerService, themeService, fc, telemetryService, hoverService, gc, hc, ic, jc) {
    super(options3, keybindingService, contextMenuService, configurationService, contextKeyService, viewDescriptorService, instantiationService, openerService, themeService, telemetryService, hoverService);
    this.fc = fc;
    this.gc = gc;
    this.hc = hc;
    this.ic = ic;
    this.jc = jc;
    this.f = this.B(new $4c());
    this.ac = this.B(new $4c());
    this.bc = this.B(new $4c());
    this.cc = this.B(new $4c());
    this.dc = { width: 0, height: 0 };
    this.ec = 0;
    const relayout = this.B(new $8h(() => this.X(), 1));
    this.B(this.onDidChangeViewWelcomeState(() => {
      if (!this.shouldShowWelcome()) {
        relayout.schedule();
      }
    }));
    this.B(Event2.any(jc.onDidChange, gc.onDidChange)(() => {
      this.$b();
    }));
    this.B(fc.collection.onBusyProvidersChange((busy) => {
      this.qc(busy);
    }));
    this.B(gc.onDidChange(() => this.$b()));
  }
  shouldShowWelcome() {
    return this.viewModel?.welcomeExperience === 1;
  }
  focus() {
    super.focus();
    if (this.ec === 1) {
      this.viewModel.tree.domFocus();
    } else {
      this.bc.value?.focus();
    }
  }
  /**
   * Gets include/exclude items in the tree, based either on visible tests
   * or a use selection. If a profile is given, only tests in that profile
   * are collected. If a bitset is given, any test that can run in that
   * bitset is collected.
   */
  getTreeIncludeExclude(profileOrBitset, withinItems, filterToType = "visible") {
    const projection = this.viewModel.projection.value;
    if (!projection) {
      return { include: [], exclude: [] };
    }
    const include = /* @__PURE__ */ new Set();
    const exclude = [];
    const runnableWithProfileOrBitset = /* @__PURE__ */ new Map();
    const isRunnableWithProfileOrBitset = (item) => {
      let value = runnableWithProfileOrBitset.get(item);
      if (value === void 0) {
        value = typeof profileOrBitset === "number" ? !!this.gc.getDefaultProfileForTest(profileOrBitset, item) : $xTb(profileOrBitset, item);
        runnableWithProfileOrBitset.set(item, value);
      }
      return value;
    };
    const attempt = (element, alreadyIncluded) => {
      if (!(element instanceof $l$b) || !this.viewModel.tree.hasElement(element)) {
        return;
      }
      const inTree = this.viewModel.tree.getNode(element);
      if (!inTree.visible) {
        if (alreadyIncluded) {
          exclude.push(element.test);
        }
        return;
      }
      const visibleRunnableChildren = inTree.children.filter((c) => c.visible && c.element instanceof $l$b && isRunnableWithProfileOrBitset(c.element.test)).length;
      if (
        // If it's not already included...
        !alreadyIncluded && isRunnableWithProfileOrBitset(element.test) && (visibleRunnableChildren === 0 || visibleRunnableChildren * 2 >= inTree.children.length) && visibleRunnableChildren !== 1
      ) {
        include.add(element.test);
        alreadyIncluded = true;
      }
      for (const child of element.children) {
        attempt(child, alreadyIncluded);
      }
    };
    if (filterToType === "selected") {
      const sel = this.viewModel.tree.getSelection().filter($Hg);
      if (sel.length) {
        L: for (const node of sel) {
          if (node instanceof $l$b) {
            for (let i2 = node; i2; i2 = i2.parent) {
              if (include.has(i2.test)) {
                continue L;
              }
            }
            include.add(node.test);
            node.children.forEach((c) => attempt(c, true));
          }
        }
        return { include: [...include], exclude };
      }
    }
    for (const root of withinItems || this.fc.collection.rootItems) {
      const element = projection.getElementByTestId(root.item.extId);
      if (!element) {
        continue;
      }
      if (typeof profileOrBitset === "object" && !$xTb(profileOrBitset, root)) {
        continue;
      }
      if (!this.viewModel.tree.hasElement(element)) {
        const visibleChildren = [...element.children].reduce((acc, c) => this.viewModel.tree.hasElement(c) && this.viewModel.tree.getNode(c).visible ? acc + 1 : acc, 0);
        if (element.children.size > 0 && visibleChildren * 2 >= element.children.size) {
          include.add(element.test);
          element.children.forEach((c) => attempt(c, true));
        } else {
          element.children.forEach((c) => attempt(c, false));
        }
      } else {
        attempt(element, false);
      }
    }
    return { include: [...include], exclude };
  }
  render() {
    super.render();
    this.B($iKb({
      name: "testingExplorerView",
      focusNotifiers: [this],
      focusNextWidget: () => {
        if (!this.viewModel.tree.isDOMFocused()) {
          this.viewModel.tree.domFocus();
        }
      },
      focusPreviousWidget: () => {
        if (this.viewModel.tree.isDOMFocused()) {
          this.bc.value?.focus();
        }
      }
    }));
  }
  /**
   * @override
   */
  W(container2) {
    super.W(container2);
    this.j = $bk(container2, $(".test-explorer"));
    this.m = $bk(this.j, $(".test-explorer-header"));
    this.f.value = this.pc();
    const messagesContainer = $bk(this.m, $(".result-summary-container"));
    this.B(this.Db.createInstance(ResultSummaryView, messagesContainer));
    const listContainer = $bk(this.j, $(".test-explorer-tree"));
    this.viewModel = this.Db.createInstance(TestingExplorerViewModel, listContainer, this.onDidChangeBodyVisibility);
    this.B(this.viewModel.tree.onDidFocus(
      () => this.ec = 1
      /* LastFocusState.Tree */
    ));
    this.B(this.viewModel.onChangeWelcomeVisibility(() => this.eb.fire()));
    this.B(this.viewModel);
    this.eb.fire();
  }
  /** @override  */
  getActionViewItem(action, options3) {
    switch (action.id) {
      case "workbench.actions.treeView.testExplorer.filter":
        this.bc.value = this.Db.createInstance($e_b, action, options3);
        this.cc.value = this.bc.value.onDidFocus(
          () => this.ec = 0
          /* LastFocusState.Input */
        );
        return this.bc.value;
      case "testing.runSelected":
        return this.mc(2, action, options3);
      case "testing.debugSelected":
        return this.mc(4, action, options3);
      case "testing.startContinuousRun":
      case "testing.stopContinuousRun":
        return this.oc(action, options3);
      default:
        return super.getActionViewItem(action, options3);
    }
  }
  /** @inheritdoc */
  lc(group2) {
    const profileActions = [];
    let participatingGroups = 0;
    let hasConfigurable = false;
    const defaults = this.gc.getGroupDefaultProfiles(group2);
    for (const { profiles: profiles2, controller } of this.gc.all()) {
      let hasAdded = false;
      for (const profile of profiles2) {
        if (profile.group !== group2) {
          continue;
        }
        if (!hasAdded) {
          hasAdded = true;
          participatingGroups++;
          profileActions.push(new $Um(`${controller.id}.$root`, controller.label.get(), void 0, false));
        }
        hasConfigurable = hasConfigurable || profile.hasConfigurationHandler;
        profileActions.push(new $Um(`${controller.id}.${profile.profileId}`, defaults.includes(profile) ? localize(11189, null, profile.label) : profile.label, void 0, void 0, () => {
          const { include, exclude } = this.getTreeIncludeExclude(profile);
          this.fc.runResolvedTests({
            exclude: exclude.map((e) => e.item.extId),
            group: profile.group,
            targets: [{
              profileId: profile.profileId,
              controllerId: profile.controllerId,
              testIds: include.map((i2) => i2.item.extId)
            }]
          });
        }));
      }
    }
    const contextKeys = [];
    if (group2 === 2) {
      contextKeys.push(["testing.profile.context.group", "run"]);
    }
    if (group2 === 4) {
      contextKeys.push(["testing.profile.context.group", "debug"]);
    }
    if (group2 === 8) {
      contextKeys.push(["testing.profile.context.group", "coverage"]);
    }
    const key2 = this.Bb.createOverlay(contextKeys);
    const menu = this.ic.getMenuActions($bJ.TestProfilesContext, key2);
    const menuActions = $P$(menu);
    const postActions = [];
    if (profileActions.length > 1) {
      postActions.push(new $Um("selectDefaultTestConfigurations", localize(11190, null), void 0, void 0, () => this.hc.executeCommand("testing.selectDefaultTestProfiles", group2)));
    }
    if (hasConfigurable) {
      postActions.push(new $Um("configureTestProfiles", localize(11191, null), void 0, void 0, () => this.hc.executeCommand("testing.configureProfile", group2)));
    }
    return menuActions.length > 0 ? $Wm.join(profileActions, menuActions, postActions) : $Wm.join(profileActions, postActions);
  }
  /**
   * @override
   */
  saveState() {
    this.bc.value?.saveState();
    super.saveState();
  }
  mc(group2, defaultAction, options3) {
    const dropdownActions = this.lc(group2);
    if (dropdownActions.length < 2) {
      return super.getActionViewItem(defaultAction, options3);
    }
    const primaryAction = this.Db.createInstance($fJ, {
      id: defaultAction.id,
      title: defaultAction.label,
      icon: group2 === 2 ? $b0b : $c0b
    }, void 0, void 0, void 0, void 0);
    return this.Db.createInstance($isb, primaryAction, this.nc(), dropdownActions, "", options3);
  }
  nc() {
    return new $Um("selectRunConfig", localize(11192, null), "codicon-chevron-down", true);
  }
  oc(defaultAction, options3) {
    const allProfiles = [...Iterable.flatMap(this.gc.all(), (cr) => {
      if (this.fc.collection.getNodeById(cr.controller.id)?.children.size) {
        return Iterable.filter(cr.profiles, (p) => p.supportsContinuousRun);
      }
      return Iterable.empty();
    })];
    if (allProfiles.length <= 1) {
      return super.getActionViewItem(defaultAction, options3);
    }
    const primaryAction = this.Db.createInstance($fJ, {
      id: defaultAction.id,
      title: defaultAction.label,
      icon: defaultAction.id === "testing.startContinuousRun" ? $n0b : $o0b
    }, void 0, void 0, void 0, void 0);
    const dropdownActions = [];
    const groups = $a(allProfiles, (p) => p.group);
    const crService = this.jc;
    for (const group2 of [
      2,
      4,
      8
      /* TestRunProfileBitset.Coverage */
    ]) {
      const profiles2 = groups[group2];
      if (!profiles2) {
        continue;
      }
      if (Object.keys(groups).length > 1) {
        dropdownActions.push({
          id: `${group2}.label`,
          label: $oQ[group2],
          enabled: false,
          class: void 0,
          tooltip: $oQ[group2],
          run: () => {
          }
        });
      }
      for (const profile of profiles2) {
        dropdownActions.push({
          id: `${group2}.${profile.profileId}`,
          label: profile.label,
          enabled: true,
          class: void 0,
          tooltip: profile.label,
          checked: crService.isEnabledForProfile(profile),
          run: () => crService.isEnabledForProfile(profile) ? crService.stopProfile(profile) : crService.start([profile])
        });
      }
    }
    return this.Db.createInstance($isb, primaryAction, this.nc(), dropdownActions, "", options3);
  }
  pc() {
    const bar = new $LZ(this.m, {
      actionViewItemProvider: (action, options3) => this.getActionViewItem(action, options3),
      triggerKeys: { keyDown: false, keys: [] }
    });
    bar.push(new $Um(
      "workbench.actions.treeView.testExplorer.filter"
      /* TestCommandId.FilterAction */
    ));
    bar.getContainer().classList.add("testing-filter-action-bar");
    return bar;
  }
  qc(busy) {
    if (!busy && this.ac) {
      this.ac.clear();
    } else if (busy && !this.ac.value) {
      this.ac.value = this.Db.createInstance($XJ, { location: this.Wb() });
    }
  }
  /**
   * @override
   */
  X(height = this.dc.height, width2 = this.dc.width) {
    super.X(height, width2);
    this.dc.height = height;
    this.dc.width = width2;
    this.j.style.height = `${height}px`;
    this.viewModel?.layout(height - this.m.clientHeight, width2);
    this.bc.value?.layout(width2);
  }
};
$i_b = __decorate([
  __param(1, $50),
  __param(2, $Ty),
  __param(3, $kl),
  __param(4, $Pk),
  __param(5, $$M),
  __param(6, $on),
  __param(7, $O4),
  __param(8, $gs),
  __param(9, $nTb),
  __param(10, $zv),
  __param(11, $5$),
  __param(12, $wTb),
  __param(13, $sn),
  __param(14, $cJ),
  __param(15, $i$b)
], $i_b);
var SUMMARY_RENDER_INTERVAL = 200;
var ResultSummaryView = class ResultSummaryView2 extends $3c {
  constructor(C, D, F, G, configurationService, instantiationService, hoverService) {
    super();
    this.C = C;
    this.D = D;
    this.F = F;
    this.G = G;
    this.f = false;
    this.w = this.B(new $4c());
    this.y = this.B(new $8h(() => this.H(), SUMMARY_RENDER_INTERVAL));
    this.z = h("div.result-summary", [
      h("div@status"),
      h("div@count"),
      h("div@count"),
      h("span"),
      h("duration@duration"),
      h("a@rerun")
    ]);
    this.j = configurationService.getValue(
      "testing.countBadge"
      /* TestingConfigKeys.CountBadge */
    );
    this.B(D.onResultsChanged(this.H, this));
    this.B(configurationService.onDidChangeConfiguration((e) => {
      if (e.affectsConfiguration(
        "testing.countBadge"
        /* TestingConfigKeys.CountBadge */
      )) {
        this.j = configurationService.getValue(
          "testing.countBadge"
          /* TestingConfigKeys.CountBadge */
        );
        this.H();
      }
    }));
    this.u = this.B(hoverService.setupManagedHover($JZ("mouse"), this.z.count, ""));
    const ab = this.B(new $LZ(this.z.rerun, {
      actionViewItemProvider: (action, options3) => $X$(instantiationService, action, options3)
    }));
    ab.push(instantiationService.createInstance($fJ, { ...new $6$b().desc, icon: $a0b }, { ...new $7$b().desc, icon: $d0b }, {}, void 0, void 0), { icon: true, label: false });
    this.H();
  }
  H() {
    const { results } = this.D;
    const { count, root, status, duration, rerun } = this.z;
    if (!results.length) {
      if (this.f) {
        root.remove();
        this.f = false;
      }
      this.C.innerText = localize(11193, null);
      this.w.clear();
      return;
    }
    const live = results.filter((r2) => !r2.completedAt);
    let counts;
    if (live.length) {
      status.className = ThemeIcon.asClassName($ds);
      counts = $g_b(true, live);
      this.y.schedule();
      const last = live[live.length - 1];
      duration.textContent = formatDuration(Date.now() - last.startedAt);
      rerun.style.display = "none";
    } else {
      const last = results[0];
      const dominantState = $ab($DQ, (s) => last.counts[s] > 0 ? s : void 0);
      status.className = ThemeIcon.asClassName($u0b.get(
        dominantState ?? 0
        /* TestResultState.Unset */
      ));
      counts = $g_b(false, [last]);
      duration.textContent = last instanceof $RQ ? formatDuration(last.completedAt - last.startedAt) : "";
      rerun.style.display = "block";
    }
    count.textContent = `${counts.passed}/${counts.totalWillBeRun}`;
    this.u.update($h_b(counts));
    this.I(counts);
    if (!this.f) {
      $$i(this.C);
      this.C.appendChild(root);
      this.f = true;
    }
  }
  I(countSummary) {
    if (countSummary && this.j !== "off" && countSummary[this.j] !== 0) {
      if (this.m instanceof $wqb && this.m.number === countSummary[this.j]) {
        return;
      }
      this.m = new $wqb(countSummary[this.j], (num) => this.J(this.j, num));
    } else if (this.G.isEnabled()) {
      if (this.m instanceof $xqb && this.m.icon === $p0b) {
        return;
      }
      this.m = new $xqb($p0b, () => localize(11194, null));
    } else {
      if (!this.m) {
        return;
      }
      this.m = void 0;
    }
    this.w.value = this.m && this.F.showViewActivity("workbench.view.testing", { badge: this.m });
  }
  J(countBadgeType, count) {
    switch (countBadgeType) {
      case "passed":
        return localize(11195, null, count);
      case "skipped":
        return localize(11196, null, count);
      default:
        return localize(11197, null, count);
    }
  }
};
ResultSummaryView = __decorate([
  __param(1, $FTb),
  __param(2, $vqb),
  __param(3, $i$b),
  __param(4, $kl),
  __param(5, $Pk),
  __param(6, $5$)
], ResultSummaryView);
var WelcomeExperience;
(function(WelcomeExperience2) {
  WelcomeExperience2[WelcomeExperience2["None"] = 0] = "None";
  WelcomeExperience2[WelcomeExperience2["ForWorkspace"] = 1] = "ForWorkspace";
  WelcomeExperience2[WelcomeExperience2["ForDocument"] = 2] = "ForDocument";
})(WelcomeExperience || (WelcomeExperience = {}));
var TestingExplorerViewModel = class TestingExplorerViewModel2 extends $3c {
  get viewMode() {
    return this.m.get() ?? "true";
  }
  set viewMode(newMode) {
    if (newMode === this.m.get()) {
      return;
    }
    this.m.set(newMode);
    this.bb();
    this.M.store(
      "testing.viewMode",
      newMode,
      1,
      1
      /* StorageTarget.MACHINE */
    );
  }
  get viewSorting() {
    return this.u.get() ?? "status";
  }
  set viewSorting(newSorting) {
    if (newSorting === this.u.get()) {
      return;
    }
    this.u.set(newSorting);
    this.tree.resort(null);
    this.M.store(
      "testing.viewSorting",
      newSorting,
      1,
      1
      /* StorageTarget.MACHINE */
    );
  }
  constructor(listContainer, onDidChangeVisibility, configurationService, editorService, editorGroupsService, F, G, H, I, J, M, N, O, P, Q, R, commandService) {
    super();
    this.F = F;
    this.G = G;
    this.H = H;
    this.I = I;
    this.J = J;
    this.M = M;
    this.N = N;
    this.O = O;
    this.P = P;
    this.Q = Q;
    this.R = R;
    this.projection = this.B(new $4c());
    this.j = new $4c();
    this.m = TestingContextKeys.viewMode.bindTo(this.N);
    this.u = TestingContextKeys.viewSorting.bindTo(this.N);
    this.w = new $ze();
    this.y = new TestExplorerActionRunner(() => this.tree.getSelection().filter($Hg));
    this.z = this.B(new $jTb({
      key: "testing.treeState",
      scope: 1,
      target: 1
    }, this.M));
    this.D = false;
    this.onChangeWelcomeVisibility = this.w.event;
    this.welcomeExperience = 0;
    this.D = !!I.reveal.get();
    this.C = this.B(J.createInstance(NoTestsForDocumentWidget, listContainer));
    this.m.set(this.M.get(
      "testing.viewMode",
      1,
      "true"
      /* TestExplorerViewMode.Tree */
    ));
    this.u.set(this.M.get(
      "testing.viewSorting",
      1,
      "location"
      /* TestExplorerViewSorting.ByLocation */
    ));
    this.Y();
    this.f = this.J.createInstance(TestsFilter, H.collection);
    this.tree = J.createInstance($r$b, "Test Explorer List", listContainer, new ListDelegate(), [
      J.createInstance(TestItemRenderer, this.y),
      J.createInstance(ErrorRenderer)
    ], {
      identityProvider: J.createInstance(IdentityProvider),
      hideTwistiesOfChildlessElements: false,
      sorter: J.createInstance(TreeSorter, this),
      keyboardNavigationLabelProvider: J.createInstance(TreeKeyboardNavigationLabelProvider),
      accessibilityProvider: J.createInstance(ListAccessibilityProvider),
      filter: this.f,
      findWidgetEnabled: false
    });
    const collapseStateSaver = this.B(new $8h(() => {
      const state = this.tree.getOptimizedViewState(this.z.get({}));
      const projection = this.projection.value;
      if (projection) {
        projection.lastState = state;
      }
    }, 3e3));
    this.B(this.tree.onDidChangeCollapseState((evt) => {
      if (evt.node.element instanceof $l$b) {
        if (!evt.node.collapsed) {
          this.projection.value?.expandElement(evt.node.element, evt.deep ? Infinity : 0);
        }
        collapseStateSaver.schedule();
      }
    }));
    this.B(this.R.onDidChange((testId) => {
      if (testId) {
        const elem = this.projection.value?.getElementByTestId(testId);
        this.tree.resort(elem?.parent && this.tree.hasElement(elem.parent) ? elem.parent : null, false);
      }
    }));
    this.B(onDidChangeVisibility((visible) => {
      if (visible) {
        this.Z();
      }
    }));
    this.B(this.tree.onContextMenu((e) => this.W(e)));
    this.B(Event2.any(I.text.onDidChange, I.fuzzy.onDidChange, H.excluded.onTestExclusionsChanged)(() => {
      if (!I.text.value) {
        return this.tree.refilter();
      }
      const items = this.f.lastIncludedTests = /* @__PURE__ */ new Set();
      this.tree.refilter();
      this.f.lastIncludedTests = void 0;
      for (const test of items) {
        this.tree.expandTo(test);
      }
    }));
    this.B(this.tree.onDidOpen((e) => {
      if (!(e.element instanceof $l$b)) {
        return;
      }
      I.didSelectTestInExplorer(e.element.test.item.extId);
      if (!e.element.children.size && e.element.test.item.uri) {
        if (!this.U(e.element)) {
          commandService.executeCommand("vscode.revealTest", e.element.test.item.extId, {
            openToSide: e.sideBySide,
            preserveFocus: true
          });
        }
      }
    }));
    this.B(this.tree);
    this.B(this.onChangeWelcomeVisibility((e) => {
      this.C.setVisible(
        e === 2
        /* WelcomeExperience.ForDocument */
      );
    }));
    this.B($aj(this.tree.getHTMLElement(), "keydown", (evt) => {
      if (evt.equals(
        3
        /* KeyCode.Enter */
      )) {
        this.X(evt);
      } else if ($u1.mightProducePrintableCharacter(evt)) {
        I.text.value = evt.browserEvent.key;
        I.focusInput();
      }
    }));
    this.B($td((reader) => {
      this.S(I.reveal.read(reader), void 0, false);
    }));
    this.B(onDidChangeVisibility((visible) => {
      if (visible) {
        I.focusInput();
      }
    }));
    let followRunningTests = $w9b(
      configurationService,
      "testing.followRunningTest"
      /* TestingConfigKeys.FollowRunningTest */
    );
    this.B(configurationService.onDidChangeConfiguration((e) => {
      if (e.affectsConfiguration(
        "testing.followRunningTest"
        /* TestingConfigKeys.FollowRunningTest */
      )) {
        followRunningTests = $w9b(
          configurationService,
          "testing.followRunningTest"
          /* TestingConfigKeys.FollowRunningTest */
        );
      }
    }));
    let alwaysRevealTestAfterStateChange = $w9b(
      configurationService,
      "testing.alwaysRevealTestOnStateChange"
      /* TestingConfigKeys.AlwaysRevealTestOnStateChange */
    );
    this.B(configurationService.onDidChangeConfiguration((e) => {
      if (e.affectsConfiguration(
        "testing.alwaysRevealTestOnStateChange"
        /* TestingConfigKeys.AlwaysRevealTestOnStateChange */
      )) {
        alwaysRevealTestAfterStateChange = $w9b(
          configurationService,
          "testing.alwaysRevealTestOnStateChange"
          /* TestingConfigKeys.AlwaysRevealTestOnStateChange */
        );
      }
    }));
    this.B(O.onTestChanged((evt) => {
      if (!followRunningTests) {
        return;
      }
      if (evt.reason !== 1) {
        return;
      }
      if (this.tree.selectionSize > 1) {
        return;
      }
      if (evt.item.ownComputedState !== 2 && !(evt.previousState === 1 && $zQ(evt.item.ownComputedState))) {
        return;
      }
      this.S(evt.item.item.extId, alwaysRevealTestAfterStateChange, false);
    }));
    this.B(O.onResultsChanged(() => {
      this.tree.resort(null);
    }));
    this.B(this.Q.onDidChange(() => {
      this.tree.rerender();
    }));
    const allOpenEditorInputs = $Dd(this, editorService.onDidEditorsChange, () => new Set(editorGroupsService.groups.flatMap((g) => g.editors).map((e) => e.resource).filter($Hg)));
    const activeResource = $Dd(this, editorService.onDidActiveEditorChange, () => {
      if (editorService.activeEditor instanceof $fub) {
        return editorService.activeEditor.primary.resource;
      } else {
        return editorService.activeEditor?.resource;
      }
    });
    const filterText = $Dd(this.I.text.onDidChange, () => this.I.text);
    this.B($td((reader) => {
      filterText.read(reader);
      if (this.I.isFilteringFor(
        "@openedFiles"
        /* TestFilterTerm.OpenedFiles */
      )) {
        this.f.filterToDocumentUri([...allOpenEditorInputs.read(reader)]);
      } else {
        this.f.filterToDocumentUri([activeResource.read(reader)].filter($Hg));
      }
      if (this.I.isFilteringFor(
        "@doc"
        /* TestFilterTerm.CurrentDoc */
      ) || this.I.isFilteringFor(
        "@openedFiles"
        /* TestFilterTerm.OpenedFiles */
      )) {
        this.tree.refilter();
      }
    }));
    this.B(this.M.onWillSaveState(({ reason }) => {
      if (reason === WillSaveStateReason.SHUTDOWN) {
        this.z.store(this.tree.getOptimizedViewState());
      }
    }));
  }
  /**
   * Re-layout the tree.
   */
  layout(height, width2) {
    this.tree.layout(height, width2);
  }
  /**
   * Tries to reveal by extension ID. Queues the request if the extension
   * ID is not currently available.
   */
  S(id2, expand = true, focus = true) {
    if (!id2) {
      this.D = false;
      return;
    }
    const projection = this.Z();
    let expandToLevel = 0;
    const idPath = [...$mQ.fromString(id2).idsFromRoot()];
    for (let i2 = idPath.length - 1; i2 >= expandToLevel; i2--) {
      const element = projection.getElementByTestId(idPath[i2].toString());
      if (!element || !this.tree.hasElement(element)) {
        continue;
      }
      if (i2 < idPath.length - 1) {
        if (expand) {
          this.tree.expand(element);
          expandToLevel = i2 + 1;
          i2 = idPath.length - 1;
          continue;
        }
      }
      let focusTarget = element;
      for (let n = element; n instanceof $l$b; n = n.parent) {
        if (n.test && this.H.excluded.contains(n.test)) {
          this.I.toggleFilteringFor("@hidden", true);
          break;
        }
        if (!expand && (this.tree.hasElement(n) && this.tree.isCollapsed(n))) {
          focusTarget = n;
        }
      }
      this.I.reveal.set(void 0, void 0);
      this.D = false;
      if (focus) {
        this.tree.domFocus();
      }
      if (this.tree.getRelativeTop(focusTarget) === null) {
        this.tree.reveal(focusTarget, 0.5);
      }
      this.j.value = $Xh(() => {
        this.tree.setFocus([focusTarget]);
        this.tree.setSelection([focusTarget]);
      }, 1);
      return;
    }
    this.D = true;
  }
  /**
   * Collapse all items in the tree.
   */
  async collapseAll() {
    this.tree.collapseAll();
  }
  /**
   * Tries to peek the first test error, if the item is in a failed state.
   */
  U(item) {
    const lookup = item.test && this.O.getStateById(item.test.item.extId);
    return lookup && lookup[1].tasks.some((s) => $yQ(s.state)) ? this.P.tryPeekFirstError(lookup[0], lookup[1], { preserveFocus: true }) : false;
  }
  W(evt) {
    const element = evt.element;
    if (!(element instanceof $l$b)) {
      return;
    }
    const { actions } = getActionableElementActions(this.N, this.F, this.H, this.R, this.Q, element);
    this.G.showContextMenu({
      getAnchor: () => evt.anchor,
      getActions: () => actions.secondary,
      getActionsContext: () => element,
      actionRunner: this.y
    });
  }
  X(evt) {
    const focused = this.tree.getFocus();
    const selected = this.tree.getSelection();
    let targeted;
    if (focused.length === 1 && selected.includes(focused[0])) {
      evt.browserEvent?.preventDefault();
      targeted = selected;
    } else {
      targeted = focused;
    }
    const toRun = targeted.filter((e) => e instanceof $l$b);
    if (toRun.length) {
      this.H.runTests({
        group: 2,
        tests: toRun.map((t) => t.test)
      });
    }
  }
  Y() {
    const shouldShowWelcome = this.H.collection.busyProviders === 0 && $oTb(this.H.collection);
    const welcomeExperience = shouldShowWelcome ? this.I.isFilteringFor(
      "@doc"
      /* TestFilterTerm.CurrentDoc */
    ) ? 2 : 1 : 0;
    if (welcomeExperience !== this.welcomeExperience) {
      this.welcomeExperience = welcomeExperience;
      this.w.fire(welcomeExperience);
    }
  }
  Z() {
    return this.projection.value ?? this.bb();
  }
  bb() {
    this.projection.clear();
    const lastState = this.z.get({});
    if (this.m.get() === "list") {
      this.projection.value = this.J.createInstance($q$b, lastState);
    } else {
      this.projection.value = this.J.createInstance($s$b, lastState);
    }
    const scheduler = this.B(new $8h(() => this.cb(), 200));
    this.projection.value.onUpdate(() => {
      if (!scheduler.isScheduled()) {
        scheduler.schedule();
      }
    });
    this.cb();
    return this.projection.value;
  }
  cb() {
    this.Y();
    this.projection.value?.applyTo(this.tree);
    this.tree.refilter();
    if (this.D) {
      this.S(this.I.reveal.get());
    }
  }
  /**
   * Gets the selected tests from the tree.
   */
  getSelectedTests() {
    return this.tree.getSelection();
  }
};
TestingExplorerViewModel = __decorate([
  __param(2, $kl),
  __param(3, $mJ),
  __param(4, $iJ),
  __param(5, $cJ),
  __param(6, $50),
  __param(7, $nTb),
  __param(8, $60b),
  __param(9, $Pk),
  __param(10, $jv),
  __param(11, $on),
  __param(12, $FTb),
  __param(13, $B0b),
  __param(14, $wTb),
  __param(15, $i$b),
  __param(16, $sn)
], TestingExplorerViewModel);
var FilterResult;
(function(FilterResult2) {
  FilterResult2[FilterResult2["Exclude"] = 0] = "Exclude";
  FilterResult2[FilterResult2["Inherit"] = 1] = "Inherit";
  FilterResult2[FilterResult2["Include"] = 2] = "Include";
})(FilterResult || (FilterResult = {}));
var hasNodeInOrParentOfUri = (collection, ident, testUri, fromNode) => {
  const queue = [fromNode ? [fromNode] : collection.rootIds];
  while (queue.length) {
    for (const id2 of queue.pop()) {
      const node = collection.getNodeById(id2);
      if (!node) {
        continue;
      }
      if (!node.item.uri || !ident.extUri.isEqualOrParent(testUri, node.item.uri)) {
        continue;
      }
      if (node.item.range || node.expand === 1) {
        return true;
      }
      queue.push(node.children);
    }
  }
  return false;
};
var TestsFilter = class TestsFilter2 {
  constructor(f, j, k, l) {
    this.f = f;
    this.j = j;
    this.k = k;
    this.l = l;
    this.d = [];
  }
  /**
   * @inheritdoc
   */
  filter(element) {
    if (element instanceof $m$b) {
      return 1;
    }
    if (element.test && !this.j.isFilteringFor(
      "@hidden"
      /* TestFilterTerm.Hidden */
    ) && this.k.excluded.contains(element.test)) {
      return 0;
    }
    switch (Math.min(this.u(element), this.q(element), this.o(element), this.m(element))) {
      case 0:
        return 0;
      case 2:
        this.lastIncludedTests?.add(element);
        return 1;
      default:
        return 2;
    }
  }
  filterToDocumentUri(uris) {
    this.d = [...uris];
  }
  m(element) {
    if (!this.j.includeTags.size && !this.j.excludeTags.size) {
      return 2;
    }
    return (this.j.includeTags.size ? element.test.item.tags.some((t) => this.j.includeTags.has(t)) : true) && element.test.item.tags.every((t) => !this.j.excludeTags.has(t)) ? 2 : 1;
  }
  o(element) {
    if (this.j.isFilteringFor(
      "@failed"
      /* TestFilterTerm.Failed */
    )) {
      return $yQ(element.state) ? 2 : 1;
    }
    if (this.j.isFilteringFor(
      "@executed"
      /* TestFilterTerm.Executed */
    )) {
      return element.state !== 0 ? 2 : 1;
    }
    return 2;
  }
  q(element) {
    if (this.d.length === 0) {
      return 2;
    }
    if (!this.j.isFilteringFor(
      "@doc"
      /* TestFilterTerm.CurrentDoc */
    ) && !this.j.isFilteringFor(
      "@openedFiles"
      /* TestFilterTerm.OpenedFiles */
    ) || !(element instanceof $l$b)) {
      return 2;
    }
    if (this.d.some((uri) => hasNodeInOrParentOfUri(this.f, this.l, uri, element.test.item.extId))) {
      return 2;
    }
    return 1;
  }
  u(element) {
    if (this.j.globList.length === 0) {
      return 2;
    }
    const fuzzy = this.j.fuzzy.value;
    for (let e = element; e; e = e.parent) {
      let included = this.j.globList[0].include === false ? 2 : 1;
      const data = e.test.item.label.toLowerCase();
      for (const { include, text: text2 } of this.j.globList) {
        if (fuzzy ? $pg(data, text2) : data.includes(text2)) {
          included = include ? 2 : 0;
        }
      }
      if (included !== 1) {
        return included;
      }
    }
    return 1;
  }
};
TestsFilter = __decorate([
  __param(1, $60b),
  __param(2, $nTb),
  __param(3, $vl)
], TestsFilter);
var TreeSorter = class {
  constructor(d) {
    this.d = d;
  }
  compare(a, b) {
    if (a instanceof $m$b || b instanceof $m$b) {
      return (a instanceof $m$b ? -1 : 0) + (b instanceof $m$b ? 1 : 0);
    }
    const durationDelta = (b.duration || 0) - (a.duration || 0);
    if (this.d.viewSorting === "duration" && durationDelta !== 0) {
      return durationDelta;
    }
    const stateDelta = $BQ(a.state, b.state);
    if (this.d.viewSorting === "status" && stateDelta !== 0) {
      return stateDelta;
    }
    let inSameLocation = false;
    if (a instanceof $l$b && b instanceof $l$b && a.test.item.uri && b.test.item.uri && a.test.item.uri.toString() === b.test.item.uri.toString() && a.test.item.range && b.test.item.range) {
      inSameLocation = true;
      const delta = a.test.item.range.startLineNumber - b.test.item.range.startLineNumber;
      if (delta !== 0) {
        return delta;
      }
    }
    const sa = a.test.item.sortText;
    const sb = b.test.item.sortText;
    return inSameLocation && !sa && !sb ? 0 : (sa || a.test.item.label).localeCompare(sb || b.test.item.label);
  }
};
var NoTestsForDocumentWidget = class NoTestsForDocumentWidget2 extends $3c {
  constructor(container2, filterState) {
    super();
    const el = this.f = $bk(container2, $(".testing-no-test-placeholder"));
    const emptyParagraph = $bk(el, $("p"));
    emptyParagraph.innerText = localize(11198, null);
    const buttonLabel = localize(11199, null);
    const button = this.B(new $k2(el, { title: buttonLabel, ...$q$ }));
    button.label = buttonLabel;
    this.B(button.onDidClick(() => filterState.toggleFilteringFor("@doc", false)));
  }
  setVisible(isVisible) {
    this.f.classList.toggle("visible", isVisible);
  }
};
NoTestsForDocumentWidget = __decorate([
  __param(1, $60b)
], NoTestsForDocumentWidget);
var TestExplorerActionRunner = class extends $Vm {
  constructor(j) {
    super();
    this.j = j;
  }
  async u(action, context) {
    if (!(action instanceof $fJ)) {
      return super.u(action, context);
    }
    const selection = this.j();
    const contextIsSelected = selection.some((s) => s === context);
    const actualContext = contextIsSelected ? selection : [context];
    const actionable = actualContext.filter((t) => t instanceof $l$b);
    await action.run(...actionable);
  }
};
var getLabelForTestTreeElement = (element) => {
  let label3 = $uTb(element.description || element.test.item.label, element.state);
  if (element instanceof $l$b) {
    if (element.duration !== void 0) {
      label3 = localize(11200, null, label3, formatDuration(element.duration));
    }
    if (element.retired) {
      label3 = localize(11201, null, label3);
    }
  }
  return label3;
};
var ListAccessibilityProvider = class {
  getWidgetAriaLabel() {
    return localize(11202, null);
  }
  getAriaLabel(element) {
    return element instanceof $m$b ? element.description : getLabelForTestTreeElement(element);
  }
};
var TreeKeyboardNavigationLabelProvider = class {
  getKeyboardNavigationLabel(element) {
    return element instanceof $m$b ? element.message : element.test.item.label;
  }
};
var ListDelegate = class {
  getHeight(element) {
    return element instanceof $m$b ? 17 + 10 : 22;
  }
  getTemplateId(element) {
    if (element instanceof $m$b) {
      return ErrorRenderer.ID;
    }
    return TestItemRenderer.ID;
  }
};
var IdentityProvider = class {
  getId(element) {
    return element.treeId;
  }
};
var ErrorRenderer = class ErrorRenderer2 {
  static {
    ErrorRenderer_1 = this;
  }
  static {
    this.ID = "error";
  }
  constructor(f, instantionService) {
    this.f = f;
    this.d = instantionService.createInstance($Q_, {});
  }
  get templateId() {
    return ErrorRenderer_1.ID;
  }
  renderTemplate(container2) {
    const label3 = $bk(container2, $(".error"));
    return { label: label3, disposable: new $2c() };
  }
  renderElement({ element }, _, data) {
    $$i(data.label);
    if (typeof element.message === "string") {
      data.label.innerText = element.message;
    } else {
      const result = this.d.render(element.message, { inline: true });
      data.label.appendChild(result.element);
    }
    data.disposable.add(this.f.setupManagedHover($JZ("mouse"), data.label, element.description));
  }
  disposeTemplate(data) {
    data.disposable.dispose();
  }
};
ErrorRenderer = ErrorRenderer_1 = __decorate([
  __param(0, $5$),
  __param(1, $Pk)
], ErrorRenderer);
var TestItemRenderer = class TestItemRenderer2 extends $3c {
  static {
    TestItemRenderer_1 = this;
  }
  static {
    this.ID = "testItem";
  }
  constructor(f, j, m, u, w, y, z, C) {
    super();
    this.f = f;
    this.j = j;
    this.m = m;
    this.u = u;
    this.w = w;
    this.y = y;
    this.z = z;
    this.C = C;
    this.templateId = TestItemRenderer_1.ID;
  }
  /**
   * @inheritdoc
   */
  renderTemplate(container2) {
    const wrapper = $bk(container2, $(".test-item"));
    const icon2 = $bk(wrapper, $(".computed-state"));
    const label3 = $bk(wrapper, $(".label"));
    const disposable = new $2c();
    $bk(wrapper, $(ThemeIcon.asCSSSelector($i0b)));
    const actionBar = disposable.add(new $LZ(wrapper, {
      actionRunner: this.f,
      actionViewItemProvider: (action, options3) => action instanceof $fJ ? this.y.createInstance($T$, action, { hoverDelegate: options3.hoverDelegate }) : void 0
    }));
    disposable.add(this.z.onDidChange((changed) => {
      const id2 = templateData.current?.test.item.extId;
      if (id2 && (!changed || changed === id2 || $mQ.isChild(id2, changed))) {
        this.D(templateData.current, templateData);
      }
    }));
    const templateData = { wrapper, label: label3, actionBar, icon: icon2, elementDisposable: new $2c(), templateDisposable: disposable };
    return templateData;
  }
  /**
   * @inheritdoc
   */
  disposeTemplate(templateData) {
    templateData.templateDisposable.clear();
  }
  /**
   * @inheritdoc
   */
  disposeElement(_element, _, templateData) {
    templateData.elementDisposable.clear();
  }
  D(element, data) {
    const { actions, contextOverlay } = getActionableElementActions(this.w, this.j, this.m, this.z, this.u, element);
    const crSelf = !!contextOverlay.getContextKeyValue(TestingContextKeys.isContinuousModeOn.key);
    const crChild = !crSelf && this.z.isEnabledForAChildOf(element.test.item.extId);
    data.actionBar.domNode.classList.toggle("testing-is-continuous-run", crSelf || crChild);
    data.actionBar.clear();
    data.actionBar.context = element;
    data.actionBar.push(actions.primary, { icon: true, label: false });
  }
  /**
   * @inheritdoc
   */
  renderElement(node, _depth, data) {
    data.elementDisposable.clear();
    data.current = node.element;
    data.elementDisposable.add(node.element.onChange(() => this._renderElement(node, data)));
    this._renderElement(node, data);
  }
  _renderElement(node, data) {
    this.D(node.element, data);
    const testHidden = this.m.excluded.contains(node.element.test);
    data.wrapper.classList.toggle("test-is-hidden", testHidden);
    const icon2 = $u0b.get(node.element.test.expand === 2 || node.element.test.item.busy ? 2 : node.element.state);
    data.icon.className = "computed-state " + (icon2 ? ThemeIcon.asClassName(icon2) : "");
    if (node.element.retired) {
      data.icon.className += " retired";
    }
    data.elementDisposable.add(this.C.setupManagedHover($JZ("mouse"), data.label, getLabelForTestTreeElement(node.element)));
    if (node.element.test.item.label.trim()) {
      $dk(data.label, ...$B1(node.element.test.item.label));
    } else {
      data.label.textContent = String.fromCharCode(160);
    }
    let description = node.element.description;
    if (node.element.duration !== void 0) {
      description = description ? `${description}: ${formatDuration(node.element.duration)}` : formatDuration(node.element.duration);
    }
    if (description) {
      $bk(data.label, $("span.test-label-description", {}, description));
    }
  }
};
TestItemRenderer = TestItemRenderer_1 = __decorate([
  __param(1, $cJ),
  __param(2, $nTb),
  __param(3, $wTb),
  __param(4, $on),
  __param(5, $Pk),
  __param(6, $i$b),
  __param(7, $5$)
], TestItemRenderer);
var formatDuration = (ms) => {
  if (ms < 10) {
    return `${ms.toFixed(1)}ms`;
  }
  if (ms < 1e3) {
    return `${ms.toFixed(0)}ms`;
  }
  return `${(ms / 1e3).toFixed(1)}s`;
};
var getActionableElementActions = (contextKeyService, menuService, testService, crService, profiles2, element) => {
  const test = element instanceof $l$b ? element.test : void 0;
  const contextKeys = $F0b(test, test ? profiles2.capabilitiesForTest(test.item) : 0);
  contextKeys.push([
    "view",
    "workbench.view.testing"
    /* Testing.ExplorerViewId */
  ]);
  if (test) {
    const ctrl = testService.getTestController(test.controllerId);
    const supportsCr = !!ctrl && profiles2.getControllerProfiles(ctrl.id).some((p) => p.supportsContinuousRun && $xTb(p, test));
    contextKeys.push([
      TestingContextKeys.canRefreshTests.key,
      ctrl && !!(ctrl.capabilities.get() & 2) && $mQ.isRoot(test.item.extId)
    ], [
      TestingContextKeys.testItemIsHidden.key,
      testService.excluded.contains(test)
    ], [
      TestingContextKeys.isContinuousModeOn.key,
      supportsCr && crService.isSpecificallyEnabledFor(test.item.extId)
    ], [
      TestingContextKeys.isParentRunningContinuously.key,
      supportsCr && crService.isEnabledForAParentOf(test.item.extId)
    ], [
      TestingContextKeys.supportsContinuousRun.key,
      supportsCr
    ], [
      TestingContextKeys.testResultOutdated.key,
      element.retired
    ], [
      TestingContextKeys.testResultState.key,
      $nQ[element.state]
    ]);
  }
  const contextOverlay = contextKeyService.createOverlay(contextKeys);
  const menu = menuService.getMenuActions($bJ.TestItem, contextOverlay, {
    shouldForwardArgs: true
  });
  const actions = $Q$(menu, "inline");
  return { actions, contextOverlay };
};
$ms((theme, collector) => {
  if (theme.type === "dark") {
    const foregroundColor = theme.getColor($eo);
    if (foregroundColor) {
      const fgWithOpacity = new $Vn(new $Sn(foregroundColor.rgba.r, foregroundColor.rgba.g, foregroundColor.rgba.b, 0.65));
      collector.addRule(`.test-explorer .test-explorer-messages { color: ${fgWithOpacity}; }`);
    }
  }
});

// out-build/vs/workbench/contrib/testing/browser/testingViewPaneContainer.js
var $j_b = class $j_b2 extends $oqb {
  constructor(layoutService, telemetryService, instantiationService, contextMenuService, themeService, storageService, configurationService, extensionService, contextService, viewDescriptorService) {
    super("workbench.view.extension.test", { mergeViewWithContainerWhenSingleView: true }, instantiationService, configurationService, layoutService, contextMenuService, telemetryService, extensionService, themeService, storageService, contextService, viewDescriptorService);
  }
  create(parent) {
    super.create(parent);
    parent.classList.add("testing-view-pane");
  }
  getOptimalWidth() {
    return 400;
  }
  getTitle() {
    return localize(11219, null);
  }
};
$j_b = __decorate([
  __param(0, $Vlb),
  __param(1, $zv),
  __param(2, $Pk),
  __param(3, $50),
  __param(4, $gs),
  __param(5, $jv),
  __param(6, $kl),
  __param(7, $wN),
  __param(8, $Zk),
  __param(9, $$M)
], $j_b);

// out-build/vs/workbench/contrib/testing/common/mainThreadTestCollection.js
var $k_b = class extends $wQ {
  /**
   * @inheritdoc
   */
  get busyProviders() {
    return this.j;
  }
  /**
   * @inheritdoc
   */
  get rootItems() {
    return this.h;
  }
  /**
   * @inheritdoc
   */
  get all() {
    return this.o();
  }
  get rootIds() {
    return Iterable.map(this.h.values(), (r2) => r2.item.extId);
  }
  constructor(uriIdentityService, d) {
    super(uriIdentityService);
    this.d = d;
    this.a = new $Ec();
    this.b = new $ze();
    this.c = /* @__PURE__ */ new WeakMap();
    this.onBusyProvidersChange = this.b.event;
    this.i = {
      add: (node) => {
        if (!node.item.uri) {
          return;
        }
        const s = this.a.get(node.item.uri);
        if (!s) {
          this.a.set(node.item.uri, /* @__PURE__ */ new Set([node]));
        } else {
          s.add(node);
        }
      },
      remove: (node) => {
        if (!node.item.uri) {
          return;
        }
        const s = this.a.get(node.item.uri);
        if (!s) {
          return;
        }
        s.delete(node);
        if (s.size === 0) {
          this.a.delete(node.item.uri);
        }
      }
    };
  }
  /**
   * @inheritdoc
   */
  expand(testId, levels) {
    const test = this.g.get(testId);
    if (!test) {
      return Promise.resolve();
    }
    const existing = this.c.get(test);
    if (existing && existing.pendingLvl >= levels) {
      return existing.prom;
    }
    const prom = this.d(test.item.extId, levels);
    const record = { doneLvl: existing ? existing.doneLvl : -1, pendingLvl: levels, prom };
    this.c.set(test, record);
    return prom.then(() => {
      record.doneLvl = levels;
    });
  }
  /**
   * @inheritdoc
   */
  getNodeById(id2) {
    return this.g.get(id2);
  }
  /**
   * @inheritdoc
   */
  getNodeByUrl(uri) {
    return this.a.get(uri) || Iterable.empty();
  }
  /**
   * @inheritdoc
   */
  getReviverDiff() {
    const ops = [{ op: 4, amount: this.k }];
    const queue = [this.rootIds];
    while (queue.length) {
      for (const child of queue.pop()) {
        const item = this.g.get(child);
        ops.push({
          op: 0,
          item: {
            controllerId: item.controllerId,
            expand: item.expand,
            item: item.item
          }
        });
        queue.push(item.children);
      }
    }
    return ops;
  }
  /**
   * Applies the diff to the collection.
   */
  apply(diff3) {
    const prevBusy = this.j;
    super.apply(diff3);
    if (prevBusy !== this.j) {
      this.b.fire(this.j);
    }
  }
  /**
   * Clears everything from the collection, and returns a diff that applies
   * that action.
   */
  clear() {
    const ops = [];
    for (const root of this.h) {
      ops.push({ op: 3, itemId: root.item.extId });
    }
    this.h.clear();
    this.g.clear();
    return ops;
  }
  /**
   * @override
   */
  y(internal) {
    return { ...internal, children: /* @__PURE__ */ new Set() };
  }
  x() {
    return this.i;
  }
  *o() {
    const queue = [this.rootIds];
    while (queue.length) {
      for (const id2 of queue.pop()) {
        const node = this.getNodeById(id2);
        yield node;
        queue.push(node.children);
      }
    }
  }
};

// out-build/vs/workbench/contrib/testing/common/testExclusions.js
var $mTb = class $mTb2 extends $3c {
  constructor(b) {
    super();
    this.b = b;
    this.a = this.B($lTb.stored(new $jTb({
      key: "excludedTestItems",
      scope: 1,
      target: 1,
      serialization: {
        deserialize: (v) => new Set(JSON.parse(v)),
        serialize: (v) => JSON.stringify([...v])
      }
    }, this.b), /* @__PURE__ */ new Set()));
    this.onTestExclusionsChanged = this.a.onDidChange;
  }
  /**
   * Gets whether there's any excluded tests.
   */
  get hasAny() {
    return this.a.value.size > 0;
  }
  /**
   * Gets all excluded tests.
   */
  get all() {
    return this.a.value;
  }
  /**
   * Sets whether a test is excluded.
   */
  toggle(test, exclude) {
    if (exclude !== true && this.a.value.has(test.item.extId)) {
      this.a.value = new Set(Iterable.filter(this.a.value, (e) => e !== test.item.extId));
    } else if (exclude !== false && !this.a.value.has(test.item.extId)) {
      this.a.value = /* @__PURE__ */ new Set([...this.a.value, test.item.extId]);
    }
  }
  /**
   * Gets whether a test is excluded.
   */
  contains(test) {
    return this.a.value.has(test.item.extId);
  }
  /**
   * Removes all test exclusions.
   */
  clear() {
    this.a.value = /* @__PURE__ */ new Set();
  }
};
$mTb = __decorate([
  __param(0, $jv)
], $mTb);

// out-build/vs/workbench/contrib/testing/common/testServiceImpl.js
var $l_b = class $l_b2 extends $3c {
  constructor(contextKeyService, instantiationService, z, C, D, F, G, H, I, J) {
    super();
    this.z = z;
    this.C = C;
    this.D = D;
    this.F = F;
    this.G = G;
    this.H = H;
    this.I = I;
    this.J = J;
    this.g = $he("testControllers", /* @__PURE__ */ new Map());
    this.h = /* @__PURE__ */ new Set();
    this.j = new $ze();
    this.m = new $ze();
    this.n = new $ze();
    this.s = /* @__PURE__ */ new Set();
    this.y = /* @__PURE__ */ new Map();
    this.onWillProcessDiff = this.m.event;
    this.onDidProcessDiff = this.n.event;
    this.onDidCancelTestRun = this.j.event;
    this.collection = new $k_b(this.z, this.expandTest.bind(this));
    this.showInlineOutput = this.B($lTb.stored(new $jTb({
      key: "inlineTestOutputVisible",
      scope: 1,
      target: 0
      /* StorageTarget.USER */
    }, this.C), true));
    this.excluded = instantiationService.createInstance($mTb);
    this.u = TestingContextKeys.isRefreshingTests.bindTo(contextKeyService);
    this.w = TestingContextKeys.activeEditorHasTests.bindTo(contextKeyService);
    this.B($H9(TestingContextKeys.providerCount, contextKeyService, (reader) => this.g.read(reader).size));
    const bindCapability = (key2, capability) => this.B($H9(key2, contextKeyService, (reader) => Iterable.some(this.g.read(reader).values(), (ctrl) => !!(ctrl.capabilities.read(reader) & capability))));
    bindCapability(
      TestingContextKeys.canRefreshTests,
      2
      /* TestControllerCapability.Refresh */
    );
    bindCapability(
      TestingContextKeys.canGoToRelatedCode,
      4
      /* TestControllerCapability.CodeRelatedToTest */
    );
    bindCapability(
      TestingContextKeys.canGoToRelatedTest,
      8
      /* TestControllerCapability.TestRelatedToCode */
    );
    this.B(D.onDidActiveEditorChange(() => this.L()));
  }
  /**
   * @inheritdoc
   */
  async expandTest(id2, levels) {
    await this.g.get().get($mQ.fromString(id2).controllerId)?.expandTest(id2, levels);
  }
  /**
   * @inheritdoc
   */
  cancelTestRun(runId, taskId) {
    this.j.fire({ runId, taskId });
    if (runId === void 0) {
      for (const runCts of this.y.values()) {
        runCts.cancel();
      }
    } else if (!taskId) {
      this.y.get(runId)?.cancel();
    }
  }
  /**
   * @inheritdoc
   */
  async runTests(req, token = CancellationToken.None) {
    const byProfile = [];
    for (const test of req.tests) {
      const existing = byProfile.find((p) => $xTb(p.profile, test));
      if (existing) {
        existing.tests.push(test);
        continue;
      }
      const bestProfile = this.F.getDefaultProfileForTest(req.group, test);
      if (!bestProfile) {
        continue;
      }
      byProfile.push({ profile: bestProfile, tests: [test] });
    }
    const resolved = {
      targets: byProfile.map(({ profile, tests }) => ({
        profileId: profile.profileId,
        controllerId: tests[0].controllerId,
        testIds: tests.map((t) => t.item.extId)
      })),
      group: req.group,
      exclude: req.exclude?.map((t) => t.item.extId),
      continuous: req.continuous
    };
    if (resolved.targets.length === 0) {
      for (const byController of $Eb(req.tests, (a, b) => a.controllerId === b.controllerId ? 0 : 1)) {
        const profiles2 = this.F.getControllerProfiles(byController[0].controllerId);
        const withControllers = byController.map((test) => ({
          profile: profiles2.find((p) => p.group === req.group && $xTb(p, test)),
          test
        }));
        for (const byProfile2 of $Eb(withControllers, (a, b) => a.profile === b.profile ? 0 : 1)) {
          const profile = byProfile2[0].profile;
          if (profile) {
            resolved.targets.push({
              testIds: byProfile2.map((t) => t.test.item.extId),
              profileId: profile.profileId,
              controllerId: profile.controllerId
            });
          }
        }
      }
    }
    return this.runResolvedTests(resolved, token);
  }
  /** @inheritdoc */
  async startContinuousRun(req, token) {
    if (!req.exclude) {
      req.exclude = [...this.excluded.all];
    }
    const trust = await this.J.requestWorkspaceTrust({
      message: localize(11355, null)
    });
    if (!trust) {
      return;
    }
    const byController = $Eb(req.targets, (a, b) => a.controllerId.localeCompare(b.controllerId));
    const requests = byController.map((group2) => this.getTestController(group2[0].controllerId)?.startContinuousRun(group2.map((controlReq) => ({
      excludeExtIds: req.exclude.filter((t) => !controlReq.testIds.includes(t)),
      profileId: controlReq.profileId,
      controllerId: controlReq.controllerId,
      testIds: controlReq.testIds
    })), token).then((result) => {
      const errs = result.map((r2) => r2.error).filter($Hg);
      if (errs.length) {
        this.G.error(localize(11356, null, errs.join(" ")));
      }
    }));
    await Promise.all(requests);
  }
  /**
   * @inheritdoc
   */
  async runResolvedTests(req, token = CancellationToken.None) {
    if (!req.exclude) {
      req.exclude = [...this.excluded.all];
    }
    const result = this.I.createLiveResult(req);
    const trust = await this.J.requestWorkspaceTrust({
      message: localize(11357, null)
    });
    if (!trust) {
      result.markComplete();
      return result;
    }
    try {
      const cancelSource = new $ad(token);
      this.y.set(result.id, cancelSource);
      const byController = $Eb(req.targets, (a, b) => a.controllerId.localeCompare(b.controllerId));
      const requests = byController.map((group2) => this.getTestController(group2[0].controllerId)?.runTests(group2.map((controlReq) => ({
        runId: result.id,
        excludeExtIds: req.exclude.filter((t) => !controlReq.testIds.includes(t)),
        profileId: controlReq.profileId,
        controllerId: controlReq.controllerId,
        testIds: controlReq.testIds
      })), cancelSource.token).then((result2) => {
        const errs = result2.map((r2) => r2.error).filter($Hg);
        if (errs.length) {
          this.G.error(localize(11358, null, errs.join(" ")));
        }
      }));
      await this.M(req);
      await Promise.all(requests);
      return result;
    } finally {
      this.y.delete(result.id);
      result.markComplete();
    }
  }
  /**
   * @inheritdoc
   */
  async provideTestFollowups(req, token) {
    const reqs = await Promise.all([...this.h].map(async (ctrl) => ({ ctrl, followups: await ctrl.provideTestFollowups(req, token) })));
    const followups = {
      followups: reqs.flatMap(({ ctrl, followups: followups2 }) => followups2.map((f) => ({
        message: f.title,
        execute: () => ctrl.executeTestFollowup(f.id)
      }))),
      dispose: () => {
        for (const { ctrl, followups: followups2 } of reqs) {
          ctrl.disposeTestFollowups(followups2.map((f) => f.id));
        }
      }
    };
    if (token.isCancellationRequested) {
      followups.dispose();
    }
    return followups;
  }
  /**
   * @inheritdoc
   */
  publishDiff(_controllerId, diff3) {
    this.m.fire(diff3);
    this.collection.apply(diff3);
    this.L();
    this.n.fire(diff3);
  }
  /**
   * @inheritdoc
   */
  getTestController(id2) {
    return this.g.get().get(id2);
  }
  /**
   * @inheritdoc
   */
  async syncTests() {
    const cts = new $ad();
    try {
      await Promise.all([...this.g.get().values()].map((c) => c.syncTests(cts.token)));
    } finally {
      cts.dispose(true);
    }
  }
  /**
   * @inheritdoc
   */
  async refreshTests(controllerId) {
    const cts = new $ad();
    this.s.add(cts);
    this.u.set(true);
    try {
      if (controllerId) {
        await this.getTestController(controllerId)?.refreshTests(cts.token);
      } else {
        await Promise.all([...this.g.get().values()].map((c) => c.refreshTests(cts.token)));
      }
    } finally {
      this.s.delete(cts);
      this.u.set(this.s.size > 0);
      cts.dispose(true);
    }
  }
  /**
   * @inheritdoc
   */
  cancelRefreshTests() {
    for (const cts of this.s) {
      cts.cancel();
    }
    this.s.clear();
    this.u.set(false);
  }
  /**
   * @inheritdoc
   */
  registerExtHost(controller) {
    this.h.add(controller);
    return $1c(() => this.h.delete(controller));
  }
  /**
   * @inheritdoc
   */
  async getTestsRelatedToCode(uri, position, token = CancellationToken.None) {
    const testIds = await Promise.all([...this.h.values()].map((v) => v.getTestsRelatedToCode(uri, position, token)));
    return testIds.flatMap((ids) => ids.map((id2) => this.collection.getNodeById(id2))).filter($Hg);
  }
  /**
   * @inheritdoc
   */
  registerTestController(id2, controller) {
    this.g.set(new Map(this.g.get()).set(id2, controller), void 0);
    return $1c(() => {
      const diff3 = [];
      for (const root of this.collection.rootItems) {
        if (root.controllerId === id2) {
          diff3.push({ op: 3, itemId: root.item.extId });
        }
      }
      this.publishDiff(id2, diff3);
      const next = new Map(this.g.get());
      next.delete(id2);
      this.g.set(next, void 0);
    });
  }
  /**
   * @inheritdoc
   */
  async getCodeRelatedToTest(test, token = CancellationToken.None) {
    return await this.g.get().get(test.controllerId)?.getRelatedCode(test.item.extId, token) || [];
  }
  L() {
    const uri = this.D.activeEditor?.resource;
    if (uri) {
      this.w.set(!Iterable.isEmpty(this.collection.getNodeByUrl(uri)));
    } else {
      this.w.set(false);
    }
  }
  async M(req, configurationService = this.H, editorService = this.D) {
    if (req.preserveFocus === true) {
      return;
    }
    const saveBeforeTest = $w9b(
      this.H,
      "testing.saveBeforeTest"
      /* TestingConfigKeys.SaveBeforeTest */
    );
    if (saveBeforeTest) {
      await editorService.saveAll();
    }
    return;
  }
};
$l_b = __decorate([
  __param(0, $on),
  __param(1, $Pk),
  __param(2, $vl),
  __param(3, $jv),
  __param(4, $mJ),
  __param(5, $wTb),
  __param(6, $PJ),
  __param(7, $kl),
  __param(8, $FTb),
  __param(9, $5M)
], $l_b);

// out-build/vs/workbench/contrib/testing/common/testingContentProvider.js
var $m_b = class $m_b2 {
  constructor(textModelResolverService, a, b, c) {
    this.a = a;
    this.b = b;
    this.c = c;
    textModelResolverService.registerTextModelContentProvider($C0b, this);
  }
  /**
   * @inheritdoc
   */
  async provideTextContent(resource) {
    const existing = this.b.getModel(resource);
    if (existing && !existing.isDisposed()) {
      return existing;
    }
    const parsed = $D0b(resource);
    if (!parsed) {
      return null;
    }
    const result = this.c.getResult(parsed.resultId);
    if (!result) {
      return null;
    }
    if (parsed.type === 0) {
      const task = result.tasks[parsed.taskIndex];
      const model = this.b.createModel("", null, resource, false);
      const append2 = (text3) => model.applyEdits([{
        range: { startColumn: 1, endColumn: 1, startLineNumber: Infinity, endLineNumber: Infinity },
        text: text3
      }]);
      const init = $Ci.concat(task.output.buffers, task.output.length).toString();
      append2($kg(init));
      let hadContent = init.length > 0;
      const dispose = new $2c();
      dispose.add(task.output.onDidWriteData((d) => {
        hadContent ||= d.byteLength > 0;
        append2($kg(d.toString()));
      }));
      task.output.endPromise.then(() => {
        if (dispose.isDisposed) {
          return;
        }
        if (!hadContent) {
          append2(localize(11323, null));
          dispose.dispose();
        }
      });
      model.onWillDispose(() => dispose.dispose());
      return model;
    }
    const test = result?.getStateById(parsed.testExtId);
    if (!test) {
      return null;
    }
    let text2;
    let language = null;
    switch (parsed.type) {
      case 3: {
        const message = test.tasks[parsed.taskIndex].messages[parsed.messageIndex];
        if (message?.type === 0) {
          text2 = message.actual;
        }
        break;
      }
      case 1: {
        text2 = "";
        const output = result.tasks[parsed.taskIndex].output;
        for (const message of test.tasks[parsed.taskIndex].messages) {
          if (message.type === 1) {
            text2 += $kg(output.getRange(message.offset, message.length).toString());
          }
        }
        break;
      }
      case 4: {
        const message = test.tasks[parsed.taskIndex].messages[parsed.messageIndex];
        if (message?.type === 0) {
          text2 = message.expected;
        }
        break;
      }
      case 2: {
        const message = test.tasks[parsed.taskIndex].messages[parsed.messageIndex];
        if (!message) {
          break;
        }
        if (message.type === 1) {
          const content = result.tasks[parsed.taskIndex].output.getRange(message.offset, message.length);
          text2 = $kg(content.toString());
        } else if (typeof message.message === "string") {
          text2 = $kg(message.message);
        } else {
          text2 = message.message.value;
          language = this.a.createById("markdown");
        }
      }
    }
    if (text2 === void 0) {
      return null;
    }
    return this.b.createModel(text2, language, resource, false);
  }
};
$m_b = __decorate([
  __param(0, $oG),
  __param(1, $1E),
  __param(2, $sG),
  __param(3, $FTb)
], $m_b);

// out-build/vs/workbench/contrib/testing/browser/testingConfigurationUi.js
function buildPicker(accessor, { onlyGroup, showConfigureButtons = true, onlyForTest, onlyConfigurable, placeholder = localize(11158, null) }) {
  const profileService = accessor.get($wTb);
  const items = [];
  const pushItems = (allProfiles, description) => {
    for (const profiles2 of $Eb(allProfiles, (a, b) => a.group - b.group)) {
      let addedHeader = false;
      if (onlyGroup) {
        if (profiles2[0].group !== onlyGroup) {
          continue;
        }
        addedHeader = true;
      }
      for (const profile of profiles2) {
        if (onlyConfigurable && !profile.hasConfigurationHandler) {
          continue;
        }
        if (!addedHeader) {
          items.push({ type: "separator", label: $vTb[profiles2[0].group] });
          addedHeader = true;
        }
        items.push({
          type: "item",
          profile,
          label: profile.label,
          description,
          alwaysShow: true,
          buttons: profile.hasConfigurationHandler && showConfigureButtons ? [{
            iconClass: ThemeIcon.asClassName($l0b),
            tooltip: localize(11159, null)
          }] : []
        });
      }
    }
  };
  if (onlyForTest !== void 0) {
    pushItems(profileService.getControllerProfiles(onlyForTest.controllerId).filter((p) => $xTb(p, onlyForTest)));
  } else {
    for (const { profiles: profiles2, controller } of profileService.all()) {
      pushItems(profiles2, controller.label.get());
    }
  }
  const quickpick = accessor.get($1M).createQuickPick({ useSeparators: true });
  quickpick.items = items;
  quickpick.placeholder = placeholder;
  return quickpick;
}
var triggerButtonHandler = (service, resolve) => (evt) => {
  const profile = evt.item.profile;
  if (profile) {
    service.configure(profile.controllerId, profile.profileId);
    resolve(void 0);
  }
};
$tn.registerCommand({
  id: "vscode.pickMultipleTestProfiles",
  handler: async (accessor, options3) => {
    const profileService = accessor.get($wTb);
    const quickpick = buildPicker(accessor, options3);
    if (!quickpick) {
      return;
    }
    const disposables = new $2c();
    disposables.add(quickpick);
    quickpick.canSelectMany = true;
    if (options3.selected) {
      quickpick.selectedItems = quickpick.items.filter((i2) => i2.type === "item").filter((i2) => options3.selected.some((s) => s.controllerId === i2.profile.controllerId && s.profileId === i2.profile.profileId));
    }
    const pick = await new Promise((resolve) => {
      disposables.add(quickpick.onDidAccept(() => {
        const selected = quickpick.selectedItems;
        resolve(selected.map((s) => s.profile).filter($Hg));
      }));
      disposables.add(quickpick.onDidHide(() => resolve(void 0)));
      disposables.add(quickpick.onDidTriggerItemButton(triggerButtonHandler(profileService, resolve)));
      quickpick.show();
    });
    disposables.dispose();
    return pick;
  }
});
$tn.registerCommand({
  id: "vscode.pickTestProfile",
  handler: async (accessor, options3) => {
    const profileService = accessor.get($wTb);
    const quickpick = buildPicker(accessor, options3);
    if (!quickpick) {
      return;
    }
    const disposables = new $2c();
    disposables.add(quickpick);
    const pick = await new Promise((resolve) => {
      disposables.add(quickpick.onDidAccept(() => resolve(quickpick.selectedItems[0]?.profile)));
      disposables.add(quickpick.onDidHide(() => resolve(void 0)));
      disposables.add(quickpick.onDidTriggerItemButton(triggerButtonHandler(profileService, resolve)));
      quickpick.show();
    });
    disposables.dispose();
    return pick;
  }
});

// out-build/vs/workbench/contrib/testing/browser/testing.contribution.js
$SC(
  $nTb,
  $l_b,
  1
  /* InstantiationType.Delayed */
);
$SC(
  $BTb,
  $ETb,
  1
  /* InstantiationType.Delayed */
);
$SC(
  $wTb,
  $zTb,
  1
  /* InstantiationType.Delayed */
);
$SC(
  $y9b,
  $z9b,
  1
  /* InstantiationType.Delayed */
);
$SC(
  $i$b,
  $j$b,
  1
  /* InstantiationType.Delayed */
);
$SC(
  $FTb,
  $GTb,
  1
  /* InstantiationType.Delayed */
);
$SC(
  $60b,
  $70b,
  1
  /* InstantiationType.Delayed */
);
$SC(
  $B0b,
  $00b,
  1
  /* InstantiationType.Delayed */
);
$SC(
  $A0b,
  $g$b,
  1
  /* InstantiationType.Delayed */
);
var viewContainer = $Wn.as(Extensions5.ViewContainersRegistry).registerViewContainer(
  {
    id: "workbench.view.extension.test",
    title: localize2(11153, "Testing"),
    ctorDescriptor: new $Nk($j_b),
    icon: $09b,
    alwaysUseContainerInfo: true,
    order: 6,
    openCommandActionDescriptor: {
      id: "workbench.view.extension.test",
      mnemonicTitle: localize(11150, null),
      // todo: coordinate with joh whether this is available
      // keybindings: { primary: KeyMod.CtrlCmd | KeyMod.Shift | KeyCode.US_SEMICOLON },
      order: 4
    },
    hideIfEmpty: true
  },
  0
  /* ViewContainerLocation.Sidebar */
);
var testResultsViewContainer = $Wn.as(Extensions5.ViewContainersRegistry).registerViewContainer({
  id: "workbench.panel.testResults",
  title: localize2(11154, "Test Results"),
  icon: $$9b,
  ctorDescriptor: new $Nk($oqb, ["workbench.panel.testResults", { mergeViewWithContainerWhenSingleView: true }]),
  hideIfEmpty: true,
  order: 3
}, 1, { doNotRegisterOpenCommand: true });
var viewsRegistry2 = $Wn.as(Extensions5.ViewsRegistry);
viewsRegistry2.registerViews([{
  id: "workbench.panel.testResults.view",
  name: localize2(11155, "Test Results"),
  containerIcon: $$9b,
  canToggleVisibility: false,
  canMoveView: true,
  when: TestingContextKeys.hasAnyResults.isEqualTo(true),
  ctorDescriptor: new $Nk($_0b)
}], testResultsViewContainer);
viewsRegistry2.registerViewWelcomeContent("workbench.view.testing", {
  content: localize(11151, null)
});
viewsRegistry2.registerViewWelcomeContent("workbench.view.testing", {
  content: "[" + localize(11152, null) + `](command:${"testing.searchForTestExtension"})`,
  order: 10
});
viewsRegistry2.registerViews([{
  id: "workbench.view.testing",
  name: localize2(11156, "Test Explorer"),
  ctorDescriptor: new $Nk($i_b),
  canToggleVisibility: true,
  canMoveView: true,
  weight: 80,
  order: -999,
  containerIcon: $09b,
  when: $7m.greater(TestingContextKeys.providerCount.key, 0)
}, {
  id: "workbench.view.testCoverage",
  name: localize2(11157, "Test Coverage"),
  ctorDescriptor: new $Nk($y0b),
  canToggleVisibility: true,
  canMoveView: true,
  weight: 80,
  order: -998,
  containerIcon: $09b,
  when: TestingContextKeys.isTestCoverageOpen
}], viewContainer);
$d_b.forEach($hJ);
$hJ($e$b);
$hJ($c$b);
$hJ($b$b);
$hJ($a$b);
$hJ($f$b);
$hJ($d$b);
$Wn.as(Extensions2.Workbench).registerWorkbenchContribution(
  $m_b,
  3
  /* LifecyclePhase.Restored */
);
$Wn.as(Extensions2.Workbench).registerWorkbenchContribution(
  $00b,
  4
  /* LifecyclePhase.Eventually */
);
$Wn.as(Extensions2.Workbench).registerWorkbenchContribution(
  $f_b,
  4
  /* LifecyclePhase.Eventually */
);
$85(
  "editor.contrib.testingOutputPeek",
  $$0b,
  1
  /* EditorContributionInstantiation.AfterFirstRender */
);
$85(
  "editor.contrib.testingDecorations",
  $h$b,
  1
  /* EditorContributionInstantiation.AfterFirstRender */
);
$85(
  "editor.contrib.coverageDecorations",
  $v0b,
  3
  /* EditorContributionInstantiation.Eventually */
);
$tn.registerCommand({
  id: "_revealTestInExplorer",
  handler: async (accessor, testId, focus) => {
    accessor.get($60b).reveal.set(typeof testId === "string" ? testId : testId.extId, void 0);
    accessor.get($uob).openView("workbench.view.testing", focus);
  }
});
$tn.registerCommand({
  id: "testing.startContinuousRunFromExtension",
  handler: async (accessor, profileRef, tests) => {
    const profiles2 = accessor.get($wTb);
    const collection = accessor.get($nTb).collection;
    const profile = profiles2.getControllerProfiles(profileRef.controllerId).find((p) => p.profileId === profileRef.profileId);
    if (!profile?.supportsContinuousRun) {
      return;
    }
    const crService = accessor.get($i$b);
    for (const test of tests) {
      const found = collection.getNodeById(test.extId);
      if (found && $xTb(profile, found)) {
        crService.start([profile], found.item.extId);
      }
    }
  }
});
$tn.registerCommand({
  id: "testing.stopContinuousRunFromExtension",
  handler: async (accessor, tests) => {
    const crService = accessor.get($i$b);
    for (const test of tests) {
      crService.stop(test.extId);
    }
  }
});
$tn.registerCommand({
  id: "vscode.peekTestError",
  handler: async (accessor, extId) => {
    const lookup = accessor.get($FTb).getStateById(extId);
    if (!lookup) {
      return false;
    }
    const [result, ownState] = lookup;
    const opener = accessor.get($B0b);
    if (opener.tryPeekFirstError(result, ownState)) {
      return true;
    }
    for (const test of result.tests) {
      if ($mQ.compare(ownState.item.extId, test.item.extId) === 2 && opener.tryPeekFirstError(result, test)) {
        return true;
      }
    }
    return false;
  }
});
$tn.registerCommand({
  id: "vscode.revealTest",
  handler: async (accessor, extId, opts) => {
    const test = accessor.get($nTb).collection.getNodeById(extId);
    if (!test) {
      return;
    }
    const commandService = accessor.get($sn);
    const fileService = accessor.get($km);
    const openerService = accessor.get($O4);
    const { range, uri } = test.item;
    if (!uri) {
      return;
    }
    const position = accessor.get($A0b).getDecoratedTestPosition(uri, extId) || range?.getStartPosition();
    accessor.get($60b).reveal.set(extId, void 0);
    accessor.get($B0b).closeAllPeeks();
    let isFile = true;
    try {
      if (!(await fileService.stat(uri)).isFile) {
        isFile = false;
      }
    } catch {
    }
    if (!isFile) {
      await commandService.executeCommand($stb, uri);
      return;
    }
    await openerService.open(position ? uri.with({ fragment: `L${position.lineNumber}:${position.column}` }) : uri, {
      openToSide: opts?.openToSide,
      editorOptions: {
        preserveFocus: opts?.preserveFocus
      }
    });
  }
});
$tn.registerCommand({
  id: "vscode.runTestsById",
  handler: async (accessor, group2, ...testIds) => {
    const testService = accessor.get($nTb);
    await $3$b(accessor.get($nTb).collection, accessor.get($TJ), testIds, (tests) => testService.runTests({ group: group2, tests }));
  }
});
$tn.registerCommand({
  id: "vscode.testing.getControllersWithTests",
  handler: async (accessor) => {
    const testService = accessor.get($nTb);
    return [...testService.collection.rootItems].filter((r2) => r2.children.size > 0).map((r2) => r2.controllerId);
  }
});
$Wn.as($Ht.Configuration).registerConfiguration($v9b);

// out-build/vs/workbench/contrib/logs/common/defaultLogLevels.js
var $n_b = $Qk("IDefaultLogLevelsService");
var DefaultLogLevelsService = class DefaultLogLevelsService2 extends $3c {
  constructor(b, c, f, g, h3) {
    super();
    this.b = b;
    this.c = c;
    this.f = f;
    this.g = g;
    this.h = h3;
    this.a = this.B(new $ze());
    this.onDidChangeDefaultLogLevels = this.a.event;
  }
  async getDefaultLogLevels() {
    const argvLogLevel = await this.n();
    return {
      default: argvLogLevel?.default ?? this.s(),
      extensions: argvLogLevel?.extensions ?? this.t()
    };
  }
  async getDefaultLogLevel(extensionId) {
    const argvLogLevel = await this.n() ?? {};
    if (extensionId) {
      extensionId = extensionId.toLowerCase();
      return this.j(argvLogLevel, extensionId);
    } else {
      return this.j(argvLogLevel);
    }
  }
  async setDefaultLogLevel(defaultLogLevel, extensionId) {
    const argvLogLevel = await this.n() ?? {};
    if (extensionId) {
      extensionId = extensionId.toLowerCase();
      const currentDefaultLogLevel = this.j(argvLogLevel, extensionId);
      argvLogLevel.extensions = argvLogLevel.extensions ?? [];
      const extension = argvLogLevel.extensions.find(([extension2]) => extension2 === extensionId);
      if (extension) {
        extension[1] = defaultLogLevel;
      } else {
        argvLogLevel.extensions.push([extensionId, defaultLogLevel]);
      }
      await this.m(argvLogLevel);
      const extensionLoggers = [...this.h.getRegisteredLoggers()].filter((logger2) => logger2.extensionId && logger2.extensionId.toLowerCase() === extensionId);
      for (const { resource } of extensionLoggers) {
        if (this.h.getLogLevel(resource) === currentDefaultLogLevel) {
          this.h.setLogLevel(resource, defaultLogLevel);
        }
      }
    } else {
      const currentLogLevel = this.j(argvLogLevel);
      argvLogLevel.default = defaultLogLevel;
      await this.m(argvLogLevel);
      if (this.h.getLogLevel() === currentLogLevel) {
        this.h.setLogLevel(defaultLogLevel);
      }
    }
    this.a.fire();
  }
  j(argvLogLevels, extension) {
    if (extension) {
      const extensionLogLevel = argvLogLevels.extensions?.find(([extensionId]) => extensionId === extension);
      if (extensionLogLevel) {
        return extensionLogLevel[1];
      }
    }
    return argvLogLevels.default ?? $Kn(this.b);
  }
  async m(logLevels) {
    const logLevelsValue = [];
    if (!$Gg(logLevels.default)) {
      logLevelsValue.push($Ln(logLevels.default));
    }
    for (const [extension, logLevel] of logLevels.extensions ?? []) {
      logLevelsValue.push(`${extension}=${$Ln(logLevel)}`);
    }
    await this.f.write(this.b.argvResource, [{ path: ["log-level"], value: logLevelsValue.length ? logLevelsValue : void 0 }], true);
  }
  async n() {
    const result = { extensions: [] };
    const logLevels = await this.r();
    for (const extensionLogLevel of logLevels) {
      const matches = $Xu.exec(extensionLogLevel);
      if (matches && matches[1] && matches[2]) {
        const logLevel = $Nn(matches[2]);
        if (!$Gg(logLevel)) {
          result.extensions?.push([matches[1].toLowerCase(), logLevel]);
        }
      } else {
        const logLevel = $Nn(extensionLogLevel);
        if (!$Gg(logLevel)) {
          result.default = logLevel;
        }
      }
    }
    return !$Gg(result.default) || result.extensions?.length ? result : void 0;
  }
  async migrateLogLevels() {
    const logLevels = await this.r();
    const regex = /^([^.]+\..+):(.+)$/;
    if (logLevels.some((extensionLogLevel) => regex.test(extensionLogLevel))) {
      const argvLogLevel = await this.n();
      if (argvLogLevel) {
        await this.m(argvLogLevel);
      }
    }
  }
  async r() {
    try {
      const content = await this.c.readFile(this.b.argvResource);
      const argv = $yw(content.value.toString());
      return $zg(argv["log-level"]) ? [argv["log-level"]] : Array.isArray(argv["log-level"]) ? argv["log-level"] : [];
    } catch (error) {
      if ($Bm(error) !== 1) {
        this.g.error(error);
      }
    }
    return [];
  }
  s() {
    return $Kn(this.b);
  }
  t() {
    const result = [];
    for (const [extension, logLevelValue] of this.b.extensionLogLevel ?? []) {
      const logLevel = $Nn(logLevelValue);
      if (!$Gg(logLevel)) {
        result.push([extension, logLevel]);
      }
    }
    return result;
  }
};
DefaultLogLevelsService = __decorate([
  __param(0, $US),
  __param(1, $km),
  __param(2, $CBb),
  __param(3, $wn),
  __param(4, $xn)
], DefaultLogLevelsService);
$SC(
  $n_b,
  DefaultLogLevelsService,
  1
  /* InstantiationType.Delayed */
);

// out-build/vs/workbench/contrib/logs/common/logsActions.js
var $o_b_1;
var $o_b = class $o_b2 extends $Um {
  static {
    $o_b_1 = this;
  }
  static {
    this.ID = "workbench.action.setLogLevel";
  }
  static {
    this.TITLE = localize2(7797, "Set Log Level...");
  }
  constructor(id2, label3, c, f, g, h3) {
    super(id2, label3);
    this.c = c;
    this.f = f;
    this.g = g;
    this.h = h3;
  }
  async run() {
    const logLevelOrChannel = await this.r();
    if (logLevelOrChannel !== null) {
      if ($yn(logLevelOrChannel)) {
        this.f.setLogLevel(logLevelOrChannel);
      } else {
        await this.t(logLevelOrChannel);
      }
    }
  }
  async r() {
    const defaultLogLevels = await this.h.getDefaultLogLevels();
    const extensionLogs = [], logs = [];
    const logLevel = this.f.getLogLevel();
    for (const channel of this.g.getChannelDescriptors()) {
      if (!$o_b_1.isLevelSettable(channel) || !channel.file) {
        continue;
      }
      const channelLogLevel = this.f.getLogLevel(channel.file) ?? logLevel;
      const item = { id: channel.id, resource: channel.file, label: channel.label, description: channelLogLevel !== logLevel ? this.L(channelLogLevel) : void 0, extensionId: channel.extensionId };
      if (channel.extensionId) {
        extensionLogs.push(item);
      } else {
        logs.push(item);
      }
    }
    const entries2 = [];
    entries2.push({ type: "separator", label: localize(7786, null) });
    entries2.push(...this.y(defaultLogLevels.default, this.f.getLogLevel(), true));
    if (extensionLogs.length) {
      entries2.push({ type: "separator", label: localize(7787, null) });
      entries2.push(...extensionLogs.sort((a, b) => a.label.localeCompare(b.label)));
    }
    entries2.push({ type: "separator", label: localize(7788, null) });
    entries2.push(...logs.sort((a, b) => a.label.localeCompare(b.label)));
    return new Promise((resolve, reject) => {
      const disposables = new $2c();
      const quickPick = disposables.add(this.c.createQuickPick({ useSeparators: true }));
      quickPick.placeholder = localize(7789, null);
      quickPick.items = entries2;
      let selectedItem;
      disposables.add(quickPick.onDidTriggerItemButton((e) => {
        quickPick.hide();
        this.h.setDefaultLogLevel(e.item.level);
      }));
      disposables.add(quickPick.onDidAccept((e) => {
        selectedItem = quickPick.selectedItems[0];
        quickPick.hide();
      }));
      disposables.add(quickPick.onDidHide(() => {
        const result = selectedItem ? selectedItem.level ?? selectedItem : null;
        disposables.dispose();
        resolve(result);
      }));
      quickPick.show();
    });
  }
  static isLevelSettable(channel) {
    return channel.log && channel.file !== void 0 && channel.id !== $fw && channel.id !== $gw;
  }
  async t(logChannel) {
    const defaultLogLevels = await this.h.getDefaultLogLevels();
    const defaultLogLevel = defaultLogLevels.extensions.find((e) => e[0] === logChannel.extensionId?.toLowerCase())?.[1] ?? defaultLogLevels.default;
    const currentLogLevel = this.f.getLogLevel(logChannel.resource) ?? defaultLogLevel;
    const entries2 = this.y(defaultLogLevel, currentLogLevel, !!logChannel.extensionId);
    return new Promise((resolve, reject) => {
      const disposables = new $2c();
      const quickPick = disposables.add(this.c.createQuickPick());
      quickPick.placeholder = logChannel ? localize(7790, null, logChannel?.label) : localize(7791, null);
      quickPick.items = entries2;
      quickPick.activeItems = entries2.filter((entry) => entry.level === this.f.getLogLevel());
      let selectedItem;
      disposables.add(quickPick.onDidTriggerItemButton((e) => {
        quickPick.hide();
        this.h.setDefaultLogLevel(e.item.level, logChannel.extensionId);
      }));
      disposables.add(quickPick.onDidAccept((e) => {
        selectedItem = quickPick.selectedItems[0];
        quickPick.hide();
      }));
      disposables.add(quickPick.onDidHide(() => {
        if (selectedItem) {
          this.f.setLogLevel(logChannel.resource, selectedItem.level);
        }
        disposables.dispose();
        resolve();
      }));
      quickPick.show();
    });
  }
  y(defaultLogLevel, currentLogLevel, canSetDefaultLogLevel) {
    const button = canSetDefaultLogLevel ? { iconClass: ThemeIcon.asClassName($6l.checkAll), tooltip: localize(7792, null) } : void 0;
    return [
      { label: this.L(LogLevel.Trace, currentLogLevel), level: LogLevel.Trace, description: this.M(LogLevel.Trace, defaultLogLevel), buttons: button && defaultLogLevel !== LogLevel.Trace ? [button] : void 0 },
      { label: this.L(LogLevel.Debug, currentLogLevel), level: LogLevel.Debug, description: this.M(LogLevel.Debug, defaultLogLevel), buttons: button && defaultLogLevel !== LogLevel.Debug ? [button] : void 0 },
      { label: this.L(LogLevel.Info, currentLogLevel), level: LogLevel.Info, description: this.M(LogLevel.Info, defaultLogLevel), buttons: button && defaultLogLevel !== LogLevel.Info ? [button] : void 0 },
      { label: this.L(LogLevel.Warning, currentLogLevel), level: LogLevel.Warning, description: this.M(LogLevel.Warning, defaultLogLevel), buttons: button && defaultLogLevel !== LogLevel.Warning ? [button] : void 0 },
      { label: this.L(LogLevel.Error, currentLogLevel), level: LogLevel.Error, description: this.M(LogLevel.Error, defaultLogLevel), buttons: button && defaultLogLevel !== LogLevel.Error ? [button] : void 0 },
      { label: this.L(LogLevel.Off, currentLogLevel), level: LogLevel.Off, description: this.M(LogLevel.Off, defaultLogLevel), buttons: button && defaultLogLevel !== LogLevel.Off ? [button] : void 0 }
    ];
  }
  L(level, current) {
    const label3 = $Mn(level).value;
    return level === current ? `$(check) ${label3}` : label3;
  }
  M(level, defaultLogLevel) {
    return defaultLogLevel === level ? localize(7793, null) : void 0;
  }
};
$o_b = $o_b_1 = __decorate([
  __param(2, $1M),
  __param(3, $xn),
  __param(4, $RS),
  __param(5, $n_b)
], $o_b);
var $p_b = class $p_b2 extends $Um {
  static {
    this.ID = "workbench.action.openSessionLogFile";
  }
  static {
    this.TITLE = localize2(7798, "Open Window Log File (Session)...");
  }
  constructor(id2, label3, c, f, g, h3) {
    super(id2, label3);
    this.c = c;
    this.f = f;
    this.g = g;
    this.h = h3;
  }
  async run() {
    const sessionResult = await this.g.pick(this.r().then((sessions) => sessions.map((s, index) => ({
      id: s.toString(),
      label: $sh(s),
      description: index === 0 ? localize(7794, null) : void 0
    }))), {
      canPickMany: false,
      placeHolder: localize(7795, null)
    });
    if (sessionResult) {
      const logFileResult = await this.g.pick(this.t(URI.parse(sessionResult.id)).then((logFiles) => logFiles.map((s) => ({
        id: s.toString(),
        label: $sh(s)
      }))), {
        canPickMany: false,
        placeHolder: localize(7796, null)
      });
      if (logFileResult) {
        return this.h.openEditor({ resource: URI.parse(logFileResult.id), options: { pinned: true } }).then(() => void 0);
      }
    }
  }
  async r() {
    const logsPath = this.c.logsHome.with({ scheme: this.c.logFile.scheme });
    const result = [logsPath];
    const stat = await this.f.resolve($uh(logsPath));
    if (stat.children) {
      result.push(...stat.children.filter((stat2) => !$oh(stat2.resource, logsPath) && stat2.isDirectory && /^\d{8}T\d{6}$/.test(stat2.name)).sort().reverse().map((d) => d.resource));
    }
    return result;
  }
  async t(session) {
    const stat = await this.f.resolve(session);
    if (stat.children) {
      return stat.children.filter((stat2) => !stat2.isDirectory).map((stat2) => stat2.resource);
    }
    return [];
  }
};
$p_b = __decorate([
  __param(2, $US),
  __param(3, $km),
  __param(4, $1M),
  __param(5, $mJ)
], $p_b);

// out-build/vs/workbench/contrib/logs/common/logs.contribution.js
$hJ(class extends $gJ {
  constructor() {
    super({
      id: $o_b.ID,
      title: $o_b.TITLE,
      category: $qn.Developer,
      f1: true
    });
  }
  run(servicesAccessor) {
    return servicesAccessor.get($Pk).createInstance($o_b, $o_b.ID, $o_b.TITLE.value).run();
  }
});
$hJ(class extends $gJ {
  constructor() {
    super({
      id: "workbench.action.setDefaultLogLevel",
      title: localize2(7784, "Set Default Log Level"),
      category: $qn.Developer
    });
  }
  run(servicesAccessor, logLevel, extensionId) {
    return servicesAccessor.get($n_b).setDefaultLogLevel(logLevel, extensionId);
  }
});
var LogOutputChannels = class LogOutputChannels2 extends $3c {
  constructor(f, g, h3, j, m) {
    super();
    this.f = f;
    this.g = g;
    this.h = h3;
    this.j = j;
    this.m = m;
    this.a = new $Jc();
    this.b = $Wn.as($SS.OutputChannels);
    this.c = this.B(new $_c());
    const contextKey = $On.bindTo(h3);
    contextKey.set($Ln(g.getLogLevel()));
    this.B(g.onDidChangeLogLevel((e) => {
      if ($yn(e)) {
        contextKey.set($Ln(g.getLogLevel()));
      }
    }));
    this.n(g.getRegisteredLoggers());
    this.B(g.onDidChangeLoggers(({ added, removed }) => {
      this.n(added);
      this.s(removed);
    }));
    this.B(g.onDidChangeVisibility(([resource, visibility]) => {
      const logger2 = g.getRegisteredLogger(resource);
      if (logger2) {
        if (visibility) {
          this.t(logger2);
        } else {
          this.u(logger2);
        }
      }
    }));
    this.y();
    this.B(Event2.filter(h3.onDidChangeContext, (e) => e.affectsSome(this.a))(() => this.r()));
  }
  n(loggers) {
    for (const logger2 of loggers) {
      if (logger2.when) {
        const contextKeyExpr2 = $7m.deserialize(logger2.when);
        if (contextKeyExpr2) {
          for (const key2 of contextKeyExpr2.keys()) {
            this.a.add(key2);
          }
          if (!this.h.contextMatchesRules(contextKeyExpr2)) {
            continue;
          }
        }
      }
      if (logger2.hidden) {
        continue;
      }
      this.t(logger2);
    }
  }
  r() {
    for (const logger2 of this.g.getRegisteredLoggers()) {
      if (logger2.when) {
        if (this.h.contextMatchesRules($7m.deserialize(logger2.when))) {
          this.t(logger2);
        } else {
          this.u(logger2);
        }
      }
    }
  }
  s(loggers) {
    for (const logger2 of loggers) {
      if (logger2.when) {
        const contextKeyExpr2 = $7m.deserialize(logger2.when);
        if (contextKeyExpr2) {
          for (const key2 of contextKeyExpr2.keys()) {
            this.a.delete(key2);
          }
        }
      }
      this.u(logger2);
    }
  }
  t(logger2) {
    const channel = this.b.getChannel(logger2.id);
    if (channel && this.m.extUri.isEqual(channel.file, logger2.resource)) {
      return;
    }
    const disposables = new $2c();
    const promise = $Hh(async (token) => {
      await $Rm(logger2.resource, this.j);
      try {
        await this.w(logger2.resource, 1, token);
        const existingChannel = this.b.getChannel(logger2.id);
        const remoteLogger = existingChannel?.file?.scheme === Schemas.vscodeRemote ? this.g.getRegisteredLogger(existingChannel.file) : void 0;
        if (remoteLogger) {
          this.u(remoteLogger);
        }
        const hasToAppendRemote = existingChannel && logger2.resource.scheme === Schemas.vscodeRemote;
        const id2 = hasToAppendRemote ? `${logger2.id}.remote` : logger2.id;
        const label3 = hasToAppendRemote ? localize(7783, null, logger2.name ?? logger2.id) : logger2.name ?? logger2.id;
        this.b.registerChannel({ id: id2, label: label3, file: logger2.resource, log: true, extensionId: logger2.extensionId });
        disposables.add($1c(() => this.b.removeChannel(id2)));
        if (remoteLogger) {
          this.t(remoteLogger);
        }
      } catch (error) {
        if (!$kb(error)) {
          this.f.error("Error while registering log channel", logger2.resource.toString(), $qb(error));
        }
      }
    });
    disposables.add($1c(() => promise.cancel()));
    this.c.set(logger2.resource.toString(), disposables);
  }
  u(logger2) {
    this.c.deleteAndDispose(logger2.resource.toString());
  }
  async w(file, trial, token) {
    const exists = await this.j.exists(file);
    if (exists) {
      return;
    }
    if (token.isCancellationRequested) {
      throw new $lb();
    }
    if (trial > 10) {
      throw new Error(`Timed out while waiting for file to be created`);
    }
    this.f.debug(`[Registering Log Channel] File does not exist. Waiting for 1s to retry.`, file.toString());
    await $Wh(1e3, token);
    await this.w(file, trial + 1, token);
  }
  y() {
    this.B($hJ(class ShowWindowLogAction extends $gJ {
      constructor() {
        super({
          id: $QCb,
          title: localize2(7785, "Show Window Log"),
          category: $qn.Developer,
          f1: true
        });
      }
      async run(servicesAccessor) {
        const outputService = servicesAccessor.get($RS);
        outputService.showChannel($PCb);
      }
    }));
  }
};
LogOutputChannels = __decorate([
  __param(0, $wn),
  __param(1, $xn),
  __param(2, $on),
  __param(3, $km),
  __param(4, $vl)
], LogOutputChannels);
var LogLevelMigration = class LogLevelMigration2 {
  constructor(defaultLogLevelsService) {
    defaultLogLevelsService.migrateLogLevels();
  }
};
LogLevelMigration = __decorate([
  __param(0, $n_b)
], LogLevelMigration);
$Wn.as(Extensions2.Workbench).registerWorkbenchContribution(
  LogOutputChannels,
  3
  /* LifecyclePhase.Restored */
);
$Wn.as(Extensions2.Workbench).registerWorkbenchContribution(
  LogLevelMigration,
  4
  /* LifecyclePhase.Eventually */
);

// out-build/vs/platform/quickinput/browser/helpQuickAccess.js
var $q_b_1;
var $q_b = class $q_b2 {
  static {
    $q_b_1 = this;
  }
  static {
    this.PREFIX = "?";
  }
  constructor(b, c) {
    this.b = b;
    this.c = c;
    this.a = $Wn.as($CM.Quickaccess);
  }
  provide(picker) {
    const disposables = new $2c();
    disposables.add(picker.onDidAccept(() => {
      const [item] = picker.selectedItems;
      if (item) {
        this.b.quickAccess.show(item.prefix, { preserveValue: true });
      }
    }));
    disposables.add(picker.onDidChangeValue((value) => {
      const providerDescriptor = this.a.getQuickAccessProvider(value.substr($q_b_1.PREFIX.length));
      if (providerDescriptor && providerDescriptor.prefix && providerDescriptor.prefix !== $q_b_1.PREFIX) {
        this.b.quickAccess.show(providerDescriptor.prefix, { preserveValue: true });
      }
    }));
    picker.items = this.getQuickAccessProviders().filter((p) => p.prefix !== $q_b_1.PREFIX);
    return disposables;
  }
  getQuickAccessProviders() {
    const providers2 = this.a.getQuickAccessProviders().sort((providerA, providerB) => providerA.prefix.localeCompare(providerB.prefix)).flatMap((provider) => this.d(provider));
    return providers2;
  }
  d(provider) {
    return provider.helpEntries.map((helpEntry) => {
      const prefix = helpEntry.prefix || provider.prefix;
      const label3 = prefix || "\u2026";
      return {
        prefix,
        label: label3,
        keybinding: helpEntry.commandId ? this.c.lookupKeybinding(helpEntry.commandId) : void 0,
        ariaLabel: localize(2058, null, label3, helpEntry.description),
        description: helpEntry.description
      };
    });
  }
};
$q_b = $q_b_1 = __decorate([
  __param(0, $1M),
  __param(1, $Ty)
], $q_b);

// out-build/vs/workbench/contrib/quickaccess/browser/viewQuickAccess.js
var $r_b_1;
var $r_b = class $r_b2 extends $rhb {
  static {
    $r_b_1 = this;
  }
  static {
    this.PREFIX = "view ";
  }
  constructor(h3, j, m, n, r2, t, u, w) {
    super($r_b_1.PREFIX, {
      noResultsPick: {
        label: localize(9094, null),
        containerLabel: ""
      }
    });
    this.h = h3;
    this.j = j;
    this.m = m;
    this.n = n;
    this.r = r2;
    this.t = t;
    this.u = u;
    this.w = w;
  }
  g(filter) {
    const filteredViewEntries = this.z().filter((entry) => {
      if (!filter) {
        return true;
      }
      entry.highlights = { label: $Rl(filter, entry.label, true) ?? void 0 };
      return entry.highlights.label || $pg(entry.containerLabel, filter);
    });
    const mapEntryToContainer = /* @__PURE__ */ new Map();
    for (const entry of filteredViewEntries) {
      if (!mapEntryToContainer.has(entry.label)) {
        mapEntryToContainer.set(entry.label, entry.containerLabel);
      }
    }
    const filteredViewEntriesWithSeparators = [];
    let lastContainer = void 0;
    for (const entry of filteredViewEntries) {
      if (lastContainer !== entry.containerLabel) {
        lastContainer = entry.containerLabel;
        let separatorLabel;
        if (mapEntryToContainer.has(lastContainer)) {
          separatorLabel = `${mapEntryToContainer.get(lastContainer)} / ${lastContainer}`;
        } else {
          separatorLabel = lastContainer;
        }
        filteredViewEntriesWithSeparators.push({ type: "separator", label: separatorLabel });
      }
      filteredViewEntriesWithSeparators.push(entry);
    }
    return filteredViewEntriesWithSeparators;
  }
  z() {
    const viewEntries = [];
    const getViewEntriesForPaneComposite = (paneComposite, viewContainer5) => {
      const viewContainerModel = this.h.getViewContainerModel(viewContainer5);
      const result = [];
      for (const view of viewContainerModel.allViewDescriptors) {
        if (this.w.contextMatchesRules(view.when)) {
          result.push({
            label: view.name.value,
            containerLabel: viewContainerModel.title,
            accept: () => this.j.openView(view.id, true)
          });
        }
      }
      return result;
    };
    const addPaneComposites = (location3, containerLabel) => {
      const paneComposites = this.u.getPaneComposites(location3);
      const visiblePaneCompositeIds = this.u.getVisiblePaneCompositeIds(location3);
      paneComposites.sort((a, b) => {
        let aIndex = visiblePaneCompositeIds.findIndex((id2) => a.id === id2);
        let bIndex = visiblePaneCompositeIds.findIndex((id2) => b.id === id2);
        if (aIndex < 0) {
          aIndex = paneComposites.indexOf(a) + visiblePaneCompositeIds.length;
        }
        if (bIndex < 0) {
          bIndex = paneComposites.indexOf(b) + visiblePaneCompositeIds.length;
        }
        return aIndex - bIndex;
      });
      for (const paneComposite of paneComposites) {
        if (this.C(paneComposite)) {
          const viewContainer5 = this.h.getViewContainerById(paneComposite.id);
          if (viewContainer5) {
            viewEntries.push({
              label: this.h.getViewContainerModel(viewContainer5).title,
              containerLabel,
              accept: () => this.u.openPaneComposite(paneComposite.id, location3, true)
            });
          }
        }
      }
    };
    addPaneComposites(0, localize(9095, null));
    addPaneComposites(1, localize(9096, null));
    addPaneComposites(2, localize(9097, null));
    const addPaneCompositeViews = (location3) => {
      const paneComposites = this.u.getPaneComposites(location3);
      for (const paneComposite of paneComposites) {
        const viewContainer5 = this.h.getViewContainerById(paneComposite.id);
        if (viewContainer5) {
          viewEntries.push(...getViewEntriesForPaneComposite(paneComposite, viewContainer5));
        }
      }
    };
    addPaneCompositeViews(
      0
      /* ViewContainerLocation.Sidebar */
    );
    addPaneCompositeViews(
      1
      /* ViewContainerLocation.Panel */
    );
    addPaneCompositeViews(
      2
      /* ViewContainerLocation.AuxiliaryBar */
    );
    this.r.groups.forEach((group2, groupIndex) => {
      group2.terminalInstances.forEach((terminal2, terminalIndex) => {
        const label3 = localize(9098, null, `${groupIndex + 1}.${terminalIndex + 1}`, terminal2.title);
        viewEntries.push({
          label: label3,
          containerLabel: localize(9099, null),
          accept: async () => {
            await this.r.showPanel(true);
            this.n.setActiveInstance(terminal2);
          }
        });
      });
    });
    this.t.getModel().getSessions(true).filter((s) => s.hasSeparateRepl()).forEach((session, _) => {
      const label3 = session.name;
      viewEntries.push({
        label: label3,
        containerLabel: localize(9100, null),
        accept: async () => {
          await this.t.focusStackFrame(void 0, void 0, session, { explicit: true });
          if (!this.j.isViewVisible($2Q)) {
            await this.j.openView($2Q, true);
          }
        }
      });
    });
    const channels = this.m.getChannelDescriptors();
    for (const channel of channels) {
      viewEntries.push({
        label: channel.label,
        containerLabel: localize(9101, null),
        accept: () => this.m.showChannel(channel.id)
      });
    }
    return viewEntries;
  }
  C(container2) {
    const viewContainer5 = this.h.getViewContainerById(container2.id);
    if (viewContainer5?.hideIfEmpty) {
      return this.h.getViewContainerModel(viewContainer5).activeViewDescriptors.length > 0;
    }
    return true;
  }
};
$r_b = $r_b_1 = __decorate([
  __param(0, $$M),
  __param(1, $uob),
  __param(2, $RS),
  __param(3, $4Pb),
  __param(4, $7Pb),
  __param(5, $0R),
  __param(6, $uqb),
  __param(7, $on)
], $r_b);
var $s_b = class _$s_b extends $gJ {
  static {
    this.ID = "workbench.action.openView";
  }
  constructor() {
    super({
      id: _$s_b.ID,
      title: localize2(9102, "Open View"),
      category: $qn.View,
      f1: true
    });
  }
  async run(accessor) {
    accessor.get($1M).quickAccess.show($r_b.PREFIX);
  }
};
var $t_b = class _$t_b extends $gJ {
  static {
    this.ID = "workbench.action.quickOpenView";
  }
  static {
    this.KEYBINDING = {
      primary: 2048 | 47,
      mac: {
        primary: 256 | 47
        /* KeyCode.KeyQ */
      },
      linux: { primary: 0 }
    };
  }
  constructor() {
    super({
      id: _$t_b.ID,
      title: localize2(9103, "Quick Open View"),
      category: $qn.View,
      f1: false,
      // hide quick pickers from command palette to not confuse with the other entry that shows a input field
      keybinding: {
        weight: 200,
        when: void 0,
        ..._$t_b.KEYBINDING
      }
    });
  }
  async run(accessor) {
    const keybindingService = accessor.get($Ty);
    const quickInputService = accessor.get($1M);
    const keys = keybindingService.lookupKeybindings(_$t_b.ID);
    quickInputService.quickAccess.show($r_b.PREFIX, { quickNavigateConfiguration: { keybindings: keys }, itemActivation: ItemActivation.FIRST });
  }
};

// out-build/vs/platform/quickinput/browser/commandsQuickAccess.js
var $u_b_1;
var $v_b_1;
var $u_b = class $u_b2 extends $rhb {
  static {
    $u_b_1 = this;
  }
  static {
    this.PREFIX = ">";
  }
  static {
    this.h = 0.5;
  }
  static {
    this.j = 5;
  }
  static {
    this.m = or($Ll, $Ql, $Ml);
  }
  constructor(options3, t, u, w, y, z) {
    super($u_b_1.PREFIX, options3);
    this.t = t;
    this.u = u;
    this.w = w;
    this.y = y;
    this.z = z;
    this.n = this.B(this.t.createInstance($v_b));
    this.f = options3;
  }
  async g(filter, _disposables, token, runOptions2) {
    const allCommandPicks = await this.G(token);
    if (token.isCancellationRequested) {
      return [];
    }
    const runTfidf = $Qc(() => {
      const tfidf = new $W3();
      tfidf.updateDocuments(allCommandPicks.map((commandPick) => ({
        key: commandPick.commandId,
        textChunks: [this.F(commandPick)]
      })));
      const result = tfidf.calculateScores(filter, token);
      return $X3(result).filter((score2) => score2.score > $u_b_1.h).slice(0, $u_b_1.j);
    });
    const filteredCommandPicks = [];
    for (const commandPick of allCommandPicks) {
      const labelHighlights = $u_b_1.m(filter, commandPick.label) ?? void 0;
      const aliasHighlights = commandPick.commandAlias ? $u_b_1.m(filter, commandPick.commandAlias) ?? void 0 : void 0;
      if (labelHighlights || aliasHighlights) {
        commandPick.highlights = {
          label: labelHighlights,
          detail: this.f.showAlias ? aliasHighlights : void 0
        };
        filteredCommandPicks.push(commandPick);
      } else if (filter === commandPick.commandId) {
        filteredCommandPicks.push(commandPick);
      } else if (filter.length >= 3) {
        const tfidf = runTfidf();
        if (token.isCancellationRequested) {
          return [];
        }
        const tfidfScore = tfidf.find((score2) => score2.key === commandPick.commandId);
        if (tfidfScore) {
          commandPick.tfIdfScore = tfidfScore.score;
          filteredCommandPicks.push(commandPick);
        }
      }
    }
    const mapLabelToCommand = /* @__PURE__ */ new Map();
    for (const commandPick of filteredCommandPicks) {
      const existingCommandForLabel = mapLabelToCommand.get(commandPick.label);
      if (existingCommandForLabel) {
        commandPick.description = commandPick.commandId;
        existingCommandForLabel.description = existingCommandForLabel.commandId;
      } else {
        mapLabelToCommand.set(commandPick.label, commandPick);
      }
    }
    filteredCommandPicks.sort((commandPickA, commandPickB) => {
      if (commandPickA.tfIdfScore && commandPickB.tfIdfScore) {
        if (commandPickA.tfIdfScore === commandPickB.tfIdfScore) {
          return commandPickA.label.localeCompare(commandPickB.label);
        }
        return commandPickB.tfIdfScore - commandPickA.tfIdfScore;
      } else if (commandPickA.tfIdfScore) {
        return 1;
      } else if (commandPickB.tfIdfScore) {
        return -1;
      }
      const commandACounter = this.n.peek(commandPickA.commandId);
      const commandBCounter = this.n.peek(commandPickB.commandId);
      if (commandACounter && commandBCounter) {
        return commandACounter > commandBCounter ? -1 : 1;
      }
      if (commandACounter) {
        return -1;
      }
      if (commandBCounter) {
        return 1;
      }
      if (this.f.suggestedCommandIds) {
        const commandASuggestion = this.f.suggestedCommandIds.has(commandPickA.commandId);
        const commandBSuggestion = this.f.suggestedCommandIds.has(commandPickB.commandId);
        if (commandASuggestion && commandBSuggestion) {
          return 0;
        }
        if (commandASuggestion) {
          return -1;
        }
        if (commandBSuggestion) {
          return 1;
        }
      }
      return commandPickA.label.localeCompare(commandPickB.label);
    });
    const commandPicks = [];
    let addOtherSeparator = false;
    let addSuggestedSeparator = true;
    let addCommonlyUsedSeparator = !!this.f.suggestedCommandIds;
    for (let i2 = 0; i2 < filteredCommandPicks.length; i2++) {
      const commandPick = filteredCommandPicks[i2];
      if (i2 === 0 && this.n.peek(commandPick.commandId)) {
        commandPicks.push({ type: "separator", label: localize(2051, null) });
        addOtherSeparator = true;
      }
      if (addSuggestedSeparator && commandPick.tfIdfScore !== void 0) {
        commandPicks.push({ type: "separator", label: localize(2052, null) });
        addSuggestedSeparator = false;
      }
      if (addCommonlyUsedSeparator && commandPick.tfIdfScore === void 0 && !this.n.peek(commandPick.commandId) && this.f.suggestedCommandIds?.has(commandPick.commandId)) {
        commandPicks.push({ type: "separator", label: localize(2053, null) });
        addOtherSeparator = true;
        addCommonlyUsedSeparator = false;
      }
      if (addOtherSeparator && commandPick.tfIdfScore === void 0 && !this.n.peek(commandPick.commandId) && !this.f.suggestedCommandIds?.has(commandPick.commandId)) {
        commandPicks.push({ type: "separator", label: localize(2054, null) });
        addOtherSeparator = false;
      }
      commandPicks.push(this.D(commandPick, runOptions2));
    }
    if (!this.H(filter, token)) {
      return commandPicks;
    }
    return {
      picks: commandPicks,
      additionalPicks: (async () => {
        const additionalCommandPicks = await this.I(allCommandPicks, filteredCommandPicks, filter, token);
        if (token.isCancellationRequested) {
          return [];
        }
        const commandPicks2 = additionalCommandPicks.map((commandPick) => this.D(commandPick, runOptions2));
        if (addSuggestedSeparator && commandPicks2[0]?.type !== "separator") {
          commandPicks2.unshift({ type: "separator", label: localize(2055, null) });
        }
        return commandPicks2;
      })()
    };
  }
  D(commandPick, runOptions2) {
    if (commandPick.type === "separator") {
      return commandPick;
    }
    const keybinding = this.u.lookupKeybinding(commandPick.commandId);
    const ariaLabel = keybinding ? localize(2056, null, commandPick.label, keybinding.getAriaLabel()) : commandPick.label;
    return {
      ...commandPick,
      ariaLabel,
      detail: this.f.showAlias && commandPick.commandAlias !== commandPick.label ? commandPick.commandAlias : void 0,
      keybinding,
      accept: async () => {
        this.n.push(commandPick.commandId);
        this.y.publicLog2("workbenchActionExecuted", {
          id: commandPick.commandId,
          from: runOptions2?.from ?? "quick open"
        });
        try {
          commandPick.args?.length ? await this.w.executeCommand(commandPick.commandId, ...commandPick.args) : await this.w.executeCommand(commandPick.commandId);
        } catch (error) {
          if (!$kb(error)) {
            this.z.error(localize(2057, null, commandPick.label), $1m(error));
          }
        }
      }
    };
  }
  // TF-IDF string to be indexed
  F({ label: label3, commandAlias, commandDescription }) {
    let chunk = label3;
    if (commandAlias && commandAlias !== label3) {
      chunk += ` - ${commandAlias}`;
    }
    if (commandDescription && commandDescription.value !== label3) {
      chunk += ` - ${commandDescription.value === commandDescription.original ? commandDescription.value : `${commandDescription.value} (${commandDescription.original})`}`;
    }
    return chunk;
  }
};
$u_b = $u_b_1 = __decorate([
  __param(1, $Pk),
  __param(2, $Ty),
  __param(3, $sn),
  __param(4, $zv),
  __param(5, $Yv)
], $u_b);
var $v_b = class $v_b2 extends $3c {
  static {
    $v_b_1 = this;
  }
  static {
    this.DEFAULT_COMMANDS_HISTORY_LENGTH = 50;
  }
  static {
    this.c = "commandPalette.mru.cache";
  }
  static {
    this.f = "commandPalette.mru.counter";
  }
  static {
    this.h = 1;
  }
  static {
    this.j = false;
  }
  constructor(n, r2, s) {
    super();
    this.n = n;
    this.r = r2;
    this.s = s;
    this.m = 0;
    this.u();
    this.w();
    this.t();
  }
  t() {
    this.B(this.r.onDidChangeConfiguration((e) => this.u(e)));
    this.B(this.n.onWillSaveState((e) => {
      if (e.reason === WillSaveStateReason.SHUTDOWN) {
        this.y();
      }
    }));
  }
  u(e) {
    if (e && !e.affectsConfiguration("workbench.commandPalette.history")) {
      return;
    }
    this.m = $v_b_1.getConfiguredCommandHistoryLength(this.r);
    if ($v_b_1.g && $v_b_1.g.limit !== this.m) {
      $v_b_1.g.limit = this.m;
      $v_b_1.j = true;
    }
  }
  w() {
    const raw = this.n.get(
      $v_b_1.c,
      0
      /* StorageScope.PROFILE */
    );
    let serializedCache;
    if (raw) {
      try {
        serializedCache = JSON.parse(raw);
      } catch (error) {
        this.s.error(`[CommandsHistory] invalid data: ${error}`);
      }
    }
    const cache2 = $v_b_1.g = new $Hc(this.m, 1);
    if (serializedCache) {
      let entries2;
      if (serializedCache.usesLRU) {
        entries2 = serializedCache.entries;
      } else {
        entries2 = serializedCache.entries.sort((a, b) => a.value - b.value);
      }
      entries2.forEach((entry) => cache2.set(entry.key, entry.value));
    }
    $v_b_1.h = this.n.getNumber($v_b_1.f, 0, $v_b_1.h);
  }
  push(commandId) {
    if (!$v_b_1.g) {
      return;
    }
    $v_b_1.g.set(commandId, $v_b_1.h++);
    $v_b_1.j = true;
  }
  peek(commandId) {
    return $v_b_1.g?.peek(commandId);
  }
  y() {
    if (!$v_b_1.g) {
      return;
    }
    if (!$v_b_1.j) {
      return;
    }
    const serializedCache = { usesLRU: true, entries: [] };
    $v_b_1.g.forEach((value, key2) => serializedCache.entries.push({ key: key2, value }));
    this.n.store(
      $v_b_1.c,
      JSON.stringify(serializedCache),
      0,
      0
      /* StorageTarget.USER */
    );
    this.n.store(
      $v_b_1.f,
      $v_b_1.h,
      0,
      0
      /* StorageTarget.USER */
    );
    $v_b_1.j = false;
  }
  static getConfiguredCommandHistoryLength(configurationService) {
    const config = configurationService.getValue();
    const configuredCommandHistoryLength = config.workbench?.commandPalette?.history;
    if (typeof configuredCommandHistoryLength === "number") {
      return configuredCommandHistoryLength;
    }
    return $v_b_1.DEFAULT_COMMANDS_HISTORY_LENGTH;
  }
  static clearHistory(configurationService, storageService) {
    const commandHistoryLength = $v_b_1.getConfiguredCommandHistoryLength(configurationService);
    $v_b_1.g = new $Hc(commandHistoryLength);
    $v_b_1.h = 1;
    $v_b_1.j = true;
  }
};
$v_b = $v_b_1 = __decorate([
  __param(0, $jv),
  __param(1, $kl),
  __param(2, $wn)
], $v_b);

// out-build/vs/editor/contrib/quickAccess/browser/commandsQuickAccess.js
var $w_b = class extends $u_b {
  constructor(options3, instantiationService, keybindingService, commandService, telemetryService, dialogService) {
    super(options3, instantiationService, keybindingService, commandService, telemetryService, dialogService);
  }
  L() {
    const activeTextEditorControl = this.J;
    if (!activeTextEditorControl) {
      return [];
    }
    const editorCommandPicks = [];
    for (const editorAction of activeTextEditorControl.getSupportedActions()) {
      let commandDescription;
      if (editorAction.metadata?.description) {
        if ($un(editorAction.metadata.description)) {
          commandDescription = editorAction.metadata.description;
        } else {
          commandDescription = { original: editorAction.metadata.description, value: editorAction.metadata.description };
        }
      }
      editorCommandPicks.push({
        commandId: editorAction.id,
        commandAlias: editorAction.alias,
        commandDescription,
        label: $0l(editorAction.label) || editorAction.id
      });
    }
    return editorCommandPicks;
  }
};

// out-build/vs/workbench/contrib/quickaccess/browser/commandsQuickAccess.js
var $x_b_1;
var $x_b = class $x_b2 extends $w_b {
  static {
    $x_b_1 = this;
  }
  static {
    this.M = 5;
  }
  static {
    this.N = 200;
  }
  get J() {
    return this.R.activeTextEditorControl;
  }
  get defaultFilterValue() {
    if (this.bb.preserveInput) {
      return DefaultQuickAccessFilterValue.LAST;
    }
    return void 0;
  }
  constructor(R, S, U, instantiationService, keybindingService, commandService, telemetryService, dialogService, W, X, Y, Z, $149, ab) {
    super({
      showAlias: !Language.isDefaultVariant(),
      noResultsPick: () => ({
        label: localize(9072, null),
        commandId: ""
      })
    }, instantiationService, keybindingService, commandService, telemetryService, dialogService);
    this.R = R;
    this.S = S;
    this.U = U;
    this.W = W;
    this.X = X;
    this.Y = Y;
    this.Z = Z;
    this.$ = $149;
    this.ab = ab;
    this.O = $Lh(this.U.whenInstalledExtensionsRegistered(), 800);
    this.P = false;
    this.B(W.onDidChangeConfiguration((e) => this.cb(e)));
    this.cb();
  }
  get bb() {
    const commandPaletteConfig = this.W.getValue().workbench.commandPalette;
    return {
      preserveInput: commandPaletteConfig.preserveInput,
      experimental: commandPaletteConfig.experimental
    };
  }
  cb(e) {
    if (e && !e.affectsConfiguration("workbench.commandPalette.experimental")) {
      return;
    }
    const config = this.bb;
    const suggestedCommandIds = config.experimental.suggestCommands && this.Z.commandPaletteSuggestedCommandIds?.length ? new Set(this.Z.commandPaletteSuggestedCommandIds) : void 0;
    this.f.suggestedCommandIds = suggestedCommandIds;
    this.P = config.experimental.enableNaturalLanguageSearch;
  }
  async G(token) {
    await this.O;
    if (token.isCancellationRequested) {
      return [];
    }
    return [
      ...this.L(),
      ...this.hb()
    ].map((picks) => ({
      ...picks,
      buttons: [{
        iconClass: ThemeIcon.asClassName($6l.gear),
        tooltip: localize(9073, null)
      }],
      trigger: () => {
        this.Y.openGlobalKeybindingSettings(false, { query: $CVb(picks.commandId, picks.commandWhen) });
        return TriggerAction.CLOSE_PICKER;
      }
    }));
  }
  H(filter, token) {
    if (!this.P || token.isCancellationRequested || filter === "" || !this.$.isEnabled()) {
      return false;
    }
    return true;
  }
  async I(allPicks, picksSoFar, filter, token) {
    if (!this.H(filter, token)) {
      return [];
    }
    let additionalPicks;
    try {
      await $Wh($x_b_1.N, token);
      additionalPicks = await this.gb(allPicks, picksSoFar, filter, token);
    } catch (e) {
      return [];
    }
    if (picksSoFar.length || additionalPicks.length) {
      additionalPicks.push({
        type: "separator"
      });
    }
    const defaultAgent = this.ab.getDefaultAgent(ChatAgentLocation.Panel);
    if (defaultAgent) {
      additionalPicks.push({
        label: localize(9074, null, defaultAgent.fullName, filter),
        commandId: this.bb.experimental.askChatLocation === "quickChat" ? $e6b : $wNb,
        args: [filter]
      });
    }
    return additionalPicks;
  }
  async gb(allPicks, picksSoFar, filter, token) {
    const relatedInformation = await this.$.getRelatedInformation(filter, [RelatedInformationType2.CommandInformation], token);
    relatedInformation.sort((a, b) => b.weight - a.weight);
    const setOfPicksSoFar = new Set(picksSoFar.map((p) => p.commandId));
    const additionalPicks = new Array();
    for (const info of relatedInformation) {
      if (additionalPicks.length === $x_b_1.M) {
        break;
      }
      const pick = allPicks.find((p) => p.commandId === info.command && !setOfPicksSoFar.has(p.commandId));
      if (pick) {
        additionalPicks.push(pick);
      }
    }
    return additionalPicks;
  }
  hb() {
    const globalCommandPicks = [];
    const scopedContextKeyService = this.R.activeEditorPane?.scopedContextKeyService || this.X.activeGroup.scopedContextKeyService;
    const globalCommandsMenu = this.S.getMenuActions($bJ.CommandPalette, scopedContextKeyService);
    const globalCommandsMenuActions = globalCommandsMenu.reduce((r2, [, actions]) => [...r2, ...actions], []).filter((action) => action instanceof $fJ && action.enabled);
    for (const action of globalCommandsMenuActions) {
      let label3 = (typeof action.item.title === "string" ? action.item.title : action.item.title.value) || action.item.id;
      const category8 = typeof action.item.category === "string" ? action.item.category : action.item.category?.value;
      if (category8) {
        label3 = localize(9075, null, category8, label3);
      }
      const aliasLabel = typeof action.item.title !== "string" ? action.item.title.original : void 0;
      const aliasCategory = category8 && action.item.category && typeof action.item.category !== "string" ? action.item.category.original : void 0;
      const commandAlias = aliasLabel && category8 ? aliasCategory ? `${aliasCategory}: ${aliasLabel}` : `${category8}: ${aliasLabel}` : aliasLabel;
      const metadataDescription = action.item.metadata?.description;
      const commandDescription = metadataDescription === void 0 || $un(metadataDescription) ? metadataDescription : { value: metadataDescription, original: metadataDescription };
      globalCommandPicks.push({
        commandId: action.item.id,
        commandWhen: action.item.precondition?.serialize(),
        commandAlias,
        label: $0l(label3),
        commandDescription
      });
    }
    return globalCommandPicks;
  }
};
$x_b = $x_b_1 = __decorate([
  __param(0, $mJ),
  __param(1, $cJ),
  __param(2, $wN),
  __param(3, $Pk),
  __param(4, $Ty),
  __param(5, $sn),
  __param(6, $zv),
  __param(7, $Yv),
  __param(8, $kl),
  __param(9, $iJ),
  __param(10, $TK),
  __param(11, $Vu),
  __param(12, $vS),
  __param(13, $ZO)
], $x_b);
var $y_b = class _$y_b extends $gJ {
  static {
    this.ID = "workbench.action.showCommands";
  }
  constructor() {
    super({
      id: _$y_b.ID,
      title: localize2(9079, "Show All Commands"),
      keybinding: {
        weight: 200,
        when: void 0,
        primary: !$Ue ? 2048 | 1024 | 46 : void 0,
        secondary: [
          59
          /* KeyCode.F1 */
        ]
      },
      f1: true
    });
  }
  async run(accessor) {
    accessor.get($1M).quickAccess.show($x_b.PREFIX);
  }
};
var $z_b = class extends $gJ {
  constructor() {
    super({
      id: "workbench.action.clearCommandHistory",
      title: localize2(9080, "Clear Command History"),
      f1: true
    });
  }
  async run(accessor) {
    const configurationService = accessor.get($kl);
    const storageService = accessor.get($jv);
    const dialogService = accessor.get($Yv);
    const commandHistoryLength = $v_b.getConfiguredCommandHistoryLength(configurationService);
    if (commandHistoryLength > 0) {
      const { confirmed } = await dialogService.confirm({
        type: "warning",
        message: localize(9076, null),
        detail: localize(9077, null),
        primaryButton: localize(9078, null)
      });
      if (!confirmed) {
        return;
      }
      $v_b.clearHistory(configurationService, storageService);
    }
  }
};

// out-build/vs/workbench/contrib/quickaccess/browser/quickAccess.contribution.js
var quickAccessRegistry2 = $Wn.as($CM.Quickaccess);
quickAccessRegistry2.registerQuickAccessProvider({
  ctor: $q_b,
  prefix: $q_b.PREFIX,
  placeholder: localize(9081, null, $q_b.PREFIX),
  helpEntries: [{
    description: localize(9082, null),
    commandCenterOrder: 70,
    commandCenterLabel: localize(9083, null)
  }]
});
quickAccessRegistry2.registerQuickAccessProvider({
  ctor: $r_b,
  prefix: $r_b.PREFIX,
  contextKey: "inViewsPicker",
  placeholder: localize(9084, null),
  helpEntries: [{ description: localize(9085, null), commandId: $s_b.ID }]
});
quickAccessRegistry2.registerQuickAccessProvider({
  ctor: $x_b,
  prefix: $x_b.PREFIX,
  contextKey: "inCommandsPicker",
  placeholder: localize(9086, null),
  helpEntries: [{ description: localize(9087, null), commandId: $y_b.ID, commandCenterOrder: 20 }]
});
$dJ.appendMenuItem($bJ.MenubarViewMenu, {
  group: "1_open",
  command: {
    id: $y_b.ID,
    title: localize(9088, null)
  },
  order: 1
});
$dJ.appendMenuItem($bJ.MenubarHelpMenu, {
  group: "1_welcome",
  command: {
    id: $y_b.ID,
    title: localize(9089, null)
  },
  order: 2
});
$dJ.appendMenuItem($bJ.MenubarViewMenu, {
  group: "1_open",
  command: {
    id: $s_b.ID,
    title: localize(9090, null)
  },
  order: 2
});
$dJ.appendMenuItem($bJ.MenubarGoMenu, {
  group: "5_infile_nav",
  command: {
    id: "workbench.action.gotoLine",
    title: localize(9091, null)
  },
  order: 1
});
$dJ.appendMenuItem($bJ.GlobalActivity, {
  group: "1_command",
  command: {
    id: $y_b.ID,
    title: localize(9092, null)
  },
  order: 1
});
$dJ.appendMenuItem($bJ.EditorContext, {
  group: "z_commands",
  when: EditorContextKeys.editorSimpleInput.toNegated(),
  command: {
    id: $y_b.ID,
    title: localize(9093, null)
  },
  order: 1
});
$hJ($z_b);
$hJ($y_b);
$hJ($s_b);
$hJ($t_b);
var inViewsPickerContextKey = "inViewsPicker";
var inViewsPickerContext = $7m.and($6yb, $7m.has(inViewsPickerContextKey));
var viewPickerKeybinding = $t_b.KEYBINDING;
var quickAccessNavigateNextInViewPickerId = "workbench.action.quickOpenNavigateNextInViewPicker";
$0I.registerCommandAndKeybindingRule({
  id: quickAccessNavigateNextInViewPickerId,
  weight: 200 + 50,
  handler: $9yb(quickAccessNavigateNextInViewPickerId, true),
  when: inViewsPickerContext,
  primary: viewPickerKeybinding.primary,
  linux: viewPickerKeybinding.linux,
  mac: viewPickerKeybinding.mac
});
var quickAccessNavigatePreviousInViewPickerId = "workbench.action.quickOpenNavigatePreviousInViewPicker";
$0I.registerCommandAndKeybindingRule({
  id: quickAccessNavigatePreviousInViewPickerId,
  weight: 200 + 50,
  handler: $9yb(quickAccessNavigatePreviousInViewPickerId, false),
  when: inViewsPickerContext,
  primary: viewPickerKeybinding.primary | 1024,
  linux: viewPickerKeybinding.linux,
  mac: {
    primary: viewPickerKeybinding.mac.primary | 1024
    /* KeyMod.Shift */
  }
});

// out-build/vs/workbench/contrib/files/browser/views/emptyView.js
var $Fwb_1;
var $Fwb = class $Fwb2 extends $_ob {
  static {
    $Fwb_1 = this;
  }
  static {
    this.ID = "workbench.explorer.emptyView";
  }
  static {
    this.NAME = localize2(7369, "No Folder Opened");
  }
  constructor(options3, themeService, viewDescriptorService, instantiationService, keybindingService, contextMenuService, b, configurationService, c, contextKeyService, openerService, telemetryService, hoverService) {
    super(options3, keybindingService, contextMenuService, configurationService, contextKeyService, viewDescriptorService, instantiationService, openerService, themeService, telemetryService, hoverService);
    this.b = b;
    this.c = c;
    this.a = false;
    this.B(this.b.onDidChangeWorkbenchState(() => this.g()));
    this.B(this.c.onDidChangeFormatters(() => this.g()));
  }
  shouldShowWelcome() {
    return true;
  }
  W(container2) {
    super.W(container2);
    this.B(new $Ak(container2, {
      onDrop: (e) => {
        container2.style.backgroundColor = "";
        const dropHandler = this.Db.createInstance($Dob, { allowWorkspaceOpen: !$r || $fl(this.b.getWorkspace()) });
        dropHandler.handleDrop(e, getWindow(container2));
      },
      onDragEnter: () => {
        const color2 = this.Fb.getColorTheme().getColor($sr);
        container2.style.backgroundColor = color2 ? color2.toString() : "";
      },
      onDragEnd: () => {
        container2.style.backgroundColor = "";
      },
      onDragLeave: () => {
        container2.style.backgroundColor = "";
      },
      onDragOver: (e) => {
        if (e.dataTransfer) {
          e.dataTransfer.dropEffect = "copy";
        }
      }
    }));
    this.g();
  }
  g() {
    if (this.a) {
      return;
    }
    if (this.b.getWorkbenchState() === 3) {
      this.Qb($Fwb_1.NAME.value);
    } else {
      this.Qb(this.title);
    }
  }
  dispose() {
    this.a = true;
    super.dispose();
  }
};
$Fwb = $Fwb_1 = __decorate([
  __param(1, $gs),
  __param(2, $$M),
  __param(3, $Pk),
  __param(4, $Ty),
  __param(5, $50),
  __param(6, $Zk),
  __param(7, $kl),
  __param(8, $ZI),
  __param(9, $on),
  __param(10, $O4),
  __param(11, $zv),
  __param(12, $5$)
], $Fwb);

// out-build/vs/workbench/contrib/files/browser/explorerViewlet.js
var explorerViewIcon = $9r("explorer-view-icon", $6l.files, localize(7071, null));
var openEditorsViewIcon = $9r("open-editors-view-icon", $6l.book, localize(7072, null));
var $bzb = class $bzb2 extends $3c {
  static {
    this.ID = "workbench.contrib.explorerViewletViews";
  }
  constructor(a, progressService) {
    super();
    this.a = a;
    progressService.withProgress({
      location: 1
      /* ProgressLocation.Explorer */
    }, () => a.getCompleteWorkspace()).finally(() => {
      this.b();
      this.B(a.onDidChangeWorkbenchState(() => this.b()));
      this.B(a.onDidChangeWorkspaceFolders(() => this.b()));
    });
  }
  b() {
    $S("code/willRegisterExplorerViews");
    const viewDescriptors = viewsRegistry3.getViews($dzb);
    const viewDescriptorsToRegister = [];
    const viewDescriptorsToDeregister = [];
    const openEditorsViewDescriptor = this.c();
    if (!viewDescriptors.some((v) => v.id === openEditorsViewDescriptor.id)) {
      viewDescriptorsToRegister.push(openEditorsViewDescriptor);
    }
    const explorerViewDescriptor = this.g();
    const registeredExplorerViewDescriptor = viewDescriptors.find((v) => v.id === explorerViewDescriptor.id);
    const emptyViewDescriptor = this.f();
    const registeredEmptyViewDescriptor = viewDescriptors.find((v) => v.id === emptyViewDescriptor.id);
    if (this.a.getWorkbenchState() === 1 || this.a.getWorkspace().folders.length === 0) {
      if (registeredExplorerViewDescriptor) {
        viewDescriptorsToDeregister.push(registeredExplorerViewDescriptor);
      }
      if (!registeredEmptyViewDescriptor) {
        viewDescriptorsToRegister.push(emptyViewDescriptor);
      }
    } else {
      if (registeredEmptyViewDescriptor) {
        viewDescriptorsToDeregister.push(registeredEmptyViewDescriptor);
      }
      if (!registeredExplorerViewDescriptor) {
        viewDescriptorsToRegister.push(explorerViewDescriptor);
      }
    }
    if (viewDescriptorsToDeregister.length) {
      viewsRegistry3.deregisterViews(viewDescriptorsToDeregister, $dzb);
    }
    if (viewDescriptorsToRegister.length) {
      viewsRegistry3.registerViews(viewDescriptorsToRegister, $dzb);
    }
    $S("code/didRegisterExplorerViews");
  }
  c() {
    return {
      id: $Syb.ID,
      name: $Syb.NAME,
      ctorDescriptor: new $Nk($Syb),
      containerIcon: openEditorsViewIcon,
      order: 0,
      canToggleVisibility: true,
      canMoveView: true,
      collapsed: false,
      hideByDefault: true,
      focusCommand: {
        id: "workbench.files.action.focusOpenEditorsView",
        keybindings: { primary: $$e(
          2048 | 41,
          35
          /* KeyCode.KeyE */
        ) }
      }
    };
  }
  f() {
    return {
      id: $Fwb.ID,
      name: $Fwb.NAME,
      containerIcon: explorerViewIcon,
      ctorDescriptor: new $Nk($Fwb),
      order: 1,
      canToggleVisibility: true,
      focusCommand: {
        id: "workbench.explorer.fileView.focus"
      }
    };
  }
  g() {
    return {
      id: $4sb,
      name: localize2(7082, "Folders"),
      containerIcon: explorerViewIcon,
      ctorDescriptor: new $Nk($Dwb),
      order: 1,
      canMoveView: true,
      canToggleVisibility: false,
      focusCommand: {
        id: "workbench.explorer.fileView.focus"
      }
    };
  }
};
$bzb = __decorate([
  __param(0, $Zk),
  __param(1, $TJ)
], $bzb);
var $czb = class $czb2 extends $oqb {
  constructor(layoutService, telemetryService, contextService, storageService, configurationService, instantiationService, contextKeyService, themeService, contextMenuService, extensionService, viewDescriptorService) {
    super($3sb, { mergeViewWithContainerWhenSingleView: true }, instantiationService, configurationService, layoutService, contextMenuService, telemetryService, extensionService, themeService, storageService, contextService, viewDescriptorService);
    this.c = $5sb.bindTo(contextKeyService);
    this.B(this.ib.onDidChangeWorkspaceName((e) => this.mb()));
  }
  create(parent) {
    super.create(parent);
    parent.classList.add("explorer-viewlet");
  }
  nb(viewDescriptor3, options3) {
    if (viewDescriptor3.id === $4sb) {
      return this.bb.createInstance($Dwb, {
        ...options3,
        delegate: {
          willOpenElement: (e) => {
            if (!$3j(e)) {
              return;
            }
            const openEditorsView = this.getOpenEditorsView();
            if (openEditorsView) {
              let delay = 0;
              const config = this.cb.getValue();
              if (!!config.workbench?.editor?.enablePreview) {
                delay = 250;
              }
              openEditorsView.setStructuralRefreshDelay(delay);
            }
          },
          didOpenElement: (e) => {
            if (!$3j(e)) {
              return;
            }
            const openEditorsView = this.getOpenEditorsView();
            openEditorsView?.setStructuralRefreshDelay(0);
          }
        }
      });
    }
    return super.nb(viewDescriptor3, options3);
  }
  getExplorerView() {
    return this.getView($4sb);
  }
  getOpenEditorsView() {
    return this.getView($Syb.ID);
  }
  setVisible(visible) {
    this.c.set(visible);
    super.setVisible(visible);
  }
  focus() {
    const explorerView = this.getView($4sb);
    if (explorerView && this.panes.every((p) => !p.isExpanded())) {
      explorerView.setExpanded(true);
    }
    if (explorerView?.isExpanded()) {
      explorerView.focus();
    } else {
      super.focus();
    }
  }
};
$czb = __decorate([
  __param(0, $Vlb),
  __param(1, $zv),
  __param(2, $Zk),
  __param(3, $jv),
  __param(4, $kl),
  __param(5, $Pk),
  __param(6, $on),
  __param(7, $gs),
  __param(8, $50),
  __param(9, $wN),
  __param(10, $$M)
], $czb);
var viewContainerRegistry = $Wn.as(Extensions5.ViewContainersRegistry);
var $dzb = viewContainerRegistry.registerViewContainer({
  id: $3sb,
  title: localize2(7083, "Explorer"),
  ctorDescriptor: new $Nk($czb),
  storageId: "workbench.explorer.views.state",
  icon: explorerViewIcon,
  alwaysUseContainerInfo: true,
  hideIfEmpty: true,
  order: 0,
  openCommandActionDescriptor: {
    id: $3sb,
    title: localize2(7084, "Explorer"),
    mnemonicTitle: localize(7073, null),
    keybindings: {
      primary: 2048 | 1024 | 35
      /* KeyCode.KeyE */
    },
    order: 0
  }
}, 0, { isDefault: true });
var openFolder2 = localize(7074, null);
var addAFolder = localize(7075, null);
var openRecent2 = localize(7076, null);
var addRootFolderButton = `[${openFolder2}](command:${$2yb.ID})`;
var addAFolderButton = `[${addAFolder}](command:${$2yb.ID})`;
var openFolderButton = `[${openFolder2}](command:${$m && !$r ? $1yb.ID : $Yyb.ID})`;
var openFolderViaWorkspaceButton = `[${openFolder2}](command:${$Zyb.ID})`;
var openRecentButton = `[${openRecent2}](command:${$_yb.ID})`;
var viewsRegistry3 = $Wn.as(Extensions5.ViewsRegistry);
viewsRegistry3.registerViewWelcomeContent($Fwb.ID, {
  content: localize(7077, null, addRootFolderButton),
  when: $7m.and(
    // inside a .code-workspace
    $epb.isEqualTo("workspace"),
    // unless we cannot enter or open workspaces (e.g. web serverless)
    $gpb
  ),
  group: ViewContentGroups.Open,
  order: 1
});
viewsRegistry3.registerViewWelcomeContent($Fwb.ID, {
  content: localize(7078, null, openFolderViaWorkspaceButton, openRecentButton),
  when: $7m.and(
    // inside a .code-workspace
    $epb.isEqualTo("workspace"),
    // we cannot enter workspaces (e.g. web serverless)
    $gpb.toNegated()
  ),
  group: ViewContentGroups.Open,
  order: 1
});
viewsRegistry3.registerViewWelcomeContent($Fwb.ID, {
  content: localize(7079, null, openFolderButton),
  when: $7m.and(
    // not inside a .code-workspace
    $epb.notEqualsTo("workspace"),
    // connected to a remote
    $kpb.notEqualsTo(""),
    // but not in web
    $veb.toNegated()
  ),
  group: ViewContentGroups.Open,
  order: 1
});
viewsRegistry3.registerViewWelcomeContent($Fwb.ID, {
  content: localize(7080, null, openFolderButton, addAFolderButton),
  when: $7m.and(
    // editors are opened
    $7m.has("editorIsOpen"),
    $7m.or(
      // not inside a .code-workspace and local
      $7m.and($epb.notEqualsTo("workspace"), $kpb.isEqualTo("")),
      // not inside a .code-workspace and web
      $7m.and($epb.notEqualsTo("workspace"), $veb)
    )
  ),
  group: ViewContentGroups.Open,
  order: 1
});
viewsRegistry3.registerViewWelcomeContent($Fwb.ID, {
  content: localize(7081, null, openFolderButton),
  when: $7m.and(
    // no editor is open
    $7m.has("editorIsOpen")?.negate(),
    $7m.or(
      // not inside a .code-workspace and local
      $7m.and($epb.notEqualsTo("workspace"), $kpb.isEqualTo("")),
      // not inside a .code-workspace and web
      $7m.and($epb.notEqualsTo("workspace"), $veb)
    )
  ),
  group: ViewContentGroups.Open,
  order: 1
});

// out-build/vs/workbench/contrib/files/browser/editors/textFileEditorTracker.js
var $A_b = class $A_b2 extends $3c {
  static {
    this.ID = "workbench.contrib.textFileEditorTracker";
  }
  constructor(a, b, c, f, g, h3, j) {
    super();
    this.a = a;
    this.b = b;
    this.c = c;
    this.f = f;
    this.g = g;
    this.h = h3;
    this.j = j;
    this.n = this.B(new $0h((units) => this.s(units), this.r()));
    this.m();
  }
  m() {
    this.B(this.b.files.onDidChangeDirty((model) => this.n.work(model.resource)));
    this.B(this.b.files.onDidSaveError((model) => this.n.work(model.resource)));
    this.B(this.b.untitled.onDidChangeDirty((model) => this.n.work(model.resource)));
    this.B(this.f.onDidChangeFocus((hasFocus) => hasFocus ? this.u() : void 0));
    this.B(this.c.onDidShutdown(() => this.dispose()));
  }
  r() {
    return 800;
  }
  s(resources) {
    this.t($Rb(resources.filter((resource) => {
      if (!this.b.isDirty(resource)) {
        return false;
      }
      const fileModel = this.b.files.get(resource);
      if (fileModel?.hasState(
        2
        /* TextFileEditorModelState.PENDING_SAVE */
      )) {
        return false;
      }
      if (resource.scheme !== Schemas.untitled && !fileModel?.hasState(
        5
        /* TextFileEditorModelState.ERROR */
      ) && this.h.hasShortAutoSaveDelay(resource)) {
        return false;
      }
      if (this.a.isOpened({ resource, typeId: resource.scheme === Schemas.untitled ? $0Gb.ID : $ntb, editorId: $1K.id })) {
        return false;
      }
      const model = fileModel ?? this.b.untitled.get(resource);
      if (model && this.j.findEditor(model)) {
        return false;
      }
      return true;
    }), (resource) => resource.toString()));
  }
  t(resources) {
    if (!resources.length) {
      return;
    }
    this.a.openEditors(resources.map((resource) => ({
      resource,
      options: { inactive: true, pinned: true, preserveFocus: true }
    })));
  }
  //#endregion
  //#region Window Focus Change: Update visible code editors when focus is gained that have a known text file model
  u() {
    $Rb($Mb(this.g.listCodeEditors().map((codeEditor) => {
      const resource = codeEditor.getModel()?.uri;
      if (!resource) {
        return void 0;
      }
      const model = this.b.files.get(resource);
      if (!model || model.isDirty() || !model.isResolved()) {
        return void 0;
      }
      return model;
    })), (model) => model.resource.toString()).forEach((model) => this.b.files.resolve(model.resource, { reload: { async: true } }));
  }
};
$A_b = __decorate([
  __param(0, $mJ),
  __param(1, $cK),
  __param(2, $KL),
  __param(3, $S4),
  __param(4, $U5),
  __param(5, $4J),
  __param(6, $6J)
], $A_b);

// out-build/vs/workbench/contrib/files/browser/editors/binaryFileEditor.js
var $B_b_1;
var $B_b = class $B_b2 extends $QUb {
  static {
    $B_b_1 = this;
  }
  static {
    this.ID = $otb;
  }
  constructor(group2, telemetryService, themeService, fb, storageService) {
    super($B_b_1.ID, group2, {
      openInternal: (input, options3) => this.gb(input, options3)
    }, telemetryService, themeService, storageService);
    this.fb = fb;
  }
  async gb(input, options3) {
    if (input instanceof $8vb && this.group.activeEditor) {
      const activeEditor = this.group.activeEditor;
      const untypedActiveEditor = activeEditor?.toUntyped();
      if (!untypedActiveEditor) {
        return;
      }
      let resolvedEditor = await this.fb.resolveEditor({
        ...untypedActiveEditor,
        options: {
          ...options3,
          override: EditorResolution.PICK
        }
      }, this.group);
      if (resolvedEditor === 2) {
        resolvedEditor = void 0;
      } else if (resolvedEditor === 1) {
        return;
      }
      if ($hL(resolvedEditor)) {
        for (const editor of resolvedEditor.editor instanceof $fub ? [resolvedEditor.editor.original, resolvedEditor.editor.modified] : [resolvedEditor.editor]) {
          if (editor instanceof $8vb) {
            editor.setForceOpenAsText();
            editor.setPreferredLanguageId($ptb);
          }
        }
      }
      await this.group.replaceEditors([{
        editor: activeEditor,
        replacement: resolvedEditor?.editor ?? input,
        options: {
          ...resolvedEditor?.options ?? options3
        }
      }]);
    }
  }
  getTitle() {
    return this.input ? this.input.getName() : localize(7041, null);
  }
};
$B_b = $B_b_1 = __decorate([
  __param(1, $zv),
  __param(2, $gs),
  __param(3, $4L),
  __param(4, $jv)
], $B_b);

// out-build/vs/workbench/contrib/files/browser/explorerService.js
var $D_b_1;
var $C_b = new $cG();
var $D_b = class $D_b2 {
  static {
    $D_b_1 = this;
  }
  static {
    this.a = 500;
  }
  // delay in ms to react to file changes to give our internal events a chance to react first
  constructor(m, n, o, q, t, u, v, w, hostService, x, y) {
    this.m = m;
    this.n = n;
    this.o = o;
    this.q = q;
    this.t = t;
    this.u = u;
    this.v = v;
    this.w = w;
    this.x = x;
    this.y = y;
    this.b = new $2c();
    this.k = [];
    this.d = this.n.getValue("explorer");
    this.h = new $hvb(this.o, this.u, this.m, this.n, this.x);
    this.b.add(this.h);
    this.b.add(this.m.onDidRunOperation((e) => this.z(e)));
    this.j = new $8h(async () => {
      const events = this.k;
      this.k = [];
      const types = [
        2
        /* FileChangeType.DELETED */
      ];
      if (this.d.sortOrder === "modified") {
        types.push(
          0
          /* FileChangeType.UPDATED */
        );
      }
      let shouldRefresh = false;
      this.roots.forEach((r2) => {
        if (this.g && !shouldRefresh) {
          shouldRefresh = doesFileEventAffect(r2, this.g, events, types);
        }
      });
      events.forEach((e) => {
        if (!shouldRefresh) {
          for (const resource of e.rawAdded) {
            const parent = this.h.findClosest($uh(resource));
            if (parent && !parent.getChild($sh(resource))) {
              shouldRefresh = true;
              break;
            }
          }
        }
      });
      if (shouldRefresh) {
        await this.refresh(false);
      }
    }, $D_b_1.a);
    this.b.add(this.m.onDidFilesChange((e) => {
      this.k.push(e);
      if (this.c) {
        return;
      }
      if (!this.j.isScheduled()) {
        this.j.schedule();
      }
    }));
    this.b.add(this.n.onDidChangeConfiguration((e) => this.B(e)));
    this.b.add(Event2.any(this.m.onDidChangeFileSystemProviderRegistrations, this.m.onDidChangeFileSystemProviderCapabilities)(async (e) => {
      let affected = false;
      this.h.roots.forEach((r2) => {
        if (r2.resource.scheme === e.scheme) {
          affected = true;
          r2.forgetChildren();
        }
      });
      if (affected) {
        if (this.g) {
          await this.g.setTreeInput();
        }
      }
    }));
    this.b.add(this.h.onDidChangeRoots(() => {
      this.g?.setTreeInput();
    }));
    this.b.add(hostService.onDidChangeFocus((hasFocus) => {
      if (hasFocus) {
        this.refresh(false);
      }
    }));
    this.l = new $2J((uri) => getRevealExcludes(n.getValue({ resource: uri })), (event) => event.affectsConfiguration("explorer.autoRevealExclude"), o, n);
    this.b.add(this.l);
  }
  get roots() {
    return this.h.roots;
  }
  get sortOrderConfiguration() {
    return {
      sortOrder: this.d.sortOrder,
      lexicographicOptions: this.d.sortOrderLexicographicOptions,
      reverse: this.d.sortOrderReverse
    };
  }
  registerView(contextProvider) {
    this.g = contextProvider;
  }
  getContext(respectMultiSelection, ignoreNestedChildren = false) {
    if (!this.g) {
      return [];
    }
    const items = new Set(this.g.getContext(respectMultiSelection));
    items.forEach((item) => {
      try {
        if (respectMultiSelection && !ignoreNestedChildren && this.g?.isItemCollapsed(item) && item.nestedChildren) {
          for (const child of item.nestedChildren) {
            items.add(child);
          }
        }
      } catch {
        return;
      }
    });
    return [...items];
  }
  async applyBulkEdit(edit3, options3) {
    const cancellationTokenSource = new $ad();
    const location3 = options3.progressLocation ?? 10;
    let progressOptions;
    if (location3 === 10) {
      progressOptions = {
        location: location3,
        title: options3.progressLabel,
        cancellable: edit3.length > 1
      };
    } else {
      progressOptions = {
        location: location3,
        title: options3.progressLabel,
        cancellable: edit3.length > 1,
        delay: 500
      };
    }
    const promise = this.w.withProgress(progressOptions, async (progress) => {
      await this.v.apply(edit3, {
        undoRedoSource: $C_b,
        label: options3.undoLabel,
        code: "undoredo.explorerOperation",
        progress,
        token: cancellationTokenSource.token,
        confirmBeforeUndo: options3.confirmBeforeUndo
      });
    }, () => cancellationTokenSource.cancel());
    await this.w.withProgress({ location: 1, delay: 500 }, () => promise);
    cancellationTokenSource.dispose();
  }
  hasViewFocus() {
    return !!this.g && this.g.hasFocus();
  }
  // IExplorerService methods
  findClosest(resource) {
    return this.h.findClosest(resource);
  }
  findClosestRoot(resource) {
    const parentRoots = this.h.roots.filter((r2) => this.u.extUri.isEqualOrParent(resource, r2.resource)).sort((first, second) => second.resource.path.length - first.resource.path.length);
    return parentRoots.length ? parentRoots[0] : null;
  }
  async setEditable(stat, data) {
    if (!this.g) {
      return;
    }
    if (!data) {
      this.c = void 0;
    } else {
      this.c = { stat, data };
    }
    const isEditing = this.isEditable(stat);
    try {
      await this.g.setEditable(stat, isEditing);
    } catch {
      const parent = stat.parent;
      const errorData = {
        parentIsDirectory: parent?.isDirectory,
        isDirectory: stat.isDirectory,
        isReadonly: !!stat.isReadonly,
        parentIsReadonly: !!parent?.isReadonly,
        parentIsExcluded: parent?.isExcluded,
        isExcluded: stat.isExcluded,
        parentIsRoot: parent?.isRoot,
        isRoot: stat.isRoot,
        parentHasNests: parent?.hasNests,
        hasNests: stat.hasNests
      };
      this.y.publicLogError2("explorerView.setEditableError", errorData);
      return;
    }
    if (!this.c && this.k.length && !this.j.isScheduled()) {
      this.j.schedule();
    }
  }
  async setToCopy(items, cut) {
    const previouslyCutItems = this.f;
    this.f = cut ? items : void 0;
    await this.q.writeResources(items.map((s) => s.resource));
    this.g?.itemsCopied(items, cut, previouslyCutItems);
  }
  isCut(item) {
    return !!this.f && this.f.some((i2) => this.u.extUri.isEqual(i2.resource, item.resource));
  }
  getEditable() {
    return this.c;
  }
  getEditableData(stat) {
    return this.c && this.c.stat === stat ? this.c.data : void 0;
  }
  isEditable(stat) {
    return !!this.c && (this.c.stat === stat || !stat);
  }
  async select(resource, reveal) {
    if (!this.g) {
      return;
    }
    const ignoreRevealExcludes = reveal === "force";
    const fileStat = this.findClosest(resource);
    if (fileStat) {
      if (!this.A(fileStat, ignoreRevealExcludes)) {
        return;
      }
      await this.g.selectResource(fileStat.resource, reveal);
      return Promise.resolve(void 0);
    }
    const options3 = {
      resolveTo: [resource],
      resolveMetadata: this.d.sortOrder === "modified"
      /* SortOrder.Modified */
    };
    const root = this.findClosestRoot(resource);
    if (!root) {
      return void 0;
    }
    try {
      const stat = await this.m.resolve(root.resource, options3);
      const modelStat = $ivb.create(this.m, this.n, this.x, stat, void 0, options3.resolveTo);
      $ivb.mergeLocalWithDisk(modelStat, root);
      const item = root.find(resource);
      await this.g.refresh(true, root);
      if (item && !this.A(item, ignoreRevealExcludes)) {
        return;
      }
      await this.g.selectResource(item ? item.resource : void 0, reveal);
    } catch (error) {
      root.error = error;
      await this.g.refresh(false, root);
    }
  }
  async refresh(reveal = true) {
    if (this.g?.hasPhantomElements()) {
      return;
    }
    this.h.roots.forEach((r2) => r2.forgetChildren());
    if (this.g) {
      await this.g.refresh(true);
      const resource = this.t.activeEditor?.resource;
      const autoReveal = this.n.getValue().explorer.autoReveal;
      if (reveal && resource && autoReveal) {
        this.select(resource, autoReveal);
      }
    }
  }
  // File events
  async z(e) {
    const shouldDeepRefresh = this.d.fileNesting.enabled;
    if (e.isOperation(
      0
      /* FileOperation.CREATE */
    ) || e.isOperation(
      3
      /* FileOperation.COPY */
    )) {
      const addedElement = e.target;
      const parentResource = $uh(addedElement.resource);
      const parents = this.h.findAll(parentResource);
      if (parents.length) {
        await Promise.all(parents.map(async (p) => {
          const resolveMetadata = this.d.sortOrder === `modified`;
          if (!p.isDirectoryResolved) {
            const stat = await this.m.resolve(p.resource, { resolveMetadata });
            if (stat) {
              const modelStat = $ivb.create(this.m, this.n, this.x, stat, p.parent);
              $ivb.mergeLocalWithDisk(modelStat, p);
            }
          }
          const childElement = $ivb.create(this.m, this.n, this.x, addedElement, p.parent);
          p.removeChild(childElement);
          p.addChild(childElement);
          await this.g?.refresh(shouldDeepRefresh, p);
        }));
      }
    } else if (e.isOperation(
      2
      /* FileOperation.MOVE */
    )) {
      const oldResource = e.resource;
      const newElement = e.target;
      const oldParentResource = $uh(oldResource);
      const newParentResource = $uh(newElement.resource);
      const modelElements = this.h.findAll(oldResource);
      const sameParentMove = modelElements.every((e2) => !e2.nestedParent) && this.u.extUri.isEqual(oldParentResource, newParentResource);
      if (sameParentMove) {
        await Promise.all(modelElements.map(async (modelElement) => {
          modelElement.rename(newElement);
          await this.g?.refresh(shouldDeepRefresh, modelElement.parent);
        }));
      } else {
        const newParents = this.h.findAll(newParentResource);
        if (newParents.length && modelElements.length) {
          await Promise.all(modelElements.map(async (modelElement, index) => {
            const oldParent = modelElement.parent;
            const oldNestedParent = modelElement.nestedParent;
            modelElement.move(newParents[index]);
            if (oldNestedParent) {
              await this.g?.refresh(false, oldNestedParent);
            }
            await this.g?.refresh(false, oldParent);
            await this.g?.refresh(shouldDeepRefresh, newParents[index]);
          }));
        }
      }
    } else if (e.isOperation(
      1
      /* FileOperation.DELETE */
    )) {
      const modelElements = this.h.findAll(e.resource);
      await Promise.all(modelElements.map(async (modelElement) => {
        if (modelElement.parent) {
          const parent = modelElement.parent;
          parent.removeChild(modelElement);
          this.g?.focusNext();
          const oldNestedParent = modelElement.nestedParent;
          if (oldNestedParent) {
            oldNestedParent.removeChild(modelElement);
            await this.g?.refresh(false, oldNestedParent);
          }
          await this.g?.refresh(shouldDeepRefresh, parent);
          if (this.g?.getFocus().length === 0) {
            this.g?.focusLast();
          }
        }
      }));
    }
  }
  // Check if an item matches a explorer.autoRevealExclude pattern
  A(item, ignore) {
    if (item === void 0 || ignore) {
      return true;
    }
    if (this.l.matches(item.resource, (name) => !!(item.parent && item.parent.getChild(name)))) {
      return false;
    }
    const root = item.root;
    let currentItem = item.parent;
    while (currentItem !== root) {
      if (currentItem === void 0) {
        return true;
      }
      if (this.l.matches(currentItem.resource)) {
        return false;
      }
      currentItem = currentItem.parent;
    }
    return true;
  }
  async B(event) {
    if (!event.affectsConfiguration("explorer")) {
      return;
    }
    let shouldRefresh = false;
    if (event.affectsConfiguration("explorer.fileNesting")) {
      shouldRefresh = true;
    }
    const configuration2 = this.n.getValue();
    const configSortOrder = configuration2?.explorer?.sortOrder || "default";
    if (this.d.sortOrder !== configSortOrder) {
      shouldRefresh = this.d.sortOrder !== void 0;
    }
    const configLexicographicOptions = configuration2?.explorer?.sortOrderLexicographicOptions || "default";
    if (this.d.sortOrderLexicographicOptions !== configLexicographicOptions) {
      shouldRefresh = shouldRefresh || this.d.sortOrderLexicographicOptions !== void 0;
    }
    const sortOrderReverse = configuration2?.explorer?.sortOrderReverse || false;
    if (this.d.sortOrderReverse !== sortOrderReverse) {
      shouldRefresh = shouldRefresh || this.d.sortOrderReverse !== void 0;
    }
    this.d = configuration2.explorer;
    if (shouldRefresh) {
      await this.refresh();
    }
  }
  dispose() {
    this.b.dispose();
  }
};
$D_b = $D_b_1 = __decorate([
  __param(0, $km),
  __param(1, $kl),
  __param(2, $Zk),
  __param(3, $30),
  __param(4, $mJ),
  __param(5, $vl),
  __param(6, $H_),
  __param(7, $TJ),
  __param(8, $S4),
  __param(9, $4J),
  __param(10, $zv)
], $D_b);
function doesFileEventAffect(item, view, events, types) {
  for (const [_name, child] of item.children) {
    if (view.isItemVisible(child)) {
      if (events.some((e) => e.contains(child.resource, ...types))) {
        return true;
      }
      if (child.isDirectory && child.isDirectoryResolved) {
        if (doesFileEventAffect(child, view, events, types)) {
          return true;
        }
      }
    }
  }
  return false;
}
function getRevealExcludes(configuration2) {
  const revealExcludes = configuration2 && configuration2.explorer && configuration2.explorer.autoRevealExclude;
  if (!revealExcludes) {
    return {};
  }
  return revealExcludes;
}

// out-build/vs/workbench/contrib/files/browser/workspaceWatcher.js
var $E_b = class $E_b2 extends $3c {
  static {
    this.ID = "workbench.contrib.workspaceWatcher";
  }
  constructor(b, c, f, g, h3, j, m, n) {
    super();
    this.b = b;
    this.c = c;
    this.f = f;
    this.g = g;
    this.h = h3;
    this.j = j;
    this.m = m;
    this.n = n;
    this.a = new $Ec((resource) => this.j.extUri.getComparisonKey(resource));
    this.r();
    this.C();
  }
  r() {
    this.B(this.f.onDidChangeWorkspaceFolders((e) => this.s(e)));
    this.B(this.f.onDidChangeWorkbenchState(() => this.t()));
    this.B(this.c.onDidChangeConfiguration((e) => this.u(e)));
    this.B(this.b.onDidWatchError((error) => this.w(error)));
  }
  s(e) {
    for (const removed of e.removed) {
      this.z(removed);
    }
    for (const added of e.added) {
      this.y(added);
    }
  }
  t() {
    this.C();
  }
  u(e) {
    if (e.affectsConfiguration("files.watcherExclude") || e.affectsConfiguration("files.watcherInclude")) {
      this.C();
    }
  }
  w(error) {
    const msg = error.toString();
    let reason = void 0;
    if (msg.indexOf("ENOSPC") >= 0) {
      reason = "ENOSPC";
      this.g.prompt(Severity2.Warning, localize(7405, null), [{
        label: localize(7406, null),
        run: () => this.h.open(URI.parse("https://go.microsoft.com/fwlink/?linkid=867693"))
      }], {
        sticky: true,
        neverShowAgain: { id: "ignoreEnospcError", isSecondary: true, scope: NeverShowAgainScope.WORKSPACE }
      });
    } else if (msg.indexOf("EUNKNOWN") >= 0) {
      reason = "EUNKNOWN";
      this.g.prompt(Severity2.Warning, localize(7407, null), [{
        label: localize(7408, null),
        run: () => this.m.reload()
      }], {
        sticky: true,
        priority: NotificationPriority.SILENT
        // reduce potential spam since we don't really know how often this fires
      });
    } else if (msg.indexOf("ETERM") >= 0) {
      reason = "ETERM";
    }
    if (reason) {
      this.n.publicLog2("fileWatcherError", { reason });
    }
  }
  y(workspace2) {
    const excludes = [];
    const config = this.c.getValue({ resource: workspace2.uri });
    if (config.files?.watcherExclude) {
      for (const key2 in config.files.watcherExclude) {
        if (key2 && config.files.watcherExclude[key2] === true) {
          excludes.push(key2);
        }
      }
    }
    const pathsToWatch = new $Ec((uri) => this.j.extUri.getComparisonKey(uri));
    pathsToWatch.set(workspace2.uri, workspace2.uri);
    if (config.files?.watcherInclude) {
      for (const includePath of config.files.watcherInclude) {
        if (!includePath) {
          continue;
        }
        if ($mc(includePath)) {
          const candidate = URI.file(includePath).with({ scheme: workspace2.uri.scheme });
          if (this.j.extUri.isEqualOrParent(candidate, workspace2.uri)) {
            pathsToWatch.set(candidate, candidate);
          }
        } else {
          const candidate = workspace2.toResource(includePath);
          pathsToWatch.set(candidate, candidate);
        }
      }
    }
    const disposables = new $2c();
    for (const [, pathToWatch] of pathsToWatch) {
      disposables.add(this.b.watch(pathToWatch, { recursive: true, excludes }));
    }
    this.a.set(workspace2.uri, disposables);
  }
  z(workspace2) {
    if (this.a.has(workspace2.uri)) {
      $Xc(this.a.get(workspace2.uri));
      this.a.delete(workspace2.uri);
    }
  }
  C() {
    this.D();
    for (const folder of this.f.getWorkspace().folders) {
      this.y(folder);
    }
  }
  D() {
    for (const [, disposable] of this.a) {
      disposable.dispose();
    }
    this.a.clear();
  }
  dispose() {
    super.dispose();
    this.D();
  }
};
$E_b = __decorate([
  __param(0, $km),
  __param(1, $kl),
  __param(2, $Zk),
  __param(3, $PJ),
  __param(4, $O4),
  __param(5, $vl),
  __param(6, $S4),
  __param(7, $zv)
], $E_b);

// out-build/vs/workbench/contrib/files/common/dirtyFilesIndicator.js
var $F_b = class $F_b2 extends $3c {
  static {
    this.ID = "workbench.contrib.dirtyFilesIndicator";
  }
  constructor(c, f, g) {
    super();
    this.c = c;
    this.f = f;
    this.g = g;
    this.a = this.B(new $4c());
    this.b = 0;
    this.m();
    this.h();
  }
  h() {
    this.B(this.f.onDidChangeDirty((workingCopy) => this.j(workingCopy)));
  }
  j(workingCopy) {
    const gotDirty = workingCopy.isDirty();
    if (gotDirty && !(workingCopy.capabilities & 2) && this.g.hasShortAutoSaveDelay(workingCopy.resource)) {
      return;
    }
    if (gotDirty || this.b > 0) {
      this.m();
    }
  }
  m() {
    const dirtyCount = this.b = this.f.dirtyCount;
    if (dirtyCount > 0) {
      this.a.value = this.c.showViewContainerActivity($3sb, {
        badge: new $wqb(dirtyCount, (num) => num === 1 ? localize(7409, null) : localize(7410, null, dirtyCount))
      });
    } else {
      this.a.clear();
    }
  }
};
$F_b = __decorate([
  __param(0, $vqb),
  __param(1, $XI),
  __param(2, $4J)
], $F_b);

// out-build/vs/workbench/contrib/files/browser/editors/fileEditorHandler.js
var $G_b = class {
  canSerialize(editorInput) {
    return true;
  }
  serialize(editorInput) {
    const fileEditorInput = editorInput;
    const resource = fileEditorInput.resource;
    const preferredResource = fileEditorInput.preferredResource;
    const serializedFileEditorInput = {
      resourceJSON: resource.toJSON(),
      preferredResourceJSON: $oh(resource, preferredResource) ? void 0 : preferredResource,
      // only storing preferredResource if it differs from the resource
      name: fileEditorInput.getPreferredName(),
      description: fileEditorInput.getPreferredDescription(),
      encoding: fileEditorInput.getEncoding(),
      modeId: fileEditorInput.getPreferredLanguageId()
      // only using the preferred user associated language here if available to not store redundant data
    };
    return JSON.stringify(serializedFileEditorInput);
  }
  deserialize(instantiationService, serializedEditorInput) {
    return instantiationService.invokeFunction((accessor) => {
      const serializedFileEditorInput = JSON.parse(serializedEditorInput);
      const resource = URI.revive(serializedFileEditorInput.resourceJSON);
      const preferredResource = URI.revive(serializedFileEditorInput.preferredResourceJSON);
      const name = serializedFileEditorInput.name;
      const description = serializedFileEditorInput.description;
      const encoding = serializedFileEditorInput.encoding;
      const languageId = serializedFileEditorInput.modeId;
      const fileEditorInput = accessor.get($YUb).createTextEditor({ resource, label: name, description, encoding, languageId, forceFile: true });
      if (preferredResource) {
        fileEditorInput.setPreferredResource(preferredResource);
      }
      return fileEditorInput;
    });
  }
};
var $H_b = class $H_b2 extends $3c {
  static {
    this.ID = "workbench.contrib.fileEditorWorkingCopyEditorHandler";
  }
  constructor(workingCopyEditorService, a, b) {
    super();
    this.a = a;
    this.b = b;
    this.B(workingCopyEditorService.registerHandler(this));
  }
  handles(workingCopy) {
    return workingCopy.typeId === $qG && this.b.canHandleResource(workingCopy.resource);
  }
  c(workingCopy) {
    return workingCopy.typeId === $qG && this.b.hasProvider(workingCopy.resource);
  }
  isOpen(workingCopy, editor) {
    if (!this.c(workingCopy)) {
      return false;
    }
    return $oh(workingCopy.resource, editor.resource);
  }
  createEditor(workingCopy) {
    return this.a.createTextEditor({ resource: workingCopy.resource, forceFile: true });
  }
};
$H_b = __decorate([
  __param(0, $6J),
  __param(1, $YUb),
  __param(2, $km)
], $H_b);

// out-build/vs/workbench/contrib/files/browser/editors/textFileEditor.js
var $I_b_1;
var $I_b = class $I_b2 extends $NUb {
  static {
    $I_b_1 = this;
  }
  static {
    this.ID = $mtb;
  }
  constructor(group2, telemetryService, fileService, f, instantiationService, $149, storageService, textResourceConfigurationService, editorService, themeService, editorGroupService, Xb, Yb, Zb, $b3, ac, bc, cc, dc) {
    super($I_b_1.ID, group2, telemetryService, instantiationService, storageService, textResourceConfigurationService, themeService, editorService, editorGroupService, fileService);
    this.f = f;
    this.$ = $149;
    this.Xb = Xb;
    this.Yb = Yb;
    this.Zb = Zb;
    this.$b = $b3;
    this.ac = ac;
    this.bc = bc;
    this.cc = cc;
    this.dc = dc;
    this.B(this.xb.onDidFilesChange((e) => this.ec(e)));
    this.B(this.xb.onDidRunOperation((e) => this.fc(e)));
  }
  ec(e) {
    for (const resource of e.rawDeleted) {
      this.lb(resource);
    }
  }
  fc(e) {
    if (e.operation === 2 && e.target) {
      this.kb(e.resource, e.target.resource, this.Zb.extUri);
    }
  }
  getTitle() {
    if (this.input) {
      return this.input.getName();
    }
    return localize(7042, null);
  }
  get input() {
    return this.W;
  }
  async setInput(input, options3, context, token) {
    $S("code/willSetInputToTextFileEditor");
    await super.setInput(input, options3, context, token);
    try {
      const resolvedModel = await input.resolve(options3);
      if (token.isCancellationRequested) {
        return;
      }
      if (resolvedModel instanceof $7vb) {
        return this.hc(input, options3);
      }
      const textFileModel = resolvedModel;
      const control = $Kg(this.a);
      control.setModel(textFileModel.textEditorModel);
      if (!$oL(options3?.viewState)) {
        const editorViewState = this.jb(input, context);
        if (editorViewState) {
          if (options3?.selection) {
            editorViewState.cursorState = [];
          }
          control.restoreViewState(editorViewState);
        }
      }
      if (options3) {
        applyTextEditorOptions(
          options3,
          control,
          1
          /* ScrollType.Immediate */
        );
      }
      control.updateOptions(this.Gb(textFileModel.isReadonly()));
      if (control.handleInitialized) {
        control.handleInitialized();
      }
    } catch (error) {
      await this.gc(error, input, options3);
    }
    $S("code/didSetInputToTextFileEditor");
  }
  async gc(error, input, options3) {
    if (error.textFileOperationResult === 0) {
      return this.hc(input, options3);
    }
    if (error.fileOperationResult === 0) {
      const actions = [];
      actions.push($Zm({
        id: "workbench.files.action.openFolder",
        label: localize(7043, null),
        run: async () => {
          return this.cc.openWindow([{ folderUri: input.resource }], { forceNewWindow: true });
        }
      }));
      if (this.$.isInsideWorkspace(input.preferredResource)) {
        actions.push($Zm({
          id: "workbench.files.action.reveal",
          label: localize(7044, null),
          run: async () => {
            await this.f.openPaneComposite($3sb, 0, true);
            return this.Yb.select(input.preferredResource, true);
          }
        }));
      }
      throw $qL(localize(7045, null), actions, { forceMessage: true });
    }
    if (error.fileOperationResult === 7) {
      let message;
      if (error instanceof $Gm) {
        message = localize(7046, null, $Sm.formatSize(error.size));
      } else {
        message = localize(7047, null);
      }
      throw $gL(this.group, input, options3, message, this.bc);
    }
    if (error.fileOperationResult === 1 && !this.dc.isReadonly(input.preferredResource) && await this.$b.hasValidBasename(input.preferredResource)) {
      const fileNotFoundError = $qL(new $Fm(
        localize(7048, null),
        1
        /* FileOperationResult.FILE_NOT_FOUND */
      ), [
        $Zm({
          id: "workbench.files.action.createMissingFile",
          label: localize(7049, null),
          run: async () => {
            await this.Xb.create([{ resource: input.preferredResource }]);
            return this.u.openEditor({
              resource: input.preferredResource,
              options: {
                pinned: true
                // new file gets pinned by default
              }
            });
          }
        })
      ], {
        // Support the flow of directly pressing `Enter` on the dialog to
        // create the file on the go. This is nice when for example following
        // a link to a file that does not exist to scaffold it quickly.
        allowDialog: true
      });
      throw fileNotFoundError;
    }
    throw error;
  }
  hc(input, options3) {
    const defaultBinaryEditor = this.ac.getValue("workbench.editor.defaultBinaryEditor");
    const editorOptions2 = {
      ...options3,
      // Make sure to not steal away the currently active group
      // because we are triggering another openEditor() call
      // and do not control the initial intent that resulted
      // in us now opening as binary.
      activation: EditorActivation.PRESERVE
    };
    if (defaultBinaryEditor && defaultBinaryEditor !== "" && defaultBinaryEditor !== $1K.id) {
      this.ic(this.group, defaultBinaryEditor, input, editorOptions2);
    } else {
      this.jc(this.group, defaultBinaryEditor, input, editorOptions2);
    }
  }
  ic(group2, editorId, editor, editorOptions2) {
    this.u.replaceEditors([{
      editor,
      replacement: { resource: editor.resource, options: { ...editorOptions2, override: editorId } }
    }], group2);
  }
  jc(group2, editorId, editor, editorOptions2) {
    if (editorId === $1K.id) {
      editor.setForceOpenAsText();
      editor.setPreferredLanguageId($ptb);
      editorOptions2 = { ...editorOptions2, forceReload: true };
    } else {
      editor.setForceOpenAsBinary();
    }
    group2.openEditor(editor, editorOptions2);
  }
  clearInput() {
    super.clearInput();
    this.a?.setModel(null);
  }
  Lb(parent, initialOptions) {
    $S("code/willCreateTextFileEditorControl");
    super.Lb(parent, initialOptions);
    $S("code/didCreateTextFileEditorControl");
  }
  nb(input) {
    return input instanceof $8vb;
  }
  ob() {
    return true;
  }
};
$I_b = $I_b_1 = __decorate([
  __param(1, $zv),
  __param(2, $km),
  __param(3, $uqb),
  __param(4, $Pk),
  __param(5, $Zk),
  __param(6, $jv),
  __param(7, $zG),
  __param(8, $mJ),
  __param(9, $gs),
  __param(10, $iJ),
  __param(11, $cK),
  __param(12, $kvb),
  __param(13, $vl),
  __param(14, $aT),
  __param(15, $kl),
  __param(16, $TK),
  __param(17, $S4),
  __param(18, $4J)
], $I_b);

// out-build/vs/workbench/contrib/files/browser/files.contribution.js
var FileUriLabelContribution = class FileUriLabelContribution2 {
  static {
    this.ID = "workbench.contrib.fileUriLabel";
  }
  constructor(labelService) {
    labelService.registerFormatter({
      scheme: Schemas.file,
      formatting: {
        label: "${authority}${path}",
        separator: sep,
        tildify: !$l,
        normalizeDriveLetter: $l,
        authorityPrefix: sep + sep,
        workspaceSuffix: ""
      }
    });
  }
};
FileUriLabelContribution = __decorate([
  __param(0, $ZI)
], FileUriLabelContribution);
$SC(
  $kvb,
  $D_b,
  1
  /* InstantiationType.Delayed */
);
$Wn.as($ZK.EditorPane).registerEditorPane($7tb.create($I_b, $I_b.ID, localize(7260, null)), [
  new $Nk($8vb)
]);
$Wn.as($ZK.EditorPane).registerEditorPane($7tb.create($B_b, $B_b.ID, localize(7261, null)), [
  new $Nk($8vb)
]);
$Wn.as($ZK.EditorFactory).registerFileEditorFactory({
  typeId: $ntb,
  createFileEditor: (resource, preferredResource, preferredName, preferredDescription, preferredEncoding, preferredLanguageId, preferredContents, instantiationService) => {
    return instantiationService.createInstance($8vb, resource, preferredResource, preferredName, preferredDescription, preferredEncoding, preferredLanguageId, preferredContents);
  },
  isFileEditor: (obj) => {
    return obj instanceof $8vb;
  }
});
$Wn.as($ZK.EditorFactory).registerEditorSerializer($ntb, $G_b);
$PL(
  $H_b.ID,
  $H_b,
  2
  /* WorkbenchPhase.BlockRestore */
);
$PL(
  $bzb.ID,
  $bzb,
  1
  /* WorkbenchPhase.BlockStartup */
);
$PL(
  $A_b.ID,
  $A_b,
  1
  /* WorkbenchPhase.BlockStartup */
);
$PL(
  $$vb.ID,
  $$vb,
  1
  /* WorkbenchPhase.BlockStartup */
);
$PL(
  FileUriLabelContribution.ID,
  FileUriLabelContribution,
  1
  /* WorkbenchPhase.BlockStartup */
);
$PL(
  $E_b.ID,
  $E_b,
  3
  /* WorkbenchPhase.AfterRestored */
);
$PL(
  $F_b.ID,
  $F_b,
  1
  /* WorkbenchPhase.BlockStartup */
);
var configurationRegistry10 = $Wn.as($Ht.Configuration);
var hotExitConfiguration = $p ? {
  "type": "string",
  "scope": 1,
  "enum": [$Jm.OFF, $Jm.ON_EXIT, $Jm.ON_EXIT_AND_WINDOW_CLOSE],
  "default": $Jm.ON_EXIT,
  "markdownEnumDescriptions": [
    localize(7262, null),
    localize(7263, null),
    localize(7264, null)
  ],
  "markdownDescription": localize(7265, null, $Jm.ON_EXIT, $Jm.ON_EXIT_AND_WINDOW_CLOSE)
} : {
  "type": "string",
  "scope": 1,
  "enum": [$Jm.OFF, $Jm.ON_EXIT_AND_WINDOW_CLOSE],
  "default": $Jm.ON_EXIT_AND_WINDOW_CLOSE,
  "markdownEnumDescriptions": [
    localize(7266, null),
    localize(7267, null)
  ],
  "markdownDescription": localize(7268, null, $Jm.ON_EXIT, $Jm.ON_EXIT_AND_WINDOW_CLOSE)
};
configurationRegistry10.registerConfiguration({
  "id": "files",
  "order": 9,
  "title": localize(7269, null),
  "type": "object",
  "properties": {
    [$Lm]: {
      "type": "object",
      "markdownDescription": localize(7270, null),
      "default": {
        ...{ "**/.git": true, "**/.svn": true, "**/.hg": true, "**/CVS": true, "**/.DS_Store": true, "**/Thumbs.db": true },
        ...$r ? {
          "**/*.crswap": true
          /* filter out swap files used for local file access */
        } : void 0
      },
      "scope": 4,
      "additionalProperties": {
        "anyOf": [
          {
            "type": "boolean",
            "enum": [true, false],
            "enumDescriptions": [localize(7271, null), localize(7272, null)],
            "description": localize(7273, null)
          },
          {
            "type": "object",
            "properties": {
              "when": {
                "type": "string",
                // expression ({ "**/*.js": { "when": "$(basename).js" } })
                "pattern": "\\w*\\$\\(basename\\)\\w*",
                "default": "$(basename).ext",
                "markdownDescription": localize(7274, null)
              }
            }
          }
        ]
      }
    },
    [$Km]: {
      "type": "object",
      "markdownDescription": localize(7275, null),
      "additionalProperties": {
        "type": "string"
      }
    },
    "files.encoding": {
      "type": "string",
      "enum": Object.keys($KJ),
      "default": "utf8",
      "description": localize(7276, null),
      "scope": 5,
      "enumDescriptions": Object.keys($KJ).map((key2) => $KJ[key2].labelLong),
      "enumItemLabels": Object.keys($KJ).map((key2) => $KJ[key2].labelLong)
    },
    "files.autoGuessEncoding": {
      "type": "boolean",
      "default": false,
      "markdownDescription": localize(7277, null, "`#files.encoding#`"),
      "scope": 5
      /* ConfigurationScope.LANGUAGE_OVERRIDABLE */
    },
    "files.candidateGuessEncodings": {
      "type": "array",
      "items": {
        "type": "string",
        "enum": Object.keys($LJ),
        "enumDescriptions": Object.keys($LJ).map((key2) => $LJ[key2].labelLong)
      },
      "default": [],
      "markdownDescription": localize(7278, null, "`#files.encoding#`"),
      "scope": 5
      /* ConfigurationScope.LANGUAGE_OVERRIDABLE */
    },
    "files.eol": {
      "type": "string",
      "enum": [
        "\n",
        "\r\n",
        "auto"
      ],
      "enumDescriptions": [
        localize(7279, null),
        localize(7280, null),
        localize(7281, null)
      ],
      "default": "auto",
      "description": localize(7282, null),
      "scope": 5
      /* ConfigurationScope.LANGUAGE_OVERRIDABLE */
    },
    "files.enableTrash": {
      "type": "boolean",
      "default": true,
      "description": localize(7283, null)
    },
    "files.trimTrailingWhitespace": {
      "type": "boolean",
      "default": false,
      "description": localize(7284, null),
      "scope": 5
      /* ConfigurationScope.LANGUAGE_OVERRIDABLE */
    },
    "files.trimTrailingWhitespaceInRegexAndStrings": {
      "type": "boolean",
      "default": true,
      "description": localize(7285, null),
      "scope": 5
      /* ConfigurationScope.LANGUAGE_OVERRIDABLE */
    },
    "files.insertFinalNewline": {
      "type": "boolean",
      "default": false,
      "description": localize(7286, null),
      "scope": 5
      /* ConfigurationScope.LANGUAGE_OVERRIDABLE */
    },
    "files.trimFinalNewlines": {
      "type": "boolean",
      "default": false,
      "description": localize(7287, null),
      scope: 5
    },
    "files.autoSave": {
      "type": "string",
      "enum": [$Im.OFF, $Im.AFTER_DELAY, $Im.ON_FOCUS_CHANGE, $Im.ON_WINDOW_CHANGE],
      "markdownEnumDescriptions": [
        localize(7288, null),
        localize(7289, null),
        localize(7290, null),
        localize(7291, null)
      ],
      "default": $r ? $Im.AFTER_DELAY : $Im.OFF,
      "markdownDescription": localize(7292, null, $Im.OFF, $Im.AFTER_DELAY, $Im.ON_FOCUS_CHANGE, $Im.ON_WINDOW_CHANGE, $Im.AFTER_DELAY),
      scope: 5
      /* ConfigurationScope.LANGUAGE_OVERRIDABLE */
    },
    "files.autoSaveDelay": {
      "type": "number",
      "default": 1e3,
      "minimum": 0,
      "markdownDescription": localize(7293, null, $Im.AFTER_DELAY),
      scope: 5
      /* ConfigurationScope.LANGUAGE_OVERRIDABLE */
    },
    "files.autoSaveWorkspaceFilesOnly": {
      "type": "boolean",
      "default": false,
      "markdownDescription": localize(7294, null, "`#files.autoSave#`"),
      scope: 5
      /* ConfigurationScope.LANGUAGE_OVERRIDABLE */
    },
    "files.autoSaveWhenNoErrors": {
      "type": "boolean",
      "default": false,
      "markdownDescription": localize(7295, null, "`#files.autoSave#`"),
      scope: 5
      /* ConfigurationScope.LANGUAGE_OVERRIDABLE */
    },
    "files.watcherExclude": {
      "type": "object",
      "patternProperties": {
        ".*": { "type": "boolean" }
      },
      "default": { "**/.git/objects/**": true, "**/.git/subtree-cache/**": true, "**/.hg/store/**": true },
      "markdownDescription": localize(7296, null),
      "scope": 4
      /* ConfigurationScope.RESOURCE */
    },
    "files.watcherInclude": {
      "type": "array",
      "items": {
        "type": "string"
      },
      "default": [],
      "description": localize(7297, null),
      "scope": 4
      /* ConfigurationScope.RESOURCE */
    },
    "files.hotExit": hotExitConfiguration,
    "files.defaultLanguage": {
      "type": "string",
      "markdownDescription": localize(7298, null)
    },
    [$Mm]: {
      "type": "object",
      "patternProperties": {
        ".*": { "type": "boolean" }
      },
      "default": {},
      "markdownDescription": localize(7299, null),
      "scope": 4
      /* ConfigurationScope.RESOURCE */
    },
    [$Nm]: {
      "type": "object",
      "patternProperties": {
        ".*": { "type": "boolean" }
      },
      "default": {},
      "markdownDescription": localize(7300, null),
      "scope": 4
      /* ConfigurationScope.RESOURCE */
    },
    [$Om]: {
      "type": "boolean",
      "markdownDescription": localize(7301, null),
      "default": false
    },
    "files.restoreUndoStack": {
      "type": "boolean",
      "description": localize(7302, null),
      "default": true
    },
    "files.saveConflictResolution": {
      "type": "string",
      "enum": [
        "askUser",
        "overwriteFileOnDisk"
      ],
      "enumDescriptions": [
        localize(7303, null),
        localize(7304, null)
      ],
      "description": localize(7305, null),
      "default": "askUser",
      "scope": 5
      /* ConfigurationScope.LANGUAGE_OVERRIDABLE */
    },
    "files.dialog.defaultPath": {
      "type": "string",
      "pattern": "^((\\/|\\\\\\\\|[a-zA-Z]:\\\\).*)?$",
      // slash OR UNC-root OR drive-root OR undefined
      "patternErrorMessage": localize(7306, null),
      "description": localize(7307, null),
      "scope": 2
      /* ConfigurationScope.MACHINE */
    },
    "files.simpleDialog.enable": {
      "type": "boolean",
      "description": localize(7308, null),
      "default": false
    },
    "files.participants.timeout": {
      type: "number",
      default: 6e4,
      markdownDescription: localize(7309, null)
    }
  }
});
configurationRegistry10.registerConfiguration({
  ...$mab,
  properties: {
    "editor.formatOnSave": {
      "type": "boolean",
      "markdownDescription": localize(7310, null, "`#files.autoSave#`"),
      "scope": 5
    },
    "editor.formatOnSaveMode": {
      "type": "string",
      "default": "file",
      "enum": [
        "file",
        "modifications",
        "modificationsIfAvailable"
      ],
      "enumDescriptions": [
        localize(7311, null),
        localize(7312, null),
        localize(7313, null)
      ],
      "markdownDescription": localize(7314, null),
      "scope": 5
    }
  }
});
configurationRegistry10.registerConfiguration({
  "id": "explorer",
  "order": 10,
  "title": localize(7315, null),
  "type": "object",
  "properties": {
    "explorer.openEditors.visible": {
      "type": "number",
      "description": localize(7316, null),
      "default": 9,
      "minimum": 1
    },
    "explorer.openEditors.minVisible": {
      "type": "number",
      "description": localize(7317, null),
      "default": 0,
      "minimum": 0
    },
    "explorer.openEditors.sortOrder": {
      "type": "string",
      "enum": ["editorOrder", "alphabetical", "fullPath"],
      "description": localize(7318, null),
      "enumDescriptions": [
        localize(7319, null),
        localize(7320, null),
        localize(7321, null)
      ],
      "default": "editorOrder"
    },
    "explorer.autoReveal": {
      "type": ["boolean", "string"],
      "enum": [true, false, "focusNoScroll"],
      "default": true,
      "enumDescriptions": [
        localize(7322, null),
        localize(7323, null),
        localize(7324, null)
      ],
      "description": localize(7325, null)
    },
    "explorer.autoRevealExclude": {
      "type": "object",
      "markdownDescription": localize(7326, null),
      "default": { "**/node_modules": true, "**/bower_components": true },
      "additionalProperties": {
        "anyOf": [
          {
            "type": "boolean",
            "description": localize(7327, null)
          },
          {
            type: "object",
            properties: {
              when: {
                type: "string",
                // expression ({ "**/*.js": { "when": "$(basename).js" } })
                pattern: "\\w*\\$\\(basename\\)\\w*",
                default: "$(basename).ext",
                description: localize(7328, null)
              }
            }
          }
        ]
      }
    },
    "explorer.enableDragAndDrop": {
      "type": "boolean",
      "description": localize(7329, null),
      "default": true
    },
    "explorer.confirmDragAndDrop": {
      "type": "boolean",
      "description": localize(7330, null),
      "default": true
    },
    "explorer.confirmPasteNative": {
      "type": "boolean",
      "description": localize(7331, null),
      "default": true
    },
    "explorer.confirmDelete": {
      "type": "boolean",
      "description": localize(7332, null),
      "default": true
    },
    "explorer.enableUndo": {
      "type": "boolean",
      "description": localize(7333, null),
      "default": true
    },
    "explorer.confirmUndo": {
      "type": "string",
      "enum": [
        "verbose",
        "default",
        "light"
        /* UndoConfirmLevel.Light */
      ],
      "description": localize(7334, null),
      "default": "default",
      "enumDescriptions": [
        localize(7335, null),
        localize(7336, null),
        localize(7337, null)
      ]
    },
    "explorer.expandSingleFolderWorkspaces": {
      "type": "boolean",
      "description": localize(7338, null),
      "default": true
    },
    "explorer.sortOrder": {
      "type": "string",
      "enum": [
        "default",
        "mixed",
        "filesFirst",
        "type",
        "modified",
        "foldersNestsFiles"
        /* SortOrder.FoldersNestsFiles */
      ],
      "default": "default",
      "enumDescriptions": [
        localize(7339, null),
        localize(7340, null),
        localize(7341, null),
        localize(7342, null),
        localize(7343, null),
        localize(7344, null)
      ],
      "markdownDescription": localize(7345, null)
    },
    "explorer.sortOrderLexicographicOptions": {
      "type": "string",
      "enum": [
        "default",
        "upper",
        "lower",
        "unicode"
        /* LexicographicOptions.Unicode */
      ],
      "default": "default",
      "enumDescriptions": [
        localize(7346, null),
        localize(7347, null),
        localize(7348, null),
        localize(7349, null)
      ],
      "description": localize(7350, null)
    },
    "explorer.sortOrderReverse": {
      "type": "boolean",
      "description": localize(7351, null),
      "default": false
    },
    "explorer.decorations.colors": {
      type: "boolean",
      description: localize(7352, null),
      default: true
    },
    "explorer.decorations.badges": {
      type: "boolean",
      description: localize(7353, null),
      default: true
    },
    "explorer.incrementalNaming": {
      "type": "string",
      enum: ["simple", "smart", "disabled"],
      enumDescriptions: [
        localize(7354, null),
        localize(7355, null),
        localize(7356, null)
      ],
      description: localize(7357, null),
      default: "simple"
    },
    "explorer.autoOpenDroppedFile": {
      "type": "boolean",
      "description": localize(7358, null),
      "default": true
    },
    "explorer.compactFolders": {
      "type": "boolean",
      "description": localize(7359, null),
      "default": true
    },
    "explorer.copyRelativePathSeparator": {
      "type": "string",
      "enum": [
        "/",
        "\\",
        "auto"
      ],
      "enumDescriptions": [
        localize(7360, null),
        localize(7361, null),
        localize(7362, null)
      ],
      "description": localize(7363, null),
      "default": "auto"
    },
    "explorer.excludeGitIgnore": {
      type: "boolean",
      markdownDescription: localize(7364, null, "`#files.exclude#`"),
      default: false,
      scope: 4
      /* ConfigurationScope.RESOURCE */
    },
    "explorer.fileNesting.enabled": {
      "type": "boolean",
      scope: 4,
      "markdownDescription": localize(7365, null),
      "default": false
    },
    "explorer.fileNesting.expand": {
      "type": "boolean",
      "markdownDescription": localize(7366, null, "`#explorer.fileNesting.enabled#`"),
      "default": true
    },
    "explorer.fileNesting.patterns": {
      "type": "object",
      scope: 4,
      "markdownDescription": localize(7367, null, "`#explorer.fileNesting.enabled#`"),
      patternProperties: {
        "^[^*]*\\*?[^*]*$": {
          markdownDescription: localize(7368, null),
          type: "string",
          pattern: "^([^,*]*\\*?[^,*]*)(, ?[^,*]*\\*?[^,*]*)*$"
        }
      },
      additionalProperties: false,
      "default": {
        "*.ts": "${capture}.js",
        "*.js": "${capture}.js.map, ${capture}.min.js, ${capture}.d.ts",
        "*.jsx": "${capture}.js",
        "*.tsx": "${capture}.ts",
        "tsconfig.json": "tsconfig.*.json",
        "package.json": "package-lock.json, yarn.lock, pnpm-lock.yaml, bun.lockb"
      }
    }
  }
});
$05.addImplementation(110, "explorer", (accessor) => {
  const undoRedoService = accessor.get($_F);
  const explorerService = accessor.get($kvb);
  const configurationService = accessor.get($kl);
  const explorerCanUndo = configurationService.getValue().explorer.enableUndo;
  if (explorerService.hasViewFocus() && undoRedoService.canUndo($C_b) && explorerCanUndo) {
    undoRedoService.undo($C_b);
    return true;
  }
  return false;
});
$$5.addImplementation(110, "explorer", (accessor) => {
  const undoRedoService = accessor.get($_F);
  const explorerService = accessor.get($kvb);
  const configurationService = accessor.get($kl);
  const explorerCanUndo = configurationService.getValue().explorer.enableUndo;
  if (explorerService.hasViewFocus() && undoRedoService.canRedo($C_b) && explorerCanUndo) {
    undoRedoService.redo($C_b);
    return true;
  }
  return false;
});
$JF.registerLanguage({
  id: $ptb,
  aliases: ["Binary"],
  mimetypes: ["text/x-code-binary"]
});

// out-build/vs/workbench/contrib/bulkEdit/browser/bulkFileEdits.js
var RenameOperation_1;
var Noop = class {
  constructor() {
    this.uris = [];
  }
  async perform() {
    return this;
  }
  toString() {
    return "(noop)";
  }
};
var RenameEdit = class {
  constructor(newUri, oldUri, options3) {
    this.newUri = newUri;
    this.oldUri = oldUri;
    this.options = options3;
    this.type = "rename";
  }
};
var RenameOperation = RenameOperation_1 = class RenameOperation2 {
  constructor(a, b, c, d) {
    this.a = a;
    this.b = b;
    this.c = c;
    this.d = d;
  }
  get uris() {
    return this.a.flatMap((edit3) => [edit3.newUri, edit3.oldUri]);
  }
  async perform(token) {
    const moves = [];
    const undoes = [];
    for (const edit3 of this.a) {
      const skip = edit3.options.overwrite === void 0 && edit3.options.ignoreIfExists && await this.d.exists(edit3.newUri);
      if (!skip) {
        moves.push({
          file: { source: edit3.oldUri, target: edit3.newUri },
          overwrite: edit3.options.overwrite
        });
        undoes.push(new RenameEdit(edit3.oldUri, edit3.newUri, edit3.options));
      }
    }
    if (moves.length === 0) {
      return new Noop();
    }
    await this.c.move(moves, token, this.b);
    return new RenameOperation_1(undoes, { isUndoing: true }, this.c, this.d);
  }
  toString() {
    return `(rename ${this.a.map((edit3) => `${edit3.oldUri} to ${edit3.newUri}`).join(", ")})`;
  }
};
RenameOperation = RenameOperation_1 = __decorate([
  __param(2, $aK),
  __param(3, $km)
], RenameOperation);
var CopyEdit = class {
  constructor(newUri, oldUri, options3) {
    this.newUri = newUri;
    this.oldUri = oldUri;
    this.options = options3;
    this.type = "copy";
  }
};
var CopyOperation = class CopyOperation2 {
  constructor(a, b, c, d, e) {
    this.a = a;
    this.b = b;
    this.c = c;
    this.d = d;
    this.e = e;
  }
  get uris() {
    return this.a.flatMap((edit3) => [edit3.newUri, edit3.oldUri]);
  }
  async perform(token) {
    const copies = [];
    for (const edit3 of this.a) {
      const skip = edit3.options.overwrite === void 0 && edit3.options.ignoreIfExists && await this.d.exists(edit3.newUri);
      if (!skip) {
        copies.push({ file: { source: edit3.oldUri, target: edit3.newUri }, overwrite: edit3.options.overwrite });
      }
    }
    if (copies.length === 0) {
      return new Noop();
    }
    const stats = await this.c.copy(copies, token, this.b);
    const undoes = [];
    for (let i2 = 0; i2 < stats.length; i2++) {
      const stat = stats[i2];
      const edit3 = this.a[i2];
      undoes.push(new DeleteEdit(stat.resource, { recursive: true, folder: this.a[i2].options.folder || stat.isDirectory, ...edit3.options }, false));
    }
    return this.e.createInstance(DeleteOperation, undoes, { isUndoing: true });
  }
  toString() {
    return `(copy ${this.a.map((edit3) => `${edit3.oldUri} to ${edit3.newUri}`).join(", ")})`;
  }
};
CopyOperation = __decorate([
  __param(2, $aK),
  __param(3, $km),
  __param(4, $Pk)
], CopyOperation);
var CreateEdit = class {
  constructor(newUri, options3, contents) {
    this.newUri = newUri;
    this.options = options3;
    this.contents = contents;
    this.type = "create";
  }
};
var CreateOperation = class CreateOperation2 {
  constructor(a, b, c, d, e, f) {
    this.a = a;
    this.b = b;
    this.c = c;
    this.d = d;
    this.e = e;
    this.f = f;
  }
  get uris() {
    return this.a.map((edit3) => edit3.newUri);
  }
  async perform(token) {
    const folderCreates = [];
    const fileCreates = [];
    const undoes = [];
    for (const edit3 of this.a) {
      if (edit3.newUri.scheme === Schemas.untitled) {
        continue;
      }
      if (edit3.options.overwrite === void 0 && edit3.options.ignoreIfExists && await this.c.exists(edit3.newUri)) {
        continue;
      }
      if (edit3.options.folder) {
        folderCreates.push({ resource: edit3.newUri });
      } else {
        const encodedReadable = typeof edit3.contents !== "undefined" ? edit3.contents : await this.f.getEncodedReadable(edit3.newUri);
        fileCreates.push({ resource: edit3.newUri, contents: encodedReadable, overwrite: edit3.options.overwrite });
      }
      undoes.push(new DeleteEdit(edit3.newUri, edit3.options, !edit3.options.folder && !edit3.contents));
    }
    if (folderCreates.length === 0 && fileCreates.length === 0) {
      return new Noop();
    }
    await this.d.createFolder(folderCreates, token, this.b);
    await this.d.create(fileCreates, token, this.b);
    return this.e.createInstance(DeleteOperation, undoes, { isUndoing: true });
  }
  toString() {
    return `(create ${this.a.map((edit3) => edit3.options.folder ? `folder ${edit3.newUri}` : `file ${edit3.newUri} with ${edit3.contents?.byteLength || 0} bytes`).join(", ")})`;
  }
};
CreateOperation = __decorate([
  __param(2, $km),
  __param(3, $aK),
  __param(4, $Pk),
  __param(5, $cK)
], CreateOperation);
var DeleteEdit = class {
  constructor(oldUri, options3, undoesCreate) {
    this.oldUri = oldUri;
    this.options = options3;
    this.undoesCreate = undoesCreate;
    this.type = "delete";
  }
};
var DeleteOperation = class DeleteOperation2 {
  constructor(a, b, c, d, e, f, g) {
    this.a = a;
    this.b = b;
    this.c = c;
    this.d = d;
    this.e = e;
    this.f = f;
    this.g = g;
  }
  get uris() {
    return this.a.map((edit3) => edit3.oldUri);
  }
  async perform(token) {
    const deletes = [];
    const undoes = [];
    for (const edit3 of this.a) {
      let fileStat;
      try {
        fileStat = await this.d.resolve(edit3.oldUri, { resolveMetadata: true });
      } catch (err) {
        if (!edit3.options.ignoreIfNotExists) {
          throw new Error(`${edit3.oldUri} does not exist and can not be deleted`);
        }
        continue;
      }
      deletes.push({
        resource: edit3.oldUri,
        recursive: edit3.options.recursive,
        useTrash: !edit3.options.skipTrashBin && this.d.hasCapability(
          edit3.oldUri,
          4096
          /* FileSystemProviderCapabilities.Trash */
        ) && this.e.getValue("files.enableTrash")
      });
      let fileContent;
      if (!edit3.undoesCreate && !edit3.options.folder && !(typeof edit3.options.maxSize === "number" && fileStat.size > edit3.options.maxSize)) {
        try {
          fileContent = await this.d.readFile(edit3.oldUri);
        } catch (err) {
          this.g.error(err);
        }
      }
      if (fileContent !== void 0) {
        undoes.push(new CreateEdit(edit3.oldUri, edit3.options, fileContent.value));
      }
    }
    if (deletes.length === 0) {
      return new Noop();
    }
    await this.c.delete(deletes, token, this.b);
    if (undoes.length === 0) {
      return new Noop();
    }
    return this.f.createInstance(CreateOperation, undoes, { isUndoing: true });
  }
  toString() {
    return `(delete ${this.a.map((edit3) => edit3.oldUri).join(", ")})`;
  }
};
DeleteOperation = __decorate([
  __param(2, $aK),
  __param(3, $km),
  __param(4, $kl),
  __param(5, $Pk),
  __param(6, $wn)
], DeleteOperation);
var FileUndoRedoElement = class {
  constructor(label3, code, operations, confirmBeforeUndo) {
    this.label = label3;
    this.code = code;
    this.operations = operations;
    this.confirmBeforeUndo = confirmBeforeUndo;
    this.type = 1;
    this.resources = operations.flatMap((op) => op.uris);
  }
  async undo() {
    await this.a();
  }
  async redo() {
    await this.a();
  }
  async a() {
    for (let i2 = 0; i2 < this.operations.length; i2++) {
      const op = this.operations[i2];
      const undo = await op.perform(CancellationToken.None);
      this.operations[i2] = undo;
    }
  }
  toString() {
    return this.operations.map((op) => String(op)).join(", ");
  }
};
var $J_b = class $J_b2 {
  constructor(a, b, c, d, e, f, g, h3, j, k) {
    this.a = a;
    this.b = b;
    this.c = c;
    this.d = d;
    this.e = e;
    this.f = f;
    this.g = g;
    this.h = h3;
    this.j = j;
    this.k = k;
  }
  async apply() {
    const undoOperations = [];
    const undoRedoInfo = { undoRedoGroupId: this.c.id };
    const edits = [];
    for (const edit3 of this.h) {
      if (edit3.newResource && edit3.oldResource && !edit3.options?.copy) {
        edits.push(new RenameEdit(edit3.newResource, edit3.oldResource, edit3.options ?? {}));
      } else if (edit3.newResource && edit3.oldResource && edit3.options?.copy) {
        edits.push(new CopyEdit(edit3.newResource, edit3.oldResource, edit3.options ?? {}));
      } else if (!edit3.newResource && edit3.oldResource) {
        edits.push(new DeleteEdit(edit3.oldResource, edit3.options ?? {}, false));
      } else if (edit3.newResource && !edit3.oldResource) {
        edits.push(new CreateEdit(edit3.newResource, edit3.options ?? {}, await edit3.options.contents));
      }
    }
    if (edits.length === 0) {
      return [];
    }
    const groups = [];
    groups[0] = [edits[0]];
    for (let i2 = 1; i2 < edits.length; i2++) {
      const edit3 = edits[i2];
      const lastGroup = groups.at(-1);
      if (lastGroup?.[0].type === edit3.type) {
        lastGroup.push(edit3);
      } else {
        groups.push([edit3]);
      }
    }
    for (const group2 of groups) {
      if (this.g.isCancellationRequested) {
        break;
      }
      let op;
      switch (group2[0].type) {
        case "rename":
          op = this.j.createInstance(RenameOperation, group2, undoRedoInfo);
          break;
        case "copy":
          op = this.j.createInstance(CopyOperation, group2, undoRedoInfo);
          break;
        case "delete":
          op = this.j.createInstance(DeleteOperation, group2, undoRedoInfo);
          break;
        case "create":
          op = this.j.createInstance(CreateOperation, group2, undoRedoInfo);
          break;
      }
      if (op) {
        const undoOp = await op.perform(this.g);
        undoOperations.push(undoOp);
      }
      this.f.report(void 0);
    }
    const undoRedoElement = new FileUndoRedoElement(this.a, this.b, undoOperations, this.e);
    this.k.pushElement(undoRedoElement, this.c, this.d);
    return undoRedoElement.resources;
  }
};
$J_b = __decorate([
  __param(8, $Pk),
  __param(9, $_F)
], $J_b);

// out-build/vs/workbench/contrib/bulkEdit/browser/bulkTextEdits.js
var ModelEditTask = class {
  constructor(g) {
    this.g = g;
    this.model = this.g.object.textEditorModel;
    this.d = [];
  }
  dispose() {
    this.g.dispose();
  }
  isNoOp() {
    if (this.d.length > 0) {
      return false;
    }
    if (this.f !== void 0 && this.f !== this.model.getEndOfLineSequence()) {
      return false;
    }
    return true;
  }
  addEdit(resourceEdit) {
    this.c = resourceEdit.versionId;
    const { textEdit } = resourceEdit;
    if (typeof textEdit.eol === "number") {
      this.f = textEdit.eol;
    }
    if (!textEdit.range && !textEdit.text) {
      return;
    }
    if ($9C.isEmpty(textEdit.range) && !textEdit.text) {
      return;
    }
    let range;
    if (!textEdit.range) {
      range = this.model.getFullModelRange();
    } else {
      range = $9C.lift(textEdit.range);
    }
    this.d.push({ ...$bD.replaceMove(range, textEdit.text), insertAsSnippet: textEdit.insertAsSnippet });
  }
  validate() {
    if (typeof this.c === "undefined" || this.model.getVersionId() === this.c) {
      return { canApply: true };
    }
    return { canApply: false, reason: this.model.uri };
  }
  getBeforeCursorState() {
    return null;
  }
  apply() {
    if (this.d.length > 0) {
      this.d = this.d.map(this.h, this).sort((a, b) => $9C.compareRangesUsingStarts(a.range, b.range));
      this.model.pushEditOperations(null, this.d, () => null);
    }
    if (this.f !== void 0) {
      this.model.pushEOL(this.f);
    }
  }
  h(edit3) {
    if (!edit3.insertAsSnippet) {
      return edit3;
    }
    if (!edit3.text) {
      return edit3;
    }
    const text2 = $0_.asInsertText(edit3.text);
    return { ...edit3, insertAsSnippet: false, text: text2 };
  }
};
var EditorEditTask = class extends ModelEditTask {
  constructor(modelReference, editor) {
    super(modelReference);
    this.j = editor;
  }
  getBeforeCursorState() {
    return this.k() ? this.j.getSelections() : null;
  }
  apply() {
    if (!this.k()) {
      super.apply();
      return;
    }
    if (this.d.length > 0) {
      const snippetCtrl = $Dcb.get(this.j);
      if (snippetCtrl && this.d.some((edit3) => edit3.insertAsSnippet)) {
        const snippetEdits = [];
        for (const edit3 of this.d) {
          if (edit3.range && edit3.text !== null) {
            snippetEdits.push({
              range: $9C.lift(edit3.range),
              template: edit3.insertAsSnippet ? edit3.text : $0_.escape(edit3.text)
            });
          }
        }
        snippetCtrl.apply(snippetEdits, { undoStopBefore: false, undoStopAfter: false });
      } else {
        this.d = this.d.map(this.h, this).sort((a, b) => $9C.compareRangesUsingStarts(a.range, b.range));
        this.j.executeEdits("", this.d);
      }
    }
    if (this.f !== void 0) {
      if (this.j.hasModel()) {
        this.j.getModel().pushEOL(this.f);
      }
    }
  }
  k() {
    return this.j?.getModel()?.uri.toString() === this.model.uri.toString();
  }
};
var $K_b = class $K_b2 {
  constructor(d, f, g, h3, j, k, l, edits, m, n, o, p) {
    this.d = d;
    this.f = f;
    this.g = g;
    this.h = h3;
    this.j = j;
    this.k = k;
    this.l = l;
    this.m = m;
    this.n = n;
    this.o = o;
    this.p = p;
    this.c = new $Ec();
    for (const edit3 of edits) {
      let array2 = this.c.get(edit3.resource);
      if (!array2) {
        array2 = [];
        this.c.set(edit3.resource, array2);
      }
      array2.push(edit3);
    }
  }
  q() {
    for (const array2 of this.c.values()) {
      for (const edit3 of array2) {
        if (typeof edit3.versionId === "number") {
          const model = this.n.getModel(edit3.resource);
          if (model && model.getVersionId() !== edit3.versionId) {
            throw new Error(`${model.uri.toString()} has changed in the meantime`);
          }
        }
      }
    }
  }
  async r() {
    const tasks2 = [];
    const promises = [];
    for (const [key2, edits] of this.c) {
      const promise = this.o.createModelReference(key2).then(async (ref) => {
        let task;
        let makeMinimal = false;
        if (this.g?.getModel()?.uri.toString() === ref.object.textEditorModel.uri.toString()) {
          task = new EditorEditTask(ref, this.g);
          makeMinimal = true;
        } else {
          task = new ModelEditTask(ref);
        }
        tasks2.push(task);
        if (!makeMinimal) {
          edits.forEach(task.addEdit, task);
          return;
        }
        const makeGroupMoreMinimal = async (start2, end) => {
          const oldEdits = edits.slice(start2, end);
          const newEdits = await this.m.computeMoreMinimalEdits(ref.object.textEditorModel.uri, oldEdits.map((e) => e.textEdit), false);
          if (!newEdits) {
            oldEdits.forEach(task.addEdit, task);
          } else {
            newEdits.forEach((edit3) => task.addEdit(new $J_(ref.object.textEditorModel.uri, edit3, void 0, void 0)));
          }
        };
        let start = 0;
        let i2 = 0;
        for (; i2 < edits.length; i2++) {
          if (edits[i2].textEdit.insertAsSnippet || edits[i2].metadata) {
            await makeGroupMoreMinimal(start, i2);
            task.addEdit(edits[i2]);
            start = i2 + 1;
          }
        }
        await makeGroupMoreMinimal(start, i2);
      });
      promises.push(promise);
    }
    await Promise.all(promises);
    return tasks2;
  }
  s(tasks2) {
    for (const task of tasks2) {
      const result = task.validate();
      if (!result.canApply) {
        return result;
      }
    }
    return { canApply: true };
  }
  async apply() {
    this.q();
    const tasks2 = await this.r();
    try {
      if (this.l.isCancellationRequested) {
        return [];
      }
      const resources = [];
      const validation = this.s(tasks2);
      if (!validation.canApply) {
        throw new Error(`${validation.reason.toString()} has changed in the meantime`);
      }
      if (tasks2.length === 1) {
        const task = tasks2[0];
        if (!task.isNoOp()) {
          const singleModelEditStackElement = new $QH(this.d, this.f, task.model, task.getBeforeCursorState());
          this.p.pushElement(singleModelEditStackElement, this.h, this.j);
          task.apply();
          singleModelEditStackElement.close();
          resources.push(task.model.uri);
        }
        this.k.report(void 0);
      } else {
        const multiModelEditStackElement = new $RH(this.d, this.f, tasks2.map((t) => new $QH(this.d, this.f, t.model, t.getBeforeCursorState())));
        this.p.pushElement(multiModelEditStackElement, this.h, this.j);
        for (const task of tasks2) {
          task.apply();
          this.k.report(void 0);
          resources.push(task.model.uri);
        }
        multiModelEditStackElement.close();
      }
      return resources;
    } finally {
      $Xc(tasks2);
    }
  }
};
$K_b = __decorate([
  __param(8, $I0),
  __param(9, $sG),
  __param(10, $oG),
  __param(11, $_F)
], $K_b);

// out-build/vs/workbench/contrib/bulkEdit/browser/opaqueEdits.js
var $L_b = class _$L_b extends $I_ {
  static is(candidate) {
    if (candidate instanceof _$L_b) {
      return true;
    } else {
      return $Bg(candidate) && Boolean(candidate.undo && candidate.redo);
    }
  }
  static lift(edit3) {
    if (edit3 instanceof _$L_b) {
      return edit3;
    } else {
      return new _$L_b(edit3.resource, edit3.undo, edit3.redo, edit3.metadata);
    }
  }
  constructor(resource, undo, redo, metadata) {
    super(metadata);
    this.resource = resource;
    this.undo = undo;
    this.redo = redo;
  }
};
var $M_b = class $M_b2 {
  constructor(a, b, c, d, e, f) {
    this.a = a;
    this.b = b;
    this.c = c;
    this.d = d;
    this.e = e;
    this.f = f;
  }
  async apply() {
    const resources = [];
    for (const edit3 of this.e) {
      if (this.d.isCancellationRequested) {
        break;
      }
      await edit3.redo();
      this.f.pushElement({
        type: 0,
        resource: edit3.resource,
        label: edit3.metadata?.label || "Custom Edit",
        code: "paste",
        undo: edit3.undo,
        redo: edit3.redo
      }, this.a, this.b);
      this.c.report(void 0);
      resources.push(edit3.resource);
    }
    return resources;
  }
};
$M_b = __decorate([
  __param(5, $_F)
], $M_b);

// out-build/vs/workbench/contrib/bulkEdit/browser/bulkEditService.js
function liftEdits(edits) {
  return edits.map((edit3) => {
    if ($J_.is(edit3)) {
      return $J_.lift(edit3);
    }
    if ($K_.is(edit3)) {
      return $K_.lift(edit3);
    }
    if ($Trb.is(edit3)) {
      return $Trb.lift(edit3);
    }
    if ($L_b.is(edit3)) {
      return $L_b.lift(edit3);
    }
    throw new Error("Unsupported edit");
  });
}
var BulkEdit = class BulkEdit2 {
  constructor(a, b, c, d, f, g, h3, j, k, l, m) {
    this.a = a;
    this.b = b;
    this.c = c;
    this.d = d;
    this.f = f;
    this.g = g;
    this.h = h3;
    this.j = j;
    this.k = k;
    this.l = l;
    this.m = m;
  }
  ariaMessage() {
    const otherResources = new $Ec();
    const textEditResources = new $Ec();
    let textEditCount = 0;
    for (const edit3 of this.g) {
      if (edit3 instanceof $J_) {
        textEditCount += 1;
        textEditResources.set(edit3.resource, true);
      } else if (edit3 instanceof $K_) {
        otherResources.set(edit3.oldResource ?? edit3.newResource, true);
      }
    }
    if (this.g.length === 0) {
      return localize(4526, null);
    } else if (otherResources.size === 0) {
      if (textEditCount > 1 && textEditResources.size > 1) {
        return localize(4527, null, textEditCount, textEditResources.size);
      } else {
        return localize(4528, null, textEditCount);
      }
    } else {
      return localize(4529, null, textEditCount, textEditResources.size, otherResources.size);
    }
  }
  async perform() {
    if (this.g.length === 0) {
      return [];
    }
    const ranges = [1];
    for (let i2 = 1; i2 < this.g.length; i2++) {
      if (Object.getPrototypeOf(this.g[i2 - 1]) === Object.getPrototypeOf(this.g[i2])) {
        ranges[ranges.length - 1]++;
      } else {
        ranges.push(1);
      }
    }
    const increment = this.g.length > 1 ? 0 : void 0;
    this.d.report({ increment, total: 100 });
    const progress = { report: (_) => this.d.report({ increment: 100 / this.g.length }) };
    const resources = [];
    let index = 0;
    for (const range of ranges) {
      if (this.f.isCancellationRequested) {
        break;
      }
      const group2 = this.g.slice(index, index + range);
      if (group2[0] instanceof $K_) {
        resources.push(await this.n(group2, this.h, this.j, this.k, progress));
      } else if (group2[0] instanceof $J_) {
        resources.push(await this.o(group2, this.h, this.j, progress));
      } else if (group2[0] instanceof $Trb) {
        resources.push(await this.p(group2, this.h, this.j, progress));
      } else if (group2[0] instanceof $L_b) {
        resources.push(await this.q(group2, this.h, this.j, progress));
      } else {
        console.log("UNKNOWN EDIT");
      }
      index = index + range;
    }
    return resources.flat();
  }
  async n(edits, undoRedoGroup, undoRedoSource, confirmBeforeUndo, progress) {
    this.m.debug("_performFileEdits", JSON.stringify(edits));
    const model = this.l.createInstance($J_b, this.a || localize(4530, null), this.b || "undoredo.workspaceEdit", undoRedoGroup, undoRedoSource, confirmBeforeUndo, progress, this.f, edits);
    return await model.apply();
  }
  async o(edits, undoRedoGroup, undoRedoSource, progress) {
    this.m.debug("_performTextEdits", JSON.stringify(edits));
    const model = this.l.createInstance($K_b, this.a || localize(4531, null), this.b || "undoredo.workspaceEdit", this.c, undoRedoGroup, undoRedoSource, progress, this.f, edits);
    return await model.apply();
  }
  async p(edits, undoRedoGroup, undoRedoSource, progress) {
    this.m.debug("_performCellEdits", JSON.stringify(edits));
    const model = this.l.createInstance($Urb, undoRedoGroup, undoRedoSource, progress, this.f, edits);
    return await model.apply();
  }
  async q(edits, undoRedoGroup, undoRedoSource, progress) {
    this.m.debug("_performOpaqueEdits", JSON.stringify(edits));
    const model = this.l.createInstance($M_b, undoRedoGroup, undoRedoSource, progress, this.f, edits);
    return await model.apply();
  }
};
BulkEdit = __decorate([
  __param(9, $Pk),
  __param(10, $wn)
], BulkEdit);
var $N_b = class $N_b2 {
  constructor(c, d, f, g, h3, j, k) {
    this.c = c;
    this.d = d;
    this.f = f;
    this.g = g;
    this.h = h3;
    this.j = j;
    this.k = k;
    this.a = new $cd();
  }
  setPreviewHandler(handler) {
    this.b = handler;
    return $1c(() => {
      if (this.b === handler) {
        this.b = void 0;
      }
    });
  }
  hasPreviewHandler() {
    return Boolean(this.b);
  }
  async apply(editsIn, options3) {
    let edits = liftEdits(Array.isArray(editsIn) ? editsIn : editsIn.edits);
    if (edits.length === 0) {
      return { ariaSummary: localize(4532, null), isApplied: false };
    }
    if (this.b && (options3?.showPreview || edits.some((value) => value.metadata?.needsConfirmation))) {
      edits = await this.b(edits, options3);
    }
    let codeEditor = options3?.editor;
    if (!codeEditor) {
      const candidate = this.f.activeTextEditorControl;
      if ($P5(candidate)) {
        codeEditor = candidate;
      } else if ($Q5(candidate)) {
        codeEditor = candidate.getModifiedEditor();
      }
    }
    if (codeEditor && codeEditor.getOption(
      96
      /* EditorOption.readOnly */
    )) {
      codeEditor = void 0;
    }
    let undoRedoGroup;
    let undoRedoGroupRemove = () => {
    };
    if (typeof options3?.undoRedoGroupId === "number") {
      for (const candidate of this.a) {
        if (candidate.id === options3.undoRedoGroupId) {
          undoRedoGroup = candidate;
          break;
        }
      }
    }
    if (!undoRedoGroup) {
      undoRedoGroup = new $bG();
      undoRedoGroupRemove = this.a.push(undoRedoGroup);
    }
    const label3 = options3?.quotableLabel || options3?.label;
    const bulkEdit = this.c.createInstance(BulkEdit, label3, options3?.code, codeEditor, options3?.progress ?? $VJ.None, options3?.token ?? CancellationToken.None, edits, undoRedoGroup, options3?.undoRedoSource, !!options3?.confirmBeforeUndo);
    let listener;
    try {
      listener = this.g.onBeforeShutdown((e) => e.veto(this.m(label3, e.reason), "veto.blukEditService"));
      const resources = await bulkEdit.perform();
      if (options3?.respectAutoSaveConfig && this.k.getValue(autoSaveSetting) === true && resources.length > 1) {
        await this.l(resources);
      }
      return { ariaSummary: bulkEdit.ariaMessage(), isApplied: edits.length > 0 };
    } catch (err) {
      this.d.error(err);
      throw err;
    } finally {
      listener?.dispose();
      undoRedoGroupRemove();
    }
  }
  async l(resources) {
    const set = new $Fc(resources);
    const saves = this.j.dirtyWorkingCopies.map(async (copy) => {
      if (set.has(copy.resource)) {
        await copy.save();
      }
    });
    const result = await Promise.allSettled(saves);
    for (const item of result) {
      if (item.status === "rejected") {
        this.d.warn(item.reason);
      }
    }
  }
  async m(label3, reason) {
    let message;
    let primaryButton;
    switch (reason) {
      case 1:
        message = localize(4533, null);
        primaryButton = localize(4534, null);
        break;
      case 4:
        message = localize(4535, null);
        primaryButton = localize(4536, null);
        break;
      case 3:
        message = localize(4537, null);
        primaryButton = localize(4538, null);
        break;
      default:
        message = localize(4539, null);
        primaryButton = localize(4540, null);
        break;
    }
    const result = await this.h.confirm({
      message,
      detail: localize(4541, null, label3 || localize(4542, null)),
      primaryButton
    });
    return !result.confirmed;
  }
};
$N_b = __decorate([
  __param(0, $Pk),
  __param(1, $wn),
  __param(2, $mJ),
  __param(3, $KL),
  __param(4, $Yv),
  __param(5, $XI),
  __param(6, $kl)
], $N_b);
$SC(
  $H_,
  $N_b,
  1
  /* InstantiationType.Delayed */
);
var autoSaveSetting = "files.refactoring.autoSave";
$Wn.as($Ht.Configuration).registerConfiguration({
  id: "files",
  properties: {
    [autoSaveSetting]: {
      description: localize(4543, null),
      default: true,
      type: "boolean"
    }
  }
});

// out-build/vs/workbench/contrib/bulkEdit/browser/conflicts.js
var $O_b = class $O_b2 {
  constructor(edits, fileService, modelService, logService) {
    this.a = new $Ec();
    this.b = new $2c();
    this.c = new $ze();
    this.onDidConflict = this.c.event;
    const _workspaceEditResources = new $Ec();
    for (const edit3 of edits) {
      if (edit3 instanceof $J_) {
        _workspaceEditResources.set(edit3.resource, true);
        if (typeof edit3.versionId === "number") {
          const model = modelService.getModel(edit3.resource);
          if (model && model.getVersionId() !== edit3.versionId) {
            this.a.set(edit3.resource, true);
            this.c.fire(this);
          }
        }
      } else if (edit3 instanceof $K_) {
        if (edit3.newResource) {
          _workspaceEditResources.set(edit3.newResource, true);
        } else if (edit3.oldResource) {
          _workspaceEditResources.set(edit3.oldResource, true);
        }
      } else if (edit3 instanceof $Trb) {
        _workspaceEditResources.set(edit3.resource, true);
      } else {
        logService.warn("UNKNOWN edit type", edit3);
      }
    }
    this.b.add(fileService.onDidFilesChange((e) => {
      for (const uri of _workspaceEditResources.keys()) {
        if (!modelService.getModel(uri) && e.contains(uri)) {
          this.a.set(uri, true);
          this.c.fire(this);
          break;
        }
      }
    }));
    const onDidChangeModel = (model) => {
      if (_workspaceEditResources.has(model.uri)) {
        this.a.set(model.uri, true);
        this.c.fire(this);
      }
    };
    for (const model of modelService.getModels()) {
      this.b.add(model.onDidChangeContent(() => onDidChangeModel(model)));
    }
  }
  dispose() {
    this.b.dispose();
    this.c.dispose();
  }
  list() {
    return [...this.a.keys()];
  }
  hasConflicts() {
    return this.a.size > 0;
  }
};
$O_b = __decorate([
  __param(1, $km),
  __param(2, $sG),
  __param(3, $wn)
], $O_b);

// out-build/vs/workbench/contrib/bulkEdit/browser/preview/bulkEditPreview.js
var $T_b_1;
var $U_b_1;
var $P_b = class {
  constructor() {
    this.c = /* @__PURE__ */ new WeakMap();
    this.d = 0;
    this.f = new $ze();
    this.onDidChange = this.f.event;
  }
  dispose() {
    this.f.dispose();
  }
  get checkedCount() {
    return this.d;
  }
  isChecked(obj) {
    return this.c.get(obj) ?? false;
  }
  updateChecked(obj, value) {
    const valueNow = this.c.get(obj);
    if (valueNow === value) {
      return;
    }
    if (valueNow === void 0) {
      if (value) {
        this.d += 1;
      }
    } else {
      if (value) {
        this.d += 1;
      } else {
        this.d -= 1;
      }
    }
    this.c.set(obj, value);
    this.f.fire(obj);
  }
};
var $Q_b = class {
  constructor(parent, textEdit) {
    this.parent = parent;
    this.textEdit = textEdit;
  }
};
var BulkFileOperationType;
(function(BulkFileOperationType2) {
  BulkFileOperationType2[BulkFileOperationType2["TextEdit"] = 1] = "TextEdit";
  BulkFileOperationType2[BulkFileOperationType2["Create"] = 2] = "Create";
  BulkFileOperationType2[BulkFileOperationType2["Delete"] = 4] = "Delete";
  BulkFileOperationType2[BulkFileOperationType2["Rename"] = 8] = "Rename";
})(BulkFileOperationType || (BulkFileOperationType = {}));
var $R_b = class {
  constructor(uri, parent) {
    this.uri = uri;
    this.parent = parent;
    this.type = 0;
    this.textEdits = [];
    this.originalEdits = /* @__PURE__ */ new Map();
  }
  addEdit(index, type, edit3) {
    this.type |= type;
    this.originalEdits.set(index, edit3);
    if (edit3 instanceof $J_) {
      this.textEdits.push(new $Q_b(this, edit3));
    } else if (type === 8) {
      this.newUri = edit3.newResource;
    }
  }
  needsConfirmation() {
    for (const [, edit3] of this.originalEdits) {
      if (!this.parent.checked.isChecked(edit3)) {
        return true;
      }
    }
    return false;
  }
};
var $S_b = class _$S_b {
  static {
    this.c = Object.freeze({
      label: localize(4567, null),
      icon: $6l.symbolFile,
      needsConfirmation: false
    });
  }
  static keyOf(metadata) {
    return metadata?.label || "<default>";
  }
  constructor(metadata = _$S_b.c) {
    this.metadata = metadata;
    this.operationByResource = /* @__PURE__ */ new Map();
  }
  get fileOperations() {
    return this.operationByResource.values();
  }
};
var $T_b = $T_b_1 = class $T_b2 {
  static async create(accessor, bulkEdit) {
    const result = accessor.get($Pk).createInstance($T_b_1, bulkEdit);
    return await result._init();
  }
  constructor(c, d, instaService) {
    this.c = c;
    this.d = d;
    this.checked = new $P_b();
    this.fileOperations = [];
    this.categories = [];
    this.conflicts = instaService.createInstance($O_b, c);
  }
  dispose() {
    this.checked.dispose();
    this.conflicts.dispose();
  }
  async _init() {
    const operationByResource = /* @__PURE__ */ new Map();
    const operationByCategory = /* @__PURE__ */ new Map();
    const newToOldUri = new $Ec();
    for (let idx = 0; idx < this.c.length; idx++) {
      const edit3 = this.c[idx];
      let uri;
      let type;
      this.checked.updateChecked(edit3, !edit3.metadata?.needsConfirmation);
      if (edit3 instanceof $J_) {
        type = 1;
        uri = edit3.resource;
      } else if (edit3 instanceof $K_) {
        if (edit3.newResource && edit3.oldResource) {
          type = 8;
          uri = edit3.oldResource;
          if (edit3.options?.overwrite === void 0 && edit3.options?.ignoreIfExists && await this.d.exists(uri)) {
            continue;
          }
          newToOldUri.set(edit3.newResource, uri);
        } else if (edit3.oldResource) {
          type = 4;
          uri = edit3.oldResource;
          if (edit3.options?.ignoreIfNotExists && !await this.d.exists(uri)) {
            continue;
          }
        } else if (edit3.newResource) {
          type = 2;
          uri = edit3.newResource;
          if (edit3.options?.overwrite === void 0 && edit3.options?.ignoreIfExists && await this.d.exists(uri)) {
            continue;
          }
        } else {
          continue;
        }
      } else {
        continue;
      }
      const insert = (uri2, map) => {
        let key3 = $lh.getComparisonKey(uri2, true);
        let operation = map.get(key3);
        if (!operation && newToOldUri.has(uri2)) {
          uri2 = newToOldUri.get(uri2);
          key3 = $lh.getComparisonKey(uri2, true);
          operation = map.get(key3);
        }
        if (!operation) {
          operation = new $R_b(uri2, this);
          map.set(key3, operation);
        }
        operation.addEdit(idx, type, edit3);
      };
      insert(uri, operationByResource);
      const key2 = $S_b.keyOf(edit3.metadata);
      let category8 = operationByCategory.get(key2);
      if (!category8) {
        category8 = new $S_b(edit3.metadata);
        operationByCategory.set(key2, category8);
      }
      insert(uri, category8.operationByResource);
    }
    operationByResource.forEach((value) => this.fileOperations.push(value));
    operationByCategory.forEach((value) => this.categories.push(value));
    for (const file of this.fileOperations) {
      if (file.type !== 1) {
        let checked = true;
        for (const edit3 of file.originalEdits.values()) {
          if (edit3 instanceof $K_) {
            checked = checked && this.checked.isChecked(edit3);
          }
        }
        if (!checked) {
          for (const edit3 of file.originalEdits.values()) {
            this.checked.updateChecked(edit3, checked);
          }
        }
      }
    }
    this.categories.sort((a, b) => {
      if (a.metadata.needsConfirmation === b.metadata.needsConfirmation) {
        return a.metadata.label.localeCompare(b.metadata.label);
      } else if (a.metadata.needsConfirmation) {
        return -1;
      } else {
        return 1;
      }
    });
    return this;
  }
  getWorkspaceEdit() {
    const result = [];
    let allAccepted = true;
    for (let i2 = 0; i2 < this.c.length; i2++) {
      const edit3 = this.c[i2];
      if (this.checked.isChecked(edit3)) {
        result[i2] = edit3;
        continue;
      }
      allAccepted = false;
    }
    if (allAccepted) {
      return this.c;
    }
    $Nb(result);
    return result;
  }
  async f(edit3) {
    const content = await edit3.options.contents;
    if (!content) {
      return void 0;
    }
    return $bD.replaceMove($9C.lift({ startLineNumber: 0, startColumn: 0, endLineNumber: Number.MAX_VALUE, endColumn: 0 }), content.toString());
  }
  async getFileEdits(uri) {
    for (const file of this.fileOperations) {
      if (file.uri.toString() === uri.toString()) {
        const result = [];
        let ignoreAll = false;
        for (const edit3 of file.originalEdits.values()) {
          if (edit3 instanceof $K_) {
            result.push(this.f(edit3));
          } else if (edit3 instanceof $J_) {
            if (this.checked.isChecked(edit3)) {
              result.push(Promise.resolve($bD.replaceMove($9C.lift(edit3.textEdit.range), !edit3.textEdit.insertAsSnippet ? edit3.textEdit.text : $0_.asInsertText(edit3.textEdit.text))));
            }
          } else if (!this.checked.isChecked(edit3)) {
            ignoreAll = true;
          }
        }
        if (ignoreAll) {
          return [];
        }
        return (await Promise.all(result)).filter((r2) => r2 !== void 0).sort((a, b) => $9C.compareRangesUsingStarts(a.range, b.range));
      }
    }
    return [];
  }
  getUriOfEdit(edit3) {
    for (const file of this.fileOperations) {
      for (const value of file.originalEdits.values()) {
        if (value === edit3) {
          return file.uri;
        }
      }
    }
    throw new Error("invalid edit");
  }
};
$T_b = $T_b_1 = __decorate([
  __param(1, $km),
  __param(2, $Pk)
], $T_b);
var $U_b = class $U_b2 {
  static {
    $U_b_1 = this;
  }
  static {
    this.c = "vscode-bulkeditpreview-editor";
  }
  static {
    this.emptyPreview = URI.from({ scheme: this.c, fragment: "empty" });
  }
  static fromPreviewUri(uri) {
    return URI.parse(uri.query);
  }
  constructor(j, k, l, m) {
    this.j = j;
    this.k = k;
    this.l = l;
    this.m = m;
    this.d = new $2c();
    this.g = /* @__PURE__ */ new Map();
    this.h = $ps();
    this.d.add(this.m.registerTextModelContentProvider($U_b_1.c, this));
    this.f = this.n();
  }
  dispose() {
    this.d.dispose();
  }
  asPreviewUri(uri) {
    return URI.from({ scheme: $U_b_1.c, authority: this.h, path: uri.path, query: uri.toString() });
  }
  async n() {
    for (const operation of this.j.fileOperations) {
      await this.o(operation.uri);
    }
    this.d.add(Event2.debounce(this.j.checked.onDidChange, (_last, e) => e, $ue)((e) => {
      const uri = this.j.getUriOfEdit(e);
      this.o(uri);
    }));
  }
  async o(uri) {
    const model = await this.p(uri);
    const undoEdits = this.g.get(model.id);
    if (undoEdits) {
      model.applyEdits(undoEdits);
    }
    const newEdits = await this.j.getFileEdits(uri);
    const newUndoEdits = model.applyEdits(newEdits, true);
    this.g.set(model.id, newUndoEdits);
  }
  async p(uri) {
    const previewUri = this.asPreviewUri(uri);
    let model = this.l.getModel(previewUri);
    if (!model) {
      try {
        const ref = await this.m.createModelReference(uri);
        const sourceModel = ref.object.textEditorModel;
        model = this.l.createModel($OI(sourceModel.createSnapshot()), this.k.createById(sourceModel.getLanguageId()), previewUri);
        ref.dispose();
      } catch {
        model = this.l.createModel("", this.k.createByFilepathOrFirstLine(previewUri), previewUri);
      }
      queueMicrotask(async () => {
        this.d.add(await this.m.createModelReference(model.uri));
      });
    }
    return model;
  }
  async provideTextContent(previewUri) {
    if (previewUri.toString() === $U_b_1.emptyPreview.toString()) {
      return this.l.createModel("", null, previewUri);
    }
    await this.f;
    return this.l.getModel(previewUri);
  }
};
$U_b = $U_b_1 = __decorate([
  __param(1, $1E),
  __param(2, $sG),
  __param(3, $oG)
], $U_b);

// out-build/vs/workbench/contrib/bulkEdit/browser/preview/bulkEditTree.js
var $4_b_1;
var $5_b_1;
var $6_b_1;
var $V_b = class {
  constructor(parent, category8) {
    this.parent = parent;
    this.category = category8;
  }
  isChecked() {
    const model = this.parent;
    let checked = true;
    for (const file of this.category.fileOperations) {
      for (const edit3 of file.originalEdits.values()) {
        checked = checked && model.checked.isChecked(edit3);
      }
    }
    return checked;
  }
  setChecked(value) {
    const model = this.parent;
    for (const file of this.category.fileOperations) {
      for (const edit3 of file.originalEdits.values()) {
        model.checked.updateChecked(edit3, value);
      }
    }
  }
};
var $W_b = class {
  constructor(parent, edit3) {
    this.parent = parent;
    this.edit = edit3;
  }
  isChecked() {
    const model = this.parent instanceof $V_b ? this.parent.parent : this.parent;
    let checked = true;
    if (this.edit.type === 1) {
      checked = !this.edit.textEdits.every((edit3) => !model.checked.isChecked(edit3.textEdit));
    }
    for (const edit3 of this.edit.originalEdits.values()) {
      if (edit3 instanceof $K_) {
        checked = checked && model.checked.isChecked(edit3);
      }
    }
    if (this.parent instanceof $V_b && this.edit.type === 1) {
      for (const category8 of model.categories) {
        for (const file of category8.fileOperations) {
          if (file.uri.toString() === this.edit.uri.toString()) {
            for (const edit3 of file.originalEdits.values()) {
              if (edit3 instanceof $K_) {
                checked = checked && model.checked.isChecked(edit3);
              }
            }
          }
        }
      }
    }
    return checked;
  }
  setChecked(value) {
    const model = this.parent instanceof $V_b ? this.parent.parent : this.parent;
    for (const edit3 of this.edit.originalEdits.values()) {
      model.checked.updateChecked(edit3, value);
    }
    if (this.parent instanceof $V_b && this.edit.type !== 1) {
      for (const category8 of model.categories) {
        for (const file of category8.fileOperations) {
          if (file.uri.toString() === this.edit.uri.toString()) {
            for (const edit3 of file.originalEdits.values()) {
              model.checked.updateChecked(edit3, value);
            }
          }
        }
      }
    }
  }
  isDisabled() {
    if (this.parent instanceof $V_b && this.edit.type === 1) {
      const model = this.parent.parent;
      let checked = true;
      for (const category8 of model.categories) {
        for (const file of category8.fileOperations) {
          if (file.uri.toString() === this.edit.uri.toString()) {
            for (const edit3 of file.originalEdits.values()) {
              if (edit3 instanceof $K_) {
                checked = checked && model.checked.isChecked(edit3);
              }
            }
          }
        }
      }
      return !checked;
    }
    return false;
  }
};
var $X_b = class {
  constructor(parent, idx, edit3, prefix, selecting, inserting, suffix) {
    this.parent = parent;
    this.idx = idx;
    this.edit = edit3;
    this.prefix = prefix;
    this.selecting = selecting;
    this.inserting = inserting;
    this.suffix = suffix;
  }
  isChecked() {
    let model = this.parent.parent;
    if (model instanceof $V_b) {
      model = model.parent;
    }
    return model.checked.isChecked(this.edit.textEdit);
  }
  setChecked(value) {
    let model = this.parent.parent;
    if (model instanceof $V_b) {
      model = model.parent;
    }
    model.checked.updateChecked(this.edit.textEdit, value);
    if (value) {
      for (const edit3 of this.parent.edit.originalEdits.values()) {
        if (edit3 instanceof $K_) {
          model.checked.updateChecked(edit3, value);
        }
      }
    }
  }
  isDisabled() {
    return this.parent.isDisabled();
  }
};
var $Y_b = class $Y_b2 {
  constructor(c, d) {
    this.c = c;
    this.d = d;
    this.groupByFile = true;
  }
  hasChildren(element) {
    if (element instanceof $W_b) {
      return element.edit.textEdits.length > 0;
    }
    if (element instanceof $X_b) {
      return false;
    }
    return true;
  }
  async getChildren(element) {
    if (element instanceof $T_b) {
      return this.groupByFile ? element.fileOperations.map((op) => new $W_b(element, op)) : element.categories.map((cat) => new $V_b(element, cat));
    }
    if (element instanceof $V_b) {
      return Array.from(element.category.fileOperations, (op) => new $W_b(element, op));
    }
    if (element instanceof $W_b && element.edit.textEdits.length > 0) {
      let textModel;
      let textModelDisposable;
      try {
        const ref = await this.c.createModelReference(element.edit.uri);
        textModel = ref.object.textEditorModel;
        textModelDisposable = ref;
      } catch {
        textModel = this.d.createInstance($QI, "", $KF, $QI.DEFAULT_CREATION_OPTIONS, null);
        textModelDisposable = textModel;
      }
      const result = element.edit.textEdits.map((edit3, idx) => {
        const range = textModel.validateRange(edit3.textEdit.textEdit.range);
        const startTokens = textModel.tokenization.getLineTokens(range.startLineNumber);
        let prefixLen = 23;
        for (let idx2 = startTokens.findTokenIndexAtOffset(range.startColumn - 1) - 1; prefixLen < 50 && idx2 >= 0; idx2--) {
          prefixLen = range.startColumn - startTokens.getStartOffset(idx2);
        }
        const endTokens = textModel.tokenization.getLineTokens(range.endLineNumber);
        let suffixLen = 0;
        for (let idx2 = endTokens.findTokenIndexAtOffset(range.endColumn - 1); suffixLen < 50 && idx2 < endTokens.getCount(); idx2++) {
          suffixLen += endTokens.getEndOffset(idx2) - endTokens.getStartOffset(idx2);
        }
        return new $X_b(element, idx, edit3, textModel.getValueInRange(new $9C(range.startLineNumber, range.startColumn - prefixLen, range.startLineNumber, range.startColumn)), textModel.getValueInRange(range), !edit3.textEdit.textEdit.insertAsSnippet ? edit3.textEdit.textEdit.text : $0_.asInsertText(edit3.textEdit.textEdit.text), textModel.getValueInRange(new $9C(range.endLineNumber, range.endColumn, range.endLineNumber, range.endColumn + suffixLen)));
      });
      textModelDisposable.dispose();
      return result;
    }
    return [];
  }
};
$Y_b = __decorate([
  __param(0, $oG),
  __param(1, $Pk)
], $Y_b);
var $Z_b = class {
  compare(a, b) {
    if (a instanceof $W_b && b instanceof $W_b) {
      return $1_b(a.edit, b.edit);
    }
    if (a instanceof $X_b && b instanceof $X_b) {
      return $9C.compareRangesUsingStarts(a.edit.textEdit.textEdit.range, b.edit.textEdit.textEdit.range);
    }
    return 0;
  }
};
function $1_b(a, b) {
  return $Tf(a.uri.toString(), b.uri.toString());
}
var $2_b = class $2_b2 {
  constructor(c) {
    this.c = c;
  }
  getWidgetAriaLabel() {
    return localize(4568, null);
  }
  getRole(_element) {
    return "checkbox";
  }
  getAriaLabel(element) {
    if (element instanceof $W_b) {
      if (element.edit.textEdits.length > 0) {
        if (element.edit.type & 8 && element.edit.newUri) {
          return localize(4569, null, this.c.getUriLabel(element.edit.uri, { relative: true }), this.c.getUriLabel(element.edit.newUri, { relative: true }));
        } else if (element.edit.type & 2) {
          return localize(4570, null, this.c.getUriLabel(element.edit.uri, { relative: true }));
        } else if (element.edit.type & 4) {
          return localize(4571, null, this.c.getUriLabel(element.edit.uri, { relative: true }));
        } else {
          return localize(4572, null, this.c.getUriLabel(element.edit.uri, { relative: true }));
        }
      } else {
        if (element.edit.type & 8 && element.edit.newUri) {
          return localize(4573, null, this.c.getUriLabel(element.edit.uri, { relative: true }), this.c.getUriLabel(element.edit.newUri, { relative: true }));
        } else if (element.edit.type & 2) {
          return localize(4574, null, this.c.getUriLabel(element.edit.uri, { relative: true }));
        } else if (element.edit.type & 4) {
          return localize(4575, null, this.c.getUriLabel(element.edit.uri, { relative: true }));
        }
      }
    }
    if (element instanceof $X_b) {
      if (element.selecting.length > 0 && element.inserting.length > 0) {
        return localize(4576, null, element.edit.textEdit.textEdit.range.startLineNumber, element.selecting, element.inserting);
      } else if (element.selecting.length > 0 && element.inserting.length === 0) {
        return localize(4577, null, element.edit.textEdit.textEdit.range.startLineNumber, element.selecting);
      } else if (element.selecting.length === 0 && element.inserting.length > 0) {
        return localize(4578, null, element.edit.textEdit.textEdit.range.startLineNumber, element.selecting);
      }
    }
    return null;
  }
};
$2_b = __decorate([
  __param(0, $ZI)
], $2_b);
var $3_b = class {
  getId(element) {
    if (element instanceof $W_b) {
      return element.edit.uri + (element.parent instanceof $V_b ? JSON.stringify(element.parent.category.metadata) : "");
    } else if (element instanceof $X_b) {
      return element.parent.edit.uri.toString() + element.idx;
    } else {
      return JSON.stringify(element.category.metadata);
    }
  }
};
var CategoryElementTemplate = class {
  constructor(container2) {
    container2.classList.add("category");
    this.icon = document.createElement("div");
    container2.appendChild(this.icon);
    this.label = new $T2(container2);
  }
};
var $4_b = class $4_b2 {
  static {
    $4_b_1 = this;
  }
  static {
    this.id = "CategoryElementRenderer";
  }
  constructor(c) {
    this.c = c;
    this.templateId = $4_b_1.id;
  }
  renderTemplate(container2) {
    return new CategoryElementTemplate(container2);
  }
  renderElement(node, _index, template) {
    template.icon.style.setProperty("--background-dark", null);
    template.icon.style.setProperty("--background-light", null);
    template.icon.style.color = "";
    const { metadata } = node.element.category;
    if (ThemeIcon.isThemeIcon(metadata.iconPath)) {
      const className = ThemeIcon.asClassName(metadata.iconPath);
      template.icon.className = className ? `theme-icon ${className}` : "";
      template.icon.style.color = metadata.iconPath.color ? this.c.getColorTheme().getColor(metadata.iconPath.color.id)?.toString() ?? "" : "";
    } else if (URI.isUri(metadata.iconPath)) {
      template.icon.className = "uri-icon";
      template.icon.style.setProperty("--background-dark", $5Z(metadata.iconPath));
      template.icon.style.setProperty("--background-light", $5Z(metadata.iconPath));
    } else if (metadata.iconPath) {
      template.icon.className = "uri-icon";
      template.icon.style.setProperty("--background-dark", $5Z(metadata.iconPath.dark));
      template.icon.style.setProperty("--background-light", $5Z(metadata.iconPath.light));
    }
    template.label.setLabel(metadata.label, metadata.description, {
      descriptionMatches: $Ul(node.filterData)
    });
  }
  disposeTemplate(template) {
    template.label.dispose();
  }
};
$4_b = $4_b_1 = __decorate([
  __param(0, $gs)
], $4_b);
var FileElementTemplate = class FileElementTemplate2 {
  constructor(container2, resourceLabels, i2) {
    this.i = i2;
    this.c = new $2c();
    this.d = new $2c();
    this.f = document.createElement("input");
    this.f.className = "edit-checkbox";
    this.f.type = "checkbox";
    this.f.setAttribute("role", "checkbox");
    container2.appendChild(this.f);
    this.g = resourceLabels.create(container2, { supportHighlights: true });
    this.h = document.createElement("span");
    this.h.className = "details";
    container2.appendChild(this.h);
  }
  dispose() {
    this.d.dispose();
    this.c.dispose();
    this.g.dispose();
  }
  set(element, score2) {
    this.d.clear();
    this.f.checked = element.isChecked();
    this.f.disabled = element.isDisabled();
    this.d.add($_i(this.f, "change", () => {
      element.setChecked(this.f.checked);
    }));
    if (element.edit.type & 8 && element.edit.newUri) {
      this.g.setResource({
        resource: element.edit.uri,
        name: localize(4579, null, this.i.getUriLabel(element.edit.uri, { relative: true }), this.i.getUriLabel(element.edit.newUri, { relative: true }))
      }, {
        fileDecorations: { colors: true, badges: false }
      });
      this.h.innerText = localize(4580, null);
    } else {
      const options3 = {
        matches: $Ul(score2),
        fileKind: FileKind.FILE,
        fileDecorations: { colors: true, badges: false },
        extraClasses: []
      };
      if (element.edit.type & 2) {
        this.h.innerText = localize(4581, null);
      } else if (element.edit.type & 4) {
        this.h.innerText = localize(4582, null);
        options3.extraClasses.push("delete");
      } else {
        this.h.innerText = "";
      }
      this.g.setFile(element.edit.uri, options3);
    }
  }
};
FileElementTemplate = __decorate([
  __param(2, $ZI)
], FileElementTemplate);
var $5_b = class $5_b2 {
  static {
    $5_b_1 = this;
  }
  static {
    this.id = "FileElementRenderer";
  }
  constructor(c, d) {
    this.c = c;
    this.d = d;
    this.templateId = $5_b_1.id;
  }
  renderTemplate(container2) {
    return new FileElementTemplate(container2, this.c, this.d);
  }
  renderElement(node, _index, template) {
    template.set(node.element, node.filterData);
  }
  disposeTemplate(template) {
    template.dispose();
  }
};
$5_b = $5_b_1 = __decorate([
  __param(1, $ZI)
], $5_b);
var TextEditElementTemplate = class TextEditElementTemplate2 {
  constructor(container2, i2) {
    this.i = i2;
    this.c = new $2c();
    this.d = new $2c();
    container2.classList.add("textedit");
    this.f = document.createElement("input");
    this.f.className = "edit-checkbox";
    this.f.type = "checkbox";
    this.f.setAttribute("role", "checkbox");
    container2.appendChild(this.f);
    this.g = document.createElement("div");
    container2.appendChild(this.g);
    this.h = this.c.add(new $S2(container2));
  }
  dispose() {
    this.d.dispose();
    this.c.dispose();
  }
  set(element) {
    this.d.clear();
    this.d.add($_i(this.f, "change", (e) => {
      element.setChecked(this.f.checked);
      e.preventDefault();
    }));
    if (element.parent.isChecked()) {
      this.f.checked = element.isChecked();
      this.f.disabled = element.isDisabled();
    } else {
      this.f.checked = element.isChecked();
      this.f.disabled = element.isDisabled();
    }
    let value = "";
    value += element.prefix;
    value += element.selecting;
    value += element.inserting;
    value += element.suffix;
    const selectHighlight = { start: element.prefix.length, end: element.prefix.length + element.selecting.length, extraClasses: ["remove"] };
    const insertHighlight = { start: selectHighlight.end, end: selectHighlight.end + element.inserting.length, extraClasses: ["insert"] };
    let title;
    const { metadata } = element.edit.textEdit;
    if (metadata && metadata.description) {
      title = localize(4583, null, metadata.label, metadata.description);
    } else if (metadata) {
      title = metadata.label;
    }
    const iconPath = metadata?.iconPath;
    if (!iconPath) {
      this.g.style.display = "none";
    } else {
      this.g.style.display = "block";
      this.g.style.setProperty("--background-dark", null);
      this.g.style.setProperty("--background-light", null);
      if (ThemeIcon.isThemeIcon(iconPath)) {
        const className = ThemeIcon.asClassName(iconPath);
        this.g.className = className ? `theme-icon ${className}` : "";
        this.g.style.color = iconPath.color ? this.i.getColorTheme().getColor(iconPath.color.id)?.toString() ?? "" : "";
      } else if (URI.isUri(iconPath)) {
        this.g.className = "uri-icon";
        this.g.style.setProperty("--background-dark", $5Z(iconPath));
        this.g.style.setProperty("--background-light", $5Z(iconPath));
      } else {
        this.g.className = "uri-icon";
        this.g.style.setProperty("--background-dark", $5Z(iconPath.dark));
        this.g.style.setProperty("--background-light", $5Z(iconPath.light));
      }
    }
    this.h.set(value, [selectHighlight, insertHighlight], title, true);
    this.g.title = title || "";
  }
};
TextEditElementTemplate = __decorate([
  __param(1, $gs)
], TextEditElementTemplate);
var $6_b = class $6_b2 {
  static {
    $6_b_1 = this;
  }
  static {
    this.id = "TextEditElementRenderer";
  }
  constructor(c) {
    this.c = c;
    this.templateId = $6_b_1.id;
  }
  renderTemplate(container2) {
    return new TextEditElementTemplate(container2, this.c);
  }
  renderElement({ element }, _index, template) {
    template.set(element);
  }
  disposeTemplate(_template) {
  }
};
$6_b = $6_b_1 = __decorate([
  __param(0, $gs)
], $6_b);
var $7_b = class {
  getHeight() {
    return 23;
  }
  getTemplateId(element) {
    if (element instanceof $W_b) {
      return $5_b.id;
    } else if (element instanceof $X_b) {
      return $6_b.id;
    } else {
      return $4_b.id;
    }
  }
};
var $8_b = class {
  getKeyboardNavigationLabel(element) {
    if (element instanceof $W_b) {
      return $sh(element.edit.uri);
    } else if (element instanceof $V_b) {
      return element.category.metadata.label;
    }
    return void 0;
  }
};

// out-build/vs/workbench/contrib/bulkEdit/browser/preview/bulkEditPane.js
var $9_b_1;
var State10;
(function(State14) {
  State14["Data"] = "data";
  State14["Message"] = "message";
})(State10 || (State10 = {}));
var $9_b = class $9_b2 extends $_ob {
  static {
    $9_b_1 = this;
  }
  static {
    this.ID = "refactorPreview";
  }
  static {
    this.Schema = "vscode-bulkeditpreview-multieditor";
  }
  static {
    this.ctxHasCategories = new $nn("refactorPreview.hasCategories", false);
  }
  static {
    this.ctxGroupByFile = new $nn("refactorPreview.groupByFile", true);
  }
  static {
    this.ctxHasCheckedChanges = new $nn("refactorPreview.hasCheckedChanges", true);
  }
  static {
    this.a = `${this.ID}.groupByFile`;
  }
  constructor(options3, ab, sb, ac, bc, cc, dc, ec, contextKeyService, viewDescriptorService, keybindingService, contextMenuService, configurationService, openerService, themeService, telemetryService, hoverService) {
    super({ ...options3, titleMenuId: $bJ.BulkEditTitle }, keybindingService, contextMenuService, configurationService, contextKeyService, viewDescriptorService, ab, openerService, themeService, telemetryService, hoverService);
    this.ab = ab;
    this.sb = sb;
    this.ac = ac;
    this.bc = bc;
    this.cc = cc;
    this.dc = dc;
    this.ec = ec;
    this.f = /* @__PURE__ */ new Map();
    this.n = new $2c();
    this.r = new $2c();
    this.lc = new $qf(async (fileOperations) => {
      const computeDiffEditorInput = new $rf(async (fileOperation) => {
        const fileOperationUri = fileOperation.uri;
        const previewUri = this.L.asPreviewUri(fileOperationUri);
        if (fileOperation.type & 4) {
          return {
            original: { resource: URI.revive(previewUri) },
            modified: { resource: void 0 },
            goToFileResource: fileOperation.uri
          };
        } else {
          let leftResource;
          try {
            (await this.bc.createModelReference(fileOperationUri)).dispose();
            leftResource = fileOperationUri;
          } catch {
            leftResource = $U_b.emptyPreview;
          }
          return {
            original: { resource: URI.revive(leftResource) },
            modified: { resource: URI.revive(previewUri) },
            goToFileResource: leftResource
          };
        }
      });
      const sortedFileOperations = fileOperations.slice().sort($1_b);
      const resources = [];
      for (const operation of sortedFileOperations) {
        resources.push(await computeDiffEditorInput.get(operation));
      }
      const getResourceDiffEditorInputIdOfOperation = async (operation) => {
        const resource = await computeDiffEditorInput.get(operation);
        return { original: resource.original.resource, modified: resource.modified.resource };
      };
      return {
        resources,
        getResourceDiffEditorInputIdOfOperation
      };
    });
    this.element.classList.add("bulk-edit-panel", "show-file-icons");
    this.h = $9_b_1.ctxHasCategories.bindTo(contextKeyService);
    this.j = $9_b_1.ctxGroupByFile.bindTo(contextKeyService);
    this.m = $9_b_1.ctxHasCheckedChanges.bindTo(contextKeyService);
    this.Gb.publicLog2("views.bulkEditPane");
  }
  dispose() {
    this.b.dispose();
    this.n.dispose();
    super.dispose();
  }
  W(parent) {
    super.W(parent);
    const resourceLabels = this.ab.createInstance($lsb, { onDidChangeVisibility: this.onDidChangeBodyVisibility });
    this.n.add(resourceLabels);
    const contentContainer = document.createElement("div");
    contentContainer.className = "content";
    parent.appendChild(contentContainer);
    const treeContainer = document.createElement("div");
    contentContainer.appendChild(treeContainer);
    this.c = this.ab.createInstance($Y_b);
    this.c.groupByFile = this.ec.getBoolean($9_b_1.a, 0, true);
    this.j.set(this.c.groupByFile);
    this.b = this.ab.createInstance($4eb, this.id, treeContainer, new $7_b(), [this.ab.createInstance($6_b), this.ab.createInstance($5_b, resourceLabels), this.ab.createInstance($4_b)], this.c, {
      accessibilityProvider: this.ab.createInstance($2_b),
      identityProvider: new $3_b(),
      expandOnlyOnTwistieClick: true,
      multipleSelectionSupport: false,
      keyboardNavigationLabelProvider: new $8_b(),
      sorter: new $Z_b(),
      selectionNavigation: true
    });
    this.n.add(this.b.onContextMenu(this.mc, this));
    this.n.add(this.b.onDidOpen((e) => this.kc(e)));
    const buttonsContainer = document.createElement("div");
    buttonsContainer.className = "buttons";
    contentContainer.appendChild(buttonsContainer);
    const buttonBar = new $n2(buttonsContainer);
    this.n.add(buttonBar);
    const btnConfirm = buttonBar.addButton({ supportIcons: true, ...$q$ });
    btnConfirm.label = localize(4562, null);
    btnConfirm.onDidClick(() => this.accept(), this, this.n);
    const btnCancel = buttonBar.addButton({ ...$q$, secondary: true });
    btnCancel.label = localize(4563, null);
    btnCancel.onDidClick(() => this.discard(), this, this.n);
    this.g = document.createElement("span");
    this.g.className = "message";
    this.g.innerText = localize(4564, null);
    parent.appendChild(this.g);
    this.hc(
      "message"
      /* State.Message */
    );
  }
  X(height, width2) {
    super.X(height, width2);
    const treeHeight = height - 50;
    this.b.getHTMLElement().parentElement.style.height = `${treeHeight}px`;
    this.b.layout(treeHeight, width2);
  }
  hc(state) {
    this.element.dataset["state"] = state;
  }
  async setInput(edit3, token) {
    this.hc(
      "data"
      /* State.Data */
    );
    this.r.clear();
    this.f.clear();
    if (this.s) {
      this.s(void 0);
      this.s = void 0;
    }
    const input = await this.ab.invokeFunction($T_b.create, edit3);
    this.L = this.ab.createInstance($U_b, input);
    this.r.add(this.L);
    this.r.add(input);
    const hasCategories = input.categories.length > 1;
    this.h.set(hasCategories);
    this.c.groupByFile = !hasCategories || this.c.groupByFile;
    this.m.set(input.checked.checkedCount > 0);
    this.t = input;
    return new Promise((resolve) => {
      token.onCancellationRequested(() => resolve(void 0));
      this.s = resolve;
      this.ic(input);
      this.r.add(input.checked.onDidChange(() => {
        this.b.updateChildren();
        this.m.set(input.checked.checkedCount > 0);
      }));
    });
  }
  hasInput() {
    return Boolean(this.t);
  }
  async ic(input) {
    const viewState = this.f.get(this.c.groupByFile);
    await this.b.setInput(input, viewState);
    this.b.domFocus();
    if (viewState) {
      return;
    }
    const expand = [...this.b.getNode(input).children].slice(0, 10);
    while (expand.length > 0) {
      const { element } = expand.shift();
      if (element instanceof $W_b) {
        await this.b.expand(element, true);
      }
      if (element instanceof $V_b) {
        await this.b.expand(element, true);
        expand.push(...this.b.getNode(element).children);
      }
    }
  }
  accept() {
    const conflicts = this.t?.conflicts.list();
    if (!conflicts || conflicts.length === 0) {
      this.jc(true);
      return;
    }
    let message;
    if (conflicts.length === 1) {
      message = localize(4565, null, this.ac.getUriLabel(conflicts[0], { relative: true }));
    } else {
      message = localize(4566, null, conflicts.length);
    }
    this.cc.warn(message).finally(() => this.jc(false));
  }
  discard() {
    this.jc(false);
  }
  jc(accept) {
    this.s?.(accept ? this.t?.getWorkspaceEdit() : void 0);
    this.t = void 0;
    this.hc(
      "message"
      /* State.Message */
    );
    this.r.clear();
  }
  toggleChecked() {
    const [first] = this.b.getFocus();
    if ((first instanceof $W_b || first instanceof $X_b) && !first.isDisabled()) {
      first.setChecked(!first.isChecked());
    } else if (first instanceof $V_b) {
      first.setChecked(!first.isChecked());
    }
  }
  groupByFile() {
    if (!this.c.groupByFile) {
      this.toggleGrouping();
    }
  }
  groupByType() {
    if (this.c.groupByFile) {
      this.toggleGrouping();
    }
  }
  toggleGrouping() {
    const input = this.b.getInput();
    if (input) {
      const oldViewState = this.b.getViewState();
      this.f.set(this.c.groupByFile, oldViewState);
      this.c.groupByFile = !this.c.groupByFile;
      this.ic(input);
      this.ec.store(
        $9_b_1.a,
        this.c.groupByFile,
        0,
        0
        /* StorageTarget.USER */
      );
      this.j.set(this.c.groupByFile);
    }
  }
  async kc(e) {
    const fileOperations = this.t?.fileOperations;
    if (!fileOperations) {
      return;
    }
    let selection = void 0;
    let fileElement;
    if (e.element instanceof $X_b) {
      fileElement = e.element.parent;
      selection = e.element.edit.textEdit.textEdit.range;
    } else if (e.element instanceof $W_b) {
      fileElement = e.element;
      selection = e.element.edit.textEdits[0]?.textEdit.textEdit.range;
    } else {
      return;
    }
    const result = await this.lc.get(fileOperations);
    const resourceId = await result.getResourceDiffEditorInputIdOfOperation(fileElement.edit);
    const options3 = {
      ...e.editorOptions,
      viewState: {
        revealData: {
          resource: resourceId,
          range: selection
        }
      }
    };
    const multiDiffSource = URI.from({ scheme: $9_b_1.Schema });
    const label3 = "Refactor Preview";
    this.sb.openEditor({
      multiDiffSource,
      label: label3,
      options: options3,
      isTransient: true,
      description: label3,
      resources: result.resources
    }, e.sideBySide ? $oJ : $nJ);
  }
  mc(e) {
    this.dc.showContextMenu({
      menuId: $bJ.BulkEditContext,
      contextKeyService: this.Bb,
      getAnchor: () => e.anchor
    });
  }
};
$9_b = $9_b_1 = __decorate([
  __param(1, $Pk),
  __param(2, $mJ),
  __param(3, $ZI),
  __param(4, $oG),
  __param(5, $Yv),
  __param(6, $50),
  __param(7, $jv),
  __param(8, $on),
  __param(9, $$M),
  __param(10, $Ty),
  __param(11, $50),
  __param(12, $kl),
  __param(13, $O4),
  __param(14, $gs),
  __param(15, $zv),
  __param(16, $5$)
], $9_b);

// out-build/vs/workbench/contrib/bulkEdit/browser/preview/bulkEdit.contribution.js
var BulkEditPreviewContribution_1;
async function getBulkEditPane(viewsService) {
  const view = await viewsService.openView($9_b.ID, true);
  if (view instanceof $9_b) {
    return view;
  }
  return void 0;
}
var UXState = class UXState2 {
  constructor(b, c) {
    this.b = b;
    this.c = c;
    this.a = b.getActivePaneComposite(
      1
      /* ViewContainerLocation.Panel */
    )?.getId();
  }
  async restore(panels, editors) {
    if (panels) {
      if (typeof this.a === "string") {
        await this.b.openPaneComposite(
          this.a,
          1
          /* ViewContainerLocation.Panel */
        );
      } else {
        this.b.hideActivePaneComposite(
          1
          /* ViewContainerLocation.Panel */
        );
      }
    }
    if (editors) {
      for (const group2 of this.c.groups) {
        const previewEditors = [];
        for (const input of group2.editors) {
          const resource = $mL.getCanonicalUri(input, { supportSideBySide: SideBySideEditor.PRIMARY });
          if (resource?.scheme === $9_b.Schema) {
            previewEditors.push(input);
          }
        }
        if (previewEditors.length) {
          group2.closeEditors(previewEditors, { preserveFocus: true });
        }
      }
    }
  }
};
UXState = __decorate([
  __param(0, $uqb),
  __param(1, $iJ)
], UXState);
var PreviewSession = class {
  constructor(uxState, cts = new $ad()) {
    this.uxState = uxState;
    this.cts = cts;
  }
};
var BulkEditPreviewContribution = class BulkEditPreviewContribution2 {
  static {
    BulkEditPreviewContribution_1 = this;
  }
  static {
    this.ID = "workbench.contrib.bulkEditPreview";
  }
  static {
    this.ctxEnabled = new $nn("refactorPreview.enabled", false);
  }
  constructor(c, d, e, f, bulkEditService, contextKeyService) {
    this.c = c;
    this.d = d;
    this.e = e;
    this.f = f;
    bulkEditService.setPreviewHandler((edits) => this.g(edits));
    this.a = BulkEditPreviewContribution_1.ctxEnabled.bindTo(contextKeyService);
  }
  async g(edits) {
    this.a.set(true);
    const uxState = this.b?.uxState ?? new UXState(this.c, this.e);
    const view = await getBulkEditPane(this.d);
    if (!view) {
      this.a.set(false);
      return edits;
    }
    if (view.hasInput()) {
      const { confirmed } = await this.f.confirm({
        type: severity_default.Info,
        message: localize(4544, null),
        detail: localize(4545, null),
        primaryButton: localize(4546, null)
      });
      if (!confirmed) {
        return [];
      }
    }
    let session;
    if (this.b) {
      await this.b.uxState.restore(false, true);
      this.b.cts.dispose(true);
      session = new PreviewSession(uxState);
    } else {
      session = new PreviewSession(uxState);
    }
    this.b = session;
    try {
      return await view.setInput(edits, session.cts.token) ?? [];
    } finally {
      if (this.b === session) {
        await this.b.uxState.restore(true, true);
        this.b.cts.dispose();
        this.a.set(false);
        this.b = void 0;
      }
    }
  }
};
BulkEditPreviewContribution = BulkEditPreviewContribution_1 = __decorate([
  __param(0, $uqb),
  __param(1, $uob),
  __param(2, $iJ),
  __param(3, $Yv),
  __param(4, $H_),
  __param(5, $on)
], BulkEditPreviewContribution);
$hJ(class ApplyAction extends $gJ {
  constructor() {
    super({
      id: "refactorPreview.apply",
      title: localize2(4548, "Apply Refactoring"),
      category: localize2(4549, "Refactor Preview"),
      icon: $6l.check,
      precondition: $7m.and(BulkEditPreviewContribution.ctxEnabled, $9_b.ctxHasCheckedChanges),
      menu: [{
        id: $bJ.BulkEditContext,
        order: 1
      }],
      keybinding: {
        weight: 100 - 10,
        when: $7m.and(BulkEditPreviewContribution.ctxEnabled, $jqb.isEqualTo($9_b.ID)),
        primary: 2048 + 3
      }
    });
  }
  async run(accessor) {
    const viewsService = accessor.get($uob);
    const view = await getBulkEditPane(viewsService);
    view?.accept();
  }
});
$hJ(class DiscardAction2 extends $gJ {
  constructor() {
    super({
      id: "refactorPreview.discard",
      title: localize2(4550, "Discard Refactoring"),
      category: localize2(4551, "Refactor Preview"),
      icon: $6l.clearAll,
      precondition: BulkEditPreviewContribution.ctxEnabled,
      menu: [{
        id: $bJ.BulkEditContext,
        order: 2
      }]
    });
  }
  async run(accessor) {
    const viewsService = accessor.get($uob);
    const view = await getBulkEditPane(viewsService);
    view?.discard();
  }
});
$hJ(class ToggleAction extends $gJ {
  constructor() {
    super({
      id: "refactorPreview.toggleCheckedState",
      title: localize2(4552, "Toggle Change"),
      category: localize2(4553, "Refactor Preview"),
      precondition: BulkEditPreviewContribution.ctxEnabled,
      keybinding: {
        weight: 200,
        when: $Leb,
        primary: 10
      },
      menu: {
        id: $bJ.BulkEditContext,
        group: "navigation"
      }
    });
  }
  async run(accessor) {
    const viewsService = accessor.get($uob);
    const view = await getBulkEditPane(viewsService);
    view?.toggleChecked();
  }
});
$hJ(class GroupByFile extends $gJ {
  constructor() {
    super({
      id: "refactorPreview.groupByFile",
      title: localize2(4554, "Group Changes By File"),
      category: localize2(4555, "Refactor Preview"),
      icon: $6l.ungroupByRefType,
      precondition: $7m.and($9_b.ctxHasCategories, $9_b.ctxGroupByFile.negate(), BulkEditPreviewContribution.ctxEnabled),
      menu: [{
        id: $bJ.BulkEditTitle,
        when: $7m.and($9_b.ctxHasCategories, $9_b.ctxGroupByFile.negate()),
        group: "navigation",
        order: 3
      }]
    });
  }
  async run(accessor) {
    const viewsService = accessor.get($uob);
    const view = await getBulkEditPane(viewsService);
    view?.groupByFile();
  }
});
$hJ(class GroupByType extends $gJ {
  constructor() {
    super({
      id: "refactorPreview.groupByType",
      title: localize2(4556, "Group Changes By Type"),
      category: localize2(4557, "Refactor Preview"),
      icon: $6l.groupByRefType,
      precondition: $7m.and($9_b.ctxHasCategories, $9_b.ctxGroupByFile, BulkEditPreviewContribution.ctxEnabled),
      menu: [{
        id: $bJ.BulkEditTitle,
        when: $7m.and($9_b.ctxHasCategories, $9_b.ctxGroupByFile),
        group: "navigation",
        order: 3
      }]
    });
  }
  async run(accessor) {
    const viewsService = accessor.get($uob);
    const view = await getBulkEditPane(viewsService);
    view?.groupByType();
  }
});
$hJ(class ToggleGrouping extends $gJ {
  constructor() {
    super({
      id: "refactorPreview.toggleGrouping",
      title: localize2(4558, "Group Changes By Type"),
      category: localize2(4559, "Refactor Preview"),
      icon: $6l.listTree,
      toggled: $9_b.ctxGroupByFile.negate(),
      precondition: $7m.and($9_b.ctxHasCategories, BulkEditPreviewContribution.ctxEnabled),
      menu: [{
        id: $bJ.BulkEditContext,
        order: 3
      }]
    });
  }
  async run(accessor) {
    const viewsService = accessor.get($uob);
    const view = await getBulkEditPane(viewsService);
    view?.toggleGrouping();
  }
});
$PL(
  BulkEditPreviewContribution.ID,
  BulkEditPreviewContribution,
  2
  /* WorkbenchPhase.BlockRestore */
);
var refactorPreviewViewIcon = $9r("refactor-preview-view-icon", $6l.lightbulb, localize(4547, null));
var container = $Wn.as(Extensions5.ViewContainersRegistry).registerViewContainer(
  {
    id: $9_b.ID,
    title: localize2(4560, "Refactor Preview"),
    hideIfEmpty: true,
    ctorDescriptor: new $Nk($oqb, [$9_b.ID, { mergeViewWithContainerWhenSingleView: true }]),
    icon: refactorPreviewViewIcon,
    storageId: $9_b.ID
  },
  1
  /* ViewContainerLocation.Panel */
);
$Wn.as(Extensions5.ViewsRegistry).registerViews([{
  id: $9_b.ID,
  name: localize2(4561, "Refactor Preview"),
  when: BulkEditPreviewContribution.ctxEnabled,
  ctorDescriptor: new $Nk($9_b),
  containerIcon: refactorPreviewViewIcon
}], container);

// out-build/vs/editor/contrib/quickAccess/browser/gotoLineQuickAccess.js
var $0_b = class _$0_b extends $a6b {
  static {
    this.PREFIX = ":";
  }
  constructor() {
    super({ canAcceptInBackground: true });
  }
  e(picker) {
    const label3 = localize(1378, null);
    picker.items = [{ label: label3 }];
    picker.ariaLabel = label3;
    return $3c.None;
  }
  d(context, picker, token) {
    const editor = context.editor;
    const disposables = new $2c();
    disposables.add(picker.onDidAccept((event) => {
      const [item] = picker.selectedItems;
      if (item) {
        if (!this.p(editor, item.lineNumber)) {
          return;
        }
        this.f(context, { range: this.m(item.lineNumber, item.column), keyMods: picker.keyMods, preserveFocus: event.inBackground });
        if (!event.inBackground) {
          picker.hide();
        }
      }
    }));
    const updatePickerAndEditor = () => {
      const position = this.n(editor, picker.value.trim().substr(_$0_b.PREFIX.length));
      const label3 = this.o(editor, position.lineNumber, position.column);
      picker.items = [{
        lineNumber: position.lineNumber,
        column: position.column,
        label: label3
      }];
      picker.ariaLabel = label3;
      if (!this.p(editor, position.lineNumber)) {
        this.clearDecorations(editor);
        return;
      }
      const range = this.m(position.lineNumber, position.column);
      editor.revealRangeInCenter(
        range,
        0
        /* ScrollType.Smooth */
      );
      this.addDecorations(editor, range);
    };
    updatePickerAndEditor();
    disposables.add(picker.onDidChangeValue(() => updatePickerAndEditor()));
    const codeEditor = $S5(editor);
    if (codeEditor) {
      const options3 = codeEditor.getOptions();
      const lineNumbers = options3.get(
        69
        /* EditorOption.lineNumbers */
      );
      if (lineNumbers.renderType === 2) {
        codeEditor.updateOptions({ lineNumbers: "on" });
        disposables.add($1c(() => codeEditor.updateOptions({ lineNumbers: "relative" })));
      }
    }
    return disposables;
  }
  m(lineNumber = 1, column = 1) {
    return {
      startLineNumber: lineNumber,
      startColumn: column,
      endLineNumber: lineNumber,
      endColumn: column
    };
  }
  n(editor, value) {
    const numbers = value.split(/,|:|#/).map((part) => parseInt(part, 10)).filter((part) => !isNaN(part));
    const endLine = this.r(editor) + 1;
    return {
      lineNumber: numbers[0] > 0 ? numbers[0] : endLine + numbers[0],
      column: numbers[1]
    };
  }
  o(editor, lineNumber, column) {
    if (this.p(editor, lineNumber)) {
      if (this.q(editor, lineNumber, column)) {
        return localize(1379, null, lineNumber, column);
      }
      return localize(1380, null, lineNumber);
    }
    const position = editor.getPosition() || { lineNumber: 1, column: 1 };
    const lineCount = this.r(editor);
    if (lineCount > 1) {
      return localize(1381, null, position.lineNumber, position.column, lineCount);
    }
    return localize(1382, null, position.lineNumber, position.column);
  }
  p(editor, lineNumber) {
    if (!lineNumber || typeof lineNumber !== "number") {
      return false;
    }
    return lineNumber > 0 && lineNumber <= this.r(editor);
  }
  q(editor, lineNumber, column) {
    if (!column || typeof column !== "number") {
      return false;
    }
    const model = this.g(editor);
    if (!model) {
      return false;
    }
    const positionCandidate = { lineNumber, column };
    return model.validatePosition(positionCandidate).equals(positionCandidate);
  }
  r(editor) {
    return this.g(editor)?.getLineCount() ?? 0;
  }
};

// out-build/vs/workbench/contrib/search/browser/replace.js
var $u7b = $Qk("replaceService");

// out-build/vs/workbench/contrib/search/browser/searchTreeModel/searchViewModelWorkbenchService.js
var $O7b = $Qk("searchViewModelWorkbenchService");

// out-build/vs/workbench/contrib/search/browser/notebookSearch/notebookSearchModelBase.js
function $N6b(obj) {
  return obj && typeof obj.bindNotebookEditorWidget === "function" && typeof obj.updateMatchesForEditorWidget === "function" && typeof obj.unbindNotebookEditorWidget === "function" && typeof obj.updateNotebookHighlights === "function" && $C6b(obj);
}
function $O6b(obj) {
  return typeof obj === "object" && obj !== null && typeof obj.parent === "function" && typeof obj.cellParent === "object" && typeof obj.isWebviewMatch === "function" && typeof obj.cellIndex === "number" && (typeof obj.webviewIndex === "number" || obj.webviewIndex === void 0) && (typeof obj.cell === "object" || obj.cell === void 0);
}

// out-build/vs/workbench/contrib/search/browser/replaceService.js
var $__b_1;
var REPLACE_PREVIEW = "replacePreview";
var toReplaceResource = (fileResource) => {
  return fileResource.with({ scheme: Schemas.internal, fragment: REPLACE_PREVIEW, query: JSON.stringify({ scheme: fileResource.scheme }) });
};
var toFileResource = (replaceResource) => {
  return replaceResource.with({ scheme: JSON.parse(replaceResource.query)["scheme"], fragment: "", query: "" });
};
var $$_b = class $$_b2 {
  static {
    this.ID = "workbench.contrib.replacePreviewContentProvider";
  }
  constructor(c, d) {
    this.c = c;
    this.d = d;
    this.d.registerTextModelContentProvider(Schemas.internal, this);
  }
  provideTextContent(uri) {
    if (uri.fragment === REPLACE_PREVIEW) {
      return this.c.createInstance(ReplacePreviewModel).resolve(uri);
    }
    return null;
  }
};
$$_b = __decorate([
  __param(0, $Pk),
  __param(1, $oG)
], $$_b);
var ReplacePreviewModel = class ReplacePreviewModel2 extends $3c {
  constructor(c, f, g, h3, j) {
    super();
    this.c = c;
    this.f = f;
    this.g = g;
    this.h = h3;
    this.j = j;
  }
  async resolve(replacePreviewUri) {
    const fileResource = toFileResource(replacePreviewUri);
    const fileMatch = this.j.searchModel.searchResult.matches(false).filter((match) => match.resource.toString() === fileResource.toString())[0];
    const ref = this.B(await this.g.createModelReference(fileResource));
    const sourceModel = ref.object.textEditorModel;
    const sourceModelLanguageId = sourceModel.getLanguageId();
    const replacePreviewModel = this.c.createModel($OI(sourceModel.createSnapshot()), this.f.createById(sourceModelLanguageId), replacePreviewUri);
    this.B(fileMatch.onChange(({ forceUpdateModel }) => this.m(sourceModel, replacePreviewModel, fileMatch, forceUpdateModel)));
    this.B(this.j.searchModel.onReplaceTermChanged(() => this.m(sourceModel, replacePreviewModel, fileMatch)));
    this.B(fileMatch.onDispose(() => replacePreviewModel.dispose()));
    this.B(replacePreviewModel.onWillDispose(() => this.dispose()));
    this.B(sourceModel.onWillDispose(() => this.dispose()));
    return replacePreviewModel;
  }
  m(sourceModel, replacePreviewModel, fileMatch, override = false) {
    if (!sourceModel.isDisposed() && !replacePreviewModel.isDisposed()) {
      this.h.updateReplacePreview(fileMatch, override);
    }
  }
};
ReplacePreviewModel = __decorate([
  __param(0, $sG),
  __param(1, $1E),
  __param(2, $oG),
  __param(3, $u7b),
  __param(4, $O7b)
], ReplacePreviewModel);
var $__b = class $__b2 {
  static {
    $__b_1 = this;
  }
  static {
    this.c = $bL.registerSource("searchReplace.source", localize(9560, null));
  }
  constructor(d, f, g, h3, i2, j) {
    this.d = d;
    this.f = f;
    this.g = g;
    this.h = h3;
    this.i = i2;
    this.j = j;
  }
  async replace(arg, progress = void 0, resource = null) {
    const edits = this.l(arg, resource);
    await this.h.apply(edits, { progress });
    const rawTextPromises = edits.map(async (e) => {
      if (e.resource.scheme === Schemas.vscodeNotebookCell) {
        const notebookResource = CellUri.parse(e.resource)?.notebook;
        if (notebookResource) {
          let ref;
          try {
            ref = await this.j.resolve(notebookResource);
            await ref.object.save({ source: $__b_1.c });
          } finally {
            ref?.dispose();
          }
        }
        return;
      } else {
        return this.d.files.get(e.resource)?.save({ source: $__b_1.c });
      }
    });
    return Promises.settled(rawTextPromises);
  }
  async openReplacePreview(element, preserveFocus, sideBySide, pinned) {
    const fileMatch = $D6b(element) ? element.parent() : element;
    const editor = await this.f.openEditor({
      original: { resource: fileMatch.resource },
      modified: { resource: toReplaceResource(fileMatch.resource) },
      label: localize(9561, null, fileMatch.name(), fileMatch.name()),
      description: this.i.getUriLabel($uh(fileMatch.resource), { relative: true }),
      options: {
        preserveFocus,
        pinned,
        revealIfVisible: true
      }
    });
    const input = editor?.input;
    const disposable = fileMatch.onDispose(() => {
      input?.dispose();
      disposable.dispose();
    });
    await this.updateReplacePreview(fileMatch);
    if (editor) {
      const editorControl = editor.getControl();
      if ($D6b(element) && editorControl) {
        editorControl.revealLineInCenter(
          element.range().startLineNumber,
          1
          /* ScrollType.Immediate */
        );
      }
    }
  }
  async updateReplacePreview(fileMatch, override = false) {
    const replacePreviewUri = toReplaceResource(fileMatch.resource);
    const [sourceModelRef, replaceModelRef] = await Promise.all([this.g.createModelReference(fileMatch.resource), this.g.createModelReference(replacePreviewUri)]);
    const sourceModel = sourceModelRef.object.textEditorModel;
    const replaceModel = replaceModelRef.object.textEditorModel;
    try {
      if (sourceModel && replaceModel) {
        if (override) {
          replaceModel.setValue(sourceModel.getValue());
        } else {
          replaceModel.undo();
        }
        this.k(fileMatch, replaceModel);
      }
    } finally {
      sourceModelRef.dispose();
      replaceModelRef.dispose();
    }
  }
  k(fileMatch, replaceModel) {
    const resourceEdits = this.l(fileMatch, replaceModel.uri);
    const modelEdits = [];
    for (const resourceEdit of resourceEdits) {
      modelEdits.push($bD.replaceMove($9C.lift(resourceEdit.textEdit.range), resourceEdit.textEdit.text));
    }
    replaceModel.pushEditOperations([], modelEdits.sort((a, b) => $9C.compareRangesUsingStarts(a.range, b.range)), () => []);
  }
  l(arg, resource = null) {
    const edits = [];
    if ($D6b(arg)) {
      if (!arg.isReadonly) {
        if ($O6b(arg)) {
          const match = arg;
          edits.push(this.m(match, match.replaceString, match.cell?.uri));
        } else {
          const match = arg;
          edits.push(this.m(match, match.replaceString, resource));
        }
      }
    }
    if ($C6b(arg)) {
      arg = [arg];
    }
    if (arg instanceof Array) {
      arg.forEach((element) => {
        const fileMatch = element;
        if (fileMatch.count() > 0) {
          edits.push(...fileMatch.matches().flatMap((match) => this.l(match, resource)));
        }
      });
    }
    return edits;
  }
  m(match, text2, resource = null) {
    const fileMatch = match.parent();
    return new $J_(resource ?? fileMatch.resource, { range: match.range(), text: text2 }, void 0, void 0);
  }
};
$__b = $__b_1 = __decorate([
  __param(0, $cK),
  __param(1, $mJ),
  __param(2, $oG),
  __param(3, $H_),
  __param(4, $ZI),
  __param(5, $orb)
], $__b);

// out-build/vs/workbench/contrib/search/browser/replaceContributions.js
function $aac() {
  $SC(
    $u7b,
    $__b,
    1
    /* InstantiationType.Delayed */
  );
  $PL(
    $$_b.ID,
    $$_b,
    1
    /* WorkbenchPhase.BlockStartup */
  );
}

// out-build/vs/workbench/contrib/search/common/notebookSearch.js
var $t7b = $Qk("notebookSearchService");

// out-build/vs/workbench/contrib/search/common/searchNotebookHelpers.js
function $gS(object) {
  return "cellResults" in object;
}
var $hS = "rawCell#";
function $iS(contentMatches, buffer) {
  let previousEndLine = -1;
  const contextGroupings = [];
  let currentContextGrouping = [];
  contentMatches.forEach((match) => {
    if (match.range.startLineNumber !== previousEndLine) {
      if (currentContextGrouping.length > 0) {
        contextGroupings.push([...currentContextGrouping]);
        currentContextGrouping = [];
      }
    }
    currentContextGrouping.push(match);
    previousEndLine = match.range.endLineNumber;
  });
  if (currentContextGrouping.length > 0) {
    contextGroupings.push([...currentContextGrouping]);
  }
  const textSearchResults = contextGroupings.map((grouping) => {
    const lineTexts = [];
    const firstLine3 = grouping[0].range.startLineNumber;
    const lastLine = grouping[grouping.length - 1].range.endLineNumber;
    for (let i2 = firstLine3; i2 <= lastLine; i2++) {
      lineTexts.push(buffer.getLineContent(i2));
    }
    return new $YN(lineTexts.join("\n") + "\n", grouping.map((m) => new $9C(m.range.startLineNumber - 1, m.range.startColumn - 1, m.range.endLineNumber - 1, m.range.endColumn - 1)));
  });
  return textSearchResults;
}

// out-build/vs/workbench/contrib/search/browser/notebookSearch/searchNotebookHelpers.js
function $I6b(match) {
  if ($K6b(match)) {
    return match.cell.id;
  } else {
    return `${$hS}${match.index}`;
  }
}
function $J6b(object) {
  return "cellResults" in object && object.cellResults instanceof Array && object.cellResults.every($K6b);
}
function $K6b(object) {
  return "cell" in object;
}
function $L6b(contentMatches, cell) {
  return $iS(contentMatches, cell.textBuffer);
}
function $M6b(webviewMatches) {
  return webviewMatches.map((rawMatch) => rawMatch.searchPreviewInfo ? new $YN(rawMatch.searchPreviewInfo.line, new $9C(0, rawMatch.searchPreviewInfo.range.start, 0, rawMatch.searchPreviewInfo.range.end), void 0, rawMatch.index) : void 0).filter((e) => !!e);
}

// out-build/vs/workbench/contrib/search/browser/notebookSearch/notebookSearchService.js
var $bac = class $bac2 {
  constructor(b, c, d, f, g, h3, i2, instantiationService) {
    this.b = b;
    this.c = c;
    this.d = d;
    this.f = f;
    this.g = g;
    this.h = h3;
    this.i = i2;
    this.a = instantiationService.createInstance($eT);
  }
  notebookSearch(query, token, searchInstanceID, onProgress) {
    if (query.type !== 2) {
      return {
        openFilesToScan: new $Fc(),
        completeData: Promise.resolve({
          messages: [],
          limitHit: false,
          results: []
        }),
        allScannedFiles: Promise.resolve(new $Fc())
      };
    }
    const localNotebookWidgets = this.m();
    const localNotebookFiles = localNotebookWidgets.map((widget) => widget.viewModel.uri);
    const getAllResults = () => {
      const searchStart = Date.now();
      const localResultPromise = this.l(query, token ?? CancellationToken.None, localNotebookWidgets, searchInstanceID);
      const searchLocalEnd = Date.now();
      const experimentalNotebooksEnabled = this.g.getValue("search").experimental?.closedNotebookRichContentResults ?? false;
      let closedResultsPromise = Promise.resolve(void 0);
      if (experimentalNotebooksEnabled) {
        closedResultsPromise = this.k(query, new $Fc(localNotebookFiles, (uri) => this.b.extUri.getComparisonKey(uri)), token ?? CancellationToken.None);
      }
      const promise = Promise.all([localResultPromise, closedResultsPromise]);
      return {
        completeData: promise.then((resolvedPromise) => {
          const openNotebookResult = resolvedPromise[0];
          const closedNotebookResult = resolvedPromise[1];
          const resolved = resolvedPromise.filter((e) => !!e);
          const resultArray = [...openNotebookResult.results.values(), ...closedNotebookResult?.results.values() ?? []];
          const results = $Mb(resultArray);
          if (onProgress) {
            results.forEach(onProgress);
          }
          this.d.trace(`local notebook search time | ${searchLocalEnd - searchStart}ms`);
          return {
            messages: [],
            limitHit: resolved.reduce((prev, cur) => prev || cur.limitHit, false),
            results
          };
        }),
        allScannedFiles: promise.then((resolvedPromise) => {
          const openNotebookResults = resolvedPromise[0];
          const closedNotebookResults = resolvedPromise[1];
          const results = $Mb([...openNotebookResults.results.keys(), ...closedNotebookResults?.results.keys() ?? []]);
          return new $Fc(results, (uri) => this.b.extUri.getComparisonKey(uri));
        })
      };
    };
    const promiseResults = getAllResults();
    return {
      openFilesToScan: new $Fc(localNotebookFiles),
      completeData: promiseResults.completeData,
      allScannedFiles: promiseResults.allScannedFiles
    };
  }
  async j(includes2, folderQueries, token) {
    const promises = includes2.map(async (includePattern) => {
      const query = this.a.file(folderQueries.map((e) => e.folder), {
        includePattern: includePattern.startsWith("/") ? includePattern : "**/" + includePattern,
        // todo: find cleaner way to ensure that globs match all appropriate filetypes
        exists: true,
        onlyFileScheme: true
      });
      return this.i.fileSearch(query, token).then((ret) => {
        return !!ret.limitHit;
      });
    });
    return Promise.any(promises);
  }
  async k(textQuery, scannedFiles, token) {
    const userAssociations = this.h.getAllUserAssociations();
    const allPriorityInfo = /* @__PURE__ */ new Map();
    const contributedNotebookTypes = this.f.getContributedNotebookTypes();
    userAssociations.forEach((association) => {
      if (!association.filenamePattern) {
        return;
      }
      const info = {
        isFromSettings: true,
        filenamePatterns: [association.filenamePattern]
      };
      const existingEntry = allPriorityInfo.get(association.viewType);
      if (existingEntry) {
        allPriorityInfo.set(association.viewType, existingEntry.concat(info));
      } else {
        allPriorityInfo.set(association.viewType, [info]);
      }
    });
    const promises = [];
    contributedNotebookTypes.forEach((notebook) => {
      if (notebook.selectors.length > 0) {
        promises.push((async () => {
          const includes2 = notebook.selectors.map((selector) => {
            const globPattern = selector.include || selector;
            return globPattern.toString();
          });
          const isInWorkspace = await this.j(includes2, textQuery.folderQueries, token);
          if (isInWorkspace) {
            const canResolve = await this.f.canResolve(notebook.id);
            if (!canResolve) {
              return void 0;
            }
            const serializer = (await this.f.withNotebookDataProvider(notebook.id)).serializer;
            return await serializer.searchInNotebooks(textQuery, token, allPriorityInfo);
          } else {
            return void 0;
          }
        })());
      }
    });
    const start = Date.now();
    const searchComplete = $Mb(await Promise.all(promises));
    const results = searchComplete.flatMap((e) => e.results);
    let limitHit = searchComplete.some((e) => e.limitHit);
    const uniqueResults = new $Ec((uri) => this.b.extUri.getComparisonKey(uri));
    let numResults = 0;
    for (const result of results) {
      if (textQuery.maxResults && numResults >= textQuery.maxResults) {
        limitHit = true;
        break;
      }
      if (!scannedFiles.has(result.resource) && !uniqueResults.has(result.resource)) {
        uniqueResults.set(result.resource, result.cellResults.length > 0 ? result : null);
        numResults++;
      }
    }
    const end = Date.now();
    this.d.trace(`query: ${textQuery.contentPattern.pattern}`);
    this.d.trace(`closed notebook search time | ${end - start}ms`);
    return {
      results: uniqueResults,
      limitHit
    };
  }
  async l(query, token, widgets2, searchID) {
    const localResults = new $Ec((uri) => this.b.extUri.getComparisonKey(uri));
    let limitHit = false;
    for (const widget of widgets2) {
      if (!widget.hasModel()) {
        continue;
      }
      const askMax = ($Dg(query.maxResults) ? query.maxResults : $SN) + 1;
      const uri = widget.viewModel.uri;
      if (!$3N(query, uri.fsPath)) {
        continue;
      }
      let matches = await widget.find(query.contentPattern.pattern, {
        regex: query.contentPattern.isRegExp,
        wholeWord: query.contentPattern.isWordMatch,
        caseSensitive: query.contentPattern.isCaseSensitive,
        includeMarkupInput: query.contentPattern.notebookInfo?.isInNotebookMarkdownInput ?? true,
        includeMarkupPreview: query.contentPattern.notebookInfo?.isInNotebookMarkdownPreview ?? true,
        includeCodeInput: query.contentPattern.notebookInfo?.isInNotebookCellInput ?? true,
        includeOutput: query.contentPattern.notebookInfo?.isInNotebookCellOutput ?? true
      }, token, false, true, searchID);
      if (matches.length) {
        if (askMax && matches.length >= askMax) {
          limitHit = true;
          matches = matches.slice(0, askMax - 1);
        }
        const cellResults = matches.map((match) => {
          const contentResults = $L6b(match.contentMatches, match.cell);
          const webviewResults = $M6b(match.webviewMatches);
          return {
            cell: match.cell,
            index: match.index,
            contentResults,
            webviewResults
          };
        });
        const fileMatch = {
          resource: uri,
          cellResults
        };
        localResults.set(uri, fileMatch);
      } else {
        localResults.set(uri, null);
      }
    }
    return {
      results: localResults,
      limitHit
    };
  }
  m() {
    const notebookWidgets = this.c.retrieveAllExistingWidgets();
    return notebookWidgets.map((widget) => widget.value).filter((val) => !!val && val.hasModel());
  }
};
$bac = __decorate([
  __param(0, $vl),
  __param(1, $yMb),
  __param(2, $wn),
  __param(3, $mrb),
  __param(4, $kl),
  __param(5, $4L),
  __param(6, $TN),
  __param(7, $Pk)
], $bac);

// out-build/vs/workbench/contrib/search/browser/notebookSearch/notebookSearchContributions.js
function $cac() {
  $SC(
    $t7b,
    $bac,
    1
    /* InstantiationType.Delayed */
  );
}

// out-build/vs/workbench/contrib/search/browser/searchIcons.js
var $96b = $9r("search-details", $6l.ellipsis, localize(9683, null));
var $06b = $9r("search-see-more", $6l.goToSearch, localize(9684, null));
var $$6b = $9r("search-show-context", $6l.listSelection, localize(9685, null));
var $_6b = $9r("search-hide-replace", $6l.chevronRight, localize(9686, null));
var $a7b = $9r("search-show-replace", $6l.chevronDown, localize(9687, null));
var $b7b = $9r("search-replace-all", $6l.replaceAll, localize(9688, null));
var $c7b = $9r("search-replace", $6l.replace, localize(9689, null));
var $d7b = $9r("search-remove", $6l.close, localize(9690, null));
var $e7b = $9r("search-refresh", $6l.refresh, localize(9691, null));
var $f7b = $9r("search-collapse-results", $6l.collapseAll, localize(9692, null));
var $g7b = $9r("search-expand-results", $6l.expandAll, localize(9693, null));
var $h7b = $9r("search-tree", $6l.listTree, localize(9694, null));
var $i7b = $9r("search-list", $6l.listFlat, localize(9695, null));
var $j7b = $9r("search-clear-results", $6l.clearAll, localize(9696, null));
var $k7b = $9r("search-stop", $6l.searchStop, localize(9697, null));
var $l7b = $9r("search-view-icon", $6l.search, localize(9698, null));
var $m7b = $9r("search-new-editor", $6l.newFile, localize(9699, null));
var $n7b = $9r("search-open-in-file", $6l.goToFile, localize(9700, null));
var $o7b = $9r("search-sparkle-filled", $6l.sparkleFilled, localize(9701, null));
var $p7b = $9r("search-sparkle-empty", $6l.sparkle, localize(9702, null));

// out-build/vs/workbench/contrib/search/browser/patternInputWidget.js
var $F6b = class $F6b2 extends $qZ {
  static {
    this.OPTION_CHANGE = "optionChange";
  }
  constructor(parent, r2, options3, t, w, y) {
    super();
    this.r = r2;
    this.t = t;
    this.w = w;
    this.y = y;
    this.h = this.B(new $ze());
    this.onSubmit = this.h.event;
    this.n = this.B(new $ze());
    this.onCancel = this.n.event;
    options3 = {
      ...{
        ariaLabel: localize(9550, null)
      },
      ...options3
    };
    this.a = options3.width ?? 100;
    this.J(options3);
    parent.appendChild(this.c);
  }
  dispose() {
    super.dispose();
    this.inputFocusTracker?.dispose();
  }
  setWidth(newWidth) {
    this.a = newWidth;
    this.r.layout();
    this.H();
  }
  getValue() {
    return this.g.value;
  }
  setValue(value) {
    if (this.g.value !== value) {
      this.g.value = value;
    }
  }
  select() {
    this.g.select();
  }
  focus() {
    this.g.focus();
  }
  inputHasFocus() {
    return this.g.hasFocus();
  }
  H() {
    this.g.width = this.a - this.I() - 2;
  }
  I() {
    return 0;
  }
  getHistory() {
    return this.g.getHistory();
  }
  clearHistory() {
    this.g.clearHistory();
  }
  prependHistory(history) {
    this.g.prependHistory(history);
  }
  clear() {
    this.setValue("");
  }
  onSearchSubmit() {
    this.g.addToHistory();
  }
  showNextTerm() {
    this.g.showNextValue();
  }
  showPreviousTerm() {
    this.g.showPreviousValue();
  }
  J(options3) {
    this.c = document.createElement("div");
    this.c.classList.add("monaco-findInput");
    const history = options3.history || [];
    this.g = new $9bb(this.c, this.r, {
      placeholder: options3.placeholder,
      showPlaceholderOnFocus: options3.showPlaceholderOnFocus,
      tooltip: options3.tooltip,
      ariaLabel: options3.ariaLabel,
      validationOptions: {
        validation: void 0
      },
      history: new Set(history),
      showHistoryHint: () => $ggb(this.y),
      inputBoxStyles: options3.inputBoxStyles
    }, this.t);
    this.B(this.g.onDidChange(() => this.h.fire(true)));
    this.inputFocusTracker = $_j(this.g.inputElement);
    this.u(this.g.inputElement, (keyboardEvent) => this.M(keyboardEvent));
    const controls = document.createElement("div");
    controls.className = "controls";
    this.L(controls);
    this.c.appendChild(controls);
    this.H();
  }
  L(_controlsDiv) {
  }
  M(keyboardEvent) {
    switch (keyboardEvent.keyCode) {
      case 3:
        this.onSearchSubmit();
        this.h.fire(false);
        return;
      case 9:
        this.n.fire();
        return;
    }
  }
};
$F6b = __decorate([
  __param(3, $on),
  __param(4, $kl),
  __param(5, $Ty)
], $F6b);
var $G6b = class $G6b2 extends $F6b {
  constructor(parent, contextViewProvider, options3, contextKeyService, configurationService, keybindingService) {
    super(parent, contextViewProvider, options3, contextKeyService, configurationService, keybindingService);
    this.N = this.B(new $ze());
    this.onChangeSearchInEditorsBox = this.N.event;
  }
  dispose() {
    super.dispose();
    this.O.dispose();
  }
  onlySearchInOpenEditors() {
    return this.O.checked;
  }
  setOnlySearchInOpenEditors(value) {
    this.O.checked = value;
    this.N.fire();
  }
  I() {
    return super.I() + this.O.width();
  }
  L(controlsDiv) {
    this.O = this.B(new $Q1({
      icon: $6l.book,
      title: localize(9551, null),
      isChecked: false,
      hoverDelegate: $JZ("element"),
      ...$u$
    }));
    this.B(this.O.onChange((viaKeyboard) => {
      this.N.fire();
      if (!viaKeyboard) {
        this.g.focus();
      }
    }));
    controlsDiv.appendChild(this.O.domNode);
    super.L(controlsDiv);
  }
};
$G6b = __decorate([
  __param(3, $on),
  __param(4, $kl),
  __param(5, $Ty)
], $G6b);
var $H6b = class $H6b2 extends $F6b {
  constructor(parent, contextViewProvider, options3, contextKeyService, configurationService, keybindingService) {
    super(parent, contextViewProvider, options3, contextKeyService, configurationService, keybindingService);
    this.N = this.B(new $ze());
    this.onChangeIgnoreBox = this.N.event;
  }
  dispose() {
    super.dispose();
    this.O.dispose();
  }
  useExcludesAndIgnoreFiles() {
    return this.O.checked;
  }
  setUseExcludesAndIgnoreFiles(value) {
    this.O.checked = value;
    this.N.fire();
  }
  I() {
    return super.I() + this.O.width();
  }
  L(controlsDiv) {
    this.O = this.B(new $Q1({
      icon: $6l.exclude,
      actionClassName: "useExcludesAndIgnoreFiles",
      title: localize(9552, null),
      isChecked: true,
      hoverDelegate: $JZ("element"),
      ...$u$
    }));
    this.B(this.O.onChange((viaKeyboard) => {
      this.N.fire();
      if (!viaKeyboard) {
        this.g.focus();
      }
    }));
    controlsDiv.appendChild(this.O.domNode);
    super.L(controlsDiv);
  }
};
$H6b = __decorate([
  __param(3, $on),
  __param(4, $kl),
  __param(5, $Ty)
], $H6b);

// out-build/vs/workbench/contrib/search/browser/AISearch/aiSearchModelBase.js
function $P6b(obj) {
  return obj && obj.getFullRange && obj.getFullRange() instanceof $9C;
}

// out-build/vs/workbench/contrib/search/browser/searchCompare.js
var elemAIndex = -1;
var elemBIndex = -1;
function $Q6b(elementA, elementB, sortOrder = "default") {
  if ($C6b(elementA) && $y6b(elementB)) {
    return 1;
  }
  if ($C6b(elementB) && $y6b(elementA)) {
    return -1;
  }
  if ($y6b(elementA) && $y6b(elementB)) {
    elemAIndex = elementA.index();
    elemBIndex = elementB.index();
    if (elemAIndex !== -1 && elemBIndex !== -1) {
      return elemAIndex - elemBIndex;
    }
    if ($P6b(elementA) && $P6b(elementB)) {
      return elementA.rank - elementB.rank;
    }
    switch (sortOrder) {
      case "countDescending":
        return elementB.count() - elementA.count();
      case "countAscending":
        return elementA.count() - elementB.count();
      case "type":
        return $JM(elementA.name(), elementB.name());
      case "fileNames":
        return $EM(elementA.name(), elementB.name());
      default:
        if (!elementA.resource || !elementB.resource) {
          return 0;
        }
        return $OM(elementA.resource.fsPath, elementB.resource.fsPath) || $EM(elementA.name(), elementB.name());
    }
  }
  if ($C6b(elementA) && $C6b(elementB)) {
    switch (sortOrder) {
      case "countDescending":
        return elementB.count() - elementA.count();
      case "countAscending":
        return elementA.count() - elementB.count();
      case "type":
        return $JM(elementA.name(), elementB.name());
      case "fileNames":
        return $EM(elementA.name(), elementB.name());
      case "modified": {
        const fileStatA = elementA.fileStat;
        const fileStatB = elementB.fileStat;
        if (fileStatA && fileStatB) {
          return fileStatB.mtime - fileStatA.mtime;
        }
      }
      default:
        return $OM(elementA.resource.fsPath, elementB.resource.fsPath) || $EM(elementA.name(), elementB.name());
    }
  }
  if ($O6b(elementA) && $O6b(elementB)) {
    return compareNotebookPos(elementA, elementB);
  }
  if ($D6b(elementA) && $D6b(elementB)) {
    return $9C.compareRangesUsingStarts(elementA.range(), elementB.range());
  }
  return 0;
}
function compareNotebookPos(match1, match2) {
  if (match1.cellIndex === match2.cellIndex) {
    if (match1.webviewIndex !== void 0 && match2.webviewIndex !== void 0) {
      return match1.webviewIndex - match2.webviewIndex;
    } else if (match1.webviewIndex === void 0 && match2.webviewIndex === void 0) {
      return $9C.compareRangesUsingStarts(match1.range(), match2.range());
    } else {
      if (match1.webviewIndex !== void 0) {
        return 1;
      } else {
        return -1;
      }
    }
  } else if (match1.cellIndex < match2.cellIndex) {
    return -1;
  } else {
    return 1;
  }
}
function $R6b(elementA, elementB, sortOrder = "default") {
  const elemAParents = $m6b(elementA);
  const elemBParents = $m6b(elementB);
  let i2 = elemAParents.length - 1;
  let j = elemBParents.length - 1;
  while (i2 >= 0 && j >= 0) {
    if (elemAParents[i2].id() !== elemBParents[j].id()) {
      return $Q6b(elemAParents[i2], elemBParents[j], sortOrder);
    }
    i2--;
    j--;
  }
  const elemAAtEnd = i2 === 0;
  const elemBAtEnd = j === 0;
  if (elemAAtEnd && !elemBAtEnd) {
    return 1;
  } else if (!elemAAtEnd && elemBAtEnd) {
    return -1;
  }
  return 0;
}

// out-build/vs/workbench/contrib/search/browser/searchActionsBase.js
var $S6b = localize2(9635, "Search");
function $T6b(viewsService) {
  const searchView = $V6b(viewsService);
  return !!(searchView && $Nj(searchView.getContainer()));
}
function $U6b(label3, inputKeyBinding) {
  return doAppendKeyBindingLabel(label3, inputKeyBinding);
}
function $V6b(viewsService) {
  return viewsService.getActiveViewWithId($PN);
}
function $W6b(viewer, currElement, sortConfig) {
  let elements = viewer.getSelection().filter((x) => x !== null).sort((a, b) => $R6b(a, b, sortConfig.sortOrder));
  if (currElement && !(elements.length > 1 && elements.includes(currElement))) {
    elements = [currElement];
  }
  return elements;
}
function $X6b(elements, focusElement) {
  if (!focusElement) {
    return false;
  }
  return !focusElement || elements.includes(focusElement) || hasDownstreamMatch(elements, focusElement);
}
function hasDownstreamMatch(elements, focusElement) {
  for (const elem of elements) {
    if ($C6b(elem) && $D6b(focusElement) && elem.matches().includes(focusElement) || $y6b(elem) && ($C6b(focusElement) && elem.getDownstreamFileMatch(focusElement.resource) || $D6b(focusElement) && elem.getDownstreamFileMatch(focusElement.parent().resource))) {
      return true;
    }
  }
  return false;
}
function $Y6b(viewsService, focus) {
  return viewsService.openView($PN, focus).then((view) => view ?? void 0);
}
function doAppendKeyBindingLabel(label3, keyBinding) {
  return keyBinding ? label3 + " (" + keyBinding.getLabel() + ")" : label3;
}

// out-build/vs/workbench/contrib/search/browser/searchMessage.js
var $57b = (message, instantiationService, notificationService, openerService, commandService, disposableStore, triggerSearch) => {
  const div = $("div.providerMessage");
  const linkedText = $U3(message.text);
  $bk(div, $("." + SeverityIcon.className(message.type === TextSearchCompleteMessageType.Information ? severity_default.Info : severity_default.Warning).split(" ").join(".")));
  for (const node of linkedText.nodes) {
    if (typeof node === "string") {
      $bk(div, document.createTextNode(node));
    } else {
      const link2 = instantiationService.createInstance(Link2, div, node, {
        opener: async (href) => {
          if (!message.trusted) {
            return;
          }
          const parsed = URI.parse(href, true);
          if (parsed.scheme === Schemas.command && message.trusted) {
            const result = await commandService.executeCommand(parsed.path);
            if (result?.triggerSearch) {
              triggerSearch();
            }
          } else if (parsed.scheme === Schemas.https) {
            openerService.open(parsed);
          } else {
            if (parsed.scheme === Schemas.command && !message.trusted) {
              notificationService.error(localize(9703, null, href));
            } else {
              notificationService.error(localize(9704, null, href));
            }
          }
        }
      });
      disposableStore.add(link2);
    }
  }
  return div;
};

// out-build/vs/workbench/contrib/search/browser/searchResultsView.js
var $k8b_1;
var $l8b_1;
var $m8b_1;
var $n8b_1;
var $j8b = class _$j8b {
  static {
    this.ITEM_HEIGHT = 22;
  }
  getHeight(element) {
    return _$j8b.ITEM_HEIGHT;
  }
  getTemplateId(element) {
    if ($y6b(element)) {
      return $l8b.TEMPLATE_ID;
    } else if ($C6b(element)) {
      return $m8b.TEMPLATE_ID;
    } else if ($D6b(element)) {
      return $n8b.TEMPLATE_ID;
    } else if ($w6b(element)) {
      return $k8b.TEMPLATE_ID;
    }
    console.error("Invalid search tree element", element);
    throw new Error("Invalid search tree element");
  }
};
var $k8b = class $k8b2 extends $3c {
  static {
    $k8b_1 = this;
  }
  static {
    this.TEMPLATE_ID = "textResultMatch";
  }
  constructor(a, b) {
    super();
    this.a = a;
    this.b = b;
    this.templateId = $k8b_1.TEMPLATE_ID;
  }
  disposeCompressedElements(node, index, templateData, height) {
  }
  renderTemplate(container2) {
    const disposables = new $2c();
    const textSearchResultElement = $bk(container2, $(".textsearchresult"));
    const label3 = this.a.create(textSearchResultElement, { supportDescriptionHighlights: true, supportHighlights: true, supportIcons: true });
    disposables.add(label3);
    return { label: label3, disposables };
  }
  async renderElement(node, index, templateData, height) {
    if ($x6b(node.element)) {
      templateData.label.setLabel(localize(9705, null));
    } else {
      const aiName = await node.element.parent().searchModel.getAITextResultProviderName();
      const localizedLabel = localize(9706, null, aiName);
      templateData.label.setLabel(`$(${$6l.copilot.id}) ${localizedLabel}`);
    }
  }
  disposeTemplate(templateData) {
    templateData.disposables.dispose();
  }
  renderCompressedElements(node, index, templateData, height) {
  }
};
$k8b = $k8b_1 = __decorate([
  __param(1, $Zk)
], $k8b);
var $l8b = class $l8b2 extends $3c {
  static {
    $l8b_1 = this;
  }
  static {
    this.TEMPLATE_ID = "folderMatch";
  }
  constructor(a, b, c, f, h3, j) {
    super();
    this.a = a;
    this.b = b;
    this.c = c;
    this.f = f;
    this.h = h3;
    this.j = j;
    this.templateId = $l8b_1.TEMPLATE_ID;
  }
  renderCompressedElements(node, index, templateData, height) {
    const compressed = node.element;
    const folder = compressed.elements[compressed.elements.length - 1];
    const label3 = compressed.elements.map((e) => e.name());
    if (folder.resource) {
      const fileKind = $A6b(folder) ? FileKind.ROOT_FOLDER : FileKind.FOLDER;
      templateData.label.setResource({ resource: folder.resource, name: label3 }, {
        fileKind,
        separator: this.f.getSeparator(folder.resource.scheme)
      });
    } else {
      templateData.label.setLabel(localize(9707, null));
    }
    this.m(folder, templateData);
  }
  renderTemplate(container2) {
    const disposables = new $2c();
    const folderMatchElement = $bk(container2, $(".foldermatch"));
    const label3 = this.b.create(folderMatchElement, { supportDescriptionHighlights: true, supportHighlights: true });
    disposables.add(label3);
    const badge = new $D2($bk(folderMatchElement, $(".badge")), {}, $E$);
    disposables.add(badge);
    const actionBarContainer = $bk(folderMatchElement, $(".actionBarContainer"));
    const elementDisposables = new $2c();
    disposables.add(elementDisposables);
    const contextKeyServiceMain = disposables.add(this.j.createScoped(container2));
    $eRb.MatchFocusKey.bindTo(contextKeyServiceMain).set(false);
    $eRb.FileFocusKey.bindTo(contextKeyServiceMain).set(false);
    $eRb.FolderFocusKey.bindTo(contextKeyServiceMain).set(true);
    const instantiationService = this.B(this.h.createChild(new $Ok([$on, contextKeyServiceMain])));
    const actions = disposables.add(instantiationService.createInstance($4$, actionBarContainer, $bJ.SearchActionMenu, {
      menuOptions: {
        shouldForwardArgs: true
      },
      hiddenItemStrategy: 0,
      toolbarOptions: {
        primaryGroup: (g) => /^inline/.test(g)
      }
    }));
    return {
      label: label3,
      badge,
      actions,
      disposables,
      elementDisposables,
      contextKeyService: contextKeyServiceMain
    };
  }
  renderElement(node, index, templateData) {
    const folderMatch = node.element;
    if (folderMatch.resource) {
      const workspaceFolder = this.c.getWorkspaceFolder(folderMatch.resource);
      if (workspaceFolder && $oh(workspaceFolder.uri, folderMatch.resource)) {
        templateData.label.setFile(folderMatch.resource, { fileKind: FileKind.ROOT_FOLDER, hidePath: true });
      } else {
        templateData.label.setFile(folderMatch.resource, { fileKind: FileKind.FOLDER, hidePath: this.a.ld });
      }
    } else {
      templateData.label.setLabel(localize(9708, null));
    }
    $eRb.IsEditableItemKey.bindTo(templateData.contextKeyService).set(!folderMatch.hasOnlyReadOnlyMatches());
    templateData.elementDisposables.add(folderMatch.onChange(() => {
      $eRb.IsEditableItemKey.bindTo(templateData.contextKeyService).set(!folderMatch.hasOnlyReadOnlyMatches());
    }));
    this.m(folderMatch, templateData);
  }
  disposeElement(element, index, templateData) {
    templateData.elementDisposables.clear();
  }
  disposeCompressedElements(node, index, templateData, height) {
    templateData.elementDisposables.clear();
  }
  disposeTemplate(templateData) {
    templateData.disposables.dispose();
  }
  m(folder, templateData) {
    const count = folder.recursiveMatchCount();
    templateData.badge.setCount(count);
    templateData.badge.setTitleFormat(count > 1 ? localize(9709, null, count) : localize(9710, null, count));
    templateData.actions.context = { viewer: this.a.getControl(), element: folder };
  }
};
$l8b = $l8b_1 = __decorate([
  __param(2, $Zk),
  __param(3, $ZI),
  __param(4, $Pk),
  __param(5, $on)
], $l8b);
var $m8b = class $m8b2 extends $3c {
  static {
    $m8b_1 = this;
  }
  static {
    this.TEMPLATE_ID = "fileMatch";
  }
  constructor(a, b, c, f, h3, j) {
    super();
    this.a = a;
    this.b = b;
    this.c = c;
    this.f = f;
    this.h = h3;
    this.j = j;
    this.templateId = $m8b_1.TEMPLATE_ID;
  }
  renderCompressedElements(node, index, templateData, height) {
    throw new Error("Should never happen since node is incompressible.");
  }
  renderTemplate(container2) {
    const disposables = new $2c();
    const elementDisposables = new $2c();
    disposables.add(elementDisposables);
    const fileMatchElement = $bk(container2, $(".filematch"));
    const label3 = this.b.create(fileMatchElement);
    disposables.add(label3);
    const badge = new $D2($bk(fileMatchElement, $(".badge")), {}, $E$);
    disposables.add(badge);
    const actionBarContainer = $bk(fileMatchElement, $(".actionBarContainer"));
    const contextKeyServiceMain = disposables.add(this.j.createScoped(container2));
    $eRb.MatchFocusKey.bindTo(contextKeyServiceMain).set(false);
    $eRb.FileFocusKey.bindTo(contextKeyServiceMain).set(true);
    $eRb.FolderFocusKey.bindTo(contextKeyServiceMain).set(false);
    const instantiationService = this.B(this.h.createChild(new $Ok([$on, contextKeyServiceMain])));
    const actions = disposables.add(instantiationService.createInstance($4$, actionBarContainer, $bJ.SearchActionMenu, {
      menuOptions: {
        shouldForwardArgs: true
      },
      hiddenItemStrategy: 0,
      toolbarOptions: {
        primaryGroup: (g) => /^inline/.test(g)
      }
    }));
    return {
      el: fileMatchElement,
      label: label3,
      badge,
      actions,
      disposables,
      elementDisposables,
      contextKeyService: contextKeyServiceMain
    };
  }
  renderElement(node, index, templateData) {
    const fileMatch = node.element;
    templateData.el.setAttribute("data-resource", fileMatch.resource.toString());
    const decorationConfig = this.f.getValue("search").decorations;
    templateData.label.setFile(fileMatch.resource, { range: $P6b(fileMatch) ? fileMatch.getFullRange() : void 0, hidePath: this.a.ld && !$B6b(fileMatch.parent()), hideIcon: false, fileDecorations: { colors: decorationConfig.colors, badges: decorationConfig.badges } });
    const count = fileMatch.count();
    templateData.badge.setCount(count);
    templateData.badge.setTitleFormat(count > 1 ? localize(9711, null, count) : localize(9712, null, count));
    templateData.actions.context = { viewer: this.a.getControl(), element: fileMatch };
    $eRb.IsEditableItemKey.bindTo(templateData.contextKeyService).set(!fileMatch.hasOnlyReadOnlyMatches());
    templateData.elementDisposables.add(fileMatch.onChange(() => {
      $eRb.IsEditableItemKey.bindTo(templateData.contextKeyService).set(!fileMatch.hasOnlyReadOnlyMatches());
    }));
    const twistieContainer = templateData.el.parentElement?.parentElement?.querySelector(".monaco-tl-twistie");
    twistieContainer?.classList.add("force-twistie");
  }
  disposeElement(element, index, templateData) {
    templateData.elementDisposables.clear();
  }
  disposeTemplate(templateData) {
    templateData.disposables.dispose();
  }
};
$m8b = $m8b_1 = __decorate([
  __param(2, $Zk),
  __param(3, $kl),
  __param(4, $Pk),
  __param(5, $on)
], $m8b);
var $n8b = class $n8b2 extends $3c {
  static {
    $n8b_1 = this;
  }
  static {
    this.TEMPLATE_ID = "match";
  }
  constructor(a, b, c, f, h3, j) {
    super();
    this.a = a;
    this.b = b;
    this.c = c;
    this.f = f;
    this.h = h3;
    this.j = j;
    this.templateId = $n8b_1.TEMPLATE_ID;
  }
  renderCompressedElements(node, index, templateData, height) {
    throw new Error("Should never happen since node is incompressible.");
  }
  renderTemplate(container2) {
    container2.classList.add("linematch");
    const lineNumber = $bk(container2, $("span.matchLineNum"));
    const parent = $bk(container2, $("a.plain.match"));
    const before = $bk(parent, $("span"));
    const match = $bk(parent, $("span.findInFileMatch"));
    const replace = $bk(parent, $("span.replaceMatch"));
    const after = $bk(parent, $("span"));
    const actionBarContainer = $bk(container2, $("span.actionBarContainer"));
    const disposables = new $2c();
    const contextKeyServiceMain = disposables.add(this.h.createScoped(container2));
    $eRb.MatchFocusKey.bindTo(contextKeyServiceMain).set(true);
    $eRb.FileFocusKey.bindTo(contextKeyServiceMain).set(false);
    $eRb.FolderFocusKey.bindTo(contextKeyServiceMain).set(false);
    const instantiationService = this.B(this.f.createChild(new $Ok([$on, contextKeyServiceMain])));
    const actions = disposables.add(instantiationService.createInstance($4$, actionBarContainer, $bJ.SearchActionMenu, {
      menuOptions: {
        shouldForwardArgs: true
      },
      hiddenItemStrategy: 0,
      toolbarOptions: {
        primaryGroup: (g) => /^inline/.test(g)
      }
    }));
    return {
      parent,
      before,
      match,
      replace,
      after,
      lineNumber,
      actions,
      disposables,
      contextKeyService: contextKeyServiceMain
    };
  }
  renderElement(node, index, templateData) {
    const match = node.element;
    const preview = match.preview();
    const replace = this.a.model.isReplaceActive() && !!this.a.model.replaceString && !match.isReadonly;
    templateData.before.textContent = preview.before;
    templateData.match.textContent = preview.inside;
    templateData.match.classList.toggle("replace", replace);
    templateData.replace.textContent = replace ? match.replaceString : "";
    templateData.after.textContent = preview.after;
    const title = (preview.fullBefore + (replace ? match.replaceString : preview.inside) + preview.after).trim().substr(0, 999);
    templateData.disposables.add(this.j.setupManagedHover($JZ("mouse"), templateData.parent, title));
    $eRb.IsEditableItemKey.bindTo(templateData.contextKeyService).set(!match.isReadonly);
    const numLines = match.range().endLineNumber - match.range().startLineNumber;
    const extraLinesStr = numLines > 0 ? `+${numLines}` : "";
    const showLineNumbers = this.c.getValue("search").showLineNumbers;
    const lineNumberStr = showLineNumbers ? `${match.range().startLineNumber}:` : "";
    templateData.lineNumber.classList.toggle("show", numLines > 0 || showLineNumbers);
    templateData.lineNumber.textContent = lineNumberStr + extraLinesStr;
    templateData.disposables.add(this.j.setupManagedHover($JZ("mouse"), templateData.lineNumber, this.m(match, showLineNumbers)));
    templateData.actions.context = { viewer: this.a.getControl(), element: match };
  }
  disposeTemplate(templateData) {
    templateData.disposables.dispose();
  }
  m(match, showLineNumbers) {
    const startLine = match.range().startLineNumber;
    const numLines = match.range().endLineNumber - match.range().startLineNumber;
    const lineNumStr = showLineNumbers ? localize(9713, null, startLine, numLines) + " " : "";
    const numLinesStr = numLines > 0 ? "+ " + localize(9714, null, numLines) : "";
    return lineNumStr + numLinesStr;
  }
};
$n8b = $n8b_1 = __decorate([
  __param(1, $Zk),
  __param(2, $kl),
  __param(3, $Pk),
  __param(4, $on),
  __param(5, $5$)
], $n8b);
var $o8b = class $o8b2 {
  constructor(a, b) {
    this.a = a;
    this.b = b;
  }
  getWidgetAriaLabel() {
    return localize(9715, null);
  }
  getAriaLabel(element) {
    if ($y6b(element)) {
      const count = element.allDownstreamFileMatches().reduce((total, current) => total + current.count(), 0);
      return element.resource ? localize(9716, null, count, element.name()) : localize(9717, null, count);
    }
    if ($C6b(element)) {
      const path = this.b.getUriLabel(element.resource, { relative: true }) || element.resource.fsPath;
      return localize(9718, null, element.count(), element.name(), $qc(path));
    }
    if ($D6b(element)) {
      const match = element;
      const searchModel = this.a.model;
      const replace = searchModel.isReplaceActive() && !!searchModel.replaceString;
      const matchString = match.getMatchString();
      const range = match.range();
      const matchText = match.text().substr(0, range.endColumn + 150);
      if (replace) {
        return localize(9719, null, matchText, range.startColumn, matchString, match.replaceString);
      }
      return localize(9720, null, matchText, range.startColumn, matchString);
    }
    return null;
  }
};
$o8b = __decorate([
  __param(1, $ZI)
], $o8b);

// out-build/vs/workbench/contrib/searchEditor/browser/constants.js
var $Z6b = new $nn("inSearchEditor", false);
var $16b = "search-editor";
var $26b = "search/editor";
var $36b = "searchEditorFindMatch";
var $46b = "workbench.editor.searchEditor";
var $56b = "search.action.openNewEditor";
var $66b = "search.action.openEditor";
var $76b = "toggleSearchEditorContextLines";
var $86b = "workbench.editorinputs.searchEditorInput";

// out-build/vs/workbench/contrib/search/browser/searchFindInput.js
var $q7b = class extends $0bb {
  constructor(container2, contextViewProvider, options3, contextKeyService, contextMenuService, instantiationService, filters2, filterStartVisiblitity) {
    super(container2, contextViewProvider, options3, contextKeyService);
    this.contextMenuService = contextMenuService;
    this.instantiationService = instantiationService;
    this.filters = filters2;
    this.$ = false;
    this.ab = this.B(new $ze());
    this.onDidChangeAIToggle = this.ab.event;
    this.g = this.B(new $n3b(filters2, contextMenuService, instantiationService, options3, localize(9682, null)));
    this.bb();
    this.I.appendChild(this.g.container);
    this.g.container.classList.add("monaco-custom-toggle");
    this.filterVisible = filterStartVisiblitity;
  }
  bb() {
    this.inputBox.paddingRight = (this.M?.visible ? this.M.width() : 0) + (this.L?.visible ? this.L.width() : 0) + (this.J?.visible ? this.J.width() : 0) + (this.g.visible ? this.g.width() : 0);
  }
  set filterVisible(visible) {
    this.g.visible = visible;
    this.updateFilterStyles();
    this.bb();
  }
  setEnabled(enabled) {
    super.setEnabled(enabled);
    if (enabled && (!this.$ || !this.g.visible)) {
      this.J?.enable();
    } else {
      this.J?.disable();
    }
  }
  updateFilterStyles() {
    this.$ = !this.filters.markupInput || !this.filters.markupPreview || !this.filters.codeInput || !this.filters.codeOutput;
    this.g.applyStyles(this.$);
  }
};

// out-build/vs/workbench/contrib/search/browser/searchWidget.js
var $r7b_1;
var SingleLineInputHeight = 26;
var ReplaceAllAction = class _ReplaceAllAction extends $Um {
  static {
    this.ID = "search.action.replaceAll";
  }
  constructor(a) {
    super(_ReplaceAllAction.ID, "", ThemeIcon.asClassName($b7b), false);
    this.a = a;
  }
  set searchWidget(searchWidget) {
    this.a = searchWidget;
  }
  run() {
    if (this.a) {
      return this.a.triggerReplaceAll();
    }
    return Promise.resolve(null);
  }
};
var ctrlKeyMod4 = $m ? 256 : 2048;
function stopPropagationForMultiLineUpwards2(event, value, textarea) {
  const isMultiline2 = !!value.match(/\n/);
  if (textarea && (isMultiline2 || textarea.clientHeight > SingleLineInputHeight) && textarea.selectionStart > 0) {
    event.stopPropagation();
    return;
  }
}
function stopPropagationForMultiLineDownwards2(event, value, textarea) {
  const isMultiline2 = !!value.match(/\n/);
  if (textarea && (isMultiline2 || textarea.clientHeight > SingleLineInputHeight) && textarea.selectionEnd < textarea.value.length) {
    event.stopPropagation();
    return;
  }
}
var $r7b = class $r7b2 extends $qZ {
  static {
    $r7b_1 = this;
  }
  static {
    this.a = 134;
  }
  static {
    this.c = localize(9776, null);
  }
  static {
    this.g = (keyBindingService2) => {
      const kb = keyBindingService2.lookupKeybinding(ReplaceAllAction.ID);
      return $U6b(localize(9777, null), kb);
    };
  }
  constructor(container2, options3, bb, cb, db, eb, fb, gb, hb, ib, jb) {
    super();
    this.bb = bb;
    this.cb = cb;
    this.db = db;
    this.eb = eb;
    this.fb = fb;
    this.gb = gb;
    this.hb = hb;
    this.ib = ib;
    this.jb = jb;
    this.J = false;
    this.L = null;
    this.M = this.B(new $ze());
    this.onSearchSubmit = this.M.event;
    this.N = this.B(new $ze());
    this.onSearchCancel = this.N.event;
    this.O = this.B(new $ze());
    this.onReplaceToggled = this.O.event;
    this.P = this.B(new $ze());
    this.onReplaceStateChange = this.P.event;
    this.Q = this.B(new $ze());
    this.onPreserveCaseChange = this.Q.event;
    this.R = this.B(new $ze());
    this.onReplaceValueChanged = this.R.event;
    this.S = this.B(new $ze());
    this.onReplaceAll = this.S.event;
    this.U = this.B(new $ze());
    this.onBlur = this.U.event;
    this.W = this.B(new $ze());
    this.onDidHeightChange = this.W.event;
    this.X = new $ze();
    this.onDidToggleContext = this.X.event;
    this.y = $eRb.ReplaceActiveKey.bindTo(this.cb);
    this.h = $eRb.SearchInputBoxFocusedKey.bindTo(this.cb);
    this.r = $eRb.ReplaceInputBoxFocusedKey.bindTo(this.cb);
    const notebookOptions = options3.notebookOptions ?? {
      isInNotebookMarkdownInput: true,
      isInNotebookMarkdownPreview: true,
      isInNotebookCellInput: true,
      isInNotebookCellOutput: true
    };
    this.Z = this.B(new $MIb(notebookOptions.isInNotebookMarkdownInput, notebookOptions.isInNotebookMarkdownPreview, notebookOptions.isInNotebookCellInput, notebookOptions.isInNotebookCellOutput, { findScopeType: NotebookFindScopeType.None }));
    this.B(this.Z.onDidChange(() => {
      if (this.searchInput) {
        this.searchInput.updateFilterStyles();
      }
    }));
    this.B(this.jb.onDidEditorsChange((e) => {
      if (this.searchInput && e.event.editor instanceof $trb && (e.event.kind === 5 || e.event.kind === 6)) {
        this.searchInput.filterVisible = this.lb();
      }
    }));
    this.I = new $Sh(500);
    this.ab = this.B(new $4c());
    this.mb(container2, options3);
    this.B(this.fb.onDidChangeConfiguration((e) => {
      if (e.affectsConfiguration("editor.accessibilitySupport")) {
        this.nb();
      }
    }));
    this.B(this.gb.onDidChangeScreenReaderOptimized(() => this.nb()));
    this.nb();
  }
  lb() {
    const editors = this.jb.editors;
    return editors.some((editor) => editor instanceof $trb);
  }
  getNotebookFilters() {
    return this.Z;
  }
  focus(select = true, focusReplace = false, suppressGlobalSearchBuffer = false) {
    this.J = suppressGlobalSearchBuffer;
    if (focusReplace && this.isReplaceShown()) {
      if (this.replaceInput) {
        this.replaceInput.focus();
        if (select) {
          this.replaceInput.select();
        }
      }
    } else {
      if (this.searchInput) {
        this.searchInput.focus();
        if (select) {
          this.searchInput.select();
        }
      }
    }
  }
  setWidth(width2) {
    this.searchInput?.inputBox.layout();
    if (this.replaceInput) {
      this.replaceInput.width = width2 - 28;
      this.replaceInput.inputBox.layout();
    }
  }
  clear() {
    this.searchInput?.clear();
    this.replaceInput?.setValue("");
    this.setReplaceAllActionState(false);
  }
  isReplaceShown() {
    return this.n ? !this.n.classList.contains("disabled") : false;
  }
  isReplaceActive() {
    return !!this.y.get();
  }
  getReplaceValue() {
    return this.replaceInput?.getValue() ?? "";
  }
  toggleReplace(show2) {
    if (show2 === void 0 || show2 !== this.isReplaceShown()) {
      this.sb();
    }
  }
  getSearchHistory() {
    return this.searchInput?.inputBox.getHistory() ?? [];
  }
  getReplaceHistory() {
    return this.replaceInput?.inputBox.getHistory() ?? [];
  }
  prependSearchHistory(history) {
    this.searchInput?.inputBox.prependHistory(history);
  }
  prependReplaceHistory(history) {
    this.replaceInput?.inputBox.prependHistory(history);
  }
  clearHistory() {
    this.searchInput?.inputBox.clearHistory();
    this.replaceInput?.inputBox.clearHistory();
  }
  showNextSearchTerm() {
    this.searchInput?.inputBox.showNextValue();
  }
  showPreviousSearchTerm() {
    this.searchInput?.inputBox.showPreviousValue();
  }
  showNextReplaceTerm() {
    this.replaceInput?.inputBox.showNextValue();
  }
  showPreviousReplaceTerm() {
    this.replaceInput?.inputBox.showPreviousValue();
  }
  searchInputHasFocus() {
    return !!this.h.get();
  }
  replaceInputHasFocus() {
    return !!this.replaceInput?.inputBox.hasFocus();
  }
  focusReplaceAllAction() {
    this.H?.focus(true);
  }
  focusRegexAction() {
    this.searchInput?.focusOnRegex();
  }
  set replaceButtonVisibility(val) {
    if (this.t) {
      this.t.element.style.display = val ? "" : "none";
    }
  }
  mb(container2, options3) {
    this.domNode = $bk(container2, $(".search-widget"));
    this.domNode.style.position = "relative";
    if (!options3._hideReplaceToggle) {
      this.ob(this.domNode);
    }
    this.pb(this.domNode, options3);
    this.rb(this.domNode, options3);
  }
  nb() {
    this.searchInput?.setFocusInputOnOptionClick(!this.gb.isScreenReaderOptimized());
  }
  ob(parent) {
    const opts = {
      buttonBackground: void 0,
      buttonBorder: void 0,
      buttonForeground: void 0,
      buttonHoverBackground: void 0,
      buttonSecondaryBackground: void 0,
      buttonSecondaryForeground: void 0,
      buttonSecondaryHoverBackground: void 0,
      buttonSeparator: void 0,
      title: localize(9778, null),
      hoverDelegate: $JZ("element")
    };
    this.t = this.B(new $k2(parent, opts));
    this.t.element.setAttribute("aria-expanded", "false");
    this.t.element.classList.add("toggle-replace-button");
    this.t.icon = $_6b;
    this.ab.value = this.t.onDidClick(() => this.sb());
  }
  pb(parent, options3) {
    const history = options3.searchHistory || [];
    const inputOptions2 = {
      label: localize(9779, null),
      validation: (value) => this.ub(value),
      placeholder: localize(9780, null),
      appendCaseSensitiveLabel: $U6b("", this.db.lookupKeybinding(
        "toggleSearchCaseSensitive"
        /* Constants.SearchCommandIds.ToggleCaseSensitiveCommandId */
      )),
      appendWholeWordsLabel: $U6b("", this.db.lookupKeybinding(
        "toggleSearchWholeWord"
        /* Constants.SearchCommandIds.ToggleWholeWordCommandId */
      )),
      appendRegexLabel: $U6b("", this.db.lookupKeybinding(
        "toggleSearchRegex"
        /* Constants.SearchCommandIds.ToggleRegexCommandId */
      )),
      history: new Set(history),
      showHistoryHint: () => $ggb(this.db),
      flexibleHeight: true,
      flexibleMaxHeight: $r7b_1.a,
      showCommonFindToggles: true,
      inputBoxStyles: options3.inputBoxStyles,
      toggleStyles: options3.toggleStyles
    };
    const searchInputContainer = $bk(parent, $(".search-container.input-box"));
    this.searchInput = this.B(new $q7b(searchInputContainer, this.bb, inputOptions2, this.cb, this.hb, this.ib, this.Z, this.lb()));
    this.B(this.searchInput.onKeyDown((keyboardEvent) => this.wb(keyboardEvent)));
    this.searchInput.setValue(options3.value || "");
    this.searchInput.setRegex(!!options3.isRegex);
    this.searchInput.setCaseSensitive(!!options3.isCaseSensitive);
    this.searchInput.setWholeWords(!!options3.isWholeWords);
    this.B(this.searchInput.onCaseSensitiveKeyDown((keyboardEvent) => this.xb(keyboardEvent)));
    this.B(this.searchInput.onRegexKeyDown((keyboardEvent) => this.yb(keyboardEvent)));
    this.B(this.searchInput.inputBox.onDidChange(() => this.vb()));
    this.B(this.searchInput.inputBox.onDidHeightChange(() => this.W.fire()));
    this.B(this.onReplaceValueChanged(() => {
      this.I.trigger(() => this.replaceInput?.inputBox.addToHistory());
    }));
    this.searchInputFocusTracker = this.B($_j(this.searchInput.inputBox.inputElement));
    this.B(this.searchInputFocusTracker.onDidFocus(async () => {
      this.h.set(true);
      const useGlobalFindBuffer = this.Db.globalFindClipboard;
      if (!this.J && useGlobalFindBuffer) {
        const globalBufferText = await this.eb.readFindText();
        if (globalBufferText && this.L !== globalBufferText) {
          this.searchInput?.inputBox.addToHistory();
          this.searchInput?.setValue(globalBufferText);
          this.searchInput?.select();
        }
        this.L = globalBufferText;
      }
      this.J = false;
    }));
    this.B(this.searchInputFocusTracker.onDidBlur(() => this.h.set(false)));
    this.Y = new $Q1({
      isChecked: false,
      title: $U6b(localize(9781, null), this.db.lookupKeybinding($76b)),
      icon: $$6b,
      hoverDelegate: $JZ("element"),
      ...$u$
    });
    this.B(this.Y.onChange(() => this.qb()));
    if (options3.showContextToggle) {
      this.contextLinesInput = new $I2(searchInputContainer, this.bb, { type: "number", inputBoxStyles: $B$ });
      this.contextLinesInput.element.classList.add("context-lines-input");
      this.contextLinesInput.value = "" + (this.fb.getValue("search").searchEditor.defaultNumberOfContextLines ?? 1);
      this.B(this.contextLinesInput.onDidChange((value) => {
        if (value !== "0") {
          this.Y.checked = true;
        }
        this.qb();
      }));
      $bk(searchInputContainer, this.Y.domNode);
    }
  }
  qb() {
    this.X.fire();
    if (this.contextLinesInput.value.includes("-")) {
      this.contextLinesInput.value = "0";
    }
    this.X.fire();
  }
  setContextLines(lines) {
    if (!this.contextLinesInput) {
      return;
    }
    if (lines === 0) {
      this.Y.checked = false;
    } else {
      this.Y.checked = true;
      this.contextLinesInput.value = "" + lines;
    }
  }
  rb(parent, options3) {
    this.n = $bk(parent, $(".replace-container.disabled"));
    const replaceBox = $bk(this.n, $(".replace-input"));
    this.replaceInput = this.B(new $$bb(replaceBox, this.bb, {
      label: localize(9782, null),
      placeholder: localize(9783, null),
      appendPreserveCaseLabel: $U6b("", this.db.lookupKeybinding(
        "toggleSearchPreserveCase"
        /* Constants.SearchCommandIds.TogglePreserveCaseId */
      )),
      history: options3.replaceHistory,
      showHistoryHint: () => $ggb(this.db),
      flexibleHeight: true,
      flexibleMaxHeight: $r7b_1.a,
      inputBoxStyles: options3.inputBoxStyles,
      toggleStyles: options3.toggleStyles
    }, this.cb, true));
    this.B(this.replaceInput.onDidOptionChange((viaKeyboard) => {
      if (!viaKeyboard) {
        if (this.replaceInput) {
          this.Q.fire(this.replaceInput.getPreserveCase());
        }
      }
    }));
    this.B(this.replaceInput.onKeyDown((keyboardEvent) => this.Ab(keyboardEvent)));
    this.replaceInput.setValue(options3.replaceValue || "");
    this.B(this.replaceInput.inputBox.onDidChange(() => this.R.fire()));
    this.B(this.replaceInput.inputBox.onDidHeightChange(() => this.W.fire()));
    this.w = new ReplaceAllAction(this);
    this.w.label = $r7b_1.c;
    this.H = this.B(new $LZ(this.n));
    this.H.push([this.w], { icon: true, label: false });
    this.s(this.H.domNode, (keyboardEvent) => this.Bb(keyboardEvent));
    this.replaceInputFocusTracker = this.B($_j(this.replaceInput.inputBox.inputElement));
    this.B(this.replaceInputFocusTracker.onDidFocus(() => this.r.set(true)));
    this.B(this.replaceInputFocusTracker.onDidBlur(() => this.r.set(false)));
    this.B(this.replaceInput.onPreserveCaseKeyDown((keyboardEvent) => this.zb(keyboardEvent)));
  }
  triggerReplaceAll() {
    this.S.fire();
    return Promise.resolve(null);
  }
  sb() {
    this.n?.classList.toggle("disabled");
    if (this.isReplaceShown()) {
      this.t?.element.classList.remove(...ThemeIcon.asClassNameArray($_6b));
      this.t?.element.classList.add(...ThemeIcon.asClassNameArray($a7b));
    } else {
      this.t?.element.classList.remove(...ThemeIcon.asClassNameArray($a7b));
      this.t?.element.classList.add(...ThemeIcon.asClassNameArray($_6b));
    }
    this.t?.element.setAttribute("aria-expanded", this.isReplaceShown() ? "true" : "false");
    this.tb();
    this.O.fire();
  }
  setValue(value) {
    this.searchInput?.setValue(value);
  }
  setReplaceAllActionState(enabled) {
    if (this.w && this.w.enabled !== enabled) {
      this.w.enabled = enabled;
      this.w.label = enabled ? $r7b_1.g(this.db) : $r7b_1.c;
      this.tb();
    }
  }
  tb() {
    const currentState = this.isReplaceActive();
    const newState = this.isReplaceShown() && !!this.w?.enabled;
    if (currentState !== newState) {
      this.y.set(newState);
      this.P.fire(newState);
      this.replaceInput?.inputBox.layout();
    }
  }
  ub(value) {
    if (value.length === 0) {
      return null;
    }
    if (!this.searchInput?.getRegex()) {
      return null;
    }
    try {
      new RegExp(value, "u");
    } catch (e) {
      return { content: e.message };
    }
    return null;
  }
  vb() {
    this.searchInput?.clearMessage();
    this.setReplaceAllActionState(false);
    if (this.Db.searchOnType) {
      if (this.searchInput?.getRegex()) {
        try {
          const regex = new RegExp(this.searchInput.getValue(), "ug");
          const matchienessHeuristic = `
								~!@#$%^&*()_+
								\`1234567890-=
								qwertyuiop[]\\
								QWERTYUIOP{}|
								asdfghjkl;'
								ASDFGHJKL:"
								zxcvbnm,./
								ZXCVBNM<>? `.match(regex)?.length ?? 0;
          const delayMultiplier = matchienessHeuristic < 50 ? 1 : matchienessHeuristic < 100 ? 5 : (
            // expressions like `.` or `\w`
            10
          );
          this.Cb(true, this.Db.searchOnTypeDebouncePeriod * delayMultiplier);
        } catch {
        }
      } else {
        this.Cb(true, this.Db.searchOnTypeDebouncePeriod);
      }
    }
  }
  wb(keyboardEvent) {
    if (keyboardEvent.equals(
      ctrlKeyMod4 | 3
      /* KeyCode.Enter */
    )) {
      this.searchInput?.inputBox.insertAtCursor("\n");
      keyboardEvent.preventDefault();
    }
    if (keyboardEvent.equals(
      3
      /* KeyCode.Enter */
    )) {
      this.searchInput?.onSearchSubmit();
      this.Cb();
      keyboardEvent.preventDefault();
    } else if (keyboardEvent.equals(
      9
      /* KeyCode.Escape */
    )) {
      this.N.fire({ focus: true });
      keyboardEvent.preventDefault();
    } else if (keyboardEvent.equals(
      2
      /* KeyCode.Tab */
    )) {
      if (this.isReplaceShown()) {
        this.replaceInput?.focus();
      } else {
        this.searchInput?.focusOnCaseSensitive();
      }
      keyboardEvent.preventDefault();
    } else if (keyboardEvent.equals(
      16
      /* KeyCode.UpArrow */
    )) {
      stopPropagationForMultiLineUpwards2(keyboardEvent, this.searchInput?.getValue() ?? "", this.searchInput?.domNode.querySelector("textarea") ?? null);
    } else if (keyboardEvent.equals(
      18
      /* KeyCode.DownArrow */
    )) {
      stopPropagationForMultiLineDownwards2(keyboardEvent, this.searchInput?.getValue() ?? "", this.searchInput?.domNode.querySelector("textarea") ?? null);
    } else if (keyboardEvent.equals(
      11
      /* KeyCode.PageUp */
    )) {
      const inputElement = this.searchInput?.inputBox.inputElement;
      if (inputElement) {
        inputElement.setSelectionRange(0, 0);
        inputElement.focus();
        keyboardEvent.preventDefault();
      }
    } else if (keyboardEvent.equals(
      12
      /* KeyCode.PageDown */
    )) {
      const inputElement = this.searchInput?.inputBox.inputElement;
      if (inputElement) {
        const endOfText = inputElement.value.length;
        inputElement.setSelectionRange(endOfText, endOfText);
        inputElement.focus();
        keyboardEvent.preventDefault();
      }
    }
  }
  xb(keyboardEvent) {
    if (keyboardEvent.equals(
      1024 | 2
      /* KeyCode.Tab */
    )) {
      if (this.isReplaceShown()) {
        this.replaceInput?.focus();
        keyboardEvent.preventDefault();
      }
    }
  }
  yb(keyboardEvent) {
    if (keyboardEvent.equals(
      2
      /* KeyCode.Tab */
    )) {
      if (this.isReplaceShown()) {
        this.replaceInput?.focusOnPreserve();
        keyboardEvent.preventDefault();
      }
    }
  }
  zb(keyboardEvent) {
    if (keyboardEvent.equals(
      2
      /* KeyCode.Tab */
    )) {
      if (this.isReplaceActive()) {
        this.focusReplaceAllAction();
      } else {
        this.U.fire();
      }
      keyboardEvent.preventDefault();
    } else if (keyboardEvent.equals(
      1024 | 2
      /* KeyCode.Tab */
    )) {
      this.focusRegexAction();
      keyboardEvent.preventDefault();
    }
  }
  Ab(keyboardEvent) {
    if (keyboardEvent.equals(
      ctrlKeyMod4 | 3
      /* KeyCode.Enter */
    )) {
      this.replaceInput?.inputBox.insertAtCursor("\n");
      keyboardEvent.preventDefault();
    }
    if (keyboardEvent.equals(
      3
      /* KeyCode.Enter */
    )) {
      this.Cb();
      keyboardEvent.preventDefault();
    } else if (keyboardEvent.equals(
      2
      /* KeyCode.Tab */
    )) {
      this.searchInput?.focusOnCaseSensitive();
      keyboardEvent.preventDefault();
    } else if (keyboardEvent.equals(
      1024 | 2
      /* KeyCode.Tab */
    )) {
      this.searchInput?.focus();
      keyboardEvent.preventDefault();
    } else if (keyboardEvent.equals(
      16
      /* KeyCode.UpArrow */
    )) {
      stopPropagationForMultiLineUpwards2(keyboardEvent, this.replaceInput?.getValue() ?? "", this.replaceInput?.domNode.querySelector("textarea") ?? null);
    } else if (keyboardEvent.equals(
      18
      /* KeyCode.DownArrow */
    )) {
      stopPropagationForMultiLineDownwards2(keyboardEvent, this.replaceInput?.getValue() ?? "", this.replaceInput?.domNode.querySelector("textarea") ?? null);
    }
  }
  Bb(keyboardEvent) {
    if (keyboardEvent.equals(
      1024 | 2
      /* KeyCode.Tab */
    )) {
      this.focusRegexAction();
      keyboardEvent.preventDefault();
    }
  }
  async Cb(triggeredOnType = false, delay = 0) {
    this.searchInput?.validate();
    if (!this.searchInput?.inputBox.isInputValid()) {
      return;
    }
    const value = this.searchInput.getValue();
    const useGlobalFindBuffer = this.Db.globalFindClipboard;
    if (value && useGlobalFindBuffer) {
      await this.eb.writeFindText(value);
    }
    this.M.fire({ triggeredOnType, delay });
  }
  getContextLines() {
    return this.Y.checked ? +this.contextLinesInput.value : 0;
  }
  modifyContextLines(increase) {
    const current = +this.contextLinesInput.value;
    const modified = current + (increase ? 1 : -1);
    this.Y.checked = modified !== 0;
    this.contextLinesInput.value = "" + modified;
  }
  toggleContextLines() {
    this.Y.checked = !this.Y.checked;
    this.qb();
  }
  dispose() {
    this.setReplaceAllActionState(false);
    super.dispose();
  }
  get Db() {
    return this.fb.getValue("search");
  }
};
$r7b = $r7b_1 = __decorate([
  __param(2, $40),
  __param(3, $on),
  __param(4, $Ty),
  __param(5, $30),
  __param(6, $kl),
  __param(7, $ND),
  __param(8, $50),
  __param(9, $Pk),
  __param(10, $mJ)
], $r7b);
function $s7b() {
  $0I.registerCommandAndKeybindingRule({
    id: ReplaceAllAction.ID,
    weight: 200,
    when: $7m.and($eRb.SearchViewVisibleKey, $eRb.ReplaceActiveKey, $7fb),
    primary: 512 | 2048 | 3,
    handler: (accessor) => {
      const viewsService = accessor.get($uob);
      if ($T6b(viewsService)) {
        const searchView = $V6b(viewsService);
        if (searchView) {
          new ReplaceAllAction(searchView.searchAndReplaceWidget).run();
        }
      }
    }
  });
}

// out-build/vs/workbench/contrib/search/common/searchHistoryService.js
var $e8b_1;
var $d8b = $Qk("searchHistoryService");
var $e8b = class $e8b2 {
  static {
    $e8b_1 = this;
  }
  static {
    this.SEARCH_HISTORY_KEY = "workbench.search.history";
  }
  constructor(b) {
    this.b = b;
    this.a = new $ze();
    this.onDidClearHistory = this.a.event;
  }
  clearHistory() {
    this.b.remove(
      $e8b_1.SEARCH_HISTORY_KEY,
      1
      /* StorageScope.WORKSPACE */
    );
    this.a.fire();
  }
  load() {
    let result;
    const raw = this.b.get(
      $e8b_1.SEARCH_HISTORY_KEY,
      1
      /* StorageScope.WORKSPACE */
    );
    if (raw) {
      try {
        result = JSON.parse(raw);
      } catch (e) {
      }
    }
    return result || {};
  }
  save(history) {
    if ($Mg(history)) {
      this.b.remove(
        $e8b_1.SEARCH_HISTORY_KEY,
        1
        /* StorageScope.WORKSPACE */
      );
    } else {
      this.b.store(
        $e8b_1.SEARCH_HISTORY_KEY,
        JSON.stringify(history),
        1,
        0
        /* StorageTarget.USER */
      );
    }
  }
};
$e8b = $e8b_1 = __decorate([
  __param(0, $jv)
], $e8b);

// out-build/vs/workbench/contrib/searchEditor/browser/searchEditorSerialization.js
var lineDelimiter = "\n";
var translateRangeLines = (n) => (range) => new $9C(range.startLineNumber + n, range.startColumn, range.endLineNumber + n, range.endColumn);
var matchToSearchResultFormat = (match, longestLineNumber) => {
  const getLinePrefix = (i2) => `${match.range().startLineNumber + i2}`;
  const fullMatchLines = match.fullPreviewLines();
  const results = [];
  fullMatchLines.forEach((sourceLine, i2) => {
    const lineNumber = getLinePrefix(i2);
    const paddingStr = " ".repeat(longestLineNumber - lineNumber.length);
    const prefix = `  ${paddingStr}${lineNumber}: `;
    const prefixOffset = prefix.length;
    const line = prefix + (sourceLine.split(/\r?\n?$/, 1)[0] || "");
    const rangeOnThisLine = ({ start, end }) => new $9C(1, (start ?? 1) + prefixOffset, 1, (end ?? sourceLine.length + 1) + prefixOffset);
    const matchRange = match.rangeInPreview();
    const matchIsSingleLine = matchRange.startLineNumber === matchRange.endLineNumber;
    let lineRange;
    if (matchIsSingleLine) {
      lineRange = rangeOnThisLine({ start: matchRange.startColumn, end: matchRange.endColumn });
    } else if (i2 === 0) {
      lineRange = rangeOnThisLine({ start: matchRange.startColumn });
    } else if (i2 === fullMatchLines.length - 1) {
      lineRange = rangeOnThisLine({ end: matchRange.endColumn });
    } else {
      lineRange = rangeOnThisLine({});
    }
    results.push({ lineNumber, line, ranges: [lineRange] });
  });
  return results;
};
function fileMatchToSearchResultFormat(fileMatch, labelFormatter) {
  const textSerializations = fileMatch.textMatches().length > 0 ? matchesToSearchResultFormat(fileMatch.resource, fileMatch.textMatches().sort($Q6b), fileMatch.context, labelFormatter) : void 0;
  const cellSerializations = $N6b(fileMatch) ? fileMatch.cellMatches().sort((a, b) => a.cellIndex - b.cellIndex).sort().filter((cellMatch) => cellMatch.contentMatches.length > 0).map((cellMatch, index) => cellMatchToSearchResultFormat(cellMatch, labelFormatter, index === 0)) : [];
  return [textSerializations, ...cellSerializations].filter((x) => !!x);
}
function matchesToSearchResultFormat(resource, sortedMatches, matchContext, labelFormatter, shouldUseHeader = true) {
  const longestLineNumber = sortedMatches[sortedMatches.length - 1].range().endLineNumber.toString().length;
  const text2 = shouldUseHeader ? [`${labelFormatter(resource)}:`] : [];
  const matchRanges = [];
  const targetLineNumberToOffset = {};
  const context = [];
  matchContext.forEach((line, lineNumber) => context.push({ line, lineNumber }));
  context.sort((a, b) => a.lineNumber - b.lineNumber);
  let lastLine = void 0;
  const seenLines = /* @__PURE__ */ new Set();
  sortedMatches.forEach((match) => {
    matchToSearchResultFormat(match, longestLineNumber).forEach((match2) => {
      if (!seenLines.has(match2.lineNumber)) {
        while (context.length && context[0].lineNumber < +match2.lineNumber) {
          const { line, lineNumber } = context.shift();
          if (lastLine !== void 0 && lineNumber !== lastLine + 1) {
            text2.push("");
          }
          text2.push(`  ${" ".repeat(longestLineNumber - `${lineNumber}`.length)}${lineNumber}  ${line}`);
          lastLine = lineNumber;
        }
        targetLineNumberToOffset[match2.lineNumber] = text2.length;
        seenLines.add(match2.lineNumber);
        text2.push(match2.line);
        lastLine = +match2.lineNumber;
      }
      matchRanges.push(...match2.ranges.map(translateRangeLines(targetLineNumberToOffset[match2.lineNumber])));
    });
  });
  while (context.length) {
    const { line, lineNumber } = context.shift();
    text2.push(`  ${lineNumber}  ${line}`);
  }
  return { text: text2, matchRanges };
}
function cellMatchToSearchResultFormat(cellMatch, labelFormatter, shouldUseHeader) {
  return matchesToSearchResultFormat(cellMatch.cell?.uri ?? cellMatch.parent.resource, cellMatch.contentMatches.sort($Q6b), cellMatch.context, labelFormatter, shouldUseHeader);
}
var contentPatternToSearchConfiguration = (pattern, includes2, excludes, contextLines) => {
  return {
    query: pattern.contentPattern.pattern,
    isRegexp: !!pattern.contentPattern.isRegExp,
    isCaseSensitive: !!pattern.contentPattern.isCaseSensitive,
    matchWholeWord: !!pattern.contentPattern.isWordMatch,
    filesToExclude: excludes,
    filesToInclude: includes2,
    showIncludesExcludes: !!(includes2 || excludes || pattern?.userDisabledExcludesAndIgnoreFiles),
    useExcludeSettingsAndIgnoreFiles: pattern?.userDisabledExcludesAndIgnoreFiles === void 0 ? true : !pattern.userDisabledExcludesAndIgnoreFiles,
    contextLines,
    onlyOpenEditors: !!pattern.onlyOpenEditors,
    notebookSearchConfig: {
      includeMarkupInput: !!pattern.contentPattern.notebookInfo?.isInNotebookMarkdownInput,
      includeMarkupPreview: !!pattern.contentPattern.notebookInfo?.isInNotebookMarkdownPreview,
      includeCodeInput: !!pattern.contentPattern.notebookInfo?.isInNotebookCellInput,
      includeOutput: !!pattern.contentPattern.notebookInfo?.isInNotebookCellOutput
    }
  };
};
var $R7b = (config) => {
  const removeNullFalseAndUndefined = (a) => a.filter((a2) => a2 !== false && a2 !== null && a2 !== void 0);
  const escapeNewlines = (str) => str.replace(/\\/g, "\\\\").replace(/\n/g, "\\n");
  return removeNullFalseAndUndefined([
    `# Query: ${escapeNewlines(config.query ?? "")}`,
    (config.isCaseSensitive || config.matchWholeWord || config.isRegexp || config.useExcludeSettingsAndIgnoreFiles === false) && `# Flags: ${$Mb([
      config.isCaseSensitive && "CaseSensitive",
      config.matchWholeWord && "WordMatch",
      config.isRegexp && "RegExp",
      config.onlyOpenEditors && "OpenEditors",
      config.useExcludeSettingsAndIgnoreFiles === false && "IgnoreExcludeSettings"
    ]).join(" ")}`,
    config.filesToInclude ? `# Including: ${config.filesToInclude}` : void 0,
    config.filesToExclude ? `# Excluding: ${config.filesToExclude}` : void 0,
    config.contextLines ? `# ContextLines: ${config.contextLines}` : void 0,
    ""
  ]).join(lineDelimiter);
};
var $T7b = () => ({
  query: "",
  filesToInclude: "",
  filesToExclude: "",
  isRegexp: false,
  isCaseSensitive: false,
  useExcludeSettingsAndIgnoreFiles: true,
  matchWholeWord: false,
  contextLines: 0,
  showIncludesExcludes: false,
  onlyOpenEditors: false,
  notebookSearchConfig: {
    includeMarkupInput: true,
    includeMarkupPreview: false,
    includeCodeInput: true,
    includeOutput: true
  }
});
var $U7b = (lines) => {
  const query = $T7b();
  const unescapeNewlines = (str) => {
    let out = "";
    for (let i2 = 0; i2 < str.length; i2++) {
      if (str[i2] === "\\") {
        i2++;
        const escaped = str[i2];
        if (escaped === "n") {
          out += "\n";
        } else if (escaped === "\\") {
          out += "\\";
        } else {
          throw Error(localize(9820, null));
        }
      } else {
        out += str[i2];
      }
    }
    return out;
  };
  const parseYML = /^# ([^:]*): (.*)$/;
  for (const line of lines) {
    const parsed = parseYML.exec(line);
    if (!parsed) {
      continue;
    }
    const [, key2, value] = parsed;
    switch (key2) {
      case "Query":
        query.query = unescapeNewlines(value);
        break;
      case "Including":
        query.filesToInclude = value;
        break;
      case "Excluding":
        query.filesToExclude = value;
        break;
      case "ContextLines":
        query.contextLines = +value;
        break;
      case "Flags": {
        query.isRegexp = value.indexOf("RegExp") !== -1;
        query.isCaseSensitive = value.indexOf("CaseSensitive") !== -1;
        query.useExcludeSettingsAndIgnoreFiles = value.indexOf("IgnoreExcludeSettings") === -1;
        query.matchWholeWord = value.indexOf("WordMatch") !== -1;
        query.onlyOpenEditors = value.indexOf("OpenEditors") !== -1;
      }
    }
  }
  query.showIncludesExcludes = !!(query.filesToInclude || query.filesToExclude || !query.useExcludeSettingsAndIgnoreFiles);
  return query;
};
var $V7b = (searchResult, rawIncludePattern, rawExcludePattern, contextLines, labelFormatter, sortOrder, limitHit) => {
  if (!searchResult.query) {
    throw Error("Internal Error: Expected query, got null");
  }
  const config = contentPatternToSearchConfiguration(searchResult.query, rawIncludePattern, rawExcludePattern, contextLines);
  const filecount = searchResult.fileCount() > 1 ? localize(9821, null, searchResult.fileCount()) : localize(9822, null);
  const resultcount = searchResult.count() > 1 ? localize(9823, null, searchResult.count()) : localize(9824, null);
  const info = [
    searchResult.count() ? `${resultcount} - ${filecount}` : localize(9825, null)
  ];
  if (limitHit) {
    info.push(localize(9826, null));
  }
  info.push("");
  const matchComparer = (a, b) => $Q6b(a, b, sortOrder);
  const allResults = flattenSearchResultSerializations(searchResult.folderMatches().sort(matchComparer).map((folderMatch) => folderMatch.allDownstreamFileMatches().sort(matchComparer).flatMap((fileMatch) => fileMatchToSearchResultFormat(fileMatch, labelFormatter))).flat());
  return {
    matchRanges: allResults.matchRanges.map(translateRangeLines(info.length)),
    text: info.concat(allResults.text).join(lineDelimiter),
    config
  };
};
var flattenSearchResultSerializations = (serializations) => {
  const text2 = [];
  const matchRanges = [];
  serializations.forEach((serialized) => {
    serialized.matchRanges.map(translateRangeLines(text2.length)).forEach((range) => matchRanges.push(range));
    serialized.text.forEach((line) => text2.push(line));
    text2.push("");
  });
  return { text: text2, matchRanges };
};
var $W7b = async (accessor, resource) => {
  const textFileService = accessor.get($cK);
  const text2 = (await textFileService.read(resource)).value;
  return $X7b(text2);
};
var $X7b = (text2) => {
  const headerlines = [];
  const bodylines = [];
  let inHeader = true;
  for (const line of text2.split(/\r?\n/g)) {
    if (inHeader) {
      headerlines.push(line);
      if (line === "") {
        inHeader = false;
      }
    } else {
      bodylines.push(line);
    }
  }
  return { config: $U7b(headerlines), text: bodylines.join("\n") };
};

// out-build/vs/workbench/contrib/searchEditor/browser/searchEditorModel.js
var $Y7b = class {
  constructor(config) {
    this.config = config;
    this.a = new $ze();
    this.onConfigDidUpdate = this.a.event;
  }
  updateConfig(config) {
    this.config = config;
    this.a.fire(config);
  }
};
var $Z7b = class {
  constructor(a) {
    this.a = a;
  }
  async resolve() {
    return $Kg($17b.models.get(this.a)).resolve();
  }
};
var SearchEditorModelFactory = class {
  constructor() {
    this.models = new $Ec();
  }
  initializeModelFromExistingModel(accessor, resource, config) {
    if (this.models.has(resource)) {
      throw Error("Unable to contruct model for resource that already exists");
    }
    const languageService = accessor.get($1E);
    const modelService = accessor.get($sG);
    const instantiationService = accessor.get($Pk);
    const workingCopyBackupService = accessor.get($yG);
    let ongoingResolve;
    this.models.set(resource, {
      resolve: () => {
        if (!ongoingResolve) {
          ongoingResolve = (async () => {
            const backup = await this.a(resource, languageService, modelService, workingCopyBackupService, instantiationService);
            if (backup) {
              return backup;
            }
            return Promise.resolve({
              resultsModel: modelService.getModel(resource) ?? modelService.createModel("", languageService.createById($QN), resource),
              configurationModel: new $Y7b(config)
            });
          })();
        }
        return ongoingResolve;
      }
    });
  }
  initializeModelFromRawData(accessor, resource, config, contents) {
    if (this.models.has(resource)) {
      throw Error("Unable to contruct model for resource that already exists");
    }
    const languageService = accessor.get($1E);
    const modelService = accessor.get($sG);
    const instantiationService = accessor.get($Pk);
    const workingCopyBackupService = accessor.get($yG);
    let ongoingResolve;
    this.models.set(resource, {
      resolve: () => {
        if (!ongoingResolve) {
          ongoingResolve = (async () => {
            const backup = await this.a(resource, languageService, modelService, workingCopyBackupService, instantiationService);
            if (backup) {
              return backup;
            }
            return Promise.resolve({
              resultsModel: modelService.createModel(contents ?? "", languageService.createById($QN), resource),
              configurationModel: new $Y7b(config)
            });
          })();
        }
        return ongoingResolve;
      }
    });
  }
  initializeModelFromExistingFile(accessor, resource, existingFile) {
    if (this.models.has(resource)) {
      throw Error("Unable to contruct model for resource that already exists");
    }
    const languageService = accessor.get($1E);
    const modelService = accessor.get($sG);
    const instantiationService = accessor.get($Pk);
    const workingCopyBackupService = accessor.get($yG);
    let ongoingResolve;
    this.models.set(resource, {
      resolve: async () => {
        if (!ongoingResolve) {
          ongoingResolve = (async () => {
            const backup = await this.a(resource, languageService, modelService, workingCopyBackupService, instantiationService);
            if (backup) {
              return backup;
            }
            const { text: text2, config } = await instantiationService.invokeFunction($W7b, existingFile);
            return {
              resultsModel: modelService.createModel(text2 ?? "", languageService.createById($QN), resource),
              configurationModel: new $Y7b(config)
            };
          })();
        }
        return ongoingResolve;
      }
    });
  }
  async a(resource, languageService, modelService, workingCopyBackupService, instantiationService) {
    const backup = await workingCopyBackupService.resolve({ resource, typeId: $26b });
    let model = modelService.getModel(resource);
    if (!model && backup) {
      const factory = await $NI(backup.value);
      model = modelService.createModel(factory, languageService.createById($QN), resource);
    }
    if (model) {
      const existingFile = model.getValue();
      const { text: text2, config } = $X7b(existingFile);
      modelService.destroyModel(resource);
      return {
        resultsModel: modelService.createModel(text2 ?? "", languageService.createById($QN), resource),
        configurationModel: new $Y7b(config)
      };
    } else {
      return void 0;
    }
  }
};
var $17b = new SearchEditorModelFactory();

// out-build/vs/workbench/contrib/searchEditor/browser/searchEditorInput.js
var $37b_1;
var $27b = ".code-search";
var SearchEditorIcon = $9r("search-editor-label-icon", $6l.search, localize(9816, null));
var $37b = class $37b2 extends $nG {
  static {
    $37b_1 = this;
  }
  static {
    this.ID = $86b;
  }
  get typeId() {
    return $37b_1.ID;
  }
  get editorId() {
    return this.typeId;
  }
  getIcon() {
    return SearchEditorIcon;
  }
  get capabilities() {
    let capabilities = 8;
    if (!this.backingUri) {
      capabilities |= 4;
    }
    return capabilities;
  }
  get resource() {
    return this.backingUri || this.modelUri;
  }
  constructor(modelUri, backingUri, u, w, y, z, C, D, F, storageService) {
    super();
    this.modelUri = modelUri;
    this.backingUri = backingUri;
    this.u = u;
    this.w = w;
    this.y = y;
    this.z = z;
    this.C = C;
    this.D = D;
    this.F = F;
    this.b = false;
    this.h = this.B(new $ze());
    this.onDidChangeContent = this.h.event;
    this.m = this.B(new $ze());
    this.onDidSave = this.m.event;
    this.r = [];
    this.model = z.createInstance($Z7b, modelUri);
    if (this.modelUri.scheme !== $16b) {
      throw Error("SearchEditorInput must be invoked with a SearchEditorScheme uri");
    }
    this.a = new $Slb($37b_1.ID, storageService);
    this.B(storageService.onWillSaveState(() => this.a.saveMemento()));
    const input = this;
    const workingCopyAdapter = new class {
      constructor() {
        this.typeId = $26b;
        this.resource = input.modelUri;
        this.capabilities = input.hasCapability(
          4
          /* EditorInputCapabilities.Untitled */
        ) ? 2 : 0;
        this.onDidChangeDirty = input.onDidChangeDirty;
        this.onDidChangeContent = input.onDidChangeContent;
        this.onDidSave = input.onDidSave;
      }
      get name() {
        return input.getName();
      }
      isDirty() {
        return input.isDirty();
      }
      isModified() {
        return input.isDirty();
      }
      backup(token) {
        return input.J(token);
      }
      save(options3) {
        return input.save(0, options3).then((editor) => !!editor);
      }
      revert(options3) {
        return input.revert(0, options3);
      }
    }();
    this.B(this.C.registerWorkingCopy(workingCopyAdapter));
  }
  async save(group2, options3) {
    if ((await this.resolveModels()).resultsModel.isDisposed()) {
      return;
    }
    if (this.backingUri) {
      await this.w.write(this.backingUri, await this.G(), options3);
      this.setDirty(false);
      this.m.fire({ reason: options3?.reason, source: options3?.source });
      return this;
    } else {
      return this.saveAs(group2, options3);
    }
  }
  tryReadConfigSync() {
    return this.t?.config;
  }
  async G() {
    const { configurationModel, resultsModel } = await this.resolveModels();
    return $R7b(configurationModel.config) + "\n" + resultsModel.getValue();
  }
  I(model) {
    this.H?.dispose();
    if (!this.isDisposed()) {
      this.H = model.onConfigDidUpdate(() => {
        if (this.c !== this.getName()) {
          this.g.fire();
          this.c = this.getName();
        }
        this.a.getMemento(
          1,
          1
          /* StorageTarget.MACHINE */
        ).searchConfig = model.config;
      });
      this.B(this.H);
    }
  }
  async resolveModels() {
    return this.model.resolve().then((data) => {
      this.s = data.resultsModel;
      this.t = data.configurationModel;
      if (this.c !== this.getName()) {
        this.g.fire();
        this.c = this.getName();
      }
      this.I(data.configurationModel);
      return data;
    });
  }
  async saveAs(group2, options3) {
    const path = await this.y.pickFileToSave(await this.L(), options3?.availableFileSystems);
    if (path) {
      this.D.publicLog2("searchEditor/saveSearchResults");
      const toWrite = await this.G();
      if (await this.w.create([{ resource: path, value: toWrite, options: { overwrite: true } }])) {
        this.setDirty(false);
        if (!$oh(path, this.modelUri)) {
          const input = this.z.invokeFunction($47b, { fileUri: path, from: "existingFile" });
          input.setMatchRanges(this.getMatchRanges());
          return input;
        }
        return this;
      }
    }
    return void 0;
  }
  getName(maxLength = 12) {
    const trimToMax = (label3) => label3.length < maxLength ? label3 : `${label3.slice(0, maxLength - 3)}...`;
    if (this.backingUri) {
      const originalURI = $mL.getOriginalUri(this);
      return localize(9817, null, $rc((originalURI ?? this.backingUri).path, $27b));
    }
    const query = this.t?.config?.query?.trim();
    if (query) {
      return localize(9818, null, trimToMax(query));
    }
    return localize(9819, null);
  }
  setDirty(dirty) {
    const wasDirty = this.b;
    this.b = dirty;
    if (wasDirty !== dirty) {
      this.f.fire();
    }
  }
  isDirty() {
    return this.b;
  }
  async rename(group2, target) {
    if ($th(target) === $27b) {
      return {
        editor: this.z.invokeFunction($47b, { from: "existingFile", fileUri: target })
      };
    }
    return void 0;
  }
  dispose() {
    this.u.destroyModel(this.modelUri);
    super.dispose();
  }
  matches(other) {
    if (super.matches(other)) {
      return true;
    }
    if (other instanceof $37b_1) {
      return !!(other.modelUri.fragment && other.modelUri.fragment === this.modelUri.fragment) || !!(other.backingUri && $oh(other.backingUri, this.backingUri));
    }
    return false;
  }
  getMatchRanges() {
    return (this.s?.getAllDecorations() ?? []).filter((decoration3) => decoration3.options.className === $36b).filter(({ range }) => !(range.startColumn === 1 && range.endColumn === 1)).map(({ range }) => range);
  }
  async setMatchRanges(ranges) {
    this.r = (await this.resolveModels()).resultsModel.deltaDecorations(this.r, ranges.map((range) => ({ range, options: {
      description: "search-editor-find-match",
      className: $36b,
      stickiness: 1
      /* TrackedRangeStickiness.NeverGrowsWhenTypingAtEdges */
    } })));
  }
  async revert(group2, options3) {
    if (options3?.soft) {
      this.setDirty(false);
      return;
    }
    if (this.backingUri) {
      const { config, text: text2 } = await this.z.invokeFunction($W7b, this.backingUri);
      const { resultsModel, configurationModel } = await this.resolveModels();
      resultsModel.setValue(text2);
      configurationModel.updateConfig(config);
    } else {
      (await this.resolveModels()).resultsModel.setValue("");
    }
    super.revert(group2, options3);
    this.setDirty(false);
  }
  async J(token) {
    const contents = await this.G();
    if (token.isCancellationRequested) {
      return {};
    }
    return {
      content: $Ni($Ci.fromString(contents))
    };
  }
  async L() {
    const query = (await this.resolveModels()).configurationModel.config.query;
    const searchFileName = (query.replace(/[^\w \-_]+/g, "_") || "Search") + $27b;
    return $vh(await this.y.defaultFilePath(this.F.defaultUriScheme), searchFileName);
  }
  toUntyped() {
    if (this.hasCapability(
      4
      /* EditorInputCapabilities.Untitled */
    )) {
      return void 0;
    }
    return {
      resource: this.resource,
      options: {
        override: $37b_1.ID
      }
    };
  }
};
$37b = $37b_1 = __decorate([
  __param(2, $sG),
  __param(3, $cK),
  __param(4, $1v),
  __param(5, $Pk),
  __param(6, $XI),
  __param(7, $zv),
  __param(8, $aT),
  __param(9, $jv)
], $37b);
var $47b = (accessor, existingData) => {
  const storageService = accessor.get($jv);
  const configurationService = accessor.get($kl);
  const instantiationService = accessor.get($Pk);
  const modelUri = existingData.from === "model" ? existingData.modelUri : URI.from({ scheme: $16b, fragment: `${Math.random()}` });
  if (!$17b.models.has(modelUri)) {
    if (existingData.from === "existingFile") {
      instantiationService.invokeFunction((accessor2) => $17b.initializeModelFromExistingFile(accessor2, modelUri, existingData.fileUri));
    } else {
      const searchEditorSettings = configurationService.getValue("search").searchEditor;
      const reuseOldSettings = searchEditorSettings.reusePriorSearchConfiguration;
      const defaultNumberOfContextLines = searchEditorSettings.defaultNumberOfContextLines;
      const priorConfig = reuseOldSettings ? new $Slb($37b.ID, storageService).getMemento(
        1,
        1
        /* StorageTarget.MACHINE */
      ).searchConfig : {};
      const defaultConfig2 = $T7b();
      const config = { ...defaultConfig2, ...priorConfig, ...existingData.config };
      if (defaultNumberOfContextLines !== null && defaultNumberOfContextLines !== void 0) {
        config.contextLines = existingData?.config?.contextLines ?? defaultNumberOfContextLines;
      }
      if (existingData.from === "rawData") {
        if (existingData.resultsContents) {
          config.contextLines = 0;
        }
        instantiationService.invokeFunction((accessor2) => $17b.initializeModelFromRawData(accessor2, modelUri, config, existingData.resultsContents));
      } else {
        instantiationService.invokeFunction((accessor2) => $17b.initializeModelFromExistingModel(accessor2, modelUri, config));
      }
    }
  }
  return instantiationService.createInstance($37b, modelUri, existingData.from === "existingFile" ? existingData.fileUri : existingData.from === "model" ? existingData.backupOf : void 0);
};

// out-build/vs/workbench/contrib/searchEditor/browser/searchEditorActions.js
var $77b = (accessor) => {
  const editorService = accessor.get($mJ);
  const input = editorService.activeEditor;
  if (input instanceof $37b) {
    editorService.activeEditorPane.toggleCaseSensitive();
  }
};
var $87b = (accessor) => {
  const editorService = accessor.get($mJ);
  const input = editorService.activeEditor;
  if (input instanceof $37b) {
    editorService.activeEditorPane.toggleWholeWords();
  }
};
var $97b = (accessor) => {
  const editorService = accessor.get($mJ);
  const input = editorService.activeEditor;
  if (input instanceof $37b) {
    editorService.activeEditorPane.toggleRegex();
  }
};
var $07b = (accessor) => {
  const editorService = accessor.get($mJ);
  const input = editorService.activeEditor;
  if (input instanceof $37b) {
    editorService.activeEditorPane.toggleContextLines();
  }
};
var $$7b = (accessor, increase) => {
  const editorService = accessor.get($mJ);
  const input = editorService.activeEditor;
  if (input instanceof $37b) {
    editorService.activeEditorPane.modifyContextLines(increase);
  }
};
var $_7b = (accessor) => {
  const editorService = accessor.get($mJ);
  const input = editorService.activeEditor;
  if (input instanceof $37b) {
    editorService.activeEditorPane.focusAllResults();
  }
};
async function $a8b(accessor) {
  const viewsService = accessor.get($uob);
  const instantiationService = accessor.get($Pk);
  const searchView = $V6b(viewsService);
  if (searchView) {
    await instantiationService.invokeFunction($b8b, {
      filesToInclude: searchView.searchIncludePattern.getValue(),
      onlyOpenEditors: searchView.searchIncludePattern.onlySearchInOpenEditors(),
      filesToExclude: searchView.searchExcludePattern.getValue(),
      isRegexp: searchView.searchAndReplaceWidget.searchInput?.getRegex(),
      isCaseSensitive: searchView.searchAndReplaceWidget.searchInput?.getCaseSensitive(),
      matchWholeWord: searchView.searchAndReplaceWidget.searchInput?.getWholeWords(),
      useExcludeSettingsAndIgnoreFiles: searchView.searchExcludePattern.useExcludesAndIgnoreFiles(),
      showIncludesExcludes: !!(searchView.searchIncludePattern.getValue() || searchView.searchExcludePattern.getValue() || !searchView.searchExcludePattern.useExcludesAndIgnoreFiles())
    });
  } else {
    await instantiationService.invokeFunction($b8b);
  }
}
var $b8b = async (accessor, _args = {}, toSide = false) => {
  const editorService = accessor.get($mJ);
  const editorGroupsService = accessor.get($iJ);
  const telemetryService = accessor.get($zv);
  const instantiationService = accessor.get($Pk);
  const configurationService = accessor.get($kl);
  const configurationResolverService = accessor.get($nY);
  const workspaceContextService = accessor.get($Zk);
  const historyService = accessor.get($tY);
  const activeWorkspaceRootUri = historyService.getLastActiveWorkspaceRoot(Schemas.file);
  const lastActiveWorkspaceRoot = activeWorkspaceRootUri ? workspaceContextService.getWorkspaceFolder(activeWorkspaceRootUri) ?? void 0 : void 0;
  const activeEditorControl = editorService.activeTextEditorControl;
  let activeModel;
  let selected = "";
  if (activeEditorControl) {
    if ($Q5(activeEditorControl)) {
      if (activeEditorControl.getOriginalEditor().hasTextFocus()) {
        activeModel = activeEditorControl.getOriginalEditor();
      } else {
        activeModel = activeEditorControl.getModifiedEditor();
      }
    } else {
      activeModel = activeEditorControl;
    }
    const selection = activeModel?.getSelection();
    selected = (selection && activeModel?.getModel()?.getValueInRange(selection)) ?? "";
    if (selection?.isEmpty() && configurationService.getValue("search").seedWithNearestWord) {
      const wordAtPosition = activeModel.getModel()?.getWordAtPosition(selection.getStartPosition());
      if (wordAtPosition) {
        selected = wordAtPosition.word;
      }
    }
  } else {
    if (editorService.activeEditor instanceof $37b) {
      const active = editorService.activeEditorPane;
      selected = active.getSelected();
    }
  }
  telemetryService.publicLog2("searchEditor/openNewSearchEditor");
  const seedSearchStringFromSelection = _args.location === "new" || configurationService.getValue("editor").find.seedSearchStringFromSelection;
  const args2 = { query: seedSearchStringFromSelection ? selected : void 0 };
  for (const entry of Object.entries(_args)) {
    const name = entry[0];
    const value = entry[1];
    if (value !== void 0) {
      args2[name] = typeof value === "string" ? await configurationResolverService.resolveAsync(lastActiveWorkspaceRoot, value) : value;
    }
  }
  const existing = editorService.getEditors(
    0
    /* EditorsOrder.MOST_RECENTLY_ACTIVE */
  ).find((id2) => id2.editor.typeId === $37b.ID);
  let editor;
  if (existing && args2.location === "reuse") {
    const group2 = editorGroupsService.getGroup(existing.groupId);
    if (!group2) {
      throw new Error("Invalid group id for search editor");
    }
    const input = existing.editor;
    editor = await group2.openEditor(input);
    if (selected) {
      editor.setQuery(selected);
    } else {
      editor.selectQuery();
    }
    editor.setSearchConfig(args2);
  } else {
    const input = instantiationService.invokeFunction($47b, { config: args2, resultsContents: "", from: "rawData" });
    editor = await editorService.openEditor(input, { pinned: true }, toSide ? $oJ : $nJ);
  }
  const searchOnType = configurationService.getValue("search").searchOnType;
  if (args2.triggerSearch === true || args2.triggerSearch !== false && searchOnType && args2.query) {
    editor.triggerSearch({ focusResults: args2.focusResults });
  }
  if (!args2.focusResults) {
    editor.focusSearchInput();
  }
};
var $c8b = async (accessor, searchResult, rawIncludePattern, rawExcludePattern, onlySearchInOpenEditors) => {
  if (!searchResult.query) {
    console.error("Expected searchResult.query to be defined. Got", searchResult);
    return;
  }
  const editorService = accessor.get($mJ);
  const telemetryService = accessor.get($zv);
  const instantiationService = accessor.get($Pk);
  const labelService = accessor.get($ZI);
  const configurationService = accessor.get($kl);
  const sortOrder = configurationService.getValue("search").sortOrder;
  telemetryService.publicLog2("searchEditor/createEditorFromSearchResult");
  const labelFormatter = (uri) => labelService.getUriLabel(uri, { relative: true });
  const { text: text2, matchRanges, config } = $V7b(searchResult, rawIncludePattern, rawExcludePattern, 0, labelFormatter, sortOrder);
  config.onlyOpenEditors = onlySearchInOpenEditors;
  const contextLines = configurationService.getValue("search").searchEditor.defaultNumberOfContextLines;
  if (searchResult.isDirty || contextLines === 0 || contextLines === null) {
    const input = instantiationService.invokeFunction($47b, { resultsContents: text2, config, from: "rawData" });
    await editorService.openEditor(input, { pinned: true });
    input.setMatchRanges(matchRanges);
  } else {
    const input = instantiationService.invokeFunction($47b, { from: "rawData", resultsContents: "", config: { ...config, contextLines } });
    const editor = await editorService.openEditor(input, { pinned: true });
    editor.triggerSearch();
  }
};

// out-build/vs/workbench/contrib/search/browser/searchView.js
var $p8b_1;
var $138 = $;
var SearchViewPosition;
(function(SearchViewPosition2) {
  SearchViewPosition2[SearchViewPosition2["SideBar"] = 0] = "SideBar";
  SearchViewPosition2[SearchViewPosition2["Panel"] = 1] = "Panel";
})(SearchViewPosition || (SearchViewPosition = {}));
var SEARCH_CANCELLED_MESSAGE = localize(9721, null);
var DEBOUNCE_DELAY = 75;
var $p8b = class $p8b2 extends $_ob {
  static {
    $p8b_1 = this;
  }
  static {
    this.c = "actions-right";
  }
  constructor(options3, Sc, Tc, Uc, Vc, Wc, Xc, Yc, Zc, instantiationService, viewDescriptorService, configurationService, $c4, ad, contextKeyService, bd, cd, dd, themeService, ed, contextMenuService, fd, keybindingService, gd, openerService, telemetryService, hoverService, hd, jd, kd) {
    super(options3, keybindingService, contextMenuService, configurationService, contextKeyService, viewDescriptorService, instantiationService, openerService, themeService, telemetryService, hoverService);
    this.Sc = Sc;
    this.Tc = Tc;
    this.Uc = Uc;
    this.Vc = Vc;
    this.Wc = Wc;
    this.Xc = Xc;
    this.Yc = Yc;
    this.Zc = Zc;
    this.$c = $c4;
    this.ad = ad;
    this.bd = bd;
    this.cd = cd;
    this.dd = dd;
    this.ed = ed;
    this.fd = fd;
    this.gd = gd;
    this.hd = hd;
    this.jd = jd;
    this.kd = kd;
    this.g = false;
    this.jc = "input";
    this.tc = new $2c();
    this.Gc = Promise.resolve();
    this.Kc = false;
    this.Nc = 0;
    this.h = $(".search-view");
    this.s = $eRb.SearchViewVisibleKey.bindTo(this.Bb);
    this.sb = $eRb.FirstMatchFocusKey.bindTo(this.Bb);
    this.ac = $eRb.FileMatchOrMatchFocusKey.bindTo(this.Bb);
    this.bc = $eRb.FileMatchOrFolderMatchFocusKey.bindTo(this.Bb);
    this.cc = $eRb.FileMatchOrFolderMatchWithResourceFocusKey.bindTo(this.Bb);
    this.dc = $eRb.FileFocusKey.bindTo(this.Bb);
    this.ec = $eRb.FolderFocusKey.bindTo(this.Bb);
    this.fc = $eRb.ResourceFolderFocusKey.bindTo(this.Bb);
    this.ic = $eRb.HasSearchResults.bindTo(this.Bb);
    this.gc = $eRb.MatchFocusKey.bindTo(this.Bb);
    this.kc = $jO.bindTo(this.Bb);
    this.lc = $eRb.ViewHasSearchPatternKey.bindTo(this.Bb);
    this.mc = $eRb.ViewHasReplacePatternKey.bindTo(this.Bb);
    this.nc = $eRb.ViewHasFilePatternKey.bindTo(this.Bb);
    this.oc = $eRb.ViewHasSomeCollapsibleKey.bindTo(this.Bb);
    this.Mc = $eRb.InTreeViewKey.bindTo(this.Bb);
    this.Rc = this.B(this.Db.createInstance(RefreshTreeController, this, () => this.qe));
    this.B(this.Bb.onDidChangeContext((e) => {
      const keys = $eRb.hasAIResultProvider.keys();
      if (e.affectsSome(new Set(keys))) {
        this.nd();
      }
    }));
    this.Bb = this.B(this.Bb.createScoped(this.h));
    $eRb.SearchViewFocusedKey.bindTo(this.Bb).set(true);
    this.t = $eRb.InputBoxFocusedKey.bindTo(this.Bb);
    this.L = $eRb.PatternIncludesFocusedKey.bindTo(this.Bb);
    this.ab = $eRb.PatternExcludesFocusedKey.bindTo(this.Bb);
    this.hc = $eRb.IsEditableItemKey.bindTo(this.Bb);
    this.Db = this.B(this.Db.createChild(new $Ok([$on, this.Bb])));
    this.B(this.Ab.onDidChangeConfiguration(async (e) => {
      if (e.affectsConfiguration("search.sortOrder")) {
        if (this.qe.sortOrder === "modified") {
          this.ue();
        }
        await this.Rc.queue();
      }
    }));
    this.n = this.ad.searchModel;
    this.j = this.Db.createInstance($eT);
    this.r = new $Slb(this.id, gd);
    this.rc = this.r.getMemento(
      1,
      1
      /* StorageTarget.MACHINE */
    );
    this.B(this.Sc.onDidFilesChange((e) => this.pe(e)));
    this.B(this.cd.untitled.onWillDispose((model) => this.oe(model.resource)));
    this.B(this.$c.onDidChangeWorkbenchState(() => this.od()));
    this.B(this.ed.onDidClearHistory(() => this.re()));
    this.B(this.Ab.onDidChangeConfiguration((e) => this.ud(e)));
    this.Dc = this.B(new $Sh(250));
    this.Hc = this.B(new $Sh(2e3));
    this.Ic = this.B(new $Sh(100));
    this.Jc = this.B(new $Sh(0));
    this.Lc = this.Db.createInstance($o8b, this);
    this.ld = this.rc["view.treeLayout"] ?? this.qe.defaultViewMode === "tree";
    this.Oc = this.B(new $8h(this.Xd.bind(this), 80));
    this.B(this.gd.onWillSaveState(() => {
      this.se();
    }));
    this.B(this.gd.onDidChangeValue(1, $e8b.SEARCH_HISTORY_KEY, this.q)(() => {
      const restoredHistory = this.ed.load();
      if (restoredHistory.include) {
        this.Ac.prependHistory(restoredHistory.include);
      }
      if (restoredHistory.exclude) {
        this.zc.prependHistory(restoredHistory.exclude);
      }
      if (restoredHistory.search) {
        this.vc.prependSearchHistory(restoredHistory.search);
      }
      if (restoredHistory.replace) {
        this.vc.prependReplaceHistory(restoredHistory.replace);
      }
    }));
    this.Ec = this.hasSearchResults();
  }
  async queueRefreshTree() {
    return this.Rc.queue();
  }
  get ld() {
    return this.Mc.get() ?? false;
  }
  set ld(visible) {
    this.Mc.set(visible);
  }
  async setTreeView(visible) {
    if (visible === this.ld) {
      return;
    }
    this.ld = visible;
    this.rd(this.Fb.getFileIconTheme());
    return this.Rc.queue();
  }
  get md() {
    return this.kc.get() ?? SearchUIState.Idle;
  }
  set md(v) {
    this.kc.set(v);
  }
  getContainer() {
    return this.h;
  }
  get searchResult() {
    return this.n && this.n.searchResult;
  }
  get model() {
    return this.n;
  }
  async nd() {
    const shouldShowAI = this.shouldShowAIResults();
    if (!this.pc.hasNode(this.searchResult)) {
      return;
    }
    if (shouldShowAI && !this.pc.hasNode(this.searchResult.aiTextSearchResult)) {
      if (this.model.searchResult.getCachedSearchComplete(false)) {
        return this.xd();
      }
    } else if (!shouldShowAI && this.pc.hasNode(this.searchResult.aiTextSearchResult)) {
      return this.xd();
    }
  }
  od() {
    if (this.$c.getWorkbenchState() !== 1 && this.Fc) {
      $ik(this.Fc);
    }
  }
  pd() {
    this.Kc = true;
    this.vc.setValue(this.n.searchResult.query?.contentPattern.pattern ?? "");
    this.vc.setReplaceAllActionState(false);
    this.vc.toggleReplace(true);
    this.Ac.setOnlySearchInOpenEditors(this.n.searchResult.query?.onlyOpenEditors || false);
    this.zc.setUseExcludesAndIgnoreFiles(!this.n.searchResult.query?.userDisabledExcludesAndIgnoreFiles || true);
    this.searchIncludePattern.setValue("");
    this.searchExcludePattern.setValue("");
    this.Kc = false;
  }
  async replaceSearchModel(searchModel, asyncResults) {
    let progressComplete;
    this.Vc.withProgress({ location: this.Wb(), delay: 0 }, (_progress) => {
      return new Promise((resolve) => progressComplete = resolve);
    });
    const slowTimer = setTimeout(() => {
      this.md = SearchUIState.SlowSearch;
    }, 2e3);
    this.Oc.schedule();
    searchModel.location = SearchModelLocation.PANEL;
    searchModel.replaceActive = this.n.isReplaceActive();
    searchModel.replaceString = this.vc.getReplaceValue();
    this.Pc?.dispose();
    this.Pc = this.B(searchModel.onSearchResultChanged(async (event) => this.wd(event)));
    this.ad.searchModel = searchModel;
    this.n = searchModel;
    this.pc.setInput(this.n.searchResult);
    await this.wd();
    this.pd();
    asyncResults.then((complete) => {
      clearTimeout(slowTimer);
      return this.Zd(progressComplete, void 0, void 0, complete);
    }, (e) => {
      clearTimeout(slowTimer);
      return this.$d(e, progressComplete, void 0, void 0);
    });
    await this.Yd();
  }
  W(parent) {
    super.W(parent);
    this.h = $bk(parent, $(".search-view"));
    this.uc = $bk(this.h, $138(".search-widgets-container"));
    this.td(this.uc);
    const history = this.ed.load();
    const filePatterns = this.rc["query.filePatterns"] || "";
    const patternExclusions = this.rc["query.folderExclusions"] || "";
    const patternExclusionsHistory = history.exclude || [];
    const patternIncludes = this.rc["query.folderIncludes"] || "";
    const patternIncludesHistory = history.include || [];
    const onlyOpenEditors = this.rc["query.onlyOpenEditors"] || false;
    const queryDetailsExpanded = this.rc["query.queryDetailsExpanded"] || "";
    const useExcludesAndIgnoreFiles = typeof this.rc["query.useExcludesAndIgnoreFiles"] === "boolean" ? this.rc["query.useExcludesAndIgnoreFiles"] : true;
    this.xc = $bk(this.uc, $138(".query-details"));
    const toggleQueryDetailsLabel = localize(9722, null);
    this.yc = $bk(this.xc, $138(".more" + ThemeIcon.asCSSSelector($96b), { tabindex: 0, role: "button", "aria-label": toggleQueryDetailsLabel }));
    this.B(this.Hb.setupManagedHover($JZ("element"), this.yc, toggleQueryDetailsLabel));
    this.B($_i(this.yc, $7j.CLICK, (e) => {
      $9j.stop(e);
      this.toggleQueryDetails(!this.fd.isScreenReaderOptimized());
    }));
    this.B($_i(this.yc, $7j.KEY_UP, (e) => {
      const event = new $if(e);
      if (event.equals(
        3
        /* KeyCode.Enter */
      ) || event.equals(
        10
        /* KeyCode.Space */
      )) {
        $9j.stop(e);
        this.toggleQueryDetails(false);
      }
    }));
    this.B($_i(this.yc, $7j.KEY_DOWN, (e) => {
      const event = new $if(e);
      if (event.equals(
        1024 | 2
        /* KeyCode.Tab */
      )) {
        if (this.vc.isReplaceActive()) {
          this.vc.focusReplaceAllAction();
        } else {
          this.vc.isReplaceShown() ? this.vc.replaceInput?.focusOnPreserve() : this.vc.focusRegexAction();
        }
        $9j.stop(e);
      }
    }));
    const folderIncludesList = $bk(this.xc, $138(".file-types.includes"));
    const filesToIncludeTitle = localize(9723, null);
    $bk(folderIncludesList, $138("h4", void 0, filesToIncludeTitle));
    this.Ac = this.B(this.Db.createInstance($G6b, folderIncludesList, this.Zc, {
      ariaLabel: filesToIncludeTitle,
      placeholder: localize(9724, null),
      showPlaceholderOnFocus: true,
      history: patternIncludesHistory,
      inputBoxStyles: $B$
    }));
    this.Ac.setValue(patternIncludes);
    this.Ac.setOnlySearchInOpenEditors(onlyOpenEditors);
    this.B(this.Ac.onCancel(() => this.cancelSearch(false)));
    this.B(this.Ac.onChangeSearchInEditorsBox(() => this.triggerQueryChange()));
    this.vd(this.Ac.inputFocusTracker, this.L);
    const excludesList = $bk(this.xc, $138(".file-types.excludes"));
    const excludesTitle = localize(9725, null);
    $bk(excludesList, $138("h4", void 0, excludesTitle));
    this.zc = this.B(this.Db.createInstance($H6b, excludesList, this.Zc, {
      ariaLabel: excludesTitle,
      placeholder: localize(9726, null),
      showPlaceholderOnFocus: true,
      history: patternExclusionsHistory,
      inputBoxStyles: $B$
    }));
    this.zc.setValue(patternExclusions);
    this.zc.setUseExcludesAndIgnoreFiles(useExcludesAndIgnoreFiles);
    this.B(this.zc.onCancel(() => this.cancelSearch(false)));
    this.B(this.zc.onChangeIgnoreBox(() => this.triggerQueryChange()));
    this.vd(this.zc.inputFocusTracker, this.ab);
    const updateHasFilePatternKey = () => this.nc.set(this.Ac.getValue().length > 0 || this.zc.getValue().length > 0);
    updateHasFilePatternKey();
    const onFilePatternSubmit = (triggeredOnType) => {
      this.triggerQueryChange({ triggeredOnType, delay: this.qe.searchOnTypeDebouncePeriod });
      if (triggeredOnType) {
        updateHasFilePatternKey();
      }
    };
    this.B(this.Ac.onSubmit(onFilePatternSubmit));
    this.B(this.zc.onSubmit(onFilePatternSubmit));
    this.sc = $bk(this.h, $138(".messages.text-search-provider-messages"));
    if (this.$c.getWorkbenchState() === 1) {
      this.ke();
    }
    this.Ed(this.h);
    if (filePatterns !== "" || patternExclusions !== "" || patternIncludes !== "" || queryDetailsExpanded !== "" || !useExcludesAndIgnoreFiles) {
      this.toggleQueryDetails(true, true, true);
    }
    this.Pc = this.B(this.n.onSearchResultChanged(async (event) => await this.wd(event)));
    this.B(this.onDidChangeBodyVisibility((visible) => this.sd(visible)));
    this.rd(this.Fb.getFileIconTheme());
    this.B(this.Fb.onDidFileIconThemeChange(this.rd, this));
  }
  rd(theme) {
    this.Bc.classList.toggle("hide-arrows", this.ld && theme.hidesExplorerArrows);
  }
  async sd(visible) {
    this.s.set(visible);
    if (visible) {
      if (this.Ec) {
        await this.xd();
        this.Ec = false;
      }
    } else {
      this.jc = "input";
    }
    this.n?.searchResult.toggleHighlights(visible);
  }
  get searchAndReplaceWidget() {
    return this.vc;
  }
  get searchIncludePattern() {
    return this.Ac;
  }
  get searchExcludePattern() {
    return this.zc;
  }
  td(container2) {
    const contentPattern = this.rc["query.contentPattern"] || "";
    const replaceText = this.rc["query.replaceText"] || "";
    const isRegex = this.rc["query.regex"] === true;
    const isWholeWords = this.rc["query.wholeWords"] === true;
    const isCaseSensitive = this.rc["query.caseSensitive"] === true;
    const history = this.ed.load();
    const searchHistory = history.search || this.rc["query.searchHistory"] || [];
    const replaceHistory = history.replace || this.rc["query.replaceHistory"] || [];
    const showReplace = typeof this.rc["view.showReplace"] === "boolean" ? this.rc["view.showReplace"] : true;
    const preserveCase = this.rc["query.preserveCase"] === true;
    const isInNotebookMarkdownInput = this.rc["query.isInNotebookMarkdownInput"] ?? true;
    const isInNotebookMarkdownPreview = this.rc["query.isInNotebookMarkdownPreview"] ?? true;
    const isInNotebookCellInput = this.rc["query.isInNotebookCellInput"] ?? true;
    const isInNotebookCellOutput = this.rc["query.isInNotebookCellOutput"] ?? true;
    this.vc = this.B(this.Db.createInstance($r7b, container2, {
      value: contentPattern,
      replaceValue: replaceText,
      isRegex,
      isCaseSensitive,
      isWholeWords,
      searchHistory,
      replaceHistory,
      preserveCase,
      inputBoxStyles: $B$,
      toggleStyles: $u$,
      notebookOptions: {
        isInNotebookMarkdownInput,
        isInNotebookMarkdownPreview,
        isInNotebookCellInput,
        isInNotebookCellOutput
      }
    }));
    if (!this.vc.searchInput || !this.vc.replaceInput) {
      this.jd.warn(`Cannot fully create search widget. Search or replace input undefined. SearchInput: ${this.vc.searchInput}, ReplaceInput: ${this.vc.replaceInput}`);
      return;
    }
    if (showReplace) {
      this.vc.toggleReplace(true);
    }
    this.B(this.vc.onSearchSubmit((options3) => this.triggerQueryChange(options3)));
    this.B(this.vc.onSearchCancel(({ focus }) => this.cancelSearch(focus)));
    this.B(this.vc.searchInput.onDidOptionChange(() => {
      this.triggerQueryChange({ shouldKeepAIResults: true });
    }));
    this.B(this.vc.getNotebookFilters().onDidChange(() => this.triggerQueryChange({ shouldKeepAIResults: true })));
    const updateHasPatternKey = () => this.lc.set(this.vc.searchInput ? this.vc.searchInput.getValue().length > 0 : false);
    updateHasPatternKey();
    this.B(this.vc.searchInput.onDidChange(() => updateHasPatternKey()));
    const updateHasReplacePatternKey = () => this.mc.set(this.vc.getReplaceValue().length > 0);
    updateHasReplacePatternKey();
    this.B(this.vc.replaceInput.inputBox.onDidChange(() => updateHasReplacePatternKey()));
    this.B(this.vc.onDidHeightChange(() => this.Md()));
    this.B(this.vc.onReplaceToggled(() => this.Md()));
    this.B(this.vc.onReplaceStateChange(async (state) => {
      this.n.replaceActive = state;
      await this.Rc.queue();
    }));
    this.B(this.vc.onPreserveCaseChange(async (state) => {
      this.n.preserveCase = state;
      await this.Rc.queue();
    }));
    this.B(this.vc.onReplaceValueChanged(() => {
      this.n.replaceString = this.vc.getReplaceValue();
      this.Dc.trigger(async () => this.Rc.queue());
    }));
    this.B(this.vc.onBlur(() => {
      this.yc.focus();
    }));
    this.B(this.vc.onReplaceAll(() => this.Ad()));
    this.vd(this.vc.searchInputFocusTracker);
    this.vd(this.vc.replaceInputFocusTracker);
  }
  shouldShowAIResults() {
    const hasProvider = $eRb.hasAIResultProvider.getValue(this.Bb);
    return !!hasProvider;
  }
  async ud(event) {
    if (event && (event.affectsConfiguration("search.decorations.colors") || event.affectsConfiguration("search.decorations.badges"))) {
      return this.Rc.queue();
    }
  }
  vd(inputFocusTracker, contextKey) {
    if (!inputFocusTracker) {
      return;
    }
    this.B(inputFocusTracker.onDidFocus(() => {
      this.jc = "input";
      this.t.set(true);
      contextKey?.set(true);
    }));
    this.B(inputFocusTracker.onDidBlur(() => {
      this.t.set(this.vc.searchInputHasFocus() || this.vc.replaceInputHasFocus() || this.Ac.inputHasFocus() || this.zc.inputHasFocus());
      contextKey?.set(false);
    }));
  }
  async wd(event) {
    if (this.isVisible()) {
      return this.xd(event);
    } else {
      this.Ec = true;
    }
  }
  async xd(event) {
    this.vc.setReplaceAllActionState(!this.n.searchResult.isEmpty());
    this.he(this.n.searchResult.query.userDisabledExcludesAndIgnoreFiles, this.n.searchResult.query?.onlyOpenEditors, event?.clearingAll);
    return this.Rc.queue(event);
  }
  yd(match) {
    const collapseResults = this.qe.collapseResults;
    return collapseResults === "alwaysCollapse" || !$D6b(match) && match.count() > 10 && collapseResults !== "alwaysExpand" ? ObjectTreeElementCollapseState.PreserveOrCollapsed : ObjectTreeElementCollapseState.PreserveOrExpanded;
  }
  zd(match) {
    const collapseResults = this.yd(match);
    if (collapseResults === ObjectTreeElementCollapseState.PreserveOrCollapsed) {
      return true;
    }
    return false;
  }
  Ad() {
    if (this.n.searchResult.count() === 0) {
      return;
    }
    const occurrences = this.n.searchResult.count();
    const fileCount = this.n.searchResult.fileCount();
    const replaceValue = this.vc.getReplaceValue() || "";
    const afterReplaceAllMessage = this.Bd(occurrences, fileCount, replaceValue);
    let progressComplete;
    let progressReporter;
    this.Vc.withProgress({ location: this.Wb(), delay: 100, total: occurrences }, (p) => {
      progressReporter = p;
      return new Promise((resolve) => progressComplete = resolve);
    });
    const confirmation = {
      title: localize(9727, null),
      message: this.Cd(occurrences, fileCount, replaceValue),
      primaryButton: localize(9728, null)
    };
    this.Xc.confirm(confirmation).then((res) => {
      if (res.confirmed) {
        this.vc.setReplaceAllActionState(false);
        this.n.searchResult.replaceAll(progressReporter).then(() => {
          progressComplete();
          const messageEl = this.Dd();
          $bk(messageEl, afterReplaceAllMessage);
          this.Md();
        }, (error) => {
          progressComplete();
          $kb(error);
          this.Wc.error(error);
        });
      } else {
        progressComplete();
      }
    });
  }
  Bd(occurrences, fileCount, replaceValue) {
    if (occurrences === 1) {
      if (fileCount === 1) {
        if (replaceValue) {
          return localize(9729, null, occurrences, fileCount, replaceValue);
        }
        return localize(9730, null, occurrences, fileCount);
      }
      if (replaceValue) {
        return localize(9731, null, occurrences, fileCount, replaceValue);
      }
      return localize(9732, null, occurrences, fileCount);
    }
    if (fileCount === 1) {
      if (replaceValue) {
        return localize(9733, null, occurrences, fileCount, replaceValue);
      }
      return localize(9734, null, occurrences, fileCount);
    }
    if (replaceValue) {
      return localize(9735, null, occurrences, fileCount, replaceValue);
    }
    return localize(9736, null, occurrences, fileCount);
  }
  Cd(occurrences, fileCount, replaceValue) {
    if (occurrences === 1) {
      if (fileCount === 1) {
        if (replaceValue) {
          return localize(9737, null, occurrences, fileCount, replaceValue);
        }
        return localize(9738, null, occurrences, fileCount);
      }
      if (replaceValue) {
        return localize(9739, null, occurrences, fileCount, replaceValue);
      }
      return localize(9740, null, occurrences, fileCount);
    }
    if (fileCount === 1) {
      if (replaceValue) {
        return localize(9741, null, occurrences, fileCount, replaceValue);
      }
      return localize(9742, null, occurrences, fileCount);
    }
    if (replaceValue) {
      return localize(9743, null, occurrences, fileCount, replaceValue);
    }
    return localize(9744, null, occurrences, fileCount);
  }
  Dd() {
    this.Fc = void 0;
    const wasHidden = this.sc.style.display === "none";
    $$i(this.sc);
    $hk(this.sc);
    this.tc.clear();
    const newMessage = $bk(this.sc, $138(".message"));
    if (wasHidden) {
      this.Md();
    }
    return newMessage;
  }
  Ed(container2) {
    this.Bc = $bk(container2, $138(".results.show-file-icons.file-icon-themable-tree"));
    const delegate = this.Db.createInstance($j8b);
    const identityProvider3 = {
      getId(element) {
        return element.id();
      }
    };
    this.Qc = this.Db.createInstance(SearchViewDataSource, this);
    this.qc = this.B(this.Db.createInstance($lsb, { onDidChangeVisibility: this.onDidChangeBodyVisibility }));
    this.pc = this.B(this.Db.createInstance($5eb, "SearchView", this.Bc, delegate, {
      isIncompressible: (element) => {
        if ($y6b(element) && !$w6b(element.parent()) && !$A6b(element.parent()) && !$B6b(element.parent())) {
          return false;
        }
        return true;
      }
    }, [
      this.B(this.Db.createInstance($l8b, this, this.qc)),
      this.B(this.Db.createInstance($m8b, this, this.qc)),
      this.B(this.Db.createInstance($k8b, this.qc)),
      this.B(this.Db.createInstance($n8b, this))
    ], this.Qc, {
      identityProvider: identityProvider3,
      accessibilityProvider: this.Lc,
      dnd: this.Db.createInstance($Kob, (element) => {
        if ($C6b(element)) {
          return element.resource;
        }
        if ($D6b(element)) {
          return $P4(element.parent().resource, element.range());
        }
        return null;
      }),
      multipleSelectionSupport: true,
      selectionNavigation: true,
      overrideStyles: this.Xb().listOverrideStyles,
      paddingBottom: $j8b.ITEM_HEIGHT,
      collapseByDefault: (e) => {
        if ($w6b(e)) {
          return e.isAIContributed;
        }
        if ($y6b(e) && e.matches().length === 1 && $y6b(e.matches()[0])) {
          return false;
        }
        return this.zd(e);
      }
    }));
    $eRb.SearchResultListFocusedKey.bindTo(this.pc.contextKeyService);
    this.pc.setInput(this.n.searchResult);
    this.B(this.pc.onContextMenu((e) => this.Fd(e)));
    const updateHasSomeCollapsible = () => this.Ic.trigger(() => this.oc.set(this.Gd()));
    updateHasSomeCollapsible();
    this.B(this.pc.onDidChangeCollapseState(() => updateHasSomeCollapsible()));
    this.B(this.pc.onDidChangeModel(() => updateHasSomeCollapsible()));
    this.B(Event2.debounce(this.pc.onDidOpen, (last, event) => event, DEBOUNCE_DELAY, true)((options3) => {
      if ($D6b(options3.element)) {
        const selectedMatch = options3.element;
        this.Cc?.setSelectedMatch(null);
        this.Cc = selectedMatch.parent();
        this.Cc.setSelectedMatch(selectedMatch);
        this.ne(selectedMatch, options3.editorOptions.preserveFocus, options3.sideBySide, options3.editorOptions.pinned);
      }
    }));
    this.B(Event2.debounce(this.pc.onDidChangeFocus, (last, event) => event, DEBOUNCE_DELAY, true)(() => {
      const selection = this.pc.getSelection();
      const focus = this.pc.getFocus()[0];
      if (selection.length > 1 && $D6b(focus)) {
        this.ne(focus, true);
      }
    }));
    this.B(Event2.any(this.pc.onDidFocus, this.pc.onDidChangeFocus)(() => {
      const focus = this.pc.getFocus()[0];
      if (this.pc.isDOMFocused()) {
        const firstElem = this.pc.getFirstElementChild(this.pc.getInput());
        this.sb.set(firstElem === focus);
        this.ac.set(!!focus);
        this.dc.set($C6b(focus));
        this.ec.set($y6b(focus));
        this.gc.set($D6b(focus));
        this.bc.set($C6b(focus) || $y6b(focus));
        this.cc.set($C6b(focus) || $z6b(focus));
        this.fc.set($z6b(focus));
        this.jc = "tree";
      }
      let editable = false;
      if ($D6b(focus)) {
        editable = !focus.isReadonly;
      } else if ($C6b(focus)) {
        editable = !focus.hasOnlyReadOnlyMatches();
      } else if ($y6b(focus)) {
        editable = !focus.hasOnlyReadOnlyMatches();
      }
      this.hc.set(editable);
    }));
    this.B(this.pc.onDidBlur(() => {
      this.sb.reset();
      this.ac.reset();
      this.dc.reset();
      this.ec.reset();
      this.gc.reset();
      this.bc.reset();
      this.cc.reset();
      this.fc.reset();
      this.hc.reset();
    }));
  }
  Fd(e) {
    e.browserEvent.preventDefault();
    e.browserEvent.stopPropagation();
    const selection = this.pc.getSelection();
    let arg;
    let context;
    if (selection && selection.length > 0) {
      arg = e.element;
      context = selection;
    } else {
      context = e.element;
    }
    this.zb.showContextMenu({
      menuId: $bJ.SearchContext,
      menuActionOptions: { shouldForwardArgs: true, arg },
      contextKeyService: this.Bb,
      getAnchor: () => e.anchor,
      getActionsContext: () => context
    });
  }
  Gd() {
    const viewer = this.getControl();
    const navigator2 = viewer.navigate();
    let node = navigator2.first();
    const shouldShowAI = this.shouldShowAIResults();
    do {
      if (node && !viewer.isCollapsed(node) && (!shouldShowAI || !$w6b(node))) {
        return true;
      }
    } while (node = navigator2.next());
    return false;
  }
  async selectNextMatch() {
    if (!this.hasSearchResults()) {
      return;
    }
    const [selected] = this.pc.getSelection();
    if (selected && !$D6b(selected)) {
      if (this.pc.isCollapsed(selected)) {
        await this.pc.expand(selected);
      }
    }
    const navigator2 = this.pc.navigate(selected);
    let next = navigator2.next();
    if (!next) {
      next = navigator2.first();
    }
    while (next && !$D6b(next)) {
      if (this.pc.isCollapsed(next)) {
        await this.pc.expand(next);
      }
      next = navigator2.next();
    }
    if (next) {
      if (next === selected) {
        this.pc.setFocus([]);
      }
      const event = $Zeb(void 0, false, false);
      this.pc.setFocus([next], event);
      this.pc.setSelection([next], event);
      this.pc.reveal(next);
      const ariaLabel = this.Lc.getAriaLabel(next);
      if (ariaLabel) {
        $_Z(ariaLabel);
      }
    }
  }
  async selectPreviousMatch() {
    if (!this.hasSearchResults()) {
      return;
    }
    const [selected] = this.pc.getSelection();
    let navigator2 = this.pc.navigate(selected);
    let prev = navigator2.previous();
    while (!prev || !$D6b(prev) && !this.pc.isCollapsed(prev)) {
      const nextPrev = prev ? navigator2.previous() : navigator2.last();
      if (!prev && !nextPrev) {
        return;
      }
      prev = nextPrev;
    }
    while (prev && !$D6b(prev)) {
      const nextItem = navigator2.next();
      if (!nextItem) {
        break;
      }
      await this.pc.expand(prev);
      navigator2 = this.pc.navigate(nextItem);
      prev = nextItem ? navigator2.previous() : navigator2.last();
    }
    if (prev) {
      if (prev === selected) {
        this.pc.setFocus([]);
      }
      const event = $Zeb(void 0, false, false);
      this.pc.setFocus([prev], event);
      this.pc.setSelection([prev], event);
      this.pc.reveal(prev);
      const ariaLabel = this.Lc.getAriaLabel(prev);
      if (ariaLabel) {
        $_Z(ariaLabel);
      }
    }
  }
  moveFocusToResults() {
    this.pc.domFocus();
  }
  focus() {
    super.focus();
    if (this.jc === "input" || !this.hasSearchResults()) {
      const updatedText = this.qe.seedOnFocus ? this.Id({ allowSearchOnType: false }) : false;
      this.vc.focus(void 0, void 0, updatedText);
    } else {
      this.pc.domFocus();
    }
  }
  updateTextFromFindWidgetOrSelection({ allowUnselectedWord = true, allowSearchOnType = true }) {
    let activeEditor = this.Tc.activeTextEditorControl;
    if ($P5(activeEditor) && !activeEditor?.hasTextFocus()) {
      const controller = $tgb.get(activeEditor);
      if (controller && controller.isFindInputFocused()) {
        return this.Hd(controller, { allowSearchOnType });
      }
      const editors = this.Uc.listCodeEditors();
      activeEditor = editors.find((editor) => editor instanceof $bdb && editor.getParentEditor() === activeEditor && editor.hasTextFocus()) ?? activeEditor;
    }
    return this.Id({ allowUnselectedWord, allowSearchOnType }, activeEditor);
  }
  Hd(controller, { allowSearchOnType = true }) {
    if (!this.qe.seedWithNearestWord && ($Qj().getSelection()?.toString() ?? "") === "") {
      return false;
    }
    const searchString = controller.getState().searchString;
    if (searchString === "") {
      return false;
    }
    this.vc.searchInput?.setCaseSensitive(controller.getState().matchCase);
    this.vc.searchInput?.setWholeWords(controller.getState().wholeWord);
    this.vc.searchInput?.setRegex(controller.getState().isRegex);
    this.Jd(searchString, allowSearchOnType);
    return true;
  }
  Id({ allowUnselectedWord = true, allowSearchOnType = true }, editor) {
    const seedSearchStringFromSelection = this.Ab.getValue("editor").find.seedSearchStringFromSelection;
    if (!seedSearchStringFromSelection || seedSearchStringFromSelection === "never") {
      return false;
    }
    let selectedText = this.Pd(allowUnselectedWord, editor);
    if (selectedText === null) {
      return false;
    }
    if (this.vc.searchInput?.getRegex()) {
      selectedText = $Af(selectedText);
    }
    this.Jd(selectedText, allowSearchOnType);
    return true;
  }
  Jd(text2, allowSearchOnType = true) {
    if (allowSearchOnType && !this.n.searchResult.isDirty) {
      this.vc.setValue(text2);
    } else {
      this.Kc = true;
      this.vc.setValue(text2);
      this.Kc = false;
    }
  }
  focusNextInputBox() {
    if (this.vc.searchInputHasFocus()) {
      if (this.vc.isReplaceShown()) {
        this.vc.focus(true, true);
      } else {
        this.Kd();
      }
      return;
    }
    if (this.vc.replaceInputHasFocus()) {
      this.Kd();
      return;
    }
    if (this.Ac.inputHasFocus()) {
      this.zc.focus();
      this.zc.select();
      return;
    }
    if (this.zc.inputHasFocus()) {
      this.Od();
      return;
    }
  }
  Kd() {
    if (this.Qd()) {
      this.toggleQueryDetails(true, this.Qd());
    } else {
      this.Od();
    }
  }
  focusPreviousInputBox() {
    if (this.vc.searchInputHasFocus()) {
      return;
    }
    if (this.vc.replaceInputHasFocus()) {
      this.vc.focus(true);
      return;
    }
    if (this.Ac.inputHasFocus()) {
      this.vc.focus(true, true);
      return;
    }
    if (this.zc.inputHasFocus()) {
      this.Ac.focus();
      this.Ac.select();
      return;
    }
    if (this.pc.isDOMFocused()) {
      this.Ld();
      return;
    }
  }
  Ld() {
    if (this.Qd()) {
      this.toggleQueryDetails(true, true, false, true);
    } else {
      this.vc.focus(true, true);
    }
  }
  Md() {
    if (this.g || !this.wc) {
      return;
    }
    const actionsPosition = this.qe.actionsPosition;
    this.getContainer().classList.toggle($p8b_1.c, actionsPosition === "right");
    this.vc.setWidth(
      this.wc.width - 28
      /* container margin */
    );
    this.zc.setWidth(
      this.wc.width - 28
      /* container margin */
    );
    this.Ac.setWidth(
      this.wc.width - 28
      /* container margin */
    );
    const widgetHeight = $Bj(this.uc);
    const messagesHeight = $Bj(this.sc);
    this.pc.layout(this.wc.height - widgetHeight - messagesHeight, this.wc.width - 28);
  }
  X(height, width2) {
    super.X(height, width2);
    this.wc = new $rj(width2, height);
    this.Md();
  }
  getControl() {
    return this.pc;
  }
  allSearchFieldsClear() {
    return this.vc.getReplaceValue() === "" && (!this.vc.searchInput || this.vc.searchInput.getValue() === "");
  }
  allFilePatternFieldsClear() {
    return this.searchExcludePattern.getValue() === "" && this.searchIncludePattern.getValue() === "";
  }
  hasSearchResults() {
    return !this.n.searchResult.isEmpty();
  }
  clearSearchResults(clearInput = true) {
    this.n.searchResult.clear();
    this.le(true);
    if (this.$c.getWorkbenchState() === 1) {
      this.ke();
    }
    if (clearInput) {
      if (this.allSearchFieldsClear()) {
        this.clearFilePatternFields();
      }
      this.vc.clear();
    }
    this.n.cancelSearch();
    this.pc.ariaLabel = localize(9745, null);
    this.kd.playSignal($N9.clear);
    this.Md();
  }
  clearFilePatternFields() {
    this.searchExcludePattern.clear();
    this.searchIncludePattern.clear();
  }
  cancelSearch(focus = true) {
    if (this.n.cancelSearch()) {
      if (focus) {
        this.vc.focus();
      }
      return true;
    }
    return false;
  }
  Od() {
    if (this.pc.getNode(void 0)) {
      this.pc.domFocus();
      const selection = this.pc.getSelection();
      if (selection.length === 0) {
        const event = $Zeb();
        this.pc.focusNext(void 0, void 0, event);
        this.pc.setSelection(this.pc.getFocus(), event);
      }
    }
  }
  Pd(allowUnselectedWord, editor) {
    if ($Nj(this.getContainer())) {
      return null;
    }
    editor = editor ?? this.Tc.activeTextEditorControl;
    if (!editor) {
      return null;
    }
    const allowUnselected = this.qe.seedWithNearestWord && allowUnselectedWord;
    return $r8b(allowUnselected, editor);
  }
  Qd() {
    return this.xc.classList.contains("more");
  }
  toggleCaseSensitive() {
    this.vc.searchInput?.setCaseSensitive(!this.vc.searchInput.getCaseSensitive());
    this.triggerQueryChange({ shouldKeepAIResults: true });
  }
  toggleWholeWords() {
    this.vc.searchInput?.setWholeWords(!this.vc.searchInput.getWholeWords());
    this.triggerQueryChange({ shouldKeepAIResults: true });
  }
  toggleRegex() {
    this.vc.searchInput?.setRegex(!this.vc.searchInput.getRegex());
    this.triggerQueryChange({ shouldKeepAIResults: true });
  }
  togglePreserveCase() {
    this.vc.replaceInput?.setPreserveCase(!this.vc.replaceInput.getPreserveCase());
    this.triggerQueryChange({ shouldKeepAIResults: true });
  }
  setSearchParameters(args2 = {}) {
    if (typeof args2.isCaseSensitive === "boolean") {
      this.vc.searchInput?.setCaseSensitive(args2.isCaseSensitive);
    }
    if (typeof args2.matchWholeWord === "boolean") {
      this.vc.searchInput?.setWholeWords(args2.matchWholeWord);
    }
    if (typeof args2.isRegex === "boolean") {
      this.vc.searchInput?.setRegex(args2.isRegex);
    }
    if (typeof args2.filesToInclude === "string") {
      this.searchIncludePattern.setValue(String(args2.filesToInclude));
    }
    if (typeof args2.filesToExclude === "string") {
      this.searchExcludePattern.setValue(String(args2.filesToExclude));
    }
    if (typeof args2.query === "string") {
      this.vc.searchInput?.setValue(args2.query);
    }
    if (typeof args2.replace === "string") {
      this.vc.replaceInput?.setValue(args2.replace);
    } else {
      if (this.vc.replaceInput && this.vc.replaceInput.getValue() !== "") {
        this.vc.replaceInput.setValue("");
      }
    }
    if (typeof args2.triggerSearch === "boolean" && args2.triggerSearch) {
      this.triggerQueryChange();
    }
    if (typeof args2.preserveCase === "boolean") {
      this.vc.replaceInput?.setPreserveCase(args2.preserveCase);
    }
    if (typeof args2.useExcludeSettingsAndIgnoreFiles === "boolean") {
      this.zc.setUseExcludesAndIgnoreFiles(args2.useExcludeSettingsAndIgnoreFiles);
    }
    if (typeof args2.onlyOpenEditors === "boolean") {
      this.searchIncludePattern.setOnlySearchInOpenEditors(args2.onlyOpenEditors);
    }
  }
  toggleQueryDetails(moveFocus = true, show2, skipLayout, reverse) {
    const cls = "more";
    show2 = typeof show2 === "undefined" ? !this.xc.classList.contains(cls) : Boolean(show2);
    this.rc["query.queryDetailsExpanded"] = show2;
    skipLayout = Boolean(skipLayout);
    if (show2) {
      this.yc.setAttribute("aria-expanded", "true");
      this.xc.classList.add(cls);
      if (moveFocus) {
        if (reverse) {
          this.zc.focus();
          this.zc.select();
        } else {
          this.Ac.focus();
          this.Ac.select();
        }
      }
    } else {
      this.yc.setAttribute("aria-expanded", "false");
      this.xc.classList.remove(cls);
      if (moveFocus) {
        this.vc.focus();
      }
    }
    if (!skipLayout && this.wc) {
      this.Md();
    }
  }
  searchInFolders(folderPaths = []) {
    this.Rd(true, folderPaths);
  }
  searchOutsideOfFolders(folderPaths = []) {
    this.Rd(false, folderPaths);
  }
  Rd(include, folderPaths) {
    if (!folderPaths.length || folderPaths.some((folderPath) => folderPath === ".")) {
      this.Ac.setValue("");
      this.vc.focus();
      return;
    }
    if (!this.Qd()) {
      this.toggleQueryDetails(true, true);
    }
    (include ? this.Ac : this.zc).setValue(folderPaths.join(", "));
    this.vc.focus(false);
  }
  triggerQueryChange(_options) {
    const options3 = { preserveFocus: true, triggeredOnType: false, delay: 0, ..._options };
    if (options3.triggeredOnType && !this.qe.searchOnType) {
      return;
    }
    if (!this.Kc) {
      const delay = options3.triggeredOnType ? options3.delay : 0;
      this.Jc.trigger(() => {
        this.Ud(options3.preserveFocus, options3.triggeredOnType, options3.shouldKeepAIResults);
      }, delay);
    }
  }
  Sd() {
    return this.zc.getValue().trim();
  }
  Td() {
    return this.Ac.getValue().trim();
  }
  Ud(preserveFocus, triggeredOnType = false, shouldKeepAIResults = false) {
    if (!this.vc.searchInput?.inputBox.isInputValid()) {
      return;
    }
    const isRegex = this.vc.searchInput.getRegex();
    const isInNotebookMarkdownInput = this.vc.getNotebookFilters().markupInput;
    const isInNotebookMarkdownPreview = this.vc.getNotebookFilters().markupPreview;
    const isInNotebookCellInput = this.vc.getNotebookFilters().codeInput;
    const isInNotebookCellOutput = this.vc.getNotebookFilters().codeOutput;
    const isWholeWords = this.vc.searchInput.getWholeWords();
    const isCaseSensitive = this.vc.searchInput.getCaseSensitive();
    const contentPattern = this.vc.searchInput.getValue();
    const excludePatternText = this.Sd();
    const includePatternText = this.Td();
    const useExcludesAndIgnoreFiles = this.zc.useExcludesAndIgnoreFiles();
    const onlySearchInOpenEditors = this.Ac.onlySearchInOpenEditors();
    if (contentPattern.length === 0) {
      this.clearSearchResults(false);
      this.Dd();
      return;
    }
    const content = {
      pattern: contentPattern,
      isRegExp: isRegex,
      isCaseSensitive,
      isWordMatch: isWholeWords,
      notebookInfo: {
        isInNotebookMarkdownInput,
        isInNotebookMarkdownPreview,
        isInNotebookCellInput,
        isInNotebookCellOutput
      }
    };
    const excludePattern = [{ pattern: this.zc.getValue() }];
    const includePattern = this.Ac.getValue();
    const charsPerLine = content.isRegExp ? 1e4 : 1e3;
    const options3 = {
      _reason: "searchView",
      extraFileResources: this.Db.invokeFunction($hO),
      maxResults: this.qe.maxResults ?? void 0,
      disregardIgnoreFiles: !useExcludesAndIgnoreFiles || void 0,
      disregardExcludeSettings: !useExcludesAndIgnoreFiles || void 0,
      onlyOpenEditors: onlySearchInOpenEditors,
      excludePattern,
      includePattern,
      previewOptions: {
        matchLines: 1,
        charsPerLine
      },
      isSmartCase: this.qe.smartCase,
      expandPatterns: true
    };
    const folderResources = this.$c.getWorkspace().folders;
    const onQueryValidationError = (err) => {
      this.vc.searchInput?.showMessage({
        content: err.message,
        type: 3
        /* MessageType.ERROR */
      });
      this.n.searchResult.clear();
    };
    let query;
    try {
      query = this.j.text(content, folderResources.map((folder) => folder.uri), options3);
    } catch (err) {
      onQueryValidationError(err);
      return;
    }
    this.Vd(query).then(() => {
      if (!shouldKeepAIResults && this.pc.hasNode(this.searchResult.aiTextSearchResult)) {
        this.pc.collapse(this.searchResult.aiTextSearchResult);
      }
      this.Wd(query, options3, excludePatternText, includePatternText, triggeredOnType, shouldKeepAIResults);
      if (!preserveFocus) {
        this.vc.focus(false, void 0, true);
      }
    }, onQueryValidationError);
  }
  Vd(query) {
    const folderQueriesExistP = query.folderQueries.map((fq) => {
      return this.Sc.exists(fq.folder).catch(() => false);
    });
    return Promise.all(folderQueriesExistP).then((existResults) => {
      const existingFolderQueries = query.folderQueries.filter((folderQuery, i2) => existResults[i2]);
      if (!query.folderQueries.length || existingFolderQueries.length) {
        query.folderQueries = existingFolderQueries;
      } else {
        const nonExistantPath = query.folderQueries[0].folder.fsPath;
        const searchPathNotFoundError = localize(9746, null, nonExistantPath);
        return Promise.reject(new Error(searchPathNotFoundError));
      }
      return void 0;
    });
  }
  Wd(query, options3, excludePatternText, includePatternText, triggeredOnType, shouldKeepAIResults) {
    this.Hc.trigger(() => {
      this.vc.searchInput?.onSearchSubmit();
      this.zc.onSearchSubmit();
      this.Ac.onSearchSubmit();
    });
    this.n.cancelSearch(true);
    this.n.cancelAISearch(true);
    this.Gc = this.Gc.then(() => this.ae(query, excludePatternText, includePatternText, triggeredOnType, shouldKeepAIResults)).then(() => void 0, () => void 0);
  }
  async Xd() {
    if (this.md === SearchUIState.Idle) {
      return;
    }
    try {
      const fileCount = this.n.searchResult.fileCount();
      if (this.Nc !== fileCount) {
        this.Nc = fileCount;
        await this.xd();
      }
    } finally {
      this.Oc.schedule();
    }
  }
  async Yd() {
    const collapseResults = this.qe.collapseResults;
    if (collapseResults !== "alwaysCollapse" && this.n.searchResult.matches().length === 1) {
      const onlyMatch = this.n.searchResult.matches()[0];
      await this.pc.expandTo(onlyMatch);
      if (onlyMatch.count() < 50) {
        await this.pc.expand(onlyMatch);
      }
    }
  }
  async Zd(progressComplete, excludePatternText, includePatternText, completed, shouldDoFinalRefresh = true) {
    this.md = SearchUIState.Idle;
    progressComplete();
    if (shouldDoFinalRefresh) {
      await this.xd();
    }
    const hasResults = !this.n.searchResult.isEmpty();
    if (completed?.exit === 1) {
      return;
    }
    if (!hasResults) {
      const hasExcludes = !!excludePatternText;
      const hasIncludes = !!includePatternText;
      let message;
      if (!completed) {
        message = SEARCH_CANCELLED_MESSAGE;
      } else if (this.Ac.onlySearchInOpenEditors()) {
        if (hasIncludes && hasExcludes) {
          message = localize(9747, null, includePatternText, excludePatternText);
        } else if (hasIncludes) {
          message = localize(9748, null, includePatternText);
        } else if (hasExcludes) {
          message = localize(9749, null, excludePatternText);
        } else {
          message = localize(9750, null);
        }
      } else {
        if (hasIncludes && hasExcludes) {
          message = localize(9751, null, includePatternText, excludePatternText);
        } else if (hasIncludes) {
          message = localize(9752, null, includePatternText);
        } else if (hasExcludes) {
          message = localize(9753, null, excludePatternText);
        } else {
          message = localize(9754, null);
        }
      }
      $_Z(message);
      const messageEl = this.Dd();
      $bk(messageEl, message);
      if (!completed) {
        const searchAgainButton = this.tc.add(new SearchLinkButton(localize(9755, null), () => this.triggerQueryChange({ preserveFocus: false }), this.Hb));
        $bk(messageEl, searchAgainButton.element);
      } else if (hasIncludes || hasExcludes) {
        const searchAgainButton = this.tc.add(new SearchLinkButton(localize(9756, null), this.ee.bind(this), this.Hb));
        $bk(messageEl, searchAgainButton.element);
      } else {
        const openSettingsButton = this.tc.add(new SearchLinkButton(localize(9757, null), this.be.bind(this), this.Hb));
        $bk(messageEl, openSettingsButton.element);
      }
      if (completed) {
        $bk(messageEl, $138("span", void 0, " - "));
        const learnMoreButton = this.tc.add(new SearchLinkButton(localize(9758, null), this.de.bind(this), this.Hb));
        $bk(messageEl, learnMoreButton.element);
      }
      if (this.$c.getWorkbenchState() === 1) {
        this.ke();
      }
      this.Md();
    } else {
      this.n.searchResult.toggleHighlights(this.isVisible());
      $_Z(localize(9759, null, this.n.searchResult.count(), this.n.searchResult.fileCount()));
    }
    if (completed && completed.limitHit) {
      completed.messages.push({ type: TextSearchCompleteMessageType.Warning, text: localize(9760, null) });
    }
    if (completed && completed.messages) {
      for (const message of completed.messages) {
        this.ie(message);
      }
    }
    this.Md();
  }
  async $d(e, progressComplete, excludePatternText, includePatternText, completed, shouldDoFinalRefresh = true) {
    this.md = SearchUIState.Idle;
    if ($kb(e)) {
      return this.Zd(progressComplete, excludePatternText, includePatternText, completed, shouldDoFinalRefresh);
    } else {
      progressComplete();
      this.vc.searchInput?.showMessage({
        content: e.message,
        type: 3
        /* MessageType.ERROR */
      });
      this.n.searchResult.clear();
      return Promise.resolve();
    }
  }
  async addAIResults() {
    const excludePatternText = this.Sd();
    const includePatternText = this.Td();
    let progressComplete;
    this.Vc.withProgress({ location: this.Wb(), delay: 0 }, (_progress) => {
      return new Promise((resolve) => progressComplete = resolve);
    });
    this.vc.searchInput?.clearMessage();
    this.md = SearchUIState.Searching;
    this.le();
    const slowTimer = setTimeout(() => {
      this.md = SearchUIState.SlowSearch;
    }, 2e3);
    this.Nc = 0;
    this.pc.setSelection([]);
    this.pc.setFocus([]);
    this.n.replaceString = this.vc.getReplaceValue();
    this.n.searchResult.setAIQueryUsingTextQuery();
    const result = this.n.addAIResults();
    return result.then((complete) => {
      clearTimeout(slowTimer);
      return this.Zd(progressComplete, excludePatternText, includePatternText, complete, false);
    }, (e) => {
      clearTimeout(slowTimer);
      return this.$d(e, progressComplete, excludePatternText, includePatternText, void 0, false);
    });
  }
  ae(query, excludePatternText, includePatternText, triggeredOnType, shouldKeepAIResults) {
    let progressComplete;
    this.Vc.withProgress({ location: this.Wb(), delay: triggeredOnType ? 300 : 0 }, (_progress) => {
      return new Promise((resolve) => progressComplete = resolve);
    });
    this.vc.searchInput?.clearMessage();
    this.md = SearchUIState.Searching;
    this.le();
    const slowTimer = setTimeout(() => {
      this.md = SearchUIState.SlowSearch;
    }, 2e3);
    this.Nc = 0;
    this.Oc.schedule();
    this.vc.setReplaceAllActionState(false);
    this.pc.setSelection([]);
    this.pc.setFocus([]);
    this.n.replaceString = this.vc.getReplaceValue();
    const result = this.n.search(query);
    if (!shouldKeepAIResults) {
      this.n.searchResult.setAIQueryUsingTextQuery(query);
    }
    return result.asyncResults.then((complete) => {
      clearTimeout(slowTimer);
      return this.Zd(progressComplete, excludePatternText, includePatternText, complete);
    }, (e) => {
      clearTimeout(slowTimer);
      return this.$d(e, progressComplete, excludePatternText, includePatternText);
    });
  }
  be(e) {
    $9j.stop(e, false);
    this.ce("@id:files.exclude,search.exclude,search.useParentIgnoreFiles,search.useGlobalIgnoreFiles,search.useIgnoreFiles");
  }
  ce(query) {
    const options3 = { query };
    return this.$c.getWorkbenchState() !== 1 ? this.dd.openWorkspaceSettings(options3) : this.dd.openUserSettings(options3);
  }
  de() {
    this.Eb.open(URI.parse("https://go.microsoft.com/fwlink/?linkid=853977"));
  }
  ee() {
    this.zc.setValue("");
    this.Ac.setValue("");
    this.Ac.setOnlySearchInOpenEditors(false);
    this.triggerQueryChange({ preserveFocus: false });
  }
  fe() {
    this.toggleQueryDetails(false, true);
    this.searchExcludePattern.setUseExcludesAndIgnoreFiles(true);
  }
  ge() {
    this.toggleQueryDetails(false, true);
    this.Ac.setOnlySearchInOpenEditors(false);
  }
  he(disregardExcludesAndIgnores, onlyOpenEditors, clear = false) {
    const fileCount = this.n.searchResult.fileCount();
    const resultCount = this.n.searchResult.count();
    this.ic.set(fileCount > 0);
    const msgWasHidden = this.sc.style.display === "none";
    const messageEl = this.Dd();
    const resultMsg = clear ? "" : this.je(resultCount, fileCount);
    this.pc.ariaLabel = resultMsg + localize(9761, null, this.searchResult.query?.contentPattern.pattern ?? "");
    $bk(messageEl, resultMsg);
    if (fileCount > 0) {
      if (disregardExcludesAndIgnores) {
        const excludesDisabledMessage = " - " + localize(9762, null) + " ";
        const enableExcludesButton = this.tc.add(new SearchLinkButton(localize(9763, null), this.fe.bind(this), this.Hb, localize(9764, null)));
        $bk(messageEl, $138("span", void 0, excludesDisabledMessage, "(", enableExcludesButton.element, ")"));
      }
      if (onlyOpenEditors) {
        const searchingInOpenMessage = " - " + localize(9765, null) + " ";
        const disableOpenEditorsButton = this.tc.add(new SearchLinkButton(localize(9766, null), this.ge.bind(this), this.Hb, localize(9767, null)));
        $bk(messageEl, $138("span", void 0, searchingInOpenMessage, "(", disableOpenEditorsButton.element, ")"));
      }
      $bk(messageEl, " - ");
      const openInEditorTooltip = $U6b(localize(9768, null), this.yb.lookupKeybinding(
        "search.action.openInEditor"
        /* Constants.SearchCommandIds.OpenInEditorCommandId */
      ));
      const openInEditorButton = this.tc.add(new SearchLinkButton(localize(9769, null), () => this.Db.invokeFunction($c8b, this.searchResult, this.searchIncludePattern.getValue(), this.searchExcludePattern.getValue(), this.searchIncludePattern.onlySearchInOpenEditors()), this.Hb, openInEditorTooltip));
      $bk(messageEl, openInEditorButton.element);
      this.Md();
    } else if (!msgWasHidden) {
      $ik(this.sc);
    }
  }
  ie(message) {
    const messageBox = this.sc.firstChild;
    if (!messageBox) {
      return;
    }
    $bk(messageBox, $57b(message, this.Db, this.Wc, this.Eb, this.Yc, this.tc, () => this.triggerQueryChange()));
  }
  je(resultCount, fileCount) {
    if (resultCount === 1 && fileCount === 1) {
      return localize(9770, null, resultCount, fileCount);
    } else if (resultCount === 1) {
      return localize(9771, null, resultCount, fileCount);
    } else if (fileCount === 1) {
      return localize(9772, null, resultCount, fileCount);
    } else {
      return localize(9773, null, resultCount, fileCount);
    }
  }
  ke() {
    this.Fc = this.Dd();
    const textEl = $bk(this.Fc, $138("p", void 0, localize(9774, null)));
    const openFolderButton2 = this.tc.add(new SearchLinkButton(localize(9775, null), () => {
      this.Yc.executeCommand($m && $p ? $1yb.ID : $Yyb.ID).catch((err) => $gb(err));
    }, this.Hb));
    $bk(textEl, openFolderButton2.element);
  }
  le(forceHideMessages = false) {
    const showingCancelled = (this.sc.firstChild?.textContent?.indexOf(SEARCH_CANCELLED_MESSAGE) ?? -1) > -1;
    if (showingCancelled || forceHideMessages || !this.Ab.getValue().search.searchOnType) {
      $ik(this.sc);
    }
    $hk(this.Bc);
    this.Cc = void 0;
  }
  me(match, uri) {
    return $O6b(match) || uri.scheme !== Schemas.untitled && this.hd.getContributedNotebookTypes(uri).length > 0;
  }
  ne(lineMatch, preserveFocus, sideBySide, pinned) {
    const useReplacePreview = this.Ab.getValue().search.useReplacePreview;
    const resource = $D6b(lineMatch) ? lineMatch.parent().resource : lineMatch.resource;
    return useReplacePreview && this.n.isReplaceActive() && !!this.n.replaceString && !this.me(lineMatch, resource) ? this.bd.openReplacePreview(lineMatch, preserveFocus, sideBySide, pinned) : this.open(lineMatch, preserveFocus, sideBySide, pinned, resource);
  }
  async open(element, preserveFocus, sideBySide, pinned, resourceInput) {
    const selection = $q8b(element, this.n);
    const oldParentMatches = $D6b(element) ? element.parent().matches() : [];
    const resource = resourceInput ?? ($D6b(element) ? element.parent().resource : element.resource);
    let editor;
    const options3 = {
      preserveFocus,
      pinned,
      selection,
      revealIfVisible: true
    };
    try {
      editor = await this.Tc.openEditor({
        resource,
        options: options3
      }, sideBySide ? $oJ : $nJ);
      const editorControl = editor?.getControl();
      if ($D6b(element) && preserveFocus && $P5(editorControl)) {
        this.n.searchResult.getRangeHighlightDecorations().highlightRange(editorControl.getModel(), element.range());
      } else {
        this.n.searchResult.getRangeHighlightDecorations().removeHighlightRange();
      }
    } catch (err) {
      $gb(err);
      return;
    }
    if (editor instanceof $ILb) {
      const elemParent = element.parent();
      if ($D6b(element)) {
        if ($O6b(element)) {
          element.parent().showMatch(element);
        } else {
          const editorWidget = editor.getControl();
          if (editorWidget) {
            elemParent.bindNotebookEditorWidget(editorWidget);
            await elemParent.updateMatchesForEditorWidget();
            const matchIndex = oldParentMatches.findIndex((e) => e.id() === element.id());
            const matches = elemParent.matches();
            const match = matchIndex >= matches.length ? matches[matches.length - 1] : matches[matchIndex];
            if ($O6b(match)) {
              elemParent.showMatch(match);
              if (!this.pc.getFocus().includes(match) || !this.pc.getSelection().includes(match)) {
                this.pc.setSelection([match], $Zeb());
                this.pc.setFocus([match]);
              }
            }
          }
        }
      }
    }
  }
  openEditorWithMultiCursor(element) {
    const resource = $D6b(element) ? element.parent().resource : element.resource;
    return this.Tc.openEditor({
      resource,
      options: {
        preserveFocus: false,
        pinned: true,
        revealIfVisible: true
      }
    }).then((editor) => {
      if (editor) {
        let fileMatch = null;
        if ($C6b(element)) {
          fileMatch = element;
        } else if ($D6b(element)) {
          fileMatch = element.parent();
        }
        if (fileMatch) {
          const selections = fileMatch.matches().map((m) => new $_D(m.range().startLineNumber, m.range().startColumn, m.range().endLineNumber, m.range().endColumn));
          const codeEditor = $S5(editor.getControl());
          if (codeEditor) {
            const multiCursorController = $Hjb.get(codeEditor);
            multiCursorController?.selectAllUsingSelections(selections);
          }
        }
      }
      this.n.searchResult.getRangeHighlightDecorations().removeHighlightRange();
    }, $gb);
  }
  oe(resource) {
    if (!this.n) {
      return;
    }
    let matches = this.n.searchResult.matches();
    for (let i2 = 0, len = matches.length; i2 < len; i2++) {
      if (resource.toString() === matches[i2].resource.toString()) {
        this.n.searchResult.remove(matches[i2]);
      }
    }
    matches = this.n.searchResult.matches(true);
    for (let i2 = 0, len = matches.length; i2 < len; i2++) {
      if (resource.toString() === matches[i2].resource.toString()) {
        this.n.searchResult.remove(matches[i2]);
      }
    }
  }
  pe(e) {
    if (!this.n || this.qe.sortOrder !== "modified" && !e.gotDeleted()) {
      return;
    }
    const matches = this.n.searchResult.matches();
    if (e.gotDeleted()) {
      const deletedMatches = matches.filter((m) => e.contains(
        m.resource,
        2
        /* FileChangeType.DELETED */
      ));
      this.n.searchResult.remove(deletedMatches);
    } else {
      const changedMatches = matches.filter((m) => e.contains(m.resource));
      if (changedMatches.length && this.qe.sortOrder === "modified") {
        this.te(changedMatches).then(async () => this.Rc.queue());
      }
    }
  }
  get qe() {
    return this.Ab.getValue("search");
  }
  re() {
    this.vc.clearHistory();
    this.zc.clearHistory();
    this.Ac.clearHistory();
  }
  saveState() {
    if (!this.vc) {
      return;
    }
    const patternExcludes = this.zc?.getValue().trim() ?? "";
    const patternIncludes = this.Ac?.getValue().trim() ?? "";
    const onlyOpenEditors = this.Ac?.onlySearchInOpenEditors() ?? false;
    const useExcludesAndIgnoreFiles = this.zc?.useExcludesAndIgnoreFiles() ?? true;
    const preserveCase = this.n.preserveCase;
    if (this.vc.searchInput) {
      const isRegex = this.vc.searchInput.getRegex();
      const isWholeWords = this.vc.searchInput.getWholeWords();
      const isCaseSensitive = this.vc.searchInput.getCaseSensitive();
      const contentPattern = this.vc.searchInput.getValue();
      const isInNotebookCellInput = this.vc.getNotebookFilters().codeInput;
      const isInNotebookCellOutput = this.vc.getNotebookFilters().codeOutput;
      const isInNotebookMarkdownInput = this.vc.getNotebookFilters().markupInput;
      const isInNotebookMarkdownPreview = this.vc.getNotebookFilters().markupPreview;
      this.rc["query.contentPattern"] = contentPattern;
      this.rc["query.regex"] = isRegex;
      this.rc["query.wholeWords"] = isWholeWords;
      this.rc["query.caseSensitive"] = isCaseSensitive;
      this.rc["query.isInNotebookMarkdownInput"] = isInNotebookMarkdownInput;
      this.rc["query.isInNotebookMarkdownPreview"] = isInNotebookMarkdownPreview;
      this.rc["query.isInNotebookCellInput"] = isInNotebookCellInput;
      this.rc["query.isInNotebookCellOutput"] = isInNotebookCellOutput;
    }
    this.rc["query.folderExclusions"] = patternExcludes;
    this.rc["query.folderIncludes"] = patternIncludes;
    this.rc["query.useExcludesAndIgnoreFiles"] = useExcludesAndIgnoreFiles;
    this.rc["query.preserveCase"] = preserveCase;
    this.rc["query.onlyOpenEditors"] = onlyOpenEditors;
    const isReplaceShown = this.searchAndReplaceWidget.isReplaceShown();
    this.rc["view.showReplace"] = isReplaceShown;
    this.rc["view.treeLayout"] = this.ld;
    this.rc["query.replaceText"] = isReplaceShown && this.vc.getReplaceValue();
    this.se();
    this.r.saveMemento();
    super.saveState();
  }
  se() {
    if (this.vc === void 0) {
      return;
    }
    const history = /* @__PURE__ */ Object.create(null);
    const searchHistory = this.vc.getSearchHistory();
    if (searchHistory && searchHistory.length) {
      history.search = searchHistory;
    }
    const replaceHistory = this.vc.getReplaceHistory();
    if (replaceHistory && replaceHistory.length) {
      history.replace = replaceHistory;
    }
    const patternExcludesHistory = this.zc.getHistory();
    if (patternExcludesHistory && patternExcludesHistory.length) {
      history.exclude = patternExcludesHistory;
    }
    const patternIncludesHistory = this.Ac.getHistory();
    if (patternIncludesHistory && patternIncludesHistory.length) {
      history.include = patternIncludesHistory;
    }
    this.ed.save(history);
  }
  async te(elements) {
    const files = elements.map((f) => f.resolveFileStat(this.Sc));
    await Promise.all(files);
  }
  ue() {
    for (const fileMatch of this.searchResult.matches()) {
      fileMatch.fileStat = void 0;
    }
    for (const fileMatch of this.searchResult.matches(true)) {
      fileMatch.fileStat = void 0;
    }
  }
  dispose() {
    this.g = true;
    this.saveState();
    super.dispose();
  }
};
$p8b = $p8b_1 = __decorate([
  __param(1, $km),
  __param(2, $mJ),
  __param(3, $U5),
  __param(4, $TJ),
  __param(5, $PJ),
  __param(6, $Yv),
  __param(7, $sn),
  __param(8, $40),
  __param(9, $Pk),
  __param(10, $$M),
  __param(11, $kl),
  __param(12, $Zk),
  __param(13, $O7b),
  __param(14, $on),
  __param(15, $u7b),
  __param(16, $cK),
  __param(17, $TK),
  __param(18, $gs),
  __param(19, $d8b),
  __param(20, $50),
  __param(21, $ND),
  __param(22, $Ty),
  __param(23, $jv),
  __param(24, $O4),
  __param(25, $zv),
  __param(26, $5$),
  __param(27, $mrb),
  __param(28, $wn),
  __param(29, $I9)
], $p8b);
var SearchLinkButton = class extends $3c {
  constructor(label3, handler, hoverService, tooltip) {
    super();
    this.element = $138("a.pointer", { tabindex: 0 }, label3);
    this.B(hoverService.setupManagedHover($JZ("mouse"), this.element, tooltip));
    this.c(handler);
  }
  c(handler) {
    const wrappedHandler = (e) => {
      $9j.stop(e, false);
      handler(e);
    };
    this.B($_i(this.element, $7j.CLICK, wrappedHandler));
    this.B($_i(this.element, $7j.KEY_DOWN, (e) => {
      const event = new $if(e);
      if (event.equals(
        10
        /* KeyCode.Space */
      ) || event.equals(
        3
        /* KeyCode.Enter */
      )) {
        wrappedHandler(e);
        event.preventDefault();
        event.stopPropagation();
      }
    }));
  }
};
function $q8b(element, viewModel) {
  let match = null;
  if ($D6b(element)) {
    match = element;
  }
  if ($C6b(element) && element.count() > 0) {
    match = element.matches()[element.matches().length - 1];
  }
  if (match) {
    const range = match.range();
    if (viewModel.isReplaceActive() && !!viewModel.replaceString) {
      const replaceString = match.replaceString;
      return {
        startLineNumber: range.startLineNumber,
        startColumn: range.startColumn,
        endLineNumber: range.startLineNumber,
        endColumn: range.startColumn + replaceString.length
      };
    }
    return range;
  }
  return void 0;
}
function $r8b(allowUnselectedWord, activeEditor) {
  let editor = activeEditor;
  if ($Q5(editor)) {
    if (editor.getOriginalEditor().hasTextFocus()) {
      editor = editor.getOriginalEditor();
    } else {
      editor = editor.getModifiedEditor();
    }
  }
  if (!$P5(editor) || !editor.hasModel()) {
    return null;
  }
  const range = editor.getSelection();
  if (!range) {
    return null;
  }
  if (range.isEmpty()) {
    if (allowUnselectedWord) {
      const wordAtPosition = editor.getModel().getWordAtPosition(range.getStartPosition());
      return wordAtPosition?.word ?? null;
    } else {
      return null;
    }
  }
  let searchText = "";
  for (let i2 = range.startLineNumber; i2 <= range.endLineNumber; i2++) {
    let lineText = editor.getModel().getLineContent(i2);
    if (i2 === range.endLineNumber) {
      lineText = lineText.substring(0, range.endColumn - 1);
    }
    if (i2 === range.startLineNumber) {
      lineText = lineText.substring(range.startColumn - 1);
    }
    if (i2 !== range.startLineNumber) {
      lineText = "\n" + lineText;
    }
    searchText += lineText;
  }
  return searchText;
}
var SearchViewDataSource = class SearchViewDataSource2 {
  constructor(c, d) {
    this.c = c;
    this.d = d;
  }
  get g() {
    return this.d.getValue("search");
  }
  h(searchResult) {
    const ret = [];
    if (!searchResult.plainTextSearchResult.isEmpty()) {
      if (!this.c.shouldShowAIResults()) {
        return this.j(searchResult.plainTextSearchResult);
      }
      ret.push(searchResult.plainTextSearchResult);
    }
    if (this.c.shouldShowAIResults() && searchResult.searchModel.hasPlainResults && !searchResult.aiTextSearchResult.hidden) {
      ret.push(searchResult.aiTextSearchResult);
    }
    return ret;
  }
  j(textSearchResult) {
    const folderMatches = textSearchResult.folderMatches().filter((fm) => !fm.isEmpty()).sort($Q6b);
    if (folderMatches.length === 1) {
      return this.k(folderMatches[0]);
    }
    return folderMatches;
  }
  k(folderMatch) {
    const matchArray = this.c.ld ? folderMatch.matches() : folderMatch.allDownstreamFileMatches();
    const matches = matchArray.sort((a, b) => $Q6b(a, b, this.g.sortOrder));
    return matches;
  }
  l(fileMatch) {
    const matches = fileMatch.matches().sort($Q6b);
    return matches;
  }
  hasChildren(element) {
    if ($D6b(element)) {
      return false;
    }
    if ($w6b(element) && element.isAIContributed) {
      return true;
    }
    const hasChildren = element.hasChildren;
    return hasChildren;
  }
  getChildren(element) {
    if ($v6b(element)) {
      return this.h(element);
    } else if ($w6b(element)) {
      if (element.isAIContributed && !this.c.model.hasAIResults) {
        return this.c.addAIResults().then(() => this.j(element));
      }
      return this.j(element);
    } else if ($y6b(element)) {
      return this.k(element);
    } else if ($C6b(element)) {
      return this.l(element);
    }
    return [];
  }
  getParent(element) {
    const parent = element.parent();
    if ($v6b(parent)) {
      throw new Error("Invalid element passed to getParent");
    }
    return parent;
  }
};
SearchViewDataSource = __decorate([
  __param(1, $kl)
], SearchViewDataSource);
var RefreshTreeController = class RefreshTreeController2 extends $3c {
  constructor(g, h3, j) {
    super();
    this.g = g;
    this.h = h3;
    this.j = j;
    this.n = [];
    this.c = this.B(new $Ph());
  }
  async queue(e) {
    if (e) {
      this.n.push(e);
    }
    return this.c.queue(this.r.bind(this));
  }
  async r() {
    const aggregateChangeEvent = this.n.length === 0 ? void 0 : {
      elements: this.n.map((e) => e.elements).flat(),
      added: this.n.some((e) => e.added),
      removed: this.n.some((e) => e.removed),
      clearingAll: this.n.some((e) => e.clearingAll)
    };
    this.n = [];
    return this.t(aggregateChangeEvent);
  }
  async s() {
    const files = this.g.model.searchResult.matches().filter((f) => !f.fileStat).map((f) => f.resolveFileStat(this.j));
    await Promise.all(files);
  }
  async t(event) {
    const searchConfig = this.h();
    if (!event || event.added || event.removed) {
      if (searchConfig.sortOrder === "modified") {
        await this.s().then(() => this.g.getControl().updateChildren(void 0));
      } else {
        await this.g.getControl().updateChildren(void 0);
      }
    } else {
      if (searchConfig.sortOrder === "countAscending" || searchConfig.sortOrder === "countDescending") {
        await this.g.getControl().updateChildren(void 0);
      } else {
        const treeHasAllElements = event.elements.every((elem) => this.g.getControl().hasNode(elem));
        if (treeHasAllElements) {
          await Promise.all(event.elements.map(async (element) => {
            await this.g.getControl().updateChildren(element);
            this.g.getControl().rerender(element);
          }));
        } else {
          this.g.getControl().updateChildren(void 0);
        }
      }
    }
  }
};
RefreshTreeController = __decorate([
  __param(2, $km)
], RefreshTreeController);

// out-build/vs/workbench/services/search/common/replace.js
var $h6b = class {
  constructor(replaceString, arg2, arg3) {
    this.b = false;
    this.a = replaceString;
    let searchPatternInfo;
    let parseParameters;
    if (typeof arg2 === "boolean") {
      parseParameters = arg2;
      this.c = arg3;
    } else {
      searchPatternInfo = arg2;
      parseParameters = !!searchPatternInfo.isRegExp;
      this.c = $Jf(searchPatternInfo.pattern, !!searchPatternInfo.isRegExp, { matchCase: searchPatternInfo.isCaseSensitive, wholeWord: searchPatternInfo.isWordMatch, multiline: searchPatternInfo.isMultiline, global: false, unicode: true });
    }
    if (parseParameters) {
      this.f(replaceString);
    }
    if (this.c.global) {
      this.c = $Jf(this.c.source, true, { matchCase: !this.c.ignoreCase, wholeWord: false, multiline: this.c.multiline, global: false });
    }
    this.d = new RegExp(/([\s\S]*?)((?:\\[uUlL])+?|)(\$[0-9]+)([\s\S]*?)/g);
  }
  get hasParameters() {
    return this.b;
  }
  get pattern() {
    return this.a;
  }
  get regExp() {
    return this.c;
  }
  /**
  * Returns the replace string for the first match in the given text.
  * If text has no matches then returns null.
  */
  getReplaceString(text2, preserveCase) {
    this.c.lastIndex = 0;
    const match = this.c.exec(text2);
    if (match) {
      if (this.hasParameters) {
        const replaceString = this.e(text2, this.c, this.buildReplaceString(match, preserveCase));
        if (match[0] === text2) {
          return replaceString;
        }
        return replaceString.substr(match.index, match[0].length - (text2.length - replaceString.length));
      }
      return this.buildReplaceString(match, preserveCase);
    }
    return null;
  }
  /**
   * replaceWithCaseOperations applies case operations to relevant replacement strings and applies
   * the affected $N arguments. It then passes unaffected $N arguments through to string.replace().
   *
   * \u			=> upper-cases one character in a match.
   * \U			=> upper-cases ALL remaining characters in a match.
   * \l			=> lower-cases one character in a match.
   * \L			=> lower-cases ALL remaining characters in a match.
   */
  e(text2, regex, replaceString) {
    if (!/\\[uUlL]/.test(replaceString)) {
      return text2.replace(regex, replaceString);
    }
    const firstMatch = regex.exec(text2);
    if (firstMatch === null) {
      return text2.replace(regex, replaceString);
    }
    let patMatch;
    let newReplaceString = "";
    let lastIndex = 0;
    let lastMatch = "";
    while ((patMatch = this.d.exec(replaceString)) !== null) {
      lastIndex = patMatch.index;
      const fullMatch = patMatch[0];
      lastMatch = fullMatch;
      let caseOps = patMatch[2];
      const money = patMatch[3];
      if (!caseOps) {
        newReplaceString += fullMatch;
        continue;
      }
      const replacement = firstMatch[parseInt(money.slice(1))];
      if (!replacement) {
        newReplaceString += fullMatch;
        continue;
      }
      const replacementLen = replacement.length;
      newReplaceString += patMatch[1];
      caseOps = caseOps.replace(/\\/g, "");
      let i2 = 0;
      for (; i2 < caseOps.length; i2++) {
        switch (caseOps[i2]) {
          case "U":
            newReplaceString += replacement.slice(i2).toUpperCase();
            i2 = replacementLen;
            break;
          case "u":
            newReplaceString += replacement[i2].toUpperCase();
            break;
          case "L":
            newReplaceString += replacement.slice(i2).toLowerCase();
            i2 = replacementLen;
            break;
          case "l":
            newReplaceString += replacement[i2].toLowerCase();
            break;
        }
      }
      if (i2 < replacementLen) {
        newReplaceString += replacement.slice(i2);
      }
      newReplaceString += patMatch[4];
    }
    newReplaceString += replaceString.slice(lastIndex + lastMatch.length);
    return text2.replace(regex, newReplaceString);
  }
  buildReplaceString(matches, preserveCase) {
    if (preserveCase) {
      return $V3(matches, this.a);
    } else {
      return this.a;
    }
  }
  /**
   * \n => LF
   * \t => TAB
   * \\ => \
   * $0 => $& (see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/replace#Specifying_a_string_as_a_parameter)
   * everything else stays untouched
   */
  f(replaceString) {
    if (!replaceString || replaceString.length === 0) {
      return;
    }
    let substrFrom = 0, result = "";
    for (let i2 = 0, len = replaceString.length; i2 < len; i2++) {
      const chCode = replaceString.charCodeAt(i2);
      if (chCode === 92) {
        i2++;
        if (i2 >= len) {
          break;
        }
        const nextChCode = replaceString.charCodeAt(i2);
        let replaceWithCharacter = null;
        switch (nextChCode) {
          case 92:
            replaceWithCharacter = "\\";
            break;
          case 110:
            replaceWithCharacter = "\n";
            break;
          case 116:
            replaceWithCharacter = "	";
            break;
        }
        if (replaceWithCharacter) {
          result += replaceString.substring(substrFrom, i2 - 1) + replaceWithCharacter;
          substrFrom = i2 + 1;
        }
      }
      if (chCode === 36) {
        i2++;
        if (i2 >= len) {
          break;
        }
        const nextChCode = replaceString.charCodeAt(i2);
        let replaceWithCharacter = null;
        switch (nextChCode) {
          case 48:
            replaceWithCharacter = "$&";
            this.b = true;
            break;
          case 96:
          case 39:
            this.b = true;
            break;
          default: {
            if (!this.g(
              nextChCode,
              49,
              57
              /* CharCode.Digit9 */
            )) {
              break;
            }
            if (i2 === replaceString.length - 1) {
              this.b = true;
              break;
            }
            let charCode = replaceString.charCodeAt(++i2);
            if (!this.g(
              charCode,
              48,
              57
              /* CharCode.Digit9 */
            )) {
              this.b = true;
              --i2;
              break;
            }
            if (i2 === replaceString.length - 1) {
              this.b = true;
              break;
            }
            charCode = replaceString.charCodeAt(++i2);
            if (!this.g(
              charCode,
              48,
              57
              /* CharCode.Digit9 */
            )) {
              this.b = true;
              --i2;
              break;
            }
            break;
          }
        }
        if (replaceWithCharacter) {
          result += replaceString.substring(substrFrom, i2 - 1) + replaceWithCharacter;
          substrFrom = i2 + 1;
        }
      }
    }
    if (substrFrom === 0) {
      return;
    }
    this.a = result + replaceString.substring(substrFrom);
  }
  g(value, from, to) {
    return from <= value && value <= to;
  }
};

// out-build/vs/workbench/contrib/search/browser/searchTreeModel/rangeDecorations.js
var $i6b_1;
var $i6b = class $i6b2 {
  static {
    $i6b_1 = this;
  }
  constructor(d) {
    this.d = d;
    this.a = null;
    this.b = null;
    this.c = new $2c();
  }
  removeHighlightRange() {
    if (this.b && this.a) {
      const decorationId = this.a;
      this.b.changeDecorations((accessor) => {
        accessor.removeDecoration(decorationId);
      });
    }
    this.a = null;
  }
  highlightRange(resource, range, ownerId2 = 0) {
    let model;
    if (URI.isUri(resource)) {
      model = this.d.getModel(resource);
    } else {
      model = resource;
    }
    if (model) {
      this.f(model, range);
    }
  }
  f(model, range) {
    this.removeHighlightRange();
    model.changeDecorations((accessor) => {
      this.a = accessor.addDecoration(range, $i6b_1.i);
    });
    this.g(model);
  }
  g(model) {
    if (this.b !== model) {
      this.h();
      this.b = model;
      this.c.add(this.b.onDidChangeDecorations((e) => {
        this.h();
        this.removeHighlightRange();
        this.b = null;
      }));
      this.c.add(this.b.onWillDispose(() => {
        this.h();
        this.removeHighlightRange();
        this.b = null;
      }));
    }
  }
  h() {
    this.c.clear();
  }
  dispose() {
    if (this.b) {
      this.removeHighlightRange();
      this.b = null;
    }
    this.c.dispose();
  }
  static {
    this.i = $WI.register({
      description: "search-range-highlight",
      stickiness: 1,
      className: "rangeHighlight",
      isWholeLine: true
    });
  }
};
$i6b = $i6b_1 = __decorate([
  __param(0, $sG)
], $i6b);

// out-build/vs/workbench/services/search/common/searchHelpers.js
function editorMatchToTextSearchResult(matches, model, previewOptions) {
  const firstLine3 = matches[0].range.startLineNumber;
  const lastLine = matches[matches.length - 1].range.endLineNumber;
  const lineTexts = [];
  for (let i2 = firstLine3; i2 <= lastLine; i2++) {
    lineTexts.push(model.getLineContent(i2));
  }
  return new $YN(lineTexts.join("\n") + "\n", matches.map((m) => new $9C(m.range.startLineNumber - 1, m.range.startColumn - 1, m.range.endLineNumber - 1, m.range.endColumn - 1)), previewOptions);
}
function $v7b(matches, model, previewOptions) {
  let previousEndLine = -1;
  const groupedMatches = [];
  let currentMatches = [];
  matches.forEach((match) => {
    if (match.range.startLineNumber !== previousEndLine) {
      currentMatches = [];
      groupedMatches.push(currentMatches);
    }
    currentMatches.push(match);
    previousEndLine = match.range.endLineNumber;
  });
  return groupedMatches.map((sameLineMatches) => {
    return editorMatchToTextSearchResult(sameLineMatches, model, previewOptions);
  });
}
function $w7b(matches, model, query) {
  const results = [];
  let prevLine = -1;
  for (let i2 = 0; i2 < matches.length; i2++) {
    const { start: matchStartLine, end: matchEndLine } = getMatchStartEnd(matches[i2]);
    if (typeof query.surroundingContext === "number" && query.surroundingContext > 0) {
      const beforeContextStartLine = Math.max(prevLine + 1, matchStartLine - query.surroundingContext);
      for (let b = beforeContextStartLine; b < matchStartLine; b++) {
        results.push({
          text: model.getLineContent(b + 1),
          lineNumber: b + 1
        });
      }
    }
    results.push(matches[i2]);
    const nextMatch = matches[i2 + 1];
    const nextMatchStartLine = nextMatch ? getMatchStartEnd(nextMatch).start : Number.MAX_VALUE;
    if (typeof query.surroundingContext === "number" && query.surroundingContext > 0) {
      const afterContextToLine = Math.min(nextMatchStartLine - 1, matchEndLine + query.surroundingContext, model.getLineCount() - 1);
      for (let a = matchEndLine + 1; a <= afterContextToLine; a++) {
        results.push({
          text: model.getLineContent(a + 1),
          lineNumber: a + 1
        });
      }
    }
    prevLine = matchEndLine;
  }
  return results;
}
function getMatchStartEnd(match) {
  const matchRanges = match.rangeLocations.map((e) => e.source);
  const matchStartLine = matchRanges[0].startLineNumber;
  const matchEndLine = matchRanges[matchRanges.length - 1].endLineNumber;
  return {
    start: matchStartLine,
    end: matchEndLine
  };
}

// out-build/vs/workbench/contrib/search/common/cellSearchModel.js
var $A7b = class extends $3c {
  constructor(_source, b, c) {
    super();
    this._source = _source;
    this.b = b;
    this.c = c;
    this.a = void 0;
  }
  f(buffer) {
    const lineCount = buffer.getLineCount();
    return new $9C(1, 1, lineCount, this.g(buffer, lineCount));
  }
  g(buffer, lineNumber) {
    if (lineNumber < 1 || lineNumber > buffer.getLineCount()) {
      throw new Error("Illegal value for lineNumber");
    }
    return buffer.getLineLength(lineNumber) + 1;
  }
  get inputTextBuffer() {
    if (!this.b) {
      const builder = new $rI();
      builder.acceptChunk(this._source);
      const bufferFactory = builder.finish(true);
      const { textBuffer, disposable } = bufferFactory.create(
        1
        /* DefaultEndOfLine.LF */
      );
      this.b = textBuffer;
      this.B(disposable);
    }
    return this.b;
  }
  get outputTextBuffers() {
    if (!this.a) {
      this.a = this.c.map((output) => {
        const builder = new $rI();
        builder.acceptChunk(output);
        const bufferFactory = builder.finish(true);
        const { textBuffer, disposable } = bufferFactory.create(
          1
          /* DefaultEndOfLine.LF */
        );
        this.B(disposable);
        return textBuffer;
      });
    }
    return this.a;
  }
  findInInputs(target) {
    const searchParams = new $fI(target, false, false, null);
    const searchData = searchParams.parseSearchRequest();
    if (!searchData) {
      return [];
    }
    const fullInputRange = this.f(this.inputTextBuffer);
    return this.inputTextBuffer.findMatchesLineByLine(fullInputRange, searchData, true, 5e3);
  }
  findInOutputs(target) {
    const searchParams = new $fI(target, false, false, null);
    const searchData = searchParams.parseSearchRequest();
    if (!searchData) {
      return [];
    }
    return this.outputTextBuffers.map((buffer) => {
      const matches = buffer.findMatchesLineByLine(this.f(buffer), searchData, true, 5e3);
      if (matches.length === 0) {
        return void 0;
      }
      return {
        textBuffer: buffer,
        matches
      };
    }).filter((item) => !!item);
  }
};

// out-build/vs/workbench/contrib/search/browser/searchTreeModel/match.js
function $x7b(rawMatch, fileMatch, isAiContributed) {
  const previewLines = rawMatch.previewText.split("\n");
  return rawMatch.rangeLocations.map((rangeLocation) => {
    const previewRange = rangeLocation.preview;
    return new $y7b(fileMatch, previewLines, previewRange, rangeLocation.source, isAiContributed);
  });
}
var $y7b = class _$y7b {
  static {
    this.b = 250;
  }
  constructor(i2, j, _fullPreviewRange, _documentRange, k = false) {
    this.i = i2;
    this.j = j;
    this.k = k;
    this.f = j[_fullPreviewRange.startLineNumber];
    const adjustedEndCol = _fullPreviewRange.startLineNumber === _fullPreviewRange.endLineNumber ? _fullPreviewRange.endColumn : this.f.length;
    this.g = new $1N(1, _fullPreviewRange.startColumn + 1, adjustedEndCol + 1);
    this.d = new $9C(_documentRange.startLineNumber + 1, _documentRange.startColumn + 1, _documentRange.endLineNumber + 1, _documentRange.endColumn + 1);
    this.h = _fullPreviewRange;
    this.c = $s6b + this.i.resource.toString() + ">" + this.d + this.getMatchString();
  }
  id() {
    return this.c;
  }
  parent() {
    return this.i;
  }
  text() {
    return this.f;
  }
  range() {
    return this.d;
  }
  preview() {
    const fullBefore = this.f.substring(0, this.g.startColumn - 1), before = $ig(fullBefore, 26, "\u2026");
    let inside = this.getMatchString(), after = this.f.substring(this.g.endColumn - 1);
    let charsRemaining = _$y7b.b - before.length;
    inside = inside.substr(0, charsRemaining);
    charsRemaining -= inside.length;
    after = after.substr(0, charsRemaining);
    return {
      before,
      fullBefore,
      inside,
      after
    };
  }
  get replaceString() {
    const searchModel = this.parent().parent().searchModel;
    if (!searchModel.replacePattern) {
      throw new Error("searchModel.replacePattern must be set before accessing replaceString");
    }
    const fullMatchText = this.fullMatchText();
    let replaceString = searchModel.replacePattern.getReplaceString(fullMatchText, searchModel.preserveCase);
    if (replaceString !== null) {
      return replaceString;
    }
    const fullMatchTextWithoutCR = fullMatchText.replace(/\r\n/g, "\n");
    if (fullMatchTextWithoutCR !== fullMatchText) {
      replaceString = searchModel.replacePattern.getReplaceString(fullMatchTextWithoutCR, searchModel.preserveCase);
      if (replaceString !== null) {
        return replaceString;
      }
    }
    const contextMatchTextWithSurroundingContent = this.fullMatchText(true);
    replaceString = searchModel.replacePattern.getReplaceString(contextMatchTextWithSurroundingContent, searchModel.preserveCase);
    if (replaceString !== null) {
      return replaceString;
    }
    const contextMatchTextWithoutCR = contextMatchTextWithSurroundingContent.replace(/\r\n/g, "\n");
    if (contextMatchTextWithoutCR !== contextMatchTextWithSurroundingContent) {
      replaceString = searchModel.replacePattern.getReplaceString(contextMatchTextWithoutCR, searchModel.preserveCase);
      if (replaceString !== null) {
        return replaceString;
      }
    }
    return searchModel.replacePattern.pattern;
  }
  fullMatchText(includeSurrounding = false) {
    let thisMatchPreviewLines;
    if (includeSurrounding) {
      thisMatchPreviewLines = this.j;
    } else {
      thisMatchPreviewLines = this.j.slice(this.h.startLineNumber, this.h.endLineNumber + 1);
      thisMatchPreviewLines[thisMatchPreviewLines.length - 1] = thisMatchPreviewLines[thisMatchPreviewLines.length - 1].slice(0, this.h.endColumn);
      thisMatchPreviewLines[0] = thisMatchPreviewLines[0].slice(this.h.startColumn);
    }
    return thisMatchPreviewLines.join("\n");
  }
  rangeInPreview() {
    return {
      ...this.h,
      startColumn: this.h.startColumn + 1,
      endColumn: this.h.endColumn + 1
    };
  }
  fullPreviewLines() {
    return this.j.slice(this.h.startLineNumber, this.h.endLineNumber + 1);
  }
  getMatchString() {
    return this.f.substring(this.g.startColumn - 1, this.g.endColumn - 1);
  }
  get isReadonly() {
    return this.k;
  }
};
__decorate([
  $0t
], $y7b.prototype, "preview", null);

// out-build/vs/workbench/contrib/search/browser/searchTreeModel/fileMatch.js
var $z7b_1;
var $z7b = class $z7b2 extends $3c {
  static {
    $z7b_1 = this;
  }
  static {
    this.b = $WI.register({
      description: "search-current-find-match",
      stickiness: 1,
      zIndex: 13,
      className: "currentFindMatch",
      overviewRuler: {
        color: $7l($_p),
        position: OverviewRulerLane3.Center
      },
      minimap: {
        color: $7l($eq),
        position: 1
        /* MinimapPosition.Inline */
      }
    });
  }
  static {
    this.c = $WI.register({
      description: "search-find-match",
      stickiness: 1,
      className: "findMatch",
      overviewRuler: {
        color: $7l($_p),
        position: OverviewRulerLane3.Center
      },
      minimap: {
        color: $7l($eq),
        position: 1
        /* MinimapPosition.Inline */
      }
    });
  }
  static f(selected) {
    return selected ? $z7b_1.b : $z7b_1.c;
  }
  get context() {
    return new Map(this.F);
  }
  constructor(G, H, I, J, L, M, N, O, labelService) {
    super();
    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.h = this.B(new $ze());
    this.onChange = this.h.event;
    this.j = this.B(new $ze());
    this.onDispose = this.j.event;
    this.s = null;
    this.t = null;
    this.y = null;
    this.D = [];
    this.F = /* @__PURE__ */ new Map();
    this.W = Promise.resolve();
    this.n = this.L.resource;
    this.u = /* @__PURE__ */ new Map();
    this.w = /* @__PURE__ */ new Set();
    this.C = new $8h(this.R.bind(this), 250);
    this.z = new $sf(() => labelService.getUriBasenameLabel(this.resource));
  }
  get closestRoot() {
    return this.M;
  }
  hasReadonlyMatches() {
    return this.matches().some((m) => m.isReadonly);
  }
  createMatches() {
    const model = this.N.getModel(this.n);
    if (model) {
      this.bindModel(model);
      this.R();
    } else {
      if (this.L.results) {
        this.L.results.filter($UN).forEach((rawMatch) => {
          $x7b(rawMatch, this, false).forEach((m) => this.add(m));
        });
      }
    }
  }
  bindModel(model) {
    this.s = model;
    this.t = this.s.onDidChangeContent(() => {
      this.C.schedule();
    });
    this.s.onWillDispose(() => this.P());
    this.updateHighlights();
  }
  P() {
    this.R();
    this.Q();
  }
  Q() {
    if (this.s) {
      this.C.cancel();
      this.s.changeDecorations((accessor) => {
        this.D = accessor.deltaDecorations(this.D, []);
      });
      this.s = null;
      this.t.dispose();
    }
  }
  R() {
    if (!this.s) {
      return;
    }
    this.u = /* @__PURE__ */ new Map();
    const wordSeparators2 = this.G.isWordMatch && this.G.wordSeparators ? this.G.wordSeparators : null;
    const matches = this.s.findMatches(this.G.pattern, this.s.getFullModelRange(), !!this.G.isRegExp, !!this.G.isCaseSensitive, wordSeparators2, false, this.I ?? $SN);
    this.U(matches, true, this.s, false);
  }
  async S(lineNumber, modelChange) {
    if (!this.s) {
      return;
    }
    const range = {
      startLineNumber: lineNumber,
      startColumn: this.s.getLineMinColumn(lineNumber),
      endLineNumber: lineNumber,
      endColumn: this.s.getLineMaxColumn(lineNumber)
    };
    const oldMatches = Array.from(this.u.values()).filter((match) => match.range().startLineNumber === lineNumber);
    oldMatches.forEach((match) => this.u.delete(match.id()));
    const wordSeparators2 = this.G.isWordMatch && this.G.wordSeparators ? this.G.wordSeparators : null;
    const matches = this.s.findMatches(this.G.pattern, range, !!this.G.isRegExp, !!this.G.isCaseSensitive, wordSeparators2, false, this.I ?? $SN);
    this.U(matches, modelChange, this.s, false);
  }
  U(matches, modelChange, model, isAiContributed) {
    const textSearchResults = $v7b(matches, model, this.H);
    textSearchResults.forEach((textSearchResult) => {
      $x7b(textSearchResult, this, isAiContributed).forEach((match) => {
        if (!this.w.has(match.id())) {
          this.add(match);
          if (this.isMatchSelected(match)) {
            this.y = match;
          }
        }
      });
    });
    this.addContext($w7b(textSearchResults, model, this.parent().parent().query));
    this.h.fire({ forceUpdateModel: modelChange });
    this.updateHighlights();
  }
  updateHighlights() {
    if (!this.s) {
      return;
    }
    this.s.changeDecorations((accessor) => {
      const newDecorations = this.parent().showHighlights ? this.matches().map((match) => ({
        range: match.range(),
        options: $z7b_1.f(this.isMatchSelected(match))
      })) : [];
      this.D = accessor.deltaDecorations(this.D, newDecorations);
    });
  }
  id() {
    return $r6b + this.resource.toString();
  }
  parent() {
    return this.J;
  }
  get hasChildren() {
    return this.u.size > 0;
  }
  matches() {
    return [...this.u.values()];
  }
  textMatches() {
    return Array.from(this.u.values());
  }
  remove(matches) {
    if (!Array.isArray(matches)) {
      matches = [matches];
    }
    for (const match of matches) {
      this.X(match);
      this.w.add(match.id());
    }
    this.h.fire({ didRemove: true });
  }
  async replace(toReplace) {
    return this.W = this.W.finally(async () => {
      await this.O.replace(toReplace);
      await this.S(toReplace.range().startLineNumber, false);
    });
  }
  setSelectedMatch(match) {
    if (match) {
      if (!this.u.has(match.id())) {
        return;
      }
      if (this.isMatchSelected(match)) {
        return;
      }
    }
    this.y = match;
    this.updateHighlights();
  }
  getSelectedMatch() {
    return this.y;
  }
  isMatchSelected(match) {
    return !!this.y && this.y.id() === match.id();
  }
  count() {
    return this.matches().length;
  }
  get resource() {
    return this.n;
  }
  name() {
    return this.z.value;
  }
  addContext(results) {
    if (!results) {
      return;
    }
    const contexts = results.filter((result) => !$UN(result));
    return contexts.forEach((context) => this.F.set(context.lineNumber, context.text));
  }
  add(match, trigger) {
    this.u.set(match.id(), match);
    if (trigger) {
      this.h.fire({ forceUpdateModel: true });
    }
  }
  X(match) {
    this.u.delete(match.id());
    if (this.isMatchSelected(match)) {
      this.setSelectedMatch(null);
      this.g?.clearCurrentFindMatchDecoration();
    } else {
      this.updateHighlights();
    }
  }
  async resolveFileStat(fileService) {
    this.r = await fileService.stat(this.resource).catch(() => void 0);
  }
  get fileStat() {
    return this.r;
  }
  set fileStat(stat) {
    this.r = stat;
  }
  dispose() {
    this.setSelectedMatch(null);
    this.Q();
    this.j.fire();
    super.dispose();
  }
  hasOnlyReadOnlyMatches() {
    return this.matches().every((match) => match.isReadonly);
  }
};
$z7b = $z7b_1 = __decorate([
  __param(6, $sG),
  __param(7, $u7b),
  __param(8, $ZI)
], $z7b);

// out-build/vs/workbench/contrib/search/browser/notebookSearch/notebookSearchModel.js
var $B7b = class extends $y7b {
  constructor(n, _fullPreviewLines, _fullPreviewRange, _documentRange, webviewIndex) {
    super(n.parent, _fullPreviewLines, _fullPreviewRange, _documentRange, false);
    this.n = n;
    this.c = $s6b + this.i.resource.toString() + ">" + this.n.cellIndex + (webviewIndex ? "_" + webviewIndex : "") + "_" + this.o() + this.d + this.getMatchString();
    this.l = webviewIndex;
  }
  parent() {
    return this.n.parent;
  }
  get cellParent() {
    return this.n;
  }
  o() {
    return this.isWebviewMatch() ? "webview" : "content";
  }
  isWebviewMatch() {
    return this.l !== void 0;
  }
  get isReadonly() {
    return super.isReadonly || !this.n.hasCellViewModel() || this.isWebviewMatch();
  }
  get cellIndex() {
    return this.n.cellIndex;
  }
  get webviewIndex() {
    return this.l;
  }
  get cell() {
    return this.n.cell;
  }
};
var $C7b = class {
  constructor(f, g, h3) {
    this.f = f;
    this.g = g;
    this.h = h3;
    this.b = /* @__PURE__ */ new Map();
    this.c = /* @__PURE__ */ new Map();
    this.d = /* @__PURE__ */ new Map();
  }
  hasCellViewModel() {
    return !(this.g instanceof $A7b);
  }
  get context() {
    return new Map(this.d);
  }
  matches() {
    return [...this.b.values(), ...this.c.values()];
  }
  get contentMatches() {
    return Array.from(this.b.values());
  }
  get webviewMatches() {
    return Array.from(this.c.values());
  }
  remove(matches) {
    if (!Array.isArray(matches)) {
      matches = [matches];
    }
    for (const match of matches) {
      this.b.delete(match.id());
      this.c.delete(match.id());
    }
  }
  clearAllMatches() {
    this.b.clear();
    this.c.clear();
  }
  addContentMatches(textSearchMatches) {
    const contentMatches = $E7b(textSearchMatches, this);
    contentMatches.forEach((match) => {
      this.b.set(match.id(), match);
    });
    this.addContext(textSearchMatches);
  }
  addContext(textSearchMatches) {
    if (!this.cell) {
      return;
    }
    this.cell.resolveTextModel().then((textModel) => {
      const textResultsWithContext = $w7b(textSearchMatches, textModel, this.parent.parent().query);
      const contexts = textResultsWithContext.filter((result) => !$UN(result));
      contexts.map((context) => ({ ...context, lineNumber: context.lineNumber + 1 })).forEach((context) => {
        this.d.set(context.lineNumber, context.text);
      });
    });
  }
  addWebviewMatches(textSearchMatches) {
    const webviewMatches = $E7b(textSearchMatches, this);
    webviewMatches.forEach((match) => {
      this.c.set(match.id(), match);
    });
  }
  setCellModel(cell) {
    this.g = cell;
  }
  get parent() {
    return this.f;
  }
  get id() {
    return this.g?.id ?? `${$hS}${this.cellIndex}`;
  }
  get cellIndex() {
    return this.h;
  }
  get cell() {
    return this.g;
  }
};
var $D7b = class $D7b2 extends $z7b {
  constructor(_query, _previewOptions, _maxResults, _parent, rawMatch, _closestRoot, bb, modelService, replaceService, labelService, cb) {
    super(_query, _previewOptions, _maxResults, _parent, rawMatch, _closestRoot, modelService, replaceService, labelService);
    this.bb = bb;
    this.cb = cb;
    this.Y = null;
    this.Z = null;
    this.db = /* @__PURE__ */ new Map();
    this.$ = new $8h(this.updateMatchesForEditorWidget.bind(this), 250);
  }
  get cellContext() {
    const cellContext = /* @__PURE__ */ new Map();
    this.db.forEach((cellMatch) => {
      cellContext.set(cellMatch.id, cellMatch.context);
    });
    return cellContext;
  }
  getCellMatch(cellID) {
    return this.db.get(cellID);
  }
  addCellMatch(rawCell) {
    const cellMatch = new $C7b(this, $K6b(rawCell) ? rawCell.cell : void 0, rawCell.index);
    this.db.set(cellMatch.id, cellMatch);
    this.addWebviewMatchesToCell(cellMatch.id, rawCell.webviewResults);
    this.addContentMatchesToCell(cellMatch.id, rawCell.contentResults);
  }
  addWebviewMatchesToCell(cellID, webviewMatches) {
    const cellMatch = this.getCellMatch(cellID);
    if (cellMatch !== void 0) {
      cellMatch.addWebviewMatches(webviewMatches);
    }
  }
  addContentMatchesToCell(cellID, contentMatches) {
    const cellMatch = this.getCellMatch(cellID);
    if (cellMatch !== void 0) {
      cellMatch.addContentMatches(contentMatches);
    }
  }
  eb(match, outputOffset) {
    if (!this.Y || !match.cell) {
      return;
    }
    if (match.webviewIndex !== void 0) {
      const index = this.Y.getCellIndex(match.cell);
      if (index !== void 0) {
        this.Y.revealCellOffsetInCenter(match.cell, outputOffset ?? 0);
      }
    } else {
      match.cell.updateEditState(match.cell.getEditState(), "focusNotebookCell");
      this.Y.setCellEditorSelection(match.cell, match.range());
      this.Y.revealRangeInCenterIfOutsideViewportAsync(match.cell, match.range());
    }
  }
  bindNotebookEditorWidget(widget) {
    if (this.Y === widget) {
      return;
    }
    this.Y = widget;
    this.Z = this.Y.textModel?.onDidChangeContent((e) => {
      if (!e.rawEvents.some((event) => event.kind === NotebookCellsChangeType.ChangeCellContent || event.kind === NotebookCellsChangeType.ModelChange)) {
        return;
      }
      this.$.schedule();
    }) ?? null;
    this.fb();
  }
  unbindNotebookEditorWidget(widget) {
    if (widget && this.Y !== widget) {
      return;
    }
    if (this.Y) {
      this.$.cancel();
      this.Z?.dispose();
    }
    this.gb();
    this.Y = null;
  }
  updateNotebookHighlights() {
    if (this.parent().showHighlights) {
      this.fb();
      this.ib(Array.from(this.db.values()));
    } else {
      this.gb();
    }
  }
  fb() {
    if (!this.Y) {
      return;
    }
    this.g?.stopWebviewFind();
    this.g?.dispose();
    this.g = new $NIb(this.Y, this.bb);
    if (this.y instanceof $B7b) {
      this.jb(this.y);
    }
  }
  gb() {
    if (this.g) {
      this.g?.stopWebviewFind();
      this.g?.dispose();
      this.g = void 0;
    }
  }
  hb(matches, modelChange) {
    if (!this.Y) {
      return;
    }
    const oldCellMatches = new Map(this.db);
    if (this.Y.getId() !== this.ab) {
      this.db.clear();
      this.ab = this.Y.getId();
    }
    matches.forEach((match) => {
      let existingCell = this.db.get(match.cell.id);
      if (this.Y && !existingCell) {
        const index = this.Y.getCellIndex(match.cell);
        const existingRawCell = oldCellMatches.get(`${$hS}${index}`);
        if (existingRawCell) {
          existingRawCell.setCellModel(match.cell);
          existingRawCell.clearAllMatches();
          existingCell = existingRawCell;
        }
      }
      existingCell?.clearAllMatches();
      const cell = existingCell ?? new $C7b(this, match.cell, match.index);
      cell.addContentMatches($L6b(match.contentMatches, match.cell));
      cell.addWebviewMatches($M6b(match.webviewMatches));
      this.db.set(cell.id, cell);
    });
    this.g?.setAllFindMatchesDecorations(matches);
    if (this.y instanceof $B7b) {
      this.jb(this.y);
    }
    this.h.fire({ forceUpdateModel: modelChange });
  }
  ib(cells) {
    if (!this.g) {
      return;
    }
    const cellFindMatch = $Mb(cells.map((cell) => {
      const webviewMatches = $Mb(cell.webviewMatches.map((match) => {
        if (!match.webviewIndex) {
          return void 0;
        }
        return {
          index: match.webviewIndex
        };
      }));
      if (!cell.cell) {
        return void 0;
      }
      const findMatches = cell.contentMatches.map((match) => {
        return new $eG(match.range(), [match.text()]);
      });
      return new $OIb(cell.cell, cell.cellIndex, findMatches, webviewMatches);
    }));
    try {
      this.g.setAllFindMatchesDecorations(cellFindMatch);
    } catch (e) {
    }
  }
  async updateMatchesForEditorWidget() {
    if (!this.Y) {
      return;
    }
    this.u = /* @__PURE__ */ new Map();
    const wordSeparators2 = this.G.isWordMatch && this.G.wordSeparators ? this.G.wordSeparators : null;
    const allMatches = await this.Y.find(this.G.pattern, {
      regex: this.G.isRegExp,
      wholeWord: this.G.isWordMatch,
      caseSensitive: this.G.isCaseSensitive,
      wordSeparators: wordSeparators2 ?? void 0,
      includeMarkupInput: this.G.notebookInfo?.isInNotebookMarkdownInput,
      includeMarkupPreview: this.G.notebookInfo?.isInNotebookMarkdownPreview,
      includeCodeInput: this.G.notebookInfo?.isInNotebookCellInput,
      includeOutput: this.G.notebookInfo?.isInNotebookCellOutput
    }, CancellationToken.None, false, true, this.bb);
    this.hb(allMatches, true);
  }
  async showMatch(match) {
    const offset = await this.jb(match);
    this.setSelectedMatch(match);
    this.eb(match, offset);
  }
  async jb(match) {
    if (!this.g || !match.cell) {
      return null;
    }
    if (match.webviewIndex === void 0) {
      return this.g.highlightCurrentFindMatchDecorationInCell(match.cell, match.range());
    } else {
      return this.g.highlightCurrentFindMatchDecorationInWebview(match.cell, match.webviewIndex);
    }
  }
  matches() {
    const matches = Array.from(this.db.values()).flatMap((e) => e.matches());
    return [...super.matches(), ...matches];
  }
  X(match) {
    if (match instanceof $B7b) {
      match.cellParent.remove(match);
      if (match.cellParent.matches().length === 0) {
        this.db.delete(match.cellParent.id);
      }
      if (this.isMatchSelected(match)) {
        this.setSelectedMatch(null);
        this.g?.clearCurrentFindMatchDecoration();
      } else {
        this.updateHighlights();
      }
      this.ib(this.cellMatches());
    } else {
      super.X(match);
    }
  }
  cellMatches() {
    return Array.from(this.db.values());
  }
  createMatches() {
    const model = this.N.getModel(this.n);
    if (model) {
      this.bindModel(model);
      this.R();
    } else {
      const notebookEditorWidgetBorrow = this.cb.retrieveExistingWidgetFromURI(this.resource);
      if (notebookEditorWidgetBorrow?.value) {
        this.bindNotebookEditorWidget(notebookEditorWidgetBorrow.value);
      }
      if (this.L.results) {
        this.L.results.filter($UN).forEach((rawMatch) => {
          $x7b(rawMatch, this, false).forEach((m) => this.add(m));
        });
      }
      if ($J6b(this.L) || $gS(this.L)) {
        this.L.cellResults?.forEach((cell) => this.addCellMatch(cell));
        this.ib(this.cellMatches());
        this.h.fire({ forceUpdateModel: true });
      }
      this.addContext(this.L.results);
    }
  }
  get hasChildren() {
    return super.hasChildren || this.db.size > 0;
  }
  setSelectedMatch(match) {
    if (match) {
      if (!this.isMatchSelected(match) && $O6b(match)) {
        this.y = match;
        return;
      }
      if (!this.u.has(match.id())) {
        return;
      }
      if (this.isMatchSelected(match)) {
        return;
      }
    }
    this.y = match;
    this.updateHighlights();
  }
  dispose() {
    this.unbindNotebookEditorWidget();
    super.dispose();
  }
};
$D7b = __decorate([
  __param(7, $sG),
  __param(8, $u7b),
  __param(9, $ZI),
  __param(10, $yMb)
], $D7b);
function $E7b(textSearchMatches, cell) {
  const notebookMatches = [];
  textSearchMatches.forEach((textSearchMatch) => {
    const previewLines = textSearchMatch.previewText.split("\n");
    textSearchMatch.rangeLocations.map((rangeLocation) => {
      const previewRange = rangeLocation.preview;
      const match = new $B7b(cell, previewLines, previewRange, rangeLocation.source, textSearchMatch.webviewIndex);
      notebookMatches.push(match);
    });
  });
  return notebookMatches;
}

// out-build/vs/workbench/contrib/search/browser/searchTreeModel/folderMatch.js
var $F7b_1;
var $F7b = $F7b_1 = class $F7b2 extends $3c {
  constructor(u, _id, w, y, z, C, D, F, G, labelService, 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 $ze());
    this.onChange = this.a.event;
    this.c = this.B(new $ze());
    this.onDispose = this.c.event;
    this.r = false;
    this.f = new $Ec();
    this.g = new $Ec();
    this.h = $Wk.forUris((key2) => this.H.extUri.ignorePathCasing(key2));
    this.j = new $Ec();
    this.n = new $Ec();
    this.s = new $sf(() => this.resource ? labelService.getUriBasenameLabel(this.resource) : "");
    this.t = $q6b + _id;
  }
  get searchModel() {
    return this.C.searchModel;
  }
  get showHighlights() {
    return this.z.showHighlights;
  }
  get closestRoot() {
    return this.D;
  }
  set replacingAll(b) {
    this.r = b;
  }
  id() {
    return this.t;
  }
  get resource() {
    return this.u;
  }
  index() {
    return this.w;
  }
  name() {
    return this.s.value;
  }
  parent() {
    return this.z;
  }
  isAIContributed() {
    return false;
  }
  get hasChildren() {
    return this.f.size > 0 || this.g.size > 0;
  }
  bindModel(model) {
    const fileMatch = this.f.get(model.uri);
    if (fileMatch) {
      fileMatch.bindModel(model);
    } else {
      const folderMatch = this.getFolderMatch(model.uri);
      const match = folderMatch?.getDownstreamFileMatch(model.uri);
      match?.bindModel(model);
    }
  }
  createIntermediateFolderMatch(resource, id2, index, query, baseWorkspaceFolder) {
    const folderMatch = this.B(this.G.createInstance($G7b, resource, id2, index, query, this, this.C, baseWorkspaceFolder));
    this.configureIntermediateMatch(folderMatch);
    this.doAddFolder(folderMatch);
    return folderMatch;
  }
  configureIntermediateMatch(folderMatch) {
    const disposable = folderMatch.onChange((event) => this.onFolderChange(folderMatch, event));
    this.B(folderMatch.onDispose(() => disposable.dispose()));
  }
  clear(clearingAll = false) {
    const changed = this.allDownstreamFileMatches();
    this.disposeMatches();
    this.a.fire({ elements: changed, removed: true, added: false, clearingAll });
  }
  remove(matches) {
    if (!Array.isArray(matches)) {
      matches = [matches];
    }
    const allMatches = $E6b(matches);
    this.doRemoveFile(allMatches);
  }
  async replace(match) {
    return this.F.replace([match]).then(() => {
      this.doRemoveFile([match], true, true, true);
    });
  }
  replaceAll() {
    const matches = this.matches();
    return this.N(matches);
  }
  matches() {
    return [...this.fileMatchesIterator(), ...this.folderMatchesIterator()];
  }
  fileMatchesIterator() {
    return this.f.values();
  }
  folderMatchesIterator() {
    return this.g.values();
  }
  isEmpty() {
    return this.I() + this.J() === 0;
  }
  getDownstreamFileMatch(uri) {
    const directChildFileMatch = this.f.get(uri);
    if (directChildFileMatch) {
      return directChildFileMatch;
    }
    const folderMatch = this.getFolderMatch(uri);
    const match = folderMatch?.getDownstreamFileMatch(uri);
    if (match) {
      return match;
    }
    return null;
  }
  allDownstreamFileMatches() {
    let recursiveChildren = [];
    const iterator = this.folderMatchesIterator();
    for (const elem of iterator) {
      recursiveChildren = recursiveChildren.concat(elem.allDownstreamFileMatches());
    }
    return [...this.fileMatchesIterator(), ...recursiveChildren];
  }
  I() {
    return this.f.size;
  }
  J() {
    return this.g.size;
  }
  count() {
    return this.I() + this.J();
  }
  recursiveFileCount() {
    return this.allDownstreamFileMatches().length;
  }
  recursiveMatchCount() {
    return this.allDownstreamFileMatches().reduce((prev, match) => prev + match.count(), 0);
  }
  get query() {
    return this.y;
  }
  doAddFile(fileMatch) {
    this.f.set(fileMatch.resource, fileMatch);
    if (this.j.has(fileMatch.resource)) {
      this.j.delete(fileMatch.resource);
    }
  }
  hasOnlyReadOnlyMatches() {
    return Array.from(this.f.values()).every((fm) => fm.hasOnlyReadOnlyMatches());
  }
  L(parent, child) {
    return this.H.extUri.isEqualOrParent(child, parent) && !this.H.extUri.isEqual(child, parent);
  }
  M(folderMatch) {
    let matchItem = this;
    while (matchItem instanceof $F7b_1) {
      if (matchItem.id() === folderMatch.id()) {
        return true;
      }
      matchItem = matchItem.parent();
    }
    return false;
  }
  getFolderMatch(resource) {
    const folderMatch = this.h.findSubstr(resource);
    return folderMatch;
  }
  doAddFolder(folderMatch) {
    if (this.resource && !this.L(this.resource, folderMatch.resource)) {
      throw Error(`${folderMatch.resource} does not belong as a child of ${this.resource}`);
    } else if (this.M(folderMatch)) {
      throw Error(`${folderMatch.resource} is a parent of ${this.resource}`);
    }
    this.g.set(folderMatch.resource, folderMatch);
    this.h.set(folderMatch.resource, folderMatch);
    if (this.n.has(folderMatch.resource)) {
      this.n.delete(folderMatch.resource);
    }
  }
  async N(matches) {
    const allMatches = $E6b(matches);
    await this.F.replace(allMatches);
    this.doRemoveFile(allMatches, true, true, true);
  }
  onFileChange(fileMatch, removed = false) {
    let added = false;
    if (!this.f.has(fileMatch.resource)) {
      this.doAddFile(fileMatch);
      added = true;
    }
    if (fileMatch.count() === 0) {
      this.doRemoveFile([fileMatch], false, false);
      added = false;
      removed = true;
    }
    if (!this.r) {
      this.a.fire({ elements: [fileMatch], added, removed });
    }
  }
  onFolderChange(folderMatch, event) {
    if (!this.g.has(folderMatch.resource)) {
      this.doAddFolder(folderMatch);
    }
    if (folderMatch.isEmpty()) {
      this.g.delete(folderMatch.resource);
      folderMatch.dispose();
    }
    this.a.fire(event);
  }
  doRemoveFile(fileMatches, dispose = true, trigger = true, keepReadonly = false) {
    const removed = [];
    for (const match of fileMatches) {
      if (this.f.get(match.resource)) {
        if (keepReadonly && match.hasReadonlyMatches()) {
          continue;
        }
        this.f.delete(match.resource);
        if (dispose) {
          match.dispose();
        } else {
          this.j.set(match.resource, match);
        }
        removed.push(match);
      } else {
        const folder = this.getFolderMatch(match.resource);
        if (folder) {
          folder.doRemoveFile([match], dispose, trigger);
        } else {
          throw Error(`FileMatch ${match.resource} is not located within FolderMatch ${this.resource}`);
        }
      }
    }
    if (trigger) {
      this.a.fire({ elements: removed, removed: true });
    }
  }
  async bindNotebookEditorWidget(editor, resource) {
    const fileMatch = this.f.get(resource);
    if ($N6b(fileMatch)) {
      if (fileMatch) {
        fileMatch.bindNotebookEditorWidget(editor);
        await fileMatch.updateMatchesForEditorWidget();
      } else {
        const folderMatches = this.folderMatchesIterator();
        for (const elem of folderMatches) {
          await elem.bindNotebookEditorWidget(editor, resource);
        }
      }
    }
  }
  addFileMatch(raw, silent, searchInstanceID) {
    const added = [];
    const updated = [];
    raw.forEach((rawFileMatch) => {
      const existingFileMatch = this.getDownstreamFileMatch(rawFileMatch.resource);
      if (existingFileMatch) {
        if (rawFileMatch.results) {
          rawFileMatch.results.filter($UN).forEach((m) => {
            $x7b(m, existingFileMatch, false).forEach((m2) => existingFileMatch.add(m2));
          });
        }
        if ($J6b(rawFileMatch) || $gS(rawFileMatch)) {
          rawFileMatch.cellResults?.forEach((rawCellMatch) => {
            if ($N6b(existingFileMatch)) {
              const existingCellMatch = existingFileMatch.getCellMatch($I6b(rawCellMatch));
              if (existingCellMatch) {
                existingCellMatch.addContentMatches(rawCellMatch.contentResults);
                existingCellMatch.addWebviewMatches(rawCellMatch.webviewResults);
              } else {
                existingFileMatch.addCellMatch(rawCellMatch);
              }
            }
          });
        }
        updated.push(existingFileMatch);
        if (rawFileMatch.results && rawFileMatch.results.length > 0) {
          existingFileMatch.addContext(rawFileMatch.results);
        }
      } else {
        if ($A6b(this) || $B6b(this)) {
          const fileMatch = this.createAndConfigureFileMatch(rawFileMatch, searchInstanceID);
          added.push(fileMatch);
        }
      }
    });
    const elements = [...added, ...updated];
    if (!silent && elements.length) {
      this.a.fire({ elements, added: !!added.length });
    }
  }
  unbindNotebookEditorWidget(editor, resource) {
    const fileMatch = this.f.get(resource);
    if ($N6b(fileMatch)) {
      if (fileMatch) {
        fileMatch.unbindNotebookEditorWidget(editor);
      } else {
        const folderMatches = this.folderMatchesIterator();
        for (const elem of folderMatches) {
          elem.unbindNotebookEditorWidget(editor, resource);
        }
      }
    }
  }
  disposeMatches() {
    [...this.f.values()].forEach((fileMatch) => fileMatch.dispose());
    [...this.g.values()].forEach((folderMatch) => folderMatch.disposeMatches());
    [...this.j.values()].forEach((fileMatch) => fileMatch.dispose());
    [...this.n.values()].forEach((folderMatch) => folderMatch.disposeMatches());
    this.f.clear();
    this.g.clear();
    this.j.clear();
    this.n.clear();
  }
  dispose() {
    this.disposeMatches();
    this.c.fire();
    super.dispose();
  }
};
$F7b = $F7b_1 = __decorate([
  __param(7, $u7b),
  __param(8, $Pk),
  __param(9, $ZI),
  __param(10, $vl)
], $F7b);
var $G7b = class $G7b2 extends $F7b {
  constructor(_resource, _id, _index, _query, _parent, _searchResult, _closestRoot, replaceService, instantiationService, labelService, uriIdentityService) {
    super(_resource, _id, _index, _query, _parent, _searchResult, _closestRoot, replaceService, instantiationService, labelService, uriIdentityService);
    this.O = new $sf(() => this.H.extUri.removeTrailingPathSeparator(this.H.extUri.normalizePath(this.resource)));
  }
  get resource() {
    return this.u;
  }
  get normalizedResource() {
    return this.O.value;
  }
};
$G7b = __decorate([
  __param(7, $u7b),
  __param(8, $Pk),
  __param(9, $ZI),
  __param(10, $vl)
], $G7b);
var $H7b = class $H7b2 extends $G7b {
  constructor(_resource, _id, _index, _query, _parent, replaceService, instantiationService, labelService, uriIdentityService) {
    super(_resource, _id, _index, _query, _parent, _parent.parent(), null, replaceService, instantiationService, labelService, uriIdentityService);
  }
  P(uri) {
    return this.H.extUri.normalizePath(this.H.extUri.dirname(uri));
  }
  Q(uri1, ur2) {
    return this.H.extUri.isEqual(uri1, ur2);
  }
  R(query, previewOptions, maxResults, parent, rawFileMatch, closestRoot, searchInstanceID) {
    const fileMatch = this.G.createInstance($D7b, query, previewOptions, maxResults, parent, rawFileMatch, closestRoot, searchInstanceID);
    fileMatch.createMatches();
    parent.doAddFile(fileMatch);
    const disposable = fileMatch.onChange(({ didRemove }) => parent.onFileChange(fileMatch, didRemove));
    this.B(fileMatch.onDispose(() => disposable.dispose()));
    return fileMatch;
  }
  createAndConfigureFileMatch(rawFileMatch, searchInstanceID) {
    if (!this.L(this.resource, rawFileMatch.resource)) {
      throw Error(`${rawFileMatch.resource} is not a descendant of ${this.resource}`);
    }
    const fileMatchParentParts = [];
    let uri = this.P(rawFileMatch.resource);
    while (!this.Q(this.normalizedResource, uri)) {
      fileMatchParentParts.unshift(uri);
      const prevUri = uri;
      uri = this.H.extUri.removeTrailingPathSeparator(this.P(uri));
      if (this.Q(prevUri, uri)) {
        throw Error(`${rawFileMatch.resource} is not correctly configured as a child of ${this.normalizedResource}`);
      }
    }
    const root = this.closestRoot ?? this;
    let parent = this;
    for (let i2 = 0; i2 < fileMatchParentParts.length; i2++) {
      let folderMatch = parent.getFolderMatch(fileMatchParentParts[i2]);
      if (!folderMatch) {
        folderMatch = parent.createIntermediateFolderMatch(fileMatchParentParts[i2], fileMatchParentParts[i2].toString(), -1, this.y, root);
      }
      parent = folderMatch;
    }
    const contentPatternToUse = typeof this.y.contentPattern === "string" ? { pattern: this.y.contentPattern } : this.y.contentPattern;
    return this.R(contentPatternToUse, this.y.previewOptions, this.y.maxResults, parent, rawFileMatch, root, searchInstanceID);
  }
};
$H7b = __decorate([
  __param(5, $u7b),
  __param(6, $Pk),
  __param(7, $ZI),
  __param(8, $vl)
], $H7b);
var $I7b = class $I7b2 extends $F7b {
  constructor(_id, _index, _query, _parent, replaceService, instantiationService, labelService, uriIdentityService) {
    super(null, _id, _index, _query, _parent, _parent.parent(), null, replaceService, instantiationService, labelService, uriIdentityService);
  }
  createAndConfigureFileMatch(rawFileMatch, searchInstanceID) {
    const contentPatternToUse = typeof this.y.contentPattern === "string" ? { pattern: this.y.contentPattern } : this.y.contentPattern;
    const fileMatch = this.B(this.G.createInstance($D7b, contentPatternToUse, this.y.previewOptions, this.y.maxResults, this, rawFileMatch, null, searchInstanceID));
    fileMatch.createMatches();
    this.doAddFile(fileMatch);
    const disposable = fileMatch.onChange(({ didRemove }) => this.onFileChange(fileMatch, didRemove));
    this.B(fileMatch.onDispose(() => disposable.dispose()));
    return fileMatch;
  }
};
$I7b = __decorate([
  __param(4, $u7b),
  __param(5, $Pk),
  __param(6, $ZI),
  __param(7, $vl)
], $I7b);

// out-build/vs/workbench/contrib/search/browser/searchTreeModel/textSearchHeading.js
var $J7b = class $J7b2 extends $3c {
  constructor(s, t, u, w) {
    super();
    this.s = s;
    this.t = t;
    this.u = u;
    this.w = w;
    this.a = this.B(new $ze());
    this.onChange = this.a.event;
    this.b = false;
    this.c = false;
    this.f = null;
    this.h = () => Promise.resolve();
    this.j = [];
    this.n = null;
    this.r = $Wk.forUris((key2) => this.w.extUri.ignorePathCasing(key2));
    this.resource = null;
    this.hidden = false;
    this.g = this.u.createInstance($i6b);
    this.B(this.onChange((e) => {
      if (e.removed) {
        this.b = !this.isEmpty();
      }
    }));
  }
  hide() {
    this.hidden = true;
    this.clear();
  }
  parent() {
    return this.t;
  }
  get hasChildren() {
    return this.j.length > 0;
  }
  get isDirty() {
    return this.b;
  }
  getFolderMatch(resource) {
    const folderMatch = this.r.findSubstr(resource);
    if (!folderMatch && this.s && this.n) {
      return this.n;
    }
    return folderMatch;
  }
  add(allRaw, searchInstanceID, silent = false) {
    const { byFolder, other } = this.groupFilesByFolder(allRaw);
    byFolder.forEach((raw) => {
      if (!raw.length) {
        return;
      }
      const folderMatch = this.getFolderMatch(raw[0].resource);
      folderMatch?.addFileMatch(raw, silent, searchInstanceID);
    });
    if (!this.isAIContributed) {
      this.n?.addFileMatch(other, silent, searchInstanceID);
    }
    this.h();
  }
  remove(matches, ai = false) {
    if (!Array.isArray(matches)) {
      matches = [matches];
    }
    matches.forEach((m) => {
      if ($y6b(m)) {
        m.clear();
      }
    });
    const fileMatches = matches.filter((m) => $C6b(m));
    const { byFolder, other } = this.groupFilesByFolder(fileMatches);
    byFolder.forEach((matches2) => {
      if (!matches2.length) {
        return;
      }
      this.getFolderMatch(matches2[0].resource)?.remove(matches2);
    });
    if (other.length) {
      this.getFolderMatch(other[0].resource)?.remove(other);
    }
  }
  groupFilesByFolder(fileMatches) {
    const rawPerFolder = new $Ec();
    const otherFileMatches = [];
    this.j.forEach((fm) => rawPerFolder.set(fm.resource, []));
    fileMatches.forEach((rawFileMatch) => {
      const folderMatch = this.getFolderMatch(rawFileMatch.resource);
      if (!folderMatch) {
        return;
      }
      const resource = folderMatch.resource;
      if (resource) {
        rawPerFolder.get(resource).push(rawFileMatch);
      } else {
        otherFileMatches.push(rawFileMatch);
      }
    });
    return {
      byFolder: rawPerFolder,
      other: otherFileMatches
    };
  }
  isEmpty() {
    return this.folderMatches().every((folderMatch) => folderMatch.isEmpty());
  }
  findFolderSubstr(resource) {
    return this.r.findSubstr(resource);
  }
  y() {
    const oldFolderMatches = this.folderMatches();
    this.h = async () => {
      oldFolderMatches.forEach((match) => match.clear());
      oldFolderMatches.forEach((match) => match.dispose());
      this.b = false;
    };
    this.cachedSearchComplete = void 0;
    this.g.removeHighlightRange();
    this.r = $Wk.forUris((key2) => this.w.extUri.ignorePathCasing(key2));
  }
  folderMatches() {
    return this.n && this.s ? [
      ...this.j,
      this.n
    ] : this.j;
  }
  z() {
    this.folderMatches().forEach((folderMatch) => folderMatch.dispose());
    this.j = [];
    this.r = $Wk.forUris((key2) => this.w.extUri.ignorePathCasing(key2));
    this.g.removeHighlightRange();
  }
  matches() {
    const matches = [];
    this.folderMatches().forEach((folderMatch) => {
      matches.push(folderMatch.allDownstreamFileMatches());
    });
    return [].concat(...matches);
  }
  get showHighlights() {
    return this.c;
  }
  toggleHighlights(value) {
    if (this.c === value) {
      return;
    }
    this.c = value;
    let selectedMatch = null;
    this.matches().forEach((fileMatch) => {
      fileMatch.updateHighlights();
      if ($N6b(fileMatch)) {
        fileMatch.updateNotebookHighlights();
      }
      if (!selectedMatch) {
        selectedMatch = fileMatch.getSelectedMatch();
      }
    });
    if (this.c && selectedMatch) {
      this.g.highlightRange(selectedMatch.parent().resource, selectedMatch.range());
    } else {
      this.g.removeHighlightRange();
    }
  }
  get rangeHighlightDecorations() {
    return this.g;
  }
  fileCount() {
    return this.folderMatches().reduce((prev, match) => prev + match.recursiveFileCount(), 0);
  }
  count() {
    return this.matches().reduce((prev, match) => prev + match.count(), 0);
  }
  clear() {
    this.cachedSearchComplete = void 0;
    this.folderMatches().forEach((folderMatch) => folderMatch.clear(true));
    this.z();
    this.j = [];
    this.n = null;
  }
  async dispose() {
    this.g.dispose();
    this.z();
    super.dispose();
    await this.h();
  }
};
$J7b = __decorate([
  __param(2, $Pk),
  __param(3, $vl)
], $J7b);
var $K7b = class $K7b2 extends $J7b {
  constructor(parent, instantiationService, uriIdentityService, C) {
    super(true, parent, instantiationService, uriIdentityService);
    this.C = C;
  }
  id() {
    return $p6b + $k6b;
  }
  get isAIContributed() {
    return false;
  }
  replace(match) {
    return this.getFolderMatch(match.resource)?.replace(match) ?? Promise.resolve();
  }
  name() {
    return "Text";
  }
  replaceAll(progress) {
    this.D = true;
    const promise = this.C.replace(this.matches(), progress);
    return promise.then(() => {
      this.D = false;
      this.clear();
    }, () => {
      this.D = false;
    });
  }
  set D(running) {
    this.folderMatches().forEach((folderMatch) => {
      folderMatch.replacingAll = running;
    });
  }
  get query() {
    return this.f;
  }
  set query(query) {
    this.y();
    if (!query) {
      return;
    }
    this.j = (query && query.folderQueries || []).map((fq) => fq.folder).map((resource, index) => this.F(resource, resource.toString(), index, query));
    this.j.forEach((fm) => this.r.set(fm.resource, fm));
    this.n = this.F(null, "otherFiles", this.j.length + 1, query);
    this.f = query;
  }
  F(resource, id2, index, query) {
    let folderMatch;
    if (resource) {
      folderMatch = this.B(this.G(resource, id2, index, query));
    } else {
      folderMatch = this.B(this.H(id2, index, query));
    }
    const disposable = folderMatch.onChange((event) => this.a.fire(event));
    this.B(folderMatch.onDispose(() => disposable.dispose()));
    return folderMatch;
  }
  G(resource, id2, index, query) {
    return this.u.createInstance($H7b, resource, id2, index, query, this);
  }
  H(id2, index, query) {
    return this.B(this.u.createInstance($I7b, id2, index, query, this));
  }
};
$K7b = __decorate([
  __param(1, $Pk),
  __param(2, $vl),
  __param(3, $u7b)
], $K7b);

// out-build/vs/workbench/contrib/search/browser/AISearch/aiSearchModel.js
var $L7b = class $L7b2 extends $J7b {
  constructor(parent, instantiationService, uriIdentityService) {
    super(false, parent, instantiationService, uriIdentityService);
  }
  name() {
    return "AI";
  }
  id() {
    return $p6b + $l6b;
  }
  get isAIContributed() {
    return true;
  }
  get query() {
    return this.f;
  }
  set query(query) {
    this.y();
    if (!query) {
      return;
    }
    this.j = (query && query.folderQueries || []).map((fq) => fq.folder).map((resource, index) => this.C(resource, resource.toString(), index, query));
    this.j.forEach((fm) => this.r.set(fm.resource, fm));
    this.f = query;
  }
  C(resource, id2, index, query) {
    const folderMatch = this.B(this.D(resource, id2, index, query));
    const disposable = folderMatch.onChange((event) => this.a.fire(event));
    this.B(folderMatch.onDispose(() => disposable.dispose()));
    return folderMatch;
  }
  D(resource, id2, index, query) {
    return this.u.createInstance($M7b, resource, id2, index, query, this);
  }
};
$L7b = __decorate([
  __param(1, $Pk),
  __param(2, $vl)
], $L7b);
var $M7b = class $M7b2 extends $3c {
  constructor(j, _id, n, r2, s, t, labelService) {
    super();
    this.j = j;
    this.n = n;
    this.r = r2;
    this.s = s;
    this.t = t;
    this.a = this.B(new $ze());
    this.onChange = this.a.event;
    this.b = this.B(new $ze());
    this.onDispose = this.b.event;
    this.u = 0;
    this.replacingAll = false;
    this.h = /* @__PURE__ */ new Map();
    this.c = $q6b + _id;
    this.f = new $sf(() => this.resource ? labelService.getUriBasenameLabel(this.resource) : "");
    this.g = /* @__PURE__ */ new Map();
  }
  get resource() {
    return this.j;
  }
  id() {
    return this.c;
  }
  index() {
    return this.n;
  }
  name() {
    return this.f.value;
  }
  count() {
    return this.h.size;
  }
  doAddFile(fileMatch) {
    this.h.set(fileMatch.id(), fileMatch);
  }
  createAndConfigureFileMatch(rawFileMatch, searchInstanceID) {
    const fileMatch = this.t.createInstance(AIFileMatch, this.r.contentPattern, this.r.previewOptions, this.r.maxResults, this, rawFileMatch, this, rawFileMatch.resource.toString() + "_" + Date.now().toString(), this.u++);
    fileMatch.createMatches();
    this.doAddFile(fileMatch);
    const disposable = fileMatch.onChange(({ didRemove }) => this.w(fileMatch, didRemove));
    this.B(fileMatch.onDispose(() => disposable.dispose()));
    return fileMatch;
  }
  isAIContributed() {
    return true;
  }
  w(fileMatch, removed = false) {
    let added = false;
    if (!this.h.has(fileMatch.id())) {
      this.doAddFile(fileMatch);
      added = true;
    }
    if (fileMatch.count() === 0) {
      this.doRemoveFile([fileMatch], false, false);
      added = false;
      removed = true;
    }
    this.a.fire({ elements: [fileMatch], added, removed });
  }
  get hasChildren() {
    return this.h.size > 0;
  }
  parent() {
    return this.s;
  }
  matches() {
    return [...this.h.values()];
  }
  allDownstreamFileMatches() {
    return [...this.h.values()];
  }
  remove(matches) {
    if (!Array.isArray(matches)) {
      matches = [matches];
    }
    const allMatches = $E6b(matches);
    this.doRemoveFile(allMatches);
  }
  addFileMatch(raw, silent, searchInstanceID) {
    const added = [];
    const updated = [];
    raw.forEach((rawFileMatch) => {
      const fileMatch = this.createAndConfigureFileMatch(rawFileMatch, searchInstanceID);
      added.push(fileMatch);
    });
    const elements = [...added, ...updated];
    if (!silent && elements.length) {
      this.a.fire({ elements, added: !!added.length });
    }
  }
  isEmpty() {
    return this.recursiveFileCount() === 0;
  }
  clear(clearingAll) {
    const changed = this.allDownstreamFileMatches();
    this.y();
    this.a.fire({ elements: changed, removed: true, added: false, clearingAll });
  }
  get showHighlights() {
    return this.s.showHighlights;
  }
  get searchModel() {
    return this._searchResult.searchModel;
  }
  get _searchResult() {
    return this.s.parent();
  }
  get query() {
    return this.r;
  }
  getDownstreamFileMatch(uri) {
    for (const fileMatch of this.h.values()) {
      if (fileMatch.resource.toString() === uri.toString()) {
        return fileMatch;
      }
    }
    return null;
  }
  replaceAll() {
    throw new Error("Cannot replace in AI search");
  }
  recursiveFileCount() {
    return this.h.size;
  }
  doRemoveFile(fileMatches, dispose = true, trigger = true, keepReadonly = false) {
    const removed = [];
    for (const match of fileMatches) {
      if (this.h.get(match.id())) {
        if (keepReadonly && match.hasReadonlyMatches()) {
          continue;
        }
        this.h.delete(match.id());
        if (dispose) {
          match.dispose();
        } else {
          this.g.set(match.id(), match);
        }
        removed.push(match);
      }
    }
    if (trigger) {
      this.a.fire({ elements: removed, removed: true });
    }
  }
  replace(match) {
    throw new Error("Cannot replace in AI search");
  }
  bindModel(model) {
  }
  unbindNotebookEditorWidget(editor, resource) {
  }
  bindNotebookEditorWidget(editor, resource) {
    return Promise.resolve();
  }
  hasOnlyReadOnlyMatches() {
    return Array.from(this.h.values()).every((fm) => fm.hasOnlyReadOnlyMatches());
  }
  fileMatchesIterator() {
    return this.h.values();
  }
  folderMatchesIterator() {
    return [].values();
  }
  recursiveMatchCount() {
    return this.h.size;
  }
  y() {
    [...this.h.values()].forEach((fileMatch) => fileMatch.dispose());
    [...this.g.values()].forEach((fileMatch) => fileMatch.dispose());
  }
  dispose() {
    this.y();
    this.b.fire();
    super.dispose();
  }
};
$M7b = __decorate([
  __param(5, $Pk),
  __param(6, $ZI)
], $M7b);
var AIFileMatch = class AIFileMatch2 extends $z7b {
  constructor(_query, _previewOptions, _maxResults, _parent, rawMatch, _closestRoot, Y, rank, modelService, replaceService, labelService) {
    super({ pattern: _query }, _previewOptions, _maxResults, _parent, rawMatch, _closestRoot, modelService, replaceService, labelService);
    this.Y = Y;
    this.rank = rank;
  }
  id() {
    return $r6b + this.Y;
  }
  getFullRange() {
    let earliestStart = void 0;
    let latestEnd = void 0;
    for (const match of this.matches()) {
      const matchStart = match.range().getStartPosition();
      const matchEnd = match.range().getEndPosition();
      if (earliestStart === void 0) {
        earliestStart = matchStart;
      } else if (matchStart.isBefore(earliestStart)) {
        earliestStart = matchStart;
      }
      if (latestEnd === void 0) {
        latestEnd = matchEnd;
      } else if (!matchEnd.isBefore(latestEnd)) {
        latestEnd = matchEnd;
      }
    }
    if (earliestStart === void 0 || latestEnd === void 0) {
      return void 0;
    }
    return new $9C(earliestStart.lineNumber, earliestStart.column, latestEnd.lineNumber, latestEnd.column);
  }
  Z() {
    const range = this.getFullRange();
    if (!range) {
      return void 0;
    }
    return range.startLineNumber + ":" + range.startColumn + "-" + range.endLineNumber + ":" + range.endColumn;
  }
  name() {
    const range = this.Z();
    return super.name() + range ? " " + range : "";
  }
  createMatches() {
    if (this.L.results) {
      this.L.results.filter($UN).forEach((rawMatch) => {
        $x7b(rawMatch, this, true).forEach((m) => this.add(m));
      });
    }
  }
};
AIFileMatch = __decorate([
  __param(8, $sG),
  __param(9, $u7b),
  __param(10, $ZI)
], AIFileMatch);

// out-build/vs/workbench/contrib/search/browser/searchTreeModel/searchResult.js
var $N7b = class $N7b2 extends $3c {
  constructor(searchModel, j, m, n) {
    super();
    this.searchModel = searchModel;
    this.j = j;
    this.m = m;
    this.n = n;
    this.a = this.B(new $Ce({
      merge: $t6b
    }));
    this.onChange = this.a.event;
    this.f = this.B(this.j.createInstance($K7b, this));
    this.g = this.B(this.j.createInstance($L7b, this));
    this.B(this.f.onChange((e) => this.a.fire(e)));
    this.B(this.g.onChange((e) => this.a.fire(e)));
    this.m.getModels().forEach((model) => this.s(model));
    this.B(this.m.onModelAdded((model) => this.s(model)));
    this.B(this.n.onDidAddNotebookEditor((widget) => {
      if (widget instanceof $aMb) {
        this.r(widget);
      }
    }));
    this.h = $o6b + Date.now().toString();
  }
  id() {
    return this.h;
  }
  get plainTextSearchResult() {
    return this.f;
  }
  get aiTextSearchResult() {
    return this.g;
  }
  get children() {
    return this.textSearchResults;
  }
  get hasChildren() {
    return true;
  }
  get textSearchResults() {
    return [this.f, this.g];
  }
  async batchReplace(elementsToReplace) {
    try {
      this.a.pause();
      await Promise.all(elementsToReplace.map(async (elem) => {
        const parent = elem.parent();
        if (($y6b(parent) || $C6b(parent)) && $j6b(parent, elementsToReplace)) {
          return;
        }
        if ($C6b(elem)) {
          await elem.parent().replace(elem);
        } else if ($D6b(elem)) {
          await elem.parent().replace(elem);
        } else if ($y6b(elem)) {
          await elem.replaceAll();
        }
      }));
    } finally {
      this.a.resume();
    }
  }
  batchRemove(elementsToRemove) {
    const removedElems = [];
    try {
      this.a.pause();
      elementsToRemove.forEach((currentElement) => {
        if (!$j6b(currentElement, removedElems)) {
          if ($w6b(currentElement)) {
            currentElement.hide();
          } else if (!$y6b(currentElement) || $z6b(currentElement)) {
            if ($C6b(currentElement)) {
              currentElement.parent().remove(currentElement);
            } else if ($D6b(currentElement)) {
              currentElement.parent().remove(currentElement);
            } else if ($z6b(currentElement)) {
              currentElement.parent().remove(currentElement);
            }
            removedElems.push(currentElement);
          }
        }
      });
    } finally {
      this.a.resume();
    }
  }
  get isDirty() {
    return this.g.isDirty || this.f.isDirty;
  }
  get query() {
    return this.f.query;
  }
  set query(query) {
    this.f.query = query;
  }
  setAIQueryUsingTextQuery(query) {
    if (!query) {
      query = this.query;
    }
    this.aiTextSearchResult.query = aiTextQueryFromTextQuery(query);
  }
  r(widget) {
    this.b?.dispose();
    this.b = widget.onWillChangeModel((model) => {
      if (model) {
        this.u(widget, model?.uri);
      }
    });
    this.c?.dispose();
    this.c = widget.onDidAttachViewModel(() => {
      if (widget.hasModel()) {
        this.t(widget, widget.textModel.uri);
      }
    });
  }
  folderMatches(ai = false) {
    if (ai) {
      return this.g.folderMatches();
    }
    return this.f.folderMatches();
  }
  s(model) {
    const folderMatch = this.f.findFolderSubstr(model.uri);
    folderMatch?.bindModel(model);
  }
  async t(editor, resource) {
    const folderMatch = this.f.findFolderSubstr(resource);
    await folderMatch?.bindNotebookEditorWidget(editor, resource);
  }
  u(editor, resource) {
    const folderMatch = this.f.findFolderSubstr(resource);
    folderMatch?.unbindNotebookEditorWidget(editor, resource);
  }
  add(allRaw, searchInstanceID, ai, silent = false) {
    this.f.hidden = false;
    this.g.hidden = false;
    if (ai) {
      this.g.add(allRaw, searchInstanceID, silent);
    } else {
      this.f.add(allRaw, searchInstanceID, silent);
    }
  }
  clear() {
    this.f.clear();
    this.g.clear();
  }
  remove(matches, ai = false) {
    if (ai) {
      this.g.remove(matches, ai);
    }
    this.f.remove(matches, ai);
  }
  replace(match) {
    return this.f.replace(match);
  }
  matches(ai) {
    if (ai === void 0) {
      return this.f.matches().concat(this.g.matches());
    } else if (ai === true) {
      return this.g.matches();
    }
    return this.f.matches();
  }
  isEmpty() {
    return this.f.isEmpty() && this.g.isEmpty();
  }
  fileCount() {
    return this.f.fileCount() + this.g.fileCount();
  }
  count() {
    return this.f.count() + this.g.count();
  }
  setCachedSearchComplete(cachedSearchComplete, ai) {
    if (ai) {
      this.g.cachedSearchComplete = cachedSearchComplete;
    } else {
      this.f.cachedSearchComplete = cachedSearchComplete;
    }
  }
  getCachedSearchComplete(ai) {
    if (ai) {
      return this.g.cachedSearchComplete;
    }
    return this.f.cachedSearchComplete;
  }
  toggleHighlights(value, ai = false) {
    if (ai) {
      this.g.toggleHighlights(value);
    } else {
      this.f.toggleHighlights(value);
    }
  }
  getRangeHighlightDecorations(ai = false) {
    if (ai) {
      return this.g.rangeHighlightDecorations;
    }
    return this.f.rangeHighlightDecorations;
  }
  replaceAll(progress) {
    return this.f.replaceAll(progress);
  }
  async dispose() {
    this.g?.dispose();
    this.f?.dispose();
    this.b?.dispose();
    this.c?.dispose();
    super.dispose();
  }
};
$N7b = __decorate([
  __param(1, $Pk),
  __param(2, $sG),
  __param(3, $yMb)
], $N7b);
function aiTextQueryFromTextQuery(query) {
  return query === null ? null : {
    ...query,
    contentPattern: query.contentPattern.pattern,
    type: 3
    /* QueryType.aiText */
  };
}

// out-build/vs/workbench/contrib/search/browser/searchTreeModel/searchModel.js
var $P7b = class $P7b2 extends $3c {
  constructor(D, F, G, H, I, J) {
    super();
    this.D = D;
    this.F = F;
    this.G = G;
    this.H = H;
    this.I = I;
    this.J = J;
    this.b = null;
    this.c = false;
    this.f = null;
    this.g = null;
    this.h = false;
    this.j = Promise.resolve();
    this.m = [];
    this.n = [];
    this.r = this.B(new $ze());
    this.onReplaceTermChanged = this.r.event;
    this.s = this.B(new $Ce({
      merge: $t6b
    }));
    this.onSearchResultChanged = this.s.event;
    this.t = null;
    this.u = null;
    this.w = false;
    this.y = false;
    this.location = SearchModelLocation.PANEL;
    this.a = this.H.createInstance($N7b, this);
    this.B(this.a.onChange((e) => this.s.fire(e)));
    this.z = new $sf(async () => this.D.getAIName());
    this.C = $n6b + Date.now().toString();
  }
  id() {
    return this.C;
  }
  async getAITextResultProviderName() {
    const result = await this.z.value;
    if (!result) {
      throw Error("Fetching AI name when no provider present.");
    }
    return result;
  }
  isReplaceActive() {
    return this.c;
  }
  set replaceActive(replaceActive) {
    this.c = replaceActive;
  }
  get replacePattern() {
    return this.g;
  }
  get replaceString() {
    return this.f || "";
  }
  set preserveCase(value) {
    this.h = value;
  }
  get preserveCase() {
    return this.h;
  }
  set replaceString(replaceString) {
    this.f = replaceString;
    if (this.b) {
      this.g = new $h6b(replaceString, this.b.contentPattern);
    }
    this.r.fire();
  }
  get searchResult() {
    return this.a;
  }
  async addAIResults(onProgress) {
    if (this.hasAIResults) {
      throw Error("AI results already exist");
    } else {
      if (this.b) {
        return this.aiSearch({
          ...this.b,
          contentPattern: this.b.contentPattern.pattern,
          type: 3
          /* QueryType.aiText */
        }, onProgress);
      } else {
        throw Error("No search query");
      }
    }
  }
  aiSearch(query, onProgress) {
    const searchInstanceID = Date.now().toString();
    const tokenSource = new $ad();
    this.u = tokenSource;
    const start = Date.now();
    const asyncAIResults = this.D.aiTextSearch(query, tokenSource.token, async (p) => {
      this.O(p, searchInstanceID, false, true);
      onProgress?.(p);
    }).finally(() => {
      tokenSource.dispose(true);
    }).then((value) => {
      this.M(value, Date.now() - start, searchInstanceID, true);
      return value;
    }, (e) => {
      this.N(e, Date.now() - start, true);
      throw e;
    });
    return asyncAIResults;
  }
  L(query, progressEmitter, searchQuery, searchInstanceID, onProgress, callerToken) {
    const asyncGenerateOnProgress = async (p) => {
      progressEmitter.fire();
      this.O(p, searchInstanceID, false, false);
      onProgress?.(p);
    };
    const syncGenerateOnProgress = (p) => {
      progressEmitter.fire();
      this.O(p, searchInstanceID, true);
      onProgress?.(p);
    };
    const tokenSource = this.t = new $ad(callerToken);
    const notebookResult = this.J.notebookSearch(query, tokenSource.token, searchInstanceID, asyncGenerateOnProgress);
    const textResult = this.D.textSearchSplitSyncAsync(searchQuery, tokenSource.token, asyncGenerateOnProgress, notebookResult.openFilesToScan, notebookResult.allScannedFiles);
    const syncResults = textResult.syncResults.results;
    syncResults.forEach((p) => {
      if (p) {
        syncGenerateOnProgress(p);
      }
    });
    const getAsyncResults = async () => {
      const searchStart = Date.now();
      const allClosedEditorResults = await textResult.asyncResults;
      const resolvedNotebookResults = await notebookResult.completeData;
      const searchLength = Date.now() - searchStart;
      const resolvedResult = {
        results: [...allClosedEditorResults.results, ...resolvedNotebookResults.results],
        messages: [...allClosedEditorResults.messages, ...resolvedNotebookResults.messages],
        limitHit: allClosedEditorResults.limitHit || resolvedNotebookResults.limitHit,
        exit: allClosedEditorResults.exit,
        stats: allClosedEditorResults.stats
      };
      this.I.trace(`whole search time | ${searchLength}ms`);
      return resolvedResult;
    };
    return {
      asyncResults: getAsyncResults().finally(() => tokenSource.dispose(true)),
      syncResults
    };
  }
  get hasAIResults() {
    return !!this.searchResult.getCachedSearchComplete(true) || !!this.u && !this.u.token.isCancellationRequested;
  }
  get hasPlainResults() {
    return !!this.searchResult.getCachedSearchComplete(false) || !!this.t && !this.t.token.isCancellationRequested;
  }
  search(query, onProgress, callerToken) {
    this.cancelSearch(true);
    this.b = query;
    if (!this.P.searchOnType) {
      this.searchResult.clear();
    }
    const searchInstanceID = Date.now().toString();
    this.a.query = this.b;
    const progressEmitter = this.B(new $ze());
    this.g = new $h6b(this.replaceString, this.b.contentPattern);
    this.j = new Promise((resolve) => setTimeout(resolve, this.P.searchOnType ? 150 : 0));
    const req = this.L(query, progressEmitter, this.b, searchInstanceID, onProgress, callerToken);
    const asyncResults = req.asyncResults;
    const syncResults = req.syncResults;
    if (onProgress) {
      syncResults.forEach((p) => {
        if (p) {
          onProgress(p);
        }
      });
    }
    const start = Date.now();
    let event;
    const progressEmitterPromise = new Promise((resolve) => {
      event = Event2.once(progressEmitter.event)(resolve);
      return event;
    });
    Promise.race([asyncResults, progressEmitterPromise]).finally(() => {
      event?.dispose();
      this.F.publicLog("searchResultsFirstRender", { duration: Date.now() - start });
    });
    try {
      return {
        asyncResults: asyncResults.then((value) => {
          this.M(value, Date.now() - start, searchInstanceID, false);
          return value;
        }, (e) => {
          this.N(e, Date.now() - start, false);
          throw e;
        }),
        syncResults
      };
    } finally {
      this.F.publicLog("searchResultsFinished", { duration: Date.now() - start });
    }
  }
  M(completed, duration, searchInstanceID, ai) {
    if (!this.b) {
      throw new Error("onSearchCompleted must be called after a search is started");
    }
    if (ai) {
      this.a.add(this.n, searchInstanceID, true);
      this.n.length = 0;
    } else {
      this.a.add(this.m, searchInstanceID, false);
      this.m.length = 0;
    }
    this.searchResult.setCachedSearchComplete(completed, ai);
    const options3 = Object.assign({}, this.b.contentPattern);
    delete options3.pattern;
    const stats = completed && completed.stats;
    const fileSchemeOnly = this.b.folderQueries.every((fq) => fq.folder.scheme === Schemas.file);
    const otherSchemeOnly = this.b.folderQueries.every((fq) => fq.folder.scheme !== Schemas.file);
    const scheme = fileSchemeOnly ? Schemas.file : otherSchemeOnly ? "other" : "mixed";
    this.F.publicLog("searchResultsShown", {
      count: this.a.count(),
      fileCount: this.a.fileCount(),
      options: options3,
      duration,
      type: stats && stats.type,
      scheme,
      searchOnTypeEnabled: this.P.searchOnType
    });
    return completed;
  }
  N(e, duration, ai) {
    if ($kb(e)) {
      this.M((ai ? this.y : this.w) ? { exit: 1, results: [], messages: [] } : void 0, duration, "", ai);
      if (ai) {
        this.y = false;
      } else {
        this.w = false;
      }
    }
  }
  O(p, searchInstanceID, sync = true, ai = false) {
    const targetQueue = ai ? this.n : this.m;
    if (p.resource) {
      targetQueue.push(p);
      if (sync) {
        if (targetQueue.length) {
          this.a.add(targetQueue, searchInstanceID, false, true);
          targetQueue.length = 0;
        }
      } else {
        this.j.then(() => {
          if (targetQueue.length) {
            this.a.add(targetQueue, searchInstanceID, ai, true);
            targetQueue.length = 0;
          }
        });
      }
    }
  }
  get P() {
    return this.G.getValue("search");
  }
  cancelSearch(cancelledForNewSearch = false) {
    if (this.t) {
      this.w = cancelledForNewSearch;
      this.t.cancel();
      return true;
    }
    return false;
  }
  cancelAISearch(cancelledForNewSearch = false) {
    if (this.u) {
      this.y = cancelledForNewSearch;
      this.u.cancel();
      return true;
    }
    return false;
  }
  dispose() {
    this.cancelSearch();
    this.cancelAISearch();
    this.searchResult.dispose();
    super.dispose();
  }
};
$P7b = __decorate([
  __param(0, $TN),
  __param(1, $zv),
  __param(2, $kl),
  __param(3, $Pk),
  __param(4, $wn),
  __param(5, $t7b)
], $P7b);
var $Q7b = class $Q7b2 {
  constructor(b) {
    this.b = b;
    this.a = null;
  }
  get searchModel() {
    if (!this.a) {
      this.a = this.b.createInstance($P7b);
    }
    return this.a;
  }
  set searchModel(searchModel) {
    this.a?.dispose();
    this.a = searchModel;
  }
};
$Q7b = __decorate([
  __param(0, $Pk)
], $Q7b);

// out-build/vs/workbench/contrib/search/browser/searchActionsCopy.js
$hJ(class CopyMatchCommandAction extends $gJ {
  constructor() {
    super({
      id: "search.action.copyMatch",
      title: localize2(9636, "Copy"),
      category: $S6b,
      keybinding: {
        weight: 200,
        when: $eRb.FileMatchOrMatchFocusKey,
        primary: 2048 | 33
      },
      menu: [{
        id: $bJ.SearchContext,
        when: $eRb.FileMatchOrMatchFocusKey,
        group: "search_2",
        order: 1
      }]
    });
  }
  async run(accessor, match) {
    await copyMatchCommand(accessor, match);
  }
});
$hJ(class CopyPathCommandAction extends $gJ {
  constructor() {
    super({
      id: "search.action.copyPath",
      title: localize2(9637, "Copy Path"),
      category: $S6b,
      keybinding: {
        weight: 200,
        when: $eRb.FileMatchOrFolderMatchWithResourceFocusKey,
        primary: 2048 | 512 | 33,
        win: {
          primary: 1024 | 512 | 33
          /* KeyCode.KeyC */
        }
      },
      menu: [{
        id: $bJ.SearchContext,
        when: $eRb.FileMatchOrFolderMatchWithResourceFocusKey,
        group: "search_2",
        order: 2
      }]
    });
  }
  async run(accessor, fileMatch) {
    await copyPathCommand2(accessor, fileMatch);
  }
});
$hJ(class CopyAllCommandAction extends $gJ {
  constructor() {
    super({
      id: "search.action.copyAll",
      title: localize2(9638, "Copy All"),
      category: $S6b,
      menu: [{
        id: $bJ.SearchContext,
        when: $eRb.HasSearchResults,
        group: "search_2",
        order: 3
      }]
    });
  }
  async run(accessor) {
    await copyAllCommand(accessor);
  }
});
var $dac = $l ? "\r\n" : "\n";
async function copyPathCommand2(accessor, fileMatch) {
  if (!fileMatch) {
    const selection = getSelectedRow(accessor);
    if (!$C6b(selection) || $z6b(selection)) {
      return;
    }
    fileMatch = selection;
  }
  const clipboardService = accessor.get($30);
  const labelService = accessor.get($ZI);
  const text2 = labelService.getUriLabel(fileMatch.resource, { noPrefix: true });
  await clipboardService.writeText(text2);
}
async function copyMatchCommand(accessor, match) {
  if (!match) {
    const selection = getSelectedRow(accessor);
    if (!selection) {
      return;
    }
    match = selection;
  }
  const clipboardService = accessor.get($30);
  const labelService = accessor.get($ZI);
  let text2;
  if ($D6b(match)) {
    text2 = matchToString(match);
  } else if ($C6b(match)) {
    text2 = fileMatchToString(match, labelService).text;
  } else if ($y6b(match)) {
    text2 = folderMatchToString(match, labelService).text;
  }
  if (text2) {
    await clipboardService.writeText(text2);
  }
}
async function copyAllCommand(accessor) {
  const viewsService = accessor.get($uob);
  const clipboardService = accessor.get($30);
  const labelService = accessor.get($ZI);
  const searchView = $V6b(viewsService);
  if (searchView) {
    const root = searchView.searchResult;
    const text2 = allFolderMatchesToString(root.folderMatches(), labelService);
    await clipboardService.writeText(text2);
  }
}
function matchToString(match, indent = 0) {
  const getFirstLinePrefix = () => `${match.range().startLineNumber},${match.range().startColumn}`;
  const getOtherLinePrefix = (i2) => match.range().startLineNumber + i2 + "";
  const fullMatchLines = match.fullPreviewLines();
  const largestPrefixSize = fullMatchLines.reduce((largest, _, i2) => {
    const thisSize = i2 === 0 ? getFirstLinePrefix().length : getOtherLinePrefix(i2).length;
    return Math.max(thisSize, largest);
  }, 0);
  const formattedLines = fullMatchLines.map((line, i2) => {
    const prefix = i2 === 0 ? getFirstLinePrefix() : getOtherLinePrefix(i2);
    const paddingStr = " ".repeat(largestPrefixSize - prefix.length);
    const indentStr = " ".repeat(indent);
    return `${indentStr}${prefix}: ${paddingStr}${line}`;
  });
  return formattedLines.join("\n");
}
function fileFolderMatchToString(match, labelService) {
  if ($C6b(match)) {
    return fileMatchToString(match, labelService);
  } else {
    return folderMatchToString(match, labelService);
  }
}
function fileMatchToString(fileMatch, labelService) {
  const matchTextRows = fileMatch.matches().sort($Q6b).map((match) => matchToString(match, 2));
  const uriString = labelService.getUriLabel(fileMatch.resource, { noPrefix: true });
  return {
    text: `${uriString}${$dac}${matchTextRows.join($dac)}`,
    count: matchTextRows.length
  };
}
function folderMatchToString(folderMatch, labelService) {
  const results = [];
  let numMatches = 0;
  const matches = folderMatch.matches().sort($Q6b);
  matches.forEach((match) => {
    const result = fileFolderMatchToString(match, labelService);
    numMatches += result.count;
    results.push(result.text);
  });
  return {
    text: results.join($dac + $dac),
    count: numMatches
  };
}
function allFolderMatchesToString(folderMatches, labelService) {
  const folderResults = [];
  folderMatches = folderMatches.sort($Q6b);
  for (let i2 = 0; i2 < folderMatches.length; i2++) {
    const folderResult = folderMatchToString(folderMatches[i2], labelService);
    if (folderResult.count) {
      folderResults.push(folderResult.text);
    }
  }
  return folderResults.join($dac + $dac);
}
function getSelectedRow(accessor) {
  const viewsService = accessor.get($uob);
  const searchView = $V6b(viewsService);
  return searchView?.getControl().getSelection()[0];
}

// out-build/vs/workbench/contrib/search/browser/searchActionsTopBar.js
$hJ(class ClearSearchHistoryCommandAction extends $gJ {
  constructor() {
    super({
      id: "search.action.clearHistory",
      title: localize2(9674, "Clear Search History"),
      category: $S6b,
      f1: true
    });
  }
  async run(accessor) {
    clearHistoryCommand(accessor);
  }
});
$hJ(class CancelSearchAction extends $gJ {
  constructor() {
    super({
      id: "search.action.cancel",
      title: localize2(9675, "Cancel Search"),
      icon: $k7b,
      category: $S6b,
      f1: true,
      precondition: $jO.isEqualTo(SearchUIState.Idle).negate(),
      keybinding: {
        weight: 200,
        when: $7m.and($eRb.SearchViewVisibleKey, $Leb),
        primary: 9
      },
      menu: [{
        id: $bJ.ViewTitle,
        group: "navigation",
        order: 0,
        when: $7m.and($7m.equals("view", $PN), $jO.isEqualTo(SearchUIState.SlowSearch))
      }]
    });
  }
  run(accessor) {
    return cancelSearch(accessor);
  }
});
$hJ(class RefreshAction extends $gJ {
  constructor() {
    super({
      id: "search.action.refreshSearchResults",
      title: localize2(9676, "Refresh"),
      icon: $e7b,
      precondition: $eRb.ViewHasSearchPatternKey,
      category: $S6b,
      f1: true,
      menu: [{
        id: $bJ.ViewTitle,
        group: "navigation",
        order: 0,
        when: $7m.and($7m.equals("view", $PN), $jO.isEqualTo(SearchUIState.SlowSearch).negate())
      }]
    });
  }
  run(accessor, ...args2) {
    return refreshSearch(accessor);
  }
});
$hJ(class CollapseDeepestExpandedLevelAction extends $gJ {
  constructor() {
    super({
      id: "search.action.collapseSearchResults",
      title: localize2(9677, "Collapse All"),
      category: $S6b,
      icon: $f7b,
      f1: true,
      precondition: $7m.and($eRb.HasSearchResults, $eRb.ViewHasSomeCollapsibleKey),
      menu: [{
        id: $bJ.ViewTitle,
        group: "navigation",
        order: 4,
        when: $7m.and($7m.equals("view", $PN), $7m.or($eRb.HasSearchResults.negate(), $eRb.ViewHasSomeCollapsibleKey))
      }]
    });
  }
  run(accessor, ...args2) {
    return collapseDeepestExpandedLevel(accessor);
  }
});
$hJ(class ExpandAllAction extends $gJ {
  constructor() {
    super({
      id: "search.action.expandSearchResults",
      title: localize2(9678, "Expand All"),
      category: $S6b,
      icon: $g7b,
      f1: true,
      precondition: $7m.and($eRb.HasSearchResults, $eRb.ViewHasSomeCollapsibleKey.toNegated()),
      menu: [{
        id: $bJ.ViewTitle,
        group: "navigation",
        order: 4,
        when: $7m.and($7m.equals("view", $PN), $eRb.HasSearchResults, $eRb.ViewHasSomeCollapsibleKey.toNegated())
      }]
    });
  }
  async run(accessor, ...args2) {
    return expandAll(accessor);
  }
});
$hJ(class ClearSearchResultsAction extends $gJ {
  constructor() {
    super({
      id: "search.action.clearSearchResults",
      title: localize2(9679, "Clear Search Results"),
      category: $S6b,
      icon: $j7b,
      f1: true,
      precondition: $7m.or($eRb.HasSearchResults, $eRb.ViewHasSearchPatternKey, $eRb.ViewHasReplacePatternKey, $eRb.ViewHasFilePatternKey),
      menu: [{
        id: $bJ.ViewTitle,
        group: "navigation",
        order: 1,
        when: $7m.equals("view", $PN)
      }]
    });
  }
  run(accessor, ...args2) {
    return clearSearchResults(accessor);
  }
});
$hJ(class ViewAsTreeAction extends $gJ {
  constructor() {
    super({
      id: "search.action.viewAsTree",
      title: localize2(9680, "View as Tree"),
      category: $S6b,
      icon: $i7b,
      f1: true,
      precondition: $7m.and($eRb.HasSearchResults, $eRb.InTreeViewKey.toNegated()),
      menu: [{
        id: $bJ.ViewTitle,
        group: "navigation",
        order: 2,
        when: $7m.and($7m.equals("view", $PN), $eRb.InTreeViewKey.toNegated())
      }]
    });
  }
  async run(accessor, ...args2) {
    const searchView = $V6b(accessor.get($uob));
    if (searchView) {
      await searchView.setTreeView(true);
    }
  }
});
$hJ(class ViewAsListAction extends $gJ {
  constructor() {
    super({
      id: "search.action.viewAsList",
      title: localize2(9681, "View as List"),
      category: $S6b,
      icon: $h7b,
      f1: true,
      precondition: $7m.and($eRb.HasSearchResults, $eRb.InTreeViewKey),
      menu: [{
        id: $bJ.ViewTitle,
        group: "navigation",
        order: 2,
        when: $7m.and($7m.equals("view", $PN), $eRb.InTreeViewKey)
      }]
    });
  }
  async run(accessor, ...args2) {
    const searchView = $V6b(accessor.get($uob));
    if (searchView) {
      await searchView.setTreeView(false);
    }
  }
});
var clearHistoryCommand = (accessor) => {
  const searchHistoryService = accessor.get($d8b);
  searchHistoryService.clearHistory();
};
async function expandAll(accessor) {
  const viewsService = accessor.get($uob);
  const searchView = $V6b(viewsService);
  if (searchView) {
    const viewer = searchView.getControl();
    if (searchView.shouldShowAIResults()) {
      if (searchView.model.hasAIResults) {
        await $f8b(viewer, void 0);
      } else {
        await $f8b(viewer, searchView.model.searchResult.plainTextSearchResult);
      }
    } else {
      await $f8b(viewer, void 0);
    }
  }
}
async function $f8b(viewer, element) {
  if (element) {
    if (!viewer.hasNode(element)) {
      return;
    }
    await viewer.expand(element, true);
  }
  const children = viewer.getNode(element)?.children;
  if (children) {
    for (const child of children) {
      if ($v6b(child.element)) {
        throw Error("SearchResult should not be a child of a RenderableMatch");
      }
      $f8b(viewer, child.element);
    }
  }
}
function clearSearchResults(accessor) {
  const viewsService = accessor.get($uob);
  const searchView = $V6b(viewsService);
  searchView?.clearSearchResults();
}
function cancelSearch(accessor) {
  const viewsService = accessor.get($uob);
  const searchView = $V6b(viewsService);
  searchView?.cancelSearch();
}
function refreshSearch(accessor) {
  const viewsService = accessor.get($uob);
  const searchView = $V6b(viewsService);
  searchView?.triggerQueryChange({ preserveFocus: false });
}
function collapseDeepestExpandedLevel(accessor) {
  const viewsService = accessor.get($uob);
  const searchView = $V6b(viewsService);
  if (searchView) {
    const viewer = searchView.getControl();
    const navigator2 = viewer.navigate();
    let node = navigator2.first();
    let canCollapseFileMatchLevel = false;
    let canCollapseFirstLevel = false;
    do {
      node = navigator2.next();
    } while ($w6b(node));
    if ($A6b(node) || searchView.ld) {
      while (node = navigator2.next()) {
        if ($w6b(node)) {
          continue;
        }
        if ($D6b(node)) {
          canCollapseFileMatchLevel = true;
          break;
        }
        if (searchView.ld && !canCollapseFirstLevel) {
          let nodeToTest = node;
          if ($y6b(node)) {
            const compressionStartNode = viewer.getCompressedTreeNode(node)?.elements[0].element;
            nodeToTest = compressionStartNode && !$D6b(compressionStartNode) && !$w6b(compressionStartNode) && !$v6b(compressionStartNode) ? compressionStartNode : node;
          }
          const immediateParent = nodeToTest.parent();
          if (!($w6b(immediateParent) || $A6b(immediateParent) || $B6b(immediateParent) || $v6b(immediateParent))) {
            canCollapseFirstLevel = true;
          }
        }
      }
    }
    if (canCollapseFileMatchLevel) {
      node = navigator2.first();
      do {
        if ($C6b(node)) {
          viewer.collapse(node);
        }
      } while (node = navigator2.next());
    } else if (canCollapseFirstLevel) {
      node = navigator2.first();
      if (node) {
        do {
          let nodeToTest = node;
          if ($y6b(node)) {
            const compressionStartNode = viewer.getCompressedTreeNode(node)?.elements[0].element;
            nodeToTest = compressionStartNode && !$D6b(compressionStartNode) && !$v6b(compressionStartNode) ? compressionStartNode : node;
          }
          const immediateParent = nodeToTest.parent();
          if ($A6b(immediateParent) || $B6b(immediateParent)) {
            if (viewer.hasNode(node)) {
              viewer.collapse(node, true);
            } else {
              viewer.collapseAll();
            }
          }
        } while (node = navigator2.next());
      }
    } else if ($w6b(navigator2.first())) {
      node = navigator2.first();
      do {
        if (!node) {
          break;
        }
        if ($w6b(viewer.getParentElement(node))) {
          viewer.collapse(node);
        }
      } while (node = navigator2.next());
    } else {
      viewer.collapseAll();
    }
    const firstFocusParent = viewer.getFocus()[0]?.parent();
    if (firstFocusParent && ($y6b(firstFocusParent) || $C6b(firstFocusParent)) && viewer.hasNode(firstFocusParent) && viewer.isCollapsed(firstFocusParent)) {
      viewer.domFocus();
      viewer.focusFirst();
      viewer.setSelection(viewer.getFocus());
    }
  }
}

// out-build/vs/workbench/contrib/search/browser/searchActionsFind.js
$hJ(class RestrictSearchToFolderAction extends $gJ {
  constructor() {
    super({
      id: "search.action.restrictSearchToFolder",
      title: localize2(9643, "Restrict Search to Folder"),
      category: $S6b,
      keybinding: {
        weight: 200,
        when: $7m.and($eRb.SearchViewVisibleKey, $eRb.ResourceFolderFocusKey),
        primary: 1024 | 512 | 36
      },
      menu: [
        {
          id: $bJ.SearchContext,
          group: "search",
          order: 3,
          when: $7m.and($eRb.ResourceFolderFocusKey)
        }
      ]
    });
  }
  async run(accessor, folderMatch) {
    await searchWithFolderCommand(accessor, false, true, void 0, folderMatch);
  }
});
$hJ(class ExpandSelectedTreeCommandAction extends $gJ {
  constructor() {
    super({
      id: "search.action.expandRecursively",
      title: localize(9639, null),
      category: $S6b,
      menu: [{
        id: $bJ.SearchContext,
        when: $7m.and($eRb.FolderFocusKey, $eRb.HasSearchResults),
        group: "search",
        order: 4
      }]
    });
  }
  async run(accessor) {
    return expandSelectSubtree(accessor);
  }
});
$hJ(class ExcludeFolderFromSearchAction extends $gJ {
  constructor() {
    super({
      id: "search.action.excludeFromSearch",
      title: localize2(9644, "Exclude Folder from Search"),
      category: $S6b,
      menu: [
        {
          id: $bJ.SearchContext,
          group: "search",
          order: 4,
          when: $7m.and($eRb.ResourceFolderFocusKey)
        }
      ]
    });
  }
  async run(accessor, folderMatch) {
    await searchWithFolderCommand(accessor, false, false, void 0, folderMatch);
  }
});
$hJ(class RevealInSideBarForSearchResultsAction extends $gJ {
  constructor() {
    super({
      id: "search.action.revealInSideBar",
      title: localize2(9645, "Reveal in Explorer View"),
      category: $S6b,
      menu: [{
        id: $bJ.SearchContext,
        when: $7m.and($eRb.FileFocusKey, $eRb.HasSearchResults),
        group: "search_3",
        order: 1
      }]
    });
  }
  async run(accessor, args2) {
    const paneCompositeService = accessor.get($uqb);
    const explorerService = accessor.get($kvb);
    const contextService = accessor.get($Zk);
    const searchView = $V6b(accessor.get($uob));
    if (!searchView) {
      return;
    }
    let fileMatch;
    if ($C6b(args2)) {
      fileMatch = args2;
    } else {
      args2 = searchView.getControl().getFocus()[0];
      return;
    }
    paneCompositeService.openPaneComposite($3sb, 0, false).then((viewlet) => {
      if (!viewlet) {
        return;
      }
      const explorerViewContainer = viewlet.getViewPaneContainer();
      const uri = fileMatch.resource;
      if (uri && contextService.isInsideWorkspace(uri)) {
        const explorerView = explorerViewContainer.getExplorerView();
        explorerView.setExpanded(true);
        explorerService.select(uri, true).then(() => explorerView.focus(), $gb);
      }
    });
  }
});
$hJ(class FindInFilesAction extends $gJ {
  constructor() {
    super({
      id: "workbench.action.findInFiles",
      title: {
        ...localize2(9646, "Find in Files"),
        mnemonicTitle: localize(9640, null)
      },
      metadata: {
        description: localize(9641, null),
        args: [
          {
            name: localize(9642, null),
            schema: {
              type: "object",
              properties: {
                query: { "type": "string" },
                replace: { "type": "string" },
                preserveCase: { "type": "boolean" },
                triggerSearch: { "type": "boolean" },
                filesToInclude: { "type": "string" },
                filesToExclude: { "type": "string" },
                isRegex: { "type": "boolean" },
                isCaseSensitive: { "type": "boolean" },
                matchWholeWord: { "type": "boolean" },
                useExcludeSettingsAndIgnoreFiles: { "type": "boolean" },
                onlyOpenEditors: { "type": "boolean" },
                showIncludesExcludes: { "type": "boolean" }
              }
            }
          }
        ]
      },
      category: $S6b,
      keybinding: {
        weight: 200,
        primary: 2048 | 1024 | 36
      },
      menu: [{
        id: $bJ.MenubarEditMenu,
        group: "4_find_global",
        order: 1
      }],
      f1: true
    });
  }
  async run(accessor, args2 = {}) {
    $g8b(accessor, args2);
  }
});
$hJ(class FindInFolderAction extends $gJ {
  // from explorer
  constructor() {
    super({
      id: "filesExplorer.findInFolder",
      title: localize2(9647, "Find in Folder..."),
      category: $S6b,
      keybinding: {
        weight: 200,
        when: $7m.and($ktb, $7sb),
        primary: 1024 | 512 | 36
      },
      menu: [
        {
          id: $bJ.ExplorerContext,
          group: "4_search",
          order: 10,
          when: $7m.and($7sb)
        }
      ]
    });
  }
  async run(accessor, resource) {
    await searchWithFolderCommand(accessor, true, true, resource);
  }
});
$hJ(class FindInWorkspaceAction extends $gJ {
  // from explorer
  constructor() {
    super({
      id: "filesExplorer.findInWorkspace",
      title: localize2(9648, "Find in Workspace..."),
      category: $S6b,
      menu: [
        {
          id: $bJ.ExplorerContext,
          group: "4_search",
          order: 10,
          when: $7m.and($_sb, $7sb.toNegated())
        }
      ]
    });
  }
  async run(accessor) {
    const searchConfig = accessor.get($kl).getValue().search;
    const mode = searchConfig.mode;
    if (mode === "view") {
      const searchView = await $Y6b(accessor.get($uob), true);
      searchView?.searchInFolders();
    } else {
      return accessor.get($sn).executeCommand($66b, {
        location: mode === "newEditor" ? "new" : "reuse",
        filesToInclude: ""
      });
    }
  }
});
async function expandSelectSubtree(accessor) {
  const viewsService = accessor.get($uob);
  const searchView = $V6b(viewsService);
  if (searchView) {
    const viewer = searchView.getControl();
    const selected = viewer.getFocus()[0];
    await $f8b(viewer, selected);
  }
}
async function searchWithFolderCommand(accessor, isFromExplorer, isIncludes, resource, folderMatch) {
  const fileService = accessor.get($km);
  const viewsService = accessor.get($uob);
  const contextService = accessor.get($Zk);
  const commandService = accessor.get($sn);
  const searchConfig = accessor.get($kl).getValue().search;
  const mode = searchConfig.mode;
  let resources;
  if (isFromExplorer) {
    resources = $mvb(resource, accessor.get($Deb), accessor.get($mJ), accessor.get($iJ), accessor.get($kvb));
  } else {
    const searchView = $V6b(viewsService);
    if (!searchView) {
      return;
    }
    resources = getMultiSelectedSearchResources(searchView.getControl(), folderMatch, searchConfig);
  }
  const resolvedResources = fileService.resolveAll(resources.map((resource2) => ({ resource: resource2 }))).then((results) => {
    const folders = [];
    results.forEach((result) => {
      if (result.success && result.stat) {
        folders.push(result.stat.isDirectory ? result.stat.resource : $uh(result.stat.resource));
      }
    });
    return $fT(folders, contextService);
  });
  if (mode === "view") {
    const searchView = await $Y6b(viewsService, true);
    if (resources && resources.length && searchView) {
      if (isIncludes) {
        searchView.searchInFolders(await resolvedResources);
      } else {
        searchView.searchOutsideOfFolders(await resolvedResources);
      }
    }
    return void 0;
  } else {
    if (isIncludes) {
      return commandService.executeCommand($66b, {
        filesToInclude: (await resolvedResources).join(", "),
        showIncludesExcludes: true,
        location: mode === "newEditor" ? "new" : "reuse"
      });
    } else {
      return commandService.executeCommand($66b, {
        filesToExclude: (await resolvedResources).join(", "),
        showIncludesExcludes: true,
        location: mode === "newEditor" ? "new" : "reuse"
      });
    }
  }
}
function getMultiSelectedSearchResources(viewer, currElement, sortConfig) {
  return $W6b(viewer, currElement, sortConfig).map((renderableMatch) => $D6b(renderableMatch) ? null : renderableMatch.resource).filter((renderableMatch) => renderableMatch !== null);
}
async function $g8b(accessor, _args = {}) {
  const searchConfig = accessor.get($kl).getValue().search;
  const viewsService = accessor.get($uob);
  const commandService = accessor.get($sn);
  const args2 = {};
  if (Object.keys(_args).length !== 0) {
    const configurationResolverService = accessor.get($nY);
    const historyService = accessor.get($tY);
    const workspaceContextService = accessor.get($Zk);
    const activeWorkspaceRootUri = historyService.getLastActiveWorkspaceRoot();
    const filteredActiveWorkspaceRootUri = activeWorkspaceRootUri?.scheme === Schemas.file || activeWorkspaceRootUri?.scheme === Schemas.vscodeRemote ? activeWorkspaceRootUri : void 0;
    const lastActiveWorkspaceRoot = filteredActiveWorkspaceRootUri ? workspaceContextService.getWorkspaceFolder(filteredActiveWorkspaceRootUri) ?? void 0 : void 0;
    for (const entry of Object.entries(_args)) {
      const name = entry[0];
      const value = entry[1];
      if (value !== void 0) {
        args2[name] = typeof value === "string" ? await configurationResolverService.resolveAsync(lastActiveWorkspaceRoot, value) : value;
      }
    }
  }
  const mode = searchConfig.mode;
  if (mode === "view") {
    $Y6b(viewsService, false).then((openedView) => {
      if (openedView) {
        const searchAndReplaceWidget = openedView.searchAndReplaceWidget;
        searchAndReplaceWidget.toggleReplace(typeof args2.replace === "string");
        let updatedText = false;
        if (typeof args2.query !== "string") {
          updatedText = openedView.updateTextFromFindWidgetOrSelection({ allowUnselectedWord: typeof args2.replace !== "string" });
        }
        openedView.setSearchParameters(args2);
        if (typeof args2.showIncludesExcludes === "boolean") {
          openedView.toggleQueryDetails(false, args2.showIncludesExcludes);
        }
        openedView.searchAndReplaceWidget.focus(void 0, updatedText, updatedText);
      }
    });
  } else {
    const convertArgs = (args3) => ({
      location: mode === "newEditor" ? "new" : "reuse",
      query: args3.query,
      filesToInclude: args3.filesToInclude,
      filesToExclude: args3.filesToExclude,
      matchWholeWord: args3.matchWholeWord,
      isCaseSensitive: args3.isCaseSensitive,
      isRegexp: args3.isRegex,
      useExcludeSettingsAndIgnoreFiles: args3.useExcludeSettingsAndIgnoreFiles,
      onlyOpenEditors: args3.onlyOpenEditors,
      showIncludesExcludes: !!(args3.filesToExclude || args3.filesToExclude || !args3.useExcludeSettingsAndIgnoreFiles)
    });
    commandService.executeCommand($66b, convertArgs(args2));
  }
}

// out-build/vs/workbench/contrib/search/browser/searchActionsNav.js
$hJ(class ToggleQueryDetailsAction extends $gJ {
  constructor() {
    super({
      id: "workbench.action.search.toggleQueryDetails",
      title: localize2(9649, "Toggle Query Details"),
      category: $S6b,
      keybinding: {
        weight: 200,
        when: $7m.or($eRb.SearchViewFocusedKey, $Z6b),
        primary: 2048 | 1024 | 40
      }
    });
  }
  run(accessor, ...args2) {
    const contextService = accessor.get($on).getContext($Lj());
    if (contextService.getValue($Z6b.serialize())) {
      accessor.get($mJ).activeEditorPane.toggleQueryDetails(args2[0]?.show);
    } else if (contextService.getValue($eRb.SearchViewFocusedKey.serialize())) {
      const searchView = $V6b(accessor.get($uob));
      $Kg(searchView).toggleQueryDetails(void 0, args2[0]?.show);
    }
  }
});
$hJ(class CloseReplaceAction extends $gJ {
  constructor() {
    super({
      id: "closeReplaceInFilesWidget",
      title: localize2(9650, "Close Replace Widget"),
      category: $S6b,
      keybinding: {
        weight: 200,
        when: $7m.and($eRb.SearchViewVisibleKey, $eRb.ReplaceInputBoxFocusedKey),
        primary: 9
      }
    });
  }
  run(accessor) {
    const searchView = $V6b(accessor.get($uob));
    if (searchView) {
      searchView.searchAndReplaceWidget.toggleReplace(false);
      searchView.searchAndReplaceWidget.focus();
    }
    return Promise.resolve(null);
  }
});
$hJ(class ToggleCaseSensitiveCommandAction extends $gJ {
  constructor() {
    super({
      id: "toggleSearchCaseSensitive",
      title: localize2(9651, "Toggle Case Sensitive"),
      category: $S6b,
      keybinding: Object.assign({
        weight: 200,
        when: $m ? $7m.and($eRb.SearchViewFocusedKey, $eRb.FileMatchOrFolderMatchFocusKey.toNegated()) : $eRb.SearchViewFocusedKey
      }, $0fb)
    });
  }
  async run(accessor) {
    toggleCaseSensitiveCommand(accessor);
  }
});
$hJ(class ToggleWholeWordCommandAction extends $gJ {
  constructor() {
    super({
      id: "toggleSearchWholeWord",
      title: localize2(9652, "Toggle Whole Word"),
      keybinding: Object.assign({
        weight: 200,
        when: $eRb.SearchViewFocusedKey
      }, $$fb),
      category: $S6b
    });
  }
  async run(accessor) {
    return toggleWholeWordCommand(accessor);
  }
});
$hJ(class ToggleRegexCommandAction extends $gJ {
  constructor() {
    super({
      id: "toggleSearchRegex",
      title: localize2(9653, "Toggle Regex"),
      keybinding: Object.assign({
        weight: 200,
        when: $eRb.SearchViewFocusedKey
      }, $_fb),
      category: $S6b
    });
  }
  async run(accessor) {
    return toggleRegexCommand(accessor);
  }
});
$hJ(class TogglePreserveCaseAction extends $gJ {
  constructor() {
    super({
      id: "toggleSearchPreserveCase",
      title: localize2(9654, "Toggle Preserve Case"),
      keybinding: Object.assign({
        weight: 200,
        when: $eRb.SearchViewFocusedKey
      }, $bgb),
      category: $S6b
    });
  }
  async run(accessor) {
    return togglePreserveCaseCommand(accessor);
  }
});
$hJ(class OpenMatchAction extends $gJ {
  constructor() {
    super({
      id: "search.action.openResult",
      title: localize2(9655, "Open Match"),
      category: $S6b,
      keybinding: {
        weight: 200,
        when: $7m.and($eRb.SearchViewVisibleKey, $eRb.FileMatchOrMatchFocusKey),
        primary: 3,
        mac: {
          primary: 3,
          secondary: [
            2048 | 18
            /* KeyCode.DownArrow */
          ]
        }
      }
    });
  }
  run(accessor) {
    const searchView = $V6b(accessor.get($uob));
    if (searchView) {
      const tree = searchView.getControl();
      const viewer = searchView.getControl();
      const focus = tree.getFocus()[0];
      if ($y6b(focus)) {
        viewer.toggleCollapsed(focus);
      } else {
        searchView.open(tree.getFocus()[0], false, false, true);
      }
    }
  }
});
$hJ(class OpenMatchToSideAction extends $gJ {
  constructor() {
    super({
      id: "search.action.openResultToSide",
      title: localize2(9656, "Open Match To Side"),
      category: $S6b,
      keybinding: {
        weight: 200,
        when: $7m.and($eRb.SearchViewVisibleKey, $eRb.FileMatchOrMatchFocusKey),
        primary: 2048 | 3,
        mac: {
          primary: 256 | 3
          /* KeyCode.Enter */
        }
      }
    });
  }
  run(accessor) {
    const searchView = $V6b(accessor.get($uob));
    if (searchView) {
      const tree = searchView.getControl();
      searchView.open(tree.getFocus()[0], false, true, true);
    }
  }
});
$hJ(class AddCursorsAtSearchResultsAction extends $gJ {
  constructor() {
    super({
      id: "addCursorsAtSearchResults",
      title: localize2(9657, "Add Cursors at Search Results"),
      keybinding: {
        weight: 200,
        when: $7m.and($eRb.SearchViewVisibleKey, $eRb.FileMatchOrMatchFocusKey),
        primary: 2048 | 1024 | 42
      },
      category: $S6b
    });
  }
  async run(accessor) {
    const searchView = $V6b(accessor.get($uob));
    if (searchView) {
      const tree = searchView.getControl();
      searchView.openEditorWithMultiCursor(tree.getFocus()[0]);
    }
  }
});
$hJ(class FocusNextInputAction extends $gJ {
  constructor() {
    super({
      id: "search.focus.nextInputBox",
      title: localize2(9658, "Focus Next Input"),
      category: $S6b,
      keybinding: {
        weight: 200,
        when: $7m.or($7m.and($Z6b, $eRb.InputBoxFocusedKey), $7m.and($eRb.SearchViewVisibleKey, $eRb.InputBoxFocusedKey)),
        primary: 2048 | 18
      }
    });
  }
  async run(accessor) {
    const editorService = accessor.get($mJ);
    const input = editorService.activeEditor;
    if (input instanceof $37b) {
      editorService.activeEditorPane.focusNextInput();
    }
    const searchView = $V6b(accessor.get($uob));
    searchView?.focusNextInputBox();
  }
});
$hJ(class FocusPreviousInputAction extends $gJ {
  constructor() {
    super({
      id: "search.focus.previousInputBox",
      title: localize2(9659, "Focus Previous Input"),
      category: $S6b,
      keybinding: {
        weight: 200,
        when: $7m.or($7m.and($Z6b, $eRb.InputBoxFocusedKey), $7m.and($eRb.SearchViewVisibleKey, $eRb.InputBoxFocusedKey, $eRb.SearchInputBoxFocusedKey.toNegated())),
        primary: 2048 | 16
      }
    });
  }
  async run(accessor) {
    const editorService = accessor.get($mJ);
    const input = editorService.activeEditor;
    if (input instanceof $37b) {
      editorService.activeEditorPane.focusPrevInput();
    }
    const searchView = $V6b(accessor.get($uob));
    searchView?.focusPreviousInputBox();
  }
});
$hJ(class FocusSearchFromResultsAction extends $gJ {
  constructor() {
    super({
      id: "search.action.focusSearchFromResults",
      title: localize2(9660, "Focus Search From Results"),
      category: $S6b,
      keybinding: {
        weight: 200,
        when: $7m.and($eRb.SearchViewVisibleKey, $7m.or($eRb.FirstMatchFocusKey, $OD)),
        primary: 2048 | 16
      }
    });
  }
  run(accessor) {
    const searchView = $V6b(accessor.get($uob));
    searchView?.focusPreviousInputBox();
  }
});
$hJ(class ToggleSearchOnTypeAction extends $gJ {
  static {
    this.a = "search.searchOnType";
  }
  constructor() {
    super({
      id: "workbench.action.toggleSearchOnType",
      title: localize2(9661, "Toggle Search on Type"),
      category: $S6b
    });
  }
  async run(accessor) {
    const configurationService = accessor.get($kl);
    const searchOnType = configurationService.getValue(ToggleSearchOnTypeAction.a);
    return configurationService.updateValue(ToggleSearchOnTypeAction.a, !searchOnType);
  }
});
$hJ(class FocusSearchListCommandAction extends $gJ {
  constructor() {
    super({
      id: "search.action.focusSearchList",
      title: localize2(9662, "Focus List"),
      category: $S6b,
      f1: true
    });
  }
  async run(accessor) {
    focusSearchListCommand(accessor);
  }
});
$hJ(class FocusNextSearchResultAction extends $gJ {
  constructor() {
    super({
      id: "search.action.focusNextSearchResult",
      title: localize2(9663, "Focus Next Search Result"),
      keybinding: [{
        primary: 62,
        weight: 200
      }],
      category: $S6b,
      f1: true,
      precondition: $7m.or($eRb.HasSearchResults, $Z6b)
    });
  }
  async run(accessor) {
    return await focusNextSearchResult(accessor);
  }
});
$hJ(class FocusPreviousSearchResultAction extends $gJ {
  constructor() {
    super({
      id: "search.action.focusPreviousSearchResult",
      title: localize2(9664, "Focus Previous Search Result"),
      keybinding: [{
        primary: 1024 | 62,
        weight: 200
      }],
      category: $S6b,
      f1: true,
      precondition: $7m.or($eRb.HasSearchResults, $Z6b)
    });
  }
  async run(accessor) {
    return await focusPreviousSearchResult(accessor);
  }
});
$hJ(class ReplaceInFilesAction extends $gJ {
  constructor() {
    super({
      id: "workbench.action.replaceInFiles",
      title: localize2(9665, "Replace in Files"),
      keybinding: [{
        primary: 2048 | 1024 | 38,
        weight: 200
      }],
      category: $S6b,
      f1: true,
      menu: [{
        id: $bJ.MenubarEditMenu,
        group: "4_find_global",
        order: 2
      }]
    });
  }
  async run(accessor) {
    return await findOrReplaceInFiles(accessor, true);
  }
});
function toggleCaseSensitiveCommand(accessor) {
  const searchView = $V6b(accessor.get($uob));
  searchView?.toggleCaseSensitive();
}
function toggleWholeWordCommand(accessor) {
  const searchView = $V6b(accessor.get($uob));
  searchView?.toggleWholeWords();
}
function toggleRegexCommand(accessor) {
  const searchView = $V6b(accessor.get($uob));
  searchView?.toggleRegex();
}
function togglePreserveCaseCommand(accessor) {
  const searchView = $V6b(accessor.get($uob));
  searchView?.togglePreserveCase();
}
var focusSearchListCommand = (accessor) => {
  const viewsService = accessor.get($uob);
  $Y6b(viewsService).then((searchView) => {
    searchView?.moveFocusToResults();
  });
};
async function focusNextSearchResult(accessor) {
  const editorService = accessor.get($mJ);
  const input = editorService.activeEditor;
  if (input instanceof $37b) {
    return editorService.activeEditorPane.focusNextResult();
  }
  return $Y6b(accessor.get($uob)).then((searchView) => searchView?.selectNextMatch());
}
async function focusPreviousSearchResult(accessor) {
  const editorService = accessor.get($mJ);
  const input = editorService.activeEditor;
  if (input instanceof $37b) {
    return editorService.activeEditorPane.focusPreviousResult();
  }
  return $Y6b(accessor.get($uob)).then((searchView) => searchView?.selectPreviousMatch());
}
async function findOrReplaceInFiles(accessor, expandSearchReplaceWidget) {
  return $Y6b(accessor.get($uob), false).then((openedView) => {
    if (openedView) {
      const searchAndReplaceWidget = openedView.searchAndReplaceWidget;
      searchAndReplaceWidget.toggleReplace(expandSearchReplaceWidget);
      const updatedText = openedView.updateTextFromFindWidgetOrSelection({ allowUnselectedWord: !expandSearchReplaceWidget });
      openedView.searchAndReplaceWidget.focus(void 0, updatedText, updatedText);
    }
  });
}

// out-build/vs/workbench/contrib/search/browser/searchActionsRemoveReplace.js
$hJ(class RemoveAction2 extends $gJ {
  constructor() {
    super({
      id: "search.action.remove",
      title: localize2(9666, "Dismiss"),
      category: $S6b,
      icon: $d7b,
      keybinding: {
        weight: 200,
        when: $7m.and($eRb.SearchViewVisibleKey, $eRb.FileMatchOrMatchFocusKey),
        primary: 20,
        mac: {
          primary: 2048 | 1
        }
      },
      menu: [
        {
          id: $bJ.SearchContext,
          group: "search",
          order: 2
        },
        {
          id: $bJ.SearchActionMenu,
          group: "inline",
          order: 2
        }
      ]
    });
  }
  async run(accessor, context) {
    const viewsService = accessor.get($uob);
    const configurationService = accessor.get($kl);
    const searchView = $V6b(viewsService);
    if (!searchView) {
      return;
    }
    let element = context?.element;
    let viewer = context?.viewer;
    if (!viewer) {
      viewer = searchView.getControl();
    }
    if (!element) {
      element = viewer.getFocus()[0] ?? void 0;
    }
    const elementsToRemove = $W6b(viewer, element, configurationService.getValue("search"));
    let focusElement = viewer.getFocus()[0] ?? void 0;
    if (elementsToRemove.length === 0) {
      return;
    }
    if (!focusElement || $v6b(focusElement)) {
      focusElement = element;
    }
    let nextFocusElement;
    const shouldRefocusMatch = $X6b(elementsToRemove, focusElement);
    if (focusElement && shouldRefocusMatch) {
      nextFocusElement = await $h8b(viewer, focusElement, elementsToRemove);
    }
    const searchResult = searchView.searchResult;
    if (searchResult) {
      searchResult.batchRemove(elementsToRemove);
    }
    await searchView.queueRefreshTree();
    if (focusElement && shouldRefocusMatch) {
      if (!nextFocusElement) {
        nextFocusElement = await $i8b(viewer, focusElement);
      }
      if (nextFocusElement && !$j6b(nextFocusElement, elementsToRemove)) {
        viewer.reveal(nextFocusElement);
        viewer.setFocus([nextFocusElement], $Zeb());
        viewer.setSelection([nextFocusElement], $Zeb());
      }
    } else if (!$zb(viewer.getFocus(), viewer.getSelection())) {
      viewer.setSelection(viewer.getFocus());
    }
    viewer.domFocus();
    return;
  }
});
$hJ(class ReplaceAction extends $gJ {
  constructor() {
    super({
      id: "search.action.replace",
      title: localize2(9667, "Replace"),
      category: $S6b,
      keybinding: {
        weight: 200,
        when: $7m.and($eRb.SearchViewVisibleKey, $eRb.ReplaceActiveKey, $eRb.MatchFocusKey, $eRb.IsEditableItemKey),
        primary: 1024 | 2048 | 22
      },
      icon: $c7b,
      menu: [
        {
          id: $bJ.SearchContext,
          when: $7m.and($eRb.ReplaceActiveKey, $eRb.MatchFocusKey, $eRb.IsEditableItemKey),
          group: "search",
          order: 1
        },
        {
          id: $bJ.SearchActionMenu,
          when: $7m.and($eRb.ReplaceActiveKey, $eRb.MatchFocusKey, $eRb.IsEditableItemKey),
          group: "inline",
          order: 1
        }
      ]
    });
  }
  async run(accessor, context) {
    return performReplace(accessor, context);
  }
});
$hJ(class ReplaceAllAction2 extends $gJ {
  constructor() {
    super({
      id: "search.action.replaceAllInFile",
      title: localize2(9668, "Replace All"),
      category: $S6b,
      keybinding: {
        weight: 200,
        when: $7m.and($eRb.SearchViewVisibleKey, $eRb.ReplaceActiveKey, $eRb.FileFocusKey, $eRb.IsEditableItemKey),
        primary: 1024 | 2048 | 22,
        secondary: [
          2048 | 1024 | 3
          /* KeyCode.Enter */
        ]
      },
      icon: $c7b,
      menu: [
        {
          id: $bJ.SearchContext,
          when: $7m.and($eRb.ReplaceActiveKey, $eRb.FileFocusKey, $eRb.IsEditableItemKey),
          group: "search",
          order: 1
        },
        {
          id: $bJ.SearchActionMenu,
          when: $7m.and($eRb.ReplaceActiveKey, $eRb.FileFocusKey, $eRb.IsEditableItemKey),
          group: "inline",
          order: 1
        }
      ]
    });
  }
  async run(accessor, context) {
    return performReplace(accessor, context);
  }
});
$hJ(class ReplaceAllInFolderAction extends $gJ {
  constructor() {
    super({
      id: "search.action.replaceAllInFolder",
      title: localize2(9669, "Replace All"),
      category: $S6b,
      keybinding: {
        weight: 200,
        when: $7m.and($eRb.SearchViewVisibleKey, $eRb.ReplaceActiveKey, $eRb.FolderFocusKey, $eRb.IsEditableItemKey),
        primary: 1024 | 2048 | 22,
        secondary: [
          2048 | 1024 | 3
          /* KeyCode.Enter */
        ]
      },
      icon: $c7b,
      menu: [
        {
          id: $bJ.SearchContext,
          when: $7m.and($eRb.ReplaceActiveKey, $eRb.FolderFocusKey, $eRb.IsEditableItemKey),
          group: "search",
          order: 1
        },
        {
          id: $bJ.SearchActionMenu,
          when: $7m.and($eRb.ReplaceActiveKey, $eRb.FolderFocusKey, $eRb.IsEditableItemKey),
          group: "inline",
          order: 1
        }
      ]
    });
  }
  async run(accessor, context) {
    return performReplace(accessor, context);
  }
});
async function performReplace(accessor, context) {
  const configurationService = accessor.get($kl);
  const viewsService = accessor.get($uob);
  const viewlet = $V6b(viewsService);
  const viewer = context?.viewer ?? viewlet?.getControl();
  if (!viewer) {
    return;
  }
  const element = context?.element ?? viewer.getFocus()[0];
  const elementsToReplace = $W6b(viewer, element ?? void 0, configurationService.getValue("search"));
  let focusElement = viewer.getFocus()[0];
  if (!focusElement || focusElement && !$j6b(focusElement, elementsToReplace) || $v6b(focusElement)) {
    focusElement = element;
  }
  if (elementsToReplace.length === 0) {
    return;
  }
  let nextFocusElement;
  if (focusElement) {
    nextFocusElement = await $h8b(viewer, focusElement, elementsToReplace);
  }
  const searchResult = viewlet?.searchResult;
  if (searchResult) {
    await searchResult.batchReplace(elementsToReplace);
  }
  await viewlet?.queueRefreshTree();
  if (focusElement) {
    if (!nextFocusElement) {
      nextFocusElement = await $i8b(viewer, focusElement);
    }
    if (nextFocusElement) {
      viewer.reveal(nextFocusElement);
      viewer.setFocus([nextFocusElement], $Zeb());
      viewer.setSelection([nextFocusElement], $Zeb());
      if ($D6b(nextFocusElement)) {
        const useReplacePreview = configurationService.getValue().search.useReplacePreview;
        if (!useReplacePreview || hasToOpenFile(accessor, nextFocusElement) || nextFocusElement instanceof $B7b) {
          viewlet?.open(nextFocusElement, true);
        } else {
          accessor.get($u7b).openReplacePreview(nextFocusElement, true);
        }
      } else if ($C6b(nextFocusElement)) {
        viewlet?.open(nextFocusElement, true);
      }
    }
  }
  viewer.domFocus();
}
function hasToOpenFile(accessor, currBottomElem) {
  if (!$D6b(currBottomElem)) {
    return false;
  }
  const activeEditor = accessor.get($mJ).activeEditor;
  const file = activeEditor?.resource;
  if (file) {
    return accessor.get($vl).extUri.isEqual(file, currBottomElem.parent().resource);
  }
  return false;
}
function compareLevels(elem1, elem2) {
  if ($D6b(elem1)) {
    if ($D6b(elem2)) {
      return 0;
    } else {
      return -1;
    }
  } else if ($C6b(elem1)) {
    if ($D6b(elem2)) {
      return 1;
    } else if ($C6b(elem2)) {
      return 0;
    } else {
      return -1;
    }
  } else if ($y6b(elem1)) {
    if ($w6b(elem2)) {
      return -1;
    } else if ($y6b(elem2)) {
      return 0;
    } else {
      return 1;
    }
  } else {
    if ($w6b(elem2)) {
      return 0;
    } else {
      return 1;
    }
  }
}
async function $h8b(viewer, element, elementsToRemove) {
  const navigator2 = viewer.navigate(element);
  if ($y6b(element)) {
    while (!!navigator2.next() && (!$y6b(navigator2.current()) || $j6b(navigator2.current(), elementsToRemove))) {
    }
  } else if ($C6b(element)) {
    while (!!navigator2.next() && (!$C6b(navigator2.current()) || $j6b(navigator2.current(), elementsToRemove))) {
      await viewer.expand(navigator2.current());
    }
  } else {
    while (navigator2.next() && (!$D6b(navigator2.current()) || $j6b(navigator2.current(), elementsToRemove))) {
      await viewer.expand(navigator2.current());
    }
  }
  return navigator2.current();
}
async function $i8b(viewer, element) {
  let lastElem = viewer.lastVisibleElement ?? null;
  while (lastElem) {
    const compareVal = compareLevels(element, lastElem);
    if (compareVal === -1) {
      const expanded2 = await viewer.expand(lastElem);
      if (!expanded2) {
        return lastElem;
      }
      lastElem = viewer.lastVisibleElement;
    } else if (compareVal === 1) {
      const potentialLastElem = viewer.getParentElement(lastElem);
      if ($v6b(potentialLastElem)) {
        break;
      } else {
        lastElem = potentialLastElem;
      }
    } else {
      return lastElem;
    }
  }
  return void 0;
}

// out-build/vs/workbench/contrib/search/browser/searchActionsSymbol.js
$hJ(class ShowAllSymbolsAction extends $gJ {
  static {
    this.ID = "workbench.action.showAllSymbols";
  }
  static {
    this.LABEL = localize(9670, null);
  }
  static {
    this.ALL_SYMBOLS_PREFIX = "#";
  }
  constructor() {
    super({
      id: "workbench.action.showAllSymbols",
      title: {
        ...localize2(9672, "Go to Symbol in Workspace..."),
        mnemonicTitle: localize(9671, null)
      },
      f1: true,
      keybinding: {
        weight: 200,
        primary: 2048 | 50
        /* KeyCode.KeyT */
      },
      menu: {
        id: $bJ.MenubarGoMenu,
        group: "3_global_nav",
        order: 2
      }
    });
  }
  async run(accessor) {
    accessor.get($1M).quickAccess.show(ShowAllSymbolsAction.ALL_SYMBOLS_PREFIX);
  }
});

// out-build/vs/workbench/contrib/search/browser/quickTextSearch/textSearchQuickAccess.js
var $eac = "%";
var DEFAULT_TEXT_QUERY_BUILDER_OPTIONS = {
  _reason: "quickAccessSearch",
  disregardIgnoreFiles: false,
  disregardExcludeSettings: false,
  onlyOpenEditors: false,
  expandPatterns: true
};
var MAX_FILES_SHOWN = 30;
var MAX_RESULTS_PER_FILE = 10;
var DEBOUNCE_DELAY2 = 75;
var $fac = class $fac2 extends $rhb {
  s(charsPerLine) {
    return {
      ...DEFAULT_TEXT_QUERY_BUILDER_OPTIONS,
      ...{
        extraFileResources: this.t.invokeFunction($hO),
        maxResults: this.D.maxResults ?? void 0,
        isSmartCase: this.D.smartCase
      },
      previewOptions: {
        matchLines: 1,
        charsPerLine
      }
    };
  }
  constructor(t, u, w, y, z, C) {
    super($eac, { canAcceptInBackground: true, shouldSkipTrimPickFilter: true });
    this.t = t;
    this.u = u;
    this.w = w;
    this.y = y;
    this.z = z;
    this.C = C;
    this.n = Promise.resolve({
      results: [],
      messages: []
    });
    this.j = this.t.createInstance($eT);
    this.m = this.B(this.t.createInstance($P7b));
    this.r = this.B(this.t.createInstance($0yb));
    this.m.location = SearchModelLocation.QUICK_ACCESS;
    this.h = new $Qh();
  }
  dispose() {
    this.m.dispose();
    super.dispose();
  }
  provide(picker, token, runOptions2) {
    const disposables = new $2c();
    if ($eac.length < picker.value.length) {
      picker.valueSelection = [$eac.length, picker.value.length];
    }
    picker.buttons = [{
      location: QuickInputButtonLocation.Inline,
      iconClass: ThemeIcon.asClassName($6l.goToSearch),
      tooltip: localize(9553, null)
    }];
    this.r.reset();
    disposables.add(picker.onDidTriggerButton(async () => {
      if (this.m.searchResult.count() > 0) {
        await this.G(void 0);
      } else {
        this.z.openView($PN, true);
      }
      picker.hide();
    }));
    const onDidChangeActive = () => {
      const [item] = picker.activeItems;
      if (item?.match) {
        this.r.set();
        const itemMatch = item.match;
        this.h.queue(async () => {
          await this.r.openTransientEditor({
            resource: itemMatch.parent().resource,
            options: { preserveFocus: true, revealIfOpened: true, ignoreError: true, selection: itemMatch.range() }
          });
        });
      }
    };
    disposables.add(Event2.debounce(picker.onDidChangeActive, (last, event) => event, DEBOUNCE_DELAY2, true)(onDidChangeActive));
    disposables.add(Event2.once(picker.onWillHide)(({ reason }) => {
      if (reason === QuickInputHideReason.Gesture) {
        this.r.restore();
      }
    }));
    disposables.add(Event2.once(picker.onDidHide)(({ reason }) => {
      this.m.searchResult.toggleHighlights(false);
    }));
    disposables.add(super.provide(picker, token, runOptions2));
    disposables.add(picker.onDidAccept(() => this.m.searchResult.toggleHighlights(false)));
    return disposables;
  }
  get D() {
    const editorConfig = this.C.getValue().workbench?.editor;
    const searchConfig = this.C.getValue().search;
    return {
      openEditorPinned: !editorConfig?.enablePreviewFromQuickOpen || !editorConfig?.enablePreview,
      preserveInput: searchConfig.quickAccess.preserveInput,
      maxResults: searchConfig.maxResults,
      smartCase: searchConfig.smartCase,
      sortOrder: searchConfig.sortOrder
    };
  }
  get defaultFilterValue() {
    if (this.D.preserveInput) {
      return DefaultQuickAccessFilterValue.LAST;
    }
    return void 0;
  }
  F(contentPattern, token) {
    if (contentPattern === "") {
      return void 0;
    }
    const folderResources = this.u.getWorkspace().folders;
    const content = {
      pattern: contentPattern
    };
    this.m.searchResult.toggleHighlights(false);
    const charsPerLine = content.isRegExp ? 1e4 : 1e3;
    const query = this.j.text(content, folderResources.map((folder) => folder.uri), this.s(charsPerLine));
    const result = this.m.search(query, void 0, token);
    const getAsyncResults = async () => {
      this.n = result.asyncResults;
      await result.asyncResults;
      const syncResultURIs = new $Fc(result.syncResults.map((e) => e.resource));
      return this.m.searchResult.matches(false).filter((e) => !syncResultURIs.has(e.resource));
    };
    return {
      syncResults: this.m.searchResult.matches(false),
      asyncResults: getAsyncResults()
    };
  }
  async G(currentElem) {
    this.z.openView($PN, false);
    const viewlet = this.z.getActiveViewWithId($PN);
    await viewlet.replaceSearchModel(this.m, this.n);
    this.m = this.t.createInstance($P7b);
    this.m.location = SearchModelLocation.QUICK_ACCESS;
    const viewer = viewlet?.getControl();
    if (currentElem) {
      viewer.setFocus([currentElem], $Zeb());
      viewer.setSelection([currentElem], $Zeb());
      viewer.reveal(currentElem);
    } else {
      viewlet.searchAndReplaceWidget.focus();
    }
  }
  H(matches, limit, firstFile) {
    matches = matches.sort((a, b) => {
      if (firstFile) {
        if (firstFile === a.resource) {
          return -1;
        } else if (firstFile === b.resource) {
          return 1;
        }
      }
      return $R6b(a, b, this.D.sortOrder);
    });
    const files = matches.length > limit ? matches.slice(0, limit) : matches;
    const picks = [];
    for (let fileIndex = 0; fileIndex < matches.length; fileIndex++) {
      if (fileIndex === limit) {
        picks.push({
          type: "separator"
        });
        picks.push({
          label: localize(9554, null),
          iconClass: ThemeIcon.asClassName($96b),
          accept: async () => {
            await this.G(matches[limit]);
          }
        });
        break;
      }
      const iFileInstanceMatch = files[fileIndex];
      const label3 = $rh(iFileInstanceMatch.resource);
      const description = this.y.getUriLabel($uh(iFileInstanceMatch.resource), { relative: true });
      picks.push({
        label: label3,
        type: "separator",
        description,
        buttons: [{
          iconClass: ThemeIcon.asClassName($n7b),
          tooltip: localize(9555, null)
        }],
        trigger: async () => {
          await this.I(iFileInstanceMatch, {});
          return TriggerAction.CLOSE_PICKER;
        }
      });
      const results = iFileInstanceMatch.matches() ?? [];
      for (let matchIndex = 0; matchIndex < results.length; matchIndex++) {
        const element = results[matchIndex];
        if (matchIndex === MAX_RESULTS_PER_FILE) {
          picks.push({
            label: localize(9556, null),
            iconClass: ThemeIcon.asClassName($96b),
            accept: async () => {
              await this.G(element);
            }
          });
          break;
        }
        const preview = element.preview();
        const previewText = (preview.before + preview.inside + preview.after).trim().substring(0, 999);
        const match = [{
          start: preview.before.length,
          end: preview.before.length + preview.inside.length
        }];
        picks.push({
          label: `${previewText}`,
          highlights: {
            label: match
          },
          buttons: [{
            iconClass: ThemeIcon.asClassName($06b),
            tooltip: localize(9557, null)
          }],
          ariaLabel: `Match at location ${element.range().startLineNumber}:${element.range().startColumn} - ${previewText}`,
          accept: async (keyMods, event) => {
            await this.I(iFileInstanceMatch, {
              keyMods,
              selection: $q8b(element, this.m),
              preserveFocus: event.inBackground,
              forcePinned: event.inBackground
            });
          },
          trigger: async () => {
            await this.G(element);
            return TriggerAction.CLOSE_PICKER;
          },
          match: element
        });
      }
    }
    return picks;
  }
  async I(iFileInstanceMatch, options3) {
    const editorOptions2 = {
      preserveFocus: options3.preserveFocus,
      pinned: options3.keyMods?.ctrlCmd || options3.forcePinned || this.D.openEditorPinned,
      selection: options3.selection
    };
    const targetGroup = options3.keyMods?.alt || this.D.openEditorPinned && options3.keyMods?.ctrlCmd || options3.forceOpenSideBySide ? $oJ : $nJ;
    await this.w.openEditor({
      resource: iFileInstanceMatch.resource,
      options: editorOptions2
    }, targetGroup);
  }
  g(contentPattern, disposables, token) {
    const searchModelAtTimeOfSearch = this.m;
    if (contentPattern === "") {
      this.m.searchResult.clear();
      return [{
        label: localize(9558, null)
      }];
    }
    const conditionalTokenCts = disposables.add(new $ad());
    disposables.add(token.onCancellationRequested(() => {
      if (searchModelAtTimeOfSearch.location === SearchModelLocation.QUICK_ACCESS) {
        conditionalTokenCts.cancel();
      }
    }));
    const allMatches = this.F(contentPattern, conditionalTokenCts.token);
    if (!allMatches) {
      return null;
    }
    const matches = allMatches.syncResults;
    const syncResult = this.H(matches, MAX_FILES_SHOWN, this.w.activeEditor?.resource);
    if (syncResult.length > 0) {
      this.m.searchResult.toggleHighlights(true);
    }
    if (matches.length >= MAX_FILES_SHOWN) {
      return syncResult;
    }
    return {
      picks: syncResult,
      additionalPicks: allMatches.asyncResults.then((asyncResults) => asyncResults.length + syncResult.length === 0 ? [{
        label: localize(9559, null)
      }] : this.H(asyncResults, MAX_FILES_SHOWN - matches.length)).then((picks) => {
        if (picks.length > 0) {
          this.m.searchResult.toggleHighlights(true);
        }
        return picks;
      })
    };
  }
};
$fac = __decorate([
  __param(0, $Pk),
  __param(1, $Zk),
  __param(2, $mJ),
  __param(3, $ZI),
  __param(4, $uob),
  __param(5, $kl)
], $fac);

// out-build/vs/workbench/contrib/search/browser/searchActionsTextQuickAccess.js
$hJ(class TextSearchQuickAccessAction extends $gJ {
  constructor() {
    super({
      id: "workbench.action.quickTextSearch",
      title: localize2(9673, "Quick Search"),
      category: $S6b,
      f1: true
    });
  }
  async run(accessor, match) {
    const quickInputService = accessor.get($1M);
    const searchText = getSearchText(accessor) ?? "";
    quickInputService.quickAccess.show($eac + searchText, { preserveValue: !!searchText });
  }
});
function getSearchText(accessor) {
  const editorService = accessor.get($mJ);
  const configurationService = accessor.get($kl);
  const activeEditor = editorService.activeTextEditorControl;
  if (!activeEditor) {
    return null;
  }
  if (!activeEditor.hasTextFocus()) {
    return null;
  }
  const seedSearchStringFromSelection = configurationService.getValue("editor.find.seedSearchStringFromSelection");
  if (!seedSearchStringFromSelection) {
    return null;
  }
  return $r8b(false, activeEditor);
}

// out-build/vs/workbench/contrib/search/browser/search.contribution.js
$SC(
  $O7b,
  $Q7b,
  1
  /* InstantiationType.Delayed */
);
$SC(
  $d8b,
  $e8b,
  1
  /* InstantiationType.Delayed */
);
$aac();
$cac();
$s7b();
var SEARCH_MODE_CONFIG = "search.mode";
var viewContainer2 = $Wn.as(Extensions5.ViewContainersRegistry).registerViewContainer({
  id: $NN,
  title: localize2(9633, "Search"),
  ctorDescriptor: new $Nk($oqb, [$NN, { mergeViewWithContainerWhenSingleView: true }]),
  hideIfEmpty: true,
  icon: $l7b,
  order: 1
}, 0, { doNotRegisterOpenCommand: true });
var viewDescriptor2 = {
  id: $PN,
  containerIcon: $l7b,
  name: localize2(9634, "Search"),
  ctorDescriptor: new $Nk($p8b),
  canToggleVisibility: false,
  canMoveView: true,
  openCommandActionDescriptor: {
    id: viewContainer2.id,
    mnemonicTitle: localize(9562, null),
    keybindings: {
      primary: 2048 | 1024 | 36,
      // Yes, this is weird. See #116188, #115556, #115511, and now #124146, for examples of what can go wrong here.
      when: $7m.regex("neverMatch", /doesNotMatch/)
    },
    order: 1
  }
};
$Wn.as(Extensions5.ViewsRegistry).registerViews([viewDescriptor2], viewContainer2);
var quickAccessRegistry3 = $Wn.as($CM.Quickaccess);
quickAccessRegistry3.registerQuickAccessProvider({
  ctor: $g6b,
  prefix: $g6b.PREFIX,
  placeholder: localize(9563, null, $0_b.PREFIX, $d6b.PREFIX),
  contextKey: $7yb,
  helpEntries: [{
    description: localize(9564, null),
    commandId: "workbench.action.quickOpen",
    commandCenterOrder: 10
  }]
});
quickAccessRegistry3.registerQuickAccessProvider({
  ctor: $$Nb,
  prefix: $$Nb.PREFIX,
  placeholder: localize(9565, null),
  contextKey: "inWorkspaceSymbolsPicker",
  helpEntries: [{
    description: localize(9566, null),
    commandId: "workbench.action.showAllSymbols"
    /* Constants.SearchCommandIds.ShowAllSymbolsActionId */
  }]
});
quickAccessRegistry3.registerQuickAccessProvider({
  ctor: $fac,
  prefix: $eac,
  contextKey: "inTextSearchPicker",
  placeholder: localize(9567, null),
  helpEntries: [
    {
      description: localize(9568, null),
      commandId: "workbench.action.quickTextSearch",
      commandCenterOrder: 25
    }
  ]
});
var configurationRegistry11 = $Wn.as($Ht.Configuration);
configurationRegistry11.registerConfiguration({
  id: "search",
  order: 13,
  title: localize(9569, null),
  type: "object",
  properties: {
    [$RN]: {
      type: "object",
      markdownDescription: localize(9570, null),
      default: { "**/node_modules": true, "**/bower_components": true, "**/*.code-search": true },
      additionalProperties: {
        anyOf: [
          {
            type: "boolean",
            description: localize(9571, null)
          },
          {
            type: "object",
            properties: {
              when: {
                type: "string",
                // expression ({ "**/*.js": { "when": "$(basename).js" } })
                pattern: "\\w*\\$\\(basename\\)\\w*",
                default: "$(basename).ext",
                markdownDescription: localize(9572, null)
              }
            }
          }
        ]
      },
      scope: 4
      /* ConfigurationScope.RESOURCE */
    },
    [SEARCH_MODE_CONFIG]: {
      type: "string",
      enum: ["view", "reuseEditor", "newEditor"],
      default: "view",
      markdownDescription: localize(9573, null),
      enumDescriptions: [
        localize(9574, null),
        localize(9575, null),
        localize(9576, null)
      ]
    },
    "search.useRipgrep": {
      type: "boolean",
      description: localize(9577, null),
      deprecationMessage: localize(9578, null),
      default: true
    },
    "search.maintainFileSearchCache": {
      type: "boolean",
      deprecationMessage: localize(9579, null),
      description: localize(9580, null),
      default: false
    },
    "search.useIgnoreFiles": {
      type: "boolean",
      markdownDescription: localize(9581, null),
      default: true,
      scope: 4
      /* ConfigurationScope.RESOURCE */
    },
    "search.useGlobalIgnoreFiles": {
      type: "boolean",
      markdownDescription: localize(9582, null, "`#search.useIgnoreFiles#`"),
      default: false,
      scope: 4
      /* ConfigurationScope.RESOURCE */
    },
    "search.useParentIgnoreFiles": {
      type: "boolean",
      markdownDescription: localize(9583, null, "`#search.useIgnoreFiles#`"),
      default: false,
      scope: 4
      /* ConfigurationScope.RESOURCE */
    },
    "search.quickOpen.includeSymbols": {
      type: "boolean",
      description: localize(9584, null),
      default: false
    },
    "search.ripgrep.maxThreads": {
      type: "number",
      description: localize(9585, null),
      default: 0
    },
    "search.quickOpen.includeHistory": {
      type: "boolean",
      description: localize(9586, null),
      default: true
    },
    "search.quickOpen.history.filterSortOrder": {
      type: "string",
      enum: ["default", "recency"],
      default: "default",
      enumDescriptions: [
        localize(9587, null),
        localize(9588, null)
      ],
      description: localize(9589, null)
    },
    "search.followSymlinks": {
      type: "boolean",
      description: localize(9590, null),
      default: true
    },
    "search.smartCase": {
      type: "boolean",
      description: localize(9591, null),
      default: false
    },
    "search.globalFindClipboard": {
      type: "boolean",
      default: false,
      description: localize(9592, null),
      included: $m
    },
    "search.location": {
      type: "string",
      enum: ["sidebar", "panel"],
      default: "sidebar",
      description: localize(9593, null),
      deprecationMessage: localize(9594, null)
    },
    "search.maxResults": {
      type: ["number", "null"],
      default: $SN,
      markdownDescription: localize(9595, null)
    },
    "search.collapseResults": {
      type: "string",
      enum: ["auto", "alwaysCollapse", "alwaysExpand"],
      enumDescriptions: [
        localize(9596, null),
        "",
        ""
      ],
      default: "alwaysExpand",
      description: localize(9597, null)
    },
    "search.useReplacePreview": {
      type: "boolean",
      default: true,
      description: localize(9598, null)
    },
    "search.showLineNumbers": {
      type: "boolean",
      default: false,
      description: localize(9599, null)
    },
    "search.usePCRE2": {
      type: "boolean",
      default: false,
      description: localize(9600, null),
      deprecationMessage: localize(9601, null)
    },
    "search.actionsPosition": {
      type: "string",
      enum: ["auto", "right"],
      enumDescriptions: [
        localize(9602, null),
        localize(9603, null)
      ],
      default: "right",
      description: localize(9604, null)
    },
    "search.searchOnType": {
      type: "boolean",
      default: true,
      description: localize(9605, null)
    },
    "search.seedWithNearestWord": {
      type: "boolean",
      default: false,
      description: localize(9606, null)
    },
    "search.seedOnFocus": {
      type: "boolean",
      default: false,
      markdownDescription: localize(9607, null)
    },
    "search.searchOnTypeDebouncePeriod": {
      type: "number",
      default: 300,
      markdownDescription: localize(9608, null, "`#search.searchOnType#`")
    },
    "search.searchEditor.doubleClickBehaviour": {
      type: "string",
      enum: ["selectWord", "goToLocation", "openLocationToSide"],
      default: "goToLocation",
      enumDescriptions: [
        localize(9609, null),
        localize(9610, null),
        localize(9611, null)
      ],
      markdownDescription: localize(9612, null)
    },
    "search.searchEditor.singleClickBehaviour": {
      type: "string",
      enum: ["default", "peekDefinition"],
      default: "default",
      enumDescriptions: [
        localize(9613, null),
        localize(9614, null)
      ],
      markdownDescription: localize(9615, null)
    },
    "search.searchEditor.reusePriorSearchConfiguration": {
      type: "boolean",
      default: false,
      markdownDescription: localize(9616, null)
    },
    "search.searchEditor.defaultNumberOfContextLines": {
      type: ["number", "null"],
      default: 1,
      markdownDescription: localize(9617, null)
    },
    "search.searchEditor.focusResultsOnSearch": {
      type: "boolean",
      default: false,
      markdownDescription: localize(9618, null)
    },
    "search.sortOrder": {
      type: "string",
      enum: [
        "default",
        "fileNames",
        "type",
        "modified",
        "countDescending",
        "countAscending"
        /* SearchSortOrder.CountAscending */
      ],
      default: "default",
      enumDescriptions: [
        localize(9619, null),
        localize(9620, null),
        localize(9621, null),
        localize(9622, null),
        localize(9623, null),
        localize(9624, null)
      ],
      description: localize(9625, null)
    },
    "search.decorations.colors": {
      type: "boolean",
      description: localize(9626, null),
      default: true
    },
    "search.decorations.badges": {
      type: "boolean",
      description: localize(9627, null),
      default: true
    },
    "search.defaultViewMode": {
      type: "string",
      enum: [
        "tree",
        "list"
        /* ViewMode.List */
      ],
      default: "list",
      enumDescriptions: [
        localize(9628, null),
        localize(9629, null)
      ],
      description: localize(9630, null)
    },
    "search.quickAccess.preserveInput": {
      type: "boolean",
      description: localize(9631, null),
      default: false
    },
    "search.experimental.closedNotebookRichContentResults": {
      type: "boolean",
      description: localize(9632, null),
      default: false
    }
  }
});
$tn.registerCommand("_executeWorkspaceSymbolProvider", async function(accessor, ...args2) {
  const [query] = args2;
  $Jg(typeof query === "string");
  const result = await $gO(query);
  return result.map((item) => item.symbol);
});
$Wn.as($YL.ConfigurationMigration).registerConfigurationMigrations([{
  key: "search.experimental.quickAccess.preserveInput",
  migrateFn: (value, _accessor) => [
    ["search.quickAccess.preserveInput", { value }],
    ["search.experimental.quickAccess.preserveInput", { value: void 0 }]
  ]
}]);

// out-build/vs/workbench/contrib/searchEditor/browser/searchEditor.js
var $67b_1;
var RESULT_LINE_REGEX = /^(\s+)(\d+)(: |  )(\s*)(.*)$/;
var FILE_LINE_REGEX = /^(\S.*):$/;
var $67b = class $67b2 extends $NUb {
  static {
    $67b_1 = this;
  }
  static {
    this.ID = $46b;
  }
  static {
    this.SEARCH_EDITOR_VIEW_STATE_PREFERENCE_KEY = "searchEditorViewState";
  }
  get Yb() {
    return this.a;
  }
  constructor(group2, telemetryService, themeService, storageService, pc, qc, rc, instantiationService, sc, tc, uc, vc, progressService, textResourceService, editorGroupService, editorService, wc, fileService, xc, yc) {
    super($67b_1.ID, group2, telemetryService, instantiationService, storageService, textResourceService, themeService, editorService, editorGroupService, fileService);
    this.pc = pc;
    this.qc = qc;
    this.rc = rc;
    this.sc = sc;
    this.tc = tc;
    this.uc = uc;
    this.vc = vc;
    this.wc = wc;
    this.xc = xc;
    this.yc = yc;
    this.fc = new $Sh(0);
    this.gc = false;
    this.hc = false;
    this.nc = 0;
    this.oc = false;
    this.lc = $(".search-editor");
    this.ic = this.B(new $YJ(progressService));
    this.B(this.kc = new $2c());
    this.jc = new $Sh(2e3);
    this.mc = this.B(this.m.createInstance($P7b));
  }
  Y(parent) {
    $bk(parent, this.lc);
    this.Zb = $bk(this.lc, $(".query-container"));
    const searchResultContainer = $bk(this.lc, $(".search-results"));
    super.Y(searchResultContainer);
    this.Ec();
    const scopedContextKeyService = $Kg(this.scopedContextKeyService);
    $Z6b.bindTo(scopedContextKeyService).set(true);
    this.Ac(this.Zb, this.B(this.m.createChild(new $Ok([$on, scopedContextKeyService]))), $eRb.InputBoxFocusedKey.bindTo(scopedContextKeyService));
  }
  Ac(container2, scopedInstantiationService, inputBoxFocusedContextKey) {
    const searchEditorInputboxStyles = $C$({ inputBorder: searchEditorTextInputBorder });
    this.Xb = this.B(scopedInstantiationService.createInstance($r7b, container2, { _hideReplaceToggle: true, showContextToggle: true, inputBoxStyles: searchEditorInputboxStyles, toggleStyles: $u$ }));
    this.B(this.Xb.onReplaceToggled(() => this.Mc()));
    this.B(this.Xb.onDidHeightChange(() => this.Mc()));
    this.B(this.Xb.onSearchSubmit(({ delay }) => this.triggerSearch({ delay })));
    if (this.Xb.searchInput) {
      this.B(this.Xb.searchInput.onDidOptionChange(() => this.triggerSearch({ resetCursor: false })));
    } else {
      this.xc.warn("SearchEditor: SearchWidget.searchInput is undefined, cannot register onDidOptionChange listener");
    }
    this.B(this.Xb.onDidToggleContext(() => this.triggerSearch({ resetCursor: false })));
    this.cc = $bk(container2, $(".includes-excludes"));
    const toggleQueryDetailsLabel = localize(9807, null);
    this.dc = $bk(this.cc, $(".expand" + ThemeIcon.asCSSSelector($96b), { tabindex: 0, role: "button", "aria-label": toggleQueryDetailsLabel }));
    this.B(this.yc.setupManagedHover($JZ("element"), this.dc, toggleQueryDetailsLabel));
    this.B($_i(this.dc, $7j.CLICK, (e) => {
      $9j.stop(e);
      this.Pc();
    }));
    this.B($_i(this.dc, $7j.KEY_UP, (e) => {
      const event = new $if(e);
      if (event.equals(
        3
        /* KeyCode.Enter */
      ) || event.equals(
        10
        /* KeyCode.Space */
      )) {
        $9j.stop(e);
        this.Pc();
      }
    }));
    this.B($_i(this.dc, $7j.KEY_DOWN, (e) => {
      const event = new $if(e);
      if (event.equals(
        1024 | 2
        /* KeyCode.Tab */
      )) {
        if (this.Xb.isReplaceActive()) {
          this.Xb.focusReplaceAllAction();
        } else {
          this.Xb.isReplaceShown() ? this.Xb.replaceInput?.focusOnPreserve() : this.Xb.focusRegexAction();
        }
        $9j.stop(e);
      }
    }));
    const folderIncludesList = $bk(this.cc, $(".file-types.includes"));
    const filesToIncludeTitle = localize(9808, null);
    $bk(folderIncludesList, $("h4", void 0, filesToIncludeTitle));
    this.ac = this.B(scopedInstantiationService.createInstance($G6b, folderIncludesList, this.sc, {
      ariaLabel: localize(9809, null),
      inputBoxStyles: searchEditorInputboxStyles
    }));
    this.ac.onSubmit((triggeredOnType) => this.triggerSearch({ resetCursor: false, delay: triggeredOnType ? this.Fc.searchOnTypeDebouncePeriod : 0 }));
    this.B(this.ac.onChangeSearchInEditorsBox(() => this.triggerSearch()));
    const excludesList = $bk(this.cc, $(".file-types.excludes"));
    const excludesTitle = localize(9810, null);
    $bk(excludesList, $("h4", void 0, excludesTitle));
    this.bc = this.B(scopedInstantiationService.createInstance($H6b, excludesList, this.sc, {
      ariaLabel: localize(9811, null),
      inputBoxStyles: searchEditorInputboxStyles
    }));
    this.bc.onSubmit((triggeredOnType) => this.triggerSearch({ resetCursor: false, delay: triggeredOnType ? this.Fc.searchOnTypeDebouncePeriod : 0 }));
    this.B(this.bc.onChangeIgnoreBox(() => this.triggerSearch()));
    this.ec = $bk(container2, $(".messages.text-search-provider-messages"));
    [this.Xb.searchInputFocusTracker, this.Xb.replaceInputFocusTracker, this.bc.inputFocusTracker, this.ac.inputFocusTracker].forEach((tracker2) => {
      if (!tracker2) {
        return;
      }
      this.B(tracker2.onDidFocus(() => setTimeout(() => inputBoxFocusedContextKey.set(true), 0)));
      this.B(tracker2.onDidBlur(() => inputBoxFocusedContextKey.set(false)));
    });
  }
  Bc(show2) {
    $$i(this.ec);
    this.kc.clear();
    if (show2) {
      const runAgainLink = $bk(this.ec, $("a.pointer.prominent.message", {}, localize(9812, null)));
      this.kc.add($_i(runAgainLink, $7j.CLICK, async () => {
        await this.triggerSearch();
        this.Yb.focus();
      }));
    }
  }
  Cc() {
    const skipContributions = [$Rkb.ID];
    return EditorExtensionsRegistry.getEditorContributions().filter((c) => skipContributions.indexOf(c.id) === -1);
  }
  Sb() {
    return { contributions: this.Cc() };
  }
  Ec() {
    this.Yb.onMouseUp((e) => {
      if (e.event.detail === 1) {
        const behaviour = this.Fc.searchEditor.singleClickBehaviour;
        const position = e.target.position;
        if (position && behaviour === "peekDefinition") {
          const line = this.Yb.getModel()?.getLineContent(position.lineNumber) ?? "";
          if (line.match(FILE_LINE_REGEX) || line.match(RESULT_LINE_REGEX)) {
            this.Yb.setSelection($9C.fromPositions(position));
            this.tc.executeCommand("editor.action.peekDefinition");
          }
        }
      } else if (e.event.detail === 2) {
        const behaviour = this.Fc.searchEditor.doubleClickBehaviour;
        const position = e.target.position;
        if (position && behaviour !== "selectWord") {
          const line = this.Yb.getModel()?.getLineContent(position.lineNumber) ?? "";
          if (line.match(RESULT_LINE_REGEX)) {
            this.Yb.setSelection($9C.fromPositions(position));
            this.tc.executeCommand(behaviour === "goToLocation" ? "editor.action.goToDeclaration" : "editor.action.openDeclarationToTheSide");
          } else if (line.match(FILE_LINE_REGEX)) {
            this.Yb.setSelection($9C.fromPositions(position));
            this.tc.executeCommand("editor.action.peekDefinition");
          }
        }
      }
    });
    this.B(this.Yb.onDidChangeModelContent(() => {
      if (!this.oc) {
        this.Nc()?.setDirty(true);
      }
    }));
  }
  getControl() {
    return this.Yb;
  }
  focus() {
    super.focus();
    const viewState = this.jb(this.Nc());
    if (viewState && viewState.focused === "editor") {
      this.Yb.focus();
    } else {
      this.Xb.focus();
    }
  }
  focusSearchInput() {
    this.Xb.searchInput?.focus();
  }
  focusFilesToIncludeInput() {
    if (!this.hc) {
      this.Pc(true);
    }
    this.ac.focus();
  }
  focusFilesToExcludeInput() {
    if (!this.hc) {
      this.Pc(true);
    }
    this.bc.focus();
  }
  focusNextInput() {
    if (this.Xb.searchInputHasFocus()) {
      if (this.hc) {
        this.ac.focus();
      } else {
        this.Yb.focus();
      }
    } else if (this.ac.inputHasFocus()) {
      this.bc.focus();
    } else if (this.bc.inputHasFocus()) {
      this.Yb.focus();
    } else if (this.Yb.hasWidgetFocus()) {
    }
  }
  focusPrevInput() {
    if (this.Xb.searchInputHasFocus()) {
      this.Yb.focus();
    } else if (this.ac.inputHasFocus()) {
      this.Xb.searchInput?.focus();
    } else if (this.bc.inputHasFocus()) {
      this.ac.focus();
    } else if (this.Yb.hasWidgetFocus()) {
    }
  }
  setQuery(query) {
    this.Xb.searchInput?.setValue(query);
  }
  selectQuery() {
    this.Xb.searchInput?.select();
  }
  toggleWholeWords() {
    this.Xb.searchInput?.setWholeWords(!this.Xb.searchInput.getWholeWords());
    this.triggerSearch({ resetCursor: false });
  }
  toggleRegex() {
    this.Xb.searchInput?.setRegex(!this.Xb.searchInput.getRegex());
    this.triggerSearch({ resetCursor: false });
  }
  toggleCaseSensitive() {
    this.Xb.searchInput?.setCaseSensitive(!this.Xb.searchInput.getCaseSensitive());
    this.triggerSearch({ resetCursor: false });
  }
  toggleContextLines() {
    this.Xb.toggleContextLines();
  }
  modifyContextLines(increase) {
    this.Xb.modifyContextLines(increase);
  }
  toggleQueryDetails(shouldShow) {
    this.Pc(shouldShow);
  }
  deleteResultBlock() {
    const linesToDelete = /* @__PURE__ */ new Set();
    const selections = this.Yb.getSelections();
    const model = this.Yb.getModel();
    if (!(selections && model)) {
      return;
    }
    const maxLine = model.getLineCount();
    const minLine = 1;
    const deleteUp = (start) => {
      for (let cursor = start; cursor >= minLine; cursor--) {
        const line = model.getLineContent(cursor);
        linesToDelete.add(cursor);
        if (line[0] !== void 0 && line[0] !== " ") {
          break;
        }
      }
    };
    const deleteDown = (start) => {
      linesToDelete.add(start);
      for (let cursor = start + 1; cursor <= maxLine; cursor++) {
        const line = model.getLineContent(cursor);
        if (line[0] !== void 0 && line[0] !== " ") {
          return cursor;
        }
        linesToDelete.add(cursor);
      }
      return;
    };
    const endingCursorLines = [];
    for (const selection of selections) {
      const lineNumber = selection.startLineNumber;
      endingCursorLines.push(deleteDown(lineNumber));
      deleteUp(lineNumber);
      for (let inner = selection.startLineNumber; inner <= selection.endLineNumber; inner++) {
        linesToDelete.add(inner);
      }
    }
    if (endingCursorLines.length === 0) {
      endingCursorLines.push(1);
    }
    const isDefined = (x) => x !== void 0;
    model.pushEditOperations(this.Yb.getSelections(), [...linesToDelete].map((line) => ({ range: new $9C(line, 1, line + 1, 1), text: "" })), () => endingCursorLines.filter(isDefined).map((line) => new $_D(line, 1, line, 1)));
  }
  cleanState() {
    this.Nc()?.setDirty(false);
  }
  get Fc() {
    return this.wc.getValue("search");
  }
  Gc(reverse) {
    const model = this.Yb.getModel();
    if (!model) {
      return;
    }
    const lastLine = model.getLineCount() ?? 1;
    const lastColumn = model.getLineLength(lastLine);
    const fallbackStart = reverse ? new $8C(lastLine, lastColumn) : new $8C(1, 1);
    const currentPosition = this.Yb.getSelection()?.getStartPosition() ?? fallbackStart;
    const matchRanges = this.Nc()?.getMatchRanges();
    if (!matchRanges) {
      return;
    }
    const matchRange = (reverse ? findPrevRange : findNextRange)(matchRanges, currentPosition);
    this.Yb.setSelection(matchRange);
    this.Yb.revealLineInCenterIfOutsideViewport(matchRange.startLineNumber);
    this.Yb.focus();
    const matchLineText = model.getLineContent(matchRange.startLineNumber);
    const matchText = model.getValueInRange(matchRange);
    let file = "";
    for (let line = matchRange.startLineNumber; line >= 1; line--) {
      const lineText = model.getValueInRange(new $9C(line, 1, line, 2));
      if (lineText !== " ") {
        file = model.getLineContent(line);
        break;
      }
    }
    $$Z(localize(9813, null, matchText, matchLineText, file.slice(0, file.length - 1)));
  }
  focusNextResult() {
    this.Gc(false);
  }
  focusPreviousResult() {
    this.Gc(true);
  }
  focusAllResults() {
    this.Yb.setSelections((this.Nc()?.getMatchRanges() ?? []).map((range) => new $_D(range.startLineNumber, range.startColumn, range.endLineNumber, range.endColumn)));
    this.Yb.focus();
  }
  async triggerSearch(_options) {
    const focusResults = this.Fc.searchEditor.focusResultsOnSearch;
    if (_options === void 0) {
      _options = { focusResults };
    } else if (_options.focusResults === void 0) {
      _options.focusResults = focusResults;
    }
    const options3 = { resetCursor: true, delay: 0, ..._options };
    if (!this.Xb.searchInput?.inputBox.isInputValid()) {
      return;
    }
    if (!this.gc) {
      await this.fc.trigger(async () => {
        this.Bc(false);
        await this.Ic();
        if (options3.resetCursor) {
          this.Yb.setPosition(new $8C(1, 1));
          this.Yb.setScrollPosition({ scrollTop: 0, scrollLeft: 0 });
        }
        if (options3.focusResults) {
          this.Yb.focus();
        }
      }, options3.delay);
    }
  }
  Hc() {
    return {
      isCaseSensitive: this.Xb.searchInput?.getCaseSensitive() ?? false,
      contextLines: this.Xb.getContextLines(),
      filesToExclude: this.bc.getValue(),
      filesToInclude: this.ac.getValue(),
      query: this.Xb.searchInput?.getValue() ?? "",
      isRegexp: this.Xb.searchInput?.getRegex() ?? false,
      matchWholeWord: this.Xb.searchInput?.getWholeWords() ?? false,
      useExcludeSettingsAndIgnoreFiles: this.bc.useExcludesAndIgnoreFiles(),
      onlyOpenEditors: this.ac.onlySearchInOpenEditors(),
      showIncludesExcludes: this.hc,
      notebookSearchConfig: {
        includeMarkupInput: this.Xb.getNotebookFilters().markupInput,
        includeMarkupPreview: this.Xb.getNotebookFilters().markupPreview,
        includeCodeInput: this.Xb.getNotebookFilters().codeInput,
        includeOutput: this.Xb.getNotebookFilters().codeOutput
      }
    };
  }
  async Ic() {
    this.mc.cancelSearch(true);
    const startInput = this.Nc();
    if (!startInput) {
      return;
    }
    this.jc.trigger(() => {
      this.Xb.searchInput?.onSearchSubmit();
      this.bc.onSearchSubmit();
      this.ac.onSearchSubmit();
    });
    const config = this.Hc();
    if (!config.query) {
      return;
    }
    const content = {
      pattern: config.query,
      isRegExp: config.isRegexp,
      isCaseSensitive: config.isCaseSensitive,
      isWordMatch: config.matchWholeWord
    };
    const options3 = {
      _reason: "searchEditor",
      extraFileResources: this.m.invokeFunction($hO),
      maxResults: this.Fc.maxResults ?? void 0,
      disregardIgnoreFiles: !config.useExcludeSettingsAndIgnoreFiles || void 0,
      disregardExcludeSettings: !config.useExcludeSettingsAndIgnoreFiles || void 0,
      excludePattern: [{ pattern: config.filesToExclude }],
      includePattern: config.filesToInclude,
      onlyOpenEditors: config.onlyOpenEditors,
      previewOptions: {
        matchLines: 1,
        charsPerLine: 1e3
      },
      surroundingContext: config.contextLines,
      isSmartCase: this.Fc.smartCase,
      expandPatterns: true,
      notebookSearchConfig: {
        includeMarkupInput: config.notebookSearchConfig.includeMarkupInput,
        includeMarkupPreview: config.notebookSearchConfig.includeMarkupPreview,
        includeCodeInput: config.notebookSearchConfig.includeCodeInput,
        includeOutput: config.notebookSearchConfig.includeOutput
      }
    };
    const folderResources = this.qc.getWorkspace().folders;
    let query;
    try {
      const queryBuilder = this.m.createInstance($eT);
      query = queryBuilder.text(content, folderResources.map((folder) => folder.uri), options3);
    } catch (err) {
      return;
    }
    this.ic.start(500);
    this.nc++;
    const { configurationModel } = await startInput.resolveModels();
    configurationModel.updateConfig(config);
    const result = this.mc.search(query);
    startInput.ongoingSearchOperation = result.asyncResults.finally(() => {
      this.nc--;
      if (this.nc === 0) {
        this.ic.stop();
      }
    });
    const searchOperation = await startInput.ongoingSearchOperation;
    await this.Jc(searchOperation, config, startInput);
  }
  async Jc(searchOperation, startConfig, startInput) {
    const input = this.Nc();
    if (!input || input !== startInput || JSON.stringify(startConfig) !== JSON.stringify(this.Hc())) {
      return;
    }
    input.ongoingSearchOperation = void 0;
    const sortOrder = this.Fc.sortOrder;
    if (sortOrder === "modified") {
      await this.Lc(this.mc.searchResult);
    }
    const controller = $hfb.get(this.Yb);
    controller?.closeWidget(false);
    const labelFormatter = (uri) => this.rc.getUriLabel(uri, { relative: true });
    const results = $V7b(this.mc.searchResult, startConfig.filesToInclude, startConfig.filesToExclude, startConfig.contextLines, labelFormatter, sortOrder, searchOperation?.limitHit);
    const { resultsModel } = await input.resolveModels();
    this.oc = true;
    this.pc.updateModel(resultsModel, results.text);
    this.oc = false;
    if (searchOperation && searchOperation.messages) {
      for (const message of searchOperation.messages) {
        this.Kc(message);
      }
    }
    this.Mc();
    input.setDirty(!input.hasCapability(
      4
      /* EditorInputCapabilities.Untitled */
    ));
    input.setMatchRanges(results.matchRanges);
  }
  Kc(message) {
    let messageBox;
    if (this.ec.firstChild) {
      messageBox = this.ec.firstChild;
    } else {
      messageBox = $bk(this.ec, $(".message"));
    }
    $bk(messageBox, $57b(message, this.m, this.vc, this.uc, this.tc, this.kc, () => this.triggerSearch()));
  }
  async Lc(searchResult) {
    const files = searchResult.matches().filter((f) => !f.fileStat).map((f) => f.resolveFileStat(this.xb));
    await Promise.all(files);
  }
  layout(dimension) {
    this.$b = dimension;
    this.Mc();
  }
  getSelected() {
    const selection = this.Yb.getSelection();
    if (selection) {
      return this.Yb.getModel()?.getValueInRange(selection) ?? "";
    }
    return "";
  }
  Mc() {
    if (this.$b) {
      this.Xb.setWidth(
        this.$b.width - 28
        /* container margin */
      );
      this.Yb.layout({ height: this.$b.height - $Bj(this.Zb), width: this.$b.width });
      this.bc.setWidth(
        this.$b.width - 28
        /* container margin */
      );
      this.ac.setWidth(
        this.$b.width - 28
        /* container margin */
      );
    }
  }
  Nc() {
    return this.input;
  }
  setSearchConfig(config) {
    this.Oc = config;
    if (config.query !== void 0) {
      this.Xb.setValue(config.query);
    }
    if (config.isCaseSensitive !== void 0) {
      this.Xb.searchInput?.setCaseSensitive(config.isCaseSensitive);
    }
    if (config.isRegexp !== void 0) {
      this.Xb.searchInput?.setRegex(config.isRegexp);
    }
    if (config.matchWholeWord !== void 0) {
      this.Xb.searchInput?.setWholeWords(config.matchWholeWord);
    }
    if (config.contextLines !== void 0) {
      this.Xb.setContextLines(config.contextLines);
    }
    if (config.filesToExclude !== void 0) {
      this.bc.setValue(config.filesToExclude);
    }
    if (config.filesToInclude !== void 0) {
      this.ac.setValue(config.filesToInclude);
    }
    if (config.onlyOpenEditors !== void 0) {
      this.ac.setOnlySearchInOpenEditors(config.onlyOpenEditors);
    }
    if (config.useExcludeSettingsAndIgnoreFiles !== void 0) {
      this.bc.setUseExcludesAndIgnoreFiles(config.useExcludeSettingsAndIgnoreFiles);
    }
    if (config.showIncludesExcludes !== void 0) {
      this.Pc(config.showIncludesExcludes);
    }
  }
  async setInput(newInput, options3, context, token) {
    await super.setInput(newInput, options3, context, token);
    if (token.isCancellationRequested) {
      return;
    }
    const { configurationModel, resultsModel } = await newInput.resolveModels();
    if (token.isCancellationRequested) {
      return;
    }
    this.Yb.setModel(resultsModel);
    this.gc = true;
    this.Bc(!newInput.ongoingSearchOperation && resultsModel.getLineCount() === 1 && resultsModel.getValueLength() === 0 && configurationModel.config.query !== "");
    this.setSearchConfig(configurationModel.config);
    this.B(configurationModel.onConfigDidUpdate((newConfig) => {
      if (newConfig !== this.Oc) {
        this.gc = true;
        this.setSearchConfig(newConfig);
        this.gc = false;
      }
    }));
    this.Tc(context);
    if (!options3?.preserveFocus) {
      this.focus();
    }
    this.gc = false;
    if (newInput.ongoingSearchOperation) {
      const existingConfig = this.Hc();
      newInput.ongoingSearchOperation.then((complete) => {
        this.Jc(complete, existingConfig, newInput);
      });
    }
  }
  Pc(_shouldShow) {
    const cls = "expanded";
    const shouldShow = _shouldShow ?? !this.cc.classList.contains(cls);
    if (shouldShow) {
      this.dc.setAttribute("aria-expanded", "true");
      this.cc.classList.add(cls);
    } else {
      this.dc.setAttribute("aria-expanded", "false");
      this.cc.classList.remove(cls);
    }
    this.hc = this.cc.classList.contains(cls);
    this.Mc();
  }
  pb(input) {
    if (input.typeId === $86b) {
      return input.modelUri;
    }
    return void 0;
  }
  mb(resource) {
    const control = this.getControl();
    const editorViewState = control.saveViewState();
    if (!editorViewState) {
      return void 0;
    }
    if (resource.toString() !== this.Nc()?.modelUri.toString()) {
      return void 0;
    }
    return { ...editorViewState, focused: this.Yb.hasWidgetFocus() ? "editor" : "input" };
  }
  nb(input) {
    return input.typeId === $86b;
  }
  Tc(context) {
    const viewState = this.jb(this.Nc(), context);
    if (viewState) {
      this.Yb.restoreViewState(viewState);
    }
  }
  getAriaLabel() {
    return this.Nc()?.getName() ?? localize(9814, null);
  }
};
$67b = $67b_1 = __decorate([
  __param(1, $zv),
  __param(2, $gs),
  __param(3, $jv),
  __param(4, $sG),
  __param(5, $Zk),
  __param(6, $ZI),
  __param(7, $Pk),
  __param(8, $40),
  __param(9, $sn),
  __param(10, $O4),
  __param(11, $PJ),
  __param(12, $ZJ),
  __param(13, $zG),
  __param(14, $iJ),
  __param(15, $mJ),
  __param(16, $kl),
  __param(17, $km),
  __param(18, $wn),
  __param(19, $5$)
], $67b);
var searchEditorTextInputBorder = $5n("searchEditor.textInputBorder", $zq, localize(9815, null));
function findNextRange(matchRanges, currentPosition) {
  for (const matchRange of matchRanges) {
    if ($8C.isBefore(currentPosition, matchRange.getStartPosition())) {
      return matchRange;
    }
  }
  return matchRanges[0];
}
function findPrevRange(matchRanges, currentPosition) {
  for (let i2 = matchRanges.length - 1; i2 >= 0; i2--) {
    const matchRange = matchRanges[i2];
    if ($8C.isBefore(matchRange.getStartPosition(), currentPosition)) {
      {
        return matchRange;
      }
    }
  }
  return matchRanges[matchRanges.length - 1];
}

// out-build/vs/workbench/contrib/searchEditor/browser/searchEditor.contribution.js
var OpenInEditorCommandId = "search.action.openInEditor";
var OpenNewEditorToSideCommandId = "search.action.openNewEditorToSide";
var FocusQueryEditorWidgetCommandId = "search.action.focusQueryEditorWidget";
var FocusQueryEditorFilesToIncludeCommandId = "search.action.focusFilesToInclude";
var FocusQueryEditorFilesToExcludeCommandId = "search.action.focusFilesToExclude";
var ToggleSearchEditorCaseSensitiveCommandId = "toggleSearchEditorCaseSensitive";
var ToggleSearchEditorWholeWordCommandId = "toggleSearchEditorWholeWord";
var ToggleSearchEditorRegexCommandId = "toggleSearchEditorRegex";
var IncreaseSearchEditorContextLinesCommandId = "increaseSearchEditorContextLines";
var DecreaseSearchEditorContextLinesCommandId = "decreaseSearchEditorContextLines";
var RerunSearchEditorSearchCommandId = "rerunSearchEditorSearch";
var CleanSearchEditorStateCommandId = "cleanSearchEditorState";
var SelectAllSearchEditorMatchesCommandId = "selectAllSearchEditorMatches";
$Wn.as($ZK.EditorPane).registerEditorPane($7tb.create($67b, $67b.ID, localize(9787, null)), [
  new $Nk($37b)
]);
var SearchEditorContribution = class SearchEditorContribution2 {
  static {
    this.ID = "workbench.contrib.searchEditor";
  }
  constructor(editorResolverService, instantiationService) {
    editorResolverService.registerEditor("*" + $27b, {
      id: $37b.ID,
      label: localize(9788, null),
      detail: $1K.providerDisplayName,
      priority: RegisteredEditorPriority.default
    }, {
      singlePerResource: true,
      canSupportResource: (resource) => $th(resource) === $27b
    }, {
      createEditorInput: ({ resource }) => {
        return { editor: instantiationService.invokeFunction($47b, { from: "existingFile", fileUri: resource }) };
      }
    });
  }
};
SearchEditorContribution = __decorate([
  __param(0, $4L),
  __param(1, $Pk)
], SearchEditorContribution);
$PL(
  SearchEditorContribution.ID,
  SearchEditorContribution,
  1
  /* WorkbenchPhase.BlockStartup */
);
var SearchEditorInputSerializer = class {
  canSerialize(input) {
    return !!input.tryReadConfigSync();
  }
  serialize(input) {
    if (!this.canSerialize(input)) {
      return void 0;
    }
    if (input.isDisposed()) {
      return JSON.stringify({ modelUri: void 0, dirty: false, config: input.tryReadConfigSync(), name: input.getName(), matchRanges: [], backingUri: input.backingUri?.toString() });
    }
    let modelUri = void 0;
    if (input.modelUri.path || input.modelUri.fragment && input.isDirty()) {
      modelUri = input.modelUri.toString();
    }
    const config = input.tryReadConfigSync();
    const dirty = input.isDirty();
    const matchRanges = dirty ? input.getMatchRanges() : [];
    const backingUri = input.backingUri;
    return JSON.stringify({ modelUri, dirty, config, name: input.getName(), matchRanges, backingUri: backingUri?.toString() });
  }
  deserialize(instantiationService, serializedEditorInput) {
    const { modelUri, dirty, config, matchRanges, backingUri } = JSON.parse(serializedEditorInput);
    if (config && config.query !== void 0) {
      if (modelUri) {
        const input = instantiationService.invokeFunction($47b, { from: "model", modelUri: URI.parse(modelUri), config, backupOf: backingUri ? URI.parse(backingUri) : void 0 });
        input.setDirty(dirty);
        input.setMatchRanges(matchRanges);
        return input;
      } else {
        if (backingUri) {
          return instantiationService.invokeFunction($47b, { from: "existingFile", fileUri: URI.parse(backingUri) });
        } else {
          return instantiationService.invokeFunction($47b, { from: "rawData", resultsContents: "", config });
        }
      }
    }
    return void 0;
  }
};
$Wn.as($ZK.EditorFactory).registerEditorSerializer($37b.ID, SearchEditorInputSerializer);
$tn.registerCommand(CleanSearchEditorStateCommandId, (accessor) => {
  const activeEditorPane = accessor.get($mJ).activeEditorPane;
  if (activeEditorPane instanceof $67b) {
    activeEditorPane.cleanState();
  }
});
var category3 = localize2(9790, "Search Editor");
var translateLegacyConfig = (legacyConfig = {}) => {
  const config = {};
  const overrides = {
    includes: "filesToInclude",
    excludes: "filesToExclude",
    wholeWord: "matchWholeWord",
    caseSensitive: "isCaseSensitive",
    regexp: "isRegexp",
    useIgnores: "useExcludeSettingsAndIgnoreFiles"
  };
  Object.entries(legacyConfig).forEach(([key2, value]) => {
    config[overrides[key2] ?? key2] = value;
  });
  return config;
};
var openArgMetadata = {
  description: "Open a new search editor. Arguments passed can include variables like ${relativeFileDirname}.",
  args: [{
    name: "Open new Search Editor args",
    schema: {
      properties: {
        query: { type: "string" },
        filesToInclude: { type: "string" },
        filesToExclude: { type: "string" },
        contextLines: { type: "number" },
        matchWholeWord: { type: "boolean" },
        isCaseSensitive: { type: "boolean" },
        isRegexp: { type: "boolean" },
        useExcludeSettingsAndIgnoreFiles: { type: "boolean" },
        showIncludesExcludes: { type: "boolean" },
        triggerSearch: { type: "boolean" },
        focusResults: { type: "boolean" },
        onlyOpenEditors: { type: "boolean" }
      }
    }
  }]
};
$hJ(class extends $gJ {
  constructor() {
    super({
      id: "search.searchEditor.action.deleteFileResults",
      title: localize2(9791, "Delete File Results"),
      keybinding: {
        weight: 100,
        primary: 2048 | 1024 | 1
      },
      precondition: $Z6b,
      category: category3,
      f1: true
    });
  }
  async run(accessor) {
    const contextService = accessor.get($on).getContext($Lj());
    if (contextService.getValue($Z6b.serialize())) {
      accessor.get($mJ).activeEditorPane.deleteResultBlock();
    }
  }
});
$hJ(class extends $gJ {
  constructor() {
    super({
      id: $56b,
      title: localize2(9792, "New Search Editor"),
      category: category3,
      f1: true,
      metadata: openArgMetadata
    });
  }
  async run(accessor, args2) {
    await accessor.get($Pk).invokeFunction($b8b, translateLegacyConfig({ location: "new", ...args2 }));
  }
});
$hJ(class extends $gJ {
  constructor() {
    super({
      id: $66b,
      title: localize2(9793, "Open Search Editor"),
      category: category3,
      f1: true,
      metadata: openArgMetadata
    });
  }
  async run(accessor, args2) {
    await accessor.get($Pk).invokeFunction($b8b, translateLegacyConfig({ location: "reuse", ...args2 }));
  }
});
$hJ(class extends $gJ {
  constructor() {
    super({
      id: OpenNewEditorToSideCommandId,
      title: localize2(9794, "Open New Search Editor to the Side"),
      category: category3,
      f1: true,
      metadata: openArgMetadata
    });
  }
  async run(accessor, args2) {
    await accessor.get($Pk).invokeFunction($b8b, translateLegacyConfig(args2), true);
  }
});
$hJ(class extends $gJ {
  constructor() {
    super({
      id: OpenInEditorCommandId,
      title: localize2(9795, "Open Results in Editor"),
      category: category3,
      f1: true,
      keybinding: {
        primary: 512 | 3,
        when: $7m.and($eRb.HasSearchResults, $eRb.SearchViewFocusedKey),
        weight: 200,
        mac: {
          primary: 2048 | 3
          /* KeyCode.Enter */
        }
      }
    });
  }
  async run(accessor) {
    const viewsService = accessor.get($uob);
    const instantiationService = accessor.get($Pk);
    const searchView = $V6b(viewsService);
    if (searchView) {
      await instantiationService.invokeFunction($c8b, searchView.searchResult, searchView.searchIncludePattern.getValue(), searchView.searchExcludePattern.getValue(), searchView.searchIncludePattern.onlySearchInOpenEditors());
    }
  }
});
$hJ(class extends $gJ {
  constructor() {
    super({
      id: RerunSearchEditorSearchCommandId,
      title: localize2(9796, "Search Again"),
      category: category3,
      keybinding: {
        primary: 2048 | 1024 | 48,
        when: $Z6b,
        weight: 100
        /* KeybindingWeight.EditorContrib */
      },
      icon: $e7b,
      menu: [
        {
          id: $bJ.EditorTitle,
          group: "navigation",
          when: $Dpb.isEqualTo($46b)
        },
        {
          id: $bJ.CommandPalette,
          when: $Dpb.isEqualTo($46b)
        }
      ]
    });
  }
  async run(accessor) {
    const editorService = accessor.get($mJ);
    const input = editorService.activeEditor;
    if (input instanceof $37b) {
      editorService.activeEditorPane.triggerSearch({ resetCursor: false });
    }
  }
});
$hJ(class extends $gJ {
  constructor() {
    super({
      id: FocusQueryEditorWidgetCommandId,
      title: localize2(9797, "Focus Search Editor Input"),
      category: category3,
      f1: true,
      precondition: $Z6b,
      keybinding: {
        primary: 9,
        weight: 100
        /* KeybindingWeight.EditorContrib */
      }
    });
  }
  async run(accessor) {
    const editorService = accessor.get($mJ);
    const input = editorService.activeEditor;
    if (input instanceof $37b) {
      editorService.activeEditorPane.focusSearchInput();
    }
  }
});
$hJ(class extends $gJ {
  constructor() {
    super({
      id: FocusQueryEditorFilesToIncludeCommandId,
      title: localize2(9798, "Focus Search Editor Files to Include"),
      category: category3,
      f1: true,
      precondition: $Z6b
    });
  }
  async run(accessor) {
    const editorService = accessor.get($mJ);
    const input = editorService.activeEditor;
    if (input instanceof $37b) {
      editorService.activeEditorPane.focusFilesToIncludeInput();
    }
  }
});
$hJ(class extends $gJ {
  constructor() {
    super({
      id: FocusQueryEditorFilesToExcludeCommandId,
      title: localize2(9799, "Focus Search Editor Files to Exclude"),
      category: category3,
      f1: true,
      precondition: $Z6b
    });
  }
  async run(accessor) {
    const editorService = accessor.get($mJ);
    const input = editorService.activeEditor;
    if (input instanceof $37b) {
      editorService.activeEditorPane.focusFilesToExcludeInput();
    }
  }
});
$hJ(class extends $gJ {
  constructor() {
    super({
      id: ToggleSearchEditorCaseSensitiveCommandId,
      title: localize2(9800, "Toggle Match Case"),
      category: category3,
      f1: true,
      precondition: $Z6b,
      keybinding: Object.assign({
        weight: 200,
        when: $eRb.SearchInputBoxFocusedKey
      }, $0fb)
    });
  }
  run(accessor) {
    $77b(accessor);
  }
});
$hJ(class extends $gJ {
  constructor() {
    super({
      id: ToggleSearchEditorWholeWordCommandId,
      title: localize2(9801, "Toggle Match Whole Word"),
      category: category3,
      f1: true,
      precondition: $Z6b,
      keybinding: Object.assign({
        weight: 200,
        when: $eRb.SearchInputBoxFocusedKey
      }, $$fb)
    });
  }
  run(accessor) {
    $87b(accessor);
  }
});
$hJ(class extends $gJ {
  constructor() {
    super({
      id: ToggleSearchEditorRegexCommandId,
      title: localize2(9802, "Toggle Use Regular Expression"),
      category: category3,
      f1: true,
      precondition: $Z6b,
      keybinding: Object.assign({
        weight: 200,
        when: $eRb.SearchInputBoxFocusedKey
      }, $_fb)
    });
  }
  run(accessor) {
    $97b(accessor);
  }
});
$hJ(class extends $gJ {
  constructor() {
    super({
      id: $76b,
      title: localize2(9803, "Toggle Context Lines"),
      category: category3,
      f1: true,
      precondition: $Z6b,
      keybinding: {
        weight: 200,
        primary: 512 | 42,
        mac: {
          primary: 2048 | 512 | 42
          /* KeyCode.KeyL */
        }
      }
    });
  }
  run(accessor) {
    $07b(accessor);
  }
});
$hJ(class extends $gJ {
  constructor() {
    super({
      id: IncreaseSearchEditorContextLinesCommandId,
      title: localize2(9804, "Increase Context Lines"),
      category: category3,
      f1: true,
      precondition: $Z6b,
      keybinding: {
        weight: 200,
        primary: 512 | 86
        /* KeyCode.Equal */
      }
    });
  }
  run(accessor) {
    $$7b(accessor, true);
  }
});
$hJ(class extends $gJ {
  constructor() {
    super({
      id: DecreaseSearchEditorContextLinesCommandId,
      title: localize2(9805, "Decrease Context Lines"),
      category: category3,
      f1: true,
      precondition: $Z6b,
      keybinding: {
        weight: 200,
        primary: 512 | 88
        /* KeyCode.Minus */
      }
    });
  }
  run(accessor) {
    $$7b(accessor, false);
  }
});
$hJ(class extends $gJ {
  constructor() {
    super({
      id: SelectAllSearchEditorMatchesCommandId,
      title: localize2(9806, "Select All Matches"),
      category: category3,
      f1: true,
      precondition: $Z6b,
      keybinding: {
        weight: 200,
        primary: 2048 | 1024 | 42
      }
    });
  }
  run(accessor) {
    $_7b(accessor);
  }
});
$hJ(class OpenSearchEditorAction extends $gJ {
  constructor() {
    super({
      id: "search.action.openNewEditorFromView",
      title: localize(9789, null),
      category: category3,
      icon: $m7b,
      menu: [{
        id: $bJ.ViewTitle,
        group: "navigation",
        order: 2,
        when: $7m.equals("view", $PN)
      }]
    });
  }
  run(accessor, ...args2) {
    return $a8b(accessor);
  }
});
var SearchEditorWorkingCopyEditorHandler = class SearchEditorWorkingCopyEditorHandler2 extends $3c {
  static {
    this.ID = "workbench.contrib.searchEditorWorkingCopyEditorHandler";
  }
  constructor(a, workingCopyEditorService) {
    super();
    this.a = a;
    this.B(workingCopyEditorService.registerHandler(this));
  }
  handles(workingCopy) {
    return workingCopy.resource.scheme === $16b;
  }
  isOpen(workingCopy, editor) {
    if (!this.handles(workingCopy)) {
      return false;
    }
    return editor instanceof $37b && $oh(workingCopy.resource, editor.modelUri);
  }
  createEditor(workingCopy) {
    const input = this.a.invokeFunction($47b, { from: "model", modelUri: workingCopy.resource });
    input.setDirty(true);
    return input;
  }
};
SearchEditorWorkingCopyEditorHandler = __decorate([
  __param(0, $Pk),
  __param(1, $6J)
], SearchEditorWorkingCopyEditorHandler);
$PL(
  SearchEditorWorkingCopyEditorHandler.ID,
  SearchEditorWorkingCopyEditorHandler,
  2
  /* WorkbenchPhase.BlockRestore */
);

// out-build/vs/workbench/contrib/sash/browser/sash.js
var $iac = class $iac2 {
  constructor(b, c) {
    this.b = b;
    this.c = c;
    this.a = new $2c();
    const onDidChangeSize = Event2.filter(b.onDidChangeConfiguration, (e) => e.affectsConfiguration("workbench.sash.size"));
    onDidChangeSize(this.d, this, this.a);
    this.d();
    const onDidChangeHoverDelay2 = Event2.filter(b.onDidChangeConfiguration, (e) => e.affectsConfiguration("workbench.sash.hoverDelay"));
    onDidChangeHoverDelay2(this.f, this, this.a);
    this.f();
  }
  d() {
    const configuredSize = this.b.getValue("workbench.sash.size");
    const size = $4i(configuredSize, 4, 20);
    const hoverSize = $4i(configuredSize, 1, 8);
    this.c.mainContainer.style.setProperty("--vscode-sash-size", size + "px");
    this.c.mainContainer.style.setProperty("--vscode-sash-hover-size", hoverSize + "px");
    $o2(size);
  }
  f() {
    $p2(this.b.getValue("workbench.sash.hoverDelay"));
  }
  dispose() {
    this.a.dispose();
  }
};
$iac = __decorate([
  __param(0, $kl),
  __param(1, $Ulb)
], $iac);

// out-build/vs/workbench/contrib/sash/browser/sash.contribution.js
$Wn.as(Extensions2.Workbench).registerWorkbenchContribution(
  $iac,
  3
  /* LifecyclePhase.Restored */
);
$Wn.as($Ht.Configuration).registerConfiguration({
  ...$UL,
  properties: {
    "workbench.sash.size": {
      type: "number",
      default: $u ? 20 : 4,
      minimum: 1,
      maximum: 20,
      description: localize(9365, null)
    },
    "workbench.sash.hoverDelay": {
      type: "number",
      default: 300,
      minimum: 0,
      maximum: 2e3,
      description: localize(9366, null)
    }
  }
});

// out-build/vs/workbench/contrib/scm/browser/activity.js
var ActiveRepositoryContextKeys = {
  ActiveRepositoryName: new $nn("scmActiveRepositoryName", ""),
  ActiveRepositoryBranchName: new $nn("scmActiveRepositoryBranchName", "")
};
var $jac = class $jac2 extends $3c {
  constructor(m, n, s, t, u, w, y) {
    super();
    this.m = m;
    this.n = n;
    this.s = s;
    this.t = t;
    this.u = u;
    this.w = w;
    this.y = y;
    this.a = $G9("scm.countBadge", "all", this.n);
    this.b = $Dd(this, Event2.any(this.t.onDidAddRepository, this.t.onDidRemoveRepository), () => this.t.repositories);
    this.c = $2d((reader) => {
      const repository = this.u.activeRepository.read(reader);
      const historyProvider = repository?.provider.historyProvider.read(reader);
      const historyItemRef = historyProvider?.historyItemRef.read(reader);
      return historyItemRef?.name;
    });
    this.f = $2d(this, (reader) => {
      switch (this.a.read(reader)) {
        case "all": {
          const repositories = this.b.read(reader);
          return [...Iterable.map(repositories, (r2) => ({ provider: r2.provider, resourceCount: this.z(r2) }))];
        }
        case "focused": {
          const repository = this.u.activeRepository.read(reader);
          return repository ? [{ provider: repository.provider, resourceCount: this.z(repository) }] : [];
        }
        case "off":
          return [];
        default:
          throw new Error("Invalid countBadge setting");
      }
    });
    this.g = $2d(this, (reader) => {
      let total = 0;
      for (const repository of this.f.read(reader)) {
        const count = repository.provider.count?.read(reader);
        const resourceCount = repository.resourceCount.read(reader);
        total = total + (count ?? resourceCount);
      }
      return total;
    });
    this.h = ActiveRepositoryContextKeys.ActiveRepositoryName.bindTo(this.s);
    this.j = ActiveRepositoryContextKeys.ActiveRepositoryBranchName.bindTo(this.s);
    this.y.registerVariables([
      { name: "activeRepositoryName", contextKey: ActiveRepositoryContextKeys.ActiveRepositoryName.key },
      { name: "activeRepositoryBranchName", contextKey: ActiveRepositoryContextKeys.ActiveRepositoryBranchName.key }
    ]);
    this.B($xd((reader, store) => {
      this.C(this.g.read(reader), store);
    }));
    this.B($xd((reader, store) => {
      const repository = this.u.activeRepository.read(reader);
      const commands2 = repository?.provider.statusBarCommands.read(reader);
      this.D(repository, commands2 ?? [], store);
    }));
    this.B($td((reader) => {
      const repository = this.u.activeRepository.read(reader);
      const historyItemRefName = this.c.read(reader);
      this.F(repository?.provider.name, historyItemRefName);
    }));
  }
  z(repository) {
    return $Dd(this, repository.provider.onDidChangeResources, () => (
      /** @description repositoryResourceCount */
      $YQb(repository.provider)
    ));
  }
  C(count, store) {
    if (count === 0) {
      return;
    }
    const badge = new $wqb(count, (num) => localize(9367, null, num));
    store.add(this.m.showViewActivity($aS, { badge }));
  }
  D(repository, commands2, store) {
    if (!repository) {
      return;
    }
    const label3 = repository.provider.rootUri ? `${$sh(repository.provider.rootUri)} (${repository.provider.label})` : repository.provider.label;
    for (let index = 0; index < commands2.length; index++) {
      const command4 = commands2[index];
      const tooltip = `${label3}${command4.tooltip ? ` - ${command4.tooltip}` : ""}`;
      let repoAgnosticActionName = command4.arguments?.[0];
      if (repoAgnosticActionName && typeof repoAgnosticActionName === "string") {
        repoAgnosticActionName = repoAgnosticActionName.substring(0, repoAgnosticActionName.lastIndexOf("/")).replace(/^git\./, "");
        if (repoAgnosticActionName.length > 1) {
          repoAgnosticActionName = repoAgnosticActionName[0].toLocaleUpperCase() + repoAgnosticActionName.slice(1);
        }
      } else {
        repoAgnosticActionName = "";
      }
      const statusbarEntry = {
        name: localize(9368, null) + (repoAgnosticActionName ? ` ${repoAgnosticActionName}` : ""),
        text: command4.title,
        ariaLabel: tooltip,
        tooltip,
        command: command4.id ? command4 : void 0
      };
      store.add(index === 0 ? this.w.addEntry(statusbarEntry, `status.scm.${index}`, 0, 1e4) : this.w.addEntry(statusbarEntry, `status.scm.${index}`, 0, { id: `status.scm.${index - 1}`, alignment: 1, compact: true }));
    }
  }
  F(repositoryName, branchName) {
    this.h.set(repositoryName ?? "");
    this.j.set(branchName ?? "");
  }
};
$jac = __decorate([
  __param(0, $vqb),
  __param(1, $kl),
  __param(2, $on),
  __param(3, $dS),
  __param(4, $eS),
  __param(5, $$qb),
  __param(6, $RTb)
], $jac);
var $kac = class $kac2 extends $3c {
  constructor(editorGroupsService, c, f) {
    super();
    this.c = c;
    this.f = f;
    this.a = $Dd(this, Event2.any(this.c.onDidAddRepository, this.c.onDidRemoveRepository), () => this.c.repositories);
    this.b = new $ze();
    const activeResourceHasChangesContextKey = new $nn("scmActiveResourceHasChanges", false, localize(9369, null));
    const activeResourceRepositoryContextKey = new $nn("scmActiveResourceRepository", void 0, localize(9370, null));
    this.q.add($xd((reader, store) => {
      for (const repository of this.a.read(reader)) {
        store.add(Event2.runAndSubscribe(repository.provider.onDidChangeResources, () => {
          this.b.fire();
        }));
      }
    }));
    const hasChangesContextKeyProvider = {
      contextKey: activeResourceHasChangesContextKey,
      getGroupContextKeyValue: (group2) => this.g(group2.activeEditor),
      onDidChange: this.b.event
    };
    const repositoryContextKeyProvider = {
      contextKey: activeResourceRepositoryContextKey,
      getGroupContextKeyValue: (group2) => this.h(group2.activeEditor),
      onDidChange: this.b.event
    };
    this.q.add(editorGroupsService.registerContextKeyProvider(hasChangesContextKeyProvider));
    this.q.add(editorGroupsService.registerContextKeyProvider(repositoryContextKeyProvider));
  }
  g(activeEditor) {
    const activeResource = $mL.getOriginalUri(activeEditor);
    if (!activeResource) {
      return false;
    }
    const activeResourceRepository = this.c.getRepository(activeResource);
    for (const resourceGroup of activeResourceRepository?.provider.groups ?? []) {
      if (resourceGroup.resources.some((scmResource) => this.f.extUri.isEqual(activeResource, scmResource.sourceUri))) {
        return true;
      }
    }
    return false;
  }
  h(activeEditor) {
    const activeResource = $mL.getOriginalUri(activeEditor);
    if (!activeResource) {
      return void 0;
    }
    const activeResourceRepository = this.c.getRepository(activeResource);
    return activeResourceRepository?.id;
  }
  dispose() {
    this.b.dispose();
    super.dispose();
  }
};
$kac = __decorate([
  __param(0, $iJ),
  __param(1, $dS),
  __param(2, $vl)
], $kac);

// out-build/vs/workbench/contrib/scm/common/scmService.js
var SCMInput = class extends $3c {
  get value() {
    return this.a;
  }
  get placeholder() {
    return this.c;
  }
  set placeholder(placeholder) {
    this.c = placeholder;
    this.f.fire(placeholder);
  }
  get enabled() {
    return this.g;
  }
  set enabled(enabled) {
    this.g = enabled;
    this.h.fire(enabled);
  }
  get visible() {
    return this.j;
  }
  set visible(visible) {
    this.j = visible;
    this.m.fire(visible);
  }
  setFocus() {
    this.n.fire();
  }
  showValidationMessage(message, type) {
    this.r.fire({ message, type });
  }
  get validateInput() {
    return this.s;
  }
  set validateInput(validateInput) {
    this.s = validateInput;
    this.t.fire();
  }
  constructor(repository, y) {
    super();
    this.repository = repository;
    this.y = y;
    this.a = "";
    this.b = new $ze();
    this.onDidChange = this.b.event;
    this.c = "";
    this.f = new $ze();
    this.onDidChangePlaceholder = this.f.event;
    this.g = true;
    this.h = new $ze();
    this.onDidChangeEnablement = this.h.event;
    this.j = true;
    this.m = new $ze();
    this.onDidChangeVisibility = this.m.event;
    this.n = new $ze();
    this.onDidChangeFocus = this.n.event;
    this.r = new $ze();
    this.onDidChangeValidationMessage = this.r.event;
    this.s = () => Promise.resolve(void 0);
    this.t = new $ze();
    this.onDidChangeValidateInput = this.t.event;
    this.w = false;
    if (this.repository.provider.rootUri) {
      this.u = y.getHistory(this.repository.provider.label, this.repository.provider.rootUri);
      this.B(this.y.onWillSaveHistory((event) => {
        if (this.u.isAtEnd()) {
          this.z();
        }
        if (this.w) {
          event.historyDidIndeedChange();
        }
        this.w = false;
      }));
    } else {
      this.u = new $G2([""], 100);
    }
    this.a = this.u.current();
  }
  setValue(value, transient, reason) {
    if (value === this.a) {
      return;
    }
    if (!transient) {
      this.u.replaceLast(this.a);
      this.u.add(value);
      this.w = true;
    }
    this.a = value;
    this.b.fire({ value, reason });
  }
  showNextHistoryValue() {
    if (this.u.isAtEnd()) {
      return;
    } else if (!this.u.has(this.value)) {
      this.z();
      this.u.resetCursor();
    }
    const value = this.u.next();
    this.setValue(value, true, SCMInputChangeReason.HistoryNext);
  }
  showPreviousHistoryValue() {
    if (this.u.isAtEnd()) {
      this.z();
    } else if (!this.u.has(this.a)) {
      this.z();
      this.u.resetCursor();
    }
    const value = this.u.previous();
    this.setValue(value, true, SCMInputChangeReason.HistoryPrevious);
  }
  z() {
    const oldValue = this.u.replaceLast(this.a);
    this.w = this.w || oldValue !== this.a;
  }
};
var SCMRepository = class {
  get selected() {
    return this.a;
  }
  constructor(id2, provider, c, inputHistory) {
    this.id = id2;
    this.provider = provider;
    this.c = c;
    this.a = false;
    this.b = new $ze();
    this.onDidChangeSelection = this.b.event;
    this.input = new SCMInput(this, inputHistory);
  }
  setSelected(selected) {
    if (this.a === selected) {
      return;
    }
    this.a = selected;
    this.b.fire(selected);
  }
  dispose() {
    this.c.dispose();
    this.provider.dispose();
  }
};
var WillSaveHistoryEvent = class {
  constructor() {
    this.a = false;
  }
  get didChangeHistory() {
    return this.a;
  }
  historyDidIndeedChange() {
    this.a = true;
  }
};
var SCMInputHistory = class SCMInputHistory2 {
  constructor(d, f) {
    this.d = d;
    this.f = f;
    this.a = new $2c();
    this.b = /* @__PURE__ */ new Map();
    this.c = this.a.add(new $ze());
    this.onWillSaveHistory = this.c.event;
    this.b = /* @__PURE__ */ new Map();
    const entries2 = this.d.getObject("scm.history", 1, []);
    for (const [providerLabel, rootUri, history] of entries2) {
      let providerHistories = this.b.get(providerLabel);
      if (!providerHistories) {
        providerHistories = new $Ec();
        this.b.set(providerLabel, providerHistories);
      }
      providerHistories.set(rootUri, new $G2(history, 100));
    }
    if (this.h()) {
      this.g();
    }
    this.a.add(this.d.onDidChangeValue(1, "scm.history", this.a)((e) => {
      if (e.external && e.key === "scm.history") {
        const raw = this.d.getObject("scm.history", 1, []);
        for (const [providerLabel, uri, rawHistory] of raw) {
          const history = this.getHistory(providerLabel, uri);
          for (const value of Iterable.reverse(rawHistory)) {
            history.prepend(value);
          }
        }
      }
    }));
    this.a.add(this.d.onWillSaveState((_) => {
      const event = new WillSaveHistoryEvent();
      this.c.fire(event);
      if (event.didChangeHistory) {
        this.g();
      }
    }));
  }
  g() {
    const raw = [];
    for (const [providerLabel, providerHistories] of this.b) {
      for (const [rootUri, history] of providerHistories) {
        if (!(history.size === 1 && history.current() === "")) {
          raw.push([providerLabel, rootUri, [...history]]);
        }
      }
    }
    this.d.store(
      "scm.history",
      raw,
      1,
      0
      /* StorageTarget.USER */
    );
  }
  getHistory(providerLabel, rootUri) {
    let providerHistories = this.b.get(providerLabel);
    if (!providerHistories) {
      providerHistories = new $Ec();
      this.b.set(providerLabel, providerHistories);
    }
    let history = providerHistories.get(rootUri);
    if (!history) {
      history = new $G2([""], 100);
      providerHistories.set(rootUri, history);
    }
    return history;
  }
  // Migrates from Application scope storage to Workspace scope.
  // TODO@joaomoreno: Change from January 2024 onwards such that the only code is to remove all `scm/input:` storage keys
  h() {
    let didSomethingChange = false;
    const machineKeys = Iterable.filter(this.d.keys(
      -1,
      1
      /* StorageTarget.MACHINE */
    ), (key2) => key2.startsWith("scm/input:"));
    for (const key2 of machineKeys) {
      try {
        const legacyHistory = JSON.parse(this.d.get(key2, -1, ""));
        const match = /^scm\/input:([^:]+):(.+)$/.exec(key2);
        if (!match || !Array.isArray(legacyHistory?.history) || !Number.isInteger(legacyHistory?.timestamp)) {
          this.d.remove(
            key2,
            -1
            /* StorageScope.APPLICATION */
          );
          continue;
        }
        const [, providerLabel, rootPath] = match;
        const rootUri = URI.file(rootPath);
        if (this.f.getWorkspaceFolder(rootUri)) {
          const history = this.getHistory(providerLabel, rootUri);
          for (const entry of Iterable.reverse(legacyHistory.history)) {
            history.prepend(entry);
          }
          didSomethingChange = true;
          this.d.remove(
            key2,
            -1
            /* StorageScope.APPLICATION */
          );
        }
      } catch {
        this.d.remove(
          key2,
          -1
          /* StorageScope.APPLICATION */
        );
      }
    }
    return didSomethingChange;
  }
  dispose() {
    this.a.dispose();
  }
};
SCMInputHistory = __decorate([
  __param(0, $jv),
  __param(1, $Zk)
], SCMInputHistory);
var $lac = class $lac2 {
  get repositories() {
    return this._repositories.values();
  }
  get repositoryCount() {
    return this._repositories.size;
  }
  constructor(f, workspaceContextService, contextKeyService, storageService, g) {
    this.f = f;
    this.g = g;
    this._repositories = /* @__PURE__ */ new Map();
    this.c = new $ze();
    this.onDidAddRepository = this.c.event;
    this.d = new $ze();
    this.onDidRemoveRepository = this.d.event;
    this.a = new SCMInputHistory(storageService, workspaceContextService);
    this.b = contextKeyService.createKey("scm.providerCount", 0);
  }
  registerSCMProvider(provider) {
    this.f.trace("SCMService#registerSCMProvider");
    if (this._repositories.has(provider.id)) {
      throw new Error(`SCM Provider ${provider.id} already exists.`);
    }
    const disposable = $1c(() => {
      this._repositories.delete(provider.id);
      this.d.fire(repository);
      this.b.set(this._repositories.size);
    });
    const repository = new SCMRepository(provider.id, provider, disposable, this.a);
    this._repositories.set(provider.id, repository);
    this.c.fire(repository);
    this.b.set(this._repositories.size);
    return repository;
  }
  getRepository(idOrResource) {
    if (typeof idOrResource === "string") {
      return this._repositories.get(idOrResource);
    }
    if (idOrResource.scheme !== Schemas.file && idOrResource.scheme !== Schemas.vscodeRemote) {
      return void 0;
    }
    let bestRepository = void 0;
    let bestMatchLength = Number.POSITIVE_INFINITY;
    for (const repository of this.repositories) {
      const root = repository.provider.rootUri;
      if (!root) {
        continue;
      }
      const path = this.g.extUri.relativePath(root, idOrResource);
      if (path && !/^\.\./.test(path) && path.length < bestMatchLength) {
        bestRepository = repository;
        bestMatchLength = path.length;
      }
    }
    return bestRepository;
  }
};
$lac = __decorate([
  __param(0, $wn),
  __param(1, $Zk),
  __param(2, $on),
  __param(3, $jv),
  __param(4, $vl)
], $lac);

// out-build/vs/workbench/contrib/scm/browser/scmViewPaneContainer.js
var $mac = class $mac2 extends $oqb {
  constructor(layoutService, telemetryService, instantiationService, contextMenuService, themeService, storageService, configurationService, extensionService, contextService, viewDescriptorService) {
    super($_R, { mergeViewWithContainerWhenSingleView: true }, instantiationService, configurationService, layoutService, contextMenuService, telemetryService, extensionService, themeService, storageService, contextService, viewDescriptorService);
  }
  create(parent) {
    super.create(parent);
    parent.classList.add("scm-viewlet");
  }
  getOptimalWidth() {
    return 400;
  }
  getTitle() {
    if (this.panes.length === 1) {
      if (this.panes[0].id === $aS || this.panes[0].id === $bS || this.panes[0].id === $cS) {
        return this.panes[0].title;
      } else {
        return super.getTitle();
      }
    }
    return localize(9531, null);
  }
};
$mac = __decorate([
  __param(0, $Vlb),
  __param(1, $zv),
  __param(2, $Pk),
  __param(3, $50),
  __param(4, $gs),
  __param(5, $jv),
  __param(6, $kl),
  __param(7, $wN),
  __param(8, $Zk),
  __param(9, $$M)
], $mac);

// out-build/vs/workbench/contrib/scm/browser/scmRepositoryRenderer.js
var $oac_1;
var $nac = class extends $Vm {
  constructor(a) {
    super();
    this.a = a;
  }
  async u(action, context) {
    if (!(action instanceof $fJ)) {
      return super.u(action, context);
    }
    const selection = this.a().map((r2) => r2.provider);
    const actionContext = selection.some((s) => s === context) ? selection : [context];
    await action.run(...actionContext);
  }
};
var $oac = class $oac2 {
  static {
    $oac_1 = this;
  }
  static {
    this.TEMPLATE_ID = "repository";
  }
  get templateId() {
    return $oac_1.TEMPLATE_ID;
  }
  constructor(a, b, d, f, g, h3, i2, j, k, l) {
    this.a = a;
    this.b = b;
    this.d = d;
    this.f = f;
    this.g = g;
    this.h = h3;
    this.i = i2;
    this.j = j;
    this.k = k;
    this.l = l;
  }
  renderTemplate(container2) {
    if (container2.classList.contains("monaco-tl-contents")) {
      container2.parentElement.parentElement.querySelector(".monaco-tl-twistie").classList.add("force-twistie");
    }
    const provider = $bk(container2, $(".scm-provider"));
    const label3 = $bk(provider, $(".label"));
    const labelCustomHover = this.h.setupManagedHover($JZ("mouse"), label3, "", {});
    const name = $bk(label3, $("span.name"));
    const description = $bk(label3, $("span.description"));
    const actions = $bk(provider, $(".actions"));
    const toolBar = new $3$(actions, { actionViewItemProvider: this.b, resetMenu: this.a }, this.j, this.f, this.g, this.i, this.d, this.l);
    const countContainer = $bk(provider, $(".count"));
    const count = new $D2(countContainer, {}, $E$);
    const visibilityDisposable = toolBar.onDidChangeDropdownVisibility((e) => provider.classList.toggle("active", e));
    const templateDisposable = $Zc(labelCustomHover, visibilityDisposable, toolBar);
    return { label: label3, labelCustomHover, name, description, countContainer, count, toolBar, elementDisposables: new $2c(), templateDisposable };
  }
  renderElement(arg, index, templateData, height) {
    const repository = $LQb(arg) ? arg : arg.element;
    templateData.name.textContent = repository.provider.name;
    if (repository.provider.rootUri) {
      templateData.labelCustomHover.update(`${repository.provider.label}: ${repository.provider.rootUri.fsPath}`);
      templateData.description.textContent = repository.provider.label;
    } else {
      templateData.labelCustomHover.update(repository.provider.label);
      templateData.description.textContent = "";
    }
    let statusPrimaryActions = [];
    let menuPrimaryActions = [];
    let menuSecondaryActions = [];
    const updateToolbar = () => {
      templateData.toolBar.setActions([...statusPrimaryActions, ...menuPrimaryActions], menuSecondaryActions);
    };
    templateData.elementDisposables.add($td((reader) => {
      const commands2 = repository.provider.statusBarCommands.read(reader) ?? [];
      statusPrimaryActions = commands2.map((c) => new $VQb(c, this.d));
      updateToolbar();
    }));
    templateData.elementDisposables.add($td((reader) => {
      const count = repository.provider.count.read(reader) ?? $YQb(repository.provider);
      templateData.countContainer.setAttribute("data-count", String(count));
      templateData.count.setCount(count);
    }));
    const repositoryMenus = this.k.menus.getRepositoryMenus(repository.provider);
    const menu = this.a === $bJ.SCMTitle ? repositoryMenus.titleMenu.menu : repositoryMenus.repositoryMenu;
    templateData.elementDisposables.add($TQb(menu, (primary, secondary) => {
      menuPrimaryActions = primary;
      menuSecondaryActions = secondary;
      updateToolbar();
    }));
    templateData.toolBar.context = repository.provider;
  }
  renderCompressedElements() {
    throw new Error("Should never happen since node is incompressible");
  }
  disposeElement(group2, index, template) {
    template.elementDisposables.clear();
  }
  disposeTemplate(templateData) {
    templateData.elementDisposables.dispose();
    templateData.templateDisposable.dispose();
    templateData.count.dispose();
  }
};
$oac = $oac_1 = __decorate([
  __param(2, $sn),
  __param(3, $on),
  __param(4, $50),
  __param(5, $5$),
  __param(6, $Ty),
  __param(7, $cJ),
  __param(8, $eS),
  __param(9, $zv)
], $oac);

// out-build/vs/workbench/contrib/scm/browser/menus.js
function actionEquals(a, b) {
  return a.id === b.id;
}
var repositoryMenuDisposables = new $2c();
$dJ.onDidChangeMenu((e) => {
  if (e.has($bJ.SCMTitle)) {
    repositoryMenuDisposables.clear();
    for (const menuItem of $dJ.getMenuItems($bJ.SCMTitle)) {
      repositoryMenuDisposables.add($dJ.appendMenuItem($bJ.SCMSourceControlInline, menuItem));
    }
  }
});
var $pac = class $pac2 {
  get actions() {
    return this.c;
  }
  get secondaryActions() {
    return this.d;
  }
  constructor(menuService, contextKeyService) {
    this.c = [];
    this.d = [];
    this.f = new $ze();
    this.onDidChangeTitle = this.f.event;
    this.g = new $2c();
    this.menu = menuService.createMenu($bJ.SCMTitle, contextKeyService);
    this.g.add(this.menu);
    this.menu.onDidChange(this.h, this, this.g);
    this.h();
  }
  h() {
    const { primary, secondary } = $Q$(this.menu.getActions({ shouldForwardArgs: true }));
    if ($zb(primary, this.c, actionEquals) && $zb(secondary, this.d, actionEquals)) {
      return;
    }
    this.c = primary;
    this.d = secondary;
    this.f.fire();
  }
  dispose() {
    this.g.dispose();
  }
};
$pac = __decorate([
  __param(0, $cJ),
  __param(1, $on)
], $pac);
var SCMMenusItem = class {
  get resourceGroupMenu() {
    if (!this.c) {
      this.c = this.i.createMenu($bJ.SCMResourceGroupContext, this.h);
    }
    return this.c;
  }
  get resourceFolderMenu() {
    if (!this.d) {
      this.d = this.i.createMenu($bJ.SCMResourceFolderContext, this.h);
    }
    return this.d;
  }
  constructor(h3, i2) {
    this.h = h3;
    this.i = i2;
  }
  getResourceMenu(resource) {
    if (typeof resource.contextValue === "undefined") {
      if (!this.f) {
        this.f = this.i.createMenu($bJ.SCMResourceContext, this.h);
      }
      return this.f;
    }
    if (!this.g) {
      this.g = /* @__PURE__ */ new Map();
    }
    let item = this.g.get(resource.contextValue);
    if (!item) {
      const contextKeyService = this.h.createOverlay([["scmResourceState", resource.contextValue]]);
      const menu = this.i.createMenu($bJ.SCMResourceContext, contextKeyService);
      item = {
        menu,
        dispose() {
          menu.dispose();
        }
      };
      this.g.set(resource.contextValue, item);
    }
    return item.menu;
  }
  dispose() {
    this.c?.dispose();
    this.d?.dispose();
    this.f?.dispose();
    if (this.g) {
      $Xc(this.g.values());
      this.g.clear();
      this.g = void 0;
    }
  }
};
var $qac = class $qac2 {
  get repositoryContextMenu() {
    if (!this.f) {
      this.f = this.i.createMenu($bJ.SCMSourceControl, this.c);
      this.g.add(this.f);
    }
    return this.f;
  }
  constructor(h3, contextKeyService, instantiationService, i2) {
    this.h = h3;
    this.i = i2;
    this.d = /* @__PURE__ */ new Map();
    this.g = new $2c();
    this.c = contextKeyService.createOverlay([
      ["scmProvider", h3.contextValue],
      ["scmProviderRootUri", h3.rootUri?.toString()],
      ["scmProviderHasRootUri", !!h3.rootUri]
    ]);
    const serviceCollection = new $Ok([$on, this.c]);
    instantiationService = instantiationService.createChild(serviceCollection, this.g);
    this.titleMenu = instantiationService.createInstance($pac);
    this.g.add(this.titleMenu);
    this.repositoryMenu = i2.createMenu($bJ.SCMSourceControlInline, this.c);
    this.g.add(this.repositoryMenu);
    h3.onDidChangeResourceGroups(this.k, this, this.g);
    this.k();
  }
  getResourceGroupMenu(group2) {
    return this.j(group2).resourceGroupMenu;
  }
  getResourceMenu(resource) {
    return this.j(resource.resourceGroup).getResourceMenu(resource);
  }
  getResourceFolderMenu(group2) {
    return this.j(group2).resourceFolderMenu;
  }
  j(group2) {
    let result = this.d.get(group2);
    if (!result) {
      const contextKeyService = this.c.createOverlay([
        ["scmResourceGroup", group2.id],
        ["multiDiffEditorEnableViewChanges", group2.multiDiffEditorEnableViewChanges]
      ]);
      result = new SCMMenusItem(contextKeyService, this.i);
      this.d.set(group2, result);
    }
    return result;
  }
  k() {
    for (const resourceGroup of this.d.keys()) {
      if (!this.h.groups.includes(resourceGroup)) {
        this.d.get(resourceGroup)?.dispose();
        this.d.delete(resourceGroup);
      }
    }
  }
  dispose() {
    this.g.dispose();
    this.d.forEach((item) => item.dispose());
  }
};
$qac = __decorate([
  __param(1, $on),
  __param(2, $Pk),
  __param(3, $cJ)
], $qac);
var $rac = class $rac2 {
  constructor(scmService, f) {
    this.f = f;
    this.c = new $2c();
    this.d = /* @__PURE__ */ new Map();
    this.titleMenu = f.createInstance($pac);
    scmService.onDidRemoveRepository(this.g, this, this.c);
  }
  g(repository) {
    const menus = this.d.get(repository.provider);
    menus?.dispose();
    this.d.delete(repository.provider);
  }
  getRepositoryMenus(provider) {
    let result = this.d.get(provider);
    if (!result) {
      const menus = this.f.createInstance($qac, provider);
      const dispose = () => {
        menus.dispose();
        this.d.delete(provider);
      };
      result = { menus, dispose };
      this.d.set(provider, result);
    }
    return result.menus;
  }
  dispose() {
    this.c.dispose();
  }
};
$rac = __decorate([
  __param(0, $dS),
  __param(1, $Pk)
], $rac);
$dJ.appendMenuItem($bJ.SCMResourceContext, {
  title: localize(9396, null),
  submenu: $bJ.SCMResourceContextShare,
  group: "45_share",
  order: 3
});

// out-build/vs/workbench/contrib/scm/browser/scmViewService.js
function getProviderStorageKey(provider) {
  return `${provider.contextValue}:${provider.label}${provider.rootUri ? `:${provider.rootUri.toString()}` : ""}`;
}
function getRepositoryName(workspaceContextService, repository) {
  if (!repository.provider.rootUri) {
    return repository.provider.label;
  }
  const folder = workspaceContextService.getWorkspaceFolder(repository.provider.rootUri);
  return folder?.uri.toString() === repository.provider.rootUri.toString() ? folder.name : $sh(repository.provider.rootUri);
}
var $sac = {
  RepositorySortKey: new $nn(
    "scmRepositorySortKey",
    "discoveryTime"
    /* ISCMRepositorySortKey.DiscoveryTime */
  )
};
var $tac = class $tac2 {
  get repositories() {
    return this.f.map((r2) => r2.repository);
  }
  get visibleRepositories() {
    if (this.n === "discoveryTime") {
      return this.f.filter((r2) => r2.selectionIndex !== -1).sort((r1, r2) => r1.selectionIndex - r2.selectionIndex).map((r2) => r2.repository);
    }
    return this.f.filter((r2) => r2.selectionIndex !== -1).map((r2) => r2.repository);
  }
  set visibleRepositories(visibleRepositories) {
    const set = new Set(visibleRepositories);
    const added = /* @__PURE__ */ new Set();
    const removed = /* @__PURE__ */ new Set();
    for (const repositoryView of this.f) {
      if (!set.has(repositoryView.repository) && repositoryView.selectionIndex !== -1) {
        repositoryView.selectionIndex = -1;
        removed.add(repositoryView.repository);
      }
      if (set.has(repositoryView.repository)) {
        if (repositoryView.selectionIndex === -1) {
          added.add(repositoryView.repository);
        }
        repositoryView.selectionIndex = visibleRepositories.indexOf(repositoryView.repository);
      }
    }
    if (added.size === 0 && removed.size === 0) {
      return;
    }
    this.h.fire({ added, removed });
    if (this.f.find((r2) => r2.focused && r2.selectionIndex === -1)) {
      this.focus(this.f.find((r2) => r2.selectionIndex !== -1)?.repository);
    }
  }
  get focusedRepository() {
    return this.f.find((r2) => r2.focused)?.repository;
  }
  constructor(p, contextKeyService, q, extensionService, instantiationService, s, t, u) {
    this.p = p;
    this.q = q;
    this.s = s;
    this.t = t;
    this.u = u;
    this.a = false;
    this.b = false;
    this.d = new $2c();
    this.f = [];
    this.g = new $ze();
    this.onDidChangeRepositories = this.g.event;
    this.h = new $ze();
    this.onDidChangeVisibleRepositories = Event2.any(this.h.event, Event2.debounce(this.g.event, (last, e) => {
      if (!last) {
        return e;
      }
      const added = new Set(last.added);
      const removed = new Set(last.removed);
      for (const repository of e.added) {
        if (removed.has(repository)) {
          removed.delete(repository);
        } else {
          added.add(repository);
        }
      }
      for (const repository of e.removed) {
        if (added.has(repository)) {
          added.delete(repository);
        } else {
          removed.add(repository);
        }
      }
      return { added, removed };
    }, 0, void 0, void 0, void 0, this.d));
    this.i = new $ze();
    this.onDidFocusRepository = this.i.event;
    this.j = $Ed({
      owner: this,
      equalsFn: () => false
    }, this.onDidFocusRepository, () => this.focusedRepository);
    this.k = $Ed({
      owner: this,
      equalsFn: () => false
    }, this.q.onDidActiveEditorChange, () => this.q.activeEditor);
    this.l = $Pd(this, (reader, lastValue) => {
      const activeEditor = this.k.read(reader);
      const activeResource = $mL.getOriginalUri(activeEditor);
      if (!activeResource) {
        return lastValue;
      }
      const repository = this.p.getRepository(activeResource);
      if (!repository) {
        return lastValue;
      }
      return Object.create(repository);
    });
    this.m = $Ud(this, [this.l, this.j]);
    this.activeRepository = $4d({
      owner: this,
      equalsFn: (r1, r2) => r1?.id === r2?.id
    }, (reader) => this.m.read(reader));
    this.menus = instantiationService.createInstance($rac);
    try {
      this.c = JSON.parse(t.get("scm:view:visibleRepositories", 1, ""));
    } catch {
    }
    this.n = this.c?.sortKey ?? this.z();
    this.o = $sac.RepositorySortKey.bindTo(contextKeyService);
    this.o.set(this.n);
    p.onDidAddRepository(this.v, this, this.d);
    p.onDidRemoveRepository(this.w, this, this.d);
    for (const repository of p.repositories) {
      this.v(repository);
    }
    t.onWillSaveState(this.B, this, this.d);
    extensionService.onWillStop(() => {
      this.B();
      this.a = false;
    }, this, this.d);
  }
  v(repository) {
    if (!this.a) {
      this.C();
    }
    const repositoryView = {
      repository,
      discoveryTime: Date.now(),
      focused: false,
      selectionIndex: -1
    };
    let removed = Iterable.empty();
    if (this.c && !this.a) {
      const index = this.c.all.indexOf(getProviderStorageKey(repository.provider));
      if (index === -1) {
        const added = [];
        this.A(this.f, repositoryView);
        this.f.forEach((repositoryView2, index2) => {
          if (repositoryView2.selectionIndex === -1) {
            added.push(repositoryView2.repository);
          }
          repositoryView2.selectionIndex = index2;
        });
        this.g.fire({ added, removed: Iterable.empty() });
        this.b = false;
        return;
      }
      if (this.c.visible.indexOf(index) === -1) {
        if (this.b) {
          this.A(this.f, repositoryView);
          this.g.fire({ added: Iterable.empty(), removed: Iterable.empty() });
          return;
        }
      } else {
        if (!this.b) {
          removed = [...this.visibleRepositories];
          this.f.forEach((r2) => {
            r2.focused = false;
            r2.selectionIndex = -1;
          });
          this.b = true;
        }
      }
    }
    const maxSelectionIndex = this.y();
    this.A(this.f, { ...repositoryView, selectionIndex: maxSelectionIndex + 1 });
    this.g.fire({ added: [repositoryView.repository], removed });
    if (!this.f.find((r2) => r2.focused)) {
      this.focus(repository);
    }
  }
  w(repository) {
    if (!this.a) {
      this.C();
    }
    const repositoriesIndex = this.f.findIndex((r2) => r2.repository === repository);
    if (repositoriesIndex === -1) {
      return;
    }
    let added = Iterable.empty();
    const repositoryView = this.f.splice(repositoriesIndex, 1);
    if (this.f.length > 0 && this.visibleRepositories.length === 0) {
      this.f[0].selectionIndex = 0;
      added = [this.f[0].repository];
    }
    this.g.fire({ added, removed: repositoryView.map((r2) => r2.repository) });
    if (repositoryView.length === 1 && repositoryView[0].focused && this.visibleRepositories.length > 0) {
      this.focus(this.visibleRepositories[0]);
    }
  }
  isVisible(repository) {
    return this.f.find((r2) => r2.repository === repository)?.selectionIndex !== -1;
  }
  toggleVisibility(repository, visible) {
    if (typeof visible === "undefined") {
      visible = !this.isVisible(repository);
    } else if (this.isVisible(repository) === visible) {
      return;
    }
    if (visible) {
      this.visibleRepositories = [...this.visibleRepositories, repository];
    } else {
      const index = this.visibleRepositories.indexOf(repository);
      if (index > -1) {
        this.visibleRepositories = [
          ...this.visibleRepositories.slice(0, index),
          ...this.visibleRepositories.slice(index + 1)
        ];
      }
    }
  }
  toggleSortKey(sortKey) {
    this.n = sortKey;
    this.o.set(this.n);
    this.f.sort(this.x.bind(this));
    this.g.fire({ added: Iterable.empty(), removed: Iterable.empty() });
  }
  focus(repository) {
    if (repository && !this.isVisible(repository)) {
      return;
    }
    this.f.forEach((r2) => r2.focused = r2.repository === repository);
    if (this.f.find((r2) => r2.focused)) {
      this.i.fire(repository);
    }
  }
  x(op1, op2) {
    if (this.n === "discoveryTime") {
      return op1.discoveryTime - op2.discoveryTime;
    }
    if (this.n === "path" && op1.repository.provider.rootUri && op2.repository.provider.rootUri) {
      return $OM(op1.repository.provider.rootUri.fsPath, op2.repository.provider.rootUri.fsPath);
    }
    const name1 = getRepositoryName(this.u, op1.repository);
    const name2 = getRepositoryName(this.u, op2.repository);
    const nameComparison = $EM(name1, name2);
    if (nameComparison === 0 && op1.repository.provider.rootUri && op2.repository.provider.rootUri) {
      return $OM(op1.repository.provider.rootUri.fsPath, op2.repository.provider.rootUri.fsPath);
    }
    return nameComparison;
  }
  y() {
    return this.f.length === 0 ? -1 : Math.max(...this.f.map((r2) => r2.selectionIndex));
  }
  z() {
    const sortOder = this.s.getValue("scm.repositories.sortOrder");
    switch (sortOder) {
      case "discovery time":
        return "discoveryTime";
      case "name":
        return "name";
      case "path":
        return "path";
      default:
        return "discoveryTime";
    }
  }
  A(repositories, repositoryView) {
    const index = $Bb(repositories, repositoryView, this.x.bind(this));
    repositories.splice(index < 0 ? ~index : index, 0, repositoryView);
  }
  B() {
    if (!this.a) {
      return;
    }
    const all = this.repositories.map((r2) => getProviderStorageKey(r2.provider));
    const visible = this.visibleRepositories.map((r2) => all.indexOf(getProviderStorageKey(r2.provider)));
    this.c = { all, sortKey: this.n, visible };
    this.t.store(
      "scm:view:visibleRepositories",
      JSON.stringify(this.c),
      1,
      1
      /* StorageTarget.MACHINE */
    );
  }
  C() {
    this.D();
  }
  D() {
    if (this.a) {
      return;
    }
    this.a = true;
  }
  dispose() {
    this.d.dispose();
    this.g.dispose();
    this.h.dispose();
  }
};
__decorate([
  $$t(5e3)
], $tac.prototype, "C", null);
$tac = __decorate([
  __param(0, $dS),
  __param(1, $on),
  __param(2, $mJ),
  __param(3, $wN),
  __param(4, $Pk),
  __param(5, $kl),
  __param(6, $jv),
  __param(7, $Zk)
], $tac);

// out-build/vs/workbench/contrib/multiDiffEditor/browser/scmMultiDiffSourceResolver.js
var $uac_1;
var $uac = class $uac2 {
  static {
    $uac_1 = this;
  }
  static {
    this.b = "scm-multi-diff-source";
  }
  static getMultiDiffSourceUri(repositoryUri, groupId) {
    return URI.from({
      scheme: $uac_1.b,
      query: JSON.stringify({ repositoryUri, groupId })
    });
  }
  static c(uri) {
    if (uri.scheme !== $uac_1.b) {
      return void 0;
    }
    let query;
    try {
      query = JSON.parse(uri.query);
    } catch (e) {
      return void 0;
    }
    if (typeof query !== "object" || query === null) {
      return void 0;
    }
    const { repositoryUri, groupId } = query;
    if (typeof repositoryUri !== "string" || typeof groupId !== "string") {
      return void 0;
    }
    return { repositoryUri: URI.parse(repositoryUri), groupId };
  }
  constructor(d, f) {
    this.d = d;
    this.f = f;
  }
  canHandleUri(uri) {
    return $uac_1.c(uri) !== void 0;
  }
  async resolveDiffSource(uri) {
    const { repositoryUri, groupId } = $uac_1.c(uri);
    const repository = await $re($Dd(this, this.d.onDidAddRepository, () => [...this.d.repositories].find((r2) => r2.provider.rootUri?.toString() === repositoryUri.toString())));
    const group2 = await $re($Dd(this, repository.provider.onDidChangeResourceGroups, () => repository.provider.groups.find((g) => g.id === groupId)));
    const scmActivities = $Dd(this.f.onDidChangeActivity, () => [...this.f.getViewContainerActivities("workbench.view.scm")]);
    const scmViewHasNoProgressBadge = scmActivities.map((activities) => !activities.some((a) => a.badge instanceof $yqb));
    await $re(scmViewHasNoProgressBadge, (v) => v);
    return new ScmResolvedMultiDiffSource(group2, repository);
  }
};
$uac = $uac_1 = __decorate([
  __param(0, $dS),
  __param(1, $vqb)
], $uac);
var ScmResolvedMultiDiffSource = class {
  constructor(c, d) {
    this.c = c;
    this.d = d;
    this.b = $Dd(this.c.onDidChangeResources, () => (
      /** @description resources */
      this.c.resources.map((e) => new $UDb(e.multiDiffEditorOriginalUri, e.multiDiffEditorModifiedUri, e.sourceUri))
    ));
    this.resources = new $Sd(this.b);
    this.contextKeys = {
      scmResourceGroup: this.c.id,
      scmProvider: this.d.provider.contextValue
    };
  }
};
var $vac = class $vac2 extends $3c {
  static {
    this.ID = "workbench.contrib.scmMultiDiffSourceResolver";
  }
  constructor(instantiationService, multiDiffSourceResolverService) {
    super();
    this.B(multiDiffSourceResolverService.registerResolver(instantiationService.createInstance($uac)));
  }
};
$vac = __decorate([
  __param(0, $Pk),
  __param(1, $TDb)
], $vac);
var $wac = class _$wac extends $gJ {
  static async openMultiFileDiffEditor(editorService, label3, repositoryRootUri, resourceGroupId, options3) {
    if (!repositoryRootUri) {
      return;
    }
    const multiDiffSource = $uac.getMultiDiffSourceUri(repositoryRootUri.toString(), resourceGroupId);
    return await editorService.openEditor({ label: label3, multiDiffSource, options: options3 });
  }
  constructor() {
    super({
      id: "_workbench.openScmMultiDiffEditor",
      title: localize2(8073, "View Changes"),
      f1: false
    });
  }
  async run(accessor, options3) {
    const editorService = accessor.get($mJ);
    await _$wac.openMultiFileDiffEditor(editorService, options3.title, URI.revive(options3.repositoryUri), options3.resourceGroupId);
  }
};

// out-build/vs/workbench/contrib/scm/browser/scmViewPane.js
var $xac_1;
var InputRenderer_1;
var ResourceGroupRenderer_1;
var ResourceRenderer_1;
var SCMInputWidget_1;
function processResourceFilterData(uri, filterData) {
  if (!filterData) {
    return [void 0, void 0];
  }
  if (!filterData.label) {
    const matches2 = $Ul(filterData);
    return [matches2, void 0];
  }
  const fileName = $sh(uri);
  const label3 = filterData.label;
  const pathLength = label3.length - fileName.length;
  const matches = $Ul(filterData.score);
  if (label3 === fileName) {
    return [matches, void 0];
  }
  const labelMatches = [];
  const descriptionMatches = [];
  for (const match of matches) {
    if (match.start > pathLength) {
      labelMatches.push({
        start: match.start - pathLength,
        end: match.end - pathLength
      });
    } else if (match.end < pathLength) {
      descriptionMatches.push(match);
    } else {
      labelMatches.push({
        start: 0,
        end: match.end - pathLength
      });
      descriptionMatches.push({
        start: match.start,
        end: pathLength
      });
    }
  }
  return [labelMatches, descriptionMatches];
}
var $xac = class $xac2 {
  static {
    $xac_1 = this;
  }
  static {
    this.DEFAULT_HEIGHT = 30;
  }
  static {
    this.TEMPLATE_ID = "actionButton";
  }
  get templateId() {
    return $xac_1.TEMPLATE_ID;
  }
  constructor(c, d, f) {
    this.c = c;
    this.d = d;
    this.f = f;
    this.b = /* @__PURE__ */ new Map();
  }
  renderTemplate(container2) {
    container2.parentElement.parentElement.querySelector(".monaco-tl-twistie").classList.add("force-no-twistie");
    container2.parentElement.parentElement.classList.add("cursor-default", "force-no-hover");
    const buttonContainer = $bk(container2, $(".button-container"));
    const actionButton = new $Dac(buttonContainer, this.d, this.c, this.f);
    return { actionButton, disposable: $3c.None, templateDisposable: actionButton };
  }
  renderElement(node, index, templateData, height) {
    templateData.disposable.dispose();
    const disposables = new $2c();
    const actionButton = node.element;
    templateData.actionButton.setButton(node.element.button);
    this.b.set(actionButton, templateData.actionButton);
    disposables.add({ dispose: () => this.b.delete(actionButton) });
    templateData.disposable = disposables;
  }
  renderCompressedElements() {
    throw new Error("Should never happen since node is incompressible");
  }
  focusActionButton(actionButton) {
    this.b.get(actionButton)?.focus();
  }
  disposeElement(node, index, template) {
    template.disposable.dispose();
  }
  disposeTemplate(templateData) {
    templateData.disposable.dispose();
    templateData.templateDisposable.dispose();
  }
};
$xac = $xac_1 = __decorate([
  __param(0, $sn),
  __param(1, $50),
  __param(2, $PJ)
], $xac);
var SCMTreeDragAndDrop = class _SCMTreeDragAndDrop {
  constructor(b) {
    this.b = b;
  }
  getDragURI(element) {
    if ($PQb(element)) {
      return element.sourceUri.toString();
    }
    return null;
  }
  onDragStart(data, originalEvent) {
    const items = _SCMTreeDragAndDrop.c(data);
    if (originalEvent.dataTransfer && items?.length) {
      this.b.invokeFunction((accessor) => $Eob(accessor, items, originalEvent));
      const fileResources = items.filter((s) => s.scheme === Schemas.file).map((r2) => r2.fsPath);
      if (fileResources.length) {
        originalEvent.dataTransfer.setData($u_.FILES, JSON.stringify(fileResources));
      }
    }
  }
  getDragLabel(elements, originalEvent) {
    if (elements.length === 1) {
      const element = elements[0];
      if ($PQb(element)) {
        return $sh(element.sourceUri);
      }
    }
    return String(elements.length);
  }
  onDragOver(data, targetElement, targetIndex, targetSector, originalEvent) {
    return true;
  }
  drop(data, targetElement, targetIndex, targetSector, originalEvent) {
  }
  static c(data) {
    const uris = [];
    for (const element of [...data.context ?? [], ...data.elements]) {
      if ($PQb(element)) {
        uris.push(element.sourceUri);
      }
    }
    return uris;
  }
  dispose() {
  }
};
var InputRenderer = class InputRenderer2 {
  static {
    InputRenderer_1 = this;
  }
  static {
    this.DEFAULT_HEIGHT = 26;
  }
  static {
    this.TEMPLATE_ID = "input";
  }
  get templateId() {
    return InputRenderer_1.TEMPLATE_ID;
  }
  constructor(f, h3, i2, k) {
    this.f = f;
    this.h = h3;
    this.i = i2;
    this.k = k;
    this.b = /* @__PURE__ */ new Map();
    this.c = /* @__PURE__ */ new WeakMap();
    this.d = /* @__PURE__ */ new WeakMap();
  }
  renderTemplate(container2) {
    container2.parentElement.parentElement.querySelector(".monaco-tl-twistie").classList.add("force-no-twistie");
    container2.parentElement.parentElement.classList.add("force-no-hover");
    const templateDisposable = new $2c();
    const inputElement = $bk(container2, $(".scm-input"));
    const inputWidget = this.k.createInstance(SCMInputWidget, inputElement, this.h);
    templateDisposable.add(inputWidget);
    return { inputWidget, inputWidgetHeight: InputRenderer_1.DEFAULT_HEIGHT, elementDisposables: new $2c(), templateDisposable };
  }
  renderElement(node, index, templateData) {
    const input = node.element;
    templateData.inputWidget.input = input;
    this.b.set(input, templateData.inputWidget);
    templateData.elementDisposables.add({
      dispose: () => this.b.delete(input)
    });
    const selections = this.d.get(input);
    if (selections) {
      templateData.inputWidget.selections = selections;
    }
    templateData.elementDisposables.add($1c(() => {
      const selections2 = templateData.inputWidget.selections;
      if (selections2) {
        this.d.set(input, selections2);
      }
    }));
    templateData.inputWidgetHeight = InputRenderer_1.DEFAULT_HEIGHT;
    const onDidChangeContentHeight = () => {
      const contentHeight = templateData.inputWidget.getContentHeight();
      this.c.set(input, contentHeight);
      if (templateData.inputWidgetHeight !== contentHeight) {
        this.i(input, contentHeight + 10);
        templateData.inputWidgetHeight = contentHeight;
        templateData.inputWidget.layout();
      }
    };
    const startListeningContentHeightChange = () => {
      templateData.elementDisposables.add(templateData.inputWidget.onDidChangeContentHeight(onDidChangeContentHeight));
      onDidChangeContentHeight();
    };
    $Xh(startListeningContentHeightChange, 0, templateData.elementDisposables);
    const layoutEditor = () => templateData.inputWidget.layout();
    templateData.elementDisposables.add(this.f.onDidChange(layoutEditor));
    layoutEditor();
  }
  renderCompressedElements() {
    throw new Error("Should never happen since node is incompressible");
  }
  disposeElement(group2, index, template) {
    template.elementDisposables.clear();
  }
  disposeTemplate(templateData) {
    templateData.templateDisposable.dispose();
  }
  getHeight(input) {
    return (this.c.get(input) ?? InputRenderer_1.DEFAULT_HEIGHT) + 10;
  }
  getRenderedInputWidget(input) {
    return this.b.get(input);
  }
  getFocusedInput() {
    for (const [input, inputWidget] of this.b) {
      if (inputWidget.hasFocus()) {
        return input;
      }
    }
    return void 0;
  }
  clearValidation() {
    for (const [, inputWidget] of this.b) {
      inputWidget.clearValidation();
    }
  }
};
InputRenderer = InputRenderer_1 = __decorate([
  __param(3, $Pk)
], InputRenderer);
var ResourceGroupRenderer = class ResourceGroupRenderer2 {
  static {
    ResourceGroupRenderer_1 = this;
  }
  static {
    this.TEMPLATE_ID = "resource group";
  }
  get templateId() {
    return ResourceGroupRenderer_1.TEMPLATE_ID;
  }
  constructor(b, c, d, f, h3, i2, k, l) {
    this.b = b;
    this.c = c;
    this.d = d;
    this.f = f;
    this.h = h3;
    this.i = i2;
    this.k = k;
    this.l = l;
  }
  renderTemplate(container2) {
    container2.parentElement.parentElement.querySelector(".monaco-tl-twistie").classList.add("force-twistie");
    const element = $bk(container2, $(".resource-group"));
    const name = $bk(element, $(".name"));
    const actionsContainer = $bk(element, $(".actions"));
    const actionBar = new $3$(actionsContainer, { actionViewItemProvider: this.b }, this.i, this.d, this.f, this.h, this.c, this.l);
    const countContainer = $bk(element, $(".count"));
    const count = new $D2(countContainer, {}, $E$);
    const disposables = $Zc(actionBar, count);
    return { name, count, actionBar, elementDisposables: new $2c(), disposables };
  }
  renderElement(node, index, template) {
    const group2 = node.element;
    template.name.textContent = group2.label;
    template.count.setCount(group2.resources.length);
    const menus = this.k.menus.getRepositoryMenus(group2.provider);
    template.elementDisposables.add($TQb(menus.getResourceGroupMenu(group2), (primary) => {
      template.actionBar.setActions(primary);
    }, "inline"));
    template.actionBar.context = group2;
  }
  renderCompressedElements(node, index, templateData, height) {
    throw new Error("Should never happen since node is incompressible");
  }
  disposeElement(group2, index, template) {
    template.elementDisposables.clear();
  }
  disposeTemplate(template) {
    template.elementDisposables.dispose();
    template.disposables.dispose();
  }
};
ResourceGroupRenderer = ResourceGroupRenderer_1 = __decorate([
  __param(1, $sn),
  __param(2, $on),
  __param(3, $50),
  __param(4, $Ty),
  __param(5, $cJ),
  __param(6, $eS),
  __param(7, $zv)
], ResourceGroupRenderer);
var RepositoryPaneActionRunner = class extends $Vm {
  constructor(b) {
    super();
    this.b = b;
  }
  async u(action, context) {
    if (!(action instanceof $fJ)) {
      return super.u(action, context);
    }
    const selection = this.b();
    const contextIsSelected = selection.some((s) => s === context);
    const actualContext = contextIsSelected ? selection : [context];
    const args2 = actualContext.map((e) => $$R.isResourceNode(e) ? $$R.collect(e) : [e]).flat();
    await action.run(...args2);
  }
};
var ResourceRenderer = class ResourceRenderer2 {
  static {
    ResourceRenderer_1 = this;
  }
  static {
    this.TEMPLATE_ID = "resource";
  }
  get templateId() {
    return ResourceRenderer_1.TEMPLATE_ID;
  }
  constructor(d, f, h3, i2, k, l, m, n, o, p, q, t, u) {
    this.d = d;
    this.f = f;
    this.h = h3;
    this.i = i2;
    this.k = k;
    this.l = l;
    this.m = m;
    this.n = n;
    this.o = o;
    this.p = p;
    this.q = q;
    this.t = t;
    this.u = u;
    this.b = new $2c();
    this.c = /* @__PURE__ */ new Map();
    u.onDidColorThemeChange(this.w, this, this.b);
  }
  renderTemplate(container2) {
    const element = $bk(container2, $(".resource"));
    const name = $bk(element, $(".name"));
    const fileLabel = this.f.create(name, { supportDescriptionHighlights: true, supportHighlights: true });
    const actionsContainer = $bk(fileLabel.element, $(".actions"));
    const actionBar = new $3$(actionsContainer, {
      actionViewItemProvider: this.h,
      actionRunner: this.i
    }, this.p, this.l, this.m, this.n, this.k, this.t);
    const decorationIcon = $bk(element, $(".decoration-icon"));
    const actionBarMenuListener = new $4c();
    const disposables = $Zc(actionBar, fileLabel, actionBarMenuListener);
    return { element, name, fileLabel, decorationIcon, actionBar, actionBarMenu: void 0, actionBarMenuListener, elementDisposables: new $2c(), disposables };
  }
  renderElement(node, index, template) {
    const resourceOrFolder = node.element;
    const iconResource = $$R.isResourceNode(resourceOrFolder) ? resourceOrFolder.element : resourceOrFolder;
    const uri = $$R.isResourceNode(resourceOrFolder) ? resourceOrFolder.uri : resourceOrFolder.sourceUri;
    const fileKind = $$R.isResourceNode(resourceOrFolder) ? FileKind.FOLDER : FileKind.FILE;
    const tooltip = !$$R.isResourceNode(resourceOrFolder) && resourceOrFolder.decorations.tooltip || "";
    const hidePath = this.d() === "tree";
    let matches;
    let descriptionMatches;
    let strikethrough;
    if ($$R.isResourceNode(resourceOrFolder)) {
      if (resourceOrFolder.element) {
        const menus = this.q.menus.getRepositoryMenus(resourceOrFolder.element.resourceGroup.provider);
        this.v(template, resourceOrFolder, menus.getResourceMenu(resourceOrFolder.element));
        template.element.classList.toggle("faded", resourceOrFolder.element.decorations.faded);
        strikethrough = resourceOrFolder.element.decorations.strikeThrough;
      } else {
        const menus = this.q.menus.getRepositoryMenus(resourceOrFolder.context.provider);
        this.v(template, resourceOrFolder, menus.getResourceFolderMenu(resourceOrFolder.context));
        matches = $Ul(node.filterData);
        template.element.classList.remove("faded");
      }
    } else {
      const menus = this.q.menus.getRepositoryMenus(resourceOrFolder.resourceGroup.provider);
      this.v(template, resourceOrFolder, menus.getResourceMenu(resourceOrFolder));
      [matches, descriptionMatches] = processResourceFilterData(uri, node.filterData);
      template.element.classList.toggle("faded", resourceOrFolder.decorations.faded);
      strikethrough = resourceOrFolder.decorations.strikeThrough;
    }
    const renderedData = {
      tooltip,
      uri,
      fileLabelOptions: { hidePath, fileKind, matches, descriptionMatches, strikethrough },
      iconResource
    };
    this.x(template, renderedData);
    this.c.set(template, renderedData);
    template.elementDisposables.add($1c(() => this.c.delete(template)));
    template.element.setAttribute("data-tooltip", tooltip);
  }
  disposeElement(resource, index, template) {
    template.elementDisposables.clear();
  }
  renderCompressedElements(node, index, template, height) {
    const compressed = node.element;
    const folder = compressed.elements[compressed.elements.length - 1];
    const label3 = compressed.elements.map((e) => e.name);
    const fileKind = FileKind.FOLDER;
    const matches = $Ul(node.filterData);
    template.fileLabel.setResource({ resource: folder.uri, name: label3 }, {
      fileDecorations: { colors: false, badges: true },
      fileKind,
      matches,
      separator: this.o.getSeparator(folder.uri.scheme)
    });
    const menus = this.q.menus.getRepositoryMenus(folder.context.provider);
    this.v(template, folder, menus.getResourceFolderMenu(folder.context));
    template.name.classList.remove("strike-through");
    template.element.classList.remove("faded");
    template.decorationIcon.style.display = "none";
    template.decorationIcon.style.backgroundImage = "";
    template.element.setAttribute("data-tooltip", "");
  }
  disposeCompressedElements(node, index, template, height) {
    template.elementDisposables.clear();
  }
  disposeTemplate(template) {
    template.elementDisposables.dispose();
    template.disposables.dispose();
  }
  v(template, resourceOrFolder, menu) {
    if (!template.actionBarMenu || template.actionBarMenu !== menu) {
      template.actionBarMenu = menu;
      template.actionBarMenuListener.value = $TQb(menu, (primary) => {
        template.actionBar.setActions(primary);
      }, "inline");
    }
    template.actionBar.context = resourceOrFolder;
  }
  w() {
    for (const [template, data] of this.c) {
      this.x(template, data);
    }
  }
  x(template, data) {
    const theme = this.u.getColorTheme();
    const icon2 = theme.type === ColorScheme.LIGHT ? data.iconResource?.decorations.icon : data.iconResource?.decorations.iconDark;
    template.fileLabel.setFile(data.uri, {
      ...data.fileLabelOptions,
      fileDecorations: { colors: false, badges: !icon2 }
    });
    if (icon2) {
      if (ThemeIcon.isThemeIcon(icon2)) {
        template.decorationIcon.className = `decoration-icon ${ThemeIcon.asClassName(icon2)}`;
        if (icon2.color) {
          template.decorationIcon.style.color = theme.getColor(icon2.color.id)?.toString() ?? "";
        }
        template.decorationIcon.style.display = "";
        template.decorationIcon.style.backgroundImage = "";
      } else {
        template.decorationIcon.className = "decoration-icon";
        template.decorationIcon.style.color = "";
        template.decorationIcon.style.display = "";
        template.decorationIcon.style.backgroundImage = $5Z(icon2);
      }
      template.decorationIcon.title = data.tooltip;
    } else {
      template.decorationIcon.className = "decoration-icon";
      template.decorationIcon.style.color = "";
      template.decorationIcon.style.display = "none";
      template.decorationIcon.style.backgroundImage = "";
      template.decorationIcon.title = "";
    }
  }
  dispose() {
    this.b.dispose();
  }
};
ResourceRenderer = ResourceRenderer_1 = __decorate([
  __param(4, $sn),
  __param(5, $on),
  __param(6, $50),
  __param(7, $Ty),
  __param(8, $ZI),
  __param(9, $cJ),
  __param(10, $eS),
  __param(11, $zv),
  __param(12, $gs)
], ResourceRenderer);
var ListDelegate2 = class {
  constructor(b) {
    this.b = b;
  }
  getHeight(element) {
    if ($MQb(element)) {
      return this.b.getHeight(element);
    } else if ($NQb(element)) {
      return $xac.DEFAULT_HEIGHT + 10;
    } else {
      return 22;
    }
  }
  getTemplateId(element) {
    if ($LQb(element)) {
      return $oac.TEMPLATE_ID;
    } else if ($MQb(element)) {
      return InputRenderer.TEMPLATE_ID;
    } else if ($NQb(element)) {
      return $xac.TEMPLATE_ID;
    } else if ($OQb(element)) {
      return ResourceGroupRenderer.TEMPLATE_ID;
    } else if ($PQb(element) || $QQb(element)) {
      return ResourceRenderer.TEMPLATE_ID;
    } else {
      throw new Error("Unknown element");
    }
  }
};
var SCMTreeCompressionDelegate = class {
  isIncompressible(element) {
    if ($$R.isResourceNode(element)) {
      return element.childrenCount === 0 || !element.parent || !element.parent.parent;
    }
    return true;
  }
};
var SCMTreeFilter = class {
  filter(element) {
    if ($OQb(element)) {
      return element.resources.length > 0 || !element.hideWhenEmpty;
    } else {
      return true;
    }
  }
};
var $yac = class {
  constructor(b, c) {
    this.b = b;
    this.c = c;
  }
  compare(one, other) {
    if ($LQb(one)) {
      if (!$LQb(other)) {
        throw new Error("Invalid comparison");
      }
      return 0;
    }
    if ($MQb(one)) {
      return -1;
    } else if ($MQb(other)) {
      return 1;
    }
    if ($NQb(one)) {
      return -1;
    } else if ($NQb(other)) {
      return 1;
    }
    if ($OQb(one)) {
      return $OQb(other) ? 0 : -1;
    }
    if (this.b() === "list") {
      if (this.c() === "name") {
        const oneName2 = $sh(one.sourceUri);
        const otherName2 = $sh(other.sourceUri);
        return $EM(oneName2, otherName2);
      }
      if (this.c() === "status") {
        const oneTooltip = one.decorations.tooltip ?? "";
        const otherTooltip = other.decorations.tooltip ?? "";
        if (oneTooltip !== otherTooltip) {
          return $Tf(oneTooltip, otherTooltip);
        }
      }
      const onePath = one.sourceUri.fsPath;
      const otherPath = other.sourceUri.fsPath;
      return $OM(onePath, otherPath);
    }
    const oneIsDirectory = $$R.isResourceNode(one);
    const otherIsDirectory = $$R.isResourceNode(other);
    if (oneIsDirectory !== otherIsDirectory) {
      return oneIsDirectory ? -1 : 1;
    }
    const oneName = $$R.isResourceNode(one) ? one.name : $sh(one.sourceUri);
    const otherName = $$R.isResourceNode(other) ? other.name : $sh(other.sourceUri);
    return $EM(oneName, otherName);
  }
};
var $zac = class $zac2 {
  constructor(b, c) {
    this.b = b;
    this.c = c;
  }
  getKeyboardNavigationLabel(element) {
    if ($$R.isResourceNode(element)) {
      return element.name;
    } else if ($LQb(element) || $MQb(element) || $NQb(element)) {
      return void 0;
    } else if ($OQb(element)) {
      return element.label;
    } else {
      if (this.b() === "list") {
        const fileName = $sh(element.sourceUri);
        const filePath = this.c.getUriLabel(element.sourceUri, { relative: true });
        return [fileName, filePath];
      } else {
        return $sh(element.sourceUri);
      }
    }
  }
  getCompressedNodeKeyboardNavigationLabel(elements) {
    const folders = elements;
    return folders.map((e) => e.name).join("/");
  }
};
$zac = __decorate([
  __param(1, $ZI)
], $zac);
function getSCMResourceId(element) {
  if ($LQb(element)) {
    const provider = element.provider;
    return `repo:${provider.id}`;
  } else if ($MQb(element)) {
    const provider = element.repository.provider;
    return `input:${provider.id}`;
  } else if ($NQb(element)) {
    const provider = element.repository.provider;
    return `actionButton:${provider.id}`;
  } else if ($OQb(element)) {
    const provider = element.provider;
    return `resourceGroup:${provider.id}/${element.id}`;
  } else if ($PQb(element)) {
    const group2 = element.resourceGroup;
    const provider = group2.provider;
    return `resource:${provider.id}/${group2.id}/${element.sourceUri.toString()}`;
  } else if ($QQb(element)) {
    const group2 = element.context;
    return `folder:${group2.provider.id}/${group2.id}/$FOLDER/${element.uri.toString()}`;
  } else {
    throw new Error("Invalid tree element");
  }
}
var SCMResourceIdentityProvider = class {
  getId(element) {
    return getSCMResourceId(element);
  }
};
var $Aac = class $Aac2 {
  constructor(b) {
    this.b = b;
  }
  getWidgetAriaLabel() {
    return localize(9514, null);
  }
  getAriaLabel(element) {
    if ($$R.isResourceNode(element)) {
      return this.b.getUriLabel(element.uri, { relative: true, noPrefix: true }) || element.name;
    } else if ($LQb(element)) {
      return `${element.provider.name} ${element.provider.label}`;
    } else if ($MQb(element)) {
      return localize(9515, null);
    } else if ($NQb(element)) {
      return element.button?.command.title ?? "";
    } else if ($OQb(element)) {
      return element.label;
    } else {
      const result = [];
      result.push($sh(element.sourceUri));
      if (element.decorations.tooltip) {
        result.push(element.decorations.tooltip);
      }
      const path = this.b.getUriLabel($uh(element.sourceUri), { relative: true, noPrefix: true });
      if (path) {
        result.push(path);
      }
      return result.join(", ");
    }
  }
};
$Aac = __decorate([
  __param(0, $ZI)
], $Aac);
var ViewMode2;
(function(ViewMode3) {
  ViewMode3["List"] = "list";
  ViewMode3["Tree"] = "tree";
})(ViewMode2 || (ViewMode2 = {}));
var ViewSortKey;
(function(ViewSortKey2) {
  ViewSortKey2["Path"] = "path";
  ViewSortKey2["Name"] = "name";
  ViewSortKey2["Status"] = "status";
})(ViewSortKey || (ViewSortKey = {}));
var Menus = {
  ViewSort: new $bJ("SCMViewSort"),
  Repositories: new $bJ("SCMRepositories"),
  ChangesSettings: new $bJ("SCMChangesSettings")
};
var $Bac = {
  SCMViewMode: new $nn(
    "scmViewMode",
    "list"
    /* ViewMode.List */
  ),
  SCMViewSortKey: new $nn(
    "scmViewSortKey",
    "path"
    /* ViewSortKey.Path */
  ),
  SCMViewAreAllRepositoriesCollapsed: new $nn("scmViewAreAllRepositoriesCollapsed", false),
  SCMViewIsAnyRepositoryCollapsible: new $nn("scmViewIsAnyRepositoryCollapsible", false),
  SCMProvider: new $nn("scmProvider", void 0),
  SCMProviderRootUri: new $nn("scmProviderRootUri", void 0),
  SCMProviderHasRootUri: new $nn("scmProviderHasRootUri", void 0),
  SCMHistoryItemCount: new $nn("scmHistoryItemCount", 0),
  SCMCurrentHistoryItemRefHasRemote: new $nn("scmCurrentHistoryItemRefHasRemote", false),
  SCMCurrentHistoryItemRefInFilter: new $nn("scmCurrentHistoryItemRefInFilter", false),
  RepositoryCount: new $nn("scmRepositoryCount", 0),
  RepositoryVisibilityCount: new $nn("scmRepositoryVisibleCount", 0),
  RepositoryVisibility(repository) {
    return new $nn(`scmRepositoryVisible:${repository.provider.id}`, false);
  }
};
$dJ.appendMenuItem($bJ.SCMTitle, {
  title: localize(9516, null),
  submenu: Menus.ViewSort,
  when: $7m.and($7m.equals("view", $aS), $Bac.RepositoryCount.notEqualsTo(0)),
  group: "0_view&sort",
  order: 1
});
$dJ.appendMenuItem(Menus.ViewSort, {
  title: localize(9517, null),
  submenu: Menus.Repositories,
  when: $7m.greater($Bac.RepositoryCount.key, 1),
  group: "0_repositories"
});
var RepositoryVisibilityAction = class extends $gJ {
  constructor(repository) {
    super({
      id: `workbench.scm.action.toggleRepositoryVisibility.${repository.provider.id}`,
      title: repository.provider.name,
      f1: false,
      precondition: $7m.or($Bac.RepositoryVisibilityCount.notEqualsTo(1), $Bac.RepositoryVisibility(repository).isEqualTo(false)),
      toggled: $Bac.RepositoryVisibility(repository).isEqualTo(true),
      menu: { id: Menus.Repositories, group: "0_repositories" }
    });
    this.b = repository;
  }
  run(accessor) {
    const scmViewService = accessor.get($eS);
    scmViewService.toggleVisibility(this.b);
  }
};
var RepositoryVisibilityActionController = class RepositoryVisibilityActionController2 {
  constructor(h3, i2, scmService) {
    this.h = h3;
    this.i = i2;
    this.b = /* @__PURE__ */ new Map();
    this.f = new $2c();
    this.c = $Bac.RepositoryCount.bindTo(h3);
    this.d = $Bac.RepositoryVisibilityCount.bindTo(h3);
    i2.onDidChangeVisibleRepositories(this.m, this, this.f);
    scmService.onDidAddRepository(this.k, this, this.f);
    scmService.onDidRemoveRepository(this.l, this, this.f);
    for (const repository of scmService.repositories) {
      this.k(repository);
    }
  }
  k(repository) {
    const action = $hJ(class extends RepositoryVisibilityAction {
      constructor() {
        super(repository);
      }
    });
    const contextKey = $Bac.RepositoryVisibility(repository).bindTo(this.h);
    contextKey.set(this.i.isVisible(repository));
    this.b.set(repository, {
      contextKey,
      dispose() {
        contextKey.reset();
        action.dispose();
      }
    });
    this.n();
  }
  l(repository) {
    this.b.get(repository)?.dispose();
    this.b.delete(repository);
    this.n();
  }
  m() {
    let count = 0;
    for (const [repository, item] of this.b) {
      const isVisible = this.i.isVisible(repository);
      item.contextKey.set(isVisible);
      if (isVisible) {
        count++;
      }
    }
    this.c.set(this.b.size);
    this.d.set(count);
  }
  n() {
    this.c.set(this.b.size);
    this.d.set(Iterable.reduce(this.b.keys(), (r2, repository) => r2 + (this.i.isVisible(repository) ? 1 : 0), 0));
  }
  dispose() {
    this.f.dispose();
    $Xc(this.b.values());
    this.b.clear();
  }
};
RepositoryVisibilityActionController = __decorate([
  __param(0, $on),
  __param(1, $eS),
  __param(2, $dS)
], RepositoryVisibilityActionController);
var SetListViewModeAction = class extends $cpb {
  constructor(id2 = "workbench.scm.action.setListViewMode", menu = {}) {
    super({
      id: id2,
      title: localize(9518, null),
      viewId: $aS,
      f1: false,
      icon: $6l.listTree,
      toggled: $Bac.SCMViewMode.isEqualTo(
        "list"
        /* ViewMode.List */
      ),
      menu: { id: Menus.ViewSort, group: "1_viewmode", ...menu }
    });
  }
  async runInView(_, view) {
    view.viewMode = "list";
  }
};
var SetListViewModeNavigationAction = class extends SetListViewModeAction {
  constructor() {
    super("workbench.scm.action.setListViewModeNavigation", {
      id: $bJ.SCMTitle,
      when: $7m.and($7m.equals("view", $aS), $Bac.RepositoryCount.notEqualsTo(0), $Bac.SCMViewMode.isEqualTo(
        "tree"
        /* ViewMode.Tree */
      )),
      group: "navigation",
      order: -1e3
    });
  }
};
var SetTreeViewModeAction = class extends $cpb {
  constructor(id2 = "workbench.scm.action.setTreeViewMode", menu = {}) {
    super({
      id: id2,
      title: localize(9519, null),
      viewId: $aS,
      f1: false,
      icon: $6l.listFlat,
      toggled: $Bac.SCMViewMode.isEqualTo(
        "tree"
        /* ViewMode.Tree */
      ),
      menu: { id: Menus.ViewSort, group: "1_viewmode", ...menu }
    });
  }
  async runInView(_, view) {
    view.viewMode = "tree";
  }
};
var SetTreeViewModeNavigationAction = class extends SetTreeViewModeAction {
  constructor() {
    super("workbench.scm.action.setTreeViewModeNavigation", {
      id: $bJ.SCMTitle,
      when: $7m.and($7m.equals("view", $aS), $Bac.RepositoryCount.notEqualsTo(0), $Bac.SCMViewMode.isEqualTo(
        "list"
        /* ViewMode.List */
      )),
      group: "navigation",
      order: -1e3
    });
  }
};
$hJ(SetListViewModeAction);
$hJ(SetTreeViewModeAction);
$hJ(SetListViewModeNavigationAction);
$hJ(SetTreeViewModeNavigationAction);
var RepositorySortAction = class extends $cpb {
  constructor(b, title) {
    super({
      id: `workbench.scm.action.repositories.setSortKey.${b}`,
      title,
      viewId: $aS,
      f1: false,
      toggled: $sac.RepositorySortKey.isEqualTo(b),
      menu: [
        {
          id: Menus.Repositories,
          group: "1_sort"
        },
        {
          id: $bJ.SCMSourceControlTitle,
          group: "1_sort"
        }
      ]
    });
    this.b = b;
  }
  runInView(accessor) {
    accessor.get($eS).toggleSortKey(this.b);
  }
};
var RepositorySortByDiscoveryTimeAction = class extends RepositorySortAction {
  constructor() {
    super("discoveryTime", localize(9520, null));
  }
};
var RepositorySortByNameAction = class extends RepositorySortAction {
  constructor() {
    super("name", localize(9521, null));
  }
};
var RepositorySortByPathAction = class extends RepositorySortAction {
  constructor() {
    super("path", localize(9522, null));
  }
};
$hJ(RepositorySortByDiscoveryTimeAction);
$hJ(RepositorySortByNameAction);
$hJ(RepositorySortByPathAction);
var SetSortKeyAction = class extends $cpb {
  constructor(b, title) {
    super({
      id: `workbench.scm.action.setSortKey.${b}`,
      title,
      viewId: $aS,
      f1: false,
      toggled: $Bac.SCMViewSortKey.isEqualTo(b),
      precondition: $Bac.SCMViewMode.isEqualTo(
        "list"
        /* ViewMode.List */
      ),
      menu: { id: Menus.ViewSort, group: "2_sort" }
    });
    this.b = b;
  }
  async runInView(_, view) {
    view.viewSortKey = this.b;
  }
};
var SetSortByNameAction = class extends SetSortKeyAction {
  constructor() {
    super("name", localize(9523, null));
  }
};
var SetSortByPathAction = class extends SetSortKeyAction {
  constructor() {
    super("path", localize(9524, null));
  }
};
var SetSortByStatusAction = class extends SetSortKeyAction {
  constructor() {
    super("status", localize(9525, null));
  }
};
$hJ(SetSortByNameAction);
$hJ(SetSortByPathAction);
$hJ(SetSortByStatusAction);
var CollapseAllRepositoriesAction = class extends $cpb {
  constructor() {
    super({
      id: `workbench.scm.action.collapseAllRepositories`,
      title: localize(9526, null),
      viewId: $aS,
      f1: false,
      icon: $6l.collapseAll,
      menu: {
        id: $bJ.SCMTitle,
        group: "navigation",
        when: $7m.and($7m.equals("view", $aS), $Bac.SCMViewIsAnyRepositoryCollapsible.isEqualTo(true), $Bac.SCMViewAreAllRepositoriesCollapsed.isEqualTo(false))
      }
    });
  }
  async runInView(_, view) {
    view.collapseAllRepositories();
  }
};
var ExpandAllRepositoriesAction = class extends $cpb {
  constructor() {
    super({
      id: `workbench.scm.action.expandAllRepositories`,
      title: localize(9527, null),
      viewId: $aS,
      f1: false,
      icon: $6l.expandAll,
      menu: {
        id: $bJ.SCMTitle,
        group: "navigation",
        when: $7m.and($7m.equals("view", $aS), $Bac.SCMViewIsAnyRepositoryCollapsible.isEqualTo(true), $Bac.SCMViewAreAllRepositoriesCollapsed.isEqualTo(true))
      }
    });
  }
  async runInView(_, view) {
    view.expandAllRepositories();
  }
};
$hJ(CollapseAllRepositoriesAction);
$hJ(ExpandAllRepositoriesAction);
var SCMInputWidgetCommandId;
(function(SCMInputWidgetCommandId2) {
  SCMInputWidgetCommandId2["CancelAction"] = "scm.input.cancelAction";
})(SCMInputWidgetCommandId || (SCMInputWidgetCommandId = {}));
var SCMInputWidgetStorageKey;
(function(SCMInputWidgetStorageKey2) {
  SCMInputWidgetStorageKey2["LastActionId"] = "scm.input.lastActionId";
})(SCMInputWidgetStorageKey || (SCMInputWidgetStorageKey = {}));
var SCMInputWidgetActionRunner = class SCMInputWidgetActionRunner2 extends $Vm {
  get runningActions() {
    return this.b;
  }
  constructor(h3, n) {
    super();
    this.h = h3;
    this.n = n;
    this.b = /* @__PURE__ */ new Set();
  }
  async u(action) {
    try {
      if (this.runningActions.size !== 0) {
        this.c?.cancel();
        if (action.id === "scm.input.cancelAction") {
          return;
        }
      }
      const context = [];
      for (const group2 of this.h.repository.provider.groups) {
        context.push({
          resourceGroupId: group2.id,
          resources: [...group2.resources.map((r2) => r2.sourceUri)]
        });
      }
      this.b.add(action);
      this.c = new $ad();
      await action.run(...[this.h.repository.provider.rootUri, context, this.c.token]);
    } finally {
      this.b.delete(action);
      if (this.b.size === 0) {
        this.n.store(
          "scm.input.lastActionId",
          action.id,
          0,
          0
          /* StorageTarget.USER */
        );
      }
    }
  }
};
SCMInputWidgetActionRunner = __decorate([
  __param(1, $jv)
], SCMInputWidgetActionRunner);
var SCMInputWidgetToolbar = class SCMInputWidgetToolbar2 extends $3$ {
  get dropdownActions() {
    return this.b;
  }
  get dropdownAction() {
    return this.c;
  }
  constructor(container2, options3, Q, R, contextMenuService, commandService, keybindingService, S, telemetryService) {
    super(container2, { resetMenu: $bJ.SCMInputBox, ...options3 }, Q, R, contextMenuService, keybindingService, commandService, telemetryService);
    this.Q = Q;
    this.R = R;
    this.S = S;
    this.b = [];
    this.O = new $ze();
    this.onDidChange = this.O.event;
    this.P = this.B(new $4c());
    this.c = new $Um("scmInputMoreActions", localize(9528, null), "codicon-chevron-down");
    this.h = new $fJ({
      id: "scm.input.cancelAction",
      title: localize(9529, null),
      icon: $6l.stopCircle
    }, void 0, void 0, void 0, void 0, R, commandService);
  }
  setInput(input) {
    this.P.value = new $2c();
    const contextKeyService = this.R.createOverlay([
      ["scmProvider", input.repository.provider.contextValue],
      ["scmProviderRootUri", input.repository.provider.rootUri?.toString()],
      ["scmProviderHasRootUri", !!input.repository.provider.rootUri]
    ]);
    const menu = this.P.value.add(this.Q.createMenu($bJ.SCMInputBox, contextKeyService, { emitEventsForSubmenuChanges: true }));
    const isEnabled = () => {
      return input.repository.provider.groups.some((g) => g.resources.length > 0);
    };
    const updateToolbar = () => {
      const actions = $R$(menu.getActions({ shouldForwardArgs: true }));
      for (const action of actions) {
        action.enabled = isEnabled();
      }
      this.c.enabled = isEnabled();
      let primaryAction = void 0;
      if (actions.length === 1) {
        primaryAction = actions[0];
      } else if (actions.length > 1) {
        const lastActionId = this.S.get("scm.input.lastActionId", 0, "");
        primaryAction = actions.find((a) => a.id === lastActionId) ?? actions[0];
      }
      this.b = actions.length === 1 ? [] : actions;
      super.setActions(primaryAction ? [primaryAction] : [], []);
      this.O.fire();
    };
    this.P.value.add(menu.onDidChange(() => updateToolbar()));
    this.P.value.add(input.repository.provider.onDidChangeResources(() => updateToolbar()));
    this.P.value.add(this.S.onDidChangeValue(0, "scm.input.lastActionId", this.P.value)(() => updateToolbar()));
    this.actionRunner = new SCMInputWidgetActionRunner(input, this.S);
    this.P.value.add(this.actionRunner.onWillRun((e) => {
      if (this.actionRunner.runningActions.size === 0) {
        super.setActions([this.h], []);
        this.O.fire();
      }
    }));
    this.P.value.add(this.actionRunner.onDidRun((e) => {
      if (this.actionRunner.runningActions.size === 0) {
        updateToolbar();
      }
    }));
    updateToolbar();
  }
};
SCMInputWidgetToolbar = __decorate([
  __param(2, $cJ),
  __param(3, $on),
  __param(4, $50),
  __param(5, $sn),
  __param(6, $Ty),
  __param(7, $jv),
  __param(8, $zv)
], SCMInputWidgetToolbar);
var SCMInputWidgetEditorOptions = class {
  constructor(f, h3) {
    this.f = f;
    this.h = h3;
    this.b = new $ze();
    this.onDidChange = this.b.event;
    this.c = $91;
    this.d = new $2c();
    const onDidChangeConfiguration = Event2.filter(this.h.onDidChangeConfiguration, (e) => {
      return e.affectsConfiguration("editor.accessibilitySupport") || e.affectsConfiguration("editor.cursorBlinking") || e.affectsConfiguration("editor.fontFamily") || e.affectsConfiguration("editor.rulers") || e.affectsConfiguration("editor.wordWrap") || e.affectsConfiguration("scm.inputFontFamily") || e.affectsConfiguration("scm.inputFontSize");
    }, this.d);
    this.d.add(onDidChangeConfiguration(() => this.b.fire()));
  }
  getEditorConstructionOptions() {
    const fontFamily = this.i();
    const fontSize = this.k();
    const lineHeight = this.m(fontSize);
    return {
      ...$Zsb(this.h),
      ...this.l(),
      cursorWidth: 1,
      dragAndDrop: true,
      dropIntoEditor: { enabled: true },
      fontFamily,
      fontSize,
      formatOnType: true,
      lineDecorationsWidth: 6,
      lineHeight,
      overflowWidgetsDomNode: this.f,
      padding: { top: 2, bottom: 2 },
      quickSuggestions: false,
      renderWhitespace: "none",
      scrollbar: {
        alwaysConsumeMouseWheel: false,
        vertical: "hidden"
      },
      wrappingIndent: "none",
      wrappingStrategy: "advanced"
    };
  }
  getEditorOptions() {
    const fontFamily = this.i();
    const fontSize = this.k();
    const lineHeight = this.m(fontSize);
    const accessibilitySupport = this.h.getValue("editor.accessibilitySupport");
    const cursorBlinking = this.h.getValue("editor.cursorBlinking");
    return { ...this.l(), accessibilitySupport, cursorBlinking, fontFamily, fontSize, lineHeight };
  }
  i() {
    const inputFontFamily = this.h.getValue("scm.inputFontFamily").trim();
    if (inputFontFamily.toLowerCase() === "editor") {
      return this.h.getValue("editor.fontFamily").trim();
    }
    if (inputFontFamily.length !== 0 && inputFontFamily.toLowerCase() !== "default") {
      return inputFontFamily;
    }
    return this.c;
  }
  k() {
    return this.h.getValue("scm.inputFontSize");
  }
  l() {
    const rulersConfig = this.h.inspect("editor.rulers", { overrideIdentifier: "scminput" });
    const rulers = rulersConfig.overrideIdentifiers?.includes("scminput") ? EditorOptions.rulers.validate(rulersConfig.value) : [];
    const wordWrapConfig = this.h.inspect("editor.wordWrap", { overrideIdentifier: "scminput" });
    const wordWrap = wordWrapConfig.overrideIdentifiers?.includes("scminput") ? EditorOptions.wordWrap.validate(wordWrapConfig.value) : "on";
    return { rulers, wordWrap };
  }
  m(fontSize) {
    return Math.round(fontSize * 1.5);
  }
  dispose() {
    this.d.dispose();
  }
};
var SCMInputWidget = class SCMInputWidget2 {
  static {
    SCMInputWidget_1 = this;
  }
  static {
    this.b = {
      [
        2
        /* InputValidationType.Information */
      ]: 5e3,
      [
        1
        /* InputValidationType.Warning */
      ]: 8e3,
      [
        0
        /* InputValidationType.Error */
      ]: 1e4
    };
  }
  get input() {
    return this.n?.input;
  }
  set input(input) {
    if (input === this.input) {
      return;
    }
    this.clearValidation();
    this.d.classList.remove("synthetic-focus");
    this.p.clear();
    this.o.set(input?.repository.id);
    if (!input) {
      this.h.setModel(void 0);
      this.n = void 0;
      return;
    }
    const textModel = input.repository.provider.inputBoxTextModel;
    this.h.setModel(textModel);
    if (this.B.getValue("editor.wordBasedSuggestions", { resource: textModel.uri }) !== "off") {
      this.B.updateValue(
        "editor.wordBasedSuggestions",
        "off",
        { resource: textModel.uri },
        8
        /* ConfigurationTarget.MEMORY */
      );
    }
    const validationDelayer = new $Th(200);
    const validate = async () => {
      const position = this.h.getSelection()?.getStartPosition();
      const offset = position && textModel.getOffsetAt(position);
      const value = textModel.getValue();
      this.y(await input.validateInput(value, offset || 0));
    };
    const triggerValidation = () => validationDelayer.trigger(validate);
    this.p.add(validationDelayer);
    this.p.add(this.h.onDidChangeCursorPosition(triggerValidation));
    const opts = this.z.getCreationOptions(textModel.getLanguageId(), textModel.uri, textModel.isForSimpleWidget);
    const onEnter = Event2.filter(this.h.onKeyDown, (e) => e.keyCode === 3, this.p);
    this.p.add(onEnter(() => textModel.detectIndentation(opts.insertSpaces, opts.tabSize)));
    textModel.setValue(input.value);
    this.p.add(input.onDidChange(({ value, reason }) => {
      const currentValue = textModel.getValue();
      if (value === currentValue) {
        return;
      }
      textModel.pushStackElement();
      textModel.pushEditOperations(null, [$bD.replaceMove(textModel.getFullModelRange(), value)], () => []);
      const position = reason === SCMInputChangeReason.HistoryPrevious ? textModel.getFullModelRange().getStartPosition() : textModel.getFullModelRange().getEndPosition();
      this.h.setPosition(position);
      this.h.revealPositionInCenterIfOutsideViewport(position);
    }));
    this.p.add(input.onDidChangeFocus(() => this.focus()));
    this.p.add(input.onDidChangeValidationMessage((e) => this.y(e, { focus: true, timeout: true })));
    this.p.add(input.onDidChangeValidateInput((e) => triggerValidation()));
    this.p.add(textModel.onDidChangeContent(() => {
      input.setValue(textModel.getValue(), true);
      triggerValidation();
    }));
    const updatePlaceholderText = () => {
      const binding = this.A.lookupKeybinding("scm.acceptInput");
      const label3 = binding ? binding.getLabel() : $m ? "Cmd+Enter" : "Ctrl+Enter";
      const placeholderText = $wf(input.placeholder, label3);
      this.h.updateOptions({ placeholder: placeholderText });
    };
    this.p.add(input.onDidChangePlaceholder(updatePlaceholderText));
    this.p.add(this.A.onDidUpdateKeybindings(updatePlaceholderText));
    updatePlaceholderText();
    let commitTemplate = "";
    this.p.add($td((reader) => {
      if (!input.visible) {
        return;
      }
      const oldCommitTemplate = commitTemplate;
      commitTemplate = input.repository.provider.commitTemplate.read(reader);
      const value = textModel.getValue();
      if (value && value !== oldCommitTemplate) {
        return;
      }
      textModel.setValue(commitTemplate);
    }));
    const updateEnablement = (enabled) => {
      this.h.updateOptions({ readOnly: !enabled });
    };
    this.p.add(input.onDidChangeEnablement((enabled) => updateEnablement(enabled)));
    updateEnablement(input.enabled);
    this.l.setInput(input);
    this.n = { input, textModel };
  }
  get selections() {
    return this.h.getSelections();
  }
  set selections(selections) {
    if (selections) {
      this.h.setSelections(selections);
    }
  }
  y(validation, options3) {
    if (this.v) {
      clearTimeout(this.v);
      this.v = 0;
    }
    this.q = validation;
    this.H();
    if (options3?.focus && !this.hasFocus()) {
      this.focus();
    }
    if (validation && options3?.timeout) {
      this.v = setTimeout(() => this.y(void 0), SCMInputWidget_1.b[validation.type]);
    }
  }
  constructor(container2, overflowWidgetsDomNode, contextKeyService, z, A, B, C, D, E, F) {
    this.z = z;
    this.A = A;
    this.B = B;
    this.C = C;
    this.D = D;
    this.E = E;
    this.F = F;
    this.m = new $2c();
    this.p = new $2c();
    this.u = false;
    this.w = false;
    this.x = false;
    this.d = $bk(container2, $(".scm-editor"));
    this.f = $bk(this.d, $(".scm-editor-container"));
    this.k = $bk(this.d, $(".scm-editor-toolbar"));
    this.c = contextKeyService.createScoped(this.d);
    this.o = this.c.createKey("scmRepository", void 0);
    this.i = new SCMInputWidgetEditorOptions(overflowWidgetsDomNode, this.B);
    this.m.add(this.i.onDidChange(this.G, this));
    this.m.add(this.i);
    const codeEditorWidgetOptions = {
      contributions: EditorExtensionsRegistry.getSomeEditorContributions([
        $fbb.ID,
        $Lbb.ID,
        $Mfb.ID,
        $iab.ID,
        $Rfb.ID,
        $Yfb.ID,
        $XJb.ID,
        $khb.ID,
        $Afb.ID,
        $Fib.ID,
        $3hb.ID,
        $Ajb.ID,
        $Esb.ID,
        $S_.ID,
        $Yjb.ID,
        $Fsb,
        $Dcb.ID,
        $qdb.ID
      ]),
      isSimpleWidget: true
    };
    const services = new $Ok([$on, this.c]);
    const instantiationService2 = C.createChild(services, this.m);
    const editorConstructionOptions = this.i.getEditorConstructionOptions();
    this.h = instantiationService2.createInstance($D9, this.f, editorConstructionOptions, codeEditorWidgetOptions);
    this.m.add(this.h);
    this.m.add(this.h.onDidFocusEditorText(() => {
      if (this.input?.repository) {
        this.D.focus(this.input.repository);
      }
      this.d.classList.add("synthetic-focus");
      this.H();
    }));
    this.m.add(this.h.onDidBlurEditorText(() => {
      this.d.classList.remove("synthetic-focus");
      setTimeout(() => {
        if (!this.q || !this.u) {
          this.clearValidation();
        }
      }, 0);
    }));
    this.m.add(this.h.onDidBlurEditorWidget(() => {
      $iab.get(this.h)?.clearWidgets();
      $Yfb.get(this.h)?.clearWidgets();
    }));
    const firstLineKey = this.c.createKey("scmInputIsInFirstPosition", false);
    const lastLineKey = this.c.createKey("scmInputIsInLastPosition", false);
    this.m.add(this.h.onDidChangeCursorPosition(({ position }) => {
      const viewModel = this.h._getViewModel();
      const lastLineNumber = viewModel.getLineCount();
      const lastLineCol = viewModel.getLineLength(lastLineNumber) + 1;
      const viewPosition = viewModel.coordinatesConverter.convertModelPositionToViewPosition(position);
      firstLineKey.set(viewPosition.lineNumber === 1 && viewPosition.column === 1);
      lastLineKey.set(viewPosition.lineNumber === lastLineNumber && viewPosition.column === lastLineCol);
    }));
    this.m.add(this.h.onDidScrollChange((e) => {
      this.k.classList.toggle("scroll-decoration", e.scrollTop > 0);
    }));
    Event2.filter(this.B.onDidChangeConfiguration, (e) => e.affectsConfiguration("scm.showInputActionButton"))(() => this.layout(), this, this.m);
    this.onDidChangeContentHeight = Event2.signal(Event2.filter(this.h.onDidContentSizeChange, (e) => e.contentHeightChanged, this.m));
    this.l = instantiationService2.createInstance(SCMInputWidgetToolbar, this.k, {
      actionViewItemProvider: (action, options3) => {
        if (action instanceof $fJ && this.l.dropdownActions.length > 1) {
          return C.createInstance($isb, action, this.l.dropdownAction, this.l.dropdownActions, "", { actionRunner: this.l.actionRunner, hoverDelegate: options3.hoverDelegate });
        }
        return $X$(C, action, options3);
      },
      menuOptions: {
        shouldForwardArgs: true
      }
    });
    this.m.add(this.l.onDidChange(() => this.layout()));
    this.m.add(this.l);
  }
  getContentHeight() {
    const lineHeight = this.h.getOption(
      68
      /* EditorOption.lineHeight */
    );
    const { top: top2, bottom } = this.h.getOption(
      88
      /* EditorOption.padding */
    );
    const inputMinLinesConfig = this.B.getValue("scm.inputMinLineCount");
    const inputMinLines = typeof inputMinLinesConfig === "number" ? $4i(inputMinLinesConfig, 1, 50) : 1;
    const editorMinHeight = inputMinLines * lineHeight + top2 + bottom;
    const inputMaxLinesConfig = this.B.getValue("scm.inputMaxLineCount");
    const inputMaxLines = typeof inputMaxLinesConfig === "number" ? $4i(inputMaxLinesConfig, 1, 50) : 10;
    const editorMaxHeight = inputMaxLines * lineHeight + top2 + bottom;
    return $4i(this.h.getContentHeight(), editorMinHeight, editorMaxHeight);
  }
  layout() {
    const editorHeight = this.getContentHeight();
    const toolbarWidth = this.I();
    const dimension = new $rj(this.d.clientWidth - toolbarWidth, editorHeight);
    if (dimension.width < 0) {
      this.w = true;
      return;
    }
    this.w = false;
    this.h.layout(dimension);
    this.H();
    const showInputActionButton = this.B.getValue("scm.showInputActionButton") === true;
    this.k.classList.toggle("hidden", !showInputActionButton || this.l?.isEmpty() === true);
    if (this.x) {
      this.x = false;
      this.focus();
    }
  }
  focus() {
    if (this.w) {
      this.w = false;
      this.x = true;
      return;
    }
    this.h.focus();
    this.d.classList.add("synthetic-focus");
  }
  hasFocus() {
    return this.h.hasTextFocus();
  }
  G() {
    this.h.updateOptions(this.i.getEditorOptions());
  }
  H() {
    this.clearValidation();
    this.d.classList.toggle(
      "validation-info",
      this.q?.type === 2
      /* InputValidationType.Information */
    );
    this.d.classList.toggle(
      "validation-warning",
      this.q?.type === 1
      /* InputValidationType.Warning */
    );
    this.d.classList.toggle(
      "validation-error",
      this.q?.type === 0
      /* InputValidationType.Error */
    );
    if (!this.q || !this.h.hasTextFocus()) {
      return;
    }
    const disposables = new $2c();
    this.t = this.E.showContextView({
      getAnchor: () => this.d,
      render: (container2) => {
        this.d.style.borderBottomLeftRadius = "0";
        this.d.style.borderBottomRightRadius = "0";
        const validationContainer = $bk(container2, $(".scm-editor-validation-container"));
        validationContainer.classList.toggle(
          "validation-info",
          this.q.type === 2
          /* InputValidationType.Information */
        );
        validationContainer.classList.toggle(
          "validation-warning",
          this.q.type === 1
          /* InputValidationType.Warning */
        );
        validationContainer.classList.toggle(
          "validation-error",
          this.q.type === 0
          /* InputValidationType.Error */
        );
        validationContainer.style.width = `${this.d.clientWidth + 2}px`;
        const element = $bk(validationContainer, $(".scm-editor-validation"));
        const message = this.q.message;
        if (typeof message === "string") {
          element.textContent = message;
        } else {
          const tracker2 = $_j(element);
          disposables.add(tracker2);
          disposables.add(tracker2.onDidFocus(() => this.u = true));
          disposables.add(tracker2.onDidBlur(() => {
            this.u = false;
            this.d.style.borderBottomLeftRadius = "2px";
            this.d.style.borderBottomRightRadius = "2px";
            this.E.hideContextView();
          }));
          const renderer = disposables.add(this.C.createInstance($Q_, {}));
          const renderedMarkdown = renderer.render(message, {
            actionHandler: {
              callback: (link2) => {
                $R_(this.F, link2, message.isTrusted);
                this.d.style.borderBottomLeftRadius = "2px";
                this.d.style.borderBottomRightRadius = "2px";
                this.E.hideContextView();
              },
              disposables
            }
          });
          disposables.add(renderedMarkdown);
          element.appendChild(renderedMarkdown.element);
        }
        const actionsContainer = $bk(validationContainer, $(".scm-editor-validation-actions"));
        const actionbar = new $LZ(actionsContainer);
        const action = new $Um("scmInputWidget.validationMessage.close", localize(9530, null), ThemeIcon.asClassName($6l.close), true, () => {
          this.E.hideContextView();
          this.d.style.borderBottomLeftRadius = "2px";
          this.d.style.borderBottomRightRadius = "2px";
        });
        disposables.add(actionbar);
        actionbar.push(action, { icon: true, label: false });
        return $3c.None;
      },
      onHide: () => {
        this.u = false;
        this.d.style.borderBottomLeftRadius = "2px";
        this.d.style.borderBottomRightRadius = "2px";
        disposables.dispose();
      },
      anchorAlignment: 0
      /* AnchorAlignment.LEFT */
    });
  }
  I() {
    const showInputActionButton = this.B.getValue("scm.showInputActionButton");
    if (!this.l || !showInputActionButton || this.l?.isEmpty() === true) {
      return 0;
    }
    return this.l.dropdownActions.length === 0 ? 26 : 39;
  }
  clearValidation() {
    this.t?.close();
    this.t = void 0;
    this.u = false;
  }
  dispose() {
    this.input = void 0;
    this.p.dispose();
    this.clearValidation();
    this.m.dispose();
  }
};
SCMInputWidget = SCMInputWidget_1 = __decorate([
  __param(2, $on),
  __param(3, $sG),
  __param(4, $Ty),
  __param(5, $kl),
  __param(6, $Pk),
  __param(7, $eS),
  __param(8, $40),
  __param(9, $O4)
], SCMInputWidget);
var $Cac = class $Cac2 extends $_ob {
  get viewMode() {
    return this.ab;
  }
  set viewMode(mode) {
    if (this.ab === mode) {
      return;
    }
    this.ab = mode;
    this.viewSortKey = this.Gc();
    this.Jc();
    this.Ac();
    this.sb.fire(mode);
    this.hc.set(mode);
    this.Kc(this.Fb.getFileIconTheme());
    this.uc.store(
      `scm.viewMode`,
      mode,
      1,
      0
      /* StorageTarget.USER */
    );
  }
  get viewSortKey() {
    return this.ac;
  }
  set viewSortKey(sortKey) {
    if (this.ac === sortKey) {
      return;
    }
    this.ac = sortKey;
    this.Jc();
    this.ic.set(sortKey);
    this.bc.fire(sortKey);
    if (this.ab === "list") {
      this.uc.store(
        `scm.viewSortKey`,
        sortKey,
        1,
        0
        /* StorageTarget.USER */
      );
    }
  }
  constructor(options3, pc, qc, rc, sc, tc, uc, vc, keybindingService, themeService, contextMenuService, instantiationService, viewDescriptorService, configurationService, contextKeyService, openerService, telemetryService, hoverService) {
    super({ ...options3, titleMenuId: $bJ.SCMTitle }, keybindingService, contextMenuService, configurationService, contextKeyService, viewDescriptorService, instantiationService, openerService, themeService, telemetryService, hoverService);
    this.pc = pc;
    this.qc = qc;
    this.rc = rc;
    this.sc = sc;
    this.tc = tc;
    this.uc = uc;
    this.vc = vc;
    this.sb = new $ze();
    this.onDidChangeViewMode = this.sb.event;
    this.bc = new $ze();
    this.onDidChangeViewSortKey = this.bc.event;
    this.cc = new $_c();
    this.dc = new $2c();
    this.ec = new $Qh();
    this.fc = new $Ph();
    this.gc = new $Ph();
    this.oc = new $2c();
    this.ab = this.Fc();
    this.ac = this.Gc();
    this.hc = $Bac.SCMViewMode.bindTo(contextKeyService);
    this.hc.set(this.ab);
    this.ic = $Bac.SCMViewSortKey.bindTo(contextKeyService);
    this.ic.set(this.viewSortKey);
    this.jc = $Bac.SCMViewAreAllRepositoriesCollapsed.bindTo(contextKeyService);
    this.kc = $Bac.SCMViewIsAnyRepositoryCollapsible.bindTo(contextKeyService);
    this.lc = $Bac.SCMProvider.bindTo(contextKeyService);
    this.mc = $Bac.SCMProviderRootUri.bindTo(contextKeyService);
    this.nc = $Bac.SCMProviderHasRootUri.bindTo(contextKeyService);
    this.b = new $ze();
    this.c = { height: void 0, width: void 0, onDidChange: this.b.event };
    this.uc.onDidChangeValue(1, void 0, this.oc)((e) => {
      switch (e.key) {
        case "scm.viewMode":
          this.viewMode = this.Fc();
          break;
        case "scm.viewSortKey":
          this.viewSortKey = this.Gc();
          break;
      }
    }, this, this.oc);
    this.uc.onWillSaveState((e) => {
      this.viewMode = this.Fc();
      this.viewSortKey = this.Gc();
      this.Ic();
    }, this, this.oc);
    Event2.any(this.sc.onDidAddRepository, this.sc.onDidRemoveRepository)(() => this.eb.fire(), this, this.oc);
    this.oc.add(this.fc);
    this.oc.add(this.gc);
  }
  X(height = this.c.height, width2 = this.c.width) {
    if (height === void 0) {
      return;
    }
    if (width2 !== void 0) {
      super.X(height, width2);
    }
    this.c.height = height;
    this.c.width = width2;
    this.b.fire();
    this.h.style.height = `${height}px`;
    this.m.layout(height, width2);
  }
  W(container2) {
    super.W(container2);
    this.h = $bk(container2, $(".scm-view.show-file-icons"));
    this.h.classList.add("file-icon-themable-tree");
    this.h.classList.add("show-file-icons");
    const updateActionsVisibility = () => this.h.classList.toggle("show-actions", this.Ab.getValue("scm.alwaysShowActions"));
    Event2.filter(this.Ab.onDidChangeConfiguration, (e) => e.affectsConfiguration("scm.alwaysShowActions"), this.oc)(updateActionsVisibility, this, this.oc);
    updateActionsVisibility();
    const updateProviderCountVisibility = () => {
      const value = this.Ab.getValue("scm.providerCountBadge");
      this.h.classList.toggle("hide-provider-counts", value === "hidden");
      this.h.classList.toggle("auto-provider-counts", value === "auto");
    };
    Event2.filter(this.Ab.onDidChangeConfiguration, (e) => e.affectsConfiguration("scm.providerCountBadge"), this.oc)(updateProviderCountVisibility, this, this.oc);
    updateProviderCountVisibility();
    const viewState = this.Hc();
    this.yc(this.h, viewState);
    this.onDidChangeBodyVisibility(async (visible) => {
      if (visible) {
        this.ec.queue(async () => {
          await this.m.setInput(this.tc, viewState);
          Event2.filter(this.Ab.onDidChangeConfiguration, (e) => e.affectsConfiguration("scm.alwaysShowRepositories"), this.dc)(() => {
            this.$b();
            this.Jc();
          }, this, this.dc);
          Event2.filter(this.Ab.onDidChangeConfiguration, (e) => e.affectsConfiguration("scm.inputMinLineCount") || e.affectsConfiguration("scm.inputMaxLineCount") || e.affectsConfiguration("scm.showActionButton"), this.dc)(() => this.Jc(), this, this.dc);
          this.qc.onDidActiveEditorChange(this.Ac, this, this.dc);
          this.tc.onDidChangeVisibleRepositories(this.Bc, this, this.dc);
          this.Bc({ added: this.tc.visibleRepositories, removed: Iterable.empty() });
          if (typeof this.f === "number") {
            this.m.scrollTop = this.f;
            this.f = void 0;
          }
          this.Mc();
        });
      } else {
        this.dc.clear();
        this.Bc({ added: Iterable.empty(), removed: [...this.cc.keys()] });
        this.f = this.m.scrollTop;
        this.Mc();
      }
    }, this, this.oc);
    this.oc.add(this.Db.createInstance(RepositoryVisibilityActionController));
    this.Fb.onDidFileIconThemeChange(this.Kc, this, this.oc);
    this.Kc(this.Fb.getFileIconTheme());
  }
  yc(container2, viewState) {
    const overflowWidgetsDomNode = $(".scm-overflow-widgets-container.monaco-editor");
    this.t = this.Db.createInstance(InputRenderer, this.c, overflowWidgetsDomNode, (input, height) => {
      try {
        this.m.updateElementHeight(input, height);
      } catch {
      }
    });
    this.L = this.Db.createInstance($xac);
    this.n = this.Db.createInstance($lsb, { onDidChangeVisibility: this.onDidChangeBodyVisibility });
    this.oc.add(this.n);
    const resourceActionRunner = new RepositoryPaneActionRunner(() => this.Ec());
    resourceActionRunner.onWillRun(() => this.m.domFocus(), this, this.oc);
    this.oc.add(resourceActionRunner);
    const treeDataSource = this.Db.createInstance(SCMTreeDataSource, () => this.viewMode);
    this.oc.add(treeDataSource);
    const compressionEnabled = $G9("scm.compactFolders", true, this.Ab);
    this.m = this.Db.createInstance($5eb, "SCM Tree Repo", container2, new ListDelegate2(this.t), new SCMTreeCompressionDelegate(), [
      this.t,
      this.L,
      this.Db.createInstance($oac, $bJ.SCMTitle, $WQb(this.Db)),
      this.Db.createInstance(ResourceGroupRenderer, $WQb(this.Db)),
      this.Db.createInstance(ResourceRenderer, () => this.viewMode, this.n, $WQb(this.Db), resourceActionRunner)
    ], treeDataSource, {
      horizontalScrolling: false,
      setRowLineHeight: false,
      transformOptimization: false,
      filter: new SCMTreeFilter(),
      dnd: new SCMTreeDragAndDrop(this.Db),
      identityProvider: new SCMResourceIdentityProvider(),
      sorter: new $yac(() => this.viewMode, () => this.viewSortKey),
      keyboardNavigationLabelProvider: this.Db.createInstance($zac, () => this.viewMode),
      overrideStyles: this.Xb().listOverrideStyles,
      compressionEnabled: compressionEnabled.get(),
      collapseByDefault: (e) => {
        if ($LQb(e) || $OQb(e) || $QQb(e)) {
          return false;
        }
        return (viewState?.expanded ?? []).indexOf(getSCMResourceId(e)) === -1;
      },
      accessibilityProvider: this.Db.createInstance($Aac)
    });
    this.oc.add(this.m);
    this.m.onDidOpen(this.zc, this, this.oc);
    this.m.onContextMenu(this.Cc, this, this.oc);
    this.m.onDidScroll(this.t.clearValidation, this.t, this.oc);
    Event2.filter(this.m.onDidChangeCollapseState, (e) => $LQb(e.node.element?.element), this.oc)(this.Mc, this, this.oc);
    this.oc.add($td((reader) => {
      this.m.updateOptions({
        compressionEnabled: compressionEnabled.read(reader)
      });
    }));
    $bk(container2, overflowWidgetsDomNode);
  }
  async zc(e) {
    if (!e.element) {
      return;
    } else if ($LQb(e.element)) {
      this.tc.focus(e.element);
      return;
    } else if ($MQb(e.element)) {
      this.tc.focus(e.element.repository);
      const widget = this.t.getRenderedInputWidget(e.element);
      if (widget) {
        widget.focus();
        this.m.setFocus([], e.browserEvent);
        const selection = this.m.getSelection();
        if (selection.length === 1 && selection[0] === e.element) {
          setTimeout(() => this.m.setSelection([]));
        }
      }
      return;
    } else if ($NQb(e.element)) {
      this.tc.focus(e.element.repository);
      this.L.focusActionButton(e.element);
      this.m.setFocus([], e.browserEvent);
      return;
    } else if ($OQb(e.element)) {
      const provider = e.element.provider;
      const repository = Iterable.find(this.sc.repositories, (r2) => r2.provider === provider);
      if (repository) {
        this.tc.focus(repository);
      }
      return;
    } else if ($PQb(e.element)) {
      if (e.element.command?.id === $$ub || e.element.command?.id === $_ub) {
        if ($5j(e.browserEvent) && e.browserEvent.button === 1) {
          const resourceGroup = e.element.resourceGroup;
          const title = `${resourceGroup.provider.label}: ${resourceGroup.label}`;
          await $wac.openMultiFileDiffEditor(this.qc, title, resourceGroup.provider.rootUri, resourceGroup.id, {
            ...e.editorOptions,
            viewState: {
              revealData: {
                resource: {
                  original: e.element.multiDiffEditorOriginalUri,
                  modified: e.element.multiDiffEditorModifiedUri
                }
              }
            },
            preserveFocus: true
          });
        } else {
          await this.pc.executeCommand(e.element.command.id, ...e.element.command.arguments || [], e);
        }
      } else {
        await e.element.open(!!e.editorOptions.preserveFocus);
        if (e.editorOptions.pinned) {
          const activeEditorPane = this.qc.activeEditorPane;
          activeEditorPane?.group.pinEditor(activeEditorPane.input);
        }
      }
      const provider = e.element.resourceGroup.provider;
      const repository = Iterable.find(this.sc.repositories, (r2) => r2.provider === provider);
      if (repository) {
        this.tc.focus(repository);
      }
    } else if ($QQb(e.element)) {
      const provider = e.element.context.provider;
      const repository = Iterable.find(this.sc.repositories, (r2) => r2.provider === provider);
      if (repository) {
        this.tc.focus(repository);
      }
      return;
    }
  }
  Ac() {
    if (!this.Ab.getValue("scm.autoReveal")) {
      return;
    }
    const uri = $mL.getOriginalUri(this.qc.activeEditor, { supportSideBySide: SideBySideEditor.PRIMARY });
    if (!uri) {
      return;
    }
    if (this.m.getFocus().some((e) => $PQb(e) && this.vc.extUri.isEqual(e.sourceUri, uri)) && this.m.getSelection().some((e) => $PQb(e) && this.vc.extUri.isEqual(e.sourceUri, uri))) {
      return;
    }
    this.fc.queue(() => this.ec.queue(async () => {
      for (const repository of this.tc.visibleRepositories) {
        const item = this.cc.get(repository);
        if (!item) {
          continue;
        }
        for (let j = repository.provider.groups.length - 1; j >= 0; j--) {
          const groupItem = repository.provider.groups[j];
          const resource = this.viewMode === "tree" ? groupItem.resourceTree.getNode(uri)?.element : groupItem.resources.find((r2) => this.vc.extUri.isEqual(r2.sourceUri, uri));
          if (resource) {
            await this.m.expandTo(resource);
            this.m.reveal(resource);
            this.m.setSelection([resource]);
            this.m.setFocus([resource]);
            return;
          }
        }
      }
    }));
  }
  Bc({ added, removed }) {
    for (const repository of added) {
      const repositoryDisposables = new $2c();
      repositoryDisposables.add($td((reader) => {
        repository.provider.actionButton.read(reader);
        this.Jc(repository);
      }));
      repositoryDisposables.add(repository.input.onDidChangeVisibility(() => this.Jc(repository)));
      repositoryDisposables.add(repository.provider.onDidChangeResourceGroups(() => this.Jc(repository)));
      const resourceGroupDisposables = repositoryDisposables.add(new $_c());
      const onDidChangeResourceGroups = () => {
        for (const [resourceGroup] of resourceGroupDisposables) {
          if (!repository.provider.groups.includes(resourceGroup)) {
            resourceGroupDisposables.deleteAndDispose(resourceGroup);
          }
        }
        for (const resourceGroup of repository.provider.groups) {
          if (!resourceGroupDisposables.has(resourceGroup)) {
            const disposableStore = new $2c();
            disposableStore.add(resourceGroup.onDidChange(() => this.Jc(repository)));
            disposableStore.add(resourceGroup.onDidChangeResources(() => this.Jc(repository)));
            resourceGroupDisposables.set(resourceGroup, disposableStore);
          }
        }
      };
      repositoryDisposables.add(repository.provider.onDidChangeResourceGroups(onDidChangeResourceGroups));
      onDidChangeResourceGroups();
      this.cc.set(repository, repositoryDisposables);
    }
    for (const repository of removed) {
      this.cc.deleteAndDispose(repository);
    }
    this.Jc();
    this.Ac();
  }
  Cc(e) {
    if (!e.element) {
      const menu = this.rc.getMenuActions(Menus.ViewSort, this.Bb);
      const actions2 = $P$(menu);
      return this.zb.showContextMenu({
        getAnchor: () => e.anchor,
        getActions: () => actions2,
        onHide: () => {
        }
      });
    }
    const element = e.element;
    let context = element;
    let actions = [];
    let actionRunner = new RepositoryPaneActionRunner(() => this.Ec());
    if ($LQb(element)) {
      const menus = this.tc.menus.getRepositoryMenus(element.provider);
      const menu = menus.repositoryContextMenu;
      context = element.provider;
      actionRunner = new $nac(() => this.Dc());
      actions = $UQb(menu);
    } else if ($MQb(element) || $NQb(element)) {
    } else if ($OQb(element)) {
      const menus = this.tc.menus.getRepositoryMenus(element.provider);
      const menu = menus.getResourceGroupMenu(element);
      actions = $UQb(menu);
    } else if ($PQb(element)) {
      const menus = this.tc.menus.getRepositoryMenus(element.resourceGroup.provider);
      const menu = menus.getResourceMenu(element);
      actions = $UQb(menu);
    } else if ($QQb(element)) {
      if (element.element) {
        const menus = this.tc.menus.getRepositoryMenus(element.element.resourceGroup.provider);
        const menu = menus.getResourceMenu(element.element);
        actions = $UQb(menu);
      } else {
        const menus = this.tc.menus.getRepositoryMenus(element.context.provider);
        const menu = menus.getResourceFolderMenu(element.context);
        actions = $UQb(menu);
      }
    }
    actionRunner.onWillRun(() => this.m.domFocus());
    this.zb.showContextMenu({
      getAnchor: () => e.anchor,
      getActions: () => actions,
      getActionsContext: () => context,
      actionRunner
    });
  }
  Dc() {
    const focusedRepositories = this.m.getFocus().filter((r2) => !!r2 && $LQb(r2));
    const selectedRepositories = this.m.getSelection().filter((r2) => !!r2 && $LQb(r2));
    return Array.from(/* @__PURE__ */ new Set([...focusedRepositories, ...selectedRepositories]));
  }
  Ec() {
    return this.m.getSelection().filter((r2) => !!r2 && !$OQb(r2));
  }
  Fc() {
    let mode = this.Ab.getValue("scm.defaultViewMode") === "list" ? "list" : "tree";
    const storageMode = this.uc.get(
      `scm.viewMode`,
      1
      /* StorageScope.WORKSPACE */
    );
    if (typeof storageMode === "string") {
      mode = storageMode;
    }
    return mode;
  }
  Gc() {
    if (this.ab === "tree") {
      return "path";
    }
    let viewSortKey;
    const viewSortKeyString = this.Ab.getValue("scm.defaultViewSortKey");
    switch (viewSortKeyString) {
      case "name":
        viewSortKey = "name";
        break;
      case "status":
        viewSortKey = "status";
        break;
      default:
        viewSortKey = "path";
        break;
    }
    const storageSortKey = this.uc.get(
      `scm.viewSortKey`,
      1
      /* StorageScope.WORKSPACE */
    );
    if (typeof storageSortKey === "string") {
      viewSortKey = storageSortKey;
    }
    return viewSortKey;
  }
  Hc() {
    const storageViewState = this.uc.get(
      "scm.viewState2",
      1
      /* StorageScope.WORKSPACE */
    );
    if (!storageViewState) {
      return void 0;
    }
    try {
      const treeViewState = JSON.parse(storageViewState);
      return treeViewState;
    } catch {
      return void 0;
    }
  }
  Ic() {
    if (this.m) {
      this.uc.store(
        "scm.viewState2",
        JSON.stringify(this.m.getViewState()),
        1,
        1
        /* StorageTarget.MACHINE */
      );
    }
  }
  Jc(element) {
    this.gc.queue(() => this.ec.queue(async () => {
      const focusedInput = this.t.getFocusedInput();
      if (element && this.m.hasNode(element)) {
        await this.m.updateChildren(element);
      } else {
        await this.m.updateChildren(void 0);
      }
      if (focusedInput) {
        this.t.getRenderedInputWidget(focusedInput)?.focus();
      }
      this.Lc();
      this.Mc();
    }));
  }
  Kc(theme) {
    this.h.classList.toggle(
      "list-view-mode",
      this.viewMode === "list"
      /* ViewMode.List */
    );
    this.h.classList.toggle(
      "tree-view-mode",
      this.viewMode === "tree"
      /* ViewMode.Tree */
    );
    this.h.classList.toggle("align-icons-and-twisties", this.viewMode === "list" && theme.hasFileIcons || theme.hasFileIcons && !theme.hasFolderIcons);
    this.h.classList.toggle("hide-arrows", this.viewMode === "tree" && theme.hidesExplorerArrows === true);
  }
  Lc() {
    const alwaysShowRepositories = this.Ab.getValue("scm.alwaysShowRepositories");
    if (!alwaysShowRepositories && this.cc.size === 1) {
      const provider = Iterable.first(this.cc.keys()).provider;
      this.lc.set(provider.contextValue);
      this.mc.set(provider.rootUri?.toString());
      this.nc.set(!!provider.rootUri);
    } else {
      this.lc.set(void 0);
      this.mc.set(void 0);
      this.nc.set(false);
    }
  }
  Mc() {
    if (!this.isBodyVisible() || this.cc.size === 1) {
      this.kc.set(false);
      this.jc.set(false);
      return;
    }
    this.kc.set(this.tc.visibleRepositories.some((r2) => this.m.hasNode(r2) && this.m.isCollapsible(r2)));
    this.jc.set(this.tc.visibleRepositories.every((r2) => this.m.hasNode(r2) && (!this.m.isCollapsible(r2) || this.m.isCollapsed(r2))));
  }
  collapseAllRepositories() {
    for (const repository of this.tc.visibleRepositories) {
      if (this.m.isCollapsible(repository)) {
        this.m.collapse(repository);
      }
    }
  }
  expandAllRepositories() {
    for (const repository of this.tc.visibleRepositories) {
      if (this.m.isCollapsible(repository)) {
        this.m.expand(repository);
      }
    }
  }
  focusPreviousInput() {
    this.ec.queue(() => this.Nc(-1));
  }
  focusNextInput() {
    this.ec.queue(() => this.Nc(1));
  }
  async Nc(delta) {
    if (!this.tc.focusedRepository || this.tc.visibleRepositories.length === 0) {
      return;
    }
    let input = this.tc.focusedRepository.input;
    const repositories = this.tc.visibleRepositories;
    if (repositories.length === 1 && this.t.getRenderedInputWidget(input)?.hasFocus() === true) {
      return;
    }
    if (repositories.length > 1 && this.t.getRenderedInputWidget(input)?.hasFocus() === true) {
      const focusedRepositoryIndex = repositories.indexOf(this.tc.focusedRepository);
      const newFocusedRepositoryIndex = rot(focusedRepositoryIndex + delta, repositories.length);
      input = repositories[newFocusedRepositoryIndex].input;
    }
    await this.m.expandTo(input);
    this.m.reveal(input);
    this.t.getRenderedInputWidget(input)?.focus();
  }
  focusPreviousResourceGroup() {
    this.ec.queue(() => this.Oc(-1));
  }
  focusNextResourceGroup() {
    this.ec.queue(() => this.Oc(1));
  }
  async Oc(delta) {
    if (!this.tc.focusedRepository || this.tc.visibleRepositories.length === 0) {
      return;
    }
    const treeHasDomFocus = $Mj(this.m.getHTMLElement());
    const resourceGroups = this.tc.focusedRepository.provider.groups;
    const focusedResourceGroup = this.m.getFocus().find((e) => $OQb(e));
    const focusedResourceGroupIndex = treeHasDomFocus && focusedResourceGroup ? resourceGroups.indexOf(focusedResourceGroup) : -1;
    let resourceGroupNext;
    if (focusedResourceGroupIndex === -1) {
      for (const resourceGroup of resourceGroups) {
        if (this.m.hasNode(resourceGroup)) {
          resourceGroupNext = resourceGroup;
          break;
        }
      }
    } else {
      let index = rot(focusedResourceGroupIndex + delta, resourceGroups.length);
      while (index !== focusedResourceGroupIndex) {
        if (this.m.hasNode(resourceGroups[index])) {
          resourceGroupNext = resourceGroups[index];
          break;
        }
        index = rot(index + delta, resourceGroups.length);
      }
    }
    if (resourceGroupNext) {
      await this.m.expandTo(resourceGroupNext);
      this.m.reveal(resourceGroupNext);
      this.m.setSelection([resourceGroupNext]);
      this.m.setFocus([resourceGroupNext]);
      this.m.domFocus();
    }
  }
  shouldShowWelcome() {
    return this.sc.repositoryCount === 0;
  }
  getActionsContext() {
    return this.tc.visibleRepositories.length === 1 ? this.tc.visibleRepositories[0].provider : void 0;
  }
  focus() {
    super.focus();
    this.ec.queue(() => {
      return new Promise((resolve) => {
        if (this.isExpanded()) {
          if (this.m.getFocus().length === 0) {
            for (const repository of this.tc.visibleRepositories) {
              const widget = this.t.getRenderedInputWidget(repository.input);
              if (widget) {
                widget.focus();
                resolve();
                return;
              }
            }
          }
          this.m.domFocus();
          resolve();
        }
      });
    });
  }
  dispose() {
    this.dc.dispose();
    this.oc.dispose();
    this.cc.dispose();
    super.dispose();
  }
};
$Cac = __decorate([
  __param(1, $sn),
  __param(2, $mJ),
  __param(3, $cJ),
  __param(4, $dS),
  __param(5, $eS),
  __param(6, $jv),
  __param(7, $vl),
  __param(8, $Ty),
  __param(9, $gs),
  __param(10, $50),
  __param(11, $Pk),
  __param(12, $$M),
  __param(13, $kl),
  __param(14, $on),
  __param(15, $O4),
  __param(16, $zv),
  __param(17, $5$)
], $Cac);
var SCMTreeDataSource = class SCMTreeDataSource2 extends $3c {
  constructor(b, c, f) {
    super();
    this.b = b;
    this.c = c;
    this.f = f;
  }
  async getChildren(inputOrElement) {
    const repositoryCount = this.f.visibleRepositories.length;
    const showActionButton = this.c.getValue("scm.showActionButton") === true;
    const alwaysShowRepositories = this.c.getValue("scm.alwaysShowRepositories") === true;
    if ($KQb(inputOrElement) && (repositoryCount > 1 || alwaysShowRepositories)) {
      return this.f.visibleRepositories;
    } else if ($KQb(inputOrElement) && repositoryCount === 1 && !alwaysShowRepositories || $LQb(inputOrElement)) {
      const children = [];
      inputOrElement = $LQb(inputOrElement) ? inputOrElement : this.f.visibleRepositories[0];
      const actionButton = inputOrElement.provider.actionButton.get();
      const resourceGroups = inputOrElement.provider.groups;
      if (inputOrElement.input.visible) {
        children.push(inputOrElement.input);
      }
      if (showActionButton && actionButton) {
        children.push({
          type: "actionButton",
          repository: inputOrElement,
          button: actionButton
        });
      }
      const hasSomeChanges = resourceGroups.some((group2) => group2.resources.length > 0);
      if (hasSomeChanges || repositoryCount === 1 && (!showActionButton || !actionButton)) {
        children.push(...resourceGroups);
      }
      return children;
    } else if ($OQb(inputOrElement)) {
      if (this.b() === "list") {
        return inputOrElement.resources;
      } else if (this.b() === "tree") {
        const children = [];
        for (const node of inputOrElement.resourceTree.root.children) {
          children.push(node.element && node.childrenCount === 0 ? node.element : node);
        }
        return children;
      }
    } else if ($QQb(inputOrElement)) {
      const children = [];
      for (const node of inputOrElement.children) {
        children.push(node.element && node.childrenCount === 0 ? node.element : node);
      }
      return children;
    }
    return [];
  }
  getParent(element) {
    if ($QQb(element)) {
      if (element.parent === element.context.resourceTree.root) {
        return element.context;
      } else if (element.parent) {
        return element.parent;
      } else {
        throw new Error("Invalid element passed to getParent");
      }
    } else if ($PQb(element)) {
      if (this.b() === "list") {
        return element.resourceGroup;
      }
      const node = element.resourceGroup.resourceTree.getNode(element.sourceUri);
      const result = node?.parent;
      if (!result) {
        throw new Error("Invalid element passed to getParent");
      }
      if (result === element.resourceGroup.resourceTree.root) {
        return element.resourceGroup;
      }
      return result;
    } else if ($MQb(element)) {
      return element.repository;
    } else if ($OQb(element)) {
      const repository = this.f.visibleRepositories.find((r2) => r2.provider === element.provider);
      if (!repository) {
        throw new Error("Invalid element passed to getParent");
      }
      return repository;
    } else {
      throw new Error("Unexpected call to getParent");
    }
  }
  hasChildren(inputOrElement) {
    if ($KQb(inputOrElement)) {
      return this.f.visibleRepositories.length !== 0;
    } else if ($LQb(inputOrElement)) {
      return true;
    } else if ($MQb(inputOrElement)) {
      return false;
    } else if ($NQb(inputOrElement)) {
      return false;
    } else if ($OQb(inputOrElement)) {
      return true;
    } else if ($PQb(inputOrElement)) {
      return false;
    } else if ($$R.isResourceNode(inputOrElement)) {
      return inputOrElement.childrenCount > 0;
    } else {
      throw new Error("hasChildren not implemented.");
    }
  }
};
SCMTreeDataSource = __decorate([
  __param(1, $kl),
  __param(2, $eS)
], SCMTreeDataSource);
var $Dac = class {
  constructor(d, f, h3, i2) {
    this.d = d;
    this.f = f;
    this.h = h3;
    this.i = i2;
    this.c = new $4c();
  }
  dispose() {
    this.c?.dispose();
  }
  setButton(button) {
    this.k();
    if (!button) {
      return;
    }
    if (button.secondaryCommands?.length) {
      const actions = [];
      for (let index = 0; index < button.secondaryCommands.length; index++) {
        const commands2 = button.secondaryCommands[index];
        for (const command4 of commands2) {
          actions.push(new $Um(command4.id, command4.title, void 0, true, async () => await this.l(command4.id, ...command4.arguments || [])));
        }
        if (commands2.length) {
          actions.push(new $Wm());
        }
      }
      actions.pop();
      this.b = new $l2(this.d, {
        actions,
        addPrimaryActionToDropdown: false,
        contextMenuProvider: this.f,
        title: button.command.tooltip,
        supportIcons: true,
        ...$q$
      });
    } else {
      this.b = new $k2(this.d, { supportIcons: true, supportShortLabel: !!button.command.shortTitle, title: button.command.tooltip, ...$q$ });
    }
    this.b.enabled = button.enabled;
    this.b.label = button.command.title;
    if (this.b instanceof $k2 && button.command.shortTitle) {
      this.b.labelShort = button.command.shortTitle;
    }
    this.b.onDidClick(async () => await this.l(button.command.id, ...button.command.arguments || []), null, this.c.value);
    this.c.value.add(this.b);
  }
  focus() {
    this.b?.focus();
  }
  k() {
    this.c.value = new $2c();
    this.b = void 0;
    $$i(this.d);
  }
  async l(commandId, ...args2) {
    try {
      await this.h.executeCommand(commandId, ...args2);
    } catch (ex) {
      this.i.error(ex);
    }
  }
};
$2sb(".scm-view .scm-editor-container");

// out-build/vs/workbench/contrib/scm/browser/scmRepositoriesViewPane.js
var ListDelegate3 = class {
  getHeight() {
    return 22;
  }
  getTemplateId() {
    return $oac.TEMPLATE_ID;
  }
};
var $Eac = class $Eac2 extends $_ob {
  constructor(options3, c, keybindingService, contextMenuService, instantiationService, viewDescriptorService, contextKeyService, configurationService, openerService, themeService, telemetryService, hoverService) {
    super({ ...options3, titleMenuId: $bJ.SCMSourceControlTitle }, keybindingService, contextMenuService, configurationService, contextKeyService, viewDescriptorService, instantiationService, openerService, themeService, telemetryService, hoverService);
    this.c = c;
    this.b = new $2c();
  }
  W(container2) {
    super.W(container2);
    const listContainer = $bk(container2, $(".scm-view.scm-repositories-view"));
    const updateProviderCountVisibility = () => {
      const value = this.Ab.getValue("scm.providerCountBadge");
      listContainer.classList.toggle("hide-provider-counts", value === "hidden");
      listContainer.classList.toggle("auto-provider-counts", value === "auto");
    };
    this.B(Event2.filter(this.Ab.onDidChangeConfiguration, (e) => e.affectsConfiguration("scm.providerCountBadge"), this.b)(updateProviderCountVisibility));
    updateProviderCountVisibility();
    const delegate = new ListDelegate3();
    const renderer = this.Db.createInstance($oac, $bJ.SCMSourceControlInline, $WQb(this.Db));
    const identityProvider3 = { getId: (r2) => r2.provider.id };
    this.a = this.Db.createInstance($Web, `SCM Main`, listContainer, delegate, [renderer], {
      identityProvider: identityProvider3,
      horizontalScrolling: false,
      overrideStyles: this.Xb().listOverrideStyles,
      accessibilityProvider: {
        getAriaLabel(r2) {
          return r2.provider.label;
        },
        getWidgetAriaLabel() {
          return localize(9513, null);
        }
      }
    });
    this.B(this.a);
    this.B(this.a.onDidChangeSelection(this.n, this));
    this.B(this.a.onContextMenu(this.m, this));
    this.B(this.c.onDidChangeRepositories(this.g, this));
    this.B(this.c.onDidChangeVisibleRepositories(this.s, this));
    if (this.orientation === 0) {
      this.B(this.Ab.onDidChangeConfiguration((e) => {
        if (e.affectsConfiguration("scm.repositories.visible")) {
          this.j();
        }
      }));
    }
    this.g();
    this.s();
  }
  g() {
    this.a.splice(0, this.a.length, this.c.repositories);
    this.j();
  }
  focus() {
    super.focus();
    this.a.domFocus();
  }
  X(height, width2) {
    super.X(height, width2);
    this.a.layout(height, width2);
  }
  j() {
    if (this.orientation === 1) {
      return;
    }
    const visibleCount = this.Ab.getValue("scm.repositories.visible");
    const empty = this.a.length === 0;
    const size = Math.min(this.a.length, visibleCount) * 22;
    this.minimumBodySize = visibleCount === 0 ? 22 : size;
    this.maximumBodySize = visibleCount === 0 ? Number.POSITIVE_INFINITY : empty ? Number.POSITIVE_INFINITY : size;
  }
  m(e) {
    if (!e.element) {
      return;
    }
    const provider = e.element.provider;
    const menus = this.c.menus.getRepositoryMenus(provider);
    const menu = menus.repositoryContextMenu;
    const actions = $UQb(menu);
    const actionRunner = this.B(new $nac(() => {
      return this.a.getSelectedElements();
    }));
    actionRunner.onWillRun(() => this.a.domFocus());
    this.zb.showContextMenu({
      actionRunner,
      getAnchor: () => e.anchor,
      getActions: () => actions,
      getActionsContext: () => provider
    });
  }
  n(e) {
    if (e.browserEvent && e.elements.length > 0) {
      const scrollTop = this.a.scrollTop;
      this.c.visibleRepositories = e.elements;
      this.a.scrollTop = scrollTop;
    }
  }
  s() {
    const oldSelection = this.a.getSelection();
    const oldSet = new Set(Iterable.map(oldSelection, (i2) => this.a.element(i2)));
    const set = new Set(this.c.visibleRepositories);
    const added = new Set(Iterable.filter(set, (r2) => !oldSet.has(r2)));
    const removed = new Set(Iterable.filter(oldSet, (r2) => !set.has(r2)));
    if (added.size === 0 && removed.size === 0) {
      return;
    }
    const selection = oldSelection.filter((i2) => !removed.has(this.a.element(i2)));
    for (let i2 = 0; i2 < this.a.length; i2++) {
      if (added.has(this.a.element(i2))) {
        selection.push(i2);
      }
    }
    this.a.setSelection(selection);
    if (selection.length > 0 && selection.indexOf(this.a.getFocus()[0]) === -1) {
      this.a.setAnchor(selection[0]);
      this.a.setFocus([selection[0]]);
    }
  }
  dispose() {
    this.b.dispose();
    super.dispose();
  }
};
$Eac = __decorate([
  __param(1, $eS),
  __param(2, $Ty),
  __param(3, $50),
  __param(4, $Pk),
  __param(5, $$M),
  __param(6, $on),
  __param(7, $kl),
  __param(8, $O4),
  __param(9, $gs),
  __param(10, $zv),
  __param(11, $5$)
], $Eac);

// out-build/vs/workbench/contrib/workspace/common/workspace.js
var $Fac = {
  IsEnabled: new $nn("isWorkspaceTrustEnabled", false, localize(12260, null)),
  IsTrusted: new $nn("isWorkspaceTrusted", false, localize(12261, null))
};
var $Gac = "workbench.trust.manage";

// out-build/vs/workbench/contrib/scm/common/quickDiffService.js
function createProviderComparer(uri) {
  return (a, b) => {
    if (a.rootUri && !b.rootUri) {
      return -1;
    } else if (!a.rootUri && b.rootUri) {
      return 1;
    } else if (!a.rootUri && !b.rootUri) {
      return 0;
    }
    const aIsParent = $ph(uri, a.rootUri);
    const bIsParent = $ph(uri, b.rootUri);
    if (aIsParent && bIsParent) {
      return a.rootUri.fsPath.length - b.rootUri.fsPath.length;
    } else if (aIsParent) {
      return -1;
    } else if (bIsParent) {
      return 1;
    } else {
      return 0;
    }
  };
}
var $Hac = class $Hac2 extends $3c {
  constructor(g) {
    super();
    this.g = g;
    this.c = /* @__PURE__ */ new Set();
    this.f = this.B(new $ze());
    this.onDidChangeQuickDiffProviders = this.f.event;
  }
  addQuickDiffProvider(quickDiff) {
    this.c.add(quickDiff);
    this.f.fire();
    return {
      dispose: () => {
        this.c.delete(quickDiff);
        this.f.fire();
      }
    };
  }
  h(diff3) {
    return !!diff3.originalResource && typeof diff3.label === "string" && typeof diff3.isSCM === "boolean";
  }
  async getQuickDiffs(uri, language = "", isSynchronized = false) {
    const providers2 = Array.from(this.c).filter((provider) => !provider.rootUri || this.g.extUri.isEqualOrParent(uri, provider.rootUri)).sort(createProviderComparer(uri));
    const diffs = await Promise.all(providers2.map(async (provider) => {
      const scoreValue = provider.selector ? $qE(provider.selector, uri, language, isSynchronized, void 0, void 0) : 10;
      const diff3 = {
        originalResource: scoreValue > 0 ? await provider.getOriginalResource(uri) ?? void 0 : void 0,
        label: provider.label,
        isSCM: provider.isSCM,
        visible: provider.visible
      };
      return diff3;
    }));
    return diffs.filter(this.h);
  }
};
$Hac = __decorate([
  __param(0, $vl)
], $Hac);

// out-build/vs/workbench/contrib/scm/browser/workingSet.js
var $Iac = class $Iac2 extends $3c {
  static {
    this.ID = "workbench.contrib.scmWorkingSets";
  }
  constructor(f, g, h3, j, m) {
    super();
    this.f = f;
    this.g = g;
    this.h = h3;
    this.j = j;
    this.m = m;
    this.b = $G9("scm.workingSets.enabled", false, this.f);
    this.c = new $_c();
    this.q.add($xd((reader, store) => {
      if (!this.b.read(reader)) {
        this.j.remove(
          "scm.workingSets",
          1
          /* StorageScope.WORKSPACE */
        );
        this.c.clearAndDisposeAll();
        return;
      }
      this.a = this.s();
      this.h.onDidAddRepository(this.n, this, store);
      this.h.onDidRemoveRepository(this.r, this, store);
      for (const repository of this.h.repositories) {
        this.n(repository);
      }
    }));
  }
  n(repository) {
    const disposables = new $2c();
    const historyItemRefId = $2d((reader) => {
      const historyProvider = repository.provider.historyProvider.read(reader);
      const historyItemRef = historyProvider?.historyItemRef.read(reader);
      return historyItemRef?.id;
    });
    disposables.add($td(async (reader) => {
      const historyItemRefIdValue = historyItemRefId.read(reader);
      if (!historyItemRefIdValue) {
        return;
      }
      const providerKey = $XQb(repository.provider);
      const repositoryWorkingSets = this.a.get(providerKey);
      if (!repositoryWorkingSets) {
        this.a.set(providerKey, { currentHistoryItemGroupId: historyItemRefIdValue, editorWorkingSets: /* @__PURE__ */ new Map() });
        return;
      }
      if (repositoryWorkingSets.currentHistoryItemGroupId === historyItemRefIdValue) {
        return;
      }
      this.t(providerKey, historyItemRefIdValue, repositoryWorkingSets);
      await this.u(providerKey, historyItemRefIdValue);
    }));
    this.c.set(repository, disposables);
  }
  r(repository) {
    this.c.deleteAndDispose(repository);
  }
  s() {
    const workingSets = /* @__PURE__ */ new Map();
    const workingSetsRaw = this.j.get(
      "scm.workingSets",
      1
      /* StorageScope.WORKSPACE */
    );
    if (!workingSetsRaw) {
      return workingSets;
    }
    for (const serializedWorkingSet of JSON.parse(workingSetsRaw)) {
      workingSets.set(serializedWorkingSet.providerKey, {
        currentHistoryItemGroupId: serializedWorkingSet.currentHistoryItemGroupId,
        editorWorkingSets: new Map(serializedWorkingSet.editorWorkingSets)
      });
    }
    return workingSets;
  }
  t(providerKey, currentHistoryItemGroupId, repositoryWorkingSets) {
    const previousHistoryItemGroupId = repositoryWorkingSets.currentHistoryItemGroupId;
    const editorWorkingSets = repositoryWorkingSets.editorWorkingSets;
    const editorWorkingSet = this.g.saveWorkingSet(previousHistoryItemGroupId);
    this.a.set(providerKey, { currentHistoryItemGroupId, editorWorkingSets: editorWorkingSets.set(previousHistoryItemGroupId, editorWorkingSet) });
    const workingSets = [];
    for (const [providerKey2, { currentHistoryItemGroupId: currentHistoryItemGroupId2, editorWorkingSets: editorWorkingSets2 }] of this.a) {
      workingSets.push({ providerKey: providerKey2, currentHistoryItemGroupId: currentHistoryItemGroupId2, editorWorkingSets: [...editorWorkingSets2] });
    }
    this.j.store(
      "scm.workingSets",
      JSON.stringify(workingSets),
      1,
      1
      /* StorageTarget.MACHINE */
    );
  }
  async u(providerKey, currentHistoryItemGroupId) {
    const workingSets = this.a.get(providerKey);
    if (!workingSets) {
      return;
    }
    let editorWorkingSetId = workingSets.editorWorkingSets.get(currentHistoryItemGroupId);
    if (!editorWorkingSetId && this.f.getValue("scm.workingSets.default") === "empty") {
      editorWorkingSetId = "empty";
    }
    if (editorWorkingSetId) {
      const preserveFocus = this.m.hasFocus(
        "workbench.parts.panel"
        /* Parts.PANEL_PART */
      );
      await this.g.applyWorkingSet(editorWorkingSetId, { preserveFocus });
    }
  }
  dispose() {
    this.c.dispose();
    super.dispose();
  }
};
$Iac = __decorate([
  __param(0, $kl),
  __param(1, $iJ),
  __param(2, $dS),
  __param(3, $jv),
  __param(4, $Vlb)
], $Iac);

// out-build/vs/workbench/contrib/scm/browser/scmHistoryViewPane.js
var HistoryItemRenderer_1;
var HistoryItemLoadMoreRenderer_1;
var PICK_REPOSITORY_ACTION_ID = "workbench.scm.action.graph.pickRepository";
var PICK_HISTORY_ITEM_REFS_ACTION_ID = "workbench.scm.action.graph.pickHistoryItemRefs";
var SCMRepositoryActionViewItem = class extends $U1 {
  constructor(c, action, options3) {
    super(null, action, { ...options3, icon: false, label: true });
    this.c = c;
  }
  C() {
    if (this.u.label && this.L) {
      this.L.classList.add("scm-graph-repository-picker");
      const icon2 = $(".icon");
      icon2.classList.add(...ThemeIcon.asClassNameArray($6l.repo));
      const name = $(".name");
      name.textContent = this.c.provider.name;
      $dk(this.L, icon2, name);
    }
  }
  F() {
    return this.c.provider.name;
  }
};
var SCMHistoryItemRefsActionViewItem = class extends $U1 {
  constructor(c, g, action, options3) {
    super(null, action, { ...options3, icon: false, label: true });
    this.c = c;
    this.g = g;
  }
  C() {
    if (this.u.label && this.L) {
      this.L.classList.add("scm-graph-history-item-picker");
      const icon2 = $(".icon");
      icon2.classList.add(...ThemeIcon.asClassNameArray($6l.gitBranch));
      const name = $(".name");
      if (this.g === "all") {
        name.textContent = localize(9485, null);
      } else if (this.g === "auto") {
        name.textContent = localize(9486, null);
      } else if (this.g.length === 1) {
        name.textContent = this.g[0].name;
      } else {
        name.textContent = localize(9487, null, this.g.length);
      }
      $dk(this.L, icon2, name);
    }
  }
  F() {
    if (this.g === "all") {
      return localize(9488, null);
    } else if (this.g === "auto") {
      const historyProvider = this.c.provider.historyProvider.get();
      return [
        historyProvider?.historyItemRef.get()?.name,
        historyProvider?.historyItemRemoteRef.get()?.name,
        historyProvider?.historyItemBaseRef.get()?.name
      ].filter((ref) => !!ref).join(", ");
    } else if (this.g.length === 1) {
      return this.g[0].name;
    } else {
      return this.g.map((ref) => ref.name).join(", ");
    }
  }
};
$hJ(class extends $cpb {
  constructor() {
    super({
      id: PICK_REPOSITORY_ACTION_ID,
      title: localize(9489, null),
      viewId: $cS,
      f1: false,
      menu: {
        id: $bJ.SCMHistoryTitle,
        when: $7m.and($7m.has("scm.providerCount"), $7m.greater("scm.providerCount", 1)),
        group: "navigation",
        order: 0
      }
    });
  }
  async runInView(_, view) {
    view.pickRepository();
  }
});
$hJ(class extends $cpb {
  constructor() {
    super({
      id: PICK_HISTORY_ITEM_REFS_ACTION_ID,
      title: localize(9490, null),
      icon: $6l.gitBranch,
      viewId: $cS,
      precondition: $Bac.SCMHistoryItemCount.notEqualsTo(0),
      f1: false,
      menu: {
        id: $bJ.SCMHistoryTitle,
        group: "navigation",
        order: 1
      }
    });
  }
  async runInView(_, view) {
    view.pickHistoryItemRef();
  }
});
$hJ(class extends $cpb {
  constructor() {
    super({
      id: "workbench.scm.action.graph.revealCurrentHistoryItem",
      title: localize(9491, null),
      icon: $6l.target,
      viewId: $cS,
      precondition: $7m.and($Bac.SCMHistoryItemCount.notEqualsTo(0), $Bac.SCMCurrentHistoryItemRefInFilter.isEqualTo(true)),
      f1: false,
      menu: {
        id: $bJ.SCMHistoryTitle,
        group: "navigation",
        order: 2
      }
    });
  }
  async runInView(_, view) {
    view.revealCurrentHistoryItem();
  }
});
$hJ(class extends $cpb {
  constructor() {
    super({
      id: "workbench.scm.action.graph.refresh",
      title: localize(9492, null),
      viewId: $cS,
      f1: false,
      icon: $6l.refresh,
      menu: {
        id: $bJ.SCMHistoryTitle,
        group: "navigation",
        order: 1e3
      }
    });
  }
  async runInView(_, view) {
    view.refresh();
  }
});
$hJ(class extends $gJ {
  constructor() {
    super({
      id: "workbench.scm.action.graph.viewChanges",
      title: localize(9493, null),
      f1: false,
      menu: [
        {
          id: $bJ.SCMChangesContext,
          group: "0_view",
          when: $7m.equals("config.multiDiffEditor.experimental.enabled", true)
        }
      ]
    });
  }
  async run(accessor, provider, ...historyItems) {
    const commandService = accessor.get($sn);
    if (!provider || historyItems.length === 0) {
      return;
    }
    const historyItem = historyItems[0];
    const historyItemLast = historyItems[historyItems.length - 1];
    const historyProvider = provider.historyProvider.get();
    if (historyItems.length > 1) {
      const ancestor = await historyProvider?.resolveHistoryItemRefsCommonAncestor([historyItem.id, historyItemLast.id]);
      if (!ancestor || ancestor !== historyItem.id && ancestor !== historyItemLast.id) {
        return;
      }
    }
    const historyItemParentId = historyItemLast.parentIds.length > 0 ? historyItemLast.parentIds[0] : void 0;
    const historyItemChanges = await historyProvider?.provideHistoryItemChanges(historyItem.id, historyItemParentId);
    if (!historyItemChanges?.length) {
      return;
    }
    const title = historyItems.length === 1 ? $ZQb(historyItem) : localize(9494, null, historyItemLast.displayId ?? historyItemLast.id, historyItem.displayId ?? historyItem.id);
    const rootUri = provider.rootUri;
    const path = rootUri ? rootUri.path : provider.label;
    const multiDiffSourceUri = URI.from({ scheme: "scm-history-item", path: `${path}/${historyItemParentId}..${historyItem.id}` }, true);
    commandService.executeCommand("_workbench.openMultiDiffEditor", { title, multiDiffSourceUri, resources: historyItemChanges });
  }
});
var ListDelegate4 = class {
  getHeight() {
    return 22;
  }
  getTemplateId(element) {
    if ($RQb(element)) {
      return HistoryItemRenderer.TEMPLATE_ID;
    } else if ($SQb(element)) {
      return HistoryItemLoadMoreRenderer.TEMPLATE_ID;
    } else {
      throw new Error("Unknown element");
    }
  }
};
var HistoryItemRenderer = class HistoryItemRenderer2 {
  static {
    HistoryItemRenderer_1 = this;
  }
  static {
    this.TEMPLATE_ID = "history-item";
  }
  get templateId() {
    return HistoryItemRenderer_1.TEMPLATE_ID;
  }
  constructor(d, f, g, j, k) {
    this.d = d;
    this.f = f;
    this.g = g;
    this.j = j;
    this.k = k;
    this.c = $G9("scm.graph.badges", "filter", this.g);
  }
  renderTemplate(container2) {
    container2.parentElement.parentElement.querySelector(".monaco-tl-twistie").classList.add("force-no-twistie");
    const element = $bk(container2, $(".history-item"));
    const graphContainer = $bk(element, $(".graph-container"));
    const iconLabel = new $T2(element, { supportIcons: true, supportHighlights: true, supportDescriptionHighlights: true });
    const labelContainer = $bk(element, $(".label-container"));
    element.appendChild(labelContainer);
    return { element, graphContainer, label: iconLabel, labelContainer, elementDisposables: new $2c(), disposables: new $2c() };
  }
  renderElement(node, index, templateData, height) {
    const historyItemViewModel = node.element.historyItemViewModel;
    const historyItem = historyItemViewModel.historyItem;
    const historyItemHover = this.j.setupManagedHover(this.d, templateData.element, this.o(node.element), {
      actions: this.n(historyItem)
    });
    templateData.elementDisposables.add(historyItemHover);
    templateData.graphContainer.textContent = "";
    templateData.graphContainer.classList.toggle("current", historyItemViewModel.isCurrent);
    templateData.graphContainer.appendChild($aRb(historyItemViewModel));
    const provider = node.element.repository.provider;
    const historyItemRef = provider.historyProvider.get()?.historyItemRef?.get();
    const extraClasses = historyItemRef?.revision === historyItem.id ? ["history-item-current"] : [];
    const [matches, descriptionMatches] = this.p(historyItemViewModel, node.filterData);
    templateData.label.setLabel(historyItem.subject, historyItem.author, { matches, descriptionMatches, extraClasses });
    this.l(historyItem, templateData);
  }
  l(historyItem, templateData) {
    templateData.elementDisposables.add($td((reader) => {
      const labelConfig = this.c.read(reader);
      templateData.labelContainer.textContent = "";
      const references = historyItem.references ? historyItem.references.slice(0) : [];
      if (references.length > 0 && references[0].color) {
        this.m([references[0]], true, templateData);
        references.splice(0, 1);
      }
      const historyItemRefsByColor = $a(references, (ref) => ref.color ? ref.color : "");
      for (const [key2, historyItemRefs] of Object.entries(historyItemRefsByColor)) {
        if (key2 === "" && labelConfig !== "all") {
          continue;
        }
        const historyItemRefByIconId = $a(historyItemRefs, (ref) => ThemeIcon.isThemeIcon(ref.icon) ? ref.icon.id : "");
        for (const [key3, historyItemRefs2] of Object.entries(historyItemRefByIconId)) {
          if (key3 === "") {
            continue;
          }
          this.m(historyItemRefs2, false, templateData);
        }
      }
    }));
  }
  m(historyItemRefs, showDescription, templateData) {
    if (historyItemRefs.length === 0 || !ThemeIcon.isThemeIcon(historyItemRefs[0].icon)) {
      return;
    }
    const elements = h("div.label", {
      style: {
        color: historyItemRefs[0].color ? $Zn($9Qb) : $Zn($eo),
        backgroundColor: historyItemRefs[0].color ? $Zn(historyItemRefs[0].color) : $Zn($8Qb)
      }
    }, [
      h("div.count@count", {
        style: {
          display: historyItemRefs.length > 1 ? "" : "none"
        }
      }),
      h("div.icon@icon"),
      h("div.description@description", {
        style: {
          display: showDescription ? "" : "none"
        }
      })
    ]);
    elements.count.textContent = historyItemRefs.length > 1 ? historyItemRefs.length.toString() : "";
    elements.icon.classList.add(...ThemeIcon.asClassNameArray(historyItemRefs[0].icon));
    elements.description.textContent = showDescription ? historyItemRefs[0].name : "";
    $bk(templateData.labelContainer, elements.root);
  }
  n(historyItem) {
    return [
      {
        commandId: "workbench.scm.action.graph.copyHistoryItemId",
        iconClass: "codicon.codicon-copy",
        label: historyItem.displayId ?? historyItem.id,
        run: () => this.f.writeText(historyItem.id)
      },
      {
        commandId: "workbench.scm.action.graph.copyHistoryItemMessage",
        iconClass: "codicon.codicon-copy",
        label: localize(9495, null),
        run: () => this.f.writeText(historyItem.message)
      }
    ];
  }
  o(element) {
    const colorTheme = this.k.getColorTheme();
    const historyItem = element.historyItemViewModel.historyItem;
    const markdown = new $bm("", { isTrusted: true, supportThemeIcons: true });
    if (historyItem.author) {
      markdown.appendMarkdown(`$(account) **${historyItem.author}**`);
      if (historyItem.timestamp) {
        const dateFormatter = $Uu.DateTimeFormat($z, { year: "numeric", month: "long", day: "numeric", hour: "numeric", minute: "numeric" });
        markdown.appendMarkdown(`, $(history) ${$Qu(historyItem.timestamp, true, true)} (${dateFormatter.format(historyItem.timestamp)})`);
      }
      markdown.appendMarkdown("\n\n");
    }
    markdown.appendMarkdown(`${historyItem.message}

`);
    if (historyItem.statistics) {
      markdown.appendMarkdown(`---

`);
      markdown.appendMarkdown(`<span>${historyItem.statistics.files === 1 ? localize(9496, null, historyItem.statistics.files) : localize(9497, null, historyItem.statistics.files)}</span>`);
      if (historyItem.statistics.insertions) {
        const additionsForegroundColor = colorTheme.getColor($0Qb);
        markdown.appendMarkdown(`,&nbsp;<span style="color:${additionsForegroundColor};">${historyItem.statistics.insertions === 1 ? localize(9498, null, historyItem.statistics.insertions, "(+)") : localize(9499, null, historyItem.statistics.insertions, "(+)")}</span>`);
      }
      if (historyItem.statistics.deletions) {
        const deletionsForegroundColor = colorTheme.getColor($$Qb);
        markdown.appendMarkdown(`,&nbsp;<span style="color:${deletionsForegroundColor};">${historyItem.statistics.deletions === 1 ? localize(9500, null, historyItem.statistics.deletions, "(-)") : localize(9501, null, historyItem.statistics.deletions, "(-)")}</span>`);
      }
    }
    if ((historyItem.references ?? []).length > 0) {
      markdown.appendMarkdown(`

---

`);
      markdown.appendMarkdown((historyItem.references ?? []).map((ref) => {
        const labelIconId = ThemeIcon.isThemeIcon(ref.icon) ? ref.icon.id : "";
        const labelBackgroundColor = ref.color ? $Zn(ref.color) : $Zn($8Qb);
        const labelForegroundColor = ref.color ? $Zn($9Qb) : $Zn($7Qb);
        return `<span style="color:${labelForegroundColor};background-color:${labelBackgroundColor};border-radius:10px;">&nbsp;$(${labelIconId})&nbsp;${ref.name}&nbsp;&nbsp;</span>`;
      }).join("&nbsp;&nbsp;"));
    }
    return { markdown, markdownNotSupportedFallback: historyItem.message };
  }
  p(historyItemViewModel, filterData) {
    if (!filterData) {
      return [void 0, void 0];
    }
    return [
      historyItemViewModel.historyItem.message === filterData.label ? $Ul(filterData.score) : void 0,
      historyItemViewModel.historyItem.author === filterData.label ? $Ul(filterData.score) : void 0
    ];
  }
  disposeElement(element, index, templateData, height) {
    templateData.elementDisposables.clear();
  }
  disposeTemplate(templateData) {
    templateData.disposables.dispose();
  }
};
HistoryItemRenderer = HistoryItemRenderer_1 = __decorate([
  __param(1, $30),
  __param(2, $kl),
  __param(3, $5$),
  __param(4, $gs)
], HistoryItemRenderer);
var HistoryItemLoadMoreRenderer = class HistoryItemLoadMoreRenderer2 {
  static {
    HistoryItemLoadMoreRenderer_1 = this;
  }
  static {
    this.TEMPLATE_ID = "historyItemLoadMore";
  }
  get templateId() {
    return HistoryItemLoadMoreRenderer_1.TEMPLATE_ID;
  }
  constructor(c, d, f) {
    this.c = c;
    this.d = d;
    this.f = f;
  }
  renderTemplate(container2) {
    container2.parentElement.parentElement.querySelector(".monaco-tl-twistie").classList.add("force-no-twistie");
    const element = $bk(container2, $(".history-item-load-more"));
    const graphPlaceholder = $bk(element, $(".graph-placeholder"));
    const historyItemPlaceholderContainer = $bk(element, $(".history-item-placeholder"));
    const historyItemPlaceholderLabel = new $T2(historyItemPlaceholderContainer, { supportIcons: true });
    return { element, graphPlaceholder, historyItemPlaceholderContainer, historyItemPlaceholderLabel, elementDisposables: new $2c(), disposables: new $2c() };
  }
  renderElement(element, index, templateData, height) {
    templateData.graphPlaceholder.textContent = "";
    templateData.graphPlaceholder.style.width = `${$3Qb * (element.element.graphColumns.length + 1)}px`;
    templateData.graphPlaceholder.appendChild($bRb(element.element.graphColumns));
    const pageOnScroll = this.f.getValue("scm.graph.pageOnScroll") === true;
    templateData.historyItemPlaceholderContainer.classList.toggle("shimmer", pageOnScroll);
    if (pageOnScroll) {
      templateData.historyItemPlaceholderLabel.setLabel("");
      this.d();
    } else {
      templateData.elementDisposables.add($td((reader) => {
        const isLoadingMore = this.c.read(reader);
        const icon2 = `$(${isLoadingMore ? "loading~spin" : "fold-down"})`;
        templateData.historyItemPlaceholderLabel.setLabel(localize(9502, null, icon2));
      }));
    }
  }
  disposeElement(element, index, templateData, height) {
    templateData.elementDisposables.clear();
  }
  disposeTemplate(templateData) {
    templateData.disposables.dispose();
  }
};
HistoryItemLoadMoreRenderer = HistoryItemLoadMoreRenderer_1 = __decorate([
  __param(2, $kl)
], HistoryItemLoadMoreRenderer);
var HistoryItemHoverDelegate = class HistoryItemHoverDelegate2 extends $6$ {
  constructor(w, y, configurationService, hoverService) {
    super("element", true, () => this.z(), configurationService, hoverService);
    this.w = w;
    this.y = y;
  }
  z() {
    const sideBarPosition = this.y.getSideBarPosition();
    let hoverPosition;
    if (this.w === 0) {
      hoverPosition = sideBarPosition === 0 ? 1 : 0;
    } else if (this.w === 2) {
      hoverPosition = sideBarPosition === 0 ? 0 : 1;
    } else {
      hoverPosition = 1;
    }
    return { additionalClasses: ["history-item-hover"], position: { hoverPosition, forcePosition: true } };
  }
};
HistoryItemHoverDelegate = __decorate([
  __param(1, $Vlb),
  __param(2, $kl),
  __param(3, $5$)
], HistoryItemHoverDelegate);
var SCMHistoryViewPaneActionRunner = class SCMHistoryViewPaneActionRunner2 extends $Vm {
  constructor(c) {
    super();
    this.c = c;
  }
  u(action, context) {
    return this.c.withProgress({ location: $cS }, async () => await super.u(action, context));
  }
};
SCMHistoryViewPaneActionRunner = __decorate([
  __param(0, $TJ)
], SCMHistoryViewPaneActionRunner);
var SCMHistoryTreeAccessibilityProvider = class {
  getWidgetAriaLabel() {
    return localize(9503, null);
  }
  getAriaLabel(element) {
    if ($LQb(element)) {
      return `${element.provider.name} ${element.provider.label}`;
    } else if ($RQb(element)) {
      const historyItem = element.historyItemViewModel.historyItem;
      return `${$0l(historyItem.message).trim()}${historyItem.author ? `, ${historyItem.author}` : ""}`;
    } else {
      return "";
    }
  }
};
var SCMHistoryTreeIdentityProvider = class {
  getId(element) {
    if ($LQb(element)) {
      const provider = element.provider;
      return `repo:${provider.id}`;
    } else if ($RQb(element)) {
      const provider = element.repository.provider;
      const historyItem = element.historyItemViewModel.historyItem;
      return `historyItem:${provider.id}/${historyItem.id}/${historyItem.parentIds.join(",")}`;
    } else if ($SQb(element)) {
      const provider = element.repository.provider;
      return `historyItemLoadMore:${provider.id}}`;
    } else {
      throw new Error("Invalid tree element");
    }
  }
};
var SCMHistoryTreeKeyboardNavigationLabelProvider = class {
  getKeyboardNavigationLabel(element) {
    if ($LQb(element)) {
      return void 0;
    } else if ($RQb(element)) {
      return [element.historyItemViewModel.historyItem.message, element.historyItemViewModel.historyItem.author];
    } else if ($SQb(element)) {
      return "";
    } else {
      throw new Error("Invalid tree element");
    }
  }
};
var SCMHistoryTreeDataSource = class extends $3c {
  async getChildren(inputOrElement) {
    if (!(inputOrElement instanceof SCMHistoryViewModel)) {
      return [];
    }
    const children = [];
    const historyItems = await inputOrElement.getHistoryItems();
    children.push(...historyItems);
    const repository = inputOrElement.repository.get();
    const lastHistoryItem = historyItems.at(-1);
    if (repository && lastHistoryItem && lastHistoryItem.historyItemViewModel.outputSwimlanes.length > 0) {
      children.push({
        repository,
        graphColumns: lastHistoryItem.historyItemViewModel.outputSwimlanes,
        type: "historyItemLoadMore"
      });
    }
    return children;
  }
  hasChildren(inputOrElement) {
    return inputOrElement instanceof SCMHistoryViewModel;
  }
};
var SCMHistoryViewModel = class SCMHistoryViewModel2 extends $3c {
  constructor(t, u, w, y, z, C) {
    super();
    this.t = t;
    this.u = u;
    this.w = w;
    this.y = y;
    this.z = z;
    this.C = C;
    this.c = $Dd(this, this.y.onDidRemoveRepository, (repository) => repository);
    this.f = this.y.repositoryCount > 0 ? $Bd(Iterable.first(this.y.repositories)) : $Dd(this, Event2.once(this.y.onDidAddRepository), (repository) => repository);
    this.g = $he(this, "auto");
    this.j = $2d((reader) => {
      const selectedRepository = this.g.read(reader);
      if (selectedRepository !== "auto") {
        return selectedRepository;
      }
      return this.z.activeRepository.read(reader);
    });
    this.repository = $Ud(this, [this.f, this.j]);
    this.onDidChangeHistoryItemsFilter = $Hd(this);
    this.isViewModelEmpty = $he(this, false);
    this.m = /* @__PURE__ */ new Map();
    this.n = /* @__PURE__ */ new Map();
    this.n = this.G();
    this.w.onWillStop(this.H, this, this.q);
    this.C.onWillSaveState(this.H, this, this.q);
    this.s = $Bac.SCMHistoryItemCount.bindTo(this.u);
    this.B($td((reader) => {
      const repository = this.c.read(reader);
      if (!repository) {
        return;
      }
      if (this.repository.get() === repository) {
        this.g.set(Iterable.first(this.y.repositories) ?? "auto", void 0);
      }
      this.m.delete(repository);
    }));
  }
  clearRepositoryState() {
    const repository = this.repository.get();
    if (!repository) {
      return;
    }
    this.m.delete(repository);
  }
  getHistoryItemsFilter() {
    const repository = this.repository.get();
    if (!repository) {
      return;
    }
    const filterState = this.n.get($XQb(repository.provider)) ?? "auto";
    if (filterState === "all" || filterState === "auto") {
      return filterState;
    }
    const repositoryState = this.m.get(repository);
    return repositoryState?.historyItemsFilter;
  }
  getCurrentHistoryItemTreeElement() {
    const repository = this.repository.get();
    if (!repository) {
      return void 0;
    }
    const state = this.m.get(repository);
    if (!state) {
      return void 0;
    }
    const historyProvider = repository?.provider.historyProvider.get();
    const historyItemRef = historyProvider?.historyItemRef.get();
    return state.viewModels.find((viewModel) => viewModel.historyItemViewModel.historyItem.id === historyItemRef?.revision);
  }
  loadMore(cursor) {
    const repository = this.repository.get();
    if (!repository) {
      return;
    }
    const state = this.m.get(repository);
    if (!state) {
      return;
    }
    this.m.set(repository, { ...state, loadMore: cursor ?? true });
  }
  async getHistoryItems() {
    const repository = this.repository.get();
    const historyProvider = repository?.provider.historyProvider.get();
    if (!repository || !historyProvider) {
      this.s.set(0);
      this.isViewModelEmpty.set(true, void 0);
      return [];
    }
    let state = this.m.get(repository);
    if (!state || state.loadMore !== false) {
      const historyItems = state?.viewModels.map((vm) => vm.historyItemViewModel.historyItem) ?? [];
      const historyItemRefs = state?.historyItemsFilter ?? await this.F(repository, historyProvider);
      const limit = $4i(this.t.getValue("scm.graph.pageSize"), 1, 1e3);
      const historyItemRefIds = historyItemRefs.map((ref) => ref.revision ?? ref.id);
      do {
        historyItems.push(...await historyProvider.provideHistoryItems({
          historyItemRefs: historyItemRefIds,
          limit,
          skip: historyItems.length
        }) ?? []);
      } while (typeof state?.loadMore === "string" && !historyItems.find((item) => item.id === state?.loadMore));
      const colorMap = this.D(historyItemRefs);
      const viewModels = $cRb(historyItems, colorMap, historyProvider.historyItemRef.get()).map((historyItemViewModel) => ({
        repository,
        historyItemViewModel,
        type: "historyItemViewModel"
      }));
      state = { historyItemsFilter: historyItemRefs, viewModels, loadMore: false };
      this.m.set(repository, state);
      this.s.set(viewModels.length);
      this.isViewModelEmpty.set(viewModels.length === 0, void 0);
    }
    return state.viewModels;
  }
  setRepository(repository) {
    this.g.set(repository, void 0);
  }
  setHistoryItemsFilter(filter) {
    const repository = this.repository.get();
    if (!repository) {
      return;
    }
    if (filter !== "auto") {
      this.n.set($XQb(repository.provider), filter);
    } else {
      this.n.delete($XQb(repository.provider));
    }
    this.H();
    this.onDidChangeHistoryItemsFilter.trigger(void 0);
  }
  D(historyItemRefs) {
    const repository = this.repository.get();
    const historyProvider = repository?.provider.historyProvider.get();
    const historyItemRef = historyProvider?.historyItemRef.get();
    const historyItemRemoteRef = historyProvider?.historyItemRemoteRef.get();
    const historyItemBaseRef = historyProvider?.historyItemBaseRef.get();
    const colorMap = /* @__PURE__ */ new Map();
    if (historyItemRef) {
      colorMap.set(historyItemRef.id, historyItemRef.color);
      if (historyItemRemoteRef) {
        colorMap.set(historyItemRemoteRef.id, historyItemRemoteRef.color);
      }
      if (historyItemBaseRef) {
        colorMap.set(historyItemBaseRef.id, historyItemBaseRef.color);
      }
    }
    for (const ref of historyItemRefs) {
      if (!colorMap.has(ref.id)) {
        colorMap.set(ref.id, void 0);
      }
    }
    return colorMap;
  }
  async F(repository, historyProvider) {
    const historyItemRefs = [];
    const historyItemsFilter = this.n.get($XQb(repository.provider)) ?? "auto";
    switch (historyItemsFilter) {
      case "all":
        historyItemRefs.push(...await historyProvider.provideHistoryItemRefs() ?? []);
        break;
      case "auto":
        historyItemRefs.push(...[
          historyProvider.historyItemRef.get(),
          historyProvider.historyItemRemoteRef.get(),
          historyProvider.historyItemBaseRef.get()
        ].filter((ref) => !!ref));
        break;
      default: {
        const refs = (await historyProvider.provideHistoryItemRefs(historyItemsFilter) ?? []).filter((ref) => historyItemsFilter.some((filter) => filter === ref.id));
        if (refs.length === 0) {
          historyItemRefs.push(...[
            historyProvider.historyItemRef.get(),
            historyProvider.historyItemRemoteRef.get(),
            historyProvider.historyItemBaseRef.get()
          ].filter((ref) => !!ref));
          this.n.delete($XQb(repository.provider));
        } else {
          historyItemRefs.push(...refs);
          this.n.set($XQb(repository.provider), refs.map((ref) => ref.id));
        }
        this.H();
        break;
      }
    }
    return historyItemRefs;
  }
  G() {
    try {
      const filterData = this.C.get(
        "scm.graphView.referencesFilter",
        1
        /* StorageScope.WORKSPACE */
      );
      if (filterData) {
        return new Map(JSON.parse(filterData));
      }
    } catch {
    }
    return /* @__PURE__ */ new Map();
  }
  H() {
    const filter = Array.from(this.n.entries());
    this.C.store(
      "scm.graphView.referencesFilter",
      JSON.stringify(filter),
      1,
      0
      /* StorageTarget.USER */
    );
  }
  dispose() {
    this.m.clear();
    super.dispose();
  }
};
SCMHistoryViewModel = __decorate([
  __param(0, $kl),
  __param(1, $on),
  __param(2, $wN),
  __param(3, $dS),
  __param(4, $eS),
  __param(5, $jv)
], SCMHistoryViewModel);
var RepositoryPicker = class RepositoryPicker2 extends $3c {
  constructor(f, g) {
    super();
    this.f = f;
    this.g = g;
    this.c = {
      label: localize(9504, null),
      description: localize(9505, null),
      repository: "auto"
    };
  }
  async pickRepository() {
    const picks = [
      this.c,
      { type: "separator" }
    ];
    picks.push(...this.g.repositories.map((r2) => ({
      label: r2.provider.name,
      description: r2.provider.rootUri?.fsPath,
      iconClass: ThemeIcon.asClassName($6l.repo),
      repository: r2
    })));
    return this.f.pick(picks, {
      placeHolder: localize(9506, null)
    });
  }
};
RepositoryPicker = __decorate([
  __param(0, $1M),
  __param(1, $eS)
], RepositoryPicker);
var HistoryItemRefPicker = class HistoryItemRefPicker2 extends $3c {
  constructor(g, j, m) {
    super();
    this.g = g;
    this.j = j;
    this.m = m;
    this.c = {
      id: "all",
      label: localize(9507, null),
      description: localize(9508, null),
      historyItemRef: "all"
    };
    this.f = {
      id: "auto",
      label: localize(9509, null),
      description: localize(9510, null),
      historyItemRef: "auto"
    };
  }
  async pickHistoryItemRef() {
    const quickPick = this.m.createQuickPick({ useSeparators: true });
    this.q.add(quickPick);
    quickPick.placeholder = localize(9511, null);
    quickPick.canSelectMany = true;
    quickPick.hideCheckAll = true;
    quickPick.busy = true;
    quickPick.show();
    const items = await this.n();
    let selectedItems = [];
    if (this.j === "all") {
      selectedItems.push(this.c);
    } else if (this.j === "auto") {
      selectedItems.push(this.f);
    } else {
      let index = 0;
      while (index < items.length) {
        if (items[index].type === "separator") {
          index++;
          continue;
        }
        if (this.j.some((ref) => ref.id === items[index].id)) {
          const item = items.splice(index, 1);
          selectedItems.push(...item);
        } else {
          index++;
        }
      }
      items.splice(2, 0, { type: "separator" }, ...selectedItems);
    }
    quickPick.items = items;
    quickPick.selectedItems = selectedItems;
    quickPick.busy = false;
    return new Promise((resolve) => {
      this.q.add(quickPick.onDidChangeSelection((items2) => {
        const { added } = $Jb(selectedItems, items2, (a, b) => $Tf(a.id ?? "", b.id ?? ""));
        if (added.length > 0) {
          if (added[0].historyItemRef === "all" || added[0].historyItemRef === "auto") {
            quickPick.selectedItems = [added[0]];
          } else {
            quickPick.selectedItems = [...quickPick.selectedItems.filter((i2) => i2.historyItemRef !== "all" && i2.historyItemRef !== "auto")];
          }
        }
        selectedItems = [...quickPick.selectedItems];
      }));
      this.q.add(quickPick.onDidAccept(() => {
        if (selectedItems.length === 0) {
          resolve(void 0);
        } else if (selectedItems.length === 1 && selectedItems[0].historyItemRef === "all") {
          resolve("all");
        } else if (selectedItems.length === 1 && selectedItems[0].historyItemRef === "auto") {
          resolve("auto");
        } else {
          resolve(selectedItems.map((item) => item.historyItemRef.id));
        }
        quickPick.hide();
      }));
      this.q.add(quickPick.onDidHide(() => {
        resolve(void 0);
        this.dispose();
      }));
    });
  }
  async n() {
    const picks = [
      this.c,
      this.f
    ];
    const historyItemRefs = await this.g.provideHistoryItemRefs() ?? [];
    const historyItemRefsByCategory = $Eb(historyItemRefs, (a, b) => $Tf(a.category ?? "", b.category ?? ""));
    for (const refs of historyItemRefsByCategory) {
      if (refs.length === 0) {
        continue;
      }
      picks.push({ type: "separator", label: refs[0].category });
      picks.push(...refs.map((ref) => {
        return {
          id: ref.id,
          label: ref.name,
          description: ref.description,
          iconClass: ThemeIcon.isThemeIcon(ref.icon) ? ThemeIcon.asClassName(ref.icon) : void 0,
          historyItemRef: ref
        };
      }));
    }
    return picks;
  }
};
HistoryItemRefPicker = __decorate([
  __param(2, $1M)
], HistoryItemRefPicker);
var $Jac = class $Jac2 extends $_ob {
  constructor(options3, ec, fc, gc, hc, configurationService, contextMenuService, keybindingService, instantiationService, viewDescriptorService, contextKeyService, openerService, themeService, telemetryService, hoverService) {
    super({
      ...options3,
      titleMenuId: $bJ.SCMHistoryTitle,
      showActions: ViewPaneShowActions.WhenExpanded
    }, keybindingService, contextMenuService, configurationService, contextKeyService, viewDescriptorService, instantiationService, openerService, themeService, telemetryService, hoverService);
    this.ec = ec;
    this.fc = fc;
    this.gc = gc;
    this.hc = hc;
    this.n = $he(this, false);
    this.s = $he(this, false);
    this.L = new $2c();
    this.ab = new $Qh();
    this.sb = new $Qh();
    this.ac = new $Ph();
    this.bc = $Bac.SCMProvider.bindTo(this.xb);
    this.cc = $Bac.SCMCurrentHistoryItemRefHasRemote.bindTo(this.xb);
    this.dc = $Bac.SCMCurrentHistoryItemRefInFilter.bindTo(this.xb);
    this.t = this.Db.createInstance(SCMHistoryViewPaneActionRunner);
    this.B(this.t);
    this.B(this.ac);
  }
  Ob(container2) {
    super.Ob(container2, this.title);
    const element = h("div.scm-graph-view-badge-container", [
      h("div.scm-graph-view-badge.monaco-count-badge.long@badge")
    ]);
    element.badge.textContent = "Outdated";
    container2.appendChild(element.root);
    this.B(this.Hb.setupManagedHover($JZ("mouse"), element.root, {
      markdown: {
        value: localize(9512, null),
        supportThemeIcons: true
      },
      markdownNotSupportedFallback: void 0
    }));
    this.B($td((reader) => {
      const outdated = this.s.read(reader);
      element.root.style.display = outdated ? "" : "none";
    }));
  }
  W(container2) {
    super.W(container2);
    this.c = $bk(container2, $(".scm-view.scm-history-view"));
    this.c.classList.add("file-icon-themable-tree");
    this.lc(this.c);
    this.onDidChangeBodyVisibility(async (visible) => {
      if (!visible) {
        this.L.clear();
        return;
      }
      this.g = this.Db.createInstance(SCMHistoryViewModel);
      this.L.add(this.g);
      const firstRepositoryInitialized = $2d(this, (reader) => {
        const repository = this.g.repository.read(reader);
        const historyProvider = repository?.provider.historyProvider.read(reader);
        const historyItemRef = historyProvider?.historyItemRef.read(reader);
        return historyItemRef !== void 0 ? true : void 0;
      });
      await $re(firstRepositoryInitialized);
      await this.hc.withProgress({ location: this.id }, async () => {
        await this.ab.queue(async () => {
          await this.f.setInput(this.g);
          this.f.scrollTop = 0;
        });
      });
      this.L.add($td((reader) => {
        this.g.isViewModelEmpty.read(reader);
        this.eb.fire();
      }));
      let isFirstRun = true;
      this.L.add($xd((reader, store) => {
        const repository = this.g.repository.read(reader);
        const historyProvider = repository?.provider.historyProvider.read(reader);
        if (!repository || !historyProvider) {
          return;
        }
        const historyItemRefId = $2d((reader2) => {
          return historyProvider.historyItemRef.read(reader2)?.id;
        });
        store.add($Wd(historyItemRefId, async (historyItemRefIdValue) => {
          await this.refresh();
          this.dc.set(this.mc(historyItemRefIdValue));
        }));
        store.add($Wd(historyProvider.historyItemRefChanges, (changes) => {
          if (changes.silent) {
            if (this.f.scrollTop === 0) {
              this.refresh();
              return;
            }
            this.s.set(true, void 0);
            return;
          }
          this.refresh();
        }));
        store.add($Wd(this.g.onDidChangeHistoryItemsFilter, async () => {
          await this.refresh();
          this.dc.set(this.mc(historyItemRefId.get()));
        }));
        store.add($td((reader2) => {
          this.cc.set(!!historyProvider.historyItemRemoteRef.read(reader2));
        }));
        this.bc.set(repository.provider.contextValue);
        this.dc.set(this.mc(historyItemRefId.get()));
        if (!isFirstRun) {
          this.refresh();
        }
        isFirstRun = false;
      }));
    });
  }
  X(height, width2) {
    super.X(height, width2);
    this.f.layout(height, width2);
  }
  getActionRunner() {
    return this.t;
  }
  getActionsContext() {
    return this.g?.repository.get()?.provider;
  }
  getActionViewItem(action, options3) {
    if (action.id === PICK_REPOSITORY_ACTION_ID) {
      const repository = this.g?.repository.get();
      if (repository) {
        return new SCMRepositoryActionViewItem(repository, action, options3);
      }
    } else if (action.id === PICK_HISTORY_ITEM_REFS_ACTION_ID) {
      const repository = this.g?.repository.get();
      const historyItemsFilter = this.g?.getHistoryItemsFilter();
      if (repository && historyItemsFilter) {
        return new SCMHistoryItemRefsActionViewItem(repository, historyItemsFilter, action, options3);
      }
    }
    return super.getActionViewItem(action, options3);
  }
  focus() {
    super.focus();
    const fakeKeyboardEvent = new KeyboardEvent("keydown");
    this.f.focusFirst(fakeKeyboardEvent);
    this.f.domFocus();
  }
  shouldShowWelcome() {
    return this.g?.isViewModelEmpty.get() === true;
  }
  async refresh() {
    this.g.clearRepositoryState();
    await this.qc();
    this.$b();
    this.s.set(false, void 0);
    this.f.scrollTop = 0;
  }
  async pickRepository() {
    const picker = this.fc.createInstance(RepositoryPicker);
    const result = await picker.pickRepository();
    if (result) {
      this.g.setRepository(result.repository);
    }
  }
  async pickHistoryItemRef() {
    const repository = this.g.repository.get();
    const historyProvider = repository?.provider.historyProvider.get();
    const historyItemsFilter = this.g.getHistoryItemsFilter();
    if (!historyProvider || !historyItemsFilter) {
      return;
    }
    const picker = this.fc.createInstance(HistoryItemRefPicker, historyProvider, historyItemsFilter);
    const result = await picker.pickHistoryItemRef();
    if (result) {
      this.g.setHistoryItemsFilter(result);
    }
  }
  async revealCurrentHistoryItem() {
    const repository = this.g.repository.get();
    const historyProvider = repository?.provider.historyProvider.get();
    const historyItemRef = historyProvider?.historyItemRef.get();
    if (!repository || !historyItemRef?.id || !historyItemRef?.revision) {
      return;
    }
    if (!this.mc(historyItemRef.id)) {
      return;
    }
    const revealTreeNode = () => {
      const historyItemTreeElement = this.g.getCurrentHistoryItemTreeElement();
      if (historyItemTreeElement && this.f.hasNode(historyItemTreeElement)) {
        this.f.reveal(historyItemTreeElement, 0.5);
        this.f.setSelection([historyItemTreeElement]);
        this.f.setFocus([historyItemTreeElement]);
        return true;
      }
      return false;
    };
    if (revealTreeNode()) {
      return;
    }
    await this.pc(historyItemRef.revision);
    revealTreeNode();
  }
  lc(container2) {
    this.m = new SCMHistoryTreeIdentityProvider();
    const historyItemHoverDelegate = this.Db.createInstance(HistoryItemHoverDelegate, this.Cb.getViewLocationById(this.id));
    this.B(historyItemHoverDelegate);
    this.j = this.Db.createInstance(SCMHistoryTreeDataSource);
    this.B(this.j);
    this.f = this.Db.createInstance($4eb, "SCM History Tree", container2, new ListDelegate4(), [
      this.Db.createInstance(HistoryItemRenderer, historyItemHoverDelegate),
      this.Db.createInstance(HistoryItemLoadMoreRenderer, this.n, () => this.pc())
    ], this.j, {
      accessibilityProvider: new SCMHistoryTreeAccessibilityProvider(),
      identityProvider: this.m,
      collapseByDefault: (e) => false,
      keyboardNavigationLabelProvider: new SCMHistoryTreeKeyboardNavigationLabelProvider(),
      horizontalScrolling: false,
      multipleSelectionSupport: false
    });
    this.B(this.f);
    this.f.onDidOpen(this.nc, this, this.q);
    this.f.onContextMenu(this.oc, this, this.q);
  }
  mc(historyItemRefId) {
    if (!historyItemRefId) {
      return false;
    }
    const historyItemFilter = this.g.getHistoryItemsFilter();
    if (historyItemFilter === "all" || historyItemFilter === "auto") {
      return true;
    }
    return Array.isArray(historyItemFilter) && !!historyItemFilter.find((ref) => ref.id === historyItemRefId);
  }
  async nc(e) {
    if (!e.element) {
      return;
    } else if ($RQb(e.element)) {
      const historyItem = e.element.historyItemViewModel.historyItem;
      const historyItemParentId = historyItem.parentIds.length > 0 ? historyItem.parentIds[0] : void 0;
      const historyProvider = e.element.repository.provider.historyProvider.get();
      const historyItemChanges = await historyProvider?.provideHistoryItemChanges(historyItem.id, historyItemParentId);
      if (historyItemChanges) {
        const title = $ZQb(historyItem);
        const rootUri = e.element.repository.provider.rootUri;
        const path = rootUri ? rootUri.path : e.element.repository.provider.label;
        const multiDiffSourceUri = URI.from({ scheme: "scm-history-item", path: `${path}/${historyItemParentId}..${historyItem.id}` }, true);
        await this.ec.executeCommand("_workbench.openMultiDiffEditor", { title, multiDiffSourceUri, resources: historyItemChanges });
      }
    } else if ($SQb(e.element)) {
      const pageOnScroll = this.Ab.getValue("scm.graph.pageOnScroll") === true;
      if (!pageOnScroll) {
        this.pc();
        this.f.setSelection([]);
      }
    }
  }
  oc(e) {
    const element = e.element;
    if (!element || !$RQb(element)) {
      return;
    }
    const historyItemMenuActions = this.gc.getMenuActions($bJ.SCMChangesContext, this.xb, {
      arg: element.repository.provider,
      shouldForwardArgs: true
    });
    const actions = $P$(historyItemMenuActions);
    if (element.historyItemViewModel.historyItem.references?.length) {
      actions.push(new $Wm());
    }
    const that = this;
    for (const ref of element.historyItemViewModel.historyItem.references ?? []) {
      const contextKeyService = this.xb.createOverlay([
        ["scmHistoryItemRef", ref.id]
      ]);
      const historyItemRefMenuActions = this.gc.getMenuActions($bJ.SCMHistoryItemRefContext, contextKeyService);
      const historyItemRefSubMenuActions = $P$(historyItemRefMenuActions).map((action) => new class extends $fJ {
        constructor() {
          super({ id: action.id, title: action.label }, void 0, { arg: element.repository.provider, shouldForwardArgs: true }, void 0, void 0, contextKeyService, that.ec);
        }
        run() {
          return super.run(element.historyItemViewModel.historyItem, ref.id);
        }
      }());
      if (historyItemRefSubMenuActions.length > 0) {
        actions.push(new $Xm(`scm.historyItemRef.${ref.id}`, ref.name, historyItemRefSubMenuActions));
      }
    }
    this.zb.showContextMenu({
      contextKeyService: this.xb,
      getAnchor: () => e.anchor,
      getActions: () => actions,
      getActionsContext: () => element.historyItemViewModel.historyItem
    });
  }
  async pc(cursor) {
    return this.sb.queue(async () => {
      if (this.n.get()) {
        return;
      }
      this.n.set(true, void 0);
      this.g.loadMore(cursor);
      await this.qc();
      this.n.set(false, void 0);
    });
  }
  qc() {
    return this.ac.queue(() => this.ab.queue(async () => {
      await this.hc.withProgress({ location: this.id }, async () => {
        await this.f.updateChildren(void 0, void 0, void 0, {
          // diffIdentityProvider: this._treeIdentityProvider
        });
      });
    }));
  }
  dispose() {
    this.L.dispose();
    super.dispose();
  }
};
$Jac = __decorate([
  __param(1, $sn),
  __param(2, $Pk),
  __param(3, $cJ),
  __param(4, $TJ),
  __param(5, $kl),
  __param(6, $50),
  __param(7, $Ty),
  __param(8, $Pk),
  __param(9, $$M),
  __param(10, $on),
  __param(11, $O4),
  __param(12, $gs),
  __param(13, $zv),
  __param(14, $5$)
], $Jac);

// out-build/vs/workbench/contrib/scm/browser/scm.contribution.js
$JF.registerLanguage({
  id: "scminput",
  extensions: [],
  aliases: [],
  // hide from language selector
  mimetypes: ["text/x-scm-input"]
});
$Wn.as(Extensions2.Workbench).registerWorkbenchContribution(
  $REb,
  3
  /* LifecyclePhase.Restored */
);
var sourceControlViewIcon = $9r("source-control-view-icon", $6l.sourceControl, localize(9397, null));
var viewContainer3 = $Wn.as(Extensions5.ViewContainersRegistry).registerViewContainer({
  id: $_R,
  title: localize2(9468, "Source Control"),
  ctorDescriptor: new $Nk($mac),
  storageId: "workbench.scm.views.state",
  icon: sourceControlViewIcon,
  alwaysUseContainerInfo: true,
  order: 2,
  hideIfEmpty: true
}, 0, { doNotRegisterOpenCommand: true });
var viewsRegistry4 = $Wn.as(Extensions5.ViewsRegistry);
viewsRegistry4.registerViewWelcomeContent($aS, {
  content: localize(9398, null),
  when: "default"
});
viewsRegistry4.registerViewWelcomeContent($aS, {
  content: localize(9399, null),
  when: $7m.and($7m.equals("scm.providerCount", 0), $Fac.IsEnabled, $Fac.IsTrusted.toNegated())
});
viewsRegistry4.registerViewWelcomeContent($aS, {
  content: `[${localize(9400, null)}](command:${$Gac})`,
  when: $7m.and($7m.equals("scm.providerCount", 0), $Fac.IsEnabled, $Fac.IsTrusted.toNegated())
});
viewsRegistry4.registerViewWelcomeContent($cS, {
  content: localize(9401, null),
  when: $Bac.SCMHistoryItemCount.isEqualTo(0)
});
viewsRegistry4.registerViews([{
  id: $bS,
  name: localize2(9469, "Source Control Repositories"),
  ctorDescriptor: new $Nk($Eac),
  canToggleVisibility: true,
  hideByDefault: true,
  canMoveView: true,
  weight: 20,
  order: 0,
  when: $7m.and($7m.has("scm.providerCount"), $7m.notEquals("scm.providerCount", 0)),
  // readonly when = ContextKeyExpr.or(ContextKeyExpr.equals('config.scm.alwaysShowProviders', true), ContextKeyExpr.and(ContextKeyExpr.notEquals('scm.providerCount', 0), ContextKeyExpr.notEquals('scm.providerCount', 1)));
  containerIcon: sourceControlViewIcon
}], viewContainer3);
viewsRegistry4.registerViews([{
  id: $aS,
  name: localize2(9470, "Source Control"),
  ctorDescriptor: new $Nk($Cac),
  canToggleVisibility: true,
  canMoveView: true,
  weight: 40,
  order: 1,
  containerIcon: sourceControlViewIcon,
  openCommandActionDescriptor: {
    id: viewContainer3.id,
    mnemonicTitle: localize(9402, null),
    keybindings: {
      primary: 0,
      win: {
        primary: 2048 | 1024 | 37
        /* KeyCode.KeyG */
      },
      linux: {
        primary: 2048 | 1024 | 37
        /* KeyCode.KeyG */
      },
      mac: {
        primary: 256 | 1024 | 37
        /* KeyCode.KeyG */
      }
    },
    order: 2
  }
}], viewContainer3);
viewsRegistry4.registerViews([{
  id: $cS,
  name: localize2(9471, "Source Control Graph"),
  ctorDescriptor: new $Nk($Jac),
  canToggleVisibility: true,
  canMoveView: true,
  weight: 40,
  order: 2,
  when: $7m.and(
    // Repository Count
    $7m.and($7m.has("scm.providerCount"), $7m.notEquals("scm.providerCount", 0)),
    // Not Serverless
    $7m.and($veb, $kpb.isEqualTo(""))?.negate()
  ),
  containerIcon: sourceControlViewIcon
}], viewContainer3);
$Wn.as(Extensions2.Workbench).registerWorkbenchContribution(
  $jac,
  3
  /* LifecyclePhase.Restored */
);
$Wn.as(Extensions2.Workbench).registerWorkbenchContribution(
  $kac,
  3
  /* LifecyclePhase.Restored */
);
$PL(
  $Iac.ID,
  $Iac,
  3
  /* WorkbenchPhase.AfterRestored */
);
$Wn.as($Ht.Configuration).registerConfiguration({
  id: "scm",
  order: 5,
  title: localize(9403, null),
  type: "object",
  scope: 4,
  properties: {
    "scm.diffDecorations": {
      type: "string",
      enum: ["all", "gutter", "overview", "minimap", "none"],
      enumDescriptions: [
        localize(9404, null),
        localize(9405, null),
        localize(9406, null),
        localize(9407, null),
        localize(9408, null)
      ],
      default: "all",
      description: localize(9409, null)
    },
    "scm.diffDecorationsGutterWidth": {
      type: "number",
      enum: [1, 2, 3, 4, 5],
      default: 3,
      description: localize(9410, null)
    },
    "scm.diffDecorationsGutterVisibility": {
      type: "string",
      enum: ["always", "hover"],
      enumDescriptions: [
        localize(9411, null),
        localize(9412, null)
      ],
      description: localize(9413, null),
      default: "always"
    },
    "scm.diffDecorationsGutterAction": {
      type: "string",
      enum: ["diff", "none"],
      enumDescriptions: [
        localize(9414, null),
        localize(9415, null)
      ],
      description: localize(9416, null),
      default: "diff"
    },
    "scm.diffDecorationsGutterPattern": {
      type: "object",
      description: localize(9417, null),
      additionalProperties: false,
      properties: {
        "added": {
          type: "boolean",
          description: localize(9418, null)
        },
        "modified": {
          type: "boolean",
          description: localize(9419, null)
        }
      },
      default: {
        "added": false,
        "modified": true
      }
    },
    "scm.diffDecorationsIgnoreTrimWhitespace": {
      type: "string",
      enum: ["true", "false", "inherit"],
      enumDescriptions: [
        localize(9420, null),
        localize(9421, null),
        localize(9422, null)
      ],
      description: localize(9423, null),
      default: "false"
    },
    "scm.alwaysShowActions": {
      type: "boolean",
      description: localize(9424, null),
      default: false
    },
    "scm.countBadge": {
      type: "string",
      enum: ["all", "focused", "off"],
      enumDescriptions: [
        localize(9425, null),
        localize(9426, null),
        localize(9427, null)
      ],
      description: localize(9428, null),
      default: "all"
    },
    "scm.providerCountBadge": {
      type: "string",
      enum: ["hidden", "auto", "visible"],
      enumDescriptions: [
        localize(9429, null),
        localize(9430, null),
        localize(9431, null)
      ],
      markdownDescription: localize(9432, null, "`#scm.alwaysShowRepositories#`"),
      default: "hidden"
    },
    "scm.defaultViewMode": {
      type: "string",
      enum: ["tree", "list"],
      enumDescriptions: [
        localize(9433, null),
        localize(9434, null)
      ],
      description: localize(9435, null),
      default: "list"
    },
    "scm.defaultViewSortKey": {
      type: "string",
      enum: ["name", "path", "status"],
      enumDescriptions: [
        localize(9436, null),
        localize(9437, null),
        localize(9438, null)
      ],
      description: localize(9439, null),
      default: "path"
    },
    "scm.autoReveal": {
      type: "boolean",
      description: localize(9440, null),
      default: true
    },
    "scm.inputFontFamily": {
      type: "string",
      markdownDescription: localize(9441, null),
      default: "default"
    },
    "scm.inputFontSize": {
      type: "number",
      markdownDescription: localize(9442, null),
      default: 13
    },
    "scm.inputMaxLineCount": {
      type: "number",
      markdownDescription: localize(9443, null),
      minimum: 1,
      maximum: 50,
      default: 10
    },
    "scm.inputMinLineCount": {
      type: "number",
      markdownDescription: localize(9444, null),
      minimum: 1,
      maximum: 50,
      default: 1
    },
    "scm.alwaysShowRepositories": {
      type: "boolean",
      markdownDescription: localize(9445, null),
      default: false
    },
    "scm.repositories.sortOrder": {
      type: "string",
      enum: ["discovery time", "name", "path"],
      enumDescriptions: [
        localize(9446, null),
        localize(9447, null),
        localize(9448, null)
      ],
      description: localize(9449, null),
      default: "discovery time"
    },
    "scm.repositories.visible": {
      type: "number",
      description: localize(9450, null),
      default: 10
    },
    "scm.showActionButton": {
      type: "boolean",
      markdownDescription: localize(9451, null),
      default: true
    },
    "scm.showInputActionButton": {
      type: "boolean",
      markdownDescription: localize(9452, null),
      default: true
    },
    "scm.workingSets.enabled": {
      type: "boolean",
      description: localize(9453, null),
      default: false
    },
    "scm.workingSets.default": {
      type: "string",
      enum: ["empty", "current"],
      enumDescriptions: [
        localize(9454, null),
        localize(9455, null)
      ],
      description: localize(9456, null),
      default: "current"
    },
    "scm.compactFolders": {
      type: "boolean",
      description: localize(9457, null),
      default: true
    },
    "scm.graph.pageOnScroll": {
      type: "boolean",
      description: localize(9458, null),
      default: true
    },
    "scm.graph.pageSize": {
      type: "number",
      description: localize(9459, null),
      minimum: 1,
      maximum: 1e3,
      default: 50
    },
    "scm.graph.badges": {
      type: "string",
      enum: ["all", "filter"],
      enumDescriptions: [
        localize(9460, null),
        localize(9461, null)
      ],
      description: localize(9462, null),
      default: "filter"
    }
  }
});
$0I.registerCommandAndKeybindingRule({
  id: "scm.acceptInput",
  metadata: { description: localize(9463, null), args: [] },
  weight: 200,
  when: $7m.has("scmRepository"),
  primary: 2048 | 3,
  handler: (accessor) => {
    const contextKeyService = accessor.get($on);
    const context = contextKeyService.getContext($Lj());
    const repositoryId = context.getValue("scmRepository");
    if (!repositoryId) {
      return Promise.resolve(null);
    }
    const scmService = accessor.get($dS);
    const repository = scmService.getRepository(repositoryId);
    if (!repository?.provider.acceptInputCommand) {
      return Promise.resolve(null);
    }
    const id2 = repository.provider.acceptInputCommand.id;
    const args2 = repository.provider.acceptInputCommand.arguments;
    const commandService = accessor.get($sn);
    return commandService.executeCommand(id2, ...args2 || []);
  }
});
$0I.registerCommandAndKeybindingRule({
  id: "scm.clearInput",
  weight: 200,
  when: $7m.and($7m.has("scmRepository"), $_bb.Visible.toNegated()),
  primary: 9,
  handler: async (accessor) => {
    const scmService = accessor.get($dS);
    const contextKeyService = accessor.get($on);
    const context = contextKeyService.getContext($Lj());
    const repositoryId = context.getValue("scmRepository");
    const repository = repositoryId ? scmService.getRepository(repositoryId) : void 0;
    repository?.input.setValue("", true);
  }
});
var viewNextCommitCommand = {
  description: { description: localize(9464, null), args: [] },
  weight: 200,
  handler: (accessor) => {
    const contextKeyService = accessor.get($on);
    const scmService = accessor.get($dS);
    const context = contextKeyService.getContext($Lj());
    const repositoryId = context.getValue("scmRepository");
    const repository = repositoryId ? scmService.getRepository(repositoryId) : void 0;
    repository?.input.showNextHistoryValue();
  }
};
var viewPreviousCommitCommand = {
  description: { description: localize(9465, null), args: [] },
  weight: 200,
  handler: (accessor) => {
    const contextKeyService = accessor.get($on);
    const scmService = accessor.get($dS);
    const context = contextKeyService.getContext($Lj());
    const repositoryId = context.getValue("scmRepository");
    const repository = repositoryId ? scmService.getRepository(repositoryId) : void 0;
    repository?.input.showPreviousHistoryValue();
  }
};
$0I.registerCommandAndKeybindingRule({
  ...viewNextCommitCommand,
  id: "scm.viewNextCommit",
  when: $7m.and($7m.has("scmRepository"), $7m.has("scmInputIsInLastPosition"), $_bb.Visible.toNegated()),
  primary: 18
  /* KeyCode.DownArrow */
});
$0I.registerCommandAndKeybindingRule({
  ...viewPreviousCommitCommand,
  id: "scm.viewPreviousCommit",
  when: $7m.and($7m.has("scmRepository"), $7m.has("scmInputIsInFirstPosition"), $_bb.Visible.toNegated()),
  primary: 16
  /* KeyCode.UpArrow */
});
$0I.registerCommandAndKeybindingRule({
  ...viewNextCommitCommand,
  id: "scm.forceViewNextCommit",
  when: $7m.has("scmRepository"),
  primary: 512 | 18
  /* KeyCode.DownArrow */
});
$0I.registerCommandAndKeybindingRule({
  ...viewPreviousCommitCommand,
  id: "scm.forceViewPreviousCommit",
  when: $7m.has("scmRepository"),
  primary: 512 | 16
  /* KeyCode.UpArrow */
});
$tn.registerCommand("scm.openInIntegratedTerminal", async (accessor, ...providers2) => {
  if (!providers2 || providers2.length === 0) {
    return;
  }
  const commandService = accessor.get($sn);
  const listService = accessor.get($Deb);
  let provider = providers2.length === 1 ? providers2[0] : void 0;
  if (!provider) {
    const list2 = listService.lastFocusedList;
    const element = list2?.getHTMLElement();
    if (list2 instanceof $Web && element && $Mj(element)) {
      const [index] = list2.getFocus();
      const focusedElement = list2.element(index);
      if ($LQb(focusedElement)) {
        provider = focusedElement.provider;
      }
    }
  }
  if (!provider?.rootUri) {
    return;
  }
  await commandService.executeCommand("openInIntegratedTerminal", provider.rootUri);
});
$tn.registerCommand("scm.openInTerminal", async (accessor, provider) => {
  if (!provider || !provider.rootUri) {
    return;
  }
  const commandService = accessor.get($sn);
  await commandService.executeCommand("openInTerminal", provider.rootUri);
});
$dJ.appendMenuItem($bJ.SCMSourceControl, {
  group: "100_end",
  command: {
    id: "scm.openInTerminal",
    title: localize(9466, null)
  },
  when: $7m.and($7m.equals("scmProviderHasRootUri", true), $7m.or($7m.equals("config.terminal.sourceControlRepositoriesKind", "external"), $7m.equals("config.terminal.sourceControlRepositoriesKind", "both")))
});
$dJ.appendMenuItem($bJ.SCMSourceControl, {
  group: "100_end",
  command: {
    id: "scm.openInIntegratedTerminal",
    title: localize(9467, null)
  },
  when: $7m.and($7m.equals("scmProviderHasRootUri", true), $7m.or($7m.equals("config.terminal.sourceControlRepositoriesKind", "integrated"), $7m.equals("config.terminal.sourceControlRepositoriesKind", "both")))
});
$0I.registerCommandAndKeybindingRule({
  id: "workbench.scm.action.focusPreviousInput",
  weight: 200,
  when: $Bac.RepositoryVisibilityCount.notEqualsTo(0),
  handler: async (accessor) => {
    const viewsService = accessor.get($uob);
    const scmView = await viewsService.openView($aS);
    if (scmView) {
      scmView.focusPreviousInput();
    }
  }
});
$0I.registerCommandAndKeybindingRule({
  id: "workbench.scm.action.focusNextInput",
  weight: 200,
  when: $Bac.RepositoryVisibilityCount.notEqualsTo(0),
  handler: async (accessor) => {
    const viewsService = accessor.get($uob);
    const scmView = await viewsService.openView($aS);
    if (scmView) {
      scmView.focusNextInput();
    }
  }
});
$0I.registerCommandAndKeybindingRule({
  id: "workbench.scm.action.focusPreviousResourceGroup",
  weight: 200,
  handler: async (accessor) => {
    const viewsService = accessor.get($uob);
    const scmView = await viewsService.openView($aS);
    if (scmView) {
      scmView.focusPreviousResourceGroup();
    }
  }
});
$0I.registerCommandAndKeybindingRule({
  id: "workbench.scm.action.focusNextResourceGroup",
  weight: 200,
  handler: async (accessor) => {
    const viewsService = accessor.get($uob);
    const scmView = await viewsService.openView($aS);
    if (scmView) {
      scmView.focusNextResourceGroup();
    }
  }
});
$SC(
  $dS,
  $lac,
  1
  /* InstantiationType.Delayed */
);
$SC(
  $eS,
  $tac,
  1
  /* InstantiationType.Delayed */
);
$SC(
  $AEb,
  $Hac,
  1
  /* InstantiationType.Delayed */
);

// out-build/vs/workbench/contrib/debug/browser/debugToolBar.js
var DEBUG_TOOLBAR_POSITION_KEY = "debug.actionswidgetposition";
var DEBUG_TOOLBAR_Y_KEY = "debug.actionswidgety";
var $Kac = class $Kac2 extends $ns {
  constructor(D, F, G, H, I, J, themeService, L, menuService, contextKeyService) {
    super(themeService);
    this.D = D;
    this.F = F;
    this.G = G;
    this.H = H;
    this.I = I;
    this.J = J;
    this.L = L;
    this.m = false;
    this.r = false;
    this.t = this.B(new $2c());
    this.u = /* @__PURE__ */ new WeakMap();
    this.C = this.B(new $4c());
    this.a = $("div.debug-toolbar");
    const customTitleBar = this.J.getValue(
      "window.titleBarStyle"
      /* TitleBarSetting.TITLE_BAR_STYLE */
    ) === "custom";
    const controlsOnLeft = customTitleBar && $x === 1;
    const controlsOnRight = customTitleBar && ($x === 3 || $x === 2);
    this.a.style.transform = `translate(
			min(
				max(${controlsOnLeft ? "60px" : "0px"}, calc(-50% + (100vw * var(--x-position)))),
				calc(100vw - 100% - ${controlsOnRight ? "100px" : "0px"})
			),
			var(--y-position)
		)`;
    this.b = $bk(this.a, $("div.drag-area" + ThemeIcon.asCSSSelector($MFb)));
    const actionBarContainer = $bk(this.a, $("div.action-bar-container"));
    this.j = menuService.createMenu($bJ.DebugToolBar, contextKeyService);
    this.B(this.j);
    this.f = [];
    this.c = this.B(new $LZ(actionBarContainer, {
      orientation: 0,
      actionViewItemProvider: (action, options3) => {
        if (action.id === $R4b) {
          return this.L.createInstance($d9b, action, void 0);
        } else if (action.id === $M4b || action.id === $K4b) {
          this.t.clear();
          const item = this.L.invokeFunction((accessor) => $Lac(action, this.t, accessor, { hoverDelegate: options3.hoverDelegate }));
          if (item) {
            return item;
          }
        }
        return $X$(this.L, action, options3);
      }
    }));
    this.g = this.B(new $8h(() => {
      const state = this.G.state;
      const toolBarLocation = this.J.getValue("debug").toolBarLocation;
      if (state === 0 || toolBarLocation !== "floating" || this.G.getModel().getSessions().every((s) => s.suppressDebugToolbar) || state === 1 && this.G.initializingOptions?.suppressDebugToolbar) {
        return this.ab();
      }
      const actions = $R$(this.j.getActions({ shouldForwardArgs: true }));
      if (!$zb(actions, this.f, (first, second) => first.id === second.id && first.enabled === second.enabled)) {
        this.c.clear();
        this.c.push(actions, { icon: true, label: false });
        this.f = actions;
      }
      this.Y();
    }, 20));
    this.updateStyles();
    this.M();
    this.ab();
  }
  M() {
    this.B(this.G.onDidChangeState(() => this.g.schedule()));
    this.B(this.J.onDidChangeConfiguration((e) => {
      if (e.affectsConfiguration("debug.toolBarLocation")) {
        this.g.schedule();
      }
      if (e.affectsConfiguration(
        "workbench.editor.showTabs"
        /* LayoutSettings.EDITOR_TABS_MODE */
      ) || e.affectsConfiguration(
        "window.commandCenter"
        /* LayoutSettings.COMMAND_CENTER */
      )) {
        this.W = void 0;
        this.S();
      }
    }));
    this.B(this.j.onDidChange(() => this.g.schedule()));
    this.B(this.c.actionRunner.onDidRun((e) => {
      if (e.error && !$kb(e.error)) {
        this.D.warn(e.error);
      }
      this.F.publicLog2("workbenchActionExecuted", { id: e.action.id, from: "debugActionsWidget" });
    }));
    this.B($fj(this.b, (event) => {
      const mouseClickEvent = new $lf(getWindow(this.b), event);
      if (mouseClickEvent.detail === 2) {
        this.S(0.5, this.U);
        this.P();
      }
    }));
    this.B($dj(this.b, (e) => {
      this.b.classList.add("dragged");
      const activeWindow = getWindow(this.H.activeContainer);
      const originEvent = new $lf(activeWindow, e);
      const originX = this.N();
      const originY = this.O();
      const mouseMoveListener = $ej(activeWindow, (e2) => {
        const mouseMoveEvent = new $lf(activeWindow, e2);
        mouseMoveEvent.preventDefault();
        this.S(originX + (mouseMoveEvent.posx - originEvent.posx) / activeWindow.innerWidth, originY + mouseMoveEvent.posy - originEvent.posy);
      });
      const mouseUpListener = $fj(activeWindow, (e2) => {
        this.P();
        this.b.classList.remove("dragged");
        mouseMoveListener.dispose();
        mouseUpListener.dispose();
      });
    }));
    this.B(this.H.onDidChangePartVisibility(() => this.S()));
    this.B(this.H.onDidChangeActiveContainer(async () => {
      this.W = void 0;
      await this.H.whenContainerStylesLoaded(getWindow(this.H.activeContainer));
      if (this.r) {
        this.Z();
        this.S();
      }
    }));
  }
  N() {
    return Number(this.a.style.getPropertyValue("--x-position"));
  }
  O() {
    return parseInt(this.a.style.getPropertyValue("--y-position"));
  }
  P() {
    const activeWindow = getWindow(this.H.activeContainer);
    const isMainWindow = this.H.activeContainer === this.H.mainContainer;
    const x = this.N();
    const y = this.O();
    if (isMainWindow) {
      this.I.store(
        DEBUG_TOOLBAR_POSITION_KEY,
        x,
        0,
        1
        /* StorageTarget.MACHINE */
      );
      this.I.store(
        DEBUG_TOOLBAR_Y_KEY,
        y,
        0,
        1
        /* StorageTarget.MACHINE */
      );
    } else {
      this.u.set(activeWindow, { x, y });
    }
  }
  updateStyles() {
    super.updateStyles();
    if (this.a) {
      this.a.style.backgroundColor = this.z($eGb) || "";
      const widgetShadowColor = this.z($Rp);
      this.a.style.boxShadow = widgetShadowColor ? `0 0 8px 2px ${widgetShadowColor}` : "";
      const contrastBorderColor = this.z($Sp);
      const borderColor = this.z($fGb);
      if (contrastBorderColor) {
        this.a.style.border = `1px solid ${contrastBorderColor}`;
      } else {
        this.a.style.border = borderColor ? `solid ${borderColor}` : "none";
        this.a.style.border = "1px 0";
      }
    }
  }
  /** Gets the stored X position of the middle of the toolbar based on the current window width */
  Q() {
    const currentWindow = getWindow(this.H.activeContainer);
    const isMainWindow = currentWindow === $Y;
    const storedPercentage = isMainWindow ? Number(this.I.get(
      DEBUG_TOOLBAR_POSITION_KEY,
      0
      /* StorageScope.PROFILE */
    )) : this.u.get(currentWindow)?.x;
    return storedPercentage !== void 0 && !isNaN(storedPercentage) ? storedPercentage : 0.5;
  }
  R() {
    const currentWindow = getWindow(this.H.activeContainer);
    const isMainWindow = currentWindow === $Y;
    const storedY = isMainWindow ? this.I.getNumber(
      DEBUG_TOOLBAR_Y_KEY,
      0
      /* StorageScope.PROFILE */
    ) : this.u.get(currentWindow)?.y;
    return storedY ?? this.U;
  }
  S(x, y) {
    if (!this.m) {
      return;
    }
    x ??= this.Q();
    y ??= this.R();
    const [yMin, yMax] = this.X;
    y = Math.max(yMin, Math.min(y, yMax));
    this.a.style.setProperty("--x-position", `${x}`);
    this.a.style.setProperty("--y-position", `${y}px`);
  }
  get U() {
    return this.H.mainContainerOffset.top;
  }
  get X() {
    if (!this.W) {
      const isTitleBarVisible = this.H.isVisible("workbench.parts.titlebar", getWindow(this.H.activeContainer));
      const yMin = isTitleBarVisible ? 0 : this.H.mainContainerOffset.top;
      let yMax = 0;
      if (isTitleBarVisible) {
        if (this.J.getValue(
          "window.commandCenter"
          /* LayoutSettings.COMMAND_CENTER */
        ) === true) {
          yMax += 35;
        } else {
          yMax += 28;
        }
      }
      if (this.J.getValue(
        "workbench.editor.showTabs"
        /* LayoutSettings.EDITOR_TABS_MODE */
      ) !== "none") {
        yMax += 35;
      }
      this.W = [yMin, yMax];
    }
    return this.W;
  }
  Y() {
    if (this.m) {
      this.S();
      return;
    }
    if (!this.r) {
      this.r = true;
      this.Z();
    }
    this.m = true;
    $hk(this.a);
    this.S();
  }
  Z() {
    this.H.activeContainer.appendChild(this.a);
    this.C.value = $_1.getInstance(getWindow(this.a)).onDidChange(() => this.S());
  }
  ab() {
    this.m = false;
    $ik(this.a);
  }
  dispose() {
    super.dispose();
    this.a?.remove();
  }
};
$Kac = __decorate([
  __param(0, $PJ),
  __param(1, $zv),
  __param(2, $0R),
  __param(3, $Vlb),
  __param(4, $jv),
  __param(5, $kl),
  __param(6, $gs),
  __param(7, $Pk),
  __param(8, $cJ),
  __param(9, $on)
], $Kac);
function $Lac(action, disposables, accessor, options3) {
  const menuService = accessor.get($cJ);
  const contextKeyService = accessor.get($on);
  const instantiationService = accessor.get($Pk);
  const menu = menuService.getMenuActions($bJ.DebugToolBarStop, contextKeyService, { shouldForwardArgs: true });
  const secondary = $R$(menu);
  if (!secondary.length) {
    return void 0;
  }
  const dropdownAction = disposables.add(new $Um("notebook.moreRunActions", localize(5990, null), "codicon-chevron-down", true));
  const item = instantiationService.createInstance($isb, action, dropdownAction, secondary, "debug-stop-actions", options3);
  return item;
}
var debugViewTitleItems = [];
var registerDebugToolBarItem = (id2, title, order, icon2, when, precondition2, alt) => {
  $dJ.appendMenuItem($bJ.DebugToolBar, {
    group: "navigation",
    when,
    order,
    command: {
      id: id2,
      title,
      icon: icon2,
      precondition: precondition2
    },
    alt
  });
  debugViewTitleItems.push($dJ.appendMenuItem($bJ.ViewContainerTitle, {
    group: "navigation",
    when: $7m.and(when, $7m.equals("viewContainer", $TQ), $5Q.notEqualsTo("inactive"), $7m.equals("config.debug.toolBarLocation", "docked")),
    order,
    command: {
      id: id2,
      title,
      icon: icon2,
      precondition: precondition2
    }
  }));
};
$Vc($dJ.onDidChangeMenu((e) => {
  if (e.has($bJ.DebugToolBar)) {
    $Xc(debugViewTitleItems);
    const items = $dJ.getMenuItems($bJ.DebugToolBar);
    for (const i2 of items) {
      debugViewTitleItems.push($dJ.appendMenuItem($bJ.ViewContainerTitle, {
        ...i2,
        when: $7m.and(i2.when, $7m.equals("viewContainer", $TQ), $5Q.notEqualsTo("inactive"), $7m.equals("config.debug.toolBarLocation", "docked"))
      }));
    }
  }
}));
var CONTEXT_TOOLBAR_COMMAND_CENTER = $7m.equals("config.debug.toolBarLocation", "commandCenter");
$dJ.appendMenuItem($bJ.CommandCenterCenter, {
  submenu: $bJ.DebugToolBar,
  title: "Debug",
  icon: $6l.debug,
  order: 1,
  when: $7m.and($9Q, CONTEXT_TOOLBAR_COMMAND_CENTER)
});
registerDebugToolBarItem($O4b, $j5b, 10, $WFb, $5Q.isEqualTo("stopped"));
registerDebugToolBarItem($J4b, $f5b, 10, $VFb, $5Q.notEqualsTo("stopped"), $7m.and($5Q.isEqualTo("running"), $uR.toNegated()));
registerDebugToolBarItem($M4b, $i5b, 70, $OFb, $tR.toNegated(), void 0, { id: $K4b, title: $g5b, icon: $PFb, precondition: $7m.and($tR.toNegated(), $KR) });
registerDebugToolBarItem($K4b, $g5b, 70, $PFb, $tR, void 0, { id: $M4b, title: $i5b, icon: $OFb, precondition: $7m.and($tR, $KR) });
registerDebugToolBarItem($F4b, $b5b, 20, $RFb, void 0, $5Q.isEqualTo("stopped"));
registerDebugToolBarItem($G4b, $c5b, 30, $SFb, void 0, $5Q.isEqualTo("stopped"));
registerDebugToolBarItem($I4b, $e5b, 40, $TFb, void 0, $5Q.isEqualTo("stopped"));
registerDebugToolBarItem($D4b, $a5b, 60, $QFb);
registerDebugToolBarItem($C4b, localize(5991, null), 50, $UFb, $vR, $5Q.isEqualTo("stopped"));
registerDebugToolBarItem($B4b, localize(5992, null), 55, $XFb, $vR, $5Q.isEqualTo("stopped"));
registerDebugToolBarItem($R4b, $k5b, 100, $6l.listTree, $7m.and($WR, CONTEXT_TOOLBAR_COMMAND_CENTER.negate()));
$dJ.appendMenuItem($bJ.DebugToolBarStop, {
  group: "navigation",
  when: $7m.and($tR.toNegated(), $KR),
  order: 0,
  command: {
    id: $K4b,
    title: $g5b,
    icon: $PFb
  }
});
$dJ.appendMenuItem($bJ.DebugToolBarStop, {
  group: "navigation",
  when: $7m.and($tR, $KR),
  order: 0,
  command: {
    id: $M4b,
    title: $i5b,
    icon: $OFb
  }
});
$dJ.appendMenuItem($bJ.DebugToolBarStop, {
  group: "navigation",
  when: $7m.or($7m.and($tR.toNegated(), $LR, $KR), $7m.and($tR, $LR)),
  order: 0,
  command: {
    id: $L4b,
    title: $h5b,
    icon: $PFb
  }
});

// out-build/vs/workbench/contrib/debug/browser/callStackView.js
var SessionsRenderer_1;
var ThreadsRenderer_1;
var StackFramesRenderer_1;
var ErrorsRenderer_1;
var $139 = $;
function assignSessionContext(element, context) {
  context.sessionId = element.getId();
  return context;
}
function assignThreadContext(element, context) {
  context.threadId = element.getId();
  assignSessionContext(element.session, context);
  return context;
}
function assignStackFrameContext(element, context) {
  context.frameId = element.getId();
  context.frameName = element.name;
  context.frameLocation = { range: element.range, source: element.source.raw };
  assignThreadContext(element.thread, context);
  return context;
}
function $Mac(element) {
  if (element instanceof $PP) {
    return assignStackFrameContext(element, {});
  } else if (element instanceof $QP) {
    return assignThreadContext(element, {});
  } else if (isDebugSession2(element)) {
    return assignSessionContext(element, {});
  } else {
    return void 0;
  }
}
function $Nac(element) {
  if (element instanceof $PP) {
    if (element.source.inMemory) {
      return element.source.raw.path || element.source.reference || element.source.name;
    }
    return element.source.uri.toString();
  }
  if (element instanceof $QP) {
    return element.threadId;
  }
  if (isDebugSession2(element)) {
    return element.getId();
  }
  return "";
}
function $Oac(stackFrame) {
  let callStack = stackFrame.thread.getStaleCallStack();
  callStack = callStack.length > 0 ? callStack : stackFrame.thread.getCallStack();
  const otherSources = callStack.map((sf) => sf.source).filter((s) => s !== stackFrame.source);
  let suffixLength = 0;
  otherSources.forEach((s) => {
    if (s.name === stackFrame.source.name) {
      suffixLength = Math.max(suffixLength, $4f(stackFrame.source.uri.path, s.uri.path));
    }
  });
  if (suffixLength === 0) {
    return stackFrame.source.name;
  }
  const from = Math.max(0, stackFrame.source.uri.path.lastIndexOf($kc.sep, stackFrame.source.uri.path.length - suffixLength - 1));
  return (from > 0 ? "..." : "") + stackFrame.source.uri.path.substring(from);
}
async function expandTo(session, tree) {
  if (session.parentSession) {
    await expandTo(session.parentSession, tree);
  }
  await tree.expand(session);
}
var $Pac = class $Pac2 extends $_ob {
  constructor(ab, contextMenuService, sb, keybindingService, instantiationService, viewDescriptorService, configurationService, contextKeyService, openerService, themeService, telemetryService, hoverService, ac) {
    super(ab, keybindingService, contextMenuService, configurationService, contextKeyService, viewDescriptorService, instantiationService, openerService, themeService, telemetryService, hoverService);
    this.ab = ab;
    this.sb = sb;
    this.ac = ac;
    this.g = false;
    this.h = false;
    this.j = false;
    this.r = /* @__PURE__ */ new Set();
    this.L = false;
    this.f = this.B(new $8h(async () => {
      const sessions = this.sb.getModel().getSessions();
      if (sessions.length === 0) {
        this.r.clear();
      }
      const thread = sessions.length === 1 && sessions[0].getAllThreads().length === 1 ? sessions[0].getAllThreads()[0] : void 0;
      const stoppedDetails = sessions.length === 1 ? sessions[0].getStoppedDetails() : void 0;
      if (stoppedDetails && (thread || typeof stoppedDetails.threadId !== "number")) {
        this.b.textContent = stoppedDescription(stoppedDetails);
        this.c.update(stoppedText(stoppedDetails));
        this.b.classList.toggle("exception", stoppedDetails.reason === "exception");
        this.a.hidden = false;
      } else if (sessions.length === 1 && sessions[0].state === 3) {
        this.b.textContent = localize(5602, null);
        this.c.update(sessions[0].getLabel());
        this.b.classList.remove("exception");
        this.a.hidden = false;
      } else {
        this.a.hidden = true;
      }
      this.$b();
      this.g = false;
      this.m.deemphasizedStackFramesToShow = [];
      await this.n.updateChildren();
      try {
        const toExpand = /* @__PURE__ */ new Set();
        sessions.forEach((s) => {
          if (s.parentSession && !this.r.has(s.parentSession)) {
            toExpand.add(s.parentSession);
          }
        });
        for (const session of toExpand) {
          await expandTo(session, this.n);
          this.r.add(session);
        }
      } catch (e) {
      }
      if (this.L) {
        this.L = false;
        await this.ec();
      }
    }, 50));
  }
  Ob(container2) {
    super.Ob(container2, this.ab.title);
    this.a = $bk(container2, $139("span.call-stack-state-message"));
    this.a.hidden = true;
    this.b = $bk(this.a, $139("span.label"));
    this.c = this.B(this.Hb.setupManagedHover($JZ("mouse"), this.a, ""));
  }
  W(container2) {
    super.W(container2);
    this.element.classList.add("debug-pane");
    container2.classList.add("debug-call-stack");
    const treeContainer = $q4b(container2);
    this.m = new CallStackDataSource(this.sb);
    this.n = this.Db.createInstance($5eb, "CallStackView", treeContainer, new CallStackDelegate(), new CallStackCompressionDelegate(this.sb), [
      this.Db.createInstance(SessionsRenderer),
      this.Db.createInstance(ThreadsRenderer),
      this.Db.createInstance(StackFramesRenderer),
      this.Db.createInstance(ErrorsRenderer),
      new LoadMoreRenderer(),
      new ShowMoreRenderer()
    ], this.m, {
      accessibilityProvider: new CallStackAccessibilityProvider(),
      compressionEnabled: true,
      autoExpandSingleChildren: true,
      identityProvider: {
        getId: (element) => {
          if (typeof element === "string") {
            return element;
          }
          if (element instanceof Array) {
            return `showMore ${element[0].getId()}`;
          }
          return element.getId();
        }
      },
      keyboardNavigationLabelProvider: {
        getKeyboardNavigationLabel: (e) => {
          if (isDebugSession2(e)) {
            return e.getLabel();
          }
          if (e instanceof $QP) {
            return `${e.name} ${e.stateLabel}`;
          }
          if (e instanceof $PP || typeof e === "string") {
            return e;
          }
          if (e instanceof $1P) {
            return LoadMoreRenderer.LABEL;
          }
          return localize(5603, null);
        },
        getCompressedNodeKeyboardNavigationLabel: (e) => {
          const firstItem = e[0];
          if (isDebugSession2(firstItem)) {
            return firstItem.getLabel();
          }
          return "";
        }
      },
      expandOnlyOnTwistieClick: true,
      overrideStyles: this.Xb().listOverrideStyles
    });
    $kR.bindTo(this.n.contextKeyService);
    this.n.setInput(this.sb.getModel());
    this.B(this.n);
    this.B(this.n.onDidOpen(async (e) => {
      if (this.h) {
        return;
      }
      const focusStackFrame = (stackFrame, thread, session, options3 = {}) => {
        this.j = true;
        try {
          this.sb.focusStackFrame(stackFrame, thread, session, { ...options3, ...{ explicit: true } });
        } finally {
          this.j = false;
        }
      };
      const element = e.element;
      if (element instanceof $PP) {
        const opts = {
          preserveFocus: e.editorOptions.preserveFocus,
          sideBySide: e.sideBySide,
          pinned: e.editorOptions.pinned
        };
        focusStackFrame(element, element.thread, element.thread.session, opts);
      }
      if (element instanceof $QP) {
        focusStackFrame(void 0, element, element.session);
      }
      if (isDebugSession2(element)) {
        focusStackFrame(void 0, void 0, element);
      }
      if (element instanceof $1P) {
        const session = this.sb.getModel().getSession(element.sessionId);
        const thread = session && session.getThread(element.threadId);
        if (thread) {
          const totalFrames = thread.stoppedDetails?.totalFrames;
          const remainingFramesCount = typeof totalFrames === "number" ? totalFrames - thread.getCallStack().length : void 0;
          await thread.fetchCallStack(remainingFramesCount);
          await this.n.updateChildren();
        }
      }
      if (element instanceof Array) {
        this.m.deemphasizedStackFramesToShow.push(...element);
        this.n.updateChildren();
      }
    }));
    this.B(this.sb.getModel().onDidChangeCallStack(() => {
      if (!this.isBodyVisible()) {
        this.g = true;
        return;
      }
      if (!this.f.isScheduled()) {
        this.f.schedule();
      }
    }));
    const onFocusChange = Event2.any(this.sb.getViewModel().onDidFocusStackFrame, this.sb.getViewModel().onDidFocusSession);
    this.B(onFocusChange(async () => {
      if (this.j) {
        return;
      }
      if (!this.isBodyVisible()) {
        this.g = true;
        this.L = true;
        return;
      }
      if (this.f.isScheduled()) {
        this.L = true;
        return;
      }
      await this.ec();
    }));
    this.B(this.n.onContextMenu((e) => this.fc(e)));
    if (this.sb.state === 2) {
      this.f.schedule(0);
    }
    this.B(this.onDidChangeBodyVisibility((visible) => {
      if (visible && this.g) {
        this.f.schedule();
      }
    }));
    this.B(this.sb.onDidNewSession((s) => {
      const sessionListeners = [];
      sessionListeners.push(s.onDidChangeName(() => {
        if (this.n.hasNode(s)) {
          this.n.rerender(s);
        }
      }));
      sessionListeners.push(s.onDidEndAdapter(() => $Xc(sessionListeners)));
      if (s.parentSession) {
        this.r.delete(s.parentSession);
      }
    }));
  }
  X(height, width2) {
    super.X(height, width2);
    this.n.layout(height, width2);
  }
  focus() {
    super.focus();
    this.n.domFocus();
  }
  collapseAll() {
    this.n.collapseAll();
  }
  async ec() {
    if (!this.n || !this.n.getInput()) {
      return;
    }
    const updateSelectionAndReveal = (element) => {
      this.h = true;
      try {
        this.n.setSelection([element]);
        if (this.n.getRelativeTop(element) === null) {
          this.n.reveal(element, 0.5);
        } else {
          this.n.reveal(element);
        }
      } catch (e) {
      } finally {
        this.h = false;
      }
    };
    const thread = this.sb.getViewModel().focusedThread;
    const session = this.sb.getViewModel().focusedSession;
    const stackFrame = this.sb.getViewModel().focusedStackFrame;
    if (!thread) {
      if (!session) {
        this.n.setSelection([]);
      } else {
        updateSelectionAndReveal(session);
      }
    } else {
      try {
        await expandTo(thread.session, this.n);
      } catch (e) {
      }
      try {
        await this.n.expand(thread);
      } catch (e) {
      }
      const toReveal = stackFrame || session;
      if (toReveal) {
        updateSelectionAndReveal(toReveal);
      }
    }
  }
  fc(e) {
    const element = e.element;
    let overlay = [];
    if (isDebugSession2(element)) {
      overlay = getSessionContextOverlay(element);
    } else if (element instanceof $QP) {
      overlay = getThreadContextOverlay(element);
    } else if (element instanceof $PP) {
      overlay = getStackFrameContextOverlay(element);
    }
    const contextKeyService = this.Bb.createOverlay(overlay);
    const menu = this.ac.getMenuActions($bJ.DebugCallStackContext, contextKeyService, { arg: $Nac(element), shouldForwardArgs: true });
    const result = $O$(menu, "inline");
    this.zb.showContextMenu({
      getAnchor: () => e.anchor,
      getActions: () => result.secondary,
      getActionsContext: () => $Mac(element)
    });
  }
};
$Pac = __decorate([
  __param(1, $50),
  __param(2, $0R),
  __param(3, $Ty),
  __param(4, $Pk),
  __param(5, $$M),
  __param(6, $kl),
  __param(7, $on),
  __param(8, $O4),
  __param(9, $gs),
  __param(10, $zv),
  __param(11, $5$),
  __param(12, $cJ)
], $Pac);
function getSessionContextOverlay(session) {
  return [
    [$gR.key, "session"],
    [$hR.key, $pP(session)],
    [
      $iR.key,
      session.state === 2
      /* State.Stopped */
    ],
    [$jR.key, session.getAllThreads().length === 1]
  ];
}
var SessionsRenderer = class SessionsRenderer2 {
  static {
    SessionsRenderer_1 = this;
  }
  static {
    this.ID = "session";
  }
  constructor(a, b, c, d) {
    this.a = a;
    this.b = b;
    this.c = c;
    this.d = d;
  }
  get templateId() {
    return SessionsRenderer_1.ID;
  }
  renderTemplate(container2) {
    const session = $bk(container2, $139(".session"));
    $bk(session, $139(ThemeIcon.asCSSSelector($5Fb)));
    const name = $bk(session, $139(".name"));
    const stateLabel = $bk(session, $139("span.state.label.monaco-count-badge.long"));
    const templateDisposable = new $2c();
    const label3 = templateDisposable.add(new $S2(name));
    const stopActionViewItemDisposables = templateDisposable.add(new $2c());
    const actionBar = templateDisposable.add(new $LZ(session, {
      actionViewItemProvider: (action, options3) => {
        if ((action.id === $M4b || action.id === $K4b) && action instanceof $fJ) {
          stopActionViewItemDisposables.clear();
          const item = this.a.invokeFunction((accessor) => $Lac(action, stopActionViewItemDisposables, accessor, { ...options3, menuAsChild: false }));
          if (item) {
            return item;
          }
        }
        if (action instanceof $fJ) {
          return this.a.createInstance($T$, action, { hoverDelegate: options3.hoverDelegate });
        } else if (action instanceof $eJ) {
          return this.a.createInstance($V$, action, { hoverDelegate: options3.hoverDelegate });
        }
        return void 0;
      }
    }));
    const elementDisposable = templateDisposable.add(new $2c());
    return { session, name, stateLabel, label: label3, actionBar, elementDisposable, templateDisposable };
  }
  renderElement(element, _, data) {
    this.f(element.element, $Ul(element.filterData), data);
  }
  renderCompressedElements(node, _index, templateData) {
    const lastElement = node.element.elements[node.element.elements.length - 1];
    const matches = $Ul(node.filterData);
    this.f(lastElement, matches, templateData);
  }
  f(session, matches, data) {
    const sessionHover = data.elementDisposable.add(this.c.setupManagedHover($JZ("mouse"), data.session, localize(5604, null)));
    data.label.set(session.getLabel(), matches);
    const stoppedDetails = session.getStoppedDetails();
    const thread = session.getAllThreads().find((t) => t.stopped);
    const contextKeyService = this.b.createOverlay(getSessionContextOverlay(session));
    const menu = data.elementDisposable.add(this.d.createMenu($bJ.DebugCallStackContext, contextKeyService));
    const setupActionBar = () => {
      data.actionBar.clear();
      const { primary } = $Q$(menu.getActions({ arg: $Nac(session), shouldForwardArgs: true }), "inline");
      data.actionBar.push(primary, { icon: true, label: false });
      data.actionBar.context = $Mac(session);
    };
    data.elementDisposable.add(menu.onDidChange(() => setupActionBar()));
    setupActionBar();
    data.stateLabel.style.display = "";
    if (stoppedDetails) {
      data.stateLabel.textContent = stoppedDescription(stoppedDetails);
      sessionHover.update(`${session.getLabel()}: ${stoppedText(stoppedDetails)}`);
      data.stateLabel.classList.toggle("exception", stoppedDetails.reason === "exception");
    } else if (thread && thread.stoppedDetails) {
      data.stateLabel.textContent = stoppedDescription(thread.stoppedDetails);
      sessionHover.update(`${session.getLabel()}: ${stoppedText(thread.stoppedDetails)}`);
      data.stateLabel.classList.toggle("exception", thread.stoppedDetails.reason === "exception");
    } else {
      data.stateLabel.textContent = localize(5605, null);
      data.stateLabel.classList.remove("exception");
    }
  }
  disposeTemplate(templateData) {
    templateData.templateDisposable.dispose();
  }
  disposeElement(_element, _, templateData) {
    templateData.elementDisposable.clear();
  }
  disposeCompressedElements(node, index, templateData, height) {
    templateData.elementDisposable.clear();
  }
};
SessionsRenderer = SessionsRenderer_1 = __decorate([
  __param(0, $Pk),
  __param(1, $on),
  __param(2, $5$),
  __param(3, $cJ)
], SessionsRenderer);
function getThreadContextOverlay(thread) {
  return [
    [$gR.key, "thread"],
    [$iR.key, thread.stopped]
  ];
}
var ThreadsRenderer = class ThreadsRenderer2 {
  static {
    ThreadsRenderer_1 = this;
  }
  static {
    this.ID = "thread";
  }
  constructor(a, b, c) {
    this.a = a;
    this.b = b;
    this.c = c;
  }
  get templateId() {
    return ThreadsRenderer_1.ID;
  }
  renderTemplate(container2) {
    const thread = $bk(container2, $139(".thread"));
    const name = $bk(thread, $139(".name"));
    const stateLabel = $bk(thread, $139("span.state.label.monaco-count-badge.long"));
    const templateDisposable = new $2c();
    const label3 = templateDisposable.add(new $S2(name));
    const actionBar = templateDisposable.add(new $LZ(thread));
    const elementDisposable = templateDisposable.add(new $2c());
    return { thread, name, stateLabel, label: label3, actionBar, elementDisposable, templateDisposable };
  }
  renderElement(element, _index, data) {
    const thread = element.element;
    data.elementDisposable.add(this.b.setupManagedHover($JZ("mouse"), data.thread, thread.name));
    data.label.set(thread.name, $Ul(element.filterData));
    data.stateLabel.textContent = thread.stateLabel;
    data.stateLabel.classList.toggle("exception", thread.stoppedDetails?.reason === "exception");
    const contextKeyService = this.a.createOverlay(getThreadContextOverlay(thread));
    const menu = data.elementDisposable.add(this.c.createMenu($bJ.DebugCallStackContext, contextKeyService));
    const setupActionBar = () => {
      data.actionBar.clear();
      const { primary } = $Q$(menu.getActions({ arg: $Nac(thread), shouldForwardArgs: true }), "inline");
      data.actionBar.push(primary, { icon: true, label: false });
      data.actionBar.context = $Mac(thread);
    };
    data.elementDisposable.add(menu.onDidChange(() => setupActionBar()));
    setupActionBar();
  }
  renderCompressedElements(_node, _index, _templateData, _height) {
    throw new Error("Method not implemented.");
  }
  disposeElement(_element, _index, templateData) {
    templateData.elementDisposable.clear();
  }
  disposeTemplate(templateData) {
    templateData.templateDisposable.dispose();
  }
};
ThreadsRenderer = ThreadsRenderer_1 = __decorate([
  __param(0, $on),
  __param(1, $5$),
  __param(2, $cJ)
], ThreadsRenderer);
function getStackFrameContextOverlay(stackFrame) {
  return [
    [$gR.key, "stackFrame"],
    [$xR.key, stackFrame.canRestart]
  ];
}
var StackFramesRenderer = class StackFramesRenderer2 {
  static {
    StackFramesRenderer_1 = this;
  }
  static {
    this.ID = "stackFrame";
  }
  constructor(a, b, c) {
    this.a = a;
    this.b = b;
    this.c = c;
  }
  get templateId() {
    return StackFramesRenderer_1.ID;
  }
  renderTemplate(container2) {
    const stackFrame = $bk(container2, $139(".stack-frame"));
    const labelDiv = $bk(stackFrame, $139("span.label.expression"));
    const file = $bk(stackFrame, $139(".file"));
    const fileName = $bk(file, $139("span.file-name"));
    const wrapper = $bk(file, $139("span.line-number-wrapper"));
    const lineNumber = $bk(wrapper, $139("span.line-number.monaco-count-badge"));
    const templateDisposable = new $2c();
    const label3 = templateDisposable.add(new $S2(labelDiv));
    const actionBar = templateDisposable.add(new $LZ(stackFrame));
    return { file, fileName, label: label3, lineNumber, stackFrame, actionBar, templateDisposable };
  }
  renderElement(element, index, data) {
    const stackFrame = element.element;
    data.stackFrame.classList.toggle("disabled", !stackFrame.source || !stackFrame.source.available || $9R(stackFrame));
    data.stackFrame.classList.toggle("label", stackFrame.presentationHint === "label");
    const hasActions = !!stackFrame.thread.session.capabilities.supportsRestartFrame && stackFrame.presentationHint !== "label" && stackFrame.presentationHint !== "subtle" && stackFrame.canRestart;
    data.stackFrame.classList.toggle("has-actions", hasActions);
    let title = stackFrame.source.inMemory ? stackFrame.source.uri.path : this.b.getUriLabel(stackFrame.source.uri);
    if (stackFrame.source.raw.origin) {
      title += `
${stackFrame.source.raw.origin}`;
    }
    data.templateDisposable.add(this.a.setupManagedHover($JZ("mouse"), data.file, title));
    data.label.set(stackFrame.name, $Ul(element.filterData), stackFrame.name);
    data.fileName.textContent = $Oac(stackFrame);
    if (stackFrame.range.startLineNumber !== void 0) {
      data.lineNumber.textContent = `${stackFrame.range.startLineNumber}`;
      if (stackFrame.range.startColumn) {
        data.lineNumber.textContent += `:${stackFrame.range.startColumn}`;
      }
      data.lineNumber.classList.remove("unavailable");
    } else {
      data.lineNumber.classList.add("unavailable");
    }
    data.actionBar.clear();
    if (hasActions) {
      const action = new $Um("debug.callStack.restartFrame", localize(5606, null), ThemeIcon.asClassName($NFb), true, async () => {
        try {
          await stackFrame.restart();
        } catch (e) {
          this.c.error(e);
        }
      });
      data.actionBar.push(action, { icon: true, label: false });
    }
  }
  renderCompressedElements(node, index, templateData, height) {
    throw new Error("Method not implemented.");
  }
  disposeTemplate(templateData) {
    templateData.actionBar.dispose();
  }
};
StackFramesRenderer = StackFramesRenderer_1 = __decorate([
  __param(0, $5$),
  __param(1, $ZI),
  __param(2, $PJ)
], StackFramesRenderer);
var ErrorsRenderer = class ErrorsRenderer2 {
  static {
    ErrorsRenderer_1 = this;
  }
  static {
    this.ID = "error";
  }
  get templateId() {
    return ErrorsRenderer_1.ID;
  }
  constructor(a) {
    this.a = a;
  }
  renderTemplate(container2) {
    const label3 = $bk(container2, $139(".error"));
    return { label: label3, templateDisposable: new $2c() };
  }
  renderElement(element, index, data) {
    const error = element.element;
    data.label.textContent = error;
    data.templateDisposable.add(this.a.setupManagedHover($JZ("mouse"), data.label, error));
  }
  renderCompressedElements(node, index, templateData, height) {
    throw new Error("Method not implemented.");
  }
  disposeTemplate(templateData) {
  }
};
ErrorsRenderer = ErrorsRenderer_1 = __decorate([
  __param(0, $5$)
], ErrorsRenderer);
var LoadMoreRenderer = class _LoadMoreRenderer {
  static {
    this.ID = "loadMore";
  }
  static {
    this.LABEL = localize(5607, null);
  }
  constructor() {
  }
  get templateId() {
    return _LoadMoreRenderer.ID;
  }
  renderTemplate(container2) {
    const label3 = $bk(container2, $139(".load-all"));
    label3.style.color = $Zn($no);
    return { label: label3 };
  }
  renderElement(element, index, data) {
    data.label.textContent = _LoadMoreRenderer.LABEL;
  }
  renderCompressedElements(node, index, templateData, height) {
    throw new Error("Method not implemented.");
  }
  disposeTemplate(templateData) {
  }
};
var ShowMoreRenderer = class _ShowMoreRenderer {
  static {
    this.ID = "showMore";
  }
  constructor() {
  }
  get templateId() {
    return _ShowMoreRenderer.ID;
  }
  renderTemplate(container2) {
    const label3 = $bk(container2, $139(".show-more"));
    label3.style.color = $Zn($no);
    return { label: label3 };
  }
  renderElement(element, index, data) {
    const stackFrames = element.element;
    if (stackFrames.every((sf) => !!(sf.source && sf.source.origin && sf.source.origin === stackFrames[0].source.origin))) {
      data.label.textContent = localize(5608, null, stackFrames.length, stackFrames[0].source.origin);
    } else {
      data.label.textContent = localize(5609, null, stackFrames.length);
    }
  }
  renderCompressedElements(node, index, templateData, height) {
    throw new Error("Method not implemented.");
  }
  disposeTemplate(templateData) {
  }
};
var CallStackDelegate = class {
  getHeight(element) {
    if (element instanceof $PP && element.presentationHint === "label") {
      return 16;
    }
    if (element instanceof $1P || element instanceof Array) {
      return 16;
    }
    return 22;
  }
  getTemplateId(element) {
    if (isDebugSession2(element)) {
      return SessionsRenderer.ID;
    }
    if (element instanceof $QP) {
      return ThreadsRenderer.ID;
    }
    if (element instanceof $PP) {
      return StackFramesRenderer.ID;
    }
    if (typeof element === "string") {
      return ErrorsRenderer.ID;
    }
    if (element instanceof $1P) {
      return LoadMoreRenderer.ID;
    }
    return ShowMoreRenderer.ID;
  }
};
function stoppedText(stoppedDetails) {
  return stoppedDetails.text ?? stoppedDescription(stoppedDetails);
}
function stoppedDescription(stoppedDetails) {
  return stoppedDetails.description || (stoppedDetails.reason ? localize(5610, null, stoppedDetails.reason) : localize(5611, null));
}
function isDebugModel(obj) {
  return typeof obj.getSessions === "function";
}
function isDebugSession2(obj) {
  return obj && typeof obj.getAllThreads === "function";
}
var CallStackDataSource = class {
  constructor(a) {
    this.a = a;
    this.deemphasizedStackFramesToShow = [];
  }
  hasChildren(element) {
    if (isDebugSession2(element)) {
      const threads = element.getAllThreads();
      return threads.length > 1 || threads.length === 1 && threads[0].stopped || !!this.a.getModel().getSessions().find((s) => s.parentSession === element);
    }
    return isDebugModel(element) || element instanceof $QP && element.stopped;
  }
  async getChildren(element) {
    if (isDebugModel(element)) {
      const sessions = element.getSessions();
      if (sessions.length === 0) {
        return Promise.resolve([]);
      }
      if (sessions.length > 1 || this.a.getViewModel().isMultiSessionView()) {
        return Promise.resolve(sessions.filter((s) => !s.parentSession));
      }
      const threads = sessions[0].getAllThreads();
      return threads.length === 1 ? this.b(threads[0]) : Promise.resolve(threads);
    } else if (isDebugSession2(element)) {
      const childSessions = this.a.getModel().getSessions().filter((s) => s.parentSession === element);
      const threads = element.getAllThreads();
      if (threads.length === 1) {
        const children = await this.b(threads[0]);
        return children.concat(childSessions);
      }
      return Promise.resolve(threads.concat(childSessions));
    } else {
      return this.b(element);
    }
  }
  b(thread) {
    return this.c(thread).then((children) => {
      const result = [];
      children.forEach((child, index) => {
        if (child instanceof $PP && child.source && $9R(child)) {
          if (this.deemphasizedStackFramesToShow.indexOf(child) === -1) {
            if (result.length) {
              const last = result[result.length - 1];
              if (last instanceof Array) {
                last.push(child);
                return;
              }
            }
            const nextChild = index < children.length - 1 ? children[index + 1] : void 0;
            if (nextChild instanceof $PP && nextChild.source && $9R(nextChild)) {
              result.push([child]);
              return;
            }
          }
        }
        result.push(child);
      });
      return result;
    });
  }
  async c(thread) {
    let callStack = thread.getCallStack();
    if (!callStack || !callStack.length) {
      await thread.fetchCallStack();
      callStack = thread.getCallStack();
    }
    if (callStack.length === 1 && thread.session.capabilities.supportsDelayedStackTraceLoading && thread.stoppedDetails && thread.stoppedDetails.totalFrames && thread.stoppedDetails.totalFrames > 1) {
      callStack = callStack.concat(thread.getStaleCallStack().slice(1));
    }
    if (thread.stoppedDetails && thread.stoppedDetails.framesErrorMessage) {
      callStack = callStack.concat([thread.stoppedDetails.framesErrorMessage]);
    }
    if (!thread.reachedEndOfCallStack && thread.stoppedDetails) {
      callStack = callStack.concat([new $1P(thread.session.getId(), thread.threadId)]);
    }
    return callStack;
  }
};
var CallStackAccessibilityProvider = class {
  getWidgetAriaLabel() {
    return localize(5612, null);
  }
  getWidgetRole() {
    return "treegrid";
  }
  getRole(_element) {
    return "row";
  }
  getAriaLabel(element) {
    if (element instanceof $QP) {
      return localize(5613, null, element.name, element.stateLabel);
    }
    if (element instanceof $PP) {
      return localize(5614, null, element.name, element.range.startLineNumber, $Oac(element));
    }
    if (isDebugSession2(element)) {
      const thread = element.getAllThreads().find((t) => t.stopped);
      const state = thread ? thread.stateLabel : localize(5615, null);
      return localize(5616, null, element.getLabel(), state);
    }
    if (typeof element === "string") {
      return element;
    }
    if (element instanceof Array) {
      return localize(5617, null, element.length);
    }
    return LoadMoreRenderer.LABEL;
  }
};
var CallStackCompressionDelegate = class {
  constructor(a) {
    this.a = a;
  }
  isIncompressible(stat) {
    if (isDebugSession2(stat)) {
      if (stat.compact) {
        return false;
      }
      const sessions = this.a.getModel().getSessions();
      if (sessions.some((s) => s.parentSession === stat && s.compact)) {
        return false;
      }
      return true;
    }
    return true;
  }
};
$hJ(class Collapse extends $cpb {
  constructor() {
    super({
      id: "callStack.collapse",
      viewId: $WQ,
      title: localize(5618, null),
      f1: false,
      icon: $6l.collapseAll,
      precondition: $5Q.isEqualTo($7R(
        2
        /* State.Stopped */
      )),
      menu: {
        id: $bJ.ViewTitle,
        order: 10,
        group: "navigation",
        when: $7m.equals("view", $WQ)
      }
    });
  }
  runInView(_accessor, view) {
    view.collapseAll();
  }
});
function registerCallStackInlineMenuItem(id2, title, icon2, when, order, precondition2) {
  $dJ.appendMenuItem($bJ.DebugCallStackContext, {
    group: "inline",
    order,
    when,
    command: { id: id2, title, icon: icon2, precondition: precondition2 }
  });
}
var threadOrSessionWithOneThread = $7m.or($gR.isEqualTo("thread"), $7m.and($gR.isEqualTo("session"), $jR));
registerCallStackInlineMenuItem($J4b, $f5b, $VFb, $7m.and(threadOrSessionWithOneThread, $iR.toNegated()), 10, $uR.toNegated());
registerCallStackInlineMenuItem($O4b, $j5b, $WFb, $7m.and(threadOrSessionWithOneThread, $iR), 10);
registerCallStackInlineMenuItem($F4b, $b5b, $RFb, threadOrSessionWithOneThread, 20, $iR);
registerCallStackInlineMenuItem($G4b, $c5b, $SFb, threadOrSessionWithOneThread, 30, $iR);
registerCallStackInlineMenuItem($I4b, $e5b, $TFb, threadOrSessionWithOneThread, 40, $iR);
registerCallStackInlineMenuItem($D4b, $a5b, $QFb, $gR.isEqualTo("session"), 50);
registerCallStackInlineMenuItem($M4b, $i5b, $OFb, $7m.and($hR.toNegated(), $gR.isEqualTo("session")), 60);
registerCallStackInlineMenuItem($K4b, $g5b, $PFb, $7m.and($hR, $gR.isEqualTo("session")), 60);

// out-build/vs/workbench/contrib/debug/browser/replAccessibleView.js
var $Qac = class {
  constructor() {
    this.priority = 70;
    this.name = "debugConsole";
    this.when = $7m.equals("focusedView", "workbench.panel.repl.view");
    this.type = "view";
  }
  getProvider(accessor) {
    const viewsService = accessor.get($uob);
    const accessibleViewService = accessor.get($shb);
    const replView = $p9b(viewsService);
    if (!replView) {
      return void 0;
    }
    const focusedElement = replView.getFocusedElement();
    return new ReplOutputAccessibleViewProvider(replView, focusedElement, accessibleViewService);
  }
};
var ReplOutputAccessibleViewProvider = class ReplOutputAccessibleViewProvider2 extends $3c {
  constructor(h3, j, m) {
    super();
    this.h = h3;
    this.j = j;
    this.m = m;
    this.id = "repl";
    this.b = this.B(new $ze());
    this.onDidChangeContent = this.b.event;
    this.c = this.B(new $ze());
    this.onDidResolveChildren = this.c.event;
    this.verbositySettingKey = "accessibility.verbosity.debug";
    this.options = {
      type: "view"
      /* AccessibleViewType.View */
    };
    this.f = /* @__PURE__ */ new Map();
    this.g = false;
    this.g = !!j;
  }
  provideContent() {
    const debugSession = this.h.getDebugSession();
    if (!debugSession) {
      return "No debug session available.";
    }
    const elements = debugSession.getReplElements();
    if (!elements.length) {
      return "No output in the debug console.";
    }
    if (!this.a) {
      this.n(elements);
    }
    return this.a ?? elements.map((e) => e.toString(true)).join("\n");
  }
  onClose() {
    this.a = void 0;
    this.f.clear();
    if (this.g) {
      return this.h.focusTree();
    }
    this.h.getReplInput().focus();
  }
  onOpen() {
    this.B(this.onDidResolveChildren(() => {
      this.b.fire();
      queueMicrotask(() => {
        if (this.j) {
          const position = this.f.get(this.j.getId());
          if (position) {
            this.m.setPosition(position, true);
          }
        }
      });
    }));
  }
  async n(elements) {
    const dataSource = this.h.getReplDataSource();
    if (!dataSource) {
      return;
    }
    let line = 1;
    const content = [];
    for (const e of elements) {
      content.push(e.toString().replace(/\n/g, ""));
      this.f.set(e.getId(), new $8C(line, 1));
      line++;
      if (dataSource.hasChildren(e)) {
        const childContent = [];
        const children = await dataSource.getChildren(e);
        for (const child of children) {
          const id2 = child.getId();
          if (!this.f.has(id2)) {
            this.f.set(id2, new $8C(line, 1));
          }
          childContent.push("  " + child.toString());
          line++;
        }
        content.push(childContent.join("\n"));
      }
    }
    this.a = content.join("\n");
    this.c.fire();
  }
};
ReplOutputAccessibleViewProvider = __decorate([
  __param(2, $shb)
], ReplOutputAccessibleViewProvider);

// out-build/vs/workbench/contrib/debug/browser/debugConsoleQuickAccess.js
var $Rac = class $Rac2 extends $rhb {
  constructor(a, b, h3) {
    super($C5b, { canAcceptInBackground: true });
    this.a = a;
    this.b = b;
    this.h = h3;
  }
  g(filter, disposables, token) {
    const debugConsolePicks = [];
    this.a.getModel().getSessions(true).filter((s) => s.hasSeparateRepl()).forEach((session, index) => {
      const pick = this.m(session, index, filter);
      if (pick) {
        debugConsolePicks.push(pick);
      }
    });
    if (debugConsolePicks.length > 0) {
      debugConsolePicks.push({ type: "separator" });
    }
    const createTerminalLabel = localize(5807, null);
    debugConsolePicks.push({
      label: `$(plus) ${createTerminalLabel}`,
      ariaLabel: createTerminalLabel,
      accept: () => this.h.executeCommand($S4b)
    });
    return debugConsolePicks;
  }
  m(session, sessionIndex, filter) {
    const label3 = session.name;
    const highlights = $Rl(filter, label3, true);
    if (highlights) {
      return {
        label: label3,
        highlights: { label: highlights },
        accept: (keyMod, event) => {
          this.a.focusStackFrame(void 0, void 0, session, { explicit: true });
          if (!this.b.isViewVisible($2Q)) {
            this.b.openView($2Q, true);
          }
        }
      };
    }
    return void 0;
  }
};
$Rac = __decorate([
  __param(0, $0R),
  __param(1, $uob),
  __param(2, $sn)
], $Rac);

// out-build/vs/workbench/contrib/debug/browser/disassemblyView.js
var $R3b_1;
var BreakpointRenderer_1;
var InstructionRenderer_1;
var disassemblyNotAvailable = {
  allowBreakpoint: false,
  isBreakpointSet: false,
  isBreakpointEnabled: false,
  instructionReference: "",
  instructionOffset: 0,
  instructionReferenceOffset: 0,
  address: 0n,
  instruction: {
    address: "-1",
    instruction: localize(5998, null)
  }
};
var $R3b = class $R3b2 extends $5tb {
  static {
    $R3b_1 = this;
  }
  static {
    this.a = 50;
  }
  constructor(group2, telemetryService, themeService, storageService, cb, db, eb) {
    super($ZQ, group2, telemetryService, themeService, storageService);
    this.cb = cb;
    this.db = db;
    this.eb = eb;
    this.j = [];
    this.m = true;
    this.r = false;
    this.u = /* @__PURE__ */ new Map();
    this.c = void 0;
    this.f = this.B(new $ze({ leakWarningThreshold: 1e3 }));
    this.g = eb.state;
    this.B(cb.onDidChangeConfiguration((e) => {
      if (e.affectsConfiguration("debug")) {
        const newValue = this.cb.getValue("debug").disassemblyView.showSourceCode;
        if (this.m !== newValue) {
          this.m = newValue;
        } else {
          this.c?.rerender();
        }
      }
    }));
  }
  get fontInfo() {
    if (!this.b) {
      this.b = this.fb();
      this.B(this.cb.onDidChangeConfiguration((e) => {
        if (e.affectsConfiguration("editor")) {
          this.b = this.fb();
        }
      }));
    }
    return this.b;
  }
  fb() {
    return $ED.createFromRawSettings(this.cb.getValue("editor"), $_1.getInstance(this.window).value);
  }
  get currentInstructionAddresses() {
    return this.eb.getModel().getSessions(false).map((session) => session.getAllThreads()).reduce((prev, curr) => prev.concat(curr), []).map((thread) => thread.getTopStackFrame()).map((frame) => frame?.instructionPointerReference).map((ref) => ref ? this.getReferenceAddress(ref) : void 0);
  }
  // Instruction reference of the top stack frame of the focused stack
  get focusedCurrentInstructionReference() {
    return this.eb.getViewModel().focusedStackFrame?.thread.getTopStackFrame()?.instructionPointerReference;
  }
  get focusedCurrentInstructionAddress() {
    const ref = this.focusedCurrentInstructionReference;
    return ref ? this.getReferenceAddress(ref) : void 0;
  }
  get focusedInstructionReference() {
    return this.eb.getViewModel().focusedStackFrame?.instructionPointerReference;
  }
  get focusedInstructionAddress() {
    const ref = this.focusedInstructionReference;
    return ref ? this.getReferenceAddress(ref) : void 0;
  }
  get isSourceCodeRender() {
    return this.m;
  }
  get debugSession() {
    return this.eb.getViewModel().focusedSession;
  }
  get onDidChangeStackFrame() {
    return this.f.event;
  }
  get focusedAddressAndOffset() {
    const element = this.c?.getFocusedElements()[0];
    if (!element) {
      return void 0;
    }
    const reference = element.instructionReference;
    const offset = Number(element.address - this.getReferenceAddress(reference));
    return { reference, offset, address: element.address };
  }
  Y(parent) {
    this.m = this.cb.getValue("debug").disassemblyView.showSourceCode;
    const lineHeight = this.fontInfo.lineHeight;
    const thisOM = this;
    const delegate = new class {
      constructor() {
        this.headerRowHeight = 0;
      }
      getHeight(row) {
        if (thisOM.isSourceCodeRender && row.showSourceLocation && row.instruction.location?.path && row.instruction.line) {
          if (row.instruction.endLine) {
            return lineHeight * (row.instruction.endLine - row.instruction.line + 2);
          } else {
            return lineHeight * 2;
          }
        }
        return lineHeight;
      }
    }();
    const instructionRenderer = this.B(this.db.createInstance(InstructionRenderer, this));
    this.c = this.B(this.db.createInstance($Yeb, "DisassemblyView", parent, delegate, [
      {
        label: "",
        tooltip: "",
        weight: 0,
        minimumWidth: this.fontInfo.lineHeight,
        maximumWidth: this.fontInfo.lineHeight,
        templateId: BreakpointRenderer.TEMPLATE_ID,
        project(row) {
          return row;
        }
      },
      {
        label: localize(5999, null),
        tooltip: "",
        weight: 0.3,
        templateId: InstructionRenderer.TEMPLATE_ID,
        project(row) {
          return row;
        }
      }
    ], [
      this.db.createInstance(BreakpointRenderer, this),
      instructionRenderer
    ], {
      identityProvider: { getId: (e) => e.instruction.address },
      horizontalScrolling: false,
      overrideStyles: {
        listBackground: $Ko
      },
      multipleSelectionSupport: false,
      setRowLineHeight: false,
      openOnSingleClick: false,
      accessibilityProvider: new AccessibilityProvider2(),
      mouseSupport: false
    }));
    this.c.domNode.classList.add("disassembly-view");
    if (this.focusedInstructionReference) {
      this.ob(this.focusedInstructionReference, 0);
    }
    this.B(this.c.onDidScroll((e) => {
      if (this.r) {
        return;
      }
      if (e.oldScrollTop > e.scrollTop && e.scrollTop < e.height) {
        this.r = true;
        const prevTop = Math.floor(e.scrollTop / this.fontInfo.lineHeight);
        this.ib($R3b_1.a).then((loaded) => {
          if (loaded > 0) {
            this.c.reveal(prevTop + loaded, 0);
          }
          this.r = false;
        });
      } else if (e.oldScrollTop < e.scrollTop && e.scrollTop + e.height > e.scrollHeight - e.height) {
        this.r = true;
        this.jb($R3b_1.a).then(() => {
          this.r = false;
        });
      }
    }));
    this.B(this.eb.getViewModel().onDidFocusStackFrame(({ stackFrame }) => {
      if (this.c && stackFrame?.instructionPointerReference) {
        this.goToInstructionAndOffset(stackFrame.instructionPointerReference, 0);
      }
      this.f.fire();
    }));
    this.B(this.eb.getModel().onDidChangeBreakpoints((bpEvent) => {
      if (bpEvent && this.c) {
        let changed = false;
        bpEvent.added?.forEach((bp) => {
          if (bp instanceof $ZP) {
            const index = this.mb(bp.instructionReference, bp.offset);
            if (index >= 0) {
              this.c.row(index).isBreakpointSet = true;
              this.c.row(index).isBreakpointEnabled = bp.enabled;
              changed = true;
            }
          }
        });
        bpEvent.removed?.forEach((bp) => {
          if (bp instanceof $ZP) {
            const index = this.mb(bp.instructionReference, bp.offset);
            if (index >= 0) {
              this.c.row(index).isBreakpointSet = false;
              changed = true;
            }
          }
        });
        bpEvent.changed?.forEach((bp) => {
          if (bp instanceof $ZP) {
            const index = this.mb(bp.instructionReference, bp.offset);
            if (index >= 0) {
              if (this.c.row(index).isBreakpointEnabled !== bp.enabled) {
                this.c.row(index).isBreakpointEnabled = bp.enabled;
                changed = true;
              }
            }
          }
        });
        this.j = this.eb.getModel().getInstructionBreakpoints();
        for (const bp of this.j) {
          this.kb(bp.instructionReference);
        }
        if (changed) {
          this.f.fire();
        }
      }
    }));
    this.B(this.eb.onDidChangeState((e) => {
      if ((e === 3 || e === 2) && (this.g !== 3 && this.g !== 2)) {
        this.pb();
        this.m = this.cb.getValue("debug").disassemblyView.showSourceCode;
      }
      this.g = e;
      this.f.fire();
    }));
  }
  layout(dimension) {
    this.c?.layout(dimension.height);
  }
  async goToInstructionAndOffset(instructionReference, offset, focus) {
    let addr = this.u.get(instructionReference);
    if (addr === void 0) {
      await this.lb(instructionReference, 0, -$R3b_1.a, $R3b_1.a * 2);
      addr = this.u.get(instructionReference);
    }
    if (addr) {
      this.hb(addr + BigInt(offset), focus);
    }
  }
  /** Gets the address associated with the instruction reference. */
  getReferenceAddress(instructionReference) {
    return this.u.get(instructionReference);
  }
  /**
   * Go to the address provided. If no address is provided, reveal the address of the currently focused stack frame. Returns false if that address is not available.
   */
  hb(address, focus) {
    if (!this.c) {
      return false;
    }
    if (!address) {
      return false;
    }
    const index = this.nb(address);
    if (index >= 0) {
      this.c.reveal(index);
      if (focus) {
        this.c.domFocus();
        this.c.setFocus([index]);
      }
      return true;
    }
    return false;
  }
  async ib(instructionCount) {
    const first = this.c?.row(0);
    if (first) {
      return this.lb(first.instructionReference, first.instructionReferenceOffset, first.instructionOffset - instructionCount, instructionCount);
    }
    return 0;
  }
  async jb(instructionCount) {
    const last = this.c?.row(this.c?.length - 1);
    if (last) {
      return this.lb(last.instructionReference, last.instructionReferenceOffset, last.instructionOffset + 1, instructionCount);
    }
    return 0;
  }
  /**
   * Sets the memory reference address. We don't just loadDisassembledInstructions
   * for this, since we can't really deal with discontiguous ranges (we can't
   * detect _if_ a range is discontiguous since we don't know how much memory
   * comes between instructions.)
   */
  async kb(instructionReference) {
    if (this.u.has(instructionReference)) {
      return true;
    }
    const s = await this.debugSession?.disassemble(instructionReference, 0, 0, 1);
    if (s && s.length > 0) {
      try {
        this.u.set(instructionReference, BigInt(s[0].address));
        return true;
      } catch {
        return false;
      }
    }
    return false;
  }
  /** Loads disasembled instructions. Returns the number of instructions that were loaded. */
  async lb(instructionReference, offset, instructionOffset, instructionCount) {
    const session = this.debugSession;
    const resultEntries = await session?.disassemble(instructionReference, offset, instructionOffset, instructionCount);
    if (!this.u.has(instructionReference) && instructionOffset !== 0) {
      await this.lb(instructionReference, 0, 0, $R3b_1.a);
    }
    if (session && resultEntries && this.c) {
      const newEntries = [];
      let lastLocation;
      let lastLine;
      for (let i2 = 0; i2 < resultEntries.length; i2++) {
        const instruction = resultEntries[i2];
        const thisInstructionOffset = instructionOffset + i2;
        if (instruction.location) {
          lastLocation = instruction.location;
          lastLine = void 0;
        }
        if (instruction.line) {
          const currentLine = {
            startLineNumber: instruction.line,
            startColumn: instruction.column ?? 0,
            endLineNumber: instruction.endLine ?? instruction.line,
            endColumn: instruction.endColumn ?? 0
          };
          if (!$9C.equalsRange(currentLine, lastLine ?? null)) {
            lastLine = currentLine;
            instruction.location = lastLocation;
          }
        }
        let address;
        try {
          address = BigInt(instruction.address);
        } catch {
          console.error(`Could not parse disassembly address ${instruction.address} (in ${JSON.stringify(instruction)})`);
          continue;
        }
        const entry = {
          allowBreakpoint: true,
          isBreakpointSet: false,
          isBreakpointEnabled: false,
          instructionReference,
          instructionReferenceOffset: offset,
          instructionOffset: thisInstructionOffset,
          instruction,
          address
        };
        newEntries.push(entry);
        if (offset === 0 && thisInstructionOffset === 0) {
          this.u.set(instructionReference, address);
        }
      }
      if (newEntries.length === 0) {
        return 0;
      }
      const refBaseAddress = this.u.get(instructionReference);
      const bps = this.j.map((p) => {
        const base = this.u.get(p.instructionReference);
        if (!base) {
          return void 0;
        }
        return {
          enabled: p.enabled,
          address: base + BigInt(p.offset || 0)
        };
      });
      if (refBaseAddress !== void 0) {
        for (const entry of newEntries) {
          const bp = bps.find((p) => p?.address === entry.address);
          if (bp) {
            entry.isBreakpointSet = true;
            entry.isBreakpointEnabled = bp.enabled;
          }
        }
      }
      const da = this.c;
      if (da.length === 1 && this.c.row(0) === disassemblyNotAvailable) {
        da.splice(0, 1);
      }
      const firstAddr = newEntries[0].address;
      const lastAddr = newEntries[newEntries.length - 1].address;
      const startN = $Cb(da.length, (i2) => Number(da.row(i2).address - firstAddr));
      const start = startN < 0 ? ~startN : startN;
      const endN = $Cb(da.length, (i2) => Number(da.row(i2).address - lastAddr));
      const end = endN < 0 ? ~endN : endN + 1;
      const toDelete = end - start;
      let lastLocated;
      for (let i2 = start - 1; i2 >= 0; i2--) {
        const { instruction } = da.row(i2);
        if (instruction.location && instruction.line !== void 0) {
          lastLocated = instruction;
          break;
        }
      }
      const shouldShowLocation = (instruction) => instruction.line !== void 0 && instruction.location !== void 0 && (!lastLocated || !$zP(instruction.location, lastLocated.location) || instruction.line !== lastLocated.line);
      for (const entry of newEntries) {
        if (shouldShowLocation(entry.instruction)) {
          entry.showSourceLocation = true;
          lastLocated = entry.instruction;
        }
      }
      da.splice(start, toDelete, newEntries);
      return newEntries.length - toDelete;
    }
    return 0;
  }
  mb(instructionReference, offset) {
    const addr = this.u.get(instructionReference);
    if (addr === void 0) {
      return -1;
    }
    return this.nb(addr + BigInt(offset));
  }
  nb(address) {
    const disassembledInstructions = this.c;
    if (disassembledInstructions && disassembledInstructions.length > 0) {
      return $Cb(disassembledInstructions.length, (index) => {
        const row = disassembledInstructions.row(index);
        return Number(row.address - address);
      });
    }
    return -1;
  }
  /**
   * Clears the table and reload instructions near the target address
   */
  ob(instructionReference, offset) {
    if (!this.c) {
      return;
    }
    this.r = true;
    this.pb();
    this.j = this.eb.getModel().getInstructionBreakpoints();
    this.lb(instructionReference, offset, -$R3b_1.a * 4, $R3b_1.a * 8).then(() => {
      if (this.c.length > 0) {
        const targetIndex = Math.floor(this.c.length / 2);
        this.c.reveal(targetIndex, 0.5);
        this.c.domFocus();
        this.c.setFocus([targetIndex]);
      }
      this.r = false;
    });
  }
  pb() {
    this.u.clear();
    this.c?.splice(0, this.c.length, [disassemblyNotAvailable]);
  }
};
$R3b = $R3b_1 = __decorate([
  __param(1, $zv),
  __param(2, $gs),
  __param(3, $jv),
  __param(4, $kl),
  __param(5, $Pk),
  __param(6, $0R)
], $R3b);
var BreakpointRenderer = class BreakpointRenderer2 {
  static {
    BreakpointRenderer_1 = this;
  }
  static {
    this.TEMPLATE_ID = "breakpoint";
  }
  constructor(g, h3) {
    this.g = g;
    this.h = h3;
    this.templateId = BreakpointRenderer_1.TEMPLATE_ID;
    this.a = "codicon-" + $CFb.regular.id;
    this.b = "codicon-" + $CFb.disabled.id;
    this.c = "codicon-" + $HFb.id;
    this.d = "codicon-" + $KFb.id;
    this.f = "codicon-" + $LFb.id;
  }
  renderTemplate(container2) {
    container2.style.alignSelf = "flex-end";
    const icon2 = $bk(container2, $(".codicon"));
    icon2.style.display = "flex";
    icon2.style.alignItems = "center";
    icon2.style.justifyContent = "center";
    icon2.style.height = this.g.fontInfo.lineHeight + "px";
    const currentElement = { element: void 0 };
    const disposables = [
      this.g.onDidChangeStackFrame(() => this.j(icon2, currentElement.element)),
      $aj(container2, "mouseover", () => {
        if (currentElement.element?.allowBreakpoint) {
          icon2.classList.add(this.c);
        }
      }),
      $aj(container2, "mouseout", () => {
        if (currentElement.element?.allowBreakpoint) {
          icon2.classList.remove(this.c);
        }
      }),
      $aj(container2, "click", () => {
        if (currentElement.element?.allowBreakpoint) {
          icon2.classList.add(this.c);
          const reference = currentElement.element.instructionReference;
          const offset = Number(currentElement.element.address - this.g.getReferenceAddress(reference));
          if (currentElement.element.isBreakpointSet) {
            this.h.removeInstructionBreakpoints(reference, offset);
          } else if (currentElement.element.allowBreakpoint && !currentElement.element.isBreakpointSet) {
            this.h.addInstructionBreakpoint({ instructionReference: reference, offset, address: currentElement.element.address, canPersist: false });
          }
        }
      })
    ];
    return { currentElement, icon: icon2, disposables };
  }
  renderElement(element, index, templateData, height) {
    templateData.currentElement.element = element;
    this.j(templateData.icon, element);
  }
  disposeTemplate(templateData) {
    $Xc(templateData.disposables);
    templateData.disposables = [];
  }
  j(icon2, element) {
    if (element?.address === this.g.focusedCurrentInstructionAddress) {
      icon2.classList.add(this.d);
    } else if (element?.address === this.g.focusedInstructionAddress) {
      icon2.classList.add(this.f);
    } else {
      icon2.classList.remove(this.d);
      icon2.classList.remove(this.f);
    }
    icon2.classList.remove(this.c);
    if (element?.isBreakpointSet) {
      if (element.isBreakpointEnabled) {
        icon2.classList.add(this.a);
        icon2.classList.remove(this.b);
      } else {
        icon2.classList.remove(this.a);
        icon2.classList.add(this.b);
      }
    } else {
      icon2.classList.remove(this.a);
      icon2.classList.remove(this.b);
    }
  }
};
BreakpointRenderer = BreakpointRenderer_1 = __decorate([
  __param(1, $0R)
], BreakpointRenderer);
var InstructionRenderer = class InstructionRenderer2 extends $3c {
  static {
    InstructionRenderer_1 = this;
  }
  static {
    this.TEMPLATE_ID = "instruction";
  }
  static {
    this.a = 25;
  }
  static {
    this.b = 30;
  }
  constructor(g, themeService, h3, j, m, n) {
    super();
    this.g = g;
    this.h = h3;
    this.j = j;
    this.m = m;
    this.n = n;
    this.templateId = InstructionRenderer_1.TEMPLATE_ID;
    this.c = themeService.getColorTheme().getColor($K3b);
    this.f = themeService.getColorTheme().getColor($L3b);
    this.B(themeService.onDidColorThemeChange((e) => {
      this.c = e.getColor($K3b);
      this.f = e.getColor($L3b);
    }));
  }
  renderTemplate(container2) {
    const sourcecode = $bk(container2, $(".sourcecode"));
    const instruction = $bk(container2, $(".instruction"));
    this.y(sourcecode);
    this.y(instruction);
    const currentElement = { element: void 0 };
    const cellDisposable = [];
    const disposables = [
      this.g.onDidChangeStackFrame(() => this.t(instruction, sourcecode, currentElement.element)),
      $aj(sourcecode, "dblclick", () => this.u(currentElement.element?.instruction))
    ];
    return { currentElement, instruction, sourcecode, cellDisposable, disposables };
  }
  renderElement(element, index, templateData, height) {
    this.r(element, index, templateData, height);
  }
  async r(element, index, templateData, height) {
    templateData.currentElement.element = element;
    const instruction = element.instruction;
    templateData.sourcecode.innerText = "";
    const sb = new $cE(1e3);
    if (this.g.isSourceCodeRender && element.showSourceLocation && instruction.location?.path && instruction.line !== void 0) {
      const sourceURI = this.w(instruction);
      if (sourceURI) {
        let textModel = void 0;
        const sourceSB = new $cE(1e4);
        const ref = await this.j.createModelReference(sourceURI);
        if (templateData.currentElement.element !== element) {
          return;
        }
        textModel = ref.object.textEditorModel;
        templateData.cellDisposable.push(ref);
        if (textModel && templateData.currentElement.element === element) {
          let lineNumber = instruction.line;
          while (lineNumber && lineNumber >= 1 && lineNumber <= textModel.getLineCount()) {
            const lineContent = textModel.getLineContent(lineNumber);
            sourceSB.appendString(`  ${lineNumber}: `);
            sourceSB.appendString(lineContent + "\n");
            if (instruction.endLine && lineNumber < instruction.endLine) {
              lineNumber++;
              continue;
            }
            break;
          }
          templateData.sourcecode.innerText = sourceSB.build();
        }
      }
    }
    let spacesToAppend = 10;
    if (instruction.address !== "-1") {
      sb.appendString(instruction.address);
      if (instruction.address.length < InstructionRenderer_1.a) {
        spacesToAppend = InstructionRenderer_1.a - instruction.address.length;
      }
      for (let i2 = 0; i2 < spacesToAppend; i2++) {
        sb.appendString(" ");
      }
    }
    if (instruction.instructionBytes) {
      sb.appendString(instruction.instructionBytes);
      spacesToAppend = 10;
      if (instruction.instructionBytes.length < InstructionRenderer_1.b) {
        spacesToAppend = InstructionRenderer_1.b - instruction.instructionBytes.length;
      }
      for (let i2 = 0; i2 < spacesToAppend; i2++) {
        sb.appendString(" ");
      }
    }
    sb.appendString(instruction.instruction);
    templateData.instruction.innerText = sb.build();
    this.t(templateData.instruction, templateData.sourcecode, element);
  }
  disposeElement(element, index, templateData, height) {
    $Xc(templateData.cellDisposable);
    templateData.cellDisposable = [];
  }
  disposeTemplate(templateData) {
    $Xc(templateData.disposables);
    templateData.disposables = [];
  }
  t(instruction, sourceCode, element) {
    if (element && this.g.currentInstructionAddresses.includes(element.address)) {
      instruction.style.background = this.c?.toString() || "transparent";
    } else if (element?.address === this.g.focusedInstructionAddress) {
      instruction.style.background = this.f?.toString() || "transparent";
    } else {
      instruction.style.background = "transparent";
    }
  }
  u(instruction) {
    if (instruction) {
      const sourceURI = this.w(instruction);
      const selection = instruction.endLine ? {
        startLineNumber: instruction.line,
        endLineNumber: instruction.endLine,
        startColumn: instruction.column || 1,
        endColumn: instruction.endColumn || 1073741824
      } : {
        startLineNumber: instruction.line,
        endLineNumber: instruction.line,
        startColumn: instruction.column || 1,
        endColumn: instruction.endColumn || 1073741824
      };
      this.h.openEditor({
        resource: sourceURI,
        description: localize(6e3, null),
        options: {
          preserveFocus: false,
          selection,
          revealIfOpened: true,
          selectionRevealType: 1,
          pinned: false
        }
      });
    }
  }
  w(instruction) {
    const path = instruction.location.path;
    if (path && $uP(path)) {
      return this.m.asCanonicalUri(URI.parse(path));
    }
    if (path && $mc(path)) {
      return this.m.asCanonicalUri(URI.file(path));
    }
    return $CP(instruction.location, instruction.location.path, this.g.debugSession.getId(), this.m, this.n);
  }
  y(element) {
    $24(element, this.g.fontInfo);
    element.style.whiteSpace = "pre";
  }
};
InstructionRenderer = InstructionRenderer_1 = __decorate([
  __param(1, $gs),
  __param(2, $mJ),
  __param(3, $oG),
  __param(4, $vl),
  __param(5, $wn)
], InstructionRenderer);
var AccessibilityProvider2 = class {
  getWidgetAriaLabel() {
    return localize(6001, null);
  }
  getAriaLabel(element) {
    let label3 = "";
    const instruction = element.instruction;
    if (instruction.address !== "-1") {
      label3 += `${localize(6002, null)}: ${instruction.address}`;
    }
    if (instruction.instructionBytes) {
      label3 += `, ${localize(6003, null)}: ${instruction.instructionBytes}`;
    }
    label3 += `, ${localize(6004, null)}: ${instruction.instruction}`;
    return label3;
  }
};
var $S3b = class $S3b2 {
  constructor(editorService, debugService, contextKeyService) {
    contextKeyService.bufferChangeEvents(() => {
      this.c = $ZR.bindTo(contextKeyService);
    });
    const onDidActiveEditorChangeListener = () => {
      if (this.b) {
        this.b.dispose();
        this.b = void 0;
      }
      const activeTextEditorControl = editorService.activeTextEditorControl;
      if ($P5(activeTextEditorControl)) {
        const language = activeTextEditorControl.getModel()?.getLanguageId();
        this.c?.set(!!language && debugService.getAdapterManager().someDebuggerInterestedInLanguage(language));
        this.b = activeTextEditorControl.onDidChangeModelLanguage((e) => {
          this.c?.set(debugService.getAdapterManager().someDebuggerInterestedInLanguage(e.newLanguage));
        });
      } else {
        this.c?.set(false);
      }
    };
    onDidActiveEditorChangeListener();
    this.a = editorService.onDidActiveEditorChange(onDidActiveEditorChangeListener);
  }
  dispose() {
    this.a.dispose();
    this.b?.dispose();
  }
};
$S3b = __decorate([
  __param(0, $mJ),
  __param(1, $0R),
  __param(2, $on)
], $S3b);

// out-build/vs/workbench/contrib/debug/browser/debugEditorActions.js
var ToggleBreakpointAction = class extends $gJ {
  constructor() {
    super({
      id: "editor.debug.action.toggleBreakpoint",
      title: {
        ...localize2(5819, "Debug: Toggle Breakpoint"),
        mnemonicTitle: localize(5808, null)
      },
      f1: true,
      precondition: $BR,
      keybinding: {
        when: $7m.or(EditorContextKeys.editorTextFocus, $YR),
        primary: 67,
        weight: 100
        /* KeybindingWeight.EditorContrib */
      },
      menu: {
        id: $bJ.MenubarDebugMenu,
        when: $BR,
        group: "4_new_breakpoint",
        order: 1
      }
    });
  }
  async run(accessor) {
    const editorService = accessor.get($mJ);
    const debugService = accessor.get($0R);
    const activePane = editorService.activeEditorPane;
    if (activePane instanceof $R3b) {
      const location3 = activePane.focusedAddressAndOffset;
      if (location3) {
        const bps = debugService.getModel().getInstructionBreakpoints();
        const toRemove = bps.find((bp) => bp.address === location3.address);
        if (toRemove) {
          debugService.removeInstructionBreakpoints(toRemove.instructionReference, toRemove.offset);
        } else {
          debugService.addInstructionBreakpoint({ instructionReference: location3.reference, offset: location3.offset, address: location3.address, canPersist: false });
        }
      }
      return;
    }
    const codeEditorService = accessor.get($U5);
    const editor = codeEditorService.getFocusedCodeEditor() || codeEditorService.getActiveCodeEditor();
    if (editor?.hasModel()) {
      const modelUri = editor.getModel().uri;
      const canSet = debugService.canSetBreakpointsIn(editor.getModel());
      const lineNumbers = [...new Set(editor.getSelections().map((s) => s.getPosition().lineNumber))];
      await Promise.all(lineNumbers.map(async (line) => {
        const bps = debugService.getModel().getBreakpoints({ lineNumber: line, uri: modelUri });
        if (bps.length) {
          await Promise.all(bps.map((bp) => debugService.removeBreakpoints(bp.getId())));
        } else if (canSet) {
          await debugService.addBreakpoints(modelUri, [{ lineNumber: line }]);
        }
      }));
    }
  }
};
var ConditionalBreakpointAction = class extends $Z5 {
  constructor() {
    super({
      id: "editor.debug.action.conditionalBreakpoint",
      label: localize2(5820, "Debug: Add Conditional Breakpoint..."),
      precondition: $BR,
      menuOpts: {
        menuId: $bJ.MenubarNewBreakpointMenu,
        title: localize(5809, null),
        group: "1_breakpoints",
        order: 1,
        when: $BR
      }
    });
  }
  async run(accessor, editor) {
    const debugService = accessor.get($0R);
    const position = editor.getPosition();
    if (position && editor.hasModel() && debugService.canSetBreakpointsIn(editor.getModel())) {
      editor.getContribution($4R)?.showBreakpointWidget(
        position.lineNumber,
        void 0,
        0
        /* BreakpointWidgetContext.CONDITION */
      );
    }
  }
};
var LogPointAction = class extends $Z5 {
  constructor() {
    super({
      id: "editor.debug.action.addLogPoint",
      label: localize2(5821, "Debug: Add Logpoint..."),
      precondition: $BR,
      menuOpts: [
        {
          menuId: $bJ.MenubarNewBreakpointMenu,
          title: localize(5810, null),
          group: "1_breakpoints",
          order: 4,
          when: $BR
        }
      ]
    });
  }
  async run(accessor, editor) {
    const debugService = accessor.get($0R);
    const position = editor.getPosition();
    if (position && editor.hasModel() && debugService.canSetBreakpointsIn(editor.getModel())) {
      editor.getContribution($4R)?.showBreakpointWidget(
        position.lineNumber,
        position.column,
        2
        /* BreakpointWidgetContext.LOG_MESSAGE */
      );
    }
  }
};
var TriggerByBreakpointAction = class extends $Z5 {
  constructor() {
    super({
      id: "editor.debug.action.triggerByBreakpoint",
      label: localize(5811, null),
      precondition: $BR,
      alias: "Debug: Triggered Breakpoint...",
      menuOpts: [
        {
          menuId: $bJ.MenubarNewBreakpointMenu,
          title: localize(5812, null),
          group: "1_breakpoints",
          order: 4,
          when: $BR
        }
      ]
    });
  }
  async run(accessor, editor) {
    const debugService = accessor.get($0R);
    const position = editor.getPosition();
    if (position && editor.hasModel() && debugService.canSetBreakpointsIn(editor.getModel())) {
      editor.getContribution($4R)?.showBreakpointWidget(
        position.lineNumber,
        position.column,
        3
        /* BreakpointWidgetContext.TRIGGER_POINT */
      );
    }
  }
};
var EditBreakpointAction = class extends $Z5 {
  constructor() {
    super({
      id: "editor.debug.action.editBreakpoint",
      label: localize(5813, null),
      alias: "Debug: Edit Existing Breakpoint",
      precondition: $BR,
      menuOpts: {
        menuId: $bJ.MenubarNewBreakpointMenu,
        title: localize(5814, null),
        group: "1_breakpoints",
        order: 1,
        when: $BR
      }
    });
  }
  async run(accessor, editor) {
    const debugService = accessor.get($0R);
    const position = editor.getPosition();
    const debugModel = debugService.getModel();
    if (!(editor.hasModel() && position)) {
      return;
    }
    const lineBreakpoints = debugModel.getBreakpoints({ lineNumber: position.lineNumber });
    if (lineBreakpoints.length === 0) {
      return;
    }
    const breakpointDistances = lineBreakpoints.map((b) => {
      if (!b.column) {
        return position.column;
      }
      return Math.abs(b.column - position.column);
    });
    const closestBreakpointIndex = breakpointDistances.indexOf(Math.min(...breakpointDistances));
    const closestBreakpoint = lineBreakpoints[closestBreakpointIndex];
    editor.getContribution($4R)?.showBreakpointWidget(closestBreakpoint.lineNumber, closestBreakpoint.column);
  }
};
var OpenDisassemblyViewAction = class _OpenDisassemblyViewAction extends $gJ {
  static {
    this.ID = "debug.action.openDisassemblyView";
  }
  constructor() {
    super({
      id: _OpenDisassemblyViewAction.ID,
      title: {
        ...localize2(5822, "Open Disassembly View"),
        mnemonicTitle: localize(5815, null)
      },
      precondition: $1R,
      menu: [
        {
          id: $bJ.EditorContext,
          group: "debug",
          order: 5,
          when: $7m.and($9Q, $eqb.toNegated(), $5Q.isEqualTo("stopped"), EditorContextKeys.editorTextFocus, $XR, $ZR)
        },
        {
          id: $bJ.DebugCallStackContext,
          group: "z_commands",
          order: 50,
          when: $7m.and($9Q, $5Q.isEqualTo("stopped"), $gR.isEqualTo("stackFrame"), $XR)
        },
        {
          id: $bJ.CommandPalette,
          when: $7m.and($9Q, $5Q.isEqualTo("stopped"), $XR)
        }
      ]
    });
  }
  run(accessor) {
    const editorService = accessor.get($mJ);
    editorService.openEditor($IP.instance, { pinned: true, revealIfOpened: true });
  }
};
var ToggleDisassemblyViewSourceCodeAction = class _ToggleDisassemblyViewSourceCodeAction extends $gJ {
  static {
    this.ID = "debug.action.toggleDisassemblyViewSourceCode";
  }
  static {
    this.configID = "debug.disassemblyView.showSourceCode";
  }
  constructor() {
    super({
      id: _ToggleDisassemblyViewSourceCodeAction.ID,
      title: {
        ...localize2(5823, "Toggle Source Code in Disassembly View"),
        mnemonicTitle: localize(5816, null)
      },
      metadata: {
        description: localize2(5824, "Shows or hides source code in disassembly")
      },
      f1: true
    });
  }
  run(accessor, editor, ...args2) {
    const configService = accessor.get($kl);
    if (configService) {
      const value = configService.getValue("debug").disassemblyView.showSourceCode;
      configService.updateValue(_ToggleDisassemblyViewSourceCodeAction.configID, !value);
    }
  }
};
var $Sac = class _$Sac extends $Z5 {
  static {
    this.ID = "editor.debug.action.runToCursor";
  }
  static {
    this.LABEL = localize2(5825, "Run to Cursor");
  }
  constructor() {
    super({
      id: _$Sac.ID,
      label: _$Sac.LABEL.value,
      alias: "Debug: Run to Cursor",
      precondition: $7m.and($BR, $eqb.toNegated(), $7m.or(EditorContextKeys.editorTextFocus, $YR), ChatContextKeys.inChatSession.negate()),
      contextMenuOpts: {
        group: "debug",
        order: 2,
        when: $9Q
      }
    });
  }
  async run(accessor, editor) {
    const position = editor.getPosition();
    if (!(editor.hasModel() && position)) {
      return;
    }
    const uri = editor.getModel().uri;
    const debugService = accessor.get($0R);
    const viewModel = debugService.getViewModel();
    const uriIdentityService = accessor.get($vl);
    let column = void 0;
    const focusedStackFrame = viewModel.focusedStackFrame;
    if (focusedStackFrame && uriIdentityService.extUri.isEqual(focusedStackFrame.source.uri, uri) && focusedStackFrame.range.startLineNumber === position.lineNumber) {
      column = position.column;
    }
    await debugService.runTo(uri, position.lineNumber, column);
  }
};
var $Tac = class _$Tac extends $Z5 {
  static {
    this.ID = "editor.debug.action.selectionToRepl";
  }
  static {
    this.LABEL = localize2(5826, "Evaluate in Debug Console");
  }
  constructor() {
    super({
      id: _$Tac.ID,
      label: _$Tac.LABEL.value,
      alias: "Debug: Evaluate in Console",
      precondition: $7m.and($9Q, EditorContextKeys.editorTextFocus, ChatContextKeys.inChatSession.negate()),
      contextMenuOpts: {
        group: "debug",
        order: 0
      }
    });
  }
  async run(accessor, editor) {
    const debugService = accessor.get($0R);
    const viewsService = accessor.get($uob);
    const viewModel = debugService.getViewModel();
    const session = viewModel.focusedSession;
    if (!editor.hasModel() || !session) {
      return;
    }
    const selection = editor.getSelection();
    let text2;
    if (selection.isEmpty()) {
      text2 = editor.getModel().getLineContent(selection.selectionStartLineNumber).trim();
    } else {
      text2 = editor.getModel().getValueInRange(selection);
    }
    const replView = await viewsService.openView($2Q, false);
    replView?.sendReplInput(text2);
  }
};
var $Uac = class _$Uac extends $Z5 {
  static {
    this.ID = "editor.debug.action.selectionToWatch";
  }
  static {
    this.LABEL = localize2(5827, "Add to Watch");
  }
  constructor() {
    super({
      id: _$Uac.ID,
      label: _$Uac.LABEL.value,
      alias: "Debug: Add to Watch",
      precondition: $7m.and($9Q, EditorContextKeys.editorTextFocus, ChatContextKeys.inChatSession.negate()),
      contextMenuOpts: {
        group: "debug",
        order: 1
      }
    });
  }
  async run(accessor, editor) {
    const debugService = accessor.get($0R);
    const viewsService = accessor.get($uob);
    const languageFeaturesService = accessor.get($mP);
    if (!editor.hasModel()) {
      return;
    }
    let expression = void 0;
    const model = editor.getModel();
    const selection = editor.getSelection();
    if (!selection.isEmpty()) {
      expression = model.getValueInRange(selection);
    } else {
      const position = editor.getPosition();
      const evaluatableExpression = await $tP(languageFeaturesService, model, position);
      if (!evaluatableExpression) {
        return;
      }
      expression = evaluatableExpression.matchingExpression;
    }
    if (!expression) {
      return;
    }
    await viewsService.openView($VQ);
    debugService.addWatchExpression(expression);
  }
};
var ShowDebugHoverAction = class extends $Z5 {
  constructor() {
    super({
      id: "editor.debug.action.showDebugHover",
      label: localize2(5828, "Debug: Show Hover"),
      precondition: $9Q,
      kbOpts: {
        kbExpr: EditorContextKeys.editorTextFocus,
        primary: $$e(
          2048 | 41,
          2048 | 39
          /* KeyCode.KeyI */
        ),
        weight: 100
        /* KeybindingWeight.EditorContrib */
      }
    });
  }
  async run(accessor, editor) {
    const position = editor.getPosition();
    if (!position || !editor.hasModel()) {
      return;
    }
    return editor.getContribution($3R)?.showHover(position, true);
  }
};
var NO_TARGETS_MESSAGE = localize(5817, null);
var StepIntoTargetsAction = class _StepIntoTargetsAction extends $Z5 {
  static {
    this.ID = "editor.debug.action.stepIntoTargets";
  }
  static {
    this.LABEL = localize(5818, null);
  }
  constructor() {
    super({
      id: _StepIntoTargetsAction.ID,
      label: _StepIntoTargetsAction.LABEL,
      alias: "Debug: Step Into Target",
      precondition: $7m.and($zR, $9Q, $5Q.isEqualTo("stopped"), EditorContextKeys.editorTextFocus),
      contextMenuOpts: {
        group: "debug",
        order: 1.5
      }
    });
  }
  async run(accessor, editor) {
    const debugService = accessor.get($0R);
    const contextMenuService = accessor.get($50);
    const uriIdentityService = accessor.get($vl);
    const session = debugService.getViewModel().focusedSession;
    const frame = debugService.getViewModel().focusedStackFrame;
    const selection = editor.getSelection();
    const targetPosition = selection?.getPosition() || frame && { lineNumber: frame.range.startLineNumber, column: frame.range.startColumn };
    if (!session || !frame || !editor.hasModel() || !uriIdentityService.extUri.isEqual(editor.getModel().uri, frame.source.uri)) {
      if (targetPosition) {
        $S_.get(editor)?.showMessage(NO_TARGETS_MESSAGE, targetPosition);
      }
      return;
    }
    const targets = await session.stepInTargets(frame.frameId);
    if (!targets?.length) {
      $S_.get(editor)?.showMessage(NO_TARGETS_MESSAGE, targetPosition);
      return;
    }
    if (selection) {
      const positionalTargets = [];
      for (const target of targets) {
        if (target.line) {
          positionalTargets.push({
            start: new $8C(target.line, target.column || 1),
            end: target.endLine ? new $8C(target.endLine, target.endColumn || 1) : void 0,
            target
          });
        }
      }
      positionalTargets.sort((a, b) => b.start.lineNumber - a.start.lineNumber || b.start.column - a.start.column);
      const needle = selection.getPosition();
      const best = positionalTargets.find((t) => t.end && needle.isBefore(t.end) && t.start.isBeforeOrEqual(needle)) || positionalTargets.find((t) => t.end === void 0 && t.start.isBeforeOrEqual(needle));
      if (best) {
        session.stepIn(frame.thread.threadId, best.target.id);
        return;
      }
    }
    editor.revealLineInCenterIfOutsideViewport(frame.range.startLineNumber);
    const cursorCoords = editor.getScrolledVisiblePosition(targetPosition);
    const editorCoords = $vj(editor.getDomNode());
    const x = editorCoords.left + cursorCoords.left;
    const y = editorCoords.top + cursorCoords.top + cursorCoords.height;
    contextMenuService.showContextMenu({
      getAnchor: () => ({ x, y }),
      getActions: () => {
        return targets.map((t) => new $Um(`stepIntoTarget:${t.id}`, t.label, void 0, true, () => session.stepIn(frame.thread.threadId, t.id)));
      }
    });
  }
};
var GoToBreakpointAction = class extends $Z5 {
  constructor(d, opts) {
    super(opts);
    this.d = d;
  }
  async run(accessor, editor) {
    const debugService = accessor.get($0R);
    const editorService = accessor.get($mJ);
    const uriIdentityService = accessor.get($vl);
    if (editor.hasModel()) {
      const currentUri = editor.getModel().uri;
      const currentLine = editor.getPosition().lineNumber;
      const allEnabledBreakpoints = debugService.getModel().getBreakpoints({ enabledOnly: true });
      let moveBreakpoint = this.d ? allEnabledBreakpoints.filter((bp) => uriIdentityService.extUri.isEqual(bp.uri, currentUri) && bp.lineNumber > currentLine).shift() : allEnabledBreakpoints.filter((bp) => uriIdentityService.extUri.isEqual(bp.uri, currentUri) && bp.lineNumber < currentLine).pop();
      if (!moveBreakpoint) {
        moveBreakpoint = this.d ? allEnabledBreakpoints.filter((bp) => bp.uri.toString() > currentUri.toString()).shift() : allEnabledBreakpoints.filter((bp) => bp.uri.toString() < currentUri.toString()).pop();
      }
      if (!moveBreakpoint && allEnabledBreakpoints.length) {
        moveBreakpoint = this.d ? allEnabledBreakpoints[0] : allEnabledBreakpoints[allEnabledBreakpoints.length - 1];
      }
      if (moveBreakpoint) {
        return $V3b(moveBreakpoint, false, true, false, debugService, editorService);
      }
    }
  }
};
var GoToNextBreakpointAction = class extends GoToBreakpointAction {
  constructor() {
    super(true, {
      id: "editor.debug.action.goToNextBreakpoint",
      label: localize2(5829, "Debug: Go to Next Breakpoint"),
      precondition: $BR
    });
  }
};
var GoToPreviousBreakpointAction = class extends GoToBreakpointAction {
  constructor() {
    super(false, {
      id: "editor.debug.action.goToPreviousBreakpoint",
      label: localize2(5830, "Debug: Go to Previous Breakpoint"),
      precondition: $BR
    });
  }
};
var CloseExceptionWidgetAction = class extends $Z5 {
  constructor() {
    super({
      id: "editor.debug.action.closeExceptionWidget",
      label: localize2(5831, "Close Exception Widget"),
      precondition: $UR,
      kbOpts: {
        primary: 9,
        weight: 100
        /* KeybindingWeight.EditorContrib */
      }
    });
  }
  async run(_accessor, editor) {
    const contribution = editor.getContribution($3R);
    contribution?.closeExceptionWidget();
  }
};
$hJ(OpenDisassemblyViewAction);
$hJ(ToggleDisassemblyViewSourceCodeAction);
$hJ(ToggleBreakpointAction);
$55(ConditionalBreakpointAction);
$55(LogPointAction);
$55(TriggerByBreakpointAction);
$55(EditBreakpointAction);
$55($Sac);
$55(StepIntoTargetsAction);
$55($Tac);
$55($Uac);
$55(ShowDebugHoverAction);
$55(GoToNextBreakpointAction);
$55(GoToPreviousBreakpointAction);
$55(CloseExceptionWidgetAction);

// out-build/vs/workbench/contrib/debug/browser/variablesView.js
var $Xac_1;
var $Yac_1;
var $140 = $;
var forgetScopes = true;
var variableInternalContext;
var dataBreakpointInfoResponse;
var $Vac = class $Vac2 extends $_ob {
  constructor(options3, contextMenuService, h3, keybindingService, configurationService, instantiationService, viewDescriptorService, contextKeyService, openerService, themeService, telemetryService, hoverService, j) {
    super(options3, keybindingService, contextMenuService, configurationService, contextKeyService, viewDescriptorService, instantiationService, openerService, themeService, telemetryService, hoverService);
    this.h = h3;
    this.j = j;
    this.b = false;
    this.f = /* @__PURE__ */ new Map();
    this.g = /* @__PURE__ */ new Set();
    this.a = new $8h(async () => {
      const stackFrame = this.h.getViewModel().focusedStackFrame;
      this.b = false;
      const input = this.c.getInput();
      if (input) {
        this.f.set(input.getId(), this.c.getViewState());
      }
      if (!stackFrame) {
        await this.c.setInput(null);
        return;
      }
      const viewState = this.f.get(stackFrame.getId());
      await this.c.setInput(stackFrame, viewState);
      const scopes = await stackFrame.getScopes();
      const toExpand = scopes.find((s) => !s.expensive);
      if (toExpand && this.c.hasNode(toExpand)) {
        this.g.add(toExpand.getId());
        await this.c.expand(toExpand);
      }
    }, 400);
  }
  W(container2) {
    super.W(container2);
    this.element.classList.add("debug-pane");
    container2.classList.add("debug-variables");
    const treeContainer = $q4b(container2);
    const expressionRenderer = this.Db.createInstance($D5b);
    this.c = this.Db.createInstance($4eb, "VariablesView", treeContainer, new VariablesDelegate(), [
      this.Db.createInstance($Yac, expressionRenderer),
      this.Db.createInstance($Xac, expressionRenderer),
      new ScopesRenderer(),
      new ScopeErrorRenderer()
    ], this.Db.createInstance(VariablesDataSource), {
      accessibilityProvider: new VariablesAccessibilityProvider(),
      identityProvider: { getId: (element) => element.getId() },
      keyboardNavigationLabelProvider: { getKeyboardNavigationLabel: (e) => e.name },
      overrideStyles: this.Xb().listOverrideStyles
    });
    this.B($Xac.rendererOnVisualizationRange(this.h.getViewModel(), this.c));
    this.c.setInput(this.h.getViewModel().focusedStackFrame ?? null);
    $dR.bindTo(this.c.contextKeyService);
    this.B(this.h.getViewModel().onDidFocusStackFrame((sf) => {
      if (!this.isBodyVisible()) {
        this.b = true;
        return;
      }
      const timeout = sf.explicit ? 0 : void 0;
      this.a.schedule(timeout);
    }));
    this.B(this.h.getViewModel().onWillUpdateViews(() => {
      const stackFrame = this.h.getViewModel().focusedStackFrame;
      if (stackFrame && forgetScopes) {
        stackFrame.forgetScopes();
      }
      forgetScopes = true;
      this.c.updateChildren();
    }));
    this.B(this.c);
    this.B(this.c.onMouseDblClick((e) => this.r(e)));
    this.B(this.c.onContextMenu(async (e) => await this.L(e)));
    this.B(this.onDidChangeBodyVisibility((visible) => {
      if (visible && this.b) {
        this.a.schedule();
      }
    }));
    let horizontalScrolling;
    this.B(this.h.getViewModel().onDidSelectExpression((e) => {
      const variable = e?.expression;
      if (variable && this.c.hasNode(variable)) {
        horizontalScrolling = this.c.options.horizontalScrolling;
        if (horizontalScrolling) {
          this.c.updateOptions({ horizontalScrolling: false });
        }
        this.c.rerender(variable);
      } else if (!e && horizontalScrolling !== void 0) {
        this.c.updateOptions({ horizontalScrolling });
        horizontalScrolling = void 0;
      }
    }));
    this.B(this.h.getViewModel().onDidEvaluateLazyExpression(async (e) => {
      if (e instanceof $MP && this.c.hasNode(e)) {
        await this.c.updateChildren(e, false, true);
        await this.c.expand(e);
      }
    }));
    this.B(this.h.onDidEndSession(() => {
      this.f.clear();
      this.g.clear();
    }));
  }
  X(width2, height) {
    super.X(height, width2);
    this.c.layout(width2, height);
  }
  focus() {
    super.focus();
    this.c.domFocus();
  }
  collapseAll() {
    this.c.collapseAll();
  }
  r(e) {
    if (this.t(e.element)) {
      this.h.getViewModel().setSelectedExpression(e.element, false);
    }
  }
  t(e) {
    const session = this.h.getViewModel().focusedSession;
    if (!session) {
      return false;
    }
    if (e instanceof $KP) {
      return !!e.treeItem.canEdit;
    }
    return e instanceof $MP && !e.presentationHint?.attributes?.includes("readOnly") && !e.presentationHint?.lazy;
  }
  async L(e) {
    const variable = e.element;
    if (!(variable instanceof $MP) || !variable.value) {
      return;
    }
    return $Wac(this.Bb, this.j, this.zb, $bJ.DebugVariablesContext, e);
  }
};
$Vac = __decorate([
  __param(1, $50),
  __param(2, $0R),
  __param(3, $Ty),
  __param(4, $kl),
  __param(5, $Pk),
  __param(6, $$M),
  __param(7, $on),
  __param(8, $O4),
  __param(9, $gs),
  __param(10, $zv),
  __param(11, $5$),
  __param(12, $cJ)
], $Vac);
async function $Wac(parentContextKeyService, menuService, contextMenuService, menuId, e) {
  const variable = e.element;
  if (!(variable instanceof $MP) || !variable.value) {
    return;
  }
  const contextKeyService = await getContextForVariableMenuWithDataAccess(parentContextKeyService, variable);
  const context = getVariablesContext(variable);
  const menu = menuService.getMenuActions(menuId, contextKeyService, { arg: context, shouldForwardArgs: false });
  const { secondary } = $O$(menu, "inline");
  contextMenuService.showContextMenu({
    getAnchor: () => e.anchor,
    getActions: () => secondary
  });
}
var getVariablesContext = (variable) => ({
  sessionId: variable.getSession()?.getId(),
  container: variable.parent instanceof $LP ? { expression: variable.parent.name } : variable.parent.toDebugProtocolObject(),
  variable: variable.toDebugProtocolObject()
});
async function getContextForVariableMenuWithDataAccess(parentContext, variable) {
  const session = variable.getSession();
  if (!session || !session.capabilities.supportsDataBreakpoints) {
    return getContextForVariableMenuBase(parentContext, variable);
  }
  const contextKeys = [];
  dataBreakpointInfoResponse = await session.dataBreakpointInfo(variable.name, variable.parent.reference);
  const dataBreakpointId = dataBreakpointInfoResponse?.dataId;
  const dataBreakpointAccessTypes = dataBreakpointInfoResponse?.accessTypes;
  if (!dataBreakpointAccessTypes) {
    contextKeys.push([$HR.key, !!dataBreakpointId]);
  } else {
    for (const accessType of dataBreakpointAccessTypes) {
      switch (accessType) {
        case "read":
          contextKeys.push([$JR.key, !!dataBreakpointId]);
          break;
        case "write":
          contextKeys.push([$HR.key, !!dataBreakpointId]);
          break;
        case "readWrite":
          contextKeys.push([$IR.key, !!dataBreakpointId]);
          break;
      }
    }
  }
  return getContextForVariableMenuBase(parentContext, variable, contextKeys);
}
function getContextForVariableMenuBase(parentContext, variable, additionalContext = []) {
  variableInternalContext = variable;
  return $EP(parentContext, variable, additionalContext);
}
function isStackFrame(obj) {
  return obj instanceof $PP;
}
var VariablesDataSource = class extends $r4b {
  hasChildren(element) {
    if (!element) {
      return false;
    }
    if (isStackFrame(element)) {
      return true;
    }
    return element.hasChildren;
  }
  c(element) {
    if (isStackFrame(element)) {
      return element.getScopes();
    }
    return element.getChildren();
  }
};
var VariablesDelegate = class {
  getHeight(element) {
    return 22;
  }
  getTemplateId(element) {
    if (element instanceof $OP) {
      return ScopeErrorRenderer.ID;
    }
    if (element instanceof $NP) {
      return ScopesRenderer.ID;
    }
    if (element instanceof $KP) {
      return $Xac.ID;
    }
    return $Yac.ID;
  }
};
var ScopesRenderer = class _ScopesRenderer {
  static {
    this.ID = "scope";
  }
  get templateId() {
    return _ScopesRenderer.ID;
  }
  renderTemplate(container2) {
    const name = $bk(container2, $140(".scope"));
    const label3 = new $S2(name);
    return { name, label: label3 };
  }
  renderElement(element, index, templateData) {
    templateData.label.set(element.element.name, $Ul(element.filterData));
  }
  disposeTemplate(templateData) {
    templateData.label.dispose();
  }
};
var ScopeErrorRenderer = class _ScopeErrorRenderer {
  static {
    this.ID = "scopeError";
  }
  get templateId() {
    return _ScopeErrorRenderer.ID;
  }
  renderTemplate(container2) {
    const wrapper = $bk(container2, $140(".scope"));
    const error = $bk(wrapper, $140(".error"));
    return { error };
  }
  renderElement(element, index, templateData) {
    templateData.error.innerText = element.element.name;
  }
  disposeTemplate() {
  }
};
var $Xac = class $Xac2 extends $s4b {
  static {
    $Xac_1 = this;
  }
  static {
    this.ID = "viz";
  }
  /**
   * Registers a helper that rerenders the tree when visualization is requested
   * or cancelled./
   */
  static rendererOnVisualizationRange(model, tree) {
    return model.onDidChangeVisualization(({ original }) => {
      if (!tree.hasNode(original)) {
        return;
      }
      const parent = tree.getParentElement(original);
      tree.updateChildren(parent, false, false);
    });
  }
  constructor(i2, debugService, contextViewService, hoverService, j, k) {
    super(debugService, contextViewService, hoverService);
    this.i = i2;
    this.j = j;
    this.k = k;
  }
  get templateId() {
    return $Xac_1.ID;
  }
  renderElement(node, index, data) {
    data.elementDisposable.clear();
    super.d(node.element, node, data);
  }
  f(expression, data, highlights) {
    const viz = expression;
    let text2 = viz.name;
    if (viz.value && typeof viz.name === "string") {
      text2 += ":";
    }
    data.label.set(text2, highlights, viz.name);
    data.elementDisposable.add(this.i.renderValue(data.value, viz, {
      showChanged: false,
      maxValueLength: 1024,
      colorize: true,
      session: expression.getSession()
    }));
  }
  g(expression) {
    const viz = expression;
    return {
      initialValue: expression.value,
      ariaLabel: localize(6078, null),
      validationOptions: {
        validation: () => viz.errorMessage ? { content: viz.errorMessage } : null
      },
      onFinish: (value, success) => {
        viz.errorMessage = void 0;
        if (success) {
          viz.edit(value).then(() => {
            forgetScopes = false;
            this.a.getViewModel().updateViews();
          });
        }
      }
    };
  }
  h(actionBar, expression, _data) {
    const viz = expression;
    const contextKeyService = viz.original ? getContextForVariableMenuBase(this.k, viz.original) : this.k;
    const context = viz.original ? getVariablesContext(viz.original) : void 0;
    const menu = this.j.getMenuActions($bJ.DebugVariablesContext, contextKeyService, { arg: context, shouldForwardArgs: false });
    const { primary } = $O$(menu, "inline");
    if (viz.original) {
      const action = new $Um("debugViz", localize(6079, null), ThemeIcon.asClassName($6l.eye), true, () => this.a.getViewModel().setVisualizedExpression(viz.original, void 0));
      action.checked = true;
      primary.push(action);
      actionBar.domNode.style.display = "initial";
    }
    actionBar.clear();
    actionBar.context = context;
    actionBar.push(primary, { icon: true, label: false });
  }
};
$Xac = $Xac_1 = __decorate([
  __param(1, $0R),
  __param(2, $40),
  __param(3, $5$),
  __param(4, $cJ),
  __param(5, $on)
], $Xac);
var $Yac = class $Yac2 extends $s4b {
  static {
    $Yac_1 = this;
  }
  static {
    this.ID = "variable";
  }
  constructor(i2, j, k, l, m, debugService, contextViewService, hoverService) {
    super(debugService, contextViewService, hoverService);
    this.i = i2;
    this.j = j;
    this.k = k;
    this.l = l;
    this.m = m;
  }
  get templateId() {
    return $Yac_1.ID;
  }
  f(expression, data, highlights) {
    data.elementDisposable.add(this.i.renderVariable(data, expression, {
      highlights,
      showChanged: true
    }));
  }
  renderElement(node, index, data) {
    data.elementDisposable.clear();
    super.d(node.element, node, data);
  }
  g(expression) {
    const variable = expression;
    return {
      initialValue: expression.value,
      ariaLabel: localize(6080, null),
      validationOptions: {
        validation: () => variable.errorMessage ? { content: variable.errorMessage } : null
      },
      onFinish: (value, success) => {
        variable.errorMessage = void 0;
        const focusedStackFrame = this.a.getViewModel().focusedStackFrame;
        if (success && variable.value !== value && focusedStackFrame) {
          variable.setVariable(value, focusedStackFrame).then(() => {
            forgetScopes = false;
            this.a.getViewModel().updateViews();
          });
        }
      }
    };
  }
  h(actionBar, expression, data) {
    const variable = expression;
    const contextKeyService = getContextForVariableMenuBase(this.k, variable);
    const context = getVariablesContext(variable);
    const menu = this.j.getMenuActions($bJ.DebugVariablesContext, contextKeyService, { arg: context, shouldForwardArgs: false });
    const { primary } = $O$(menu, "inline");
    actionBar.clear();
    actionBar.context = context;
    actionBar.push(primary, { icon: true, label: false });
    const cts = new $ad();
    data.elementDisposable.add($1c(() => cts.dispose(true)));
    this.l.getApplicableFor(expression, cts.token).then((result) => {
      data.elementDisposable.add(result);
      const originalExpression = expression instanceof $KP && expression.original || expression;
      const actions = result.object.map((v) => new $Um("debugViz", v.name, v.iconClass || "debug-viz-icon", void 0, this.t(v, originalExpression, cts.token)));
      if (actions.length === 0) {
      } else if (actions.length === 1) {
        actionBar.push(actions[0], { icon: true, label: false });
      } else {
        actionBar.push(new $Um("debugViz", localize(6081, null), ThemeIcon.asClassName($6l.eye), void 0, () => this.q(actions, originalExpression, data)), { icon: true, label: false });
      }
    });
  }
  q(actions, expression, data) {
    this.m.showContextMenu({
      getAnchor: () => data.actionBar.getContainer(),
      getActions: () => actions
    });
  }
  t(viz, expression, token) {
    return async () => {
      const resolved = await viz.resolve(token);
      if (token.isCancellationRequested) {
        return;
      }
      if (resolved.type === 0) {
        viz.execute();
      } else {
        const replacement = await this.l.getVisualizedNodeFor(resolved.id, expression);
        if (replacement) {
          this.a.getViewModel().setVisualizedExpression(expression, replacement);
        }
      }
    };
  }
};
$Yac = $Yac_1 = __decorate([
  __param(1, $cJ),
  __param(2, $on),
  __param(3, $FP),
  __param(4, $50),
  __param(5, $0R),
  __param(6, $40),
  __param(7, $5$)
], $Yac);
var VariablesAccessibilityProvider = class {
  getWidgetAriaLabel() {
    return localize(6082, null);
  }
  getAriaLabel(element) {
    if (element instanceof $NP) {
      return localize(6083, null, element.name);
    }
    if (element instanceof $MP) {
      return localize(6084, null, element.name, element.value);
    }
    return null;
  }
};
var $Zac = "debug.setVariable";
$tn.registerCommand({
  id: $Zac,
  handler: (accessor) => {
    const debugService = accessor.get($0R);
    debugService.getViewModel().setSelectedExpression(variableInternalContext, false);
  }
});
$tn.registerCommand({
  metadata: {
    description: $x5b
  },
  id: $$4b,
  handler: async (accessor, arg, ctx) => {
    const debugService = accessor.get($0R);
    const clipboardService = accessor.get($30);
    let elementContext = "";
    let elements;
    if (arg instanceof $MP || arg instanceof $LP) {
      elementContext = "watch";
      elements = ctx ? ctx : [];
    } else {
      elementContext = "variables";
      elements = variableInternalContext ? [variableInternalContext] : [];
    }
    const stackFrame = debugService.getViewModel().focusedStackFrame;
    const session = debugService.getViewModel().focusedSession;
    if (!stackFrame || !session || elements.length === 0) {
      return;
    }
    const evalContext = session.capabilities.supportsClipboardContext ? "clipboard" : elementContext;
    const toEvaluate = elements.map((element) => element instanceof $MP ? element.evaluateName || element.value : element.name);
    try {
      const evaluations = await Promise.all(toEvaluate.map((expr) => session.evaluate(expr, stackFrame.frameId, evalContext)));
      const result = $Mb(evaluations).map((evaluation) => evaluation.body.result);
      if (result.length) {
        clipboardService.writeText(result.join("\n"));
      }
    } catch (e) {
      const result = elements.map((element) => element.value);
      clipboardService.writeText(result.join("\n"));
    }
  }
});
var $1ac = "workbench.debug.viewlet.action.viewMemory";
var HEX_EDITOR_EXTENSION_ID = "ms-vscode.hexeditor";
var HEX_EDITOR_EDITOR_ID = "hexEditor.hexedit";
$tn.registerCommand({
  id: $1ac,
  handler: async (accessor, arg, ctx) => {
    const debugService = accessor.get($0R);
    let sessionId;
    let memoryReference;
    if ("sessionId" in arg) {
      if (!arg.sessionId || !arg.variable.memoryReference) {
        return;
      }
      sessionId = arg.sessionId;
      memoryReference = arg.variable.memoryReference;
    } else {
      if (!arg.memoryReference) {
        return;
      }
      const focused = debugService.getViewModel().focusedSession;
      if (!focused) {
        return;
      }
      sessionId = focused.getId();
      memoryReference = arg.memoryReference;
    }
    const extensionsWorkbenchService = accessor.get($vzb);
    const editorService = accessor.get($mJ);
    const notificationService = accessor.get($PJ);
    const extensionService = accessor.get($wN);
    const telemetryService = accessor.get($zv);
    const ext = await extensionService.getExtension(HEX_EDITOR_EXTENSION_ID);
    if (ext || await tryInstallHexEditor(extensionsWorkbenchService, notificationService)) {
      telemetryService.publicLog("debug/didViewMemory", {
        debugType: debugService.getModel().getSession(sessionId)?.configuration.type
      });
      await editorService.openEditor({
        resource: $RP(sessionId, memoryReference),
        options: {
          revealIfOpened: true,
          override: HEX_EDITOR_EDITOR_ID
        }
      }, $oJ);
    }
  }
});
async function tryInstallHexEditor(extensionsWorkbenchService, notificationService) {
  try {
    await extensionsWorkbenchService.install(
      HEX_EDITOR_EXTENSION_ID,
      {
        justification: localize(6085, null),
        enable: true
      },
      15
      /* ProgressLocation.Notification */
    );
    return true;
  } catch (error) {
    notificationService.error(error);
    return false;
  }
}
var $2ac = "debug.breakWhenValueChanges";
$tn.registerCommand({
  id: $2ac,
  handler: async (accessor) => {
    const debugService = accessor.get($0R);
    if (dataBreakpointInfoResponse) {
      await debugService.addDataBreakpoint({ description: dataBreakpointInfoResponse.description, src: { type: 0, dataId: dataBreakpointInfoResponse.dataId }, canPersist: !!dataBreakpointInfoResponse.canPersist, accessTypes: dataBreakpointInfoResponse.accessTypes, accessType: "write" });
    }
  }
});
var $3ac = "debug.breakWhenValueIsAccessed";
$tn.registerCommand({
  id: $3ac,
  handler: async (accessor) => {
    const debugService = accessor.get($0R);
    if (dataBreakpointInfoResponse) {
      await debugService.addDataBreakpoint({ description: dataBreakpointInfoResponse.description, src: { type: 0, dataId: dataBreakpointInfoResponse.dataId }, canPersist: !!dataBreakpointInfoResponse.canPersist, accessTypes: dataBreakpointInfoResponse.accessTypes, accessType: "readWrite" });
    }
  }
});
var $4ac = "debug.breakWhenValueIsRead";
$tn.registerCommand({
  id: $4ac,
  handler: async (accessor) => {
    const debugService = accessor.get($0R);
    if (dataBreakpointInfoResponse) {
      await debugService.addDataBreakpoint({ description: dataBreakpointInfoResponse.description, src: { type: 0, dataId: dataBreakpointInfoResponse.dataId }, canPersist: !!dataBreakpointInfoResponse.canPersist, accessTypes: dataBreakpointInfoResponse.accessTypes, accessType: "read" });
    }
  }
});
$tn.registerCommand({
  metadata: {
    description: $w5b
  },
  id: $04b,
  handler: async (accessor, context) => {
    const clipboardService = accessor.get($30);
    await clipboardService.writeText(context.variable.evaluateName);
  }
});
$tn.registerCommand({
  metadata: {
    description: $y5b
  },
  id: $94b,
  handler: async (accessor, context) => {
    const debugService = accessor.get($0R);
    debugService.addWatchExpression(context.variable.evaluateName);
  }
});
$hJ(class extends $cpb {
  constructor() {
    super({
      id: "variables.collapse",
      viewId: $UQ,
      title: localize(6086, null),
      f1: false,
      icon: $6l.collapseAll,
      menu: {
        id: $bJ.ViewTitle,
        group: "navigation",
        when: $7m.equals("view", $UQ)
      }
    });
  }
  runInView(_accessor, view) {
    view.collapseAll();
  }
});

// out-build/vs/workbench/contrib/debug/browser/debugHover.js
var $6ac_1;
var $141 = $;
var ShowDebugHoverResult;
(function(ShowDebugHoverResult2) {
  ShowDebugHoverResult2[ShowDebugHoverResult2["NOT_CHANGED"] = 0] = "NOT_CHANGED";
  ShowDebugHoverResult2[ShowDebugHoverResult2["NOT_AVAILABLE"] = 1] = "NOT_AVAILABLE";
  ShowDebugHoverResult2[ShowDebugHoverResult2["CANCELLED"] = 2] = "CANCELLED";
})(ShowDebugHoverResult || (ShowDebugHoverResult = {}));
async function doFindExpression(container2, namesToFind) {
  if (!container2) {
    return null;
  }
  const children = await container2.getChildren();
  const filtered = children.filter((v) => namesToFind[0] === v.name);
  if (filtered.length !== 1) {
    return null;
  }
  if (namesToFind.length === 1) {
    return filtered[0];
  } else {
    return doFindExpression(filtered[0], namesToFind.slice(1));
  }
}
async function $5ac(stackFrame, namesToFind) {
  const scopes = await stackFrame.getScopes();
  const nonExpensive = scopes.filter((s) => !s.expensive);
  const expressions = $Mb(await Promise.all(nonExpensive.map((scope) => doFindExpression(scope, namesToFind))));
  return expressions.length > 0 && expressions.every((e) => e.value === expressions[0].value) ? expressions[0] : void 0;
}
var $6ac = class $6ac2 {
  static {
    $6ac_1 = this;
  }
  static {
    this.ID = "debug.hoverWidget";
  }
  get isShowingComplexValue() {
    return this.j?.hidden === false;
  }
  constructor(u, w, z, A, B, C) {
    this.u = u;
    this.w = w;
    this.z = z;
    this.A = A;
    this.B = B;
    this.C = C;
    this.allowEditorOverflow = true;
    this.i = this.u.createDecorationsCollection();
    this.t = false;
    this.n = [];
    this.g = null;
    this.h = [
      1,
      2
      /* ContentWidgetPositionPreference.BELOW */
    ];
    this.p = this.z.createInstance(DebugHoverComputer, this.u);
    this.q = this.z.createInstance($D5b);
  }
  D() {
    this.d = $141(".debug-hover-widget");
    this.j = $bk(this.d, $141(".complex-value"));
    this.k = $bk(this.j, $141(".title"));
    this.m = $bk(this.j, $141(".debug-hover-tree"));
    this.m.setAttribute("role", "tree");
    const tip = $bk(this.j, $141(".tip"));
    tip.textContent = localize(5834, null, $m ? "Option" : "Alt");
    const dataSource = this.z.createInstance(DebugHoverDataSource);
    this.f = this.z.createInstance($4eb, "DebugHover", this.m, new DebugHoverDelegate(), [
      this.z.createInstance($Yac, this.q),
      this.z.createInstance($Xac, this.q)
    ], dataSource, {
      accessibilityProvider: new DebugHoverAccessibilityProvider(),
      mouseSupport: false,
      horizontalScrolling: true,
      useShadows: false,
      keyboardNavigationLabelProvider: { getKeyboardNavigationLabel: (e) => e.name },
      overrideStyles: {
        listBackground: $jp
      }
    });
    this.n.push($Xac.rendererOnVisualizationRange(this.w.getViewModel(), this.f));
    this.l = $141(".value");
    this.l.tabIndex = 0;
    this.l.setAttribute("role", "tooltip");
    this.o = new $CZ(this.l, {
      horizontal: 2
      /* ScrollbarVisibility.Hidden */
    });
    this.d.appendChild(this.o.getDomNode());
    this.n.push(this.o);
    this.u.applyFontInfo(this.d);
    this.d.style.backgroundColor = $Zn($jp);
    this.d.style.border = `1px solid ${$Zn($lp)}`;
    this.d.style.color = $Zn($kp);
    this.n.push(this.f.onContextMenu(async (e) => await this.E(e)));
    this.n.push(this.f.onDidChangeContentHeight(() => {
      if (!this.t) {
        this.I();
      }
    }));
    this.n.push(this.f.onDidChangeContentWidth(() => {
      if (!this.t) {
        this.I();
      }
    }));
    this.F();
    this.u.addContentWidget(this);
  }
  async E(e) {
    const variable = e.element;
    if (!(variable instanceof $MP) || !variable.value) {
      return;
    }
    return $Wac(this.B, this.A, this.C, $bJ.DebugHoverContext, e);
  }
  F() {
    this.n.push($aj(this.d, "keydown", (e) => {
      if (e.equals(
        9
        /* KeyCode.Escape */
      )) {
        this.hide();
      }
    }));
    this.n.push(this.u.onDidChangeConfiguration((e) => {
      if (e.hasChanged(
        52
        /* EditorOption.fontInfo */
      )) {
        this.u.applyFontInfo(this.d);
      }
    }));
    this.n.push(this.w.getViewModel().onDidEvaluateLazyExpression(async (e) => {
      if (e instanceof $MP && this.f.hasNode(e)) {
        await this.f.updateChildren(e, false, true);
        await this.f.expand(e);
      }
    }));
  }
  isHovered() {
    return !!this.d?.matches(":hover");
  }
  isVisible() {
    return !!this.a;
  }
  willBeVisible() {
    return !!this.c;
  }
  getId() {
    return $6ac_1.ID;
  }
  getDomNode() {
    return this.d;
  }
  /**
   * Gets whether the given coordinates are in the safe triangle formed from
   * the position at which the hover was initiated.
   */
  isInSafeTriangle(x, y) {
    return this.a && !!this.b?.contains(x, y);
  }
  async showAt(position, focus, mouseEvent) {
    this.c?.dispose(true);
    const cancellationSource = this.c = new $ad();
    const session = this.w.getViewModel().focusedSession;
    if (!session || !this.u.hasModel()) {
      this.hide();
      return 1;
    }
    const result = await this.p.compute(position, cancellationSource.token);
    if (cancellationSource.token.isCancellationRequested) {
      this.hide();
      return 2;
    }
    if (!result.range) {
      this.hide();
      return 1;
    }
    if (this.isVisible() && !result.rangeChanged) {
      return 0;
    }
    const expression = await this.p.evaluate(session);
    if (cancellationSource.token.isCancellationRequested) {
      this.hide();
      return 2;
    }
    if (!expression || expression instanceof $LP && !expression.available) {
      this.hide();
      return 1;
    }
    this.i.set([{
      range: result.range,
      options: $6ac_1.G
    }]);
    return this.H(session, result.range.getStartPosition(), expression, focus, mouseEvent);
  }
  static {
    this.G = $WI.register({
      description: "bdebug-hover-highlight",
      className: "hoverHighlight"
    });
  }
  async H(session, position, expression, focus, mouseEvent) {
    if (!this.d) {
      this.D();
    }
    this.g = position;
    const store = new $2c();
    this.a = { store };
    if (!expression.hasChildren) {
      this.j.hidden = true;
      this.l.hidden = false;
      store.add(this.q.renderValue(this.l, expression, {
        showChanged: false,
        colorize: true,
        hover: false,
        session
      }));
      this.l.title = "";
      this.u.layoutContentWidget(this);
      this.b = mouseEvent && new $Gk(mouseEvent.posx, mouseEvent.posy, this.d);
      this.o.scanDomNode();
      if (focus) {
        this.u.render();
        this.l.focus();
      }
      return void 0;
    }
    this.l.hidden = true;
    this.r = expression;
    store.add(this.q.renderValue(this.k, expression, { hover: false, session }));
    this.u.layoutContentWidget(this);
    this.b = mouseEvent && new $Gk(mouseEvent.posx, mouseEvent.posy, this.d);
    this.f.scrollTop = 0;
    this.f.scrollLeft = 0;
    this.j.hidden = false;
    if (focus) {
      this.u.render();
      this.f.domFocus();
    }
  }
  I() {
    this.J();
    this.u.layoutContentWidget(this);
  }
  J() {
    const scrollBarHeight = 10;
    let maxHeightToAvoidCursorOverlay = Infinity;
    if (this.g) {
      const editorTop = this.u.getDomNode()?.offsetTop || 0;
      const containerTop = this.m.offsetTop + editorTop;
      const hoveredCharTop = this.u.getTopForLineNumber(this.g.lineNumber, true) - this.u.getScrollTop();
      if (containerTop < hoveredCharTop) {
        maxHeightToAvoidCursorOverlay = hoveredCharTop + editorTop - 22;
      }
    }
    const treeHeight = Math.min(Math.max(266, this.u.getLayoutInfo().height * 0.55), this.f.contentHeight + scrollBarHeight, maxHeightToAvoidCursorOverlay);
    const realTreeWidth = this.f.contentWidth;
    const treeWidth = $4i(realTreeWidth, 400, 550);
    this.f.layout(treeHeight, treeWidth);
    this.m.style.height = `${treeHeight}px`;
    this.o.scanDomNode();
  }
  beforeRender() {
    if (this.r) {
      const expression = this.r;
      this.r = void 0;
      this.t = true;
      this.f.setInput(expression).finally(() => {
        this.t = false;
      });
    }
    return null;
  }
  afterRender(positionPreference) {
    if (positionPreference) {
      this.h = [positionPreference];
    }
  }
  hide() {
    if (this.c) {
      this.c.dispose(true);
      this.c = void 0;
    }
    if (!this.a) {
      return;
    }
    if ($Nj(this.d)) {
      this.u.focus();
    }
    this.a.store.dispose();
    this.a = void 0;
    this.i.clear();
    this.u.layoutContentWidget(this);
    this.h = [
      1,
      2
      /* ContentWidgetPositionPreference.BELOW */
    ];
  }
  getPosition() {
    return this.a ? {
      position: this.g,
      preference: this.h
    } : null;
  }
  dispose() {
    this.n = $Xc(this.n);
  }
};
$6ac = $6ac_1 = __decorate([
  __param(1, $0R),
  __param(2, $Pk),
  __param(3, $cJ),
  __param(4, $on),
  __param(5, $50)
], $6ac);
var DebugHoverAccessibilityProvider = class {
  getWidgetAriaLabel() {
    return localize(5835, null);
  }
  getAriaLabel(element) {
    return localize(5836, null, element.name, element.value);
  }
};
var DebugHoverDataSource = class extends $r4b {
  hasChildren(element) {
    return element.hasChildren;
  }
  c(element) {
    return element.getChildren();
  }
};
var DebugHoverDelegate = class {
  getHeight(element) {
    return 18;
  }
  getTemplateId(element) {
    if (element instanceof $KP) {
      return $Xac.ID;
    }
    return $Yac.ID;
  }
};
var DebugHoverComputer = class DebugHoverComputer2 {
  constructor(b, c, d, f) {
    this.b = b;
    this.c = c;
    this.d = d;
    this.f = f;
  }
  async compute(position, token) {
    const session = this.c.getViewModel().focusedSession;
    if (!session || !this.b.hasModel()) {
      return { rangeChanged: false };
    }
    const model = this.b.getModel();
    const result = await $tP(this.d, model, position, token);
    if (!result) {
      return { rangeChanged: false };
    }
    const { range, matchingExpression } = result;
    const rangeChanged = !this.a?.range.equalsRange(range);
    this.a = { expression: matchingExpression, range: $9C.lift(range) };
    return { rangeChanged, range: this.a.range };
  }
  async evaluate(session) {
    if (!this.a) {
      this.f.error("No expression to evaluate");
      return;
    }
    const textModel = this.b.getModel();
    const debugSource = textModel && session.getSourceForUri(textModel?.uri);
    if (session.capabilities.supportsEvaluateForHovers) {
      const expression = new $LP(this.a.expression);
      await expression.evaluate(session, this.c.getViewModel().focusedStackFrame, "hover", void 0, debugSource ? {
        line: this.a.range.startLineNumber,
        column: this.a.range.startColumn,
        source: debugSource.raw
      } : void 0);
      return expression;
    } else {
      const focusedStackFrame = this.c.getViewModel().focusedStackFrame;
      if (focusedStackFrame) {
        return await $5ac(focusedStackFrame, $Mb(this.a.expression.split(".").map((word) => word.trim())));
      }
    }
    return void 0;
  }
};
DebugHoverComputer = __decorate([
  __param(1, $0R),
  __param(2, $mP),
  __param(3, $wn)
], DebugHoverComputer);

// out-build/vs/workbench/contrib/debug/browser/exceptionWidget.js
var $142 = $;
var debugExceptionWidgetBorder = $5n("debugExceptionWidget.border", "#a31515", localize(6005, null));
var debugExceptionWidgetBackground = $5n("debugExceptionWidget.background", { dark: "#420b0d", light: "#f1dfde", hcDark: "#420b0d", hcLight: "#f1dfde" }, localize(6006, null));
var $7ac = class $7ac2 extends $_db {
  constructor(editor, b, c, themeService, d) {
    super(editor, { showFrame: true, showArrow: true, isAccessible: true, frameWidth: 1, className: "exception-widget-container" });
    this.b = b;
    this.c = c;
    this.d = d;
    this.i(themeService.getColorTheme());
    this.n.add(themeService.onDidColorThemeChange(this.i.bind(this)));
    this.create();
    const onDidLayoutChangeScheduler = new $8h(() => this.D(void 0, void 0), 50);
    this.n.add(this.editor.onDidLayoutChange(() => onDidLayoutChangeScheduler.schedule()));
    this.n.add(onDidLayoutChangeScheduler);
  }
  i(theme) {
    this.a = theme.getColor(debugExceptionWidgetBackground);
    const frameColor = theme.getColor(debugExceptionWidgetBorder);
    this.style({
      arrowColor: frameColor,
      frameColor
    });
  }
  o() {
    if (this.container) {
      this.container.style.backgroundColor = this.a ? this.a.toString() : "";
    }
    super.o();
  }
  B(container2) {
    this.A("exception-widget");
    const fontInfo = this.editor.getOption(
      52
      /* EditorOption.fontInfo */
    );
    container2.style.fontSize = `${fontInfo.fontSize}px`;
    container2.style.lineHeight = `${fontInfo.lineHeight}px`;
    container2.tabIndex = 0;
    const title = $142(".title");
    const label3 = $142(".label");
    $bk(title, label3);
    const actions = $142(".actions");
    $bk(title, actions);
    label3.textContent = this.b.id ? localize(6007, null, this.b.id) : localize(6008, null);
    let ariaLabel = label3.textContent;
    const actionBar = new $LZ(actions);
    actionBar.push(new $Um("editor.closeExceptionWidget", localize(6009, null), ThemeIcon.asClassName($_r), true, async () => {
      const contribution = this.editor.getContribution($3R);
      contribution?.closeExceptionWidget();
    }), { label: false, icon: true });
    $bk(container2, title);
    if (this.b.description) {
      const description = $142(".description");
      description.textContent = this.b.description;
      ariaLabel += ", " + this.b.description;
      $bk(container2, description);
    }
    if (this.b.details && this.b.details.stackTrace) {
      const stackTrace = $142(".stack-trace");
      const linkDetector = this.d.createInstance($p4b);
      const linkedStackTrace = linkDetector.linkify(this.b.details.stackTrace, true, this.c ? this.c.root : void 0, void 0, { type: 0, store: this.n });
      stackTrace.appendChild(linkedStackTrace);
      $bk(container2, stackTrace);
      ariaLabel += ", " + this.b.details.stackTrace;
    }
    container2.setAttribute("aria-label", ariaLabel);
  }
  D(_heightInPixel, _widthInPixel) {
    this.container.style.height = "initial";
    const lineHeight = this.editor.getOption(
      68
      /* EditorOption.lineHeight */
    );
    const arrowHeight = Math.round(lineHeight / 3);
    const computedLinesNumber = Math.ceil((this.container.offsetHeight + arrowHeight) / lineHeight);
    this.E(computedLinesNumber);
  }
  focus() {
    this.container?.focus();
  }
  hasFocus() {
    if (!this.container) {
      return false;
    }
    return $Nj(this.container);
  }
};
$7ac = __decorate([
  __param(3, $gs),
  __param(4, $Pk)
], $7ac);

// out-build/vs/workbench/contrib/debug/browser/debugEditorContribution.js
var MAX_NUM_INLINE_VALUES = 100;
var MAX_INLINE_DECORATOR_LENGTH = 150;
var MAX_TOKENIZATION_LINE_LEN = 500;
var DEAFULT_INLINE_DEBOUNCE_DELAY = 200;
var $8ac = $5n("editor.inlineValuesForeground", {
  dark: "#ffffff80",
  light: "#00000080",
  hcDark: "#ffffff80",
  hcLight: "#00000080"
}, localize(5832, null));
var $9ac = $5n("editor.inlineValuesBackground", "#ffc80033", localize(5833, null));
var InlineSegment = class {
  constructor(column, text2) {
    this.column = column;
    this.text = text2;
  }
};
function createInlineValueDecoration(lineNumber, contentText, column = 1073741824) {
  if (contentText.length > MAX_INLINE_DECORATOR_LENGTH) {
    contentText = contentText.substring(0, MAX_INLINE_DECORATOR_LENGTH) + "...";
  }
  return [
    {
      range: {
        startLineNumber: lineNumber,
        endLineNumber: lineNumber,
        startColumn: column,
        endColumn: column
      },
      options: {
        description: "debug-inline-value-decoration-spacer",
        after: {
          content: $wg,
          cursorStops: InjectedTextCursorStops.None
        },
        showIfCollapsed: true
      }
    },
    {
      range: {
        startLineNumber: lineNumber,
        endLineNumber: lineNumber,
        startColumn: column,
        endColumn: column
      },
      options: {
        description: "debug-inline-value-decoration",
        after: {
          content: replaceWsWithNoBreakWs(contentText),
          inlineClassName: "debug-inline-value",
          inlineClassNameAffectsLetterSpacing: true,
          cursorStops: InjectedTextCursorStops.None
        },
        showIfCollapsed: true
      }
    }
  ];
}
function replaceWsWithNoBreakWs(str) {
  return str.replace(/[ \t]/g, $wg);
}
function createInlineValueDecorationsInsideRange(expressions, ranges, model, wordToLineNumbersMap) {
  const nameValueMap = /* @__PURE__ */ new Map();
  for (const expr of expressions) {
    nameValueMap.set(expr.name, expr.value);
    if (nameValueMap.size >= MAX_NUM_INLINE_VALUES) {
      break;
    }
  }
  const lineToNamesMap = /* @__PURE__ */ new Map();
  nameValueMap.forEach((_value, name) => {
    const lineNumbers = wordToLineNumbersMap.get(name);
    if (lineNumbers) {
      for (const lineNumber of lineNumbers) {
        if (ranges.some((r2) => lineNumber >= r2.startLineNumber && lineNumber <= r2.endLineNumber)) {
          if (!lineToNamesMap.has(lineNumber)) {
            lineToNamesMap.set(lineNumber, []);
          }
          if (lineToNamesMap.get(lineNumber).indexOf(name) === -1) {
            lineToNamesMap.get(lineNumber).push(name);
          }
        }
      }
    }
  });
  return [...lineToNamesMap].map(([line, names]) => ({
    line,
    variables: names.sort((first, second) => {
      const content = model.getLineContent(line);
      return content.indexOf(first) - content.indexOf(second);
    }).map((name) => ({ name, value: nameValueMap.get(name) }))
  }));
}
function getWordToLineNumbersMap(model, lineNumber, result) {
  const lineLength = model.getLineLength(lineNumber);
  if (lineLength > MAX_TOKENIZATION_LINE_LEN) {
    return;
  }
  const lineContent = model.getLineContent(lineNumber);
  model.tokenization.forceTokenization(lineNumber);
  const lineTokens = model.tokenization.getLineTokens(lineNumber);
  for (let tokenIndex = 0, tokenCount = lineTokens.getCount(); tokenIndex < tokenCount; tokenIndex++) {
    const tokenType = lineTokens.getStandardTokenType(tokenIndex);
    if (tokenType === 0) {
      $JD.lastIndex = 0;
      const tokenStartOffset = lineTokens.getStartOffset(tokenIndex);
      const tokenEndOffset = lineTokens.getEndOffset(tokenIndex);
      const tokenStr = lineContent.substring(tokenStartOffset, tokenEndOffset);
      const wordMatch = $JD.exec(tokenStr);
      if (wordMatch) {
        const word = wordMatch[0];
        if (!result.has(word)) {
          result.set(word, []);
        }
        result.get(word).push(lineNumber);
      }
    }
  }
}
var $0ac = class $0ac2 {
  constructor(w, x, y, z, A, B, C, contextKeyService, D, featureDebounceService) {
    this.w = w;
    this.x = x;
    this.y = y;
    this.z = z;
    this.A = A;
    this.B = B;
    this.C = C;
    this.D = D;
    this.g = false;
    this.i = false;
    this.l = new $4c();
    this.m = false;
    this.o = this.w.createDecorationsCollection();
    this.p = new $2c();
    this.u = new $4c();
    this.t = featureDebounceService.for(D.inlineValuesProvider, "InlineValues", { min: DEAFULT_INLINE_DEBOUNCE_DELAY });
    this.d = this.y.createInstance($6ac, this.w);
    this.c = [this.u, this.l, this.p];
    this.E();
    this.h = $UR.bindTo(contextKeyService);
    this.S();
  }
  E() {
    this.c.push(this.x.getViewModel().onDidFocusStackFrame((e) => this.L(e.stackFrame)));
    this.c.push(this.w.onMouseDown((e) => this.P(e)));
    this.c.push(this.w.onMouseUp(() => this.g = false));
    this.c.push(this.w.onMouseMove((e) => this.Q(e)));
    this.c.push(this.w.onMouseLeave((e) => {
      const hoverDomNode = this.d.getDomNode();
      if (!hoverDomNode) {
        return;
      }
      const rect = hoverDomNode.getBoundingClientRect();
      if (e.event.posx < rect.left || e.event.posx > rect.right || e.event.posy < rect.top || e.event.posy > rect.bottom) {
        this.O();
      }
    }));
    this.c.push(this.w.onKeyDown((e) => this.R(e)));
    this.c.push(this.w.onDidChangeModelContent(() => {
      this.F = void 0;
      this.V.schedule();
    }));
    this.c.push(this.x.getViewModel().onWillUpdateViews(() => this.V.schedule()));
    this.c.push(this.x.getViewModel().onDidEvaluateLazyExpression(() => this.V.schedule()));
    this.c.push(this.w.onDidChangeModel(async () => {
      this.H();
      this.S();
      this.O();
      this.F = void 0;
      const stackFrame = this.x.getViewModel().focusedStackFrame;
      await this.W(stackFrame);
    }));
    this.c.push(this.w.onDidScrollChange(() => {
      this.O();
      const model = this.w.getModel();
      if (model && this.D.inlineValuesProvider.has(model)) {
        this.V.schedule();
      }
    }));
    this.c.push(this.A.onDidChangeConfiguration((e) => {
      if (e.affectsConfiguration("editor.hover")) {
        this.G();
      }
    }));
    this.c.push(this.x.onDidChangeState((state) => {
      if (state !== 2) {
        this.S();
      }
    }));
    this.G();
  }
  G() {
    const model = this.w.getModel();
    if (model) {
      this.q = this.A.getValue("editor.hover", {
        resource: model.uri,
        overrideIdentifier: model.getLanguageId()
      });
    }
  }
  H() {
    const stackFrame = this.x.getViewModel().focusedStackFrame;
    const model = this.w.getModel();
    if (model) {
      this.I(model, stackFrame);
    }
  }
  I(model, stackFrame) {
    if (!stackFrame || !this.C.extUri.isEqual(model.uri, stackFrame.source.uri)) {
      this.l.clear();
      return;
    }
    const ownerDocument = this.w.getContainerDomNode().ownerDocument;
    this.l.value = $_i(ownerDocument, "keydown", (keydownEvent) => {
      const standardKeyboardEvent = new $if(keydownEvent);
      if (standardKeyboardEvent.keyCode === 6) {
        this.m = true;
        const debugHoverWasVisible = this.d.isVisible();
        this.d.hide();
        this.u.clear();
        if (debugHoverWasVisible && this.f) {
          this.K(this.f.position, false);
        }
        const onKeyUp = new $9Z(ownerDocument, "keyup");
        const listener = Event2.any(this.B.onDidChangeFocus, onKeyUp.event)((keyupEvent) => {
          let standardKeyboardEvent2 = void 0;
          if ($4j(keyupEvent)) {
            standardKeyboardEvent2 = new $if(keyupEvent);
          }
          if (!standardKeyboardEvent2 || standardKeyboardEvent2.keyCode === 6) {
            this.m = false;
            this.J();
            listener.dispose();
            onKeyUp.dispose();
          }
        });
      }
    });
  }
  async showHover(position, focus, mouseEvent) {
    this.J();
    const sf = this.x.getViewModel().focusedStackFrame;
    const model = this.w.getModel();
    if (sf && model && this.C.extUri.isEqual(sf.source.uri, model.uri)) {
      const result = await this.d.showAt(position, focus, mouseEvent);
      if (result === 1) {
        this.K(position, focus);
      }
    } else {
      this.K(position, focus);
    }
  }
  J() {
    if (this.u.value || this.q?.enabled === false) {
      return;
    }
    const hoverController = this.w.getContribution($Afb.ID);
    hoverController?.hideContentHover();
    this.w.updateOptions({ hover: { enabled: false } });
    this.u.value = {
      dispose: () => {
        this.w.updateOptions({
          hover: { enabled: this.q?.enabled ?? true }
        });
      }
    };
  }
  K(position, focus) {
    const hoverController = this.w.getContribution($Afb.ID);
    const range = new $9C(position.lineNumber, position.column, position.lineNumber, position.column);
    this.u.clear();
    hoverController?.showContentHover(range, 1, 0, focus);
  }
  async L(sf) {
    const model = this.w.getModel();
    if (model) {
      this.I(model, sf);
      if (sf && this.C.extUri.isEqual(sf.source.uri, model.uri)) {
        await this.S();
      } else {
        this.O();
      }
    }
    await this.W(sf);
  }
  get M() {
    const baseDelay = this.q?.delay || 0;
    const delayFactor = $4i(2 - (baseDelay - 300) / 600, 1, 2);
    return baseDelay * delayFactor;
  }
  get N() {
    const scheduler = new $8h(() => {
      if (this.f && !this.m) {
        this.showHover(this.f.position, false, this.f.event);
      }
    }, this.M);
    this.c.push(scheduler);
    return scheduler;
  }
  O() {
    if (this.d.willBeVisible()) {
      this.d.hide();
    }
    this.N.cancel();
    this.u.clear();
  }
  // hover business
  P(mouseEvent) {
    this.g = true;
    if (mouseEvent.target.type === 9 && mouseEvent.target.detail === $6ac.ID) {
      return;
    }
    this.O();
  }
  Q(mouseEvent) {
    if (this.x.state !== 2) {
      return;
    }
    const target = mouseEvent.target;
    const stopKey = $m ? "metaKey" : "ctrlKey";
    if (!this.m) {
      if (target.type === 2) {
        this.u.clear();
        this.i = true;
      } else if (this.i) {
        this.i = false;
        this.G();
      }
    }
    if (target.type === 9 && target.detail === $6ac.ID || this.d.isInSafeTriangle(mouseEvent.event.posx, mouseEvent.event.posy)) {
      const sticky = this.q?.sticky ?? true;
      if (sticky || this.d.isShowingComplexValue || mouseEvent.event[stopKey]) {
        return;
      }
    }
    if (target.type === 6) {
      if (target.position && !$8C.equals(target.position, this.f?.position || null) && !this.d.isInSafeTriangle(mouseEvent.event.posx, mouseEvent.event.posy)) {
        this.f = { position: target.position, event: mouseEvent.event };
        this.J();
        this.N.schedule(this.M);
      }
    } else if (!this.g) {
      this.O();
    }
  }
  R(e) {
    const stopKey = $m ? 57 : 5;
    if (e.keyCode !== stopKey && e.keyCode !== 6) {
      this.O();
    }
  }
  // end hover business
  // exception widget
  async S() {
    const model = this.w.getModel();
    const focusedSf = this.x.getViewModel().focusedStackFrame;
    const callStack = focusedSf ? focusedSf.thread.getCallStack() : null;
    if (!model || !focusedSf || !callStack || callStack.length === 0) {
      this.closeExceptionWidget();
      return;
    }
    const exceptionSf = callStack.find((sf) => !!(sf && sf.source && sf.source.available && sf.source.presentationHint !== "deemphasize"));
    if (!exceptionSf || exceptionSf !== focusedSf) {
      this.closeExceptionWidget();
      return;
    }
    const sameUri = this.C.extUri.isEqual(exceptionSf.source.uri, model.uri);
    if (this.j && !sameUri) {
      this.closeExceptionWidget();
    } else if (sameUri) {
      const exceptionInfo = await focusedSf.thread.exceptionInfo;
      if (exceptionInfo) {
        this.T(exceptionInfo, this.x.getViewModel().focusedSession, exceptionSf.range.startLineNumber, exceptionSf.range.startColumn);
      }
    }
  }
  T(exceptionInfo, debugSession, lineNumber, column) {
    if (this.j) {
      this.j.dispose();
    }
    this.j = this.y.createInstance($7ac, this.w, exceptionInfo, debugSession);
    this.j.show({ lineNumber, column }, 0);
    this.j.focus();
    this.w.revealRangeInCenter({
      startLineNumber: lineNumber,
      startColumn: column,
      endLineNumber: lineNumber,
      endColumn: column
    });
    this.h.set(true);
  }
  closeExceptionWidget() {
    if (this.j) {
      const shouldFocusEditor = this.j.hasFocus();
      this.j.dispose();
      this.j = void 0;
      this.h.set(false);
      if (shouldFocusEditor) {
        this.w.focus();
      }
    }
  }
  async addLaunchConfiguration() {
    const model = this.w.getModel();
    if (!model) {
      return;
    }
    let configurationsArrayPosition;
    let lastProperty;
    const getConfigurationPosition = () => {
      let depthInArray = 0;
      $Fw(model.getValue(), {
        onObjectProperty: (property) => {
          lastProperty = property;
        },
        onArrayBegin: (offset) => {
          if (lastProperty === "configurations" && depthInArray === 0) {
            configurationsArrayPosition = model.getPositionAt(offset + 1);
          }
          depthInArray++;
        },
        onArrayEnd: () => {
          depthInArray--;
        }
      });
    };
    getConfigurationPosition();
    if (!configurationsArrayPosition) {
      const { tabSize, insertSpaces } = model.getOptions();
      const eol = model.getEOL();
      const edit3 = $rc(model.uri.fsPath) === "launch.json" ? $Xw(model.getValue(), ["configurations"], [], { tabSize, insertSpaces, eol })[0] : $Xw(model.getValue(), ["launch"], { "configurations": [] }, { tabSize, insertSpaces, eol })[0];
      const startPosition = model.getPositionAt(edit3.offset);
      const lineNumber = startPosition.lineNumber;
      const range = new $9C(lineNumber, startPosition.column, lineNumber, model.getLineMaxColumn(lineNumber));
      model.pushEditOperations(null, [$bD.replace(range, edit3.content)], () => null);
      getConfigurationPosition();
    }
    if (!configurationsArrayPosition) {
      return;
    }
    this.w.focus();
    const insertLine = (position) => {
      if (model.getLineLastNonWhitespaceColumn(position.lineNumber) > position.column) {
        this.w.setPosition(position);
        CoreEditingCommands.LineBreakInsert.runEditorCommand(null, this.w, null);
      }
      this.w.setPosition(position);
      return this.z.executeCommand("editor.action.insertLineAfter");
    };
    await insertLine(configurationsArrayPosition);
    await this.z.executeCommand("editor.action.triggerSuggest");
  }
  // Inline Decorations
  get U() {
    return new $8h(() => {
      this.p.clear();
      this.o.clear();
    }, 100);
  }
  get V() {
    const model = this.w.getModel();
    return new $8h(async () => await this.W(this.x.getViewModel().focusedStackFrame), model ? this.t.get(model) : DEAFULT_INLINE_DEBOUNCE_DELAY);
  }
  async W(stackFrame) {
    const var_value_format = "{0} = {1}";
    const separator = ", ";
    const model = this.w.getModel();
    const inlineValuesSetting = this.A.getValue("debug").inlineValues;
    const inlineValuesTurnedOn = inlineValuesSetting === true || inlineValuesSetting === "on" || inlineValuesSetting === "auto" && model && this.D.inlineValuesProvider.has(model);
    if (!inlineValuesTurnedOn || !model || !stackFrame || model.uri.toString() !== stackFrame.source.uri.toString()) {
      if (!this.U.isScheduled()) {
        this.U.schedule();
      }
      return;
    }
    this.U.cancel();
    this.p.clear();
    const viewRanges = this.w.getVisibleRangesPlusViewportAboveBelow();
    let allDecorations;
    const cts = new $ad();
    this.p.add($1c(() => cts.dispose(true)));
    if (this.D.inlineValuesProvider.has(model)) {
      const findVariable = async (_key, caseSensitiveLookup) => {
        const scopes = await stackFrame.getMostSpecificScopes(stackFrame.range);
        const key2 = caseSensitiveLookup ? _key : _key.toLowerCase();
        for (const scope of scopes) {
          const variables = await scope.getChildren();
          const found = variables.find((v) => caseSensitiveLookup ? v.name === key2 : v.name.toLowerCase() === key2);
          if (found) {
            return found.value;
          }
        }
        return void 0;
      };
      const ctx = {
        frameId: stackFrame.frameId,
        stoppedLocation: new $9C(stackFrame.range.startLineNumber, stackFrame.range.startColumn + 1, stackFrame.range.endLineNumber, stackFrame.range.endColumn + 1)
      };
      const providers2 = this.D.inlineValuesProvider.ordered(model).reverse();
      allDecorations = [];
      const lineDecorations = /* @__PURE__ */ new Map();
      const promises = providers2.flatMap((provider) => viewRanges.map((range) => Promise.resolve(provider.provideInlineValues(model, range, ctx, cts.token)).then(async (result) => {
        if (result) {
          for (const iv of result) {
            let text2 = void 0;
            switch (iv.type) {
              case "text":
                text2 = iv.text;
                break;
              case "variable": {
                let va = iv.variableName;
                if (!va) {
                  const lineContent = model.getLineContent(iv.range.startLineNumber);
                  va = lineContent.substring(iv.range.startColumn - 1, iv.range.endColumn - 1);
                }
                const value = await findVariable(va, iv.caseSensitiveLookup);
                if (value) {
                  text2 = $wf(var_value_format, va, value);
                }
                break;
              }
              case "expression": {
                let expr = iv.expression;
                if (!expr) {
                  const lineContent = model.getLineContent(iv.range.startLineNumber);
                  expr = lineContent.substring(iv.range.startColumn - 1, iv.range.endColumn - 1);
                }
                if (expr) {
                  const expression = new $LP(expr);
                  await expression.evaluate(stackFrame.thread.session, stackFrame, "watch", true);
                  if (expression.available) {
                    text2 = $wf(var_value_format, expr, expression.value);
                  }
                }
                break;
              }
            }
            if (text2) {
              const line = iv.range.startLineNumber;
              let lineSegments = lineDecorations.get(line);
              if (!lineSegments) {
                lineSegments = [];
                lineDecorations.set(line, lineSegments);
              }
              if (!lineSegments.some((iv2) => iv2.text === text2)) {
                lineSegments.push(new InlineSegment(iv.range.startColumn, text2));
              }
            }
          }
        }
      }, (err) => {
        $hb(err);
      })));
      const startTime = Date.now();
      await Promise.all(promises);
      this.V.delay = this.t.update(model, Date.now() - startTime);
      lineDecorations.forEach((segments, line) => {
        if (segments.length > 0) {
          segments = segments.sort((a, b) => a.column - b.column);
          const text2 = segments.map((s) => s.text).join(separator);
          allDecorations.push(...createInlineValueDecoration(line, text2));
        }
      });
    } else {
      const scopes = await stackFrame.getMostSpecificScopes(stackFrame.range);
      const scopesWithVariables = await Promise.all(scopes.map(async (scope) => ({ scope, variables: await scope.getChildren() })));
      const valuesPerLine = /* @__PURE__ */ new Map();
      for (const { scope, variables } of scopesWithVariables) {
        let scopeRange = new $9C(0, 0, stackFrame.range.startLineNumber, stackFrame.range.startColumn);
        if (scope.range) {
          scopeRange = scopeRange.setStartPosition(scope.range.startLineNumber, scope.range.startColumn);
        }
        const ownRanges = viewRanges.map((r2) => r2.intersectRanges(scopeRange)).filter($Hg);
        this.F ??= new WordsToLineNumbersCache(model);
        for (const range of ownRanges) {
          this.F.ensureRangePopulated(range);
        }
        const mapped = createInlineValueDecorationsInsideRange(variables, ownRanges, model, this.F.value);
        for (const { line, variables: variables2 } of mapped) {
          let values = valuesPerLine.get(line);
          if (!values) {
            values = /* @__PURE__ */ new Map();
            valuesPerLine.set(line, values);
          }
          for (const { name, value } of variables2) {
            if (!values.has(name)) {
              values.set(name, value);
            }
          }
        }
      }
      allDecorations = [...valuesPerLine.entries()].flatMap(([line, values]) => createInlineValueDecoration(line, [...values].map(([n, v]) => `${n} = ${v}`).join(", ")));
    }
    if (cts.token.isCancellationRequested) {
      return;
    }
    let preservePosition;
    if (this.w.getOption(
      137
      /* EditorOption.wordWrap */
    ) !== "off") {
      const position = this.w.getPosition();
      if (position && this.w.getVisibleRanges().some((r2) => r2.containsPosition(position))) {
        preservePosition = { position, top: this.w.getTopForPosition(position.lineNumber, position.column) };
      }
    }
    this.o.set(allDecorations);
    if (preservePosition) {
      const top2 = this.w.getTopForPosition(preservePosition.position.lineNumber, preservePosition.position.column);
      this.w.setScrollTop(
        this.w.getScrollTop() - (preservePosition.top - top2),
        1
        /* ScrollType.Immediate */
      );
    }
  }
  dispose() {
    if (this.d) {
      this.d.dispose();
    }
    if (this.k) {
      this.k.dispose();
    }
    this.c = $Xc(this.c);
  }
};
__decorate([
  $0t
], $0ac.prototype, "N", null);
__decorate([
  $0t
], $0ac.prototype, "U", null);
__decorate([
  $0t
], $0ac.prototype, "V", null);
$0ac = __decorate([
  __param(1, $0R),
  __param(2, $Pk),
  __param(3, $sn),
  __param(4, $kl),
  __param(5, $S4),
  __param(6, $vl),
  __param(7, $on),
  __param(8, $mP),
  __param(9, $tbb)
], $0ac);
var WordsToLineNumbersCache = class {
  constructor(d) {
    this.d = d;
    this.value = /* @__PURE__ */ new Map();
    this.c = new Uint8Array(Math.ceil(d.getLineCount() / 8));
  }
  /** Ensures that variables names in the given range have been identified. */
  ensureRangePopulated(range) {
    for (let lineNumber = range.startLineNumber; lineNumber <= range.endLineNumber; lineNumber++) {
      const bin = lineNumber >> 3;
      const bit = 1 << (lineNumber & 7);
      if (!(this.c[bin] & bit)) {
        getWordToLineNumbersMap(this.d, lineNumber, this.value);
        this.c[bin] |= bit;
      }
    }
  }
};
$tn.registerCommand("_executeInlineValueProvider", async (accessor, uri, iRange, context) => {
  $Jg(URI.isUri(uri));
  $Jg($9C.isIRange(iRange));
  if (!context || typeof context.frameId !== "number" || !$9C.isIRange(context.stoppedLocation)) {
    throw $nb("context");
  }
  const model = accessor.get($sG).getModel(uri);
  if (!model) {
    throw $nb("uri");
  }
  const range = $9C.lift(iRange);
  const { inlineValuesProvider } = accessor.get($mP);
  const providers2 = inlineValuesProvider.ordered(model);
  const providerResults = await Promise.all(providers2.map((provider) => provider.provideInlineValues(model, range, context, CancellationToken.None)));
  return providerResults.flat().filter($Hg);
});

// out-build/vs/workbench/contrib/debug/browser/debugProgress.js
var $$ac = class $$ac2 {
  constructor(debugService, progressService, viewsService) {
    this.a = [];
    let progressListener;
    const listenOnProgress = (session) => {
      if (progressListener) {
        progressListener.dispose();
        progressListener = void 0;
      }
      if (session) {
        progressListener = session.onDidProgressStart(async (progressStartEvent) => {
          const promise = new Promise((r2) => {
            const listener = Event2.any(Event2.filter(session.onDidProgressEnd, (e) => e.body.progressId === progressStartEvent.body.progressId), session.onDidEndAdapter)(() => {
              listener.dispose();
              r2();
            });
          });
          if (viewsService.isViewContainerVisible($TQ)) {
            progressService.withProgress({ location: $TQ }, () => promise);
          }
          const source = debugService.getAdapterManager().getDebuggerLabel(session.configuration.type);
          progressService.withProgress({
            location: 15,
            title: progressStartEvent.body.title,
            cancellable: progressStartEvent.body.cancellable,
            source,
            delay: 500
          }, (progressStep) => {
            let total = 0;
            const reportProgress = (progress) => {
              let increment = void 0;
              if (typeof progress.percentage === "number") {
                increment = progress.percentage - total;
                total += increment;
              }
              progressStep.report({
                message: progress.message,
                increment,
                total: typeof increment === "number" ? 100 : void 0
              });
            };
            if (progressStartEvent.body.message) {
              reportProgress(progressStartEvent.body);
            }
            const progressUpdateListener = session.onDidProgressUpdate((e) => {
              if (e.body.progressId === progressStartEvent.body.progressId) {
                reportProgress(e.body);
              }
            });
            return promise.then(() => progressUpdateListener.dispose());
          }, () => session.cancel(progressStartEvent.body.progressId));
        });
      }
    };
    this.a.push(debugService.getViewModel().onDidFocusSession(listenOnProgress));
    listenOnProgress(debugService.getViewModel().focusedSession);
    this.a.push(debugService.onWillNewSession((session) => {
      if (!progressListener) {
        listenOnProgress(session);
      }
    }));
  }
  dispose() {
    $Xc(this.a);
  }
};
$$ac = __decorate([
  __param(0, $0R),
  __param(1, $TJ),
  __param(2, $uob)
], $$ac);

// out-build/vs/workbench/contrib/debug/browser/debugQuickAccess.js
var $_ac = class $_ac2 extends $rhb {
  constructor(a, b, h3, j) {
    super($B5b, {
      noResultsPick: {
        label: localize(5894, null)
      }
    });
    this.a = a;
    this.b = b;
    this.h = h3;
    this.j = j;
  }
  async g(filter) {
    const picks = [];
    if (!this.a.getAdapterManager().hasEnabledDebuggers()) {
      return [];
    }
    picks.push({ type: "separator", label: "launch.json" });
    const configManager = this.a.getConfigurationManager();
    let lastGroup;
    for (const config of configManager.getAllConfigurations()) {
      const highlights = $Rl(filter, config.name, true);
      if (highlights) {
        if (lastGroup !== config.presentation?.group) {
          picks.push({ type: "separator" });
          lastGroup = config.presentation?.group;
        }
        picks.push({
          label: config.name,
          description: this.b.getWorkbenchState() === 3 ? config.launch.name : "",
          highlights: { label: highlights },
          buttons: [{
            iconClass: ThemeIcon.asClassName($1Fb),
            tooltip: localize(5895, null)
          }],
          trigger: () => {
            config.launch.openConfigFile({ preserveFocus: false });
            return TriggerAction.CLOSE_PICKER;
          },
          accept: async () => {
            await configManager.selectConfiguration(config.launch, config.name);
            try {
              await this.a.startDebugging(config.launch, void 0, { startedByUser: true });
            } catch (error) {
              this.j.error(error);
            }
          }
        });
      }
    }
    const dynamicProviders = await configManager.getDynamicProviders();
    if (dynamicProviders.length > 0) {
      picks.push({
        type: "separator",
        label: localize(5896, null)
      });
    }
    configManager.getRecentDynamicConfigurations().forEach(({ name, type }) => {
      const highlights = $Rl(filter, name, true);
      if (highlights) {
        picks.push({
          label: name,
          highlights: { label: highlights },
          buttons: [{
            iconClass: ThemeIcon.asClassName($3Fb),
            tooltip: localize(5897, null)
          }],
          trigger: () => {
            configManager.removeRecentDynamicConfigurations(name, type);
            return TriggerAction.CLOSE_PICKER;
          },
          accept: async () => {
            await configManager.selectConfiguration(void 0, name, void 0, { type });
            try {
              const { launch, getConfig } = configManager.selectedConfiguration;
              const config = await getConfig();
              await this.a.startDebugging(launch, config, { startedByUser: true });
            } catch (error) {
              this.j.error(error);
            }
          }
        });
      }
    });
    dynamicProviders.forEach((provider) => {
      picks.push({
        label: `$(folder) ${provider.label}...`,
        ariaLabel: localize(5898, null, provider.label),
        accept: async () => {
          const pick = await provider.pick();
          if (pick) {
            await configManager.selectConfiguration(pick.launch, pick.config.name, pick.config, { type: provider.type });
            this.a.startDebugging(pick.launch, pick.config, { startedByUser: true });
          }
        }
      });
    });
    const visibleLaunches = configManager.getLaunches().filter((launch) => !launch.hidden);
    if (visibleLaunches.length > 0) {
      picks.push({ type: "separator", label: localize(5899, null) });
    }
    for (const launch of visibleLaunches) {
      const label3 = this.b.getWorkbenchState() === 3 ? localize(5900, null, launch.name) : localize(5901, null);
      picks.push({
        label: label3,
        description: this.b.getWorkbenchState() === 3 ? launch.name : "",
        highlights: { label: $Rl(filter, label3, true) ?? void 0 },
        accept: () => this.h.executeCommand($y4b, launch.uri.toString())
      });
    }
    return picks;
  }
};
$_ac = __decorate([
  __param(0, $0R),
  __param(1, $Zk),
  __param(2, $sn),
  __param(3, $PJ)
], $_ac);

// out-build/vs/platform/debug/common/extensionHostDebug.js
var $Ax = $Qk("extensionHostDebugService");

// out-build/vs/workbench/contrib/debug/common/debugCompoundRoot.js
var $lP = class {
  constructor() {
    this.a = false;
    this.b = new $ze();
    this.onDidSessionStop = this.b.event;
  }
  sessionStopped() {
    if (!this.a) {
      this.a = true;
      this.b.fire();
    }
  }
};

// out-build/vs/workbench/contrib/debug/common/debugStorage.js
var DEBUG_BREAKPOINTS_KEY = "debug.breakpoint";
var DEBUG_FUNCTION_BREAKPOINTS_KEY = "debug.functionbreakpoint";
var DEBUG_DATA_BREAKPOINTS_KEY = "debug.databreakpoint";
var DEBUG_EXCEPTION_BREAKPOINTS_KEY = "debug.exceptionbreakpoint";
var DEBUG_WATCH_EXPRESSIONS_KEY = "debug.watchexpressions";
var DEBUG_CHOSEN_ENVIRONMENTS_KEY = "debug.chosenenvironment";
var DEBUG_UX_STATE_KEY = "debug.uxstate";
var $DP = class $DP2 extends $3c {
  constructor(a, b, c, f) {
    super();
    this.a = a;
    this.b = b;
    this.c = c;
    this.f = f;
    this.breakpoints = $he(this, this.g());
    this.functionBreakpoints = $he(this, this.h());
    this.exceptionBreakpoints = $he(this, this.j());
    this.dataBreakpoints = $he(this, this.m());
    this.watchExpressions = $he(this, this.n());
    this.B(a.onDidChangeValue(1, void 0, this.q)((e) => {
      if (e.external) {
        switch (e.key) {
          case DEBUG_BREAKPOINTS_KEY:
            return this.breakpoints.set(this.g(), void 0);
          case DEBUG_FUNCTION_BREAKPOINTS_KEY:
            return this.functionBreakpoints.set(this.h(), void 0);
          case DEBUG_EXCEPTION_BREAKPOINTS_KEY:
            return this.exceptionBreakpoints.set(this.j(), void 0);
          case DEBUG_DATA_BREAKPOINTS_KEY:
            return this.dataBreakpoints.set(this.m(), void 0);
          case DEBUG_WATCH_EXPRESSIONS_KEY:
            return this.watchExpressions.set(this.n(), void 0);
        }
      }
    }));
  }
  loadDebugUxState() {
    return this.a.get(DEBUG_UX_STATE_KEY, 1, "default");
  }
  storeDebugUxState(value) {
    this.a.store(
      DEBUG_UX_STATE_KEY,
      value,
      1,
      1
      /* StorageTarget.MACHINE */
    );
  }
  g() {
    let result;
    try {
      result = JSON.parse(this.a.get(DEBUG_BREAKPOINTS_KEY, 1, "[]")).map((breakpoint) => {
        breakpoint.uri = URI.revive(breakpoint.uri);
        return new $VP(breakpoint, this.b, this.c, this.f, breakpoint.id);
      });
    } catch (e) {
    }
    return result || [];
  }
  h() {
    let result;
    try {
      result = JSON.parse(this.a.get(DEBUG_FUNCTION_BREAKPOINTS_KEY, 1, "[]")).map((fb) => {
        return new $WP(fb, fb.id);
      });
    } catch (e) {
    }
    return result || [];
  }
  j() {
    let result;
    try {
      result = JSON.parse(this.a.get(DEBUG_EXCEPTION_BREAKPOINTS_KEY, 1, "[]")).map((exBreakpoint) => {
        return new $YP(exBreakpoint, exBreakpoint.id);
      });
    } catch (e) {
    }
    return result || [];
  }
  m() {
    let result;
    try {
      result = JSON.parse(this.a.get(DEBUG_DATA_BREAKPOINTS_KEY, 1, "[]")).map((dbp) => {
        return new $XP(dbp, dbp.id);
      });
    } catch (e) {
    }
    return result || [];
  }
  n() {
    let result;
    try {
      result = JSON.parse(this.a.get(DEBUG_WATCH_EXPRESSIONS_KEY, 1, "[]")).map((watchStoredData) => {
        return new $LP(watchStoredData.name, watchStoredData.id);
      });
    } catch (e) {
    }
    return result || [];
  }
  loadChosenEnvironments() {
    const obj = JSON.parse(this.a.get(DEBUG_CHOSEN_ENVIRONMENTS_KEY, 1, "{}"));
    return $Xv(obj, (value) => typeof value === "string" ? { type: value } : value);
  }
  storeChosenEnvironments(environments) {
    this.a.store(
      DEBUG_CHOSEN_ENVIRONMENTS_KEY,
      JSON.stringify(environments),
      1,
      1
      /* StorageTarget.MACHINE */
    );
  }
  storeWatchExpressions(watchExpressions) {
    if (watchExpressions.length) {
      this.a.store(
        DEBUG_WATCH_EXPRESSIONS_KEY,
        JSON.stringify(watchExpressions.map((we) => ({ name: we.name, id: we.getId() }))),
        1,
        1
        /* StorageTarget.MACHINE */
      );
    } else {
      this.a.remove(
        DEBUG_WATCH_EXPRESSIONS_KEY,
        1
        /* StorageScope.WORKSPACE */
      );
    }
  }
  storeBreakpoints(debugModel) {
    const breakpoints = debugModel.getBreakpoints();
    if (breakpoints.length) {
      this.a.store(
        DEBUG_BREAKPOINTS_KEY,
        JSON.stringify(breakpoints),
        1,
        1
        /* StorageTarget.MACHINE */
      );
    } else {
      this.a.remove(
        DEBUG_BREAKPOINTS_KEY,
        1
        /* StorageScope.WORKSPACE */
      );
    }
    const functionBreakpoints = debugModel.getFunctionBreakpoints();
    if (functionBreakpoints.length) {
      this.a.store(
        DEBUG_FUNCTION_BREAKPOINTS_KEY,
        JSON.stringify(functionBreakpoints),
        1,
        1
        /* StorageTarget.MACHINE */
      );
    } else {
      this.a.remove(
        DEBUG_FUNCTION_BREAKPOINTS_KEY,
        1
        /* StorageScope.WORKSPACE */
      );
    }
    const dataBreakpoints = debugModel.getDataBreakpoints().filter((dbp) => dbp.canPersist);
    if (dataBreakpoints.length) {
      this.a.store(
        DEBUG_DATA_BREAKPOINTS_KEY,
        JSON.stringify(dataBreakpoints),
        1,
        1
        /* StorageTarget.MACHINE */
      );
    } else {
      this.a.remove(
        DEBUG_DATA_BREAKPOINTS_KEY,
        1
        /* StorageScope.WORKSPACE */
      );
    }
    const exceptionBreakpoints = debugModel.getExceptionBreakpoints();
    if (exceptionBreakpoints.length) {
      this.a.store(
        DEBUG_EXCEPTION_BREAKPOINTS_KEY,
        JSON.stringify(exceptionBreakpoints),
        1,
        1
        /* StorageTarget.MACHINE */
      );
    } else {
      this.a.remove(
        DEBUG_EXCEPTION_BREAKPOINTS_KEY,
        1
        /* StorageScope.WORKSPACE */
      );
    }
  }
};
$DP = __decorate([
  __param(0, $jv),
  __param(1, $cK),
  __param(2, $vl),
  __param(3, $wn)
], $DP);

// out-build/vs/workbench/contrib/debug/common/debugTelemetry.js
var $cbc = class $cbc2 {
  constructor(a, b) {
    this.a = a;
    this.b = b;
  }
  logDebugSessionStart(dbgr, launchJsonExists) {
    const extension = dbgr.getMainExtensionDescriptor();
    this.b.publicLog("debugSessionStart", {
      type: dbgr.type,
      breakpointCount: this.a.getBreakpoints().length,
      exceptionBreakpoints: this.a.getExceptionBreakpoints(),
      watchExpressionsCount: this.a.getWatchExpressions().length,
      extensionName: extension.identifier.value,
      isBuiltin: extension.isBuiltin,
      launchJsonExists
    });
  }
  logDebugSessionStop(session, adapterExitEvent) {
    const breakpoints = this.a.getBreakpoints();
    this.b.publicLog("debugSessionStop", {
      type: session && session.configuration.type,
      success: adapterExitEvent.emittedStopped || breakpoints.length === 0,
      sessionLengthInSeconds: adapterExitEvent.sessionLengthInSeconds,
      breakpointCount: breakpoints.length,
      watchExpressionsCount: this.a.getWatchExpressions().length
    });
  }
};
$cbc = __decorate([
  __param(1, $zv)
], $cbc);

// out-build/vs/workbench/contrib/debug/common/debugViewModel.js
var $dbc = class {
  constructor(D) {
    this.D = D;
    this.firstSessionStart = true;
    this.e = new $ze();
    this.f = new $ze();
    this.g = new $ze();
    this.h = new $ze();
    this.i = new $ze();
    this.j = new $ze();
    this.k = new $ze();
    this.l = /* @__PURE__ */ new WeakMap();
    this.m = /* @__PURE__ */ new Map();
    D.bufferChangeEvents(() => {
      this.n = $eR.bindTo(D);
      this.o = $rR.bindTo(D);
      this.p = $vR.bindTo(D);
      this.q = $tR.bindTo(D);
      this.r = $uR.bindTo(D);
      this.s = $wR.bindTo(D);
      this.t = $zR.bindTo(D);
      this.u = $yR.bindTo(D);
      this.v = $ER.bindTo(D);
      this.w = $FR.bindTo(D);
      this.x = $GR.bindTo(D);
      this.y = $WR.bindTo(D);
      this.z = $KR.bindTo(D);
      this.A = $LR.bindTo(D);
      this.B = $XR.bindTo(D);
      this.C = $1R.bindTo(D);
    });
  }
  getId() {
    return "root";
  }
  get focusedSession() {
    return this.b;
  }
  get focusedThread() {
    return this.c;
  }
  get focusedStackFrame() {
    return this.a;
  }
  setFocus(stackFrame, thread, session, explicit) {
    const shouldEmitForStackFrame = this.a !== stackFrame;
    const shouldEmitForSession = this.b !== session;
    const shouldEmitForThread = this.c !== thread;
    this.a = stackFrame;
    this.c = thread;
    this.b = session;
    this.D.bufferChangeEvents(() => {
      this.o.set(!!session?.capabilities.supportsLoadedSourcesRequest);
      this.p.set(!!session?.capabilities.supportsStepBack);
      this.s.set(!!session?.capabilities.supportsRestartFrame);
      this.t.set(!!session?.capabilities.supportsStepInTargetsRequest);
      this.u.set(!!session?.capabilities.supportsGotoTargetsRequest);
      this.v.set(!!session?.capabilities.supportsSetVariable);
      this.w.set(!!session?.capabilities.supportsDataBreakpointBytes);
      this.x.set(!!session?.capabilities.supportsSetExpression);
      this.z.set(!!session?.capabilities.supportTerminateDebuggee);
      this.A.set(!!session?.capabilities.supportSuspendDebuggee);
      this.B.set(!!session?.capabilities.supportsDisassembleRequest);
      this.C.set(!!stackFrame?.instructionPointerReference);
      const attach = !!session && $pP(session);
      this.q.set(attach);
      this.r.set(!!session && !!session.configuration.noDebug);
    });
    if (shouldEmitForSession) {
      this.e.fire(session);
    }
    if (shouldEmitForStackFrame) {
      this.g.fire({ stackFrame, explicit, session });
    } else if (shouldEmitForThread) {
      this.f.fire({ thread, explicit, session });
    }
  }
  get onDidFocusSession() {
    return this.e.event;
  }
  get onDidFocusThread() {
    return this.f.event;
  }
  get onDidFocusStackFrame() {
    return this.g.event;
  }
  get onDidChangeVisualization() {
    return this.k.event;
  }
  getSelectedExpression() {
    return this.d;
  }
  setSelectedExpression(expression, settingWatch) {
    this.d = expression ? { expression, settingWatch } : void 0;
    this.n.set(!!expression);
    this.h.fire(this.d);
  }
  get onDidSelectExpression() {
    return this.h.event;
  }
  get onDidEvaluateLazyExpression() {
    return this.i.event;
  }
  updateViews() {
    this.j.fire();
  }
  get onWillUpdateViews() {
    return this.j.event;
  }
  isMultiSessionView() {
    return !!this.y.get();
  }
  setMultiSessionView(isMultiSessionView) {
    this.y.set(isMultiSessionView);
  }
  setVisualizedExpression(original, visualized) {
    const current = this.l.get(original) || original;
    const key2 = this.E(original);
    if (visualized) {
      this.l.set(original, visualized);
      this.m.set(key2, visualized.treeId);
    } else {
      this.l.delete(original);
      this.m.delete(key2);
    }
    this.k.fire({ original: current, replacement: visualized || original });
  }
  getVisualizedExpression(expression) {
    return this.l.get(expression) || this.m.get(this.E(expression));
  }
  async evaluateLazyExpression(expression) {
    await expression.evaluateLazy();
    this.i.fire(expression);
  }
  E(expr) {
    return JSON.stringify([
      expr.name,
      expr.type,
      !!expr.memoryReference
    ].join("\0"));
  }
};

// out-build/vs/workbench/contrib/debug/common/breakpoints.js
var $ebc = class $ebc2 {
  constructor(b, c) {
    this.b = b;
    this.c = c;
    this.a = typeof b.when === "string" ? $7m.deserialize(b.when) : void 0;
  }
  get language() {
    return this.b.language;
  }
  get enabled() {
    return !this.a || this.c.contextMatchesRules(this.a);
  }
};
$ebc = __decorate([
  __param(1, $on)
], $ebc);

// out-build/vs/workbench/services/configurationResolver/common/configurationResolverUtils.js
function $abc(schema9) {
  schema9.pattern = schema9.pattern || "^(?!.*\\$\\{(env|config|command)\\.)";
  schema9.patternErrorMessage = schema9.patternErrorMessage || localize(12634, null);
}

// out-build/vs/workbench/contrib/debug/common/debugger.js
var $bbc = class $bbc2 {
  constructor(f, dbgContribution, extensionDescription, g, h3, i2, j, k, l) {
    this.f = f;
    this.g = g;
    this.h = h3;
    this.i = i2;
    this.j = j;
    this.k = k;
    this.l = l;
    this.b = [];
    this.a = { type: dbgContribution.type };
    this.merge(dbgContribution, extensionDescription);
    this.d = typeof this.a.when === "string" ? $7m.deserialize(this.a.when) : void 0;
    this.e = typeof this.a.hiddenWhen === "string" ? $7m.deserialize(this.a.hiddenWhen) : void 0;
  }
  merge(otherDebuggerContribution, extensionDescription) {
    function mixin(destination, source, overwrite, level = 0) {
      if (!$Bg(destination)) {
        return source;
      }
      if ($Bg(source)) {
        Object.keys(source).forEach((key2) => {
          if (key2 !== "__proto__") {
            if ($Bg(destination[key2]) && $Bg(source[key2])) {
              mixin(destination[key2], source[key2], overwrite, level + 1);
            } else {
              if (key2 in destination) {
                if (overwrite) {
                  if (level === 0 && key2 === "type") {
                  } else {
                    destination[key2] = source[key2];
                  }
                }
              } else {
                destination[key2] = source[key2];
              }
            }
          }
        });
      }
      return destination;
    }
    if (this.b.indexOf(extensionDescription) < 0) {
      this.b.push(extensionDescription);
      mixin(this.a, otherDebuggerContribution, extensionDescription.isBuiltin);
      if ($rP(otherDebuggerContribution)) {
        this.c = extensionDescription;
      }
    }
  }
  async startDebugging(configuration2, parentSessionId) {
    const parentSession = this.k.getModel().getSession(parentSessionId);
    return await this.k.startDebugging(void 0, configuration2, { parentSession }, void 0);
  }
  async createDebugAdapter(session) {
    await this.f.activateDebuggers("onDebugAdapterProtocolTracker", this.type);
    const da = this.f.createDebugAdapter(session);
    if (da) {
      return Promise.resolve(da);
    }
    throw new Error(localize(6170, null, this.type));
  }
  async substituteVariables(folder, config) {
    const substitutedConfig = await this.f.substituteVariables(this.type, folder, config);
    return await this.i.resolveWithInteractionReplace(folder, substitutedConfig, "launch", this.variables, substitutedConfig.__configurationTarget);
  }
  runInTerminal(args2, sessionId) {
    return this.f.runInTerminal(this.type, args2, sessionId);
  }
  get label() {
    return this.a.label || this.a.type;
  }
  get type() {
    return this.a.type;
  }
  get variables() {
    return this.a.variables;
  }
  get configurationSnippets() {
    return this.a.configurationSnippets;
  }
  get languages() {
    return this.a.languages;
  }
  get when() {
    return this.d;
  }
  get hiddenWhen() {
    return this.e;
  }
  get enabled() {
    return !this.d || this.l.contextMatchesRules(this.d);
  }
  get isHiddenFromDropdown() {
    if (!this.e) {
      return false;
    }
    return this.l.contextMatchesRules(this.e);
  }
  get strings() {
    return this.a.strings ?? this.a.uiMessages;
  }
  interestedInLanguage(languageId) {
    return !!(this.languages && this.languages.indexOf(languageId) >= 0);
  }
  hasInitialConfiguration() {
    return !!this.a.initialConfigurations;
  }
  hasDynamicConfigurationProviders() {
    return this.k.getConfigurationManager().hasDebugConfigurationProvider(this.type, DebugConfigurationProviderTriggerKind.Dynamic);
  }
  hasConfigurationProvider() {
    return this.k.getConfigurationManager().hasDebugConfigurationProvider(this.type);
  }
  getInitialConfigurationContent(initialConfigs) {
    let initialConfigurations = this.a.initialConfigurations || [];
    if (initialConfigs) {
      initialConfigurations = initialConfigurations.concat(initialConfigs);
    }
    const eol = this.h.getEOL(URI.from({ scheme: Schemas.untitled, path: "1" })) === "\r\n" ? "\r\n" : "\n";
    const configs = JSON.stringify(initialConfigurations, null, "	").split("\n").map((line) => "	" + line).join(eol).trim();
    const comment1 = localize(6171, null);
    const comment2 = localize(6172, null);
    const comment3 = localize(6173, null, "https://go.microsoft.com/fwlink/?linkid=830387");
    let content = [
      "{",
      `	// ${comment1}`,
      `	// ${comment2}`,
      `	// ${comment3}`,
      `	"version": "0.2.0",`,
      `	"configurations": ${configs}`,
      "}"
    ].join(eol);
    const editorConfig = this.g.getValue();
    if (editorConfig.editor && editorConfig.editor.insertSpaces) {
      content = content.replace(new RegExp("	", "g"), " ".repeat(editorConfig.editor.tabSize));
    }
    return Promise.resolve(content);
  }
  getMainExtensionDescriptor() {
    return this.c || this.b[0];
  }
  getCustomTelemetryEndpoint() {
    const aiKey = this.a.aiKey;
    if (!aiKey) {
      return void 0;
    }
    const sendErrorTelemtry = $mw(this.j.remoteAuthority) !== "other";
    return {
      id: `${this.getMainExtensionDescriptor().publisher}.${this.type}`,
      aiKey,
      sendErrorTelemetry: sendErrorTelemtry
    };
  }
  getSchemaAttributes(definitions3) {
    if (!this.a.configurationAttributes) {
      return null;
    }
    return Object.keys(this.a.configurationAttributes).map((request) => {
      const definitionId = `${this.type}:${request}`;
      const platformSpecificDefinitionId = `${this.type}:${request}:platform`;
      const attributes = this.a.configurationAttributes[request];
      const defaultRequired = ["name", "type", "request"];
      attributes.required = attributes.required && attributes.required.length ? defaultRequired.concat(attributes.required) : defaultRequired;
      attributes.additionalProperties = false;
      attributes.type = "object";
      if (!attributes.properties) {
        attributes.properties = {};
      }
      const properties = attributes.properties;
      properties["type"] = {
        enum: [this.type],
        enumDescriptions: [this.label],
        description: localize(6174, null),
        pattern: "^(?!node2)",
        deprecationMessage: this.a.deprecated || (this.enabled ? void 0 : $2R(this.type)),
        doNotSuggest: !!this.a.deprecated,
        errorMessage: localize(6175, null),
        patternErrorMessage: localize(6176, null)
      };
      properties["request"] = {
        enum: [request],
        description: localize(6177, null)
      };
      for (const prop in definitions3["common"].properties) {
        properties[prop] = {
          $ref: `#/definitions/common/properties/${prop}`
        };
      }
      Object.keys(properties).forEach((name) => {
        $abc(properties[name]);
      });
      definitions3[definitionId] = { ...attributes };
      definitions3[platformSpecificDefinitionId] = {
        type: "object",
        additionalProperties: false,
        properties: $Tv(properties, (key2) => key2 !== "type" && key2 !== "request" && key2 !== "name")
      };
      const attributesCopy = { ...attributes };
      attributesCopy.properties = {
        ...properties,
        ...{
          windows: {
            $ref: `#/definitions/${platformSpecificDefinitionId}`,
            description: localize(6178, null)
          },
          osx: {
            $ref: `#/definitions/${platformSpecificDefinitionId}`,
            description: localize(6179, null)
          },
          linux: {
            $ref: `#/definitions/${platformSpecificDefinitionId}`,
            description: localize(6180, null)
          }
        }
      };
      return attributesCopy;
    });
  }
};
$bbc = __decorate([
  __param(3, $kl),
  __param(4, $AG),
  __param(5, $nY),
  __param(6, $US),
  __param(7, $0R),
  __param(8, $on)
], $bbc);

// out-build/vs/workbench/services/configurationResolver/common/configurationResolverSchema.js
var idDescription = localize(12618, null);
var typeDescription = localize(12619, null);
var descriptionDescription = localize(12620, null);
var defaultDescription = localize(12621, null);
var $fbc = {
  definitions: {
    inputs: {
      type: "array",
      description: localize(12622, null),
      items: {
        oneOf: [
          {
            type: "object",
            required: ["id", "type", "description"],
            additionalProperties: false,
            properties: {
              id: {
                type: "string",
                description: idDescription
              },
              type: {
                type: "string",
                description: typeDescription,
                enum: ["promptString"],
                enumDescriptions: [
                  localize(12623, null)
                ]
              },
              description: {
                type: "string",
                description: descriptionDescription
              },
              default: {
                type: "string",
                description: defaultDescription
              },
              password: {
                type: "boolean",
                description: localize(12624, null)
              }
            }
          },
          {
            type: "object",
            required: ["id", "type", "description", "options"],
            additionalProperties: false,
            properties: {
              id: {
                type: "string",
                description: idDescription
              },
              type: {
                type: "string",
                description: typeDescription,
                enum: ["pickString"],
                enumDescriptions: [
                  localize(12625, null)
                ]
              },
              description: {
                type: "string",
                description: descriptionDescription
              },
              default: {
                type: "string",
                description: defaultDescription
              },
              options: {
                type: "array",
                description: localize(12626, null),
                items: {
                  oneOf: [
                    {
                      type: "string"
                    },
                    {
                      type: "object",
                      required: ["value"],
                      additionalProperties: false,
                      properties: {
                        label: {
                          type: "string",
                          description: localize(12627, null)
                        },
                        value: {
                          type: "string",
                          description: localize(12628, null)
                        }
                      }
                    }
                  ]
                }
              }
            }
          },
          {
            type: "object",
            required: ["id", "type", "command"],
            additionalProperties: false,
            properties: {
              id: {
                type: "string",
                description: idDescription
              },
              type: {
                type: "string",
                description: typeDescription,
                enum: ["command"],
                enumDescriptions: [
                  localize(12629, null)
                ]
              },
              command: {
                type: "string",
                description: localize(12630, null)
              },
              args: {
                oneOf: [
                  {
                    type: "object",
                    description: localize(12631, null)
                  },
                  {
                    type: "array",
                    description: localize(12632, null)
                  },
                  {
                    type: "string",
                    description: localize(12633, null)
                  }
                ]
              }
            }
          }
        ]
      }
    }
  }
};

// out-build/vs/workbench/contrib/debug/common/debugSchemas.js
var $gbc = $tN.registerExtensionPoint({
  extensionPoint: "debuggers",
  defaultExtensionKind: ["workspace"],
  jsonSchema: {
    description: localize(6191, null),
    type: "array",
    defaultSnippets: [{ body: [{ type: "" }] }],
    items: {
      additionalProperties: false,
      type: "object",
      defaultSnippets: [{ body: { type: "", program: "", runtime: "" } }],
      properties: {
        type: {
          description: localize(6192, null),
          type: "string"
        },
        label: {
          description: localize(6193, null),
          type: "string"
        },
        program: {
          description: localize(6194, null),
          type: "string"
        },
        args: {
          description: localize(6195, null),
          type: "array"
        },
        runtime: {
          description: localize(6196, null),
          type: "string"
        },
        runtimeArgs: {
          description: localize(6197, null),
          type: "array"
        },
        variables: {
          description: localize(6198, null),
          type: "object"
        },
        initialConfigurations: {
          description: localize(6199, null),
          type: ["array", "string"]
        },
        languages: {
          description: localize(6200, null),
          type: "array"
        },
        configurationSnippets: {
          description: localize(6201, null),
          type: "array"
        },
        configurationAttributes: {
          description: localize(6202, null),
          type: "object"
        },
        when: {
          description: localize(6203, null),
          type: "string",
          default: ""
        },
        hiddenWhen: {
          description: localize(6204, null),
          type: "string",
          default: ""
        },
        deprecated: {
          description: localize(6205, null),
          type: "string",
          default: ""
        },
        windows: {
          description: localize(6206, null),
          type: "object",
          properties: {
            runtime: {
              description: localize(6207, null),
              type: "string"
            }
          }
        },
        osx: {
          description: localize(6208, null),
          type: "object",
          properties: {
            runtime: {
              description: localize(6209, null),
              type: "string"
            }
          }
        },
        linux: {
          description: localize(6210, null),
          type: "object",
          properties: {
            runtime: {
              description: localize(6211, null),
              type: "string"
            }
          }
        },
        strings: {
          description: localize(6212, null),
          type: "object",
          properties: {
            unverifiedBreakpoints: {
              description: localize(6213, null),
              type: "string"
            }
          }
        }
      }
    }
  }
});
var $hbc = $tN.registerExtensionPoint({
  extensionPoint: "breakpoints",
  jsonSchema: {
    description: localize(6214, null),
    type: "array",
    defaultSnippets: [{ body: [{ language: "" }] }],
    items: {
      type: "object",
      additionalProperties: false,
      defaultSnippets: [{ body: { language: "" } }],
      properties: {
        language: {
          description: localize(6215, null),
          type: "string"
        },
        when: {
          description: localize(6216, null),
          type: "string",
          default: ""
        }
      }
    }
  }
});
var $ibc = {
  type: "object",
  description: localize(6217, null),
  properties: {
    hidden: {
      type: "boolean",
      default: false,
      description: localize(6218, null)
    },
    group: {
      type: "string",
      default: "",
      description: localize(6219, null)
    },
    order: {
      type: "number",
      default: 1,
      description: localize(6220, null)
    }
  },
  default: {
    hidden: false,
    group: "",
    order: 1
  }
};
var defaultCompound = { name: "Compound", configurations: [] };
var $jbc = {
  id: $rK,
  type: "object",
  title: localize(6221, null),
  allowTrailingCommas: true,
  allowComments: true,
  required: [],
  default: { version: "0.2.0", configurations: [], compounds: [] },
  properties: {
    version: {
      type: "string",
      description: localize(6222, null),
      default: "0.2.0"
    },
    configurations: {
      type: "array",
      description: localize(6223, null),
      items: {
        defaultSnippets: [],
        "type": "object",
        oneOf: []
      }
    },
    compounds: {
      type: "array",
      description: localize(6224, null),
      items: {
        type: "object",
        required: ["name", "configurations"],
        properties: {
          name: {
            type: "string",
            description: localize(6225, null)
          },
          presentation: $ibc,
          configurations: {
            type: "array",
            default: [],
            items: {
              oneOf: [{
                enum: [],
                description: localize(6226, null)
              }, {
                type: "object",
                required: ["name"],
                properties: {
                  name: {
                    enum: [],
                    description: localize(6227, null)
                  },
                  folder: {
                    enum: [],
                    description: localize(6228, null)
                  }
                }
              }]
            },
            description: localize(6229, null)
          },
          stopAll: {
            type: "boolean",
            default: false,
            description: localize(6230, null)
          },
          preLaunchTask: {
            type: "string",
            default: "",
            description: localize(6231, null)
          }
        },
        default: defaultCompound
      },
      default: [
        defaultCompound
      ]
    },
    inputs: $fbc.definitions.inputs
  }
};
var DebuggersDataRenderer = class extends $3c {
  constructor() {
    super(...arguments);
    this.type = "table";
  }
  shouldRender(manifest) {
    return !!manifest.contributes?.debuggers;
  }
  render(manifest) {
    const contrib = manifest.contributes?.debuggers || [];
    if (!contrib.length) {
      return { data: { headers: [], rows: [] }, dispose: () => {
      } };
    }
    const headers = [
      localize(6232, null),
      localize(6233, null)
    ];
    const rows = contrib.map((d) => {
      return [
        d.label ?? "",
        d.type
      ];
    });
    return {
      data: {
        headers,
        rows
      },
      dispose: () => {
      }
    };
  }
};
$Wn.as(Extensions3.ExtensionFeaturesRegistry).registerExtensionFeature({
  id: "debuggers",
  label: localize(6234, null),
  access: {
    canToggle: false
  },
  renderer: new $Nk(DebuggersDataRenderer)
});

// out-build/vs/workbench/contrib/debug/browser/debugAdapterManager.js
var jsonRegistry2 = $Wn.as($Xn.JSONContribution);
var $kbc = class $kbc2 extends $3c {
  constructor(z, C, D, F, G, H, I, J, L, M, N, O, P) {
    super();
    this.z = z;
    this.C = C;
    this.D = D;
    this.F = F;
    this.G = G;
    this.H = H;
    this.I = I;
    this.J = J;
    this.L = L;
    this.M = M;
    this.N = N;
    this.O = O;
    this.P = P;
    this.g = /* @__PURE__ */ new Map();
    this.m = new $ze();
    this.n = new $ze();
    this.r = [];
    this.t = /* @__PURE__ */ new Set();
    this.u = [];
    this.y = /* @__PURE__ */ new Set();
    this.f = [];
    this.b = [];
    this.Q();
    this.J.bufferChangeEvents(() => {
      this.h = $BR.bindTo(J);
      this.j = $CR.bindTo(J);
    });
    this.B(this.J.onDidChangeContext((e) => {
      if (e.affectsSome(this.t)) {
        this.h.set(this.hasEnabledDebuggers());
        this.S();
      }
    }));
    this.B(this.onDidDebuggersExtPointRead(() => {
      this.j.set(this.b.length > 0);
    }));
    const updateTaskScheduler = this.B(new $8h(() => this.R(), 5e3));
    this.B(Event2.any(O.onDidChangeTaskConfig, O.onDidChangeTaskProviders)(() => {
      updateTaskScheduler.cancel();
      updateTaskScheduler.schedule();
    }));
    this.N.when(
      4
      /* LifecyclePhase.Eventually */
    ).then(() => this.j.set(this.b.length > 0));
    this.B(z.onDidNewSession((s) => {
      this.y.add(s.configuration.type);
    }));
    updateTaskScheduler.schedule();
  }
  Q() {
    $gbc.setHandler((extensions, delta) => {
      delta.added.forEach((added) => {
        added.value.forEach((rawAdapter) => {
          if (!rawAdapter.type || typeof rawAdapter.type !== "string") {
            added.collector.error(localize(5743, null));
          }
          if (rawAdapter.type !== "*") {
            const existing = this.getDebugger(rawAdapter.type);
            if (existing) {
              existing.merge(rawAdapter, added.description);
            } else {
              const dbg = this.G.createInstance($bbc, this, rawAdapter, added.description);
              dbg.when?.keys().forEach((key2) => this.t.add(key2));
              this.b.push(dbg);
            }
          }
        });
      });
      extensions.forEach((extension) => {
        extension.value.forEach((rawAdapter) => {
          if (rawAdapter.type === "*") {
            this.b.forEach((dbg) => dbg.merge(rawAdapter, extension.description));
          }
        });
      });
      delta.removed.forEach((removed) => {
        const removedTypes = removed.value.map((rawAdapter) => rawAdapter.type);
        this.b = this.b.filter((d) => removedTypes.indexOf(d.type) === -1);
      });
      this.S();
      this.n.fire();
    });
    $hbc.setHandler((extensions) => {
      this.r = extensions.flatMap((ext) => ext.value.map((breakpoint) => this.G.createInstance($ebc, breakpoint)));
    });
  }
  R() {
    this.O.getKnownTasks().then((tasks2) => {
      this.u = tasks2.map((task) => task._label);
      this.S();
    });
  }
  S() {
    const items = $jbc.properties["configurations"].items;
    const taskSchema = $aQ.getJsonSchema();
    const definitions3 = {
      "common": {
        properties: {
          "name": {
            type: "string",
            description: localize(5744, null),
            default: "Launch"
          },
          "debugServer": {
            type: "number",
            description: localize(5745, null),
            default: 4711
          },
          "preLaunchTask": {
            anyOf: [taskSchema, {
              type: ["string"]
            }],
            default: "",
            defaultSnippets: [{ body: { task: "", type: "" } }],
            description: localize(5746, null),
            examples: this.u
          },
          "postDebugTask": {
            anyOf: [taskSchema, {
              type: ["string"]
            }],
            default: "",
            defaultSnippets: [{ body: { task: "", type: "" } }],
            description: localize(5747, null),
            examples: this.u
          },
          "presentation": $ibc,
          "internalConsoleOptions": $6R,
          "suppressMultipleSessionWarning": {
            type: "boolean",
            description: localize(5748, null),
            default: true
          }
        }
      }
    };
    $jbc.definitions = definitions3;
    items.oneOf = [];
    items.defaultSnippets = [];
    this.b.forEach((adapter) => {
      const schemaAttributes = adapter.getSchemaAttributes(definitions3);
      if (schemaAttributes && items.oneOf) {
        items.oneOf.push(...schemaAttributes);
      }
      const configurationSnippets = adapter.configurationSnippets;
      if (configurationSnippets && items.defaultSnippets) {
        items.defaultSnippets.push(...configurationSnippets);
      }
    });
    jsonRegistry2.registerSchema($rK, $jbc);
  }
  registerDebugAdapterFactory(debugTypes, debugAdapterLauncher) {
    debugTypes.forEach((debugType) => this.g.set(debugType, debugAdapterLauncher));
    this.h.set(this.hasEnabledDebuggers());
    this.m.fire();
    return {
      dispose: () => {
        debugTypes.forEach((debugType) => this.g.delete(debugType));
      }
    };
  }
  hasEnabledDebuggers() {
    for (const [type] of this.g) {
      const dbg = this.getDebugger(type);
      if (dbg && dbg.enabled) {
        return true;
      }
    }
    return false;
  }
  createDebugAdapter(session) {
    const factory = this.g.get(session.configuration.type);
    if (factory) {
      return factory.createDebugAdapter(session);
    }
    return void 0;
  }
  substituteVariables(debugType, folder, config) {
    const factory = this.g.get(debugType);
    if (factory) {
      return factory.substituteVariables(folder, config);
    }
    return Promise.resolve(config);
  }
  runInTerminal(debugType, args2, sessionId) {
    const factory = this.g.get(debugType);
    if (factory) {
      return factory.runInTerminal(args2, sessionId);
    }
    return Promise.resolve(void 0);
  }
  registerDebugAdapterDescriptorFactory(debugAdapterProvider) {
    this.f.push(debugAdapterProvider);
    return {
      dispose: () => {
        this.unregisterDebugAdapterDescriptorFactory(debugAdapterProvider);
      }
    };
  }
  unregisterDebugAdapterDescriptorFactory(debugAdapterProvider) {
    const ix = this.f.indexOf(debugAdapterProvider);
    if (ix >= 0) {
      this.f.splice(ix, 1);
    }
  }
  getDebugAdapterDescriptor(session) {
    const config = session.configuration;
    const providers2 = this.f.filter((p) => p.type === config.type && p.createDebugAdapterDescriptor);
    if (providers2.length === 1) {
      return providers2[0].createDebugAdapterDescriptor(session);
    } else {
    }
    return Promise.resolve(void 0);
  }
  getDebuggerLabel(type) {
    const dbgr = this.getDebugger(type);
    if (dbgr) {
      return dbgr.label;
    }
    return void 0;
  }
  get onDidRegisterDebugger() {
    return this.m.event;
  }
  get onDidDebuggersExtPointRead() {
    return this.n.event;
  }
  canSetBreakpointsIn(model) {
    const languageId = model.getLanguageId();
    if (!languageId || languageId === "jsonc" || languageId === "log") {
      return false;
    }
    if (this.D.getValue("debug").allowBreakpointsEverywhere) {
      return true;
    }
    return this.r.some((breakpoints) => breakpoints.language === languageId && breakpoints.enabled);
  }
  getDebugger(type) {
    return this.b.find((dbg) => $1f(dbg.type, type));
  }
  getEnabledDebugger(type) {
    const adapter = this.getDebugger(type);
    return adapter && adapter.enabled ? adapter : void 0;
  }
  someDebuggerInterestedInLanguage(languageId) {
    return !!this.b.filter((d) => d.enabled).find((a) => a.interestedInLanguage(languageId));
  }
  async guessDebugger(gettingConfigurations) {
    const activeTextEditorControl = this.C.activeTextEditorControl;
    let candidates = [];
    let languageLabel = null;
    let model = null;
    if ($P5(activeTextEditorControl)) {
      model = activeTextEditorControl.getModel();
      const language = model ? model.getLanguageId() : void 0;
      if (language) {
        languageLabel = this.L.getLanguageName(language);
      }
      const adapters = this.b.filter((a) => a.enabled).filter((a) => language && a.interestedInLanguage(language));
      if (adapters.length === 1) {
        return { debugger: adapters[0] };
      }
      if (adapters.length > 1) {
        candidates = adapters;
      }
    }
    if ((!languageLabel || gettingConfigurations || model && this.canSetBreakpointsIn(model)) && candidates.length === 0) {
      await this.activateDebuggers("onDebugInitialConfigurations");
      candidates = this.b.filter((a) => a.enabled).filter((dbg) => dbg.hasInitialConfiguration() || dbg.hasDynamicConfigurationProviders() || dbg.hasConfigurationProvider());
    }
    if (candidates.length === 0 && languageLabel) {
      if (languageLabel.indexOf(" ") >= 0) {
        languageLabel = `'${languageLabel}'`;
      }
      const { confirmed } = await this.M.confirm({
        type: severity_default.Warning,
        message: localize(5749, null, languageLabel),
        primaryButton: localize(5750, null, languageLabel)
      });
      if (confirmed) {
        await this.H.executeCommand("debug.installAdditionalDebuggers", languageLabel);
      }
      return void 0;
    }
    this.U();
    candidates.sort((first, second) => first.label.localeCompare(second.label));
    candidates = candidates.filter((a) => !a.isHiddenFromDropdown);
    const suggestedCandidates = [];
    const otherCandidates = [];
    candidates.forEach((d) => {
      const descriptor = d.getMainExtensionDescriptor();
      if (descriptor.id && !!this.w?.has(descriptor.id)) {
        suggestedCandidates.push(d);
      } else if (this.y.has(d.type)) {
        suggestedCandidates.push(d);
      } else {
        otherCandidates.push(d);
      }
    });
    const picks = [];
    const dynamic = await this.z.configurationManager().getDynamicProviders();
    if (suggestedCandidates.length > 0) {
      picks.push({ type: "separator", label: localize(5751, null) }, ...suggestedCandidates.map((c) => ({ label: c.label, pick: () => ({ debugger: c }) })));
    }
    if (otherCandidates.length > 0) {
      if (picks.length > 0) {
        picks.push({ type: "separator", label: "" });
      }
      picks.push(...otherCandidates.map((c) => ({ label: c.label, pick: () => ({ debugger: c }) })));
    }
    if (dynamic.length) {
      if (picks.length) {
        picks.push({ type: "separator", label: "" });
      }
      for (const d of dynamic) {
        picks.push({
          label: localize(5752, null, d.label),
          pick: async () => {
            const cfg = await d.pick();
            if (!cfg) {
              return void 0;
            }
            return cfg && { debugger: this.getDebugger(d.type), withConfig: cfg };
          }
        });
      }
    }
    picks.push({ type: "separator", label: "" }, { label: languageLabel ? localize(5753, null, languageLabel) : localize(5754, null) });
    const contributed = this.P.getMenuActions($bJ.DebugCreateConfiguration, this.J);
    for (const [, action] of contributed) {
      for (const item of action) {
        picks.push(item);
      }
    }
    const placeHolder = localize(5755, null);
    return this.F.pick(picks, { activeItem: picks[0], placeHolder }).then(async (picked) => {
      if (picked && "pick" in picked && typeof picked.pick === "function") {
        return await picked.pick();
      }
      if (picked instanceof $fJ) {
        picked.run();
        return;
      }
      if (picked) {
        this.H.executeCommand("debug.installAdditionalDebuggers", languageLabel);
      }
      return void 0;
    });
  }
  U() {
    if (!this.w) {
      this.w = /* @__PURE__ */ new Set();
      const status = this.I.getExtensionsStatus();
      for (const id2 in status) {
        if (!!status[id2].activationTimes) {
          this.w.add(id2);
        }
      }
    }
  }
  async activateDebuggers(activationEvent, debugType) {
    this.U();
    const promises = [
      this.I.activateByEvent(activationEvent),
      this.I.activateByEvent("onDebug")
    ];
    if (debugType) {
      promises.push(this.I.activateByEvent(`${activationEvent}:${debugType}`));
    }
    await Promise.all(promises);
  }
};
$kbc = __decorate([
  __param(1, $mJ),
  __param(2, $kl),
  __param(3, $1M),
  __param(4, $Pk),
  __param(5, $sn),
  __param(6, $wN),
  __param(7, $on),
  __param(8, $1E),
  __param(9, $Yv),
  __param(10, $KL),
  __param(11, $3Sb),
  __param(12, $cJ)
], $kbc);

// out-build/vs/workbench/contrib/debug/browser/debugConfigurationManager.js
var jsonRegistry3 = $Wn.as($Xn.JSONContribution);
jsonRegistry3.registerSchema($rK, $jbc);
var DEBUG_SELECTED_CONFIG_NAME_KEY = "debug.selectedconfigname";
var DEBUG_SELECTED_ROOT = "debug.selectedroot";
var DEBUG_SELECTED_TYPE = "debug.selectedtype";
var DEBUG_RECENT_DYNAMIC_CONFIGURATIONS = "debug.recentdynamicconfigurations";
var ON_DEBUG_DYNAMIC_CONFIGURATIONS_NAME = "onDebugDynamicConfigurations";
var $lbc = class $lbc2 {
  constructor(r2, s, u, v, w, x, y, z, A, contextKeyService, B) {
    this.r = r2;
    this.s = s;
    this.u = u;
    this.v = v;
    this.w = w;
    this.x = x;
    this.y = y;
    this.z = z;
    this.A = A;
    this.B = B;
    this.g = () => Promise.resolve(void 0);
    this.j = false;
    this.m = new $ze();
    this.q = new $ze();
    this.onDidChangeConfigurationProviders = this.q.event;
    this.n = [];
    this.k = [this.q];
    this.D();
    this.E();
    this.C();
    const previousSelectedRoot = this.x.get(
      DEBUG_SELECTED_ROOT,
      1
      /* StorageScope.WORKSPACE */
    );
    const previousSelectedType = this.x.get(
      DEBUG_SELECTED_TYPE,
      1
      /* StorageScope.WORKSPACE */
    );
    const previousSelectedLaunch = this.a.find((l) => l.uri.toString() === previousSelectedRoot);
    const previousSelectedName = this.x.get(
      DEBUG_SELECTED_CONFIG_NAME_KEY,
      1
      /* StorageScope.WORKSPACE */
    );
    this.o = $4Q.bindTo(contextKeyService);
    const dynamicConfig = previousSelectedType ? { type: previousSelectedType } : void 0;
    if (previousSelectedLaunch && previousSelectedLaunch.getConfigurationNames().length) {
      this.selectConfiguration(previousSelectedLaunch, previousSelectedName, void 0, dynamicConfig);
    } else if (this.a.length > 0) {
      this.selectConfiguration(void 0, previousSelectedName, void 0, dynamicConfig);
    }
  }
  registerDebugConfigurationProvider(debugConfigurationProvider) {
    this.n.push(debugConfigurationProvider);
    this.q.fire();
    return {
      dispose: () => {
        this.unregisterDebugConfigurationProvider(debugConfigurationProvider);
        this.q.fire();
      }
    };
  }
  unregisterDebugConfigurationProvider(debugConfigurationProvider) {
    const ix = this.n.indexOf(debugConfigurationProvider);
    if (ix >= 0) {
      this.n.splice(ix, 1);
    }
  }
  /**
   * if scope is not specified,a value of DebugConfigurationProvideTrigger.Initial is assumed.
   */
  hasDebugConfigurationProvider(debugType, triggerKind) {
    if (triggerKind === void 0) {
      triggerKind = DebugConfigurationProviderTriggerKind.Initial;
    }
    const provider = this.n.find((p) => p.provideDebugConfigurations && p.type === debugType && p.triggerKind === triggerKind);
    return !!provider;
  }
  async resolveConfigurationByProviders(folderUri, type, config, token) {
    const resolveDebugConfigurationForType = async (type2, config2) => {
      if (type2 !== "*") {
        await this.r.activateDebuggers("onDebugResolve", type2);
      }
      for (const p of this.n) {
        if (p.type === type2 && p.resolveDebugConfiguration && config2) {
          config2 = await p.resolveDebugConfiguration(folderUri, config2, token);
        }
      }
      return config2;
    };
    let resolvedType = config.type ?? type;
    let result = config;
    for (let seen = /* @__PURE__ */ new Set(); result && !seen.has(resolvedType); ) {
      seen.add(resolvedType);
      result = await resolveDebugConfigurationForType(resolvedType, result);
      result = await resolveDebugConfigurationForType("*", result);
      resolvedType = result?.type ?? type;
    }
    return result;
  }
  async resolveDebugConfigurationWithSubstitutedVariables(folderUri, type, config, token) {
    const providers2 = this.n.filter((p) => p.type === type && p.resolveDebugConfigurationWithSubstitutedVariables).concat(this.n.filter((p) => p.type === "*" && p.resolveDebugConfigurationWithSubstitutedVariables));
    let result = config;
    await $Yh(providers2.map((provider) => async () => {
      if (result) {
        result = await provider.resolveDebugConfigurationWithSubstitutedVariables(folderUri, result, token);
      }
    }));
    return result;
  }
  async provideDebugConfigurations(folderUri, type, token) {
    await this.r.activateDebuggers("onDebugInitialConfigurations");
    const results = await Promise.all(this.n.filter((p) => p.type === type && p.triggerKind === DebugConfigurationProviderTriggerKind.Initial && p.provideDebugConfigurations).map((p) => p.provideDebugConfigurations(folderUri, token)));
    return results.reduce((first, second) => first.concat(second), []);
  }
  async getDynamicProviders() {
    await this.y.whenInstalledExtensionsRegistered();
    const debugDynamicExtensionsTypes = this.y.extensions.reduce((acc, e) => {
      if (!e.activationEvents) {
        return acc;
      }
      const explicitTypes = [];
      let hasGenericEvent = false;
      for (const event of e.activationEvents) {
        if (event === ON_DEBUG_DYNAMIC_CONFIGURATIONS_NAME) {
          hasGenericEvent = true;
        } else if (event.startsWith(`${ON_DEBUG_DYNAMIC_CONFIGURATIONS_NAME}:`)) {
          explicitTypes.push(event.slice(ON_DEBUG_DYNAMIC_CONFIGURATIONS_NAME.length + 1));
        }
      }
      if (explicitTypes.length) {
        explicitTypes.forEach((t) => acc.add(t));
      } else if (hasGenericEvent) {
        const debuggerType = e.contributes?.debuggers?.[0].type;
        if (debuggerType) {
          acc.add(debuggerType);
        }
      }
      return acc;
    }, /* @__PURE__ */ new Set());
    for (const configProvider of this.n) {
      if (configProvider.triggerKind === DebugConfigurationProviderTriggerKind.Dynamic) {
        debugDynamicExtensionsTypes.add(configProvider.type);
      }
    }
    return [...debugDynamicExtensionsTypes].map((type) => {
      return {
        label: this.r.getDebuggerLabel(type),
        getProvider: async () => {
          await this.r.activateDebuggers(ON_DEBUG_DYNAMIC_CONFIGURATIONS_NAME, type);
          return this.n.find((p) => p.type === type && p.triggerKind === DebugConfigurationProviderTriggerKind.Dynamic && p.provideDebugConfigurations);
        },
        type,
        pick: async () => {
          await this.r.activateDebuggers(ON_DEBUG_DYNAMIC_CONFIGURATIONS_NAME, type);
          const disposables = new $2c();
          const token = new $ad();
          disposables.add(token);
          const input = disposables.add(this.v.createQuickPick());
          input.busy = true;
          input.placeholder = localize(5802, null);
          const chosenPromise = new Promise((resolve) => {
            disposables.add(input.onDidAccept(() => resolve(input.activeItems[0])));
            disposables.add(input.onDidTriggerItemButton(async (context) => {
              resolve(void 0);
              const { launch, config } = context.item;
              await launch.openConfigFile({ preserveFocus: false, type: config.type, suppressInitialConfigs: true });
              await launch.writeConfiguration(config);
              await this.selectConfiguration(launch, config.name);
              this.removeRecentDynamicConfigurations(config.name, config.type);
            }));
            disposables.add(input.onDidHide(() => resolve(void 0)));
          }).finally(() => token.cancel());
          let items;
          try {
            items = await this.getDynamicConfigurationsByType(type, token.token);
          } catch (err) {
            this.B.error(err);
            disposables.dispose();
            return;
          }
          input.items = items;
          input.busy = false;
          input.show();
          const chosen = await chosenPromise;
          disposables.dispose();
          return chosen;
        }
      };
    });
  }
  async getDynamicConfigurationsByType(type, token = CancellationToken.None) {
    await this.r.activateDebuggers(ON_DEBUG_DYNAMIC_CONFIGURATIONS_NAME, type);
    const picks = [];
    const provider = this.n.find((p) => p.type === type && p.triggerKind === DebugConfigurationProviderTriggerKind.Dynamic && p.provideDebugConfigurations);
    this.getLaunches().forEach((launch) => {
      if (provider) {
        picks.push(provider.provideDebugConfigurations(launch.workspace?.uri, token).then((configurations) => configurations.map((config) => ({
          label: config.name,
          description: launch.name,
          config,
          buttons: [{
            iconClass: ThemeIcon.asClassName($1Fb),
            tooltip: localize(5803, null)
          }],
          launch
        }))));
      }
    });
    return (await Promise.all(picks)).flat();
  }
  getAllConfigurations() {
    const all = [];
    for (const l of this.a) {
      for (const name of l.getConfigurationNames()) {
        const config = l.getConfiguration(name) || l.getCompound(name);
        if (config) {
          all.push({ launch: l, name, presentation: config.presentation });
        }
      }
    }
    return $xP(all);
  }
  removeRecentDynamicConfigurations(name, type) {
    const remaining = this.getRecentDynamicConfigurations().filter((c) => c.name !== name || c.type !== type);
    this.x.store(
      DEBUG_RECENT_DYNAMIC_CONFIGURATIONS,
      JSON.stringify(remaining),
      1,
      1
      /* StorageTarget.MACHINE */
    );
    if (this.selectedConfiguration.name === name && this.h === type && this.j) {
      this.selectConfiguration(void 0, void 0);
    } else {
      this.m.fire();
    }
  }
  getRecentDynamicConfigurations() {
    return JSON.parse(this.x.get(DEBUG_RECENT_DYNAMIC_CONFIGURATIONS, 1, "[]"));
  }
  C() {
    this.k.push(Event2.any(this.s.onDidChangeWorkspaceFolders, this.s.onDidChangeWorkbenchState)(() => {
      this.D();
      this.selectConfiguration(void 0);
      this.E();
    }));
    this.k.push(this.u.onDidChangeConfiguration(async (e) => {
      if (e.affectsConfiguration("launch")) {
        await this.selectConfiguration(void 0);
        this.E();
      }
    }));
    this.k.push(this.r.onDidDebuggersExtPointRead(() => {
      this.E();
    }));
  }
  D() {
    this.a = this.s.getWorkspace().folders.map((folder) => this.w.createInstance(Launch, this, this.r, folder));
    if (this.s.getWorkbenchState() === 3) {
      this.a.push(this.w.createInstance(WorkspaceLaunch, this, this.r));
    }
    this.a.push(this.w.createInstance(UserLaunch, this, this.r));
    if (this.d && this.a.indexOf(this.d) === -1) {
      this.selectConfiguration(void 0);
    }
  }
  E() {
    const compoundConfigurationsSchema = $jbc.properties["compounds"].items.properties["configurations"];
    const launchNames = this.a.map((l) => l.getConfigurationNames(true)).reduce((first, second) => first.concat(second), []);
    compoundConfigurationsSchema.items.oneOf[0].enum = launchNames;
    compoundConfigurationsSchema.items.oneOf[1].properties.name.enum = launchNames;
    const folderNames = this.s.getWorkspace().folders.map((f) => f.name);
    compoundConfigurationsSchema.items.oneOf[1].properties.folder.enum = folderNames;
    jsonRegistry3.registerSchema($rK, $jbc);
  }
  getLaunches() {
    return this.a;
  }
  getLaunch(workspaceUri) {
    if (!URI.isUri(workspaceUri)) {
      return void 0;
    }
    return this.a.find((l) => l.workspace && this.A.extUri.isEqual(l.workspace.uri, workspaceUri));
  }
  get selectedConfiguration() {
    return {
      launch: this.d,
      name: this.b,
      getConfig: this.g,
      type: this.h
    };
  }
  get onDidSelectConfiguration() {
    return this.m.event;
  }
  getWorkspaceLaunch() {
    if (this.s.getWorkbenchState() === 3) {
      return this.a[this.a.length - 1];
    }
    return void 0;
  }
  async selectConfiguration(launch, name, config, dynamicConfig) {
    if (typeof launch === "undefined") {
      const rootUri = this.z.getLastActiveWorkspaceRoot();
      launch = this.getLaunch(rootUri);
      if (!launch || launch.getConfigurationNames().length === 0) {
        launch = this.a.find((l) => !!(l && l.getConfigurationNames().length)) || launch || this.a[0];
      }
    }
    const previousLaunch = this.d;
    const previousName = this.b;
    const previousSelectedDynamic = this.j;
    this.d = launch;
    if (this.d) {
      this.x.store(
        DEBUG_SELECTED_ROOT,
        this.d.uri.toString(),
        1,
        1
        /* StorageTarget.MACHINE */
      );
    } else {
      this.x.remove(
        DEBUG_SELECTED_ROOT,
        1
        /* StorageScope.WORKSPACE */
      );
    }
    const names = launch ? launch.getConfigurationNames() : [];
    this.g = () => {
      const selected = this.b ? launch?.getConfiguration(this.b) : void 0;
      return Promise.resolve(selected || config);
    };
    let type = config?.type;
    if (name && names.indexOf(name) >= 0) {
      this.F(name);
    } else if (dynamicConfig && dynamicConfig.type) {
      type = dynamicConfig.type;
      if (!config) {
        const providers2 = (await this.getDynamicProviders()).filter((p) => p.type === type);
        this.g = async () => {
          const activatedProviders = await Promise.all(providers2.map((p) => p.getProvider()));
          const provider = activatedProviders.length > 0 ? activatedProviders[0] : void 0;
          if (provider && launch && launch.workspace) {
            const token = new $ad();
            const dynamicConfigs = await provider.provideDebugConfigurations(launch.workspace.uri, token.token);
            const dynamicConfig2 = dynamicConfigs.find((c) => c.name === name);
            if (dynamicConfig2) {
              return dynamicConfig2;
            }
          }
          return void 0;
        };
      }
      this.F(name);
      let recentDynamicProviders = this.getRecentDynamicConfigurations();
      if (name && dynamicConfig.type) {
        recentDynamicProviders.unshift({ name, type: dynamicConfig.type });
        recentDynamicProviders = $Rb(recentDynamicProviders, (t) => `${t.name} : ${t.type}`);
        this.x.store(
          DEBUG_RECENT_DYNAMIC_CONFIGURATIONS,
          JSON.stringify(recentDynamicProviders),
          1,
          1
          /* StorageTarget.MACHINE */
        );
      }
    } else if (!this.b || names.indexOf(this.b) === -1) {
      const nameToSet = names.length ? names[0] : void 0;
      this.F(nameToSet);
    }
    if (!config && launch && this.b) {
      config = launch.getConfiguration(this.b);
      type = config?.type;
    }
    this.h = dynamicConfig?.type || config?.type;
    this.j = !!dynamicConfig;
    this.x.store(
      DEBUG_SELECTED_TYPE,
      dynamicConfig ? this.h : void 0,
      1,
      1
      /* StorageTarget.MACHINE */
    );
    if (type) {
      this.o.set(type);
    } else {
      this.o.reset();
    }
    if (this.d !== previousLaunch || this.b !== previousName || previousSelectedDynamic !== this.j) {
      this.m.fire();
    }
  }
  F(selectedName) {
    this.b = selectedName;
    if (this.b) {
      this.x.store(
        DEBUG_SELECTED_CONFIG_NAME_KEY,
        this.b,
        1,
        1
        /* StorageTarget.MACHINE */
      );
    } else {
      this.x.remove(
        DEBUG_SELECTED_CONFIG_NAME_KEY,
        1
        /* StorageScope.WORKSPACE */
      );
    }
  }
  dispose() {
    this.k = $Xc(this.k);
  }
};
$lbc = __decorate([
  __param(1, $Zk),
  __param(2, $kl),
  __param(3, $1M),
  __param(4, $Pk),
  __param(5, $jv),
  __param(6, $wN),
  __param(7, $tY),
  __param(8, $vl),
  __param(9, $on),
  __param(10, $wn)
], $lbc);
var AbstractLaunch = class {
  constructor(b, d) {
    this.b = b;
    this.d = d;
  }
  getCompound(name) {
    const config = this.a();
    if (!config || !config.compounds) {
      return void 0;
    }
    return config.compounds.find((compound) => compound.name === name);
  }
  getConfigurationNames(ignoreCompoundsAndPresentation = false) {
    const config = this.a();
    if (!config || !Array.isArray(config.configurations) && !Array.isArray(config.compounds)) {
      return [];
    } else {
      const configurations = [];
      if (config.configurations) {
        configurations.push(...config.configurations.filter((cfg) => cfg && typeof cfg.name === "string"));
      }
      if (ignoreCompoundsAndPresentation) {
        return configurations.map((c) => c.name);
      }
      if (config.compounds) {
        configurations.push(...config.compounds.filter((compound) => typeof compound.name === "string" && compound.configurations && compound.configurations.length));
      }
      return $xP(configurations).map((c) => c.name);
    }
  }
  getConfiguration(name) {
    const config = $Lv(this.a());
    if (!config || !config.configurations) {
      return void 0;
    }
    const configuration2 = config.configurations.find((config2) => config2 && config2.name === name);
    if (configuration2) {
      if (this instanceof UserLaunch) {
        configuration2.__configurationTarget = 2;
      } else if (this instanceof WorkspaceLaunch) {
        configuration2.__configurationTarget = 5;
      } else {
        configuration2.__configurationTarget = 6;
      }
    }
    return configuration2;
  }
  async getInitialConfigurationContent(folderUri, type, useInitialConfigs, token) {
    let content = "";
    const adapter = type ? { debugger: this.d.getEnabledDebugger(type) } : await this.d.guessDebugger(true);
    if (adapter?.withConfig && adapter.debugger) {
      content = await adapter.debugger.getInitialConfigurationContent([adapter.withConfig.config]);
    } else if (adapter?.debugger) {
      const initialConfigs = useInitialConfigs ? await this.b.provideDebugConfigurations(folderUri, adapter.debugger.type, token || CancellationToken.None) : [];
      content = await adapter.debugger.getInitialConfigurationContent(initialConfigs);
    }
    return content;
  }
  get hidden() {
    return false;
  }
};
var Launch = class Launch2 extends AbstractLaunch {
  constructor(configurationManager, adapterManager, workspace2, g, h3, j, k) {
    super(configurationManager, adapterManager);
    this.workspace = workspace2;
    this.g = g;
    this.h = h3;
    this.j = j;
    this.k = k;
  }
  get uri() {
    return $vh(this.workspace.uri, "/.vscode/launch.json");
  }
  get name() {
    return this.workspace.name;
  }
  a() {
    return this.k.inspect("launch", { resource: this.workspace.uri }).workspaceFolderValue;
  }
  async openConfigFile({ preserveFocus, type, suppressInitialConfigs }, token) {
    const resource = this.uri;
    let created2 = false;
    let content = "";
    try {
      const fileContent = await this.g.readFile(resource);
      content = fileContent.value.toString();
    } catch {
      content = await this.getInitialConfigurationContent(this.workspace.uri, type, !suppressInitialConfigs, token);
      if (!content) {
        return { editor: null, created: false };
      }
      created2 = true;
      try {
        await this.h.write(resource, content);
      } catch (error) {
        throw new Error(localize(5804, null, error.message));
      }
    }
    const index = content.indexOf(`"${this.b.selectedConfiguration.name}"`);
    let startLineNumber = 1;
    for (let i2 = 0; i2 < index; i2++) {
      if (content.charAt(i2) === "\n") {
        startLineNumber++;
      }
    }
    const selection = startLineNumber > 1 ? { startLineNumber, startColumn: 4 } : void 0;
    const editor = await this.j.openEditor({
      resource,
      options: {
        selection,
        preserveFocus,
        pinned: created2,
        revealIfVisible: true
      }
    }, $nJ);
    return {
      editor: editor ?? null,
      created: created2
    };
  }
  async writeConfiguration(configuration2) {
    const fullConfig = $Lv(this.a());
    if (!fullConfig.configurations) {
      fullConfig.configurations = [];
    }
    fullConfig.configurations.push(configuration2);
    await this.k.updateValue(
      "launch",
      fullConfig,
      { resource: this.workspace.uri },
      6
      /* ConfigurationTarget.WORKSPACE_FOLDER */
    );
  }
};
Launch = __decorate([
  __param(3, $km),
  __param(4, $cK),
  __param(5, $mJ),
  __param(6, $kl)
], Launch);
var WorkspaceLaunch = class WorkspaceLaunch2 extends AbstractLaunch {
  constructor(configurationManager, adapterManager, g, h3, j) {
    super(configurationManager, adapterManager);
    this.g = g;
    this.h = h3;
    this.j = j;
  }
  get workspace() {
    return void 0;
  }
  get uri() {
    return this.j.getWorkspace().configuration;
  }
  get name() {
    return localize(5805, null);
  }
  a() {
    return this.h.inspect("launch").workspaceValue;
  }
  async openConfigFile({ preserveFocus, type, useInitialConfigs }, token) {
    const launchExistInFile = !!this.a();
    if (!launchExistInFile) {
      const content = await this.getInitialConfigurationContent(void 0, type, useInitialConfigs, token);
      if (content) {
        await this.h.updateValue(
          "launch",
          $yw(content),
          5
          /* ConfigurationTarget.WORKSPACE */
        );
      } else {
        return { editor: null, created: false };
      }
    }
    const editor = await this.g.openEditor({
      resource: this.j.getWorkspace().configuration,
      options: { preserveFocus }
    }, $nJ);
    return {
      editor: editor ?? null,
      created: false
    };
  }
};
WorkspaceLaunch = __decorate([
  __param(2, $mJ),
  __param(3, $kl),
  __param(4, $Zk)
], WorkspaceLaunch);
var UserLaunch = class UserLaunch2 extends AbstractLaunch {
  constructor(configurationManager, adapterManager, g, h3) {
    super(configurationManager, adapterManager);
    this.g = g;
    this.h = h3;
  }
  get workspace() {
    return void 0;
  }
  get uri() {
    return this.h.userSettingsResource;
  }
  get name() {
    return localize(5806, null);
  }
  get hidden() {
    return true;
  }
  a() {
    return this.g.inspect("launch").userValue;
  }
  async openConfigFile({ preserveFocus, type, useInitialContent }) {
    const editor = await this.h.openUserSettings({ jsonEditor: true, preserveFocus, revealSetting: { key: "launch" } });
    return {
      editor: editor ?? null,
      created: false
    };
  }
};
UserLaunch = __decorate([
  __param(2, $kl),
  __param(3, $TK)
], UserLaunch);

// out-build/vs/workbench/contrib/debug/browser/debugMemory.js
var rangeRe = /range=([0-9]+):([0-9]+)/;
var $mbc = class {
  constructor(d) {
    this.d = d;
    this.a = 0;
    this.b = /* @__PURE__ */ new Map();
    this.c = new $ze();
    this.onDidChangeCapabilities = Event2.None;
    this.onDidChangeFile = this.c.event;
    this.capabilities = 0 | 1024 | 4;
    d.onDidEndSession(({ session }) => {
      for (const [fd, memory] of this.b) {
        if (memory.session === session) {
          this.close(fd);
        }
      }
    });
  }
  watch(resource, opts) {
    if (opts.recursive) {
      return $1c(() => {
      });
    }
    const { session, memoryReference, offset } = this.f(resource);
    const disposable = new $2c();
    disposable.add(session.onDidChangeState(() => {
      if (session.state === 3 || session.state === 0) {
        this.c.fire([{ type: 2, resource }]);
      }
    }));
    disposable.add(session.onDidInvalidateMemory((e) => {
      if (e.body.memoryReference !== memoryReference) {
        return;
      }
      if (offset && (e.body.offset >= offset.toOffset || e.body.offset + e.body.count < offset.fromOffset)) {
        return;
      }
      this.c.fire([{
        resource,
        type: 0
        /* FileChangeType.UPDATED */
      }]);
    }));
    return disposable;
  }
  /** @inheritdoc */
  stat(file) {
    const { readOnly } = this.f(file);
    return Promise.resolve({
      type: FileType.File,
      mtime: 0,
      ctime: 0,
      size: 0,
      permissions: readOnly ? FilePermission.Readonly : void 0
    });
  }
  /** @inheritdoc */
  mkdir() {
    throw $xm(`Not allowed`, FileSystemProviderErrorCode.NoPermissions);
  }
  /** @inheritdoc */
  readdir() {
    throw $xm(`Not allowed`, FileSystemProviderErrorCode.NoPermissions);
  }
  /** @inheritdoc */
  delete() {
    throw $xm(`Not allowed`, FileSystemProviderErrorCode.NoPermissions);
  }
  /** @inheritdoc */
  rename() {
    throw $xm(`Not allowed`, FileSystemProviderErrorCode.NoPermissions);
  }
  /** @inheritdoc */
  open(resource, _opts) {
    const { session, memoryReference, offset } = this.f(resource);
    const fd = this.a++;
    let region = session.getMemory(memoryReference);
    if (offset) {
      region = new MemoryRegionView(region, offset);
    }
    this.b.set(fd, { session, region });
    return Promise.resolve(fd);
  }
  /** @inheritdoc */
  close(fd) {
    this.b.get(fd)?.region.dispose();
    this.b.delete(fd);
    return Promise.resolve();
  }
  /** @inheritdoc */
  async writeFile(resource, content) {
    const { offset } = this.f(resource);
    if (!offset) {
      throw $xm(`Range must be present to read a file`, FileSystemProviderErrorCode.FileNotFound);
    }
    const fd = await this.open(resource, { create: false });
    try {
      await this.write(fd, offset.fromOffset, content, 0, content.length);
    } finally {
      this.close(fd);
    }
  }
  /** @inheritdoc */
  async readFile(resource) {
    const { offset } = this.f(resource);
    if (!offset) {
      throw $xm(`Range must be present to read a file`, FileSystemProviderErrorCode.FileNotFound);
    }
    const data = new Uint8Array(offset.toOffset - offset.fromOffset);
    const fd = await this.open(resource, { create: false });
    try {
      await this.read(fd, offset.fromOffset, data, 0, data.length);
      return data;
    } finally {
      this.close(fd);
    }
  }
  /** @inheritdoc */
  async read(fd, pos, data, offset, length) {
    const memory = this.b.get(fd);
    if (!memory) {
      throw $xm(`No file with that descriptor open`, FileSystemProviderErrorCode.Unavailable);
    }
    const ranges = await memory.region.read(pos, length);
    let readSoFar = 0;
    for (const range of ranges) {
      switch (range.type) {
        case 1:
          return readSoFar;
        case 2:
          if (readSoFar > 0) {
            return readSoFar;
          } else {
            throw $xm(range.error, FileSystemProviderErrorCode.Unknown);
          }
        case 0: {
          const start = Math.max(0, pos - range.offset);
          const toWrite = range.data.slice(start, Math.min(range.data.byteLength, start + (length - readSoFar)));
          data.set(toWrite.buffer, offset + readSoFar);
          readSoFar += toWrite.byteLength;
          break;
        }
        default:
          $hd(range);
      }
    }
    return readSoFar;
  }
  /** @inheritdoc */
  write(fd, pos, data, offset, length) {
    const memory = this.b.get(fd);
    if (!memory) {
      throw $xm(`No file with that descriptor open`, FileSystemProviderErrorCode.Unavailable);
    }
    return memory.region.write(pos, $Ci.wrap(data).slice(offset, offset + length));
  }
  f(uri) {
    if (uri.scheme !== $8R) {
      throw $xm(`Cannot open file with scheme ${uri.scheme}`, FileSystemProviderErrorCode.FileNotFound);
    }
    const session = this.d.getModel().getSession(uri.authority);
    if (!session) {
      throw $xm(`Debug session not found`, FileSystemProviderErrorCode.FileNotFound);
    }
    let offset;
    const rangeMatch = rangeRe.exec(uri.query);
    if (rangeMatch) {
      offset = { fromOffset: Number(rangeMatch[1]), toOffset: Number(rangeMatch[2]) };
    }
    const [, memoryReference] = uri.path.split("/");
    return {
      session,
      offset,
      readOnly: !session.capabilities.supportsWriteMemoryRequest,
      sessionId: uri.authority,
      memoryReference: decodeURIComponent(memoryReference)
    };
  }
};
var MemoryRegionView = class extends $3c {
  constructor(c, range) {
    super();
    this.c = c;
    this.range = range;
    this.a = new $ze();
    this.onDidInvalidate = this.a.event;
    this.b = this.range.toOffset - this.range.fromOffset;
    this.writable = c.writable;
    this.B(c);
    this.B(c.onDidInvalidate((e) => {
      const fromOffset = $4i(e.fromOffset - range.fromOffset, 0, this.b);
      const toOffset = $4i(e.toOffset - range.fromOffset, 0, this.b);
      if (toOffset > fromOffset) {
        this.a.fire({ fromOffset, toOffset });
      }
    }));
  }
  read(fromOffset, toOffset) {
    if (fromOffset < 0) {
      throw new RangeError(`Invalid fromOffset: ${fromOffset}`);
    }
    return this.c.read(this.range.fromOffset + fromOffset, this.range.fromOffset + Math.min(toOffset, this.b));
  }
  write(offset, data) {
    return this.c.write(this.range.fromOffset + offset, data);
  }
};

// out-build/vs/workbench/contrib/debug/browser/rawDebugSession.js
var $nbc = class $nbc2 {
  constructor(debugAdapter, dbgr, E, F, G, H, I, J) {
    this.dbgr = dbgr;
    this.E = E;
    this.F = F;
    this.G = G;
    this.H = H;
    this.I = I;
    this.J = J;
    this.a = true;
    this.b = false;
    this.d = false;
    this.f = false;
    this.g = false;
    this.h = false;
    this.i = 0;
    this.j = false;
    this.k = new $ze();
    this.l = new $ze();
    this.m = new $ze();
    this.n = new $ze();
    this.o = new $ze();
    this.p = new $ze();
    this.q = new $ze();
    this.r = new $ze();
    this.s = new $ze();
    this.t = new $ze();
    this.u = new $ze();
    this.v = new $ze();
    this.w = new $ze();
    this.x = new $ze();
    this.y = new $ze();
    this.z = new $ze();
    this.A = new $ze();
    this.C = false;
    this.D = [];
    this.B = debugAdapter;
    this.c = /* @__PURE__ */ Object.create(null);
    this.D.push(this.B.onError((err) => {
      this.K(err);
    }));
    this.D.push(this.B.onExit((code) => {
      if (code !== 0) {
        this.K(new Error(`exit code: ${code}`));
      } else {
        this.K();
      }
    }));
    this.B.onEvent((event) => {
      switch (event.event) {
        case "initialized":
          this.b = true;
          this.k.fire(event);
          break;
        case "loadedSource":
          this.s.fire(event);
          break;
        case "capabilities":
          if (event.body) {
            const capabilities = event.body.capabilities;
            this.S(capabilities);
          }
          break;
        case "stopped":
          this.j = true;
          this.C = true;
          this.l.fire(event);
          break;
        case "continued":
          this.a = event.body.allThreadsContinued === false ? false : true;
          this.m.fire(event);
          break;
        case "thread":
          this.p.fire(event);
          break;
        case "output":
          this.q.fire(event);
          break;
        case "breakpoint":
          this.r.fire(event);
          break;
        case "terminated":
          this.n.fire(event);
          break;
        case "exited":
          this.o.fire(event);
          break;
        case "progressStart":
          this.t.fire(event);
          break;
        case "progressUpdate":
          this.u.fire(event);
          break;
        case "progressEnd":
          this.v.fire(event);
          break;
        case "invalidated":
          this.w.fire(event);
          break;
        case "memory":
          this.x.fire(event);
          break;
        case "process":
          break;
        case "module":
          break;
        default:
          this.y.fire(event);
          break;
      }
      this.z.fire(event);
    });
    this.B.onRequest((request) => this.N(request));
  }
  get isInShutdown() {
    return this.f;
  }
  get onDidExitAdapter() {
    return this.A.event;
  }
  get capabilities() {
    return this.c;
  }
  /**
   * DA is ready to accepts setBreakpoint requests.
   * Becomes true after "initialized" events has been received.
   */
  get readyForBreakpoints() {
    return this.b;
  }
  //---- DAP events
  get onDidInitialize() {
    return this.k.event;
  }
  get onDidStop() {
    return this.l.event;
  }
  get onDidContinued() {
    return this.m.event;
  }
  get onDidTerminateDebugee() {
    return this.n.event;
  }
  get onDidExitDebugee() {
    return this.o.event;
  }
  get onDidThread() {
    return this.p.event;
  }
  get onDidOutput() {
    return this.q.event;
  }
  get onDidBreakpoint() {
    return this.r.event;
  }
  get onDidLoadedSource() {
    return this.s.event;
  }
  get onDidCustomEvent() {
    return this.y.event;
  }
  get onDidProgressStart() {
    return this.t.event;
  }
  get onDidProgressUpdate() {
    return this.u.event;
  }
  get onDidProgressEnd() {
    return this.v.event;
  }
  get onDidInvalidated() {
    return this.w.event;
  }
  get onDidInvalidateMemory() {
    return this.x.event;
  }
  get onDidEvent() {
    return this.z.event;
  }
  //---- DebugAdapter lifecycle
  /**
   * Starts the underlying debug adapter and tracks the session time for telemetry.
   */
  async start() {
    if (!this.B) {
      return Promise.reject(new Error(localize(6023, null)));
    }
    await this.B.startSession();
    this.i = (/* @__PURE__ */ new Date()).getTime();
  }
  /**
   * Send client capabilities to the debug adapter and receive DA capabilities in return.
   */
  async initialize(args2) {
    const response = await this.P("initialize", args2, void 0, void 0, false);
    if (response) {
      this.S(response.body);
    }
    return response;
  }
  /**
   * Terminate the debuggee and shutdown the adapter
   */
  disconnect(args2) {
    const terminateDebuggee = this.capabilities.supportTerminateDebuggee ? args2.terminateDebuggee : void 0;
    const suspendDebuggee = this.capabilities.supportTerminateDebuggee && this.capabilities.supportSuspendDebuggee ? args2.suspendDebuggee : void 0;
    return this.K(void 0, args2.restart, terminateDebuggee, suspendDebuggee);
  }
  //---- DAP requests
  async launchOrAttach(config) {
    const response = await this.P(config.request, config, void 0, void 0, false);
    if (response) {
      this.S(response.body);
    }
    return response;
  }
  /**
   * Try killing the debuggee softly...
   */
  terminate(restart = false) {
    if (this.capabilities.supportsTerminateRequest) {
      if (!this.g) {
        this.g = true;
        return this.P("terminate", { restart }, void 0);
      }
      return this.disconnect({ terminateDebuggee: true, restart });
    }
    return Promise.reject(new Error("terminated not supported"));
  }
  restart(args2) {
    if (this.capabilities.supportsRestartRequest) {
      return this.P("restart", args2);
    }
    return Promise.reject(new Error("restart not supported"));
  }
  async next(args2) {
    this.C = false;
    const response = await this.P("next", args2);
    if (!this.C) {
      this.T(args2.threadId);
    }
    return response;
  }
  async stepIn(args2) {
    this.C = false;
    const response = await this.P("stepIn", args2);
    if (!this.C) {
      this.T(args2.threadId);
    }
    return response;
  }
  async stepOut(args2) {
    this.C = false;
    const response = await this.P("stepOut", args2);
    if (!this.C) {
      this.T(args2.threadId);
    }
    return response;
  }
  async continue(args2) {
    this.C = false;
    const response = await this.P("continue", args2);
    if (response && response.body && response.body.allThreadsContinued !== void 0) {
      this.a = response.body.allThreadsContinued;
    }
    if (!this.C) {
      this.T(args2.threadId, this.a);
    }
    return response;
  }
  pause(args2) {
    return this.P("pause", args2);
  }
  terminateThreads(args2) {
    if (this.capabilities.supportsTerminateThreadsRequest) {
      return this.P("terminateThreads", args2);
    }
    return Promise.reject(new Error("terminateThreads not supported"));
  }
  setVariable(args2) {
    if (this.capabilities.supportsSetVariable) {
      return this.P("setVariable", args2);
    }
    return Promise.reject(new Error("setVariable not supported"));
  }
  setExpression(args2) {
    if (this.capabilities.supportsSetExpression) {
      return this.P("setExpression", args2);
    }
    return Promise.reject(new Error("setExpression not supported"));
  }
  async restartFrame(args2, threadId) {
    if (this.capabilities.supportsRestartFrame) {
      this.C = false;
      const response = await this.P("restartFrame", args2);
      if (!this.C) {
        this.T(threadId);
      }
      return response;
    }
    return Promise.reject(new Error("restartFrame not supported"));
  }
  stepInTargets(args2) {
    if (this.capabilities.supportsStepInTargetsRequest) {
      return this.P("stepInTargets", args2);
    }
    return Promise.reject(new Error("stepInTargets not supported"));
  }
  completions(args2, token) {
    if (this.capabilities.supportsCompletionsRequest) {
      return this.P("completions", args2, token);
    }
    return Promise.reject(new Error("completions not supported"));
  }
  setBreakpoints(args2) {
    return this.P("setBreakpoints", args2);
  }
  setFunctionBreakpoints(args2) {
    if (this.capabilities.supportsFunctionBreakpoints) {
      return this.P("setFunctionBreakpoints", args2);
    }
    return Promise.reject(new Error("setFunctionBreakpoints not supported"));
  }
  dataBreakpointInfo(args2) {
    if (this.capabilities.supportsDataBreakpoints) {
      return this.P("dataBreakpointInfo", args2);
    }
    return Promise.reject(new Error("dataBreakpointInfo not supported"));
  }
  setDataBreakpoints(args2) {
    if (this.capabilities.supportsDataBreakpoints) {
      return this.P("setDataBreakpoints", args2);
    }
    return Promise.reject(new Error("setDataBreakpoints not supported"));
  }
  setExceptionBreakpoints(args2) {
    return this.P("setExceptionBreakpoints", args2);
  }
  breakpointLocations(args2) {
    if (this.capabilities.supportsBreakpointLocationsRequest) {
      return this.P("breakpointLocations", args2);
    }
    return Promise.reject(new Error("breakpointLocations is not supported"));
  }
  configurationDone() {
    if (this.capabilities.supportsConfigurationDoneRequest) {
      return this.P("configurationDone", null);
    }
    return Promise.reject(new Error("configurationDone not supported"));
  }
  stackTrace(args2, token) {
    return this.P("stackTrace", args2, token);
  }
  exceptionInfo(args2) {
    if (this.capabilities.supportsExceptionInfoRequest) {
      return this.P("exceptionInfo", args2);
    }
    return Promise.reject(new Error("exceptionInfo not supported"));
  }
  scopes(args2, token) {
    return this.P("scopes", args2, token);
  }
  variables(args2, token) {
    return this.P("variables", args2, token);
  }
  source(args2) {
    return this.P("source", args2);
  }
  locations(args2) {
    return this.P("locations", args2);
  }
  loadedSources(args2) {
    if (this.capabilities.supportsLoadedSourcesRequest) {
      return this.P("loadedSources", args2);
    }
    return Promise.reject(new Error("loadedSources not supported"));
  }
  threads() {
    return this.P("threads", null);
  }
  evaluate(args2) {
    return this.P("evaluate", args2);
  }
  async stepBack(args2) {
    if (this.capabilities.supportsStepBack) {
      this.C = false;
      const response = await this.P("stepBack", args2);
      if (!this.C) {
        this.T(args2.threadId);
      }
      return response;
    }
    return Promise.reject(new Error("stepBack not supported"));
  }
  async reverseContinue(args2) {
    if (this.capabilities.supportsStepBack) {
      this.C = false;
      const response = await this.P("reverseContinue", args2);
      if (!this.C) {
        this.T(args2.threadId);
      }
      return response;
    }
    return Promise.reject(new Error("reverseContinue not supported"));
  }
  gotoTargets(args2) {
    if (this.capabilities.supportsGotoTargetsRequest) {
      return this.P("gotoTargets", args2);
    }
    return Promise.reject(new Error("gotoTargets is not supported"));
  }
  async goto(args2) {
    if (this.capabilities.supportsGotoTargetsRequest) {
      this.C = false;
      const response = await this.P("goto", args2);
      if (!this.C) {
        this.T(args2.threadId);
      }
      return response;
    }
    return Promise.reject(new Error("goto is not supported"));
  }
  async setInstructionBreakpoints(args2) {
    if (this.capabilities.supportsInstructionBreakpoints) {
      return await this.P("setInstructionBreakpoints", args2);
    }
    return Promise.reject(new Error("setInstructionBreakpoints is not supported"));
  }
  async disassemble(args2) {
    if (this.capabilities.supportsDisassembleRequest) {
      return await this.P("disassemble", args2);
    }
    return Promise.reject(new Error("disassemble is not supported"));
  }
  async readMemory(args2) {
    if (this.capabilities.supportsReadMemoryRequest) {
      return await this.P("readMemory", args2);
    }
    return Promise.reject(new Error("readMemory is not supported"));
  }
  async writeMemory(args2) {
    if (this.capabilities.supportsWriteMemoryRequest) {
      return await this.P("writeMemory", args2);
    }
    return Promise.reject(new Error("writeMemory is not supported"));
  }
  cancel(args2) {
    return this.P("cancel", args2);
  }
  custom(request, args2) {
    return this.P(request, args2);
  }
  //---- private
  async K(error, restart = false, terminateDebuggee = void 0, suspendDebuggee = void 0) {
    if (!this.f) {
      this.f = true;
      if (this.B) {
        try {
          const args2 = { restart };
          if (typeof terminateDebuggee === "boolean") {
            args2.terminateDebuggee = terminateDebuggee;
          }
          if (typeof suspendDebuggee === "boolean") {
            args2.suspendDebuggee = suspendDebuggee;
          }
          await this.P("disconnect", args2, void 0, error ? 200 : 2e3);
        } catch (e) {
        } finally {
          await this.L(error);
        }
      } else {
        return this.L(error);
      }
    }
  }
  async L(error) {
    try {
      if (this.B) {
        const da = this.B;
        this.B = null;
        await da.stopSession();
        this.d = true;
      }
    } finally {
      this.M(error);
    }
  }
  M(error) {
    if (!this.h) {
      this.h = true;
      const e = {
        emittedStopped: this.j,
        sessionLengthInSeconds: ((/* @__PURE__ */ new Date()).getTime() - this.i) / 1e3
      };
      if (error && !this.d) {
        e.error = error;
      }
      this.A.fire(e);
    }
  }
  async N(request) {
    const response = {
      type: "response",
      seq: 0,
      command: request.command,
      request_seq: request.seq,
      success: true
    };
    const safeSendResponse = (response2) => this.B && this.B.sendResponse(response2);
    if (request.command === "launchVSCode") {
      try {
        let result = await this.O(request.arguments);
        if (!result.success) {
          const { confirmed } = await this.J.confirm({
            type: Severity2.Warning,
            message: localize(6024, null),
            primaryButton: localize(6025, null)
          });
          if (confirmed) {
            result = await this.O(request.arguments);
          } else {
            response.success = false;
            safeSendResponse(response);
            await this.K();
          }
        }
        response.body = {
          rendererDebugPort: result.rendererDebugPort
        };
        safeSendResponse(response);
      } catch (err) {
        response.success = false;
        response.message = err.message;
        safeSendResponse(response);
      }
    } else if (request.command === "runInTerminal") {
      try {
        const shellProcessId = await this.dbgr.runInTerminal(request.arguments, this.E);
        const resp = response;
        resp.body = {};
        if (typeof shellProcessId === "number") {
          resp.body.shellProcessId = shellProcessId;
        }
        safeSendResponse(resp);
      } catch (err) {
        response.success = false;
        response.message = err.message;
        safeSendResponse(response);
      }
    } else if (request.command === "startDebugging") {
      try {
        const args2 = request.arguments;
        const config = {
          ...args2.configuration,
          ...{
            request: args2.request,
            type: this.dbgr.type,
            name: args2.configuration.name || this.F
          }
        };
        const success = await this.dbgr.startDebugging(config, this.E);
        if (success) {
          safeSendResponse(response);
        } else {
          response.success = false;
          response.message = "Failed to start debugging";
          safeSendResponse(response);
        }
      } catch (err) {
        response.success = false;
        response.message = err.message;
        safeSendResponse(response);
      }
    } else {
      response.success = false;
      response.message = `unknown request '${request.command}'`;
      safeSendResponse(response);
    }
  }
  O(vscodeArgs) {
    const args2 = [];
    for (const arg of vscodeArgs.args) {
      const a2 = (arg.prefix || "") + (arg.path || "");
      const match = /^--(.+)=(.+)$/.exec(a2);
      if (match && match.length === 3) {
        const key2 = match[1];
        let value = match[2];
        if ((key2 === "file-uri" || key2 === "folder-uri") && !$uP(arg.path)) {
          value = $uP(value) ? value : URI.file(value).toString();
        }
        args2.push(`--${key2}=${value}`);
      } else {
        args2.push(a2);
      }
    }
    if (vscodeArgs.env) {
      args2.push(`--extensionEnvironment=${JSON.stringify(vscodeArgs.env)}`);
    }
    return this.G.openExtensionDevelopmentHostWindow(args2, !!vscodeArgs.debugRenderer);
  }
  P(command4, args2, token, timeout, showErrors = true) {
    return new Promise((completeDispatch, errorDispatch) => {
      if (!this.B) {
        if (this.f) {
          completeDispatch(void 0);
        } else {
          errorDispatch(new Error(localize(6026, null, command4)));
        }
        return;
      }
      let cancelationListener;
      const requestId = this.B.sendRequest(command4, args2, (response) => {
        cancelationListener?.dispose();
        if (response.success) {
          completeDispatch(response);
        } else {
          errorDispatch(response);
        }
      }, timeout);
      if (token) {
        cancelationListener = token.onCancellationRequested(() => {
          cancelationListener.dispose();
          if (this.capabilities.supportsCancelRequest) {
            this.cancel({ requestId });
          }
        });
      }
    }).then(void 0, (err) => Promise.reject(this.Q(err, showErrors)));
  }
  Q(errorResponse, showErrors) {
    if (errorResponse.command === "canceled" && errorResponse.message === "canceled") {
      return new $lb();
    }
    const error = errorResponse?.body?.error;
    const errorMessage = errorResponse?.message || "";
    const userMessage = error ? $nP(error.format, false, error.variables) : errorMessage;
    const url = error?.url;
    if (error && url) {
      const label3 = error.urlLabel ? error.urlLabel : localize(6027, null);
      const uri = URI.parse(url);
      const actionId = uri.scheme === Schemas.command ? "debug.moreInfo.command" : "debug.moreInfo";
      return $3m(userMessage, [$Zm({ id: actionId, label: label3, run: () => this.H.open(uri, { allowCommands: true }) })]);
    }
    if (showErrors && error && error.format && error.showUser) {
      this.I.error(userMessage);
    }
    const result = new $ub(userMessage);
    result.showUser = error?.showUser;
    return result;
  }
  S(capabilities) {
    if (capabilities) {
      this.c = $Ov(this.c, capabilities);
    }
  }
  T(threadId, allThreadsContinued = false) {
    this.m.fire({
      type: "event",
      event: "continued",
      body: {
        threadId,
        allThreadsContinued
      },
      seq: void 0
    });
  }
  dispose() {
    $Xc(this.D);
  }
};
$nbc = __decorate([
  __param(4, $Ax),
  __param(5, $O4),
  __param(6, $PJ),
  __param(7, $Yv)
], $nbc);

// out-build/vs/workbench/contrib/debug/browser/debugSession.js
var TRIGGERED_BREAKPOINT_MAX_DELAY = 1500;
var $obc = class $obc2 {
  constructor(I, J, root, K, options3, L, M, N, O, P, Q, R, S, lifecycleService, T, U, V, W, X, Y, testResultService, Z) {
    this.I = I;
    this.J = J;
    this.root = root;
    this.K = K;
    this.L = L;
    this.M = M;
    this.N = N;
    this.O = O;
    this.P = P;
    this.Q = Q;
    this.R = R;
    this.S = S;
    this.T = T;
    this.U = U;
    this.V = V;
    this.W = W;
    this.X = X;
    this.Y = Y;
    this.Z = Z;
    this.b = false;
    this.f = /* @__PURE__ */ new Map();
    this.g = /* @__PURE__ */ new Map();
    this.h = [];
    this.j = /* @__PURE__ */ new Map();
    this.k = new $2c();
    this.l = new $2c();
    this.r = [];
    this.u = this.k.add(new $pbc());
    this.w = new $ze();
    this.x = new $ze();
    this.y = new $ze();
    this.z = new $ze();
    this.A = new $ze();
    this.B = new $ze();
    this.C = new $ze();
    this.D = new $ze();
    this.E = new $ze();
    this.G = new $ze();
    this.c = options3 || {};
    this.parentSession = this.c.parentSession;
    if (this.hasSeparateRepl()) {
      this.q = new $o4b(this.O);
    } else {
      this.q = this.parentSession.q;
    }
    const toDispose = this.l;
    const replListener = toDispose.add(new $4c());
    replListener.value = this.q.onDidChangeElements((e) => this.E.fire(e));
    if (lifecycleService) {
      toDispose.add(lifecycleService.onWillShutdown(() => {
        this.jb();
        $Xc(toDispose);
      }));
    }
    this.correlatedTestRun = options3?.testRun ? testResultService.getResult(options3.testRun.runId) : this.parentSession?.correlatedTestRun;
    if (this.correlatedTestRun) {
      toDispose.add(this.correlatedTestRun.onComplete(() => this.terminate()));
    }
    const compoundRoot = this.c.compoundRoot;
    if (compoundRoot) {
      toDispose.add(compoundRoot.onDidSessionStop(() => this.terminate()));
    }
    this.n = new $8h(() => {
      if (this.L.getModel().getSessions().some(
        (s) => s.state === 2
        /* State.Stopped */
      ) || this.getAllThreads().some((t) => t.stopped)) {
        if (typeof this.o === "number") {
          const thread = this.L.getViewModel().focusedThread;
          if (thread && thread.threadId === this.o && !thread.stopped) {
            const toFocusThreadId = this.getStoppedDetails()?.threadId;
            const toFocusThread = typeof toFocusThreadId === "number" ? this.getThread(toFocusThreadId) : void 0;
            this.L.focusStackFrame(void 0, toFocusThread);
          }
        } else {
          const session = this.L.getViewModel().focusedSession;
          if (session && session.getId() === this.getId() && session.state !== 2) {
            this.L.focusStackFrame(void 0);
          }
        }
      }
    }, 800);
    const parent = this.c.parentSession;
    if (parent) {
      toDispose.add(parent.onDidEndAdapter(() => {
        if (!this.hasSeparateRepl() && this.raw?.isInShutdown === false) {
          this.q = this.q.clone();
          replListener.value = this.q.onDidChangeElements((e) => this.E.fire(e));
          this.parentSession = void 0;
        }
      }));
    }
  }
  getId() {
    return this.I;
  }
  setSubId(subId) {
    this.a = subId;
  }
  getMemory(memoryReference) {
    return new $SP(memoryReference, this);
  }
  get subId() {
    return this.a;
  }
  get configuration() {
    return this.J.resolved;
  }
  get unresolvedConfiguration() {
    return this.J.unresolved;
  }
  get lifecycleManagedByParent() {
    return !!this.c.lifecycleManagedByParent;
  }
  get compact() {
    return !!this.c.compact;
  }
  get saveBeforeRestart() {
    return this.c.saveBeforeRestart ?? !this.c?.parentSession;
  }
  get compoundRoot() {
    return this.c.compoundRoot;
  }
  get suppressDebugStatusbar() {
    return this.c.suppressDebugStatusbar ?? false;
  }
  get suppressDebugToolbar() {
    return this.c.suppressDebugToolbar ?? false;
  }
  get suppressDebugView() {
    return this.c.suppressDebugView ?? false;
  }
  get autoExpandLazyVariables() {
    const screenReaderOptimized = this.Z.isScreenReaderOptimized();
    const value = this.O.getValue("debug").autoExpandLazyVariables;
    return value === "auto" && screenReaderOptimized || value === "on";
  }
  setConfiguration(configuration2) {
    this.J = configuration2;
  }
  getLabel() {
    const includeRoot = this.Q.getWorkspace().folders.length > 1;
    return includeRoot && this.root ? `${this.name} (${$rh(this.root.uri)})` : this.name;
  }
  setName(name) {
    this.F = name;
    this.G.fire(name);
  }
  get name() {
    return this.F || this.configuration.name;
  }
  get state() {
    if (!this.b) {
      return 1;
    }
    if (!this.raw) {
      return 0;
    }
    const focusedThread = this.L.getViewModel().focusedThread;
    if (focusedThread && focusedThread.session === this) {
      return focusedThread.stopped ? 2 : 3;
    }
    if (this.getAllThreads().some((t) => t.stopped)) {
      return 2;
    }
    return 3;
  }
  get capabilities() {
    return this.raw ? this.raw.capabilities : /* @__PURE__ */ Object.create(null);
  }
  //---- events
  get onDidChangeState() {
    return this.w.event;
  }
  get onDidEndAdapter() {
    return this.x.event;
  }
  get onDidChangeReplElements() {
    return this.E.event;
  }
  get onDidChangeName() {
    return this.G.event;
  }
  //---- DAP events
  get onDidCustomEvent() {
    return this.z.event;
  }
  get onDidLoadedSource() {
    return this.y.event;
  }
  get onDidProgressStart() {
    return this.A.event;
  }
  get onDidProgressUpdate() {
    return this.B.event;
  }
  get onDidProgressEnd() {
    return this.C.event;
  }
  get onDidInvalidateMemory() {
    return this.D.event;
  }
  //---- DAP requests
  /**
   * create and initialize a new debug adapter for this session
   */
  async initialize(dbgr) {
    if (this.raw) {
      await this.jb();
    }
    try {
      const debugAdapter = await dbgr.createDebugAdapter(this);
      this.raw = this.U.createInstance($nbc, debugAdapter, dbgr, this.I, this.configuration.name);
      await this.raw.start();
      this.db();
      await this.raw.initialize({
        clientID: "vscode",
        clientName: this.R.nameLong,
        adapterID: this.configuration.type,
        pathFormat: "path",
        linesStartAt1: true,
        columnsStartAt1: true,
        supportsVariableType: true,
        // #8858
        supportsVariablePaging: true,
        // #9537
        supportsRunInTerminalRequest: true,
        // #10574
        locale: $z,
        // #169114
        supportsProgressReporting: true,
        // #92253
        supportsInvalidatedEvent: true,
        // #106745
        supportsMemoryReferences: true,
        //#129684
        supportsArgsCanBeInterpretedByShell: true,
        // #149910
        supportsMemoryEvent: true,
        // #133643
        supportsStartDebuggingRequest: true,
        supportsANSIStyling: true
      });
      this.b = true;
      this.w.fire();
      this.rememberedCapabilities = this.raw.capabilities;
      this.L.setExceptionBreakpointsForSession(this, this.raw && this.raw.capabilities.exceptionBreakpointFilters || []);
      this.L.getModel().registerBreakpointModes(this.configuration.type, this.raw.capabilities.breakpointModes || []);
    } catch (err) {
      this.b = true;
      this.w.fire();
      await this.jb();
      throw err;
    }
  }
  /**
   * launch or attach to the debuggee
   */
  async launchOrAttach(config) {
    if (!this.raw) {
      throw new Error(localize(5924, null, "launch or attach"));
    }
    if (this.parentSession && this.parentSession.state === 0) {
      throw $mb();
    }
    config.__sessionId = this.getId();
    try {
      await this.raw.launchOrAttach(config);
    } catch (err) {
      this.jb();
      throw err;
    }
  }
  /**
   * terminate the current debug adapter session
   */
  async terminate(restart = false) {
    if (!this.raw) {
      this.hb();
    }
    this.mb();
    if (this.c.lifecycleManagedByParent && this.parentSession) {
      await this.parentSession.terminate(restart);
    } else if (this.correlatedTestRun && !this.correlatedTestRun.completedAt && !this.v) {
      this.v = true;
      this.Y.cancelTestRun(this.correlatedTestRun.id);
    } else if (this.raw) {
      if (this.raw.capabilities.supportsTerminateRequest && this.J.resolved.request === "launch") {
        await this.raw.terminate(restart);
      } else {
        await this.raw.disconnect({ restart, terminateDebuggee: true });
      }
    }
    if (!restart) {
      this.c.compoundRoot?.sessionStopped();
    }
  }
  /**
   * end the current debug adapter session
   */
  async disconnect(restart = false, suspend = false) {
    if (!this.raw) {
      this.hb();
    }
    this.mb();
    if (this.c.lifecycleManagedByParent && this.parentSession) {
      await this.parentSession.disconnect(restart, suspend);
    } else if (this.raw) {
      await this.raw.disconnect({ restart, terminateDebuggee: false, suspendDebuggee: suspend });
    }
    if (!restart) {
      this.c.compoundRoot?.sessionStopped();
    }
  }
  /**
   * restart debug adapter session
   */
  async restart() {
    if (!this.raw) {
      throw new Error(localize(5925, null, "restart"));
    }
    this.mb();
    if (this.c.lifecycleManagedByParent && this.parentSession) {
      await this.parentSession.restart();
    } else {
      await this.raw.restart({ arguments: this.configuration });
    }
  }
  async sendBreakpoints(modelUri, breakpointsToSend, sourceModified) {
    if (!this.raw) {
      throw new Error(localize(5926, null, "breakpoints"));
    }
    if (!this.raw.readyForBreakpoints) {
      return Promise.resolve(void 0);
    }
    const rawSource = this.kb(modelUri);
    if (breakpointsToSend.length && !rawSource.adapterData) {
      rawSource.adapterData = breakpointsToSend[0].adapterData;
    }
    if (rawSource.path) {
      rawSource.path = $1t(rawSource.path);
    }
    const response = await this.raw.setBreakpoints({
      source: rawSource,
      lines: breakpointsToSend.map((bp) => bp.sessionAgnosticData.lineNumber),
      breakpoints: breakpointsToSend.map((bp) => bp.toDAP()),
      sourceModified
    });
    if (response?.body) {
      const data = /* @__PURE__ */ new Map();
      for (let i2 = 0; i2 < breakpointsToSend.length; i2++) {
        data.set(breakpointsToSend[i2].getId(), response.body.breakpoints[i2]);
      }
      this.K.setBreakpointSessionData(this.getId(), this.capabilities, data);
    }
  }
  async sendFunctionBreakpoints(fbpts) {
    if (!this.raw) {
      throw new Error(localize(5927, null, "function breakpoints"));
    }
    if (this.raw.readyForBreakpoints) {
      const response = await this.raw.setFunctionBreakpoints({ breakpoints: fbpts.map((bp) => bp.toDAP()) });
      if (response?.body) {
        const data = /* @__PURE__ */ new Map();
        for (let i2 = 0; i2 < fbpts.length; i2++) {
          data.set(fbpts[i2].getId(), response.body.breakpoints[i2]);
        }
        this.K.setBreakpointSessionData(this.getId(), this.capabilities, data);
      }
    }
  }
  async sendExceptionBreakpoints(exbpts) {
    if (!this.raw) {
      throw new Error(localize(5928, null, "exception breakpoints"));
    }
    if (this.raw.readyForBreakpoints) {
      const args2 = this.capabilities.supportsExceptionFilterOptions ? {
        filters: [],
        filterOptions: exbpts.map((exb) => {
          if (exb.condition) {
            return { filterId: exb.filter, condition: exb.condition };
          }
          return { filterId: exb.filter };
        })
      } : { filters: exbpts.map((exb) => exb.filter) };
      const response = await this.raw.setExceptionBreakpoints(args2);
      if (response?.body && response.body.breakpoints) {
        const data = /* @__PURE__ */ new Map();
        for (let i2 = 0; i2 < exbpts.length; i2++) {
          data.set(exbpts[i2].getId(), response.body.breakpoints[i2]);
        }
        this.K.setBreakpointSessionData(this.getId(), this.capabilities, data);
      }
    }
  }
  dataBytesBreakpointInfo(address, bytes) {
    if (this.raw?.capabilities.supportsDataBreakpointBytes === false) {
      throw new Error(localize(5929, null));
    }
    return this.$({ name: address, bytes, asAddress: true });
  }
  dataBreakpointInfo(name, variablesReference) {
    return this.$({ name, variablesReference });
  }
  async $(args2) {
    if (!this.raw) {
      throw new Error(localize(5930, null, "data breakpoints info"));
    }
    if (!this.raw.readyForBreakpoints) {
      throw new Error(localize(5931, null));
    }
    const response = await this.raw.dataBreakpointInfo(args2);
    return response?.body;
  }
  async sendDataBreakpoints(dataBreakpoints) {
    if (!this.raw) {
      throw new Error(localize(5932, null, "data breakpoints"));
    }
    if (this.raw.readyForBreakpoints) {
      const converted = await Promise.all(dataBreakpoints.map(async (bp) => {
        try {
          const dap = await bp.toDAP(this);
          return { dap, bp };
        } catch (e) {
          return { bp, message: e.message };
        }
      }));
      const response = await this.raw.setDataBreakpoints({ breakpoints: converted.map((d) => d.dap).filter($Hg) });
      if (response?.body) {
        const data = /* @__PURE__ */ new Map();
        let i2 = 0;
        for (const dap of converted) {
          if (!dap.dap) {
            data.set(dap.bp.getId(), dap.message);
          } else if (i2 < response.body.breakpoints.length) {
            data.set(dap.bp.getId(), response.body.breakpoints[i2++]);
          }
        }
        this.K.setBreakpointSessionData(this.getId(), this.capabilities, data);
      }
    }
  }
  async sendInstructionBreakpoints(instructionBreakpoints) {
    if (!this.raw) {
      throw new Error(localize(5933, null, "instruction breakpoints"));
    }
    if (this.raw.readyForBreakpoints) {
      const response = await this.raw.setInstructionBreakpoints({ breakpoints: instructionBreakpoints.map((ib) => ib.toDAP()) });
      if (response?.body) {
        const data = /* @__PURE__ */ new Map();
        for (let i2 = 0; i2 < instructionBreakpoints.length; i2++) {
          data.set(instructionBreakpoints[i2].getId(), response.body.breakpoints[i2]);
        }
        this.K.setBreakpointSessionData(this.getId(), this.capabilities, data);
      }
    }
  }
  async breakpointsLocations(uri, lineNumber) {
    if (!this.raw) {
      throw new Error(localize(5934, null, "breakpoints locations"));
    }
    const source = this.kb(uri);
    const response = await this.raw.breakpointLocations({ source, line: lineNumber });
    if (!response || !response.body || !response.body.breakpoints) {
      return [];
    }
    const positions = response.body.breakpoints.map((bp) => ({ lineNumber: bp.line, column: bp.column || 1 }));
    return $Rb(positions, (p) => `${p.lineNumber}:${p.column}`);
  }
  getDebugProtocolBreakpoint(breakpointId) {
    return this.K.getDebugProtocolBreakpoint(breakpointId, this.getId());
  }
  customRequest(request, args2) {
    if (!this.raw) {
      throw new Error(localize(5935, null, request));
    }
    return this.raw.custom(request, args2);
  }
  stackTrace(threadId, startFrame, levels, token) {
    if (!this.raw) {
      throw new Error(localize(5936, null, "stackTrace"));
    }
    const sessionToken = this.lb(threadId, token);
    return this.raw.stackTrace({ threadId, startFrame, levels }, sessionToken);
  }
  async exceptionInfo(threadId) {
    if (!this.raw) {
      throw new Error(localize(5937, null, "exceptionInfo"));
    }
    const response = await this.raw.exceptionInfo({ threadId });
    if (response) {
      return {
        id: response.body.exceptionId,
        description: response.body.description,
        breakMode: response.body.breakMode,
        details: response.body.details
      };
    }
    return void 0;
  }
  scopes(frameId, threadId) {
    if (!this.raw) {
      throw new Error(localize(5938, null, "scopes"));
    }
    const token = this.lb(threadId);
    return this.raw.scopes({ frameId }, token);
  }
  variables(variablesReference, threadId, filter, start, count) {
    if (!this.raw) {
      throw new Error(localize(5939, null, "variables"));
    }
    const token = threadId ? this.lb(threadId) : void 0;
    return this.raw.variables({ variablesReference, filter, start, count }, token);
  }
  evaluate(expression, frameId, context, location3) {
    if (!this.raw) {
      throw new Error(localize(5940, null, "evaluate"));
    }
    return this.raw.evaluate({ expression, frameId, context, line: location3?.line, column: location3?.column, source: location3?.source });
  }
  async restartFrame(frameId, threadId) {
    await this.bb();
    if (!this.raw) {
      throw new Error(localize(5941, null, "restartFrame"));
    }
    await this.raw.restartFrame({ frameId }, threadId);
  }
  ab(threadId, granularity) {
    const thread = this.getThread(threadId);
    if (thread) {
      thread.lastSteppingGranularity = granularity;
    }
  }
  async next(threadId, granularity) {
    await this.bb();
    if (!this.raw) {
      throw new Error(localize(5942, null, "next"));
    }
    this.ab(threadId, granularity);
    await this.raw.next({ threadId, granularity });
  }
  async stepIn(threadId, targetId, granularity) {
    await this.bb();
    if (!this.raw) {
      throw new Error(localize(5943, null, "stepIn"));
    }
    this.ab(threadId, granularity);
    await this.raw.stepIn({ threadId, targetId, granularity });
  }
  async stepOut(threadId, granularity) {
    await this.bb();
    if (!this.raw) {
      throw new Error(localize(5944, null, "stepOut"));
    }
    this.ab(threadId, granularity);
    await this.raw.stepOut({ threadId, granularity });
  }
  async stepBack(threadId, granularity) {
    await this.bb();
    if (!this.raw) {
      throw new Error(localize(5945, null, "stepBack"));
    }
    this.ab(threadId, granularity);
    await this.raw.stepBack({ threadId, granularity });
  }
  async continue(threadId) {
    await this.bb();
    if (!this.raw) {
      throw new Error(localize(5946, null, "continue"));
    }
    await this.raw.continue({ threadId });
  }
  async reverseContinue(threadId) {
    await this.bb();
    if (!this.raw) {
      throw new Error(localize(5947, null, "reverse continue"));
    }
    await this.raw.reverseContinue({ threadId });
  }
  async pause(threadId) {
    if (!this.raw) {
      throw new Error(localize(5948, null, "pause"));
    }
    await this.raw.pause({ threadId });
  }
  async terminateThreads(threadIds) {
    if (!this.raw) {
      throw new Error(localize(5949, null, "terminateThreads"));
    }
    await this.raw.terminateThreads({ threadIds });
  }
  setVariable(variablesReference, name, value) {
    if (!this.raw) {
      throw new Error(localize(5950, null, "setVariable"));
    }
    return this.raw.setVariable({ variablesReference, name, value });
  }
  setExpression(frameId, expression, value) {
    if (!this.raw) {
      throw new Error(localize(5951, null, "setExpression"));
    }
    return this.raw.setExpression({ expression, value, frameId });
  }
  gotoTargets(source, line, column) {
    if (!this.raw) {
      throw new Error(localize(5952, null, "gotoTargets"));
    }
    return this.raw.gotoTargets({ source, line, column });
  }
  goto(threadId, targetId) {
    if (!this.raw) {
      throw new Error(localize(5953, null, "goto"));
    }
    return this.raw.goto({ threadId, targetId });
  }
  loadSource(resource) {
    if (!this.raw) {
      return Promise.reject(new Error(localize(5954, null, "loadSource")));
    }
    const source = this.getSourceForUri(resource);
    let rawSource;
    if (source) {
      rawSource = source.raw;
    } else {
      const data = $BP.getEncodedDebugData(resource);
      rawSource = { path: data.path, sourceReference: data.sourceReference };
    }
    return this.raw.source({ sourceReference: rawSource.sourceReference || 0, source: rawSource });
  }
  async getLoadedSources() {
    if (!this.raw) {
      return Promise.reject(new Error(localize(5955, null, "getLoadedSources")));
    }
    const response = await this.raw.loadedSources({});
    if (response?.body && response.body.sources) {
      return response.body.sources.map((src) => this.getSource(src));
    } else {
      return [];
    }
  }
  async completions(frameId, threadId, text2, position, overwriteBefore, token) {
    if (!this.raw) {
      return Promise.reject(new Error(localize(5956, null, "completions")));
    }
    const sessionCancelationToken = this.lb(threadId, token);
    return this.raw.completions({
      frameId,
      text: text2,
      column: position.column,
      line: position.lineNumber
    }, sessionCancelationToken);
  }
  async stepInTargets(frameId) {
    if (!this.raw) {
      return Promise.reject(new Error(localize(5957, null, "stepInTargets")));
    }
    const response = await this.raw.stepInTargets({ frameId });
    return response?.body.targets;
  }
  async cancel(progressId) {
    if (!this.raw) {
      return Promise.reject(new Error(localize(5958, null, "cancel")));
    }
    return this.raw.cancel({ progressId });
  }
  async disassemble(memoryReference, offset, instructionOffset, instructionCount) {
    if (!this.raw) {
      return Promise.reject(new Error(localize(5959, null, "disassemble")));
    }
    const response = await this.raw.disassemble({ memoryReference, offset, instructionOffset, instructionCount, resolveSymbols: true });
    return response?.body?.instructions;
  }
  readMemory(memoryReference, offset, count) {
    if (!this.raw) {
      return Promise.reject(new Error(localize(5960, null, "readMemory")));
    }
    return this.raw.readMemory({ count, memoryReference, offset });
  }
  writeMemory(memoryReference, offset, data, allowPartial) {
    if (!this.raw) {
      return Promise.reject(new Error(localize(5961, null, "disassemble")));
    }
    return this.raw.writeMemory({ memoryReference, offset, allowPartial, data });
  }
  async resolveLocationReference(locationReference) {
    if (!this.raw) {
      throw new Error(localize(5962, null, "locations"));
    }
    const location3 = await this.raw.locations({ locationReference });
    if (!location3?.body) {
      throw new Error(localize(5963, null, "locations"));
    }
    const source = this.getSource(location3.body.source);
    return { column: 1, ...location3.body, source };
  }
  //---- threads
  getThread(threadId) {
    return this.g.get(threadId);
  }
  getAllThreads() {
    const result = [];
    this.h.forEach((threadId) => {
      const thread = this.g.get(threadId);
      if (thread) {
        result.push(thread);
      }
    });
    return result;
  }
  clearThreads(removeThreads, reference = void 0) {
    if (reference !== void 0 && reference !== null) {
      const thread = this.g.get(reference);
      if (thread) {
        thread.clearCallStack();
        thread.stoppedDetails = void 0;
        thread.stopped = false;
        if (removeThreads) {
          this.g.delete(reference);
        }
      }
    } else {
      this.g.forEach((thread) => {
        thread.clearCallStack();
        thread.stoppedDetails = void 0;
        thread.stopped = false;
      });
      if (removeThreads) {
        this.g.clear();
        this.h = [];
        $JP.allValues.clear();
      }
    }
  }
  getStoppedDetails() {
    return this.r.length >= 1 ? this.r[0] : void 0;
  }
  rawUpdate(data) {
    this.h = [];
    data.threads.forEach((thread) => {
      this.h.push(thread.id);
      if (!this.g.has(thread.id)) {
        this.g.set(thread.id, new $QP(this, thread.name, thread.id));
      } else if (thread.name) {
        const oldThread = this.g.get(thread.id);
        if (oldThread) {
          oldThread.name = thread.name;
        }
      }
    });
    this.g.forEach((t) => {
      if (this.h.indexOf(t.threadId) === -1) {
        this.g.delete(t.threadId);
      }
    });
    const stoppedDetails = data.stoppedDetails;
    if (stoppedDetails) {
      if (stoppedDetails.allThreadsStopped) {
        this.g.forEach((thread) => {
          thread.stoppedDetails = thread.threadId === stoppedDetails.threadId ? stoppedDetails : { reason: thread.stoppedDetails?.reason };
          thread.stopped = true;
          thread.clearCallStack();
        });
      } else {
        const thread = typeof stoppedDetails.threadId === "number" ? this.g.get(stoppedDetails.threadId) : void 0;
        if (thread) {
          thread.stoppedDetails = stoppedDetails;
          thread.clearCallStack();
          thread.stopped = true;
        }
      }
    }
  }
  bb() {
    if (!this.H) {
      return;
    }
    return $Lh(this.H, TRIGGERED_BREAKPOINT_MAX_DELAY);
  }
  async cb(stoppedDetails) {
    if (this.raw) {
      const response = await this.raw.threads();
      if (response?.body && response.body.threads) {
        this.K.rawUpdate({
          sessionId: this.getId(),
          threads: response.body.threads,
          stoppedDetails
        });
      }
    }
  }
  initializeForTest(raw) {
    this.raw = raw;
    this.db();
  }
  //---- private
  db() {
    if (!this.raw) {
      return;
    }
    this.k.add(this.raw.onDidInitialize(async () => {
      $_Z(this.configuration.noDebug ? localize(5964, null) : localize(5965, null));
      const sendConfigurationDone = async () => {
        if (this.raw && this.raw.capabilities.supportsConfigurationDoneRequest) {
          try {
            await this.raw.configurationDone();
          } catch (e) {
            this.S.error(e);
            this.raw?.disconnect({});
          }
        }
        return void 0;
      };
      try {
        await this.L.sendAllBreakpoints(this);
      } finally {
        await sendConfigurationDone();
        await this.cb();
      }
    }));
    const statusQueue = this.u;
    this.k.add(this.raw.onDidStop((event) => this.eb(event.body)));
    this.k.add(this.raw.onDidThread((event) => {
      statusQueue.cancel([event.body.threadId]);
      if (event.body.reason === "started") {
        if (!this.m) {
          this.m = new $8h(() => {
            this.cb();
          }, 100);
          this.k.add(this.m);
        }
        if (!this.m.isScheduled()) {
          this.m.schedule();
        }
      } else if (event.body.reason === "exited") {
        this.K.clearThreads(this.getId(), true, event.body.threadId);
        const viewModel = this.L.getViewModel();
        const focusedThread = viewModel.focusedThread;
        this.n.cancel();
        if (focusedThread && event.body.threadId === focusedThread.threadId) {
          this.L.focusStackFrame(void 0, void 0, viewModel.focusedSession, { explicit: false });
        }
      }
    }));
    this.k.add(this.raw.onDidTerminateDebugee(async (event) => {
      $_Z(localize(5966, null));
      if (event.body && event.body.restart) {
        await this.L.restartSession(this, event.body.restart);
      } else if (this.raw) {
        await this.raw.disconnect({ terminateDebuggee: false });
      }
    }));
    this.k.add(this.raw.onDidContinued((event) => {
      const allThreads = event.body.allThreadsContinued !== false;
      statusQueue.cancel(allThreads ? void 0 : [event.body.threadId]);
      const threadId = allThreads ? void 0 : event.body.threadId;
      if (typeof threadId === "number") {
        this.r = this.r.filter((sd) => sd.threadId !== threadId);
        const tokens = this.j.get(threadId);
        this.j.delete(threadId);
        tokens?.forEach((t) => t.dispose(true));
      } else {
        this.r = [];
        this.mb();
      }
      this.o = threadId;
      this.n.schedule();
      this.K.clearThreads(this.getId(), false, threadId);
      this.w.fire();
    }));
    const outputQueue = new $3h();
    this.k.add(this.raw.onDidOutput(async (event) => {
      const outputSeverity = event.body.category === "stderr" ? severity_default.Error : event.body.category === "console" ? severity_default.Warning : severity_default.Info;
      if (event.body.variablesReference) {
        const source = event.body.source && event.body.line ? {
          lineNumber: event.body.line,
          column: event.body.column ? event.body.column : 1,
          source: this.getSource(event.body.source)
        } : void 0;
        const container2 = new $JP(this, void 0, event.body.variablesReference, $ps());
        const children = container2.getChildren();
        outputQueue.queue(async () => {
          const resolved = await children;
          if (resolved.length === 1) {
            this.appendToRepl({ output: event.body.output, expression: resolved[0], sev: outputSeverity, source }, event.body.category === "important");
            return;
          }
          resolved.forEach((child) => {
            child.name = null;
            this.appendToRepl({ output: "", expression: child, sev: outputSeverity, source }, event.body.category === "important");
          });
        });
        return;
      }
      outputQueue.queue(async () => {
        if (!event.body || !this.raw) {
          return;
        }
        if (event.body.category === "telemetry") {
          const telemetryEndpoint = this.raw.dbgr.getCustomTelemetryEndpoint();
          if (telemetryEndpoint && this.M.telemetryLevel !== 0) {
            let data = event.body.data;
            if (!telemetryEndpoint.sendErrorTelemetry && event.body.data) {
              data = $oP(event.body.data);
            }
            this.V.publicLog(telemetryEndpoint, event.body.output, data);
          }
          return;
        }
        const source = event.body.source && event.body.line ? {
          lineNumber: event.body.line,
          column: event.body.column ? event.body.column : 1,
          source: this.getSource(event.body.source)
        } : void 0;
        if (event.body.group === "start" || event.body.group === "startCollapsed") {
          const expanded2 = event.body.group === "start";
          this.q.startGroup(this, event.body.output || "", expanded2, source);
          return;
        }
        if (event.body.group === "end") {
          this.q.endGroup();
          if (!event.body.output) {
            return;
          }
        }
        if (typeof event.body.output === "string") {
          this.appendToRepl({ output: event.body.output, sev: outputSeverity, source }, event.body.category === "important");
        }
      });
    }));
    this.k.add(this.raw.onDidBreakpoint((event) => {
      const id2 = event.body && event.body.breakpoint ? event.body.breakpoint.id : void 0;
      const breakpoint = this.K.getBreakpoints().find((bp) => bp.getIdFromAdapter(this.getId()) === id2);
      const functionBreakpoint = this.K.getFunctionBreakpoints().find((bp) => bp.getIdFromAdapter(this.getId()) === id2);
      const dataBreakpoint = this.K.getDataBreakpoints().find((dbp) => dbp.getIdFromAdapter(this.getId()) === id2);
      const exceptionBreakpoint = this.K.getExceptionBreakpoints().find((excbp) => excbp.getIdFromAdapter(this.getId()) === id2);
      if (event.body.reason === "new" && event.body.breakpoint.source && event.body.breakpoint.line) {
        const source = this.getSource(event.body.breakpoint.source);
        const bps = this.K.addBreakpoints(source.uri, [{
          column: event.body.breakpoint.column,
          enabled: true,
          lineNumber: event.body.breakpoint.line
        }], false);
        if (bps.length === 1) {
          const data = /* @__PURE__ */ new Map([[bps[0].getId(), event.body.breakpoint]]);
          this.K.setBreakpointSessionData(this.getId(), this.capabilities, data);
        }
      }
      if (event.body.reason === "removed") {
        if (breakpoint) {
          this.K.removeBreakpoints([breakpoint]);
        }
        if (functionBreakpoint) {
          this.K.removeFunctionBreakpoints(functionBreakpoint.getId());
        }
        if (dataBreakpoint) {
          this.K.removeDataBreakpoints(dataBreakpoint.getId());
        }
      }
      if (event.body.reason === "changed") {
        if (breakpoint) {
          if (!breakpoint.column) {
            event.body.breakpoint.column = void 0;
          }
          const data = /* @__PURE__ */ new Map([[breakpoint.getId(), event.body.breakpoint]]);
          this.K.setBreakpointSessionData(this.getId(), this.capabilities, data);
        }
        if (functionBreakpoint) {
          const data = /* @__PURE__ */ new Map([[functionBreakpoint.getId(), event.body.breakpoint]]);
          this.K.setBreakpointSessionData(this.getId(), this.capabilities, data);
        }
        if (dataBreakpoint) {
          const data = /* @__PURE__ */ new Map([[dataBreakpoint.getId(), event.body.breakpoint]]);
          this.K.setBreakpointSessionData(this.getId(), this.capabilities, data);
        }
        if (exceptionBreakpoint) {
          const data = /* @__PURE__ */ new Map([[exceptionBreakpoint.getId(), event.body.breakpoint]]);
          this.K.setBreakpointSessionData(this.getId(), this.capabilities, data);
        }
      }
    }));
    this.k.add(this.raw.onDidLoadedSource((event) => {
      this.y.fire({
        reason: event.body.reason,
        source: this.getSource(event.body.source)
      });
    }));
    this.k.add(this.raw.onDidCustomEvent((event) => {
      this.z.fire(event);
    }));
    this.k.add(this.raw.onDidProgressStart((event) => {
      this.A.fire(event);
    }));
    this.k.add(this.raw.onDidProgressUpdate((event) => {
      this.B.fire(event);
    }));
    this.k.add(this.raw.onDidProgressEnd((event) => {
      this.C.fire(event);
    }));
    this.k.add(this.raw.onDidInvalidateMemory((event) => {
      this.D.fire(event);
    }));
    this.k.add(this.raw.onDidInvalidated(async (event) => {
      const areas = event.body.areas || ["all"];
      if (areas.includes("threads") || areas.includes("stacks") || areas.includes("all")) {
        this.mb();
        this.K.clearThreads(this.getId(), true);
        const details = this.r;
        this.r.length = 1;
        await Promise.all(details.map((d) => this.eb(d)));
      }
      const viewModel = this.L.getViewModel();
      if (viewModel.focusedSession === this) {
        viewModel.updateViews();
      }
    }));
    this.k.add(this.raw.onDidExitAdapter((event) => this.hb(event)));
  }
  async eb(event) {
    this.n.cancel();
    this.r.push(event);
    if (event.hitBreakpointIds) {
      this.H = this.fb(event.hitBreakpointIds);
    }
    this.u.run(this.cb(event).then(() => event.threadId === void 0 ? this.h : [event.threadId]), async (threadId, token) => {
      const hasLotsOfThreads = event.threadId === void 0 && this.h.length > 10;
      const focusedThread = this.L.getViewModel().focusedThread;
      const focusedThreadDoesNotExist = focusedThread !== void 0 && focusedThread.session === this && !this.g.has(focusedThread.threadId);
      if (focusedThreadDoesNotExist) {
        this.L.focusStackFrame(void 0, void 0);
      }
      const thread = typeof threadId === "number" ? this.getThread(threadId) : void 0;
      if (thread) {
        const promises = this.K.refreshTopOfCallstack(
          thread,
          /* fetchFullStack= */
          !hasLotsOfThreads
        );
        const focus = async () => {
          if (focusedThreadDoesNotExist || !event.preserveFocusHint && thread.getCallStack().length) {
            const focusedStackFrame2 = this.L.getViewModel().focusedStackFrame;
            if (!focusedStackFrame2 || focusedStackFrame2.thread.session === this) {
              const preserveFocus = !this.O.getValue("debug").focusEditorOnBreak;
              await this.L.focusStackFrame(void 0, thread, void 0, { preserveFocus });
            }
            if (thread.stoppedDetails && !token.isCancellationRequested) {
              if (thread.stoppedDetails.reason === "breakpoint" && this.O.getValue("debug").openDebug === "openOnDebugBreak" && !this.suppressDebugView) {
                await this.P.openPaneComposite(
                  $TQ,
                  0
                  /* ViewContainerLocation.Sidebar */
                );
              }
              if (this.O.getValue("debug").focusWindowOnBreak && !this.W.extensionTestsLocationURI) {
                const activeWindow = $Qj();
                if (!activeWindow.document.hasFocus()) {
                  await this.N.focus($Y, {
                    force: true
                    /* Application may not be active */
                  });
                }
              }
            }
          }
        };
        await promises.topCallStack;
        if (!event.hitBreakpointIds) {
          this.H = this.fb(thread);
        }
        if (token.isCancellationRequested) {
          return;
        }
        focus();
        await promises.wholeCallStack;
        if (token.isCancellationRequested) {
          return;
        }
        const focusedStackFrame = this.L.getViewModel().focusedStackFrame;
        if (!focusedStackFrame || $9R(focusedStackFrame)) {
          focus();
        }
      }
      this.w.fire();
    });
  }
  async fb(hitBreakpointIdsOrThread) {
    let breakpoints;
    if (Array.isArray(hitBreakpointIdsOrThread)) {
      breakpoints = this.K.getBreakpoints().filter((bp) => hitBreakpointIdsOrThread.includes(bp.getIdFromAdapter(this.I)));
    } else {
      const frame = hitBreakpointIdsOrThread.getTopStackFrame();
      if (frame === void 0) {
        return;
      }
      if (hitBreakpointIdsOrThread.stoppedDetails && hitBreakpointIdsOrThread.stoppedDetails.reason !== "breakpoint") {
        return;
      }
      breakpoints = this.gb(frame.source.uri, frame.range.startLineNumber, frame.range.endLineNumber, frame.range.startColumn, frame.range.endColumn);
    }
    const urisToResend = /* @__PURE__ */ new Set();
    this.K.getBreakpoints({ triggeredOnly: true, enabledOnly: true }).forEach((bp) => {
      breakpoints.forEach((cbp) => {
        if (bp.enabled && bp.triggeredBy === cbp.getId()) {
          bp.setSessionDidTrigger(this.getId());
          urisToResend.add(bp.uri.toString());
        }
      });
    });
    const results = [];
    urisToResend.forEach((uri) => results.push(this.L.sendBreakpoints(URI.parse(uri), void 0, this)));
    return Promise.all(results);
  }
  gb(uri, startLineNumber, endLineNumber, startColumn, endColumn) {
    return this.K.getBreakpoints({ uri }).filter((bp) => {
      if (bp.lineNumber < startLineNumber || bp.lineNumber > endLineNumber) {
        return false;
      }
      if (bp.column && (bp.column < startColumn || bp.column > endColumn)) {
        return false;
      }
      return true;
    });
  }
  hb(event) {
    this.b = true;
    this.K.setBreakpointSessionData(this.getId(), this.capabilities, void 0);
    this.jb();
    this.x.fire(event);
  }
  // Disconnects and clears state. Session can be initialized again for a new connection.
  jb() {
    this.k.clear();
    if (this.raw) {
      this.raw.disconnect({});
      this.raw.dispose();
      this.raw = void 0;
    }
    this.m?.dispose();
    this.m = void 0;
    this.n.cancel();
    this.n.dispose();
    this.K.clearThreads(this.getId(), true);
    this.w.fire();
  }
  dispose() {
    this.mb();
    this.k.dispose();
    this.l.dispose();
  }
  //---- sources
  getSourceForUri(uri) {
    return this.f.get(this.T.asCanonicalUri(uri).toString());
  }
  getSource(raw) {
    let source = new $BP(raw, this.getId(), this.T, this.X);
    const uriKey = source.uri.toString();
    const found = this.f.get(uriKey);
    if (found) {
      source = found;
      source.raw = $Ov(source.raw, raw);
      if (source.raw && raw) {
        source.raw.presentationHint = raw.presentationHint;
      }
    } else {
      this.f.set(uriKey, source);
    }
    return source;
  }
  kb(uri) {
    const source = this.getSourceForUri(uri);
    if (source) {
      return source.raw;
    } else {
      const data = $BP.getEncodedDebugData(uri);
      return { name: data.name, path: data.path, sourceReference: data.sourceReference };
    }
  }
  lb(threadId, token) {
    const tokenSource = new $ad(token);
    const tokens = this.j.get(threadId) || [];
    tokens.push(tokenSource);
    this.j.set(threadId, tokens);
    return tokenSource.token;
  }
  mb() {
    this.j.forEach((tokens) => tokens.forEach((t) => t.dispose(true)));
    this.j.clear();
  }
  // REPL
  getReplElements() {
    return this.q.getReplElements();
  }
  hasSeparateRepl() {
    return !this.parentSession || this.c.repl !== "mergeWithParent";
  }
  removeReplExpressions() {
    this.q.removeReplExpressions();
  }
  async addReplExpression(stackFrame, expression) {
    await this.q.addReplExpression(this, stackFrame, expression);
    this.L.getViewModel().updateViews();
  }
  appendToRepl(data, isImportant) {
    this.q.appendToRepl(this, data);
    if (isImportant) {
      this.S.notify({ message: data.output.toString(), severity: data.sev, source: this.name });
    }
  }
};
$obc = __decorate([
  __param(5, $0R),
  __param(6, $zv),
  __param(7, $S4),
  __param(8, $kl),
  __param(9, $uqb),
  __param(10, $Zk),
  __param(11, $Vu),
  __param(12, $PJ),
  __param(13, $KL),
  __param(14, $vl),
  __param(15, $Pk),
  __param(16, $Av),
  __param(17, $US),
  __param(18, $wn),
  __param(19, $nTb),
  __param(20, $FTb),
  __param(21, $ND)
], $obc);
var $pbc = class extends $3c {
  constructor() {
    super(...arguments);
    this.a = [];
    this.b = this.B(new $_c());
  }
  /**
   * Runs the operation.
   * If thread is undefined it affects all threads.
   */
  async run(threadIdsP, operation) {
    const cancelledWhileLookingUpThreads = /* @__PURE__ */ new Set();
    this.a.push(cancelledWhileLookingUpThreads);
    const threadIds = await threadIdsP;
    for (let i2 = 0; i2 < this.a.length; i2++) {
      const s = this.a[i2];
      if (s === cancelledWhileLookingUpThreads) {
        this.a.splice(i2, 1);
        break;
      } else {
        for (const threadId of threadIds) {
          s.add(threadId);
        }
      }
    }
    if (cancelledWhileLookingUpThreads.has(void 0)) {
      return;
    }
    await Promise.all(threadIds.map((threadId) => {
      if (cancelledWhileLookingUpThreads.has(threadId)) {
        return;
      }
      this.b.get(threadId)?.cancel();
      const cts = new $ad();
      this.b.set(threadId, cts);
      return operation(threadId, cts.token);
    }));
  }
  /**
   * Cancels all ongoing state operations on the given threads.
   * If threads is undefined it cancel all threads.
   */
  cancel(threadIds) {
    if (!threadIds) {
      for (const [_, op] of this.b) {
        op.cancel();
      }
      this.b.clearAndDisposeAll();
      for (const s of this.a) {
        s.add(void 0);
      }
    } else {
      for (const threadId of threadIds) {
        this.b.get(threadId)?.cancel();
        this.b.deleteAndDispose(threadId);
        for (const s of this.a) {
          s.add(threadId);
        }
      }
    }
  }
};

// out-build/vs/workbench/contrib/markers/common/markers.js
var MarkersViewMode;
(function(MarkersViewMode2) {
  MarkersViewMode2["Table"] = "table";
  MarkersViewMode2["Tree"] = "tree";
})(MarkersViewMode || (MarkersViewMode = {}));
var Markers;
(function(Markers2) {
  Markers2.MARKERS_CONTAINER_ID = "workbench.panel.markers";
  Markers2.MARKERS_VIEW_ID = "workbench.panel.markers.view";
  Markers2.MARKERS_VIEW_STORAGE_ID = "workbench.panel.markers";
  Markers2.MARKER_COPY_ACTION_ID = "problems.action.copy";
  Markers2.MARKER_COPY_MESSAGE_ACTION_ID = "problems.action.copyMessage";
  Markers2.RELATED_INFORMATION_COPY_MESSAGE_ACTION_ID = "problems.action.copyRelatedInformationMessage";
  Markers2.FOCUS_PROBLEMS_FROM_FILTER = "problems.action.focusProblemsFromFilter";
  Markers2.MARKERS_VIEW_FOCUS_FILTER = "problems.action.focusFilter";
  Markers2.MARKERS_VIEW_CLEAR_FILTER_TEXT = "problems.action.clearFilterText";
  Markers2.MARKERS_VIEW_SHOW_MULTILINE_MESSAGE = "problems.action.showMultilineMessage";
  Markers2.MARKERS_VIEW_SHOW_SINGLELINE_MESSAGE = "problems.action.showSinglelineMessage";
  Markers2.MARKER_OPEN_ACTION_ID = "problems.action.open";
  Markers2.MARKER_OPEN_SIDE_ACTION_ID = "problems.action.openToSide";
  Markers2.MARKER_SHOW_PANEL_ID = "workbench.action.showErrorsWarnings";
  Markers2.MARKER_SHOW_QUICK_FIX = "problems.action.showQuickFixes";
  Markers2.TOGGLE_MARKERS_VIEW_ACTION_ID = "workbench.actions.view.toggleProblems";
})(Markers || (Markers = {}));
var MarkersContextKeys;
(function(MarkersContextKeys2) {
  MarkersContextKeys2.MarkersViewModeContextKey = new $nn(
    "problemsViewMode",
    "tree"
    /* MarkersViewMode.Tree */
  );
  MarkersContextKeys2.MarkersTreeVisibilityContextKey = new $nn("problemsVisibility", false);
  MarkersContextKeys2.MarkerFocusContextKey = new $nn("problemFocus", false);
  MarkersContextKeys2.MarkerViewFilterFocusContextKey = new $nn("problemsFilterFocus", false);
  MarkersContextKeys2.RelatedInformationFocusContextKey = new $nn("relatedInformationFocus", false);
  MarkersContextKeys2.ShowErrorsFilterContextKey = new $nn("problems.filter.errors", true);
  MarkersContextKeys2.ShowWarningsFilterContextKey = new $nn("problems.filter.warnings", true);
  MarkersContextKeys2.ShowInfoFilterContextKey = new $nn("problems.filter.info", true);
  MarkersContextKeys2.ShowActiveFileFilterContextKey = new $nn("problems.filter.activeFile", false);
  MarkersContextKeys2.ShowExcludedFilesFilterContextKey = new $nn("problems.filter.excludedFiles", true);
})(MarkersContextKeys || (MarkersContextKeys = {}));

// out-build/vs/workbench/contrib/debug/browser/debugTaskRunner.js
var onceFilter = (event, filter) => Event2.once(Event2.filter(event, filter));
var TaskRunResult;
(function(TaskRunResult2) {
  TaskRunResult2[TaskRunResult2["Failure"] = 0] = "Failure";
  TaskRunResult2[TaskRunResult2["Success"] = 1] = "Success";
})(TaskRunResult || (TaskRunResult = {}));
var DEBUG_TASK_ERROR_CHOICE_KEY = "debug.taskerrorchoice";
var ABORT_LABEL = localize(5973, null);
var DEBUG_ANYWAY_LABEL = localize(5974, null);
var DEBUG_ANYWAY_LABEL_NO_MEMO = localize(5975, null);
var $qbc = class $qbc2 {
  constructor(b, c, d, f, g, h3, i2, j) {
    this.b = b;
    this.c = c;
    this.d = d;
    this.f = f;
    this.g = g;
    this.h = h3;
    this.i = i2;
    this.j = j;
    this.a = new $ad();
  }
  cancel() {
    this.a.dispose(true);
    this.a = new $ad();
  }
  dispose() {
    this.a.dispose(true);
  }
  async runTaskAndCheckErrors(root, taskId) {
    try {
      const taskSummary = await this.runTask(root, taskId, this.a.token);
      if (taskSummary && (taskSummary.exitCode === void 0 || taskSummary.cancelled)) {
        return 0;
      }
      const errorCount = taskId ? this.c.read({ severities: MarkerSeverity.Error, take: 2 }).length : 0;
      const successExitCode = taskSummary && taskSummary.exitCode === 0;
      const failureExitCode = taskSummary && taskSummary.exitCode !== 0;
      const onTaskErrors = this.d.getValue("debug").onTaskErrors;
      if (successExitCode || onTaskErrors === "debugAnyway" || errorCount === 0 && !failureExitCode) {
        return 1;
      }
      if (onTaskErrors === "showErrors") {
        await this.f.openView(Markers.MARKERS_VIEW_ID, true);
        return Promise.resolve(
          0
          /* TaskRunResult.Failure */
        );
      }
      if (onTaskErrors === "abort") {
        return Promise.resolve(
          0
          /* TaskRunResult.Failure */
        );
      }
      const taskLabel = typeof taskId === "string" ? taskId : taskId ? taskId.name : "";
      const message = errorCount > 1 ? localize(5976, null, taskLabel) : errorCount === 1 ? localize(5977, null, taskLabel) : taskSummary && typeof taskSummary.exitCode === "number" ? localize(5978, null, taskLabel, taskSummary.exitCode) : localize(5979, null, taskLabel);
      let DebugChoice;
      (function(DebugChoice2) {
        DebugChoice2[DebugChoice2["DebugAnyway"] = 1] = "DebugAnyway";
        DebugChoice2[DebugChoice2["ShowErrors"] = 2] = "ShowErrors";
        DebugChoice2[DebugChoice2["Cancel"] = 0] = "Cancel";
      })(DebugChoice || (DebugChoice = {}));
      const { result, checkboxChecked } = await this.g.prompt({
        type: severity_default.Warning,
        message,
        buttons: [
          {
            label: DEBUG_ANYWAY_LABEL,
            run: () => DebugChoice.DebugAnyway
          },
          {
            label: localize(5980, null),
            run: () => DebugChoice.ShowErrors
          }
        ],
        cancelButton: {
          label: ABORT_LABEL,
          run: () => DebugChoice.Cancel
        },
        checkbox: {
          label: localize(5981, null)
        }
      });
      const debugAnyway = result === DebugChoice.DebugAnyway;
      const abort = result === DebugChoice.Cancel;
      if (checkboxChecked) {
        this.d.updateValue("debug.onTaskErrors", result === DebugChoice.DebugAnyway ? "debugAnyway" : abort ? "abort" : "showErrors");
      }
      if (abort) {
        return Promise.resolve(
          0
          /* TaskRunResult.Failure */
        );
      }
      if (debugAnyway) {
        return 1;
      }
      await this.f.openView(Markers.MARKERS_VIEW_ID, true);
      return Promise.resolve(
        0
        /* TaskRunResult.Failure */
      );
    } catch (err) {
      const taskConfigureAction = this.b.configureAction();
      const choiceMap = JSON.parse(this.h.get(DEBUG_TASK_ERROR_CHOICE_KEY, 1, "{}"));
      let choice = -1;
      let DebugChoice;
      (function(DebugChoice2) {
        DebugChoice2[DebugChoice2["DebugAnyway"] = 0] = "DebugAnyway";
        DebugChoice2[DebugChoice2["ConfigureTask"] = 1] = "ConfigureTask";
        DebugChoice2[DebugChoice2["Cancel"] = 2] = "Cancel";
      })(DebugChoice || (DebugChoice = {}));
      if (choiceMap[err.message] !== void 0) {
        choice = choiceMap[err.message];
      } else {
        const { result, checkboxChecked } = await this.g.prompt({
          type: severity_default.Error,
          message: err.message,
          buttons: [
            {
              label: localize(5982, null),
              run: () => DebugChoice.DebugAnyway
            },
            {
              label: taskConfigureAction.label,
              run: () => DebugChoice.ConfigureTask
            }
          ],
          cancelButton: {
            run: () => DebugChoice.Cancel
          },
          checkbox: {
            label: localize(5983, null)
          }
        });
        choice = result;
        if (checkboxChecked) {
          choiceMap[err.message] = choice;
          this.h.store(
            DEBUG_TASK_ERROR_CHOICE_KEY,
            JSON.stringify(choiceMap),
            1,
            1
            /* StorageTarget.MACHINE */
          );
        }
      }
      if (choice === DebugChoice.ConfigureTask) {
        await taskConfigureAction.run();
      }
      return choice === DebugChoice.DebugAnyway ? 1 : 0;
    }
  }
  async runTask(root, taskId, token = this.a.token) {
    if (!taskId) {
      return Promise.resolve(null);
    }
    if (!root) {
      return Promise.reject(new Error(localize(5984, null, typeof taskId === "string" ? taskId : taskId.type)));
    }
    const task = await this.b.getTask(root, taskId);
    if (!task) {
      const errorMessage = typeof taskId === "string" ? localize(5985, null, taskId) : localize(5986, null);
      return Promise.reject($3m(errorMessage, [new $Um($V4b, $m5b, void 0, true, () => this.i.executeCommand($V4b))]));
    }
    let taskStarted = false;
    const store = new $2c();
    const getTaskKey = (t) => t.getKey() ?? t.getMapKey();
    const taskKey = getTaskKey(task);
    const inactivePromise = new Promise((resolve) => store.add(onceFilter(this.b.onDidStateChange, (e) => {
      return (e.kind === "inactive" || e.kind === "processEnded" && e.exitCode === void 0) && getTaskKey(e.__task) === taskKey;
    })((e) => {
      taskStarted = true;
      resolve(e.kind === "processEnded" ? { exitCode: e.exitCode } : null);
    })));
    store.add(onceFilter(this.b.onDidStateChange, (e) => (e.kind === "active" || e.kind === "dependsOnStarted") && getTaskKey(e.__task) === taskKey)(() => {
      taskStarted = true;
    }));
    const didAcquireInput = store.add(new $ze());
    store.add(onceFilter(this.b.onDidStateChange, (e) => e.kind === "acquiredInput" && getTaskKey(e.__task) === taskKey)(() => didAcquireInput.fire()));
    const taskDonePromise = this.b.getActiveTasks().then(async (tasks2) => {
      if (tasks2.find((t) => getTaskKey(t) === taskKey)) {
        didAcquireInput.fire();
        const busyTasks = await this.b.getBusyTasks();
        if (busyTasks.find((t) => getTaskKey(t) === taskKey)) {
          taskStarted = true;
          return inactivePromise;
        }
        return Promise.resolve(null);
      }
      const taskPromise = this.b.run(task);
      if (task.configurationProperties.isBackground) {
        return inactivePromise;
      }
      return taskPromise.then((x) => x ?? null);
    });
    const result = new Promise((resolve, reject) => {
      taskDonePromise.then((result2) => {
        taskStarted = true;
        resolve(result2);
      }, (error) => reject(error));
      store.add(token.onCancellationRequested(() => {
        resolve({ exitCode: void 0, cancelled: true });
        this.b.terminate(task).catch(() => {
        });
      }));
      store.add(didAcquireInput.event(() => {
        const waitTime = task.configurationProperties.isBackground ? 5e3 : 1e4;
        store.add($Xh(() => {
          if (!taskStarted) {
            const errorMessage = localize(5987, null, typeof taskId === "string" ? taskId : JSON.stringify(taskId));
            reject({ severity: severity_default.Error, message: errorMessage });
          }
        }, waitTime));
        const hideSlowPreLaunchWarning = this.d.getValue("debug").hideSlowPreLaunchWarning;
        if (!hideSlowPreLaunchWarning) {
          store.add($Xh(() => {
            const message = localize(5988, null, task.configurationProperties.name);
            const buttons = [DEBUG_ANYWAY_LABEL_NO_MEMO, ABORT_LABEL];
            const canConfigure = task instanceof $gQ || task instanceof $hQ;
            if (canConfigure) {
              buttons.splice(1, 0, localize(5989, null));
            }
            this.j.withProgress({ location: 15, title: message, buttons }, () => result.catch(() => {
            }), (choice) => {
              if (choice === void 0) {
              } else if (choice === 0) {
                resolve({ exitCode: 0 });
              } else {
                resolve({ exitCode: void 0, cancelled: true });
                this.b.terminate(task).catch(() => {
                });
                if (canConfigure && choice === 1) {
                  this.b.openConfig(task);
                }
              }
            });
          }, 1e4));
        }
      }));
    });
    return result.finally(() => store.dispose());
  }
};
$qbc = __decorate([
  __param(0, $3Sb),
  __param(1, $DE),
  __param(2, $kl),
  __param(3, $uob),
  __param(4, $Yv),
  __param(5, $jv),
  __param(6, $sn),
  __param(7, $TJ)
], $qbc);

// out-build/vs/workbench/contrib/debug/browser/debugService.js
var $rbc = class $rbc2 {
  constructor(J, K, L, M, N, O, P, Q, R, S, T, U, V, W, X, Y, Z, $149, ab, bb, cb) {
    this.J = J;
    this.K = K;
    this.L = L;
    this.M = M;
    this.N = N;
    this.O = O;
    this.P = P;
    this.Q = Q;
    this.R = R;
    this.S = S;
    this.T = T;
    this.U = U;
    this.V = V;
    this.W = W;
    this.X = X;
    this.Y = Y;
    this.Z = Z;
    this.$ = $149;
    this.ab = ab;
    this.bb = bb;
    this.cb = cb;
    this.h = /* @__PURE__ */ new Set();
    this.r = new $2c();
    this.C = false;
    this.F = /* @__PURE__ */ new Map();
    this.I = false;
    this.B = /* @__PURE__ */ new Set();
    this.a = new $ze();
    this.b = new $ze();
    this.f = new $ze();
    this.g = new $ze();
    this.q = this.T.createInstance($kbc, {
      onDidNewSession: this.onDidNewSession,
      configurationManager: () => this.p
    });
    this.r.add(this.q);
    this.p = this.T.createInstance($lbc, this.q);
    this.r.add(this.p);
    this.i = this.r.add(this.T.createInstance($DP));
    this.H = this.i.loadChosenEnvironments();
    this.j = this.T.createInstance($2P, this.i);
    this.m = this.T.createInstance($cbc, this.j);
    this.k = new $dbc(R);
    this.o = this.T.createInstance($qbc);
    this.r.add(this.V.onDidFilesChange((e) => this.vb(e)));
    this.r.add(this.S.onWillShutdown(this.dispose, this));
    this.r.add(this.X.onAttachSession((event) => {
      const session = this.j.getSession(event.sessionId, true);
      if (session) {
        session.configuration.request = "attach";
        session.configuration.port = event.port;
        session.setSubId(event.subId);
        this.lb(session);
      }
    }));
    this.r.add(this.X.onTerminateSession((event) => {
      const session = this.j.getSession(event.sessionId);
      if (session && session.subId === event.subId) {
        session.disconnect();
      }
    }));
    this.r.add(this.k.onDidFocusStackFrame(() => {
      this.hb();
    }));
    this.r.add(this.k.onDidFocusSession((session) => {
      this.hb();
      if (session) {
        this.setExceptionBreakpointFallbackSession(session.getId());
      }
    }));
    this.r.add(Event2.any(this.q.onDidRegisterDebugger, this.p.onDidSelectConfiguration)(() => {
      const debugUxValue = this.state !== 0 || this.p.getAllConfigurations().length > 0 && this.q.hasEnabledDebuggers() ? "default" : "simple";
      this.x.set(debugUxValue);
      this.i.storeDebugUxState(debugUxValue);
    }));
    this.r.add(this.j.onDidChangeCallStack(() => {
      const numberOfSessions = this.j.getSessions().filter((s) => !s.parentSession).length;
      this.G?.dispose();
      if (numberOfSessions > 0) {
        const viewContainer5 = this.M.getViewContainerByViewId($WQ);
        if (viewContainer5) {
          this.G = this.Y.showViewContainerActivity(viewContainer5.id, { badge: new $wqb(numberOfSessions, (n) => n === 1 ? localize(5902, null) : localize(5903, null, n)) });
        }
      }
    }));
    this.r.add(J.onDidActiveEditorChange(() => {
      this.R.bufferChangeEvents(() => {
        if (J.activeEditor === $IP.instance) {
          this.A.set(true);
        } else {
          this.A?.reset();
        }
      });
    }));
    this.r.add(this.S.onBeforeShutdown(() => {
      for (const editor of J.editors) {
        if (editor.resource?.scheme === $8R) {
          editor.dispose();
        }
      }
    }));
    this.r.add(U.onWillStop((evt) => {
      evt.veto(this.j.getSessions().length > 0, localize(5904, null));
    }));
    this.db(R);
  }
  db(contextKeyService) {
    queueMicrotask(() => {
      contextKeyService.bufferChangeEvents(() => {
        this.u = $3Q.bindTo(contextKeyService);
        this.v = $5Q.bindTo(contextKeyService);
        this.y = $8Q.bindTo(contextKeyService);
        this.w = $9Q.bindTo(contextKeyService);
        this.x = $7Q.bindTo(contextKeyService);
        this.x.set(this.i.loadDebugUxState());
        this.z = $AR.bindTo(contextKeyService);
        this.A = $YR.bindTo(contextKeyService);
      });
      const setBreakpointsExistContext = () => this.z.set(!!(this.j.getBreakpoints().length || this.j.getDataBreakpoints().length || this.j.getFunctionBreakpoints().length));
      setBreakpointsExistContext();
      this.r.add(this.j.onDidChangeBreakpoints(() => setBreakpointsExistContext()));
    });
  }
  getModel() {
    return this.j;
  }
  getViewModel() {
    return this.k;
  }
  getConfigurationManager() {
    return this.p;
  }
  getAdapterManager() {
    return this.q;
  }
  sourceIsNotAvailable(uri) {
    this.j.sourceIsNotAvailable(uri);
  }
  dispose() {
    this.r.dispose();
  }
  //---- state management
  get state() {
    const focusedSession = this.k.focusedSession;
    if (focusedSession) {
      return focusedSession.state;
    }
    return this.C ? 1 : 0;
  }
  get initializingOptions() {
    return this.D;
  }
  eb(options3) {
    if (!this.C) {
      this.C = true;
      this.D = options3;
      this.hb();
    }
  }
  fb() {
    if (this.C) {
      this.C = false;
      this.D = void 0;
      this.hb();
    }
  }
  gb(id2) {
    if (id2) {
      const token = this.F.get(id2);
      if (token) {
        token.cancel();
        this.F.delete(id2);
      }
    } else {
      this.F.forEach((t) => t.cancel());
      this.F.clear();
    }
  }
  hb() {
    const state = this.state;
    if (this.E !== state) {
      this.R.bufferChangeEvents(() => {
        this.v.set($7R(state));
        this.w.set(
          state !== 0
          /* State.Inactive */
        );
        const debugUxValue = state !== 0 && state !== 1 || this.q.hasEnabledDebuggers() && this.p.selectedConfiguration.name ? "default" : "simple";
        this.x.set(debugUxValue);
        this.i.storeDebugUxState(debugUxValue);
      });
      this.E = state;
      this.a.fire(state);
    }
  }
  get onDidChangeState() {
    return this.a.event;
  }
  get onDidNewSession() {
    return this.b.event;
  }
  get onWillNewSession() {
    return this.f.event;
  }
  get onDidEndSession() {
    return this.g.event;
  }
  ib() {
    if (!this.I) {
      this.r.add(this.V.registerProvider($8R, new $mbc(this)));
      this.I = true;
    }
  }
  //---- life cycle management
  /**
   * main entry point
   * properly manages compounds, checks for errors and handles the initializing state.
   */
  async startDebugging(launch, configOrName, options3, saveBeforeStart = !options3?.parentSession) {
    const message = options3 && options3.noDebug ? localize(5905, null) : localize(5906, null);
    const trust = await this.ab.requestWorkspaceTrust({ message });
    if (!trust) {
      return false;
    }
    this.ib();
    this.eb(options3);
    this.y.set(true);
    try {
      await this.U.activateByEvent("onDebug");
      if (saveBeforeStart) {
        await $yP(this.W, this.J);
      }
      await this.U.whenInstalledExtensionsRegistered();
      let config;
      let compound;
      if (!configOrName) {
        configOrName = this.p.selectedConfiguration.name;
      }
      if (typeof configOrName === "string" && launch) {
        config = launch.getConfiguration(configOrName);
        compound = launch.getCompound(configOrName);
      } else if (typeof configOrName !== "string") {
        config = configOrName;
      }
      if (compound) {
        if (!compound.configurations) {
          throw new Error(localize(5907, null));
        }
        if (compound.preLaunchTask) {
          const taskResult = await this.o.runTaskAndCheckErrors(launch?.workspace || this.Q.getWorkspace(), compound.preLaunchTask);
          if (taskResult === 0) {
            this.fb();
            return false;
          }
        }
        if (compound.stopAll) {
          options3 = { ...options3, compoundRoot: new $lP() };
        }
        const values = await Promise.all(compound.configurations.map((configData) => {
          const name = typeof configData === "string" ? configData : configData.name;
          if (name === compound.name) {
            return Promise.resolve(false);
          }
          let launchForName;
          if (typeof configData === "string") {
            const launchesContainingName = this.p.getLaunches().filter((l) => !!l.getConfiguration(name));
            if (launchesContainingName.length === 1) {
              launchForName = launchesContainingName[0];
            } else if (launch && launchesContainingName.length > 1 && launchesContainingName.indexOf(launch) >= 0) {
              launchForName = launch;
            } else {
              throw new Error(launchesContainingName.length === 0 ? localize(5908, null, name) : localize(5909, null, name));
            }
          } else if (configData.folder) {
            const launchesMatchingConfigData = this.p.getLaunches().filter((l) => l.workspace && l.workspace.name === configData.folder && !!l.getConfiguration(configData.name));
            if (launchesMatchingConfigData.length === 1) {
              launchForName = launchesMatchingConfigData[0];
            } else {
              throw new Error(localize(5910, null, configData.folder, configData.name, compound.name));
            }
          }
          return this.jb(launchForName, launchForName.getConfiguration(name), options3);
        }));
        const result2 = values.every((success) => !!success);
        this.fb();
        return result2;
      }
      if (configOrName && !config) {
        const message2 = !!launch ? localize(5911, null, typeof configOrName === "string" ? configOrName : configOrName.name) : localize(5912, null);
        throw new Error(message2);
      }
      const result = await this.jb(launch, config, options3);
      this.fb();
      return result;
    } catch (err) {
      this.N.error(err);
      this.fb();
      return Promise.reject(err);
    }
  }
  /**
   * gets the debugger for the type, resolves configurations by providers, substitutes variables and runs prelaunch tasks
   */
  async jb(launch, config, options3) {
    let type;
    if (config) {
      type = config.type;
    } else {
      config = /* @__PURE__ */ Object.create(null);
    }
    if (options3 && options3.noDebug) {
      config.noDebug = true;
    } else if (options3 && typeof options3.noDebug === "undefined" && options3.parentSession && options3.parentSession.configuration.noDebug) {
      config.noDebug = true;
    }
    const unresolvedConfig = $Lv(config);
    let guess;
    let activeEditor;
    if (!type) {
      activeEditor = this.J.activeEditor;
      if (activeEditor && activeEditor.resource) {
        const chosen = this.H[activeEditor.resource.toString()];
        if (chosen) {
          type = chosen.type;
          if (chosen.dynamicLabel) {
            const dyn = await this.p.getDynamicConfigurationsByType(chosen.type);
            const found = dyn.find((d) => d.label === chosen.dynamicLabel);
            if (found) {
              launch = found.launch;
              Object.assign(config, found.config);
            }
          }
        }
      }
      if (!type) {
        guess = await this.q.guessDebugger(false);
        if (guess) {
          type = guess.debugger.type;
          if (guess.withConfig) {
            launch = guess.withConfig.launch;
            Object.assign(config, guess.withConfig.config);
          }
        }
      }
    }
    const initCancellationToken = new $ad();
    const sessionId = $ps();
    this.F.set(sessionId, initCancellationToken);
    const configByProviders = await this.p.resolveConfigurationByProviders(launch && launch.workspace ? launch.workspace.uri : void 0, type, config, initCancellationToken.token);
    if (configByProviders && configByProviders.type) {
      try {
        let resolvedConfig = await this.nb(launch, configByProviders);
        if (!resolvedConfig) {
          return false;
        }
        if (initCancellationToken.token.isCancellationRequested) {
          return false;
        }
        const workspace2 = launch?.workspace || this.Q.getWorkspace();
        const taskResult = await this.o.runTaskAndCheckErrors(workspace2, resolvedConfig.preLaunchTask);
        if (taskResult === 0) {
          return false;
        }
        const cfg = await this.p.resolveDebugConfigurationWithSubstitutedVariables(launch && launch.workspace ? launch.workspace.uri : void 0, resolvedConfig.type, resolvedConfig, initCancellationToken.token);
        if (!cfg) {
          if (launch && type && cfg === null && !initCancellationToken.token.isCancellationRequested) {
            await launch.openConfigFile({ preserveFocus: true, type }, initCancellationToken.token);
          }
          return false;
        }
        resolvedConfig = cfg;
        const dbg = this.q.getDebugger(resolvedConfig.type);
        if (!dbg || configByProviders.request !== "attach" && configByProviders.request !== "launch") {
          let message;
          if (configByProviders.request !== "attach" && configByProviders.request !== "launch") {
            message = configByProviders.request ? localize(5913, null, "request", configByProviders.request) : localize(5914, null, "request");
          } else {
            message = resolvedConfig.type ? localize(5915, null, resolvedConfig.type) : localize(5916, null);
          }
          const actionList = [];
          actionList.push(new $Um("installAdditionalDebuggers", localize(5917, null, resolvedConfig.type), void 0, true, async () => this.Z.executeCommand("debug.installAdditionalDebuggers", resolvedConfig?.type)));
          await this.ob(message, actionList);
          return false;
        }
        if (!dbg.enabled) {
          await this.ob($2R(dbg.type), []);
          return false;
        }
        const result = await this.kb(sessionId, launch?.workspace, { resolved: resolvedConfig, unresolved: unresolvedConfig }, options3);
        if (result && guess && activeEditor && activeEditor.resource) {
          this.H[activeEditor.resource.toString()] = { type: guess.debugger.type, dynamicLabel: guess.withConfig?.label };
          this.i.storeChosenEnvironments(this.H);
        }
        return result;
      } catch (err) {
        if (err && err.message) {
          await this.ob(err.message);
        } else if (this.Q.getWorkbenchState() === 1) {
          await this.ob(localize(5918, null));
        }
        if (launch && !initCancellationToken.token.isCancellationRequested) {
          await launch.openConfigFile({ preserveFocus: true }, initCancellationToken.token);
        }
        return false;
      }
    }
    if (launch && type && configByProviders === null && !initCancellationToken.token.isCancellationRequested) {
      await launch.openConfigFile({ preserveFocus: true, type }, initCancellationToken.token);
    }
    return false;
  }
  /**
   * instantiates the new session, initializes the session, registers session listeners and reports telemetry
   */
  async kb(sessionId, root, configuration2, options3) {
    const session = this.T.createInstance($obc, sessionId, configuration2, root, this.j, options3);
    if (options3?.startedByUser && this.j.getSessions().some((s) => s.getLabel() === session.getLabel()) && configuration2.resolved.suppressMultipleSessionWarning !== true) {
      const result = await this.O.confirm({ message: localize(5919, null, session.getLabel()) });
      if (!result.confirmed) {
        return false;
      }
    }
    this.j.addSession(session);
    this.f.fire(session);
    const openDebug = this.W.getValue("debug").openDebug;
    if (!configuration2.resolved.noDebug && (openDebug === "openOnSessionStart" || openDebug !== "neverOpen" && this.k.firstSessionStart) && !session.suppressDebugView) {
      await this.K.openPaneComposite(
        $TQ,
        0
        /* ViewContainerLocation.Sidebar */
      );
    }
    try {
      await this.lb(session);
      const internalConsoleOptions = session.configuration.internalConsoleOptions || this.W.getValue("debug").internalConsoleOptions;
      if (internalConsoleOptions === "openOnSessionStart" || this.k.firstSessionStart && internalConsoleOptions === "openOnFirstSessionStart") {
        this.L.openView($2Q, false);
      }
      this.k.firstSessionStart = false;
      const showSubSessions = this.W.getValue("debug").showSubSessionsInToolBar;
      const sessions = this.j.getSessions();
      const shownSessions = showSubSessions ? sessions : sessions.filter((s) => !s.parentSession);
      if (shownSessions.length > 1) {
        this.k.setMultiSessionView(true);
      }
      this.b.fire(session);
      return true;
    } catch (error) {
      if ($kb(error)) {
        return false;
      }
      if (session && session.getReplElements().length > 0) {
        this.L.openView($2Q, false);
      }
      if (session.configuration && session.configuration.request === "attach" && session.configuration.__autoAttach) {
        return false;
      }
      const errorMessage = error instanceof Error ? error.message : error;
      if (error.showUser !== false) {
        await this.ob(errorMessage, $2m(error) ? error.actions : []);
      }
      return false;
    }
  }
  async lb(session, forceFocus = false) {
    this.mb(session);
    const dbgr = this.q.getDebugger(session.configuration.type);
    try {
      await session.initialize(dbgr);
      await session.launchOrAttach(session.configuration);
      const launchJsonExists = !!session.root && !!this.W.getValue("launch", { resource: session.root.uri });
      await this.m.logDebugSessionStart(dbgr, launchJsonExists);
      if (forceFocus || !this.k.focusedSession || session.parentSession === this.k.focusedSession && session.compact) {
        await this.focusStackFrame(void 0, void 0, session);
      }
    } catch (err) {
      if (this.k.focusedSession === session) {
        await this.focusStackFrame(void 0);
      }
      return Promise.reject(err);
    }
  }
  mb(session) {
    const listenerDisposables = new $2c();
    this.r.add(listenerDisposables);
    const sessionRunningScheduler = listenerDisposables.add(new $8h(() => {
      if (session.state === 3 && this.k.focusedSession === session) {
        this.k.setFocus(void 0, this.k.focusedThread, session, false);
      }
    }, 200));
    listenerDisposables.add(session.onDidChangeState(() => {
      if (session.state === 3 && this.k.focusedSession === session) {
        sessionRunningScheduler.schedule();
      }
      if (session === this.k.focusedSession) {
        this.hb();
      }
    }));
    listenerDisposables.add(this.onDidEndSession((e) => {
      if (e.session === session) {
        this.r.delete(listenerDisposables);
      }
    }));
    listenerDisposables.add(session.onDidEndAdapter(async (adapterExitEvent) => {
      if (adapterExitEvent) {
        if (adapterExitEvent.error) {
          this.N.error(localize(5920, null, adapterExitEvent.error.message || adapterExitEvent.error.toString()));
        }
        this.m.logDebugSessionStop(session, adapterExitEvent);
      }
      const extensionDebugSession = $qP(session);
      if (extensionDebugSession && extensionDebugSession.state === 3 && extensionDebugSession.configuration.noDebug) {
        this.X.close(extensionDebugSession.getId());
      }
      if (session.configuration.postDebugTask) {
        const root = session.root ?? this.Q.getWorkspace();
        try {
          await this.o.runTask(root, session.configuration.postDebugTask);
        } catch (err) {
          this.N.error(err);
        }
      }
      this.fb();
      this.gb(session.getId());
      if (this.W.getValue("debug").closeReadonlyTabsOnEnd) {
        const editorsToClose = this.J.getEditors(
          1
          /* EditorsOrder.SEQUENTIAL */
        ).filter(({ editor }) => {
          return editor.resource?.scheme === $5R && session.getId() === $BP.getEncodedDebugData(editor.resource).sessionId;
        });
        this.J.closeEditors(editorsToClose);
      }
      this.g.fire({ session, restart: this.h.has(session) });
      const focusedSession = this.k.focusedSession;
      if (focusedSession && focusedSession.getId() === session.getId()) {
        const { session: session2, thread, stackFrame } = $sbc(this.j, void 0, void 0, void 0, focusedSession);
        this.k.setFocus(stackFrame, thread, session2, false);
      }
      if (this.j.getSessions().length === 0) {
        this.k.setMultiSessionView(false);
        if (this.P.isVisible(
          "workbench.parts.sidebar"
          /* Parts.SIDEBAR_PART */
        ) && this.W.getValue("debug").openExplorerOnEnd) {
          this.K.openPaneComposite(
            $3sb,
            0
            /* ViewContainerLocation.Sidebar */
          );
        }
        const dataBreakpoints = this.j.getDataBreakpoints().filter((dbp) => !dbp.canPersist);
        dataBreakpoints.forEach((dbp) => this.j.removeDataBreakpoints(dbp.getId()));
        if (this.W.getValue("debug").console.closeOnEnd) {
          const debugConsoleContainer = this.M.getViewContainerByViewId($2Q);
          if (debugConsoleContainer && this.L.isViewContainerVisible(debugConsoleContainer.id)) {
            this.L.closeViewContainer(debugConsoleContainer.id);
          }
        }
      }
      this.j.removeExceptionBreakpointsForSession(session.getId());
    }));
  }
  async restartSession(session, restartData) {
    if (session.saveBeforeRestart) {
      await $yP(this.W, this.J);
    }
    const isAutoRestart = !!restartData;
    const runTasks = async () => {
      if (isAutoRestart) {
        return Promise.resolve(
          1
          /* TaskRunResult.Success */
        );
      }
      const root = session.root || this.Q.getWorkspace();
      await this.o.runTask(root, session.configuration.preRestartTask);
      await this.o.runTask(root, session.configuration.postDebugTask);
      const taskResult1 = await this.o.runTaskAndCheckErrors(root, session.configuration.preLaunchTask);
      if (taskResult1 !== 1) {
        return taskResult1;
      }
      return this.o.runTaskAndCheckErrors(root, session.configuration.postRestartTask);
    };
    const extensionDebugSession = $qP(session);
    if (extensionDebugSession) {
      const taskResult = await runTasks();
      if (taskResult === 1) {
        this.X.reload(extensionDebugSession.getId());
      }
      return;
    }
    let needsToSubstitute = false;
    let unresolved;
    const launch = session.root ? this.p.getLaunch(session.root.uri) : void 0;
    if (launch) {
      unresolved = launch.getConfiguration(session.configuration.name);
      if (unresolved && !$Pv(unresolved, session.unresolvedConfiguration)) {
        unresolved.noDebug = session.configuration.noDebug;
        needsToSubstitute = true;
      }
    }
    let resolved = session.configuration;
    if (launch && needsToSubstitute && unresolved) {
      const initCancellationToken = new $ad();
      this.F.set(session.getId(), initCancellationToken);
      const resolvedByProviders = await this.p.resolveConfigurationByProviders(launch.workspace ? launch.workspace.uri : void 0, unresolved.type, unresolved, initCancellationToken.token);
      if (resolvedByProviders) {
        resolved = await this.nb(launch, resolvedByProviders);
        if (resolved && !initCancellationToken.token.isCancellationRequested) {
          resolved = await this.p.resolveDebugConfigurationWithSubstitutedVariables(launch && launch.workspace ? launch.workspace.uri : void 0, resolved.type, resolved, initCancellationToken.token);
        }
      } else {
        resolved = resolvedByProviders;
      }
    }
    if (resolved) {
      session.setConfiguration({ resolved, unresolved });
    }
    session.configuration.__restart = restartData;
    const doRestart = async (fn) => {
      this.h.add(session);
      let didRestart = false;
      try {
        didRestart = await fn() !== false;
      } catch (e) {
        didRestart = false;
        throw e;
      } finally {
        this.h.delete(session);
        if (!didRestart) {
          this.g.fire({ session, restart: false });
        }
      }
    };
    for (const breakpoint of this.j.getBreakpoints({ triggeredOnly: true })) {
      breakpoint.setSessionDidTrigger(session.getId(), false);
    }
    if (session.correlatedTestRun) {
      if (!session.correlatedTestRun.completedAt) {
        this.cb.cancelTestRun(session.correlatedTestRun.id);
        await Event2.toPromise(session.correlatedTestRun.onComplete);
      }
      this.cb.runResolvedTests(session.correlatedTestRun.request);
      return;
    }
    if (session.capabilities.supportsRestartRequest) {
      const taskResult = await runTasks();
      if (taskResult === 1) {
        await doRestart(async () => {
          await session.restart();
          return true;
        });
      }
      return;
    }
    const shouldFocus = !!this.k.focusedSession && session.getId() === this.k.focusedSession.getId();
    return doRestart(async () => {
      if (isAutoRestart) {
        await session.disconnect(true);
      } else {
        await session.terminate(true);
      }
      return new Promise((c, e) => {
        setTimeout(async () => {
          const taskResult = await runTasks();
          if (taskResult !== 1) {
            return c(false);
          }
          if (!resolved) {
            return c(false);
          }
          try {
            await this.lb(session, shouldFocus);
            this.b.fire(session);
            c(true);
          } catch (error) {
            e(error);
          }
        }, 300);
      });
    });
  }
  async stopSession(session, disconnect = false, suspend = false) {
    if (session) {
      return disconnect ? session.disconnect(void 0, suspend) : session.terminate();
    }
    const sessions = this.j.getSessions();
    if (sessions.length === 0) {
      this.o.cancel();
      await this.$.cancel();
      this.fb();
      this.gb(void 0);
    }
    return Promise.all(sessions.map((s) => disconnect ? s.disconnect(void 0, suspend) : s.terminate()));
  }
  async nb(launch, config) {
    const dbg = this.q.getDebugger(config.type);
    if (dbg) {
      let folder = void 0;
      if (launch && launch.workspace) {
        folder = launch.workspace;
      } else {
        const folders = this.Q.getWorkspace().folders;
        if (folders.length === 1) {
          folder = folders[0];
        }
      }
      try {
        return await dbg.substituteVariables(folder, config);
      } catch (err) {
        this.ob(err.message, void 0, !!launch?.getConfiguration(config.name));
        return void 0;
      }
    }
    return Promise.resolve(config);
  }
  async ob(message, errorActions = [], promptLaunchJson = true) {
    const configureAction = new $Um($V4b, $m5b, void 0, true, () => this.Z.executeCommand($V4b));
    const actions = errorActions.filter((action) => action.id.endsWith(".command")).length > 0 ? errorActions : [...errorActions, ...promptLaunchJson ? [configureAction] : []];
    await this.O.prompt({
      type: severity_default.Error,
      message,
      buttons: actions.map((action) => ({
        label: action.label,
        run: () => action.run()
      })),
      cancelButton: true
    });
  }
  //---- focus management
  async focusStackFrame(_stackFrame, _thread, _session, options3) {
    const { stackFrame, thread, session } = $sbc(this.j, _stackFrame, _thread, _session);
    if (stackFrame) {
      const editor = await stackFrame.openInEditor(this.J, options3?.preserveFocus ?? true, options3?.sideBySide, options3?.pinned);
      if (editor) {
        if (editor.input === $IP.instance) {
        } else {
          const control = editor.getControl();
          if (stackFrame && $P5(control) && control.hasModel()) {
            const model = control.getModel();
            const lineNumber = stackFrame.range.startLineNumber;
            if (lineNumber >= 1 && lineNumber <= model.getLineCount()) {
              const lineContent = control.getModel().getLineContent(lineNumber);
              $$Z(localize(5921, null, lineContent, thread && thread.stoppedDetails ? `, reason ${thread.stoppedDetails.reason}` : "", stackFrame.source ? stackFrame.source.name : "", stackFrame.range.startLineNumber));
            }
          }
        }
      }
    }
    if (session) {
      this.u.set(session.configuration.type);
    } else {
      this.u.reset();
    }
    this.k.setFocus(stackFrame, thread, session, !!options3?.explicit);
  }
  //---- watches
  addWatchExpression(name) {
    const we = this.j.addWatchExpression(name);
    if (!name) {
      this.k.setSelectedExpression(we, false);
    }
    this.i.storeWatchExpressions(this.j.getWatchExpressions());
  }
  renameWatchExpression(id2, newName) {
    this.j.renameWatchExpression(id2, newName);
    this.i.storeWatchExpressions(this.j.getWatchExpressions());
  }
  moveWatchExpression(id2, position) {
    this.j.moveWatchExpression(id2, position);
    this.i.storeWatchExpressions(this.j.getWatchExpressions());
  }
  removeWatchExpressions(id2) {
    this.j.removeWatchExpressions(id2);
    this.i.storeWatchExpressions(this.j.getWatchExpressions());
  }
  //---- breakpoints
  canSetBreakpointsIn(model) {
    return this.q.canSetBreakpointsIn(model);
  }
  async enableOrDisableBreakpoints(enable, breakpoint) {
    if (breakpoint) {
      this.j.setEnablement(breakpoint, enable);
      this.i.storeBreakpoints(this.j);
      if (breakpoint instanceof $VP) {
        await this.qb(enable, breakpoint);
        await this.sendBreakpoints(breakpoint.originalUri);
      } else if (breakpoint instanceof $WP) {
        await this.rb();
      } else if (breakpoint instanceof $XP) {
        await this.sb();
      } else if (breakpoint instanceof $ZP) {
        await this.tb();
      } else {
        await this.ub();
      }
    } else {
      this.j.enableOrDisableAllBreakpoints(enable);
      this.i.storeBreakpoints(this.j);
      await this.sendAllBreakpoints();
    }
    this.i.storeBreakpoints(this.j);
  }
  async addBreakpoints(uri, rawBreakpoints, ariaAnnounce = true) {
    const breakpoints = this.j.addBreakpoints(uri, rawBreakpoints);
    if (ariaAnnounce) {
      breakpoints.forEach((bp) => $_Z(localize(5922, null, bp.lineNumber, uri.fsPath)));
    }
    this.i.storeBreakpoints(this.j);
    await this.sendBreakpoints(uri);
    this.i.storeBreakpoints(this.j);
    return breakpoints;
  }
  async updateBreakpoints(uri, data, sendOnResourceSaved) {
    this.j.updateBreakpoints(data);
    this.i.storeBreakpoints(this.j);
    if (sendOnResourceSaved) {
      this.B.add(uri);
    } else {
      await this.sendBreakpoints(uri);
      this.i.storeBreakpoints(this.j);
    }
  }
  async removeBreakpoints(id2) {
    const breakpoints = this.j.getBreakpoints();
    const toRemove = breakpoints.filter((bp) => !id2 || bp.getId() === id2);
    toRemove.forEach((bp) => $_Z(localize(5923, null, bp.lineNumber, bp.uri.fsPath)));
    const urisToClear = new Set(toRemove.map((bp) => bp.originalUri.toString()));
    this.j.removeBreakpoints(toRemove);
    this.pb(breakpoints, toRemove).forEach((uri) => urisToClear.add(uri.toString()));
    this.i.storeBreakpoints(this.j);
    await Promise.all([...urisToClear].map((uri) => this.sendBreakpoints(URI.parse(uri))));
  }
  setBreakpointsActivated(activated) {
    this.j.setBreakpointsActivated(activated);
    return this.sendAllBreakpoints();
  }
  async addFunctionBreakpoint(opts, id2) {
    this.j.addFunctionBreakpoint(opts ?? { name: "" }, id2);
    if (opts) {
      this.i.storeBreakpoints(this.j);
      await this.rb();
      this.i.storeBreakpoints(this.j);
    }
  }
  async updateFunctionBreakpoint(id2, update) {
    this.j.updateFunctionBreakpoint(id2, update);
    this.i.storeBreakpoints(this.j);
    await this.rb();
  }
  async removeFunctionBreakpoints(id2) {
    this.j.removeFunctionBreakpoints(id2);
    this.i.storeBreakpoints(this.j);
    await this.rb();
  }
  async addDataBreakpoint(opts) {
    this.j.addDataBreakpoint(opts);
    this.i.storeBreakpoints(this.j);
    await this.sb();
    this.i.storeBreakpoints(this.j);
  }
  async updateDataBreakpoint(id2, update) {
    this.j.updateDataBreakpoint(id2, update);
    this.i.storeBreakpoints(this.j);
    await this.sb();
  }
  async removeDataBreakpoints(id2) {
    this.j.removeDataBreakpoints(id2);
    this.i.storeBreakpoints(this.j);
    await this.sb();
  }
  async addInstructionBreakpoint(opts) {
    this.j.addInstructionBreakpoint(opts);
    this.i.storeBreakpoints(this.j);
    await this.tb();
    this.i.storeBreakpoints(this.j);
  }
  async removeInstructionBreakpoints(instructionReference, offset) {
    this.j.removeInstructionBreakpoints(instructionReference, offset);
    this.i.storeBreakpoints(this.j);
    await this.tb();
  }
  setExceptionBreakpointFallbackSession(sessionId) {
    this.j.setExceptionBreakpointFallbackSession(sessionId);
    this.i.storeBreakpoints(this.j);
  }
  setExceptionBreakpointsForSession(session, filters2) {
    this.j.setExceptionBreakpointsForSession(session.getId(), filters2);
    this.i.storeBreakpoints(this.j);
  }
  async setExceptionBreakpointCondition(exceptionBreakpoint, condition) {
    this.j.setExceptionBreakpointCondition(exceptionBreakpoint, condition);
    this.i.storeBreakpoints(this.j);
    await this.ub();
  }
  async sendAllBreakpoints(session) {
    const setBreakpointsPromises = $Rb(this.j.getBreakpoints(), (bp) => bp.originalUri.toString()).map((bp) => this.sendBreakpoints(bp.originalUri, false, session));
    if (session?.capabilities.supportsConfigurationDoneRequest) {
      await Promise.all([
        ...setBreakpointsPromises,
        this.rb(session),
        this.sb(session),
        this.tb(session),
        this.ub(session)
      ]);
    } else {
      await Promise.all(setBreakpointsPromises);
      await this.rb(session);
      await this.sb(session);
      await this.tb(session);
      await this.ub(session);
    }
  }
  /**
   * Removes the condition of triggered breakpoints that depended on
   * breakpoints in `removedBreakpoints`. Returns the URIs of resources that
   * had their breakpoints changed in this way.
   */
  pb(allBreakpoints, removedBreakpoints) {
    const affectedUris = [];
    for (const removed of removedBreakpoints) {
      for (const existing of allBreakpoints) {
        if (!removedBreakpoints.includes(existing) && existing.triggeredBy === removed.getId()) {
          this.j.updateBreakpoints(/* @__PURE__ */ new Map([[existing.getId(), { triggeredBy: void 0 }]]));
          affectedUris.push(existing.originalUri);
        }
      }
    }
    return affectedUris;
  }
  async qb(enable, breakpoint) {
    if (enable) {
      if (breakpoint.triggeredBy) {
        const trigger = this.j.getBreakpoints().find((bp) => breakpoint.triggeredBy === bp.getId());
        if (trigger && !trigger.enabled) {
          await this.enableOrDisableBreakpoints(enable, trigger);
        }
      }
    }
    await Promise.all(this.j.getBreakpoints().filter((bp) => bp.triggeredBy === breakpoint.getId() && bp.enabled !== enable).map((bp) => this.enableOrDisableBreakpoints(enable, bp)));
  }
  async sendBreakpoints(modelUri, sourceModified = false, session) {
    const breakpointsToSend = this.j.getBreakpoints({ originalUri: modelUri, enabledOnly: true });
    await sendToOneOrAllSessions(this.j, session, async (s) => {
      if (!s.configuration.noDebug) {
        const sessionBps = breakpointsToSend.filter((bp) => !bp.triggeredBy || bp.getSessionDidTrigger(s.getId()));
        await s.sendBreakpoints(modelUri, sessionBps, sourceModified);
      }
    });
  }
  async rb(session) {
    const breakpointsToSend = this.j.getFunctionBreakpoints().filter((fbp) => fbp.enabled && this.j.areBreakpointsActivated());
    await sendToOneOrAllSessions(this.j, session, async (s) => {
      if (s.capabilities.supportsFunctionBreakpoints && !s.configuration.noDebug) {
        await s.sendFunctionBreakpoints(breakpointsToSend);
      }
    });
  }
  async sb(session) {
    const breakpointsToSend = this.j.getDataBreakpoints().filter((fbp) => fbp.enabled && this.j.areBreakpointsActivated());
    await sendToOneOrAllSessions(this.j, session, async (s) => {
      if (s.capabilities.supportsDataBreakpoints && !s.configuration.noDebug) {
        await s.sendDataBreakpoints(breakpointsToSend);
      }
    });
  }
  async tb(session) {
    const breakpointsToSend = this.j.getInstructionBreakpoints().filter((fbp) => fbp.enabled && this.j.areBreakpointsActivated());
    await sendToOneOrAllSessions(this.j, session, async (s) => {
      if (s.capabilities.supportsInstructionBreakpoints && !s.configuration.noDebug) {
        await s.sendInstructionBreakpoints(breakpointsToSend);
      }
    });
  }
  ub(session) {
    return sendToOneOrAllSessions(this.j, session, async (s) => {
      const enabledExceptionBps = this.j.getExceptionBreakpointsForSession(s.getId()).filter((exb) => exb.enabled);
      if (s.capabilities.supportsConfigurationDoneRequest && (!s.capabilities.exceptionBreakpointFilters || s.capabilities.exceptionBreakpointFilters.length === 0)) {
        return;
      }
      if (!s.configuration.noDebug) {
        await s.sendExceptionBreakpoints(enabledExceptionBps);
      }
    });
  }
  vb(fileChangesEvent) {
    const toRemove = this.j.getBreakpoints().filter((bp) => fileChangesEvent.contains(
      bp.originalUri,
      2
      /* FileChangeType.DELETED */
    ));
    if (toRemove.length) {
      this.j.removeBreakpoints(toRemove);
    }
    const toSend = [];
    for (const uri of this.B) {
      if (fileChangesEvent.contains(
        uri,
        0
        /* FileChangeType.UPDATED */
      )) {
        toSend.push(uri);
      }
    }
    for (const uri of toSend) {
      this.B.delete(uri);
      this.sendBreakpoints(uri, true);
    }
  }
  async runTo(uri, lineNumber, column) {
    let breakpointToRemove;
    let threadToContinue = this.getViewModel().focusedThread;
    const addTempBreakPoint = async () => {
      const bpExists = !!this.getModel().getBreakpoints({ column, lineNumber, uri }).length;
      if (!bpExists) {
        const addResult = await this.wb(uri, lineNumber, column);
        if (addResult.thread) {
          threadToContinue = addResult.thread;
        }
        if (addResult.breakpoint) {
          breakpointToRemove = addResult.breakpoint;
        }
      }
      return { threadToContinue, breakpointToRemove };
    };
    const removeTempBreakPoint = (state) => {
      if (state === 2 || state === 0) {
        if (breakpointToRemove) {
          this.removeBreakpoints(breakpointToRemove.getId());
        }
        return true;
      }
      return false;
    };
    await addTempBreakPoint();
    if (this.state === 0) {
      const { launch, name, getConfig } = this.getConfigurationManager().selectedConfiguration;
      const config = await getConfig();
      const configOrName = config ? Object.assign($Lv(config), {}) : name;
      const listener = this.onDidChangeState((state) => {
        if (removeTempBreakPoint(state)) {
          listener.dispose();
        }
      });
      await this.startDebugging(launch, configOrName, void 0, true);
    }
    if (this.state === 2) {
      const focusedSession = this.getViewModel().focusedSession;
      if (!focusedSession || !threadToContinue) {
        return;
      }
      const listener = threadToContinue.session.onDidChangeState(() => {
        if (removeTempBreakPoint(focusedSession.state)) {
          listener.dispose();
        }
      });
      await threadToContinue.continue();
    }
  }
  async wb(uri, lineNumber, column) {
    const debugModel = this.getModel();
    const viewModel = this.getViewModel();
    const breakpoints = await this.addBreakpoints(uri, [{ lineNumber, column }], false);
    const breakpoint = breakpoints?.[0];
    if (!breakpoint) {
      return { breakpoint: void 0, thread: viewModel.focusedThread };
    }
    if (!breakpoint.verified) {
      let listener;
      await $Lh(new Promise((resolve) => {
        listener = debugModel.onDidChangeBreakpoints(() => {
          if (breakpoint.verified) {
            resolve();
          }
        });
      }), 2e3);
      listener.dispose();
    }
    let Score;
    (function(Score2) {
      Score2[Score2["Focused"] = 0] = "Focused";
      Score2[Score2["Verified"] = 1] = "Verified";
      Score2[Score2["VerifiedAndPausedInFile"] = 2] = "VerifiedAndPausedInFile";
      Score2[Score2["VerifiedAndFocused"] = 3] = "VerifiedAndFocused";
    })(Score || (Score = {}));
    let bestThread = viewModel.focusedThread;
    let bestScore = 0;
    for (const sessionId of breakpoint.sessionsThatVerified) {
      const session = debugModel.getSession(sessionId);
      if (!session) {
        continue;
      }
      const threads = session.getAllThreads().filter((t) => t.stopped);
      if (bestScore < 3) {
        if (viewModel.focusedThread && threads.includes(viewModel.focusedThread)) {
          bestThread = viewModel.focusedThread;
          bestScore = 3;
        }
      }
      if (bestScore < 2) {
        const pausedInThisFile = threads.find((t) => {
          const top2 = t.getTopStackFrame();
          return top2 && this.bb.extUri.isEqual(top2.source.uri, uri);
        });
        if (pausedInThisFile) {
          bestThread = pausedInThisFile;
          bestScore = 2;
        }
      }
      if (bestScore < 1) {
        bestThread = threads[0];
        bestScore = 2;
      }
    }
    return { thread: bestThread, breakpoint };
  }
};
$rbc = __decorate([
  __param(0, $mJ),
  __param(1, $uqb),
  __param(2, $uob),
  __param(3, $$M),
  __param(4, $PJ),
  __param(5, $Yv),
  __param(6, $Vlb),
  __param(7, $Zk),
  __param(8, $on),
  __param(9, $KL),
  __param(10, $Pk),
  __param(11, $wN),
  __param(12, $km),
  __param(13, $kl),
  __param(14, $Ax),
  __param(15, $vqb),
  __param(16, $sn),
  __param(17, $1M),
  __param(18, $5M),
  __param(19, $vl),
  __param(20, $nTb)
], $rbc);
function $sbc(model, stackFrame, thread, session, avoidSession) {
  if (!session) {
    if (stackFrame || thread) {
      session = stackFrame ? stackFrame.thread.session : thread.session;
    } else {
      const sessions = model.getSessions();
      const stoppedSession = sessions.find(
        (s) => s.state === 2
        /* State.Stopped */
      );
      session = stoppedSession || sessions.find((s) => s !== avoidSession && s !== avoidSession?.parentSession) || (sessions.length ? sessions[0] : void 0);
    }
  }
  if (!thread) {
    if (stackFrame) {
      thread = stackFrame.thread;
    } else {
      const threads = session ? session.getAllThreads() : void 0;
      const stoppedThread = threads && threads.find((t) => t.stopped);
      thread = stoppedThread || (threads && threads.length ? threads[0] : void 0);
    }
  }
  if (!stackFrame && thread) {
    stackFrame = thread.getTopStackFrame();
  }
  return { session, thread, stackFrame };
}
async function sendToOneOrAllSessions(model, session, send) {
  if (session) {
    await send(session);
  } else {
    await Promise.all(model.getSessions().map((s) => send(s)));
  }
}

// out-build/vs/workbench/contrib/debug/browser/debugStatus.js
var $tbc = class $tbc2 {
  constructor(d, f, configurationService) {
    this.d = d;
    this.f = f;
    this.b = [];
    const addStatusBarEntry = () => {
      this.c = this.d.addEntry(
        this.g,
        "status.debug",
        0,
        30
        /* Low Priority */
      );
    };
    const setShowInStatusBar = () => {
      this.a = configurationService.getValue("debug").showInStatusBar;
      if (this.a === "always" && !this.c) {
        addStatusBarEntry();
      }
    };
    setShowInStatusBar();
    this.b.push(this.f.onDidChangeState((state) => {
      if (state !== 0 && this.a === "onFirstSessionStart" && !this.c) {
        addStatusBarEntry();
      }
    }));
    this.b.push(configurationService.onDidChangeConfiguration((e) => {
      if (e.affectsConfiguration("debug.showInStatusBar")) {
        setShowInStatusBar();
        if (this.c && this.a === "never") {
          this.c.dispose();
          this.c = void 0;
        }
      }
    }));
    this.b.push(this.f.getConfigurationManager().onDidSelectConfiguration((e) => {
      this.c?.update(this.g);
    }));
  }
  get g() {
    let text2 = "";
    const manager = this.f.getConfigurationManager();
    const name = manager.selectedConfiguration.name || "";
    const nameAndLaunchPresent = name && manager.selectedConfiguration.launch;
    if (nameAndLaunchPresent) {
      text2 = manager.getLaunches().length > 1 ? `${name} (${manager.selectedConfiguration.launch.name})` : name;
    }
    return {
      name: localize(5970, null),
      text: "$(debug-alt-small) " + text2,
      ariaLabel: localize(5971, null, text2),
      tooltip: localize(5972, null),
      command: "workbench.action.debug.selectandstart"
    };
  }
  dispose() {
    this.c?.dispose();
    $Xc(this.b);
  }
};
$tbc = __decorate([
  __param(0, $$qb),
  __param(1, $0R),
  __param(2, $kl)
], $tbc);

// out-build/vs/workbench/contrib/debug/browser/debugTitle.js
var $ubc = class $ubc2 {
  constructor(debugService, hostService, titleService) {
    this.a = [];
    const updateTitle = () => {
      if (debugService.state === 2 && !hostService.hasFocus) {
        titleService.updateProperties({ prefix: "\u{1F534}" });
      } else {
        titleService.updateProperties({ prefix: "" });
      }
    };
    this.a.push(debugService.onDidChangeState(updateTitle));
    this.a.push(hostService.onDidChangeFocus(updateTitle));
  }
  dispose() {
    $Xc(this.a);
  }
};
$ubc = __decorate([
  __param(0, $0R),
  __param(1, $S4),
  __param(2, $RTb)
], $ubc);

// out-build/vs/workbench/contrib/debug/browser/welcomeView.js
var debugStartLanguageKey = "debugStartLanguage";
var CONTEXT_DEBUG_START_LANGUAGE = new $nn(debugStartLanguageKey, void 0);
var CONTEXT_DEBUGGER_INTERESTED_IN_ACTIVE_EDITOR = new $nn("debuggerInterestedInActiveEditor", false);
var $vbc = class $vbc2 extends $_ob {
  static {
    this.ID = "workbench.debug.welcome";
  }
  static {
    this.LABEL = localize2(6101, "Run");
  }
  constructor(options3, themeService, keybindingService, contextMenuService, configurationService, contextKeyService, c, f, instantiationService, viewDescriptorService, openerService, storageSevice, telemetryService, hoverService) {
    super(options3, keybindingService, contextMenuService, configurationService, contextKeyService, viewDescriptorService, instantiationService, openerService, themeService, telemetryService, hoverService);
    this.c = c;
    this.f = f;
    this.a = CONTEXT_DEBUG_START_LANGUAGE.bindTo(contextKeyService);
    this.b = CONTEXT_DEBUGGER_INTERESTED_IN_ACTIVE_EDITOR.bindTo(contextKeyService);
    const lastSetLanguage = storageSevice.get(
      debugStartLanguageKey,
      1
      /* StorageScope.WORKSPACE */
    );
    this.a.set(lastSetLanguage);
    const setContextKey = () => {
      let editorControl = this.f.activeTextEditorControl;
      if ($Q5(editorControl)) {
        editorControl = editorControl.getModifiedEditor();
      }
      if ($P5(editorControl)) {
        const model = editorControl.getModel();
        const language = model ? model.getLanguageId() : void 0;
        if (language && this.c.getAdapterManager().someDebuggerInterestedInLanguage(language)) {
          this.a.set(language);
          this.b.set(true);
          storageSevice.store(
            debugStartLanguageKey,
            language,
            1,
            1
            /* StorageTarget.MACHINE */
          );
          return;
        }
      }
      this.b.set(false);
    };
    const disposables = new $2c();
    this.B(disposables);
    this.B(f.onDidActiveEditorChange(() => {
      disposables.clear();
      let editorControl = this.f.activeTextEditorControl;
      if ($Q5(editorControl)) {
        editorControl = editorControl.getModifiedEditor();
      }
      if ($P5(editorControl)) {
        disposables.add(editorControl.onDidChangeModelLanguage(setContextKey));
      }
      setContextKey();
    }));
    this.B(this.c.getAdapterManager().onDidRegisterDebugger(setContextKey));
    this.B(this.onDidChangeBodyVisibility((visible) => {
      if (visible) {
        setContextKey();
      }
    }));
    setContextKey();
    const debugKeybinding = this.yb.lookupKeybinding($W4b);
    debugKeybindingLabel = debugKeybinding ? ` (${debugKeybinding.getLabel()})` : "";
  }
  shouldShowWelcome() {
    return true;
  }
};
$vbc = __decorate([
  __param(1, $gs),
  __param(2, $Ty),
  __param(3, $50),
  __param(4, $kl),
  __param(5, $on),
  __param(6, $0R),
  __param(7, $mJ),
  __param(8, $Pk),
  __param(9, $$M),
  __param(10, $O4),
  __param(11, $jv),
  __param(12, $zv),
  __param(13, $5$)
], $vbc);
var viewsRegistry5 = $Wn.as(Extensions5.ViewsRegistry);
viewsRegistry5.registerViewWelcomeContent($vbc.ID, {
  content: localize(6096, null, $m && !$r ? $1yb.ID : $Xyb.ID),
  when: $7m.and($BR, CONTEXT_DEBUGGER_INTERESTED_IN_ACTIVE_EDITOR.toNegated()),
  group: ViewContentGroups.Open
});
var debugKeybindingLabel = "";
viewsRegistry5.registerViewWelcomeContent($vbc.ID, {
  content: `[${localize(6097, null)}${debugKeybindingLabel}](command:${$W4b})`,
  when: $BR,
  group: ViewContentGroups.Debug,
  // Allow inserting more buttons directly after this one (by setting order to 1).
  order: 1
});
viewsRegistry5.registerViewWelcomeContent($vbc.ID, {
  content: localize(6098, null, `${$V4b}?${encodeURIComponent(JSON.stringify([{ addNew: true }]))}`),
  when: $7m.and($BR, $epb.notEqualsTo("empty")),
  group: ViewContentGroups.Debug
});
viewsRegistry5.registerViewWelcomeContent($vbc.ID, {
  content: localize(6099, null, $m && !$r ? $1yb.ID : $Yyb.ID),
  when: $7m.and($BR, $epb.isEqualTo("empty")),
  group: ViewContentGroups.Debug
});
viewsRegistry5.registerViewWelcomeContent($vbc.ID, {
  content: localize(6100, null),
  when: $CR.toNegated(),
  group: ViewContentGroups.Debug
});

// out-build/vs/workbench/contrib/debug/browser/debugViewlet.js
var $wbc = class $wbc2 extends $oqb {
  constructor(layoutService, telemetryService, Bb, Cb, instantiationService, contextService, storageService, themeService, contextMenuService, extensionService, configurationService, Db, Eb, viewDescriptorService) {
    super($TQ, { mergeViewWithContainerWhenSingleView: true }, instantiationService, configurationService, layoutService, contextMenuService, telemetryService, extensionService, themeService, storageService, contextService, viewDescriptorService);
    this.Bb = Bb;
    this.Cb = Cb;
    this.Db = Db;
    this.Eb = Eb;
    this.$ = /* @__PURE__ */ new Map();
    this.Ab = this.B(new $2c());
    this.B(this.Cb.onDidChangeState((state) => this.Fb(state)));
    this.B(this.Eb.onDidChangeContext((e) => {
      if (e.affectsSome(/* @__PURE__ */ new Set([$6Q, "inDebugMode"]))) {
        this.mb();
      }
    }));
    this.B(this.ib.onDidChangeWorkbenchState(() => this.mb()));
    this.B(this.cb.onDidChangeConfiguration((e) => {
      if (e.affectsConfiguration("debug.toolBarLocation") || e.affectsConfiguration("debug.hideLauncherWhileDebugging")) {
        this.mb();
      }
    }));
  }
  create(parent) {
    super.create(parent);
    parent.classList.add("debug-viewlet");
  }
  focus() {
    super.focus();
    if (this.c) {
      this.c.focus();
    } else {
      this.focusView($vbc.ID);
    }
  }
  getActionViewItem(action, options3) {
    if (action.id === $W4b) {
      this.c = this.bb.createInstance($c9b, null, action, options3);
      return this.c;
    }
    if (action.id === $R4b) {
      return new $d9b(action, void 0, this.Cb, this.Db, this.cb);
    }
    if (action.id === $M4b || action.id === $K4b) {
      this.Ab.clear();
      const item = this.bb.invokeFunction((accessor) => $Lac(action, this.Ab, accessor, { hoverDelegate: options3.hoverDelegate }));
      if (item) {
        return item;
      }
    }
    return $X$(this.bb, action, options3);
  }
  focusView(id2) {
    const view = this.getView(id2);
    if (view) {
      view.focus();
    }
  }
  Fb(state) {
    if (this.r) {
      this.r();
      this.r = void 0;
    }
    if (state === 1) {
      this.Bb.withProgress({ location: $TQ }, (_progress) => {
        return new Promise((resolve) => this.r = resolve);
      });
    }
  }
  addPanes(panes) {
    super.addPanes(panes);
    for (const { pane } of panes) {
      if (pane.id === $YQ) {
        this.t = pane;
        this.Gb();
      } else {
        this.$.set(pane.id, pane.onDidChange(() => this.Gb()));
      }
    }
  }
  removePanes(panes) {
    super.removePanes(panes);
    for (const pane of panes) {
      $Xc(this.$.get(pane.id));
      this.$.delete(pane.id);
    }
  }
  Gb() {
    if (this.t) {
      const allOtherCollapsed = this.panes.every((view) => !view.isExpanded() || view === this.t);
      this.t.maximumBodySize = allOtherCollapsed ? Number.POSITIVE_INFINITY : this.t.minimumBodySize;
    }
  }
};
$wbc = __decorate([
  __param(0, $Vlb),
  __param(1, $zv),
  __param(2, $TJ),
  __param(3, $0R),
  __param(4, $Pk),
  __param(5, $Zk),
  __param(6, $jv),
  __param(7, $gs),
  __param(8, $50),
  __param(9, $wN),
  __param(10, $kl),
  __param(11, $40),
  __param(12, $on),
  __param(13, $$M)
], $wbc);
$dJ.appendMenuItem($bJ.ViewContainerTitle, {
  when: $7m.and($7m.equals("viewContainer", $TQ), $7Q.notEqualsTo("simple"), $epb.notEqualsTo("empty"), $7m.or($5Q.isEqualTo("inactive"), $7m.notEquals("config.debug.toolBarLocation", "docked")), $7m.or($7m.not("config.debug.hideLauncherWhileDebugging"), $7m.not("inDebugMode"))),
  order: 10,
  group: "navigation",
  command: {
    precondition: $5Q.notEqualsTo($7R(
      1
      /* State.Initializing */
    )),
    id: $W4b,
    title: $n5b
  }
});
$hJ(class extends $gJ {
  constructor() {
    super({
      id: $V4b,
      title: {
        value: $m5b,
        original: "Open 'launch.json'",
        mnemonicTitle: localize(5993, null)
      },
      metadata: {
        description: localize2(5997, "Opens the file used to configure how your program is debugged")
      },
      f1: true,
      icon: $1Fb,
      precondition: $7Q.notEqualsTo("simple"),
      menu: [{
        id: $bJ.ViewContainerTitle,
        group: "navigation",
        order: 20,
        when: $7m.and($7m.equals("viewContainer", $TQ), $7Q.notEqualsTo("simple"), $epb.notEqualsTo("empty"), $7m.or($5Q.isEqualTo("inactive"), $7m.notEquals("config.debug.toolBarLocation", "docked")))
      }, {
        id: $bJ.ViewContainerTitle,
        order: 20,
        // Show in debug viewlet secondary actions when debugging and debug toolbar is docked
        when: $7m.and($7m.equals("viewContainer", $TQ), $5Q.notEqualsTo("inactive"), $7m.equals("config.debug.toolBarLocation", "docked"))
      }, {
        id: $bJ.MenubarDebugMenu,
        group: "2_configuration",
        order: 1,
        when: $BR
      }]
    });
  }
  async run(accessor, opts) {
    const debugService = accessor.get($0R);
    const quickInputService = accessor.get($1M);
    const configurationManager = debugService.getConfigurationManager();
    let launch;
    if (configurationManager.selectedConfiguration.name) {
      launch = configurationManager.selectedConfiguration.launch;
    } else {
      const launches = configurationManager.getLaunches().filter((l) => !l.hidden);
      if (launches.length === 1) {
        launch = launches[0];
      } else {
        const picks = launches.map((l) => ({ label: l.name, launch: l }));
        const picked = await quickInputService.pick(picks, {
          activeItem: picks[0],
          placeHolder: localize(5994, null)
        });
        if (picked) {
          launch = picked.launch;
        }
      }
    }
    if (launch) {
      const { editor } = await launch.openConfigFile({ preserveFocus: false });
      if (editor && opts?.addNew) {
        const codeEditor = editor.getControl();
        if (codeEditor) {
          await codeEditor.getContribution($3R)?.addLaunchConfiguration();
        }
      }
    }
  }
});
$hJ(class extends $gJ {
  constructor() {
    super({
      id: "debug.toggleReplIgnoreFocus",
      title: localize(5995, null),
      toggled: $7m.has(`view.${$2Q}.visible`),
      menu: [{
        id: $nqb,
        group: "3_toggleRepl",
        order: 30,
        when: $7m.and($7m.equals("viewContainer", $TQ))
      }]
    });
  }
  async run(accessor) {
    const viewsService = accessor.get($uob);
    if (viewsService.isViewVisible($2Q)) {
      viewsService.closeView($2Q);
    } else {
      await viewsService.openView($2Q);
    }
  }
});
$dJ.appendMenuItem($bJ.ViewContainerTitle, {
  when: $7m.and($7m.equals("viewContainer", $TQ), $5Q.notEqualsTo("inactive"), $7m.or($7m.equals("config.debug.toolBarLocation", "docked"), $7m.has("config.debug.hideLauncherWhileDebugging"))),
  order: 10,
  command: {
    id: $S4b,
    title: localize(5996, null)
  }
});

// out-build/vs/workbench/contrib/debug/common/debugContentProvider.js
var $xbc_1;
var $xbc = class $xbc2 {
  static {
    $xbc_1 = this;
  }
  constructor(textModelResolverService, c, d, e, f) {
    this.c = c;
    this.d = d;
    this.e = e;
    this.f = f;
    this.b = /* @__PURE__ */ new Map();
    textModelResolverService.registerTextModelContentProvider($5R, this);
    $xbc_1.a = this;
  }
  dispose() {
    this.b.forEach((cancellationSource) => cancellationSource.dispose());
  }
  provideTextContent(resource) {
    return this.g(resource, true);
  }
  /**
   * Reload the model content of the given resource.
   * If there is no model for the given resource, this method does nothing.
   */
  static refreshDebugContent(resource) {
    $xbc_1.a?.g(resource, false);
  }
  /**
   * Create or reload the model content of the given resource.
   */
  g(resource, createIfNotExists) {
    const model = this.d.getModel(resource);
    if (!model && !createIfNotExists) {
      return null;
    }
    let session;
    if (resource.query) {
      const data = $BP.getEncodedDebugData(resource);
      session = this.c.getModel().getSession(data.sessionId);
    }
    if (!session) {
      session = this.c.getViewModel().focusedSession;
    }
    if (!session) {
      return Promise.reject(new $ub(localize(6167, null)));
    }
    const createErrModel = (errMsg) => {
      this.c.sourceIsNotAvailable(resource);
      const languageSelection = this.e.createById($KF);
      const message = errMsg ? localize(6168, null, resource.path, errMsg) : localize(6169, null, resource.path);
      return this.d.createModel(message, languageSelection, resource);
    };
    return session.loadSource(resource).then((response) => {
      if (response && response.body) {
        if (model) {
          const newContent = response.body.content;
          const cancellationSource = this.b.get(model.id);
          cancellationSource?.cancel();
          const myToken = new $ad();
          this.b.set(model.id, myToken);
          return this.f.computeMoreMinimalEdits(model.uri, [{ text: newContent, range: model.getFullModelRange() }]).then((edits) => {
            this.b.delete(model.id);
            if (!myToken.token.isCancellationRequested && edits && edits.length > 0) {
              model.applyEdits(edits.map((edit3) => $bD.replace($9C.lift(edit3.range), edit3.text)));
            }
            return model;
          });
        } else {
          const mime = response.body.mimeType || $Nsb(resource)[0];
          const languageSelection = this.e.createByMimeType(mime);
          return this.d.createModel(response.body.content, languageSelection, resource);
        }
      }
      return createErrModel();
    }, (err) => createErrModel(err.message));
  }
};
$xbc = $xbc_1 = __decorate([
  __param(0, $oG),
  __param(1, $0R),
  __param(2, $sG),
  __param(3, $1E),
  __param(4, $I0)
], $xbc);

// out-build/vs/workbench/contrib/debug/browser/loadedScriptsView.js
var NEW_STYLE_COMPRESS = true;
var URI_SCHEMA_PATTERN = /^[a-zA-Z][a-zA-Z0-9\+\-\.]+:/;
var BaseTreeItem = class _BaseTreeItem {
  constructor(h3, j, isIncompressible = false) {
    this.h = h3;
    this.j = j;
    this.isIncompressible = isIncompressible;
    this.d = /* @__PURE__ */ new Map();
    this.c = false;
  }
  updateLabel(label3) {
    this.j = label3;
  }
  isLeaf() {
    return this.d.size === 0;
  }
  getSession() {
    if (this.h) {
      return this.h.getSession();
    }
    return void 0;
  }
  setSource(session, source) {
    this.g = source;
    this.d.clear();
    if (source.raw && source.raw.sources) {
      for (const src of source.raw.sources) {
        if (src.name && src.path) {
          const s = new _BaseTreeItem(this, src.name);
          this.d.set(src.path, s);
          const ss = session.getSource(src);
          s.setSource(session, ss);
        }
      }
    }
  }
  createIfNeeded(key2, factory) {
    let child = this.d.get(key2);
    if (!child) {
      child = factory(this, key2);
      this.d.set(key2, child);
    }
    return child;
  }
  getChild(key2) {
    return this.d.get(key2);
  }
  remove(key2) {
    this.d.delete(key2);
  }
  removeFromParent() {
    if (this.h) {
      this.h.remove(this.j);
      if (this.h.d.size === 0) {
        this.h.removeFromParent();
      }
    }
  }
  getTemplateId() {
    return "id";
  }
  // a dynamic ID based on the parent chain; required for reparenting (see #55448)
  getId() {
    const parent = this.getParent();
    return parent ? `${parent.getId()}/${this.getInternalId()}` : this.getInternalId();
  }
  getInternalId() {
    return this.j;
  }
  // skips intermediate single-child nodes
  getParent() {
    if (this.h) {
      if (this.h.isSkipped()) {
        return this.h.getParent();
      }
      return this.h;
    }
    return void 0;
  }
  isSkipped() {
    if (this.h) {
      if (this.h.m()) {
        return true;
      }
      return false;
    }
    return true;
  }
  // skips intermediate single-child nodes
  hasChildren() {
    const child = this.m();
    if (child) {
      return child.hasChildren();
    }
    return this.d.size > 0;
  }
  // skips intermediate single-child nodes
  getChildren() {
    const child = this.m();
    if (child) {
      return child.getChildren();
    }
    const array2 = [];
    for (const child2 of this.d.values()) {
      array2.push(child2);
    }
    return array2.sort((a, b) => this.k(a, b));
  }
  // skips intermediate single-child nodes
  getLabel(separateRootFolder = true) {
    const child = this.m();
    if (child) {
      const sep2 = this instanceof RootFolderTreeItem && separateRootFolder ? " \u2022 " : $kc.sep;
      return `${this.j}${sep2}${child.getLabel()}`;
    }
    return this.j;
  }
  // skips intermediate single-child nodes
  getHoverLabel() {
    if (this.g && this.h && this.h.g) {
      return this.g.raw.path || this.g.raw.name;
    }
    const label3 = this.getLabel(false);
    const parent = this.getParent();
    if (parent) {
      const hover = parent.getHoverLabel();
      if (hover) {
        return `${hover}/${label3}`;
      }
    }
    return label3;
  }
  // skips intermediate single-child nodes
  getSource() {
    const child = this.m();
    if (child) {
      return child.getSource();
    }
    return this.g;
  }
  k(a, b) {
    if (a.j && b.j) {
      return a.j.localeCompare(b.j);
    }
    return 0;
  }
  m() {
    if (!this.g && !this.c && this.n()) {
      if (this.d.size === 1) {
        return this.d.values().next().value;
      }
      if (this.d.size > 1) {
        this.c = true;
      }
    }
    return void 0;
  }
  n() {
    if (NEW_STYLE_COMPRESS) {
      return this instanceof RootTreeItem;
    } else {
      return !(this instanceof RootFolderTreeItem) && !(this instanceof SessionTreeItem);
    }
  }
};
var RootFolderTreeItem = class extends BaseTreeItem {
  constructor(parent, folder) {
    super(parent, folder.name, true);
    this.folder = folder;
  }
};
var RootTreeItem = class extends BaseTreeItem {
  constructor(o, p, q) {
    super(void 0, "Root");
    this.o = o;
    this.p = p;
    this.q = q;
  }
  add(session) {
    return this.createIfNeeded(session.getId(), () => new SessionTreeItem(this.q, this, session, this.o, this.p));
  }
  find(session) {
    return this.getChild(session.getId());
  }
};
var SessionTreeItem = class _SessionTreeItem extends BaseTreeItem {
  static {
    this.o = /^(https?:\/\/[^/]+)(\/.*)$/;
  }
  constructor(labelService, parent, session, t, u) {
    super(parent, session.getLabel(), true);
    this.t = t;
    this.u = u;
    this.q = /* @__PURE__ */ new Map();
    this.r = labelService;
    this.p = session;
  }
  getInternalId() {
    return this.p.getId();
  }
  getSession() {
    return this.p;
  }
  getHoverLabel() {
    return void 0;
  }
  hasChildren() {
    return true;
  }
  k(a, b) {
    const acat = this.w(a);
    const bcat = this.w(b);
    if (acat !== bcat) {
      return acat - bcat;
    }
    return super.k(a, b);
  }
  w(item) {
    if (item instanceof RootFolderTreeItem) {
      return item.folder.index;
    }
    const l = item.getLabel();
    if (l && /^<.+>$/.test(l)) {
      return 1e3;
    }
    return 999;
  }
  async addPath(source) {
    let folder;
    let url;
    let path = source.raw.path;
    if (!path) {
      return;
    }
    if (this.r && URI_SCHEMA_PATTERN.test(path)) {
      path = this.r.getUriLabel(URI.parse(path));
    }
    const match = _SessionTreeItem.o.exec(path);
    if (match && match.length === 3) {
      url = match[1];
      path = decodeURI(match[2]);
    } else {
      if ($mc(path)) {
        const resource = URI.file(path);
        folder = this.u ? this.u.getWorkspaceFolder(resource) : null;
        if (folder) {
          path = $lc($Ff(resource.path.substring(folder.uri.path.length), $kc.sep));
          const hasMultipleRoots = this.u.getWorkspace().folders.length > 1;
          if (hasMultipleRoots) {
            path = $kc.sep + path;
          } else {
            folder = null;
          }
        } else {
          path = $lc(path);
          if ($l) {
            path = $1t(path);
          } else {
            path = $2t(path, (await this.t.userHome()).fsPath);
          }
        }
      }
    }
    let leaf = this;
    path.split(/[\/\\]/).forEach((segment, i2) => {
      if (i2 === 0 && folder) {
        const f = folder;
        leaf = leaf.createIfNeeded(folder.name, (parent) => new RootFolderTreeItem(parent, f));
      } else if (i2 === 0 && url) {
        leaf = leaf.createIfNeeded(url, (parent) => new BaseTreeItem(parent, url));
      } else {
        leaf = leaf.createIfNeeded(segment, (parent) => new BaseTreeItem(parent, segment));
      }
    });
    leaf.setSource(this.p, source);
    if (source.raw.path) {
      this.q.set(source.raw.path, leaf);
    }
  }
  removePath(source) {
    if (source.raw.path) {
      const leaf = this.q.get(source.raw.path);
      if (leaf) {
        leaf.removeFromParent();
        return true;
      }
    }
    return false;
  }
};
function asTreeElement(item, viewState) {
  const children = item.getChildren();
  const collapsed2 = viewState ? !viewState.expanded.has(item.getId()) : !(item instanceof SessionTreeItem);
  return {
    element: item,
    collapsed: collapsed2,
    collapsible: item.hasChildren(),
    children: children.map((i2) => asTreeElement(i2, viewState))
  };
}
var $ybc = class $ybc2 extends $_ob {
  constructor(options3, contextMenuService, keybindingService, instantiationService, viewDescriptorService, configurationService, t, contextKeyService, L, ab, sb, ac, openerService, themeService, telemetryService, hoverService) {
    super(options3, keybindingService, contextMenuService, configurationService, contextKeyService, viewDescriptorService, instantiationService, openerService, themeService, telemetryService, hoverService);
    this.t = t;
    this.L = L;
    this.ab = ab;
    this.sb = sb;
    this.ac = ac;
    this.n = false;
    this.g = $sR.bindTo(contextKeyService);
  }
  W(container2) {
    super.W(container2);
    this.element.classList.add("debug-pane");
    container2.classList.add("debug-loaded-scripts");
    container2.classList.add("show-file-icons");
    this.c = $q4b(container2);
    this.r = new LoadedScriptsFilter();
    const root = new RootTreeItem(this.ac, this.L, this.sb);
    this.j = this.Db.createInstance($lsb, { onDidChangeVisibility: this.onDidChangeBodyVisibility });
    this.B(this.j);
    this.h = this.Db.createInstance($2eb, "LoadedScriptsView", this.c, new LoadedScriptsDelegate(), [new LoadedScriptsRenderer(this.j)], {
      compressionEnabled: NEW_STYLE_COMPRESS,
      collapseByDefault: true,
      hideTwistiesOfChildlessElements: true,
      identityProvider: {
        getId: (element) => element.getId()
      },
      keyboardNavigationLabelProvider: {
        getKeyboardNavigationLabel: (element) => {
          return element.getLabel();
        },
        getCompressedNodeKeyboardNavigationLabel: (elements) => {
          return elements.map((e) => e.getLabel()).join("/");
        }
      },
      filter: this.r,
      accessibilityProvider: new LoadedSciptsAccessibilityProvider(),
      overrideStyles: this.Xb().listOverrideStyles
    });
    const updateView = (viewState2) => this.h.setChildren(null, asTreeElement(root, viewState2).children);
    updateView();
    this.m = new $8h(() => {
      this.n = false;
      if (this.h) {
        updateView();
      }
    }, 300);
    this.B(this.m);
    this.B(this.h.onDidOpen((e) => {
      if (e.element instanceof BaseTreeItem) {
        const source = e.element.getSource();
        if (source && source.available) {
          const nullRange = { startLineNumber: 0, startColumn: 0, endLineNumber: 0, endColumn: 0 };
          source.openInEditor(this.t, nullRange, e.editorOptions.preserveFocus, e.sideBySide, e.editorOptions.pinned);
        }
      }
    }));
    this.B(this.h.onDidChangeFocus(() => {
      const focus = this.h.getFocus();
      if (focus instanceof SessionTreeItem) {
        this.g.set("session");
      } else {
        this.g.reset();
      }
    }));
    const scheduleRefreshOnVisible = () => {
      if (this.isBodyVisible()) {
        this.m.schedule();
      } else {
        this.n = true;
      }
    };
    const addSourcePathsToSession = async (session) => {
      if (session.capabilities.supportsLoadedSourcesRequest) {
        const sessionNode = root.add(session);
        const paths = await session.getLoadedSources();
        for (const path of paths) {
          await sessionNode.addPath(path);
        }
        scheduleRefreshOnVisible();
      }
    };
    const registerSessionListeners = (session) => {
      this.B(session.onDidChangeName(async () => {
        const sessionRoot = root.find(session);
        if (sessionRoot) {
          sessionRoot.updateLabel(session.getLabel());
          scheduleRefreshOnVisible();
        }
      }));
      this.B(session.onDidLoadedSource(async (event) => {
        let sessionRoot;
        switch (event.reason) {
          case "new":
          case "changed":
            sessionRoot = root.add(session);
            await sessionRoot.addPath(event.source);
            scheduleRefreshOnVisible();
            if (event.reason === "changed") {
              $xbc.refreshDebugContent(event.source.uri);
            }
            break;
          case "removed":
            sessionRoot = root.find(session);
            if (sessionRoot && sessionRoot.removePath(event.source)) {
              scheduleRefreshOnVisible();
            }
            break;
          default:
            this.r.setFilter(event.source.name);
            this.h.refilter();
            break;
        }
      }));
    };
    this.B(this.ab.onDidNewSession(registerSessionListeners));
    this.ab.getModel().getSessions().forEach(registerSessionListeners);
    this.B(this.ab.onDidEndSession(({ session }) => {
      root.remove(session.getId());
      this.m.schedule();
    }));
    this.m.schedule(0);
    this.B(this.onDidChangeBodyVisibility((visible) => {
      if (visible && this.n) {
        this.m.schedule();
      }
    }));
    let viewState;
    this.B(this.h.onDidChangeFindPattern((pattern) => {
      if (this.h.findMode === TreeFindMode.Highlight) {
        return;
      }
      if (!viewState && pattern) {
        const expanded2 = /* @__PURE__ */ new Set();
        const visit = (node) => {
          if (node.element && !node.collapsed) {
            expanded2.add(node.element.getId());
          }
          for (const child of node.children) {
            visit(child);
          }
        };
        visit(this.h.getNode());
        viewState = { expanded: expanded2 };
        this.h.expandAll();
      } else if (!pattern && viewState) {
        this.h.setFocus([]);
        updateView(viewState);
        viewState = void 0;
      }
    }));
    this.ab.getModel().getSessions().forEach((session) => addSourcePathsToSession(session));
  }
  X(height, width2) {
    super.X(height, width2);
    this.h.layout(height, width2);
  }
  collapseAll() {
    this.h.collapseAll();
  }
  dispose() {
    $Xc(this.h);
    $Xc(this.j);
    super.dispose();
  }
};
$ybc = __decorate([
  __param(1, $50),
  __param(2, $Ty),
  __param(3, $Pk),
  __param(4, $$M),
  __param(5, $kl),
  __param(6, $mJ),
  __param(7, $on),
  __param(8, $Zk),
  __param(9, $0R),
  __param(10, $ZI),
  __param(11, $aT),
  __param(12, $O4),
  __param(13, $gs),
  __param(14, $zv),
  __param(15, $5$)
], $ybc);
var LoadedScriptsDelegate = class {
  getHeight(element) {
    return 22;
  }
  getTemplateId(element) {
    return LoadedScriptsRenderer.ID;
  }
};
var LoadedScriptsRenderer = class _LoadedScriptsRenderer {
  static {
    this.ID = "lsrenderer";
  }
  constructor(c) {
    this.c = c;
  }
  get templateId() {
    return _LoadedScriptsRenderer.ID;
  }
  renderTemplate(container2) {
    const label3 = this.c.create(container2, { supportHighlights: true });
    return { label: label3 };
  }
  renderElement(node, index, data) {
    const element = node.element;
    const label3 = element.getLabel();
    this.d(element, label3, data, node.filterData);
  }
  renderCompressedElements(node, index, data, height) {
    const element = node.element.elements[node.element.elements.length - 1];
    const labels2 = node.element.elements.map((e) => e.getLabel());
    this.d(element, labels2, data, node.filterData);
  }
  d(element, labels2, data, filterData) {
    const label3 = {
      name: labels2
    };
    const options3 = {
      title: element.getHoverLabel()
    };
    if (element instanceof RootFolderTreeItem) {
      options3.fileKind = FileKind.ROOT_FOLDER;
    } else if (element instanceof SessionTreeItem) {
      options3.title = localize(6016, null);
      options3.hideIcon = true;
    } else if (element instanceof BaseTreeItem) {
      const src = element.getSource();
      if (src && src.uri) {
        label3.resource = src.uri;
        options3.fileKind = FileKind.FILE;
      } else {
        options3.fileKind = FileKind.FOLDER;
      }
    }
    options3.matches = $Ul(filterData);
    data.label.setResource(label3, options3);
  }
  disposeTemplate(templateData) {
    templateData.label.dispose();
  }
};
var LoadedSciptsAccessibilityProvider = class {
  getWidgetAriaLabel() {
    return localize(6017, null);
  }
  getAriaLabel(element) {
    if (element instanceof RootFolderTreeItem) {
      return localize(6018, null, element.getLabel());
    }
    if (element instanceof SessionTreeItem) {
      return localize(6019, null, element.getLabel());
    }
    if (element.hasChildren()) {
      return localize(6020, null, element.getLabel());
    } else {
      return localize(6021, null, element.getLabel());
    }
  }
};
var LoadedScriptsFilter = class {
  setFilter(filterText) {
    this.c = filterText;
  }
  filter(element, parentVisibility) {
    if (!this.c) {
      return 1;
    }
    if (element.isLeaf()) {
      const name = element.getLabel();
      if (name.indexOf(this.c) >= 0) {
        return 1;
      }
      return 0;
    }
    return 2;
  }
};
$hJ(class Collapse2 extends $cpb {
  constructor() {
    super({
      id: "loadedScripts.collapse",
      viewId: $XQ,
      title: localize(6022, null),
      f1: false,
      icon: $6l.collapseAll,
      menu: {
        id: $bJ.ViewTitle,
        order: 30,
        group: "navigation",
        when: $7m.equals("view", $XQ)
      }
    });
  }
  runInView(_accessor, view) {
    view.collapseAll();
  }
});

// out-build/vs/workbench/contrib/debug/browser/statusbarColorProvider.js
var $zbc = $5n("statusBar.debuggingBackground", {
  dark: "#CC6633",
  light: "#CC6633",
  hcDark: "#BA592C",
  hcLight: "#B5200D"
}, localize(6074, null));
var $Abc = $5n("statusBar.debuggingForeground", {
  dark: $2mb,
  light: $2mb,
  hcDark: $2mb,
  hcLight: "#FFFFFF"
}, localize(6075, null));
var $Bbc = $5n("statusBar.debuggingBorder", $6mb, localize(6076, null));
var $Cbc = $5n("commandCenter.debuggingBackground", $0n($zbc, 0.258), localize(6077, null), true);
var $Dbc = class $Dbc2 {
  set c(enabled) {
    if (enabled === !!this.b) {
      return;
    }
    if (enabled) {
      this.b = this.g.overrideStyle({
        priority: 10,
        foreground: $Abc,
        background: $zbc,
        border: $Bbc
      });
    } else {
      this.b.dispose();
      this.b = void 0;
    }
  }
  constructor(d, f, g, h3, i2) {
    this.d = d;
    this.f = f;
    this.g = g;
    this.h = h3;
    this.i = i2;
    this.a = new $2c();
    this.d.onDidChangeState(this.j, this, this.a);
    this.f.onDidChangeWorkbenchState(this.j, this, this.a);
    this.i.onDidChangeConfiguration((e) => {
      if (e.affectsConfiguration("debug.enableStatusBarColor") || e.affectsConfiguration("debug.toolBarLocation")) {
        this.j();
      }
    }, void 0, this.a);
    this.j();
  }
  j() {
    const debugConfig = this.i.getValue("debug");
    const isInDebugMode = $Ebc(this.d.state, this.d.getModel().getSessions());
    if (!debugConfig.enableStatusBarColor) {
      this.c = false;
    } else {
      this.c = isInDebugMode;
    }
    const isInCommandCenter = debugConfig.toolBarLocation === "commandCenter";
    this.h.mainContainer.style.setProperty($Yn($cob), isInCommandCenter && isInDebugMode ? $Zn($Cbc) : "");
  }
  dispose() {
    this.b?.dispose();
    this.a.dispose();
  }
};
$Dbc = __decorate([
  __param(0, $0R),
  __param(1, $Zk),
  __param(2, $$qb),
  __param(3, $Ulb),
  __param(4, $kl)
], $Dbc);
function $Ebc(state, sessions) {
  if (state === 0 || state === 1 || sessions.every((s) => s.suppressDebugStatusbar || s.configuration?.noDebug)) {
    return false;
  }
  return true;
}

// out-build/vs/workbench/contrib/debug/browser/watchExpressionsView.js
var $Gbc_1;
var MAX_VALUE_RENDER_LENGTH_IN_VIEWLET3 = 1024;
var ignoreViewUpdates = false;
var useCachedEvaluation = false;
var $Fbc = class $Fbc2 extends $_ob {
  constructor(options3, contextMenuService, n, keybindingService, instantiationService, viewDescriptorService, configurationService, contextKeyService, openerService, themeService, telemetryService, hoverService, menuService) {
    super(options3, keybindingService, contextMenuService, configurationService, contextKeyService, viewDescriptorService, instantiationService, openerService, themeService, telemetryService, hoverService);
    this.n = n;
    this.b = false;
    this.j = menuService.createMenu($bJ.DebugWatchContext, contextKeyService);
    this.B(this.j);
    this.a = new $8h(() => {
      this.b = false;
      this.c.updateChildren();
    }, 50);
    this.f = $cR.bindTo(contextKeyService);
    this.h = $NR.bindTo(contextKeyService);
    this.f.set(this.n.getModel().getWatchExpressions().length > 0);
    this.g = $lR.bindTo(contextKeyService);
    this.m = instantiationService.createInstance($D5b);
  }
  W(container2) {
    super.W(container2);
    this.element.classList.add("debug-pane");
    container2.classList.add("debug-watch");
    const treeContainer = $q4b(container2);
    const expressionsRenderer = this.Db.createInstance($Gbc, this.m);
    this.c = this.Db.createInstance($4eb, "WatchExpressions", treeContainer, new WatchExpressionsDelegate(), [
      expressionsRenderer,
      this.Db.createInstance($Yac, this.m),
      this.Db.createInstance($Xac, this.m)
    ], this.Db.createInstance(WatchExpressionsDataSource), {
      accessibilityProvider: new WatchExpressionsAccessibilityProvider(),
      identityProvider: { getId: (element) => element.getId() },
      keyboardNavigationLabelProvider: {
        getKeyboardNavigationLabel: (e) => {
          if (e === this.n.getViewModel().getSelectedExpression()?.expression) {
            return void 0;
          }
          return e.name;
        }
      },
      dnd: new WatchExpressionsDragAndDrop(this.n),
      overrideStyles: this.Xb().listOverrideStyles
    });
    this.B(this.c);
    this.c.setInput(this.n);
    $bR.bindTo(this.c.contextKeyService);
    this.B($Xac.rendererOnVisualizationRange(this.n.getViewModel(), this.c));
    this.B(this.c.onContextMenu((e) => this.L(e)));
    this.B(this.c.onMouseDblClick((e) => this.t(e)));
    this.B(this.n.getModel().onDidChangeWatchExpressions(async (we) => {
      this.f.set(this.n.getModel().getWatchExpressions().length > 0);
      if (!this.isBodyVisible()) {
        this.b = true;
      } else {
        if (we && !we.name) {
          useCachedEvaluation = true;
        }
        await this.c.updateChildren();
        useCachedEvaluation = false;
        if (we instanceof $LP) {
          this.c.reveal(we);
        }
      }
    }));
    this.B(this.n.getViewModel().onDidFocusStackFrame(() => {
      if (!this.isBodyVisible()) {
        this.b = true;
        return;
      }
      if (!this.a.isScheduled()) {
        this.a.schedule();
      }
    }));
    this.B(this.n.getViewModel().onWillUpdateViews(() => {
      if (!ignoreViewUpdates) {
        this.c.updateChildren();
      }
    }));
    this.B(this.onDidChangeBodyVisibility((visible) => {
      if (visible && this.b) {
        this.a.schedule();
      }
    }));
    let horizontalScrolling;
    this.B(this.n.getViewModel().onDidSelectExpression((e) => {
      const expression = e?.expression;
      if (expression && this.c.hasNode(expression)) {
        horizontalScrolling = this.c.options.horizontalScrolling;
        if (horizontalScrolling) {
          this.c.updateOptions({ horizontalScrolling: false });
        }
        if (expression.name) {
          this.c.rerender(expression);
        }
      } else if (!expression && horizontalScrolling !== void 0) {
        this.c.updateOptions({ horizontalScrolling });
        horizontalScrolling = void 0;
      }
    }));
    this.B(this.n.getViewModel().onDidEvaluateLazyExpression(async (e) => {
      if (e instanceof $MP && this.c.hasNode(e)) {
        await this.c.updateChildren(e, false, true);
        await this.c.expand(e);
      }
    }));
  }
  X(height, width2) {
    super.X(height, width2);
    this.c.layout(height, width2);
  }
  focus() {
    super.focus();
    this.c.domFocus();
  }
  collapseAll() {
    this.c.collapseAll();
  }
  t(e) {
    if (e.browserEvent.target.className.indexOf("twistie") >= 0) {
      return;
    }
    const element = e.element;
    const selectedExpression = this.n.getViewModel().getSelectedExpression();
    if (element instanceof $LP && element !== selectedExpression?.expression || element instanceof $KP && element.treeItem.canEdit) {
      this.n.getViewModel().setSelectedExpression(element, false);
    } else if (!element) {
      this.n.addWatchExpression();
    }
  }
  L(e) {
    const element = e.element;
    const selection = this.c.getSelection();
    this.g.set(element instanceof $LP ? "expression" : element instanceof $MP ? "variable" : void 0);
    const attributes = element instanceof $MP ? element.presentationHint?.attributes : void 0;
    this.h.set(!!attributes && attributes.indexOf("readOnly") >= 0 || !!element?.presentationHint?.lazy);
    const actions = $P$(this.j.getActions({ arg: element, shouldForwardArgs: true }));
    this.zb.showContextMenu({
      getAnchor: () => e.anchor,
      getActions: () => actions,
      getActionsContext: () => element && selection.includes(element) ? selection : element ? [element] : []
    });
  }
};
$Fbc = __decorate([
  __param(1, $50),
  __param(2, $0R),
  __param(3, $Ty),
  __param(4, $Pk),
  __param(5, $$M),
  __param(6, $kl),
  __param(7, $on),
  __param(8, $O4),
  __param(9, $gs),
  __param(10, $zv),
  __param(11, $5$),
  __param(12, $cJ)
], $Fbc);
var WatchExpressionsDelegate = class {
  getHeight(_element) {
    return 22;
  }
  getTemplateId(element) {
    if (element instanceof $LP) {
      return $Gbc.ID;
    }
    if (element instanceof $KP) {
      return $Xac.ID;
    }
    return $Yac.ID;
  }
};
function isDebugService(element) {
  return typeof element.getConfigurationManager === "function";
}
var WatchExpressionsDataSource = class extends $r4b {
  hasChildren(element) {
    return isDebugService(element) || element.hasChildren;
  }
  c(element) {
    if (isDebugService(element)) {
      const debugService = element;
      const watchExpressions = debugService.getModel().getWatchExpressions();
      const viewModel = debugService.getViewModel();
      return Promise.all(watchExpressions.map((we) => !!we.name && !useCachedEvaluation ? we.evaluate(viewModel.focusedSession, viewModel.focusedStackFrame, "watch").then(() => we) : Promise.resolve(we)));
    }
    return element.getChildren();
  }
};
var $Gbc = class $Gbc2 extends $s4b {
  static {
    $Gbc_1 = this;
  }
  static {
    this.ID = "watchexpression";
  }
  constructor(i2, j, k, debugService, contextViewService, hoverService, l) {
    super(debugService, contextViewService, hoverService);
    this.i = i2;
    this.j = j;
    this.k = k;
    this.l = l;
  }
  get templateId() {
    return $Gbc_1.ID;
  }
  renderElement(node, index, data) {
    data.elementDisposable.clear();
    data.elementDisposable.add(this.l.onDidChangeConfiguration((e) => {
      if (e.affectsConfiguration("debug.showVariableTypes")) {
        super.d(node.element, node, data);
      }
    }));
    super.d(node.element, node, data);
  }
  f(expression, data, highlights) {
    let text2;
    data.type.textContent = "";
    const showType = this.l.getValue("debug").showVariableTypes;
    if (showType && expression.type) {
      text2 = typeof expression.value === "string" ? `${expression.name}: ` : expression.name;
      data.type.textContent = expression.type + " =";
    } else {
      text2 = typeof expression.value === "string" ? `${expression.name} =` : expression.name;
    }
    let title;
    if (expression.type) {
      if (showType) {
        title = `${expression.name}`;
      } else {
        title = expression.type === expression.value ? expression.type : `${expression.type}`;
      }
    } else {
      title = expression.value;
    }
    data.label.set(text2, highlights, title);
    data.elementDisposable.add(this.i.renderValue(data.value, expression, {
      showChanged: true,
      maxValueLength: MAX_VALUE_RENDER_LENGTH_IN_VIEWLET3,
      colorize: true,
      session: expression.getSession()
    }));
  }
  g(expression, settingValue) {
    if (settingValue) {
      return {
        initialValue: expression.value,
        ariaLabel: localize(6087, null),
        onFinish: async (value, success) => {
          if (success && value) {
            const focusedFrame = this.a.getViewModel().focusedStackFrame;
            if (focusedFrame && (expression instanceof $MP || expression instanceof $LP)) {
              await expression.setExpression(value, focusedFrame);
              this.a.getViewModel().updateViews();
            }
          }
        }
      };
    }
    return {
      initialValue: expression.name ? expression.name : "",
      ariaLabel: localize(6088, null),
      placeholder: localize(6089, null),
      onFinish: (value, success) => {
        if (success && value) {
          this.a.renameWatchExpression(expression.getId(), value);
          ignoreViewUpdates = true;
          this.a.getViewModel().updateViews();
          ignoreViewUpdates = false;
        } else if (!expression.name) {
          this.a.removeWatchExpressions(expression.getId());
        }
      }
    };
  }
  h(actionBar, expression) {
    const contextKeyService = getContextForWatchExpressionMenu(this.k, expression);
    const context = expression;
    const menu = this.j.getMenuActions($bJ.DebugWatchContext, contextKeyService, { arg: context, shouldForwardArgs: false });
    const { primary } = $O$(menu, "inline");
    actionBar.clear();
    actionBar.context = context;
    actionBar.push(primary, { icon: true, label: false });
  }
};
$Gbc = $Gbc_1 = __decorate([
  __param(1, $cJ),
  __param(2, $on),
  __param(3, $0R),
  __param(4, $40),
  __param(5, $5$),
  __param(6, $kl)
], $Gbc);
function getContextForWatchExpressionMenu(parentContext, expression) {
  return parentContext.createOverlay([
    [$mR.key, expression.memoryReference !== void 0],
    [$lR.key, "expression"]
  ]);
}
var WatchExpressionsAccessibilityProvider = class {
  getWidgetAriaLabel() {
    return localize(6090, null);
  }
  getAriaLabel(element) {
    if (element instanceof $LP) {
      return localize(6091, null, element.name, element.value);
    }
    return localize(6092, null, element.name, element.value);
  }
};
var WatchExpressionsDragAndDrop = class {
  constructor(a) {
    this.a = a;
  }
  onDragOver(data, targetElement, targetIndex, targetSector, originalEvent) {
    if (!(data instanceof $g1)) {
      return false;
    }
    const expressions = data.elements;
    if (!(expressions.length > 0 && expressions[0] instanceof $LP)) {
      return false;
    }
    let dropEffectPosition = void 0;
    if (targetIndex === void 0) {
      dropEffectPosition = "drop-target-after";
      targetIndex = -1;
    } else {
      switch (targetSector) {
        case 0:
        case 1:
          dropEffectPosition = "drop-target-before";
          break;
        case 2:
        case 3:
          dropEffectPosition = "drop-target-after";
          break;
      }
    }
    return { accept: true, effect: { type: 1, position: dropEffectPosition }, feedback: [targetIndex] };
  }
  getDragURI(element) {
    if (!(element instanceof $LP) || element === this.a.getViewModel().getSelectedExpression()?.expression) {
      return null;
    }
    return element.getId();
  }
  getDragLabel(elements) {
    if (elements.length === 1) {
      return elements[0].name;
    }
    return void 0;
  }
  drop(data, targetElement, targetIndex, targetSector, originalEvent) {
    if (!(data instanceof $g1)) {
      return;
    }
    const draggedElement = data.elements[0];
    if (!(draggedElement instanceof $LP)) {
      throw new Error("Invalid dragged element");
    }
    const watches = this.a.getModel().getWatchExpressions();
    const sourcePosition = watches.indexOf(draggedElement);
    let targetPosition;
    if (targetElement instanceof $LP) {
      targetPosition = watches.indexOf(targetElement);
      switch (targetSector) {
        case 3:
        case 2:
          targetPosition++;
          break;
      }
      if (sourcePosition < targetPosition) {
        targetPosition--;
      }
    } else {
      targetPosition = watches.length - 1;
    }
    this.a.moveWatchExpression(draggedElement.getId(), targetPosition);
  }
  dispose() {
  }
};
$hJ(class Collapse3 extends $cpb {
  constructor() {
    super({
      id: "watch.collapse",
      viewId: $VQ,
      title: localize(6093, null),
      f1: false,
      icon: $6l.collapseAll,
      precondition: $cR,
      menu: {
        id: $bJ.ViewTitle,
        order: 30,
        group: "navigation",
        when: $7m.equals("view", $VQ)
      }
    });
  }
  runInView(_accessor, view) {
    view.collapseAll();
  }
});
var $Hbc = "workbench.debug.viewlet.action.addWatchExpression";
var $Ibc = localize(6094, null);
$hJ(class AddWatchExpressionAction extends $gJ {
  constructor() {
    super({
      id: $Hbc,
      title: $Ibc,
      f1: false,
      icon: $9Fb,
      menu: {
        id: $bJ.ViewTitle,
        group: "navigation",
        when: $7m.equals("view", $VQ)
      }
    });
  }
  run(accessor) {
    const debugService = accessor.get($0R);
    debugService.addWatchExpression();
  }
});
var $Jbc = "workbench.debug.viewlet.action.removeAllWatchExpressions";
var $Kbc = localize(6095, null);
$hJ(class RemoveAllWatchExpressionsAction extends $gJ {
  constructor() {
    super({
      id: $Jbc,
      // Use old and long id for backwards compatibility
      title: $Kbc,
      f1: false,
      icon: $7Fb,
      precondition: $cR,
      menu: {
        id: $bJ.ViewTitle,
        order: 20,
        group: "navigation",
        when: $7m.equals("view", $VQ)
      }
    });
  }
  run(accessor) {
    const debugService = accessor.get($0R);
    debugService.removeWatchExpressions();
  }
});

// out-build/vs/workbench/contrib/debug/common/debugLifecycle.js
var $Lbc = class $Lbc2 {
  constructor(lifecycleService, b, c, d) {
    this.b = b;
    this.c = c;
    this.d = d;
    this.a = lifecycleService.onBeforeShutdown(async (e) => e.veto(this.f(e.reason), "veto.debug"));
  }
  f(_reason) {
    const rootSessions = this.b.getModel().getSessions().filter((s) => s.parentSession === void 0);
    if (rootSessions.length === 0) {
      return false;
    }
    const shouldConfirmOnExit = this.c.getValue("debug").confirmOnExit;
    if (shouldConfirmOnExit === "never") {
      return false;
    }
    return this.g(rootSessions.length);
  }
  dispose() {
    return this.a.dispose();
  }
  async g(numSessions) {
    let message;
    if (numSessions === 1) {
      message = localize(6181, null);
    } else {
      message = localize(6182, null);
    }
    const res = await this.d.confirm({
      message,
      type: "warning",
      primaryButton: localize(6183, null)
    });
    return !res.confirmed;
  }
};
$Lbc = __decorate([
  __param(0, $KL),
  __param(1, $0R),
  __param(2, $kl),
  __param(3, $Yv)
], $Lbc);

// out-build/vs/workbench/contrib/notebook/browser/contrib/notebookVariables/notebookVariableCommands.js
var $Mbc = "workbench.debug.viewlet.action.copyWorkspaceVariableValue";
var $Nbc = localize(8173, null);
$hJ(class extends $gJ {
  constructor() {
    super({
      id: $Mbc,
      title: $Nbc,
      f1: false
    });
  }
  run(accessor, context) {
    const clipboardService = accessor.get($30);
    if (context.value) {
      clipboardService.writeText(context.value);
    }
  }
});
$hJ(class extends $gJ {
  constructor() {
    super({
      id: "_executeNotebookVariableProvider",
      title: localize(8174, null),
      f1: false
    });
  }
  async run(accessor, resource) {
    if (!resource) {
      return [];
    }
    const uri = URI.revive(resource);
    const notebookKernelService = accessor.get($CL);
    const notebookService = accessor.get($mrb);
    const notebookTextModel = notebookService.getNotebookTextModel(uri);
    if (!notebookTextModel) {
      return [];
    }
    const selectedKernel = notebookKernelService.getMatchingKernel(notebookTextModel).selected;
    if (selectedKernel && selectedKernel.hasVariableProvider) {
      const variables = selectedKernel.provideVariables(notebookTextModel.uri, void 0, "named", 0, CancellationToken.None);
      return await variables.map((variable) => {
        return variable;
      }).toPromise();
    }
    return [];
  }
});

// out-build/vs/workbench/contrib/debug/browser/debugSettingMigration.js
$Wn.as($YL.ConfigurationMigration).registerConfigurationMigrations([{
  key: "debug.autoExpandLazyVariables",
  migrateFn: (value) => {
    if (value === true) {
      return { value: "on" };
    } else if (value === false) {
      return { value: "off" };
    }
    return [];
  }
}]);

// out-build/vs/workbench/contrib/debug/browser/replAccessibilityHelp.js
var $Obc = class {
  constructor() {
    this.priority = 120;
    this.name = "replHelp";
    this.when = $7m.equals("focusedView", "workbench.panel.repl.view");
    this.type = "help";
  }
  getProvider(accessor) {
    const viewsService = accessor.get($uob);
    const replView = $p9b(viewsService);
    if (!replView) {
      return void 0;
    }
    return new ReplAccessibilityHelpProvider(replView);
  }
};
var ReplAccessibilityHelpProvider = class extends $3c {
  constructor(b) {
    super();
    this.b = b;
    this.id = "replHelp";
    this.verbositySettingKey = "accessibility.verbosity.debug";
    this.options = {
      type: "help"
      /* AccessibleViewType.Help */
    };
    this.a = false;
    this.a = !!b.getFocusedElement();
  }
  onClose() {
    if (this.a) {
      return this.b.focusTree();
    }
    this.b.getReplInput().focus();
  }
  provideContent() {
    return [
      localize(6045, null, "<keybinding:workbench.panel.repl.view.focus>"),
      localize(6046, null, "<keybinding:widgetNavigation.focusPrevious>"),
      localize(6047, null, "<keybinding:widgetNavigation.focusNext>"),
      localize(6048, null),
      localize(6049, null, "<keybinding:editor.action.accessibleView>"),
      localize(6050, null, "<keybinding:workbench.view.debug>"),
      localize(6051, null, "<keybinding:workbench.debug.panel.action.clearReplAction>"),
      localize(6052, null)
    ].join("\n");
  }
};

// out-build/vs/workbench/contrib/debug/common/replAccessibilityAnnouncer.js
var $Pbc = class $Pbc2 extends $3c {
  static {
    this.ID = "debug.replAccessibilityAnnouncer";
  }
  constructor(debugService, accessibilityService, logService) {
    super();
    const viewModel = debugService.getViewModel();
    this.B(viewModel.onDidFocusSession((session) => {
      if (!session) {
        return;
      }
      this.B(session.onDidChangeReplElements((element) => {
        if (!element || !("originalExpression" in element)) {
          return;
        }
        const value = element.toString();
        accessibilityService.status(value);
        logService.trace("ReplAccessibilityAnnouncer#onDidChangeReplElements", element.originalExpression + ": " + value);
      }));
    }));
  }
};
$Pbc = __decorate([
  __param(0, $0R),
  __param(1, $ND),
  __param(2, $wn)
], $Pbc);

// out-build/vs/workbench/contrib/debug/browser/runAndDebugAccessibilityHelp.js
var $Qbc = class {
  constructor() {
    this.priority = 120;
    this.name = "runAndDebugHelp";
    this.when = $7m.or($7m.and($7m.equals("activeViewlet", "workbench.view.debug"), $4pb), $7m.equals($jqb.key, $UQ), $7m.equals($jqb.key, $VQ), $7m.equals($jqb.key, $WQ), $7m.equals($jqb.key, $XQ), $7m.equals($jqb.key, $YQ));
    this.type = "help";
  }
  getProvider(accessor) {
    return new RunAndDebugAccessibilityHelpProvider(accessor.get($sn), accessor.get($uob));
  }
};
var RunAndDebugAccessibilityHelpProvider = class RunAndDebugAccessibilityHelpProvider2 extends $3c {
  constructor(b, c) {
    super();
    this.b = b;
    this.c = c;
    this.id = "runAndDebug";
    this.verbositySettingKey = "accessibility.verbosity.debug";
    this.options = {
      type: "help"
      /* AccessibleViewType.Help */
    };
    this.a = this.c.getFocusedViewName();
  }
  onClose() {
    switch (this.a) {
      case "Watch":
        this.b.executeCommand("workbench.debug.action.focusWatchView");
        break;
      case "Variables":
        this.b.executeCommand("workbench.debug.action.focusVariablesView");
        break;
      case "Call Stack":
        this.b.executeCommand("workbench.debug.action.focusCallStackView");
        break;
      case "Breakpoints":
        this.b.executeCommand("workbench.debug.action.focusBreakpointsView");
        break;
      default:
        this.b.executeCommand("workbench.view.debug");
    }
  }
  provideContent() {
    return [
      localize(6058, null, "<keybinding:workbench.view.debug>"),
      localize(6059, null, "<keybinding:workbench.action.debug.start>"),
      localize(6060, null, "<keybinding:workbench.panel.repl.view.focus>"),
      AccessibilityHelpNLS.setBreakpoint,
      AccessibilityHelpNLS.addToWatch,
      localize(6061, null),
      localize(6062, null, "<keybinding:workbench.action.debug.restart>"),
      localize(6063, null, "<keybinding:workbench.action.debug.stop>"),
      localize(6064, null, "<keybinding:workbench.action.debug.continue>"),
      localize(6065, null, "<keybinding:workbench.action.debug.stepInto>"),
      localize(6066, null, "<keybinding:workbench.action.debug.stepOver>"),
      localize(6067, null, "<keybinding:workbench.action.debug.stepOut>"),
      localize(6068, null),
      localize(6069, null, "<keybinding:workbench.debug.action.focusBreakpointsView>"),
      localize(6070, null, "<keybinding:workbench.debug.action.focusCallStackView>"),
      localize(6071, null, "<keybinding:workbench.debug.action.focusVariablesView>"),
      localize(6072, null, "<keybinding:workbench.debug.action.focusWatchView>"),
      localize(6073, null, "accessibility.debugWatchVariableAnnouncements")
    ].join("\n");
  }
};
RunAndDebugAccessibilityHelpProvider = __decorate([
  __param(0, $sn),
  __param(1, $uob)
], RunAndDebugAccessibilityHelpProvider);

// out-build/vs/workbench/contrib/debug/common/debugAccessibilityAnnouncer.js
var $Rbc = class $Rbc2 extends $3c {
  static {
    this.ID = "workbench.contrib.debugWatchAccessibilityAnnouncer";
  }
  constructor(b, c, f, g) {
    super();
    this.b = b;
    this.c = c;
    this.f = f;
    this.g = g;
    this.a = this.B(new $4c());
    this.h();
    this.B(g.onDidChangeConfiguration((e) => {
      if (e.affectsConfiguration("accessibility.debugWatchVariableAnnouncements")) {
        this.h();
      }
    }));
  }
  h() {
    const value = this.g.getValue("accessibility.debugWatchVariableAnnouncements");
    if (value && !this.a.value) {
      this.a.value = this.b.getModel().onDidChangeWatchExpressionValue((e) => {
        if (!e || e.value === $LP.DEFAULT_VALUE) {
          return;
        }
        this.f.alert(`${e.name} = ${e.value}`);
        this.c.trace(`debugAccessibilityAnnouncerValueChanged ${e.name} ${e.value}`);
      });
    } else {
      this.a.clear();
    }
  }
};
$Rbc = __decorate([
  __param(0, $0R),
  __param(1, $wn),
  __param(2, $ND),
  __param(3, $kl)
], $Rbc);

// out-build/vs/workbench/contrib/debug/browser/debug.contribution.js
var debugCategory = localize(5624, null);
$hGb();
$SC(
  $0R,
  $rbc,
  1
  /* InstantiationType.Delayed */
);
$SC(
  $FP,
  $HP,
  1
  /* InstantiationType.Delayed */
);
$Wn.as(Extensions2.Workbench).registerWorkbenchContribution(
  $tbc,
  4
  /* LifecyclePhase.Eventually */
);
$Wn.as(Extensions2.Workbench).registerWorkbenchContribution(
  $$ac,
  4
  /* LifecyclePhase.Eventually */
);
if ($r) {
  $Wn.as(Extensions2.Workbench).registerWorkbenchContribution(
    $ubc,
    4
    /* LifecyclePhase.Eventually */
  );
}
$Wn.as(Extensions2.Workbench).registerWorkbenchContribution(
  $Kac,
  3
  /* LifecyclePhase.Restored */
);
$Wn.as(Extensions2.Workbench).registerWorkbenchContribution(
  $xbc,
  4
  /* LifecyclePhase.Eventually */
);
$Wn.as(Extensions2.Workbench).registerWorkbenchContribution(
  $Dbc,
  4
  /* LifecyclePhase.Eventually */
);
$Wn.as(Extensions2.Workbench).registerWorkbenchContribution(
  $S3b,
  4
  /* LifecyclePhase.Eventually */
);
$Wn.as(Extensions2.Workbench).registerWorkbenchContribution(
  $Lbc,
  4
  /* LifecyclePhase.Eventually */
);
$Wn.as($CM.Quickaccess).registerQuickAccessProvider({
  ctor: $_ac,
  prefix: $B5b,
  contextKey: "inLaunchConfigurationsPicker",
  placeholder: localize(5625, null),
  helpEntries: [{
    description: localize(5626, null),
    commandId: $S4b,
    commandCenterOrder: 50
  }]
});
$Wn.as($CM.Quickaccess).registerQuickAccessProvider({
  ctor: $Rac,
  prefix: $C5b,
  contextKey: "inDebugConsolePicker",
  placeholder: localize(5627, null),
  helpEntries: [{ description: localize(5628, null), commandId: $T4b }]
});
$85(
  "editor.contrib.callStack",
  $Q3b,
  1
  /* EditorContributionInstantiation.AfterFirstRender */
);
$85(
  $4R,
  $Z3b,
  1
  /* EditorContributionInstantiation.AfterFirstRender */
);
$85(
  $3R,
  $0ac,
  2
  /* EditorContributionInstantiation.BeforeFirstInteraction */
);
var registerDebugCommandPaletteItem = (id2, title, when, precondition2) => {
  $dJ.appendMenuItem($bJ.CommandPalette, {
    when: $7m.and($BR, when),
    group: debugCategory,
    command: {
      id: id2,
      title,
      category: $_4b,
      precondition: precondition2
    }
  });
};
registerDebugCommandPaletteItem($D4b, $a5b);
registerDebugCommandPaletteItem($E4b, localize2(5721, "Terminate Thread"), $9Q);
registerDebugCommandPaletteItem($F4b, $b5b, $9Q, $5Q.isEqualTo("stopped"));
registerDebugCommandPaletteItem($G4b, $c5b, $9Q, $5Q.isEqualTo("stopped"));
registerDebugCommandPaletteItem($H4b, $d5b, $9Q, $7m.and($zR, $9Q, $5Q.isEqualTo("stopped")));
registerDebugCommandPaletteItem($I4b, $e5b, $9Q, $5Q.isEqualTo("stopped"));
registerDebugCommandPaletteItem($J4b, $f5b, $9Q, $7m.and($5Q.isEqualTo("running"), $uR.toNegated()));
registerDebugCommandPaletteItem($K4b, $g5b, $9Q, $7m.or($tR, $KR));
registerDebugCommandPaletteItem($L4b, $h5b, $9Q, $7m.or($tR, $7m.and($LR, $KR)));
registerDebugCommandPaletteItem($M4b, $i5b, $9Q, $7m.or($tR.toNegated(), $KR));
registerDebugCommandPaletteItem($O4b, $j5b, $9Q, $5Q.isEqualTo("stopped"));
registerDebugCommandPaletteItem($P4b, localize2(5722, "Focus on Debug Console View"));
registerDebugCommandPaletteItem($Q4b, localize2(5723, "Jump to Cursor"), $yR);
registerDebugCommandPaletteItem($Q4b, localize2(5724, "Set Next Statement"), $yR);
registerDebugCommandPaletteItem($Sac.ID, $Sac.LABEL, $BR);
registerDebugCommandPaletteItem($Tac.ID, $Tac.LABEL, $9Q);
registerDebugCommandPaletteItem($Uac.ID, $Uac.LABEL);
registerDebugCommandPaletteItem($z4b, localize2(5725, "Inline Breakpoint"));
registerDebugCommandPaletteItem($W4b, $n5b, $7m.and($BR, $5Q.notEqualsTo($7R(
  1
  /* State.Initializing */
))));
registerDebugCommandPaletteItem($X4b, $o5b, $7m.and($BR, $5Q.notEqualsTo($7R(
  1
  /* State.Initializing */
))));
registerDebugCommandPaletteItem($S4b, $l5b, $7m.and($BR, $5Q.notEqualsTo($7R(
  1
  /* State.Initializing */
))));
registerDebugCommandPaletteItem($24b, $p5b);
registerDebugCommandPaletteItem($34b, $q5b);
registerDebugCommandPaletteItem($44b, $r5b, $9Q);
registerDebugCommandPaletteItem($T4b, $z5b);
registerDebugCommandPaletteItem($U4b, $A5b);
registerDebugCommandPaletteItem($54b, $s5b, $9Q, $5Q.isEqualTo("stopped"));
registerDebugCommandPaletteItem($64b, $t5b, $9Q, $5Q.isEqualTo("stopped"));
registerDebugCommandPaletteItem($74b, $u5b, $9Q, $5Q.isEqualTo("stopped"));
registerDebugCommandPaletteItem($84b, $v5b, $9Q, $5Q.isEqualTo("stopped"));
var registerDebugViewMenuItem = (menuId, id2, title, order, when, precondition2, group2 = "navigation", icon2) => {
  $dJ.appendMenuItem(menuId, {
    group: group2,
    when,
    order,
    icon: icon2,
    command: {
      id: id2,
      title,
      icon: icon2,
      precondition: precondition2
    }
  });
};
registerDebugViewMenuItem($bJ.DebugCallStackContext, $D4b, $a5b, 10, $gR.isEqualTo("session"), void 0, "3_modification");
registerDebugViewMenuItem($bJ.DebugCallStackContext, $K4b, $g5b, 20, $gR.isEqualTo("session"), void 0, "3_modification");
registerDebugViewMenuItem($bJ.DebugCallStackContext, $L4b, $h5b, 21, $7m.and($gR.isEqualTo("session"), $LR, $KR), void 0, "3_modification");
registerDebugViewMenuItem($bJ.DebugCallStackContext, $M4b, $i5b, 30, $gR.isEqualTo("session"), void 0, "3_modification");
registerDebugViewMenuItem($bJ.DebugCallStackContext, $J4b, $f5b, 10, $7m.and($gR.isEqualTo("thread"), $7m.and($5Q.isEqualTo("running"), $uR.toNegated())));
registerDebugViewMenuItem($bJ.DebugCallStackContext, $O4b, $j5b, 10, $7m.and($gR.isEqualTo("thread"), $5Q.isEqualTo("stopped")));
registerDebugViewMenuItem($bJ.DebugCallStackContext, $F4b, $b5b, 20, $gR.isEqualTo("thread"), $5Q.isEqualTo("stopped"));
registerDebugViewMenuItem($bJ.DebugCallStackContext, $G4b, $c5b, 30, $gR.isEqualTo("thread"), $5Q.isEqualTo("stopped"));
registerDebugViewMenuItem($bJ.DebugCallStackContext, $I4b, $e5b, 40, $gR.isEqualTo("thread"), $5Q.isEqualTo("stopped"));
registerDebugViewMenuItem($bJ.DebugCallStackContext, $E4b, localize(5629, null), 10, $gR.isEqualTo("thread"), void 0, "termination");
registerDebugViewMenuItem($bJ.DebugCallStackContext, $N4b, localize(5630, null), 10, $7m.and($gR.isEqualTo("stackFrame"), $wR), $xR);
registerDebugViewMenuItem($bJ.DebugCallStackContext, $A4b, localize(5631, null), 20, $gR.isEqualTo("stackFrame"), void 0, "3_modification");
registerDebugViewMenuItem($bJ.DebugVariablesContext, $1ac, localize(5632, null), 15, $mR, $9Q, "inline", $dGb);
registerDebugViewMenuItem($bJ.DebugVariablesContext, $Zac, localize(5633, null), 10, $7m.or($ER, $7m.and($MR, $GR)), $NR.toNegated(), "3_modification");
registerDebugViewMenuItem($bJ.DebugVariablesContext, $$4b, $x5b, 10, void 0, void 0, "5_cutcopypaste");
registerDebugViewMenuItem($bJ.DebugVariablesContext, $04b, $w5b, 20, $MR, void 0, "5_cutcopypaste");
registerDebugViewMenuItem($bJ.DebugVariablesContext, $94b, $y5b, 100, $MR, void 0, "z_commands");
registerDebugViewMenuItem($bJ.DebugVariablesContext, $4ac, localize(5634, null), 200, $JR, void 0, "z_commands");
registerDebugViewMenuItem($bJ.DebugVariablesContext, $2ac, localize(5635, null), 210, $HR, void 0, "z_commands");
registerDebugViewMenuItem($bJ.DebugVariablesContext, $3ac, localize(5636, null), 220, $IR, void 0, "z_commands");
registerDebugViewMenuItem($bJ.DebugHoverContext, $1ac, localize(5637, null), 15, $mR, $9Q, "inline", $dGb);
registerDebugViewMenuItem($bJ.DebugHoverContext, $$4b, $x5b, 10, void 0, void 0, "5_cutcopypaste");
registerDebugViewMenuItem($bJ.DebugHoverContext, $04b, $w5b, 20, $MR, void 0, "5_cutcopypaste");
registerDebugViewMenuItem($bJ.DebugHoverContext, $94b, $y5b, 100, $MR, void 0, "z_commands");
registerDebugViewMenuItem($bJ.DebugHoverContext, $4ac, localize(5638, null), 200, $JR, void 0, "z_commands");
registerDebugViewMenuItem($bJ.DebugHoverContext, $2ac, localize(5639, null), 210, $HR, void 0, "z_commands");
registerDebugViewMenuItem($bJ.DebugHoverContext, $3ac, localize(5640, null), 220, $IR, void 0, "z_commands");
registerDebugViewMenuItem($bJ.DebugWatchContext, $Hbc, $Ibc, 10, void 0, void 0, "3_modification");
registerDebugViewMenuItem($bJ.DebugWatchContext, $Y4b, localize(5641, null), 20, $lR.isEqualTo("expression"), void 0, "3_modification");
registerDebugViewMenuItem($bJ.DebugWatchContext, $Z4b, localize(5642, null), 30, $7m.or($7m.and($lR.isEqualTo("expression"), $GR), $7m.and($lR.isEqualTo("variable"), $ER)), $NR.toNegated(), "3_modification");
registerDebugViewMenuItem($bJ.DebugWatchContext, $$4b, localize(5643, null), 40, $7m.or($lR.isEqualTo("expression"), $lR.isEqualTo("variable")), $9Q, "3_modification");
registerDebugViewMenuItem($bJ.DebugWatchContext, $1ac, localize(5644, null), 10, $mR, void 0, "inline", $dGb);
registerDebugViewMenuItem($bJ.DebugWatchContext, $14b, localize(5645, null), 20, $lR.isEqualTo("expression"), void 0, "inline", $8Fb);
registerDebugViewMenuItem($bJ.DebugWatchContext, $Jbc, $Kbc, 20, void 0, void 0, "z_commands");
registerDebugViewMenuItem($bJ.NotebookVariablesContext, $Mbc, $Nbc, 20, $OR);
if ($m) {
  const registerTouchBarEntry = (id2, title, order, when, iconUri) => {
    $dJ.appendMenuItem($bJ.TouchBarContext, {
      command: {
        id: id2,
        title,
        icon: { dark: iconUri }
      },
      when: $7m.and($BR, when),
      group: "9_debug",
      order
    });
  };
  registerTouchBarEntry($X4b, $o5b, 0, $9Q.toNegated(), $ih.asFileUri("vs/workbench/contrib/debug/browser/media/continue-tb.png"));
  registerTouchBarEntry($W4b, $n5b, 1, $9Q.toNegated(), $ih.asFileUri("vs/workbench/contrib/debug/browser/media/run-with-debugging-tb.png"));
  registerTouchBarEntry($O4b, $j5b, 0, $5Q.isEqualTo("stopped"), $ih.asFileUri("vs/workbench/contrib/debug/browser/media/continue-tb.png"));
  registerTouchBarEntry($J4b, $f5b, 1, $7m.and($9Q, $7m.and($5Q.isEqualTo("running"), $uR.toNegated())), $ih.asFileUri("vs/workbench/contrib/debug/browser/media/pause-tb.png"));
  registerTouchBarEntry($F4b, $b5b, 2, $9Q, $ih.asFileUri("vs/workbench/contrib/debug/browser/media/stepover-tb.png"));
  registerTouchBarEntry($G4b, $c5b, 3, $9Q, $ih.asFileUri("vs/workbench/contrib/debug/browser/media/stepinto-tb.png"));
  registerTouchBarEntry($I4b, $e5b, 4, $9Q, $ih.asFileUri("vs/workbench/contrib/debug/browser/media/stepout-tb.png"));
  registerTouchBarEntry($D4b, $a5b, 5, $9Q, $ih.asFileUri("vs/workbench/contrib/debug/browser/media/restart-tb.png"));
  registerTouchBarEntry($M4b, $i5b, 6, $9Q, $ih.asFileUri("vs/workbench/contrib/debug/browser/media/stop-tb.png"));
}
$dJ.appendMenuItem($bJ.EditorTitle, { submenu: $bJ.EditorTitleRun, rememberDefaultAction: true, title: localize2(5726, "Run or Debug..."), icon: $YFb, group: "navigation", order: -1 });
$dJ.appendMenuItem($bJ.MenubarMainMenu, {
  submenu: $bJ.MenubarDebugMenu,
  title: {
    ...localize2(5727, "Run"),
    mnemonicTitle: localize(5646, null)
  },
  order: 6
});
$dJ.appendMenuItem($bJ.MenubarDebugMenu, {
  group: "1_debug",
  command: {
    id: $W4b,
    title: localize(5647, null)
  },
  order: 1,
  when: $BR
});
$dJ.appendMenuItem($bJ.MenubarDebugMenu, {
  group: "1_debug",
  command: {
    id: $X4b,
    title: localize(5648, null)
  },
  order: 2,
  when: $BR
});
$dJ.appendMenuItem($bJ.MenubarDebugMenu, {
  group: "1_debug",
  command: {
    id: $M4b,
    title: localize(5649, null),
    precondition: $9Q
  },
  order: 3,
  when: $BR
});
$dJ.appendMenuItem($bJ.MenubarDebugMenu, {
  group: "1_debug",
  command: {
    id: $D4b,
    title: localize(5650, null),
    precondition: $9Q
  },
  order: 4,
  when: $BR
});
$dJ.appendMenuItem($bJ.MenubarDebugMenu, {
  group: "2_configuration",
  command: {
    id: $y4b,
    title: localize(5651, null)
  },
  order: 2,
  when: $BR
});
$dJ.appendMenuItem($bJ.MenubarDebugMenu, {
  group: "3_step",
  command: {
    id: $F4b,
    title: localize(5652, null),
    precondition: $5Q.isEqualTo("stopped")
  },
  order: 1,
  when: $BR
});
$dJ.appendMenuItem($bJ.MenubarDebugMenu, {
  group: "3_step",
  command: {
    id: $G4b,
    title: localize(5653, null),
    precondition: $5Q.isEqualTo("stopped")
  },
  order: 2,
  when: $BR
});
$dJ.appendMenuItem($bJ.MenubarDebugMenu, {
  group: "3_step",
  command: {
    id: $I4b,
    title: localize(5654, null),
    precondition: $5Q.isEqualTo("stopped")
  },
  order: 3,
  when: $BR
});
$dJ.appendMenuItem($bJ.MenubarDebugMenu, {
  group: "3_step",
  command: {
    id: $O4b,
    title: localize(5655, null),
    precondition: $5Q.isEqualTo("stopped")
  },
  order: 4,
  when: $BR
});
$dJ.appendMenuItem($bJ.MenubarNewBreakpointMenu, {
  group: "1_breakpoints",
  command: {
    id: $z4b,
    title: localize(5656, null)
  },
  order: 2,
  when: $BR
});
$dJ.appendMenuItem($bJ.MenubarDebugMenu, {
  group: "4_new_breakpoint",
  title: localize(5657, null),
  submenu: $bJ.MenubarNewBreakpointMenu,
  order: 2,
  when: $BR
});
$dJ.appendMenuItem($bJ.MenubarDebugMenu, {
  group: "z_install",
  command: {
    id: "debug.installAdditionalDebuggers",
    title: localize(5658, null)
  },
  order: 1
});
var VIEW_CONTAINER = $Wn.as(Extensions5.ViewContainersRegistry).registerViewContainer({
  id: $1Q,
  title: localize2(5728, "Debug Console"),
  icon: $vFb,
  ctorDescriptor: new $Nk($oqb, [$1Q, { mergeViewWithContainerWhenSingleView: true }]),
  storageId: $1Q,
  hideIfEmpty: true,
  order: 2
}, 1, { doNotRegisterOpenCommand: true });
$Wn.as(Extensions5.ViewsRegistry).registerViews([{
  id: $2Q,
  name: localize2(5729, "Debug Console"),
  containerIcon: $vFb,
  canToggleVisibility: false,
  canMoveView: true,
  when: $BR,
  ctorDescriptor: new $Nk(Repl),
  openCommandActionDescriptor: {
    id: "workbench.debug.action.toggleRepl",
    mnemonicTitle: localize(5659, null),
    keybindings: {
      primary: 2048 | 1024 | 55
      /* KeyCode.KeyY */
    },
    order: 2
  }
}], VIEW_CONTAINER);
var viewContainer4 = $Wn.as(Extensions5.ViewContainersRegistry).registerViewContainer(
  {
    id: $TQ,
    title: localize2(5730, "Run and Debug"),
    openCommandActionDescriptor: {
      id: $TQ,
      mnemonicTitle: localize(5660, null),
      keybindings: {
        primary: 2048 | 1024 | 34
        /* KeyCode.KeyD */
      },
      order: 3
    },
    ctorDescriptor: new $Nk($wbc),
    icon: $wFb,
    alwaysUseContainerInfo: true,
    order: 3
  },
  0
  /* ViewContainerLocation.Sidebar */
);
var viewsRegistry6 = $Wn.as(Extensions5.ViewsRegistry);
viewsRegistry6.registerViews([{ id: $UQ, name: localize2(5731, "Variables"), containerIcon: $xFb, ctorDescriptor: new $Nk($Vac), order: 10, weight: 40, canToggleVisibility: true, canMoveView: true, focusCommand: { id: "workbench.debug.action.focusVariablesView" }, when: $7Q.isEqualTo("default") }], viewContainer4);
viewsRegistry6.registerViews([{ id: $VQ, name: localize2(5732, "Watch"), containerIcon: $yFb, ctorDescriptor: new $Nk($Fbc), order: 20, weight: 10, canToggleVisibility: true, canMoveView: true, focusCommand: { id: "workbench.debug.action.focusWatchView" }, when: $7Q.isEqualTo("default") }], viewContainer4);
viewsRegistry6.registerViews([{ id: $WQ, name: localize2(5733, "Call Stack"), containerIcon: $zFb, ctorDescriptor: new $Nk($Pac), order: 30, weight: 30, canToggleVisibility: true, canMoveView: true, focusCommand: { id: "workbench.debug.action.focusCallStackView" }, when: $7Q.isEqualTo("default") }], viewContainer4);
viewsRegistry6.registerViews([{ id: $YQ, name: localize2(5734, "Breakpoints"), containerIcon: $AFb, ctorDescriptor: new $Nk($U3b), order: 40, weight: 20, canToggleVisibility: true, canMoveView: true, focusCommand: { id: "workbench.debug.action.focusBreakpointsView" }, when: $7m.or($AR, $7Q.isEqualTo("default"), $8Q) }], viewContainer4);
viewsRegistry6.registerViews([{ id: $vbc.ID, name: $vbc.LABEL, containerIcon: $wFb, ctorDescriptor: new $Nk($vbc), order: 1, weight: 40, canToggleVisibility: true, when: $7Q.isEqualTo("simple") }], viewContainer4);
viewsRegistry6.registerViews([{ id: $XQ, name: localize2(5735, "Loaded Scripts"), containerIcon: $BFb, ctorDescriptor: new $Nk($ybc), order: 35, weight: 5, canToggleVisibility: true, canMoveView: true, collapsed: true, when: $7m.and($rR, $7Q.isEqualTo("default")) }], viewContainer4);
$Wn.as($ZK.EditorPane).registerEditorPane($7tb.create($R3b, $ZQ, localize(5661, null)), [new $Nk($IP)]);
var configurationRegistry12 = $Wn.as($Ht.Configuration);
configurationRegistry12.registerConfiguration({
  id: "debug",
  order: 20,
  title: localize(5662, null),
  type: "object",
  properties: {
    "debug.showVariableTypes": {
      type: "boolean",
      description: localize(5663, null),
      default: false
    },
    "debug.allowBreakpointsEverywhere": {
      type: "boolean",
      description: localize(5664, null),
      default: false
    },
    "debug.gutterMiddleClickAction": {
      type: "string",
      enum: ["logpoint", "conditionalBreakpoint", "triggeredBreakpoint", "none"],
      description: localize(5665, null),
      enumDescriptions: [
        localize(5666, null),
        localize(5667, null),
        localize(5668, null),
        localize(5669, null)
      ],
      default: "logpoint"
    },
    "debug.openExplorerOnEnd": {
      type: "boolean",
      description: localize(5670, null),
      default: false
    },
    "debug.closeReadonlyTabsOnEnd": {
      type: "boolean",
      description: localize(5671, null),
      default: false
    },
    "debug.inlineValues": {
      type: "string",
      "enum": ["on", "off", "auto"],
      description: localize(5672, null),
      "enumDescriptions": [
        localize(5673, null),
        localize(5674, null),
        localize(5675, null)
      ],
      default: "auto"
    },
    "debug.toolBarLocation": {
      enum: ["floating", "docked", "commandCenter", "hidden"],
      markdownDescription: localize(5676, null, "`#window.commandCenter#`"),
      default: "floating",
      markdownEnumDescriptions: [
        localize(5677, null),
        localize(5678, null),
        localize(5679, null),
        localize(5680, null)
      ]
    },
    "debug.showInStatusBar": {
      enum: ["never", "always", "onFirstSessionStart"],
      enumDescriptions: [localize(5681, null), localize(5682, null), localize(5683, null)],
      description: localize(5684, null),
      default: "onFirstSessionStart"
    },
    "debug.internalConsoleOptions": $6R,
    "debug.console.closeOnEnd": {
      type: "boolean",
      description: localize(5685, null),
      default: false
    },
    "debug.terminal.clearBeforeReusing": {
      type: "boolean",
      description: localize(5686, null),
      default: false
    },
    "debug.openDebug": {
      enum: ["neverOpen", "openOnSessionStart", "openOnFirstSessionStart", "openOnDebugBreak"],
      default: "openOnDebugBreak",
      description: localize(5687, null)
    },
    "debug.showSubSessionsInToolBar": {
      type: "boolean",
      description: localize(5688, null),
      default: false
    },
    "debug.console.fontSize": {
      type: "number",
      description: localize(5689, null),
      default: $m ? 12 : 14
    },
    "debug.console.fontFamily": {
      type: "string",
      description: localize(5690, null),
      default: "default"
    },
    "debug.console.lineHeight": {
      type: "number",
      description: localize(5691, null),
      default: 0
    },
    "debug.console.wordWrap": {
      type: "boolean",
      description: localize(5692, null),
      default: true
    },
    "debug.console.historySuggestions": {
      type: "boolean",
      description: localize(5693, null),
      default: true
    },
    "debug.console.collapseIdenticalLines": {
      type: "boolean",
      description: localize(5694, null),
      default: true
    },
    "debug.console.acceptSuggestionOnEnter": {
      enum: ["off", "on"],
      description: localize(5695, null),
      default: "off"
    },
    "launch": {
      type: "object",
      description: localize(5696, null),
      default: { configurations: [], compounds: [] },
      $ref: $rK,
      disallowConfigurationDefault: true
    },
    "debug.focusWindowOnBreak": {
      type: "boolean",
      description: localize(5697, null),
      default: true
    },
    "debug.focusEditorOnBreak": {
      type: "boolean",
      description: localize(5698, null),
      default: true
    },
    "debug.onTaskErrors": {
      enum: ["debugAnyway", "showErrors", "prompt", "abort"],
      enumDescriptions: [localize(5699, null), localize(5700, null), localize(5701, null), localize(5702, null)],
      description: localize(5703, null),
      default: "prompt"
    },
    "debug.showBreakpointsInOverviewRuler": {
      type: "boolean",
      description: localize(5704, null),
      default: false
    },
    "debug.showInlineBreakpointCandidates": {
      type: "boolean",
      description: localize(5705, null),
      default: true
    },
    "debug.saveBeforeStart": {
      description: localize(5706, null),
      enum: ["allEditorsInActiveGroup", "nonUntitledEditorsInActiveGroup", "none"],
      enumDescriptions: [
        localize(5707, null),
        localize(5708, null),
        localize(5709, null)
      ],
      default: "allEditorsInActiveGroup",
      scope: 5
      /* ConfigurationScope.LANGUAGE_OVERRIDABLE */
    },
    "debug.confirmOnExit": {
      description: localize(5710, null),
      type: "string",
      enum: ["never", "always"],
      enumDescriptions: [
        localize(5711, null),
        localize(5712, null)
      ],
      default: "never"
    },
    "debug.disassemblyView.showSourceCode": {
      type: "boolean",
      default: true,
      description: localize(5713, null)
    },
    "debug.autoExpandLazyVariables": {
      type: "string",
      enum: ["auto", "on", "off"],
      default: "auto",
      enumDescriptions: [
        localize(5714, null),
        localize(5715, null),
        localize(5716, null)
      ],
      description: localize(5717, null)
    },
    "debug.enableStatusBarColor": {
      type: "boolean",
      description: localize(5718, null),
      default: true
    },
    "debug.hideLauncherWhileDebugging": {
      type: "boolean",
      markdownDescription: localize(5719, null, "`#debug.toolBarLocation#`"),
      default: false
    },
    "debug.hideSlowPreLaunchWarning": {
      type: "boolean",
      markdownDescription: localize(5720, null),
      default: false
    }
  }
});
$vhb.register(new $Qac());
$vhb.register(new $Obc());
$vhb.register(new $Qbc());
$PL(
  $Pbc.ID,
  $Pbc,
  3
  /* WorkbenchPhase.AfterRestored */
);
$PL(
  $Rbc.ID,
  $Rbc,
  3
  /* WorkbenchPhase.AfterRestored */
);

// out-build/vs/workbench/contrib/markers/browser/markersFileDecorations.js
var MarkersDecorationsProvider = class {
  constructor(a) {
    this.a = a;
    this.label = localize(7857, null);
    this.onDidChange = a.onMarkerChanged;
  }
  provideDecorations(resource) {
    const markers = this.a.read({
      resource,
      severities: MarkerSeverity.Error | MarkerSeverity.Warning
    });
    let first;
    for (const marker of markers) {
      if (!first || marker.severity > first.severity) {
        first = marker;
      }
    }
    if (!first) {
      return void 0;
    }
    return {
      weight: 100 * first.severity,
      bubble: true,
      tooltip: markers.length === 1 ? localize(7858, null) : localize(7859, null, markers.length),
      letter: markers.length < 10 ? markers.length.toString() : "9+",
      color: first.severity === MarkerSeverity.Error ? $xr : $yr
    };
  }
};
var MarkersFileDecorations = class MarkersFileDecorations2 {
  constructor(d, f, g) {
    this.d = d;
    this.f = f;
    this.g = g;
    this.a = [
      this.g.onDidChangeConfiguration((e) => {
        if (e.affectsConfiguration("problems.visibility")) {
          this.h();
        }
      })
    ];
    this.h();
  }
  dispose() {
    $Xc(this.b);
    $Xc(this.a);
  }
  h() {
    const problem = this.g.getValue("problems.visibility");
    if (problem === void 0) {
      return;
    }
    const value = this.g.getValue("problems");
    const shouldEnable = problem && value.decorations.enabled;
    if (shouldEnable === this.c) {
      if (!problem || !value.decorations.enabled) {
        this.b?.dispose();
        this.b = void 0;
      }
      return;
    }
    this.c = shouldEnable;
    if (this.c) {
      const provider = new MarkersDecorationsProvider(this.d);
      this.b = this.f.registerDecorationsProvider(provider);
    } else if (this.b) {
      this.b.dispose();
    }
  }
};
MarkersFileDecorations = __decorate([
  __param(0, $DE),
  __param(1, $jsb),
  __param(2, $kl)
], MarkersFileDecorations);
$Wn.as($Ht.Configuration).registerConfiguration({
  "id": "problems",
  "order": 101,
  "type": "object",
  "properties": {
    "problems.decorations.enabled": {
      "markdownDescription": localize(7860, null, "`#problems.visibility#`"),
      "type": "boolean",
      "default": true
    }
  }
});
$Wn.as(Extensions2.Workbench).registerWorkbenchContribution(
  MarkersFileDecorations,
  3
  /* LifecyclePhase.Restored */
);

// out-build/vs/workbench/contrib/markers/browser/markersModel.js
function $Sbc(a, b) {
  return $lh.compare(a.resource, b.resource);
}
function compareResourceMarkers(a, b) {
  const [firstMarkerOfA] = a.markers;
  const [firstMarkerOfB] = b.markers;
  let res = 0;
  if (firstMarkerOfA && firstMarkerOfB) {
    res = MarkerSeverity.compare(firstMarkerOfA.marker.severity, firstMarkerOfB.marker.severity);
  }
  if (res === 0) {
    res = a.path.localeCompare(b.path) || a.name.localeCompare(b.name);
  }
  return res;
}
var $Tbc = class _$Tbc {
  constructor(id2, resource) {
    this.id = id2;
    this.resource = resource;
    this.c = new $Ec();
    this.e = 0;
    this.path = this.resource.fsPath;
    this.name = $sh(this.resource);
  }
  get markers() {
    if (!this.d) {
      this.d = [...this.c.values()].flat().sort(_$Tbc.f);
    }
    return this.d;
  }
  has(uri) {
    return this.c.has(uri);
  }
  set(uri, marker) {
    this.delete(uri);
    if ($Qb(marker)) {
      this.c.set(uri, marker);
      this.e += marker.length;
      this.d = void 0;
    }
  }
  delete(uri) {
    const array2 = this.c.get(uri);
    if (array2) {
      this.e -= array2.length;
      this.d = void 0;
      this.c.delete(uri);
    }
  }
  get total() {
    return this.e;
  }
  static f(a, b) {
    return MarkerSeverity.compare(a.marker.severity, b.marker.severity) || $lh.compare(a.resource, b.resource) || $9C.compareRangesUsingStarts(a.marker, b.marker);
  }
};
var $Ubc = class {
  get resource() {
    return this.marker.resource;
  }
  get range() {
    return this.marker;
  }
  get lines() {
    if (!this.c) {
      this.c = $Mf(this.marker.message);
    }
    return this.c;
  }
  constructor(id2, marker, relatedInformation = []) {
    this.id = id2;
    this.marker = marker;
    this.relatedInformation = relatedInformation;
  }
  toString() {
    return JSON.stringify({
      ...this.marker,
      resource: this.marker.resource.path,
      relatedInformation: this.relatedInformation.length ? this.relatedInformation.map((r2) => ({ ...r2.raw, resource: r2.raw.resource.path })) : void 0
    }, null, "	");
  }
};
var $Vbc = class extends $Ubc {
  constructor(marker, sourceMatches, codeMatches, messageMatches, fileMatches, ownerMatches) {
    super(marker.id, marker.marker, marker.relatedInformation);
    this.sourceMatches = sourceMatches;
    this.codeMatches = codeMatches;
    this.messageMatches = messageMatches;
    this.fileMatches = fileMatches;
    this.ownerMatches = ownerMatches;
  }
};
var $Wbc = class {
  constructor(id2, marker, raw) {
    this.id = id2;
    this.marker = marker;
    this.raw = raw;
  }
};
var $Xbc = class {
  get resourceMarkers() {
    if (!this.d) {
      this.d = [...this.f.values()].sort(compareResourceMarkers);
    }
    return this.d;
  }
  constructor() {
    this.d = void 0;
    this.e = new $ze();
    this.onDidChange = this.e.event;
    this.g = 0;
    this.f = /* @__PURE__ */ new Map();
  }
  reset() {
    const removed = /* @__PURE__ */ new Set();
    for (const resourceMarker of this.f.values()) {
      removed.add(resourceMarker);
    }
    this.f.clear();
    this.g = 0;
    this.e.fire({ removed, added: /* @__PURE__ */ new Set(), updated: /* @__PURE__ */ new Set() });
  }
  get total() {
    return this.g;
  }
  getResourceMarkers(resource) {
    return this.f.get($lh.getComparisonKey(resource, true)) ?? null;
  }
  setResourceMarkers(resourcesMarkers) {
    const change = { added: /* @__PURE__ */ new Set(), removed: /* @__PURE__ */ new Set(), updated: /* @__PURE__ */ new Set() };
    for (const [resource, rawMarkers] of resourcesMarkers) {
      if ($zYb.has(resource.scheme)) {
        continue;
      }
      const key2 = $lh.getComparisonKey(resource, true);
      let resourceMarkers = this.f.get(key2);
      if ($Qb(rawMarkers)) {
        if (!resourceMarkers) {
          const resourceMarkersId = this.h(resource.toString());
          resourceMarkers = new $Tbc(resourceMarkersId, resource.with({ fragment: null }));
          this.f.set(key2, resourceMarkers);
          change.added.add(resourceMarkers);
        } else {
          change.updated.add(resourceMarkers);
        }
        const markersCountByKey = /* @__PURE__ */ new Map();
        const markers = rawMarkers.map((rawMarker) => {
          const key3 = IMarkerData.makeKey(rawMarker);
          const index = markersCountByKey.get(key3) || 0;
          markersCountByKey.set(key3, index + 1);
          const markerId = this.h(resourceMarkers.id, key3, index, rawMarker.resource.toString());
          let relatedInformation = void 0;
          if (rawMarker.relatedInformation) {
            relatedInformation = rawMarker.relatedInformation.map((r2, index2) => new $Wbc(this.h(markerId, r2.resource.toString(), r2.startLineNumber, r2.startColumn, r2.endLineNumber, r2.endColumn, index2), rawMarker, r2));
          }
          return new $Ubc(markerId, rawMarker, relatedInformation);
        });
        this.g -= resourceMarkers.total;
        resourceMarkers.set(resource, markers);
        this.g += resourceMarkers.total;
      } else if (resourceMarkers) {
        this.g -= resourceMarkers.total;
        resourceMarkers.delete(resource);
        this.g += resourceMarkers.total;
        if (resourceMarkers.total === 0) {
          this.f.delete(key2);
          change.removed.add(resourceMarkers);
        } else {
          change.updated.add(resourceMarkers);
        }
      }
    }
    this.d = void 0;
    if (change.added.size || change.removed.size || change.updated.size) {
      this.e.fire(change);
    }
  }
  h(...values) {
    return `${$Xi(values)}`;
  }
  dispose() {
    this.e.dispose();
    this.f.clear();
  }
};

// out-build/vs/workbench/contrib/markers/browser/messages.js
var $Ybc = class {
  static {
    this.MARKERS_PANEL_TOGGLE_LABEL = localize(7874, null);
  }
  static {
    this.MARKERS_PANEL_SHOW_LABEL = localize2(7919, "Focus Problems (Errors, Warnings, Infos)");
  }
  static {
    this.PROBLEMS_PANEL_CONFIGURATION_TITLE = localize(7875, null);
  }
  static {
    this.PROBLEMS_PANEL_CONFIGURATION_AUTO_REVEAL = localize(7876, null);
  }
  static {
    this.PROBLEMS_PANEL_CONFIGURATION_VIEW_MODE = localize(7877, null);
  }
  static {
    this.PROBLEMS_PANEL_CONFIGURATION_SHOW_CURRENT_STATUS = localize(7878, null);
  }
  static {
    this.PROBLEMS_PANEL_CONFIGURATION_COMPARE_ORDER = localize(7879, null);
  }
  static {
    this.PROBLEMS_PANEL_CONFIGURATION_COMPARE_ORDER_SEVERITY = localize(7880, null);
  }
  static {
    this.PROBLEMS_PANEL_CONFIGURATION_COMPARE_ORDER_POSITION = localize(7881, null);
  }
  static {
    this.MARKERS_PANEL_TITLE_PROBLEMS = localize2(7920, "Problems");
  }
  static {
    this.MARKERS_PANEL_NO_PROBLEMS_BUILT = localize(7882, null);
  }
  static {
    this.MARKERS_PANEL_NO_PROBLEMS_ACTIVE_FILE_BUILT = localize(7883, null);
  }
  static {
    this.MARKERS_PANEL_NO_PROBLEMS_FILTERS = localize(7884, null);
  }
  static {
    this.MARKERS_PANEL_ACTION_TOOLTIP_MORE_FILTERS = localize(7885, null);
  }
  static {
    this.MARKERS_PANEL_FILTER_LABEL_SHOW_ERRORS = localize(7886, null);
  }
  static {
    this.MARKERS_PANEL_FILTER_LABEL_SHOW_WARNINGS = localize(7887, null);
  }
  static {
    this.MARKERS_PANEL_FILTER_LABEL_SHOW_INFOS = localize(7888, null);
  }
  static {
    this.MARKERS_PANEL_FILTER_LABEL_EXCLUDED_FILES = localize(7889, null);
  }
  static {
    this.MARKERS_PANEL_FILTER_LABEL_ACTIVE_FILE = localize(7890, null);
  }
  static {
    this.MARKERS_PANEL_ACTION_TOOLTIP_FILTER = localize(7891, null);
  }
  static {
    this.MARKERS_PANEL_ACTION_TOOLTIP_QUICKFIX = localize(7892, null);
  }
  static {
    this.MARKERS_PANEL_FILTER_ARIA_LABEL = localize(7893, null);
  }
  static {
    this.MARKERS_PANEL_FILTER_PLACEHOLDER = localize(7894, null);
  }
  static {
    this.MARKERS_PANEL_FILTER_ERRORS = localize(7895, null);
  }
  static {
    this.MARKERS_PANEL_FILTER_WARNINGS = localize(7896, null);
  }
  static {
    this.MARKERS_PANEL_FILTER_INFOS = localize(7897, null);
  }
  static {
    this.MARKERS_PANEL_SINGLE_ERROR_LABEL = localize(7898, null);
  }
  static {
    this.MARKERS_PANEL_MULTIPLE_ERRORS_LABEL = (noOfErrors) => {
      return localize(7899, null, "" + noOfErrors);
    };
  }
  static {
    this.MARKERS_PANEL_SINGLE_WARNING_LABEL = localize(7900, null);
  }
  static {
    this.MARKERS_PANEL_MULTIPLE_WARNINGS_LABEL = (noOfWarnings) => {
      return localize(7901, null, "" + noOfWarnings);
    };
  }
  static {
    this.MARKERS_PANEL_SINGLE_INFO_LABEL = localize(7902, null);
  }
  static {
    this.MARKERS_PANEL_MULTIPLE_INFOS_LABEL = (noOfInfos) => {
      return localize(7903, null, "" + noOfInfos);
    };
  }
  static {
    this.MARKERS_PANEL_SINGLE_UNKNOWN_LABEL = localize(7904, null);
  }
  static {
    this.MARKERS_PANEL_MULTIPLE_UNKNOWNS_LABEL = (noOfUnknowns) => {
      return localize(7905, null, "" + noOfUnknowns);
    };
  }
  static {
    this.MARKERS_PANEL_AT_LINE_COL_NUMBER = (ln, col) => {
      return localize(7906, null, "" + ln, "" + col);
    };
  }
  static {
    this.MARKERS_TREE_ARIA_LABEL_RESOURCE = (noOfProblems, fileName, folder) => {
      return localize(7907, null, noOfProblems, fileName, folder);
    };
  }
  static {
    this.MARKERS_TREE_ARIA_LABEL_MARKER = (marker) => {
      const relatedInformationMessage = marker.relatedInformation.length ? localize(7908, null, marker.relatedInformation.length) : "";
      switch (marker.marker.severity) {
        case MarkerSeverity.Error:
          return marker.marker.source ? localize(7909, null, marker.marker.message, marker.marker.startLineNumber, marker.marker.startColumn, relatedInformationMessage, marker.marker.source) : localize(7910, null, marker.marker.message, marker.marker.startLineNumber, marker.marker.startColumn, relatedInformationMessage);
        case MarkerSeverity.Warning:
          return marker.marker.source ? localize(7911, null, marker.marker.message, marker.marker.startLineNumber, marker.marker.startColumn, relatedInformationMessage, marker.marker.source) : localize(7912, null, marker.marker.message, marker.marker.startLineNumber, marker.marker.startColumn, relatedInformationMessage, relatedInformationMessage);
        case MarkerSeverity.Info:
          return marker.marker.source ? localize(7913, null, marker.marker.message, marker.marker.startLineNumber, marker.marker.startColumn, relatedInformationMessage, marker.marker.source) : localize(7914, null, marker.marker.message, marker.marker.startLineNumber, marker.marker.startColumn, relatedInformationMessage);
        default:
          return marker.marker.source ? localize(7915, null, marker.marker.source, marker.marker.message, marker.marker.startLineNumber, marker.marker.startColumn, relatedInformationMessage, marker.marker.source) : localize(7916, null, marker.marker.message, marker.marker.startLineNumber, marker.marker.startColumn, relatedInformationMessage);
      }
    };
  }
  static {
    this.MARKERS_TREE_ARIA_LABEL_RELATED_INFORMATION = (relatedInformation) => localize(7917, null, relatedInformation.message, relatedInformation.startLineNumber, relatedInformation.startColumn, $sh(relatedInformation.resource));
  }
  static {
    this.SHOW_ERRORS_WARNINGS_ACTION_LABEL = localize(7918, null);
  }
};

// out-build/vs/workbench/contrib/markers/browser/markersViewActions.js
var $Zbc = class extends $3c {
  constructor(options3, b) {
    super();
    this.b = b;
    this.a = this.B(new $ze());
    this.onDidChange = this.a.event;
    this.c = MarkersContextKeys.ShowExcludedFilesFilterContextKey.bindTo(this.b);
    this.f = MarkersContextKeys.ShowActiveFileFilterContextKey.bindTo(this.b);
    this.g = MarkersContextKeys.ShowWarningsFilterContextKey.bindTo(this.b);
    this.h = MarkersContextKeys.ShowErrorsFilterContextKey.bindTo(this.b);
    this.j = MarkersContextKeys.ShowInfoFilterContextKey.bindTo(this.b);
    this.h.set(options3.showErrors);
    this.g.set(options3.showWarnings);
    this.j.set(options3.showInfos);
    this.c.set(options3.excludedFiles);
    this.f.set(options3.activeFile);
    this.filterHistory = options3.filterHistory;
  }
  get excludedFiles() {
    return !!this.c.get();
  }
  set excludedFiles(filesExclude) {
    if (this.c.get() !== filesExclude) {
      this.c.set(filesExclude);
      this.a.fire({ excludedFiles: true });
    }
  }
  get activeFile() {
    return !!this.f.get();
  }
  set activeFile(activeFile) {
    if (this.f.get() !== activeFile) {
      this.f.set(activeFile);
      this.a.fire({ activeFile: true });
    }
  }
  get showWarnings() {
    return !!this.g.get();
  }
  set showWarnings(showWarnings) {
    if (this.g.get() !== showWarnings) {
      this.g.set(showWarnings);
      this.a.fire({ showWarnings: true });
    }
  }
  get showErrors() {
    return !!this.h.get();
  }
  set showErrors(showErrors) {
    if (this.h.get() !== showErrors) {
      this.h.set(showErrors);
      this.a.fire({ showErrors: true });
    }
  }
  get showInfos() {
    return !!this.j.get();
  }
  set showInfos(showInfos) {
    if (this.j.get() !== showInfos) {
      this.j.set(showInfos);
      this.a.fire({ showInfos: true });
    }
  }
};
var $1bc = class _$1bc extends $Um {
  static {
    this.ID = "workbench.actions.problems.quickfix";
  }
  static {
    this.a = "markers-panel-action-quickfix " + ThemeIcon.asClassName($6l.lightBulb);
  }
  static {
    this.b = _$1bc.a + " autofixable";
  }
  get quickFixes() {
    return this.f;
  }
  set quickFixes(quickFixes) {
    this.f = quickFixes;
    this.enabled = this.f.length > 0;
  }
  autoFixable(autofixable) {
    this.class = autofixable ? _$1bc.b : _$1bc.a;
  }
  constructor(marker) {
    super(_$1bc.ID, $Ybc.MARKERS_PANEL_ACTION_TOOLTIP_QUICKFIX, _$1bc.a, false);
    this.marker = marker;
    this.c = this.B(new $ze());
    this.onShowQuickFixes = this.c.event;
    this.f = [];
  }
  run() {
    this.c.fire();
    return Promise.resolve();
  }
};
var $2bc = class $2bc2 extends $U1 {
  constructor(action, options3, a) {
    super(null, action, { ...options3, icon: true, label: false });
    this.a = a;
  }
  onClick(event) {
    $9j.stop(event, true);
    this.showQuickFixes();
  }
  showQuickFixes() {
    if (!this.element) {
      return;
    }
    if (!this.isEnabled()) {
      return;
    }
    const elementPosition = $vj(this.element);
    const quickFixes = this.action.quickFixes;
    if (quickFixes.length) {
      this.a.showContextMenu({
        getAnchor: () => ({ x: elementPosition.left + 10, y: elementPosition.top + elementPosition.height + 4 }),
        getActions: () => quickFixes
      });
    }
  }
};
$2bc = __decorate([
  __param(2, $50)
], $2bc);

// out-build/vs/workbench/contrib/markers/browser/markersFilterOptions.js
var $3bc = class {
  constructor(globalExpression, rootExpressions, uriIdentityService) {
    this.a = $Dl(globalExpression);
    this.b = $Wk.forUris((uri) => uriIdentityService.extUri.ignorePathCasing(uri));
    for (const expression of rootExpressions) {
      this.b.set(expression.root, { root: expression.root, expression: $Dl(expression.expression) });
    }
  }
  matches(resource) {
    const rootExpression = this.b.findSubstr(resource);
    if (rootExpression) {
      const path = $xh(rootExpression.root, resource);
      if (path && !!rootExpression.expression(path)) {
        return true;
      }
    }
    return !!this.a(resource.path);
  }
};
var $4bc = class _$4bc {
  static {
    this._filter = $Sl;
  }
  static {
    this._messageFilter = $Rl;
  }
  static EMPTY(uriIdentityService) {
    return new _$4bc("", [], false, false, false, uriIdentityService);
  }
  constructor(filter, filesExclude, showWarnings, showErrors, showInfos, uriIdentityService) {
    this.filter = filter;
    this.showWarnings = false;
    this.showErrors = false;
    this.showInfos = false;
    filter = filter.trim();
    this.showWarnings = showWarnings;
    this.showErrors = showErrors;
    this.showInfos = showInfos;
    const filesExcludeByRoot = Array.isArray(filesExclude) ? filesExclude : [];
    const excludesExpression = Array.isArray(filesExclude) ? $yl() : filesExclude;
    for (const { expression } of filesExcludeByRoot) {
      for (const pattern of Object.keys(expression)) {
        if (!pattern.endsWith("/**")) {
          expression[`${$Gf(pattern, "/")}/**`] = expression[pattern];
        }
      }
    }
    const negate = filter.startsWith("!");
    this.textFilter = { text: (negate ? $Ff(filter, "!") : filter).trim(), negate };
    const includeExpression = $yl();
    if (filter) {
      const filters2 = $Bl(filter, ",").map((s) => s.trim()).filter((s) => !!s.length);
      for (const f of filters2) {
        if (f.startsWith("!")) {
          const filterText = $Ff(f, "!");
          if (filterText) {
            this.a(excludesExpression, filterText);
          }
        } else {
          this.a(includeExpression, f);
        }
      }
    }
    this.excludesMatcher = new $3bc(excludesExpression, filesExcludeByRoot, uriIdentityService);
    this.includesMatcher = new $3bc(includeExpression, [], uriIdentityService);
  }
  a(expression, pattern) {
    if (pattern[0] === ".") {
      pattern = "*" + pattern;
    }
    expression[`**/${pattern}/**`] = true;
    expression[`**/${pattern}`] = true;
  }
};

// out-build/vs/workbench/contrib/markers/browser/markersTreeViewer.js
var $5bc = class $5bc2 {
  constructor(a) {
    this.a = a;
  }
  getWidgetAriaLabel() {
    return localize(7865, null);
  }
  getAriaLabel(element) {
    if (element instanceof $Tbc) {
      const path = this.a.getUriLabel(element.resource, { relative: true }) || element.resource.fsPath;
      return $Ybc.MARKERS_TREE_ARIA_LABEL_RESOURCE(element.markers.length, element.name, $qc(path));
    }
    if (element instanceof $Ubc || element instanceof $Vbc) {
      return $Ybc.MARKERS_TREE_ARIA_LABEL_MARKER(element);
    }
    if (element instanceof $Wbc) {
      return $Ybc.MARKERS_TREE_ARIA_LABEL_RELATED_INFORMATION(element.raw);
    }
    return null;
  }
};
$5bc = __decorate([
  __param(0, $ZI)
], $5bc);
var TemplateId;
(function(TemplateId2) {
  TemplateId2["ResourceMarkers"] = "rm";
  TemplateId2["Marker"] = "m";
  TemplateId2["RelatedInformation"] = "ri";
})(TemplateId || (TemplateId = {}));
var $6bc = class _$6bc {
  static {
    this.LINE_HEIGHT = 22;
  }
  constructor(a) {
    this.a = a;
  }
  getHeight(element) {
    if (element instanceof $Ubc) {
      const viewModel = this.a.getViewModel(element);
      const noOfLines = !viewModel || viewModel.multiline ? element.lines.length : 1;
      return noOfLines * _$6bc.LINE_HEIGHT;
    }
    return _$6bc.LINE_HEIGHT;
  }
  getTemplateId(element) {
    if (element instanceof $Tbc) {
      return "rm";
    } else if (element instanceof $Ubc) {
      return "m";
    } else {
      return "ri";
    }
  }
};
var FilterDataType2;
(function(FilterDataType3) {
  FilterDataType3[FilterDataType3["ResourceMarkers"] = 0] = "ResourceMarkers";
  FilterDataType3[FilterDataType3["Marker"] = 1] = "Marker";
  FilterDataType3[FilterDataType3["RelatedInformation"] = 2] = "RelatedInformation";
})(FilterDataType2 || (FilterDataType2 = {}));
var $7bc = class {
  constructor(d, onDidChangeRenderNodeCount) {
    this.d = d;
    this.a = /* @__PURE__ */ new Map();
    this.b = new $2c();
    this.templateId = "rm";
    onDidChangeRenderNodeCount(this.e, this, this.b);
  }
  renderTemplate(container2) {
    const resourceLabelContainer = $bk(container2, $(".resource-label-container"));
    const resourceLabel = this.d.create(resourceLabelContainer, { supportHighlights: true });
    const badgeWrapper = $bk(container2, $(".count-badge-wrapper"));
    const count = new $D2(badgeWrapper, {}, $E$);
    return { count, resourceLabel };
  }
  renderElement(node, _, templateData) {
    const resourceMarkers = node.element;
    const uriMatches = node.filterData && node.filterData.uriMatches || [];
    templateData.resourceLabel.setFile(resourceMarkers.resource, { matches: uriMatches });
    this.f(node, templateData);
    const nodeRenders = this.a.get(resourceMarkers) ?? [];
    this.a.set(resourceMarkers, [...nodeRenders, templateData]);
  }
  disposeElement(node, index, templateData) {
    const nodeRenders = this.a.get(node.element) ?? [];
    const nodeRenderIndex = nodeRenders.findIndex((nodeRender) => templateData === nodeRender);
    if (nodeRenderIndex < 0) {
      throw new Error("Disposing unknown resource marker");
    }
    if (nodeRenders.length === 1) {
      this.a.delete(node.element);
    } else {
      nodeRenders.splice(nodeRenderIndex, 1);
    }
  }
  disposeTemplate(templateData) {
    templateData.resourceLabel.dispose();
    templateData.count.dispose();
  }
  e(node) {
    const nodeRenders = this.a.get(node.element);
    if (!nodeRenders) {
      return;
    }
    nodeRenders.forEach((nodeRender) => this.f(node, nodeRender));
  }
  f(node, templateData) {
    templateData.count.setCount(node.children.reduce((r2, n) => r2 + (n.visible ? 1 : 0), 0));
  }
  dispose() {
    this.b.dispose();
  }
};
var $9bc = class $9bc2 {
  constructor(a, b, d, e) {
    this.a = a;
    this.b = b;
    this.d = d;
    this.e = e;
    this.templateId = "m";
  }
  renderTemplate(container2) {
    const data = /* @__PURE__ */ Object.create(null);
    data.markerWidget = new MarkerWidget(container2, this.a, this.b, this.e, this.d);
    return data;
  }
  renderElement(node, _, templateData) {
    templateData.markerWidget.render(node.element, node.filterData);
  }
  disposeTemplate(templateData) {
    templateData.markerWidget.dispose();
  }
};
$9bc = __decorate([
  __param(1, $5$),
  __param(2, $Pk),
  __param(3, $O4)
], $9bc);
var expandedIcon = $9r("markers-view-multi-line-expanded", $6l.chevronUp, localize(7866, null));
var collapsedIcon = $9r("markers-view-multi-line-collapsed", $6l.chevronDown, localize(7867, null));
var toggleMultilineAction = "problems.action.toggleMultiline";
var ToggleMultilineActionViewItem = class extends $U1 {
  render(container2) {
    super.render(container2);
    this.b();
  }
  I() {
    super.I();
    this.b();
  }
  b() {
    this.element?.setAttribute("aria-expanded", `${this._action.class === ThemeIcon.asClassName(expandedIcon)}`);
  }
};
var MarkerWidget = class extends $3c {
  constructor(m, s, t, u, _instantiationService) {
    super();
    this.m = m;
    this.s = s;
    this.t = t;
    this.u = u;
    this.j = this.B(new $2c());
    this.a = this.B(new $LZ($bk(m, $(".actions")), {
      actionViewItemProvider: (action, options3) => action.id === $1bc.ID ? _instantiationService.createInstance($2bc, action, options3) : void 0
    }));
    this.f = $bk(m, $(""));
    this.b = $bk(this.f, $(""));
    this.g = $bk(m, $(".marker-message-details-container"));
    this.h = this.B(this.t.setupManagedHover($JZ("mouse"), this.g, ""));
  }
  render(element, filterData) {
    this.a.clear();
    this.j.clear();
    $$i(this.g);
    this.f.className = `marker-icon ${severity_default.toString(MarkerSeverity.toSeverity(element.marker.severity))}`;
    this.b.className = `codicon ${SeverityIcon.className(MarkerSeverity.toSeverity(element.marker.severity))}`;
    this.w(element);
    this.z(element, filterData);
    this.j.add($_i(this.m, $7j.MOUSE_OVER, () => this.s.onMarkerMouseHover(element)));
    this.j.add($_i(this.m, $7j.MOUSE_LEAVE, () => this.s.onMarkerMouseLeave(element)));
  }
  w(marker) {
    const viewModel = this.s.getViewModel(marker);
    if (viewModel) {
      const quickFixAction = viewModel.quickFixAction;
      this.a.push([quickFixAction], { icon: true, label: false });
      this.f.classList.toggle("quickFix", quickFixAction.enabled);
      quickFixAction.onDidChange(({ enabled }) => {
        if (!$Ig(enabled)) {
          this.f.classList.toggle("quickFix", enabled);
        }
      }, this, this.j);
      quickFixAction.onShowQuickFixes(() => {
        const quickFixActionViewItem = this.a.viewItems[0];
        if (quickFixActionViewItem) {
          quickFixActionViewItem.showQuickFixes();
        }
      }, this, this.j);
    }
  }
  y(marker, parent) {
    const multilineActionbar = this.j.add(new $LZ($bk(parent, $(".multiline-actions")), {
      actionViewItemProvider: (action2, options3) => {
        if (action2.id === toggleMultilineAction) {
          return new ToggleMultilineActionViewItem(void 0, action2, { ...options3, icon: true });
        }
        return void 0;
      }
    }));
    this.j.add($1c(() => multilineActionbar.dispose()));
    const viewModel = this.s.getViewModel(marker);
    const multiline = viewModel && viewModel.multiline;
    const action = new $Um(toggleMultilineAction);
    action.enabled = !!viewModel && marker.lines.length > 1;
    action.tooltip = multiline ? localize(7868, null) : localize(7869, null);
    action.class = ThemeIcon.asClassName(multiline ? expandedIcon : collapsedIcon);
    action.run = () => {
      if (viewModel) {
        viewModel.multiline = !viewModel.multiline;
      }
      return Promise.resolve();
    };
    multilineActionbar.push([action], { icon: true, label: false });
  }
  z(element, filterData) {
    const { marker, lines } = element;
    const viewState = this.s.getViewModel(element);
    const multiline = !viewState || viewState.multiline;
    const lineMatches = filterData && filterData.lineMatches || [];
    this.h.update(element.marker.message);
    const lineElements = [];
    for (let index = 0; index < (multiline ? lines.length : 1); index++) {
      const lineElement = $bk(this.g, $(".marker-message-line"));
      const messageElement = $bk(lineElement, $(".marker-message"));
      const highlightedLabel = this.j.add(new $S2(messageElement));
      highlightedLabel.set(lines[index].length > 1e3 ? `${lines[index].substring(0, 1e3)}...` : lines[index], lineMatches[index]);
      if (lines[index] === "") {
        lineElement.style.height = `${$6bc.LINE_HEIGHT}px`;
      }
      lineElements.push(lineElement);
    }
    this.C(marker, filterData, lineElements[0]);
    this.y(element, lineElements[0]);
  }
  C(marker, filterData, parent) {
    parent.classList.add("details-container");
    if (marker.source || marker.code) {
      const source = this.j.add(new $S2($bk(parent, $(".marker-source"))));
      const sourceMatches = filterData && filterData.sourceMatches || [];
      source.set(marker.source, sourceMatches);
      if (marker.code) {
        if (typeof marker.code === "string") {
          const code = this.j.add(new $S2($bk(parent, $(".marker-code"))));
          const codeMatches = filterData && filterData.codeMatches || [];
          code.set(marker.code, codeMatches);
        } else {
          const container2 = $(".marker-code");
          const code = this.j.add(new $S2(container2));
          const link2 = marker.code.target.toString(true);
          this.j.add(new Link2(parent, { href: link2, label: container2, title: link2 }, void 0, this.t, this.u));
          const codeMatches = filterData && filterData.codeMatches || [];
          code.set(marker.code.value, codeMatches);
        }
      }
    }
    const lnCol = $bk(parent, $("span.marker-line"));
    lnCol.textContent = $Ybc.MARKERS_PANEL_AT_LINE_COL_NUMBER(marker.startLineNumber, marker.startColumn);
  }
};
var $0bc = class $0bc2 {
  constructor(a) {
    this.a = a;
    this.templateId = "ri";
  }
  renderTemplate(container2) {
    const data = /* @__PURE__ */ Object.create(null);
    $bk(container2, $(".actions"));
    $bk(container2, $(".icon"));
    data.resourceLabel = new $S2($bk(container2, $(".related-info-resource")));
    data.lnCol = $bk(container2, $("span.marker-line"));
    const separator = $bk(container2, $("span.related-info-resource-separator"));
    separator.textContent = ":";
    separator.style.paddingRight = "4px";
    data.description = new $S2($bk(container2, $(".marker-description")));
    return data;
  }
  renderElement(node, _, templateData) {
    const relatedInformation = node.element.raw;
    const uriMatches = node.filterData && node.filterData.uriMatches || [];
    const messageMatches = node.filterData && node.filterData.messageMatches || [];
    const resourceLabelTitle = this.a.getUriLabel(relatedInformation.resource, { relative: true });
    templateData.resourceLabel.set($sh(relatedInformation.resource), uriMatches, resourceLabelTitle);
    templateData.lnCol.textContent = $Ybc.MARKERS_PANEL_AT_LINE_COL_NUMBER(relatedInformation.startLineNumber, relatedInformation.startColumn);
    templateData.description.set(relatedInformation.message, messageMatches, relatedInformation.message);
  }
  disposeTemplate(templateData) {
    templateData.resourceLabel.dispose();
    templateData.description.dispose();
  }
};
$0bc = __decorate([
  __param(0, $ZI)
], $0bc);
var $$bc = class {
  constructor(options3) {
    this.options = options3;
  }
  filter(element, parentVisibility) {
    if (element instanceof $Tbc) {
      return this.a(element);
    } else if (element instanceof $Ubc) {
      return this.b(element, parentVisibility);
    } else {
      return this.d(element, parentVisibility);
    }
  }
  a(resourceMarkers) {
    if ($zYb.has(resourceMarkers.resource.scheme)) {
      return false;
    }
    if (this.options.excludesMatcher.matches(resourceMarkers.resource)) {
      return false;
    }
    if (this.options.includesMatcher.matches(resourceMarkers.resource)) {
      return true;
    }
    if (this.options.textFilter.text && !this.options.textFilter.negate) {
      const uriMatches = $4bc._filter(this.options.textFilter.text, $sh(resourceMarkers.resource));
      if (uriMatches) {
        return { visibility: true, data: { type: 0, uriMatches: uriMatches || [] } };
      }
    }
    return 2;
  }
  b(marker, parentVisibility) {
    const matchesSeverity = this.options.showErrors && MarkerSeverity.Error === marker.marker.severity || this.options.showWarnings && MarkerSeverity.Warning === marker.marker.severity || this.options.showInfos && MarkerSeverity.Info === marker.marker.severity;
    if (!matchesSeverity) {
      return false;
    }
    if (!this.options.textFilter.text) {
      return true;
    }
    const lineMatches = [];
    for (const line of marker.lines) {
      const lineMatch = $4bc._messageFilter(this.options.textFilter.text, line);
      lineMatches.push(lineMatch || []);
    }
    const sourceMatches = marker.marker.source ? $4bc._filter(this.options.textFilter.text, marker.marker.source) : void 0;
    const codeMatches = marker.marker.code ? $4bc._filter(this.options.textFilter.text, typeof marker.marker.code === "string" ? marker.marker.code : marker.marker.code.value) : void 0;
    const matched = sourceMatches || codeMatches || lineMatches.some((lineMatch) => lineMatch.length > 0);
    if (matched && !this.options.textFilter.negate) {
      return { visibility: true, data: { type: 1, lineMatches, sourceMatches: sourceMatches || [], codeMatches: codeMatches || [] } };
    }
    if (matched && this.options.textFilter.negate && parentVisibility === 2) {
      return false;
    }
    if (!matched && this.options.textFilter.negate && parentVisibility === 2) {
      return true;
    }
    return parentVisibility;
  }
  d(relatedInformation, parentVisibility) {
    if (!this.options.textFilter.text) {
      return true;
    }
    const uriMatches = $4bc._filter(this.options.textFilter.text, $sh(relatedInformation.raw.resource));
    const messageMatches = $4bc._messageFilter(this.options.textFilter.text, $rc(relatedInformation.raw.message));
    const matched = uriMatches || messageMatches;
    if (matched && !this.options.textFilter.negate) {
      return { visibility: true, data: { type: 2, uriMatches: uriMatches || [], messageMatches: messageMatches || [] } };
    }
    if (matched && this.options.textFilter.negate && parentVisibility === 2) {
      return false;
    }
    if (!matched && this.options.textFilter.negate && parentVisibility === 2) {
      return true;
    }
    return parentVisibility;
  }
};
var $_bc = class $_bc2 extends $3c {
  constructor(g, h3, j, m, s) {
    super();
    this.g = g;
    this.h = h3;
    this.j = j;
    this.m = m;
    this.s = s;
    this.a = this.B(new $ze());
    this.onDidChange = this.a.event;
    this.b = null;
    this.f = null;
    this.t = true;
    this.u = null;
    this.B($1c(() => {
      if (this.b) {
        this.b.cancel();
      }
      if (this.f) {
        this.f.cancel();
      }
    }));
  }
  get multiline() {
    return this.t;
  }
  set multiline(value) {
    if (this.t !== value) {
      this.t = value;
      this.a.fire();
    }
  }
  get quickFixAction() {
    if (!this.u) {
      this.u = this.B(this.j.createInstance($1bc, this.g));
    }
    return this.u;
  }
  showLightBulb() {
    this.w(true);
  }
  async w(waitForModel) {
    const codeActions = await this.y(waitForModel);
    this.quickFixAction.quickFixes = codeActions ? this.z(codeActions) : [];
    this.quickFixAction.autoFixable(!!codeActions && codeActions.hasAutoFix);
  }
  y(waitForModel) {
    if (this.f !== null) {
      return this.f;
    }
    return this.D(waitForModel).then((model) => {
      if (model) {
        if (!this.f) {
          this.f = $Hh((cancellationToken) => {
            return $Cab(this.s.codeActionProvider, model, new $9C(this.g.range.startLineNumber, this.g.range.startColumn, this.g.range.endLineNumber, this.g.range.endColumn), {
              type: 1,
              triggerAction: CodeActionTriggerSource.ProblemsView,
              filter: { include: $pab.QuickFix }
            }, $VJ.None, cancellationToken).then((actions) => {
              return this.B(actions);
            });
          });
        }
        return this.f;
      }
      return null;
    });
  }
  z(codeActions) {
    return codeActions.validActions.map((item) => new $Um(item.action.command ? item.action.command.id : item.action.title, item.action.title, void 0, true, () => {
      return this.C(this.g).then(() => this.j.invokeFunction($Dab, item, ApplyCodeActionReason.FromProblemsView));
    }));
  }
  C(element) {
    const { resource, selection } = { resource: element.resource, selection: element.range };
    return this.m.openEditor({
      resource,
      options: {
        selection,
        preserveFocus: true,
        pinned: false,
        revealIfVisible: true
      }
    }, $nJ).then(() => void 0);
  }
  D(waitForModel) {
    const model = this.h.getModel(this.g.resource);
    if (model) {
      return Promise.resolve(model);
    }
    if (waitForModel) {
      if (!this.b) {
        this.b = $Hh((cancellationToken) => {
          return new Promise((c) => {
            this.B(this.h.onModelAdded((model2) => {
              if ($oh(model2.uri, this.g.resource)) {
                c(model2);
              }
            }));
          });
        });
      }
      return this.b;
    }
    return Promise.resolve(null);
  }
};
$_bc = __decorate([
  __param(1, $sG),
  __param(2, $Pk),
  __param(3, $mJ),
  __param(4, $mP)
], $_bc);
var $acc = class $acc2 extends $3c {
  constructor(multiline = true, viewMode = "tree", t, u) {
    super();
    this.t = t;
    this.u = u;
    this.a = this.B(new $ze());
    this.onDidChange = this.a.event;
    this.b = this.B(new $ze());
    this.onDidChangeViewMode = this.b.event;
    this.f = /* @__PURE__ */ new Map();
    this.g = /* @__PURE__ */ new Map();
    this.h = false;
    this.j = null;
    this.m = new $Sh(300);
    this.w = true;
    this.y = "tree";
    this.w = multiline;
    this.y = viewMode;
    this.s = MarkersContextKeys.MarkersViewModeContextKey.bindTo(this.t);
    this.s.set(viewMode);
  }
  add(marker) {
    if (!this.f.has(marker.id)) {
      const viewModel = this.u.createInstance($_bc, marker);
      const disposables = [viewModel];
      viewModel.multiline = this.multiline;
      viewModel.onDidChange(() => {
        if (!this.h) {
          this.a.fire(marker);
        }
      }, this, disposables);
      this.f.set(marker.id, { viewModel, disposables });
      const markers = this.g.get(marker.resource.toString()) || [];
      markers.push(marker);
      this.g.set(marker.resource.toString(), markers);
    }
  }
  remove(resource) {
    const markers = this.g.get(resource.toString()) || [];
    for (const marker of markers) {
      const value = this.f.get(marker.id);
      if (value) {
        $Xc(value.disposables);
      }
      this.f.delete(marker.id);
      if (this.j === marker) {
        this.j = null;
      }
    }
    this.g.delete(resource.toString());
  }
  getViewModel(marker) {
    const value = this.f.get(marker.id);
    return value ? value.viewModel : null;
  }
  onMarkerMouseHover(marker) {
    this.j = marker;
    this.m.trigger(() => {
      if (this.j) {
        const model = this.getViewModel(this.j);
        if (model) {
          model.showLightBulb();
        }
      }
    });
  }
  onMarkerMouseLeave(marker) {
    if (this.j === marker) {
      this.j = null;
    }
  }
  get multiline() {
    return this.w;
  }
  set multiline(value) {
    let changed = false;
    if (this.w !== value) {
      this.w = value;
      changed = true;
    }
    this.h = true;
    this.f.forEach(({ viewModel }) => {
      if (viewModel.multiline !== value) {
        viewModel.multiline = value;
        changed = true;
      }
    });
    this.h = false;
    if (changed) {
      this.a.fire(void 0);
    }
  }
  get viewMode() {
    return this.y;
  }
  set viewMode(value) {
    if (this.y === value) {
      return;
    }
    this.y = value;
    this.b.fire(value);
    this.s.set(value);
  }
  dispose() {
    this.f.forEach(({ disposables }) => $Xc(disposables));
    this.f.clear();
    this.g.clear();
    super.dispose();
  }
};
$acc = __decorate([
  __param(2, $on),
  __param(3, $Pk)
], $acc);

// out-build/vs/workbench/contrib/markers/browser/markersTable.js
var MarkerSeverityColumnRenderer_1;
var MarkerCodeColumnRenderer_1;
var MarkerFileColumnRenderer_1;
var $143 = $;
var MarkerSeverityColumnRenderer = class MarkerSeverityColumnRenderer2 {
  static {
    MarkerSeverityColumnRenderer_1 = this;
  }
  static {
    this.TEMPLATE_ID = "severity";
  }
  constructor(c, d) {
    this.c = c;
    this.d = d;
    this.templateId = MarkerSeverityColumnRenderer_1.TEMPLATE_ID;
  }
  renderTemplate(container2) {
    const severityColumn = $bk(container2, $143(".severity"));
    const icon2 = $bk(severityColumn, $143(""));
    const actionBarColumn = $bk(container2, $143(".actions"));
    const actionBar = new $LZ(actionBarColumn, {
      actionViewItemProvider: (action, options3) => action.id === $1bc.ID ? this.d.createInstance($2bc, action, options3) : void 0
    });
    return { actionBar, icon: icon2 };
  }
  renderElement(element, index, templateData, height) {
    const toggleQuickFix = (enabled) => {
      if (!$Ig(enabled)) {
        const container2 = $Gj(templateData.icon, "monaco-table-td");
        container2.classList.toggle("quickFix", enabled);
      }
    };
    templateData.icon.title = MarkerSeverity.toString(element.marker.severity);
    templateData.icon.className = `marker-icon ${severity_default.toString(MarkerSeverity.toSeverity(element.marker.severity))} codicon ${SeverityIcon.className(MarkerSeverity.toSeverity(element.marker.severity))}`;
    templateData.actionBar.clear();
    const viewModel = this.c.getViewModel(element);
    if (viewModel) {
      const quickFixAction = viewModel.quickFixAction;
      templateData.actionBar.push([quickFixAction], { icon: true, label: false });
      toggleQuickFix(viewModel.quickFixAction.enabled);
      quickFixAction.onDidChange(({ enabled }) => toggleQuickFix(enabled));
      quickFixAction.onShowQuickFixes(() => {
        const quickFixActionViewItem = templateData.actionBar.viewItems[0];
        if (quickFixActionViewItem) {
          quickFixActionViewItem.showQuickFixes();
        }
      });
    }
  }
  disposeTemplate(templateData) {
  }
};
MarkerSeverityColumnRenderer = MarkerSeverityColumnRenderer_1 = __decorate([
  __param(1, $Pk)
], MarkerSeverityColumnRenderer);
var MarkerCodeColumnRenderer = class MarkerCodeColumnRenderer2 {
  static {
    MarkerCodeColumnRenderer_1 = this;
  }
  static {
    this.TEMPLATE_ID = "code";
  }
  constructor(c, d) {
    this.c = c;
    this.d = d;
    this.templateId = MarkerCodeColumnRenderer_1.TEMPLATE_ID;
  }
  renderTemplate(container2) {
    const templateDisposable = new $2c();
    const codeColumn = $bk(container2, $143(".code"));
    const sourceLabel = templateDisposable.add(new $S2(codeColumn));
    sourceLabel.element.classList.add("source-label");
    const codeLabel = templateDisposable.add(new $S2(codeColumn));
    codeLabel.element.classList.add("code-label");
    const codeLink = templateDisposable.add(new Link2(codeColumn, { href: "", label: "" }, {}, this.c, this.d));
    return { codeColumn, sourceLabel, codeLabel, codeLink, templateDisposable };
  }
  renderElement(element, index, templateData, height) {
    templateData.codeColumn.classList.remove("code-label");
    templateData.codeColumn.classList.remove("code-link");
    if (element.marker.source && element.marker.code) {
      if (typeof element.marker.code === "string") {
        templateData.codeColumn.classList.add("code-label");
        templateData.codeColumn.title = `${element.marker.source} (${element.marker.code})`;
        templateData.sourceLabel.set(element.marker.source, element.sourceMatches);
        templateData.codeLabel.set(element.marker.code, element.codeMatches);
      } else {
        templateData.codeColumn.classList.add("code-link");
        templateData.codeColumn.title = `${element.marker.source} (${element.marker.code.value})`;
        templateData.sourceLabel.set(element.marker.source, element.sourceMatches);
        const codeLinkLabel = templateData.templateDisposable.add(new $S2($143(".code-link-label")));
        codeLinkLabel.set(element.marker.code.value, element.codeMatches);
        templateData.codeLink.link = {
          href: element.marker.code.target.toString(true),
          title: element.marker.code.target.toString(true),
          label: codeLinkLabel.element
        };
      }
    } else {
      templateData.codeColumn.title = "";
      templateData.sourceLabel.set("-");
    }
  }
  disposeTemplate(templateData) {
    templateData.templateDisposable.dispose();
  }
};
MarkerCodeColumnRenderer = MarkerCodeColumnRenderer_1 = __decorate([
  __param(0, $5$),
  __param(1, $O4)
], MarkerCodeColumnRenderer);
var MarkerMessageColumnRenderer = class _MarkerMessageColumnRenderer {
  constructor() {
    this.templateId = _MarkerMessageColumnRenderer.TEMPLATE_ID;
  }
  static {
    this.TEMPLATE_ID = "message";
  }
  renderTemplate(container2) {
    const columnElement = $bk(container2, $143(".message"));
    const highlightedLabel = new $S2(columnElement);
    return { columnElement, highlightedLabel };
  }
  renderElement(element, index, templateData, height) {
    templateData.columnElement.title = element.marker.message;
    templateData.highlightedLabel.set(element.marker.message, element.messageMatches);
  }
  disposeTemplate(templateData) {
    templateData.highlightedLabel.dispose();
  }
};
var MarkerFileColumnRenderer = class MarkerFileColumnRenderer2 {
  static {
    MarkerFileColumnRenderer_1 = this;
  }
  static {
    this.TEMPLATE_ID = "file";
  }
  constructor(c) {
    this.c = c;
    this.templateId = MarkerFileColumnRenderer_1.TEMPLATE_ID;
  }
  renderTemplate(container2) {
    const columnElement = $bk(container2, $143(".file"));
    const fileLabel = new $S2(columnElement);
    fileLabel.element.classList.add("file-label");
    const positionLabel = new $S2(columnElement);
    positionLabel.element.classList.add("file-position");
    return { columnElement, fileLabel, positionLabel };
  }
  renderElement(element, index, templateData, height) {
    const positionLabel = $Ybc.MARKERS_PANEL_AT_LINE_COL_NUMBER(element.marker.startLineNumber, element.marker.startColumn);
    templateData.columnElement.title = `${this.c.getUriLabel(element.marker.resource, { relative: false })} ${positionLabel}`;
    templateData.fileLabel.set(this.c.getUriLabel(element.marker.resource, { relative: true }), element.fileMatches);
    templateData.positionLabel.set(positionLabel, void 0);
  }
  disposeTemplate(templateData) {
    templateData.fileLabel.dispose();
    templateData.positionLabel.dispose();
  }
};
MarkerFileColumnRenderer = MarkerFileColumnRenderer_1 = __decorate([
  __param(0, $ZI)
], MarkerFileColumnRenderer);
var MarkerOwnerColumnRenderer = class _MarkerOwnerColumnRenderer {
  constructor() {
    this.templateId = _MarkerOwnerColumnRenderer.TEMPLATE_ID;
  }
  static {
    this.TEMPLATE_ID = "owner";
  }
  renderTemplate(container2) {
    const columnElement = $bk(container2, $143(".owner"));
    const highlightedLabel = new $S2(columnElement);
    return { columnElement, highlightedLabel };
  }
  renderElement(element, index, templateData, height) {
    templateData.columnElement.title = element.marker.owner;
    templateData.highlightedLabel.set(element.marker.owner, element.ownerMatches);
  }
  disposeTemplate(templateData) {
    templateData.highlightedLabel.dispose();
  }
};
var MarkersTableVirtualDelegate = class _MarkersTableVirtualDelegate {
  constructor() {
    this.headerRowHeight = _MarkersTableVirtualDelegate.HEADER_ROW_HEIGHT;
  }
  static {
    this.HEADER_ROW_HEIGHT = 24;
  }
  static {
    this.ROW_HEIGHT = 24;
  }
  getHeight(item) {
    return _MarkersTableVirtualDelegate.ROW_HEIGHT;
  }
};
var $bcc = class $bcc2 extends $3c {
  constructor(h3, j, n, r2, options3, s, t) {
    super();
    this.h = h3;
    this.j = j;
    this.n = n;
    this.r = r2;
    this.s = s;
    this.t = t;
    this.c = 0;
    this.g = this.s.createInstance($Yeb, "Markers", this.h, new MarkersTableVirtualDelegate(), [
      {
        label: "",
        tooltip: "",
        weight: 0,
        minimumWidth: 36,
        maximumWidth: 36,
        templateId: MarkerSeverityColumnRenderer.TEMPLATE_ID,
        project(row) {
          return row;
        }
      },
      {
        label: localize(7861, null),
        tooltip: "",
        weight: 1,
        minimumWidth: 100,
        maximumWidth: 300,
        templateId: MarkerCodeColumnRenderer.TEMPLATE_ID,
        project(row) {
          return row;
        }
      },
      {
        label: localize(7862, null),
        tooltip: "",
        weight: 4,
        templateId: MarkerMessageColumnRenderer.TEMPLATE_ID,
        project(row) {
          return row;
        }
      },
      {
        label: localize(7863, null),
        tooltip: "",
        weight: 2,
        templateId: MarkerFileColumnRenderer.TEMPLATE_ID,
        project(row) {
          return row;
        }
      },
      {
        label: localize(7864, null),
        tooltip: "",
        weight: 1,
        minimumWidth: 100,
        maximumWidth: 300,
        templateId: MarkerOwnerColumnRenderer.TEMPLATE_ID,
        project(row) {
          return row;
        }
      }
    ], [
      this.s.createInstance(MarkerSeverityColumnRenderer, this.j),
      this.s.createInstance(MarkerCodeColumnRenderer),
      this.s.createInstance(MarkerMessageColumnRenderer),
      this.s.createInstance(MarkerFileColumnRenderer),
      this.s.createInstance(MarkerOwnerColumnRenderer)
    ], options3);
    const list2 = this.g.domNode.querySelector(".monaco-list-rows");
    const onRowHover = Event2.chain(this.B(new $9Z(list2, "mouseover")).event, ($149) => $149.map((e) => $Gj(e.target, "monaco-list-row", "monaco-list-rows")).filter((e) => !!e).map((e) => parseInt(e.getAttribute("data-index"))));
    const onListLeave = Event2.map(this.B(new $9Z(list2, "mouseleave")).event, () => -1);
    const onRowHoverOrLeave = Event2.latch(Event2.any(onRowHover, onListLeave));
    const onRowPermanentHover = Event2.debounce(onRowHoverOrLeave, (_, e) => e, 500);
    this.B(onRowPermanentHover((e) => {
      if (e !== -1 && this.g.row(e)) {
        this.j.onMarkerMouseHover(this.g.row(e));
      }
    }));
  }
  get contextKeyService() {
    return this.g.contextKeyService;
  }
  get onContextMenu() {
    return this.g.onContextMenu;
  }
  get onDidOpen() {
    return this.g.onDidOpen;
  }
  get onDidChangeFocus() {
    return this.g.onDidChangeFocus;
  }
  get onDidChangeSelection() {
    return this.g.onDidChangeSelection;
  }
  collapseMarkers() {
  }
  domFocus() {
    this.g.domFocus();
  }
  filterMarkers(resourceMarkers, filterOptions) {
    this.r = filterOptions;
    this.reset(resourceMarkers);
  }
  getFocus() {
    const focus = this.g.getFocus();
    return focus.length > 0 ? [...focus.map((f) => this.g.row(f))] : [];
  }
  getHTMLElement() {
    return this.g.getHTMLElement();
  }
  getRelativeTop(marker) {
    return marker ? this.g.getRelativeTop(this.g.indexOf(marker)) : null;
  }
  getSelection() {
    const selection = this.g.getSelection();
    return selection.length > 0 ? [...selection.map((i2) => this.g.row(i2))] : [];
  }
  getVisibleItemCount() {
    return this.c;
  }
  isVisible() {
    return !this.h.classList.contains("hidden");
  }
  layout(height, width2) {
    this.h.style.height = `${height}px`;
    this.g.layout(height, width2);
  }
  reset(resourceMarkers) {
    this.n = resourceMarkers;
    const items = [];
    for (const resourceMarker of this.n) {
      for (const marker of resourceMarker.markers) {
        if ($zYb.has(marker.resource.scheme)) {
          continue;
        }
        if (this.r.excludesMatcher.matches(marker.resource)) {
          continue;
        }
        if (this.r.includesMatcher.matches(marker.resource)) {
          items.push(new $Vbc(marker));
          continue;
        }
        const matchesSeverity = this.r.showErrors && MarkerSeverity.Error === marker.marker.severity || this.r.showWarnings && MarkerSeverity.Warning === marker.marker.severity || this.r.showInfos && MarkerSeverity.Info === marker.marker.severity;
        if (!matchesSeverity) {
          continue;
        }
        if (this.r.textFilter.text) {
          const sourceMatches = marker.marker.source ? $4bc._filter(this.r.textFilter.text, marker.marker.source) ?? void 0 : void 0;
          const codeMatches = marker.marker.code ? $4bc._filter(this.r.textFilter.text, typeof marker.marker.code === "string" ? marker.marker.code : marker.marker.code.value) ?? void 0 : void 0;
          const messageMatches = $4bc._messageFilter(this.r.textFilter.text, marker.marker.message) ?? void 0;
          const fileMatches = $4bc._messageFilter(this.r.textFilter.text, this.t.getUriLabel(marker.resource, { relative: true })) ?? void 0;
          const ownerMatches = $4bc._messageFilter(this.r.textFilter.text, marker.marker.owner) ?? void 0;
          const matched = sourceMatches || codeMatches || messageMatches || fileMatches || ownerMatches;
          if (matched && !this.r.textFilter.negate || !matched && this.r.textFilter.negate) {
            items.push(new $Vbc(marker, sourceMatches, codeMatches, messageMatches, fileMatches, ownerMatches));
          }
          continue;
        }
        items.push(new $Vbc(marker));
      }
    }
    this.c = items.length;
    this.g.splice(0, Number.POSITIVE_INFINITY, items.sort((a, b) => {
      let result = MarkerSeverity.compare(a.marker.severity, b.marker.severity);
      if (result === 0) {
        result = $Sbc(a.marker, b.marker);
      }
      if (result === 0) {
        result = $9C.compareRangesUsingStarts(a.marker, b.marker);
      }
      return result;
    }));
  }
  revealMarkers(activeResource, focus, lastSelectedRelativeTop) {
    if (activeResource) {
      const activeResourceIndex = this.n.indexOf(activeResource);
      if (activeResourceIndex !== -1) {
        if (this.w(activeResource)) {
          const tableSelection = this.g.getSelection();
          this.g.reveal(tableSelection[0], lastSelectedRelativeTop);
          if (focus) {
            this.g.setFocus(tableSelection);
          }
        } else {
          this.g.reveal(activeResourceIndex, 0);
          if (focus) {
            this.g.setFocus([activeResourceIndex]);
            this.g.setSelection([activeResourceIndex]);
          }
        }
      }
    } else if (focus) {
      this.g.setSelection([]);
      this.g.focusFirst();
    }
  }
  setAriaLabel(label3) {
    this.g.domNode.ariaLabel = label3;
  }
  setMarkerSelection(selection, focus) {
    if (this.isVisible()) {
      if (selection && selection.length > 0) {
        this.g.setSelection(selection.map((m) => this.u(m)));
        if (focus && focus.length > 0) {
          this.g.setFocus(focus.map((f) => this.u(f)));
        } else {
          this.g.setFocus([this.u(selection[0])]);
        }
        this.g.reveal(this.u(selection[0]));
      } else if (this.getSelection().length === 0 && this.getVisibleItemCount() > 0) {
        this.g.setSelection([0]);
        this.g.setFocus([0]);
        this.g.reveal(0);
      }
    }
  }
  toggleVisibility(hide3) {
    this.h.classList.toggle("hidden", hide3);
  }
  update(resourceMarkers) {
    for (const resourceMarker of resourceMarkers) {
      const index = this.n.indexOf(resourceMarker);
      this.n.splice(index, 1, resourceMarker);
    }
    this.reset(this.n);
  }
  updateMarker(marker) {
    this.g.rerender();
  }
  u(marker) {
    for (let index = 0; index < this.g.length; index++) {
      if (this.g.row(index).marker === marker.marker) {
        return index;
      }
    }
    return -1;
  }
  w(resource) {
    const selectedElement = this.getSelection();
    if (selectedElement && selectedElement.length > 0) {
      if (selectedElement[0] instanceof $Ubc) {
        if (resource.has(selectedElement[0].marker.resource)) {
          return true;
        }
      }
    }
    return false;
  }
};
$bcc = __decorate([
  __param(5, $Pk),
  __param(6, $ZI)
], $bcc);

// out-build/vs/workbench/contrib/markers/browser/markersView.js
function createResourceMarkersIterator(resourceMarkers) {
  return Iterable.map(resourceMarkers.markers, (m) => {
    const relatedInformationIt = Iterable.from(m.relatedInformation);
    const children = Iterable.map(relatedInformationIt, (r2) => ({ element: r2 }));
    return { element: m, children };
  });
}
var $ccc = class $ccc2 extends $apb {
  constructor(options3, instantiationService, viewDescriptorService, nc, configurationService, telemetryService, oc, contextKeyService, pc, contextMenuService, qc, keybindingService, storageService, openerService, themeService, hoverService) {
    const memento = new $Slb(Markers.MARKERS_VIEW_STORAGE_ID, storageService);
    const panelState = memento.getMemento(
      1,
      1
      /* StorageTarget.MACHINE */
    );
    super({
      ...options3,
      filterOptions: {
        ariaLabel: $Ybc.MARKERS_PANEL_FILTER_ARIA_LABEL,
        placeholder: $Ybc.MARKERS_PANEL_FILTER_PLACEHOLDER,
        focusContextKey: MarkersContextKeys.MarkerViewFilterFocusContextKey.key,
        text: panelState["filter"] || "",
        history: panelState["filterHistory"] || []
      }
    }, keybindingService, contextMenuService, configurationService, contextKeyService, viewDescriptorService, instantiationService, openerService, themeService, telemetryService, hoverService);
    this.nc = nc;
    this.oc = oc;
    this.pc = pc;
    this.qc = qc;
    this.a = 0;
    this.b = null;
    this.ab = this.B(new $2c());
    this.ac = this.B(new $2c());
    this.gc = 0;
    this.hc = 0;
    this.kc = void 0;
    this.lc = false;
    this.onDidChangeVisibility = this.onDidChangeBodyVisibility;
    this.ic = memento;
    this.jc = panelState;
    this.h = this.B(instantiationService.createInstance($Xbc));
    this.mc = this.B(instantiationService.createInstance($acc, this.jc["multiline"], this.jc["viewMode"] ?? this.xc()));
    this.B(this.onDidChangeVisibility((visible) => this.Gc(visible)));
    this.B(this.mc.onDidChangeViewMode((_) => this.Jc()));
    this.dc = instantiationService.createInstance($5bc);
    this.cc = { getId(element) {
      return element.id;
    } };
    this.Mc();
    this.s = new $$bc($4bc.EMPTY(qc));
    this.c = this.B(this.Db.createInstance($BLb));
    this.filters = this.B(new $Zbc({
      filterHistory: this.jc["filterHistory"] || [],
      showErrors: this.jc["showErrors"] !== false,
      showWarnings: this.jc["showWarnings"] !== false,
      showInfos: this.jc["showInfos"] !== false,
      excludedFiles: !!this.jc["useFilesExclude"],
      activeFile: !!this.jc["activeFile"]
    }, this.Bb));
    this.B(this.Ab.onDidChangeConfiguration((e) => {
      if (this.filters.excludedFiles && e.affectsConfiguration("files.exclude")) {
        this.wc();
      }
    }));
  }
  render() {
    super.render();
    this.B($iKb({
      name: "markersView",
      focusNotifiers: [this, this.filterWidget],
      focusNextWidget: () => {
        if (this.filterWidget.hasFocus()) {
          this.focus();
        }
      },
      focusPreviousWidget: () => {
        if (!this.filterWidget.hasFocus()) {
          this.focusFilter();
        }
      }
    }));
  }
  W(parent) {
    super.W(parent);
    parent.classList.add("markers-panel");
    this.B($_i(parent, "keydown", (e) => {
      const event = new $if(e);
      if (!this.yb.mightProducePrintableCharacter(event)) {
        return;
      }
      const result = this.yb.softDispatch(event, event.target);
      if (result.kind === 1 || result.kind === 2) {
        return;
      }
      this.focusFilter();
    }));
    const panelContainer = $bk(parent, $(".markers-panel-container"));
    this.Cc(panelContainer);
    this.Bc(panelContainer);
    this.bc = $bk(panelContainer, $(".widget-container"));
    this.Dc(this.bc);
    this.wc();
    this.Pc();
  }
  getTitle() {
    return $Ybc.MARKERS_PANEL_TITLE_PROBLEMS.value;
  }
  L(height = this.gc, width2 = this.hc) {
    if (this.ec) {
      this.ec.style.height = `${height}px`;
    }
    this.sb.layout(height, width2);
    this.gc = height;
    this.hc = width2;
  }
  focus() {
    super.focus();
    if ($Mj(this.sb.getHTMLElement())) {
      return;
    }
    if (this.Oc()) {
      this.ec.focus();
    } else {
      this.sb.domFocus();
      this.sb.setMarkerSelection();
    }
  }
  focusFilter() {
    this.filterWidget.focus();
  }
  updateBadge(total, filtered) {
    this.filterWidget.updateBadge(total === filtered || total === 0 ? void 0 : localize(7870, null, filtered, total));
  }
  checkMoreFilters() {
    this.filterWidget.checkMoreFilters(!this.filters.showErrors || !this.filters.showWarnings || !this.filters.showInfos || this.filters.excludedFiles || this.filters.activeFile);
  }
  clearFilterText() {
    this.filterWidget.setFilterText("");
  }
  showQuickFixes(marker) {
    const viewModel = this.mc.getViewModel(marker);
    if (viewModel) {
      viewModel.quickFixAction.run();
    }
  }
  openFileAtElement(element, preserveFocus, sideByside, pinned) {
    const { resource, selection } = element instanceof $Ubc ? { resource: element.resource, selection: element.range } : element instanceof $Wbc ? { resource: element.raw.resource, selection: element.raw } : "marker" in element ? { resource: element.marker.resource, selection: element.marker.range } : { resource: null, selection: null };
    if (resource && selection) {
      this.nc.openEditor({
        resource,
        options: {
          selection,
          preserveFocus,
          pinned,
          revealIfVisible: true
        }
      }, sideByside ? $oJ : $nJ).then((editor) => {
        if (editor && preserveFocus) {
          this.c.highlightRange({ resource, range: selection }, editor.getControl());
        } else {
          this.c.removeHighlightRange();
        }
      });
      return true;
    } else {
      this.c.removeHighlightRange();
    }
    return false;
  }
  tc(markerOrChange) {
    if (this.isVisible()) {
      const hasSelection = this.sb.getSelection().length > 0;
      if (markerOrChange) {
        if (markerOrChange instanceof $Ubc) {
          this.sb.updateMarker(markerOrChange);
        } else {
          if (markerOrChange.added.size || markerOrChange.removed.size) {
            this.vc();
          } else {
            this.sb.update([...markerOrChange.updated]);
          }
        }
      } else {
        this.vc();
      }
      if (hasSelection) {
        this.sb.setMarkerSelection();
      }
      this.kc = void 0;
      const { total, filtered } = this.getFilterStats();
      this.cd(total === 0 || filtered === 0);
      this.Qc();
      this.updateBadge(total, filtered);
      this.checkMoreFilters();
    }
  }
  uc(marker) {
    this.tc(marker);
  }
  vc() {
    this.sb.reset(this.Ac());
  }
  wc() {
    this.s.options = new $4bc(this.filterWidget.getFilterText(), this.yc(), this.filters.showWarnings, this.filters.showErrors, this.filters.showInfos, this.qc);
    this.sb.filterMarkers(this.Ac(), this.s.options);
    this.kc = void 0;
    const { total, filtered } = this.getFilterStats();
    this.cd(total === 0 || filtered === 0);
    this.Qc();
    this.updateBadge(total, filtered);
    this.checkMoreFilters();
  }
  xc() {
    switch (this.Ab.getValue("problems.defaultViewMode")) {
      case "table":
        return "table";
      case "tree":
        return "tree";
      default:
        return "tree";
    }
  }
  yc() {
    if (!this.filters.excludedFiles) {
      return [];
    }
    const workspaceFolders = this.pc.getWorkspace().folders;
    return workspaceFolders.length ? workspaceFolders.map((workspaceFolder) => ({ root: workspaceFolder.uri, expression: this.zc(workspaceFolder.uri) })) : this.zc();
  }
  zc(resource) {
    return $Lv(this.Ab.getValue("files.exclude", { resource })) || {};
  }
  Ac() {
    if (!this.filters.activeFile) {
      return this.h.resourceMarkers;
    }
    let resourceMarkers = [];
    if (this.b) {
      const activeResourceMarkers = this.h.getResourceMarkers(this.b);
      if (activeResourceMarkers) {
        resourceMarkers = [activeResourceMarkers];
      }
    }
    return resourceMarkers;
  }
  Bc(parent) {
    this.ec = $bk(parent, $(".message-box-container"));
    this.ec.setAttribute("aria-labelledby", "markers-panel-arialabel");
  }
  Cc(parent) {
    this.fc = $bk(parent, $(""));
    this.fc.setAttribute("id", "markers-panel-arialabel");
  }
  Dc(parent) {
    this.sb = this.mc.viewMode === "table" ? this.Ec(parent) : this.Fc(parent);
    this.ac.add(this.sb);
    const markerFocusContextKey = MarkersContextKeys.MarkerFocusContextKey.bindTo(this.sb.contextKeyService);
    const relatedInformationFocusContextKey = MarkersContextKeys.RelatedInformationFocusContextKey.bindTo(this.sb.contextKeyService);
    this.ac.add(this.sb.onDidChangeFocus((focus) => {
      markerFocusContextKey.set(focus.elements.some((e) => e instanceof $Ubc));
      relatedInformationFocusContextKey.set(focus.elements.some((e) => e instanceof $Wbc));
    }));
    this.ac.add(Event2.debounce(this.sb.onDidOpen, (last, event) => event, 75, true)((options3) => {
      this.openFileAtElement(options3.element, !!options3.editorOptions.preserveFocus, options3.sideBySide, !!options3.editorOptions.pinned);
    }));
    this.ac.add(Event2.any(this.sb.onDidChangeSelection, this.sb.onDidChangeFocus)(() => {
      const elements = [...this.sb.getSelection(), ...this.sb.getFocus()];
      for (const element of elements) {
        if (element instanceof $Ubc) {
          const viewModel = this.mc.getViewModel(element);
          viewModel?.showLightBulb();
        }
      }
    }));
    this.ac.add(this.sb.onContextMenu(this.ad, this));
    this.ac.add(this.sb.onDidChangeSelection(this.Nc, this));
  }
  Ec(parent) {
    const table = this.Db.createInstance($bcc, $bk(parent, $(".markers-table-container")), this.mc, this.Ac(), this.s.options, {
      accessibilityProvider: this.dc,
      dnd: this.Db.createInstance($Kob, (element) => {
        if (element instanceof $Vbc) {
          return $P4(element.resource, element.range);
        }
        return null;
      }),
      horizontalScrolling: false,
      identityProvider: this.cc,
      multipleSelectionSupport: true,
      selectionNavigation: true
    });
    return table;
  }
  Fc(parent) {
    const onDidChangeRenderNodeCount = new $Ie();
    const treeLabels = this.Db.createInstance($lsb, this);
    const virtualDelegate = new $6bc(this.mc);
    const renderers = [
      this.Db.createInstance($7bc, treeLabels, onDidChangeRenderNodeCount.event),
      this.Db.createInstance($9bc, this.mc),
      this.Db.createInstance($0bc)
    ];
    const tree = this.Db.createInstance(MarkersTree, "MarkersView", $bk(parent, $(".tree-container.show-file-icons")), virtualDelegate, renderers, {
      filter: this.s,
      accessibilityProvider: this.dc,
      identityProvider: this.cc,
      dnd: this.Db.createInstance($Kob, (element) => {
        if (element instanceof $Tbc) {
          return element.resource;
        }
        if (element instanceof $Ubc) {
          return $P4(element.resource, element.range);
        }
        if (element instanceof $Wbc) {
          return $P4(element.raw.resource, element.raw);
        }
        return null;
      }),
      expandOnlyOnTwistieClick: (e) => e instanceof $Ubc && e.relatedInformation.length > 0,
      overrideStyles: this.Xb().listOverrideStyles,
      selectionNavigation: true,
      multipleSelectionSupport: true
    });
    onDidChangeRenderNodeCount.input = tree.onDidChangeRenderNodeCount;
    return tree;
  }
  collapseAll() {
    this.sb.collapseMarkers();
  }
  setMultiline(multiline) {
    this.mc.multiline = multiline;
  }
  setViewMode(viewMode) {
    this.mc.viewMode = viewMode;
  }
  Gc(visible) {
    this.ab.clear();
    if (visible) {
      for (const disposable of this.Hc()) {
        this.ab.add(disposable);
      }
      this.tc();
    }
  }
  Hc() {
    const disposables = [];
    const readMarkers = (resource) => this.oc.read({ resource, severities: MarkerSeverity.Error | MarkerSeverity.Warning | MarkerSeverity.Info });
    this.h.setResourceMarkers($Eb(readMarkers(), $Sbc).map((group2) => [group2[0].resource, group2]));
    disposables.push(Event2.debounce(this.oc.onMarkerChanged, (resourcesMap, resources) => {
      resourcesMap = resourcesMap || new $Ec();
      resources.forEach((resource) => resourcesMap.set(resource, resource));
      return resourcesMap;
    }, 64)((resourcesMap) => {
      this.h.setResourceMarkers([...resourcesMap.values()].map((resource) => [resource, readMarkers(resource)]));
    }));
    disposables.push(Event2.any(this.h.onDidChange, this.nc.onDidActiveEditorChange)((changes) => {
      if (changes) {
        this.Ic(changes);
      } else {
        this.Lc();
      }
    }));
    disposables.push($1c(() => this.h.reset()));
    this.h.resourceMarkers.forEach((resourceMarker) => resourceMarker.markers.forEach((marker) => this.mc.add(marker)));
    disposables.push(this.mc.onDidChange((marker) => this.uc(marker)));
    disposables.push($1c(() => this.h.resourceMarkers.forEach((resourceMarker) => this.mc.remove(resourceMarker.resource))));
    disposables.push(this.filters.onDidChange((event) => {
      if (event.activeFile) {
        this.tc();
      } else if (event.excludedFiles || event.showWarnings || event.showErrors || event.showInfos) {
        this.wc();
      }
    }));
    disposables.push(this.filterWidget.onDidChangeFilterText((e) => this.wc()));
    disposables.push($1c(() => {
      this.kc = void 0;
    }));
    disposables.push($1c(() => this.c.removeHighlightRange()));
    return disposables;
  }
  Ic(change) {
    const resourceMarkers = [...change.added, ...change.removed, ...change.updated];
    const resources = [];
    for (const { resource } of resourceMarkers) {
      this.mc.remove(resource);
      const resourceMarkers2 = this.h.getResourceMarkers(resource);
      if (resourceMarkers2) {
        for (const marker of resourceMarkers2.markers) {
          this.mc.add(marker);
        }
      }
      resources.push(resource);
    }
    this.lc = this.lc || this.Kc(resources);
    this.tc(change);
    this.Zc();
    if (this.lc) {
      this.Xc();
      this.lc = false;
    }
  }
  Jc() {
    if (this.bc && this.sb) {
      this.bc.textContent = "";
      this.ac.clear();
    }
    const selection = /* @__PURE__ */ new Set();
    for (const marker of this.sb.getSelection()) {
      if (marker instanceof $Tbc) {
        marker.markers.forEach((m) => selection.add(m));
      } else if (marker instanceof $Ubc || marker instanceof $Vbc) {
        selection.add(marker);
      }
    }
    const focus = /* @__PURE__ */ new Set();
    for (const marker of this.sb.getFocus()) {
      if (marker instanceof $Ubc || marker instanceof $Vbc) {
        focus.add(marker);
      }
    }
    this.Dc(this.bc);
    this.tc();
    if (selection.size > 0) {
      this.sb.setMarkerSelection(Array.from(selection), Array.from(focus));
      this.sb.domFocus();
    }
  }
  Kc(changedResources) {
    const currentlyActiveResource = this.b;
    if (!currentlyActiveResource) {
      return false;
    }
    const resourceForCurrentActiveResource = this.Yc();
    if (resourceForCurrentActiveResource) {
      return false;
    }
    return changedResources.some((r2) => r2.toString() === currentlyActiveResource.toString());
  }
  Lc() {
    this.Mc();
    if (this.filters.activeFile) {
      this.tc();
    }
    this.Xc();
  }
  Mc() {
    const activeEditor = this.nc.activeEditor;
    this.b = activeEditor ? $mL.getOriginalUri(activeEditor, { supportSideBySide: SideBySideEditor.PRIMARY }) ?? null : null;
  }
  Nc() {
    const selection = this.sb.getSelection();
    if (selection && selection.length > 0) {
      this.a = this.sb.getRelativeTop(selection[0]) || 0;
    }
  }
  Oc() {
    const { total, filtered } = this.getFilterStats();
    return total === 0 || filtered === 0;
  }
  Pc() {
    this.kc = void 0;
    this.vc();
    this.cd(this.Oc());
    this.Qc();
  }
  Qc() {
    if (!this.ec || !this.fc) {
      return;
    }
    $$i(this.ec);
    const { total, filtered } = this.getFilterStats();
    if (filtered === 0) {
      this.ec.style.display = "block";
      this.ec.setAttribute("tabIndex", "0");
      if (this.filters.activeFile) {
        this.Rc(this.ec);
      } else {
        if (total > 0) {
          this.Sc(this.ec);
        } else {
          this.Uc(this.ec);
        }
      }
    } else {
      this.ec.style.display = "none";
      if (filtered === total) {
        this.Vc(localize(7871, null, total));
      } else {
        this.Vc(localize(7872, null, filtered, total));
      }
      this.ec.removeAttribute("tabIndex");
    }
  }
  Rc(container2) {
    if (this.b && this.h.getResourceMarkers(this.b)) {
      this.Sc(container2);
    } else {
      this.Tc(container2);
    }
  }
  Sc(container2) {
    const span1 = $bk(container2, $("span"));
    span1.textContent = $Ybc.MARKERS_PANEL_NO_PROBLEMS_FILTERS;
    const link2 = $bk(container2, $("a.messageAction"));
    link2.textContent = localize(7873, null);
    link2.setAttribute("tabIndex", "0");
    const span2 = $bk(container2, $("span"));
    span2.textContent = ".";
    $aj(link2, $7j.CLICK, () => this.Wc());
    $aj(link2, $7j.KEY_DOWN, (e) => {
      if (e.equals(
        3
        /* KeyCode.Enter */
      ) || e.equals(
        10
        /* KeyCode.Space */
      )) {
        this.Wc();
        e.stopPropagation();
      }
    });
    this.Vc($Ybc.MARKERS_PANEL_NO_PROBLEMS_FILTERS);
  }
  Tc(container2) {
    const span = $bk(container2, $("span"));
    span.textContent = $Ybc.MARKERS_PANEL_NO_PROBLEMS_ACTIVE_FILE_BUILT;
    this.Vc($Ybc.MARKERS_PANEL_NO_PROBLEMS_ACTIVE_FILE_BUILT);
  }
  Uc(container2) {
    const span = $bk(container2, $("span"));
    span.textContent = $Ybc.MARKERS_PANEL_NO_PROBLEMS_BUILT;
    this.Vc($Ybc.MARKERS_PANEL_NO_PROBLEMS_BUILT);
  }
  Vc(label3) {
    this.sb.setAriaLabel(label3);
    this.fc.setAttribute("aria-label", label3);
  }
  Wc() {
    this.filterWidget.setFilterText("");
    this.filters.excludedFiles = false;
    this.filters.showErrors = true;
    this.filters.showWarnings = true;
    this.filters.showInfos = true;
  }
  Xc(focus = false) {
    if (this.filters.activeFile) {
      return;
    }
    const autoReveal = this.Ab.getValue("problems.autoReveal");
    if (typeof autoReveal === "boolean" && autoReveal) {
      const currentActiveResource = this.Yc();
      this.sb.revealMarkers(currentActiveResource, focus, this.a);
    }
  }
  Yc() {
    return this.b ? this.h.getResourceMarkers(this.b) : null;
  }
  Zc() {
    this.c.removeHighlightRange();
    if ($Mj(this.sb.getHTMLElement())) {
      this.$c();
    }
  }
  $c() {
    const selections = this.sb.getSelection() ?? [];
    if (selections.length !== 1) {
      return;
    }
    const selection = selections[0];
    if (!(selection instanceof $Ubc)) {
      return;
    }
    this.c.highlightRange(selection);
  }
  ad(e) {
    const element = e.element;
    if (!element) {
      return;
    }
    e.browserEvent.preventDefault();
    e.browserEvent.stopPropagation();
    this.zb.showContextMenu({
      getAnchor: () => e.anchor,
      menuId: $bJ.ProblemsPanelContext,
      contextKeyService: this.sb.contextKeyService,
      getActions: () => this.bd(element),
      getActionViewItem: (action) => {
        const keybinding = this.yb.lookupKeybinding(action.id);
        if (keybinding) {
          return new $U1(action, action, { label: true, keybinding: keybinding.getLabel() });
        }
        return void 0;
      },
      onHide: (wasCancelled) => {
        if (wasCancelled) {
          this.sb.domFocus();
        }
      }
    });
  }
  bd(element) {
    const result = [];
    if (element instanceof $Ubc) {
      const viewModel = this.mc.getViewModel(element);
      if (viewModel) {
        const quickFixActions = viewModel.quickFixAction.quickFixes;
        if (quickFixActions.length) {
          result.push(...quickFixActions);
          result.push(new $Wm());
        }
      }
    }
    return result;
  }
  getFocusElement() {
    return this.sb.getFocus()[0] ?? void 0;
  }
  getFocusedSelectedElements() {
    const focus = this.getFocusElement();
    if (!focus) {
      return null;
    }
    const selection = this.sb.getSelection();
    if (selection.includes(focus)) {
      const result = [];
      for (const selected of selection) {
        if (selected) {
          result.push(selected);
        }
      }
      return result;
    } else {
      return [focus];
    }
  }
  getAllResourceMarkers() {
    return this.h.resourceMarkers;
  }
  getFilterStats() {
    if (!this.kc) {
      this.kc = {
        total: this.h.total,
        filtered: this.sb?.getVisibleItemCount() ?? 0
      };
    }
    return this.kc;
  }
  cd(hide3) {
    this.sb.toggleVisibility(hide3);
    this.L();
  }
  saveState() {
    this.jc["filter"] = this.filterWidget.getFilterText();
    this.jc["filterHistory"] = this.filters.filterHistory;
    this.jc["showErrors"] = this.filters.showErrors;
    this.jc["showWarnings"] = this.filters.showWarnings;
    this.jc["showInfos"] = this.filters.showInfos;
    this.jc["useFilesExclude"] = this.filters.excludedFiles;
    this.jc["activeFile"] = this.filters.activeFile;
    this.jc["multiline"] = this.mc.multiline;
    this.jc["viewMode"] = this.mc.viewMode;
    this.ic.saveMemento();
    super.saveState();
  }
  dispose() {
    super.dispose();
  }
};
$ccc = __decorate([
  __param(1, $Pk),
  __param(2, $$M),
  __param(3, $mJ),
  __param(4, $kl),
  __param(5, $zv),
  __param(6, $DE),
  __param(7, $on),
  __param(8, $Zk),
  __param(9, $50),
  __param(10, $vl),
  __param(11, $Ty),
  __param(12, $jv),
  __param(13, $O4),
  __param(14, $gs),
  __param(15, $5$)
], $ccc);
var MarkersTree = class MarkersTree2 extends $1eb {
  constructor(user, b, delegate, renderers, options3, instantiationService, contextKeyService, listService, themeService, configurationService) {
    super(user, b, delegate, renderers, options3, instantiationService, contextKeyService, listService, configurationService);
    this.b = b;
    this.a = MarkersContextKeys.MarkersTreeVisibilityContextKey.bindTo(contextKeyService);
  }
  collapseMarkers() {
    this.collapseAll();
    this.setSelection([]);
    this.setFocus([]);
    this.getHTMLElement().focus();
    this.focusFirst();
  }
  filterMarkers() {
    this.refilter();
  }
  getVisibleItemCount() {
    let filtered = 0;
    const root = this.getNode();
    for (const resourceMarkerNode of root.children) {
      for (const markerNode of resourceMarkerNode.children) {
        if (resourceMarkerNode.visible && markerNode.visible) {
          filtered++;
        }
      }
    }
    return filtered;
  }
  isVisible() {
    return !this.b.classList.contains("hidden");
  }
  toggleVisibility(hide3) {
    this.a.set(!hide3);
    this.b.classList.toggle("hidden", hide3);
  }
  reset(resourceMarkers) {
    this.setChildren(null, Iterable.map(resourceMarkers, (m) => ({ element: m, children: createResourceMarkersIterator(m) })));
  }
  revealMarkers(activeResource, focus, lastSelectedRelativeTop) {
    if (activeResource) {
      if (this.hasElement(activeResource)) {
        if (!this.isCollapsed(activeResource) && this.g(activeResource)) {
          this.reveal(this.getSelection()[0], lastSelectedRelativeTop);
          if (focus) {
            this.setFocus(this.getSelection());
          }
        } else {
          this.expand(activeResource);
          this.reveal(activeResource, 0);
          if (focus) {
            this.setFocus([activeResource]);
            this.setSelection([activeResource]);
          }
        }
      }
    } else if (focus) {
      this.setSelection([]);
      this.focusFirst();
    }
  }
  setAriaLabel(label3) {
    this.ariaLabel = label3;
  }
  setMarkerSelection(selection, focus) {
    if (this.isVisible()) {
      if (selection && selection.length > 0) {
        this.setSelection(selection.map((m) => this.c(m)));
        if (focus && focus.length > 0) {
          this.setFocus(focus.map((f) => this.c(f)));
        } else {
          this.setFocus([this.c(selection[0])]);
        }
        this.reveal(this.c(selection[0]));
      } else if (this.getSelection().length === 0) {
        const firstVisibleElement = this.firstVisibleElement;
        const marker = firstVisibleElement ? firstVisibleElement instanceof $Tbc ? firstVisibleElement.markers[0] : firstVisibleElement instanceof $Ubc ? firstVisibleElement : void 0 : void 0;
        if (marker) {
          this.setSelection([marker]);
          this.setFocus([marker]);
          this.reveal(marker);
        }
      }
    }
  }
  update(resourceMarkers) {
    for (const resourceMarker of resourceMarkers) {
      if (this.hasElement(resourceMarker)) {
        this.setChildren(resourceMarker, createResourceMarkersIterator(resourceMarker));
        this.rerender(resourceMarker);
      }
    }
  }
  updateMarker(marker) {
    this.rerender(marker);
  }
  c(marker) {
    for (const resourceNode of this.getNode().children) {
      for (const markerNode of resourceNode.children) {
        if (markerNode.element instanceof $Ubc && markerNode.element.marker === marker.marker) {
          return markerNode.element;
        }
      }
    }
    return null;
  }
  g(resource) {
    const selectedElement = this.getSelection();
    if (selectedElement && selectedElement.length > 0) {
      if (selectedElement[0] instanceof $Ubc) {
        if (resource.has(selectedElement[0].marker.resource)) {
          return true;
        }
      }
    }
    return false;
  }
  dispose() {
    super.dispose();
  }
  layout(height, width2) {
    this.b.style.height = `${height}px`;
    super.layout(height, width2);
  }
};
MarkersTree = __decorate([
  __param(5, $Pk),
  __param(6, $on),
  __param(7, $Deb),
  __param(8, $gs),
  __param(9, $kl)
], MarkersTree);

// out-build/vs/workbench/contrib/markers/browser/markers.contribution.js
$0I.registerCommandAndKeybindingRule({
  id: Markers.MARKER_OPEN_ACTION_ID,
  weight: 200,
  when: $7m.and(MarkersContextKeys.MarkerFocusContextKey),
  primary: 3,
  mac: {
    primary: 3,
    secondary: [
      2048 | 18
      /* KeyCode.DownArrow */
    ]
  },
  handler: (accessor, args2) => {
    const markersView = accessor.get($uob).getActiveViewWithId(Markers.MARKERS_VIEW_ID);
    markersView.openFileAtElement(markersView.getFocusElement(), false, false, true);
  }
});
$0I.registerCommandAndKeybindingRule({
  id: Markers.MARKER_OPEN_SIDE_ACTION_ID,
  weight: 200,
  when: $7m.and(MarkersContextKeys.MarkerFocusContextKey),
  primary: 2048 | 3,
  mac: {
    primary: 256 | 3
    /* KeyCode.Enter */
  },
  handler: (accessor, args2) => {
    const markersView = accessor.get($uob).getActiveViewWithId(Markers.MARKERS_VIEW_ID);
    markersView.openFileAtElement(markersView.getFocusElement(), false, true, true);
  }
});
$0I.registerCommandAndKeybindingRule({
  id: Markers.MARKER_SHOW_PANEL_ID,
  weight: 200,
  when: void 0,
  primary: void 0,
  handler: async (accessor, args2) => {
    await accessor.get($uob).openView(Markers.MARKERS_VIEW_ID);
  }
});
$0I.registerCommandAndKeybindingRule({
  id: Markers.MARKER_SHOW_QUICK_FIX,
  weight: 200,
  when: MarkersContextKeys.MarkerFocusContextKey,
  primary: 2048 | 89,
  handler: (accessor, args2) => {
    const markersView = accessor.get($uob).getActiveViewWithId(Markers.MARKERS_VIEW_ID);
    const focusedElement = markersView.getFocusElement();
    if (focusedElement instanceof $Ubc) {
      markersView.showQuickFixes(focusedElement);
    }
  }
});
$Wn.as($Ht.Configuration).registerConfiguration({
  ...$WL,
  "properties": {
    "problems.autoReveal": {
      "description": $Ybc.PROBLEMS_PANEL_CONFIGURATION_AUTO_REVEAL,
      "type": "boolean",
      "default": true
    },
    "problems.defaultViewMode": {
      "description": $Ybc.PROBLEMS_PANEL_CONFIGURATION_VIEW_MODE,
      "type": "string",
      "default": "tree",
      "enum": ["table", "tree"]
    },
    "problems.showCurrentInStatus": {
      "description": $Ybc.PROBLEMS_PANEL_CONFIGURATION_SHOW_CURRENT_STATUS,
      "type": "boolean",
      "default": false
    },
    "problems.sortOrder": {
      "description": $Ybc.PROBLEMS_PANEL_CONFIGURATION_COMPARE_ORDER,
      "type": "string",
      "default": "severity",
      "enum": ["severity", "position"],
      "enumDescriptions": [
        $Ybc.PROBLEMS_PANEL_CONFIGURATION_COMPARE_ORDER_SEVERITY,
        $Ybc.PROBLEMS_PANEL_CONFIGURATION_COMPARE_ORDER_POSITION
      ]
    }
  }
});
var markersViewIcon = $9r("markers-view-icon", $6l.warning, localize(7815, null));
var VIEW_CONTAINER2 = $Wn.as(Extensions5.ViewContainersRegistry).registerViewContainer({
  id: Markers.MARKERS_CONTAINER_ID,
  title: $Ybc.MARKERS_PANEL_TITLE_PROBLEMS,
  icon: markersViewIcon,
  hideIfEmpty: true,
  order: 0,
  ctorDescriptor: new $Nk($oqb, [Markers.MARKERS_CONTAINER_ID, { mergeViewWithContainerWhenSingleView: true }]),
  storageId: Markers.MARKERS_VIEW_STORAGE_ID
}, 1, { doNotRegisterOpenCommand: true });
$Wn.as(Extensions5.ViewsRegistry).registerViews([{
  id: Markers.MARKERS_VIEW_ID,
  containerIcon: markersViewIcon,
  name: $Ybc.MARKERS_PANEL_TITLE_PROBLEMS,
  canToggleVisibility: false,
  canMoveView: true,
  ctorDescriptor: new $Nk($ccc),
  openCommandActionDescriptor: {
    id: "workbench.actions.view.problems",
    mnemonicTitle: localize(7816, null),
    keybindings: {
      primary: 2048 | 1024 | 43
      /* KeyCode.KeyM */
    },
    order: 0
  }
}], VIEW_CONTAINER2);
var workbenchRegistry = $Wn.as(Extensions2.Workbench);
$hJ(class extends $cpb {
  constructor() {
    super({
      id: `workbench.actions.table.${Markers.MARKERS_VIEW_ID}.viewAsTree`,
      title: localize(7817, null),
      metadata: {
        description: localize2(7845, "Show the problems view as a tree.")
      },
      menu: {
        id: $bJ.ViewTitle,
        when: $7m.and($7m.equals("view", Markers.MARKERS_VIEW_ID), MarkersContextKeys.MarkersViewModeContextKey.isEqualTo(
          "table"
          /* MarkersViewMode.Table */
        )),
        group: "navigation",
        order: 3
      },
      icon: $6l.listTree,
      viewId: Markers.MARKERS_VIEW_ID
    });
  }
  async runInView(serviceAccessor, view) {
    view.setViewMode(
      "tree"
      /* MarkersViewMode.Tree */
    );
  }
});
$hJ(class extends $cpb {
  constructor() {
    super({
      id: `workbench.actions.table.${Markers.MARKERS_VIEW_ID}.viewAsTable`,
      title: localize(7818, null),
      metadata: {
        description: localize2(7846, "Show the problems view as a table.")
      },
      menu: {
        id: $bJ.ViewTitle,
        when: $7m.and($7m.equals("view", Markers.MARKERS_VIEW_ID), MarkersContextKeys.MarkersViewModeContextKey.isEqualTo(
          "tree"
          /* MarkersViewMode.Tree */
        )),
        group: "navigation",
        order: 3
      },
      icon: $6l.listFlat,
      viewId: Markers.MARKERS_VIEW_ID
    });
  }
  async runInView(serviceAccessor, view) {
    view.setViewMode(
      "table"
      /* MarkersViewMode.Table */
    );
  }
});
$hJ(class extends $cpb {
  constructor() {
    super({
      id: `workbench.actions.${Markers.MARKERS_VIEW_ID}.toggleErrors`,
      title: localize(7819, null),
      metadata: {
        description: localize2(7847, "Show or hide errors in the problems view.")
      },
      category: localize(7820, null),
      toggled: MarkersContextKeys.ShowErrorsFilterContextKey,
      menu: {
        id: $7ob,
        group: "1_filter",
        when: $7m.equals("view", Markers.MARKERS_VIEW_ID),
        order: 1
      },
      viewId: Markers.MARKERS_VIEW_ID
    });
  }
  async runInView(serviceAccessor, view) {
    view.filters.showErrors = !view.filters.showErrors;
  }
});
$hJ(class extends $cpb {
  constructor() {
    super({
      id: `workbench.actions.${Markers.MARKERS_VIEW_ID}.toggleWarnings`,
      title: localize(7821, null),
      metadata: {
        description: localize2(7848, "Show or hide warnings in the problems view.")
      },
      category: localize(7822, null),
      toggled: MarkersContextKeys.ShowWarningsFilterContextKey,
      menu: {
        id: $7ob,
        group: "1_filter",
        when: $7m.equals("view", Markers.MARKERS_VIEW_ID),
        order: 2
      },
      viewId: Markers.MARKERS_VIEW_ID
    });
  }
  async runInView(serviceAccessor, view) {
    view.filters.showWarnings = !view.filters.showWarnings;
  }
});
$hJ(class extends $cpb {
  constructor() {
    super({
      id: `workbench.actions.${Markers.MARKERS_VIEW_ID}.toggleInfos`,
      title: localize(7823, null),
      category: localize(7824, null),
      toggled: MarkersContextKeys.ShowInfoFilterContextKey,
      metadata: {
        description: localize2(7849, "Show or hide infos in the problems view.")
      },
      menu: {
        id: $7ob,
        group: "1_filter",
        when: $7m.equals("view", Markers.MARKERS_VIEW_ID),
        order: 3
      },
      viewId: Markers.MARKERS_VIEW_ID
    });
  }
  async runInView(serviceAccessor, view) {
    view.filters.showInfos = !view.filters.showInfos;
  }
});
$hJ(class extends $cpb {
  constructor() {
    super({
      id: `workbench.actions.${Markers.MARKERS_VIEW_ID}.toggleActiveFile`,
      title: localize(7825, null),
      metadata: {
        description: localize2(7850, "Show or hide problems (errors, warnings, info) only from the active file in the problems view.")
      },
      category: localize(7826, null),
      toggled: MarkersContextKeys.ShowActiveFileFilterContextKey,
      menu: {
        id: $7ob,
        group: "2_filter",
        when: $7m.equals("view", Markers.MARKERS_VIEW_ID),
        order: 1
      },
      viewId: Markers.MARKERS_VIEW_ID
    });
  }
  async runInView(serviceAccessor, view) {
    view.filters.activeFile = !view.filters.activeFile;
  }
});
$hJ(class extends $cpb {
  constructor() {
    super({
      id: `workbench.actions.${Markers.MARKERS_VIEW_ID}.toggleExcludedFiles`,
      title: localize(7827, null),
      metadata: {
        description: localize2(7851, "Show or hide excluded files in the problems view.")
      },
      category: localize(7828, null),
      toggled: MarkersContextKeys.ShowExcludedFilesFilterContextKey.negate(),
      menu: {
        id: $7ob,
        group: "2_filter",
        when: $7m.equals("view", Markers.MARKERS_VIEW_ID),
        order: 2
      },
      viewId: Markers.MARKERS_VIEW_ID
    });
  }
  async runInView(serviceAccessor, view) {
    view.filters.excludedFiles = !view.filters.excludedFiles;
  }
});
$hJ(class extends $gJ {
  constructor() {
    super({
      id: "workbench.action.problems.focus",
      title: $Ybc.MARKERS_PANEL_SHOW_LABEL,
      category: $qn.View,
      f1: true
    });
  }
  async run(accessor) {
    accessor.get($uob).openView(Markers.MARKERS_VIEW_ID, true);
  }
});
$hJ(class extends $cpb {
  constructor() {
    const when = $7m.and($jqb.isEqualTo(Markers.MARKERS_VIEW_ID), MarkersContextKeys.MarkersTreeVisibilityContextKey, MarkersContextKeys.RelatedInformationFocusContextKey.toNegated());
    super({
      id: Markers.MARKER_COPY_ACTION_ID,
      title: localize2(7852, "Copy"),
      menu: {
        id: $bJ.ProblemsPanelContext,
        when,
        group: "navigation"
      },
      keybinding: {
        weight: 200,
        primary: 2048 | 33,
        when
      },
      viewId: Markers.MARKERS_VIEW_ID
    });
  }
  async runInView(serviceAccessor, markersView) {
    const clipboardService = serviceAccessor.get($30);
    const selection = markersView.getFocusedSelectedElements() || markersView.getAllResourceMarkers();
    const markers = [];
    const addMarker = (marker) => {
      if (!markers.includes(marker)) {
        markers.push(marker);
      }
    };
    for (const selected of selection) {
      if (selected instanceof $Tbc) {
        selected.markers.forEach(addMarker);
      } else if (selected instanceof $Ubc) {
        addMarker(selected);
      }
    }
    if (markers.length) {
      await clipboardService.writeText(`[${markers}]`);
    }
  }
});
$hJ(class extends $cpb {
  constructor() {
    super({
      id: Markers.MARKER_COPY_MESSAGE_ACTION_ID,
      title: localize2(7853, "Copy Message"),
      menu: {
        id: $bJ.ProblemsPanelContext,
        when: MarkersContextKeys.MarkerFocusContextKey,
        group: "navigation"
      },
      viewId: Markers.MARKERS_VIEW_ID
    });
  }
  async runInView(serviceAccessor, markersView) {
    const clipboardService = serviceAccessor.get($30);
    const element = markersView.getFocusElement();
    if (element instanceof $Ubc) {
      await clipboardService.writeText(element.marker.message);
    }
  }
});
$hJ(class extends $cpb {
  constructor() {
    super({
      id: Markers.RELATED_INFORMATION_COPY_MESSAGE_ACTION_ID,
      title: localize2(7854, "Copy Message"),
      menu: {
        id: $bJ.ProblemsPanelContext,
        when: MarkersContextKeys.RelatedInformationFocusContextKey,
        group: "navigation"
      },
      viewId: Markers.MARKERS_VIEW_ID
    });
  }
  async runInView(serviceAccessor, markersView) {
    const clipboardService = serviceAccessor.get($30);
    const element = markersView.getFocusElement();
    if (element instanceof $Wbc) {
      await clipboardService.writeText(element.raw.message);
    }
  }
});
$hJ(class extends $cpb {
  constructor() {
    super({
      id: Markers.FOCUS_PROBLEMS_FROM_FILTER,
      title: localize(7829, null),
      keybinding: {
        when: MarkersContextKeys.MarkerViewFilterFocusContextKey,
        weight: 200,
        primary: 2048 | 18
        /* KeyCode.DownArrow */
      },
      viewId: Markers.MARKERS_VIEW_ID
    });
  }
  async runInView(serviceAccessor, markersView) {
    markersView.focus();
  }
});
$hJ(class extends $cpb {
  constructor() {
    super({
      id: Markers.MARKERS_VIEW_FOCUS_FILTER,
      title: localize(7830, null),
      keybinding: {
        when: $jqb.isEqualTo(Markers.MARKERS_VIEW_ID),
        weight: 200,
        primary: 2048 | 36
        /* KeyCode.KeyF */
      },
      viewId: Markers.MARKERS_VIEW_ID
    });
  }
  async runInView(serviceAccessor, markersView) {
    markersView.focusFilter();
  }
});
$hJ(class extends $cpb {
  constructor() {
    super({
      id: Markers.MARKERS_VIEW_SHOW_MULTILINE_MESSAGE,
      title: localize2(7855, "Show message in multiple lines"),
      category: localize(7831, null),
      menu: {
        id: $bJ.CommandPalette,
        when: $7m.has($kqb(Markers.MARKERS_VIEW_ID))
      },
      viewId: Markers.MARKERS_VIEW_ID
    });
  }
  async runInView(serviceAccessor, markersView) {
    markersView.setMultiline(true);
  }
});
$hJ(class extends $cpb {
  constructor() {
    super({
      id: Markers.MARKERS_VIEW_SHOW_SINGLELINE_MESSAGE,
      title: localize2(7856, "Show message in single line"),
      category: localize(7832, null),
      menu: {
        id: $bJ.CommandPalette,
        when: $7m.has($kqb(Markers.MARKERS_VIEW_ID))
      },
      viewId: Markers.MARKERS_VIEW_ID
    });
  }
  async runInView(serviceAccessor, markersView) {
    markersView.setMultiline(false);
  }
});
$hJ(class extends $cpb {
  constructor() {
    super({
      id: Markers.MARKERS_VIEW_CLEAR_FILTER_TEXT,
      title: localize(7833, null),
      category: localize(7834, null),
      keybinding: {
        when: MarkersContextKeys.MarkerViewFilterFocusContextKey,
        weight: 200,
        primary: 9
        /* KeyCode.Escape */
      },
      viewId: Markers.MARKERS_VIEW_ID
    });
  }
  async runInView(serviceAccessor, markersView) {
    markersView.clearFilterText();
  }
});
$hJ(class extends $cpb {
  constructor() {
    super({
      id: `workbench.actions.treeView.${Markers.MARKERS_VIEW_ID}.collapseAll`,
      title: localize(7835, null),
      menu: {
        id: $bJ.ViewTitle,
        when: $7m.and($7m.equals("view", Markers.MARKERS_VIEW_ID), MarkersContextKeys.MarkersViewModeContextKey.isEqualTo(
          "tree"
          /* MarkersViewMode.Tree */
        )),
        group: "navigation",
        order: 2
      },
      icon: $6l.collapseAll,
      viewId: Markers.MARKERS_VIEW_ID
    });
  }
  async runInView(serviceAccessor, view) {
    return view.collapseAll();
  }
});
$hJ(class extends $gJ {
  constructor() {
    super({
      id: Markers.TOGGLE_MARKERS_VIEW_ACTION_ID,
      title: $Ybc.MARKERS_PANEL_TOGGLE_LABEL
    });
  }
  async run(accessor) {
    const viewsService = accessor.get($uob);
    if (viewsService.isViewVisible(Markers.MARKERS_VIEW_ID)) {
      viewsService.closeView(Markers.MARKERS_VIEW_ID);
    } else {
      viewsService.openView(Markers.MARKERS_VIEW_ID, true);
    }
  }
});
var MarkersStatusBarContributions = class MarkersStatusBarContributions2 extends $3c {
  constructor(c, f, g) {
    super();
    this.c = c;
    this.f = f;
    this.g = g;
    this.a = this.B(this.f.addEntry(
      this.h(),
      "status.problems",
      0,
      50
      /* Medium Priority */
    ));
    const addStatusBarEntry = () => {
      this.b = this.f.addEntry(this.j(), "status.problemsVisibility", 0, 49);
    };
    let config = this.g.getValue("problems.visibility");
    if (!config) {
      addStatusBarEntry();
    }
    this.B(this.c.onMarkerChanged(() => {
      this.a.update(this.h());
    }));
    this.B(this.g.onDidChangeConfiguration((e) => {
      if (e.affectsConfiguration("problems.visibility")) {
        this.a.update(this.h());
        config = this.g.getValue("problems.visibility");
        if (!config && !this.b) {
          addStatusBarEntry();
        } else if (config && this.b) {
          this.b.dispose();
          this.b = void 0;
        }
      }
    }));
  }
  h() {
    const markersStatistics = this.c.getStatistics();
    const tooltip = this.m(markersStatistics);
    return {
      name: localize(7836, null),
      text: this.r(markersStatistics),
      ariaLabel: tooltip,
      tooltip,
      command: "workbench.actions.view.toggleProblems"
    };
  }
  j() {
    this.f.updateEntryVisibility("status.problemsVisibility", true);
    const openSettingsCommand2 = "workbench.action.openSettings";
    const configureSettingsLabel2 = "@id:problems.visibility";
    const tooltip = localize(7837, null);
    return {
      name: localize(7838, null),
      text: "$(whole-word)",
      ariaLabel: tooltip,
      tooltip,
      kind: "warning",
      command: { title: openSettingsCommand2, arguments: [configureSettingsLabel2], id: openSettingsCommand2 }
    };
  }
  m(stats) {
    const errorTitle = (n) => localize(7839, null, n);
    const warningTitle = (n) => localize(7840, null, n);
    const infoTitle = (n) => localize(7841, null, n);
    const titles = [];
    if (stats.errors > 0) {
      titles.push(errorTitle(stats.errors));
    }
    if (stats.warnings > 0) {
      titles.push(warningTitle(stats.warnings));
    }
    if (stats.infos > 0) {
      titles.push(infoTitle(stats.infos));
    }
    if (titles.length === 0) {
      return localize(7842, null);
    }
    return titles.join(", ");
  }
  r(stats) {
    const problemsText = [];
    problemsText.push("$(error) " + this.s(stats.errors));
    problemsText.push("$(warning) " + this.s(stats.warnings));
    if (stats.infos > 0) {
      problemsText.push("$(info) " + this.s(stats.infos));
    }
    return problemsText.join(" ");
  }
  s(n) {
    const manyProblems = localize(7843, null);
    return n > 9999 ? manyProblems : n > 999 ? n.toString().charAt(0) + "K" : n.toString();
  }
};
MarkersStatusBarContributions = __decorate([
  __param(0, $DE),
  __param(1, $$qb),
  __param(2, $kl)
], MarkersStatusBarContributions);
workbenchRegistry.registerWorkbenchContribution(
  MarkersStatusBarContributions,
  3
  /* LifecyclePhase.Restored */
);
var ActivityUpdater = class ActivityUpdater2 extends $3c {
  constructor(b, c) {
    super();
    this.b = b;
    this.c = c;
    this.a = this.B(new $4c());
    this.B(this.c.onMarkerChanged(() => this.f()));
    this.f();
  }
  f() {
    const { errors, warnings, infos } = this.c.getStatistics();
    const total = errors + warnings + infos;
    if (total > 0) {
      const message = localize(7844, null, total);
      this.a.value = this.b.showViewActivity(Markers.MARKERS_VIEW_ID, { badge: new $wqb(total, () => message) });
    } else {
      this.a.value = void 0;
    }
  }
};
ActivityUpdater = __decorate([
  __param(0, $vqb),
  __param(1, $DE)
], ActivityUpdater);
workbenchRegistry.registerWorkbenchContribution(
  ActivityUpdater,
  3
  /* LifecyclePhase.Restored */
);

// out-build/vs/workbench/contrib/mergeEditor/browser/view/colors.js
var diff2 = $5n("mergeEditor.change.background", "#9bb95533", localize(7999, null));
var $YHb = $5n("mergeEditor.change.word.background", { dark: "#9ccc2c33", light: "#9ccc2c66", hcDark: "#9ccc2c33", hcLight: "#9ccc2c66" }, localize(8e3, null));
var $ZHb = $5n("mergeEditor.changeBase.background", { dark: "#4B1818FF", light: "#FFCCCCFF", hcDark: "#4B1818FF", hcLight: "#FFCCCCFF" }, localize(8001, null));
var $1Hb = $5n("mergeEditor.changeBase.word.background", { dark: "#6F1313FF", light: "#FFA3A3FF", hcDark: "#6F1313FF", hcLight: "#FFA3A3FF" }, localize(8002, null));
var $2Hb = $5n("mergeEditor.conflict.unhandledUnfocused.border", { dark: "#ffa6007a", light: "#ffa600FF", hcDark: "#ffa6007a", hcLight: "#ffa6007a" }, localize(8003, null));
var $3Hb = $5n("mergeEditor.conflict.unhandledFocused.border", "#ffa600", localize(8004, null));
var $4Hb = $5n("mergeEditor.conflict.handledUnfocused.border", "#86868649", localize(8005, null));
var $5Hb = $5n("mergeEditor.conflict.handledFocused.border", "#c1c1c1cc", localize(8006, null));
var $6Hb = $5n("mergeEditor.conflict.handled.minimapOverViewRuler", "#adaca8ee", localize(8007, null));
var $7Hb = $5n("mergeEditor.conflict.unhandled.minimapOverViewRuler", "#fcba03FF", localize(8008, null));
var $8Hb = $5n("mergeEditor.conflictingLines.background", "#ffea0047", localize(8009, null));
var contentTransparency2 = 0.4;
var $9Hb = $5n("mergeEditor.conflict.input1.background", $0n($2p, contentTransparency2), localize(8010, null));
var $0Hb = $5n("mergeEditor.conflict.input2.background", $0n($4p, contentTransparency2), localize(8011, null));

// out-build/vs/workbench/contrib/mergeEditor/browser/view/editorGutter.js
var $$Hb = class extends $3c {
  constructor(m, n, r2) {
    super();
    this.m = m;
    this.n = n;
    this.r = r2;
    this.a = $Dd(this, this.m.onDidScrollChange, (e) => (
      /** @description editor.onDidScrollChange */
      this.m.getScrollTop()
    ));
    this.b = this.a.map((scrollTop) => (
      /** @description isScrollTopZero */
      scrollTop === 0
    ));
    this.c = $Dd(this, this.m.onDidChangeModel, (e) => (
      /** @description editor.onDidChangeModel */
      this.m.hasModel()
    ));
    this.f = $Gd("onDidChangeViewZones", this.m.onDidChangeViewZones);
    this.g = $Gd("onDidContentSizeChange", this.m.onDidContentSizeChange);
    this.j = $Hd("domNodeSizeChanged");
    this.s = /* @__PURE__ */ new Map();
    this.n.className = "gutter monaco-editor";
    const scrollDecoration = this.n.appendChild(h("div.scroll-decoration", { role: "presentation", ariaHidden: "true", style: { width: "100%" } }).root);
    const o = new ResizeObserver(() => {
      $ce((tx) => {
        this.j.trigger(tx);
      });
    });
    o.observe(this.n);
    this.B($1c(() => o.disconnect()));
    this.B($td((reader) => {
      scrollDecoration.className = this.b.read(reader) ? "" : "scroll-decoration";
    }));
    this.B($td((reader) => (
      /** @description EditorGutter.Render */
      this.t(reader)
    )));
  }
  dispose() {
    super.dispose();
    $dk(this.n);
  }
  t(reader) {
    if (!this.c.read(reader)) {
      return;
    }
    this.j.read(reader);
    this.f.read(reader);
    this.g.read(reader);
    const scrollTop = this.a.read(reader);
    const visibleRanges = this.m.getVisibleRanges();
    const unusedIds = new Set(this.s.keys());
    if (visibleRanges.length > 0) {
      const visibleRange = visibleRanges[0];
      const visibleRange2 = new $jHb(visibleRange.startLineNumber, visibleRange.endLineNumber - visibleRange.startLineNumber).deltaEnd(1);
      const gutterItems = this.r.getIntersectingGutterItems(visibleRange2, reader);
      for (const gutterItem of gutterItems) {
        if (!gutterItem.range.touches(visibleRange2)) {
          continue;
        }
        unusedIds.delete(gutterItem.id);
        let view = this.s.get(gutterItem.id);
        if (!view) {
          const viewDomNode = document.createElement("div");
          this.n.appendChild(viewDomNode);
          const itemView = this.r.createView(gutterItem, viewDomNode);
          view = new ManagedGutterItemView2(itemView, viewDomNode);
          this.s.set(gutterItem.id, view);
        } else {
          view.gutterItemView.update(gutterItem);
        }
        const top2 = gutterItem.range.startLineNumber <= this.m.getModel().getLineCount() ? this.m.getTopForLineNumber(gutterItem.range.startLineNumber, true) - scrollTop : this.m.getBottomForLineNumber(gutterItem.range.startLineNumber - 1, false) - scrollTop;
        const bottom = this.m.getBottomForLineNumber(gutterItem.range.endLineNumberExclusive - 1, true) - scrollTop;
        const height = bottom - top2;
        view.domNode.style.top = `${top2}px`;
        view.domNode.style.height = `${height}px`;
        view.gutterItemView.layout(top2, height, 0, this.n.clientHeight);
      }
    }
    for (const id2 of unusedIds) {
      const view = this.s.get(id2);
      view.gutterItemView.dispose();
      view.domNode.remove();
      this.s.delete(id2);
    }
  }
};
var ManagedGutterItemView2 = class {
  constructor(gutterItemView, domNode) {
    this.gutterItemView = gutterItemView;
    this.domNode = domNode;
  }
};

// out-build/vs/workbench/contrib/mergeEditor/browser/view/editors/codeEditorView.js
var $_Hb = class extends $3c {
  updateOptions(newOptions) {
    this.editor.updateOptions(newOptions);
  }
  constructor(s, viewModel, t) {
    super();
    this.s = s;
    this.viewModel = viewModel;
    this.t = t;
    this.model = this.viewModel.map((m) => (
      /** @description model */
      m?.model
    ));
    this.a = h("div.code-view", [
      h("div.header@header", [
        h("span.title@title"),
        h("span.description@description"),
        h("span.detail@detail"),
        h("span.toolbar@toolbar")
      ]),
      h("div.container", [
        h("div.gutter@gutterDiv"),
        h("div@editor")
      ])
    ]);
    this.b = new $ze();
    this.view = {
      element: this.a.root,
      minimumWidth: $Xob.width,
      maximumWidth: $Yob.width,
      minimumHeight: $Xob.height,
      maximumHeight: $Yob.height,
      onDidChange: this.b.event,
      layout: (width2, height, top2, left) => {
        $nHb(this.a.root, { width: width2, height, top: top2, left });
        this.editor.layout({
          width: width2 - this.a.gutterDiv.clientWidth,
          height: height - this.a.header.clientHeight
        });
      }
      // preferredWidth?: number | undefined;
      // preferredHeight?: number | undefined;
      // priority?: LayoutPriority | undefined;
      // snap?: boolean | undefined;
    };
    this.f = $G9("mergeEditor.showCheckboxes", false, this.t);
    this.j = $G9("mergeEditor.showDeletionMarkers", true, this.t);
    this.n = $G9("mergeEditor.useSimplifiedDecorations", false, this.t);
    this.editor = this.s.createInstance($D9, this.a.editor, {}, {
      contributions: this.u()
    });
    this.isFocused = $Dd(this, Event2.any(this.editor.onDidBlurEditorWidget, this.editor.onDidFocusEditorWidget), () => (
      /** @description editor.hasWidgetFocus */
      this.editor.hasWidgetFocus()
    ));
    this.cursorPosition = $Dd(this, this.editor.onDidChangeCursorPosition, () => (
      /** @description editor.getPosition */
      this.editor.getPosition()
    ));
    this.selection = $Dd(this, this.editor.onDidChangeCursorSelection, () => (
      /** @description editor.getSelections */
      this.editor.getSelections()
    ));
    this.cursorLineNumber = this.cursorPosition.map((p) => (
      /** @description cursorPosition.lineNumber */
      p?.lineNumber
    ));
  }
  u() {
    return EditorExtensionsRegistry.getEditorContributions().filter((c) => c.id !== $9gb.ID && c.id !== $vbb.ID);
  }
};
function $aIb(codeEditorView, translateRange) {
  const selections = $2d((reader) => {
    const viewModel = codeEditorView.viewModel.read(reader);
    if (!viewModel) {
      return [];
    }
    const baseRange = viewModel.selectionInBase.read(reader);
    if (!baseRange || baseRange.sourceEditor === codeEditorView) {
      return [];
    }
    return baseRange.rangesInBase.map((r2) => translateRange(r2, viewModel));
  });
  return $td((reader) => {
    const ranges = selections.read(reader);
    if (ranges.length === 0) {
      return;
    }
    codeEditorView.editor.setSelections(ranges.map((r2) => new $_D(r2.startLineNumber, r2.startColumn, r2.endLineNumber, r2.endColumn)));
  });
}
var $bIb = class $bIb2 extends $3c {
  constructor(menuId, targetHtmlElement, instantiationService) {
    super();
    const toolbar = instantiationService.createInstance($4$, targetHtmlElement, menuId, {
      menuOptions: { renderShortTitle: true },
      toolbarOptions: { primaryGroup: (g) => g === "primary" }
    });
    this.q.add(toolbar);
  }
};
$bIb = __decorate([
  __param(2, $Pk)
], $bIb);

// out-build/vs/workbench/contrib/mergeEditor/browser/view/editors/baseCodeEditorView.js
var $cIb = class $cIb2 extends $_Hb {
  constructor(viewModel, instantiationService, configurationService) {
    super(instantiationService, viewModel, configurationService);
    this.w = $2d(this, (reader) => {
      const viewModel2 = this.viewModel.read(reader);
      if (!viewModel2) {
        return [];
      }
      const model = viewModel2.model;
      const textModel = model.base;
      const activeModifiedBaseRange = viewModel2.activeModifiedBaseRange.read(reader);
      const showNonConflictingChanges = viewModel2.showNonConflictingChanges.read(reader);
      const showDeletionMarkers = this.j.read(reader);
      const result = [];
      for (const modifiedBaseRange of model.modifiedBaseRanges.read(reader)) {
        const range = modifiedBaseRange.baseRange;
        if (!range) {
          continue;
        }
        const isHandled = model.isHandled(modifiedBaseRange).read(reader);
        if (!modifiedBaseRange.isConflicting && isHandled && !showNonConflictingChanges) {
          continue;
        }
        const blockClassNames = ["merge-editor-block"];
        let blockPadding = [0, 0, 0, 0];
        if (isHandled) {
          blockClassNames.push("handled");
        }
        if (modifiedBaseRange === activeModifiedBaseRange) {
          blockClassNames.push("focused");
          blockPadding = [0, 2, 0, 2];
        }
        blockClassNames.push("base");
        const inputToDiffAgainst = viewModel2.baseShowDiffAgainst.read(reader);
        if (inputToDiffAgainst) {
          for (const diff3 of modifiedBaseRange.getInputDiffs(inputToDiffAgainst)) {
            const range2 = diff3.inputRange.toInclusiveRange();
            if (range2) {
              result.push({
                range: range2,
                options: {
                  className: `merge-editor-diff base`,
                  description: "Merge Editor",
                  isWholeLine: true
                }
              });
            }
            for (const diff22 of diff3.rangeMappings) {
              if (showDeletionMarkers || !diff22.inputRange.isEmpty()) {
                result.push({
                  range: diff22.inputRange,
                  options: {
                    className: diff22.inputRange.isEmpty() ? `merge-editor-diff-empty-word base` : `merge-editor-diff-word base`,
                    description: "Merge Editor",
                    showIfCollapsed: true
                  }
                });
              }
            }
          }
        }
        result.push({
          range: range.toInclusiveRangeOrEmpty(),
          options: {
            showIfCollapsed: true,
            blockClassName: blockClassNames.join(" "),
            blockPadding,
            blockIsAfterEnd: range.startLineNumber > textModel.getLineCount(),
            description: "Merge Editor",
            minimap: {
              position: 2,
              color: { id: isHandled ? $6Hb : $7Hb }
            },
            overviewRuler: modifiedBaseRange.isConflicting ? {
              position: OverviewRulerLane.Center,
              color: { id: isHandled ? $6Hb : $7Hb }
            } : void 0
          }
        });
      }
      return result;
    });
    this.B($aIb(this, (baseRange, viewModel2) => baseRange));
    this.B(instantiationService.createInstance($bIb, $bJ.MergeBaseToolbar, this.a.title));
    this.B($xd((reader, store) => {
      if (this.f.read(reader)) {
        store.add(new $$Hb(this.editor, this.a.gutterDiv, {
          getIntersectingGutterItems: (range, reader2) => [],
          createView: (item, target) => {
            throw new $vb();
          }
        }));
      }
    }));
    this.B($td((reader) => {
      const vm = this.viewModel.read(reader);
      if (!vm) {
        return;
      }
      this.editor.setModel(vm.model.base);
      $dk(this.a.title, ...$B1(localize(8033, null)));
      const baseShowDiffAgainst = vm.baseShowDiffAgainst.read(reader);
      let node = void 0;
      if (baseShowDiffAgainst) {
        const label3 = localize(8034, null, baseShowDiffAgainst === 1 ? vm.model.input1.title : vm.model.input2.title);
        const tooltip = localize(8035, null);
        node = h("span", { title: tooltip }, [label3]).root;
      }
      $dk(this.a.description, ...node ? [node] : []);
    }));
    this.B($oHb(this.editor, this.w));
  }
};
$cIb = __decorate([
  __param(1, $Pk),
  __param(2, $kl)
], $cIb);

// out-build/vs/workbench/contrib/mergeEditor/browser/view/scrollSynchronizer.js
var $dcc = class extends $3c {
  get a() {
    return this.h.get()?.model;
  }
  get f() {
    return this.s.get().kind === "columns";
  }
  get g() {
    return this.s.get().kind === "mixed" && !this.s.get().showBaseAtTop;
  }
  constructor(h3, j, m, n, r2, s) {
    super();
    this.h = h3;
    this.j = j;
    this.m = m;
    this.n = n;
    this.r = r2;
    this.s = s;
    this.b = new $J3();
    const handleInput1OnScroll = this.updateScrolling = () => {
      if (!this.a) {
        return;
      }
      this.m.editor.setScrollTop(
        this.j.editor.getScrollTop(),
        1
        /* ScrollType.Immediate */
      );
      if (this.f) {
        this.r.editor.setScrollTop(
          this.j.editor.getScrollTop(),
          1
          /* ScrollType.Immediate */
        );
      } else {
        const mappingInput1Result = this.a.input1ResultMapping.get();
        this.t(this.j.editor, this.r.editor, mappingInput1Result);
      }
      const baseView = this.n.get();
      if (baseView) {
        if (this.g) {
          this.n.get()?.editor.setScrollTop(
            this.j.editor.getScrollTop(),
            1
            /* ScrollType.Immediate */
          );
        } else {
          const mapping2 = new $DHb(this.a.baseInput1Diffs.get(), -1).reverse();
          this.t(this.j.editor, baseView.editor, mapping2);
        }
      }
    };
    this.q.add(this.j.editor.onDidScrollChange(this.b.makeExclusiveOrSkip((c) => {
      if (c.scrollTopChanged) {
        handleInput1OnScroll();
      }
      if (c.scrollLeftChanged) {
        this.n.get()?.editor.setScrollLeft(
          c.scrollLeft,
          1
          /* ScrollType.Immediate */
        );
        this.m.editor.setScrollLeft(
          c.scrollLeft,
          1
          /* ScrollType.Immediate */
        );
        this.r.editor.setScrollLeft(
          c.scrollLeft,
          1
          /* ScrollType.Immediate */
        );
      }
    })));
    this.q.add(this.m.editor.onDidScrollChange(this.b.makeExclusiveOrSkip((c) => {
      if (!this.a) {
        return;
      }
      if (c.scrollTopChanged) {
        this.j.editor.setScrollTop(
          c.scrollTop,
          1
          /* ScrollType.Immediate */
        );
        if (this.f) {
          this.r.editor.setScrollTop(
            this.m.editor.getScrollTop(),
            1
            /* ScrollType.Immediate */
          );
        } else {
          const mappingInput2Result = this.a.input2ResultMapping.get();
          this.t(this.m.editor, this.r.editor, mappingInput2Result);
        }
        const baseView = this.n.get();
        if (baseView && this.a) {
          if (this.g) {
            this.n.get()?.editor.setScrollTop(
              c.scrollTop,
              1
              /* ScrollType.Immediate */
            );
          } else {
            const mapping2 = new $DHb(this.a.baseInput2Diffs.get(), -1).reverse();
            this.t(this.m.editor, baseView.editor, mapping2);
          }
        }
      }
      if (c.scrollLeftChanged) {
        this.n.get()?.editor.setScrollLeft(
          c.scrollLeft,
          1
          /* ScrollType.Immediate */
        );
        this.j.editor.setScrollLeft(
          c.scrollLeft,
          1
          /* ScrollType.Immediate */
        );
        this.r.editor.setScrollLeft(
          c.scrollLeft,
          1
          /* ScrollType.Immediate */
        );
      }
    })));
    this.q.add(this.r.editor.onDidScrollChange(this.b.makeExclusiveOrSkip((c) => {
      if (c.scrollTopChanged) {
        if (this.f) {
          this.j.editor.setScrollTop(
            c.scrollTop,
            1
            /* ScrollType.Immediate */
          );
          this.m.editor.setScrollTop(
            c.scrollTop,
            1
            /* ScrollType.Immediate */
          );
        } else {
          const mapping1 = this.a?.resultInput1Mapping.get();
          this.t(this.r.editor, this.j.editor, mapping1);
          const mapping2 = this.a?.resultInput2Mapping.get();
          this.t(this.r.editor, this.m.editor, mapping2);
        }
        const baseMapping = this.a?.resultBaseMapping.get();
        const baseView = this.n.get();
        if (baseView && this.a) {
          this.t(this.r.editor, baseView.editor, baseMapping);
        }
      }
      if (c.scrollLeftChanged) {
        this.n.get()?.editor?.setScrollLeft(
          c.scrollLeft,
          1
          /* ScrollType.Immediate */
        );
        this.j.editor.setScrollLeft(
          c.scrollLeft,
          1
          /* ScrollType.Immediate */
        );
        this.m.editor.setScrollLeft(
          c.scrollLeft,
          1
          /* ScrollType.Immediate */
        );
      }
    })));
    this.q.add($xd((reader, store) => {
      const baseView = this.n.read(reader);
      if (baseView) {
        store.add(baseView.editor.onDidScrollChange(this.b.makeExclusiveOrSkip((c) => {
          if (c.scrollTopChanged) {
            if (!this.a) {
              return;
            }
            if (this.g) {
              this.j.editor.setScrollTop(
                c.scrollTop,
                1
                /* ScrollType.Immediate */
              );
              this.m.editor.setScrollTop(
                c.scrollTop,
                1
                /* ScrollType.Immediate */
              );
            } else {
              const baseInput1Mapping = new $DHb(this.a.baseInput1Diffs.get(), -1);
              this.t(baseView.editor, this.j.editor, baseInput1Mapping);
              const baseInput2Mapping = new $DHb(this.a.baseInput2Diffs.get(), -1);
              this.t(baseView.editor, this.m.editor, baseInput2Mapping);
            }
            const baseMapping = this.a?.baseResultMapping.get();
            this.t(baseView.editor, this.r.editor, baseMapping);
          }
          if (c.scrollLeftChanged) {
            this.r.editor.setScrollLeft(
              c.scrollLeft,
              1
              /* ScrollType.Immediate */
            );
            this.j.editor.setScrollLeft(
              c.scrollLeft,
              1
              /* ScrollType.Immediate */
            );
            this.m.editor.setScrollLeft(
              c.scrollLeft,
              1
              /* ScrollType.Immediate */
            );
          }
        })));
      }
    }));
  }
  t(scrollingEditor, targetEditor, mapping2) {
    if (!mapping2) {
      return;
    }
    const visibleRanges = scrollingEditor.getVisibleRanges();
    if (visibleRanges.length === 0) {
      return;
    }
    const topLineNumber = visibleRanges[0].startLineNumber - 1;
    const result = mapping2.project(topLineNumber);
    const sourceRange = result.inputRange;
    const targetRange = result.outputRange;
    const resultStartTopPx = targetEditor.getTopForLineNumber(targetRange.startLineNumber);
    const resultEndPx = targetEditor.getTopForLineNumber(targetRange.endLineNumberExclusive);
    const sourceStartTopPx = scrollingEditor.getTopForLineNumber(sourceRange.startLineNumber);
    const sourceEndPx = scrollingEditor.getTopForLineNumber(sourceRange.endLineNumberExclusive);
    const factor2 = Math.min((scrollingEditor.getScrollTop() - sourceStartTopPx) / (sourceEndPx - sourceStartTopPx), 1);
    const resultScrollPosition = resultStartTopPx + (resultEndPx - resultStartTopPx) * factor2;
    targetEditor.setScrollTop(
      resultScrollPosition,
      1
      /* ScrollType.Immediate */
    );
  }
};

// out-build/vs/workbench/contrib/mergeEditor/browser/view/viewModel.js
var $qIb = class $qIb2 extends $3c {
  constructor(model, inputCodeEditorView1, inputCodeEditorView2, resultCodeEditorView, baseCodeEditorView, showNonConflictingChanges, c, f) {
    super();
    this.model = model;
    this.inputCodeEditorView1 = inputCodeEditorView1;
    this.inputCodeEditorView2 = inputCodeEditorView2;
    this.resultCodeEditorView = resultCodeEditorView;
    this.baseCodeEditorView = baseCodeEditorView;
    this.showNonConflictingChanges = showNonConflictingChanges;
    this.c = c;
    this.f = f;
    this.a = $he(this, { range: void 0, counter: 0 });
    this.b = this.B(new AttachedHistory(this.model.resultTextModel));
    this.shouldUseAppendInsteadOfAccept = $G9("mergeEditor.shouldUseAppendInsteadOfAccept", false, this.c);
    this.g = 0;
    this.h = $Qd(this, (reader, lastValue) => {
      const editors = [
        this.inputCodeEditorView1,
        this.inputCodeEditorView2,
        this.resultCodeEditorView,
        this.baseCodeEditorView.read(reader)
      ];
      const view = editors.find((e) => e && e.isFocused.read(reader));
      return view ? { view, counter: this.g++ } : lastValue || { view: void 0, counter: this.g++ };
    });
    this.baseShowDiffAgainst = $2d(this, (reader) => {
      const lastFocusedEditor = this.h.read(reader);
      if (lastFocusedEditor.view === this.inputCodeEditorView1) {
        return 1;
      } else if (lastFocusedEditor.view === this.inputCodeEditorView2) {
        return 2;
      }
      return void 0;
    });
    this.selectionInBase = $2d(this, (reader) => {
      const sourceEditor = this.h.read(reader).view;
      if (!sourceEditor) {
        return void 0;
      }
      const selections = sourceEditor.selection.read(reader) || [];
      const rangesInBase = selections.map((selection) => {
        if (sourceEditor === this.inputCodeEditorView1) {
          return this.model.translateInputRangeToBase(1, selection);
        } else if (sourceEditor === this.inputCodeEditorView2) {
          return this.model.translateInputRangeToBase(2, selection);
        } else if (sourceEditor === this.resultCodeEditorView) {
          return this.model.translateResultRangeToBase(selection);
        } else if (sourceEditor === this.baseCodeEditorView.read(reader)) {
          return selection;
        } else {
          return selection;
        }
      });
      return {
        rangesInBase,
        sourceEditor
      };
    });
    this.activeModifiedBaseRange = $2d(this, (reader) => {
      const focusedEditor = this.h.read(reader);
      const manualRange = this.a.read(reader);
      if (manualRange.counter > focusedEditor.counter) {
        return manualRange.range;
      }
      if (!focusedEditor.view) {
        return;
      }
      const cursorLineNumber = focusedEditor.view.cursorLineNumber.read(reader);
      if (!cursorLineNumber) {
        return void 0;
      }
      const modifiedBaseRanges = this.model.modifiedBaseRanges.read(reader);
      return modifiedBaseRanges.find((r2) => {
        const range = this.j(focusedEditor.view, r2, reader);
        return range.isEmpty ? range.startLineNumber === cursorLineNumber : range.contains(cursorLineNumber);
      });
    });
    this.B(resultCodeEditorView.editor.onDidChangeModelContent((e) => {
      if (this.model.isApplyingEditInResult || e.isRedoing || e.isUndoing) {
        return;
      }
      const baseRangeStates = [];
      for (const change of e.changes) {
        const rangeInBase = this.model.translateResultRangeToBase($9C.lift(change.range));
        const baseRanges = this.model.findModifiedBaseRangesInRange(new $jHb(rangeInBase.startLineNumber, rangeInBase.endLineNumber - rangeInBase.startLineNumber));
        if (baseRanges.length === 1) {
          const isHandled = this.model.isHandled(baseRanges[0]).get();
          if (!isHandled) {
            baseRangeStates.push(baseRanges[0]);
          }
        }
      }
      if (baseRangeStates.length === 0) {
        return;
      }
      const element = {
        model: this.model,
        redo() {
          $ce((tx) => {
            for (const r2 of baseRangeStates) {
              this.model.setHandled(r2, true, tx);
            }
          });
        },
        undo() {
          $ce((tx) => {
            for (const r2 of baseRangeStates) {
              this.model.setHandled(r2, false, tx);
            }
          });
        }
      };
      this.b.pushAttachedHistoryElement(element);
      element.redo();
    }));
  }
  j(editor, modifiedBaseRange, reader) {
    if (editor === this.resultCodeEditorView) {
      return this.model.getLineRangeInResult(modifiedBaseRange.baseRange, reader);
    } else if (editor === this.baseCodeEditorView.get()) {
      return modifiedBaseRange.baseRange;
    } else {
      const input = editor === this.inputCodeEditorView1 ? 1 : 2;
      return modifiedBaseRange.getInputRange(input);
    }
  }
  setActiveModifiedBaseRange(range, tx) {
    this.a.set({ range, counter: this.g++ }, tx);
  }
  setState(baseRange, state, tx, inputNumber) {
    this.a.set({ range: baseRange, counter: this.g++ }, tx);
    this.model.setState(baseRange, state, inputNumber, tx);
    this.h.clearCache(tx);
  }
  n(getModifiedBaseRange) {
    let editor = this.h.get().view;
    if (!editor) {
      editor = this.resultCodeEditorView;
    }
    const curLineNumber = editor.editor.getPosition()?.lineNumber;
    if (curLineNumber === void 0) {
      return;
    }
    const modifiedBaseRange = getModifiedBaseRange(editor, curLineNumber);
    if (modifiedBaseRange) {
      const range = this.j(editor, modifiedBaseRange, void 0);
      editor.editor.focus();
      let startLineNumber = range.startLineNumber;
      let endLineNumberExclusive = range.endLineNumberExclusive;
      if (range.startLineNumber > editor.editor.getModel().getLineCount()) {
        $ce((tx) => {
          this.setActiveModifiedBaseRange(modifiedBaseRange, tx);
        });
        startLineNumber = endLineNumberExclusive = editor.editor.getModel().getLineCount();
      }
      editor.editor.setPosition({
        lineNumber: startLineNumber,
        column: editor.editor.getModel().getLineFirstNonWhitespaceColumn(startLineNumber)
      });
      editor.editor.revealLinesNearTop(
        startLineNumber,
        endLineNumberExclusive,
        0
        /* ScrollType.Smooth */
      );
    }
  }
  goToNextModifiedBaseRange(predicate) {
    this.n((e, l) => this.model.modifiedBaseRanges.get().find((r2) => predicate(r2) && this.j(e, r2, void 0).startLineNumber > l) || this.model.modifiedBaseRanges.get().find((r2) => predicate(r2)));
  }
  goToPreviousModifiedBaseRange(predicate) {
    this.n((e, l) => $1(this.model.modifiedBaseRanges.get(), (r2) => predicate(r2) && this.j(e, r2, void 0).endLineNumberExclusive < l) || $1(this.model.modifiedBaseRanges.get(), (r2) => predicate(r2)));
  }
  toggleActiveConflict(inputNumber) {
    const activeModifiedBaseRange = this.activeModifiedBaseRange.get();
    if (!activeModifiedBaseRange) {
      this.f.error(localize(8053, null));
      return;
    }
    $ce((tx) => {
      this.setState(activeModifiedBaseRange, this.model.getState(activeModifiedBaseRange).get().toggle(inputNumber), tx, inputNumber);
    });
  }
  acceptAll(inputNumber) {
    $ce((tx) => {
      for (const range of this.model.modifiedBaseRanges.get()) {
        this.setState(range, this.model.getState(range).get().withInputValue(inputNumber, true), tx, inputNumber);
      }
    });
  }
};
$qIb = __decorate([
  __param(6, $kl),
  __param(7, $PJ)
], $qIb);
var AttachedHistory = class extends $3c {
  constructor(c) {
    super();
    this.c = c;
    this.a = [];
    this.b = this.c.getAlternativeVersionId();
    this.B(c.onDidChangeContent((e) => {
      const currentAltId = c.getAlternativeVersionId();
      if (e.isRedoing) {
        for (const item of this.a) {
          if (this.b < item.altId && item.altId <= currentAltId) {
            item.element.redo();
          }
        }
      } else if (e.isUndoing) {
        for (let i2 = this.a.length - 1; i2 >= 0; i2--) {
          const item = this.a[i2];
          if (currentAltId < item.altId && item.altId <= this.b) {
            item.element.undo();
          }
        }
      } else {
        while (this.a.length > 0 && this.a[this.a.length - 1].altId > this.b) {
          this.a.pop();
        }
      }
      this.b = currentAltId;
    }));
  }
  /**
   * Pushes an history item that is tied to the last text edit (or an extension of it).
   * When the last text edit is undone/redone, so is is this history item.
   */
  pushAttachedHistoryElement(element) {
    this.a.push({ altId: this.c.getAlternativeVersionId(), element });
  }
};

// out-build/vs/workbench/contrib/mergeEditor/browser/view/lineAlignment.js
function $ecc(m) {
  const equalRanges1 = toEqualRangeMappings(m.input1Diffs.flatMap((d) => d.rangeMappings), m.baseRange.toRange(), m.input1Range.toRange());
  const equalRanges2 = toEqualRangeMappings(m.input2Diffs.flatMap((d) => d.rangeMappings), m.baseRange.toRange(), m.input2Range.toRange());
  const commonRanges = splitUpCommonEqualRangeMappings(equalRanges1, equalRanges2);
  let result = [];
  result.push([m.input1Range.startLineNumber - 1, m.baseRange.startLineNumber - 1, m.input2Range.startLineNumber - 1]);
  function isFullSync(lineAlignment) {
    return lineAlignment.every((i2) => i2 !== void 0);
  }
  for (const m2 of commonRanges) {
    const lineAlignment = [m2.output1Pos?.lineNumber, m2.inputPos.lineNumber, m2.output2Pos?.lineNumber];
    const alignmentIsFullSync = isFullSync(lineAlignment);
    let shouldAdd = true;
    if (alignmentIsFullSync) {
      const isNewFullSyncAlignment = !result.some((r2) => isFullSync(r2) && r2.some((v, idx) => v !== void 0 && v === lineAlignment[idx]));
      if (isNewFullSyncAlignment) {
        result = result.filter((r2) => !r2.some((v, idx) => v !== void 0 && v === lineAlignment[idx]));
      }
      shouldAdd = isNewFullSyncAlignment;
    } else {
      const isNew = !result.some((r2) => r2.some((v, idx) => v !== void 0 && v === lineAlignment[idx]));
      shouldAdd = isNew;
    }
    if (shouldAdd) {
      result.push(lineAlignment);
    } else {
      if (m2.length.isGreaterThan(new $gD(1, 0))) {
        result.push([
          m2.output1Pos ? m2.output1Pos.lineNumber + 1 : void 0,
          m2.inputPos.lineNumber + 1,
          m2.output2Pos ? m2.output2Pos.lineNumber + 1 : void 0
        ]);
      }
    }
  }
  const finalLineAlignment = [m.input1Range.endLineNumberExclusive, m.baseRange.endLineNumberExclusive, m.input2Range.endLineNumberExclusive];
  result = result.filter((r2) => r2.every((v, idx) => v !== finalLineAlignment[idx]));
  result.push(finalLineAlignment);
  $kd(() => $ld(result.map((r2) => r2[0]).filter($Hg), (a, b) => a < b) && $ld(result.map((r2) => r2[1]).filter($Hg), (a, b) => a <= b) && $ld(result.map((r2) => r2[2]).filter($Hg), (a, b) => a < b) && result.every((alignment) => alignment.filter($Hg).length >= 2));
  return result;
}
function toEqualRangeMappings(diffs, inputRange, outputRange) {
  const result = [];
  let equalRangeInputStart = inputRange.getStartPosition();
  let equalRangeOutputStart = outputRange.getStartPosition();
  for (const d of diffs) {
    const equalRangeMapping2 = new $GHb($9C.fromPositions(equalRangeInputStart, d.inputRange.getStartPosition()), $9C.fromPositions(equalRangeOutputStart, d.outputRange.getStartPosition()));
    $kd(() => $yHb(equalRangeMapping2.inputRange).equals($yHb(equalRangeMapping2.outputRange)));
    if (!equalRangeMapping2.inputRange.isEmpty()) {
      result.push(equalRangeMapping2);
    }
    equalRangeInputStart = d.inputRange.getEndPosition();
    equalRangeOutputStart = d.outputRange.getEndPosition();
  }
  const equalRangeMapping = new $GHb($9C.fromPositions(equalRangeInputStart, inputRange.getEndPosition()), $9C.fromPositions(equalRangeOutputStart, outputRange.getEndPosition()));
  $kd(() => $yHb(equalRangeMapping.inputRange).equals($yHb(equalRangeMapping.outputRange)));
  if (!equalRangeMapping.inputRange.isEmpty()) {
    result.push(equalRangeMapping);
  }
  return result;
}
function splitUpCommonEqualRangeMappings(equalRangeMappings1, equalRangeMappings2) {
  const result = [];
  const events = [];
  for (const [input, rangeMappings] of [[0, equalRangeMappings1], [1, equalRangeMappings2]]) {
    for (const rangeMapping of rangeMappings) {
      events.push({
        input,
        start: true,
        inputPos: rangeMapping.inputRange.getStartPosition(),
        outputPos: rangeMapping.outputRange.getStartPosition()
      });
      events.push({
        input,
        start: false,
        inputPos: rangeMapping.inputRange.getEndPosition(),
        outputPos: rangeMapping.outputRange.getEndPosition()
      });
    }
  }
  events.sort($9b((m) => m.inputPos, $8C.compare));
  const starts = [void 0, void 0];
  let lastInputPos;
  for (const event of events) {
    if (lastInputPos && starts.some((s) => !!s)) {
      const length = $zHb(lastInputPos, event.inputPos);
      if (!length.isZero()) {
        result.push({
          inputPos: lastInputPos,
          length,
          output1Pos: starts[0],
          output2Pos: starts[1]
        });
        if (starts[0]) {
          starts[0] = $AHb(starts[0], length);
        }
        if (starts[1]) {
          starts[1] = $AHb(starts[1], length);
        }
      }
    }
    starts[event.input] = event.start ? event.outputPos : void 0;
    lastInputPos = event.inputPos;
  }
  return result;
}

// out-build/vs/workbench/contrib/mergeEditor/browser/view/viewZones.js
var $fcc = class {
  constructor(e, f, g) {
    this.e = e;
    this.f = f;
    this.g = g;
    this.b = new $rIb(this.e);
    this.c = new $rIb(this.f);
    this.d = new $rIb(this.g);
  }
  computeViewZones(reader, viewModel, options3) {
    let input1LinesAdded = 0;
    let input2LinesAdded = 0;
    let baseLinesAdded = 0;
    let resultLinesAdded = 0;
    const input1ViewZones = [];
    const input2ViewZones = [];
    const baseViewZones = [];
    const resultViewZones = [];
    const model = viewModel.model;
    const resultDiffs = model.baseResultDiffs.read(reader);
    const baseRangeWithStoreAndTouchingDiffs = join2(model.modifiedBaseRanges.read(reader), resultDiffs, (baseRange, diff3) => baseRange.baseRange.touches(diff3.inputRange) ? CompareResult.neitherLessOrGreaterThan : $jHb.compareByStart(baseRange.baseRange, diff3.inputRange));
    const shouldShowCodeLenses = options3.codeLensesVisible;
    const showNonConflictingChanges = options3.showNonConflictingChanges;
    let lastModifiedBaseRange = void 0;
    let lastBaseResultDiff = void 0;
    for (const m of baseRangeWithStoreAndTouchingDiffs) {
      if (shouldShowCodeLenses && m.left && (m.left.isConflicting || showNonConflictingChanges || !model.isHandled(m.left).read(reader))) {
        const actions = new $sIb(viewModel, m.left);
        if (options3.shouldAlignResult || !actions.inputIsEmpty.read(reader)) {
          input1ViewZones.push(new CommandViewZone(this.b, m.left.input1Range.startLineNumber - 1, actions.itemsInput1));
          input2ViewZones.push(new CommandViewZone(this.c, m.left.input2Range.startLineNumber - 1, actions.itemsInput2));
          if (options3.shouldAlignBase) {
            baseViewZones.push(new Placeholder(m.left.baseRange.startLineNumber - 1, 16));
          }
        }
        const afterLineNumber = m.left.baseRange.startLineNumber + (lastBaseResultDiff?.resultingDeltaFromOriginalToModified ?? 0) - 1;
        resultViewZones.push(new CommandViewZone(this.d, afterLineNumber, actions.resultItems));
      }
      const lastResultDiff = m.rights.at(-1);
      if (lastResultDiff) {
        lastBaseResultDiff = lastResultDiff;
      }
      let alignedLines;
      if (m.left) {
        alignedLines = $ecc(m.left).map((a) => ({
          input1Line: a[0],
          baseLine: a[1],
          input2Line: a[2],
          resultLine: void 0
        }));
        lastModifiedBaseRange = m.left;
        alignedLines[alignedLines.length - 1].resultLine = m.left.baseRange.endLineNumberExclusive + (lastBaseResultDiff ? lastBaseResultDiff.resultingDeltaFromOriginalToModified : 0);
      } else {
        alignedLines = [{
          baseLine: lastResultDiff.inputRange.endLineNumberExclusive,
          input1Line: lastResultDiff.inputRange.endLineNumberExclusive + (lastModifiedBaseRange ? lastModifiedBaseRange.input1Range.endLineNumberExclusive - lastModifiedBaseRange.baseRange.endLineNumberExclusive : 0),
          input2Line: lastResultDiff.inputRange.endLineNumberExclusive + (lastModifiedBaseRange ? lastModifiedBaseRange.input2Range.endLineNumberExclusive - lastModifiedBaseRange.baseRange.endLineNumberExclusive : 0),
          resultLine: lastResultDiff.outputRange.endLineNumberExclusive
        }];
      }
      for (const { input1Line, baseLine, input2Line, resultLine } of alignedLines) {
        if (!options3.shouldAlignBase && (input1Line === void 0 || input2Line === void 0)) {
          continue;
        }
        const input1Line_ = input1Line !== void 0 ? input1Line + input1LinesAdded : -1;
        const input2Line_ = input2Line !== void 0 ? input2Line + input2LinesAdded : -1;
        const baseLine_ = baseLine + baseLinesAdded;
        const resultLine_ = resultLine !== void 0 ? resultLine + resultLinesAdded : -1;
        const max = Math.max(options3.shouldAlignBase ? baseLine_ : 0, input1Line_, input2Line_, options3.shouldAlignResult ? resultLine_ : 0);
        if (input1Line !== void 0) {
          const diffInput1 = max - input1Line_;
          if (diffInput1 > 0) {
            input1ViewZones.push(new Spacer(input1Line - 1, diffInput1));
            input1LinesAdded += diffInput1;
          }
        }
        if (input2Line !== void 0) {
          const diffInput2 = max - input2Line_;
          if (diffInput2 > 0) {
            input2ViewZones.push(new Spacer(input2Line - 1, diffInput2));
            input2LinesAdded += diffInput2;
          }
        }
        if (options3.shouldAlignBase) {
          const diffBase = max - baseLine_;
          if (diffBase > 0) {
            baseViewZones.push(new Spacer(baseLine - 1, diffBase));
            baseLinesAdded += diffBase;
          }
        }
        if (options3.shouldAlignResult && resultLine !== void 0) {
          const diffResult = max - resultLine_;
          if (diffResult > 0) {
            resultViewZones.push(new Spacer(resultLine - 1, diffResult));
            resultLinesAdded += diffResult;
          }
        }
      }
    }
    return new $gcc(input1ViewZones, input2ViewZones, baseViewZones, resultViewZones);
  }
};
var $gcc = class {
  constructor(input1ViewZones, input2ViewZones, baseViewZones, resultViewZones) {
    this.input1ViewZones = input1ViewZones;
    this.input2ViewZones = input2ViewZones;
    this.baseViewZones = baseViewZones;
    this.resultViewZones = resultViewZones;
  }
};
var $hcc = class {
};
var Spacer = class extends $hcc {
  constructor(b, c) {
    super();
    this.b = b;
    this.c = c;
  }
  create(viewZoneChangeAccessor, viewZoneIdsToCleanUp, disposableStore) {
    viewZoneIdsToCleanUp.push(viewZoneChangeAccessor.addZone({
      afterLineNumber: this.b,
      heightInLines: this.c,
      domNode: $("div.diagonal-fill")
    }));
  }
};
var Placeholder = class extends $hcc {
  constructor(b, c) {
    super();
    this.b = b;
    this.c = c;
  }
  create(viewZoneChangeAccessor, viewZoneIdsToCleanUp, disposableStore) {
    viewZoneIdsToCleanUp.push(viewZoneChangeAccessor.addZone({
      afterLineNumber: this.b,
      heightInPx: this.c,
      domNode: $("div.conflict-actions-placeholder")
    }));
  }
};
var CommandViewZone = class extends $hcc {
  constructor(b, c, d) {
    super();
    this.b = b;
    this.c = c;
    this.d = d;
  }
  create(viewZoneChangeAccessor, viewZoneIdsToCleanUp, disposableStore) {
    disposableStore.add(this.b.createWidget(viewZoneChangeAccessor, this.c, this.d, viewZoneIdsToCleanUp));
  }
};

// out-build/vs/workbench/contrib/mergeEditor/browser/view/editors/inputCodeEditorView.js
var $dIb = class $dIb2 extends $_Hb {
  constructor(inputNumber, viewModel, instantiationService, contextMenuService, configurationService) {
    super(instantiationService, viewModel, configurationService);
    this.inputNumber = inputNumber;
    this.otherInputNumber = this.inputNumber === 1 ? 2 : 1;
    this.w = $4d({ debugName: `input${this.inputNumber}.modifiedBaseRangeGutterItemInfos` }, (reader) => {
      const viewModel2 = this.viewModel.read(reader);
      if (!viewModel2) {
        return [];
      }
      const model = viewModel2.model;
      const inputNumber2 = this.inputNumber;
      const showNonConflictingChanges = viewModel2.showNonConflictingChanges.read(reader);
      return model.modifiedBaseRanges.read(reader).filter((r2) => r2.getInputDiffs(this.inputNumber).length > 0 && (showNonConflictingChanges || r2.isConflicting || !model.isHandled(r2).read(reader))).map((baseRange, idx) => new $eIb(idx.toString(), baseRange, inputNumber2, viewModel2));
    });
    this.y = $4d({ debugName: `input${this.inputNumber}.decorations` }, (reader) => {
      const viewModel2 = this.viewModel.read(reader);
      if (!viewModel2) {
        return [];
      }
      const model = viewModel2.model;
      const textModel = (this.inputNumber === 1 ? model.input1 : model.input2).textModel;
      const activeModifiedBaseRange = viewModel2.activeModifiedBaseRange.read(reader);
      const result = new Array();
      const showNonConflictingChanges = viewModel2.showNonConflictingChanges.read(reader);
      const showDeletionMarkers = this.j.read(reader);
      const diffWithThis = viewModel2.baseCodeEditorView.read(reader) !== void 0 && viewModel2.baseShowDiffAgainst.read(reader) === this.inputNumber;
      const useSimplifiedDecorations = !diffWithThis && this.n.read(reader);
      for (const modifiedBaseRange of model.modifiedBaseRanges.read(reader)) {
        const range = modifiedBaseRange.getInputRange(this.inputNumber);
        if (!range) {
          continue;
        }
        const blockClassNames = ["merge-editor-block"];
        let blockPadding = [0, 0, 0, 0];
        const isHandled = model.isInputHandled(modifiedBaseRange, this.inputNumber).read(reader);
        if (isHandled) {
          blockClassNames.push("handled");
        }
        if (modifiedBaseRange === activeModifiedBaseRange) {
          blockClassNames.push("focused");
          blockPadding = [0, 2, 0, 2];
        }
        if (modifiedBaseRange.isConflicting) {
          blockClassNames.push("conflicting");
        }
        const inputClassName = this.inputNumber === 1 ? "input i1" : "input i2";
        blockClassNames.push(inputClassName);
        if (!modifiedBaseRange.isConflicting && !showNonConflictingChanges && isHandled) {
          continue;
        }
        if (useSimplifiedDecorations && !isHandled) {
          blockClassNames.push("use-simplified-decorations");
        }
        result.push({
          range: range.toInclusiveRangeOrEmpty(),
          options: {
            showIfCollapsed: true,
            blockClassName: blockClassNames.join(" "),
            blockPadding,
            blockIsAfterEnd: range.startLineNumber > textModel.getLineCount(),
            description: "Merge Editor",
            minimap: {
              position: 2,
              color: { id: isHandled ? $6Hb : $7Hb }
            },
            overviewRuler: modifiedBaseRange.isConflicting ? {
              position: OverviewRulerLane.Center,
              color: { id: isHandled ? $6Hb : $7Hb }
            } : void 0
          }
        });
        if (!useSimplifiedDecorations && (modifiedBaseRange.isConflicting || !model.isHandled(modifiedBaseRange).read(reader))) {
          const inputDiffs = modifiedBaseRange.getInputDiffs(this.inputNumber);
          for (const diff3 of inputDiffs) {
            const range2 = diff3.outputRange.toInclusiveRange();
            if (range2) {
              result.push({
                range: range2,
                options: {
                  className: `merge-editor-diff ${inputClassName}`,
                  description: "Merge Editor",
                  isWholeLine: true
                }
              });
            }
            if (diff3.rangeMappings) {
              for (const d of diff3.rangeMappings) {
                if (showDeletionMarkers || !d.outputRange.isEmpty()) {
                  result.push({
                    range: d.outputRange,
                    options: {
                      className: d.outputRange.isEmpty() ? `merge-editor-diff-empty-word ${inputClassName}` : `merge-editor-diff-word ${inputClassName}`,
                      description: "Merge Editor",
                      showIfCollapsed: true
                    }
                  });
                }
              }
            }
          }
        }
      }
      return result;
    });
    this.a.root.classList.add(`input`);
    this.B(new $$Hb(this.editor, this.a.gutterDiv, {
      getIntersectingGutterItems: (range, reader) => {
        if (this.f.read(reader)) {
          return this.w.read(reader);
        } else {
          return [];
        }
      },
      createView: (item, target) => new $fIb(item, target, contextMenuService)
    }));
    this.B($aIb(this, (baseRange, viewModel2) => viewModel2.model.translateBaseRangeToInput(this.inputNumber, baseRange)));
    this.B(instantiationService.createInstance($bIb, inputNumber === 1 ? $bJ.MergeInput1Toolbar : $bJ.MergeInput2Toolbar, this.a.toolbar));
    this.B($ud({ debugName: `input${this.inputNumber}: update labels & text model` }, (reader) => {
      const vm = this.viewModel.read(reader);
      if (!vm) {
        return;
      }
      this.editor.setModel(this.inputNumber === 1 ? vm.model.input1.textModel : vm.model.input2.textModel);
      const title = this.inputNumber === 1 ? vm.model.input1.title || localize(8036, null) : vm.model.input2.title || localize(8037, null);
      const description = this.inputNumber === 1 ? vm.model.input1.description : vm.model.input2.description;
      const detail2 = this.inputNumber === 1 ? vm.model.input1.detail : vm.model.input2.detail;
      $dk(this.a.title, ...$B1(title));
      $dk(this.a.description, ...description ? $B1(description) : []);
      $dk(this.a.detail, ...detail2 ? $B1(detail2) : []);
    }));
    this.B($oHb(this.editor, this.y));
  }
};
$dIb = __decorate([
  __param(2, $Pk),
  __param(3, $50),
  __param(4, $kl)
], $dIb);
var $eIb = class {
  constructor(id2, b, f, g) {
    this.id = id2;
    this.b = b;
    this.f = f;
    this.g = g;
    this.a = this.g.model;
    this.range = this.b.getInputRange(this.f);
    this.enabled = this.a.isUpToDate;
    this.toggleState = $2d(this, (reader) => {
      const input = this.a.getState(this.b).read(reader).getInput(this.f);
      return input === 2 && !this.b.isOrderRelevant ? 1 : input;
    });
    this.state = $2d(this, (reader) => {
      const active = this.g.activeModifiedBaseRange.read(reader);
      if (!this.a.hasBaseRange(this.b)) {
        return { handled: false, focused: false };
      }
      return {
        handled: this.a.isHandled(this.b).read(reader),
        focused: this.b === active
      };
    });
  }
  setState(value, tx) {
    this.g.setState(this.b, this.a.getState(this.b).get().withInputValue(this.f, value), tx, this.f);
  }
  toggleBothSides() {
    $ce((tx) => {
      const state = this.a.getState(this.b).get();
      this.a.setState(this.b, state.toggle(this.f).toggle(this.f === 1 ? 2 : 1), true, tx);
    });
  }
  getContextMenuActions() {
    const state = this.a.getState(this.b).get();
    const handled = this.a.isHandled(this.b).get();
    const update = (newState) => {
      $ce((tx) => {
        return this.g.setState(this.b, newState, tx, this.f);
      });
    };
    function action(id2, label3, targetState, checked) {
      const action2 = new $Um(id2, label3, void 0, true, () => {
        update(targetState);
      });
      action2.checked = checked;
      return action2;
    }
    const both = state.includesInput1 && state.includesInput2;
    return [
      this.b.input1Diffs.length > 0 ? action("mergeEditor.acceptInput1", localize(8038, null, this.a.input1.title), state.toggle(1), state.includesInput1) : void 0,
      this.b.input2Diffs.length > 0 ? action("mergeEditor.acceptInput2", localize(8039, null, this.a.input2.title), state.toggle(2), state.includesInput2) : void 0,
      this.b.isConflicting ? $uHb(action("mergeEditor.acceptBoth", localize(8040, null), state.withInputValue(1, !both).withInputValue(2, !both), both), { enabled: this.b.canBeCombined }) : void 0,
      new $Wm(),
      this.b.isConflicting ? $uHb(action("mergeEditor.swap", localize(8041, null), state.swap(), false), { enabled: !state.kind && (!both || this.b.isOrderRelevant) }) : void 0,
      $uHb(new $Um("mergeEditor.markAsHandled", localize(8042, null), void 0, true, () => {
        $ce((tx) => {
          this.a.setHandled(this.b, !handled, tx);
        });
      }), { checked: handled })
    ].filter($Hg);
  }
};
var $fIb = class extends $3c {
  constructor(item, target, contextMenuService) {
    super();
    this.f = $he(this, false);
    this.a = $he(this, item);
    const checkBox = new $Q1({
      isChecked: false,
      title: "",
      icon: $6l.check,
      ...$u$
    });
    checkBox.domNode.classList.add("accept-conflict-group");
    this.B($_i(checkBox.domNode, $7j.MOUSE_DOWN, (e) => {
      const item2 = this.a.get();
      if (!item2) {
        return;
      }
      if (e.button === /* Right */
      2) {
        e.stopPropagation();
        e.preventDefault();
        contextMenuService.showContextMenu({
          getAnchor: () => checkBox.domNode,
          getActions: () => item2.getContextMenuActions()
        });
      } else if (e.button === /* Middle */
      1) {
        e.stopPropagation();
        e.preventDefault();
        item2.toggleBothSides();
      }
    }));
    this.B($td((reader) => {
      const item2 = this.a.read(reader);
      const value = item2.toggleState.read(reader);
      const iconMap = {
        [
          0
          /* InputState.excluded */
        ]: { icon: void 0, checked: false, title: localize(8043, null) },
        [
          3
          /* InputState.unrecognized */
        ]: { icon: $6l.circleFilled, checked: false, title: localize(8044, null) },
        [
          1
          /* InputState.first */
        ]: { icon: $6l.check, checked: true, title: localize(8045, null) },
        [
          2
          /* InputState.second */
        ]: { icon: $6l.checkAll, checked: true, title: localize(8046, null) }
      };
      const state = iconMap[value];
      checkBox.setIcon(state.icon);
      checkBox.checked = state.checked;
      checkBox.setTitle(state.title);
      if (!item2.enabled.read(reader)) {
        checkBox.disable();
      } else {
        checkBox.enable();
      }
    }));
    this.B($td((reader) => {
      const state = this.a.read(reader).state.read(reader);
      const classNames = [
        "merge-accept-gutter-marker",
        state.handled && "handled",
        state.focused && "focused",
        this.f.read(reader) ? "multi-line" : "single-line"
      ];
      target.className = classNames.filter((c) => typeof c === "string").join(" ");
    }));
    this.B(checkBox.onChange(() => {
      $ce((tx) => {
        this.a.get().setState(checkBox.checked, tx);
      });
    }));
    target.appendChild(h("div.background", [$wg]).root);
    target.appendChild(this.b = h("div.checkbox", [h("div.checkbox-background", [checkBox.domNode])]).root);
  }
  layout(top2, height, viewTop, viewHeight) {
    const checkboxHeight = this.b.clientHeight;
    const middleHeight = height / 2 - checkboxHeight / 2;
    const margin = checkboxHeight;
    let effectiveCheckboxTop = top2 + middleHeight;
    const preferredViewPortRange = [
      margin,
      viewTop + viewHeight - margin - checkboxHeight
    ];
    const preferredParentRange = [
      top2 + margin,
      top2 + height - checkboxHeight - margin
    ];
    if (preferredParentRange[0] < preferredParentRange[1]) {
      effectiveCheckboxTop = $4i(effectiveCheckboxTop, preferredViewPortRange[0], preferredViewPortRange[1]);
      effectiveCheckboxTop = $4i(effectiveCheckboxTop, preferredParentRange[0], preferredParentRange[1]);
    }
    this.b.style.top = `${effectiveCheckboxTop - top2}px`;
    $ce((tx) => {
      this.f.set(height > 30, tx);
    });
  }
  update(baseRange) {
    $ce((tx) => {
      this.a.set(baseRange, tx);
    });
  }
};

// out-build/vs/workbench/contrib/mergeEditor/browser/view/editors/resultCodeEditorView.js
var $pIb = class $pIb2 extends $_Hb {
  constructor(viewModel, instantiationService, w, configurationService) {
    super(instantiationService, viewModel, configurationService);
    this.w = w;
    this.y = $2d(this, (reader) => {
      const viewModel2 = this.viewModel.read(reader);
      if (!viewModel2) {
        return [];
      }
      const model = viewModel2.model;
      const textModel = model.resultTextModel;
      const result = new Array();
      const baseRangeWithStoreAndTouchingDiffs = join2(model.modifiedBaseRanges.read(reader), model.baseResultDiffs.read(reader), (baseRange, diff3) => baseRange.baseRange.touches(diff3.inputRange) ? CompareResult.neitherLessOrGreaterThan : $jHb.compareByStart(baseRange.baseRange, diff3.inputRange));
      const activeModifiedBaseRange = viewModel2.activeModifiedBaseRange.read(reader);
      const showNonConflictingChanges = viewModel2.showNonConflictingChanges.read(reader);
      for (const m of baseRangeWithStoreAndTouchingDiffs) {
        const modifiedBaseRange = m.left;
        if (modifiedBaseRange) {
          const blockClassNames = ["merge-editor-block"];
          let blockPadding = [0, 0, 0, 0];
          const isHandled = model.isHandled(modifiedBaseRange).read(reader);
          if (isHandled) {
            blockClassNames.push("handled");
          }
          if (modifiedBaseRange === activeModifiedBaseRange) {
            blockClassNames.push("focused");
            blockPadding = [0, 2, 0, 2];
          }
          if (modifiedBaseRange.isConflicting) {
            blockClassNames.push("conflicting");
          }
          blockClassNames.push("result");
          if (!modifiedBaseRange.isConflicting && !showNonConflictingChanges && isHandled) {
            continue;
          }
          const range = model.getLineRangeInResult(modifiedBaseRange.baseRange, reader);
          result.push({
            range: range.toInclusiveRangeOrEmpty(),
            options: {
              showIfCollapsed: true,
              blockClassName: blockClassNames.join(" "),
              blockPadding,
              blockIsAfterEnd: range.startLineNumber > textModel.getLineCount(),
              description: "Result Diff",
              minimap: {
                position: 2,
                color: { id: isHandled ? $6Hb : $7Hb }
              },
              overviewRuler: modifiedBaseRange.isConflicting ? {
                position: OverviewRulerLane.Center,
                color: { id: isHandled ? $6Hb : $7Hb }
              } : void 0
            }
          });
        }
        if (!modifiedBaseRange || modifiedBaseRange.isConflicting) {
          for (const diff3 of m.rights) {
            const range = diff3.outputRange.toInclusiveRange();
            if (range) {
              result.push({
                range,
                options: {
                  className: `merge-editor-diff result`,
                  description: "Merge Editor",
                  isWholeLine: true
                }
              });
            }
            if (diff3.rangeMappings) {
              for (const d of diff3.rangeMappings) {
                result.push({
                  range: d.outputRange,
                  options: {
                    className: `merge-editor-diff-word result`,
                    description: "Merge Editor"
                  }
                });
              }
            }
          }
        }
      }
      return result;
    });
    this.editor.invokeWithinContext((accessor) => {
      const contextKeyService = accessor.get($on);
      const isMergeResultEditor = $hIb.bindTo(contextKeyService);
      isMergeResultEditor.set(true);
      this.B($1c(() => isMergeResultEditor.reset()));
    });
    this.a.gutterDiv.style.width = "5px";
    this.a.root.classList.add(`result`);
    this.B($xd((reader, store) => {
      if (this.f.read(reader)) {
        store.add(new $$Hb(this.editor, this.a.gutterDiv, {
          getIntersectingGutterItems: (range, reader2) => [],
          createView: (item, target) => {
            throw new $vb();
          }
        }));
      }
    }));
    this.B($td((reader) => {
      const vm = this.viewModel.read(reader);
      if (!vm) {
        return;
      }
      this.editor.setModel(vm.model.resultTextModel);
      $dk(this.a.title, ...$B1(localize(8047, null)));
      $dk(this.a.description, ...$B1(this.w.getUriLabel(vm.model.resultTextModel.uri, { relative: true })));
    }));
    const remainingConflictsActionBar = this.B(new $LZ(this.a.detail));
    this.B($td((reader) => {
      const vm = this.viewModel.read(reader);
      if (!vm) {
        return;
      }
      const model = vm.model;
      if (!model) {
        return;
      }
      const count = model.unhandledConflictsCount.read(reader);
      const text2 = count === 1 ? localize(8048, null, count) : localize(8049, null, count);
      remainingConflictsActionBar.clear();
      remainingConflictsActionBar.push({
        class: void 0,
        enabled: count > 0,
        id: "nextConflict",
        label: text2,
        run() {
          vm.model.telemetry.reportConflictCounterClicked();
          vm.goToNextModifiedBaseRange((m) => !model.isHandled(m).get());
        },
        tooltip: count > 0 ? localize(8050, null) : localize(8051, null)
      });
    }));
    this.B($oHb(this.editor, this.y));
    this.B($aIb(this, (baseRange, viewModel2) => viewModel2.model.translateBaseRangeToResult(baseRange)));
    this.B(instantiationService.createInstance($bIb, $bJ.MergeInputResultToolbar, this.a.toolbar));
  }
};
$pIb = __decorate([
  __param(1, $Pk),
  __param(2, $ZI),
  __param(3, $kl)
], $pIb);

// out-build/vs/workbench/contrib/mergeEditor/browser/view/mergeEditor.js
var $icc_1;
var MergeEditorLayoutStore_1;
var $icc = class $icc2 extends $aub {
  static {
    $icc_1 = this;
  }
  static {
    this.ID = "mergeEditor";
  }
  get viewModel() {
    return this.f;
  }
  get inputModel() {
    return this.gc;
  }
  get model() {
    return this.inputModel.get()?.model;
  }
  get hc() {
    return !!this.mc.getValue("mergeEditor.writableInputs");
  }
  constructor(group2, instantiation, lc, telemetryService, storageService, themeService, textResourceConfigurationService, mc, editorService, editorGroupService, fileService, nc, oc) {
    super($icc_1.ID, group2, telemetryService, instantiation, storageService, textResourceConfigurationService, themeService, editorService, editorGroupService, fileService);
    this.lc = lc;
    this.mc = mc;
    this.nc = nc;
    this.oc = oc;
    this.c = new $2c();
    this.f = $he(this, void 0);
    this.Sb = this.B(new $4c());
    this.Tb = this.B(this.m.createInstance($dIb, 1, this.f));
    this.Ub = $he(this, void 0);
    this.Vb = $he(this, void 0);
    this.Wb = this.B(this.m.createInstance($dIb, 2, this.f));
    this.Xb = this.B(this.m.createInstance($pIb, this.f));
    this.Yb = this.m.createInstance(MergeEditorLayoutStore);
    this.Zb = $he(this, this.Yb.value);
    this.$b = $gIb.bindTo(this.lc);
    this.ac = $iIb.bindTo(this.lc);
    this.bc = $jIb.bindTo(this.lc);
    this.cc = $kIb.bindTo(this.lc);
    this.dc = $nIb.bindTo(this.lc);
    this.ec = $mIb.bindTo(this.lc);
    this.fc = $lIb.bindTo(this.lc);
    this.gc = $he(this, void 0);
    this.ic = new $fcc(this.Tb.editor, this.Wb.editor, this.Xb.editor);
    this.jc = $G9("mergeEditor.showCodeLenses", true, this.oc);
    this.kc = this.B(new $dcc(this.f, this.Tb, this.Wb, this.Ub, this.Xb, this.Zb));
    this.pc = new $ze();
    this.onDidChangeSizeConstraints = this.pc.event;
    this.wc = this.B(new $2c());
    this.Cc = this.m.createInstance($wHb, "mergeEditor/showNonConflictingChanges");
    this.Dc = $he(this, this.Cc.get() ?? false);
  }
  dispose() {
    this.c.dispose();
    this.$b.reset();
    this.ac.reset();
    this.fc.reset();
    super.dispose();
  }
  get minimumWidth() {
    return this.Yb.value.kind === "mixed" ? this.Tb.view.minimumWidth + this.Wb.view.minimumWidth : this.Tb.view.minimumWidth + this.Wb.view.minimumWidth + this.Xb.view.minimumWidth;
  }
  // #endregion
  getTitle() {
    if (this.input) {
      return this.input.getName();
    }
    return localize(8052, null);
  }
  Lb(parent, initialOptions) {
    this.$ = parent;
    parent.classList.add("merge-editor");
    this.xc(this.Yb.value);
    this.sc(initialOptions);
  }
  Mb(options3) {
    this.sc(options3);
  }
  sc(options3) {
    const inputOptions2 = $vHb(options3, {
      minimap: { enabled: false },
      glyphMargin: false,
      lineNumbersMinChars: 2,
      readOnly: !this.hc
    });
    this.Tb.updateOptions(inputOptions2);
    this.Wb.updateOptions(inputOptions2);
    this.Vb.set({ ...this.Wb.editor.getRawOptions() }, void 0);
    this.Xb.updateOptions(options3);
  }
  Nb() {
    return this.Xb.editor;
  }
  layout(dimension) {
    this.Sb.value?.layout(dimension.width, dimension.height);
  }
  async setInput(input, options3, context, token) {
    if (!(input instanceof $7Ob)) {
      throw new $vb("ONLY MergeEditorInput is supported");
    }
    await super.setInput(input, options3, context, token);
    this.c.clear();
    $ce((tx) => {
      this.f.set(void 0, tx);
      this.gc.set(void 0, tx);
    });
    const inputModel = await input.resolve();
    const model = inputModel.model;
    const viewModel = this.m.createInstance($qIb, model, this.Tb, this.Wb, this.Xb, this.Ub, this.Dc);
    model.telemetry.reportMergeEditorOpened({
      combinableConflictCount: model.combinableConflictCount,
      conflictCount: model.conflictCount,
      baseTop: this.Zb.get().showBaseAtTop,
      baseVisible: this.Zb.get().showBase,
      isColumnView: this.Zb.get().kind === "columns"
    });
    $ce((tx) => {
      this.f.set(viewModel, tx);
      this.gc.set(inputModel, tx);
    });
    this.c.add(viewModel);
    this.dc.set(inputModel.resultUri.toString());
    this.ec.set(model.base.uri.toString());
    this.c.add($1c(() => {
      this.ec.reset();
      this.dc.reset();
    }));
    this.c.add($xd((reader, store) => {
      const baseView = this.Ub.read(reader);
      this.Xb.editor.changeViewZones((resultViewZoneAccessor) => {
        const layout = this.Zb.read(reader);
        const shouldAlignResult = layout.kind === "columns";
        const shouldAlignBase = layout.kind === "mixed" && !layout.showBaseAtTop;
        this.Tb.editor.changeViewZones((input1ViewZoneAccessor) => {
          this.Wb.editor.changeViewZones((input2ViewZoneAccessor) => {
            if (baseView) {
              baseView.editor.changeViewZones((baseViewZoneAccessor) => {
                store.add(this.uc(reader, viewModel, this.Tb.editor, input1ViewZoneAccessor, this.Wb.editor, input2ViewZoneAccessor, baseView.editor, baseViewZoneAccessor, shouldAlignBase, this.Xb.editor, resultViewZoneAccessor, shouldAlignResult));
              });
            } else {
              store.add(this.uc(reader, viewModel, this.Tb.editor, input1ViewZoneAccessor, this.Wb.editor, input2ViewZoneAccessor, void 0, void 0, false, this.Xb.editor, resultViewZoneAccessor, shouldAlignResult));
            }
          });
        });
      });
      this.kc.updateScrolling();
    }));
    const viewState = this.jb(input, context);
    if (viewState) {
      this.zc(viewState);
    } else {
      this.c.add($tHb(model.onInitialized, () => {
        const firstConflict = model.modifiedBaseRanges.get().find((r2) => r2.isConflicting);
        if (!firstConflict) {
          return;
        }
        this.Tb.editor.revealLineInCenter(firstConflict.input1Range.startLineNumber);
        $ce((tx) => {
          viewModel.setActiveModifiedBaseRange(firstConflict, tx);
        });
      }));
    }
    const mirrorWordWrapTransientState = (candidate) => {
      const candidateState = $UIb(candidate, this.nc);
      $TIb(model.input2.textModel, candidateState, this.nc);
      $TIb(model.input1.textModel, candidateState, this.nc);
      $TIb(model.resultTextModel, candidateState, this.nc);
      const baseTextModel = this.Ub.get()?.editor.getModel();
      if (baseTextModel) {
        $TIb(baseTextModel, candidateState, this.nc);
      }
    };
    this.c.add(this.nc.onDidChangeTransientModelProperty((candidate) => {
      mirrorWordWrapTransientState(candidate);
    }));
    mirrorWordWrapTransientState(this.Xb.editor.getModel());
    const that = this;
    this.c.add(new class {
      constructor() {
        this.b = new $2c();
        for (const model2 of this.c()) {
          this.b.add(model2.onDidChangeContent(() => this.d()));
        }
      }
      dispose() {
        this.b.dispose();
      }
      *c() {
        yield model.base;
        yield model.input1.textModel;
        yield model.input2.textModel;
      }
      d() {
        for (const model2 of this.c()) {
          if (model2.getValueLength() > 0) {
            return;
          }
        }
        that.u.replaceEditors([{ editor: input, replacement: { resource: input.result, options: { preserveFocus: true } }, forceReplaceDirty: true }], that.group);
      }
    }());
  }
  uc(reader, viewModel, input1Editor, input1ViewZoneAccessor, input2Editor, input2ViewZoneAccessor, baseEditor, baseViewZoneAccessor, shouldAlignBase, resultEditor, resultViewZoneAccessor, shouldAlignResult) {
    const input1ViewZoneIds = [];
    const input2ViewZoneIds = [];
    const baseViewZoneIds = [];
    const resultViewZoneIds = [];
    const viewZones = this.ic.computeViewZones(reader, viewModel, {
      codeLensesVisible: this.jc.read(reader),
      showNonConflictingChanges: this.Dc.read(reader),
      shouldAlignBase,
      shouldAlignResult
    });
    const disposableStore = new $2c();
    if (baseViewZoneAccessor) {
      for (const v of viewZones.baseViewZones) {
        v.create(baseViewZoneAccessor, baseViewZoneIds, disposableStore);
      }
    }
    for (const v of viewZones.resultViewZones) {
      v.create(resultViewZoneAccessor, resultViewZoneIds, disposableStore);
    }
    for (const v of viewZones.input1ViewZones) {
      v.create(input1ViewZoneAccessor, input1ViewZoneIds, disposableStore);
    }
    for (const v of viewZones.input2ViewZones) {
      v.create(input2ViewZoneAccessor, input2ViewZoneIds, disposableStore);
    }
    disposableStore.add({
      dispose: () => {
        input1Editor.changeViewZones((a) => {
          for (const zone of input1ViewZoneIds) {
            a.removeZone(zone);
          }
        });
        input2Editor.changeViewZones((a) => {
          for (const zone of input2ViewZoneIds) {
            a.removeZone(zone);
          }
        });
        baseEditor?.changeViewZones((a) => {
          for (const zone of baseViewZoneIds) {
            a.removeZone(zone);
          }
        });
        resultEditor.changeViewZones((a) => {
          for (const zone of resultViewZoneIds) {
            a.removeZone(zone);
          }
        });
      }
    });
    return disposableStore;
  }
  setOptions(options3) {
    super.setOptions(options3);
    if (options3) {
      applyTextEditorOptions(
        options3,
        this.Xb.editor,
        0
        /* ScrollType.Smooth */
      );
    }
  }
  clearInput() {
    super.clearInput();
    this.c.clear();
    for (const { editor } of [this.Tb, this.Wb, this.Xb]) {
      editor.setModel(null);
    }
  }
  focus() {
    super.focus();
    (this.getControl() ?? this.Xb.editor).focus();
  }
  hasFocus() {
    for (const { editor } of [this.Tb, this.Wb, this.Xb]) {
      if (editor.hasTextFocus()) {
        return true;
      }
    }
    return super.hasFocus();
  }
  Z(visible) {
    super.Z(visible);
    for (const { editor } of [this.Tb, this.Wb, this.Xb]) {
      if (visible) {
        editor.onVisible();
      } else {
        editor.onHide();
      }
    }
    this.$b.set(visible);
  }
  // ---- interact with "outside world" via`getControl`, `scopedContextKeyService`: we only expose the result-editor keep the others internal
  getControl() {
    return this.Xb.editor;
  }
  get scopedContextKeyService() {
    const control = this.getControl();
    return control?.invokeWithinContext((accessor) => accessor.get($on));
  }
  // --- layout
  toggleBase() {
    this.setLayout({
      ...this.Yb.value,
      showBase: !this.Yb.value.showBase
    });
  }
  toggleShowBaseTop() {
    const showBaseTop = this.Yb.value.showBase && this.Yb.value.showBaseAtTop;
    this.setLayout({
      ...this.Yb.value,
      showBaseAtTop: true,
      showBase: !showBaseTop
    });
  }
  toggleShowBaseCenter() {
    const showBaseCenter = this.Yb.value.showBase && !this.Yb.value.showBaseAtTop;
    this.setLayout({
      ...this.Yb.value,
      showBaseAtTop: false,
      showBase: !showBaseCenter
    });
  }
  setLayoutKind(kind) {
    this.setLayout({
      ...this.Yb.value,
      kind
    });
  }
  setLayout(newLayout) {
    const value = this.Yb.value;
    if (JSON.stringify(value) === JSON.stringify(newLayout)) {
      return;
    }
    this.model?.telemetry.reportLayoutChange({
      baseTop: newLayout.showBaseAtTop,
      baseVisible: newLayout.showBase,
      isColumnView: newLayout.kind === "columns"
    });
    this.xc(newLayout);
  }
  xc(layout) {
    $ce((tx) => {
      if (layout.showBase && !this.Ub.get()) {
        this.wc.clear();
        const baseView = this.wc.add(this.m.createInstance($cIb, this.viewModel));
        this.wc.add($td((reader) => {
          const options3 = this.Vb.read(reader);
          if (options3) {
            baseView.updateOptions(options3);
          }
        }));
        this.Ub.set(baseView, tx);
      } else if (!layout.showBase && this.Ub.get()) {
        this.Ub.set(void 0, tx);
        this.wc.clear();
      }
      if (layout.kind === "mixed") {
        this.yc([
          layout.showBaseAtTop && layout.showBase ? {
            size: 38,
            data: this.Ub.get().view
          } : void 0,
          {
            size: 38,
            groups: [
              { data: this.Tb.view },
              !layout.showBaseAtTop && layout.showBase ? { data: this.Ub.get().view } : void 0,
              { data: this.Wb.view }
            ].filter($Hg)
          },
          {
            size: 62,
            data: this.Xb.view
          }
        ].filter($Hg));
      } else if (layout.kind === "columns") {
        this.yc([
          layout.showBase ? {
            size: 40,
            data: this.Ub.get().view
          } : void 0,
          {
            size: 60,
            groups: [{ data: this.Tb.view }, { data: this.Xb.view }, { data: this.Wb.view }]
          }
        ].filter($Hg));
      }
      this.Yb.value = layout;
      this.ac.set(layout.kind);
      this.bc.set(layout.showBase);
      this.cc.set(layout.showBaseAtTop);
      this.pc.fire();
      this.Zb.set(layout, tx);
    });
  }
  yc(descriptor) {
    let width2 = -1;
    let height = -1;
    if (this.Sb.value) {
      width2 = this.Sb.value.width;
      height = this.Sb.value.height;
    }
    this.Sb.value = $y2.from({
      orientation: 0,
      size: 100,
      groups: descriptor
    }, {
      styles: { separatorBorder: this.h.getColor($UZb) ?? $Vn.transparent },
      proportionalLayout: true
    });
    $dk(this.$, this.Sb.value.element);
    if (width2 !== -1) {
      this.Sb.value.layout(width2, height);
    }
  }
  zc(state) {
    if (!state) {
      return;
    }
    this.Xb.editor.restoreViewState(state);
    if (state.input1State) {
      this.Tb.editor.restoreViewState(state.input1State);
    }
    if (state.input2State) {
      this.Wb.editor.restoreViewState(state.input2State);
    }
    if (state.focusIndex >= 0) {
      [this.Tb.editor, this.Wb.editor, this.Xb.editor][state.focusIndex].focus();
    }
  }
  mb(resource) {
    if (!$oh(this.inputModel.get()?.resultUri, resource)) {
      return void 0;
    }
    const result = this.Xb.editor.saveViewState();
    if (!result) {
      return void 0;
    }
    const input1State = this.Tb.editor.saveViewState() ?? void 0;
    const input2State = this.Wb.editor.saveViewState() ?? void 0;
    const focusIndex = [this.Tb.editor, this.Wb.editor, this.Xb.editor].findIndex((editor) => editor.hasWidgetFocus());
    return { ...result, input1State, input2State, focusIndex };
  }
  nb(input) {
    return input instanceof $7Ob;
  }
  toggleShowNonConflictingChanges() {
    this.Dc.set(!this.Dc.get(), void 0);
    this.Cc.set(this.Dc.get());
    this.fc.set(this.Dc.get());
  }
};
$icc = $icc_1 = __decorate([
  __param(1, $Pk),
  __param(2, $on),
  __param(3, $zv),
  __param(4, $jv),
  __param(5, $gs),
  __param(6, $zG),
  __param(7, $kl),
  __param(8, $mJ),
  __param(9, $iJ),
  __param(10, $km),
  __param(11, $U5),
  __param(12, $kl)
], $icc);
var MergeEditorLayoutStore = class MergeEditorLayoutStore2 {
  static {
    MergeEditorLayoutStore_1 = this;
  }
  static {
    this.b = "mergeEditor/layout";
  }
  constructor(d) {
    this.d = d;
    this.c = { kind: "mixed", showBase: false, showBaseAtTop: true };
    const value = d.get(MergeEditorLayoutStore_1.b, 0, "mixed");
    if (value === "mixed" || value === "columns") {
      this.c = { kind: value, showBase: false, showBaseAtTop: true };
    } else if (value) {
      try {
        this.c = JSON.parse(value);
      } catch (e) {
        $gb(e);
      }
    }
  }
  get value() {
    return this.c;
  }
  set value(value) {
    if (this.c !== value) {
      this.c = value;
      this.d.store(
        MergeEditorLayoutStore_1.b,
        JSON.stringify(this.c),
        0,
        0
        /* StorageTarget.USER */
      );
    }
  }
};
MergeEditorLayoutStore = MergeEditorLayoutStore_1 = __decorate([
  __param(0, $jv)
], MergeEditorLayoutStore);
var $jcc = class $jcc2 extends $3c {
  constructor(b, codeEditorService) {
    super();
    this.b = b;
    this.q.add(codeEditorService.registerCodeEditorOpenHandler(this.c.bind(this)));
  }
  async c(input, _source, sideBySide) {
    const activePane = this.b.activeEditorPane;
    if (!sideBySide && input.options && activePane instanceof $icc && activePane.getControl() && activePane.input instanceof $7Ob && $oh(input.resource, activePane.input.result)) {
      const targetEditor = activePane.getControl();
      applyTextEditorOptions(
        input.options,
        targetEditor,
        0
        /* ScrollType.Smooth */
      );
      return targetEditor;
    }
    return null;
  }
};
$jcc = __decorate([
  __param(0, $mJ),
  __param(1, $U5)
], $jcc);
var $kcc = class $kcc2 extends $3c {
  static {
    this.ID = "workbench.contrib.mergeEditorResolver";
  }
  constructor(editorResolverService, instantiationService) {
    super();
    const mergeEditorInputFactory = (mergeEditor) => {
      return {
        editor: instantiationService.createInstance($7Ob, mergeEditor.base.resource, {
          uri: mergeEditor.input1.resource,
          title: mergeEditor.input1.label ?? $sh(mergeEditor.input1.resource),
          description: mergeEditor.input1.description ?? "",
          detail: mergeEditor.input1.detail
        }, {
          uri: mergeEditor.input2.resource,
          title: mergeEditor.input2.label ?? $sh(mergeEditor.input2.resource),
          description: mergeEditor.input2.description ?? "",
          detail: mergeEditor.input2.detail
        }, mergeEditor.result.resource)
      };
    };
    this.B(editorResolverService.registerEditor(`*`, {
      id: $1K.id,
      label: $1K.displayName,
      detail: $1K.providerDisplayName,
      priority: RegisteredEditorPriority.builtin
    }, {}, {
      createMergeEditorInput: mergeEditorInputFactory
    }));
  }
};
$kcc = __decorate([
  __param(0, $4L),
  __param(1, $Pk)
], $kcc);

// out-build/vs/workbench/contrib/mergeEditor/browser/commands/commands.js
var MergeEditorAction = class extends $gJ {
  constructor(desc) {
    super(desc);
  }
  run(accessor) {
    const { activeEditorPane } = accessor.get($mJ);
    if (activeEditorPane instanceof $icc) {
      const vm = activeEditorPane.viewModel.get();
      if (!vm) {
        return;
      }
      this.runWithViewModel(vm, accessor);
    }
  }
};
var MergeEditorAction2 = class extends $gJ {
  constructor(desc) {
    super(desc);
  }
  run(accessor, ...args2) {
    const { activeEditorPane } = accessor.get($mJ);
    if (activeEditorPane instanceof $icc) {
      const vm = activeEditorPane.viewModel.get();
      if (!vm) {
        return;
      }
      return this.runWithMergeEditor({
        viewModel: vm,
        inputModel: activeEditorPane.inputModel.get(),
        input: activeEditorPane.input,
        editorIdentifier: {
          editor: activeEditorPane.input,
          groupId: activeEditorPane.group.id
        }
      }, accessor, ...args2);
    }
  }
};
var $lcc = class extends $gJ {
  constructor() {
    super({
      id: "_open.mergeEditor",
      title: localize2(7927, "Open Merge Editor")
    });
  }
  run(accessor, ...args2) {
    const validatedArgs = IRelaxedOpenArgs.validate(args2[0]);
    const input = {
      base: { resource: validatedArgs.base },
      input1: { resource: validatedArgs.input1.uri, label: validatedArgs.input1.title, description: validatedArgs.input1.description, detail: validatedArgs.input1.detail },
      input2: { resource: validatedArgs.input2.uri, label: validatedArgs.input2.title, description: validatedArgs.input2.description, detail: validatedArgs.input2.detail },
      result: { resource: validatedArgs.output },
      options: { preserveFocus: true }
    };
    accessor.get($mJ).openEditor(input);
  }
};
var IRelaxedOpenArgs;
(function(IRelaxedOpenArgs2) {
  function validate(obj) {
    if (!obj || typeof obj !== "object") {
      throw new TypeError("invalid argument");
    }
    const o = obj;
    const base = toUri(o.base);
    const output = toUri(o.output);
    const input1 = toInputData2(o.input1);
    const input2 = toInputData2(o.input2);
    return { base, input1, input2, output };
  }
  IRelaxedOpenArgs2.validate = validate;
  function toInputData2(obj) {
    if (typeof obj === "string") {
      return new $6Ob(URI.parse(obj, true), void 0, void 0, void 0);
    }
    if (!obj || typeof obj !== "object") {
      throw new TypeError("invalid argument");
    }
    if (isUriComponents3(obj)) {
      return new $6Ob(URI.revive(obj), void 0, void 0, void 0);
    }
    const o = obj;
    const title = o.title;
    const uri = toUri(o.uri);
    const detail2 = o.detail;
    const description = o.description;
    return new $6Ob(uri, title, detail2, description);
  }
  function toUri(obj) {
    if (typeof obj === "string") {
      return URI.parse(obj, true);
    } else if (obj && typeof obj === "object") {
      return URI.revive(obj);
    }
    throw new TypeError("invalid argument");
  }
  function isUriComponents3(obj) {
    if (!obj || typeof obj !== "object") {
      return false;
    }
    const o = obj;
    return typeof o.scheme === "string" && typeof o.authority === "string" && typeof o.path === "string" && typeof o.query === "string" && typeof o.fragment === "string";
  }
})(IRelaxedOpenArgs || (IRelaxedOpenArgs = {}));
var $mcc = class extends $gJ {
  constructor() {
    super({
      id: "merge.mixedLayout",
      title: localize2(7928, "Mixed Layout"),
      toggled: $iIb.isEqualTo("mixed"),
      menu: [
        {
          id: $bJ.EditorTitle,
          when: $gIb,
          group: "1_merge",
          order: 9
        }
      ],
      precondition: $gIb
    });
  }
  run(accessor) {
    const { activeEditorPane } = accessor.get($mJ);
    if (activeEditorPane instanceof $icc) {
      activeEditorPane.setLayoutKind("mixed");
    }
  }
};
var $ncc = class extends $gJ {
  constructor() {
    super({
      id: "merge.columnLayout",
      title: localize2(7929, "Column Layout"),
      toggled: $iIb.isEqualTo("columns"),
      menu: [{
        id: $bJ.EditorTitle,
        when: $gIb,
        group: "1_merge",
        order: 10
      }],
      precondition: $gIb
    });
  }
  run(accessor) {
    const { activeEditorPane } = accessor.get($mJ);
    if (activeEditorPane instanceof $icc) {
      activeEditorPane.setLayoutKind("columns");
    }
  }
};
var $occ = class extends $gJ {
  constructor() {
    super({
      id: "merge.showNonConflictingChanges",
      title: localize2(7930, "Show Non-Conflicting Changes"),
      toggled: $lIb.isEqualTo(true),
      menu: [
        {
          id: $bJ.EditorTitle,
          when: $gIb,
          group: "3_merge",
          order: 9
        }
      ],
      precondition: $gIb
    });
  }
  run(accessor) {
    const { activeEditorPane } = accessor.get($mJ);
    if (activeEditorPane instanceof $icc) {
      activeEditorPane.toggleShowNonConflictingChanges();
    }
  }
};
var $pcc = class extends $gJ {
  constructor() {
    super({
      id: "merge.showBase",
      title: localize2(7931, "Show Base"),
      toggled: $jIb.isEqualTo(true),
      menu: [
        {
          id: $bJ.EditorTitle,
          when: $7m.and($gIb, $iIb.isEqualTo("columns")),
          group: "2_merge",
          order: 9
        }
      ]
    });
  }
  run(accessor) {
    const { activeEditorPane } = accessor.get($mJ);
    if (activeEditorPane instanceof $icc) {
      activeEditorPane.toggleBase();
    }
  }
};
var $qcc = class extends $gJ {
  constructor() {
    super({
      id: "merge.showBaseTop",
      title: localize2(7932, "Show Base Top"),
      toggled: $7m.and($jIb, $kIb),
      menu: [
        {
          id: $bJ.EditorTitle,
          when: $7m.and($gIb, $iIb.isEqualTo("mixed")),
          group: "2_merge",
          order: 10
        }
      ]
    });
  }
  run(accessor) {
    const { activeEditorPane } = accessor.get($mJ);
    if (activeEditorPane instanceof $icc) {
      activeEditorPane.toggleShowBaseTop();
    }
  }
};
var $rcc = class extends $gJ {
  constructor() {
    super({
      id: "merge.showBaseCenter",
      title: localize2(7933, "Show Base Center"),
      toggled: $7m.and($jIb, $kIb.negate()),
      menu: [
        {
          id: $bJ.EditorTitle,
          when: $7m.and($gIb, $iIb.isEqualTo("mixed")),
          group: "2_merge",
          order: 11
        }
      ]
    });
  }
  run(accessor) {
    const { activeEditorPane } = accessor.get($mJ);
    if (activeEditorPane instanceof $icc) {
      activeEditorPane.toggleShowBaseCenter();
    }
  }
};
var mergeEditorCategory = localize2(7934, "Merge Editor");
var $scc = class extends MergeEditorAction {
  constructor() {
    super({
      id: "merge.openResult",
      icon: $6l.goToFile,
      title: localize2(7935, "Open File"),
      category: mergeEditorCategory,
      menu: [{
        id: $bJ.EditorTitle,
        when: $gIb,
        group: "navigation",
        order: 1
      }],
      precondition: $gIb
    });
  }
  runWithViewModel(viewModel, accessor) {
    const editorService = accessor.get($mJ);
    editorService.openEditor({ resource: viewModel.model.resultTextModel.uri });
  }
};
var $tcc = class extends MergeEditorAction {
  constructor() {
    super({
      id: "merge.goToNextUnhandledConflict",
      category: mergeEditorCategory,
      title: localize2(7936, "Go to Next Unhandled Conflict"),
      icon: $6l.arrowDown,
      menu: [
        {
          id: $bJ.EditorTitle,
          when: $gIb,
          group: "navigation",
          order: 3
        }
      ],
      f1: true,
      precondition: $gIb
    });
  }
  runWithViewModel(viewModel) {
    viewModel.model.telemetry.reportNavigationToNextConflict();
    viewModel.goToNextModifiedBaseRange((r2) => !viewModel.model.isHandled(r2).get());
  }
};
var $ucc = class extends MergeEditorAction {
  constructor() {
    super({
      id: "merge.goToPreviousUnhandledConflict",
      category: mergeEditorCategory,
      title: localize2(7937, "Go to Previous Unhandled Conflict"),
      icon: $6l.arrowUp,
      menu: [
        {
          id: $bJ.EditorTitle,
          when: $gIb,
          group: "navigation",
          order: 2
        }
      ],
      f1: true,
      precondition: $gIb
    });
  }
  runWithViewModel(viewModel) {
    viewModel.model.telemetry.reportNavigationToPreviousConflict();
    viewModel.goToPreviousModifiedBaseRange((r2) => !viewModel.model.isHandled(r2).get());
  }
};
var $vcc = class extends MergeEditorAction {
  constructor() {
    super({
      id: "merge.toggleActiveConflictInput1",
      category: mergeEditorCategory,
      title: localize2(7938, "Toggle Current Conflict from Left"),
      f1: true,
      precondition: $gIb
    });
  }
  runWithViewModel(viewModel) {
    viewModel.toggleActiveConflict(1);
  }
};
var $wcc = class extends MergeEditorAction {
  constructor() {
    super({
      id: "merge.toggleActiveConflictInput2",
      category: mergeEditorCategory,
      title: localize2(7939, "Toggle Current Conflict from Right"),
      f1: true,
      precondition: $gIb
    });
  }
  runWithViewModel(viewModel) {
    viewModel.toggleActiveConflict(2);
  }
};
var $xcc = class extends MergeEditorAction {
  constructor() {
    super({
      id: "mergeEditor.compareInput1WithBase",
      category: mergeEditorCategory,
      title: localize2(7940, "Compare Input 1 With Base"),
      shortTitle: localize(7921, null),
      f1: true,
      precondition: $gIb,
      menu: { id: $bJ.MergeInput1Toolbar, group: "primary" },
      icon: $6l.compareChanges
    });
  }
  runWithViewModel(viewModel, accessor) {
    const editorService = accessor.get($mJ);
    mergeEditorCompare(viewModel, editorService, 1);
  }
};
var $ycc = class extends MergeEditorAction {
  constructor() {
    super({
      id: "mergeEditor.compareInput2WithBase",
      category: mergeEditorCategory,
      title: localize2(7941, "Compare Input 2 With Base"),
      shortTitle: localize(7922, null),
      f1: true,
      precondition: $gIb,
      menu: { id: $bJ.MergeInput2Toolbar, group: "primary" },
      icon: $6l.compareChanges
    });
  }
  runWithViewModel(viewModel, accessor) {
    const editorService = accessor.get($mJ);
    mergeEditorCompare(viewModel, editorService, 2);
  }
};
async function mergeEditorCompare(viewModel, editorService, inputNumber) {
  editorService.openEditor(editorService.activeEditor, { pinned: true });
  const model = viewModel.model;
  const base = model.base;
  const input = inputNumber === 1 ? viewModel.inputCodeEditorView1.editor : viewModel.inputCodeEditorView2.editor;
  const lineNumber = input.getPosition().lineNumber;
  await editorService.openEditor({
    original: { resource: base.uri },
    modified: { resource: input.getModel().uri },
    options: {
      selection: {
        startLineNumber: lineNumber,
        startColumn: 1
      },
      revealIfOpened: true,
      revealIfVisible: true
    }
  });
}
var $zcc = class extends MergeEditorAction {
  constructor() {
    super({
      id: "merge.openBaseEditor",
      category: mergeEditorCategory,
      title: localize2(7942, "Open Base File"),
      f1: true,
      precondition: $gIb
    });
  }
  runWithViewModel(viewModel, accessor) {
    const openerService = accessor.get($O4);
    openerService.open(viewModel.model.base.uri);
  }
};
var $Acc = class extends MergeEditorAction {
  constructor() {
    super({
      id: "merge.acceptAllInput1",
      category: mergeEditorCategory,
      title: localize2(7943, "Accept All Changes from Left"),
      f1: true,
      precondition: $gIb,
      menu: { id: $bJ.MergeInput1Toolbar, group: "primary" },
      icon: $6l.checkAll
    });
  }
  runWithViewModel(viewModel) {
    viewModel.acceptAll(1);
  }
};
var $Bcc = class extends MergeEditorAction {
  constructor() {
    super({
      id: "merge.acceptAllInput2",
      category: mergeEditorCategory,
      title: localize2(7944, "Accept All Changes from Right"),
      f1: true,
      precondition: $gIb,
      menu: { id: $bJ.MergeInput2Toolbar, group: "primary" },
      icon: $6l.checkAll
    });
  }
  runWithViewModel(viewModel) {
    viewModel.acceptAll(2);
  }
};
var $Ccc = class extends MergeEditorAction {
  constructor() {
    super({
      id: "mergeEditor.resetResultToBaseAndAutoMerge",
      category: mergeEditorCategory,
      title: localize2(7945, "Reset Result"),
      shortTitle: localize(7923, null),
      f1: true,
      precondition: $gIb,
      menu: { id: $bJ.MergeInputResultToolbar, group: "primary" },
      icon: $6l.discard
    });
  }
  runWithViewModel(viewModel, accessor) {
    viewModel.model.reset();
  }
};
var $Dcc = class extends $gJ {
  constructor() {
    super({
      id: "mergeEditor.resetCloseWithConflictsChoice",
      category: mergeEditorCategory,
      title: localize2(7946, "Reset Choice for 'Close with Conflicts'"),
      f1: true
    });
  }
  run(accessor) {
    accessor.get($jv).remove(
      $oIb,
      0
      /* StorageScope.PROFILE */
    );
  }
};
var $Ecc = class extends MergeEditorAction2 {
  constructor() {
    super({
      id: "mergeEditor.acceptMerge",
      category: mergeEditorCategory,
      title: localize2(7947, "Complete Merge"),
      f1: false,
      precondition: $gIb
    });
  }
  async runWithMergeEditor({ inputModel, editorIdentifier, viewModel }, accessor) {
    const dialogService = accessor.get($Yv);
    const editorService = accessor.get($mJ);
    if (viewModel.model.unhandledConflictsCount.get() > 0) {
      const { confirmed } = await dialogService.confirm({
        message: localize(7924, null, $sh(inputModel.resultUri)),
        detail: localize(7925, null),
        primaryButton: localize(7926, null)
      });
      if (!confirmed) {
        return {
          successful: false
        };
      }
    }
    await inputModel.accept();
    await editorService.closeEditor(editorIdentifier);
    return {
      successful: true
    };
  }
};

// out-build/vs/workbench/contrib/mergeEditor/browser/commands/devCommands.js
var MERGE_EDITOR_CATEGORY = localize2(7958, "Merge Editor (Dev)");
var $Fcc = class extends $gJ {
  constructor() {
    super({
      id: "merge.dev.copyContentsJson",
      category: MERGE_EDITOR_CATEGORY,
      title: localize2(7959, "Copy Merge Editor State as JSON"),
      icon: $6l.layoutCentered,
      f1: true,
      precondition: $gIb
    });
  }
  run(accessor) {
    const { activeEditorPane } = accessor.get($mJ);
    const clipboardService = accessor.get($30);
    const notificationService = accessor.get($PJ);
    if (!(activeEditorPane instanceof $icc)) {
      notificationService.info({
        name: localize(7948, null),
        message: localize(7949, null)
      });
      return;
    }
    const model = activeEditorPane.model;
    if (!model) {
      return;
    }
    const contents = {
      languageId: model.resultTextModel.getLanguageId(),
      base: model.base.getValue(),
      input1: model.input1.textModel.getValue(),
      input2: model.input2.textModel.getValue(),
      result: model.resultTextModel.getValue(),
      initialResult: model.getInitialResultValue()
    };
    const jsonStr = JSON.stringify(contents, void 0, 4);
    clipboardService.writeText(jsonStr);
    notificationService.info({
      name: localize(7950, null),
      message: localize(7951, null)
    });
  }
};
var $Gcc = class extends $gJ {
  constructor() {
    super({
      id: "merge.dev.saveContentsToFolder",
      category: MERGE_EDITOR_CATEGORY,
      title: localize2(7960, "Save Merge Editor State to Folder"),
      icon: $6l.layoutCentered,
      f1: true,
      precondition: $gIb
    });
  }
  async run(accessor) {
    const { activeEditorPane } = accessor.get($mJ);
    const notificationService = accessor.get($PJ);
    const dialogService = accessor.get($1v);
    const fileService = accessor.get($km);
    const languageService = accessor.get($1E);
    if (!(activeEditorPane instanceof $icc)) {
      notificationService.info({
        name: localize(7952, null),
        message: localize(7953, null)
      });
      return;
    }
    const model = activeEditorPane.model;
    if (!model) {
      return;
    }
    const result = await dialogService.showOpenDialog({
      canSelectFiles: false,
      canSelectFolders: true,
      canSelectMany: false,
      title: localize(7954, null)
    });
    if (!result) {
      return;
    }
    const targetDir = result[0];
    const extension = languageService.getExtensions(model.resultTextModel.getLanguageId())[0] || "";
    async function write(fileName, source) {
      await fileService.writeFile(URI.joinPath(targetDir, fileName + extension), $Ci.fromString(source), {});
    }
    await Promise.all([
      write("base", model.base.getValue()),
      write("input1", model.input1.textModel.getValue()),
      write("input2", model.input2.textModel.getValue()),
      write("result", model.resultTextModel.getValue()),
      write("initialResult", model.getInitialResultValue())
    ]);
    notificationService.info({
      name: localize(7955, null),
      message: localize(7956, null)
    });
  }
};
var $Hcc = class extends $gJ {
  constructor() {
    super({
      id: "merge.dev.loadContentsFromFolder",
      category: MERGE_EDITOR_CATEGORY,
      title: localize2(7961, "Load Merge Editor State from Folder"),
      icon: $6l.layoutCentered,
      f1: true
    });
  }
  async run(accessor, args2) {
    const dialogService = accessor.get($1v);
    const editorService = accessor.get($mJ);
    const fileService = accessor.get($km);
    const quickInputService = accessor.get($1M);
    if (!args2) {
      args2 = {};
    }
    let targetDir;
    if (!args2.folderUri) {
      const result = await dialogService.showOpenDialog({
        canSelectFiles: false,
        canSelectFolders: true,
        canSelectMany: false,
        title: localize(7957, null)
      });
      if (!result) {
        return;
      }
      targetDir = result[0];
    } else {
      targetDir = args2.folderUri;
    }
    const targetDirInfo = await fileService.resolve(targetDir);
    function findFile(name) {
      return targetDirInfo.children.find((c) => c.name.startsWith(name))?.resource;
    }
    const shouldOpenInitial = await promptOpenInitial(quickInputService, args2.resultState);
    const baseUri = findFile("base");
    const input1Uri = findFile("input1");
    const input2Uri = findFile("input2");
    const resultUri = findFile(shouldOpenInitial ? "initialResult" : "result");
    const input = {
      base: { resource: baseUri },
      input1: { resource: input1Uri, label: "Input 1", description: "Input 1", detail: "(from file)" },
      input2: { resource: input2Uri, label: "Input 2", description: "Input 2", detail: "(from file)" },
      result: { resource: resultUri }
    };
    editorService.openEditor(input);
  }
};
async function promptOpenInitial(quickInputService, resultStateOverride) {
  if (resultStateOverride) {
    return resultStateOverride === "initial";
  }
  const result = await quickInputService.pick([{ label: "result", result: false }, { label: "initial result", result: true }], { canPickMany: false });
  return result?.result;
}

// out-build/vs/workbench/contrib/mergeEditor/browser/mergeEditorSerializer.js
var $Icc = class {
  canSerialize() {
    return true;
  }
  serialize(editor) {
    return JSON.stringify(this.toJSON(editor));
  }
  toJSON(editor) {
    return {
      base: editor.base,
      input1: editor.input1,
      input2: editor.input2,
      result: editor.result
    };
  }
  deserialize(instantiationService, raw) {
    try {
      const data = $bu(raw);
      return instantiationService.createInstance($7Ob, data.base, new $6Ob(data.input1.uri, data.input1.title, data.input1.detail, data.input1.description), new $6Ob(data.input2.uri, data.input2.title, data.input2.detail, data.input2.description), data.result);
    } catch (err) {
      $gb(err);
      return void 0;
    }
  }
};

// out-build/vs/workbench/contrib/mergeEditor/browser/mergeEditor.contribution.js
$Wn.as($ZK.EditorPane).registerEditorPane($7tb.create($icc, $icc.ID, localize(7962, null)), [
  new $Nk($7Ob)
]);
$Wn.as($ZK.EditorFactory).registerEditorSerializer($7Ob.ID, $Icc);
$Wn.as($Ht.Configuration).registerConfiguration({
  properties: {
    "mergeEditor.diffAlgorithm": {
      type: "string",
      enum: ["legacy", "advanced"],
      default: "advanced",
      markdownEnumDescriptions: [
        localize(7963, null),
        localize(7964, null)
      ]
    },
    "mergeEditor.showDeletionMarkers": {
      type: "boolean",
      default: true,
      description: "Controls if deletions in base or one of the inputs should be indicated by a vertical bar."
    }
  }
});
$hJ($scc);
$hJ($mcc);
$hJ($ncc);
$hJ($lcc);
$hJ($zcc);
$hJ($occ);
$hJ($pcc);
$hJ($qcc);
$hJ($rcc);
$hJ($tcc);
$hJ($ucc);
$hJ($vcc);
$hJ($wcc);
$hJ($xcc);
$hJ($ycc);
$hJ($Acc);
$hJ($Bcc);
$hJ($Ccc);
$hJ($Ecc);
$hJ($Dcc);
$hJ($Fcc);
$hJ($Gcc);
$hJ($Hcc);
$Wn.as(Extensions2.Workbench).registerWorkbenchContribution(
  $jcc,
  3
  /* LifecyclePhase.Restored */
);
$PL(
  $kcc.ID,
  $kcc,
  1
  /* WorkbenchPhase.BlockStartup */
);

// out-build/vs/workbench/contrib/multiDiffEditor/browser/multiDiffEditor.js
var $cFb_1;
var $cFb = class $cFb2 extends $$tb {
  static {
    $cFb_1 = this;
  }
  static {
    this.ID = "multiDiffEditor";
  }
  get viewModel() {
    return this.c;
  }
  constructor(group2, instantiationService, telemetryService, themeService, storageService, editorService, editorGroupService, textResourceConfigurationService, f) {
    super($cFb_1.ID, group2, "multiDiffEditor", telemetryService, instantiationService, storageService, textResourceConfigurationService, themeService, editorService, editorGroupService);
    this.f = f;
    this.a = void 0;
  }
  Y(parent) {
    this.a = this.B(this.m.createInstance($0Eb, parent, this.m.createInstance(WorkbenchUIElementFactory3)));
    this.B(this.a.onDidChangeActiveControl(() => {
      this.S.fire();
    }));
  }
  async setInput(input, options3, context, token) {
    await super.setInput(input, options3, context, token);
    this.c = await input.getViewModel();
    this.a.setViewModel(this.c);
    const viewState = this.jb(input, context);
    if (viewState) {
      this.a.setViewState(viewState);
    }
    this.$(options3);
  }
  setOptions(options3) {
    this.$(options3);
  }
  $(options3) {
    const viewState = options3?.viewState;
    if (!viewState || !viewState.revealData) {
      return;
    }
    this.a?.reveal(viewState.revealData.resource, {
      range: viewState.revealData.range ? $9C.lift(viewState.revealData.range) : void 0,
      highlight: true
    });
  }
  async clearInput() {
    await super.clearInput();
    this.a.setViewModel(void 0);
  }
  layout(dimension) {
    this.a.layout(dimension);
  }
  getControl() {
    return this.a.getActiveControl();
  }
  focus() {
    super.focus();
    this.a?.getActiveControl()?.focus();
  }
  hasFocus() {
    return this.a?.getActiveControl()?.hasTextFocus() || super.hasFocus();
  }
  mb(resource) {
    return this.a.getViewState();
  }
  nb(input) {
    return input instanceof $_Eb;
  }
  pb(input) {
    return input.resource;
  }
  tryGetCodeEditor(resource) {
    return this.a.tryGetCodeEditor(resource);
  }
  findDocumentDiffItem(resource) {
    const i2 = this.a.findDocumentDiffItem(resource);
    if (!i2) {
      return void 0;
    }
    const i22 = i2;
    return i22.multiDiffEditorItem;
  }
  async showWhile(promise) {
    return this.f.showWhile(promise);
  }
};
$cFb = $cFb_1 = __decorate([
  __param(1, $Pk),
  __param(2, $zv),
  __param(3, $gs),
  __param(4, $jv),
  __param(5, $mJ),
  __param(6, $iJ),
  __param(7, $zG),
  __param(8, $ZJ)
], $cFb);
var WorkbenchUIElementFactory3 = class WorkbenchUIElementFactory4 {
  constructor(a) {
    this.a = a;
  }
  createResourceLabel(element) {
    const label3 = this.a.createInstance($msb, element, {});
    return {
      setUri(uri, options3 = {}) {
        if (!uri) {
          label3.element.clear();
        } else {
          label3.element.setFile(uri, { strikethrough: options3.strikethrough });
        }
      },
      dispose() {
        label3.dispose();
      }
    };
  }
};
WorkbenchUIElementFactory3 = __decorate([
  __param(0, $Pk)
], WorkbenchUIElementFactory3);

// out-build/vs/workbench/contrib/multiDiffEditor/browser/actions.js
var $Jcc = class extends $gJ {
  constructor() {
    super({
      id: "multiDiffEditor.goToFile",
      title: localize2(8066, "Open File"),
      icon: $6l.goToFile,
      precondition: $Dpb.isEqualTo($cFb.ID),
      menu: {
        when: $Dpb.isEqualTo($cFb.ID),
        id: $bJ.MultiDiffEditorFileToolbar,
        order: 22,
        group: "navigation"
      }
    });
  }
  async run(accessor, ...args2) {
    const uri = args2[0];
    const editorService = accessor.get($mJ);
    const activeEditorPane = editorService.activeEditorPane;
    let selections = void 0;
    if (!(activeEditorPane instanceof $cFb)) {
      return;
    }
    const editor = activeEditorPane.tryGetCodeEditor(uri);
    if (editor) {
      selections = editor.editor.getSelections() ?? void 0;
    }
    let targetUri = uri;
    const item = activeEditorPane.findDocumentDiffItem(uri);
    if (item && item.goToFileUri) {
      targetUri = item.goToFileUri;
    }
    await editorService.openEditor({
      resource: targetUri,
      options: {
        selection: selections?.[0],
        selectionRevealType: 1
      }
    });
  }
};
var $Kcc = class extends $gJ {
  constructor() {
    super({
      id: "multiDiffEditor.collapseAll",
      title: localize2(8067, "Collapse All Diffs"),
      icon: $6l.collapseAll,
      precondition: $7m.and($7m.equals("activeEditor", $cFb.ID), $7m.not("multiDiffEditorAllCollapsed")),
      menu: {
        when: $7m.and($7m.equals("activeEditor", $cFb.ID), $7m.not("multiDiffEditorAllCollapsed")),
        id: $bJ.EditorTitle,
        group: "navigation",
        order: 100
      },
      f1: true
    });
  }
  async run(accessor, ...args2) {
    const resolvedContext = $sub(args2, accessor.get($mJ), accessor.get($iJ), accessor.get($Deb));
    const groupContext = resolvedContext.groupedEditors[0];
    if (!groupContext) {
      return;
    }
    const editor = groupContext.editors[0];
    if (editor instanceof $_Eb) {
      const viewModel = await editor.getViewModel();
      viewModel.collapseAll();
    }
  }
};
var $Lcc = class extends $gJ {
  constructor() {
    super({
      id: "multiDiffEditor.expandAll",
      title: localize2(8068, "Expand All Diffs"),
      icon: $6l.expandAll,
      precondition: $7m.and($7m.equals("activeEditor", $cFb.ID), $7m.has("multiDiffEditorAllCollapsed")),
      menu: {
        when: $7m.and($7m.equals("activeEditor", $cFb.ID), $7m.has("multiDiffEditorAllCollapsed")),
        id: $bJ.EditorTitle,
        group: "navigation",
        order: 100
      },
      f1: true
    });
  }
  async run(accessor, ...args2) {
    const resolvedContext = $sub(args2, accessor.get($mJ), accessor.get($iJ), accessor.get($Deb));
    const groupContext = resolvedContext.groupedEditors[0];
    if (!groupContext) {
      return;
    }
    const editor = groupContext.editors[0];
    if (editor instanceof $_Eb) {
      const viewModel = await editor.getViewModel();
      viewModel.expandAll();
    }
  }
};

// out-build/vs/workbench/contrib/multiDiffEditor/browser/multiDiffEditor.contribution.js
$hJ($Jcc);
$hJ($Kcc);
$hJ($Lcc);
$Wn.as($Ht.Configuration).registerConfiguration({
  properties: {
    "multiDiffEditor.experimental.enabled": {
      type: "boolean",
      default: true,
      description: "Enable experimental multi diff editor."
    }
  }
});
$SC(
  $TDb,
  $VDb,
  1
  /* InstantiationType.Delayed */
);
$PL(
  $aFb.ID,
  $aFb,
  1
  /* WorkbenchPhase.BlockStartup */
);
$Wn.as($ZK.EditorPane).registerEditorPane($7tb.create($cFb, $cFb.ID, localize(8070, null)), [new $Nk($_Eb)]);
$Wn.as($ZK.EditorFactory).registerEditorSerializer($_Eb.ID, $bFb);
$hJ($wac);
$PL(
  $vac.ID,
  $vac,
  1
  /* WorkbenchPhase.BlockStartup */
);

// out-build/vs/workbench/contrib/mappedEdits/common/mappedEdits.contribution.js
$tn.registerCommand("_executeMappedEditsProvider", async (accessor, documentUri, codeBlocks, context) => {
  const modelService = accessor.get($oG);
  const langFeaturesService = accessor.get($mP);
  const document2 = await modelService.createModelReference(documentUri);
  let result = null;
  try {
    const providers2 = langFeaturesService.mappedEditsProvider.ordered(document2.object.textEditorModel);
    if (providers2.length > 0) {
      const mostRelevantProvider = providers2[0];
      const cancellationTokenSource = new $ad();
      result = await mostRelevantProvider.provideMappedEdits(document2.object.textEditorModel, codeBlocks, context, cancellationTokenSource.token);
    }
  } finally {
    document2.dispose();
  }
  return result;
});

// out-build/vs/workbench/contrib/commands/common/commands.contribution.js
var RunCommands = class extends $gJ {
  constructor() {
    super({
      id: "runCommands",
      title: localize2(5311, "Run Commands"),
      f1: false,
      metadata: {
        description: localize(5307, null),
        args: [
          {
            name: "args",
            schema: {
              type: "object",
              required: ["commands"],
              properties: {
                commands: {
                  type: "array",
                  description: localize(5308, null),
                  items: {
                    anyOf: [
                      {
                        $ref: "vscode://schemas/keybindings#/definitions/commandNames"
                      },
                      {
                        type: "string"
                      },
                      {
                        type: "object",
                        required: ["command"],
                        properties: {
                          command: {
                            "anyOf": [
                              {
                                $ref: "vscode://schemas/keybindings#/definitions/commandNames"
                              },
                              {
                                type: "string"
                              }
                            ]
                          }
                        },
                        $ref: "vscode://schemas/keybindings#/definitions/commandsSchemas"
                      }
                    ]
                  }
                }
              }
            }
          }
        ]
      }
    });
  }
  // dev decisions:
  // - this command takes a single argument-object because
  //	- keybinding definitions don't allow running commands with several arguments
  //  - and we want to be able to take on different other arguments in future, e.g., `runMode : 'serial' | 'concurrent'`
  async run(accessor, args2) {
    const notificationService = accessor.get($PJ);
    if (!this.a(args2)) {
      notificationService.error(localize(5309, null));
      return;
    }
    if (args2.commands.length === 0) {
      notificationService.warn(localize(5310, null));
      return;
    }
    const commandService = accessor.get($sn);
    const logService = accessor.get($wn);
    let i2 = 0;
    try {
      for (; i2 < args2.commands.length; ++i2) {
        const cmd = args2.commands[i2];
        logService.debug(`runCommands: executing ${i2}-th command: ${$Qv(cmd)}`);
        await this.b(commandService, cmd);
        logService.debug(`runCommands: executed ${i2}-th command`);
      }
    } catch (err) {
      logService.debug(`runCommands: executing ${i2}-th command resulted in an error: ${err instanceof Error ? err.message : $Qv(err)}`);
      notificationService.error(err);
    }
  }
  a(args2) {
    if (!args2 || typeof args2 !== "object") {
      return false;
    }
    if (!("commands" in args2) || !Array.isArray(args2.commands)) {
      return false;
    }
    for (const cmd of args2.commands) {
      if (typeof cmd === "string") {
        continue;
      }
      if (typeof cmd === "object" && typeof cmd.command === "string") {
        continue;
      }
      return false;
    }
    return true;
  }
  b(commandService, cmd) {
    let commandID, commandArgs;
    if (typeof cmd === "string") {
      commandID = cmd;
    } else {
      commandID = cmd.command;
      commandArgs = cmd.args;
    }
    if (commandArgs === void 0) {
      return commandService.executeCommand(commandID);
    } else {
      if (Array.isArray(commandArgs)) {
        return commandService.executeCommand(commandID, ...commandArgs);
      } else {
        return commandService.executeCommand(commandID, commandArgs);
      }
    }
  }
};
$hJ(RunCommands);

// out-build/vs/workbench/contrib/comments/browser/commentsInputContentProvider.js
var $Mcc = class $Mcc2 extends $3c {
  static {
    this.ID = "comments.input.contentProvider";
  }
  constructor(textModelService, codeEditorService, a, b) {
    super();
    this.a = a;
    this.b = b;
    this.B(textModelService.registerTextModelContentProvider(Schemas.commentsInput, this));
    this.B(codeEditorService.registerCodeEditorOpenHandler(async (input, editor, _sideBySide) => {
      if (!(editor instanceof $2Jb)) {
        return null;
      }
      if (editor.getModel()?.uri.toString() !== input.resource.toString()) {
        return null;
      }
      if (input.options) {
        applyTextEditorOptions(
          input.options,
          editor,
          1
          /* ScrollType.Immediate */
        );
      }
      return editor;
    }));
  }
  async provideTextContent(resource) {
    const existing = this.a.getModel(resource);
    return existing ?? this.a.createModel("", this.b.createById("markdown"), resource);
  }
};
$Mcc = __decorate([
  __param(0, $oG),
  __param(1, $U5),
  __param(2, $sG),
  __param(3, $1E)
], $Mcc);

// out-build/vs/workbench/contrib/comments/browser/commentsEditorContribution.js
$85(
  ID,
  $tSb,
  1
  /* EditorContributionInstantiation.AfterFirstRender */
);
$PL(
  $Mcc.ID,
  $Mcc,
  2
  /* WorkbenchPhase.BlockRestore */
);
$0I.registerCommandAndKeybindingRule({
  id: "editor.action.nextCommentThreadAction",
  handler: async (accessor, args2) => {
    const activeEditor = $Ncc(accessor);
    if (!activeEditor) {
      return Promise.resolve();
    }
    const controller = $tSb.get(activeEditor);
    if (!controller) {
      return Promise.resolve();
    }
    controller.nextCommentThread(true);
  },
  weight: 100,
  primary: 512 | 67
});
$0I.registerCommandAndKeybindingRule({
  id: "editor.action.previousCommentThreadAction",
  handler: async (accessor, args2) => {
    const activeEditor = $Ncc(accessor);
    if (!activeEditor) {
      return Promise.resolve();
    }
    const controller = $tSb.get(activeEditor);
    if (!controller) {
      return Promise.resolve();
    }
    controller.previousCommentThread(true);
  },
  weight: 100,
  primary: 1024 | 512 | 67
  /* KeyCode.F9 */
});
$hJ(class extends $gJ {
  constructor() {
    super({
      id: "editor.action.nextCommentedRangeAction",
      title: {
        value: localize(5369, null),
        original: "Go to Next Commented Range"
      },
      category: {
        value: localize(5370, null),
        original: "Comments"
      },
      menu: [{
        id: $bJ.CommandPalette,
        when: CommentContextKeys.activeEditorHasCommentingRange
      }],
      keybinding: {
        primary: 512 | 68,
        weight: 100,
        when: CommentContextKeys.activeEditorHasCommentingRange
      }
    });
  }
  run(accessor, ...args2) {
    const activeEditor = $Ncc(accessor);
    if (!activeEditor) {
      return;
    }
    const controller = $tSb.get(activeEditor);
    if (!controller) {
      return;
    }
    controller.nextCommentThread(false);
  }
});
$hJ(class extends $gJ {
  constructor() {
    super({
      id: "editor.action.previousCommentedRangeAction",
      title: {
        value: localize(5371, null),
        original: "Go to Previous Commented Range"
      },
      category: {
        value: localize(5372, null),
        original: "Comments"
      },
      menu: [{
        id: $bJ.CommandPalette,
        when: CommentContextKeys.activeEditorHasCommentingRange
      }],
      keybinding: {
        primary: 1024 | 512 | 68,
        weight: 100,
        when: CommentContextKeys.activeEditorHasCommentingRange
      }
    });
  }
  run(accessor, ...args2) {
    const activeEditor = $Ncc(accessor);
    if (!activeEditor) {
      return;
    }
    const controller = $tSb.get(activeEditor);
    if (!controller) {
      return;
    }
    controller.previousCommentThread(false);
  }
});
$hJ(class extends $gJ {
  constructor() {
    super({
      id: "editor.action.nextCommentingRange",
      title: {
        value: localize(5373, null),
        original: "Go to Next Commenting Range"
      },
      category: {
        value: localize(5374, null),
        original: "Comments"
      },
      menu: [{
        id: $bJ.CommandPalette,
        when: CommentContextKeys.activeEditorHasCommentingRange
      }],
      keybinding: {
        primary: $$e(
          2048 | 41,
          2048 | 512 | 18
          /* KeyCode.DownArrow */
        ),
        weight: 100,
        when: $7m.and($OD, $7m.or(EditorContextKeys.focus, CommentContextKeys.commentFocused, $7m.and($nsb, $tsb.isEqualTo(
          "comments"
          /* AccessibleViewProviderId.Comments */
        ))))
      }
    });
  }
  run(accessor, args2) {
    const activeEditor = $Ncc(accessor);
    if (!activeEditor) {
      return;
    }
    const controller = $tSb.get(activeEditor);
    if (!controller) {
      return;
    }
    controller.nextCommentingRange();
  }
});
$hJ(class extends $gJ {
  constructor() {
    super({
      id: "editor.action.previousCommentingRange",
      title: {
        value: localize(5375, null),
        original: "Go to Previous Commenting Range"
      },
      category: {
        value: localize(5376, null),
        original: "Comments"
      },
      menu: [{
        id: $bJ.CommandPalette,
        when: CommentContextKeys.activeEditorHasCommentingRange
      }],
      keybinding: {
        primary: $$e(
          2048 | 41,
          2048 | 512 | 16
          /* KeyCode.UpArrow */
        ),
        weight: 100,
        when: $7m.and($OD, $7m.or(EditorContextKeys.focus, CommentContextKeys.commentFocused, $7m.and($nsb, $tsb.isEqualTo(
          "comments"
          /* AccessibleViewProviderId.Comments */
        ))))
      }
    });
  }
  async run(accessor, ...args2) {
    const activeEditor = $Ncc(accessor);
    if (!activeEditor) {
      return;
    }
    const controller = $tSb.get(activeEditor);
    if (!controller) {
      return;
    }
    controller.previousCommentingRange();
  }
});
$hJ(class extends $gJ {
  constructor() {
    super({
      id: "workbench.action.toggleCommenting",
      title: {
        value: localize(5377, null),
        original: "Toggle Editor Commenting"
      },
      category: {
        value: localize(5378, null),
        original: "Comments"
      },
      menu: [{
        id: $bJ.CommandPalette,
        when: CommentContextKeys.WorkspaceHasCommenting
      }]
    });
  }
  run(accessor, ...args2) {
    const commentService = accessor.get($RJb);
    const enable = commentService.isCommentingEnabled;
    commentService.enableCommenting(!enable);
  }
});
$hJ(class extends $gJ {
  constructor() {
    super({
      id: "workbench.action.addComment",
      title: {
        value: localize(5379, null),
        original: "Add Comment on Current Selection"
      },
      category: {
        value: localize(5380, null),
        original: "Comments"
      },
      menu: [{
        id: $bJ.CommandPalette,
        when: CommentContextKeys.activeCursorHasCommentingRange
      }],
      keybinding: {
        primary: $$e(
          2048 | 41,
          2048 | 512 | 33
          /* KeyCode.KeyC */
        ),
        weight: 100,
        when: CommentContextKeys.activeCursorHasCommentingRange
      }
    });
  }
  async run(accessor, args2) {
    const activeEditor = $Ncc(accessor);
    if (!activeEditor) {
      return;
    }
    const controller = $tSb.get(activeEditor);
    if (!controller) {
      return;
    }
    const position = args2?.range ? new $9C(args2.range.startLineNumber, args2.range.startLineNumber, args2.range.endLineNumber, args2.range.endColumn) : args2?.fileComment ? void 0 : activeEditor.getSelection();
    const notificationService = accessor.get($PJ);
    try {
      await controller.addOrToggleCommentAtLine(position, void 0);
    } catch (e) {
      notificationService.error(localize(5381, null));
    }
  }
});
$hJ(class extends $gJ {
  constructor() {
    super({
      id: "workbench.action.focusCommentOnCurrentLine",
      title: {
        value: localize(5382, null),
        original: "Focus Comment on Current Line"
      },
      category: {
        value: localize(5383, null),
        original: "Comments"
      },
      f1: true,
      precondition: CommentContextKeys.activeCursorHasComment
    });
  }
  async run(accessor, ...args2) {
    const activeEditor = $Ncc(accessor);
    if (!activeEditor) {
      return;
    }
    const controller = $tSb.get(activeEditor);
    if (!controller) {
      return;
    }
    const position = activeEditor.getSelection();
    const notificationService = accessor.get($PJ);
    let error = false;
    try {
      const commentAtLine = controller.getCommentsAtLine(position);
      if (commentAtLine.length === 0) {
        error = true;
      } else {
        await controller.revealCommentThread(commentAtLine[0].commentThread.threadId, void 0, false, CommentWidgetFocus.Widget);
      }
    } catch (e) {
      error = true;
    }
    if (error) {
      notificationService.error(localize(5384, null));
    }
  }
});
$hJ(class extends $gJ {
  constructor() {
    super({
      id: "workbench.action.collapseAllComments",
      title: {
        value: localize(5385, null),
        original: "Collapse All Comments"
      },
      category: {
        value: localize(5386, null),
        original: "Comments"
      },
      menu: [{
        id: $bJ.CommandPalette,
        when: CommentContextKeys.WorkspaceHasCommenting
      }]
    });
  }
  run(accessor, ...args2) {
    getActiveController(accessor)?.collapseAll();
  }
});
$hJ(class extends $gJ {
  constructor() {
    super({
      id: "workbench.action.expandAllComments",
      title: {
        value: localize(5387, null),
        original: "Expand All Comments"
      },
      category: {
        value: localize(5388, null),
        original: "Comments"
      },
      menu: [{
        id: $bJ.CommandPalette,
        when: CommentContextKeys.WorkspaceHasCommenting
      }]
    });
  }
  run(accessor, ...args2) {
    getActiveController(accessor)?.expandAll();
  }
});
$hJ(class extends $gJ {
  constructor() {
    super({
      id: "workbench.action.expandUnresolvedComments",
      title: {
        value: localize(5389, null),
        original: "Expand Unresolved Comments"
      },
      category: {
        value: localize(5390, null),
        original: "Comments"
      },
      menu: [{
        id: $bJ.CommandPalette,
        when: CommentContextKeys.WorkspaceHasCommenting
      }]
    });
  }
  run(accessor, ...args2) {
    getActiveController(accessor)?.expandUnresolved();
  }
});
$0I.registerCommandAndKeybindingRule({
  id: "editor.action.submitComment",
  weight: 100,
  primary: 2048 | 3,
  when: $YJb,
  handler: (accessor, args2) => {
    const activeCodeEditor = accessor.get($U5).getFocusedCodeEditor();
    if (activeCodeEditor instanceof $2Jb) {
      activeCodeEditor.getParentThread().submitComment();
    }
  }
});
$0I.registerCommandAndKeybindingRule({
  id: "workbench.action.hideComment",
  weight: 100,
  primary: 9,
  secondary: [
    1024 | 9
    /* KeyCode.Escape */
  ],
  when: $7m.or($YJb, CommentContextKeys.commentFocused),
  handler: (accessor, args2) => {
    const activeCodeEditor = accessor.get($U5).getFocusedCodeEditor();
    if (activeCodeEditor instanceof $2Jb) {
      activeCodeEditor.getParentThread().collapse();
    } else if (activeCodeEditor) {
      const controller = $tSb.get(activeCodeEditor);
      if (!controller) {
        return;
      }
      const notificationService = accessor.get($PJ);
      const commentService = accessor.get($RJb);
      let error = false;
      try {
        const activeComment = commentService.lastActiveCommentcontroller?.activeComment;
        if (!activeComment) {
          error = true;
        } else {
          controller.collapseAndFocusRange(activeComment.thread.threadId);
        }
      } catch (e) {
        error = true;
      }
      if (error) {
        notificationService.error(localize(5391, null));
      }
    }
  }
});
function $Ncc(accessor) {
  let activeTextEditorControl = accessor.get($mJ).activeTextEditorControl;
  if ($Q5(activeTextEditorControl)) {
    if (activeTextEditorControl.getOriginalEditor().hasTextFocus()) {
      activeTextEditorControl = activeTextEditorControl.getOriginalEditor();
    } else {
      activeTextEditorControl = activeTextEditorControl.getModifiedEditor();
    }
  }
  if (!$P5(activeTextEditorControl) || !activeTextEditorControl.hasModel()) {
    return null;
  }
  return activeTextEditorControl;
}
function getActiveController(accessor) {
  const activeEditor = $Ncc(accessor);
  if (!activeEditor) {
    return void 0;
  }
  const controller = $tSb.get(activeEditor);
  if (!controller) {
    return void 0;
  }
  return controller;
}

// out-build/vs/workbench/contrib/comments/browser/commentsAccessibleView.js
var $Occ = class extends $3c {
  getProvider(accessor) {
    const contextKeyService = accessor.get($on);
    const viewsService = accessor.get($uob);
    const menuService = accessor.get($cJ);
    const commentsView = viewsService.getActiveViewWithId($_Rb);
    const focusedCommentNode = commentsView?.focusedCommentNode;
    if (!commentsView || !focusedCommentNode) {
      return;
    }
    const menus = this.B(new $dSb(menuService));
    menus.setContextKeyService(contextKeyService);
    return new CommentsAccessibleContentProvider(commentsView, focusedCommentNode, menus);
  }
  constructor() {
    super();
    this.priority = 90;
    this.name = "comment";
    this.when = $ySb;
    this.type = "view";
  }
};
var $Pcc = class extends $3c {
  getProvider(accessor) {
    const commentService = accessor.get($RJb);
    const editorService = accessor.get($mJ);
    const uriIdentityService = accessor.get($vl);
    const threads = commentService.commentsModel.hasCommentThreads();
    if (!threads) {
      return;
    }
    return new CommentsThreadWidgetAccessibleContentProvider(commentService, editorService, uriIdentityService);
  }
  constructor() {
    super();
    this.priority = 85;
    this.name = "commentThread";
    this.when = CommentContextKeys.commentFocused;
    this.type = "view";
  }
};
var CommentsAccessibleContentProvider = class extends $3c {
  constructor(a, b, c) {
    super();
    this.a = a;
    this.b = b;
    this.c = c;
    this.id = "comments";
    this.verbositySettingKey = "accessibility.verbosity.comments";
    this.options = {
      type: "view"
      /* AccessibleViewType.View */
    };
    this.actions = [...this.c.getResourceContextActions(this.b)].filter((i2) => i2.enabled).map((action) => {
      return {
        ...action,
        run: () => {
          this.a.focus();
          action.run({
            thread: this.b.thread,
            $mid: 7,
            commentControlHandle: this.b.controllerHandle,
            commentThreadHandle: this.b.threadHandle
          });
        }
      };
    });
  }
  provideContent() {
    const commentNode = this.a.focusedCommentNode;
    const content = this.a.focusedCommentInfo?.toString();
    if (!commentNode || !content) {
      throw new Error("Comment tree is focused but no comment is selected");
    }
    return content;
  }
  onClose() {
    this.a.focus();
  }
  provideNextContent() {
    this.a.focusNextNode();
    return this.provideContent();
  }
  providePreviousContent() {
    this.a.focusPreviousNode();
    return this.provideContent();
  }
};
var CommentsThreadWidgetAccessibleContentProvider = class CommentsThreadWidgetAccessibleContentProvider2 extends $3c {
  constructor(b, c, f) {
    super();
    this.b = b;
    this.c = c;
    this.f = f;
    this.id = "commentThread";
    this.verbositySettingKey = "accessibility.verbosity.comments";
    this.options = {
      type: "view"
      /* AccessibleViewType.View */
    };
  }
  get g() {
    if (!this.a && this.b.lastActiveCommentcontroller) {
      this.a = this.b.lastActiveCommentcontroller.activeComment;
    }
    return this.a;
  }
  provideContent() {
    if (!this.g) {
      throw new Error("No current comment thread");
    }
    const comment = this.g.comment?.body;
    const commentLabel = typeof comment === "string" ? comment : comment?.value ?? "";
    const resource = this.g.thread.resource;
    const range = this.g.thread.range;
    let contentLabel = "";
    if (resource && range) {
      const editor = this.c.findEditors(URI.parse(resource)) || [];
      const codeEditor = this.c.activeEditorPane?.getControl();
      if (editor?.length && $P5(codeEditor)) {
        const content = codeEditor.getModel()?.getValueInRange(range);
        if (content) {
          contentLabel = "\nCorresponding code: \n" + content;
        }
      }
    }
    return commentLabel + contentLabel;
  }
  onClose() {
    const lastComment = this.a;
    this.a = void 0;
    if (lastComment) {
      $sSb(this.b, this.c, this.f, lastComment.thread, lastComment.comment);
    }
  }
  provideNextContent() {
    const newCommentInfo = $rSb(this.a, "next");
    if (newCommentInfo) {
      this.a = newCommentInfo;
      return this.provideContent();
    }
    return void 0;
  }
  providePreviousContent() {
    const newCommentInfo = $rSb(this.a, "previous");
    if (newCommentInfo) {
      this.a = newCommentInfo;
      return this.provideContent();
    }
    return void 0;
  }
};
CommentsThreadWidgetAccessibleContentProvider = __decorate([
  __param(0, $RJb),
  __param(1, $mJ),
  __param(2, $vl)
], CommentsThreadWidgetAccessibleContentProvider);

// out-build/vs/workbench/contrib/comments/browser/commentsAccessibility.js
var CommentAccessibilityHelpNLS;
(function(CommentAccessibilityHelpNLS2) {
  CommentAccessibilityHelpNLS2.intro = localize(5351, null);
  CommentAccessibilityHelpNLS2.tabFocus = localize(5352, null, `<keybinding:${$Ekb.ID}>`);
  CommentAccessibilityHelpNLS2.commentCommands = localize(5353, null);
  CommentAccessibilityHelpNLS2.escape = localize(5354, null);
  CommentAccessibilityHelpNLS2.nextRange = localize(5355, null, `<keybinding:${"editor.action.nextCommentingRange"}>`);
  CommentAccessibilityHelpNLS2.previousRange = localize(5356, null, `<keybinding:${"editor.action.previousCommentingRange"}>`);
  CommentAccessibilityHelpNLS2.nextCommentThread = localize(5357, null, `<keybinding:${"editor.action.nextCommentThreadAction"}>`);
  CommentAccessibilityHelpNLS2.previousCommentThread = localize(5358, null, `<keybinding:${"editor.action.previousCommentThreadAction"}>`);
  CommentAccessibilityHelpNLS2.nextCommentedRange = localize(5359, null, `<keybinding:${"editor.action.nextCommentedRangeAction"}>`);
  CommentAccessibilityHelpNLS2.previousCommentedRange = localize(5360, null, `<keybinding:${"editor.action.previousCommentedRangeAction"}>`);
  CommentAccessibilityHelpNLS2.addComment = localize(5361, null, `<keybinding:${"workbench.action.addComment"}>`);
  CommentAccessibilityHelpNLS2.submitComment = localize(5362, null, `<keybinding:${"editor.action.submitComment"}>`);
})(CommentAccessibilityHelpNLS || (CommentAccessibilityHelpNLS = {}));
var $Qcc = class extends $3c {
  constructor() {
    super(...arguments);
    this.id = "comments";
    this.verbositySettingKey = "accessibility.verbosity.comments";
    this.options = {
      type: "help"
      /* AccessibleViewType.Help */
    };
  }
  provideContent() {
    return [CommentAccessibilityHelpNLS.tabFocus, CommentAccessibilityHelpNLS.commentCommands, CommentAccessibilityHelpNLS.escape, CommentAccessibilityHelpNLS.addComment, CommentAccessibilityHelpNLS.submitComment, CommentAccessibilityHelpNLS.nextRange, CommentAccessibilityHelpNLS.previousRange].join("\n");
  }
  onClose() {
    this.a?.focus();
  }
};
var $Rcc = class {
  constructor() {
    this.priority = 110;
    this.name = "comments";
    this.type = "help";
    this.when = $7m.or($YJb, CommentContextKeys.commentFocused);
  }
  getProvider(accessor) {
    return accessor.get($Pk).createInstance($Qcc);
  }
};

// out-build/vs/workbench/contrib/comments/browser/comments.contribution.js
$hJ(class Collapse4 extends $cpb {
  constructor() {
    super({
      viewId: $_Rb,
      id: "comments.collapse",
      title: localize(5335, null),
      f1: false,
      icon: $6l.collapseAll,
      menu: {
        id: $bJ.ViewTitle,
        group: "navigation",
        when: $7m.and($7m.and($7m.equals("view", $_Rb), $wSb), $xSb),
        order: 100
      }
    });
  }
  runInView(_accessor, view) {
    view.collapseAll();
  }
});
$hJ(class Expand extends $cpb {
  constructor() {
    super({
      viewId: $_Rb,
      id: "comments.expand",
      title: localize(5336, null),
      f1: false,
      icon: $6l.expandAll,
      menu: {
        id: $bJ.ViewTitle,
        group: "navigation",
        when: $7m.and($7m.and($7m.equals("view", $_Rb), $wSb), $7m.not($xSb.key)),
        order: 100
      }
    });
  }
  runInView(_accessor, view) {
    view.expandAll();
  }
});
$hJ(class Reply extends $gJ {
  constructor() {
    super({
      id: "comments.reply",
      title: localize(5337, null),
      icon: $6l.reply,
      precondition: $7m.equals("canReply", true),
      menu: [
        {
          id: $bJ.CommentsViewThreadActions,
          order: 100
        },
        {
          id: $bJ.AccessibleView,
          when: $7m.and($osb, $7m.equals(
            $tsb.key,
            "comments"
            /* AccessibleViewProviderId.Comments */
          ))
        }
      ]
    });
  }
  run(accessor, marshalledCommentThread) {
    const commentService = accessor.get($RJb);
    const editorService = accessor.get($mJ);
    const uriIdentityService = accessor.get($vl);
    $sSb(commentService, editorService, uriIdentityService, marshalledCommentThread.thread, marshalledCommentThread.thread.comments[marshalledCommentThread.thread.comments.length - 1], true);
  }
});
$Wn.as($Ht.Configuration).registerConfiguration({
  id: "comments",
  order: 20,
  title: localize(5338, null),
  type: "object",
  properties: {
    "comments.openPanel": {
      enum: ["neverOpen", "openOnSessionStart", "openOnSessionStartWithComments"],
      default: "openOnSessionStartWithComments",
      description: localize(5339, null),
      restricted: false,
      markdownDeprecationMessage: localize(5340, null)
    },
    "comments.openView": {
      enum: ["never", "file", "firstFile", "firstFileUnresolved"],
      enumDescriptions: [localize(5341, null), localize(5342, null), localize(5343, null), localize(5344, null)],
      default: "firstFile",
      description: localize(5345, null),
      restricted: false
    },
    "comments.useRelativeTime": {
      type: "boolean",
      default: true,
      description: localize(5346, null)
    },
    "comments.visible": {
      type: "boolean",
      default: true,
      description: localize(5347, null)
    },
    "comments.maxHeight": {
      type: "boolean",
      default: true,
      description: localize(5348, null)
    },
    "comments.collapseOnResolve": {
      type: "boolean",
      default: true,
      description: localize(5349, null)
    }
  }
});
$SC(
  $RJb,
  $SJb,
  1
  /* InstantiationType.Delayed */
);
var $Scc = class $Scc2 extends $3c {
  constructor(c, f) {
    super();
    this.c = c;
    this.f = f;
    this.a = this.B(new $4c());
    this.b = 0;
    this.B(this.c.onDidSetAllCommentThreads(this.g, this));
    this.B(this.c.onDidUpdateCommentThreads(this.h, this));
  }
  g(e) {
    let unresolved = 0;
    for (const thread of e.commentThreads) {
      if (thread.state === CommentThreadState.Unresolved) {
        unresolved++;
      }
    }
    this.j(unresolved);
  }
  h() {
    let unresolved = 0;
    for (const resource of this.c.commentsModel.resourceCommentThreads) {
      for (const thread of resource.commentThreads) {
        if (thread.threadState === CommentThreadState.Unresolved) {
          unresolved++;
        }
      }
    }
    this.j(unresolved);
  }
  j(unresolved) {
    if (unresolved === this.b) {
      return;
    }
    this.b = unresolved;
    const message = localize(5350, null, this.b);
    this.a.value = this.f.showViewActivity($_Rb, { badge: new $wqb(this.b, () => message) });
  }
};
$Scc = __decorate([
  __param(0, $RJb),
  __param(1, $vqb)
], $Scc);
$Wn.as(Extensions2.Workbench).registerWorkbenchContribution(
  $Scc,
  4
  /* LifecyclePhase.Eventually */
);
$vhb.register(new $Occ());
$vhb.register(new $Pcc());
$vhb.register(new $Rcc());

// out-build/vs/workbench/contrib/url/browser/externalUriResolver.js
var $Tcc = class $Tcc2 extends $3c {
  static {
    this.ID = "workbench.contrib.externalUriResolver";
  }
  constructor(_openerService, _workbenchEnvironmentService) {
    super();
    if (_workbenchEnvironmentService.options?.resolveExternalUri) {
      this.B(_openerService.registerExternalUriResolver({
        resolveExternalUri: async (resource) => {
          return {
            resolved: await _workbenchEnvironmentService.options.resolveExternalUri(resource),
            dispose: () => {
            }
          };
        }
      }));
    }
  }
};
$Tcc = __decorate([
  __param(0, $O4),
  __param(1, $M4)
], $Tcc);

// out-build/vs/workbench/contrib/url/browser/trustedDomainsFileSystemProvider.js
var TRUSTED_DOMAINS_SCHEMA = "trustedDomains";
var TRUSTED_DOMAINS_STAT = {
  type: FileType.File,
  ctime: Date.now(),
  mtime: Date.now(),
  size: 0
};
var CONFIG_HELP_TEXT_PRE = `// Links matching one or more entries in the list below can be opened without link protection.
// The following examples show what entries can look like:
// - "https://microsoft.com": Matches this specific domain using https
// - "https://microsoft.com:8080": Matches this specific domain on this port using https
// - "https://microsoft.com:*": Matches this specific domain on any port using https
// - "https://microsoft.com/foo": Matches https://microsoft.com/foo and https://microsoft.com/foo/bar,
//   but not https://microsoft.com/foobar or https://microsoft.com/bar
// - "https://*.microsoft.com": Match all domains ending in "microsoft.com" using https
// - "microsoft.com": Match this specific domain using either http or https
// - "*.microsoft.com": Match all domains ending in "microsoft.com" using either http or https
// - "http://192.168.0.1: Matches this specific IP using http
// - "http://192.168.0.*: Matches all IP's with this prefix using http
// - "*": Match all domains using either http or https
//
`;
var CONFIG_HELP_TEXT_AFTER = `//
// You can use the "Manage Trusted Domains" command to open this file.
// Save this file to apply the trusted domains rules.
`;
var CONFIG_PLACEHOLDER_TEXT = `[
	// "https://microsoft.com"
]`;
function computeTrustedDomainContent(defaultTrustedDomains, trustedDomains, configuring) {
  let content = CONFIG_HELP_TEXT_PRE;
  if (defaultTrustedDomains.length > 0) {
    content += `// By default, VS Code trusts "localhost" as well as the following domains:
`;
    defaultTrustedDomains.forEach((d) => {
      content += `// - "${d}"
`;
    });
  } else {
    content += `// By default, VS Code trusts "localhost".
`;
  }
  content += CONFIG_HELP_TEXT_AFTER;
  content += configuring ? `
// Currently configuring trust for ${configuring}
` : "";
  if (trustedDomains.length === 0) {
    content += CONFIG_PLACEHOLDER_TEXT;
  } else {
    content += JSON.stringify(trustedDomains, null, 2);
  }
  return content;
}
var $Ucc = class $Ucc2 {
  static {
    this.ID = "workbench.contrib.trustedDomainsFileSystemProvider";
  }
  constructor(a, b, c) {
    this.a = a;
    this.b = b;
    this.c = c;
    this.capabilities = 2;
    this.onDidChangeCapabilities = Event2.None;
    this.onDidChangeFile = Event2.None;
    this.a.registerProvider(TRUSTED_DOMAINS_SCHEMA, this);
  }
  stat(resource) {
    return Promise.resolve(TRUSTED_DOMAINS_STAT);
  }
  async readFile(resource) {
    let trustedDomainsContent = this.b.get(
      $_Mb,
      -1
      /* StorageScope.APPLICATION */
    );
    const configuring = resource.fragment;
    const { defaultTrustedDomains, trustedDomains } = await this.c.invokeFunction($cNb);
    if (!trustedDomainsContent || trustedDomainsContent.indexOf(CONFIG_HELP_TEXT_PRE) === -1 || trustedDomainsContent.indexOf(CONFIG_HELP_TEXT_AFTER) === -1 || trustedDomainsContent.indexOf(configuring ?? "") === -1 || [...defaultTrustedDomains, ...trustedDomains].some((d) => !$Kg(trustedDomainsContent).includes(d))) {
      trustedDomainsContent = computeTrustedDomainContent(defaultTrustedDomains, trustedDomains, configuring);
    }
    const buffer = $Ci.fromString(trustedDomainsContent).buffer;
    return buffer;
  }
  writeFile(resource, content, opts) {
    try {
      const trustedDomainsContent = $Ci.wrap(content).toString();
      const trustedDomains = $yw(trustedDomainsContent);
      this.b.store(
        $_Mb,
        trustedDomainsContent,
        -1,
        0
        /* StorageTarget.USER */
      );
      this.b.store(
        $$Mb,
        JSON.stringify(trustedDomains) || "",
        -1,
        0
        /* StorageTarget.USER */
      );
    } catch (err) {
    }
    return Promise.resolve();
  }
  watch(resource, opts) {
    return {
      dispose() {
        return;
      }
    };
  }
  mkdir(resource) {
    return Promise.resolve(void 0);
  }
  readdir(resource) {
    return Promise.resolve(void 0);
  }
  delete(resource, opts) {
    return Promise.resolve(void 0);
  }
  rename(from, to, opts) {
    return Promise.resolve(void 0);
  }
};
$Ucc = __decorate([
  __param(0, $km),
  __param(1, $jv),
  __param(2, $Pk)
], $Ucc);

// out-build/vs/workbench/contrib/url/browser/trustedDomainsValidator.js
var $Vcc = class $Vcc2 {
  constructor(a, b, c, d, e, f, g, h3, i2, j, k, l) {
    this.a = a;
    this.b = b;
    this.c = c;
    this.d = d;
    this.e = e;
    this.f = f;
    this.g = g;
    this.h = h3;
    this.i = i2;
    this.j = j;
    this.k = k;
    this.l = l;
    this.a.registerValidator({ shouldOpen: (uri, options3) => this.validateLink(uri, options3) });
  }
  async validateLink(resource, openOptions) {
    if (!$0g(resource, Schemas.http) && !$0g(resource, Schemas.https)) {
      return true;
    }
    if (openOptions?.fromWorkspace && this.k.isWorkspaceTrusted() && !this.j.getValue("workbench.trustedDomains.promptInTrustedWorkspace")) {
      return true;
    }
    const originalResource = resource;
    let resourceUri;
    if (typeof resource === "string") {
      resourceUri = URI.parse(resource);
    } else {
      resourceUri = resource;
    }
    if (await this.l.isValid(resourceUri)) {
      return true;
    } else {
      const { scheme, authority, path, query, fragment } = resourceUri;
      let formattedLink = `${scheme}://${authority}${path}`;
      const linkTail = `${query ? "?" + query : ""}${fragment ? "#" + fragment : ""}`;
      const remainingLength = Math.max(0, 60 - formattedLink.length);
      const linkTailLengthToKeep = Math.min(Math.max(5, remainingLength), linkTail.length);
      if (linkTailLengthToKeep === linkTail.length) {
        formattedLink += linkTail;
      } else {
        formattedLink += linkTail.charAt(0) + "..." + linkTail.substring(linkTail.length - linkTailLengthToKeep + 1);
      }
      const { result } = await this.c.prompt({
        type: severity_default.Info,
        message: localize(11524, null, this.d.nameShort),
        detail: typeof originalResource === "string" ? originalResource : formattedLink,
        buttons: [
          {
            label: localize(11525, null),
            run: () => true
          },
          {
            label: localize(11526, null),
            run: () => {
              this.g.writeText(typeof originalResource === "string" ? originalResource : resourceUri.toString(true));
              return false;
            }
          },
          {
            label: localize(11527, null),
            run: async () => {
              const { trustedDomains } = this.i.invokeFunction($dNb);
              const domainToOpen = `${scheme}://${authority}`;
              const pickedDomains = await $bNb(trustedDomains, domainToOpen, resourceUri, this.e, this.b, this.f, this.h);
              if (pickedDomains.indexOf("*") !== -1) {
                return true;
              }
              if ($hNb(resourceUri, pickedDomains)) {
                return true;
              }
              return false;
            }
          }
        ],
        cancelButton: {
          run: () => false
        }
      });
      return result;
    }
  }
};
$Vcc = __decorate([
  __param(0, $O4),
  __param(1, $jv),
  __param(2, $Yv),
  __param(3, $Vu),
  __param(4, $1M),
  __param(5, $mJ),
  __param(6, $30),
  __param(7, $zv),
  __param(8, $Pk),
  __param(9, $kl),
  __param(10, $4M),
  __param(11, $fNb)
], $Vcc);

// out-build/vs/workbench/contrib/url/browser/url.contribution.js
var OpenUrlAction = class extends $gJ {
  constructor() {
    super({
      id: "workbench.action.url.openUrl",
      title: localize2(11530, "Open URL"),
      category: $qn.Developer,
      f1: true
    });
  }
  async run(accessor) {
    const quickInputService = accessor.get($1M);
    const urlService = accessor.get($4y);
    return quickInputService.input({ prompt: localize(11528, null) }).then((input) => {
      if (input) {
        const uri = URI.parse(input);
        urlService.open(uri, { originalUrl: input });
      }
    });
  }
};
$hJ(OpenUrlAction);
$tn.registerCommand($aNb);
$dJ.appendMenuItem($bJ.CommandPalette, {
  command: {
    id: $aNb.id,
    title: $aNb.description.description
  }
});
$Wn.as(Extensions2.Workbench).registerWorkbenchContribution(
  $Vcc,
  3
  /* LifecyclePhase.Restored */
);
$PL(
  $Ucc.ID,
  $Ucc,
  2
  /* WorkbenchPhase.BlockRestore */
);
$PL(
  $Tcc.ID,
  $Tcc,
  2
  /* WorkbenchPhase.BlockRestore */
);
var configurationRegistry13 = $Wn.as($Ht.Configuration);
configurationRegistry13.registerConfiguration({
  ...$UL,
  properties: {
    "workbench.trustedDomains.promptInTrustedWorkspace": {
      scope: 1,
      type: "boolean",
      default: false,
      description: localize(11529, null)
    }
  }
});
$SC(
  $fNb,
  $gNb,
  1
  /* InstantiationType.Delayed */
);

// out-build/vs/workbench/contrib/webviewPanel/browser/webviewCommands.js
var webviewActiveContextKeyExpr = $7m.and(
  $7m.equals("activeEditor", $ROb.ID),
  EditorContextKeys.focus.toNegated()
  /* https://github.com/microsoft/vscode/issues/58668 */
);
var $Wcc = class _$Wcc extends $gJ {
  static {
    this.ID = "editor.action.webvieweditor.showFind";
  }
  static {
    this.LABEL = localize(11801, null);
  }
  constructor() {
    super({
      id: _$Wcc.ID,
      title: _$Wcc.LABEL,
      keybinding: {
        when: $7m.and(webviewActiveContextKeyExpr, $Brb),
        primary: 2048 | 36,
        weight: 100
        /* KeybindingWeight.EditorContrib */
      }
    });
  }
  run(accessor) {
    getActiveWebviewEditor(accessor)?.showFind();
  }
};
var $Xcc = class _$Xcc extends $gJ {
  static {
    this.ID = "editor.action.webvieweditor.hideFind";
  }
  static {
    this.LABEL = localize(11802, null);
  }
  constructor() {
    super({
      id: _$Xcc.ID,
      title: _$Xcc.LABEL,
      keybinding: {
        when: $7m.and(webviewActiveContextKeyExpr, $zrb),
        primary: 9,
        weight: 100
        /* KeybindingWeight.EditorContrib */
      }
    });
  }
  run(accessor) {
    getActiveWebviewEditor(accessor)?.hideFind();
  }
};
var $Ycc = class _$Ycc extends $gJ {
  static {
    this.ID = "editor.action.webvieweditor.findNext";
  }
  static {
    this.LABEL = localize(11803, null);
  }
  constructor() {
    super({
      id: _$Ycc.ID,
      title: _$Ycc.LABEL,
      keybinding: {
        when: $7m.and(webviewActiveContextKeyExpr, $Arb),
        primary: 3,
        weight: 100
        /* KeybindingWeight.EditorContrib */
      }
    });
  }
  run(accessor) {
    getActiveWebviewEditor(accessor)?.runFindAction(false);
  }
};
var $Zcc = class _$Zcc extends $gJ {
  static {
    this.ID = "editor.action.webvieweditor.findPrevious";
  }
  static {
    this.LABEL = localize(11804, null);
  }
  constructor() {
    super({
      id: _$Zcc.ID,
      title: _$Zcc.LABEL,
      keybinding: {
        when: $7m.and(webviewActiveContextKeyExpr, $Arb),
        primary: 1024 | 3,
        weight: 100
        /* KeybindingWeight.EditorContrib */
      }
    });
  }
  run(accessor) {
    getActiveWebviewEditor(accessor)?.runFindAction(true);
  }
};
var $1cc = class _$1cc extends $gJ {
  static {
    this.ID = "workbench.action.webview.reloadWebviewAction";
  }
  static {
    this.LABEL = localize2(11805, "Reload Webviews");
  }
  constructor() {
    super({
      id: _$1cc.ID,
      title: _$1cc.LABEL,
      category: $qn.Developer,
      menu: [{
        id: $bJ.CommandPalette
      }]
    });
  }
  async run(accessor) {
    const webviewService = accessor.get($Crb);
    for (const webview of webviewService.webviews) {
      webview.reload();
    }
  }
};
function getActiveWebviewEditor(accessor) {
  const editorService = accessor.get($mJ);
  const activeEditor = editorService.activeEditor;
  return activeEditor instanceof $8Lb ? activeEditor.webview : void 0;
}

// out-build/vs/workbench/contrib/webviewPanel/browser/webviewEditorInputSerializer.js
var $URb = class $URb2 {
  static {
    this.ID = $8Lb.typeId;
  }
  constructor(a) {
    this.a = a;
  }
  canSerialize(input) {
    return this.a.shouldPersist(input);
  }
  serialize(input) {
    if (!this.canSerialize(input)) {
      return void 0;
    }
    const data = this.c(input);
    try {
      return JSON.stringify(data);
    } catch {
      return void 0;
    }
  }
  deserialize(_instantiationService, serializedEditorInput) {
    const data = this.b(JSON.parse(serializedEditorInput));
    return this.a.openRevivedWebview({
      webviewInitInfo: {
        providedViewType: data.providedId,
        origin: data.origin,
        title: data.title,
        options: data.webviewOptions,
        contentOptions: data.contentOptions,
        extension: data.extension
      },
      viewType: data.viewType,
      title: data.title,
      iconPath: data.iconPath,
      state: data.state,
      group: data.group
    });
  }
  b(data) {
    return {
      ...data,
      extension: $VRb(data.extensionId, data.extensionLocation),
      iconPath: reviveIconPath(data.iconPath),
      state: reviveState(data.state),
      webviewOptions: $WRb(data.options),
      contentOptions: $XRb(data.options)
    };
  }
  c(input) {
    return {
      origin: input.webview.origin,
      viewType: input.viewType,
      providedId: input.providedId,
      title: input.getName(),
      options: { ...input.webview.options, ...input.webview.contentOptions },
      extensionLocation: input.extension?.location,
      extensionId: input.extension?.id.value,
      state: input.webview.state,
      iconPath: input.iconPath ? { light: input.iconPath.light, dark: input.iconPath.dark } : void 0,
      group: input.group
    };
  }
};
$URb = __decorate([
  __param(0, $SOb)
], $URb);
function $VRb(extensionId, extensionLocation) {
  if (!extensionId) {
    return void 0;
  }
  const location3 = reviveUri(extensionLocation);
  if (!location3) {
    return void 0;
  }
  return {
    id: new $5z(extensionId),
    location: location3
  };
}
function reviveIconPath(data) {
  if (!data) {
    return void 0;
  }
  const light = reviveUri(data.light);
  const dark = reviveUri(data.dark);
  return light && dark ? { light, dark } : void 0;
}
function reviveUri(data) {
  if (!data) {
    return void 0;
  }
  try {
    if (typeof data === "string") {
      return URI.parse(data);
    }
    return URI.from(data);
  } catch {
    return void 0;
  }
}
function reviveState(state) {
  return typeof state === "string" ? state : void 0;
}
function $WRb(options3) {
  return options3;
}
function $XRb(options3) {
  return {
    ...options3,
    localResourceRoots: options3.localResourceRoots?.map((uri) => reviveUri(uri))
  };
}

// out-build/vs/workbench/contrib/webviewPanel/browser/webviewPanel.contribution.js
$Wn.as($ZK.EditorPane).registerEditorPane($7tb.create($ROb, $ROb.ID, localize(11807, null)), [new $Nk($8Lb)]);
var WebviewPanelContribution = class WebviewPanelContribution2 extends $3c {
  static {
    this.ID = "workbench.contrib.webviewPanel";
  }
  constructor(editorService, a) {
    super();
    this.a = a;
    this.B(editorService.onWillOpenEditor((e) => {
      const group2 = a.getGroup(e.groupId);
      if (group2) {
        this.b(e.editor, group2);
      }
    }));
  }
  b(editor, group2) {
    if (!(editor instanceof $8Lb) || editor.typeId !== $8Lb.typeId) {
      return;
    }
    if (group2.contains(editor)) {
      return;
    }
    let previousGroup;
    const groups = this.a.groups;
    for (const group3 of groups) {
      if (group3.contains(editor)) {
        previousGroup = group3;
        break;
      }
    }
    if (!previousGroup) {
      return;
    }
    previousGroup.closeEditor(editor);
  }
};
WebviewPanelContribution = __decorate([
  __param(0, $mJ),
  __param(1, $iJ)
], WebviewPanelContribution);
$PL(
  WebviewPanelContribution.ID,
  WebviewPanelContribution,
  1
  /* WorkbenchPhase.BlockStartup */
);
$Wn.as($ZK.EditorFactory).registerEditorSerializer($URb.ID, $URb);
$SC(
  $SOb,
  $UOb,
  1
  /* InstantiationType.Delayed */
);
$hJ($Wcc);
$hJ($Xcc);
$hJ($Ycc);
$hJ($Zcc);
$hJ($1cc);

// out-build/vs/workbench/contrib/webviewView/browser/webviewView.contribution.js
$SC(
  $3Rb,
  $4Rb,
  1
  /* InstantiationType.Delayed */
);

// out-build/vs/workbench/contrib/customEditor/browser/customEditorInputFactory.js
var $YRb = class $YRb2 extends $URb {
  static {
    this.ID = $VOb.typeId;
  }
  constructor(webviewWorkbenchService, d, e) {
    super(webviewWorkbenchService);
    this.d = d;
    this.e = e;
  }
  serialize(input) {
    const dirty = input.isDirty();
    const data = {
      ...this.c(input),
      editorResource: input.resource.toJSON(),
      dirty,
      backupId: dirty ? input.backupId : void 0
    };
    try {
      return JSON.stringify(data);
    } catch {
      return void 0;
    }
  }
  b(data) {
    return {
      ...super.b(data),
      editorResource: URI.from(data.editorResource),
      dirty: data.dirty
    };
  }
  deserialize(_instantiationService, serializedEditorInput) {
    const data = this.b(JSON.parse(serializedEditorInput));
    const webview = reviveWebview(this.e, data);
    const customInput = this.d.createInstance($VOb, { resource: data.editorResource, viewType: data.viewType }, webview, { startsDirty: data.dirty, backupId: data.backupId });
    if (typeof data.group === "number") {
      customInput.updateGroup(data.group);
    }
    return customInput;
  }
};
$YRb = __decorate([
  __param(0, $SOb),
  __param(1, $Pk),
  __param(2, $Crb)
], $YRb);
function reviveWebview(webviewService, data) {
  const webview = webviewService.createWebviewOverlay({
    providedViewType: data.viewType,
    origin: data.origin,
    title: void 0,
    options: {
      purpose: "customEditor",
      enableFindWidget: data.webviewOptions.enableFindWidget,
      retainContextWhenHidden: data.webviewOptions.retainContextWhenHidden
    },
    contentOptions: data.contentOptions,
    extension: data.extension
  });
  webview.state = data.state;
  return webview;
}
var $ZRb = class $ZRb2 extends $3c {
  static {
    this.ID = "workbench.contrib.complexCustomWorkingCopyEditorHandler";
  }
  constructor(a, _workingCopyEditorService, b, c, _customEditorService) {
    super();
    this.a = a;
    this.b = b;
    this.c = c;
    this.B(_workingCopyEditorService.registerHandler(this));
  }
  handles(workingCopy) {
    return workingCopy.resource.scheme === Schemas.vscodeCustomEditor;
  }
  isOpen(workingCopy, editor) {
    if (!this.handles(workingCopy)) {
      return false;
    }
    if (workingCopy.resource.authority === "jupyter-notebook-ipynb" && editor instanceof $trb) {
      try {
        const data = JSON.parse(workingCopy.resource.query);
        const workingCopyResource = URI.from(data);
        return $oh(workingCopyResource, editor.resource);
      } catch {
        return false;
      }
    }
    if (!(editor instanceof $VOb)) {
      return false;
    }
    if (workingCopy.resource.authority !== editor.viewType.replace(/[^a-z0-9\-_]/gi, "-").toLowerCase()) {
      return false;
    }
    try {
      const data = JSON.parse(workingCopy.resource.query);
      const workingCopyResource = URI.from(data);
      return $oh(workingCopyResource, editor.resource);
    } catch {
      return false;
    }
  }
  async createEditor(workingCopy) {
    const backup = await this.b.resolve(workingCopy);
    if (!backup?.meta) {
      throw new Error(`No backup found for custom editor: ${workingCopy.resource}`);
    }
    const backupData = backup.meta;
    const extension = $VRb(backupData.extension?.id, backupData.extension?.location);
    const webview = reviveWebview(this.c, {
      viewType: backupData.viewType,
      origin: backupData.webview.origin,
      webviewOptions: $WRb(backupData.webview.options),
      contentOptions: $XRb(backupData.webview.options),
      state: backupData.webview.state,
      extension
    });
    const editor = this.a.createInstance($VOb, { resource: URI.revive(backupData.editorResource), viewType: backupData.viewType }, webview, { backupId: backupData.backupId });
    editor.updateGroup(0);
    return editor;
  }
};
$ZRb = __decorate([
  __param(0, $Pk),
  __param(1, $6J),
  __param(2, $yG),
  __param(3, $Crb),
  __param(4, $LOb)
], $ZRb);

// out-build/vs/workbench/contrib/customEditor/common/customEditorModelManager.js
var $2cc = class {
  constructor() {
    this.a = /* @__PURE__ */ new Map();
  }
  async getAllModels(resource) {
    const keyStart = `${resource.toString()}@@@`;
    const models = [];
    for (const [key2, entry] of this.a) {
      if (key2.startsWith(keyStart) && entry.model) {
        models.push(await entry.model);
      }
    }
    return models;
  }
  async get(resource, viewType) {
    const key2 = this.b(resource, viewType);
    const entry = this.a.get(key2);
    return entry?.model;
  }
  tryRetain(resource, viewType) {
    const key2 = this.b(resource, viewType);
    const entry = this.a.get(key2);
    if (!entry) {
      return void 0;
    }
    entry.counter++;
    return entry.model.then((model) => {
      return {
        object: model,
        dispose: $Qc(() => {
          if (--entry.counter <= 0) {
            entry.model.then((x) => x.dispose());
            this.a.delete(key2);
          }
        })
      };
    });
  }
  add(resource, viewType, model) {
    const key2 = this.b(resource, viewType);
    const existing = this.a.get(key2);
    if (existing) {
      throw new Error("Model already exists");
    }
    this.a.set(key2, { viewType, model, counter: 0 });
    return this.tryRetain(resource, viewType);
  }
  disposeAllModelsForView(viewType) {
    for (const [key2, value] of this.a) {
      if (value.viewType === viewType) {
        value.model.then((x) => x.dispose());
        this.a.delete(key2);
      }
    }
  }
  b(resource, viewType) {
    return `${resource.toString()}@@@${viewType}`;
  }
};

// out-build/vs/workbench/contrib/customEditor/common/extensionPoint.js
var Fields = Object.freeze({
  viewType: "viewType",
  displayName: "displayName",
  selector: "selector",
  priority: "priority"
});
var CustomEditorsContribution = {
  description: localize(5464, null),
  type: "array",
  defaultSnippets: [{
    body: [{
      [Fields.viewType]: "$1",
      [Fields.displayName]: "$2",
      [Fields.selector]: [{
        filenamePattern: "$3"
      }]
    }]
  }],
  items: {
    type: "object",
    required: [
      Fields.viewType,
      Fields.displayName,
      Fields.selector
    ],
    properties: {
      [Fields.viewType]: {
        type: "string",
        markdownDescription: localize(5465, null)
      },
      [Fields.displayName]: {
        type: "string",
        description: localize(5466, null)
      },
      [Fields.selector]: {
        type: "array",
        description: localize(5467, null),
        items: {
          type: "object",
          defaultSnippets: [{
            body: {
              filenamePattern: "$1"
            }
          }],
          properties: {
            filenamePattern: {
              type: "string",
              description: localize(5468, null)
            }
          }
        }
      },
      [Fields.priority]: {
        type: "string",
        markdownDeprecationMessage: localize(5469, null),
        enum: [
          "default",
          "option"
        ],
        markdownEnumDescriptions: [
          localize(5470, null),
          localize(5471, null)
        ],
        default: "default"
      }
    }
  }
};
var $3cc = $tN.registerExtensionPoint({
  extensionPoint: "customEditors",
  deps: [$Ssb],
  jsonSchema: CustomEditorsContribution,
  activationEventsGenerator: (contribs, result) => {
    for (const contrib of contribs) {
      const viewType = contrib[Fields.viewType];
      if (viewType) {
        result.push(`onCustomEditor:${viewType}`);
      }
    }
  }
});
var CustomEditorsDataRenderer = class extends $3c {
  constructor() {
    super(...arguments);
    this.type = "table";
  }
  shouldRender(manifest) {
    return !!manifest.contributes?.customEditors;
  }
  render(manifest) {
    const customEditors = manifest.contributes?.customEditors || [];
    if (!customEditors.length) {
      return { data: { headers: [], rows: [] }, dispose: () => {
      } };
    }
    const headers = [
      localize(5472, null),
      localize(5473, null),
      localize(5474, null)
    ];
    const rows = customEditors.map((customEditor) => {
      return [
        customEditor.viewType,
        customEditor.priority ?? "",
        $Mb(customEditor.selector.map((x) => x.filenamePattern)).join(", ")
      ];
    });
    return {
      data: {
        headers,
        rows
      },
      dispose: () => {
      }
    };
  }
};
$Wn.as(Extensions3.ExtensionFeaturesRegistry).registerExtensionFeature({
  id: "customEditors",
  label: localize(5475, null),
  access: {
    canToggle: false
  },
  renderer: new $Nk(CustomEditorsDataRenderer)
});

// out-build/vs/workbench/contrib/customEditor/common/contributedCustomEditors.js
var $4cc = class _$4cc extends $3c {
  static {
    this.a = "customEditors";
  }
  static {
    this.b = "editors";
  }
  constructor(storageService) {
    super();
    this.c = /* @__PURE__ */ new Map();
    this.g = this.B(new $ze());
    this.onChange = this.g.event;
    this.f = new $Slb(_$4cc.a, storageService);
    const mementoObject = this.f.getMemento(
      0,
      1
      /* StorageTarget.MACHINE */
    );
    for (const info of mementoObject[_$4cc.b] || []) {
      this.j(new $OOb(info));
    }
    $3cc.setHandler((extensions) => {
      this.h(extensions);
    });
  }
  h(extensions) {
    this.c.clear();
    for (const extension of extensions) {
      for (const webviewEditorContribution of extension.value) {
        this.j(new $OOb({
          id: webviewEditorContribution.viewType,
          displayName: webviewEditorContribution.displayName,
          providerDisplayName: extension.description.isBuiltin ? localize(5461, null) : extension.description.displayName || extension.description.identifier.value,
          selector: webviewEditorContribution.selector || [],
          priority: getPriorityFromContribution(webviewEditorContribution, extension.description)
        }));
      }
    }
    const mementoObject = this.f.getMemento(
      0,
      1
      /* StorageTarget.MACHINE */
    );
    mementoObject[_$4cc.b] = Array.from(this.c.values());
    this.f.saveMemento();
    this.g.fire();
  }
  [Symbol.iterator]() {
    return this.c.values();
  }
  get(viewType) {
    return this.c.get(viewType);
  }
  getContributedEditors(resource) {
    return Array.from(this.c.values()).filter((customEditor) => customEditor.matches(resource));
  }
  j(info) {
    if (this.c.has(info.id)) {
      console.error(`Custom editor with id '${info.id}' already registered`);
      return;
    }
    this.c.set(info.id, info);
  }
};
function getPriorityFromContribution(contribution, extension) {
  switch (contribution.priority) {
    case RegisteredEditorPriority.default:
    case RegisteredEditorPriority.option:
      return contribution.priority;
    case RegisteredEditorPriority.builtin:
      return extension.isBuiltin ? RegisteredEditorPriority.builtin : RegisteredEditorPriority.default;
    default:
      return RegisteredEditorPriority.default;
  }
}

// out-build/vs/workbench/contrib/customEditor/browser/customEditors.js
var $5cc = class $5cc2 extends $3c {
  constructor(fileService, storageService, n, r2, s, t, u) {
    super();
    this.n = n;
    this.r = r2;
    this.s = s;
    this.t = t;
    this.u = u;
    this.b = 0;
    this.c = this.B(new $2c());
    this.g = /* @__PURE__ */ new Map();
    this.h = new $2cc();
    this.j = this.B(new $ze());
    this.onDidChangeEditorTypes = this.j.event;
    this.m = $Wn.as($ZK.EditorFactory).getFileEditorFactory();
    this.a = this.B(new $4cc(storageService));
    this.u.bufferChangeEvents(this.y.bind(this));
    this.B(this.a.onChange(() => {
      this.u.bufferChangeEvents(this.y.bind(this));
      this.j.fire();
    }));
    const activeCustomEditorContextKeyProvider = {
      contextKey: $MOb,
      getGroupContextKeyValue: (group2) => this.C(group2),
      onDidChange: this.onDidChangeEditorTypes
    };
    const customEditorIsEditableContextKeyProvider = {
      contextKey: $NOb,
      getGroupContextKeyValue: (group2) => this.D(group2),
      onDidChange: this.onDidChangeEditorTypes
    };
    this.B(this.r.registerContextKeyProvider(activeCustomEditorContextKeyProvider));
    this.B(this.r.registerContextKeyProvider(customEditorIsEditableContextKeyProvider));
    this.B(fileService.onDidRunOperation((e) => {
      if (e.isOperation(
        2
        /* FileOperation.MOVE */
      )) {
        this.F(e.resource, this.t.asCanonicalUri(e.target.resource));
      }
    }));
    const PRIORITY3 = 105;
    this.B($05.addImplementation(PRIORITY3, "custom-editor", () => {
      return this.w((editor) => editor.undo());
    }));
    this.B($$5.addImplementation(PRIORITY3, "custom-editor", () => {
      return this.w((editor) => editor.redo());
    }));
  }
  getEditorTypes() {
    return [...this.a];
  }
  w(f) {
    const activeEditor = this.n.activeEditor;
    if (activeEditor instanceof $VOb) {
      const result = f(activeEditor);
      if (result) {
        return result;
      }
      return true;
    }
    return false;
  }
  y() {
    this.c.clear();
    for (const contributedEditor of this.a) {
      for (const globPattern of contributedEditor.selector) {
        if (!globPattern.filenamePattern) {
          continue;
        }
        this.c.add(this.u.registerEditor(globPattern.filenamePattern, {
          id: contributedEditor.id,
          label: contributedEditor.displayName,
          detail: contributedEditor.providerDisplayName,
          priority: contributedEditor.priority
        }, {
          singlePerResource: () => !(this.getCustomEditorCapabilities(contributedEditor.id)?.supportsMultipleEditorsPerDocument ?? false)
        }, {
          createEditorInput: ({ resource }, group2) => {
            return { editor: $VOb.create(this.s, resource, contributedEditor.id, group2.id) };
          },
          createUntitledEditorInput: ({ resource }, group2) => {
            return { editor: $VOb.create(this.s, resource ?? URI.from({ scheme: Schemas.untitled, authority: `Untitled-${this.b++}` }), contributedEditor.id, group2.id) };
          },
          createDiffEditorInput: (diffEditorInput, group2) => {
            return { editor: this.z(diffEditorInput, contributedEditor.id, group2) };
          }
        }));
      }
    }
  }
  z(editor, editorID, group2) {
    const modifiedOverride = $VOb.create(this.s, $Kg(editor.modified.resource), editorID, group2.id, { customClasses: "modified" });
    const originalOverride = $VOb.create(this.s, $Kg(editor.original.resource), editorID, group2.id, { customClasses: "original" });
    return this.s.createInstance($fub, editor.label, editor.description, originalOverride, modifiedOverride, true);
  }
  get models() {
    return this.h;
  }
  getCustomEditor(viewType) {
    return this.a.get(viewType);
  }
  getContributedCustomEditors(resource) {
    return new $POb(this.a.getContributedEditors(resource));
  }
  getUserConfiguredCustomEditors(resource) {
    const resourceAssocations = this.u.getAssociationsForResource(resource);
    return new $POb($Mb(resourceAssocations.map((association) => this.a.get(association.viewType))));
  }
  getAllCustomEditors(resource) {
    return new $POb([
      ...this.getUserConfiguredCustomEditors(resource).allEditors,
      ...this.getContributedCustomEditors(resource).allEditors
    ]);
  }
  registerCustomEditorCapabilities(viewType, options3) {
    if (this.g.has(viewType)) {
      throw new Error(`Capabilities for ${viewType} already set`);
    }
    this.g.set(viewType, options3);
    return $1c(() => {
      this.g.delete(viewType);
    });
  }
  getCustomEditorCapabilities(viewType) {
    return this.g.get(viewType);
  }
  C(group2) {
    const activeEditorPane = group2.activeEditorPane;
    const resource = activeEditorPane?.input?.resource;
    if (!resource) {
      return "";
    }
    return activeEditorPane?.input instanceof $VOb ? activeEditorPane.input.viewType : "";
  }
  D(group2) {
    const activeEditorPane = group2.activeEditorPane;
    const resource = activeEditorPane?.input?.resource;
    if (!resource) {
      return false;
    }
    return activeEditorPane?.input instanceof $VOb;
  }
  async F(oldResource, newResource) {
    if ($th(oldResource).toLowerCase() === $th(newResource).toLowerCase()) {
      return;
    }
    const possibleEditors = this.getAllCustomEditors(newResource);
    if (!possibleEditors.allEditors.some((editor) => editor.priority !== RegisteredEditorPriority.option)) {
      return;
    }
    const editorsToReplace = /* @__PURE__ */ new Map();
    for (const group2 of this.r.groups) {
      for (const editor of group2.editors) {
        if (this.m.isFileEditor(editor) && !(editor instanceof $VOb) && $oh(editor.resource, newResource)) {
          let entry = editorsToReplace.get(group2.id);
          if (!entry) {
            entry = [];
            editorsToReplace.set(group2.id, entry);
          }
          entry.push(editor);
        }
      }
    }
    if (!editorsToReplace.size) {
      return;
    }
    for (const [group2, entries2] of editorsToReplace) {
      this.n.replaceEditors(entries2.map((editor) => {
        let replacement;
        if (possibleEditors.defaultEditor) {
          const viewType = possibleEditors.defaultEditor.id;
          replacement = $VOb.create(this.s, newResource, viewType, group2);
        } else {
          replacement = { resource: newResource, options: { override: $1K.id } };
        }
        return {
          editor,
          replacement,
          options: {
            preserveFocus: true
          }
        };
      }), group2);
    }
  }
};
$5cc = __decorate([
  __param(0, $km),
  __param(1, $jv),
  __param(2, $mJ),
  __param(3, $iJ),
  __param(4, $Pk),
  __param(5, $vl),
  __param(6, $4L)
], $5cc);

// out-build/vs/workbench/contrib/customEditor/browser/customEditor.contribution.js
$SC(
  $LOb,
  $5cc,
  1
  /* InstantiationType.Delayed */
);
$Wn.as($ZK.EditorPane).registerEditorPane($7tb.create($ROb, $ROb.ID, "Webview Editor"), [
  new $Nk($VOb)
]);
$Wn.as($ZK.EditorFactory).registerEditorSerializer($YRb.ID, $YRb);
$PL(
  $ZRb.ID,
  $ZRb,
  1
  /* WorkbenchPhase.BlockStartup */
);

// out-build/vs/workbench/contrib/externalUriOpener/common/externalUriOpener.contribution.js
$SC(
  $MRb,
  $NRb,
  1
  /* InstantiationType.Delayed */
);
$Wn.as($Ht.Configuration).registerConfiguration($JRb);

// out-build/vs/workbench/contrib/extensions/common/extensionsInput.js
var ExtensionEditorIcon = $9r("extensions-editor-label-icon", $6l.extensions, localize(6978, null));
var $szb = class _$szb extends $nG {
  static {
    this.ID = "workbench.extensions.input2";
  }
  get typeId() {
    return _$szb.ID;
  }
  get capabilities() {
    return 2 | 8;
  }
  get resource() {
    return URI.from({
      scheme: Schemas.extension,
      path: $nc(this.a.identifier.id, "extension")
    });
  }
  constructor(a) {
    super();
    this.a = a;
  }
  get extension() {
    return this.a;
  }
  getName() {
    return localize(6979, null, this.a.displayName);
  }
  getIcon() {
    return ExtensionEditorIcon;
  }
  matches(other) {
    if (super.matches(other)) {
      return true;
    }
    return other instanceof _$szb && $DA(this.a.identifier, other.a.identifier);
  }
};

// out-build/vs/workbench/contrib/extensions/browser/extensionFeaturesTab.js
var RuntimeStatusMarkdownRenderer = class RuntimeStatusMarkdownRenderer2 extends $3c {
  static {
    this.ID = "runtimeStatus";
  }
  constructor(c, h3, j, m) {
    super();
    this.c = c;
    this.h = h3;
    this.j = j;
    this.m = m;
    this.type = "element";
  }
  shouldRender(manifest) {
    const extensionId = new $5z($GA(manifest.publisher, manifest.name));
    if (!this.c.extensions.some((e) => $5z.equals(e.identifier, extensionId))) {
      return false;
    }
    return !!manifest.main || !!manifest.browser;
  }
  render(manifest) {
    const disposables = new $2c();
    const extensionId = new $5z($GA(manifest.publisher, manifest.name));
    const emitter = disposables.add(new $ze());
    disposables.add(this.c.onDidChangeExtensionsStatus((e) => {
      if (e.some((extension) => $5z.equals(extension, extensionId))) {
        emitter.fire(this.n(manifest, disposables));
      }
    }));
    disposables.add(this.m.onDidChangeAccessData((e) => emitter.fire(this.n(manifest, disposables))));
    return {
      onDidChange: emitter.event,
      data: this.n(manifest, disposables),
      dispose: () => disposables.dispose()
    };
  }
  n(manifest, disposables) {
    const container2 = $(".runtime-status");
    const extensionId = new $5z($GA(manifest.publisher, manifest.name));
    const status = this.c.getExtensionsStatus()[extensionId.value];
    if (this.c.extensions.some((extension) => $5z.equals(extension.identifier, extensionId))) {
      const data = new $bm();
      data.appendMarkdown(`### ${localize(6411, null)}

`);
      if (status.activationTimes) {
        if (status.activationTimes.activationReason.startup) {
          data.appendMarkdown(`Activated on Startup: \`${status.activationTimes.activateCallTime}ms\``);
        } else {
          data.appendMarkdown(`Activated by \`${status.activationTimes.activationReason.activationEvent}\` event: \`${status.activationTimes.activateCallTime}ms\``);
        }
      } else {
        data.appendMarkdown("Not yet activated");
      }
      this.r(data, container2, disposables);
    }
    const features = $Wn.as(Extensions3.ExtensionFeaturesRegistry).getExtensionFeatures();
    for (const feature of features) {
      const accessData = this.m.getAccessData(extensionId, feature.id);
      if (accessData) {
        this.r(new $bm(`
 ### ${localize(6412, null, feature.label)}

`), container2, disposables);
        if (accessData.accessTimes.length) {
          const description = $bk(container2, $(".feature-chart-description", void 0, localize(6413, null, accessData?.accessTimes.length, feature.accessDataLabel ?? feature.label)));
          description.style.marginBottom = "8px";
          this.s(container2, accessData.accessTimes, disposables);
        }
        const status2 = accessData?.current?.status;
        if (status2) {
          const data = new $bm();
          if (status2?.severity === severity_default.Error) {
            data.appendMarkdown(`$(${$vCb.id}) ${status2.message}

`);
          }
          if (status2?.severity === severity_default.Warning) {
            data.appendMarkdown(`$(${$wCb.id}) ${status2.message}

`);
          }
          if (data.value) {
            this.r(data, container2, disposables);
          }
        }
      }
    }
    if (status.runtimeErrors.length || status.messages.length) {
      const data = new $bm();
      if (status.runtimeErrors.length) {
        data.appendMarkdown(`
 ### ${localize(6414, null, status.runtimeErrors.length)}
`);
        for (const error of status.runtimeErrors) {
          data.appendMarkdown(`$(${$6l.error.id})&nbsp;${$qb(error)}

`);
        }
      }
      if (status.messages.length) {
        data.appendMarkdown(`
 ### ${localize(6415, null, status.messages.length)}
`);
        for (const message of status.messages) {
          data.appendMarkdown(`$(${(message.type === severity_default.Error ? $6l.error : message.type === severity_default.Warning ? $6l.warning : $6l.info).id})&nbsp;${message.message}

`);
        }
      }
      if (data.value) {
        this.r(data, container2, disposables);
      }
    }
    return container2;
  }
  r(markdown, container2, disposables) {
    const { element, dispose } = $D1({
      value: markdown.value,
      isTrusted: markdown.isTrusted,
      supportThemeIcons: true
    }, {
      actionHandler: {
        callback: (content) => this.h.open(content, { allowCommands: !!markdown.isTrusted }).catch($gb),
        disposables
      }
    });
    disposables.add($1c(dispose));
    $bk(container2, element);
  }
  s(container2, accessTimes, disposables) {
    const width2 = 450;
    const height = 250;
    const margin = { top: 0, right: 4, bottom: 20, left: 4 };
    const innerWidth = width2 - margin.left - margin.right;
    const innerHeight = height - margin.top - margin.bottom;
    const chartContainer = $bk(container2, $(".feature-chart-container"));
    chartContainer.style.position = "relative";
    const tooltip = $bk(chartContainer, $(".feature-chart-tooltip"));
    tooltip.style.position = "absolute";
    tooltip.style.width = "0px";
    tooltip.style.height = "0px";
    let maxCount = 100;
    const map = /* @__PURE__ */ new Map();
    for (const accessTime of accessTimes) {
      const day2 = `${accessTime.getDate()} ${accessTime.toLocaleString("default", { month: "short" })}`;
      map.set(day2, (map.get(day2) ?? 0) + 1);
      maxCount = Math.max(maxCount, map.get(day2));
    }
    const now = /* @__PURE__ */ new Date();
    const points = [];
    for (let i2 = 0; i2 <= 30; i2++) {
      const date = new Date(now);
      date.setDate(now.getDate() - (30 - i2));
      const dateString = `${date.getDate()} ${date.toLocaleString("default", { month: "short" })}`;
      const count = map.get(dateString) ?? 0;
      const x = i2 / 30 * innerWidth;
      const y = innerHeight - count / maxCount * innerHeight;
      points.push({ x, y, date: dateString, count });
    }
    const chart = $bk(chartContainer, $(".feature-chart"));
    const svg2 = $bk(chart, $.SVG("svg"));
    svg2.setAttribute("width", `${width2}px`);
    svg2.setAttribute("height", `${height}px`);
    svg2.setAttribute("viewBox", `0 0 ${width2} ${height}`);
    const g = $.SVG("g");
    g.setAttribute("transform", `translate(${margin.left},${margin.top})`);
    svg2.appendChild(g);
    const xAxisLine = $.SVG("line");
    xAxisLine.setAttribute("x1", "0");
    xAxisLine.setAttribute("y1", `${innerHeight}`);
    xAxisLine.setAttribute("x2", `${innerWidth}`);
    xAxisLine.setAttribute("y2", `${innerHeight}`);
    xAxisLine.setAttribute("stroke", $Zn($Io));
    xAxisLine.setAttribute("stroke-width", "1px");
    g.appendChild(xAxisLine);
    for (let i2 = 1; i2 <= 30; i2 += 7) {
      const date = new Date(now);
      date.setDate(now.getDate() - (30 - i2));
      const dateString = `${date.getDate()} ${date.toLocaleString("default", { month: "short" })}`;
      const x = i2 / 30 * innerWidth;
      const tick = $.SVG("line");
      tick.setAttribute("x1", `${x}`);
      tick.setAttribute("y1", `${innerHeight}`);
      tick.setAttribute("x2", `${x}`);
      tick.setAttribute("y2", `${innerHeight + 10}`);
      tick.setAttribute("stroke", $Zn($Io));
      tick.setAttribute("stroke-width", "1px");
      g.appendChild(tick);
      const ruler = $.SVG("line");
      ruler.setAttribute("x1", `${x}`);
      ruler.setAttribute("y1", `0`);
      ruler.setAttribute("x2", `${x}`);
      ruler.setAttribute("y2", `${innerHeight}`);
      ruler.setAttribute("stroke", $Zn($Jo));
      ruler.setAttribute("stroke-width", "1px");
      g.appendChild(ruler);
      const xAxisDate = $.SVG("text");
      xAxisDate.setAttribute("x", `${x}`);
      xAxisDate.setAttribute("y", `${height}`);
      xAxisDate.setAttribute("text-anchor", "middle");
      xAxisDate.setAttribute("fill", $Zn($eo));
      xAxisDate.setAttribute("font-size", "10px");
      xAxisDate.textContent = dateString;
      g.appendChild(xAxisDate);
    }
    const line = $.SVG("polyline");
    line.setAttribute("fill", "none");
    line.setAttribute("stroke", $Zn($Ho));
    line.setAttribute("stroke-width", `2px`);
    line.setAttribute("points", points.map((p) => `${p.x},${p.y}`).join(" "));
    g.appendChild(line);
    const highlightCircle = $.SVG("circle");
    highlightCircle.setAttribute("r", `4px`);
    highlightCircle.style.display = "none";
    g.appendChild(highlightCircle);
    const hoverDisposable = disposables.add(new $4c());
    const mouseMoveListener = (event) => {
      const rect = svg2.getBoundingClientRect();
      const mouseX = event.clientX - rect.left - margin.left;
      let closestPoint;
      let minDistance = Infinity;
      points.forEach((point) => {
        const distance = Math.abs(point.x - mouseX);
        if (distance < minDistance) {
          minDistance = distance;
          closestPoint = point;
        }
      });
      if (closestPoint) {
        highlightCircle.setAttribute("cx", `${closestPoint.x}`);
        highlightCircle.setAttribute("cy", `${closestPoint.y}`);
        highlightCircle.style.display = "block";
        tooltip.style.left = `${closestPoint.x + 24}px`;
        tooltip.style.top = `${closestPoint.y + 14}px`;
        hoverDisposable.value = this.j.showHover({
          content: new $bm(`${closestPoint.date}: ${closestPoint.count} requests`),
          target: tooltip,
          appearance: {
            showPointer: true,
            skipFadeInAnimation: true
          }
        });
      } else {
        hoverDisposable.value = void 0;
      }
    };
    svg2.addEventListener("mousemove", mouseMoveListener);
    disposables.add($1c(() => svg2.removeEventListener("mousemove", mouseMoveListener)));
    const mouseLeaveListener = () => {
      highlightCircle.style.display = "none";
      hoverDisposable.value = void 0;
    };
    svg2.addEventListener("mouseleave", mouseLeaveListener);
    disposables.add($1c(() => svg2.removeEventListener("mouseleave", mouseLeaveListener)));
  }
};
RuntimeStatusMarkdownRenderer = __decorate([
  __param(0, $wN),
  __param(1, $O4),
  __param(2, $5$),
  __param(3, $wlb)
], RuntimeStatusMarkdownRenderer);
var runtimeStatusFeature = {
  id: RuntimeStatusMarkdownRenderer.ID,
  label: localize(6416, null),
  access: {
    canToggle: false
  },
  renderer: new $Nk(RuntimeStatusMarkdownRenderer)
};
var $6cc = class $6cc2 extends $ns {
  constructor(s, t, themeService, u) {
    super(themeService);
    this.s = s;
    this.t = t;
    this.u = u;
    this.c = this.B(new $4c());
    this.m = [];
    this.r = new $5z($GA(s.publisher, s.name));
    this.domNode = $("div.subcontent.feature-contributions");
    this.C();
  }
  layout(height, width2) {
    this.m.forEach((participant) => participant.layout(height, width2));
  }
  C() {
    const features = this.H();
    if (features.length === 0) {
      $bk($(".no-features"), this.domNode).textContent = localize(6417, null);
      return;
    }
    const splitView = this.B(new $r2(this.domNode, {
      orientation: 1,
      proportionalLayout: true
    }));
    this.m.push({
      layout: (height, width2) => {
        splitView.el.style.height = `${height - 14}px`;
        splitView.layout(width2);
      }
    });
    const featuresListContainer = $(".features-list-container");
    const list2 = this.B(this.D(featuresListContainer));
    list2.splice(0, list2.length, features);
    const featureViewContainer = $(".feature-view-container");
    this.B(list2.onDidChangeSelection((e) => {
      const feature = e.elements[0];
      if (feature) {
        this.G(feature, featureViewContainer);
      }
    }));
    const index = this.t ? features.findIndex((f) => f.id === this.t) : 0;
    list2.setSelection([index === -1 ? 0 : index]);
    splitView.addView({
      onDidChange: Event2.None,
      element: featuresListContainer,
      minimumSize: 100,
      maximumSize: Number.POSITIVE_INFINITY,
      layout: (width2, _, height) => {
        featuresListContainer.style.width = `${width2}px`;
        list2.layout(height, width2);
      }
    }, 200, void 0, true);
    splitView.addView({
      onDidChange: Event2.None,
      element: featureViewContainer,
      minimumSize: 500,
      maximumSize: Number.POSITIVE_INFINITY,
      layout: (width2, _, height) => {
        featureViewContainer.style.width = `${width2}px`;
        this.j = { height, width: width2 };
        this.F();
      }
    }, Sizing.Distribute, void 0, true);
    splitView.style({
      separatorBorder: this.h.getColor($Umb)
    });
  }
  D(container2) {
    const renderer = this.u.createInstance(ExtensionFeatureItemRenderer, this.r);
    const delegate = new ExtensionFeatureItemDelegate();
    const list2 = this.u.createInstance($Web, "ExtensionFeaturesList", $bk(container2, $(".features-list-wrapper")), delegate, [renderer], {
      multipleSelectionSupport: false,
      setRowLineHeight: false,
      horizontalScrolling: false,
      accessibilityProvider: {
        getAriaLabel(extensionFeature2) {
          return extensionFeature2?.label ?? "";
        },
        getWidgetAriaLabel() {
          return localize(6418, null);
        }
      },
      openOnSingleClick: true
    });
    return list2;
  }
  F() {
    this.c.value?.layout(this.j?.height, this.j?.width);
  }
  G(feature, container2) {
    if (this.c.value?.feature.id === feature.id) {
      return;
    }
    $$i(container2);
    this.c.value = this.u.createInstance(ExtensionFeatureView, this.r, this.s, feature);
    container2.appendChild(this.c.value.domNode);
    this.F();
  }
  H() {
    const features = $Wn.as(Extensions3.ExtensionFeaturesRegistry).getExtensionFeatures().filter((feature) => {
      const renderer2 = this.I(feature);
      const shouldRender = renderer2?.shouldRender(this.s);
      renderer2?.dispose();
      return shouldRender;
    }).sort((a, b) => a.label.localeCompare(b.label));
    const renderer = this.I(runtimeStatusFeature);
    if (renderer?.shouldRender(this.s)) {
      features.splice(0, 0, runtimeStatusFeature);
    }
    renderer?.dispose();
    return features;
  }
  I(feature) {
    return feature.renderer ? this.u.createInstance(feature.renderer) : void 0;
  }
};
$6cc = __decorate([
  __param(2, $gs),
  __param(3, $Pk)
], $6cc);
var ExtensionFeatureItemDelegate = class {
  getHeight() {
    return 22;
  }
  getTemplateId() {
    return "extensionFeatureDescriptor";
  }
};
var ExtensionFeatureItemRenderer = class ExtensionFeatureItemRenderer2 {
  constructor(c, d) {
    this.c = c;
    this.d = d;
    this.templateId = "extensionFeatureDescriptor";
  }
  renderTemplate(container2) {
    container2.classList.add("extension-feature-list-item");
    const label3 = $bk(container2, $(".extension-feature-label"));
    const disabledElement = $bk(container2, $(".extension-feature-disabled-label"));
    disabledElement.textContent = localize(6419, null);
    const statusElement = $bk(container2, $(".extension-feature-status"));
    return { label: label3, disabledElement, statusElement, disposables: new $2c() };
  }
  renderElement(element, index, templateData) {
    templateData.disposables.clear();
    templateData.label.textContent = element.label;
    templateData.disabledElement.style.display = element.id === runtimeStatusFeature.id || this.d.isEnabled(this.c, element.id) ? "none" : "inherit";
    templateData.disposables.add(this.d.onDidChangeEnablement(({ extension, featureId, enabled }) => {
      if ($5z.equals(extension, this.c) && featureId === element.id) {
        templateData.disabledElement.style.display = enabled ? "none" : "inherit";
      }
    }));
    const statusElementClassName = templateData.statusElement.className;
    const updateStatus = () => {
      const accessData = this.d.getAccessData(this.c, element.id);
      if (accessData?.current?.status) {
        templateData.statusElement.style.display = "inherit";
        templateData.statusElement.className = `${statusElementClassName} ${SeverityIcon.className(accessData.current.status.severity)}`;
      } else {
        templateData.statusElement.style.display = "none";
      }
    };
    updateStatus();
    templateData.disposables.add(this.d.onDidChangeAccessData(({ extension, featureId }) => {
      if ($5z.equals(extension, this.c) && featureId === element.id) {
        updateStatus();
      }
    }));
  }
  disposeElement(element, index, templateData, height) {
    templateData.disposables.dispose();
  }
  disposeTemplate(templateData) {
    templateData.disposables.dispose();
  }
};
ExtensionFeatureItemRenderer = __decorate([
  __param(1, $wlb)
], ExtensionFeatureItemRenderer);
var ExtensionFeatureView = class ExtensionFeatureView2 extends $3c {
  constructor(h3, j, feature, m, n, r2, s) {
    super();
    this.h = h3;
    this.j = j;
    this.feature = feature;
    this.m = m;
    this.n = n;
    this.r = r2;
    this.s = s;
    this.c = [];
    this.domNode = $(".extension-feature-content");
    this.t(this.domNode);
  }
  t(content) {
    const header = $bk(content, $(".feature-header"));
    const title = $bk(header, $(".feature-title"));
    title.textContent = this.feature.label;
    if (this.feature.access.canToggle) {
      const actionsContainer = $bk(header, $(".feature-actions"));
      const button = new $k2(actionsContainer, $q$);
      this.u(button);
      this.B(this.r.onDidChangeEnablement(({ extension, featureId }) => {
        if ($5z.equals(extension, this.h) && featureId === this.feature.id) {
          this.u(button);
        }
      }));
      this.B(button.onDidClick(async () => {
        const enabled = this.r.isEnabled(this.h, this.feature.id);
        const confirmationResult = await this.s.confirm({
          title: localize(6420, null, this.feature.label),
          message: enabled ? localize(6421, null, this.j.displayName ?? this.h.value, this.feature.label) : localize(6422, null, this.j.displayName ?? this.h.value, this.feature.label),
          custom: true,
          primaryButton: enabled ? localize(6423, null) : localize(6424, null),
          cancelButton: localize(6425, null)
        });
        if (confirmationResult.confirmed) {
          this.r.setEnablement(this.h, this.feature.id, !enabled);
        }
      }));
    }
    const body = $bk(content, $(".feature-body"));
    const bodyContent = $(".feature-body-content");
    const scrollableContent = this.B(new $CZ(bodyContent, {}));
    $bk(body, scrollableContent.getDomNode());
    this.c.push({ layout: () => scrollableContent.scanDomNode() });
    scrollableContent.scanDomNode();
    if (this.feature.description) {
      const description = $bk(bodyContent, $(".feature-description"));
      description.textContent = this.feature.description;
    }
    const accessData = this.r.getAccessData(this.h, this.feature.id);
    if (accessData?.current?.status) {
      $bk(bodyContent, $(".feature-status", void 0, $(`span${ThemeIcon.asCSSSelector(accessData.current.status.severity === severity_default.Error ? $vCb : accessData.current.status.severity === severity_default.Warning ? $wCb : $xCb)}`, void 0), $("span", void 0, accessData.current.status.message)));
    }
    const featureContentElement = $bk(bodyContent, $(".feature-content"));
    if (this.feature.renderer) {
      const renderer = this.n.createInstance(this.feature.renderer);
      if (renderer.type === "table") {
        this.w(featureContentElement, renderer);
      } else if (renderer.type === "markdown") {
        this.D(featureContentElement, renderer);
      } else if (renderer.type === "markdown+table") {
        this.C(featureContentElement, renderer);
      } else if (renderer.type === "element") {
        this.H(featureContentElement, renderer);
      }
    }
  }
  u(button) {
    button.label = this.r.isEnabled(this.h, this.feature.id) ? localize(6426, null) : localize(6427, null);
  }
  w(container2, renderer) {
    const tableData = this.B(renderer.render(this.j));
    const tableDisposable = this.B(new $4c());
    if (tableData.onDidChange) {
      this.B(tableData.onDidChange((data) => {
        $$i(container2);
        tableDisposable.value = this.z(data, container2);
      }));
    }
    tableDisposable.value = this.z(tableData.data, container2);
  }
  z(tableData, container2) {
    const disposables = new $2c();
    $bk(container2, $("table", void 0, $("tr", void 0, ...tableData.headers.map((header) => $("th", void 0, header))), ...tableData.rows.map((row) => {
      return $("tr", void 0, ...row.map((rowData) => {
        if (typeof rowData === "string") {
          return $("td", void 0, $("p", void 0, rowData));
        }
        const data = Array.isArray(rowData) ? rowData : [rowData];
        return $("td", void 0, ...data.map((item) => {
          const result = [];
          if ($dm(rowData)) {
            const element = $("", void 0);
            this.F(rowData, element);
            result.push(element);
          } else if (item instanceof $ff) {
            const element = $("");
            const kbl = disposables.add(new $32(element, OS, $o$));
            kbl.set(item);
            result.push(element);
          } else if (item instanceof $Vn) {
            result.push($("span", { class: "colorBox", style: "background-color: " + $Vn.Format.CSS.format(item) }, ""));
            result.push($("code", void 0, $Vn.Format.CSS.formatHex(item)));
          }
          return result;
        }).flat());
      }));
    })));
    return disposables;
  }
  C(container2, renderer) {
    const markdownAndTableData = this.B(renderer.render(this.j));
    if (markdownAndTableData.onDidChange) {
      this.B(markdownAndTableData.onDidChange((data) => {
        $$i(container2);
        this.G(data, container2);
      }));
    }
    this.G(markdownAndTableData.data, container2);
  }
  D(container2, renderer) {
    container2.classList.add("markdown");
    const markdownData = this.B(renderer.render(this.j));
    if (markdownData.onDidChange) {
      this.B(markdownData.onDidChange((data) => {
        $$i(container2);
        this.F(data, container2);
      }));
    }
    this.F(markdownData.data, container2);
  }
  F(markdown, container2) {
    const { element, dispose } = $D1({
      value: markdown.value,
      isTrusted: markdown.isTrusted,
      supportThemeIcons: true
    }, {
      actionHandler: {
        callback: (content) => this.m.open(content, { allowCommands: !!markdown.isTrusted }).catch($gb),
        disposables: this.q
      }
    });
    this.B($1c(dispose));
    $bk(container2, element);
  }
  G(data, container2) {
    for (const markdownOrTable of data) {
      if ($dm(markdownOrTable)) {
        const element = $("", void 0);
        this.F(markdownOrTable, element);
        $bk(container2, element);
      } else {
        const tableElement = $bk(container2, $("table"));
        this.z(markdownOrTable, tableElement);
      }
    }
  }
  H(container2, renderer) {
    const elementData = renderer.render(this.j);
    if (elementData.onDidChange) {
      this.B(elementData.onDidChange((data) => {
        $$i(container2);
        container2.appendChild(data);
      }));
    }
    container2.appendChild(elementData.data);
  }
  layout(height, width2) {
    this.c.forEach((p) => p.layout(height, width2));
  }
};
ExtensionFeatureView = __decorate([
  __param(3, $O4),
  __param(4, $Pk),
  __param(5, $wlb),
  __param(6, $Yv)
], ExtensionFeatureView);

// out-build/vs/workbench/contrib/extensions/browser/extensionsWidgets.js
var $gdc_1;
var $7cc = class extends $3c {
  constructor() {
    super(...arguments);
    this.b = null;
  }
  get extension() {
    return this.b;
  }
  set extension(extension) {
    this.b = extension;
    this.update();
  }
  update() {
    this.render();
  }
};
function $8cc(element, callback) {
  const disposables = new $2c();
  disposables.add($_i(element, $7j.CLICK, $kk(callback)));
  disposables.add($_i(element, $7j.KEY_UP, (e) => {
    const keyboardEvent = new $if(e);
    if (keyboardEvent.equals(
      10
      /* KeyCode.Space */
    ) || keyboardEvent.equals(
      3
      /* KeyCode.Enter */
    )) {
      e.preventDefault();
      e.stopPropagation();
      callback();
    }
  }));
  return disposables;
}
var $9cc = class _$9cc extends $7cc {
  constructor(a, c) {
    super();
    this.a = a;
    this.c = c;
    a.classList.add("extension-install-count");
    this.render();
  }
  render() {
    this.a.innerText = "";
    if (!this.extension) {
      return;
    }
    if (this.c && this.extension.state !== 3) {
      return;
    }
    const installLabel = _$9cc.getInstallLabel(this.extension, this.c);
    if (!installLabel) {
      return;
    }
    $bk(this.a, $("span" + ThemeIcon.asCSSSelector($nCb)));
    const count = $bk(this.a, $("span.count"));
    count.textContent = installLabel;
  }
  static getInstallLabel(extension, small) {
    const installCount = extension.installCount;
    if (installCount === void 0) {
      return void 0;
    }
    let installLabel;
    if (small) {
      if (installCount > 1e6) {
        installLabel = `${Math.floor(installCount / 1e5) / 10}M`;
      } else if (installCount > 1e3) {
        installLabel = `${Math.floor(installCount / 1e3)}K`;
      } else {
        installLabel = String(installCount);
      }
    } else {
      installLabel = installCount.toLocaleString($z);
    }
    return installLabel;
  }
};
var $0cc = class $0cc2 extends $7cc {
  constructor(c, f, hoverService) {
    super();
    this.c = c;
    this.f = f;
    c.classList.add("extension-ratings");
    if (this.f) {
      c.classList.add("small");
    }
    this.a = this.B(hoverService.setupManagedHover($JZ("mouse"), c, ""));
    this.render();
  }
  render() {
    this.c.innerText = "";
    if (!this.extension) {
      return;
    }
    if (this.f && this.extension.state !== 3) {
      return;
    }
    if (this.extension.rating === void 0) {
      return;
    }
    if (this.f && !this.extension.ratingCount) {
      return;
    }
    const rating = Math.round(this.extension.rating * 2) / 2;
    this.a.update(localize(6871, null, rating));
    if (this.f) {
      $bk(this.c, $("span" + ThemeIcon.asCSSSelector($sCb)));
      const count = $bk(this.c, $("span.count"));
      count.textContent = String(rating);
    } else {
      for (let i2 = 1; i2 <= 5; i2++) {
        if (rating >= i2) {
          $bk(this.c, $("span" + ThemeIcon.asCSSSelector($sCb)));
        } else if (rating >= i2 - 0.5) {
          $bk(this.c, $("span" + ThemeIcon.asCSSSelector($tCb)));
        } else {
          $bk(this.c, $("span" + ThemeIcon.asCSSSelector($uCb)));
        }
      }
      if (this.extension.ratingCount) {
        const ratingCountElemet = $bk(this.c, $("span", void 0, ` (${this.extension.ratingCount})`));
        ratingCountElemet.style.paddingLeft = "1px";
      }
    }
  }
};
$0cc = __decorate([
  __param(2, $5$)
], $0cc);
var $$cc = class $$cc2 extends $7cc {
  constructor(f, g, hoverService, h3) {
    super();
    this.f = f;
    this.g = g;
    this.h = h3;
    this.a = this.B(new $2c());
    this.c = this.B(hoverService.setupManagedHover($JZ("mouse"), f, ""));
    this.render();
  }
  render() {
    $dk(this.f);
    this.a.clear();
    if (!this.extension?.publisherDomain?.verified) {
      return;
    }
    if (this.extension.resourceExtension) {
      return;
    }
    if (this.extension.local?.source === "resource") {
      return;
    }
    const publisherDomainLink = URI.parse(this.extension.publisherDomain.link);
    const verifiedPublisher = $bk(this.f, $("span.extension-verified-publisher.clickable"));
    $bk(verifiedPublisher, $C1($pCb));
    if (!this.g) {
      verifiedPublisher.tabIndex = 0;
      this.c.update(`Verified Domain: ${this.extension.publisherDomain.link}`);
      verifiedPublisher.setAttribute("role", "link");
      $bk(verifiedPublisher, $("span.extension-verified-publisher-domain", void 0, publisherDomainLink.authority.startsWith("www.") ? publisherDomainLink.authority.substring(4) : publisherDomainLink.authority));
      this.a.add($8cc(verifiedPublisher, () => this.h.open(publisherDomainLink)));
    }
  }
};
$$cc = __decorate([
  __param(2, $5$),
  __param(3, $O4)
], $$cc);
var $_cc = class $_cc2 extends $7cc {
  constructor(c, f, g, h3) {
    super();
    this.c = c;
    this.f = f;
    this.g = g;
    this.h = h3;
    this.a = this.B(new $2c());
    this.render();
  }
  render() {
    $dk(this.c);
    this.a.clear();
    if (!this.extension?.publisherSponsorLink) {
      return;
    }
    const sponsor = $bk(this.c, $("span.sponsor.clickable", { tabIndex: 0 }));
    this.a.add(this.f.setupManagedHover($JZ("mouse"), sponsor, this.extension?.publisherSponsorLink.toString() ?? ""));
    sponsor.setAttribute("role", "link");
    const sponsorIconElement = $C1($rCb);
    const label3 = $("span", void 0, localize(6872, null));
    $bk(sponsor, sponsorIconElement, label3);
    this.a.add($8cc(sponsor, () => {
      this.h.publicLog2("extensionsAction.sponsorExtension", { extensionId: this.extension.identifier.id });
      this.g.open(this.extension.publisherSponsorLink);
    }));
  }
};
$_cc = __decorate([
  __param(1, $5$),
  __param(2, $O4),
  __param(3, $zv)
], $_cc);
var $adc = class $adc2 extends $7cc {
  constructor(f, g) {
    super();
    this.f = f;
    this.g = g;
    this.c = this.B(new $2c());
    this.render();
    this.B($1c(() => this.h()));
    this.B(this.g.onDidChangeRecommendations(() => this.render()));
  }
  h() {
    this.a?.remove();
    this.a = void 0;
    this.c.clear();
  }
  render() {
    this.h();
    if (!this.extension || this.extension.state === 1 || this.extension.deprecationInfo) {
      return;
    }
    const extRecommendations = this.g.getAllRecommendationsWithReason();
    if (extRecommendations[this.extension.identifier.id.toLowerCase()]) {
      this.a = $bk(this.f, $("div.extension-bookmark"));
      const recommendation = $bk(this.a, $(".recommendation"));
      $bk(recommendation, $("span" + ThemeIcon.asCSSSelector($oCb)));
    }
  }
};
$adc = __decorate([
  __param(1, $ABb)
], $adc);
var $bdc = class extends $7cc {
  constructor(f) {
    super();
    this.f = f;
    this.c = this.B(new $2c());
    this.render();
    this.B($1c(() => this.g()));
  }
  g() {
    this.a?.remove();
    this.a = void 0;
    this.c.clear();
  }
  render() {
    this.g();
    if (this.extension?.state === 1 ? this.extension.preRelease : this.extension?.hasPreReleaseVersion) {
      this.a = $bk(this.f, $("div.extension-bookmark"));
      const preRelease = $bk(this.a, $(".pre-release"));
      $bk(preRelease, $("span" + ThemeIcon.asCSSSelector($qCb)));
    }
  }
};
var $cdc = class $cdc2 extends $7cc {
  constructor(parent, f, g, h3) {
    super();
    this.f = f;
    this.g = g;
    this.h = h3;
    this.a = this.B(new $4c());
    this.c = $bk(parent, $(".extension-remote-badge-container"));
    this.render();
    this.B($1c(() => this.j()));
  }
  j() {
    this.a.value?.element.remove();
    this.a.clear();
  }
  render() {
    this.j();
    if (!this.extension || !this.extension.local || !this.extension.server || !(this.g.localExtensionManagementServer && this.g.remoteExtensionManagementServer) || this.extension.server !== this.g.remoteExtensionManagementServer) {
      return;
    }
    this.a.value = this.h.createInstance(RemoteBadge, this.f);
    $bk(this.c, this.a.value.element);
  }
};
$cdc = __decorate([
  __param(2, $nzb),
  __param(3, $Pk)
], $cdc);
var RemoteBadge = class RemoteBadge2 extends $3c {
  constructor(a, hoverService, b, c, f) {
    super();
    this.a = a;
    this.b = b;
    this.c = c;
    this.f = f;
    this.element = $("div.extension-badge.extension-remote-badge");
    this.elementHover = this.B(hoverService.setupManagedHover($JZ("mouse"), this.element, ""));
    this.g();
  }
  g() {
    $bk(this.element, $("span" + ThemeIcon.asCSSSelector($mCb)));
    const applyBadgeStyle = () => {
      if (!this.element) {
        return;
      }
      const bgColor = this.c.getColorTheme().getColor($Nnb);
      const fgColor = this.c.getColorTheme().getColor($Onb);
      this.element.style.backgroundColor = bgColor ? bgColor.toString() : "";
      this.element.style.color = fgColor ? fgColor.toString() : "";
    };
    applyBadgeStyle();
    this.B(this.c.onDidColorThemeChange(() => applyBadgeStyle()));
    if (this.a) {
      const updateTitle = () => {
        if (this.element && this.f.remoteExtensionManagementServer) {
          this.elementHover.update(localize(6873, null, this.f.remoteExtensionManagementServer.label));
        }
      };
      this.B(this.b.onDidChangeFormatters(() => updateTitle()));
      updateTitle();
    }
  }
};
RemoteBadge = __decorate([
  __param(1, $5$),
  __param(2, $ZI),
  __param(3, $gs),
  __param(4, $nzb)
], RemoteBadge);
var $ddc = class extends $7cc {
  constructor(f) {
    super();
    this.f = f;
    this.render();
    this.B($1c(() => this.g()));
  }
  g() {
    this.a?.remove();
    this.c?.dispose();
    this.c = void 0;
  }
  render() {
    this.g();
    if (!this.extension || !this.extension.categories?.some((category8) => category8.toLowerCase() === "extension packs") || !this.extension.extensionPack.length) {
      return;
    }
    this.a = $bk(this.f, $(".extension-badge.extension-pack-badge"));
    this.c = new $D2(this.a, {}, $E$);
    this.c.setCount(this.extension.extensionPack.length);
  }
};
var $edc = class $edc2 extends $7cc {
  constructor(c, f, g, h3, j) {
    super();
    this.c = c;
    this.f = f;
    this.g = g;
    this.h = h3;
    this.j = j;
    this.a = this.B(new $2c());
    this.B(Event2.filter(this.f.onDidChangeConfiguration, (e) => e.affectsConfiguration("settingsSync.ignoredExtensions"))(() => this.render()));
    this.B(j.onDidChangeEnablement(() => this.update()));
    this.render();
  }
  render() {
    this.a.clear();
    this.c.innerText = "";
    if (this.extension && this.extension.state === 1 && this.j.isEnabled() && this.g.isExtensionIgnoredToSync(this.extension)) {
      const element = $bk(this.c, $("span.extension-sync-ignored" + ThemeIcon.asCSSSelector($lCb)));
      this.a.add(this.h.setupManagedHover($JZ("mouse"), element, localize(6874, null)));
      element.classList.add(...ThemeIcon.asClassNameArray($lCb));
    }
  }
};
$edc = __decorate([
  __param(1, $kl),
  __param(2, $vzb),
  __param(3, $5$),
  __param(4, $6Bb)
], $edc);
var $fdc = class $fdc2 extends $7cc {
  constructor(a, c, extensionService, f, g) {
    super();
    this.a = a;
    this.c = c;
    this.f = f;
    this.g = g;
    this.B(extensionService.onDidChangeExtensionsStatus((extensions) => {
      if (this.extension && extensions.some((e) => $DA({ id: e.value }, this.extension.identifier))) {
        this.update();
      }
    }));
    this.B(f.onDidChangeAccessData((e) => {
      if (this.extension && $5z.equals(this.extension.identifier.id, e.extension)) {
        this.update();
      }
    }));
  }
  render() {
    this.c.innerText = "";
    if (!this.extension) {
      return;
    }
    if (this.a.filters.featureId && this.extension.state === 1) {
      const accessData = this.f.getAllAccessDataForExtension(new $5z(this.extension.identifier.id)).get(this.a.filters.featureId);
      const feature = $Wn.as(Extensions3.ExtensionFeaturesRegistry).getExtensionFeature(this.a.filters.featureId);
      if (feature?.icon && accessData) {
        const featureAccessTimeElement = $bk(this.c, $("span.activationTime"));
        featureAccessTimeElement.textContent = localize(6875, null, accessData.accessTimes.length);
        const iconElement = $bk(this.c, $("span" + ThemeIcon.asCSSSelector(feature.icon)));
        iconElement.style.paddingLeft = "4px";
        return;
      }
    }
    const extensionStatus = this.g.getExtensionRuntimeStatus(this.extension);
    if (extensionStatus?.activationTimes) {
      const activationTime = extensionStatus.activationTimes.codeLoadingTime + extensionStatus.activationTimes.activateCallTime;
      $bk(this.c, $("span" + ThemeIcon.asCSSSelector($zCb)));
      const activationTimeElement = $bk(this.c, $("span.activationTime"));
      activationTimeElement.textContent = `${activationTime}ms`;
    }
  }
};
$fdc = __decorate([
  __param(2, $wN),
  __param(3, $wlb),
  __param(4, $vzb)
], $fdc);
var $gdc = $gdc_1 = class $gdc2 extends $7cc {
  constructor(c, f, g, h3, j, m, n, r2, s) {
    super();
    this.c = c;
    this.f = f;
    this.g = g;
    this.h = h3;
    this.j = j;
    this.m = m;
    this.n = n;
    this.r = r2;
    this.s = s;
    this.a = this.B(new $4c());
  }
  render() {
    this.a.value = void 0;
    if (this.extension) {
      this.a.value = this.j.setupManagedHover({
        delay: this.m.getValue("workbench.hover.delay"),
        showHover: (options3, focus) => {
          return this.j.showHover({
            ...options3,
            additionalClasses: ["extension-hover"],
            position: {
              hoverPosition: this.c.position(),
              forcePosition: true
            },
            persistence: {
              hideOnKeyDown: true
            }
          }, focus);
        },
        placement: "element"
      }, this.c.target, {
        markdown: () => Promise.resolve(this.t()),
        markdownNotSupportedFallback: void 0
      }, {
        appearance: {
          showHoverHint: true
        }
      });
    }
  }
  t() {
    if (!this.extension) {
      return void 0;
    }
    const markdown = new $bm("", { isTrusted: true, supportThemeIcons: true });
    markdown.appendMarkdown(`**${this.extension.displayName}**`);
    if (valid(this.extension.version)) {
      markdown.appendMarkdown(`&nbsp;<span style="background-color:#8080802B;">**&nbsp;_v${this.extension.version}${this.extension.isPreReleaseVersion ? " (pre-release)" : ""}_**&nbsp;</span>`);
    }
    markdown.appendText(`
`);
    if (this.extension.state === 1) {
      let addSeparator = false;
      const installLabel = $9cc.getInstallLabel(this.extension, true);
      if (installLabel) {
        if (addSeparator) {
          markdown.appendText(`  |  `);
        }
        markdown.appendMarkdown(`$(${$nCb.id}) ${installLabel}`);
        addSeparator = true;
      }
      if (this.extension.rating) {
        if (addSeparator) {
          markdown.appendText(`  |  `);
        }
        const rating = Math.round(this.extension.rating * 2) / 2;
        markdown.appendMarkdown(`$(${$sCb.id}) [${rating}](${this.extension.url}&ssr=false#review-details)`);
        addSeparator = true;
      }
      if (this.extension.publisherSponsorLink) {
        if (addSeparator) {
          markdown.appendText(`  |  `);
        }
        markdown.appendMarkdown(`$(${$rCb.id}) [${localize(6876, null)}](${this.extension.publisherSponsorLink})`);
        addSeparator = true;
      }
      if (addSeparator) {
        markdown.appendText(`
`);
      }
    }
    const location3 = this.extension.resourceExtension?.location ?? (this.extension.local?.source === "resource" ? this.extension.local?.location : void 0);
    if (location3) {
      if (this.extension.isWorkspaceScoped && this.s.isInsideWorkspace(location3)) {
        markdown.appendMarkdown(localize(6877, null));
      } else {
        markdown.appendMarkdown(localize(6878, null));
      }
      markdown.appendText(`
`);
    }
    if (this.extension.description) {
      markdown.appendMarkdown(`${this.extension.description}`);
      markdown.appendText(`
`);
    }
    if (this.extension.publisherDomain?.verified) {
      const bgColor = this.r.getColorTheme().getColor($kdc);
      const publisherVerifiedTooltip = localize(6879, null, `[${URI.parse(this.extension.publisherDomain.link).authority}](${this.extension.publisherDomain.link})`);
      markdown.appendMarkdown(`<span style="color:${bgColor ? $Vn.Format.CSS.formatHex(bgColor) : "#ffffff"};">$(${$pCb.id})</span>&nbsp;${publisherVerifiedTooltip}`);
      markdown.appendText(`
`);
    }
    if (this.extension.outdated) {
      markdown.appendMarkdown(localize(6880, null));
      markdown.appendMarkdown(`&nbsp;<span style="background-color:#8080802B;">**&nbsp;_v${this.extension.latestVersion}_**&nbsp;</span>`);
      markdown.appendText(`
`);
    }
    const preReleaseMessage = $gdc_1.getPreReleaseMessage(this.extension);
    const extensionRuntimeStatus = this.g.getExtensionRuntimeStatus(this.extension);
    const extensionFeaturesAccessData = this.h.getAllAccessDataForExtension(new $5z(this.extension.identifier.id));
    const extensionStatus = this.f.status;
    const runtimeState = this.extension.runtimeState;
    const recommendationMessage = this.u(this.extension);
    if (extensionRuntimeStatus || extensionFeaturesAccessData.size || extensionStatus.length || runtimeState || recommendationMessage || preReleaseMessage) {
      markdown.appendMarkdown(`---`);
      markdown.appendText(`
`);
      if (extensionRuntimeStatus) {
        if (extensionRuntimeStatus.activationTimes) {
          const activationTime = extensionRuntimeStatus.activationTimes.codeLoadingTime + extensionRuntimeStatus.activationTimes.activateCallTime;
          markdown.appendMarkdown(`${localize(6881, null)}${extensionRuntimeStatus.activationTimes.activationReason.startup ? ` (${localize(6882, null)})` : ""}: \`${activationTime}ms\``);
          markdown.appendText(`
`);
        }
        if (extensionRuntimeStatus.runtimeErrors.length || extensionRuntimeStatus.messages.length) {
          const hasErrors = extensionRuntimeStatus.runtimeErrors.length || extensionRuntimeStatus.messages.some((message) => message.type === severity_default.Error);
          const hasWarnings = extensionRuntimeStatus.messages.some((message) => message.type === severity_default.Warning);
          const errorsLink = extensionRuntimeStatus.runtimeErrors.length ? `[${extensionRuntimeStatus.runtimeErrors.length === 1 ? localize(6883, null) : localize(6884, null, extensionRuntimeStatus.runtimeErrors.length)}](${URI.parse(`command:extension.open?${encodeURIComponent(JSON.stringify([
            this.extension.identifier.id,
            "features"
            /* ExtensionEditorTab.Features */
          ]))}`)})` : void 0;
          const messageLink = extensionRuntimeStatus.messages.length ? `[${extensionRuntimeStatus.messages.length === 1 ? localize(6885, null) : localize(6886, null, extensionRuntimeStatus.messages.length)}](${URI.parse(`command:extension.open?${encodeURIComponent(JSON.stringify([
            this.extension.identifier.id,
            "features"
            /* ExtensionEditorTab.Features */
          ]))}`)})` : void 0;
          markdown.appendMarkdown(`$(${hasErrors ? $vCb.id : hasWarnings ? $wCb.id : $xCb.id}) This extension has reported `);
          if (errorsLink && messageLink) {
            markdown.appendMarkdown(`${errorsLink} and ${messageLink}`);
          } else {
            markdown.appendMarkdown(`${errorsLink || messageLink}`);
          }
          markdown.appendText(`
`);
        }
      }
      if (extensionFeaturesAccessData.size) {
        const registry4 = $Wn.as(Extensions3.ExtensionFeaturesRegistry);
        for (const [featureId, accessData] of extensionFeaturesAccessData) {
          if (accessData?.accessTimes.length) {
            const feature = registry4.getExtensionFeature(featureId);
            if (feature) {
              markdown.appendMarkdown(localize(6887, null, feature.label));
              markdown.appendMarkdown(`: [${localize(6888, null, accessData.accessTimes.length, feature.accessDataLabel ?? feature.label)}](${URI.parse(`command:extension.open?${encodeURIComponent(JSON.stringify([
                this.extension.identifier.id,
                "features"
                /* ExtensionEditorTab.Features */
              ]))}`)})`);
              markdown.appendText(`
`);
            }
          }
        }
      }
      for (const status of extensionStatus) {
        if (status.icon) {
          markdown.appendMarkdown(`$(${status.icon.id})&nbsp;`);
        }
        markdown.appendMarkdown(status.message.value);
        markdown.appendText(`
`);
      }
      if (runtimeState) {
        markdown.appendMarkdown(`$(${$xCb.id})&nbsp;`);
        markdown.appendMarkdown(`${runtimeState.reason}`);
        markdown.appendText(`
`);
      }
      if (preReleaseMessage) {
        const extensionPreReleaseIcon = this.r.getColorTheme().getColor($ldc);
        markdown.appendMarkdown(`<span style="color:${extensionPreReleaseIcon ? $Vn.Format.CSS.formatHex(extensionPreReleaseIcon) : "#ffffff"};">$(${$qCb.id})</span>&nbsp;${preReleaseMessage}`);
        markdown.appendText(`
`);
      }
      if (recommendationMessage) {
        markdown.appendMarkdown(recommendationMessage);
        markdown.appendText(`
`);
      }
    }
    return markdown;
  }
  u(extension) {
    if (extension.state === 1) {
      return void 0;
    }
    if (extension.deprecationInfo) {
      return void 0;
    }
    const recommendation = this.n.getAllRecommendationsWithReason()[extension.identifier.id.toLowerCase()];
    if (!recommendation?.reasonText) {
      return void 0;
    }
    const bgColor = this.r.getColorTheme().getColor($HDb);
    return `<span style="color:${bgColor ? $Vn.Format.CSS.formatHex(bgColor) : "#ffffff"};">$(${$uCb.id})</span>&nbsp;${recommendation.reasonText}`;
  }
  static getPreReleaseMessage(extension) {
    if (!extension.hasPreReleaseVersion) {
      return void 0;
    }
    if (extension.isBuiltin) {
      return void 0;
    }
    if (extension.isPreReleaseVersion) {
      return void 0;
    }
    if (extension.preRelease) {
      return void 0;
    }
    const preReleaseVersionLink = `[${localize(6889, null)}](${URI.parse(`command:workbench.extensions.action.showPreReleaseVersion?${encodeURIComponent(JSON.stringify([extension.identifier.id]))}`)})`;
    return localize(6890, null, preReleaseVersionLink);
  }
};
$gdc = $gdc_1 = __decorate([
  __param(2, $vzb),
  __param(3, $wlb),
  __param(4, $5$),
  __param(5, $kl),
  __param(6, $ABb),
  __param(7, $gs),
  __param(8, $Zk)
], $gdc);
var $hdc = class $hdc2 extends $7cc {
  constructor(f, g, h3) {
    super();
    this.f = f;
    this.g = g;
    this.h = h3;
    this.a = this.B(new $4c());
    this.c = this.B(new $ze());
    this.onDidRender = this.c.event;
    this.render();
    this.B(g.onDidChangeStatus(() => this.render()));
  }
  render() {
    $dk(this.f);
    this.a.value = void 0;
    const disposables = new $2c();
    this.a.value = disposables;
    const extensionStatus = this.g.status;
    if (extensionStatus.length) {
      const markdown = new $bm("", { isTrusted: true, supportThemeIcons: true });
      for (let i2 = 0; i2 < extensionStatus.length; i2++) {
        const status = extensionStatus[i2];
        if (status.icon) {
          markdown.appendMarkdown(`$(${status.icon.id})&nbsp;`);
        }
        markdown.appendMarkdown(status.message.value);
        if (i2 < extensionStatus.length - 1) {
          markdown.appendText(`
`);
        }
      }
      const rendered = disposables.add($D1(markdown, {
        actionHandler: {
          callback: (content) => {
            this.h.open(content, { allowCommands: true }).catch($gb);
          },
          disposables
        }
      }));
      $bk(this.f, rendered.element);
    }
    this.c.fire();
  }
};
$hdc = __decorate([
  __param(2, $O4)
], $hdc);
var $idc = class $idc2 extends $7cc {
  constructor(c, f, g) {
    super();
    this.c = c;
    this.f = f;
    this.g = g;
    this.a = this.B(new $ze());
    this.onDidRender = this.a.event;
    this.render();
    this.B(this.f.onDidChangeRecommendations(() => this.render()));
  }
  render() {
    $dk(this.c);
    const recommendationStatus = this.h();
    if (recommendationStatus) {
      if (recommendationStatus.icon) {
        $bk(this.c, $(`div${ThemeIcon.asCSSSelector(recommendationStatus.icon)}`));
      }
      $bk(this.c, $(`div.recommendation-text`, void 0, recommendationStatus.message));
    }
    this.a.fire();
  }
  h() {
    if (!this.extension || this.extension.deprecationInfo || this.extension.state === 1) {
      return void 0;
    }
    const extRecommendations = this.f.getAllRecommendationsWithReason();
    if (extRecommendations[this.extension.identifier.id.toLowerCase()]) {
      const reasonText = extRecommendations[this.extension.identifier.id.toLowerCase()].reasonText;
      if (reasonText) {
        return { icon: $uCb, message: reasonText };
      }
    } else if (this.g.globalIgnoredRecommendations.indexOf(this.extension.identifier.id.toLowerCase()) !== -1) {
      return { icon: void 0, message: localize(6891, null) };
    }
    return void 0;
  }
};
$idc = __decorate([
  __param(1, $ABb),
  __param(2, $BBb)
], $idc);
var $jdc = $5n("extensionIcon.starForeground", { light: "#DF6100", dark: "#FF8E00", hcDark: "#FF8E00", hcLight: $no }, localize(6892, null), false);
var $kdc = $5n("extensionIcon.verifiedForeground", $no, localize(6893, null), false);
var $ldc = $5n("extensionIcon.preReleaseForeground", { dark: "#1d9271", light: "#1d9271", hcDark: "#1d9271", hcLight: $no }, localize(6894, null), false);
var $mdc = $5n("extensionIcon.sponsorForeground", { light: "#B51E78", dark: "#D758B3", hcDark: null, hcLight: "#B51E78" }, localize(6895, null), false);
$ms((theme, collector) => {
  const extensionRatingIcon = theme.getColor($jdc);
  if (extensionRatingIcon) {
    collector.addRule(`.extension-ratings .codicon-extensions-star-full, .extension-ratings .codicon-extensions-star-half { color: ${extensionRatingIcon}; }`);
    collector.addRule(`.monaco-hover.extension-hover .markdown-hover .hover-contents ${ThemeIcon.asCSSSelector($sCb)} { color: ${extensionRatingIcon}; }`);
  }
  const extensionVerifiedPublisherIcon = theme.getColor($kdc);
  if (extensionVerifiedPublisherIcon) {
    collector.addRule(`${ThemeIcon.asCSSSelector($pCb)} { color: ${extensionVerifiedPublisherIcon}; }`);
  }
  collector.addRule(`.monaco-hover.extension-hover .markdown-hover .hover-contents ${ThemeIcon.asCSSSelector($rCb)} { color: var(--vscode-extensionIcon-sponsorForeground); }`);
  collector.addRule(`.extension-editor > .header > .details > .subtitle .sponsor ${ThemeIcon.asCSSSelector($rCb)} { color: var(--vscode-extensionIcon-sponsorForeground); }`);
});

// out-build/vs/workbench/contrib/extensions/browser/extensionsList.js
var EXTENSION_LIST_ELEMENT_HEIGHT = 72;
var $ndc = class {
  getHeight() {
    return EXTENSION_LIST_ELEMENT_HEIGHT;
  }
  getTemplateId() {
    return "extension";
  }
};
var $odc = class $odc2 {
  constructor(a, b, c, d, f, g, h3, i2) {
    this.a = a;
    this.b = b;
    this.c = c;
    this.d = d;
    this.f = f;
    this.g = g;
    this.h = h3;
    this.i = i2;
  }
  get templateId() {
    return "extension";
  }
  renderTemplate(root) {
    const recommendationWidget = this.c.createInstance($adc, $bk(root, $(".extension-bookmark-container")));
    const preReleaseWidget = this.c.createInstance($bdc, $bk(root, $(".extension-bookmark-container")));
    const element = $bk(root, $(".extension-list-item"));
    const iconContainer = $bk(element, $(".icon-container"));
    const icon2 = $bk(iconContainer, $("img.icon", { alt: "" }));
    const iconRemoteBadgeWidget = this.c.createInstance($cdc, iconContainer, false);
    const extensionPackBadgeWidget = this.c.createInstance($ddc, iconContainer);
    const details = $bk(element, $(".details"));
    const headerContainer = $bk(details, $(".header-container"));
    const header = $bk(headerContainer, $(".header"));
    const name = $bk(header, $("span.name"));
    const installCount = $bk(header, $("span.install-count"));
    const ratings = $bk(header, $("span.ratings"));
    const syncIgnore = $bk(header, $("span.sync-ignored"));
    const activationStatus = $bk(header, $("span.activation-status"));
    const headerRemoteBadgeWidget = this.c.createInstance($cdc, header, false);
    const description = $bk(details, $(".description.ellipsis"));
    const footer = $bk(details, $(".footer"));
    const publisher = $bk(footer, $(".author.ellipsis"));
    const verifiedPublisherWidget = this.c.createInstance($$cc, $bk(publisher, $(`.verified-publisher`)), true);
    const publisherDisplayName = $bk(publisher, $(".publisher-name.ellipsis"));
    const actionbar = new $LZ(footer, {
      actionViewItemProvider: (action, options3) => {
        if (action instanceof $VCb) {
          return new $WCb(action, {
            ...options3,
            icon: true,
            label: true,
            menuActionsOrProvider: { getActions: () => action.menuActions },
            menuActionClassNames: action.menuActionClassNames
          }, this.i);
        }
        if (action instanceof $0Cb) {
          return action.createActionViewItem(options3);
        }
        return void 0;
      },
      focusOnlyEnabledItems: true
    });
    actionbar.setFocusable(false);
    actionbar.onDidRun(({ error }) => error && this.d.error(error));
    const extensionStatusIconAction = this.c.createInstance($ADb);
    const actions = [
      this.c.createInstance($yDb),
      this.c.createInstance($9Cb, true),
      this.c.createInstance($lDb),
      this.c.createInstance($6Cb, false),
      this.c.createInstance($YCb),
      this.c.createInstance($ZCb),
      this.c.createInstance($pDb),
      this.c.createInstance($qDb),
      this.c.createInstance($2Cb, false),
      this.c.createInstance($3Cb),
      this.c.createInstance($4Cb),
      extensionStatusIconAction,
      this.c.createInstance($aDb)
    ];
    const extensionHoverWidget = this.c.createInstance($gdc, { target: root, position: this.b.hoverOptions.position }, extensionStatusIconAction);
    const widgets2 = [
      recommendationWidget,
      preReleaseWidget,
      iconRemoteBadgeWidget,
      extensionPackBadgeWidget,
      headerRemoteBadgeWidget,
      verifiedPublisherWidget,
      extensionHoverWidget,
      this.c.createInstance($edc, syncIgnore),
      this.c.createInstance($fdc, this.a, activationStatus),
      this.c.createInstance($9cc, installCount, true),
      this.c.createInstance($0cc, ratings, true)
    ];
    const extensionContainers = this.c.createInstance($Bzb, [...actions, ...widgets2]);
    actionbar.push(actions, { icon: true, label: true });
    const disposable = $Zc(...actions, ...widgets2, actionbar, extensionContainers);
    return {
      root,
      element,
      icon: icon2,
      name,
      installCount,
      ratings,
      description,
      publisherDisplayName,
      disposables: [disposable],
      actionbar,
      extensionDisposables: [],
      set extension(extension) {
        extensionContainers.extension = extension;
      }
    };
  }
  renderPlaceholder(index, data) {
    data.element.classList.add("loading");
    data.root.removeAttribute("aria-label");
    data.root.removeAttribute("data-extension-id");
    data.extensionDisposables = $Xc(data.extensionDisposables);
    data.icon.src = "";
    data.name.textContent = "";
    data.description.textContent = "";
    data.publisherDisplayName.textContent = "";
    data.installCount.style.display = "none";
    data.ratings.style.display = "none";
    data.extension = null;
  }
  renderElement(extension, index, data) {
    data.element.classList.remove("loading");
    data.root.setAttribute("data-extension-id", extension.identifier.id);
    if (extension.state !== 3 && !extension.server) {
      extension = this.g.local.filter((e) => e.server === extension.server && $DA(e.identifier, extension.identifier))[0] || extension;
    }
    data.extensionDisposables = $Xc(data.extensionDisposables);
    const updateEnablement = () => {
      const disabled = extension.state === 1 && extension.local && !this.h.isEnabled(extension.local);
      const deprecated = !!extension.deprecationInfo;
      data.element.classList.toggle("deprecated", deprecated);
      data.root.classList.toggle("disabled", disabled);
    };
    updateEnablement();
    this.f.onDidChangeExtensions(() => updateEnablement(), this, data.extensionDisposables);
    data.extensionDisposables.push($_i(data.icon, "error", () => data.icon.src = extension.iconUrlFallback, { once: true }));
    data.icon.src = extension.iconUrl;
    if (!data.icon.complete) {
      data.icon.style.visibility = "hidden";
      data.icon.onload = () => data.icon.style.visibility = "inherit";
    } else {
      data.icon.style.visibility = "inherit";
    }
    data.name.textContent = extension.displayName;
    data.description.textContent = extension.description;
    const updatePublisher = () => {
      data.publisherDisplayName.textContent = !extension.resourceExtension && extension.local?.source !== "resource" ? extension.publisherDisplayName : "";
    };
    updatePublisher();
    Event2.filter(this.g.onChange, (e) => !!e && $DA(e.identifier, extension.identifier))(() => updatePublisher(), this, data.extensionDisposables);
    data.installCount.style.display = "";
    data.ratings.style.display = "";
    data.extension = extension;
    if (extension.gallery && extension.gallery.properties && extension.gallery.properties.localizedLanguages && extension.gallery.properties.localizedLanguages.length) {
      data.description.textContent = extension.gallery.properties.localizedLanguages.map((name) => name[0].toLocaleUpperCase() + name.slice(1)).join(", ");
    }
    this.a.onFocus((e) => {
      if ($DA(extension.identifier, e.identifier)) {
        data.actionbar.setFocusable(true);
      }
    }, this, data.extensionDisposables);
    this.a.onBlur((e) => {
      if ($DA(extension.identifier, e.identifier)) {
        data.actionbar.setFocusable(false);
      }
    }, this, data.extensionDisposables);
  }
  disposeElement(extension, index, data) {
    data.extensionDisposables = $Xc(data.extensionDisposables);
  }
  disposeTemplate(data) {
    data.extensionDisposables = $Xc(data.extensionDisposables);
    data.disposables = $Xc(data.disposables);
  }
};
$odc = __decorate([
  __param(2, $Pk),
  __param(3, $PJ),
  __param(4, $wN),
  __param(5, $vzb),
  __param(6, $qzb),
  __param(7, $50)
], $odc);
$ms((theme, collector) => {
  const verifiedPublisherIconColor = theme.getColor($kdc);
  if (verifiedPublisherIconColor) {
    const disabledVerifiedPublisherIconColor = verifiedPublisherIconColor.transparent(0.5).makeOpaque($4lb(theme));
    collector.addRule(`.extensions-list .monaco-list .monaco-list-row.disabled:not(.selected) .author .verified-publisher ${ThemeIcon.asCSSSelector($pCb)} { color: ${disabledVerifiedPublisherIconColor}; }`);
  }
});

// out-build/vs/base/common/paging.js
function createPage(elements) {
  return {
    isResolved: !!elements,
    promise: null,
    cts: null,
    promiseIndexes: /* @__PURE__ */ new Set(),
    elements: elements || []
  };
}
function $Uz(elements) {
  return {
    firstPage: elements,
    total: elements.length,
    pageSize: elements.length,
    getPage: (pageIndex, cancellationToken) => {
      return Promise.resolve(elements);
    }
  };
}
var $Vz = class {
  get length() {
    return this.a.total;
  }
  constructor(arg) {
    this.b = [];
    this.a = Array.isArray(arg) ? $Uz(arg) : arg;
    const totalPages = Math.ceil(this.a.total / this.a.pageSize);
    this.b = [
      createPage(this.a.firstPage.slice()),
      ...$Ub(totalPages - 1).map(() => createPage())
    ];
  }
  isResolved(index) {
    const pageIndex = Math.floor(index / this.a.pageSize);
    const page = this.b[pageIndex];
    return !!page.isResolved;
  }
  get(index) {
    const pageIndex = Math.floor(index / this.a.pageSize);
    const indexInPage = index % this.a.pageSize;
    const page = this.b[pageIndex];
    return page.elements[indexInPage];
  }
  resolve(index, cancellationToken) {
    if (cancellationToken.isCancellationRequested) {
      return Promise.reject(new $lb());
    }
    const pageIndex = Math.floor(index / this.a.pageSize);
    const indexInPage = index % this.a.pageSize;
    const page = this.b[pageIndex];
    if (page.isResolved) {
      return Promise.resolve(page.elements[indexInPage]);
    }
    if (!page.promise) {
      page.cts = new $ad();
      page.promise = this.a.getPage(pageIndex, page.cts.token).then((elements) => {
        page.elements = elements;
        page.isResolved = true;
        page.promise = null;
        page.cts = null;
      }, (err) => {
        page.isResolved = false;
        page.promise = null;
        page.cts = null;
        return Promise.reject(err);
      });
    }
    const listener = cancellationToken.onCancellationRequested(() => {
      if (!page.cts) {
        return;
      }
      page.promiseIndexes.delete(index);
      if (page.promiseIndexes.size === 0) {
        page.cts.cancel();
      }
    });
    page.promiseIndexes.add(index);
    return page.promise.then(() => page.elements[indexInPage]).finally(() => listener.dispose());
  }
};
var $Wz = class {
  get length() {
    return this.a.length;
  }
  constructor(a, b = 500) {
    this.a = a;
    this.b = b;
  }
  isResolved(index) {
    return this.a.isResolved(index);
  }
  get(index) {
    return this.a.get(index);
  }
  resolve(index, cancellationToken) {
    return new Promise((c, e) => {
      if (cancellationToken.isCancellationRequested) {
        return e(new $lb());
      }
      const timer = setTimeout(() => {
        if (cancellationToken.isCancellationRequested) {
          return e(new $lb());
        }
        timeoutCancellation.dispose();
        this.a.resolve(index, cancellationToken).then(c, e);
      }, this.b);
      const timeoutCancellation = cancellationToken.onCancellationRequested(() => {
        clearTimeout(timer);
        timeoutCancellation.dispose();
        e(new $lb());
      });
    });
  }
};

// out-build/vs/workbench/contrib/extensions/common/extensionQuery.js
var $pdc = class _$pdc {
  constructor(value, sortBy) {
    this.value = value;
    this.sortBy = sortBy;
    this.value = value.trim();
  }
  static suggestions(query) {
    const commands2 = ["installed", "updates", "enabled", "disabled", "builtin", "featured", "popular", "recommended", "recentlyPublished", "workspaceUnsupported", "deprecated", "sort", "category", "tag", "ext", "id"];
    const subcommands = {
      "sort": ["installs", "rating", "name", "publishedDate", "updateDate"],
      "category": $4z.map((c) => `"${c.toLowerCase()}"`),
      "tag": [""],
      "ext": [""],
      "id": [""]
    };
    const queryContains = (substr) => query.indexOf(substr) > -1;
    const hasSort = subcommands.sort.some((subcommand) => queryContains(`@sort:${subcommand}`));
    const hasCategory = subcommands.category.some((subcommand) => queryContains(`@category:${subcommand}`));
    return commands2.flatMap((command4) => {
      if (hasSort && command4 === "sort" || hasCategory && command4 === "category") {
        return [];
      }
      if (command4 in subcommands) {
        return subcommands[command4].map((subcommand) => `@${command4}:${subcommand}${subcommand === "" ? "" : " "}`);
      } else {
        return queryContains(`@${command4}`) ? [] : [`@${command4} `];
      }
    });
  }
  static parse(value) {
    let sortBy = "";
    value = value.replace(/@sort:(\w+)(-\w*)?/g, (match, by, order) => {
      sortBy = by;
      return "";
    });
    return new _$pdc(value, sortBy);
  }
  toString() {
    let result = this.value;
    if (this.sortBy) {
      result = `${result}${result ? " " : ""}@sort:${this.sortBy}`;
    }
    return result;
  }
  isValid() {
    return !/@outdated/.test(this.value);
  }
  equals(other) {
    return this.value === other.value && this.sortBy === other.sortBy;
  }
};

// out-build/vs/workbench/contrib/extensions/browser/extensionsViews.js
var $rdc_1;
var $qdc = "none";
var ExtensionsViewState = class extends $3c {
  constructor() {
    super(...arguments);
    this.c = this.B(new $ze());
    this.onFocus = this.c.event;
    this.f = this.B(new $ze());
    this.onBlur = this.f.event;
    this.g = [];
    this.filters = {};
  }
  onFocusChange(extensions) {
    this.g.forEach((extension) => this.f.fire(extension));
    this.g = extensions;
    this.g.forEach((extension) => this.c.fire(extension));
  }
};
var LocalSortBy;
(function(LocalSortBy2) {
  LocalSortBy2["UpdateDate"] = "UpdateDate";
})(LocalSortBy || (LocalSortBy = {}));
function isLocalSortBy(value) {
  switch (value) {
    case "UpdateDate":
      return true;
  }
}
var $rdc = class $rdc2 extends $_ob {
  static {
    $rdc_1 = this;
  }
  static {
    this.c = 7 * 24 * 60 * 60 * 1e3;
  }
  // 7 days
  constructor(L, viewletViewOptions, ab, keybindingService, contextMenuService, instantiationService, themeService, sb, ac, bc, telemetryService, hoverService, configurationService, cc, dc, ec, fc, gc, hc, contextKeyService, viewDescriptorService, openerService, ic, jc, kc, lc, mc, nc, oc, pc) {
    super({
      ...viewletViewOptions,
      showActions: ViewPaneShowActions.Always,
      maximumBodySize: L.flexibleHeight ? jc.getNumber(`${viewletViewOptions.id}.size`, 0, 0) ? void 0 : 0 : void 0
    }, keybindingService, contextMenuService, configurationService, contextKeyService, viewDescriptorService, instantiationService, openerService, themeService, telemetryService, hoverService);
    this.L = L;
    this.ab = ab;
    this.sb = sb;
    this.ac = ac;
    this.bc = bc;
    this.cc = cc;
    this.dc = dc;
    this.ec = ec;
    this.fc = fc;
    this.gc = gc;
    this.hc = hc;
    this.ic = ic;
    this.jc = jc;
    this.kc = kc;
    this.lc = lc;
    this.mc = mc;
    this.nc = nc;
    this.oc = oc;
    this.pc = pc;
    this.h = null;
    this.j = null;
    this.t = this.B(new $Vm());
    if (this.L.onDidChangeTitle) {
      this.B(this.L.onDidChangeTitle((title) => this.Qb(title)));
    }
    this.B(this.t.onDidRun(({ error }) => error && this.ab.error(error)));
    this.qc();
  }
  qc() {
  }
  U(container2) {
    container2.classList.add("extension-view-header");
    super.U(container2);
    if (!this.L.hideBadge) {
      this.g = this.B(new $D2($bk(container2, $(".count-badge-wrapper")), {}, $E$));
    }
  }
  W(container2) {
    super.W(container2);
    const messageContainer = $bk(container2, $(".message-container"));
    const messageSeverityIcon = $bk(messageContainer, $(""));
    const messageBox = $bk(messageContainer, $(".message"));
    const extensionsList = $bk(container2, $(".extensions-list"));
    const delegate = new $ndc();
    this.n = new ExtensionsViewState();
    const renderer = this.Db.createInstance($odc, this.n, {
      hoverOptions: {
        position: () => {
          const viewLocation = this.Cb.getViewLocationById(this.id);
          if (viewLocation === 0) {
            return this.mc.getSideBarPosition() === 0 ? 1 : 0;
          }
          if (viewLocation === 2) {
            return this.mc.getSideBarPosition() === 0 ? 0 : 1;
          }
          return 1;
        }
      }
    });
    this.h = this.Db.createInstance($Xeb, "Extensions", extensionsList, delegate, [renderer], {
      multipleSelectionSupport: false,
      setRowLineHeight: false,
      horizontalScrolling: false,
      accessibilityProvider: {
        getAriaLabel(extension) {
          return $Idc(extension);
        },
        getWidgetAriaLabel() {
          return localize(6859, null);
        }
      },
      overrideStyles: this.Xb().listOverrideStyles,
      openOnSingleClick: true
    });
    $Kzb.bindTo(this.h.contextKeyService);
    this.B(this.h.onContextMenu((e) => this.vc(e), this));
    this.B(this.h.onDidChangeFocus((e) => this.n?.onFocusChange($Mb(e.elements)), this));
    this.B(this.h);
    this.B(this.n);
    this.B(Event2.debounce(Event2.filter(this.h.onDidOpen, (e) => e.element !== null), (_, event) => event, 75, true)((options3) => {
      this.hd(options3.element, { sideByside: options3.sideBySide, ...options3.editorOptions });
    }));
    this.f = {
      extensionsList,
      messageBox,
      messageContainer,
      messageSeverityIcon
    };
    if (this.m) {
      this.bd(this.m.model);
    }
  }
  X(height, width2) {
    super.X(height, width2);
    if (this.f) {
      this.f.extensionsList.style.height = height + "px";
    }
    this.h?.layout(height, width2);
  }
  async show(query, refresh) {
    if (this.j) {
      if (!refresh && this.j.query === query) {
        return this.j.request;
      }
      this.j.request.cancel();
      this.j = null;
    }
    if (this.m) {
      this.m.disposables.dispose();
      this.m = void 0;
      if (this.n) {
        this.n.filters = {};
      }
    }
    const parsedQuery = $pdc.parse(query);
    const options3 = {
      sortOrder: 0
      /* SortOrder.Default */
    };
    switch (parsedQuery.sortBy) {
      case "installs":
        options3.sortBy = 4;
        break;
      case "rating":
        options3.sortBy = 12;
        break;
      case "name":
        options3.sortBy = 2;
        break;
      case "publishedDate":
        options3.sortBy = 10;
        break;
      case "updateDate":
        options3.sortBy = "UpdateDate";
        break;
    }
    const request = $Hh(async (token) => {
      try {
        this.m = await this.wc(parsedQuery, options3, token);
        const model = this.m.model;
        this.bd(model, this.m.description ? { text: this.m.description, severity: Severity2.Info } : void 0);
        if (this.m.onDidChangeModel) {
          this.m.disposables.add(this.m.onDidChangeModel((model2) => {
            if (this.m) {
              this.m.model = model2;
              this.cd(model2);
            }
          }));
        }
        return model;
      } catch (e) {
        const model = new $Vz([]);
        if (!$kb(e)) {
          this.pc.error(e);
          this.bd(model, this.ed(e));
        }
        return this.h ? this.h.model : model;
      }
    });
    request.finally(() => this.j = null);
    this.j = { query, request };
    return request;
  }
  count() {
    return this.m?.model.length ?? 0;
  }
  uc() {
    const emptyModel = new $Vz([]);
    this.bd(emptyModel);
    return Promise.resolve(emptyModel);
  }
  async vc(e) {
    if (e.element) {
      const disposables = new $2c();
      const manageExtensionAction = disposables.add(this.Db.createInstance($aDb));
      const extension = e.element ? this.ac.local.find((local) => $DA(local.identifier, e.element.identifier) && (!e.element.server || e.element.server === local.server)) || e.element : e.element;
      manageExtensionAction.extension = extension;
      let groups = [];
      if (manageExtensionAction.enabled) {
        groups = await manageExtensionAction.getActionGroups();
      } else if (extension) {
        groups = await $_Cb(extension, this.Bb, this.Db);
        groups.forEach((group2) => group2.forEach((extensionAction) => {
          if (extensionAction instanceof $UCb) {
            extensionAction.extension = extension;
          }
        }));
      }
      let actions = [];
      for (const menuActions of groups) {
        actions = [...actions, ...menuActions, new $Wm()];
      }
      actions.pop();
      this.zb.showContextMenu({
        getAnchor: () => e.anchor,
        getActions: () => actions,
        actionRunner: this.t,
        onHide: () => disposables.dispose()
      });
    }
  }
  async wc(query, options3, token) {
    const idRegex2 = /@id:(([a-z0-9A-Z][a-z0-9\-A-Z]*)\.([a-z0-9A-Z][a-z0-9\-A-Z]*))/g;
    const ids = [];
    let idMatch;
    while ((idMatch = idRegex2.exec(query.value)) !== null) {
      const name = idMatch[1];
      ids.push(name);
    }
    if (ids.length) {
      const model2 = await this.xc(ids, options3, token);
      return { model: model2, disposables: new $2c() };
    }
    if ($rdc_1.isLocalExtensionsQuery(query.value, query.sortBy)) {
      return this.yc(query, options3);
    }
    if ($rdc_1.isSearchPopularQuery(query.value)) {
      query.value = query.value.replace("@popular", "");
      options3.sortBy = !options3.sortBy ? 4 : options3.sortBy;
    } else if ($rdc_1.isSearchRecentlyPublishedQuery(query.value)) {
      query.value = query.value.replace("@recentlyPublished", "");
      options3.sortBy = !options3.sortBy ? 10 : options3.sortBy;
    }
    const galleryQueryOptions = { ...options3, sortBy: isLocalSortBy(options3.sortBy) ? void 0 : options3.sortBy };
    const model = await this.Mc(query, galleryQueryOptions, token);
    return { model, disposables: new $2c() };
  }
  async xc(ids, options3, token) {
    const idsSet = ids.reduce((result2, id2) => {
      result2.add(id2.toLowerCase());
      return result2;
    }, /* @__PURE__ */ new Set());
    const result = (await this.ac.queryLocal(this.L.server)).filter((e) => idsSet.has(e.identifier.id.toLowerCase()));
    const galleryIds = result.length ? ids.filter((id2) => result.every((r2) => !$DA(r2.identifier, { id: id2 }))) : ids;
    if (galleryIds.length) {
      const galleryResult = await this.ac.getExtensions(galleryIds.map((id2) => ({ id: id2 })), { source: "queryById" }, token);
      result.push(...galleryResult);
    }
    return new $Vz(result);
  }
  async yc(query, options3) {
    const local = await this.ac.queryLocal(this.L.server);
    let { extensions, canIncludeInstalledExtensions, description } = await this.zc(local, this.sb.extensions, query, options3);
    const disposables = new $2c();
    const onDidChangeModel = disposables.add(new $ze());
    if (canIncludeInstalledExtensions) {
      let isDisposed = false;
      disposables.add($1c(() => isDisposed = true));
      disposables.add(Event2.debounce(Event2.any(Event2.filter(
        this.ac.onChange,
        (e) => e?.state === 1
        /* ExtensionState.Installed */
      ), this.sb.onDidChangeExtensions), () => void 0)(async () => {
        const local2 = this.L.server ? this.ac.installed.filter((e) => e.server === this.L.server) : this.ac.local;
        const { extensions: newExtensions } = await this.zc(local2, this.sb.extensions, query, options3);
        if (!isDisposed) {
          const mergedExtensions = this.Lc(extensions, newExtensions);
          if (mergedExtensions) {
            extensions = mergedExtensions;
            onDidChangeModel.fire(new $Vz(extensions));
          }
        }
      }));
    }
    return {
      model: new $Vz(extensions),
      description,
      onDidChangeModel: onDidChangeModel.event,
      disposables
    };
  }
  async zc(local, runningExtensions, query, options3) {
    const value = query.value;
    let extensions = [];
    let canIncludeInstalledExtensions = true;
    let description;
    if (/@builtin/i.test(value)) {
      extensions = this.Ac(local, query, options3);
      canIncludeInstalledExtensions = false;
    } else if (/@installed/i.test(value)) {
      extensions = this.Dc(local, runningExtensions, query, options3);
    } else if (/@outdated/i.test(value)) {
      extensions = this.Ec(local, query, options3);
    } else if (/@disabled/i.test(value)) {
      extensions = this.Fc(local, runningExtensions, query, options3);
    } else if (/@enabled/i.test(value)) {
      extensions = this.Gc(local, runningExtensions, query, options3);
    } else if (/@workspaceUnsupported/i.test(value)) {
      extensions = this.Hc(local, query, options3);
    } else if (/@deprecated/i.test(query.value)) {
      extensions = await this.Ic(local, query, options3);
    } else if (/@recentlyUpdated/i.test(query.value)) {
      extensions = this.Jc(local, query, options3);
    } else if (/@feature:/i.test(query.value)) {
      const result = this.Kc(local, query);
      if (result) {
        extensions = result.extensions;
        description = result.description;
      }
    }
    return { extensions, canIncludeInstalledExtensions, description };
  }
  Ac(local, query, options3) {
    let { value, includedCategories, excludedCategories } = this.Cc(query.value);
    value = value.replace(/@builtin/g, "").replace(/@sort:(\w+)(-\w*)?/g, "").trim().toLowerCase();
    const result = local.filter((e) => e.isBuiltin && (e.name.toLowerCase().indexOf(value) > -1 || e.displayName.toLowerCase().indexOf(value) > -1) && this.Bc(e, includedCategories, excludedCategories));
    return this.Oc(result, options3);
  }
  Bc(e, includedCategories, excludedCategories) {
    if (!includedCategories.length && !excludedCategories.length) {
      return true;
    }
    if (e.categories.length) {
      if (excludedCategories.length && e.categories.some((category8) => excludedCategories.includes(category8.toLowerCase()))) {
        return false;
      }
      return e.categories.some((category8) => includedCategories.includes(category8.toLowerCase()));
    } else {
      return includedCategories.includes($qdc);
    }
  }
  Cc(value) {
    const includedCategories = [];
    const excludedCategories = [];
    value = value.replace(/\bcategory:("([^"]*)"|([^"]\S*))(\s+|\b|$)/g, (_, quotedCategory, category8) => {
      const entry = (category8 || quotedCategory || "").toLowerCase();
      if (entry.startsWith("-")) {
        if (excludedCategories.indexOf(entry) === -1) {
          excludedCategories.push(entry);
        }
      } else {
        if (includedCategories.indexOf(entry) === -1) {
          includedCategories.push(entry);
        }
      }
      return "";
    });
    return { value, includedCategories, excludedCategories };
  }
  Dc(local, runningExtensions, query, options3) {
    let { value, includedCategories, excludedCategories } = this.Cc(query.value);
    value = value.replace(/@installed/g, "").replace(/@sort:(\w+)(-\w*)?/g, "").trim().toLowerCase();
    const matchingText = (e) => (e.name.toLowerCase().indexOf(value) > -1 || e.displayName.toLowerCase().indexOf(value) > -1 || e.description.toLowerCase().indexOf(value) > -1) && this.Bc(e, includedCategories, excludedCategories);
    let result;
    if (options3.sortBy !== void 0) {
      result = local.filter((e) => !e.isBuiltin && matchingText(e));
      result = this.Oc(result, options3);
    } else {
      result = local.filter((e) => (!e.isBuiltin || e.outdated || e.runtimeState !== void 0) && matchingText(e));
      const runningExtensionsById = runningExtensions.reduce((result2, e) => {
        result2.set(e.identifier.value, e);
        return result2;
      }, new $7z());
      const defaultSort = (e1, e2) => {
        const running1 = runningExtensionsById.get(e1.identifier.id);
        const isE1Running = !!running1 && this.dc.getExtensionManagementServer($DN(running1)) === e1.server;
        const running2 = runningExtensionsById.get(e2.identifier.id);
        const isE2Running = running2 && this.dc.getExtensionManagementServer($DN(running2)) === e2.server;
        if (isE1Running && isE2Running) {
          return e1.displayName.localeCompare(e2.displayName);
        }
        const isE1LanguagePackExtension = e1.local && $9z(e1.local.manifest);
        const isE2LanguagePackExtension = e2.local && $9z(e2.local.manifest);
        if (!isE1Running && !isE2Running) {
          if (isE1LanguagePackExtension) {
            return -1;
          }
          if (isE2LanguagePackExtension) {
            return 1;
          }
          return e1.displayName.localeCompare(e2.displayName);
        }
        if (isE1Running && isE2LanguagePackExtension || isE2Running && isE1LanguagePackExtension) {
          return e1.displayName.localeCompare(e2.displayName);
        }
        return isE1Running ? -1 : 1;
      };
      const incompatible = [];
      const deprecated = [];
      const outdated = [];
      const actionRequired = [];
      const noActionRequired = [];
      for (const e of result) {
        if (e.enablementState === 5) {
          incompatible.push(e);
        } else if (e.deprecationInfo) {
          deprecated.push(e);
        } else if (e.outdated && this.lc.isEnabledEnablementState(e.enablementState)) {
          outdated.push(e);
        } else if (e.runtimeState) {
          actionRequired.push(e);
        } else {
          noActionRequired.push(e);
        }
      }
      result = [
        ...incompatible.sort(defaultSort),
        ...deprecated.sort(defaultSort),
        ...outdated.sort(defaultSort),
        ...actionRequired.sort(defaultSort),
        ...noActionRequired.sort(defaultSort)
      ];
    }
    return result;
  }
  Ec(local, query, options3) {
    let { value, includedCategories, excludedCategories } = this.Cc(query.value);
    value = value.replace(/@outdated/g, "").replace(/@sort:(\w+)(-\w*)?/g, "").trim().toLowerCase();
    const result = local.sort((e1, e2) => e1.displayName.localeCompare(e2.displayName)).filter((extension) => extension.outdated && (extension.name.toLowerCase().indexOf(value) > -1 || extension.displayName.toLowerCase().indexOf(value) > -1) && this.Bc(extension, includedCategories, excludedCategories));
    return this.Oc(result, options3);
  }
  Fc(local, runningExtensions, query, options3) {
    let { value, includedCategories, excludedCategories } = this.Cc(query.value);
    value = value.replace(/@disabled/g, "").replace(/@sort:(\w+)(-\w*)?/g, "").trim().toLowerCase();
    const result = local.sort((e1, e2) => e1.displayName.localeCompare(e2.displayName)).filter((e) => runningExtensions.every((r2) => !$DA({ id: r2.identifier.value, uuid: r2.uuid }, e.identifier)) && (e.name.toLowerCase().indexOf(value) > -1 || e.displayName.toLowerCase().indexOf(value) > -1) && this.Bc(e, includedCategories, excludedCategories));
    return this.Oc(result, options3);
  }
  Gc(local, runningExtensions, query, options3) {
    let { value, includedCategories, excludedCategories } = this.Cc(query.value);
    value = value ? value.replace(/@enabled/g, "").replace(/@sort:(\w+)(-\w*)?/g, "").trim().toLowerCase() : "";
    local = local.filter((e) => !e.isBuiltin);
    const result = local.sort((e1, e2) => e1.displayName.localeCompare(e2.displayName)).filter((e) => runningExtensions.some((r2) => $DA({ id: r2.identifier.value, uuid: r2.uuid }, e.identifier)) && (e.name.toLowerCase().indexOf(value) > -1 || e.displayName.toLowerCase().indexOf(value) > -1) && this.Bc(e, includedCategories, excludedCategories));
    return this.Oc(result, options3);
  }
  Hc(local, query, options3) {
    const queryString = query.value;
    const match = queryString.match(/^\s*@workspaceUnsupported(?::(untrusted|virtual)(Partial)?)?(?:\s+([^\s]*))?/i);
    if (!match) {
      return [];
    }
    const type = match[1]?.toLowerCase();
    const partial = !!match[2];
    const nameFilter = match[3]?.toLowerCase();
    if (nameFilter) {
      local = local.filter((extension) => extension.name.toLowerCase().indexOf(nameFilter) > -1 || extension.displayName.toLowerCase().indexOf(nameFilter) > -1);
    }
    const hasVirtualSupportType = (extension, supportType) => {
      return extension.local && this.ec.getExtensionVirtualWorkspaceSupportType(extension.local.manifest) === supportType;
    };
    const hasRestrictedSupportType = (extension, supportType) => {
      if (!extension.local) {
        return false;
      }
      const enablementState = this.lc.getEnablementState(extension.local);
      if (enablementState !== 10 && enablementState !== 11 && enablementState !== 0 && enablementState !== 7) {
        return false;
      }
      if (this.ec.getExtensionUntrustedWorkspaceSupportType(extension.local.manifest) === supportType) {
        return true;
      }
      if (supportType === false) {
        const dependencies = $NA(local.map((ext) => ext.local), extension.local);
        return dependencies.some((ext) => this.ec.getExtensionUntrustedWorkspaceSupportType(ext.manifest) === supportType);
      }
      return false;
    };
    const inVirtualWorkspace = $_S(this.gc.getWorkspace());
    const inRestrictedWorkspace = !this.kc.isWorkspaceTrusted();
    if (type === "virtual") {
      local = local.filter((extension) => inVirtualWorkspace && hasVirtualSupportType(extension, partial ? "limited" : false) && !(inRestrictedWorkspace && hasRestrictedSupportType(extension, false)));
    } else if (type === "untrusted") {
      local = local.filter((extension) => hasRestrictedSupportType(extension, partial ? "limited" : false) && !(inVirtualWorkspace && hasVirtualSupportType(extension, false)));
    } else {
      local = local.filter((extension) => inVirtualWorkspace && !hasVirtualSupportType(extension, true) || inRestrictedWorkspace && !hasRestrictedSupportType(extension, true));
    }
    return this.Oc(local, options3);
  }
  async Ic(local, query, options3) {
    const value = query.value.replace(/@deprecated/g, "").replace(/@sort:(\w+)(-\w*)?/g, "").trim().toLowerCase();
    const extensionsControlManifest = await this.fc.getExtensionsControlManifest();
    const deprecatedExtensionIds = Object.keys(extensionsControlManifest.deprecated);
    local = local.filter((e) => deprecatedExtensionIds.includes(e.identifier.id) && (!value || e.name.toLowerCase().indexOf(value) > -1 || e.displayName.toLowerCase().indexOf(value) > -1));
    return this.Oc(local, options3);
  }
  Jc(local, query, options3) {
    let { value, includedCategories, excludedCategories } = this.Cc(query.value);
    const currentTime = Date.now();
    local = local.filter((e) => !e.isBuiltin && !e.outdated && e.local?.updated && e.local?.installedTimestamp !== void 0 && currentTime - e.local.installedTimestamp < $rdc_1.c);
    value = value.replace(/@recentlyUpdated/g, "").replace(/@sort:(\w+)(-\w*)?/g, "").trim().toLowerCase();
    const result = local.filter((e) => (e.name.toLowerCase().indexOf(value) > -1 || e.displayName.toLowerCase().indexOf(value) > -1) && this.Bc(e, includedCategories, excludedCategories));
    options3.sortBy = options3.sortBy ?? "UpdateDate";
    return this.Oc(result, options3);
  }
  Kc(local, query) {
    const value = query.value.replace(/@feature:/g, "").trim();
    const featureId = value.split(" ")[0];
    const feature = $Wn.as(Extensions3.ExtensionFeaturesRegistry).getExtensionFeature(featureId);
    if (!feature) {
      return void 0;
    }
    if (this.n) {
      this.n.filters.featureId = featureId;
    }
    const renderer = feature.renderer ? this.Db.createInstance(feature.renderer) : void 0;
    try {
      const result = [];
      for (const e of local) {
        if (!e.local) {
          continue;
        }
        const accessData = this.nc.getAccessData(new $5z(e.identifier.id), featureId);
        const shouldRender = renderer?.shouldRender(e.local.manifest);
        if (accessData || shouldRender) {
          result.push([e, accessData?.accessTimes.length ?? 0]);
        }
      }
      return {
        extensions: result.sort(([, a], [, b]) => b - a).map(([e]) => e),
        description: localize(6860, null, feature.label)
      };
    } finally {
      renderer?.dispose();
    }
  }
  Lc(extensions, newExtensions) {
    const oldExtensions = [...extensions];
    const findPreviousExtensionIndex = (from) => {
      let index = -1;
      const previousExtensionInNew = newExtensions[from];
      if (previousExtensionInNew) {
        index = oldExtensions.findIndex((e) => $DA(e.identifier, previousExtensionInNew.identifier));
        if (index === -1) {
          return findPreviousExtensionIndex(from - 1);
        }
      }
      return index;
    };
    let hasChanged = false;
    for (let index = 0; index < newExtensions.length; index++) {
      const extension = newExtensions[index];
      if (extensions.every((r2) => !$DA(r2.identifier, extension.identifier))) {
        hasChanged = true;
        extensions.splice(findPreviousExtensionIndex(index - 1) + 1, 0, extension);
      }
    }
    return hasChanged ? extensions : void 0;
  }
  async Mc(query, options3, token) {
    const hasUserDefinedSortOrder = options3.sortBy !== void 0;
    if (!hasUserDefinedSortOrder && !query.value.trim()) {
      options3.sortBy = 4;
    }
    if (this.Pc(query)) {
      return this.Qc(query, options3, token);
    }
    const text2 = query.value;
    if (!text2) {
      options3.source = "viewlet";
      const pager2 = await this.ac.queryGallery(options3, token);
      return new $Vz(pager2);
    }
    if (/\bext:([^\s]+)\b/g.test(text2)) {
      options3.text = text2;
      options3.source = "file-extension-tags";
      const pager2 = await this.ac.queryGallery(options3, token);
      return new $Vz(pager2);
    }
    options3.text = text2.substring(0, 350);
    options3.source = "searchText";
    if (hasUserDefinedSortOrder || /\b(category|tag):([^\s]+)\b/gi.test(text2) || /\bfeatured(\s+|\b|$)/gi.test(text2)) {
      const pager2 = await this.ac.queryGallery(options3, token);
      return new $Vz(pager2);
    }
    const [pager, preferredExtensions] = await Promise.all([
      this.ac.queryGallery(options3, token),
      this.Nc(options3.text.toLowerCase(), token).catch(() => [])
    ]);
    return preferredExtensions.length ? new $Jdc(preferredExtensions, pager) : new $Vz(pager);
  }
  async Nc(searchText, token) {
    const preferredExtensions = this.ac.local.filter((e) => !e.isBuiltin && (e.name.toLowerCase().indexOf(searchText) > -1 || e.displayName.toLowerCase().indexOf(searchText) > -1 || e.description.toLowerCase().indexOf(searchText) > -1));
    const preferredExtensionUUIDs = /* @__PURE__ */ new Set();
    if (preferredExtensions.length) {
      const extesionsToFetch = [];
      for (const extension of preferredExtensions) {
        if (extension.identifier.uuid) {
          preferredExtensionUUIDs.add(extension.identifier.uuid);
        }
        if (!extension.gallery && extension.identifier.uuid) {
          extesionsToFetch.push(extension.identifier);
        }
      }
      if (extesionsToFetch.length) {
        this.ac.getExtensions(extesionsToFetch, CancellationToken.None).catch(
          (e) => null
          /*ignore error*/
        );
      }
    }
    const preferredResults = [];
    try {
      const manifest = await this.fc.getExtensionsControlManifest();
      if (Array.isArray(manifest.search)) {
        for (const s of manifest.search) {
          if (s.query && s.query.toLowerCase() === searchText && Array.isArray(s.preferredResults)) {
            preferredResults.push(...s.preferredResults);
            break;
          }
        }
      }
      if (preferredResults.length) {
        const result = await this.ac.getExtensions(preferredResults.map((id2) => ({ id: id2 })), token);
        for (const extension of result) {
          if (extension.identifier.uuid && !preferredExtensionUUIDs.has(extension.identifier.uuid)) {
            preferredExtensions.push(extension);
          }
        }
      }
    } catch (e) {
      this.pc.warn("Failed to get preferred results from the extensions control manifest.", e);
    }
    return preferredExtensions;
  }
  Oc(extensions, options3) {
    switch (options3.sortBy) {
      case 4:
        extensions = extensions.sort((e1, e2) => typeof e2.installCount === "number" && typeof e1.installCount === "number" ? e2.installCount - e1.installCount : NaN);
        break;
      case "UpdateDate":
        extensions = extensions.sort((e1, e2) => typeof e2.local?.installedTimestamp === "number" && typeof e1.local?.installedTimestamp === "number" ? e2.local.installedTimestamp - e1.local.installedTimestamp : typeof e2.local?.installedTimestamp === "number" ? 1 : typeof e1.local?.installedTimestamp === "number" ? -1 : NaN);
        break;
      case 6:
      case 12:
        extensions = extensions.sort((e1, e2) => typeof e2.rating === "number" && typeof e1.rating === "number" ? e2.rating - e1.rating : NaN);
        break;
      default:
        extensions = extensions.sort((e1, e2) => e1.displayName.localeCompare(e2.displayName));
        break;
    }
    if (options3.sortOrder === 2) {
      extensions = extensions.reverse();
    }
    return extensions;
  }
  Pc(query) {
    return $rdc_1.isWorkspaceRecommendedExtensionsQuery(query.value) || $rdc_1.isKeymapsRecommendedExtensionsQuery(query.value) || $rdc_1.isLanguageRecommendedExtensionsQuery(query.value) || $rdc_1.isExeRecommendedExtensionsQuery(query.value) || $rdc_1.isRemoteRecommendedExtensionsQuery(query.value) || /@recommended:all/i.test(query.value) || $rdc_1.isSearchRecommendedExtensionsQuery(query.value) || $rdc_1.isRecommendedExtensionsQuery(query.value);
  }
  async Qc(query, options3, token) {
    if ($rdc_1.isWorkspaceRecommendedExtensionsQuery(query.value)) {
      return this.Tc(query, options3, token);
    }
    if ($rdc_1.isKeymapsRecommendedExtensionsQuery(query.value)) {
      return this.Uc(query, options3, token);
    }
    if ($rdc_1.isLanguageRecommendedExtensionsQuery(query.value)) {
      return this.Vc(query, options3, token);
    }
    if ($rdc_1.isExeRecommendedExtensionsQuery(query.value)) {
      return this.Xc(query, options3, token);
    }
    if ($rdc_1.isRemoteRecommendedExtensionsQuery(query.value)) {
      return this.Wc(query, options3, token);
    }
    if (/@recommended:all/i.test(query.value)) {
      return this.$c(options3, token);
    }
    if ($rdc_1.isSearchRecommendedExtensionsQuery(query.value) || $rdc_1.isRecommendedExtensionsQuery(query.value) && options3.sortBy !== void 0) {
      return this.ad(query, options3, token);
    }
    if ($rdc_1.isRecommendedExtensionsQuery(query.value)) {
      return this.Yc(query, options3, token);
    }
    return new $Vz([]);
  }
  async Rc(recommendations, options3, token) {
    const result = [];
    if (recommendations.length) {
      const galleryExtensions = [];
      const resourceExtensions = [];
      for (const recommendation of recommendations) {
        if (typeof recommendation === "string") {
          galleryExtensions.push(recommendation);
        } else {
          resourceExtensions.push(recommendation);
        }
      }
      if (galleryExtensions.length) {
        try {
          const extensions = await this.ac.getExtensions(galleryExtensions.map((id2) => ({ id: id2 })), { source: options3.source }, token);
          for (const extension of extensions) {
            if (extension.gallery && !extension.deprecationInfo && await this.fc.canInstall(extension.gallery) === true) {
              result.push(extension);
            }
          }
        } catch (error) {
          if (!resourceExtensions.length || !this.fd(error)) {
            throw error;
          }
        }
      }
      if (resourceExtensions.length) {
        const extensions = await this.ac.getResourceExtensions(resourceExtensions, true);
        for (const extension of extensions) {
          if (await this.ac.canInstall(extension) === true) {
            result.push(extension);
          }
        }
      }
    }
    return result;
  }
  async Sc() {
    const recommendations = await this.bc.getWorkspaceRecommendations();
    const { important } = await this.bc.getConfigBasedRecommendations();
    for (const configBasedRecommendation of important) {
      if (!recommendations.find((extensionId) => extensionId === configBasedRecommendation)) {
        recommendations.push(configBasedRecommendation);
      }
    }
    return recommendations;
  }
  async Tc(query, options3, token) {
    const recommendations = await this.Sc();
    const installableRecommendations = await this.Rc(recommendations, { ...options3, source: "recommendations-workspace" }, token);
    return new $Vz(installableRecommendations);
  }
  async Uc(query, options3, token) {
    const value = query.value.replace(/@recommended:keymaps/g, "").trim().toLowerCase();
    const recommendations = this.bc.getKeymapRecommendations();
    const installableRecommendations = (await this.Rc(recommendations, { ...options3, source: "recommendations-keymaps" }, token)).filter((extension) => extension.identifier.id.toLowerCase().indexOf(value) > -1);
    return new $Vz(installableRecommendations);
  }
  async Vc(query, options3, token) {
    const value = query.value.replace(/@recommended:languages/g, "").trim().toLowerCase();
    const recommendations = this.bc.getLanguageRecommendations();
    const installableRecommendations = (await this.Rc(recommendations, { ...options3, source: "recommendations-languages" }, token)).filter((extension) => extension.identifier.id.toLowerCase().indexOf(value) > -1);
    return new $Vz(installableRecommendations);
  }
  async Wc(query, options3, token) {
    const value = query.value.replace(/@recommended:remotes/g, "").trim().toLowerCase();
    const recommendations = this.bc.getRemoteRecommendations();
    const installableRecommendations = (await this.Rc(recommendations, { ...options3, source: "recommendations-remotes" }, token)).filter((extension) => extension.identifier.id.toLowerCase().indexOf(value) > -1);
    return new $Vz(installableRecommendations);
  }
  async Xc(query, options3, token) {
    const exe = query.value.replace(/@exe:/g, "").trim().toLowerCase();
    const { important, others } = await this.bc.getExeBasedRecommendations(exe.startsWith('"') ? exe.substring(1, exe.length - 1) : exe);
    const installableRecommendations = await this.Rc([...important, ...others], { ...options3, source: "recommendations-exe" }, token);
    return new $Vz(installableRecommendations);
  }
  async Yc(query, options3, token) {
    const otherRecommendations = await this.Zc();
    const installableRecommendations = await this.Rc(otherRecommendations, { ...options3, source: "recommendations-other", sortBy: void 0 }, token);
    const result = $Mb(otherRecommendations.map((id2) => installableRecommendations.find((i2) => $DA(i2.identifier, { id: id2 }))));
    return new $Vz(result);
  }
  async Zc() {
    const local = (await this.ac.queryLocal(this.L.server)).map((e) => e.identifier.id.toLowerCase());
    const workspaceRecommendations = (await this.Sc()).map((extensionId) => $zg(extensionId) ? extensionId.toLowerCase() : extensionId);
    return $Rb((await Promise.all([
      // Order is important
      this.bc.getImportantRecommendations(),
      this.bc.getFileBasedRecommendations(),
      this.bc.getOtherRecommendations()
    ])).flat().filter((extensionId) => !local.includes(extensionId.toLowerCase()) && !workspaceRecommendations.includes(extensionId.toLowerCase())), (extensionId) => extensionId.toLowerCase());
  }
  // Get All types of recommendations, trimmed to show a max of 8 at any given time
  async $c(options3, token) {
    const localExtensions = await this.ac.queryLocal(this.L.server);
    const localExtensionIds = localExtensions.map((e) => e.identifier.id.toLowerCase());
    const allRecommendations = $Rb((await Promise.all([
      // Order is important
      this.Sc(),
      this.bc.getImportantRecommendations(),
      this.bc.getFileBasedRecommendations(),
      this.bc.getOtherRecommendations()
    ])).flat().filter((extensionId) => {
      if ($zg(extensionId)) {
        return !localExtensionIds.includes(extensionId.toLowerCase());
      }
      return !localExtensions.some((localExtension) => localExtension.local && this.oc.extUri.isEqual(localExtension.local.location, extensionId));
    }));
    const installableRecommendations = await this.Rc(allRecommendations, { ...options3, source: "recommendations-all", sortBy: void 0 }, token);
    const result = [];
    for (let i2 = 0; i2 < installableRecommendations.length && result.length < 8; i2++) {
      const recommendation = allRecommendations[i2];
      if ($zg(recommendation)) {
        const extension = installableRecommendations.find((extension2) => $DA(extension2.identifier, { id: recommendation }));
        if (extension) {
          result.push(extension);
        }
      } else {
        const extension = installableRecommendations.find((extension2) => extension2.resourceExtension && this.oc.extUri.isEqual(extension2.resourceExtension.location, recommendation));
        if (extension) {
          result.push(extension);
        }
      }
    }
    return new $Vz(result);
  }
  async ad(query, options3, token) {
    const value = query.value.replace(/@recommended/g, "").trim().toLowerCase();
    const recommendations = $Rb([...await this.Sc(), ...await this.Zc()]);
    const installableRecommendations = (await this.Rc(recommendations, { ...options3, source: "recommendations", sortBy: void 0 }, token)).filter((extension) => extension.identifier.id.toLowerCase().indexOf(value) > -1);
    return new $Vz(this.Oc(installableRecommendations, options3));
  }
  bd(model, message, donotResetScrollTop) {
    if (this.h) {
      this.h.model = new $Wz(model);
      this.dd(message);
      if (!donotResetScrollTop) {
        this.h.scrollTop = 0;
      }
    }
    if (this.g) {
      this.g.setCount(this.count());
    }
  }
  cd(model) {
    if (this.h) {
      this.h.model = new $Wz(model);
      this.dd();
    }
    if (this.g) {
      this.g.setCount(this.count());
    }
  }
  dd(message) {
    if (this.f) {
      const count = this.count();
      this.f.extensionsList.classList.toggle("hidden", count === 0);
      this.f.messageContainer.classList.toggle("hidden", !message && count > 0);
      if (this.isBodyVisible()) {
        if (message) {
          this.f.messageSeverityIcon.className = SeverityIcon.className(message.severity);
          this.f.messageBox.textContent = message.text;
        } else if (this.count() === 0) {
          this.f.messageSeverityIcon.className = "";
          this.f.messageBox.textContent = localize(6861, null);
        }
        if (this.f.messageBox.textContent) {
          $$Z(this.f.messageBox.textContent);
        }
      }
    }
    this.gd();
  }
  ed(error) {
    if (this.fd(error)) {
      return { text: localize(6862, null), severity: Severity2.Warning };
    } else {
      return { text: localize(6863, null, $qb(error)), severity: Severity2.Error };
    }
  }
  fd(error) {
    if (error instanceof $qA) {
      return error.code === "Offline";
    }
    return $7u(error);
  }
  gd() {
    if (this.L.flexibleHeight) {
      this.maximumBodySize = this.h?.model.length ? Number.POSITIVE_INFINITY : 0;
      this.jc.store(
        `${this.id}.size`,
        this.h?.model.length || 0,
        0,
        1
        /* StorageTarget.MACHINE */
      );
    }
  }
  hd(extension, options3) {
    extension = this.ac.local.filter((e) => $DA(e.identifier, extension.identifier))[0] || extension;
    this.ac.open(extension, options3).then(void 0, (err) => this.jd(err));
  }
  jd(err) {
    if ($kb(err)) {
      return;
    }
    const message = err && err.message || "";
    if (/ECONNREFUSED/.test(message)) {
      const error = $3m(localize(6864, null), [
        new $Um("open user settings", localize(6865, null), void 0, true, () => this.ic.openUserSettings())
      ]);
      this.ab.error(error);
      return;
    }
    this.ab.error(err);
  }
  dispose() {
    super.dispose();
    if (this.j) {
      this.j.request.cancel();
      this.j = null;
    }
    if (this.m) {
      this.m.disposables.dispose();
      this.m = void 0;
    }
    this.h = null;
  }
  static isLocalExtensionsQuery(query, sortBy) {
    return this.isInstalledExtensionsQuery(query) || this.isSearchInstalledExtensionsQuery(query) || this.isOutdatedExtensionsQuery(query) || this.isEnabledExtensionsQuery(query) || this.isDisabledExtensionsQuery(query) || this.isBuiltInExtensionsQuery(query) || this.isSearchBuiltInExtensionsQuery(query) || this.isBuiltInGroupExtensionsQuery(query) || this.isSearchDeprecatedExtensionsQuery(query) || this.isSearchWorkspaceUnsupportedExtensionsQuery(query) || this.isSearchRecentlyUpdatedQuery(query) || this.isSearchExtensionUpdatesQuery(query) || this.isSortInstalledExtensionsQuery(query, sortBy) || this.isFeatureExtensionsQuery(query);
  }
  static isSearchBuiltInExtensionsQuery(query) {
    return /@builtin\s.+/i.test(query);
  }
  static isBuiltInExtensionsQuery(query) {
    return /^\s*@builtin$/i.test(query.trim());
  }
  static isBuiltInGroupExtensionsQuery(query) {
    return /^\s*@builtin:.+$/i.test(query.trim());
  }
  static isSearchWorkspaceUnsupportedExtensionsQuery(query) {
    return /^\s*@workspaceUnsupported(:(untrusted|virtual)(Partial)?)?(\s|$)/i.test(query);
  }
  static isInstalledExtensionsQuery(query) {
    return /@installed$/i.test(query);
  }
  static isSearchInstalledExtensionsQuery(query) {
    return /@installed\s./i.test(query) || this.isFeatureExtensionsQuery(query);
  }
  static isOutdatedExtensionsQuery(query) {
    return /@outdated/i.test(query);
  }
  static isEnabledExtensionsQuery(query) {
    return /@enabled/i.test(query);
  }
  static isDisabledExtensionsQuery(query) {
    return /@disabled/i.test(query);
  }
  static isSearchDeprecatedExtensionsQuery(query) {
    return /@deprecated\s?.*/i.test(query);
  }
  static isRecommendedExtensionsQuery(query) {
    return /^@recommended$/i.test(query.trim());
  }
  static isSearchRecommendedExtensionsQuery(query) {
    return /@recommended\s.+/i.test(query);
  }
  static isWorkspaceRecommendedExtensionsQuery(query) {
    return /@recommended:workspace/i.test(query);
  }
  static isExeRecommendedExtensionsQuery(query) {
    return /@exe:.+/i.test(query);
  }
  static isRemoteRecommendedExtensionsQuery(query) {
    return /@recommended:remotes/i.test(query);
  }
  static isKeymapsRecommendedExtensionsQuery(query) {
    return /@recommended:keymaps/i.test(query);
  }
  static isLanguageRecommendedExtensionsQuery(query) {
    return /@recommended:languages/i.test(query);
  }
  static isSortInstalledExtensionsQuery(query, sortBy) {
    return sortBy !== void 0 && sortBy !== "" && query === "" || !sortBy && /^@sort:\S*$/i.test(query);
  }
  static isSearchPopularQuery(query) {
    return /@popular/i.test(query);
  }
  static isSearchRecentlyPublishedQuery(query) {
    return /@recentlyPublished/i.test(query);
  }
  static isSearchRecentlyUpdatedQuery(query) {
    return /@recentlyUpdated/i.test(query);
  }
  static isSearchExtensionUpdatesQuery(query) {
    return /@updates/i.test(query);
  }
  static isSortUpdateDateQuery(query) {
    return /@sort:updateDate/i.test(query);
  }
  static isFeatureExtensionsQuery(query) {
    return /@feature:/i.test(query);
  }
  focus() {
    super.focus();
    if (!this.h) {
      return;
    }
    if (!(this.h.getFocus().length || this.h.getSelection().length)) {
      this.h.focusNext();
    }
    this.h.domFocus();
  }
};
$rdc = $rdc_1 = __decorate([
  __param(2, $PJ),
  __param(3, $Ty),
  __param(4, $50),
  __param(5, $Pk),
  __param(6, $gs),
  __param(7, $wN),
  __param(8, $vzb),
  __param(9, $ABb),
  __param(10, $zv),
  __param(11, $5$),
  __param(12, $kl),
  __param(13, $Zk),
  __param(14, $nzb),
  __param(15, $LCb),
  __param(16, $pzb),
  __param(17, $Zk),
  __param(18, $Vu),
  __param(19, $on),
  __param(20, $$M),
  __param(21, $O4),
  __param(22, $TK),
  __param(23, $jv),
  __param(24, $4M),
  __param(25, $qzb),
  __param(26, $Vlb),
  __param(27, $wlb),
  __param(28, $vl),
  __param(29, $wn)
], $rdc);
var $sdc = class extends $rdc {
  async show() {
    const query = this.dc.webExtensionManagementServer && !this.dc.localExtensionManagementServer && !this.dc.remoteExtensionManagementServer ? "@web" : "";
    return super.show(query);
  }
};
var $tdc = class extends $rdc {
  async show(query) {
    query = query ? query : "@installed";
    if (!$rdc.isLocalExtensionsQuery(query) || $rdc.isSortInstalledExtensionsQuery(query)) {
      query = query += " @installed";
    }
    return super.show(query.trim());
  }
};
var $udc = class extends $rdc {
  async show(query) {
    query = query || "@enabled";
    return $rdc.isEnabledExtensionsQuery(query) ? super.show(query) : $rdc.isSortInstalledExtensionsQuery(query) ? super.show("@enabled " + query) : this.uc();
  }
};
var $vdc = class extends $rdc {
  async show(query) {
    query = query || "@disabled";
    return $rdc.isDisabledExtensionsQuery(query) ? super.show(query) : $rdc.isSortInstalledExtensionsQuery(query) ? super.show("@disabled " + query) : this.uc();
  }
};
var $wdc = class extends $rdc {
  async show(query) {
    query = query ? query : "@outdated";
    if ($rdc.isSearchExtensionUpdatesQuery(query)) {
      query = query.replace("@updates", "@outdated");
    }
    return super.show(query.trim());
  }
  gd() {
    super.gd();
    this.setExpanded(this.count() > 0);
  }
};
var $xdc = class extends $rdc {
  async show(query) {
    query = query ? query : "@recentlyUpdated";
    if ($rdc.isSearchExtensionUpdatesQuery(query)) {
      query = query.replace("@updates", "@recentlyUpdated");
    }
    return super.show(query.trim());
  }
};
var $ydc = class $ydc2 extends $rdc {
  constructor(L, viewletViewOptions, notificationService, keybindingService, contextMenuService, instantiationService, themeService, extensionService, extensionsWorkbenchService, extensionRecommendationsService, telemetryService, hoverService, configurationService, contextService, extensionManagementServerService, extensionManifestPropertiesService, extensionManagementService, workspaceService, productService, contextKeyService, viewDescriptorService, openerService, preferencesService, storageService, workspaceTrustManagementService, extensionEnablementService, layoutService, extensionFeaturesManagementService, uriIdentityService, logService) {
    super(L, viewletViewOptions, notificationService, keybindingService, contextMenuService, instantiationService, themeService, extensionService, extensionsWorkbenchService, extensionRecommendationsService, telemetryService, hoverService, configurationService, contextService, extensionManagementServerService, extensionManifestPropertiesService, extensionManagementService, workspaceService, productService, contextKeyService, viewDescriptorService, openerService, preferencesService, storageService, workspaceTrustManagementService, extensionEnablementService, layoutService, extensionFeaturesManagementService, uriIdentityService, logService);
    this.L = L;
  }
  show() {
    return super.show(this.L.query);
  }
};
$ydc = __decorate([
  __param(2, $PJ),
  __param(3, $Ty),
  __param(4, $50),
  __param(5, $Pk),
  __param(6, $gs),
  __param(7, $wN),
  __param(8, $vzb),
  __param(9, $ABb),
  __param(10, $zv),
  __param(11, $5$),
  __param(12, $kl),
  __param(13, $Zk),
  __param(14, $nzb),
  __param(15, $LCb),
  __param(16, $pzb),
  __param(17, $Zk),
  __param(18, $Vu),
  __param(19, $on),
  __param(20, $$M),
  __param(21, $O4),
  __param(22, $TK),
  __param(23, $jv),
  __param(24, $4M),
  __param(25, $qzb),
  __param(26, $Vlb),
  __param(27, $wlb),
  __param(28, $vl),
  __param(29, $wn)
], $ydc);
function toSpecificWorkspaceUnsupportedQuery(query, qualifier) {
  if (!query) {
    return "@workspaceUnsupported:" + qualifier;
  }
  const match = query.match(new RegExp(`@workspaceUnsupported(:${qualifier})?(\\s|$)`, "i"));
  if (match) {
    if (!match[1]) {
      return query.replace(/@workspaceUnsupported/gi, "@workspaceUnsupported:" + qualifier);
    }
    return query;
  }
  return void 0;
}
var $zdc = class extends $rdc {
  async show(query) {
    const updatedQuery = toSpecificWorkspaceUnsupportedQuery(query, "untrusted");
    return updatedQuery ? super.show(updatedQuery) : this.uc();
  }
};
var $Adc = class extends $rdc {
  async show(query) {
    const updatedQuery = toSpecificWorkspaceUnsupportedQuery(query, "untrustedPartial");
    return updatedQuery ? super.show(updatedQuery) : this.uc();
  }
};
var $Bdc = class extends $rdc {
  async show(query) {
    const updatedQuery = toSpecificWorkspaceUnsupportedQuery(query, "virtual");
    return updatedQuery ? super.show(updatedQuery) : this.uc();
  }
};
var $Cdc = class extends $rdc {
  async show(query) {
    const updatedQuery = toSpecificWorkspaceUnsupportedQuery(query, "virtualPartial");
    return updatedQuery ? super.show(updatedQuery) : this.uc();
  }
};
var $Ddc = class extends $rdc {
  async show(query) {
    return $rdc.isSearchDeprecatedExtensionsQuery(query) ? super.show(query) : this.uc();
  }
};
var $Edc = class extends $rdc {
  constructor() {
    super(...arguments);
    this.kd = this.B(new $Th(2e3));
    this.ld = Promise.resolve();
  }
  async show(query) {
    const queryPromise = super.show(query);
    this.kd.trigger(() => this.md());
    this.ld = queryPromise.then(null, null);
    return queryPromise;
  }
  async md() {
    await this.ld;
    this.Gb.publicLog2("extensionsView:MarketplaceSearchFinished");
  }
};
var $Fdc = class extends $rdc {
  constructor() {
    super(...arguments);
    this.kd = "@recommended:all";
  }
  W(container2) {
    super.W(container2);
    this.B(this.bc.onDidChangeRecommendations(() => {
      this.show("");
    }));
  }
  async show(query) {
    if (query && query.trim() !== this.kd) {
      return this.uc();
    }
    const model = await super.show(this.kd);
    if (!this.ac.local.some((e) => !e.isBuiltin)) {
      this.setExpanded(model.length > 0);
    }
    return model;
  }
};
var $Gdc = class extends $rdc {
  constructor() {
    super(...arguments);
    this.kd = "@recommended";
  }
  W(container2) {
    super.W(container2);
    this.B(this.bc.onDidChangeRecommendations(() => {
      this.show("");
    }));
  }
  async show(query) {
    return query && query.trim() !== this.kd ? this.uc() : super.show(this.kd);
  }
};
var $Hdc = class extends $rdc {
  constructor() {
    super(...arguments);
    this.kd = "@recommended:workspace";
  }
  W(container2) {
    super.W(container2);
    this.B(this.bc.onDidChangeRecommendations(() => this.show(this.kd)));
    this.B(this.cc.onDidChangeWorkbenchState(() => this.show(this.kd)));
  }
  async show(query) {
    const shouldShowEmptyView = query && query.trim() !== "@recommended" && query.trim() !== "@recommended:workspace";
    const model = await (shouldShowEmptyView ? this.uc() : super.show(this.kd));
    this.setExpanded(model.length > 0);
    return model;
  }
  async md() {
    const installed = (await this.ac.queryLocal()).filter(
      (l) => l.enablementState !== 1
      /* EnablementState.DisabledByExtensionKind */
    );
    const recommendations = (await this.Sc()).filter((recommendation) => installed.every((local) => $zg(recommendation) ? !$DA({ id: recommendation }, local.identifier) : !this.oc.extUri.isEqual(recommendation, local.local?.location)));
    return this.Rc(recommendations, { source: "install-all-workspace-recommendations" }, CancellationToken.None);
  }
  async installWorkspaceRecommendations() {
    const installableRecommendations = await this.md();
    if (installableRecommendations.length) {
      const galleryExtensions = [];
      const resourceExtensions = [];
      for (const recommendation of installableRecommendations) {
        if (recommendation.gallery) {
          galleryExtensions.push({ extension: recommendation.gallery, options: {} });
        } else {
          resourceExtensions.push(recommendation);
        }
      }
      await Promise.all([
        this.fc.installGalleryExtensions(galleryExtensions),
        ...resourceExtensions.map((extension) => this.ac.install(extension))
      ]);
    } else {
      this.ab.notify({
        severity: Severity2.Info,
        message: localize(6866, null)
      });
    }
  }
};
function $Idc(extension) {
  if (!extension) {
    return "";
  }
  const publisher = extension.publisherDomain?.verified ? localize(6867, null, extension.publisherDisplayName) : localize(6868, null, extension.publisherDisplayName);
  const deprecated = extension?.deprecationInfo ? localize(6869, null) : "";
  const rating = extension?.rating ? localize(6870, null, extension.rating.toFixed(2), extension.ratingCount) : "";
  return `${extension.displayName}, ${deprecated ? `${deprecated}, ` : ""}${extension.version}, ${publisher}, ${extension.description} ${rating ? `, ${rating}` : ""}`;
}
var $Jdc = class {
  constructor(h3, j) {
    this.h = h3;
    this.j = j;
    this.c = /* @__PURE__ */ new Map();
    this.d = /* @__PURE__ */ new Set();
    this.f = [];
    for (let i2 = 0; i2 < this.h.length; i2++) {
      this.c.set(i2, this.h[i2]);
    }
    for (const e of h3) {
      if (e.identifier.uuid) {
        this.d.add(e.identifier.uuid);
      }
    }
    this.length = h3.length - this.d.size + this.j.total;
    const totalPages = Math.ceil(this.j.total / this.j.pageSize);
    this.k(0, this.j.firstPage);
    this.g = $Ub(totalPages - 1).map(() => ({
      promise: null,
      cts: null,
      promiseIndexes: /* @__PURE__ */ new Set()
    }));
  }
  isResolved(index) {
    return this.c.has(index);
  }
  get(index) {
    return this.c.get(index);
  }
  async resolve(index, cancellationToken) {
    if (cancellationToken.isCancellationRequested) {
      throw new $lb();
    }
    if (this.isResolved(index)) {
      return this.get(index);
    }
    const indexInPagedModel = index - this.h.length + this.f.length;
    const pageIndex = Math.floor(indexInPagedModel / this.j.pageSize);
    const page = this.g[pageIndex];
    if (!page.promise) {
      page.cts = new $ad();
      page.promise = this.j.getPage(pageIndex, page.cts.token).then((extensions) => this.k(pageIndex, extensions)).catch((e) => {
        page.promise = null;
        throw e;
      }).finally(() => page.cts = null);
    }
    const listener = cancellationToken.onCancellationRequested(() => {
      if (!page.cts) {
        return;
      }
      page.promiseIndexes.delete(index);
      if (page.promiseIndexes.size === 0) {
        page.cts.cancel();
      }
    });
    page.promiseIndexes.add(index);
    try {
      await page.promise;
    } finally {
      listener.dispose();
    }
    return this.get(index);
  }
  k(pageIndex, extensions) {
    let adjustIndexOfNextPagesBy = 0;
    const pageStartIndex = pageIndex * this.j.pageSize;
    for (let i2 = 0; i2 < extensions.length; i2++) {
      const e = extensions[i2];
      if (e.gallery?.identifier.uuid && this.d.has(e.gallery.identifier.uuid)) {
        this.f.push(e);
        adjustIndexOfNextPagesBy++;
      } else {
        this.c.set(this.h.length - this.f.length + pageStartIndex + i2, e);
      }
    }
    if (pageIndex !== 0 && adjustIndexOfNextPagesBy) {
      const nextPageStartIndex = (pageIndex + 1) * this.j.pageSize;
      const indices = [...this.c.keys()].sort();
      for (const index of indices) {
        if (index >= nextPageStartIndex) {
          const e = this.c.get(index);
          if (e) {
            this.c.delete(index);
            this.c.set(index - adjustIndexOfNextPagesBy, e);
          }
        }
      }
    }
  }
};

// out-build/vs/workbench/contrib/extensions/browser/extensionsViewer.js
var ExtensionRenderer_1;
var $Kdc = class $Kdc2 extends $3c {
  constructor(parent, delegate, f) {
    super();
    this.f = f;
    this.element = $bk(parent, $(".extensions-grid-view"));
    this.a = this.f.createInstance($odc, { onFocus: Event2.None, onBlur: Event2.None, filters: {} }, { hoverOptions: { position() {
      return 2;
    } } });
    this.b = delegate;
    this.c = this.B(new $2c());
  }
  setExtensions(extensions) {
    this.c.clear();
    extensions.forEach((e, index) => this.g(e, index));
  }
  g(extension, index) {
    const extensionContainer = $bk(this.element, $(".extension-container"));
    extensionContainer.style.height = `${this.b.getHeight()}px`;
    extensionContainer.setAttribute("tabindex", "0");
    const template = this.a.renderTemplate(extensionContainer);
    this.c.add($1c(() => this.a.disposeTemplate(template)));
    const openExtensionAction = this.f.createInstance(OpenExtensionAction);
    openExtensionAction.extension = extension;
    template.name.setAttribute("tabindex", "0");
    const handleEvent = (e) => {
      if (e instanceof $if && e.keyCode !== 3) {
        return;
      }
      openExtensionAction.run(e.ctrlKey || e.metaKey);
      e.stopPropagation();
      e.preventDefault();
    };
    this.c.add($_i(template.name, $7j.CLICK, (e) => handleEvent(new $lf(getWindow(template.name), e))));
    this.c.add($_i(template.name, $7j.KEY_DOWN, (e) => handleEvent(new $if(e))));
    this.c.add($_i(extensionContainer, $7j.KEY_DOWN, (e) => handleEvent(new $if(e))));
    this.a.renderElement(extension, index, template);
  }
};
$Kdc = __decorate([
  __param(2, $Pk)
], $Kdc);
var AsyncDataSource = class {
  hasChildren({ hasChildren }) {
    return hasChildren;
  }
  getChildren(extensionData) {
    return extensionData.getChildren();
  }
};
var VirualDelegate = class {
  getHeight(element) {
    return 62;
  }
  getTemplateId({ extension }) {
    return extension ? ExtensionRenderer.TEMPLATE_ID : UnknownExtensionRenderer.TEMPLATE_ID;
  }
};
var ExtensionRenderer = class ExtensionRenderer2 {
  static {
    ExtensionRenderer_1 = this;
  }
  static {
    this.TEMPLATE_ID = "extension-template";
  }
  constructor(a) {
    this.a = a;
  }
  get templateId() {
    return ExtensionRenderer_1.TEMPLATE_ID;
  }
  renderTemplate(container2) {
    container2.classList.add("extension");
    const icon2 = $bk(container2, $("img.icon"));
    const details = $bk(container2, $(".details"));
    const header = $bk(details, $(".header"));
    const name = $bk(header, $("span.name"));
    const openExtensionAction = this.a.createInstance(OpenExtensionAction);
    const extensionDisposables = [$_i(name, "click", (e) => {
      openExtensionAction.run(e.ctrlKey || e.metaKey);
      e.stopPropagation();
      e.preventDefault();
    })];
    const identifier2 = $bk(header, $("span.identifier"));
    const footer = $bk(details, $(".footer"));
    const author = $bk(footer, $(".author"));
    return {
      icon: icon2,
      name,
      identifier: identifier2,
      author,
      extensionDisposables,
      set extensionData(extensionData) {
        openExtensionAction.extension = extensionData.extension;
      }
    };
  }
  renderElement(node, index, data) {
    const extension = node.element.extension;
    data.extensionDisposables.push($_i(data.icon, "error", () => data.icon.src = extension.iconUrlFallback, { once: true }));
    data.icon.src = extension.iconUrl;
    if (!data.icon.complete) {
      data.icon.style.visibility = "hidden";
      data.icon.onload = () => data.icon.style.visibility = "inherit";
    } else {
      data.icon.style.visibility = "inherit";
    }
    data.name.textContent = extension.displayName;
    data.identifier.textContent = extension.identifier.id;
    data.author.textContent = extension.publisherDisplayName;
    data.extensionData = node.element;
  }
  disposeTemplate(templateData) {
    templateData.extensionDisposables = $Xc(templateData.extensionDisposables);
  }
};
ExtensionRenderer = ExtensionRenderer_1 = __decorate([
  __param(0, $Pk)
], ExtensionRenderer);
var UnknownExtensionRenderer = class _UnknownExtensionRenderer {
  static {
    this.TEMPLATE_ID = "unknown-extension-template";
  }
  get templateId() {
    return _UnknownExtensionRenderer.TEMPLATE_ID;
  }
  renderTemplate(container2) {
    const messageContainer = $bk(container2, $("div.unknown-extension"));
    $bk(messageContainer, $("span.error-marker")).textContent = localize(6813, null);
    $bk(messageContainer, $("span.message")).textContent = localize(6814, null);
    const identifier2 = $bk(messageContainer, $("span.message"));
    return { identifier: identifier2 };
  }
  renderElement(node, index, data) {
    data.identifier.textContent = node.element.extension.identifier.id;
  }
  disposeTemplate(data) {
  }
};
var OpenExtensionAction = class OpenExtensionAction2 extends $Um {
  constructor(b) {
    super("extensions.action.openExtension", "");
    this.b = b;
  }
  set extension(extension) {
    this.a = extension;
  }
  run(sideByside) {
    if (this.a) {
      return this.b.open(this.a, { sideByside });
    }
    return Promise.resolve();
  }
};
OpenExtensionAction = __decorate([
  __param(0, $vzb)
], OpenExtensionAction);
var $Ldc = class $Ldc2 extends $4eb {
  constructor(input, container2, overrideStyles2, contextKeyService, listService, instantiationService, configurationService, extensionsWorkdbenchService) {
    const delegate = new VirualDelegate();
    const dataSource = new AsyncDataSource();
    const renderers = [instantiationService.createInstance(ExtensionRenderer), instantiationService.createInstance(UnknownExtensionRenderer)];
    const identityProvider3 = {
      getId({ extension, parent }) {
        return parent ? this.getId(parent) + "/" + extension.identifier.id : extension.identifier.id;
      }
    };
    super("ExtensionsTree", container2, delegate, renderers, dataSource, {
      indent: 40,
      identityProvider: identityProvider3,
      multipleSelectionSupport: false,
      overrideStyles: overrideStyles2,
      accessibilityProvider: {
        getAriaLabel(extensionData) {
          return $Idc(extensionData.extension);
        },
        getWidgetAriaLabel() {
          return localize(6815, null);
        }
      }
    }, instantiationService, contextKeyService, listService, configurationService);
    this.setInput(input);
    this.w.add(this.onDidChangeSelection((event) => {
      if ($4j(event.browserEvent)) {
        extensionsWorkdbenchService.open(event.elements[0].extension, { sideByside: false });
      }
    }));
  }
};
$Ldc = __decorate([
  __param(3, $on),
  __param(4, $Deb),
  __param(5, $Pk),
  __param(6, $kl),
  __param(7, $vzb)
], $Ldc);
var $Mdc = class _$Mdc {
  constructor(extension, parent, getChildrenExtensionIds, extensionsWorkbenchService) {
    this.extension = extension;
    this.parent = parent;
    this.a = getChildrenExtensionIds;
    this.c = extensionsWorkbenchService;
    this.b = this.a(extension);
  }
  get hasChildren() {
    return $Qb(this.b);
  }
  async getChildren() {
    if (this.hasChildren) {
      const result = await $Ndc(this.b, this.c);
      return result.map((extension) => new _$Mdc(extension, this, this.a, this.c));
    }
    return null;
  }
};
async function $Ndc(extensions, extensionsWorkbenchService) {
  const localById = extensionsWorkbenchService.local.reduce((result2, e) => {
    result2.set(e.identifier.id.toLowerCase(), e);
    return result2;
  }, /* @__PURE__ */ new Map());
  const result = [];
  const toQuery = [];
  for (const extensionId of extensions) {
    const id2 = extensionId.toLowerCase();
    const local = localById.get(id2);
    if (local) {
      result.push(local);
    } else {
      toQuery.push(id2);
    }
  }
  if (toQuery.length) {
    const galleryResult = await extensionsWorkbenchService.getExtensions(toQuery.map((id2) => ({ id: id2 })), CancellationToken.None);
    result.push(...galleryResult);
  }
  return result;
}
$ms((theme, collector) => {
  const focusBackground = theme.getColor($er);
  if (focusBackground) {
    collector.addRule(`.extensions-grid-view .extension-container:focus { background-color: ${focusBackground}; outline: none; }`);
  }
  const focusForeground = theme.getColor($fr);
  if (focusForeground) {
    collector.addRule(`.extensions-grid-view .extension-container:focus { color: ${focusForeground}; }`);
  }
  const foregroundColor = theme.getColor($eo);
  const editorBackgroundColor = theme.getColor($Ko);
  if (foregroundColor && editorBackgroundColor) {
    const authorForeground = foregroundColor.transparent(0.9).makeOpaque(editorBackgroundColor);
    collector.addRule(`.extensions-grid-view .extension-container:not(.disabled) .author { color: ${authorForeground}; }`);
    const disabledExtensionForeground = foregroundColor.transparent(0.5).makeOpaque(editorBackgroundColor);
    collector.addRule(`.extensions-grid-view .extension-container.disabled { color: ${disabledExtensionForeground}; }`);
  }
});

// out-build/vs/workbench/contrib/markdown/browser/markedGfmHeadingIdPlugin.js
var githubSlugReplaceRegex = /[\0-\x1F!-,\.\/:-@\[-\^`\{-\xA9\xAB-\xB4\xB6-\xB9\xBB-\xBF\xD7\xF7\u02C2-\u02C5\u02D2-\u02DF\u02E5-\u02EB\u02ED\u02EF-\u02FF\u0375\u0378\u0379\u037E\u0380-\u0385\u0387\u038B\u038D\u03A2\u03F6\u0482\u0530\u0557\u0558\u055A-\u055F\u0589-\u0590\u05BE\u05C0\u05C3\u05C6\u05C8-\u05CF\u05EB-\u05EE\u05F3-\u060F\u061B-\u061F\u066A-\u066D\u06D4\u06DD\u06DE\u06E9\u06FD\u06FE\u0700-\u070F\u074B\u074C\u07B2-\u07BF\u07F6-\u07F9\u07FB\u07FC\u07FE\u07FF\u082E-\u083F\u085C-\u085F\u086B-\u089F\u08B5\u08C8-\u08D2\u08E2\u0964\u0965\u0970\u0984\u098D\u098E\u0991\u0992\u09A9\u09B1\u09B3-\u09B5\u09BA\u09BB\u09C5\u09C6\u09C9\u09CA\u09CF-\u09D6\u09D8-\u09DB\u09DE\u09E4\u09E5\u09F2-\u09FB\u09FD\u09FF\u0A00\u0A04\u0A0B-\u0A0E\u0A11\u0A12\u0A29\u0A31\u0A34\u0A37\u0A3A\u0A3B\u0A3D\u0A43-\u0A46\u0A49\u0A4A\u0A4E-\u0A50\u0A52-\u0A58\u0A5D\u0A5F-\u0A65\u0A76-\u0A80\u0A84\u0A8E\u0A92\u0AA9\u0AB1\u0AB4\u0ABA\u0ABB\u0AC6\u0ACA\u0ACE\u0ACF\u0AD1-\u0ADF\u0AE4\u0AE5\u0AF0-\u0AF8\u0B00\u0B04\u0B0D\u0B0E\u0B11\u0B12\u0B29\u0B31\u0B34\u0B3A\u0B3B\u0B45\u0B46\u0B49\u0B4A\u0B4E-\u0B54\u0B58-\u0B5B\u0B5E\u0B64\u0B65\u0B70\u0B72-\u0B81\u0B84\u0B8B-\u0B8D\u0B91\u0B96-\u0B98\u0B9B\u0B9D\u0BA0-\u0BA2\u0BA5-\u0BA7\u0BAB-\u0BAD\u0BBA-\u0BBD\u0BC3-\u0BC5\u0BC9\u0BCE\u0BCF\u0BD1-\u0BD6\u0BD8-\u0BE5\u0BF0-\u0BFF\u0C0D\u0C11\u0C29\u0C3A-\u0C3C\u0C45\u0C49\u0C4E-\u0C54\u0C57\u0C5B-\u0C5F\u0C64\u0C65\u0C70-\u0C7F\u0C84\u0C8D\u0C91\u0CA9\u0CB4\u0CBA\u0CBB\u0CC5\u0CC9\u0CCE-\u0CD4\u0CD7-\u0CDD\u0CDF\u0CE4\u0CE5\u0CF0\u0CF3-\u0CFF\u0D0D\u0D11\u0D45\u0D49\u0D4F-\u0D53\u0D58-\u0D5E\u0D64\u0D65\u0D70-\u0D79\u0D80\u0D84\u0D97-\u0D99\u0DB2\u0DBC\u0DBE\u0DBF\u0DC7-\u0DC9\u0DCB-\u0DCE\u0DD5\u0DD7\u0DE0-\u0DE5\u0DF0\u0DF1\u0DF4-\u0E00\u0E3B-\u0E3F\u0E4F\u0E5A-\u0E80\u0E83\u0E85\u0E8B\u0EA4\u0EA6\u0EBE\u0EBF\u0EC5\u0EC7\u0ECE\u0ECF\u0EDA\u0EDB\u0EE0-\u0EFF\u0F01-\u0F17\u0F1A-\u0F1F\u0F2A-\u0F34\u0F36\u0F38\u0F3A-\u0F3D\u0F48\u0F6D-\u0F70\u0F85\u0F98\u0FBD-\u0FC5\u0FC7-\u0FFF\u104A-\u104F\u109E\u109F\u10C6\u10C8-\u10CC\u10CE\u10CF\u10FB\u1249\u124E\u124F\u1257\u1259\u125E\u125F\u1289\u128E\u128F\u12B1\u12B6\u12B7\u12BF\u12C1\u12C6\u12C7\u12D7\u1311\u1316\u1317\u135B\u135C\u1360-\u137F\u1390-\u139F\u13F6\u13F7\u13FE-\u1400\u166D\u166E\u1680\u169B-\u169F\u16EB-\u16ED\u16F9-\u16FF\u170D\u1715-\u171F\u1735-\u173F\u1754-\u175F\u176D\u1771\u1774-\u177F\u17D4-\u17D6\u17D8-\u17DB\u17DE\u17DF\u17EA-\u180A\u180E\u180F\u181A-\u181F\u1879-\u187F\u18AB-\u18AF\u18F6-\u18FF\u191F\u192C-\u192F\u193C-\u1945\u196E\u196F\u1975-\u197F\u19AC-\u19AF\u19CA-\u19CF\u19DA-\u19FF\u1A1C-\u1A1F\u1A5F\u1A7D\u1A7E\u1A8A-\u1A8F\u1A9A-\u1AA6\u1AA8-\u1AAF\u1AC1-\u1AFF\u1B4C-\u1B4F\u1B5A-\u1B6A\u1B74-\u1B7F\u1BF4-\u1BFF\u1C38-\u1C3F\u1C4A-\u1C4C\u1C7E\u1C7F\u1C89-\u1C8F\u1CBB\u1CBC\u1CC0-\u1CCF\u1CD3\u1CFB-\u1CFF\u1DFA\u1F16\u1F17\u1F1E\u1F1F\u1F46\u1F47\u1F4E\u1F4F\u1F58\u1F5A\u1F5C\u1F5E\u1F7E\u1F7F\u1FB5\u1FBD\u1FBF-\u1FC1\u1FC5\u1FCD-\u1FCF\u1FD4\u1FD5\u1FDC-\u1FDF\u1FED-\u1FF1\u1FF5\u1FFD-\u203E\u2041-\u2053\u2055-\u2070\u2072-\u207E\u2080-\u208F\u209D-\u20CF\u20F1-\u2101\u2103-\u2106\u2108\u2109\u2114\u2116-\u2118\u211E-\u2123\u2125\u2127\u2129\u212E\u213A\u213B\u2140-\u2144\u214A-\u214D\u214F-\u215F\u2189-\u24B5\u24EA-\u2BFF\u2C2F\u2C5F\u2CE5-\u2CEA\u2CF4-\u2CFF\u2D26\u2D28-\u2D2C\u2D2E\u2D2F\u2D68-\u2D6E\u2D70-\u2D7E\u2D97-\u2D9F\u2DA7\u2DAF\u2DB7\u2DBF\u2DC7\u2DCF\u2DD7\u2DDF\u2E00-\u2E2E\u2E30-\u3004\u3008-\u3020\u3030\u3036\u3037\u303D-\u3040\u3097\u3098\u309B\u309C\u30A0\u30FB\u3100-\u3104\u3130\u318F-\u319F\u31C0-\u31EF\u3200-\u33FF\u4DC0-\u4DFF\u9FFD-\u9FFF\uA48D-\uA4CF\uA4FE\uA4FF\uA60D-\uA60F\uA62C-\uA63F\uA673\uA67E\uA6F2-\uA716\uA720\uA721\uA789\uA78A\uA7C0\uA7C1\uA7CB-\uA7F4\uA828-\uA82B\uA82D-\uA83F\uA874-\uA87F\uA8C6-\uA8CF\uA8DA-\uA8DF\uA8F8-\uA8FA\uA8FC\uA92E\uA92F\uA954-\uA95F\uA97D-\uA97F\uA9C1-\uA9CE\uA9DA-\uA9DF\uA9FF\uAA37-\uAA3F\uAA4E\uAA4F\uAA5A-\uAA5F\uAA77-\uAA79\uAAC3-\uAADA\uAADE\uAADF\uAAF0\uAAF1\uAAF7-\uAB00\uAB07\uAB08\uAB0F\uAB10\uAB17-\uAB1F\uAB27\uAB2F\uAB5B\uAB6A-\uAB6F\uABEB\uABEE\uABEF\uABFA-\uABFF\uD7A4-\uD7AF\uD7C7-\uD7CA\uD7FC-\uD7FF\uE000-\uF8FF\uFA6E\uFA6F\uFADA-\uFAFF\uFB07-\uFB12\uFB18-\uFB1C\uFB29\uFB37\uFB3D\uFB3F\uFB42\uFB45\uFBB2-\uFBD2\uFD3E-\uFD4F\uFD90\uFD91\uFDC8-\uFDEF\uFDFC-\uFDFF\uFE10-\uFE1F\uFE30-\uFE32\uFE35-\uFE4C\uFE50-\uFE6F\uFE75\uFEFD-\uFF0F\uFF1A-\uFF20\uFF3B-\uFF3E\uFF40\uFF5B-\uFF65\uFFBF-\uFFC1\uFFC8\uFFC9\uFFD0\uFFD1\uFFD8\uFFD9\uFFDD-\uFFFF]|\uD800[\uDC0C\uDC27\uDC3B\uDC3E\uDC4E\uDC4F\uDC5E-\uDC7F\uDCFB-\uDD3F\uDD75-\uDDFC\uDDFE-\uDE7F\uDE9D-\uDE9F\uDED1-\uDEDF\uDEE1-\uDEFF\uDF20-\uDF2C\uDF4B-\uDF4F\uDF7B-\uDF7F\uDF9E\uDF9F\uDFC4-\uDFC7\uDFD0\uDFD6-\uDFFF]|\uD801[\uDC9E\uDC9F\uDCAA-\uDCAF\uDCD4-\uDCD7\uDCFC-\uDCFF\uDD28-\uDD2F\uDD64-\uDDFF\uDF37-\uDF3F\uDF56-\uDF5F\uDF68-\uDFFF]|\uD802[\uDC06\uDC07\uDC09\uDC36\uDC39-\uDC3B\uDC3D\uDC3E\uDC56-\uDC5F\uDC77-\uDC7F\uDC9F-\uDCDF\uDCF3\uDCF6-\uDCFF\uDD16-\uDD1F\uDD3A-\uDD7F\uDDB8-\uDDBD\uDDC0-\uDDFF\uDE04\uDE07-\uDE0B\uDE14\uDE18\uDE36\uDE37\uDE3B-\uDE3E\uDE40-\uDE5F\uDE7D-\uDE7F\uDE9D-\uDEBF\uDEC8\uDEE7-\uDEFF\uDF36-\uDF3F\uDF56-\uDF5F\uDF73-\uDF7F\uDF92-\uDFFF]|\uD803[\uDC49-\uDC7F\uDCB3-\uDCBF\uDCF3-\uDCFF\uDD28-\uDD2F\uDD3A-\uDE7F\uDEAA\uDEAD-\uDEAF\uDEB2-\uDEFF\uDF1D-\uDF26\uDF28-\uDF2F\uDF51-\uDFAF\uDFC5-\uDFDF\uDFF7-\uDFFF]|\uD804[\uDC47-\uDC65\uDC70-\uDC7E\uDCBB-\uDCCF\uDCE9-\uDCEF\uDCFA-\uDCFF\uDD35\uDD40-\uDD43\uDD48-\uDD4F\uDD74\uDD75\uDD77-\uDD7F\uDDC5-\uDDC8\uDDCD\uDDDB\uDDDD-\uDDFF\uDE12\uDE38-\uDE3D\uDE3F-\uDE7F\uDE87\uDE89\uDE8E\uDE9E\uDEA9-\uDEAF\uDEEB-\uDEEF\uDEFA-\uDEFF\uDF04\uDF0D\uDF0E\uDF11\uDF12\uDF29\uDF31\uDF34\uDF3A\uDF45\uDF46\uDF49\uDF4A\uDF4E\uDF4F\uDF51-\uDF56\uDF58-\uDF5C\uDF64\uDF65\uDF6D-\uDF6F\uDF75-\uDFFF]|\uD805[\uDC4B-\uDC4F\uDC5A-\uDC5D\uDC62-\uDC7F\uDCC6\uDCC8-\uDCCF\uDCDA-\uDD7F\uDDB6\uDDB7\uDDC1-\uDDD7\uDDDE-\uDDFF\uDE41-\uDE43\uDE45-\uDE4F\uDE5A-\uDE7F\uDEB9-\uDEBF\uDECA-\uDEFF\uDF1B\uDF1C\uDF2C-\uDF2F\uDF3A-\uDFFF]|\uD806[\uDC3B-\uDC9F\uDCEA-\uDCFE\uDD07\uDD08\uDD0A\uDD0B\uDD14\uDD17\uDD36\uDD39\uDD3A\uDD44-\uDD4F\uDD5A-\uDD9F\uDDA8\uDDA9\uDDD8\uDDD9\uDDE2\uDDE5-\uDDFF\uDE3F-\uDE46\uDE48-\uDE4F\uDE9A-\uDE9C\uDE9E-\uDEBF\uDEF9-\uDFFF]|\uD807[\uDC09\uDC37\uDC41-\uDC4F\uDC5A-\uDC71\uDC90\uDC91\uDCA8\uDCB7-\uDCFF\uDD07\uDD0A\uDD37-\uDD39\uDD3B\uDD3E\uDD48-\uDD4F\uDD5A-\uDD5F\uDD66\uDD69\uDD8F\uDD92\uDD99-\uDD9F\uDDAA-\uDEDF\uDEF7-\uDFAF\uDFB1-\uDFFF]|\uD808[\uDF9A-\uDFFF]|\uD809[\uDC6F-\uDC7F\uDD44-\uDFFF]|[\uD80A\uD80B\uD80E-\uD810\uD812-\uD819\uD824-\uD82B\uD82D\uD82E\uD830-\uD833\uD837\uD839\uD83D\uD83F\uD87B-\uD87D\uD87F\uD885-\uDB3F\uDB41-\uDBFF][\uDC00-\uDFFF]|\uD80D[\uDC2F-\uDFFF]|\uD811[\uDE47-\uDFFF]|\uD81A[\uDE39-\uDE3F\uDE5F\uDE6A-\uDECF\uDEEE\uDEEF\uDEF5-\uDEFF\uDF37-\uDF3F\uDF44-\uDF4F\uDF5A-\uDF62\uDF78-\uDF7C\uDF90-\uDFFF]|\uD81B[\uDC00-\uDE3F\uDE80-\uDEFF\uDF4B-\uDF4E\uDF88-\uDF8E\uDFA0-\uDFDF\uDFE2\uDFE5-\uDFEF\uDFF2-\uDFFF]|\uD821[\uDFF8-\uDFFF]|\uD823[\uDCD6-\uDCFF\uDD09-\uDFFF]|\uD82C[\uDD1F-\uDD4F\uDD53-\uDD63\uDD68-\uDD6F\uDEFC-\uDFFF]|\uD82F[\uDC6B-\uDC6F\uDC7D-\uDC7F\uDC89-\uDC8F\uDC9A-\uDC9C\uDC9F-\uDFFF]|\uD834[\uDC00-\uDD64\uDD6A-\uDD6C\uDD73-\uDD7A\uDD83\uDD84\uDD8C-\uDDA9\uDDAE-\uDE41\uDE45-\uDFFF]|\uD835[\uDC55\uDC9D\uDCA0\uDCA1\uDCA3\uDCA4\uDCA7\uDCA8\uDCAD\uDCBA\uDCBC\uDCC4\uDD06\uDD0B\uDD0C\uDD15\uDD1D\uDD3A\uDD3F\uDD45\uDD47-\uDD49\uDD51\uDEA6\uDEA7\uDEC1\uDEDB\uDEFB\uDF15\uDF35\uDF4F\uDF6F\uDF89\uDFA9\uDFC3\uDFCC\uDFCD]|\uD836[\uDC00-\uDDFF\uDE37-\uDE3A\uDE6D-\uDE74\uDE76-\uDE83\uDE85-\uDE9A\uDEA0\uDEB0-\uDFFF]|\uD838[\uDC07\uDC19\uDC1A\uDC22\uDC25\uDC2B-\uDCFF\uDD2D-\uDD2F\uDD3E\uDD3F\uDD4A-\uDD4D\uDD4F-\uDEBF\uDEFA-\uDFFF]|\uD83A[\uDCC5-\uDCCF\uDCD7-\uDCFF\uDD4C-\uDD4F\uDD5A-\uDFFF]|\uD83B[\uDC00-\uDDFF\uDE04\uDE20\uDE23\uDE25\uDE26\uDE28\uDE33\uDE38\uDE3A\uDE3C-\uDE41\uDE43-\uDE46\uDE48\uDE4A\uDE4C\uDE50\uDE53\uDE55\uDE56\uDE58\uDE5A\uDE5C\uDE5E\uDE60\uDE63\uDE65\uDE66\uDE6B\uDE73\uDE78\uDE7D\uDE7F\uDE8A\uDE9C-\uDEA0\uDEA4\uDEAA\uDEBC-\uDFFF]|\uD83C[\uDC00-\uDD2F\uDD4A-\uDD4F\uDD6A-\uDD6F\uDD8A-\uDFFF]|\uD83E[\uDC00-\uDFEF\uDFFA-\uDFFF]|\uD869[\uDEDE-\uDEFF]|\uD86D[\uDF35-\uDF3F]|\uD86E[\uDC1E\uDC1F]|\uD873[\uDEA2-\uDEAF]|\uD87A[\uDFE1-\uDFFF]|\uD87E[\uDE1E-\uDFFF]|\uD884[\uDF4B-\uDFFF]|\uDB40[\uDC00-\uDCFF\uDDF0-\uDFFF]/g;
function slugify(heading2) {
  const slugifiedHeading = heading2.trim().toLowerCase().replace(githubSlugReplaceRegex, "").replace(/\s/g, "-");
  return slugifiedHeading;
}
var unescapeTest = /&(#(?:\d+)|(?:#x[0-9A-Fa-f]+)|(?:\w+));?/ig;
function unescape(html3) {
  return html3.replace(unescapeTest, (_, n) => {
    n = n.toLowerCase();
    if (n === "colon") {
      return ":";
    }
    if (n.charAt(0) === "#") {
      return n.charAt(1) === "x" ? String.fromCharCode(parseInt(n.substring(2), 16)) : String.fromCharCode(+n.substring(1));
    }
    return "";
  });
}
function $Odc({ prefix = "", globalSlugs = false } = {}) {
  return {
    // hooks: {
    // 	preprocess(src: string) {
    // 		if (!globalSlugs) {
    // 			resetHeadings();
    // 		}
    // 		return src;
    // 	},
    // },
    renderer: {
      heading({ tokens, depth }) {
        const text2 = this.parser.parseInline(tokens);
        const raw = unescape(this.parser.parseInline(tokens, this.parser.textRenderer)).trim().replace(/<[!\/a-z].*?>/gi, "");
        const level = depth;
        const id2 = `${prefix}${slugify(raw)}`;
        return `<h${level} id="${id2}">${text2}</h${level}>
`;
      }
    }
  };
}

// out-build/vs/workbench/contrib/markdown/browser/markdownDocumentRenderer.js
var $Pdc = `
body {
	padding: 10px 20px;
	line-height: 22px;
	max-width: 882px;
	margin: 0 auto;
}

body *:last-child {
	margin-bottom: 0;
}

img {
	max-width: 100%;
	max-height: 100%;
}

a {
	text-decoration: var(--text-link-decoration);
}

a:hover {
	text-decoration: underline;
}

a:focus,
input:focus,
select:focus,
textarea:focus {
	outline: 1px solid -webkit-focus-ring-color;
	outline-offset: -1px;
}

hr {
	border: 0;
	height: 2px;
	border-bottom: 2px solid;
}

h1 {
	padding-bottom: 0.3em;
	line-height: 1.2;
	border-bottom-width: 1px;
	border-bottom-style: solid;
}

h1, h2, h3 {
	font-weight: normal;
}

table {
	border-collapse: collapse;
}

th {
	text-align: left;
	border-bottom: 1px solid;
}

th,
td {
	padding: 5px 10px;
}

table > tbody > tr + tr > td {
	border-top-width: 1px;
	border-top-style: solid;
}

blockquote {
	margin: 0 7px 0 5px;
	padding: 0 16px 0 10px;
	border-left-width: 5px;
	border-left-style: solid;
}

code {
	font-family: "SF Mono", Monaco, Menlo, Consolas, "Ubuntu Mono", "Liberation Mono", "DejaVu Sans Mono", "Courier New", monospace;
}

pre {
	padding: 16px;
	border-radius: 3px;
	overflow: auto;
}

pre code {
	font-family: var(--vscode-editor-font-family);
	font-weight: var(--vscode-editor-font-weight);
	font-size: var(--vscode-editor-font-size);
	line-height: 1.5;
	color: var(--vscode-editor-foreground);
	tab-size: 4;
}

.monaco-tokenized-source {
	white-space: pre;
}

/** Theming */

.pre {
	background-color: var(--vscode-textCodeBlock-background);
}

.vscode-high-contrast h1 {
	border-color: rgb(0, 0, 0);
}

.vscode-light th {
	border-color: rgba(0, 0, 0, 0.69);
}

.vscode-dark th {
	border-color: rgba(255, 255, 255, 0.69);
}

.vscode-light h1,
.vscode-light hr,
.vscode-light td {
	border-color: rgba(0, 0, 0, 0.18);
}

.vscode-dark h1,
.vscode-dark hr,
.vscode-dark td {
	border-color: rgba(255, 255, 255, 0.18);
}

@media (forced-colors: active) and (prefers-color-scheme: light){
	body {
		forced-color-adjust: none;
	}
}

@media (forced-colors: active) and (prefers-color-scheme: dark){
	body {
		forced-color-adjust: none;
	}
}
`;
var allowedProtocols = [Schemas.http, Schemas.https, Schemas.command];
function sanitize(documentContent, allowUnknownProtocols) {
  const hook = $uk(allowedProtocols, true);
  try {
    return purify.sanitize(documentContent, {
      ...{
        ALLOWED_TAGS: [
          ...$vk,
          "checkbox",
          "checklist"
        ],
        ALLOWED_ATTR: [
          ...$E1,
          "data-command",
          "name",
          "id",
          "role",
          "tabindex",
          "x-dispatch",
          "required",
          "checked",
          "placeholder",
          "when-checked",
          "checked-on"
        ]
      },
      ...allowUnknownProtocols ? { ALLOW_UNKNOWN_PROTOCOLS: true } : {}
    });
  } finally {
    hook.dispose();
  }
}
async function $Qdc(text2, extensionService, languageService, options3) {
  const m = new Marked(MarkedHighlight.markedHighlight({
    async: true,
    async highlight(code, lang) {
      if (typeof lang !== "string") {
        return $zf(code);
      }
      await extensionService.whenInstalledExtensionsRegistered();
      if (options3?.token?.isCancellationRequested) {
        return "";
      }
      const languageId = languageService.getLanguageIdByLanguageName(lang) ?? languageService.getLanguageIdByLanguageName(lang.split(/\s+|:|,|(?!^)\{|\?]/, 1)[0]);
      return $o9(languageService, code, languageId);
    }
  }), $Odc(), ...options3?.markedExtensions ?? []);
  const raw = await m.parse(text2, { async: true });
  if (options3?.shouldSanitize ?? true) {
    return sanitize(raw, options3?.allowUnknownProtocols ?? false);
  } else {
    return raw;
  }
}
var MarkedHighlight;
(function(MarkedHighlight2) {
  function markedHighlight(options3) {
    if (typeof options3 === "function") {
      options3 = {
        highlight: options3
      };
    }
    if (!options3 || typeof options3.highlight !== "function") {
      throw new Error("Must provide highlight function");
    }
    return {
      async: !!options3.async,
      walkTokens(token) {
        if (token.type !== "code") {
          return;
        }
        const lang = getLang(token.lang);
        if (options3.async) {
          return Promise.resolve(options3.highlight(token.text, lang, token.lang || "")).then(updateToken(token));
        }
        const code = options3.highlight(token.text, lang, token.lang || "");
        if (code instanceof Promise) {
          throw new Error("markedHighlight is not set to async but the highlight function is async. Set the async option to true on markedHighlight to await the async highlight function.");
        }
        updateToken(token)(code);
      },
      renderer: {
        code({ text: text2, lang, escaped }) {
          const classAttr = lang ? ` class="language-${escape2(lang)}"` : "";
          text2 = text2.replace(/\n$/, "");
          return `<pre><code${classAttr}>${escaped ? text2 : escape2(text2, true)}
</code></pre>`;
        }
      }
    };
  }
  MarkedHighlight2.markedHighlight = markedHighlight;
  function getLang(lang) {
    return (lang || "").match(/\S*/)[0];
  }
  function updateToken(token) {
    return (code) => {
      if (typeof code === "string" && code !== token.text) {
        token.escaped = true;
        token.text = code;
      }
    };
  }
  const escapeTest2 = /[&<>"']/;
  const escapeReplace2 = new RegExp(escapeTest2.source, "g");
  const escapeTestNoEncode2 = /[<>"']|&(?!(#\d{1,7}|#[Xx][a-fA-F0-9]{1,6}|\w+);)/;
  const escapeReplaceNoEncode2 = new RegExp(escapeTestNoEncode2.source, "g");
  const escapeReplacement = {
    "&": "&amp;",
    "<": "&lt;",
    ">": "&gt;",
    '"': "&quot;",
    [`'`]: "&#39;"
  };
  const getEscapeReplacement2 = (ch) => escapeReplacement[ch];
  function escape2(html3, encode) {
    if (encode) {
      if (escapeTest2.test(html3)) {
        return html3.replace(escapeReplace2, getEscapeReplacement2);
      }
    } else {
      if (escapeTestNoEncode2.test(html3)) {
        return html3.replace(escapeReplaceNoEncode2, getEscapeReplacement2);
      }
    }
    return html3;
  }
})(MarkedHighlight || (MarkedHighlight = {}));

// out-build/vs/workbench/contrib/extensions/browser/extensionEditor.js
var $Rdc_1;
function toDateString(date) {
  return `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, "0")}-${String(date.getDate()).padStart(2, "0")}, ${date.toLocaleTimeString($z, { hourCycle: "h23" })}`;
}
function toMemoryString(bytes) {
  if (bytes < 1024) {
    return `${bytes} B`;
  }
  if (bytes < 1024 * 1024) {
    return `${(bytes / 1024).toFixed(1)} KB`;
  }
  if (bytes < 1024 * 1024 * 1024) {
    return `${(bytes / 1024 / 1024).toFixed(1)} MB`;
  }
  return `${(bytes / 1024 / 1024 / 1024).toFixed(1)} GB`;
}
var NavBar = class extends $3c {
  get onChange() {
    return this.b.event;
  }
  get currentId() {
    return this.c;
  }
  constructor(container2) {
    super();
    this.b = this.B(new $ze());
    this.c = null;
    const element = $bk(container2, $(".navbar"));
    this.f = [];
    this.g = this.B(new $LZ(element));
  }
  push(id2, label3, tooltip) {
    const action = new $Um(id2, label3, void 0, true, () => this.h(id2, true));
    action.tooltip = tooltip;
    this.f.push(action);
    this.g.push(action);
    if (this.f.length === 1) {
      this.h(id2);
    }
  }
  clear() {
    this.f = $Xc(this.f);
    this.g.clear();
  }
  switch(id2) {
    const action = this.f.find((action2) => action2.id === id2);
    if (action) {
      action.run();
      return true;
    }
    return false;
  }
  h(id2, focus) {
    this.c = id2;
    this.b.fire({ id: id2, focus: !!focus });
    this.f.forEach((a) => a.checked = a.id === id2);
  }
};
var WebviewIndex;
(function(WebviewIndex2) {
  WebviewIndex2[WebviewIndex2["Readme"] = 0] = "Readme";
  WebviewIndex2[WebviewIndex2["Changelog"] = 1] = "Changelog";
})(WebviewIndex || (WebviewIndex = {}));
var CONTEXT_SHOW_PRE_RELEASE_VERSION = new $nn("showPreReleaseVersion", false);
var ExtensionWithDifferentGalleryVersionWidget = class extends $7cc {
  constructor() {
    super(...arguments);
    this.c = null;
  }
  get gallery() {
    return this.c;
  }
  set gallery(gallery) {
    if (this.extension && gallery && !$DA(this.extension.identifier, gallery.identifier)) {
      return;
    }
    this.c = gallery;
    this.update();
  }
};
var VersionWidget = class extends ExtensionWithDifferentGalleryVersionWidget {
  constructor(container2, hoverService) {
    super();
    this.f = $bk(container2, $("code.version", void 0, "pre-release"));
    this.B(hoverService.setupManagedHover($JZ("mouse"), this.f, localize(6357, null)));
    this.render();
  }
  render() {
    if (this.extension?.preRelease) {
      $hk(this.f);
    } else {
      $ik(this.f);
    }
  }
};
var $Rdc = class $Rdc2 extends $5tb {
  static {
    $Rdc_1 = this;
  }
  static {
    this.ID = "workbench.editor.extension";
  }
  constructor(group2, telemetryService, gb, hb, ib, themeService, jb, kb, lb, storageService, mb, nb, ob, pb, qb, rb, sb, tb, ub, vb, wb, xb, yb) {
    super($Rdc_1.ID, group2, telemetryService, themeService, storageService);
    this.gb = gb;
    this.hb = hb;
    this.ib = ib;
    this.jb = jb;
    this.kb = kb;
    this.lb = lb;
    this.mb = mb;
    this.nb = nb;
    this.ob = ob;
    this.pb = pb;
    this.qb = qb;
    this.rb = rb;
    this.sb = sb;
    this.tb = tb;
    this.ub = ub;
    this.vb = vb;
    this.wb = wb;
    this.xb = xb;
    this.yb = yb;
    this.b = this.B(new $4c());
    this.m = /* @__PURE__ */ new Map();
    this.r = "";
    this.s = [];
    this.u = this.B(new $2c());
    this.cb = this.B(new $2c());
    this.db = null;
    this.f = null;
    this.g = null;
    this.j = null;
  }
  get scopedContextKeyService() {
    return this.b.value;
  }
  Y(parent) {
    const root = $bk(parent, $(".extension-editor"));
    this.b.value = this.qb.createScoped(root);
    this.b.value.createKey("inExtensionEditor", true);
    this.fb = CONTEXT_SHOW_PRE_RELEASE_VERSION.bindTo(this.b.value);
    root.tabIndex = 0;
    root.style.outline = "none";
    root.setAttribute("role", "document");
    const header = $bk(root, $(".header"));
    const iconContainer = $bk(header, $(".icon-container"));
    const icon2 = $bk(iconContainer, $("img.icon", { draggable: false, alt: "" }));
    const remoteBadge = this.gb.createInstance($cdc, iconContainer, true);
    const details = $bk(header, $(".details"));
    const title = $bk(details, $(".title"));
    const name = $bk(title, $("span.name.clickable", { role: "heading", tabIndex: 0 }));
    this.B(this.vb.setupManagedHover($JZ("mouse"), name, localize(6358, null)));
    const versionWidget = new VersionWidget(title, this.vb);
    const preview = $bk(title, $("span.preview"));
    this.B(this.vb.setupManagedHover($JZ("mouse"), preview, localize(6359, null)));
    preview.textContent = localize(6360, null);
    const builtin = $bk(title, $("span.builtin"));
    builtin.textContent = localize(6361, null);
    const subtitle = $bk(details, $(".subtitle"));
    const publisher = $bk($bk(subtitle, $(".subtitle-entry")), $(".publisher.clickable", { tabIndex: 0 }));
    publisher.setAttribute("role", "button");
    const publisherDisplayName = $bk(publisher, $(".publisher-name"));
    const verifiedPublisherWidget = this.gb.createInstance($$cc, $bk(publisher, $(".verified-publisher")), false);
    const resource = $bk($bk(subtitle, $(".subtitle-entry.resource")), $("", { tabIndex: 0 }));
    resource.setAttribute("role", "button");
    const installCount = $bk($bk(subtitle, $(".subtitle-entry")), $("span.install", { tabIndex: 0 }));
    this.B(this.vb.setupManagedHover($JZ("mouse"), installCount, localize(6362, null)));
    const installCountWidget = this.gb.createInstance($9cc, installCount, false);
    const rating = $bk($bk(subtitle, $(".subtitle-entry")), $("span.rating.clickable", { tabIndex: 0 }));
    this.B(this.vb.setupManagedHover($JZ("mouse"), rating, localize(6363, null)));
    rating.setAttribute("role", "link");
    const ratingsWidget = this.gb.createInstance($0cc, rating, false);
    const sponsorWidget = this.gb.createInstance($_cc, $bk(subtitle, $(".subtitle-entry")));
    const widgets2 = [
      remoteBadge,
      versionWidget,
      verifiedPublisherWidget,
      installCountWidget,
      ratingsWidget,
      sponsorWidget
    ];
    const description = $bk(details, $(".description"));
    const installAction = this.gb.createInstance($YCb);
    const actions = [
      this.gb.createInstance($lDb),
      this.gb.createInstance($yDb),
      this.gb.createInstance($6Cb, true),
      this.gb.createInstance($mDb),
      this.gb.createInstance($nDb),
      this.gb.createInstance($oDb),
      this.gb.createInstance($pDb),
      this.gb.createInstance($qDb),
      this.gb.createInstance($jDb),
      this.gb.createInstance($kDb),
      this.gb.createInstance($2Cb, false),
      this.gb.createInstance($3Cb),
      this.gb.createInstance($4Cb),
      installAction,
      this.gb.createInstance($ZCb),
      this.gb.createInstance($VCb, "extensions.uninstall", $5Cb.UninstallClass, [
        [
          this.gb.createInstance($9Cb, false),
          this.gb.createInstance($5Cb),
          this.gb.createInstance($eDb, null, true)
        ]
      ]),
      this.gb.createInstance($dDb),
      this.gb.createInstance($7Cb),
      new $bDb(this.scopedContextKeyService || this.qb, this.gb)
    ];
    const actionsAndStatusContainer = $bk(details, $(".actions-status-container"));
    const extensionActionBar = this.B(new $LZ(actionsAndStatusContainer, {
      actionViewItemProvider: (action, options3) => {
        if (action instanceof $0Cb) {
          return action.createActionViewItem(options3);
        }
        if (action instanceof $VCb) {
          return new $WCb(action, {
            ...options3,
            icon: true,
            label: true,
            menuActionsOrProvider: { getActions: () => action.menuActions },
            menuActionClassNames: action.menuActionClassNames
          }, this.pb);
        }
        if (action instanceof $7Cb) {
          return new $S1(void 0, action, { ...options3, icon: true, label: true, checkboxStyles: $x$ });
        }
        return void 0;
      },
      focusOnlyEnabledItems: true
    }));
    extensionActionBar.push(actions, { icon: true, label: true });
    extensionActionBar.setFocusable(true);
    this.B(Event2.any(...actions.map((a) => Event2.filter(a.onDidChange, (e) => e.enabled !== void 0)))(() => {
      extensionActionBar.setFocusable(false);
      extensionActionBar.setFocusable(true);
    }));
    const otherExtensionContainers = [];
    const extensionStatusAction = this.gb.createInstance($ADb);
    const extensionStatusWidget = this.B(this.gb.createInstance($hdc, $bk(actionsAndStatusContainer, $(".status")), extensionStatusAction));
    otherExtensionContainers.push(extensionStatusAction, new class extends $7cc {
      render() {
        actionsAndStatusContainer.classList.toggle(
          "list-layout",
          this.extension?.state === 1
          /* ExtensionState.Installed */
        );
      }
    }());
    const recommendationWidget = this.gb.createInstance($idc, $bk(details, $(".recommendation")));
    widgets2.push(recommendationWidget);
    this.B(Event2.any(extensionStatusWidget.onDidRender, recommendationWidget.onDidRender)(() => {
      if (this.eb) {
        this.layout(this.eb);
      }
    }));
    const extensionContainers = this.gb.createInstance($Bzb, [...actions, ...widgets2, ...otherExtensionContainers]);
    for (const disposable of [...actions, ...widgets2, ...otherExtensionContainers, extensionContainers]) {
      this.B(disposable);
    }
    const onError2 = Event2.chain(extensionActionBar.onDidRun, ($149) => $149.map(({ error }) => error).filter((error) => !!error));
    this.B(onError2(this.Yb, this));
    const body = $bk(root, $(".body"));
    const navbar = new NavBar(body);
    const content = $bk(body, $(".content"));
    content.id = $ps();
    this.c = {
      builtin,
      content,
      description,
      header,
      icon: icon2,
      iconContainer,
      installCount,
      name,
      navbar,
      preview,
      publisher,
      publisherDisplayName,
      resource,
      rating,
      actionsAndStatusContainer,
      extensionActionBar,
      set extension(extension) {
        extensionContainers.extension = extension;
      },
      set gallery(gallery) {
        versionWidget.gallery = gallery;
      },
      set manifest(manifest) {
        installAction.manifest = manifest;
      }
    };
  }
  async setInput(input, options3, context, token) {
    await super.setInput(input, options3, context, token);
    this.Ab();
    if (this.c) {
      await this.Cb(input.extension, this.c, !!options3?.preserveFocus);
    }
  }
  setOptions(options3) {
    const currentOptions = this.options;
    super.setOptions(options3);
    this.Ab();
    if (this.input && this.c && currentOptions?.showPreReleaseVersion !== options3?.showPreReleaseVersion) {
      this.Cb(this.input.extension, this.c, !!options3?.preserveFocus);
      return;
    }
    if (options3?.tab) {
      this.c?.navbar.switch(options3.tab);
    }
  }
  Ab() {
    let showPreReleaseVersion = this.options?.showPreReleaseVersion;
    if ($Gg(showPreReleaseVersion)) {
      showPreReleaseVersion = !!this.input.extension.gallery?.properties.isPreReleaseVersion;
    }
    this.fb?.set(showPreReleaseVersion);
  }
  async openTab(tab) {
    if (!this.input || !this.c) {
      return;
    }
    if (this.c.navbar.switch(tab)) {
      return;
    }
    if (tab === "extensionPack") {
      this.c.navbar.switch(
        "readme"
        /* ExtensionEditorTab.Readme */
      );
    }
  }
  async Bb(extension, preRelease) {
    if (extension.resourceExtension) {
      return null;
    }
    if (extension.local?.source === "resource") {
      return null;
    }
    if ($Gg(preRelease)) {
      return null;
    }
    if (preRelease === extension.gallery?.properties.isPreReleaseVersion) {
      return null;
    }
    if (preRelease && !extension.hasPreReleaseVersion) {
      return null;
    }
    if (!preRelease && !extension.hasReleaseVersion) {
      return null;
    }
    return (await this.ib.getExtensions([{ ...extension.identifier, preRelease, hasPreRelease: extension.hasPreReleaseVersion }], CancellationToken.None))[0] || null;
  }
  async Cb(extension, template, preserveFocus) {
    this.db = null;
    this.cb.clear();
    const token = this.cb.add(new $ad()).token;
    const gallery = await this.Bb(extension, this.options?.showPreReleaseVersion);
    if (token.isCancellationRequested) {
      return;
    }
    this.f = new $of(() => gallery ? this.ib.getReadme(gallery, token) : extension.getReadme(token));
    this.g = new $of(() => gallery ? this.ib.getChangelog(gallery, token) : extension.getChangelog(token));
    this.j = new $of(() => gallery ? this.ib.getManifest(gallery, token) : extension.getManifest(token));
    template.extension = extension;
    template.gallery = gallery;
    template.manifest = null;
    this.cb.add($_i(template.icon, "error", () => template.icon.src = extension.iconUrlFallback, { once: true }));
    template.icon.src = extension.iconUrl;
    template.name.textContent = extension.displayName;
    template.name.classList.toggle("clickable", !!extension.url);
    template.name.classList.toggle("deprecated", !!extension.deprecationInfo);
    template.preview.style.display = extension.preview ? "inherit" : "none";
    template.builtin.style.display = extension.isBuiltin ? "inherit" : "none";
    template.description.textContent = extension.description;
    template.publisher.classList.toggle("clickable", !!extension.url);
    template.publisherDisplayName.textContent = extension.publisherDisplayName;
    template.publisher.parentElement?.classList.toggle("hide", !!extension.resourceExtension || extension.local?.source === "resource");
    this.cb.add(this.vb.setupManagedHover($JZ("mouse"), template.publisher, localize(6364, null, extension.publisher)));
    const location3 = extension.resourceExtension?.location ?? (extension.local?.source === "resource" ? extension.local?.location : void 0);
    template.resource.parentElement?.classList.toggle("hide", !location3);
    if (location3) {
      const workspaceFolder = this.rb.getWorkspaceFolder(location3);
      if (workspaceFolder && extension.isWorkspaceScoped) {
        template.resource.parentElement?.classList.add("clickable");
        this.cb.add(this.vb.setupManagedHover($JZ("mouse"), template.resource, this.ub.extUri.relativePath(workspaceFolder.uri, location3)));
        template.resource.textContent = localize(6365, null);
        this.cb.add($8cc(template.resource, () => {
          this.tb.openView($4sb, true).then(() => this.sb.select(location3, true));
        }));
      } else {
        template.resource.parentElement?.classList.remove("clickable");
        this.cb.add(this.vb.setupManagedHover($JZ("mouse"), template.resource, location3.path));
        template.resource.textContent = localize(6366, null);
      }
    }
    template.installCount.parentElement?.classList.toggle("hide", !extension.url);
    template.rating.parentElement?.classList.toggle("hide", !extension.url);
    template.rating.classList.toggle("clickable", !!extension.url);
    if (extension.url) {
      this.cb.add($8cc(template.name, () => this.kb.open(URI.parse(extension.url))));
      this.cb.add($8cc(template.rating, () => this.kb.open(URI.parse(`${extension.url}&ssr=false#review-details`))));
      this.cb.add($8cc(template.publisher, () => this.hb.openSearch(`publisher:"${extension.publisherDisplayName}"`)));
    }
    const manifest = await this.j.get().promise;
    if (token.isCancellationRequested) {
      return;
    }
    if (manifest) {
      template.manifest = manifest;
    }
    this.Db(extension, manifest, template, preserveFocus);
    const extRecommendations = this.lb.getAllRecommendationsWithReason();
    let recommendationsData = {};
    if (extRecommendations[extension.identifier.id.toLowerCase()]) {
      recommendationsData = { recommendationReason: extRecommendations[extension.identifier.id.toLowerCase()].reasonId };
    }
    this.Q.publicLog("extensionGallery:openExtension", { ...extension.telemetryData, ...recommendationsData });
  }
  Db(extension, manifest, template, preserveFocus) {
    template.content.innerText = "";
    template.navbar.clear();
    if (this.r !== extension.identifier.id) {
      this.m.clear();
      this.r = extension.identifier.id;
    }
    template.navbar.push("readme", localize(6367, null), localize(6368, null));
    if (manifest) {
      template.navbar.push("features", localize(6369, null), localize(6370, null));
    }
    if (extension.hasChangelog()) {
      template.navbar.push("changelog", localize(6371, null), localize(6372, null));
    }
    if (extension.dependencies.length) {
      template.navbar.push("dependencies", localize(6373, null), localize(6374, null));
    }
    if (manifest && manifest.extensionPack?.length && !this.Kb(manifest)) {
      template.navbar.push("extensionPack", localize(6375, null), localize(6376, null));
    }
    if (this.options?.tab) {
      template.navbar.switch(this.options.tab);
    }
    if (template.navbar.currentId) {
      this.Eb(extension, { id: template.navbar.currentId, focus: !preserveFocus }, template);
    }
    template.navbar.onChange((e) => this.Eb(extension, e, template), this, this.cb);
  }
  clearInput() {
    this.u.clear();
    this.cb.clear();
    super.clearInput();
  }
  focus() {
    super.focus();
    this.db?.focus();
  }
  showFind() {
    this.activeWebview?.showFind();
  }
  runFindAction(previous) {
    this.activeWebview?.runFindAction(previous);
  }
  get activeWebview() {
    if (!this.db || !this.db.runFindAction) {
      return void 0;
    }
    return this.db;
  }
  Eb(extension, { id: id2, focus }, template) {
    this.u.clear();
    template.content.innerText = "";
    this.db = null;
    if (id2) {
      const cts = new $ad();
      this.u.add($1c(() => cts.dispose(true)));
      this.Fb(id2, extension, template, cts.token).then((activeElement) => {
        if (cts.token.isCancellationRequested) {
          return;
        }
        this.db = activeElement;
        if (focus) {
          this.focus();
        }
      });
    }
  }
  Fb(id2, extension, template, token) {
    switch (id2) {
      case "readme":
        return this.Jb(extension, template, token);
      case "features":
        return this.Tb(template, token);
      case "changelog":
        return this.Sb(extension, template, token);
      case "dependencies":
        return this.Ub(extension, template, token);
      case "extensionPack":
        return this.Vb(extension, template, token);
    }
    return Promise.resolve(null);
  }
  async Gb(extension, cacheResult, noContentCopy, container2, webviewIndex, title, token) {
    try {
      const body = await this.Hb(extension, cacheResult, container2, token);
      if (token.isCancellationRequested) {
        return Promise.resolve(null);
      }
      const webview = this.u.add(this.nb.createWebviewOverlay({
        title,
        options: {
          enableFindWidget: true,
          tryRestoreScrollPosition: true,
          disableServiceWorker: true
        },
        contentOptions: {},
        extension: void 0
      }));
      webview.initialScrollProgress = this.m.get(webviewIndex) || 0;
      webview.claim(this, this.window, this.scopedContextKeyService);
      $Ej(webview.container, container2);
      webview.layoutWebviewOverElement(container2);
      webview.setHtml(body);
      webview.claim(this, this.window, void 0);
      this.u.add(webview.onDidFocus(() => this.y?.fire()));
      this.u.add(webview.onDidScroll(() => this.m.set(webviewIndex, webview.initialScrollProgress)));
      const removeLayoutParticipant = $Wb(this.s, {
        layout: () => {
          webview.layoutWebviewOverElement(container2);
        }
      });
      this.u.add($1c(removeLayoutParticipant));
      let isDisposed = false;
      this.u.add($1c(() => {
        isDisposed = true;
      }));
      this.u.add(this.n.onDidColorThemeChange(async () => {
        const body2 = await this.Hb(extension, cacheResult, container2);
        if (!isDisposed) {
          webview.setHtml(body2);
        }
      }));
      this.u.add(webview.onDidClickLink((link2) => {
        if (!link2) {
          return;
        }
        if ($0g(link2, Schemas.http) || $0g(link2, Schemas.https) || $0g(link2, Schemas.mailto)) {
          this.kb.open(link2);
        }
        if ($0g(link2, Schemas.command) && extension.type === 0) {
          this.kb.open(link2, { allowCommands: true });
        }
      }));
      return webview;
    } catch (e) {
      const p = $bk(container2, $("p.nocontent"));
      p.textContent = noContentCopy;
      return p;
    }
  }
  async Hb(extension, cacheResult, container2, token) {
    const contents = await this.Xb(() => cacheResult, container2);
    if (token?.isCancellationRequested) {
      return "";
    }
    const content = await $Qdc(contents, this.mb, this.ob, { shouldSanitize: extension.type !== 0, token });
    if (token?.isCancellationRequested) {
      return "";
    }
    return this.Ib(content);
  }
  Ib(body) {
    const nonce = $ps();
    const colorMap = $YE.getColorMap();
    const css = colorMap ? $4Gb(colorMap) : "";
    return `<!DOCTYPE html>
		<html>
			<head>
				<meta http-equiv="Content-type" content="text/html;charset=UTF-8">
				<meta http-equiv="Content-Security-Policy" content="default-src 'none'; img-src https: data:; media-src https:; script-src 'none'; style-src 'nonce-${nonce}';">
				<style nonce="${nonce}">
					${$Pdc}

					/* prevent scroll-to-top button from blocking the body text */
					body {
						padding-bottom: 75px;
					}

					#scroll-to-top {
						position: fixed;
						width: 32px;
						height: 32px;
						right: 25px;
						bottom: 25px;
						background-color: var(--vscode-button-secondaryBackground);
						border-color: var(--vscode-button-border);
						border-radius: 50%;
						cursor: pointer;
						box-shadow: 1px 1px 1px rgba(0,0,0,.25);
						outline: none;
						display: flex;
						justify-content: center;
						align-items: center;
					}

					#scroll-to-top:hover {
						background-color: var(--vscode-button-secondaryHoverBackground);
						box-shadow: 2px 2px 2px rgba(0,0,0,.25);
					}

					body.vscode-high-contrast #scroll-to-top {
						border-width: 2px;
						border-style: solid;
						box-shadow: none;
					}

					#scroll-to-top span.icon::before {
						content: "";
						display: block;
						background: var(--vscode-button-secondaryForeground);
						/* Chevron up icon */
						webkit-mask-image: url('data:image/svg+xml;base64,PD94bWwgdmVyc2lvbj0iMS4wIiBlbmNvZGluZz0idXRmLTgiPz4KPCEtLSBHZW5lcmF0b3I6IEFkb2JlIElsbHVzdHJhdG9yIDE5LjIuMCwgU1ZHIEV4cG9ydCBQbHVnLUluIC4gU1ZHIFZlcnNpb246IDYuMDAgQnVpbGQgMCkgIC0tPgo8c3ZnIHZlcnNpb249IjEuMSIgaWQ9IkxheWVyXzEiIHhtbG5zPSJodHRwOi8vd3d3LnczLm9yZy8yMDAwL3N2ZyIgeG1sbnM6eGxpbms9Imh0dHA6Ly93d3cudzMub3JnLzE5OTkveGxpbmsiIHg9IjBweCIgeT0iMHB4IgoJIHZpZXdCb3g9IjAgMCAxNiAxNiIgc3R5bGU9ImVuYWJsZS1iYWNrZ3JvdW5kOm5ldyAwIDAgMTYgMTY7IiB4bWw6c3BhY2U9InByZXNlcnZlIj4KPHN0eWxlIHR5cGU9InRleHQvY3NzIj4KCS5zdDB7ZmlsbDojRkZGRkZGO30KCS5zdDF7ZmlsbDpub25lO30KPC9zdHlsZT4KPHRpdGxlPnVwY2hldnJvbjwvdGl0bGU+CjxwYXRoIGNsYXNzPSJzdDAiIGQ9Ik04LDUuMWwtNy4zLDcuM0wwLDExLjZsOC04bDgsOGwtMC43LDAuN0w4LDUuMXoiLz4KPHJlY3QgY2xhc3M9InN0MSIgd2lkdGg9IjE2IiBoZWlnaHQ9IjE2Ii8+Cjwvc3ZnPgo=');
						-webkit-mask-image: url('data:image/svg+xml;base64,PD94bWwgdmVyc2lvbj0iMS4wIiBlbmNvZGluZz0idXRmLTgiPz4KPCEtLSBHZW5lcmF0b3I6IEFkb2JlIElsbHVzdHJhdG9yIDE5LjIuMCwgU1ZHIEV4cG9ydCBQbHVnLUluIC4gU1ZHIFZlcnNpb246IDYuMDAgQnVpbGQgMCkgIC0tPgo8c3ZnIHZlcnNpb249IjEuMSIgaWQ9IkxheWVyXzEiIHhtbG5zPSJodHRwOi8vd3d3LnczLm9yZy8yMDAwL3N2ZyIgeG1sbnM6eGxpbms9Imh0dHA6Ly93d3cudzMub3JnLzE5OTkveGxpbmsiIHg9IjBweCIgeT0iMHB4IgoJIHZpZXdCb3g9IjAgMCAxNiAxNiIgc3R5bGU9ImVuYWJsZS1iYWNrZ3JvdW5kOm5ldyAwIDAgMTYgMTY7IiB4bWw6c3BhY2U9InByZXNlcnZlIj4KPHN0eWxlIHR5cGU9InRleHQvY3NzIj4KCS5zdDB7ZmlsbDojRkZGRkZGO30KCS5zdDF7ZmlsbDpub25lO30KPC9zdHlsZT4KPHRpdGxlPnVwY2hldnJvbjwvdGl0bGU+CjxwYXRoIGNsYXNzPSJzdDAiIGQ9Ik04LDUuMWwtNy4zLDcuM0wwLDExLjZsOC04bDgsOGwtMC43LDAuN0w4LDUuMXoiLz4KPHJlY3QgY2xhc3M9InN0MSIgd2lkdGg9IjE2IiBoZWlnaHQ9IjE2Ii8+Cjwvc3ZnPgo=');
						width: 16px;
						height: 16px;
					}
					${css}
				</style>
			</head>
			<body>
				<a id="scroll-to-top" role="button" aria-label="scroll to top" href="#"><span class="icon"></span></a>
				${body}
			</body>
		</html>`;
  }
  async Jb(extension, template, token) {
    const details = $bk(template.content, $(".details"));
    const readmeContainer = $bk(details, $(".readme-container"));
    const additionalDetailsContainer = $bk(details, $(".additional-details-container"));
    const layout = () => details.classList.toggle("narrow", this.eb && this.eb.width < 500);
    layout();
    this.u.add($1c($Wb(this.s, { layout })));
    let activeElement = null;
    const manifest = await this.j.get().promise;
    if (manifest && manifest.extensionPack?.length && this.Kb(manifest)) {
      activeElement = await this.Lb(extension, manifest, readmeContainer, token);
    } else {
      activeElement = await this.Gb(extension, this.f.get(), localize(6377, null), readmeContainer, 0, localize(6378, null), token);
    }
    this.Mb(additionalDetailsContainer, extension);
    return activeElement;
  }
  Kb(manifest) {
    return !!manifest.categories?.some((category8) => category8.toLowerCase() === "extension packs");
  }
  async Lb(extension, manifest, container2, token) {
    if (token.isCancellationRequested) {
      return Promise.resolve(null);
    }
    const extensionPackReadme = $bk(container2, $("div", { class: "extension-pack-readme" }));
    extensionPackReadme.style.margin = "0 auto";
    extensionPackReadme.style.maxWidth = "882px";
    const extensionPack = $bk(extensionPackReadme, $("div", { class: "extension-pack" }));
    if (manifest.extensionPack.length <= 3) {
      extensionPackReadme.classList.add("one-row");
    } else if (manifest.extensionPack.length <= 6) {
      extensionPackReadme.classList.add("two-rows");
    } else if (manifest.extensionPack.length <= 9) {
      extensionPackReadme.classList.add("three-rows");
    } else {
      extensionPackReadme.classList.add("more-rows");
    }
    const extensionPackHeader = $bk(extensionPack, $("div.header"));
    extensionPackHeader.textContent = localize(6379, null, manifest.extensionPack.length);
    const extensionPackContent = $bk(extensionPack, $("div", { class: "extension-pack-content" }));
    extensionPackContent.setAttribute("tabindex", "0");
    $bk(extensionPack, $("div.footer"));
    const readmeContent = $bk(extensionPackReadme, $("div.readme-content"));
    await Promise.all([
      this.Wb(manifest, extensionPackContent, token),
      this.Gb(extension, this.f.get(), localize(6380, null), readmeContent, 0, localize(6381, null), token)
    ]);
    return { focus: () => extensionPackContent.focus() };
  }
  Mb(container2, extension) {
    const content = $("div", { class: "additional-details-content", tabindex: "0" });
    const scrollableContent = new $CZ(content, {});
    const layout = () => scrollableContent.scanDomNode();
    const removeLayoutParticipant = $Wb(this.s, { layout });
    this.u.add($1c(removeLayoutParticipant));
    this.u.add(scrollableContent);
    if (extension.local) {
      this.Pb(content, extension.local);
    }
    if (extension.gallery) {
      this.Rb(content, extension);
    }
    this.Nb(content, extension);
    this.Ob(content, extension);
    $bk(container2, scrollableContent.getDomNode());
    scrollableContent.scanDomNode();
  }
  Nb(container2, extension) {
    if (extension.categories.length) {
      const categoriesContainer = $bk(container2, $(".categories-container.additional-details-element"));
      $bk(categoriesContainer, $(".additional-details-title", void 0, localize(6382, null)));
      const categoriesElement = $bk(categoriesContainer, $(".categories"));
      for (const category8 of extension.categories) {
        this.cb.add($8cc($bk(categoriesElement, $("span.category", { tabindex: "0" }, category8)), () => this.hb.openSearch(`@category:"${category8}"`)));
      }
    }
  }
  Ob(container2, extension) {
    const resources = [];
    if (extension.url) {
      resources.push([localize(6383, null), URI.parse(extension.url)]);
    }
    if (extension.url && extension.supportUrl) {
      try {
        resources.push([localize(6384, null), URI.parse(extension.supportUrl)]);
      } catch (error) {
      }
    }
    if (extension.repository) {
      try {
        resources.push([localize(6385, null), URI.parse(extension.repository)]);
      } catch (error) {
      }
    }
    if (extension.url && extension.licenseUrl) {
      try {
        resources.push([localize(6386, null), URI.parse(extension.licenseUrl)]);
      } catch (error) {
      }
    }
    if (extension.publisherUrl) {
      resources.push([extension.publisherDisplayName, extension.publisherUrl]);
    }
    if (resources.length || extension.publisherSponsorLink) {
      const extensionResourcesContainer = $bk(container2, $(".resources-container.additional-details-element"));
      $bk(extensionResourcesContainer, $(".additional-details-title", void 0, localize(6387, null)));
      const resourcesElement = $bk(extensionResourcesContainer, $(".resources"));
      for (const [label3, uri] of resources) {
        const resource = $bk(resourcesElement, $("a.resource", { tabindex: "0" }, label3));
        this.cb.add($8cc(resource, () => {
          this.kb.open(uri);
        }));
        this.cb.add(this.vb.setupManagedHover($JZ("mouse"), resource, uri.toString()));
      }
    }
  }
  Pb(container2, extension) {
    const installInfoContainer = $bk(container2, $(".more-info-container.additional-details-element"));
    $bk(installInfoContainer, $(".additional-details-title", void 0, localize(6388, null)));
    const installInfo = $bk(installInfoContainer, $(".more-info"));
    $bk(installInfo, $(".more-info-entry", void 0, $("div", void 0, localize(6389, null)), $("code", void 0, extension.identifier.id)));
    $bk(installInfo, $(".more-info-entry", void 0, $("div", void 0, localize(6390, null)), $("code", void 0, extension.manifest.version)));
    if (extension.installedTimestamp) {
      $bk(installInfo, $(".more-info-entry", void 0, $("div", void 0, localize(6391, null)), $("div", void 0, toDateString(new Date(extension.installedTimestamp)))));
    }
    if (extension.source !== "gallery") {
      const element = $("div", void 0, extension.source === "vsix" ? localize(6392, null) : localize(6393, null));
      $bk(installInfo, $(".more-info-entry", void 0, $("div", void 0, localize(6394, null)), element));
      if ($p && extension.source === "resource" && extension.location.scheme === Schemas.file) {
        element.classList.add("link");
        element.title = extension.location.fsPath;
        this.cb.add($8cc(element, () => this.kb.open(extension.location, { openExternal: true })));
      }
    }
    if (extension.size) {
      const element = $("div", void 0, toMemoryString(extension.size));
      $bk(installInfo, $(".more-info-entry", void 0, $("div", { title: localize(6395, null) }, localize(6396, null)), element));
      if ($p && extension.location.scheme === Schemas.file) {
        element.classList.add("link");
        element.title = extension.location.fsPath;
        this.cb.add($8cc(element, () => this.kb.open(extension.location, { openExternal: true })));
      }
    }
    this.Qb(extension).then((cacheLocation) => {
      if (!cacheLocation) {
        return;
      }
      $yA(cacheLocation, this.yb).then((cacheSize) => {
        if (!cacheSize) {
          return;
        }
        const element = $("div", void 0, toMemoryString(cacheSize));
        $bk(installInfo, $(".more-info-entry", void 0, $("div", { title: localize(6397, null) }, localize(6398, null)), element));
        if ($p && extension.location.scheme === Schemas.file) {
          element.classList.add("link");
          element.title = cacheLocation.fsPath;
          this.cb.add($8cc(element, () => this.kb.open(cacheLocation.with({ scheme: Schemas.file }), { openExternal: true })));
        }
      });
    });
  }
  async Qb(extension) {
    let extensionCacheLocation = this.ub.extUri.joinPath(this.wb.defaultProfile.globalStorageHome, extension.identifier.id.toLowerCase());
    if (extension.location.scheme === Schemas.vscodeRemote) {
      const environment = await this.xb.getEnvironment();
      if (!environment) {
        return void 0;
      }
      extensionCacheLocation = this.ub.extUri.joinPath(environment.globalStorageHome, extension.identifier.id.toLowerCase());
    }
    return extensionCacheLocation;
  }
  Rb(container2, extension) {
    const gallery = extension.gallery;
    const moreInfoContainer = $bk(container2, $(".more-info-container.additional-details-element"));
    $bk(moreInfoContainer, $(".additional-details-title", void 0, localize(6399, null)));
    const moreInfo = $bk(moreInfoContainer, $(".more-info"));
    if (gallery) {
      if (!extension.local) {
        $bk(moreInfo, $(".more-info-entry", void 0, $("div", void 0, localize(6400, null)), $("code", void 0, extension.identifier.id)));
        $bk(moreInfo, $(".more-info-entry", void 0, $("div", void 0, localize(6401, null)), $("code", void 0, gallery.version)));
      }
      $bk(moreInfo, $(".more-info-entry", void 0, $("div", void 0, localize(6402, null)), $("div", void 0, toDateString(new Date(gallery.releaseDate)))), $(".more-info-entry", void 0, $("div", void 0, localize(6403, null)), $("div", void 0, toDateString(new Date(gallery.lastUpdated)))));
    }
  }
  Sb(extension, template, token) {
    return this.Gb(extension, this.g.get(), localize(6404, null), template.content, 1, localize(6405, null), token);
  }
  async Tb(template, token) {
    const manifest = await this.Xb(() => this.j.get(), template.content);
    if (token.isCancellationRequested) {
      return null;
    }
    if (!manifest) {
      return null;
    }
    const extensionFeaturesTab = this.u.add(this.gb.createInstance($6cc, manifest, this.options?.feature));
    const layout = () => extensionFeaturesTab.layout(template.content.clientHeight, template.content.clientWidth);
    const removeLayoutParticipant = $Wb(this.s, { layout });
    this.u.add($1c(removeLayoutParticipant));
    $bk(template.content, extensionFeaturesTab.domNode);
    layout();
    return extensionFeaturesTab.domNode;
  }
  Ub(extension, template, token) {
    if (token.isCancellationRequested) {
      return Promise.resolve(null);
    }
    if ($Pb(extension.dependencies)) {
      $bk(template.content, $("p.nocontent")).textContent = localize(6406, null);
      return Promise.resolve(template.content);
    }
    const content = $("div", { class: "subcontent" });
    const scrollableContent = new $CZ(content, {});
    $bk(template.content, scrollableContent.getDomNode());
    this.u.add(scrollableContent);
    const dependenciesTree = this.gb.createInstance($Ldc, new $Mdc(extension, null, (extension2) => extension2.dependencies || [], this.hb), content, {
      listBackground: $Ko
    });
    const layout = () => {
      scrollableContent.scanDomNode();
      const scrollDimensions = scrollableContent.getScrollDimensions();
      dependenciesTree.layout(scrollDimensions.height);
    };
    const removeLayoutParticipant = $Wb(this.s, { layout });
    this.u.add($1c(removeLayoutParticipant));
    this.u.add(dependenciesTree);
    scrollableContent.scanDomNode();
    return Promise.resolve({ focus() {
      dependenciesTree.domFocus();
    } });
  }
  async Vb(extension, template, token) {
    if (token.isCancellationRequested) {
      return Promise.resolve(null);
    }
    const manifest = await this.Xb(() => this.j.get(), template.content);
    if (token.isCancellationRequested) {
      return null;
    }
    if (!manifest) {
      return null;
    }
    return this.Wb(manifest, template.content, token);
  }
  async Wb(manifest, parent, token) {
    if (token.isCancellationRequested) {
      return null;
    }
    const content = $("div", { class: "subcontent" });
    const scrollableContent = new $CZ(content, { useShadows: false });
    $bk(parent, scrollableContent.getDomNode());
    const extensionsGridView = this.gb.createInstance($Kdc, content, new $ndc());
    const extensions = await $Ndc(manifest.extensionPack, this.hb);
    extensionsGridView.setExtensions(extensions);
    scrollableContent.scanDomNode();
    this.u.add(scrollableContent);
    this.u.add(extensionsGridView);
    this.u.add($1c($Wb(this.s, { layout: () => scrollableContent.scanDomNode() })));
    return content;
  }
  Xb(loadingTask, container2) {
    container2.classList.add("loading");
    const result = this.u.add(loadingTask());
    const onDone = () => container2.classList.remove("loading");
    result.promise.then(onDone, onDone);
    return result.promise;
  }
  layout(dimension) {
    this.eb = dimension;
    this.s.forEach((p) => p.layout());
  }
  Yb(err) {
    if ($kb(err)) {
      return;
    }
    this.jb.error(err);
  }
};
$Rdc = $Rdc_1 = __decorate([
  __param(1, $zv),
  __param(2, $Pk),
  __param(3, $vzb),
  __param(4, $pA),
  __param(5, $gs),
  __param(6, $PJ),
  __param(7, $O4),
  __param(8, $ABb),
  __param(9, $jv),
  __param(10, $wN),
  __param(11, $Crb),
  __param(12, $1E),
  __param(13, $50),
  __param(14, $on),
  __param(15, $Zk),
  __param(16, $kvb),
  __param(17, $uob),
  __param(18, $vl),
  __param(19, $5$),
  __param(20, $rs),
  __param(21, $RL),
  __param(22, $km)
], $Rdc);
var contextKeyExpr = $7m.and($7m.equals("activeEditor", $Rdc.ID), EditorContextKeys.focus.toNegated());
$hJ(class ShowExtensionEditorFindAction extends $gJ {
  constructor() {
    super({
      id: "editor.action.extensioneditor.showfind",
      title: localize(6407, null),
      keybinding: {
        when: contextKeyExpr,
        weight: 100,
        primary: 2048 | 36
      }
    });
  }
  run(accessor) {
    const extensionEditor = getExtensionEditor(accessor);
    extensionEditor?.showFind();
  }
});
$hJ(class StartExtensionEditorFindNextAction extends $gJ {
  constructor() {
    super({
      id: "editor.action.extensioneditor.findNext",
      title: localize(6408, null),
      keybinding: {
        when: $7m.and(contextKeyExpr, $Arb),
        primary: 3,
        weight: 100
        /* KeybindingWeight.EditorContrib */
      }
    });
  }
  run(accessor) {
    const extensionEditor = getExtensionEditor(accessor);
    extensionEditor?.runFindAction(false);
  }
});
$hJ(class StartExtensionEditorFindPreviousAction extends $gJ {
  constructor() {
    super({
      id: "editor.action.extensioneditor.findPrevious",
      title: localize(6409, null),
      keybinding: {
        when: $7m.and(contextKeyExpr, $Arb),
        primary: 1024 | 3,
        weight: 100
        /* KeybindingWeight.EditorContrib */
      }
    });
  }
  run(accessor) {
    const extensionEditor = getExtensionEditor(accessor);
    extensionEditor?.runFindAction(true);
  }
});
$ms((theme, collector) => {
  const link2 = theme.getColor($no);
  if (link2) {
    collector.addRule(`.monaco-workbench .extension-editor .content .details .additional-details-container .resources-container a.resource { color: ${link2}; }`);
    collector.addRule(`.monaco-workbench .extension-editor .content .feature-contributions a { color: ${link2}; }`);
  }
  const activeLink = theme.getColor($oo);
  if (activeLink) {
    collector.addRule(`.monaco-workbench .extension-editor .content .details .additional-details-container .resources-container a.resource:hover,
			.monaco-workbench .extension-editor .content .details .additional-details-container .resources-container a.resource:active { color: ${activeLink}; }`);
    collector.addRule(`.monaco-workbench .extension-editor .content .feature-contributions a:hover,
			.monaco-workbench .extension-editor .content .feature-contributions a:active { color: ${activeLink}; }`);
  }
  const buttonHoverBackgroundColor = theme.getColor($Vq);
  if (buttonHoverBackgroundColor) {
    collector.addRule(`.monaco-workbench .extension-editor .content > .details > .additional-details-container .categories-container > .categories > .category:hover { background-color: ${buttonHoverBackgroundColor}; border-color: ${buttonHoverBackgroundColor}; }`);
    collector.addRule(`.monaco-workbench .extension-editor .content > .details > .additional-details-container .tags-container > .tags > .tag:hover { background-color: ${buttonHoverBackgroundColor}; border-color: ${buttonHoverBackgroundColor}; }`);
  }
  const buttonForegroundColor = theme.getColor($Sq);
  if (buttonForegroundColor) {
    collector.addRule(`.monaco-workbench .extension-editor .content > .details > .additional-details-container .categories-container > .categories > .category:hover { color: ${buttonForegroundColor}; }`);
    collector.addRule(`.monaco-workbench .extension-editor .content > .details > .additional-details-container .tags-container > .tags > .tag:hover { color: ${buttonForegroundColor}; }`);
  }
});
function getExtensionEditor(accessor) {
  const activeEditorPane = accessor.get($mJ).activeEditorPane;
  if (activeEditorPane instanceof $Rdc) {
    return activeEditorPane;
  }
  return null;
}

// out-build/vs/workbench/contrib/extensions/browser/extensionsViewlet.js
var $Sdc = new $nn("defaultExtensionViews", true);
var $Tdc = new $nn("extensionsSortByValue", "");
var $Udc = new $nn("searchMarketplaceExtensions", false);
var $Vdc = new $nn("extensionSearchHasText", false);
var InstalledExtensionsContext = new $nn("installedExtensions", false);
var SearchInstalledExtensionsContext = new $nn("searchInstalledExtensions", false);
var SearchRecentlyUpdatedExtensionsContext = new $nn("searchRecentlyUpdatedExtensions", false);
var SearchExtensionUpdatesContext = new $nn("searchExtensionUpdates", false);
var SearchOutdatedExtensionsContext = new $nn("searchOutdatedExtensions", false);
var SearchEnabledExtensionsContext = new $nn("searchEnabledExtensions", false);
var SearchDisabledExtensionsContext = new $nn("searchDisabledExtensions", false);
var HasInstalledExtensionsContext = new $nn("hasInstalledExtensions", true);
var $Wdc = new $nn("builtInExtensions", false);
var SearchBuiltInExtensionsContext = new $nn("searchBuiltInExtensions", false);
var SearchUnsupportedWorkspaceExtensionsContext = new $nn("searchUnsupportedWorkspaceExtensions", false);
var SearchDeprecatedExtensionsContext = new $nn("searchDeprecatedExtensions", false);
var $Xdc = new $nn("recommendedExtensions", false);
var SortByUpdateDateContext = new $nn("sortByUpdateDate", false);
var $Ydc = new $nn("extensionsSearchValue", "");
var REMOTE_CATEGORY = localize2(6834, "Remote");
var $Zdc = class $Zdc2 extends $3c {
  constructor(b, f, viewDescriptorService, g) {
    super();
    this.b = b;
    this.f = f;
    this.g = g;
    this.a = viewDescriptorService.getViewContainerById($tzb);
    this.h();
  }
  h() {
    const viewDescriptors = [];
    viewDescriptors.push(...this.j());
    viewDescriptors.push(...this.m());
    viewDescriptors.push(...this.n());
    viewDescriptors.push(...this.s());
    viewDescriptors.push(...this.u());
    viewDescriptors.push(...this.w());
    $Wn.as(Extensions5.ViewsRegistry).registerViews(viewDescriptors, this.a);
  }
  j() {
    const viewDescriptors = [];
    const servers = [];
    if (this.b.localExtensionManagementServer) {
      servers.push(this.b.localExtensionManagementServer);
    }
    if (this.b.remoteExtensionManagementServer) {
      servers.push(this.b.remoteExtensionManagementServer);
    }
    if (this.b.webExtensionManagementServer) {
      servers.push(this.b.webExtensionManagementServer);
    }
    const getViewName = (viewTitle, server) => {
      return servers.length > 1 ? `${server.label} - ${viewTitle}` : viewTitle;
    };
    let installedWebExtensionsContextChangeEvent = Event2.None;
    if (this.b.webExtensionManagementServer && this.b.remoteExtensionManagementServer) {
      const interestingContextKeys = /* @__PURE__ */ new Set();
      interestingContextKeys.add("hasInstalledWebExtensions");
      installedWebExtensionsContextChangeEvent = Event2.filter(this.g.onDidChangeContext, (e) => e.affectsSome(interestingContextKeys));
    }
    const serverLabelChangeEvent = Event2.any(this.f.onDidChangeFormatters, installedWebExtensionsContextChangeEvent);
    for (const server of servers) {
      const getInstalledViewName = () => getViewName(localize(6816, null), server);
      const onDidChangeTitle = Event2.map(serverLabelChangeEvent, () => getInstalledViewName());
      const id2 = servers.length > 1 ? `workbench.views.extensions.${server.id}.installed` : `workbench.views.extensions.installed`;
      viewDescriptors.push({
        id: id2,
        get name() {
          return {
            value: getInstalledViewName(),
            original: getViewName("Installed", server)
          };
        },
        weight: 100,
        order: 1,
        when: $7m.and($Sdc),
        ctorDescriptor: new $Nk($tdc, [{ server, flexibleHeight: true, onDidChangeTitle }]),
        /* Installed extensions views shall not be allowed to hidden when there are more than one server */
        canToggleVisibility: servers.length === 1
      });
      if (server === this.b.remoteExtensionManagementServer && this.b.localExtensionManagementServer) {
        this.B($hJ(class InstallLocalExtensionsInRemoteAction2 extends $gJ {
          constructor() {
            super({
              id: "workbench.extensions.installLocalExtensions",
              get title() {
                return localize2(6835, "Install Local Extensions in '{0}'...", server.label);
              },
              category: REMOTE_CATEGORY,
              icon: $hCb,
              f1: true,
              menu: {
                id: $bJ.ViewTitle,
                when: $7m.equals("view", id2),
                group: "navigation"
              }
            });
          }
          run(accessor) {
            return accessor.get($Pk).createInstance($EDb).run();
          }
        }));
      }
    }
    if (this.b.localExtensionManagementServer && this.b.remoteExtensionManagementServer) {
      this.B($hJ(class InstallRemoteExtensionsInLocalAction2 extends $gJ {
        constructor() {
          super({
            id: "workbench.extensions.actions.installLocalExtensionsInRemote",
            title: localize2(6836, "Install Remote Extensions Locally..."),
            category: REMOTE_CATEGORY,
            f1: true
          });
        }
        run(accessor) {
          return accessor.get($Pk).createInstance($FDb, "workbench.extensions.actions.installLocalExtensionsInRemote").run();
        }
      }));
    }
    viewDescriptors.push({
      id: "workbench.views.extensions.popular",
      name: localize2(6837, "Popular"),
      ctorDescriptor: new $Nk($sdc, [{ hideBadge: true }]),
      when: $7m.and($Sdc, $7m.not("hasInstalledExtensions"), $Jzb),
      weight: 60,
      order: 2,
      canToggleVisibility: false
    });
    viewDescriptors.push({
      id: "extensions.recommendedList",
      name: localize2(6838, "Recommended"),
      ctorDescriptor: new $Nk($Fdc, [{ flexibleHeight: true }]),
      when: $7m.and($Sdc, SortByUpdateDateContext.negate(), $7m.not("config.extensions.showRecommendationsOnlyOnDemand"), $Jzb),
      weight: 40,
      order: 3,
      canToggleVisibility: true
    });
    if (servers.length === 1) {
      viewDescriptors.push({
        id: "workbench.views.extensions.enabled",
        name: localize2(6839, "Enabled"),
        ctorDescriptor: new $Nk($udc, [{}]),
        when: $7m.and($Sdc, $7m.has("hasInstalledExtensions")),
        hideByDefault: true,
        weight: 40,
        order: 4,
        canToggleVisibility: true
      });
      viewDescriptors.push({
        id: "workbench.views.extensions.disabled",
        name: localize2(6840, "Disabled"),
        ctorDescriptor: new $Nk($vdc, [{}]),
        when: $7m.and($Sdc, $7m.has("hasInstalledExtensions")),
        hideByDefault: true,
        weight: 10,
        order: 5,
        canToggleVisibility: true
      });
    }
    return viewDescriptors;
  }
  m() {
    const viewDescriptors = [];
    viewDescriptors.push({
      id: "workbench.views.extensions.marketplace",
      name: localize2(6841, "Marketplace"),
      ctorDescriptor: new $Nk($Edc, [{}]),
      when: $7m.and($7m.has("searchMarketplaceExtensions"))
    });
    viewDescriptors.push({
      id: "workbench.views.extensions.searchInstalled",
      name: localize2(6842, "Installed"),
      ctorDescriptor: new $Nk($rdc, [{}]),
      when: $7m.or($7m.has("searchInstalledExtensions"), $7m.has("installedExtensions"))
    });
    viewDescriptors.push({
      id: "workbench.views.extensions.searchRecentlyUpdated",
      name: localize2(6843, "Recently Updated"),
      ctorDescriptor: new $Nk($xdc, [{}]),
      when: $7m.or(SearchExtensionUpdatesContext, $7m.has("searchRecentlyUpdatedExtensions")),
      order: 2
    });
    viewDescriptors.push({
      id: "workbench.views.extensions.searchEnabled",
      name: localize2(6844, "Enabled"),
      ctorDescriptor: new $Nk($rdc, [{}]),
      when: $7m.and($7m.has("searchEnabledExtensions"))
    });
    viewDescriptors.push({
      id: "workbench.views.extensions.searchDisabled",
      name: localize2(6845, "Disabled"),
      ctorDescriptor: new $Nk($rdc, [{}]),
      when: $7m.and($7m.has("searchDisabledExtensions"))
    });
    viewDescriptors.push({
      id: $Dzb,
      name: localize2(6846, "Available Updates"),
      ctorDescriptor: new $Nk($wdc, [{}]),
      when: $7m.or(SearchExtensionUpdatesContext, $7m.has("searchOutdatedExtensions")),
      order: 1
    });
    viewDescriptors.push({
      id: "workbench.views.extensions.searchBuiltin",
      name: localize2(6847, "Builtin"),
      ctorDescriptor: new $Nk($rdc, [{}]),
      when: $7m.and($7m.has("searchBuiltInExtensions"))
    });
    viewDescriptors.push({
      id: "workbench.views.extensions.searchWorkspaceUnsupported",
      name: localize2(6848, "Workspace Unsupported"),
      ctorDescriptor: new $Nk($rdc, [{}]),
      when: $7m.and($7m.has("searchWorkspaceUnsupportedExtensions"))
    });
    return viewDescriptors;
  }
  n() {
    const viewDescriptors = [];
    viewDescriptors.push({
      id: $Czb,
      name: localize2(6849, "Workspace Recommendations"),
      ctorDescriptor: new $Nk($Hdc, [{}]),
      when: $7m.and($7m.has("recommendedExtensions"), $epb.notEqualsTo("empty")),
      order: 1
    });
    viewDescriptors.push({
      id: "workbench.views.extensions.otherRecommendations",
      name: localize2(6850, "Other Recommendations"),
      ctorDescriptor: new $Nk($Gdc, [{}]),
      when: $7m.has("recommendedExtensions"),
      order: 2
    });
    return viewDescriptors;
  }
  s() {
    const viewDescriptors = [];
    const configuredCategories = ["themes", "programming languages"];
    const otherCategories = $4z.filter((c) => !configuredCategories.includes(c.toLowerCase()));
    otherCategories.push($qdc);
    const otherCategoriesQuery = `${otherCategories.map((c) => `category:"${c}"`).join(" ")} ${configuredCategories.map((c) => `category:"-${c}"`).join(" ")}`;
    viewDescriptors.push({
      id: "workbench.views.extensions.builtinFeatureExtensions",
      name: localize2(6851, "Features"),
      ctorDescriptor: new $Nk($ydc, [{ query: `@builtin ${otherCategoriesQuery}` }]),
      when: $7m.has("builtInExtensions")
    });
    viewDescriptors.push({
      id: "workbench.views.extensions.builtinThemeExtensions",
      name: localize2(6852, "Themes"),
      ctorDescriptor: new $Nk($ydc, [{ query: `@builtin category:themes` }]),
      when: $7m.has("builtInExtensions")
    });
    viewDescriptors.push({
      id: "workbench.views.extensions.builtinProgrammingLanguageExtensions",
      name: localize2(6853, "Programming Languages"),
      ctorDescriptor: new $Nk($ydc, [{ query: `@builtin category:"programming languages"` }]),
      when: $7m.has("builtInExtensions")
    });
    return viewDescriptors;
  }
  u() {
    const viewDescriptors = [];
    viewDescriptors.push({
      id: "workbench.views.extensions.untrustedUnsupportedExtensions",
      name: localize2(6854, "Disabled in Restricted Mode"),
      ctorDescriptor: new $Nk($zdc, [{}]),
      when: $7m.and(SearchUnsupportedWorkspaceExtensionsContext)
    });
    viewDescriptors.push({
      id: "workbench.views.extensions.untrustedPartiallySupportedExtensions",
      name: localize2(6855, "Limited in Restricted Mode"),
      ctorDescriptor: new $Nk($Adc, [{}]),
      when: $7m.and(SearchUnsupportedWorkspaceExtensionsContext)
    });
    viewDescriptors.push({
      id: "workbench.views.extensions.virtualUnsupportedExtensions",
      name: localize2(6856, "Disabled in Virtual Workspaces"),
      ctorDescriptor: new $Nk($Bdc, [{}]),
      when: $7m.and($lpb, SearchUnsupportedWorkspaceExtensionsContext)
    });
    viewDescriptors.push({
      id: "workbench.views.extensions.virtualPartiallySupportedExtensions",
      name: localize2(6857, "Limited in Virtual Workspaces"),
      ctorDescriptor: new $Nk($Cdc, [{}]),
      when: $7m.and($lpb, SearchUnsupportedWorkspaceExtensionsContext)
    });
    return viewDescriptors;
  }
  w() {
    const viewDescriptors = [];
    viewDescriptors.push({
      id: "workbench.views.extensions.deprecatedExtensions",
      name: localize2(6858, "Deprecated"),
      ctorDescriptor: new $Nk($Ddc, [{}]),
      when: $7m.and(SearchDeprecatedExtensionsContext)
    });
    return viewDescriptors;
  }
};
$Zdc = __decorate([
  __param(0, $nzb),
  __param(1, $ZI),
  __param(2, $$M),
  __param(3, $on)
], $Zdc);
var $1dc = class $1dc2 extends $oqb {
  constructor(layoutService, telemetryService, Zb, instantiationService, $b3, ac, bc, cc, dc, themeService, configurationService, storageService, contextService, ec, contextMenuService, extensionService, viewDescriptorService, fc, gc) {
    super($tzb, { mergeViewWithContainerWhenSingleView: true }, instantiationService, configurationService, layoutService, contextMenuService, telemetryService, extensionService, themeService, storageService, contextService, viewDescriptorService);
    this.Zb = Zb;
    this.$b = $b3;
    this.ac = ac;
    this.bc = bc;
    this.cc = cc;
    this.dc = dc;
    this.ec = ec;
    this.fc = fc;
    this.gc = gc;
    this.ic = this.B(new $4c());
    this.Tb = new $Sh(500);
    this.Ab = $Ydc.bindTo(ec);
    this.Bb = $Sdc.bindTo(ec);
    this.Cb = $Tdc.bindTo(ec);
    this.Db = $Udc.bindTo(ec);
    this.Eb = $Vdc.bindTo(ec);
    this.Fb = SortByUpdateDateContext.bindTo(ec);
    this.Gb = InstalledExtensionsContext.bindTo(ec);
    this.Hb = SearchInstalledExtensionsContext.bindTo(ec);
    this.Ib = SearchRecentlyUpdatedExtensionsContext.bindTo(ec);
    this.Jb = SearchExtensionUpdatesContext.bindTo(ec);
    this.Qb = SearchUnsupportedWorkspaceExtensionsContext.bindTo(ec);
    this.Rb = SearchDeprecatedExtensionsContext.bindTo(ec);
    this.Kb = SearchOutdatedExtensionsContext.bindTo(ec);
    this.Lb = SearchEnabledExtensionsContext.bindTo(ec);
    this.Mb = SearchDisabledExtensionsContext.bindTo(ec);
    this.Nb = HasInstalledExtensionsContext.bindTo(ec);
    this.Ob = $Wdc.bindTo(ec);
    this.Pb = SearchBuiltInExtensionsContext.bindTo(ec);
    this.Sb = $Xdc.bindTo(ec);
    this.B(this.dc.onDidPaneCompositeOpen((e) => {
      if (e.viewContainerLocation === 0) {
        this.tc(e.composite);
      }
    }, this));
    this.B(ac.onReset(() => this.refresh()));
    this.Yb = this.F(
      1,
      1
      /* StorageTarget.MACHINE */
    );
  }
  get searchValue() {
    return this.Wb?.getValue();
  }
  create(parent) {
    parent.classList.add("extensions-viewlet");
    this.Ub = parent;
    const overlay = $bk(this.Ub, $(".overlay"));
    const overlayBackgroundColor = this.z($Vnb) ?? "";
    overlay.style.backgroundColor = overlayBackgroundColor;
    $ik(overlay);
    this.Vb = $bk(this.Ub, $(".header"));
    const placeholder = localize(6817, null);
    const searchValue = this.Yb["query.value"] ? this.Yb["query.value"] : "";
    const searchContainer = $bk(this.Vb, $(".extensions-search-container"));
    this.Wb = this.B(this.bb.createInstance($NZb, `${$tzb}.searchbox`, searchContainer, {
      triggerCharacters: ["@"],
      sortKey: (item) => {
        if (item.indexOf(":") === -1) {
          return "a";
        } else if (/ext:/.test(item) || /id:/.test(item) || /tag:/.test(item)) {
          return "b";
        } else if (/sort:/.test(item)) {
          return "c";
        } else {
          return "d";
        }
      },
      provideResults: (query) => $pdc.suggestions(query)
    }, placeholder, "extensions:searchinput", { placeholderText: placeholder, value: searchValue }));
    this.Xb = $bk(this.Vb, $(".notification-container.hidden", { "tabindex": "0" }));
    this.jc();
    this.B(this.ac.onDidChangeExtensionsNotification(() => this.jc()));
    this.kc();
    if (this.Wb.getValue()) {
      this.lc();
    }
    this.B(this.Wb.onInputDidChange(() => {
      this.Cb.set($pdc.parse(this.Wb?.getValue() ?? "").sortBy);
      this.lc();
    }, this));
    this.B(this.Wb.onShouldFocusResults(() => this.sc(), this));
    const controlElement = $bk(searchContainer, $(".extensions-search-actions-container"));
    this.B(this.bb.createInstance($4$, controlElement, $Ozb, {
      toolbarOptions: {
        primaryGroup: () => true
      },
      actionViewItemProvider: (action, options3) => $X$(this.bb, action, options3)
    }));
    this.B(new $Ak(this.Ub, {
      onDragEnter: (e) => {
        if (this.wc(e)) {
          $hk(overlay);
        }
      },
      onDragLeave: (e) => {
        if (this.wc(e)) {
          $ik(overlay);
        }
      },
      onDragOver: (e) => {
        if (this.wc(e)) {
          e.dataTransfer.dropEffect = "copy";
        }
      },
      onDrop: async (e) => {
        if (this.wc(e)) {
          $ik(overlay);
          const vsixs = $Mb((await this.bb.invokeFunction((accessor) => $w_(accessor, e))).map((editor) => editor.resource && $th(editor.resource) === ".vsix" ? editor.resource : void 0));
          if (vsixs.length > 0) {
            try {
              await this.gc.executeCommand($Gzb, vsixs);
            } catch (err) {
              this.cc.error(err);
            }
          }
        }
      }
    }));
    super.create($bk(this.Ub, $(".extensions")));
    const focusTracker = this.B($_j(this.Ub));
    const isSearchBoxFocused = () => this.Wb?.inputWidget.hasWidgetFocus();
    this.B($iKb({
      name: "extensionsView",
      focusNotifiers: [focusTracker],
      focusNextWidget: () => {
        if (isSearchBoxFocused()) {
          this.sc();
        }
      },
      focusPreviousWidget: () => {
        if (!isSearchBoxFocused()) {
          this.Wb?.focus();
        }
      }
    }));
  }
  focus() {
    super.focus();
    this.Wb?.focus();
  }
  layout(dimension) {
    this.hc = dimension;
    if (this.Ub) {
      this.Ub.classList.toggle("narrow", dimension.width <= 250);
      this.Ub.classList.toggle("mini", dimension.width <= 200);
    }
    this.Wb?.layout(new $rj(dimension.width - 34 - /*padding*/
    8 - 24 * 2, 20));
    const searchBoxHeight = 20 + 21;
    const headerHeight = this.Vb && !!this.Xb?.childNodes.length ? this.Xb.clientHeight + searchBoxHeight + 10 : searchBoxHeight;
    this.Vb.style.height = `${headerHeight}px`;
    super.layout(new $rj(dimension.width, dimension.height - headerHeight));
  }
  getOptimalWidth() {
    return 400;
  }
  search(value) {
    if (this.Wb && this.Wb.getValue() !== value) {
      this.Wb.setValue(value);
    }
  }
  async refresh() {
    await this.kc();
    this.oc(true);
    if (this.cb.getValue($yzb)) {
      this.ac.checkForUpdates();
    }
  }
  jc() {
    if (!this.Xb) {
      return;
    }
    $$i(this.Xb);
    this.ic.value = new $2c();
    const status = this.ac.getExtensionsNotification();
    const query = status?.extensions.map((extension) => `@id:${extension.identifier.id}`).join(" ");
    if (status && (query === this.Wb?.getValue() || !this.Db.get())) {
      this.Xb.setAttribute("aria-label", status.message);
      this.Xb.classList.remove("hidden");
      const messageContainer = $bk(this.Xb, $(".message-container"));
      $bk(messageContainer, $("span")).className = SeverityIcon.className(status.severity);
      $bk(messageContainer, $("span.message", void 0, status.message));
      const showAction = $bk(messageContainer, $("span.message-text-action", {
        "tabindex": "0",
        "role": "button",
        "aria-label": `${status.message}. ${localize(6818, null)}`
      }, localize(6819, null)));
      this.ic.value.add($_i(showAction, $7j.CLICK, () => this.search(query ?? "")));
      this.ic.value.add($_i(showAction, $7j.KEY_DOWN, (e) => {
        const standardKeyboardEvent = new $if(e);
        if (standardKeyboardEvent.keyCode === 3 || standardKeyboardEvent.keyCode === 10) {
          this.search(query ?? "");
        }
        standardKeyboardEvent.stopPropagation();
      }));
      const dismissAction = $bk(this.Xb, $(`span.message-action${ThemeIcon.asCSSSelector($6l.close)}`, {
        "tabindex": "0",
        "role": "button",
        "aria-label": localize(6820, null),
        "title": localize(6821, null)
      }));
      this.ic.value.add($_i(dismissAction, $7j.CLICK, () => status.dismiss()));
      this.ic.value.add($_i(dismissAction, $7j.KEY_DOWN, (e) => {
        const standardKeyboardEvent = new $if(e);
        if (standardKeyboardEvent.keyCode === 3 || standardKeyboardEvent.keyCode === 10) {
          status.dismiss();
        }
        standardKeyboardEvent.stopPropagation();
      }));
    } else {
      this.Xb.removeAttribute("aria-label");
      this.Xb.classList.add("hidden");
    }
    if (this.hc) {
      this.layout(this.hc);
    }
  }
  async kc() {
    const result = await this.ac.queryLocal();
    this.Nb.set(result.some((r2) => !r2.isBuiltin));
  }
  lc() {
    this.Tb.trigger(() => this.oc(), this.Wb && this.Wb.getValue() ? 500 : 0).then(void 0, (err) => this.vc(err));
  }
  mc() {
    return this.Wb ? this.Wb.getValue().trim().replace(/@category/g, "category").replace(/@tag:/g, "tag:").replace(/@ext:/g, "ext:").replace(/@featured/g, "featured").replace(/@popular/g, this.bc.webExtensionManagementServer && !this.bc.localExtensionManagementServer && !this.bc.remoteExtensionManagementServer ? "@web" : "@popular") : "";
  }
  I() {
    const value = this.Wb ? this.Wb.getValue() : "";
    if ($rdc.isLocalExtensionsQuery(value)) {
      this.Yb["query.value"] = value;
    } else {
      this.Yb["query.value"] = "";
    }
    super.I();
  }
  oc(refresh) {
    const value = this.mc();
    this.ec.bufferChangeEvents(() => {
      const isRecommendedExtensionsQuery = $rdc.isRecommendedExtensionsQuery(value);
      this.Eb.set(value.trim() !== "");
      this.Ab.set(value);
      this.Gb.set($rdc.isInstalledExtensionsQuery(value));
      this.Hb.set($rdc.isSearchInstalledExtensionsQuery(value));
      this.Ib.set($rdc.isSearchRecentlyUpdatedQuery(value) && !$rdc.isSearchExtensionUpdatesQuery(value));
      this.Kb.set($rdc.isOutdatedExtensionsQuery(value) && !$rdc.isSearchExtensionUpdatesQuery(value));
      this.Jb.set($rdc.isSearchExtensionUpdatesQuery(value));
      this.Lb.set($rdc.isEnabledExtensionsQuery(value));
      this.Mb.set($rdc.isDisabledExtensionsQuery(value));
      this.Pb.set($rdc.isSearchBuiltInExtensionsQuery(value));
      this.Qb.set($rdc.isSearchWorkspaceUnsupportedExtensionsQuery(value));
      this.Rb.set($rdc.isSearchDeprecatedExtensionsQuery(value));
      this.Ob.set($rdc.isBuiltInExtensionsQuery(value));
      this.Sb.set(isRecommendedExtensionsQuery);
      this.Db.set(!!value && !$rdc.isLocalExtensionsQuery(value) && !isRecommendedExtensionsQuery);
      this.Fb.set($rdc.isSortUpdateDateQuery(value));
      this.Bb.set(!value || $rdc.isSortInstalledExtensionsQuery(value));
    });
    this.jc();
    return this.uc(Promise.all(this.panes.map((view) => view.show(this.mc(), refresh).then((model) => this.qc(model.length, view.id))))).then(() => void 0);
  }
  tb(added) {
    const addedViews = super.tb(added);
    this.uc(Promise.all(addedViews.map((addedView) => addedView.show(this.mc()).then((model) => this.qc(model.length, addedView.id)))));
    return addedViews;
  }
  qc(count, viewId) {
    const view = this.P.visibleViewDescriptors.find((view2) => view2.id === viewId);
    switch (count) {
      case 0:
        break;
      case 1:
        if (view) {
          $$Z(localize(6822, null, view.name.value));
        } else {
          $$Z(localize(6823, null));
        }
        break;
      default:
        if (view) {
          $$Z(localize(6824, null, count, view.name.value));
        } else {
          $$Z(localize(6825, null, count));
        }
        break;
    }
  }
  rc() {
    for (const pane of this.panes) {
      if (pane.isExpanded() && pane instanceof $rdc) {
        return pane;
      }
    }
    return void 0;
  }
  sc() {
    const pane = this.rc();
    if (pane && pane.count() > 0) {
      pane.focus();
    }
  }
  tc(viewlet) {
    if (!viewlet || viewlet.getId() === $tzb) {
      return;
    }
    if (this.cb.getValue($zzb)) {
      const promises = this.$b.groups.map((group2) => {
        const editors = group2.editors.filter((input) => input instanceof $szb);
        return group2.closeEditors(editors);
      });
      Promise.all(promises);
    }
  }
  uc(promise) {
    return this.Zb.withProgress({
      location: 5
      /* ProgressLocation.Extensions */
    }, () => promise);
  }
  vc(err) {
    if ($kb(err)) {
      return;
    }
    const message = err && err.message || "";
    if (/ECONNREFUSED/.test(message)) {
      const error = $3m(localize(6826, null), [
        new $Um("open user settings", localize(6827, null), void 0, true, () => this.fc.openUserSettings())
      ]);
      this.cc.error(error);
      return;
    }
    this.cc.error(err);
  }
  wc(e) {
    if (e.dataTransfer) {
      const typesLowerCase = e.dataTransfer.types.map((t) => t.toLocaleLowerCase());
      return typesLowerCase.indexOf("files") !== -1;
    }
    return false;
  }
};
$1dc = __decorate([
  __param(0, $Vlb),
  __param(1, $zv),
  __param(2, $TJ),
  __param(3, $Pk),
  __param(4, $iJ),
  __param(5, $vzb),
  __param(6, $nzb),
  __param(7, $PJ),
  __param(8, $uqb),
  __param(9, $gs),
  __param(10, $kl),
  __param(11, $jv),
  __param(12, $Zk),
  __param(13, $on),
  __param(14, $50),
  __param(15, $wN),
  __param(16, $$M),
  __param(17, $TK),
  __param(18, $sn)
], $1dc);
var $2dc = class $2dc2 extends $3c {
  constructor(b, f, g, h3) {
    super();
    this.b = b;
    this.f = f;
    this.g = g;
    this.h = h3;
    this.a = this.B(new $4c());
    this.j();
    this.B(Event2.any(Event2.debounce(f.onChange, () => void 0, 100, void 0, void 0, void 0, this.q), f.onDidChangeExtensionsNotification)(this.j, this));
  }
  j() {
    this.a.clear();
    let badge;
    const extensionsNotification = this.f.getExtensionsNotification();
    if (extensionsNotification) {
      if (extensionsNotification.severity === severity_default.Warning) {
        badge = new $zqb(() => extensionsNotification.message);
      }
    } else {
      const actionRequired = this.h.getValue($Azb) === true ? [] : this.f.installed.filter((e) => e.runtimeState !== void 0);
      const outdated = this.f.outdated.reduce((r2, e) => r2 + (this.g.isEnabled(e.local) && !actionRequired.includes(e) ? 1 : 0), 0);
      const newBadgeNumber = outdated + actionRequired.length;
      if (newBadgeNumber > 0) {
        let msg = "";
        if (outdated) {
          msg += outdated === 1 ? localize(6828, null, outdated) : localize(6829, null, outdated);
        }
        if (outdated > 0 && actionRequired.length > 0) {
          msg += ", ";
        }
        if (actionRequired.length) {
          msg += actionRequired.length === 1 ? localize(6830, null, actionRequired.length) : localize(6831, null, actionRequired.length);
        }
        badge = new $wqb(newBadgeNumber, () => msg);
      }
    }
    if (badge) {
      this.a.value = this.b.showViewContainerActivity($tzb, { badge });
    }
  }
};
$2dc = __decorate([
  __param(0, $vqb),
  __param(1, $vzb),
  __param(2, $qzb),
  __param(3, $kl)
], $2dc);
var $3dc = class $3dc2 {
  constructor(a, b, d, f, g) {
    this.a = a;
    this.b = b;
    this.d = d;
    this.f = f;
    this.g = g;
    if (!this.g.disableExtensions) {
      this.h();
    }
  }
  h() {
    this.i().then(() => $Wh(1e3 * 60 * 5)).then(() => this.h());
  }
  i() {
    return this.a.getExtensionsControlManifest().then((extensionsControlManifest) => {
      return this.a.getInstalled(
        1
        /* ExtensionType.User */
      ).then((installed) => {
        const maliciousExtensions = installed.filter((e) => extensionsControlManifest.malicious.some((identifier2) => $DA(e.identifier, identifier2)));
        if (maliciousExtensions.length) {
          return Promises.settled(maliciousExtensions.map((e) => this.a.uninstall(e).then(() => {
            this.f.prompt(severity_default.Warning, localize(6832, null, e.identifier.id), [{
              label: localize(6833, null),
              run: () => this.b.reload()
            }], {
              sticky: true,
              priority: NotificationPriority.URGENT
            });
          })));
        } else {
          return Promise.resolve(void 0);
        }
      }).then(() => void 0);
    }, (err) => this.d.error(err));
  }
};
$3dc = __decorate([
  __param(0, $sA),
  __param(1, $S4),
  __param(2, $wn),
  __param(3, $PJ),
  __param(4, $US)
], $3dc);

// out-build/vs/workbench/contrib/extensions/browser/extensionsActivationProgress.js
var $4dc = class $4dc2 {
  constructor(extensionService, progressService, logService) {
    const options3 = {
      location: 10,
      title: localize(6778, null)
    };
    let deferred;
    let count = 0;
    this.a = extensionService.onWillActivateByEvent((e) => {
      logService.trace("onWillActivateByEvent: ", e.event);
      if (!deferred) {
        deferred = new $gi();
        progressService.withProgress(options3, (_) => deferred.p);
      }
      count++;
      Promise.race([e.activation, $Wh(5e3, CancellationToken.None)]).finally(() => {
        if (--count === 0) {
          deferred.complete(void 0);
          deferred = void 0;
        }
      });
    });
  }
  dispose() {
    this.a.dispose();
  }
};
$4dc = __decorate([
  __param(0, $wN),
  __param(1, $TJ),
  __param(2, $wn)
], $4dc);

// out-build/vs/workbench/contrib/extensions/browser/extensionsDependencyChecker.js
var $5dc = class $5dc2 extends $3c {
  constructor(a, b, c, f) {
    super();
    this.a = a;
    this.b = b;
    this.c = c;
    this.f = f;
    $tn.registerCommand("workbench.extensions.installMissingDependencies", () => this.j());
    $dJ.appendMenuItem($bJ.CommandPalette, {
      command: {
        id: "workbench.extensions.installMissingDependencies",
        category: localize(6780, null),
        title: localize(6781, null)
      }
    });
  }
  async g() {
    const allMissingDependencies = await this.h();
    const localExtensions = await this.b.queryLocal();
    return allMissingDependencies.filter((id2) => localExtensions.every((l) => !$DA(l.identifier, { id: id2 })));
  }
  async h() {
    await this.a.whenInstalledExtensionsRegistered();
    const runningExtensionsIds = this.a.extensions.reduce((result, r2) => {
      result.add(r2.identifier.value.toLowerCase());
      return result;
    }, /* @__PURE__ */ new Set());
    const missingDependencies = /* @__PURE__ */ new Set();
    for (const extension of this.a.extensions) {
      if (extension.extensionDependencies) {
        extension.extensionDependencies.forEach((dep) => {
          if (!runningExtensionsIds.has(dep.toLowerCase())) {
            missingDependencies.add(dep);
          }
        });
      }
    }
    return [...missingDependencies.values()];
  }
  async j() {
    const missingDependencies = await this.g();
    if (missingDependencies.length) {
      const extensions = await this.b.getExtensions(missingDependencies.map((id2) => ({ id: id2 })), CancellationToken.None);
      if (extensions.length) {
        await Promises.settled(extensions.map((extension) => this.b.install(extension)));
        this.c.notify({
          severity: Severity2.Info,
          message: localize(6782, null),
          actions: {
            primary: [new $Um("realod", localize(6783, null), "", true, () => this.f.reload())]
          }
        });
      }
    } else {
      this.c.info(localize(6784, null));
    }
  }
};
$5dc = __decorate([
  __param(0, $wN),
  __param(1, $vzb),
  __param(2, $PJ),
  __param(3, $S4)
], $5dc);

// out-build/vs/workbench/contrib/extensions/browser/extensionsQuickAccess.js
var $6dc_1;
var $7dc_1;
var $6dc = class $6dc2 extends $rhb {
  static {
    $6dc_1 = this;
  }
  static {
    this.PREFIX = "ext install ";
  }
  constructor(a, b, h3, j, m) {
    super($6dc_1.PREFIX);
    this.a = a;
    this.b = b;
    this.h = h3;
    this.j = j;
    this.m = m;
  }
  g(filter, disposables, token) {
    if (!filter) {
      return [{
        label: localize(6809, null)
      }];
    }
    const genericSearchPickItem = {
      label: localize(6810, null, filter),
      accept: () => this.a.openSearch(filter)
    };
    if (/\./.test(filter)) {
      return this.r(filter, genericSearchPickItem, token);
    }
    return [genericSearchPickItem];
  }
  async r(filter, fallback2, token) {
    try {
      const [galleryExtension] = await this.b.getExtensions([{ id: filter }], token);
      if (token.isCancellationRequested) {
        return [];
      }
      if (!galleryExtension) {
        return [fallback2];
      }
      return [{
        label: localize(6811, null, filter),
        accept: () => this.s(galleryExtension, filter)
      }];
    } catch (error) {
      if (token.isCancellationRequested) {
        return [];
      }
      this.m.error(error);
      return [fallback2];
    }
  }
  async s(extension, name) {
    try {
      await this.a.openSearch(`@id:${name}`);
      await this.h.installFromGallery(extension);
    } catch (error) {
      this.j.error(error);
    }
  }
};
$6dc = $6dc_1 = __decorate([
  __param(0, $vzb),
  __param(1, $pA),
  __param(2, $sA),
  __param(3, $PJ),
  __param(4, $wn)
], $6dc);
var $7dc = class $7dc2 extends $rhb {
  static {
    $7dc_1 = this;
  }
  static {
    this.PREFIX = "ext ";
  }
  constructor(a) {
    super($7dc_1.PREFIX);
    this.a = a;
  }
  g() {
    return [{
      label: localize(6812, null),
      accept: () => this.a.openSearch("")
    }];
  }
};
$7dc = $7dc_1 = __decorate([
  __param(0, $vzb)
], $7dc);

// out-build/vs/workbench/contrib/extensions/browser/extensionRecommendations.js
var $8dc = class extends $3c {
  constructor() {
    super(...arguments);
    this.f = null;
  }
  get activated() {
    return this.f !== null;
  }
  activate() {
    if (!this.f) {
      this.f = this.c();
    }
    return this.f;
  }
};

// out-build/vs/workbench/contrib/extensions/browser/exeBasedRecommendations.js
var $9dc = class $9dc2 extends $8dc {
  get otherRecommendations() {
    return this.a.map((tip) => this.r(tip));
  }
  get importantRecommendations() {
    return this.b.map((tip) => this.r(tip));
  }
  get recommendations() {
    return [...this.importantRecommendations, ...this.otherRecommendations];
  }
  constructor(g) {
    super();
    this.g = g;
    this.a = [];
    this.b = [];
  }
  getRecommendations(exe) {
    const important = this.b.filter((tip) => tip.exeName.toLowerCase() === exe.toLowerCase()).map((tip) => this.r(tip));
    const others = this.a.filter((tip) => tip.exeName.toLowerCase() === exe.toLowerCase()).map((tip) => this.r(tip));
    return { important, others };
  }
  async c() {
    this.a = await this.g.getOtherExecutableBasedTips();
    await this.m();
  }
  async m() {
    if (!this.j) {
      this.j = this.n();
    }
    return this.j;
  }
  async n() {
    const importantExeBasedRecommendations = /* @__PURE__ */ new Map();
    this.b = await this.g.getImportantExecutableBasedTips();
    this.b.forEach((tip) => importantExeBasedRecommendations.set(tip.extensionId.toLowerCase(), tip));
    return importantExeBasedRecommendations;
  }
  r(tip) {
    return {
      extension: tip.extensionId.toLowerCase(),
      reason: {
        reasonId: 2,
        reasonText: localize(6356, null, tip.exeFriendlyName)
      }
    };
  }
};
$9dc = __decorate([
  __param(0, $wA)
], $9dc);

// out-build/vs/workbench/contrib/extensions/browser/workspaceRecommendations.js
var WORKSPACE_EXTENSIONS_FOLDER = ".vscode/extensions";
var $0dc = class $0dc2 extends $8dc {
  get recommendations() {
    return this.g;
  }
  get ignoredRecommendations() {
    return this.j;
  }
  constructor(r2, s, t, u, w, y) {
    super();
    this.r = r2;
    this.s = s;
    this.t = t;
    this.u = u;
    this.w = w;
    this.y = y;
    this.g = [];
    this.h = this.B(new $ze());
    this.onDidChangeRecommendations = this.h.event;
    this.j = [];
    this.m = [];
    this.n = this.B(new $8h(() => this.C(), 1e3));
  }
  async c() {
    this.m = await this.D();
    await this.F();
    this.B(this.r.onDidChangeExtensionsConfigs(() => this.H()));
    for (const folder of this.s.getWorkspace().folders) {
      this.B(this.u.watch(this.t.extUri.joinPath(folder.uri, WORKSPACE_EXTENSIONS_FOLDER)));
    }
    this.B(this.s.onDidChangeWorkspaceFolders(() => this.n.schedule()));
    this.B(this.u.onDidFilesChange((e) => {
      if (this.s.getWorkspace().folders.some((folder) => e.affects(
        this.t.extUri.joinPath(folder.uri, WORKSPACE_EXTENSIONS_FOLDER),
        1,
        2
        /* FileChangeType.DELETED */
      ))) {
        this.n.schedule();
      }
    }));
  }
  async C() {
    const existing = this.m;
    this.m = await this.D();
    if (!$zb(existing, this.m, (a, b) => this.t.extUri.isEqual(a, b))) {
      this.H();
    }
  }
  async D() {
    const workspaceExtensions = [];
    for (const workspaceFolder of this.s.getWorkspace().folders) {
      const extensionsLocaiton = this.t.extUri.joinPath(workspaceFolder.uri, WORKSPACE_EXTENSIONS_FOLDER);
      try {
        const stat = await this.u.resolve(extensionsLocaiton);
        for (const extension of stat.children ?? []) {
          if (!extension.isDirectory) {
            continue;
          }
          workspaceExtensions.push(extension.resource);
        }
      } catch (error) {
      }
    }
    if (workspaceExtensions.length) {
      const resourceExtensions = await this.w.getExtensions(workspaceExtensions);
      return resourceExtensions.map((extension) => extension.location);
    }
    return [];
  }
  /**
   * Parse all extensions.json files, fetch workspace recommendations, filter out invalid and unwanted ones
   */
  async F() {
    const extensionsConfigs = await this.r.getExtensionsConfigs();
    const { invalidRecommendations, message } = await this.G(extensionsConfigs);
    if (invalidRecommendations.length) {
      this.y.warn(`The ${invalidRecommendations.length} extension(s) below, in workspace recommendations have issues:
${message}`);
    }
    this.g = [];
    this.j = [];
    for (const extensionsConfig of extensionsConfigs) {
      if (extensionsConfig.unwantedRecommendations) {
        for (const unwantedRecommendation of extensionsConfig.unwantedRecommendations) {
          if (invalidRecommendations.indexOf(unwantedRecommendation) === -1) {
            this.j.push(unwantedRecommendation);
          }
        }
      }
      if (extensionsConfig.recommendations) {
        for (const extensionId of extensionsConfig.recommendations) {
          if (invalidRecommendations.indexOf(extensionId) === -1) {
            this.g.push({
              extension: extensionId,
              reason: {
                reasonId: 0,
                reasonText: localize(6970, null)
              }
            });
          }
        }
      }
    }
    for (const extension of this.m) {
      this.g.push({
        extension,
        reason: {
          reasonId: 0,
          reasonText: localize(6971, null)
        }
      });
    }
  }
  async G(contents) {
    const validExtensions = [];
    const invalidExtensions = [];
    let message = "";
    const allRecommendations = $Rb(contents.flatMap(({ recommendations }) => recommendations || []));
    const regEx = new RegExp($cA);
    for (const extensionId of allRecommendations) {
      if (regEx.test(extensionId)) {
        validExtensions.push(extensionId);
      } else {
        invalidExtensions.push(extensionId);
        message += `${extensionId} (bad format) Expected: <provider>.<name>
`;
      }
    }
    return { validRecommendations: validExtensions, invalidRecommendations: invalidExtensions, message };
  }
  async H() {
    await this.F();
    this.h.fire();
  }
};
$0dc = __decorate([
  __param(0, $FBb),
  __param(1, $Zk),
  __param(2, $vl),
  __param(3, $km),
  __param(4, $pzb),
  __param(5, $PJ)
], $0dc);

// 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 = {}));
function $$dc(source) {
  switch (source) {
    case 1:
      return "file";
    case 2:
      return "workspace";
    case 3:
      return "exe";
  }
}
var RecommendationsNotificationResult;
(function(RecommendationsNotificationResult2) {
  RecommendationsNotificationResult2["Ignored"] = "ignored";
  RecommendationsNotificationResult2["Cancelled"] = "cancelled";
  RecommendationsNotificationResult2["TooMany"] = "toomany";
  RecommendationsNotificationResult2["IncompatibleWindow"] = "incompatibleWindow";
  RecommendationsNotificationResult2["Accepted"] = "reacted";
})(RecommendationsNotificationResult || (RecommendationsNotificationResult = {}));
var $_dc = $Qk("IExtensionRecommendationNotificationService");

// out-build/vs/workbench/contrib/extensions/browser/fileBasedRecommendations.js
var promptedRecommendationsStorageKey = "fileBasedRecommendations/promptedRecommendations";
var recommendationsStorageKey = "extensionsAssistant/recommendations";
var milliSecondsInADay = 1e3 * 60 * 60 * 24;
var $aec = class $aec2 extends $8dc {
  get recommendations() {
    const recommendations = [];
    [...this.j.keys()].sort((a, b) => {
      if (this.j.get(a).recommendedTime === this.j.get(b).recommendedTime) {
        if (this.m.has(a)) {
          return -1;
        }
        if (this.m.has(b)) {
          return 1;
        }
      }
      return this.j.get(a).recommendedTime > this.j.get(b).recommendedTime ? -1 : 1;
    }).forEach((extensionId) => {
      recommendations.push({
        extension: extensionId,
        reason: {
          reasonId: 1,
          reasonText: localize(6967, null)
        }
      });
    });
    return recommendations;
  }
  get importantRecommendations() {
    return this.recommendations.filter((e) => this.m.has(e.extension));
  }
  get otherRecommendations() {
    return this.recommendations.filter((e) => !this.m.has(e.extension));
  }
  constructor(n, r2, s, productService, t, u, w, y) {
    super();
    this.n = n;
    this.r = r2;
    this.s = s;
    this.t = t;
    this.u = u;
    this.w = w;
    this.y = y;
    this.h = /* @__PURE__ */ new Map();
    this.j = /* @__PURE__ */ new Map();
    this.m = /* @__PURE__ */ new Set();
    this.g = {};
    if (productService.extensionRecommendations) {
      for (const [extensionId, recommendation] of Object.entries(productService.extensionRecommendations)) {
        if (recommendation.onFileOpen) {
          this.g[extensionId.toLowerCase()] = recommendation.onFileOpen;
        }
      }
    }
  }
  async c() {
    if ($Mg(this.g)) {
      return;
    }
    await this.n.whenInitialized;
    const cachedRecommendations = this.N();
    const now = Date.now();
    Object.entries(cachedRecommendations).forEach(([key2, value]) => {
      const diff3 = (now - value) / milliSecondsInADay;
      if (diff3 <= 7 && this.g[key2]) {
        this.j.set(key2.toLowerCase(), { recommendedTime: value });
      }
    });
    this.B(this.r.onModelAdded((model) => this.C(model)));
    this.r.getModels().forEach((model) => this.C(model));
  }
  C(model) {
    const uri = model.uri.scheme === Schemas.vscodeNotebookCell ? CellUri.parse(model.uri)?.notebook : model.uri;
    if (!uri) {
      return;
    }
    const supportedSchemes = $Rb([Schemas.untitled, Schemas.file, Schemas.vscodeRemote, ...this.y.getWorkspace().folders.map((folder) => folder.uri.scheme)]);
    if (!uri || !supportedSchemes.includes(uri.scheme)) {
      return;
    }
    $Xh(() => this.D(uri, model), 0, this.q);
  }
  /**
   * Prompt the user to either install the recommended extension for the file type in the current editor model
   * or prompt to search the marketplace if it has extensions that can support the file type
   */
  D(uri, model, extensionRecommendations) {
    if (model.isDisposed()) {
      return;
    }
    const pattern = $th(uri).toLowerCase();
    extensionRecommendations = extensionRecommendations ?? this.h.get(pattern) ?? this.g;
    const extensionRecommendationEntries = Object.entries(extensionRecommendations);
    if (extensionRecommendationEntries.length === 0) {
      return;
    }
    const processedPathGlobs = /* @__PURE__ */ new Map();
    const installed = this.n.local;
    const recommendationsByPattern = {};
    const matchedRecommendations = {};
    const unmatchedRecommendations = {};
    let listenOnLanguageChange = false;
    const languageId = model.getLanguageId();
    for (const [extensionId, conditions] of extensionRecommendationEntries) {
      const conditionsByPattern = [];
      const matchedConditions = [];
      const unmatchedConditions = [];
      for (const condition of conditions) {
        let languageMatched = false;
        let pathGlobMatched = false;
        const isLanguageCondition = !!condition.languages;
        const isFileContentCondition = !!condition.contentPattern;
        if (isLanguageCondition || isFileContentCondition) {
          conditionsByPattern.push(condition);
        }
        if (isLanguageCondition) {
          if (condition.languages.includes(languageId)) {
            languageMatched = true;
          }
        }
        if (condition.pathGlob) {
          const pathGlob = condition.pathGlob;
          if (processedPathGlobs.get(pathGlob) ?? $Cl(condition.pathGlob, uri.with({ fragment: "" }).toString())) {
            pathGlobMatched = true;
          }
          processedPathGlobs.set(pathGlob, pathGlobMatched);
        }
        let matched = languageMatched || pathGlobMatched;
        if (pattern && !matched) {
          continue;
        }
        if (matched && condition.whenInstalled) {
          if (!condition.whenInstalled.every((id2) => installed.some((local) => $DA({ id: id2 }, local.identifier)))) {
            matched = false;
          }
        }
        if (matched && condition.whenNotInstalled) {
          if (installed.some((local) => condition.whenNotInstalled?.some((id2) => $DA({ id: id2 }, local.identifier)))) {
            matched = false;
          }
        }
        if (matched && isFileContentCondition) {
          if (!model.findMatches(condition.contentPattern, false, true, false, null, false).length) {
            matched = false;
          }
        }
        if (matched) {
          matchedConditions.push(condition);
          conditionsByPattern.pop();
        } else {
          if (isLanguageCondition || isFileContentCondition) {
            unmatchedConditions.push(condition);
            if (isLanguageCondition) {
              listenOnLanguageChange = true;
            }
          }
        }
      }
      if (matchedConditions.length) {
        matchedRecommendations[extensionId] = matchedConditions;
      }
      if (unmatchedConditions.length) {
        unmatchedRecommendations[extensionId] = unmatchedConditions;
      }
      if (conditionsByPattern.length) {
        recommendationsByPattern[extensionId] = conditionsByPattern;
      }
    }
    if (pattern) {
      this.h.set(pattern, recommendationsByPattern);
    }
    if (Object.keys(unmatchedRecommendations).length) {
      if (listenOnLanguageChange) {
        const disposables = new $2c();
        disposables.add(model.onDidChangeLanguage(() => {
          $Xh(() => {
            if (!disposables.isDisposed) {
              this.D(uri, model, unmatchedRecommendations);
              disposables.dispose();
            }
          }, 0, disposables);
        }));
        disposables.add(model.onWillDispose(() => disposables.dispose()));
      }
    }
    if (Object.keys(matchedRecommendations).length) {
      this.F(uri, model, matchedRecommendations);
    }
  }
  F(uri, model, extensionRecommendations) {
    let isImportantRecommendationForLanguage = false;
    const importantRecommendations = /* @__PURE__ */ new Set();
    const fileBasedRecommendations = /* @__PURE__ */ new Set();
    for (const [extensionId, conditions] of Object.entries(extensionRecommendations)) {
      for (const condition of conditions) {
        fileBasedRecommendations.add(extensionId);
        if (condition.important) {
          importantRecommendations.add(extensionId);
          this.m.add(extensionId);
        }
        if (condition.languages) {
          isImportantRecommendationForLanguage = true;
        }
      }
    }
    for (const recommendation of fileBasedRecommendations) {
      const filedBasedRecommendation = this.j.get(recommendation) || { recommendedTime: Date.now(), sources: [] };
      filedBasedRecommendation.recommendedTime = Date.now();
      this.j.set(recommendation, filedBasedRecommendation);
    }
    this.O();
    if (this.u.hasToIgnoreRecommendationNotifications()) {
      return;
    }
    const language = model.getLanguageId();
    const languageName = this.s.getLanguageName(language);
    if (importantRecommendations.size && this.G(languageName && isImportantRecommendationForLanguage && language !== $KF ? localize(6968, null, languageName) : $sh(uri), language, [...importantRecommendations])) {
      return;
    }
  }
  G(name, language, recommendations) {
    recommendations = this.L(recommendations);
    if (recommendations.length === 0) {
      return false;
    }
    recommendations = this.M(recommendations, this.n.local).filter((extensionId) => this.m.has(extensionId));
    const promptedRecommendations = language !== $KF ? this.I()[language] : void 0;
    if (promptedRecommendations) {
      recommendations = recommendations.filter((extensionId) => promptedRecommendations.includes(extensionId));
    }
    if (recommendations.length === 0) {
      return false;
    }
    this.H(recommendations, name, language);
    return true;
  }
  async H(extensions, name, language) {
    try {
      const result = await this.u.promptImportantExtensionsInstallNotification({
        extensions,
        name,
        source: 1
        /* RecommendationSource.FILE */
      });
      if (result === "reacted") {
        this.J(language, extensions);
      }
    } catch (error) {
    }
  }
  I() {
    return JSON.parse(this.t.get(promptedRecommendationsStorageKey, 0, "{}"));
  }
  J(language, extensions) {
    const promptedRecommendations = this.I();
    promptedRecommendations[language] = $Rb([...promptedRecommendations[language] ?? [], ...extensions]);
    this.t.store(
      promptedRecommendationsStorageKey,
      JSON.stringify(promptedRecommendations),
      0,
      0
      /* StorageTarget.USER */
    );
  }
  L(recommendationsToSuggest) {
    const ignoredRecommendations = [...this.w.ignoredRecommendations, ...this.u.ignoredRecommendations];
    return recommendationsToSuggest.filter((id2) => !ignoredRecommendations.includes(id2));
  }
  M(recommendationsToSuggest, installed) {
    const installedExtensionsIds = installed.reduce((result, i2) => {
      if (i2.enablementState !== 1) {
        result.add(i2.identifier.id.toLowerCase());
      }
      return result;
    }, /* @__PURE__ */ new Set());
    return recommendationsToSuggest.filter((id2) => !installedExtensionsIds.has(id2.toLowerCase()));
  }
  N() {
    let storedRecommendations = JSON.parse(this.t.get(recommendationsStorageKey, 0, "[]"));
    if (Array.isArray(storedRecommendations)) {
      storedRecommendations = storedRecommendations.reduce((result2, id2) => {
        result2[id2] = Date.now();
        return result2;
      }, {});
    }
    const result = {};
    Object.entries(storedRecommendations).forEach(([key2, value]) => {
      if (typeof value === "number") {
        result[key2.toLowerCase()] = value;
      }
    });
    return result;
  }
  O() {
    const storedRecommendations = {};
    this.j.forEach((value, key2) => storedRecommendations[key2] = value.recommendedTime);
    this.t.store(
      recommendationsStorageKey,
      JSON.stringify(storedRecommendations),
      0,
      1
      /* StorageTarget.MACHINE */
    );
  }
};
$aec = __decorate([
  __param(0, $vzb),
  __param(1, $sG),
  __param(2, $1E),
  __param(3, $Vu),
  __param(4, $jv),
  __param(5, $_dc),
  __param(6, $BBb),
  __param(7, $Zk)
], $aec);

// out-build/vs/workbench/contrib/extensions/browser/keymapRecommendations.js
var $bec = class $bec2 extends $8dc {
  get recommendations() {
    return this.a;
  }
  constructor(b) {
    super();
    this.b = b;
    this.a = [];
  }
  async c() {
    if (this.b.keymapExtensionTips) {
      this.a = this.b.keymapExtensionTips.map((extensionId) => ({
        extension: extensionId.toLowerCase(),
        reason: {
          reasonId: 6,
          reasonText: ""
        }
      }));
    }
  }
};
$bec = __decorate([
  __param(0, $Vu)
], $bec);

// out-build/vs/workbench/contrib/extensions/browser/languageRecommendations.js
var $cec = class $cec2 extends $8dc {
  get recommendations() {
    return this.a;
  }
  constructor(b) {
    super();
    this.b = b;
    this.a = [];
  }
  async c() {
    if (this.b.languageExtensionTips) {
      this.a = this.b.languageExtensionTips.map((extensionId) => ({
        extension: extensionId.toLowerCase(),
        reason: {
          reasonId: 6,
          reasonText: ""
        }
      }));
    }
  }
};
$cec = __decorate([
  __param(0, $Vu)
], $cec);

// out-build/vs/workbench/contrib/extensions/browser/configBasedRecommendations.js
var $dec = class $dec2 extends $8dc {
  get otherRecommendations() {
    return this.h;
  }
  get importantRecommendations() {
    return this.j;
  }
  get recommendations() {
    return [...this.importantRecommendations, ...this.otherRecommendations];
  }
  constructor(m, n) {
    super();
    this.m = m;
    this.n = n;
    this.a = [];
    this.b = [];
    this.g = this.B(new $ze());
    this.onDidChangeRecommendations = this.g.event;
    this.h = [];
    this.j = [];
  }
  async c() {
    await this.s();
    this.B(this.n.onDidChangeWorkspaceFolders((e) => this.t(e)));
  }
  async s() {
    const workspace2 = this.n.getWorkspace();
    const importantTips = /* @__PURE__ */ new Map();
    const otherTips = /* @__PURE__ */ new Map();
    for (const folder of workspace2.folders) {
      const configBasedTips = await this.m.getConfigBasedTips(folder.uri);
      for (const tip of configBasedTips) {
        if (tip.important) {
          importantTips.set(tip.extensionId, tip);
        } else {
          otherTips.set(tip.extensionId, tip);
        }
      }
    }
    this.a = [...importantTips.values()];
    this.b = [...otherTips.values()].filter((tip) => !importantTips.has(tip.extensionId));
    this.h = this.b.map((tip) => this.u(tip));
    this.j = this.a.map((tip) => this.u(tip));
  }
  async t(event) {
    if (event.added.length) {
      const oldImportantRecommended = this.a;
      await this.s();
      if (this.a.some((current) => oldImportantRecommended.every((old) => current.extensionId !== old.extensionId))) {
        this.g.fire();
      }
    }
  }
  u(tip) {
    return {
      extension: tip.extensionId,
      reason: {
        reasonId: 3,
        reasonText: localize(6355, null)
      },
      whenNotInstalled: tip.whenNotInstalled
    };
  }
};
$dec = __decorate([
  __param(0, $wA),
  __param(1, $Zk)
], $dec);

// out-build/vs/workbench/contrib/extensions/browser/webRecommendations.js
var $eec = class $eec2 extends $8dc {
  get recommendations() {
    return this.a;
  }
  constructor(b, g) {
    super();
    this.b = b;
    this.g = g;
    this.a = [];
  }
  async c() {
    const isOnlyWeb = this.g.webExtensionManagementServer && !this.g.localExtensionManagementServer && !this.g.remoteExtensionManagementServer;
    if (isOnlyWeb && Array.isArray(this.b.webExtensionTips)) {
      this.a = this.b.webExtensionTips.map((extensionId) => ({
        extension: extensionId.toLowerCase(),
        reason: {
          reasonId: 6,
          reasonText: localize(6969, null, this.b.nameLong)
        }
      }));
    }
  }
};
$eec = __decorate([
  __param(0, $Vu),
  __param(1, $nzb)
], $eec);

// out-build/vs/workbench/contrib/extensions/browser/remoteRecommendations.js
var $fec = class $fec2 extends $8dc {
  get recommendations() {
    return this.a;
  }
  constructor(b) {
    super();
    this.b = b;
    this.a = [];
  }
  async c() {
    const extensionTips = { ...this.b.remoteExtensionTips, ...this.b.virtualWorkspaceExtensionTips };
    const currentPlatform = $k($x);
    this.a = Object.values(extensionTips).filter(({ supportedPlatforms }) => !supportedPlatforms || supportedPlatforms.includes(currentPlatform)).map((extension) => ({
      extension: extension.extensionId.toLowerCase(),
      reason: {
        reasonId: 6,
        reasonText: ""
      }
    }));
  }
};
$fec = __decorate([
  __param(0, $Vu)
], $fec);

// out-build/vs/workbench/contrib/extensions/browser/extensionRecommendationsService.js
var $gec = class $gec2 extends $3c {
  constructor(instantiationService, s, t, u, w, y, z, C, D, F, G) {
    super();
    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 = G;
    this.r = this.B(new $ze());
    this.onDidChangeRecommendations = this.r.event;
    this.b = this.B(instantiationService.createInstance($0dc));
    this.a = this.B(instantiationService.createInstance($aec));
    this.c = this.B(instantiationService.createInstance($dec));
    this.f = this.B(instantiationService.createInstance($9dc));
    this.g = this.B(instantiationService.createInstance($bec));
    this.h = this.B(instantiationService.createInstance($eec));
    this.j = this.B(instantiationService.createInstance($cec));
    this.m = this.B(instantiationService.createInstance($fec));
    if (!this.I()) {
      this.n = 0;
      this.activationPromise = Promise.resolve();
      return;
    }
    this.n = +/* @__PURE__ */ new Date();
    this.activationPromise = this.H();
    this.B(this.y.onDidInstallExtensions((e) => this.L(e)));
  }
  async H() {
    try {
      await Promise.allSettled([
        this.F.whenExtensionsReady(),
        this.G.whenInitializationFinished(),
        this.s.when(
          3
          /* LifecyclePhase.Restored */
        )
      ]);
    } catch (error) {
    }
    await Promise.all([
      this.b.activate(),
      this.c.activate(),
      this.a.activate(),
      this.g.activate(),
      this.j.activate(),
      this.h.activate(),
      this.m.activate()
    ]);
    this.B(Event2.any(this.b.onDidChangeRecommendations, this.c.onDidChangeRecommendations, this.z.onDidChangeIgnoredRecommendations)(() => this.r.fire()));
    this.B(this.z.onDidChangeGlobalIgnoredRecommendation(({ extensionId, isRecommended }) => {
      if (!isRecommended) {
        const reason = this.getAllRecommendationsWithReason()[extensionId];
        if (reason && reason.reasonId) {
          this.u.publicLog2("extensionsRecommendations:ignoreRecommendation", { extensionId, recommendationReason: reason.reasonId });
        }
      }
    }));
    this.O();
  }
  I() {
    return this.t.isEnabled() && !this.w.isExtensionDevelopment;
  }
  async J() {
    await Promise.all([this.f.activate(), this.c.activate()]);
  }
  getAllRecommendationsWithReason() {
    this.J();
    const output = /* @__PURE__ */ Object.create(null);
    const allRecommendations = [
      ...this.c.recommendations,
      ...this.f.recommendations,
      ...this.a.recommendations,
      ...this.b.recommendations,
      ...this.g.recommendations,
      ...this.j.recommendations,
      ...this.h.recommendations
    ];
    for (const { extension, reason } of allRecommendations) {
      if ($zg(extension) && this.N(extension)) {
        output[extension.toLowerCase()] = reason;
      }
    }
    return output;
  }
  async getConfigBasedRecommendations() {
    await this.c.activate();
    return {
      important: this.M(this.c.importantRecommendations),
      others: this.M(this.c.otherRecommendations)
    };
  }
  async getOtherRecommendations() {
    await this.activationPromise;
    await this.J();
    const recommendations = [
      ...this.c.otherRecommendations,
      ...this.f.otherRecommendations,
      ...this.h.recommendations
    ];
    const extensionIds = this.M(recommendations);
    $Zb(extensionIds, this.n);
    return extensionIds;
  }
  async getImportantRecommendations() {
    await this.J();
    const recommendations = [
      ...this.a.importantRecommendations,
      ...this.c.importantRecommendations,
      ...this.f.importantRecommendations
    ];
    const extensionIds = this.M(recommendations);
    $Zb(extensionIds, this.n);
    return extensionIds;
  }
  getKeymapRecommendations() {
    return this.M(this.g.recommendations);
  }
  getLanguageRecommendations() {
    return this.M(this.j.recommendations);
  }
  getRemoteRecommendations() {
    return this.M(this.m.recommendations);
  }
  async getWorkspaceRecommendations() {
    if (!this.I()) {
      return [];
    }
    await this.b.activate();
    const result = [];
    for (const { extension } of this.b.recommendations) {
      if ($zg(extension)) {
        if (!result.includes(extension.toLowerCase()) && this.N(extension)) {
          result.push(extension.toLowerCase());
        }
      } else {
        result.push(extension);
      }
    }
    return result;
  }
  async getExeBasedRecommendations(exe) {
    await this.f.activate();
    const { important, others } = exe ? this.f.getRecommendations(exe) : { important: this.f.importantRecommendations, others: this.f.otherRecommendations };
    return { important: this.M(important), others: this.M(others) };
  }
  getFileBasedRecommendations() {
    return this.M(this.a.recommendations);
  }
  L(results) {
    for (const e of results) {
      if (e.source && !URI.isUri(e.source) && e.operation === 2) {
        const extRecommendations = this.getAllRecommendationsWithReason() || {};
        const recommendationReason = extRecommendations[e.source.identifier.id.toLowerCase()];
        if (recommendationReason) {
          this.u.publicLog("extensionGallery:install:recommendations", { ...e.source.telemetryData, recommendationReason: recommendationReason.reasonId });
        }
      }
    }
  }
  M(recommendations) {
    const extensionIds = [];
    for (const { extension } of recommendations) {
      if ($zg(extension) && this.N(extension) && !extensionIds.includes(extension.toLowerCase())) {
        extensionIds.push(extension.toLowerCase());
      }
    }
    return extensionIds;
  }
  N(extensionId) {
    return !this.z.ignoredRecommendations.includes(extensionId.toLowerCase());
  }
  async O() {
    const installed = await this.D.queryLocal();
    const allowedRecommendations = [
      ...this.b.recommendations,
      ...this.c.importantRecommendations.filter((recommendation) => !recommendation.whenNotInstalled || recommendation.whenNotInstalled.every((id2) => installed.every((local) => !$DA(local.identifier, { id: id2 }))))
    ].map(({ extension }) => extension).filter((extension) => !$zg(extension) || this.N(extension));
    if (allowedRecommendations.length) {
      await this.P($Wh(5e3));
      await this.C.promptWorkspaceRecommendations(allowedRecommendations);
    }
  }
  P(o) {
    this.B($1c(() => o.cancel()));
    return o;
  }
};
$gec = __decorate([
  __param(0, $Pk),
  __param(1, $KL),
  __param(2, $pA),
  __param(3, $zv),
  __param(4, $Xk),
  __param(5, $sA),
  __param(6, $BBb),
  __param(7, $_dc),
  __param(8, $vzb),
  __param(9, $NY),
  __param(10, $9Vb)
], $gec);

// out-build/vs/workbench/contrib/update/common/update.js
var $hec = "update.showCurrentReleaseNotes";
var $iec = "developer.showCurrentFileAsReleaseNotes";

// out-build/vs/workbench/contrib/extensions/browser/extensionsWorkbenchService.js
var $kec_1;
var $jec = class $jec2 {
  constructor(g, h3, server, local, j, k, l, n, o, q, s) {
    this.g = g;
    this.h = h3;
    this.server = server;
    this.local = local;
    this.j = j;
    this.k = k;
    this.l = l;
    this.n = n;
    this.o = o;
    this.q = q;
    this.s = s;
    this.enablementState = 10;
    this.f = /* @__PURE__ */ new Map();
    this.isMalicious = false;
  }
  get resourceExtension() {
    if (this.k) {
      return this.k.resourceExtension;
    }
    if (this.local?.isWorkspaceScoped) {
      return {
        type: "resource",
        identifier: this.local.identifier,
        location: this.local.location,
        manifest: this.local.manifest,
        changelogUri: this.local.changelogUrl,
        readmeUri: this.local.readmeUrl
      };
    }
    return void 0;
  }
  get gallery() {
    return this.j;
  }
  set gallery(gallery) {
    this.j = gallery;
    this.f.clear();
  }
  get type() {
    return this.local ? this.local.type : 1;
  }
  get isBuiltin() {
    return this.local ? this.local.isBuiltin : false;
  }
  get isWorkspaceScoped() {
    if (this.local) {
      return this.local.isWorkspaceScoped;
    }
    if (this.k) {
      return this.k.isWorkspaceScoped;
    }
    return false;
  }
  get name() {
    if (this.gallery) {
      return this.gallery.name;
    }
    return this.A()?.name ?? "";
  }
  get displayName() {
    if (this.gallery) {
      return this.gallery.displayName || this.gallery.name;
    }
    return this.A()?.displayName ?? this.name;
  }
  get identifier() {
    if (this.gallery) {
      return this.gallery.identifier;
    }
    if (this.resourceExtension) {
      return this.resourceExtension.identifier;
    }
    return this.local.identifier;
  }
  get uuid() {
    return this.gallery ? this.gallery.identifier.uuid : this.local?.identifier.uuid;
  }
  get publisher() {
    if (this.gallery) {
      return this.gallery.publisher;
    }
    return this.A()?.publisher ?? "";
  }
  get publisherDisplayName() {
    if (this.gallery) {
      return this.gallery.publisherDisplayName || this.gallery.publisher;
    }
    if (this.local?.publisherDisplayName) {
      return this.local.publisherDisplayName;
    }
    return this.publisher;
  }
  get publisherUrl() {
    if (!this.s.extensionsGallery || !this.gallery) {
      return void 0;
    }
    return $vh(URI.parse(this.s.extensionsGallery.publisherUrl), this.publisher);
  }
  get publisherDomain() {
    return this.gallery?.publisherDomain;
  }
  get publisherSponsorLink() {
    return this.gallery?.publisherSponsorLink ? URI.parse(this.gallery.publisherSponsorLink) : void 0;
  }
  get version() {
    return this.local ? this.local.manifest.version : this.latestVersion;
  }
  get pinned() {
    return !!this.local?.pinned;
  }
  get latestVersion() {
    return this.gallery ? this.gallery.version : this.A()?.version ?? "";
  }
  get description() {
    return this.gallery ? this.gallery.description : this.A()?.description ?? "";
  }
  get url() {
    if (!this.s.extensionsGallery || !this.gallery) {
      return void 0;
    }
    return `${this.s.extensionsGallery.itemUrl}?itemName=${this.publisher}.${this.name}`;
  }
  get iconUrl() {
    return this.v || this.u || this.t || this.x;
  }
  get iconUrlFallback() {
    return this.w || this.u || this.t || this.x;
  }
  get t() {
    if (this.local && this.local.manifest.icon) {
      return $ih.uriToBrowserUri($vh(this.local.location, this.local.manifest.icon)).toString(true);
    }
    return null;
  }
  get u() {
    if (this.resourceExtension?.manifest.icon) {
      return $ih.uriToBrowserUri($vh(this.resourceExtension.location, this.resourceExtension.manifest.icon)).toString(true);
    }
    return null;
  }
  get v() {
    return this.gallery?.assets.icon ? this.gallery.assets.icon.uri : null;
  }
  get w() {
    return this.gallery?.assets.icon ? this.gallery.assets.icon.fallbackUri : null;
  }
  get x() {
    if (this.type === 0 && this.local) {
      if (this.local.manifest && this.local.manifest.contributes) {
        if (Array.isArray(this.local.manifest.contributes.themes) && this.local.manifest.contributes.themes.length) {
          return $ih.asBrowserUri("vs/workbench/contrib/extensions/browser/media/theme-icon.png").toString(true);
        }
        if (Array.isArray(this.local.manifest.contributes.grammars) && this.local.manifest.contributes.grammars.length) {
          return $ih.asBrowserUri("vs/workbench/contrib/extensions/browser/media/language-icon.svg").toString(true);
        }
      }
    }
    return $ozb;
  }
  get repository() {
    return this.gallery && this.gallery.assets.repository ? this.gallery.assets.repository.uri : void 0;
  }
  get licenseUrl() {
    return this.gallery && this.gallery.assets.license ? this.gallery.assets.license.uri : void 0;
  }
  get supportUrl() {
    return this.gallery && this.gallery.supportLink ? this.gallery.supportLink : void 0;
  }
  get state() {
    return this.g(this);
  }
  get installCount() {
    return this.gallery ? this.gallery.installCount : void 0;
  }
  get rating() {
    return this.gallery ? this.gallery.rating : void 0;
  }
  get ratingCount() {
    return this.gallery ? this.gallery.ratingCount : void 0;
  }
  get outdated() {
    try {
      if (!this.gallery || !this.local) {
        return false;
      }
      if (this.type === 0 && this.s.quality === "stable") {
        return false;
      }
      if (!this.local.preRelease && this.gallery.properties.isPreReleaseVersion) {
        return false;
      }
      if (gt(this.latestVersion, this.version)) {
        return true;
      }
      if (this.outdatedTargetPlatform) {
        return true;
      }
    } catch (error) {
    }
    return false;
  }
  get outdatedTargetPlatform() {
    return !!this.local && !!this.gallery && ![
      "undefined",
      "web"
      /* TargetPlatform.WEB */
    ].includes(this.local.targetPlatform) && this.gallery.properties.targetPlatform !== "web" && this.local.targetPlatform !== this.gallery.properties.targetPlatform && eq(this.latestVersion, this.version);
  }
  get runtimeState() {
    return this.h(this);
  }
  get telemetryData() {
    const { local, gallery } = this;
    if (gallery) {
      return $LA(gallery);
    } else if (local) {
      return $KA(local);
    } else {
      return {};
    }
  }
  get preview() {
    return this.local?.manifest.preview ?? this.gallery?.preview ?? false;
  }
  get preRelease() {
    return !!this.local?.preRelease;
  }
  get isPreReleaseVersion() {
    if (this.local) {
      return this.local.isPreReleaseVersion;
    }
    return !!this.gallery?.properties.isPreReleaseVersion;
  }
  get hasPreReleaseVersion() {
    return !!this.gallery?.hasPreReleaseVersion || !!this.local?.hasPreReleaseVersion || !!this.y;
  }
  get hasReleaseVersion() {
    return !!this.resourceExtension || !!this.gallery?.hasReleaseVersion;
  }
  z() {
    return this.local && !this.outdated ? this.local : void 0;
  }
  async getManifest(token) {
    const local = this.z();
    if (local) {
      return local.manifest;
    }
    if (this.gallery) {
      return this.getGalleryManifest(token);
    }
    if (this.resourceExtension) {
      return this.resourceExtension.manifest;
    }
    return null;
  }
  async getGalleryManifest(token = CancellationToken.None) {
    if (this.gallery) {
      let cache2 = this.f.get("manifest");
      if (!cache2) {
        if (this.gallery.assets.manifest) {
          this.f.set("manifest", cache2 = this.l.getManifest(this.gallery, token).catch((e) => {
            this.f.delete("manifest");
            throw e;
          }));
        } else {
          this.o.error(localize(6896, null), this.identifier.id);
        }
      }
      return cache2;
    }
    return null;
  }
  hasReadme() {
    if (this.local && this.local.readmeUrl) {
      return true;
    }
    if (this.gallery && this.gallery.assets.readme) {
      return true;
    }
    if (this.resourceExtension?.readmeUri) {
      return true;
    }
    return this.type === 0;
  }
  async getReadme(token) {
    const local = this.z();
    if (local?.readmeUrl) {
      const content = await this.q.readFile(local.readmeUrl);
      return content.value.toString();
    }
    if (this.gallery) {
      if (this.gallery.assets.readme) {
        return this.l.getReadme(this.gallery, token);
      }
      this.n.publicLog("extensions:NotFoundReadMe", this.telemetryData);
    }
    if (this.type === 0) {
      return Promise.resolve(`# ${this.displayName || this.name}
**Notice:** This extension is bundled with Visual Studio Code. It can be disabled but not uninstalled.
## Features
${this.description}
`);
    }
    if (this.resourceExtension?.readmeUri) {
      const content = await this.q.readFile(this.resourceExtension?.readmeUri);
      return content.value.toString();
    }
    return Promise.reject(new Error("not available"));
  }
  hasChangelog() {
    if (this.local && this.local.changelogUrl) {
      return true;
    }
    if (this.gallery && this.gallery.assets.changelog) {
      return true;
    }
    return this.type === 0;
  }
  async getChangelog(token) {
    const local = this.z();
    if (local?.changelogUrl) {
      const content = await this.q.readFile(local.changelogUrl);
      return content.value.toString();
    }
    if (this.gallery?.assets.changelog) {
      return this.l.getChangelog(this.gallery, token);
    }
    if (this.type === 0) {
      return Promise.resolve(`Please check the [VS Code Release Notes](command:${$hec}) for changes to the built-in extensions.`);
    }
    return Promise.reject(new Error("not available"));
  }
  get categories() {
    const { local, gallery, resourceExtension } = this;
    if (local && local.manifest.categories && !this.outdated) {
      return local.manifest.categories;
    }
    if (gallery) {
      return gallery.categories;
    }
    if (resourceExtension) {
      return resourceExtension.manifest.categories ?? [];
    }
    return [];
  }
  get tags() {
    const { gallery } = this;
    if (gallery) {
      return gallery.tags.filter((tag2) => !tag2.startsWith("_"));
    }
    return [];
  }
  get dependencies() {
    const { local, gallery, resourceExtension } = this;
    if (local && local.manifest.extensionDependencies && !this.outdated) {
      return local.manifest.extensionDependencies;
    }
    if (gallery) {
      return gallery.properties.dependencies || [];
    }
    if (resourceExtension) {
      return resourceExtension.manifest.extensionDependencies || [];
    }
    return [];
  }
  get extensionPack() {
    const { local, gallery, resourceExtension } = this;
    if (local && local.manifest.extensionPack && !this.outdated) {
      return local.manifest.extensionPack;
    }
    if (gallery) {
      return gallery.properties.extensionPack || [];
    }
    if (resourceExtension) {
      return resourceExtension.manifest.extensionPack || [];
    }
    return [];
  }
  setExtensionsControlManifest(extensionsControlManifest) {
    this.isMalicious = extensionsControlManifest.malicious.some((identifier2) => $DA(this.identifier, identifier2));
    this.deprecationInfo = extensionsControlManifest.deprecated ? extensionsControlManifest.deprecated[this.identifier.id.toLowerCase()] : void 0;
    this.y = extensionsControlManifest?.extensionsEnabledWithPreRelease?.includes(this.identifier.id.toLowerCase());
  }
  A() {
    if (this.local) {
      return this.local.manifest;
    }
    if (this.resourceExtension) {
      return this.resourceExtension.manifest;
    }
    return null;
  }
};
$jec = __decorate([
  __param(6, $pA),
  __param(7, $zv),
  __param(8, $wn),
  __param(9, $km),
  __param(10, $Vu)
], $jec);
var EXTENSIONS_AUTO_UPDATE_KEY = "extensions.autoUpdate";
var EXTENSIONS_DONOT_AUTO_UPDATE_KEY = "extensions.donotAutoUpdate";
var EXTENSIONS_DISMISSED_NOTIFICATIONS_KEY = "extensions.dismissedNotifications";
var Extensions7 = class Extensions8 extends $3c {
  get onChange() {
    return this.f.event;
  }
  get onReset() {
    return this.g.event;
  }
  constructor(server, s, t, u, w, y, z, C, D) {
    super();
    this.server = server;
    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 = this.B(new $ze());
    this.g = this.B(new $ze());
    this.h = [];
    this.j = [];
    this.n = [];
    this.B(server.extensionManagementService.onInstallExtension((e) => this.J(e)));
    this.B(server.extensionManagementService.onDidInstallExtensions((e) => this.N(e)));
    this.B(server.extensionManagementService.onUninstallExtension((e) => this.Q(e.identifier)));
    this.B(server.extensionManagementService.onDidUninstallExtension((e) => this.R(e)));
    this.B(server.extensionManagementService.onDidUpdateExtensionMetadata((e) => this.O(e.local)));
    this.B(server.extensionManagementService.onDidChangeProfile(() => this.M()));
    this.B(y.onEnablementChanged((e) => this.S(e)));
    this.B(Event2.any(this.onChange, this.onReset)(() => this.F = void 0));
    if (this.u) {
      this.B(this.z.onInstallExtension((e) => {
        if (e.workspaceScoped) {
          this.J(e);
        }
      }));
      this.B(this.z.onDidInstallExtensions((e) => {
        const result = e.filter((e2) => e2.workspaceScoped);
        if (result.length) {
          this.N(result);
        }
      }));
      this.B(this.z.onUninstallExtension((e) => {
        if (e.workspaceScoped) {
          this.Q(e.identifier);
        }
      }));
      this.B(this.z.onDidUninstallExtension((e) => {
        if (e.workspaceScoped) {
          this.R(e);
        }
      }));
    }
  }
  get local() {
    if (!this.F) {
      this.F = [];
      for (const extension of this.n) {
        this.F.push(extension);
      }
      for (const extension of this.h) {
        if (!this.n.some((installed) => $DA(installed.identifier, extension.identifier))) {
          this.F.push(extension);
        }
      }
    }
    return this.F;
  }
  async queryInstalled(productVersion) {
    await this.L(productVersion);
    this.f.fire(void 0);
    return this.local;
  }
  async syncInstalledExtensionsWithGallery(galleryExtensions, productVersion) {
    const extensions = await this.G(galleryExtensions, productVersion);
    for (const [extension, gallery] of extensions) {
      if (extension.local && !extension.local.identifier.uuid) {
        extension.local = await this.I(extension.local, gallery);
      }
      if (!extension.gallery || extension.gallery.version !== gallery.version || extension.gallery.properties.targetPlatform !== gallery.properties.targetPlatform) {
        extension.gallery = gallery;
        this.f.fire({ extension });
      }
    }
  }
  async G(galleryExtensions, productVersion) {
    const mappedExtensions = this.H(galleryExtensions);
    const targetPlatform = await this.server.extensionManagementService.getTargetPlatform();
    const compatibleGalleryExtensions = [];
    const compatibleGalleryExtensionsToFetch = [];
    await Promise.allSettled(mappedExtensions.map(async ([extension, gallery]) => {
      if (extension.local) {
        if (await this.w.isExtensionCompatible(gallery, extension.local.preRelease, targetPlatform, productVersion)) {
          compatibleGalleryExtensions.push(gallery);
        } else {
          compatibleGalleryExtensionsToFetch.push({ ...extension.local.identifier, preRelease: extension.local.preRelease });
        }
      }
    }));
    if (compatibleGalleryExtensionsToFetch.length) {
      const result = await this.w.getExtensions(compatibleGalleryExtensionsToFetch, { targetPlatform, compatible: true, queryAllVersions: true, productVersion }, CancellationToken.None);
      compatibleGalleryExtensions.push(...result);
    }
    return this.H(compatibleGalleryExtensions);
  }
  H(galleryExtensions) {
    const mappedExtensions = [];
    const byUUID = /* @__PURE__ */ new Map(), byID = /* @__PURE__ */ new Map();
    for (const gallery of galleryExtensions) {
      byUUID.set(gallery.identifier.uuid, gallery);
      byID.set(gallery.identifier.id.toLowerCase(), gallery);
    }
    for (const installed of this.n) {
      if (installed.uuid) {
        const gallery = byUUID.get(installed.uuid);
        if (gallery) {
          mappedExtensions.push([installed, gallery]);
          continue;
        }
      }
      if (installed.local?.source !== "resource") {
        const gallery = byID.get(installed.identifier.id.toLowerCase());
        if (gallery) {
          mappedExtensions.push([installed, gallery]);
        }
      }
    }
    return mappedExtensions;
  }
  async I(localExtension, gallery) {
    let isPreReleaseVersion2 = false;
    if (localExtension.manifest.version !== gallery.version) {
      this.C.publicLog2("galleryService:updateMetadata");
      const galleryWithLocalVersion = (await this.w.getExtensions([{ ...localExtension.identifier, version: localExtension.manifest.version }], CancellationToken.None))[0];
      isPreReleaseVersion2 = !!galleryWithLocalVersion?.properties?.isPreReleaseVersion;
    }
    return this.z.updateMetadata(localExtension, { id: gallery.identifier.uuid, publisherDisplayName: gallery.publisherDisplayName, publisherId: gallery.publisherId, isPreReleaseVersion: isPreReleaseVersion2 });
  }
  canInstall(galleryExtension) {
    return this.server.extensionManagementService.canInstall(galleryExtension);
  }
  J(event) {
    const { source } = event;
    if (source && !URI.isUri(source)) {
      const extension = this.n.find((e) => $DA(e.identifier, source.identifier)) ?? this.D.createInstance($jec, this.s, this.t, this.server, void 0, source, void 0);
      this.h.push(extension);
      this.f.fire({ extension });
    }
  }
  async L(productVersion) {
    const extensionsControlManifest = await this.server.extensionManagementService.getExtensionsControlManifest();
    const all = await this.server.extensionManagementService.getInstalled(void 0, void 0, productVersion);
    if (this.u) {
      all.push(...await this.z.getInstalledWorkspaceExtensions(true));
    }
    const installed = $JA(all, (r2) => r2.identifier).reduce((result, extensions) => {
      if (extensions.length === 1) {
        result.push(extensions[0]);
      } else {
        let workspaceExtension, userExtension, systemExtension;
        for (const extension2 of extensions) {
          if (extension2.isWorkspaceScoped) {
            workspaceExtension = extension2;
          } else if (extension2.type === 1) {
            userExtension = extension2;
          } else {
            systemExtension = extension2;
          }
        }
        const extension = workspaceExtension ?? userExtension ?? systemExtension;
        if (extension) {
          result.push(extension);
        }
      }
      return result;
    }, []);
    const byId = $Vb(this.n, (e) => e.local ? e.local.identifier.id : e.identifier.id);
    this.n = installed.map((local) => {
      const extension = byId[local.identifier.id] || this.D.createInstance($jec, this.s, this.t, this.server, local, void 0, void 0);
      extension.local = local;
      extension.enablementState = this.y.getEnablementState(local);
      extension.setExtensionsControlManifest(extensionsControlManifest);
      return extension;
    });
  }
  async M() {
    this.n = [];
    this.h = [];
    this.j = [];
    await this.L();
    this.g.fire();
  }
  async N(results) {
    const extensions = [];
    for (const event of results) {
      const { local, source } = event;
      const gallery = source && !URI.isUri(source) ? source : void 0;
      const location3 = source && URI.isUri(source) ? source : void 0;
      const installingExtension = gallery ? this.h.filter((e) => $DA(e.identifier, gallery.identifier))[0] : null;
      this.h = installingExtension ? this.h.filter((e) => e !== installingExtension) : this.h;
      let extension = installingExtension ? installingExtension : location3 || local ? this.D.createInstance($jec, this.s, this.t, this.server, local, void 0, void 0) : void 0;
      if (extension) {
        if (local) {
          const installed = this.n.filter((e) => $DA(e.identifier, extension.identifier))[0];
          if (installed) {
            extension = installed;
          } else {
            this.n.push(extension);
          }
          extension.local = local;
          if (!extension.gallery) {
            extension.gallery = gallery;
          }
          extension.enablementState = this.y.getEnablementState(local);
        }
        extensions.push(extension);
      }
      this.f.fire(!local || !extension ? void 0 : { extension, operation: event.operation });
    }
    if (extensions.length) {
      const manifest = await this.server.extensionManagementService.getExtensionsControlManifest();
      for (const extension of extensions) {
        extension.setExtensionsControlManifest(manifest);
      }
      this.P(extensions);
    }
  }
  async O(local) {
    const extension = this.n.find((e) => $DA(e.identifier, local.identifier));
    if (extension?.local) {
      const hasChanged = extension.local.pinned !== local.pinned || extension.local.preRelease !== local.preRelease;
      extension.local = local;
      if (hasChanged) {
        this.f.fire({ extension });
      }
    }
  }
  async P(extensions) {
    const toMatch = extensions.filter((e) => e.local && !e.gallery && e.local.source !== "resource");
    if (!toMatch.length) {
      return;
    }
    if (!this.w.isEnabled()) {
      return;
    }
    this.C.publicLog2("galleryService:matchInstalledExtension");
    const galleryExtensions = await this.w.getExtensions(toMatch.map((e) => ({ ...e.identifier, preRelease: e.local?.preRelease })), { compatible: true, targetPlatform: await this.server.extensionManagementService.getTargetPlatform() }, CancellationToken.None);
    for (const extension of extensions) {
      const compatible = galleryExtensions.find((e) => $DA(e.identifier, extension.identifier));
      if (compatible) {
        extension.gallery = compatible;
        this.f.fire({ extension });
      }
    }
  }
  Q(identifier2) {
    const extension = this.n.filter((e) => $DA(e.identifier, identifier2))[0];
    if (extension) {
      const uninstalling = this.j.filter((e) => $DA(e.identifier, identifier2))[0] || extension;
      this.j = [uninstalling, ...this.j.filter((e) => !$DA(e.identifier, identifier2))];
      this.f.fire(uninstalling ? { extension: uninstalling } : void 0);
    }
  }
  R({ identifier: identifier2, error }) {
    const uninstalled = this.j.find((e) => $DA(e.identifier, identifier2)) || this.n.find((e) => $DA(e.identifier, identifier2));
    this.j = this.j.filter((e) => !$DA(e.identifier, identifier2));
    if (!error) {
      this.n = this.n.filter((e) => !$DA(e.identifier, identifier2));
    }
    if (uninstalled) {
      this.f.fire({ extension: uninstalled });
    }
  }
  S(platformExtensions) {
    const extensions = this.local.filter((e) => platformExtensions.some((p) => $DA(e.identifier, p.identifier)));
    for (const extension of extensions) {
      if (extension.local) {
        const enablementState = this.y.getEnablementState(extension.local);
        if (enablementState !== extension.enablementState) {
          extension.enablementState = enablementState;
          this.f.fire({ extension });
        }
      }
    }
  }
  getExtensionState(extension) {
    if (extension.gallery && this.h.some((e) => !!e.gallery && $DA(e.gallery.identifier, extension.gallery.identifier))) {
      return 0;
    }
    if (this.j.some((e) => $DA(e.identifier, extension.identifier))) {
      return 2;
    }
    const local = this.n.filter((e) => e === extension || e.gallery && extension.gallery && $DA(e.gallery.identifier, extension.gallery.identifier))[0];
    return local ? 1 : 3;
  }
};
Extensions7 = __decorate([
  __param(4, $pA),
  __param(5, $qzb),
  __param(6, $pzb),
  __param(7, $zv),
  __param(8, $Pk)
], Extensions7);
var $kec = class $kec2 extends $3c {
  static {
    $kec_1 = this;
  }
  static {
    this.f = 1e3 * 60 * 60 * 12;
  }
  // 12 hours
  get onChange() {
    return this.w.event;
  }
  get onReset() {
    return this.C.event;
  }
  constructor(G, H, I, J, L, M, N, urlService, O, P, Q, R, S, U, W, X, contextKeyService, Y, Z, $149, ab, bb, cb, db, eb, fb, gb, hb, ib, jb, kb, lb, mb, nb) {
    super();
    this.G = G;
    this.H = H;
    this.I = I;
    this.J = J;
    this.L = L;
    this.M = M;
    this.N = N;
    this.O = O;
    this.P = P;
    this.Q = Q;
    this.R = R;
    this.S = S;
    this.U = U;
    this.W = W;
    this.X = X;
    this.Y = Y;
    this.Z = Z;
    this.$ = $149;
    this.ab = ab;
    this.bb = bb;
    this.cb = cb;
    this.db = db;
    this.eb = eb;
    this.fb = fb;
    this.gb = gb;
    this.hb = hb;
    this.ib = ib;
    this.jb = jb;
    this.kb = kb;
    this.lb = lb;
    this.mb = mb;
    this.nb = nb;
    this.h = null;
    this.j = null;
    this.n = null;
    this.s = [];
    this.w = this.B(new $ze());
    this.z = new $ze();
    this.onDidChangeExtensionsNotification = this.z.event;
    this.C = new $ze();
    this.preferPreReleases = this.X.quality !== "stable";
    this.D = [];
    this.F = [];
    this.sb = this.B(new $4c());
    const preferPreReleasesValue = L.getValue("_extensions.preferPreReleases");
    if (!$Gg(preferPreReleasesValue)) {
      this.preferPreReleases = !!preferPreReleasesValue;
    }
    this.g = $Izb.bindTo(contextKeyService);
    if (R.localExtensionManagementServer) {
      this.h = this.B(G.createInstance(Extensions7, R.localExtensionManagementServer, (ext) => this.Kb(ext), (ext) => this.Ib(ext), !R.remoteExtensionManagementServer));
      this.B(this.h.onChange((e) => this.yb(e?.extension)));
      this.B(this.h.onReset((e) => this.xb()));
      this.s.push(this.h);
    }
    if (R.remoteExtensionManagementServer) {
      this.j = this.B(G.createInstance(Extensions7, R.remoteExtensionManagementServer, (ext) => this.Kb(ext), (ext) => this.Ib(ext), true));
      this.B(this.j.onChange((e) => this.yb(e?.extension)));
      this.B(this.j.onReset((e) => this.xb()));
      this.s.push(this.j);
    }
    if (R.webExtensionManagementServer) {
      this.n = this.B(G.createInstance(Extensions7, R.webExtensionManagementServer, (ext) => this.Kb(ext), (ext) => this.Ib(ext), !(R.remoteExtensionManagementServer || R.localExtensionManagementServer)));
      this.B(this.n.onChange((e) => this.yb(e?.extension)));
      this.B(this.n.onReset((e) => this.xb()));
      this.s.push(this.n);
    }
    this.t = new $Th($kec_1.f);
    this.u = new $Th(1e3);
    this.B($1c(() => {
      this.t.cancel();
      this.u.cancel();
    }));
    urlService.registerHandler(this);
    if (this.X.quality !== "stable") {
      this.ob();
    }
    this.whenInitialized = this.pb();
  }
  ob() {
    $Wn.as($Ht.Configuration).registerConfiguration({
      id: "extensions",
      order: 30,
      title: localize(6897, null),
      type: "object",
      properties: {
        [$Azb]: {
          type: "boolean",
          description: localize(6898, null),
          default: false
        }
      }
    });
  }
  async pb() {
    await Promise.all([this.queryLocal(), this.$.whenInstalledExtensionsRegistered()]);
    if (this.q.isDisposed) {
      return;
    }
    this.vb(this.$.extensions, []);
    this.B(this.$.onDidChangeExtensions(({ added, removed }) => this.vb(added, removed)));
    await this.bb.when(
      4
      /* LifecyclePhase.Eventually */
    );
    if (this.q.isDisposed) {
      return;
    }
    this.qb();
    this.Cb();
    this.ub();
    this.B(this.eb.onDidChangeValue(0, EXTENSIONS_DISMISSED_NOTIFICATIONS_KEY, this.q)((e) => this.Bb()));
    this.B(this.eb.onDidChangeValue(-1, EXTENSIONS_AUTO_UPDATE_KEY, this.q)((e) => this.Yb()));
    this.B(this.eb.onDidChangeValue(-1, EXTENSIONS_DONOT_AUTO_UPDATE_KEY, this.q)((e) => this.Yb()));
    this.B(Event2.debounce(this.onChange, () => void 0, 100)(() => {
      this.Cb();
      this.pc();
    }));
  }
  qb() {
    this.B(this.L.onDidChangeConfiguration((e) => {
      if (e.affectsConfiguration($xzb)) {
        if (this.rb()) {
          this.Pb();
        }
      }
      if (e.affectsConfiguration($yzb)) {
        if (this.Mb()) {
          this.checkForUpdates();
        }
      }
    }));
    this.B(this.O.onEnablementChanged((platformExtensions) => {
      if (this.getAutoUpdateValue() === "onlyEnabledExtensions" && platformExtensions.some((e) => this.O.isEnabled(e))) {
        this.checkForUpdates();
      }
    }));
    this.B(Event2.debounce(this.onChange, () => void 0, 100)(() => this.g.set(this.outdated.length > 0)));
    this.B(this.hb.onStateChange((e) => {
      if (e.type === "checking for updates" && e.explicit || e.type === "available for download" || e.type === "downloaded") {
        this.M.publicLog2("extensions:updatecheckonproductupdate");
        if (this.Mb()) {
          this.checkForUpdates();
        }
      }
    }));
    this.B(this.nb.onDidChangeAllowedExtensions(() => {
      if (this.Mb()) {
        this.checkForUpdates();
      }
    }));
    this.g.set(this.outdated.length > 0);
    this.Nb(true);
    if ($r) {
      this.Rb();
      if (!this.rb()) {
        this.Qb();
      }
    }
    this.tb();
    this.B(this.L.onDidChangeConfiguration((e) => {
      if (e.affectsConfiguration($Azb)) {
        this.tb();
      }
    }));
  }
  rb() {
    return this.getAutoUpdateValue() !== false;
  }
  getAutoUpdateValue() {
    const autoUpdate = this.L.getValue($xzb);
    if (autoUpdate === "onlySelectedExtensions") {
      return false;
    }
    return $Fg(autoUpdate) || autoUpdate === "onlyEnabledExtensions" ? autoUpdate : true;
  }
  async updateAutoUpdateForAllExtensions(isAutoUpdateEnabled) {
    const wasAutoUpdateEnabled = this.rb();
    if (wasAutoUpdateEnabled === isAutoUpdateEnabled) {
      return;
    }
    const result = await this.fb.confirm({
      title: localize(6899, null),
      message: isAutoUpdateEnabled ? localize(6900, null) : localize(6901, null),
      detail: localize(6902, null)
    });
    if (!result.confirmed) {
      return;
    }
    this.uc([]);
    await this.L.updateValue($xzb, isAutoUpdateEnabled);
    this.zc([]);
    await this.wb(!isAutoUpdateEnabled);
    this.w.fire(void 0);
  }
  tb() {
    this.sb.value = void 0;
    if (this.L.getValue($Azb) === true) {
      this.sb.value = this.P.onDidChangeFocus((focus) => {
        if (!focus && this.L.getValue($Azb) === true) {
          this.updateRunningExtensions(true);
        }
      });
    }
  }
  ub() {
    const extensionIds = this.installed.filter((extension) => !extension.isBuiltin && (extension.enablementState === 11 || extension.enablementState === 10)).map((extension) => $5z.toKey(extension.identifier.id));
    this.M.publicLog2("installedExtensions", { extensionIds: new $bw(extensionIds.join(";")), count: extensionIds.length });
  }
  async vb(added, removed) {
    const changedExtensions = [];
    const extensionsToFetch = [];
    for (const desc of added) {
      const extension = this.installed.find((e) => $DA({ id: desc.identifier.value, uuid: desc.uuid }, e.identifier));
      if (extension) {
        changedExtensions.push(extension);
      } else {
        extensionsToFetch.push(desc);
      }
    }
    const workspaceExtensions = [];
    for (const desc of removed) {
      if (this.jb.isInsideWorkspace(desc.extensionLocation)) {
        workspaceExtensions.push(desc);
      } else {
        extensionsToFetch.push(desc);
      }
    }
    if (extensionsToFetch.length) {
      const extensions = await this.getExtensions(extensionsToFetch.map((e) => ({ id: e.identifier.value, uuid: e.uuid })), CancellationToken.None);
      changedExtensions.push(...extensions);
    }
    if (workspaceExtensions.length) {
      const extensions = await this.getResourceExtensions(workspaceExtensions.map((e) => e.extensionLocation), true);
      changedExtensions.push(...extensions);
    }
    for (const changedExtension of changedExtensions) {
      this.w.fire(changedExtension);
    }
  }
  wb(pinned) {
    return this.Q.withProgress({
      location: 5,
      title: localize(6903, null)
    }, () => this.I.resetPinnedStateForAllUserExtensions(pinned));
  }
  xb() {
    for (const task of this.F) {
      task.cancel();
    }
    this.F = [];
    this.D = [];
    this.yb();
    this.C.fire();
  }
  yb(extension) {
    this.Ab = void 0;
    this.zb = void 0;
    this.w.fire(extension);
  }
  get local() {
    if (!this.zb) {
      if (this.s.length === 1) {
        this.zb = this.installed;
      } else {
        this.zb = [];
        const byId = $JA(this.installed, (r2) => r2.identifier);
        for (const extensions of byId) {
          this.zb.push(this.Jb(extensions));
        }
      }
    }
    return this.zb;
  }
  get installed() {
    if (!this.Ab) {
      this.Ab = [];
      for (const extensions of this.s) {
        for (const extension of extensions.local) {
          this.Ab.push(extension);
        }
      }
    }
    return this.Ab;
  }
  get outdated() {
    return this.installed.filter(
      (e) => e.outdated && e.local && e.state === 1
      /* ExtensionState.Installed */
    );
  }
  async queryLocal(server) {
    if (server) {
      if (this.h && this.R.localExtensionManagementServer === server) {
        return this.h.queryInstalled(this.Tb());
      }
      if (this.j && this.R.remoteExtensionManagementServer === server) {
        return this.j.queryInstalled(this.Tb());
      }
      if (this.n && this.R.webExtensionManagementServer === server) {
        return this.n.queryInstalled(this.Tb());
      }
    }
    if (this.h) {
      try {
        await this.h.queryInstalled(this.Tb());
      } catch (error) {
        this.Z.error(error);
      }
    }
    if (this.j) {
      try {
        await this.j.queryInstalled(this.Tb());
      } catch (error) {
        this.Z.error(error);
      }
    }
    if (this.n) {
      try {
        await this.n.queryInstalled(this.Tb());
      } catch (error) {
        this.Z.error(error);
      }
    }
    return this.local;
  }
  async queryGallery(arg1, arg2) {
    if (!this.J.isEnabled()) {
      return $Uz([]);
    }
    const options3 = CancellationToken.isCancellationToken(arg1) ? {} : arg1;
    const token = CancellationToken.isCancellationToken(arg1) ? arg1 : arg2;
    options3.text = options3.text ? this.Eb(options3.text) : options3.text;
    options3.includePreRelease = $Gg(options3.includePreRelease) ? this.preferPreReleases : options3.includePreRelease;
    const extensionsControlManifest = await this.I.getExtensionsControlManifest();
    const pager = await this.J.query(options3, token);
    this.Lb(pager.firstPage);
    return {
      firstPage: pager.firstPage.map((gallery) => this.Fb(gallery, extensionsControlManifest)),
      total: pager.total,
      pageSize: pager.pageSize,
      getPage: async (pageIndex, token2) => {
        const page = await pager.getPage(pageIndex, token2);
        this.Lb(page);
        return page.map((gallery) => this.Fb(gallery, extensionsControlManifest));
      }
    };
  }
  async getExtensions(extensionInfos, arg1, arg2) {
    if (!this.J.isEnabled()) {
      return [];
    }
    extensionInfos.forEach((e) => e.preRelease = e.preRelease ?? this.preferPreReleases);
    const extensionsControlManifest = await this.I.getExtensionsControlManifest();
    const galleryExtensions = await this.J.getExtensions(extensionInfos, arg1, arg2);
    this.Lb(galleryExtensions);
    return galleryExtensions.map((gallery) => this.Fb(gallery, extensionsControlManifest));
  }
  async getResourceExtensions(locations, isWorkspaceScoped) {
    const resourceExtensions = await this.I.getExtensions(locations);
    return resourceExtensions.map((resourceExtension) => this.Hb(resourceExtension.location) ?? this.G.createInstance($jec, (ext) => this.Kb(ext), (ext) => this.Ib(ext), void 0, void 0, void 0, { resourceExtension, isWorkspaceScoped }));
  }
  Bb() {
    if (this.Hc !== this.Ic()) {
      this.Gc = void 0;
      this.Cb();
    }
  }
  Cb() {
    const computedNotificiations = this.Db();
    const dismissedNotifications = [];
    let extensionsNotification;
    if (computedNotificiations.length) {
      for (const dismissedNotification of this.Ec()) {
        if (computedNotificiations.some((e) => e.key === dismissedNotification)) {
          dismissedNotifications.push(dismissedNotification);
        }
      }
      if (!dismissedNotifications.includes(computedNotificiations[0].key)) {
        extensionsNotification = {
          message: computedNotificiations[0].message,
          severity: computedNotificiations[0].severity,
          extensions: computedNotificiations[0].extensions,
          key: computedNotificiations[0].key,
          dismiss: () => {
            this.Fc([...this.Ec(), computedNotificiations[0].key]);
            this.Cb();
          }
        };
      }
    }
    this.Fc(dismissedNotifications);
    if (this.y?.key !== extensionsNotification?.key) {
      this.y = extensionsNotification;
      this.z.fire(this.y);
    }
  }
  Db() {
    const computedNotificiations = [];
    const disallowedExtensions = this.local.filter(
      (e) => e.enablementState === 6
      /* EnablementState.DisabledByAllowlist */
    );
    if (disallowedExtensions.length) {
      computedNotificiations.push({
        message: this.L.inspect($CA).policy ? localize(6904, null) : localize(6905, null),
        severity: Severity2.Warning,
        extensions: disallowedExtensions,
        key: "disallowedExtensions:" + disallowedExtensions.sort((a, b) => a.identifier.id.localeCompare(b.identifier.id)).map((e) => e.identifier.id.toLowerCase()).join("-")
      });
    }
    const invalidExtensions = this.local.filter((e) => e.enablementState === 5 && !e.isWorkspaceScoped);
    if (invalidExtensions.length) {
      if (invalidExtensions.some((e) => e.local && e.local.manifest.engines?.vscode && (!$1A(e.local.manifest.engines.vscode, this.X.version, this.X.date) || $2A([...e.local.manifest.enabledApiProposals ?? []])))) {
        computedNotificiations.push({
          message: localize(6906, null),
          severity: Severity2.Warning,
          extensions: invalidExtensions,
          key: "incompatibleExtensions:" + invalidExtensions.sort((a, b) => a.identifier.id.localeCompare(b.identifier.id)).map((e) => `${e.identifier.id.toLowerCase()}@${e.local?.manifest.version}`).join("-")
        });
      } else {
        computedNotificiations.push({
          message: localize(6907, null),
          severity: Severity2.Warning,
          extensions: invalidExtensions,
          key: "invalidExtensions:" + invalidExtensions.sort((a, b) => a.identifier.id.localeCompare(b.identifier.id)).map((e) => `${e.identifier.id.toLowerCase()}@${e.local?.manifest.version}`).join("-")
        });
      }
    }
    const deprecatedExtensions = this.local.filter((e) => !!e.deprecationInfo && e.local && this.O.isEnabled(e.local));
    if (deprecatedExtensions.length) {
      computedNotificiations.push({
        message: localize(6908, null),
        severity: Severity2.Warning,
        extensions: deprecatedExtensions,
        key: "deprecatedExtensions:" + deprecatedExtensions.sort((a, b) => a.identifier.id.localeCompare(b.identifier.id)).map((e) => e.identifier.id.toLowerCase()).join("-")
      });
    }
    return computedNotificiations;
  }
  getExtensionsNotification() {
    return this.y;
  }
  Eb(text2) {
    text2 = text2.replace(/@web/g, `tag:"${$eA}"`);
    const extensionRegex2 = /\bext:([^\s]+)\b/g;
    if (extensionRegex2.test(text2)) {
      text2 = text2.replace(extensionRegex2, (m, ext) => {
        const lookup = this.X.extensionKeywords || {};
        const keywords = lookup[ext] || [];
        const languageId = this.S.guessLanguageIdByFilepathOrFirstLine(URI.file(`.${ext}`));
        const languageName = languageId && this.S.getLanguageName(languageId);
        const languageTag = languageName ? ` tag:"${languageName}"` : "";
        return `tag:"__ext_${ext}" tag:"__ext_.${ext}" ${keywords.map((tag2) => `tag:"${tag2}"`).join(" ")}${languageTag} tag:"${ext}"`;
      });
    }
    return text2.substr(0, 350);
  }
  Fb(gallery, extensionsControlManifest) {
    let extension = this.Gb(gallery);
    if (!extension) {
      extension = this.G.createInstance($jec, (ext) => this.Kb(ext), (ext) => this.Ib(ext), void 0, void 0, gallery, void 0);
      extension.setExtensionsControlManifest(extensionsControlManifest);
    }
    return extension;
  }
  Gb(gallery) {
    for (const installed of this.local) {
      if (installed.identifier.uuid) {
        if (installed.identifier.uuid === gallery.identifier.uuid) {
          return installed;
        }
      } else if (installed.local?.source !== "resource") {
        if ($DA(installed.identifier, gallery.identifier)) {
          return installed;
        }
      }
    }
    return null;
  }
  Hb(location3) {
    return this.local.find((e) => e.local && this.ib.extUri.isEqualOrParent(location3, e.local?.location)) ?? null;
  }
  async open(extension, options3) {
    if (typeof extension === "string") {
      const id2 = extension;
      extension = this.installed.find((e) => $DA(e.identifier, { id: id2 })) ?? (await this.getExtensions([{ id: extension }], CancellationToken.None))[0];
    }
    if (!extension) {
      throw new Error(`Extension not found. ${extension}`);
    }
    await this.H.openEditor(this.G.createInstance($szb, extension), options3, options3?.sideByside ? $oJ : $nJ);
  }
  async openSearch(searchValue, preserveFoucs) {
    const viewPaneContainer = (await this.kb.openViewContainer($tzb, true))?.getViewPaneContainer();
    viewPaneContainer.search(searchValue);
    if (!preserveFoucs) {
      viewPaneContainer.focus();
    }
  }
  getExtensionRuntimeStatus(extension) {
    const extensionsStatus = this.$.getExtensionsStatus();
    for (const id2 of Object.keys(extensionsStatus)) {
      if ($DA({ id: id2 }, extension.identifier)) {
        return extensionsStatus[id2];
      }
    }
    return void 0;
  }
  async updateRunningExtensions(auto = false) {
    const toAdd = [];
    const toRemove = [];
    const extensionsToCheck = [...this.local];
    for (const extension of extensionsToCheck) {
      const runtimeState = extension.runtimeState;
      if (!runtimeState || runtimeState.action !== "restartExtensions") {
        continue;
      }
      if (extension.state === 3) {
        toRemove.push(extension.identifier.id);
        continue;
      }
      if (!extension.local) {
        continue;
      }
      const isEnabled = this.O.isEnabled(extension.local);
      if (isEnabled) {
        const runningExtension = this.$.extensions.find((e) => $DA({ id: e.identifier.value, uuid: e.uuid }, extension.identifier));
        if (runningExtension) {
          toRemove.push(runningExtension.identifier.value);
        }
        toAdd.push(extension.local);
      } else {
        toRemove.push(extension.identifier.id);
      }
    }
    for (const extension of this.$.extensions) {
      if (extension.isUnderDevelopment) {
        continue;
      }
      if (extensionsToCheck.some((e) => $DA({ id: extension.identifier.value, uuid: extension.uuid }, e.local?.identifier ?? e.identifier))) {
        continue;
      }
      toRemove.push(extension.identifier.value);
    }
    if (toAdd.length || toRemove.length) {
      if (await this.$.stopExtensionHosts(localize(6909, null), auto)) {
        await this.$.startExtensionHosts({ toAdd, toRemove });
        if (auto) {
          this.N.notify({
            severity: Severity2.Info,
            message: localize(6910, null),
            priority: NotificationPriority.SILENT
          });
        }
        this.M.publicLog2("extensions:autorestart", { count: toAdd.length + toRemove.length, auto });
      }
    }
  }
  Ib(extension) {
    const isUninstalled = extension.state === 3;
    const runningExtension = this.$.extensions.find((e) => $DA({ id: e.identifier.value }, extension.identifier));
    const reloadAction = this.R.remoteExtensionManagementServer ? "reloadWindow" : "restartExtensions";
    const reloadActionLabel = reloadAction === "reloadWindow" ? localize(6911, null) : localize(6912, null);
    if (isUninstalled) {
      const canRemoveRunningExtension = runningExtension && this.$.canRemoveExtension(runningExtension);
      const isSameExtensionRunning = runningExtension && (!extension.server || extension.server === this.R.getExtensionManagementServer($DN(runningExtension))) && (!extension.resourceExtension || this.ib.extUri.isEqual(extension.resourceExtension.location, runningExtension.extensionLocation));
      if (!canRemoveRunningExtension && isSameExtensionRunning && !runningExtension.isUnderDevelopment) {
        return { action: reloadAction, reason: localize(6913, null, reloadActionLabel) };
      }
      return void 0;
    }
    if (extension.local) {
      const isSameExtensionRunning = runningExtension && extension.server === this.R.getExtensionManagementServer($DN(runningExtension));
      const isEnabled = this.O.isEnabled(extension.local);
      if (runningExtension) {
        if (isEnabled) {
          if (this.$.canAddExtension($EN(extension.local))) {
            return void 0;
          }
          const runningExtensionServer = this.R.getExtensionManagementServer($DN(runningExtension));
          if (isSameExtensionRunning) {
            if (!runningExtension.isUnderDevelopment && (extension.version !== runningExtension.version || extension.local.targetPlatform !== runningExtension.targetPlatform)) {
              const productCurrentVersion = this.Ub();
              const productUpdateVersion = this.Vb();
              if (productUpdateVersion && !$1A(extension.local.manifest.engines.vscode, productCurrentVersion.version, productCurrentVersion.date) && $1A(extension.local.manifest.engines.vscode, productUpdateVersion.version, productUpdateVersion.date)) {
                const state = this.hb.state;
                if (state.type === "available for download") {
                  return { action: "downloadUpdate", reason: localize(6914, null, this.X.nameLong) };
                }
                if (state.type === "downloaded") {
                  return { action: "applyUpdate", reason: localize(6915, null, this.X.nameLong) };
                }
                if (state.type === "ready") {
                  return { action: "quitAndInstall", reason: localize(6916, null, this.X.nameLong) };
                }
                return void 0;
              }
              return { action: reloadAction, reason: localize(6917, null, reloadActionLabel) };
            }
            if (this.s.length > 1) {
              const extensionInOtherServer = this.installed.filter((e) => $DA(e.identifier, extension.identifier) && e.server !== extension.server)[0];
              if (extensionInOtherServer) {
                if (runningExtensionServer === this.R.remoteExtensionManagementServer && this.Y.prefersExecuteOnUI(extension.local.manifest) && extensionInOtherServer.server === this.R.localExtensionManagementServer) {
                  return { action: reloadAction, reason: localize(6918, null, reloadActionLabel) };
                }
                if (runningExtensionServer === this.R.localExtensionManagementServer && this.Y.prefersExecuteOnWorkspace(extension.local.manifest) && extensionInOtherServer.server === this.R.remoteExtensionManagementServer) {
                  return { action: reloadAction, reason: localize(6919, null, reloadActionLabel, this.R.remoteExtensionManagementServer?.label) };
                }
              }
            }
          } else {
            if (extension.server === this.R.localExtensionManagementServer && runningExtensionServer === this.R.remoteExtensionManagementServer) {
              if (this.Y.prefersExecuteOnUI(extension.local.manifest)) {
                return { action: reloadAction, reason: localize(6920, null, reloadActionLabel) };
              }
            }
            if (extension.server === this.R.remoteExtensionManagementServer && runningExtensionServer === this.R.localExtensionManagementServer) {
              if (this.Y.prefersExecuteOnWorkspace(extension.local.manifest)) {
                return { action: reloadAction, reason: localize(6921, null, reloadActionLabel) };
              }
            }
          }
          return void 0;
        } else {
          if (isSameExtensionRunning) {
            return { action: reloadAction, reason: localize(6922, null, reloadActionLabel) };
          }
        }
        return void 0;
      } else {
        if (isEnabled && !this.$.canAddExtension($EN(extension.local))) {
          return { action: reloadAction, reason: localize(6923, null, reloadActionLabel) };
        }
        const otherServer = extension.server ? extension.server === this.R.localExtensionManagementServer ? this.R.remoteExtensionManagementServer : this.R.localExtensionManagementServer : null;
        if (otherServer && extension.enablementState === 1) {
          const extensionInOtherServer = this.local.filter((e) => $DA(e.identifier, extension.identifier) && e.server === otherServer)[0];
          if (extensionInOtherServer && extensionInOtherServer.local && this.O.isEnabled(extensionInOtherServer.local)) {
            return { action: reloadAction, reason: localize(6924, null, reloadActionLabel) };
          }
        }
      }
    }
    return void 0;
  }
  Jb(extensions) {
    if (extensions.length === 1) {
      return extensions[0];
    }
    const enabledExtensions = extensions.filter((e) => e.local && this.O.isEnabled(e.local));
    if (enabledExtensions.length === 1) {
      return enabledExtensions[0];
    }
    const extensionsToChoose = enabledExtensions.length ? enabledExtensions : extensions;
    const manifest = extensionsToChoose.find((e) => e.local && e.local.manifest)?.local?.manifest;
    if (!manifest) {
      return extensionsToChoose[0];
    }
    const extensionKinds = this.Y.getExtensionKind(manifest);
    let extension = extensionsToChoose.find((extension2) => {
      for (const extensionKind of extensionKinds) {
        switch (extensionKind) {
          case "ui":
            if (extension2.server === this.R.localExtensionManagementServer) {
              return true;
            }
            return false;
          case "workspace":
            if (extension2.server === this.R.remoteExtensionManagementServer) {
              return true;
            }
            return false;
          case "web":
            if (extension2.server === this.R.webExtensionManagementServer) {
              return true;
            }
            return false;
        }
      }
      return false;
    });
    if (!extension && this.R.localExtensionManagementServer) {
      extension = extensionsToChoose.find((extension2) => {
        for (const extensionKind of extensionKinds) {
          switch (extensionKind) {
            case "workspace":
              if (extension2.server === this.R.localExtensionManagementServer) {
                return true;
              }
              return false;
            case "web":
              if (extension2.server === this.R.localExtensionManagementServer) {
                return true;
              }
              return false;
          }
        }
        return false;
      });
    }
    if (!extension && this.R.webExtensionManagementServer) {
      extension = extensionsToChoose.find((extension2) => {
        for (const extensionKind of extensionKinds) {
          switch (extensionKind) {
            case "web":
              if (extension2.server === this.R.webExtensionManagementServer) {
                return true;
              }
              return false;
          }
        }
        return false;
      });
    }
    if (!extension && this.R.remoteExtensionManagementServer) {
      extension = extensionsToChoose.find((extension2) => {
        for (const extensionKind of extensionKinds) {
          switch (extensionKind) {
            case "web":
              if (extension2.server === this.R.remoteExtensionManagementServer) {
                return true;
              }
              return false;
          }
        }
        return false;
      });
    }
    return extension || extensions[0];
  }
  Kb(extension) {
    if (this.D.some((i2) => $DA(i2.identifier, extension.identifier) && (!extension.server || i2.server === extension.server))) {
      return 0;
    }
    if (this.j) {
      const state = this.j.getExtensionState(extension);
      if (state !== 3) {
        return state;
      }
    }
    if (this.n) {
      const state = this.n.getExtensionState(extension);
      if (state !== 3) {
        return state;
      }
    }
    if (this.h) {
      return this.h.getExtensionState(extension);
    }
    return 3;
  }
  async checkForUpdates(onlyBuiltin) {
    if (!this.J.isEnabled()) {
      return;
    }
    const extensions = [];
    if (this.h) {
      extensions.push(this.h);
    }
    if (this.j) {
      extensions.push(this.j);
    }
    if (this.n) {
      extensions.push(this.n);
    }
    if (!extensions.length) {
      return;
    }
    const infos = [];
    for (const installed of this.local) {
      if (onlyBuiltin && !installed.isBuiltin) {
        continue;
      }
      if (installed.isBuiltin && !installed.local?.pinned && (installed.type === 0 || !installed.local?.identifier.uuid)) {
        continue;
      }
      if (installed.local?.source === "resource") {
        continue;
      }
      infos.push({ ...installed.identifier, preRelease: !!installed.local?.preRelease });
    }
    if (infos.length) {
      const targetPlatform = await extensions[0].server.extensionManagementService.getTargetPlatform();
      this.M.publicLog2("galleryService:checkingForUpdates", {
        count: infos.length
      });
      const galleryExtensions = await this.J.getExtensions(infos, { targetPlatform, compatible: true, productVersion: this.Tb(), preferResourceApi: true }, CancellationToken.None);
      if (galleryExtensions.length) {
        await this.Lb(galleryExtensions);
      }
    }
  }
  async updateAll() {
    const toUpdate = [];
    this.outdated.forEach((extension) => {
      if (extension.gallery) {
        toUpdate.push({
          extension: extension.gallery,
          options: {
            operation: 3,
            installPreReleaseVersion: extension.local?.isPreReleaseVersion,
            profileLocation: this.db.currentProfile.extensionsResource,
            isApplicationScoped: extension.local?.isApplicationScoped
          }
        });
      }
    });
    return this.I.installGalleryExtensions(toUpdate);
  }
  async downloadVSIX(extensionId, preRelease) {
    let [galleryExtension] = await this.J.getExtensions([{ id: extensionId, preRelease }], { compatible: true }, CancellationToken.None);
    if (!galleryExtension) {
      throw new Error(localize(6925, null, extensionId));
    }
    let targetPlatform = galleryExtension.properties.targetPlatform;
    const options3 = [];
    for (const targetPlatform2 of galleryExtension.allTargetPlatforms) {
      if (targetPlatform2 !== "undefined" && targetPlatform2 !== "unknown" && targetPlatform2 !== "universal") {
        options3.push({
          label: $jA(targetPlatform2),
          id: targetPlatform2
        });
      }
    }
    if (options3.length) {
      const message = localize(6926, null);
      const option = await this.mb.pick(options3.sort((a, b) => a.label.localeCompare(b.label)), { placeHolder: message });
      if (!option) {
        return;
      }
      targetPlatform = option.id;
    }
    if (targetPlatform !== galleryExtension.properties.targetPlatform) {
      [galleryExtension] = await this.J.getExtensions([{ id: extensionId, preRelease }], { compatible: true, targetPlatform }, CancellationToken.None);
    }
    const result = await this.lb.showOpenDialog({
      title: localize(6927, null),
      canSelectFiles: false,
      canSelectFolders: true,
      canSelectMany: false,
      openLabel: localize(6928, null)
    });
    if (!result?.[0]) {
      return;
    }
    this.Q.withProgress({
      location: 15
      /* ProgressLocation.Notification */
    }, async (progress) => {
      progress.report({ message: localize(6929, null) });
      const name = `${galleryExtension.identifier.id}-${galleryExtension.version}${targetPlatform !== "undefined" && targetPlatform !== "universal" && targetPlatform !== "unknown" ? `-${targetPlatform}` : ""}.vsix`;
      await this.J.download(
        galleryExtension,
        this.ib.extUri.joinPath(result[0], name),
        1
        /* InstallOperation.None */
      );
      this.N.info(localize(6930, null));
    });
  }
  async Lb(gallery) {
    const extensions = [];
    if (this.h) {
      extensions.push(this.h);
    }
    if (this.j) {
      extensions.push(this.j);
    }
    if (this.n) {
      extensions.push(this.n);
    }
    if (!extensions.length) {
      return;
    }
    await Promise.allSettled(extensions.map((extensions2) => extensions2.syncInstalledExtensionsWithGallery(gallery, this.Tb())));
    if (this.outdated.length) {
      this.Pb();
    }
  }
  Mb() {
    return this.L.getValue($yzb);
  }
  Nb(immediate = false) {
    this.t.cancel();
    this.t.trigger(async () => {
      if (this.Mb()) {
        await this.checkForUpdates();
      }
      this.Nb();
    }, immediate ? 0 : this.Ob()).then(void 0, (err) => null);
  }
  Ob() {
    if (this.X.quality === "insider" && this.Vb()) {
      return 1e3 * 60 * 60 * 1;
    }
    return $kec_1.f;
  }
  Pb() {
    this.u.trigger(() => this.Sb()).then(void 0, (err) => null);
  }
  async Qb() {
    await this.checkForUpdates(true);
    const toUpdate = this.outdated.filter((e) => e.isBuiltin);
    await Promises.settled(toUpdate.map((e) => this.install(e, e.local?.preRelease ? { installPreReleaseVersion: true } : void 0)));
  }
  async Rb() {
    const infos = [];
    for (const installed of this.local) {
      if (installed.isBuiltin && installed.local?.pinned && installed.local?.identifier.uuid) {
        infos.push({ ...installed.identifier, version: installed.version });
      }
    }
    if (infos.length) {
      const galleryExtensions = await this.J.getExtensions(infos, CancellationToken.None);
      if (galleryExtensions.length) {
        await this.Lb(galleryExtensions);
      }
    }
  }
  async Sb() {
    const toUpdate = [];
    for (const extension of this.outdated) {
      if (!this.Wb(extension)) {
        continue;
      }
      if (await this.shouldRequireConsentToUpdate(extension)) {
        continue;
      }
      toUpdate.push(extension);
    }
    if (!toUpdate.length) {
      return;
    }
    const productVersion = this.Tb();
    await Promises.settled(toUpdate.map((e) => this.install(e, e.local?.preRelease ? { installPreReleaseVersion: true, productVersion } : { productVersion })));
  }
  Tb() {
    return this.Vb() ?? this.Ub();
  }
  Ub() {
    return { version: this.X.version, date: this.X.date };
  }
  Vb() {
    switch (this.hb.state.type) {
      case "available for download":
      case "downloaded":
      case "updating":
      case "ready": {
        const version2 = this.hb.state.update.productVersion;
        if (version2 && valid(version2)) {
          return { version: version2, date: this.hb.state.update.timestamp ? new Date(this.hb.state.update.timestamp).toISOString() : void 0 };
        }
      }
    }
    return void 0;
  }
  Wb(extension) {
    if (extension.deprecationInfo?.disallowInstall) {
      return false;
    }
    const autoUpdateValue = this.getAutoUpdateValue();
    if (autoUpdateValue === false) {
      const extensionsToAutoUpdate = this.getEnabledAutoUpdateExtensions();
      const extensionId = extension.identifier.id.toLowerCase();
      if (extensionsToAutoUpdate.includes(extensionId)) {
        return true;
      }
      if (this.Xb(extension.publisher) && !extensionsToAutoUpdate.includes(`-${extensionId}`)) {
        return true;
      }
      return false;
    }
    if (extension.pinned) {
      return false;
    }
    const disabledAutoUpdateExtensions = this.getDisabledAutoUpdateExtensions();
    if (disabledAutoUpdateExtensions.includes(extension.identifier.id.toLowerCase())) {
      return false;
    }
    if (autoUpdateValue === true) {
      return true;
    }
    if (autoUpdateValue === "onlyEnabledExtensions") {
      return this.O.isEnabledEnablementState(extension.enablementState);
    }
    return false;
  }
  async shouldRequireConsentToUpdate(extension) {
    if (!extension.outdated) {
      return;
    }
    if (extension.local?.manifest.main || extension.local?.manifest.browser) {
      return;
    }
    if (!extension.gallery) {
      return;
    }
    if ($Hg(extension.gallery.properties?.executesCode)) {
      if (!extension.gallery.properties.executesCode) {
        return;
      }
    } else {
      const manifest = extension instanceof $jec ? await extension.getGalleryManifest() : await this.J.getManifest(extension.gallery, CancellationToken.None);
      if (!manifest?.main && !manifest?.browser) {
        return;
      }
    }
    return localize(6931, null, extension.displayName);
  }
  isAutoUpdateEnabledFor(extensionOrPublisher) {
    if ($zg(extensionOrPublisher)) {
      if ($dA.test(extensionOrPublisher)) {
        throw new Error("Expected publisher string, found extension identifier");
      }
      if (this.rb()) {
        return true;
      }
      return this.Xb(extensionOrPublisher);
    }
    return this.Wb(extensionOrPublisher);
  }
  Xb(publisher) {
    const publishersToAutoUpdate = this.tc();
    return publishersToAutoUpdate.includes(publisher.toLowerCase());
  }
  async updateAutoUpdateEnablementFor(extensionOrPublisher, enable) {
    if (this.rb()) {
      if ($zg(extensionOrPublisher)) {
        throw new Error("Expected extension, found publisher string");
      }
      const disabledAutoUpdateExtensions = this.getDisabledAutoUpdateExtensions();
      const extensionId = extensionOrPublisher.identifier.id.toLowerCase();
      const extensionIndex = disabledAutoUpdateExtensions.indexOf(extensionId);
      if (enable) {
        if (extensionIndex !== -1) {
          disabledAutoUpdateExtensions.splice(extensionIndex, 1);
        }
      } else {
        if (extensionIndex === -1) {
          disabledAutoUpdateExtensions.push(extensionId);
        }
      }
      this.zc(disabledAutoUpdateExtensions);
      if (enable && extensionOrPublisher.local && extensionOrPublisher.pinned) {
        await this.I.updateMetadata(extensionOrPublisher.local, { pinned: false });
      }
      this.w.fire(extensionOrPublisher);
    } else {
      const enabledAutoUpdateExtensions = this.getEnabledAutoUpdateExtensions();
      if ($zg(extensionOrPublisher)) {
        if ($dA.test(extensionOrPublisher)) {
          throw new Error("Expected publisher string, found extension identifier");
        }
        extensionOrPublisher = extensionOrPublisher.toLowerCase();
        if (this.isAutoUpdateEnabledFor(extensionOrPublisher) !== enable) {
          if (enable) {
            enabledAutoUpdateExtensions.push(extensionOrPublisher);
          } else {
            if (enabledAutoUpdateExtensions.includes(extensionOrPublisher)) {
              enabledAutoUpdateExtensions.splice(enabledAutoUpdateExtensions.indexOf(extensionOrPublisher), 1);
            }
          }
        }
        this.uc(enabledAutoUpdateExtensions);
        for (const e of this.installed) {
          if (e.publisher.toLowerCase() === extensionOrPublisher) {
            this.w.fire(e);
          }
        }
      } else {
        const extensionId = extensionOrPublisher.identifier.id.toLowerCase();
        const enableAutoUpdatesForPublisher = this.isAutoUpdateEnabledFor(extensionOrPublisher.publisher.toLowerCase());
        const enableAutoUpdatesForExtension = enabledAutoUpdateExtensions.includes(extensionId);
        const disableAutoUpdatesForExtension = enabledAutoUpdateExtensions.includes(`-${extensionId}`);
        if (enable) {
          if (disableAutoUpdatesForExtension) {
            enabledAutoUpdateExtensions.splice(enabledAutoUpdateExtensions.indexOf(`-${extensionId}`), 1);
          }
          if (enableAutoUpdatesForPublisher) {
            if (enableAutoUpdatesForExtension) {
              enabledAutoUpdateExtensions.splice(enabledAutoUpdateExtensions.indexOf(extensionId), 1);
            }
          } else {
            if (!enableAutoUpdatesForExtension) {
              enabledAutoUpdateExtensions.push(extensionId);
            }
          }
        } else {
          if (enableAutoUpdatesForExtension) {
            enabledAutoUpdateExtensions.splice(enabledAutoUpdateExtensions.indexOf(extensionId), 1);
          }
          if (enableAutoUpdatesForPublisher) {
            if (!disableAutoUpdatesForExtension) {
              enabledAutoUpdateExtensions.push(`-${extensionId}`);
            }
          } else {
            if (disableAutoUpdatesForExtension) {
              enabledAutoUpdateExtensions.splice(enabledAutoUpdateExtensions.indexOf(`-${extensionId}`), 1);
            }
          }
        }
        this.uc(enabledAutoUpdateExtensions);
        this.w.fire(extensionOrPublisher);
      }
    }
    if (enable) {
      this.Sb();
    }
  }
  Yb() {
    if (this.wc !== this.xc() || this.Bc !== this.Cc()) {
      const userExtensions = this.installed.filter((e) => !e.isBuiltin);
      const groupBy = (extensions) => {
        const shouldAutoUpdate2 = [];
        const shouldNotAutoUpdate2 = [];
        for (const extension of extensions) {
          if (this.Wb(extension)) {
            shouldAutoUpdate2.push(extension);
          } else {
            shouldNotAutoUpdate2.push(extension);
          }
        }
        return [shouldAutoUpdate2, shouldNotAutoUpdate2];
      };
      const [wasShouldAutoUpdate, wasShouldNotAutoUpdate] = groupBy(userExtensions);
      this.vc = void 0;
      this.Ac = void 0;
      const [shouldAutoUpdate, shouldNotAutoUpdate] = groupBy(userExtensions);
      for (const e of wasShouldAutoUpdate ?? []) {
        if (shouldNotAutoUpdate?.includes(e)) {
          this.w.fire(e);
        }
      }
      for (const e of wasShouldNotAutoUpdate ?? []) {
        if (shouldAutoUpdate?.includes(e)) {
          this.w.fire(e);
        }
      }
    }
  }
  async canInstall(extension) {
    if (!(extension instanceof $jec)) {
      return new $bm().appendText(localize(6932, null));
    }
    if (extension.isMalicious) {
      return new $bm().appendText(localize(6933, null));
    }
    if (extension.deprecationInfo?.disallowInstall) {
      return new $bm().appendText(localize(6934, null));
    }
    if (extension.gallery) {
      if (!extension.gallery.isSigned) {
        return new $bm().appendText(localize(6935, null));
      }
      const localResult = this.h ? await this.h.canInstall(extension.gallery) : void 0;
      if (localResult === true) {
        return true;
      }
      const remoteResult = this.j ? await this.j.canInstall(extension.gallery) : void 0;
      if (remoteResult === true) {
        return true;
      }
      const webResult = this.n ? await this.n.canInstall(extension.gallery) : void 0;
      if (webResult === true) {
        return true;
      }
      return localResult ?? remoteResult ?? webResult ?? new $bm().appendText(localize(6936, null, extension.displayName ?? extension.identifier.id));
    }
    if (extension.resourceExtension && await this.I.canInstall(extension.resourceExtension) === true) {
      return true;
    }
    return new $bm().appendText(localize(6937, null, extension.displayName ?? extension.identifier.id));
  }
  async install(arg, installOptions = {}, progressLocation) {
    let installable;
    let extension;
    if (arg instanceof URI) {
      installable = arg;
    } else {
      let installableInfo;
      let gallery;
      if ($zg(arg)) {
        extension = this.local.find((e) => $DA(e.identifier, { id: arg }));
        if (!extension?.isBuiltin) {
          installableInfo = { id: arg, version: installOptions.version, preRelease: installOptions.installPreReleaseVersion ?? this.preferPreReleases };
        }
      } else if (arg.gallery) {
        extension = arg;
        gallery = arg.gallery;
        if (installOptions.version && installOptions.version !== gallery?.version) {
          installableInfo = { id: extension.identifier.id, version: installOptions.version };
        }
      } else if (arg.resourceExtension) {
        extension = arg;
        installable = arg.resourceExtension;
      }
      if (installableInfo) {
        const targetPlatform = extension?.server ? await extension.server.extensionManagementService.getTargetPlatform() : void 0;
        gallery = (await this.J.getExtensions([installableInfo], { targetPlatform }, CancellationToken.None)).at(0);
      }
      if (!extension && gallery) {
        extension = this.G.createInstance($jec, (ext) => this.Kb(ext), (ext) => this.Ib(ext), void 0, void 0, gallery, void 0);
        extension.setExtensionsControlManifest(await this.I.getExtensionsControlManifest());
      }
      if (extension?.isMalicious) {
        throw new Error(localize(6938, null));
      }
      if (!(installOptions.enable && extension?.local)) {
        if (!installable) {
          if (!gallery) {
            const id2 = $zg(arg) ? arg : arg.identifier.id;
            if (installOptions.version) {
              throw new Error(localize(6939, null, id2, installOptions.version));
            } else {
              throw new Error(localize(6940, null, id2));
            }
          }
          installable = gallery;
        }
        if (installOptions.version) {
          installOptions.installGivenVersion = true;
        }
        if (extension?.isWorkspaceScoped) {
          installOptions.isWorkspaceScoped = true;
        }
      }
    }
    if (installable) {
      if (installOptions.justification) {
        const syncCheck = $Gg(installOptions.isMachineScoped) && this.gb.isEnabled() && this.gb.isResourceEnabled(
          "extensions"
          /* SyncResource.Extensions */
        );
        const buttons = [];
        buttons.push({
          label: $zg(installOptions.justification) || !installOptions.justification.action ? localize(6941, null) : localize(6942, null, installOptions.justification.action),
          run: () => true
        });
        if (!extension) {
          buttons.push({ label: localize(6943, null), run: () => {
            this.open(extension);
            return false;
          } });
        }
        const result = await this.fb.prompt({
          title: localize(6944, null),
          message: extension ? localize(6945, null, extension.displayName, extension.publisherDisplayName) : localize(6946, null),
          detail: $zg(installOptions.justification) ? installOptions.justification : installOptions.justification.reason,
          cancelButton: true,
          buttons,
          checkbox: syncCheck ? {
            label: localize(6947, null),
            checked: true
          } : void 0
        });
        if (!result.result) {
          throw new $lb();
        }
        if (syncCheck) {
          installOptions.isMachineScoped = !result.checkboxChecked;
        }
      }
      if (installable instanceof URI) {
        extension = await this.cc(void 0, () => this.dc(installable, installOptions), progressLocation);
      } else if (extension) {
        if (extension.resourceExtension) {
          extension = await this.cc(extension, () => this.I.installResourceExtension(installable, installOptions), progressLocation);
        } else {
          extension = await this.cc(extension, () => this.ec(extension, installable, installOptions), progressLocation);
        }
      }
    }
    if (!extension) {
      throw new Error(localize(6948, null));
    }
    if (installOptions.enable) {
      if (extension.enablementState === 9 || extension.enablementState === 8) {
        if (installOptions.justification) {
          const result = await this.fb.confirm({
            title: localize(6949, null),
            message: localize(6950, null, extension.displayName),
            detail: $zg(installOptions.justification) ? installOptions.justification : installOptions.justification.reason,
            primaryButton: $zg(installOptions.justification) ? localize(6951, null) : localize(6952, null, installOptions.justification.action)
          });
          if (!result.confirmed) {
            throw new $lb();
          }
        }
        await this.setEnablement(
          extension,
          extension.enablementState === 9 ? 11 : 10
          /* EnablementState.EnabledGlobally */
        );
      }
      await this.gc(extension);
    }
    return extension;
  }
  async installInServer(extension, server) {
    await this.cc(extension, async () => {
      const local = extension.local;
      if (!local) {
        throw new Error("Extension not found");
      }
      if (!extension.gallery) {
        extension = (await this.getExtensions([{ ...extension.identifier, preRelease: local.preRelease }], CancellationToken.None))[0] ?? extension;
      }
      if (extension.gallery) {
        return server.extensionManagementService.installFromGallery(extension.gallery, { installPreReleaseVersion: local.preRelease });
      }
      const targetPlatform = await server.extensionManagementService.getTargetPlatform();
      if (!$nA(local.targetPlatform, [local.targetPlatform], targetPlatform)) {
        throw new Error(localize(6953, null, extension.identifier.id));
      }
      const vsix = await this.I.zip(local);
      try {
        return await server.extensionManagementService.install(vsix);
      } finally {
        try {
          await this.cb.del(vsix);
        } catch (error) {
          this.Z.error(error);
        }
      }
    });
  }
  canSetLanguage(extension) {
    if (!$r) {
      return false;
    }
    if (!extension.gallery) {
      return false;
    }
    const locale = $xX(extension.gallery);
    if (!locale) {
      return false;
    }
    return true;
  }
  async setLanguage(extension) {
    if (!this.canSetLanguage(extension)) {
      throw new Error("Can not set language");
    }
    const locale = $xX(extension.gallery);
    if (locale === $z) {
      return;
    }
    const localizedLanguageName = extension.gallery?.properties?.localizedLanguages?.[0];
    return this.ab.setLocale({ id: locale, galleryExtension: extension.gallery, extensionId: extension.identifier.id, label: localizedLanguageName ?? extension.displayName });
  }
  setEnablement(extensions, enablementState) {
    extensions = Array.isArray(extensions) ? extensions : [extensions];
    return this.hc(extensions, enablementState);
  }
  async uninstall(e) {
    const extension = e.local ? e : this.local.find((local) => $DA(local.identifier, e.identifier));
    if (!extension?.local) {
      throw new Error("Missing local");
    }
    const extensionsToUninstall = [{ extension: extension.local }];
    for (const packExtension of this.Zb(extension.local, this.local)) {
      if (!extensionsToUninstall.some((e2) => $DA(e2.extension.identifier, packExtension.identifier))) {
        extensionsToUninstall.push({ extension: packExtension });
      }
    }
    const dependents = [];
    for (const { extension: extension2 } of extensionsToUninstall) {
      for (const local of this.local) {
        if (!local.local) {
          continue;
        }
        if ($DA(local.identifier, extension2.identifier)) {
          continue;
        }
        if (local.dependencies.length === 0) {
          continue;
        }
        if (extension2.manifest.extensionPack?.some((id2) => $DA({ id: id2 }, local.identifier))) {
          continue;
        }
        if (dependents.some((d) => d.extensionPack.some((id2) => $DA({ id: id2 }, local.identifier)))) {
          continue;
        }
        if (local.dependencies.some((dep) => $DA(extension2.identifier, { id: dep }))) {
          dependents.push(local);
          extensionsToUninstall.push({ extension: local.local });
        }
      }
    }
    if (dependents.length) {
      const { result } = await this.fb.prompt({
        title: localize(6954, null),
        type: Severity2.Warning,
        message: this.$b(extension, dependents),
        buttons: [{
          label: localize(6955, null),
          run: () => true
        }],
        cancelButton: {
          run: () => false
        }
      });
      if (!result) {
        throw new $lb();
      }
    }
    return this.qc({
      location: 5,
      title: localize(6956, null),
      source: `${extension.identifier.id}`
    }, () => this.I.uninstallExtensions(extensionsToUninstall).then(() => void 0));
  }
  Zb(extension, installed, checked = []) {
    if (checked.some((e) => $DA(e.identifier, extension.identifier))) {
      return [];
    }
    checked.push(extension);
    const extensionsPack = extension.manifest.extensionPack ?? [];
    if (extensionsPack.length) {
      const packedExtensions = [];
      for (const i2 of installed) {
        if (i2.local && !i2.isBuiltin && extensionsPack.some((id2) => $DA({ id: id2 }, i2.identifier))) {
          packedExtensions.push(i2.local);
        }
      }
      const packOfPackedExtensions = [];
      for (const packedExtension of packedExtensions) {
        packOfPackedExtensions.push(...this.Zb(packedExtension, installed, checked));
      }
      return [...packedExtensions, ...packOfPackedExtensions];
    }
    return [];
  }
  $b(extension, dependents) {
    if (dependents.length === 1) {
      return localize(6957, null, extension.displayName, dependents[0].displayName);
    }
    if (dependents.length === 2) {
      return localize(6958, null, extension.displayName, dependents[0].displayName, dependents[1].displayName);
    }
    return localize(6959, null, extension.displayName, dependents[0].displayName, dependents[1].displayName);
  }
  reinstall(extension) {
    return this.cc(extension, () => {
      const ext = extension.local ? extension : this.local.filter((e) => $DA(e.identifier, extension.identifier))[0];
      const toReinstall = ext && ext.local ? ext.local : null;
      if (!toReinstall) {
        throw new Error("Missing local");
      }
      return this.I.reinstallFromGallery(toReinstall);
    });
  }
  isExtensionIgnoredToSync(extension) {
    return extension.local ? !this.bc(extension.local) : this.U.hasToNeverSyncExtension(extension.identifier.id);
  }
  async togglePreRelease(extension) {
    if (!extension.local) {
      return;
    }
    if (extension.preRelease !== extension.isPreReleaseVersion) {
      await this.I.updateMetadata(extension.local, { preRelease: !extension.preRelease });
      return;
    }
    await this.install(extension, { installPreReleaseVersion: !extension.preRelease, preRelease: !extension.preRelease });
  }
  async toggleExtensionIgnoredToSync(extension) {
    const isIgnored = this.isExtensionIgnoredToSync(extension);
    if (extension.local && isIgnored) {
      extension.local = await this.updateSynchronizingInstalledExtension(extension.local, true);
      this.w.fire(extension);
    } else {
      this.U.updateIgnoredExtensions(extension.identifier.id, !isIgnored);
    }
    await this.W.triggerSync(["IgnoredExtensionsUpdated"], false, false);
  }
  async toggleApplyExtensionToAllProfiles(extension) {
    if (!extension.local || $8z(extension.local.manifest) || extension.isBuiltin) {
      return;
    }
    const isApplicationScoped = extension.local.isApplicationScoped;
    await Promise.all(this.ac().map(async (extensions) => {
      const local = extensions.local.find((e) => $DA(e.identifier, extension.identifier))?.local;
      if (local && local.isApplicationScoped === isApplicationScoped) {
        await this.I.toggleAppliationScope(local, this.db.currentProfile.extensionsResource);
      }
    }));
  }
  ac() {
    const extensions = [];
    if (this.h) {
      extensions.push(this.h);
    }
    if (this.j) {
      extensions.push(this.j);
    }
    if (this.n) {
      extensions.push(this.n);
    }
    return extensions;
  }
  bc(extension) {
    if (extension.isMachineScoped) {
      return false;
    }
    if (this.U.hasToAlwaysSyncExtension(extension.identifier.id)) {
      return true;
    }
    return !this.U.hasToNeverSyncExtension(extension.identifier.id);
  }
  async updateSynchronizingInstalledExtension(extension, sync) {
    const isMachineScoped = !sync;
    if (extension.isMachineScoped !== isMachineScoped) {
      extension = await this.I.updateMetadata(extension, { isMachineScoped });
    }
    if (sync) {
      this.U.updateIgnoredExtensions(extension.identifier.id, false);
    }
    return extension;
  }
  cc(extension, installTask, progressLocation) {
    const title = extension ? localize(6960, null, extension.displayName) : localize(6961, null);
    return this.qc({
      location: progressLocation ?? 5,
      title
    }, async () => {
      try {
        if (extension) {
          this.D.push(extension);
          this.w.fire(extension);
        }
        const local = await installTask();
        return await this.fc(local.identifier);
      } finally {
        if (extension) {
          this.D = this.D.filter((e) => e !== extension);
          this.w.fire(void 0);
        }
      }
    });
  }
  async dc(vsix, installOptions) {
    const manifest = await this.I.getManifest(vsix);
    const existingExtension = this.local.find((local) => $DA(local.identifier, { id: $IA(manifest.publisher, manifest.name) }));
    if (existingExtension) {
      installOptions = installOptions || {};
      if (existingExtension.latestVersion === manifest.version) {
        installOptions.pinned = existingExtension.local?.pinned || !this.Wb(existingExtension);
      } else {
        installOptions.installGivenVersion = true;
      }
    }
    return this.I.installVSIX(vsix, manifest, installOptions);
  }
  ec(extension, gallery, installOptions) {
    installOptions = installOptions ?? {};
    installOptions.pinned = extension.local?.pinned || !this.Wb(extension);
    if (extension.local) {
      installOptions.productVersion = this.Tb();
      installOptions.operation = 3;
      return this.I.updateFromGallery(gallery, extension.local, installOptions);
    } else {
      return this.I.installFromGallery(gallery, installOptions);
    }
  }
  async fc(identifier2) {
    let installedExtension = this.local.find((local) => $DA(local.identifier, identifier2));
    if (!installedExtension) {
      await Event2.toPromise(Event2.filter(this.onChange, (e) => !!e && this.local.some((local) => $DA(local.identifier, identifier2))));
    }
    installedExtension = this.local.find((local) => $DA(local.identifier, identifier2));
    if (!installedExtension) {
      throw new Error("Extension should have been installed");
    }
    return installedExtension;
  }
  async gc(extension) {
    if (this.$.extensions.find((e) => $5z.equals(e.identifier, extension.identifier.id))) {
      return;
    }
    if (!extension.local || !this.$.canAddExtension($EN(extension.local))) {
      return;
    }
    await new Promise((c, e) => {
      const disposable = this.$.onDidChangeExtensions(() => {
        try {
          if (this.$.extensions.find((e2) => $5z.equals(e2.identifier, extension.identifier.id))) {
            disposable.dispose();
            c();
          }
        } catch (error) {
          e(error);
        }
      });
    });
  }
  hc(extensions, enablementState) {
    const enable = enablementState === 10 || enablementState === 11;
    if (enable) {
      const allDependenciesAndPackedExtensions = this.jc(extensions, this.local, enablementState, { dependencies: true, pack: true });
      return this.ic(extensions, allDependenciesAndPackedExtensions, enablementState);
    } else {
      const packedExtensions = this.jc(extensions, this.local, enablementState, { dependencies: false, pack: true });
      if (packedExtensions.length) {
        return this.ic(extensions, packedExtensions, enablementState);
      }
      return this.ic(extensions, [], enablementState);
    }
  }
  async ic(extensions, otherExtensions, enablementState) {
    const allExtensions = [...extensions, ...otherExtensions];
    const enable = enablementState === 10 || enablementState === 11;
    if (!enable) {
      for (const extension of extensions) {
        const dependents = this.kc(extension, allExtensions, this.local);
        if (dependents.length) {
          const { result } = await this.fb.prompt({
            title: localize(6962, null),
            type: Severity2.Warning,
            message: this.lc(extension, allExtensions, dependents),
            buttons: [{
              label: localize(6963, null),
              run: () => true
            }],
            cancelButton: {
              run: () => false
            }
          });
          if (!result) {
            throw new $lb();
          }
          await this.ic(dependents, [extension], enablementState);
        }
      }
    }
    return this.nc(allExtensions, enablementState);
  }
  jc(extensions, installed, enablementState, options3, checked = []) {
    const toCheck = extensions.filter((e) => checked.indexOf(e) === -1);
    if (toCheck.length) {
      for (const extension of toCheck) {
        checked.push(extension);
      }
      const extensionsToEanbleOrDisable = installed.filter((i2) => {
        if (checked.indexOf(i2) !== -1) {
          return false;
        }
        const enable = enablementState === 10 || enablementState === 11;
        const isExtensionEnabled = i2.enablementState === 10 || i2.enablementState === 11;
        if (enable === isExtensionEnabled) {
          return false;
        }
        return (enable || !i2.isBuiltin) && (options3.dependencies || options3.pack) && extensions.some((extension) => options3.dependencies && extension.dependencies.some((id2) => $DA({ id: id2 }, i2.identifier)) || options3.pack && extension.extensionPack.some((id2) => $DA({ id: id2 }, i2.identifier)));
      });
      if (extensionsToEanbleOrDisable.length) {
        extensionsToEanbleOrDisable.push(...this.jc(extensionsToEanbleOrDisable, installed, enablementState, options3, checked));
      }
      return extensionsToEanbleOrDisable;
    }
    return [];
  }
  kc(extension, extensionsToDisable, installed) {
    return installed.filter((i2) => {
      if (i2.dependencies.length === 0) {
        return false;
      }
      if (i2 === extension) {
        return false;
      }
      if (!this.O.isEnabledEnablementState(i2.enablementState)) {
        return false;
      }
      if (extensionsToDisable.indexOf(i2) !== -1) {
        return false;
      }
      return i2.dependencies.some((dep) => [extension, ...extensionsToDisable].some((d) => $DA(d.identifier, { id: dep })));
    });
  }
  lc(extension, allDisabledExtensions, dependents) {
    for (const e of [extension, ...allDisabledExtensions]) {
      const dependentsOfTheExtension = dependents.filter((d) => d.dependencies.some((id2) => $DA({ id: id2 }, e.identifier)));
      if (dependentsOfTheExtension.length) {
        return this.mc(e, dependentsOfTheExtension);
      }
    }
    return "";
  }
  mc(extension, dependents) {
    if (dependents.length === 1) {
      return localize(6964, null, extension.displayName, dependents[0].displayName);
    }
    if (dependents.length === 2) {
      return localize(6965, null, extension.displayName, dependents[0].displayName, dependents[1].displayName);
    }
    return localize(6966, null, extension.displayName, dependents[0].displayName, dependents[1].displayName);
  }
  async nc(extensions, enablementState) {
    const changed = await this.O.setEnablement(extensions.map((e) => e.local), enablementState);
    for (let i2 = 0; i2 < changed.length; i2++) {
      if (changed[i2]) {
        this.M.publicLog(enablementState === 10 || enablementState === 11 ? "extension:enable" : "extension:disable", extensions[i2].telemetryData);
      }
    }
    return changed;
  }
  pc() {
    if (this.installed.some(
      (e) => e.state === 0 || e.state === 2
      /* ExtensionState.Uninstalling */
    )) {
      if (!this.oc) {
        this.qc({
          location: 5
          /* ProgressLocation.Extensions */
        }, () => new Promise((resolve) => this.oc = resolve));
      }
    } else {
      this.oc?.();
      this.oc = void 0;
    }
  }
  qc(options3, task) {
    return this.Q.withProgress(options3, async () => {
      const cancelableTask = $Hh(() => task());
      this.F.push(cancelableTask);
      try {
        return await cancelableTask;
      } finally {
        const index = this.F.indexOf(cancelableTask);
        if (index !== -1) {
          this.F.splice(index, 1);
        }
      }
    });
  }
  rc(err) {
    if ($kb(err)) {
      return;
    }
    const message = err && err.message || "";
    if (/getaddrinfo ENOTFOUND|getaddrinfo ENOENT|connect EACCES|connect ECONNREFUSED/.test(message)) {
      return;
    }
    this.N.error(err);
  }
  handleURL(uri, options3) {
    if (!/^extension/.test(uri.path)) {
      return Promise.resolve(false);
    }
    this.sc(uri);
    return Promise.resolve(true);
  }
  sc(uri) {
    const match = /^extension\/([^/]+)$/.exec(uri.path);
    if (!match) {
      return;
    }
    const extensionId = match[1];
    this.queryLocal().then(async (local) => {
      let extension = local.find((local2) => $DA(local2.identifier, { id: extensionId }));
      if (!extension) {
        [extension] = await this.getExtensions([{ id: extensionId }], { source: "uri" }, CancellationToken.None);
      }
      if (extension) {
        await this.P.focus($Y);
        await this.open(extension);
      }
    }).then(void 0, (error) => this.rc(error));
  }
  tc() {
    return this.getEnabledAutoUpdateExtensions().filter((id2) => !$dA.test(id2));
  }
  getEnabledAutoUpdateExtensions() {
    try {
      const parsedValue = JSON.parse(this.wc);
      if (Array.isArray(parsedValue)) {
        return parsedValue;
      }
    } catch (e) {
    }
    return [];
  }
  uc(enabledAutoUpdateExtensions) {
    this.wc = JSON.stringify(enabledAutoUpdateExtensions);
  }
  get wc() {
    if (!this.vc) {
      this.vc = this.xc();
    }
    return this.vc;
  }
  set wc(enabledAuotUpdateExtensionsValue) {
    if (this.wc !== enabledAuotUpdateExtensionsValue) {
      this.vc = enabledAuotUpdateExtensionsValue;
      this.yc(enabledAuotUpdateExtensionsValue);
    }
  }
  xc() {
    return this.eb.get(EXTENSIONS_AUTO_UPDATE_KEY, -1, "[]");
  }
  yc(value) {
    this.eb.store(
      EXTENSIONS_AUTO_UPDATE_KEY,
      value,
      -1,
      0
      /* StorageTarget.USER */
    );
  }
  getDisabledAutoUpdateExtensions() {
    try {
      const parsedValue = JSON.parse(this.Bc);
      if (Array.isArray(parsedValue)) {
        return parsedValue;
      }
    } catch (e) {
    }
    return [];
  }
  zc(disabledAutoUpdateExtensions) {
    this.Bc = JSON.stringify(disabledAutoUpdateExtensions);
  }
  get Bc() {
    if (!this.Ac) {
      this.Ac = this.Cc();
    }
    return this.Ac;
  }
  set Bc(disabledAutoUpdateExtensionsValue) {
    if (this.Bc !== disabledAutoUpdateExtensionsValue) {
      this.Ac = disabledAutoUpdateExtensionsValue;
      this.Dc(disabledAutoUpdateExtensionsValue);
    }
  }
  Cc() {
    return this.eb.get(EXTENSIONS_DONOT_AUTO_UPDATE_KEY, -1, "[]");
  }
  Dc(value) {
    this.eb.store(
      EXTENSIONS_DONOT_AUTO_UPDATE_KEY,
      value,
      -1,
      0
      /* StorageTarget.USER */
    );
  }
  Ec() {
    try {
      const parsedValue = JSON.parse(this.Hc);
      if (Array.isArray(parsedValue)) {
        return parsedValue;
      }
    } catch (e) {
    }
    return [];
  }
  Fc(dismissedNotifications) {
    this.Hc = JSON.stringify(dismissedNotifications);
  }
  get Hc() {
    if (!this.Gc) {
      this.Gc = this.Ic();
    }
    return this.Gc;
  }
  set Hc(dismissedNotificationsValue) {
    if (this.Hc !== dismissedNotificationsValue) {
      this.Gc = dismissedNotificationsValue;
      this.Jc(dismissedNotificationsValue);
    }
  }
  Ic() {
    return this.eb.get(EXTENSIONS_DISMISSED_NOTIFICATIONS_KEY, 0, "[]");
  }
  Jc(value) {
    this.eb.store(
      EXTENSIONS_DISMISSED_NOTIFICATIONS_KEY,
      value,
      0,
      0
      /* StorageTarget.USER */
    );
  }
};
$kec = $kec_1 = __decorate([
  __param(0, $Pk),
  __param(1, $mJ),
  __param(2, $pzb),
  __param(3, $pA),
  __param(4, $kl),
  __param(5, $zv),
  __param(6, $PJ),
  __param(7, $4y),
  __param(8, $qzb),
  __param(9, $S4),
  __param(10, $TJ),
  __param(11, $nzb),
  __param(12, $1E),
  __param(13, $DYb),
  __param(14, $9Bb),
  __param(15, $Vu),
  __param(16, $on),
  __param(17, $LCb),
  __param(18, $wn),
  __param(19, $wN),
  __param(20, $NCb),
  __param(21, $KL),
  __param(22, $km),
  __param(23, $gT),
  __param(24, $jv),
  __param(25, $Yv),
  __param(26, $6Bb),
  __param(27, $az),
  __param(28, $vl),
  __param(29, $Zk),
  __param(30, $uob),
  __param(31, $1v),
  __param(32, $1M),
  __param(33, $xA)
], $kec);

// out-build/vs/workbench/contrib/extensions/browser/extensionRecommendationNotificationService.js
var ignoreImportantExtensionRecommendationStorageKey = "extensionsAssistant/importantRecommendationsIgnore";
var donotShowWorkspaceRecommendationsStorageKey = "extensionsAssistant/workspaceRecommendationsIgnore";
var RecommendationsNotification = class extends $3c {
  constructor(h3, j, m, n) {
    super();
    this.h = h3;
    this.j = j;
    this.m = m;
    this.n = n;
    this.a = this.B(new $ze());
    this.onDidClose = this.a.event;
    this.b = this.B(new $ze());
    this.onDidChangeVisibility = this.b.event;
    this.g = false;
    this.s = this.B(new $4c());
    this.t = this.B(new $4c());
  }
  show() {
    if (!this.f) {
      this.u(this.n.prompt(this.h, this.j, this.m, { sticky: true, onCancel: () => this.g = true }));
    }
  }
  hide() {
    if (this.f) {
      this.s.clear();
      this.f.close();
      this.g = false;
      this.u(this.n.prompt(this.h, this.j, this.m, { priority: NotificationPriority.SILENT, onCancel: () => this.g = true }));
    }
  }
  isCancelled() {
    return this.g;
  }
  u(notificationHandle) {
    this.s.clear();
    this.t.clear();
    this.f = notificationHandle;
    this.s.value = this.f.onDidClose(() => {
      this.s.dispose();
      this.t.dispose();
      this.a.fire();
      this.a.dispose();
      this.b.dispose();
    });
    this.t.value = this.f.onDidChangeVisibility((e) => this.b.fire(e));
  }
};
var $lec = class $lec2 extends $3c {
  // Ignored Important Recommendations
  get ignoredRecommendations() {
    return $Rb([...JSON.parse(this.m.get(ignoreImportantExtensionRecommendationStorageKey, 0, "[]"))].map((i2) => i2.toLowerCase()));
  }
  constructor(j, m, n, s, t, u, w, y, z, C, D) {
    super();
    this.j = j;
    this.m = m;
    this.n = n;
    this.s = s;
    this.t = t;
    this.u = u;
    this.w = w;
    this.y = y;
    this.z = z;
    this.C = C;
    this.D = D;
    this.a = [];
    this.b = [];
    this.h = [];
  }
  hasToIgnoreRecommendationNotifications() {
    const config = this.j.getValue("extensions");
    return config.ignoreRecommendations || !!config.showRecommendationsOnlyOnDemand;
  }
  async promptImportantExtensionsInstallNotification(extensionRecommendations) {
    const ignoredRecommendations = [...this.y.ignoredRecommendations, ...this.ignoredRecommendations];
    const extensions = extensionRecommendations.extensions.filter((id2) => !ignoredRecommendations.includes(id2));
    if (!extensions.length) {
      return "ignored";
    }
    return this.F({ ...extensionRecommendations, extensions }, {
      onDidInstallRecommendedExtensions: (extensions2) => extensions2.forEach((extension) => this.s.publicLog2("extensionRecommendations:popup", { userReaction: "install", extensionId: extension.identifier.id, source: $$dc(extensionRecommendations.source) })),
      onDidShowRecommendedExtensions: (extensions2) => extensions2.forEach((extension) => this.s.publicLog2("extensionRecommendations:popup", { userReaction: "show", extensionId: extension.identifier.id, source: $$dc(extensionRecommendations.source) })),
      onDidCancelRecommendedExtensions: (extensions2) => extensions2.forEach((extension) => this.s.publicLog2("extensionRecommendations:popup", { userReaction: "cancelled", extensionId: extension.identifier.id, source: $$dc(extensionRecommendations.source) })),
      onDidNeverShowRecommendedExtensionsAgain: (extensions2) => {
        for (const extension of extensions2) {
          this.P(extension.identifier.id);
          this.s.publicLog2("extensionRecommendations:popup", { userReaction: "neverShowAgain", extensionId: extension.identifier.id, source: $$dc(extensionRecommendations.source) });
        }
        this.n.prompt(Severity2.Info, localize(6428, null), [{
          label: localize(6429, null),
          run: () => this.Q(true)
        }, {
          label: localize(6430, null),
          run: () => this.Q(false)
        }]);
      }
    });
  }
  async promptWorkspaceRecommendations(recommendations) {
    if (this.m.getBoolean(donotShowWorkspaceRecommendationsStorageKey, 1, false)) {
      return;
    }
    let installed = await this.u.getInstalled();
    installed = installed.filter(
      (l) => this.w.getEnablementState(l) !== 1
      /* EnablementState.DisabledByExtensionKind */
    );
    recommendations = recommendations.filter((recommendation) => installed.every((local) => $zg(recommendation) ? !$DA({ id: recommendation }, local.identifier) : !this.D.extUri.isEqual(recommendation, local.location)));
    if (!recommendations.length) {
      return;
    }
    await this.F({ extensions: recommendations, source: 2, name: localize(6431, null) }, {
      onDidInstallRecommendedExtensions: () => this.s.publicLog2("extensionWorkspaceRecommendations:popup", { userReaction: "install" }),
      onDidShowRecommendedExtensions: () => this.s.publicLog2("extensionWorkspaceRecommendations:popup", { userReaction: "show" }),
      onDidCancelRecommendedExtensions: () => this.s.publicLog2("extensionWorkspaceRecommendations:popup", { userReaction: "cancelled" }),
      onDidNeverShowRecommendedExtensionsAgain: () => {
        this.s.publicLog2("extensionWorkspaceRecommendations:popup", { userReaction: "neverShowAgain" });
        this.m.store(
          donotShowWorkspaceRecommendationsStorageKey,
          true,
          1,
          1
          /* StorageTarget.MACHINE */
        );
      }
    });
  }
  async F({ extensions: extensionIds, source, name, searchValue }, recommendationsNotificationActions) {
    if (this.hasToIgnoreRecommendationNotifications()) {
      return "ignored";
    }
    if (source === 3 && this.C.remoteAuthority) {
      return "incompatibleWindow";
    }
    if (source === 3 && (this.b.includes(
      3
      /* RecommendationSource.EXE */
    ) || this.b.length >= 2)) {
      return "toomany";
    }
    this.b.push(source);
    if (source === 3 && extensionIds.every((id2) => $zg(id2) && this.a.includes(id2))) {
      return "ignored";
    }
    const extensions = await this.O(extensionIds);
    if (!extensions.length) {
      return "ignored";
    }
    this.a = $Rb([...this.a, ...extensionIds.filter($zg)]);
    let extensionsMessage = "";
    if (extensions.length === 1) {
      extensionsMessage = localize(6432, null, extensions[0].displayName, extensions[0].publisherDisplayName);
    } else {
      const publishers = [...extensions.reduce((result, extension) => result.add(extension.publisherDisplayName), /* @__PURE__ */ new Set())];
      if (publishers.length > 2) {
        extensionsMessage = localize(6433, null, publishers[0], publishers[1]);
      } else if (publishers.length === 2) {
        extensionsMessage = localize(6434, null, publishers[0], publishers[1]);
      } else {
        extensionsMessage = localize(6435, null, publishers[0]);
      }
    }
    let message = localize(6436, null, extensionsMessage, name);
    if (source === 3) {
      message = localize(6437, null, name, extensionsMessage);
    }
    if (!searchValue) {
      searchValue = source === 2 ? "@recommended" : extensions.map((extensionId) => `@id:${extensionId.identifier.id}`).join(" ");
    }
    const donotShowAgainLabel = source === 2 ? localize(6438, null) : extensions.length > 1 ? localize(6439, null) : localize(6440, null);
    return $Kh([
      this.R(this.G(extensions, message, searchValue, donotShowAgainLabel, source, recommendationsNotificationActions)),
      this.R(this.H(extensions))
    ]);
  }
  G(extensions, message, searchValue, donotShowAgainLabel, source, { onDidInstallRecommendedExtensions, onDidShowRecommendedExtensions, onDidCancelRecommendedExtensions, onDidNeverShowRecommendedExtensionsAgain }) {
    return $Hh(async (token) => {
      let accepted = false;
      const choices = [];
      const installExtensions = async (isMachineScoped) => {
        this.t.openSearch(searchValue);
        onDidInstallRecommendedExtensions(extensions);
        const galleryExtensions = [], resourceExtensions = [];
        for (const extension of extensions) {
          if (extension.gallery) {
            galleryExtensions.push(extension.gallery);
          } else if (extension.resourceExtension) {
            resourceExtensions.push(extension);
          }
        }
        await Promises.settled([
          Promises.settled(extensions.map((extension) => this.t.open(extension, { pinned: true }))),
          galleryExtensions.length ? this.u.installGalleryExtensions(galleryExtensions.map((e) => ({ extension: e, options: { isMachineScoped } }))) : Promise.resolve(),
          resourceExtensions.length ? Promise.allSettled(resourceExtensions.map((r2) => this.t.install(r2))) : Promise.resolve()
        ]);
      };
      choices.push({
        label: localize(6441, null),
        run: () => installExtensions(false),
        menu: this.z.isEnabled() && this.z.isResourceEnabled(
          "extensions"
          /* SyncResource.Extensions */
        ) ? [{
          label: localize(6442, null),
          run: () => installExtensions(true)
        }] : void 0
      });
      choices.push(...[{
        label: localize(6443, null),
        run: async () => {
          onDidShowRecommendedExtensions(extensions);
          for (const extension of extensions) {
            this.t.open(extension, { pinned: true });
          }
          this.t.openSearch(searchValue);
        }
      }, {
        label: donotShowAgainLabel,
        isSecondary: true,
        run: () => {
          onDidNeverShowRecommendedExtensionsAgain(extensions);
        }
      }]);
      try {
        accepted = await this.I(Severity2.Info, message, choices, source, token);
      } catch (error) {
        if (!$kb(error)) {
          throw error;
        }
      }
      if (accepted) {
        return "reacted";
      } else {
        onDidCancelRecommendedExtensions(extensions);
        return "cancelled";
      }
    });
  }
  H(extensions) {
    const installedExtensions = [];
    const disposables = new $2c();
    return $Hh(async (token) => {
      disposables.add(token.onCancellationRequested((e) => disposables.dispose()));
      return new Promise((c, e) => {
        disposables.add(this.u.onInstallExtension((e2) => {
          installedExtensions.push(e2.identifier.id.toLowerCase());
          if (extensions.every((e3) => installedExtensions.includes(e3.identifier.id.toLowerCase()))) {
            c(
              "reacted"
              /* RecommendationsNotificationResult.Accepted */
            );
          }
        }));
      });
    });
  }
  /**
   * Show recommendations in Queue
   * At any time only one recommendation is shown
   * If a new recommendation comes in
   * 		=> If no recommendation is visible, show it immediately
   *		=> Otherwise, add to the pending queue
   * 			=> If it is not exe based and has higher or same priority as current, hide the current notification after showing it for 3s.
   * 			=> Otherwise wait until the current notification is hidden.
   */
  async I(severity, message, choices, source, token) {
    const disposables = new $2c();
    try {
      const recommendationsNotification = disposables.add(new RecommendationsNotification(severity, message, choices, this.n));
      disposables.add(Event2.once(Event2.filter(recommendationsNotification.onDidChangeVisibility, (e) => !e))(() => this.J()));
      if (this.g) {
        const index = this.h.length;
        disposables.add(token.onCancellationRequested(() => this.h.splice(index, 1)));
        this.h.push({ recommendationsNotification, source, token });
        if (source !== 3 && source <= this.g.source) {
          this.M(3e3);
        }
      } else {
        this.g = { recommendationsNotification, source, from: Date.now() };
        recommendationsNotification.show();
      }
      await $Ih(new Promise((c) => disposables.add(Event2.once(recommendationsNotification.onDidClose)(c))), token);
      return !recommendationsNotification.isCancelled();
    } finally {
      disposables.dispose();
    }
  }
  J() {
    const index = this.L();
    const [nextNotificaiton] = index > -1 ? this.h.splice(index, 1) : [];
    $Wh(nextNotificaiton ? 500 : 0).then(() => {
      this.N();
      if (nextNotificaiton) {
        this.g = { recommendationsNotification: nextNotificaiton.recommendationsNotification, source: nextNotificaiton.source, from: Date.now() };
        nextNotificaiton.recommendationsNotification.show();
      }
    });
  }
  /**
   * Return the recent high priroity pending notification
   */
  L() {
    let index = this.h.length - 1;
    if (this.h.length) {
      for (let i2 = 0; i2 < this.h.length; i2++) {
        if (this.h[i2].source <= this.h[index].source) {
          index = i2;
        }
      }
    }
    return index;
  }
  M(timeInMillis) {
    if (this.g && !this.f) {
      const visibleNotification = this.g;
      this.f = $Wh(Math.max(timeInMillis - (Date.now() - visibleNotification.from), 0));
      this.f.then(() => visibleNotification.recommendationsNotification.hide());
    }
  }
  N() {
    this.f?.cancel();
    this.f = void 0;
    this.g = void 0;
  }
  async O(recommendations) {
    const result = [];
    if (recommendations.length) {
      const galleryExtensions = [];
      const resourceExtensions = [];
      for (const recommendation of recommendations) {
        if (typeof recommendation === "string") {
          galleryExtensions.push(recommendation);
        } else {
          resourceExtensions.push(recommendation);
        }
      }
      if (galleryExtensions.length) {
        const extensions = await this.t.getExtensions(galleryExtensions.map((id2) => ({ id: id2 })), { source: "install-recommendations" }, CancellationToken.None);
        for (const extension of extensions) {
          if (extension.gallery && await this.u.canInstall(extension.gallery) === true) {
            result.push(extension);
          }
        }
      }
      if (resourceExtensions.length) {
        const extensions = await this.t.getResourceExtensions(resourceExtensions, true);
        for (const extension of extensions) {
          if (await this.t.canInstall(extension) === true) {
            result.push(extension);
          }
        }
      }
    }
    return result;
  }
  P(id2) {
    const importantRecommendationsIgnoreList = [...this.ignoredRecommendations];
    if (!importantRecommendationsIgnoreList.includes(id2.toLowerCase())) {
      importantRecommendationsIgnoreList.push(id2.toLowerCase());
      this.m.store(
        ignoreImportantExtensionRecommendationStorageKey,
        JSON.stringify(importantRecommendationsIgnoreList),
        0,
        0
        /* StorageTarget.USER */
      );
    }
  }
  Q(configVal) {
    this.j.updateValue("extensions.ignoreRecommendations", configVal);
  }
  R(o) {
    this.B($1c(() => o.cancel()));
    return o;
  }
};
$lec = __decorate([
  __param(0, $kl),
  __param(1, $jv),
  __param(2, $PJ),
  __param(3, $zv),
  __param(4, $vzb),
  __param(5, $pzb),
  __param(6, $qzb),
  __param(7, $BBb),
  __param(8, $6Bb),
  __param(9, $US),
  __param(10, $vl)
], $lec);

// out-build/vs/workbench/services/extensions/common/extensionRunningLocation.js
var $lN = class {
  constructor(affinity) {
    this.affinity = affinity;
    this.kind = 1;
  }
  equals(other) {
    return this.kind === other.kind && this.affinity === other.affinity;
  }
  asString() {
    if (this.affinity === 0) {
      return "LocalProcess";
    }
    return `LocalProcess${this.affinity}`;
  }
};
var $mN = class {
  constructor(affinity) {
    this.affinity = affinity;
    this.kind = 2;
  }
  equals(other) {
    return this.kind === other.kind && this.affinity === other.affinity;
  }
  asString() {
    if (this.affinity === 0) {
      return "LocalWebWorker";
    }
    return `LocalWebWorker${this.affinity}`;
  }
};
var $nN = class {
  constructor() {
    this.kind = 3;
    this.affinity = 0;
  }
  equals(other) {
    return this.kind === other.kind;
  }
  asString() {
    return "Remote";
  }
};

// out-build/vs/workbench/contrib/extensions/common/runtimeExtensionsInput.js
var RuntimeExtensionsEditorIcon = $9r("runtime-extensions-editor-label-icon", $6l.extensions, localize(6984, null));
var $mec = class _$mec extends $nG {
  constructor() {
    super(...arguments);
    this.resource = URI.from({
      scheme: "runtime-extensions",
      path: "default"
    });
  }
  static {
    this.ID = "workbench.runtimeExtensions.input";
  }
  get typeId() {
    return _$mec.ID;
  }
  get capabilities() {
    return 2 | 8;
  }
  static get instance() {
    if (!_$mec._instance || _$mec._instance.isDisposed()) {
      _$mec._instance = new _$mec();
    }
    return _$mec._instance;
  }
  getName() {
    return localize(6985, null);
  }
  getIcon() {
    return RuntimeExtensionsEditorIcon;
  }
  matches(other) {
    if (super.matches(other)) {
      return true;
    }
    return other instanceof _$mec;
  }
};

// out-build/vs/workbench/contrib/extensions/browser/abstractRuntimeExtensionsEditor.js
var $nec_1;
var $nec = class $nec2 extends $5tb {
  static {
    $nec_1 = this;
  }
  static {
    this.ID = "workbench.editor.runtimeExtensions";
  }
  constructor(group2, telemetryService, themeService, m, r2, s, u, cb, db, storageService, eb, fb, gb, hb, ib, jb) {
    super($nec_1.ID, group2, telemetryService, themeService, storageService);
    this.m = m;
    this.r = r2;
    this.s = s;
    this.u = u;
    this.cb = cb;
    this.db = db;
    this.eb = eb;
    this.fb = fb;
    this.gb = gb;
    this.hb = hb;
    this.ib = ib;
    this.jb = jb;
    this.c = null;
    this.f = null;
    this.g = this.B(new $8h(() => this.kb(), 200));
    this.B(this.s.onDidChangeExtensionsStatus(() => this.g.schedule()));
    this.B(this.hb.onDidChangeAccessData(() => this.g.schedule()));
    this.kb();
  }
  async kb() {
    this.f = await this.lb();
    this.c?.splice(0, this.c.length, this.f);
  }
  async lb() {
    await this.s.whenInstalledExtensionsRegistered();
    const extensionsDescriptions = this.s.extensions.filter((extension) => {
      return Boolean(extension.main) || Boolean(extension.browser);
    });
    const marketplaceMap = new $7z();
    const marketPlaceExtensions = await this.r.queryLocal();
    for (const extension of marketPlaceExtensions) {
      marketplaceMap.set(extension.identifier.id, extension);
    }
    const statusMap = this.s.getExtensionsStatus();
    const segments = new $7z();
    const profileInfo = this.nb();
    if (profileInfo) {
      let currentStartTime = profileInfo.startTime;
      for (let i2 = 0, len = profileInfo.deltas.length; i2 < len; i2++) {
        const id2 = profileInfo.ids[i2];
        const delta = profileInfo.deltas[i2];
        let extensionSegments = segments.get(id2);
        if (!extensionSegments) {
          extensionSegments = [];
          segments.set(id2, extensionSegments);
        }
        extensionSegments.push(currentStartTime);
        currentStartTime = currentStartTime + delta;
        extensionSegments.push(currentStartTime);
      }
    }
    let result = [];
    for (let i2 = 0, len = extensionsDescriptions.length; i2 < len; i2++) {
      const extensionDescription = extensionsDescriptions[i2];
      let extProfileInfo = null;
      if (profileInfo) {
        const extensionSegments = segments.get(extensionDescription.identifier) || [];
        let extensionTotalTime = 0;
        for (let j = 0, lenJ = extensionSegments.length / 2; j < lenJ; j++) {
          const startTime = extensionSegments[2 * j];
          const endTime = extensionSegments[2 * j + 1];
          extensionTotalTime += endTime - startTime;
        }
        extProfileInfo = {
          segments: extensionSegments,
          totalTime: extensionTotalTime
        };
      }
      result[i2] = {
        originalIndex: i2,
        description: extensionDescription,
        marketplaceInfo: marketplaceMap.get(extensionDescription.identifier),
        status: statusMap[extensionDescription.identifier.value],
        profileInfo: extProfileInfo || void 0,
        unresponsiveProfile: this.ob(extensionDescription.identifier)
      };
    }
    result = result.filter((element) => element.status.activationStarted);
    const isUnresponsive = (extension) => extension.unresponsiveProfile === profileInfo;
    const profileTime = (extension) => extension.profileInfo?.totalTime ?? 0;
    const activationTime = (extension) => (extension.status.activationTimes?.codeLoadingTime ?? 0) + (extension.status.activationTimes?.activateCallTime ?? 0);
    result = result.sort((a, b) => {
      if (isUnresponsive(a) || isUnresponsive(b)) {
        return +isUnresponsive(b) - +isUnresponsive(a);
      } else if (profileTime(a) || profileTime(b)) {
        return profileTime(b) - profileTime(a);
      } else if (activationTime(a) || activationTime(b)) {
        return activationTime(b) - activationTime(a);
      }
      return a.originalIndex - b.originalIndex;
    });
    return result;
  }
  Y(parent) {
    parent.classList.add("runtime-extensions-editor");
    const TEMPLATE_ID = "runtimeExtensionElementTemplate";
    const delegate = new class {
      getHeight(element) {
        return 70;
      }
      getTemplateId(element) {
        return TEMPLATE_ID;
      }
    }();
    const renderer = {
      templateId: TEMPLATE_ID,
      renderTemplate: (root) => {
        const element = $bk(root, $(".extension"));
        const iconContainer = $bk(element, $(".icon-container"));
        const icon2 = $bk(iconContainer, $("img.icon"));
        const desc = $bk(element, $("div.desc"));
        const headerContainer = $bk(desc, $(".header-container"));
        const header = $bk(headerContainer, $(".header"));
        const name = $bk(header, $("div.name"));
        const version2 = $bk(header, $("span.version"));
        const msgContainer = $bk(desc, $("div.msg"));
        const actionbar = new $LZ(desc);
        actionbar.onDidRun(({ error }) => error && this.u.error(error));
        const timeContainer = $bk(element, $(".time"));
        const activationTime = $bk(timeContainer, $("div.activation-time"));
        const profileTime = $bk(timeContainer, $("div.profile-time"));
        const disposables = [actionbar];
        return {
          root,
          element,
          icon: icon2,
          name,
          version: version2,
          actionbar,
          activationTime,
          profileTime,
          msgContainer,
          disposables,
          elementDisposables: []
        };
      },
      renderElement: (element, index, data) => {
        data.elementDisposables = $Xc(data.elementDisposables);
        data.root.classList.toggle("odd", index % 2 === 1);
        data.elementDisposables.push($_i(data.icon, "error", () => data.icon.src = element.marketplaceInfo?.iconUrlFallback || $ozb, { once: true }));
        data.icon.src = element.marketplaceInfo?.iconUrl || $ozb;
        if (!data.icon.complete) {
          data.icon.style.visibility = "hidden";
          data.icon.onload = () => data.icon.style.visibility = "inherit";
        } else {
          data.icon.style.visibility = "inherit";
        }
        data.name.textContent = (element.marketplaceInfo?.displayName || element.description.identifier.value).substr(0, 50);
        data.version.textContent = element.description.version;
        const activationTimes = element.status.activationTimes;
        if (activationTimes) {
          const syncTime = activationTimes.codeLoadingTime + activationTimes.activateCallTime;
          data.activationTime.textContent = activationTimes.activationReason.startup ? `Startup Activation: ${syncTime}ms` : `Activation: ${syncTime}ms`;
        } else {
          data.activationTime.textContent = `Activating...`;
        }
        data.actionbar.clear();
        const slowExtensionAction = this.pb(element);
        if (slowExtensionAction) {
          data.actionbar.push(slowExtensionAction, { icon: false, label: true });
        }
        if ($Qb(element.status.runtimeErrors)) {
          const reportExtensionIssueAction = this.qb(element);
          if (reportExtensionIssueAction) {
            data.actionbar.push(reportExtensionIssueAction, { icon: false, label: true });
          }
        }
        let title;
        if (activationTimes) {
          const activationId = activationTimes.activationReason.extensionId.value;
          const activationEvent = activationTimes.activationReason.activationEvent;
          if (activationEvent === "*") {
            title = localize(6337, null, activationId);
          } else if (/^workspaceContains:/.test(activationEvent)) {
            const fileNameOrGlob = activationEvent.substr("workspaceContains:".length);
            if (fileNameOrGlob.indexOf("*") >= 0 || fileNameOrGlob.indexOf("?") >= 0) {
              title = localize(6338, null, fileNameOrGlob, activationId);
            } else {
              title = localize(6339, null, fileNameOrGlob, activationId);
            }
          } else if (/^workspaceContainsTimeout:/.test(activationEvent)) {
            const glob = activationEvent.substr("workspaceContainsTimeout:".length);
            title = localize(6340, null, glob, activationId);
          } else if (activationEvent === "onStartupFinished") {
            title = localize(6341, null, activationId);
          } else if (/^onLanguage:/.test(activationEvent)) {
            const language = activationEvent.substr("onLanguage:".length);
            title = localize(6342, null, language, activationId);
          } else {
            title = localize(6343, null, activationEvent, activationId);
          }
        } else {
          title = localize(6344, null);
        }
        data.elementDisposables.push(this.ib.setupManagedHover($JZ("mouse"), data.activationTime, title));
        $$i(data.msgContainer);
        if (this.ob(element.description.identifier)) {
          const el = $("span", void 0, ...$B1(` $(alert) Unresponsive`));
          const extensionHostFreezTitle = localize(6345, null);
          data.elementDisposables.push(this.ib.setupManagedHover($JZ("mouse"), el, extensionHostFreezTitle));
          data.msgContainer.appendChild(el);
        }
        if ($Qb(element.status.runtimeErrors)) {
          const el = $("span", void 0, ...$B1(`$(bug) ${localize(6346, null, element.status.runtimeErrors.length)}`));
          data.msgContainer.appendChild(el);
        }
        if (element.status.messages && element.status.messages.length > 0) {
          const el = $("span", void 0, ...$B1(`$(alert) ${element.status.messages[0].message}`));
          data.msgContainer.appendChild(el);
        }
        let extraLabel = null;
        if (element.status.runningLocation && element.status.runningLocation.equals(new $mN(0))) {
          extraLabel = `$(globe) web worker`;
        } else if (element.description.extensionLocation.scheme === Schemas.vscodeRemote) {
          const hostLabel = this.eb.getHostLabel(Schemas.vscodeRemote, this.fb.remoteAuthority);
          if (hostLabel) {
            extraLabel = `$(remote) ${hostLabel}`;
          } else {
            extraLabel = `$(remote) ${element.description.extensionLocation.authority}`;
          }
        } else if (element.status.runningLocation && element.status.runningLocation.affinity > 0) {
          extraLabel = element.status.runningLocation instanceof $mN ? `$(globe) web worker ${element.status.runningLocation.affinity + 1}` : `$(server-process) local process ${element.status.runningLocation.affinity + 1}`;
        }
        if (extraLabel) {
          const el = $("span", void 0, ...$B1(extraLabel));
          data.msgContainer.appendChild(el);
        }
        const features = $Wn.as(Extensions3.ExtensionFeaturesRegistry).getExtensionFeatures();
        for (const feature of features) {
          const accessData = this.hb.getAccessData(element.description.identifier, feature.id);
          if (accessData) {
            const status = accessData?.current?.status;
            if (status) {
              data.msgContainer.appendChild($("span", void 0, `${feature.label}: `));
              data.msgContainer.appendChild($("span", void 0, ...$B1(`$(${status.severity === Severity2.Error ? $vCb.id : $wCb.id}) ${status.message}`)));
            }
            if (accessData?.accessTimes.length > 0) {
              const element2 = $("span", void 0, `${localize(6347, null, feature.label, accessData.accessTimes.length)}${accessData.current ? localize(6348, null, accessData.current.accessTimes.length) : ""}`);
              if (accessData.current) {
                const title2 = localize(6349, null, $Qu(accessData.current.lastAccessed, true, true));
                data.elementDisposables.push(this.ib.setupManagedHover($JZ("mouse"), element2, title2));
              }
              data.msgContainer.appendChild(element2);
            }
          }
        }
        if (element.profileInfo) {
          data.profileTime.textContent = `Profile: ${(element.profileInfo.totalTime / 1e3).toFixed(2)}ms`;
        } else {
          data.profileTime.textContent = "";
        }
      },
      disposeTemplate: (data) => {
        data.disposables = $Xc(data.disposables);
      }
    };
    this.c = this.db.createInstance($Web, "RuntimeExtensions", parent, delegate, [renderer], {
      multipleSelectionSupport: false,
      setRowLineHeight: false,
      horizontalScrolling: false,
      overrideStyles: {
        listBackground: $Ko
      },
      accessibilityProvider: new class {
        getWidgetAriaLabel() {
          return localize(6350, null);
        }
        getAriaLabel(element) {
          return element.description.name;
        }
      }()
    });
    this.c.splice(0, this.c.length, this.f || void 0);
    this.c.onContextMenu((e) => {
      if (!e.element) {
        return;
      }
      const actions = [];
      actions.push(new $Um("runtimeExtensionsEditor.action.copyId", localize(6351, null, e.element.description.identifier.value), void 0, true, () => {
        this.gb.writeText(e.element.description.identifier.value);
      }));
      const reportExtensionIssueAction = this.qb(e.element);
      if (reportExtensionIssueAction) {
        actions.push(reportExtensionIssueAction);
      }
      actions.push(new $Wm());
      if (e.element.marketplaceInfo) {
        actions.push(new $Um("runtimeExtensionsEditor.action.disableWorkspace", localize(6352, null), void 0, true, () => this.r.setEnablement(
          e.element.marketplaceInfo,
          9
          /* EnablementState.DisabledWorkspace */
        )));
        actions.push(new $Um("runtimeExtensionsEditor.action.disable", localize(6353, null), void 0, true, () => this.r.setEnablement(
          e.element.marketplaceInfo,
          8
          /* EnablementState.DisabledGlobally */
        )));
      }
      actions.push(new $Wm());
      const menuActions = this.jb.getMenuActions($bJ.ExtensionEditorContextMenu, this.m);
      actions.push(...$O$(menuActions).secondary);
      this.cb.showContextMenu({
        getAnchor: () => e.anchor,
        getActions: () => actions
      });
    });
  }
  layout(dimension) {
    this.c?.layout(dimension.height);
  }
};
$nec = $nec_1 = __decorate([
  __param(1, $zv),
  __param(2, $gs),
  __param(3, $on),
  __param(4, $vzb),
  __param(5, $wN),
  __param(6, $PJ),
  __param(7, $50),
  __param(8, $Pk),
  __param(9, $jv),
  __param(10, $ZI),
  __param(11, $US),
  __param(12, $30),
  __param(13, $wlb),
  __param(14, $5$),
  __param(15, $cJ)
], $nec);
var $oec = class extends $gJ {
  constructor() {
    super({
      id: "workbench.action.showRuntimeExtensions",
      title: localize2(6354, "Show Running Extensions"),
      category: $qn.Developer,
      f1: true,
      menu: {
        id: $bJ.ViewContainerTitle,
        when: $7m.equals("viewContainer", "workbench.view.extensions"),
        group: "2_enablement",
        order: 3
      }
    });
  }
  async run(accessor) {
    await accessor.get($mJ).openEditor($mec.instance, { pinned: true });
  }
};

// out-build/vs/workbench/contrib/extensions/browser/extensionEnablementWorkspaceTrustTransitionParticipant.js
var $pec = class $pec2 extends $3c {
  constructor(extensionService, hostService, environmentService, extensionEnablementService, workspaceTrustEnablementService, workspaceTrustManagementService) {
    super();
    if (workspaceTrustEnablementService.isWorkspaceTrustEnabled()) {
      workspaceTrustManagementService.workspaceTrustInitialized.then(() => {
        const workspaceTrustTransitionParticipant = new class {
          async participate(trusted) {
            if (trusted) {
              await extensionEnablementService.updateExtensionsEnablementsWhenWorkspaceTrustChanges();
            } else {
              if (environmentService.remoteAuthority) {
                hostService.reload();
              } else {
                const stopped = await extensionService.stopExtensionHosts(localize(6410, null));
                await extensionEnablementService.updateExtensionsEnablementsWhenWorkspaceTrustChanges();
                if (stopped) {
                  extensionService.startExtensionHosts();
                }
              }
            }
          }
        }();
        this.B(workspaceTrustManagementService.addWorkspaceTrustTransitionParticipant(workspaceTrustTransitionParticipant));
      });
    }
  }
};
$pec = __decorate([
  __param(0, $wN),
  __param(1, $S4),
  __param(2, $US),
  __param(3, $qzb),
  __param(4, $3M),
  __param(5, $4M)
], $pec);

// out-build/vs/workbench/contrib/extensions/browser/extensionsCompletionItemsProvider.js
var $qec = class $qec2 extends $3c {
  constructor(a, languageFeaturesService) {
    super();
    this.a = a;
    this.B(languageFeaturesService.completionProvider.register({ language: "jsonc", pattern: "**/settings.json" }, {
      _debugDisplayName: "extensionsCompletionProvider",
      provideCompletionItems: async (model, position, _context, token) => {
        const getWordRangeAtPosition = (model2, position2) => {
          const wordAtPosition = model2.getWordAtPosition(position2);
          return wordAtPosition ? new $9C(position2.lineNumber, wordAtPosition.startColumn, position2.lineNumber, wordAtPosition.endColumn) : null;
        };
        const location3 = $xw(model.getValue(), model.getOffsetAt(position));
        const range = getWordRangeAtPosition(model, position) ?? $9C.fromPositions(position, position);
        if (location3.path[0] === "extensions.supportUntrustedWorkspaces" && location3.path.length === 2 && location3.isAtPropertyKey) {
          let alreadyConfigured = [];
          try {
            alreadyConfigured = Object.keys($yw(model.getValue())["extensions.supportUntrustedWorkspaces"]);
          } catch (e) {
          }
          return { suggestions: await this.b(alreadyConfigured, range) };
        }
        return { suggestions: [] };
      }
    }));
  }
  async b(alreadyConfigured, range) {
    const suggestions = [];
    const installedExtensions = (await this.a.getInstalled()).filter((e) => e.manifest.main);
    const proposedExtensions = installedExtensions.filter((e) => alreadyConfigured.indexOf(e.identifier.id) === -1);
    if (proposedExtensions.length) {
      suggestions.push(...proposedExtensions.map((e) => {
        const text2 = `"${e.identifier.id}": {
	"supported": true,
	"version": "${e.manifest.version}"
},`;
        return { label: e.identifier.id, kind: 13, insertText: text2, filterText: text2, range };
      }));
    } else {
      const text2 = '"vscode.csharp": {\n	"supported": true,\n	"version": "0.0.0"\n},';
      suggestions.push({ label: localize(6779, null), kind: 13, insertText: text2, filterText: text2, range });
    }
    return suggestions;
  }
};
$qec = __decorate([
  __param(0, $sA),
  __param(1, $mP)
], $qec);

// out-build/vs/platform/extensionManagement/common/unsupportedExtensionsMigration.js
async function $rec(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((i2) => $DA(i2.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) => $DA(e, unsupportedExtension.identifier));
        await extensionManagementService.uninstall(unsupportedExtension);
        logService.info(`Uninstalled the unsupported extension '${unsupportedExtension.identifier.id}'`);
        let preReleaseExtension = installed.find((i2) => $DA(i2.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($GA(unsupportedExtension.manifest.publisher, unsupportedExtension.manifest.name), $GA(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/workbench/contrib/extensions/browser/unsupportedExtensionsMigrationContribution.js
var $sec = class $sec2 {
  constructor(extensionManagementServerService, extensionGalleryService, extensionStorageService, extensionEnablementService, logService) {
    if (extensionManagementServerService.remoteExtensionManagementServer) {
      $rec(extensionManagementServerService.remoteExtensionManagementServer.extensionManagementService, extensionGalleryService, extensionStorageService, extensionEnablementService, logService);
    }
    if (extensionManagementServerService.webExtensionManagementServer) {
      $rec(extensionManagementServerService.webExtensionManagementServer.extensionManagementService, extensionGalleryService, extensionStorageService, extensionEnablementService, logService);
    }
  }
};
$sec = __decorate([
  __param(0, $nzb),
  __param(1, $pA),
  __param(2, $AM),
  __param(3, $vA),
  __param(4, $wn)
], $sec);

// out-build/vs/workbench/contrib/extensions/browser/extensions.contribution.js
$SC(
  $vzb,
  $kec,
  0
  /* InstantiationType.Eager */
);
$SC(
  $_dc,
  $lec,
  1
  /* InstantiationType.Delayed */
);
$SC(
  $ABb,
  $gec,
  0
  /* InstantiationType.Eager */
);
$Wn.as($CM.Quickaccess).registerQuickAccessProvider({
  ctor: $7dc,
  prefix: $7dc.PREFIX,
  placeholder: localize(6444, null),
  helpEntries: [{ description: localize(6445, null) }]
});
$Wn.as($ZK.EditorPane).registerEditorPane($7tb.create($Rdc, $Rdc.ID, localize(6446, null)), [
  new $Nk($szb)
]);
$Wn.as(Extensions5.ViewContainersRegistry).registerViewContainer(
  {
    id: $tzb,
    title: localize2(6558, "Extensions"),
    openCommandActionDescriptor: {
      id: $tzb,
      mnemonicTitle: localize(6447, null),
      keybindings: {
        primary: 2048 | 1024 | 54
        /* KeyCode.KeyX */
      },
      order: 4
    },
    ctorDescriptor: new $Nk($1dc),
    icon: $cCb,
    order: 4,
    rejectAddedViews: true,
    alwaysUseContainerInfo: true
  },
  0
  /* ViewContainerLocation.Sidebar */
);
$Wn.as($Ht.Configuration).registerConfiguration({
  id: "extensions",
  order: 30,
  title: localize(6448, null),
  type: "object",
  properties: {
    "extensions.autoUpdate": {
      enum: [true, "onlyEnabledExtensions", false],
      enumItemLabels: [
        localize(6449, null),
        localize(6450, null),
        localize(6451, null)
      ],
      enumDescriptions: [
        localize(6452, null),
        localize(6453, null),
        localize(6454, null)
      ],
      description: localize(6455, null),
      default: true,
      scope: 1,
      tags: ["usesOnlineServices"]
    },
    "extensions.autoCheckUpdates": {
      type: "boolean",
      description: localize(6456, null),
      default: true,
      scope: 1,
      tags: ["usesOnlineServices"]
    },
    "extensions.ignoreRecommendations": {
      type: "boolean",
      description: localize(6457, null),
      default: false
    },
    "extensions.showRecommendationsOnlyOnDemand": {
      type: "boolean",
      deprecationMessage: localize(6458, null),
      default: false,
      tags: ["usesOnlineServices"]
    },
    "extensions.closeExtensionDetailsOnViewChange": {
      type: "boolean",
      description: localize(6459, null),
      default: false
    },
    "extensions.confirmedUriHandlerExtensionIds": {
      type: "array",
      items: {
        type: "string"
      },
      description: localize(6460, null),
      default: [],
      scope: 1
      /* ConfigurationScope.APPLICATION */
    },
    "extensions.webWorker": {
      type: ["boolean", "string"],
      enum: [true, false, "auto"],
      enumDescriptions: [
        localize(6461, null),
        localize(6462, null),
        localize(6463, null)
      ],
      description: localize(6464, null),
      default: "auto"
    },
    "extensions.supportVirtualWorkspaces": {
      type: "object",
      markdownDescription: localize(6465, null),
      patternProperties: {
        "([a-z0-9A-Z][a-z0-9-A-Z]*)\\.([a-z0-9A-Z][a-z0-9-A-Z]*)$": {
          type: "boolean",
          default: false
        }
      },
      additionalProperties: false,
      default: {},
      defaultSnippets: [{
        "body": {
          "pub.name": false
        }
      }]
    },
    "extensions.experimental.affinity": {
      type: "object",
      markdownDescription: localize(6466, null),
      patternProperties: {
        "([a-z0-9A-Z][a-z0-9-A-Z]*)\\.([a-z0-9A-Z][a-z0-9-A-Z]*)$": {
          type: "integer",
          default: 1
        }
      },
      additionalProperties: false,
      default: {},
      defaultSnippets: [{
        "body": {
          "pub.name": 1
        }
      }]
    },
    [$FCb]: {
      type: "object",
      scope: 1,
      markdownDescription: localize(6467, null),
      patternProperties: {
        "([a-z0-9A-Z][a-z0-9-A-Z]*)\\.([a-z0-9A-Z][a-z0-9-A-Z]*)$": {
          type: "object",
          properties: {
            "supported": {
              type: ["boolean", "string"],
              enum: [true, false, "limited"],
              enumDescriptions: [
                localize(6468, null),
                localize(6469, null),
                localize(6470, null)
              ],
              description: localize(6471, null)
            },
            "version": {
              type: "string",
              description: localize(6472, null)
            }
          }
        }
      }
    },
    "extensions.experimental.deferredStartupFinishedActivation": {
      type: "boolean",
      description: localize(6473, null),
      default: false
    },
    "extensions.experimental.issueQuickAccess": {
      type: "boolean",
      description: localize(6474, null),
      default: true
    },
    "extensions.verifySignature": {
      type: "boolean",
      description: localize(6475, null),
      default: true,
      scope: 1,
      included: $p && !$n
    },
    [$BA]: {
      type: "boolean",
      description: localize(6476, null),
      default: true,
      scope: 1,
      tags: ["onExp", "usesOnlineServices"]
    },
    [$CA]: {
      // Note: Type is set only to object because to support policies generation during build time, where single type is expected.
      type: "object",
      markdownDescription: localize(6477, null),
      default: "*",
      defaultSnippets: [{
        body: {},
        description: localize(6478, null)
      }, {
        body: {
          "*": true
        },
        description: localize(6479, null)
      }],
      scope: 1,
      policy: {
        name: "AllowedExtensions",
        minimumVersion: "1.96"
      },
      additionalProperties: false,
      patternProperties: {
        "([a-z0-9A-Z][a-z0-9-A-Z]*)\\.([a-z0-9A-Z][a-z0-9-A-Z]*)$": {
          anyOf: [
            {
              type: ["boolean", "string"],
              enum: [true, false, "stable"],
              description: localize(6480, null),
              enumDescriptions: [
                localize(6481, null),
                localize(6482, null),
                localize(6483, null)
              ]
            },
            {
              type: "array",
              items: {
                type: "string"
              },
              description: localize(6484, null)
            }
          ]
        },
        "([a-z0-9A-Z][a-z0-9-A-Z]*)$": {
          type: ["boolean", "string"],
          enum: [true, false, "stable"],
          description: localize(6485, null),
          enumDescriptions: [
            localize(6486, null),
            localize(6487, null),
            localize(6488, null)
          ]
        },
        "\\*": {
          type: "boolean",
          enum: [true, false],
          description: localize(6489, null),
          enumDescriptions: [
            localize(6490, null),
            localize(6491, null)
          ]
        }
      }
    }
  }
});
var jsonRegistry4 = $Wn.as($Xn.JSONContribution);
jsonRegistry4.registerSchema($xBb, $yBb);
$tn.registerCommand("_extensions.manage", (accessor, extensionId, tab, preserveFocus, feature) => {
  const extensionService = accessor.get($vzb);
  const extension = extensionService.local.find((e) => $DA(e.identifier, { id: extensionId }));
  if (extension) {
    extensionService.open(extension, { tab, preserveFocus, feature });
  } else {
    throw new Error(localize(6492, null, extensionId));
  }
});
$tn.registerCommand("extension.open", async (accessor, extensionId, tab, preserveFocus, feature, sideByside) => {
  const extensionService = accessor.get($vzb);
  const commandService = accessor.get($sn);
  const [extension] = await extensionService.getExtensions([{ id: extensionId }], CancellationToken.None);
  if (extension) {
    return extensionService.open(extension, { tab, preserveFocus, feature, sideByside });
  }
  return commandService.executeCommand("_extensions.manage", extensionId, tab, preserveFocus, feature);
});
$tn.registerCommand({
  id: "workbench.extensions.installExtension",
  metadata: {
    description: localize(6493, null),
    args: [
      {
        name: "extensionIdOrVSIXUri",
        description: localize(6494, null),
        constraint: (value) => typeof value === "string" || value instanceof URI
      },
      {
        name: "options",
        description: "(optional) Options for installing the extension. Object with the following properties: `installOnlyNewlyAddedFromExtensionPackVSIX`: When enabled, VS Code installs only newly added extensions from the extension pack VSIX. This option is considered only when installing VSIX. ",
        isOptional: true,
        schema: {
          "type": "object",
          "properties": {
            "installOnlyNewlyAddedFromExtensionPackVSIX": {
              "type": "boolean",
              "description": localize(6495, null),
              default: false
            },
            "installPreReleaseVersion": {
              "type": "boolean",
              "description": localize(6496, null),
              default: false
            },
            "donotSync": {
              "type": "boolean",
              "description": localize(6497, null),
              default: false
            },
            "justification": {
              "type": ["string", "object"],
              "description": localize(6498, null)
            },
            "enable": {
              "type": "boolean",
              "description": localize(6499, null),
              default: false
            },
            "context": {
              "type": "object",
              "description": localize(6500, null)
            }
          }
        }
      }
    ]
  },
  handler: async (accessor, arg, options3) => {
    const extensionsWorkbenchService = accessor.get($vzb);
    const extensionManagementService = accessor.get($pzb);
    const extensionGalleryService = accessor.get($pA);
    try {
      if (typeof arg === "string") {
        const [id2, version2] = $FA(arg);
        const extension = extensionsWorkbenchService.local.find((e) => $DA(e.identifier, { id: id2, uuid: version2 }));
        if (extension?.enablementState === 1) {
          const [gallery] = await extensionGalleryService.getExtensions([{ id: id2, preRelease: options3?.installPreReleaseVersion }], CancellationToken.None);
          if (!gallery) {
            throw new Error(localize(6501, null, arg));
          }
          await extensionManagementService.installFromGallery(gallery, {
            isMachineScoped: options3?.donotSync ? true : void 0,
            /* do not allow syncing extensions automatically while installing through the command */
            installPreReleaseVersion: options3?.installPreReleaseVersion,
            installGivenVersion: !!version2,
            context: {
              ...options3?.context,
              [$gA]: "command"
              /* ExtensionInstallSource.COMMAND */
            }
          });
        } else {
          await extensionsWorkbenchService.install(
            arg,
            {
              version: version2,
              installPreReleaseVersion: options3?.installPreReleaseVersion,
              context: {
                ...options3?.context,
                [$gA]: "command"
                /* ExtensionInstallSource.COMMAND */
              },
              justification: options3?.justification,
              enable: options3?.enable,
              isMachineScoped: options3?.donotSync ? true : void 0
              /* do not allow syncing extensions automatically while installing through the command */
            },
            15
            /* ProgressLocation.Notification */
          );
        }
      } else {
        const vsix = URI.revive(arg);
        await extensionsWorkbenchService.install(vsix, { installOnlyNewlyAddedFromExtensionPack: options3?.installOnlyNewlyAddedFromExtensionPackVSIX, installGivenVersion: true });
      }
    } catch (e) {
      $gb(e);
      throw e;
    }
  }
});
$tn.registerCommand({
  id: "workbench.extensions.uninstallExtension",
  metadata: {
    description: localize(6502, null),
    args: [
      {
        name: localize(6503, null),
        schema: {
          "type": "string"
        }
      }
    ]
  },
  handler: async (accessor, id2) => {
    if (!id2) {
      throw new Error(localize(6504, null));
    }
    const extensionManagementService = accessor.get($sA);
    const installed = await extensionManagementService.getInstalled();
    const [extensionToUninstall] = installed.filter((e) => $DA(e.identifier, { id: id2 }));
    if (!extensionToUninstall) {
      throw new Error(localize(6505, null, id2));
    }
    if (extensionToUninstall.isBuiltin) {
      throw new Error(localize(6506, null, id2));
    }
    try {
      await extensionManagementService.uninstall(extensionToUninstall);
    } catch (e) {
      $gb(e);
      throw e;
    }
  }
});
$tn.registerCommand({
  id: "workbench.extensions.search",
  metadata: {
    description: localize(6507, null),
    args: [
      {
        name: localize(6508, null),
        schema: { "type": "string" }
      }
    ]
  },
  handler: async (accessor, query = "") => {
    return accessor.get($vzb).openSearch(query);
  }
});
function overrideActionForActiveExtensionEditorWebview(command4, f) {
  command4?.addImplementation(105, "extensions-editor", (accessor) => {
    const editorService = accessor.get($mJ);
    const editor = editorService.activeEditorPane;
    if (editor instanceof $Rdc) {
      if (editor.activeWebview?.isFocused) {
        f(editor.activeWebview);
        return true;
      }
    }
    return false;
  });
}
overrideActionForActiveExtensionEditorWebview($kab, (webview) => webview.copy());
overrideActionForActiveExtensionEditorWebview($jab, (webview) => webview.cut());
overrideActionForActiveExtensionEditorWebview($lab, (webview) => webview.paste());
var $tec = new $nn("hasLocalServer", false);
var $uec = new $nn("hasRemoteServer", false);
var $vec = new $nn("hasWebServer", false);
async function runAction(action) {
  try {
    await action.run();
  } finally {
    if ($Wc(action)) {
      action.dispose();
    }
  }
}
var ExtensionsContributions = class ExtensionsContributions2 extends $3c {
  constructor(a, extensionGalleryService, contextKeyService, b, g, h3, j, m, n, s) {
    super();
    this.a = a;
    this.b = b;
    this.g = g;
    this.h = h3;
    this.j = j;
    this.m = m;
    this.n = n;
    this.s = s;
    const hasGalleryContext = $Jzb.bindTo(contextKeyService);
    if (extensionGalleryService.isEnabled()) {
      hasGalleryContext.set(true);
    }
    const hasLocalServerContext = $tec.bindTo(contextKeyService);
    if (this.a.localExtensionManagementServer) {
      hasLocalServerContext.set(true);
    }
    const hasRemoteServerContext = $uec.bindTo(contextKeyService);
    if (this.a.remoteExtensionManagementServer) {
      hasRemoteServerContext.set(true);
    }
    const hasWebServerContext = $vec.bindTo(contextKeyService);
    if (this.a.webExtensionManagementServer) {
      hasWebServerContext.set(true);
    }
    this.u();
    this.w();
    this.t();
  }
  t() {
    if (this.a.localExtensionManagementServer || this.a.remoteExtensionManagementServer || this.a.webExtensionManagementServer) {
      $Wn.as($CM.Quickaccess).registerQuickAccessProvider({
        ctor: $6dc,
        prefix: $6dc.PREFIX,
        placeholder: localize(6509, null),
        helpEntries: [{ description: localize(6510, null) }]
      });
    }
  }
  // Global actions
  u() {
    this.B($dJ.appendMenuItem($bJ.MenubarPreferencesMenu, {
      command: {
        id: $tzb,
        title: localize(6511, null)
      },
      group: "2_configuration",
      order: 3
    }));
    this.B($dJ.appendMenuItem($bJ.GlobalActivity, {
      command: {
        id: $tzb,
        title: localize(6512, null)
      },
      group: "2_configuration",
      order: 3
    }));
    this.y({
      id: "workbench.extensions.action.focusExtensionsView",
      title: localize2(6559, "Focus on Extensions View"),
      category: $zA,
      f1: true,
      run: async (accessor) => {
        await accessor.get($vzb).openSearch("");
      }
    });
    this.y({
      id: "workbench.extensions.action.installExtensions",
      title: localize2(6560, "Install Extensions"),
      category: $zA,
      menu: {
        id: $bJ.CommandPalette,
        when: $7m.and($Jzb, $7m.or($tec, $uec, $vec))
      },
      run: async (accessor) => {
        accessor.get($uob).openViewContainer($tzb, true);
      }
    });
    this.y({
      id: "workbench.extensions.action.showRecommendedKeymapExtensions",
      title: localize2(6561, "Keymaps"),
      category: $AA,
      menu: [{
        id: $bJ.CommandPalette,
        when: $Jzb
      }, {
        id: $bJ.EditorTitle,
        when: $7m.and($$Yb, $Jzb),
        group: "2_keyboard_discover_actions"
      }],
      menuTitles: {
        [$bJ.EditorTitle.id]: localize(6513, null)
      },
      run: () => this.g.openSearch("@recommended:keymaps ")
    });
    this.y({
      id: "workbench.extensions.action.showLanguageExtensions",
      title: localize2(6562, "Language Extensions"),
      category: $AA,
      menu: {
        id: $bJ.CommandPalette,
        when: $Jzb
      },
      run: () => this.g.openSearch("@recommended:languages ")
    });
    this.y({
      id: "workbench.extensions.action.checkForUpdates",
      title: localize2(6563, "Check for Extension Updates"),
      category: $zA,
      menu: [{
        id: $bJ.CommandPalette,
        when: $7m.and($Jzb, $7m.or($tec, $uec, $vec))
      }, {
        id: $bJ.ViewContainerTitle,
        when: $7m.and($7m.equals("viewContainer", $tzb), $Jzb),
        group: "1_updates",
        order: 1
      }],
      run: async () => {
        await this.g.checkForUpdates();
        const outdated = this.g.outdated;
        if (outdated.length) {
          return this.g.openSearch("@outdated ");
        } else {
          return this.m.info(localize(6514, null));
        }
      }
    });
    const enableAutoUpdateWhenCondition = $7m.equals(`config.${$xzb}`, false);
    this.y({
      id: "workbench.extensions.action.enableAutoUpdate",
      title: localize2(6564, "Enable Auto Update for All Extensions"),
      category: $zA,
      precondition: enableAutoUpdateWhenCondition,
      menu: [{
        id: $bJ.ViewContainerTitle,
        order: 5,
        group: "1_updates",
        when: $7m.and($7m.equals("viewContainer", $tzb), enableAutoUpdateWhenCondition)
      }, {
        id: $bJ.CommandPalette
      }],
      run: (accessor) => accessor.get($vzb).updateAutoUpdateForAllExtensions(true)
    });
    const disableAutoUpdateWhenCondition = $7m.notEquals(`config.${$xzb}`, false);
    this.y({
      id: "workbench.extensions.action.disableAutoUpdate",
      title: localize2(6565, "Disable Auto Update for All Extensions"),
      precondition: disableAutoUpdateWhenCondition,
      category: $zA,
      menu: [{
        id: $bJ.ViewContainerTitle,
        order: 5,
        group: "1_updates",
        when: $7m.and($7m.equals("viewContainer", $tzb), disableAutoUpdateWhenCondition)
      }, {
        id: $bJ.CommandPalette
      }],
      run: (accessor) => accessor.get($vzb).updateAutoUpdateForAllExtensions(false)
    });
    this.y({
      id: "workbench.extensions.action.updateAllExtensions",
      title: localize2(6566, "Update All Extensions"),
      category: $zA,
      precondition: $Izb,
      menu: [
        {
          id: $bJ.CommandPalette,
          when: $7m.and($Jzb, $7m.or($tec, $uec, $vec))
        },
        {
          id: $bJ.ViewContainerTitle,
          when: $7m.and($7m.equals("viewContainer", $tzb), $7m.or($7m.has(`config.${$xzb}`).negate(), $7m.equals(`config.${$xzb}`, "onlyEnabledExtensions"))),
          group: "1_updates",
          order: 2
        },
        {
          id: $bJ.ViewTitle,
          when: $7m.equals("view", $Dzb),
          group: "navigation",
          order: 1
        }
      ],
      icon: $iCb,
      run: async () => {
        await this.g.updateAll();
      }
    });
    this.y({
      id: "workbench.extensions.action.enableAll",
      title: localize2(6567, "Enable All Extensions"),
      category: $zA,
      menu: [{
        id: $bJ.CommandPalette,
        when: $7m.or($tec, $uec, $vec)
      }, {
        id: $bJ.ViewContainerTitle,
        when: $7m.equals("viewContainer", $tzb),
        group: "2_enablement",
        order: 1
      }],
      run: async () => {
        const extensionsToEnable = this.g.local.filter((e) => !!e.local && this.h.canChangeEnablement(e.local) && !this.h.isEnabled(e.local));
        if (extensionsToEnable.length) {
          await this.g.setEnablement(
            extensionsToEnable,
            10
            /* EnablementState.EnabledGlobally */
          );
        }
      }
    });
    this.y({
      id: "workbench.extensions.action.enableAllWorkspace",
      title: localize2(6568, "Enable All Extensions for this Workspace"),
      category: $zA,
      menu: {
        id: $bJ.CommandPalette,
        when: $7m.and($epb.notEqualsTo("empty"), $7m.or($tec, $uec, $vec))
      },
      run: async () => {
        const extensionsToEnable = this.g.local.filter((e) => !!e.local && this.h.canChangeEnablement(e.local) && !this.h.isEnabled(e.local));
        if (extensionsToEnable.length) {
          await this.g.setEnablement(
            extensionsToEnable,
            11
            /* EnablementState.EnabledWorkspace */
          );
        }
      }
    });
    this.y({
      id: "workbench.extensions.action.disableAll",
      title: localize2(6569, "Disable All Installed Extensions"),
      category: $zA,
      menu: [{
        id: $bJ.CommandPalette,
        when: $7m.or($tec, $uec, $vec)
      }, {
        id: $bJ.ViewContainerTitle,
        when: $7m.equals("viewContainer", $tzb),
        group: "2_enablement",
        order: 2
      }],
      run: async () => {
        const extensionsToDisable = this.g.local.filter((e) => !e.isBuiltin && !!e.local && this.h.isEnabled(e.local) && this.h.canChangeEnablement(e.local));
        if (extensionsToDisable.length) {
          await this.g.setEnablement(
            extensionsToDisable,
            8
            /* EnablementState.DisabledGlobally */
          );
        }
      }
    });
    this.y({
      id: "workbench.extensions.action.disableAllWorkspace",
      title: localize2(6570, "Disable All Installed Extensions for this Workspace"),
      category: $zA,
      menu: {
        id: $bJ.CommandPalette,
        when: $7m.and($epb.notEqualsTo("empty"), $7m.or($tec, $uec, $vec))
      },
      run: async () => {
        const extensionsToDisable = this.g.local.filter((e) => !e.isBuiltin && !!e.local && this.h.isEnabled(e.local) && this.h.canChangeEnablement(e.local));
        if (extensionsToDisable.length) {
          await this.g.setEnablement(
            extensionsToDisable,
            9
            /* EnablementState.DisabledWorkspace */
          );
        }
      }
    });
    this.y({
      id: $Fzb,
      title: localize2(6571, "Install from VSIX..."),
      category: $zA,
      menu: [{
        id: $bJ.CommandPalette,
        when: $7m.or($tec, $uec)
      }, {
        id: $bJ.ViewContainerTitle,
        when: $7m.and($7m.equals("viewContainer", $tzb), $7m.or($tec, $uec)),
        group: "3_install",
        order: 1
      }],
      run: async (accessor) => {
        const fileDialogService = accessor.get($1v);
        const commandService = accessor.get($sn);
        const vsixPaths = await fileDialogService.showOpenDialog({
          title: localize(6515, null),
          filters: [{ name: "VSIX Extensions", extensions: ["vsix"] }],
          canSelectFiles: true,
          canSelectMany: true,
          openLabel: $7t(localize(6516, null))
        });
        if (vsixPaths) {
          await commandService.executeCommand($Gzb, vsixPaths);
        }
      }
    });
    this.y({
      id: $Gzb,
      title: localize(6517, null),
      menu: [{
        id: $bJ.ExplorerContext,
        group: "extensions",
        when: $7m.and($lqb.Extension.isEqualTo(".vsix"), $7m.or($tec, $uec))
      }],
      run: async (accessor, resources) => {
        const extensionsWorkbenchService = accessor.get($vzb);
        const hostService = accessor.get($S4);
        const notificationService = accessor.get($PJ);
        const vsixs = Array.isArray(resources) ? resources : [resources];
        const result = await Promise.allSettled(vsixs.map(async (vsix) => await extensionsWorkbenchService.install(vsix, { installGivenVersion: true })));
        let error, requireReload = false, requireRestart = false;
        for (const r2 of result) {
          if (r2.status === "rejected") {
            error = new Error(r2.reason);
            break;
          }
          requireReload = requireReload || r2.value.runtimeState?.action === "reloadWindow";
          requireRestart = requireRestart || r2.value.runtimeState?.action === "restartExtensions";
        }
        if (error) {
          throw error;
        }
        if (requireReload) {
          notificationService.prompt(Severity2.Info, localize(6518, null), [{
            label: localize(6519, null),
            run: () => hostService.reload()
          }]);
        } else if (requireRestart) {
          notificationService.prompt(Severity2.Info, localize(6520, null), [{
            label: localize(6521, null),
            run: () => extensionsWorkbenchService.updateRunningExtensions()
          }]);
        } else {
          notificationService.prompt(Severity2.Info, localize(6522, null), []);
        }
      }
    });
    this.y({
      id: "workbench.extensions.action.installExtensionFromLocation",
      title: localize2(6572, "Install Extension from Location..."),
      category: $qn.Developer,
      menu: [{
        id: $bJ.CommandPalette,
        when: $7m.or($vec, $tec)
      }],
      run: async (accessor) => {
        const extensionManagementService = accessor.get($pzb);
        if ($r) {
          return new Promise((c, e) => {
            const quickInputService = accessor.get($1M);
            const disposables = new $2c();
            const quickPick = disposables.add(quickInputService.createQuickPick());
            quickPick.title = localize(6523, null);
            quickPick.customButton = true;
            quickPick.customLabel = localize(6524, null);
            quickPick.placeholder = localize(6525, null);
            quickPick.ignoreFocusOut = true;
            disposables.add(Event2.any(quickPick.onDidAccept, quickPick.onDidCustom)(async () => {
              quickPick.hide();
              if (quickPick.value) {
                try {
                  await extensionManagementService.installFromLocation(URI.parse(quickPick.value));
                } catch (error) {
                  e(error);
                  return;
                }
              }
              c();
            }));
            disposables.add(quickPick.onDidHide(() => disposables.dispose()));
            quickPick.show();
          });
        } else {
          const fileDialogService = accessor.get($1v);
          const extensionLocation = await fileDialogService.showOpenDialog({
            canSelectFolders: true,
            canSelectFiles: false,
            canSelectMany: false,
            title: localize(6526, null)
          });
          if (extensionLocation?.[0]) {
            await extensionManagementService.installFromLocation(extensionLocation[0]);
          }
        }
      }
    });
    const extensionsFilterSubMenu = new $bJ("extensionsFilterSubMenu");
    $dJ.appendMenuItem($Ozb, {
      submenu: extensionsFilterSubMenu,
      title: localize(6527, null),
      group: "navigation",
      order: 2,
      icon: $gCb
    });
    const showFeaturedExtensionsId = "extensions.filter.featured";
    this.y({
      id: showFeaturedExtensionsId,
      title: localize2(6573, "Show Featured Extensions"),
      category: $zA,
      menu: [{
        id: $bJ.CommandPalette,
        when: $Jzb
      }, {
        id: extensionsFilterSubMenu,
        when: $Jzb,
        group: "1_predefined",
        order: 1
      }],
      menuTitles: {
        [extensionsFilterSubMenu.id]: localize(6528, null)
      },
      run: () => this.g.openSearch("@featured ")
    });
    this.y({
      id: "workbench.extensions.action.showPopularExtensions",
      title: localize2(6574, "Show Popular Extensions"),
      category: $zA,
      menu: [{
        id: $bJ.CommandPalette,
        when: $Jzb
      }, {
        id: extensionsFilterSubMenu,
        when: $Jzb,
        group: "1_predefined",
        order: 2
      }],
      menuTitles: {
        [extensionsFilterSubMenu.id]: localize(6529, null)
      },
      run: () => this.g.openSearch("@popular ")
    });
    this.y({
      id: "workbench.extensions.action.showRecommendedExtensions",
      title: localize2(6575, "Show Recommended Extensions"),
      category: $zA,
      menu: [{
        id: $bJ.CommandPalette,
        when: $Jzb
      }, {
        id: extensionsFilterSubMenu,
        when: $Jzb,
        group: "1_predefined",
        order: 2
      }],
      menuTitles: {
        [extensionsFilterSubMenu.id]: localize(6530, null)
      },
      run: () => this.g.openSearch("@recommended ")
    });
    this.y({
      id: "workbench.extensions.action.recentlyPublishedExtensions",
      title: localize2(6576, "Show Recently Published Extensions"),
      category: $zA,
      menu: [{
        id: $bJ.CommandPalette,
        when: $Jzb
      }, {
        id: extensionsFilterSubMenu,
        when: $Jzb,
        group: "1_predefined",
        order: 2
      }],
      menuTitles: {
        [extensionsFilterSubMenu.id]: localize(6531, null)
      },
      run: () => this.g.openSearch("@recentlyPublished ")
    });
    const extensionsCategoryFilterSubMenu = new $bJ("extensionsCategoryFilterSubMenu");
    $dJ.appendMenuItem(extensionsFilterSubMenu, {
      submenu: extensionsCategoryFilterSubMenu,
      title: localize(6532, null),
      when: $Jzb,
      group: "2_categories",
      order: 1
    });
    $4z.forEach((category8, index) => {
      this.y({
        id: `extensions.actions.searchByCategory.${category8}`,
        title: category8,
        menu: [{
          id: extensionsCategoryFilterSubMenu,
          when: $Jzb,
          order: index
        }],
        run: () => this.g.openSearch(`@category:"${category8.toLowerCase()}"`)
      });
    });
    this.y({
      id: "workbench.extensions.action.listBuiltInExtensions",
      title: localize2(6577, "Show Built-in Extensions"),
      category: $zA,
      menu: [{
        id: $bJ.CommandPalette,
        when: $7m.or($tec, $uec, $vec)
      }, {
        id: extensionsFilterSubMenu,
        group: "3_installed",
        order: 2
      }],
      menuTitles: {
        [extensionsFilterSubMenu.id]: localize(6533, null)
      },
      run: () => this.g.openSearch("@builtin ")
    });
    this.y({
      id: "workbench.extensions.action.extensionUpdates",
      title: localize2(6578, "Show Extension Updates"),
      category: $zA,
      precondition: $Jzb,
      f1: true,
      menu: [{
        id: extensionsFilterSubMenu,
        group: "3_installed",
        when: $Jzb,
        order: 1
      }],
      menuTitles: {
        [extensionsFilterSubMenu.id]: localize(6534, null)
      },
      run: () => this.g.openSearch("@updates")
    });
    this.y({
      id: $Hzb,
      title: localize2(6579, "Show Extensions Unsupported By Workspace"),
      category: $zA,
      menu: [{
        id: $bJ.CommandPalette,
        when: $7m.or($tec, $uec)
      }, {
        id: extensionsFilterSubMenu,
        group: "3_installed",
        order: 5,
        when: $7m.or($tec, $uec)
      }],
      menuTitles: {
        [extensionsFilterSubMenu.id]: localize(6535, null)
      },
      run: () => this.g.openSearch("@workspaceUnsupported")
    });
    this.y({
      id: "workbench.extensions.action.showEnabledExtensions",
      title: localize2(6580, "Show Enabled Extensions"),
      category: $zA,
      menu: [{
        id: $bJ.CommandPalette,
        when: $7m.or($tec, $uec, $vec)
      }, {
        id: extensionsFilterSubMenu,
        group: "3_installed",
        order: 3
      }],
      menuTitles: {
        [extensionsFilterSubMenu.id]: localize(6536, null)
      },
      run: () => this.g.openSearch("@enabled ")
    });
    this.y({
      id: "workbench.extensions.action.showDisabledExtensions",
      title: localize2(6581, "Show Disabled Extensions"),
      category: $zA,
      menu: [{
        id: $bJ.CommandPalette,
        when: $7m.or($tec, $uec, $vec)
      }, {
        id: extensionsFilterSubMenu,
        group: "3_installed",
        order: 4
      }],
      menuTitles: {
        [extensionsFilterSubMenu.id]: localize(6537, null)
      },
      run: () => this.g.openSearch("@disabled ")
    });
    const extensionsSortSubMenu = new $bJ("extensionsSortSubMenu");
    $dJ.appendMenuItem(extensionsFilterSubMenu, {
      submenu: extensionsSortSubMenu,
      title: localize(6538, null),
      when: $7m.and($7m.or($Jzb, $Sdc)),
      group: "4_sort",
      order: 1
    });
    [
      { id: "installs", title: localize(6539, null), precondition: $Wdc.negate() },
      { id: "rating", title: localize(6540, null), precondition: $Wdc.negate() },
      { id: "name", title: localize(6541, null), precondition: $Wdc.negate() },
      { id: "publishedDate", title: localize(6542, null), precondition: $Wdc.negate() },
      { id: "updateDate", title: localize(6543, null), precondition: $7m.and($Udc.negate(), $Xdc.negate(), $Wdc.negate()) }
    ].map(({ id: id2, title, precondition: precondition2 }, index) => {
      this.y({
        id: `extensions.sort.${id2}`,
        title,
        precondition: $7m.and(precondition2, $7m.regex($Ydc.key, /^@feature:/).negate()),
        menu: [{
          id: extensionsSortSubMenu,
          when: $7m.or($Jzb, $Sdc),
          order: index
        }],
        toggled: $Tdc.isEqualTo(id2),
        run: async () => {
          const extensionsViewPaneContainer = (await this.b.openViewContainer($tzb, true))?.getViewPaneContainer();
          const currentQuery = $pdc.parse(extensionsViewPaneContainer?.searchValue ?? "");
          extensionsViewPaneContainer?.search(new $pdc(currentQuery.value, id2).toString());
          extensionsViewPaneContainer?.focus();
        }
      });
    });
    this.y({
      id: "workbench.extensions.action.clearExtensionsSearchResults",
      title: localize2(6582, "Clear Extensions Search Results"),
      category: $zA,
      icon: $eCb,
      f1: true,
      precondition: $Vdc,
      menu: {
        id: $Ozb,
        group: "navigation",
        order: 1
      },
      run: async (accessor) => {
        const viewPaneContainer = accessor.get($uob).getActiveViewPaneContainerWithId($tzb);
        if (viewPaneContainer) {
          const extensionsViewPaneContainer = viewPaneContainer;
          extensionsViewPaneContainer.search("");
          extensionsViewPaneContainer.focus();
        }
      }
    });
    this.y({
      id: "workbench.extensions.action.refreshExtension",
      title: localize2(6583, "Refresh"),
      category: $zA,
      icon: $fCb,
      f1: true,
      menu: {
        id: $bJ.ViewContainerTitle,
        when: $7m.equals("viewContainer", $tzb),
        group: "navigation",
        order: 2
      },
      run: async (accessor) => {
        const viewPaneContainer = accessor.get($uob).getActiveViewPaneContainerWithId($tzb);
        if (viewPaneContainer) {
          await viewPaneContainer.refresh();
        }
      }
    });
    this.y({
      id: "workbench.extensions.action.installWorkspaceRecommendedExtensions",
      title: localize(6544, null),
      icon: $iCb,
      menu: {
        id: $bJ.ViewTitle,
        when: $7m.equals("view", $Czb),
        group: "navigation",
        order: 1
      },
      run: async (accessor) => {
        const view = accessor.get($uob).getActiveViewWithId($Czb);
        return view.installWorkspaceRecommendations();
      }
    });
    this.y({
      id: $xDb.ID,
      title: $xDb.LABEL,
      icon: $jCb,
      menu: [{
        id: $bJ.CommandPalette,
        when: $epb.notEqualsTo("empty")
      }, {
        id: $bJ.ViewTitle,
        when: $7m.equals("view", $Czb),
        group: "navigation",
        order: 2
      }],
      run: () => runAction(this.j.createInstance($xDb, $xDb.ID, $xDb.LABEL))
    });
    this.y({
      id: $CDb.ID,
      title: { value: $CDb.LABEL, original: "Install Specific Version of Extension..." },
      category: $zA,
      menu: {
        id: $bJ.CommandPalette,
        when: $7m.and($Jzb, $7m.or($tec, $uec, $vec))
      },
      run: () => runAction(this.j.createInstance($CDb, $CDb.ID, $CDb.LABEL))
    });
    this.y({
      id: $BDb.ID,
      title: { value: $BDb.LABEL, original: "Reinstall Extension..." },
      category: $qn.Developer,
      menu: {
        id: $bJ.CommandPalette,
        when: $7m.and($Jzb, $7m.or($tec, $uec))
      },
      run: () => runAction(this.j.createInstance($BDb, $BDb.ID, $BDb.LABEL))
    });
  }
  // Extension Context Menu
  w() {
    this.y({
      id: $mDb.ID,
      title: $mDb.TITLE,
      menu: {
        id: $bJ.ExtensionContext,
        group: $Lzb,
        order: 0,
        when: $7m.and($7m.not("inExtensionEditor"), $7m.equals("extensionStatus", "installed"), $7m.has("extensionHasColorThemes"))
      },
      run: async (accessor, extensionId) => {
        const extensionWorkbenchService = accessor.get($vzb);
        const instantiationService = accessor.get($Pk);
        const extension = extensionWorkbenchService.local.find((e) => $DA(e.identifier, { id: extensionId }));
        if (extension) {
          const action = instantiationService.createInstance($mDb);
          action.extension = extension;
          return action.run();
        }
      }
    });
    this.y({
      id: $nDb.ID,
      title: $nDb.TITLE,
      menu: {
        id: $bJ.ExtensionContext,
        group: $Lzb,
        order: 0,
        when: $7m.and($7m.not("inExtensionEditor"), $7m.equals("extensionStatus", "installed"), $7m.has("extensionHasFileIconThemes"))
      },
      run: async (accessor, extensionId) => {
        const extensionWorkbenchService = accessor.get($vzb);
        const instantiationService = accessor.get($Pk);
        const extension = extensionWorkbenchService.local.find((e) => $DA(e.identifier, { id: extensionId }));
        if (extension) {
          const action = instantiationService.createInstance($nDb);
          action.extension = extension;
          return action.run();
        }
      }
    });
    this.y({
      id: $oDb.ID,
      title: $oDb.TITLE,
      menu: {
        id: $bJ.ExtensionContext,
        group: $Lzb,
        order: 0,
        when: $7m.and($7m.not("inExtensionEditor"), $7m.equals("extensionStatus", "installed"), $7m.has("extensionHasProductIconThemes"))
      },
      run: async (accessor, extensionId) => {
        const extensionWorkbenchService = accessor.get($vzb);
        const instantiationService = accessor.get($Pk);
        const extension = extensionWorkbenchService.local.find((e) => $DA(e.identifier, { id: extensionId }));
        if (extension) {
          const action = instantiationService.createInstance($oDb);
          action.extension = extension;
          return action.run();
        }
      }
    });
    this.y({
      id: "workbench.extensions.action.showPreReleaseVersion",
      title: localize2(6584, "Show Pre-Release Version"),
      menu: {
        id: $bJ.ExtensionContext,
        group: $Mzb,
        order: 0,
        when: $7m.and($7m.has("inExtensionEditor"), $7m.has("galleryExtensionHasPreReleaseVersion"), $7m.has("isPreReleaseExtensionAllowed"), $7m.not("showPreReleaseVersion"), $7m.not("isBuiltinExtension"))
      },
      run: async (accessor, extensionId) => {
        const extensionWorkbenchService = accessor.get($vzb);
        const extension = (await extensionWorkbenchService.getExtensions([{ id: extensionId }], CancellationToken.None))[0];
        extensionWorkbenchService.open(extension, { showPreReleaseVersion: true });
      }
    });
    this.y({
      id: "workbench.extensions.action.showReleasedVersion",
      title: localize2(6585, "Show Release Version"),
      menu: {
        id: $bJ.ExtensionContext,
        group: $Mzb,
        order: 1,
        when: $7m.and($7m.has("inExtensionEditor"), $7m.has("galleryExtensionHasPreReleaseVersion"), $7m.has("extensionHasReleaseVersion"), $7m.has("showPreReleaseVersion"), $7m.not("isBuiltinExtension"))
      },
      run: async (accessor, extensionId) => {
        const extensionWorkbenchService = accessor.get($vzb);
        const extension = (await extensionWorkbenchService.getExtensions([{ id: extensionId }], CancellationToken.None))[0];
        extensionWorkbenchService.open(extension, { showPreReleaseVersion: false });
      }
    });
    this.y({
      id: $7Cb.ID,
      title: $7Cb.LABEL,
      category: $zA,
      precondition: $7m.and($7m.or($7m.notEquals(`config.${$xzb}`, "onlyEnabledExtensions"), $7m.equals("isExtensionEnabled", true)), $7m.not("extensionDisallowInstall"), $7m.has("isExtensionAllowed")),
      menu: {
        id: $bJ.ExtensionContext,
        group: $Nzb,
        order: 1,
        when: $7m.and($7m.not("inExtensionEditor"), $7m.equals("extensionStatus", "installed"), $7m.not("isBuiltinExtension"))
      },
      run: async (accessor, id2) => {
        const instantiationService = accessor.get($Pk);
        const extensionWorkbenchService = accessor.get($vzb);
        const extension = extensionWorkbenchService.local.find((e) => $DA(e.identifier, { id: id2 }));
        if (extension) {
          const action = instantiationService.createInstance($7Cb);
          action.extension = extension;
          return action.run();
        }
      }
    });
    this.y({
      id: $8Cb.ID,
      title: { value: $8Cb.LABEL, original: "Auto Update (Publisher)" },
      category: $zA,
      precondition: $7m.equals(`config.${$xzb}`, false),
      menu: {
        id: $bJ.ExtensionContext,
        group: $Nzb,
        order: 2,
        when: $7m.and($7m.equals("extensionStatus", "installed"), $7m.not("isBuiltinExtension"))
      },
      run: async (accessor, id2) => {
        const instantiationService = accessor.get($Pk);
        const extensionWorkbenchService = accessor.get($vzb);
        const extension = extensionWorkbenchService.local.find((e) => $DA(e.identifier, { id: id2 }));
        if (extension) {
          const action = instantiationService.createInstance($8Cb);
          action.extension = extension;
          return action.run();
        }
      }
    });
    this.y({
      id: "workbench.extensions.action.switchToPreRlease",
      title: localize(6545, null),
      category: $zA,
      menu: {
        id: $bJ.ExtensionContext,
        group: $Mzb,
        order: 2,
        when: $7m.and($Jzb, $7m.has("galleryExtensionHasPreReleaseVersion"), $7m.has("isPreReleaseExtensionAllowed"), $7m.not("installedExtensionIsOptedToPreRelease"), $7m.not("inExtensionEditor"), $7m.equals("extensionStatus", "installed"), $7m.not("isBuiltinExtension"))
      },
      run: async (accessor, id2) => {
        const instantiationService = accessor.get($Pk);
        const extensionWorkbenchService = accessor.get($vzb);
        const extension = extensionWorkbenchService.local.find((e) => $DA(e.identifier, { id: id2 }));
        if (extension) {
          const action = instantiationService.createInstance($dDb);
          action.extension = extension;
          return action.run();
        }
      }
    });
    this.y({
      id: "workbench.extensions.action.switchToRelease",
      title: localize(6546, null),
      category: $zA,
      menu: {
        id: $bJ.ExtensionContext,
        group: $Mzb,
        order: 2,
        when: $7m.and($Jzb, $7m.has("galleryExtensionHasPreReleaseVersion"), $7m.has("isExtensionAllowed"), $7m.has("installedExtensionIsOptedToPreRelease"), $7m.not("inExtensionEditor"), $7m.equals("extensionStatus", "installed"), $7m.not("isBuiltinExtension"))
      },
      run: async (accessor, id2) => {
        const instantiationService = accessor.get($Pk);
        const extensionWorkbenchService = accessor.get($vzb);
        const extension = extensionWorkbenchService.local.find((e) => $DA(e.identifier, { id: id2 }));
        if (extension) {
          const action = instantiationService.createInstance($dDb);
          action.extension = extension;
          return action.run();
        }
      }
    });
    this.y({
      id: $qDb.ID,
      title: $qDb.TITLE,
      menu: {
        id: $bJ.ExtensionContext,
        group: $Mzb,
        order: 0,
        when: $7m.and($7m.not("inExtensionEditor"), $7m.has("canSetLanguage"), $7m.has("isActiveLanguagePackExtension"))
      },
      run: async (accessor, extensionId) => {
        const instantiationService = accessor.get($Pk);
        const extensionsWorkbenchService = accessor.get($vzb);
        const extension = (await extensionsWorkbenchService.getExtensions([{ id: extensionId }], CancellationToken.None))[0];
        const action = instantiationService.createInstance($qDb);
        action.extension = extension;
        return action.run();
      }
    });
    this.y({
      id: "workbench.extensions.action.installUnsigned",
      title: localize(6547, null),
      menu: {
        id: $bJ.ExtensionContext,
        group: "0_install",
        when: $7m.and($7m.equals("extensionStatus", "uninstalled"), $7m.has("isGalleryExtension"), $7m.not("extensionDisallowInstall"), $7m.has("extensionIsUnsigned")),
        order: 1
      },
      run: async (accessor, extensionId) => {
        const instantiationService = accessor.get($Pk);
        const extension = this.g.local.filter((e) => $DA(e.identifier, { id: extensionId }))[0] || (await this.g.getExtensions([{ id: extensionId }], CancellationToken.None))[0];
        if (extension) {
          const action = instantiationService.createInstance($XCb, { installPreReleaseVersion: this.g.preferPreReleases });
          action.extension = extension;
          return action.run();
        }
      }
    });
    this.y({
      id: "workbench.extensions.action.installAndDonotSync",
      title: localize(6548, null),
      menu: {
        id: $bJ.ExtensionContext,
        group: "0_install",
        when: $7m.and($7m.equals("extensionStatus", "uninstalled"), $7m.has("isGalleryExtension"), $7m.has("isExtensionAllowed"), $7m.not("extensionDisallowInstall"), $tXb),
        order: 1
      },
      run: async (accessor, extensionId) => {
        const instantiationService = accessor.get($Pk);
        const extension = this.g.local.filter((e) => $DA(e.identifier, { id: extensionId }))[0] || (await this.g.getExtensions([{ id: extensionId }], CancellationToken.None))[0];
        if (extension) {
          const action = instantiationService.createInstance($XCb, {
            installPreReleaseVersion: this.g.preferPreReleases,
            isMachineScoped: true
          });
          action.extension = extension;
          return action.run();
        }
      }
    });
    this.y({
      id: "workbench.extensions.action.installPrereleaseAndDonotSync",
      title: localize(6549, null),
      menu: {
        id: $bJ.ExtensionContext,
        group: "0_install",
        when: $7m.and($7m.equals("extensionStatus", "uninstalled"), $7m.has("isGalleryExtension"), $7m.has("extensionHasPreReleaseVersion"), $7m.has("isPreReleaseExtensionAllowed"), $7m.not("extensionDisallowInstall"), $tXb),
        order: 2
      },
      run: async (accessor, extensionId) => {
        const instantiationService = accessor.get($Pk);
        const extension = this.g.local.filter((e) => $DA(e.identifier, { id: extensionId }))[0] || (await this.g.getExtensions([{ id: extensionId }], CancellationToken.None))[0];
        if (extension) {
          const action = instantiationService.createInstance($XCb, {
            isMachineScoped: true,
            preRelease: true
          });
          action.extension = extension;
          return action.run();
        }
      }
    });
    this.y({
      id: $eDb.ID,
      title: $eDb.LABEL,
      menu: {
        id: $bJ.ExtensionContext,
        group: "0_install",
        when: $7m.and($7m.equals("extensionStatus", "uninstalled"), $7m.has("isGalleryExtension"), $7m.has("isExtensionAllowed"), $7m.not("extensionDisallowInstall")),
        order: 3
      },
      run: async (accessor, extensionId) => {
        const instantiationService = accessor.get($Pk);
        const extension = this.g.local.filter((e) => $DA(e.identifier, { id: extensionId }))[0] || (await this.g.getExtensions([{ id: extensionId }], CancellationToken.None))[0];
        if (extension) {
          return instantiationService.createInstance($eDb, extension, false).run();
        }
      }
    });
    this.y({
      id: "workbench.extensions.action.copyExtension",
      title: localize2(6586, "Copy"),
      menu: {
        id: $bJ.ExtensionContext,
        group: "1_copy"
      },
      run: async (accessor, extensionId) => {
        const clipboardService = accessor.get($30);
        const extension = this.g.local.filter((e) => $DA(e.identifier, { id: extensionId }))[0] || (await this.g.getExtensions([{ id: extensionId }], CancellationToken.None))[0];
        if (extension) {
          const name = localize(6550, null, extension.displayName);
          const id2 = localize(6551, null, extensionId);
          const description = localize(6552, null, extension.description);
          const verision = localize(6553, null, extension.version);
          const publisher = localize(6554, null, extension.publisherDisplayName);
          const link2 = extension.url ? localize(6555, null, `${extension.url}`) : null;
          const clipboardStr = `${name}
${id2}
${description}
${verision}
${publisher}${link2 ? "\n" + link2 : ""}`;
          await clipboardService.writeText(clipboardStr);
        }
      }
    });
    this.y({
      id: "workbench.extensions.action.copyExtensionId",
      title: localize2(6587, "Copy Extension ID"),
      menu: {
        id: $bJ.ExtensionContext,
        group: "1_copy"
      },
      run: async (accessor, id2) => accessor.get($30).writeText(id2)
    });
    this.y({
      id: "workbench.extensions.action.copyLink",
      title: localize2(6588, "Copy Link"),
      menu: {
        id: $bJ.ExtensionContext,
        group: "1_copy",
        when: $7m.has("isGalleryExtension")
      },
      run: async (accessor, extensionId) => {
        const clipboardService = accessor.get($30);
        const productService = accessor.get($Vu);
        if (productService.extensionsGallery?.itemUrl) {
          const link2 = `${productService.extensionsGallery.itemUrl}?itemName=${extensionId}`;
          await clipboardService.writeText(link2);
        }
      }
    });
    this.y({
      id: "workbench.extensions.action.configure",
      title: localize2(6589, "Settings"),
      menu: {
        id: $bJ.ExtensionContext,
        group: "2_configure",
        when: $7m.and($7m.equals("extensionStatus", "installed"), $7m.has("extensionHasConfiguration")),
        order: 1
      },
      run: async (accessor, id2) => accessor.get($TK).openSettings({ jsonEditor: false, query: `@ext:${id2}` })
    });
    this.y({
      id: "workbench.extensions.action.download",
      title: localize(6556, null),
      menu: {
        id: $bJ.ExtensionContext,
        when: $7m.and($7m.equals("extensionStatus", "uninstalled"), $7m.has("isGalleryExtension")),
        order: this.s.quality === "stable" ? 0 : 1
      },
      run: async (accessor, extensionId) => {
        accessor.get($vzb).downloadVSIX(extensionId, false);
      }
    });
    this.y({
      id: "workbench.extensions.action.downloadPreRelease",
      title: localize(6557, null),
      menu: {
        id: $bJ.ExtensionContext,
        when: $7m.and($7m.equals("extensionStatus", "uninstalled"), $7m.has("isGalleryExtension"), $7m.has("extensionHasPreReleaseVersion")),
        order: this.s.quality === "stable" ? 1 : 0
      },
      run: async (accessor, extensionId) => {
        accessor.get($vzb).downloadVSIX(extensionId, true);
      }
    });
    this.y({
      id: "workbench.extensions.action.manageAccountPreferences",
      title: localize2(6590, "Account Preferences"),
      menu: {
        id: $bJ.ExtensionContext,
        group: "2_configure",
        when: $7m.and($7m.equals("extensionStatus", "installed"), $7m.has("extensionHasAccountPreferences")),
        order: 2
      },
      run: (accessor, id2) => accessor.get($sn).executeCommand("_manageAccountPreferencesForExtension", id2)
    });
    this.y({
      id: "workbench.extensions.action.configureKeybindings",
      title: localize2(6591, "Keyboard Shortcuts"),
      menu: {
        id: $bJ.ExtensionContext,
        group: "2_configure",
        when: $7m.and($7m.equals("extensionStatus", "installed"), $7m.has("extensionHasKeybindings")),
        order: 2
      },
      run: async (accessor, id2) => accessor.get($TK).openGlobalKeybindingSettings(false, { query: `@ext:${id2}` })
    });
    this.y({
      id: "workbench.extensions.action.toggleApplyToAllProfiles",
      title: localize2(6592, "Apply Extension to all Profiles"),
      toggled: $7m.has("isApplicationScopedExtension"),
      menu: {
        id: $bJ.ExtensionContext,
        group: "2_configure",
        when: $7m.and($7m.equals("extensionStatus", "installed"), $7m.has("isDefaultApplicationScopedExtension").negate(), $7m.has("isBuiltinExtension").negate(), $7m.equals("isWorkspaceScopedExtension", false)),
        order: 3
      },
      run: async (accessor, _, extensionArg) => {
        const uriIdentityService = accessor.get($vl);
        const extension = extensionArg.location ? this.g.installed.find((e) => uriIdentityService.extUri.isEqual(e.local?.location, extensionArg.location)) : void 0;
        if (extension) {
          return this.g.toggleApplyExtensionToAllProfiles(extension);
        }
      }
    });
    this.y({
      id: $Ezb,
      title: localize2(6593, "Sync This Extension"),
      menu: {
        id: $bJ.ExtensionContext,
        group: "2_configure",
        when: $7m.and($7m.equals("extensionStatus", "installed"), $tXb, $7m.equals("isWorkspaceScopedExtension", false)),
        order: 4
      },
      run: async (accessor, id2) => {
        const extension = this.g.local.find((e) => $DA({ id: id2 }, e.identifier));
        if (extension) {
          return this.g.toggleExtensionIgnoredToSync(extension);
        }
      }
    });
    this.y({
      id: "workbench.extensions.action.ignoreRecommendation",
      title: localize2(6594, "Ignore Recommendation"),
      menu: {
        id: $bJ.ExtensionContext,
        group: "3_recommendations",
        when: $7m.has("isExtensionRecommended"),
        order: 1
      },
      run: async (accessor, id2) => accessor.get($BBb).toggleGlobalIgnoredRecommendation(id2, true)
    });
    this.y({
      id: "workbench.extensions.action.undoIgnoredRecommendation",
      title: localize2(6595, "Undo Ignored Recommendation"),
      menu: {
        id: $bJ.ExtensionContext,
        group: "3_recommendations",
        when: $7m.has("isUserIgnoredRecommendation"),
        order: 1
      },
      run: async (accessor, id2) => accessor.get($BBb).toggleGlobalIgnoredRecommendation(id2, false)
    });
    this.y({
      id: "workbench.extensions.action.addExtensionToWorkspaceRecommendations",
      title: localize2(6596, "Add to Workspace Recommendations"),
      menu: {
        id: $bJ.ExtensionContext,
        group: "3_recommendations",
        when: $7m.and($epb.notEqualsTo("empty"), $7m.has("isBuiltinExtension").negate(), $7m.has("isExtensionWorkspaceRecommended").negate(), $7m.has("isUserIgnoredRecommendation").negate(), $7m.notEquals("extensionSource", "resource")),
        order: 2
      },
      run: (accessor, id2) => accessor.get($FBb).toggleRecommendation(id2)
    });
    this.y({
      id: "workbench.extensions.action.removeExtensionFromWorkspaceRecommendations",
      title: localize2(6597, "Remove from Workspace Recommendations"),
      menu: {
        id: $bJ.ExtensionContext,
        group: "3_recommendations",
        when: $7m.and($epb.notEqualsTo("empty"), $7m.has("isBuiltinExtension").negate(), $7m.has("isExtensionWorkspaceRecommended")),
        order: 2
      },
      run: (accessor, id2) => accessor.get($FBb).toggleRecommendation(id2)
    });
    this.y({
      id: "workbench.extensions.action.addToWorkspaceRecommendations",
      title: localize2(6598, "Add Extension to Workspace Recommendations"),
      category: $uzb,
      menu: {
        id: $bJ.CommandPalette,
        when: $7m.and($epb.isEqualTo("workspace"), $7m.equals("resourceScheme", Schemas.extension))
      },
      async run(accessor) {
        const editorService = accessor.get($mJ);
        const workspaceExtensionsConfigService = accessor.get($FBb);
        if (!(editorService.activeEditor instanceof $szb)) {
          return;
        }
        const extensionId = editorService.activeEditor.extension.identifier.id.toLowerCase();
        const recommendations = await workspaceExtensionsConfigService.getRecommendations();
        if (recommendations.includes(extensionId)) {
          return;
        }
        await workspaceExtensionsConfigService.toggleRecommendation(extensionId);
      }
    });
    this.y({
      id: "workbench.extensions.action.addToWorkspaceFolderRecommendations",
      title: localize2(6599, "Add Extension to Workspace Folder Recommendations"),
      category: $uzb,
      menu: {
        id: $bJ.CommandPalette,
        when: $7m.and($epb.isEqualTo("folder"), $7m.equals("resourceScheme", Schemas.extension))
      },
      run: () => this.n.executeCommand("workbench.extensions.action.addToWorkspaceRecommendations")
    });
    this.y({
      id: "workbench.extensions.action.addToWorkspaceIgnoredRecommendations",
      title: localize2(6600, "Add Extension to Workspace Ignored Recommendations"),
      category: $uzb,
      menu: {
        id: $bJ.CommandPalette,
        when: $7m.and($epb.isEqualTo("workspace"), $7m.equals("resourceScheme", Schemas.extension))
      },
      async run(accessor) {
        const editorService = accessor.get($mJ);
        const workspaceExtensionsConfigService = accessor.get($FBb);
        if (!(editorService.activeEditor instanceof $szb)) {
          return;
        }
        const extensionId = editorService.activeEditor.extension.identifier.id.toLowerCase();
        const unwantedRecommendations = await workspaceExtensionsConfigService.getUnwantedRecommendations();
        if (unwantedRecommendations.includes(extensionId)) {
          return;
        }
        await workspaceExtensionsConfigService.toggleUnwantedRecommendation(extensionId);
      }
    });
    this.y({
      id: "workbench.extensions.action.addToWorkspaceFolderIgnoredRecommendations",
      title: localize2(6601, "Add Extension to Workspace Folder Ignored Recommendations"),
      category: $uzb,
      menu: {
        id: $bJ.CommandPalette,
        when: $7m.and($epb.isEqualTo("folder"), $7m.equals("resourceScheme", Schemas.extension))
      },
      run: () => this.n.executeCommand("workbench.extensions.action.addToWorkspaceIgnoredRecommendations")
    });
    this.y({
      id: $wDb.ID,
      title: { value: $wDb.LABEL, original: "Configure Recommended Extensions (Workspace)" },
      category: $uzb,
      menu: {
        id: $bJ.CommandPalette,
        when: $epb.isEqualTo("workspace")
      },
      run: () => runAction(this.j.createInstance($wDb, $wDb.ID, $wDb.LABEL))
    });
  }
  y(extensionActionOptions) {
    const menus = extensionActionOptions.menu ? Array.isArray(extensionActionOptions.menu) ? extensionActionOptions.menu : [extensionActionOptions.menu] : [];
    let menusWithOutTitles = [];
    const menusWithTitles = [];
    if (extensionActionOptions.menuTitles) {
      for (let index = 0; index < menus.length; index++) {
        const menu = menus[index];
        const menuTitle = extensionActionOptions.menuTitles[menu.id.id];
        if (menuTitle) {
          menusWithTitles.push({ id: menu.id, item: { ...menu, command: { id: extensionActionOptions.id, title: menuTitle } } });
        } else {
          menusWithOutTitles.push(menu);
        }
      }
    } else {
      menusWithOutTitles = menus;
    }
    const disposables = new $2c();
    disposables.add($hJ(class extends $gJ {
      constructor() {
        super({
          ...extensionActionOptions,
          menu: menusWithOutTitles
        });
      }
      run(accessor, ...args2) {
        return extensionActionOptions.run(accessor, ...args2);
      }
    }));
    if (menusWithTitles.length) {
      disposables.add($dJ.appendMenuItems(menusWithTitles));
    }
    return disposables;
  }
};
ExtensionsContributions = __decorate([
  __param(0, $nzb),
  __param(1, $pA),
  __param(2, $on),
  __param(3, $uob),
  __param(4, $vzb),
  __param(5, $qzb),
  __param(6, $Pk),
  __param(7, $Yv),
  __param(8, $sn),
  __param(9, $Vu)
], ExtensionsContributions);
var ExtensionStorageCleaner = class ExtensionStorageCleaner2 {
  constructor(extensionManagementService, storageService) {
    $BM.removeOutdatedExtensionVersions(extensionManagementService, storageService);
  }
};
ExtensionStorageCleaner = __decorate([
  __param(0, $sA),
  __param(1, $jv)
], ExtensionStorageCleaner);
var workbenchRegistry2 = $Wn.as(Extensions2.Workbench);
workbenchRegistry2.registerWorkbenchContribution(
  ExtensionsContributions,
  3
  /* LifecyclePhase.Restored */
);
workbenchRegistry2.registerWorkbenchContribution(
  $2dc,
  4
  /* LifecyclePhase.Eventually */
);
workbenchRegistry2.registerWorkbenchContribution(
  $3dc,
  4
  /* LifecyclePhase.Eventually */
);
workbenchRegistry2.registerWorkbenchContribution(
  $b4b,
  3
  /* LifecyclePhase.Restored */
);
workbenchRegistry2.registerWorkbenchContribution(
  $Zdc,
  3
  /* LifecyclePhase.Restored */
);
workbenchRegistry2.registerWorkbenchContribution(
  $4dc,
  4
  /* LifecyclePhase.Eventually */
);
workbenchRegistry2.registerWorkbenchContribution(
  $5dc,
  4
  /* LifecyclePhase.Eventually */
);
workbenchRegistry2.registerWorkbenchContribution(
  $pec,
  3
  /* LifecyclePhase.Restored */
);
workbenchRegistry2.registerWorkbenchContribution(
  $qec,
  3
  /* LifecyclePhase.Restored */
);
workbenchRegistry2.registerWorkbenchContribution(
  $sec,
  4
  /* LifecyclePhase.Eventually */
);
if ($r) {
  workbenchRegistry2.registerWorkbenchContribution(
    ExtensionStorageCleaner,
    4
    /* LifecyclePhase.Eventually */
  );
}
$hJ($oec);
$Wn.as($YL.ConfigurationMigration).registerConfigurationMigrations([{
  key: $xzb,
  migrateFn: (value, accessor) => {
    if (value === "onlySelectedExtensions") {
      return { value: false };
    }
    return [];
  }
}]);

// out-build/vs/workbench/contrib/output/common/outputChannelModel.js
var OutputFileListener = class extends $3c {
  constructor(h3, j, m) {
    super();
    this.h = h3;
    this.j = j;
    this.m = m;
    this.a = new $ze();
    this.onDidContentChange = this.a.event;
    this.b = false;
    this.f = new $Th(500);
  }
  watch(eTag) {
    if (!this.b) {
      this.g = eTag;
      this.n();
      this.m.trace("Started polling", this.h.toString());
      this.b = true;
    }
  }
  n() {
    const loop = () => this.r().then(() => this.n());
    this.f.trigger(loop).catch((error) => {
      if (!$kb(error)) {
        throw error;
      }
    });
  }
  async r() {
    const stat = await this.j.stat(this.h);
    if (stat.etag !== this.g) {
      this.g = stat.etag;
      this.a.fire(stat.size);
    }
  }
  unwatch() {
    if (this.b) {
      this.f.cancel();
      this.b = false;
      this.m.trace("Stopped polling", this.h.toString());
    }
  }
  dispose() {
    this.unwatch();
    super.dispose();
  }
};
var $wec = class $wec2 extends $3c {
  constructor(u, w, y, z, C, logService, D) {
    super();
    this.u = u;
    this.w = w;
    this.y = y;
    this.z = z;
    this.C = C;
    this.D = D;
    this.a = this.B(new $ze());
    this.onDispose = this.a.event;
    this.f = "";
    this.g = null;
    this.h = null;
    this.j = false;
    this.m = this.B(new $4c());
    this.n = this.B(new $Th(300));
    this.s = 0;
    this.t = 0;
    this.b = this.B(new OutputFileListener(this.y, this.z, logService));
    this.B(this.b.onDidContentChange((size) => this.P(size)));
    this.B($1c(() => this.b.unwatch()));
  }
  append(message) {
    throw new Error("Not supported");
  }
  replace(message) {
    throw new Error("Not supported");
  }
  clear() {
    this.update(OutputChannelUpdateMode.Clear, this.t, true);
  }
  update(mode, till, immediate) {
    const loadModelPromise = this.g ? this.g : Promise.resolve();
    loadModelPromise.then(() => this.G(mode, till, immediate));
  }
  loadModel() {
    this.g = Promises.withAsyncBody(async (c, e) => {
      try {
        let content = "";
        if (await this.z.exists(this.y)) {
          const fileContent = await this.z.readFile(this.y, { position: this.s });
          this.t = this.s + fileContent.value.byteLength;
          this.f = fileContent.etag;
          content = fileContent.value.toString();
        } else {
          this.s = 0;
          this.t = 0;
        }
        c(this.F(content));
      } catch (error) {
        e(error);
      }
    });
    return this.g;
  }
  F(content) {
    if (this.h) {
      this.h.setValue(content);
    } else {
      this.h = this.C.createModel(content, this.w, this.u);
      this.b.watch(this.f);
      const disposable = this.h.onWillDispose(() => {
        this.N();
        this.b.unwatch();
        this.h = null;
        $Xc(disposable);
      });
    }
    return this.h;
  }
  G(mode, till, immediate) {
    if (mode === OutputChannelUpdateMode.Clear || mode === OutputChannelUpdateMode.Replace) {
      this.s = this.t = $Dg(till) ? till : this.t;
      this.N();
    }
    if (!this.h) {
      return;
    }
    this.j = true;
    if (!this.m.value) {
      this.m.value = new $ad();
    }
    const token = this.m.value.token;
    if (mode === OutputChannelUpdateMode.Clear) {
      this.H(this.h);
    } else if (mode === OutputChannelUpdateMode.Replace) {
      this.r = this.J(this.h, token).finally(() => this.r = void 0);
    } else {
      this.I(this.h, immediate, token);
    }
  }
  H(model) {
    this.M(model, [$bD.delete(model.getFullModelRange())], $Ci.fromString(""));
  }
  I(model, immediate, token) {
    this.n.trigger(async () => {
      if (token.isCancellationRequested) {
        return;
      }
      if (this.r) {
        try {
          await this.r;
        } catch (e) {
        }
        if (token.isCancellationRequested) {
          return;
        }
      }
      const contentToAppend = await this.O();
      if (token.isCancellationRequested) {
        return;
      }
      const lastLine = model.getLineCount();
      const lastLineMaxColumn = model.getLineMaxColumn(lastLine);
      const edits = [$bD.insert(new $8C(lastLine, lastLineMaxColumn), contentToAppend.toString())];
      this.M(model, edits, contentToAppend);
    }, immediate ? 0 : void 0).catch((error) => {
      if (!$kb(error)) {
        throw error;
      }
    });
  }
  async J(model, token) {
    const contentToReplace = await this.O();
    if (token.isCancellationRequested) {
      return;
    }
    const edits = await this.L(model, contentToReplace.toString());
    if (token.isCancellationRequested) {
      return;
    }
    this.M(model, edits, contentToReplace);
  }
  async L(model, contentToReplace) {
    if (!contentToReplace) {
      return [$bD.delete(model.getFullModelRange())];
    }
    if (contentToReplace !== model.getValue()) {
      const edits = await this.D.computeMoreMinimalEdits(model.uri, [{ text: contentToReplace.toString(), range: model.getFullModelRange() }]);
      if (edits?.length) {
        return edits.map((edit3) => $bD.replace($9C.lift(edit3.range), edit3.text));
      }
    }
    return [];
  }
  M(model, edits, content) {
    if (edits.length) {
      model.applyEdits(edits);
    }
    this.t = this.t + content.byteLength;
    this.j = false;
  }
  N() {
    this.m.value?.cancel();
    this.m.value = void 0;
    this.n.cancel();
    this.r = void 0;
    this.j = false;
  }
  async O() {
    const content = await this.z.readFile(this.y, { position: this.t });
    this.f = content.etag;
    return content.value;
  }
  P(size) {
    if (this.h) {
      if (!this.j) {
        if ($Dg(size) && this.t > size) {
          this.update(OutputChannelUpdateMode.Clear, 0, true);
        }
      }
      this.update(
        OutputChannelUpdateMode.Append,
        void 0,
        false
        /* Not needed to update immediately. Wait to collect more changes and update. */
      );
    }
  }
  Q() {
    return !!this.h;
  }
  dispose() {
    this.a.fire();
    super.dispose();
  }
};
$wec = __decorate([
  __param(3, $km),
  __param(4, $sG),
  __param(5, $wn),
  __param(6, $I0)
], $wec);
var OutputChannelBackedByFile = class OutputChannelBackedByFile2 extends $wec {
  constructor(id2, modelUri, language, file, fileService, modelService, loggerService, logService, editorWorkerService) {
    super(modelUri, language, file, fileService, modelService, logService, editorWorkerService);
    this.R = loggerService.createLogger(file, { logLevel: "always", donotRotate: true, donotUseFormatters: true, hidden: true });
    this.S = 0;
  }
  append(message) {
    this.U(message);
    this.update(OutputChannelUpdateMode.Append, void 0, this.Q());
  }
  replace(message) {
    const till = this.S;
    this.U(message);
    this.update(OutputChannelUpdateMode.Replace, till, true);
  }
  U(content) {
    this.S += $Ci.fromString(content).byteLength;
    this.R.info(content);
    if (this.Q()) {
      this.R.flush();
    }
  }
};
OutputChannelBackedByFile = __decorate([
  __param(4, $km),
  __param(5, $sG),
  __param(6, $xn),
  __param(7, $wn),
  __param(8, $I0)
], OutputChannelBackedByFile);
var $xec = class $xec2 extends $3c {
  constructor(id2, modelUri, language, outputDir, f, g) {
    super();
    this.f = f;
    this.g = g;
    this.a = this.B(new $ze());
    this.onDispose = this.a.event;
    this.b = this.h(id2, modelUri, language, outputDir);
  }
  async h(id2, modelUri, language, outputDirPromise) {
    const outputDir = await outputDirPromise;
    const file = $vh(outputDir, `${id2.replace(/[\\/:\*\?"<>\|]/g, "")}.log`);
    await this.g.createFile(file);
    const outputChannelModel = this.B(this.f.createInstance(OutputChannelBackedByFile, id2, modelUri, language, file));
    this.B(outputChannelModel.onDispose(() => this.a.fire()));
    return outputChannelModel;
  }
  append(output) {
    this.b.then((outputChannelModel) => outputChannelModel.append(output));
  }
  update(mode, till, immediate) {
    this.b.then((outputChannelModel) => outputChannelModel.update(mode, till, immediate));
  }
  loadModel() {
    return this.b.then((outputChannelModel) => outputChannelModel.loadModel());
  }
  clear() {
    this.b.then((outputChannelModel) => outputChannelModel.clear());
  }
  replace(value) {
    this.b.then((outputChannelModel) => outputChannelModel.replace(value));
  }
};
$xec = __decorate([
  __param(4, $Pk),
  __param(5, $km)
], $xec);

// out-build/vs/workbench/contrib/output/common/outputChannelModelService.js
var $yec = $Qk("outputChannelModelService");
var $zec = class $zec2 {
  constructor(b, c, environmentService) {
    this.b = b;
    this.c = c;
    this.d = null;
    this.a = $vh(environmentService.windowLogsPath, `output_${$Tu(/* @__PURE__ */ new Date()).replace(/-|:|\.\d+Z$/g, "")}`);
  }
  createOutputChannelModel(id2, modelUri, language, file) {
    return file ? this.c.createInstance($wec, modelUri, language, file) : this.c.createInstance($xec, id2, modelUri, language, this.e);
  }
  get e() {
    if (!this.d) {
      this.d = this.b.createFolder(this.a).then(() => this.a);
    }
    return this.d;
  }
};
$zec = __decorate([
  __param(0, $km),
  __param(1, $Pk),
  __param(2, $US)
], $zec);
$SC(
  $yec,
  $zec,
  1
  /* InstantiationType.Delayed */
);

// out-build/vs/workbench/contrib/output/browser/outputLinkProvider.js
var $Cec_1;
var $Cec = class $Cec2 extends $3c {
  static {
    $Cec_1 = this;
  }
  static {
    this.a = 3 * 60 * 1e3;
  }
  // dispose worker after 3 minutes of inactivity
  constructor(g, h3, j) {
    super();
    this.g = g;
    this.h = h3;
    this.j = j;
    this.c = new $8h(() => this.t(), $Cec_1.a);
    this.m();
    this.n();
  }
  m() {
    this.B(this.g.onDidChangeWorkspaceFolders(() => this.n()));
  }
  n() {
    const folders = this.g.getWorkspace().folders;
    if (folders.length > 0) {
      if (!this.f) {
        this.f = this.j.linkProvider.register([{ language: $HS, scheme: "*" }, { language: $JS, scheme: "*" }], {
          provideLinks: async (model) => {
            const links = await this.s(model.uri);
            return links && { links };
          }
        });
      }
    } else {
      $Xc(this.f);
      this.f = void 0;
    }
    this.t();
    this.c.cancel();
  }
  r() {
    this.c.schedule();
    if (!this.b) {
      this.b = new OutputLinkWorkerClient(this.g, this.h);
    }
    return this.b;
  }
  async s(modelUri) {
    return this.r().provideLinks(modelUri);
  }
  t() {
    if (this.b) {
      this.b.dispose();
      this.b = void 0;
    }
  }
};
$Cec = $Cec_1 = __decorate([
  __param(0, $Zk),
  __param(1, $sG),
  __param(2, $mP)
], $Cec);
var OutputLinkWorkerClient = class OutputLinkWorkerClient2 extends $3c {
  constructor(f, modelService) {
    super();
    this.f = f;
    this.a = this.B($412("vs/workbench/contrib/output/common/outputLinkComputer", "OutputLinkDetectionWorker"));
    this.b = $C0.create(this.a, modelService);
    this.c = this.g();
  }
  async g() {
    await this.a.proxy.$setWorkspaceFolders(this.f.getWorkspace().folders.map((folder) => folder.uri.toString()));
  }
  async provideLinks(modelUri) {
    await this.c;
    await this.b.ensureSyncedResources([modelUri]);
    return this.a.proxy.$computeLinks(modelUri.toString());
  }
};
OutputLinkWorkerClient = __decorate([
  __param(0, $Zk),
  __param(1, $sG)
], OutputLinkWorkerClient);

// out-build/vs/workbench/contrib/output/browser/outputServices.js
var OUTPUT_ACTIVE_CHANNEL_KEY = "output.activechannel";
var OutputChannel = class OutputChannel2 extends $3c {
  constructor(outputChannelDescriptor, outputChannelModelService, languageService) {
    super();
    this.outputChannelDescriptor = outputChannelDescriptor;
    this.scrollLock = false;
    this.id = outputChannelDescriptor.id;
    this.label = outputChannelDescriptor.label;
    this.uri = URI.from({ scheme: Schemas.outputChannel, path: this.id });
    this.model = this.B(outputChannelModelService.createOutputChannelModel(this.id, this.uri, outputChannelDescriptor.languageId ? languageService.createById(outputChannelDescriptor.languageId) : languageService.createByMimeType(outputChannelDescriptor.log ? $IS : $GS), outputChannelDescriptor.file));
  }
  append(output) {
    this.model.append(output);
  }
  update(mode, till) {
    this.model.update(mode, till, true);
  }
  clear() {
    this.model.clear();
  }
  replace(value) {
    this.model.replace(value);
  }
};
OutputChannel = __decorate([
  __param(1, $yec),
  __param(2, $1E)
], OutputChannel);
var $Eec = class $Eec2 extends $3c {
  constructor(r2, s, textModelResolverService, t, u, w, y, contextKeyService, z) {
    super();
    this.r = r2;
    this.s = s;
    this.t = t;
    this.u = u;
    this.w = w;
    this.y = y;
    this.z = z;
    this.a = /* @__PURE__ */ new Map();
    this.f = this.B(new $ze());
    this.onActiveOutputChannel = this.f.event;
    this.b = this.r.get(OUTPUT_ACTIVE_CHANNEL_KEY, 1, "");
    this.g = $TS.bindTo(contextKeyService);
    this.g.set(this.b);
    this.B(this.onActiveOutputChannel((channel) => this.g.set(channel)));
    this.h = $MS.bindTo(contextKeyService);
    this.j = $NS.bindTo(contextKeyService);
    this.m = $OS.bindTo(contextKeyService);
    this.n = $PS.bindTo(contextKeyService);
    this.B(textModelResolverService.registerTextModelContentProvider(Schemas.outputChannel, this));
    this.B(s.createInstance($Cec));
    const registry4 = $Wn.as($SS.OutputChannels);
    for (const channelIdentifier of registry4.getChannels()) {
      this.C(channelIdentifier.id);
    }
    this.B(registry4.onDidRegisterChannel(this.C, this));
    if (!this.c) {
      const channels = this.getChannelDescriptors();
      this.I(channels && channels.length > 0 ? this.getChannel(channels[0].id) : void 0);
    }
    this.B(Event2.filter(this.y.onDidChangeViewVisibility, (e) => e.id === $KS && e.visible)(() => {
      if (this.c) {
        this.y.getActiveViewWithId($KS)?.showChannel(this.c, true);
      }
    }));
    this.B(this.u.onDidChangeLogLevel((_level) => {
      this.G();
      this.H();
    }));
    this.B(this.z.onDidChangeDefaultLogLevels(() => {
      this.H();
    }));
    this.B(this.w.onDidShutdown(() => this.dispose()));
  }
  provideTextContent(resource) {
    const channel = this.getChannel(resource.path);
    if (channel) {
      return channel.model.loadModel();
    }
    return null;
  }
  async showChannel(id2, preserveFocus) {
    const channel = this.getChannel(id2);
    if (this.c?.id !== channel?.id) {
      this.I(channel);
      this.f.fire(id2);
    }
    const outputView = await this.y.openView($KS, !preserveFocus);
    if (outputView && channel) {
      outputView.showChannel(channel, !!preserveFocus);
    }
  }
  getChannel(id2) {
    return this.a.get(id2);
  }
  getChannelDescriptor(id2) {
    return $Wn.as($SS.OutputChannels).getChannel(id2);
  }
  getChannelDescriptors() {
    return $Wn.as($SS.OutputChannels).getChannels();
  }
  getActiveChannel() {
    return this.c;
  }
  async C(channelId) {
    const channel = this.D(channelId);
    this.a.set(channelId, channel);
    if (!this.c || this.b === channelId) {
      this.I(channel);
      this.f.fire(channelId);
      const outputView = this.y.getActiveViewWithId($KS);
      outputView?.showChannel(channel, true);
    }
  }
  D(id2) {
    const channel = this.F(id2);
    this.B(Event2.once(channel.model.onDispose)(() => {
      if (this.c === channel) {
        const channels = this.getChannelDescriptors();
        const channel2 = channels.length ? this.getChannel(channels[0].id) : void 0;
        if (channel2 && this.y.isViewVisible($KS)) {
          this.showChannel(channel2.id);
        } else {
          this.I(void 0);
        }
      }
      $Wn.as($SS.OutputChannels).removeChannel(id2);
    }));
    return channel;
  }
  F(id2) {
    const channelData = $Wn.as($SS.OutputChannels).getChannel(id2);
    if (!channelData) {
      this.t.error(`Channel '${id2}' is not registered yet`);
      throw new Error(`Channel '${id2}' is not registered yet`);
    }
    return this.s.createInstance(OutputChannel, channelData);
  }
  G() {
    const descriptor = this.c?.outputChannelDescriptor;
    const channelLogLevel = descriptor?.log ? this.u.getLogLevel(descriptor.file) : void 0;
    this.m.set(channelLogLevel !== void 0 ? $Ln(channelLogLevel) : "");
  }
  async H() {
    const descriptor = this.c?.outputChannelDescriptor;
    if (descriptor?.log) {
      const channelLogLevel = this.u.getLogLevel(descriptor.file);
      const channelDefaultLogLevel = await this.z.getDefaultLogLevel(descriptor.extensionId);
      this.n.set(channelDefaultLogLevel === channelLogLevel);
    } else {
      this.n.set(false);
    }
  }
  I(channel) {
    this.c = channel;
    const descriptor = channel?.outputChannelDescriptor;
    this.h.set(!!descriptor?.file);
    this.j.set(descriptor !== void 0 && $o_b.isLevelSettable(descriptor));
    this.H();
    this.G();
    if (this.c) {
      this.r.store(
        OUTPUT_ACTIVE_CHANNEL_KEY,
        this.c.id,
        1,
        1
        /* StorageTarget.MACHINE */
      );
    } else {
      this.r.remove(
        OUTPUT_ACTIVE_CHANNEL_KEY,
        1
        /* StorageScope.WORKSPACE */
      );
    }
  }
};
$Eec = __decorate([
  __param(0, $jv),
  __param(1, $Pk),
  __param(2, $oG),
  __param(3, $wn),
  __param(4, $xn),
  __param(5, $KL),
  __param(6, $uob),
  __param(7, $on),
  __param(8, $n_b)
], $Eec);

// out-build/vs/workbench/contrib/output/browser/outputView.js
var $Dec = class $Dec2 extends $_ob {
  get scrollLock() {
    return !!this.f.get();
  }
  set scrollLock(scrollLock) {
    this.f.set(scrollLock);
  }
  constructor(options3, keybindingService, contextMenuService, configurationService, contextKeyService, viewDescriptorService, instantiationService, openerService, themeService, telemetryService, hoverService) {
    super(options3, keybindingService, contextMenuService, configurationService, contextKeyService, viewDescriptorService, instantiationService, openerService, themeService, telemetryService, hoverService);
    this.c = null;
    this.f = $QS.bindTo(this.Bb);
    const editorInstantiationService = this.B(instantiationService.createChild(new $Ok([$on, this.xb])));
    this.a = this.B(editorInstantiationService.createInstance(OutputEditor));
    this.B(this.a.onTitleAreaUpdate(() => {
      this.Qb(this.a.getTitle());
      this.$b();
    }));
    this.B(this.onDidChangeBodyVisibility(() => this.j(this.isBodyVisible())));
  }
  showChannel(channel, preserveFocus) {
    if (this.b !== channel.id) {
      this.m(channel);
    }
    if (!preserveFocus) {
      this.focus();
    }
  }
  focus() {
    super.focus();
    this.c?.then(() => this.a.focus());
  }
  W(container2) {
    super.W(container2);
    this.a.create(container2);
    container2.classList.add("output-view");
    const codeEditor = this.a.getControl();
    codeEditor.setAriaOptions({ role: "document", activeDescendant: void 0 });
    this.B(codeEditor.onDidChangeModelContent(() => {
      if (!this.scrollLock) {
        this.a.revealLastLine();
      }
    }));
    this.B(codeEditor.onDidChangeCursorPosition((e) => {
      if (e.reason !== 3) {
        return;
      }
      if (!this.Ab.getValue("output.smartScroll.enabled")) {
        return;
      }
      const model = codeEditor.getModel();
      if (model) {
        const newPositionLine = e.position.lineNumber;
        const lastLine = model.getLineCount();
        this.scrollLock = lastLine !== newPositionLine;
      }
    }));
  }
  X(height, width2) {
    super.X(height, width2);
    this.a.layout(new $rj(width2, height));
  }
  j(visible) {
    this.a.setVisible(visible);
    if (!visible) {
      this.n();
    }
  }
  m(channel) {
    this.b = channel.id;
    const input = this.r(channel);
    if (!this.a.input || !input.matches(this.a.input)) {
      this.c?.cancel();
      this.c = $Hh((token) => this.a.setInput(this.r(channel), { preserveFocus: true }, /* @__PURE__ */ Object.create(null), token).then(() => this.a));
    }
  }
  n() {
    this.b = void 0;
    this.a.clearInput();
    this.c = null;
  }
  r(channel) {
    return this.Db.createInstance($6vb, channel.uri, localize(8700, null, channel.label), localize(8701, null, channel.label), void 0, void 0);
  }
};
$Dec = __decorate([
  __param(1, $Ty),
  __param(2, $50),
  __param(3, $kl),
  __param(4, $on),
  __param(5, $$M),
  __param(6, $Pk),
  __param(7, $O4),
  __param(8, $gs),
  __param(9, $zv),
  __param(10, $5$)
], $Dec);
var OutputEditor = class OutputEditor2 extends $OUb {
  constructor(telemetryService, instantiationService, storageService, $149, textResourceConfigurationService, themeService, editorGroupService, editorService, fileService) {
    super($KS, editorGroupService.activeGroup, telemetryService, instantiationService, storageService, textResourceConfigurationService, themeService, editorGroupService, editorService, fileService);
    this.$ = $149;
    this.c = this.B(instantiationService.createInstance($lqb));
  }
  getId() {
    return $KS;
  }
  getTitle() {
    return localize(8702, null);
  }
  Hb(configuration2) {
    const options3 = super.Hb(configuration2);
    options3.wordWrap = "on";
    options3.lineNumbers = "off";
    options3.glyphMargin = false;
    options3.lineDecorationsWidth = 20;
    options3.rulers = [];
    options3.folding = false;
    options3.scrollBeyondLastLine = false;
    options3.renderLineHighlight = "none";
    options3.minimap = { enabled: false };
    options3.renderValidationDecorations = "editable";
    options3.padding = void 0;
    options3.readOnly = true;
    options3.domReadOnly = true;
    options3.unicodeHighlight = {
      nonBasicASCII: false,
      invisibleCharacters: false,
      ambiguousCharacters: false
    };
    const outputConfig = this.$.getValue("[Log]");
    if (outputConfig) {
      if (outputConfig["editor.minimap.enabled"]) {
        options3.minimap = { enabled: true };
      }
      if ("editor.wordWrap" in outputConfig) {
        options3.wordWrap = outputConfig["editor.wordWrap"];
      }
    }
    return options3;
  }
  Yb() {
    return this.input ? this.input.getAriaLabel() : localize(8703, null);
  }
  Cb() {
    return this.input ? $0tb(this.input, void 0, void 0, this.cb.count) : this.Yb();
  }
  async setInput(input, options3, context, token) {
    const focus = !(options3 && options3.preserveFocus);
    if (this.input && input.matches(this.input)) {
      return;
    }
    if (this.input) {
      this.input.dispose();
    }
    await super.setInput(input, options3, context, token);
    this.c.set(input.resource);
    if (focus) {
      this.focus();
    }
    this.revealLastLine();
  }
  clearInput() {
    if (this.input) {
      this.input.dispose();
    }
    super.clearInput();
    this.c.reset();
  }
  Y(parent) {
    parent.setAttribute("role", "document");
    super.Y(parent);
    const scopedContextKeyService = this.scopedContextKeyService;
    if (scopedContextKeyService) {
      $LS.bindTo(scopedContextKeyService).set(true);
    }
  }
};
OutputEditor = __decorate([
  __param(0, $zv),
  __param(1, $Pk),
  __param(2, $jv),
  __param(3, $kl),
  __param(4, $zG),
  __param(5, $gs),
  __param(6, $iJ),
  __param(7, $mJ),
  __param(8, $km)
], OutputEditor);

// out-build/vs/workbench/contrib/output/browser/output.contribution.js
$SC(
  $RS,
  $Eec,
  1
  /* InstantiationType.Delayed */
);
$JF.registerLanguage({
  id: $HS,
  extensions: [],
  mimetypes: [$GS]
});
$JF.registerLanguage({
  id: $JS,
  extensions: [],
  mimetypes: [$IS]
});
var outputViewIcon = $9r("output-view-icon", $6l.output, localize(8675, null));
var VIEW_CONTAINER3 = $Wn.as(Extensions5.ViewContainersRegistry).registerViewContainer({
  id: $KS,
  title: localize2(8690, "Output"),
  icon: outputViewIcon,
  order: 1,
  ctorDescriptor: new $Nk($oqb, [$KS, { mergeViewWithContainerWhenSingleView: true }]),
  storageId: $KS,
  hideIfEmpty: true
}, 1, { doNotRegisterOpenCommand: true });
$Wn.as(Extensions5.ViewsRegistry).registerViews([{
  id: $KS,
  name: localize2(8691, "Output"),
  containerIcon: outputViewIcon,
  canMoveView: true,
  canToggleVisibility: false,
  ctorDescriptor: new $Nk($Dec),
  openCommandActionDescriptor: {
    id: "workbench.action.output.toggleOutput",
    mnemonicTitle: localize(8676, null),
    keybindings: {
      primary: 2048 | 1024 | 51,
      linux: {
        primary: $$e(
          2048 | 41,
          2048 | 38
          /* KeyCode.KeyH */
        )
        // On Ubuntu Ctrl+Shift+U is taken by some global OS command
      }
    },
    order: 1
  }
}], VIEW_CONTAINER3);
var OutputContribution = class OutputContribution2 extends $3c {
  constructor(f, g, h3) {
    super();
    this.f = f;
    this.g = g;
    this.h = h3;
    this.j();
  }
  j() {
    this.m();
    this.n();
    this.r();
    this.s();
    this.t();
    this.u();
    this.C();
    this.D();
    this.z();
  }
  m() {
    this.B($hJ(class extends $gJ {
      constructor() {
        super({
          id: `workbench.output.action.switchBetweenOutputs`,
          title: localize(8677, null)
        });
      }
      async run(accessor, channelId) {
        if (channelId) {
          accessor.get($RS).showChannel(channelId, true);
        }
      }
    }));
    const switchOutputMenu = new $bJ("workbench.output.menu.switchOutput");
    this.B($dJ.appendMenuItem($bJ.ViewTitle, {
      submenu: switchOutputMenu,
      title: localize(8678, null),
      group: "navigation",
      when: $7m.equals("view", $KS),
      order: 1,
      isSelection: true
    }));
    const registeredChannels = /* @__PURE__ */ new Map();
    this.B($1c(() => $Xc(registeredChannels.values())));
    const registerOutputChannels = (channels) => {
      for (const channel of channels) {
        const title = channel.label;
        const group2 = channel.extensionId ? "0_ext_outputchannels" : "1_core_outputchannels";
        registeredChannels.set(channel.id, $hJ(class extends $gJ {
          constructor() {
            super({
              id: `workbench.action.output.show.${channel.id}`,
              title,
              toggled: $TS.isEqualTo(channel.id),
              menu: {
                id: switchOutputMenu,
                group: group2
              }
            });
          }
          async run(accessor) {
            return accessor.get($RS).showChannel(channel.id, true);
          }
        }));
      }
    };
    registerOutputChannels(this.f.getChannelDescriptors());
    const outputChannelRegistry2 = $Wn.as($SS.OutputChannels);
    this.B(outputChannelRegistry2.onDidRegisterChannel((e) => {
      const channel = this.f.getChannelDescriptor(e);
      if (channel) {
        registerOutputChannels([channel]);
      }
    }));
    this.B(outputChannelRegistry2.onDidRemoveChannel((e) => {
      registeredChannels.get(e)?.dispose();
      registeredChannels.delete(e);
    }));
  }
  n() {
    this.B($hJ(class extends $gJ {
      constructor() {
        super({
          id: "workbench.action.showOutputChannels",
          title: localize2(8692, "Show Output Channels..."),
          category: localize2(8693, "Output"),
          f1: true
        });
      }
      async run(accessor) {
        const outputService = accessor.get($RS);
        const quickInputService = accessor.get($1M);
        const extensionChannels = [], coreChannels = [];
        for (const channel of outputService.getChannelDescriptors()) {
          if (channel.extensionId) {
            extensionChannels.push(channel);
          } else {
            coreChannels.push(channel);
          }
        }
        const entries2 = [];
        for (const { id: id2, label: label3 } of extensionChannels) {
          entries2.push({ id: id2, label: label3 });
        }
        if (extensionChannels.length && coreChannels.length) {
          entries2.push({ type: "separator" });
        }
        for (const { id: id2, label: label3 } of coreChannels) {
          entries2.push({ id: id2, label: label3 });
        }
        const entry = await quickInputService.pick(entries2, { placeHolder: localize(8679, null) });
        if (entry) {
          return outputService.showChannel(entry.id);
        }
      }
    }));
  }
  r() {
    this.B($hJ(class extends $gJ {
      constructor() {
        super({
          id: `workbench.output.action.clearOutput`,
          title: localize2(8694, "Clear Output"),
          category: $qn.View,
          menu: [{
            id: $bJ.ViewTitle,
            when: $7m.equals("view", $KS),
            group: "navigation",
            order: 2
          }, {
            id: $bJ.CommandPalette
          }, {
            id: $bJ.EditorContext,
            when: $LS
          }],
          icon: $6l.clearAll
        });
      }
      async run(accessor) {
        const outputService = accessor.get($RS);
        const accessibilitySignalService = accessor.get($I9);
        const activeChannel = outputService.getActiveChannel();
        if (activeChannel) {
          activeChannel.clear();
          accessibilitySignalService.playSignal($N9.clear);
        }
      }
    }));
  }
  s() {
    this.B($hJ(class extends $gJ {
      constructor() {
        super({
          id: `workbench.output.action.toggleAutoScroll`,
          title: localize2(8695, "Toggle Auto Scrolling"),
          tooltip: localize(8680, null),
          menu: {
            id: $bJ.ViewTitle,
            when: $7m.and($7m.equals("view", $KS)),
            group: "navigation",
            order: 3
          },
          icon: $6l.lock,
          toggled: {
            condition: $QS,
            icon: $6l.unlock,
            tooltip: localize(8681, null)
          }
        });
      }
      async run(accessor) {
        const outputView = accessor.get($uob).getActiveViewWithId($KS);
        outputView.scrollLock = !outputView.scrollLock;
      }
    }));
  }
  t() {
    const that = this;
    this.B($hJ(class extends $gJ {
      constructor() {
        super({
          id: `workbench.action.openActiveLogOutputFile`,
          title: localize2(8696, "Open Output in Editor"),
          menu: [{
            id: $bJ.ViewTitle,
            when: $7m.equals("view", $KS),
            group: "navigation",
            order: 4,
            isHiddenByDefault: true
          }],
          icon: $6l.goToFile,
          precondition: $MS
        });
      }
      async run() {
        that.w();
      }
    }));
  }
  u() {
    const that = this;
    this.B($hJ(class extends $gJ {
      constructor() {
        super({
          id: `workbench.action.openActiveLogOutputFileInNewWindow`,
          title: localize2(8697, "Open Output in New Window"),
          menu: [{
            id: $bJ.ViewTitle,
            when: $7m.equals("view", $KS),
            group: "navigation",
            order: 5,
            isHiddenByDefault: true
          }],
          icon: $6l.emptyWindow,
          precondition: $MS
        });
      }
      async run() {
        that.w($pJ);
      }
    }));
  }
  async w(group2) {
    const fileOutputChannelDescriptor = this.y();
    if (fileOutputChannelDescriptor) {
      await this.h.updateReadonly(fileOutputChannelDescriptor.file, true);
      await this.g.openEditor({
        resource: fileOutputChannelDescriptor.file,
        options: {
          pinned: true
        }
      }, group2);
    }
  }
  y() {
    const channel = this.f.getActiveChannel();
    if (channel) {
      const descriptor = this.f.getChannelDescriptors().filter((c) => c.id === channel.id)[0];
      if (descriptor?.file) {
        return descriptor;
      }
    }
    return null;
  }
  z() {
    const that = this;
    const logLevelMenu = new $bJ("workbench.output.menu.logLevel");
    this.B($dJ.appendMenuItem($bJ.ViewTitle, {
      submenu: logLevelMenu,
      title: localize(8682, null),
      group: "navigation",
      when: $7m.and($7m.equals("view", $KS), $NS),
      icon: $6l.gear,
      order: 6
    }));
    let order = 0;
    const registerLogLevel = (logLevel) => {
      this.B($hJ(class extends $gJ {
        constructor() {
          super({
            id: `workbench.action.output.activeOutputLogLevel.${logLevel}`,
            title: $Mn(logLevel).value,
            toggled: $OS.isEqualTo($Ln(logLevel)),
            menu: {
              id: logLevelMenu,
              order: order++,
              group: "0_level"
            }
          });
        }
        async run(accessor) {
          const channel = that.f.getActiveChannel();
          if (channel) {
            const channelDescriptor = that.f.getChannelDescriptor(channel.id);
            if (channelDescriptor?.log && channelDescriptor.file) {
              return accessor.get($xn).setLogLevel(channelDescriptor.file, logLevel);
            }
          }
        }
      }));
    };
    registerLogLevel(LogLevel.Trace);
    registerLogLevel(LogLevel.Debug);
    registerLogLevel(LogLevel.Info);
    registerLogLevel(LogLevel.Warning);
    registerLogLevel(LogLevel.Error);
    registerLogLevel(LogLevel.Off);
    this.B($hJ(class extends $gJ {
      constructor() {
        super({
          id: `workbench.action.output.activeOutputLogLevelDefault`,
          title: localize(8683, null),
          menu: {
            id: logLevelMenu,
            order,
            group: "1_default"
          },
          precondition: $PS.negate()
        });
      }
      async run(accessor) {
        const channel = that.f.getActiveChannel();
        if (channel) {
          const channelDescriptor = that.f.getChannelDescriptor(channel.id);
          if (channelDescriptor?.log && channelDescriptor.file) {
            const logLevel = accessor.get($xn).getLogLevel(channelDescriptor.file);
            return await accessor.get($n_b).setDefaultLogLevel(logLevel, channelDescriptor.extensionId);
          }
        }
      }
    }));
  }
  C() {
    this.B($hJ(class extends $gJ {
      constructor() {
        super({
          id: "workbench.action.showLogs",
          title: localize2(8698, "Show Logs..."),
          category: $qn.Developer,
          menu: {
            id: $bJ.CommandPalette
          }
        });
      }
      async run(accessor) {
        const outputService = accessor.get($RS);
        const quickInputService = accessor.get($1M);
        const extensionLogs = [], logs = [];
        for (const channel of outputService.getChannelDescriptors()) {
          if (channel.log) {
            if (channel.extensionId) {
              extensionLogs.push(channel);
            } else {
              logs.push(channel);
            }
          }
        }
        const entries2 = [];
        for (const { id: id2, label: label3 } of logs) {
          entries2.push({ id: id2, label: label3 });
        }
        if (extensionLogs.length && logs.length) {
          entries2.push({ type: "separator", label: localize(8684, null) });
        }
        for (const { id: id2, label: label3 } of extensionLogs) {
          entries2.push({ id: id2, label: label3 });
        }
        const entry = await quickInputService.pick(entries2, { placeHolder: localize(8685, null) });
        if (entry) {
          return outputService.showChannel(entry.id);
        }
      }
    }));
  }
  D() {
    this.B($hJ(class extends $gJ {
      constructor() {
        super({
          id: "workbench.action.openLogFile",
          title: localize2(8699, "Open Log File..."),
          category: $qn.Developer,
          menu: {
            id: $bJ.CommandPalette
          },
          metadata: {
            description: "workbench.action.openLogFile",
            args: [{
              name: "logFile",
              schema: {
                markdownDescription: localize(8686, null),
                type: "string"
              }
            }]
          }
        });
      }
      async run(accessor, args2) {
        const outputService = accessor.get($RS);
        const quickInputService = accessor.get($1M);
        const editorService = accessor.get($mJ);
        const fileConfigurationService = accessor.get($4J);
        let entry;
        const argName = args2 && typeof args2 === "string" ? args2 : void 0;
        const extensionChannels = [];
        const coreChannels = [];
        for (const c of outputService.getChannelDescriptors()) {
          if (c.file && c.log) {
            const e = { id: c.id, label: c.label, channel: c };
            if (c.extensionId) {
              extensionChannels.push(e);
            } else {
              coreChannels.push(e);
            }
            if (e.id === argName) {
              entry = e;
            }
          }
        }
        if (!entry) {
          const entries2 = [...extensionChannels.sort((a, b) => a.label.localeCompare(b.label))];
          if (entries2.length && coreChannels.length) {
            entries2.push({ type: "separator" });
            entries2.push(...coreChannels.sort((a, b) => a.label.localeCompare(b.label)));
          }
          entry = await quickInputService.pick(entries2, { placeHolder: localize(8687, null) });
        }
        if (entry) {
          const resource = $Kg(entry.channel.file);
          await fileConfigurationService.updateReadonly(resource, true);
          await editorService.openEditor({
            resource,
            options: {
              pinned: true
            }
          });
        }
      }
    }));
  }
};
OutputContribution = __decorate([
  __param(0, $RS),
  __param(1, $mJ),
  __param(2, $4J)
], OutputContribution);
$Wn.as(Extensions2.Workbench).registerWorkbenchContribution(
  OutputContribution,
  3
  /* LifecyclePhase.Restored */
);
$Wn.as($Ht.Configuration).registerConfiguration({
  id: "output",
  order: 30,
  title: localize(8688, null),
  type: "object",
  properties: {
    "output.smartScroll.enabled": {
      type: "boolean",
      description: localize(8689, null),
      default: true,
      scope: 3,
      tags: ["output"]
    }
  }
});
$0I.registerKeybindingRule({
  id: "cursorWordAccessibilityLeft",
  when: $7m.and(EditorContextKeys.textInputFocus, $OD, $ueb, $7m.equals($jqb.key, $KS)),
  primary: 2048 | 15,
  weight: 200
  /* KeybindingWeight.WorkbenchContrib */
});
$0I.registerKeybindingRule({
  id: "cursorWordAccessibilityLeftSelect",
  when: $7m.and(EditorContextKeys.textInputFocus, $OD, $ueb, $7m.equals($jqb.key, $KS)),
  primary: 2048 | 1024 | 15,
  weight: 200
  /* KeybindingWeight.WorkbenchContrib */
});
$0I.registerKeybindingRule({
  id: "cursorWordAccessibilityRight",
  when: $7m.and(EditorContextKeys.textInputFocus, $OD, $ueb, $7m.equals($jqb.key, $KS)),
  primary: 2048 | 17,
  weight: 200
  /* KeybindingWeight.WorkbenchContrib */
});
$0I.registerKeybindingRule({
  id: "cursorWordAccessibilityRightSelect",
  when: $7m.and(EditorContextKeys.textInputFocus, $OD, $ueb, $7m.equals($jqb.key, $KS)),
  primary: 2048 | 1024 | 17,
  weight: 200
  /* KeybindingWeight.WorkbenchContrib */
});

// out-build/vs/platform/terminal/common/terminalLogService.js
var $Fec = class $Fec2 extends $3c {
  get onDidChangeLogLevel() {
    return this.a.onDidChangeLogLevel;
  }
  constructor(c, workspaceContextService, environmentService) {
    super();
    this.c = c;
    this.a = this.c.createLogger($vh(environmentService.logsHome, "terminal.log"), { id: "terminal", name: localize(2125, null) });
    this.B(Event2.runAndSubscribe(workspaceContextService.onDidChangeWorkspaceFolders, () => {
      this.b = workspaceContextService.getWorkspace().id.substring(0, 7);
    }));
  }
  getLevel() {
    return this.a.getLevel();
  }
  setLevel(level) {
    this.a.setLevel(level);
  }
  flush() {
    this.a.flush();
  }
  trace(message, ...args2) {
    this.a.trace(this.f(message), args2);
  }
  debug(message, ...args2) {
    this.a.debug(this.f(message), args2);
  }
  info(message, ...args2) {
    this.a.info(this.f(message), args2);
  }
  warn(message, ...args2) {
    this.a.warn(this.f(message), args2);
  }
  error(message, ...args2) {
    if (message instanceof Error) {
      this.a.error(this.f(""), message, args2);
      return;
    }
    this.a.error(this.f(message), args2);
  }
  f(message) {
    if (this.a.getLevel() === LogLevel.Trace) {
      return `[${this.b}] ${message}`;
    }
    return message;
  }
};
$Fec = __decorate([
  __param(0, $xn),
  __param(1, $Zk),
  __param(2, $Xk)
], $Fec);

// out-build/vs/platform/terminal/common/terminalProfiles.js
function $tB(detectedProfiles, extensionProfiles) {
  const result = [{
    name: null,
    description: localize(2157, null)
  }];
  result.push(...detectedProfiles.map((e) => {
    return {
      name: e.profileName,
      description: createProfileDescription(e)
    };
  }));
  if (extensionProfiles) {
    result.push(...extensionProfiles.map((extensionProfile) => {
      return {
        name: extensionProfile.title,
        description: createExtensionProfileDescription(extensionProfile)
      };
    }));
  }
  return {
    values: result.map((e) => e.name),
    markdownDescriptions: result.map((e) => e.description)
  };
}
function createProfileDescription(profile) {
  let description = `$(${ThemeIcon.isThemeIcon(profile.icon) ? profile.icon.id : profile.icon ? profile.icon : $6l.terminal.id}) ${profile.profileName}
- path: ${profile.path}`;
  if (profile.args) {
    if (typeof profile.args === "string") {
      description += `
- args: "${profile.args}"`;
    } else {
      description += `
- args: [${profile.args.length === 0 ? "" : `'${profile.args.join(`','`)}'`}]`;
    }
  }
  if (profile.overrideName !== void 0) {
    description += `
- overrideName: ${profile.overrideName}`;
  }
  if (profile.color) {
    description += `
- color: ${profile.color}`;
  }
  if (profile.env) {
    description += `
- env: ${JSON.stringify(profile.env)}`;
  }
  return description;
}
function createExtensionProfileDescription(profile) {
  const description = `$(${ThemeIcon.isThemeIcon(profile.icon) ? profile.icon.id : profile.icon ? profile.icon : $6l.terminal.id}) ${profile.title}
- extensionIdentifier: ${profile.extensionIdentifier}`;
  return description;
}
function $uB(args1, args2) {
  if (!args1 && !args2) {
    return true;
  } else if (typeof args1 === "string" && typeof args2 === "string") {
    return args1 === args2;
  } else if (Array.isArray(args1) && Array.isArray(args2)) {
    if (args1.length !== args2.length) {
      return false;
    }
    for (let i2 = 0; i2 < args1.length; i2++) {
      if (args1[i2] !== args2[i2]) {
        return false;
      }
    }
    return true;
  }
  return false;
}
function $vB(a, b) {
  if (!a && !b) {
    return true;
  } else if (!a || !b) {
    return false;
  }
  if (ThemeIcon.isThemeIcon(a) && ThemeIcon.isThemeIcon(b)) {
    return a.id === b.id && a.color === b.color;
  }
  if (typeof a === "object" && "light" in a && "dark" in a && typeof b === "object" && "light" in b && "dark" in b) {
    const castedA = a;
    const castedB = b;
    if ((URI.isUri(castedA.light) || $wB(castedA.light)) && (URI.isUri(castedA.dark) || $wB(castedA.dark)) && (URI.isUri(castedB.light) || $wB(castedB.light)) && (URI.isUri(castedB.dark) || $wB(castedB.dark))) {
      return castedA.light.path === castedB.light.path && castedA.dark.path === castedB.dark.path;
    }
  }
  if (URI.isUri(a) && URI.isUri(b) || ($wB(a) || $wB(b))) {
    const castedA = a;
    const castedB = b;
    return castedA.path === castedB.path && castedA.scheme === castedB.scheme;
  }
  return false;
}
function $wB(thing) {
  if (!thing) {
    return false;
  }
  return typeof thing.path === "string" && typeof thing.scheme === "string";
}

// out-build/vs/platform/terminal/common/terminalPlatformConfiguration.js
var $xB = {
  type: ["string", "null"],
  enum: [
    "terminal.ansiBlack",
    "terminal.ansiRed",
    "terminal.ansiGreen",
    "terminal.ansiYellow",
    "terminal.ansiBlue",
    "terminal.ansiMagenta",
    "terminal.ansiCyan",
    "terminal.ansiWhite"
  ],
  default: null
};
var $yB = {
  type: "string",
  enum: Array.from($4l(), (icon2) => icon2.id),
  markdownEnumDescriptions: Array.from($4l(), (icon2) => `$(${icon2.id})`)
};
var terminalProfileBaseProperties = {
  args: {
    description: localize(2126, null),
    type: "array",
    items: {
      type: "string"
    }
  },
  overrideName: {
    description: localize(2127, null),
    type: "boolean"
  },
  icon: {
    description: localize(2128, null),
    ...$yB
  },
  color: {
    description: localize(2129, null),
    ...$xB
  },
  env: {
    markdownDescription: localize(2130, null),
    type: "object",
    additionalProperties: {
      type: ["string", "null"]
    },
    default: {}
  }
};
var terminalProfileSchema = {
  type: "object",
  required: ["path"],
  properties: {
    path: {
      description: localize(2131, null),
      type: ["string", "array"],
      items: {
        type: "string"
      }
    },
    ...terminalProfileBaseProperties
  }
};
var terminalAutomationProfileSchema = {
  type: "object",
  required: ["path"],
  properties: {
    path: {
      description: localize(2132, null),
      type: ["string"],
      items: {
        type: "string"
      }
    },
    ...terminalProfileBaseProperties
  }
};
function createTerminalProfileMarkdownDescription(platform) {
  const key2 = platform === 2 ? "linux" : platform === 1 ? "osx" : "windows";
  return localize(2133, null, $k(platform), '```json\n"terminal.integrated.profile.' + key2 + '": {\n  "bash": null\n}\n```', "[", "](https://code.visualstudio.com/docs/terminal/profiles)");
}
var terminalPlatformConfiguration = {
  id: "terminal",
  order: 100,
  title: localize(2134, null),
  type: "object",
  properties: {
    [
      "terminal.integrated.automationProfile.linux"
      /* TerminalSettingId.AutomationProfileLinux */
    ]: {
      restricted: true,
      markdownDescription: localize(2135, null),
      type: ["object", "null"],
      default: null,
      "anyOf": [
        { type: "null" },
        terminalAutomationProfileSchema
      ],
      defaultSnippets: [
        {
          body: {
            path: "${1}",
            icon: "${2}"
          }
        }
      ]
    },
    [
      "terminal.integrated.automationProfile.osx"
      /* TerminalSettingId.AutomationProfileMacOs */
    ]: {
      restricted: true,
      markdownDescription: localize(2136, null),
      type: ["object", "null"],
      default: null,
      "anyOf": [
        { type: "null" },
        terminalAutomationProfileSchema
      ],
      defaultSnippets: [
        {
          body: {
            path: "${1}",
            icon: "${2}"
          }
        }
      ]
    },
    [
      "terminal.integrated.automationProfile.windows"
      /* TerminalSettingId.AutomationProfileWindows */
    ]: {
      restricted: true,
      markdownDescription: localize(2137, null, "`terminal.integrated.automationShell.windows`"),
      type: ["object", "null"],
      default: null,
      "anyOf": [
        { type: "null" },
        terminalAutomationProfileSchema
      ],
      defaultSnippets: [
        {
          body: {
            path: "${1}",
            icon: "${2}"
          }
        }
      ]
    },
    [
      "terminal.integrated.profiles.windows"
      /* TerminalSettingId.ProfilesWindows */
    ]: {
      restricted: true,
      markdownDescription: createTerminalProfileMarkdownDescription(
        3
        /* Platform.Windows */
      ),
      type: "object",
      default: {
        "PowerShell": {
          source: "PowerShell",
          icon: "terminal-powershell"
        },
        "Command Prompt": {
          path: [
            "${env:windir}\\Sysnative\\cmd.exe",
            "${env:windir}\\System32\\cmd.exe"
          ],
          args: [],
          icon: "terminal-cmd"
        },
        "Git Bash": {
          source: "Git Bash"
        }
      },
      additionalProperties: {
        "anyOf": [
          {
            type: "object",
            required: ["source"],
            properties: {
              source: {
                description: localize(2138, null),
                enum: ["PowerShell", "Git Bash"]
              },
              ...terminalProfileBaseProperties
            }
          },
          {
            type: "object",
            required: ["extensionIdentifier", "id", "title"],
            properties: {
              extensionIdentifier: {
                description: localize(2139, null),
                type: "string"
              },
              id: {
                description: localize(2140, null),
                type: "string"
              },
              title: {
                description: localize(2141, null),
                type: "string"
              },
              ...terminalProfileBaseProperties
            }
          },
          { type: "null" },
          terminalProfileSchema
        ]
      }
    },
    [
      "terminal.integrated.profiles.osx"
      /* TerminalSettingId.ProfilesMacOs */
    ]: {
      restricted: true,
      markdownDescription: createTerminalProfileMarkdownDescription(
        1
        /* Platform.Mac */
      ),
      type: "object",
      default: {
        "bash": {
          path: "bash",
          args: ["-l"],
          icon: "terminal-bash"
        },
        "zsh": {
          path: "zsh",
          args: ["-l"]
        },
        "fish": {
          path: "fish",
          args: ["-l"]
        },
        "tmux": {
          path: "tmux",
          icon: "terminal-tmux"
        },
        "pwsh": {
          path: "pwsh",
          icon: "terminal-powershell"
        }
      },
      additionalProperties: {
        "anyOf": [
          {
            type: "object",
            required: ["extensionIdentifier", "id", "title"],
            properties: {
              extensionIdentifier: {
                description: localize(2142, null),
                type: "string"
              },
              id: {
                description: localize(2143, null),
                type: "string"
              },
              title: {
                description: localize(2144, null),
                type: "string"
              },
              ...terminalProfileBaseProperties
            }
          },
          { type: "null" },
          terminalProfileSchema
        ]
      }
    },
    [
      "terminal.integrated.profiles.linux"
      /* TerminalSettingId.ProfilesLinux */
    ]: {
      restricted: true,
      markdownDescription: createTerminalProfileMarkdownDescription(
        2
        /* Platform.Linux */
      ),
      type: "object",
      default: {
        "bash": {
          path: "bash",
          icon: "terminal-bash"
        },
        "zsh": {
          path: "zsh"
        },
        "fish": {
          path: "fish"
        },
        "tmux": {
          path: "tmux",
          icon: "terminal-tmux"
        },
        "pwsh": {
          path: "pwsh",
          icon: "terminal-powershell"
        }
      },
      additionalProperties: {
        "anyOf": [
          {
            type: "object",
            required: ["extensionIdentifier", "id", "title"],
            properties: {
              extensionIdentifier: {
                description: localize(2145, null),
                type: "string"
              },
              id: {
                description: localize(2146, null),
                type: "string"
              },
              title: {
                description: localize(2147, null),
                type: "string"
              },
              ...terminalProfileBaseProperties
            }
          },
          { type: "null" },
          terminalProfileSchema
        ]
      }
    },
    [
      "terminal.integrated.useWslProfiles"
      /* TerminalSettingId.UseWslProfiles */
    ]: {
      description: localize(2148, null),
      type: "boolean",
      default: true
    },
    [
      "terminal.integrated.inheritEnv"
      /* TerminalSettingId.InheritEnv */
    ]: {
      scope: 1,
      description: localize(2149, null),
      type: "boolean",
      default: true
    },
    [
      "terminal.integrated.persistentSessionScrollback"
      /* TerminalSettingId.PersistentSessionScrollback */
    ]: {
      scope: 1,
      markdownDescription: localize(2150, null),
      type: "number",
      default: 100
    },
    [
      "terminal.integrated.showLinkHover"
      /* TerminalSettingId.ShowLinkHover */
    ]: {
      scope: 1,
      description: localize(2151, null),
      type: "boolean",
      default: true
    },
    [
      "terminal.integrated.ignoreProcessNames"
      /* TerminalSettingId.IgnoreProcessNames */
    ]: {
      markdownDescription: localize(2152, null, "`#terminal.integrated.confirmOnKill#`"),
      type: "array",
      items: {
        type: "string",
        uniqueItems: true
      },
      default: [
        // Popular prompt programs, these should not count as child processes
        "starship",
        "oh-my-posh",
        // Git bash may runs a subprocess of itself (bin\bash.exe -> usr\bin\bash.exe)
        "bash",
        "zsh"
      ]
    }
  }
};
function $zB() {
  $Wn.as($Ht.Configuration).registerConfiguration(terminalPlatformConfiguration);
  $AB();
}
var defaultProfilesConfiguration;
function $AB(detectedProfiles, extensionContributedProfiles) {
  const registry4 = $Wn.as($Ht.Configuration);
  let profileEnum;
  if (detectedProfiles) {
    profileEnum = $tB(detectedProfiles?.profiles, extensionContributedProfiles);
  }
  const oldDefaultProfilesConfiguration = defaultProfilesConfiguration;
  defaultProfilesConfiguration = {
    id: "terminal",
    order: 100,
    title: localize(2153, null),
    type: "object",
    properties: {
      [
        "terminal.integrated.defaultProfile.linux"
        /* TerminalSettingId.DefaultProfileLinux */
      ]: {
        restricted: true,
        markdownDescription: localize(2154, null),
        type: ["string", "null"],
        default: null,
        enum: detectedProfiles?.os === 3 ? profileEnum?.values : void 0,
        markdownEnumDescriptions: detectedProfiles?.os === 3 ? profileEnum?.markdownDescriptions : void 0
      },
      [
        "terminal.integrated.defaultProfile.osx"
        /* TerminalSettingId.DefaultProfileMacOs */
      ]: {
        restricted: true,
        markdownDescription: localize(2155, null),
        type: ["string", "null"],
        default: null,
        enum: detectedProfiles?.os === 2 ? profileEnum?.values : void 0,
        markdownEnumDescriptions: detectedProfiles?.os === 2 ? profileEnum?.markdownDescriptions : void 0
      },
      [
        "terminal.integrated.defaultProfile.windows"
        /* TerminalSettingId.DefaultProfileWindows */
      ]: {
        restricted: true,
        markdownDescription: localize(2156, null),
        type: ["string", "null"],
        default: null,
        enum: detectedProfiles?.os === 1 ? profileEnum?.values : void 0,
        markdownEnumDescriptions: detectedProfiles?.os === 1 ? profileEnum?.markdownDescriptions : void 0
      }
    }
  };
  registry4.updateConfigurations({ add: [defaultProfilesConfiguration], remove: oldDefaultProfilesConfiguration ? [oldDefaultProfilesConfiguration] : [] });
}

// out-build/vs/workbench/contrib/terminal/browser/baseTerminalBackend.js
var $Gec = class extends $3c {
  get isResponsive() {
    return !this.a;
  }
  constructor(h3, j, historyService, configurationResolverService, statusBarService, m) {
    super();
    this.h = h3;
    this.j = j;
    this.m = m;
    this.a = false;
    this.b = this.B(new $ze());
    this.onPtyHostConnected = this.b.event;
    this.c = this.B(new $ze());
    this.onPtyHostRestart = this.c.event;
    this.f = this.B(new $ze());
    this.onPtyHostUnresponsive = this.f.event;
    this.g = this.B(new $ze());
    this.onPtyHostResponsive = this.g.event;
    let unresponsiveStatusBarEntry;
    let statusBarAccessor;
    let hasStarted = false;
    this.B(this.h.onPtyHostExit(() => {
      this.j.error(`The terminal's pty host process exited, the connection to all terminal processes was lost`);
    }));
    this.B(this.onPtyHostConnected(() => hasStarted = true));
    this.B(this.h.onPtyHostStart(() => {
      this.j.debug(`The terminal's pty host process is starting`);
      if (hasStarted) {
        this.j.trace("IPtyHostController#onPtyHostRestart");
        this.c.fire();
      }
      statusBarAccessor?.dispose();
      this.a = false;
    }));
    this.B(this.h.onPtyHostUnresponsive(() => {
      statusBarAccessor?.dispose();
      if (!unresponsiveStatusBarEntry) {
        unresponsiveStatusBarEntry = {
          name: localize(10368, null),
          text: `$(debug-disconnect) ${localize(10369, null)}`,
          tooltip: localize(10370, null),
          ariaLabel: localize(10371, null),
          command: "workbench.action.terminal.restartPtyHost",
          kind: "warning"
        };
      }
      statusBarAccessor = statusBarService.addEntry(
        unresponsiveStatusBarEntry,
        "ptyHostStatus",
        0
        /* StatusbarAlignment.LEFT */
      );
      this.a = true;
      this.f.fire();
    }));
    this.B(this.h.onPtyHostResponsive(() => {
      if (!this.a) {
        return;
      }
      this.j.info("The pty host became responsive again");
      statusBarAccessor?.dispose();
      this.a = false;
      this.g.fire();
    }));
    this.B(this.h.onPtyHostRequestResolveVariables(async (e) => {
      if (e.workspaceId !== this.m.getWorkspace().id) {
        return;
      }
      const activeWorkspaceRootUri = historyService.getLastActiveWorkspaceRoot(Schemas.file);
      const lastActiveWorkspaceRoot = activeWorkspaceRootUri ? this.m.getWorkspaceFolder(activeWorkspaceRootUri) ?? void 0 : void 0;
      const resolveCalls = e.originalText.map((t) => {
        return configurationResolverService.resolveAsync(lastActiveWorkspaceRoot, t);
      });
      const result = await Promise.all(resolveCalls);
      this.h.acceptPtyHostResolvedVariables(e.requestId, result);
    }));
  }
  restartPtyHost() {
    this.h.restartPtyHost();
  }
  n(serializedState) {
    if (serializedState === void 0) {
      return void 0;
    }
    const parsedUnknown = JSON.parse(serializedState);
    if (!("version" in parsedUnknown) || !("state" in parsedUnknown) || !Array.isArray(parsedUnknown.state)) {
      this.j.warn("Could not revive serialized processes, wrong format", parsedUnknown);
      return void 0;
    }
    const parsedCrossVersion = parsedUnknown;
    if (parsedCrossVersion.version !== 1) {
      this.j.warn(`Could not revive serialized processes, wrong version "${parsedCrossVersion.version}"`, parsedCrossVersion);
      return void 0;
    }
    return parsedCrossVersion.state;
  }
  s() {
    return this.m.getWorkspace().id;
  }
};

// out-build/vs/workbench/contrib/terminal/common/basePty.js
var $Hec = class extends $3c {
  constructor(id2, shouldPersist) {
    super();
    this.id = id2;
    this.shouldPersist = shouldPersist;
    this.a = {
      cwd: "",
      initialCwd: "",
      fixedDimensions: { cols: void 0, rows: void 0 },
      title: "",
      shellType: void 0,
      hasChildProcesses: true,
      resolvedShellLaunchConfig: {},
      overrideDimensions: void 0,
      failedShellIntegrationActivation: false,
      usedShellIntegrationInjection: void 0
    };
    this.b = { cols: -1, rows: -1 };
    this.c = false;
    this.f = this.B(new $ze());
    this.onProcessData = this.f.event;
    this.g = this.B(new $ze());
    this.onProcessReplayComplete = this.g.event;
    this.h = this.B(new $ze());
    this.onProcessReady = this.h.event;
    this.j = this.B(new $ze());
    this.onDidChangeProperty = this.j.event;
    this.m = this.B(new $ze());
    this.onProcessExit = this.m.event;
    this.n = this.B(new $ze());
    this.onRestoreCommands = this.n.event;
  }
  async getInitialCwd() {
    return this.a.initialCwd;
  }
  async getCwd() {
    return this.a.cwd || this.a.initialCwd;
  }
  handleData(e) {
    this.f.fire(e);
  }
  handleExit(e) {
    this.m.fire(e);
  }
  handleReady(e) {
    this.h.fire(e);
  }
  handleDidChangeProperty({ type, value }) {
    switch (type) {
      case "cwd":
        this.a.cwd = value;
        break;
      case "initialCwd":
        this.a.initialCwd = value;
        break;
      case "resolvedShellLaunchConfig":
        if (value.cwd && typeof value.cwd !== "string") {
          value.cwd = URI.revive(value.cwd);
        }
    }
    this.j.fire({ type, value });
  }
  async handleReplay(e) {
    $S(`code/terminal/willHandleReplay/${this.id}`);
    try {
      this.c = true;
      for (const innerEvent of e.events) {
        if (innerEvent.cols !== 0 || innerEvent.rows !== 0) {
          this.j.fire({ type: "overrideDimensions", value: { cols: innerEvent.cols, rows: innerEvent.rows, forceExactSize: true } });
        }
        const e2 = { data: innerEvent.data, trackCommit: true };
        this.f.fire(e2);
        await e2.writePromise;
      }
    } finally {
      this.c = false;
    }
    if (e.commands) {
      this.n.fire(e.commands);
    }
    this.j.fire({ type: "overrideDimensions", value: void 0 });
    $S(`code/terminal/didHandleReplay/${this.id}`);
    this.g.fire();
  }
};

// out-build/vs/workbench/contrib/terminal/browser/remotePty.js
var $Iec = class $Iec2 extends $Hec {
  constructor(id2, shouldPersist, s, t, u) {
    super(id2, shouldPersist);
    this.s = s;
    this.t = t;
    this.u = u;
    this.r = new $Uh();
  }
  async start() {
    const env3 = await this.t.getEnvironment();
    if (!env3) {
      throw new Error("Could not fetch remote environment");
    }
    this.u.trace("Spawning remote agent process", { terminalId: this.id });
    const startResult = await this.s.start(this.id);
    if (startResult && "message" in startResult) {
      return startResult;
    }
    this.r.open();
    return startResult;
  }
  async detach(forcePersist) {
    await this.r.wait();
    return this.s.detachFromProcess(this.id, forcePersist);
  }
  shutdown(immediate) {
    this.r.wait().then((_) => {
      this.s.shutdown(this.id, immediate);
    });
  }
  input(data) {
    if (this.c) {
      return;
    }
    this.r.wait().then((_) => {
      this.s.input(this.id, data);
    });
  }
  processBinary(e) {
    return this.s.processBinary(this.id, e);
  }
  resize(cols, rows) {
    if (this.c || this.b.cols === cols && this.b.rows === rows) {
      return;
    }
    this.r.wait().then((_) => {
      this.b.cols = cols;
      this.b.rows = rows;
      this.s.resize(this.id, cols, rows);
    });
  }
  async clearBuffer() {
    await this.s.clearBuffer(this.id);
  }
  freePortKillProcess(port) {
    if (!this.s.freePortKillProcess) {
      throw new Error("freePortKillProcess does not exist on the local pty service");
    }
    return this.s.freePortKillProcess(port);
  }
  acknowledgeDataEvent(charCount) {
    if (this.c) {
      return;
    }
    this.r.wait().then((_) => {
      this.s.acknowledgeDataEvent(this.id, charCount);
    });
  }
  async setUnicodeVersion(version2) {
    return this.s.setUnicodeVersion(this.id, version2);
  }
  async refreshProperty(type) {
    return this.s.refreshProperty(this.id, type);
  }
  async updateProperty(type, value) {
    return this.s.updateProperty(this.id, type, value);
  }
  handleOrphanQuestion() {
    this.s.orphanQuestionReply(this.id);
  }
};
$Iec = __decorate([
  __param(3, $RL),
  __param(4, $8x)
], $Iec);

// out-build/vs/workbench/contrib/terminal/common/remote/remoteTerminalChannel.js
var $FY = "remoteterminal";
var $GY = class $GY2 {
  get onPtyHostExit() {
    return this.b.listen(
      "$onPtyHostExitEvent"
      /* RemoteTerminalChannelEvent.OnPtyHostExitEvent */
    );
  }
  get onPtyHostStart() {
    return this.b.listen(
      "$onPtyHostStartEvent"
      /* RemoteTerminalChannelEvent.OnPtyHostStartEvent */
    );
  }
  get onPtyHostUnresponsive() {
    return this.b.listen(
      "$onPtyHostUnresponsiveEvent"
      /* RemoteTerminalChannelEvent.OnPtyHostUnresponsiveEvent */
    );
  }
  get onPtyHostResponsive() {
    return this.b.listen(
      "$onPtyHostResponsiveEvent"
      /* RemoteTerminalChannelEvent.OnPtyHostResponsiveEvent */
    );
  }
  get onPtyHostRequestResolveVariables() {
    return this.b.listen(
      "$onPtyHostRequestResolveVariablesEvent"
      /* RemoteTerminalChannelEvent.OnPtyHostRequestResolveVariablesEvent */
    );
  }
  get onProcessData() {
    return this.b.listen(
      "$onProcessDataEvent"
      /* RemoteTerminalChannelEvent.OnProcessDataEvent */
    );
  }
  get onProcessExit() {
    return this.b.listen(
      "$onProcessExitEvent"
      /* RemoteTerminalChannelEvent.OnProcessExitEvent */
    );
  }
  get onProcessReady() {
    return this.b.listen(
      "$onProcessReadyEvent"
      /* RemoteTerminalChannelEvent.OnProcessReadyEvent */
    );
  }
  get onProcessReplay() {
    return this.b.listen(
      "$onProcessReplayEvent"
      /* RemoteTerminalChannelEvent.OnProcessReplayEvent */
    );
  }
  get onProcessOrphanQuestion() {
    return this.b.listen(
      "$onProcessOrphanQuestion"
      /* RemoteTerminalChannelEvent.OnProcessOrphanQuestion */
    );
  }
  get onExecuteCommand() {
    return this.b.listen(
      "$onExecuteCommand"
      /* RemoteTerminalChannelEvent.OnExecuteCommand */
    );
  }
  get onDidRequestDetach() {
    return this.b.listen(
      "$onDidRequestDetach"
      /* RemoteTerminalChannelEvent.OnDidRequestDetach */
    );
  }
  get onDidChangeProperty() {
    return this.b.listen(
      "$onDidChangeProperty"
      /* RemoteTerminalChannelEvent.OnDidChangeProperty */
    );
  }
  constructor(a, b, c, d, e, f, g, h3, i2, j) {
    this.a = a;
    this.b = b;
    this.c = c;
    this.d = d;
    this.e = e;
    this.f = f;
    this.g = g;
    this.h = h3;
    this.i = i2;
    this.j = j;
  }
  restartPtyHost() {
    return this.b.call("$restartPtyHost", []);
  }
  async createProcess(shellLaunchConfig, configuration2, activeWorkspaceRootUri, options3, shouldPersistTerminal, cols, rows, unicodeVersion) {
    await this.c.whenRemoteConfigurationLoaded();
    const resolvedVariables = /* @__PURE__ */ Object.create(null);
    const lastActiveWorkspace = activeWorkspaceRootUri ? this.d.getWorkspaceFolder(activeWorkspaceRootUri) ?? void 0 : void 0;
    let allResolvedVariables = void 0;
    try {
      allResolvedVariables = (await this.e.resolveAnyMap(lastActiveWorkspace, {
        shellLaunchConfig,
        configuration: configuration2
      })).resolvedVariables;
    } catch (err) {
      this.h.error(err);
    }
    if (allResolvedVariables) {
      for (const [name, value] of allResolvedVariables.entries()) {
        if (/^config:/.test(name) || name === "selectedText" || name === "lineNumber") {
          resolvedVariables[name] = value;
        }
      }
    }
    const envVariableCollections = [];
    for (const [k, v] of this.f.collections.entries()) {
      envVariableCollections.push([k, $BB(v.map), $CB(v.descriptionMap)]);
    }
    const resolverResult = await this.g.resolveAuthority(this.a);
    const resolverEnv = resolverResult.options && resolverResult.options.extensionHostEnv;
    const workspace2 = this.d.getWorkspace();
    const workspaceFolders = workspace2.folders;
    const activeWorkspaceFolder = activeWorkspaceRootUri ? this.d.getWorkspaceFolder(activeWorkspaceRootUri) : null;
    const activeFileResource = $mL.getOriginalUri(this.i.activeEditor, {
      supportSideBySide: SideBySideEditor.PRIMARY,
      filterByScheme: [Schemas.file, Schemas.vscodeUserData, Schemas.vscodeRemote]
    });
    const args2 = {
      configuration: configuration2,
      resolvedVariables,
      envVariableCollections,
      shellLaunchConfig,
      workspaceId: workspace2.id,
      workspaceName: this.j.getWorkspaceLabel(workspace2),
      workspaceFolders,
      activeWorkspaceFolder,
      activeFileResource,
      shouldPersistTerminal,
      options: options3,
      cols,
      rows,
      unicodeVersion,
      resolverEnv
    };
    return await this.b.call("$createProcess", args2);
  }
  requestDetachInstance(workspaceId, instanceId) {
    return this.b.call("$requestDetachInstance", [workspaceId, instanceId]);
  }
  acceptDetachInstanceReply(requestId, persistentProcessId) {
    return this.b.call("$acceptDetachInstanceReply", [requestId, persistentProcessId]);
  }
  attachToProcess(id2) {
    return this.b.call("$attachToProcess", [id2]);
  }
  detachFromProcess(id2, forcePersist) {
    return this.b.call("$detachFromProcess", [id2, forcePersist]);
  }
  listProcesses() {
    return this.b.call(
      "$listProcesses"
      /* RemoteTerminalChannelRequest.ListProcesses */
    );
  }
  getLatency() {
    return this.b.call(
      "$getLatency"
      /* RemoteTerminalChannelRequest.GetLatency */
    );
  }
  getPerformanceMarks() {
    return this.b.call(
      "$getPerformanceMarks"
      /* RemoteTerminalChannelRequest.GetPerformanceMarks */
    );
  }
  reduceConnectionGraceTime() {
    return this.b.call(
      "$reduceConnectionGraceTime"
      /* RemoteTerminalChannelRequest.ReduceConnectionGraceTime */
    );
  }
  processBinary(id2, data) {
    return this.b.call("$processBinary", [id2, data]);
  }
  start(id2) {
    return this.b.call("$start", [id2]);
  }
  input(id2, data) {
    return this.b.call("$input", [id2, data]);
  }
  acknowledgeDataEvent(id2, charCount) {
    return this.b.call("$acknowledgeDataEvent", [id2, charCount]);
  }
  setUnicodeVersion(id2, version2) {
    return this.b.call("$setUnicodeVersion", [id2, version2]);
  }
  shutdown(id2, immediate) {
    return this.b.call("$shutdown", [id2, immediate]);
  }
  resize(id2, cols, rows) {
    return this.b.call("$resize", [id2, cols, rows]);
  }
  clearBuffer(id2) {
    return this.b.call("$clearBuffer", [id2]);
  }
  getInitialCwd(id2) {
    return this.b.call("$getInitialCwd", [id2]);
  }
  getCwd(id2) {
    return this.b.call("$getCwd", [id2]);
  }
  orphanQuestionReply(id2) {
    return this.b.call("$orphanQuestionReply", [id2]);
  }
  sendCommandResult(reqId, isError, payload) {
    return this.b.call("$sendCommandResult", [reqId, isError, payload]);
  }
  freePortKillProcess(port) {
    return this.b.call("$freePortKillProcess", [port]);
  }
  getDefaultSystemShell(osOverride) {
    return this.b.call("$getDefaultSystemShell", [osOverride]);
  }
  getProfiles(profiles2, defaultProfile, includeDetectedProfiles) {
    return this.b.call("$getProfiles", [this.d.getWorkspace().id, profiles2, defaultProfile, includeDetectedProfiles]);
  }
  acceptPtyHostResolvedVariables(requestId, resolved) {
    return this.b.call("$acceptPtyHostResolvedVariables", [requestId, resolved]);
  }
  getEnvironment() {
    return this.b.call(
      "$getEnvironment"
      /* RemoteTerminalChannelRequest.GetEnvironment */
    );
  }
  getWslPath(original, direction) {
    return this.b.call("$getWslPath", [original, direction]);
  }
  setTerminalLayoutInfo(layout) {
    const workspace2 = this.d.getWorkspace();
    const args2 = {
      workspaceId: workspace2.id,
      tabs: layout ? layout.tabs : []
    };
    return this.b.call("$setTerminalLayoutInfo", args2);
  }
  updateTitle(id2, title, titleSource) {
    return this.b.call("$updateTitle", [id2, title, titleSource]);
  }
  updateIcon(id2, userInitiated, icon2, color2) {
    return this.b.call("$updateIcon", [id2, userInitiated, icon2, color2]);
  }
  refreshProperty(id2, property) {
    return this.b.call("$refreshProperty", [id2, property]);
  }
  updateProperty(id2, property, value) {
    return this.b.call("$updateProperty", [id2, property, value]);
  }
  getTerminalLayoutInfo() {
    const workspace2 = this.d.getWorkspace();
    const args2 = {
      workspaceId: workspace2.id
    };
    return this.b.call("$getTerminalLayoutInfo", args2);
  }
  reviveTerminalProcesses(workspaceId, state, dateTimeFormatLocate) {
    return this.b.call("$reviveTerminalProcesses", [workspaceId, state, dateTimeFormatLocate]);
  }
  getRevivedPtyNewId(id2) {
    return this.b.call("$getRevivedPtyNewId", [id2]);
  }
  serializeTerminalState(ids) {
    return this.b.call("$serializeTerminalState", [ids]);
  }
  // #region Pty service contribution RPC calls
  installAutoReply(match, reply) {
    return this.b.call("$installAutoReply", [match, reply]);
  }
  uninstallAllAutoReplies() {
    return this.b.call("$uninstallAllAutoReplies", []);
  }
};
$GY = __decorate([
  __param(2, $EK),
  __param(3, $Zk),
  __param(4, $nY),
  __param(5, $NX),
  __param(6, $bC),
  __param(7, $8x),
  __param(8, $mJ),
  __param(9, $ZI)
], $GY);

// out-build/vs/workbench/contrib/terminal/browser/remoteTerminalBackend.js
var $Jec = class $Jec2 {
  static {
    this.ID = "remoteTerminalBackend";
  }
  constructor(instantiationService, remoteAgentService, terminalInstanceService) {
    const connection = remoteAgentService.getConnection();
    if (connection?.remoteAuthority) {
      const channel = instantiationService.createInstance($GY, connection.remoteAuthority, connection.getChannel($FY));
      const backend = instantiationService.createInstance(RemoteTerminalBackend, connection.remoteAuthority, channel);
      $Wn.as($6x.Backend).registerTerminalBackend(backend);
      terminalInstanceService.didRegisterBackend(backend);
    }
  }
};
$Jec = __decorate([
  __param(0, $Pk),
  __param(1, $RL),
  __param(2, $8Pb)
], $Jec);
var RemoteTerminalBackend = class RemoteTerminalBackend2 extends $Gec {
  get whenReady() {
    return this.u.p;
  }
  setReady() {
    this.u.complete();
  }
  constructor(remoteAuthority, z, C, D, logService, F, G, H, workspaceContextService, configurationResolverService, I, J, statusBarService) {
    super(z, logService, I, configurationResolverService, statusBarService, workspaceContextService);
    this.remoteAuthority = remoteAuthority;
    this.z = z;
    this.C = C;
    this.D = D;
    this.F = F;
    this.G = G;
    this.H = H;
    this.I = I;
    this.J = J;
    this.r = /* @__PURE__ */ new Map();
    this.u = new $gi();
    this.w = this.B(new $ze());
    this.onDidRequestDetach = this.w.event;
    this.y = this.B(new $ze());
    this.onRestoreCommands = this.y.event;
    this.z.onProcessData((e) => this.r.get(e.id)?.handleData(e.event));
    this.z.onProcessReplay((e) => {
      this.r.get(e.id)?.handleReplay(e.event);
      if (e.event.commands.commands.length > 0) {
        this.y.fire({ id: e.id, commands: e.event.commands.commands });
      }
    });
    this.z.onProcessOrphanQuestion((e) => this.r.get(e.id)?.handleOrphanQuestion());
    this.z.onDidRequestDetach((e) => this.w.fire(e));
    this.z.onProcessReady((e) => this.r.get(e.id)?.handleReady(e.event));
    this.z.onDidChangeProperty((e) => this.r.get(e.id)?.handleDidChangeProperty(e.property));
    this.z.onProcessExit((e) => {
      const pty = this.r.get(e.id);
      if (pty) {
        pty.handleExit(e.event);
        this.r.delete(e.id);
      }
    });
    const allowedCommands = ["_remoteCLI.openExternal", "_remoteCLI.windowOpen", "_remoteCLI.getSystemStatus", "_remoteCLI.manageExtensions"];
    this.z.onExecuteCommand(async (e) => {
      const pty = this.r.get(e.persistentProcessId);
      if (!pty) {
        return;
      }
      const reqId = e.reqId;
      const commandId = e.commandId;
      if (!allowedCommands.includes(commandId)) {
        this.z.sendCommandResult(reqId, true, "Invalid remote cli command: " + commandId);
        return;
      }
      const commandArgs = e.commandArgs.map((arg) => $cu(arg));
      try {
        const result = await this.F.executeCommand(e.commandId, ...commandArgs);
        this.z.sendCommandResult(reqId, false, result);
      } catch (err) {
        this.z.sendCommandResult(reqId, true, err);
      }
    });
    this.b.fire();
  }
  async requestDetachInstance(workspaceId, instanceId) {
    if (!this.z) {
      throw new Error(`Cannot request detach instance when there is no remote!`);
    }
    return this.z.requestDetachInstance(workspaceId, instanceId);
  }
  async acceptDetachInstanceReply(requestId, persistentProcessId) {
    if (!this.z) {
      throw new Error(`Cannot accept detached instance when there is no remote!`);
    } else if (!persistentProcessId) {
      this.j.warn("Cannot attach to feature terminals, custom pty terminals, or those without a persistentProcessId");
      return;
    }
    return this.z.acceptDetachInstanceReply(requestId, persistentProcessId);
  }
  async persistTerminalState() {
    if (!this.z) {
      throw new Error(`Cannot persist terminal state when there is no remote!`);
    }
    const ids = Array.from(this.r.keys());
    const serialized = await this.z.serializeTerminalState(ids);
    this.G.store(
      "terminal.integrated.bufferState",
      serialized,
      1,
      1
      /* StorageTarget.MACHINE */
    );
  }
  async createProcess(shellLaunchConfig, cwd2, cols, rows, unicodeVersion, env3, options3, shouldPersist) {
    if (!this.z) {
      throw new Error(`Cannot create remote terminal when there is no remote!`);
    }
    const remoteEnv = await this.C.getEnvironment();
    if (!remoteEnv) {
      throw new Error("Could not fetch remote environment");
    }
    const terminalConfig = this.J.getValue($9X);
    const configuration2 = {
      "terminal.integrated.env.windows": this.J.getValue(
        "terminal.integrated.env.windows"
        /* TerminalSettingId.EnvWindows */
      ),
      "terminal.integrated.env.osx": this.J.getValue(
        "terminal.integrated.env.osx"
        /* TerminalSettingId.EnvMacOs */
      ),
      "terminal.integrated.env.linux": this.J.getValue(
        "terminal.integrated.env.linux"
        /* TerminalSettingId.EnvLinux */
      ),
      "terminal.integrated.cwd": this.J.getValue(
        "terminal.integrated.cwd"
        /* TerminalSettingId.Cwd */
      ),
      "terminal.integrated.detectLocale": terminalConfig.detectLocale
    };
    const shellLaunchConfigDto = {
      name: shellLaunchConfig.name,
      executable: shellLaunchConfig.executable,
      args: shellLaunchConfig.args,
      cwd: shellLaunchConfig.cwd,
      env: shellLaunchConfig.env,
      useShellEnvironment: shellLaunchConfig.useShellEnvironment,
      reconnectionProperties: shellLaunchConfig.reconnectionProperties,
      type: shellLaunchConfig.type,
      isFeatureTerminal: shellLaunchConfig.isFeatureTerminal
    };
    const activeWorkspaceRootUri = this.I.getLastActiveWorkspaceRoot();
    const result = await this.z.createProcess(shellLaunchConfigDto, configuration2, activeWorkspaceRootUri, options3, shouldPersist, cols, rows, unicodeVersion);
    const pty = this.D.createInstance($Iec, result.persistentTerminalId, shouldPersist, this.z);
    this.r.set(result.persistentTerminalId, pty);
    return pty;
  }
  async attachToProcess(id2) {
    if (!this.z) {
      throw new Error(`Cannot create remote terminal when there is no remote!`);
    }
    try {
      await this.z.attachToProcess(id2);
      const pty = this.D.createInstance($Iec, id2, true, this.z);
      this.r.set(id2, pty);
      return pty;
    } catch (e) {
      this.j.trace(`Couldn't attach to process ${e.message}`);
    }
    return void 0;
  }
  async attachToRevivedProcess(id2) {
    if (!this.z) {
      throw new Error(`Cannot create remote terminal when there is no remote!`);
    }
    try {
      const newId = await this.z.getRevivedPtyNewId(id2) ?? id2;
      return await this.attachToProcess(newId);
    } catch (e) {
      this.j.trace(`Couldn't attach to process ${e.message}`);
    }
    return void 0;
  }
  async listProcesses() {
    return this.z.listProcesses();
  }
  async getLatency() {
    const sw = new $te();
    const results = await this.z.getLatency();
    sw.stop();
    return [
      {
        label: "window<->ptyhostservice<->ptyhost",
        latency: sw.elapsed()
      },
      ...results
    ];
  }
  async updateProperty(id2, property, value) {
    await this.z.updateProperty(id2, property, value);
  }
  async updateTitle(id2, title, titleSource) {
    await this.z.updateTitle(id2, title, titleSource);
  }
  async updateIcon(id2, userInitiated, icon2, color2) {
    await this.z.updateIcon(id2, userInitiated, icon2, color2);
  }
  async getDefaultSystemShell(osOverride) {
    return this.z.getDefaultSystemShell(osOverride) || "";
  }
  async getProfiles(profiles2, defaultProfile, includeDetectedProfiles) {
    return this.z.getProfiles(profiles2, defaultProfile, includeDetectedProfiles) || [];
  }
  async getEnvironment() {
    return this.z.getEnvironment() || {};
  }
  async getShellEnvironment() {
    const connection = this.C.getConnection();
    if (!connection) {
      return void 0;
    }
    const resolverResult = await this.H.resolveAuthority(connection.remoteAuthority);
    return resolverResult.options?.extensionHostEnv;
  }
  async getWslPath(original, direction) {
    const env3 = await this.C.getEnvironment();
    if (env3?.os !== 1) {
      return original;
    }
    return this.z.getWslPath(original, direction) || original;
  }
  async setTerminalLayoutInfo(layout) {
    if (!this.z) {
      throw new Error(`Cannot call setActiveInstanceId when there is no remote`);
    }
    return this.z.setTerminalLayoutInfo(layout);
  }
  async reduceConnectionGraceTime() {
    if (!this.z) {
      throw new Error("Cannot reduce grace time when there is no remote");
    }
    return this.z.reduceConnectionGraceTime();
  }
  async getTerminalLayoutInfo() {
    if (!this.z) {
      throw new Error(`Cannot call getActiveInstanceId when there is no remote`);
    }
    const workspaceId = this.s();
    const serializedState = this.G.get(
      "terminal.integrated.bufferState",
      1
      /* StorageScope.WORKSPACE */
    );
    const reviveBufferState = this.n(serializedState);
    if (reviveBufferState && reviveBufferState.length > 0) {
      try {
        $S("code/terminal/willReviveTerminalProcessesRemote");
        await this.z.reviveTerminalProcesses(workspaceId, reviveBufferState, Intl.DateTimeFormat().resolvedOptions().locale);
        $S("code/terminal/didReviveTerminalProcessesRemote");
        this.G.remove(
          "terminal.integrated.bufferState",
          1
          /* StorageScope.WORKSPACE */
        );
        const layoutInfo = this.G.get(
          "terminal.integrated.layoutInfo",
          1
          /* StorageScope.WORKSPACE */
        );
        if (layoutInfo) {
          $S("code/terminal/willSetTerminalLayoutInfoRemote");
          await this.z.setTerminalLayoutInfo(JSON.parse(layoutInfo));
          $S("code/terminal/didSetTerminalLayoutInfoRemote");
          this.G.remove(
            "terminal.integrated.layoutInfo",
            1
            /* StorageScope.WORKSPACE */
          );
        }
      } catch (e) {
        this.j.warn("RemoteTerminalBackend#getTerminalLayoutInfo Error", e && typeof e === "object" && "message" in e ? e.message : e);
      }
    }
    return this.z.getTerminalLayoutInfo();
  }
  async getPerformanceMarks() {
    return this.z.getPerformanceMarks();
  }
  installAutoReply(match, reply) {
    return this.z.installAutoReply(match, reply);
  }
  uninstallAllAutoReplies() {
    return this.z.uninstallAllAutoReplies();
  }
};
RemoteTerminalBackend = __decorate([
  __param(2, $RL),
  __param(3, $Pk),
  __param(4, $8x),
  __param(5, $sn),
  __param(6, $jv),
  __param(7, $bC),
  __param(8, $Zk),
  __param(9, $nY),
  __param(10, $tY),
  __param(11, $kl),
  __param(12, $$qb)
], RemoteTerminalBackend);

// out-build/vs/workbench/contrib/terminal/common/terminalStrings.js
var $Kec = {
  terminal: localize(10776, null),
  new: localize(10777, null),
  doNotShowAgain: localize(10778, null),
  currentSessionCategory: localize(10779, null),
  previousSessionCategory: localize(10780, null),
  typeTask: localize(10781, null),
  typeLocal: localize(10782, null),
  actionCategory: localize2(10785, "Terminal"),
  focus: localize2(10786, "Focus Terminal"),
  focusAndHideAccessibleBuffer: localize2(10787, "Focus Terminal and Hide Accessible Buffer"),
  kill: {
    ...localize2(10788, "Kill Terminal"),
    short: localize(10783, null)
  },
  moveToEditor: localize2(10789, "Move Terminal into Editor Area"),
  moveIntoNewWindow: localize2(10790, "Move Terminal into New Window"),
  moveToTerminalPanel: localize2(10791, "Move Terminal into Panel"),
  changeIcon: localize2(10792, "Change Icon..."),
  changeColor: localize2(10793, "Change Color..."),
  split: {
    ...localize2(10794, "Split Terminal"),
    short: localize(10784, null)
  },
  unsplit: localize2(10795, "Unsplit Terminal"),
  rename: localize2(10796, "Rename..."),
  toggleSizeToContentWidth: localize2(10797, "Toggle Size to Content Width"),
  focusHover: localize2(10798, "Focus Hover"),
  sendSequence: localize2(10799, "Send Custom Sequence To Terminal"),
  newWithCwd: localize2(10800, "Create New Terminal Starting in a Custom Working Directory"),
  renameWithArgs: localize2(10801, "Rename the Currently Active Terminal"),
  scrollToPreviousCommand: localize2(10802, "Scroll To Previous Command"),
  scrollToNextCommand: localize2(10803, "Scroll To Next Command")
};

// out-build/vs/workbench/services/configurationResolver/common/variableResolver.js
var $DY = class _$DY {
  static {
    this.VARIABLE_LHS = "${";
  }
  static {
    this.VARIABLE_REGEXP = /\$\{(.*?)\}/g;
  }
  constructor(_context, _labelService, _userHomePromise, _envVariablesPromise) {
    this.h = /* @__PURE__ */ new Map();
    this.a = _context;
    this.b = _labelService;
    this.g = _userHomePromise;
    if (_envVariablesPromise) {
      this.c = _envVariablesPromise.then((envVariables) => {
        return this.i(envVariables);
      });
    }
  }
  i(envVariables) {
    if ($l) {
      const ev = /* @__PURE__ */ Object.create(null);
      Object.keys(envVariables).forEach((key2) => {
        ev[key2.toLowerCase()] = envVariables[key2];
      });
      return ev;
    }
    return envVariables;
  }
  resolveWithEnvironment(environment, root, value) {
    return this.l({ env: this.i(environment), userHome: void 0 }, root ? root.uri : void 0, value);
  }
  async resolveAsync(root, value) {
    const environment = {
      env: await this.c,
      userHome: await this.g
    };
    return this.l(environment, root ? root.uri : void 0, value);
  }
  async j(workspaceFolder, config, commandValueMapping, resolvedVariables) {
    const result = $Lv(config);
    if ($l && result.windows) {
      Object.keys(result.windows).forEach((key2) => result[key2] = result.windows[key2]);
    } else if ($m && result.osx) {
      Object.keys(result.osx).forEach((key2) => result[key2] = result.osx[key2]);
    } else if ($n && result.linux) {
      Object.keys(result.linux).forEach((key2) => result[key2] = result.linux[key2]);
    }
    delete result.windows;
    delete result.osx;
    delete result.linux;
    const environmentPromises = {
      env: await this.c,
      userHome: await this.g
    };
    return this.l(environmentPromises, workspaceFolder ? workspaceFolder.uri : void 0, result, commandValueMapping, resolvedVariables);
  }
  async resolveAnyAsync(workspaceFolder, config, commandValueMapping) {
    return this.j(workspaceFolder, config, commandValueMapping);
  }
  async resolveAnyMap(workspaceFolder, config, commandValueMapping) {
    const resolvedVariables = /* @__PURE__ */ new Map();
    const newConfig = await this.j(workspaceFolder, config, commandValueMapping, resolvedVariables);
    return { newConfig, resolvedVariables };
  }
  resolveWithInteractionReplace(folder, config, section, variables) {
    throw new Error("resolveWithInteractionReplace not implemented.");
  }
  resolveWithInteraction(folder, config, section, variables) {
    throw new Error("resolveWithInteraction not implemented.");
  }
  contributeVariable(variable, resolution) {
    if (this.h.has(variable)) {
      throw new Error("Variable " + variable + " is contributed twice.");
    } else {
      this.h.set(variable, resolution);
    }
  }
  async l(environment, folderUri, value, commandValueMapping, resolvedVariables) {
    if ($zg(value)) {
      return this.m(environment, folderUri, value, commandValueMapping, resolvedVariables);
    } else if (Array.isArray(value)) {
      return Promise.all(value.map((s) => this.l(environment, folderUri, s, commandValueMapping, resolvedVariables)));
    } else if ($Bg(value)) {
      const result = /* @__PURE__ */ Object.create(null);
      const replaced = await Promise.all(Object.keys(value).map(async (key2) => {
        const replaced2 = await this.m(environment, folderUri, key2, commandValueMapping, resolvedVariables);
        return [replaced2, await this.l(environment, folderUri, value[key2], commandValueMapping, resolvedVariables)];
      }));
      for (const [key2, value2] of replaced) {
        result[key2] = value2;
      }
      return result;
    }
    return value;
  }
  m(environment, folderUri, value, commandValueMapping, resolvedVariables) {
    return $Sf(value, _$DY.VARIABLE_REGEXP, async (match, variable) => {
      if (variable.includes(_$DY.VARIABLE_LHS)) {
        return match;
      }
      let resolvedValue = await this.o(environment, match, variable, folderUri, commandValueMapping);
      resolvedVariables?.set(variable, resolvedValue);
      if (resolvedValue !== match && $zg(resolvedValue) && resolvedValue.match(_$DY.VARIABLE_REGEXP)) {
        resolvedValue = await this.m(environment, folderUri, resolvedValue, commandValueMapping, resolvedVariables);
      }
      return resolvedValue;
    });
  }
  n(displayUri) {
    return this.b ? this.b.getUriLabel(displayUri, { noPrefix: true }) : displayUri.fsPath;
  }
  async o(environment, match, variable, folderUri, commandValueMapping) {
    let argument;
    const parts = variable.split(":");
    if (parts.length > 1) {
      variable = parts[0];
      argument = parts[1];
    }
    const getFilePath = (variableKind) => {
      const filePath = this.a.getFilePath();
      if (filePath) {
        return $1t(filePath);
      }
      throw new $oY(variableKind, localize(12635, null, match));
    };
    const getFolderPathForFile = (variableKind) => {
      const filePath = getFilePath(variableKind);
      if (this.a.getWorkspaceFolderPathForFile) {
        const folderPath = this.a.getWorkspaceFolderPathForFile();
        if (folderPath) {
          return $1t(folderPath);
        }
      }
      throw new $oY(variableKind, localize(12636, null, match, $rc(filePath)));
    };
    const getFolderUri = (variableKind) => {
      if (argument) {
        const folder = this.a.getFolderUri(argument);
        if (folder) {
          return folder;
        }
        throw new $oY(variableKind, localize(12637, null, match, argument));
      }
      if (folderUri) {
        return folderUri;
      }
      if (this.a.getWorkspaceFolderCount() > 1) {
        throw new $oY(variableKind, localize(12638, null, match));
      }
      throw new $oY(variableKind, localize(12639, null, match));
    };
    switch (variable) {
      case "env":
        if (argument) {
          if (environment.env) {
            const env3 = environment.env[$l ? argument.toLowerCase() : argument];
            if ($zg(env3)) {
              return env3;
            }
          }
          return "";
        }
        throw new $oY(VariableKind.Env, localize(12640, null, match));
      case "config":
        if (argument) {
          const config = this.a.getConfigurationValue(folderUri, argument);
          if ($Ig(config)) {
            throw new $oY(VariableKind.Config, localize(12641, null, match, argument));
          }
          if ($Bg(config)) {
            throw new $oY(VariableKind.Config, localize(12642, null, match, argument));
          }
          return config;
        }
        throw new $oY(VariableKind.Config, localize(12643, null, match));
      case "command":
        return this.p(VariableKind.Command, match, argument, commandValueMapping, "command");
      case "input":
        return this.p(VariableKind.Input, match, argument, commandValueMapping, "input");
      case "extensionInstallFolder":
        if (argument) {
          const ext = await this.a.getExtension(argument);
          if (!ext) {
            throw new $oY(VariableKind.ExtensionInstallFolder, localize(12644, null, match, argument));
          }
          return this.n(ext.extensionLocation);
        }
        throw new $oY(VariableKind.ExtensionInstallFolder, localize(12645, null, match));
      default: {
        switch (variable) {
          case "workspaceRoot":
          case "workspaceFolder":
            return $1t(this.n(getFolderUri(VariableKind.WorkspaceFolder)));
          case "cwd":
            return folderUri || argument ? $1t(this.n(getFolderUri(VariableKind.Cwd))) : cwd();
          case "workspaceRootFolderName":
          case "workspaceFolderBasename":
            return $1t($rc(this.n(getFolderUri(VariableKind.WorkspaceFolderBasename))));
          case "userHome": {
            if (environment.userHome) {
              return environment.userHome;
            }
            throw new $oY(VariableKind.UserHome, localize(12646, null, match));
          }
          case "lineNumber": {
            const lineNumber = this.a.getLineNumber();
            if (lineNumber) {
              return lineNumber;
            }
            throw new $oY(VariableKind.LineNumber, localize(12647, null, match));
          }
          case "selectedText": {
            const selectedText = this.a.getSelectedText();
            if (selectedText) {
              return selectedText;
            }
            throw new $oY(VariableKind.SelectedText, localize(12648, null, match));
          }
          case "file":
            return getFilePath(VariableKind.File);
          case "fileWorkspaceFolder":
            return getFolderPathForFile(VariableKind.FileWorkspaceFolder);
          case "fileWorkspaceFolderBasename":
            return $rc(getFolderPathForFile(VariableKind.FileWorkspaceFolderBasename));
          case "relativeFile":
            if (folderUri || argument) {
              return $pc(this.n(getFolderUri(VariableKind.RelativeFile)), getFilePath(VariableKind.RelativeFile));
            }
            return getFilePath(VariableKind.RelativeFile);
          case "relativeFileDirname": {
            const dirname = $qc(getFilePath(VariableKind.RelativeFileDirname));
            if (folderUri || argument) {
              const relative = $pc(this.n(getFolderUri(VariableKind.RelativeFileDirname)), dirname);
              return relative.length === 0 ? "." : relative;
            }
            return dirname;
          }
          case "fileDirname":
            return $qc(getFilePath(VariableKind.FileDirname));
          case "fileExtname":
            return $sc(getFilePath(VariableKind.FileExtname));
          case "fileBasename":
            return $rc(getFilePath(VariableKind.FileBasename));
          case "fileBasenameNoExtension": {
            const basename = $rc(getFilePath(VariableKind.FileBasenameNoExtension));
            return basename.slice(0, basename.length - $sc(basename).length);
          }
          case "fileDirnameBasename":
            return $rc($qc(getFilePath(VariableKind.FileDirnameBasename)));
          case "execPath": {
            const ep = this.a.getExecPath();
            if (ep) {
              return ep;
            }
            return match;
          }
          case "execInstallFolder": {
            const ar = this.a.getAppRoot();
            if (ar) {
              return ar;
            }
            return match;
          }
          case "pathSeparator":
          case "/":
            return sep;
          default:
            try {
              const key2 = argument ? `${variable}:${argument}` : variable;
              return this.p(VariableKind.Unknown, match, key2, commandValueMapping, void 0);
            } catch (error) {
              return match;
            }
        }
      }
    }
  }
  p(variableKind, match, argument, commandValueMapping, prefix) {
    if (argument && commandValueMapping) {
      const v = prefix === void 0 ? commandValueMapping[argument] : commandValueMapping[prefix + ":" + argument];
      if (typeof v === "string") {
        return v;
      }
      throw new $oY(variableKind, localize(12649, null, match));
    }
    return match;
  }
};

// out-build/vs/workbench/contrib/terminal/browser/terminalContextMenu.js
var $Mec = class {
  constructor(instance2) {
    this.instanceId = instance2.instanceId;
  }
  toJSON() {
    return {
      $mid: 15,
      instanceId: this.instanceId
    };
  }
};
var $Nec = class extends $Vm {
  // eslint-disable-next-line @typescript-eslint/naming-convention
  async u(action, context) {
    if (Array.isArray(context) && context.every((e) => e instanceof $Mec)) {
      await action.run(context?.[0], context);
      return;
    }
    return super.u(action, context);
  }
};
function $Oec(targetWindow, event, contextInstances, menu, contextMenuService, extraActions) {
  const standardEvent = new $lf(targetWindow, event);
  const actions = $P$(menu.getActions({ shouldForwardArgs: true }));
  if (extraActions) {
    actions.push(...extraActions);
  }
  const context = contextInstances ? $5b(contextInstances).map((e) => new $Mec(e)) : [];
  contextMenuService.showContextMenu({
    actionRunner: new $Nec(),
    getAnchor: () => standardEvent,
    getActions: () => actions,
    getActionsContext: () => context
  });
}

// out-build/vs/workbench/contrib/terminal/browser/terminalActions.js
var $Pec = "\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500";
var $Qec = localize(10380, null);
var category4 = $Kec.actionCategory;
var sharedWhenClause = (() => {
  const terminalAvailable = $7m.or(TerminalContextKeys.processSupported, TerminalContextKeys.terminalHasBeenCreated);
  return {
    terminalAvailable,
    terminalAvailable_and_opened: $7m.and(terminalAvailable, TerminalContextKeys.isOpen),
    terminalAvailable_and_editorActive: $7m.and(terminalAvailable, TerminalContextKeys.terminalEditorActive),
    terminalAvailable_and_singularSelection: $7m.and(terminalAvailable, TerminalContextKeys.tabsSingularSelection),
    focusInAny_and_normalBuffer: $7m.and(TerminalContextKeys.focusInAny, TerminalContextKeys.altBufferActive.negate())
  };
})();
async function $Rec(instance2, folders, commandService, configService) {
  switch (configService.config.splitCwd) {
    case "workspaceRoot":
      if (folders !== void 0 && commandService !== void 0) {
        if (folders.length === 1) {
          return folders[0].uri;
        } else if (folders.length > 1) {
          const options3 = {
            placeHolder: localize(10381, null)
          };
          const workspace2 = await commandService.executeCommand($Wyb, [options3]);
          if (!workspace2) {
            return void 0;
          }
          return Promise.resolve(workspace2.uri);
        }
      }
      return "";
    case "initial":
      return instance2.getInitialCwd();
    case "inherited":
      return instance2.getCwd();
  }
}
var $Sec = async (accessor, args2) => {
  const instance2 = accessor.get($4Pb).activeInstance;
  if (instance2) {
    const text2 = $Bg(args2) && "text" in args2 ? toOptionalString(args2.text) : void 0;
    if (!text2) {
      return;
    }
    const configurationResolverService = accessor.get($nY);
    const workspaceContextService = accessor.get($Zk);
    const historyService = accessor.get($tY);
    const activeWorkspaceRootUri = historyService.getLastActiveWorkspaceRoot(instance2.isRemote ? Schemas.vscodeRemote : Schemas.file);
    const lastActiveWorkspaceRoot = activeWorkspaceRootUri ? workspaceContextService.getWorkspaceFolder(activeWorkspaceRootUri) ?? void 0 : void 0;
    const resolvedText = await configurationResolverService.resolveAsync(lastActiveWorkspaceRoot, text2);
    instance2.sendText(resolvedText, false);
  }
};
var $Tec = class $Tec2 extends $Um {
  constructor(a) {
    super("workbench.action.terminal.launchHelp", localize(10382, null));
    this.a = a;
  }
  async run() {
    this.a.open("https://aka.ms/vscode-troubleshoot-terminal-launch");
  }
};
$Tec = __decorate([
  __param(0, $O4)
], $Tec);
function $Uec(options3) {
  options3.f1 = options3.f1 ?? true;
  options3.category = options3.category ?? category4;
  options3.precondition = options3.precondition ?? TerminalContextKeys.processSupported;
  const runFunc = options3.run;
  const strictOptions = options3;
  delete strictOptions["run"];
  return $hJ(class extends $gJ {
    constructor() {
      super(strictOptions);
    }
    run(accessor, args2, args22) {
      return runFunc(getTerminalServices(accessor), accessor, args2, args22);
    }
  });
}
function parseActionArgs(args2) {
  if (Array.isArray(args2)) {
    if (args2.every((e) => e instanceof $Mec)) {
      return args2;
    }
  } else if (args2 instanceof $Mec) {
    return [args2];
  }
  return void 0;
}
function $Vec(options3) {
  const originalRun = options3.run;
  return $Uec({
    ...options3,
    run: async (c, accessor, focusedInstanceArgs, allInstanceArgs) => {
      let instances = getSelectedInstances2(accessor, allInstanceArgs);
      if (!instances) {
        const activeInstance = (options3.activeInstanceType === "view" ? c.groupService : options3.activeInstanceType === "editor" ? c.editorService : c.service).activeInstance;
        if (!activeInstance) {
          return;
        }
        instances = [activeInstance];
      }
      const results = [];
      for (const instance2 of instances) {
        results.push(originalRun(instance2, c, accessor, focusedInstanceArgs));
      }
      await Promise.all(results);
      if (options3.runAfter) {
        options3.runAfter(instances, c, accessor, focusedInstanceArgs);
      }
    }
  });
}
function $Wec(options3) {
  const originalRun = options3.run;
  return $Uec({
    ...options3,
    run: (c, accessor, args2) => {
      const activeInstance = c.service.activeInstance;
      if (activeInstance) {
        return originalRun(activeInstance, c, accessor, args2);
      }
    }
  });
}
function $Xec(options3) {
  const originalRun = options3.run;
  return $Uec({
    ...options3,
    run: (c, accessor, args2) => {
      const activeDetached = Iterable.find(c.service.detachedInstances, (d) => d.xterm.isFocused);
      if (activeDetached) {
        return originalRun(activeDetached.xterm, accessor, activeDetached, args2);
      }
      const activeInstance = c.service.activeInstance;
      if (activeInstance?.xterm) {
        return originalRun(activeInstance.xterm, accessor, activeInstance, args2);
      }
    }
  });
}
function getTerminalServices(accessor) {
  return {
    service: accessor.get($4Pb),
    configService: accessor.get($5Pb),
    groupService: accessor.get($7Pb),
    instanceService: accessor.get($8Pb),
    editorService: accessor.get($6Pb),
    profileService: accessor.get($hY),
    profileResolverService: accessor.get($fY)
  };
}
function $Yec() {
  $Uec({
    id: "workbench.action.terminal.newInActiveWorkspace",
    title: localize2(10400, "Create New Terminal (In Active Workspace)"),
    run: async (c) => {
      if (c.service.isProcessSupportRegistered) {
        const instance2 = await c.service.createTerminal({ location: c.service.defaultLocation });
        if (!instance2) {
          return;
        }
        c.service.setActiveInstance(instance2);
      }
      await c.groupService.showPanel(true);
    }
  });
  $1ec([]);
  $Uec({
    id: "workbench.action.createTerminalEditor",
    title: localize2(10401, "Create New Terminal in Editor Area"),
    run: async (c, _, args2) => {
      const options3 = $Bg(args2) && "location" in args2 ? args2 : { location: TerminalLocation2.Editor };
      const instance2 = await c.service.createTerminal(options3);
      await instance2.focusWhenReady();
    }
  });
  $Uec({
    id: "workbench.action.createTerminalEditorSameGroup",
    title: localize2(10402, "Create New Terminal in Editor Area"),
    f1: false,
    run: async (c, accessor, args2) => {
      const editorGroupsService = accessor.get($iJ);
      const instance2 = await c.service.createTerminal({
        location: { viewColumn: $AS(editorGroupsService, editorGroupsService.activeGroup) }
      });
      await instance2.focusWhenReady();
    }
  });
  $Uec({
    id: "workbench.action.createTerminalEditorSide",
    title: localize2(10403, "Create New Terminal in Editor Area to the Side"),
    run: async (c) => {
      const instance2 = await c.service.createTerminal({
        location: { viewColumn: $oJ }
      });
      await instance2.focusWhenReady();
    }
  });
  $Vec({
    id: "workbench.action.terminal.moveToEditor",
    title: $Kec.moveToEditor,
    precondition: sharedWhenClause.terminalAvailable_and_opened,
    activeInstanceType: "view",
    run: (instance2, c) => c.service.moveToEditor(instance2),
    runAfter: (instances) => instances.at(-1)?.focus()
  });
  $Vec({
    id: "workbench.action.terminal.moveIntoNewWindow",
    title: $Kec.moveIntoNewWindow,
    precondition: sharedWhenClause.terminalAvailable_and_opened,
    run: (instance2, c) => c.service.moveIntoNewEditor(instance2),
    runAfter: (instances) => instances.at(-1)?.focus()
  });
  $Uec({
    id: "workbench.action.terminal.moveToTerminalPanel",
    title: $Kec.moveToTerminalPanel,
    precondition: sharedWhenClause.terminalAvailable_and_editorActive,
    run: (c, _, args2) => {
      const source = toOptionalUri(args2) ?? c.editorService.activeInstance;
      if (source) {
        c.service.moveToTerminalView(source);
      }
    }
  });
  $Uec({
    id: "workbench.action.terminal.focusPreviousPane",
    title: localize2(10404, "Focus Previous Terminal in Terminal Group"),
    keybinding: {
      primary: 512 | 15,
      secondary: [
        512 | 16
        /* KeyCode.UpArrow */
      ],
      mac: {
        primary: 512 | 2048 | 15,
        secondary: [
          512 | 2048 | 16
          /* KeyCode.UpArrow */
        ]
      },
      when: TerminalContextKeys.focus,
      weight: 200
      /* KeybindingWeight.WorkbenchContrib */
    },
    precondition: sharedWhenClause.terminalAvailable,
    run: async (c) => {
      c.groupService.activeGroup?.focusPreviousPane();
      await c.groupService.showPanel(true);
    }
  });
  $Uec({
    id: "workbench.action.terminal.focusNextPane",
    title: localize2(10405, "Focus Next Terminal in Terminal Group"),
    keybinding: {
      primary: 512 | 17,
      secondary: [
        512 | 18
        /* KeyCode.DownArrow */
      ],
      mac: {
        primary: 512 | 2048 | 17,
        secondary: [
          512 | 2048 | 18
          /* KeyCode.DownArrow */
        ]
      },
      when: TerminalContextKeys.focus,
      weight: 200
      /* KeybindingWeight.WorkbenchContrib */
    },
    precondition: sharedWhenClause.terminalAvailable,
    run: async (c) => {
      c.groupService.activeGroup?.focusNextPane();
      await c.groupService.showPanel(true);
    }
  });
  $Uec({
    id: "workbench.action.terminal.resizePaneLeft",
    title: localize2(10406, "Resize Terminal Left"),
    keybinding: {
      linux: {
        primary: 2048 | 1024 | 15
        /* KeyCode.LeftArrow */
      },
      mac: {
        primary: 2048 | 256 | 15
        /* KeyCode.LeftArrow */
      },
      when: TerminalContextKeys.focus,
      weight: 200
      /* KeybindingWeight.WorkbenchContrib */
    },
    precondition: sharedWhenClause.terminalAvailable,
    run: (c) => c.groupService.activeGroup?.resizePane(
      0
      /* Direction.Left */
    )
  });
  $Uec({
    id: "workbench.action.terminal.resizePaneRight",
    title: localize2(10407, "Resize Terminal Right"),
    keybinding: {
      linux: {
        primary: 2048 | 1024 | 17
        /* KeyCode.RightArrow */
      },
      mac: {
        primary: 2048 | 256 | 17
        /* KeyCode.RightArrow */
      },
      when: TerminalContextKeys.focus,
      weight: 200
      /* KeybindingWeight.WorkbenchContrib */
    },
    precondition: sharedWhenClause.terminalAvailable,
    run: (c) => c.groupService.activeGroup?.resizePane(
      1
      /* Direction.Right */
    )
  });
  $Uec({
    id: "workbench.action.terminal.resizePaneUp",
    title: localize2(10408, "Resize Terminal Up"),
    keybinding: {
      mac: {
        primary: 2048 | 256 | 16
        /* KeyCode.UpArrow */
      },
      when: TerminalContextKeys.focus,
      weight: 200
      /* KeybindingWeight.WorkbenchContrib */
    },
    precondition: sharedWhenClause.terminalAvailable,
    run: (c) => c.groupService.activeGroup?.resizePane(
      2
      /* Direction.Up */
    )
  });
  $Uec({
    id: "workbench.action.terminal.resizePaneDown",
    title: localize2(10409, "Resize Terminal Down"),
    keybinding: {
      mac: {
        primary: 2048 | 256 | 18
        /* KeyCode.DownArrow */
      },
      when: TerminalContextKeys.focus,
      weight: 200
      /* KeybindingWeight.WorkbenchContrib */
    },
    precondition: sharedWhenClause.terminalAvailable,
    run: (c) => c.groupService.activeGroup?.resizePane(
      3
      /* Direction.Down */
    )
  });
  $Uec({
    id: "workbench.action.terminal.focus",
    title: $Kec.focus,
    keybinding: {
      when: $7m.and($OD, $ssb, $tsb.isEqualTo(
        "terminal"
        /* AccessibleViewProviderId.Terminal */
      )),
      primary: 2048 | 18,
      weight: 200
      /* KeybindingWeight.WorkbenchContrib */
    },
    precondition: sharedWhenClause.terminalAvailable,
    run: async (c) => {
      const instance2 = c.service.activeInstance || await c.service.createTerminal({ location: TerminalLocation2.Panel });
      if (!instance2) {
        return;
      }
      c.service.setActiveInstance(instance2);
      focusActiveTerminal(instance2, c);
    }
  });
  $Uec({
    id: "workbench.action.terminal.focusTabs",
    title: localize2(10410, "Focus Terminal Tabs View"),
    keybinding: {
      primary: 2048 | 1024 | 93,
      weight: 200,
      when: $7m.or(TerminalContextKeys.tabsFocus, TerminalContextKeys.focus)
    },
    precondition: sharedWhenClause.terminalAvailable,
    run: (c) => c.groupService.focusTabs()
  });
  $Uec({
    id: "workbench.action.terminal.focusNext",
    title: localize2(10411, "Focus Next Terminal Group"),
    precondition: sharedWhenClause.terminalAvailable,
    keybinding: {
      primary: 2048 | 12,
      mac: {
        primary: 2048 | 1024 | 94
        /* KeyCode.BracketRight */
      },
      when: $7m.and(TerminalContextKeys.focus, TerminalContextKeys.editorFocus.negate()),
      weight: 200
      /* KeybindingWeight.WorkbenchContrib */
    },
    run: async (c) => {
      c.groupService.setActiveGroupToNext();
      await c.groupService.showPanel(true);
    }
  });
  $Uec({
    id: "workbench.action.terminal.focusPrevious",
    title: localize2(10412, "Focus Previous Terminal Group"),
    precondition: sharedWhenClause.terminalAvailable,
    keybinding: {
      primary: 2048 | 11,
      mac: {
        primary: 2048 | 1024 | 92
        /* KeyCode.BracketLeft */
      },
      when: $7m.and(TerminalContextKeys.focus, TerminalContextKeys.editorFocus.negate()),
      weight: 200
      /* KeybindingWeight.WorkbenchContrib */
    },
    run: async (c) => {
      c.groupService.setActiveGroupToPrevious();
      await c.groupService.showPanel(true);
    }
  });
  $Uec({
    id: "workbench.action.terminal.runSelectedText",
    title: localize2(10413, "Run Selected Text In Active Terminal"),
    run: async (c, accessor) => {
      const codeEditorService = accessor.get($U5);
      const editor = codeEditorService.getActiveCodeEditor();
      if (!editor || !editor.hasModel()) {
        return;
      }
      const instance2 = await c.service.getActiveOrCreateInstance({ acceptsInput: true });
      const selection = editor.getSelection();
      let text2;
      if (selection.isEmpty()) {
        text2 = editor.getModel().getLineContent(selection.selectionStartLineNumber).trim();
      } else {
        const endOfLinePreference = $l ? 1 : 2;
        text2 = editor.getModel().getValueInRange(selection, endOfLinePreference);
      }
      instance2.sendText(text2, true, true);
      await c.service.revealActiveTerminal(true);
    }
  });
  $Uec({
    id: "workbench.action.terminal.runActiveFile",
    title: localize2(10414, "Run Active File In Active Terminal"),
    precondition: sharedWhenClause.terminalAvailable,
    run: async (c, accessor) => {
      const codeEditorService = accessor.get($U5);
      const notificationService = accessor.get($PJ);
      const workbenchEnvironmentService = accessor.get($US);
      const editor = codeEditorService.getActiveCodeEditor();
      if (!editor || !editor.hasModel()) {
        return;
      }
      const instance2 = await c.service.getActiveOrCreateInstance({ acceptsInput: true });
      const isRemote = instance2 ? instance2.isRemote : workbenchEnvironmentService.remoteAuthority ? true : false;
      const uri = editor.getModel().uri;
      if (!isRemote && uri.scheme !== Schemas.file && uri.scheme !== Schemas.vscodeUserData || isRemote && uri.scheme !== Schemas.vscodeRemote) {
        notificationService.warn(localize(10383, null));
        return;
      }
      await instance2.sendPath(uri, true);
      return c.groupService.showPanel();
    }
  });
  $Xec({
    id: "workbench.action.terminal.scrollDown",
    title: localize2(10415, "Scroll Down (Line)"),
    keybinding: {
      primary: 2048 | 512 | 12,
      linux: {
        primary: 2048 | 1024 | 18
        /* KeyCode.DownArrow */
      },
      when: sharedWhenClause.focusInAny_and_normalBuffer,
      weight: 200
      /* KeybindingWeight.WorkbenchContrib */
    },
    precondition: sharedWhenClause.terminalAvailable,
    run: (xterm) => xterm.scrollDownLine()
  });
  $Xec({
    id: "workbench.action.terminal.scrollDownPage",
    title: localize2(10416, "Scroll Down (Page)"),
    keybinding: {
      primary: 1024 | 12,
      mac: {
        primary: 12
        /* KeyCode.PageDown */
      },
      when: sharedWhenClause.focusInAny_and_normalBuffer,
      weight: 200
      /* KeybindingWeight.WorkbenchContrib */
    },
    precondition: sharedWhenClause.terminalAvailable,
    run: (xterm) => xterm.scrollDownPage()
  });
  $Xec({
    id: "workbench.action.terminal.scrollToBottom",
    title: localize2(10417, "Scroll to Bottom"),
    keybinding: {
      primary: 2048 | 13,
      linux: {
        primary: 1024 | 13
        /* KeyCode.End */
      },
      when: sharedWhenClause.focusInAny_and_normalBuffer,
      weight: 200
      /* KeybindingWeight.WorkbenchContrib */
    },
    precondition: sharedWhenClause.terminalAvailable,
    run: (xterm) => xterm.scrollToBottom()
  });
  $Xec({
    id: "workbench.action.terminal.scrollUp",
    title: localize2(10418, "Scroll Up (Line)"),
    keybinding: {
      primary: 2048 | 512 | 11,
      linux: {
        primary: 2048 | 1024 | 16
        /* KeyCode.UpArrow */
      },
      when: sharedWhenClause.focusInAny_and_normalBuffer,
      weight: 200
      /* KeybindingWeight.WorkbenchContrib */
    },
    precondition: sharedWhenClause.terminalAvailable,
    run: (xterm) => xterm.scrollUpLine()
  });
  $Xec({
    id: "workbench.action.terminal.scrollUpPage",
    title: localize2(10419, "Scroll Up (Page)"),
    f1: true,
    keybinding: {
      primary: 1024 | 11,
      mac: {
        primary: 11
        /* KeyCode.PageUp */
      },
      when: sharedWhenClause.focusInAny_and_normalBuffer,
      weight: 200
      /* KeybindingWeight.WorkbenchContrib */
    },
    precondition: sharedWhenClause.terminalAvailable,
    run: (xterm) => xterm.scrollUpPage()
  });
  $Xec({
    id: "workbench.action.terminal.scrollToTop",
    title: localize2(10420, "Scroll to Top"),
    keybinding: {
      primary: 2048 | 14,
      linux: {
        primary: 1024 | 14
        /* KeyCode.Home */
      },
      when: sharedWhenClause.focusInAny_and_normalBuffer,
      weight: 200
      /* KeybindingWeight.WorkbenchContrib */
    },
    precondition: sharedWhenClause.terminalAvailable,
    run: (xterm) => xterm.scrollToTop()
  });
  $Xec({
    id: "workbench.action.terminal.clearSelection",
    title: localize2(10421, "Clear Selection"),
    keybinding: {
      primary: 9,
      when: $7m.and(TerminalContextKeys.focusInAny, TerminalContextKeys.textSelected, TerminalContextKeys.notFindVisible),
      weight: 200
      /* KeybindingWeight.WorkbenchContrib */
    },
    precondition: sharedWhenClause.terminalAvailable,
    run: (xterm) => {
      if (xterm.hasSelection()) {
        xterm.clearSelection();
      }
    }
  });
  $Uec({
    id: "workbench.action.terminal.changeIcon",
    title: $Kec.changeIcon,
    precondition: sharedWhenClause.terminalAvailable,
    run: (c, _, args2) => getResourceOrActiveInstance(c, args2)?.changeIcon()
  });
  $Uec({
    id: "workbench.action.terminal.changeIconActiveTab",
    title: $Kec.changeIcon,
    f1: false,
    precondition: sharedWhenClause.terminalAvailable_and_singularSelection,
    run: async (c, accessor, args2) => {
      let icon2;
      if (c.groupService.lastAccessedMenu === "inline-tab") {
        getResourceOrActiveInstance(c, args2)?.changeIcon();
        return;
      }
      for (const terminal2 of getSelectedInstances(accessor) ?? []) {
        icon2 = await terminal2.changeIcon(icon2);
      }
    }
  });
  $Uec({
    id: "workbench.action.terminal.changeColor",
    title: $Kec.changeColor,
    precondition: sharedWhenClause.terminalAvailable,
    run: (c, _, args2) => getResourceOrActiveInstance(c, args2)?.changeColor()
  });
  $Uec({
    id: "workbench.action.terminal.changeColorActiveTab",
    title: $Kec.changeColor,
    f1: false,
    precondition: sharedWhenClause.terminalAvailable_and_singularSelection,
    run: async (c, accessor, args2) => {
      let color2;
      let i2 = 0;
      if (c.groupService.lastAccessedMenu === "inline-tab") {
        getResourceOrActiveInstance(c, args2)?.changeColor();
        return;
      }
      for (const terminal2 of getSelectedInstances(accessor) ?? []) {
        const skipQuickPick = i2 !== 0;
        color2 = await terminal2.changeColor(color2, skipQuickPick);
        i2++;
      }
    }
  });
  $Uec({
    id: "workbench.action.terminal.rename",
    title: $Kec.rename,
    precondition: sharedWhenClause.terminalAvailable,
    run: (c, accessor, args2) => renameWithQuickPick(c, accessor, args2)
  });
  $Uec({
    id: "workbench.action.terminal.renameActiveTab",
    title: $Kec.rename,
    f1: false,
    keybinding: {
      primary: 60,
      mac: {
        primary: 3
        /* KeyCode.Enter */
      },
      when: $7m.and(TerminalContextKeys.tabsFocus),
      weight: 200
      /* KeybindingWeight.WorkbenchContrib */
    },
    precondition: sharedWhenClause.terminalAvailable_and_singularSelection,
    run: async (c, accessor) => {
      const terminalGroupService = accessor.get($7Pb);
      const notificationService = accessor.get($PJ);
      const instances = getSelectedInstances(accessor);
      const firstInstance = instances?.[0];
      if (!firstInstance) {
        return;
      }
      if (terminalGroupService.lastAccessedMenu === "inline-tab") {
        return renameWithQuickPick(c, accessor, firstInstance);
      }
      c.service.setEditingTerminal(firstInstance);
      c.service.setEditable(firstInstance, {
        validationMessage: (value) => $Zec(value),
        onFinish: async (value, success) => {
          c.service.setEditable(firstInstance, null);
          c.service.setEditingTerminal(void 0);
          if (success) {
            const promises = [];
            for (const instance2 of instances) {
              promises.push((async () => {
                await instance2.rename(value);
              })());
            }
            try {
              await Promise.all(promises);
            } catch (e) {
              notificationService.error(e);
            }
          }
        }
      });
    }
  });
  $Wec({
    id: "workbench.action.terminal.detachSession",
    title: localize2(10422, "Detach Session"),
    run: (activeInstance) => activeInstance.detachProcessAndDispose(TerminalExitReason2.User)
  });
  $Uec({
    id: "workbench.action.terminal.attachToSession",
    title: localize2(10423, "Attach to Session"),
    run: async (c, accessor) => {
      const quickInputService = accessor.get($1M);
      const labelService = accessor.get($ZI);
      const remoteAgentService = accessor.get($RL);
      const notificationService = accessor.get($PJ);
      const remoteAuthority = remoteAgentService.getConnection()?.remoteAuthority ?? void 0;
      const backend = await accessor.get($8Pb).getBackend(remoteAuthority);
      if (!backend) {
        throw new Error(`No backend registered for remote authority '${remoteAuthority}'`);
      }
      const terms = await backend.listProcesses();
      backend.reduceConnectionGraceTime();
      const unattachedTerms = terms.filter((term) => !c.service.isAttachedToTerminal(term));
      const items = unattachedTerms.map((term) => {
        const cwdLabel = labelService.getUriLabel(URI.file(term.cwd));
        return {
          label: term.title,
          detail: term.workspaceName ? `${term.workspaceName} \u2E31 ${cwdLabel}` : cwdLabel,
          description: term.pid ? String(term.pid) : "",
          term
        };
      });
      if (items.length === 0) {
        notificationService.info(localize(10384, null));
        return;
      }
      const selected = await quickInputService.pick(items, { canPickMany: false });
      if (selected) {
        const instance2 = await c.service.createTerminal({
          config: { attachPersistentProcess: selected.term }
        });
        c.service.setActiveInstance(instance2);
        await focusActiveTerminal(instance2, c);
      }
    }
  });
  $Wec({
    id: "workbench.action.terminal.scrollToPreviousCommand",
    title: $Kec.scrollToPreviousCommand,
    keybinding: {
      primary: 2048 | 16,
      when: $7m.and(TerminalContextKeys.focus, $OD.negate()),
      weight: 200
      /* KeybindingWeight.WorkbenchContrib */
    },
    precondition: sharedWhenClause.terminalAvailable,
    icon: $6l.arrowUp,
    menu: [
      {
        id: $bJ.ViewTitle,
        group: "navigation",
        order: 4,
        when: $7m.equals("view", $7X),
        isHiddenByDefault: true
      }
    ],
    run: (activeInstance) => activeInstance.xterm?.markTracker.scrollToPreviousMark(void 0, void 0, activeInstance.capabilities.has(
      2
      /* TerminalCapability.CommandDetection */
    ))
  });
  $Wec({
    id: "workbench.action.terminal.scrollToNextCommand",
    title: $Kec.scrollToNextCommand,
    keybinding: {
      primary: 2048 | 18,
      when: $7m.and(TerminalContextKeys.focus, $OD.negate()),
      weight: 200
      /* KeybindingWeight.WorkbenchContrib */
    },
    precondition: sharedWhenClause.terminalAvailable,
    icon: $6l.arrowDown,
    menu: [
      {
        id: $bJ.ViewTitle,
        group: "navigation",
        order: 4,
        when: $7m.equals("view", $7X),
        isHiddenByDefault: true
      }
    ],
    run: (activeInstance) => {
      activeInstance.xterm?.markTracker.scrollToNextMark();
      activeInstance.focus();
    }
  });
  $Wec({
    id: "workbench.action.terminal.selectToPreviousCommand",
    title: localize2(10424, "Select To Previous Command"),
    keybinding: {
      primary: 2048 | 1024 | 16,
      when: TerminalContextKeys.focus,
      weight: 200
      /* KeybindingWeight.WorkbenchContrib */
    },
    precondition: sharedWhenClause.terminalAvailable,
    run: (activeInstance) => {
      activeInstance.xterm?.markTracker.selectToPreviousMark();
      activeInstance.focus();
    }
  });
  $Wec({
    id: "workbench.action.terminal.selectToNextCommand",
    title: localize2(10425, "Select To Next Command"),
    keybinding: {
      primary: 2048 | 1024 | 18,
      when: TerminalContextKeys.focus,
      weight: 200
      /* KeybindingWeight.WorkbenchContrib */
    },
    precondition: sharedWhenClause.terminalAvailable,
    run: (activeInstance) => {
      activeInstance.xterm?.markTracker.selectToNextMark();
      activeInstance.focus();
    }
  });
  $Xec({
    id: "workbench.action.terminal.selectToPreviousLine",
    title: localize2(10426, "Select To Previous Line"),
    precondition: sharedWhenClause.terminalAvailable,
    run: async (xterm, _, instance2) => {
      xterm.markTracker.selectToPreviousLine();
      (instance2 || xterm).focus();
    }
  });
  $Xec({
    id: "workbench.action.terminal.selectToNextLine",
    title: localize2(10427, "Select To Next Line"),
    precondition: sharedWhenClause.terminalAvailable,
    run: async (xterm, _, instance2) => {
      xterm.markTracker.selectToNextLine();
      (instance2 || xterm).focus();
    }
  });
  $Uec({
    id: "workbench.action.terminal.sendSequence",
    title: $Kec.sendSequence,
    f1: false,
    metadata: {
      description: $Kec.sendSequence.value,
      args: [{
        name: "args",
        schema: {
          type: "object",
          required: ["text"],
          properties: {
            text: {
              description: localize(10385, null),
              type: "string"
            }
          }
        }
      }]
    },
    run: (c, accessor, args2) => $Sec(accessor, args2)
  });
  $Uec({
    id: "workbench.action.terminal.newWithCwd",
    title: $Kec.newWithCwd,
    metadata: {
      description: $Kec.newWithCwd.value,
      args: [{
        name: "args",
        schema: {
          type: "object",
          required: ["cwd"],
          properties: {
            cwd: {
              description: localize(10386, null),
              type: "string"
            }
          }
        }
      }]
    },
    run: async (c, _, args2) => {
      const cwd2 = $Bg(args2) && "cwd" in args2 ? toOptionalString(args2.cwd) : void 0;
      const instance2 = await c.service.createTerminal({ cwd: cwd2 });
      if (!instance2) {
        return;
      }
      c.service.setActiveInstance(instance2);
      await focusActiveTerminal(instance2, c);
    }
  });
  $Wec({
    id: "workbench.action.terminal.renameWithArg",
    title: $Kec.renameWithArgs,
    metadata: {
      description: $Kec.renameWithArgs.value,
      args: [{
        name: "args",
        schema: {
          type: "object",
          required: ["name"],
          properties: {
            name: {
              description: localize(10387, null),
              type: "string",
              minLength: 1
            }
          }
        }
      }]
    },
    precondition: sharedWhenClause.terminalAvailable,
    run: async (activeInstance, c, accessor, args2) => {
      const notificationService = accessor.get($PJ);
      const name = $Bg(args2) && "name" in args2 ? toOptionalString(args2.name) : void 0;
      if (!name) {
        notificationService.warn(localize(10388, null));
        return;
      }
      activeInstance.rename(name);
    }
  });
  $Wec({
    id: "workbench.action.terminal.relaunch",
    title: localize2(10428, "Relaunch Active Terminal"),
    run: (activeInstance) => activeInstance.relaunch()
  });
  $Uec({
    id: "workbench.action.terminal.split",
    title: $Kec.split,
    precondition: $7m.or(TerminalContextKeys.processSupported, TerminalContextKeys.webExtensionContributedProfile),
    keybinding: {
      primary: 2048 | 1024 | 26,
      weight: 200,
      mac: {
        primary: 2048 | 93,
        secondary: [
          256 | 1024 | 26
          /* KeyCode.Digit5 */
        ]
      },
      when: TerminalContextKeys.focus
    },
    icon: $6l.splitHorizontal,
    run: async (c, accessor, args2) => {
      const optionsOrProfile = $Bg(args2) ? args2 : void 0;
      const commandService = accessor.get($sn);
      const workspaceContextService = accessor.get($Zk);
      const options3 = convertOptionsOrProfileToOptions(optionsOrProfile);
      const activeInstance = (await c.service.getInstanceHost(options3?.location)).activeInstance;
      if (!activeInstance) {
        return;
      }
      const cwd2 = await $Rec(activeInstance, workspaceContextService.getWorkspace().folders, commandService, c.configService);
      if (cwd2 === void 0) {
        return;
      }
      const instance2 = await c.service.createTerminal({ location: { parentTerminal: activeInstance }, config: options3?.config, cwd: cwd2 });
      await focusActiveTerminal(instance2, c);
    }
  });
  $Uec({
    id: "workbench.action.terminal.splitActiveTab",
    title: $Kec.split,
    f1: false,
    keybinding: {
      primary: 2048 | 1024 | 26,
      mac: {
        primary: 2048 | 93,
        secondary: [
          256 | 1024 | 26
          /* KeyCode.Digit5 */
        ]
      },
      weight: 200,
      when: TerminalContextKeys.tabsFocus
    },
    run: async (c, accessor) => {
      const instances = getSelectedInstances(accessor);
      if (instances) {
        const promises = [];
        for (const t of instances) {
          promises.push((async () => {
            await c.service.createTerminal({ location: { parentTerminal: t } });
            await c.groupService.showPanel(true);
          })());
        }
        await Promise.all(promises);
      }
    }
  });
  $Vec({
    id: "workbench.action.terminal.unsplit",
    title: $Kec.unsplit,
    precondition: sharedWhenClause.terminalAvailable,
    run: async (instance2, c) => {
      const group2 = c.groupService.getGroupForInstance(instance2);
      if (group2 && group2?.terminalInstances.length > 1) {
        c.groupService.unsplitInstance(instance2);
      }
    }
  });
  $Uec({
    id: "workbench.action.terminal.joinActiveTab",
    title: localize2(10429, "Join Terminals"),
    precondition: $7m.and(sharedWhenClause.terminalAvailable, TerminalContextKeys.tabsSingularSelection.toNegated()),
    run: async (c, accessor) => {
      const instances = getSelectedInstances(accessor);
      if (instances && instances.length > 1) {
        c.groupService.joinInstances(instances);
      }
    }
  });
  $Uec({
    id: "workbench.action.terminal.join",
    title: localize2(10430, "Join Terminals..."),
    precondition: sharedWhenClause.terminalAvailable,
    run: async (c, accessor) => {
      const themeService = accessor.get($gs);
      const notificationService = accessor.get($PJ);
      const quickInputService = accessor.get($1M);
      const picks = [];
      if (c.groupService.instances.length <= 1) {
        notificationService.warn(localize(10389, null));
        return;
      }
      const otherInstances = c.groupService.instances.filter((i2) => i2.instanceId !== c.groupService.activeInstance?.instanceId);
      for (const terminal2 of otherInstances) {
        const group2 = c.groupService.getGroupForInstance(terminal2);
        if (group2?.terminalInstances.length === 1) {
          const iconId = $eQb(accessor, terminal2);
          const label3 = `$(${iconId}): ${terminal2.title}`;
          const iconClasses = [];
          const colorClass = $_Pb(terminal2);
          if (colorClass) {
            iconClasses.push(colorClass);
          }
          const uriClasses = $dQb(terminal2, themeService.getColorTheme().type);
          if (uriClasses) {
            iconClasses.push(...uriClasses);
          }
          picks.push({
            terminal: terminal2,
            label: label3,
            iconClasses
          });
        }
      }
      if (picks.length === 0) {
        notificationService.warn(localize(10390, null));
        return;
      }
      const result = await quickInputService.pick(picks, {});
      if (result) {
        c.groupService.joinInstances([result.terminal, c.groupService.activeInstance]);
      }
    }
  });
  $Wec({
    id: "workbench.action.terminal.splitInActiveWorkspace",
    title: localize2(10431, "Split Terminal (In Active Workspace)"),
    run: async (instance2, c) => {
      const newInstance = await c.service.createTerminal({ location: { parentTerminal: instance2 } });
      if (newInstance?.target !== TerminalLocation2.Editor) {
        await c.groupService.showPanel(true);
      }
    }
  });
  $Xec({
    id: "workbench.action.terminal.selectAll",
    title: localize2(10432, "Select All"),
    precondition: sharedWhenClause.terminalAvailable,
    keybinding: [{
      // Don't use ctrl+a by default as that would override the common go to start
      // of prompt shell binding
      primary: 0,
      // Technically this doesn't need to be here as it will fall back to this
      // behavior anyway when handed to xterm.js, having this handled by VS Code
      // makes it easier for users to see how it works though.
      mac: {
        primary: 2048 | 31
        /* KeyCode.KeyA */
      },
      weight: 200,
      when: TerminalContextKeys.focusInAny
    }],
    run: (xterm) => xterm.selectAll()
  });
  $Uec({
    id: "workbench.action.terminal.new",
    title: localize2(10433, "Create New Terminal"),
    precondition: $7m.or(TerminalContextKeys.processSupported, TerminalContextKeys.webExtensionContributedProfile),
    icon: $NPb,
    keybinding: {
      primary: 2048 | 1024 | 91,
      mac: {
        primary: 256 | 1024 | 91
        /* KeyCode.Backquote */
      },
      weight: 200
      /* KeybindingWeight.WorkbenchContrib */
    },
    run: async (c, accessor, args2) => {
      let eventOrOptions = $Bg(args2) ? args2 : void 0;
      const workspaceContextService = accessor.get($Zk);
      const commandService = accessor.get($sn);
      const folders = workspaceContextService.getWorkspace().folders;
      if (eventOrOptions && $3j(eventOrOptions) && (eventOrOptions.altKey || eventOrOptions.ctrlKey)) {
        await c.service.createTerminal({ location: { splitActiveTerminal: true } });
        return;
      }
      if (c.service.isProcessSupportRegistered) {
        eventOrOptions = !eventOrOptions || $3j(eventOrOptions) ? {} : eventOrOptions;
        let instance2;
        if (folders.length <= 1) {
          instance2 = await c.service.createTerminal(eventOrOptions);
        } else {
          const cwd2 = (await pickTerminalCwd(accessor))?.cwd;
          if (!cwd2) {
            return;
          }
          eventOrOptions.cwd = cwd2;
          instance2 = await c.service.createTerminal(eventOrOptions);
        }
        c.service.setActiveInstance(instance2);
        await focusActiveTerminal(instance2, c);
      } else {
        if (c.profileService.contributedProfiles.length > 0) {
          commandService.executeCommand(
            "workbench.action.terminal.newWithProfile"
            /* TerminalCommandId.NewWithProfile */
          );
        } else {
          commandService.executeCommand(
            "workbench.action.terminal.toggleTerminal"
            /* TerminalCommandId.Toggle */
          );
        }
      }
    }
  });
  async function killInstance(c, instance2) {
    if (!instance2) {
      return;
    }
    await c.service.safeDisposeTerminal(instance2);
    if (c.groupService.instances.length > 0) {
      await c.groupService.showPanel(true);
    }
  }
  $Uec({
    id: "workbench.action.terminal.kill",
    title: localize2(10434, "Kill the Active Terminal Instance"),
    precondition: $7m.or(sharedWhenClause.terminalAvailable, TerminalContextKeys.isOpen),
    icon: $MPb,
    run: async (c) => killInstance(c, c.groupService.activeInstance)
  });
  $Uec({
    id: "workbench.action.terminal.killViewOrEditor",
    title: $Kec.kill,
    f1: false,
    // This is an internal command used for context menus
    precondition: $7m.or(sharedWhenClause.terminalAvailable, TerminalContextKeys.isOpen),
    run: async (c) => killInstance(c, c.service.activeInstance)
  });
  $Uec({
    id: "workbench.action.terminal.killAll",
    title: localize2(10435, "Kill All Terminals"),
    precondition: $7m.or(sharedWhenClause.terminalAvailable, TerminalContextKeys.isOpen),
    icon: $6l.trash,
    run: async (c) => {
      const disposePromises = [];
      for (const instance2 of c.service.instances) {
        disposePromises.push(c.service.safeDisposeTerminal(instance2));
      }
      await Promise.all(disposePromises);
    }
  });
  $Uec({
    id: "workbench.action.terminal.killEditor",
    title: localize2(10436, "Kill the Active Terminal in Editor Area"),
    precondition: sharedWhenClause.terminalAvailable,
    keybinding: {
      primary: 2048 | 53,
      win: { primary: 2048 | 62, secondary: [
        2048 | 53
        /* KeyCode.KeyW */
      ] },
      weight: 200,
      when: $7m.and(TerminalContextKeys.focus, TerminalContextKeys.editorFocus)
    },
    run: (c, accessor) => accessor.get($sn).executeCommand($xub)
  });
  $Uec({
    id: "workbench.action.terminal.killActiveTab",
    title: $Kec.kill,
    f1: false,
    precondition: $7m.or(sharedWhenClause.terminalAvailable, TerminalContextKeys.isOpen),
    keybinding: {
      primary: 20,
      mac: {
        primary: 2048 | 1,
        secondary: [
          20
          /* KeyCode.Delete */
        ]
      },
      weight: 200,
      when: TerminalContextKeys.tabsFocus
    },
    run: async (c, accessor) => {
      const disposePromises = [];
      for (const terminal2 of getSelectedInstances(accessor, true) ?? []) {
        disposePromises.push(c.service.safeDisposeTerminal(terminal2));
      }
      await Promise.all(disposePromises);
      c.groupService.focusTabs();
    }
  });
  $Uec({
    id: "workbench.action.terminal.focusHover",
    title: $Kec.focusHover,
    precondition: $7m.or(sharedWhenClause.terminalAvailable, TerminalContextKeys.isOpen),
    keybinding: {
      primary: $$e(
        2048 | 41,
        2048 | 39
        /* KeyCode.KeyI */
      ),
      weight: 200,
      when: $7m.or(TerminalContextKeys.tabsFocus, TerminalContextKeys.focus)
    },
    run: (c) => c.groupService.focusHover()
  });
  $Wec({
    id: "workbench.action.terminal.clear",
    title: localize2(10437, "Clear"),
    precondition: sharedWhenClause.terminalAvailable,
    keybinding: [{
      primary: 0,
      mac: {
        primary: 2048 | 41
        /* KeyCode.KeyK */
      },
      // Weight is higher than work workbench contributions so the keybinding remains
      // highest priority when chords are registered afterwards
      weight: 200 + 1,
      // Disable the keybinding when accessibility mode is enabled as chords include
      // important screen reader keybindings such as cmd+k, cmd+i to show the hover
      when: $7m.or($7m.and(TerminalContextKeys.focus, $OD.negate()), $7m.and($OD, $osb, $tsb.isEqualTo(
        "terminal"
        /* AccessibleViewProviderId.Terminal */
      )))
    }],
    run: (activeInstance) => activeInstance.clearBuffer()
  });
  $Uec({
    id: "workbench.action.terminal.selectDefaultShell",
    title: localize2(10438, "Select Default Profile"),
    run: (c) => c.service.showProfileQuickPick("setDefault")
  });
  $Uec({
    id: "workbench.action.terminal.openSettings",
    title: localize2(10439, "Configure Terminal Settings"),
    precondition: sharedWhenClause.terminalAvailable,
    run: (c, accessor) => accessor.get($TK).openSettings({ jsonEditor: false, query: "@feature:terminal" })
  });
  $Wec({
    id: "workbench.action.terminal.setDimensions",
    title: localize2(10440, "Set Fixed Dimensions"),
    precondition: sharedWhenClause.terminalAvailable_and_opened,
    run: (activeInstance) => activeInstance.setFixedDimensions()
  });
  $Vec({
    id: "workbench.action.terminal.sizeToContentWidth",
    title: $Kec.toggleSizeToContentWidth,
    precondition: sharedWhenClause.terminalAvailable_and_opened,
    keybinding: {
      primary: 512 | 56,
      weight: 200,
      when: TerminalContextKeys.focus
    },
    run: (instance2) => instance2.toggleSizeToContentWidth()
  });
  $Uec({
    id: "workbench.action.terminal.switchTerminal",
    title: localize2(10441, "Switch Terminal"),
    precondition: sharedWhenClause.terminalAvailable,
    run: async (c, accessor, args2) => {
      const item = toOptionalString(args2);
      if (!item) {
        return;
      }
      if (item === $Pec) {
        c.service.refreshActiveGroup();
        return;
      }
      if (item === $Qec) {
        accessor.get($kl).updateValue("terminal.integrated.tabs.enabled", true);
        return;
      }
      const terminalIndexRe = /^([0-9]+): /;
      const indexMatches = terminalIndexRe.exec(item);
      if (indexMatches) {
        c.groupService.setActiveGroupByIndex(Number(indexMatches[1]) - 1);
        return c.groupService.showPanel(true);
      }
      const quickSelectProfiles = c.profileService.availableProfiles;
      const profileSelection = item.substring(4);
      if (quickSelectProfiles) {
        const profile = quickSelectProfiles.find((profile2) => profile2.profileName === profileSelection);
        if (profile) {
          const instance2 = await c.service.createTerminal({
            config: profile
          });
          c.service.setActiveInstance(instance2);
        } else {
          console.warn(`No profile with name "${profileSelection}"`);
        }
      } else {
        console.warn(`Unmatched terminal item: "${item}"`);
      }
    }
  });
}
function getSelectedInstances2(accessor, args2) {
  const terminalService = accessor.get($4Pb);
  const result = [];
  const context = parseActionArgs(args2);
  if (context && context.length > 0) {
    for (const instanceContext of context) {
      const instance2 = terminalService.getInstanceFromId(instanceContext.instanceId);
      if (instance2) {
        result.push(instance2);
      }
    }
    if (result.length > 0) {
      return result;
    }
  }
  return void 0;
}
function getSelectedInstances(accessor, args2, args22) {
  const listService = accessor.get($Deb);
  const terminalService = accessor.get($4Pb);
  const terminalGroupService = accessor.get($7Pb);
  const result = [];
  const list2 = listService.lastFocusedList;
  const selections = list2?.getSelection();
  if (terminalGroupService.lastAccessedMenu === "inline-tab" && !selections?.length) {
    const instance2 = terminalGroupService.activeInstance;
    return instance2 ? [terminalGroupService.activeInstance] : void 0;
  }
  if (!list2 || !selections) {
    return void 0;
  }
  const focused = list2.getFocus();
  if (focused.length === 1 && !selections.includes(focused[0])) {
    result.push(terminalService.getInstanceFromIndex(focused[0]));
    return result;
  }
  for (const selection of selections) {
    result.push(terminalService.getInstanceFromIndex(selection));
  }
  return result.filter((r2) => !!r2);
}
function $Zec(name) {
  if (!name || name.trim().length === 0) {
    return {
      content: localize(10391, null),
      severity: Severity2.Info
    };
  }
  return null;
}
function convertOptionsOrProfileToOptions(optionsOrProfile) {
  if ($Bg(optionsOrProfile) && "profileName" in optionsOrProfile) {
    return { config: optionsOrProfile, location: optionsOrProfile.location };
  }
  return optionsOrProfile;
}
var newWithProfileAction;
function $1ec(detectedProfiles) {
  const profileEnum = $tB(detectedProfiles);
  newWithProfileAction?.dispose();
  newWithProfileAction = $hJ(class extends $gJ {
    constructor() {
      super({
        id: "workbench.action.terminal.newWithProfile",
        title: localize2(10442, "Create New Terminal (With Profile)"),
        f1: true,
        precondition: $7m.or(TerminalContextKeys.processSupported, TerminalContextKeys.webExtensionContributedProfile),
        metadata: {
          description: "workbench.action.terminal.newWithProfile",
          args: [{
            name: "args",
            schema: {
              type: "object",
              required: ["profileName"],
              properties: {
                profileName: {
                  description: localize(10392, null),
                  type: "string",
                  enum: profileEnum.values,
                  markdownEnumDescriptions: profileEnum.markdownDescriptions
                },
                location: {
                  description: localize(10393, null),
                  type: "string",
                  enum: ["view", "editor"],
                  enumDescriptions: [
                    localize(10394, null),
                    localize(10395, null)
                  ]
                }
              }
            }
          }]
        }
      });
    }
    async run(accessor, eventOrOptionsOrProfile, profile) {
      const c = getTerminalServices(accessor);
      const workspaceContextService = accessor.get($Zk);
      const commandService = accessor.get($sn);
      let event;
      let options3;
      let instance2;
      let cwd2;
      if ($Bg(eventOrOptionsOrProfile) && eventOrOptionsOrProfile && "profileName" in eventOrOptionsOrProfile) {
        const config = c.profileService.availableProfiles.find((profile2) => profile2.profileName === eventOrOptionsOrProfile.profileName);
        if (!config) {
          throw new Error(`Could not find terminal profile "${eventOrOptionsOrProfile.profileName}"`);
        }
        options3 = { config };
        if ("location" in eventOrOptionsOrProfile) {
          switch (eventOrOptionsOrProfile.location) {
            case "editor":
              options3.location = TerminalLocation2.Editor;
              break;
            case "view":
              options3.location = TerminalLocation2.Panel;
              break;
          }
        }
      } else if ($3j(eventOrOptionsOrProfile) || $5j(eventOrOptionsOrProfile) || $4j(eventOrOptionsOrProfile)) {
        event = eventOrOptionsOrProfile;
        options3 = profile ? { config: profile } : void 0;
      } else {
        options3 = convertOptionsOrProfileToOptions(eventOrOptionsOrProfile);
      }
      if (event && (event.altKey || event.ctrlKey)) {
        const parentTerminal = c.service.activeInstance;
        if (parentTerminal) {
          await c.service.createTerminal({ location: { parentTerminal }, config: options3?.config });
          return;
        }
      }
      const folders = workspaceContextService.getWorkspace().folders;
      if (folders.length > 1) {
        const options4 = {
          placeHolder: localize(10396, null)
        };
        const workspace2 = await commandService.executeCommand($Wyb, [options4]);
        if (!workspace2) {
          return;
        }
        cwd2 = workspace2.uri;
      }
      if (options3) {
        options3.cwd = cwd2;
        instance2 = await c.service.createTerminal(options3);
      } else {
        instance2 = await c.service.showProfileQuickPick("createInstance", cwd2);
      }
      if (instance2) {
        c.service.setActiveInstance(instance2);
        await focusActiveTerminal(instance2, c);
      }
    }
  });
  return newWithProfileAction;
}
function getResourceOrActiveInstance(c, resource) {
  return c.service.getInstanceFromResource(toOptionalUri(resource)) || c.service.activeInstance;
}
async function pickTerminalCwd(accessor, cancel) {
  const quickInputService = accessor.get($1M);
  const labelService = accessor.get($ZI);
  const contextService = accessor.get($Zk);
  const modelService = accessor.get($sG);
  const languageService = accessor.get($1E);
  const configurationService = accessor.get($kl);
  const configurationResolverService = accessor.get($nY);
  const folders = contextService.getWorkspace().folders;
  if (!folders.length) {
    return;
  }
  const folderCwdPairs = await Promise.all(folders.map((e) => resolveWorkspaceFolderCwd(e, configurationService, configurationResolverService)));
  const shrinkedPairs = $2ec(folderCwdPairs);
  if (shrinkedPairs.length === 1) {
    return shrinkedPairs[0];
  }
  const folderPicks = shrinkedPairs.map((pair) => {
    const label3 = pair.folder.name;
    const description = pair.isOverridden ? localize(10397, null, labelService.getUriLabel(pair.cwd, { relative: !pair.isAbsolute })) : labelService.getUriLabel($uh(pair.cwd), { relative: true });
    return {
      label: label3,
      description: description !== label3 ? description : void 0,
      pair,
      iconClasses: $gdb(modelService, languageService, pair.cwd, FileKind.ROOT_FOLDER)
    };
  });
  const options3 = {
    placeHolder: localize(10398, null),
    matchOnDescription: true,
    canPickMany: false
  };
  const token = cancel || CancellationToken.None;
  const pick = await quickInputService.pick(folderPicks, options3, token);
  return pick?.pair;
}
async function resolveWorkspaceFolderCwd(folder, configurationService, configurationResolverService) {
  const cwdConfig = configurationService.getValue("terminal.integrated.cwd", { resource: folder.uri });
  if (!$zg(cwdConfig) || cwdConfig.length === 0) {
    return { folder, cwd: folder.uri, isAbsolute: false, isOverridden: false };
  }
  const resolvedCwdConfig = await configurationResolverService.resolveAsync(folder, cwdConfig);
  return $mc(resolvedCwdConfig) || resolvedCwdConfig.startsWith($DY.VARIABLE_LHS) ? { folder, isAbsolute: true, isOverridden: true, cwd: URI.from({ ...folder.uri, path: resolvedCwdConfig }) } : { folder, isAbsolute: false, isOverridden: true, cwd: URI.joinPath(folder.uri, resolvedCwdConfig) };
}
function $2ec(pairs) {
  const map = /* @__PURE__ */ new Map();
  for (const pair of pairs) {
    const key2 = pair.cwd.toString();
    const value = map.get(key2);
    if (!value || key2 === pair.folder.uri.toString()) {
      map.set(key2, pair);
    }
  }
  const selectedPairs = new Set(map.values());
  const selectedPairsInOrder = pairs.filter((x) => selectedPairs.has(x));
  return selectedPairsInOrder;
}
async function focusActiveTerminal(instance2, c) {
  if (instance2.target === TerminalLocation2.Editor) {
    await c.editorService.revealActiveEditor();
    await instance2.focusWhenReady(true);
  } else {
    await c.groupService.showPanel(true);
  }
}
async function renameWithQuickPick(c, accessor, resource) {
  let instance2 = resource;
  if (!instance2 || !instance2?.rename) {
    instance2 = getResourceOrActiveInstance(c, resource);
  }
  if (instance2) {
    const title = await accessor.get($1M).input({
      value: instance2.title,
      prompt: localize(10399, null)
    });
    instance2.rename(title);
  }
}
function toOptionalUri(obj) {
  return URI.isUri(obj) ? obj : void 0;
}
function toOptionalString(obj) {
  return $zg(obj) ? obj : void 0;
}

// out-build/vs/workbench/contrib/terminal/browser/terminalCommands.js
function $3ec() {
  registerOpenTerminalAtIndexCommands();
}
function registerOpenTerminalAtIndexCommands() {
  for (let i2 = 0; i2 < 9; i2++) {
    const terminalIndex = i2;
    const visibleIndex = i2 + 1;
    $0I.registerCommandAndKeybindingRule({
      id: `workbench.action.terminal.focusAtIndex${visibleIndex}`,
      weight: 200,
      when: void 0,
      primary: 0,
      handler: (accessor) => {
        accessor.get($7Pb).setActiveInstanceByIndex(terminalIndex);
        return accessor.get($7Pb).showPanel(true);
      }
    });
  }
}

// out-build/vs/workbench/contrib/terminal/browser/terminalConfigurationService.js
var $4ec = class $4ec2 extends $3c {
  get config() {
    return this.b;
  }
  get onConfigChanged() {
    return this.f.event;
  }
  constructor(g) {
    super();
    this.g = g;
    this.f = new $ze();
    this.a = this.B(new $5ec(this, this.g));
    this.B(Event2.runAndSubscribe(this.g.onDidChangeConfiguration, (e) => {
      if (!e || e.affectsConfiguration($9X)) {
        this.h();
      }
    }));
  }
  setPanelContainer(panelContainer) {
    return this.a.setPanelContainer(panelContainer);
  }
  configFontIsMonospace() {
    return this.a.configFontIsMonospace();
  }
  getFont(w, xtermCore, excludeDimensions) {
    return this.a.getFont(w, xtermCore, excludeDimensions);
  }
  h() {
    const configValues = { ...this.g.getValue($9X) };
    configValues.fontWeight = this.j(configValues.fontWeight, $cY);
    configValues.fontWeightBold = this.j(configValues.fontWeightBold, $dY);
    this.b = configValues;
    this.f.fire();
  }
  j(input, defaultWeight) {
    if (input === "normal" || input === "bold") {
      return input;
    }
    return clampInt(input, $aY, $bY, defaultWeight);
  }
};
$4ec = __decorate([
  __param(0, $kl)
], $4ec);
var FontConstants;
(function(FontConstants2) {
  FontConstants2[FontConstants2["MinimumFontSize"] = 6] = "MinimumFontSize";
  FontConstants2[FontConstants2["MaximumFontSize"] = 100] = "MaximumFontSize";
})(FontConstants || (FontConstants = {}));
var $5ec = class extends $3c {
  constructor(f, g) {
    super();
    this.f = f;
    this.g = g;
    this.linuxDistro = 1;
    this.B($1c(() => this.b?.remove()));
  }
  setPanelContainer(panelContainer) {
    this.a = panelContainer;
  }
  configFontIsMonospace() {
    const fontSize = 15;
    const fontFamily = this.f.config.fontFamily || this.g.getValue("editor").fontFamily || EDITOR_FONT_DEFAULTS.fontFamily;
    const iRect = this.j("i", fontFamily, fontSize);
    const wRect = this.j("w", fontFamily, fontSize);
    if (!iRect || !wRect || !iRect.width || !wRect.width) {
      return true;
    }
    return iRect.width === wRect.width;
  }
  /**
   * Gets the font information based on the terminal.integrated.fontFamily
   * terminal.integrated.fontSize, terminal.integrated.lineHeight configuration properties
   */
  getFont(w, xtermCore, excludeDimensions) {
    const editorConfig = this.g.getValue("editor");
    let fontFamily = this.f.config.fontFamily || editorConfig.fontFamily || EDITOR_FONT_DEFAULTS.fontFamily || "monospace";
    let fontSize = clampInt(this.f.config.fontSize, 6, 100, EDITOR_FONT_DEFAULTS.fontSize);
    if (!this.f.config.fontFamily) {
      if (this.linuxDistro === 2) {
        fontFamily = "'DejaVu Sans Mono'";
      }
      if (this.linuxDistro === 3) {
        fontFamily = "'Ubuntu Mono'";
        fontSize = clampInt(fontSize + 2, 6, 100, EDITOR_FONT_DEFAULTS.fontSize);
      }
    }
    fontFamily += ", monospace";
    if ($m) {
      fontFamily += ", AppleBraille";
    }
    const letterSpacing = this.f.config.letterSpacing ? Math.max(Math.floor(this.f.config.letterSpacing), $$X) : $0X;
    const lineHeight = this.f.config.lineHeight ? Math.max(this.f.config.lineHeight, 1) : $_X;
    if (excludeDimensions) {
      return {
        fontFamily,
        fontSize,
        letterSpacing,
        lineHeight
      };
    }
    if (xtermCore?._renderService?._renderer.value) {
      const cellDims = xtermCore._renderService.dimensions.css.cell;
      if (cellDims?.width && cellDims?.height) {
        return {
          fontFamily,
          fontSize,
          letterSpacing,
          lineHeight,
          charHeight: cellDims.height / lineHeight,
          charWidth: cellDims.width - Math.round(letterSpacing) / w.devicePixelRatio
        };
      }
    }
    return this.m(w, fontFamily, fontSize, letterSpacing, lineHeight);
  }
  h() {
    if (!this.a) {
      throw new Error("Cannot measure element when terminal is not attached");
    }
    if (!this.b || !this.b.parentElement) {
      this.b = document.createElement("div");
      this.a.appendChild(this.b);
    }
    return this.b;
  }
  j(char, fontFamily, fontSize) {
    let charMeasureElement;
    try {
      charMeasureElement = this.h();
    } catch {
      return void 0;
    }
    const style = charMeasureElement.style;
    style.display = "inline-block";
    style.fontFamily = fontFamily;
    style.fontSize = fontSize + "px";
    style.lineHeight = "normal";
    charMeasureElement.innerText = char;
    const rect = charMeasureElement.getBoundingClientRect();
    style.display = "none";
    return rect;
  }
  m(w, fontFamily, fontSize, letterSpacing, lineHeight) {
    const rect = this.j("X", fontFamily, fontSize);
    if (this.c && (!rect || !rect.width || !rect.height)) {
      return this.c;
    }
    this.c = {
      fontFamily,
      fontSize,
      letterSpacing,
      lineHeight,
      charWidth: 0,
      charHeight: 0
    };
    if (rect && rect.width && rect.height) {
      this.c.charHeight = Math.ceil(rect.height);
      if (this.f.config.gpuAcceleration === "off") {
        this.c.charWidth = rect.width;
      } else {
        const deviceCharWidth = Math.floor(rect.width * w.devicePixelRatio);
        const deviceCellWidth = deviceCharWidth + Math.round(letterSpacing);
        const cssCellWidth = deviceCellWidth / w.devicePixelRatio;
        this.c.charWidth = cssCellWidth - Math.round(letterSpacing) / w.devicePixelRatio;
      }
    }
    return this.c;
  }
};
function clampInt(source, minimum, maximum, fallback2) {
  let r2 = parseInt(source, 10);
  if (isNaN(r2)) {
    return fallback2;
  }
  if (typeof minimum === "number") {
    r2 = Math.max(minimum, r2);
  }
  if (typeof maximum === "number") {
    r2 = Math.min(maximum, r2);
  }
  return r2;
}

// out-build/vs/workbench/contrib/terminal/browser/terminalMenus.js
var ContextMenuGroup;
(function(ContextMenuGroup2) {
  ContextMenuGroup2["Create"] = "1_create";
  ContextMenuGroup2["Edit"] = "3_edit";
  ContextMenuGroup2["Clear"] = "5_clear";
  ContextMenuGroup2["Kill"] = "7_kill";
  ContextMenuGroup2["Config"] = "9_config";
})(ContextMenuGroup || (ContextMenuGroup = {}));
var TerminalMenuBarGroup;
(function(TerminalMenuBarGroup2) {
  TerminalMenuBarGroup2["Create"] = "1_create";
  TerminalMenuBarGroup2["Run"] = "3_run";
  TerminalMenuBarGroup2["Manage"] = "5_manage";
  TerminalMenuBarGroup2["Configure"] = "7_configure";
})(TerminalMenuBarGroup || (TerminalMenuBarGroup = {}));
function $6ec() {
  $dJ.appendMenuItems([
    {
      id: $bJ.MenubarTerminalMenu,
      item: {
        group: "1_create",
        command: {
          id: "workbench.action.terminal.new",
          title: localize(10486, null)
        },
        order: 1
      }
    },
    {
      id: $bJ.MenubarTerminalMenu,
      item: {
        group: "1_create",
        command: {
          id: "workbench.action.terminal.split",
          title: localize(10487, null),
          precondition: $7m.has(
            "terminalIsOpen"
            /* TerminalContextKeyStrings.IsOpen */
          )
        },
        order: 2,
        when: TerminalContextKeys.processSupported
      }
    },
    {
      id: $bJ.MenubarTerminalMenu,
      item: {
        group: "3_run",
        command: {
          id: "workbench.action.terminal.runActiveFile",
          title: localize(10488, null)
        },
        order: 3,
        when: TerminalContextKeys.processSupported
      }
    },
    {
      id: $bJ.MenubarTerminalMenu,
      item: {
        group: "3_run",
        command: {
          id: "workbench.action.terminal.runSelectedText",
          title: localize(10489, null)
        },
        order: 4,
        when: TerminalContextKeys.processSupported
      }
    }
  ]);
  $dJ.appendMenuItems([
    {
      id: $bJ.TerminalInstanceContext,
      item: {
        group: "1_create",
        command: {
          id: "workbench.action.terminal.split",
          title: $Kec.split.value
        }
      }
    },
    {
      id: $bJ.TerminalInstanceContext,
      item: {
        command: {
          id: "workbench.action.terminal.new",
          title: $Kec.new
        },
        group: "1_create"
        /* ContextMenuGroup.Create */
      }
    },
    {
      id: $bJ.TerminalInstanceContext,
      item: {
        command: {
          id: "workbench.action.terminal.killViewOrEditor",
          title: $Kec.kill.value
        },
        group: "7_kill"
        /* ContextMenuGroup.Kill */
      }
    },
    {
      id: $bJ.TerminalInstanceContext,
      item: {
        command: {
          id: "workbench.action.terminal.copySelection",
          title: localize(10490, null)
        },
        group: "3_edit",
        order: 1
      }
    },
    {
      id: $bJ.TerminalInstanceContext,
      item: {
        command: {
          id: "workbench.action.terminal.copySelectionAsHtml",
          title: localize(10491, null)
        },
        group: "3_edit",
        order: 2
      }
    },
    {
      id: $bJ.TerminalInstanceContext,
      item: {
        command: {
          id: "workbench.action.terminal.paste",
          title: localize(10492, null)
        },
        group: "3_edit",
        order: 3
      }
    },
    {
      id: $bJ.TerminalInstanceContext,
      item: {
        command: {
          id: "workbench.action.terminal.clear",
          title: localize(10493, null)
        },
        group: "5_clear"
      }
    },
    {
      id: $bJ.TerminalInstanceContext,
      item: {
        command: {
          id: "workbench.action.terminal.sizeToContentWidth",
          title: $Kec.toggleSizeToContentWidth
        },
        group: "9_config"
        /* ContextMenuGroup.Config */
      }
    },
    {
      id: $bJ.TerminalInstanceContext,
      item: {
        command: {
          id: "workbench.action.terminal.selectAll",
          title: localize(10494, null)
        },
        group: "3_edit",
        order: 3
      }
    }
  ]);
  $dJ.appendMenuItems([
    {
      id: $bJ.TerminalEditorInstanceContext,
      item: {
        group: "1_create",
        command: {
          id: "workbench.action.terminal.split",
          title: $Kec.split.value
        }
      }
    },
    {
      id: $bJ.TerminalEditorInstanceContext,
      item: {
        command: {
          id: "workbench.action.terminal.new",
          title: $Kec.new
        },
        group: "1_create"
        /* ContextMenuGroup.Create */
      }
    },
    {
      id: $bJ.TerminalEditorInstanceContext,
      item: {
        command: {
          id: "workbench.action.terminal.killEditor",
          title: $Kec.kill.value
        },
        group: "7_kill"
        /* ContextMenuGroup.Kill */
      }
    },
    {
      id: $bJ.TerminalEditorInstanceContext,
      item: {
        command: {
          id: "workbench.action.terminal.copySelection",
          title: localize(10495, null)
        },
        group: "3_edit",
        order: 1
      }
    },
    {
      id: $bJ.TerminalEditorInstanceContext,
      item: {
        command: {
          id: "workbench.action.terminal.copySelectionAsHtml",
          title: localize(10496, null)
        },
        group: "3_edit",
        order: 2
      }
    },
    {
      id: $bJ.TerminalEditorInstanceContext,
      item: {
        command: {
          id: "workbench.action.terminal.paste",
          title: localize(10497, null)
        },
        group: "3_edit",
        order: 3
      }
    },
    {
      id: $bJ.TerminalEditorInstanceContext,
      item: {
        command: {
          id: "workbench.action.terminal.clear",
          title: localize(10498, null)
        },
        group: "5_clear"
      }
    },
    {
      id: $bJ.TerminalEditorInstanceContext,
      item: {
        command: {
          id: "workbench.action.terminal.selectAll",
          title: localize(10499, null)
        },
        group: "3_edit",
        order: 3
      }
    },
    {
      id: $bJ.TerminalEditorInstanceContext,
      item: {
        command: {
          id: "workbench.action.terminal.sizeToContentWidth",
          title: $Kec.toggleSizeToContentWidth
        },
        group: "9_config"
        /* ContextMenuGroup.Config */
      }
    }
  ]);
  $dJ.appendMenuItems([
    {
      id: $bJ.TerminalTabEmptyAreaContext,
      item: {
        command: {
          id: "workbench.action.terminal.newWithProfile",
          title: localize(10500, null)
        },
        group: "1_create"
        /* ContextMenuGroup.Create */
      }
    },
    {
      id: $bJ.TerminalTabEmptyAreaContext,
      item: {
        command: {
          id: "workbench.action.terminal.new",
          title: $Kec.new
        },
        group: "1_create"
        /* ContextMenuGroup.Create */
      }
    }
  ]);
  $dJ.appendMenuItems([
    {
      id: $bJ.TerminalNewDropdownContext,
      item: {
        command: {
          id: "workbench.action.terminal.selectDefaultShell",
          title: localize2(10516, "Select Default Profile")
        },
        group: "3_configure"
      }
    },
    {
      id: $bJ.TerminalNewDropdownContext,
      item: {
        command: {
          id: "workbench.action.terminal.openSettings",
          title: localize(10501, null)
        },
        group: "3_configure"
      }
    },
    {
      id: $bJ.TerminalNewDropdownContext,
      item: {
        command: {
          id: "workbench.action.tasks.runTask",
          title: localize(10502, null)
        },
        when: $2Sb,
        group: "4_tasks",
        order: 1
      }
    },
    {
      id: $bJ.TerminalNewDropdownContext,
      item: {
        command: {
          id: "workbench.action.tasks.configureTaskRunner",
          title: localize(10503, null)
        },
        when: $2Sb,
        group: "4_tasks",
        order: 2
      }
    }
  ]);
  $dJ.appendMenuItems([
    {
      id: $bJ.ViewTitle,
      item: {
        command: {
          id: "workbench.action.terminal.switchTerminal",
          title: localize2(10517, "Switch Terminal")
        },
        group: "navigation",
        order: 0,
        when: $7m.and($7m.equals("view", $7X), $7m.not(`config.${"terminal.integrated.tabs.enabled"}`))
      }
    },
    {
      // This is used to show instead of tabs when there is only a single terminal
      id: $bJ.ViewTitle,
      item: {
        command: {
          id: "workbench.action.terminal.focus",
          title: $Kec.focus
        },
        alt: {
          id: "workbench.action.terminal.split",
          title: $Kec.split.value,
          icon: $6l.splitHorizontal
        },
        group: "navigation",
        order: 0,
        when: $7m.and($7m.equals("view", $7X), $7m.has(`config.${"terminal.integrated.tabs.enabled"}`), $7m.or($7m.and($7m.equals(`config.${"terminal.integrated.tabs.showActiveTerminal"}`, "singleTerminal"), $7m.equals("terminalGroupCount", 1)), $7m.and($7m.equals(`config.${"terminal.integrated.tabs.showActiveTerminal"}`, "singleTerminalOrNarrow"), $7m.or($7m.equals("terminalGroupCount", 1), $7m.has(
          "isTerminalTabsNarrow"
          /* TerminalContextKeyStrings.TabsNarrow */
        ))), $7m.and($7m.equals(`config.${"terminal.integrated.tabs.showActiveTerminal"}`, "singleGroup"), $7m.equals("terminalGroupCount", 1)), $7m.equals(`config.${"terminal.integrated.tabs.showActiveTerminal"}`, "always")))
      }
    },
    {
      id: $bJ.ViewTitle,
      item: {
        command: {
          id: "workbench.action.terminal.split",
          title: $Kec.split,
          icon: $6l.splitHorizontal
        },
        group: "navigation",
        order: 2,
        when: TerminalContextKeys.shouldShowViewInlineActions
      }
    },
    {
      id: $bJ.ViewTitle,
      item: {
        command: {
          id: "workbench.action.terminal.kill",
          title: $Kec.kill,
          icon: $6l.trash
        },
        group: "navigation",
        order: 3,
        when: TerminalContextKeys.shouldShowViewInlineActions
      }
    },
    {
      id: $bJ.ViewTitle,
      item: {
        command: {
          id: "workbench.action.terminal.new",
          title: $Kec.new,
          icon: $6l.plus
        },
        alt: {
          id: "workbench.action.terminal.split",
          title: $Kec.split.value,
          icon: $6l.splitHorizontal
        },
        group: "navigation",
        order: 0,
        when: $7m.and($7m.equals("view", $7X), $7m.or(TerminalContextKeys.webExtensionContributedProfile, TerminalContextKeys.processSupported))
      }
    },
    {
      id: $bJ.ViewTitle,
      item: {
        command: {
          id: "workbench.action.terminal.clear",
          title: localize(10504, null),
          icon: $6l.clearAll
        },
        group: "navigation",
        order: 4,
        when: $7m.equals("view", $7X),
        isHiddenByDefault: true
      }
    },
    {
      id: $bJ.ViewTitle,
      item: {
        command: {
          id: "workbench.action.terminal.runActiveFile",
          title: localize(10505, null),
          icon: $6l.run
        },
        group: "navigation",
        order: 5,
        when: $7m.equals("view", $7X),
        isHiddenByDefault: true
      }
    },
    {
      id: $bJ.ViewTitle,
      item: {
        command: {
          id: "workbench.action.terminal.runSelectedText",
          title: localize(10506, null),
          icon: $6l.selection
        },
        group: "navigation",
        order: 6,
        when: $7m.equals("view", $7X),
        isHiddenByDefault: true
      }
    }
  ]);
  $dJ.appendMenuItems([
    {
      id: $bJ.TerminalTabContext,
      item: {
        command: {
          id: "workbench.action.terminal.splitActiveTab",
          title: $Kec.split.value
        },
        group: "1_create",
        order: 1
      }
    },
    {
      id: $bJ.TerminalTabContext,
      item: {
        command: {
          id: "workbench.action.terminal.moveToEditor",
          title: $Kec.moveToEditor.value
        },
        group: "1_create",
        order: 2
      }
    },
    {
      id: $bJ.TerminalTabContext,
      item: {
        command: {
          id: "workbench.action.terminal.moveIntoNewWindow",
          title: $Kec.moveIntoNewWindow.value
        },
        group: "1_create",
        order: 2
      }
    },
    {
      id: $bJ.TerminalTabContext,
      item: {
        command: {
          id: "workbench.action.terminal.renameActiveTab",
          title: localize(10507, null)
        },
        group: "3_edit"
        /* ContextMenuGroup.Edit */
      }
    },
    {
      id: $bJ.TerminalTabContext,
      item: {
        command: {
          id: "workbench.action.terminal.changeIconActiveTab",
          title: localize(10508, null)
        },
        group: "3_edit"
        /* ContextMenuGroup.Edit */
      }
    },
    {
      id: $bJ.TerminalTabContext,
      item: {
        command: {
          id: "workbench.action.terminal.changeColorActiveTab",
          title: localize(10509, null)
        },
        group: "3_edit"
        /* ContextMenuGroup.Edit */
      }
    },
    {
      id: $bJ.TerminalTabContext,
      item: {
        command: {
          id: "workbench.action.terminal.sizeToContentWidth",
          title: $Kec.toggleSizeToContentWidth
        },
        group: "3_edit"
        /* ContextMenuGroup.Edit */
      }
    },
    {
      id: $bJ.TerminalTabContext,
      item: {
        command: {
          id: "workbench.action.terminal.joinActiveTab",
          title: localize(10510, null)
        },
        when: TerminalContextKeys.tabsSingularSelection.toNegated(),
        group: "9_config"
        /* ContextMenuGroup.Config */
      }
    },
    {
      id: $bJ.TerminalTabContext,
      item: {
        command: {
          id: "workbench.action.terminal.unsplit",
          title: $Kec.unsplit.value
        },
        when: $7m.and(TerminalContextKeys.tabsSingularSelection, TerminalContextKeys.splitTerminal),
        group: "9_config"
        /* ContextMenuGroup.Config */
      }
    },
    {
      id: $bJ.TerminalTabContext,
      item: {
        command: {
          id: "workbench.action.terminal.killActiveTab",
          title: $Kec.kill.value
        },
        group: "7_kill"
      }
    }
  ]);
  $dJ.appendMenuItem($bJ.EditorTitleContext, {
    command: {
      id: "workbench.action.terminal.moveToTerminalPanel",
      title: $Kec.moveToTerminalPanel
    },
    when: $lqb.Scheme.isEqualTo(Schemas.vscodeTerminal),
    group: "2_files"
  });
  $dJ.appendMenuItem($bJ.EditorTitleContext, {
    command: {
      id: "workbench.action.terminal.rename",
      title: $Kec.rename
    },
    when: $lqb.Scheme.isEqualTo(Schemas.vscodeTerminal),
    group: "2_files"
  });
  $dJ.appendMenuItem($bJ.EditorTitleContext, {
    command: {
      id: "workbench.action.terminal.changeColor",
      title: $Kec.changeColor
    },
    when: $lqb.Scheme.isEqualTo(Schemas.vscodeTerminal),
    group: "2_files"
  });
  $dJ.appendMenuItem($bJ.EditorTitleContext, {
    command: {
      id: "workbench.action.terminal.changeIcon",
      title: $Kec.changeIcon
    },
    when: $lqb.Scheme.isEqualTo(Schemas.vscodeTerminal),
    group: "2_files"
  });
  $dJ.appendMenuItem($bJ.EditorTitleContext, {
    command: {
      id: "workbench.action.terminal.sizeToContentWidth",
      title: $Kec.toggleSizeToContentWidth
    },
    when: $lqb.Scheme.isEqualTo(Schemas.vscodeTerminal),
    group: "2_files"
  });
  $dJ.appendMenuItem($bJ.EditorTitle, {
    command: {
      id: "workbench.action.createTerminalEditorSameGroup",
      title: $Kec.new,
      icon: $6l.plus
    },
    alt: {
      id: "workbench.action.terminal.split",
      title: $Kec.split.value,
      icon: $6l.splitHorizontal
    },
    group: "navigation",
    order: 0,
    when: $lqb.Scheme.isEqualTo(Schemas.vscodeTerminal)
  });
}
function $7ec(location3, profiles2, defaultProfileName, contributedProfiles, terminalService, dropdownMenu) {
  let dropdownActions = [];
  let submenuActions = [];
  profiles2 = profiles2.filter((e) => !e.isAutoDetected);
  const splitLocation = location3 === TerminalLocation2.Editor || typeof location3 === "object" && "viewColumn" in location3 && location3.viewColumn === $nJ ? { viewColumn: $oJ } : { splitActiveTerminal: true };
  for (const p of profiles2) {
    const isDefault = p.profileName === defaultProfileName;
    const options3 = { config: p, location: location3 };
    const splitOptions = { config: p, location: splitLocation };
    const sanitizedProfileName = p.profileName.replace(/[\n\r\t]/g, "");
    dropdownActions.push(new $Um("workbench.action.terminal.newWithProfile", isDefault ? localize(10511, null, sanitizedProfileName) : sanitizedProfileName, void 0, true, async () => {
      const instance2 = await terminalService.createTerminal(options3);
      terminalService.setActiveInstance(instance2);
      await terminalService.focusActiveInstance();
    }));
    submenuActions.push(new $Um("workbench.action.terminal.split", isDefault ? localize(10512, null, sanitizedProfileName) : sanitizedProfileName, void 0, true, async () => {
      const instance2 = await terminalService.createTerminal(splitOptions);
      terminalService.setActiveInstance(instance2);
      await terminalService.focusActiveInstance();
    }));
  }
  for (const contributed of contributedProfiles) {
    const isDefault = contributed.title === defaultProfileName;
    const title = isDefault ? localize(10513, null, contributed.title.replace(/[\n\r\t]/g, "")) : contributed.title.replace(/[\n\r\t]/g, "");
    dropdownActions.push(new $Um("contributed", title, void 0, true, () => terminalService.createTerminal({
      config: {
        extensionIdentifier: contributed.extensionIdentifier,
        id: contributed.id,
        title
      },
      location: location3
    })));
    submenuActions.push(new $Um("contributed-split", title, void 0, true, () => terminalService.createTerminal({
      config: {
        extensionIdentifier: contributed.extensionIdentifier,
        id: contributed.id,
        title
      },
      location: splitLocation
    })));
  }
  const defaultProfileAction = dropdownActions.find((d) => d.label.endsWith("(Default)"));
  if (defaultProfileAction) {
    dropdownActions = dropdownActions.filter((d) => d !== defaultProfileAction).sort((a, b) => a.label.localeCompare(b.label));
    dropdownActions.unshift(defaultProfileAction);
  }
  if (dropdownActions.length > 0) {
    dropdownActions.push(new $Xm("split.profile", localize(10514, null), submenuActions));
    dropdownActions.push(new $Wm());
  }
  const actions = dropdownMenu.getActions();
  dropdownActions.push(...$Wm.join(...actions.map((a) => a[1])));
  const defaultSubmenuProfileAction = submenuActions.find((d) => d.label.endsWith("(Default)"));
  if (defaultSubmenuProfileAction) {
    submenuActions = submenuActions.filter((d) => d !== defaultSubmenuProfileAction).sort((a, b) => a.label.localeCompare(b.label));
    submenuActions.unshift(defaultSubmenuProfileAction);
  }
  const dropdownAction = new $Um("refresh profiles", localize(10515, null), "codicon-chevron-down", true);
  return { dropdownAction, dropdownMenuActions: dropdownActions, className: `terminal-tab-actions-${terminalService.resolveLocation(location3)}` };
}

// out-build/vs/workbench/contrib/terminal/browser/terminalEditor.js
var $8ec = class $8ec2 extends $5tb {
  constructor(group2, telemetryService, themeService, storageService, u, cb, db, eb, contextKeyService, menuService, fb, gb, hb, ib) {
    super($$Pb, group2, telemetryService, themeService, storageService);
    this.u = u;
    this.cb = cb;
    this.db = db;
    this.eb = eb;
    this.fb = fb;
    this.gb = gb;
    this.hb = hb;
    this.ib = ib;
    this.f = void 0;
    this.r = false;
    this.s = this.B(new $2c());
    this.j = this.B(menuService.createMenu($bJ.TerminalNewDropdownContext, contextKeyService));
    this.m = this.B(menuService.createMenu($bJ.TerminalInstanceContext, contextKeyService));
  }
  async setInput(newInput, options3, context, token) {
    this.f?.terminalInstance?.detachFromElement();
    this.f = newInput;
    await super.setInput(newInput, options3, context, token);
    this.f.terminalInstance?.attachToElement(this.c);
    if (this.g) {
      this.layout(this.g);
    }
    this.f.terminalInstance?.setVisible(this.isVisible() && this.ib.isVisible("workbench.parts.editor", this.window));
    if (this.f.terminalInstance) {
      this.B(this.f.terminalInstance.onDidFocus(() => this.jb()));
      this.f.setCopyLaunchConfig(this.f.terminalInstance.shellLaunchConfig);
    }
  }
  clearInput() {
    super.clearInput();
    if (this.c && this.f?.terminalInstance?.domElement.parentElement === this.c) {
      this.f.terminalInstance?.detachFromElement();
    }
    this.f = void 0;
  }
  jb() {
    if (!this.f?.terminalInstance) {
      return;
    }
    this.u.setActiveInstance(this.f.terminalInstance);
  }
  focus() {
    super.focus();
    this.f?.terminalInstance?.focus(true);
  }
  // eslint-disable-next-line @typescript-eslint/naming-convention
  Y(parent) {
    this.b = parent;
    this.c = $(".terminal-overflow-guard.terminal-editor");
    this.b.appendChild(this.c);
    this.lb();
  }
  lb() {
    if (!this.b) {
      return;
    }
    this.B($_i(this.b, "mousedown", async (event) => {
      const terminal2 = this.u.activeInstance;
      if (this.u.instances.length > 0 && terminal2) {
        const result = await terminal2.handleMouseEvent(event, this.m);
        if (typeof result === "object" && result.cancelContextMenu) {
          this.r = true;
        }
      }
    }));
    this.B($_i(this.b, "contextmenu", (event) => {
      const rightClickBehavior = this.eb.config.rightClickBehavior;
      if (rightClickBehavior === "nothing" && !event.shiftKey) {
        event.preventDefault();
        event.stopImmediatePropagation();
        this.r = false;
        return;
      } else if (!this.r && rightClickBehavior !== "copyPaste" && rightClickBehavior !== "paste") {
        if (!this.r) {
          $Oec(this.window, event, this.f?.terminalInstance, this.m, this.gb);
        }
        event.preventDefault();
        event.stopImmediatePropagation();
        this.r = false;
      }
    }));
  }
  layout(dimension) {
    const instance2 = this.f?.terminalInstance;
    if (instance2) {
      instance2.attachToElement(this.c);
      instance2.layout(dimension);
    }
    this.g = dimension;
  }
  setVisible(visible) {
    super.setVisible(visible);
    this.f?.terminalInstance?.setVisible(visible && this.ib.isVisible("workbench.parts.editor", this.window));
  }
  getActionViewItem(action, options3) {
    switch (action.id) {
      case "workbench.action.createTerminalEditor": {
        if (action instanceof $fJ) {
          const location3 = { viewColumn: $nJ };
          const actions = $7ec(location3, this.hb.availableProfiles, this.nb(), this.hb.contributedProfiles, this.db, this.j);
          this.mb(actions.dropdownAction, actions.dropdownMenuActions);
          const button = this.fb.createInstance($isb, action, actions.dropdownAction, actions.dropdownMenuActions, actions.className, { hoverDelegate: options3.hoverDelegate });
          return button;
        }
      }
    }
    return super.getActionViewItem(action, options3);
  }
  /**
   * Actions might be of type Action (disposable) or Separator or SubmenuAction, which don't extend Disposable
   */
  mb(dropdownAction, dropdownMenuActions) {
    this.s.clear();
    if (dropdownAction instanceof $Um) {
      this.s.add(dropdownAction);
    }
    dropdownMenuActions.filter((a) => a instanceof $Um).forEach((a) => this.s.add(a));
  }
  nb() {
    let defaultProfileName;
    try {
      defaultProfileName = this.hb.getDefaultProfileName();
    } catch (e) {
      defaultProfileName = this.cb.defaultProfileName;
    }
    return defaultProfileName;
  }
};
$8ec = __decorate([
  __param(1, $zv),
  __param(2, $gs),
  __param(3, $jv),
  __param(4, $6Pb),
  __param(5, $fY),
  __param(6, $4Pb),
  __param(7, $5Pb),
  __param(8, $on),
  __param(9, $cJ),
  __param(10, $Pk),
  __param(11, $50),
  __param(12, $hY),
  __param(13, $Vlb)
], $8ec);

// out-build/vs/workbench/contrib/terminal/browser/terminalEditorSerializer.js
var $9ec = class $9ec2 {
  constructor(a) {
    this.a = a;
  }
  canSerialize(editorInput) {
    return typeof editorInput.terminalInstance?.persistentProcessId === "number" && editorInput.terminalInstance.shouldPersist;
  }
  serialize(editorInput) {
    if (!this.canSerialize(editorInput)) {
      return;
    }
    return JSON.stringify(this.b(editorInput.terminalInstance));
  }
  deserialize(instantiationService, serializedEditorInput) {
    const terminalInstance = JSON.parse(serializedEditorInput);
    return this.a.reviveInput(terminalInstance);
  }
  b(instance2) {
    return {
      id: instance2.persistentProcessId,
      pid: instance2.processId || 0,
      title: instance2.title,
      titleSource: instance2.titleSource,
      cwd: "",
      icon: instance2.icon,
      color: instance2.color,
      hasChildProcesses: instance2.hasChildProcesses,
      isFeatureTerminal: instance2.shellLaunchConfig.isFeatureTerminal,
      hideFromUser: instance2.shellLaunchConfig.hideFromUser,
      reconnectionProperties: instance2.shellLaunchConfig.reconnectionProperties,
      shellIntegrationNonce: instance2.shellIntegrationNonce
    };
  }
};
$9ec = __decorate([
  __param(0, $6Pb)
], $9ec);

// out-build/vs/workbench/contrib/terminal/browser/terminalUri.js
function $0ec(resource) {
  const [, workspaceId, instanceId] = resource.path.split("/");
  if (!workspaceId || !Number.parseInt(instanceId)) {
    throw new Error(`Could not parse terminal uri for resource ${resource}`);
  }
  return { workspaceId, instanceId: Number.parseInt(instanceId) };
}
function $$ec(workspaceId, instanceId, title) {
  return URI.from({
    scheme: Schemas.vscodeTerminal,
    path: `/${workspaceId}/${instanceId}`,
    fragment: title || void 0
  });
}
function $_ec(event) {
  const resources = event.dataTransfer?.getData(
    "Terminals"
    /* TerminalDataTransfers.Terminals */
  );
  if (resources) {
    const json = JSON.parse(resources);
    const result = [];
    for (const entry of json) {
      result.push(URI.parse(entry));
    }
    return result.length === 0 ? void 0 : result;
  }
  return void 0;
}
function $afc(instances, resource) {
  if (resource) {
    for (const instance2 of instances) {
      if (instance2.resource.path === resource.path) {
        return instance2;
      }
    }
  }
  return void 0;
}

// out-build/vs/workbench/contrib/terminal/browser/terminalEditorService.js
var $bfc = class $bfc2 extends $3c {
  constructor(t, u, w, y, lifecycleService, contextKeyService) {
    super();
    this.t = t;
    this.u = u;
    this.w = w;
    this.y = y;
    this.instances = [];
    this.a = -1;
    this.b = false;
    this.g = /* @__PURE__ */ new Map();
    this.h = /* @__PURE__ */ new Map();
    this.j = this.B(new $ze());
    this.onDidDisposeInstance = this.j.event;
    this.m = this.B(new $ze());
    this.onDidFocusInstance = this.m.event;
    this.n = this.B(new $ze());
    this.onDidChangeInstanceCapability = this.n.event;
    this.r = this.B(new $ze());
    this.onDidChangeActiveInstance = this.r.event;
    this.s = this.B(new $ze());
    this.onDidChangeInstances = this.s.event;
    this.f = TerminalContextKeys.terminalEditorActive.bindTo(contextKeyService);
    this.B($1c(() => {
      for (const d of this.h.values()) {
        $Xc(d);
      }
    }));
    this.B(lifecycleService.onWillShutdown(() => this.b = true));
    this.B(this.t.onDidActiveEditorChange(() => {
      const activeEditor = this.t.activeEditor;
      const instance2 = activeEditor instanceof $fQb ? activeEditor?.terminalInstance : void 0;
      const terminalEditorActive = !!instance2 && activeEditor instanceof $fQb;
      this.f.set(terminalEditorActive);
      if (terminalEditorActive) {
        activeEditor?.setGroup(this.t.activeEditorPane?.group);
        this.setActiveInstance(instance2);
      } else {
        for (const instance3 of this.instances) {
          instance3.resetFocusContextKey();
        }
      }
    }));
    this.B(this.t.onDidVisibleEditorsChange(() => {
      const knownIds = this.instances.map((i2) => i2.instanceId);
      const terminalEditors = this.z();
      const unknownEditor = terminalEditors.find((input) => {
        const inputId = input instanceof $fQb ? input.terminalInstance?.instanceId : void 0;
        if (inputId === void 0) {
          return false;
        }
        return !knownIds.includes(inputId);
      });
      if (unknownEditor instanceof $fQb && unknownEditor.terminalInstance) {
        this.g.set(unknownEditor.terminalInstance.resource.path, unknownEditor);
        this.instances.push(unknownEditor.terminalInstance);
      }
    }));
    this.B(this.t.onDidCloseEditor((e) => {
      const instance2 = e.editor instanceof $fQb ? e.editor.terminalInstance : void 0;
      if (instance2) {
        const instanceIndex = this.instances.findIndex((e2) => e2 === instance2);
        if (instanceIndex !== -1) {
          const wasActiveInstance = this.instances[instanceIndex] === this.activeInstance;
          this.D(instance2);
          if (wasActiveInstance) {
            this.setActiveInstance(void 0);
          }
        }
      }
    }));
  }
  z() {
    return this.t.visibleEditors.filter((e) => e instanceof $fQb && e.terminalInstance?.instanceId);
  }
  get activeInstance() {
    if (this.instances.length === 0 || this.a === -1) {
      return void 0;
    }
    return this.instances[this.a];
  }
  setActiveInstance(instance2) {
    this.a = instance2 ? this.instances.findIndex((e) => e === instance2) : -1;
    this.r.fire(this.activeInstance);
  }
  async focusInstance(instance2) {
    return instance2.focusWhenReady(true);
  }
  async focusActiveInstance() {
    return this.activeInstance?.focusWhenReady(true);
  }
  async openEditor(instance2, editorOptions2) {
    const resource = this.resolveResource(instance2);
    if (resource) {
      await this.c?.promise;
      this.c = {
        instanceId: instance2.instanceId,
        promise: this.t.openEditor({
          resource,
          description: instance2.description || instance2.shellLaunchConfig.type,
          options: {
            pinned: true,
            forceReload: true,
            preserveFocus: editorOptions2?.preserveFocus
          }
        }, editorOptions2?.viewColumn ?? $nJ)
      };
      await this.c?.promise;
      this.c = void 0;
    }
  }
  resolveResource(instance2) {
    const resource = instance2.resource;
    const inputKey = resource.path;
    const cachedEditor = this.g.get(inputKey);
    if (cachedEditor) {
      return cachedEditor.resource;
    }
    instance2.target = TerminalLocation2.Editor;
    const input = this.y.createInstance($fQb, resource, instance2);
    this.C(inputKey, input, instance2);
    return input.resource;
  }
  getInputFromResource(resource) {
    const input = this.g.get(resource.path);
    if (!input) {
      throw new Error(`Could not get input from resource: ${resource.path}`);
    }
    return input;
  }
  C(inputKey, input, instance2) {
    this.g.set(inputKey, input);
    this.h.set(inputKey, [
      instance2.onDidFocus(this.m.fire, this.m),
      instance2.onDisposed(this.j.fire, this.j),
      instance2.capabilities.onDidAddCapabilityType(() => this.n.fire(instance2)),
      instance2.capabilities.onDidRemoveCapabilityType(() => this.n.fire(instance2))
    ]);
    this.instances.push(instance2);
    this.s.fire();
  }
  D(instance2) {
    const inputKey = instance2.resource.path;
    this.g.delete(inputKey);
    const instanceIndex = this.instances.findIndex((e) => e === instance2);
    if (instanceIndex !== -1) {
      this.instances.splice(instanceIndex, 1);
    }
    const disposables = this.h.get(inputKey);
    this.h.delete(inputKey);
    if (disposables) {
      $Xc(disposables);
    }
    this.s.fire();
  }
  getInstanceFromResource(resource) {
    return $afc(this.instances, resource);
  }
  splitInstance(instanceToSplit, shellLaunchConfig = {}) {
    if (instanceToSplit.target === TerminalLocation2.Editor) {
      const group2 = this.g.get(instanceToSplit.resource.path)?.group;
      if (group2) {
        this.u.activateGroup(group2);
      }
    }
    const instance2 = this.w.createInstance(shellLaunchConfig, TerminalLocation2.Editor);
    const resource = this.resolveResource(instance2);
    if (resource) {
      this.t.openEditor({
        resource: URI.revive(resource),
        description: instance2.description,
        options: {
          pinned: true,
          forceReload: true
        }
      }, $oJ);
    }
    return instance2;
  }
  reviveInput(deserializedInput) {
    if ("pid" in deserializedInput) {
      const newDeserializedInput = { ...deserializedInput, findRevivedId: true };
      const instance2 = this.w.createInstance({ attachPersistentProcess: newDeserializedInput }, TerminalLocation2.Editor);
      const input = this.y.createInstance($fQb, instance2.resource, instance2);
      this.C(instance2.resource.path, input, instance2);
      return input;
    } else {
      throw new Error(`Could not revive terminal editor input, ${deserializedInput}`);
    }
  }
  detachInstance(instance2) {
    const inputKey = instance2.resource.path;
    const editorInput = this.g.get(inputKey);
    editorInput?.detachInstance();
    this.D(instance2);
    if (!this.b) {
      editorInput?.dispose();
    }
  }
  async revealActiveEditor(preserveFocus) {
    const instance2 = this.activeInstance;
    if (!instance2) {
      return;
    }
    if (this.c?.instanceId === instance2.instanceId) {
      return;
    }
    const editorInput = this.g.get(instance2.resource.path);
    this.t.openEditor(editorInput, {
      pinned: true,
      forceReload: true,
      preserveFocus,
      activation: EditorActivation.PRESERVE
    });
  }
};
$bfc = __decorate([
  __param(0, $mJ),
  __param(1, $iJ),
  __param(2, $8Pb),
  __param(3, $Pk),
  __param(4, $KL),
  __param(5, $on)
], $bfc);

// out-build/vs/workbench/contrib/terminal/browser/terminalGroup.js
var Constants13;
(function(Constants27) {
  Constants27[Constants27["SplitPaneMinSize"] = 80] = "SplitPaneMinSize";
  Constants27[Constants27["ResizePartCellCount"] = 4] = "ResizePartCellCount";
})(Constants13 || (Constants13 = {}));
var SplitPaneContainer = class extends $3c {
  get onDidChange() {
    return this.m;
  }
  constructor(n, orientation) {
    super();
    this.n = n;
    this.orientation = orientation;
    this.g = this.B(new $2c());
    this.h = [];
    this.j = /* @__PURE__ */ new Map();
    this.m = Event2.None;
    this.b = this.n.offsetWidth;
    this.a = this.n.offsetHeight;
    this.r();
    this.f.layout(this.orientation === 1 ? this.b : this.a);
  }
  r() {
    this.f = new $r2(this.n, { orientation: this.orientation });
    this.g.clear();
    this.g.add(this.f.onDidSashReset(() => this.f.distributeViewSizes()));
  }
  split(instance2, index) {
    this.s(instance2, index);
  }
  resizePane(index, direction, amount) {
    if (this.h.length <= 1) {
      return;
    }
    const sizes = [];
    for (let i2 = 0; i2 < this.f.length; i2++) {
      sizes.push(this.f.getViewSize(i2));
    }
    const isSizingEndPane = index !== this.h.length - 1;
    const indexToChange = isSizingEndPane ? index + 1 : index - 1;
    if (isSizingEndPane && direction === 0) {
      amount *= -1;
    } else if (!isSizingEndPane && direction === 1) {
      amount *= -1;
    } else if (isSizingEndPane && direction === 2) {
      amount *= -1;
    } else if (!isSizingEndPane && direction === 3) {
      amount *= -1;
    }
    if (sizes[index] + amount < 80) {
      amount = 80 - sizes[index];
    } else if (sizes[indexToChange] - amount < 80) {
      amount = sizes[indexToChange] - 80;
    }
    sizes[index] += amount;
    sizes[indexToChange] -= amount;
    for (let i2 = 0; i2 < this.f.length - 1; i2++) {
      this.f.resizeView(i2, sizes[i2]);
    }
  }
  resizePanes(relativeSizes) {
    if (this.h.length <= 1) {
      return;
    }
    relativeSizes[relativeSizes.length - 1] += 1 - relativeSizes.reduce((totalValue, currentValue) => totalValue + currentValue, 0);
    let totalSize = 0;
    for (let i2 = 0; i2 < this.f.length; i2++) {
      totalSize += this.f.getViewSize(i2);
    }
    for (let i2 = 0; i2 < this.f.length; i2++) {
      this.f.resizeView(i2, totalSize * relativeSizes[i2]);
    }
  }
  getPaneSize(instance2) {
    const paneForInstance = this.j.get(instance2);
    if (!paneForInstance) {
      return 0;
    }
    const index = this.h.indexOf(paneForInstance);
    return this.f.getViewSize(index);
  }
  s(instance2, index) {
    const child = new SplitPane(instance2, this.orientation === 1 ? this.a : this.b);
    child.orientation = this.orientation;
    if (typeof index === "number") {
      this.h.splice(index, 0, child);
    } else {
      this.h.push(child);
    }
    this.j.set(instance2, this.h[this.h.indexOf(child)]);
    this.u(() => this.f.addView(child, Sizing.Distribute, index));
    this.layout(this.b, this.a);
    this.m = Event2.any(...this.h.map((c) => c.onDidChange));
  }
  remove(instance2) {
    let index = null;
    for (let i2 = 0; i2 < this.h.length; i2++) {
      if (this.h[i2].instance === instance2) {
        index = i2;
      }
    }
    if (index !== null) {
      this.h.splice(index, 1);
      this.j.delete(instance2);
      this.f.removeView(index, Sizing.Distribute);
      instance2.detachFromElement();
    }
  }
  layout(width2, height) {
    this.b = width2;
    this.a = height;
    if (this.orientation === 1) {
      this.h.forEach((c) => c.orthogonalLayout(height));
      this.f.layout(width2);
    } else {
      this.h.forEach((c) => c.orthogonalLayout(width2));
      this.f.layout(height);
    }
  }
  setOrientation(orientation) {
    if (this.orientation === orientation) {
      return;
    }
    this.orientation = orientation;
    while (this.n.children.length > 0) {
      this.n.children[0].remove();
    }
    this.g.clear();
    this.f.dispose();
    this.r();
    this.u(() => {
      this.h.forEach((child) => {
        child.orientation = orientation;
        this.f.addView(child, 1);
      });
    });
  }
  u(innerFunction) {
    this.h.forEach((c) => c.instance.disableLayout = true);
    innerFunction();
    this.h.forEach((c) => c.instance.disableLayout = false);
  }
};
var SplitPane = class {
  get onDidChange() {
    return this.a;
  }
  constructor(instance2, orthogonalSize) {
    this.instance = instance2;
    this.orthogonalSize = orthogonalSize;
    this.minimumSize = 80;
    this.maximumSize = Number.MAX_VALUE;
    this.a = Event2.None;
    this.element = document.createElement("div");
    this.element.className = "terminal-split-pane";
    this.instance.attachToElement(this.element);
  }
  layout(size) {
    if (!size || !this.orthogonalSize) {
      return;
    }
    if (this.orientation === 0) {
      this.instance.layout({ width: this.orthogonalSize, height: size });
    } else {
      this.instance.layout({ width: size, height: this.orthogonalSize });
    }
  }
  orthogonalLayout(size) {
    this.orthogonalSize = size;
  }
};
var $cfc = class $cfc2 extends $3c {
  get terminalInstances() {
    return this.a;
  }
  constructor(F, shellLaunchConfigOrInstance, G, H, I, J, L) {
    super();
    this.F = F;
    this.G = G;
    this.H = H;
    this.I = I;
    this.J = J;
    this.L = L;
    this.a = [];
    this.g = 2;
    this.h = 1;
    this.j = /* @__PURE__ */ new Map();
    this.m = -1;
    this.r = false;
    this.s = this.B(new $ze());
    this.onDidDisposeInstance = this.s.event;
    this.u = this.B(new $ze());
    this.onDidFocusInstance = this.u.event;
    this.w = this.B(new $ze());
    this.onDidChangeInstanceCapability = this.w.event;
    this.y = this.B(new $ze());
    this.onDisposed = this.y.event;
    this.z = this.B(new $ze());
    this.onInstancesChanged = this.z.event;
    this.C = this.B(new $ze());
    this.onDidChangeActiveInstance = this.C.event;
    this.D = this.B(new $ze());
    this.onPanelOrientationChanged = this.D.event;
    if (shellLaunchConfigOrInstance) {
      this.addInstance(shellLaunchConfigOrInstance);
    }
    if (this.F) {
      this.attachToElement(this.F);
    }
    this.D.fire(
      this.h === 1 && $Wlb(this.g) ? 1 : 0
      /* Orientation.VERTICAL */
    );
    this.B($1c(() => {
      if (this.F && this.f) {
        this.f.remove();
        this.f = void 0;
      }
    }));
  }
  addInstance(shellLaunchConfigOrInstance, parentTerminalId) {
    let instance2;
    const parentIndex = parentTerminalId ? this.a.findIndex((t) => t.instanceId === parentTerminalId) : this.m;
    if ("instanceId" in shellLaunchConfigOrInstance) {
      instance2 = shellLaunchConfigOrInstance;
    } else {
      instance2 = this.H.createInstance(shellLaunchConfigOrInstance, TerminalLocation2.Panel);
    }
    if (this.a.length === 0) {
      this.a.push(instance2);
      this.m = 0;
    } else {
      this.a.splice(parentIndex + 1, 0, instance2);
    }
    this.M(instance2);
    if (this.b) {
      this.b.split(instance2, parentIndex + 1);
    }
    this.z.fire();
  }
  dispose() {
    this.a = [];
    this.z.fire();
    super.dispose();
  }
  get activeInstance() {
    if (this.a.length === 0) {
      return void 0;
    }
    return this.a[this.m];
  }
  getLayoutInfo(isActive2) {
    const instances = this.terminalInstances.filter((instance2) => typeof instance2.persistentProcessId === "number" && instance2.shouldPersist);
    const totalSize = instances.map((t) => this.b?.getPaneSize(t) || 0).reduce((total, size) => total += size, 0);
    return {
      isActive: isActive2,
      activePersistentProcessId: this.activeInstance ? this.activeInstance.persistentProcessId : void 0,
      terminals: instances.map((t) => {
        return {
          relativeSize: totalSize > 0 ? this.b.getPaneSize(t) / totalSize : 0,
          terminal: t.persistentProcessId || 0
        };
      })
    };
  }
  M(instance2) {
    this.j.set(instance2.instanceId, [
      instance2.onDisposed((instance3) => {
        this.s.fire(instance3);
        this.N(instance3);
      }),
      instance2.onDidFocus((instance3) => {
        this.P(instance3);
        this.u.fire(instance3);
      }),
      instance2.capabilities.onDidAddCapabilityType(() => this.w.fire(instance2)),
      instance2.capabilities.onDidRemoveCapabilityType(() => this.w.fire(instance2))
    ]);
  }
  N(instance2) {
    this.O(instance2);
  }
  removeInstance(instance2) {
    this.O(instance2);
  }
  O(instance2) {
    const index = this.a.indexOf(instance2);
    if (index === -1) {
      return;
    }
    const wasActiveInstance = instance2 === this.activeInstance;
    this.a.splice(index, 1);
    if (wasActiveInstance && this.a.length > 0) {
      const newIndex = index < this.a.length ? index : this.a.length - 1;
      this.setActiveInstanceByIndex(newIndex);
      this.activeInstance?.focus(true);
    } else if (index < this.m) {
      this.m--;
    }
    this.b?.remove(instance2);
    if (this.a.length === 0) {
      this.y.fire(this);
      this.dispose();
    } else {
      this.z.fire();
    }
    const disposables = this.j.get(instance2.instanceId);
    if (disposables) {
      $Xc(disposables);
      this.j.delete(instance2.instanceId);
    }
  }
  moveInstance(instances, index, position) {
    instances = $5b(instances);
    const hasInvalidInstance = instances.some((instance2) => !this.terminalInstances.includes(instance2));
    if (hasInvalidInstance) {
      return;
    }
    const insertIndex = position === "before" ? index : index + 1;
    this.a.splice(insertIndex, 0, ...instances);
    for (const item of instances) {
      const originSourceGroupIndex = position === "after" ? this.a.indexOf(item) : this.a.lastIndexOf(item);
      this.a.splice(originSourceGroupIndex, 1);
    }
    if (this.b) {
      for (let i2 = 0; i2 < instances.length; i2++) {
        const item = instances[i2];
        this.b.remove(item);
        this.b.split(item, index + (position === "before" ? i2 : 0));
      }
    }
    this.z.fire();
  }
  P(instance2) {
    this.setActiveInstanceByIndex(this.Q(instance2.instanceId));
  }
  Q(terminalId) {
    let terminalIndex = -1;
    this.terminalInstances.forEach((terminalInstance, i2) => {
      if (terminalInstance.instanceId === terminalId) {
        terminalIndex = i2;
      }
    });
    if (terminalIndex === -1) {
      throw new Error(`Terminal with ID ${terminalId} does not exist (has it already been disposed?)`);
    }
    return terminalIndex;
  }
  setActiveInstanceByIndex(index, force) {
    if (index < 0 || index >= this.a.length) {
      return;
    }
    const oldActiveInstance = this.activeInstance;
    this.m = index;
    if (oldActiveInstance !== this.activeInstance || force) {
      this.z.fire();
      this.C.fire(this.activeInstance);
    }
  }
  attachToElement(element) {
    this.F = element;
    if (!this.f) {
      this.f = document.createElement("div");
      this.f.classList.add("terminal-group");
    }
    this.F.appendChild(this.f);
    if (!this.b) {
      this.g = this.I.getPanelPosition();
      this.h = this.J.getViewLocationById($7X);
      const orientation = this.h === 1 && $Wlb(this.g) ? 1 : 0;
      this.b = this.L.createInstance(SplitPaneContainer, this.f, orientation);
      this.terminalInstances.forEach((instance2) => this.b.split(instance2, this.m + 1));
    }
  }
  get title() {
    if (this.a.length === 0) {
      return "";
    }
    let title = this.terminalInstances[0].title + this.R(this.terminalInstances[0]);
    if (this.terminalInstances[0].description) {
      title += ` (${this.terminalInstances[0].description})`;
    }
    for (let i2 = 1; i2 < this.terminalInstances.length; i2++) {
      const instance2 = this.terminalInstances[i2];
      if (instance2.title) {
        title += `, ${instance2.title + this.R(instance2)}`;
        if (instance2.description) {
          title += ` (${instance2.description})`;
        }
      }
    }
    return title;
  }
  R(instance2) {
    if (this.G.config.enableBell && instance2.statusList.statuses.some(
      (e) => e.id === "bell"
      /* TerminalStatus.Bell */
    )) {
      return "*";
    }
    return "";
  }
  setVisible(visible) {
    this.r = visible;
    if (this.f) {
      this.f.style.display = visible ? "" : "none";
    }
    this.terminalInstances.forEach((i2) => i2.setVisible(visible));
  }
  split(shellLaunchConfig) {
    const instance2 = this.H.createInstance(shellLaunchConfig, TerminalLocation2.Panel);
    this.addInstance(instance2, shellLaunchConfig.parentTerminalId);
    this.P(instance2);
    return instance2;
  }
  addDisposable(disposable) {
    this.B(disposable);
  }
  layout(width2, height) {
    if (this.b) {
      const newPanelPosition = this.I.getPanelPosition();
      const newTerminalLocation = this.J.getViewLocationById($7X);
      const terminalPositionChanged = newPanelPosition !== this.g || newTerminalLocation !== this.h;
      if (terminalPositionChanged) {
        const newOrientation = newTerminalLocation === 1 && $Wlb(newPanelPosition) ? 1 : 0;
        this.b.setOrientation(newOrientation);
        this.g = newPanelPosition;
        this.h = newTerminalLocation;
        this.D.fire(this.b.orientation);
      }
      this.b.layout(width2, height);
      if (this.n && this.r) {
        this.resizePanes(this.n);
        this.n = void 0;
      }
    }
  }
  focusPreviousPane() {
    const newIndex = this.m === 0 ? this.a.length - 1 : this.m - 1;
    this.setActiveInstanceByIndex(newIndex);
  }
  focusNextPane() {
    const newIndex = this.m === this.a.length - 1 ? 0 : this.m + 1;
    this.setActiveInstanceByIndex(newIndex);
  }
  S() {
    switch (this.h) {
      case 1:
        return this.g;
      case 0:
        return this.I.getSideBarPosition();
      case 2:
        return this.I.getSideBarPosition() === 0 ? 1 : 0;
    }
  }
  U() {
    return $Wlb(this.S()) ? 1 : 0;
  }
  resizePane(direction) {
    if (!this.b) {
      return;
    }
    const isHorizontalResize = direction === 0 || direction === 1;
    const groupOrientation = this.U();
    const shouldResizePart = isHorizontalResize && groupOrientation === 0 || !isHorizontalResize && groupOrientation === 1;
    const font = this.G.getFont(getWindow(this.f));
    const charSize = isHorizontalResize ? font.charWidth : font.charHeight;
    if (charSize) {
      let resizeAmount = charSize * 4;
      if (shouldResizePart) {
        const position = this.S();
        const shouldShrink = position === 0 && direction === 0 || position === 1 && direction === 1 || position === 2 && direction === 3 || position === 3 && direction === 2;
        if (shouldShrink) {
          resizeAmount *= -1;
        }
        this.I.resizePart($5Wb(this.h), resizeAmount, resizeAmount);
      } else {
        this.b.resizePane(this.m, direction, resizeAmount);
      }
    }
  }
  resizePanes(relativeSizes) {
    if (!this.b) {
      this.n = relativeSizes;
      return;
    }
    this.b.resizePanes(relativeSizes);
  }
};
$cfc = __decorate([
  __param(2, $5Pb),
  __param(3, $8Pb),
  __param(4, $Vlb),
  __param(5, $$M),
  __param(6, $Pk)
], $cfc);

// out-build/vs/workbench/contrib/terminal/browser/terminalGroupService.js
var $jfc = class $jfc2 extends $3c {
  get instances() {
    return this.groups.reduce((p, c) => p.concat(c.terminalInstances), []);
  }
  constructor(D, F, G, H, I) {
    super();
    this.D = D;
    this.F = F;
    this.G = G;
    this.H = H;
    this.I = I;
    this.groups = [];
    this.activeGroupIndex = -1;
    this.lastAccessedMenu = "inline-tab";
    this.j = false;
    this.m = this.B(new $ze());
    this.onDidChangeActiveGroup = this.m.event;
    this.n = this.B(new $ze());
    this.onDidDisposeGroup = this.n.event;
    this.r = this.B(new $ze());
    this.onDidChangeGroups = this.r.event;
    this.s = this.B(new $ze());
    this.onDidShow = this.s.event;
    this.t = this.B(new $ze());
    this.onDidDisposeInstance = this.t.event;
    this.u = this.B(new $ze());
    this.onDidFocusInstance = this.u.event;
    this.w = this.B(new $ze());
    this.onDidChangeActiveInstance = this.w.event;
    this.y = this.B(new $ze());
    this.onDidChangeInstances = this.y.event;
    this.z = this.B(new $ze());
    this.onDidChangeInstanceCapability = this.z.event;
    this.C = this.B(new $ze());
    this.onDidChangePanelOrientation = this.C.event;
    this.N = (sources) => {
      return new Set(sources.map((source) => this.getGroupForInstance(source)).filter((group2) => group2 !== void 0));
    };
    this.f = TerminalContextKeys.groupCount.bindTo(this.D);
    this.B(this.onDidDisposeGroup((group2) => this.L(group2)));
    this.B(this.onDidChangeGroups(() => this.f.set(this.groups.length)));
    this.B(Event2.any(this.onDidChangeActiveGroup, this.onDidChangeInstances)(() => this.updateVisibility()));
    this.B(this.I.onShow(() => this.j = true));
    this.B(this.I.onHide(() => this.j = false));
  }
  hidePanel() {
    const panel = this.H.getViewContainerByViewId($7X);
    if (panel && this.H.getViewContainerModel(panel).activeViewDescriptors.length === 1) {
      this.G.closeView($7X);
      TerminalContextKeys.tabsMouse.bindTo(this.D).set(false);
    }
  }
  get activeGroup() {
    if (this.activeGroupIndex < 0 || this.activeGroupIndex >= this.groups.length) {
      return void 0;
    }
    return this.groups[this.activeGroupIndex];
  }
  set activeGroup(value) {
    if (value === void 0) {
      return;
    }
    const index = this.groups.findIndex((e) => e === value);
    this.setActiveGroupByIndex(index);
  }
  get activeInstance() {
    return this.activeGroup?.activeInstance;
  }
  setActiveInstance(instance2) {
    this.setActiveInstanceByIndex(this.J(instance2.instanceId));
  }
  J(terminalId) {
    const terminalIndex = this.instances.findIndex((e) => e.instanceId === terminalId);
    if (terminalIndex === -1) {
      throw new Error(`Terminal with ID ${terminalId} does not exist (has it already been disposed?)`);
    }
    return terminalIndex;
  }
  setContainer(container2) {
    this.h = container2;
    this.groups.forEach((group2) => group2.attachToElement(container2));
  }
  async focusTabs() {
    if (this.instances.length === 0) {
      return;
    }
    await this.showPanel(true);
    const pane = this.G.getActiveViewWithId($7X);
    pane?.terminalTabbedView?.focusTabs();
  }
  async focusHover() {
    if (this.instances.length === 0) {
      return;
    }
    const pane = this.G.getActiveViewWithId($7X);
    pane?.terminalTabbedView?.focusHover();
  }
  async focusInstance(_) {
    return this.showPanel(true);
  }
  async focusActiveInstance() {
    return this.showPanel(true);
  }
  createGroup(slcOrInstance) {
    const group2 = this.F.createInstance($cfc, this.h, slcOrInstance);
    this.groups.push(group2);
    group2.addDisposable(Event2.forward(group2.onPanelOrientationChanged, this.C));
    group2.addDisposable(Event2.forward(group2.onDidDisposeInstance, this.t));
    group2.addDisposable(Event2.forward(group2.onDidFocusInstance, this.u));
    group2.addDisposable(Event2.forward(group2.onDidChangeInstanceCapability, this.z));
    group2.addDisposable(Event2.forward(group2.onInstancesChanged, this.y));
    group2.addDisposable(Event2.forward(group2.onDisposed, this.n));
    group2.addDisposable(group2.onDidChangeActiveInstance((e) => {
      if (group2 === this.activeGroup) {
        this.w.fire(e);
      }
    }));
    if (group2.terminalInstances.length > 0) {
      this.y.fire();
    }
    if (this.instances.length === 1) {
      this.setActiveInstanceByIndex(0);
    }
    this.r.fire();
    return group2;
  }
  async showPanel(focus) {
    const pane = this.G.getActiveViewWithId($7X) ?? await this.G.openView($7X, focus);
    pane?.setExpanded(true);
    if (focus) {
      await $Wh(0);
      const instance2 = this.activeInstance;
      if (instance2) {
        if (pane && !pane.isVisible()) {
          await this.G.openView($7X, focus);
        }
        await instance2.focusWhenReady(true);
      }
    }
    this.s.fire();
  }
  getInstanceFromResource(resource) {
    return $afc(this.instances, resource);
  }
  L(group2) {
    const activeGroup = this.activeGroup;
    const wasActiveGroup = group2 === activeGroup;
    const index = this.groups.indexOf(group2);
    if (index !== -1) {
      this.groups.splice(index, 1);
      this.r.fire();
    }
    if (wasActiveGroup) {
      if (this.groups.length > 0 && !this.j) {
        const newIndex = index < this.groups.length ? index : this.groups.length - 1;
        this.setActiveGroupByIndex(newIndex, true);
        this.activeInstance?.focus(true);
      }
    } else {
      if (this.activeGroupIndex > index) {
        this.setActiveGroupByIndex(this.activeGroupIndex - 1);
      }
    }
    if (this.activeGroupIndex >= this.groups.length) {
      this.setActiveGroupByIndex(this.groups.length - 1);
    }
    this.y.fire();
    this.r.fire();
    if (wasActiveGroup) {
      this.m.fire(this.activeGroup);
      this.w.fire(this.activeInstance);
    }
  }
  /**
   * @param force Whether to force the group change, this should be used when the previous active
   * group has been removed.
   */
  setActiveGroupByIndex(index, force) {
    if (index === -1 && this.groups.length === 0) {
      if (this.activeGroupIndex !== -1) {
        this.activeGroupIndex = -1;
        this.m.fire(this.activeGroup);
        this.w.fire(this.activeInstance);
      }
      return;
    }
    if (index < 0 || index >= this.groups.length) {
      return;
    }
    const oldActiveGroup = this.activeGroup;
    this.activeGroupIndex = index;
    if (force || oldActiveGroup !== this.activeGroup) {
      this.m.fire(this.activeGroup);
      this.w.fire(this.activeInstance);
    }
  }
  M(index) {
    let currentGroupIndex = 0;
    while (index >= 0 && currentGroupIndex < this.groups.length) {
      const group2 = this.groups[currentGroupIndex];
      const count = group2.terminalInstances.length;
      if (index < count) {
        return {
          group: group2,
          groupIndex: currentGroupIndex,
          instance: group2.terminalInstances[index],
          instanceIndex: index
        };
      }
      index -= count;
      currentGroupIndex++;
    }
    return void 0;
  }
  setActiveInstanceByIndex(index) {
    const activeInstance = this.activeInstance;
    const instanceLocation = this.M(index);
    const newActiveInstance = instanceLocation?.group.terminalInstances[instanceLocation.instanceIndex];
    if (!instanceLocation || activeInstance === newActiveInstance) {
      return;
    }
    const activeInstanceIndex = instanceLocation.instanceIndex;
    this.activeGroupIndex = instanceLocation.groupIndex;
    this.m.fire(this.activeGroup);
    instanceLocation.group.setActiveInstanceByIndex(activeInstanceIndex, true);
  }
  setActiveGroupToNext() {
    if (this.groups.length <= 1) {
      return;
    }
    let newIndex = this.activeGroupIndex + 1;
    if (newIndex >= this.groups.length) {
      newIndex = 0;
    }
    this.setActiveGroupByIndex(newIndex);
  }
  setActiveGroupToPrevious() {
    if (this.groups.length <= 1) {
      return;
    }
    let newIndex = this.activeGroupIndex - 1;
    if (newIndex < 0) {
      newIndex = this.groups.length - 1;
    }
    this.setActiveGroupByIndex(newIndex);
  }
  moveGroup(source, target) {
    source = $5b(source);
    const sourceGroups = this.N(source);
    const targetGroup = this.getGroupForInstance(target);
    if (!targetGroup || sourceGroups.size === 0) {
      return;
    }
    if (sourceGroups.size === 1 && sourceGroups.has(targetGroup)) {
      const targetIndex = targetGroup.terminalInstances.indexOf(target);
      const sortedSources = source.sort((a, b) => {
        return targetGroup.terminalInstances.indexOf(a) - targetGroup.terminalInstances.indexOf(b);
      });
      const firstTargetIndex = targetGroup.terminalInstances.indexOf(sortedSources[0]);
      const position2 = firstTargetIndex < targetIndex ? "after" : "before";
      targetGroup.moveInstance(sortedSources, targetIndex, position2);
      this.y.fire();
      return;
    }
    const targetGroupIndex = this.groups.indexOf(targetGroup);
    const sortedSourceGroups = Array.from(sourceGroups).sort((a, b) => {
      return this.groups.indexOf(a) - this.groups.indexOf(b);
    });
    const firstSourceGroupIndex = this.groups.indexOf(sortedSourceGroups[0]);
    const position = firstSourceGroupIndex < targetGroupIndex ? "after" : "before";
    const insertIndex = position === "after" ? targetGroupIndex + 1 : targetGroupIndex;
    this.groups.splice(insertIndex, 0, ...sortedSourceGroups);
    for (const sourceGroup of sortedSourceGroups) {
      const originSourceGroupIndex = position === "after" ? this.groups.indexOf(sourceGroup) : this.groups.lastIndexOf(sourceGroup);
      this.groups.splice(originSourceGroupIndex, 1);
    }
    this.y.fire();
  }
  moveGroupToEnd(source) {
    source = $5b(source);
    const sourceGroups = this.N(source);
    if (sourceGroups.size === 0) {
      return;
    }
    const lastInstanceIndex = this.groups.length - 1;
    const sortedSourceGroups = Array.from(sourceGroups).sort((a, b) => {
      return this.groups.indexOf(a) - this.groups.indexOf(b);
    });
    this.groups.splice(lastInstanceIndex + 1, 0, ...sortedSourceGroups);
    for (const sourceGroup of sortedSourceGroups) {
      const sourceGroupIndex = this.groups.indexOf(sourceGroup);
      this.groups.splice(sourceGroupIndex, 1);
    }
    this.y.fire();
  }
  moveInstance(source, target, side) {
    const sourceGroup = this.getGroupForInstance(source);
    const targetGroup = this.getGroupForInstance(target);
    if (!sourceGroup || !targetGroup) {
      return;
    }
    if (sourceGroup !== targetGroup) {
      sourceGroup.removeInstance(source);
      targetGroup.addInstance(source);
    }
    const index = targetGroup.terminalInstances.indexOf(target) + (side === "after" ? 1 : 0);
    targetGroup.moveInstance(source, index, side);
  }
  unsplitInstance(instance2) {
    const oldGroup = this.getGroupForInstance(instance2);
    if (!oldGroup || oldGroup.terminalInstances.length < 2) {
      return;
    }
    oldGroup.removeInstance(instance2);
    this.createGroup(instance2);
  }
  joinInstances(instances) {
    const group2 = this.getGroupForInstance(instances[0]);
    if (group2) {
      let differentGroups = true;
      for (let i2 = 1; i2 < group2.terminalInstances.length; i2++) {
        if (group2.terminalInstances.includes(instances[i2])) {
          differentGroups = false;
          break;
        }
      }
      if (!differentGroups && group2.terminalInstances.length === instances.length) {
        return;
      }
    }
    let candidateInstance = void 0;
    let candidateGroup = void 0;
    for (const instance2 of instances) {
      const group3 = this.getGroupForInstance(instance2);
      if (group3?.terminalInstances.length === 1) {
        candidateInstance = instance2;
        candidateGroup = group3;
        break;
      }
    }
    if (!candidateGroup) {
      candidateGroup = this.createGroup();
    }
    const wasActiveGroup = this.activeGroup === candidateGroup;
    for (const instance2 of instances) {
      if (instance2 === candidateInstance) {
        continue;
      }
      const oldGroup = this.getGroupForInstance(instance2);
      if (!oldGroup) {
        continue;
      }
      oldGroup.removeInstance(instance2);
      candidateGroup.addInstance(instance2);
    }
    this.setActiveInstance(instances[0]);
    this.y.fire();
    if (!wasActiveGroup) {
      this.m.fire(this.activeGroup);
    }
  }
  instanceIsSplit(instance2) {
    const group2 = this.getGroupForInstance(instance2);
    if (!group2) {
      return false;
    }
    return group2.terminalInstances.length > 1;
  }
  getGroupForInstance(instance2) {
    return this.groups.find((group2) => group2.terminalInstances.includes(instance2));
  }
  getGroupLabels() {
    return this.groups.filter((group2) => group2.terminalInstances.length > 0).map((group2, index) => {
      return `${index + 1}: ${group2.title ? group2.title : ""}`;
    });
  }
  /**
   * Visibility should be updated in the following cases:
   * 1. Toggle `TERMINAL_VIEW_ID` visibility
   * 2. Change active group
   * 3. Change instances in active group
   */
  updateVisibility() {
    const visible = this.G.isViewVisible($7X);
    this.groups.forEach((g, i2) => g.setVisible(visible && i2 === this.activeGroupIndex));
  }
};
$jfc = __decorate([
  __param(0, $on),
  __param(1, $Pk),
  __param(2, $uob),
  __param(3, $$M),
  __param(4, $1M)
], $jfc);

// out-build/vs/platform/terminal/common/capabilities/naiveCwdDetectionCapability.js
var $kfc = class {
  constructor(a) {
    this.a = a;
    this.type = 1;
    this.b = "";
    this.c = new $ze();
    this.onDidChangeCwd = this.c.event;
  }
  async getCwd() {
    if (!this.a) {
      return Promise.resolve("");
    }
    const newCwd = await this.a.getCwd();
    if (newCwd !== this.b) {
      this.c.fire(newCwd);
    }
    this.b = newCwd;
    return this.b;
  }
};

// out-build/vs/platform/terminal/common/terminalRecorder.js
var Constants14;
(function(Constants27) {
  Constants27[Constants27["MaxRecorderDataSize"] = 10485760] = "MaxRecorderDataSize";
})(Constants14 || (Constants14 = {}));
var $lfc = class {
  constructor(cols, rows) {
    this.b = 0;
    this.a = [{ cols, rows, data: [] }];
  }
  handleResize(cols, rows) {
    if (this.a.length > 0) {
      const lastEntry = this.a[this.a.length - 1];
      if (lastEntry.data.length === 0) {
        this.a.pop();
      }
    }
    if (this.a.length > 0) {
      const lastEntry = this.a[this.a.length - 1];
      if (lastEntry.cols === cols && lastEntry.rows === rows) {
        return;
      }
      if (lastEntry.cols === 0 && lastEntry.rows === 0) {
        lastEntry.cols = cols;
        lastEntry.rows = rows;
        return;
      }
    }
    this.a.push({ cols, rows, data: [] });
  }
  handleData(data) {
    const lastEntry = this.a[this.a.length - 1];
    lastEntry.data.push(data);
    this.b += data.length;
    while (this.b > 10485760) {
      const firstEntry = this.a[0];
      const remainingToDelete = this.b - 10485760;
      if (remainingToDelete >= firstEntry.data[0].length) {
        this.b -= firstEntry.data[0].length;
        firstEntry.data.shift();
        if (firstEntry.data.length === 0) {
          this.a.shift();
        }
      } else {
        firstEntry.data[0] = firstEntry.data[0].substr(remainingToDelete);
        this.b -= remainingToDelete;
      }
    }
  }
  generateReplayEventSync() {
    this.a.forEach((entry) => {
      if (entry.data.length > 0) {
        entry.data = [entry.data.join("")];
      }
    });
    return {
      events: this.a.map((entry) => ({ cols: entry.cols, rows: entry.rows, data: entry.data[0] ?? "" })),
      // No command restoration is needed when relaunching terminals
      commands: {
        isWindowsPty: false,
        commands: [],
        promptInputModel: void 0
      }
    };
  }
  async generateReplayEvent() {
    return this.generateReplayEventSync();
  }
};

// out-build/vs/workbench/contrib/terminal/browser/environmentVariableInfo.js
var $mfc = class $mfc2 {
  constructor(a, b, c, d, f) {
    this.a = a;
    this.b = b;
    this.c = c;
    this.d = d;
    this.f = f;
    this.requiresAction = true;
  }
  g(scope) {
    const extSet = /* @__PURE__ */ new Set();
    addExtensionIdentifiers(extSet, this.a.added.values());
    addExtensionIdentifiers(extSet, this.a.removed.values());
    addExtensionIdentifiers(extSet, this.a.changed.values());
    let message = localize(10372, null);
    message += getMergedDescription(this.c, scope, this.f, extSet);
    return message;
  }
  h() {
    return [{
      label: localize(10373, null),
      run: () => this.d.getInstanceFromId(this.b)?.relaunch(),
      commandId: "workbench.action.terminal.relaunch"
      /* TerminalCommandId.Relaunch */
    }];
  }
  getStatus(scope) {
    return {
      id: "relaunch-needed",
      severity: severity_default.Warning,
      icon: $6l.warning,
      tooltip: this.g(scope),
      hoverActions: this.h()
    };
  }
};
$mfc = __decorate([
  __param(3, $4Pb),
  __param(4, $wN)
], $mfc);
var $nfc = class $nfc2 {
  constructor(a, b, c) {
    this.a = a;
    this.b = b;
    this.c = c;
    this.requiresAction = false;
  }
  d(scope) {
    const extSet = /* @__PURE__ */ new Set();
    addExtensionIdentifiers(extSet, this.a.getVariableMap(scope).values());
    let message = localize(10374, null);
    message += getMergedDescription(this.a, scope, this.c, extSet);
    return message;
  }
  f(scope) {
    return [{
      label: localize(10375, null),
      run: () => this.b.executeCommand("workbench.action.terminal.showEnvironmentContributions", scope),
      commandId: "workbench.action.terminal.showEnvironmentContributions"
      /* TerminalCommandId.ShowEnvironmentContributions */
    }];
  }
  getStatus(scope) {
    return {
      id: "env-var-info-changes-active",
      severity: severity_default.Info,
      tooltip: this.d(scope),
      hoverActions: this.f(scope)
    };
  }
};
$nfc = __decorate([
  __param(1, $sn),
  __param(2, $wN)
], $nfc);
function getMergedDescription(collection, scope, extensionService, extSet) {
  const message = ["\n"];
  const globalDescriptions = collection.getDescriptionMap(void 0);
  const workspaceDescriptions = collection.getDescriptionMap(scope);
  for (const ext of extSet) {
    const globalDescription = globalDescriptions.get(ext);
    if (globalDescription) {
      message.push(`
- \`${getExtensionName(ext, extensionService)}\``);
      message.push(`: ${globalDescription}`);
    }
    const workspaceDescription = workspaceDescriptions.get(ext);
    if (workspaceDescription) {
      const workspaceSuffix = globalDescription ? ` (${localize(10376, null)})` : "";
      message.push(`
- \`${getExtensionName(ext, extensionService)}${workspaceSuffix}\``);
      message.push(`: ${workspaceDescription}`);
    }
    if (!globalDescription && !workspaceDescription) {
      message.push(`
- \`${getExtensionName(ext, extensionService)}\``);
    }
  }
  return message.join("");
}
function addExtensionIdentifiers(extSet, diff3) {
  for (const mutators of diff3) {
    for (const mutator of mutators) {
      extSet.add(mutator.extensionIdentifier);
    }
  }
}
function getExtensionName(id2, extensionService) {
  return extensionService.extensions.find((e) => e.id === id2)?.displayName || id2;
}

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

// out-build/vs/platform/terminal/common/environmentVariableCollection.js
var mutatorTypeToLabelMap = /* @__PURE__ */ new Map([
  [EnvironmentVariableMutatorType2.Append, "APPEND"],
  [EnvironmentVariableMutatorType2.Prepend, "PREPEND"],
  [EnvironmentVariableMutatorType2.Replace, "REPLACE"]
]);
var $HB = class {
  constructor(collections) {
    this.collections = collections;
    this.a = /* @__PURE__ */ new Map();
    this.b = /* @__PURE__ */ new Map();
    collections.forEach((collection, extensionIdentifier) => {
      this.d(collection, extensionIdentifier);
      const it = collection.map.entries();
      let next = it.next();
      while (!next.done) {
        const mutator = next.value[1];
        const key2 = next.value[0];
        let entry = this.a.get(key2);
        if (!entry) {
          entry = [];
          this.a.set(key2, entry);
        }
        if (entry.length > 0 && entry[0].type === EnvironmentVariableMutatorType2.Replace) {
          next = it.next();
          continue;
        }
        const extensionMutator = {
          extensionIdentifier,
          value: mutator.value,
          type: mutator.type,
          scope: mutator.scope,
          variable: mutator.variable,
          options: mutator.options
        };
        if (!extensionMutator.scope) {
          delete extensionMutator.scope;
        }
        entry.unshift(extensionMutator);
        next = it.next();
      }
    });
  }
  async applyToProcessEnvironment(env3, scope, variableResolver) {
    let lowerToActualVariableNames;
    if ($l) {
      lowerToActualVariableNames = {};
      Object.keys(env3).forEach((e) => lowerToActualVariableNames[e.toLowerCase()] = e);
    }
    for (const [variable, mutators] of this.getVariableMap(scope)) {
      const actualVariable = $l ? lowerToActualVariableNames[variable.toLowerCase()] || variable : variable;
      for (const mutator of mutators) {
        const value = variableResolver ? await variableResolver(mutator.value) : mutator.value;
        if (mutator.options?.applyAtProcessCreation ?? true) {
          switch (mutator.type) {
            case EnvironmentVariableMutatorType2.Append:
              env3[actualVariable] = (env3[actualVariable] || "") + value;
              break;
            case EnvironmentVariableMutatorType2.Prepend:
              env3[actualVariable] = value + (env3[actualVariable] || "");
              break;
            case EnvironmentVariableMutatorType2.Replace:
              env3[actualVariable] = value;
              break;
          }
        }
        if (mutator.options?.applyAtShellIntegration ?? false) {
          const key2 = `VSCODE_ENV_${mutatorTypeToLabelMap.get(mutator.type)}`;
          env3[key2] = (env3[key2] ? env3[key2] + ":" : "") + variable + "=" + this.c(value);
        }
      }
    }
  }
  c(value) {
    return value.replaceAll(":", "\\x3a");
  }
  diff(other, scope) {
    const added = /* @__PURE__ */ new Map();
    const changed = /* @__PURE__ */ new Map();
    const removed = /* @__PURE__ */ new Map();
    other.getVariableMap(scope).forEach((otherMutators, variable) => {
      const currentMutators = this.getVariableMap(scope).get(variable);
      const result = getMissingMutatorsFromArray(otherMutators, currentMutators);
      if (result) {
        added.set(variable, result);
      }
    });
    this.getVariableMap(scope).forEach((currentMutators, variable) => {
      const otherMutators = other.getVariableMap(scope).get(variable);
      const result = getMissingMutatorsFromArray(currentMutators, otherMutators);
      if (result) {
        removed.set(variable, result);
      }
    });
    this.getVariableMap(scope).forEach((currentMutators, variable) => {
      const otherMutators = other.getVariableMap(scope).get(variable);
      const result = getChangedMutatorsFromArray(currentMutators, otherMutators);
      if (result) {
        changed.set(variable, result);
      }
    });
    if (added.size === 0 && changed.size === 0 && removed.size === 0) {
      return void 0;
    }
    return { added, changed, removed };
  }
  getVariableMap(scope) {
    const result = /* @__PURE__ */ new Map();
    for (const mutators of this.a.values()) {
      const filteredMutators = mutators.filter((m) => filterScope(m, scope));
      if (filteredMutators.length > 0) {
        result.set(filteredMutators[0].variable, filteredMutators);
      }
    }
    return result;
  }
  getDescriptionMap(scope) {
    const result = /* @__PURE__ */ new Map();
    for (const mutators of this.b.values()) {
      const filteredMutators = mutators.filter((m) => filterScope(m, scope, true));
      for (const mutator of filteredMutators) {
        result.set(mutator.extensionIdentifier, mutator.description);
      }
    }
    return result;
  }
  d(collection, extensionIdentifier) {
    if (!collection.descriptionMap) {
      return;
    }
    const it = collection.descriptionMap.entries();
    let next = it.next();
    while (!next.done) {
      const mutator = next.value[1];
      const key2 = next.value[0];
      let entry = this.b.get(key2);
      if (!entry) {
        entry = [];
        this.b.set(key2, entry);
      }
      const extensionMutator = {
        extensionIdentifier,
        scope: mutator.scope,
        description: mutator.description
      };
      if (!extensionMutator.scope) {
        delete extensionMutator.scope;
      }
      entry.push(extensionMutator);
      next = it.next();
    }
  }
};
function filterScope(mutator, scope, strictFilter = false) {
  if (!mutator.scope) {
    if (strictFilter) {
      return scope === mutator.scope;
    }
    return true;
  }
  if (mutator.scope.workspaceFolder && scope?.workspaceFolder && mutator.scope.workspaceFolder.index === scope.workspaceFolder.index) {
    return true;
  }
  return false;
}
function getMissingMutatorsFromArray(current, other) {
  if (!other) {
    return current;
  }
  const otherMutatorExtensions = /* @__PURE__ */ new Set();
  other.forEach((m) => otherMutatorExtensions.add(m.extensionIdentifier));
  const result = [];
  current.forEach((mutator) => {
    if (!otherMutatorExtensions.has(mutator.extensionIdentifier)) {
      result.push(mutator);
    }
  });
  return result.length === 0 ? void 0 : result;
}
function getChangedMutatorsFromArray(current, other) {
  if (!other) {
    return void 0;
  }
  const otherMutatorExtensions = /* @__PURE__ */ new Map();
  other.forEach((m) => otherMutatorExtensions.set(m.extensionIdentifier, m));
  const result = [];
  current.forEach((mutator) => {
    const otherMutator = otherMutatorExtensions.get(mutator.extensionIdentifier);
    if (otherMutator && (mutator.type !== otherMutator.type || mutator.value !== otherMutator.value || mutator.scope?.workspaceFolder?.index !== otherMutator.scope?.workspaceFolder?.index)) {
      result.push(otherMutator);
    }
  });
  return result.length === 0 ? void 0 : result;
}

// 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 $Ex(env3, ...preserve) {
  const set = preserve.reduce((set2, key2) => {
    set2[key2] = true;
    return set2;
  }, {});
  const keysToRemove = [
    /^ELECTRON_.+$/,
    /^VSCODE_(?!(PORTABLE|SHELL_LOGIN|ENV_REPLACE|ENV_APPEND|ENV_PREPEND)).+$/,
    /^SNAP(|_.*)$/,
    /^GDK_PIXBUF_.+$/
  ];
  const envKeys = Object.keys(env3);
  envKeys.filter((key2) => !set[key2]).forEach((envKey) => {
    for (let i2 = 0; i2 < keysToRemove.length; i2++) {
      if (envKey.search(keysToRemove[i2]) !== -1) {
        delete env3[envKey];
        break;
      }
    }
  });
}

// out-build/vs/workbench/contrib/terminal/common/terminalEnvironment.js
function $uY(parent, other) {
  if (!other) {
    return;
  }
  if ($l) {
    for (const configKey in other) {
      let actualKey = configKey;
      for (const envKey in parent) {
        if (configKey.toLowerCase() === envKey.toLowerCase()) {
          actualKey = envKey;
          break;
        }
      }
      const value = other[configKey];
      if (value !== void 0) {
        _mergeEnvironmentValue(parent, actualKey, value);
      }
    }
  } else {
    Object.keys(other).forEach((key2) => {
      const value = other[key2];
      if (value !== void 0) {
        _mergeEnvironmentValue(parent, key2, value);
      }
    });
  }
}
function _mergeEnvironmentValue(env3, key2, value) {
  if (typeof value === "string") {
    env3[key2] = value;
  } else {
    delete env3[key2];
  }
}
function $vY(env3, version2, locale, detectLocale) {
  env3["TERM_PROGRAM"] = "vscode";
  if (version2) {
    env3["TERM_PROGRAM_VERSION"] = version2;
  }
  if ($wY(env3, detectLocale)) {
    env3["LANG"] = $xY(locale);
  }
  env3["COLORTERM"] = "truecolor";
}
function mergeNonNullKeys(env3, other) {
  if (!other) {
    return;
  }
  for (const key2 of Object.keys(other)) {
    const value = other[key2];
    if (value !== void 0 && value !== null) {
      env3[key2] = value;
    }
  }
}
async function resolveConfigurationVariables(variableResolver, env3) {
  await Promise.all(Object.entries(env3).map(async ([key2, value]) => {
    if (typeof value === "string") {
      try {
        env3[key2] = await variableResolver(value);
      } catch (e) {
        env3[key2] = value;
      }
    }
  }));
  return env3;
}
function $wY(env3, detectLocale) {
  if (detectLocale === "on") {
    return true;
  }
  if (detectLocale === "auto") {
    const lang = env3["LANG"];
    return !lang || lang.search(/\.UTF\-8$/) === -1 && lang.search(/\.utf8$/) === -1 && lang.search(/\.euc.+/) === -1;
  }
  return false;
}
function $xY(locale) {
  const parts = locale ? locale.split("-") : [];
  const n = parts.length;
  if (n === 0) {
    return "en_US.UTF-8";
  }
  if (n === 1) {
    const languageVariants = {
      af: "ZA",
      am: "ET",
      be: "BY",
      bg: "BG",
      ca: "ES",
      cs: "CZ",
      da: "DK",
      // de: 'AT',
      // de: 'CH',
      de: "DE",
      el: "GR",
      // en: 'AU',
      // en: 'CA',
      // en: 'GB',
      // en: 'IE',
      // en: 'NZ',
      en: "US",
      es: "ES",
      et: "EE",
      eu: "ES",
      fi: "FI",
      // fr: 'BE',
      // fr: 'CA',
      // fr: 'CH',
      fr: "FR",
      he: "IL",
      hr: "HR",
      hu: "HU",
      hy: "AM",
      is: "IS",
      // it: 'CH',
      it: "IT",
      ja: "JP",
      kk: "KZ",
      ko: "KR",
      lt: "LT",
      // nl: 'BE',
      nl: "NL",
      no: "NO",
      pl: "PL",
      pt: "BR",
      // pt: 'PT',
      ro: "RO",
      ru: "RU",
      sk: "SK",
      sl: "SI",
      sr: "YU",
      sv: "SE",
      tr: "TR",
      uk: "UA",
      zh: "CN"
    };
    if (parts[0] in languageVariants) {
      parts.push(languageVariants[parts[0]]);
    }
  } else {
    parts[1] = parts[1].toUpperCase();
  }
  return parts.join("_") + ".UTF-8";
}
async function $yY(shell, userHome, variableResolver, root, customCwd, logService) {
  if (shell.cwd) {
    const unresolved = typeof shell.cwd === "object" ? shell.cwd.fsPath : shell.cwd;
    const resolved = await _resolveCwd(unresolved, variableResolver);
    return $rY(resolved || unresolved);
  }
  let cwd2;
  if (!shell.ignoreConfigurationCwd && customCwd) {
    if (variableResolver) {
      customCwd = await _resolveCwd(customCwd, variableResolver, logService);
    }
    if (customCwd) {
      if ($mc(customCwd)) {
        cwd2 = customCwd;
      } else if (root) {
        cwd2 = $nc(root.fsPath, customCwd);
      }
    }
  }
  if (!cwd2) {
    cwd2 = root ? root.fsPath : userHome || "";
  }
  return $rY(cwd2);
}
async function _resolveCwd(cwd2, variableResolver, logService) {
  if (variableResolver) {
    try {
      return await variableResolver(cwd2);
    } catch (e) {
      logService?.error("Could not resolve terminal cwd", e);
      return void 0;
    }
  }
  return cwd2;
}
function $zY(lastActiveWorkspace, env3, configurationResolverService) {
  if (!configurationResolverService) {
    return void 0;
  }
  return (str) => configurationResolverService.resolveWithEnvironment(env3, lastActiveWorkspace, str);
}
async function $AY(shellLaunchConfig, envFromConfig, variableResolver, version2, detectLocale, baseEnv) {
  const env3 = {};
  if (shellLaunchConfig.strictEnv) {
    mergeNonNullKeys(env3, shellLaunchConfig.env);
  } else {
    mergeNonNullKeys(env3, baseEnv);
    const allowedEnvFromConfig = { ...envFromConfig };
    if (variableResolver) {
      if (allowedEnvFromConfig) {
        await resolveConfigurationVariables(variableResolver, allowedEnvFromConfig);
      }
      if (shellLaunchConfig.env) {
        await resolveConfigurationVariables(variableResolver, shellLaunchConfig.env);
      }
    }
    if ($m) {
      if (env3["VSCODE_NODE_OPTIONS"]) {
        env3["NODE_OPTIONS"] = env3["VSCODE_NODE_OPTIONS"];
        delete env3["VSCODE_NODE_OPTIONS"];
      }
      if (env3["VSCODE_NODE_REPL_EXTERNAL_MODULE"]) {
        env3["NODE_REPL_EXTERNAL_MODULE"] = env3["VSCODE_NODE_REPL_EXTERNAL_MODULE"];
        delete env3["VSCODE_NODE_REPL_EXTERNAL_MODULE"];
      }
    }
    $Ex(env3, "VSCODE_IPC_HOOK_CLI");
    $uY(env3, allowedEnvFromConfig);
    $uY(env3, shellLaunchConfig.env);
    $vY(env3, version2, $z, detectLocale);
  }
  return env3;
}
async function $BY(resource, executable, title, shellType, backend, os, isWindowsFrontend = $l) {
  let originalPath;
  if ($zg(resource)) {
    originalPath = resource;
  } else {
    originalPath = resource.fsPath;
    if (isWindowsFrontend && os !== 1) {
      originalPath = originalPath.replace(/\\/g, "/");
    } else if (!isWindowsFrontend && os === 1) {
      originalPath = originalPath.replace(/\//g, "\\");
    }
  }
  if (!executable) {
    return originalPath;
  }
  const hasSpace = originalPath.includes(" ");
  const hasParens = originalPath.includes("(") || originalPath.includes(")");
  const pathBasename = $rc(executable, ".exe");
  const isPowerShell = pathBasename === "pwsh" || title === "pwsh" || pathBasename === "powershell" || title === "powershell";
  if (isPowerShell && (hasSpace || originalPath.includes("'"))) {
    return `& '${originalPath.replace(/'/g, "''")}'`;
  }
  if (hasParens && isPowerShell) {
    return `& '${originalPath}'`;
  }
  if (os === 1) {
    if (shellType !== void 0) {
      if (shellType === "gitbash") {
        return $pY(originalPath.replace(/\\/g, "/"));
      } else if (shellType === "wsl") {
        return backend?.getWslPath(originalPath, "win-to-unix") || originalPath;
      } else if (hasSpace) {
        return `"${originalPath}"`;
      }
      return originalPath;
    }
    const lowerExecutable = executable.toLowerCase();
    if (lowerExecutable.includes("wsl") || lowerExecutable.includes("bash.exe") && !lowerExecutable.toLowerCase().includes("git")) {
      return backend?.getWslPath(originalPath, "win-to-unix") || originalPath;
    } else if (hasSpace) {
      return `"${originalPath}"`;
    }
    return originalPath;
  }
  return $pY(originalPath);
}
function $CY(cwd2, workspaceContextService, historyService) {
  const cwdUri = typeof cwd2 === "string" ? URI.parse(cwd2) : cwd2;
  let workspaceFolder = cwdUri ? workspaceContextService.getWorkspaceFolder(cwdUri) ?? void 0 : void 0;
  if (!workspaceFolder) {
    const activeWorkspaceRootUri = historyService.getLastActiveWorkspaceRoot();
    workspaceFolder = activeWorkspaceRootUri ? workspaceContextService.getWorkspaceFolder(activeWorkspaceRootUri) ?? void 0 : void 0;
  }
  return workspaceFolder;
}

// out-build/vs/workbench/contrib/terminal/browser/terminalProcessManager.js
var ProcessConstants;
(function(ProcessConstants2) {
  ProcessConstants2[ProcessConstants2["ErrorLaunchThresholdDuration"] = 500] = "ErrorLaunchThresholdDuration";
  ProcessConstants2[ProcessConstants2["LatencyMeasuringInterval"] = 1e3] = "LatencyMeasuringInterval";
})(ProcessConstants || (ProcessConstants = {}));
var ProcessType;
(function(ProcessType2) {
  ProcessType2[ProcessType2["Process"] = 0] = "Process";
  ProcessType2[ProcessType2["PsuedoTerminal"] = 1] = "PsuedoTerminal";
})(ProcessType || (ProcessType = {}));
var $ofc = class $ofc2 extends $3c {
  get persistentProcessId() {
    return this.b?.id;
  }
  get shouldPersist() {
    return !!this.reconnectionProperties || (this.b ? this.b.shouldPersist : false);
  }
  get hasWrittenData() {
    return this.n;
  }
  get hasChildProcesses() {
    return this.r;
  }
  get reconnectionProperties() {
    return this.z?.attachPersistentProcess?.reconnectionProperties || this.z?.reconnectionProperties || void 0;
  }
  get extEnvironmentVariableCollection() {
    return this.j;
  }
  constructor(R, cwd2, environmentVariableCollections, shellIntegrationNonce, S, U, W, X, Y, Z, $149, ab, bb, cb, db, eb, fb, gb, hb, ib) {
    super();
    this.R = R;
    this.S = S;
    this.U = U;
    this.W = W;
    this.X = X;
    this.Y = Y;
    this.Z = Z;
    this.$ = $149;
    this.ab = ab;
    this.bb = bb;
    this.cb = cb;
    this.db = db;
    this.eb = eb;
    this.fb = fb;
    this.gb = gb;
    this.hb = hb;
    this.ib = ib;
    this.processState = 1;
    this.capabilities = this.B(new $zPb());
    this.a = false;
    this.b = null;
    this.f = 0;
    this.g = [];
    this.n = false;
    this.r = false;
    this.t = false;
    this.y = false;
    this.C = { cols: 0, rows: 0 };
    this.D = this.B(new $ze());
    this.onPtyDisconnect = this.D.event;
    this.F = this.B(new $ze());
    this.onPtyReconnect = this.F.event;
    this.G = this.B(new $ze());
    this.onProcessReady = this.G.event;
    this.H = this.B(new $ze());
    this.onProcessStateChange = this.H.event;
    this.I = this.B(new $ze());
    this.onBeforeProcessData = this.I.event;
    this.J = this.B(new $ze());
    this.onProcessData = this.J.event;
    this.L = this.B(new $ze());
    this.onProcessReplayComplete = this.L.event;
    this.M = this.B(new $ze());
    this.onDidChangeProperty = this.M.event;
    this.N = this.B(new $ze());
    this.onEnvironmentVariableInfoChanged = this.N.event;
    this.O = this.B(new $ze());
    this.onProcessExit = this.O.event;
    this.P = this.B(new $ze());
    this.onRestoreCommands = this.P.event;
    this.Q = $CY(cwd2, this.X, this.S);
    this.ptyProcessReady = this.jb();
    this.m = new AckDataBufferer((e) => this.b?.acknowledgeDataEvent(e));
    this.u = this.B(this.U.createInstance(SeamlessRelaunchDataFilter));
    this.B(this.u.onProcessData((ev) => {
      const data = typeof ev === "string" ? ev : ev.data;
      const beforeProcessDataEvent = { data };
      this.I.fire(beforeProcessDataEvent);
      if (beforeProcessDataEvent.data && beforeProcessDataEvent.data.length > 0) {
        if (typeof ev !== "string") {
          ev.data = beforeProcessDataEvent.data;
        }
        this.J.fire(typeof ev !== "string" ? ev : { data: beforeProcessDataEvent.data, trackCommit: false });
      }
    }));
    if (cwd2 && typeof cwd2 === "object") {
      this.remoteAuthority = $8v(cwd2);
    } else {
      this.remoteAuthority = this.Z.remoteAuthority;
    }
    if (environmentVariableCollections) {
      this.j = new $HB(environmentVariableCollections);
      this.B(this.cb.onDidChangeCollections((newCollection) => this.qb(newCollection)));
      this.environmentVariableInfo = this.U.createInstance($nfc, this.j);
      this.N.fire(this.environmentVariableInfo);
    }
    this.shellIntegrationNonce = shellIntegrationNonce ?? $ps();
  }
  async freePortKillProcess(port) {
    try {
      if (this.b?.freePortKillProcess) {
        await this.b?.freePortKillProcess(port);
      }
    } catch (e) {
      this.ib.notify({ message: localize(10518, null, port, e), severity: severity_default.Warning });
    }
  }
  dispose(immediate = false) {
    this.a = true;
    if (this.b) {
      this.pb(
        5
        /* ProcessState.KilledByUser */
      );
      this.b.shutdown(immediate);
      this.b = null;
    }
    super.dispose();
  }
  jb() {
    return new Promise((c) => {
      const listener = Event2.once(this.onProcessReady)(() => {
        this.W.debug(`Terminal process ready (shellProcessId: ${this.shellProcessId})`);
        this.q.delete(listener);
        c(void 0);
      });
      this.q.add(listener);
    });
  }
  async detachFromProcess(forcePersist) {
    await this.b?.detach?.(forcePersist);
    this.b = null;
  }
  async createProcess(shellLaunchConfig, cols, rows, reset = true) {
    this.z = shellLaunchConfig;
    this.C.cols = cols;
    this.C.rows = rows;
    let newProcess;
    if (shellLaunchConfig.customPtyImplementation) {
      this.f = 1;
      newProcess = shellLaunchConfig.customPtyImplementation(this.R, cols, rows);
    } else {
      const backend = await this.gb.getBackend(this.remoteAuthority);
      if (!backend) {
        throw new Error(`No terminal backend registered for remote authority '${this.remoteAuthority}'`);
      }
      this.backend = backend;
      const variableResolver = $zY(this.Q, await this.eb.getEnvironment(this.remoteAuthority), this.Y);
      this.userHome = this.bb.resolvedUserHome?.fsPath;
      this.os = OS;
      if (!!this.remoteAuthority) {
        const userHomeUri = await this.bb.userHome();
        this.userHome = userHomeUri.path;
        const remoteEnv = await this.ab.getEnvironment();
        if (!remoteEnv) {
          throw new Error(`Failed to get remote environment for remote authority "${this.remoteAuthority}"`);
        }
        this.userHome = remoteEnv.userHome.path;
        this.os = remoteEnv.os;
        const env3 = await this.kb(backend, variableResolver, shellLaunchConfig);
        const shouldPersist = (this.fb.getValue(
          "task.reconnection"
          /* TaskSettingId.Reconnection */
        ) && shellLaunchConfig.reconnectionProperties || !shellLaunchConfig.isFeatureTerminal) && this.db.config.enablePersistentSessions && !shellLaunchConfig.isTransient;
        if (shellLaunchConfig.attachPersistentProcess) {
          const result2 = await backend.attachToProcess(shellLaunchConfig.attachPersistentProcess.id);
          if (result2) {
            newProcess = result2;
          } else {
            this.W.warn(`Attach to process failed for terminal`, shellLaunchConfig.attachPersistentProcess);
            shellLaunchConfig.attachPersistentProcess = void 0;
          }
        }
        if (!newProcess) {
          await this.eb.resolveShellLaunchConfig(shellLaunchConfig, {
            remoteAuthority: this.remoteAuthority,
            os: this.os
          });
          const options3 = {
            shellIntegration: {
              enabled: this.fb.getValue(
                "terminal.integrated.shellIntegration.enabled"
                /* TerminalSettingId.ShellIntegrationEnabled */
              ),
              suggestEnabled: this.fb.getValue(
                "terminal.integrated.suggest.enabled"
                /* TerminalContribSettingId.SuggestEnabled */
              ),
              nonce: this.shellIntegrationNonce
            },
            windowsEnableConpty: this.db.config.windowsEnableConpty,
            windowsUseConptyDll: this.db.config.experimental?.windowsUseConptyDll ?? false,
            environmentVariableCollections: this.j?.collections ? $FB(this.j.collections) : void 0,
            workspaceFolder: this.Q
          };
          try {
            newProcess = await backend.createProcess(
              shellLaunchConfig,
              "",
              // TODO: Fix cwd
              cols,
              rows,
              this.db.config.unicodeVersion,
              env3,
              // TODO:
              options3,
              shouldPersist
            );
          } catch (e) {
            if (e?.message === "Could not fetch remote environment") {
              this.W.trace(`Could not fetch remote environment, silently failing`);
              return void 0;
            }
            throw e;
          }
        }
        if (!this.a) {
          this.mb(backend);
        }
      } else {
        if (shellLaunchConfig.attachPersistentProcess) {
          const result2 = shellLaunchConfig.attachPersistentProcess.findRevivedId ? await backend.attachToRevivedProcess(shellLaunchConfig.attachPersistentProcess.id) : await backend.attachToProcess(shellLaunchConfig.attachPersistentProcess.id);
          if (result2) {
            newProcess = result2;
          } else {
            this.W.warn(`Attach to process failed for terminal`, shellLaunchConfig.attachPersistentProcess);
            shellLaunchConfig.attachPersistentProcess = void 0;
          }
        }
        if (!newProcess) {
          newProcess = await this.lb(backend, shellLaunchConfig, cols, rows, this.userHome, variableResolver);
        }
        if (!this.a) {
          this.mb(backend);
        }
      }
    }
    if (this.a) {
      newProcess.shutdown(false);
      return void 0;
    }
    this.b = newProcess;
    this.pb(
      2
      /* ProcessState.Launching */
    );
    if (this.os === 3 || this.os === 2) {
      this.capabilities.add(1, new $kfc(this.b));
    }
    this.u.newProcess(this.b, reset);
    if (this.w) {
      $Xc(this.w);
    }
    this.w = [
      newProcess.onProcessReady((e) => {
        this.shellProcessId = e.pid;
        this.h = e.cwd;
        this.M.fire({ type: "initialCwd", value: this.h });
        this.G.fire(e);
        if (this.g.length > 0 && this.b) {
          newProcess.input(this.g.join(""));
          this.g.length = 0;
        }
      }),
      newProcess.onProcessExit((exitCode) => this.ob(exitCode)),
      newProcess.onDidChangeProperty(({ type, value }) => {
        switch (type) {
          case "hasChildProcesses":
            this.r = value;
            break;
          case "failedShellIntegrationActivation":
            this.hb?.publicLog2("terminal/shellIntegrationActivationFailureCustomArgs");
            break;
        }
        this.M.fire({ type, value });
      })
    ];
    if (newProcess.onProcessReplayComplete) {
      this.w.push(newProcess.onProcessReplayComplete(() => this.L.fire()));
    }
    if (newProcess.onRestoreCommands) {
      this.w.push(newProcess.onRestoreCommands((e) => this.P.fire(e)));
    }
    setTimeout(
      () => {
        if (this.processState === 2) {
          this.pb(
            3
            /* ProcessState.Running */
          );
        }
      },
      500
      /* ProcessConstants.ErrorLaunchThresholdDuration */
    );
    const result = await newProcess.start();
    if (result) {
      return result;
    }
    $gj($Qj(), () => {
      this.backend?.getLatency().then((measurements) => {
        this.W.info(`Latency measurements for ${this.remoteAuthority ?? "local"} backend
${measurements.map((e) => `${e.label}: ${e.latency.toFixed(2)}ms`).join("\n")}`);
      });
    });
    return void 0;
  }
  async relaunch(shellLaunchConfig, cols, rows, reset) {
    this.ptyProcessReady = this.jb();
    this.W.trace(`Relaunching terminal instance ${this.R}`);
    if (this.y) {
      this.y = false;
      this.F.fire();
    }
    this.n = false;
    return this.createProcess(shellLaunchConfig, cols, rows, reset);
  }
  // Fetch any extension environment additions and apply them
  async kb(backend, variableResolver, shellLaunchConfig) {
    const workspaceFolder = $CY(shellLaunchConfig.cwd, this.X, this.S);
    const platformKey = $l ? "windows" : $m ? "osx" : "linux";
    const envFromConfigValue = this.fb.getValue(`terminal.integrated.env.${platformKey}`);
    let baseEnv;
    if (shellLaunchConfig.useShellEnvironment) {
      baseEnv = await backend.getShellEnvironment();
    } else {
      baseEnv = await this.eb.getEnvironment(this.remoteAuthority);
    }
    const env3 = await $AY(shellLaunchConfig, envFromConfigValue, variableResolver, this.$.version, this.db.config.detectLocale, baseEnv);
    if (!this.a && $sY(shellLaunchConfig)) {
      this.j = this.cb.mergedCollection;
      this.B(this.cb.onDidChangeCollections((newCollection) => this.qb(newCollection)));
      await this.j.applyToProcessEnvironment(env3, { workspaceFolder }, variableResolver);
      if (this.j.getVariableMap({ workspaceFolder }).size) {
        this.environmentVariableInfo = this.U.createInstance($nfc, this.j);
        this.N.fire(this.environmentVariableInfo);
      }
    }
    return env3;
  }
  async lb(backend, shellLaunchConfig, cols, rows, userHome, variableResolver) {
    await this.eb.resolveShellLaunchConfig(shellLaunchConfig, {
      remoteAuthority: void 0,
      os: OS
    });
    const activeWorkspaceRootUri = this.S.getLastActiveWorkspaceRoot(Schemas.file);
    const initialCwd = await $yY(shellLaunchConfig, userHome, variableResolver, activeWorkspaceRootUri, this.db.config.cwd, this.W);
    const env3 = await this.kb(backend, variableResolver, shellLaunchConfig);
    const options3 = {
      shellIntegration: {
        enabled: this.fb.getValue(
          "terminal.integrated.shellIntegration.enabled"
          /* TerminalSettingId.ShellIntegrationEnabled */
        ),
        suggestEnabled: this.fb.getValue(
          "terminal.integrated.suggest.enabled"
          /* TerminalContribSettingId.SuggestEnabled */
        ),
        nonce: this.shellIntegrationNonce
      },
      windowsEnableConpty: this.db.config.windowsEnableConpty,
      windowsUseConptyDll: this.db.config.experimental?.windowsUseConptyDll ?? false,
      environmentVariableCollections: this.j ? $FB(this.j.collections) : void 0,
      workspaceFolder: this.Q
    };
    const shouldPersist = (this.fb.getValue(
      "task.reconnection"
      /* TaskSettingId.Reconnection */
    ) && shellLaunchConfig.reconnectionProperties || !shellLaunchConfig.isFeatureTerminal) && this.db.config.enablePersistentSessions && !shellLaunchConfig.isTransient;
    return await backend.createProcess(shellLaunchConfig, initialCwd, cols, rows, this.db.config.unicodeVersion, env3, options3, shouldPersist);
  }
  mb(backend) {
    if (this.t) {
      return;
    }
    this.t = true;
    this.B(backend.onPtyHostUnresponsive(() => {
      this.y = true;
      this.D.fire();
    }));
    this.s = backend.onPtyHostResponsive(() => {
      this.y = false;
      this.F.fire();
    });
    this.B($1c(() => this.s?.dispose()));
    this.B(backend.onPtyHostRestart(async () => {
      if (!this.y) {
        this.y = true;
        this.D.fire();
      }
      this.s?.dispose();
      this.s = void 0;
      if (this.z) {
        if (this.z.isFeatureTerminal && !this.reconnectionProperties) {
          this.ob(-1);
        } else {
          const message = localize(10519, null);
          this.J.fire({ data: $W0b(message, { loudFormatting: true }), trackCommit: false });
          await this.relaunch(this.z, this.C.cols, this.C.rows, false);
        }
      }
    }));
  }
  async getBackendOS() {
    let os = OS;
    if (!!this.remoteAuthority) {
      const remoteEnv = await this.ab.getEnvironment();
      if (!remoteEnv) {
        throw new Error(`Failed to get remote environment for remote authority "${this.remoteAuthority}"`);
      }
      os = remoteEnv.os;
    }
    return os;
  }
  setDimensions(cols, rows, sync) {
    if (sync) {
      this.nb(cols, rows);
      return;
    }
    return this.ptyProcessReady.then(() => this.nb(cols, rows));
  }
  async setUnicodeVersion(version2) {
    return this.b?.setUnicodeVersion(version2);
  }
  nb(cols, rows) {
    if (!this.b) {
      return;
    }
    try {
      this.b.resize(cols, rows);
    } catch (error) {
      if (error.code !== "EPIPE" && error.code !== "ERR_IPC_CHANNEL_CLOSED") {
        throw error;
      }
    }
    this.C.cols = cols;
    this.C.rows = rows;
  }
  async write(data) {
    await this.ptyProcessReady;
    this.u.disableSeamlessRelaunch();
    this.n = true;
    if (this.shellProcessId || this.f === 1) {
      if (this.b) {
        this.b.input(data);
      }
    } else {
      this.g.push(data);
    }
  }
  async processBinary(data) {
    await this.ptyProcessReady;
    this.u.disableSeamlessRelaunch();
    this.n = true;
    this.b?.processBinary(data);
  }
  get initialCwd() {
    return this.h ?? "";
  }
  async refreshProperty(type) {
    if (!this.b) {
      throw new Error("Cannot refresh property when process is not set");
    }
    return this.b.refreshProperty(type);
  }
  async updateProperty(type, value) {
    return this.b?.updateProperty(type, value);
  }
  acknowledgeDataEvent(charCount) {
    this.m.ack(charCount);
  }
  ob(exitCode) {
    this.b = null;
    if (this.processState === 2) {
      this.pb(
        4
        /* ProcessState.KilledDuringLaunch */
      );
    }
    if (this.processState === 3) {
      this.pb(
        6
        /* ProcessState.KilledByProcess */
      );
    }
    this.O.fire(exitCode);
  }
  pb(state) {
    this.processState = state;
    this.H.fire();
  }
  qb(newCollection) {
    const diff3 = this.j.diff(newCollection, { workspaceFolder: this.Q });
    if (diff3 === void 0) {
      if (this.environmentVariableInfo instanceof $mfc) {
        this.environmentVariableInfo = this.U.createInstance($nfc, this.j);
        this.N.fire(this.environmentVariableInfo);
      }
      return;
    }
    this.environmentVariableInfo = this.U.createInstance($mfc, diff3, this.R, newCollection);
    this.N.fire(this.environmentVariableInfo);
  }
  async clearBuffer() {
    this.b?.clearBuffer?.();
  }
};
$ofc = __decorate([
  __param(4, $tY),
  __param(5, $Pk),
  __param(6, $8x),
  __param(7, $Zk),
  __param(8, $nY),
  __param(9, $US),
  __param(10, $Vu),
  __param(11, $RL),
  __param(12, $aT),
  __param(13, $NX),
  __param(14, $5Pb),
  __param(15, $fY),
  __param(16, $kl),
  __param(17, $8Pb),
  __param(18, $zv),
  __param(19, $PJ)
], $ofc);
var AckDataBufferer = class {
  constructor(b) {
    this.b = b;
    this.a = 0;
  }
  ack(charCount) {
    this.a += charCount;
    while (this.a > 5e3) {
      this.a -= 5e3;
      this.b(
        5e3
        /* FlowControlConstants.CharCountAckSize */
      );
    }
  }
};
var SeamlessRelaunchConstants;
(function(SeamlessRelaunchConstants2) {
  SeamlessRelaunchConstants2[SeamlessRelaunchConstants2["RecordTerminalDuration"] = 1e4] = "RecordTerminalDuration";
  SeamlessRelaunchConstants2[SeamlessRelaunchConstants2["SwapWaitMaximumDuration"] = 3e3] = "SwapWaitMaximumDuration";
})(SeamlessRelaunchConstants || (SeamlessRelaunchConstants = {}));
var SeamlessRelaunchDataFilter = class SeamlessRelaunchDataFilter2 extends $3c {
  get onProcessData() {
    return this.r.event;
  }
  constructor(s) {
    super();
    this.s = s;
    this.m = false;
    this.r = this.B(new $ze());
  }
  newProcess(process2, reset) {
    this.h?.dispose();
    this.j?.shutdown(false);
    this.j = process2;
    if (!this.a || !reset || this.m) {
      this.f?.dispose();
      [this.a, this.f] = this.u(process2);
      if (this.m && reset) {
        this.r.fire("\x1Bc");
      }
      this.h = process2.onProcessData((e) => this.r.fire(e));
      this.m = false;
      return;
    }
    if (this.b) {
      this.triggerSwap();
    }
    this.n = $Y.setTimeout(
      () => this.triggerSwap(),
      3e3
      /* SeamlessRelaunchConstants.SwapWaitMaximumDuration */
    );
    this.h?.dispose();
    this.f?.dispose();
    const recorder = this.u(process2);
    [this.b, this.g] = recorder;
  }
  /**
   * Disables seamless relaunch for the active process
   */
  disableSeamlessRelaunch() {
    this.m = true;
    this.t();
    this.triggerSwap();
  }
  /**
   * Trigger the swap of the processes if needed (eg. timeout, input)
   */
  triggerSwap() {
    if (this.n) {
      $Y.clearTimeout(this.n);
      this.n = void 0;
    }
    if (!this.a) {
      return;
    }
    if (!this.b) {
      this.a = void 0;
      this.f?.dispose();
      return;
    }
    const firstData = this.w(this.a);
    const secondData = this.w(this.b);
    if (firstData === secondData) {
      this.s.trace(`Seamless terminal relaunch - identical content`);
    } else {
      this.s.trace(`Seamless terminal relaunch - resetting content`);
      this.r.fire({ data: `\x1Bc${secondData}`, trackCommit: false });
    }
    this.h?.dispose();
    this.h = this.j.onProcessData((e) => this.r.fire(e));
    this.a = this.b;
    this.f?.dispose();
    this.f = this.g;
    this.b = void 0;
  }
  t() {
    if (this.n) {
      return;
    }
    this.a = void 0;
    this.f?.dispose();
    this.b = void 0;
    this.g?.dispose();
  }
  u(process2) {
    const recorder = new $lfc(0, 0);
    const disposable = process2.onProcessData((e) => recorder.handleData(typeof e === "string" ? e : e.data));
    return [recorder, disposable];
  }
  w(recorder) {
    return recorder.generateReplayEventSync().events.filter((e) => !!e.data).map((e) => e.data).join("");
  }
};
SeamlessRelaunchDataFilter = __decorate([
  __param(0, $8x)
], SeamlessRelaunchDataFilter);

// out-build/vs/workbench/contrib/terminal/browser/terminalStatusList.js
var TerminalStatus;
(function(TerminalStatus2) {
  TerminalStatus2["Bell"] = "bell";
  TerminalStatus2["Disconnected"] = "disconnected";
  TerminalStatus2["RelaunchNeeded"] = "relaunch-needed";
  TerminalStatus2["EnvironmentVariableInfoChangesActive"] = "env-var-info-changes-active";
  TerminalStatus2["ShellIntegrationAttentionNeeded"] = "shell-integration-attention-needed";
})(TerminalStatus || (TerminalStatus = {}));
var $8Ob = class $8Ob2 extends $3c {
  get onDidAddStatus() {
    return this.c.event;
  }
  get onDidRemoveStatus() {
    return this.f.event;
  }
  get onDidChangePrimaryStatus() {
    return this.g.event;
  }
  constructor(h3) {
    super();
    this.h = h3;
    this.a = /* @__PURE__ */ new Map();
    this.b = /* @__PURE__ */ new Map();
    this.c = this.B(new $ze());
    this.f = this.B(new $ze());
    this.g = this.B(new $ze());
  }
  get primary() {
    let result;
    for (const s of this.a.values()) {
      if (!result || s.severity >= result.severity) {
        if (s.icon || !result?.icon) {
          result = s;
        }
      }
    }
    return result;
  }
  get statuses() {
    return Array.from(this.a.values());
  }
  add(status, duration) {
    status = this.j(status);
    const outTimeout = this.b.get(status.id);
    if (outTimeout) {
      $Y.clearTimeout(outTimeout);
      this.b.delete(status.id);
    }
    if (duration && duration > 0) {
      const timeout = $Y.setTimeout(() => this.remove(status), duration);
      this.b.set(status.id, timeout);
    }
    const existingStatus = this.a.get(status.id);
    if (existingStatus && existingStatus !== status) {
      this.f.fire(existingStatus);
      this.a.delete(existingStatus.id);
    }
    if (!this.a.has(status.id)) {
      const oldPrimary = this.primary;
      this.a.set(status.id, status);
      this.c.fire(status);
      const newPrimary = this.primary;
      if (oldPrimary !== newPrimary) {
        this.g.fire(newPrimary);
      }
    }
  }
  remove(statusOrId) {
    const status = typeof statusOrId === "string" ? this.a.get(statusOrId) : statusOrId;
    if (status && this.a.get(status.id)) {
      const wasPrimary = this.primary?.id === status.id;
      this.a.delete(status.id);
      this.f.fire(status);
      if (wasPrimary) {
        this.g.fire(this.primary);
      }
    }
  }
  toggle(status, value) {
    if (value) {
      this.add(status);
    } else {
      this.remove(status);
    }
  }
  j(status) {
    if (!status.icon || ThemeIcon.getModifier(status.icon) !== "spin" || this.h.getValue(
      "terminal.integrated.tabs.enableAnimation"
      /* TerminalSettingId.TabsEnableAnimation */
    )) {
      return status;
    }
    let icon2;
    if (status.icon.id === $ds.id) {
      icon2 = $6l.play;
    } else {
      icon2 = ThemeIcon.modify(status.icon, void 0);
    }
    return {
      ...status,
      icon: icon2
    };
  }
};
$8Ob = __decorate([
  __param(0, $kl)
], $8Ob);
function $9Ob(severity) {
  switch (severity) {
    case severity_default.Error:
      return $xr;
    case severity_default.Warning:
      return $yr;
    default:
      return "";
  }
}

// out-build/vs/workbench/contrib/terminal/browser/xterm/lineDataEventAddon.js
var $pfc = class extends $3c {
  constructor(f) {
    super();
    this.f = f;
    this.b = false;
    this.c = this.B(new $ze());
    this.onLineData = this.c.event;
  }
  async activate(xterm) {
    this.a = xterm;
    const buffer = xterm.buffer;
    await this.f;
    this.B(xterm.onLineFeed(() => {
      const newLine = buffer.active.getLine(buffer.active.baseY + buffer.active.cursorY);
      if (newLine && !newLine.isWrapped) {
        this.g(buffer.active, buffer.active.baseY + buffer.active.cursorY - 1);
      }
    }));
    this.B($1c(() => {
      this.g(buffer.active, buffer.active.baseY + buffer.active.cursorY);
    }));
  }
  setOperatingSystem(os) {
    if (this.b || !this.a) {
      return;
    }
    this.b = true;
    if (os === 1) {
      const xterm = this.a;
      this.B(xterm.parser.registerCsiHandler({ final: "H" }, () => {
        const buffer = xterm.buffer;
        this.g(buffer.active, buffer.active.baseY + buffer.active.cursorY);
        return false;
      }));
    }
  }
  g(buffer, lineIndex) {
    let line = buffer.getLine(lineIndex);
    if (!line) {
      return;
    }
    let lineData = line.translateToString(true);
    while (lineIndex > 0 && line.isWrapped) {
      line = buffer.getLine(--lineIndex);
      if (!line) {
        break;
      }
      lineData = line.translateToString(false) + lineData;
    }
    this.c.fire(lineData);
  }
};

// out-build/vs/base/browser/ui/icons/iconSelectBox.js
var $V2 = class _$V2 extends $3c {
  static {
    this.a = 0;
  }
  constructor(t) {
    super();
    this.t = t;
    this.domId = `icon_select_box_id_${++_$V2.a}`;
    this.b = this.B(new $ze());
    this.onDidSelect = this.b.event;
    this.c = [];
    this.f = 0;
    this.g = 1;
    this.r = 36;
    this.s = 36;
    this.domNode = $(".icon-select-box");
    this.B(this.u());
  }
  u() {
    const disposables = new $2c();
    const iconSelectBoxContainer = $bk(this.domNode, $(".icon-select-box-container"));
    iconSelectBoxContainer.style.margin = "10px 15px";
    const iconSelectInputContainer = $bk(iconSelectBoxContainer, $(".icon-select-input-container"));
    iconSelectInputContainer.style.paddingBottom = "10px";
    this.h = disposables.add(new $I2(iconSelectInputContainer, void 0, {
      placeholder: localize(17, null),
      inputBoxStyles: this.t.inputBoxStyles
    }));
    const iconsContainer = this.m = $(".icon-select-icons-container", { id: `${this.domId}_icons` });
    iconsContainer.role = "listbox";
    iconsContainer.tabIndex = 0;
    this.j = disposables.add(new $CZ(iconsContainer, {
      useShadows: false,
      horizontal: 2
    }));
    $bk(iconSelectBoxContainer, this.j.getDomNode());
    if (this.t.showIconInfo) {
      this.n = this.B(new $S2($bk($bk(iconSelectBoxContainer, $(".icon-select-id-container")), $(".icon-select-id-label"))));
    }
    const iconsDisposables = disposables.add(new $4c());
    iconsDisposables.value = this.w(this.t.icons, [], iconsContainer);
    this.j.scanDomNode();
    disposables.add(this.h.onDidChange((value) => {
      const icons2 = [], matches = [];
      for (const icon2 of this.t.icons) {
        const match = this.C(value, icon2.id);
        if (match) {
          icons2.push(icon2);
          matches.push(match);
        }
      }
      if (icons2.length) {
        iconsDisposables.value = this.w(icons2, matches, iconsContainer);
        this.j?.scanDomNode();
      }
    }));
    this.h.inputElement.role = "combobox";
    this.h.inputElement.ariaHasPopup = "menu";
    this.h.inputElement.ariaAutoComplete = "list";
    this.h.inputElement.ariaExpanded = "true";
    this.h.inputElement.setAttribute("aria-controls", iconsContainer.id);
    return disposables;
  }
  w(icons2, matches, container2) {
    const disposables = new $2c();
    $$i(container2);
    const focusedIcon = this.c[this.f]?.icon;
    let focusedIconIndex = 0;
    const renderedIcons = [];
    if (icons2.length) {
      for (let index = 0; index < icons2.length; index++) {
        const icon2 = icons2[index];
        const iconContainer = $bk(container2, $(".icon-container", { id: `${this.domId}_icons_${index}` }));
        iconContainer.style.width = `${this.r}px`;
        iconContainer.style.height = `${this.s}px`;
        iconContainer.title = icon2.id;
        iconContainer.role = "button";
        iconContainer.setAttribute("aria-setsize", `${icons2.length}`);
        iconContainer.setAttribute("aria-posinset", `${index + 1}`);
        $bk(iconContainer, $(ThemeIcon.asCSSSelector(icon2)));
        renderedIcons.push({ icon: icon2, element: iconContainer, highlightMatches: matches[index] });
        disposables.add($_i(iconContainer, $7j.CLICK, (e) => {
          e.stopPropagation();
          this.setSelection(index);
        }));
        if (icon2 === focusedIcon) {
          focusedIconIndex = index;
        }
      }
    } else {
      const noResults = localize(18, null);
      $bk(container2, $(".icon-no-results", void 0, noResults));
      $$Z(noResults);
    }
    this.c.splice(0, this.c.length, ...renderedIcons);
    this.y(focusedIconIndex);
    return disposables;
  }
  y(index) {
    const existing = this.c[this.f];
    if (existing) {
      existing.element.classList.remove("focused");
    }
    this.f = index;
    const renderedItem = this.c[index];
    if (renderedItem) {
      renderedItem.element.classList.add("focused");
    }
    if (this.h) {
      if (renderedItem) {
        this.h.inputElement.setAttribute("aria-activedescendant", renderedItem.element.id);
      } else {
        this.h.inputElement.removeAttribute("aria-activedescendant");
      }
    }
    if (this.n) {
      if (renderedItem) {
        this.n.set(renderedItem.icon.id, renderedItem.highlightMatches);
      } else {
        this.n.set("");
      }
    }
    this.z(index);
  }
  z(index) {
    if (!this.j) {
      return;
    }
    if (index < 0 || index >= this.c.length) {
      return;
    }
    const element = this.c[index].element;
    if (!element) {
      return;
    }
    const { height } = this.j.getScrollDimensions();
    const { scrollTop } = this.j.getScrollPosition();
    if (element.offsetTop + this.s > scrollTop + height) {
      this.j.setScrollPosition({ scrollTop: element.offsetTop + this.s - height });
    } else if (element.offsetTop < scrollTop) {
      this.j.setScrollPosition({ scrollTop: element.offsetTop });
    }
  }
  C(word, wordToMatchAgainst) {
    const matchIndex = wordToMatchAgainst.toLowerCase().indexOf(word.toLowerCase());
    if (matchIndex !== -1) {
      return [{ start: matchIndex, end: matchIndex + word.length }];
    }
    return null;
  }
  layout(dimension) {
    this.domNode.style.width = `${dimension.width}px`;
    this.domNode.style.height = `${dimension.height}px`;
    const iconsContainerWidth = dimension.width - 30;
    this.g = Math.floor(iconsContainerWidth / this.r);
    if (this.g === 0) {
      throw new Error("Insufficient width");
    }
    const extraSpace = iconsContainerWidth % this.r;
    const iconElementMargin = Math.floor(extraSpace / this.g);
    for (const { element } of this.c) {
      element.style.marginRight = `${iconElementMargin}px`;
    }
    const containerPadding = extraSpace % this.g;
    if (this.m) {
      this.m.style.paddingLeft = `${Math.floor(containerPadding / 2)}px`;
      this.m.style.paddingRight = `${Math.ceil(containerPadding / 2)}px`;
    }
    if (this.j) {
      this.j.getDomNode().style.height = `${this.n ? dimension.height - 80 : dimension.height - 40}px`;
      this.j.scanDomNode();
    }
  }
  getFocus() {
    return [this.f];
  }
  setSelection(index) {
    if (index < 0 || index >= this.c.length) {
      throw new Error(`Invalid index ${index}`);
    }
    this.y(index);
    this.b.fire(this.c[index].icon);
  }
  clearInput() {
    if (this.h) {
      this.h.value = "";
    }
  }
  focus() {
    this.h?.focus();
    this.y(0);
  }
  focusNext() {
    this.y((this.f + 1) % this.c.length);
  }
  focusPrevious() {
    this.y((this.f - 1 + this.c.length) % this.c.length);
  }
  focusNextRow() {
    let nextRowIndex = this.f + this.g;
    if (nextRowIndex >= this.c.length) {
      nextRowIndex = (nextRowIndex + 1) % this.g;
      nextRowIndex = nextRowIndex >= this.c.length ? 0 : nextRowIndex;
    }
    this.y(nextRowIndex);
  }
  focusPreviousRow() {
    let previousRowIndex = this.f - this.g;
    if (previousRowIndex < 0) {
      const numberOfRows = Math.floor(this.c.length / this.g);
      previousRowIndex = this.f + this.g * numberOfRows - 1;
      previousRowIndex = previousRowIndex < 0 ? this.c.length - 1 : previousRowIndex >= this.c.length ? previousRowIndex - this.g : previousRowIndex;
    }
    this.y(previousRowIndex);
  }
  getFocusedIcon() {
    return this.c[this.f].icon;
  }
};

// out-build/vs/workbench/services/userDataProfile/browser/iconSelectBox.js
var $tfc_1;
var $qfc = new $nn("iconSelectBoxFocus", true);
var $rfc = new $nn("iconSelectBoxInputFocus", true);
var $sfc = new $nn("iconSelectBoxInputEmpty", true);
var $tfc = class $tfc2 extends $V2 {
  static {
    $tfc_1 = this;
  }
  static getFocusedWidget() {
    return $tfc_1.D;
  }
  constructor(options3, contextKeyService) {
    super(options3);
    this.F = this.B(contextKeyService.createScoped(this.domNode));
    $qfc.bindTo(this.F);
    this.G = $rfc.bindTo(this.F);
    this.H = $sfc.bindTo(this.F);
    if (this.h) {
      const focusTracker = this.B($_j(this.h.inputElement));
      this.B(focusTracker.onDidFocus(() => this.G.set(true)));
      this.B(focusTracker.onDidBlur(() => this.G.set(false)));
      this.B(this.h.onDidChange(() => this.H.set(this.h?.value.length === 0)));
    }
  }
  focus() {
    super.focus();
    $tfc_1.D = this;
  }
};
$tfc = $tfc_1 = __decorate([
  __param(1, $on)
], $tfc);
$0I.registerCommandAndKeybindingRule({
  id: "iconSelectBox.focusUp",
  weight: 200,
  when: $qfc,
  primary: 16,
  handler: () => {
    const selectBox = $tfc.getFocusedWidget();
    if (selectBox) {
      selectBox.focusPreviousRow();
    }
  }
});
$0I.registerCommandAndKeybindingRule({
  id: "iconSelectBox.focusDown",
  weight: 200,
  when: $qfc,
  primary: 18,
  handler: () => {
    const selectBox = $tfc.getFocusedWidget();
    if (selectBox) {
      selectBox.focusNextRow();
    }
  }
});
$0I.registerCommandAndKeybindingRule({
  id: "iconSelectBox.focusNext",
  weight: 200,
  when: $7m.and($qfc, $7m.or($sfc, $rfc.toNegated())),
  primary: 17,
  handler: () => {
    const selectBox = $tfc.getFocusedWidget();
    if (selectBox) {
      selectBox.focusNext();
    }
  }
});
$0I.registerCommandAndKeybindingRule({
  id: "iconSelectBox.focusPrevious",
  weight: 200,
  when: $7m.and($qfc, $7m.or($sfc, $rfc.toNegated())),
  primary: 15,
  handler: () => {
    const selectBox = $tfc.getFocusedWidget();
    if (selectBox) {
      selectBox.focusPrevious();
    }
  }
});
$0I.registerCommandAndKeybindingRule({
  id: "iconSelectBox.selectFocused",
  weight: 200,
  when: $qfc,
  primary: 3,
  handler: () => {
    const selectBox = $tfc.getFocusedWidget();
    if (selectBox) {
      selectBox.setSelection(selectBox.getFocus()[0]);
    }
  }
});

// out-build/vs/workbench/contrib/terminal/browser/terminalIconPicker.js
var icons = new $sf(() => {
  const iconDefinitions = $0r().getIcons();
  const includedChars = /* @__PURE__ */ new Set();
  const dedupedIcons = iconDefinitions.filter((e) => {
    if (e.id === $3l.blank.id) {
      return false;
    }
    if (!("fontCharacter" in e.defaults)) {
      return false;
    }
    if (includedChars.has(e.defaults.fontCharacter)) {
      return false;
    }
    includedChars.add(e.defaults.fontCharacter);
    return true;
  });
  return dedupedIcons;
});
var $ufc = class $ufc2 extends $3c {
  constructor(instantiationService, b) {
    super();
    this.b = b;
    this.a = instantiationService.createInstance($tfc, {
      icons: icons.value,
      inputBoxStyles: $B$,
      showIconInfo: true
    });
  }
  async pickIcons() {
    const dimension = new $rj(486, 260);
    return new Promise((resolve) => {
      this.B(this.a.onDidSelect((e) => {
        resolve(e);
        this.a.dispose();
      }));
      this.a.clearInput();
      const hoverWidget = this.b.showHover({
        content: this.a.domNode,
        target: $Pj().body,
        position: {
          hoverPosition: 2
        },
        persistence: {
          sticky: true
        },
        appearance: {
          showPointer: true
        }
      }, true);
      if (hoverWidget) {
        this.B(hoverWidget);
      }
      this.a.layout(dimension);
      this.a.focus();
    });
  }
};
$ufc = __decorate([
  __param(0, $Pk),
  __param(1, $5$)
], $ufc);

// out-build/vs/workbench/contrib/terminal/browser/terminalResizeDebouncer.js
var Constants15;
(function(Constants27) {
  Constants27[Constants27["StartDebouncingThreshold"] = 200] = "StartDebouncingThreshold";
})(Constants15 || (Constants15 = {}));
var $vfc = class extends $3c {
  constructor(g, h3, j, m, n) {
    super();
    this.g = g;
    this.h = h3;
    this.j = j;
    this.m = m;
    this.n = n;
    this.a = 0;
    this.b = 0;
    this.c = this.B(new $4c());
    this.f = this.B(new $4c());
  }
  async resize(cols, rows, immediate) {
    this.a = cols;
    this.b = rows;
    if (immediate || this.h().raw.buffer.normal.length < 200) {
      this.c.clear();
      this.f.clear();
      this.j(cols, rows);
      return;
    }
    const win = getWindow(this.h().raw.element);
    if (win && !this.g()) {
      if (!this.c.value) {
        this.c.value = $gj(win, async () => {
          this.m(this.a);
          this.c.clear();
        });
      }
      if (!this.f.value) {
        this.f.value = $gj(win, async () => {
          this.n(this.b);
          this.f.clear();
        });
      }
      return;
    }
    this.n(rows);
    this.a = cols;
    this.r(cols);
  }
  flush() {
    if (this.c.value || this.f.value) {
      this.c.clear();
      this.f.clear();
      this.j(this.a, this.b);
    }
  }
  r(cols) {
    this.m(cols);
  }
};
__decorate([
  $$t(100)
], $vfc.prototype, "r", null);

// out-build/vs/workbench/contrib/terminal/browser/terminalInstance.js
var $wfc_1;
var Constants16;
(function(Constants27) {
  Constants27[Constants27["WaitForContainerThreshold"] = 100] = "WaitForContainerThreshold";
  Constants27[Constants27["DefaultCols"] = 80] = "DefaultCols";
  Constants27[Constants27["DefaultRows"] = 30] = "DefaultRows";
  Constants27[Constants27["MaxCanvasWidth"] = 4096] = "MaxCanvasWidth";
})(Constants16 || (Constants16 = {}));
var xtermConstructor;
var shellIntegrationSupportedShellTypes = [
  "bash",
  "zsh",
  "pwsh",
  "python"
];
var $wfc = class $wfc2 extends $3c {
  static {
    $wfc_1 = this;
  }
  static {
    this.f = 1;
  }
  get domElement() {
    return this.M;
  }
  get usedShellIntegrationInjection() {
    return this.xb;
  }
  pauseInputEvents(barrier) {
    this.Bb = barrier;
  }
  get store() {
    return this.q;
  }
  get extEnvironmentVariableCollection() {
    return this.h.extEnvironmentVariableCollection;
  }
  get waitOnExit() {
    return this.cc.attachPersistentProcess?.waitOnExit || this.cc.waitOnExit;
  }
  set waitOnExit(value) {
    this.cc.waitOnExit = value;
  }
  get targetRef() {
    return this.Cb;
  }
  get target() {
    return this.Cb.object;
  }
  set target(value) {
    this.Cb.object = value;
    this.Xb.fire(value);
  }
  get instanceId() {
    return this.t;
  }
  get resource() {
    return this.m;
  }
  get cols() {
    if (this.X !== void 0) {
      return this.X;
    }
    if (this.db && this.db.cols) {
      if (this.db.forceExactSize) {
        return this.db.cols;
      }
      return Math.min(Math.max(this.db.cols, 2), this.U);
    }
    return this.U;
  }
  get rows() {
    if (this.Y !== void 0) {
      return this.Y;
    }
    if (this.db && this.db.rows) {
      if (this.db.forceExactSize) {
        return this.db.rows;
      }
      return Math.min(Math.max(this.db.rows, 2), this.W);
    }
    return this.W;
  }
  get isDisposed() {
    return this.q.isDisposed;
  }
  get fixedCols() {
    return this.X;
  }
  get fixedRows() {
    return this.Y;
  }
  get maxCols() {
    return this.U;
  }
  get maxRows() {
    return this.W;
  }
  // TODO: Ideally processId would be merged into processReady
  get processId() {
    return this.h.shellProcessId;
  }
  // TODO: How does this work with detached processes?
  // TODO: Should this be an event as it can fire twice?
  get processReady() {
    return this.h.ptyProcessReady;
  }
  get hasChildProcesses() {
    return this.shellLaunchConfig.attachPersistentProcess?.hasChildProcesses || this.h.hasChildProcesses;
  }
  get reconnectionProperties() {
    return this.shellLaunchConfig.attachPersistentProcess?.reconnectionProperties || this.shellLaunchConfig.reconnectionProperties;
  }
  get areLinksReady() {
    return this.eb;
  }
  get initialDataEvents() {
    return this.gb;
  }
  get exitCode() {
    return this.D;
  }
  get exitReason() {
    return this.F;
  }
  get hadFocusOnExit() {
    return this.z;
  }
  get isTitleSetByProcess() {
    return !!this.kb.value;
  }
  get shellLaunchConfig() {
    return this.cc;
  }
  get shellType() {
    return this.H;
  }
  get os() {
    return this.h.os;
  }
  get isRemote() {
    return this.h.remoteAuthority !== void 0;
  }
  get remoteAuthority() {
    return this.h.remoteAuthority;
  }
  get hasFocus() {
    return $Nj(this.M);
  }
  get title() {
    return this.I;
  }
  get titleSource() {
    return this.J;
  }
  get icon() {
    return this.Cc();
  }
  get color() {
    return this.Dc();
  }
  get processName() {
    return this.qb;
  }
  get sequence() {
    return this.rb;
  }
  get staticTitle() {
    return this.sb;
  }
  get workspaceFolder() {
    return this.tb;
  }
  get cwd() {
    return this.Z;
  }
  get initialCwd() {
    return this.$;
  }
  get description() {
    if (this.pb) {
      return this.pb;
    }
    const type = this.shellLaunchConfig.attachPersistentProcess?.type || this.shellLaunchConfig.type;
    switch (type) {
      case "Task":
        return $Kec.typeTask;
      case "Local":
        return $Kec.typeLocal;
      default:
        return void 0;
    }
  }
  get userHome() {
    return this.vb;
  }
  get shellIntegrationNonce() {
    return this.h.shellIntegrationNonce;
  }
  get injectedArgs() {
    return this.ab;
  }
  constructor(bc, cc, dc, ec, instantiationService, fc, gc, hc, ic, jc, kc, lc, mc, nc, oc, pc, qc, rc, sc, workbenchEnvironmentService, tc, uc, vc, wc, xc, yc, zc, Ac, Bc) {
    super();
    this.bc = bc;
    this.cc = cc;
    this.dc = dc;
    this.ec = ec;
    this.fc = fc;
    this.gc = gc;
    this.hc = hc;
    this.ic = ic;
    this.jc = jc;
    this.kc = kc;
    this.lc = lc;
    this.mc = mc;
    this.nc = nc;
    this.oc = oc;
    this.pc = pc;
    this.qc = qc;
    this.rc = rc;
    this.sc = sc;
    this.tc = tc;
    this.uc = uc;
    this.vc = vc;
    this.wc = wc;
    this.xc = xc;
    this.yc = yc;
    this.zc = zc;
    this.Ac = Ac;
    this.Bc = Bc;
    this.j = /* @__PURE__ */ new Map();
    this.u = 0;
    this.w = 0;
    this.I = "";
    this.J = TitleEventSource.Process;
    this.U = 0;
    this.W = 0;
    this.Z = void 0;
    this.$ = void 0;
    this.ab = void 0;
    this.bb = true;
    this.eb = false;
    this.fb = this.B(new $4c());
    this.gb = [];
    this.kb = this.B(new $4c());
    this.mb = this.B(new $4c());
    this.qb = "";
    this.xb = false;
    this.capabilities = this.B(new $APb());
    this.disableLayout = false;
    this.Cb = new $0c(void 0);
    this.Db = new $ze();
    this.onExit = this.Db.event;
    this.Eb = this.B(new $ze());
    this.onDisposed = this.Eb.event;
    this.Fb = this.B(new $ze());
    this.onProcessIdReady = this.Fb.event;
    this.Gb = this.B(new $ze());
    this.onProcessReplayComplete = this.Gb.event;
    this.Hb = this.B(new $ze());
    this.onTitleChanged = this.Hb.event;
    this.Ib = this.B(new $ze());
    this.onIconChanged = this.Ib.event;
    this.Jb = this.B(new $ze());
    this.onWillData = this.Jb.event;
    this.Kb = this.B(new $ze());
    this.onData = this.Kb.event;
    this.Lb = this.B(new $ze());
    this.onBinary = this.Lb.event;
    this.Mb = this.B(new $ze());
    this.onRequestExtHostProcess = this.Mb.event;
    this.Nb = this.B(new $ze());
    this.onDimensionsChanged = this.Nb.event;
    this.Ob = this.B(new $ze());
    this.onMaximumDimensionsChanged = this.Ob.event;
    this.Pb = this.B(new $ze());
    this.onDidFocus = this.Pb.event;
    this.Qb = this.B(new $ze());
    this.onDidRequestFocus = this.Qb.event;
    this.Rb = this.B(new $ze());
    this.onDidBlur = this.Rb.event;
    this.Sb = this.B(new $ze());
    this.onDidInputData = this.Sb.event;
    this.Tb = this.B(new $ze());
    this.onDidChangeSelection = this.Tb.event;
    this.Ub = this.B(new $ze());
    this.onRequestAddInstanceToGroup = this.Ub.event;
    this.Vb = this.B(new $ze());
    this.onDidChangeHasChildProcesses = this.Vb.event;
    this.Wb = this.B(new $ze());
    this.onDidExecuteText = this.Wb.event;
    this.Xb = this.B(new $ze());
    this.onDidChangeTarget = this.Xb.event;
    this.Yb = this.B(new $ze());
    this.onDidSendText = this.Yb.event;
    this.Zb = this.B(new $ze());
    this.onDidChangeShellType = this.Zb.event;
    this.$b = this.B(new $ze());
    this.onDidChangeVisibility = this.$b.event;
    this.ac = this.B(new $ze({
      onDidAddFirstListener: async () => (this.xterm ?? await this.n)?.raw.loadAddon(this.yb)
    }));
    this.onLineData = this.ac.event;
    this.M = document.createElement("div");
    this.M.classList.add("terminal-wrapper");
    this.lb = this.B(instantiationService.createInstance($X0b));
    this.G = [];
    this.y = false;
    this.z = false;
    this.C = false;
    this.t = $wfc_1.f++;
    this.ob = false;
    this.Y = cc.attachPersistentProcess?.fixedDimensions?.rows;
    this.X = cc.attachPersistentProcess?.fixedDimensions?.cols;
    this.m = $$ec(this.tc.getWorkspace().id, this.instanceId, this.title);
    if (this.cc.attachPersistentProcess?.hideFromUser) {
      this.cc.hideFromUser = this.cc.attachPersistentProcess.hideFromUser;
    }
    if (this.cc.attachPersistentProcess?.isFeatureTerminal) {
      this.cc.isFeatureTerminal = this.cc.attachPersistentProcess.isFeatureTerminal;
    }
    if (this.cc.attachPersistentProcess?.type) {
      this.cc.type = this.cc.attachPersistentProcess.type;
    }
    if (this.shellLaunchConfig.cwd) {
      const cwdUri = typeof this.cc.cwd === "string" ? URI.from({
        scheme: Schemas.file,
        path: this.cc.cwd
      }) : this.cc.cwd;
      if (cwdUri) {
        this.tb = this.tc.getWorkspaceFolder(cwdUri) ?? void 0;
      }
    }
    if (!this.tb) {
      const activeWorkspaceRootUri = this.wc.getLastActiveWorkspaceRoot();
      this.tb = activeWorkspaceRootUri ? this.tc.getWorkspaceFolder(activeWorkspaceRootUri) ?? void 0 : void 0;
    }
    const scopedContextKeyService = this.B(dc.createScoped(this.M));
    this.zb = scopedContextKeyService;
    this.g = this.B(instantiationService.createChild(new $Ok([$on, scopedContextKeyService])));
    this.O = TerminalContextKeys.focus.bindTo(scopedContextKeyService);
    this.P = TerminalContextKeys.terminalHasFixedWidth.bindTo(scopedContextKeyService);
    this.Q = TerminalContextKeys.textSelected.bindTo(scopedContextKeyService);
    this.R = TerminalContextKeys.altBufferActive.bindTo(scopedContextKeyService);
    this.S = TerminalContextKeys.terminalShellIntegrationEnabled.bindTo(scopedContextKeyService);
    this.oc.trace(`terminalInstance#ctor (instanceId: ${this.instanceId})`, this.cc);
    this.B(this.capabilities.onDidAddCapabilityType((e) => this.oc.debug("terminalInstance added capability", e)));
    this.B(this.capabilities.onDidRemoveCapabilityType((e) => this.oc.debug("terminalInstance removed capability", e)));
    const capabilityListeners = this.B(new $_c());
    this.B(this.capabilities.onDidAddCapabilityType((capability) => {
      capabilityListeners.get(capability)?.dispose();
      if (capability === 0) {
        const cwdDetection = this.capabilities.get(capability);
        if (cwdDetection) {
          capabilityListeners.set(capability, cwdDetection.onDidChangeCwd((e) => {
            this.Z = e;
            this.rd(this.title, TitleEventSource.Config);
          }));
        }
      }
      if (capability === 2) {
        const commandDetection = this.capabilities.get(capability);
        if (commandDetection) {
          capabilityListeners.set(capability, Event2.any(commandDetection.promptInputModel.onDidStartInput, commandDetection.promptInputModel.onDidChangeInput, commandDetection.promptInputModel.onDidFinishInput)(() => this.ub?.refreshLabel(this)));
        }
      }
    }));
    this.B(this.capabilities.onDidRemoveCapabilityType((capability) => {
      capabilityListeners.get(capability)?.dispose();
    }));
    if (!this.shellLaunchConfig.executable && !workbenchEnvironmentService.remoteAuthority) {
      this.gc.resolveIcon(this.cc, OS);
    }
    this.jb = cc.attachPersistentProcess?.icon || cc.icon;
    if (this.shellLaunchConfig.customPtyImplementation) {
      this.rd(this.cc.name, TitleEventSource.Api);
    }
    this.statusList = this.B(this.g.createInstance($8Ob));
    this.Ec();
    this.h = this.Qc();
    this.hb = new $Vh(
      100
      /* Constants.WaitForContainerThreshold */
    );
    this.ib = new $Vh(1e3);
    this.n = this.Jc();
    this.n.then(async () => {
      await this.hb.wait();
      if (!this.shellLaunchConfig.customPtyImplementation && this.fc.config.shellIntegration?.enabled && !this.shellLaunchConfig.executable) {
        const os = await this.h.getBackendOS();
        const defaultProfile = await this.gc.getDefaultProfile({ remoteAuthority: this.remoteAuthority, os });
        this.shellLaunchConfig.executable = defaultProfile.path;
        this.shellLaunchConfig.args = defaultProfile.args;
        if (this.shellLaunchConfig.isExtensionOwnedTerminal) {
          this.shellLaunchConfig.icon ??= defaultProfile.icon;
          this.shellLaunchConfig.color ??= defaultProfile.color;
          this.shellLaunchConfig.env ??= defaultProfile.env;
        } else {
          this.shellLaunchConfig.icon = defaultProfile.icon;
          this.shellLaunchConfig.color = defaultProfile.color;
          this.shellLaunchConfig.env = defaultProfile.env;
        }
      }
      await this.Rc();
      if (this.shellLaunchConfig.attachPersistentProcess) {
        this.Z = this.shellLaunchConfig.attachPersistentProcess.cwd;
        this.rd(this.shellLaunchConfig.attachPersistentProcess.title, this.shellLaunchConfig.attachPersistentProcess.titleSource);
        this.setShellType(this.shellType);
      }
      if (this.X) {
        await this.kd();
      }
    }).catch((err) => {
      if (!this.isDisposed) {
        throw err;
      }
    });
    this.B(this.nc.onDidChangeConfiguration(async (e) => {
      if (e.affectsConfiguration(
        "accessibility.verbosity.terminal"
        /* AccessibilityVerbositySettingId.Terminal */
      )) {
        this.fd(this.xterm?.raw, this.t, this.title);
      }
      if (e.affectsConfiguration("terminal.integrated")) {
        this.updateConfig();
        this.setVisible(this.C);
      }
      const layoutSettings = [
        "terminal.integrated.fontSize",
        "terminal.integrated.fontFamily",
        "terminal.integrated.fontWeight",
        "terminal.integrated.fontWeightBold",
        "terminal.integrated.letterSpacing",
        "terminal.integrated.lineHeight",
        "editor.fontFamily"
      ];
      if (layoutSettings.some((id2) => e.affectsConfiguration(id2))) {
        this.bb = true;
        await this.dd();
      }
      if (e.affectsConfiguration(
        "terminal.integrated.unicodeVersion"
        /* TerminalSettingId.UnicodeVersion */
      )) {
        this.bd();
      }
      if (e.affectsConfiguration("editor.accessibilitySupport")) {
        this.updateAccessibilitySupport();
      }
      if (e.affectsConfiguration(
        "terminal.integrated.tabs.title"
        /* TerminalSettingId.TerminalTitle */
      ) || e.affectsConfiguration(
        "terminal.integrated.tabs.separator"
        /* TerminalSettingId.TerminalTitleSeparator */
      ) || e.affectsConfiguration(
        "terminal.integrated.tabs.description"
        /* TerminalSettingId.TerminalDescription */
      )) {
        this.ub?.refreshLabel(this);
      }
    }));
    this.B(this.tc.onDidChangeWorkspaceFolders(() => this.ub?.refreshLabel(this)));
    let initialDataEventsTimeout = getWindow(this.L).setTimeout(() => {
      initialDataEventsTimeout = void 0;
      this.gb = void 0;
      this.fb.clear();
    }, 1e4);
    this.B($1c(() => {
      if (initialDataEventsTimeout) {
        getWindow(this.L).clearTimeout(initialDataEventsTimeout);
      }
    }));
    const contributionDescs = TerminalExtensionsRegistry.getTerminalContributions();
    for (const desc of contributionDescs) {
      if (this.j.has(desc.id)) {
        $gb(new Error(`Cannot have two terminal contributions with the same id ${desc.id}`));
        continue;
      }
      let contribution;
      try {
        contribution = this.B(this.g.createInstance(desc.ctor, {
          instance: this,
          processManager: this.h,
          widgetManager: this.lb
        }));
        this.j.set(desc.id, contribution);
      } catch (err) {
        $gb(err);
      }
      this.n.then((xterm) => {
        if (xterm) {
          contribution.xtermReady?.(xterm);
        }
      });
      this.B(this.onDisposed(() => {
        contribution.dispose();
        this.j.delete(desc.id);
        if ("instance" in contribution) {
          delete contribution.instance;
        }
        if ("_instance" in contribution) {
          delete contribution._instance;
        }
      }));
    }
  }
  getContribution(id2) {
    return this.j.get(id2);
  }
  Cc() {
    if (!this.jb) {
      this.jb = this.h.processState >= 2 ? $0r().getIcon(this.nc.getValue(
        "terminal.integrated.tabs.defaultIcon"
        /* TerminalSettingId.TabsDefaultIcon */
      )) : void 0;
    }
    return this.jb;
  }
  Dc() {
    if (this.shellLaunchConfig.color) {
      return this.shellLaunchConfig.color;
    }
    if (this.shellLaunchConfig?.attachPersistentProcess?.color) {
      return this.shellLaunchConfig.attachPersistentProcess.color;
    }
    if (this.h.processState >= 2) {
      return void 0;
    }
    return void 0;
  }
  Ec() {
    if (!this.L) {
      this.U = 80;
      this.W = 30;
      return;
    }
    const computedStyle = getWindow(this.L).getComputedStyle(this.L);
    const width2 = parseInt(computedStyle.width);
    const height = parseInt(computedStyle.height);
    this.Fc(width2, height);
  }
  /**
   * Evaluates and sets the cols and rows of the terminal if possible.
   * @param width The width of the container.
   * @param height The height of the container.
   * @return The terminal's width if it requires a layout.
   */
  Fc(width2, height) {
    if (!width2 || !height) {
      this.Gc();
      return null;
    }
    const dimension = this.Ic(width2, height);
    if (!dimension) {
      this.Gc();
      return null;
    }
    const font = this.xterm ? this.xterm.getFont() : this.fc.getFont(getWindow(this.domElement));
    const newRC = $3Pb(getWindow(this.domElement), font, dimension.width, dimension.height);
    if (!newRC) {
      this.Gc();
      return null;
    }
    if (this.U !== newRC.cols || this.W !== newRC.rows) {
      this.U = newRC.cols;
      this.W = newRC.rows;
      this.Hc();
    }
    return dimension.width;
  }
  Gc() {
    if ($wfc_1.c) {
      this.U = $wfc_1.c.cols;
      this.W = $wfc_1.c.rows;
    }
  }
  Hc() {
    this.Ob.fire();
  }
  Ic(width2, height) {
    const font = this.xterm ? this.xterm.getFont() : this.fc.getFont(getWindow(this.domElement));
    if (!font || !font.charWidth || !font.charHeight) {
      return void 0;
    }
    if (!this.xterm?.raw.element) {
      return void 0;
    }
    const computedStyle = getWindow(this.xterm.raw.element).getComputedStyle(this.xterm.raw.element);
    const horizontalPadding = parseInt(computedStyle.paddingLeft) + parseInt(computedStyle.paddingRight) + 14;
    const verticalPadding = parseInt(computedStyle.paddingTop) + parseInt(computedStyle.paddingBottom);
    $wfc_1.b = new $rj(Math.min(4096, width2 - horizontalPadding), height - verticalPadding + (this.wb && this.N ? -5 : 0));
    return $wfc_1.b;
  }
  get persistentProcessId() {
    return this.h.persistentProcessId;
  }
  get shouldPersist() {
    return this.h.shouldPersist && !this.shellLaunchConfig.isTransient && (!this.reconnectionProperties || this.nc.getValue("task.reconnection") === true);
  }
  static getXtermConstructor(keybindingService, contextKeyService) {
    const keybinding = keybindingService.lookupKeybinding("workbench.action.terminal.focusAccessibleBuffer", contextKeyService);
    if (xtermConstructor) {
      return xtermConstructor;
    }
    xtermConstructor = Promises.withAsyncBody(async (resolve) => {
      const Terminal = (await $sJ("@xterm/xterm", "lib/xterm.js")).Terminal;
      Terminal.strings.promptLabel = localize(10460, null);
      Terminal.strings.tooMuchOutput = keybinding ? localize(10461, null, keybinding.getLabel()) : localize(10462, null);
      resolve(Terminal);
    });
    return xtermConstructor;
  }
  /**
   * Create xterm.js instance and attach data listeners.
   */
  async Jc() {
    const Terminal = await $wfc_1.getXtermConstructor(this.ic, this.dc);
    if (this.isDisposed) {
      return void 0;
    }
    const disableShellIntegrationReporting = this.shellLaunchConfig.executable === void 0 || this.shellType === void 0 || !shellIntegrationSupportedShellTypes.includes(this.shellType);
    const xterm = this.g.createInstance($2Pb, Terminal, {
      cols: this.U,
      rows: this.W,
      xtermColorProvider: this.g.createInstance($zfc, this.Cb),
      capabilities: this.capabilities,
      shellIntegrationNonce: this.h.shellIntegrationNonce,
      disableShellIntegrationReporting
    });
    this.xterm = xterm;
    this.Ab = this.B(new $vfc(() => this.C, () => xterm, async (cols, rows) => {
      xterm.raw.resize(cols, rows);
      await this.ed(xterm.raw);
    }, async (cols) => {
      xterm.raw.resize(cols, xterm.raw.rows);
      await this.ed(xterm.raw);
    }, async (rows) => {
      xterm.raw.resize(xterm.raw.cols, rows);
      await this.ed(xterm.raw);
    }));
    this.B($1c(() => this.Ab = void 0));
    this.updateAccessibilitySupport();
    this.B(this.xterm.onDidRequestRunCommand((e) => {
      this.sendText(e.command.command, e.noNewLine ? false : true);
    }));
    this.B(this.xterm.onDidRequestRefreshDimensions(() => {
      if (this.nb) {
        this.layout(this.nb);
      }
    }));
    const initialTextWrittenPromise = this.cc.initialText ? new Promise((r2) => this.Yc(xterm, r2)) : void 0;
    const lineDataEventAddon = this.B(new $pfc(initialTextWrittenPromise));
    this.B(lineDataEventAddon.onLineData((e) => this.ac.fire(e)));
    this.yb = lineDataEventAddon;
    $Xh(() => {
      this.B(xterm.raw.onBell(() => {
        if (this.nc.getValue(
          "terminal.integrated.enableBell"
          /* TerminalSettingId.EnableBell */
        ) || this.nc.getValue(
          "terminal.integrated.enableVisualBell"
          /* TerminalSettingId.EnableVisualBell */
        )) {
          this.statusList.add({
            id: "bell",
            severity: Severity2.Warning,
            icon: $6l.bell,
            tooltip: localize(10463, null)
          }, this.fc.config.bellDuration);
        }
        this.Ac.playSignal($N9.terminalBell);
      }));
    }, 1e3, this.q);
    this.B(xterm.raw.onSelectionChange(() => this.Tb.fire(this)));
    this.B(xterm.raw.buffer.onBufferChange(() => this.Oc()));
    this.B(this.h.onProcessData((e) => this.Sc(e)));
    this.B(xterm.raw.onData(async (data) => {
      await this.Bb?.wait();
      await this.h.write(data);
      this.Sb.fire(data);
    }));
    this.B(xterm.raw.onBinary((data) => this.h.processBinary(data)));
    this.B(this.h.onProcessReady(async (processTraits) => {
      if (this.h.os) {
        lineDataEventAddon.setOperatingSystem(this.h.os);
      }
      xterm.raw.options.windowsPty = processTraits.windowsPty;
    }));
    this.B(this.h.onRestoreCommands((e) => this.xterm?.shellIntegration.deserialize(e)));
    this.B(this.Bc.onDidChangeLocation(({ views }) => {
      if (views.some((v) => v.id === $7X)) {
        xterm.refresh();
      }
    }));
    if (!this.capabilities.has(
      0
      /* TerminalCapability.CwdDetection */
    )) {
      let onKeyListener = xterm.raw.onKey((e) => {
        const event = new $if(e.domEvent);
        if (event.equals(
          3
          /* KeyCode.Enter */
        )) {
          this.ad();
        }
      });
      this.B(this.capabilities.onDidAddCapabilityType((e) => {
        if (e === 0) {
          onKeyListener?.dispose();
          onKeyListener = void 0;
        }
      }));
    }
    this.hc.userHome().then((userHome) => {
      this.vb = userHome.fsPath;
    });
    if (this.C) {
      this.Kc();
    }
    return xterm;
  }
  async runCommand(commandLine, shouldExecute) {
    let commandDetection = this.capabilities.get(
      2
      /* TerminalCapability.CommandDetection */
    );
    if (!commandDetection && (this.h.processState === 1 || this.h.processState === 2)) {
      const store = new $2c();
      await Promise.race([
        new Promise((r2) => {
          store.add(this.capabilities.onDidAddCapabilityType((e) => {
            if (e === 2) {
              commandDetection = this.capabilities.get(
                2
                /* TerminalCapability.CommandDetection */
              );
              r2();
            }
          }));
        }),
        $Wh(2e3)
      ]);
      store.dispose();
    }
    if (!commandDetection || commandDetection.promptInputModel.value.length > 0) {
      await this.sendText("", false);
      await $Wh(100);
    }
    await this.sendText(commandLine, shouldExecute, !shouldExecute);
  }
  detachFromElement() {
    this.M.remove();
    this.L = void 0;
  }
  attachToElement(container2) {
    if (this.L === container2) {
      return;
    }
    if (!this.ib.isOpen()) {
      this.ib.open();
    }
    this.L = container2;
    this.L.appendChild(this.M);
    if (this.xterm?.raw.element) {
      this.xterm.raw.open(this.xterm.raw.element);
    }
    this.xterm?.refresh();
    setTimeout(() => {
      if (this.q.isDisposed) {
        return;
      }
      this.Nc(container2);
    }, 0);
  }
  /**
   * Opens the the terminal instance inside the parent DOM element previously set with
   * `attachToElement`, you must ensure the parent DOM element is explicitly visible before
   * invoking this function as it performs some DOM calculations internally
   */
  Kc() {
    if (!this.xterm || this.xterm.raw.element) {
      return;
    }
    if (!this.L || !this.L.isConnected) {
      throw new Error("A container element needs to be set with `attachToElement` and be part of the DOM before calling `_open`");
    }
    const xtermElement = document.createElement("div");
    this.M.appendChild(xtermElement);
    this.L.appendChild(this.M);
    const xterm = this.xterm;
    this.M.xterm = xterm.raw;
    const screenElement = xterm.attachToElement(xtermElement);
    for (const contribution of this.j.values()) {
      if (!this.xterm) {
        this.n.then((xterm2) => {
          if (xterm2) {
            contribution.xtermOpen?.(xterm2);
          }
        });
      } else {
        contribution.xtermOpen?.(this.xterm);
      }
    }
    this.B(xterm.shellIntegration.onDidChangeStatus(() => {
      if (this.hasFocus) {
        this.Mc();
      } else {
        this.S.reset();
      }
    }));
    if (!xterm.raw.element || !xterm.raw.textarea) {
      throw new Error("xterm elements not set after open");
    }
    this.fd(xterm.raw, this.t, this.I);
    xterm.raw.attachCustomKeyEventHandler((event) => {
      if (this.y) {
        return false;
      }
      const standardKeyboardEvent = new $if(event);
      const resolveResult = this.ic.softDispatch(standardKeyboardEvent, standardKeyboardEvent.target);
      const isValidChord = resolveResult.kind === 1 && this.fc.config.allowChords && event.key !== "Escape";
      if (this.ic.inChordMode || isValidChord) {
        event.preventDefault();
        return false;
      }
      const SHOW_TERMINAL_CONFIG_PROMPT_KEY = "terminal.integrated.showTerminalConfigPrompt";
      const EXCLUDED_KEYS = ["RightArrow", "LeftArrow", "UpArrow", "DownArrow", "Space", "Meta", "Control", "Shift", "Alt", "", "Delete", "Backspace", "Tab"];
      if (this.pc.getBoolean(SHOW_TERMINAL_CONFIG_PROMPT_KEY, -1, true) && !EXCLUDED_KEYS.includes(event.key) && !event.ctrlKey && !event.shiftKey && !event.altKey) {
        this.ob = true;
      }
      if (resolveResult.kind === 2 && resolveResult.commandId && this.G.some((k) => k === resolveResult.commandId) && !this.fc.config.sendKeybindingsToShell) {
        if (this.pc.getBoolean(SHOW_TERMINAL_CONFIG_PROMPT_KEY, -1, true) && this.ob && !$8X.includes(resolveResult.commandId)) {
          this.jc.prompt(Severity2.Info, localize(10464, null, this.rc.nameLong), [
            {
              label: localize(10465, null),
              run: () => {
                this.kc.openSettings({ jsonEditor: false, query: `@id:${"terminal.integrated.commandsToSkipShell"},${"terminal.integrated.sendKeybindingsToShell"},${"terminal.integrated.allowChords"}` });
              }
            }
          ]);
          this.pc.store(
            SHOW_TERMINAL_CONFIG_PROMPT_KEY,
            false,
            -1,
            0
            /* StorageTarget.USER */
          );
        }
        event.preventDefault();
        return false;
      }
      if (this.fc.config.allowMnemonics && !$m && event.altKey) {
        return false;
      }
      if ($94.getTabFocusMode() && event.key === "Tab") {
        return false;
      }
      if (event.key === "Tab" && event.shiftKey) {
        event.preventDefault();
        return true;
      }
      if ($l && event.altKey && event.key === "F4" && !event.ctrlKey) {
        return false;
      }
      if (!$5e.clipboard.readText && event.key === "v" && event.ctrlKey) {
        return false;
      }
      return true;
    });
    this.B($_i(xterm.raw.element, "mousedown", () => {
      const listener = $_i(xterm.raw.element.ownerDocument, "mouseup", () => {
        setTimeout(() => this.Pc(), 0);
        listener.dispose();
      });
    }));
    this.B($_i(xterm.raw.element, "touchstart", () => {
      xterm.raw.focus();
    }));
    this.B($_i(xterm.raw.element, "keyup", () => {
      setTimeout(() => this.Pc(), 0);
    }));
    this.B($_i(xterm.raw.textarea, "focus", () => this.Lc(true)));
    this.B($_i(xterm.raw.textarea, "blur", () => this.Lc(false)));
    this.B($_i(xterm.raw.textarea, "focusout", () => this.Lc(false)));
    this.Nc(this.L);
    this.lb.attachToElement(screenElement);
    if (this.nb) {
      this.layout(this.nb);
    }
    this.updateConfig();
    if (xterm.raw.options.disableStdin) {
      this.Xc(xterm.raw);
    }
  }
  Lc(focused) {
    if (focused) {
      this.O.set(true);
      this.Mc();
      this.Pb.fire(this);
    } else {
      this.resetFocusContextKey();
      this.Rb.fire(this);
      this.Pc();
    }
  }
  Mc() {
    if (this.xterm) {
      this.S.set(
        this.xterm.shellIntegration.status === 2
        /* ShellIntegrationStatus.VSCode */
      );
    }
  }
  resetFocusContextKey() {
    this.O.reset();
    this.S.reset();
  }
  Nc(container2) {
    const store = new $2c();
    const dndController = store.add(this.g.createInstance(TerminalInstanceDragAndDropController, container2));
    store.add(dndController.onDropTerminal((e) => this.Ub.fire(e)));
    store.add(dndController.onDropFile(async (path) => {
      this.focus();
      await this.sendPath(path, false);
    }));
    store.add(new $Ak(container2, dndController));
    this.mb.value = store;
  }
  hasSelection() {
    return this.xterm ? this.xterm.raw.hasSelection() : false;
  }
  get selection() {
    return this.xterm && this.hasSelection() ? this.xterm.raw.getSelection() : void 0;
  }
  clearSelection() {
    this.xterm?.raw.clearSelection();
  }
  Oc() {
    this.R.set(!!(this.xterm && this.xterm.raw.buffer.active === this.xterm.raw.buffer.alternate));
  }
  dispose(reason) {
    if (this.shellLaunchConfig.type === "Task" && reason === TerminalExitReason2.Process && this.D !== 0 && !this.shellLaunchConfig.waitOnExit) {
      return;
    }
    if (this.isDisposed) {
      return;
    }
    this.oc.trace(`terminalInstance#dispose (instanceId: ${this.instanceId})`);
    $Xc(this.lb);
    if (this.xterm?.raw.element) {
      this.z = this.hasFocus;
    }
    if (this.M.xterm) {
      this.M.xterm = void 0;
    }
    if (this.N) {
      this.N.dispose();
      this.N = void 0;
    }
    try {
      this.xterm?.dispose();
    } catch (err) {
      this.oc.error("Exception occurred during xterm disposal", err);
    }
    if ($Ue) {
      this.resetFocusContextKey();
      this.Q.reset();
      this.Rb.fire(this);
    }
    if (this.s) {
      this.s.dispose();
      this.s = void 0;
    }
    if (this.F === void 0) {
      this.F = reason ?? TerminalExitReason2.Unknown;
    }
    this.h.dispose();
    this.Uc(void 0);
    this.Eb.fire(this);
    super.dispose();
  }
  async detachProcessAndDispose(reason) {
    await this.h.detachFromProcess(reason === TerminalExitReason2.User);
    this.dispose(reason);
  }
  focus(force) {
    this.Oc();
    if (!this.xterm) {
      return;
    }
    if (force || !$Qj().getSelection()?.toString()) {
      this.xterm.raw.focus();
      this.Qb.fire();
    }
  }
  async focusWhenReady(force) {
    await this.n;
    await this.ib.wait();
    this.focus(force);
  }
  async sendText(text2, shouldExecute, bracketedPasteMode) {
    if (bracketedPasteMode && this.xterm?.raw.modes.bracketedPasteMode) {
      text2 = `\x1B[200~${text2}\x1B[201~`;
    }
    text2 = text2.replace(/\r?\n/g, "\r");
    if (shouldExecute && !text2.endsWith("\r")) {
      text2 += "\r";
    }
    this.oc.debug("sending data (vscode)", text2);
    await this.h.write(text2);
    this.Sb.fire(text2);
    this.Yb.fire(text2);
    this.xterm?.scrollToBottom();
    if (shouldExecute) {
      this.Wb.fire();
    }
  }
  async sendPath(originalPath, shouldExecute) {
    return this.sendText(await this.preparePathForShell(originalPath), shouldExecute);
  }
  async preparePathForShell(originalPath) {
    await this.processReady;
    return $BY(originalPath, this.shellLaunchConfig.executable, this.title, this.shellType, this.h.backend, this.h.os);
  }
  setVisible(visible) {
    const didChange = this.C !== visible;
    this.C = visible;
    this.M.classList.toggle("active", visible);
    if (visible && this.xterm) {
      this.Kc();
      this.Ab?.flush();
      this.dd();
    }
    if (didChange) {
      this.$b.fire(visible);
    }
  }
  scrollDownLine() {
    this.xterm?.scrollDownLine();
  }
  scrollDownPage() {
    this.xterm?.scrollDownPage();
  }
  scrollToBottom() {
    this.xterm?.scrollToBottom();
  }
  scrollUpLine() {
    this.xterm?.scrollUpLine();
  }
  scrollUpPage() {
    this.xterm?.scrollUpPage();
  }
  scrollToTop() {
    this.xterm?.scrollToTop();
  }
  clearBuffer() {
    this.h.clearBuffer();
    this.xterm?.clearBuffer();
  }
  Pc() {
    const isActive2 = !!this.lc.getActiveViewWithId($7X);
    let isEditorActive = false;
    const editor = this.uc.activeEditor;
    if (editor) {
      isEditorActive = editor instanceof $fQb;
    }
    this.Q.set((isActive2 || isEditorActive) && this.hasSelection());
  }
  Qc() {
    let deserializedCollections;
    if (this.shellLaunchConfig.attachPersistentProcess?.environmentVariableCollections) {
      deserializedCollections = $GB(this.shellLaunchConfig.attachPersistentProcess.environmentVariableCollections);
    }
    const processManager = this.g.createInstance($ofc, this.t, this.shellLaunchConfig?.cwd, deserializedCollections, this.shellLaunchConfig.attachPersistentProcess?.shellIntegrationNonce);
    this.capabilities.add(processManager.capabilities);
    this.B(processManager.onProcessReady(async (e) => {
      this.Fb.fire(this);
      this.$ = await this.getInitialCwd();
      if (!this.ub) {
        this.ub = this.B(this.g.createInstance($xfc));
        this.B(this.ub.onDidChangeLabel((e2) => {
          const wasChanged = this.I !== e2.title || this.pb !== e2.description;
          if (wasChanged) {
            this.I = e2.title;
            this.pb = e2.description;
            this.Hb.fire(this);
          }
        }));
      }
      if (this.cc.name) {
        this.rd(this.cc.name, TitleEventSource.Api);
      } else {
        setTimeout(() => {
          this.n.then((xterm) => {
            if (xterm) {
              this.kb.value = xterm.raw.onTitleChange((e2) => this.Zc(e2));
            }
          });
        });
        this.rd(this.cc.executable, TitleEventSource.Process);
      }
    }));
    this.B(processManager.onProcessExit((exitCode) => this.Uc(exitCode)));
    this.B(processManager.onDidChangeProperty(({ type, value }) => {
      switch (type) {
        case "cwd":
          this.Z = value;
          this.ub?.refreshLabel(this);
          break;
        case "initialCwd":
          this.$ = value;
          this.Z = this.$;
          this.rd(this.title, TitleEventSource.Config);
          this.jb = this.cc.attachPersistentProcess?.icon || this.cc.icon;
          this.Ib.fire({ instance: this, userInitiated: false });
          break;
        case "title":
          this.rd(value ?? "", TitleEventSource.Process);
          break;
        case "overrideDimensions":
          this.setOverrideDimensions(value, true);
          break;
        case "resolvedShellLaunchConfig":
          this.md(value);
          break;
        case "shellType":
          this.setShellType(value);
          break;
        case "hasChildProcesses":
          this.Vb.fire(value);
          break;
        case "usedShellIntegrationInjection":
          this.xb = true;
          break;
      }
    }));
    this.fb.value = processManager.onProcessData((ev) => this.gb?.push(ev.data));
    this.B(processManager.onProcessReplayComplete(() => this.Gb.fire()));
    this.B(processManager.onEnvironmentVariableInfoChanged((e) => this.nd(e)));
    this.B(processManager.onPtyDisconnect(() => {
      if (this.xterm) {
        this.xterm.raw.options.disableStdin = true;
      }
      this.statusList.add({
        id: "disconnected",
        severity: Severity2.Error,
        icon: $6l.debugDisconnect,
        tooltip: localize(10466, null)
      });
    }));
    this.B(processManager.onPtyReconnect(() => {
      if (this.xterm) {
        this.xterm.raw.options.disableStdin = false;
      }
      this.statusList.remove(
        "disconnected"
        /* TerminalStatus.Disconnected */
      );
    }));
    return processManager;
  }
  async Rc() {
    if (this.isDisposed) {
      return;
    }
    const activeWorkspaceRootUri = this.wc.getLastActiveWorkspaceRoot(Schemas.file);
    if (activeWorkspaceRootUri) {
      const trusted = await this.$c();
      if (!trusted) {
        this.Uc({ message: localize(10467, null) });
      }
    } else if (this.Z && this.vb && this.Z !== this.vb) {
      this.Uc({
        message: localize(10468, null, this.Z, this.vb)
      });
    }
    if (this.L && this.U === 0 && this.W === 0) {
      this.Ec();
      this.xterm?.raw.resize(
        this.U || 80,
        this.W || 30
        /* Constants.DefaultRows */
      );
    }
    const originalIcon = this.shellLaunchConfig.icon;
    await this.h.createProcess(
      this.cc,
      this.U || 80,
      this.W || 30
      /* Constants.DefaultRows */
    ).then((result) => {
      if (result) {
        if ("message" in result) {
          this.Uc(result);
        } else if ("injectedArgs" in result) {
          this.ab = result.injectedArgs;
        }
      }
    });
    if (this.isDisposed) {
      return;
    }
    if (this.xterm?.shellIntegration) {
      this.capabilities.add(this.xterm.shellIntegration.capabilities);
    }
    if (originalIcon !== this.shellLaunchConfig.icon || this.shellLaunchConfig.color) {
      this.jb = this.cc.attachPersistentProcess?.icon || this.cc.icon;
      this.Ib.fire({ instance: this, userInitiated: false });
    }
  }
  registerMarker(offset) {
    return this.xterm?.raw.registerMarker(offset);
  }
  addBufferMarker(properties) {
    this.capabilities.get(
      4
      /* TerminalCapability.BufferMarkDetection */
    )?.addMark(properties);
  }
  scrollToMark(startMarkId, endMarkId, highlight) {
    this.xterm?.markTracker.scrollToClosestMarker(startMarkId, endMarkId, highlight);
  }
  async freePortKillProcess(port, command4) {
    await this.h?.freePortKillProcess(port);
    this.runCommand(command4, false);
  }
  Sc(ev) {
    const execIndex = ev.data.indexOf("\x1B]633;C\x07");
    if (execIndex !== -1) {
      if (ev.trackCommit) {
        this.Tc(ev.data.substring(0, execIndex + "\x1B]633;C\x07".length));
        ev.writePromise = new Promise((r2) => this.Tc(ev.data.substring(execIndex + "\x1B]633;C\x07".length), r2));
      } else {
        this.Tc(ev.data.substring(0, execIndex + "\x1B]633;C\x07".length));
        this.Tc(ev.data.substring(execIndex + "\x1B]633;C\x07".length));
      }
    } else {
      if (ev.trackCommit) {
        ev.writePromise = new Promise((r2) => this.Tc(ev.data, r2));
      } else {
        this.Tc(ev.data);
      }
    }
  }
  Tc(data, cb) {
    this.Jb.fire(data);
    const messageId = ++this.u;
    this.xterm?.raw.write(data, () => {
      this.w = messageId;
      this.h.acknowledgeDataEvent(data.length);
      cb?.();
      this.Kb.fire(data);
    });
  }
  /**
   * Called when either a process tied to a terminal has exited or when a terminal renderer
   * simulates a process exiting (e.g. custom execution task).
   * @param exitCode The exit code of the process, this is undefined when the terminal was exited
   * through user action.
   */
  async Uc(exitCodeOrError) {
    if (this.y) {
      return;
    }
    const parsedExitResult = $yfc(exitCodeOrError, this.shellLaunchConfig, this.h.processState, this.$);
    if (this.xb && this.h.processState === 4 && parsedExitResult?.code !== 0) {
      this.Vc(parsedExitResult?.message);
      this.Db.fire(exitCodeOrError);
      return;
    }
    this.y = true;
    await this.Wc();
    this.D = parsedExitResult?.code;
    const exitMessage = parsedExitResult?.message;
    this.oc.debug("Terminal process exit", "instanceId", this.instanceId, "code", this.D, "processState", this.h.processState);
    const waitOnExit = this.waitOnExit;
    if (waitOnExit && this.h.processState !== 5) {
      this.n.then((xterm) => {
        if (!xterm) {
          return;
        }
        if (exitMessage) {
          xterm.raw.write($W0b(exitMessage));
        }
        switch (typeof waitOnExit) {
          case "string":
            xterm.raw.write($W0b(waitOnExit, { excludeLeadingNewLine: true }));
            break;
          case "function":
            if (this.exitCode !== void 0) {
              xterm.raw.write($W0b(waitOnExit(this.exitCode), { excludeLeadingNewLine: true }));
            }
            break;
        }
        xterm.raw.options.disableStdin = true;
        if (xterm.raw.textarea) {
          this.Xc(xterm.raw);
        }
      });
    } else {
      if (exitMessage) {
        const failedDuringLaunch = this.h.processState === 4;
        if (failedDuringLaunch || this.fc.config.showExitAlert) {
          this.jc.notify({
            message: exitMessage,
            severity: Severity2.Error,
            actions: { primary: [this.g.createInstance($Tec)] }
          });
        } else {
          this.oc.warn(exitMessage);
        }
      }
      this.dispose(TerminalExitReason2.Process);
    }
    this.Db.fire(exitCodeOrError);
    if (this.isDisposed) {
      this.Db.dispose();
    }
  }
  Vc(exitMessage) {
    this.cc.ignoreShellIntegration = true;
    this.relaunch();
    this.statusList.add({
      id: "shell-integration-attention-needed",
      severity: Severity2.Warning,
      icon: $6l.warning,
      tooltip: `${exitMessage} ` + localize(10469, null),
      hoverActions: [{
        commandId: "workbench.action.terminal.learnMore",
        label: localize(10470, null),
        run: () => {
          this.yc.open("https://code.visualstudio.com/docs/editor/integrated-terminal#_shell-integration");
        }
      }, {
        commandId: "workbench.action.openSettings",
        label: localize(10471, null),
        run: () => {
          this.zc.executeCommand("workbench.action.openSettings", "terminal.integrated.shellIntegration.enabled");
        }
      }]
    });
    this.xc.publicLog2("terminal/shellIntegrationFailureProcessExit");
  }
  /**
   * Ensure write calls to xterm.js have finished before resolving.
   */
  Wc() {
    if (this.u === this.w) {
      return Promise.resolve();
    }
    let retries = 0;
    return new Promise((r2) => {
      const interval = $kj($Qj().window, () => {
        if (this.u === this.w || ++retries === 5) {
          interval.dispose();
          r2();
        }
      }, 20);
    });
  }
  Xc(xterm) {
    if (xterm.textarea && !this.s) {
      this.s = $_i(xterm.textarea, "keypress", (event) => {
        if (this.s) {
          this.s.dispose();
          this.s = void 0;
          this.dispose(TerminalExitReason2.Process);
          event.preventDefault();
        }
      });
    }
  }
  Yc(xterm, callback) {
    if (!this.cc.initialText) {
      callback?.();
      return;
    }
    const text2 = typeof this.cc.initialText === "string" ? this.cc.initialText : this.cc.initialText?.text;
    if (typeof this.cc.initialText === "string") {
      xterm.raw.writeln(text2, callback);
    } else {
      if (this.cc.initialText.trailingNewLine) {
        xterm.raw.writeln(text2, callback);
      } else {
        xterm.raw.write(text2, callback);
      }
    }
  }
  async reuseTerminal(shell, reset = false) {
    this.s?.dispose();
    this.s = void 0;
    const xterm = this.xterm;
    if (xterm) {
      if (!reset) {
        await new Promise((r2) => xterm.raw.write("\n\x1B[G", r2));
      }
      if (shell.initialText) {
        this.cc.initialText = shell.initialText;
        await new Promise((r2) => this.Yc(xterm, r2));
      }
      if (this.y && this.cc.waitOnExit) {
        xterm.raw.options.disableStdin = false;
        this.y = false;
      }
      if (reset) {
        xterm.clearDecorations();
      }
    }
    this.statusList.remove(
      "relaunch-needed"
      /* TerminalStatus.RelaunchNeeded */
    );
    if (!reset) {
      shell.initialText = " ";
    }
    this.cc = shell;
    await this.h.relaunch(this.cc, this.U || 80, this.W || 30, reset).then((result) => {
      if (result) {
        if ("message" in result) {
          this.Uc(result);
        } else if ("injectedArgs" in result) {
          this.ab = result.injectedArgs;
        }
      }
    });
  }
  relaunch() {
    this.reuseTerminal(this.cc, true);
  }
  Zc(title) {
    if (this.isTitleSetByProcess) {
      this.rd(title, TitleEventSource.Sequence);
    }
  }
  async $c() {
    return await this.vc.requestWorkspaceTrust({
      message: localize(10472, null)
    }) === true;
  }
  async ad() {
    if (this.isDisposed || this.shellLaunchConfig.customPtyImplementation) {
      return;
    }
    try {
      const cwd2 = await this.pd(
        "cwd"
        /* ProcessPropertyType.Cwd */
      );
      if (typeof cwd2 !== "string") {
        throw new Error(`cwd is not a string ${cwd2}`);
      }
    } catch (e) {
      if (e instanceof Error && e.message === "Cannot refresh property when process is not set") {
        return;
      }
      throw e;
    }
  }
  updateConfig() {
    this.cd(this.fc.config.commandsToSkipShell);
    this.od(this.h.environmentVariableInfo);
  }
  async bd() {
    this.h.setUnicodeVersion(this.fc.config.unicodeVersion);
  }
  updateAccessibilitySupport() {
    this.xterm.raw.options.screenReaderMode = this.qc.isScreenReaderOptimized();
  }
  cd(commands2) {
    const excludeCommands = commands2.filter((command4) => command4[0] === "-").map((command4) => command4.slice(1));
    this.G = $kY.filter((defaultCommand) => {
      return !excludeCommands.includes(defaultCommand);
    }).concat(commands2);
  }
  layout(dimension) {
    this.nb = dimension;
    if (this.disableLayout) {
      return;
    }
    if (dimension.width <= 0 || dimension.height <= 0) {
      return;
    }
    const terminalWidth = this.Fc(dimension.width, dimension.height);
    if (!terminalWidth) {
      return;
    }
    this.dd();
    if (!this.hb.isOpen()) {
      this.hb.open();
    }
    for (const contribution of this.j.values()) {
      if (!this.xterm) {
        this.n.then((xterm) => {
          if (xterm) {
            contribution.layout?.(xterm, dimension);
          }
        });
      } else {
        contribution.layout?.(this.xterm, dimension);
      }
    }
  }
  async dd(immediate) {
    if (!this.xterm) {
      return;
    }
    let cols = this.cols;
    let rows = this.rows;
    if (this.C && this.bb) {
      const font = this.xterm.getFont();
      const config = this.fc.config;
      this.xterm.raw.options.letterSpacing = font.letterSpacing;
      this.xterm.raw.options.lineHeight = font.lineHeight;
      this.xterm.raw.options.fontSize = font.fontSize;
      this.xterm.raw.options.fontFamily = font.fontFamily;
      this.xterm.raw.options.fontWeight = config.fontWeight;
      this.xterm.raw.options.fontWeightBold = config.fontWeightBold;
      this.Ec();
      cols = this.cols;
      rows = this.rows;
      this.bb = false;
    }
    if (isNaN(cols) || isNaN(rows)) {
      return;
    }
    if (cols !== this.xterm.raw.cols || rows !== this.xterm.raw.rows) {
      if (this.Y || this.X) {
        await this.qd("fixedDimensions", { cols: this.X, rows: this.Y });
      }
      this.Nb.fire();
    }
    $wfc_1.c = { cols, rows };
    this.Ab.resize(cols, rows, immediate ?? false);
  }
  async ed(rawXterm) {
    await this.h.setDimensions(rawXterm.cols, rawXterm.rows);
  }
  setShellType(shellType) {
    if (this.H === shellType) {
      return;
    }
    if (shellType) {
      this.H = shellType;
      this.bc.set(shellType?.toString());
      this.Zb.fire(shellType);
    }
  }
  fd(xterm, terminalId, title) {
    const labelParts = [];
    if (xterm && xterm.textarea) {
      if (title && title.length > 0) {
        labelParts.push(localize(10473, null, terminalId, title));
      } else {
        labelParts.push(localize(10474, null, terminalId));
      }
      const screenReaderOptimized = this.qc.isScreenReaderOptimized();
      if (!screenReaderOptimized) {
        labelParts.push(localize(10475, null));
      }
      const accessibilityHelpKeybinding = this.ic.lookupKeybinding(
        "editor.action.accessibilityHelp"
        /* AccessibilityCommandId.OpenAccessibilityHelp */
      )?.getLabel();
      if (this.nc.getValue(
        "accessibility.verbosity.terminal"
        /* AccessibilityVerbositySettingId.Terminal */
      ) && accessibilityHelpKeybinding) {
        labelParts.push(localize(10476, null, accessibilityHelpKeybinding));
      }
      xterm.textarea.setAttribute("aria-label", labelParts.join("\n"));
    }
  }
  gd(title, eventSource) {
    if (!title) {
      return this.qb;
    }
    switch (eventSource) {
      case TitleEventSource.Process:
        if (this.h.os === 1) {
          title = $jc.parse(title).name;
        } else {
          const firstSpaceIndex = title.indexOf(" ");
          if (title.startsWith("/")) {
            title = $rc(title);
          } else if (firstSpaceIndex > -1) {
            title = title.substring(0, firstSpaceIndex);
          }
        }
        this.qb = title;
        break;
      case TitleEventSource.Api:
        this.sb = title;
        this.kb.value = void 0;
        break;
      case TitleEventSource.Sequence:
        this.rb = title;
        if (this.h.os === 1 && title.match(/^[a-zA-Z]:\\.+\.[a-zA-Z]{1,3}/)) {
          this.rb = $jc.parse(title).name;
        }
        break;
    }
    this.J = eventSource;
    return title;
  }
  setOverrideDimensions(dimensions, immediate = false) {
    if (this.db && this.db.forceExactSize && !dimensions && this.W === 0 && this.U === 0) {
      this.U = this.db.cols;
      this.W = this.db.rows;
    }
    this.db = dimensions;
    if (immediate) {
      this.dd(true);
    } else {
      this.dd();
    }
  }
  async setFixedDimensions() {
    const cols = await this.sc.input({
      title: localize(10477, null),
      placeHolder: "Enter a number of columns or leave empty for automatic width",
      validateInput: async (text2) => text2.length > 0 && !text2.match(/^\d+$/) ? { content: "Enter a number or leave empty size automatically", severity: Severity2.Error } : void 0
    });
    if (cols === void 0) {
      return;
    }
    this.X = this.hd(cols);
    this.ub?.refreshLabel(this);
    this.P.set(!!this.X);
    const rows = await this.sc.input({
      title: localize(10478, null),
      placeHolder: "Enter a number of rows or leave empty for automatic height",
      validateInput: async (text2) => text2.length > 0 && !text2.match(/^\d+$/) ? { content: "Enter a number or leave empty size automatically", severity: Severity2.Error } : void 0
    });
    if (rows === void 0) {
      return;
    }
    this.Y = this.hd(rows);
    this.ub?.refreshLabel(this);
    await this.jd();
    this.dd();
    this.focus();
  }
  hd(value) {
    if (value === "") {
      return void 0;
    }
    const parsed = parseInt(value);
    if (parsed <= 0) {
      throw new Error(`Could not parse dimension "${value}"`);
    }
    return parsed;
  }
  async toggleSizeToContentWidth() {
    if (!this.xterm?.raw.buffer.active) {
      return;
    }
    if (this.wb) {
      this.P.set(false);
      this.X = void 0;
      this.Y = void 0;
      this.wb = false;
      this.Ec();
      await this.dd();
    } else {
      const font = this.xterm ? this.xterm.getFont() : this.fc.getFont(getWindow(this.domElement));
      const maxColsForTexture = Math.floor(4096 / (font.charWidth ?? 20));
      const proposedCols = Math.max(this.maxCols, Math.min(this.xterm.getLongestViewportWrappedLineLength(), maxColsForTexture));
      if (proposedCols > this.xterm.raw.cols) {
        this.X = proposedCols;
      }
    }
    await this.jd();
    this.ub?.refreshLabel(this);
    this.focus();
  }
  jd() {
    if (this.X || this.Y) {
      return this.kd();
    }
    return this.ld();
  }
  async kd() {
    const charWidth = (this.xterm ? this.xterm.getFont() : this.fc.getFont(getWindow(this.domElement))).charWidth;
    if (!this.xterm?.raw.element || !this.L || !charWidth || !this.X) {
      return;
    }
    this.M.classList.add("fixed-dims");
    this.wb = true;
    this.Ec();
    await this.dd();
    this.P.set(true);
    if (!this.N) {
      this.N = this.B(new $CZ(this.M, {
        vertical: 2,
        horizontal: 1,
        useShadows: false,
        scrollYToX: false,
        consumeMouseWheelIfScrollbarIsNeeded: false
      }));
      this.L.appendChild(this.N.getDomNode());
    }
    this.N.setScrollDimensions({
      width: this.xterm.raw.element.clientWidth,
      scrollWidth: this.X * charWidth + 40
      // Padding + scroll bar
    });
    this.N.getDomNode().style.paddingBottom = "16px";
    if ($l) {
      for (let i2 = this.xterm.raw.buffer.active.viewportY; i2 < this.xterm.raw.buffer.active.length; i2++) {
        const line = this.xterm.raw.buffer.active.getLine(i2);
        line._line.isWrapped = false;
      }
    }
  }
  async ld() {
    if (!this.L || !this.N) {
      return;
    }
    this.N.getDomNode().remove();
    this.N.dispose();
    this.N = void 0;
    this.M.remove();
    this.M.classList.remove("fixed-dims");
    this.L.appendChild(this.M);
  }
  md(shellLaunchConfig) {
    this.cc.args = shellLaunchConfig.args;
    this.cc.cwd = shellLaunchConfig.cwd;
    this.cc.executable = shellLaunchConfig.executable;
    this.cc.env = shellLaunchConfig.env;
  }
  nd(info) {
    if (info.requiresAction) {
      this.xterm?.raw.textarea?.setAttribute("aria-label", localize(10479, null, this.t));
    }
    this.od(info);
  }
  async od(info) {
    if (!info) {
      this.statusList.remove(
        "relaunch-needed"
        /* TerminalStatus.RelaunchNeeded */
      );
      this.statusList.remove(
        "env-var-info-changes-active"
        /* TerminalStatus.EnvironmentVariableInfoChangesActive */
      );
      return;
    }
    if (
      // The change requires a relaunch
      info.requiresAction && // The feature is enabled
      this.fc.config.environmentChangesRelaunch && // Has not been interacted with
      !this.h.hasWrittenData && // Not a feature terminal or is a reconnecting task terminal (TODO: Need to explain the latter case)
      (!this.cc.isFeatureTerminal || this.reconnectionProperties && this.nc.getValue("task.reconnection") === true) && // Not a custom pty
      !this.cc.customPtyImplementation && // Not an extension owned terminal
      !this.cc.isExtensionOwnedTerminal && // Not a reconnected or revived terminal
      !this.cc.attachPersistentProcess && // Not a Windows remote using ConPTY (#187084)
      !(this.h.remoteAuthority && this.fc.config.windowsEnableConpty && await this.h.getBackendOS() === 1)
    ) {
      this.relaunch();
      return;
    }
    const workspaceFolder = $CY(this.shellLaunchConfig.cwd, this.tc, this.wc);
    this.statusList.add(info.getStatus({ workspaceFolder }));
  }
  async getInitialCwd() {
    if (!this.$) {
      this.$ = this.h.initialCwd;
    }
    return this.$;
  }
  async getCwd() {
    if (this.capabilities.has(
      0
      /* TerminalCapability.CwdDetection */
    )) {
      return this.capabilities.get(
        0
        /* TerminalCapability.CwdDetection */
      ).getCwd();
    } else if (this.capabilities.has(
      1
      /* TerminalCapability.NaiveCwdDetection */
    )) {
      return this.capabilities.get(
        1
        /* TerminalCapability.NaiveCwdDetection */
      ).getCwd();
    }
    return this.h.initialCwd;
  }
  async pd(type) {
    await this.processReady;
    return this.h.refreshProperty(type);
  }
  async qd(type, value) {
    return this.h.updateProperty(type, value);
  }
  async rename(title) {
    this.rd(title, TitleEventSource.Api);
  }
  rd(title, eventSource) {
    const reset = !title;
    title = this.gd(title, eventSource);
    const titleChanged = title !== this.I;
    this.I = title;
    this.ub?.refreshLabel(this, reset);
    this.fd(this.xterm?.raw, this.t, this.I);
    if (titleChanged) {
      this.Hb.fire(this);
    }
  }
  async changeIcon(icon2) {
    if (icon2) {
      this.jb = icon2;
      this.Ib.fire({ instance: this, userInitiated: true });
      return icon2;
    }
    const iconPicker = this.g.createInstance($ufc);
    const pickedIcon = await iconPicker.pickIcons();
    iconPicker.dispose();
    if (!pickedIcon) {
      return void 0;
    }
    this.jb = pickedIcon;
    this.Ib.fire({ instance: this, userInitiated: true });
    return pickedIcon;
  }
  async changeColor(color2, skipQuickPick) {
    if (color2) {
      this.shellLaunchConfig.color = color2;
      this.Ib.fire({ instance: this, userInitiated: true });
      return color2;
    } else if (skipQuickPick) {
      this.shellLaunchConfig.color = "";
      this.Ib.fire({ instance: this, userInitiated: true });
      return;
    }
    const icon2 = this.Cc();
    if (!icon2) {
      return;
    }
    const colorTheme = this.mc.getColorTheme();
    const standardColors = $aQb(colorTheme);
    const colorStyleDisposable = $bQb(colorTheme);
    const items = [];
    for (const colorKey of standardColors) {
      const colorClass = $_Pb(colorKey);
      items.push({
        label: `$(${$6l.circleFilled.id}) ${colorKey.replace("terminal.ansi", "")}`,
        id: colorKey,
        description: colorKey,
        iconClasses: [colorClass]
      });
    }
    items.push({ type: "separator" });
    const showAllColorsItem = { label: "Reset to default" };
    items.push(showAllColorsItem);
    const disposables = [];
    const quickPick = this.sc.createQuickPick({ useSeparators: true });
    disposables.push(quickPick);
    quickPick.items = items;
    quickPick.matchOnDescription = true;
    quickPick.placeholder = localize(10480, null);
    quickPick.show();
    const result = await new Promise((r2) => {
      disposables.push(quickPick.onDidHide(() => r2(void 0)));
      disposables.push(quickPick.onDidAccept(() => r2(quickPick.selectedItems[0])));
    });
    $Xc(disposables);
    if (result) {
      this.shellLaunchConfig.color = result.id;
      this.Ib.fire({ instance: this, userInitiated: true });
    }
    quickPick.hide();
    colorStyleDisposable.dispose();
    return result?.id;
  }
  forceScrollbarVisibility() {
    this.M.classList.add("force-scrollbar");
  }
  resetScrollbarVisibility() {
    this.M.classList.remove("force-scrollbar");
  }
  setParentContextKeyService(parentContextKeyService) {
    this.zb.updateParent(parentContextKeyService);
  }
  async handleMouseEvent(event, contextMenu) {
    if ($Uj(event.target) && (event.target.classList.contains("scrollbar") || event.target.classList.contains("slider"))) {
      return { cancelContextMenu: true };
    }
    for (const contrib of this.j.values()) {
      const result = await contrib.handleMouseEvent?.(event);
      if (result?.handled) {
        return { cancelContextMenu: true };
      }
    }
    if (event.which === 2) {
      switch (this.fc.config.middleClickBehavior) {
        case "default":
        default:
          this.focus();
          break;
      }
      return;
    }
    if (event.which === 3) {
      if (event.shiftKey) {
        $Oec($Qj(), event, this, contextMenu, this.ec);
        return;
      }
      const rightClickBehavior = this.fc.config.rightClickBehavior;
      if (rightClickBehavior === "nothing") {
        if (!event.shiftKey) {
          return { cancelContextMenu: true };
        }
        return;
      }
    }
  }
};
__decorate([
  $$t(50)
], $wfc.prototype, "Hc", null);
__decorate([
  $$t(1e3)
], $wfc.prototype, "relaunch", null);
__decorate([
  $$t(2e3)
], $wfc.prototype, "ad", null);
$wfc = $wfc_1 = __decorate([
  __param(2, $on),
  __param(3, $50),
  __param(4, $Pk),
  __param(5, $5Pb),
  __param(6, $fY),
  __param(7, $aT),
  __param(8, $Ty),
  __param(9, $PJ),
  __param(10, $TK),
  __param(11, $uob),
  __param(12, $gs),
  __param(13, $kl),
  __param(14, $8x),
  __param(15, $jv),
  __param(16, $ND),
  __param(17, $Vu),
  __param(18, $1M),
  __param(19, $US),
  __param(20, $Zk),
  __param(21, $mJ),
  __param(22, $5M),
  __param(23, $tY),
  __param(24, $zv),
  __param(25, $O4),
  __param(26, $sn),
  __param(27, $I9),
  __param(28, $$M)
], $wfc);
var TerminalInstanceDragAndDropController = class TerminalInstanceDragAndDropController2 extends $3c {
  get onDropFile() {
    return this.c.event;
  }
  get onDropTerminal() {
    return this.f.event;
  }
  constructor(g, h3, j) {
    super();
    this.g = g;
    this.h = h3;
    this.j = j;
    this.c = this.B(new $ze());
    this.f = this.B(new $ze());
    this.B($1c(() => this.m()));
  }
  m() {
    this.b?.remove();
    this.b = void 0;
  }
  onDragEnter(e) {
    if (!$z_(e, $kZ.FILES, $kZ.RESOURCES, "Terminals", $u_.FILES)) {
      return;
    }
    if (!this.b) {
      this.b = document.createElement("div");
      this.b.classList.add("terminal-drop-overlay");
    }
    if ($z_(
      e,
      "Terminals"
      /* TerminalDataTransfers.Terminals */
    )) {
      const side = this.n(e);
      this.b.classList.toggle("drop-before", side === "before");
      this.b.classList.toggle("drop-after", side === "after");
    }
    if (!this.b.parentElement) {
      this.g.appendChild(this.b);
    }
  }
  onDragLeave(e) {
    this.m();
  }
  onDragEnd(e) {
    this.m();
  }
  onDragOver(e) {
    if (!e.dataTransfer || !this.b) {
      return;
    }
    if ($z_(
      e,
      "Terminals"
      /* TerminalDataTransfers.Terminals */
    )) {
      const side = this.n(e);
      this.b.classList.toggle("drop-before", side === "before");
      this.b.classList.toggle("drop-after", side === "after");
    }
    this.b.style.opacity = "1";
  }
  async onDrop(e) {
    this.m();
    if (!e.dataTransfer) {
      return;
    }
    const terminalResources = $_ec(e);
    if (terminalResources) {
      for (const uri of terminalResources) {
        const side = this.n(e);
        this.f.fire({ uri, side });
      }
      return;
    }
    let path;
    const rawResources = e.dataTransfer.getData($kZ.RESOURCES);
    if (rawResources) {
      path = URI.parse(JSON.parse(rawResources)[0]);
    }
    const rawCodeFiles = e.dataTransfer.getData($u_.FILES);
    if (!path && rawCodeFiles) {
      path = URI.file(JSON.parse(rawCodeFiles)[0]);
    }
    if (!path && e.dataTransfer.files.length > 0 && $E_(e.dataTransfer.files[0])) {
      path = URI.file($E_(e.dataTransfer.files[0]));
    }
    if (!path) {
      return;
    }
    this.c.fire(path);
  }
  n(e) {
    const target = this.g;
    if (!target) {
      return "after";
    }
    const rect = target.getBoundingClientRect();
    return this.s() === 1 ? e.clientX - rect.left < rect.width / 2 ? "before" : "after" : e.clientY - rect.top < rect.height / 2 ? "before" : "after";
  }
  s() {
    const panelPosition = this.h.getPanelPosition();
    const terminalLocation = this.j.getViewLocationById($7X);
    return terminalLocation === 1 && $Wlb(panelPosition) ? 1 : 0;
  }
};
TerminalInstanceDragAndDropController = __decorate([
  __param(1, $Vlb),
  __param(2, $$M)
], TerminalInstanceDragAndDropController);
var TerminalLabelType;
(function(TerminalLabelType2) {
  TerminalLabelType2["Title"] = "title";
  TerminalLabelType2["Description"] = "description";
})(TerminalLabelType || (TerminalLabelType = {}));
var $xfc = class $xfc2 extends $3c {
  get title() {
    return this.b;
  }
  get description() {
    return this.c;
  }
  constructor(g, h3, j) {
    super();
    this.g = g;
    this.h = h3;
    this.j = j;
    this.b = "";
    this.c = "";
    this.f = this.B(new $ze());
    this.onDidChangeLabel = this.f.event;
  }
  refreshLabel(instance2, reset) {
    this.b = this.computeLabel(instance2, this.h.config.tabs.title, "title", reset);
    this.c = this.computeLabel(
      instance2,
      this.h.config.tabs.description,
      "description"
      /* TerminalLabelType.Description */
    );
    if (this.b !== instance2.title || this.c !== instance2.description || reset) {
      this.f.fire({ title: this.b, description: this.c });
    }
  }
  computeLabel(instance2, labelTemplate, labelType, reset) {
    const type = instance2.shellLaunchConfig.attachPersistentProcess?.type || instance2.shellLaunchConfig.type;
    const commandDetection = instance2.capabilities.get(
      2
      /* TerminalCapability.CommandDetection */
    );
    const promptInputModel = commandDetection?.promptInputModel;
    const nonTaskSpinner = type === "Task" ? "" : " $(loading~spin)";
    const templateProperties = {
      cwd: instance2.cwd || instance2.initialCwd || "",
      cwdFolder: "",
      workspaceFolderName: instance2.workspaceFolder?.name,
      workspaceFolder: instance2.workspaceFolder ? $rc(instance2.workspaceFolder.uri.fsPath) : void 0,
      local: type === "Local" ? $Kec.typeLocal : void 0,
      process: instance2.processName,
      sequence: instance2.sequence,
      task: type === "Task" ? $Kec.typeTask : void 0,
      fixedDimensions: instance2.fixedCols ? instance2.fixedRows ? `\u2194${instance2.fixedCols} \u2195${instance2.fixedRows}` : `\u2194${instance2.fixedCols}` : instance2.fixedRows ? `\u2195${instance2.fixedRows}` : "",
      separator: { label: this.h.config.tabs.separator },
      shellType: instance2.shellType,
      shellCommand: commandDetection?.executingCommand && promptInputModel ? promptInputModel.value + nonTaskSpinner : void 0,
      shellPromptInput: commandDetection?.executingCommand && promptInputModel ? promptInputModel.getCombinedString(true) + nonTaskSpinner : promptInputModel?.getCombinedString(true)
    };
    templateProperties.workspaceFolderName = instance2.workspaceFolder?.name ?? templateProperties.workspaceFolder;
    labelTemplate = labelTemplate.trim();
    if (!labelTemplate) {
      return labelType === "title" ? instance2.processName || "" : "";
    }
    if (!reset && instance2.staticTitle && labelType === "title") {
      return instance2.staticTitle.replace(/[\n\r\t]/g, "") || templateProperties.process?.replace(/[\n\r\t]/g, "") || "";
    }
    const detection = instance2.capabilities.has(
      0
      /* TerminalCapability.CwdDetection */
    ) || instance2.capabilities.has(
      1
      /* TerminalCapability.NaiveCwdDetection */
    );
    const folders = this.j.getWorkspace().folders;
    const multiRootWorkspace = folders.length > 1;
    if (templateProperties.cwd && detection && (!instance2.shellLaunchConfig.isFeatureTerminal || labelType === "title")) {
      const cwdUri = URI.from({
        scheme: instance2.workspaceFolder?.uri.scheme || Schemas.file,
        path: instance2.cwd ? $oc(instance2.cwd) : void 0
      });
      let showCwd = false;
      if (multiRootWorkspace) {
        showCwd = true;
      } else if (instance2.workspaceFolder?.uri) {
        const caseSensitive = this.g.hasCapability(
          instance2.workspaceFolder.uri,
          1024
          /* FileSystemProviderCapabilities.PathCaseSensitive */
        );
        showCwd = cwdUri.fsPath.localeCompare(instance2.workspaceFolder.uri.fsPath, void 0, { sensitivity: caseSensitive ? "case" : "base" }) !== 0;
      }
      if (showCwd) {
        templateProperties.cwdFolder = $rc(templateProperties.cwd);
      }
    }
    const label3 = $5t(labelTemplate, templateProperties).replace(/[\n\r\t]/g, "").trim();
    return label3 === "" && labelType === "title" ? instance2.processName || "" : label3;
  }
};
$xfc = __decorate([
  __param(0, $km),
  __param(1, $5Pb),
  __param(2, $Zk)
], $xfc);
function $yfc(exitCodeOrError, shellLaunchConfig, processState, initialCwd) {
  if (exitCodeOrError === void 0 || exitCodeOrError === 0) {
    return { code: exitCodeOrError, message: void 0 };
  }
  const code = typeof exitCodeOrError === "number" ? exitCodeOrError : exitCodeOrError.code;
  let message = void 0;
  switch (typeof exitCodeOrError) {
    case "number": {
      let commandLine = void 0;
      if (shellLaunchConfig.executable) {
        commandLine = shellLaunchConfig.executable;
        if (typeof shellLaunchConfig.args === "string") {
          commandLine += ` ${shellLaunchConfig.args}`;
        } else if (shellLaunchConfig.args && shellLaunchConfig.args.length) {
          commandLine += shellLaunchConfig.args.map((a) => ` '${a}'`).join();
        }
      }
      if (processState === 4) {
        if (commandLine) {
          message = localize(10481, null, commandLine, code);
        } else {
          message = localize(10482, null, code);
        }
      } else {
        if (commandLine) {
          message = localize(10483, null, commandLine, code);
        } else {
          message = localize(10484, null, code);
        }
      }
      break;
    }
    case "object": {
      if (exitCodeOrError.message.toString().includes("Could not find pty with id")) {
        break;
      }
      let innerMessage = exitCodeOrError.message;
      const conptyError = exitCodeOrError.message.match(/.*error code:\s*(\d+).*$/);
      if (conptyError) {
        const errorCode = conptyError.length > 1 ? parseInt(conptyError[1]) : void 0;
        switch (errorCode) {
          case 5:
            innerMessage = `Access was denied to the path containing your executable "${shellLaunchConfig.executable}". Manage and change your permissions to get this to work`;
            break;
          case 267:
            innerMessage = `Invalid starting directory "${initialCwd}", review your terminal.integrated.cwd setting`;
            break;
          case 1260:
            innerMessage = `Windows cannot open this program because it has been prevented by a software restriction policy. For more information, open Event Viewer or contact your system Administrator`;
            break;
        }
      }
      message = localize(10485, null, innerMessage);
      break;
    }
  }
  return { code, message };
}
var $zfc = class $zfc2 {
  constructor(b, c) {
    this.b = b;
    this.c = c;
  }
  getBackgroundColor(theme) {
    const terminalBackground = theme.getColor($$Ob);
    if (terminalBackground) {
      return terminalBackground;
    }
    if (this.b.object === TerminalLocation2.Editor) {
      return theme.getColor($Ko);
    }
    const location3 = this.c.getViewLocationById($7X);
    if (location3 === 1) {
      return theme.getColor($Imb);
    }
    return theme.getColor($Pnb);
  }
};
$zfc = __decorate([
  __param(1, $$M)
], $zfc);

// out-build/vs/workbench/contrib/terminal/browser/terminalInstanceService.js
var $Afc = class $Afc2 extends $3c {
  get onDidCreateInstance() {
    return this.c.event;
  }
  get onDidRegisterBackend() {
    return this.f.event;
  }
  constructor(g, h3, environmentService) {
    super();
    this.g = g;
    this.h = h3;
    this.b = /* @__PURE__ */ new Map();
    this.c = this.B(new $ze());
    this.f = this.B(new $ze());
    this.a = TerminalContextKeys.shellType.bindTo(this.h);
    for (const remoteAuthority of [void 0, environmentService.remoteAuthority]) {
      const { promise, resolve } = $Oh();
      this.b.set(remoteAuthority, { promise, resolve });
    }
  }
  createInstance(config, target) {
    const shellLaunchConfig = this.convertProfileToShellLaunchConfig(config);
    const instance2 = this.g.createInstance($wfc, this.a, shellLaunchConfig);
    instance2.target = target;
    this.c.fire(instance2);
    return instance2;
  }
  convertProfileToShellLaunchConfig(shellLaunchConfigOrProfile, cwd2) {
    if (shellLaunchConfigOrProfile && "profileName" in shellLaunchConfigOrProfile) {
      const profile = shellLaunchConfigOrProfile;
      if (!profile.path) {
        return shellLaunchConfigOrProfile;
      }
      return {
        executable: profile.path,
        args: profile.args,
        env: profile.env,
        icon: profile.icon,
        color: profile.color,
        name: profile.overrideName ? profile.profileName : void 0,
        cwd: cwd2
      };
    }
    if (shellLaunchConfigOrProfile) {
      if (cwd2) {
        shellLaunchConfigOrProfile.cwd = cwd2;
      }
      return shellLaunchConfigOrProfile;
    }
    return {};
  }
  async getBackend(remoteAuthority) {
    let backend = $Wn.as($6x.Backend).getTerminalBackend(remoteAuthority);
    if (!backend) {
      await this.b.get(remoteAuthority)?.promise;
      backend = $Wn.as($6x.Backend).getTerminalBackend(remoteAuthority);
    }
    return backend;
  }
  getRegisteredBackends() {
    return $Wn.as($6x.Backend).backends.values();
  }
  didRegisterBackend(backend) {
    this.b.get(backend.remoteAuthority)?.resolve();
    this.f.fire(backend);
  }
};
$Afc = __decorate([
  __param(0, $Pk),
  __param(1, $on),
  __param(2, $US)
], $Afc);
$SC(
  $8Pb,
  $Afc,
  1
  /* InstantiationType.Delayed */
);

// out-build/vs/workbench/contrib/terminal/browser/terminalMainContribution.js
var $Bfc = class $Bfc2 extends $3c {
  static {
    this.ID = "terminalMain";
  }
  constructor(editorResolverService, embedderTerminalService, workbenchEnvironmentService, labelService, lifecycleService, terminalService, terminalEditorService, terminalGroupService, terminalInstanceService) {
    super();
    this.a(editorResolverService, embedderTerminalService, workbenchEnvironmentService, labelService, lifecycleService, terminalService, terminalEditorService, terminalGroupService, terminalInstanceService);
  }
  async a(editorResolverService, embedderTerminalService, workbenchEnvironmentService, labelService, lifecycleService, terminalService, terminalEditorService, terminalGroupService, terminalInstanceService) {
    this.B(embedderTerminalService.onDidCreateTerminal(async (embedderTerminal) => {
      const terminal2 = await terminalService.createTerminal({
        config: embedderTerminal,
        location: TerminalLocation2.Panel,
        skipContributedProfileCheck: true
      });
      terminalService.setActiveInstance(terminal2);
      await terminalService.revealActiveTerminal();
    }));
    await lifecycleService.when(
      3
      /* LifecyclePhase.Restored */
    );
    this.B(editorResolverService.registerEditor(`${Schemas.vscodeTerminal}:/**`, {
      id: $$Pb,
      label: $Kec.terminal,
      priority: RegisteredEditorPriority.exclusive
    }, {
      canSupportResource: (uri) => uri.scheme === Schemas.vscodeTerminal,
      singlePerResource: true
    }, {
      createEditorInput: async ({ resource, options: options3 }) => {
        let instance2 = terminalService.getInstanceFromResource(resource);
        if (instance2) {
          const sourceGroup = terminalGroupService.getGroupForInstance(instance2);
          sourceGroup?.removeInstance(instance2);
        } else {
          const terminalIdentifier = $0ec(resource);
          if (!terminalIdentifier.instanceId) {
            throw new Error("Terminal identifier without instanceId");
          }
          const primaryBackend = terminalService.getPrimaryBackend();
          if (!primaryBackend) {
            throw new Error("No terminal primary backend");
          }
          const attachPersistentProcess = await primaryBackend.requestDetachInstance(terminalIdentifier.workspaceId, terminalIdentifier.instanceId);
          if (!attachPersistentProcess) {
            throw new Error("No terminal persistent process to attach");
          }
          instance2 = terminalInstanceService.createInstance({ attachPersistentProcess }, TerminalLocation2.Editor);
        }
        const resolvedResource = terminalEditorService.resolveResource(instance2);
        const editor = terminalEditorService.getInputFromResource(resolvedResource);
        return {
          editor,
          options: {
            ...options3,
            pinned: true,
            forceReload: true,
            override: $$Pb
          }
        };
      }
    }));
    this.B(labelService.registerFormatter({
      scheme: Schemas.vscodeTerminal,
      formatting: {
        label: "${path}",
        separator: ""
      }
    }));
  }
};
$Bfc = __decorate([
  __param(0, $4L),
  __param(1, $U4),
  __param(2, $US),
  __param(3, $ZI),
  __param(4, $KL),
  __param(5, $4Pb),
  __param(6, $6Pb),
  __param(7, $7Pb),
  __param(8, $8Pb)
], $Bfc);

// out-build/vs/workbench/contrib/terminal/common/terminalExtensionPoints.js
var terminalsExtPoint = $tN.registerExtensionPoint($lY);
var $Cfc = $Qk("terminalContributionsService");
var $Dfc = class {
  get terminalProfiles() {
    return this.a;
  }
  constructor() {
    this.a = [];
    terminalsExtPoint.setHandler((contributions) => {
      this.a = contributions.map((c) => {
        return c.value?.profiles?.filter((p) => hasValidTerminalIcon(p)).map((e) => {
          return { ...e, extensionIdentifier: c.description.identifier.value };
        }) || [];
      }).flat();
    });
  }
};
function hasValidTerminalIcon(profile) {
  return !profile.icon || (typeof profile.icon === "string" || URI.isUri(profile.icon) || "light" in profile.icon && "dark" in profile.icon && URI.isUri(profile.icon.light) && URI.isUri(profile.icon.dark));
}

// out-build/vs/workbench/contrib/terminal/browser/terminalProfileService.js
var $Efc = class $Efc2 extends $3c {
  get onDidChangeAvailableProfiles() {
    return this.s.event;
  }
  get profilesReady() {
    return this.c;
  }
  get availableProfiles() {
    if (!this.m) {
      this.refreshAvailableProfiles();
    }
    return this.f || [];
  }
  get contributedProfiles() {
    const userConfiguredProfileNames = this.f?.map((p) => p.profileName) || [];
    return this.h?.filter((p) => !userConfiguredProfileNames.includes(p.title)) || [];
  }
  constructor(t, u, w, y, z, C, D) {
    super();
    this.t = t;
    this.u = u;
    this.w = w;
    this.y = y;
    this.z = z;
    this.C = C;
    this.D = D;
    this.h = [];
    this.m = false;
    this.n = this.B(new $4c());
    this.r = /* @__PURE__ */ new Map();
    this.s = this.B(new $ze());
    this.B(this.y.onDidChangeExtensions(() => this.refreshAvailableProfiles()));
    this.a = TerminalContextKeys.webExtensionContributedProfile.bindTo(this.t);
    this.L();
    this.c = this.z.getEnvironment().then(() => {
      this.b = new $Vh(2e4);
      return this.b.wait().then(() => {
      });
    });
    this.refreshAvailableProfiles();
    this.F();
  }
  async F() {
    const platformKey = await this.getPlatformKey();
    this.B(this.u.onDidChangeConfiguration(async (e) => {
      if (e.affectsConfiguration("terminal.integrated.automationProfile." + platformKey) || e.affectsConfiguration("terminal.integrated.defaultProfile." + platformKey) || e.affectsConfiguration("terminal.integrated.profiles." + platformKey) || e.affectsConfiguration(
        "terminal.integrated.useWslProfiles"
        /* TerminalSettingId.UseWslProfiles */
      )) {
        if (e.source !== 7) {
          this.refreshAvailableProfiles();
          this.m = false;
        } else {
          this.m = true;
        }
      }
    }));
  }
  getDefaultProfileName() {
    return this.j;
  }
  getDefaultProfile(os) {
    let defaultProfileName;
    if (os) {
      defaultProfileName = this.u.getValue(`${"terminal.integrated.defaultProfile."}${this.G(os)}`);
      if (!defaultProfileName || typeof defaultProfileName !== "string") {
        return void 0;
      }
    } else {
      defaultProfileName = this.j;
    }
    if (!defaultProfileName) {
      return void 0;
    }
    return this.availableProfiles.find((e) => e.profileName === defaultProfileName && !e.isAutoDetected);
  }
  G(os) {
    switch (os) {
      case 3:
        return "linux";
      case 2:
        return "osx";
      case 1:
        return "windows";
    }
  }
  refreshAvailableProfiles() {
    this.H();
  }
  async H() {
    const profiles2 = await this.J(true);
    const profilesChanged = !$zb(profiles2, this.f, profilesEqual);
    const contributedProfilesChanged = await this.I();
    const platform = await this.getPlatformKey();
    const automationProfile = this.u.getValue(`${"terminal.integrated.automationProfile."}${platform}`);
    const automationProfileChanged = !$Pv(automationProfile, this.g);
    if (profilesChanged || contributedProfilesChanged || automationProfileChanged) {
      this.f = profiles2;
      this.g = automationProfile;
      this.s.fire(this.f);
      this.b.open();
      this.L();
      await this.M(this.f);
    }
  }
  async I() {
    const platformKey = await this.getPlatformKey();
    const excludedContributedProfiles = [];
    const configProfiles = this.u.getValue("terminal.integrated.profiles." + platformKey);
    for (const [profileName, value] of Object.entries(configProfiles)) {
      if (value === null) {
        excludedContributedProfiles.push(profileName);
      }
    }
    const filteredContributedProfiles = Array.from(this.w.terminalProfiles.filter((p) => !excludedContributedProfiles.includes(p.title)));
    const contributedProfilesChanged = !$zb(filteredContributedProfiles, this.h, contributedProfilesEqual);
    this.h = filteredContributedProfiles;
    return contributedProfilesChanged;
  }
  getContributedProfileProvider(extensionIdentifier, id2) {
    const extMap = this.r.get(extensionIdentifier);
    return extMap?.get(id2);
  }
  async J(includeDetectedProfiles) {
    const primaryBackend = await this.D.getBackend(this.C.remoteAuthority);
    if (!primaryBackend) {
      return this.f || [];
    }
    const platform = await this.getPlatformKey();
    this.j = this.u.getValue(`${"terminal.integrated.defaultProfile."}${platform}`) ?? void 0;
    return primaryBackend.getProfiles(this.u.getValue(`${"terminal.integrated.profiles."}${platform}`), this.j, includeDetectedProfiles);
  }
  L() {
    this.a.set($r && this.h.length > 0);
  }
  async M(profiles2) {
    const env3 = await this.z.getEnvironment();
    $AB({ os: env3?.os || OS, profiles: profiles2 }, this.h);
    this.n.value = $1ec(profiles2);
  }
  async getPlatformKey() {
    const env3 = await this.z.getEnvironment();
    if (env3) {
      return env3.os === 1 ? "windows" : env3.os === 2 ? "osx" : "linux";
    }
    return $l ? "windows" : $m ? "osx" : "linux";
  }
  registerTerminalProfileProvider(extensionIdentifier, id2, profileProvider) {
    let extMap = this.r.get(extensionIdentifier);
    if (!extMap) {
      extMap = /* @__PURE__ */ new Map();
      this.r.set(extensionIdentifier, extMap);
    }
    extMap.set(id2, profileProvider);
    return $1c(() => this.r.delete(id2));
  }
  async registerContributedProfile(args2) {
    const platformKey = await this.getPlatformKey();
    const profilesConfig = await this.u.getValue(`${"terminal.integrated.profiles."}${platformKey}`);
    if (typeof profilesConfig === "object") {
      const newProfile = {
        extensionIdentifier: args2.extensionIdentifier,
        icon: args2.options.icon,
        id: args2.id,
        title: args2.title,
        color: args2.options.color
      };
      profilesConfig[args2.title] = newProfile;
    }
    await this.u.updateValue(
      `${"terminal.integrated.profiles."}${platformKey}`,
      profilesConfig,
      2
      /* ConfigurationTarget.USER */
    );
    return;
  }
  async getContributedDefaultProfile(shellLaunchConfig) {
    if (shellLaunchConfig && !shellLaunchConfig.extHostTerminalId && !("executable" in shellLaunchConfig)) {
      const key2 = await this.getPlatformKey();
      const defaultProfileName = this.u.getValue(`${"terminal.integrated.defaultProfile."}${key2}`);
      const contributedDefaultProfile = this.contributedProfiles.find((p) => p.title === defaultProfileName);
      return contributedDefaultProfile;
    }
    return void 0;
  }
};
__decorate([
  $_t(2e3)
], $Efc.prototype, "refreshAvailableProfiles", null);
$Efc = __decorate([
  __param(0, $on),
  __param(1, $kl),
  __param(2, $Cfc),
  __param(3, $wN),
  __param(4, $RL),
  __param(5, $US),
  __param(6, $8Pb)
], $Efc);
function profilesEqual(one, other) {
  return one.profileName === other.profileName && $uB(one.args, other.args) && one.color === other.color && $vB(one.icon, other.icon) && one.isAutoDetected === other.isAutoDetected && one.isDefault === other.isDefault && one.overrideName === other.overrideName && one.path === other.path;
}
function contributedProfilesEqual(one, other) {
  return one.extensionIdentifier === other.extensionIdentifier && one.color === other.color && one.icon === other.icon && one.id === other.id && one.title === other.title;
}

// out-build/vs/workbench/contrib/terminal/browser/terminalProfileQuickpick.js
var $Lec = class $Lec2 {
  constructor(c, d, f, g, h3, i2) {
    this.c = c;
    this.d = d;
    this.f = f;
    this.g = g;
    this.h = h3;
    this.i = i2;
  }
  async showAndGetResult(type) {
    const platformKey = await this.c.getPlatformKey();
    const profilesKey = "terminal.integrated.profiles." + platformKey;
    const result = await this.j(type);
    const defaultProfileKey = `${"terminal.integrated.defaultProfile."}${platformKey}`;
    if (!result) {
      return;
    }
    if (type === "setDefault") {
      if ("command" in result.profile) {
        return;
      } else if ("id" in result.profile) {
        await this.f.updateValue(
          defaultProfileKey,
          result.profile.title,
          2
          /* ConfigurationTarget.USER */
        );
        return {
          config: {
            extensionIdentifier: result.profile.extensionIdentifier,
            id: result.profile.id,
            title: result.profile.title,
            options: {
              color: result.profile.color,
              icon: result.profile.icon
            }
          },
          keyMods: result.keyMods
        };
      }
      if ("isAutoDetected" in result.profile) {
        const profilesConfig = await this.f.getValue(profilesKey);
        if (typeof profilesConfig === "object") {
          const newProfile = {
            path: result.profile.path
          };
          if (result.profile.args) {
            newProfile.args = result.profile.args;
          }
          profilesConfig[result.profile.profileName] = this.k(result.profile);
          await this.f.updateValue(
            profilesKey,
            profilesConfig,
            2
            /* ConfigurationTarget.USER */
          );
        }
      }
      await this.f.updateValue(
        defaultProfileKey,
        result.profileName,
        2
        /* ConfigurationTarget.USER */
      );
    } else if (type === "createInstance") {
      if ("id" in result.profile) {
        return {
          config: {
            extensionIdentifier: result.profile.extensionIdentifier,
            id: result.profile.id,
            title: result.profile.title,
            options: {
              icon: result.profile.icon,
              color: result.profile.color
            }
          },
          keyMods: result.keyMods
        };
      } else {
        return { config: result.profile, keyMods: result.keyMods };
      }
    }
    return "profileName" in result.profile ? result.profile.profileName : result.profile.title;
  }
  async j(type) {
    const platformKey = await this.c.getPlatformKey();
    const profiles2 = this.c.availableProfiles;
    const profilesKey = "terminal.integrated.profiles." + platformKey;
    const defaultProfileName = this.c.getDefaultProfileName();
    let keyMods;
    const options3 = {
      placeHolder: type === "createInstance" ? localize(10520, null) : localize(10521, null),
      onDidTriggerItemButton: async (context) => {
        if (!await this.l(context.item.profile)) {
          return;
        }
        if ("command" in context.item.profile) {
          return;
        }
        if ("id" in context.item.profile) {
          return;
        }
        const configProfiles2 = this.f.getValue("terminal.integrated.profiles." + platformKey);
        const existingProfiles = !!configProfiles2 ? Object.keys(configProfiles2) : [];
        const name = await this.g.input({
          prompt: localize(10522, null),
          value: context.item.profile.profileName,
          validateInput: async (input) => {
            if (existingProfiles.includes(input)) {
              return localize(10523, null);
            }
            return void 0;
          }
        });
        if (!name) {
          return;
        }
        const newConfigValue = {
          ...configProfiles2,
          [name]: this.k(context.item.profile)
        };
        await this.f.updateValue(
          profilesKey,
          newConfigValue,
          2
          /* ConfigurationTarget.USER */
        );
      },
      onKeyMods: (mods) => keyMods = mods
    };
    const quickPickItems = [];
    const configProfiles = profiles2.filter((e) => !e.isAutoDetected);
    const autoDetectedProfiles = profiles2.filter((e) => e.isAutoDetected);
    if (configProfiles.length > 0) {
      quickPickItems.push({ type: "separator", label: localize(10524, null) });
      quickPickItems.push(...this.n(configProfiles.map((e) => this.m(e)), defaultProfileName));
    }
    quickPickItems.push({ type: "separator", label: localize(10525, null) });
    const contributedProfiles = [];
    for (const contributed of this.c.contributedProfiles) {
      let icon2;
      if (typeof contributed.icon === "string") {
        if (contributed.icon.startsWith("$(")) {
          icon2 = ThemeIcon.fromString(contributed.icon);
        } else {
          icon2 = ThemeIcon.fromId(contributed.icon);
        }
      }
      if (!icon2 || !$0r().getIcon(icon2.id)) {
        icon2 = this.d.getDefaultIcon();
      }
      const uriClasses = $dQb(contributed, this.h.getColorTheme().type, true);
      const colorClass = $_Pb(contributed);
      const iconClasses = [];
      if (uriClasses) {
        iconClasses.push(...uriClasses);
      }
      if (colorClass) {
        iconClasses.push(colorClass);
      }
      contributedProfiles.push({
        label: `$(${icon2.id}) ${contributed.title}`,
        profile: {
          extensionIdentifier: contributed.extensionIdentifier,
          title: contributed.title,
          icon: contributed.icon,
          id: contributed.id,
          color: contributed.color
        },
        profileName: contributed.title,
        iconClasses
      });
    }
    if (contributedProfiles.length > 0) {
      quickPickItems.push(...this.n(contributedProfiles, defaultProfileName));
    }
    if (autoDetectedProfiles.length > 0) {
      quickPickItems.push({ type: "separator", label: localize(10526, null) });
      quickPickItems.push(...this.n(autoDetectedProfiles.map((e) => this.m(e)), defaultProfileName));
    }
    const colorStyleDisposable = $bQb(this.h.getColorTheme());
    const result = await this.g.pick(quickPickItems, options3);
    colorStyleDisposable.dispose();
    if (!result) {
      return void 0;
    }
    if (!await this.l(result.profile)) {
      return void 0;
    }
    if (keyMods) {
      result.keyMods = keyMods;
    }
    return result;
  }
  k(profile) {
    const result = { path: profile.path };
    if (profile.args) {
      result.args = profile.args;
    }
    if (profile.env) {
      result.env = profile.env;
    }
    return result;
  }
  async l(profile) {
    const isUnsafePath = "isUnsafePath" in profile && profile.isUnsafePath;
    const requiresUnsafePath = "requiresUnsafePath" in profile && profile.requiresUnsafePath;
    if (!isUnsafePath && !requiresUnsafePath) {
      return true;
    }
    return await new Promise((r2) => {
      const unsafePaths = [];
      if (isUnsafePath) {
        unsafePaths.push(profile.path);
      }
      if (requiresUnsafePath) {
        unsafePaths.push(requiresUnsafePath);
      }
      const handle2 = this.i.prompt(Severity2.Warning, localize(10527, null, `"${unsafePaths.join(",")}"`), [{
        label: localize(10528, null),
        run: () => r2(true)
      }, {
        label: localize(10529, null),
        run: () => r2(false)
      }]);
      handle2.onDidClose(() => r2(false));
    });
  }
  m(profile) {
    const buttons = [{
      iconClass: ThemeIcon.asClassName($OPb),
      tooltip: localize(10530, null)
    }];
    const icon2 = profile.icon && ThemeIcon.isThemeIcon(profile.icon) ? profile.icon : $6l.terminal;
    const label3 = `$(${icon2.id}) ${profile.profileName}`;
    const friendlyPath = profile.isFromPath ? $rc(profile.path) : profile.path;
    const colorClass = $_Pb(profile);
    const iconClasses = [];
    if (colorClass) {
      iconClasses.push(colorClass);
    }
    if (profile.args) {
      if (typeof profile.args === "string") {
        return { label: label3, description: `${profile.path} ${profile.args}`, profile, profileName: profile.profileName, buttons, iconClasses };
      }
      const argsString = profile.args.map((e) => {
        if (e.includes(" ")) {
          return `"${e.replace(/"/g, '\\"')}"`;
        }
        return e;
      }).join(" ");
      return { label: label3, description: `${friendlyPath} ${argsString}`, profile, profileName: profile.profileName, buttons, iconClasses };
    }
    return { label: label3, description: friendlyPath, profile, profileName: profile.profileName, buttons, iconClasses };
  }
  n(items, defaultProfileName) {
    return items.sort((a, b) => {
      if (b.profileName === defaultProfileName) {
        return 1;
      }
      if (a.profileName === defaultProfileName) {
        return -1;
      }
      return a.profileName.localeCompare(b.profileName);
    });
  }
};
$Lec = __decorate([
  __param(0, $hY),
  __param(1, $fY),
  __param(2, $kl),
  __param(3, $1M),
  __param(4, $gs),
  __param(5, $PJ)
], $Lec);

// out-build/vs/workbench/contrib/terminal/browser/terminalEvents.js
function $Ffc(currentInstances, onAddInstance, onRemoveInstance, capabilityId, getEvent) {
  const store = new $2c();
  const multiplexer = store.add(new $Fe());
  const capabilityListeners = store.add(new $_c());
  function addCapability(instance2, capability) {
    const listener = multiplexer.add(Event2.map(getEvent(capability), (data) => ({ instance: instance2, data })));
    let instanceCapabilityListeners = capabilityListeners.get(instance2.instanceId);
    if (!instanceCapabilityListeners) {
      instanceCapabilityListeners = new $_c();
      capabilityListeners.set(instance2.instanceId, instanceCapabilityListeners);
    }
    instanceCapabilityListeners.set(capability, listener);
  }
  for (const instance2 of currentInstances) {
    const capability = instance2.capabilities.get(capabilityId);
    if (capability) {
      addCapability(instance2, capability);
    }
  }
  store.add(onRemoveInstance((instance2) => {
    capabilityListeners.deleteAndDispose(instance2.instanceId);
  }));
  const addCapabilityMultiplexer = store.add(new $Ge(currentInstances, onAddInstance, onRemoveInstance, (instance2) => Event2.map(instance2.capabilities.onDidAddCapability, (changeEvent) => ({ instance: instance2, changeEvent }))));
  store.add(addCapabilityMultiplexer.event((e) => {
    if (e.changeEvent.id === capabilityId) {
      addCapability(e.instance, e.changeEvent.capability);
    }
  }));
  const removeCapabilityMultiplexer = store.add(new $Ge(currentInstances, onAddInstance, onRemoveInstance, (instance2) => Event2.map(instance2.capabilities.onDidRemoveCapability, (changeEvent) => ({ instance: instance2, changeEvent }))));
  store.add(removeCapabilityMultiplexer.event((e) => {
    if (e.changeEvent.id === capabilityId) {
      capabilityListeners.get(e.instance.instanceId)?.deleteAndDispose(e.changeEvent.id);
    }
  }));
  return {
    dispose: () => store.dispose(),
    event: multiplexer.event
  };
}

// out-build/vs/workbench/contrib/terminal/browser/terminalService.js
var $Gfc = class $Gfc2 extends $3c {
  get isProcessSupportRegistered() {
    return !!this.n.get();
  }
  get connectionState() {
    return this.D;
  }
  get whenConnected() {
    return this.F.p;
  }
  get restoredGroupCount() {
    return this.G;
  }
  get instances() {
    return this.kb.instances.concat(this.jb.instances).concat(this.j);
  }
  get detachedInstances() {
    return this.b;
  }
  getReconnectedTerminals(reconnectionOwner) {
    return this.I.get(reconnectionOwner);
  }
  get defaultLocation() {
    return this.ib.config.defaultLocation === "editor" ? TerminalLocation2.Editor : TerminalLocation2.Panel;
  }
  get activeInstance() {
    for (const activeHostTerminal of this.a.values()) {
      if (activeHostTerminal?.hasFocus) {
        return activeHostTerminal;
      }
    }
    return this.J;
  }
  get onDidCreateInstance() {
    return this.M.event;
  }
  get onDidChangeInstanceDimensions() {
    return this.N.event;
  }
  get onDidRegisterProcessSupport() {
    return this.O.event;
  }
  get onDidChangeConnectionState() {
    return this.P.event;
  }
  get onDidRequestStartExtensionTerminal() {
    return this.Q.event;
  }
  get onDidDisposeInstance() {
    return this.R.event;
  }
  get onDidFocusInstance() {
    return this.S.event;
  }
  get onDidChangeActiveInstance() {
    return this.U.event;
  }
  get onDidChangeInstances() {
    return this.W.event;
  }
  get onDidChangeInstanceCapability() {
    return this.X.event;
  }
  get onDidChangeActiveGroup() {
    return this.Y.event;
  }
  // Lazily initialized events that fire when the specified event fires on _any_ terminal
  // TODO: Batch events
  get onAnyInstanceData() {
    return this.B(this.createOnInstanceEvent((instance2) => Event2.map(instance2.onData, (data) => ({ instance: instance2, data })))).event;
  }
  get onAnyInstanceDataInput() {
    return this.B(this.createOnInstanceEvent((e) => Event2.map(e.onDidInputData, () => e, e.store))).event;
  }
  get onAnyInstanceIconChange() {
    return this.B(this.createOnInstanceEvent((e) => e.onIconChanged)).event;
  }
  get onAnyInstanceMaximumDimensionsChange() {
    return this.B(this.createOnInstanceEvent((e) => Event2.map(e.onMaximumDimensionsChanged, () => e, e.store))).event;
  }
  get onAnyInstancePrimaryStatusChange() {
    return this.B(this.createOnInstanceEvent((e) => Event2.map(e.statusList.onDidChangePrimaryStatus, () => e, e.store))).event;
  }
  get onAnyInstanceProcessIdReady() {
    return this.B(this.createOnInstanceEvent((e) => e.onProcessIdReady)).event;
  }
  get onAnyInstanceSelectionChange() {
    return this.B(this.createOnInstanceEvent((e) => e.onDidChangeSelection)).event;
  }
  get onAnyInstanceTitleChange() {
    return this.B(this.createOnInstanceEvent((e) => e.onTitleChanged)).event;
  }
  constructor(Z, $149, ab, bb, cb, db, eb, fb, gb, hb, ib, jb, kb, lb, mb, nb, ob, pb, qb, rb, sb, tb) {
    super();
    this.Z = Z;
    this.$ = $149;
    this.ab = ab;
    this.bb = bb;
    this.cb = cb;
    this.db = db;
    this.eb = eb;
    this.fb = fb;
    this.gb = gb;
    this.hb = hb;
    this.ib = ib;
    this.jb = jb;
    this.kb = kb;
    this.lb = lb;
    this.mb = mb;
    this.nb = nb;
    this.ob = ob;
    this.pb = pb;
    this.qb = qb;
    this.rb = rb;
    this.sb = sb;
    this.tb = tb;
    this.a = /* @__PURE__ */ new Map();
    this.b = /* @__PURE__ */ new Set();
    this.h = false;
    this.j = [];
    this.m = /* @__PURE__ */ new Map();
    this.D = 0;
    this.F = new $gi();
    this.G = 0;
    this.I = /* @__PURE__ */ new Map();
    this.M = this.B(new $ze());
    this.N = this.B(new $ze());
    this.O = this.B(new $ze());
    this.P = this.B(new $ze());
    this.Q = this.B(new $ze());
    this.R = this.B(new $ze());
    this.S = this.B(new $ze());
    this.U = this.B(new $ze());
    this.W = this.B(new $ze());
    this.X = this.B(new $ze());
    this.Y = this.B(new $ze());
    this.B(this.onDidCreateInstance(() => this.nb.refreshAvailableProfiles()));
    this.vb(this.kb);
    this.vb(this.jb);
    this.B(this.kb.onDidChangeActiveGroup(this.Y.fire, this.Y));
    this.B(this.lb.onDidCreateInstance((instance2) => {
      this.Mb(instance2);
      this.M.fire(instance2);
    }));
    this.B(this.kb.onDidChangeActiveInstance((instance2) => {
      if (!instance2 && !this.h) {
        this.kb.hidePanel();
      }
      if (instance2?.shellType) {
        this.f.set(instance2.shellType.toString());
      } else if (!instance2 || !instance2.shellType) {
        this.f.reset();
      }
    }));
    this.Db();
    this.f = TerminalContextKeys.shellType.bindTo(this.Z);
    this.n = TerminalContextKeys.processSupported.bindTo(this.Z);
    this.n.set(!$r || this.db.getConnection() !== null);
    this.u = TerminalContextKeys.terminalHasBeenCreated.bindTo(this.Z);
    this.w = TerminalContextKeys.count.bindTo(this.Z);
    this.c = TerminalContextKeys.terminalEditorActive.bindTo(this.Z);
    this.B(this.onDidChangeActiveInstance((instance2) => {
      this.c.set(!!instance2?.target && instance2.target === TerminalLocation2.Editor);
    }));
    this.B($149.onBeforeShutdown(async (e) => e.veto(this.Eb(e.reason), "veto.terminal")));
    this.B($149.onWillShutdown((e) => this.Ib(e)));
    this.ub();
    $Wh(0).then(() => this.B(this.cb.createInstance(TerminalEditorStyle, $Y.document.head)));
  }
  async showProfileQuickPick(type, cwd2) {
    const quickPick = this.cb.createInstance($Lec);
    const result = await quickPick.showAndGetResult(type);
    if (!result) {
      return;
    }
    if (typeof result === "string") {
      return;
    }
    const keyMods = result.keyMods;
    if (type === "createInstance") {
      const activeInstance = this.getDefaultInstanceHost().activeInstance;
      let instance2;
      if (result.config && "id" in result?.config) {
        await this.createContributedTerminalProfile(result.config.extensionIdentifier, result.config.id, {
          icon: result.config.options?.icon,
          color: result.config.options?.color,
          location: !!(keyMods?.alt && activeInstance) ? { splitActiveTerminal: true } : this.defaultLocation
        });
        return;
      } else if (result.config && "profileName" in result.config) {
        if (keyMods?.alt && activeInstance) {
          instance2 = await this.createTerminal({ location: { parentTerminal: activeInstance }, config: result.config, cwd: cwd2 });
        } else {
          instance2 = await this.createTerminal({ location: this.defaultLocation, config: result.config, cwd: cwd2 });
        }
      }
      if (instance2 && this.defaultLocation !== TerminalLocation2.Editor) {
        this.kb.showPanel(true);
        this.setActiveInstance(instance2);
        return instance2;
      }
    }
    return void 0;
  }
  async ub() {
    $S("code/terminal/willGetTerminalBackend");
    this.s = await this.lb.getBackend(this.hb.remoteAuthority);
    $S("code/terminal/didGetTerminalBackend");
    const enableTerminalReconnection = this.ib.config.enablePersistentSessions;
    this.D = 0;
    const isPersistentRemote = !!this.hb.remoteAuthority && enableTerminalReconnection;
    if (this.s) {
      this.B(this.s.onDidRequestDetach(async (e) => {
        const instanceToDetach = this.getInstanceFromResource($$ec(e.workspaceId, e.instanceId));
        if (instanceToDetach) {
          const persistentProcessId = instanceToDetach?.persistentProcessId;
          if (persistentProcessId && !instanceToDetach.shellLaunchConfig.isFeatureTerminal && !instanceToDetach.shellLaunchConfig.customPtyImplementation) {
            if (instanceToDetach.target === TerminalLocation2.Editor) {
              this.jb.detachInstance(instanceToDetach);
            } else {
              this.kb.getGroupForInstance(instanceToDetach)?.removeInstance(instanceToDetach);
            }
            await instanceToDetach.detachProcessAndDispose(TerminalExitReason2.User);
            await this.s?.acceptDetachInstanceReply(e.requestId, persistentProcessId);
          } else {
            await this.s?.acceptDetachInstanceReply(e.requestId, void 0);
          }
        }
      }));
    }
    $S("code/terminal/willReconnect");
    let reconnectedPromise;
    if (isPersistentRemote) {
      reconnectedPromise = this.yb();
    } else if (enableTerminalReconnection) {
      reconnectedPromise = this.zb();
    } else {
      reconnectedPromise = Promise.resolve();
    }
    reconnectedPromise.then(async () => {
      this.xb();
      $S("code/terminal/didReconnect");
      $S("code/terminal/willReplay");
      const instances = await this.H?.then((groups) => groups.map((e) => e.terminalInstances).flat()) ?? [];
      await Promise.all(instances.map((e) => new Promise((r2) => Event2.once(e.onProcessReplayComplete)(r2))));
      $S("code/terminal/didReplay");
      $S("code/terminal/willGetPerformanceMarks");
      await Promise.all(Array.from(this.lb.getRegisteredBackends()).map(async (backend) => {
        this.tb.setPerformanceMarks(backend.remoteAuthority === void 0 ? "localPtyHost" : "remotePtyHost", await backend.getPerformanceMarks());
        backend.setReady();
      }));
      $S("code/terminal/didGetPerformanceMarks");
      this.F.complete();
    });
  }
  getPrimaryBackend() {
    return this.s;
  }
  vb(host) {
    this.B(host.onDidChangeInstances(this.W.fire, this.W));
    this.B(host.onDidDisposeInstance(this.R.fire, this.R));
    this.B(host.onDidChangeActiveInstance((instance2) => this.wb(host, instance2)));
    this.B(host.onDidFocusInstance((instance2) => {
      this.S.fire(instance2);
      this.wb(host, instance2);
    }));
    this.B(host.onDidChangeInstanceCapability((instance2) => {
      this.X.fire(instance2);
    }));
    this.a.set(host, void 0);
  }
  wb(host, instance2) {
    this.a.set(host, instance2);
    if (instance2 === void 0) {
      for (const active of this.a.values()) {
        if (active) {
          instance2 = active;
        }
      }
    }
    this.J = instance2;
    this.U.fire(instance2);
  }
  setActiveInstance(value) {
    if (value.shellLaunchConfig.hideFromUser) {
      this.Yb(value);
    }
    if (value.target === TerminalLocation2.Editor) {
      this.jb.setActiveInstance(value);
    } else {
      this.kb.setActiveInstance(value);
    }
  }
  async focusInstance(instance2) {
    if (instance2.target === TerminalLocation2.Editor) {
      return this.jb.focusInstance(instance2);
    }
    return this.kb.focusInstance(instance2);
  }
  async focusActiveInstance() {
    if (!this.J) {
      return;
    }
    return this.focusInstance(this.J);
  }
  async createContributedTerminalProfile(extensionIdentifier, id2, options3) {
    await this.ob.activateByEvent(`onTerminalProfile:${id2}`);
    const profileProvider = this.nb.getContributedProfileProvider(extensionIdentifier, id2);
    if (!profileProvider) {
      this.pb.error(`No terminal profile provider registered for id "${id2}"`);
      return;
    }
    try {
      await profileProvider.createContributedTerminalProfile(options3);
      this.kb.setActiveInstanceByIndex(this.kb.instances.length - 1);
      await this.kb.activeInstance?.focusWhenReady();
    } catch (e) {
      this.pb.error(e.message);
    }
  }
  async safeDisposeTerminal(instance2) {
    if (instance2.target !== TerminalLocation2.Editor && instance2.hasChildProcesses && (this.ib.config.confirmOnKill === "panel" || this.ib.config.confirmOnKill === "always")) {
      const veto = await this.Pb(true);
      if (veto) {
        return;
      }
    }
    return new Promise((r2) => {
      Event2.once(instance2.onExit)(() => r2());
      instance2.dispose(TerminalExitReason2.User);
    });
  }
  xb() {
    this.D = 1;
    this.P.fire();
    this.ab.trace("Pty host ready");
  }
  async yb() {
    const remoteAuthority = this.hb.remoteAuthority;
    if (!remoteAuthority) {
      return;
    }
    const backend = await this.lb.getBackend(remoteAuthority);
    if (!backend) {
      return;
    }
    $S("code/terminal/willGetTerminalLayoutInfo");
    const layoutInfo = await backend.getTerminalLayoutInfo();
    $S("code/terminal/didGetTerminalLayoutInfo");
    backend.reduceConnectionGraceTime();
    $S("code/terminal/willRecreateTerminalGroups");
    await this.Ab(layoutInfo);
    $S("code/terminal/didRecreateTerminalGroups");
    this.Cb();
    this.ab.trace("Reconnected to remote terminals");
  }
  async zb() {
    const localBackend = await this.lb.getBackend();
    if (!localBackend) {
      return;
    }
    $S("code/terminal/willGetTerminalLayoutInfo");
    const layoutInfo = await localBackend.getTerminalLayoutInfo();
    $S("code/terminal/didGetTerminalLayoutInfo");
    if (layoutInfo && layoutInfo.tabs.length > 0) {
      $S("code/terminal/willRecreateTerminalGroups");
      this.H = this.Ab(layoutInfo);
      $S("code/terminal/didRecreateTerminalGroups");
    }
    this.Cb();
    this.ab.trace("Reconnected to local terminals");
  }
  Ab(layoutInfo) {
    const groupPromises = [];
    let activeGroup;
    if (layoutInfo) {
      for (const tabLayout of layoutInfo.tabs) {
        const terminalLayouts = tabLayout.terminals.filter((t) => t.terminal && t.terminal.isOrphan);
        if (terminalLayouts.length) {
          this.G += terminalLayouts.length;
          const promise = this.Bb(tabLayout, terminalLayouts);
          groupPromises.push(promise);
          if (tabLayout.isActive) {
            activeGroup = promise;
          }
          const activeInstance = this.instances.find((t) => t.shellLaunchConfig.attachPersistentProcess?.id === tabLayout.activePersistentProcessId);
          if (activeInstance) {
            this.setActiveInstance(activeInstance);
          }
        }
      }
      if (layoutInfo.tabs.length) {
        activeGroup?.then((group2) => this.kb.activeGroup = group2);
      }
    }
    return Promise.all(groupPromises).then((result) => result.filter((e) => !!e));
  }
  async Bb(tabLayout, terminalLayouts) {
    let lastInstance;
    for (const terminalLayout of terminalLayouts) {
      const attachPersistentProcess = terminalLayout.terminal;
      if (this.$.startupKind !== 3 && attachPersistentProcess.type === "Task") {
        continue;
      }
      $S(`code/terminal/willRecreateTerminal/${attachPersistentProcess.id}-${attachPersistentProcess.pid}`);
      lastInstance = this.createTerminal({
        config: { attachPersistentProcess },
        location: lastInstance ? { parentTerminal: lastInstance } : TerminalLocation2.Panel
      });
      lastInstance.then(() => $S(`code/terminal/didRecreateTerminal/${attachPersistentProcess.id}-${attachPersistentProcess.pid}`));
    }
    const group2 = lastInstance?.then((instance2) => {
      const g = this.kb.getGroupForInstance(instance2);
      g?.resizePanes(tabLayout.terminals.map((terminal2) => terminal2.relativeSize));
      return g;
    });
    return group2;
  }
  Cb() {
    this.B(this.onDidChangeActiveGroup(() => this.Jb()));
    this.B(this.onDidChangeActiveInstance(() => this.Jb()));
    this.B(this.onDidChangeInstances(() => this.Jb()));
    this.B(this.onAnyInstanceProcessIdReady(() => this.Jb()));
    this.B(this.onAnyInstanceTitleChange((instance2) => this.Kb(instance2)));
    this.B(this.onAnyInstanceIconChange((e) => this.Lb(e.instance, e.userInitiated)));
  }
  Db() {
    const terminalIsOpenContext = TerminalContextKeys.isOpen.bindTo(this.Z);
    const updateTerminalContextKeys = () => {
      terminalIsOpenContext.set(this.instances.length > 0);
      this.w.set(this.instances.length);
    };
    this.B(this.onDidChangeInstances(() => updateTerminalContextKeys()));
  }
  async getActiveOrCreateInstance(options3) {
    const activeInstance = this.activeInstance;
    if (!activeInstance) {
      return this.createTerminal();
    }
    if (!options3?.acceptsInput || activeInstance.xterm?.isStdinDisabled !== true) {
      return activeInstance;
    }
    const instance2 = await this.createTerminal();
    this.setActiveInstance(instance2);
    await this.revealActiveTerminal();
    return instance2;
  }
  async revealTerminal(source, preserveFocus) {
    if (source.target === TerminalLocation2.Editor) {
      await this.jb.revealActiveEditor(preserveFocus);
    } else {
      await this.kb.showPanel();
    }
  }
  async revealActiveTerminal(preserveFocus) {
    const instance2 = this.activeInstance;
    if (!instance2) {
      return;
    }
    await this.revealTerminal(instance2, preserveFocus);
  }
  setEditable(instance2, data) {
    if (!data) {
      this.C = void 0;
    } else {
      this.C = { instance: instance2, data };
    }
    const pane = this.eb.getActiveViewWithId($7X);
    const isEditing = this.isEditable(instance2);
    pane?.terminalTabbedView?.setEditable(isEditing);
  }
  isEditable(instance2) {
    return !!this.C && (this.C.instance === instance2 || !instance2);
  }
  getEditableData(instance2) {
    return this.C && this.C.instance === instance2 ? this.C.data : void 0;
  }
  requestStartExtensionTerminal(proxy, cols, rows) {
    return new Promise((callback) => {
      this.Q.fire({ proxy, cols, rows, callback });
    });
  }
  Eb(reason) {
    if ($r) {
      this.h = true;
      return false;
    }
    return this.Fb(reason);
  }
  async Fb(reason) {
    if (this.instances.length === 0) {
      return false;
    }
    try {
      this.z = await this.y?.getWindowCount();
      const shouldReviveProcesses = this.Gb(reason);
      if (shouldReviveProcesses) {
        await Promise.race([
          this.s?.persistTerminalState(),
          $Wh(2e3)
        ]);
      }
      const shouldPersistProcesses = this.ib.config.enablePersistentSessions && reason === 3;
      if (!shouldPersistProcesses) {
        const hasDirtyInstances = this.ib.config.confirmOnExit === "always" && this.instances.length > 0 || this.ib.config.confirmOnExit === "hasChildProcesses" && this.instances.some((e) => e.hasChildProcesses);
        if (hasDirtyInstances) {
          return this.Hb(reason);
        }
      }
    } catch (err) {
      this.ab.warn("Exception occurred during terminal shutdown", err);
    }
    this.h = true;
    return false;
  }
  setNativeDelegate(nativeDelegate) {
    this.y = nativeDelegate;
  }
  Gb(reason) {
    if (!this.ib.config.enablePersistentSessions) {
      return false;
    }
    switch (this.ib.config.persistentSessionReviveProcess) {
      case "onExit": {
        if (reason === 1 && (this.z === 1 && !$m)) {
          return true;
        }
        return reason === 4 || reason === 2;
      }
      case "onExitAndWindowClose":
        return reason !== 3;
      default:
        return false;
    }
  }
  async Hb(reason) {
    const veto = await this.Pb();
    if (!veto) {
      this.h = true;
    }
    return veto;
  }
  Ib(e) {
    const shouldPersistTerminals = this.ib.config.enablePersistentSessions && e.reason === 3;
    for (const instance2 of [...this.kb.instances, ...this.j]) {
      if (shouldPersistTerminals && instance2.shouldPersist) {
        instance2.detachProcessAndDispose(TerminalExitReason2.Shutdown);
      } else {
        instance2.dispose(TerminalExitReason2.Shutdown);
      }
    }
    if (!shouldPersistTerminals && !this.Gb(e.reason)) {
      this.s?.setTerminalLayoutInfo(void 0);
    }
  }
  Jb() {
    if (this.h) {
      return;
    }
    if (!this.ib.config.enablePersistentSessions) {
      return;
    }
    const tabs = this.kb.groups.map((g) => g.getLayoutInfo(g === this.kb.activeGroup));
    const state = { tabs };
    this.s?.setTerminalLayoutInfo(state);
  }
  Kb(instance2) {
    if (!this.ib.config.enablePersistentSessions || !instance2 || !instance2.persistentProcessId || !instance2.title || instance2.isDisposed) {
      return;
    }
    if (instance2.staticTitle) {
      this.s?.updateTitle(instance2.persistentProcessId, instance2.staticTitle, TitleEventSource.Api);
    } else {
      this.s?.updateTitle(instance2.persistentProcessId, instance2.title, instance2.titleSource);
    }
  }
  Lb(instance2, userInitiated) {
    if (!this.ib.config.enablePersistentSessions || !instance2 || !instance2.persistentProcessId || !instance2.icon || instance2.isDisposed) {
      return;
    }
    this.s?.updateIcon(instance2.persistentProcessId, userInitiated, instance2.icon, instance2.color);
  }
  refreshActiveGroup() {
    this.Y.fire(this.kb.activeGroup);
  }
  getInstanceFromId(terminalId) {
    let bgIndex = -1;
    this.j.forEach((terminalInstance, i2) => {
      if (terminalInstance.instanceId === terminalId) {
        bgIndex = i2;
      }
    });
    if (bgIndex !== -1) {
      return this.j[bgIndex];
    }
    try {
      return this.instances[this.Ob(terminalId)];
    } catch {
      return void 0;
    }
  }
  getInstanceFromIndex(terminalIndex) {
    return this.instances[terminalIndex];
  }
  getInstanceFromResource(resource) {
    return $afc(this.instances, resource);
  }
  isAttachedToTerminal(remoteTerm) {
    return this.instances.some((term) => term.processId === remoteTerm.pid);
  }
  moveToEditor(source, group2) {
    if (source.target === TerminalLocation2.Editor) {
      return;
    }
    const sourceGroup = this.kb.getGroupForInstance(source);
    if (!sourceGroup) {
      return;
    }
    sourceGroup.removeInstance(source);
    this.jb.openEditor(source, group2 ? { viewColumn: group2 } : void 0);
  }
  moveIntoNewEditor(source) {
    this.moveToEditor(source, $pJ);
  }
  async moveToTerminalView(source, target, side) {
    if (URI.isUri(source)) {
      source = this.getInstanceFromResource(source);
    }
    if (!source) {
      return;
    }
    this.jb.detachInstance(source);
    if (source.target !== TerminalLocation2.Editor) {
      await this.kb.showPanel(true);
      return;
    }
    source.target = TerminalLocation2.Panel;
    let group2;
    if (target) {
      group2 = this.kb.getGroupForInstance(target);
    }
    if (!group2) {
      group2 = this.kb.createGroup();
    }
    group2.addInstance(source);
    this.setActiveInstance(source);
    await this.kb.showPanel(true);
    if (target && side) {
      const index = group2.terminalInstances.indexOf(target) + (side === "after" ? 1 : 0);
      group2.moveInstance(source, index, side);
    }
    this.W.fire();
    this.Y.fire(this.kb.activeGroup);
  }
  Mb(instance2) {
    const instanceDisposables = [
      instance2.onDimensionsChanged(() => {
        this.N.fire(instance2);
        if (this.ib.config.enablePersistentSessions && this.isProcessSupportRegistered) {
          this.Jb();
        }
      }),
      instance2.onDidFocus(this.U.fire, this.U),
      instance2.onRequestAddInstanceToGroup(async (e) => await this.Nb(instance2, e))
    ];
    instance2.onDisposed(() => $Xc(instanceDisposables));
  }
  async Nb(instance2, e) {
    const terminalIdentifier = $0ec(e.uri);
    if (terminalIdentifier.instanceId === void 0) {
      return;
    }
    let sourceInstance = this.getInstanceFromResource(e.uri);
    if (!sourceInstance) {
      const attachPersistentProcess = await this.s?.requestDetachInstance(terminalIdentifier.workspaceId, terminalIdentifier.instanceId);
      if (attachPersistentProcess) {
        sourceInstance = await this.createTerminal({ config: { attachPersistentProcess }, resource: e.uri });
        this.kb.moveInstance(sourceInstance, instance2, e.side);
        return;
      }
    }
    sourceInstance = this.kb.getInstanceFromResource(e.uri);
    if (sourceInstance) {
      this.kb.moveInstance(sourceInstance, instance2, e.side);
      return;
    }
    sourceInstance = this.jb.getInstanceFromResource(e.uri);
    if (sourceInstance) {
      this.moveToTerminalView(sourceInstance, instance2, e.side);
      return;
    }
    return;
  }
  registerProcessSupport(isSupported) {
    if (!isSupported) {
      return;
    }
    this.n.set(isSupported);
    this.O.fire();
  }
  // TODO: Remove this, it should live in group/editor servioce
  Ob(terminalId) {
    let terminalIndex = -1;
    this.instances.forEach((terminalInstance, i2) => {
      if (terminalInstance.instanceId === terminalId) {
        terminalIndex = i2;
      }
    });
    if (terminalIndex === -1) {
      throw new Error(`Terminal with ID ${terminalId} does not exist (has it already been disposed?)`);
    }
    return terminalIndex;
  }
  async Pb(singleTerminal) {
    let message;
    if (this.instances.length === 1 || singleTerminal) {
      message = localize(10531, null);
    } else {
      message = localize(10532, null, this.instances.length);
    }
    const { confirmed } = await this.bb.confirm({
      type: "warning",
      message,
      primaryButton: localize(10533, null)
    });
    return !confirmed;
  }
  getDefaultInstanceHost() {
    if (this.defaultLocation === TerminalLocation2.Editor) {
      return this.jb;
    }
    return this.kb;
  }
  async getInstanceHost(location3) {
    if (location3) {
      if (location3 === TerminalLocation2.Editor) {
        return this.jb;
      } else if (typeof location3 === "object") {
        if ("viewColumn" in location3) {
          return this.jb;
        } else if ("parentTerminal" in location3) {
          return (await location3.parentTerminal).target === TerminalLocation2.Editor ? this.jb : this.kb;
        }
      } else {
        return this.kb;
      }
    }
    return this;
  }
  async createTerminal(options3) {
    if (this.nb.availableProfiles.length === 0) {
      const isPtyTerminal = options3?.config && "customPtyImplementation" in options3.config;
      const isLocalInRemoteTerminal = this.db.getConnection() && URI.isUri(options3?.cwd) && options3?.cwd.scheme === Schemas.vscodeFileResource;
      if (!isPtyTerminal && !isLocalInRemoteTerminal) {
        if (this.D === 0) {
          $S(`code/terminal/willGetProfiles`);
        }
        await this.nb.profilesReady;
        if (this.D === 0) {
          $S(`code/terminal/didGetProfiles`);
        }
      }
    }
    const config = options3?.config || this.nb.getDefaultProfile();
    const shellLaunchConfig = config && "extensionIdentifier" in config ? {} : this.lb.convertProfileToShellLaunchConfig(config || {});
    const contributedProfile = options3?.skipContributedProfileCheck ? void 0 : await this.Qb(shellLaunchConfig, options3);
    const splitActiveTerminal = typeof options3?.location === "object" && "splitActiveTerminal" in options3.location ? options3.location.splitActiveTerminal : typeof options3?.location === "object" ? "parentTerminal" in options3.location : false;
    await this.Rb(shellLaunchConfig, splitActiveTerminal, options3);
    if (contributedProfile) {
      const resolvedLocation = await this.resolveLocation(options3?.location);
      let location4;
      if (splitActiveTerminal) {
        location4 = resolvedLocation === TerminalLocation2.Editor ? { viewColumn: $oJ } : { splitActiveTerminal: true };
      } else {
        location4 = typeof options3?.location === "object" && "viewColumn" in options3.location ? options3.location : resolvedLocation;
      }
      await this.createContributedTerminalProfile(contributedProfile.extensionIdentifier, contributedProfile.id, {
        icon: contributedProfile.icon,
        color: contributedProfile.color,
        location: location4,
        cwd: shellLaunchConfig.cwd
      });
      const instanceHost = resolvedLocation === TerminalLocation2.Editor ? this.jb : this.kb;
      const instance2 = instanceHost.instances[instanceHost.instances.length - 1];
      await instance2?.focusWhenReady();
      this.u.set(true);
      return instance2;
    }
    if (!shellLaunchConfig.customPtyImplementation && !this.isProcessSupportRegistered) {
      throw new Error("Could not create terminal when process support is not registered");
    }
    if (shellLaunchConfig.hideFromUser) {
      const instance2 = this.lb.createInstance(shellLaunchConfig, TerminalLocation2.Panel);
      this.j.push(instance2);
      this.m.set(instance2.instanceId, [
        instance2.onDisposed(this.R.fire, this.R)
      ]);
      this.u.set(true);
      return instance2;
    }
    this.Xb(shellLaunchConfig);
    const location3 = await this.resolveLocation(options3?.location) || this.defaultLocation;
    const parent = await this.Vb(options3?.location);
    this.u.set(true);
    if (parent) {
      return this.Sb(shellLaunchConfig, location3, parent);
    }
    return this.Ub(shellLaunchConfig, location3, options3);
  }
  async Qb(shellLaunchConfig, options3) {
    if (options3?.config && "extensionIdentifier" in options3.config) {
      return options3.config;
    }
    return this.nb.getContributedDefaultProfile(shellLaunchConfig);
  }
  async createDetachedTerminal(options3) {
    const ctor = await $wfc.getXtermConstructor(this.sb, this.Z);
    const xterm = this.cb.createInstance($2Pb, ctor, {
      cols: options3.cols,
      rows: options3.rows,
      xtermColorProvider: options3.colorProvider,
      capabilities: options3.capabilities || new $zPb()
    });
    if (options3.readonly) {
      xterm.raw.attachCustomKeyEventHandler(() => false);
    }
    const instance2 = new $Z0b(xterm, options3, this.cb);
    this.b.add(instance2);
    const l = xterm.onDidDispose(() => {
      this.b.delete(instance2);
      l.dispose();
    });
    return instance2;
  }
  async Rb(shellLaunchConfig, splitActiveTerminal, options3) {
    const cwd2 = shellLaunchConfig.cwd;
    if (!cwd2) {
      if (options3?.cwd) {
        shellLaunchConfig.cwd = options3.cwd;
      } else if (splitActiveTerminal && options3?.location) {
        let parent = this.activeInstance;
        if (typeof options3.location === "object" && "parentTerminal" in options3.location) {
          parent = await options3.location.parentTerminal;
        }
        if (!parent) {
          throw new Error("Cannot split without an active instance");
        }
        shellLaunchConfig.cwd = await $Rec(parent, this.qb.getWorkspace().folders, this.rb, this.gb);
      }
    }
  }
  Sb(shellLaunchConfig, location3, parent) {
    let instance2;
    if (typeof shellLaunchConfig.cwd !== "object" && typeof parent.shellLaunchConfig.cwd === "object") {
      shellLaunchConfig.cwd = URI.from({
        scheme: parent.shellLaunchConfig.cwd.scheme,
        authority: parent.shellLaunchConfig.cwd.authority,
        path: shellLaunchConfig.cwd || parent.shellLaunchConfig.cwd.path
      });
    }
    if (location3 === TerminalLocation2.Editor || parent.target === TerminalLocation2.Editor) {
      instance2 = this.jb.splitInstance(parent, shellLaunchConfig);
    } else {
      const group2 = this.kb.getGroupForInstance(parent);
      if (!group2) {
        throw new Error(`Cannot split a terminal without a group (instanceId: ${parent.instanceId}, title: ${parent.title})`);
      }
      shellLaunchConfig.parentTerminalId = parent.instanceId;
      instance2 = group2.split(shellLaunchConfig);
    }
    this.Tb(instance2);
    return instance2;
  }
  Tb(instance2) {
    if (!instance2.reconnectionProperties?.ownerId) {
      return;
    }
    const reconnectedTerminals = this.I.get(instance2.reconnectionProperties.ownerId);
    if (reconnectedTerminals) {
      reconnectedTerminals.push(instance2);
    } else {
      this.I.set(instance2.reconnectionProperties.ownerId, [instance2]);
    }
  }
  Ub(shellLaunchConfig, location3, options3) {
    let instance2;
    const editorOptions2 = this.Wb(options3?.location);
    if (location3 === TerminalLocation2.Editor) {
      instance2 = this.lb.createInstance(shellLaunchConfig, TerminalLocation2.Editor);
      this.jb.openEditor(instance2, editorOptions2);
    } else {
      const group2 = this.kb.createGroup(shellLaunchConfig);
      instance2 = group2.terminalInstances[0];
    }
    this.Tb(instance2);
    return instance2;
  }
  async resolveLocation(location3) {
    if (location3 && typeof location3 === "object") {
      if ("parentTerminal" in location3) {
        const parentTerminal = await location3.parentTerminal;
        return !parentTerminal.target ? TerminalLocation2.Panel : parentTerminal.target;
      } else if ("viewColumn" in location3) {
        return TerminalLocation2.Editor;
      } else if ("splitActiveTerminal" in location3) {
        return !this.J?.target ? TerminalLocation2.Panel : this.J?.target;
      }
    }
    return location3;
  }
  async Vb(location3) {
    if (location3 && typeof location3 === "object" && "parentTerminal" in location3) {
      return location3.parentTerminal;
    } else if (location3 && typeof location3 === "object" && "splitActiveTerminal" in location3) {
      return this.activeInstance;
    }
    return void 0;
  }
  Wb(location3) {
    if (location3 && typeof location3 === "object" && "viewColumn" in location3) {
      location3.viewColumn = $zS(this.mb, this.fb, location3.viewColumn);
      return location3;
    }
    return void 0;
  }
  Xb(shellLaunchConfig) {
    if (typeof shellLaunchConfig.cwd !== "string" && shellLaunchConfig.cwd?.scheme === Schemas.file) {
      if ($lpb.getValue(this.Z)) {
        shellLaunchConfig.initialText = $W0b(localize(10534, null, "\x1B[3m", "\x1B[23m"), { excludeLeadingNewLine: true, loudFormatting: true });
        shellLaunchConfig.type = "Local";
      } else if (this.db.getConnection()) {
        shellLaunchConfig.initialText = $W0b(localize(10535, null, "\x1B[3m", "\x1B[23m"), { excludeLeadingNewLine: true, loudFormatting: true });
        shellLaunchConfig.type = "Local";
      }
    }
  }
  Yb(instance2) {
    this.j.splice(this.j.indexOf(instance2), 1);
    const disposables = this.m.get(instance2.instanceId);
    if (disposables) {
      $Xc(disposables);
    }
    this.m.delete(instance2.instanceId);
    instance2.shellLaunchConfig.hideFromUser = false;
    this.kb.createGroup(instance2);
    if (this.instances.length === 1) {
      this.kb.setActiveInstanceByIndex(0);
    }
    this.W.fire();
  }
  async setContainers(panelContainer, terminalContainer) {
    this.ib.setPanelContainer(panelContainer);
    this.kb.setContainer(terminalContainer);
  }
  getEditingTerminal() {
    return this.L;
  }
  setEditingTerminal(instance2) {
    this.L = instance2;
  }
  createOnInstanceEvent(getEvent) {
    return new $Ge(this.instances, this.onDidCreateInstance, this.onDidDisposeInstance, getEvent);
  }
  createOnInstanceCapabilityEvent(capabilityId, getEvent) {
    return $Ffc(this.instances, this.onDidCreateInstance, this.onDidDisposeInstance, capabilityId, getEvent);
  }
};
__decorate([
  $0t
], $Gfc.prototype, "onAnyInstanceData", null);
__decorate([
  $0t
], $Gfc.prototype, "onAnyInstanceDataInput", null);
__decorate([
  $0t
], $Gfc.prototype, "onAnyInstanceIconChange", null);
__decorate([
  $0t
], $Gfc.prototype, "onAnyInstanceMaximumDimensionsChange", null);
__decorate([
  $0t
], $Gfc.prototype, "onAnyInstancePrimaryStatusChange", null);
__decorate([
  $0t
], $Gfc.prototype, "onAnyInstanceProcessIdReady", null);
__decorate([
  $0t
], $Gfc.prototype, "onAnyInstanceSelectionChange", null);
__decorate([
  $0t
], $Gfc.prototype, "onAnyInstanceTitleChange", null);
__decorate([
  $$t(500)
], $Gfc.prototype, "Jb", null);
__decorate([
  $$t(500)
], $Gfc.prototype, "Kb", null);
__decorate([
  $$t(500)
], $Gfc.prototype, "Lb", null);
$Gfc = __decorate([
  __param(0, $on),
  __param(1, $KL),
  __param(2, $8x),
  __param(3, $Yv),
  __param(4, $Pk),
  __param(5, $RL),
  __param(6, $uob),
  __param(7, $kl),
  __param(8, $5Pb),
  __param(9, $US),
  __param(10, $5Pb),
  __param(11, $6Pb),
  __param(12, $7Pb),
  __param(13, $8Pb),
  __param(14, $iJ),
  __param(15, $hY),
  __param(16, $wN),
  __param(17, $PJ),
  __param(18, $Zk),
  __param(19, $sn),
  __param(20, $Ty),
  __param(21, $iQb)
], $Gfc);
var TerminalEditorStyle = class TerminalEditorStyle2 extends $ns {
  constructor(container2, b, c, f, j) {
    super(c);
    this.b = b;
    this.c = c;
    this.f = f;
    this.j = j;
    this.m();
    this.a = $VZ(container2);
    this.B($1c(() => this.a.remove()));
    this.updateStyles();
  }
  m() {
    this.B(this.b.onAnyInstanceIconChange(() => this.updateStyles()));
    this.B(this.b.onDidCreateInstance(() => this.updateStyles()));
    this.B(this.j.onDidActiveEditorChange(() => {
      if (this.j.activeEditor instanceof $fQb) {
        this.updateStyles();
      }
    }));
    this.B(this.j.onDidCloseEditor(() => {
      if (this.j.activeEditor instanceof $fQb) {
        this.updateStyles();
      }
    }));
    this.B(this.f.onDidChangeAvailableProfiles(() => this.updateStyles()));
  }
  updateStyles() {
    super.updateStyles();
    const colorTheme = this.c.getColorTheme();
    let css = "";
    const productIconTheme = this.c.getProductIconTheme();
    for (const instance2 of this.b.instances) {
      const icon2 = instance2.icon;
      if (!icon2) {
        continue;
      }
      let uri = void 0;
      if (icon2 instanceof URI) {
        uri = icon2;
      } else if (icon2 instanceof Object && "light" in icon2 && "dark" in icon2) {
        uri = colorTheme.type === ColorScheme.LIGHT ? icon2.light : icon2.dark;
      }
      const iconClasses = $dQb(instance2, colorTheme.type);
      if (uri instanceof URI && iconClasses && iconClasses.length > 1) {
        css += $7Z`.monaco-workbench .terminal-tab.${$6Z(iconClasses[0])}::before
					{content: ''; background-image: ${$5Z(uri)};}`;
      }
      if (ThemeIcon.isThemeIcon(icon2)) {
        const iconRegistry4 = $0r();
        const iconContribution = iconRegistry4.getIcon(icon2.id);
        if (iconContribution) {
          const def2 = productIconTheme.getIcon(iconContribution);
          if (def2) {
            css += $7Z`.monaco-workbench .terminal-tab.codicon-${$6Z(icon2.id)}::before
							{content: ${$4Z(def2.fontCharacter)} !important; font-family: ${$4Z(def2.font?.id ?? "codicon")} !important;}`;
          }
        }
      }
    }
    const iconForegroundColor = colorTheme.getColor($io);
    if (iconForegroundColor) {
      css += $7Z`.monaco-workbench .show-file-icons .file-icon.terminal-tab::before { color: ${iconForegroundColor}; }`;
    }
    css += $cQb(colorTheme, true);
    this.a.textContent = css;
  }
};
TerminalEditorStyle = __decorate([
  __param(1, $4Pb),
  __param(2, $gs),
  __param(3, $hY),
  __param(4, $mJ)
], TerminalEditorStyle);

// out-build/vs/workbench/contrib/terminal/browser/terminalTooltip.js
function $dfc(instance2) {
  let statusString = "";
  const statuses = instance2.statusList.statuses;
  const actions = [];
  for (const status of statuses) {
    statusString += `

---

${status.icon ? `$(${status.icon?.id}) ` : ""}${status.tooltip || status.id}`;
    if (status.hoverActions) {
      actions.push(...status.hoverActions);
    }
  }
  const shellProcessString = $ffc(instance2, true);
  const shellIntegrationString = $efc(instance2, true);
  const content = new $bm(instance2.title + shellProcessString + shellIntegrationString + statusString, { supportThemeIcons: true });
  return { content, actions };
}
function $efc(instance2, markdown) {
  const shellIntegrationCapabilities = [];
  if (instance2.capabilities.has(
    2
    /* TerminalCapability.CommandDetection */
  )) {
    shellIntegrationCapabilities.push(
      2
      /* TerminalCapability.CommandDetection */
    );
  }
  if (instance2.capabilities.has(
    0
    /* TerminalCapability.CwdDetection */
  )) {
    shellIntegrationCapabilities.push(
      0
      /* TerminalCapability.CwdDetection */
    );
  }
  let shellIntegrationString = "";
  if (shellIntegrationCapabilities.length > 0) {
    shellIntegrationString += `${markdown ? "\n\n---\n\n" : "\n\n"}${localize(10544, null)}`;
  } else {
    if (instance2.shellLaunchConfig.ignoreShellIntegration) {
      shellIntegrationString += `${markdown ? "\n\n---\n\n" : "\n\n"}${localize(10545, null)}`;
    } else {
      if (instance2.usedShellIntegrationInjection) {
        shellIntegrationString += `${markdown ? "\n\n---\n\n" : "\n\n"}${localize(10546, null)}`;
      }
    }
  }
  return shellIntegrationString;
}
function $ffc(instance2, markdown) {
  const lines = [];
  if (instance2.processId && instance2.processId > 0) {
    lines.push(localize(10547, null, "PID", instance2.processId) + "\n");
  }
  if (instance2.shellLaunchConfig.executable) {
    let commandLine = instance2.shellLaunchConfig.executable;
    const args2 = $5b(instance2.injectedArgs || instance2.shellLaunchConfig.args || []).map((x) => `'${x}'`).join(" ");
    if (args2) {
      commandLine += ` ${args2}`;
    }
    lines.push(localize(10548, null, commandLine));
  }
  return lines.length ? `${markdown ? "\n\n---\n\n" : "\n\n"}${lines.join("\n")}` : "";
}

// out-build/vs/workbench/contrib/terminal/browser/terminalTabsList.js
var $144 = $;
var TerminalTabsListSizes;
(function(TerminalTabsListSizes2) {
  TerminalTabsListSizes2[TerminalTabsListSizes2["TabHeight"] = 22] = "TabHeight";
  TerminalTabsListSizes2[TerminalTabsListSizes2["NarrowViewWidth"] = 46] = "NarrowViewWidth";
  TerminalTabsListSizes2[TerminalTabsListSizes2["WideViewMinimumWidth"] = 80] = "WideViewMinimumWidth";
  TerminalTabsListSizes2[TerminalTabsListSizes2["DefaultWidth"] = 120] = "DefaultWidth";
  TerminalTabsListSizes2[TerminalTabsListSizes2["MidpointViewWidth"] = 63] = "MidpointViewWidth";
  TerminalTabsListSizes2[TerminalTabsListSizes2["ActionbarMinimumWidth"] = 105] = "ActionbarMinimumWidth";
  TerminalTabsListSizes2[TerminalTabsListSizes2["MaximumWidth"] = 500] = "MaximumWidth";
})(TerminalTabsListSizes || (TerminalTabsListSizes = {}));
var $gfc = class $gfc2 extends $Web {
  constructor(container2, contextKeyService, listService, themeService, V, W, X, instantiationService, decorationsService, Y, lifecycleService, Z) {
    super("TerminalTabsList", container2, {
      getHeight: () => 22,
      getTemplateId: () => "terminal.tabs"
    }, [instantiationService.createInstance(TerminalTabsRenderer, container2, instantiationService.createInstance($lsb, $ksb), () => this.getSelectedElements())], {
      horizontalScrolling: false,
      supportDynamicHeights: false,
      selectionNavigation: true,
      identityProvider: {
        getId: (e) => e?.instanceId
      },
      accessibilityProvider: instantiationService.createInstance(TerminalTabsAccessibilityProvider),
      smoothScrolling: V.getValue("workbench.list.smoothScrolling"),
      multipleSelectionSupport: true,
      paddingBottom: 22,
      dnd: instantiationService.createInstance(TerminalTabsDragAndDrop),
      openOnSingleClick: true
    }, contextKeyService, listService, V, instantiationService);
    this.V = V;
    this.W = W;
    this.X = X;
    this.Y = Y;
    this.Z = Z;
    const instanceDisposables = [
      this.X.onDidChangeInstances(() => this.refresh()),
      this.X.onDidChangeGroups(() => this.refresh()),
      this.X.onDidShow(() => this.refresh()),
      this.X.onDidChangeInstanceCapability(() => this.refresh()),
      this.W.onAnyInstanceTitleChange(() => this.refresh()),
      this.W.onAnyInstanceIconChange(() => this.refresh()),
      this.W.onAnyInstancePrimaryStatusChange(() => this.refresh()),
      this.W.onDidChangeConnectionState(() => this.refresh()),
      this.Y.onDidColorThemeChange(() => this.refresh()),
      this.X.onDidChangeActiveInstance((e) => {
        if (e) {
          const i2 = this.X.instances.indexOf(e);
          this.setSelection([i2]);
          this.reveal(i2);
        }
        this.refresh();
      })
    ];
    this.z.add(lifecycleService.onWillShutdown((e) => {
      $Xc(instanceDisposables);
      instanceDisposables.length = 0;
    }));
    this.z.add($1c(() => {
      $Xc(instanceDisposables);
      instanceDisposables.length = 0;
    }));
    this.z.add(this.onMouseDblClick(async (e) => {
      const focus = this.getFocus();
      if (focus.length === 0) {
        const instance2 = await this.W.createTerminal({ location: TerminalLocation2.Panel });
        this.X.setActiveInstance(instance2);
        await instance2.focusWhenReady();
      }
      if (this.W.getEditingTerminal()?.instanceId === e.element?.instanceId) {
        return;
      }
      if (this.ab() === "doubleClick" && this.getFocus().length === 1) {
        e.element?.focus(true);
      }
    }));
    this.z.add(this.onMouseClick(async (e) => {
      if (this.W.getEditingTerminal()?.instanceId === e.element?.instanceId) {
        return;
      }
      if (e.browserEvent.altKey && e.element) {
        await this.W.createTerminal({ location: { parentTerminal: e.element } });
      } else if (this.ab() === "singleClick") {
        if (this.getSelection().length <= 1) {
          e.element?.focus(true);
        }
      }
    }));
    this.z.add(this.onContextMenu((e) => {
      if (!e.element) {
        this.setSelection([]);
        return;
      }
      const selection = this.getSelectedElements();
      if (!selection || !selection.find((s) => e.element === s)) {
        this.setFocus(e.index !== void 0 ? [e.index] : []);
      }
    }));
    this.S = TerminalContextKeys.tabsSingularSelection.bindTo(contextKeyService);
    this.U = TerminalContextKeys.splitTerminal.bindTo(contextKeyService);
    this.z.add(this.onDidChangeSelection((e) => this.bb()));
    this.z.add(this.onDidChangeFocus(() => this.bb()));
    this.z.add(this.onDidOpen(async (e) => {
      const instance2 = e.element;
      if (!instance2) {
        return;
      }
      this.X.setActiveInstance(instance2);
      if (!e.editorOptions.preserveFocus) {
        await instance2.focusWhenReady();
      }
    }));
    if (!this.c) {
      this.c = this.z.add(instantiationService.createInstance(TabDecorationsProvider));
      this.z.add(decorationsService.registerDecorationsProvider(this.c));
    }
    this.refresh();
  }
  ab() {
    return this.V.getValue(
      "terminal.integrated.tabs.focusMode"
      /* TerminalSettingId.TabsFocusMode */
    );
  }
  refresh(cancelEditing = true) {
    if (cancelEditing && this.W.isEditable(void 0)) {
      this.domFocus();
    }
    this.splice(0, this.length, this.X.instances.slice());
  }
  focusHover() {
    const instance2 = this.getSelectedElements()[0];
    if (!instance2) {
      return;
    }
    this.Z.showHover({
      ...$dfc(instance2),
      target: this.getHTMLElement(),
      trapFocus: true
    }, true);
  }
  bb() {
    this.S.set(this.getSelectedElements().length === 1);
    const instance2 = this.getFocusedElements();
    this.U.set(instance2.length > 0 && this.X.instanceIsSplit(instance2[0]));
  }
};
$gfc = __decorate([
  __param(1, $on),
  __param(2, $Deb),
  __param(3, $gs),
  __param(4, $kl),
  __param(5, $4Pb),
  __param(6, $7Pb),
  __param(7, $Pk),
  __param(8, $jsb),
  __param(9, $gs),
  __param(10, $KL),
  __param(11, $5$)
], $gfc);
var TerminalTabsRenderer = class TerminalTabsRenderer2 {
  constructor(a, b, c, d, f, g, h3, j, k, l, m, n) {
    this.a = a;
    this.b = b;
    this.c = c;
    this.d = d;
    this.f = f;
    this.g = g;
    this.h = h3;
    this.j = j;
    this.k = k;
    this.l = l;
    this.m = m;
    this.n = n;
    this.templateId = "terminal.tabs";
  }
  renderTemplate(container2) {
    const element = $bk(container2, $144(".terminal-tabs-entry"));
    const context = {};
    const label3 = this.b.create(element, {
      supportHighlights: true,
      supportDescriptionHighlights: true,
      supportIcons: true,
      hoverDelegate: {
        delay: 0,
        showHover: (options3) => {
          return this.j.showDelayedHover({
            ...options3,
            actions: context.hoverActions,
            target: element,
            appearance: {
              showPointer: true
            },
            position: {
              hoverPosition: this.f.config.tabs.location === "left" ? 1 : 0
              /* HoverPosition.LEFT */
            }
          }, { groupId: "terminal-tabs-list" });
        }
      }
    });
    const actionsContainer = $bk(label3.element, $144(".actions"));
    const actionBar = new $LZ(actionsContainer, {
      actionRunner: new $Nec(),
      actionViewItemProvider: (action, options3) => action instanceof $fJ ? this.d.createInstance($T$, action, { hoverDelegate: options3.hoverDelegate }) : void 0
    });
    return {
      element,
      label: label3,
      actionBar,
      context,
      elementDisposables: new $2c()
    };
  }
  shouldHideText() {
    return this.a ? this.a.clientWidth < 63 : false;
  }
  shouldHideActionBar() {
    return this.a ? this.a.clientWidth <= 105 : false;
  }
  renderElement(instance2, index, template) {
    const hasText = !this.shouldHideText();
    const group2 = this.h.getGroupForInstance(instance2);
    if (!group2) {
      throw new Error(`Could not find group for instance "${instance2.instanceId}"`);
    }
    template.element.classList.toggle("has-text", hasText);
    template.element.classList.toggle("is-active", this.h.activeInstance === instance2);
    let prefix = "";
    if (group2.terminalInstances.length > 1) {
      const terminalIndex = group2.terminalInstances.indexOf(instance2);
      if (terminalIndex === 0) {
        prefix = `\u250C `;
      } else if (terminalIndex === group2.terminalInstances.length - 1) {
        prefix = `\u2514 `;
      } else {
        prefix = `\u251C `;
      }
    }
    const hoverInfo = $dfc(instance2);
    template.context.hoverActions = hoverInfo.actions;
    const iconId = this.d.invokeFunction($eQb, instance2);
    const hasActionbar = !this.shouldHideActionBar();
    let label3 = "";
    if (!hasText) {
      const primaryStatus = instance2.statusList.primary;
      if (primaryStatus && primaryStatus.severity > severity_default.Ignore) {
        label3 = `${prefix}$(${primaryStatus.icon?.id || iconId})`;
      } else {
        label3 = `${prefix}$(${iconId})`;
      }
    } else {
      this.fillActionBar(instance2, template);
      label3 = prefix;
      if (instance2.icon) {
        label3 += `$(${iconId}) ${instance2.title}`;
      }
    }
    if (!hasActionbar) {
      template.actionBar.clear();
    }
    template.elementDisposables.add($_i(template.element, $7j.AUXCLICK, (e) => {
      e.stopImmediatePropagation();
      if (e.button === 1) {
        this.g.safeDisposeTerminal(instance2);
      }
    }));
    const extraClasses = [];
    const colorClass = $_Pb(instance2);
    if (colorClass) {
      extraClasses.push(colorClass);
    }
    const uriClasses = $dQb(instance2, this.m.getColorTheme().type);
    if (uriClasses) {
      extraClasses.push(...uriClasses);
    }
    template.label.setResource({
      resource: instance2.resource,
      name: label3,
      description: hasText ? instance2.description : void 0
    }, {
      fileDecorations: {
        colors: true,
        badges: hasText
      },
      title: {
        markdown: hoverInfo.content,
        markdownNotSupportedFallback: void 0
      },
      extraClasses
    });
    const editableData = this.g.getEditableData(instance2);
    template.label.element.classList.toggle("editable-tab", !!editableData);
    if (editableData) {
      template.elementDisposables.add(this.o(template.label.element.querySelector(".monaco-icon-label-container"), instance2, editableData));
      template.actionBar.clear();
    }
  }
  o(container2, instance2, editableData) {
    const value = instance2.title || "";
    const inputBox = new $I2(container2, this.n, {
      validationOptions: {
        validation: (value2) => {
          const message = editableData.validationMessage(value2);
          if (!message || message.severity !== severity_default.Error) {
            return null;
          }
          return {
            content: message.content,
            formatContent: true,
            type: 3
            /* MessageType.ERROR */
          };
        }
      },
      ariaLabel: localize(10539, null),
      inputBoxStyles: $B$
    });
    inputBox.element.style.height = "22px";
    inputBox.value = value;
    inputBox.focus();
    inputBox.select({ start: 0, end: value.length });
    const done = $Qc((success, finishEditing) => {
      inputBox.element.style.display = "none";
      const value2 = inputBox.value;
      $Xc(toDispose);
      inputBox.element.remove();
      if (finishEditing) {
        editableData.onFinish(value2, success);
      }
    });
    const showInputBoxNotification = () => {
      if (inputBox.isInputValid()) {
        const message = editableData.validationMessage(inputBox.value);
        if (message) {
          inputBox.showMessage({
            content: message.content,
            formatContent: true,
            type: message.severity === severity_default.Info ? 1 : message.severity === severity_default.Warning ? 2 : 3
            /* MessageType.ERROR */
          });
        } else {
          inputBox.hideMessage();
        }
      }
    };
    showInputBoxNotification();
    const toDispose = [
      inputBox,
      $aj(inputBox.inputElement, $7j.KEY_DOWN, (e) => {
        e.stopPropagation();
        if (e.equals(
          3
          /* KeyCode.Enter */
        )) {
          done(inputBox.isInputValid(), true);
        } else if (e.equals(
          9
          /* KeyCode.Escape */
        )) {
          done(false, true);
        }
      }),
      $aj(inputBox.inputElement, $7j.KEY_UP, (e) => {
        showInputBoxNotification();
      }),
      $_i(inputBox.inputElement, $7j.BLUR, () => {
        done(inputBox.isInputValid(), true);
      })
    ];
    return $1c(() => {
      done(false, false);
    });
  }
  disposeElement(instance2, index, templateData) {
    templateData.elementDisposables.clear();
    templateData.actionBar.clear();
  }
  disposeTemplate(templateData) {
    templateData.elementDisposables.dispose();
    templateData.label.dispose();
    templateData.actionBar.dispose();
  }
  fillActionBar(instance2, template) {
    const actions = [
      new $Um("workbench.action.terminal.splitActiveTab", $Kec.split.short, ThemeIcon.asClassName($6l.splitHorizontal), true, async () => {
        this.q(instance2, async (e) => {
          this.g.createTerminal({ location: { parentTerminal: e } });
        });
      }),
      new $Um("workbench.action.terminal.killActiveTab", $Kec.kill.short, ThemeIcon.asClassName($6l.trashcan), true, async () => {
        this.q(instance2, (e) => this.g.safeDisposeTerminal(e));
      })
    ];
    template.actionBar.clear();
    for (const action of actions) {
      template.actionBar.push(action, { icon: true, label: false, keybinding: this.k.lookupKeybinding(action.id)?.getLabel() });
    }
  }
  q(instance2, callback) {
    const selection = this.c();
    if (selection.includes(instance2)) {
      for (const s of selection) {
        if (s) {
          callback(s);
        }
      }
    } else {
      callback(instance2);
    }
    this.h.focusTabs();
    this.l.lastFocusedList?.focusNext();
  }
};
TerminalTabsRenderer = __decorate([
  __param(3, $Pk),
  __param(4, $5Pb),
  __param(5, $4Pb),
  __param(6, $7Pb),
  __param(7, $5$),
  __param(8, $Ty),
  __param(9, $Deb),
  __param(10, $gs),
  __param(11, $40)
], TerminalTabsRenderer);
var TerminalTabsAccessibilityProvider = class TerminalTabsAccessibilityProvider2 {
  constructor(a) {
    this.a = a;
  }
  getWidgetAriaLabel() {
    return localize(10540, null);
  }
  getAriaLabel(instance2) {
    let ariaLabel = "";
    const tab = this.a.getGroupForInstance(instance2);
    if (tab && tab.terminalInstances?.length > 1) {
      const terminalIndex = tab.terminalInstances.indexOf(instance2);
      ariaLabel = localize(10541, null, instance2.instanceId, instance2.title, terminalIndex + 1, tab.terminalInstances.length);
    } else {
      ariaLabel = localize(10542, null, instance2.instanceId, instance2.title);
    }
    return ariaLabel;
  }
};
TerminalTabsAccessibilityProvider = __decorate([
  __param(0, $7Pb)
], TerminalTabsAccessibilityProvider);
var TerminalTabsDragAndDrop = class TerminalTabsDragAndDrop2 extends $3c {
  constructor(f, g, h3) {
    super();
    this.f = f;
    this.g = g;
    this.h = h3;
    this.b = $3c.None;
    this.c = this.f.getPrimaryBackend();
  }
  getDragURI(instance2) {
    if (this.f.getEditingTerminal()?.instanceId === instance2.instanceId) {
      return null;
    }
    return instance2.resource.toString();
  }
  getDragLabel(elements, originalEvent) {
    return elements.length === 1 ? elements[0].title : void 0;
  }
  onDragLeave() {
    this.a = void 0;
    this.b.dispose();
    this.b = $3c.None;
  }
  onDragStart(data, originalEvent) {
    if (!originalEvent.dataTransfer) {
      return;
    }
    const dndData = data.getData();
    if (!Array.isArray(dndData)) {
      return;
    }
    const terminals = dndData.filter((e) => "instanceId" in e);
    if (terminals.length > 0) {
      originalEvent.dataTransfer.setData("Terminals", JSON.stringify(terminals.map((e) => e.resource.toString())));
    }
  }
  onDragOver(data, targetInstance, targetIndex, targetSector, originalEvent) {
    if (data instanceof $i1) {
      if (!$z_(originalEvent, $kZ.FILES, $kZ.RESOURCES, "Terminals", $u_.FILES)) {
        return false;
      }
    }
    const didChangeAutoFocusInstance = this.a !== targetInstance;
    if (didChangeAutoFocusInstance) {
      this.b.dispose();
      this.a = targetInstance;
    }
    if (!targetInstance && !$z_(
      originalEvent,
      "Terminals"
      /* TerminalDataTransfers.Terminals */
    )) {
      return data instanceof $g1;
    }
    if (didChangeAutoFocusInstance && targetInstance) {
      this.b = $Xh(() => {
        this.f.setActiveInstance(targetInstance);
        this.a = void 0;
      }, 500, this.q);
    }
    return {
      feedback: targetIndex ? [targetIndex] : void 0,
      accept: true,
      effect: {
        type: 1,
        position: "drop-target"
        /* ListDragOverEffectPosition.Over */
      }
    };
  }
  async drop(data, targetInstance, targetIndex, targetSector, originalEvent) {
    this.b.dispose();
    this.a = void 0;
    let sourceInstances;
    const promises = [];
    const resources = $_ec(originalEvent);
    if (resources) {
      for (const uri of resources) {
        const instance2 = this.f.getInstanceFromResource(uri);
        if (instance2) {
          if (Array.isArray(sourceInstances)) {
            sourceInstances.push(instance2);
          } else {
            sourceInstances = [instance2];
          }
          this.f.moveToTerminalView(instance2);
        } else if (this.c) {
          const terminalIdentifier = $0ec(uri);
          if (terminalIdentifier.instanceId) {
            promises.push(this.c.requestDetachInstance(terminalIdentifier.workspaceId, terminalIdentifier.instanceId));
          }
        }
      }
    }
    if (promises.length) {
      let processes = await Promise.all(promises);
      processes = processes.filter((p) => p !== void 0);
      let lastInstance;
      for (const attachPersistentProcess of processes) {
        lastInstance = await this.f.createTerminal({ config: { attachPersistentProcess } });
      }
      if (lastInstance) {
        this.f.setActiveInstance(lastInstance);
      }
      return;
    }
    if (sourceInstances === void 0) {
      if (!(data instanceof $g1)) {
        this.j(targetInstance, originalEvent);
        return;
      }
      const draggedElement = data.getData();
      if (!draggedElement || !Array.isArray(draggedElement)) {
        return;
      }
      sourceInstances = [];
      for (const e of draggedElement) {
        if ("instanceId" in e) {
          sourceInstances.push(e);
        }
      }
    }
    if (!targetInstance) {
      this.g.moveGroupToEnd(sourceInstances);
      this.f.setActiveInstance(sourceInstances[0]);
      const targetGroup2 = this.g.getGroupForInstance(sourceInstances[0]);
      if (targetGroup2) {
        const index = this.g.groups.indexOf(targetGroup2);
        this.h.lastFocusedList?.setSelection([index]);
      }
      return;
    }
    this.g.moveGroup(sourceInstances, targetInstance);
    this.f.setActiveInstance(sourceInstances[0]);
    const targetGroup = this.g.getGroupForInstance(sourceInstances[0]);
    if (targetGroup) {
      const index = this.g.groups.indexOf(targetGroup);
      this.h.lastFocusedList?.setSelection([index]);
    }
  }
  async j(instance2, e) {
    if (!instance2 || !e.dataTransfer) {
      return;
    }
    let resource;
    const rawResources = e.dataTransfer.getData($kZ.RESOURCES);
    if (rawResources) {
      resource = URI.parse(JSON.parse(rawResources)[0]);
    }
    const rawCodeFiles = e.dataTransfer.getData($u_.FILES);
    if (!resource && rawCodeFiles) {
      resource = URI.file(JSON.parse(rawCodeFiles)[0]);
    }
    if (!resource && e.dataTransfer.files.length > 0 && $E_(e.dataTransfer.files[0])) {
      resource = URI.file($E_(e.dataTransfer.files[0]));
    }
    if (!resource) {
      return;
    }
    this.f.setActiveInstance(instance2);
    instance2.focus();
    await instance2.sendPath(resource, false);
  }
};
TerminalTabsDragAndDrop = __decorate([
  __param(0, $4Pb),
  __param(1, $7Pb),
  __param(2, $Deb)
], TerminalTabsDragAndDrop);
var TabDecorationsProvider = class TabDecorationsProvider2 extends $3c {
  constructor(b) {
    super();
    this.b = b;
    this.label = localize(10543, null);
    this.a = this.B(new $ze());
    this.onDidChange = this.a.event;
    this.B(this.b.onAnyInstancePrimaryStatusChange((e) => this.a.fire([e.resource])));
  }
  provideDecorations(resource) {
    if (resource.scheme !== Schemas.vscodeTerminal) {
      return void 0;
    }
    const instance2 = this.b.getInstanceFromResource(resource);
    if (!instance2) {
      return void 0;
    }
    const primaryStatus = instance2?.statusList?.primary;
    if (!primaryStatus?.icon) {
      return void 0;
    }
    return {
      color: $9Ob(primaryStatus.severity),
      letter: primaryStatus.icon,
      tooltip: primaryStatus.tooltip
    };
  }
};
TabDecorationsProvider = __decorate([
  __param(0, $4Pb)
], TabDecorationsProvider);

// out-build/vs/workbench/contrib/terminal/browser/terminalTabbedView.js
var $145 = $;
var CssClass;
(function(CssClass2) {
  CssClass2["ViewIsVertical"] = "terminal-side-view";
})(CssClass || (CssClass = {}));
var WidthConstants;
(function(WidthConstants2) {
  WidthConstants2[WidthConstants2["StatusIcon"] = 30] = "StatusIcon";
  WidthConstants2[WidthConstants2["SplitAnnotation"] = 30] = "SplitAnnotation";
})(WidthConstants || (WidthConstants = {}));
var $hfc = class $hfc2 extends $3c {
  constructor(parentElement, H, I, J, L, M, N, menuService, O, contextKeyService, P) {
    super();
    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.u = false;
    this.g = $145(".tabs-container");
    const tabListContainer = $145(".tabs-list-container");
    this.f = $145(".tabs-list");
    tabListContainer.appendChild(this.f);
    this.g.appendChild(tabListContainer);
    this.w = this.B(menuService.createMenu($bJ.TerminalInstanceContext, contextKeyService));
    this.y = this.B(menuService.createMenu($bJ.TerminalTabContext, contextKeyService));
    this.z = this.B(menuService.createMenu($bJ.TerminalTabEmptyAreaContext, contextKeyService));
    this.h = this.B(this.L.createInstance($gfc, this.f));
    const terminalOuterContainer = $145(".terminal-outer-container");
    this.b = $145(".terminal-groups-container");
    terminalOuterContainer.appendChild(this.b);
    this.H.setContainers(parentElement, this.b);
    this.C = TerminalContextKeys.tabsNarrow.bindTo(contextKeyService);
    this.D = TerminalContextKeys.tabsFocus.bindTo(contextKeyService);
    this.F = TerminalContextKeys.tabsMouse.bindTo(contextKeyService);
    this.n = this.I.config.tabs.location === "left" ? 0 : 1;
    this.r = this.I.config.tabs.location === "left" ? 1 : 0;
    this.B(N.onDidChangeConfiguration((e) => {
      if (e.affectsConfiguration(
        "terminal.integrated.tabs.enabled"
        /* TerminalSettingId.TabsEnabled */
      ) || e.affectsConfiguration(
        "terminal.integrated.tabs.hideCondition"
        /* TerminalSettingId.TabsHideCondition */
      )) {
        this.R();
      } else if (e.affectsConfiguration(
        "terminal.integrated.tabs.location"
        /* TerminalSettingId.TabsLocation */
      )) {
        this.n = this.I.config.tabs.location === "left" ? 0 : 1;
        this.r = this.I.config.tabs.location === "left" ? 1 : 0;
        if (this.Q()) {
          this.a.swapViews(0, 1);
          this.cb();
          this.bb();
          this.a.resizeView(this.n, this.S());
        }
      }
    }));
    this.B(this.J.onDidChangeInstances(() => this.R()));
    this.B(this.J.onDidChangeGroups(() => this.R()));
    this.eb(parentElement, this.b);
    this.B(this.J.onDidChangePanelOrientation((orientation) => {
      this.G = orientation;
      if (this.G === 0) {
        this.b.classList.add(
          "terminal-side-view"
          /* CssClass.ViewIsVertical */
        );
      } else {
        this.b.classList.remove(
          "terminal-side-view"
          /* CssClass.ViewIsVertical */
        );
      }
    }));
    this.a = new $r2(parentElement, { orientation: 1, proportionalLayout: false });
    this.Z(terminalOuterContainer);
  }
  Q() {
    const enabled = this.I.config.tabs.enabled;
    const hide3 = this.I.config.tabs.hideCondition;
    if (!enabled) {
      return false;
    }
    if (hide3 === "never") {
      return true;
    }
    if (hide3 === "singleTerminal" && this.J.instances.length > 1) {
      return true;
    }
    if (hide3 === "singleGroup" && this.J.groups.length > 1) {
      return true;
    }
    return false;
  }
  R() {
    if (this.Q()) {
      if (this.a.length === 1) {
        this.ab();
        this.bb();
        this.a.resizeView(this.n, this.S());
        this.rerenderTabs();
      }
    } else {
      if (this.a.length === 2 && !this.F.get()) {
        this.a.removeView(this.n);
        this.m?.remove();
        this.cb();
      }
    }
  }
  S() {
    const widthKey = this.G === 0 ? "tabs-list-width-vertical" : "tabs-list-width-horizontal";
    const storedValue = this.O.get(
      widthKey,
      0
      /* StorageScope.PROFILE */
    );
    if (!storedValue || !parseInt(storedValue)) {
      return this.G === 0 ? 46 : 120;
    }
    return parseInt(storedValue);
  }
  U() {
    let idealWidth = 80;
    const offscreenCanvas = document.createElement("canvas");
    offscreenCanvas.width = 1;
    offscreenCanvas.height = 1;
    const ctx = offscreenCanvas.getContext("2d");
    if (ctx) {
      const style = getWindow(this.f).getComputedStyle(this.f);
      ctx.font = `${style.fontStyle} ${style.fontSize} ${style.fontFamily}`;
      const maxInstanceWidth = this.J.instances.reduce((p, c) => {
        return Math.max(p, ctx.measureText(c.title + (c.description || "")).width + this.W(c));
      }, 0);
      idealWidth = Math.ceil(Math.max(
        maxInstanceWidth,
        80
        /* TerminalTabsListSizes.WideViewMinimumWidth */
      ));
    }
    const currentWidth = Math.ceil(this.a.getViewSize(this.n));
    if (currentWidth === idealWidth) {
      idealWidth = 46;
    }
    this.a.resizeView(this.n, idealWidth);
    this.Y(idealWidth);
  }
  W(instance2) {
    const additionalWidth = 40;
    const statusIconWidth = instance2.statusList.statuses.length > 0 ? 30 : 0;
    const splitAnnotationWidth = (this.J.getGroupForInstance(instance2)?.terminalInstances.length || 0) > 1 ? 30 : 0;
    return additionalWidth + splitAnnotationWidth + statusIconWidth;
  }
  X() {
    const listWidth = this.a.getViewSize(this.n);
    if (!this.t || listWidth <= 0) {
      return;
    }
    this.Y(listWidth);
  }
  Y(width2) {
    if (width2 < 63 && width2 >= 46) {
      width2 = 46;
      this.a.resizeView(this.n, width2);
    } else if (width2 >= 63 && width2 < 80) {
      width2 = 80;
      this.a.resizeView(this.n, width2);
    }
    this.rerenderTabs();
    const widthKey = this.G === 0 ? "tabs-list-width-vertical" : "tabs-list-width-horizontal";
    this.O.store(
      widthKey,
      width2,
      0,
      0
      /* StorageTarget.USER */
    );
  }
  Z(terminalOuterContainer) {
    this.B(this.a.onDidSashReset(() => this.U()));
    this.B(this.a.onDidSashChange(() => this.X()));
    if (this.Q()) {
      this.ab();
    }
    this.a.addView({
      element: terminalOuterContainer,
      layout: (width2) => this.J.groups.forEach((tab) => tab.layout(width2, this.s || 0)),
      minimumSize: 120,
      maximumSize: Number.POSITIVE_INFINITY,
      onDidChange: () => $3c.None,
      priority: 2
      /* LayoutPriority.High */
    }, Sizing.Distribute, this.r);
    if (this.Q()) {
      this.bb();
    }
  }
  ab() {
    this.a.addView({
      element: this.g,
      layout: (width2) => this.h.layout(this.s || 0, width2),
      minimumSize: 46,
      maximumSize: 500,
      onDidChange: () => $3c.None,
      priority: 1
      /* LayoutPriority.Low */
    }, Sizing.Distribute, this.n);
    this.rerenderTabs();
  }
  rerenderTabs() {
    this.db();
    this.h.refresh();
  }
  bb() {
    let interval;
    this.j = [
      this.a.sashes[0].onDidStart((e) => {
        interval = $kj(getWindow(this.a.el), () => {
          this.rerenderTabs();
        }, 100);
      }),
      this.a.sashes[0].onDidEnd((e) => {
        interval.dispose();
      })
    ];
  }
  cb() {
    if (this.j) {
      $Xc(this.j);
      this.j = void 0;
    }
  }
  db() {
    const hasText = this.f.clientWidth > 63;
    this.g.classList.toggle("has-text", hasText);
    this.C.set(!hasText);
  }
  layout(width2, height) {
    this.s = height;
    this.t = width2;
    this.a.layout(width2);
    if (this.Q()) {
      this.a.resizeView(this.n, this.S());
    }
    this.db();
  }
  eb(parentDomElement, terminalContainer) {
    this.B($_i(this.g, "mouseleave", async (event) => {
      this.F.set(false);
      this.R();
      event.stopPropagation();
    }));
    this.B($_i(this.g, "mouseenter", async (event) => {
      this.F.set(true);
      event.stopPropagation();
    }));
    this.B($_i(terminalContainer, "mousedown", async (event) => {
      const terminal2 = this.J.activeInstance;
      if (this.J.instances.length > 0 && terminal2) {
        const result = await terminal2.handleMouseEvent(event, this.w);
        if (typeof result === "object" && result.cancelContextMenu) {
          this.u = true;
        }
      }
    }));
    this.B($_i(terminalContainer, "contextmenu", (event) => {
      const rightClickBehavior = this.I.config.rightClickBehavior;
      if (rightClickBehavior === "nothing" && !event.shiftKey) {
        this.u = true;
      }
      terminalContainer.focus();
      if (!this.u) {
        $Oec(getWindow(terminalContainer), event, this.J.activeInstance, this.w, this.M);
      }
      event.preventDefault();
      event.stopImmediatePropagation();
      this.u = false;
    }));
    this.B($_i(this.g, "contextmenu", (event) => {
      const rightClickBehavior = this.I.config.rightClickBehavior;
      if (rightClickBehavior === "nothing" && !event.shiftKey) {
        this.u = true;
      }
      if (!this.u) {
        const emptyList = this.h.getFocus().length === 0;
        if (!emptyList) {
          this.J.lastAccessedMenu = "tab-list";
        }
        const selectedInstances = this.h.getSelectedElements();
        const focusedInstance = this.h.getFocusedElements()?.[0];
        if (focusedInstance) {
          selectedInstances.splice(selectedInstances.findIndex((e) => e.instanceId === focusedInstance.instanceId), 1);
          selectedInstances.unshift(focusedInstance);
        }
        $Oec(getWindow(this.g), event, selectedInstances, emptyList ? this.z : this.y, this.M, emptyList ? this.fb() : void 0);
      }
      event.preventDefault();
      event.stopImmediatePropagation();
      this.u = false;
    }));
    this.B($_i(terminalContainer.ownerDocument, "keydown", (event) => {
      terminalContainer.classList.toggle("alt-active", !!event.altKey);
    }));
    this.B($_i(terminalContainer.ownerDocument, "keyup", (event) => {
      terminalContainer.classList.toggle("alt-active", !!event.altKey);
    }));
    this.B($_i(parentDomElement, "keyup", (event) => {
      if (event.keyCode === 27) {
        event.stopPropagation();
      }
    }));
    this.B($_i(this.g, $7j.FOCUS_IN, () => {
      this.D.set(true);
    }));
    this.B($_i(this.g, $7j.FOCUS_OUT, () => {
      this.D.set(false);
    }));
  }
  fb() {
    return [
      new $Wm(),
      this.N.inspect(
        "terminal.integrated.tabs.location"
        /* TerminalSettingId.TabsLocation */
      ).userValue === "left" ? new $Um("moveRight", localize(10536, null), void 0, void 0, async () => {
        this.N.updateValue("terminal.integrated.tabs.location", "right");
      }) : new $Um("moveLeft", localize(10537, null), void 0, void 0, async () => {
        this.N.updateValue("terminal.integrated.tabs.location", "left");
      }),
      new $Um("hideTabs", localize(10538, null), void 0, void 0, async () => {
        this.N.updateValue("terminal.integrated.tabs.enabled", false);
      })
    ];
  }
  setEditable(isEditing) {
    if (!isEditing) {
      this.h.domFocus();
    }
    this.h.refresh(false);
  }
  focusTabs() {
    if (!this.Q()) {
      return;
    }
    this.D.set(true);
    const selected = this.h.getSelection();
    this.h.domFocus();
    if (selected) {
      this.h.setFocus(selected);
    }
  }
  focus() {
    if (this.H.connectionState === 1) {
      this.gb();
      return;
    }
    const previousActiveElement = this.f.ownerDocument.activeElement;
    if (previousActiveElement) {
      this.B(this.H.onDidChangeConnectionState(() => {
        if ($Mj(previousActiveElement)) {
          this.gb();
        }
      }));
    }
  }
  focusHover() {
    if (this.Q()) {
      this.h.focusHover();
      return;
    }
    const instance2 = this.J.activeInstance;
    if (!instance2) {
      return;
    }
    this.P.showHover({
      ...$dfc(instance2),
      target: this.b,
      trapFocus: true
    }, true);
  }
  gb() {
    this.J.activeInstance?.focusWhenReady();
  }
};
$hfc = __decorate([
  __param(1, $4Pb),
  __param(2, $5Pb),
  __param(3, $7Pb),
  __param(4, $Pk),
  __param(5, $50),
  __param(6, $kl),
  __param(7, $cJ),
  __param(8, $jv),
  __param(9, $on),
  __param(10, $5$)
], $hfc);

// out-build/vs/workbench/contrib/terminal/browser/terminalView.js
var $ifc = class $ifc2 extends $_ob {
  get terminalTabbedView() {
    return this.f;
  }
  constructor(options3, keybindingService, s, viewDescriptorService, t, L, ab, sb, ac, bc, themeService, telemetryService, hoverService, cc, dc, openerService, ec, fc, gc, hc, ic) {
    super(options3, keybindingService, L, t, s, viewDescriptorService, ab, openerService, themeService, telemetryService, hoverService);
    this.s = s;
    this.t = t;
    this.L = L;
    this.ab = ab;
    this.sb = sb;
    this.ac = ac;
    this.bc = bc;
    this.cc = cc;
    this.dc = dc;
    this.ec = ec;
    this.fc = fc;
    this.gc = gc;
    this.hc = hc;
    this.ic = ic;
    this.g = false;
    this.h = this.B(new $4c());
    this.r = this.B(new $2c());
    this.B(this.sb.onDidRegisterProcessSupport(() => {
      this.eb.fire();
    }));
    this.B(this.sb.onDidChangeInstances(() => {
      if (this.tc() && this.bc.instances.length <= 1) {
        this.eb.fire();
      }
      if (!this.b) {
        return;
      }
      if (!this.f) {
        this.nc();
      }
      if (this.bc.instances.length === 1) {
        this.X(this.b.offsetHeight, this.b.offsetWidth);
      }
    }));
    this.j = this.B(this.ec.createMenu($bJ.TerminalNewDropdownContext, this.s));
    this.m = this.B(this.ec.createMenu($bJ.TerminalTabContext, this.s));
    this.B(this.fc.onDidChangeAvailableProfiles((profiles2) => this.sc(profiles2)));
    this.n = TerminalContextKeys.viewShowing.bindTo(this.s);
    this.B(this.onDidChangeBodyVisibility((e) => {
      if (e) {
        this.f?.rerenderTabs();
      }
    }));
    this.B(this.t.onDidChangeConfiguration((e) => {
      if (this.b && (e.affectsConfiguration(
        "terminal.integrated.shellIntegration.decorationsEnabled"
        /* TerminalSettingId.ShellIntegrationDecorationsEnabled */
      ) || e.affectsConfiguration(
        "terminal.integrated.shellIntegration.enabled"
        /* TerminalSettingId.ShellIntegrationEnabled */
      ))) {
        this.jc(this.b);
      }
    }));
    this.B(this.sb.onDidCreateInstance((i2) => {
      i2.capabilities.onDidAddCapabilityType((c) => {
        if (c === 2 && this.kc()) {
          this.b?.classList.add("shell-integration");
        }
      });
    }));
  }
  jc(container2) {
    container2.classList.toggle("shell-integration", this.kc());
  }
  kc() {
    const decorationsEnabled = this.t.getValue(
      "terminal.integrated.shellIntegration.decorationsEnabled"
      /* TerminalSettingId.ShellIntegrationDecorationsEnabled */
    );
    return (decorationsEnabled === "both" || decorationsEnabled === "gutter") && this.t.getValue(
      "terminal.integrated.shellIntegration.enabled"
      /* TerminalSettingId.ShellIntegrationEnabled */
    );
  }
  lc(checkRestoredTerminals) {
    if (this.isBodyVisible() && this.sb.isProcessSupportRegistered && this.sb.connectionState === 1) {
      const wasInitialized = this.g;
      this.g = true;
      let hideOnStartup = "never";
      if (!wasInitialized) {
        hideOnStartup = this.t.getValue(
          "terminal.integrated.hideOnStartup"
          /* TerminalSettingId.HideOnStartup */
        );
        if (hideOnStartup === "always") {
          this.bc.hidePanel();
        }
      }
      let shouldCreate = this.bc.groups.length === 0;
      if (checkRestoredTerminals) {
        shouldCreate &&= this.sb.restoredGroupCount === 0;
      }
      if (!shouldCreate) {
        return;
      }
      if (!wasInitialized) {
        switch (hideOnStartup) {
          case "never":
            this.sb.createTerminal({ location: TerminalLocation2.Panel });
            break;
          case "whenEmpty":
            if (this.sb.restoredGroupCount === 0) {
              this.bc.hidePanel();
            }
            break;
        }
        return;
      }
      this.sb.createTerminal({ location: TerminalLocation2.Panel });
    }
  }
  // eslint-disable-next-line @typescript-eslint/naming-convention
  W(container2) {
    super.W(container2);
    if (!this.b) {
      this.jc(container2);
    }
    this.b = container2;
    this.b.classList.add("integrated-terminal");
    $VZ(this.b);
    this.ab.createInstance(TerminalThemeIconStyle, this.b);
    if (!this.shouldShowWelcome()) {
      this.nc();
    }
    this.B(this.Ab.onDidChangeConfiguration((e) => {
      if (e.affectsConfiguration(
        "terminal.integrated.fontFamily"
        /* TerminalSettingId.FontFamily */
      ) || e.affectsConfiguration("editor.fontFamily")) {
        if (!this.ac.configFontIsMonospace()) {
          const choices = [{
            label: localize(10549, null),
            run: () => this.Ab.updateValue("terminal.integrated.fontFamily", "monospace")
          }];
          this.cc.prompt(Severity2.Warning, localize(10550, null), choices);
        }
      }
    }));
    this.B(this.onDidChangeBodyVisibility(async (visible) => {
      this.n.set(visible);
      if (visible) {
        if (this.tc()) {
          this.eb.fire();
        }
        this.lc(false);
        this.bc.showPanel(false);
      } else {
        for (const instance2 of this.bc.instances) {
          instance2.resetFocusContextKey();
        }
      }
      this.bc.updateVisibility();
    }));
    this.B(this.sb.onDidChangeConnectionState(() => this.lc(true)));
    this.X(this.b.offsetHeight, this.b.offsetWidth);
  }
  nc() {
    if (!this.b) {
      return;
    }
    this.f = this.B(this.Db.createInstance($hfc, this.b));
  }
  // eslint-disable-next-line @typescript-eslint/naming-convention
  X(height, width2) {
    super.X(height, width2);
    this.f?.layout(width2, height);
  }
  getActionViewItem(action, options3) {
    switch (action.id) {
      case "workbench.action.terminal.split": {
        const that = this;
        const panelOnlySplitAction = new class extends $Um {
          constructor() {
            super(action.id, action.label, action.class, action.enabled);
            this.checked = action.checked;
            this.tooltip = action.tooltip;
            this.B(action);
          }
          async run() {
            const instance2 = that.bc.activeInstance;
            if (instance2) {
              const newInstance = await that.sb.createTerminal({ location: { parentTerminal: instance2 } });
              return newInstance?.focusWhenReady();
            }
            return;
          }
        }();
        return new $U1(action, panelOnlySplitAction, { ...options3, icon: true, label: false, keybinding: this.rc(action) });
      }
      case "workbench.action.terminal.switchTerminal": {
        return this.ab.createInstance(SwitchTerminalActionViewItem, action);
      }
      case "workbench.action.terminal.focus": {
        if (action instanceof $fJ) {
          const actions = $P$(this.m.getActions({ shouldForwardArgs: true }));
          return this.ab.createInstance(SingleTerminalTabActionViewItem, action, actions);
        }
      }
      case "workbench.action.terminal.new": {
        if (action instanceof $fJ) {
          const actions = $7ec(TerminalLocation2.Panel, this.fc.availableProfiles, this.qc(), this.fc.contributedProfiles, this.sb, this.j);
          this.pc(actions.dropdownAction, actions.dropdownMenuActions);
          this.h.value = new $isb(action, actions.dropdownAction, actions.dropdownMenuActions, actions.className, { hoverDelegate: options3.hoverDelegate }, this.L, this.dc, this.cc, this.s, this.hc, this.ic);
          this.h.value?.update(actions.dropdownAction, actions.dropdownMenuActions);
          return this.h.value;
        }
      }
    }
    return super.getActionViewItem(action, options3);
  }
  /**
   * Actions might be of type Action (disposable) or Separator or SubmenuAction, which don't extend Disposable
   */
  pc(dropdownAction, dropdownMenuActions) {
    this.r.clear();
    if (dropdownAction instanceof $Um) {
      this.r.add(dropdownAction);
    }
    dropdownMenuActions.filter((a) => a instanceof $Um).forEach((a) => this.r.add(a));
  }
  qc() {
    let defaultProfileName;
    try {
      defaultProfileName = this.fc.getDefaultProfileName();
    } catch (e) {
      defaultProfileName = this.gc.defaultProfileName;
    }
    return defaultProfileName;
  }
  rc(action) {
    return this.dc.lookupKeybinding(action.id)?.getLabel() ?? void 0;
  }
  sc(profiles2) {
    const actions = $7ec(TerminalLocation2.Panel, profiles2, this.qc(), this.fc.contributedProfiles, this.sb, this.j);
    this.pc(actions.dropdownAction, actions.dropdownMenuActions);
    this.h.value?.update(actions.dropdownAction, actions.dropdownMenuActions);
  }
  focus() {
    super.focus();
    if (this.sb.connectionState === 1) {
      this.bc.showPanel(true);
      return;
    }
    const previousActiveElement = this.element.ownerDocument.activeElement;
    if (previousActiveElement) {
      this.B(this.sb.onDidChangeConnectionState(() => {
        if (previousActiveElement && $Mj(previousActiveElement)) {
          this.bc.showPanel(true);
        }
      }));
    }
  }
  tc() {
    return !this.sb.isProcessSupportRegistered;
  }
  shouldShowWelcome() {
    return this.tc() && this.sb.instances.length === 0;
  }
};
$ifc = __decorate([
  __param(1, $Ty),
  __param(2, $on),
  __param(3, $$M),
  __param(4, $kl),
  __param(5, $50),
  __param(6, $Pk),
  __param(7, $4Pb),
  __param(8, $5Pb),
  __param(9, $7Pb),
  __param(10, $gs),
  __param(11, $zv),
  __param(12, $5$),
  __param(13, $PJ),
  __param(14, $Ty),
  __param(15, $O4),
  __param(16, $cJ),
  __param(17, $hY),
  __param(18, $fY),
  __param(19, $gs),
  __param(20, $ND)
], $ifc);
var SwitchTerminalActionViewItem = class SwitchTerminalActionViewItem2 extends $V1 {
  constructor(action, h3, r2, contextViewService, terminalProfileService) {
    super(null, action, getTerminalSelectOpenItems(h3, r2), r2.activeGroupIndex, contextViewService, $K$, { ariaLabel: localize(10551, null), optionsAsChildren: true });
    this.h = h3;
    this.r = r2;
    this.B(h3.onDidChangeInstances(() => this.s(), this));
    this.B(h3.onDidChangeActiveGroup(() => this.s(), this));
    this.B(h3.onDidChangeActiveInstance(() => this.s(), this));
    this.B(h3.onAnyInstanceTitleChange(() => this.s(), this));
    this.B(r2.onDidChangeGroups(() => this.s(), this));
    this.B(h3.onDidChangeConnectionState(() => this.s(), this));
    this.B(terminalProfileService.onDidChangeAvailableProfiles(() => this.s(), this));
    this.B(h3.onAnyInstancePrimaryStatusChange(() => this.s(), this));
  }
  render(container2) {
    super.render(container2);
    container2.classList.add("switch-terminal");
    container2.style.borderColor = $Zn($Rq);
  }
  s() {
    const options3 = getTerminalSelectOpenItems(this.h, this.r);
    this.setOptions(options3, this.r.activeGroupIndex);
  }
};
SwitchTerminalActionViewItem = __decorate([
  __param(1, $4Pb),
  __param(2, $7Pb),
  __param(3, $40),
  __param(4, $hY)
], SwitchTerminalActionViewItem);
function getTerminalSelectOpenItems(terminalService, terminalGroupService) {
  let items;
  if (terminalService.connectionState === 1) {
    items = terminalGroupService.getGroupLabels().map((label3) => {
      return { text: label3 };
    });
  } else {
    items = [{ text: localize(10552, null) }];
  }
  items.push({ text: $Pec, isDisabled: true });
  items.push({ text: $Qec });
  return items;
}
var SingleTerminalTabActionViewItem = class SingleTerminalTabActionViewItem2 extends $T$ {
  constructor(action, y, keybindingService, notificationService, contextKeyService, themeService, jb, lb, mb, contextMenuService, nb, ob, _accessibilityService) {
    super(action, {
      draggable: true,
      hoverDelegate: ob.createInstance(SingleTabHoverDelegate)
    }, keybindingService, notificationService, contextKeyService, themeService, contextMenuService, _accessibilityService);
    this.y = y;
    this.jb = jb;
    this.lb = lb;
    this.mb = mb;
    this.nb = nb;
    this.ob = ob;
    this.m = [];
    this.B(Event2.debounce(Event2.any(this.jb.onAnyInstancePrimaryStatusChange, this.mb.onDidChangeActiveInstance, Event2.map(this.jb.onAnyInstanceIconChange, (e) => e.instance), this.jb.onAnyInstanceTitleChange, this.jb.onDidChangeInstanceCapability), (last, e) => {
      if (!last) {
        last = /* @__PURE__ */ new Set();
      }
      if (e) {
        last.add(e);
      }
      return last;
    }, $ue)((merged) => {
      for (const e of merged) {
        this.C(e);
      }
    }));
    this.B($1c(() => $Xc(this.m)));
  }
  async onClick(event) {
    this.mb.lastAccessedMenu = "inline-tab";
    if (event.altKey && this.db.alt) {
      this.nb.executeCommand(this.db.alt.id, { location: TerminalLocation2.Panel });
    } else {
      this.qb();
    }
  }
  // eslint-disable-next-line @typescript-eslint/naming-convention
  C(e) {
    if (e && e !== this.mb.activeInstance) {
      return;
    }
    if (this.m.length === 0 && this.element && this.L) {
      this.m.push($_i(this.element, $7j.CONTEXT_MENU, (e2) => {
        if (e2.button === 2) {
          this.qb();
          e2.preventDefault();
        }
      }));
      this.m.push($_i(this.element, $7j.AUXCLICK, (e2) => {
        if (e2.button === 1) {
          const instance2 = this.mb.activeInstance;
          if (instance2) {
            this.jb.safeDisposeTerminal(instance2);
          }
          e2.preventDefault();
        }
      }));
      this.m.push($_i(this.element, $7j.DRAG_START, (e2) => {
        const instance2 = this.mb.activeInstance;
        if (e2.dataTransfer && instance2) {
          e2.dataTransfer.setData("Terminals", JSON.stringify([instance2.resource.toString()]));
        }
      }));
    }
    if (this.L) {
      const label3 = this.L;
      const instance2 = this.mb.activeInstance;
      if (!instance2) {
        $dk(label3, "");
        return;
      }
      label3.classList.add("single-terminal-tab");
      let colorStyle = "";
      const primaryStatus = instance2.statusList.primary;
      if (primaryStatus) {
        const colorKey = $9Ob(primaryStatus.severity);
        this.ab.getColorTheme();
        const foundColor = this.ab.getColorTheme().getColor(colorKey);
        if (foundColor) {
          colorStyle = foundColor.toString();
        }
      }
      label3.style.color = colorStyle;
      $dk(label3, ...$B1(this.ob.invokeFunction(getSingleTabLabel, instance2, this.lb.config.tabs.separator, ThemeIcon.isThemeIcon(this.eb.item.icon) ? this.eb.item.icon : void 0)));
      if (this.g) {
        label3.classList.remove(this.g);
        this.g = void 0;
      }
      if (this.b) {
        label3.classList.remove(this.b);
        this.b = void 0;
      }
      if (this.h) {
        label3.classList.remove(this.h);
        label3.classList.remove("terminal-uri-icon");
        this.h = void 0;
      }
      const colorClass = $_Pb(instance2);
      if (colorClass) {
        this.b = colorClass;
        label3.classList.add(colorClass);
      }
      const uriClasses = $dQb(instance2, this.ab.getColorTheme().type);
      if (uriClasses) {
        this.h = uriClasses?.[0];
        label3.classList.add(...uriClasses);
      }
      if (this.eb.item.icon) {
        this.g = `alt-command`;
        label3.classList.add(this.g);
      }
      this.G();
    }
  }
  qb() {
    this.bb.showContextMenu({
      actionRunner: new $Nec(),
      getAnchor: () => this.element,
      getActions: () => this.y,
      // The context is always the active instance in the terminal view
      getActionsContext: () => {
        const instance2 = this.mb.activeInstance;
        return instance2 ? [new $Mec(instance2)] : [];
      }
    });
  }
};
SingleTerminalTabActionViewItem = __decorate([
  __param(2, $Ty),
  __param(3, $PJ),
  __param(4, $on),
  __param(5, $gs),
  __param(6, $4Pb),
  __param(7, $5Pb),
  __param(8, $7Pb),
  __param(9, $50),
  __param(10, $sn),
  __param(11, $Pk),
  __param(12, $ND)
], SingleTerminalTabActionViewItem);
function getSingleTabLabel(accessor, instance2, separator, icon2) {
  if (!instance2 || !instance2.title) {
    return "";
  }
  const iconId = ThemeIcon.isThemeIcon(instance2.icon) ? instance2.icon.id : accessor.get($fY).getDefaultIcon().id;
  const label3 = `$(${icon2?.id || iconId}) ${getSingleTabTitle(instance2, separator)}`;
  const primaryStatus = instance2.statusList.primary;
  if (!primaryStatus?.icon) {
    return label3;
  }
  return `${label3} $(${primaryStatus.icon.id})`;
}
function getSingleTabTitle(instance2, separator) {
  if (!instance2) {
    return "";
  }
  return !instance2.description ? instance2.title : `${instance2.title} ${separator} ${instance2.description}`;
}
var TerminalThemeIconStyle = class TerminalThemeIconStyle2 extends $ns {
  constructor(container2, f, g, j) {
    super(f);
    this.f = f;
    this.g = g;
    this.j = j;
    this.m();
    this.b = $VZ(container2);
    this.B($1c(() => this.b.remove()));
    this.updateStyles();
  }
  m() {
    this.B(this.g.onAnyInstanceIconChange(() => this.updateStyles()));
    this.B(this.g.onDidChangeInstances(() => this.updateStyles()));
    this.B(this.j.onDidChangeGroups(() => this.updateStyles()));
  }
  updateStyles() {
    super.updateStyles();
    const colorTheme = this.f.getColorTheme();
    let css = "";
    for (const instance2 of this.g.instances) {
      const icon2 = instance2.icon;
      if (!icon2) {
        continue;
      }
      let uri = void 0;
      if (icon2 instanceof URI) {
        uri = icon2;
      } else if (icon2 instanceof Object && "light" in icon2 && "dark" in icon2) {
        uri = colorTheme.type === ColorScheme.LIGHT ? icon2.light : icon2.dark;
      }
      const iconClasses = $dQb(instance2, colorTheme.type);
      if (uri instanceof URI && iconClasses && iconClasses.length > 1) {
        css += `.monaco-workbench .${iconClasses[0]} .monaco-highlighted-label .codicon, .monaco-action-bar .terminal-uri-icon.single-terminal-tab.action-label:not(.alt-command) .codicon{background-image: ${$5Z(uri)};}`;
      }
    }
    for (const instance2 of this.g.instances) {
      const colorClass = $_Pb(instance2);
      if (!colorClass || !instance2.color) {
        continue;
      }
      const color2 = colorTheme.getColor(instance2.color);
      if (color2) {
        css += `.monaco-workbench .${colorClass} .codicon:first-child:not(.codicon-split-horizontal):not(.codicon-trashcan):not(.file-icon){ color: ${color2} !important; }`;
      }
    }
    this.b.textContent = css;
  }
};
TerminalThemeIconStyle = __decorate([
  __param(1, $gs),
  __param(2, $4Pb),
  __param(3, $7Pb)
], TerminalThemeIconStyle);
var SingleTabHoverDelegate = class SingleTabHoverDelegate2 {
  constructor(d, f, g) {
    this.d = d;
    this.f = f;
    this.g = g;
    this.b = 0;
    this.placement = "element";
  }
  get delay() {
    return Date.now() - this.b < 200 ? 0 : this.d.getValue("workbench.hover.delay");
  }
  showHover(options3, focus) {
    const instance2 = this.g.activeInstance;
    if (!instance2) {
      return;
    }
    const hoverInfo = $dfc(instance2);
    return this.f.showHover({
      ...options3,
      content: hoverInfo.content,
      actions: hoverInfo.actions
    }, focus);
  }
  onDidHideHover() {
    this.b = Date.now();
  }
};
SingleTabHoverDelegate = __decorate([
  __param(0, $kl),
  __param(1, $5$),
  __param(2, $7Pb)
], SingleTabHoverDelegate);

// out-build/vs/workbench/contrib/terminal/common/terminalConfiguration.js
var terminalDescriptors = "\n- " + [
  "`${cwd}`: " + localize(10606, null),
  "`${cwdFolder}`: " + localize(10607, null),
  "`${workspaceFolder}`: " + localize(10608, null),
  "`${workspaceFolderName}`: " + localize(10609, null),
  "`${local}`: " + localize(10610, null),
  "`${process}`: " + localize(10611, null),
  "`${separator}`: " + localize(10612, null, "(` - `)"),
  "`${sequence}`: " + localize(10613, null),
  "`${task}`: " + localize(10614, null),
  "`${shellType}`: " + localize(10615, null),
  "`${shellCommand}`: " + localize(10616, null),
  "`${shellPromptInput}`: " + localize(10617, null)
].join("\n- ");
var terminalTitle = localize(10618, null);
terminalTitle += terminalDescriptors;
var terminalDescription = localize(10619, null);
terminalDescription += terminalDescriptors;
var $Hfc = $m ? 12 : 14;
var terminalConfiguration = {
  id: "terminal",
  order: 100,
  title: localize(10620, null),
  type: "object",
  properties: {
    [
      "terminal.integrated.sendKeybindingsToShell"
      /* TerminalSettingId.SendKeybindingsToShell */
    ]: {
      markdownDescription: localize(10621, null, "`#terminal.integrated.commandsToSkipShell#`"),
      type: "boolean",
      default: false
    },
    [
      "terminal.integrated.tabs.defaultColor"
      /* TerminalSettingId.TabsDefaultColor */
    ]: {
      description: localize(10622, null),
      ...$xB,
      scope: 4
      /* ConfigurationScope.RESOURCE */
    },
    [
      "terminal.integrated.tabs.defaultIcon"
      /* TerminalSettingId.TabsDefaultIcon */
    ]: {
      description: localize(10623, null),
      ...$yB,
      default: $6l.terminal.id,
      scope: 4
      /* ConfigurationScope.RESOURCE */
    },
    [
      "terminal.integrated.tabs.enabled"
      /* TerminalSettingId.TabsEnabled */
    ]: {
      description: localize(10624, null),
      type: "boolean",
      default: true
    },
    [
      "terminal.integrated.tabs.enableAnimation"
      /* TerminalSettingId.TabsEnableAnimation */
    ]: {
      description: localize(10625, null),
      type: "boolean",
      default: true
    },
    [
      "terminal.integrated.tabs.hideCondition"
      /* TerminalSettingId.TabsHideCondition */
    ]: {
      description: localize(10626, null),
      type: "string",
      enum: ["never", "singleTerminal", "singleGroup"],
      enumDescriptions: [
        localize(10627, null),
        localize(10628, null),
        localize(10629, null)
      ],
      default: "singleTerminal"
    },
    [
      "terminal.integrated.tabs.showActiveTerminal"
      /* TerminalSettingId.TabsShowActiveTerminal */
    ]: {
      description: localize(10630, null),
      type: "string",
      enum: ["always", "singleTerminal", "singleTerminalOrNarrow", "never"],
      enumDescriptions: [
        localize(10631, null),
        localize(10632, null),
        localize(10633, null),
        localize(10634, null)
      ],
      default: "singleTerminalOrNarrow"
    },
    [
      "terminal.integrated.tabs.showActions"
      /* TerminalSettingId.TabsShowActions */
    ]: {
      description: localize(10635, null),
      type: "string",
      enum: ["always", "singleTerminal", "singleTerminalOrNarrow", "never"],
      enumDescriptions: [
        localize(10636, null),
        localize(10637, null),
        localize(10638, null),
        localize(10639, null)
      ],
      default: "singleTerminalOrNarrow"
    },
    [
      "terminal.integrated.tabs.location"
      /* TerminalSettingId.TabsLocation */
    ]: {
      type: "string",
      enum: ["left", "right"],
      enumDescriptions: [
        localize(10640, null),
        localize(10641, null)
      ],
      default: "right",
      description: localize(10642, null)
    },
    [
      "terminal.integrated.defaultLocation"
      /* TerminalSettingId.DefaultLocation */
    ]: {
      type: "string",
      enum: [
        "editor",
        "view"
        /* TerminalLocationString.TerminalView */
      ],
      enumDescriptions: [
        localize(10643, null),
        localize(10644, null)
      ],
      default: "view",
      description: localize(10645, null)
    },
    [
      "terminal.integrated.tabs.focusMode"
      /* TerminalSettingId.TabsFocusMode */
    ]: {
      type: "string",
      enum: ["singleClick", "doubleClick"],
      enumDescriptions: [
        localize(10646, null),
        localize(10647, null)
      ],
      default: "doubleClick",
      description: localize(10648, null)
    },
    [
      "terminal.integrated.macOptionIsMeta"
      /* TerminalSettingId.MacOptionIsMeta */
    ]: {
      description: localize(10649, null),
      type: "boolean",
      default: false
    },
    [
      "terminal.integrated.macOptionClickForcesSelection"
      /* TerminalSettingId.MacOptionClickForcesSelection */
    ]: {
      description: localize(10650, null),
      type: "boolean",
      default: false
    },
    [
      "terminal.integrated.altClickMovesCursor"
      /* TerminalSettingId.AltClickMovesCursor */
    ]: {
      markdownDescription: localize(10651, null, "`#editor.multiCursorModifier#`", "`'alt'`"),
      type: "boolean",
      default: true
    },
    [
      "terminal.integrated.copyOnSelection"
      /* TerminalSettingId.CopyOnSelection */
    ]: {
      description: localize(10652, null),
      type: "boolean",
      default: false
    },
    [
      "terminal.integrated.enableMultiLinePasteWarning"
      /* TerminalSettingId.EnableMultiLinePasteWarning */
    ]: {
      markdownDescription: localize(10653, null),
      type: "string",
      enum: ["auto", "always", "never"],
      markdownEnumDescriptions: [
        localize(10654, null),
        localize(10655, null),
        localize(10656, null)
      ],
      default: "auto"
    },
    [
      "terminal.integrated.drawBoldTextInBrightColors"
      /* TerminalSettingId.DrawBoldTextInBrightColors */
    ]: {
      description: localize(10657, null),
      type: "boolean",
      default: true
    },
    [
      "terminal.integrated.fontFamily"
      /* TerminalSettingId.FontFamily */
    ]: {
      markdownDescription: localize(10658, null, "`#editor.fontFamily#`"),
      type: "string"
    },
    [
      "terminal.integrated.fontLigatures"
      /* TerminalSettingId.FontLigatures */
    ]: {
      markdownDescription: localize(10659, null, `\`#${"terminal.integrated.fontFamily"}#\``),
      type: "boolean",
      tags: ["preview"],
      default: false
    },
    [
      "terminal.integrated.fontSize"
      /* TerminalSettingId.FontSize */
    ]: {
      description: localize(10660, null),
      type: "number",
      default: $Hfc,
      minimum: 6,
      maximum: 100
    },
    [
      "terminal.integrated.letterSpacing"
      /* TerminalSettingId.LetterSpacing */
    ]: {
      description: localize(10661, null),
      type: "number",
      default: $0X
    },
    [
      "terminal.integrated.lineHeight"
      /* TerminalSettingId.LineHeight */
    ]: {
      description: localize(10662, null),
      type: "number",
      default: $_X
    },
    [
      "terminal.integrated.minimumContrastRatio"
      /* TerminalSettingId.MinimumContrastRatio */
    ]: {
      markdownDescription: localize(10663, null),
      type: "number",
      default: 4.5,
      tags: ["accessibility"]
    },
    [
      "terminal.integrated.tabStopWidth"
      /* TerminalSettingId.TabStopWidth */
    ]: {
      markdownDescription: localize(10664, null),
      type: "number",
      minimum: 1,
      default: 8
    },
    [
      "terminal.integrated.fastScrollSensitivity"
      /* TerminalSettingId.FastScrollSensitivity */
    ]: {
      markdownDescription: localize(10665, null),
      type: "number",
      default: 5
    },
    [
      "terminal.integrated.mouseWheelScrollSensitivity"
      /* TerminalSettingId.MouseWheelScrollSensitivity */
    ]: {
      markdownDescription: localize(10666, null),
      type: "number",
      default: 1
    },
    [
      "terminal.integrated.bellDuration"
      /* TerminalSettingId.BellDuration */
    ]: {
      markdownDescription: localize(10667, null),
      type: "number",
      default: 1e3
    },
    [
      "terminal.integrated.fontWeight"
      /* TerminalSettingId.FontWeight */
    ]: {
      "anyOf": [
        {
          type: "number",
          minimum: $aY,
          maximum: $bY,
          errorMessage: localize(10668, null)
        },
        {
          type: "string",
          pattern: "^(normal|bold|1000|[1-9][0-9]{0,2})$"
        },
        {
          enum: $eY
        }
      ],
      description: localize(10669, null),
      default: "normal"
    },
    [
      "terminal.integrated.fontWeightBold"
      /* TerminalSettingId.FontWeightBold */
    ]: {
      "anyOf": [
        {
          type: "number",
          minimum: $aY,
          maximum: $bY,
          errorMessage: localize(10670, null)
        },
        {
          type: "string",
          pattern: "^(normal|bold|1000|[1-9][0-9]{0,2})$"
        },
        {
          enum: $eY
        }
      ],
      description: localize(10671, null),
      default: "bold"
    },
    [
      "terminal.integrated.cursorBlinking"
      /* TerminalSettingId.CursorBlinking */
    ]: {
      description: localize(10672, null),
      type: "boolean",
      default: false
    },
    [
      "terminal.integrated.cursorStyle"
      /* TerminalSettingId.CursorStyle */
    ]: {
      description: localize(10673, null),
      enum: ["block", "line", "underline"],
      default: "block"
    },
    [
      "terminal.integrated.cursorStyleInactive"
      /* TerminalSettingId.CursorStyleInactive */
    ]: {
      description: localize(10674, null),
      enum: ["outline", "block", "line", "underline", "none"],
      default: "outline"
    },
    [
      "terminal.integrated.cursorWidth"
      /* TerminalSettingId.CursorWidth */
    ]: {
      markdownDescription: localize(10675, null, "`#terminal.integrated.cursorStyle#`", "`line`"),
      type: "number",
      default: 1
    },
    [
      "terminal.integrated.scrollback"
      /* TerminalSettingId.Scrollback */
    ]: {
      description: localize(10676, null),
      type: "number",
      default: 1e3
    },
    [
      "terminal.integrated.detectLocale"
      /* TerminalSettingId.DetectLocale */
    ]: {
      markdownDescription: localize(10677, null),
      type: "string",
      enum: ["auto", "off", "on"],
      markdownEnumDescriptions: [
        localize(10678, null),
        localize(10679, null),
        localize(10680, null)
      ],
      default: "auto"
    },
    [
      "terminal.integrated.gpuAcceleration"
      /* TerminalSettingId.GpuAcceleration */
    ]: {
      type: "string",
      enum: ["auto", "on", "off"],
      markdownEnumDescriptions: [
        localize(10681, null),
        localize(10682, null),
        localize(10683, null)
      ],
      default: "auto",
      description: localize(10684, null)
    },
    [
      "terminal.integrated.tabs.separator"
      /* TerminalSettingId.TerminalTitleSeparator */
    ]: {
      "type": "string",
      "default": " - ",
      "markdownDescription": localize(10685, null, `\`#${"terminal.integrated.tabs.title"}#\``, `\`#${"terminal.integrated.tabs.description"}#\``)
    },
    [
      "terminal.integrated.tabs.title"
      /* TerminalSettingId.TerminalTitle */
    ]: {
      "type": "string",
      "default": "${process}",
      "markdownDescription": terminalTitle
    },
    [
      "terminal.integrated.tabs.description"
      /* TerminalSettingId.TerminalDescription */
    ]: {
      "type": "string",
      "default": "${task}${separator}${local}${separator}${cwdFolder}",
      "markdownDescription": terminalDescription
    },
    [
      "terminal.integrated.rightClickBehavior"
      /* TerminalSettingId.RightClickBehavior */
    ]: {
      type: "string",
      enum: ["default", "copyPaste", "paste", "selectWord", "nothing"],
      enumDescriptions: [
        localize(10686, null),
        localize(10687, null),
        localize(10688, null),
        localize(10689, null),
        localize(10690, null)
      ],
      default: $m ? "selectWord" : $l ? "copyPaste" : "default",
      description: localize(10691, null)
    },
    [
      "terminal.integrated.middleClickBehavior"
      /* TerminalSettingId.MiddleClickBehavior */
    ]: {
      type: "string",
      enum: ["default", "paste"],
      enumDescriptions: [
        localize(10692, null),
        localize(10693, null)
      ],
      default: "default",
      description: localize(10694, null)
    },
    [
      "terminal.integrated.cwd"
      /* TerminalSettingId.Cwd */
    ]: {
      restricted: true,
      description: localize(10695, null),
      type: "string",
      default: void 0,
      scope: 4
      /* ConfigurationScope.RESOURCE */
    },
    [
      "terminal.integrated.confirmOnExit"
      /* TerminalSettingId.ConfirmOnExit */
    ]: {
      description: localize(10696, null),
      type: "string",
      enum: ["never", "always", "hasChildProcesses"],
      enumDescriptions: [
        localize(10697, null),
        localize(10698, null),
        localize(10699, null)
      ],
      default: "never"
    },
    [
      "terminal.integrated.confirmOnKill"
      /* TerminalSettingId.ConfirmOnKill */
    ]: {
      description: localize(10700, null),
      type: "string",
      enum: ["never", "editor", "panel", "always"],
      enumDescriptions: [
        localize(10701, null),
        localize(10702, null),
        localize(10703, null),
        localize(10704, null)
      ],
      default: "editor"
    },
    [
      "terminal.integrated.enableBell"
      /* TerminalSettingId.EnableBell */
    ]: {
      markdownDeprecationMessage: localize(10705, null),
      type: "boolean",
      default: false
    },
    [
      "terminal.integrated.enableVisualBell"
      /* TerminalSettingId.EnableVisualBell */
    ]: {
      description: localize(10706, null),
      type: "boolean",
      default: false
    },
    [
      "terminal.integrated.commandsToSkipShell"
      /* TerminalSettingId.CommandsToSkipShell */
    ]: {
      markdownDescription: localize(10707, null, $kY.sort().map((command4) => `- ${command4}`).join("\n"), `[${localize(10708, null)}](command:workbench.action.openRawDefaultSettings '${localize(10709, null)}')`),
      type: "array",
      items: {
        type: "string"
      },
      default: []
    },
    [
      "terminal.integrated.allowChords"
      /* TerminalSettingId.AllowChords */
    ]: {
      markdownDescription: localize(10710, null, "`#terminal.integrated.commandsToSkipShell#`"),
      type: "boolean",
      default: true
    },
    [
      "terminal.integrated.allowMnemonics"
      /* TerminalSettingId.AllowMnemonics */
    ]: {
      markdownDescription: localize(10711, null),
      type: "boolean",
      default: false
    },
    [
      "terminal.integrated.env.osx"
      /* TerminalSettingId.EnvMacOs */
    ]: {
      restricted: true,
      markdownDescription: localize(10712, null),
      type: "object",
      additionalProperties: {
        type: ["string", "null"]
      },
      default: {}
    },
    [
      "terminal.integrated.env.linux"
      /* TerminalSettingId.EnvLinux */
    ]: {
      restricted: true,
      markdownDescription: localize(10713, null),
      type: "object",
      additionalProperties: {
        type: ["string", "null"]
      },
      default: {}
    },
    [
      "terminal.integrated.env.windows"
      /* TerminalSettingId.EnvWindows */
    ]: {
      restricted: true,
      markdownDescription: localize(10714, null),
      type: "object",
      additionalProperties: {
        type: ["string", "null"]
      },
      default: {}
    },
    [
      "terminal.integrated.environmentChangesIndicator"
      /* TerminalSettingId.EnvironmentChangesIndicator */
    ]: {
      markdownDescription: localize(10715, null),
      type: "string",
      enum: ["off", "on", "warnonly"],
      enumDescriptions: [
        localize(10716, null),
        localize(10717, null),
        localize(10718, null)
      ],
      default: "warnonly"
    },
    [
      "terminal.integrated.environmentChangesRelaunch"
      /* TerminalSettingId.EnvironmentChangesRelaunch */
    ]: {
      markdownDescription: localize(10719, null),
      type: "boolean",
      default: true
    },
    [
      "terminal.integrated.showExitAlert"
      /* TerminalSettingId.ShowExitAlert */
    ]: {
      description: localize(10720, null),
      type: "boolean",
      default: true
    },
    [
      "terminal.integrated.experimental.windowsUseConptyDll"
      /* TerminalSettingId.ExperimentalWindowsUseConptyDll */
    ]: {
      markdownDescription: localize(10721, null),
      type: "boolean",
      default: false
    },
    [
      "terminal.integrated.splitCwd"
      /* TerminalSettingId.SplitCwd */
    ]: {
      description: localize(10722, null),
      type: "string",
      enum: ["workspaceRoot", "initial", "inherited"],
      enumDescriptions: [
        localize(10723, null),
        localize(10724, null),
        localize(10725, null)
      ],
      default: "inherited"
    },
    [
      "terminal.integrated.windowsEnableConpty"
      /* TerminalSettingId.WindowsEnableConpty */
    ]: {
      description: localize(10726, null),
      type: "boolean",
      default: true
    },
    [
      "terminal.integrated.wordSeparators"
      /* TerminalSettingId.WordSeparators */
    ]: {
      markdownDescription: localize(10727, null),
      type: "string",
      // allow-any-unicode-next-line
      default: " ()[]{}',\"`\u2500\u2018\u2019\u201C\u201D|"
    },
    [
      "terminal.integrated.enableFileLinks"
      /* TerminalSettingId.EnableFileLinks */
    ]: {
      description: localize(10728, null),
      type: "string",
      enum: ["off", "on", "notRemote"],
      enumDescriptions: [
        localize(10729, null),
        localize(10730, null),
        localize(10731, null)
      ],
      default: "on"
    },
    [
      "terminal.integrated.allowedLinkSchemes"
      /* TerminalSettingId.AllowedLinkSchemes */
    ]: {
      description: localize(10732, null),
      type: "array",
      items: {
        type: "string"
      },
      default: [
        "file",
        "http",
        "https",
        "mailto",
        "vscode",
        "vscode-insiders"
      ]
    },
    [
      "terminal.integrated.unicodeVersion"
      /* TerminalSettingId.UnicodeVersion */
    ]: {
      type: "string",
      enum: ["6", "11"],
      enumDescriptions: [
        localize(10733, null),
        localize(10734, null)
      ],
      default: "11",
      description: localize(10735, null)
    },
    [
      "terminal.integrated.enablePersistentSessions"
      /* TerminalSettingId.EnablePersistentSessions */
    ]: {
      description: localize(10736, null),
      type: "boolean",
      default: true
    },
    [
      "terminal.integrated.persistentSessionReviveProcess"
      /* TerminalSettingId.PersistentSessionReviveProcess */
    ]: {
      markdownDescription: localize(10737, null),
      type: "string",
      enum: ["onExit", "onExitAndWindowClose", "never"],
      markdownEnumDescriptions: [
        localize(10738, null),
        localize(10739, null),
        localize(10740, null)
      ],
      default: "onExit"
    },
    [
      "terminal.integrated.hideOnStartup"
      /* TerminalSettingId.HideOnStartup */
    ]: {
      description: localize(10741, null),
      type: "string",
      enum: ["never", "whenEmpty", "always"],
      markdownEnumDescriptions: [
        localize(10742, null),
        localize(10743, null),
        localize(10744, null)
      ],
      default: "never"
    },
    [
      "terminal.integrated.customGlyphs"
      /* TerminalSettingId.CustomGlyphs */
    ]: {
      markdownDescription: localize(10745, null, `\`#${"terminal.integrated.gpuAcceleration"}#\``),
      type: "boolean",
      default: true
    },
    [
      "terminal.integrated.rescaleOverlappingGlyphs"
      /* TerminalSettingId.RescaleOverlappingGlyphs */
    ]: {
      markdownDescription: localize(10746, null),
      type: "boolean",
      default: true
    },
    [
      "terminal.integrated.shellIntegration.enabled"
      /* TerminalSettingId.ShellIntegrationEnabled */
    ]: {
      restricted: true,
      markdownDescription: localize(10747, null, "`#terminal.integrated.shellIntegration.decorationsEnabled#`", "`#editor.accessibilitySupport#`"),
      type: "boolean",
      default: true
    },
    [
      "terminal.integrated.shellIntegration.decorationsEnabled"
      /* TerminalSettingId.ShellIntegrationDecorationsEnabled */
    ]: {
      restricted: true,
      markdownDescription: localize(10748, null),
      type: "string",
      enum: ["both", "gutter", "overviewRuler", "never"],
      enumDescriptions: [
        localize(10749, null),
        localize(10750, null),
        localize(10751, null),
        localize(10752, null)
      ],
      default: "both"
    },
    [
      "terminal.integrated.smoothScrolling"
      /* TerminalSettingId.SmoothScrolling */
    ]: {
      markdownDescription: localize(10753, null),
      type: "boolean",
      default: false
    },
    [
      "terminal.integrated.ignoreBracketedPasteMode"
      /* TerminalSettingId.IgnoreBracketedPasteMode */
    ]: {
      markdownDescription: localize(10754, null, "`\\x1b[200~`", "`\\x1b[201~`"),
      type: "boolean",
      default: false
    },
    [
      "terminal.integrated.enableImages"
      /* TerminalSettingId.EnableImages */
    ]: {
      restricted: true,
      markdownDescription: localize(10755, null, `\`#${"terminal.integrated.gpuAcceleration"}#\``),
      type: "boolean",
      default: false
    },
    [
      "terminal.integrated.focusAfterRun"
      /* TerminalSettingId.FocusAfterRun */
    ]: {
      markdownDescription: localize(10756, null),
      enum: ["terminal", "accessible-buffer", "none"],
      default: "none",
      tags: ["accessibility"],
      markdownEnumDescriptions: [
        localize(10757, null),
        localize(10758, null),
        localize(10759, null)
      ]
    },
    ...$5X
  }
};
function $Ifc() {
  const configurationRegistry22 = $Wn.as($Ht.Configuration);
  configurationRegistry22.registerConfiguration(terminalConfiguration);
}
$Wn.as($YL.ConfigurationMigration).registerConfigurationMigrations([{
  key: "terminal.integrated.enableBell",
  migrateFn: (enableBell, accessor) => {
    const configurationKeyValuePairs = [];
    let announcement = accessor("accessibility.signals.terminalBell")?.announcement ?? accessor("accessibility.alert.terminalBell");
    if (announcement !== void 0 && typeof announcement !== "string") {
      announcement = announcement ? "auto" : "off";
    }
    configurationKeyValuePairs.push(["accessibility.signals.terminalBell", { value: { sound: enableBell ? "on" : "off", announcement } }]);
    configurationKeyValuePairs.push(["terminal.integrated.enableBell", { value: void 0 }]);
    configurationKeyValuePairs.push(["terminal.integrated.enableVisualBell", { value: enableBell }]);
    return configurationKeyValuePairs;
  }
}]);

// out-build/vs/workbench/contrib/terminal/browser/terminalKeybindings.js
function $Jfc(text2, rule) {
  $0I.registerCommandAndKeybindingRule({
    id: "workbench.action.terminal.sendSequence",
    weight: 200,
    when: rule.when || TerminalContextKeys.focus,
    primary: rule.primary,
    mac: rule.mac,
    linux: rule.linux,
    win: rule.win,
    handler: $Sec,
    args: { text: text2 }
  });
}

// out-build/vs/workbench/contrib/terminal/browser/terminal.contribution.js
$SC(
  $8x,
  $Fec,
  1
  /* InstantiationType.Delayed */
);
$SC(
  $5Pb,
  $4ec,
  1
  /* InstantiationType.Delayed */
);
$SC(
  $4Pb,
  $Gfc,
  1
  /* InstantiationType.Delayed */
);
$SC(
  $6Pb,
  $bfc,
  1
  /* InstantiationType.Delayed */
);
$SC(
  $7Pb,
  $jfc,
  1
  /* InstantiationType.Delayed */
);
$SC(
  $8Pb,
  $Afc,
  1
  /* InstantiationType.Delayed */
);
$SC(
  $hY,
  $Efc,
  1
  /* InstantiationType.Delayed */
);
$PL(
  $Bfc.ID,
  $Bfc,
  1
  /* WorkbenchPhase.BlockStartup */
);
$PL(
  $Jec.ID,
  $Jec,
  3
  /* WorkbenchPhase.AfterRestored */
);
$zB();
$Ifc();
$Wn.as($ZK.EditorFactory).registerEditorSerializer($fQb.ID, $9ec);
$Wn.as($ZK.EditorPane).registerEditorPane($7tb.create($8ec, $$Pb, $Kec.terminal), [
  new $Nk($fQb)
]);
$Wn.as($A_.DragAndDropContribution).register({
  dataFormatKey: "Terminals",
  getEditorInputs(data) {
    const editors = [];
    try {
      const terminalEditors = JSON.parse(data);
      for (const terminalEditor of terminalEditors) {
        editors.push({ resource: URI.parse(terminalEditor) });
      }
    } catch (error) {
    }
    return editors;
  },
  setData(resources, event) {
    const terminalResources = resources.filter(({ resource }) => resource.scheme === Schemas.vscodeTerminal);
    if (terminalResources.length) {
      event.dataTransfer?.setData("Terminals", JSON.stringify(terminalResources.map(({ resource }) => resource.toString())));
    }
  }
});
var VIEW_CONTAINER4 = $Wn.as(Extensions5.ViewContainersRegistry).registerViewContainer({
  id: $7X,
  title: localize2(10378, "Terminal"),
  icon: $KPb,
  ctorDescriptor: new $Nk($oqb, [$7X, { mergeViewWithContainerWhenSingleView: true }]),
  storageId: $7X,
  hideIfEmpty: true,
  order: 3
}, 1, { doNotRegisterOpenCommand: true, isDefault: true });
$Wn.as(Extensions5.ViewsRegistry).registerViews([{
  id: $7X,
  name: localize2(10379, "Terminal"),
  containerIcon: $KPb,
  canToggleVisibility: false,
  canMoveView: true,
  ctorDescriptor: new $Nk($ifc),
  openCommandActionDescriptor: {
    id: "workbench.action.terminal.toggleTerminal",
    mnemonicTitle: localize(10377, null),
    keybindings: {
      primary: 2048 | 91,
      mac: {
        primary: 256 | 91
        /* KeyCode.Backquote */
      }
    },
    order: 3
  }
}], VIEW_CONTAINER4);
$Yec();
var Constants17;
(function(Constants27) {
  Constants27[Constants27["CtrlLetterOffset"] = 64] = "CtrlLetterOffset";
})(Constants17 || (Constants17 = {}));
if ($l) {
  $Jfc(String.fromCharCode(
    "V".charCodeAt(0) - 64
    /* Constants.CtrlLetterOffset */
  ), {
    when: $7m.and(TerminalContextKeys.focus, $7m.equals(
      "terminalShellType",
      "pwsh"
      /* GeneralShellType.PowerShell */
    ), $OD.negate()),
    primary: 2048 | 52
    /* KeyCode.KeyV */
  });
}
$Jfc("\x1B[24~a", {
  when: $7m.and(TerminalContextKeys.focus, $7m.equals(
    "terminalShellType",
    "pwsh"
    /* GeneralShellType.PowerShell */
  ), TerminalContextKeys.terminalShellIntegrationEnabled, $OD.negate()),
  primary: 2048 | 10,
  mac: {
    primary: 256 | 10
    /* KeyCode.Space */
  }
});
$Jfc("\x1B[24~b", {
  when: $7m.and(TerminalContextKeys.focus, $7m.equals(
    "terminalShellType",
    "pwsh"
    /* GeneralShellType.PowerShell */
  ), TerminalContextKeys.terminalShellIntegrationEnabled, $OD.negate()),
  primary: 512 | 10
  /* KeyCode.Space */
});
$Jfc("\x1B[24~c", {
  when: $7m.and(TerminalContextKeys.focus, $7m.equals(
    "terminalShellType",
    "pwsh"
    /* GeneralShellType.PowerShell */
  ), TerminalContextKeys.terminalShellIntegrationEnabled, $OD.negate()),
  primary: 1024 | 3
  /* KeyCode.Enter */
});
$Jfc("\x1B[24~d", {
  when: $7m.and(TerminalContextKeys.focus, $7m.equals(
    "terminalShellType",
    "pwsh"
    /* GeneralShellType.PowerShell */
  ), TerminalContextKeys.terminalShellIntegrationEnabled, $OD.negate()),
  mac: {
    primary: 1024 | 2048 | 17
    /* KeyCode.RightArrow */
  }
});
$Jfc("\x1B[1;2H", {
  when: $7m.and(TerminalContextKeys.focus, $7m.equals(
    "terminalShellType",
    "pwsh"
    /* GeneralShellType.PowerShell */
  )),
  mac: {
    primary: 1024 | 2048 | 15
    /* KeyCode.LeftArrow */
  }
});
$Jfc("", {
  when: $7m.and(TerminalContextKeys.focus, $OD),
  primary: 2048 | 512 | 48,
  mac: {
    primary: 256 | 512 | 48
    /* KeyCode.KeyR */
  }
});
$Jfc("\x07", {
  when: TerminalContextKeys.focus,
  primary: 2048 | 512 | 37,
  mac: {
    primary: 256 | 512 | 37
    /* KeyCode.KeyG */
  }
});
if ($u) {
  $Jfc(String.fromCharCode(
    "C".charCodeAt(0) - 64
    /* Constants.CtrlLetterOffset */
  ), {
    when: $7m.and(TerminalContextKeys.focus),
    primary: 256 | 33
    /* KeyCode.KeyC */
  });
}
$Jfc(String.fromCharCode(
  "W".charCodeAt(0) - 64
  /* Constants.CtrlLetterOffset */
), {
  primary: 2048 | 1,
  mac: {
    primary: 512 | 1
    /* KeyCode.Backspace */
  }
});
if ($l) {
  $Jfc(String.fromCharCode(
    "H".charCodeAt(0) - 64
    /* Constants.CtrlLetterOffset */
  ), {
    when: $7m.and(TerminalContextKeys.focus, $7m.equals(
      "terminalShellType",
      "cmd"
      /* WindowsShellType.CommandPrompt */
    )),
    primary: 2048 | 1
  });
}
$Jfc("\x1Bd", {
  primary: 2048 | 20,
  mac: {
    primary: 512 | 20
    /* KeyCode.Delete */
  }
});
$Jfc("", {
  mac: {
    primary: 2048 | 1
    /* KeyCode.Backspace */
  }
});
$Jfc(String.fromCharCode("A".charCodeAt(0) - 64), {
  mac: {
    primary: 2048 | 15
    /* KeyCode.LeftArrow */
  }
});
$Jfc(String.fromCharCode("E".charCodeAt(0) - 64), {
  mac: {
    primary: 2048 | 17
    /* KeyCode.RightArrow */
  }
});
$Jfc("\0", {
  primary: 2048 | 1024 | 23,
  mac: {
    primary: 256 | 1024 | 23
    /* KeyCode.Digit2 */
  }
});
$Jfc("", {
  primary: 2048 | 1024 | 27,
  mac: {
    primary: 256 | 1024 | 27
    /* KeyCode.Digit6 */
  }
});
$Jfc("", {
  primary: 2048 | 90,
  mac: {
    primary: 256 | 90
    /* KeyCode.Slash */
  }
});
$3ec();
$6ec();
$vPb();

// out-build/vs/workbench/contrib/terminal/common/environmentVariableService.js
var $Kfc = class $Kfc2 extends $3c {
  get onDidChangeCollections() {
    return this.a.event;
  }
  constructor(b, f) {
    super();
    this.b = b;
    this.f = f;
    this.collections = /* @__PURE__ */ new Map();
    this.a = this.B(new $ze());
    this.f.remove(
      "terminal.integrated.environmentVariableCollections",
      1
      /* StorageScope.WORKSPACE */
    );
    const serializedPersistedCollections = this.f.get(
      "terminal.integrated.environmentVariableCollectionsV2",
      1
      /* StorageScope.WORKSPACE */
    );
    if (serializedPersistedCollections) {
      const collectionsJson = JSON.parse(serializedPersistedCollections);
      collectionsJson.forEach((c) => this.collections.set(c.extensionIdentifier, {
        persistent: true,
        map: $DB(c.collection),
        descriptionMap: $EB(c.description)
      }));
      this.t();
    }
    this.mergedCollection = this.s();
    this.B(this.b.onDidChangeExtensions(() => this.t()));
  }
  set(extensionIdentifier, collection) {
    this.collections.set(extensionIdentifier, collection);
    this.g();
  }
  delete(extensionIdentifier) {
    this.collections.delete(extensionIdentifier);
    this.g();
  }
  g() {
    this.h();
    this.mergedCollection = this.s();
    this.m();
  }
  h() {
    this.j();
  }
  j() {
    const collectionsJson = [];
    this.collections.forEach((collection, extensionIdentifier) => {
      if (collection.persistent) {
        collectionsJson.push({
          extensionIdentifier,
          collection: $BB(this.collections.get(extensionIdentifier).map),
          description: $CB(collection.descriptionMap)
        });
      }
    });
    const stringifiedJson = JSON.stringify(collectionsJson);
    this.f.store(
      "terminal.integrated.environmentVariableCollectionsV2",
      stringifiedJson,
      1,
      1
      /* StorageTarget.MACHINE */
    );
  }
  m() {
    this.n();
  }
  n() {
    this.a.fire(this.mergedCollection);
  }
  s() {
    return new $HB(this.collections);
  }
  async t() {
    await this.b.whenInstalledExtensionsRegistered();
    const registeredExtensions = this.b.extensions;
    let changes = false;
    this.collections.forEach((_, extensionIdentifier) => {
      const isExtensionRegistered = registeredExtensions.some((r2) => r2.identifier.value === extensionIdentifier);
      if (!isExtensionRegistered) {
        this.collections.delete(extensionIdentifier);
        changes = true;
      }
    });
    if (changes) {
      this.g();
    }
  }
};
__decorate([
  $_t(1e3)
], $Kfc.prototype, "h", null);
__decorate([
  $$t(1e3)
], $Kfc.prototype, "m", null);
$Kfc = __decorate([
  __param(0, $wN),
  __param(1, $jv)
], $Kfc);

// out-build/vs/workbench/contrib/terminal/common/environmentVariable.contribution.js
$SC(
  $NX,
  $Kfc,
  1
  /* InstantiationType.Delayed */
);

// out-build/vs/workbench/contrib/terminal/common/terminalExtensionPoints.contribution.js
$SC(
  $Cfc,
  $Dfc,
  1
  /* InstantiationType.Delayed */
);

// out-build/vs/workbench/contrib/terminalContrib/accessibility/browser/bufferContentTracker.js
var $Lfc = class $Lfc2 extends $3c {
  get lines() {
    return this.c;
  }
  constructor(f, g, h3) {
    super();
    this.f = f;
    this.g = g;
    this.h = h3;
    this.b = 0;
    this.c = [];
    this.bufferToEditorLineMapping = /* @__PURE__ */ new Map();
  }
  reset() {
    this.c = [];
    this.a = void 0;
    this.update();
  }
  update() {
    if (this.a?.isDisposed) {
      this.c = [];
      this.a = void 0;
    }
    this.m();
    this.j();
    this.n();
    this.a = this.B(this.f.raw.registerMarker());
    this.h.debug("Buffer content tracker: set ", this.c.length, " lines");
  }
  j() {
    const buffer = this.f.raw.buffer.active;
    const start = this.a?.line ? this.a.line - this.f.raw.rows + 1 : 0;
    const end = buffer.baseY;
    if (start < 0 || start > end) {
      return;
    }
    const scrollback = this.g.getValue(
      "terminal.integrated.scrollback"
      /* TerminalSettingId.Scrollback */
    );
    const maxBufferSize = scrollback + this.f.raw.rows - 1;
    const linesToAdd = end - start;
    if (linesToAdd + this.c.length > maxBufferSize) {
      const numToRemove = linesToAdd + this.c.length - maxBufferSize;
      for (let i2 = 0; i2 < numToRemove; i2++) {
        this.c.shift();
      }
      this.h.debug("Buffer content tracker: removed ", numToRemove, " lines from top of cached lines, now ", this.c.length, " lines");
    }
    const cachedLines = [];
    let currentLine = "";
    for (let i2 = start; i2 < end; i2++) {
      const line = buffer.getLine(i2);
      if (!line) {
        continue;
      }
      this.bufferToEditorLineMapping.set(i2, this.c.length + cachedLines.length);
      const isWrapped = buffer.getLine(i2 + 1)?.isWrapped;
      currentLine += line.translateToString(!isWrapped);
      if (currentLine && !isWrapped || i2 === buffer.baseY + this.f.raw.rows - 1) {
        if (line.length) {
          cachedLines.push(currentLine);
          currentLine = "";
        }
      }
    }
    this.h.debug("Buffer content tracker:", cachedLines.length, " lines cached");
    this.c.push(...cachedLines);
  }
  m() {
    if (!this.c.length) {
      return;
    }
    let linesToRemove = this.b;
    let index = 1;
    while (linesToRemove) {
      this.bufferToEditorLineMapping.forEach((value, key2) => {
        if (value === this.c.length - index) {
          this.bufferToEditorLineMapping.delete(key2);
        }
      });
      this.c.pop();
      index++;
      linesToRemove--;
    }
    this.h.debug("Buffer content tracker: removed lines from viewport, now ", this.c.length, " lines cached");
  }
  n() {
    const buffer = this.f.raw.buffer.active;
    this.b = 0;
    let currentLine = "";
    for (let i2 = buffer.baseY; i2 < buffer.baseY + this.f.raw.rows; i2++) {
      const line = buffer.getLine(i2);
      if (!line) {
        continue;
      }
      this.bufferToEditorLineMapping.set(i2, this.c.length);
      const isWrapped = buffer.getLine(i2 + 1)?.isWrapped;
      currentLine += line.translateToString(!isWrapped);
      if (currentLine && !isWrapped || i2 === buffer.baseY + this.f.raw.rows - 1) {
        if (currentLine.length) {
          this.b++;
          this.c.push(currentLine);
          currentLine = "";
        }
      }
    }
    this.h.debug("Viewport content update complete, ", this.c.length, " lines in the viewport");
  }
};
$Lfc = __decorate([
  __param(1, $kl),
  __param(2, $8x)
], $Lfc);

// out-build/vs/workbench/contrib/terminalContrib/accessibility/browser/terminalAccessibilityHelp.js
var ClassName2;
(function(ClassName3) {
  ClassName3["Active"] = "active";
  ClassName3["EditorTextArea"] = "textarea";
})(ClassName2 || (ClassName2 = {}));
var $Mfc = class $Mfc2 extends $3c {
  onClose() {
    const expr = $7m.and($osb, $7m.equals(
      $tsb.key,
      "terminal-help"
      /* AccessibleViewProviderId.TerminalHelp */
    ));
    if (expr?.evaluate(this.g.getContext(null))) {
      this.c.executeCommand(
        "workbench.action.terminal.focusAccessibleBuffer"
        /* TerminalAccessibilityCommandId.FocusAccessibleBuffer */
      );
    } else {
      this.b.focus();
    }
    this.dispose();
  }
  constructor(b, _xterm, c, f, g) {
    super();
    this.b = b;
    this.c = c;
    this.f = f;
    this.g = g;
    this.id = "terminal-help";
    this.a = false;
    this.options = {
      type: "help",
      readMoreUrl: "https://code.visualstudio.com/docs/editor/accessibility#_terminal-accessibility"
    };
    this.verbositySettingKey = "accessibility.verbosity.terminal";
    this.a = _xterm.shellIntegration.status === 2;
  }
  provideContent() {
    const content = [
      localize(
        10810,
        null,
        "workbench.action.terminal.focusAccessibleBuffer"
        /* TerminalAccessibilityCommandId.FocusAccessibleBuffer */
      ),
      localize(10811, null),
      localize(
        10812,
        null,
        "workbench.action.terminal.openDetectedLink"
        /* TerminalLinksCommandId.OpenDetectedLink */
      ),
      localize(
        10813,
        null,
        "workbench.action.terminal.newWithProfile"
        /* TerminalCommandId.NewWithProfile */
      ),
      localize(
        10814,
        null,
        "terminal.integrated.focusAfterRun"
        /* TerminalSettingId.FocusAfterRun */
      )
    ];
    if (!this.f.getValue(
      "terminal.integrated.accessibleViewFocusOnCommandExecution"
      /* TerminalAccessibilitySettingId.AccessibleViewFocusOnCommandExecution */
    )) {
      content.push(localize(10815, null));
    }
    if (this.b.shellType === "cmd") {
      content.push(localize(10816, null));
    }
    if (this.a) {
      content.push(localize(10817, null));
      content.push("- " + localize(
        10818,
        null,
        "workbench.action.terminal.accessibleBufferGoToNextCommand"
        /* TerminalAccessibilityCommandId.AccessibleBufferGoToNextCommand */
      ));
      content.push("- " + localize(
        10819,
        null,
        "workbench.action.terminal.accessibleBufferGoToPreviousCommand"
        /* TerminalAccessibilityCommandId.AccessibleBufferGoToPreviousCommand */
      ));
      content.push("- " + localize(
        10820,
        null,
        "editor.action.accessibleViewGoToSymbol"
        /* AccessibilityCommandId.GoToSymbol */
      ));
      content.push("- " + localize(
        10821,
        null,
        "workbench.action.terminal.runRecentCommand"
        /* TerminalHistoryCommandId.RunRecentCommand */
      ));
      content.push("- " + localize(
        10822,
        null,
        "workbench.action.terminal.goToRecentDirectory"
        /* TerminalHistoryCommandId.GoToRecentDirectory */
      ));
    } else {
      content.push(localize(10823, null));
    }
    return content.join("\n");
  }
};
$Mfc = __decorate([
  __param(2, $sn),
  __param(3, $kl),
  __param(4, $on)
], $Mfc);

// out-build/vs/workbench/contrib/terminalContrib/accessibility/browser/terminalAccessibleBufferProvider.js
var $Nfc = class $Nfc2 extends $3c {
  constructor(c, f, customHelp, configurationService, terminalService) {
    super();
    this.c = c;
    this.f = f;
    this.id = "terminal";
    this.options = {
      type: "view",
      language: "terminal",
      id: "terminal"
      /* AccessibleViewProviderId.Terminal */
    };
    this.verbositySettingKey = "accessibility.verbosity.terminal";
    this.b = new $ze();
    this.onDidRequestClearLastProvider = this.b.event;
    this.options.customHelp = customHelp;
    this.options.position = configurationService.getValue(
      "terminal.integrated.accessibleViewPreserveCursorPosition"
      /* TerminalAccessibilitySettingId.AccessibleViewPreserveCursorPosition */
    ) ? "initial-bottom" : "bottom";
    this.B(this.c.onDisposed(() => this.b.fire(
      "terminal"
      /* AccessibleViewProviderId.Terminal */
    )));
    this.B(configurationService.onDidChangeConfiguration((e) => {
      if (e.affectsConfiguration(
        "terminal.integrated.accessibleViewPreserveCursorPosition"
        /* TerminalAccessibilitySettingId.AccessibleViewPreserveCursorPosition */
      )) {
        this.options.position = configurationService.getValue(
          "terminal.integrated.accessibleViewPreserveCursorPosition"
          /* TerminalAccessibilitySettingId.AccessibleViewPreserveCursorPosition */
        ) ? "initial-bottom" : "bottom";
      }
    }));
    this.a = terminalService.activeInstance;
    this.B(terminalService.onDidChangeActiveInstance(() => {
      if (terminalService.activeInstance && this.a?.instanceId !== terminalService.activeInstance?.instanceId) {
        this.b.fire(
          "terminal"
          /* AccessibleViewProviderId.Terminal */
        );
        this.a = terminalService.activeInstance;
      }
    }));
  }
  onClose() {
    this.c.focus();
  }
  provideContent() {
    this.f.update();
    return this.f.lines.join("\n");
  }
  getSymbols() {
    const commands2 = this.g() ?? [];
    const symbols = [];
    for (const command4 of commands2) {
      const label3 = command4.command.command;
      if (label3) {
        symbols.push({
          label: label3,
          lineNumber: command4.lineNumber
        });
      }
    }
    return symbols;
  }
  g() {
    const capability = this.c.capabilities.get(
      2
      /* TerminalCapability.CommandDetection */
    );
    const commands2 = capability?.commands;
    const currentCommand = capability?.currentCommand;
    if (!commands2?.length) {
      return;
    }
    const result = [];
    for (const command4 of commands2) {
      const lineNumber = this.h(command4);
      if (lineNumber === void 0) {
        continue;
      }
      result.push({ command: command4, lineNumber, exitCode: command4.exitCode });
    }
    if (currentCommand) {
      const lineNumber = this.h(currentCommand);
      if (lineNumber !== void 0) {
        result.push({ command: currentCommand, lineNumber });
      }
    }
    return result;
  }
  h(command4) {
    let line;
    if ("marker" in command4) {
      line = command4.marker?.line;
    } else if ("commandStartMarker" in command4) {
      line = command4.commandStartMarker?.line;
    }
    if (line === void 0 || line < 0) {
      return;
    }
    line = this.f.bufferToEditorLineMapping.get(line);
    if (line === void 0) {
      return;
    }
    return line + 1;
  }
};
$Nfc = __decorate([
  __param(3, $kl),
  __param(4, $4Pb)
], $Nfc);

// out-build/vs/workbench/contrib/terminalContrib/accessibility/browser/textAreaSyncAddon.js
var $Ofc = class $Ofc2 extends $3c {
  activate(terminal2) {
    this.a = terminal2;
    this.j();
  }
  constructor(c, f, g, h3) {
    super();
    this.c = c;
    this.f = f;
    this.g = g;
    this.h = h3;
    this.b = this.B(new $4c());
    this.B(Event2.runAndSubscribe(Event2.any(this.c.onDidAddCapability, this.c.onDidRemoveCapability, this.f.onDidChangeScreenReaderOptimized), () => {
      this.j();
    }));
  }
  j() {
    const commandDetection = this.c.get(
      2
      /* TerminalCapability.CommandDetection */
    );
    if (this.m() && commandDetection) {
      if (!this.b.value) {
        const textarea = this.a?.textarea;
        if (textarea) {
          this.b.value = Event2.runAndSubscribe(commandDetection.promptInputModel.onDidChangeInput, () => this.n(textarea));
        }
      }
    } else {
      this.b.clear();
    }
  }
  m() {
    return this.f.isScreenReaderOptimized() || this.g.getValue(
      "terminal.integrated.developer.devMode"
      /* TerminalSettingId.DevMode */
    );
  }
  n(textArea) {
    const commandCapability = this.c.get(
      2
      /* TerminalCapability.CommandDetection */
    );
    if (!commandCapability) {
      return;
    }
    textArea.value = commandCapability.promptInputModel.value;
    textArea.selectionStart = commandCapability.promptInputModel.cursorIndex;
    textArea.selectionEnd = commandCapability.promptInputModel.cursorIndex;
    this.h.debug(`TextAreaSyncAddon#sync: text changed to "${textArea.value}"`);
  }
};
__decorate([
  $$t(50)
], $Ofc.prototype, "n", null);
$Ofc = __decorate([
  __param(1, $ND),
  __param(2, $kl),
  __param(3, $8x)
], $Ofc);

// out-build/vs/workbench/contrib/terminalContrib/accessibility/browser/terminal.accessibility.contribution.js
var TextAreaSyncContribution_1;
var $Pfc_1;
var TextAreaSyncContribution = class TextAreaSyncContribution2 extends $2c {
  static {
    TextAreaSyncContribution_1 = this;
  }
  static {
    this.ID = "terminal.textAreaSync";
  }
  static get(instance2) {
    return instance2.getContribution(TextAreaSyncContribution_1.ID);
  }
  constructor(j, m) {
    super();
    this.j = j;
    this.m = m;
  }
  layout(xterm) {
    if (this.h) {
      return;
    }
    this.h = this.add(this.m.createInstance($Ofc, this.j.instance.capabilities));
    xterm.raw.loadAddon(this.h);
    this.h.activate(xterm.raw);
  }
};
TextAreaSyncContribution = TextAreaSyncContribution_1 = __decorate([
  __param(1, $Pk)
], TextAreaSyncContribution);
$Y0b(TextAreaSyncContribution.ID, TextAreaSyncContribution);
var $Pfc = class $Pfc2 extends $3c {
  static {
    $Pfc_1 = this;
  }
  static {
    this.ID = "terminal.accessibleBufferProvider";
  }
  static get(instance2) {
    return instance2.getContribution($Pfc_1.ID);
  }
  constructor(m, n, r2, s, t, u, w) {
    super();
    this.m = m;
    this.n = n;
    this.r = r2;
    this.s = s;
    this.t = t;
    this.u = u;
    this.w = w;
    this.j = new $4c();
    this.B($vSb.addImplementation(90, "terminal", () => {
      if (this.w.activeInstance !== this.m.instance) {
        return false;
      }
      this.show();
      return true;
    }, TerminalContextKeys.focus));
    this.B(this.m.instance.onDidExecuteText(() => {
      const focusAfterRun = s.getValue(
        "terminal.integrated.focusAfterRun"
        /* TerminalSettingId.FocusAfterRun */
      );
      if (focusAfterRun === "terminal") {
        this.m.instance.focus(true);
      } else if (focusAfterRun === "accessible-buffer") {
        this.show();
      }
    }));
    this.B(this.s.onDidChangeConfiguration((e) => {
      if (e.affectsConfiguration(
        "terminal.integrated.accessibleViewFocusOnCommandExecution"
        /* TerminalAccessibilitySettingId.AccessibleViewFocusOnCommandExecution */
      )) {
        this.y();
      }
    }));
    this.B(this.m.instance.capabilities.onDidAddCapability((e) => {
      if (e.capability.type === 2) {
        this.y();
      }
    }));
  }
  xtermReady(xterm) {
    const addon = this.u.createInstance($Ofc, this.m.instance.capabilities);
    xterm.raw.loadAddon(addon);
    addon.activate(xterm.raw);
    this.h = xterm;
    this.B(this.h.raw.onWriteParsed(async () => {
      if (this.w.activeInstance !== this.m.instance) {
        return;
      }
      if (this.z() && this.h.raw.buffer.active.baseY === 0) {
        this.show();
      }
    }));
    const onRequestUpdateEditor = Event2.latch(this.h.raw.onScroll);
    this.B(onRequestUpdateEditor(() => {
      if (this.w.activeInstance !== this.m.instance) {
        return;
      }
      if (this.z()) {
        this.show();
      }
    }));
  }
  y() {
    if (!this.m.instance.capabilities.has(
      2
      /* TerminalCapability.CommandDetection */
    )) {
      return;
    }
    if (!this.s.getValue(
      "terminal.integrated.accessibleViewFocusOnCommandExecution"
      /* TerminalAccessibilitySettingId.AccessibleViewFocusOnCommandExecution */
    )) {
      this.j.clear();
      return;
    } else if (this.j.value) {
      return;
    }
    const capability = this.m.instance.capabilities.get(
      2
      /* TerminalCapability.CommandDetection */
    );
    this.j.value = this.B(capability.onCommandExecuted(() => {
      if (this.m.instance.hasFocus) {
        this.show();
      }
    }));
  }
  z() {
    return $tsb.getValue(this.t) === "terminal";
  }
  show() {
    if (!this.h) {
      return;
    }
    if (!this.f) {
      this.f = this.B(this.u.createInstance($Lfc, this.h));
    }
    if (!this.g) {
      this.g = this.B(this.u.createInstance($Nfc, this.m.instance, this.f, () => {
        return this.B(this.u.createInstance($Mfc, this.m.instance, this.h)).provideContent();
      }));
    }
    const position = this.s.getValue(
      "terminal.integrated.accessibleViewPreserveCursorPosition"
      /* TerminalAccessibilitySettingId.AccessibleViewPreserveCursorPosition */
    ) ? this.r.getPosition(
      "terminal"
      /* AccessibleViewProviderId.Terminal */
    ) : void 0;
    this.r.show(this.g, position);
  }
  navigateToCommand(type) {
    const currentLine = this.r.getPosition(
      "terminal"
      /* AccessibleViewProviderId.Terminal */
    )?.lineNumber;
    const commands2 = this.C();
    if (!commands2?.length || !currentLine) {
      return;
    }
    const filteredCommands = type === "previous" ? commands2.filter((c) => c.lineNumber < currentLine).sort((a, b) => b.lineNumber - a.lineNumber) : commands2.filter((c) => c.lineNumber > currentLine).sort((a, b) => a.lineNumber - b.lineNumber);
    if (!filteredCommands.length) {
      return;
    }
    const command4 = filteredCommands[0];
    const commandLine = command4.command.command;
    if (!$l && commandLine) {
      this.r.setPosition(new $8C(command4.lineNumber, 1), true);
      alert(commandLine);
    } else {
      this.r.setPosition(new $8C(command4.lineNumber, 1), true, true);
    }
    if (command4.exitCode) {
      this.n.playSignal($N9.terminalCommandFailed);
    } else {
      this.n.playSignal($N9.terminalCommandSucceeded);
    }
  }
  C() {
    const capability = this.m.instance.capabilities.get(
      2
      /* TerminalCapability.CommandDetection */
    );
    const commands2 = capability?.commands;
    const currentCommand = capability?.currentCommand;
    if (!commands2?.length) {
      return;
    }
    const result = [];
    for (const command4 of commands2) {
      const lineNumber = this.D(command4);
      if (!lineNumber) {
        continue;
      }
      result.push({ command: command4, lineNumber, exitCode: command4.exitCode });
    }
    if (currentCommand) {
      const lineNumber = this.D(currentCommand);
      if (!!lineNumber) {
        result.push({ command: currentCommand, lineNumber });
      }
    }
    return result;
  }
  D(command4) {
    if (!this.f) {
      return;
    }
    let line;
    if ("marker" in command4) {
      line = command4.marker?.line;
    } else if ("commandStartMarker" in command4) {
      line = command4.commandStartMarker?.line;
    }
    if (line === void 0 || line < 0) {
      return;
    }
    line = this.f.bufferToEditorLineMapping.get(line);
    if (line === void 0) {
      return;
    }
    return line + 1;
  }
};
$Pfc = $Pfc_1 = __decorate([
  __param(1, $I9),
  __param(2, $shb),
  __param(3, $kl),
  __param(4, $on),
  __param(5, $Pk),
  __param(6, $4Pb)
], $Pfc);
$Y0b($Pfc.ID, $Pfc);
var $Qfc = class extends $3c {
  constructor() {
    super();
    this.B($uSb.addImplementation(105, "terminal", async (accessor) => {
      const instantiationService = accessor.get($Pk);
      const terminalService = accessor.get($4Pb);
      const accessibleViewService = accessor.get($shb);
      const instance2 = await terminalService.getActiveOrCreateInstance();
      await terminalService.revealActiveTerminal();
      const terminal2 = instance2?.xterm;
      if (!terminal2) {
        return;
      }
      accessibleViewService.show(instantiationService.createInstance($Mfc, instance2, terminal2));
    }, $7m.or(TerminalContextKeys.focus, $7m.and($osb, $7m.equals(
      $tsb.key,
      "terminal"
      /* AccessibleViewProviderId.Terminal */
    )))));
  }
};
$Y0b($Qfc.ID, $Qfc);
var FocusAccessibleBufferAction = class extends $gJ {
  constructor() {
    super({
      id: "workbench.action.terminal.focusAccessibleBuffer",
      title: localize2(10805, "Focus Accessible Terminal View"),
      precondition: $7m.or(TerminalContextKeys.processSupported, TerminalContextKeys.terminalHasBeenCreated),
      keybinding: [
        {
          primary: 512 | 60,
          secondary: [
            2048 | 16
            /* KeyCode.UpArrow */
          ],
          linux: {
            primary: 512 | 60 | 1024,
            secondary: [
              2048 | 16
              /* KeyCode.UpArrow */
            ]
          },
          weight: 200,
          when: $7m.and($OD, TerminalContextKeys.focus)
        }
      ]
    });
  }
  async run(accessor, ...args2) {
    const terminalService = accessor.get($4Pb);
    const terminal2 = await terminalService.getActiveOrCreateInstance();
    if (!terminal2?.xterm) {
      return;
    }
    $Pfc.get(terminal2)?.show();
  }
};
$hJ(FocusAccessibleBufferAction);
$Uec({
  id: "workbench.action.terminal.accessibleBufferGoToNextCommand",
  title: localize2(10806, "Accessible Buffer Go to Next Command"),
  precondition: $7m.or(TerminalContextKeys.processSupported, TerminalContextKeys.terminalHasBeenCreated, $7m.and($osb, $7m.equals(
    $tsb.key,
    "terminal"
    /* AccessibleViewProviderId.Terminal */
  ))),
  keybinding: [
    {
      primary: 512 | 18,
      when: $7m.and($7m.and($osb, $7m.equals(
        $tsb.key,
        "terminal"
        /* AccessibleViewProviderId.Terminal */
      ))),
      weight: 200 + 2
    }
  ],
  run: async (c) => {
    const instance2 = c.service.activeInstance;
    if (!instance2) {
      return;
    }
    $Pfc.get(instance2)?.navigateToCommand(
      "next"
      /* NavigationType.Next */
    );
  }
});
$Uec({
  id: "workbench.action.terminal.accessibleBufferGoToPreviousCommand",
  title: localize2(10807, "Accessible Buffer Go to Previous Command"),
  precondition: $7m.and($7m.or(TerminalContextKeys.processSupported, TerminalContextKeys.terminalHasBeenCreated), $7m.and($osb, $7m.equals(
    $tsb.key,
    "terminal"
    /* AccessibleViewProviderId.Terminal */
  ))),
  keybinding: [
    {
      primary: 512 | 16,
      when: $7m.and($7m.and($osb, $7m.equals(
        $tsb.key,
        "terminal"
        /* AccessibleViewProviderId.Terminal */
      ))),
      weight: 200 + 2
    }
  ],
  run: async (c) => {
    const instance2 = c.service.activeInstance;
    if (!instance2) {
      return;
    }
    $Pfc.get(instance2)?.navigateToCommand(
      "previous"
      /* NavigationType.Previous */
    );
  }
});
$Uec({
  id: "workbench.action.terminal.scrollToBottomAccessibleView",
  title: localize2(10808, "Scroll to Accessible View Bottom"),
  precondition: $7m.and($7m.or(TerminalContextKeys.processSupported, TerminalContextKeys.terminalHasBeenCreated), $7m.and($osb, $7m.equals(
    $tsb.key,
    "terminal"
    /* AccessibleViewProviderId.Terminal */
  ))),
  keybinding: {
    primary: 2048 | 13,
    linux: {
      primary: 1024 | 13
      /* KeyCode.End */
    },
    when: $tsb.isEqualTo(
      "terminal"
      /* AccessibleViewProviderId.Terminal */
    ),
    weight: 200
    /* KeybindingWeight.WorkbenchContrib */
  },
  run: (c, accessor) => {
    const accessibleViewService = accessor.get($shb);
    const lastPosition = accessibleViewService.getLastPosition();
    if (!lastPosition) {
      return;
    }
    accessibleViewService.setPosition(lastPosition, true);
  }
});
$Uec({
  id: "workbench.action.terminal.scrollToTopAccessibleView",
  title: localize2(10809, "Scroll to Accessible View Top"),
  precondition: $7m.and($7m.or(TerminalContextKeys.processSupported, TerminalContextKeys.terminalHasBeenCreated), $7m.and($osb, $7m.equals(
    $tsb.key,
    "terminal"
    /* AccessibleViewProviderId.Terminal */
  ))),
  keybinding: {
    primary: 2048 | 14,
    linux: {
      primary: 1024 | 14
      /* KeyCode.Home */
    },
    when: $tsb.isEqualTo(
      "terminal"
      /* AccessibleViewProviderId.Terminal */
    ),
    weight: 200
    /* KeybindingWeight.WorkbenchContrib */
  },
  run: (c, accessor) => accessor.get($shb)?.setPosition(new $8C(1, 1), true)
});

// out-build/vs/workbench/contrib/terminalContrib/autoReplies/browser/terminal.autoReplies.contribution.js
var $Rfc = class $Rfc2 extends $3c {
  static {
    this.ID = "terminalAutoReplies";
  }
  constructor(a, terminalInstanceService) {
    super();
    this.a = a;
    for (const backend of terminalInstanceService.getRegisteredBackends()) {
      this.b(backend);
    }
    this.B(terminalInstanceService.onDidRegisterBackend(async (e) => this.b(e)));
  }
  b(backend) {
    const initialConfig = this.a.getValue($9X);
    for (const match of Object.keys(initialConfig.autoReplies)) {
      const reply = initialConfig.autoReplies[match];
      if (reply) {
        backend.installAutoReply(match, reply);
      }
    }
    this.B(this.a.onDidChangeConfiguration(async (e) => {
      if (e.affectsConfiguration(
        "terminal.integrated.autoReplies"
        /* TerminalAutoRepliesSettingId.AutoReplies */
      )) {
        backend.uninstallAllAutoReplies();
        const config = this.a.getValue($9X);
        for (const match of Object.keys(config.autoReplies)) {
          const reply = config.autoReplies[match];
          if (reply) {
            backend.installAutoReply(match, reply);
          }
        }
      }
    }));
  }
};
$Rfc = __decorate([
  __param(0, $kl),
  __param(1, $8Pb)
], $Rfc);
$PL(
  $Rfc.ID,
  $Rfc,
  3
  /* WorkbenchPhase.AfterRestored */
);

// out-build/vs/workbench/contrib/terminalContrib/developer/browser/terminal.developer.contribution.js
var DevModeContribution_1;
$Uec({
  id: "workbench.action.terminal.showTextureAtlas",
  title: localize2(10887, "Show Terminal Texture Atlas"),
  category: $qn.Developer,
  precondition: $7m.or(TerminalContextKeys.isOpen),
  run: async (c, accessor) => {
    const fileService = accessor.get($km);
    const openerService = accessor.get($O4);
    const workspaceContextService = accessor.get($Zk);
    const bitmap = await c.service.activeInstance?.xterm?.textureAtlas;
    if (!bitmap) {
      return;
    }
    const cwdUri = workspaceContextService.getWorkspace().folders[0].uri;
    const fileUri = URI.joinPath(cwdUri, "textureAtlas.png");
    const canvas = document.createElement("canvas");
    canvas.width = bitmap.width;
    canvas.height = bitmap.height;
    const ctx = canvas.getContext("bitmaprenderer");
    if (!ctx) {
      return;
    }
    ctx.transferFromImageBitmap(bitmap);
    const blob = await new Promise((res) => canvas.toBlob(res));
    if (!blob) {
      return;
    }
    await fileService.writeFile(fileUri, $Ci.wrap(new Uint8Array(await blob.arrayBuffer())));
    openerService.open(fileUri);
  }
});
$Uec({
  id: "workbench.action.terminal.writeDataToTerminal",
  title: localize2(10888, "Write Data to Terminal"),
  category: $qn.Developer,
  run: async (c, accessor) => {
    const quickInputService = accessor.get($1M);
    const instance2 = await c.service.getActiveOrCreateInstance();
    await c.service.revealActiveTerminal();
    await instance2.processReady;
    if (!instance2.xterm) {
      throw new Error("Cannot write data to terminal if xterm isn't initialized");
    }
    const data = await quickInputService.input({
      value: "",
      placeHolder: "Enter data, use \\x to escape",
      prompt: localize(10885, null)
    });
    if (!data) {
      return;
    }
    let escapedData = data.replace(/\\n/g, "\n").replace(/\\r/g, "\r");
    while (true) {
      const match = escapedData.match(/\\x([0-9a-fA-F]{2})/);
      if (match === null || match.index === void 0 || match.length < 2) {
        break;
      }
      escapedData = escapedData.slice(0, match.index) + String.fromCharCode(parseInt(match[1], 16)) + escapedData.slice(match.index + 4);
    }
    const xterm = instance2.xterm;
    xterm._writeText(escapedData);
  }
});
$Uec({
  id: "workbench.action.terminal.recordSession",
  title: localize2(10889, "Record Terminal Session"),
  category: $qn.Developer,
  run: async (c, accessor) => {
    const clipboardService = accessor.get($30);
    const commandService = accessor.get($sn);
    const statusbarService = accessor.get($$qb);
    const store = new $2c();
    const text2 = localize(10886, null);
    const statusbarEntry = {
      text: text2,
      name: text2,
      ariaLabel: text2,
      showProgress: true
    };
    const statusbarHandle = statusbarService.addEntry(
      statusbarEntry,
      "recordSession",
      0
      /* StatusbarAlignment.LEFT */
    );
    store.add(statusbarHandle);
    const instance2 = await c.service.createTerminal();
    c.service.setActiveInstance(instance2);
    await c.service.revealActiveTerminal();
    await Promise.all([
      instance2.processReady,
      instance2.focusWhenReady(true)
    ]);
    return new Promise((resolve) => {
      const events = [];
      const endRecording = () => {
        const session = JSON.stringify(events, null, 2);
        clipboardService.writeText(session);
        store.dispose();
        resolve();
      };
      const timer = store.add(new $Sh(5e3));
      store.add(Event2.runAndSubscribe(instance2.onDimensionsChanged, () => {
        events.push({
          type: "resize",
          cols: instance2.cols,
          rows: instance2.rows
        });
        timer.trigger(endRecording);
      }));
      store.add(commandService.onWillExecuteCommand((e) => {
        events.push({
          type: "command",
          id: e.commandId
        });
        timer.trigger(endRecording);
      }));
      store.add(instance2.onWillData((data) => {
        events.push({
          type: "output",
          data
        });
        timer.trigger(endRecording);
      }));
      store.add(instance2.onDidSendText((data) => {
        events.push({
          type: "sendText",
          data
        });
        timer.trigger(endRecording);
      }));
      store.add(instance2.xterm.raw.onData((data) => {
        events.push({
          type: "input",
          data
        });
        timer.trigger(endRecording);
      }));
      let commandDetectedRegistered = false;
      store.add(Event2.runAndSubscribe(instance2.capabilities.onDidAddCapability, (e) => {
        if (commandDetectedRegistered) {
          return;
        }
        const commandDetection = instance2.capabilities.get(
          2
          /* TerminalCapability.CommandDetection */
        );
        if (!commandDetection) {
          return;
        }
        store.add(commandDetection.promptInputModel.onDidChangeInput((e2) => {
          events.push({
            type: "promptInputChange",
            data: commandDetection.promptInputModel.getCombinedString()
          });
          timer.trigger(endRecording);
        }));
        commandDetectedRegistered = true;
      }));
    });
  }
});
$Uec({
  id: "workbench.action.terminal.restartPtyHost",
  title: localize2(10890, "Restart Pty Host"),
  category: $qn.Developer,
  run: async (c, accessor) => {
    const logService = accessor.get($8x);
    const backends = Array.from(c.instanceService.getRegisteredBackends());
    const unresponsiveBackends = backends.filter((e) => !e.isResponsive);
    const restartCandidates = unresponsiveBackends.length > 0 ? unresponsiveBackends : backends;
    for (const backend of restartCandidates) {
      logService.warn(`Restarting pty host for authority "${backend.remoteAuthority}"`);
      backend.restartPtyHost();
    }
  }
});
var DevModeContributionState;
(function(DevModeContributionState2) {
  DevModeContributionState2[DevModeContributionState2["Off"] = 0] = "Off";
  DevModeContributionState2[DevModeContributionState2["WaitingForCapability"] = 1] = "WaitingForCapability";
  DevModeContributionState2[DevModeContributionState2["On"] = 2] = "On";
})(DevModeContributionState || (DevModeContributionState = {}));
var DevModeContribution = class DevModeContribution2 extends $3c {
  static {
    DevModeContribution_1 = this;
  }
  static {
    this.ID = "terminal.devMode";
  }
  static get(instance2) {
    return instance2.getContribution(DevModeContribution_1.ID);
  }
  constructor(h3, j) {
    super();
    this.h = h3;
    this.j = j;
    this.b = new $4c();
    this.f = 0;
    this.g = 0;
    this.B(this.j.onDidChangeConfiguration((e) => {
      if (e.affectsConfiguration(
        "terminal.integrated.developer.devMode"
        /* TerminalSettingId.DevMode */
      )) {
        this.m();
      }
    }));
  }
  xtermReady(xterm) {
    this.a = xterm;
    this.m();
  }
  m() {
    const devMode = this.n();
    this.a?.raw.element?.classList.toggle("dev-mode", devMode);
    const commandDetection = this.h.instance.capabilities.get(
      2
      /* TerminalCapability.CommandDetection */
    );
    if (devMode) {
      if (commandDetection) {
        if (this.g === 2) {
          return;
        }
        this.g = 2;
        const commandDecorations = new $_c();
        const otherDisposables = new $2c();
        this.b.value = $Zc(
          commandDecorations,
          otherDisposables,
          // Prompt input
          this.h.instance.onDidBlur(() => this.m()),
          this.h.instance.onDidFocus(() => this.m()),
          commandDetection.promptInputModel.onDidChangeInput(() => this.m()),
          // Sequence markers
          commandDetection.onCommandFinished((command4) => {
            const colorClass = `color-${this.f}`;
            const decorations = [];
            commandDecorations.set(command4, $Zc(...decorations));
            if (command4.promptStartMarker) {
              const d = this.h.instance.xterm.raw?.registerDecoration({
                marker: command4.promptStartMarker
              });
              if (d) {
                decorations.push(d);
                otherDisposables.add(d.onRender((e) => {
                  e.textContent = "A";
                  e.classList.add("xterm-sequence-decoration", "top", "left", colorClass);
                }));
              }
            }
            if (command4.marker) {
              const d = this.h.instance.xterm.raw?.registerDecoration({
                marker: command4.marker,
                x: command4.startX
              });
              if (d) {
                decorations.push(d);
                otherDisposables.add(d.onRender((e) => {
                  e.textContent = "B";
                  e.classList.add("xterm-sequence-decoration", "top", "right", colorClass);
                }));
              }
            }
            if (command4.executedMarker) {
              const d = this.h.instance.xterm.raw?.registerDecoration({
                marker: command4.executedMarker,
                x: command4.executedX
              });
              if (d) {
                decorations.push(d);
                otherDisposables.add(d.onRender((e) => {
                  e.textContent = "C";
                  e.classList.add("xterm-sequence-decoration", "bottom", "left", colorClass);
                }));
              }
            }
            if (command4.endMarker) {
              const d = this.h.instance.xterm.raw?.registerDecoration({
                marker: command4.endMarker
              });
              if (d) {
                decorations.push(d);
                otherDisposables.add(d.onRender((e) => {
                  e.textContent = "D";
                  e.classList.add("xterm-sequence-decoration", "bottom", "right", colorClass);
                }));
              }
            }
            this.f = (this.f + 1) % 2;
          }),
          commandDetection.onCommandInvalidated((commands2) => {
            for (const c of commands2) {
              const decorations = commandDecorations.get(c);
              if (decorations) {
                $Xc(decorations);
              }
              commandDecorations.deleteAndDispose(c);
            }
          })
        );
      } else {
        if (this.g === 1) {
          return;
        }
        this.g = 1;
        this.b.value = this.h.instance.capabilities.onDidAddCapabilityType((e) => {
          if (e === 2) {
            this.m();
          }
        });
      }
    } else {
      if (this.g === 0) {
        return;
      }
      this.g = 0;
      this.b.clear();
    }
  }
  n() {
    return this.j.getValue(
      "terminal.integrated.developer.devMode"
      /* TerminalSettingId.DevMode */
    ) || false;
  }
};
DevModeContribution = DevModeContribution_1 = __decorate([
  __param(1, $kl)
], DevModeContribution);
$Y0b(DevModeContribution.ID, DevModeContribution);

// out-build/vs/workbench/contrib/terminalContrib/environmentChanges/browser/terminal.environmentChanges.contribution.js
var EnvironmentCollectionProvider_1;
$Wec({
  id: "workbench.action.terminal.showEnvironmentContributions",
  title: localize2(10894, "Show Environment Contributions"),
  run: async (activeInstance, c, accessor, arg) => {
    const collection = activeInstance.extEnvironmentVariableCollection;
    if (collection) {
      const scope = arg;
      const instantiationService = accessor.get($Pk);
      const outputProvider = instantiationService.createInstance(EnvironmentCollectionProvider);
      const editorService = accessor.get($mJ);
      const timestamp = (/* @__PURE__ */ new Date()).getTime();
      const scopeDesc = scope?.workspaceFolder ? ` - ${scope.workspaceFolder.name}` : "";
      const textContent = await outputProvider.provideTextContent(URI.from({
        scheme: EnvironmentCollectionProvider.scheme,
        path: `Environment changes${scopeDesc}`,
        fragment: describeEnvironmentChanges(collection, scope),
        query: `environment-collection-${timestamp}`
      }));
      if (textContent) {
        await editorService.openEditor({
          resource: textContent.uri
        });
      }
    }
  }
});
function describeEnvironmentChanges(collection, scope) {
  let content = `# ${localize(10891, null)}`;
  const globalDescriptions = collection.getDescriptionMap(void 0);
  const workspaceDescriptions = collection.getDescriptionMap(scope);
  for (const [ext, coll] of collection.collections) {
    content += `

## ${localize(10892, null, ext)}`;
    content += "\n";
    const globalDescription = globalDescriptions.get(ext);
    if (globalDescription) {
      content += `
${globalDescription}
`;
    }
    const workspaceDescription = workspaceDescriptions.get(ext);
    if (workspaceDescription) {
      const workspaceSuffix = globalDescription ? ` (${localize(10893, null)})` : "";
      content += `
${workspaceDescription}${workspaceSuffix}
`;
    }
    for (const mutator of coll.map.values()) {
      if (filterScope2(mutator, scope) === false) {
        continue;
      }
      content += `
- \`${mutatorTypeLabel(mutator.type, mutator.value, mutator.variable)}\``;
    }
  }
  return content;
}
function filterScope2(mutator, scope) {
  if (!mutator.scope) {
    return true;
  }
  if (mutator.scope.workspaceFolder && scope?.workspaceFolder && mutator.scope.workspaceFolder.index === scope.workspaceFolder.index) {
    return true;
  }
  return false;
}
function mutatorTypeLabel(type, value, variable) {
  switch (type) {
    case EnvironmentVariableMutatorType2.Prepend:
      return `${variable}=${value}\${env:${variable}}`;
    case EnvironmentVariableMutatorType2.Append:
      return `${variable}=\${env:${variable}}${value}`;
    default:
      return `${variable}=${value}`;
  }
}
var EnvironmentCollectionProvider = class EnvironmentCollectionProvider2 {
  static {
    EnvironmentCollectionProvider_1 = this;
  }
  static {
    this.scheme = "ENVIRONMENT_CHANGES_COLLECTION";
  }
  constructor(textModelResolverService, a) {
    this.a = a;
    textModelResolverService.registerTextModelContentProvider(EnvironmentCollectionProvider_1.scheme, this);
  }
  async provideTextContent(resource) {
    const existing = this.a.getModel(resource);
    if (existing && !existing.isDisposed()) {
      return existing;
    }
    return this.a.createModel(resource.fragment, { languageId: "markdown", onDidChange: Event2.None }, resource, false);
  }
};
EnvironmentCollectionProvider = EnvironmentCollectionProvider_1 = __decorate([
  __param(0, $oG),
  __param(1, $sG)
], EnvironmentCollectionProvider);

// out-build/vs/workbench/contrib/codeEditor/browser/find/simpleFindWidget.js
var NLS_FIND_INPUT_LABEL3 = localize(5190, null);
var NLS_FIND_INPUT_PLACEHOLDER3 = localize(5191, null);
var NLS_PREVIOUS_MATCH_BTN_LABEL3 = localize(5192, null);
var NLS_NEXT_MATCH_BTN_LABEL3 = localize(5193, null);
var NLS_CLOSE_BTN_LABEL3 = localize(5194, null);
var SIMPLE_FIND_WIDGET_INITIAL_WIDTH = 310;
var MATCHES_COUNT_WIDTH = 73;
var $Sfc = class extends $qZ {
  constructor(options3, contextViewService, contextKeyService, hoverService, M) {
    super();
    this.M = M;
    this.I = false;
    this.J = false;
    this.L = 0;
    this.state = new $1fb();
    this.y = options3.matchesLimit ?? Number.MAX_SAFE_INTEGER;
    this.a = this.B(new $0bb(null, contextViewService, {
      label: NLS_FIND_INPUT_LABEL3,
      placeholder: NLS_FIND_INPUT_PLACEHOLDER3,
      validation: (value) => {
        if (value.length === 0 || !this.a.getRegex()) {
          return null;
        }
        try {
          new RegExp(value);
          return null;
        } catch (e) {
          this.J = false;
          this.bb(this.J);
          return { content: e.message };
        }
      },
      showCommonFindToggles: options3.showCommonFindToggles,
      appendCaseSensitiveLabel: options3.appendCaseSensitiveActionId ? this.W(options3.appendCaseSensitiveActionId) : void 0,
      appendRegexLabel: options3.appendRegexActionId ? this.W(options3.appendRegexActionId) : void 0,
      appendWholeWordsLabel: options3.appendWholeWordsActionId ? this.W(options3.appendWholeWordsActionId) : void 0,
      showHistoryHint: () => $ggb(M),
      inputBoxStyles: $B$,
      toggleStyles: $u$
    }, contextKeyService));
    this.r = this.B(new $Sh(500));
    this.B(this.a.onInput(async (e) => {
      if (!options3.checkImeCompletionState || !this.a.isImeSessionInProgress) {
        this.J = this.N();
        if (options3.showResultCount) {
          await this.updateResultCount();
        }
        this.bb(this.J);
        this.cb();
        this.X();
      }
    }));
    this.a.setRegex(!!this.state.isRegex);
    this.a.setCaseSensitive(!!this.state.matchCase);
    this.a.setWholeWords(!!this.state.wholeWord);
    this.B(this.a.onDidOptionChange(() => {
      this.state.change({
        isRegex: this.a.getRegex(),
        wholeWord: this.a.getWholeWords(),
        matchCase: this.a.getCaseSensitive()
      }, true);
    }));
    this.B(this.state.onFindReplaceStateChange(() => {
      this.a.setRegex(this.state.isRegex);
      this.a.setWholeWords(this.state.wholeWord);
      this.a.setCaseSensitive(this.state.matchCase);
      this.findFirst();
    }));
    this.t = this.B(new $qgb({
      label: NLS_PREVIOUS_MATCH_BTN_LABEL3 + (options3.previousMatchActionId ? this.W(options3.previousMatchActionId) : ""),
      icon: $kgb,
      onTrigger: () => {
        this.find(true);
      }
    }, hoverService));
    this.w = this.B(new $qgb({
      label: NLS_NEXT_MATCH_BTN_LABEL3 + (options3.nextMatchActionId ? this.W(options3.nextMatchActionId) : ""),
      icon: $lgb,
      onTrigger: () => {
        this.find(false);
      }
    }, hoverService));
    const closeBtn = this.B(new $qgb({
      label: NLS_CLOSE_BTN_LABEL3 + (options3.closeWidgetActionId ? this.W(options3.closeWidgetActionId) : ""),
      icon: $_r,
      onTrigger: () => {
        this.hide();
      }
    }, hoverService));
    this.g = document.createElement("div");
    this.g.classList.add("simple-find-part");
    this.g.appendChild(this.a.domNode);
    this.g.appendChild(this.t.domNode);
    this.g.appendChild(this.w.domNode);
    this.g.appendChild(closeBtn.domNode);
    this.c = document.createElement("div");
    this.c.classList.add("simple-find-part-wrapper");
    this.c.appendChild(this.g);
    this.u(this.g, (e) => {
      if (e.equals(
        9
        /* KeyCode.Escape */
      )) {
        this.hide();
        e.preventDefault();
        return;
      }
    });
    this.h = this.B($_j(this.g));
    this.B(this.h.onDidFocus(this.O.bind(this)));
    this.B(this.h.onDidBlur(this.P.bind(this)));
    this.n = this.B($_j(this.a.domNode));
    this.B(this.n.onDidFocus(this.Q.bind(this)));
    this.B(this.n.onDidBlur(this.R.bind(this)));
    this.B($_i(this.g, "click", (event) => {
      event.stopPropagation();
    }));
    if (options3?.showResultCount) {
      this.c.classList.add("result-count");
      this.H = document.createElement("div");
      this.H.className = "matchesCount";
      this.a.domNode.insertAdjacentElement("afterend", this.H);
      this.B(this.a.onDidChange(async () => {
        await this.updateResultCount();
      }));
      this.B(this.a.onDidOptionChange(async () => {
        this.J = this.N();
        await this.updateResultCount();
        this.cb();
        this.X();
      }));
    }
    let initialMinWidth = options3?.initialWidth;
    if (initialMinWidth) {
      initialMinWidth = initialMinWidth < SIMPLE_FIND_WIDGET_INITIAL_WIDTH ? SIMPLE_FIND_WIDGET_INITIAL_WIDTH : initialMinWidth;
      this.c.style.width = `${initialMinWidth}px`;
    }
    if (options3?.enableSash) {
      const _initialMinWidth = initialMinWidth ?? SIMPLE_FIND_WIDGET_INITIAL_WIDTH;
      let originalWidth = _initialMinWidth;
      const resizeSash = this.B(new $q2(this.g, this, { orientation: 0, size: 1 }));
      this.B(resizeSash.onDidStart(() => {
        originalWidth = parseFloat($pj(this.c).width);
      }));
      this.B(resizeSash.onDidChange((e) => {
        const width2 = originalWidth + e.startX - e.currentX;
        if (width2 < _initialMinWidth) {
          return;
        }
        this.c.style.width = `${width2}px`;
      }));
      this.B(resizeSash.onDidReset((e) => {
        const currentWidth = parseFloat($pj(this.c).width);
        if (currentWidth === _initialMinWidth) {
          this.c.style.width = "100%";
        } else {
          this.c.style.width = `${_initialMinWidth}px`;
        }
      }));
    }
  }
  getVerticalSashLeft(_sash) {
    return 0;
  }
  get U() {
    return this.a.getValue();
  }
  get focusTracker() {
    return this.h;
  }
  W(actionId) {
    const kb = this.M?.lookupKeybinding(actionId);
    if (!kb) {
      return "";
    }
    return ` (${kb.getLabel()})`;
  }
  dispose() {
    super.dispose();
    this.c?.remove();
  }
  isVisible() {
    return this.I;
  }
  getDomNode() {
    return this.c;
  }
  getFindInputDomNode() {
    return this.a.domNode;
  }
  reveal(initialInput, animated = true) {
    if (initialInput) {
      this.a.setValue(initialInput);
    }
    if (this.I) {
      this.a.select();
      return;
    }
    this.I = true;
    this.updateResultCount();
    this.layout();
    setTimeout(() => {
      this.g.classList.toggle("suppress-transition", !animated);
      this.g.classList.add("visible", "visible-transition");
      this.g.setAttribute("aria-hidden", "false");
      this.a.select();
      if (!animated) {
        setTimeout(() => {
          this.g.classList.remove("suppress-transition");
        }, 0);
      }
    }, 0);
  }
  show(initialInput) {
    if (initialInput && !this.I) {
      this.a.setValue(initialInput);
    }
    this.I = true;
    this.layout();
    setTimeout(() => {
      this.g.classList.add("visible", "visible-transition");
      this.g.setAttribute("aria-hidden", "false");
    }, 0);
  }
  hide(animated = true) {
    if (this.I) {
      this.g.classList.toggle("suppress-transition", !animated);
      this.g.classList.remove("visible-transition");
      this.g.setAttribute("aria-hidden", "true");
      setTimeout(() => {
        this.I = false;
        this.bb(this.J);
        this.g.classList.remove("visible", "suppress-transition");
      }, animated ? 200 : 0);
    }
  }
  layout(width2 = this.L) {
    this.L = width2;
    if (!this.I) {
      return;
    }
    if (this.H) {
      let reducedFindWidget = false;
      if (SIMPLE_FIND_WIDGET_INITIAL_WIDTH + MATCHES_COUNT_WIDTH + 28 >= width2) {
        reducedFindWidget = true;
      }
      this.g.classList.toggle("reduced-find-widget", reducedFindWidget);
    }
  }
  X() {
    this.r.trigger(this.Y.bind(this));
  }
  Y() {
    this.a.inputBox.addToHistory();
  }
  Z() {
    return this.a.getRegex();
  }
  $() {
    return this.a.getWholeWords();
  }
  ab() {
    return this.a.getCaseSensitive();
  }
  bb(foundMatch) {
    const hasInput = this.U.length > 0;
    this.t.setEnabled(this.I && hasInput && foundMatch);
    this.w.setEnabled(this.I && hasInput && foundMatch);
  }
  cb() {
    this.w.focus();
    this.a.inputBox.focus();
  }
  async updateResultCount() {
    if (!this.H) {
      this.bb(this.J);
      return;
    }
    const count = await this.S();
    this.H.innerText = "";
    const showRedOutline = this.U.length > 0 && count?.resultCount === 0;
    this.H.classList.toggle("no-results", showRedOutline);
    let label3 = "";
    if (count?.resultCount) {
      let matchesCount = String(count.resultCount);
      if (count.resultCount >= this.y) {
        matchesCount += "+";
      }
      let matchesPosition = String(count.resultIndex + 1);
      if (matchesPosition === "0") {
        matchesPosition = "?";
      }
      label3 = $wf($mgb, matchesPosition, matchesCount);
    } else {
      label3 = $ngb;
    }
    $_Z(this.db(label3, this.U));
    this.H.appendChild(document.createTextNode(label3));
    this.J = !!count && count.resultCount > 0;
    this.bb(this.J);
  }
  changeState(state) {
    this.state.change(state, false);
  }
  db(label3, searchString) {
    if (!searchString) {
      return localize(5195, null);
    }
    if (label3 === $ngb) {
      return searchString === "" ? localize(5196, null, label3) : localize(5197, null, label3, searchString);
    }
    return localize(5198, null, label3, searchString);
  }
};
var $Tfc = $5n("simpleFindWidget.sashBorder", { dark: "#454545", light: "#C8C8C8", hcDark: "#6FC3DF", hcLight: "#0F4A85" }, localize(5199, null));
$ms((theme, collector) => {
  const resizeBorderBackground = theme.getColor($Tfc);
  collector.addRule(`.monaco-workbench .simple-find-part .monaco-sash { background-color: ${resizeBorderBackground}; border-color: ${resizeBorderBackground} }`);
});

// out-build/vs/workbench/contrib/terminalContrib/find/browser/textInputContextMenu.js
function $Ufc(targetWindow, event, clipboardService, contextMenuService) {
  const standardEvent = new $lf(targetWindow, event);
  const actions = [];
  actions.push(
    // Undo/Redo
    new $Um("undo", localize(10903, null), void 0, true, async () => $Qj().document.execCommand("undo")),
    new $Um("redo", localize(10904, null), void 0, true, async () => $Qj().document.execCommand("redo")),
    new $Wm(),
    // Cut / Copy / Paste
    new $Um("editor.action.clipboardCutAction", localize(10905, null), void 0, true, async () => $Qj().document.execCommand("cut")),
    new $Um("editor.action.clipboardCopyAction", localize(10906, null), void 0, true, async () => $Qj().document.execCommand("copy")),
    new $Um("editor.action.clipboardPasteAction", localize(10907, null), void 0, true, async (element) => {
      if ($p) {
        $Qj().document.execCommand("paste");
      } else {
        const clipboardText = await clipboardService.readText();
        if ($Xj(element) || $Yj(element)) {
          const selectionStart = element.selectionStart || 0;
          const selectionEnd = element.selectionEnd || 0;
          element.value = `${element.value.substring(0, selectionStart)}${clipboardText}${element.value.substring(selectionEnd, element.value.length)}`;
          element.selectionStart = selectionStart + clipboardText.length;
          element.selectionEnd = element.selectionStart;
        }
      }
    }),
    new $Wm(),
    // Select All
    new $Um("editor.action.selectAll", localize(10908, null), void 0, true, async () => $Qj().document.execCommand("selectAll"))
  );
  contextMenuService.showContextMenu({
    getAnchor: () => standardEvent,
    getActions: () => actions,
    getActionsContext: () => event.target
  });
}

// out-build/vs/workbench/contrib/terminalContrib/clipboard/browser/terminalClipboard.js
async function $Vfc(accessor, text2, bracketedPasteMode) {
  const configurationService = accessor.get($kl);
  const dialogService = accessor.get($Yv);
  const textForLines = text2.split(/\r?\n/);
  if (textForLines.length === 1) {
    return true;
  }
  function parseConfigValue(value) {
    if (typeof value === "string") {
      if (value === "auto" || value === "always" || value === "never") {
        return value;
      }
    }
    if (typeof value === "boolean") {
      return value ? "auto" : "never";
    }
    return "auto";
  }
  const configValue = parseConfigValue(configurationService.getValue(
    "terminal.integrated.enableMultiLinePasteWarning"
    /* TerminalSettingId.EnableMultiLinePasteWarning */
  ));
  if (configValue === "never") {
    return true;
  }
  if (configValue === "auto") {
    if (bracketedPasteMode) {
      return true;
    }
    const textForLines2 = text2.split(/\r?\n/);
    if (textForLines2.length === 2 && textForLines2[1].trim().length === 0) {
      return true;
    }
  }
  const displayItemsCount = 3;
  const maxPreviewLineLength = 30;
  let detail2 = localize(10878, null);
  for (let i2 = 0; i2 < Math.min(textForLines.length, displayItemsCount); i2++) {
    const line = textForLines[i2];
    const cleanedLine = line.length > maxPreviewLineLength ? `${line.slice(0, maxPreviewLineLength)}\u2026` : line;
    detail2 += `
${cleanedLine}`;
  }
  if (textForLines.length > displayItemsCount) {
    detail2 += `
\u2026`;
  }
  const { result, checkboxChecked } = await dialogService.prompt({
    message: localize(10879, null, textForLines.length),
    detail: detail2,
    type: "warning",
    buttons: [
      {
        label: localize(10880, null),
        run: () => ({ confirmed: true, singleLine: false })
      },
      {
        label: localize(10881, null),
        run: () => ({ confirmed: true, singleLine: true })
      }
    ],
    cancelButton: true,
    checkbox: {
      label: localize(10882, null)
    }
  });
  if (!result) {
    return false;
  }
  if (result.confirmed && checkboxChecked) {
    await configurationService.updateValue("terminal.integrated.enableMultiLinePasteWarning", false);
  }
  if (result.singleLine) {
    return { modifiedText: text2.replace(/\r?\n/g, "") };
  }
  return result.confirmed;
}

// out-build/vs/workbench/contrib/terminalContrib/clipboard/browser/terminal.clipboard.contribution.js
var $Wfc_1;
var $Wfc = class $Wfc2 extends $3c {
  static {
    $Wfc_1 = this;
  }
  static {
    this.ID = "terminal.clipboard";
  }
  static get(instance2) {
    return instance2.getContribution($Wfc_1.ID);
  }
  constructor(h3, j, m, n, r2, s) {
    super();
    this.h = h3;
    this.j = j;
    this.m = m;
    this.n = n;
    this.r = r2;
    this.s = s;
    this.b = void 0;
    this.f = this.B(new $ze());
    this.onWillPaste = this.f.event;
    this.g = this.B(new $ze());
    this.onDidPaste = this.g.event;
  }
  xtermReady(xterm) {
    this.a = xterm;
    this.B(xterm.onDidRequestCopyAsHtml((e) => this.copySelection(true, e.command)));
    this.B(xterm.raw.onSelectionChange(async () => {
      if (this.m.getValue(
        "terminal.integrated.copyOnSelection"
        /* TerminalSettingId.CopyOnSelection */
      )) {
        if (this.b === false) {
          return;
        }
        if (this.h.instance.hasSelection()) {
          await this.copySelection();
        }
      }
    }));
  }
  async copySelection(asHtml, command4) {
    this.a?.copySelection(asHtml, command4);
  }
  /**
   * Focuses and pastes the contents of the clipboard into the terminal instance.
   */
  async paste() {
    await this.t(await this.j.readText());
  }
  /**
   * Focuses and pastes the contents of the selection clipboard into the terminal instance.
   */
  async pasteSelection() {
    await this.t(await this.j.readText("selection"));
  }
  async t(value) {
    if (!this.a) {
      return;
    }
    let currentText = value;
    const shouldPasteText = await this.n.invokeFunction($Vfc, currentText, this.a?.raw.modes.bracketedPasteMode);
    if (!shouldPasteText) {
      return;
    }
    if (typeof shouldPasteText === "object") {
      currentText = shouldPasteText.modifiedText;
    }
    this.h.instance.focus();
    this.f.fire(currentText);
    this.a.raw.paste(currentText);
    this.g.fire(currentText);
  }
  async handleMouseEvent(event) {
    switch (event.button) {
      case 1: {
        if (this.s.config.middleClickBehavior === "paste") {
          this.paste();
          return { handled: true };
        }
        break;
      }
      case 2: {
        if (event.shiftKey) {
          return;
        }
        const rightClickBehavior = this.s.config.rightClickBehavior;
        if (rightClickBehavior !== "copyPaste" && rightClickBehavior !== "paste") {
          return;
        }
        if (rightClickBehavior === "copyPaste" && this.h.instance.hasSelection()) {
          await this.copySelection();
          this.h.instance.clearSelection();
        } else {
          if ($5e.clipboard.readText) {
            this.paste();
          } else {
            this.r.info(`This browser doesn't support the clipboard.readText API needed to trigger a paste, try ${$m ? "\u2318" : "Ctrl"}+V instead.`);
          }
        }
        if ($m) {
          setTimeout(() => this.h.instance.clearSelection(), 0);
        }
        return { handled: true };
      }
    }
  }
  /**
   * Override the copy on selection feature with a custom value.
   * @param value Whether to enable copySelection.
   */
  overrideCopyOnSelection(value) {
    if (this.b !== void 0) {
      throw new Error("Cannot set a copy on selection override multiple times");
    }
    this.b = value;
    return $1c(() => this.b = void 0);
  }
};
$Wfc = $Wfc_1 = __decorate([
  __param(1, $30),
  __param(2, $kl),
  __param(3, $Pk),
  __param(4, $PJ),
  __param(5, $5Pb)
], $Wfc);
$Y0b($Wfc.ID, $Wfc, false);
var terminalAvailableWhenClause = $7m.or(TerminalContextKeys.processSupported, TerminalContextKeys.terminalHasBeenCreated);
$Wec({
  id: "workbench.action.terminal.copyLastCommand",
  title: localize2(10870, "Copy Last Command"),
  precondition: terminalAvailableWhenClause,
  run: async (instance2, c, accessor) => {
    const clipboardService = accessor.get($30);
    const commands2 = instance2.capabilities.get(
      2
      /* TerminalCapability.CommandDetection */
    )?.commands;
    if (!commands2 || commands2.length === 0) {
      return;
    }
    const command4 = commands2[commands2.length - 1];
    if (!command4.command) {
      return;
    }
    await clipboardService.writeText(command4.command);
  }
});
$Wec({
  id: "workbench.action.terminal.copyLastCommandOutput",
  title: localize2(10871, "Copy Last Command Output"),
  precondition: terminalAvailableWhenClause,
  run: async (instance2, c, accessor) => {
    const clipboardService = accessor.get($30);
    const commands2 = instance2.capabilities.get(
      2
      /* TerminalCapability.CommandDetection */
    )?.commands;
    if (!commands2 || commands2.length === 0) {
      return;
    }
    const command4 = commands2[commands2.length - 1];
    if (!command4?.hasOutput()) {
      return;
    }
    const output = command4.getOutput();
    if ($zg(output)) {
      await clipboardService.writeText(output);
    }
  }
});
$Wec({
  id: "workbench.action.terminal.copyLastCommandAndLastCommandOutput",
  title: localize2(10872, "Copy Last Command and Output"),
  precondition: terminalAvailableWhenClause,
  run: async (instance2, c, accessor) => {
    const clipboardService = accessor.get($30);
    const commands2 = instance2.capabilities.get(
      2
      /* TerminalCapability.CommandDetection */
    )?.commands;
    if (!commands2 || commands2.length === 0) {
      return;
    }
    const command4 = commands2[commands2.length - 1];
    if (!command4?.hasOutput()) {
      return;
    }
    const output = command4.getOutput();
    if ($zg(output)) {
      await clipboardService.writeText(`${command4.command !== "" ? command4.command + "\n" : ""}${output}`);
    }
  }
});
if ($5e.clipboard.writeText) {
  $Xec({
    id: "workbench.action.terminal.copySelection",
    title: localize2(10873, "Copy Selection"),
    // TODO: Why is copy still showing up when text isn't selected?
    precondition: $7m.or(TerminalContextKeys.textSelectedInFocused, $7m.and(terminalAvailableWhenClause, TerminalContextKeys.textSelected)),
    keybinding: [{
      primary: 2048 | 1024 | 33,
      mac: {
        primary: 2048 | 33
        /* KeyCode.KeyC */
      },
      weight: 200,
      when: $7m.or($7m.and(TerminalContextKeys.textSelected, TerminalContextKeys.focus), TerminalContextKeys.textSelectedInFocused)
    }],
    run: (activeInstance) => activeInstance.copySelection()
  });
  $Xec({
    id: "workbench.action.terminal.copyAndClearSelection",
    title: localize2(10874, "Copy and Clear Selection"),
    precondition: $7m.or(TerminalContextKeys.textSelectedInFocused, $7m.and(terminalAvailableWhenClause, TerminalContextKeys.textSelected)),
    keybinding: [{
      win: {
        primary: 2048 | 33
        /* KeyCode.KeyC */
      },
      weight: 200,
      when: $7m.or($7m.and(TerminalContextKeys.textSelected, TerminalContextKeys.focus), TerminalContextKeys.textSelectedInFocused)
    }],
    run: async (xterm) => {
      await xterm.copySelection();
      xterm.clearSelection();
    }
  });
  $Xec({
    id: "workbench.action.terminal.copySelectionAsHtml",
    title: localize2(10875, "Copy Selection as HTML"),
    f1: true,
    category: $Kec.actionCategory,
    precondition: $7m.or(TerminalContextKeys.textSelectedInFocused, $7m.and(terminalAvailableWhenClause, TerminalContextKeys.textSelected)),
    run: (xterm) => xterm.copySelection(true)
  });
}
if ($5e.clipboard.readText) {
  $Wec({
    id: "workbench.action.terminal.paste",
    title: localize2(10876, "Paste into Active Terminal"),
    precondition: terminalAvailableWhenClause,
    keybinding: [{
      primary: 2048 | 52,
      win: { primary: 2048 | 52, secondary: [
        2048 | 1024 | 52
        /* KeyCode.KeyV */
      ] },
      linux: {
        primary: 2048 | 1024 | 52
        /* KeyCode.KeyV */
      },
      weight: 200,
      when: TerminalContextKeys.focus
    }],
    run: (activeInstance) => $Wfc.get(activeInstance)?.paste()
  });
}
if ($5e.clipboard.readText && $n) {
  $Wec({
    id: "workbench.action.terminal.pasteSelection",
    title: localize2(10877, "Paste Selection into Active Terminal"),
    precondition: terminalAvailableWhenClause,
    keybinding: [{
      linux: {
        primary: 1024 | 19
        /* KeyCode.Insert */
      },
      weight: 200,
      when: TerminalContextKeys.focus
    }],
    run: (activeInstance) => $Wfc.get(activeInstance)?.pasteSelection()
  });
}

// out-build/vs/workbench/contrib/terminalContrib/find/browser/terminalFindWidget.js
var TERMINAL_FIND_WIDGET_INITIAL_WIDTH = 419;
var $Xfc = class $Xfc2 extends $Sfc {
  constructor(ib, clipboardService, configurationService, contextKeyService, contextMenuService, contextViewService, hoverService, keybindingService, themeService) {
    super({
      showCommonFindToggles: true,
      checkImeCompletionState: true,
      showResultCount: true,
      initialWidth: TERMINAL_FIND_WIDGET_INITIAL_WIDTH,
      enableSash: true,
      appendCaseSensitiveActionId: "workbench.action.terminal.toggleFindCaseSensitive",
      appendRegexActionId: "workbench.action.terminal.toggleFindRegex",
      appendWholeWordsActionId: "workbench.action.terminal.toggleFindWholeWord",
      previousMatchActionId: "workbench.action.terminal.findPrevious",
      nextMatchActionId: "workbench.action.terminal.findNext",
      closeWidgetActionId: "workbench.action.terminal.hideFind",
      type: "Terminal",
      matchesLimit: 2e4
      /* XtermTerminalConstants.SearchHighlightLimit */
    }, contextViewService, contextKeyService, hoverService, keybindingService);
    this.ib = ib;
    this.B(this.state.onFindReplaceStateChange(() => {
      this.show();
    }));
    this.eb = TerminalContextKeys.findInputFocus.bindTo(contextKeyService);
    this.fb = TerminalContextKeys.findFocus.bindTo(contextKeyService);
    this.gb = TerminalContextKeys.findVisible.bindTo(contextKeyService);
    const innerDom = this.getDomNode().firstChild;
    if (innerDom) {
      this.B($_i(innerDom, "mousedown", (event) => {
        event.stopPropagation();
      }));
      this.B($_i(innerDom, "contextmenu", (event) => {
        event.stopPropagation();
      }));
    }
    const findInputDomNode = this.getFindInputDomNode();
    this.B($_i(findInputDomNode, "contextmenu", (event) => {
      $Ufc(getWindow(findInputDomNode), event, clipboardService, contextMenuService);
      event.stopPropagation();
    }));
    this.B(themeService.onDidColorThemeChange(() => {
      if (this.isVisible()) {
        this.find(true, true);
      }
    }));
    this.B(configurationService.onDidChangeConfiguration((e) => {
      if (e.affectsConfiguration("workbench.colorCustomizations") && this.isVisible()) {
        this.find(true, true);
      }
    }));
    this.updateResultCount();
  }
  find(previous, update) {
    const xterm = this.ib.xterm;
    if (!xterm) {
      return;
    }
    if (previous) {
      this.rb(xterm, this.U, { regex: this.Z(), wholeWord: this.$(), caseSensitive: this.ab(), incremental: update });
    } else {
      this.qb(xterm, this.U, { regex: this.Z(), wholeWord: this.$(), caseSensitive: this.ab() });
    }
  }
  reveal() {
    const initialInput = this.ib.hasSelection() && !this.ib.selection.includes("\n") ? this.ib.selection : void 0;
    const inputValue = initialInput ?? this.U;
    const xterm = this.ib.xterm;
    if (xterm && inputValue && inputValue !== "") {
      this.rb(xterm, inputValue, { incremental: true, regex: this.Z(), wholeWord: this.$(), caseSensitive: this.ab() }).then((foundMatch) => {
        this.bb(foundMatch);
        this.B(Event2.once(xterm.onDidChangeSelection)(() => xterm.clearActiveSearchDecoration()));
      });
    }
    this.bb(false);
    super.reveal(inputValue);
    this.gb.set(true);
  }
  show() {
    const initialInput = this.ib.hasSelection() && !this.ib.selection.includes("\n") ? this.ib.selection : void 0;
    super.show(initialInput);
    this.gb.set(true);
  }
  hide() {
    super.hide();
    this.gb.reset();
    this.ib.focus(true);
    this.ib.xterm?.clearSearchDecorations();
  }
  async S() {
    return this.ib.xterm?.findResult;
  }
  N() {
    const xterm = this.ib.xterm;
    if (xterm) {
      this.rb(xterm, this.U, { regex: this.Z(), wholeWord: this.$(), caseSensitive: this.ab(), incremental: true }).then((foundMatch) => {
        this.bb(foundMatch);
      });
    }
    return false;
  }
  O() {
    if ("overrideCopyOnSelection" in this.ib) {
      this.hb = $Wfc.get(this.ib)?.overrideCopyOnSelection(false);
    }
    this.fb.set(true);
  }
  P() {
    this.hb?.dispose();
    this.ib.xterm?.clearActiveSearchDecoration();
    this.fb.reset();
  }
  Q() {
    this.eb.set(true);
  }
  R() {
    this.eb.reset();
  }
  findFirst() {
    const instance2 = this.ib;
    if (instance2.hasSelection()) {
      instance2.clearSelection();
    }
    const xterm = instance2.xterm;
    if (xterm) {
      this.rb(xterm, this.U, { regex: this.Z(), wholeWord: this.$(), caseSensitive: this.ab() });
    }
  }
  async qb(xterm, term, options3) {
    return xterm.findNext(term, options3).then((foundMatch) => {
      this.B(Event2.once(xterm.onDidChangeSelection)(() => xterm.clearActiveSearchDecoration()));
      return foundMatch;
    });
  }
  async rb(xterm, term, options3) {
    return xterm.findPrevious(term, options3).then((foundMatch) => {
      this.B(Event2.once(xterm.onDidChangeSelection)(() => xterm.clearActiveSearchDecoration()));
      return foundMatch;
    });
  }
};
$Xfc = __decorate([
  __param(1, $30),
  __param(2, $kl),
  __param(3, $on),
  __param(4, $50),
  __param(5, $40),
  __param(6, $5$),
  __param(7, $Ty),
  __param(8, $gs)
], $Xfc);

// out-build/vs/workbench/contrib/terminalContrib/find/browser/terminal.find.contribution.js
var TerminalFindContribution_1;
var TerminalFindContribution = class TerminalFindContribution2 extends $3c {
  static {
    TerminalFindContribution_1 = this;
  }
  static {
    this.ID = "terminal.find";
  }
  static get(instance2) {
    return instance2.getContribution(TerminalFindContribution_1.ID);
  }
  get findWidget() {
    return this.a.value;
  }
  constructor(ctx, instantiationService, terminalService) {
    super();
    this.a = new $sf(() => {
      const findWidget = instantiationService.createInstance($Xfc, ctx.instance);
      findWidget.focusTracker.onDidFocus(() => {
        TerminalFindContribution_1.activeFindWidget = this;
        ctx.instance.forceScrollbarVisibility();
        if (!$9Pb(ctx.instance)) {
          terminalService.setActiveInstance(ctx.instance);
        }
      });
      findWidget.focusTracker.onDidBlur(() => {
        TerminalFindContribution_1.activeFindWidget = void 0;
        ctx.instance.resetScrollbarVisibility();
      });
      if (!ctx.instance.domElement) {
        throw new Error("FindWidget expected terminal DOM to be initialized");
      }
      ctx.instance.domElement?.appendChild(findWidget.getDomNode());
      if (this.b) {
        findWidget.layout(this.b.width);
      }
      return findWidget;
    });
  }
  layout(_xterm, dimension) {
    this.b = dimension;
    this.a.rawValue?.layout(dimension.width);
  }
  xtermReady(xterm) {
    this.B(xterm.onDidChangeFindResults(() => this.a.rawValue?.updateResultCount()));
  }
  dispose() {
    if (TerminalFindContribution_1.activeFindWidget === this) {
      TerminalFindContribution_1.activeFindWidget = void 0;
    }
    super.dispose();
    this.a.rawValue?.dispose();
  }
};
TerminalFindContribution = TerminalFindContribution_1 = __decorate([
  __param(1, $Pk),
  __param(2, $4Pb)
], TerminalFindContribution);
$Y0b(TerminalFindContribution.ID, TerminalFindContribution, true);
$Xec({
  id: "workbench.action.terminal.focusFind",
  title: localize2(10895, "Focus Find"),
  keybinding: {
    primary: 2048 | 36,
    when: $7m.or(TerminalContextKeys.findFocus, TerminalContextKeys.focusInAny),
    weight: 200
    /* KeybindingWeight.WorkbenchContrib */
  },
  precondition: $7m.or(TerminalContextKeys.processSupported, TerminalContextKeys.terminalHasBeenCreated),
  run: (_xterm, _accessor, activeInstance) => {
    const contr = TerminalFindContribution.activeFindWidget || TerminalFindContribution.get(activeInstance);
    contr?.findWidget.reveal();
  }
});
$Xec({
  id: "workbench.action.terminal.hideFind",
  title: localize2(10896, "Hide Find"),
  keybinding: {
    primary: 9,
    secondary: [
      1024 | 9
      /* KeyCode.Escape */
    ],
    when: $7m.and(TerminalContextKeys.focusInAny, TerminalContextKeys.findVisible),
    weight: 200
    /* KeybindingWeight.WorkbenchContrib */
  },
  precondition: $7m.or(TerminalContextKeys.processSupported, TerminalContextKeys.terminalHasBeenCreated),
  run: (_xterm, _accessor, activeInstance) => {
    const contr = TerminalFindContribution.activeFindWidget || TerminalFindContribution.get(activeInstance);
    contr?.findWidget.hide();
  }
});
$Xec({
  id: "workbench.action.terminal.toggleFindRegex",
  title: localize2(10897, "Toggle Find Using Regex"),
  keybinding: {
    primary: 512 | 48,
    mac: {
      primary: 2048 | 512 | 48
      /* KeyCode.KeyR */
    },
    when: TerminalContextKeys.findVisible,
    weight: 200
    /* KeybindingWeight.WorkbenchContrib */
  },
  precondition: $7m.or(TerminalContextKeys.processSupported, TerminalContextKeys.terminalHasBeenCreated),
  run: (_xterm, _accessor, activeInstance) => {
    const contr = TerminalFindContribution.activeFindWidget || TerminalFindContribution.get(activeInstance);
    const state = contr?.findWidget.state;
    state?.change({ isRegex: !state.isRegex }, false);
  }
});
$Xec({
  id: "workbench.action.terminal.toggleFindWholeWord",
  title: localize2(10898, "Toggle Find Using Whole Word"),
  keybinding: {
    primary: 512 | 53,
    mac: {
      primary: 2048 | 512 | 53
      /* KeyCode.KeyW */
    },
    when: TerminalContextKeys.findVisible,
    weight: 200
    /* KeybindingWeight.WorkbenchContrib */
  },
  precondition: $7m.or(TerminalContextKeys.processSupported, TerminalContextKeys.terminalHasBeenCreated),
  run: (_xterm, _accessor, activeInstance) => {
    const contr = TerminalFindContribution.activeFindWidget || TerminalFindContribution.get(activeInstance);
    const state = contr?.findWidget.state;
    state?.change({ wholeWord: !state.wholeWord }, false);
  }
});
$Xec({
  id: "workbench.action.terminal.toggleFindCaseSensitive",
  title: localize2(10899, "Toggle Find Using Case Sensitive"),
  keybinding: {
    primary: 512 | 33,
    mac: {
      primary: 2048 | 512 | 33
      /* KeyCode.KeyC */
    },
    when: TerminalContextKeys.findVisible,
    weight: 200
    /* KeybindingWeight.WorkbenchContrib */
  },
  precondition: $7m.or(TerminalContextKeys.processSupported, TerminalContextKeys.terminalHasBeenCreated),
  run: (_xterm, _accessor, activeInstance) => {
    const contr = TerminalFindContribution.activeFindWidget || TerminalFindContribution.get(activeInstance);
    const state = contr?.findWidget.state;
    state?.change({ matchCase: !state.matchCase }, false);
  }
});
$Xec({
  id: "workbench.action.terminal.findNext",
  title: localize2(10900, "Find Next"),
  keybinding: [
    {
      primary: 61,
      mac: { primary: 2048 | 37, secondary: [
        61
        /* KeyCode.F3 */
      ] },
      when: $7m.or(TerminalContextKeys.focusInAny, TerminalContextKeys.findFocus),
      weight: 200
      /* KeybindingWeight.WorkbenchContrib */
    },
    {
      primary: 1024 | 3,
      when: TerminalContextKeys.findInputFocus,
      weight: 200
      /* KeybindingWeight.WorkbenchContrib */
    }
  ],
  precondition: $7m.or(TerminalContextKeys.processSupported, TerminalContextKeys.terminalHasBeenCreated),
  run: (_xterm, _accessor, activeInstance) => {
    const contr = TerminalFindContribution.activeFindWidget || TerminalFindContribution.get(activeInstance);
    const widget = contr?.findWidget;
    if (widget) {
      widget.show();
      widget.find(false);
    }
  }
});
$Xec({
  id: "workbench.action.terminal.findPrevious",
  title: localize2(10901, "Find Previous"),
  keybinding: [
    {
      primary: 1024 | 61,
      mac: { primary: 2048 | 1024 | 37, secondary: [
        1024 | 61
        /* KeyCode.F3 */
      ] },
      when: $7m.or(TerminalContextKeys.focusInAny, TerminalContextKeys.findFocus),
      weight: 200
      /* KeybindingWeight.WorkbenchContrib */
    },
    {
      primary: 3,
      when: TerminalContextKeys.findInputFocus,
      weight: 200
      /* KeybindingWeight.WorkbenchContrib */
    }
  ],
  precondition: $7m.or(TerminalContextKeys.processSupported, TerminalContextKeys.terminalHasBeenCreated),
  run: (_xterm, _accessor, activeInstance) => {
    const contr = TerminalFindContribution.activeFindWidget || TerminalFindContribution.get(activeInstance);
    const widget = contr?.findWidget;
    if (widget) {
      widget.show();
      widget.find(true);
    }
  }
});
$Wec({
  id: "workbench.action.terminal.searchWorkspace",
  title: localize2(10902, "Search Workspace"),
  keybinding: [
    {
      primary: 2048 | 1024 | 36,
      when: $7m.and(TerminalContextKeys.processSupported, TerminalContextKeys.focus, TerminalContextKeys.textSelected),
      weight: 200 + 50
    }
  ],
  run: (activeInstance, c, accessor) => $g8b(accessor, { query: activeInstance.selection })
});

// out-build/vs/workbench/contrib/terminalContrib/chat/browser/terminalChat.js
var TerminalChatCommandId;
(function(TerminalChatCommandId2) {
  TerminalChatCommandId2["Start"] = "workbench.action.terminal.chat.start";
  TerminalChatCommandId2["Close"] = "workbench.action.terminal.chat.close";
  TerminalChatCommandId2["MakeRequest"] = "workbench.action.terminal.chat.makeRequest";
  TerminalChatCommandId2["Cancel"] = "workbench.action.terminal.chat.cancel";
  TerminalChatCommandId2["RunCommand"] = "workbench.action.terminal.chat.runCommand";
  TerminalChatCommandId2["RunFirstCommand"] = "workbench.action.terminal.chat.runFirstCommand";
  TerminalChatCommandId2["InsertCommand"] = "workbench.action.terminal.chat.insertCommand";
  TerminalChatCommandId2["InsertFirstCommand"] = "workbench.action.terminal.chat.insertFirstCommand";
  TerminalChatCommandId2["ViewInChat"] = "workbench.action.terminal.chat.viewInChat";
})(TerminalChatCommandId || (TerminalChatCommandId = {}));
var $Yfc = $bJ.for("terminalChatWidget");
var $Zfc = $bJ.for("terminalChatWidget.status");
var $1fc = $bJ.for("terminalChatWidget.toolbar");
var TerminalChatContextKeyStrings;
(function(TerminalChatContextKeyStrings2) {
  TerminalChatContextKeyStrings2["ChatFocus"] = "terminalChatFocus";
  TerminalChatContextKeyStrings2["ChatVisible"] = "terminalChatVisible";
  TerminalChatContextKeyStrings2["ChatActiveRequest"] = "terminalChatActiveRequest";
  TerminalChatContextKeyStrings2["ChatInputHasText"] = "terminalChatInputHasText";
  TerminalChatContextKeyStrings2["ChatAgentRegistered"] = "terminalChatAgentRegistered";
  TerminalChatContextKeyStrings2["ChatResponseEditorFocused"] = "terminalChatResponseEditorFocused";
  TerminalChatContextKeyStrings2["ChatResponseContainsCodeBlock"] = "terminalChatResponseContainsCodeBlock";
  TerminalChatContextKeyStrings2["ChatResponseContainsMultipleCodeBlocks"] = "terminalChatResponseContainsMultipleCodeBlocks";
  TerminalChatContextKeyStrings2["ChatResponseSupportsIssueReporting"] = "terminalChatResponseSupportsIssueReporting";
  TerminalChatContextKeyStrings2["ChatSessionResponseVote"] = "terminalChatSessionResponseVote";
})(TerminalChatContextKeyStrings || (TerminalChatContextKeyStrings = {}));
var TerminalChatContextKeys;
(function(TerminalChatContextKeys2) {
  TerminalChatContextKeys2.focused = new $nn("terminalChatFocus", false, localize(10834, null));
  TerminalChatContextKeys2.visible = new $nn("terminalChatVisible", false, localize(10835, null));
  TerminalChatContextKeys2.requestActive = new $nn("terminalChatActiveRequest", false, localize(10836, null));
  TerminalChatContextKeys2.inputHasText = new $nn("terminalChatInputHasText", false, localize(10837, null));
  TerminalChatContextKeys2.responseContainsCodeBlock = new $nn("terminalChatResponseContainsCodeBlock", false, localize(10838, null));
  TerminalChatContextKeys2.responseContainsMultipleCodeBlocks = new $nn("terminalChatResponseContainsMultipleCodeBlocks", false, localize(10839, null));
  TerminalChatContextKeys2.hasChatAgent = new $nn("terminalChatAgentRegistered", false, localize(10840, null));
})(TerminalChatContextKeys || (TerminalChatContextKeys = {}));

// out-build/vs/workbench/contrib/terminalContrib/stickyScroll/browser/terminalStickyScrollColorRegistry.js
var $2fc = $5n("terminalStickyScroll.background", null, localize(10970, null));
var $3fc = $5n("terminalStickyScrollHover.background", {
  dark: "#2A2D2E",
  light: "#F0F0F0",
  hcDark: "#E48B39",
  hcLight: "#0f4a85"
}, localize(10971, null));
$5n("terminalStickyScroll.border", {
  dark: null,
  light: null,
  hcDark: "#6fc3df",
  hcLight: "#0f4a85"
}, localize(10972, null));

// out-build/vs/workbench/contrib/terminalContrib/stickyScroll/browser/terminalStickyScrollOverlay.js
var OverlayState;
(function(OverlayState2) {
  OverlayState2[OverlayState2["Off"] = 0] = "Off";
  OverlayState2[OverlayState2["On"] = 1] = "On";
})(OverlayState || (OverlayState = {}));
var CssClasses;
(function(CssClasses2) {
  CssClasses2["Visible"] = "visible";
})(CssClasses || (CssClasses = {}));
var Constants18;
(function(Constants27) {
  Constants27[Constants27["StickyScrollPercentageCap"] = 0.4] = "StickyScrollPercentageCap";
})(Constants18 || (Constants18 = {}));
var $4fc = class $4fc2 extends $3c {
  constructor(w, y, z, C, xtermCtor, configurationService, contextKeyService, D, F, menuService, G, H) {
    super();
    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.b = new $1Pb();
    this.r = this.B(new $4c());
    this.s = 0;
    this.t = false;
    this.u = 5;
    this.n = this.B(menuService.createMenu($bJ.TerminalStickyScrollContext, contextKeyService));
    this.B(Event2.runAndSubscribe(this.y.raw.buffer.onBufferChange, (buffer) => {
      this.I(
        (buffer ?? this.y.raw.buffer.active).type === "normal" ? 1 : 0
        /* OverlayState.Off */
      );
    }));
    this.B(Event2.runAndSubscribe(configurationService.onDidChangeConfiguration, (e) => {
      if (!e || e.affectsConfiguration(
        "terminal.integrated.stickyScroll.maxLineCount"
        /* TerminalStickyScrollSettingId.MaxLineCount */
      )) {
        this.u = configurationService.getValue(
          "terminal.integrated.stickyScroll.maxLineCount"
          /* TerminalStickyScrollSettingId.MaxLineCount */
        );
      }
    }));
    this.B(this.w.onDidChangeTarget(() => this.R()));
    xtermCtor.then((ctor) => {
      if (this.q.isDisposed) {
        return;
      }
      this.a = this.B(new ctor({
        rows: 1,
        cols: this.y.raw.cols,
        allowProposedApi: true,
        ...this.S()
      }));
      this.U();
      this.B(configurationService.onDidChangeConfiguration((e) => {
        if (e.affectsConfiguration($9X)) {
          this.R();
        }
      }));
      this.B(this.H.onDidColorThemeChange(() => {
        this.R();
      }));
      this.B(this.y.raw.onResize(() => {
        this.R();
        this.N();
      }));
      this.B(this.w.onDidChangeVisibility((isVisible) => {
        if (isVisible) {
          this.N();
        }
      }));
      this.b.importAddon("serialize").then((SerializeAddon) => {
        if (this.q.isDisposed) {
          return;
        }
        this.c = this.B(new SerializeAddon());
        this.y.raw.loadAddon(this.c);
        this.N();
      });
    });
  }
  lockHide() {
    this.h?.classList.add("lock-hide");
  }
  unlockHide() {
    this.h?.classList.remove("lock-hide");
  }
  I(state) {
    if (this.s === state) {
      return;
    }
    switch (state) {
      case 0: {
        this.M(false);
        this.L();
        break;
      }
      case 1: {
        this.N();
        this.J();
        break;
      }
    }
  }
  J() {
    if (!this.r.value) {
      this.r.value = $Zc(Event2.any(
        this.y.raw.onScroll,
        this.y.raw.onLineFeed,
        // Rarely an update may be required after just a cursor move, like when
        // scrolling horizontally in a pager
        this.y.raw.onCursorMove
      )(() => this.N()), $aj(this.y.raw.element.querySelector(".xterm-viewport"), "scroll", () => this.N()));
    }
  }
  L() {
    this.r.clear();
  }
  M(isVisible) {
    if (isVisible) {
      this.Q();
    }
    this.h?.classList.toggle("visible", isVisible);
  }
  N() {
    if (this.t) {
      return;
    }
    this.t = true;
    queueMicrotask(() => {
      this.O();
      this.t = false;
    });
  }
  O() {
    const command4 = this.C.getCommandForLine(this.y.raw.buffer.active.viewportY);
    this.j = void 0;
    if (!command4) {
      this.M(false);
      return;
    }
    if (!("marker" in command4)) {
      const partialCommand = this.C.currentCommand;
      if (partialCommand?.commandStartMarker && partialCommand.commandExecutedMarker) {
        this.P(partialCommand, partialCommand.commandStartMarker);
        return;
      }
      this.M(false);
      return;
    }
    const marker = command4.marker;
    if (!marker || marker.line === -1) {
      this.M(false);
      return;
    }
    this.P(command4, marker);
  }
  P(command4, startMarker) {
    const xterm = this.y.raw;
    if (!xterm.element?.parentElement || !this.a || !this.c) {
      return;
    }
    if (command4.promptStartMarker?.line === -1) {
      this.M(false);
      return;
    }
    const buffer = xterm.buffer.active;
    const promptRowCount = command4.getPromptRowCount();
    const commandRowCount = command4.getCommandRowCount();
    const stickyScrollLineStart = startMarker.line - (promptRowCount - 1);
    const isPartialCommand = !("getOutput" in command4);
    const rowOffset = !isPartialCommand && command4.endMarker ? Math.max(buffer.viewportY - command4.endMarker.line + 1, 0) : 0;
    const maxLineCount = Math.min(this.u, Math.floor(
      xterm.rows * 0.4
      /* Constants.StickyScrollPercentageCap */
    ));
    const stickyScrollLineCount = Math.min(promptRowCount + commandRowCount - 1, maxLineCount) - rowOffset;
    if (buffer.viewportY <= stickyScrollLineStart) {
      this.M(false);
      return;
    }
    if (isPartialCommand && buffer.viewportY === buffer.baseY && buffer.cursorY === xterm.rows - 1) {
      const line = buffer.getLine(buffer.baseY + xterm.rows - 1);
      if (buffer.cursorX === 1 && lineStartsWith(line, ":") || buffer.cursorX === 5 && lineStartsWith(line, "(END)")) {
        this.M(false);
        return;
      }
    }
    const content = this.c.serialize({
      range: {
        start: stickyScrollLineStart + rowOffset,
        end: stickyScrollLineStart + rowOffset + Math.max(stickyScrollLineCount - 1, 0)
      }
    });
    if (isPartialCommand && $kg(content).length === 0) {
      this.M(false);
      return;
    }
    if (content && this.m !== content || this.a.cols !== xterm.cols || this.a.rows !== stickyScrollLineCount) {
      this.a.resize(this.a.cols, stickyScrollLineCount);
      this.a.write("\x1B[0m\x1B[H\x1B[2J");
      this.a.write(content);
      this.m = content;
    }
    if (content) {
      this.j = command4;
      this.M(true);
      if (this.h) {
        const termBox = xterm.element.getBoundingClientRect();
        if (termBox.height > 0) {
          const rowHeight = termBox.height / xterm.rows;
          const overlayHeight = stickyScrollLineCount * rowHeight;
          let endMarkerOffset = 0;
          if (!isPartialCommand && command4.endMarker && command4.endMarker.line !== -1) {
            if (buffer.viewportY + stickyScrollLineCount > command4.endMarker.line) {
              const diff3 = buffer.viewportY + stickyScrollLineCount - command4.endMarker.line;
              endMarkerOffset = diff3 * rowHeight;
            }
          }
          this.h.style.bottom = `${termBox.height - overlayHeight + 1 + endMarkerOffset}px`;
        }
      }
    } else {
      this.M(false);
    }
  }
  Q() {
    if (
      // The element is already created
      this.h || // If the overlay is yet to be created, the terminal cannot be opened so defer to next call
      !this.a || // The xterm.js instance isn't opened yet
      !this.y?.raw.element?.parentElement
    ) {
      return;
    }
    const overlay = this.a;
    const hoverOverlay = $(".hover-overlay");
    this.h = $(".terminal-sticky-scroll", void 0, hoverOverlay);
    this.y.raw.element.parentElement.append(this.h);
    this.B($1c(() => this.h?.remove()));
    let hoverTitle = localize(10973, null);
    const scrollToPreviousCommandKeybinding = this.F.lookupKeybinding(
      "workbench.action.terminal.scrollToPreviousCommand"
      /* TerminalCommandId.ScrollToPreviousCommand */
    );
    if (scrollToPreviousCommandKeybinding) {
      const label3 = scrollToPreviousCommandKeybinding.getLabel();
      if (label3) {
        hoverTitle += "\n" + localize(10974, null, $Kec.scrollToPreviousCommand.value, label3);
      }
    }
    const scrollToNextCommandKeybinding = this.F.lookupKeybinding(
      "workbench.action.terminal.scrollToNextCommand"
      /* TerminalCommandId.ScrollToNextCommand */
    );
    if (scrollToNextCommandKeybinding) {
      const label3 = scrollToNextCommandKeybinding.getLabel();
      if (label3) {
        hoverTitle += "\n" + localize(10975, null, $Kec.scrollToNextCommand.value, label3);
      }
    }
    hoverOverlay.title = hoverTitle;
    const scrollBarWidth = this.y.raw._core.viewport?.scrollBarWidth;
    if (scrollBarWidth !== void 0) {
      this.h.style.right = `${scrollBarWidth}px`;
    }
    this.a.open(this.h);
    this.b.importAddon("ligatures").then((LigaturesAddon) => {
      if (this.q.isDisposed || !this.a) {
        return;
      }
      this.g = new LigaturesAddon();
      this.a.loadAddon(this.g);
    });
    this.B($aj(hoverOverlay, "click", () => {
      if (this.y && this.j) {
        this.y.markTracker.revealCommand(this.j);
        this.w.focus();
      }
    }));
    this.B($aj(hoverOverlay, "wheel", (e) => this.y?.raw.element?.dispatchEvent(new WheelEvent(e.type, e))));
    this.B($_i(hoverOverlay, "mousedown", (e) => {
      e.stopImmediatePropagation();
      e.preventDefault();
    }));
    this.B($_i(hoverOverlay, "contextmenu", (e) => {
      e.stopImmediatePropagation();
      e.preventDefault();
      $Oec(getWindow(hoverOverlay), e, this.w, this.n, this.D);
    }));
    this.B($aj(hoverOverlay, "mouseover", () => overlay.options.theme = this.X(true)));
    this.B($aj(hoverOverlay, "mouseleave", () => overlay.options.theme = this.X(false)));
  }
  R() {
    if (!this.a) {
      return;
    }
    this.a.resize(this.y.raw.cols, this.a.rows);
    this.a.options = this.S();
    this.U();
  }
  S() {
    const o = this.y.raw.options;
    return {
      cursorInactiveStyle: "none",
      scrollback: 0,
      logLevel: "off",
      theme: this.X(false),
      documentOverride: o.documentOverride,
      fontFamily: o.fontFamily,
      fontWeight: o.fontWeight,
      fontWeightBold: o.fontWeightBold,
      fontSize: o.fontSize,
      letterSpacing: o.letterSpacing,
      lineHeight: o.lineHeight,
      drawBoldTextInBrightColors: o.drawBoldTextInBrightColors,
      minimumContrastRatio: o.minimumContrastRatio,
      tabStopWidth: o.tabStopWidth,
      customGlyphs: o.customGlyphs
    };
  }
  async U() {
    if (this.W() && !this.f) {
      const WebglAddon = await this.b.importAddon("webgl");
      if (this.q.isDisposed) {
        return;
      }
      this.f = this.B(new WebglAddon());
      this.a?.loadAddon(this.f);
    } else if (!this.W() && this.f) {
      this.f.dispose();
      this.f = void 0;
    }
  }
  W() {
    return this.G.config.gpuAcceleration === "auto" || this.G.config.gpuAcceleration === "on";
  }
  X(isHovering) {
    const theme = this.H.getColorTheme();
    return {
      ...this.y.getXtermTheme(),
      background: isHovering ? theme.getColor($3fc)?.toString() ?? this.z.getBackgroundColor(theme)?.toString() : theme.getColor($2fc)?.toString() ?? this.z.getBackgroundColor(theme)?.toString(),
      selectionBackground: void 0,
      selectionInactiveBackground: void 0
    };
  }
};
__decorate([
  $_t(0)
], $4fc.prototype, "R", null);
__decorate([
  $_t(0)
], $4fc.prototype, "U", null);
$4fc = __decorate([
  __param(5, $kl),
  __param(6, $on),
  __param(7, $50),
  __param(8, $Ty),
  __param(9, $cJ),
  __param(10, $5Pb),
  __param(11, $gs)
], $4fc);
function lineStartsWith(line, text2) {
  if (!line) {
    return false;
  }
  for (let i2 = 0; i2 < text2.length; i2++) {
    if (line.getCell(i2)?.getChars() !== text2[i2]) {
      return false;
    }
  }
  return true;
}

// out-build/vs/workbench/contrib/terminalContrib/stickyScroll/browser/terminalStickyScrollContribution.js
var $5fc_1;
var $5fc = class $5fc2 extends $3c {
  static {
    $5fc_1 = this;
  }
  static {
    this.ID = "terminal.stickyScroll";
  }
  static get(instance2) {
    return instance2.getContribution($5fc_1.ID);
  }
  constructor(g, h3, j, m, n) {
    super();
    this.g = g;
    this.h = h3;
    this.j = j;
    this.m = m;
    this.n = n;
    this.b = this.B(new $4c());
    this.c = this.B(new $4c());
    this.f = this.B(new $4c());
    this.B(Event2.runAndSubscribe(this.h.onDidChangeConfiguration, (e) => {
      if (!e || e.affectsConfiguration(
        "terminal.integrated.stickyScroll.enabled"
        /* TerminalStickyScrollSettingId.Enabled */
      )) {
        this.r();
      }
    }));
  }
  xtermReady(xterm) {
    this.a = xterm;
    this.r();
  }
  xtermOpen(xterm) {
    this.r();
  }
  hideLock() {
    this.b.value?.lockHide();
  }
  hideUnlock() {
    this.b.value?.unlockHide();
  }
  r() {
    if (this.b.value) {
      this.t();
    } else {
      this.s();
    }
    if (this.b.value) {
      this.c.clear();
      if (!this.f.value) {
        this.f.value = this.g.instance.capabilities.onDidRemoveCapability((e) => {
          if (e.id === 2) {
            this.r();
          }
        });
      }
    } else {
      this.f.clear();
      if (!this.c.value) {
        this.c.value = this.g.instance.capabilities.onDidAddCapability((e) => {
          if (e.id === 2) {
            this.r();
          }
        });
      }
    }
  }
  s() {
    if (this.u()) {
      const xtermCtorEventually = $wfc.getXtermConstructor(this.n, this.j);
      this.b.value = this.m.createInstance($4fc, this.g.instance, this.a, this.m.createInstance($zfc, this.g.instance.targetRef), this.g.instance.capabilities.get(
        2
        /* TerminalCapability.CommandDetection */
      ), xtermCtorEventually);
    }
  }
  t() {
    if (!this.u()) {
      this.b.clear();
    }
  }
  u() {
    const capability = this.g.instance.capabilities.get(
      2
      /* TerminalCapability.CommandDetection */
    );
    return !!(this.h.getValue(
      "terminal.integrated.stickyScroll.enabled"
      /* TerminalStickyScrollSettingId.Enabled */
    ) && capability && this.a?.raw?.element);
  }
};
$5fc = $5fc_1 = __decorate([
  __param(1, $kl),
  __param(2, $on),
  __param(3, $Pk),
  __param(4, $Ty)
], $5fc);

// out-build/vs/workbench/contrib/terminalContrib/chat/browser/terminalChatWidget.js
var Constants19;
(function(Constants27) {
  Constants27[Constants27["HorizontalMargin"] = 10] = "HorizontalMargin";
  Constants27[Constants27["VerticalMargin"] = 30] = "VerticalMargin";
  Constants27[Constants27["RightPadding"] = 12] = "RightPadding";
  Constants27[Constants27["MaxHeight"] = 480] = "MaxHeight";
  Constants27[Constants27["MaxHeightPercentageOfViewport"] = 0.75] = "MaxHeightPercentageOfViewport";
})(Constants19 || (Constants19 = {}));
var Message2;
(function(Message3) {
  Message3[Message3["None"] = 0] = "None";
  Message3[Message3["AcceptSession"] = 1] = "AcceptSession";
  Message3[Message3["CancelSession"] = 2] = "CancelSession";
  Message3[Message3["PauseSession"] = 4] = "PauseSession";
  Message3[Message3["CancelRequest"] = 8] = "CancelRequest";
  Message3[Message3["CancelInput"] = 16] = "CancelInput";
  Message3[Message3["AcceptInput"] = 32] = "AcceptInput";
  Message3[Message3["ReturnInput"] = 64] = "ReturnInput";
})(Message2 || (Message2 = {}));
var $6fc = class $6fc2 extends $3c {
  get inlineChatWidget() {
    return this.c;
  }
  get lastResponseContent() {
    return this.u;
  }
  constructor(G, H, I, contextKeyService, J, L, M, instantiationService) {
    super();
    this.G = G;
    this.H = H;
    this.I = I;
    this.J = J;
    this.L = L;
    this.M = M;
    this.b = this.B(new $ze());
    this.onDidHide = this.b.event;
    this.s = this.q.add(new $ze());
    this.t = "terminal-inline-chat-view-state";
    this.w = "terminal";
    this.y = this.B(new $4c());
    this.F = $he(this, false);
    this.requestInProgress = this.F;
    this.g = TerminalChatContextKeys.focused.bindTo(contextKeyService);
    this.h = TerminalChatContextKeys.visible.bindTo(contextKeyService);
    this.j = TerminalChatContextKeys.requestActive.bindTo(contextKeyService);
    this.m = TerminalChatContextKeys.responseContainsCodeBlock.bindTo(contextKeyService);
    this.n = TerminalChatContextKeys.responseContainsMultipleCodeBlocks.bindTo(contextKeyService);
    this.a = document.createElement("div");
    this.a.classList.add("terminal-inline-chat");
    this.G.appendChild(this.a);
    this.c = instantiationService.createInstance($wGb, {
      location: ChatAgentLocation.Terminal,
      resolveData: () => {
        return void 0;
      }
    }, {
      statusMenuId: {
        menu: $Zfc,
        options: {
          buttonConfigProvider: (action) => ({
            isSecondary: action.id !== "workbench.action.terminal.chat.runCommand" && action.id !== "workbench.action.terminal.chat.runFirstCommand"
            /* TerminalChatCommandId.RunFirstCommand */
          })
        }
      },
      secondaryMenuId: $zAb,
      chatWidgetViewOptions: {
        menus: {
          telemetrySource: "terminal-inline-chat",
          executeToolbar: $bJ.ChatExecute,
          inputSideToolbar: $Yfc
        }
      }
    });
    this.B(this.c.chatWidget.onDidChangeViewModel(() => this.Z()));
    this.B(Event2.any(this.c.onDidChangeHeight, this.H.onDimensionsChanged, this.c.chatWidget.onDidChangeContentHeight, Event2.debounce(this.I.raw.onCursorMove, () => void 0, $ue))(() => this.O()));
    const observer = new ResizeObserver(() => this.O());
    observer.observe(this.G);
    this.B($1c(() => observer.disconnect()));
    this.Q();
    this.a.appendChild(this.c.domNode);
    this.f = this.B($_j(this.a));
    this.B(this.f.onDidFocus(() => this.g.set(true)));
    this.B(this.f.onDidBlur(() => this.g.set(false)));
    this.B($td((r2) => {
      const isBusy = this.c.requestInProgress.read(r2);
      this.a.classList.toggle("busy", isBusy);
      this.c.toggleStatus(!!this.c.responseContent);
      if (isBusy || !this.c.responseContent) {
        this.m.set(false);
        this.n.set(false);
      } else {
        Promise.all([
          this.c.getCodeBlockInfo(0),
          this.c.getCodeBlockInfo(1)
        ]).then(([firstCodeBlock, secondCodeBlock]) => {
          this.m.set(!!firstCodeBlock);
          this.n.set(!!secondCodeBlock);
          this.c.updateToolbar(true);
        });
      }
    }));
    this.hide();
  }
  O() {
    if (this.N) {
      this.P();
    }
  }
  P() {
    const xtermElement = this.I.raw.element;
    if (!xtermElement) {
      return;
    }
    const style = $Qj().getComputedStyle(xtermElement);
    const xtermLeftPadding = parseInt(style.paddingLeft);
    const width2 = xtermElement.clientWidth - xtermLeftPadding - 12;
    if (width2 === 0) {
      return;
    }
    const terminalViewportHeight = this.U();
    const widgetAllowedPercentBasedHeight = (terminalViewportHeight ?? 0) * 0.75;
    const height = Math.max(Math.min(480, this.c.contentHeight, widgetAllowedPercentBasedHeight), this.c.minHeight);
    if (height === 0) {
      return;
    }
    this.N = new $rj(width2, height);
    this.c.layout(this.N);
    this.c.domNode.style.paddingLeft = `${xtermLeftPadding}px`;
    this.S();
  }
  Q() {
    this.inlineChatWidget.placeholder = this.y.value?.welcomeMessage?.title ?? localize(10868, null);
  }
  async reveal(viewState) {
    await this.X(viewState);
    this.P();
    this.a.classList.remove("hide");
    this.h.set(true);
    this.Q();
    this.c.focus();
    this.H.scrollToBottom();
  }
  R() {
    const font = this.H.xterm?.getFont();
    if (!font?.charHeight) {
      return;
    }
    const terminalWrapperHeight = this.U() ?? 0;
    const cellHeight = font.charHeight * font.lineHeight;
    const topPadding = terminalWrapperHeight - this.H.rows * cellHeight;
    const cursorY = (this.H.xterm?.raw.buffer.active.cursorY ?? 0) + 1;
    return topPadding + cursorY * cellHeight;
  }
  S() {
    const top2 = this.R();
    if (!top2) {
      return;
    }
    this.a.style.top = `${top2}px`;
    const terminalViewportHeight = this.U();
    if (!terminalViewportHeight) {
      return;
    }
    const widgetAllowedPercentBasedHeight = terminalViewportHeight * 0.75;
    const height = Math.max(Math.min(480, this.c.contentHeight, widgetAllowedPercentBasedHeight), this.c.minHeight);
    if (top2 > terminalViewportHeight - height && terminalViewportHeight - height > 0) {
      this.W(top2 - (terminalViewportHeight - height));
    } else {
      this.W(void 0);
    }
  }
  U() {
    return this.G.clientHeight;
  }
  hide() {
    this.a.classList.add("hide");
    this.c.reset();
    this.Q();
    this.c.updateToolbar(false);
    this.h.set(false);
    this.c.value = "";
    this.H.focus();
    this.W(void 0);
    this.b.fire();
  }
  W(offset) {
    if (offset === void 0 || this.a.classList.contains("hide")) {
      this.G.style.position = "";
      this.G.style.bottom = "";
      $5fc.get(this.H)?.hideUnlock();
    } else {
      this.G.style.position = "relative";
      this.G.style.bottom = `${offset}px`;
      $5fc.get(this.H)?.hideLock();
    }
  }
  focus() {
    this.inlineChatWidget.focus();
  }
  hasFocus() {
    return this.c.hasFocus();
  }
  setValue(value) {
    this.c.value = value ?? "";
  }
  async acceptCommand(shouldExecute) {
    const code = await this.inlineChatWidget.getCodeBlockInfo(0);
    if (!code) {
      return;
    }
    const value = code.getValue();
    this.H.runCommand(value, shouldExecute);
    this.clear();
  }
  get focusTracker() {
    return this.f;
  }
  async X(viewState) {
    this.z = $Hh(async (token) => {
      if (!this.y.value) {
        this.y.value = this.J.startSession(ChatAgentLocation.Terminal, token);
        const model = this.y.value;
        if (model) {
          this.c.setChatModel(model, this.Y());
        }
        if (!this.y.value) {
          throw new Error("Failed to start chat session");
        }
      }
    });
    this.B($1c(() => this.z?.cancel()));
  }
  Y() {
    const rawViewState = this.L.get(this.t, 0, void 0);
    let viewState;
    if (rawViewState) {
      try {
        viewState = JSON.parse(rawViewState);
      } catch {
        viewState = void 0;
      }
    }
    return viewState;
  }
  Z() {
    this.L.store(
      this.t,
      JSON.stringify(this.c.chatWidget.getViewState()),
      0,
      0
      /* StorageTarget.USER */
    );
  }
  clear() {
    this.cancel();
    this.y.clear();
    this.m.reset();
    this.j.reset();
    this.hide();
    this.setValue(void 0);
  }
  async acceptInput(query, options3) {
    if (!this.y.value) {
      await this.reveal();
    }
    this.s.fire(
      32
      /* Message.AcceptInput */
    );
    const lastInput = this.c.value;
    if (!lastInput) {
      return;
    }
    this.D?.cancel();
    this.D = new $ad();
    const store = new $2c();
    this.j.set(true);
    let responseContent = "";
    const response = await this.c.chatWidget.acceptInput(lastInput, { isVoiceInput: options3?.isVoiceInput });
    this.C = response?.requestId;
    const responsePromise = new $gi();
    try {
      this.j.set(true);
      if (response) {
        store.add(response.onDidChange(async () => {
          responseContent += response.response.value;
          if (response.isCanceled) {
            this.j.set(false);
            responsePromise.complete(void 0);
            return;
          }
          if (response.isComplete) {
            this.j.set(false);
            this.j.set(false);
            const firstCodeBlock = await this.c.getCodeBlockInfo(0);
            const secondCodeBlock = await this.c.getCodeBlockInfo(1);
            this.m.set(!!firstCodeBlock);
            this.n.set(!!secondCodeBlock);
            this.c.updateToolbar(true);
            responsePromise.complete(response);
          }
        }));
      }
      await responsePromise.p;
      this.u = response?.response.getMarkdown();
      return response;
    } catch {
      this.u = void 0;
      return;
    } finally {
      store.dispose();
    }
  }
  cancel() {
    this.z?.cancel();
    this.z = void 0;
    this.D?.cancel();
    this.j.set(false);
    const model = this.c.getChatModel();
    if (!model?.sessionId) {
      return;
    }
    this.J.cancelCurrentRequestForSession(model?.sessionId);
  }
  async viewInChat() {
    const widget = await $3Nb(this.M);
    const currentRequest = this.c.chatWidget.viewModel?.model.getRequests().find((r2) => r2.id === this.C);
    if (!widget || !currentRequest?.response) {
      return;
    }
    const message = [];
    for (const item of currentRequest.response.response.value) {
      if (item.kind === "textEditGroup") {
        for (const group2 of item.edits) {
          message.push({
            kind: "textEdit",
            edits: group2,
            uri: item.uri
          });
        }
      } else {
        message.push(item);
      }
    }
    this.J.addCompleteRequest(widget.viewModel.sessionId, `@${this.w} ${currentRequest.message.text}`, currentRequest.variableData, currentRequest.attempt, {
      message,
      result: currentRequest.response.result,
      followups: currentRequest.response.followups
    });
    widget.focusLastMessage();
    this.hide();
  }
};
$6fc = __decorate([
  __param(3, $on),
  __param(4, $qO),
  __param(5, $jv),
  __param(6, $uob),
  __param(7, $Pk)
], $6fc);

// out-build/vs/workbench/contrib/terminalContrib/chat/browser/terminalChatController.js
var $7fc_1;
var $7fc = class $7fc2 extends $3c {
  static {
    $7fc_1 = this;
  }
  static {
    this.ID = "terminal.chat";
  }
  static get(instance2) {
    return instance2.getContribution($7fc_1.ID);
  }
  /**
   * The terminal chat widget for the controller, this will be undefined if xterm is not ready yet (ie. the
   * terminal is still initializing). This wraps the inline chat widget.
   */
  get terminalChatWidget() {
    return this.a?.value;
  }
  get lastResponseContent() {
    return this.b;
  }
  get scopedContextKeyService() {
    return this.a?.value.inlineChatWidget.scopedContextKeyService ?? this.f;
  }
  constructor(c, chatCodeBlockContextProviderService, f, g, h3) {
    super();
    this.c = c;
    this.f = f;
    this.g = g;
    this.h = h3;
    this.j = void 0;
    this.B(chatCodeBlockContextProviderService.registerProvider({
      getCodeBlockContext: (editor) => {
        if (!editor || !this.a?.hasValue || !this.hasFocus()) {
          return;
        }
        return {
          element: editor,
          code: editor.getValue(),
          codeBlockIndex: 0,
          languageId: editor.getModel().getLanguageId()
        };
      }
    }, "terminal"));
  }
  xtermReady(xterm) {
    this.a = new $sf(() => {
      const chatWidget = this.B(this.g.createInstance($6fc, this.c.instance.domElement, this.c.instance, xterm));
      this.B(chatWidget.focusTracker.onDidFocus(() => {
        $7fc_1.activeChatController = this;
        if (!$9Pb(this.c.instance)) {
          this.h.setActiveInstance(this.c.instance);
        }
      }));
      this.B(chatWidget.focusTracker.onDidBlur(() => {
        $7fc_1.activeChatController = void 0;
        this.c.instance.resetScrollbarVisibility();
      }));
      if (!this.c.instance.domElement) {
        throw new Error("FindWidget expected terminal DOM to be initialized");
      }
      return chatWidget;
    });
  }
  m() {
    const inlineChatWidget = this.a?.value.inlineChatWidget;
    if (inlineChatWidget) {
      inlineChatWidget.placeholder = this.n();
    }
  }
  n() {
    return this.j ?? "";
  }
  setPlaceholder(text2) {
    this.j = text2;
    this.m();
  }
  resetPlaceholder() {
    this.j = void 0;
    this.m();
  }
  updateInput(text2, selectAll = true) {
    const widget = this.a?.value.inlineChatWidget;
    if (widget) {
      widget.value = text2;
      if (selectAll) {
        widget.selectAll();
      }
    }
  }
  focus() {
    this.a?.value.focus();
  }
  hasFocus() {
    return this.a?.rawValue?.hasFocus() ?? false;
  }
  async viewInChat() {
    const chatModel = this.terminalChatWidget?.inlineChatWidget.chatWidget.viewModel?.model;
    if (chatModel) {
      await this.g.invokeFunction(moveToPanelChat2, chatModel);
    }
    this.a?.rawValue?.hide();
  }
};
$7fc = $7fc_1 = __decorate([
  __param(1, $8Nb),
  __param(2, $on),
  __param(3, $Pk),
  __param(4, $4Pb)
], $7fc);
async function moveToPanelChat2(accessor, model) {
  const viewsService = accessor.get($uob);
  const chatService = accessor.get($qO);
  const widget = await $3Nb(viewsService);
  if (widget && widget.viewModel && model) {
    for (const request of model.getRequests().slice()) {
      await chatService.adoptRequest(widget.viewModel.model.sessionId, request);
    }
    widget.focusLastMessage();
  }
}

// out-build/vs/workbench/contrib/terminalContrib/chat/browser/terminalChatAccessibleView.js
var $8fc = class {
  constructor() {
    this.priority = 105;
    this.name = "terminalInlineChat";
    this.type = "view";
    this.when = TerminalChatContextKeys.focused;
  }
  getProvider(accessor) {
    const terminalService = accessor.get($4Pb);
    const menuService = accessor.get($cJ);
    const actions = [];
    const contextKeyService = $7fc.activeChatController?.scopedContextKeyService;
    if (contextKeyService) {
      const menuActions = menuService.getMenuActions($Zfc, contextKeyService);
      for (const action of menuActions) {
        for (const a of action[1]) {
          if (a instanceof $fJ) {
            actions.push(a);
          }
        }
      }
    }
    const controller = terminalService.activeInstance?.getContribution($7fc.ID) ?? void 0;
    if (!controller?.lastResponseContent) {
      return;
    }
    const responseContent = controller.lastResponseContent;
    return new $thb("terminal-chat", {
      type: "view"
      /* AccessibleViewType.View */
    }, () => {
      return responseContent;
    }, () => {
      controller.focus();
    }, "accessibility.verbosity.inlineChat", void 0, actions);
  }
};

// out-build/vs/workbench/contrib/terminalContrib/chat/browser/terminalChatActions.js
$Xec({
  id: "workbench.action.terminal.chat.start",
  title: localize2(10857, "Terminal Inline Chat"),
  category: $Y2b.category,
  keybinding: {
    primary: 2048 | 39,
    when: $7m.and(TerminalContextKeys.focusInAny),
    // HACK: Force weight to be higher than the extension contributed keybinding to override it until it gets replaced
    weight: 400 + 1
    // KeybindingWeight.WorkbenchContrib,
  },
  f1: true,
  precondition: $7m.and($7m.or(TerminalContextKeys.processSupported, TerminalContextKeys.terminalHasBeenCreated), TerminalChatContextKeys.hasChatAgent),
  run: (_xterm, _accessor, activeInstance, opts) => {
    if ($9Pb(activeInstance)) {
      return;
    }
    const contr = $7fc.activeChatController || $7fc.get(activeInstance);
    if (opts) {
      opts = typeof opts === "string" ? { query: opts } : opts;
      if (typeof opts === "object" && opts !== null && "query" in opts && typeof opts.query === "string") {
        contr?.updateInput(opts.query, false);
        if (!("isPartialQuery" in opts && opts.isPartialQuery)) {
          contr?.terminalChatWidget?.acceptInput();
        }
      }
    }
    contr?.terminalChatWidget?.reveal();
  }
});
$Xec({
  id: "workbench.action.terminal.chat.close",
  title: localize2(10858, "Close"),
  category: $Y2b.category,
  keybinding: {
    primary: 9,
    when: $7m.and($7m.or(TerminalContextKeys.focus, TerminalChatContextKeys.focused), TerminalChatContextKeys.visible),
    weight: 200
  },
  menu: [{
    id: $Zfc,
    group: "0_main",
    order: 2,
    when: TerminalChatContextKeys.responseContainsCodeBlock
  }],
  icon: $6l.close,
  f1: true,
  precondition: TerminalChatContextKeys.visible,
  run: (_xterm, _accessor, activeInstance) => {
    if ($9Pb(activeInstance)) {
      return;
    }
    const contr = $7fc.activeChatController || $7fc.get(activeInstance);
    contr?.terminalChatWidget?.clear();
  }
});
$Xec({
  id: "workbench.action.terminal.chat.runCommand",
  title: localize2(10859, "Run Chat Command"),
  shortTitle: localize2(10860, "Run"),
  category: $Y2b.category,
  precondition: $7m.and($7m.or(TerminalContextKeys.processSupported, TerminalContextKeys.terminalHasBeenCreated), TerminalChatContextKeys.requestActive.negate(), TerminalChatContextKeys.responseContainsCodeBlock, TerminalChatContextKeys.responseContainsMultipleCodeBlocks.negate()),
  icon: $6l.play,
  keybinding: {
    when: TerminalChatContextKeys.requestActive.negate(),
    weight: 200,
    primary: 2048 | 3
  },
  menu: {
    id: $Zfc,
    group: "0_main",
    order: 0,
    when: $7m.and(TerminalChatContextKeys.responseContainsCodeBlock, TerminalChatContextKeys.responseContainsMultipleCodeBlocks.negate(), TerminalChatContextKeys.requestActive.negate())
  },
  run: (_xterm, _accessor, activeInstance) => {
    if ($9Pb(activeInstance)) {
      return;
    }
    const contr = $7fc.activeChatController || $7fc.get(activeInstance);
    contr?.terminalChatWidget?.acceptCommand(true);
  }
});
$Xec({
  id: "workbench.action.terminal.chat.runFirstCommand",
  title: localize2(10861, "Run First Chat Command"),
  shortTitle: localize2(10862, "Run First"),
  category: $Y2b.category,
  precondition: $7m.and($7m.or(TerminalContextKeys.processSupported, TerminalContextKeys.terminalHasBeenCreated), TerminalChatContextKeys.requestActive.negate(), TerminalChatContextKeys.responseContainsMultipleCodeBlocks),
  icon: $6l.play,
  keybinding: {
    when: TerminalChatContextKeys.requestActive.negate(),
    weight: 200,
    primary: 2048 | 3
  },
  menu: {
    id: $Zfc,
    group: "0_main",
    order: 0,
    when: $7m.and(TerminalChatContextKeys.responseContainsMultipleCodeBlocks, TerminalChatContextKeys.requestActive.negate())
  },
  run: (_xterm, _accessor, activeInstance) => {
    if ($9Pb(activeInstance)) {
      return;
    }
    const contr = $7fc.activeChatController || $7fc.get(activeInstance);
    contr?.terminalChatWidget?.acceptCommand(true);
  }
});
$Xec({
  id: "workbench.action.terminal.chat.insertCommand",
  title: localize2(10863, "Insert Chat Command"),
  shortTitle: localize2(10864, "Insert"),
  category: $Y2b.category,
  icon: $6l.insert,
  precondition: $7m.and($7m.or(TerminalContextKeys.processSupported, TerminalContextKeys.terminalHasBeenCreated), TerminalChatContextKeys.requestActive.negate(), TerminalChatContextKeys.responseContainsCodeBlock, TerminalChatContextKeys.responseContainsMultipleCodeBlocks.negate()),
  keybinding: {
    when: TerminalChatContextKeys.requestActive.negate(),
    weight: 200,
    primary: 512 | 3,
    secondary: [
      2048 | 3 | 512
      /* KeyMod.Alt */
    ]
  },
  menu: {
    id: $Zfc,
    group: "0_main",
    order: 1,
    when: $7m.and(TerminalChatContextKeys.responseContainsCodeBlock, TerminalChatContextKeys.responseContainsMultipleCodeBlocks.negate(), TerminalChatContextKeys.requestActive.negate())
  },
  run: (_xterm, _accessor, activeInstance) => {
    if ($9Pb(activeInstance)) {
      return;
    }
    const contr = $7fc.activeChatController || $7fc.get(activeInstance);
    contr?.terminalChatWidget?.acceptCommand(false);
  }
});
$Xec({
  id: "workbench.action.terminal.chat.insertFirstCommand",
  title: localize2(10865, "Insert First Chat Command"),
  shortTitle: localize2(10866, "Insert First"),
  category: $Y2b.category,
  precondition: $7m.and($7m.or(TerminalContextKeys.processSupported, TerminalContextKeys.terminalHasBeenCreated), TerminalChatContextKeys.requestActive.negate(), TerminalChatContextKeys.responseContainsMultipleCodeBlocks),
  keybinding: {
    when: TerminalChatContextKeys.requestActive.negate(),
    weight: 200,
    primary: 512 | 3,
    secondary: [
      2048 | 3 | 512
      /* KeyMod.Alt */
    ]
  },
  menu: {
    id: $Zfc,
    group: "0_main",
    order: 1,
    when: $7m.and(TerminalChatContextKeys.responseContainsMultipleCodeBlocks, TerminalChatContextKeys.requestActive.negate())
  },
  run: (_xterm, _accessor, activeInstance) => {
    if ($9Pb(activeInstance)) {
      return;
    }
    const contr = $7fc.activeChatController || $7fc.get(activeInstance);
    contr?.terminalChatWidget?.acceptCommand(false);
  }
});
$Xec({
  id: "workbench.action.terminal.chat.viewInChat",
  title: localize2(10867, "View in Chat"),
  category: $Y2b.category,
  precondition: $7m.and($7m.or(TerminalContextKeys.processSupported, TerminalContextKeys.terminalHasBeenCreated), TerminalChatContextKeys.requestActive.negate()),
  icon: $6l.commentDiscussion,
  menu: [{
    id: $Zfc,
    group: "zzz",
    order: 1,
    isHiddenByDefault: true,
    when: $7m.and(TerminalChatContextKeys.responseContainsCodeBlock, TerminalChatContextKeys.requestActive.negate())
  }],
  run: (_xterm, _accessor, activeInstance) => {
    if ($9Pb(activeInstance)) {
      return;
    }
    const contr = $7fc.activeChatController || $7fc.get(activeInstance);
    contr?.viewInChat();
  }
});

// out-build/vs/workbench/contrib/terminalContrib/chat/browser/terminalChatAccessibilityHelp.js
var $9fc = class {
  constructor() {
    this.priority = 110;
    this.name = "terminalChat";
    this.when = TerminalChatContextKeys.focused;
    this.type = "help";
  }
  getProvider(accessor) {
    const terminalService = accessor.get($4Pb);
    const instance2 = terminalService.activeInstance;
    if (!instance2) {
      return;
    }
    const helpText = $0fc(accessor);
    return new $thb(
      "terminal-chat",
      {
        type: "help"
        /* AccessibleViewType.Help */
      },
      () => helpText,
      () => $7fc.get(instance2)?.terminalChatWidget?.focus(),
      "accessibility.verbosity.terminalChat"
      /* AccessibilityVerbositySettingId.TerminalChat */
    );
  }
};
function $0fc(accessor) {
  const keybindingService = accessor.get($Ty);
  const content = [];
  const openAccessibleViewKeybinding = keybindingService.lookupKeybinding("editor.action.accessibleView")?.getAriaLabel();
  const runCommandKeybinding = keybindingService.lookupKeybinding(
    "workbench.action.terminal.chat.runCommand"
    /* TerminalChatCommandId.RunCommand */
  )?.getAriaLabel();
  const insertCommandKeybinding = keybindingService.lookupKeybinding(
    "workbench.action.terminal.chat.insertCommand"
    /* TerminalChatCommandId.InsertCommand */
  )?.getAriaLabel();
  const makeRequestKeybinding = keybindingService.lookupKeybinding(
    "workbench.action.terminal.chat.makeRequest"
    /* TerminalChatCommandId.MakeRequest */
  )?.getAriaLabel();
  const startChatKeybinding = keybindingService.lookupKeybinding(
    "workbench.action.terminal.chat.start"
    /* TerminalChatCommandId.Start */
  )?.getAriaLabel();
  const focusResponseKeybinding = keybindingService.lookupKeybinding("chat.action.focus")?.getAriaLabel();
  const focusInputKeybinding = keybindingService.lookupKeybinding("workbench.action.chat.focusInput")?.getAriaLabel();
  content.push(localize(10841, null));
  content.push(localize(10842, null, startChatKeybinding));
  content.push(makeRequestKeybinding ? localize(10843, null, makeRequestKeybinding) : localize(10844, null));
  content.push(openAccessibleViewKeybinding ? localize(10845, null, openAccessibleViewKeybinding) : localize(10846, null));
  content.push(focusResponseKeybinding ? localize(10847, null, focusResponseKeybinding) : localize(10848, null));
  content.push(focusInputKeybinding ? localize(10849, null, focusInputKeybinding) : localize(10850, null));
  content.push(runCommandKeybinding ? localize(10851, null, runCommandKeybinding) : localize(10852, null));
  content.push(insertCommandKeybinding ? localize(10853, null, insertCommandKeybinding) : localize(10854, null));
  content.push(localize(10855, null));
  content.push(localize(10856, null));
  return content.join("\n");
}

// out-build/vs/workbench/contrib/terminalContrib/chat/browser/terminalChatEnabler.js
var $$fc = class $$fc2 {
  static {
    this.Id = "terminalChat.enabler";
  }
  constructor(chatAgentService, contextKeyService) {
    this.b = new $2c();
    this.a = TerminalChatContextKeys.hasChatAgent.bindTo(contextKeyService);
    this.b.add(chatAgentService.onDidChangeAgents(() => {
      const hasTerminalAgent = Boolean(chatAgentService.getDefaultAgent(ChatAgentLocation.Terminal));
      this.a.set(hasTerminalAgent);
    }));
  }
  dispose() {
    this.a.reset();
    this.b.dispose();
  }
};
$$fc = __decorate([
  __param(0, $ZO),
  __param(1, $on)
], $$fc);

// out-build/vs/workbench/contrib/terminalContrib/chat/browser/terminal.chat.contribution.js
$Y0b($7fc.ID, $7fc, false);
$vhb.register(new $8fc());
$vhb.register(new $9fc());
$PL(
  $$fc.Id,
  $$fc,
  3
  /* WorkbenchPhase.AfterRestored */
);

// out-build/vs/workbench/contrib/terminalContrib/commandGuide/browser/terminal.commandGuide.contribution.js
var TerminalCommandGuideContribution_1;
var TerminalCommandGuideContribution = class TerminalCommandGuideContribution2 extends $3c {
  static {
    TerminalCommandGuideContribution_1 = this;
  }
  static {
    this.ID = "terminal.commandGuide";
  }
  static get(instance2) {
    return instance2.getContribution(TerminalCommandGuideContribution_1.ID);
  }
  constructor(c, f) {
    super();
    this.c = c;
    this.f = f;
    this.b = this.B(new $4c());
  }
  xtermOpen(xterm) {
    this.a = xterm;
    this.g();
    this.B(this.f.onDidChangeConfiguration((e) => {
      if (e.affectsConfiguration(
        "terminal.integrated.shellIntegration.showCommandGuide"
        /* TerminalCommandGuideSettingId.ShowCommandGuide */
      )) {
        this.g();
      }
    }));
  }
  g() {
    const xterm = this.a;
    if (!xterm) {
      return;
    }
    const showCommandGuide = this.f.getValue($SX).showCommandGuide;
    if (!!this.b.value === showCommandGuide) {
      return;
    }
    if (!showCommandGuide) {
      this.b.clear();
    } else {
      const screenElement = xterm.raw.element.querySelector(".xterm-screen");
      const viewportElement = xterm.raw.element.querySelector(".xterm-viewport");
      this.b.value = $Zc($_i(screenElement, "mousemove", (e) => this.h(screenElement, xterm, e)), $_i(viewportElement, "mousemove", (e) => this.h(screenElement, xterm, e)), $_i(xterm.raw.element, "mouseout", () => xterm.markTracker.showCommandGuide(void 0)), xterm.raw.onData(() => xterm.markTracker.showCommandGuide(void 0)), $1c(() => xterm.markTracker.showCommandGuide(void 0)));
    }
  }
  h(element, xterm, e) {
    const rect = element.getBoundingClientRect();
    if (!rect) {
      return;
    }
    const mouseCursorY = Math.floor((e.clientY - rect.top) / (rect.height / xterm.raw.rows));
    const command4 = this.c.instance.capabilities.get(
      2
      /* TerminalCapability.CommandDetection */
    )?.getCommandForLine(xterm.raw.buffer.active.viewportY + mouseCursorY);
    if (command4 && "getOutput" in command4) {
      xterm.markTracker.showCommandGuide(command4);
    } else {
      xterm.markTracker.showCommandGuide(void 0);
    }
  }
};
TerminalCommandGuideContribution = TerminalCommandGuideContribution_1 = __decorate([
  __param(1, $kl)
], TerminalCommandGuideContribution);
$Y0b(TerminalCommandGuideContribution.ID, TerminalCommandGuideContribution, false);
var $_fc = $5n("terminalCommandGuide.foreground", {
  dark: $0n($lr, 1),
  light: $0n($lr, 1),
  hcDark: $Jmb,
  hcLight: $Jmb
}, localize(10883, null));

// out-build/vs/workbench/contrib/terminalContrib/history/common/history.js
var Constants20;
(function(Constants27) {
  Constants27[Constants27["DefaultHistoryLimit"] = 100] = "DefaultHistoryLimit";
})(Constants20 || (Constants20 = {}));
var StorageKeys;
(function(StorageKeys2) {
  StorageKeys2["Entries"] = "terminal.history.entries";
  StorageKeys2["Timestamp"] = "terminal.history.timestamp";
})(StorageKeys || (StorageKeys = {}));
var directoryHistory = void 0;
function $agc(accessor) {
  if (!directoryHistory) {
    directoryHistory = accessor.get($Pk).createInstance($cgc, "dirs");
  }
  return directoryHistory;
}
var commandHistory = void 0;
function $bgc(accessor) {
  if (!commandHistory) {
    commandHistory = accessor.get($Pk).createInstance($cgc, "commands");
  }
  return commandHistory;
}
var $cgc = class $cgc2 extends $3c {
  get entries() {
    this.n();
    return this.a.entries();
  }
  constructor(h3, j, m) {
    super();
    this.h = h3;
    this.j = j;
    this.m = m;
    this.b = 0;
    this.f = false;
    this.g = true;
    this.a = new $Hc(this.u());
    this.B(this.j.onDidChangeConfiguration((e) => {
      if (e.affectsConfiguration(
        "terminal.integrated.shellIntegration.history"
        /* TerminalHistorySettingId.ShellIntegrationCommandHistory */
      )) {
        this.a.limit = this.u();
      }
    }));
    this.B(this.m.onDidChangeValue(-1, this.w(), this.q)(() => {
      if (!this.g) {
        this.g = this.m.getNumber(this.w(), -1, 0) !== this.b;
      }
    }));
  }
  add(key2, value) {
    this.n();
    this.a.set(key2, value);
    this.t();
  }
  remove(key2) {
    this.n();
    this.a.delete(key2);
    this.t();
  }
  clear() {
    this.n();
    this.a.clear();
    this.t();
  }
  n() {
    if (!this.f) {
      this.r();
      this.f = true;
    }
    if (this.g) {
      this.a.clear();
      this.r();
      this.g = false;
    }
  }
  r() {
    this.b = this.m.getNumber(this.w(), -1, 0);
    const serialized = this.s();
    if (serialized) {
      for (const entry of serialized.entries) {
        this.a.set(entry.key, entry.value);
      }
    }
  }
  s() {
    const raw = this.m.get(
      this.y(),
      -1
      /* StorageScope.APPLICATION */
    );
    if (raw === void 0 || raw.length === 0) {
      return void 0;
    }
    let serialized = void 0;
    try {
      serialized = JSON.parse(raw);
    } catch {
      return void 0;
    }
    return serialized;
  }
  t() {
    const serialized = { entries: [] };
    this.a.forEach((value, key2) => serialized.entries.push({ key: key2, value }));
    this.m.store(
      this.y(),
      JSON.stringify(serialized),
      -1,
      1
      /* StorageTarget.MACHINE */
    );
    this.b = Date.now();
    this.m.store(
      this.w(),
      this.b,
      -1,
      1
      /* StorageTarget.MACHINE */
    );
  }
  u() {
    const historyLimit = this.j.getValue(
      "terminal.integrated.shellIntegration.history"
      /* TerminalHistorySettingId.ShellIntegrationCommandHistory */
    );
    return typeof historyLimit === "number" ? historyLimit : 100;
  }
  w() {
    return `${"terminal.history.timestamp"}.${this.h}`;
  }
  y() {
    return `${"terminal.history.entries"}.${this.h}`;
  }
};
$cgc = __decorate([
  __param(1, $kl),
  __param(2, $jv)
], $cgc);
var shellFileHistory = /* @__PURE__ */ new Map();
async function $dgc(accessor, shellType) {
  const cached = shellFileHistory.get(shellType);
  if (cached === null) {
    return void 0;
  }
  if (cached !== void 0) {
    return cached;
  }
  let result;
  switch (shellType) {
    case "bash":
      result = await $fgc(accessor);
      break;
    case "pwsh":
      result = await $igc(accessor);
      break;
    case "zsh":
      result = await $ggc(accessor);
      break;
    case "fish":
      result = await $jgc(accessor);
      break;
    case "python":
      result = await $hgc(accessor);
      break;
    default:
      return void 0;
  }
  if (result === void 0) {
    shellFileHistory.set(shellType, null);
    return void 0;
  }
  shellFileHistory.set(shellType, result);
  return result;
}
function $egc() {
  shellFileHistory.clear();
}
async function $fgc(accessor) {
  const fileService = accessor.get($km);
  const remoteAgentService = accessor.get($RL);
  const remoteEnvironment = await remoteAgentService.getEnvironment();
  if (remoteEnvironment?.os === 1 || !remoteEnvironment && $l) {
    return void 0;
  }
  const sourceLabel = "~/.bash_history";
  const resolvedFile = await fetchFileContents(env["HOME"], ".bash_history", false, fileService, remoteAgentService);
  if (resolvedFile === void 0) {
    return void 0;
  }
  const fileLines = resolvedFile.content.split("\n");
  const result = /* @__PURE__ */ new Set();
  let currentLine;
  let currentCommand = void 0;
  let wrapChar = void 0;
  for (let i2 = 0; i2 < fileLines.length; i2++) {
    currentLine = fileLines[i2];
    if (currentCommand === void 0) {
      currentCommand = currentLine;
    } else {
      currentCommand += `
${currentLine}`;
    }
    for (let c = 0; c < currentLine.length; c++) {
      if (wrapChar) {
        if (currentLine[c] === wrapChar) {
          wrapChar = void 0;
        }
      } else {
        if (currentLine[c].match(/['"]/)) {
          wrapChar = currentLine[c];
        }
      }
    }
    if (wrapChar === void 0) {
      if (currentCommand.length > 0) {
        result.add(currentCommand.trim());
      }
      currentCommand = void 0;
    }
  }
  return {
    sourceLabel,
    sourceResource: resolvedFile.resource,
    commands: Array.from(result.values())
  };
}
async function $ggc(accessor) {
  const fileService = accessor.get($km);
  const remoteAgentService = accessor.get($RL);
  const remoteEnvironment = await remoteAgentService.getEnvironment();
  if (remoteEnvironment?.os === 1 || !remoteEnvironment && $l) {
    return void 0;
  }
  const sourceLabel = "~/.zsh_history";
  const resolvedFile = await fetchFileContents(env["HOME"], ".zsh_history", false, fileService, remoteAgentService);
  if (resolvedFile === void 0) {
    return void 0;
  }
  const fileLines = resolvedFile.content.split(/\:\s\d+\:\d+;/);
  const result = /* @__PURE__ */ new Set();
  for (let i2 = 0; i2 < fileLines.length; i2++) {
    const sanitized = fileLines[i2].replace(/\\\n/g, "\n").trim();
    if (sanitized.length > 0) {
      result.add(sanitized);
    }
  }
  return {
    sourceLabel,
    sourceResource: resolvedFile.resource,
    commands: Array.from(result.values())
  };
}
async function $hgc(accessor) {
  const fileService = accessor.get($km);
  const remoteAgentService = accessor.get($RL);
  const sourceLabel = "~/.python_history";
  const resolvedFile = await fetchFileContents(env["HOME"], ".python_history", false, fileService, remoteAgentService);
  if (resolvedFile === void 0) {
    return void 0;
  }
  const fileLines = resolvedFile.content.split("\n");
  const result = /* @__PURE__ */ new Set();
  fileLines.forEach((line) => {
    if (line.trim().length > 0) {
      result.add(line.trim());
    }
  });
  return {
    sourceLabel,
    sourceResource: resolvedFile.resource,
    commands: Array.from(result.values())
  };
}
async function $igc(accessor) {
  const fileService = accessor.get($km);
  const remoteAgentService = accessor.get($RL);
  let folderPrefix;
  let filePath;
  const remoteEnvironment = await remoteAgentService.getEnvironment();
  const isFileWindows = remoteEnvironment?.os === 1 || !remoteEnvironment && $l;
  let sourceLabel;
  if (isFileWindows) {
    folderPrefix = env["APPDATA"];
    filePath = "Microsoft\\Windows\\PowerShell\\PSReadLine\\ConsoleHost_history.txt";
    sourceLabel = `$APPDATA\\Microsoft\\Windows\\PowerShell\\PSReadLine\\ConsoleHost_history.txt`;
  } else {
    folderPrefix = env["HOME"];
    filePath = ".local/share/powershell/PSReadline/ConsoleHost_history.txt";
    sourceLabel = `~/${filePath}`;
  }
  const resolvedFile = await fetchFileContents(folderPrefix, filePath, isFileWindows, fileService, remoteAgentService);
  if (resolvedFile === void 0) {
    return void 0;
  }
  const fileLines = resolvedFile.content.split("\n");
  const result = /* @__PURE__ */ new Set();
  let currentLine;
  let currentCommand = void 0;
  let wrapChar = void 0;
  for (let i2 = 0; i2 < fileLines.length; i2++) {
    currentLine = fileLines[i2];
    if (currentCommand === void 0) {
      currentCommand = currentLine;
    } else {
      currentCommand += `
${currentLine}`;
    }
    if (!currentLine.endsWith("`")) {
      const sanitized = currentCommand.trim();
      if (sanitized.length > 0) {
        result.add(sanitized);
      }
      currentCommand = void 0;
      continue;
    }
    for (let c = 0; c < currentLine.length; c++) {
      if (wrapChar) {
        if (currentLine[c] === wrapChar) {
          wrapChar = void 0;
        }
      } else {
        if (currentLine[c].match(/`/)) {
          wrapChar = currentLine[c];
        }
      }
    }
    if (!wrapChar) {
      const sanitized = currentCommand.trim();
      if (sanitized.length > 0) {
        result.add(sanitized);
      }
      currentCommand = void 0;
    } else {
      currentCommand = currentCommand.replace(/`$/, "");
      wrapChar = void 0;
    }
  }
  return {
    sourceLabel,
    sourceResource: resolvedFile.resource,
    commands: Array.from(result.values())
  };
}
async function $jgc(accessor) {
  const fileService = accessor.get($km);
  const remoteAgentService = accessor.get($RL);
  const remoteEnvironment = await remoteAgentService.getEnvironment();
  if (remoteEnvironment?.os === 1 || !remoteEnvironment && $l) {
    return void 0;
  }
  const overridenDataHome = env["XDG_DATA_HOME"];
  let folderPrefix;
  let filePath;
  let sourceLabel;
  if (overridenDataHome) {
    sourceLabel = "$XDG_DATA_HOME/fish/fish_history";
    folderPrefix = env["XDG_DATA_HOME"];
    filePath = "fish/fish_history";
  } else {
    sourceLabel = "~/.local/share/fish/fish_history";
    folderPrefix = env["HOME"];
    filePath = ".local/share/fish/fish_history";
  }
  const resolvedFile = await fetchFileContents(folderPrefix, filePath, false, fileService, remoteAgentService);
  if (resolvedFile === void 0) {
    return void 0;
  }
  const result = /* @__PURE__ */ new Set();
  const cmds = resolvedFile.content.split("\n").filter((x) => x.startsWith("- cmd:")).map((x) => x.substring(6).trimStart());
  for (let i2 = 0; i2 < cmds.length; i2++) {
    const sanitized = $kgc(cmds[i2]).trim();
    if (sanitized.length > 0) {
      result.add(sanitized);
    }
  }
  return {
    sourceLabel,
    sourceResource: resolvedFile.resource,
    commands: Array.from(result.values())
  };
}
function $kgc(cmd) {
  return repeatedReplace(/(^|[^\\])((?:\\\\)*)(\\n)/g, cmd, "$1$2\n");
}
function repeatedReplace(pattern, value, replaceValue) {
  let last;
  let current = value;
  while (true) {
    last = current;
    current = current.replace(pattern, replaceValue);
    if (current === last) {
      return current;
    }
  }
}
async function fetchFileContents(folderPrefix, filePath, isFileWindows, fileService, remoteAgentService) {
  if (!folderPrefix) {
    return void 0;
  }
  const connection = remoteAgentService.getConnection();
  const isRemote = !!connection?.remoteAuthority;
  const resource = URI.from({
    scheme: isRemote ? Schemas.vscodeRemote : Schemas.file,
    authority: isRemote ? connection.remoteAuthority : void 0,
    path: URI.file($nc(folderPrefix, filePath)).path
  });
  let content;
  try {
    content = await fileService.readFile(resource);
  } catch (e) {
    if (e instanceof $Fm && e.fileOperationResult === 1) {
      return void 0;
    }
    throw e;
  }
  if (content === void 0) {
    return void 0;
  }
  return {
    resource,
    content: content.value.toString()
  };
}

// out-build/vs/platform/quickinput/browser/quickPickPin.js
var pinButtonClass = ThemeIcon.asClassName($6l.pin);
var pinnedButtonClass = ThemeIcon.asClassName($6l.pinned);
var buttonClasses = [pinButtonClass, pinnedButtonClass];
function $lgc(storageService, storageKey, quickPick, filterDuplicates) {
  const itemsWithoutPinned = quickPick.items;
  let itemsWithPinned = _formatPinnedItems(storageKey, quickPick, storageService, void 0, filterDuplicates);
  const disposables = new $2c();
  disposables.add(quickPick.onDidTriggerItemButton(async (buttonEvent) => {
    const expectedButton = buttonEvent.button.iconClass && buttonClasses.includes(buttonEvent.button.iconClass);
    if (expectedButton) {
      quickPick.items = itemsWithoutPinned;
      itemsWithPinned = _formatPinnedItems(storageKey, quickPick, storageService, buttonEvent.item, filterDuplicates);
      quickPick.items = quickPick.value ? itemsWithoutPinned : itemsWithPinned;
    }
  }));
  disposables.add(quickPick.onDidChangeValue(async (value) => {
    if (quickPick.items === itemsWithPinned && value) {
      quickPick.items = itemsWithoutPinned;
    } else if (quickPick.items === itemsWithoutPinned && !value) {
      quickPick.items = itemsWithPinned;
    }
  }));
  quickPick.items = quickPick.value ? itemsWithoutPinned : itemsWithPinned;
  quickPick.show();
  return disposables;
}
function _formatPinnedItems(storageKey, quickPick, storageService, changedItem, filterDuplicates) {
  const formattedItems = [];
  let pinnedItems;
  if (changedItem) {
    pinnedItems = updatePinnedItems(storageKey, changedItem, storageService);
  } else {
    pinnedItems = getPinnedItems(storageKey, storageService);
  }
  if (pinnedItems.length) {
    formattedItems.push({ type: "separator", label: localize(2079, null) });
  }
  const pinnedIds = /* @__PURE__ */ new Set();
  for (const itemToFind of pinnedItems) {
    const itemToPin = quickPick.items.find((item) => itemsMatch(item, itemToFind));
    if (itemToPin) {
      const pinnedItemId = getItemIdentifier(itemToPin);
      const pinnedItem = { ...itemToPin };
      if (!filterDuplicates || !pinnedIds.has(pinnedItemId)) {
        pinnedIds.add(pinnedItemId);
        updateButtons(pinnedItem, false);
        formattedItems.push(pinnedItem);
      }
    }
  }
  for (const item of quickPick.items) {
    updateButtons(item, true);
    formattedItems.push(item);
  }
  return formattedItems;
}
function getItemIdentifier(item) {
  return item.type === "separator" ? "" : item.id || `${item.label}${item.description}${item.detail}}`;
}
function updateButtons(item, removePin) {
  if (item.type === "separator") {
    return;
  }
  const newButtons = item.buttons?.filter((button) => button.iconClass && !buttonClasses.includes(button.iconClass)) ?? [];
  newButtons.unshift({
    iconClass: removePin ? pinButtonClass : pinnedButtonClass,
    tooltip: removePin ? localize(2080, null) : localize(2081, null),
    alwaysVisible: false
  });
  item.buttons = newButtons;
}
function itemsMatch(itemA, itemB) {
  return getItemIdentifier(itemA) === getItemIdentifier(itemB);
}
function updatePinnedItems(storageKey, changedItem, storageService) {
  const removePin = changedItem.buttons?.find((b) => b.iconClass === pinnedButtonClass);
  let items = getPinnedItems(storageKey, storageService);
  if (removePin) {
    items = items.filter((item) => getItemIdentifier(item) !== getItemIdentifier(changedItem));
  } else {
    items.push(changedItem);
  }
  storageService.store(
    storageKey,
    JSON.stringify(items),
    1,
    1
    /* StorageTarget.MACHINE */
  );
  return items;
}
function getPinnedItems(storageKey, storageService) {
  const items = storageService.get(
    storageKey,
    1
    /* StorageScope.WORKSPACE */
  );
  return items ? JSON.parse(items) : [];
}

// out-build/vs/workbench/contrib/terminalContrib/history/browser/terminalRunRecentQuickPick.js
var TerminalOutputProvider_1;
async function $mgc(accessor, instance2, terminalInRunCommandPicker, type, filterMode, value) {
  if (!instance2.xterm) {
    return;
  }
  const accessibleViewService = accessor.get($shb);
  const editorService = accessor.get($mJ);
  const instantiationService = accessor.get($Pk);
  const quickInputService = accessor.get($1M);
  const storageService = accessor.get($jv);
  const runRecentStorageKey = `${"terminal.pinnedRecentCommands"}.${instance2.shellType}`;
  let placeholder;
  let items = [];
  const commandMap = /* @__PURE__ */ new Set();
  const removeFromCommandHistoryButton = {
    iconClass: ThemeIcon.asClassName($TPb),
    tooltip: localize(10913, null)
  };
  const commandOutputButton = {
    iconClass: ThemeIcon.asClassName($UPb),
    tooltip: localize(10914, null),
    alwaysVisible: false
  };
  const openResourceButtons = [];
  if (type === "command") {
    let formatLabel2 = function(label3) {
      return label3.replace(/\r?\n/g, "\u23CE").replace(/\s\s\s+/g, "\u22EF");
    };
    var formatLabel = formatLabel2;
    placeholder = $m ? localize(10915, null) : localize(10916, null);
    const cmdDetection = instance2.capabilities.get(
      2
      /* TerminalCapability.CommandDetection */
    );
    const commands2 = cmdDetection?.commands;
    const executingCommand = cmdDetection?.executingCommand;
    if (executingCommand) {
      commandMap.add(executingCommand);
    }
    if (commands2 && commands2.length > 0) {
      for (const entry of commands2) {
        const label3 = entry.command.trim();
        if (label3.length === 0 || commandMap.has(label3)) {
          continue;
        }
        let description = $qY(entry.cwd, instance2.userHome, instance2.os === 1 ? "\\" : "/");
        if (entry.exitCode) {
          if (entry.exitCode === -1) {
            description += " failed";
          } else {
            description += ` exitCode: ${entry.exitCode}`;
          }
        }
        description = description.trim();
        const buttons = [commandOutputButton];
        const lastItem = items.length > 0 ? items[items.length - 1] : void 0;
        if (lastItem?.type !== "separator" && lastItem?.label === label3) {
          lastItem.id = entry.timestamp.toString();
          lastItem.description = description;
          continue;
        }
        items.push({
          label: formatLabel2(label3),
          rawLabel: label3,
          description,
          id: entry.timestamp.toString(),
          command: entry,
          buttons: entry.hasOutput() ? buttons : void 0
        });
        commandMap.add(label3);
      }
      items = items.reverse();
    }
    if (executingCommand) {
      items.unshift({
        label: formatLabel2(executingCommand),
        rawLabel: executingCommand,
        description: cmdDetection.cwd
      });
    }
    if (items.length > 0) {
      items.unshift({
        type: "separator",
        buttons: [],
        // HACK: Force full sized separators as there's no flag currently
        label: $Kec.currentSessionCategory
      });
    }
    const history = instantiationService.invokeFunction($bgc);
    const previousSessionItems = [];
    for (const [label3, info] of history.entries) {
      if (!commandMap.has(label3) && info.shellType === instance2.shellType) {
        previousSessionItems.unshift({
          label: formatLabel2(label3),
          rawLabel: label3,
          buttons: [removeFromCommandHistoryButton]
        });
        commandMap.add(label3);
      }
    }
    if (previousSessionItems.length > 0) {
      items.push({
        type: "separator",
        buttons: [],
        // HACK: Force full sized separators as there's no flag currently
        label: $Kec.previousSessionCategory
      }, ...previousSessionItems);
    }
    const shellFileHistory2 = await instantiationService.invokeFunction($dgc, instance2.shellType);
    if (shellFileHistory2 !== void 0) {
      const dedupedShellFileItems = [];
      for (const label3 of shellFileHistory2.commands) {
        if (!commandMap.has(label3)) {
          dedupedShellFileItems.unshift({
            label: formatLabel2(label3),
            rawLabel: label3
          });
        }
      }
      if (dedupedShellFileItems.length > 0) {
        const button = {
          iconClass: ThemeIcon.asClassName($WPb),
          tooltip: localize(10917, null),
          alwaysVisible: false,
          resource: shellFileHistory2.sourceResource
        };
        openResourceButtons.push(button);
        items.push({
          type: "separator",
          buttons: [button],
          label: localize(10918, null, instance2.shellType),
          description: shellFileHistory2.sourceLabel
        }, ...dedupedShellFileItems);
      }
    }
  } else {
    placeholder = $m ? localize(10919, null) : localize(10920, null);
    const cwds = instance2.capabilities.get(
      0
      /* TerminalCapability.CwdDetection */
    )?.cwds || [];
    if (cwds && cwds.length > 0) {
      for (const label3 of cwds) {
        items.push({ label: label3, rawLabel: label3 });
      }
      items = items.reverse();
      items.unshift({ type: "separator", label: $Kec.currentSessionCategory });
    }
    const history = instantiationService.invokeFunction($agc);
    const previousSessionItems = [];
    for (const [label3, info] of history.entries) {
      if ((info === null || info.remoteAuthority === instance2.remoteAuthority) && !cwds.includes(label3)) {
        previousSessionItems.unshift({
          label: label3,
          rawLabel: label3,
          buttons: [removeFromCommandHistoryButton]
        });
      }
    }
    if (previousSessionItems.length > 0) {
      items.push({ type: "separator", label: $Kec.previousSessionCategory }, ...previousSessionItems);
    }
  }
  if (items.length === 0) {
    return;
  }
  const disposables = new $2c();
  const fuzzySearchToggle = disposables.add(new $Q1({
    title: "Fuzzy search",
    icon: $VPb,
    isChecked: filterMode === "fuzzy",
    inputActiveOptionBorder: $Zn($Aq),
    inputActiveOptionForeground: $Zn($Dq),
    inputActiveOptionBackground: $Zn($Cq)
  }));
  disposables.add(fuzzySearchToggle.onChange(() => {
    instantiationService.invokeFunction($mgc, instance2, terminalInRunCommandPicker, type, fuzzySearchToggle.checked ? "fuzzy" : "contiguous", quickPick.value);
  }));
  const outputProvider = disposables.add(instantiationService.createInstance(TerminalOutputProvider));
  const quickPick = disposables.add(quickInputService.createQuickPick({ useSeparators: true }));
  const originalItems = items;
  quickPick.items = [...originalItems];
  quickPick.sortByLabel = false;
  quickPick.placeholder = placeholder;
  quickPick.matchOnLabelMode = filterMode || "contiguous";
  quickPick.toggles = [fuzzySearchToggle];
  disposables.add(quickPick.onDidTriggerItemButton(async (e) => {
    if (e.button === removeFromCommandHistoryButton) {
      if (type === "command") {
        instantiationService.invokeFunction($bgc)?.remove(e.item.label);
      } else {
        instantiationService.invokeFunction($agc)?.remove(e.item.label);
      }
    } else if (e.button === commandOutputButton) {
      const selectedCommand = e.item.command;
      const output = selectedCommand?.getOutput();
      if (output && selectedCommand?.command) {
        const textContent = await outputProvider.provideTextContent(URI.from({
          scheme: TerminalOutputProvider.scheme,
          path: `${selectedCommand.command}... ${$Qu(selectedCommand.timestamp, true)}`,
          fragment: output,
          query: `terminal-output-${selectedCommand.timestamp}-${instance2.instanceId}`
        }));
        if (textContent) {
          await editorService.openEditor({
            resource: textContent.uri
          });
        }
      }
    }
    await instantiationService.invokeFunction($mgc, instance2, terminalInRunCommandPicker, type, filterMode, value);
  }));
  disposables.add(quickPick.onDidTriggerSeparatorButton(async (e) => {
    const resource = openResourceButtons.find((openResourceButton) => e.button === openResourceButton)?.resource;
    if (resource) {
      await editorService.openEditor({
        resource
      });
    }
  }));
  disposables.add(quickPick.onDidChangeValue(async (value2) => {
    if (!value2) {
      await instantiationService.invokeFunction($mgc, instance2, terminalInRunCommandPicker, type, filterMode, value2);
    }
  }));
  let terminalScrollStateSaved = false;
  function restoreScrollState() {
    terminalScrollStateSaved = false;
    instance2.xterm?.markTracker.restoreScrollState();
    instance2.xterm?.markTracker.clear();
  }
  disposables.add(quickPick.onDidChangeActive(async () => {
    const xterm = instance2.xterm;
    if (!xterm) {
      return;
    }
    const [item] = quickPick.activeItems;
    if (!item) {
      return;
    }
    if ("command" in item && item.command && item.command.marker) {
      if (!terminalScrollStateSaved) {
        xterm.markTracker.saveScrollState();
        terminalScrollStateSaved = true;
      }
      const promptRowCount = item.command.getPromptRowCount();
      const commandRowCount = item.command.getCommandRowCount();
      xterm.markTracker.revealRange({
        start: {
          x: 1,
          y: item.command.marker.line - (promptRowCount - 1) + 1
        },
        end: {
          x: instance2.cols,
          y: item.command.marker.line + (commandRowCount - 1) + 1
        }
      });
    } else {
      restoreScrollState();
    }
  }));
  disposables.add(quickPick.onDidAccept(async () => {
    const result = quickPick.activeItems[0];
    let text2;
    if (type === "cwd") {
      text2 = `cd ${await instance2.preparePathForShell(result.rawLabel)}`;
    } else {
      text2 = result.rawLabel;
    }
    quickPick.hide();
    instance2.runCommand(text2, !quickPick.keyMods.alt);
    if (quickPick.keyMods.alt) {
      instance2.focus();
    }
    restoreScrollState();
  }));
  disposables.add(quickPick.onDidHide(() => restoreScrollState()));
  if (value) {
    quickPick.value = value;
  }
  return new Promise((r2) => {
    terminalInRunCommandPicker.set(true);
    disposables.add($lgc(storageService, runRecentStorageKey, quickPick, true));
    disposables.add(quickPick.onDidHide(() => {
      terminalInRunCommandPicker.set(false);
      accessibleViewService.showLastProvider(
        "terminal"
        /* AccessibleViewProviderId.Terminal */
      );
      r2();
      disposables.dispose();
    }));
  });
}
var TerminalOutputProvider = class TerminalOutputProvider2 extends $3c {
  static {
    TerminalOutputProvider_1 = this;
  }
  static {
    this.scheme = "TERMINAL_OUTPUT";
  }
  constructor(textModelResolverService, a) {
    super();
    this.a = a;
    this.B(textModelResolverService.registerTextModelContentProvider(TerminalOutputProvider_1.scheme, this));
  }
  async provideTextContent(resource) {
    const existing = this.a.getModel(resource);
    if (existing && !existing.isDisposed()) {
      return existing;
    }
    return this.a.createModel(resource.fragment, null, resource, false);
  }
};
TerminalOutputProvider = TerminalOutputProvider_1 = __decorate([
  __param(0, $oG),
  __param(1, $sG)
], TerminalOutputProvider);

// out-build/vs/workbench/contrib/terminalContrib/history/browser/terminal.history.contribution.js
var TerminalHistoryContribution_1;
var TerminalHistoryContribution = class TerminalHistoryContribution2 extends $3c {
  static {
    TerminalHistoryContribution_1 = this;
  }
  static {
    this.ID = "terminal.history";
  }
  static get(instance2) {
    return instance2.getContribution(TerminalHistoryContribution_1.ID);
  }
  constructor(b, contextKeyService, f) {
    super();
    this.b = b;
    this.f = f;
    this.a = TerminalContextKeys.inTerminalRunCommandPicker.bindTo(contextKeyService);
    this.B(b.instance.capabilities.onDidAddCapabilityType((e) => {
      switch (e) {
        case 0: {
          b.instance.capabilities.get(
            0
            /* TerminalCapability.CwdDetection */
          )?.onDidChangeCwd((e2) => {
            this.f.invokeFunction($agc)?.add(e2, { remoteAuthority: b.instance.remoteAuthority });
          });
          break;
        }
        case 2: {
          b.instance.capabilities.get(
            2
            /* TerminalCapability.CommandDetection */
          )?.onCommandFinished((e2) => {
            if (e2.command.trim().length > 0) {
              this.f.invokeFunction($bgc)?.add(e2.command, { shellType: b.instance.shellType });
            }
          });
          break;
        }
      }
    }));
  }
  /**
   * Triggers a quick pick that displays recent commands or cwds. Selecting one will
   * rerun it in the active terminal.
   */
  async runRecent(type, filterMode, value) {
    return this.f.invokeFunction($mgc, this.b.instance, this.a, type, filterMode, value);
  }
};
TerminalHistoryContribution = TerminalHistoryContribution_1 = __decorate([
  __param(1, $on),
  __param(2, $Pk)
], TerminalHistoryContribution);
$Y0b(TerminalHistoryContribution.ID, TerminalHistoryContribution);
var precondition = $7m.or(TerminalContextKeys.processSupported, TerminalContextKeys.terminalHasBeenCreated);
$Uec({
  id: "workbench.action.terminal.clearPreviousSessionHistory",
  title: localize2(10909, "Clear Previous Session History"),
  precondition,
  run: async (c, accessor) => {
    $bgc(accessor).clear();
    $egc();
  }
});
$Wec({
  id: "workbench.action.terminal.goToRecentDirectory",
  title: localize2(10910, "Go to Recent Directory..."),
  metadata: {
    description: localize2(10911, "Goes to a recent folder")
  },
  precondition,
  keybinding: {
    primary: 2048 | 37,
    when: TerminalContextKeys.focus,
    weight: 200
    /* KeybindingWeight.WorkbenchContrib */
  },
  run: async (activeInstance, c) => {
    const history = TerminalHistoryContribution.get(activeInstance);
    if (!history) {
      return;
    }
    await history.runRecent("cwd");
    if (activeInstance?.target === TerminalLocation2.Editor) {
      await c.editorService.revealActiveEditor();
    } else {
      await c.groupService.showPanel(false);
    }
  }
});
$Wec({
  id: "workbench.action.terminal.runRecentCommand",
  title: localize2(10912, "Run Recent Command..."),
  precondition,
  keybinding: [
    {
      primary: 2048 | 48,
      when: $7m.and($OD, $7m.or(TerminalContextKeys.focus, $7m.and($osb, $tsb.isEqualTo(
        "terminal"
        /* AccessibleViewProviderId.Terminal */
      )))),
      weight: 200
      /* KeybindingWeight.WorkbenchContrib */
    },
    {
      primary: 2048 | 512 | 48,
      mac: {
        primary: 256 | 512 | 48
        /* KeyCode.KeyR */
      },
      when: $7m.and(TerminalContextKeys.focus, $OD.negate()),
      weight: 200
      /* KeybindingWeight.WorkbenchContrib */
    }
  ],
  run: async (activeInstance, c) => {
    const history = TerminalHistoryContribution.get(activeInstance);
    if (!history) {
      return;
    }
    await history.runRecent("command");
    if (activeInstance?.target === TerminalLocation2.Editor) {
      await c.editorService.revealActiveEditor();
    } else {
      await c.groupService.showPanel(false);
    }
  }
});

// out-build/vs/workbench/contrib/terminalContrib/links/browser/terminalLinkHelpers.js
function $ngc(lines, bufferWidth, range, startLine) {
  const bufferRange = {
    start: {
      x: range.startColumn,
      y: range.startLineNumber + startLine
    },
    end: {
      x: range.endColumn - 1,
      y: range.endLineNumber + startLine
    }
  };
  let startOffset = 0;
  const startWrappedLineCount = Math.ceil(range.startColumn / bufferWidth);
  for (let y = 0; y < Math.min(startWrappedLineCount); y++) {
    const lineLength = Math.min(bufferWidth, range.startColumn - 1 - y * bufferWidth);
    let lineOffset = 0;
    const line = lines[y];
    if (!line) {
      break;
    }
    for (let x = 0; x < Math.min(bufferWidth, lineLength + lineOffset); x++) {
      const cell = line.getCell(x);
      if (!cell) {
        break;
      }
      const width2 = cell.getWidth();
      if (width2 === 2) {
        lineOffset++;
      }
      const char = cell.getChars();
      if (char.length > 1) {
        lineOffset -= char.length - 1;
      }
    }
    startOffset += lineOffset;
  }
  let endOffset = 0;
  const endWrappedLineCount = Math.ceil(range.endColumn / bufferWidth);
  for (let y = Math.max(0, startWrappedLineCount - 1); y < endWrappedLineCount; y++) {
    const start = y === startWrappedLineCount - 1 ? (range.startColumn - 1 + startOffset) % bufferWidth : 0;
    const lineLength = Math.min(bufferWidth, range.endColumn + startOffset - y * bufferWidth);
    let lineOffset = 0;
    const line = lines[y];
    if (!line) {
      break;
    }
    for (let x = start; x < Math.min(bufferWidth, lineLength + lineOffset); x++) {
      const cell = line.getCell(x);
      if (!cell) {
        break;
      }
      const width2 = cell.getWidth();
      const chars = cell.getChars();
      if (width2 === 2) {
        lineOffset++;
      }
      if (x === bufferWidth - 1 && chars === "") {
        lineOffset++;
      }
      if (chars.length > 1) {
        lineOffset -= chars.length - 1;
      }
    }
    endOffset += lineOffset;
  }
  bufferRange.start.x += startOffset;
  bufferRange.end.x += startOffset + endOffset;
  while (bufferRange.start.x > bufferWidth) {
    bufferRange.start.x -= bufferWidth;
    bufferRange.start.y++;
  }
  while (bufferRange.end.x > bufferWidth) {
    bufferRange.end.x -= bufferWidth;
    bufferRange.end.y++;
  }
  return bufferRange;
}
function $ogc(bufferRange, viewportY) {
  return {
    start: {
      x: bufferRange.start.x - 1,
      y: bufferRange.start.y - viewportY - 1
    },
    end: {
      x: bufferRange.end.x - 1,
      y: bufferRange.end.y - viewportY - 1
    }
  };
}
function $pgc(buffer, lineStart, lineEnd, cols) {
  const maxLineLength = Math.max(2048, cols * 2);
  lineEnd = Math.min(lineEnd, lineStart + maxLineLength);
  let content = "";
  for (let i2 = lineStart; i2 <= lineEnd; i2++) {
    const line = buffer.getLine(i2);
    if (line) {
      content += line.translateToString(true, 0, cols);
    }
  }
  return content;
}
function $qgc(buffer, lineStart, lineEnd, cols) {
  let bufferRangeStart = void 0;
  let lastFgAttr = -1;
  let lastBgAttr = -1;
  const ranges = [];
  for (let y = lineStart; y <= lineEnd; y++) {
    const line = buffer.getLine(y);
    if (!line) {
      continue;
    }
    for (let x = 0; x < cols; x++) {
      const cell = line.getCell(x);
      if (!cell) {
        break;
      }
      const thisFgAttr = cell.isBold() | cell.isInverse() | cell.isStrikethrough() | cell.isUnderline();
      const thisBgAttr = cell.isDim() | cell.isItalic();
      if (lastFgAttr === -1 || lastBgAttr === -1) {
        bufferRangeStart = { x, y };
      } else {
        if (lastFgAttr !== thisFgAttr || lastBgAttr !== thisBgAttr) {
          const bufferRangeEnd = { x, y };
          ranges.push({
            start: bufferRangeStart,
            end: bufferRangeEnd
          });
          bufferRangeStart = { x, y };
        }
      }
      lastFgAttr = thisFgAttr;
      lastBgAttr = thisBgAttr;
    }
  }
  return ranges;
}
function $rgc(capabilities, y, text2, osPath, logService) {
  const cwd2 = capabilities.get(
    2
    /* TerminalCapability.CommandDetection */
  )?.getCwdForLine(y);
  logService.trace("terminalLinkHelpers#updateLinkWithRelativeCwd cwd", cwd2);
  if (!cwd2) {
    return void 0;
  }
  const result = [];
  const sep2 = osPath.sep;
  if (!text2.includes(sep2)) {
    result.push(osPath.resolve(cwd2 + sep2 + text2));
  } else {
    let commonDirs = 0;
    let i2 = 0;
    const cwdPath = cwd2.split(sep2).reverse();
    const linkPath = text2.split(sep2);
    while (i2 < cwdPath.length) {
      result.push(osPath.resolve(cwd2 + sep2 + linkPath.slice(commonDirs).join(sep2)));
      if (cwdPath[i2] === linkPath[i2]) {
        commonDirs++;
      } else {
        break;
      }
      i2++;
    }
  }
  return result;
}
function $sgc(os) {
  return os === 1 ? $jc : $kc;
}

// out-build/vs/workbench/contrib/terminalContrib/links/browser/terminalExternalLinkDetector.js
var $tgc = class {
  constructor(id2, xterm, a) {
    this.id = id2;
    this.xterm = xterm;
    this.a = a;
    this.maxLinkLength = 2e3;
  }
  async detect(lines, startLine, endLine) {
    const text2 = $pgc(this.xterm.buffer.active, startLine, endLine, this.xterm.cols);
    if (text2 === "" || text2.length > this.maxLinkLength) {
      return [];
    }
    const externalLinks = await this.a(text2);
    if (!externalLinks) {
      return [];
    }
    const result = externalLinks.map((link2) => {
      const bufferRange = $ngc(lines, this.xterm.cols, {
        startColumn: link2.startIndex + 1,
        startLineNumber: 1,
        endColumn: link2.startIndex + link2.length + 1,
        endLineNumber: 1
      }, startLine);
      const matchingText = text2.substring(link2.startIndex, link2.startIndex + link2.length) || "";
      const l = {
        text: matchingText,
        label: link2.label,
        bufferRange,
        type: { id: this.id },
        activate: link2.activate
      };
      return l;
    });
    return result;
  }
};

// out-build/vs/workbench/contrib/terminalContrib/links/browser/terminalLink.js
var $ugc = class $ugc2 extends $3c {
  get onInvalidated() {
    return this.c.event;
  }
  get type() {
    return this.n;
  }
  constructor(f, range, text2, uri, parsedLink, actions, g, h3, j, m, label3, n, r2) {
    super();
    this.f = f;
    this.range = range;
    this.text = text2;
    this.uri = uri;
    this.parsedLink = parsedLink;
    this.actions = actions;
    this.g = g;
    this.h = h3;
    this.j = j;
    this.m = m;
    this.label = label3;
    this.n = n;
    this.r = r2;
    this.a = this.B(new $4c());
    this.b = this.B(new $4c());
    this.c = new $ze();
    this.decorations = {
      pointerCursor: false,
      underline: this.m
    };
  }
  activate(event, text2) {
    this.h(event, text2);
  }
  hover(event, text2) {
    const w = getWindow(event);
    const d = w.document;
    const hoverListeners = this.b.value = new $2c();
    hoverListeners.add($_i(d, "keydown", (e) => {
      if (!e.repeat && this.u(e)) {
        this.s();
      }
    }));
    hoverListeners.add($_i(d, "keyup", (e) => {
      if (!e.repeat && !this.u(e)) {
        this.t();
      }
    }));
    hoverListeners.add(this.f.onRender((e) => {
      const viewportRangeY = this.range.start.y - this.g;
      if (viewportRangeY >= e.start && viewportRangeY <= e.end) {
        this.c.fire();
      }
    }));
    if (this.m) {
      this.a.value = new $8h(() => {
        this.j(this, $ogc(this.range, this.g), this.m ? () => this.s() : void 0, this.m ? () => this.t() : void 0);
        this.a.clear();
      }, this.r.getValue("workbench.hover.delay"));
      this.a.value.schedule();
    }
    const origin = { x: event.pageX, y: event.pageY };
    hoverListeners.add($_i(d, $7j.MOUSE_MOVE, (e) => {
      if (this.u(e)) {
        this.s();
      } else {
        this.t();
      }
      if (Math.abs(e.pageX - origin.x) > w.devicePixelRatio * 2 || Math.abs(e.pageY - origin.y) > w.devicePixelRatio * 2) {
        origin.x = e.pageX;
        origin.y = e.pageY;
        this.a.value?.schedule();
      }
    }));
  }
  leave() {
    this.b.clear();
    this.a.clear();
  }
  s() {
    if (!this.decorations.pointerCursor) {
      this.decorations.pointerCursor = true;
    }
    if (!this.decorations.underline) {
      this.decorations.underline = true;
    }
  }
  t() {
    if (this.decorations.pointerCursor) {
      this.decorations.pointerCursor = false;
    }
    if (this.decorations.underline !== this.m) {
      this.decorations.underline = this.m;
    }
  }
  u(event) {
    const multiCursorModifier2 = this.r.getValue("editor.multiCursorModifier");
    if (multiCursorModifier2 === "ctrlCmd") {
      return !!event.altKey;
    }
    return $m ? event.metaKey : event.ctrlKey;
  }
};
$ugc = __decorate([
  __param(12, $kl)
], $ugc);

// out-build/vs/workbench/contrib/terminalContrib/links/browser/terminalLinkDetectorAdapter.js
var $vgc = class $vgc2 extends $3c {
  constructor(f, g) {
    super();
    this.f = f;
    this.g = g;
    this.b = this.B(new $ze());
    this.onDidActivateLink = this.b.event;
    this.c = this.B(new $ze());
    this.onDidShowHover = this.c.event;
    this.h = /* @__PURE__ */ new Map();
  }
  async provideLinks(bufferLineNumber, callback) {
    let activeRequest = this.h.get(bufferLineNumber);
    if (activeRequest) {
      await activeRequest;
      callback(this.a);
      return;
    }
    if (this.a) {
      for (const link2 of this.a) {
        link2.dispose();
      }
    }
    activeRequest = this.j(bufferLineNumber);
    this.h.set(bufferLineNumber, activeRequest);
    this.a = await activeRequest;
    this.h.delete(bufferLineNumber);
    callback(this.a);
  }
  async j(bufferLineNumber) {
    const links = [];
    let startLine = bufferLineNumber - 1;
    let endLine = startLine;
    const lines = [
      this.f.xterm.buffer.active.getLine(startLine)
    ];
    const maxCharacterContext = Math.max(this.f.maxLinkLength, this.f.xterm.cols);
    const maxLineContext = Math.ceil(maxCharacterContext / this.f.xterm.cols);
    const minStartLine = Math.max(startLine - maxLineContext, 0);
    const maxEndLine = Math.min(endLine + maxLineContext, this.f.xterm.buffer.active.length);
    while (startLine >= minStartLine && this.f.xterm.buffer.active.getLine(startLine)?.isWrapped) {
      lines.unshift(this.f.xterm.buffer.active.getLine(startLine - 1));
      startLine--;
    }
    while (endLine < maxEndLine && this.f.xterm.buffer.active.getLine(endLine + 1)?.isWrapped) {
      lines.push(this.f.xterm.buffer.active.getLine(endLine + 1));
      endLine++;
    }
    const detectedLinks = await this.f.detect(lines, startLine, endLine);
    for (const link2 of detectedLinks) {
      links.push(this.m(link2, async (event) => this.b.fire({ link: link2, event })));
    }
    return links;
  }
  m(l, activateCallback) {
    if (!l.disableTrimColon && l.text.length > 0 && l.text.charAt(l.text.length - 1) === ":") {
      l.text = l.text.slice(0, -1);
      l.bufferRange.end.x--;
    }
    return this.g.createInstance(
      $ugc,
      this.f.xterm,
      l.bufferRange,
      l.text,
      l.uri,
      l.parsedLink,
      l.actions,
      this.f.xterm.buffer.active.viewportY,
      activateCallback,
      (link2, viewportRange, modifierDownCallback, modifierUpCallback) => this.c.fire({
        link: link2,
        viewportRange,
        modifierDownCallback,
        modifierUpCallback
      }),
      l.type !== "Search",
      // Only search is low confidence
      l.label || this.n(l.type),
      l.type
    );
  }
  n(type) {
    switch (type) {
      case "Search":
        return localize(10926, null);
      case "LocalFile":
        return localize(10927, null);
      case "LocalFolderInWorkspace":
        return localize(10928, null);
      case "LocalFolderOutsideWorkspace":
        return localize(10929, null);
      case "Url":
      default:
        return localize(10930, null);
    }
  }
};
$vgc = __decorate([
  __param(1, $Pk)
], $vgc);

// out-build/vs/workbench/contrib/terminalContrib/links/browser/terminalLinkParsing.js
var linkSuffixRegexEol = new $sf(() => generateLinkSuffixRegex(true));
var linkSuffixRegex = new $sf(() => generateLinkSuffixRegex(false));
function generateLinkSuffixRegex(eolOnly) {
  let ri = 0;
  let ci = 0;
  let rei = 0;
  let cei = 0;
  function r2() {
    return `(?<row${ri++}>\\d+)`;
  }
  function c() {
    return `(?<col${ci++}>\\d+)`;
  }
  function re() {
    return `(?<rowEnd${rei++}>\\d+)`;
  }
  function ce() {
    return `(?<colEnd${cei++}>\\d+)`;
  }
  const eolSuffix = eolOnly ? "$" : "";
  const lineAndColumnRegexClauses = [
    // foo:339
    // foo:339:12
    // foo:339:12-789
    // foo:339:12-341.789
    // foo:339.12
    // foo 339
    // foo 339:12                              [#140780]
    // foo 339.12
    // foo#339
    // foo#339:12                              [#190288]
    // foo#339.12
    // foo, 339                                [#217927]
    // "foo",339
    // "foo",339:12
    // "foo",339.12
    // "foo",339.12-789
    // "foo",339.12-341.789
    `(?::|#| |['"],|, )${r2()}([:.]${c()}(?:-(?:${re()}\\.)?${ce()})?)?` + eolSuffix,
    // The quotes below are optional           [#171652]
    // "foo", line 339                         [#40468]
    // "foo", line 339, col 12
    // "foo", line 339, column 12
    // "foo":line 339
    // "foo":line 339, col 12
    // "foo":line 339, column 12
    // "foo": line 339
    // "foo": line 339, col 12
    // "foo": line 339, column 12
    // "foo" on line 339
    // "foo" on line 339, col 12
    // "foo" on line 339, column 12
    // "foo" line 339 column 12
    // "foo", line 339, character 12           [#171880]
    // "foo", line 339, characters 12-789      [#171880]
    // "foo", lines 339-341                    [#171880]
    // "foo", lines 339-341, characters 12-789 [#178287]
    `['"]?(?:,? |: ?| on )lines? ${r2()}(?:-${re()})?(?:,? (?:col(?:umn)?|characters?) ${c()}(?:-${ce()})?)?` + eolSuffix,
    // () and [] are interchangeable
    // foo(339)
    // foo(339,12)
    // foo(339, 12)
    // foo (339)
    // foo (339,12)
    // foo (339, 12)
    // foo: (339)
    // foo: (339,12)
    // foo: (339, 12)
    // foo(339:12)                             [#229842]
    // foo (339:12)                            [#229842]
    `:? ?[\\[\\(]${r2()}(?:(?:, ?|:)${c()})?[\\]\\)]` + eolSuffix
  ];
  const suffixClause = lineAndColumnRegexClauses.join("|").replace(/ /g, `[${"\xA0"} ]`);
  return new RegExp(`(${suffixClause})`, eolOnly ? void 0 : "g");
}
function $mRb(link2) {
  const suffix = $pRb(link2)?.suffix;
  if (!suffix) {
    return link2;
  }
  return link2.substring(0, suffix.index);
}
function $nRb(link2) {
  const start = link2.startsWith("\\\\?\\") ? 4 : 0;
  const index = link2.indexOf("?", start);
  if (index === -1) {
    return link2;
  }
  return link2.substring(0, index);
}
function $oRb(line) {
  let match;
  const results = [];
  linkSuffixRegex.value.lastIndex = 0;
  while ((match = linkSuffixRegex.value.exec(line)) !== null) {
    const suffix = $qRb(match);
    if (suffix === null) {
      break;
    }
    results.push(suffix);
  }
  return results;
}
function $pRb(link2) {
  return $qRb(linkSuffixRegexEol.value.exec(link2));
}
function $qRb(match) {
  const groups = match?.groups;
  if (!groups || match.length < 1) {
    return null;
  }
  return {
    row: parseIntOptional(groups.row0 || groups.row1 || groups.row2),
    col: parseIntOptional(groups.col0 || groups.col1 || groups.col2),
    rowEnd: parseIntOptional(groups.rowEnd0 || groups.rowEnd1 || groups.rowEnd2),
    colEnd: parseIntOptional(groups.colEnd0 || groups.colEnd1 || groups.colEnd2),
    suffix: { index: match.index, text: match[0] }
  };
}
function parseIntOptional(value) {
  if (value === void 0) {
    return value;
  }
  return parseInt(value);
}
var linkWithSuffixPathCharacters = /(?<path>(?:file:\/\/\/)?[^\s\|<>\[\({][^\s\|<>]*)$/;
function $rRb(line, os) {
  const results = detectLinksViaSuffix(line);
  const noSuffixPaths = detectPathsNoSuffix(line, os);
  binaryInsertList(results, noSuffixPaths);
  return results;
}
function binaryInsertList(list2, newItems) {
  if (list2.length === 0) {
    list2.push(...newItems);
  }
  for (const item of newItems) {
    binaryInsert(list2, item, 0, list2.length);
  }
}
function binaryInsert(list2, newItem, low, high) {
  if (list2.length === 0) {
    list2.push(newItem);
    return;
  }
  if (low > high) {
    return;
  }
  const mid = Math.floor((low + high) / 2);
  if (mid >= list2.length || newItem.path.index < list2[mid].path.index && (mid === 0 || newItem.path.index > list2[mid - 1].path.index)) {
    if (mid >= list2.length || newItem.path.index + newItem.path.text.length < list2[mid].path.index && (mid === 0 || newItem.path.index > list2[mid - 1].path.index + list2[mid - 1].path.text.length)) {
      list2.splice(mid, 0, newItem);
    }
    return;
  }
  if (newItem.path.index > list2[mid].path.index) {
    binaryInsert(list2, newItem, mid + 1, high);
  } else {
    binaryInsert(list2, newItem, low, mid - 1);
  }
}
function detectLinksViaSuffix(line) {
  const results = [];
  const suffixes = $oRb(line);
  for (const suffix of suffixes) {
    const beforeSuffix = line.substring(0, suffix.suffix.index);
    const possiblePathMatch = beforeSuffix.match(linkWithSuffixPathCharacters);
    if (possiblePathMatch && possiblePathMatch.index !== void 0 && possiblePathMatch.groups?.path) {
      let linkStartIndex = possiblePathMatch.index;
      let path = possiblePathMatch.groups.path;
      let prefix = void 0;
      const prefixMatch = path.match(/^(?<prefix>['"]+)/);
      if (prefixMatch?.groups?.prefix) {
        prefix = {
          index: linkStartIndex,
          text: prefixMatch.groups.prefix
        };
        path = path.substring(prefix.text.length);
        if (path.trim().length === 0) {
          continue;
        }
        if (prefixMatch.groups.prefix.length > 1) {
          if (suffix.suffix.text[0].match(/['"]/) && prefixMatch.groups.prefix[prefixMatch.groups.prefix.length - 1] === suffix.suffix.text[0]) {
            const trimPrefixAmount = prefixMatch.groups.prefix.length - 1;
            prefix.index += trimPrefixAmount;
            prefix.text = prefixMatch.groups.prefix[prefixMatch.groups.prefix.length - 1];
            linkStartIndex += trimPrefixAmount;
          }
        }
      }
      results.push({
        path: {
          index: linkStartIndex + (prefix?.text.length || 0),
          text: path
        },
        prefix,
        suffix
      });
    }
  }
  return results;
}
var RegexPathConstants;
(function(RegexPathConstants2) {
  RegexPathConstants2["PathPrefix"] = "(?:\\.\\.?|\\~|file://)";
  RegexPathConstants2["PathSeparatorClause"] = "\\/";
  RegexPathConstants2["ExcludedPathCharactersClause"] = "[^\\0<>\\?\\s!`&*()'\":;\\\\]";
  RegexPathConstants2["ExcludedStartPathCharactersClause"] = "[^\\0<>\\?\\s!`&*()\\[\\]'\":;\\\\]";
  RegexPathConstants2["WinOtherPathPrefix"] = "\\.\\.?|\\~";
  RegexPathConstants2["WinPathSeparatorClause"] = "(?:\\\\|\\/)";
  RegexPathConstants2["WinExcludedPathCharactersClause"] = "[^\\0<>\\?\\|\\/\\s!`&*()'\":;]";
  RegexPathConstants2["WinExcludedStartPathCharactersClause"] = "[^\\0<>\\?\\|\\/\\s!`&*()\\[\\]'\":;]";
})(RegexPathConstants || (RegexPathConstants = {}));
var unixLocalLinkClause = "(?:(?:" + RegexPathConstants.PathPrefix + "|(?:" + RegexPathConstants.ExcludedStartPathCharactersClause + RegexPathConstants.ExcludedPathCharactersClause + "*))?(?:" + RegexPathConstants.PathSeparatorClause + "(?:" + RegexPathConstants.ExcludedPathCharactersClause + ")+)+)";
var $sRb = "(?:\\\\\\\\\\?\\\\|file:\\/\\/\\/)?[a-zA-Z]:";
var winLocalLinkClause = `(?:(?:(?:${$sRb}|${RegexPathConstants.WinOtherPathPrefix})|(?:` + RegexPathConstants.WinExcludedStartPathCharactersClause + RegexPathConstants.WinExcludedPathCharactersClause + "*))?(?:" + RegexPathConstants.WinPathSeparatorClause + "(?:" + RegexPathConstants.WinExcludedPathCharactersClause + ")+)+)";
function detectPathsNoSuffix(line, os) {
  const results = [];
  const regex = new RegExp(os === 1 ? winLocalLinkClause : unixLocalLinkClause, "g");
  let match;
  while ((match = regex.exec(line)) !== null) {
    let text2 = match[0];
    let index = match.index;
    if (!text2) {
      break;
    }
    if (
      // --- a/foo/bar
      // +++ b/foo/bar
      (line.startsWith("--- a/") || line.startsWith("+++ b/")) && index === 4 || // diff --git a/foo/bar b/foo/bar
      line.startsWith("diff --git") && (text2.startsWith("a/") || text2.startsWith("b/"))
    ) {
      text2 = text2.substring(2);
      index += 2;
    }
    results.push({
      path: {
        index,
        text: text2
      },
      prefix: void 0,
      suffix: void 0
    });
  }
  return results;
}

// out-build/vs/workbench/contrib/terminalContrib/links/browser/terminalLinkOpeners.js
var $wgc = class $wgc2 {
  constructor(a) {
    this.a = a;
  }
  async open(link2) {
    if (!link2.uri) {
      throw new Error("Tried to open file link without a resolved URI");
    }
    const linkSuffix = link2.parsedLink ? link2.parsedLink.suffix : $pRb(link2.text);
    let selection = link2.selection;
    if (!selection) {
      selection = linkSuffix?.row === void 0 ? void 0 : {
        startLineNumber: linkSuffix.row ?? 1,
        startColumn: linkSuffix.col ?? 1,
        endLineNumber: linkSuffix.rowEnd,
        endColumn: linkSuffix.colEnd
      };
    }
    await this.a.openEditor({
      resource: link2.uri,
      options: { pinned: true, selection, revealIfOpened: true }
    });
  }
};
$wgc = __decorate([
  __param(0, $mJ)
], $wgc);
var $xgc = class $xgc2 {
  constructor(a) {
    this.a = a;
  }
  async open(link2) {
    if (!link2.uri) {
      throw new Error("Tried to open folder in workspace link without a resolved URI");
    }
    await this.a.executeCommand("revealInExplorer", link2.uri);
  }
};
$xgc = __decorate([
  __param(0, $sn)
], $xgc);
var $ygc = class $ygc2 {
  constructor(a) {
    this.a = a;
  }
  async open(link2) {
    if (!link2.uri) {
      throw new Error("Tried to open folder in workspace link without a resolved URI");
    }
    this.a.openWindow([{ folderUri: link2.uri }], { forceNewWindow: true });
  }
};
$ygc = __decorate([
  __param(0, $S4)
], $ygc);
var $zgc = class $zgc2 {
  constructor(b, c, d, f, g, h3, instantiationService, i2, j, k, l, m) {
    this.b = b;
    this.c = c;
    this.d = d;
    this.f = f;
    this.g = g;
    this.h = h3;
    this.i = i2;
    this.j = j;
    this.k = k;
    this.l = l;
    this.m = m;
    this.a = instantiationService.createInstance($eT);
  }
  async open(link2) {
    const osPath = $sgc(this.g());
    const pathSeparator = osPath.sep;
    let text2 = link2.text.replace(/^file:\/\/\/?/, "");
    text2 = osPath.normalize(text2).replace(/^(\.+[\\/])+/, "");
    if (link2.contextLine) {
      const parsedLinks = $rRb(link2.contextLine, this.g());
      const matchingParsedLink = parsedLinks.find((parsedLink) => parsedLink.suffix && link2.text.startsWith(parsedLink.path.text));
      if (matchingParsedLink) {
        if (matchingParsedLink.suffix?.row !== void 0) {
          text2 = matchingParsedLink.path.text;
          text2 += `:${matchingParsedLink.suffix.row}`;
          if (matchingParsedLink.suffix?.col !== void 0) {
            text2 += `:${matchingParsedLink.suffix.col}`;
          }
        }
      }
    }
    text2 = text2.replace(/:[^\\/\d][^\d]*$/, "");
    text2 = text2.replace(/\.$/, "");
    this.m.getWorkspace().folders.forEach((folder) => {
      if (text2.substring(0, folder.name.length + 1) === folder.name + pathSeparator) {
        text2 = text2.substring(folder.name.length + 1);
        return;
      }
    });
    let cwdResolvedText = text2;
    if (this.b.has(
      2
      /* TerminalCapability.CommandDetection */
    )) {
      cwdResolvedText = $rgc(this.b, link2.bufferRange.start.y, text2, osPath, this.k)?.[0] || text2;
    }
    if (await this.o(cwdResolvedText, link2)) {
      return;
    }
    if (text2 !== cwdResolvedText) {
      if (await this.o(text2, link2)) {
        return;
      }
    }
    return this.i.quickAccess.show(text2);
  }
  async n(sanitizedLink) {
    const os = this.g();
    const pathModule = $sgc(os);
    const isAbsolute = pathModule.isAbsolute(sanitizedLink);
    let absolutePath = isAbsolute ? sanitizedLink : void 0;
    if (!isAbsolute && this.c.length > 0) {
      absolutePath = pathModule.join(this.c, sanitizedLink);
    }
    let resourceMatch;
    if (absolutePath) {
      let normalizedAbsolutePath = absolutePath;
      if (os === 1) {
        normalizedAbsolutePath = absolutePath.replace(/\\/g, "/");
        if (normalizedAbsolutePath.match(/[a-z]:/i)) {
          normalizedAbsolutePath = `/${normalizedAbsolutePath}`;
        }
      }
      let uri;
      if (this.l.remoteAuthority) {
        uri = URI.from({
          scheme: Schemas.vscodeRemote,
          authority: this.l.remoteAuthority,
          path: normalizedAbsolutePath
        });
      } else {
        uri = URI.file(normalizedAbsolutePath);
      }
      try {
        const fileStat = await this.h.stat(uri);
        resourceMatch = { uri, isDirectory: fileStat.isDirectory };
      } catch {
      }
    }
    if (!resourceMatch) {
      const results = await this.j.fileSearch(this.a.file(this.m.getWorkspace().folders, {
        filePattern: sanitizedLink,
        maxResults: 2
      }));
      if (results.results.length > 0) {
        if (results.results.length === 1) {
          resourceMatch = { uri: results.results[0].resource };
        } else if (!isAbsolute) {
          const results2 = await this.j.fileSearch(this.a.file(this.m.getWorkspace().folders, {
            filePattern: `**/${sanitizedLink}`
          }));
          const exactMatches = results2.results.filter((e) => e.resource.toString().endsWith(sanitizedLink));
          if (exactMatches.length === 1) {
            resourceMatch = { uri: exactMatches[0].resource };
          }
        }
      }
    }
    return resourceMatch;
  }
  async o(text2, link2) {
    const sanitizedLink = text2.replace(/:\d+(:\d+)?$/, "");
    try {
      const result = await this.n(sanitizedLink);
      if (result) {
        const { uri, isDirectory } = result;
        const linkToOpen = {
          // Use the absolute URI's path here so the optional line/col get detected
          text: result.uri.path + (text2.match(/:\d+(:\d+)?$/)?.[0] || ""),
          uri,
          bufferRange: link2.bufferRange,
          type: link2.type
        };
        if (uri) {
          await (isDirectory ? this.f.open(linkToOpen) : this.d.open(linkToOpen));
          return true;
        }
      }
    } catch {
      return false;
    }
    return false;
  }
};
$zgc = __decorate([
  __param(5, $km),
  __param(6, $Pk),
  __param(7, $1M),
  __param(8, $TN),
  __param(9, $8x),
  __param(10, $US),
  __param(11, $Zk)
], $zgc);
var $Agc = class $Agc2 {
  constructor(a, b, c) {
    this.a = a;
    this.b = b;
    this.c = c;
  }
  async open(link2) {
    if (!link2.uri) {
      throw new Error("Tried to open a url without a resolved URI");
    }
    this.b.open(link2.text, {
      allowTunneling: this.a && this.c.getValue("remote.forwardOnOpen"),
      allowContributedOpeners: true,
      openExternal: true
    });
  }
};
$Agc = __decorate([
  __param(1, $O4),
  __param(2, $kl)
], $Agc);

// out-build/vs/workbench/contrib/terminalContrib/links/browser/terminalLocalLinkDetector.js
var Constants21;
(function(Constants27) {
  Constants27[Constants27["MaxLineLength"] = 2e3] = "MaxLineLength";
  Constants27[Constants27["MaxResolvedLinksInLine"] = 10] = "MaxResolvedLinksInLine";
  Constants27[Constants27["MaxResolvedLinkLength"] = 1024] = "MaxResolvedLinkLength";
})(Constants21 || (Constants21 = {}));
var fallbackMatchers = [
  // Python style error: File "<path>", line <line>
  /^ *File (?<link>"(?<path>.+)"(, line (?<line>\d+))?)/,
  // Unknown tool #200166: FILE  <path>:<line>:<col>
  /^ +FILE +(?<link>(?<path>.+)(?::(?<line>\d+)(?::(?<col>\d+))?)?)/,
  // Some C++ compile error formats:
  // C:\foo\bar baz(339) : error ...
  // C:\foo\bar baz(339,12) : error ...
  // C:\foo\bar baz(339, 12) : error ...
  // C:\foo\bar baz(339): error ...       [#178584, Visual Studio CL/NVIDIA CUDA compiler]
  // C:\foo\bar baz(339,12): ...
  // C:\foo\bar baz(339, 12): ...
  /^(?<link>(?<path>.+)\((?<line>\d+)(?:, ?(?<col>\d+))?\)) ?:/,
  // C:\foo/bar baz:339 : error ...
  // C:\foo/bar baz:339:12 : error ...
  // C:\foo/bar baz:339: error ...
  // C:\foo/bar baz:339:12: error ...     [#178584, Clang]
  /^(?<link>(?<path>.+):(?<line>\d+)(?::(?<col>\d+))?) ?:/,
  // Cmd prompt
  /^(?<link>(?<path>.+))>/,
  // The whole line is the path
  /^ *(?<link>(?<path>.+))/
];
var $Bgc = class $Bgc2 {
  static {
    this.id = "local";
  }
  constructor(xterm, a, b, c, d, e, f) {
    this.xterm = xterm;
    this.a = a;
    this.b = b;
    this.c = c;
    this.d = d;
    this.e = e;
    this.f = f;
    this.maxLinkLength = 500;
  }
  async detect(lines, startLine, endLine) {
    const links = [];
    const text2 = $pgc(this.xterm.buffer.active, startLine, endLine, this.xterm.cols);
    if (text2 === "" || text2.length > 2e3) {
      return [];
    }
    let stringIndex = -1;
    let resolvedLinkCount = 0;
    const os = this.b.os || OS;
    const parsedLinks = $rRb(text2, os);
    this.d.trace("terminalLocalLinkDetector#detect text", text2);
    this.d.trace("terminalLocalLinkDetector#detect parsedLinks", parsedLinks);
    for (const parsedLink of parsedLinks) {
      if (parsedLink.path.text.length > 1024) {
        continue;
      }
      const bufferRange = $ngc(lines, this.xterm.cols, {
        startColumn: (parsedLink.prefix?.index ?? parsedLink.path.index) + 1,
        startLineNumber: 1,
        endColumn: parsedLink.path.index + parsedLink.path.text.length + (parsedLink.suffix?.suffix.text.length ?? 0) + 1,
        endLineNumber: 1
      }, startLine);
      const linkCandidates = [];
      const osPath = $sgc(os);
      const isUri = parsedLink.path.text.startsWith("file://");
      if (osPath.isAbsolute(parsedLink.path.text) || parsedLink.path.text.startsWith("~") || isUri) {
        linkCandidates.push(parsedLink.path.text);
      } else {
        if (this.a.has(
          2
          /* TerminalCapability.CommandDetection */
        )) {
          const absolutePath = $rgc(this.a, bufferRange.start.y, parsedLink.path.text, osPath, this.d);
          if (absolutePath) {
            linkCandidates.push(...absolutePath);
          }
        }
        if (linkCandidates.length === 0) {
          linkCandidates.push(parsedLink.path.text);
          if (parsedLink.path.text.match(/^(\.\.[\/\\])+/)) {
            linkCandidates.push(parsedLink.path.text.replace(/^(\.\.[\/\\])+/, ""));
          }
        }
      }
      const specialEndCharRegex = /[\[\]"'\.]$/;
      const trimRangeMap = /* @__PURE__ */ new Map();
      const specialEndLinkCandidates = [];
      for (const candidate of linkCandidates) {
        let previous = candidate;
        let removed = previous.replace(specialEndCharRegex, "");
        let trimRange = 0;
        while (removed !== previous) {
          if (!parsedLink.suffix) {
            trimRange++;
          }
          specialEndLinkCandidates.push(removed);
          trimRangeMap.set(removed, trimRange);
          previous = removed;
          removed = removed.replace(specialEndCharRegex, "");
        }
      }
      linkCandidates.push(...specialEndLinkCandidates);
      this.d.trace("terminalLocalLinkDetector#detect linkCandidates", linkCandidates);
      const simpleLink = await this.j(void 0, bufferRange, linkCandidates, trimRangeMap);
      if (simpleLink) {
        simpleLink.parsedLink = parsedLink;
        simpleLink.text = text2.substring(parsedLink.prefix?.index ?? parsedLink.path.index, parsedLink.suffix ? parsedLink.suffix.suffix.index + parsedLink.suffix.suffix.text.length : parsedLink.path.index + parsedLink.path.text.length);
        this.d.trace("terminalLocalLinkDetector#detect verified link", simpleLink);
        links.push(simpleLink);
      }
      if (++resolvedLinkCount >= 10) {
        break;
      }
    }
    if (links.length === 0) {
      for (const matcher of fallbackMatchers) {
        const match = text2.match(matcher);
        const group2 = match?.groups;
        if (!group2) {
          continue;
        }
        const link2 = group2?.link;
        const path = group2?.path;
        const line = group2?.line;
        const col = group2?.col;
        if (!link2 || !path) {
          continue;
        }
        if (link2.length > 1024) {
          continue;
        }
        stringIndex = text2.indexOf(link2);
        const bufferRange = $ngc(lines, this.xterm.cols, {
          startColumn: stringIndex + 1,
          startLineNumber: 1,
          endColumn: stringIndex + link2.length + 1,
          endLineNumber: 1
        }, startLine);
        const suffix = line ? `:${line}${col ? `:${col}` : ""}` : "";
        const simpleLink = await this.j(`${path}${suffix}`, bufferRange, [path]);
        if (simpleLink) {
          links.push(simpleLink);
        }
        break;
      }
    }
    if (links.length === 0) {
      const rangeCandidates = $qgc(this.xterm.buffer.active, startLine, endLine, this.xterm.cols);
      for (const rangeCandidate of rangeCandidates) {
        let text3 = "";
        for (let y = rangeCandidate.start.y; y <= rangeCandidate.end.y; y++) {
          const line = this.xterm.buffer.active.getLine(y);
          if (!line) {
            break;
          }
          const lineStartX = y === rangeCandidate.start.y ? rangeCandidate.start.x : 0;
          const lineEndX = y === rangeCandidate.end.y ? rangeCandidate.end.x : this.xterm.cols - 1;
          text3 += line.translateToString(false, lineStartX, lineEndX);
        }
        rangeCandidate.start.x++;
        rangeCandidate.start.y++;
        rangeCandidate.end.y++;
        const simpleLink = await this.j(text3, rangeCandidate, [text3]);
        if (simpleLink) {
          links.push(simpleLink);
        }
        if (++resolvedLinkCount >= 10) {
          break;
        }
      }
    }
    return links;
  }
  g(uri) {
    const folders = this.f.getWorkspace().folders;
    for (let i2 = 0; i2 < folders.length; i2++) {
      if (this.e.extUri.isEqualOrParent(uri, folders[i2].uri)) {
        return true;
      }
    }
    return false;
  }
  async h(linkCandidates) {
    for (const link2 of linkCandidates) {
      let uri;
      if (link2.startsWith("file://")) {
        uri = URI.parse(link2);
      }
      const result = await this.c.resolveLink(this.b, link2, uri);
      if (result) {
        return result;
      }
    }
    return void 0;
  }
  /**
   * Validates a set of link candidates and returns a link if validated.
   * @param linkText The link text, this should be undefined to use the link stat value
   * @param trimRangeMap A map of link candidates to the amount of buffer range they need trimmed.
   */
  async j(linkText, bufferRange, linkCandidates, trimRangeMap) {
    const linkStat = await this.h(linkCandidates);
    if (linkStat) {
      let type;
      if (linkStat.isDirectory) {
        if (this.g(linkStat.uri)) {
          type = "LocalFolderInWorkspace";
        } else {
          type = "LocalFolderOutsideWorkspace";
        }
      } else {
        type = "LocalFile";
      }
      const trimRange = trimRangeMap?.get(linkStat.link);
      if (trimRange) {
        bufferRange.end.x -= trimRange;
        if (bufferRange.end.x < 0) {
          bufferRange.end.y--;
          bufferRange.end.x += this.xterm.cols;
        }
      }
      return {
        text: linkText ?? linkStat.link,
        uri: linkStat.uri,
        bufferRange,
        type
      };
    }
    return void 0;
  }
};
$Bgc = __decorate([
  __param(4, $8x),
  __param(5, $vl),
  __param(6, $Zk)
], $Bgc);

// out-build/vs/workbench/contrib/terminalContrib/links/browser/terminalUriLinkDetector.js
var Constants22;
(function(Constants27) {
  Constants27[Constants27["MaxResolvedLinksInLine"] = 10] = "MaxResolvedLinksInLine";
})(Constants22 || (Constants22 = {}));
var $Cgc = class $Cgc2 {
  static {
    this.id = "uri";
  }
  constructor(xterm, a, b, c, d, e) {
    this.xterm = xterm;
    this.a = a;
    this.b = b;
    this.c = c;
    this.d = d;
    this.e = e;
    this.maxLinkLength = 2048;
  }
  async detect(lines, startLine, endLine) {
    const links = [];
    const linkComputerTarget = new TerminalLinkAdapter(this.xterm, startLine, endLine);
    const computedLinks = $$9.computeLinks(linkComputerTarget);
    let resolvedLinkCount = 0;
    this.c.trace("terminalUriLinkDetector#detect computedLinks", computedLinks);
    for (const computedLink of computedLinks) {
      const bufferRange = $ngc(lines, this.xterm.cols, computedLink.range, startLine);
      const uri = computedLink.url ? typeof computedLink.url === "string" ? URI.parse(this.g(computedLink.url)) : computedLink.url : void 0;
      if (!uri) {
        continue;
      }
      const text2 = computedLink.url?.toString() || "";
      if (text2.length > this.maxLinkLength) {
        continue;
      }
      if (uri.scheme !== Schemas.file) {
        links.push({
          text: text2,
          uri,
          bufferRange,
          type: "Url"
          /* TerminalBuiltinLinkType.Url */
        });
        continue;
      }
      if (uri.authority.length !== 2 && uri.authority.endsWith(":")) {
        continue;
      }
      const uriCandidates = [uri];
      if (uri.authority.length > 0) {
        uriCandidates.push(URI.from({ ...uri, authority: void 0 }));
      }
      this.c.trace("terminalUriLinkDetector#detect uriCandidates", uriCandidates);
      for (const uriCandidate of uriCandidates) {
        const linkStat = await this.b.resolveLink(this.a, text2, uriCandidate);
        if (linkStat) {
          let type;
          if (linkStat.isDirectory) {
            if (this.f(uriCandidate)) {
              type = "LocalFolderInWorkspace";
            } else {
              type = "LocalFolderOutsideWorkspace";
            }
          } else {
            type = "LocalFile";
          }
          const simpleLink = {
            // Use computedLink.url if it's a string to retain the line/col suffix
            text: typeof computedLink.url === "string" ? computedLink.url : linkStat.link,
            uri: uriCandidate,
            bufferRange,
            type
          };
          this.c.trace("terminalUriLinkDetector#detect verified link", simpleLink);
          links.push(simpleLink);
          resolvedLinkCount++;
          break;
        }
      }
      if (++resolvedLinkCount >= 10) {
        break;
      }
    }
    return links;
  }
  f(uri) {
    const folders = this.e.getWorkspace().folders;
    for (let i2 = 0; i2 < folders.length; i2++) {
      if (this.d.extUri.isEqualOrParent(uri, folders[i2].uri)) {
        return true;
      }
    }
    return false;
  }
  g(path) {
    return path.replace(/:\d+(:\d+)?$/, "");
  }
};
$Cgc = __decorate([
  __param(3, $8x),
  __param(4, $vl),
  __param(5, $Zk)
], $Cgc);
var TerminalLinkAdapter = class {
  constructor(a, b, c) {
    this.a = a;
    this.b = b;
    this.c = c;
  }
  getLineCount() {
    return 1;
  }
  getLineContent() {
    return $pgc(this.a.buffer.active, this.b, this.c, this.a.cols);
  }
};

// out-build/vs/workbench/contrib/terminalContrib/links/browser/terminalWordLinkDetector.js
var Constants23;
(function(Constants27) {
  Constants27[Constants27["MaxLineLength"] = 2e3] = "MaxLineLength";
})(Constants23 || (Constants23 = {}));
var $Dgc = class $Dgc2 extends $3c {
  static {
    this.id = "word";
  }
  constructor(xterm, b, c) {
    super();
    this.xterm = xterm;
    this.b = b;
    this.c = c;
    this.maxLinkLength = 100;
    this.g();
    this.B(this.b.onDidChangeConfiguration((e) => {
      if (e.affectsConfiguration(
        "terminal.integrated.wordSeparators"
        /* TerminalSettingId.WordSeparators */
      )) {
        this.g();
      }
    }));
  }
  detect(lines, startLine, endLine) {
    const links = [];
    const text2 = $pgc(this.xterm.buffer.active, startLine, endLine, this.xterm.cols);
    if (text2 === "" || text2.length > 2e3) {
      return [];
    }
    const words = this.f(text2);
    for (const word of words) {
      if (word.text === "") {
        continue;
      }
      if (word.text.length > 0 && word.text.charAt(word.text.length - 1) === ":") {
        word.text = word.text.slice(0, -1);
        word.endIndex--;
      }
      const bufferRange = $ngc(lines, this.xterm.cols, {
        startColumn: word.startIndex + 1,
        startLineNumber: 1,
        endColumn: word.endIndex + 1,
        endLineNumber: 1
      }, startLine);
      if ($0g(word.text, this.c.urlProtocol)) {
        const uri = URI.parse(word.text);
        if (uri) {
          links.push({
            text: word.text,
            uri,
            bufferRange,
            type: "Url"
            /* TerminalBuiltinLinkType.Url */
          });
        }
        continue;
      }
      links.push({
        text: word.text,
        bufferRange,
        type: "Search",
        contextLine: text2
      });
    }
    return links;
  }
  f(text2) {
    const words = [];
    const splitWords = text2.split(this.a);
    let runningIndex = 0;
    for (let i2 = 0; i2 < splitWords.length; i2++) {
      words.push({
        text: splitWords[i2],
        startIndex: runningIndex,
        endIndex: runningIndex + splitWords[i2].length
      });
      runningIndex += splitWords[i2].length + 1;
    }
    return words;
  }
  g() {
    const separators = this.b.getValue($9X).wordSeparators;
    let powerlineSymbols = "";
    for (let i2 = 57520; i2 <= 57535; i2++) {
      powerlineSymbols += String.fromCharCode(i2);
    }
    this.a = new RegExp(`[${$Af(separators)}${powerlineSymbols}]`, "g");
  }
};
$Dgc = __decorate([
  __param(1, $kl),
  __param(2, $Vu)
], $Dgc);

// out-build/vs/workbench/contrib/terminal/browser/widgets/terminalHoverWidget.js
var $146 = $;
var $Egc = class $Egc2 extends $3c {
  constructor(a, b, c, f, g, h3) {
    super();
    this.a = a;
    this.b = b;
    this.c = c;
    this.f = f;
    this.g = g;
    this.h = h3;
    this.id = "hover";
  }
  attach(container2) {
    const showLinkHover = this.h.getValue(
      "terminal.integrated.showLinkHover"
      /* TerminalSettingId.ShowLinkHover */
    );
    if (!showLinkHover) {
      return;
    }
    const target = new CellHoverTarget(container2, this.a);
    const hover = this.g.showHover({
      target,
      content: this.b,
      actions: this.c,
      linkHandler: this.f,
      // .xterm-hover lets xterm know that the hover is part of a link
      additionalClasses: ["xterm-hover"]
    });
    if (hover) {
      this.B(hover);
    }
  }
};
$Egc = __decorate([
  __param(4, $5$),
  __param(5, $kl)
], $Egc);
var CellHoverTarget = class extends $qZ {
  get targetElements() {
    return this.c;
  }
  constructor(container2, g) {
    super();
    this.g = g;
    this.c = [];
    this.a = $146("div.terminal-hover-targets.xterm-hover");
    const rowCount = this.g.viewportRange.end.y - this.g.viewportRange.start.y + 1;
    const width2 = (this.g.viewportRange.end.y > this.g.viewportRange.start.y ? this.g.terminalDimensions.width - this.g.viewportRange.start.x : this.g.viewportRange.end.x - this.g.viewportRange.start.x + 1) * this.g.cellDimensions.width;
    const topTarget = $146("div.terminal-hover-target.hoverHighlight");
    topTarget.style.left = `${this.g.viewportRange.start.x * this.g.cellDimensions.width}px`;
    topTarget.style.bottom = `${(this.g.terminalDimensions.height - this.g.viewportRange.start.y - 1) * this.g.cellDimensions.height}px`;
    topTarget.style.width = `${width2}px`;
    topTarget.style.height = `${this.g.cellDimensions.height}px`;
    this.c.push(this.a.appendChild(topTarget));
    if (rowCount > 2) {
      const middleTarget = $146("div.terminal-hover-target.hoverHighlight");
      middleTarget.style.left = `0px`;
      middleTarget.style.bottom = `${(this.g.terminalDimensions.height - this.g.viewportRange.start.y - 1 - (rowCount - 2)) * this.g.cellDimensions.height}px`;
      middleTarget.style.width = `${this.g.terminalDimensions.width * this.g.cellDimensions.width}px`;
      middleTarget.style.height = `${(rowCount - 2) * this.g.cellDimensions.height}px`;
      this.c.push(this.a.appendChild(middleTarget));
    }
    if (rowCount > 1) {
      const bottomTarget = $146("div.terminal-hover-target.hoverHighlight");
      bottomTarget.style.left = `0px`;
      bottomTarget.style.bottom = `${(this.g.terminalDimensions.height - this.g.viewportRange.end.y - 1) * this.g.cellDimensions.height}px`;
      bottomTarget.style.width = `${(this.g.viewportRange.end.x + 1) * this.g.cellDimensions.width}px`;
      bottomTarget.style.height = `${this.g.cellDimensions.height}px`;
      this.c.push(this.a.appendChild(bottomTarget));
    }
    if (this.g.modifierDownCallback && this.g.modifierUpCallback) {
      let down = false;
      this.B($_i(container2.ownerDocument, "keydown", (e) => {
        if (e.ctrlKey && !down) {
          down = true;
          this.g.modifierDownCallback();
        }
      }));
      this.B($_i(container2.ownerDocument, "keyup", (e) => {
        if (!e.ctrlKey) {
          down = false;
          this.g.modifierUpCallback();
        }
      }));
    }
    container2.appendChild(this.a);
    this.B($1c(() => this.a?.remove()));
  }
};

// out-build/vs/workbench/contrib/terminalContrib/links/browser/terminalMultiLineLinkDetector.js
var Constants24;
(function(Constants27) {
  Constants27[Constants27["MaxLineLength"] = 2e3] = "MaxLineLength";
  Constants27[Constants27["MaxResolvedLinkLength"] = 1024] = "MaxResolvedLinkLength";
})(Constants24 || (Constants24 = {}));
var lineNumberPrefixMatchers = [
  // Ripgrep:
  //   /some/file
  //   16:searchresult
  //   16:    searchresult
  // Eslint:
  //   /some/file
  //     16:5  error ...
  /^ *(?<link>(?<line>\d+):(?<col>\d+)?)/
];
var gitDiffMatchers = [
  // --- a/some/file
  // +++ b/some/file
  // @@ -8,11 +8,11 @@ file content...
  /^(?<link>@@ .+ \+(?<toFileLine>\d+),(?<toFileCount>\d+) @@)/
];
var $Fgc = class $Fgc2 {
  static {
    this.id = "multiline";
  }
  constructor(xterm, a, b, c, d, e) {
    this.xterm = xterm;
    this.a = a;
    this.b = b;
    this.c = c;
    this.d = d;
    this.e = e;
    this.maxLinkLength = 500;
  }
  async detect(lines, startLine, endLine) {
    const links = [];
    const text2 = $pgc(this.xterm.buffer.active, startLine, endLine, this.xterm.cols);
    if (text2 === "" || text2.length > 2e3) {
      return [];
    }
    this.c.trace("terminalMultiLineLinkDetector#detect text", text2);
    for (const matcher of lineNumberPrefixMatchers) {
      const match = text2.match(matcher);
      const group2 = match?.groups;
      if (!group2) {
        continue;
      }
      const link2 = group2?.link;
      const line = group2?.line;
      const col = group2?.col;
      if (!link2 || line === void 0) {
        continue;
      }
      if (link2.length > 1024) {
        continue;
      }
      this.c.trace("terminalMultiLineLinkDetector#detect candidate", link2);
      let possiblePath;
      for (let index = startLine - 1; index >= 0; index--) {
        if (this.xterm.buffer.active.getLine(index).isWrapped) {
          continue;
        }
        const text3 = $pgc(this.xterm.buffer.active, index, index, this.xterm.cols);
        if (!text3.match(/^\s*\d/)) {
          possiblePath = text3;
          break;
        }
      }
      if (!possiblePath) {
        continue;
      }
      const linkStat = await this.b.resolveLink(this.a, possiblePath);
      if (linkStat) {
        let type;
        if (linkStat.isDirectory) {
          if (this.f(linkStat.uri)) {
            type = "LocalFolderInWorkspace";
          } else {
            type = "LocalFolderOutsideWorkspace";
          }
        } else {
          type = "LocalFile";
        }
        const bufferRange = $ngc(lines, this.xterm.cols, {
          startColumn: 1,
          startLineNumber: 1,
          endColumn: 1 + text2.length,
          endLineNumber: 1
        }, startLine);
        const simpleLink = {
          text: link2,
          uri: linkStat.uri,
          selection: {
            startLineNumber: parseInt(line),
            startColumn: col ? parseInt(col) : 1
          },
          disableTrimColon: true,
          bufferRange,
          type
        };
        this.c.trace("terminalMultiLineLinkDetector#detect verified link", simpleLink);
        links.push(simpleLink);
        break;
      }
    }
    if (links.length === 0) {
      for (const matcher of gitDiffMatchers) {
        const match = text2.match(matcher);
        const group2 = match?.groups;
        if (!group2) {
          continue;
        }
        const link2 = group2?.link;
        const toFileLine = group2?.toFileLine;
        const toFileCount = group2?.toFileCount;
        if (!link2 || toFileLine === void 0) {
          continue;
        }
        if (link2.length > 1024) {
          continue;
        }
        this.c.trace("terminalMultiLineLinkDetector#detect candidate", link2);
        let possiblePath;
        for (let index = startLine - 1; index >= 0; index--) {
          if (this.xterm.buffer.active.getLine(index).isWrapped) {
            continue;
          }
          const text3 = $pgc(this.xterm.buffer.active, index, index, this.xterm.cols);
          const match2 = text3.match(/\+\+\+ b\/(?<path>.+)/);
          if (match2) {
            possiblePath = match2.groups?.path;
            break;
          }
        }
        if (!possiblePath) {
          continue;
        }
        const linkStat = await this.b.resolveLink(this.a, possiblePath);
        if (linkStat) {
          let type;
          if (linkStat.isDirectory) {
            if (this.f(linkStat.uri)) {
              type = "LocalFolderInWorkspace";
            } else {
              type = "LocalFolderOutsideWorkspace";
            }
          } else {
            type = "LocalFile";
          }
          const bufferRange = $ngc(lines, this.xterm.cols, {
            startColumn: 1,
            startLineNumber: 1,
            endColumn: 1 + link2.length,
            endLineNumber: 1
          }, startLine);
          const simpleLink = {
            text: link2,
            uri: linkStat.uri,
            selection: {
              startLineNumber: parseInt(toFileLine),
              startColumn: 1,
              endLineNumber: parseInt(toFileLine) + parseInt(toFileCount)
            },
            bufferRange,
            type
          };
          this.c.trace("terminalMultiLineLinkDetector#detect verified link", simpleLink);
          links.push(simpleLink);
          break;
        }
      }
    }
    return links;
  }
  f(uri) {
    const folders = this.e.getWorkspace().folders;
    for (let i2 = 0; i2 < folders.length; i2++) {
      if (this.d.extUri.isEqualOrParent(uri, folders[i2].uri)) {
        return true;
      }
    }
    return false;
  }
};
$Fgc = __decorate([
  __param(3, $8x),
  __param(4, $vl),
  __param(5, $Zk)
], $Fgc);

// out-build/vs/workbench/contrib/terminalContrib/links/browser/terminalLinkManager.js
var $Ggc = class $Ggc2 extends $2c {
  constructor(m, n, capabilities, q, s, t, notificationService, terminalConfigurationService, u, w) {
    super();
    this.m = m;
    this.n = n;
    this.q = q;
    this.s = s;
    this.t = t;
    this.u = u;
    this.w = w;
    this.b = /* @__PURE__ */ new Map();
    this.c = [];
    this.h = [];
    this.j = /* @__PURE__ */ new Map();
    let enableFileLinks = true;
    const enableFileLinksConfig = this.s.getValue($9X).enableFileLinks;
    switch (enableFileLinksConfig) {
      case "off":
      case false:
        enableFileLinks = false;
        break;
      case "notRemote":
        enableFileLinks = !this.n.remoteAuthority;
        break;
    }
    if (enableFileLinks) {
      this.z($Fgc.id, this.t.createInstance($Fgc, this.m, this.n, this.q));
      this.z($Bgc.id, this.t.createInstance($Bgc, this.m, capabilities, this.n, this.q));
    }
    this.z($Cgc.id, this.t.createInstance($Cgc, this.m, this.n, this.q));
    this.z($Dgc.id, this.add(this.t.createInstance($Dgc, this.m)));
    const localFileOpener = this.t.createInstance($wgc);
    const localFolderInWorkspaceOpener = this.t.createInstance($xgc);
    this.j.set("LocalFile", localFileOpener);
    this.j.set("LocalFolderInWorkspace", localFolderInWorkspaceOpener);
    this.j.set("LocalFolderOutsideWorkspace", this.t.createInstance($ygc));
    this.j.set("Search", this.t.createInstance($zgc, capabilities, this.n.initialCwd, localFileOpener, localFolderInWorkspaceOpener, () => this.n.os || OS));
    this.j.set("Url", this.t.createInstance($Agc, !!this.n.remoteAuthority));
    this.I();
    let activeHoverDisposable;
    let activeTooltipScheduler;
    this.add($1c(() => {
      this.H();
      $Xc(this.h);
      activeHoverDisposable?.dispose();
      activeTooltipScheduler?.dispose();
    }));
    this.m.options.linkHandler = {
      allowNonHttpProtocols: true,
      activate: (event, text2) => {
        if (!this.J(event)) {
          return;
        }
        const colonIndex = text2.indexOf(":");
        if (colonIndex === -1) {
          throw new Error(`Could not find scheme in link "${text2}"`);
        }
        const scheme = text2.substring(0, colonIndex);
        if (terminalConfigurationService.config.allowedLinkSchemes.indexOf(scheme) === -1) {
          notificationService.prompt(Severity2.Warning, localize(10931, null, scheme), [
            {
              label: localize(10932, null, scheme),
              run: () => {
                const allowedLinkSchemes = [
                  ...terminalConfigurationService.config.allowedLinkSchemes,
                  scheme
                ];
                this.s.updateValue(`terminal.integrated.allowedLinkSchemes`, allowedLinkSchemes);
              }
            }
          ]);
        }
        this.j.get(
          "Url"
          /* TerminalBuiltinLinkType.Url */
        )?.open({
          type: "Url",
          text: text2,
          bufferRange: null,
          uri: URI.parse(text2)
        });
      },
      hover: (e, text2, range) => {
        activeHoverDisposable?.dispose();
        activeHoverDisposable = void 0;
        activeTooltipScheduler?.dispose();
        activeTooltipScheduler = new $8h(() => {
          const core2 = this.m._core;
          const cellDimensions = {
            width: core2._renderService.dimensions.css.cell.width,
            height: core2._renderService.dimensions.css.cell.height
          };
          const terminalDimensions = {
            width: this.m.cols,
            height: this.m.rows
          };
          activeHoverDisposable = this.G({
            viewportRange: $ogc(range, this.m.buffer.active.viewportY),
            cellDimensions,
            terminalDimensions
          }, this.L(text2, text2), void 0, (text3) => this.m.options.linkHandler?.activate(e, text3, range));
          activeTooltipScheduler?.dispose();
          activeTooltipScheduler = void 0;
        }, this.s.getValue("workbench.hover.delay"));
        activeTooltipScheduler.schedule();
      }
    };
  }
  z(id2, detector, isExternal = false) {
    const detectorAdapter = this.add(this.t.createInstance($vgc, detector));
    this.add(detectorAdapter.onDidActivateLink((e) => {
      e.event?.preventDefault();
      if (e.event && !(e.event instanceof $0Pb) && !this.J(e.event)) {
        return;
      }
      if (e.link.activate) {
        e.link.activate(e.link.text);
      } else {
        this.B(e.link);
      }
    }));
    this.add(detectorAdapter.onDidShowHover((e) => this.F(e.link, e.viewportRange, e.modifierDownCallback, e.modifierUpCallback)));
    if (!isExternal) {
      this.b.set(id2, detectorAdapter);
    }
    return detectorAdapter;
  }
  async B(link2) {
    this.u.debug("Opening link", link2);
    const opener = this.j.get(link2.type);
    if (!opener) {
      throw new Error(`No matching opener for link type "${link2.type}"`);
    }
    await opener.open(link2);
  }
  async openRecentLink(type) {
    let links;
    let i2 = this.m.buffer.active.length;
    while ((!links || links.length === 0) && i2 >= this.m.buffer.active.viewportY) {
      links = await this.D(i2, type);
      i2--;
    }
    if (!links || links.length < 1) {
      return void 0;
    }
    const event = new $0Pb($7j.CLICK);
    links[0].activate(event, links[0].text);
    return links[0];
  }
  async getLinks() {
    const viewportLinksByLinePromises = [];
    for (let i2 = this.m.buffer.active.viewportY + this.m.rows - 1; i2 >= this.m.buffer.active.viewportY; i2--) {
      viewportLinksByLinePromises.push(this.C(i2));
    }
    const viewportLinksByLine = await Promise.all(viewportLinksByLinePromises);
    const viewportLinks = {
      wordLinks: [],
      webLinks: [],
      fileLinks: [],
      folderLinks: []
    };
    for (const links of viewportLinksByLine) {
      if (links) {
        const { wordLinks, webLinks, fileLinks, folderLinks } = links;
        if (wordLinks?.length) {
          viewportLinks.wordLinks.push(...wordLinks.reverse());
        }
        if (webLinks?.length) {
          viewportLinks.webLinks.push(...webLinks.reverse());
        }
        if (fileLinks?.length) {
          viewportLinks.fileLinks.push(...fileLinks.reverse());
        }
        if (folderLinks?.length) {
          viewportLinks.folderLinks.push(...folderLinks.reverse());
        }
      }
    }
    const aboveViewportLinksPromises = [];
    for (let i2 = this.m.buffer.active.viewportY - 1; i2 >= 0; i2--) {
      aboveViewportLinksPromises.push(this.C(i2));
    }
    const belowViewportLinksPromises = [];
    for (let i2 = this.m.buffer.active.length - 1; i2 >= this.m.buffer.active.viewportY + this.m.rows; i2--) {
      belowViewportLinksPromises.push(this.C(i2));
    }
    const allLinks = Promise.all(aboveViewportLinksPromises).then(async (aboveViewportLinks) => {
      const belowViewportLinks = await Promise.all(belowViewportLinksPromises);
      const allResults = {
        wordLinks: [...viewportLinks.wordLinks],
        webLinks: [...viewportLinks.webLinks],
        fileLinks: [...viewportLinks.fileLinks],
        folderLinks: [...viewportLinks.folderLinks]
      };
      for (const links of [...belowViewportLinks, ...aboveViewportLinks]) {
        if (links) {
          const { wordLinks, webLinks, fileLinks, folderLinks } = links;
          if (wordLinks?.length) {
            allResults.wordLinks.push(...wordLinks.reverse());
          }
          if (webLinks?.length) {
            allResults.webLinks.push(...webLinks.reverse());
          }
          if (fileLinks?.length) {
            allResults.fileLinks.push(...fileLinks.reverse());
          }
          if (folderLinks?.length) {
            allResults.folderLinks.push(...folderLinks.reverse());
          }
        }
      }
      return allResults;
    });
    return {
      viewport: viewportLinks,
      all: allLinks
    };
  }
  async C(y) {
    const unfilteredWordLinks = await this.D(y, "word");
    const webLinks = await this.D(y, "url");
    const fileLinks = await this.D(y, "localFile");
    const folderLinks = await this.D(y, "localFolder");
    const words = /* @__PURE__ */ new Set();
    let wordLinks;
    if (unfilteredWordLinks) {
      wordLinks = [];
      for (const link2 of unfilteredWordLinks) {
        if (!words.has(link2.text) && link2.text.length > 1) {
          wordLinks.push(link2);
          words.add(link2.text);
        }
      }
    }
    return { wordLinks, webLinks, fileLinks, folderLinks };
  }
  async D(y, type) {
    switch (type) {
      case "word":
        return await new Promise((r2) => this.b.get($Dgc.id)?.provideLinks(y, r2));
      case "url":
        return await new Promise((r2) => this.b.get($Cgc.id)?.provideLinks(y, r2));
      case "localFile": {
        const links = await new Promise((r2) => this.b.get($Bgc.id)?.provideLinks(y, r2));
        return links?.filter(
          (link2) => link2.type === "LocalFile"
          /* TerminalBuiltinLinkType.LocalFile */
        );
      }
      case "localFolder": {
        const links = await new Promise((r2) => this.b.get($Bgc.id)?.provideLinks(y, r2));
        return links?.filter(
          (link2) => link2.type === "LocalFolderInWorkspace"
          /* TerminalBuiltinLinkType.LocalFolderInWorkspace */
        );
      }
    }
  }
  F(link2, viewportRange, modifierDownCallback, modifierUpCallback) {
    if (!this.a) {
      return;
    }
    const core2 = this.m._core;
    const cellDimensions = {
      width: core2._renderService.dimensions.css.cell.width,
      height: core2._renderService.dimensions.css.cell.height
    };
    const terminalDimensions = {
      width: this.m.cols,
      height: this.m.rows
    };
    this.G({
      viewportRange,
      cellDimensions,
      terminalDimensions,
      modifierDownCallback,
      modifierUpCallback
    }, this.L(link2.text, link2.label), link2.actions, (text2) => link2.activate(void 0, text2), link2);
  }
  G(targetOptions, text2, actions, linkHandler, link2) {
    if (this.a) {
      const widget = this.t.createInstance($Egc, targetOptions, text2, actions, linkHandler);
      const attached = this.a.attachWidget(widget);
      if (attached) {
        link2?.onInvalidated(() => attached.dispose());
      }
      return attached;
    }
    return void 0;
  }
  setWidgetManager(widgetManager) {
    this.a = widgetManager;
  }
  H() {
    $Xc(this.c);
    this.c.length = 0;
  }
  I() {
    const proxyLinkProvider = async (bufferLineNumber) => {
      return this.externalProvideLinksCb?.(bufferLineNumber);
    };
    const detectorId = `extension-${this.h.length}`;
    const wrappedLinkProvider = this.z(detectorId, new $tgc(detectorId, this.m, proxyLinkProvider), true);
    this.c.push(this.m.registerLinkProvider(wrappedLinkProvider));
    for (const p of this.b.values()) {
      this.c.push(this.m.registerLinkProvider(p));
    }
  }
  J(event) {
    const editorConf = this.s.getValue("editor");
    if (editorConf.multiCursorModifier === "ctrlCmd") {
      return !!event.altKey;
    }
    return $m ? event.metaKey : event.ctrlKey;
  }
  L(uri, label3) {
    const editorConf = this.s.getValue("editor");
    let clickLabel = "";
    if (editorConf.multiCursorModifier === "ctrlCmd") {
      if ($m) {
        clickLabel = localize(10933, null);
      } else {
        clickLabel = localize(10934, null);
      }
    } else {
      if ($m) {
        clickLabel = localize(10935, null);
      } else {
        clickLabel = localize(10936, null);
      }
    }
    let fallbackLabel = localize(10937, null);
    try {
      if (this.w.canTunnel(URI.parse(uri))) {
        fallbackLabel = localize(10938, null);
      }
    } catch {
    }
    const markdown = new $bm("", true);
    if (label3) {
      label3 = markdown.appendText(label3).value;
      markdown.value = "";
    }
    if (uri) {
      uri = markdown.appendText(uri).value;
      markdown.value = "";
    }
    label3 = label3 || fallbackLabel;
    uri = uri || label3;
    if (/(\s|&nbsp;)/.test(uri)) {
      uri = localize(10939, null);
    }
    return markdown.appendLink(uri, label3).appendMarkdown(` (${clickLabel})`);
  }
};
$Ggc = __decorate([
  __param(4, $kl),
  __param(5, $Pk),
  __param(6, $PJ),
  __param(7, $5Pb),
  __param(8, $8x),
  __param(9, $tC)
], $Ggc);

// out-build/vs/workbench/contrib/terminalContrib/links/browser/terminalLinkProviderService.js
var $Hgc = class {
  constructor() {
    this.a = /* @__PURE__ */ new Set();
    this.b = new $ze();
    this.c = new $ze();
  }
  get linkProviders() {
    return this.a;
  }
  get onDidAddLinkProvider() {
    return this.b.event;
  }
  get onDidRemoveLinkProvider() {
    return this.c.event;
  }
  registerLinkProvider(linkProvider) {
    const disposables = [];
    this.a.add(linkProvider);
    this.b.fire(linkProvider);
    return {
      dispose: () => {
        for (const disposable of disposables) {
          disposable.dispose();
        }
        this.a.delete(linkProvider);
        this.c.fire(linkProvider);
      }
    };
  }
};

// out-build/vs/workbench/contrib/terminalContrib/links/browser/terminalLinkQuickpick.js
var $Igc = class $Igc2 extends $2c {
  constructor(j, instantiationService, m, n) {
    super();
    this.j = j;
    this.m = m;
    this.n = n;
    this.a = new $Qh();
    this.h = this.add(new $ze());
    this.onDidRequestMoreLinks = this.h.event;
    this.u = false;
    this.b = this.add(instantiationService.createInstance($0yb));
  }
  async show(instance2, links) {
    this.c = instance2;
    const result = await Promise.race([links.all, $Wh(500)]);
    const usingAllLinks = typeof result === "object";
    const resolvedLinks = usingAllLinks ? result : links.viewport;
    const wordPicks = resolvedLinks.wordLinks ? await this.q(resolvedLinks.wordLinks) : void 0;
    const filePicks = resolvedLinks.fileLinks ? await this.q(resolvedLinks.fileLinks) : void 0;
    const folderPicks = resolvedLinks.folderLinks ? await this.q(resolvedLinks.folderLinks) : void 0;
    const webPicks = resolvedLinks.webLinks ? await this.q(resolvedLinks.webLinks) : void 0;
    const picks = [];
    if (webPicks) {
      picks.push({ type: "separator", label: localize(10940, null) });
      picks.push(...webPicks);
    }
    if (filePicks) {
      picks.push({ type: "separator", label: localize(10941, null) });
      picks.push(...filePicks);
    }
    if (folderPicks) {
      picks.push({ type: "separator", label: localize(10942, null) });
      picks.push(...folderPicks);
    }
    if (wordPicks) {
      picks.push({ type: "separator", label: localize(10943, null) });
      picks.push(...wordPicks);
    }
    const pick = this.n.createQuickPick({ useSeparators: true });
    const disposables = new $2c();
    disposables.add(pick);
    pick.items = picks;
    pick.placeholder = localize(10944, null);
    pick.sortByLabel = false;
    pick.show();
    if (pick.activeItems.length > 0) {
      this.s(pick.activeItems[0]);
    }
    let accepted = false;
    if (!usingAllLinks) {
      disposables.add(Event2.once(pick.onDidChangeValue)(async () => {
        const allLinks = await links.all;
        if (accepted) {
          return;
        }
        const wordIgnoreLinks = [...allLinks.fileLinks ?? [], ...allLinks.folderLinks ?? [], ...allLinks.webLinks ?? []];
        const wordPicks2 = allLinks.wordLinks ? await this.q(allLinks.wordLinks, wordIgnoreLinks) : void 0;
        const filePicks2 = allLinks.fileLinks ? await this.q(allLinks.fileLinks) : void 0;
        const folderPicks2 = allLinks.folderLinks ? await this.q(allLinks.folderLinks) : void 0;
        const webPicks2 = allLinks.webLinks ? await this.q(allLinks.webLinks) : void 0;
        const picks2 = [];
        if (webPicks2) {
          picks2.push({ type: "separator", label: localize(10945, null) });
          picks2.push(...webPicks2);
        }
        if (filePicks2) {
          picks2.push({ type: "separator", label: localize(10946, null) });
          picks2.push(...filePicks2);
        }
        if (folderPicks2) {
          picks2.push({ type: "separator", label: localize(10947, null) });
          picks2.push(...folderPicks2);
        }
        if (wordPicks2) {
          picks2.push({ type: "separator", label: localize(10948, null) });
          picks2.push(...wordPicks2);
        }
        pick.items = picks2;
      }));
    }
    disposables.add(pick.onDidChangeActive(async () => {
      const [item] = pick.activeItems;
      this.s(item);
    }));
    return new Promise((r2) => {
      disposables.add(pick.onDidHide(({ reason }) => {
        if (this.u) {
          const markTracker = this.c?.xterm?.markTracker;
          if (markTracker) {
            markTracker.restoreScrollState();
            markTracker.clear();
            this.u = false;
          }
        }
        if (reason === QuickInputHideReason.Gesture) {
          this.b.restore();
        }
        disposables.dispose();
        if (pick.selectedItems.length === 0) {
          this.j.showLastProvider(
            "terminal"
            /* AccessibleViewProviderId.Terminal */
          );
        }
        r2();
      }));
      disposables.add(Event2.once(pick.onDidAccept)(() => {
        if (this.u) {
          const markTracker = this.c?.xterm?.markTracker;
          if (markTracker) {
            markTracker.restoreScrollState();
            markTracker.clear();
            this.u = false;
          }
        }
        accepted = true;
        const event = new $0Pb($7j.CLICK);
        const activeItem = pick.activeItems?.[0];
        if (activeItem && "link" in activeItem) {
          activeItem.link.activate(event, activeItem.label);
        }
        disposables.dispose();
        r2();
      }));
    });
  }
  /**
   * @param ignoreLinks Links with labels to not include in the picks.
   */
  async q(links, ignoreLinks) {
    if (!links) {
      return;
    }
    const linkTextKeys = /* @__PURE__ */ new Set();
    const linkUriKeys = /* @__PURE__ */ new Set();
    const picks = [];
    for (const link2 of links) {
      let label3 = link2.text;
      if (!linkTextKeys.has(label3) && (!ignoreLinks || !ignoreLinks.some((e) => e.text === label3))) {
        linkTextKeys.add(label3);
        let description;
        if ("uri" in link2 && link2.uri) {
          if (link2.type === "LocalFile" || link2.type === "LocalFolderInWorkspace" || link2.type === "LocalFolderOutsideWorkspace") {
            label3 = $rh(link2.uri);
            description = this.m.getUriLabel($uh(link2.uri), { relative: true });
          }
          if (link2.type === "LocalFile") {
            if (link2.parsedLink?.suffix?.row !== void 0) {
              label3 += `:${link2.parsedLink.suffix.row}`;
              if (link2.parsedLink?.suffix?.rowEnd !== void 0) {
                label3 += `-${link2.parsedLink.suffix.rowEnd}`;
              }
              if (link2.parsedLink?.suffix?.col !== void 0) {
                label3 += `:${link2.parsedLink.suffix.col}`;
                if (link2.parsedLink?.suffix?.colEnd !== void 0) {
                  label3 += `-${link2.parsedLink.suffix.colEnd}`;
                }
              }
            }
          }
          if (linkUriKeys.has(label3 + "|" + (description ?? ""))) {
            continue;
          }
          linkUriKeys.add(label3 + "|" + (description ?? ""));
        }
        picks.push({ label: label3, link: link2, description });
      }
    }
    return picks.length > 0 ? picks : void 0;
  }
  s(item) {
    if (!item || !("link" in item) || !item.link) {
      return;
    }
    const link2 = item.link;
    this.w(link2);
    if (!("uri" in link2) || !link2.uri) {
      return;
    }
    if (link2.type !== "LocalFile") {
      return;
    }
    this.t(link2);
  }
  t(link2) {
    const linkSuffix = link2.parsedLink ? link2.parsedLink.suffix : $pRb(link2.text);
    const selection = linkSuffix?.row === void 0 ? void 0 : {
      startLineNumber: linkSuffix.row ?? 1,
      startColumn: linkSuffix.col ?? 1,
      endLineNumber: linkSuffix.rowEnd,
      endColumn: linkSuffix.colEnd
    };
    this.b.set();
    this.a.queue(async () => {
      await this.b.openTransientEditor({
        resource: link2.uri,
        options: { preserveFocus: true, revealIfOpened: true, ignoreError: true, selection }
      });
    });
  }
  w(link2) {
    const xterm = this.c?.xterm;
    if (!xterm) {
      return;
    }
    if (!this.u) {
      xterm.markTracker.saveScrollState();
      this.u = true;
    }
    xterm.markTracker.revealRange(link2.range);
  }
};
$Igc = __decorate([
  __param(0, $shb),
  __param(1, $Pk),
  __param(2, $ZI),
  __param(3, $1M)
], $Igc);

// out-build/vs/workbench/contrib/terminalContrib/links/browser/terminalLinkResolver.js
var $Jgc = class $Jgc2 {
  constructor(b) {
    this.b = b;
    this.a = /* @__PURE__ */ new Map();
  }
  async resolveLink(processManager, link2, uri) {
    if (uri && uri.scheme === Schemas.file && processManager.remoteAuthority) {
      uri = uri.with({
        scheme: Schemas.vscodeRemote,
        authority: processManager.remoteAuthority
      });
    }
    let cache2 = this.a.get(processManager.remoteAuthority ?? "");
    if (!cache2) {
      cache2 = new LinkCache();
      this.a.set(processManager.remoteAuthority ?? "", cache2);
    }
    const cached = cache2.get(uri || link2);
    if (cached !== void 0) {
      return cached;
    }
    if (uri) {
      try {
        const stat = await this.b.stat(uri);
        const result = { uri, link: link2, isDirectory: stat.isDirectory };
        cache2.set(uri, result);
        return result;
      } catch (e) {
        cache2.set(uri, null);
        return null;
      }
    }
    let linkUrl = $mRb(link2);
    linkUrl = $nRb(linkUrl);
    if (linkUrl.length === 0) {
      cache2.set(link2, null);
      return null;
    }
    if ($l && link2.match(/^\/mnt\/[a-z]/i) && processManager.backend) {
      linkUrl = await processManager.backend.getWslPath(linkUrl, "unix-to-win");
    } else if ($l && link2.match(/^(?:\/\/|\\\\)wsl(?:\$|\.localhost)(\/|\\)/)) {
    } else {
      const preprocessedLink = this.c(linkUrl, processManager.initialCwd, processManager.os, processManager.userHome);
      if (!preprocessedLink) {
        cache2.set(link2, null);
        return null;
      }
      linkUrl = preprocessedLink;
    }
    try {
      let uri2;
      if (processManager.remoteAuthority) {
        uri2 = URI.from({
          scheme: Schemas.vscodeRemote,
          authority: processManager.remoteAuthority,
          path: linkUrl
        });
      } else {
        uri2 = URI.file(linkUrl);
      }
      try {
        const stat = await this.b.stat(uri2);
        const result = { uri: uri2, link: link2, isDirectory: stat.isDirectory };
        cache2.set(link2, result);
        return result;
      } catch (e) {
        cache2.set(link2, null);
        return null;
      }
    } catch {
      cache2.set(link2, null);
      return null;
    }
  }
  c(link2, initialCwd, os, userHome) {
    const osPath = this.d(os);
    if (link2.charAt(0) === "~") {
      if (!userHome) {
        return null;
      }
      link2 = osPath.join(userHome, link2.substring(1));
    } else if (link2.charAt(0) !== "/" && link2.charAt(0) !== "~") {
      if (os === 1) {
        if (!link2.match("^" + $sRb) && !link2.startsWith("\\\\?\\")) {
          if (!initialCwd) {
            return null;
          }
          link2 = osPath.join(initialCwd, link2);
        } else {
          link2 = link2.replace(/^\\\\\?\\/, "");
        }
      } else {
        if (!initialCwd) {
          return null;
        }
        link2 = osPath.join(initialCwd, link2);
      }
    }
    link2 = osPath.normalize(link2);
    return link2;
  }
  d(os) {
    return (os ?? OS) === 1 ? $jc : $kc;
  }
};
$Jgc = __decorate([
  __param(0, $km)
], $Jgc);
var LinkCacheConstants;
(function(LinkCacheConstants2) {
  LinkCacheConstants2[LinkCacheConstants2["TTL"] = 1e4] = "TTL";
})(LinkCacheConstants || (LinkCacheConstants = {}));
var LinkCache = class {
  constructor() {
    this.a = /* @__PURE__ */ new Map();
    this.b = 0;
  }
  set(link2, value) {
    if (this.b) {
      $Y.clearTimeout(this.b);
    }
    this.b = $Y.setTimeout(
      () => this.a.clear(),
      1e4
      /* LinkCacheConstants.TTL */
    );
    this.a.set(this.c(link2), value);
  }
  get(link2) {
    return this.a.get(this.c(link2));
  }
  c(link2) {
    if (URI.isUri(link2)) {
      return link2.toString();
    }
    return link2;
  }
};

// out-build/vs/workbench/contrib/terminalContrib/links/browser/terminal.links.contribution.js
var TerminalLinkContribution_1;
$SC(
  $tRb,
  $Hgc,
  1
  /* InstantiationType.Delayed */
);
var TerminalLinkContribution = class TerminalLinkContribution2 extends $2c {
  static {
    TerminalLinkContribution_1 = this;
  }
  static {
    this.ID = "terminal.link";
  }
  static get(instance2) {
    return instance2.getContribution(TerminalLinkContribution_1.ID);
  }
  constructor(h3, j, m) {
    super();
    this.h = h3;
    this.j = j;
    this.m = m;
    this.c = this.j.createInstance($Jgc);
  }
  xtermReady(xterm) {
    const linkManager = this.a = this.add(this.j.createInstance($Ggc, xterm.raw, this.h.processManager, this.h.instance.capabilities, this.c));
    if ($iY(this.h.processManager)) {
      const disposable = linkManager.add(Event2.once(this.h.processManager.onProcessReady)(() => {
        linkManager.setWidgetManager(this.h.widgetManager);
        this.delete(disposable);
      }));
    } else {
      linkManager.setWidgetManager(this.h.widgetManager);
    }
    if (!$9Pb(this.h.instance)) {
      for (const linkProvider of this.m.linkProviders) {
        linkManager.externalProvideLinksCb = linkProvider.provideLinks.bind(linkProvider, this.h.instance);
      }
      linkManager.add(this.m.onDidAddLinkProvider((e) => {
        linkManager.externalProvideLinksCb = e.provideLinks.bind(e, this.h.instance);
      }));
    }
    linkManager.add(this.m.onDidRemoveLinkProvider(() => linkManager.externalProvideLinksCb = void 0));
  }
  async showLinkQuickpick(extended) {
    if (!this.b) {
      this.b = this.add(this.j.createInstance($Igc));
      this.b.onDidRequestMoreLinks(() => {
        this.showLinkQuickpick(true);
      });
    }
    const links = await this.n();
    return await this.b.show(this.h.instance, links);
  }
  async n() {
    if (!this.a) {
      throw new Error("terminal links are not ready, cannot generate link quick pick");
    }
    return this.a.getLinks();
  }
  async openRecentLink(type) {
    if (!this.a) {
      throw new Error("terminal links are not ready, cannot open a link");
    }
    this.a.openRecentLink(type);
  }
};
TerminalLinkContribution = TerminalLinkContribution_1 = __decorate([
  __param(1, $Pk),
  __param(2, $tRb)
], TerminalLinkContribution);
$Y0b(TerminalLinkContribution.ID, TerminalLinkContribution, true);
var category5 = $Kec.actionCategory;
$Wec({
  id: "workbench.action.terminal.openDetectedLink",
  title: localize2(10922, "Open Detected Link..."),
  f1: true,
  category: category5,
  precondition: TerminalContextKeys.terminalHasBeenCreated,
  keybinding: [
    {
      primary: 2048 | 1024 | 45,
      weight: 200 + 1,
      when: TerminalContextKeys.focus
    },
    {
      primary: 2048 | 1024 | 37,
      weight: 200 + 1,
      when: $7m.and($osb, $7m.equals(
        $tsb.key,
        "terminal"
        /* AccessibleViewProviderId.Terminal */
      ))
    }
  ],
  run: (activeInstance) => TerminalLinkContribution.get(activeInstance)?.showLinkQuickpick()
});
$Wec({
  id: "workbench.action.terminal.openUrlLink",
  title: localize2(10923, "Open Last URL Link"),
  metadata: {
    description: localize2(10924, "Opens the last detected URL/URI link in the terminal")
  },
  f1: true,
  category: category5,
  precondition: TerminalContextKeys.terminalHasBeenCreated,
  run: (activeInstance) => TerminalLinkContribution.get(activeInstance)?.openRecentLink("url")
});
$Wec({
  id: "workbench.action.terminal.openFileLink",
  title: localize2(10925, "Open Last Local File Link"),
  f1: true,
  category: category5,
  precondition: TerminalContextKeys.terminalHasBeenCreated,
  run: (activeInstance) => TerminalLinkContribution.get(activeInstance)?.openRecentLink("localFile")
});

// out-build/vs/workbench/contrib/terminalContrib/zoom/browser/terminal.zoom.contribution.js
var TerminalMouseWheelZoomContribution_1;
var TerminalMouseWheelZoomContribution = class TerminalMouseWheelZoomContribution2 extends $3c {
  static {
    TerminalMouseWheelZoomContribution_1 = this;
  }
  static {
    this.ID = "terminal.mouseWheelZoom";
  }
  static get(instance2) {
    return instance2.getContribution(TerminalMouseWheelZoomContribution_1.ID);
  }
  constructor(_ctx, b) {
    super();
    this.b = b;
    this.a = this.B(new $4c());
  }
  xtermOpen(xterm) {
    this.B(Event2.runAndSubscribe(this.b.onDidChangeConfiguration, (e) => {
      if (!e || e.affectsConfiguration(
        "terminal.integrated.mouseWheelZoom"
        /* TerminalZoomSettingId.MouseWheelZoom */
      )) {
        if (!!this.b.getValue(
          "terminal.integrated.mouseWheelZoom"
          /* TerminalZoomSettingId.MouseWheelZoom */
        )) {
          this.g(xterm.raw);
        } else {
          this.a.clear();
        }
      }
    }));
  }
  f() {
    return this.b.getValue(
      "terminal.integrated.fontSize"
      /* TerminalSettingId.FontSize */
    );
  }
  g(raw) {
    const classifier = $yZ.INSTANCE;
    let prevMouseWheelTime = 0;
    let gestureStartFontSize = this.f();
    let gestureHasZoomModifiers = false;
    let gestureAccumulatedDelta = 0;
    raw.attachCustomWheelEventHandler((e) => {
      const browserEvent = e;
      if (classifier.isPhysicalMouseWheel()) {
        if (this.h(browserEvent)) {
          const delta = browserEvent.deltaY > 0 ? -1 : 1;
          this.b.updateValue("terminal.integrated.fontSize", this.f() + delta);
          browserEvent.preventDefault();
          browserEvent.stopPropagation();
          return false;
        }
      } else {
        if (Date.now() - prevMouseWheelTime > 50) {
          gestureStartFontSize = this.f();
          gestureHasZoomModifiers = this.h(browserEvent);
          gestureAccumulatedDelta = 0;
        }
        prevMouseWheelTime = Date.now();
        gestureAccumulatedDelta += browserEvent.deltaY;
        if (gestureHasZoomModifiers) {
          const deltaAbs = Math.ceil(Math.abs(gestureAccumulatedDelta / 5));
          const deltaDirection = gestureAccumulatedDelta > 0 ? -1 : 1;
          const delta = deltaAbs * deltaDirection;
          this.b.updateValue("terminal.integrated.fontSize", gestureStartFontSize + delta);
          gestureAccumulatedDelta += browserEvent.deltaY;
          browserEvent.preventDefault();
          browserEvent.stopPropagation();
          return false;
        }
      }
      return true;
    });
    this.a.value = $1c(() => raw.attachCustomWheelEventHandler(() => true));
  }
  h(browserEvent) {
    return $m ? (browserEvent.metaKey || browserEvent.ctrlKey) && !browserEvent.shiftKey && !browserEvent.altKey : browserEvent.ctrlKey && !browserEvent.metaKey && !browserEvent.shiftKey && !browserEvent.altKey;
  }
};
TerminalMouseWheelZoomContribution = TerminalMouseWheelZoomContribution_1 = __decorate([
  __param(1, $kl)
], TerminalMouseWheelZoomContribution);
$Y0b(TerminalMouseWheelZoomContribution.ID, TerminalMouseWheelZoomContribution, true);
$Uec({
  id: "workbench.action.terminal.fontZoomIn",
  title: localize2(11009, "Increase Font Size"),
  run: async (c, accessor) => {
    const configurationService = accessor.get($kl);
    const value = configurationService.getValue(
      "terminal.integrated.fontSize"
      /* TerminalSettingId.FontSize */
    );
    if ($Dg(value)) {
      await configurationService.updateValue("terminal.integrated.fontSize", value + 1);
    }
  }
});
$Uec({
  id: "workbench.action.terminal.fontZoomOut",
  title: localize2(11010, "Decrease Font Size"),
  run: async (c, accessor) => {
    const configurationService = accessor.get($kl);
    const value = configurationService.getValue(
      "terminal.integrated.fontSize"
      /* TerminalSettingId.FontSize */
    );
    if ($Dg(value)) {
      await configurationService.updateValue("terminal.integrated.fontSize", value - 1);
    }
  }
});
$Uec({
  id: "workbench.action.terminal.fontZoomReset",
  title: localize2(11011, "Reset Font Size"),
  run: async (c, accessor) => {
    const configurationService = accessor.get($kl);
    await configurationService.updateValue("terminal.integrated.fontSize", $Hfc);
  }
});

// out-build/vs/workbench/contrib/terminalContrib/stickyScroll/browser/terminal.stickyScroll.contribution.js
$Y0b($5fc.ID, $5fc);
var TerminalStickyScrollCommandId;
(function(TerminalStickyScrollCommandId2) {
  TerminalStickyScrollCommandId2["ToggleStickyScroll"] = "workbench.action.terminal.toggleStickyScroll";
})(TerminalStickyScrollCommandId || (TerminalStickyScrollCommandId = {}));
$Uec({
  id: "workbench.action.terminal.toggleStickyScroll",
  title: localize2(10969, "Toggle Sticky Scroll"),
  toggled: {
    condition: $7m.equals(`config.${"terminal.integrated.stickyScroll.enabled"}`, true),
    title: localize(10967, null),
    mnemonicTitle: localize(10968, null)
  },
  run: (c, accessor) => {
    const configurationService = accessor.get($kl);
    const newValue = !configurationService.getValue(
      "terminal.integrated.stickyScroll.enabled"
      /* TerminalStickyScrollSettingId.Enabled */
    );
    return configurationService.updateValue("terminal.integrated.stickyScroll.enabled", newValue);
  },
  menu: [
    { id: $bJ.TerminalStickyScrollContext }
  ]
});

// out-build/vs/workbench/contrib/terminalContrib/quickAccess/browser/terminalQuickAccess.js
var $Kgc_1;
var terminalPicks = [];
var $Kgc = class $Kgc2 extends $rhb {
  static {
    $Kgc_1 = this;
  }
  static {
    this.PREFIX = "term ";
  }
  constructor(a, b, h3, j, m, n, r2) {
    super($Kgc_1.PREFIX, { canAcceptInBackground: true });
    this.a = a;
    this.b = b;
    this.h = h3;
    this.j = j;
    this.m = m;
    this.n = n;
    this.r = r2;
  }
  g(filter) {
    terminalPicks = [];
    terminalPicks.push({ type: "separator", label: "panel" });
    const terminalGroups = this.m.groups;
    for (let groupIndex = 0; groupIndex < terminalGroups.length; groupIndex++) {
      const terminalGroup = terminalGroups[groupIndex];
      for (let terminalIndex = 0; terminalIndex < terminalGroup.terminalInstances.length; terminalIndex++) {
        const terminal2 = terminalGroup.terminalInstances[terminalIndex];
        const pick = this.t(terminal2, terminalIndex, filter, { groupIndex, groupSize: terminalGroup.terminalInstances.length });
        if (pick) {
          terminalPicks.push(pick);
        }
      }
    }
    if (terminalPicks.length > 0) {
      terminalPicks.push({ type: "separator", label: "editor" });
    }
    const terminalEditors = this.j.instances;
    for (let editorIndex = 0; editorIndex < terminalEditors.length; editorIndex++) {
      const term = terminalEditors[editorIndex];
      term.target = TerminalLocation2.Editor;
      const pick = this.t(term, editorIndex, filter);
      if (pick) {
        terminalPicks.push(pick);
      }
    }
    if (terminalPicks.length > 0) {
      terminalPicks.push({ type: "separator" });
    }
    const createTerminalLabel = localize(10952, null);
    terminalPicks.push({
      label: `$(plus) ${createTerminalLabel}`,
      ariaLabel: createTerminalLabel,
      accept: () => this.a.executeCommand(
        "workbench.action.terminal.new"
        /* TerminalCommandId.New */
      )
    });
    const createWithProfileLabel = localize(10953, null);
    terminalPicks.push({
      label: `$(plus) ${createWithProfileLabel}`,
      ariaLabel: createWithProfileLabel,
      accept: () => this.a.executeCommand(
        "workbench.action.terminal.newWithProfile"
        /* TerminalCommandId.NewWithProfile */
      )
    });
    return terminalPicks;
  }
  t(terminal2, terminalIndex, filter, groupInfo) {
    const iconId = this.h.invokeFunction($eQb, terminal2);
    const index = groupInfo ? groupInfo.groupSize > 1 ? `${groupInfo.groupIndex + 1}.${terminalIndex + 1}` : `${groupInfo.groupIndex + 1}` : `${terminalIndex + 1}`;
    const label3 = `$(${iconId}) ${index}: ${terminal2.title}`;
    const iconClasses = [];
    const colorClass = $_Pb(terminal2);
    if (colorClass) {
      iconClasses.push(colorClass);
    }
    const uriClasses = $dQb(terminal2, this.r.getColorTheme().type);
    if (uriClasses) {
      iconClasses.push(...uriClasses);
    }
    const highlights = $Rl(filter, label3, true);
    if (highlights) {
      return {
        label: label3,
        description: terminal2.description,
        highlights: { label: highlights },
        buttons: [
          {
            iconClass: ThemeIcon.asClassName($LPb),
            tooltip: localize(10954, null)
          },
          {
            iconClass: ThemeIcon.asClassName($MPb),
            tooltip: $Kec.kill.value
          }
        ],
        iconClasses,
        trigger: (buttonIndex) => {
          switch (buttonIndex) {
            case 0:
              this.a.executeCommand("workbench.action.terminal.rename", terminal2);
              return TriggerAction.NO_ACTION;
            case 1:
              this.n.safeDisposeTerminal(terminal2);
              return TriggerAction.REMOVE_ITEM;
          }
          return TriggerAction.NO_ACTION;
        },
        accept: (keyMod, event) => {
          if (terminal2.target === TerminalLocation2.Editor) {
            const existingEditors = this.b.findEditors(terminal2.resource);
            this.j.openEditor(terminal2, { viewColumn: existingEditors?.[0].groupId });
            this.j.setActiveInstance(terminal2);
          } else {
            this.m.showPanel(!event.inBackground);
            this.m.setActiveInstance(terminal2);
          }
        }
      };
    }
    return void 0;
  }
};
$Kgc = $Kgc_1 = __decorate([
  __param(0, $sn),
  __param(1, $mJ),
  __param(2, $Pk),
  __param(3, $6Pb),
  __param(4, $7Pb),
  __param(5, $4Pb),
  __param(6, $gs)
], $Kgc);

// out-build/vs/workbench/contrib/terminalContrib/quickAccess/browser/terminal.quickAccess.contribution.js
var TerminalQuickAccessCommandId;
(function(TerminalQuickAccessCommandId2) {
  TerminalQuickAccessCommandId2["QuickOpenTerm"] = "workbench.action.quickOpenTerm";
})(TerminalQuickAccessCommandId || (TerminalQuickAccessCommandId = {}));
var quickAccessRegistry4 = $Wn.as($CM.Quickaccess);
var inTerminalsPicker = "inTerminalPicker";
quickAccessRegistry4.registerQuickAccessProvider({
  ctor: $Kgc,
  prefix: $Kgc.PREFIX,
  contextKey: inTerminalsPicker,
  placeholder: localize(10949, null),
  helpEntries: [{
    description: localize(10950, null),
    commandId: "workbench.action.quickOpenTerm"
    /* TerminalQuickAccessCommandId.QuickOpenTerm */
  }]
});
var quickAccessNavigateNextInTerminalPickerId = "workbench.action.quickOpenNavigateNextInTerminalPicker";
$tn.registerCommand({ id: quickAccessNavigateNextInTerminalPickerId, handler: $9yb(quickAccessNavigateNextInTerminalPickerId, true) });
var quickAccessNavigatePreviousInTerminalPickerId = "workbench.action.quickOpenNavigatePreviousInTerminalPicker";
$tn.registerCommand({ id: quickAccessNavigatePreviousInTerminalPickerId, handler: $9yb(quickAccessNavigatePreviousInTerminalPickerId, false) });
$Uec({
  id: "workbench.action.quickOpenTerm",
  title: localize2(10951, "Switch Active Terminal"),
  precondition: $7m.or(TerminalContextKeys.processSupported, TerminalContextKeys.terminalHasBeenCreated),
  run: (c, accessor) => accessor.get($1M).quickAccess.show($Kgc.PREFIX)
});

// out-build/vs/workbench/contrib/terminalContrib/quickFix/browser/quickFixAddon.js
var QuickFixDecorationSelector;
(function(QuickFixDecorationSelector2) {
  QuickFixDecorationSelector2["QuickFix"] = "quick-fix";
})(QuickFixDecorationSelector || (QuickFixDecorationSelector = {}));
var quickFixClasses = [
  "quick-fix",
  "codicon",
  "terminal-command-decoration",
  "xterm-decoration"
  /* DecorationSelector.XtermDecoration */
];
var $Lgc = class $Lgc2 extends $3c {
  constructor(w, z, C, D, F, G, H, I, J, L, M) {
    super();
    this.w = w;
    this.z = z;
    this.C = C;
    this.D = D;
    this.F = F;
    this.G = G;
    this.H = H;
    this.I = I;
    this.J = J;
    this.L = L;
    this.M = M;
    this.b = /* @__PURE__ */ new Map();
    this.h = this.B(new $4c());
    this.j = this.B(new $4c());
    this.r = /* @__PURE__ */ new Set();
    this.s = false;
    this.t = new $ze();
    this.onDidRequestRerunCommand = this.t.event;
    this.u = new $ze();
    this.onDidUpdateQuickFixes = this.u.event;
    const commandDetectionCapability = this.z.get(
      2
      /* TerminalCapability.CommandDetection */
    );
    if (commandDetectionCapability) {
      this.N();
    } else {
      this.B(this.z.onDidAddCapabilityType((c) => {
        if (c === 2) {
          this.N();
        }
      }));
    }
    this.B(this.M.onDidRegisterProvider((result) => this.registerCommandFinishedListener(convertToQuickFixOptions(result))));
    this.M.extensionQuickFixes.then((quickFixSelectors) => {
      for (const selector of quickFixSelectors) {
        this.registerCommandSelector(selector);
      }
    });
    this.B(this.M.onDidRegisterCommandSelector((selector) => this.registerCommandSelector(selector)));
    this.B(this.M.onDidUnregisterProvider((id2) => this.b.delete(id2)));
  }
  activate(terminal2) {
    this.a = terminal2;
  }
  showMenu() {
    if (!this.m) {
      return;
    }
    const actions = this.m.quickFixes.map((f) => new TerminalQuickFixItem(f, f.type, f.source, f.label, f.kind));
    const actionSet = {
      allActions: actions,
      hasAutoFix: false,
      hasAIFix: false,
      allAIFixes: false,
      validActions: actions,
      dispose: () => {
      }
    };
    const delegate = {
      onSelect: async (fix) => {
        fix.action?.run();
        this.D.hide();
      },
      onHide: () => {
        this.a?.focus();
      }
    };
    this.D.show("quickFixWidget", false, toActionWidgetItems(actionSet.validActions, true), delegate, this.m.anchor, this.m.parentElement);
  }
  registerCommandSelector(selector) {
    if (this.r.has(selector.id)) {
      return;
    }
    const matcherKey = selector.commandLineMatcher.toString();
    const currentOptions = this.b.get(matcherKey) || [];
    currentOptions.push({
      id: selector.id,
      type: "unresolved",
      commandLineMatcher: selector.commandLineMatcher,
      outputMatcher: selector.outputMatcher,
      commandExitResult: selector.commandExitResult,
      kind: selector.kind
    });
    this.r.add(selector.id);
    this.b.set(matcherKey, currentOptions);
  }
  registerCommandFinishedListener(options3) {
    const matcherKey = options3.commandLineMatcher.toString();
    let currentOptions = this.b.get(matcherKey) || [];
    currentOptions = currentOptions.filter((o) => o.id !== options3.id);
    currentOptions.push(options3);
    this.b.set(matcherKey, currentOptions);
  }
  N() {
    const terminal2 = this.a;
    const commandDetection = this.z.get(
      2
      /* TerminalCapability.CommandDetection */
    );
    if (!terminal2 || !commandDetection) {
      return;
    }
    this.B(commandDetection.onCommandFinished(async (command4) => await this.O(command4, this.w)));
  }
  /**
   * Resolves quick fixes, if any, based on the
   * @param command & its output
   */
  async O(command4, aliases) {
    const terminal2 = this.a;
    if (!terminal2 || command4.wasReplayed) {
      return;
    }
    if (command4.command !== "" && this.n) {
      this.P(command4, this.n);
    }
    const resolver = async (selector, lines) => {
      if (lines === void 0) {
        return void 0;
      }
      const id2 = selector.id;
      await this.H.activateByEvent(`onTerminalQuickFixRequest:${id2}`);
      return this.M.providers.get(id2)?.provideTerminalQuickFixes(command4, lines, {
        type: "resolved",
        commandLineMatcher: selector.commandLineMatcher,
        outputMatcher: selector.outputMatcher,
        commandExitResult: selector.commandExitResult,
        kind: selector.kind,
        id: selector.id
      }, new $ad().token);
    };
    const result = await $Mgc(aliases, terminal2, command4, this.b, this.F, this.J, this.I, this.t, resolver);
    if (!result) {
      return;
    }
    this.g = result;
    this.n = this.g[0].id;
    this.Q();
    this.u.fire({ command: command4, actions: this.g });
    this.g = void 0;
  }
  P(command4, id2) {
    this.L?.publicLog2("terminal/quick-fix", {
      quickFixId: id2,
      ranQuickFix: this.s
    });
    this.h.clear();
    this.j.clear();
    this.u.fire({ command: command4, actions: this.g });
    this.g = void 0;
    this.n = void 0;
    this.s = false;
  }
  /**
   * Registers a decoration with the quick fixes
   */
  Q() {
    if (!this.a) {
      return;
    }
    this.h.clear();
    this.j.clear();
    const quickFixes = this.g;
    if (!quickFixes || quickFixes.length === 0) {
      return;
    }
    const marker = this.a.registerMarker();
    if (!marker) {
      return;
    }
    const decoration3 = this.h.value = this.a.registerDecoration({ marker, width: 2, layer: "top" });
    if (!decoration3) {
      return;
    }
    const store = this.j.value = new $2c();
    store.add(decoration3.onRender((e) => {
      const rect = e.getBoundingClientRect();
      const anchor = {
        x: rect.x,
        y: rect.y,
        width: rect.width,
        height: rect.height
      };
      if (e.classList.contains(
        "quick-fix"
        /* QuickFixDecorationSelector.QuickFix */
      )) {
        if (this.m) {
          this.m.anchor = anchor;
        }
        return;
      }
      e.classList.add(...quickFixClasses);
      const isExplainOnly = quickFixes.every((e2) => e2.kind === "explain");
      if (isExplainOnly) {
        e.classList.add("explainOnly");
      }
      e.classList.add(...ThemeIcon.asClassNameArray(isExplainOnly ? $6l.sparkle : $6l.lightBulb));
      $YPb(this.G, e);
      this.C.playSignal($N9.terminalQuickFix);
      const parentElement = e.closest(".xterm")?.parentElement;
      if (!parentElement) {
        return;
      }
      this.m = { quickFixes, anchor, parentElement };
      this.B($_i(e, $7j.CLICK, () => this.showMenu()));
    }));
    store.add(decoration3.onDispose(() => this.m = void 0));
  }
};
$Lgc = __decorate([
  __param(2, $I9),
  __param(3, $dab),
  __param(4, $sn),
  __param(5, $kl),
  __param(6, $wN),
  __param(7, $ZI),
  __param(8, $O4),
  __param(9, $zv),
  __param(10, $uRb)
], $Lgc);
async function $Mgc(aliases, terminal2, terminalCommand, quickFixOptions, commandService, openerService, labelService, onDidRequestRerunCommand, getResolvedFixes) {
  const commandQuickFixSet = /* @__PURE__ */ new Set();
  const openQuickFixSet = /* @__PURE__ */ new Set();
  const fixes = [];
  const newCommand = terminalCommand.command;
  for (const options3 of quickFixOptions.values()) {
    for (const option of options3) {
      if (option.commandExitResult === "success" && terminalCommand.exitCode !== 0 || option.commandExitResult === "error" && terminalCommand.exitCode === 0) {
        continue;
      }
      let quickFixes;
      if (option.type === "resolved") {
        quickFixes = await option.getQuickFixes(terminalCommand, $CPb(terminal2.buffer.active, terminalCommand, terminal2.cols, option.outputMatcher), option, new $ad().token);
      } else if (option.type === "unresolved") {
        if (!getResolvedFixes) {
          throw new Error("No resolved fix provider");
        }
        quickFixes = await getResolvedFixes(option, option.outputMatcher ? $CPb(terminal2.buffer.active, terminalCommand, terminal2.cols, option.outputMatcher) : void 0);
      } else if (option.type === "internal") {
        const commandLineMatch = newCommand.match(option.commandLineMatcher);
        if (!commandLineMatch) {
          continue;
        }
        const outputMatcher = option.outputMatcher;
        let outputMatch;
        if (outputMatcher) {
          outputMatch = terminalCommand.getOutputMatch(outputMatcher);
        }
        if (!outputMatch) {
          continue;
        }
        const matchResult = { commandLineMatch, outputMatch, commandLine: terminalCommand.command };
        quickFixes = option.getQuickFixes(matchResult);
      }
      if (quickFixes) {
        for (const quickFix of $5b(quickFixes)) {
          let action;
          if ("type" in quickFix) {
            switch (quickFix.type) {
              case TerminalQuickFixType2.TerminalCommand: {
                const fix = quickFix;
                if (commandQuickFixSet.has(fix.terminalCommand)) {
                  continue;
                }
                commandQuickFixSet.add(fix.terminalCommand);
                const label3 = localize(10955, null, fix.terminalCommand);
                action = {
                  type: TerminalQuickFixType2.TerminalCommand,
                  kind: option.kind,
                  class: void 0,
                  source: quickFix.source,
                  id: quickFix.id,
                  label: label3,
                  enabled: true,
                  run: () => {
                    onDidRequestRerunCommand?.fire({
                      command: fix.terminalCommand,
                      shouldExecute: fix.shouldExecute ?? true
                    });
                  },
                  tooltip: label3,
                  command: fix.terminalCommand,
                  shouldExecute: fix.shouldExecute
                };
                break;
              }
              case TerminalQuickFixType2.Opener: {
                const fix = quickFix;
                if (!fix.uri) {
                  return;
                }
                if (openQuickFixSet.has(fix.uri.toString())) {
                  continue;
                }
                openQuickFixSet.add(fix.uri.toString());
                const isUrl = fix.uri.scheme === Schemas.http || fix.uri.scheme === Schemas.https;
                const uriLabel = isUrl ? encodeURI(fix.uri.toString(true)) : labelService.getUriLabel(fix.uri);
                const label3 = localize(10956, null, uriLabel);
                action = {
                  source: quickFix.source,
                  id: quickFix.id,
                  label: label3,
                  type: TerminalQuickFixType2.Opener,
                  kind: option.kind,
                  class: void 0,
                  enabled: true,
                  run: () => openerService.open(fix.uri),
                  tooltip: label3,
                  uri: fix.uri
                };
                break;
              }
              case TerminalQuickFixType2.Port: {
                const fix = quickFix;
                action = {
                  source: "builtin",
                  type: fix.type,
                  kind: option.kind,
                  id: fix.id,
                  label: fix.label,
                  class: fix.class,
                  enabled: fix.enabled,
                  run: () => {
                    fix.run();
                  },
                  tooltip: fix.tooltip
                };
                break;
              }
              case TerminalQuickFixType2.VscodeCommand: {
                const fix = quickFix;
                action = {
                  source: quickFix.source,
                  type: fix.type,
                  kind: option.kind,
                  id: fix.id,
                  label: fix.title,
                  class: void 0,
                  enabled: true,
                  run: () => commandService.executeCommand(fix.id),
                  tooltip: fix.title
                };
                break;
              }
            }
            if (action) {
              fixes.push(action);
            }
          }
        }
      }
    }
  }
  return fixes.length > 0 ? fixes : void 0;
}
function convertToQuickFixOptions(selectorProvider) {
  return {
    id: selectorProvider.selector.id,
    type: "resolved",
    commandLineMatcher: selectorProvider.selector.commandLineMatcher,
    outputMatcher: selectorProvider.selector.outputMatcher,
    commandExitResult: selectorProvider.selector.commandExitResult,
    kind: selectorProvider.selector.kind,
    getQuickFixes: selectorProvider.provider.provideTerminalQuickFixes
  };
}
var TerminalQuickFixItem = class {
  constructor(action, type, source, title, kind = "fix") {
    this.action = action;
    this.type = type;
    this.source = source;
    this.title = title;
    this.kind = kind;
    this.disabled = false;
  }
};
function toActionWidgetItems(inputQuickFixes, showHeaders) {
  const menuItems = [];
  menuItems.push({
    kind: "header",
    group: {
      kind: $pab.QuickFix,
      title: localize(10957, null)
    }
  });
  for (const quickFix of showHeaders ? inputQuickFixes : inputQuickFixes.filter((i2) => !!i2.action)) {
    if (!quickFix.disabled && quickFix.action) {
      menuItems.push({
        kind: "action",
        item: quickFix,
        group: {
          kind: $pab.QuickFix,
          icon: getQuickFixIcon(quickFix),
          title: quickFix.action.label
        },
        disabled: false,
        label: quickFix.title
      });
    }
  }
  return menuItems;
}
function getQuickFixIcon(quickFix) {
  if (quickFix.kind === "explain") {
    return $6l.sparkle;
  }
  switch (quickFix.type) {
    case TerminalQuickFixType2.Opener:
      if ("uri" in quickFix.action && quickFix.action.uri) {
        const isUrl = quickFix.action.uri.scheme === Schemas.http || quickFix.action.uri.scheme === Schemas.https;
        return isUrl ? $6l.linkExternal : $6l.goToFile;
      }
    case TerminalQuickFixType2.TerminalCommand:
      return $6l.run;
    case TerminalQuickFixType2.Port:
      return $6l.debugDisconnect;
    case TerminalQuickFixType2.VscodeCommand:
      return $6l.lightbulb;
  }
}

// out-build/vs/workbench/contrib/terminalContrib/quickFix/browser/terminalQuickFixBuiltinActions.js
var $Ngc = /git/;
var $Ogc = /and can be fast-forwarded/;
var $Pgc = /git\s+push/;
var $Qgc = /error: did you mean `--(.+)` \(with two dashes\)\?/;
var $Rgc = /(?:(most similar commands? (is|are)))/;
var $Sgc = /(?:address already in use (?:0\.0\.0\.0|127\.0\.0\.1|localhost|::):|Unable to bind [^ ]*:|can't listen on port |listen EADDRINUSE [^ ]*:)(?<portNumber>\d{4,5})/;
var $Tgc = /git push --set-upstream origin (?<branchName>[^\s]+)/;
var $Ugc = /remote:\s*(?<link>https:\/\/github\.com\/.+\/.+\/pull\/new\/.+)/;
var $Vgc = /Suggestion \[General\]:/;
var $Wgc = /Suggestion \[cmd-not-found\]:/;
var QuickFixSource;
(function(QuickFixSource2) {
  QuickFixSource2["Builtin"] = "builtin";
})(QuickFixSource || (QuickFixSource = {}));
function $Xgc() {
  return {
    id: "Git Similar",
    type: "internal",
    commandLineMatcher: $Ngc,
    outputMatcher: {
      lineMatcher: $Rgc,
      anchor: "bottom",
      offset: 0,
      length: 10
    },
    commandExitResult: "error",
    getQuickFixes: (matchResult) => {
      const regexMatch = matchResult.outputMatch?.regexMatch[0];
      if (!regexMatch || !matchResult.outputMatch) {
        return;
      }
      const actions = [];
      const startIndex = matchResult.outputMatch.outputLines.findIndex((l) => l.includes(regexMatch)) + 1;
      const results = matchResult.outputMatch.outputLines.map((r2) => r2.trim());
      for (let i2 = startIndex; i2 < results.length; i2++) {
        const fixedCommand = results[i2];
        if (fixedCommand) {
          actions.push({
            id: "Git Similar",
            type: TerminalQuickFixType2.TerminalCommand,
            terminalCommand: matchResult.commandLine.replace(/git\s+[^\s]+/, () => `git ${fixedCommand}`),
            shouldExecute: true,
            source: "builtin"
            /* QuickFixSource.Builtin */
          });
        }
      }
      return actions;
    }
  };
}
function $Ygc() {
  return {
    id: "Git Fast Forward Pull",
    type: "internal",
    commandLineMatcher: $Ngc,
    outputMatcher: {
      lineMatcher: $Ogc,
      anchor: "bottom",
      offset: 0,
      length: 8
    },
    commandExitResult: "success",
    getQuickFixes: (matchResult) => {
      return {
        type: TerminalQuickFixType2.TerminalCommand,
        id: "Git Fast Forward Pull",
        terminalCommand: `git pull`,
        shouldExecute: true,
        source: "builtin"
        /* QuickFixSource.Builtin */
      };
    }
  };
}
function $Zgc() {
  return {
    id: "Git Two Dashes",
    type: "internal",
    commandLineMatcher: $Ngc,
    outputMatcher: {
      lineMatcher: $Qgc,
      anchor: "bottom",
      offset: 0,
      length: 2
    },
    commandExitResult: "error",
    getQuickFixes: (matchResult) => {
      const problemArg = matchResult?.outputMatch?.regexMatch?.[1];
      if (!problemArg) {
        return;
      }
      return {
        type: TerminalQuickFixType2.TerminalCommand,
        id: "Git Two Dashes",
        terminalCommand: matchResult.commandLine.replace(` -${problemArg}`, () => ` --${problemArg}`),
        shouldExecute: true,
        source: "builtin"
        /* QuickFixSource.Builtin */
      };
    }
  };
}
function $1gc(runCallback) {
  return {
    id: "Free Port",
    type: "internal",
    commandLineMatcher: /.+/,
    outputMatcher: {
      lineMatcher: $Sgc,
      anchor: "bottom",
      offset: 0,
      length: 30
    },
    commandExitResult: "error",
    getQuickFixes: (matchResult) => {
      const port = matchResult?.outputMatch?.regexMatch?.groups?.portNumber;
      if (!port) {
        return;
      }
      const label3 = localize(10959, null, port);
      return {
        type: TerminalQuickFixType2.Port,
        class: void 0,
        tooltip: label3,
        id: "Free Port",
        label: label3,
        enabled: true,
        source: "builtin",
        run: () => runCallback(port, matchResult.commandLine)
      };
    }
  };
}
function $2gc() {
  return {
    id: "Git Push Set Upstream",
    type: "internal",
    commandLineMatcher: $Pgc,
    /**
                Example output on Windows:
                8: PS C:\Users\merogge\repos\xterm.js> git push
                7: fatal: The current branch sdjfskdjfdslkjf has no upstream branch.
                6: To push the current branch and set the remote as upstream, use
                5:
                4:	git push --set-upstream origin sdjfskdjfdslkjf
                3:
                2: To have this happen automatically for branches without a tracking
                1: upstream, see 'push.autoSetupRemote' in 'git help config'.
                0:
    
                Example output on macOS:
                5: meganrogge@Megans-MacBook-Pro xterm.js % git push
                4: fatal: The current branch merogge/asjdkfsjdkfsdjf has no upstream branch.
                3: To push the current branch and set the remote as upstream, use
                2:
                1:	git push --set-upstream origin merogge/asjdkfsjdkfsdjf
                0:
             */
    outputMatcher: {
      lineMatcher: $Tgc,
      anchor: "bottom",
      offset: 0,
      length: 8
    },
    commandExitResult: "error",
    getQuickFixes: (matchResult) => {
      const matches = matchResult.outputMatch;
      const commandToRun = "git push --set-upstream origin ${group:branchName}";
      if (!matches) {
        return;
      }
      const groups = matches.regexMatch.groups;
      if (!groups) {
        return;
      }
      const actions = [];
      let fixedCommand = commandToRun;
      for (const [key2, value] of Object.entries(groups)) {
        const varToResolve = `\${group:${key2}}`;
        if (!commandToRun.includes(varToResolve)) {
          return [];
        }
        fixedCommand = fixedCommand.replaceAll(varToResolve, () => value);
      }
      if (fixedCommand) {
        actions.push({
          type: TerminalQuickFixType2.TerminalCommand,
          id: "Git Push Set Upstream",
          terminalCommand: fixedCommand,
          shouldExecute: true,
          source: "builtin"
          /* QuickFixSource.Builtin */
        });
        return actions;
      }
      return;
    }
  };
}
function $3gc() {
  return {
    id: "Git Create Pr",
    type: "internal",
    commandLineMatcher: $Pgc,
    // Example output:
    // ...
    // 10: remote:
    // 9:  remote: Create a pull request for 'my_branch' on GitHub by visiting:
    // 8:  remote:      https://github.com/microsoft/vscode/pull/new/my_branch
    // 7:  remote:
    // 6:  remote: GitHub found x vulnerabilities on microsoft/vscode's default branch (...). To find out more, visit:
    // 5:  remote:      https://github.com/microsoft/vscode/security/dependabot
    // 4:  remote:
    // 3:  To https://github.com/microsoft/vscode
    // 2:  * [new branch]              my_branch -> my_branch
    // 1:  Branch 'my_branch' set up to track remote branch 'my_branch' from 'origin'.
    // 0:
    outputMatcher: {
      lineMatcher: $Ugc,
      anchor: "bottom",
      offset: 4,
      // ~6 should only be needed here for security alerts, but the git provider can customize
      // the text, so use 12 to be safe.
      length: 12
    },
    commandExitResult: "success",
    getQuickFixes: (matchResult) => {
      const link2 = matchResult?.outputMatch?.regexMatch?.groups?.link?.trimEnd();
      if (!link2) {
        return;
      }
      const label3 = localize(10960, null, link2);
      return {
        id: "Git Create Pr",
        label: label3,
        enabled: true,
        type: TerminalQuickFixType2.Opener,
        uri: URI.parse(link2),
        source: "builtin"
        /* QuickFixSource.Builtin */
      };
    }
  };
}
function $4gc() {
  return {
    id: "Pwsh General Error",
    type: "internal",
    commandLineMatcher: /.+/,
    outputMatcher: {
      lineMatcher: $Vgc,
      anchor: "bottom",
      offset: 0,
      length: 10
    },
    commandExitResult: "error",
    getQuickFixes: (matchResult) => {
      const lines = matchResult.outputMatch?.regexMatch.input?.split("\n");
      if (!lines) {
        return;
      }
      let i2 = 0;
      let inFeedbackProvider = false;
      for (; i2 < lines.length; i2++) {
        if (lines[i2].match($Vgc)) {
          inFeedbackProvider = true;
          break;
        }
      }
      if (!inFeedbackProvider) {
        return;
      }
      const suggestions = lines[i2 + 1].match(/The most similar commands are: (?<values>.+)./)?.groups?.values?.split(", ");
      if (!suggestions) {
        return;
      }
      const result = [];
      for (const suggestion of suggestions) {
        result.push({
          id: "Pwsh General Error",
          type: TerminalQuickFixType2.TerminalCommand,
          terminalCommand: suggestion,
          source: "builtin"
          /* QuickFixSource.Builtin */
        });
      }
      return result;
    }
  };
}
function $5gc() {
  return {
    id: "Unix Command Not Found",
    type: "internal",
    commandLineMatcher: /.+/,
    outputMatcher: {
      lineMatcher: $Wgc,
      anchor: "bottom",
      offset: 0,
      length: 10
    },
    commandExitResult: "error",
    getQuickFixes: (matchResult) => {
      const lines = matchResult.outputMatch?.regexMatch.input?.split("\n");
      if (!lines) {
        return;
      }
      let i2 = 0;
      let inFeedbackProvider = false;
      for (; i2 < lines.length; i2++) {
        if (lines[i2].match($Wgc)) {
          inFeedbackProvider = true;
          break;
        }
      }
      if (!inFeedbackProvider) {
        return;
      }
      const result = [];
      let inSuggestions = false;
      for (; i2 < lines.length; i2++) {
        const line = lines[i2].trim();
        if (line.length === 0) {
          break;
        }
        const installCommand = line.match(/You also have .+ installed, you can run '(?<command>.+)' instead./)?.groups?.command;
        if (installCommand) {
          result.push({
            id: "Pwsh Unix Command Not Found Error",
            type: TerminalQuickFixType2.TerminalCommand,
            terminalCommand: installCommand,
            source: "builtin"
            /* QuickFixSource.Builtin */
          });
          inSuggestions = false;
          continue;
        }
        if (line.match(/Command '.+' not found, but can be installed with:/)) {
          inSuggestions = true;
          continue;
        }
        if (inSuggestions) {
          result.push({
            id: "Pwsh Unix Command Not Found Error",
            type: TerminalQuickFixType2.TerminalCommand,
            terminalCommand: line.trim(),
            source: "builtin"
            /* QuickFixSource.Builtin */
          });
        }
      }
      return result;
    }
  };
}

// out-build/vs/workbench/contrib/terminalContrib/quickFix/browser/terminalQuickFixService.js
var $6gc = class $6gc2 {
  get providers() {
    return this.b;
  }
  constructor(g) {
    this.g = g;
    this.a = /* @__PURE__ */ new Map();
    this.b = /* @__PURE__ */ new Map();
    this.d = new $ze();
    this.onDidRegisterProvider = this.d.event;
    this.e = new $ze();
    this.onDidRegisterCommandSelector = this.e.event;
    this.f = new $ze();
    this.onDidUnregisterProvider = this.f.event;
    this.extensionQuickFixes = new Promise((r2) => quickFixExtensionPoint.setHandler((fixes) => {
      r2(fixes.filter((c) => $zN(c.description, "terminalQuickFixProvider")).map((c) => {
        if (!c.value) {
          return [];
        }
        return c.value.map((fix) => {
          return { ...fix, extensionIdentifier: c.description.identifier.value };
        });
      }).flat());
    }));
    this.extensionQuickFixes.then((selectors) => {
      for (const selector of selectors) {
        this.registerCommandSelector(selector);
      }
    });
  }
  registerCommandSelector(selector) {
    this.a.set(selector.id, selector);
    this.e.fire(selector);
  }
  registerQuickFixProvider(id2, provider) {
    let disposed = false;
    this.extensionQuickFixes.then(() => {
      if (disposed) {
        return;
      }
      this.b.set(id2, provider);
      const selector = this.a.get(id2);
      if (!selector) {
        this.g.error(`No registered selector for ID: ${id2}`);
        return;
      }
      this.d.fire({ selector, provider });
    });
    return $1c(() => {
      disposed = true;
      this.b.delete(id2);
      const selector = this.a.get(id2);
      if (selector) {
        this.a.delete(id2);
        this.f.fire(selector.id);
      }
    });
  }
};
$6gc = __decorate([
  __param(0, $wn)
], $6gc);
var quickFixExtensionPoint = $tN.registerExtensionPoint({
  extensionPoint: "terminalQuickFixes",
  defaultExtensionKind: ["workspace"],
  activationEventsGenerator: (terminalQuickFixes, result) => {
    for (const quickFixContrib of terminalQuickFixes ?? []) {
      result.push(`onTerminalQuickFixRequest:${quickFixContrib.id}`);
    }
  },
  jsonSchema: {
    description: localize(10961, null),
    type: "array",
    items: {
      type: "object",
      additionalProperties: false,
      required: ["id", "commandLineMatcher", "outputMatcher", "commandExitResult"],
      defaultSnippets: [{
        body: {
          id: "$1",
          commandLineMatcher: "$2",
          outputMatcher: "$3",
          exitStatus: "$4"
        }
      }],
      properties: {
        id: {
          description: localize(10962, null),
          type: "string"
        },
        commandLineMatcher: {
          description: localize(10963, null),
          type: "string"
        },
        outputMatcher: {
          markdownDescription: localize(10964, null),
          type: "object",
          required: ["lineMatcher", "anchor", "offset", "length"],
          properties: {
            lineMatcher: {
              description: "A regular expression or string to test the command line against",
              type: "string"
            },
            anchor: {
              description: "Where the search should begin in the buffer",
              enum: ["top", "bottom"]
            },
            offset: {
              description: "The number of lines vertically from the anchor in the buffer to start matching against",
              type: "number"
            },
            length: {
              description: "The number of rows to match against, this should be as small as possible for performance reasons",
              type: "number"
            }
          }
        },
        commandExitResult: {
          description: localize(10965, null),
          enum: ["success", "error"],
          enumDescriptions: [
            "The command exited with an exit code of zero.",
            "The command exited with a non-zero exit code."
          ]
        },
        kind: {
          description: localize(10966, null, '`"fix"`'),
          enum: ["default", "explain"],
          enumDescriptions: [
            "A high confidence quick fix.",
            "An explanation of the problem."
          ]
        }
      }
    }
  }
});

// out-build/vs/workbench/contrib/terminalContrib/quickFix/browser/terminal.quickFix.contribution.js
var TerminalQuickFixContribution_1;
$SC(
  $uRb,
  $6gc,
  1
  /* InstantiationType.Delayed */
);
var TerminalQuickFixContribution = class TerminalQuickFixContribution2 extends $2c {
  static {
    TerminalQuickFixContribution_1 = this;
  }
  static {
    this.ID = "quickFix";
  }
  static get(instance2) {
    return instance2.getContribution(TerminalQuickFixContribution_1.ID);
  }
  get addon() {
    return this.a;
  }
  constructor(c, h3) {
    super();
    this.c = c;
    this.h = h3;
    this.b = this.add(new $4c());
  }
  xtermReady(xterm) {
    this.a = this.h.createInstance($Lgc, void 0, this.c.instance.capabilities);
    xterm.raw.loadAddon(this.a);
    this.add(this.a.onDidRequestRerunCommand((e) => this.c.instance.runCommand(e.command, e.shouldExecute || false)));
    this.add(this.a.onDidUpdateQuickFixes((e) => {
      this.b.value = e.actions ? xterm.decorationAddon.registerMenuItems(e.command, e.actions) : void 0;
    }));
    for (const actionOption of [
      $Zgc(),
      $Ygc(),
      $1gc((port, command4) => this.c.instance.freePortKillProcess(port, command4)),
      $Xgc(),
      $2gc(),
      $3gc(),
      $5gc(),
      $4gc()
    ]) {
      this.a.registerCommandFinishedListener(actionOption);
    }
  }
};
TerminalQuickFixContribution = TerminalQuickFixContribution_1 = __decorate([
  __param(1, $Pk)
], TerminalQuickFixContribution);
$Y0b(TerminalQuickFixContribution.ID, TerminalQuickFixContribution);
var TerminalQuickFixCommandId;
(function(TerminalQuickFixCommandId2) {
  TerminalQuickFixCommandId2["ShowQuickFixes"] = "workbench.action.terminal.showQuickFixes";
})(TerminalQuickFixCommandId || (TerminalQuickFixCommandId = {}));
$Wec({
  id: "workbench.action.terminal.showQuickFixes",
  title: localize2(10958, "Show Terminal Quick Fixes"),
  precondition: TerminalContextKeys.focus,
  keybinding: {
    primary: 2048 | 89,
    weight: 200
    /* KeybindingWeight.WorkbenchContrib */
  },
  run: (activeInstance) => TerminalQuickFixContribution.get(activeInstance)?.addon?.showMenu()
});

// out-build/vs/workbench/contrib/terminalContrib/typeAhead/browser/terminalTypeAheadAddon.js
var VT;
(function(VT2) {
  VT2["Esc"] = "\x1B";
  VT2["Csi"] = "\x1B[";
  VT2["ShowCursor"] = "\x1B[?25h";
  VT2["HideCursor"] = "\x1B[?25l";
  VT2["DeleteChar"] = "\x1B[X";
  VT2["DeleteRestOfLine"] = "\x1B[K";
})(VT || (VT = {}));
var CSI_STYLE_RE = /^\x1b\[[0-9;]*m/;
var CSI_MOVE_RE = /^\x1b\[?([0-9]*)(;[35])?O?([DC])/;
var NOT_WORD_RE = /[^a-z0-9]/i;
var StatsConstants;
(function(StatsConstants2) {
  StatsConstants2[StatsConstants2["StatsBufferSize"] = 24] = "StatsBufferSize";
  StatsConstants2[StatsConstants2["StatsSendTelemetryEvery"] = 3e5] = "StatsSendTelemetryEvery";
  StatsConstants2[StatsConstants2["StatsMinSamplesToTurnOn"] = 5] = "StatsMinSamplesToTurnOn";
  StatsConstants2[StatsConstants2["StatsMinAccuracyToTurnOn"] = 0.3] = "StatsMinAccuracyToTurnOn";
  StatsConstants2[StatsConstants2["StatsToggleOffThreshold"] = 0.5] = "StatsToggleOffThreshold";
})(StatsConstants || (StatsConstants = {}));
var PREDICTION_OMIT_RE = /^(\x1b\[(\??25[hl]|\??[0-9;]+n))+/;
var core = (terminal2) => terminal2._core;
var flushOutput = (terminal2) => {
};
var CursorMoveDirection;
(function(CursorMoveDirection2) {
  CursorMoveDirection2["Back"] = "D";
  CursorMoveDirection2["Forwards"] = "C";
})(CursorMoveDirection || (CursorMoveDirection = {}));
var Cursor = class _Cursor {
  get x() {
    return this.d;
  }
  get y() {
    return this.f;
  }
  get baseY() {
    return this.h;
  }
  get coordinate() {
    return { x: this.d, y: this.f, baseY: this.h };
  }
  constructor(rows, cols, j) {
    this.rows = rows;
    this.cols = cols;
    this.j = j;
    this.d = 0;
    this.f = 1;
    this.h = 1;
    this.d = j.cursorX;
    this.f = j.cursorY;
    this.h = j.baseY;
  }
  getLine() {
    return this.j.getLine(this.f + this.h);
  }
  getCell(loadInto) {
    return this.getLine()?.getCell(this.d, loadInto);
  }
  moveTo(coordinate) {
    this.d = coordinate.x;
    this.f = coordinate.y + coordinate.baseY - this.h;
    return this.moveInstruction();
  }
  clone() {
    const c = new _Cursor(this.rows, this.cols, this.j);
    c.moveTo(this);
    return c;
  }
  move(x, y) {
    this.d = x;
    this.f = y;
    return this.moveInstruction();
  }
  shift(x = 0, y = 0) {
    this.d += x;
    this.f += y;
    return this.moveInstruction();
  }
  moveInstruction() {
    if (this.f >= this.rows) {
      this.h += this.f - (this.rows - 1);
      this.f = this.rows - 1;
    } else if (this.f < 0) {
      this.h -= this.f;
      this.f = 0;
    }
    return `${"\x1B["}${this.f + 1};${this.d + 1}H`;
  }
};
var moveToWordBoundary = (b, cursor, direction) => {
  let ateLeadingWhitespace = false;
  if (direction < 0) {
    cursor.shift(-1);
  }
  let cell;
  while (cursor.x >= 0) {
    cell = cursor.getCell(cell);
    if (!cell?.getCode()) {
      return;
    }
    const chars = cell.getChars();
    if (NOT_WORD_RE.test(chars)) {
      if (ateLeadingWhitespace) {
        break;
      }
    } else {
      ateLeadingWhitespace = true;
    }
    cursor.shift(direction);
  }
  if (direction < 0) {
    cursor.shift(1);
  }
};
var MatchResult;
(function(MatchResult2) {
  MatchResult2[MatchResult2["Success"] = 0] = "Success";
  MatchResult2[MatchResult2["Failure"] = 1] = "Failure";
  MatchResult2[MatchResult2["Buffer"] = 2] = "Buffer";
})(MatchResult || (MatchResult = {}));
var StringReader = class {
  get remaining() {
    return this.d.length - this.index;
  }
  get eof() {
    return this.index === this.d.length;
  }
  get rest() {
    return this.d.slice(this.index);
  }
  constructor(d) {
    this.d = d;
    this.index = 0;
  }
  /**
   * Advances the reader and returns the character if it matches.
   */
  eatChar(char) {
    if (this.d[this.index] !== char) {
      return;
    }
    this.index++;
    return char;
  }
  /**
   * Advances the reader and returns the string if it matches.
   */
  eatStr(substr) {
    if (this.d.slice(this.index, substr.length) !== substr) {
      return;
    }
    this.index += substr.length;
    return substr;
  }
  /**
   * Matches and eats the substring character-by-character. If EOF is reached
   * before the substring is consumed, it will buffer. Index is not moved
   * if it's not a match.
   */
  eatGradually(substr) {
    const prevIndex = this.index;
    for (let i2 = 0; i2 < substr.length; i2++) {
      if (i2 > 0 && this.eof) {
        return 2;
      }
      if (!this.eatChar(substr[i2])) {
        this.index = prevIndex;
        return 1;
      }
    }
    return 0;
  }
  /**
   * Advances the reader and returns the regex if it matches.
   */
  eatRe(re) {
    const match = re.exec(this.d.slice(this.index));
    if (!match) {
      return;
    }
    this.index += match[0].length;
    return match;
  }
  /**
   * Advances the reader and returns the character if the code matches.
   */
  eatCharCode(min = 0, max = min + 1) {
    const code = this.d.charCodeAt(this.index);
    if (code < min || code >= max) {
      return void 0;
    }
    this.index++;
    return code;
  }
};
var HardBoundary = class {
  constructor() {
    this.clearAfterTimeout = false;
  }
  apply() {
    return "";
  }
  rollback() {
    return "";
  }
  rollForwards() {
    return "";
  }
  matches() {
    return 1;
  }
};
var TentativeBoundary = class {
  constructor(inner) {
    this.inner = inner;
  }
  apply(buffer, cursor) {
    this.d = cursor.clone();
    this.inner.apply(buffer, this.d);
    return "";
  }
  rollback(cursor) {
    this.inner.rollback(cursor.clone());
    return "";
  }
  rollForwards(cursor, withInput) {
    if (this.d) {
      cursor.moveTo(this.d);
    }
    return withInput;
  }
  matches(input) {
    return this.inner.matches(input);
  }
};
var isTenativeCharacterPrediction = (p) => p instanceof TentativeBoundary && p.inner instanceof CharacterPrediction;
var CharacterPrediction = class _CharacterPrediction {
  constructor(d, f) {
    this.d = d;
    this.f = f;
    this.affectsStyle = true;
  }
  apply(_, cursor) {
    const cell = cursor.getCell();
    this.appliedAt = cell ? { pos: cursor.coordinate, oldAttributes: attributesToSeq(cell), oldChar: cell.getChars() } : { pos: cursor.coordinate, oldAttributes: "", oldChar: "" };
    cursor.shift(1);
    return this.d.apply + this.f + this.d.undo;
  }
  rollback(cursor) {
    if (!this.appliedAt) {
      return "";
    }
    const { oldAttributes, oldChar, pos } = this.appliedAt;
    const r2 = cursor.moveTo(pos) + (oldChar ? `${oldAttributes}${oldChar}${cursor.moveTo(pos)}` : "\x1B[X");
    return r2;
  }
  rollForwards(cursor, input) {
    if (!this.appliedAt) {
      return "";
    }
    return cursor.clone().moveTo(this.appliedAt.pos) + input;
  }
  matches(input, lookBehind) {
    const startIndex = input.index;
    while (input.eatRe(CSI_STYLE_RE)) {
    }
    if (input.eof) {
      return 2;
    }
    if (input.eatChar(this.f)) {
      return 0;
    }
    if (lookBehind instanceof _CharacterPrediction) {
      const sillyZshOutcome = input.eatGradually(`\b${lookBehind.f}${this.f}`);
      if (sillyZshOutcome !== 1) {
        return sillyZshOutcome;
      }
    }
    input.index = startIndex;
    return 1;
  }
};
var BackspacePrediction = class {
  constructor(f) {
    this.f = f;
  }
  apply(_, cursor) {
    const isLastChar = !cursor.getLine()?.translateToString(void 0, cursor.x).trim();
    const pos = cursor.coordinate;
    const move = cursor.shift(-1);
    const cell = cursor.getCell();
    this.d = cell ? { isLastChar, pos, oldAttributes: attributesToSeq(cell), oldChar: cell.getChars() } : { isLastChar, pos, oldAttributes: "", oldChar: "" };
    return move + "\x1B[X";
  }
  rollback(cursor) {
    if (!this.d) {
      return "";
    }
    const { oldAttributes, oldChar, pos } = this.d;
    if (!oldChar) {
      return cursor.moveTo(pos) + "\x1B[X";
    }
    return oldAttributes + oldChar + cursor.moveTo(pos) + attributesToSeq(core(this.f)._inputHandler._curAttrData);
  }
  rollForwards() {
    return "";
  }
  matches(input) {
    if (this.d?.isLastChar) {
      const r1 = input.eatGradually(`\b${"\x1B["}K`);
      if (r1 !== 1) {
        return r1;
      }
      const r2 = input.eatGradually(`\b \b`);
      if (r2 !== 1) {
        return r2;
      }
    }
    return 1;
  }
};
var NewlinePrediction = class {
  apply(_, cursor) {
    this.d = cursor.coordinate;
    cursor.move(0, cursor.y + 1);
    return "\r\n";
  }
  rollback(cursor) {
    return this.d ? cursor.moveTo(this.d) : "";
  }
  rollForwards() {
    return "";
  }
  matches(input) {
    return input.eatGradually("\r\n");
  }
};
var LinewrapPrediction = class extends NewlinePrediction {
  apply(_, cursor) {
    this.d = cursor.coordinate;
    cursor.move(0, cursor.y + 1);
    return " \r";
  }
  matches(input) {
    const r2 = input.eatGradually(" \r");
    if (r2 !== 1) {
      const r22 = input.eatGradually(
        "\x1B[K"
        /* VT.DeleteRestOfLine */
      );
      return r22 === 2 ? 2 : r2;
    }
    return input.eatGradually("\r\n");
  }
};
var CursorMovePrediction = class {
  constructor(f, h3, j) {
    this.f = f;
    this.h = h3;
    this.j = j;
  }
  apply(buffer, cursor) {
    const prevPosition = cursor.x;
    const currentCell = cursor.getCell();
    const prevAttrs = currentCell ? attributesToSeq(currentCell) : "";
    const { j: amount, f: direction, h: moveByWords } = this;
    const delta = direction === "D" ? -1 : 1;
    const target = cursor.clone();
    if (moveByWords) {
      for (let i2 = 0; i2 < amount; i2++) {
        moveToWordBoundary(buffer, target, delta);
      }
    } else {
      target.shift(delta * amount);
    }
    this.d = {
      amount: Math.abs(cursor.x - target.x),
      prevPosition,
      prevAttrs,
      rollForward: cursor.moveTo(target)
    };
    return this.d.rollForward;
  }
  rollback(cursor) {
    if (!this.d) {
      return "";
    }
    return cursor.move(this.d.prevPosition, cursor.y) + this.d.prevAttrs;
  }
  rollForwards() {
    return "";
  }
  matches(input) {
    if (!this.d) {
      return 1;
    }
    const direction = this.f;
    const { amount, rollForward } = this.d;
    if (input.eatStr(`${"\x1B["}${direction}`.repeat(amount))) {
      return 0;
    }
    if (direction === "D") {
      if (input.eatStr(`\b`.repeat(amount))) {
        return 0;
      }
    }
    if (rollForward) {
      const r2 = input.eatGradually(rollForward);
      if (r2 !== 1) {
        return r2;
      }
    }
    return input.eatGradually(`${"\x1B["}${amount}${direction}`);
  }
};
var $7gc = class extends $3c {
  /**
   * Gets the percent (0-1) of predictions that were accurate.
   */
  get accuracy() {
    let correctCount = 0;
    for (const [, correct] of this.f) {
      if (correct) {
        correctCount++;
      }
    }
    return correctCount / (this.f.length || 1);
  }
  /**
   * Gets the number of recorded stats.
   */
  get sampleSize() {
    return this.f.length;
  }
  /**
   * Gets latency stats of successful predictions.
   */
  get latency() {
    const latencies = this.f.filter(([, correct]) => correct).map(([s]) => s).sort();
    return {
      count: latencies.length,
      min: latencies[0],
      median: latencies[Math.floor(latencies.length / 2)],
      max: latencies[latencies.length - 1]
    };
  }
  /**
   * Gets the maximum observed latency.
   */
  get maxLatency() {
    let max = -Infinity;
    for (const [latency, correct] of this.f) {
      if (correct) {
        max = Math.max(latency, max);
      }
    }
    return max;
  }
  constructor(timeline) {
    super();
    this.f = [];
    this.h = 0;
    this.j = /* @__PURE__ */ new WeakMap();
    this.m = new $ze();
    this.onChange = this.m.event;
    this.B(timeline.onPredictionAdded((p) => this.j.set(p, Date.now())));
    this.B(timeline.onPredictionSucceeded(this.t.bind(this, true)));
    this.B(timeline.onPredictionFailed(this.t.bind(this, false)));
  }
  t(correct, prediction) {
    const started = this.j.get(prediction);
    this.f[this.h] = [Date.now() - started, correct];
    this.h = (this.h + 1) % 24;
    this.m.fire();
  }
};
var $8gc = class {
  get u() {
    return this.d.filter(({ gen }) => gen === this.d[0].gen).map(({ p }) => p);
  }
  get isShowingPredictions() {
    return this.l;
  }
  get length() {
    return this.d.length;
  }
  constructor(terminal2, w) {
    this.terminal = terminal2;
    this.w = w;
    this.d = [];
    this.f = 0;
    this.l = false;
    this.o = new $ze();
    this.onPredictionAdded = this.o.event;
    this.q = new $ze();
    this.onPredictionFailed = this.q.event;
    this.t = new $ze();
    this.onPredictionSucceeded = this.t.event;
  }
  setShowPredictions(show2) {
    if (show2 === this.l) {
      return;
    }
    this.l = show2;
    const buffer = this.A();
    if (!buffer) {
      return;
    }
    const toApply = this.u;
    if (show2) {
      this.clearCursor();
      this.w.expectIncomingStyle(toApply.reduce((count, p) => p.affectsStyle ? count + 1 : count, 0));
      this.terminal.write(toApply.map((p) => p.apply(buffer, this.physicalCursor(buffer))).join(""));
    } else {
      this.terminal.write(toApply.reverse().map((p) => p.rollback(this.physicalCursor(buffer))).join(""));
    }
  }
  /**
   * Undoes any predictions written and resets expectations.
   */
  undoAllPredictions() {
    const buffer = this.A();
    if (this.l && buffer) {
      this.terminal.write(this.u.reverse().map((p) => p.rollback(this.physicalCursor(buffer))).join(""));
    }
    this.d = [];
  }
  /**
   * Should be called when input is incoming to the temrinal.
   */
  beforeServerInput(input) {
    const originalInput = input;
    if (this.k) {
      input = this.k + input;
      this.k = void 0;
    }
    if (!this.d.length) {
      this.z();
      return input;
    }
    const buffer = this.A();
    if (!buffer) {
      this.z();
      return input;
    }
    let output = "";
    const reader = new StringReader(input);
    const startingGen = this.d[0].gen;
    const emitPredictionOmitted = () => {
      const omit = reader.eatRe(PREDICTION_OMIT_RE);
      if (omit) {
        output += omit[0];
      }
    };
    ReadLoop: while (this.d.length && reader.remaining > 0) {
      emitPredictionOmitted();
      const { p: prediction, gen } = this.d[0];
      const cursor = this.physicalCursor(buffer);
      const beforeTestReaderIndex = reader.index;
      switch (prediction.matches(reader, this.m)) {
        case 0: {
          const eaten = input.slice(beforeTestReaderIndex, reader.index);
          if (gen === startingGen) {
            output += prediction.rollForwards?.(cursor, eaten);
          } else {
            prediction.apply(buffer, this.physicalCursor(buffer));
            output += eaten;
          }
          this.t.fire(prediction);
          this.m = prediction;
          this.d.shift();
          break;
        }
        case 2:
          this.k = input.slice(beforeTestReaderIndex);
          reader.index = input.length;
          break ReadLoop;
        case 1: {
          const rollback = this.d.filter((p) => p.gen === startingGen).reverse();
          output += rollback.map(({ p }) => p.rollback(this.physicalCursor(buffer))).join("");
          if (rollback.some((r2) => r2.p.affectsStyle)) {
            output += attributesToSeq(core(this.terminal)._inputHandler._curAttrData);
          }
          this.z();
          this.q.fire(prediction);
          break ReadLoop;
        }
      }
    }
    emitPredictionOmitted();
    if (!reader.eof) {
      output += reader.rest;
      this.z();
    }
    if (this.d.length && startingGen !== this.d[0].gen) {
      for (const { p, gen } of this.d) {
        if (gen !== this.d[0].gen) {
          break;
        }
        if (p.affectsStyle) {
          this.w.expectIncomingStyle();
        }
        output += p.apply(buffer, this.physicalCursor(buffer));
      }
    }
    if (!this.l) {
      return originalInput;
    }
    if (output.length === 0 || output === input) {
      return output;
    }
    if (this.h) {
      output += this.h.moveInstruction();
    }
    output = "\x1B[?25l" + output + "\x1B[?25h";
    return output;
  }
  /**
   * Clears any expected predictions and stored state. Should be called when
   * the pty gives us something we don't recognize.
   */
  z() {
    this.d = [];
    this.clearCursor();
    this.m = void 0;
  }
  /**
   * Appends a typeahead prediction.
   */
  addPrediction(buffer, prediction) {
    this.d.push({ gen: this.f, p: prediction });
    this.o.fire(prediction);
    if (this.f !== this.d[0].gen) {
      prediction.apply(buffer, this.tentativeCursor(buffer));
      return false;
    }
    const text2 = prediction.apply(buffer, this.physicalCursor(buffer));
    this.j = void 0;
    if (this.l && text2) {
      if (prediction.affectsStyle) {
        this.w.expectIncomingStyle();
      }
      this.terminal.write(text2);
    }
    return true;
  }
  addBoundary(buffer, prediction) {
    let applied = false;
    if (buffer && prediction) {
      applied = this.addPrediction(buffer, new TentativeBoundary(prediction));
      prediction.apply(buffer, this.tentativeCursor(buffer));
    }
    this.f++;
    return applied;
  }
  /**
   * Peeks the last prediction written.
   */
  peekEnd() {
    return this.d[this.d.length - 1]?.p;
  }
  /**
   * Peeks the first pending prediction.
   */
  peekStart() {
    return this.d[0]?.p;
  }
  /**
   * Current position of the cursor in the terminal.
   */
  physicalCursor(buffer) {
    if (!this.h) {
      if (this.l) {
        flushOutput(this.terminal);
      }
      this.h = new Cursor(this.terminal.rows, this.terminal.cols, buffer);
    }
    return this.h;
  }
  /**
   * Cursor position if all predictions and boundaries that have been inserted
   * so far turn out to be successfully predicted.
   */
  tentativeCursor(buffer) {
    if (!this.j) {
      this.j = this.physicalCursor(buffer).clone();
    }
    return this.j;
  }
  clearCursor() {
    this.h = void 0;
    this.j = void 0;
  }
  A() {
    const buffer = this.terminal.buffer.active;
    return buffer.type === "normal" ? buffer : void 0;
  }
};
var attributesToArgs = (cell) => {
  if (cell.isAttributeDefault()) {
    return [0];
  }
  const args2 = [];
  if (cell.isBold()) {
    args2.push(1);
  }
  if (cell.isDim()) {
    args2.push(2);
  }
  if (cell.isItalic()) {
    args2.push(3);
  }
  if (cell.isUnderline()) {
    args2.push(4);
  }
  if (cell.isBlink()) {
    args2.push(5);
  }
  if (cell.isInverse()) {
    args2.push(7);
  }
  if (cell.isInvisible()) {
    args2.push(8);
  }
  if (cell.isFgRGB()) {
    args2.push(38, 2, cell.getFgColor() >>> 24, cell.getFgColor() >>> 16 & 255, cell.getFgColor() & 255);
  }
  if (cell.isFgPalette()) {
    args2.push(38, 5, cell.getFgColor());
  }
  if (cell.isFgDefault()) {
    args2.push(39);
  }
  if (cell.isBgRGB()) {
    args2.push(48, 2, cell.getBgColor() >>> 24, cell.getBgColor() >>> 16 & 255, cell.getBgColor() & 255);
  }
  if (cell.isBgPalette()) {
    args2.push(48, 5, cell.getBgColor());
  }
  if (cell.isBgDefault()) {
    args2.push(49);
  }
  return args2;
};
var attributesToSeq = (cell) => `${"\x1B["}${attributesToArgs(cell).join(";")}m`;
var arrayHasPrefixAt = (a, ai, b) => {
  if (a.length - ai > b.length) {
    return false;
  }
  for (let bi = 0; bi < b.length; bi++, ai++) {
    if (b[ai] !== a[ai]) {
      return false;
    }
  }
  return true;
};
var getColorWidth = (params, pos) => {
  const accu = [0, 0, -1, 0, 0, 0];
  let cSpace = 0;
  let advance = 0;
  do {
    const v = params[pos + advance];
    accu[advance + cSpace] = typeof v === "number" ? v : v[0];
    if (typeof v !== "number") {
      let i2 = 0;
      do {
        if (accu[1] === 5) {
          cSpace = 1;
        }
        accu[advance + i2 + 1 + cSpace] = v[i2];
      } while (++i2 < v.length && i2 + advance + 1 + cSpace < accu.length);
      break;
    }
    if (accu[1] === 5 && advance + cSpace >= 2 || accu[1] === 2 && advance + cSpace >= 5) {
      break;
    }
    if (accu[1]) {
      cSpace = 1;
    }
  } while (++advance + pos < params.length && advance + cSpace < accu.length);
  return advance;
};
var TypeAheadStyle = class _TypeAheadStyle {
  static d(args2) {
    return `${"\x1B["}${args2.join(";")}m`;
  }
  constructor(value, m) {
    this.m = m;
    this.f = 0;
    this.onUpdate(value);
  }
  /**
   * Signals that a style was written to the terminal and we should watch
   * for it coming in.
   */
  expectIncomingStyle(n = 1) {
    this.f += n * 2;
  }
  /**
   * Starts tracking for CSI changes in the terminal.
   */
  startTracking() {
    this.f = 0;
    this.q(attributesToArgs(core(this.m)._inputHandler._curAttrData));
    this.l = this.m.parser.registerCsiHandler({ final: "m" }, (args2) => {
      this.q(args2);
      return false;
    });
  }
  /**
   * Stops tracking terminal CSI changes.
   */
  debounceStopTracking() {
    this.o();
  }
  /**
   * @inheritdoc
   */
  dispose() {
    this.o();
  }
  o() {
    this.l?.dispose();
    this.l = void 0;
  }
  q(args2) {
    const originalUndo = this.k;
    for (let i2 = 0; i2 < args2.length; ) {
      const px = args2[i2];
      const p = typeof px === "number" ? px : px[0];
      if (this.f) {
        if (arrayHasPrefixAt(args2, i2, this.k)) {
          this.f--;
          i2 += this.k.length;
          continue;
        }
        if (arrayHasPrefixAt(args2, i2, this.h)) {
          this.f--;
          i2 += this.h.length;
          continue;
        }
      }
      const width2 = p === 38 || p === 48 || p === 58 ? getColorWidth(args2, i2) : 1;
      switch (this.h[0]) {
        case 1:
          if (p === 2) {
            this.k = [22, 2];
          } else if (p === 22 || p === 0) {
            this.k = [22];
          }
          break;
        case 2:
          if (p === 1) {
            this.k = [22, 1];
          } else if (p === 22 || p === 0) {
            this.k = [22];
          }
          break;
        case 38:
          if (p === 0 || p === 39 || p === 100) {
            this.k = [39];
          } else if (p >= 30 && p <= 38 || p >= 90 && p <= 97) {
            this.k = args2.slice(i2, i2 + width2);
          }
          break;
        default:
          if (p === this.h[0]) {
            this.k = this.h;
          } else if (p === 0) {
            this.k = this.j;
          }
      }
      i2 += width2;
    }
    if (originalUndo !== this.k) {
      this.undo = _TypeAheadStyle.d(this.k);
    }
  }
  /**
   * Updates the current typeahead style.
   */
  onUpdate(style) {
    const { applyArgs, undoArgs } = this.t(style);
    this.h = applyArgs;
    this.k = this.j = undoArgs;
    this.apply = _TypeAheadStyle.d(this.h);
    this.undo = _TypeAheadStyle.d(this.k);
  }
  t(style) {
    switch (style) {
      case "bold":
        return { applyArgs: [1], undoArgs: [22] };
      case "dim":
        return { applyArgs: [2], undoArgs: [22] };
      case "italic":
        return { applyArgs: [3], undoArgs: [23] };
      case "underlined":
        return { applyArgs: [4], undoArgs: [24] };
      case "inverted":
        return { applyArgs: [7], undoArgs: [27] };
      default: {
        let color2;
        try {
          color2 = $Vn.fromHex(style);
        } catch {
          color2 = new $Vn(new $Sn(255, 0, 0, 1));
        }
        const { r: r2, g, b } = color2.rgba;
        return { applyArgs: [38, 2, r2, g, b], undoArgs: [39] };
      }
    }
  }
};
__decorate([
  $$t(2e3)
], TypeAheadStyle.prototype, "debounceStopTracking", null);
var compileExcludeRegexp = (programs = $2X) => new RegExp(`\\b(${programs.map($Af).join("|")})\\b`, "i");
var CharPredictState;
(function(CharPredictState2) {
  CharPredictState2[CharPredictState2["Unknown"] = 0] = "Unknown";
  CharPredictState2[CharPredictState2["HasPendingChar"] = 1] = "HasPendingChar";
  CharPredictState2[CharPredictState2["Validated"] = 2] = "Validated";
})(CharPredictState || (CharPredictState = {}));
var $9gc = class $9gc2 extends $3c {
  constructor(C, D, F) {
    super();
    this.C = C;
    this.D = D;
    this.F = F;
    this.h = this.D.getValue($9X).localEchoLatencyThreshold;
    this.j = compileExcludeRegexp(this.D.getValue($9X).localEchoExcludePrograms);
    this.w = "";
    this.B($1c(() => this.z?.dispose()));
  }
  activate(terminal2) {
    const style = this.f = this.B(new TypeAheadStyle(this.D.getValue($9X).localEchoStyle, terminal2));
    const timeline = this.u = new $8gc(terminal2, this.f);
    const stats = this.stats = this.B(new $7gc(this.u));
    timeline.setShowPredictions(this.h === 0);
    this.B(terminal2.onData((e) => this.L(e)));
    this.B(terminal2.onTitleChange((title) => {
      this.w = title;
      this.H(stats, timeline);
    }));
    this.B(terminal2.onResize(() => {
      timeline.setShowPredictions(false);
      timeline.clearCursor();
      this.H(stats, timeline);
    }));
    this.B(this.D.onDidChangeConfiguration((e) => {
      if (e.affectsConfiguration($9X)) {
        style.onUpdate(this.D.getValue($9X).localEchoStyle);
        this.h = this.D.getValue($9X).localEchoLatencyThreshold;
        this.j = compileExcludeRegexp(this.D.getValue($9X).localEchoExcludePrograms);
        this.H(stats, timeline);
      }
    }));
    this.B(this.u.onPredictionSucceeded((p) => {
      if (this.m?.charState === 1 && isTenativeCharacterPrediction(p) && p.inner.appliedAt) {
        if (p.inner.appliedAt.pos.y + p.inner.appliedAt.pos.baseY === this.m.y) {
          this.m.charState = 2;
        }
      }
    }));
    this.B(this.C.onBeforeProcessData((e) => this.M(e)));
    let nextStatsSend;
    this.B(stats.onChange(() => {
      if (!nextStatsSend) {
        nextStatsSend = setTimeout(
          () => {
            this.J(stats);
            nextStatsSend = void 0;
          },
          3e5
          /* StatsConstants.StatsSendTelemetryEvery */
        );
      }
      if (timeline.length === 0) {
        style.debounceStopTracking();
      }
      this.H(stats, timeline);
    }));
  }
  reset() {
    this.m = void 0;
  }
  G() {
    if (!this.stats || !this.u) {
      return;
    }
    this.z?.dispose();
    if (this.u.length === 0 || this.u.peekStart()?.clearAfterTimeout === false) {
      this.z = void 0;
      return;
    }
    this.z = $Xh(() => {
      this.u?.undoAllPredictions();
      if (this.m?.charState === 1) {
        this.m.charState = 0;
      }
    }, Math.max(500, this.stats.maxLatency * 3 / 2), this.q);
  }
  /**
   * Note on debounce:
   *
   * We want to toggle the state only when the user has a pause in their
   * typing. Otherwise, we could turn this on when the PTY sent data but the
   * terminal cursor is not updated, causes issues.
   */
  H(stats, timeline) {
    this.I(stats, timeline);
  }
  I(stats, timeline) {
    if (this.j.test(this.w)) {
      timeline.setShowPredictions(false);
    } else if (this.h < 0) {
      timeline.setShowPredictions(false);
    } else if (this.h === 0) {
      timeline.setShowPredictions(true);
    } else if (stats.sampleSize > 5 && stats.accuracy > 0.3) {
      const latency = stats.latency.median;
      if (latency >= this.h) {
        timeline.setShowPredictions(true);
      } else if (latency < this.h / 0.5) {
        timeline.setShowPredictions(false);
      }
    }
  }
  J(stats) {
    this.F.publicLog("terminalLatencyStats", {
      ...stats.latency,
      predictionAccuracy: stats.accuracy
    });
  }
  L(data) {
    if (this.u?.terminal.buffer.active.type !== "normal") {
      return;
    }
    const terminal2 = this.u.terminal;
    const buffer = terminal2.buffer.active;
    if (buffer.cursorX === 1 && buffer.cursorY === terminal2.rows - 1) {
      if (buffer.getLine(buffer.cursorY + buffer.baseY)?.getCell(0)?.getChars() === ":") {
        return;
      }
    }
    const actualY = buffer.baseY + buffer.cursorY;
    if (actualY !== this.m?.y) {
      this.m = {
        y: actualY,
        startingX: buffer.cursorX,
        endingX: buffer.cursorX,
        charState: 0
        /* CharPredictState.Unknown */
      };
    } else {
      this.m.startingX = Math.min(this.m.startingX, buffer.cursorX);
      this.m.endingX = Math.max(this.m.endingX, this.u.physicalCursor(buffer).x);
    }
    const addLeftNavigating = (p) => this.u.tentativeCursor(buffer).x <= this.m.startingX ? this.u.addBoundary(buffer, p) : this.u.addPrediction(buffer, p);
    const addRightNavigating = (p) => this.u.tentativeCursor(buffer).x >= this.m.endingX - 1 ? this.u.addBoundary(buffer, p) : this.u.addPrediction(buffer, p);
    const reader = new StringReader(data);
    while (reader.remaining > 0) {
      if (reader.eatCharCode(127)) {
        const previous = this.u.peekEnd();
        if (previous && previous instanceof CharacterPrediction) {
          this.u.addBoundary();
        }
        if (this.u.isShowingPredictions) {
          flushOutput(this.u.terminal);
        }
        if (this.u.tentativeCursor(buffer).x <= this.m.startingX) {
          this.u.addBoundary(buffer, new BackspacePrediction(this.u.terminal));
        } else {
          this.m.endingX--;
          this.u.addPrediction(buffer, new BackspacePrediction(this.u.terminal));
        }
        continue;
      }
      if (reader.eatCharCode(32, 126)) {
        const char = data[reader.index - 1];
        const prediction = new CharacterPrediction(this.f, char);
        if (this.m.charState === 0) {
          this.u.addBoundary(buffer, prediction);
          this.m.charState = 1;
        } else {
          this.u.addPrediction(buffer, prediction);
        }
        if (this.u.tentativeCursor(buffer).x >= terminal2.cols) {
          this.u.addBoundary(buffer, new LinewrapPrediction());
        }
        continue;
      }
      const cursorMv = reader.eatRe(CSI_MOVE_RE);
      if (cursorMv) {
        const direction = cursorMv[3];
        const p = new CursorMovePrediction(direction, !!cursorMv[2], Number(cursorMv[1]) || 1);
        if (direction === "D") {
          addLeftNavigating(p);
        } else {
          addRightNavigating(p);
        }
        continue;
      }
      if (reader.eatStr(`${"\x1B"}f`)) {
        addRightNavigating(new CursorMovePrediction("C", true, 1));
        continue;
      }
      if (reader.eatStr(`${"\x1B"}b`)) {
        addLeftNavigating(new CursorMovePrediction("D", true, 1));
        continue;
      }
      if (reader.eatChar("\r") && buffer.cursorY < terminal2.rows - 1) {
        this.u.addPrediction(buffer, new NewlinePrediction());
        continue;
      }
      this.u.addBoundary(buffer, new HardBoundary());
      break;
    }
    if (this.u.length === 1) {
      this.G();
      this.f.startTracking();
    }
  }
  M(event) {
    if (!this.u) {
      return;
    }
    event.data = this.u.beforeServerInput(event.data);
    this.G();
  }
};
__decorate([
  $$t(100)
], $9gc.prototype, "H", null);
$9gc = __decorate([
  __param(1, $kl),
  __param(2, $zv)
], $9gc);

// out-build/vs/workbench/contrib/terminalContrib/typeAhead/browser/terminal.typeAhead.contribution.js
var TerminalTypeAheadContribution_1;
var TerminalTypeAheadContribution = class TerminalTypeAheadContribution2 extends $2c {
  static {
    TerminalTypeAheadContribution_1 = this;
  }
  static {
    this.ID = "terminal.typeAhead";
  }
  static get(instance2) {
    return instance2.getContribution(TerminalTypeAheadContribution_1.ID);
  }
  constructor(b, c, h3) {
    super();
    this.b = b;
    this.c = c;
    this.h = h3;
    this.add($1c(() => this.a?.dispose()));
  }
  xtermReady(xterm) {
    this.j(xterm.raw);
    this.add(this.c.onDidChangeConfiguration((e) => {
      if (e.affectsConfiguration(
        "terminal.integrated.localEchoEnabled"
        /* TerminalTypeAheadSettingId.LocalEchoEnabled */
      )) {
        this.j(xterm.raw);
      }
    }));
    this.add(this.b.processManager.onProcessReady(() => {
      this.a?.reset();
    }));
  }
  j(xterm) {
    const enabled = this.c.getValue($9X).localEchoEnabled;
    const isRemote = !!this.b.processManager.remoteAuthority;
    if (enabled === "off" || enabled === "auto" && !isRemote) {
      this.a?.dispose();
      this.a = void 0;
      return;
    }
    if (this.a) {
      return;
    }
    if (enabled === "on" || enabled === "auto" && isRemote) {
      this.a = this.h.createInstance($9gc, this.b.processManager);
      xterm.loadAddon(this.a);
    }
  }
};
TerminalTypeAheadContribution = TerminalTypeAheadContribution_1 = __decorate([
  __param(1, $kl),
  __param(2, $Pk)
], TerminalTypeAheadContribution);
$Y0b(TerminalTypeAheadContribution.ID, TerminalTypeAheadContribution);

// out-build/vs/workbench/services/suggest/browser/simpleCompletionItem.js
var $vRb = class {
  constructor(completion) {
    this.completion = completion;
    this.fileExtLow = "";
    this.score = FuzzyScore.Default;
    this.labelLow = this.completion.label.toLowerCase();
    this.labelLowExcludeFileExt = this.labelLow;
    if (completion.isFile) {
      if ($l) {
        this.labelLow = this.labelLow.replaceAll("/", "\\");
      }
      const extIndex = this.labelLow.lastIndexOf(".");
      if (extIndex !== -1) {
        this.labelLowExcludeFileExt = this.labelLow.substring(0, extIndex);
        this.fileExtLow = this.labelLow.substring(extIndex + 1);
      }
    }
  }
};

// out-build/vs/workbench/services/suggest/browser/simpleCompletionModel.js
var $0gc = class {
  constructor(leadingLineContent, characterCountDelta) {
    this.leadingLineContent = leadingLineContent;
    this.characterCountDelta = characterCountDelta;
  }
};
var Refilter2;
(function(Refilter3) {
  Refilter3[Refilter3["Nothing"] = 0] = "Nothing";
  Refilter3[Refilter3["All"] = 1] = "All";
  Refilter3[Refilter3["Incr"] = 2] = "Incr";
})(Refilter2 || (Refilter2 = {}));
var $$gc = class {
  constructor(h3, j) {
    this.h = h3;
    this.j = j;
    this.e = 1;
    this.f = $Wl.default;
    this.g = {};
  }
  get items() {
    this.k();
    return this.d;
  }
  get stats() {
    this.k();
    return this.c;
  }
  get lineContext() {
    return this.j;
  }
  set lineContext(value) {
    if (this.j.leadingLineContent !== value.leadingLineContent || this.j.characterCountDelta !== value.characterCountDelta) {
      this.e = this.j.characterCountDelta < value.characterCountDelta && this.d ? 2 : 1;
      this.j = value;
    }
  }
  k() {
    if (this.e !== 0) {
      this.l();
    }
  }
  l() {
    const labelLengths = [];
    const { leadingLineContent, characterCountDelta } = this.j;
    let word = "";
    let wordLow = "";
    const source = this.e === 1 ? this.h : this.d;
    const target = [];
    const scoreFn = !this.g.filterGraceful || source.length > 2e3 ? $Xl : $Yl;
    for (let i2 = 0; i2 < source.length; i2++) {
      const item = source[i2];
      const overwriteBefore = item.completion.replacementLength;
      const wordLen = overwriteBefore + characterCountDelta;
      if (word.length !== wordLen) {
        word = wordLen === 0 ? "" : leadingLineContent.slice(-wordLen);
        wordLow = word.toLowerCase();
      }
      item.word = word;
      if (wordLen === 0) {
        item.score = FuzzyScore.Default;
      } else {
        let wordPos = 0;
        while (wordPos < overwriteBefore) {
          const ch = word.charCodeAt(wordPos);
          if (ch === 32 || ch === 9) {
            wordPos += 1;
          } else {
            break;
          }
        }
        if (wordPos >= wordLen) {
          item.score = FuzzyScore.Default;
        } else {
          const match = scoreFn(word, wordLow, wordPos, item.completion.label, item.labelLow, 0, this.f);
          if (!match && word !== "") {
            continue;
          }
          item.score = match || FuzzyScore.Default;
        }
      }
      item.idx = i2;
      target.push(item);
      labelLengths.push(item.completion.label.length);
    }
    this.d = target.sort((a, b) => {
      let score2 = 0;
      if (a.completion.isKeyword && a.labelLow !== wordLow || b.completion.isKeyword && b.labelLow !== wordLow) {
        score2 = (a.completion.isKeyword ? 1 : 0) - (b.completion.isKeyword ? 1 : 0);
        if (score2 !== 0) {
          return score2;
        }
      }
      score2 = b.score[0] - a.score[0];
      if (score2 !== 0) {
        return score2;
      }
      const isArg = leadingLineContent.includes(" ");
      if (!isArg && a.fileExtLow.length > 0 && b.fileExtLow.length > 0) {
        score2 = a.labelLowExcludeFileExt.length - b.labelLowExcludeFileExt.length;
        if (score2 !== 0) {
          return score2;
        }
        score2 = fileExtScore(b.fileExtLow) - fileExtScore(a.fileExtLow);
        if (score2 !== 0) {
          return score2;
        }
        score2 = a.fileExtLow.length - b.fileExtLow.length;
      }
      return score2;
    });
    this.e = 0;
    this.c = {
      pLabelLen: labelLengths.length ? $Db(labelLengths.length - 0.85, labelLengths, (a, b) => a - b) : 0
    };
  }
};
var fileExtScores = new Map($l ? [
  // Windows - .ps1 > .exe > .bat > .cmd. This is the command precedence when running the files
  //           without an extension, tested manually in pwsh v7.4.4
  ["ps1", 0.09],
  ["exe", 0.08],
  ["bat", 0.07],
  ["cmd", 0.07],
  // Non-Windows
  ["sh", -0.05],
  ["bash", -0.05],
  ["zsh", -0.05],
  ["fish", -0.05],
  ["csh", -0.06],
  // C shell
  ["ksh", -0.06]
  // Korn shell
  // Scripting language files are excluded here as the standard behavior on Windows will just open
  // the file in a text editor, not run the file
] : [
  // Pwsh
  ["ps1", 0.05],
  // Windows
  ["bat", -0.05],
  ["cmd", -0.05],
  ["exe", -0.05],
  // Non-Windows
  ["sh", 0.05],
  ["bash", 0.05],
  ["zsh", 0.05],
  ["fish", 0.05],
  ["csh", 0.04],
  // C shell
  ["ksh", 0.04],
  // Korn shell
  // Scripting languages
  ["py", 0.05],
  // Python
  ["pl", 0.05]
  // Perl
]);
function fileExtScore(ext) {
  return fileExtScores.get(ext) || 0;
}

// out-build/vs/workbench/services/suggest/browser/simpleSuggestWidgetRenderer.js
function $_gc(index) {
  return `simple-suggest-aria-id:${index}`;
}
var $ahc = class {
  constructor(b) {
    this.b = b;
    this.a = new $ze();
    this.onDidToggleDetails = this.a.event;
    this.templateId = "suggestion";
  }
  dispose() {
    this.a.dispose();
  }
  renderTemplate(container2) {
    const disposables = new $2c();
    const root = container2;
    root.classList.add("show-file-icons");
    const icon2 = $bk(container2, $(".icon"));
    const colorspan = $bk(icon2, $("span.colorspan"));
    const text2 = $bk(container2, $(".contents"));
    const main = $bk(text2, $(".main"));
    const iconContainer = $bk(main, $(".icon-label.codicon"));
    const left = $bk(main, $("span.left"));
    const right = $bk(main, $("span.right"));
    const iconLabel = new $T2(left, { supportHighlights: true, supportIcons: true });
    disposables.add(iconLabel);
    const parametersLabel = $bk(left, $("span.signature-label"));
    const qualifierLabel = $bk(left, $("span.qualifier-label"));
    const detailsLabel = $bk(right, $("span.details-label"));
    const configureFont = () => {
      const fontFeatureSettings = "";
      const { fontFamily, fontSize, lineHeight, fontWeight, letterSpacing } = this.b();
      const fontSizePx = `${fontSize}px`;
      const lineHeightPx = `${lineHeight}px`;
      const letterSpacingPx = `${letterSpacing}px`;
      root.style.fontSize = fontSizePx;
      root.style.fontWeight = fontWeight;
      root.style.letterSpacing = letterSpacingPx;
      main.style.fontFamily = fontFamily;
      main.style.fontFeatureSettings = fontFeatureSettings;
      main.style.lineHeight = lineHeightPx;
      icon2.style.height = lineHeightPx;
      icon2.style.width = lineHeightPx;
    };
    configureFont();
    return { root, left, right, icon: icon2, colorspan, iconLabel, iconContainer, parametersLabel, qualifierLabel, detailsLabel, disposables };
  }
  renderElement(element, index, data) {
    const { completion } = element;
    data.root.id = $_gc(index);
    data.colorspan.style.backgroundColor = "";
    const labelOptions = {
      labelEscapeNewLines: true,
      matches: $Ul(element.score)
    };
    data.icon.className = "icon hide";
    data.iconContainer.className = "";
    data.iconContainer.classList.add("suggest-icon", ...ThemeIcon.asClassNameArray(completion.icon || $6l.symbolText));
    data.iconLabel.setLabel(completion.label, void 0, labelOptions);
    data.parametersLabel.textContent = "";
    data.detailsLabel.textContent = stripNewLines2(completion.detail || "");
    data.root.classList.add("string-label");
    $hk(data.detailsLabel);
    data.right.classList.remove("can-expand-details");
  }
  disposeTemplate(templateData) {
    templateData.disposables.dispose();
  }
};
function stripNewLines2(str) {
  return str.replace(/\r\n|\r|\n/g, "");
}

// out-build/vs/workbench/services/suggest/browser/simpleSuggestWidget.js
var $147 = $;
var State11;
(function(State14) {
  State14[State14["Hidden"] = 0] = "Hidden";
  State14[State14["Loading"] = 1] = "Loading";
  State14[State14["Empty"] = 2] = "Empty";
  State14[State14["Open"] = 3] = "Open";
  State14[State14["Frozen"] = 4] = "Frozen";
  State14[State14["Details"] = 5] = "Details";
})(State11 || (State11 = {}));
var WidgetPositionPreference;
(function(WidgetPositionPreference2) {
  WidgetPositionPreference2[WidgetPositionPreference2["Above"] = 0] = "Above";
  WidgetPositionPreference2[WidgetPositionPreference2["Below"] = 1] = "Below";
})(WidgetPositionPreference || (WidgetPositionPreference = {}));
var $bhc = class $bhc2 extends $3c {
  get list() {
    return this.m;
  }
  constructor(w, y, z, options3, instantiationService) {
    super();
    this.w = w;
    this.y = y;
    this.z = z;
    this.a = 0;
    this.f = false;
    this.h = this.B(new $4c());
    this.r = this.B(new $6h());
    this.s = this.B(new $ze());
    this.onDidSelect = this.s.event;
    this.t = this.B(new $ze());
    this.onDidHide = this.t.event;
    this.u = this.B(new $ze());
    this.onDidShow = this.u.event;
    this.element = this.B(new $_2());
    this.element.domNode.classList.add("workbench-suggest-widget");
    this.w.appendChild(this.element.domNode);
    class ResizeState {
      constructor(persistedSize, currentSize, persistHeight = false, persistWidth = false) {
        this.persistedSize = persistedSize;
        this.currentSize = currentSize;
        this.persistHeight = persistHeight;
        this.persistWidth = persistWidth;
      }
    }
    let state;
    this.B(this.element.onDidWillResize(() => {
      state = new ResizeState(this.y.restore(), this.element.size);
    }));
    this.B(this.element.onDidResize((e) => {
      this.H(e.dimension.width, e.dimension.height);
      if (state) {
        state.persistHeight = state.persistHeight || !!e.north || !!e.south;
        state.persistWidth = state.persistWidth || !!e.east || !!e.west;
      }
      if (!e.done) {
        return;
      }
      if (state) {
        const { itemHeight, defaultSize } = this.I();
        const threshold = Math.round(itemHeight / 2);
        let { width: width2, height } = this.element.size;
        if (!state.persistHeight || Math.abs(state.currentSize.height - height) <= threshold) {
          height = state.persistedSize?.height ?? defaultSize.height;
        }
        if (!state.persistWidth || Math.abs(state.currentSize.width - width2) <= threshold) {
          width2 = state.persistedSize?.width ?? defaultSize.width;
        }
        this.y.store(new $rj(width2, height));
      }
      state = void 0;
    }));
    const renderer = new $ahc(z);
    this.B(renderer);
    this.j = $bk(this.element.domNode, $147(".tree"));
    this.m = this.B(new $A1("SuggestWidget", this.j, {
      getHeight: (_element) => this.I().itemHeight,
      getTemplateId: (_element) => "suggestion"
    }, [renderer], {
      alwaysConsumeMouseWheel: true,
      useShadows: false,
      mouseSupport: false,
      multipleSelectionSupport: false,
      accessibilityProvider: {
        getRole: () => "option",
        getWidgetAriaLabel: () => localize(13111, null),
        getWidgetRole: () => "listbox",
        getAriaLabel: (item) => {
          let label3 = item.completion.label;
          if (typeof item.completion.label !== "string") {
            const { detail: detail3, description } = item.completion.label;
            if (detail3 && description) {
              label3 = localize(13112, null, label3, detail3, description);
            } else if (detail3) {
              label3 = localize(13113, null, label3, detail3);
            } else if (description) {
              label3 = localize(13114, null, label3, description);
            }
          }
          const { detail: detail2 } = item.completion;
          return localize(13115, null, label3, detail2);
        }
      }
    }));
    if (options3.statusBarMenuId) {
      this.n = this.B(instantiationService.createInstance($cdb, this.element.domNode, options3.statusBarMenuId));
      this.element.domNode.classList.toggle("with-status-bar", true);
    }
    this.B(this.m.onMouseDown((e) => this.J(e)));
    this.B(this.m.onTap((e) => this.J(e)));
    this.B(this.m.onDidChangeSelection((e) => this.L(e)));
  }
  setCompletionModel(completionModel) {
    this.b = completionModel;
  }
  hasCompletions() {
    return this.b?.items.length !== 0;
  }
  showSuggestions(selectionIndex, isFrozen2, isAuto, cursorPosition) {
    this.C = cursorPosition;
    if (isFrozen2 && this.a !== 2 && this.a !== 0) {
      this.D(
        4
        /* State.Frozen */
      );
      return;
    }
    const visibleCount = this.b?.items.length ?? 0;
    const isEmpty = visibleCount === 0;
    if (isEmpty) {
      this.D(
        isAuto ? 0 : 2
        /* State.Empty */
      );
      this.b = void 0;
      return;
    }
    try {
      this.m.splice(0, this.m.length, this.b?.items ?? []);
      this.D(
        isFrozen2 ? 4 : 3
        /* State.Open */
      );
      this.m.reveal(selectionIndex, 0);
      this.m.setFocus([selectionIndex]);
    } finally {
    }
    this.h.value = $ij(getWindow(this.element.domNode), () => {
      this.h.clear();
      this.G(this.element.size);
    });
  }
  setLineContext(lineContext) {
    if (this.b) {
      this.b.lineContext = lineContext;
    }
  }
  D(state) {
    if (this.a === state) {
      return;
    }
    this.a = state;
    this.element.domNode.classList.toggle(
      "frozen",
      state === 4
      /* State.Frozen */
    );
    this.element.domNode.classList.remove("message");
    switch (state) {
      case 0:
        $ik(this.j);
        if (this.n) {
          $ik(this.n?.element);
        }
        this.n?.hide();
        this.r.cancel();
        this.element.domNode.classList.remove("visible");
        this.m.splice(0, this.m.length);
        this.c = void 0;
        break;
      case 1:
        this.element.domNode.classList.add("message");
        $ik(this.j);
        if (this.n) {
          $ik(this.n?.element);
        }
        this.F();
        break;
      case 2:
        this.element.domNode.classList.add("message");
        $ik(this.j);
        if (this.n) {
          $ik(this.n?.element);
        }
        this.F();
        break;
      case 3:
        $hk(this.j);
        if (this.n) {
          $hk(this.n?.element);
        }
        this.F();
        break;
      case 4:
        $hk(this.j);
        if (this.n) {
          $hk(this.n?.element);
        }
        this.F();
        break;
      case 5:
        $hk(this.j);
        if (this.n) {
          $hk(this.n?.element);
        }
        this.F();
        break;
    }
  }
  F() {
    this.n?.show();
    $hk(this.element.domNode);
    this.G(this.y.restore());
    this.u.fire(this);
    this.r.cancelAndSet(() => {
      this.element.domNode.classList.add("visible");
    }, 100);
  }
  hide() {
    this.h.clear();
    this.D(
      0
      /* State.Hidden */
    );
    this.t.fire(this);
    $ik(this.element.domNode);
    this.element.clearSashHoverState();
    const dim = this.y.restore();
    const minPersistedHeight = Math.ceil(this.I().itemHeight * 4.3);
    if (dim && dim.height < minPersistedHeight) {
      this.y.store(dim.with(void 0, minPersistedHeight));
    }
  }
  G(size) {
    if (!this.C) {
      return;
    }
    const bodyBox = $qj(this.w.ownerDocument.body);
    const info = this.I();
    if (!size) {
      size = info.defaultSize;
    }
    let height = size.height;
    let width2 = size.width;
    if (this.n) {
      this.n.element.style.lineHeight = `${info.itemHeight}px`;
    }
    const maxWidth = bodyBox.width - info.borderHeight - 2 * info.horizontalPadding;
    if (width2 > maxWidth) {
      width2 = maxWidth;
    }
    const preferredWidth = this.b ? this.b.stats.pLabelLen * info.typicalHalfwidthCharacterWidth : width2;
    const fullHeight = info.statusBarHeight + this.m.contentHeight + info.borderHeight;
    const minHeight = info.itemHeight + info.statusBarHeight;
    const editorBox = $vj(this.w);
    const cursorBox = this.C;
    const cursorBottom = editorBox.top + cursorBox.top + cursorBox.height;
    const maxHeightBelow = Math.min(bodyBox.height - cursorBottom - info.verticalPadding, fullHeight);
    const availableSpaceAbove = editorBox.top + cursorBox.top - info.verticalPadding;
    const maxHeightAbove = Math.min(availableSpaceAbove, fullHeight);
    let maxHeight = Math.min(Math.max(maxHeightAbove, maxHeightBelow) + info.borderHeight, fullHeight);
    if (height === this.c?.capped) {
      height = this.c.wanted;
    }
    if (height < minHeight) {
      height = minHeight;
    }
    if (height > maxHeight) {
      height = maxHeight;
    }
    const forceRenderingAboveRequiredSpace = 150;
    if (height > maxHeightBelow || this.f && availableSpaceAbove > forceRenderingAboveRequiredSpace) {
      this.g = 0;
      this.element.enableSashes(true, true, false, false);
      maxHeight = maxHeightAbove;
    } else {
      this.g = 1;
      this.element.enableSashes(false, true, true, false);
      maxHeight = maxHeightBelow;
    }
    this.element.preferredSize = new $rj(preferredWidth, info.defaultSize.height);
    this.element.maxSize = new $rj(maxWidth, maxHeight);
    this.element.minSize = new $rj(220, minHeight);
    this.c = height === fullHeight ? { wanted: this.c?.wanted ?? size.height, capped: height } : void 0;
    this.element.domNode.style.left = `${this.C.left}px`;
    if (this.g === 0) {
      this.element.domNode.style.top = `${this.C.top - height - info.borderHeight}px`;
    } else {
      this.element.domNode.style.top = `${this.C.top + this.C.height}px`;
    }
    this.H(width2, height);
  }
  H(width2, height) {
    const { width: maxWidth, height: maxHeight } = this.element.maxSize;
    width2 = Math.min(maxWidth, width2);
    if (maxHeight) {
      height = Math.min(maxHeight, height);
    }
    const { statusBarHeight } = this.I();
    this.m.layout(height - statusBarHeight, width2);
    this.j.style.height = `${height - statusBarHeight}px`;
    this.j.style.width = `${width2}px`;
    this.j.style.height = `${height}px`;
    this.element.layout(height, width2);
  }
  I() {
    const fontInfo = this.z();
    const itemHeight = $4i(Math.ceil(fontInfo.lineHeight), 8, 1e3);
    const statusBarHeight = 0;
    const borderWidth = 1;
    const borderHeight = 2 * borderWidth;
    return {
      itemHeight,
      statusBarHeight,
      borderWidth,
      borderHeight,
      typicalHalfwidthCharacterWidth: 10,
      verticalPadding: 22,
      horizontalPadding: 14,
      defaultSize: new $rj(430, statusBarHeight + 12 * itemHeight + borderHeight)
    };
  }
  J(e) {
    if (typeof e.element === "undefined" || typeof e.index === "undefined") {
      return;
    }
    e.browserEvent.preventDefault();
    e.browserEvent.stopPropagation();
    this.M(e.element, e.index);
  }
  L(e) {
    if (e.elements.length) {
      this.M(e.elements[0], e.indexes[0]);
    }
  }
  M(item, index) {
    const completionModel = this.b;
    if (completionModel) {
      this.s.fire({ item, index, model: completionModel });
    }
  }
  selectNext() {
    this.m.focusNext(1, true);
    const focus = this.m.getFocus();
    if (focus.length > 0) {
      this.m.reveal(focus[0]);
    }
    return true;
  }
  selectNextPage() {
    this.m.focusNextPage();
    const focus = this.m.getFocus();
    if (focus.length > 0) {
      this.m.reveal(focus[0]);
    }
    return true;
  }
  selectPrevious() {
    this.m.focusPrevious(1, true);
    const focus = this.m.getFocus();
    if (focus.length > 0) {
      this.m.reveal(focus[0]);
    }
    return true;
  }
  selectPreviousPage() {
    this.m.focusPreviousPage();
    const focus = this.m.getFocus();
    if (focus.length > 0) {
      this.m.reveal(focus[0]);
    }
    return true;
  }
  getFocusedItem() {
    if (this.b) {
      return {
        item: this.m.getFocusedElements()[0],
        index: this.m.getFocus()[0],
        model: this.b
      };
    }
    return void 0;
  }
  forceRenderingAbove() {
    if (!this.f) {
      this.f = true;
      this.G(this.y.restore());
    }
  }
  stopForceRenderingAbove() {
    this.f = false;
  }
};
$bhc = __decorate([
  __param(4, $Pk)
], $bhc);

// out-build/vs/workbench/contrib/terminalContrib/suggest/browser/terminalSuggestAddon.js
var $chc_1;
var $chc = class $chc2 extends $3c {
  static {
    $chc_1 = this;
  }
  static {
    this.lastAcceptedCompletionTimestamp = 0;
  }
  constructor(N, O, P, Q, R, S, U, W) {
    super();
    this.N = N;
    this.O = O;
    this.P = P;
    this.Q = Q;
    this.R = R;
    this.S = S;
    this.U = U;
    this.W = W;
    this.f = this.B(new $4c());
    this.s = true;
    this.t = sep;
    this.u = false;
    this.z = 0;
    this.C = 0;
    this.D = 0;
    this.G = 0;
    this.isPasting = false;
    this.I = this.B(new $ze());
    this.onBell = this.I.event;
    this.J = this.B(new $ze());
    this.onAcceptedCompletion = this.J.event;
    this.L = this.B(new $ze());
    this.onDidReceiveCompletions = this.L.event;
    this.M = /* @__PURE__ */ new Map([
      [TerminalCompletionItemKind2.File, $6l.file],
      [TerminalCompletionItemKind2.Folder, $6l.folder],
      [TerminalCompletionItemKind2.Flag, $6l.symbolProperty],
      [TerminalCompletionItemKind2.Method, $6l.symbolMethod],
      [TerminalCompletionItemKind2.Argument, $6l.symbolVariable]
    ]);
    this.B(Event2.runAndSubscribe(Event2.any(this.O.onDidAddCapabilityType, this.O.onDidRemoveCapabilityType), () => {
      const commandDetection = this.O.get(
        2
        /* TerminalCapability.CommandDetection */
      );
      if (commandDetection) {
        if (this.b !== commandDetection.promptInputModel) {
          this.b = commandDetection.promptInputModel;
          this.f.value = $Zc(this.b.onDidChangeInput((e) => this.Y(e)), this.b.onDidFinishInput(() => this.hideSuggestWidget()));
        }
      } else {
        this.b = void 0;
      }
    }));
  }
  activate(xterm) {
    this.a = xterm;
    this.B(xterm.onData(async (e) => {
      this.F = e;
      this.G = Date.now();
    }));
  }
  async X(terminal2, token, triggerCharacter) {
    if (!terminal2?.element || !this.s || !this.b) {
      return;
    }
    if (!$Nj(terminal2.element)) {
      return;
    }
    if (!this.N) {
      return;
    }
    let doNotRequestExtensionCompletions = false;
    if (this.G < $chc_1.lastAcceptedCompletionTimestamp) {
      doNotRequestExtensionCompletions = true;
    }
    const enableExtensionCompletions = this.R.getValue($ZX).enableExtensionCompletions;
    if (enableExtensionCompletions && !doNotRequestExtensionCompletions) {
      await this.W.activateByEvent("onTerminalCompletionsRequested");
    }
    const providedCompletions = await this.Q.provideCompletions(this.b.value, this.b.cursorIndex, this.N, token, triggerCharacter, doNotRequestExtensionCompletions);
    if (!providedCompletions?.length || token.isCancellationRequested) {
      return;
    }
    this.L.fire();
    const replacementIndices = [...new Set(providedCompletions.map((c) => c.replacementIndex))];
    const replacementIndex = replacementIndices.length === 1 ? replacementIndices[0] : 0;
    this.D = replacementIndex;
    this.C = this.b.cursorIndex;
    this.h = {
      value: this.b.value,
      prefix: this.b.prefix,
      suffix: this.b.suffix,
      cursorIndex: this.b.cursorIndex,
      ghostTextIndex: this.b.ghostTextIndex
    };
    this.y = this.h.prefix.substring(replacementIndex, replacementIndex + this.b.cursorIndex + this.z);
    const completions = providedCompletions.flat();
    if (!completions?.length) {
      return;
    }
    const firstChar = this.y.length === 0 ? "" : this.y[0];
    if (this.y.includes(" ") || firstChar === "[") {
      this.y = this.b.prefix;
    }
    if (this.w?.isDirectory && completions.every((e) => e.isDirectory)) {
      completions.push(this.w);
    }
    this.w = void 0;
    this.z = this.h.cursorIndex - this.C;
    let normalizedLeadingLineContent = this.y;
    this.u = completions.some((e) => e.isDirectory);
    if (this.u) {
      const firstDir = completions.find((e) => e.isDirectory);
      this.t = firstDir?.label.match(/(?<sep>[\\\/])/)?.groups?.sep ?? sep;
      normalizedLeadingLineContent = $dhc(normalizedLeadingLineContent, this.t);
    }
    for (const completion of completions) {
      if (!completion.icon && completion.kind !== void 0) {
        completion.icon = this.M.get(completion.kind);
      }
    }
    const lineContext = new $0gc(normalizedLeadingLineContent, this.z);
    const model = new $$gc(completions.filter((c) => !!c.label).map((c) => new $vRb(c)), lineContext);
    if (token.isCancellationRequested) {
      return;
    }
    this.$(model);
  }
  setContainerWithOverflow(container2) {
    this.m = container2;
  }
  setScreen(screen) {
    this.n = screen;
  }
  async requestCompletions(triggerCharacter) {
    if (!this.b) {
      return;
    }
    if (this.isPasting) {
      return;
    }
    if (this.H) {
      this.H.cancel();
      this.H.dispose();
    }
    this.H = new $ad();
    const token = this.H.token;
    await this.X(this.a, token, triggerCharacter);
  }
  Y(promptInputState) {
    const config = this.R.getValue($ZX);
    if (!this.g || promptInputState.cursorIndex > this.g.cursorIndex) {
      let sent = false;
      if (!this.P.get()) {
        if (config.quickSuggestions) {
          if (promptInputState.cursorIndex === 1 || promptInputState.prefix.match(/([\s\[])[^\s]$/)) {
            if (!this.F?.match(/^\x1b[\[O]?[A-D]$/)) {
              this.requestCompletions();
              sent = true;
            }
          }
        }
      }
      if (config.suggestOnTriggerCharacters && !sent) {
        const prefix = promptInputState.prefix;
        if (
          // Only trigger on `-` if it's after a space. This is required to not clear
          // completions when typing the `-` in `git cherry-pick`
          prefix?.match(/\s[\-]$/) || // Only trigger on `\` and `/` if it's a directory. Not doing so causes problems
          // with git branches in particular
          this.u && prefix?.match(/[\\\/]$/)
        ) {
          this.requestCompletions();
          sent = true;
        }
        if (!sent) {
          for (const provider of this.Q.providers) {
            if (!provider.triggerCharacters) {
              continue;
            }
            for (const char of provider.triggerCharacters) {
              if (prefix?.endsWith(char)) {
                this.requestCompletions(true);
                sent = true;
                break;
              }
            }
          }
        }
      }
    }
    this.g = promptInputState;
    if (!this.b || !this.a || !this.r || this.y === void 0) {
      return;
    }
    this.h = promptInputState;
    if (this.h.cursorIndex > 1 && this.h.value.at(this.h.cursorIndex - 1) === " ") {
      this.hideSuggestWidget();
      return;
    }
    if (this.h && this.h.cursorIndex <= this.y.length) {
      this.hideSuggestWidget();
      return;
    }
    if (this.P.get()) {
      this.z = this.h.cursorIndex - this.C;
      let normalizedLeadingLineContent = this.h.value.substring(this.D, this.C + this.z);
      if (this.u) {
        normalizedLeadingLineContent = $dhc(normalizedLeadingLineContent, this.t);
      }
      const lineContext = new $0gc(normalizedLeadingLineContent, this.z);
      this.r.setLineContext(lineContext);
    }
    if (!this.r.hasCompletions()) {
      this.hideSuggestWidget();
      return;
    }
    const dimensions = this.Z();
    if (!dimensions.width || !dimensions.height) {
      return;
    }
    const xtermBox = this.n.getBoundingClientRect();
    this.r.showSuggestions(0, false, false, {
      left: xtermBox.left + this.a.buffer.active.cursorX * dimensions.width,
      top: xtermBox.top + this.a.buffer.active.cursorY * dimensions.height,
      height: dimensions.height
    });
  }
  Z() {
    const cssCellDims = this.a._core._renderService.dimensions.css.cell;
    return {
      width: cssCellDims.width,
      height: cssCellDims.height
    };
  }
  $(model) {
    if (!this.a?.element) {
      return;
    }
    const suggestWidget = this.ab(this.a);
    suggestWidget.setCompletionModel(model);
    if (model.items.length === 0 || !this.b) {
      return;
    }
    this.j = model;
    const dimensions = this.Z();
    if (!dimensions.width || !dimensions.height) {
      return;
    }
    const xtermBox = this.n.getBoundingClientRect();
    suggestWidget.showSuggestions(0, false, false, {
      left: xtermBox.left + this.a.buffer.active.cursorX * dimensions.width,
      top: xtermBox.top + this.a.buffer.active.cursorY * dimensions.height,
      height: dimensions.height
    });
  }
  ab(terminal2) {
    if (!this.r) {
      const c = this.U.config;
      const font = this.U.getFont($Qj());
      const fontInfo = {
        fontFamily: font.fontFamily,
        fontSize: font.fontSize,
        lineHeight: Math.ceil(1.5 * font.fontSize),
        fontWeight: c.fontWeight.toString(),
        letterSpacing: font.letterSpacing
      };
      this.r = this.B(this.S.createInstance($bhc, this.m, this.S.createInstance(PersistedWidgetSize2), () => fontInfo, {}));
      this.r.list.style($J$({
        listInactiveFocusBackground: $ldb,
        listInactiveFocusOutline: $lo
      }));
      this.B(this.r.onDidSelect(async (e) => this.acceptSelectedSuggestion(e)));
      this.B(this.r.onDidHide(() => this.P.set(false)));
      this.B(this.r.onDidShow(() => this.P.set(true)));
      this.P.set(false);
    }
    return this.r;
  }
  selectPreviousSuggestion() {
    this.r?.selectPrevious();
  }
  selectPreviousPageSuggestion() {
    this.r?.selectPreviousPage();
  }
  selectNextSuggestion() {
    this.r?.selectNext();
  }
  selectNextPageSuggestion() {
    this.r?.selectNextPage();
  }
  acceptSelectedSuggestion(suggestion, respectRunOnEnter) {
    if (!suggestion) {
      suggestion = this.r?.getFocusedItem();
    }
    const initialPromptInputState = this.g;
    if (!suggestion || !initialPromptInputState || this.y === void 0 || !this.j) {
      return;
    }
    $chc_1.lastAcceptedCompletionTimestamp = Date.now();
    this.r?.hide();
    const currentPromptInputState = this.h ?? initialPromptInputState;
    const replacementText = currentPromptInputState.value.substring(suggestion.item.completion.replacementIndex ?? this.D, currentPromptInputState.cursorIndex);
    let rightSideReplacementText = "";
    if (
      // The line didn't end with ghost text
      (currentPromptInputState.ghostTextIndex === -1 || currentPromptInputState.ghostTextIndex > currentPromptInputState.cursorIndex) && // There is more than one charatcer
      currentPromptInputState.value.length > currentPromptInputState.cursorIndex + 1 && // THe next character is not a space
      currentPromptInputState.value.at(currentPromptInputState.cursorIndex) !== " "
    ) {
      const spaceIndex = currentPromptInputState.value.substring(currentPromptInputState.cursorIndex, currentPromptInputState.ghostTextIndex === -1 ? void 0 : currentPromptInputState.ghostTextIndex).indexOf(" ");
      rightSideReplacementText = currentPromptInputState.value.substring(currentPromptInputState.cursorIndex, spaceIndex === -1 ? void 0 : currentPromptInputState.cursorIndex + spaceIndex);
    }
    const completion = suggestion.item.completion;
    let completionText = completion.label;
    if ((completion.isDirectory || completion.isFile) && completionText.includes(" ")) {
      completionText = completionText.replaceAll(" ", "\\ ");
    }
    let runOnEnter = false;
    if (respectRunOnEnter) {
      const runOnEnterConfig = this.R.getValue($ZX).runOnEnter;
      switch (runOnEnterConfig) {
        case "always": {
          runOnEnter = true;
          break;
        }
        case "exactMatch": {
          runOnEnter = replacementText.toLowerCase() === completionText.toLowerCase();
          break;
        }
        case "exactMatchIgnoreExtension": {
          runOnEnter = replacementText.toLowerCase() === completionText.toLowerCase();
          if (completion.isFile) {
            runOnEnter ||= replacementText.toLowerCase() === completionText.toLowerCase().replace(/\.[^\.]+$/, "");
          }
          break;
        }
      }
    }
    if (completion.icon === $6l.folder) {
      $chc_1.lastAcceptedCompletionTimestamp = 0;
    }
    this.w = completion;
    const commonPrefixLen = $3f(replacementText, completionText);
    const commonPrefix = replacementText.substring(replacementText.length - 1 - commonPrefixLen, replacementText.length - 1);
    const completionSuffix = completionText.substring(commonPrefixLen);
    let resultSequence;
    if (currentPromptInputState.suffix.length > 0 && currentPromptInputState.prefix.endsWith(commonPrefix) && currentPromptInputState.suffix.startsWith(completionSuffix)) {
      resultSequence = "\x1BOC".repeat(completion.label.length - commonPrefixLen);
    } else {
      resultSequence = [
        // Backspace (left) to remove all additional input
        "\x7F".repeat(replacementText.length - commonPrefixLen),
        // Delete (right) to remove any additional text in the same word
        "\x1B[3~".repeat(rightSideReplacementText.length),
        // Write the completion
        completionSuffix,
        // Run on enter if needed
        runOnEnter ? "\r" : ""
      ].join("");
    }
    this.J.fire(resultSequence);
    this.hideSuggestWidget();
  }
  hideSuggestWidget() {
    this.H?.cancel();
    this.H = void 0;
    this.h = void 0;
    this.y = void 0;
    this.r?.hide();
  }
};
$chc = $chc_1 = __decorate([
  __param(3, $wRb),
  __param(4, $kl),
  __param(5, $Pk),
  __param(6, $5Pb),
  __param(7, $wN)
], $chc);
var PersistedWidgetSize2 = class PersistedWidgetSize3 {
  constructor(b) {
    this.b = b;
    this.a = "terminal.integrated.suggestSize";
  }
  restore() {
    const raw = this.b.get(
      this.a,
      0
      /* StorageScope.PROFILE */
    ) ?? "";
    try {
      const obj = JSON.parse(raw);
      if ($rj.is(obj)) {
        return $rj.lift(obj);
      }
    } catch {
    }
    return void 0;
  }
  store(size) {
    this.b.store(
      this.a,
      JSON.stringify(size),
      0,
      1
      /* StorageTarget.MACHINE */
    );
  }
  reset() {
    this.b.remove(
      this.a,
      0
      /* StorageScope.PROFILE */
    );
  }
};
PersistedWidgetSize2 = __decorate([
  __param(0, $jv)
], PersistedWidgetSize2);
function $dhc(path, sep2) {
  if (sep2 === "/") {
    return path.replaceAll("\\", "/");
  }
  return path.replaceAll("/", "\\");
}

// out-build/vs/workbench/contrib/terminalContrib/suggest/browser/pwshCompletionProviderAddon.js
var $ehc_1;
var VSCodeSuggestOscPt;
(function(VSCodeSuggestOscPt2) {
  VSCodeSuggestOscPt2["Completions"] = "Completions";
  VSCodeSuggestOscPt2["CompletionsPwshCommands"] = "CompletionsPwshCommands";
})(VSCodeSuggestOscPt || (VSCodeSuggestOscPt = {}));
var Constants25;
(function(Constants27) {
  Constants27["CachedPwshCommandsStorageKey"] = "terminal.suggest.pwshCommands";
})(Constants25 || (Constants25 = {}));
var RequestCompletionsSequence;
(function(RequestCompletionsSequence2) {
  RequestCompletionsSequence2["Contextual"] = "\x1B[24~e";
  RequestCompletionsSequence2["Global"] = "\x1B[24~f";
  RequestCompletionsSequence2["Git"] = "\x1B[24~g";
  RequestCompletionsSequence2["Code"] = "\x1B[24~h";
})(RequestCompletionsSequence || (RequestCompletionsSequence = {}));
var $ehc = class $ehc2 extends $3c {
  static {
    $ehc_1 = this;
  }
  static {
    this.ID = "terminal.pwshCompletionProvider";
  }
  constructor(providedPwshCommands, capabilities, y, z) {
    super();
    this.y = y;
    this.z = z;
    this.id = $ehc_1.ID;
    this.isBuiltin = true;
    this.shellTypes = [
      "pwsh"
      /* GeneralShellType.PowerShell */
    ];
    this.a = false;
    this.b = false;
    this.f = 0;
    this.n = true;
    this.isPasting = false;
    this.r = null;
    this.s = this.B(new $ze());
    this.onBell = this.s.event;
    this.t = this.B(new $ze());
    this.onAcceptedCompletion = this.t.event;
    this.u = this.B(new $ze());
    this.onDidReceiveCompletions = this.u.event;
    this.w = this.B(new $ze());
    this.onDidRequestSendText = this.w.event;
    this.B(Event2.runAndSubscribe(Event2.any(capabilities.onDidAddCapabilityType, capabilities.onDidRemoveCapabilityType), () => {
      const commandDetection = capabilities.get(
        2
        /* TerminalCapability.CommandDetection */
      );
      if (commandDetection) {
        if (this.j !== commandDetection.promptInputModel) {
          this.j = commandDetection.promptInputModel;
        }
      } else {
        this.j = void 0;
      }
    }));
    $ehc_1.cachedPwshCommands = providedPwshCommands || /* @__PURE__ */ new Set();
    if ($ehc_1.cachedPwshCommands.size === 0) {
      const config = this.z.get("terminal.suggest.pwshCommands", -1, void 0);
      if (config !== void 0) {
        const completions = JSON.parse(config);
        for (const c of completions) {
          $ehc_1.cachedPwshCommands.add(c);
        }
      }
    }
    this.B(this.y.onDidChangeConfiguration((e) => {
      if (e.affectsConfiguration(
        "terminal.integrated.suggest.enabled"
        /* TerminalSuggestSettingId.Enabled */
      )) {
        this.clearSuggestCache();
      }
    }));
  }
  clearSuggestCache() {
    $ehc_1.cachedPwshCommands.clear();
    this.z.remove(
      "terminal.suggest.pwshCommands",
      -1
      /* StorageScope.APPLICATION */
    );
  }
  activate(xterm) {
    this.g = xterm;
    this.B(xterm.onData(() => {
      this.f = Date.now();
    }));
    const config = this.y.getValue($ZX);
    const enabled = config.enabled;
    if (!enabled) {
      return;
    }
    this.B(xterm.parser.registerOscHandler(633, (data) => {
      return this.C(data);
    }));
  }
  C(data) {
    if (!this.g) {
      return false;
    }
    const [command4, ...args2] = data.split(";");
    switch (command4) {
      case "Completions":
        this.D(this.g, data, command4, args2);
        return true;
      case "CompletionsPwshCommands":
        return this.F(this.g, data, command4, args2);
    }
    return false;
  }
  D(terminal2, data, command4, args2) {
    this.u.fire();
    if (!terminal2.element || !this.n || !this.j) {
      this.G(void 0);
      return;
    }
    if (!$Nj(terminal2.element)) {
      this.G(void 0);
      return;
    }
    let replacementIndex = 0;
    let replacementLength = this.j.cursorIndex;
    this.m = {
      value: this.j.value,
      prefix: this.j.prefix,
      suffix: this.j.suffix,
      cursorIndex: this.j.cursorIndex,
      ghostTextIndex: this.j.ghostTextIndex
    };
    let leadingLineContent = this.m.prefix.substring(replacementIndex, replacementIndex + replacementLength);
    const firstChar = leadingLineContent.length === 0 ? "" : leadingLineContent[0];
    const isGlobalCommand = !leadingLineContent.includes(" ") && firstChar !== "[";
    if (!isGlobalCommand) {
      replacementIndex = parseInt(args2[0]);
      replacementLength = parseInt(args2[1]);
      leadingLineContent = this.j.prefix;
    }
    const payload = data.slice(
      command4.length + args2[0].length + args2[1].length + args2[2].length + 4
      /*semi-colons*/
    );
    const rawCompletions = args2.length === 0 || payload.length === 0 ? void 0 : JSON.parse(payload);
    const completions = $fhc(rawCompletions, replacementIndex, replacementLength);
    if (isGlobalCommand) {
      for (const c of $ehc_1.cachedPwshCommands) {
        c.replacementIndex = replacementIndex;
        c.replacementLength = replacementLength;
        completions.push(c);
      }
    }
    if (this.h?.isDirectory && completions.every((c) => c.isDirectory)) {
      completions.push(this.h);
    }
    this.h = void 0;
    this.G(completions);
  }
  async F(terminal2, data, command4, args2) {
    const type = args2[0];
    const rawCompletions = JSON.parse(data.slice(
      command4.length + type.length + 2
      /*semi-colons*/
    ));
    const completions = $fhc(rawCompletions, 0, 0);
    const set = $ehc_1.cachedPwshCommands;
    set.clear();
    for (const c of completions) {
      set.add(c);
    }
    this.z.store(
      "terminal.suggest.pwshCommands",
      JSON.stringify(Array.from(set.values())),
      -1,
      1
      /* StorageTarget.MACHINE */
    );
    return true;
  }
  G(result) {
    if (!this.r) {
      return;
    }
    this.r.complete(result);
    this.r = null;
  }
  H() {
    this.r = new $gi();
    return this.r.p;
  }
  provideCompletions(value, cursorPosition, token) {
    const builtinCompletionsConfig = this.y.getValue($ZX).builtinCompletions;
    if (!this.a && builtinCompletionsConfig.pwshCode) {
      this.w.fire(
        "\x1B[24~h"
        /* RequestCompletionsSequence.Code */
      );
      this.a = true;
    }
    if (!this.b && builtinCompletionsConfig.pwshGit) {
      this.w.fire(
        "\x1B[24~g"
        /* RequestCompletionsSequence.Git */
      );
      this.b = true;
    }
    if ($ehc_1.cachedPwshCommands.size === 0) {
      this.w.fire(
        "\x1B[24~f"
        /* RequestCompletionsSequence.Global */
      );
    }
    if (this.f > $chc.lastAcceptedCompletionTimestamp) {
      this.w.fire(
        "\x1B[24~e"
        /* RequestCompletionsSequence.Contextual */
      );
    }
    if (token.isCancellationRequested) {
      return Promise.resolve(void 0);
    }
    return new Promise((resolve) => {
      const completionPromise = this.H();
      this.B(token.onCancellationRequested(() => {
        this.G(void 0);
      }));
      completionPromise.then((result) => {
        if (token.isCancellationRequested) {
          resolve(void 0);
        } else {
          resolve(result);
        }
      });
    });
  }
};
$ehc = $ehc_1 = __decorate([
  __param(2, $kl),
  __param(3, $jv)
], $ehc);
function $fhc(rawCompletions, replacementIndex, replacementLength) {
  if (!rawCompletions) {
    return [];
  }
  let typedRawCompletions;
  if (!Array.isArray(rawCompletions)) {
    typedRawCompletions = [rawCompletions];
  } else {
    if (rawCompletions.length === 0) {
      return [];
    }
    if (typeof rawCompletions[0] === "string") {
      typedRawCompletions = [rawCompletions].map((e) => ({
        CompletionText: e[0],
        ResultType: e[1],
        ToolTip: e[2],
        CustomIcon: e[3]
      }));
    } else if (Array.isArray(rawCompletions[0])) {
      typedRawCompletions = rawCompletions.map((e) => ({
        CompletionText: e[0],
        ResultType: e[1],
        ToolTip: e[2],
        CustomIcon: e[3]
      }));
    } else {
      typedRawCompletions = rawCompletions;
    }
  }
  return typedRawCompletions.map((e) => rawCompletionToITerminalCompletion(e, replacementIndex, replacementLength));
}
function rawCompletionToITerminalCompletion(rawCompletion, replacementIndex, replacementLength) {
  let label3 = rawCompletion.CompletionText;
  if (rawCompletion.ResultType === 4 && !label3.match(/^[\-+]$/) && // Don't add a `/` to `-` or `+` (navigate location history)
  !label3.match(/^\.\.?$/) && !label3.match(/[\\\/]$/)) {
    const separator = label3.match(/(?<sep>[\\\/])/)?.groups?.sep ?? sep;
    label3 = label3 + separator;
  }
  const detail2 = rawCompletion.ToolTip ?? label3;
  const icon2 = getIcon(rawCompletion.ResultType, rawCompletion.CustomIcon);
  const isExecutable = rawCompletion.ResultType === 2 && rawCompletion.CompletionText.match(/\.[a-z0-9]{2,4}$/i);
  if (isExecutable) {
    rawCompletion.ResultType = 3;
  }
  return {
    label: label3,
    icon: icon2,
    detail: detail2,
    isFile: rawCompletion.ResultType === 3,
    isDirectory: rawCompletion.ResultType === 4,
    isKeyword: rawCompletion.ResultType === 12,
    replacementIndex,
    replacementLength
  };
}
function getIcon(resultType, customIconId) {
  if (customIconId) {
    const icon2 = customIconId in $6l ? $6l[customIconId] : $6l.symbolText;
    if (icon2) {
      return icon2;
    }
  }
  return pwshTypeToIconMap[resultType] ?? $6l.symbolText;
}
var pwshTypeToIconMap = {
  0: $6l.symbolText,
  1: $6l.history,
  2: $6l.symbolMethod,
  3: $6l.symbolFile,
  4: $6l.folder,
  5: $6l.symbolProperty,
  6: $6l.symbolMethod,
  7: $6l.symbolVariable,
  8: $6l.symbolValue,
  9: $6l.symbolVariable,
  10: $6l.symbolNamespace,
  11: $6l.symbolInterface,
  12: $6l.symbolKeyword,
  13: $6l.symbolKeyword
};

// out-build/vs/workbench/contrib/terminalContrib/suggest/browser/terminal.suggest.contribution.js
var TerminalSuggestContribution_1;
$SC(
  $wRb,
  $yRb,
  1
  /* InstantiationType.Delayed */
);
var TerminalSuggestContribution = class TerminalSuggestContribution2 extends $2c {
  static {
    TerminalSuggestContribution_1 = this;
  }
  static {
    this.ID = "terminal.suggest";
  }
  static get(instance2) {
    return instance2.getContribution(TerminalSuggestContribution_1.ID);
  }
  get addon() {
    return this.a.value;
  }
  get pwshAddon() {
    return this.b.value;
  }
  constructor(j, m, n, q, r2) {
    super();
    this.j = j;
    this.m = m;
    this.n = n;
    this.q = q;
    this.r = r2;
    this.a = new $4c();
    this.b = new $4c();
    this.c = new Set(TerminalContextKeys.suggestWidgetVisible.key);
    this.add($1c(() => {
      this.a?.dispose();
      this.b?.dispose();
    }));
    this.h = TerminalContextKeys.suggestWidgetVisible.bindTo(this.m);
  }
  xtermOpen(xterm) {
    const config = this.n.getValue($ZX);
    const enabled = config.enabled;
    if (!enabled) {
      return;
    }
    this.add(Event2.runAndSubscribe(this.j.instance.onDidChangeShellType, async () => {
      this.t(xterm.raw);
    }));
    this.add(this.m.onDidChangeContext((e) => {
      if (e.affectsSome(this.c)) {
        this.t(xterm.raw);
      }
    }));
    this.add(this.n.onDidChangeConfiguration((e) => {
      if (e.affectsConfiguration(
        "terminal.integrated.sendKeybindingsToShell"
        /* TerminalSettingId.SendKeybindingsToShell */
      )) {
        this.t(xterm.raw);
      }
    }));
  }
  s(xterm) {
    if (this.j.instance.shellType !== "pwsh") {
      return;
    }
    const pwshCompletionProviderAddon = this.b.value = this.q.createInstance($ehc, void 0, this.j.instance.capabilities);
    xterm.loadAddon(pwshCompletionProviderAddon);
    this.add(pwshCompletionProviderAddon);
    this.add(pwshCompletionProviderAddon.onDidRequestSendText((text2) => {
      this.j.instance.focus();
      this.j.instance.sendText(text2, false);
    }));
    this.add(this.r.registerTerminalCompletionProvider("builtinPwsh", "pwsh", pwshCompletionProviderAddon));
    if (!$l) {
      let barrier;
      if (pwshCompletionProviderAddon) {
        this.add(pwshCompletionProviderAddon.onDidRequestSendText(() => {
          barrier = new $Vh(2e3);
          this.j.instance.pauseInputEvents(barrier);
        }));
      }
      if (this.b.value) {
        this.add(this.b.value.onDidReceiveCompletions(() => {
          barrier?.open();
          barrier = void 0;
        }));
      } else {
        throw Error("no addon");
      }
    }
  }
  t(xterm) {
    const sendingKeybindingsToShell = this.n.getValue($9X).sendKeybindingsToShell;
    if (sendingKeybindingsToShell || !this.j.instance.shellType) {
      this.a.clear();
      this.b.clear();
      return;
    }
    if (this.h) {
      const addon = this.a.value = this.q.createInstance($chc, this.j.instance.shellType, this.j.instance.capabilities, this.h);
      xterm.loadAddon(addon);
      this.s(xterm);
      if (this.j.instance.target === TerminalLocation2.Editor) {
        addon.setContainerWithOverflow(xterm.element);
      } else {
        addon.setContainerWithOverflow($Gj(xterm.element, "panel"));
      }
      addon.setScreen(xterm.element.querySelector(".xterm-screen"));
      this.add(this.j.instance.onDidBlur(() => addon.hideSuggestWidget()));
      this.add(addon.onAcceptedCompletion(async (text2) => {
        this.j.instance.focus();
        this.j.instance.sendText(text2, false);
      }));
      const clipboardContrib = $Wfc.get(this.j.instance);
      this.add(clipboardContrib.onWillPaste(() => addon.isPasting = true));
      this.add(clipboardContrib.onDidPaste(() => {
        setTimeout(() => addon.isPasting = false, 100);
      }));
      if (!$l) {
        let barrier;
        this.add(addon.onDidReceiveCompletions(() => {
          barrier?.open();
          barrier = void 0;
        }));
      }
    }
  }
};
TerminalSuggestContribution = TerminalSuggestContribution_1 = __decorate([
  __param(1, $on),
  __param(2, $kl),
  __param(3, $Pk),
  __param(4, $wRb)
], TerminalSuggestContribution);
$Y0b(TerminalSuggestContribution.ID, TerminalSuggestContribution);
$Wec({
  id: "workbench.action.terminal.requestCompletions",
  title: localize2(10978, "Request Completions"),
  keybinding: {
    primary: 2048 | 10,
    mac: {
      primary: 256 | 10
      /* KeyCode.Space */
    },
    weight: 200 + 1,
    when: $7m.and(TerminalContextKeys.focus, TerminalContextKeys.terminalShellIntegrationEnabled, $7m.equals(`config.${"terminal.integrated.suggest.enabled"}`, true))
  },
  run: (activeInstance) => TerminalSuggestContribution.get(activeInstance)?.addon?.requestCompletions()
});
$Wec({
  id: "workbench.action.terminal.selectPrevSuggestion",
  title: localize2(10979, "Select the Previous Suggestion"),
  f1: false,
  precondition: $7m.and($7m.or(TerminalContextKeys.processSupported, TerminalContextKeys.terminalHasBeenCreated), TerminalContextKeys.focus, TerminalContextKeys.isOpen, TerminalContextKeys.suggestWidgetVisible),
  keybinding: {
    // Up is bound to other workbench keybindings that this needs to beat
    primary: 16,
    weight: 200 + 1
  },
  run: (activeInstance) => TerminalSuggestContribution.get(activeInstance)?.addon?.selectPreviousSuggestion()
});
$Wec({
  id: "workbench.action.terminal.selectPrevPageSuggestion",
  title: localize2(10980, "Select the Previous Page Suggestion"),
  f1: false,
  precondition: $7m.and($7m.or(TerminalContextKeys.processSupported, TerminalContextKeys.terminalHasBeenCreated), TerminalContextKeys.focus, TerminalContextKeys.isOpen, TerminalContextKeys.suggestWidgetVisible),
  keybinding: {
    // Up is bound to other workbench keybindings that this needs to beat
    primary: 11,
    weight: 200 + 1
  },
  run: (activeInstance) => TerminalSuggestContribution.get(activeInstance)?.addon?.selectPreviousPageSuggestion()
});
$Wec({
  id: "workbench.action.terminal.selectNextSuggestion",
  title: localize2(10981, "Select the Next Suggestion"),
  f1: false,
  precondition: $7m.and($7m.or(TerminalContextKeys.processSupported, TerminalContextKeys.terminalHasBeenCreated), TerminalContextKeys.focus, TerminalContextKeys.isOpen, TerminalContextKeys.suggestWidgetVisible),
  keybinding: {
    // Down is bound to other workbench keybindings that this needs to beat
    primary: 18,
    weight: 200 + 1
  },
  run: (activeInstance) => TerminalSuggestContribution.get(activeInstance)?.addon?.selectNextSuggestion()
});
$Wec({
  id: "workbench.action.terminal.selectNextPageSuggestion",
  title: localize2(10982, "Select the Next Page Suggestion"),
  f1: false,
  precondition: $7m.and($7m.or(TerminalContextKeys.processSupported, TerminalContextKeys.terminalHasBeenCreated), TerminalContextKeys.focus, TerminalContextKeys.isOpen, TerminalContextKeys.suggestWidgetVisible),
  keybinding: {
    // Down is bound to other workbench keybindings that this needs to beat
    primary: 12,
    weight: 200 + 1
  },
  run: (activeInstance) => TerminalSuggestContribution.get(activeInstance)?.addon?.selectNextPageSuggestion()
});
$Wec({
  id: "workbench.action.terminal.acceptSelectedSuggestion",
  title: localize2(10983, "Accept Selected Suggestion"),
  f1: false,
  precondition: $7m.and($7m.or(TerminalContextKeys.processSupported, TerminalContextKeys.terminalHasBeenCreated), TerminalContextKeys.focus, TerminalContextKeys.isOpen, TerminalContextKeys.suggestWidgetVisible),
  keybinding: {
    primary: 2,
    // Tab is bound to other workbench keybindings that this needs to beat
    weight: 200 + 1
  },
  run: (activeInstance) => TerminalSuggestContribution.get(activeInstance)?.addon?.acceptSelectedSuggestion()
});
$Wec({
  id: "workbench.action.terminal.acceptSelectedSuggestionEnter",
  title: localize2(10984, "Accept Selected Suggestion (Enter)"),
  f1: false,
  precondition: $7m.and($7m.or(TerminalContextKeys.processSupported, TerminalContextKeys.terminalHasBeenCreated), TerminalContextKeys.focus, TerminalContextKeys.isOpen, TerminalContextKeys.suggestWidgetVisible),
  keybinding: {
    primary: 3,
    // Enter is bound to other workbench keybindings that this needs to beat
    weight: 200 + 1,
    when: $7m.notEquals(`config.${"terminal.integrated.suggest.runOnEnter"}`, "ignore")
  },
  run: async (activeInstance) => TerminalSuggestContribution.get(activeInstance)?.addon?.acceptSelectedSuggestion(void 0, true)
});
$Wec({
  id: "workbench.action.terminal.hideSuggestWidget",
  title: localize2(10985, "Hide Suggest Widget"),
  f1: false,
  precondition: $7m.and($7m.or(TerminalContextKeys.processSupported, TerminalContextKeys.terminalHasBeenCreated), TerminalContextKeys.focus, TerminalContextKeys.isOpen, TerminalContextKeys.suggestWidgetVisible),
  keybinding: {
    primary: 9,
    // Escape is bound to other workbench keybindings that this needs to beat
    weight: 200 + 1
  },
  run: (activeInstance) => TerminalSuggestContribution.get(activeInstance)?.addon?.hideSuggestWidget()
});
$Wec({
  id: "workbench.action.terminal.clearSuggestCache",
  title: localize2(10986, "Clear Suggest Cache"),
  f1: true,
  run: (activeInstance) => TerminalSuggestContribution.get(activeInstance)?.pwshAddon?.clearSuggestCache()
});

// out-build/vs/workbench/contrib/terminalContrib/chat/browser/terminal.initialHint.contribution.js
var $hhc_1;
var $148 = $;
var Constants26;
(function(Constants27) {
  Constants27["InitialHintHideStorageKey"] = "terminal.initialHint.hide";
})(Constants26 || (Constants26 = {}));
var $ghc = class extends $3c {
  get onDidRequestCreateHint() {
    return this.a.event;
  }
  constructor(c, f) {
    super();
    this.c = c;
    this.f = f;
    this.a = this.B(new $ze());
    this.b = this.B(new $4c());
  }
  activate(terminal2) {
    const store = this.B(new $2c());
    this.b.value = store;
    const capability = this.c.get(
      2
      /* TerminalCapability.CommandDetection */
    );
    if (capability) {
      store.add(Event2.once(capability.promptInputModel.onDidStartInput)(() => this.a.fire()));
    } else {
      this.B(this.c.onDidAddCapability((e) => {
        if (e.id === 2) {
          const capability2 = e.capability;
          store.add(Event2.once(capability2.promptInputModel.onDidStartInput)(() => this.a.fire()));
          if (!capability2.promptInputModel.value) {
            this.a.fire();
          }
        }
      }));
    }
    const agentListener = this.f((e) => {
      if (e?.locations.includes(ChatAgentLocation.Terminal)) {
        this.a.fire();
        agentListener.dispose();
      }
    });
    this.b.value?.add(agentListener);
  }
};
var $hhc = class $hhc2 extends $3c {
  static {
    $hhc_1 = this;
  }
  static {
    this.ID = "terminal.initialHint";
  }
  static get(instance2) {
    return instance2.getContribution($hhc_1.ID);
  }
  constructor(g, h3, j, m, n, r2, s) {
    super();
    this.g = g;
    this.h = h3;
    this.j = j;
    this.m = m;
    this.n = n;
    this.r = r2;
    this.s = s;
    this.B(this.j.onDidChangeConfiguration((e) => {
      if (e.affectsConfiguration(
        "terminal.integrated.initialHint"
        /* TerminalInitialHintSettingId.Enabled */
      )) {
        this.n.remove(
          "terminal.initialHint.hide",
          -1
          /* StorageScope.APPLICATION */
        );
      }
    }));
  }
  xtermOpen(xterm) {
    if ("shellLaunchConfig" in this.g.instance && (this.g.instance.shellLaunchConfig.isExtensionOwnedTerminal || this.g.instance.shellLaunchConfig.isFeatureTerminal)) {
      return;
    }
    if (this.n.getBoolean("terminal.initialHint.hide", -1, false)) {
      return;
    }
    if (this.s.instances.length + this.r.instances.length !== 1) {
      return;
    }
    this.f = xterm;
    this.a = this.B(this.m.createInstance($ghc, this.g.instance.capabilities, this.h.onDidChangeAgents));
    this.f.raw.loadAddon(this.a);
    this.B(this.a.onDidRequestCreateHint(() => this.t()));
  }
  t() {
    const instance2 = this.g.instance instanceof $wfc ? this.g.instance : void 0;
    const commandDetectionCapability = instance2?.capabilities.get(
      2
      /* TerminalCapability.CommandDetection */
    );
    if (!instance2 || !this.f || this.b || !commandDetectionCapability || commandDetectionCapability.promptInputModel.value || !!instance2.shellLaunchConfig.attachPersistentProcess) {
      return;
    }
    if (!this.j.getValue(
      "terminal.integrated.initialHint"
      /* TerminalInitialHintSettingId.Enabled */
    )) {
      return;
    }
    if (!this.c) {
      const marker = this.f.raw.registerMarker();
      if (!marker) {
        return;
      }
      if (this.f.raw.buffer.active.cursorX === 0) {
        return;
      }
      this.B(marker);
      this.c = this.f.raw.registerDecoration({
        marker,
        x: this.f.raw.buffer.active.cursorX + 1
      });
      if (this.c) {
        this.B(this.c);
      }
    }
    this.B(this.f.raw.onKey(() => this.dispose()));
    this.B(this.j.onDidChangeConfiguration((e) => {
      if (e.affectsConfiguration(
        "terminal.integrated.initialHint"
        /* TerminalInitialHintSettingId.Enabled */
      ) && !this.j.getValue(
        "terminal.integrated.initialHint"
        /* TerminalInitialHintSettingId.Enabled */
      )) {
        this.dispose();
      }
    }));
    const inputModel = commandDetectionCapability.promptInputModel;
    if (inputModel) {
      this.B(inputModel.onDidChangeInput(() => {
        if (inputModel.value) {
          this.dispose();
        }
      }));
    }
    if (!this.c) {
      return;
    }
    this.B(this.c);
    this.B(this.c.onRender((e) => {
      if (!this.b && this.f?.isFocused && this.s.instances.length + this.r.instances.length === 1) {
        const terminalAgents = this.h.getActivatedAgents().filter((candidate) => candidate.locations.includes(ChatAgentLocation.Terminal));
        if (terminalAgents?.length) {
          const widget = this.B(this.m.createInstance(TerminalInitialHintWidget, instance2));
          this.a?.dispose();
          this.b = widget.getDomNode(terminalAgents);
          if (!this.b) {
            return;
          }
          e.appendChild(this.b);
          e.classList.add("terminal-initial-hint");
          const font = this.f.getFont();
          if (font) {
            e.style.fontFamily = font.fontFamily;
            e.style.fontSize = font.fontSize + "px";
          }
        }
      }
      if (this.b && this.f) {
        const decoration3 = this.b.parentElement;
        if (decoration3) {
          decoration3.style.width = (this.f.raw.cols - this.f.raw.buffer.active.cursorX) / this.f.raw.cols * 100 + "%";
        }
      }
    }));
  }
};
$hhc = $hhc_1 = __decorate([
  __param(1, $ZO),
  __param(2, $kl),
  __param(3, $Pk),
  __param(4, $jv),
  __param(5, $6Pb),
  __param(6, $7Pb)
], $hhc);
$Y0b($hhc.ID, $hhc, false);
var TerminalInitialHintWidget = class TerminalInitialHintWidget2 extends $3c {
  constructor(g, h3, j, m, n, r2, s, t, u, w) {
    super();
    this.g = g;
    this.h = h3;
    this.j = j;
    this.m = m;
    this.n = n;
    this.r = r2;
    this.s = s;
    this.t = t;
    this.u = u;
    this.w = w;
    this.b = this.B(new $2c());
    this.c = false;
    this.f = "";
    this.b.add(g.onDidFocus(() => {
      if (this.g.hasFocus && this.c && this.f && this.m.getValue(
        "accessibility.verbosity.terminalChat"
        /* AccessibilityVerbositySettingId.TerminalChat */
      )) {
        $_Z(this.f);
      }
    }));
    this.b.add(w.onDidChangeInstances(() => {
      if (this.w.instances.length !== 1) {
        this.dispose();
      }
    }));
    this.b.add(this.m.onDidChangeConfiguration((e) => {
      if (e.affectsConfiguration(
        "terminal.integrated.initialHint"
        /* TerminalInitialHintSettingId.Enabled */
      ) && !this.m.getValue(
        "terminal.integrated.initialHint"
        /* TerminalInitialHintSettingId.Enabled */
      )) {
        this.dispose();
      }
    }));
  }
  y(agents) {
    let providerName = (agents.length === 1 ? agents[0].fullName : void 0) ?? this.s.nameShort;
    const defaultAgent = this.h.getDefaultAgent(ChatAgentLocation.Panel);
    if (defaultAgent?.extensionId.value === agents[0].extensionId.value) {
      providerName = defaultAgent.fullName ?? providerName;
    }
    let ariaLabel = `Ask ${providerName} something or start typing to dismiss.`;
    const handleClick = () => {
      this.t.store(
        "terminal.initialHint.hide",
        true,
        -1,
        0
        /* StorageTarget.USER */
      );
      this.u.publicLog2("workbenchActionExecuted", {
        id: "terminalInlineChat.hintAction",
        from: "hint"
      });
      this.j.executeCommand("workbench.action.terminal.chat.start", { from: "hint" });
    };
    this.b.add(this.j.onDidExecuteCommand((e) => {
      if (e.commandId === "workbench.action.terminal.chat.start") {
        this.t.store(
          "terminal.initialHint.hide",
          true,
          -1,
          0
          /* StorageTarget.USER */
        );
        this.dispose();
      }
    }));
    const hintHandler = {
      disposables: this.b,
      callback: (index, _event) => {
        switch (index) {
          case "0":
            handleClick();
            break;
        }
      }
    };
    const hintElement = $148("div.terminal-initial-hint");
    hintElement.style.display = "block";
    const keybindingHint = this.r.lookupKeybinding(
      "workbench.action.terminal.chat.start"
      /* TerminalChatCommandId.Start */
    );
    const keybindingHintLabel = keybindingHint?.getLabel();
    if (keybindingHint && keybindingHintLabel) {
      const actionPart = localize(10828, null, keybindingHintLabel, providerName);
      const [before, after] = actionPart.split(keybindingHintLabel).map((fragment) => {
        const hintPart = $148("a", void 0, fragment);
        this.b.add($_i(hintPart, $7j.CLICK, handleClick));
        return hintPart;
      });
      hintElement.appendChild(before);
      const label3 = hintHandler.disposables.add(new $32(hintElement, OS));
      label3.set(keybindingHint);
      label3.element.style.width = "min-content";
      label3.element.style.display = "inline";
      label3.element.style.cursor = "pointer";
      this.b.add($_i(label3.element, $7j.CLICK, handleClick));
      hintElement.appendChild(after);
      const typeToDismiss = localize(10829, null);
      const textHint2 = $148("span.detail", void 0, typeToDismiss);
      hintElement.appendChild(textHint2);
      ariaLabel = actionPart.concat(typeToDismiss);
    } else {
      const hintMsg = localize(10830, null, providerName);
      const rendered = $RZ(hintMsg, { actionHandler: hintHandler });
      hintElement.appendChild(rendered);
    }
    return { ariaLabel, hintHandler, hintElement };
  }
  getDomNode(agents) {
    if (!this.a) {
      this.a = $148(".terminal-initial-hint");
      this.a.style.paddingLeft = "4px";
      const { hintElement, ariaLabel } = this.y(agents);
      this.a.append(hintElement);
      this.f = ariaLabel.concat(localize(
        10831,
        null,
        "accessibility.verbosity.terminalChat"
        /* AccessibilityVerbositySettingId.TerminalChat */
      ));
      this.b.add($_i(this.a, "click", () => {
        this.a?.remove();
        this.a = void 0;
      }));
      this.b.add($_i(this.a, $7j.CONTEXT_MENU, (e) => {
        this.n.showContextMenu({
          getAnchor: () => {
            return new $lf($Qj(), e);
          },
          getActions: () => {
            return [
              {
                id: "workench.action.disableTerminalInitialHint",
                label: localize(10832, null),
                tooltip: localize(10833, null),
                enabled: true,
                class: void 0,
                run: () => this.m.updateValue("terminal.integrated.initialHint", false)
              }
            ];
          }
        });
      }));
    }
    return this.a;
  }
  dispose() {
    this.a?.remove();
    super.dispose();
  }
};
TerminalInitialHintWidget = __decorate([
  __param(1, $ZO),
  __param(2, $sn),
  __param(3, $kl),
  __param(4, $50),
  __param(5, $Ty),
  __param(6, $Vu),
  __param(7, $jv),
  __param(8, $zv),
  __param(9, $4Pb)
], TerminalInitialHintWidget);

// out-build/vs/workbench/contrib/terminalContrib/wslRecommendation/browser/terminal.wslRecommendation.contribution.js
var $ihc = class $ihc2 extends $3c {
  static {
    this.ID = "terminalWslRecommendation";
  }
  constructor(extensionManagementService, instantiationService, notificationService, productService, terminalService) {
    super();
    if (!$l) {
      return;
    }
    const exeBasedExtensionTips = productService.exeBasedExtensionTips;
    if (!exeBasedExtensionTips || !exeBasedExtensionTips.wsl) {
      return;
    }
    let listener = terminalService.onDidCreateInstance(async (instance2) => {
      async function isExtensionInstalled(id2) {
        const extensions = await extensionManagementService.getInstalled();
        return extensions.some((e) => e.identifier.id === id2);
      }
      if (!instance2.shellLaunchConfig.executable || $rc(instance2.shellLaunchConfig.executable).toLowerCase() !== "wsl.exe") {
        return;
      }
      listener?.dispose();
      listener = void 0;
      const extId = Object.keys(exeBasedExtensionTips.wsl.recommendations).find((extId2) => exeBasedExtensionTips.wsl.recommendations[extId2].important);
      if (!extId || await isExtensionInstalled(extId)) {
        return;
      }
      notificationService.prompt(Severity2.Info, localize(11007, null, exeBasedExtensionTips.wsl.friendlyName), [
        {
          label: localize(11008, null),
          run: () => {
            instantiationService.createInstance($sDb, extId).run();
          }
        }
      ], {
        sticky: true,
        neverShowAgain: { id: "terminalConfigHelper/launchRecommendationsIgnore", scope: NeverShowAgainScope.APPLICATION },
        onCancel: () => {
        }
      });
    });
  }
};
$ihc = __decorate([
  __param(0, $sA),
  __param(1, $Pk),
  __param(2, $PJ),
  __param(3, $Vu),
  __param(4, $4Pb)
], $ihc);
$PL(
  $ihc.ID,
  $ihc,
  4
  /* WorkbenchPhase.Eventually */
);

// out-build/vs/platform/externalTerminal/common/externalTerminal.js
var $9x = $Qk("externalTerminal");

// out-build/vs/workbench/contrib/externalTerminal/browser/externalTerminal.contribution.js
var OPEN_IN_TERMINAL_COMMAND_ID = "openInTerminal";
var OPEN_IN_INTEGRATED_TERMINAL_COMMAND_ID = "openInIntegratedTerminal";
function registerOpenTerminalCommand(id2, explorerKind) {
  $tn.registerCommand({
    id: id2,
    handler: async (accessor, resource) => {
      const configurationService = accessor.get($kl);
      const fileService = accessor.get($km);
      const integratedTerminalService = accessor.get($4Pb);
      const remoteAgentService = accessor.get($RL);
      const terminalGroupService = accessor.get($7Pb);
      let externalTerminalService = void 0;
      try {
        externalTerminalService = accessor.get($9x);
      } catch {
      }
      const resources = $mvb(resource, accessor.get($Deb), accessor.get($mJ), accessor.get($iJ), accessor.get($kvb));
      return fileService.resolveAll(resources.map((r2) => ({ resource: r2 }))).then(async (stats) => {
        const config = configurationService.getValue();
        const useIntegratedTerminal = remoteAgentService.getConnection() || explorerKind === "integrated";
        const targets = $Rb(stats.filter((data) => data.success));
        if (useIntegratedTerminal) {
          const opened = {};
          const cwds = targets.map(({ stat }) => {
            const resource2 = stat.resource;
            if (stat.isDirectory) {
              return resource2;
            }
            return URI.from({
              scheme: resource2.scheme,
              authority: resource2.authority,
              fragment: resource2.fragment,
              query: resource2.query,
              path: $qc(resource2.path)
            });
          });
          for (const cwd2 of cwds) {
            if (opened[cwd2.path]) {
              return;
            }
            opened[cwd2.path] = true;
            const instance2 = await integratedTerminalService.createTerminal({ config: { cwd: cwd2 } });
            if (instance2 && instance2.target !== TerminalLocation2.Editor && (resources.length === 1 || !resource || cwd2.path === resource.path || cwd2.path === $qc(resource.path))) {
              integratedTerminalService.setActiveInstance(instance2);
              terminalGroupService.showPanel(true);
            }
          }
        } else if (externalTerminalService) {
          $Rb(targets.map(({ stat }) => stat.isDirectory ? stat.resource.fsPath : $qc(stat.resource.fsPath))).forEach((cwd2) => {
            externalTerminalService.openTerminal(config.terminal.external, cwd2);
          });
        }
      });
    }
  });
}
registerOpenTerminalCommand(OPEN_IN_TERMINAL_COMMAND_ID, "external");
registerOpenTerminalCommand(OPEN_IN_INTEGRATED_TERMINAL_COMMAND_ID, "integrated");
var $jhc = class $jhc2 extends $3c {
  constructor(c) {
    super();
    this.c = c;
    const shouldShowIntegratedOnLocal = $7m.and($lqb.Scheme.isEqualTo(Schemas.file), $7m.or($7m.equals("config.terminal.explorerKind", "integrated"), $7m.equals("config.terminal.explorerKind", "both")));
    const shouldShowExternalKindOnLocal = $7m.and($lqb.Scheme.isEqualTo(Schemas.file), $7m.or($7m.equals("config.terminal.explorerKind", "external"), $7m.equals("config.terminal.explorerKind", "both")));
    this.a = {
      group: "navigation",
      order: 30,
      command: {
        id: OPEN_IN_INTEGRATED_TERMINAL_COMMAND_ID,
        title: localize(7017, null)
      },
      when: $7m.or(shouldShowIntegratedOnLocal, $lqb.Scheme.isEqualTo(Schemas.vscodeRemote))
    };
    this.b = {
      group: "navigation",
      order: 31,
      command: {
        id: OPEN_IN_TERMINAL_COMMAND_ID,
        title: localize(7018, null)
      },
      when: shouldShowExternalKindOnLocal
    };
    $dJ.appendMenuItem($bJ.ExplorerContext, this.b);
    $dJ.appendMenuItem($bJ.ExplorerContext, this.a);
    this.B(this.c.onDidChangeConfiguration((e) => {
      if (e.affectsConfiguration("terminal.explorerKind") || e.affectsConfiguration("terminal.external")) {
        this.g();
      }
    }));
    this.g();
  }
  f() {
    const config = this.c.getValue().terminal;
    if ($l && config.external?.windowsExec) {
      const file = $rc(config.external.windowsExec);
      if (file === "wt" || file === "wt.exe") {
        return true;
      }
    }
    return false;
  }
  g() {
    if (this.f()) {
      this.b.command.title = localize(7019, null);
    }
  }
};
$jhc = __decorate([
  __param(0, $kl)
], $jhc);
$Wn.as(Extensions2.Workbench).registerWorkbenchContribution(
  $jhc,
  3
  /* LifecyclePhase.Restored */
);

// out-build/vs/workbench/contrib/relauncher/browser/relauncher.contribution.js
var $khc_1;
var $khc = class $khc2 extends $3c {
  static {
    $khc_1 = this;
  }
  static {
    this.a = [
      "window.titleBarStyle",
      "window.nativeTabs",
      "window.nativeFullScreen",
      "window.clickThroughInactive",
      "window.experimentalControlOverlay",
      "update.mode",
      "editor.accessibilitySupport",
      "security.workspace.trust.enabled",
      "workbench.enableExperiments",
      "_extensionsGallery.enablePPE",
      "security.restrictUNCAccess",
      "accessibility.verbosity.debug"
    ];
  }
  constructor(w, y, z, C, userDataSyncWorkbenchService, D, F) {
    super();
    this.w = w;
    this.y = y;
    this.z = z;
    this.C = C;
    this.D = D;
    this.F = F;
    this.b = new ChangeObserver("string");
    this.c = new ChangeObserver("boolean");
    this.f = new ChangeObserver("boolean");
    this.g = new ChangeObserver("boolean");
    this.h = new ChangeObserver("boolean");
    this.j = new ChangeObserver("string");
    this.n = new ChangeObserver("boolean");
    this.r = new ChangeObserver("boolean");
    this.s = new ChangeObserver("boolean");
    this.t = new ChangeObserver("boolean");
    this.u = new ChangeObserver("boolean");
    this.I(false);
    this.B(this.y.onDidChangeConfiguration((e) => this.G(e)));
    this.B(userDataSyncWorkbenchService.onDidTurnOnSync((e) => this.I(true)));
  }
  G(e) {
    if (e && !$khc_1.a.some((key2) => e.affectsConfiguration(key2))) {
      return;
    }
    if (this.H()) {
      return;
    }
    this.I(
      e.source !== 7
      /* ConfigurationTarget.DEFAULT */
      /* do not ask to relaunch if defaults changed */
    );
  }
  H() {
    return !this.C.isEnabled() && this.z.status === "syncing";
  }
  I(askToRelaunch) {
    let changed = false;
    function processChanged(didChange) {
      changed = changed || didChange;
    }
    const config = this.y.getValue();
    if ($p) {
      processChanged((config.window.titleBarStyle === "native" || config.window.titleBarStyle === "custom") && this.b.handleChange(config.window?.titleBarStyle));
      processChanged($m && this.c.handleChange(config.window?.nativeTabs));
      processChanged($m && this.f.handleChange(config.window?.nativeFullScreen));
      processChanged($m && this.g.handleChange(config.window?.clickThroughInactive));
      processChanged($n && this.h.handleChange(config.window?.experimentalControlOverlay));
      processChanged(this.j.handleChange(config.update?.mode));
      if ($n && typeof config.editor?.accessibilitySupport === "string" && config.editor.accessibilitySupport !== this.m) {
        this.m = config.editor.accessibilitySupport;
        if (this.m === "on") {
          changed = true;
        }
      }
      processChanged(this.n.handleChange(config?.security?.workspace?.trust?.enabled));
      processChanged(this.t.handleChange(config?.security?.restrictUNCAccess));
      processChanged(this.u.handleChange(config?.accessibility?.verbosity?.debug));
    }
    processChanged(this.r.handleChange(config.workbench?.enableExperiments));
    processChanged(this.D.quality !== "stable" && this.s.handleChange(config._extensionsGallery?.enablePPE));
    if (askToRelaunch && changed && this.w.hasFocus) {
      this.J($p ? localize(9104, null) : localize(9105, null), $p ? localize(9106, null, this.D.nameLong) : localize(9107, null, this.D.nameLong), $p ? localize(9108, null) : localize(9109, null), () => this.w.restart());
    }
  }
  async J(message, detail2, primaryButton, confirmedFn) {
    const { confirmed } = await this.F.confirm({ message, detail: detail2, primaryButton });
    if (confirmed) {
      confirmedFn();
    }
  }
};
$khc = $khc_1 = __decorate([
  __param(0, $S4),
  __param(1, $kl),
  __param(2, $7Bb),
  __param(3, $6Bb),
  __param(4, $oXb),
  __param(5, $Vu),
  __param(6, $Yv)
], $khc);
var ChangeObserver = class _ChangeObserver {
  static create(typeName) {
    return new _ChangeObserver(typeName);
  }
  constructor(a) {
    this.a = a;
    this.b = void 0;
  }
  /**
   * Returns if there was a change compared to the last value
   */
  handleChange(value) {
    if (typeof value === this.a && value !== this.b) {
      this.b = value;
      return true;
    }
    return false;
  }
};
var $lhc = class $lhc2 extends $3c {
  constructor(f, extensionService, hostService, environmentService) {
    super();
    this.f = f;
    this.b = this.B(new $8h(async () => {
      if (!!environmentService.extensionTestsLocationURI) {
        return;
      }
      if (environmentService.remoteAuthority) {
        hostService.reload();
      } else if ($p) {
        const stopped = await extensionService.stopExtensionHosts(localize(9110, null));
        if (stopped) {
          extensionService.startExtensionHosts();
        }
      }
    }, 10));
    this.f.getCompleteWorkspace().then((workspace2) => {
      this.a = workspace2.folders.length > 0 ? workspace2.folders[0].uri : void 0;
      this.g();
      this.B(this.f.onDidChangeWorkbenchState(() => setTimeout(() => this.g())));
    });
    this.B($1c(() => {
      this.c?.dispose();
    }));
  }
  g() {
    if (this.f.getWorkbenchState() === 3) {
      const workspace2 = this.f.getWorkspace();
      this.a = workspace2.folders.length > 0 ? workspace2.folders[0].uri : void 0;
      if (!this.c) {
        this.c = this.f.onDidChangeWorkspaceFolders(() => this.h());
      }
    } else {
      $Xc(this.c);
      this.c = void 0;
    }
  }
  h() {
    const workspace2 = this.f.getWorkspace();
    const newFirstFolderResource = workspace2.folders.length > 0 ? workspace2.folders[0].uri : void 0;
    if (!$oh(this.a, newFirstFolderResource)) {
      this.a = newFirstFolderResource;
      this.b.schedule();
    }
  }
};
$lhc = __decorate([
  __param(0, $Zk),
  __param(1, $wN),
  __param(2, $S4),
  __param(3, $US)
], $lhc);
var workbenchRegistry3 = $Wn.as(Extensions2.Workbench);
workbenchRegistry3.registerWorkbenchContribution(
  $khc,
  3
  /* LifecyclePhase.Restored */
);
workbenchRegistry3.registerWorkbenchContribution(
  $lhc,
  3
  /* LifecyclePhase.Restored */
);

// out-build/vs/base/common/parsers.js
var ValidationState;
(function(ValidationState2) {
  ValidationState2[ValidationState2["OK"] = 0] = "OK";
  ValidationState2[ValidationState2["Info"] = 1] = "Info";
  ValidationState2[ValidationState2["Warning"] = 2] = "Warning";
  ValidationState2[ValidationState2["Error"] = 3] = "Error";
  ValidationState2[ValidationState2["Fatal"] = 4] = "Fatal";
})(ValidationState || (ValidationState = {}));
var $3P = class {
  constructor() {
    this.a = 0;
  }
  get state() {
    return this.a;
  }
  set state(value) {
    if (value > this.a) {
      this.a = value;
    }
  }
  isOK() {
    return this.a === 0;
  }
  isFatal() {
    return this.a === 4;
  }
};
var $4P = class {
  constructor(problemReporter) {
    this.a = problemReporter;
  }
  reset() {
    this.a.status.state = 0;
  }
  get problemReporter() {
    return this.a;
  }
  info(message) {
    this.a.info(message);
  }
  warn(message) {
    this.a.warn(message);
  }
  error(message) {
    this.a.error(message);
  }
  fatal(message) {
    this.a.fatal(message);
  }
};

// out-build/vs/workbench/contrib/tasks/common/problemMatcher.js
var FileLocationKind;
(function(FileLocationKind2) {
  FileLocationKind2[FileLocationKind2["Default"] = 0] = "Default";
  FileLocationKind2[FileLocationKind2["Relative"] = 1] = "Relative";
  FileLocationKind2[FileLocationKind2["Absolute"] = 2] = "Absolute";
  FileLocationKind2[FileLocationKind2["AutoDetect"] = 3] = "AutoDetect";
  FileLocationKind2[FileLocationKind2["Search"] = 4] = "Search";
})(FileLocationKind || (FileLocationKind = {}));
(function(FileLocationKind2) {
  function fromString(value) {
    value = value.toLowerCase();
    if (value === "absolute") {
      return FileLocationKind2.Absolute;
    } else if (value === "relative") {
      return FileLocationKind2.Relative;
    } else if (value === "autodetect") {
      return FileLocationKind2.AutoDetect;
    } else if (value === "search") {
      return FileLocationKind2.Search;
    } else {
      return void 0;
    }
  }
  FileLocationKind2.fromString = fromString;
})(FileLocationKind || (FileLocationKind = {}));
var ProblemLocationKind;
(function(ProblemLocationKind2) {
  ProblemLocationKind2[ProblemLocationKind2["File"] = 0] = "File";
  ProblemLocationKind2[ProblemLocationKind2["Location"] = 1] = "Location";
})(ProblemLocationKind || (ProblemLocationKind = {}));
(function(ProblemLocationKind2) {
  function fromString(value) {
    value = value.toLowerCase();
    if (value === "file") {
      return ProblemLocationKind2.File;
    } else if (value === "location") {
      return ProblemLocationKind2.Location;
    } else {
      return void 0;
    }
  }
  ProblemLocationKind2.fromString = fromString;
})(ProblemLocationKind || (ProblemLocationKind = {}));
var ApplyToKind;
(function(ApplyToKind2) {
  ApplyToKind2[ApplyToKind2["allDocuments"] = 0] = "allDocuments";
  ApplyToKind2[ApplyToKind2["openDocuments"] = 1] = "openDocuments";
  ApplyToKind2[ApplyToKind2["closedDocuments"] = 2] = "closedDocuments";
})(ApplyToKind || (ApplyToKind = {}));
(function(ApplyToKind2) {
  function fromString(value) {
    value = value.toLowerCase();
    if (value === "alldocuments") {
      return ApplyToKind2.allDocuments;
    } else if (value === "opendocuments") {
      return ApplyToKind2.openDocuments;
    } else if (value === "closeddocuments") {
      return ApplyToKind2.closedDocuments;
    } else {
      return void 0;
    }
  }
  ApplyToKind2.fromString = fromString;
})(ApplyToKind || (ApplyToKind = {}));
function $5P(value) {
  return value && $zg(value.name) ? true : false;
}
async function $6P(filename, matcher, fileService) {
  const kind = matcher.fileLocation;
  let fullPath;
  if (kind === FileLocationKind.Absolute) {
    fullPath = filename;
  } else if (kind === FileLocationKind.Relative && matcher.filePrefix && $zg(matcher.filePrefix)) {
    fullPath = $nc(matcher.filePrefix, filename);
  } else if (kind === FileLocationKind.AutoDetect) {
    const matcherClone = $Lv(matcher);
    matcherClone.fileLocation = FileLocationKind.Relative;
    if (fileService) {
      const relative = await $6P(filename, matcherClone);
      let stat = void 0;
      try {
        stat = await fileService.stat(relative);
      } catch (ex) {
      }
      if (stat) {
        return relative;
      }
    }
    matcherClone.fileLocation = FileLocationKind.Absolute;
    return $6P(filename, matcherClone);
  } else if (kind === FileLocationKind.Search && fileService) {
    const fsProvider = fileService.getProvider(Schemas.file);
    if (fsProvider) {
      const uri = await searchForFileLocation(filename, fsProvider, matcher.filePrefix);
      fullPath = uri?.path;
    }
    if (!fullPath) {
      const absoluteMatcher = $Lv(matcher);
      absoluteMatcher.fileLocation = FileLocationKind.Absolute;
      return $6P(filename, absoluteMatcher);
    }
  }
  if (fullPath === void 0) {
    throw new Error("FileLocationKind is not actionable. Does the matcher have a filePrefix? This should never happen.");
  }
  fullPath = $lc(fullPath);
  fullPath = fullPath.replace(/\\/g, "/");
  if (fullPath[0] !== "/") {
    fullPath = "/" + fullPath;
  }
  if (matcher.uriProvider !== void 0) {
    return matcher.uriProvider(fullPath);
  } else {
    return URI.file(fullPath);
  }
}
async function searchForFileLocation(filename, fsProvider, args2) {
  const exclusions = new Set($5b(args2.exclude || []).map((x) => URI.file(x).path));
  async function search2(dir) {
    if (exclusions.has(dir.path)) {
      return void 0;
    }
    const entries2 = await fsProvider.readdir(dir);
    const subdirs = [];
    for (const [name, fileType] of entries2) {
      if (fileType === FileType.Directory) {
        subdirs.push(URI.joinPath(dir, name));
        continue;
      }
      if (fileType === FileType.File) {
        const fullUri = URI.joinPath(dir, name);
        if (fullUri.path.endsWith(filename)) {
          return fullUri;
        }
      }
    }
    for (const subdir of subdirs) {
      const result = await search2(subdir);
      if (result) {
        return result;
      }
    }
    return void 0;
  }
  for (const dir of $5b(args2.include || [])) {
    const hit = await search2(URI.file(dir));
    if (hit) {
      return hit;
    }
  }
  return void 0;
}
function $7P(matcher, fileService) {
  const pattern = matcher.pattern;
  if (Array.isArray(pattern)) {
    return new MultiLineMatcher(matcher, fileService);
  } else {
    return new SingleLineMatcher(matcher, fileService);
  }
}
var endOfLine = OS === 1 ? "\r\n" : "\n";
var AbstractLineMatcher = class {
  constructor(matcher, fileService) {
    this.a = matcher;
    this.b = fileService;
  }
  handle(lines, start = 0) {
    return { match: null, continue: false };
  }
  next(line) {
    return null;
  }
  c(data, pattern, matches) {
    if (data) {
      this.e(data, "file", pattern, matches, true);
      this.d(data, "message", pattern, matches, true);
      this.e(data, "code", pattern, matches, true);
      this.e(data, "severity", pattern, matches, true);
      this.e(data, "location", pattern, matches, true);
      this.e(data, "line", pattern, matches);
      this.e(data, "character", pattern, matches);
      this.e(data, "endLine", pattern, matches);
      this.e(data, "endCharacter", pattern, matches);
      return true;
    } else {
      return false;
    }
  }
  d(data, property, pattern, matches, trim = false) {
    const patternProperty = pattern[property];
    if ($Gg(data[property])) {
      this.e(data, property, pattern, matches, trim);
    } else if (!$Gg(patternProperty) && patternProperty < matches.length) {
      let value = matches[patternProperty];
      if (trim) {
        value = $Ef(value);
      }
      data[property] += endOfLine + value;
    }
  }
  e(data, property, pattern, matches, trim = false) {
    const patternAtProperty = pattern[property];
    if ($Gg(data[property]) && !$Gg(patternAtProperty) && patternAtProperty < matches.length) {
      let value = matches[patternAtProperty];
      if (value !== void 0) {
        if (trim) {
          value = $Ef(value);
        }
        data[property] = value;
      }
    }
  }
  f(data) {
    try {
      const location3 = this.h(data);
      if (data.file && location3 && data.message) {
        const marker = {
          severity: this.l(data),
          startLineNumber: location3.startLineNumber,
          startColumn: location3.startCharacter,
          endLineNumber: location3.endLineNumber,
          endColumn: location3.endCharacter,
          message: data.message
        };
        if (data.code !== void 0) {
          marker.code = data.code;
        }
        if (this.a.source !== void 0) {
          marker.source = this.a.source;
        }
        return {
          description: this.a,
          resource: this.g(data.file),
          marker
        };
      }
    } catch (err) {
      console.error(`Failed to convert problem data into match: ${JSON.stringify(data)}`);
    }
    return void 0;
  }
  g(filename) {
    return $6P(filename, this.a, this.b);
  }
  h(data) {
    if (data.kind === ProblemLocationKind.File) {
      return this.k(0, 0, 0, 0);
    }
    if (data.location) {
      return this.j(data.location);
    }
    if (!data.line) {
      return null;
    }
    const startLine = parseInt(data.line);
    const startColumn = data.character ? parseInt(data.character) : void 0;
    const endLine = data.endLine ? parseInt(data.endLine) : void 0;
    const endColumn = data.endCharacter ? parseInt(data.endCharacter) : void 0;
    return this.k(startLine, startColumn, endLine, endColumn);
  }
  j(value) {
    if (!value || !value.match(/(\d+|\d+,\d+|\d+,\d+,\d+,\d+)/)) {
      return null;
    }
    const parts = value.split(",");
    const startLine = parseInt(parts[0]);
    const startColumn = parts.length > 1 ? parseInt(parts[1]) : void 0;
    if (parts.length > 3) {
      return this.k(startLine, startColumn, parseInt(parts[2]), parseInt(parts[3]));
    } else {
      return this.k(startLine, startColumn, void 0, void 0);
    }
  }
  k(startLine, startColumn, endLine, endColumn) {
    if (startColumn !== void 0 && endColumn !== void 0) {
      return { startLineNumber: startLine, startCharacter: startColumn, endLineNumber: endLine || startLine, endCharacter: endColumn };
    }
    if (startColumn !== void 0) {
      return { startLineNumber: startLine, startCharacter: startColumn, endLineNumber: startLine, endCharacter: startColumn };
    }
    return { startLineNumber: startLine, startCharacter: 1, endLineNumber: startLine, endCharacter: 2 ** 31 - 1 };
  }
  l(data) {
    let result = null;
    if (data.severity) {
      const value = data.severity;
      if (value) {
        result = severity_default.fromValue(value);
        if (result === severity_default.Ignore) {
          if (value === "E") {
            result = severity_default.Error;
          } else if (value === "W") {
            result = severity_default.Warning;
          } else if (value === "I") {
            result = severity_default.Info;
          } else if ($1f(value, "hint")) {
            result = severity_default.Info;
          } else if ($1f(value, "note")) {
            result = severity_default.Info;
          }
        }
      }
    }
    if (result === null || result === severity_default.Ignore) {
      result = this.a.severity || severity_default.Error;
    }
    return MarkerSeverity.fromSeverity(result);
  }
};
var SingleLineMatcher = class extends AbstractLineMatcher {
  constructor(matcher, fileService) {
    super(matcher, fileService);
    this.m = matcher.pattern;
  }
  get matchLength() {
    return 1;
  }
  handle(lines, start = 0) {
    ok(lines.length - start === 1);
    const data = /* @__PURE__ */ Object.create(null);
    if (this.m.kind !== void 0) {
      data.kind = this.m.kind;
    }
    const matches = this.m.regexp.exec(lines[start]);
    if (matches) {
      this.c(data, this.m, matches);
      const match = this.f(data);
      if (match) {
        return { match, continue: false };
      }
    }
    return { match: null, continue: false };
  }
  next(line) {
    return null;
  }
};
var MultiLineMatcher = class extends AbstractLineMatcher {
  constructor(matcher, fileService) {
    super(matcher, fileService);
    this.m = matcher.pattern;
  }
  get matchLength() {
    return this.m.length;
  }
  handle(lines, start = 0) {
    ok(lines.length - start === this.m.length);
    this.n = /* @__PURE__ */ Object.create(null);
    let data = this.n;
    data.kind = this.m[0].kind;
    for (let i2 = 0; i2 < this.m.length; i2++) {
      const pattern = this.m[i2];
      const matches = pattern.regexp.exec(lines[i2 + start]);
      if (!matches) {
        return { match: null, continue: false };
      } else {
        if (pattern.loop && i2 === this.m.length - 1) {
          data = $Lv(data);
        }
        this.c(data, pattern, matches);
      }
    }
    const loop = !!this.m[this.m.length - 1].loop;
    if (!loop) {
      this.n = void 0;
    }
    const markerMatch = data ? this.f(data) : null;
    return { match: markerMatch ? markerMatch : null, continue: loop };
  }
  next(line) {
    const pattern = this.m[this.m.length - 1];
    ok(pattern.loop === true && this.n !== null);
    const matches = pattern.regexp.exec(line);
    if (!matches) {
      this.n = void 0;
      return null;
    }
    const data = $Lv(this.n);
    let problemMatch;
    if (this.c(data, pattern, matches)) {
      problemMatch = this.f(data);
    }
    return problemMatch ? problemMatch : null;
  }
};
var Config;
(function(Config2) {
  let CheckedProblemPattern;
  (function(CheckedProblemPattern2) {
    function is(value) {
      const candidate = value;
      return candidate && $zg(candidate.regexp);
    }
    CheckedProblemPattern2.is = is;
  })(CheckedProblemPattern = Config2.CheckedProblemPattern || (Config2.CheckedProblemPattern = {}));
  let NamedProblemPattern;
  (function(NamedProblemPattern2) {
    function is(value) {
      const candidate = value;
      return candidate && $zg(candidate.name);
    }
    NamedProblemPattern2.is = is;
  })(NamedProblemPattern = Config2.NamedProblemPattern || (Config2.NamedProblemPattern = {}));
  let NamedCheckedProblemPattern;
  (function(NamedCheckedProblemPattern2) {
    function is(value) {
      const candidate = value;
      return candidate && NamedProblemPattern.is(candidate) && $zg(candidate.regexp);
    }
    NamedCheckedProblemPattern2.is = is;
  })(NamedCheckedProblemPattern = Config2.NamedCheckedProblemPattern || (Config2.NamedCheckedProblemPattern = {}));
  let MultiLineProblemPattern;
  (function(MultiLineProblemPattern2) {
    function is(value) {
      return value && Array.isArray(value);
    }
    MultiLineProblemPattern2.is = is;
  })(MultiLineProblemPattern = Config2.MultiLineProblemPattern || (Config2.MultiLineProblemPattern = {}));
  let MultiLineCheckedProblemPattern;
  (function(MultiLineCheckedProblemPattern2) {
    function is(value) {
      if (!MultiLineProblemPattern.is(value)) {
        return false;
      }
      for (const element of value) {
        if (!Config2.CheckedProblemPattern.is(element)) {
          return false;
        }
      }
      return true;
    }
    MultiLineCheckedProblemPattern2.is = is;
  })(MultiLineCheckedProblemPattern = Config2.MultiLineCheckedProblemPattern || (Config2.MultiLineCheckedProblemPattern = {}));
  let NamedMultiLineCheckedProblemPattern;
  (function(NamedMultiLineCheckedProblemPattern2) {
    function is(value) {
      const candidate = value;
      return candidate && $zg(candidate.name) && Array.isArray(candidate.patterns) && MultiLineCheckedProblemPattern.is(candidate.patterns);
    }
    NamedMultiLineCheckedProblemPattern2.is = is;
  })(NamedMultiLineCheckedProblemPattern = Config2.NamedMultiLineCheckedProblemPattern || (Config2.NamedMultiLineCheckedProblemPattern = {}));
  function isNamedProblemMatcher(value) {
    return $zg(value.name);
  }
  Config2.isNamedProblemMatcher = isNamedProblemMatcher;
})(Config || (Config = {}));
var $8P = class extends $4P {
  constructor(logger2) {
    super(logger2);
  }
  parse(value) {
    if (Config.NamedMultiLineCheckedProblemPattern.is(value)) {
      return this.c(value);
    } else if (Config.MultiLineCheckedProblemPattern.is(value)) {
      return this.d(value);
    } else if (Config.NamedCheckedProblemPattern.is(value)) {
      const result = this.b(value);
      result.name = value.name;
      return result;
    } else if (Config.CheckedProblemPattern.is(value)) {
      return this.b(value);
    } else {
      this.error(localize(10263, null));
      return null;
    }
  }
  b(value) {
    const result = this.e(value, true);
    if (result === void 0) {
      return null;
    } else if (result.kind === void 0) {
      result.kind = ProblemLocationKind.Location;
    }
    return this.f([result]) ? result : null;
  }
  c(value) {
    const validPatterns = this.d(value.patterns);
    if (!validPatterns) {
      return null;
    }
    const result = {
      name: value.name,
      label: value.label ? value.label : value.name,
      patterns: validPatterns
    };
    return result;
  }
  d(values) {
    const result = [];
    for (let i2 = 0; i2 < values.length; i2++) {
      const pattern = this.e(values[i2], false);
      if (pattern === void 0) {
        return null;
      }
      if (i2 < values.length - 1) {
        if (!$Gg(pattern.loop) && pattern.loop) {
          pattern.loop = false;
          this.error(localize(10264, null));
        }
      }
      result.push(pattern);
    }
    if (result[0].kind === void 0) {
      result[0].kind = ProblemLocationKind.Location;
    }
    return this.f(result) ? result : null;
  }
  e(value, setDefaults) {
    const regexp = this.g(value.regexp);
    if (regexp === void 0) {
      return void 0;
    }
    let result = { regexp };
    if (value.kind) {
      result.kind = ProblemLocationKind.fromString(value.kind);
    }
    function copyProperty(result2, source, resultKey, sourceKey) {
      const value2 = source[sourceKey];
      if (typeof value2 === "number") {
        result2[resultKey] = value2;
      }
    }
    copyProperty(result, value, "file", "file");
    copyProperty(result, value, "location", "location");
    copyProperty(result, value, "line", "line");
    copyProperty(result, value, "character", "column");
    copyProperty(result, value, "endLine", "endLine");
    copyProperty(result, value, "endCharacter", "endColumn");
    copyProperty(result, value, "severity", "severity");
    copyProperty(result, value, "code", "code");
    copyProperty(result, value, "message", "message");
    if (value.loop === true || value.loop === false) {
      result.loop = value.loop;
    }
    if (setDefaults) {
      if (result.location || result.kind === ProblemLocationKind.File) {
        const defaultValue = {
          file: 1,
          message: 0
        };
        result = $Ov(result, defaultValue, false);
      } else {
        const defaultValue = {
          file: 1,
          line: 2,
          character: 3,
          message: 0
        };
        result = $Ov(result, defaultValue, false);
      }
    }
    return result;
  }
  f(values) {
    let file = false, message = false, location3 = false, line = false;
    const locationKind = values[0].kind === void 0 ? ProblemLocationKind.Location : values[0].kind;
    values.forEach((pattern, i2) => {
      if (i2 !== 0 && pattern.kind) {
        this.error(localize(10265, null));
      }
      file = file || !$Gg(pattern.file);
      message = message || !$Gg(pattern.message);
      location3 = location3 || !$Gg(pattern.location);
      line = line || !$Gg(pattern.line);
    });
    if (!(file && message)) {
      this.error(localize(10266, null));
      return false;
    }
    if (locationKind === ProblemLocationKind.Location && !(location3 || line)) {
      this.error(localize(10267, null));
      return false;
    }
    return true;
  }
  g(value) {
    let result;
    try {
      result = new RegExp(value);
    } catch (err) {
      this.error(localize(10268, null, value));
    }
    return result;
  }
};
var $9P = class {
  constructor(a, b = new $3P()) {
    this.a = a;
    this.b = b;
  }
  info(message) {
    this.b.state = 1;
    this.a.info(message);
  }
  warn(message) {
    this.b.state = 2;
    this.a.warn(message);
  }
  error(message) {
    this.b.state = 3;
    this.a.error(message);
  }
  fatal(message) {
    this.b.state = 4;
    this.a.error(message);
  }
  get status() {
    return this.b;
  }
};
var Schemas2;
(function(Schemas3) {
  Schemas3.ProblemPattern = {
    default: {
      regexp: "^([^\\\\s].*)\\\\((\\\\d+,\\\\d+)\\\\):\\\\s*(.*)$",
      file: 1,
      location: 2,
      message: 3
    },
    type: "object",
    additionalProperties: false,
    properties: {
      regexp: {
        type: "string",
        description: localize(10269, null)
      },
      kind: {
        type: "string",
        description: localize(10270, null)
      },
      file: {
        type: "integer",
        description: localize(10271, null)
      },
      location: {
        type: "integer",
        description: localize(10272, null)
      },
      line: {
        type: "integer",
        description: localize(10273, null)
      },
      column: {
        type: "integer",
        description: localize(10274, null)
      },
      endLine: {
        type: "integer",
        description: localize(10275, null)
      },
      endColumn: {
        type: "integer",
        description: localize(10276, null)
      },
      severity: {
        type: "integer",
        description: localize(10277, null)
      },
      code: {
        type: "integer",
        description: localize(10278, null)
      },
      message: {
        type: "integer",
        description: localize(10279, null)
      },
      loop: {
        type: "boolean",
        description: localize(10280, null)
      }
    }
  };
  Schemas3.NamedProblemPattern = $Lv(Schemas3.ProblemPattern);
  Schemas3.NamedProblemPattern.properties = $Lv(Schemas3.NamedProblemPattern.properties) || {};
  Schemas3.NamedProblemPattern.properties["name"] = {
    type: "string",
    description: localize(10281, null)
  };
  Schemas3.MultiLineProblemPattern = {
    type: "array",
    items: Schemas3.ProblemPattern
  };
  Schemas3.NamedMultiLineProblemPattern = {
    type: "object",
    additionalProperties: false,
    properties: {
      name: {
        type: "string",
        description: localize(10282, null)
      },
      patterns: {
        type: "array",
        description: localize(10283, null),
        items: Schemas3.ProblemPattern
      }
    }
  };
  Schemas3.WatchingPattern = {
    type: "object",
    additionalProperties: false,
    properties: {
      regexp: {
        type: "string",
        description: localize(10284, null)
      },
      file: {
        type: "integer",
        description: localize(10285, null)
      }
    }
  };
  Schemas3.PatternType = {
    anyOf: [
      {
        type: "string",
        description: localize(10286, null)
      },
      Schemas3.ProblemPattern,
      Schemas3.MultiLineProblemPattern
    ],
    description: localize(10287, null)
  };
  Schemas3.ProblemMatcher = {
    type: "object",
    additionalProperties: false,
    properties: {
      base: {
        type: "string",
        description: localize(10288, null)
      },
      owner: {
        type: "string",
        description: localize(10289, null)
      },
      source: {
        type: "string",
        description: localize(10290, null)
      },
      severity: {
        type: "string",
        enum: ["error", "warning", "info"],
        description: localize(10291, null)
      },
      applyTo: {
        type: "string",
        enum: ["allDocuments", "openDocuments", "closedDocuments"],
        description: localize(10292, null)
      },
      pattern: Schemas3.PatternType,
      fileLocation: {
        oneOf: [
          {
            type: "string",
            enum: ["absolute", "relative", "autoDetect", "search"]
          },
          {
            type: "array",
            prefixItems: [
              {
                type: "string",
                enum: ["absolute", "relative", "autoDetect", "search"]
              }
            ],
            minItems: 1,
            maxItems: 1,
            additionalItems: false
          },
          {
            type: "array",
            prefixItems: [
              { type: "string", enum: ["relative", "autoDetect"] },
              { type: "string" }
            ],
            minItems: 2,
            maxItems: 2,
            additionalItems: false,
            examples: [
              ["relative", "${workspaceFolder}"],
              ["autoDetect", "${workspaceFolder}"]
            ]
          },
          {
            type: "array",
            prefixItems: [
              { type: "string", enum: ["search"] },
              {
                type: "object",
                properties: {
                  "include": {
                    oneOf: [
                      { type: "string" },
                      { type: "array", items: { type: "string" } }
                    ]
                  },
                  "exclude": {
                    oneOf: [
                      { type: "string" },
                      { type: "array", items: { type: "string" } }
                    ]
                  }
                },
                required: ["include"]
              }
            ],
            minItems: 2,
            maxItems: 2,
            additionalItems: false,
            examples: [
              ["search", { "include": ["${workspaceFolder}"] }],
              ["search", { "include": ["${workspaceFolder}"], "exclude": [] }]
            ]
          }
        ],
        description: localize(10293, null)
      },
      background: {
        type: "object",
        additionalProperties: false,
        description: localize(10294, null),
        properties: {
          activeOnStart: {
            type: "boolean",
            description: localize(10295, null)
          },
          beginsPattern: {
            oneOf: [
              {
                type: "string"
              },
              Schemas3.WatchingPattern
            ],
            description: localize(10296, null)
          },
          endsPattern: {
            oneOf: [
              {
                type: "string"
              },
              Schemas3.WatchingPattern
            ],
            description: localize(10297, null)
          }
        }
      },
      watching: {
        type: "object",
        additionalProperties: false,
        deprecationMessage: localize(10298, null),
        description: localize(10299, null),
        properties: {
          activeOnStart: {
            type: "boolean",
            description: localize(10300, null)
          },
          beginsPattern: {
            oneOf: [
              {
                type: "string"
              },
              Schemas3.WatchingPattern
            ],
            description: localize(10301, null)
          },
          endsPattern: {
            oneOf: [
              {
                type: "string"
              },
              Schemas3.WatchingPattern
            ],
            description: localize(10302, null)
          }
        }
      }
    }
  };
  Schemas3.LegacyProblemMatcher = $Lv(Schemas3.ProblemMatcher);
  Schemas3.LegacyProblemMatcher.properties = $Lv(Schemas3.LegacyProblemMatcher.properties) || {};
  Schemas3.LegacyProblemMatcher.properties["watchedTaskBeginsRegExp"] = {
    type: "string",
    deprecationMessage: localize(10303, null),
    description: localize(10304, null)
  };
  Schemas3.LegacyProblemMatcher.properties["watchedTaskEndsRegExp"] = {
    type: "string",
    deprecationMessage: localize(10305, null),
    description: localize(10306, null)
  };
  Schemas3.NamedProblemMatcher = $Lv(Schemas3.ProblemMatcher);
  Schemas3.NamedProblemMatcher.properties = $Lv(Schemas3.NamedProblemMatcher.properties) || {};
  Schemas3.NamedProblemMatcher.properties.name = {
    type: "string",
    description: localize(10307, null)
  };
  Schemas3.NamedProblemMatcher.properties.label = {
    type: "string",
    description: localize(10308, null)
  };
})(Schemas2 || (Schemas2 = {}));
var problemPatternExtPoint = $tN.registerExtensionPoint({
  extensionPoint: "problemPatterns",
  jsonSchema: {
    description: localize(10309, null),
    type: "array",
    items: {
      anyOf: [
        Schemas2.NamedProblemPattern,
        Schemas2.NamedMultiLineProblemPattern
      ]
    }
  }
});
var ProblemPatternRegistryImpl = class {
  constructor() {
    this.a = /* @__PURE__ */ Object.create(null);
    this.c();
    this.b = new Promise((resolve, reject) => {
      problemPatternExtPoint.setHandler((extensions, delta) => {
        try {
          delta.removed.forEach((extension) => {
            const problemPatterns = extension.value;
            for (const pattern of problemPatterns) {
              if (this.a[pattern.name]) {
                delete this.a[pattern.name];
              }
            }
          });
          delta.added.forEach((extension) => {
            const problemPatterns = extension.value;
            const parser2 = new $8P(new $9P(extension.collector));
            for (const pattern of problemPatterns) {
              if (Config.NamedMultiLineCheckedProblemPattern.is(pattern)) {
                const result = parser2.parse(pattern);
                if (parser2.problemReporter.status.state < 3) {
                  this.add(result.name, result.patterns);
                } else {
                  extension.collector.error(localize(10310, null));
                  extension.collector.error(JSON.stringify(pattern, void 0, 4));
                }
              } else if (Config.NamedProblemPattern.is(pattern)) {
                const result = parser2.parse(pattern);
                if (parser2.problemReporter.status.state < 3) {
                  this.add(pattern.name, result);
                } else {
                  extension.collector.error(localize(10311, null));
                  extension.collector.error(JSON.stringify(pattern, void 0, 4));
                }
              }
              parser2.reset();
            }
          });
        } catch (error) {
        }
        resolve(void 0);
      });
    });
  }
  onReady() {
    return this.b;
  }
  add(key2, value) {
    this.a[key2] = value;
  }
  get(key2) {
    return this.a[key2];
  }
  c() {
    this.add("msCompile", {
      regexp: /^(?:\s*\d+>)?(\S.*)\((\d+|\d+,\d+|\d+,\d+,\d+,\d+)\)\s*:\s+((?:fatal +)?error|warning|info)\s+(\w+\d+)\s*:\s*(.*)$/,
      kind: ProblemLocationKind.Location,
      file: 1,
      location: 2,
      severity: 3,
      code: 4,
      message: 5
    });
    this.add("gulp-tsc", {
      regexp: /^([^\s].*)\((\d+|\d+,\d+|\d+,\d+,\d+,\d+)\):\s+(\d+)\s+(.*)$/,
      kind: ProblemLocationKind.Location,
      file: 1,
      location: 2,
      code: 3,
      message: 4
    });
    this.add("cpp", {
      regexp: /^(\S.*)\((\d+|\d+,\d+|\d+,\d+,\d+,\d+)\):\s+(error|warning|info)\s+(C\d+)\s*:\s*(.*)$/,
      kind: ProblemLocationKind.Location,
      file: 1,
      location: 2,
      severity: 3,
      code: 4,
      message: 5
    });
    this.add("csc", {
      regexp: /^(\S.*)\((\d+|\d+,\d+|\d+,\d+,\d+,\d+)\):\s+(error|warning|info)\s+(CS\d+)\s*:\s*(.*)$/,
      kind: ProblemLocationKind.Location,
      file: 1,
      location: 2,
      severity: 3,
      code: 4,
      message: 5
    });
    this.add("vb", {
      regexp: /^(\S.*)\((\d+|\d+,\d+|\d+,\d+,\d+,\d+)\):\s+(error|warning|info)\s+(BC\d+)\s*:\s*(.*)$/,
      kind: ProblemLocationKind.Location,
      file: 1,
      location: 2,
      severity: 3,
      code: 4,
      message: 5
    });
    this.add("lessCompile", {
      regexp: /^\s*(.*) in file (.*) line no. (\d+)$/,
      kind: ProblemLocationKind.Location,
      message: 1,
      file: 2,
      line: 3
    });
    this.add("jshint", {
      regexp: /^(.*):\s+line\s+(\d+),\s+col\s+(\d+),\s(.+?)(?:\s+\((\w)(\d+)\))?$/,
      kind: ProblemLocationKind.Location,
      file: 1,
      line: 2,
      character: 3,
      message: 4,
      severity: 5,
      code: 6
    });
    this.add("jshint-stylish", [
      {
        regexp: /^(.+)$/,
        kind: ProblemLocationKind.Location,
        file: 1
      },
      {
        regexp: /^\s+line\s+(\d+)\s+col\s+(\d+)\s+(.+?)(?:\s+\((\w)(\d+)\))?$/,
        line: 1,
        character: 2,
        message: 3,
        severity: 4,
        code: 5,
        loop: true
      }
    ]);
    this.add("eslint-compact", {
      regexp: /^(.+):\sline\s(\d+),\scol\s(\d+),\s(Error|Warning|Info)\s-\s(.+)\s\((.+)\)$/,
      file: 1,
      kind: ProblemLocationKind.Location,
      line: 2,
      character: 3,
      severity: 4,
      message: 5,
      code: 6
    });
    this.add("eslint-stylish", [
      {
        regexp: /^((?:[a-zA-Z]:)*[./\\]+.*?)$/,
        kind: ProblemLocationKind.Location,
        file: 1
      },
      {
        regexp: /^\s+(\d+):(\d+)\s+(error|warning|info)\s+(.+?)(?:\s\s+(.*))?$/,
        line: 1,
        character: 2,
        severity: 3,
        message: 4,
        code: 5,
        loop: true
      }
    ]);
    this.add("go", {
      regexp: /^([^:]*: )?((.:)?[^:]*):(\d+)(:(\d+))?: (.*)$/,
      kind: ProblemLocationKind.Location,
      file: 2,
      line: 4,
      character: 6,
      message: 7
    });
  }
};
var $0P = new ProblemPatternRegistryImpl();
var $$P = class extends $4P {
  constructor(logger2) {
    super(logger2);
  }
  parse(json) {
    const result = this.c(json);
    if (!this.b(json, result)) {
      return void 0;
    }
    this.e(json, result);
    return result;
  }
  b(externalProblemMatcher, problemMatcher) {
    if (!problemMatcher) {
      this.error(localize(10312, null, JSON.stringify(externalProblemMatcher, null, 4)));
      return false;
    }
    if (!problemMatcher.pattern) {
      this.error(localize(10313, null, JSON.stringify(externalProblemMatcher, null, 4)));
      return false;
    }
    if (!problemMatcher.owner) {
      this.error(localize(10314, null, JSON.stringify(externalProblemMatcher, null, 4)));
      return false;
    }
    if ($Gg(problemMatcher.fileLocation)) {
      this.error(localize(10315, null, JSON.stringify(externalProblemMatcher, null, 4)));
      return false;
    }
    return true;
  }
  c(description) {
    let result = null;
    const owner = $zg(description.owner) ? description.owner : $ps();
    const source = $zg(description.source) ? description.source : void 0;
    let applyTo = $zg(description.applyTo) ? ApplyToKind.fromString(description.applyTo) : ApplyToKind.allDocuments;
    if (!applyTo) {
      applyTo = ApplyToKind.allDocuments;
    }
    let fileLocation = void 0;
    let filePrefix = void 0;
    let kind;
    if ($Gg(description.fileLocation)) {
      fileLocation = FileLocationKind.Relative;
      filePrefix = "${workspaceFolder}";
    } else if ($zg(description.fileLocation)) {
      kind = FileLocationKind.fromString(description.fileLocation);
      if (kind) {
        fileLocation = kind;
        if (kind === FileLocationKind.Relative || kind === FileLocationKind.AutoDetect) {
          filePrefix = "${workspaceFolder}";
        } else if (kind === FileLocationKind.Search) {
          filePrefix = { include: ["${workspaceFolder}"] };
        }
      }
    } else if ($Ag(description.fileLocation)) {
      const values = description.fileLocation;
      if (values.length > 0) {
        kind = FileLocationKind.fromString(values[0]);
        if (values.length === 1 && kind === FileLocationKind.Absolute) {
          fileLocation = kind;
        } else if (values.length === 2 && (kind === FileLocationKind.Relative || kind === FileLocationKind.AutoDetect) && values[1]) {
          fileLocation = kind;
          filePrefix = values[1];
        }
      }
    } else if (Array.isArray(description.fileLocation)) {
      const kind2 = FileLocationKind.fromString(description.fileLocation[0]);
      if (kind2 === FileLocationKind.Search) {
        fileLocation = FileLocationKind.Search;
        filePrefix = description.fileLocation[1] ?? { include: ["${workspaceFolder}"] };
      }
    }
    const pattern = description.pattern ? this.d(description.pattern) : void 0;
    let severity = description.severity ? severity_default.fromValue(description.severity) : void 0;
    if (severity === severity_default.Ignore) {
      this.info(localize(10316, null, description.severity));
      severity = severity_default.Error;
    }
    if ($zg(description.base)) {
      const variableName = description.base;
      if (variableName.length > 1 && variableName[0] === "$") {
        const base = $_P.get(variableName.substring(1));
        if (base) {
          result = $Lv(base);
          if (description.owner !== void 0 && owner !== void 0) {
            result.owner = owner;
          }
          if (description.source !== void 0 && source !== void 0) {
            result.source = source;
          }
          if (description.fileLocation !== void 0 && fileLocation !== void 0) {
            result.fileLocation = fileLocation;
            result.filePrefix = filePrefix;
          }
          if (description.pattern !== void 0 && pattern !== void 0 && pattern !== null) {
            result.pattern = pattern;
          }
          if (description.severity !== void 0 && severity !== void 0) {
            result.severity = severity;
          }
          if (description.applyTo !== void 0 && applyTo !== void 0) {
            result.applyTo = applyTo;
          }
        }
      }
    } else if (fileLocation && pattern) {
      result = {
        owner,
        applyTo,
        fileLocation,
        pattern
      };
      if (source) {
        result.source = source;
      }
      if (filePrefix) {
        result.filePrefix = filePrefix;
      }
      if (severity) {
        result.severity = severity;
      }
    }
    if (Config.isNamedProblemMatcher(description)) {
      result.name = description.name;
      result.label = $zg(description.label) ? description.label : description.name;
    }
    return result;
  }
  d(value) {
    if ($zg(value)) {
      const variableName = value;
      if (variableName.length > 1 && variableName[0] === "$") {
        const result = $0P.get(variableName.substring(1));
        if (!result) {
          this.error(localize(10317, null, variableName));
        }
        return result;
      } else {
        if (variableName.length === 0) {
          this.error(localize(10318, null));
        } else {
          this.error(localize(10319, null, variableName));
        }
      }
    } else if (value) {
      const problemPatternParser = new $8P(this.problemReporter);
      if (Array.isArray(value)) {
        return problemPatternParser.parse(value);
      } else {
        return problemPatternParser.parse(value);
      }
    }
    return null;
  }
  e(external, internal) {
    const oldBegins = this.g(external.watchedTaskBeginsRegExp);
    const oldEnds = this.g(external.watchedTaskEndsRegExp);
    if (oldBegins && oldEnds) {
      internal.watching = {
        activeOnStart: false,
        beginsPattern: { regexp: oldBegins },
        endsPattern: { regexp: oldEnds }
      };
      return;
    }
    const backgroundMonitor = external.background || external.watching;
    if ($Ig(backgroundMonitor)) {
      return;
    }
    const begins = this.f(backgroundMonitor.beginsPattern);
    const ends = this.f(backgroundMonitor.endsPattern);
    if (begins && ends) {
      internal.watching = {
        activeOnStart: $Fg(backgroundMonitor.activeOnStart) ? backgroundMonitor.activeOnStart : false,
        beginsPattern: begins,
        endsPattern: ends
      };
      return;
    }
    if (begins || ends) {
      this.error(localize(10320, null));
    }
  }
  f(external) {
    if ($Ig(external)) {
      return null;
    }
    let regexp;
    let file;
    if ($zg(external)) {
      regexp = this.g(external);
    } else {
      regexp = this.g(external.regexp);
      if ($Dg(external.file)) {
        file = external.file;
      }
    }
    if (!regexp) {
      return null;
    }
    return file ? { regexp, file } : { regexp, file: 1 };
  }
  g(value) {
    let result = null;
    if (!value) {
      return result;
    }
    try {
      result = new RegExp(value);
    } catch (err) {
      this.error(localize(10321, null, value));
    }
    return result;
  }
};
var problemMatchersExtPoint = $tN.registerExtensionPoint({
  extensionPoint: "problemMatchers",
  deps: [problemPatternExtPoint],
  jsonSchema: {
    description: localize(10322, null),
    type: "array",
    items: Schemas2.NamedProblemMatcher
  }
});
var ProblemMatcherRegistryImpl = class {
  constructor() {
    this.c = new $ze();
    this.onMatcherChanged = this.c.event;
    this.a = /* @__PURE__ */ Object.create(null);
    this.d();
    this.b = new Promise((resolve, reject) => {
      problemMatchersExtPoint.setHandler((extensions, delta) => {
        try {
          delta.removed.forEach((extension) => {
            const problemMatchers = extension.value;
            for (const matcher2 of problemMatchers) {
              if (this.a[matcher2.name]) {
                delete this.a[matcher2.name];
              }
            }
          });
          delta.added.forEach((extension) => {
            const problemMatchers = extension.value;
            const parser2 = new $$P(new $9P(extension.collector));
            for (const matcher2 of problemMatchers) {
              const result = parser2.parse(matcher2);
              if (result && $5P(result)) {
                this.add(result);
              }
            }
          });
          if (delta.removed.length > 0 || delta.added.length > 0) {
            this.c.fire();
          }
        } catch (error) {
        }
        const matcher = this.get("tsc-watch");
        if (matcher) {
          matcher.tscWatch = true;
        }
        resolve(void 0);
      });
    });
  }
  onReady() {
    $0P.onReady();
    return this.b;
  }
  add(matcher) {
    this.a[matcher.name] = matcher;
  }
  get(name) {
    return this.a[name];
  }
  keys() {
    return Object.keys(this.a);
  }
  d() {
    this.add({
      name: "msCompile",
      label: localize(10323, null),
      owner: "msCompile",
      source: "cpp",
      applyTo: ApplyToKind.allDocuments,
      fileLocation: FileLocationKind.Absolute,
      pattern: $0P.get("msCompile")
    });
    this.add({
      name: "lessCompile",
      label: localize(10324, null),
      deprecated: true,
      owner: "lessCompile",
      source: "less",
      applyTo: ApplyToKind.allDocuments,
      fileLocation: FileLocationKind.Absolute,
      pattern: $0P.get("lessCompile"),
      severity: severity_default.Error
    });
    this.add({
      name: "gulp-tsc",
      label: localize(10325, null),
      owner: "typescript",
      source: "ts",
      applyTo: ApplyToKind.closedDocuments,
      fileLocation: FileLocationKind.Relative,
      filePrefix: "${workspaceFolder}",
      pattern: $0P.get("gulp-tsc")
    });
    this.add({
      name: "jshint",
      label: localize(10326, null),
      owner: "jshint",
      source: "jshint",
      applyTo: ApplyToKind.allDocuments,
      fileLocation: FileLocationKind.Absolute,
      pattern: $0P.get("jshint")
    });
    this.add({
      name: "jshint-stylish",
      label: localize(10327, null),
      owner: "jshint",
      source: "jshint",
      applyTo: ApplyToKind.allDocuments,
      fileLocation: FileLocationKind.Absolute,
      pattern: $0P.get("jshint-stylish")
    });
    this.add({
      name: "eslint-compact",
      label: localize(10328, null),
      owner: "eslint",
      source: "eslint",
      applyTo: ApplyToKind.allDocuments,
      fileLocation: FileLocationKind.Absolute,
      filePrefix: "${workspaceFolder}",
      pattern: $0P.get("eslint-compact")
    });
    this.add({
      name: "eslint-stylish",
      label: localize(10329, null),
      owner: "eslint",
      source: "eslint",
      applyTo: ApplyToKind.allDocuments,
      fileLocation: FileLocationKind.Absolute,
      pattern: $0P.get("eslint-stylish")
    });
    this.add({
      name: "go",
      label: localize(10330, null),
      owner: "go",
      source: "go",
      applyTo: ApplyToKind.allDocuments,
      fileLocation: FileLocationKind.Relative,
      filePrefix: "${workspaceFolder}",
      pattern: $0P.get("go")
    });
  }
};
var $_P = new ProblemMatcherRegistryImpl();

// out-build/vs/workbench/contrib/tasks/browser/runAutomaticTasks.js
var ALLOW_AUTOMATIC_TASKS = "task.allowAutomaticTasks";
var $mhc = class $mhc2 extends $3c {
  constructor(b, c, f, g) {
    super();
    this.b = b;
    this.c = c;
    this.f = f;
    this.g = g;
    this.a = false;
    if (this.b.isReconnected) {
      this.h();
    } else {
      this.B(Event2.once(this.b.onDidReconnectToTasks)(async () => await this.h()));
    }
    this.B(this.f.onDidChangeTrust(async () => await this.h()));
  }
  async h() {
    if (!this.f.isWorkspaceTrusted()) {
      return;
    }
    if (this.a || this.c.getValue(ALLOW_AUTOMATIC_TASKS) === "off") {
      return;
    }
    this.a = true;
    this.g.trace("RunAutomaticTasks: Trying to run tasks.");
    if (!this.b.hasTaskSystemInfo) {
      this.g.trace("RunAutomaticTasks: Awaiting task system info.");
      await Event2.toPromise(Event2.once(this.b.onDidChangeTaskSystemInfo));
    }
    let workspaceTasks = await this.b.getWorkspaceTasks(
      2
      /* TaskRunSource.FolderOpen */
    );
    this.g.trace(`RunAutomaticTasks: Found ${workspaceTasks.size} automatic tasks`);
    let autoTasks = this.n(this.b, workspaceTasks);
    this.g.trace(`RunAutomaticTasks: taskNames=${JSON.stringify(autoTasks.taskNames)}`);
    if (autoTasks.taskNames.length === 0) {
      const updatedWithinTimeout = await Promise.race([
        new Promise((resolve) => {
          Event2.toPromise(Event2.once(this.b.onDidChangeTaskConfig)).then(() => resolve(true));
        }),
        new Promise((resolve) => {
          const timer = setTimeout(() => {
            clearTimeout(timer);
            resolve(false);
          }, 1e4);
        })
      ]);
      if (!updatedWithinTimeout) {
        this.g.trace(`RunAutomaticTasks: waited some extra time, but no update of tasks configuration`);
        return;
      }
      workspaceTasks = await this.b.getWorkspaceTasks(
        2
        /* TaskRunSource.FolderOpen */
      );
      autoTasks = this.n(this.b, workspaceTasks);
      this.g.trace(`RunAutomaticTasks: updated taskNames=${JSON.stringify(autoTasks.taskNames)}`);
    }
    this.r(this.b, this.c, autoTasks.tasks, autoTasks.taskNames);
  }
  j(taskService, tasks2) {
    tasks2.forEach((task) => {
      if (task instanceof Promise) {
        task.then((promiseResult) => {
          if (promiseResult) {
            taskService.run(promiseResult);
          }
        });
      } else {
        taskService.run(task);
      }
    });
  }
  m(source) {
    const taskKind = TaskSourceKind.toConfigurationTarget(source.kind);
    switch (taskKind) {
      case 6: {
        return $vh(source.config.workspaceFolder.uri, source.config.file);
      }
      case 5: {
        return source.config.workspace?.configuration ?? void 0;
      }
    }
    return void 0;
  }
  n(taskService, workspaceTaskResult) {
    const tasks2 = new Array();
    const taskNames = new Array();
    const locations = /* @__PURE__ */ new Map();
    if (workspaceTaskResult) {
      workspaceTaskResult.forEach((resultElement) => {
        if (resultElement.set) {
          resultElement.set.tasks.forEach((task) => {
            if (task.runOptions.runOn === RunOnOptions.folderOpen) {
              tasks2.push(task);
              taskNames.push(task._label);
              const location3 = this.m(task._source);
              if (location3) {
                locations.set(location3.fsPath, location3);
              }
            }
          });
        }
        if (resultElement.configurations) {
          for (const configuredTask of Object.values(resultElement.configurations.byIdentifier)) {
            if (configuredTask.runOptions.runOn === RunOnOptions.folderOpen) {
              tasks2.push(new Promise((resolve) => {
                taskService.getTask(resultElement.workspaceFolder, configuredTask._id, true).then((task) => resolve(task));
              }));
              if (configuredTask._label) {
                taskNames.push(configuredTask._label);
              } else {
                taskNames.push(configuredTask.configures.task);
              }
              const location3 = this.m(configuredTask._source);
              if (location3) {
                locations.set(location3.fsPath, location3);
              }
            }
          }
        }
      });
    }
    return { tasks: tasks2, taskNames, locations };
  }
  async r(taskService, configurationService, tasks2, taskNames) {
    if (taskNames.length === 0) {
      return;
    }
    if (configurationService.getValue(ALLOW_AUTOMATIC_TASKS) === "off") {
      return;
    }
    this.j(taskService, tasks2);
  }
};
$mhc = __decorate([
  __param(0, $3Sb),
  __param(1, $kl),
  __param(2, $4M),
  __param(3, $wn)
], $mhc);
var $nhc = class _$nhc extends $gJ {
  static {
    this.ID = "workbench.action.tasks.manageAutomaticRunning";
  }
  static {
    this.LABEL = localize(10038, null);
  }
  constructor() {
    super({
      id: _$nhc.ID,
      title: _$nhc.LABEL,
      category: $dQ
    });
  }
  async run(accessor) {
    const quickInputService = accessor.get($1M);
    const configurationService = accessor.get($kl);
    const allowItem = { label: localize(10039, null) };
    const disallowItem = { label: localize(10040, null) };
    const value = await quickInputService.pick([allowItem, disallowItem], { canPickMany: false });
    if (!value) {
      return;
    }
    configurationService.updateValue(
      ALLOW_AUTOMATIC_TASKS,
      value === allowItem ? "on" : "off",
      2
      /* ConfigurationTarget.USER */
    );
  }
};

// out-build/vs/workbench/contrib/tasks/common/jsonSchemaCommon.js
var schema5 = {
  definitions: {
    showOutputType: {
      type: "string",
      enum: ["always", "silent", "never"]
    },
    options: {
      type: "object",
      description: localize(10222, null),
      properties: {
        cwd: {
          type: "string",
          description: localize(10223, null)
        },
        env: {
          type: "object",
          additionalProperties: {
            type: "string"
          },
          description: localize(10224, null)
        }
      },
      additionalProperties: {
        type: ["string", "array", "object"]
      }
    },
    problemMatcherType: {
      oneOf: [
        {
          type: "string",
          errorMessage: localize(10225, null)
        },
        Schemas2.LegacyProblemMatcher,
        {
          type: "array",
          items: {
            anyOf: [
              {
                type: "string",
                errorMessage: localize(10226, null)
              },
              Schemas2.LegacyProblemMatcher
            ]
          }
        }
      ]
    },
    shellConfiguration: {
      type: "object",
      additionalProperties: false,
      description: localize(10227, null),
      properties: {
        executable: {
          type: "string",
          description: localize(10228, null)
        },
        args: {
          type: "array",
          description: localize(10229, null),
          items: {
            type: "string"
          }
        }
      }
    },
    commandConfiguration: {
      type: "object",
      additionalProperties: false,
      properties: {
        command: {
          type: "string",
          description: localize(10230, null)
        },
        args: {
          type: "array",
          description: localize(10231, null),
          items: {
            type: "string"
          }
        },
        options: {
          $ref: "#/definitions/options"
        }
      }
    },
    taskDescription: {
      type: "object",
      required: ["taskName"],
      additionalProperties: false,
      properties: {
        taskName: {
          type: "string",
          description: localize(10232, null)
        },
        command: {
          type: "string",
          description: localize(10233, null)
        },
        args: {
          type: "array",
          description: localize(10234, null),
          items: {
            type: "string"
          }
        },
        options: {
          $ref: "#/definitions/options"
        },
        windows: {
          anyOf: [
            {
              $ref: "#/definitions/commandConfiguration",
              description: localize(10235, null)
            },
            {
              properties: {
                problemMatcher: {
                  $ref: "#/definitions/problemMatcherType",
                  description: localize(10236, null)
                }
              }
            }
          ]
        },
        osx: {
          anyOf: [
            {
              $ref: "#/definitions/commandConfiguration",
              description: localize(10237, null)
            },
            {
              properties: {
                problemMatcher: {
                  $ref: "#/definitions/problemMatcherType",
                  description: localize(10238, null)
                }
              }
            }
          ]
        },
        linux: {
          anyOf: [
            {
              $ref: "#/definitions/commandConfiguration",
              description: localize(10239, null)
            },
            {
              properties: {
                problemMatcher: {
                  $ref: "#/definitions/problemMatcherType",
                  description: localize(10240, null)
                }
              }
            }
          ]
        },
        suppressTaskName: {
          type: "boolean",
          description: localize(10241, null),
          default: true
        },
        showOutput: {
          $ref: "#/definitions/showOutputType",
          description: localize(10242, null)
        },
        echoCommand: {
          type: "boolean",
          description: localize(10243, null),
          default: true
        },
        isWatching: {
          type: "boolean",
          deprecationMessage: localize(10244, null),
          description: localize(10245, null),
          default: true
        },
        isBackground: {
          type: "boolean",
          description: localize(10246, null),
          default: true
        },
        promptOnClose: {
          type: "boolean",
          description: localize(10247, null),
          default: false
        },
        isBuildCommand: {
          type: "boolean",
          description: localize(10248, null),
          default: true
        },
        isTestCommand: {
          type: "boolean",
          description: localize(10249, null),
          default: true
        },
        problemMatcher: {
          $ref: "#/definitions/problemMatcherType",
          description: localize(10250, null)
        }
      }
    },
    taskRunnerConfiguration: {
      type: "object",
      required: [],
      properties: {
        command: {
          type: "string",
          description: localize(10251, null)
        },
        args: {
          type: "array",
          description: localize(10252, null),
          items: {
            type: "string"
          }
        },
        options: {
          $ref: "#/definitions/options"
        },
        showOutput: {
          $ref: "#/definitions/showOutputType",
          description: localize(10253, null)
        },
        isWatching: {
          type: "boolean",
          deprecationMessage: localize(10254, null),
          description: localize(10255, null),
          default: true
        },
        isBackground: {
          type: "boolean",
          description: localize(10256, null),
          default: true
        },
        promptOnClose: {
          type: "boolean",
          description: localize(10257, null),
          default: false
        },
        echoCommand: {
          type: "boolean",
          description: localize(10258, null),
          default: true
        },
        suppressTaskName: {
          type: "boolean",
          description: localize(10259, null),
          default: true
        },
        taskSelector: {
          type: "string",
          description: localize(10260, null)
        },
        problemMatcher: {
          $ref: "#/definitions/problemMatcherType",
          description: localize(10261, null)
        },
        tasks: {
          type: "array",
          description: localize(10262, null),
          items: {
            type: "object",
            $ref: "#/definitions/taskDescription"
          }
        }
      }
    }
  }
};
var jsonSchemaCommon_default = schema5;

// out-build/vs/workbench/contrib/tasks/common/jsonSchema_v1.js
var schema6 = {
  oneOf: [
    {
      allOf: [
        {
          type: "object",
          required: ["version"],
          properties: {
            version: {
              type: "string",
              enum: ["0.1.0"],
              deprecationMessage: localize(10132, null),
              description: localize(10133, null)
            },
            _runner: {
              deprecationMessage: localize(10134, null)
            },
            runner: {
              type: "string",
              enum: ["process", "terminal"],
              default: "process",
              description: localize(10135, null)
            },
            windows: {
              $ref: "#/definitions/taskRunnerConfiguration",
              description: localize(10136, null)
            },
            osx: {
              $ref: "#/definitions/taskRunnerConfiguration",
              description: localize(10137, null)
            },
            linux: {
              $ref: "#/definitions/taskRunnerConfiguration",
              description: localize(10138, null)
            }
          }
        },
        {
          $ref: "#/definitions/taskRunnerConfiguration"
        }
      ]
    }
  ]
};
var shellCommand = {
  type: "boolean",
  default: true,
  description: localize(10139, null)
};
schema6.definitions = $Lv(jsonSchemaCommon_default.definitions);
var definitions = schema6.definitions;
definitions["commandConfiguration"]["properties"]["isShellCommand"] = $Lv(shellCommand);
definitions["taskDescription"]["properties"]["isShellCommand"] = $Lv(shellCommand);
definitions["taskRunnerConfiguration"]["properties"]["isShellCommand"] = $Lv(shellCommand);
Object.getOwnPropertyNames(definitions).forEach((key2) => {
  const newKey = key2 + "1";
  definitions[newKey] = definitions[key2];
  delete definitions[key2];
});
function fixReferences(literal) {
  if (Array.isArray(literal)) {
    literal.forEach(fixReferences);
  } else if (typeof literal === "object") {
    if (literal["$ref"]) {
      literal["$ref"] = literal["$ref"] + "1";
    }
    Object.getOwnPropertyNames(literal).forEach((property) => {
      const value = literal[property];
      if (Array.isArray(value) || typeof value === "object") {
        fixReferences(value);
      }
    });
  }
}
fixReferences(schema6);
$_P.onReady().then(() => {
  try {
    const matcherIds = $_P.keys().map((key2) => "$" + key2);
    definitions.problemMatcherType1.oneOf[0].enum = matcherIds;
    definitions.problemMatcherType1.oneOf[2].items.anyOf[1].enum = matcherIds;
  } catch (err) {
    console.log("Installing problem matcher ids failed");
  }
});
var jsonSchema_v1_default = schema6;

// out-build/vs/workbench/contrib/tasks/common/jsonSchema_v2.js
function fixReferences2(literal) {
  if (Array.isArray(literal)) {
    literal.forEach(fixReferences2);
  } else if (typeof literal === "object") {
    if (literal["$ref"]) {
      literal["$ref"] = literal["$ref"] + "2";
    }
    Object.getOwnPropertyNames(literal).forEach((property) => {
      const value = literal[property];
      if (Array.isArray(value) || typeof value === "object") {
        fixReferences2(value);
      }
    });
  }
}
var shellCommand2 = {
  anyOf: [
    {
      type: "boolean",
      default: true,
      description: localize(10140, null)
    },
    {
      $ref: "#/definitions/shellConfiguration"
    }
  ],
  deprecationMessage: localize(10141, null)
};
var hide = {
  type: "boolean",
  description: localize(10142, null),
  default: true
};
var taskIdentifier = {
  type: "object",
  additionalProperties: true,
  properties: {
    type: {
      type: "string",
      description: localize(10143, null)
    }
  }
};
var dependsOn = {
  anyOf: [
    {
      type: "string",
      description: localize(10144, null)
    },
    taskIdentifier,
    {
      type: "array",
      description: localize(10145, null),
      items: {
        anyOf: [
          {
            type: "string"
          },
          taskIdentifier
        ]
      }
    }
  ],
  description: localize(10146, null)
};
var dependsOrder = {
  type: "string",
  enum: ["parallel", "sequence"],
  enumDescriptions: [
    localize(10147, null),
    localize(10148, null)
  ],
  default: "parallel",
  description: localize(10149, null)
};
var detail = {
  type: "string",
  description: localize(10150, null)
};
var icon = {
  type: "object",
  description: localize(10151, null),
  properties: {
    id: {
      description: localize(10152, null),
      type: ["string", "null"],
      enum: Array.from($4l(), (icon2) => icon2.id),
      markdownEnumDescriptions: Array.from($4l(), (icon2) => `$(${icon2.id})`)
    },
    color: {
      description: localize(10153, null),
      type: ["string", "null"],
      enum: [
        "terminal.ansiBlack",
        "terminal.ansiRed",
        "terminal.ansiGreen",
        "terminal.ansiYellow",
        "terminal.ansiBlue",
        "terminal.ansiMagenta",
        "terminal.ansiCyan",
        "terminal.ansiWhite"
      ]
    }
  }
};
var presentation = {
  type: "object",
  default: {
    echo: true,
    reveal: "always",
    focus: false,
    panel: "shared",
    showReuseMessage: true,
    clear: false
  },
  description: localize(10154, null),
  additionalProperties: false,
  properties: {
    echo: {
      type: "boolean",
      default: true,
      description: localize(10155, null)
    },
    focus: {
      type: "boolean",
      default: false,
      description: localize(10156, null)
    },
    revealProblems: {
      type: "string",
      enum: ["always", "onProblem", "never"],
      enumDescriptions: [
        localize(10157, null),
        localize(10158, null),
        localize(10159, null)
      ],
      default: "never",
      description: localize(10160, null)
    },
    reveal: {
      type: "string",
      enum: ["always", "silent", "never"],
      enumDescriptions: [
        localize(10161, null),
        localize(10162, null),
        localize(10163, null)
      ],
      default: "always",
      description: localize(10164, null)
    },
    panel: {
      type: "string",
      enum: ["shared", "dedicated", "new"],
      default: "shared",
      description: localize(10165, null)
    },
    showReuseMessage: {
      type: "boolean",
      default: true,
      description: localize(10166, null)
    },
    clear: {
      type: "boolean",
      default: false,
      description: localize(10167, null)
    },
    group: {
      type: "string",
      description: localize(10168, null)
    },
    close: {
      type: "boolean",
      description: localize(10169, null)
    }
  }
};
var terminal = $Lv(presentation);
terminal.deprecationMessage = localize(10170, null);
var groupStrings = {
  type: "string",
  enum: [
    "build",
    "test",
    "none"
  ],
  enumDescriptions: [
    localize(10171, null),
    localize(10172, null),
    localize(10173, null)
  ],
  description: localize(10174, null)
};
var group = {
  oneOf: [
    groupStrings,
    {
      type: "object",
      properties: {
        kind: groupStrings,
        isDefault: {
          type: ["boolean", "string"],
          default: false,
          description: localize(10175, null)
        }
      }
    }
  ],
  defaultSnippets: [
    {
      body: { kind: "build", isDefault: true },
      description: localize(10176, null)
    },
    {
      body: { kind: "test", isDefault: true },
      description: localize(10177, null)
    }
  ],
  description: localize(10178, null)
};
var taskType = {
  type: "string",
  enum: ["shell"],
  default: "process",
  description: localize(10179, null)
};
var command2 = {
  oneOf: [
    {
      oneOf: [
        {
          type: "string"
        },
        {
          type: "array",
          items: {
            type: "string"
          },
          description: localize(10180, null)
        }
      ]
    },
    {
      type: "object",
      required: ["value", "quoting"],
      properties: {
        value: {
          oneOf: [
            {
              type: "string"
            },
            {
              type: "array",
              items: {
                type: "string"
              },
              description: localize(10181, null)
            }
          ],
          description: localize(10182, null)
        },
        quoting: {
          type: "string",
          enum: ["escape", "strong", "weak"],
          enumDescriptions: [
            localize(10183, null),
            localize(10184, null),
            localize(10185, null)
          ],
          default: "strong",
          description: localize(10186, null)
        }
      }
    }
  ],
  description: localize(10187, null)
};
var args = {
  type: "array",
  items: {
    oneOf: [
      {
        type: "string"
      },
      {
        type: "object",
        required: ["value", "quoting"],
        properties: {
          value: {
            type: "string",
            description: localize(10188, null)
          },
          quoting: {
            type: "string",
            enum: ["escape", "strong", "weak"],
            enumDescriptions: [
              localize(10189, null),
              localize(10190, null),
              localize(10191, null)
            ],
            default: "strong",
            description: localize(10192, null)
          }
        }
      }
    ]
  },
  description: localize(10193, null)
};
var label = {
  type: "string",
  description: localize(10194, null)
};
var version = {
  type: "string",
  enum: ["2.0.0"],
  description: localize(10195, null)
};
var identifier = {
  type: "string",
  description: localize(10196, null),
  deprecationMessage: localize(10197, null)
};
var runOptions = {
  type: "object",
  additionalProperties: false,
  properties: {
    reevaluateOnRerun: {
      type: "boolean",
      description: localize(10198, null),
      default: true
    },
    runOn: {
      type: "string",
      enum: ["default", "folderOpen"],
      description: localize(10199, null),
      default: "default"
    },
    instanceLimit: {
      type: "number",
      description: localize(10200, null),
      default: 1
    }
  },
  description: localize(10201, null)
};
var commonSchemaDefinitions = jsonSchemaCommon_default.definitions;
var options2 = $Lv(commonSchemaDefinitions.options);
var optionsProperties = options2.properties;
optionsProperties.shell = $Lv(commonSchemaDefinitions.shellConfiguration);
var taskConfiguration = {
  type: "object",
  additionalProperties: false,
  properties: {
    label: {
      type: "string",
      description: localize(10202, null)
    },
    taskName: {
      type: "string",
      description: localize(10203, null),
      deprecationMessage: localize(10204, null)
    },
    identifier: $Lv(identifier),
    group: $Lv(group),
    isBackground: {
      type: "boolean",
      description: localize(10205, null),
      default: true
    },
    promptOnClose: {
      type: "boolean",
      description: localize(10206, null),
      default: false
    },
    presentation: $Lv(presentation),
    icon: $Lv(icon),
    hide: $Lv(hide),
    options: options2,
    problemMatcher: {
      $ref: "#/definitions/problemMatcherType",
      description: localize(10207, null)
    },
    runOptions: $Lv(runOptions),
    dependsOn: $Lv(dependsOn),
    dependsOrder: $Lv(dependsOrder),
    detail: $Lv(detail)
  }
};
var taskDefinitions = [];
$aQ.onReady().then(() => {
  $ohc();
});
function $ohc() {
  for (const taskType2 of $aQ.all()) {
    if (taskDefinitions.find((schema10) => {
      return schema10.properties?.type?.enum?.find ? schema10.properties?.type.enum.find((element) => element === taskType2.taskType) : void 0;
    })) {
      continue;
    }
    const schema9 = $Lv(taskConfiguration);
    const schemaProperties = schema9.properties;
    schemaProperties.type = {
      type: "string",
      description: localize(10208, null),
      enum: [taskType2.taskType]
    };
    if (taskType2.required) {
      schema9.required = taskType2.required.slice();
    } else {
      schema9.required = [];
    }
    schema9.required.push("type");
    if (taskType2.properties) {
      for (const key2 of Object.keys(taskType2.properties)) {
        const property = taskType2.properties[key2];
        schemaProperties[key2] = $Lv(property);
      }
    }
    fixReferences2(schema9);
    taskDefinitions.push(schema9);
  }
}
var customize = $Lv(taskConfiguration);
customize.properties.customize = {
  type: "string",
  deprecationMessage: localize(10209, null)
};
if (!customize.required) {
  customize.required = [];
}
customize.required.push("customize");
taskDefinitions.push(customize);
var definitions2 = $Lv(commonSchemaDefinitions);
var taskDescription = definitions2.taskDescription;
taskDescription.required = ["label"];
var taskDescriptionProperties = taskDescription.properties;
taskDescriptionProperties.label = $Lv(label);
taskDescriptionProperties.command = $Lv(command2);
taskDescriptionProperties.args = $Lv(args);
taskDescriptionProperties.isShellCommand = $Lv(shellCommand2);
taskDescriptionProperties.dependsOn = dependsOn;
taskDescriptionProperties.hide = $Lv(hide);
taskDescriptionProperties.dependsOrder = dependsOrder;
taskDescriptionProperties.identifier = $Lv(identifier);
taskDescriptionProperties.type = $Lv(taskType);
taskDescriptionProperties.presentation = $Lv(presentation);
taskDescriptionProperties.terminal = terminal;
taskDescriptionProperties.icon = $Lv(icon);
taskDescriptionProperties.group = $Lv(group);
taskDescriptionProperties.runOptions = $Lv(runOptions);
taskDescriptionProperties.detail = detail;
taskDescriptionProperties.taskName.deprecationMessage = localize(10210, null);
var processTask = $Lv(taskDescription);
taskDescription.default = {
  label: "My Task",
  type: "shell",
  command: "echo Hello",
  problemMatcher: []
};
definitions2.showOutputType.deprecationMessage = localize(10211, null);
taskDescriptionProperties.echoCommand.deprecationMessage = localize(10212, null);
taskDescriptionProperties.suppressTaskName.deprecationMessage = localize(10213, null);
taskDescriptionProperties.isBuildCommand.deprecationMessage = localize(10214, null);
taskDescriptionProperties.isTestCommand.deprecationMessage = localize(10215, null);
processTask.properties.type = {
  type: "string",
  enum: ["process"],
  default: "process",
  description: localize(10216, null)
};
processTask.required.push("command");
processTask.required.push("type");
taskDefinitions.push(processTask);
taskDefinitions.push({
  $ref: "#/definitions/taskDescription"
});
var definitionsTaskRunnerConfigurationProperties = definitions2.taskRunnerConfiguration.properties;
var tasks = definitionsTaskRunnerConfigurationProperties.tasks;
tasks.items = {
  oneOf: taskDefinitions
};
definitionsTaskRunnerConfigurationProperties.inputs = $fbc.definitions.inputs;
definitions2.commandConfiguration.properties.isShellCommand = $Lv(shellCommand2);
definitions2.commandConfiguration.properties.args = $Lv(args);
definitions2.options.properties.shell = {
  $ref: "#/definitions/shellConfiguration"
};
definitionsTaskRunnerConfigurationProperties.isShellCommand = $Lv(shellCommand2);
definitionsTaskRunnerConfigurationProperties.type = $Lv(taskType);
definitionsTaskRunnerConfigurationProperties.group = $Lv(group);
definitionsTaskRunnerConfigurationProperties.presentation = $Lv(presentation);
definitionsTaskRunnerConfigurationProperties.suppressTaskName.deprecationMessage = localize(10217, null);
definitionsTaskRunnerConfigurationProperties.taskSelector.deprecationMessage = localize(10218, null);
var osSpecificTaskRunnerConfiguration = $Lv(definitions2.taskRunnerConfiguration);
delete osSpecificTaskRunnerConfiguration.properties.tasks;
osSpecificTaskRunnerConfiguration.additionalProperties = false;
definitions2.osSpecificTaskRunnerConfiguration = osSpecificTaskRunnerConfiguration;
definitionsTaskRunnerConfigurationProperties.version = $Lv(version);
var schema7 = {
  oneOf: [
    {
      "allOf": [
        {
          type: "object",
          required: ["version"],
          properties: {
            version: $Lv(version),
            windows: {
              "$ref": "#/definitions/osSpecificTaskRunnerConfiguration",
              "description": localize(10219, null)
            },
            osx: {
              "$ref": "#/definitions/osSpecificTaskRunnerConfiguration",
              "description": localize(10220, null)
            },
            linux: {
              "$ref": "#/definitions/osSpecificTaskRunnerConfiguration",
              "description": localize(10221, null)
            }
          }
        },
        {
          $ref: "#/definitions/taskRunnerConfiguration"
        }
      ]
    }
  ]
};
schema7.definitions = definitions2;
function deprecatedVariableMessage(schemaMap, property) {
  const mapAtProperty = schemaMap[property].properties;
  if (mapAtProperty) {
    Object.keys(mapAtProperty).forEach((name) => {
      deprecatedVariableMessage(mapAtProperty, name);
    });
  } else {
    $abc(schemaMap[property]);
  }
}
Object.getOwnPropertyNames(definitions2).forEach((key2) => {
  const newKey = key2 + "2";
  definitions2[newKey] = definitions2[key2];
  delete definitions2[key2];
  deprecatedVariableMessage(definitions2, newKey);
});
fixReferences2(schema7);
function $phc() {
  try {
    const matcherIds = $_P.keys().map((key2) => "$" + key2);
    definitions2.problemMatcherType2.oneOf[0].enum = matcherIds;
    definitions2.problemMatcherType2.oneOf[2].items.anyOf[0].enum = matcherIds;
  } catch (err) {
    console.log("Installing problem matcher ids failed");
  }
}
$_P.onReady().then(() => {
  $phc();
});
var jsonSchema_v2_default = schema7;

// out-build/vs/workbench/contrib/tasks/common/taskSystem.js
var TaskErrors;
(function(TaskErrors2) {
  TaskErrors2[TaskErrors2["NotConfigured"] = 0] = "NotConfigured";
  TaskErrors2[TaskErrors2["RunningTask"] = 1] = "RunningTask";
  TaskErrors2[TaskErrors2["NoBuildTask"] = 2] = "NoBuildTask";
  TaskErrors2[TaskErrors2["NoTestTask"] = 3] = "NoTestTask";
  TaskErrors2[TaskErrors2["ConfigValidationError"] = 4] = "ConfigValidationError";
  TaskErrors2[TaskErrors2["TaskNotFound"] = 5] = "TaskNotFound";
  TaskErrors2[TaskErrors2["NoValidTaskRunner"] = 6] = "NoValidTaskRunner";
  TaskErrors2[TaskErrors2["UnknownError"] = 7] = "UnknownError";
})(TaskErrors || (TaskErrors = {}));
var $VSb = class {
  constructor(severity, message, code) {
    this.severity = severity;
    this.message = message;
    this.code = code;
  }
};
var Triggers;
(function(Triggers2) {
  Triggers2.shortcut = "shortcut";
  Triggers2.command = "command";
  Triggers2.reconnect = "reconnect";
})(Triggers || (Triggers = {}));
var TaskExecuteKind;
(function(TaskExecuteKind2) {
  TaskExecuteKind2[TaskExecuteKind2["Started"] = 1] = "Started";
  TaskExecuteKind2[TaskExecuteKind2["Active"] = 2] = "Active";
})(TaskExecuteKind || (TaskExecuteKind = {}));

// out-build/vs/workbench/contrib/tasks/common/taskTemplates.js
var dotnetBuild = {
  id: "dotnetCore",
  label: ".NET Core",
  sort: "NET Core",
  autoDetect: false,
  description: localize(10360, null),
  content: [
    "{",
    "	// See https://go.microsoft.com/fwlink/?LinkId=733558",
    "	// for the documentation about the tasks.json format",
    '	"version": "2.0.0",',
    '	"tasks": [',
    "		{",
    '			"label": "build",',
    '			"command": "dotnet",',
    '			"type": "shell",',
    '			"args": [',
    '				"build",',
    "				// Ask dotnet build to generate full paths for file names.",
    '				"/property:GenerateFullPaths=true",',
    "				// Do not generate summary otherwise it leads to duplicate errors in Problems panel",
    '				"/consoleloggerparameters:NoSummary"',
    "			],",
    '			"group": "build",',
    '			"presentation": {',
    '				"reveal": "silent"',
    "			},",
    '			"problemMatcher": "$msCompile"',
    "		}",
    "	]",
    "}"
  ].join("\n")
};
var msbuild = {
  id: "msbuild",
  label: "MSBuild",
  autoDetect: false,
  description: localize(10361, null),
  content: [
    "{",
    "	// See https://go.microsoft.com/fwlink/?LinkId=733558",
    "	// for the documentation about the tasks.json format",
    '	"version": "2.0.0",',
    '	"tasks": [',
    "		{",
    '			"label": "build",',
    '			"type": "shell",',
    '			"command": "msbuild",',
    '			"args": [',
    "				// Ask msbuild to generate full paths for file names.",
    '				"/property:GenerateFullPaths=true",',
    '				"/t:build",',
    "				// Do not generate summary otherwise it leads to duplicate errors in Problems panel",
    '				"/consoleloggerparameters:NoSummary"',
    "			],",
    '			"group": "build",',
    '			"presentation": {',
    "				// Reveal the output only if unrecognized errors occur.",
    '				"reveal": "silent"',
    "			},",
    "			// Use the standard MS compiler pattern to detect errors, warnings and infos",
    '			"problemMatcher": "$msCompile"',
    "		}",
    "	]",
    "}"
  ].join("\n")
};
var command3 = {
  id: "externalCommand",
  label: "Others",
  autoDetect: false,
  description: localize(10362, null),
  content: [
    "{",
    "	// See https://go.microsoft.com/fwlink/?LinkId=733558",
    "	// for the documentation about the tasks.json format",
    '	"version": "2.0.0",',
    '	"tasks": [',
    "		{",
    '			"label": "echo",',
    '			"type": "shell",',
    '			"command": "echo Hello"',
    "		}",
    "	]",
    "}"
  ].join("\n")
};
var maven = {
  id: "maven",
  label: "maven",
  sort: "MVN",
  autoDetect: false,
  description: localize(10363, null),
  content: [
    "{",
    "	// See https://go.microsoft.com/fwlink/?LinkId=733558",
    "	// for the documentation about the tasks.json format",
    '	"version": "2.0.0",',
    '	"tasks": [',
    "		{",
    '			"label": "verify",',
    '			"type": "shell",',
    '			"command": "mvn -B verify",',
    '			"group": "build"',
    "		},",
    "		{",
    '			"label": "test",',
    '			"type": "shell",',
    '			"command": "mvn -B test",',
    '			"group": "test"',
    "		}",
    "	]",
    "}"
  ].join("\n")
};
var _templates = null;
function $qhc() {
  if (!_templates) {
    _templates = [dotnetBuild, msbuild, maven].sort((a, b) => {
      return (a.sort || a.label).localeCompare(b.sort || b.label);
    });
    _templates.push(command3);
  }
  return _templates;
}

// out-build/vs/workbench/contrib/tasks/common/taskConfiguration.js
var ShellQuoting3;
(function(ShellQuoting4) {
  ShellQuoting4[ShellQuoting4["escape"] = 1] = "escape";
  ShellQuoting4[ShellQuoting4["strong"] = 2] = "strong";
  ShellQuoting4[ShellQuoting4["weak"] = 3] = "weak";
})(ShellQuoting3 || (ShellQuoting3 = {}));
var ITaskIdentifier;
(function(ITaskIdentifier2) {
  function is(value) {
    const candidate = value;
    return candidate !== void 0 && $zg(value.type);
  }
  ITaskIdentifier2.is = is;
})(ITaskIdentifier || (ITaskIdentifier = {}));
var CommandString2;
(function(CommandString3) {
  function value(value2) {
    if ($zg(value2)) {
      return value2;
    } else if ($Ag(value2)) {
      return value2.join(" ");
    } else {
      if ($zg(value2.value)) {
        return value2.value;
      } else {
        return value2.value.join(" ");
      }
    }
  }
  CommandString3.value = value;
})(CommandString2 || (CommandString2 = {}));
var ProblemMatcherKind;
(function(ProblemMatcherKind2) {
  ProblemMatcherKind2[ProblemMatcherKind2["Unknown"] = 0] = "Unknown";
  ProblemMatcherKind2[ProblemMatcherKind2["String"] = 1] = "String";
  ProblemMatcherKind2[ProblemMatcherKind2["ProblemMatcher"] = 2] = "ProblemMatcher";
  ProblemMatcherKind2[ProblemMatcherKind2["Array"] = 3] = "Array";
})(ProblemMatcherKind || (ProblemMatcherKind = {}));
var EMPTY_ARRAY = [];
Object.freeze(EMPTY_ARRAY);
function assignProperty(target, source, key2) {
  const sourceAtKey = source[key2];
  if (sourceAtKey !== void 0) {
    target[key2] = sourceAtKey;
  }
}
function fillProperty(target, source, key2) {
  const sourceAtKey = source[key2];
  if (target[key2] === void 0 && sourceAtKey !== void 0) {
    target[key2] = sourceAtKey;
  }
}
function _isEmpty(value, properties, allowEmptyArray = false) {
  if (value === void 0 || value === null || properties === void 0) {
    return true;
  }
  for (const meta of properties) {
    const property = value[meta.property];
    if (property !== void 0 && property !== null) {
      if (meta.type !== void 0 && !meta.type.isEmpty(property)) {
        return false;
      } else if (!Array.isArray(property) || property.length > 0 || allowEmptyArray) {
        return false;
      }
    }
  }
  return true;
}
function _assignProperties(target, source, properties) {
  if (!source || _isEmpty(source, properties)) {
    return target;
  }
  if (!target || _isEmpty(target, properties)) {
    return source;
  }
  for (const meta of properties) {
    const property = meta.property;
    let value;
    if (meta.type !== void 0) {
      value = meta.type.assignProperties(target[property], source[property]);
    } else {
      value = source[property];
    }
    if (value !== void 0 && value !== null) {
      target[property] = value;
    }
  }
  return target;
}
function _fillProperties(target, source, properties, allowEmptyArray = false) {
  if (!source || _isEmpty(source, properties)) {
    return target;
  }
  if (!target || _isEmpty(target, properties, allowEmptyArray)) {
    return source;
  }
  for (const meta of properties) {
    const property = meta.property;
    let value;
    if (meta.type) {
      value = meta.type.fillProperties(target[property], source[property]);
    } else if (target[property] === void 0) {
      value = source[property];
    }
    if (value !== void 0 && value !== null) {
      target[property] = value;
    }
  }
  return target;
}
function _fillDefaults(target, defaults, properties, context) {
  if (target && Object.isFrozen(target)) {
    return target;
  }
  if (target === void 0 || target === null || defaults === void 0 || defaults === null) {
    if (defaults !== void 0 && defaults !== null) {
      return $Lv(defaults);
    } else {
      return void 0;
    }
  }
  for (const meta of properties) {
    const property = meta.property;
    if (target[property] !== void 0) {
      continue;
    }
    let value;
    if (meta.type) {
      value = meta.type.fillDefaults(target[property], context);
    } else {
      value = defaults[property];
    }
    if (value !== void 0 && value !== null) {
      target[property] = value;
    }
  }
  return target;
}
function _freeze(target, properties) {
  if (target === void 0 || target === null) {
    return void 0;
  }
  if (Object.isFrozen(target)) {
    return target;
  }
  for (const meta of properties) {
    if (meta.type) {
      const value = target[meta.property];
      if (value) {
        meta.type.freeze(value);
      }
    }
  }
  Object.freeze(target);
  return target;
}
var RunOnOptions2;
(function(RunOnOptions3) {
  function fromString(value) {
    if (!value) {
      return RunOnOptions.default;
    }
    switch (value.toLowerCase()) {
      case "folderopen":
        return RunOnOptions.folderOpen;
      case "default":
      default:
        return RunOnOptions.default;
    }
  }
  RunOnOptions3.fromString = fromString;
})(RunOnOptions2 || (RunOnOptions2 = {}));
var RunOptions2;
(function(RunOptions3) {
  const properties = [{ property: "reevaluateOnRerun" }, { property: "runOn" }, { property: "instanceLimit" }];
  function fromConfiguration(value) {
    return {
      reevaluateOnRerun: value ? value.reevaluateOnRerun : true,
      runOn: value ? RunOnOptions2.fromString(value.runOn) : RunOnOptions.default,
      instanceLimit: value ? value.instanceLimit : 1
    };
  }
  RunOptions3.fromConfiguration = fromConfiguration;
  function assignProperties(target, source) {
    return _assignProperties(target, source, properties);
  }
  RunOptions3.assignProperties = assignProperties;
  function fillProperties(target, source) {
    return _fillProperties(target, source, properties);
  }
  RunOptions3.fillProperties = fillProperties;
})(RunOptions2 || (RunOptions2 = {}));
var ShellConfiguration;
(function(ShellConfiguration2) {
  const properties = [{ property: "executable" }, { property: "args" }, { property: "quoting" }];
  function is(value) {
    const candidate = value;
    return candidate && ($zg(candidate.executable) || $Ag(candidate.args));
  }
  ShellConfiguration2.is = is;
  function from(config, context) {
    if (!is(config)) {
      return void 0;
    }
    const result = {};
    if (config.executable !== void 0) {
      result.executable = config.executable;
    }
    if (config.args !== void 0) {
      result.args = config.args.slice();
    }
    if (config.quoting !== void 0) {
      result.quoting = $Lv(config.quoting);
    }
    return result;
  }
  ShellConfiguration2.from = from;
  function isEmpty(value) {
    return _isEmpty(value, properties, true);
  }
  ShellConfiguration2.isEmpty = isEmpty;
  function assignProperties(target, source) {
    return _assignProperties(target, source, properties);
  }
  ShellConfiguration2.assignProperties = assignProperties;
  function fillProperties(target, source) {
    return _fillProperties(target, source, properties, true);
  }
  ShellConfiguration2.fillProperties = fillProperties;
  function fillDefaults(value, context) {
    return value;
  }
  ShellConfiguration2.fillDefaults = fillDefaults;
  function freeze3(value) {
    if (!value) {
      return void 0;
    }
    return Object.freeze(value);
  }
  ShellConfiguration2.freeze = freeze3;
})(ShellConfiguration || (ShellConfiguration = {}));
var CommandOptions2;
(function(CommandOptions3) {
  const properties = [{ property: "cwd" }, { property: "env" }, { property: "shell", type: ShellConfiguration }];
  const defaults = { cwd: "${workspaceFolder}" };
  function from(options3, context) {
    const result = {};
    if (options3.cwd !== void 0) {
      if ($zg(options3.cwd)) {
        result.cwd = options3.cwd;
      } else {
        context.taskLoadIssues.push(localize(10331, null, options3.cwd));
      }
    }
    if (options3.env !== void 0) {
      result.env = $Lv(options3.env);
    }
    result.shell = ShellConfiguration.from(options3.shell, context);
    return isEmpty(result) ? void 0 : result;
  }
  CommandOptions3.from = from;
  function isEmpty(value) {
    return _isEmpty(value, properties);
  }
  CommandOptions3.isEmpty = isEmpty;
  function assignProperties(target, source) {
    if (source === void 0 || isEmpty(source)) {
      return target;
    }
    if (target === void 0 || isEmpty(target)) {
      return source;
    }
    assignProperty(target, source, "cwd");
    if (target.env === void 0) {
      target.env = source.env;
    } else if (source.env !== void 0) {
      const env3 = /* @__PURE__ */ Object.create(null);
      if (target.env !== void 0) {
        Object.keys(target.env).forEach((key2) => env3[key2] = target.env[key2]);
      }
      if (source.env !== void 0) {
        Object.keys(source.env).forEach((key2) => env3[key2] = source.env[key2]);
      }
      target.env = env3;
    }
    target.shell = ShellConfiguration.assignProperties(target.shell, source.shell);
    return target;
  }
  CommandOptions3.assignProperties = assignProperties;
  function fillProperties(target, source) {
    return _fillProperties(target, source, properties);
  }
  CommandOptions3.fillProperties = fillProperties;
  function fillDefaults(value, context) {
    return _fillDefaults(value, defaults, properties, context);
  }
  CommandOptions3.fillDefaults = fillDefaults;
  function freeze3(value) {
    return _freeze(value, properties);
  }
  CommandOptions3.freeze = freeze3;
})(CommandOptions2 || (CommandOptions2 = {}));
var CommandConfiguration;
(function(CommandConfiguration2) {
  let PresentationOptions2;
  (function(PresentationOptions3) {
    const properties2 = [{ property: "echo" }, { property: "reveal" }, { property: "revealProblems" }, { property: "focus" }, { property: "panel" }, { property: "showReuseMessage" }, { property: "clear" }, { property: "group" }, { property: "close" }];
    function from2(config, context) {
      let echo;
      let reveal;
      let revealProblems;
      let focus;
      let panel;
      let showReuseMessage;
      let clear;
      let group2;
      let close2;
      let hasProps = false;
      if ($Fg(config.echoCommand)) {
        echo = config.echoCommand;
        hasProps = true;
      }
      if ($zg(config.showOutput)) {
        reveal = RevealKind.fromString(config.showOutput);
        hasProps = true;
      }
      const presentation2 = config.presentation || config.terminal;
      if (presentation2) {
        if ($Fg(presentation2.echo)) {
          echo = presentation2.echo;
        }
        if ($zg(presentation2.reveal)) {
          reveal = RevealKind.fromString(presentation2.reveal);
        }
        if ($zg(presentation2.revealProblems)) {
          revealProblems = RevealProblemKind.fromString(presentation2.revealProblems);
        }
        if ($Fg(presentation2.focus)) {
          focus = presentation2.focus;
        }
        if ($zg(presentation2.panel)) {
          panel = PanelKind.fromString(presentation2.panel);
        }
        if ($Fg(presentation2.showReuseMessage)) {
          showReuseMessage = presentation2.showReuseMessage;
        }
        if ($Fg(presentation2.clear)) {
          clear = presentation2.clear;
        }
        if ($zg(presentation2.group)) {
          group2 = presentation2.group;
        }
        if ($Fg(presentation2.close)) {
          close2 = presentation2.close;
        }
        hasProps = true;
      }
      if (!hasProps) {
        return void 0;
      }
      return { echo, reveal, revealProblems, focus, panel, showReuseMessage, clear, group: group2, close: close2 };
    }
    PresentationOptions3.from = from2;
    function assignProperties2(target, source) {
      return _assignProperties(target, source, properties2);
    }
    PresentationOptions3.assignProperties = assignProperties2;
    function fillProperties2(target, source) {
      return _fillProperties(target, source, properties2);
    }
    PresentationOptions3.fillProperties = fillProperties2;
    function fillDefaults2(value, context) {
      const defaultEcho = context.engine === ExecutionEngine.Terminal ? true : false;
      return _fillDefaults(value, { echo: defaultEcho, reveal: RevealKind.Always, revealProblems: RevealProblemKind.Never, focus: false, panel: PanelKind.Shared, showReuseMessage: true, clear: false }, properties2, context);
    }
    PresentationOptions3.fillDefaults = fillDefaults2;
    function freeze4(value) {
      return _freeze(value, properties2);
    }
    PresentationOptions3.freeze = freeze4;
    function isEmpty2(value) {
      return _isEmpty(value, properties2);
    }
    PresentationOptions3.isEmpty = isEmpty2;
  })(PresentationOptions2 = CommandConfiguration2.PresentationOptions || (CommandConfiguration2.PresentationOptions = {}));
  let ShellString;
  (function(ShellString2) {
    function from2(value) {
      if (value === void 0 || value === null) {
        return void 0;
      }
      if ($zg(value)) {
        return value;
      } else if ($Ag(value)) {
        return value.join(" ");
      } else {
        const quoting = ShellQuoting2.from(value.quoting);
        const result = $zg(value.value) ? value.value : $Ag(value.value) ? value.value.join(" ") : void 0;
        if (result) {
          return {
            value: result,
            quoting
          };
        } else {
          return void 0;
        }
      }
    }
    ShellString2.from = from2;
  })(ShellString || (ShellString = {}));
  const properties = [
    { property: "runtime" },
    { property: "name" },
    { property: "options", type: CommandOptions2 },
    { property: "args" },
    { property: "taskSelector" },
    { property: "suppressTaskName" },
    { property: "presentation", type: PresentationOptions2 }
  ];
  function from(config, context) {
    let result = fromBase(config, context);
    let osConfig = void 0;
    if (config.windows && context.platform === 3) {
      osConfig = fromBase(config.windows, context);
    } else if (config.osx && context.platform === 1) {
      osConfig = fromBase(config.osx, context);
    } else if (config.linux && context.platform === 2) {
      osConfig = fromBase(config.linux, context);
    }
    if (osConfig) {
      result = assignProperties(
        result,
        osConfig,
        context.schemaVersion === 2
        /* Tasks.JsonSchemaVersion.V2_0_0 */
      );
    }
    return isEmpty(result) ? void 0 : result;
  }
  CommandConfiguration2.from = from;
  function fromBase(config, context) {
    const name = ShellString.from(config.command);
    let runtime;
    if ($zg(config.type)) {
      if (config.type === "shell" || config.type === "process") {
        runtime = RuntimeType.fromString(config.type);
      }
    }
    if ($Fg(config.isShellCommand) || ShellConfiguration.is(config.isShellCommand)) {
      runtime = RuntimeType.Shell;
    } else if (config.isShellCommand !== void 0) {
      runtime = !!config.isShellCommand ? RuntimeType.Shell : RuntimeType.Process;
    }
    const result = {
      name,
      runtime,
      presentation: PresentationOptions2.from(config, context)
    };
    if (config.args !== void 0) {
      result.args = [];
      for (const arg of config.args) {
        const converted = ShellString.from(arg);
        if (converted !== void 0) {
          result.args.push(converted);
        } else {
          context.taskLoadIssues.push(localize(10332, null, arg ? JSON.stringify(arg, void 0, 4) : "undefined"));
        }
      }
    }
    if (config.options !== void 0) {
      result.options = CommandOptions2.from(config.options, context);
      if (result.options && result.options.shell === void 0 && ShellConfiguration.is(config.isShellCommand)) {
        result.options.shell = ShellConfiguration.from(config.isShellCommand, context);
        if (context.engine !== ExecutionEngine.Terminal) {
          context.taskLoadIssues.push(localize(10333, null));
        }
      }
    }
    if ($zg(config.taskSelector)) {
      result.taskSelector = config.taskSelector;
    }
    if ($Fg(config.suppressTaskName)) {
      result.suppressTaskName = config.suppressTaskName;
    }
    return isEmpty(result) ? void 0 : result;
  }
  function hasCommand(value) {
    return value && !!value.name;
  }
  CommandConfiguration2.hasCommand = hasCommand;
  function isEmpty(value) {
    return _isEmpty(value, properties);
  }
  CommandConfiguration2.isEmpty = isEmpty;
  function assignProperties(target, source, overwriteArgs) {
    if (isEmpty(source)) {
      return target;
    }
    if (isEmpty(target)) {
      return source;
    }
    assignProperty(target, source, "name");
    assignProperty(target, source, "runtime");
    assignProperty(target, source, "taskSelector");
    assignProperty(target, source, "suppressTaskName");
    if (source.args !== void 0) {
      if (target.args === void 0 || overwriteArgs) {
        target.args = source.args;
      } else {
        target.args = target.args.concat(source.args);
      }
    }
    target.presentation = PresentationOptions2.assignProperties(target.presentation, source.presentation);
    target.options = CommandOptions2.assignProperties(target.options, source.options);
    return target;
  }
  CommandConfiguration2.assignProperties = assignProperties;
  function fillProperties(target, source) {
    return _fillProperties(target, source, properties);
  }
  CommandConfiguration2.fillProperties = fillProperties;
  function fillGlobals(target, source, taskName) {
    if (source === void 0 || isEmpty(source)) {
      return target;
    }
    target = target || {
      name: void 0,
      runtime: void 0,
      presentation: void 0
    };
    if (target.name === void 0) {
      fillProperty(target, source, "name");
      fillProperty(target, source, "taskSelector");
      fillProperty(target, source, "suppressTaskName");
      let args2 = source.args ? source.args.slice() : [];
      if (!target.suppressTaskName && taskName) {
        if (target.taskSelector !== void 0) {
          args2.push(target.taskSelector + taskName);
        } else {
          args2.push(taskName);
        }
      }
      if (target.args) {
        args2 = args2.concat(target.args);
      }
      target.args = args2;
    }
    fillProperty(target, source, "runtime");
    target.presentation = PresentationOptions2.fillProperties(target.presentation, source.presentation);
    target.options = CommandOptions2.fillProperties(target.options, source.options);
    return target;
  }
  CommandConfiguration2.fillGlobals = fillGlobals;
  function fillDefaults(value, context) {
    if (!value || Object.isFrozen(value)) {
      return;
    }
    if (value.name !== void 0 && value.runtime === void 0) {
      value.runtime = RuntimeType.Process;
    }
    value.presentation = PresentationOptions2.fillDefaults(value.presentation, context);
    if (!isEmpty(value)) {
      value.options = CommandOptions2.fillDefaults(value.options, context);
    }
    if (value.args === void 0) {
      value.args = EMPTY_ARRAY;
    }
    if (value.suppressTaskName === void 0) {
      value.suppressTaskName = context.schemaVersion === 2;
    }
  }
  CommandConfiguration2.fillDefaults = fillDefaults;
  function freeze3(value) {
    return _freeze(value, properties);
  }
  CommandConfiguration2.freeze = freeze3;
})(CommandConfiguration || (CommandConfiguration = {}));
var ProblemMatcherConverter;
(function(ProblemMatcherConverter2) {
  function namedFrom(declares, context) {
    const result = /* @__PURE__ */ Object.create(null);
    if (!Array.isArray(declares)) {
      return result;
    }
    declares.forEach((value) => {
      const namedProblemMatcher = new $$P(context.problemReporter).parse(value);
      if ($5P(namedProblemMatcher)) {
        result[namedProblemMatcher.name] = namedProblemMatcher;
      } else {
        context.problemReporter.error(localize(10334, null, JSON.stringify(value, void 0, 4)));
      }
    });
    return result;
  }
  ProblemMatcherConverter2.namedFrom = namedFrom;
  function fromWithOsConfig(external, context) {
    let result = {};
    if (external.windows && external.windows.problemMatcher && context.platform === 3) {
      result = from(external.windows.problemMatcher, context);
    } else if (external.osx && external.osx.problemMatcher && context.platform === 1) {
      result = from(external.osx.problemMatcher, context);
    } else if (external.linux && external.linux.problemMatcher && context.platform === 2) {
      result = from(external.linux.problemMatcher, context);
    } else if (external.problemMatcher) {
      result = from(external.problemMatcher, context);
    }
    return result;
  }
  ProblemMatcherConverter2.fromWithOsConfig = fromWithOsConfig;
  function from(config, context) {
    const result = [];
    if (config === void 0) {
      return { value: result };
    }
    const errors = [];
    function addResult(matcher) {
      if (matcher.value) {
        result.push(matcher.value);
      }
      if (matcher.errors) {
        errors.push(...matcher.errors);
      }
    }
    const kind = getProblemMatcherKind(config);
    if (kind === ProblemMatcherKind.Unknown) {
      const error = localize(10335, null, JSON.stringify(config, null, 4));
      context.problemReporter.warn(error);
    } else if (kind === ProblemMatcherKind.String || kind === ProblemMatcherKind.ProblemMatcher) {
      addResult(resolveProblemMatcher(config, context));
    } else if (kind === ProblemMatcherKind.Array) {
      const problemMatchers = config;
      problemMatchers.forEach((problemMatcher) => {
        addResult(resolveProblemMatcher(problemMatcher, context));
      });
    }
    return { value: result, errors };
  }
  ProblemMatcherConverter2.from = from;
  function getProblemMatcherKind(value) {
    if ($zg(value)) {
      return ProblemMatcherKind.String;
    } else if (Array.isArray(value)) {
      return ProblemMatcherKind.Array;
    } else if (!$Gg(value)) {
      return ProblemMatcherKind.ProblemMatcher;
    } else {
      return ProblemMatcherKind.Unknown;
    }
  }
  function resolveProblemMatcher(value, context) {
    if ($zg(value)) {
      let variableName = value;
      if (variableName.length > 1 && variableName[0] === "$") {
        variableName = variableName.substring(1);
        const global = $_P.get(variableName);
        if (global) {
          return { value: $Lv(global) };
        }
        let localProblemMatcher = context.namedProblemMatchers[variableName];
        if (localProblemMatcher) {
          localProblemMatcher = $Lv(localProblemMatcher);
          delete localProblemMatcher.name;
          return { value: localProblemMatcher };
        }
      }
      return { errors: [localize(10336, null, value)] };
    } else {
      const json = value;
      return { value: new $$P(context.problemReporter).parse(json) };
    }
  }
})(ProblemMatcherConverter || (ProblemMatcherConverter = {}));
var GroupKind;
(function(GroupKind2) {
  function from(external) {
    if (external === void 0) {
      return void 0;
    } else if ($zg(external) && TaskGroup.is(external)) {
      return { _id: external, isDefault: false };
    } else if ($zg(external.kind) && TaskGroup.is(external.kind)) {
      const group2 = external.kind;
      const isDefault = $Gg(external.isDefault) ? false : external.isDefault;
      return { _id: group2, isDefault };
    }
    return void 0;
  }
  GroupKind2.from = from;
  function to(group2) {
    if ($zg(group2)) {
      return group2;
    } else if (!group2.isDefault) {
      return group2._id;
    }
    return {
      kind: group2._id,
      isDefault: group2.isDefault
    };
  }
  GroupKind2.to = to;
})(GroupKind || (GroupKind = {}));
var TaskDependency;
(function(TaskDependency2) {
  function uriFromSource(context, source) {
    switch (source) {
      case TaskConfigSource.User:
        return $bQ;
      case TaskConfigSource.TasksJson:
        return context.workspaceFolder.uri;
      default:
        return context.workspace && context.workspace.configuration ? context.workspace.configuration : context.workspaceFolder.uri;
    }
  }
  function from(external, context, source) {
    if ($zg(external)) {
      return { uri: uriFromSource(context, source), task: external };
    } else if (ITaskIdentifier.is(external)) {
      return {
        uri: uriFromSource(context, source),
        task: TaskDefinition.createTaskIdentifier(external, context.problemReporter)
      };
    } else {
      return void 0;
    }
  }
  TaskDependency2.from = from;
})(TaskDependency || (TaskDependency = {}));
var DependsOrder2;
(function(DependsOrder3) {
  function from(order) {
    switch (order) {
      case "sequence":
        return "sequence";
      case "parallel":
      default:
        return "parallel";
    }
  }
  DependsOrder3.from = from;
})(DependsOrder2 || (DependsOrder2 = {}));
var ConfigurationProperties;
(function(ConfigurationProperties2) {
  const properties = [
    { property: "name" },
    { property: "identifier" },
    { property: "group" },
    { property: "isBackground" },
    { property: "promptOnClose" },
    { property: "dependsOn" },
    { property: "presentation", type: CommandConfiguration.PresentationOptions },
    { property: "problemMatchers" },
    { property: "options" },
    { property: "icon" },
    { property: "hide" }
  ];
  function from(external, context, includeCommandOptions, source, properties2) {
    if (!external) {
      return {};
    }
    const result = {};
    if (properties2) {
      for (const propertyName of Object.keys(properties2)) {
        if (external[propertyName] !== void 0) {
          result[propertyName] = $Lv(external[propertyName]);
        }
      }
    }
    if ($zg(external.taskName)) {
      result.name = external.taskName;
    }
    if ($zg(external.label) && context.schemaVersion === 2) {
      result.name = external.label;
    }
    if ($zg(external.identifier)) {
      result.identifier = external.identifier;
    }
    result.icon = external.icon;
    result.hide = external.hide;
    if (external.isBackground !== void 0) {
      result.isBackground = !!external.isBackground;
    }
    if (external.promptOnClose !== void 0) {
      result.promptOnClose = !!external.promptOnClose;
    }
    result.group = GroupKind.from(external.group);
    if (external.dependsOn !== void 0) {
      if (Array.isArray(external.dependsOn)) {
        result.dependsOn = external.dependsOn.reduce((dependencies, item) => {
          const dependency = TaskDependency.from(item, context, source);
          if (dependency) {
            dependencies.push(dependency);
          }
          return dependencies;
        }, []);
      } else {
        const dependsOnValue = TaskDependency.from(external.dependsOn, context, source);
        result.dependsOn = dependsOnValue ? [dependsOnValue] : void 0;
      }
    }
    result.dependsOrder = DependsOrder2.from(external.dependsOrder);
    if (includeCommandOptions && (external.presentation !== void 0 || external.terminal !== void 0)) {
      result.presentation = CommandConfiguration.PresentationOptions.from(external, context);
    }
    if (includeCommandOptions && external.options !== void 0) {
      result.options = CommandOptions2.from(external.options, context);
    }
    const configProblemMatcher = ProblemMatcherConverter.fromWithOsConfig(external, context);
    if (configProblemMatcher.value !== void 0) {
      result.problemMatchers = configProblemMatcher.value;
    }
    if (external.detail) {
      result.detail = external.detail;
    }
    return isEmpty(result) ? {} : { value: result, errors: configProblemMatcher.errors };
  }
  ConfigurationProperties2.from = from;
  function isEmpty(value) {
    return _isEmpty(value, properties);
  }
  ConfigurationProperties2.isEmpty = isEmpty;
})(ConfigurationProperties || (ConfigurationProperties = {}));
var label2 = "Workspace";
var ConfiguringTask;
(function(ConfiguringTask2) {
  const grunt = "grunt.";
  const jake = "jake.";
  const gulp = "gulp.";
  const npm = "vscode.npm.";
  const typescript = "vscode.typescript.";
  function from(external, context, index, source, registry4) {
    if (!external) {
      return void 0;
    }
    const type = external.type;
    const customize2 = external.customize;
    if (!type && !customize2) {
      context.problemReporter.error(localize(10337, null, JSON.stringify(external, null, 4)));
      return void 0;
    }
    const typeDeclaration = type ? registry4?.get?.(type) || $aQ.get(type) : void 0;
    if (!typeDeclaration) {
      const message = localize(10338, null, type);
      context.problemReporter.error(message);
      return void 0;
    }
    let identifier2;
    if ($zg(customize2)) {
      if (customize2.indexOf(grunt) === 0) {
        identifier2 = { type: "grunt", task: customize2.substring(grunt.length) };
      } else if (customize2.indexOf(jake) === 0) {
        identifier2 = { type: "jake", task: customize2.substring(jake.length) };
      } else if (customize2.indexOf(gulp) === 0) {
        identifier2 = { type: "gulp", task: customize2.substring(gulp.length) };
      } else if (customize2.indexOf(npm) === 0) {
        identifier2 = { type: "npm", script: customize2.substring(npm.length + 4) };
      } else if (customize2.indexOf(typescript) === 0) {
        identifier2 = { type: "typescript", tsconfig: customize2.substring(typescript.length + 6) };
      }
    } else {
      if ($zg(external.type)) {
        identifier2 = external;
      }
    }
    if (identifier2 === void 0) {
      context.problemReporter.error(localize(10339, null, JSON.stringify(external, void 0, 0)));
      return void 0;
    }
    const taskIdentifier2 = TaskDefinition.createTaskIdentifier(identifier2, context.problemReporter);
    if (taskIdentifier2 === void 0) {
      context.problemReporter.error(localize(10340, null, JSON.stringify(external, void 0, 0)));
      return void 0;
    }
    const configElement = {
      workspaceFolder: context.workspaceFolder,
      file: ".vscode/tasks.json",
      index,
      element: external
    };
    let taskSource;
    switch (source) {
      case TaskConfigSource.User: {
        taskSource = { kind: TaskSourceKind.User, config: configElement, label: label2 };
        break;
      }
      case TaskConfigSource.WorkspaceFile: {
        taskSource = { kind: TaskSourceKind.WorkspaceFile, config: configElement, label: label2 };
        break;
      }
      default: {
        taskSource = { kind: TaskSourceKind.Workspace, config: configElement, label: label2 };
        break;
      }
    }
    const result = new $hQ(`${typeDeclaration.extensionId}.${taskIdentifier2._key}`, taskSource, void 0, type, taskIdentifier2, RunOptions2.fromConfiguration(external.runOptions), { hide: external.hide });
    const configuration2 = ConfigurationProperties.from(external, context, true, source, typeDeclaration.properties);
    result.addTaskLoadMessages(configuration2.errors);
    if (configuration2.value) {
      result.configurationProperties = Object.assign(result.configurationProperties, configuration2.value);
      if (result.configurationProperties.name) {
        result._label = result.configurationProperties.name;
      } else {
        let label3 = result.configures.type;
        if (typeDeclaration.required && typeDeclaration.required.length > 0) {
          for (const required of typeDeclaration.required) {
            const value = result.configures[required];
            if (value) {
              label3 = label3 + ": " + value;
              break;
            }
          }
        }
        result._label = label3;
      }
      if (!result.configurationProperties.identifier) {
        result.configurationProperties.identifier = taskIdentifier2._key;
      }
    }
    return result;
  }
  ConfiguringTask2.from = from;
})(ConfiguringTask || (ConfiguringTask = {}));
var CustomTask;
(function(CustomTask2) {
  function from(external, context, index, source) {
    if (!external) {
      return void 0;
    }
    let type = external.type;
    if (type === void 0 || type === null) {
      type = $eQ;
    }
    if (type !== $eQ && type !== "shell" && type !== "process") {
      context.problemReporter.error(localize(10341, null, JSON.stringify(external, null, 4)));
      return void 0;
    }
    let taskName = external.taskName;
    if ($zg(external.label) && context.schemaVersion === 2) {
      taskName = external.label;
    }
    if (!taskName) {
      context.problemReporter.error(localize(10342, null, JSON.stringify(external, null, 4)));
      return void 0;
    }
    let taskSource;
    switch (source) {
      case TaskConfigSource.User: {
        taskSource = { kind: TaskSourceKind.User, config: { index, element: external, file: ".vscode/tasks.json", workspaceFolder: context.workspaceFolder }, label: label2 };
        break;
      }
      case TaskConfigSource.WorkspaceFile: {
        taskSource = { kind: TaskSourceKind.WorkspaceFile, config: { index, element: external, file: ".vscode/tasks.json", workspaceFolder: context.workspaceFolder, workspace: context.workspace }, label: label2 };
        break;
      }
      default: {
        taskSource = { kind: TaskSourceKind.Workspace, config: { index, element: external, file: ".vscode/tasks.json", workspaceFolder: context.workspaceFolder }, label: label2 };
        break;
      }
    }
    const result = new $gQ(context.uuidMap.getUUID(taskName), taskSource, taskName, $eQ, void 0, false, RunOptions2.fromConfiguration(external.runOptions), {
      name: taskName,
      identifier: taskName
    });
    const configuration2 = ConfigurationProperties.from(external, context, false, source);
    result.addTaskLoadMessages(configuration2.errors);
    if (configuration2.value) {
      result.configurationProperties = Object.assign(result.configurationProperties, configuration2.value);
    }
    const supportLegacy = true;
    if (supportLegacy) {
      const legacy = external;
      if (result.configurationProperties.isBackground === void 0 && legacy.isWatching !== void 0) {
        result.configurationProperties.isBackground = !!legacy.isWatching;
      }
      if (result.configurationProperties.group === void 0) {
        if (legacy.isBuildCommand === true) {
          result.configurationProperties.group = TaskGroup.Build;
        } else if (legacy.isTestCommand === true) {
          result.configurationProperties.group = TaskGroup.Test;
        }
      }
    }
    const command4 = CommandConfiguration.from(external, context);
    if (command4) {
      result.command = command4;
    }
    if (external.command !== void 0) {
      command4.suppressTaskName = true;
    }
    return result;
  }
  CustomTask2.from = from;
  function fillGlobals(task, globals) {
    if (CommandConfiguration.hasCommand(task.command) || task.configurationProperties.dependsOn === void 0) {
      task.command = CommandConfiguration.fillGlobals(task.command, globals.command, task.configurationProperties.name);
    }
    if (task.configurationProperties.problemMatchers === void 0 && globals.problemMatcher !== void 0) {
      task.configurationProperties.problemMatchers = $Lv(globals.problemMatcher);
      task.hasDefinedMatchers = true;
    }
    if (task.configurationProperties.promptOnClose === void 0 && task.configurationProperties.isBackground === void 0 && globals.promptOnClose !== void 0) {
      task.configurationProperties.promptOnClose = globals.promptOnClose;
    }
  }
  CustomTask2.fillGlobals = fillGlobals;
  function fillDefaults(task, context) {
    CommandConfiguration.fillDefaults(task.command, context);
    if (task.configurationProperties.promptOnClose === void 0) {
      task.configurationProperties.promptOnClose = task.configurationProperties.isBackground !== void 0 ? !task.configurationProperties.isBackground : true;
    }
    if (task.configurationProperties.isBackground === void 0) {
      task.configurationProperties.isBackground = false;
    }
    if (task.configurationProperties.problemMatchers === void 0) {
      task.configurationProperties.problemMatchers = EMPTY_ARRAY;
    }
  }
  CustomTask2.fillDefaults = fillDefaults;
  function createCustomTask(contributedTask, configuredProps) {
    const result = new $gQ(configuredProps._id, Object.assign({}, configuredProps._source, { customizes: contributedTask.defines }), configuredProps.configurationProperties.name || contributedTask._label, $eQ, contributedTask.command, false, contributedTask.runOptions, {
      name: configuredProps.configurationProperties.name || contributedTask.configurationProperties.name,
      identifier: configuredProps.configurationProperties.identifier || contributedTask.configurationProperties.identifier,
      icon: configuredProps.configurationProperties.icon,
      hide: configuredProps.configurationProperties.hide
    });
    result.addTaskLoadMessages(configuredProps.taskLoadMessages);
    const resultConfigProps = result.configurationProperties;
    assignProperty(resultConfigProps, configuredProps.configurationProperties, "group");
    assignProperty(resultConfigProps, configuredProps.configurationProperties, "isBackground");
    assignProperty(resultConfigProps, configuredProps.configurationProperties, "dependsOn");
    assignProperty(resultConfigProps, configuredProps.configurationProperties, "problemMatchers");
    assignProperty(resultConfigProps, configuredProps.configurationProperties, "promptOnClose");
    assignProperty(resultConfigProps, configuredProps.configurationProperties, "detail");
    result.command.presentation = CommandConfiguration.PresentationOptions.assignProperties(result.command.presentation, configuredProps.configurationProperties.presentation);
    result.command.options = CommandOptions2.assignProperties(result.command.options, configuredProps.configurationProperties.options);
    result.runOptions = RunOptions2.assignProperties(result.runOptions, configuredProps.runOptions);
    const contributedConfigProps = contributedTask.configurationProperties;
    fillProperty(resultConfigProps, contributedConfigProps, "group");
    fillProperty(resultConfigProps, contributedConfigProps, "isBackground");
    fillProperty(resultConfigProps, contributedConfigProps, "dependsOn");
    fillProperty(resultConfigProps, contributedConfigProps, "problemMatchers");
    fillProperty(resultConfigProps, contributedConfigProps, "promptOnClose");
    fillProperty(resultConfigProps, contributedConfigProps, "detail");
    result.command.presentation = CommandConfiguration.PresentationOptions.fillProperties(result.command.presentation, contributedConfigProps.presentation);
    result.command.options = CommandOptions2.fillProperties(result.command.options, contributedConfigProps.options);
    result.runOptions = RunOptions2.fillProperties(result.runOptions, contributedTask.runOptions);
    if (contributedTask.hasDefinedMatchers === true) {
      result.hasDefinedMatchers = true;
    }
    return result;
  }
  CustomTask2.createCustomTask = createCustomTask;
})(CustomTask || (CustomTask = {}));
var TaskParser;
(function(TaskParser2) {
  function isCustomTask(value) {
    const type = value.type;
    const customize2 = value.customize;
    return customize2 === void 0 && (type === void 0 || type === null || type === $eQ || type === "shell" || type === "process");
  }
  const builtinTypeContextMap = {
    shell: $XSb,
    process: $ZSb
  };
  function from(externals, globals, context, source, registry4) {
    const result = { custom: [], configured: [] };
    if (!externals) {
      return result;
    }
    const defaultBuildTask = { task: void 0, rank: -1 };
    const defaultTestTask = { task: void 0, rank: -1 };
    const schema2_0_0 = context.schemaVersion === 2;
    const baseLoadIssues = $Lv(context.taskLoadIssues);
    for (let index = 0; index < externals.length; index++) {
      const external = externals[index];
      const definition = external.type ? registry4?.get?.(external.type) || $aQ.get(external.type) : void 0;
      let typeNotSupported = false;
      if (definition && definition.when && !context.contextKeyService.contextMatchesRules(definition.when)) {
        typeNotSupported = true;
      } else if (!definition && external.type) {
        for (const key2 of Object.keys(builtinTypeContextMap)) {
          if (external.type === key2) {
            typeNotSupported = !$XSb.evaluate(context.contextKeyService.getContext(null));
            break;
          }
        }
      }
      if (typeNotSupported) {
        context.problemReporter.info(localize(10343, null, external.type));
        continue;
      }
      if (isCustomTask(external)) {
        const customTask = CustomTask.from(external, context, index, source);
        if (customTask) {
          CustomTask.fillGlobals(customTask, globals);
          CustomTask.fillDefaults(customTask, context);
          if (schema2_0_0) {
            if ((customTask.command === void 0 || customTask.command.name === void 0) && (customTask.configurationProperties.dependsOn === void 0 || customTask.configurationProperties.dependsOn.length === 0)) {
              context.problemReporter.error(localize(10344, null, customTask.configurationProperties.name, JSON.stringify(external, void 0, 4)));
              continue;
            }
          } else {
            if (customTask.command === void 0 || customTask.command.name === void 0) {
              context.problemReporter.warn(localize(10345, null, customTask.configurationProperties.name, JSON.stringify(external, void 0, 4)));
              continue;
            }
          }
          if (customTask.configurationProperties.group === TaskGroup.Build && defaultBuildTask.rank < 2) {
            defaultBuildTask.task = customTask;
            defaultBuildTask.rank = 2;
          } else if (customTask.configurationProperties.group === TaskGroup.Test && defaultTestTask.rank < 2) {
            defaultTestTask.task = customTask;
            defaultTestTask.rank = 2;
          } else if (customTask.configurationProperties.name === "build" && defaultBuildTask.rank < 1) {
            defaultBuildTask.task = customTask;
            defaultBuildTask.rank = 1;
          } else if (customTask.configurationProperties.name === "test" && defaultTestTask.rank < 1) {
            defaultTestTask.task = customTask;
            defaultTestTask.rank = 1;
          }
          customTask.addTaskLoadMessages(context.taskLoadIssues);
          result.custom.push(customTask);
        }
      } else {
        const configuredTask = ConfiguringTask.from(external, context, index, source, registry4);
        if (configuredTask) {
          configuredTask.addTaskLoadMessages(context.taskLoadIssues);
          result.configured.push(configuredTask);
        }
      }
      context.taskLoadIssues = $Lv(baseLoadIssues);
    }
    const defaultBuildGroupName = $zg(defaultBuildTask.task?.configurationProperties.group) ? defaultBuildTask.task?.configurationProperties.group : defaultBuildTask.task?.configurationProperties.group?._id;
    const defaultTestTaskGroupName = $zg(defaultTestTask.task?.configurationProperties.group) ? defaultTestTask.task?.configurationProperties.group : defaultTestTask.task?.configurationProperties.group?._id;
    if (defaultBuildGroupName !== TaskGroup.Build._id && defaultBuildTask.rank > -1 && defaultBuildTask.rank < 2 && defaultBuildTask.task) {
      defaultBuildTask.task.configurationProperties.group = TaskGroup.Build;
    } else if (defaultTestTaskGroupName !== TaskGroup.Test._id && defaultTestTask.rank > -1 && defaultTestTask.rank < 2 && defaultTestTask.task) {
      defaultTestTask.task.configurationProperties.group = TaskGroup.Test;
    }
    return result;
  }
  TaskParser2.from = from;
  function assignTasks(target, source) {
    if (source === void 0 || source.length === 0) {
      return target;
    }
    if (target === void 0 || target.length === 0) {
      return source;
    }
    if (source) {
      const map = /* @__PURE__ */ Object.create(null);
      target.forEach((task) => {
        map[task.configurationProperties.name] = task;
      });
      source.forEach((task) => {
        map[task.configurationProperties.name] = task;
      });
      const newTarget = [];
      target.forEach((task) => {
        newTarget.push(map[task.configurationProperties.name]);
        delete map[task.configurationProperties.name];
      });
      Object.keys(map).forEach((key2) => newTarget.push(map[key2]));
      target = newTarget;
    }
    return target;
  }
  TaskParser2.assignTasks = assignTasks;
})(TaskParser || (TaskParser = {}));
var Globals;
(function(Globals2) {
  function from(config, context) {
    let result = fromBase(config, context);
    let osGlobals = void 0;
    if (config.windows && context.platform === 3) {
      osGlobals = fromBase(config.windows, context);
    } else if (config.osx && context.platform === 1) {
      osGlobals = fromBase(config.osx, context);
    } else if (config.linux && context.platform === 2) {
      osGlobals = fromBase(config.linux, context);
    }
    if (osGlobals) {
      result = Globals2.assignProperties(result, osGlobals);
    }
    const command4 = CommandConfiguration.from(config, context);
    if (command4) {
      result.command = command4;
    }
    Globals2.fillDefaults(result, context);
    Globals2.freeze(result);
    return result;
  }
  Globals2.from = from;
  function fromBase(config, context) {
    const result = {};
    if (config.suppressTaskName !== void 0) {
      result.suppressTaskName = !!config.suppressTaskName;
    }
    if (config.promptOnClose !== void 0) {
      result.promptOnClose = !!config.promptOnClose;
    }
    if (config.problemMatcher) {
      result.problemMatcher = ProblemMatcherConverter.from(config.problemMatcher, context).value;
    }
    return result;
  }
  Globals2.fromBase = fromBase;
  function isEmpty(value) {
    return !value || value.command === void 0 && value.promptOnClose === void 0 && value.suppressTaskName === void 0;
  }
  Globals2.isEmpty = isEmpty;
  function assignProperties(target, source) {
    if (isEmpty(source)) {
      return target;
    }
    if (isEmpty(target)) {
      return source;
    }
    assignProperty(target, source, "promptOnClose");
    assignProperty(target, source, "suppressTaskName");
    return target;
  }
  Globals2.assignProperties = assignProperties;
  function fillDefaults(value, context) {
    if (!value) {
      return;
    }
    CommandConfiguration.fillDefaults(value.command, context);
    if (value.suppressTaskName === void 0) {
      value.suppressTaskName = context.schemaVersion === 2;
    }
    if (value.promptOnClose === void 0) {
      value.promptOnClose = true;
    }
  }
  Globals2.fillDefaults = fillDefaults;
  function freeze3(value) {
    Object.freeze(value);
    if (value.command) {
      CommandConfiguration.freeze(value.command);
    }
  }
  Globals2.freeze = freeze3;
})(Globals || (Globals = {}));
var ExecutionEngine2;
(function(ExecutionEngine3) {
  function from(config) {
    const runner = config.runner || config._runner;
    let result;
    if (runner) {
      switch (runner) {
        case "terminal":
          result = ExecutionEngine.Terminal;
          break;
        case "process":
          result = ExecutionEngine.Process;
          break;
      }
    }
    const schemaVersion = JsonSchemaVersion2.from(config);
    if (schemaVersion === 1) {
      return result || ExecutionEngine.Process;
    } else if (schemaVersion === 2) {
      return ExecutionEngine.Terminal;
    } else {
      throw new Error("Shouldn't happen.");
    }
  }
  ExecutionEngine3.from = from;
})(ExecutionEngine2 || (ExecutionEngine2 = {}));
var JsonSchemaVersion2;
(function(JsonSchemaVersion3) {
  const _default = 2;
  function from(config) {
    const version2 = config.version;
    if (!version2) {
      return _default;
    }
    switch (version2) {
      case "0.1.0":
        return 1;
      case "2.0.0":
        return 2;
      default:
        return _default;
    }
  }
  JsonSchemaVersion3.from = from;
})(JsonSchemaVersion2 || (JsonSchemaVersion2 = {}));
var $rhc = class {
  constructor(other) {
    this.b = /* @__PURE__ */ Object.create(null);
    if (other) {
      for (const key2 of Object.keys(other.b)) {
        const value = other.b[key2];
        if (Array.isArray(value)) {
          this.b[key2] = value.slice();
        } else {
          this.b[key2] = value;
        }
      }
    }
  }
  start() {
    this.a = this.b;
    this.b = /* @__PURE__ */ Object.create(null);
  }
  getUUID(identifier2) {
    const lastValue = this.a ? this.a[identifier2] : void 0;
    let result = void 0;
    if (lastValue !== void 0) {
      if (Array.isArray(lastValue)) {
        result = lastValue.shift();
        if (lastValue.length === 0) {
          delete this.a[identifier2];
        }
      } else {
        result = lastValue;
        delete this.a[identifier2];
      }
    }
    if (result === void 0) {
      result = $ps();
    }
    const currentValue = this.b[identifier2];
    if (currentValue === void 0) {
      this.b[identifier2] = result;
    } else {
      if (Array.isArray(currentValue)) {
        currentValue.push(result);
      } else {
        const arrayValue = [currentValue];
        arrayValue.push(result);
        this.b[identifier2] = arrayValue;
      }
    }
    return result;
  }
  finish() {
    this.a = void 0;
  }
};
var TaskConfigSource;
(function(TaskConfigSource2) {
  TaskConfigSource2[TaskConfigSource2["TasksJson"] = 0] = "TasksJson";
  TaskConfigSource2[TaskConfigSource2["WorkspaceFile"] = 1] = "WorkspaceFile";
  TaskConfigSource2[TaskConfigSource2["User"] = 2] = "User";
})(TaskConfigSource || (TaskConfigSource = {}));
var ConfigurationParser = class {
  constructor(workspaceFolder, workspace2, platform, problemReporter, uuidMap) {
    this.a = workspaceFolder;
    this.b = workspace2;
    this.e = platform;
    this.c = problemReporter;
    this.d = uuidMap;
  }
  run(fileConfig, source, contextKeyService) {
    const engine = ExecutionEngine2.from(fileConfig);
    const schemaVersion = JsonSchemaVersion2.from(fileConfig);
    const context = {
      workspaceFolder: this.a,
      workspace: this.b,
      problemReporter: this.c,
      uuidMap: this.d,
      namedProblemMatchers: {},
      engine,
      schemaVersion,
      platform: this.e,
      taskLoadIssues: [],
      contextKeyService
    };
    const taskParseResult = this.f(fileConfig, context, source);
    return {
      validationStatus: this.c.status,
      custom: taskParseResult.custom,
      configured: taskParseResult.configured,
      engine
    };
  }
  f(fileConfig, context, source) {
    const globals = Globals.from(fileConfig, context);
    if (this.c.status.isFatal()) {
      return { custom: [], configured: [] };
    }
    context.namedProblemMatchers = ProblemMatcherConverter.namedFrom(fileConfig.declares, context);
    let globalTasks = void 0;
    let externalGlobalTasks = void 0;
    if (fileConfig.windows && context.platform === 3) {
      globalTasks = TaskParser.from(fileConfig.windows.tasks, globals, context, source).custom;
      externalGlobalTasks = fileConfig.windows.tasks;
    } else if (fileConfig.osx && context.platform === 1) {
      globalTasks = TaskParser.from(fileConfig.osx.tasks, globals, context, source).custom;
      externalGlobalTasks = fileConfig.osx.tasks;
    } else if (fileConfig.linux && context.platform === 2) {
      globalTasks = TaskParser.from(fileConfig.linux.tasks, globals, context, source).custom;
      externalGlobalTasks = fileConfig.linux.tasks;
    }
    if (context.schemaVersion === 2 && globalTasks && globalTasks.length > 0 && externalGlobalTasks && externalGlobalTasks.length > 0) {
      const taskContent = [];
      for (const task of externalGlobalTasks) {
        taskContent.push(JSON.stringify(task, null, 4));
      }
      context.problemReporter.error(localize(10346, null, taskContent.join("\n")));
    }
    let result = { custom: [], configured: [] };
    if (fileConfig.tasks) {
      result = TaskParser.from(fileConfig.tasks, globals, context, source);
    }
    if (globalTasks) {
      result.custom = TaskParser.assignTasks(result.custom, globalTasks);
    }
    if ((!result.custom || result.custom.length === 0) && (globals.command && globals.command.name)) {
      const matchers = ProblemMatcherConverter.from(fileConfig.problemMatcher, context).value ?? [];
      const isBackground = fileConfig.isBackground ? !!fileConfig.isBackground : fileConfig.isWatching ? !!fileConfig.isWatching : void 0;
      const name = CommandString.value(globals.command.name);
      const task = new $gQ(context.uuidMap.getUUID(name), Object.assign({}, source, "workspace", { config: { index: -1, element: fileConfig, workspaceFolder: context.workspaceFolder } }), name, $eQ, {
        name: void 0,
        runtime: void 0,
        presentation: void 0,
        suppressTaskName: true
      }, false, { reevaluateOnRerun: true }, {
        name,
        identifier: name,
        group: TaskGroup.Build,
        isBackground,
        problemMatchers: matchers
      });
      const taskGroupKind = GroupKind.from(fileConfig.group);
      if (taskGroupKind !== void 0) {
        task.configurationProperties.group = taskGroupKind;
      } else if (fileConfig.group === "none") {
        task.configurationProperties.group = void 0;
      }
      CustomTask.fillGlobals(task, globals);
      CustomTask.fillDefaults(task, context);
      result.custom = [task];
    }
    result.custom = result.custom || [];
    result.configured = result.configured || [];
    return result;
  }
};
var uuidMaps = /* @__PURE__ */ new Map();
var recentUuidMaps = /* @__PURE__ */ new Map();
function $shc(workspaceFolder, workspace2, platform, configuration2, logger2, source, contextKeyService, isRecents = false) {
  const recentOrOtherMaps = isRecents ? recentUuidMaps : uuidMaps;
  let selectedUuidMaps = recentOrOtherMaps.get(source);
  if (!selectedUuidMaps) {
    recentOrOtherMaps.set(source, /* @__PURE__ */ new Map());
    selectedUuidMaps = recentOrOtherMaps.get(source);
  }
  let uuidMap = selectedUuidMaps.get(workspaceFolder.uri.toString());
  if (!uuidMap) {
    uuidMap = new $rhc();
    selectedUuidMaps.set(workspaceFolder.uri.toString(), uuidMap);
  }
  try {
    uuidMap.start();
    return new ConfigurationParser(workspaceFolder, workspace2, platform, logger2, uuidMap).run(configuration2, source, contextKeyService);
  } finally {
    uuidMap.finish();
  }
}
function $thc(contributedTask, configuredProps) {
  return CustomTask.createCustomTask(contributedTask, configuredProps);
}

// out-build/vs/workbench/contrib/tasks/common/problemCollectors.js
var ProblemCollectorEventKind;
(function(ProblemCollectorEventKind2) {
  ProblemCollectorEventKind2["BackgroundProcessingBegins"] = "backgroundProcessingBegins";
  ProblemCollectorEventKind2["BackgroundProcessingEnds"] = "backgroundProcessingEnds";
})(ProblemCollectorEventKind || (ProblemCollectorEventKind = {}));
var IProblemCollectorEvent;
(function(IProblemCollectorEvent2) {
  function create2(kind) {
    return Object.freeze({ kind });
  }
  IProblemCollectorEvent2.create = create2;
})(IProblemCollectorEvent || (IProblemCollectorEvent = {}));
var $uhc = class extends $3c {
  constructor(problemMatchers, D, F, fileService) {
    super();
    this.problemMatchers = problemMatchers;
    this.D = D;
    this.F = F;
    this.m = new $2c();
    this.y = new $ze();
    this.onDidFindFirstMatch = this.y.event;
    this.z = new $ze();
    this.onDidFindErrors = this.z.event;
    this.C = new $ze();
    this.onDidRequestInvalidateLastMarker = this.C.event;
    this.a = /* @__PURE__ */ Object.create(null);
    this.h = 1;
    problemMatchers.map((elem) => $7P(elem, fileService)).forEach((matcher) => {
      const length = matcher.matchLength;
      if (length > this.h) {
        this.h = length;
      }
      let value = this.a[length];
      if (!value) {
        value = [];
        this.a[length] = value;
      }
      value.push(matcher);
    });
    this.g = [];
    this.b = null;
    this.c = 0;
    this.f = void 0;
    this.j = /* @__PURE__ */ Object.create(null);
    this.r = /* @__PURE__ */ new Map();
    for (const problemMatcher of problemMatchers) {
      const current = this.r.get(problemMatcher.owner);
      if (current === void 0) {
        this.r.set(problemMatcher.owner, problemMatcher.applyTo);
      } else {
        this.r.set(problemMatcher.owner, this.J(current, problemMatcher.applyTo));
      }
    }
    this.s = /* @__PURE__ */ new Map();
    this.t = /* @__PURE__ */ new Map();
    this.u = /* @__PURE__ */ new Map();
    this.B(this.F.onModelAdded((model) => {
      this.j[model.uri.toString()] = true;
    }, this, this.m));
    this.B(this.F.onModelRemoved((model) => {
      delete this.j[model.uri.toString()];
    }, this, this.m));
    this.F.getModels().forEach((model) => this.j[model.uri.toString()] = true);
    this.w = new $ze();
  }
  get onDidStateChange() {
    return this.w.event;
  }
  processLine(line) {
    if (this.n) {
      const oldTail = this.n;
      this.n = oldTail.then(() => {
        return this.G(line);
      });
    } else {
      this.n = this.G(line);
    }
  }
  dispose() {
    super.dispose();
    this.m.dispose();
  }
  get numberOfMatches() {
    return this.c;
  }
  get maxMarkerSeverity() {
    return this.f;
  }
  H(line) {
    let result = null;
    if (this.b) {
      result = this.b.next(line);
      if (result) {
        this.M(result);
        return result;
      }
      this.N();
      this.b = null;
    }
    if (this.g.length < this.h) {
      this.g.push(line);
    } else {
      const end = this.g.length - 1;
      for (let i2 = 0; i2 < end; i2++) {
        this.g[i2] = this.g[i2 + 1];
      }
      this.g[end] = line;
    }
    result = this.L();
    if (result) {
      this.N();
    }
    return result;
  }
  async I(result) {
    switch (result.description.applyTo) {
      case ApplyToKind.allDocuments:
        return true;
      case ApplyToKind.openDocuments:
        return !!this.j[(await result.resource).toString()];
      case ApplyToKind.closedDocuments:
        return !this.j[(await result.resource).toString()];
      default:
        return true;
    }
  }
  J(current, value) {
    if (current === value || current === ApplyToKind.allDocuments) {
      return current;
    }
    return ApplyToKind.allDocuments;
  }
  L() {
    this.b = null;
    const length = this.g.length;
    for (let startIndex = 0; startIndex < length; startIndex++) {
      const candidates = this.a[length - startIndex];
      if (!candidates) {
        continue;
      }
      for (const matcher of candidates) {
        const result = matcher.handle(this.g, startIndex);
        if (result.match) {
          this.M(result.match);
          if (result.continue) {
            this.b = matcher;
          }
          return result.match;
        }
      }
    }
    return null;
  }
  M(match) {
    this.c++;
    if (this.f === void 0 || match.marker.severity > this.f) {
      this.f = match.marker.severity;
    }
  }
  N() {
    if (this.g.length > 0) {
      this.g = [];
    }
  }
  O(owner) {
    const resourceSetToClean = this.R(owner);
    this.D.read({ owner }).forEach((marker) => resourceSetToClean.set(marker.resource.toString(), marker.resource));
  }
  P(owner, resource) {
    this.R(owner).set(resource.toString(), resource);
  }
  Q(owner, resource) {
    const resourceSet = this.s.get(owner);
    resourceSet?.delete(resource);
  }
  R(owner) {
    let result = this.s.get(owner);
    if (!result) {
      result = /* @__PURE__ */ new Map();
      this.s.set(owner, result);
    }
    return result;
  }
  S() {
    this.s.forEach((value, owner) => {
      this.W(owner, value);
    });
    this.s = /* @__PURE__ */ new Map();
  }
  U(owner) {
    const toClean = this.s.get(owner);
    if (toClean) {
      this.W(owner, toClean);
      this.s.delete(owner);
    }
  }
  W(owner, toClean) {
    const uris = [];
    const applyTo = this.r.get(owner);
    toClean.forEach((uri, uriAsString) => {
      if (applyTo === ApplyToKind.allDocuments || applyTo === ApplyToKind.openDocuments && this.j[uriAsString] || applyTo === ApplyToKind.closedDocuments && !this.j[uriAsString]) {
        uris.push(uri);
      }
    });
    this.D.remove(owner, uris);
  }
  X(marker, owner, resourceAsString) {
    let markersPerOwner = this.t.get(owner);
    if (!markersPerOwner) {
      markersPerOwner = /* @__PURE__ */ new Map();
      this.t.set(owner, markersPerOwner);
    }
    let markersPerResource = markersPerOwner.get(resourceAsString);
    if (!markersPerResource) {
      markersPerResource = /* @__PURE__ */ new Map();
      markersPerOwner.set(resourceAsString, markersPerResource);
    }
    const key2 = IMarkerData.makeKeyOptionalMessage(marker, false);
    let existingMarker;
    if (!markersPerResource.has(key2)) {
      markersPerResource.set(key2, marker);
    } else if ((existingMarker = markersPerResource.get(key2)) !== void 0 && existingMarker.message.length < marker.message.length && $l) {
      markersPerResource.set(key2, marker);
    }
  }
  Y() {
    this.t.forEach((markersPerOwner, owner) => {
      const deliveredMarkersPerOwner = this.ab(owner);
      markersPerOwner.forEach((markers, resource) => {
        this.$(owner, resource, markers, deliveredMarkersPerOwner);
      });
    });
  }
  Z(owner, resource) {
    const markersPerOwner = this.t.get(owner);
    if (!markersPerOwner) {
      return;
    }
    const deliveredMarkersPerOwner = this.ab(owner);
    const markersPerResource = markersPerOwner.get(resource);
    if (!markersPerResource) {
      return;
    }
    this.$(owner, resource, markersPerResource, deliveredMarkersPerOwner);
  }
  $(owner, resource, markers, reported) {
    if (markers.size !== reported.get(resource)) {
      const toSet = [];
      markers.forEach((value) => toSet.push(value));
      this.D.changeOne(owner, URI.parse(resource), toSet);
      reported.set(resource, markers.size);
    }
  }
  ab(owner) {
    let result = this.u.get(owner);
    if (!result) {
      result = /* @__PURE__ */ new Map();
      this.u.set(owner, result);
    }
    return result;
  }
  bb() {
    this.c = 0;
    this.f = void 0;
    this.t.clear();
    this.u.clear();
  }
  done() {
    this.Y();
    this.S();
  }
};
var ProblemHandlingStrategy;
(function(ProblemHandlingStrategy2) {
  ProblemHandlingStrategy2[ProblemHandlingStrategy2["Clean"] = 0] = "Clean";
})(ProblemHandlingStrategy || (ProblemHandlingStrategy = {}));
var $vhc = class extends $uhc {
  constructor(problemMatchers, markerService, modelService, _strategy = 0, fileService) {
    super(problemMatchers, markerService, modelService, fileService);
    const ownerSet = /* @__PURE__ */ Object.create(null);
    problemMatchers.forEach((description) => ownerSet[description.owner] = true);
    this.cb = Object.keys(ownerSet);
    this.cb.forEach((owner) => {
      this.O(owner);
    });
  }
  async G(line) {
    const markerMatch = this.H(line);
    if (!markerMatch) {
      return;
    }
    const owner = markerMatch.description.owner;
    const resource = await markerMatch.resource;
    const resourceAsString = resource.toString();
    this.Q(owner, resourceAsString);
    const shouldApplyMatch = await this.I(markerMatch);
    if (shouldApplyMatch) {
      this.X(markerMatch.marker, owner, resourceAsString);
      if (this.db !== owner || this.eb !== resourceAsString) {
        if (this.db && this.eb) {
          this.Z(this.db, this.eb);
        }
        this.db = owner;
        this.eb = resourceAsString;
      }
    }
  }
};
var $whc = class extends $uhc {
  constructor(problemMatchers, markerService, modelService, fileService) {
    super(problemMatchers, markerService, modelService, fileService);
    this.gb = [];
    this.beginPatterns = [];
    this.kb();
    this.cb = [];
    this.db = /* @__PURE__ */ new Set();
    this.problemMatchers.forEach((matcher) => {
      if (matcher.watching) {
        const key2 = $ps();
        this.cb.push({
          key: key2,
          matcher,
          begin: matcher.watching.beginsPattern,
          end: matcher.watching.endsPattern
        });
        this.beginPatterns.push(matcher.watching.beginsPattern.regexp);
      }
    });
    this.m.add(this.F.onModelRemoved((modelEvent) => {
      let markerChanged = Event2.debounce(this.D.onMarkerChanged, (last, e) => {
        return (last ?? []).concat(e);
      }, 500, false, true)(async (markerEvent) => {
        markerChanged?.dispose();
        markerChanged = void 0;
        if (!markerEvent || !markerEvent.includes(modelEvent.uri) || this.D.read({ resource: modelEvent.uri }).length !== 0) {
          return;
        }
        const oldLines = Array.from(this.gb);
        for (const line of oldLines) {
          await this.G(line);
        }
      });
      setTimeout(async () => {
        const _markerChanged = markerChanged;
        markerChanged = void 0;
        _markerChanged?.dispose();
      }, 600);
    }));
  }
  aboutToStart() {
    for (const background of this.cb) {
      if (background.matcher.watching && background.matcher.watching.activeOnStart) {
        this.db.add(background.key);
        this.w.fire(IProblemCollectorEvent.create(
          "backgroundProcessingBegins"
          /* ProblemCollectorEventKind.BackgroundProcessingBegins */
        ));
        this.O(background.matcher.owner);
      }
    }
  }
  async G(line) {
    if (await this.ib(line) || this.jb(line)) {
      return;
    }
    this.gb.push(line);
    const markerMatch = this.H(line);
    if (!markerMatch) {
      return;
    }
    const resource = await markerMatch.resource;
    const owner = markerMatch.description.owner;
    const resourceAsString = resource.toString();
    this.Q(owner, resourceAsString);
    const shouldApplyMatch = await this.I(markerMatch);
    if (shouldApplyMatch) {
      this.X(markerMatch.marker, owner, resourceAsString);
      if (this.eb !== owner || this.fb !== resourceAsString) {
        this.lb();
        this.eb = owner;
        this.fb = resourceAsString;
      }
    }
  }
  forceDelivery() {
    this.lb();
  }
  async ib(line) {
    let result = false;
    for (const background of this.cb) {
      const matches = background.begin.regexp.exec(line);
      if (matches) {
        if (this.db.has(background.key)) {
          continue;
        }
        this.db.add(background.key);
        result = true;
        this.y.fire();
        this.gb = [];
        this.gb.push(line);
        this.w.fire(IProblemCollectorEvent.create(
          "backgroundProcessingBegins"
          /* ProblemCollectorEventKind.BackgroundProcessingBegins */
        ));
        this.bb();
        this.kb();
        const owner = background.matcher.owner;
        const file = matches[background.begin.file];
        if (file) {
          const resource = $6P(file, background.matcher);
          this.P(owner, await resource);
        } else {
          this.O(owner);
        }
      }
    }
    return result;
  }
  jb(line) {
    let result = false;
    for (const background of this.cb) {
      const matches = background.end.regexp.exec(line);
      if (matches) {
        if (this.c > 0) {
          this.z.fire();
        } else {
          this.C.fire();
        }
        if (this.db.has(background.key)) {
          this.db.delete(background.key);
          this.kb();
          this.w.fire(IProblemCollectorEvent.create(
            "backgroundProcessingEnds"
            /* ProblemCollectorEventKind.BackgroundProcessingEnds */
          ));
          result = true;
          this.gb.push(line);
          const owner = background.matcher.owner;
          this.U(owner);
          this.bb();
        }
      }
    }
    return result;
  }
  kb() {
    this.lb();
    this.eb = void 0;
    this.fb = void 0;
  }
  lb() {
    if (this.eb && this.fb) {
      this.Z(this.eb, this.fb);
    }
  }
  done() {
    [...this.r.keys()].forEach((owner) => {
      this.O(owner);
    });
    super.done();
  }
  isWatching() {
    return this.cb.length > 0;
  }
};

// out-build/vs/workbench/contrib/tasks/browser/taskTerminalStatus.js
var TASK_TERMINAL_STATUS_ID = "task_terminal_status";
var $xhc = { id: TASK_TERMINAL_STATUS_ID, icon: $ds, severity: severity_default.Info, tooltip: localize(10108, null) };
var $yhc = { id: TASK_TERMINAL_STATUS_ID, icon: $6l.check, severity: severity_default.Info, tooltip: localize(10109, null) };
var SUCCEEDED_INACTIVE_TASK_STATUS = { id: TASK_TERMINAL_STATUS_ID, icon: $6l.check, severity: severity_default.Info, tooltip: localize(10110, null) };
var $zhc = { id: TASK_TERMINAL_STATUS_ID, icon: $6l.error, severity: severity_default.Error, tooltip: localize(10111, null) };
var FAILED_INACTIVE_TASK_STATUS = { id: TASK_TERMINAL_STATUS_ID, icon: $6l.error, severity: severity_default.Error, tooltip: localize(10112, null) };
var WARNING_TASK_STATUS = { id: TASK_TERMINAL_STATUS_ID, icon: $6l.warning, severity: severity_default.Warning, tooltip: localize(10113, null) };
var WARNING_INACTIVE_TASK_STATUS = { id: TASK_TERMINAL_STATUS_ID, icon: $6l.warning, severity: severity_default.Warning, tooltip: localize(10114, null) };
var INFO_TASK_STATUS = { id: TASK_TERMINAL_STATUS_ID, icon: $6l.info, severity: severity_default.Info, tooltip: localize(10115, null) };
var INFO_INACTIVE_TASK_STATUS = { id: TASK_TERMINAL_STATUS_ID, icon: $6l.info, severity: severity_default.Info, tooltip: localize(10116, null) };
var $Ahc = class $Ahc2 extends $3c {
  constructor(taskService, c) {
    super();
    this.c = c;
    this.a = /* @__PURE__ */ new Map();
    this.B(taskService.onDidStateChange((event) => {
      switch (event.kind) {
        case "processStarted":
        case "active":
          this.j(event);
          break;
        case "inactive":
          this.h(event);
          break;
        case "processEnded":
          this.g(event);
          break;
      }
    }));
    this.B($1c(() => {
      for (const terminalData of this.a.values()) {
        terminalData.disposeListener?.dispose();
      }
      this.a.clear();
    }));
  }
  addTerminal(task, terminal2, problemMatcher) {
    const status = { id: TASK_TERMINAL_STATUS_ID, severity: severity_default.Info };
    terminal2.statusList.add(status);
    this.B(problemMatcher.onDidFindFirstMatch(() => {
      this.b = terminal2.registerMarker();
      if (this.b) {
        this.B(this.b);
      }
    }));
    this.B(problemMatcher.onDidFindErrors(() => {
      if (this.b) {
        terminal2.addBufferMarker({ marker: this.b, hoverMessage: localize(10117, null), disableCommandStorage: true });
      }
    }));
    this.B(problemMatcher.onDidRequestInvalidateLastMarker(() => {
      this.b?.dispose();
      this.b = void 0;
    }));
    this.a.set(terminal2.instanceId, { terminal: terminal2, task, status, problemMatcher, taskRunEnded: false });
  }
  f(event) {
    if (!("terminalId" in event) || !event.terminalId) {
      return void 0;
    }
    return this.a.get(event.terminalId);
  }
  g(event) {
    const terminalData = this.f(event);
    if (!terminalData) {
      return;
    }
    terminalData.taskRunEnded = true;
    terminalData.terminal.statusList.remove(terminalData.status);
    if (event.exitCode === 0 && terminalData.problemMatcher.numberOfMatches === 0) {
      this.c.playSignal($N9.taskCompleted);
      if (terminalData.task.configurationProperties.isBackground) {
        for (const status of terminalData.terminal.statusList.statuses) {
          terminalData.terminal.statusList.remove(status);
        }
      } else {
        terminalData.terminal.statusList.add($yhc);
      }
    } else if (event.exitCode || terminalData.problemMatcher.maxMarkerSeverity === MarkerSeverity.Error) {
      this.c.playSignal($N9.taskFailed);
      terminalData.terminal.statusList.add($zhc);
    } else if (terminalData.problemMatcher.maxMarkerSeverity === MarkerSeverity.Warning) {
      terminalData.terminal.statusList.add(WARNING_TASK_STATUS);
    } else if (terminalData.problemMatcher.maxMarkerSeverity === MarkerSeverity.Info) {
      terminalData.terminal.statusList.add(INFO_TASK_STATUS);
    }
  }
  h(event) {
    const terminalData = this.f(event);
    if (!terminalData || !terminalData.problemMatcher || terminalData.taskRunEnded) {
      return;
    }
    terminalData.terminal.statusList.remove(terminalData.status);
    if (terminalData.problemMatcher.numberOfMatches === 0) {
      this.c.playSignal($N9.taskCompleted);
      terminalData.terminal.statusList.add(SUCCEEDED_INACTIVE_TASK_STATUS);
    } else if (terminalData.problemMatcher.maxMarkerSeverity === MarkerSeverity.Error) {
      this.c.playSignal($N9.taskFailed);
      terminalData.terminal.statusList.add(FAILED_INACTIVE_TASK_STATUS);
    } else if (terminalData.problemMatcher.maxMarkerSeverity === MarkerSeverity.Warning) {
      terminalData.terminal.statusList.add(WARNING_INACTIVE_TASK_STATUS);
    } else if (terminalData.problemMatcher.maxMarkerSeverity === MarkerSeverity.Info) {
      terminalData.terminal.statusList.add(INFO_INACTIVE_TASK_STATUS);
    }
  }
  j(event) {
    const terminalData = this.f(event);
    if (!terminalData) {
      return;
    }
    if (!terminalData.disposeListener) {
      terminalData.disposeListener = this.B(new $4c());
      terminalData.disposeListener.value = terminalData.terminal.onDisposed(() => {
        if (!event.terminalId) {
          return;
        }
        this.a.delete(event.terminalId);
        terminalData.disposeListener?.dispose();
      });
    }
    terminalData.taskRunEnded = false;
    terminalData.terminal.statusList.remove(terminalData.status);
    if (terminalData.problemMatcher instanceof $vhc || terminalData.problemMatcher?.problemMatchers.length > 0 || event.runType === "singleRun") {
      terminalData.terminal.statusList.add($xhc);
    }
  }
};
$Ahc = __decorate([
  __param(0, $3Sb),
  __param(1, $I9)
], $Ahc);

// out-build/vs/workbench/contrib/terminal/browser/terminalEscapeSequences.js
var ShellIntegrationOscPs2;
(function(ShellIntegrationOscPs3) {
  ShellIntegrationOscPs3[ShellIntegrationOscPs3["FinalTerm"] = 133] = "FinalTerm";
  ShellIntegrationOscPs3[ShellIntegrationOscPs3["VSCode"] = 633] = "VSCode";
  ShellIntegrationOscPs3[ShellIntegrationOscPs3["ITerm"] = 1337] = "ITerm";
})(ShellIntegrationOscPs2 || (ShellIntegrationOscPs2 = {}));
var VSCodeOscPt2;
(function(VSCodeOscPt3) {
  VSCodeOscPt3["PromptStart"] = "A";
  VSCodeOscPt3["CommandStart"] = "B";
  VSCodeOscPt3["CommandExecuted"] = "C";
  VSCodeOscPt3["CommandFinished"] = "D";
  VSCodeOscPt3["CommandLine"] = "E";
  VSCodeOscPt3["ContinuationStart"] = "F";
  VSCodeOscPt3["ContinuationEnd"] = "G";
  VSCodeOscPt3["RightPromptStart"] = "H";
  VSCodeOscPt3["RightPromptEnd"] = "I";
  VSCodeOscPt3["Property"] = "P";
})(VSCodeOscPt2 || (VSCodeOscPt2 = {}));
var VSCodeOscProperty;
(function(VSCodeOscProperty2) {
  VSCodeOscProperty2["Task"] = "Task";
  VSCodeOscProperty2["Cwd"] = "Cwd";
})(VSCodeOscProperty || (VSCodeOscProperty = {}));
var ITermOscPt2;
(function(ITermOscPt3) {
  ITermOscPt3["SetMark"] = "SetMark";
})(ITermOscPt2 || (ITermOscPt2 = {}));
function $Bhc(osc, data) {
  return oscSequence(633, osc, data);
}
function oscSequence(ps, pt, data) {
  let result = `\x1B]${ps};${pt}`;
  if (data) {
    result += `;${data}`;
  }
  result += `\x07`;
  return result;
}

// out-build/vs/workbench/contrib/tasks/browser/terminalTaskSystem.js
var ReconnectionType = "Task";
var VariableResolver = class _VariableResolver {
  static {
    this.b = /\$\{(.*?)\}/g;
  }
  constructor(workspaceFolder, taskSystemInfo, values, c) {
    this.workspaceFolder = workspaceFolder;
    this.taskSystemInfo = taskSystemInfo;
    this.values = values;
    this.c = c;
  }
  async resolve(value) {
    const replacers = [];
    value.replace(_VariableResolver.b, (match, ...args2) => {
      replacers.push(this.d(match, args2));
      return match;
    });
    const resolvedReplacers = await Promise.all(replacers);
    return value.replace(_VariableResolver.b, () => resolvedReplacers.shift());
  }
  async d(match, args2) {
    const result = this.values.get(match.substring(2, match.length - 1));
    if (result !== void 0 && result !== null) {
      return result;
    }
    if (this.c) {
      return this.c.resolveAsync(this.workspaceFolder, match);
    }
    return match;
  }
};
var VerifiedTask = class {
  constructor(task, resolver, trigger) {
    this.task = task;
    this.resolver = resolver;
    this.trigger = trigger;
  }
  verify() {
    let verified = false;
    if (this.trigger && this.resolvedVariables && this.workspaceFolder && this.shellLaunchConfig !== void 0) {
      verified = true;
    }
    return verified;
  }
  getVerifiedTask() {
    if (this.verify()) {
      return { task: this.task, resolver: this.resolver, trigger: this.trigger, resolvedVariables: this.resolvedVariables, systemInfo: this.systemInfo, workspaceFolder: this.workspaceFolder, shellLaunchConfig: this.shellLaunchConfig };
    } else {
      throw new Error("VerifiedTask was not checked. verify must be checked before getVerifiedTask.");
    }
  }
};
var $Dhc = class _$Dhc extends $3c {
  static {
    this.TelemetryEventName = "taskService";
  }
  static {
    this.b = "__process__";
  }
  static {
    this.c = {
      "cmd": {
        strong: '"'
      },
      "powershell": {
        escape: {
          escapeChar: "`",
          charsToEscape: ` "'()`
        },
        strong: "'",
        weak: '"'
      },
      "bash": {
        escape: {
          escapeChar: "\\",
          charsToEscape: ` "'`
        },
        strong: "'",
        weak: '"'
      },
      "zsh": {
        escape: {
          escapeChar: "\\",
          charsToEscape: ` "'`
        },
        strong: "'",
        weak: '"'
      }
    };
  }
  static {
    this.f = {
      "Linux": _$Dhc.c["bash"],
      "Mac": _$Dhc.c["bash"],
      "Windows": _$Dhc.c["powershell"]
    };
  }
  taskShellIntegrationStartSequence(cwd2) {
    return $Bhc(
      "A"
      /* VSCodeOscPt.PromptStart */
    ) + $Bhc("P", `${"Task"}=True`) + (cwd2 ? $Bhc("P", `${"Cwd"}=${typeof cwd2 === "string" ? cwd2 : cwd2.fsPath}`) : "") + $Bhc(
      "B"
      /* VSCodeOscPt.CommandStart */
    );
  }
  get taskShellIntegrationOutputSequence() {
    return $Bhc(
      "C"
      /* VSCodeOscPt.CommandExecuted */
    );
  }
  constructor(L, M, N, O, P, Q, R, S, U, W, X, Y, Z, $149, ab, bb, cb, instantiationService, taskSystemInfoResolver) {
    super();
    this.L = L;
    this.M = M;
    this.N = N;
    this.O = O;
    this.P = P;
    this.Q = Q;
    this.R = R;
    this.S = S;
    this.U = U;
    this.W = W;
    this.X = X;
    this.Y = Y;
    this.Z = Z;
    this.$ = $149;
    this.ab = ab;
    this.bb = bb;
    this.cb = cb;
    this.z = false;
    this.G = Promise.resolve();
    this.H = false;
    this.g = /* @__PURE__ */ Object.create(null);
    this.h = /* @__PURE__ */ Object.create(null);
    this.j = /* @__PURE__ */ Object.create(null);
    this.m = new $Gc();
    this.n = /* @__PURE__ */ Object.create(null);
    this.I = new $ze();
    this.u = taskSystemInfoResolver;
    this.B(this.F = instantiationService.createInstance($Ahc));
  }
  get onDidStateChange() {
    return this.I.event;
  }
  db(value) {
    this.Sb(value + "\n");
  }
  eb() {
    this.N.showChannel(this.X, true);
  }
  reconnect(task, resolver) {
    this.Db();
    return this.run(task, resolver, Triggers.reconnect);
  }
  run(task, resolver, trigger = Triggers.command) {
    task = task.clone();
    const instances = $jQ.is(task) || this.vb(task) ? [] : this.gb(task);
    const validInstance = instances.length < ((task.runOptions && task.runOptions.instanceLimit) ?? 1);
    const instance2 = instances[0]?.count?.count ?? 0;
    this.y = new VerifiedTask(task, resolver, trigger);
    if (instance2 > 0) {
      task.instance = instance2;
    }
    if (!validInstance) {
      const terminalData = instances[instances.length - 1];
      this.w = this.y;
      return { kind: 2, task: terminalData.task, active: { same: true, background: task.configurationProperties.isBackground }, promise: terminalData.promise };
    }
    try {
      const executeResult = { kind: 1, task, started: {}, promise: this.kb(task, resolver, trigger, /* @__PURE__ */ new Set(), /* @__PURE__ */ new Map(), void 0) };
      executeResult.promise.then((summary) => {
        this.w = this.y;
      });
      return executeResult;
    } catch (error) {
      if (error instanceof $VSb) {
        throw error;
      } else if (error instanceof Error) {
        this.db(error.message);
        throw new $VSb(
          severity_default.Error,
          error.message,
          7
          /* TaskErrors.UnknownError */
        );
      } else {
        this.db(error.toString());
        throw new $VSb(
          severity_default.Error,
          localize(10118, null),
          7
          /* TaskErrors.UnknownError */
        );
      }
    }
  }
  rerun() {
    if (this.w && this.w.verify()) {
      if (this.w.task.runOptions.reevaluateOnRerun !== void 0 && !this.w.task.runOptions.reevaluateOnRerun) {
        this.z = true;
      }
      const result = this.run(this.w.task, this.w.resolver);
      result.promise.then((summary) => {
        this.z = false;
      });
      return result;
    } else {
      return void 0;
    }
  }
  fb(task) {
    if (task.taskLoadMessages && task.taskLoadMessages.length > 0) {
      task.taskLoadMessages.forEach((loadMessage) => {
        this.db(loadMessage + "\n");
      });
      const openOutput = "Show Output";
      this.cb.prompt(severity_default.Warning, localize(10119, null, task._label), [{
        label: openOutput,
        run: () => this.eb()
      }]);
    }
  }
  isTaskVisible(task) {
    const terminalData = this.g[task.getMapKey()];
    if (!terminalData?.terminal) {
      return false;
    }
    const activeTerminalInstance = this.L.activeInstance;
    const isPanelShowingTerminal = !!this.P.getActiveViewWithId($7X);
    return isPanelShowingTerminal && activeTerminalInstance?.instanceId === terminalData.terminal.instanceId;
  }
  revealTask(task) {
    const terminalData = this.g[task.getMapKey()];
    if (!terminalData?.terminal) {
      return false;
    }
    const isTerminalInPanel = this.ab.getViewLocationById($7X) === 1;
    if (isTerminalInPanel && this.isTaskVisible(task)) {
      if (this.C) {
        if (this.D) {
          this.L.setActiveInstance(this.D);
        }
        this.O.openPaneComposite(
          this.C,
          1
          /* ViewContainerLocation.Panel */
        );
      } else {
        this.O.hideActivePaneComposite(
          1
          /* ViewContainerLocation.Panel */
        );
      }
      this.C = void 0;
      this.D = void 0;
    } else {
      if (isTerminalInPanel) {
        this.C = this.O.getActivePaneComposite(
          1
          /* ViewContainerLocation.Panel */
        )?.getId();
        if (this.C === $7X) {
          this.D = this.L.activeInstance ?? void 0;
        }
      }
      this.L.setActiveInstance(terminalData.terminal);
      if ($gQ.is(task) || $iQ.is(task)) {
        this.M.showPanel(task.command.presentation.focus);
      }
    }
    return true;
  }
  isActive() {
    return Promise.resolve(this.isActiveSync());
  }
  isActiveSync() {
    return Object.values(this.g).some((value) => !!value.terminal);
  }
  canAutoTerminate() {
    return Object.values(this.g).every((value) => !value.task.configurationProperties.promptOnClose);
  }
  getActiveTasks() {
    return Object.values(this.g).flatMap((value) => value.terminal ? value.task : []);
  }
  getLastInstance(task) {
    const recentKey = task.getKey();
    return Object.values(this.g).reverse().find((value) => recentKey && recentKey === value.task.getKey())?.task;
  }
  getBusyTasks() {
    return Object.keys(this.h).map((key2) => this.h[key2]);
  }
  customExecutionComplete(task, result) {
    const activeTerminal = this.g[task.getMapKey()];
    if (!activeTerminal?.terminal) {
      return Promise.reject(new Error("Expected to have a terminal for a custom execution task"));
    }
    return new Promise((resolve) => {
      resolve();
    });
  }
  gb(task) {
    const recentKey = task.getKey();
    return Object.values(this.g).filter((value) => recentKey && recentKey === value.task.getKey());
  }
  hb(task) {
    const key2 = typeof task === "string" ? task : task.getMapKey();
    const taskToRemove = this.g[key2];
    if (!taskToRemove) {
      return;
    }
    delete this.g[key2];
  }
  ib(event) {
    if (event.kind !== "changed") {
      const activeTask = this.g[event.__task.getMapKey()];
      if (activeTask) {
        activeTask.state = event.kind;
      }
    }
    this.I.fire(event);
  }
  terminate(task) {
    const activeTerminal = this.g[task.getMapKey()];
    if (!activeTerminal) {
      return Promise.resolve({ success: false, task: void 0 });
    }
    const terminal2 = activeTerminal.terminal;
    if (!terminal2) {
      return Promise.resolve({ success: false, task: void 0 });
    }
    return new Promise((resolve, reject) => {
      terminal2.onDisposed((terminal3) => {
        this.ib(TaskEvent.terminated(task, terminal3.instanceId, terminal3.exitReason));
      });
      const onExit = terminal2.onExit(() => {
        const task2 = activeTerminal.task;
        try {
          onExit.dispose();
          this.ib(TaskEvent.terminated(task2, terminal2.instanceId, terminal2.exitReason));
        } catch (error) {
        }
        resolve({ success: true, task: task2 });
      });
      terminal2.dispose();
    });
  }
  terminateAll() {
    const promises = [];
    for (const [key2, terminalData] of Object.entries(this.g)) {
      const terminal2 = terminalData?.terminal;
      if (terminal2) {
        promises.push(new Promise((resolve, reject) => {
          const onExit = terminal2.onExit(() => {
            const task = terminalData.task;
            try {
              onExit.dispose();
              this.ib(TaskEvent.terminated(task, terminal2.instanceId, terminal2.exitReason));
            } catch (error) {
            }
            if (this.g[key2] === terminalData) {
              delete this.g[key2];
            }
            resolve({ success: true, task: terminalData.task });
          });
        }));
        terminal2.dispose();
      }
    }
    return Promise.all(promises);
  }
  jb(task) {
    this.db(localize(10120, null, task._label));
    this.eb();
  }
  kb(task, resolver, trigger, liveDependencies, encounteredTasks, alreadyResolved) {
    this.fb(task);
    const mapKey = task.getMapKey();
    const promise = Promise.resolve().then(async () => {
      alreadyResolved = alreadyResolved ?? /* @__PURE__ */ new Map();
      const promises = [];
      if (task.configurationProperties.dependsOn) {
        const nextLiveDependencies = new Set(liveDependencies).add(task.getCommonTaskId());
        for (const dependency of task.configurationProperties.dependsOn) {
          const dependencyTask = await resolver.resolve(dependency.uri, dependency.task);
          if (dependencyTask) {
            this.mb(dependencyTask, task);
            let taskResult;
            const commonKey = dependencyTask.getCommonTaskId();
            if (nextLiveDependencies.has(commonKey)) {
              this.jb(dependencyTask);
              taskResult = Promise.resolve({});
            } else {
              taskResult = encounteredTasks.get(commonKey);
              if (!taskResult) {
                const activeTask2 = this.g[dependencyTask.getMapKey()] ?? this.gb(dependencyTask).pop();
                taskResult = activeTask2 && this.nb(activeTask2);
              }
            }
            if (!taskResult) {
              this.ib(TaskEvent.general("dependsOnStarted", task));
              taskResult = this.ob(dependencyTask, resolver, trigger, nextLiveDependencies, encounteredTasks, alreadyResolved);
            }
            encounteredTasks.set(commonKey, taskResult);
            promises.push(taskResult);
            if (task.configurationProperties.dependsOrder === "sequence") {
              const promiseResult = await taskResult;
              if (promiseResult.exitCode !== 0) {
                break;
              }
            }
          } else {
            this.db(localize(10121, null, $zg(dependency.task) ? dependency.task : JSON.stringify(dependency.task, void 0, 0), dependency.uri.toString()));
            this.eb();
          }
        }
      }
      return Promise.all(promises).then((summaries) => {
        for (const summary of summaries) {
          if (summary.exitCode !== 0) {
            return { exitCode: summary.exitCode };
          }
        }
        if (($iQ.is(task) || $gQ.is(task)) && task.command) {
          if (this.z) {
            return this.wb(task, trigger, alreadyResolved);
          } else {
            return this.ub(task, trigger, alreadyResolved);
          }
        }
        return { exitCode: 0 };
      });
    }).finally(() => {
      delete this.g[mapKey];
    });
    const lastInstance = this.gb(task).pop();
    const count = lastInstance?.count ?? { count: 0 };
    count.count++;
    const activeTask = { task, promise, count };
    this.g[mapKey] = activeTask;
    return promise;
  }
  lb(task) {
    return new Promise((resolve) => {
      const taskInactiveDisposable = this.onDidStateChange((taskEvent) => {
        if (taskEvent.kind === "inactive" && taskEvent.__task === task) {
          taskInactiveDisposable.dispose();
          resolve({ exitCode: 0 });
        }
      });
    });
  }
  mb(dependencyTask, task) {
    if (dependencyTask.configurationProperties.icon) {
      dependencyTask.configurationProperties.icon.id ||= task.configurationProperties.icon?.id;
      dependencyTask.configurationProperties.icon.color ||= task.configurationProperties.icon?.color;
    } else {
      dependencyTask.configurationProperties.icon = task.configurationProperties.icon;
    }
  }
  async nb(task) {
    if (!task.task.configurationProperties.isBackground) {
      return task.promise;
    }
    if (!task.task.configurationProperties.problemMatchers || task.task.configurationProperties.problemMatchers.length === 0) {
      return task.promise;
    }
    if (task.state === "inactive") {
      return { exitCode: 0 };
    }
    return this.lb(task.task);
  }
  async ob(task, resolver, trigger, liveDependencies, encounteredTasks, alreadyResolved) {
    if (!task.configurationProperties.isBackground) {
      return this.kb(task, resolver, trigger, liveDependencies, encounteredTasks, alreadyResolved);
    }
    const inactivePromise = this.lb(task);
    return Promise.race([inactivePromise, this.kb(task, resolver, trigger, liveDependencies, encounteredTasks, alreadyResolved)]);
  }
  async pb(systemInfo, workspaceFolder, task, cwd2, envPath) {
    const command4 = await this.S.resolveAsync(workspaceFolder, CommandString.value(task.command.name));
    cwd2 = cwd2 ? await this.S.resolveAsync(workspaceFolder, cwd2) : void 0;
    const paths = envPath ? await Promise.all(envPath.split($xc).map((p) => this.S.resolveAsync(workspaceFolder, p))) : void 0;
    let foundExecutable = await systemInfo?.findExecutable(command4, cwd2, paths);
    if (!foundExecutable) {
      foundExecutable = $nc(cwd2 ?? "", command4);
    }
    return foundExecutable;
  }
  qb(variables, alreadyResolved) {
    if (alreadyResolved.size === 0) {
      return variables;
    }
    const unresolved = /* @__PURE__ */ new Set();
    for (const variable of variables) {
      if (!alreadyResolved.has(variable.substring(2, variable.length - 1))) {
        unresolved.add(variable);
      }
    }
    return unresolved;
  }
  rb(mergeInto, mergeFrom) {
    for (const entry of mergeFrom) {
      if (!mergeInto.has(entry[0])) {
        mergeInto.set(entry[0], entry[1]);
      }
    }
  }
  async sb(taskSystemInfo, workspaceFolder, task, variables, alreadyResolved) {
    const resolved = await this.tb(taskSystemInfo, workspaceFolder, task, variables, alreadyResolved);
    this.ib(TaskEvent.general("acquiredInput", task));
    return resolved;
  }
  tb(taskSystemInfo, workspaceFolder, task, variables, alreadyResolved) {
    const isProcess = task.command && task.command.runtime === RuntimeType.Process;
    const options3 = task.command && task.command.options ? task.command.options : void 0;
    const cwd2 = options3 ? options3.cwd : void 0;
    let envPath = void 0;
    if (options3 && options3.env) {
      for (const key2 of Object.keys(options3.env)) {
        if (key2.toLowerCase() === "path") {
          if ($zg(options3.env[key2])) {
            envPath = options3.env[key2];
          }
          break;
        }
      }
    }
    const unresolved = this.qb(variables, alreadyResolved);
    let resolvedVariables;
    if (taskSystemInfo && workspaceFolder) {
      const resolveSet = {
        variables: unresolved
      };
      if (taskSystemInfo.platform === 3 && isProcess) {
        resolveSet.process = { name: CommandString.value(task.command.name) };
        if (cwd2) {
          resolveSet.process.cwd = cwd2;
        }
        if (envPath) {
          resolveSet.process.path = envPath;
        }
      }
      resolvedVariables = taskSystemInfo.resolveVariables(workspaceFolder, resolveSet, TaskSourceKind.toConfigurationTarget(task._source.kind)).then(async (resolved) => {
        if (!resolved) {
          return void 0;
        }
        this.rb(alreadyResolved, resolved.variables);
        resolved.variables = new Map(alreadyResolved);
        if (isProcess) {
          let process2 = CommandString.value(task.command.name);
          if (taskSystemInfo.platform === 3) {
            process2 = await this.pb(taskSystemInfo, workspaceFolder, task, cwd2, envPath);
          }
          resolved.variables.set(_$Dhc.b, process2);
        }
        return resolved;
      });
      return resolvedVariables;
    } else {
      const variablesArray = new Array();
      unresolved.forEach((variable) => variablesArray.push(variable));
      return new Promise((resolve, reject) => {
        this.S.resolveWithInteraction(workspaceFolder, variablesArray, "tasks", void 0, TaskSourceKind.toConfigurationTarget(task._source.kind)).then(async (resolvedVariablesMap) => {
          if (resolvedVariablesMap) {
            this.rb(alreadyResolved, resolvedVariablesMap);
            resolvedVariablesMap = new Map(alreadyResolved);
            if (isProcess) {
              let processVarValue;
              if ($l) {
                processVarValue = await this.pb(taskSystemInfo, workspaceFolder, task, cwd2, envPath);
              } else {
                processVarValue = await this.S.resolveAsync(workspaceFolder, CommandString.value(task.command.name));
              }
              resolvedVariablesMap.set(_$Dhc.b, processVarValue);
            }
            const resolvedVariablesResult = {
              variables: resolvedVariablesMap
            };
            resolve(resolvedVariablesResult);
          } else {
            resolve(void 0);
          }
        }, (reason) => {
          reject(reason);
        });
      });
    }
  }
  ub(task, trigger, alreadyResolved) {
    const taskWorkspaceFolder = task.getWorkspaceFolder();
    let workspaceFolder;
    if (taskWorkspaceFolder) {
      workspaceFolder = this.y.workspaceFolder = taskWorkspaceFolder;
    } else {
      const folders = this.U.getWorkspace().folders;
      workspaceFolder = folders.length > 0 ? folders[0] : void 0;
    }
    const systemInfo = this.y.systemInfo = this.u(workspaceFolder);
    const variables = /* @__PURE__ */ new Set();
    this.Ib(variables, task);
    const resolvedVariables = this.sb(systemInfo, workspaceFolder, task, variables, alreadyResolved);
    return resolvedVariables.then((resolvedVariables2) => {
      if (resolvedVariables2 && !this.vb(task)) {
        this.y.resolvedVariables = resolvedVariables2;
        return this.xb(task, trigger, new VariableResolver(workspaceFolder, systemInfo, resolvedVariables2.variables, this.S), workspaceFolder);
      } else {
        this.ib(TaskEvent.general("end", task));
        return Promise.resolve({ exitCode: 0 });
      }
    }, (reason) => {
      return Promise.reject(reason);
    });
  }
  vb(task) {
    const isCustomExecution = task.command.runtime === RuntimeType.CustomExecution;
    return !(task.command !== void 0 && task.command.runtime && (isCustomExecution || task.command.name !== void 0));
  }
  wb(task, trigger, alreadyResolved) {
    const lastTask = this.w;
    if (!lastTask) {
      return Promise.reject(new Error("No task previously run"));
    }
    const workspaceFolder = this.y.workspaceFolder = lastTask.workspaceFolder;
    const variables = /* @__PURE__ */ new Set();
    this.Ib(variables, task);
    let hasAllVariables = true;
    variables.forEach((value) => {
      if (value.substring(2, value.length - 1) in lastTask.getVerifiedTask().resolvedVariables) {
        hasAllVariables = false;
      }
    });
    if (!hasAllVariables) {
      return this.sb(lastTask.getVerifiedTask().systemInfo, lastTask.getVerifiedTask().workspaceFolder, task, variables, alreadyResolved).then((resolvedVariables) => {
        if (!resolvedVariables) {
          this.ib(TaskEvent.general("end", task));
          return { exitCode: 0 };
        }
        this.y.resolvedVariables = resolvedVariables;
        return this.xb(task, trigger, new VariableResolver(lastTask.getVerifiedTask().workspaceFolder, lastTask.getVerifiedTask().systemInfo, resolvedVariables.variables, this.S), workspaceFolder);
      }, (reason) => {
        return Promise.reject(reason);
      });
    } else {
      this.y.resolvedVariables = lastTask.getVerifiedTask().resolvedVariables;
      return this.xb(task, trigger, new VariableResolver(lastTask.getVerifiedTask().workspaceFolder, lastTask.getVerifiedTask().systemInfo, lastTask.getVerifiedTask().resolvedVariables.variables, this.S), workspaceFolder);
    }
  }
  async xb(task, trigger, resolver, workspaceFolder) {
    let terminal2 = void 0;
    let error = void 0;
    let promise = void 0;
    if (task.configurationProperties.isBackground) {
      const problemMatchers = await this.Pb(resolver, task.configurationProperties.problemMatchers);
      const watchingProblemMatcher = new $whc(problemMatchers, this.Q, this.R, this.Y);
      if (problemMatchers.length > 0 && !watchingProblemMatcher.isWatching()) {
        this.Sb(localize(10122, null, task._label));
        this.eb();
      }
      const toDispose = new $2c();
      let eventCounter = 0;
      const mapKey = task.getMapKey();
      toDispose.add(watchingProblemMatcher.onDidStateChange((event) => {
        if (event.kind === "backgroundProcessingBegins") {
          eventCounter++;
          this.h[mapKey] = task;
          this.ib(TaskEvent.general("active", task, terminal2?.instanceId));
        } else if (event.kind === "backgroundProcessingEnds") {
          eventCounter--;
          if (this.h[mapKey]) {
            delete this.h[mapKey];
          }
          this.ib(TaskEvent.general("inactive", task, terminal2?.instanceId));
          if (eventCounter === 0) {
            if (watchingProblemMatcher.numberOfMatches > 0 && watchingProblemMatcher.maxMarkerSeverity && watchingProblemMatcher.maxMarkerSeverity >= MarkerSeverity.Error) {
              const reveal = task.command.presentation.reveal;
              const revealProblems = task.command.presentation.revealProblems;
              if (revealProblems === RevealProblemKind.OnProblem) {
                this.P.openView(Markers.MARKERS_VIEW_ID, true);
              } else if (reveal === RevealKind.Silent) {
                this.L.setActiveInstance(terminal2);
                this.M.showPanel(false);
              }
            }
          }
        }
      }));
      watchingProblemMatcher.aboutToStart();
      let delayer4 = void 0;
      [terminal2, error] = await this.Fb(task, resolver, workspaceFolder);
      if (error) {
        return Promise.reject(new Error(error.message));
      }
      if (!terminal2) {
        return Promise.reject(new Error(`Failed to create terminal for task ${task._label}`));
      }
      this.F.addTerminal(task, terminal2, watchingProblemMatcher);
      let processStartedSignaled = false;
      terminal2.processReady.then(() => {
        if (!processStartedSignaled) {
          this.ib(TaskEvent.processStarted(task, terminal2.instanceId, terminal2.processId));
          processStartedSignaled = true;
        }
      }, (_error) => {
        this.bb.error("Task terminal process never got ready");
      });
      this.ib(TaskEvent.start(task, terminal2.instanceId, resolver.values));
      let onData;
      if (problemMatchers.length) {
        onData = terminal2.onLineData((line) => {
          watchingProblemMatcher.processLine(line);
          if (!delayer4) {
            delayer4 = new $Sh(3e3);
          }
          delayer4.trigger(() => {
            watchingProblemMatcher.forceDelivery();
            delayer4 = void 0;
          });
        });
      }
      promise = new Promise((resolve, reject) => {
        const onExit = terminal2.onExit((terminalLaunchResult) => {
          const exitCode = typeof terminalLaunchResult === "number" ? terminalLaunchResult : terminalLaunchResult?.code;
          onData?.dispose();
          onExit.dispose();
          const key2 = task.getMapKey();
          if (this.h[mapKey]) {
            delete this.h[mapKey];
          }
          this.hb(task);
          this.ib(TaskEvent.changed());
          if (terminalLaunchResult !== void 0) {
            switch (task.command.presentation.panel) {
              case PanelKind.Dedicated:
                this.n[key2] = terminal2.instanceId.toString();
                break;
              case PanelKind.Shared:
                this.m.set(
                  key2,
                  terminal2.instanceId.toString(),
                  1
                  /* Touch.AsOld */
                );
                break;
            }
          }
          const reveal = task.command.presentation.reveal;
          if (reveal === RevealKind.Silent && (exitCode !== 0 || watchingProblemMatcher.numberOfMatches > 0 && watchingProblemMatcher.maxMarkerSeverity && watchingProblemMatcher.maxMarkerSeverity >= MarkerSeverity.Error)) {
            try {
              this.L.setActiveInstance(terminal2);
              this.M.showPanel(false);
            } catch (e) {
            }
          }
          watchingProblemMatcher.done();
          watchingProblemMatcher.dispose();
          if (!processStartedSignaled) {
            this.ib(TaskEvent.processStarted(task, terminal2.instanceId, terminal2.processId));
            processStartedSignaled = true;
          }
          this.ib(TaskEvent.processEnded(task, terminal2.instanceId, exitCode));
          for (let i2 = 0; i2 < eventCounter; i2++) {
            this.ib(TaskEvent.general("inactive", task, terminal2.instanceId));
          }
          eventCounter = 0;
          this.ib(TaskEvent.general("end", task));
          toDispose.dispose();
          resolve({ exitCode: exitCode ?? void 0 });
        });
      });
      if (trigger === Triggers.reconnect && !!terminal2.xterm) {
        const bufferLines = [];
        const bufferReverseIterator = terminal2.xterm.getBufferReverseIterator();
        const startRegex = new RegExp(watchingProblemMatcher.beginPatterns.map((pattern) => pattern.source).join("|"));
        for (const nextLine of bufferReverseIterator) {
          bufferLines.push(nextLine);
          if (startRegex.test(nextLine)) {
            break;
          }
        }
        let delayer5 = void 0;
        for (let i2 = bufferLines.length - 1; i2 >= 0; i2--) {
          watchingProblemMatcher.processLine(bufferLines[i2]);
          if (!delayer5) {
            delayer5 = new $Sh(3e3);
          }
          delayer5.trigger(() => {
            watchingProblemMatcher.forceDelivery();
            delayer5 = void 0;
          });
        }
      }
    } else {
      [terminal2, error] = await this.Fb(task, resolver, workspaceFolder);
      if (error) {
        return Promise.reject(new Error(error.message));
      }
      if (!terminal2) {
        return Promise.reject(new Error(`Failed to create terminal for task ${task._label}`));
      }
      this.ib(TaskEvent.start(task, terminal2.instanceId, resolver.values));
      const mapKey = task.getMapKey();
      this.h[mapKey] = task;
      this.ib(TaskEvent.general("active", task, terminal2.instanceId));
      const problemMatchers = await this.Pb(resolver, task.configurationProperties.problemMatchers);
      const startStopProblemMatcher = new $vhc(problemMatchers, this.Q, this.R, 0, this.Y);
      this.F.addTerminal(task, terminal2, startStopProblemMatcher);
      let processStartedSignaled = false;
      terminal2.processReady.then(() => {
        if (!processStartedSignaled) {
          this.ib(TaskEvent.processStarted(task, terminal2.instanceId, terminal2.processId));
          processStartedSignaled = true;
        }
      }, (_error) => {
      });
      const onData = terminal2.onLineData((line) => {
        startStopProblemMatcher.processLine(line);
      });
      promise = new Promise((resolve, reject) => {
        const onExit = terminal2.onExit((terminalLaunchResult) => {
          const exitCode = typeof terminalLaunchResult === "number" ? terminalLaunchResult : terminalLaunchResult?.code;
          onExit.dispose();
          const key2 = task.getMapKey();
          this.hb(task);
          this.ib(TaskEvent.changed());
          if (terminalLaunchResult !== void 0) {
            switch (task.command.presentation.panel) {
              case PanelKind.Dedicated:
                this.n[key2] = terminal2.instanceId.toString();
                break;
              case PanelKind.Shared:
                this.m.set(
                  key2,
                  terminal2.instanceId.toString(),
                  1
                  /* Touch.AsOld */
                );
                break;
            }
          }
          const reveal = task.command.presentation.reveal;
          const revealProblems = task.command.presentation.revealProblems;
          const revealProblemPanel = terminal2 && revealProblems === RevealProblemKind.OnProblem && startStopProblemMatcher.numberOfMatches > 0;
          if (revealProblemPanel) {
            this.P.openView(Markers.MARKERS_VIEW_ID);
          } else if (terminal2 && reveal === RevealKind.Silent && (exitCode !== 0 || startStopProblemMatcher.numberOfMatches > 0 && startStopProblemMatcher.maxMarkerSeverity && startStopProblemMatcher.maxMarkerSeverity >= MarkerSeverity.Error)) {
            try {
              this.L.setActiveInstance(terminal2);
              this.M.showPanel(false);
            } catch (e) {
            }
          }
          setTimeout(() => {
            onData.dispose();
            startStopProblemMatcher.done();
            startStopProblemMatcher.dispose();
          }, 100);
          if (!processStartedSignaled && terminal2) {
            this.ib(TaskEvent.processStarted(task, terminal2.instanceId, terminal2.processId));
            processStartedSignaled = true;
          }
          this.ib(TaskEvent.processEnded(task, terminal2?.instanceId, exitCode ?? void 0));
          if (this.h[mapKey]) {
            delete this.h[mapKey];
          }
          this.ib(TaskEvent.general("inactive", task, terminal2?.instanceId));
          this.ib(TaskEvent.general("end", task, terminal2?.instanceId));
          resolve({ exitCode: exitCode ?? void 0 });
        });
      });
    }
    const showProblemPanel = task.command.presentation && task.command.presentation.revealProblems === RevealProblemKind.Always;
    if (showProblemPanel) {
      this.P.openView(Markers.MARKERS_VIEW_ID);
    } else if (task.command.presentation && (task.command.presentation.focus || task.command.presentation.reveal === RevealKind.Always)) {
      this.L.setActiveInstance(terminal2);
      await this.L.revealTerminal(terminal2);
      if (task.command.presentation.focus) {
        this.L.focusInstance(terminal2);
      }
    }
    this.g[task.getMapKey()].terminal = terminal2;
    this.ib(TaskEvent.changed());
    return promise;
  }
  yb(task) {
    const needsFolderQualification = this.U.getWorkbenchState() === 3;
    return needsFolderQualification ? task.getQualifiedLabel() : task.configurationProperties.name || "";
  }
  async zb(task, workspaceFolder, variableResolver, platform, options3, command4, args2, waitOnExit) {
    let shellLaunchConfig;
    const isShellCommand = task.command.runtime === RuntimeType.Shell;
    const needsFolderQualification = this.U.getWorkbenchState() === 3;
    const terminalName = this.yb(task);
    const type = ReconnectionType;
    const originalCommand = task.command.name;
    let cwd2;
    if (options3.cwd) {
      cwd2 = options3.cwd;
      if (!$mc(cwd2)) {
        if (workspaceFolder && workspaceFolder.uri.scheme === Schemas.file) {
          cwd2 = $nc(workspaceFolder.uri.fsPath, cwd2);
        }
      }
      cwd2 = $Wg(cwd2) ? cwd2 : $Fh(URI.from({ scheme: Schemas.file, path: cwd2 }), this.W.remoteAuthority, this.$.defaultUriScheme);
    }
    if (isShellCommand) {
      let os;
      switch (platform) {
        case 3:
          os = 1;
          break;
        case 1:
          os = 2;
          break;
        case 2:
        default:
          os = 3;
          break;
      }
      const defaultProfile = await this.Z.getDefaultProfile({
        allowAutomationShell: true,
        os,
        remoteAuthority: this.W.remoteAuthority
      });
      let icon2;
      if (task.configurationProperties.icon?.id) {
        icon2 = ThemeIcon.fromId(task.configurationProperties.icon.id);
      } else {
        const taskGroupKind = task.configurationProperties.group ? GroupKind.to(task.configurationProperties.group) : void 0;
        const kindId = typeof taskGroupKind === "string" ? taskGroupKind : taskGroupKind?.kind;
        icon2 = kindId === "test" ? ThemeIcon.fromId($6l.beaker.id) : defaultProfile.icon;
      }
      shellLaunchConfig = {
        name: terminalName,
        type,
        executable: defaultProfile.path,
        args: defaultProfile.args,
        env: { ...defaultProfile.env },
        icon: icon2,
        color: task.configurationProperties.icon?.color || void 0,
        waitOnExit
      };
      let shellSpecified = false;
      const shellOptions = task.command.options && task.command.options.shell;
      if (shellOptions) {
        if (shellOptions.executable) {
          if (shellOptions.executable !== shellLaunchConfig.executable) {
            shellLaunchConfig.args = void 0;
          }
          shellLaunchConfig.executable = await this.Qb(variableResolver, shellOptions.executable);
          shellSpecified = true;
        }
        if (shellOptions.args) {
          shellLaunchConfig.args = await this.Ob(variableResolver, shellOptions.args.slice());
        }
      }
      if (shellLaunchConfig.args === void 0) {
        shellLaunchConfig.args = [];
      }
      const shellArgs = Array.isArray(shellLaunchConfig.args) ? shellLaunchConfig.args.slice(0) : [shellLaunchConfig.args];
      const toAdd = [];
      const basename = $kc.basename((await this.$.fileURI(shellLaunchConfig.executable)).path).toLowerCase();
      const commandLine = this.Gb(platform, basename, shellOptions, command4, originalCommand, args2);
      let windowsShellArgs = false;
      if (platform === 3) {
        windowsShellArgs = true;
        const userHome = await this.$.userHome();
        if (basename === "cmd.exe" && (options3.cwd && $Wg(options3.cwd) || !options3.cwd && $Wg(userHome.fsPath))) {
          return void 0;
        }
        if (basename === "powershell.exe" || basename === "pwsh.exe") {
          if (!shellSpecified) {
            toAdd.push("-Command");
          }
        } else if (basename === "bash.exe" || basename === "zsh.exe") {
          windowsShellArgs = false;
          if (!shellSpecified) {
            toAdd.push("-c");
          }
        } else if (basename === "wsl.exe") {
          if (!shellSpecified) {
            toAdd.push("-e");
          }
        } else {
          if (!shellSpecified) {
            toAdd.push("/d", "/c");
          }
        }
      } else {
        if (!shellSpecified) {
          if (platform === 1) {
          }
          toAdd.push("-c");
        }
      }
      const combinedShellArgs = this.Ab(toAdd, shellArgs);
      combinedShellArgs.push(commandLine);
      shellLaunchConfig.args = windowsShellArgs ? combinedShellArgs.join(" ") : combinedShellArgs;
      if (task.command.presentation && task.command.presentation.echo) {
        if (needsFolderQualification && workspaceFolder) {
          const folder = cwd2 && typeof cwd2 === "object" && "path" in cwd2 ? $rc(cwd2.path) : workspaceFolder.name;
          shellLaunchConfig.initialText = this.taskShellIntegrationStartSequence(cwd2) + $W0b(localize(10123, null, folder, commandLine), { excludeLeadingNewLine: true }) + this.taskShellIntegrationOutputSequence;
        } else {
          shellLaunchConfig.initialText = this.taskShellIntegrationStartSequence(cwd2) + $W0b(localize(10124, null, commandLine), { excludeLeadingNewLine: true }) + this.taskShellIntegrationOutputSequence;
        }
      } else {
        shellLaunchConfig.initialText = {
          text: this.taskShellIntegrationStartSequence(cwd2) + this.taskShellIntegrationOutputSequence,
          trailingNewLine: false
        };
      }
    } else {
      const commandExecutable = task.command.runtime !== RuntimeType.CustomExecution ? CommandString.value(command4) : void 0;
      const executable = !isShellCommand ? await this.Qb(variableResolver, await this.Qb(variableResolver, "${" + _$Dhc.b + "}")) : commandExecutable;
      shellLaunchConfig = {
        name: terminalName,
        type,
        icon: task.configurationProperties.icon?.id ? ThemeIcon.fromId(task.configurationProperties.icon.id) : void 0,
        color: task.configurationProperties.icon?.color || void 0,
        executable,
        args: args2.map((a) => $zg(a) ? a : a.value),
        waitOnExit
      };
      if (task.command.presentation && task.command.presentation.echo) {
        const getArgsToEcho = (args3) => {
          if (!args3 || args3.length === 0) {
            return "";
          }
          if ($zg(args3)) {
            return args3;
          }
          return args3.join(" ");
        };
        if (needsFolderQualification && workspaceFolder) {
          shellLaunchConfig.initialText = this.taskShellIntegrationStartSequence(cwd2) + $W0b(localize(10125, null, workspaceFolder.name, `${shellLaunchConfig.executable} ${getArgsToEcho(shellLaunchConfig.args)}`), { excludeLeadingNewLine: true }) + this.taskShellIntegrationOutputSequence;
        } else {
          shellLaunchConfig.initialText = this.taskShellIntegrationStartSequence(cwd2) + $W0b(localize(10126, null, `${shellLaunchConfig.executable} ${getArgsToEcho(shellLaunchConfig.args)}`), { excludeLeadingNewLine: true }) + this.taskShellIntegrationOutputSequence;
        }
      } else {
        shellLaunchConfig.initialText = {
          text: this.taskShellIntegrationStartSequence(cwd2) + this.taskShellIntegrationOutputSequence,
          trailingNewLine: false
        };
      }
    }
    if (cwd2) {
      shellLaunchConfig.cwd = cwd2;
    }
    if (options3.env) {
      if (shellLaunchConfig.env) {
        shellLaunchConfig.env = { ...shellLaunchConfig.env, ...options3.env };
      } else {
        shellLaunchConfig.env = options3.env;
      }
    }
    shellLaunchConfig.isFeatureTerminal = true;
    shellLaunchConfig.useShellEnvironment = true;
    return shellLaunchConfig;
  }
  Ab(shellCommandArgs, configuredShellArgs) {
    const combinedShellArgs = $Lv(configuredShellArgs);
    shellCommandArgs.forEach((element) => {
      const shouldAddShellCommandArg = configuredShellArgs.every((arg, index) => {
        if (arg.toLowerCase() === element && configuredShellArgs.length > index + 1) {
          return !configuredShellArgs.slice(index + 1).every((testArg) => testArg.startsWith("-"));
        } else {
          return arg.toLowerCase() !== element;
        }
      });
      if (shouldAddShellCommandArg) {
        combinedShellArgs.push(element);
      }
    });
    return combinedShellArgs;
  }
  async Bb(task) {
    if (!this.J) {
      return;
    }
    for (let i2 = 0; i2 < this.J.length; i2++) {
      const terminal2 = this.J[i2];
      if (getReconnectionData(terminal2)?.lastTask === task.getCommonTaskId()) {
        this.J.splice(i2, 1);
        return terminal2;
      }
    }
    return void 0;
  }
  async Cb(task, group2, launchConfigs) {
    const reconnectedTerminal = await this.Bb(task);
    const onDisposed = (terminal2) => this.ib(TaskEvent.terminated(task, terminal2.instanceId, terminal2.exitReason));
    if (reconnectedTerminal) {
      if ("command" in task && task.command.presentation) {
        reconnectedTerminal.waitOnExit = getWaitOnExitValue(task.command.presentation, task.configurationProperties);
      }
      reconnectedTerminal.onDisposed(onDisposed);
      this.bb.trace("reconnected to task and terminal", task._id);
      return reconnectedTerminal;
    }
    if (group2) {
      for (const terminal2 of Object.values(this.j)) {
        if (terminal2.group === group2) {
          this.bb.trace(`Found terminal to split for group ${group2}`);
          const originalInstance = terminal2.terminal;
          const result = await this.L.createTerminal({ location: { parentTerminal: originalInstance }, config: launchConfigs });
          result.onDisposed(onDisposed);
          if (result) {
            return result;
          }
        }
      }
      this.bb.trace(`No terminal found to split for group ${group2}`);
    }
    const createdTerminal = await this.L.createTerminal({ config: launchConfigs });
    createdTerminal.onDisposed(onDisposed);
    return createdTerminal;
  }
  Db() {
    if (this.H) {
      this.bb.trace(`Already reconnected, to ${this.J?.length} terminals so returning`);
      return;
    }
    this.J = this.L.getReconnectedTerminals(ReconnectionType)?.filter((t) => !t.isDisposed && getReconnectionData(t)) || [];
    this.bb.trace(`Attempting reconnection of ${this.J?.length} terminals`);
    if (!this.J?.length) {
      this.bb.trace(`No terminals to reconnect to so returning`);
    } else {
      for (const terminal2 of this.J) {
        const data = getReconnectionData(terminal2);
        if (data) {
          const terminalData = { lastTask: data.lastTask, group: data.group, terminal: terminal2 };
          this.j[terminal2.instanceId] = terminalData;
          this.bb.trace("Reconnecting to task terminal", terminalData.lastTask, terminal2.instanceId);
        }
      }
    }
    this.H = true;
  }
  Eb(terminal2, terminalData) {
    delete this.j[terminal2.instanceId];
    delete this.n[terminalData.lastTask];
    this.m.delete(terminalData.lastTask);
    const mapKey = terminalData.lastTask;
    this.hb(mapKey);
    if (this.h[mapKey]) {
      delete this.h[mapKey];
    }
  }
  async Fb(task, resolver, workspaceFolder) {
    const platform = resolver.taskSystemInfo ? resolver.taskSystemInfo.platform : $x;
    const options3 = await this.Rb(resolver, task.command.options);
    const presentationOptions = task.command.presentation;
    if (!presentationOptions) {
      throw new Error("Task presentation options should not be undefined here.");
    }
    const waitOnExit = getWaitOnExitValue(presentationOptions, task.configurationProperties);
    let command4;
    let args2;
    let launchConfigs;
    if (task.command.runtime === RuntimeType.CustomExecution) {
      this.y.shellLaunchConfig = launchConfigs = {
        customPtyImplementation: (id2, cols, rows) => new $lRb(id2, cols, rows, this.L),
        waitOnExit,
        name: this.yb(task),
        initialText: task.command.presentation && task.command.presentation.echo ? $W0b(localize(10127, null, task._label), { excludeLeadingNewLine: true }) : void 0,
        isFeatureTerminal: true,
        icon: task.configurationProperties.icon?.id ? ThemeIcon.fromId(task.configurationProperties.icon.id) : void 0,
        color: task.configurationProperties.icon?.color || void 0
      };
    } else {
      const resolvedResult = await this.Nb(resolver, task.command);
      command4 = resolvedResult.command;
      args2 = resolvedResult.args;
      this.y.shellLaunchConfig = launchConfigs = await this.zb(task, workspaceFolder, resolver, platform, options3, command4, args2, waitOnExit);
      if (launchConfigs === void 0) {
        return [void 0, new $VSb(
          severity_default.Error,
          localize(10128, null),
          7
          /* TaskErrors.UnknownError */
        )];
      }
    }
    const prefersSameTerminal = presentationOptions.panel === PanelKind.Dedicated;
    const allowsSharedTerminal = presentationOptions.panel === PanelKind.Shared;
    const group2 = presentationOptions.group;
    const taskKey = task.getMapKey();
    let terminalToReuse;
    if (prefersSameTerminal) {
      const terminalId = this.n[taskKey];
      if (terminalId) {
        terminalToReuse = this.j[terminalId];
        delete this.n[taskKey];
      }
    } else if (allowsSharedTerminal) {
      let terminalId = this.m.remove(taskKey);
      if (!terminalId) {
        for (const taskId of this.m.keys()) {
          const idleTerminalId = this.m.get(taskId);
          if (idleTerminalId && this.j[idleTerminalId] && this.j[idleTerminalId].group === group2) {
            terminalId = this.m.remove(taskId);
            break;
          }
        }
      }
      if (terminalId) {
        terminalToReuse = this.j[terminalId];
      }
    }
    if (terminalToReuse) {
      if (!launchConfigs) {
        throw new Error("Task shell launch configuration should not be undefined here.");
      }
      terminalToReuse.terminal.scrollToBottom();
      if (task.configurationProperties.isBackground) {
        launchConfigs.reconnectionProperties = { ownerId: ReconnectionType, data: { lastTask: task.getCommonTaskId(), group: group2, label: task._label, id: task._id } };
      }
      await terminalToReuse.terminal.reuseTerminal(launchConfigs);
      if (task.command.presentation && task.command.presentation.clear) {
        terminalToReuse.terminal.clearBuffer();
      }
      this.j[terminalToReuse.terminal.instanceId.toString()].lastTask = taskKey;
      return [terminalToReuse.terminal, void 0];
    }
    this.G = this.G.then(() => this.Cb(task, group2, launchConfigs));
    const terminal2 = await this.G;
    if (task.configurationProperties.isBackground) {
      terminal2.shellLaunchConfig.reconnectionProperties = { ownerId: ReconnectionType, data: { lastTask: task.getCommonTaskId(), group: group2, label: task._label, id: task._id } };
    }
    const terminalKey = terminal2.instanceId.toString();
    const terminalData = { terminal: terminal2, lastTask: taskKey, group: group2 };
    terminal2.onDisposed(() => this.Eb(terminal2, terminalData));
    this.j[terminalKey] = terminalData;
    return [terminal2, void 0];
  }
  Gb(platform, shellExecutable, shellOptions, command4, originalCommand, args2) {
    const basename = $uc(shellExecutable).name.toLowerCase();
    const shellQuoteOptions = this.Hb(basename, shellOptions, platform);
    function needsQuotes(value2) {
      if (value2.length >= 2) {
        const first = value2[0] === shellQuoteOptions.strong ? shellQuoteOptions.strong : value2[0] === shellQuoteOptions.weak ? shellQuoteOptions.weak : void 0;
        if (first === value2[value2.length - 1]) {
          return false;
        }
      }
      let quote2;
      for (let i2 = 0; i2 < value2.length; i2++) {
        const ch = value2[i2];
        if (ch === quote2) {
          quote2 = void 0;
        } else if (quote2 !== void 0) {
          continue;
        } else if (ch === shellQuoteOptions.escape) {
          i2++;
        } else if (ch === shellQuoteOptions.strong || ch === shellQuoteOptions.weak) {
          quote2 = ch;
        } else if (ch === " ") {
          return true;
        }
      }
      return false;
    }
    function quote(value2, kind) {
      if (kind === ShellQuoting2.Strong && shellQuoteOptions.strong) {
        return [shellQuoteOptions.strong + value2 + shellQuoteOptions.strong, true];
      } else if (kind === ShellQuoting2.Weak && shellQuoteOptions.weak) {
        return [shellQuoteOptions.weak + value2 + shellQuoteOptions.weak, true];
      } else if (kind === ShellQuoting2.Escape && shellQuoteOptions.escape) {
        if ($zg(shellQuoteOptions.escape)) {
          return [value2.replace(/ /g, shellQuoteOptions.escape + " "), true];
        } else {
          const buffer = [];
          for (const ch of shellQuoteOptions.escape.charsToEscape) {
            buffer.push(`\\${ch}`);
          }
          const regexp = new RegExp("[" + buffer.join(",") + "]", "g");
          const escapeChar = shellQuoteOptions.escape.escapeChar;
          return [value2.replace(regexp, (match) => escapeChar + match), true];
        }
      }
      return [value2, false];
    }
    function quoteIfNecessary(value2) {
      if ($zg(value2)) {
        if (needsQuotes(value2)) {
          return quote(value2, ShellQuoting2.Strong);
        } else {
          return [value2, false];
        }
      } else {
        return quote(value2.value, value2.quoting);
      }
    }
    if ((!args2 || args2.length === 0) && $zg(command4) && (command4 === originalCommand || needsQuotes(originalCommand))) {
      return command4;
    }
    const result = [];
    let commandQuoted = false;
    let argQuoted = false;
    let value;
    let quoted;
    [value, quoted] = quoteIfNecessary(command4);
    result.push(value);
    commandQuoted = quoted;
    for (const arg of args2) {
      [value, quoted] = quoteIfNecessary(arg);
      result.push(value);
      argQuoted = argQuoted || quoted;
    }
    let commandLine = result.join(" ");
    if (platform === 3) {
      if (basename === "cmd" && commandQuoted && argQuoted) {
        commandLine = '"' + commandLine + '"';
      } else if ((basename === "powershell" || basename === "pwsh") && commandQuoted) {
        commandLine = "& " + commandLine;
      }
    }
    return commandLine;
  }
  Hb(shellBasename, shellOptions, platform) {
    if (shellOptions && shellOptions.quoting) {
      return shellOptions.quoting;
    }
    return _$Dhc.c[shellBasename] || _$Dhc.f[$k(platform)];
  }
  Ib(variables, task) {
    if (task.command && task.command.name) {
      this.Kb(variables, task.command, task);
    }
    this.Lb(variables, task.configurationProperties.problemMatchers);
    if (task.command.runtime === RuntimeType.CustomExecution && ($gQ.is(task) || $iQ.is(task))) {
      let definition;
      if ($gQ.is(task)) {
        definition = task._source.config.element;
      } else {
        definition = $Lv(task.defines);
        delete definition._key;
        delete definition.type;
      }
      this.Jb(variables, definition);
    }
  }
  Jb(variables, definition) {
    if ($zg(definition)) {
      this.Mb(variables, definition);
    } else if (Array.isArray(definition)) {
      definition.forEach((element) => this.Jb(variables, element));
    } else if ($Bg(definition)) {
      for (const key2 in definition) {
        this.Jb(variables, definition[key2]);
      }
    }
  }
  Kb(variables, command4, task) {
    if (command4.runtime === RuntimeType.CustomExecution) {
      return;
    }
    if (command4.name === void 0) {
      throw new Error("Command name should never be undefined here.");
    }
    this.Mb(variables, command4.name);
    command4.args?.forEach((arg) => this.Mb(variables, arg));
    const scope = task._source.scope;
    if (scope !== 1) {
      variables.add("${workspaceFolder}");
    }
    if (command4.options) {
      const options3 = command4.options;
      if (options3.cwd) {
        this.Mb(variables, options3.cwd);
      }
      const optionsEnv = options3.env;
      if (optionsEnv) {
        Object.keys(optionsEnv).forEach((key2) => {
          const value = optionsEnv[key2];
          if ($zg(value)) {
            this.Mb(variables, value);
          }
        });
      }
      if (options3.shell) {
        if (options3.shell.executable) {
          this.Mb(variables, options3.shell.executable);
        }
        options3.shell.args?.forEach((arg) => this.Mb(variables, arg));
      }
    }
  }
  Lb(variables, values) {
    if (values === void 0 || values === null || values.length === 0) {
      return;
    }
    values.forEach((value) => {
      let matcher;
      if ($zg(value)) {
        if (value[0] === "$") {
          matcher = $_P.get(value.substring(1));
        } else {
          matcher = $_P.get(value);
        }
      } else {
        matcher = value;
      }
      if (matcher && matcher.filePrefix) {
        if ($zg(matcher.filePrefix)) {
          this.Mb(variables, matcher.filePrefix);
        } else {
          for (const fp of [...$5b(matcher.filePrefix.include || []), ...$5b(matcher.filePrefix.exclude || [])]) {
            this.Mb(variables, fp);
          }
        }
      }
    });
  }
  Mb(variables, value) {
    const string = $zg(value) ? value : value.value;
    const r2 = /\$\{(.*?)\}/g;
    let matches;
    do {
      matches = r2.exec(string);
      if (matches) {
        variables.add(matches[0]);
      }
    } while (matches);
  }
  async Nb(resolver, commandConfig) {
    let args2 = commandConfig.args ? commandConfig.args.slice() : [];
    args2 = await this.Ob(resolver, args2);
    const command4 = await this.Qb(resolver, commandConfig.name);
    return { command: command4, args: args2 };
  }
  async Ob(resolver, value) {
    return Promise.all(value.map((s) => this.Qb(resolver, s)));
  }
  async Pb(resolver, values) {
    if (values === void 0 || values === null || values.length === 0) {
      return [];
    }
    const result = [];
    for (const value of values) {
      let matcher;
      if ($zg(value)) {
        if (value[0] === "$") {
          matcher = $_P.get(value.substring(1));
        } else {
          matcher = $_P.get(value);
        }
      } else {
        matcher = value;
      }
      if (!matcher) {
        this.Sb(localize(10129, null));
        continue;
      }
      const taskSystemInfo = resolver.taskSystemInfo;
      const hasFilePrefix = matcher.filePrefix !== void 0;
      const hasUriProvider = taskSystemInfo !== void 0 && taskSystemInfo.uriProvider !== void 0;
      if (!hasFilePrefix && !hasUriProvider) {
        result.push(matcher);
      } else {
        const copy = $Lv(matcher);
        if (hasUriProvider && taskSystemInfo !== void 0) {
          copy.uriProvider = taskSystemInfo.uriProvider;
        }
        if (hasFilePrefix) {
          const filePrefix = copy.filePrefix;
          if ($zg(filePrefix)) {
            copy.filePrefix = await this.Qb(resolver, filePrefix);
          } else if (filePrefix !== void 0) {
            if (filePrefix.include) {
              filePrefix.include = Array.isArray(filePrefix.include) ? await Promise.all(filePrefix.include.map((x) => this.Qb(resolver, x))) : await this.Qb(resolver, filePrefix.include);
            }
            if (filePrefix.exclude) {
              filePrefix.exclude = Array.isArray(filePrefix.exclude) ? await Promise.all(filePrefix.exclude.map((x) => this.Qb(resolver, x))) : await this.Qb(resolver, filePrefix.exclude);
            }
          }
        }
        result.push(copy);
      }
    }
    return result;
  }
  async Qb(resolver, value) {
    if ($zg(value)) {
      return resolver.resolve(value);
    } else if (value !== void 0) {
      return {
        value: await resolver.resolve(value.value),
        quoting: value.quoting
      };
    } else {
      throw new Error("Should never try to resolve undefined.");
    }
  }
  async Rb(resolver, options3) {
    if (options3 === void 0 || options3 === null) {
      let cwd2;
      try {
        cwd2 = await this.Qb(resolver, "${workspaceFolder}");
      } catch (e) {
      }
      return { cwd: cwd2 };
    }
    const result = $zg(options3.cwd) ? { cwd: await this.Qb(resolver, options3.cwd) } : { cwd: await this.Qb(resolver, "${workspaceFolder}") };
    if (options3.env) {
      result.env = /* @__PURE__ */ Object.create(null);
      for (const key2 of Object.keys(options3.env)) {
        const value = options3.env[key2];
        if ($zg(value)) {
          result.env[key2] = await this.Qb(resolver, value);
        } else {
          result.env[key2] = value.toString();
        }
      }
    }
    return result;
  }
  static {
    this.WellKnownCommands = {
      "ant": true,
      "cmake": true,
      "eslint": true,
      "gradle": true,
      "grunt": true,
      "gulp": true,
      "jake": true,
      "jenkins": true,
      "jshint": true,
      "make": true,
      "maven": true,
      "msbuild": true,
      "msc": true,
      "nmake": true,
      "npm": true,
      "rake": true,
      "tsc": true,
      "xbuild": true
    };
  }
  getSanitizedCommand(cmd) {
    let result = cmd.toLowerCase();
    const index = result.lastIndexOf(sep);
    if (index !== -1) {
      result = result.substring(index + 1);
    }
    if (_$Dhc.WellKnownCommands[result]) {
      return result;
    }
    return "other";
  }
  Sb(output) {
    const outputChannel = this.N.getChannel(this.X);
    outputChannel?.append(output);
  }
};
function getWaitOnExitValue(presentationOptions, configurationProperties) {
  if (presentationOptions.close === void 0 || presentationOptions.close === false) {
    if (presentationOptions.reveal !== RevealKind.Never || !configurationProperties.isBackground || presentationOptions.close === false) {
      if (presentationOptions.panel === PanelKind.New) {
        return taskShellIntegrationWaitOnExitSequence(localize(10130, null));
      } else if (presentationOptions.showReuseMessage) {
        return taskShellIntegrationWaitOnExitSequence(localize(10131, null));
      } else {
        return true;
      }
    }
  }
  return !presentationOptions.close;
}
function taskShellIntegrationWaitOnExitSequence(message) {
  return (exitCode) => {
    return `${$Bhc("D", exitCode.toString())}${message}`;
  };
}
function getReconnectionData(terminal2) {
  return terminal2.shellLaunchConfig.attachPersistentProcess?.reconnectionProperties?.data;
}

// out-build/vs/workbench/contrib/tasks/browser/taskQuickPick.js
var $Ihc_1;
var $Ehc = "task.quickOpen.detail";
var $Fhc = "task.quickOpen.skip";
function $Ghc(folder) {
  return "uri" in folder;
}
var SHOW_ALL = localize(10088, null);
var $Hhc = $9r("tasks-list-configure", $6l.gear, localize(10089, null));
var removeTaskIcon = $9r("tasks-remove", $6l.close, localize(10090, null));
var runTaskStorageKey = "runTaskStorageKey";
var $Ihc = $Ihc_1 = class $Ihc2 extends $3c {
  constructor(g, h3, m, n, r2, s, u) {
    super();
    this.g = g;
    this.h = h3;
    this.m = m;
    this.n = n;
    this.r = r2;
    this.s = s;
    this.u = u;
    this.c = this.g.createSorter();
  }
  w() {
    return !!this.h.getValue($Ehc);
  }
  y(task) {
    if (task._label) {
      return task._label;
    }
    if ($hQ.is(task)) {
      let label3 = task.configures.type;
      const configures = $Lv(task.configures);
      delete configures["_key"];
      delete configures["type"];
      Object.keys(configures).forEach((key2) => label3 += `: ${configures[key2]}`);
      return label3;
    }
    return "";
  }
  static getTaskLabelWithIcon(task, labelGuess) {
    const label3 = labelGuess || task._label;
    const icon2 = task.configurationProperties.icon;
    if (!icon2) {
      return `${label3}`;
    }
    return icon2.id ? `$(${icon2.id}) ${label3}` : `$(${$6l.tools.id}) ${label3}`;
  }
  static applyColorStyles(task, entry, themeService) {
    if (task.configurationProperties.icon?.color) {
      const colorTheme = themeService.getColorTheme();
      const disposable = $bQb(colorTheme);
      entry.iconClasses = [$_Pb(task.configurationProperties.icon.color)];
      return disposable;
    }
    return;
  }
  z(task, extraButtons = []) {
    const buttons = [
      { iconClass: ThemeIcon.asClassName($Hhc), tooltip: localize(10091, null) },
      ...extraButtons
    ];
    const entry = { label: $Ihc_1.getTaskLabelWithIcon(task, this.y(task)), description: this.g.getTaskDescription(task), task, detail: this.w() ? task.configurationProperties.detail : void 0, buttons };
    const disposable = $Ihc_1.applyColorStyles(task, entry, this.r);
    if (disposable) {
      this.B(disposable);
    }
    return entry;
  }
  C(entries2, tasks2, groupLabel, extraButtons = []) {
    entries2.push({ type: "separator", label: groupLabel });
    tasks2.forEach((task) => {
      if (!task.configurationProperties.hide) {
        entries2.push(this.z(task, extraButtons));
      }
    });
  }
  D(entries2, types) {
    entries2.push({ type: "separator", label: localize(10092, null) });
    types.forEach((type) => {
      entries2.push({ label: `$(folder) ${type}`, task: type, ariaLabel: localize(10093, null, type) });
    });
    entries2.push({ label: SHOW_ALL, task: SHOW_ALL, alwaysShow: true });
  }
  F(result) {
    const tasks2 = [];
    Array.from(result).forEach(([key2, folderTasks]) => {
      if (folderTasks.set) {
        tasks2.push(...folderTasks.set.tasks);
      }
      if (folderTasks.configurations) {
        for (const configuration2 in folderTasks.configurations.byIdentifier) {
          tasks2.push(folderTasks.configurations.byIdentifier[configuration2]);
        }
      }
    });
    return tasks2;
  }
  G(recentTasks, configuredTasks) {
    let dedupedConfiguredTasks = [];
    const foundRecentTasks = Array(recentTasks.length).fill(false);
    for (let j = 0; j < configuredTasks.length; j++) {
      const workspaceFolder = configuredTasks[j].getWorkspaceFolder()?.uri.toString();
      const definition = configuredTasks[j].getDefinition()?._key;
      const type = configuredTasks[j].type;
      const label3 = configuredTasks[j]._label;
      const recentKey = configuredTasks[j].getKey();
      const findIndex = recentTasks.findIndex((value) => {
        return workspaceFolder && definition && value.getWorkspaceFolder()?.uri.toString() === workspaceFolder && (value.getDefinition()?._key === definition || value.type === type && value._label === label3) || recentKey && value.getKey() === recentKey;
      });
      if (findIndex === -1) {
        dedupedConfiguredTasks.push(configuredTasks[j]);
      } else {
        recentTasks[findIndex] = configuredTasks[j];
        foundRecentTasks[findIndex] = true;
      }
    }
    dedupedConfiguredTasks = dedupedConfiguredTasks.sort((a, b) => this.c.compare(a, b));
    const prunedRecentTasks = [];
    for (let i2 = 0; i2 < recentTasks.length; i2++) {
      if (foundRecentTasks[i2] || $hQ.is(recentTasks[i2])) {
        prunedRecentTasks.push(recentTasks[i2]);
      }
    }
    return { configuredTasks: dedupedConfiguredTasks, recentTasks: prunedRecentTasks };
  }
  async getTopLevelEntries(defaultEntry) {
    if (this.f !== void 0) {
      return { entries: this.f };
    }
    let recentTasks = (await this.g.getSavedTasks("historical")).reverse();
    const configuredTasks = this.F(await this.g.getWorkspaceTasks());
    const extensionTaskTypes = this.g.taskTypes();
    this.f = [];
    const dedupeAndPrune = this.G(recentTasks, configuredTasks);
    const dedupedConfiguredTasks = dedupeAndPrune.configuredTasks;
    recentTasks = dedupeAndPrune.recentTasks;
    if (recentTasks.length > 0) {
      const removeRecentButton = {
        iconClass: ThemeIcon.asClassName(removeTaskIcon),
        tooltip: localize(10094, null)
      };
      this.C(this.f, recentTasks, localize(10095, null), [removeRecentButton]);
    }
    if (configuredTasks.length > 0) {
      if (dedupedConfiguredTasks.length > 0) {
        this.C(this.f, dedupedConfiguredTasks, localize(10096, null));
      }
    }
    if (defaultEntry && configuredTasks.length === 0) {
      this.f.push({ type: "separator", label: localize(10097, null) });
      this.f.push(defaultEntry);
    }
    if (extensionTaskTypes.length > 0) {
      this.D(this.f, extensionTaskTypes);
    }
    return { entries: this.f, isSingleConfigured: configuredTasks.length === 1 ? configuredTasks[0] : void 0 };
  }
  async handleSettingOption(selectedType) {
    const { confirmed } = await this.s.confirm({
      type: Severity2.Warning,
      message: localize(10098, null, selectedType),
      cancelButton: localize(10099, null)
    });
    if (confirmed) {
      await this.h.updateValue(`${selectedType}.autoDetect`, "on");
      await new Promise((resolve) => setTimeout(() => resolve(), 100));
      return this.show(localize(10100, null), void 0, selectedType);
    }
    return void 0;
  }
  async show(placeHolder, defaultEntry, startAtType, name) {
    const disposables = new $2c();
    const picker = disposables.add(this.m.createQuickPick({ useSeparators: true }));
    picker.placeholder = placeHolder;
    picker.matchOnDescription = true;
    picker.ignoreFocusOut = false;
    disposables.add(picker.onDidTriggerItemButton(async (context) => {
      const task = context.item.task;
      if (context.button.iconClass === ThemeIcon.asClassName(removeTaskIcon)) {
        const key2 = task && !$zg(task) ? task.getKey() : void 0;
        if (key2) {
          this.g.removeRecentlyUsedTask(key2);
        }
        const indexToRemove = picker.items.indexOf(context.item);
        if (indexToRemove >= 0) {
          picker.items = [...picker.items.slice(0, indexToRemove), ...picker.items.slice(indexToRemove + 1)];
        }
      } else if (context.button.iconClass === ThemeIcon.asClassName($Hhc)) {
        this.m.cancel();
        if ($iQ.is(task)) {
          this.g.customize(task, void 0, true);
        } else if ($gQ.is(task) || $hQ.is(task)) {
          let canOpenConfig = false;
          try {
            canOpenConfig = await this.g.openConfig(task);
          } catch (e) {
          }
          if (!canOpenConfig) {
            this.g.customize(task, void 0, true);
          }
        }
      }
    }));
    if (name) {
      picker.value = name;
    }
    let firstLevelTask = startAtType;
    if (!firstLevelTask) {
      const topLevelEntriesResult = await this.getTopLevelEntries(defaultEntry);
      if (topLevelEntriesResult.isSingleConfigured && this.h.getValue($Fhc)) {
        disposables.dispose();
        return this.J(topLevelEntriesResult.isSingleConfigured);
      }
      const taskQuickPickEntries = topLevelEntriesResult.entries;
      firstLevelTask = await this.H(picker, taskQuickPickEntries, disposables);
    }
    do {
      if ($zg(firstLevelTask)) {
        if (name) {
          await this.H(picker, (await this.getTopLevelEntries(defaultEntry)).entries, disposables);
          disposables.dispose();
          return void 0;
        }
        const selectedEntry = await this.doPickerSecondLevel(picker, disposables, firstLevelTask);
        if (selectedEntry && !selectedEntry.settingType && selectedEntry.task === null) {
          picker.value = "";
          firstLevelTask = await this.H(picker, (await this.getTopLevelEntries(defaultEntry)).entries, disposables);
        } else if (selectedEntry && $zg(selectedEntry.settingType)) {
          disposables.dispose();
          return this.handleSettingOption(selectedEntry.settingType);
        } else {
          disposables.dispose();
          return selectedEntry?.task && !$zg(selectedEntry?.task) ? this.J(selectedEntry?.task) : void 0;
        }
      } else if (firstLevelTask) {
        disposables.dispose();
        return this.J(firstLevelTask);
      } else {
        disposables.dispose();
        return firstLevelTask;
      }
    } while (1);
    return;
  }
  async H(picker, taskQuickPickEntries, disposables) {
    picker.items = taskQuickPickEntries;
    disposables.add($lgc(this.u, runTaskStorageKey, picker, true));
    const firstLevelPickerResult = await new Promise((resolve) => {
      disposables.add(Event2.once(picker.onDidAccept)(async () => {
        resolve(picker.selectedItems ? picker.selectedItems[0] : void 0);
      }));
    });
    return firstLevelPickerResult?.task;
  }
  async doPickerSecondLevel(picker, disposables, type, name) {
    picker.busy = true;
    if (type === SHOW_ALL) {
      const items = (await this.g.tasks()).filter((t) => !t.configurationProperties.hide).sort((a, b) => this.c.compare(a, b)).map((task) => this.z(task));
      items.push(...$Ihc_1.allSettingEntries(this.h));
      picker.items = items;
    } else {
      picker.value = name || "";
      picker.items = await this.I(type);
    }
    await picker.show();
    picker.busy = false;
    const secondLevelPickerResult = await new Promise((resolve) => {
      disposables.add(Event2.once(picker.onDidAccept)(async () => {
        resolve(picker.selectedItems ? picker.selectedItems[0] : void 0);
      }));
    });
    return secondLevelPickerResult;
  }
  static allSettingEntries(configurationService) {
    const entries2 = [];
    const gruntEntry = $Ihc_1.getSettingEntry(configurationService, "grunt");
    if (gruntEntry) {
      entries2.push(gruntEntry);
    }
    const gulpEntry = $Ihc_1.getSettingEntry(configurationService, "gulp");
    if (gulpEntry) {
      entries2.push(gulpEntry);
    }
    const jakeEntry = $Ihc_1.getSettingEntry(configurationService, "jake");
    if (jakeEntry) {
      entries2.push(jakeEntry);
    }
    return entries2;
  }
  static getSettingEntry(configurationService, type) {
    if (configurationService.getValue(`${type}.autoDetect`) === "off") {
      return {
        label: localize(10101, null, type[0].toUpperCase() + type.slice(1), type),
        task: null,
        settingType: type,
        alwaysShow: true
      };
    }
    return void 0;
  }
  async I(type) {
    const tasks2 = (await this.g.tasks({ type })).sort((a, b) => this.c.compare(a, b));
    let taskQuickPickEntries = [];
    if (tasks2.length > 0) {
      for (const task of tasks2) {
        if (!task.configurationProperties.hide) {
          taskQuickPickEntries.push(this.z(task));
        }
      }
      taskQuickPickEntries.push({
        type: "separator"
      }, {
        label: localize(10102, null),
        task: null,
        alwaysShow: true
      });
    } else {
      taskQuickPickEntries = [{
        label: localize(10103, null, type),
        task: null,
        alwaysShow: true
      }];
    }
    const settingEntry = $Ihc_1.getSettingEntry(this.h, type);
    if (settingEntry) {
      taskQuickPickEntries.push(settingEntry);
    }
    return taskQuickPickEntries;
  }
  async J(task) {
    if (!$hQ.is(task)) {
      return task;
    }
    const resolvedTask = await this.g.tryResolveTask(task);
    if (!resolvedTask) {
      this.n.error(localize(10104, null, task.type));
    }
    return resolvedTask;
  }
};
$Ihc = $Ihc_1 = __decorate([
  __param(0, $3Sb),
  __param(1, $kl),
  __param(2, $1M),
  __param(3, $PJ),
  __param(4, $gs),
  __param(5, $Yv),
  __param(6, $jv)
], $Ihc);

// out-build/vs/workbench/contrib/tasks/browser/abstractTaskService.js
var $Jhc_1;
var QUICKOPEN_HISTORY_LIMIT_CONFIG = "task.quickOpen.history";
var PROBLEM_MATCHER_NEVER_CONFIG = "task.problemMatchers.neverPrompt";
var USE_SLOW_PICKER = "task.quickOpen.showAll";
var ConfigureTaskAction;
(function(ConfigureTaskAction2) {
  ConfigureTaskAction2.ID = "workbench.action.tasks.configureTaskRunner";
  ConfigureTaskAction2.TEXT = localize2(10037, "Configure Task");
})(ConfigureTaskAction || (ConfigureTaskAction = {}));
var ProblemReporter = class {
  constructor(d) {
    this.d = d;
    this.c = new $3P();
  }
  info(message) {
    this.c.state = 1;
    this.d.append(message + "\n");
  }
  warn(message) {
    this.c.state = 2;
    this.d.append(message + "\n");
  }
  error(message) {
    this.c.state = 3;
    this.d.append(message + "\n");
  }
  fatal(message) {
    this.c.state = 4;
    this.d.append(message + "\n");
  }
  get status() {
    return this.c;
  }
};
var TaskMap = class _TaskMap {
  constructor() {
    this.c = /* @__PURE__ */ new Map();
  }
  forEach(callback) {
    this.c.forEach(callback);
  }
  static getKey(workspaceFolder) {
    let key2;
    if ($zg(workspaceFolder)) {
      key2 = workspaceFolder;
    } else {
      const uri = $Ghc(workspaceFolder) ? workspaceFolder.uri : workspaceFolder.configuration;
      key2 = uri ? uri.toString() : "";
    }
    return key2;
  }
  get(workspaceFolder) {
    const key2 = _TaskMap.getKey(workspaceFolder);
    let result = this.c.get(key2);
    if (!result) {
      result = [];
      this.c.set(key2, result);
    }
    return result;
  }
  add(workspaceFolder, ...task) {
    const key2 = _TaskMap.getKey(workspaceFolder);
    let values = this.c.get(key2);
    if (!values) {
      values = [];
      this.c.set(key2, values);
    }
    values.push(...task);
  }
  all() {
    const result = [];
    this.c.forEach((values) => result.push(...values));
    return result;
  }
};
var $Jhc = class $Jhc2 extends $3c {
  static {
    $Jhc_1 = this;
  }
  static {
    this.c = "workbench.tasks.recentlyUsedTasks";
  }
  static {
    this.g = "workbench.tasks.recentlyUsedTasks2";
  }
  static {
    this.h = "workbench.tasks.persistentTasks";
  }
  static {
    this.j = "workbench.tasks.ignoreTask010Shown";
  }
  static {
    this.OutputChannelId = "tasks";
  }
  static {
    this.OutputChannelLabel = localize(9935, null);
  }
  static {
    this.m = 0;
  }
  get isReconnected() {
    return this.n;
  }
  constructor(bb, cb, db, eb, fb, gb, hb, ib, jb, kb, lb, mb, nb, ob, pb, qb, rb, sb, tb, ub, vb, wb, xb, yb, zb, Ab, Bb, Cb, Db, Eb, Fb, Gb, Hb, Ib, remoteAgentService, Jb) {
    super();
    this.bb = bb;
    this.cb = cb;
    this.db = db;
    this.eb = eb;
    this.fb = fb;
    this.gb = gb;
    this.hb = hb;
    this.ib = ib;
    this.jb = jb;
    this.kb = kb;
    this.lb = lb;
    this.mb = mb;
    this.nb = nb;
    this.ob = ob;
    this.pb = pb;
    this.qb = qb;
    this.rb = rb;
    this.sb = sb;
    this.tb = tb;
    this.ub = ub;
    this.vb = vb;
    this.wb = wb;
    this.xb = xb;
    this.yb = yb;
    this.zb = zb;
    this.Ab = Ab;
    this.Bb = Bb;
    this.Cb = Cb;
    this.Db = Db;
    this.Eb = Eb;
    this.Fb = Fb;
    this.Gb = Gb;
    this.Hb = Hb;
    this.Ib = Ib;
    this.Jb = Jb;
    this.n = false;
    this.J = [];
    this.S = new $ze();
    this.U = new $ze();
    this.W = new $ze();
    this.X = false;
    this.onDidChangeTaskSystemInfo = this.W.event;
    this.Y = new $ze();
    this.onDidReconnectToTasks = this.Y.event;
    this.Z = new $ze();
    this.onDidChangeTaskConfig = this.Z.event;
    this.$ = this.B(new $ze());
    this.onDidChangeTaskProviders = this.$.event;
    this.ab = /* @__PURE__ */ new Set();
    this.H = Event2.toPromise(this.onDidChangeTaskSystemInfo);
    this.G = void 0;
    this.I = void 0;
    this.J = void 0;
    this.P = this.db.getChannel($Jhc_1.OutputChannelId);
    this.C = /* @__PURE__ */ new Map();
    this.D = /* @__PURE__ */ new Map();
    this.F = /* @__PURE__ */ new Map();
    this.B(this.jb.onDidChangeWorkspaceFolders(() => {
      const folderSetup = this.dd();
      if (this.Pb !== folderSetup[2]) {
        this.Wb();
        this.I = void 0;
      }
      this.Ub(folderSetup);
      return this.Rc(
        2
        /* TaskRunSource.FolderOpen */
      );
    }));
    this.B(this.bb.onDidChangeConfiguration(async (e) => {
      if (!e.affectsConfiguration("tasks") || !this.I && !this.G) {
        return;
      }
      if (!this.I || this.I instanceof $Dhc) {
        this.P.clear();
      }
      if (e.affectsConfiguration(
        "task.reconnection"
        /* TaskSettingId.Reconnection */
      )) {
        if (!this.bb.getValue(
          "task.reconnection"
          /* TaskSettingId.Reconnection */
        )) {
          this.N?.clear();
          this.sb.remove(
            $Jhc_1.h,
            1
            /* StorageScope.WORKSPACE */
          );
        }
      }
      this.gc();
      await this.Rc(
        3
        /* TaskRunSource.ConfigurationChange */
      );
      this.Z.fire();
    }));
    this.O = $cQ.bindTo(xb);
    this.Q = this.B(new $ze());
    this.Mb().then(() => $YSb.bindTo(this.xb).set(true));
    $1Sb.bindTo(this.xb).set($r && !remoteAgentService.getConnection()?.remoteAuthority);
    this.pb.contributeVariable("defaultBuildTask", async () => {
      let tasks2 = await this.wc(TaskGroup.Build, true);
      if (tasks2.length > 0) {
        const defaults2 = this.vd(tasks2);
        if (defaults2.length === 1) {
          return defaults2[0]._label;
        }
      }
      tasks2 = await this.wc(TaskGroup.Build);
      const defaults = this.vd(tasks2);
      if (defaults.length === 1) {
        return defaults[0]._label;
      } else if (defaults.length) {
        tasks2 = defaults;
      }
      let entry;
      if (tasks2 && tasks2.length > 0) {
        entry = await this.md(tasks2, localize(9936, null));
      }
      const task = entry ? entry.task : void 0;
      if (!task) {
        return void 0;
      }
      return task._label;
    });
    this.B(this.Ib.onBeforeShutdown((e) => {
      this.X = e.reason !== 3;
    }));
    this.B(this.onDidStateChange((e) => {
      this.Xc(localize(9937, null, e.kind), true);
      if (e.kind === "changed") {
      } else if ((this.X || e.kind === "terminated" && e.exitReason === TerminalExitReason2.User) && e.taskId) {
        const key2 = e.__task.getKey();
        if (key2) {
          this.removePersistentTask(key2);
        }
      } else if (e.kind === "start" && e.__task && e.__task.getWorkspaceFolder()) {
        this.jc(e.__task);
      }
    }));
    this.R = new Promise((resolve) => {
      Event2.once(this.U.event)(() => resolve());
    });
    if (this.qb.getReconnectedTerminals("Task")?.length) {
      this.Kb();
    } else {
      this.qb.whenConnected.then(() => {
        if (this.qb.getReconnectedTerminals("Task")?.length) {
          this.Kb();
        } else {
          this.n = true;
          this.Y.fire();
        }
      });
    }
    this.Od();
  }
  registerSupportedExecutions(custom, shell, process2) {
    if (custom !== void 0) {
      const customContext = $WSb.bindTo(this.xb);
      customContext.set(custom);
    }
    const isVirtual = !!$lpb.getValue(this.xb);
    if (shell !== void 0) {
      const shellContext = $XSb.bindTo(this.xb);
      shellContext.set(shell && !isVirtual);
    }
    if (process2 !== void 0) {
      const processContext = $ZSb.bindTo(this.xb);
      processContext.set(process2 && !isVirtual);
    }
    this.G = void 0;
    this.S.fire();
    if ($r || custom && shell && process2) {
      this.U.fire();
    }
  }
  Kb() {
    if (this.Ib.startupKind !== 3) {
      this.Xc(localize(9938, null), true);
      this.n = true;
      this.sb.remove(
        $Jhc_1.h,
        1
        /* StorageScope.WORKSPACE */
      );
    }
    if (!this.bb.getValue(
      "task.reconnection"
      /* TaskSettingId.Reconnection */
    ) || this.n) {
      this.Xc(localize(9939, null, this.bb.getValue(
        "task.reconnection"
        /* TaskSettingId.Reconnection */
      ), this.n), true);
      this.n = true;
      return;
    }
    this.Xc(localize(9940, null), true);
    this.getWorkspaceTasks(
      4
      /* TaskRunSource.Reconnect */
    ).then(async () => {
      this.n = await this.Lb();
      this.Xc(localize(9941, null), true);
      this.Y.fire();
    });
  }
  async Lb() {
    const tasks2 = await this.getSavedTasks("persistent");
    if (!tasks2.length) {
      this.Xc(localize(9942, null), true);
      return true;
    }
    const taskLabels = tasks2.map((task) => task._label).join(", ");
    this.Xc(localize(9943, null, taskLabels), true);
    for (const task of tasks2) {
      if ($hQ.is(task)) {
        const resolved = await this.tryResolveTask(task);
        if (resolved) {
          this.run(
            resolved,
            void 0,
            4
            /* TaskRunSource.Reconnect */
          );
        }
      } else {
        this.run(
          task,
          void 0,
          4
          /* TaskRunSource.Reconnect */
        );
      }
    }
    return true;
  }
  get onDidStateChange() {
    return this.Q.event;
  }
  get supportsMultipleTaskExecutions() {
    return this.inTerminal();
  }
  async Mb() {
    $tn.registerCommand({
      id: "workbench.action.tasks.runTask",
      handler: async (accessor, arg) => {
        if (await this.qd()) {
          await this.rd(arg);
        }
      },
      metadata: {
        description: "Run Task",
        args: [{
          name: "args",
          isOptional: true,
          description: localize(9944, null),
          schema: {
            anyOf: [
              {
                type: "string",
                description: localize(9945, null)
              },
              {
                type: "object",
                properties: {
                  type: {
                    type: "string",
                    description: localize(9946, null)
                  },
                  task: {
                    type: "string",
                    description: localize(9947, null)
                  }
                }
              }
            ]
          }
        }]
      }
    });
    $tn.registerCommand("workbench.action.tasks.reRunTask", async (accessor, arg) => {
      if (await this.qd()) {
        this.ud();
      }
    });
    $tn.registerCommand("workbench.action.tasks.restartTask", async (accessor, arg) => {
      if (await this.qd()) {
        this.Bd(arg);
      }
    });
    $tn.registerCommand("workbench.action.tasks.terminate", async (accessor, arg) => {
      if (await this.qd()) {
        this.Ad(arg);
      }
    });
    $tn.registerCommand("workbench.action.tasks.showLog", () => {
      this.Vb(void 0, true);
    });
    $tn.registerCommand("workbench.action.tasks.build", async () => {
      if (await this.qd()) {
        this.yd();
      }
    });
    $tn.registerCommand("workbench.action.tasks.test", async () => {
      if (await this.qd()) {
        this.zd();
      }
    });
    $tn.registerCommand("workbench.action.tasks.configureTaskRunner", async () => {
      if (await this.qd()) {
        this.Jd();
      }
    });
    $tn.registerCommand("workbench.action.tasks.configureDefaultBuildTask", async () => {
      if (await this.qd()) {
        this.Kd();
      }
    });
    $tn.registerCommand("workbench.action.tasks.configureDefaultTestTask", async () => {
      if (await this.qd()) {
        this.Ld();
      }
    });
    $tn.registerCommand("workbench.action.tasks.showTasks", async () => {
      if (await this.qd()) {
        return this.runShowTasks();
      }
    });
    $tn.registerCommand("workbench.action.tasks.toggleProblems", () => this.gb.executeCommand(Markers.TOGGLE_MARKERS_VIEW_ACTION_ID));
    $tn.registerCommand("workbench.action.tasks.openUserTasks", async () => {
      const resource = this.Cc(TaskSourceKind.User);
      if (resource) {
        this.Ed(resource, TaskSourceKind.User);
      }
    });
    $tn.registerCommand("workbench.action.tasks.openWorkspaceFileTasks", async () => {
      const resource = this.Cc(TaskSourceKind.WorkspaceFile);
      if (resource) {
        this.Ed(resource, TaskSourceKind.WorkspaceFile);
      }
    });
  }
  get Nb() {
    if (!this.u) {
      this.Ub();
    }
    return this.u;
  }
  get Ob() {
    if (!this.y) {
      this.Ub();
    }
    return this.y;
  }
  get Pb() {
    if (this.s === void 0) {
      this.Ub();
    }
    return this.s;
  }
  get Qb() {
    if (this.r === void 0) {
      this.Ub();
    }
    return this.r;
  }
  get Rb() {
    if (this.z === void 0) {
      this.z = !this.sb.getBoolean($Jhc_1.j, 1, false);
    }
    return this.z;
  }
  Sb(type) {
    const result = [];
    result.push("onCommand:workbench.action.tasks.runTask");
    if (type) {
      result.push(`onTaskType:${type}`);
    } else {
      for (const definition of $aQ.all()) {
        result.push(`onTaskType:${definition.taskType}`);
      }
    }
    return result;
  }
  async Tb(type) {
    await this.nb.whenInstalledExtensionsRegistered();
    const hasLoggedActivation = this.ab.has(type ?? "all");
    if (!hasLoggedActivation) {
      this.Xc("Activating task providers " + (type ?? "all"));
    }
    const result = await $Lh(Promise.all(this.Sb(type).map((activationEvent) => this.nb.activateByEvent(activationEvent))), 5e3, () => console.warn("Timed out activating extensions for task providers"));
    if (result) {
      this.ab.add(type ?? "all");
    }
  }
  Ub(setup) {
    if (!setup) {
      setup = this.dd();
    }
    this.u = setup[0];
    if (this.y) {
      if (this.y.length !== setup[1].length) {
        this.z = void 0;
      } else {
        const set = /* @__PURE__ */ new Set();
        this.y.forEach((folder) => set.add(folder.uri.toString()));
        for (const folder of setup[1]) {
          if (!set.has(folder.uri.toString())) {
            this.z = void 0;
            break;
          }
        }
      }
    }
    this.y = setup[1];
    this.s = setup[2];
    this.r = setup[3];
    this.w = setup[4];
  }
  Vb(runSource = 1, userRequested) {
    if (!$lpb.getValue(this.xb) && (runSource === 1 || runSource === 3)) {
      if (userRequested) {
        this.db.showChannel(this.P.id, true);
      } else {
        this.wb.prompt(severity_default.Warning, localize(9948, null), [{
          label: localize(9949, null),
          run: () => {
            this.db.showChannel(this.P.id, true);
          }
        }]);
      }
    }
  }
  Wb() {
    if (this.J) {
      $Xc(this.J);
      this.J = void 0;
    }
  }
  registerTaskProvider(provider, type) {
    if (!provider) {
      return {
        dispose: () => {
        }
      };
    }
    const handle2 = $Jhc_1.m++;
    this.C.set(handle2, provider);
    this.D.set(handle2, type);
    this.$.fire();
    return {
      dispose: () => {
        this.C.delete(handle2);
        this.D.delete(handle2);
        this.$.fire();
      }
    };
  }
  get hasTaskSystemInfo() {
    const infosCount = Array.from(this.F.values()).flat().length;
    if (this.yb.remoteAuthority) {
      return infosCount > 1;
    }
    return infosCount > 0;
  }
  registerTaskSystem(key2, info) {
    if (info.platform === 0) {
      key2 = this.Nb.length ? this.Nb[0].uri.scheme : key2;
    }
    if (!this.F.has(key2)) {
      this.F.set(key2, [info]);
    } else {
      const infos = this.F.get(key2);
      if (info.platform === 0) {
        infos.push(info);
      } else {
        infos.unshift(info);
      }
    }
    if (this.hasTaskSystemInfo) {
      this.W.fire();
    }
  }
  Xb(key2) {
    const infos = this.F.get(key2);
    return infos && infos.length ? infos[0] : void 0;
  }
  extensionCallbackTaskComplete(task, result) {
    if (!this.I) {
      return Promise.resolve();
    }
    return this.I.customExecutionComplete(task, result);
  }
  /**
   * Get a subset of workspace tasks that match a certain predicate.
   */
  async Yb(predicate) {
    const result = [];
    const tasks2 = await this.getWorkspaceTasks();
    for (const [, workspaceTasks] of tasks2) {
      if (workspaceTasks.configurations) {
        for (const taskName in workspaceTasks.configurations.byIdentifier) {
          const task = workspaceTasks.configurations.byIdentifier[taskName];
          if (predicate(task, workspaceTasks.workspaceFolder)) {
            result.push(task);
          }
        }
      }
      if (workspaceTasks.set) {
        for (const task of workspaceTasks.set.tasks) {
          if (predicate(task, workspaceTasks.workspaceFolder)) {
            result.push(task);
          }
        }
      }
    }
    return result;
  }
  async Zb(group2, isDefault) {
    return this.Yb((task) => {
      const taskGroup = task.configurationProperties.group;
      if (taskGroup && typeof taskGroup !== "string") {
        return taskGroup._id === group2._id && (!isDefault || !!taskGroup.isDefault);
      }
      return false;
    });
  }
  async getTask(folder, identifier2, compareId = false, type = void 0) {
    if (!await this.qd()) {
      return;
    }
    const name = $zg(folder) ? folder : $Ghc(folder) ? folder.name : folder.configuration ? $sh(folder.configuration) : void 0;
    if (this.Ob.some((ignored) => ignored.name === name)) {
      return Promise.reject(new Error(localize(9950, null, name)));
    }
    const key2 = !$zg(identifier2) ? TaskDefinition.createTaskIdentifier(identifier2, console) : identifier2;
    if (key2 === void 0) {
      return Promise.resolve(void 0);
    }
    const requestedFolder = TaskMap.getKey(folder);
    const matchedTasks = await this.Yb((task, workspaceFolder) => {
      const taskFolder = TaskMap.getKey(workspaceFolder);
      if (taskFolder !== requestedFolder && taskFolder !== $bQ) {
        return false;
      }
      return task.matches(key2, compareId);
    });
    matchedTasks.sort((task) => task._source.kind === TaskSourceKind.Extension ? 1 : -1);
    if (matchedTasks.length > 0) {
      const task = matchedTasks[0];
      if ($hQ.is(task)) {
        return this.tryResolveTask(task);
      } else {
        return task;
      }
    }
    const map = await this.Oc({ type });
    let values = map.get(folder);
    values = values.concat(map.get($bQ));
    if (!values) {
      return void 0;
    }
    values = values.filter((task) => task.matches(key2, compareId)).sort((task) => task._source.kind === TaskSourceKind.Extension ? 1 : -1);
    return values.length > 0 ? values[0] : void 0;
  }
  async tryResolveTask(configuringTask) {
    if (!await this.qd()) {
      return;
    }
    await this.Tb(configuringTask.type);
    let matchingProvider;
    let matchingProviderUnavailable = false;
    for (const [handle2, provider] of this.C) {
      const providerType = this.D.get(handle2);
      if (configuringTask.type === providerType) {
        if (providerType && !this.Nc(providerType)) {
          matchingProviderUnavailable = true;
          continue;
        }
        matchingProvider = provider;
        break;
      }
    }
    if (!matchingProvider) {
      if (matchingProviderUnavailable) {
        this.Xc(localize(9951, null, configuringTask.configures.type));
      }
      return;
    }
    try {
      const resolvedTask = await matchingProvider.resolveTask(configuringTask);
      if (resolvedTask && resolvedTask._id === configuringTask._id) {
        return $thc(resolvedTask, configuringTask);
      }
    } catch (error) {
    }
    const tasks2 = await this.tasks({ type: configuringTask.type });
    for (const task of tasks2) {
      if (task._id === configuringTask._id) {
        return $thc(task, configuringTask);
      }
    }
    return;
  }
  async tasks(filter) {
    if (!await this.qd()) {
      return [];
    }
    if (!this.$b(filter)) {
      return Promise.resolve([]);
    }
    return this.Oc(filter).then((map) => this.bc(filter, map));
  }
  async getKnownTasks(filter) {
    if (!this.$b(filter)) {
      return Promise.resolve([]);
    }
    return this.Oc(filter, true, true).then((map) => this.bc(filter, map));
  }
  taskTypes() {
    const types = [];
    if (this.qc()) {
      for (const definition of $aQ.all()) {
        if (this.Nc(definition.taskType)) {
          types.push(definition.taskType);
        }
      }
    }
    return types;
  }
  createSorter() {
    return new $kQ(this.jb.getWorkspace() ? this.jb.getWorkspace().folders : []);
  }
  ac() {
    if (!this.I) {
      return Promise.resolve(false);
    }
    return this.I.isActive();
  }
  async getActiveTasks() {
    if (!this.I) {
      return [];
    }
    return this.I.getActiveTasks();
  }
  async getBusyTasks() {
    if (!this.I) {
      return [];
    }
    return this.I.getBusyTasks();
  }
  getRecentlyUsedTasksV1() {
    if (this.L) {
      return this.L;
    }
    const quickOpenHistoryLimit = this.bb.getValue(QUICKOPEN_HISTORY_LIMIT_CONFIG);
    this.L = new $Hc(quickOpenHistoryLimit);
    const storageValue = this.sb.get(
      $Jhc_1.c,
      1
      /* StorageScope.WORKSPACE */
    );
    if (storageValue) {
      try {
        const values = JSON.parse(storageValue);
        if (Array.isArray(values)) {
          for (const value of values) {
            this.L.set(value, value);
          }
        }
      } catch (error) {
      }
    }
    return this.L;
  }
  bc(filter, map) {
    if (!filter || !filter.type) {
      return map.all();
    }
    const result = [];
    map.forEach((tasks2) => {
      for (const task of tasks2) {
        if ($iQ.is(task) && (task.defines.type === filter.type || task._source.label === filter.type)) {
          result.push(task);
        } else if ($gQ.is(task)) {
          if (task.type === filter.type) {
            result.push(task);
          } else {
            const customizes = task.customizes();
            if (customizes && customizes.type === filter.type) {
              result.push(task);
            }
          }
        }
      }
    });
    return result;
  }
  cc(type) {
    return type === "persistent" ? this.ec() : this.dc();
  }
  dc() {
    if (this.M) {
      return this.M;
    }
    const quickOpenHistoryLimit = this.bb.getValue(QUICKOPEN_HISTORY_LIMIT_CONFIG);
    this.M = new $Hc(quickOpenHistoryLimit);
    const storageValue = this.sb.get(
      $Jhc_1.g,
      1
      /* StorageScope.WORKSPACE */
    );
    if (storageValue) {
      try {
        const values = JSON.parse(storageValue);
        if (Array.isArray(values)) {
          for (const value of values) {
            this.M.set(value[0], value[1]);
          }
        }
      } catch (error) {
      }
    }
    return this.M;
  }
  ec() {
    if (this.N) {
      this.Xc(localize(9952, null, this.N.size), true);
      return this.N;
    }
    this.N = new $Hc(10);
    const storageValue = this.sb.get(
      $Jhc_1.h,
      1
      /* StorageScope.WORKSPACE */
    );
    if (storageValue) {
      try {
        const values = JSON.parse(storageValue);
        if (Array.isArray(values)) {
          for (const value of values) {
            this.N.set(value[0], value[1]);
          }
        }
      } catch (error) {
      }
    }
    return this.N;
  }
  fc(key2) {
    const keyValue = JSON.parse(key2);
    return {
      folder: keyValue.folder,
      isWorkspaceFile: keyValue.id?.endsWith(TaskSourceKind.WorkspaceFile)
    };
  }
  async getSavedTasks(type) {
    const folderMap = /* @__PURE__ */ Object.create(null);
    this.Nb.forEach((folder) => {
      folderMap[folder.uri.toString()] = folder;
    });
    const folderToTasksMap = /* @__PURE__ */ new Map();
    const workspaceToTaskMap = /* @__PURE__ */ new Map();
    const storedTasks = this.cc(type);
    const tasks2 = [];
    this.Xc(localize(9953, null), true);
    function addTaskToMap(map, folder, task) {
      if (folder && !map.has(folder)) {
        map.set(folder, []);
      }
      if (folder && (folderMap[folder] || folder === $bQ) && task) {
        map.get(folder).push(task);
      }
    }
    for (const entry of storedTasks.entries()) {
      try {
        const key2 = entry[0];
        const task = JSON.parse(entry[1]);
        const folderInfo = this.fc(key2);
        this.Xc(localize(9954, null, key2, task, folderInfo.folder), true);
        addTaskToMap(folderInfo.isWorkspaceFile ? workspaceToTaskMap : folderToTasksMap, folderInfo.folder, task);
      } catch (error) {
        this.Xc(localize(9955, null, error), true);
      }
    }
    const readTasksMap = /* @__PURE__ */ new Map();
    async function readTasks(that, map, isWorkspaceFile) {
      for (const key2 of map.keys()) {
        const custom = [];
        const customized = /* @__PURE__ */ Object.create(null);
        const taskConfigSource = folderMap[key2] ? isWorkspaceFile ? TaskConfigSource.WorkspaceFile : TaskConfigSource.TasksJson : TaskConfigSource.User;
        await that.ad(folderMap[key2] ?? await that.Sc(), {
          version: "2.0.0",
          tasks: map.get(key2)
        }, 0, custom, customized, taskConfigSource, true);
        custom.forEach((task) => {
          const taskKey = task.getKey();
          if (taskKey) {
            readTasksMap.set(taskKey, task);
          }
        });
        for (const configuration2 in customized) {
          const taskKey = customized[configuration2].getKey();
          if (taskKey) {
            readTasksMap.set(taskKey, customized[configuration2]);
          }
        }
      }
    }
    await readTasks(this, folderToTasksMap, false);
    await readTasks(this, workspaceToTaskMap, true);
    for (const key2 of storedTasks.keys()) {
      if (readTasksMap.has(key2)) {
        tasks2.push(readTasksMap.get(key2));
        this.Xc(localize(9956, null, key2), true);
      } else {
        this.Xc(localize(9957, null, key2), true);
      }
    }
    return tasks2;
  }
  removeRecentlyUsedTask(taskRecentlyUsedKey) {
    if (this.cc("historical").has(taskRecentlyUsedKey)) {
      this.cc("historical").delete(taskRecentlyUsedKey);
      this.ic();
    }
  }
  removePersistentTask(key2) {
    this.Xc(localize(9958, null, key2), true);
    if (this.cc("persistent").has(key2)) {
      this.cc("persistent").delete(key2);
      this.kc();
    }
  }
  gc() {
    const quickOpenHistoryLimit = this.bb.getValue(QUICKOPEN_HISTORY_LIMIT_CONFIG);
    if (this.M) {
      this.M.limit = quickOpenHistoryLimit;
    }
  }
  async hc(task) {
    let key2 = task.getKey();
    if (!$jQ.is(task) && key2) {
      const customizations = this.Ac(task);
      if ($iQ.is(task) && customizations) {
        const custom = [];
        const customized = /* @__PURE__ */ Object.create(null);
        await this.ad(task._source.workspaceFolder ?? this.Nb[0], {
          version: "2.0.0",
          tasks: [customizations]
        }, 0, custom, customized, TaskConfigSource.TasksJson, true);
        for (const configuration2 in customized) {
          key2 = customized[configuration2].getKey();
        }
      }
      this.cc("historical").set(key2, JSON.stringify(customizations));
      this.ic();
    }
  }
  ic() {
    if (!this.M) {
      return;
    }
    const quickOpenHistoryLimit = this.bb.getValue(QUICKOPEN_HISTORY_LIMIT_CONFIG);
    if (quickOpenHistoryLimit === 0) {
      return;
    }
    let keys = [...this.M.keys()];
    if (keys.length > quickOpenHistoryLimit) {
      keys = keys.slice(0, quickOpenHistoryLimit);
    }
    const keyValues = [];
    for (const key2 of keys) {
      keyValues.push([key2, this.M.get(
        key2,
        0
        /* Touch.None */
      )]);
    }
    this.sb.store(
      $Jhc_1.g,
      JSON.stringify(keyValues),
      1,
      1
      /* StorageTarget.MACHINE */
    );
  }
  async jc(task) {
    if (!this.bb.getValue(
      "task.reconnection"
      /* TaskSettingId.Reconnection */
    )) {
      return;
    }
    let key2 = task.getKey();
    if (!$jQ.is(task) && key2) {
      const customizations = this.Ac(task);
      if ($iQ.is(task) && customizations) {
        const custom = [];
        const customized = /* @__PURE__ */ Object.create(null);
        await this.ad(task._source.workspaceFolder ?? this.Nb[0], {
          version: "2.0.0",
          tasks: [customizations]
        }, 0, custom, customized, TaskConfigSource.TasksJson, true);
        for (const configuration2 in customized) {
          key2 = customized[configuration2].getKey();
        }
      }
      if (!task.configurationProperties.isBackground) {
        return;
      }
      this.Xc(localize(9959, null, key2), true);
      this.cc("persistent").set(key2, JSON.stringify(customizations));
      this.kc();
    }
  }
  kc() {
    this.N = this.cc("persistent");
    const keys = [...this.N.keys()];
    const keyValues = [];
    for (const key2 of keys) {
      keyValues.push([key2, this.N.get(
        key2,
        0
        /* Touch.None */
      )]);
    }
    this.Xc(localize(9960, null, keys.join(", ")), true);
    this.sb.store(
      $Jhc_1.h,
      JSON.stringify(keyValues),
      1,
      1
      /* StorageTarget.MACHINE */
    );
  }
  lc() {
    this.ub.open(URI.parse("https://code.visualstudio.com/docs/editor/tasks#_defining-a-problem-matcher"));
  }
  async mc(group2) {
    const tasksOfGroup = await this.Zb(group2, true);
    if (tasksOfGroup.length === 1 && typeof tasksOfGroup[0].configurationProperties.group !== "string" && tasksOfGroup[0].configurationProperties.group?.isDefault) {
      let resolvedTask;
      if ($hQ.is(tasksOfGroup[0])) {
        resolvedTask = await this.tryResolveTask(tasksOfGroup[0]);
      } else {
        resolvedTask = tasksOfGroup[0];
      }
      if (resolvedTask) {
        return this.run(
          resolvedTask,
          void 0,
          1
          /* TaskRunSource.User */
        );
      }
    }
    return void 0;
  }
  async nc() {
    const tryBuildShortcut = await this.mc(TaskGroup.Build);
    if (tryBuildShortcut) {
      return tryBuildShortcut;
    }
    return this.pc();
  }
  async oc() {
    const tryTestShortcut = await this.mc(TaskGroup.Test);
    if (tryTestShortcut) {
      return tryTestShortcut;
    }
    return this.pc(true);
  }
  async pc(test) {
    const tasks2 = await this.Oc();
    const runnable = this.Ec(tasks2, test ? TaskGroup.Test : TaskGroup.Build);
    if (!runnable || !runnable.task) {
      if (test) {
        if (this.Qb === 1) {
          throw new $VSb(
            severity_default.Info,
            localize(9961, null),
            3
            /* TaskErrors.NoTestTask */
          );
        } else {
          throw new $VSb(
            severity_default.Info,
            localize(9962, null),
            3
            /* TaskErrors.NoTestTask */
          );
        }
      } else {
        if (this.Qb === 1) {
          throw new $VSb(
            severity_default.Info,
            localize(9963, null),
            2
            /* TaskErrors.NoBuildTask */
          );
        } else {
          throw new $VSb(
            severity_default.Info,
            localize(9964, null),
            2
            /* TaskErrors.NoBuildTask */
          );
        }
      }
    }
    let executeTaskResult;
    try {
      executeTaskResult = await this.Hc(
        runnable.task,
        runnable.resolver,
        1
        /* TaskRunSource.User */
      );
    } catch (error) {
      this.hd(error);
      return Promise.reject(error);
    }
    return executeTaskResult;
  }
  async run(task, options3, runSource = 0) {
    if (!await this.qd()) {
      return;
    }
    if (!task) {
      throw new $VSb(
        severity_default.Info,
        localize(9965, null),
        5
        /* TaskErrors.TaskNotFound */
      );
    }
    const resolver = this.Fc();
    let executeTaskResult;
    try {
      if (options3 && options3.attachProblemMatcher && this.tc(task) && !$jQ.is(task)) {
        const taskToExecute = await this.vc(task);
        if (taskToExecute) {
          executeTaskResult = await this.Hc(taskToExecute, resolver, runSource);
        }
      } else {
        executeTaskResult = await this.Hc(task, resolver, runSource);
      }
      return executeTaskResult;
    } catch (error) {
      this.hd(error);
      return Promise.reject(error);
    }
  }
  qc() {
    const settingValue = this.bb.getValue(
      "task.autoDetect"
      /* TaskSettingId.AutoDetect */
    );
    return settingValue === "on";
  }
  rc(type) {
    const settingValue = this.bb.getValue(PROBLEM_MATCHER_NEVER_CONFIG);
    if ($Fg(settingValue)) {
      return !settingValue;
    }
    if (type === void 0) {
      return true;
    }
    const settingValueMap = settingValue;
    return !settingValueMap[type];
  }
  sc(task) {
    let type;
    if ($gQ.is(task)) {
      const configProperties = task._source.config.element;
      type = configProperties.type;
    } else {
      type = task.getDefinition().type;
    }
    return type;
  }
  tc(task) {
    const enabled = this.rc(this.sc(task));
    if (enabled === false) {
      return false;
    }
    if (!this.xc(task)) {
      return false;
    }
    if (task.configurationProperties.group !== void 0 && task.configurationProperties.group !== TaskGroup.Build) {
      return false;
    }
    if (task.configurationProperties.problemMatchers !== void 0 && task.configurationProperties.problemMatchers.length > 0) {
      return false;
    }
    if ($iQ.is(task)) {
      return !task.hasDefinedMatchers && !!task.configurationProperties.problemMatchers && task.configurationProperties.problemMatchers.length === 0;
    }
    if ($gQ.is(task)) {
      const configProperties = task._source.config.element;
      return configProperties.problemMatcher === void 0 && !task.hasDefinedMatchers;
    }
    return false;
  }
  async uc(type) {
    const current = this.bb.getValue(PROBLEM_MATCHER_NEVER_CONFIG);
    if (current === true) {
      return;
    }
    let newValue;
    if (current !== false) {
      newValue = current;
    } else {
      newValue = /* @__PURE__ */ Object.create(null);
    }
    newValue[type] = true;
    return this.bb.updateValue(PROBLEM_MATCHER_NEVER_CONFIG, newValue);
  }
  async vc(task) {
    let entries2 = [];
    for (const key2 of $_P.keys()) {
      const matcher = $_P.get(key2);
      if (matcher.deprecated) {
        continue;
      }
      if (matcher.name === matcher.label) {
        entries2.push({ label: matcher.name, matcher });
      } else {
        entries2.push({
          label: matcher.label,
          description: `$${matcher.name}`,
          matcher
        });
      }
    }
    if (entries2.length === 0) {
      return;
    }
    entries2 = entries2.sort((a, b) => {
      if (a.label && b.label) {
        return a.label.localeCompare(b.label);
      } else {
        return 0;
      }
    });
    entries2.unshift({ type: "separator", label: localize(9966, null) });
    let taskType2;
    if ($gQ.is(task)) {
      const configProperties = task._source.config.element;
      taskType2 = configProperties.type;
    } else {
      taskType2 = task.getDefinition().type;
    }
    entries2.unshift({ label: localize(9967, null), matcher: void 0 }, { label: localize(9968, null), matcher: void 0, never: true }, { label: localize(9969, null, taskType2), matcher: void 0, setting: taskType2 }, { label: localize(9970, null), matcher: void 0, learnMore: true });
    const problemMatcher = await this.ob.pick(entries2, { placeHolder: localize(9971, null) });
    if (!problemMatcher) {
      return task;
    }
    if (problemMatcher.learnMore) {
      this.lc();
      return void 0;
    }
    if (problemMatcher.never) {
      this.customize(task, { problemMatcher: [] }, true);
      return task;
    }
    if (problemMatcher.matcher) {
      const newTask = task.clone();
      const matcherReference = `$${problemMatcher.matcher.name}`;
      const properties = { problemMatcher: [matcherReference] };
      newTask.configurationProperties.problemMatchers = [matcherReference];
      const matcher = $_P.get(problemMatcher.matcher.name);
      if (matcher && matcher.watching !== void 0) {
        properties.isBackground = true;
        newTask.configurationProperties.isBackground = true;
      }
      this.customize(task, properties, true);
      return newTask;
    }
    if (problemMatcher.setting) {
      await this.uc(problemMatcher.setting);
    }
    return task;
  }
  async wc(group2, waitToActivate) {
    const groups = await this.Oc(void 0, waitToActivate);
    const result = [];
    groups.forEach((tasks2) => {
      for (const task of tasks2) {
        const configTaskGroup = TaskGroup.from(task.configurationProperties.group);
        if (configTaskGroup?._id === group2._id) {
          result.push(task);
        }
      }
    });
    return result;
  }
  needsFolderQualification() {
    return this.jb.getWorkbenchState() === 3;
  }
  xc(task) {
    if (this.Qb !== 2) {
      return false;
    }
    if ($gQ.is(task)) {
      return true;
    }
    if ($iQ.is(task)) {
      return !!task.getWorkspaceFolder();
    }
    return false;
  }
  async yc(resource, task) {
    let reference;
    let stringValue = "";
    try {
      reference = await this.Bb.createModelReference(resource);
      const model = reference.object.textEditorModel;
      const { tabSize, insertSpaces } = model.getOptions();
      const eol = model.getEOL();
      let stringified = $Tw(task, { eol, tabSize, insertSpaces });
      const regex = new RegExp(eol + (insertSpaces ? " ".repeat(tabSize) : "\\t"), "g");
      stringified = stringified.replace(regex, eol + (insertSpaces ? " ".repeat(tabSize * 3) : "			"));
      const twoTabs = insertSpaces ? " ".repeat(tabSize * 2) : "		";
      stringValue = twoTabs + stringified.slice(0, stringified.length - 1) + twoTabs + stringified.slice(stringified.length - 1);
    } finally {
      reference?.dispose();
    }
    return stringValue;
  }
  async zc(resource, task, configIndex = -1) {
    if (resource === void 0) {
      return Promise.resolve(false);
    }
    const fileContent = await this.ib.readFile(resource);
    const content = fileContent.value;
    if (!content || !task) {
      return false;
    }
    const contentValue = content.toString();
    let stringValue;
    if (configIndex !== -1) {
      const json = this.bb.getValue("tasks", { resource });
      if (json.tasks && json.tasks.length > configIndex) {
        stringValue = await this.yc(resource, json.tasks[configIndex]);
      }
    }
    if (!stringValue) {
      if (typeof task === "string") {
        stringValue = task;
      } else {
        stringValue = await this.yc(resource, task);
      }
    }
    const index = contentValue.indexOf(stringValue);
    let startLineNumber = 1;
    for (let i2 = 0; i2 < index; i2++) {
      if (contentValue.charAt(i2) === "\n") {
        startLineNumber++;
      }
    }
    let endLineNumber = startLineNumber;
    for (let i2 = 0; i2 < stringValue.length; i2++) {
      if (stringValue.charAt(i2) === "\n") {
        endLineNumber++;
      }
    }
    const selection = startLineNumber > 1 ? { startLineNumber, startColumn: startLineNumber === endLineNumber ? 4 : 3, endLineNumber, endColumn: startLineNumber === endLineNumber ? void 0 : 4 } : void 0;
    await this.hb.openEditor({
      resource,
      options: {
        pinned: false,
        forceReload: true,
        // because content might have changed
        selection,
        selectionRevealType: 1
        /* TextEditorSelectionRevealType.CenterIfOutsideViewport */
      }
    });
    return !!selection;
  }
  Ac(task) {
    let toCustomize;
    const taskConfig = $gQ.is(task) || $hQ.is(task) ? task._source.config : void 0;
    if (taskConfig && taskConfig.element) {
      toCustomize = { ...taskConfig.element };
    } else if ($iQ.is(task)) {
      toCustomize = {};
      const identifier2 = Object.assign(/* @__PURE__ */ Object.create(null), task.defines);
      delete identifier2["_key"];
      Object.keys(identifier2).forEach((key2) => toCustomize[key2] = identifier2[key2]);
      if (task.configurationProperties.problemMatchers && task.configurationProperties.problemMatchers.length > 0 && $Ag(task.configurationProperties.problemMatchers)) {
        toCustomize.problemMatcher = task.configurationProperties.problemMatchers;
      }
      if (task.configurationProperties.group) {
        toCustomize.group = GroupKind.to(task.configurationProperties.group);
      }
    }
    if (!toCustomize) {
      return void 0;
    }
    if (toCustomize.problemMatcher === void 0 && task.configurationProperties.problemMatchers === void 0 || task.configurationProperties.problemMatchers && task.configurationProperties.problemMatchers.length === 0) {
      toCustomize.problemMatcher = [];
    }
    if (task._source.label !== "Workspace") {
      toCustomize.label = task.configurationProperties.identifier;
    } else {
      toCustomize.label = task._label;
    }
    toCustomize.detail = task.configurationProperties.detail;
    return toCustomize;
  }
  async customize(task, properties, openConfig) {
    if (!await this.qd()) {
      return;
    }
    const workspaceFolder = task.getWorkspaceFolder();
    if (!workspaceFolder) {
      return Promise.resolve(void 0);
    }
    const configuration2 = this.gd(workspaceFolder, task._source.kind);
    if (configuration2.hasParseErrors) {
      this.wb.warn(localize(9972, null));
      return Promise.resolve(void 0);
    }
    const fileConfig = configuration2.config;
    const toCustomize = this.Ac(task);
    if (!toCustomize) {
      return Promise.resolve(void 0);
    }
    const index = $gQ.is(task) ? task._source.config.index : void 0;
    if (properties) {
      for (const property of Object.getOwnPropertyNames(properties)) {
        const value = properties[property];
        if (value !== void 0 && value !== null) {
          toCustomize[property] = value;
        }
      }
    }
    if (!fileConfig) {
      const value = {
        version: "2.0.0",
        tasks: [toCustomize]
      };
      let content = [
        "{",
        localize(9973, null)
      ].join("\n") + JSON.stringify(value, null, "	").substr(1);
      const editorConfig = this.bb.getValue();
      if (editorConfig.editor.insertSpaces) {
        content = content.replace(/(\n)(\t+)/g, (_, s1, s2) => s1 + " ".repeat(s2.length * editorConfig.editor.tabSize));
      }
      await this.lb.create([{ resource: workspaceFolder.toResource(".vscode/tasks.json"), value: content }]);
    } else {
      if (index === -1 && properties) {
        if (properties.problemMatcher !== void 0) {
          fileConfig.problemMatcher = properties.problemMatcher;
          await this.Bc(workspaceFolder, "tasks.problemMatchers", fileConfig.problemMatcher, task._source.kind);
        } else if (properties.group !== void 0) {
          fileConfig.group = properties.group;
          await this.Bc(workspaceFolder, "tasks.group", fileConfig.group, task._source.kind);
        }
      } else {
        if (!Array.isArray(fileConfig.tasks)) {
          fileConfig.tasks = [];
        }
        if (index === void 0) {
          fileConfig.tasks.push(toCustomize);
        } else {
          fileConfig.tasks[index] = toCustomize;
        }
        await this.Bc(workspaceFolder, "tasks.tasks", fileConfig.tasks, task._source.kind);
      }
    }
    if (openConfig) {
      this.zc(this.Dc(task), toCustomize);
    }
  }
  Bc(workspaceFolder, key2, value, source) {
    let target = void 0;
    switch (source) {
      case TaskSourceKind.User:
        target = 2;
        break;
      case TaskSourceKind.WorkspaceFile:
        target = 5;
        break;
      default:
        if (this.jb.getWorkbenchState() === 2) {
          target = 5;
        } else if (this.jb.getWorkbenchState() === 3) {
          target = 6;
        }
    }
    if (target) {
      return this.bb.updateValue(key2, value, { resource: workspaceFolder.uri }, target);
    } else {
      return void 0;
    }
  }
  Cc(kind) {
    this.Ub();
    switch (kind) {
      case TaskSourceKind.User: {
        return $vh($uh(this.Cb.userSettingsResource), "tasks.json");
      }
      case TaskSourceKind.WorkspaceFile: {
        if (this.w && this.w.configuration) {
          return this.w.configuration;
        }
      }
      default: {
        return void 0;
      }
    }
  }
  Dc(task) {
    if ($gQ.is(task)) {
      let uri = this.Cc(task._source.kind);
      if (!uri) {
        const taskFolder = task.getWorkspaceFolder();
        if (taskFolder) {
          uri = taskFolder.toResource(task._source.config.file);
        } else {
          uri = this.Nb[0].uri;
        }
      }
      return uri;
    } else {
      return task.getWorkspaceFolder().toResource(".vscode/tasks.json");
    }
  }
  async openConfig(task) {
    let resource;
    if (task) {
      resource = this.Dc(task);
    } else {
      resource = this.u && this.u.length > 0 ? this.u[0].toResource(".vscode/tasks.json") : void 0;
    }
    return this.zc(resource, task ? task._label : void 0, task ? task._source.config.index : -1);
  }
  Ec(tasks2, group2) {
    const resolverData = /* @__PURE__ */ new Map();
    const workspaceTasks = [];
    const extensionTasks = [];
    tasks2.forEach((tasks3, folder) => {
      let data = resolverData.get(folder);
      if (!data) {
        data = {
          id: /* @__PURE__ */ new Map(),
          label: /* @__PURE__ */ new Map(),
          identifier: /* @__PURE__ */ new Map()
        };
        resolverData.set(folder, data);
      }
      for (const task of tasks3) {
        data.id.set(task._id, task);
        data.label.set(task._label, task);
        if (task.configurationProperties.identifier) {
          data.identifier.set(task.configurationProperties.identifier, task);
        }
        if (group2 && task.configurationProperties.group === group2) {
          if (task._source.kind === TaskSourceKind.Workspace) {
            workspaceTasks.push(task);
          } else {
            extensionTasks.push(task);
          }
        }
      }
    });
    const resolver = {
      resolve: async (uri, alias) => {
        const data = resolverData.get(typeof uri === "string" ? uri : uri.toString());
        if (!data) {
          return void 0;
        }
        return data.id.get(alias) || data.label.get(alias) || data.identifier.get(alias);
      }
    };
    if (workspaceTasks.length > 0) {
      if (workspaceTasks.length > 1) {
        this.Xc(localize(9974, null));
      }
      return { task: workspaceTasks[0], resolver };
    }
    if (extensionTasks.length === 0) {
      return void 0;
    }
    if (extensionTasks.length === 1) {
      return { task: extensionTasks[0], resolver };
    } else {
      const id2 = $ps();
      const task = new $jQ(id2, { kind: TaskSourceKind.InMemory, label: "inMemory" }, id2, "inMemory", { reevaluateOnRerun: true }, {
        identifier: id2,
        dependsOn: extensionTasks.map((extensionTask) => {
          return { uri: extensionTask.getWorkspaceFolder().uri, task: extensionTask._id };
        }),
        name: id2
      });
      return { task, resolver };
    }
  }
  Fc(grouped) {
    let resolverData;
    async function quickResolve(that, uri, identifier2) {
      const foundTasks = await that.Yb((task2) => {
        const taskUri = $hQ.is(task2) || $gQ.is(task2) ? task2._source.config.workspaceFolder?.uri : void 0;
        const originalUri = typeof uri === "string" ? uri : uri.toString();
        if (taskUri?.toString() !== originalUri) {
          return false;
        }
        if ($zg(identifier2)) {
          return task2._label === identifier2 || task2.configurationProperties.identifier === identifier2;
        } else {
          const keyedIdentifier = task2.getDefinition(true);
          const searchIdentifier = TaskDefinition.createTaskIdentifier(identifier2, console);
          return searchIdentifier && keyedIdentifier ? searchIdentifier._key === keyedIdentifier._key : false;
        }
      });
      if (foundTasks.length === 0) {
        return void 0;
      }
      const task = foundTasks[0];
      if ($hQ.is(task)) {
        return that.tryResolveTask(task);
      }
      return task;
    }
    async function getResolverData(that) {
      if (resolverData === void 0) {
        resolverData = /* @__PURE__ */ new Map();
        (grouped || await that.Oc()).forEach((tasks2, folder) => {
          let data = resolverData.get(folder);
          if (!data) {
            data = { label: /* @__PURE__ */ new Map(), identifier: /* @__PURE__ */ new Map(), taskIdentifier: /* @__PURE__ */ new Map() };
            resolverData.set(folder, data);
          }
          for (const task of tasks2) {
            data.label.set(task._label, task);
            if (task.configurationProperties.identifier) {
              data.identifier.set(task.configurationProperties.identifier, task);
            }
            const keyedIdentifier = task.getDefinition(true);
            if (keyedIdentifier !== void 0) {
              data.taskIdentifier.set(keyedIdentifier._key, task);
            }
          }
        });
      }
      return resolverData;
    }
    async function fullResolve(that, uri, identifier2) {
      const allResolverData = await getResolverData(that);
      const data = allResolverData.get(typeof uri === "string" ? uri : uri.toString());
      if (!data) {
        return void 0;
      }
      if ($zg(identifier2)) {
        return data.label.get(identifier2) || data.identifier.get(identifier2);
      } else {
        const key2 = TaskDefinition.createTaskIdentifier(identifier2, console);
        return key2 !== void 0 ? data.taskIdentifier.get(key2._key) : void 0;
      }
    }
    return {
      resolve: async (uri, identifier2) => {
        if (!identifier2) {
          return void 0;
        }
        if (resolverData === void 0 && grouped === void 0) {
          return await quickResolve(this, uri, identifier2) ?? fullResolve(this, uri, identifier2);
        } else {
          return fullResolve(this, uri, identifier2);
        }
      }
    };
  }
  async Gc() {
    let SaveBeforeRunConfigOptions;
    (function(SaveBeforeRunConfigOptions2) {
      SaveBeforeRunConfigOptions2["Always"] = "always";
      SaveBeforeRunConfigOptions2["Never"] = "never";
      SaveBeforeRunConfigOptions2["Prompt"] = "prompt";
    })(SaveBeforeRunConfigOptions || (SaveBeforeRunConfigOptions = {}));
    const saveBeforeRunTaskConfig = this.bb.getValue(
      "task.saveBeforeRun"
      /* TaskSettingId.SaveBeforeRun */
    );
    if (saveBeforeRunTaskConfig === SaveBeforeRunConfigOptions.Never) {
      return false;
    } else if (saveBeforeRunTaskConfig === SaveBeforeRunConfigOptions.Prompt && this.hb.editors.some((e) => e.isDirty())) {
      const { confirmed } = await this.vb.confirm({
        message: localize(9975, null),
        detail: localize(9976, null),
        primaryButton: localize(9977, null),
        cancelButton: localize(9978, null)
      });
      if (!confirmed) {
        return false;
      }
    }
    await this.hb.saveAll({
      reason: 2
      /* SaveReason.AUTO */
    });
    return true;
  }
  async Hc(task, resolver, runSource) {
    let taskToRun = task;
    if (await this.Gc()) {
      await this.bb.reloadConfiguration();
      await this.Rc();
      const taskFolder = task.getWorkspaceFolder();
      const taskIdentifier2 = task.configurationProperties.identifier;
      const taskType2 = $gQ.is(task) ? task.customizes()?.type : $iQ.is(task) ? task.type : void 0;
      taskToRun = (taskFolder && taskIdentifier2 && runSource === 1 ? await this.getTask(taskFolder, taskIdentifier2, false, taskType2) : task) ?? task;
    }
    await $_P.onReady();
    const executeResult = runSource === 4 ? this.Mc().reconnect(taskToRun, resolver) : this.Mc().run(taskToRun, resolver);
    if (executeResult) {
      return this.Ic(executeResult, runSource);
    }
    return { exitCode: 0 };
  }
  async Ic(executeResult, runSource) {
    if (runSource === 1) {
      await this.hc(executeResult.task);
    }
    if (executeResult.kind === 2) {
      const active = executeResult.active;
      if (active && active.same && runSource === 2 || runSource === 4) {
        this.Gb.debug("Ignoring task that is already active", executeResult.task);
        return executeResult.promise;
      }
      if (active && active.same) {
        if (this.I?.isTaskVisible(executeResult.task)) {
          const message = localize(9979, null, executeResult.task.getQualifiedLabel());
          const lastInstance = this.Mc().getLastInstance(executeResult.task) ?? executeResult.task;
          this.wb.prompt(severity_default.Warning, message, [
            {
              label: localize(9980, null),
              run: () => this.terminate(lastInstance)
            },
            {
              label: localize(9981, null),
              run: () => this.Jc(lastInstance)
            }
          ], { sticky: true });
        } else {
          this.I?.revealTask(executeResult.task);
        }
      } else {
        throw new $VSb(
          severity_default.Warning,
          localize(9982, null),
          1
          /* TaskErrors.RunningTask */
        );
      }
    }
    this.hc(executeResult.task);
    return executeResult.promise;
  }
  async Jc(task) {
    if (!this.I) {
      return;
    }
    const response = await this.I.terminate(task);
    if (response.success) {
      try {
        await this.run(task);
      } catch {
      }
    } else {
      this.wb.warn(localize(9983, null, $zg(task) ? task : task.configurationProperties.name));
    }
  }
  async terminate(task) {
    if (!await this.qd()) {
      return { success: true, task: void 0 };
    }
    if (!this.I) {
      return { success: true, task: void 0 };
    }
    return this.I.terminate(task);
  }
  Kc() {
    if (!this.I) {
      return Promise.resolve([]);
    }
    return this.I.terminateAll();
  }
  Lc() {
    return new $Dhc(this.qb, this.rb, this.db, this.eb, this.fb, this.cb, this.mb, this.pb, this.jb, this.yb, $Jhc_1.OutputChannelId, this.ib, this.zb, this.Ab, this.Db, this.Gb, this.wb, this.Jb, (workspaceFolder) => {
      if (workspaceFolder) {
        return this.Xb(workspaceFolder.uri.scheme);
      } else if (this.F.size > 0) {
        const infos = Array.from(this.F.entries());
        const notFile = infos.filter((info) => info[0] !== Schemas.file);
        if (notFile.length > 0) {
          return notFile[0][1][0];
        }
        return infos[0][1][0];
      } else {
        return void 0;
      }
    });
  }
  Nc(type) {
    const definition = $aQ.get(type);
    return !definition || !definition.when || this.xb.contextMatchesRules(definition.when);
  }
  async Oc(filter, waitToActivate, knownOnlyOrTrusted) {
    await this.R;
    const type = filter?.type;
    const needsRecentTasksMigration = this.nd();
    if (!waitToActivate) {
      await this.Tb(filter?.type);
    }
    const validTypes = /* @__PURE__ */ Object.create(null);
    $aQ.all().forEach((definition) => validTypes[definition.taskType] = true);
    validTypes["shell"] = true;
    validTypes["process"] = true;
    const contributedTaskSets = await new Promise((resolve) => {
      const result2 = [];
      let counter = 0;
      const done = (value) => {
        if (value) {
          result2.push(value);
        }
        if (--counter === 0) {
          resolve(result2);
        }
      };
      const error = (error2) => {
        try {
          if (error2 && $zg(error2.message)) {
            this.Xc(`Error: ${error2.message}
`);
            this.Vb();
          } else {
            this.Xc("Unknown error received while collecting tasks from providers.");
            this.Vb();
          }
        } finally {
          if (--counter === 0) {
            resolve(result2);
          }
        }
      };
      if (this.qc() && this.Qb === 2 && this.C.size > 0) {
        let foundAnyProviders = false;
        for (const [handle2, provider] of this.C) {
          const providerType = this.D.get(handle2);
          if (type === void 0 || type === providerType) {
            if (providerType && !this.Nc(providerType)) {
              continue;
            }
            foundAnyProviders = true;
            counter++;
            $Lh(provider.provideTasks(validTypes).then((taskSet) => {
              for (const task of taskSet.tasks) {
                if (task.type !== this.D.get(handle2)) {
                  this.Xc(localize(9984, null, this.D.get(handle2), task.type));
                  if (task.type !== "shell" && task.type !== "process") {
                    this.Vb();
                  }
                  break;
                }
              }
              return done(taskSet);
            }, error), 5e3, () => {
              console.error("Timed out getting tasks from ", providerType);
              done(void 0);
            });
          }
        }
        if (!foundAnyProviders) {
          resolve(result2);
        }
      } else {
        resolve(result2);
      }
    });
    const result = new TaskMap();
    const contributedTasks = new TaskMap();
    for (const set of contributedTaskSets) {
      for (const task of set.tasks) {
        const workspaceFolder = task.getWorkspaceFolder();
        if (workspaceFolder) {
          contributedTasks.add(workspaceFolder, task);
        }
      }
    }
    try {
      let tasks2 = [];
      if (!knownOnlyOrTrusted || this.Fb.isWorkspaceTrusted()) {
        tasks2 = Array.from(await this.getWorkspaceTasks());
      }
      await Promise.all(this.Pc(tasks2, filter, result, contributedTasks, waitToActivate));
      if (needsRecentTasksMigration) {
        await this.od(result.all());
      }
      return result;
    } catch {
      const result2 = new TaskMap();
      for (const set of contributedTaskSets) {
        for (const task of set.tasks) {
          const folder = task.getWorkspaceFolder();
          if (folder) {
            result2.add(folder, task);
          }
        }
      }
      return result2;
    }
  }
  Pc(customTasksKeyValuePairs, filter, result, contributedTasks, waitToActivate) {
    return customTasksKeyValuePairs.map(async ([key2, folderTasks]) => {
      const contributed = contributedTasks.get(key2);
      if (!folderTasks.set) {
        if (contributed) {
          result.add(key2, ...contributed);
        }
        return;
      }
      if (this.jb.getWorkbenchState() === 1) {
        result.add(key2, ...folderTasks.set.tasks);
      } else {
        const configurations = folderTasks.configurations;
        const legacyTaskConfigurations = folderTasks.set ? this.Qc(folderTasks.set) : void 0;
        const customTasksToDelete = [];
        if (configurations || legacyTaskConfigurations) {
          const unUsedConfigurations = /* @__PURE__ */ new Set();
          if (configurations) {
            Object.keys(configurations.byIdentifier).forEach((key3) => unUsedConfigurations.add(key3));
          }
          for (const task of contributed) {
            if (!$iQ.is(task)) {
              continue;
            }
            if (configurations) {
              const configuringTask = configurations.byIdentifier[task.defines._key];
              if (configuringTask) {
                unUsedConfigurations.delete(task.defines._key);
                result.add(key2, $thc(task, configuringTask));
              } else {
                result.add(key2, task);
              }
            } else if (legacyTaskConfigurations) {
              const configuringTask = legacyTaskConfigurations[task.defines._key];
              if (configuringTask) {
                result.add(key2, $thc(task, configuringTask));
                customTasksToDelete.push(configuringTask);
              } else {
                result.add(key2, task);
              }
            } else {
              result.add(key2, task);
            }
          }
          if (customTasksToDelete.length > 0) {
            const toDelete = customTasksToDelete.reduce((map, task) => {
              map[task._id] = true;
              return map;
            }, /* @__PURE__ */ Object.create(null));
            for (const task of folderTasks.set.tasks) {
              if (toDelete[task._id]) {
                continue;
              }
              result.add(key2, task);
            }
          } else {
            result.add(key2, ...folderTasks.set.tasks);
          }
          const unUsedConfigurationsAsArray = Array.from(unUsedConfigurations);
          const unUsedConfigurationPromises = unUsedConfigurationsAsArray.map(async (value) => {
            const configuringTask = configurations.byIdentifier[value];
            if (filter?.type && filter.type !== configuringTask.configures.type) {
              return;
            }
            let requiredTaskProviderUnavailable = false;
            for (const [handle2, provider] of this.C) {
              const providerType = this.D.get(handle2);
              if (configuringTask.type === providerType) {
                if (providerType && !this.Nc(providerType)) {
                  requiredTaskProviderUnavailable = true;
                  continue;
                }
                try {
                  const resolvedTask = await provider.resolveTask(configuringTask);
                  if (resolvedTask && resolvedTask._id === configuringTask._id) {
                    result.add(key2, $thc(resolvedTask, configuringTask));
                    return;
                  }
                } catch (error) {
                }
              }
            }
            if (requiredTaskProviderUnavailable) {
              this.Xc(localize(9985, null, configuringTask.configures.type));
            } else if (!waitToActivate) {
              this.Xc(localize(9986, null, configuringTask.configures.type, JSON.stringify(configuringTask._source.config.element, void 0, 4)));
              this.Vb();
            }
          });
          await Promise.all(unUsedConfigurationPromises);
        } else {
          result.add(key2, ...folderTasks.set.tasks);
          result.add(key2, ...contributed);
        }
      }
    });
  }
  Qc(workspaceTasks) {
    let result;
    function getResult() {
      if (result) {
        return result;
      }
      result = /* @__PURE__ */ Object.create(null);
      return result;
    }
    for (const task of workspaceTasks.tasks) {
      if ($gQ.is(task)) {
        const commandName = task.command && task.command.name;
        if (commandName === "gulp" || commandName === "grunt" || commandName === "jake") {
          const identifier2 = KeyedTaskIdentifier.create({
            type: commandName,
            task: task.configurationProperties.name
          });
          getResult()[identifier2._key] = task;
        }
      }
    }
    return result;
  }
  async getWorkspaceTasks(runSource = 1) {
    if (!await this.qd()) {
      return /* @__PURE__ */ new Map();
    }
    await $Lh(this.R, 2e3, () => {
      this.Gb.warn("Timed out waiting for all supported executions");
    });
    await this.H;
    if (this.G) {
      return this.G;
    }
    return this.Rc(runSource);
  }
  Rc(runSource = 1) {
    this.G = this.Tc(runSource);
    return this.G;
  }
  async Sc() {
    let folder = this.Nb.length > 0 ? this.Nb[0] : void 0;
    if (!folder) {
      const userhome = await this.Ab.userHome();
      folder = new $$k({ uri: userhome, name: $sh(userhome), index: 0 });
    }
    return folder;
  }
  async Tc(runSource = 1) {
    const promises = [];
    for (const folder2 of this.Nb) {
      promises.push(this.Vc(folder2, runSource));
    }
    const values = await Promise.all(promises);
    const result = /* @__PURE__ */ new Map();
    for (const value of values) {
      if (value) {
        result.set(value.workspaceFolder.uri.toString(), value);
      }
    }
    const folder = await this.Sc();
    if (this.jb.getWorkbenchState() !== 1) {
      const workspaceFileTasks = await this.Yc(folder, runSource);
      if (workspaceFileTasks && this.w && this.w.configuration) {
        result.set(this.w.configuration.toString(), workspaceFileTasks);
      }
    }
    const userTasks = await this.Zc(folder, runSource);
    if (userTasks) {
      result.set($bQ, userTasks);
    }
    return result;
  }
  get Uc() {
    return $XSb.getValue(this.xb) === true && $ZSb.getValue(this.xb) === true;
  }
  async Vc(workspaceFolder, runSource = 1) {
    const workspaceFolderConfiguration = this.s === ExecutionEngine.Process ? await this.cd(workspaceFolder) : await this.bd(workspaceFolder);
    if (!workspaceFolderConfiguration || !workspaceFolderConfiguration.config || workspaceFolderConfiguration.hasErrors) {
      return Promise.resolve({ workspaceFolder, set: void 0, configurations: void 0, hasErrors: workspaceFolderConfiguration ? workspaceFolderConfiguration.hasErrors : false });
    }
    await $_P.onReady();
    const taskSystemInfo = this.Xb(workspaceFolder.uri.scheme);
    const problemReporter = new ProblemReporter(this.P);
    const parseResult = $shc(workspaceFolder, void 0, taskSystemInfo ? taskSystemInfo.platform : $x, workspaceFolderConfiguration.config, problemReporter, TaskConfigSource.TasksJson, this.xb);
    let hasErrors = false;
    if (!parseResult.validationStatus.isOK() && parseResult.validationStatus.state !== 1) {
      hasErrors = true;
      this.Vb(runSource);
    }
    if (problemReporter.status.isFatal()) {
      problemReporter.fatal(localize(9987, null));
      return { workspaceFolder, set: void 0, configurations: void 0, hasErrors };
    }
    let customizedTasks;
    if (parseResult.configured && parseResult.configured.length > 0) {
      customizedTasks = {
        byIdentifier: /* @__PURE__ */ Object.create(null)
      };
      for (const task of parseResult.configured) {
        customizedTasks.byIdentifier[task.configures._key] = task;
      }
    }
    if (!this.Uc && parseResult.custom.length > 0) {
      console.warn("Custom workspace tasks are not supported.");
    }
    return { workspaceFolder, set: { tasks: this.Uc ? parseResult.custom : [] }, configurations: customizedTasks, hasErrors };
  }
  Wc(config, location3) {
    if (!config) {
      return { config: void 0, hasParseErrors: false };
    }
    const parseErrors = config.$parseErrors;
    if (parseErrors) {
      let isAffected = false;
      for (const parseError of parseErrors) {
        if (/tasks\.json$/.test(parseError)) {
          isAffected = true;
          break;
        }
      }
      if (isAffected) {
        this.Xc(localize(9988, null, location3));
        this.Vb();
        return { config, hasParseErrors: true };
      }
    }
    return { config, hasParseErrors: false };
  }
  Xc(value, verbose) {
    if (!verbose || this.bb.getValue(
      "task.verboseLogging"
      /* TaskSettingId.VerboseLogging */
    )) {
      this.P.append(value + "\n");
    }
  }
  async Yc(workspaceFolder, runSource = 1) {
    if (this.s === ExecutionEngine.Process) {
      return this.$c(workspaceFolder);
    }
    const workspaceFileConfig = this.gd(workspaceFolder, TaskSourceKind.WorkspaceFile);
    const configuration2 = this.Wc(workspaceFileConfig.config, localize(9989, null));
    const customizedTasks = {
      byIdentifier: /* @__PURE__ */ Object.create(null)
    };
    const custom = [];
    await this.ad(workspaceFolder, configuration2.config, runSource, custom, customizedTasks.byIdentifier, TaskConfigSource.WorkspaceFile);
    const engine = configuration2.config ? ExecutionEngine2.from(configuration2.config) : ExecutionEngine.Terminal;
    if (engine === ExecutionEngine.Process) {
      this.wb.warn(localize(9990, null));
      return this.$c(workspaceFolder);
    }
    return { workspaceFolder, set: { tasks: custom }, configurations: customizedTasks, hasErrors: configuration2.hasParseErrors };
  }
  async Zc(workspaceFolder, runSource = 1) {
    if (this.s === ExecutionEngine.Process) {
      return this.$c(workspaceFolder);
    }
    const userTasksConfig = this.gd(workspaceFolder, TaskSourceKind.User);
    const configuration2 = this.Wc(userTasksConfig.config, localize(9991, null));
    const customizedTasks = {
      byIdentifier: /* @__PURE__ */ Object.create(null)
    };
    const custom = [];
    await this.ad(workspaceFolder, configuration2.config, runSource, custom, customizedTasks.byIdentifier, TaskConfigSource.User);
    const engine = configuration2.config ? ExecutionEngine2.from(configuration2.config) : ExecutionEngine.Terminal;
    if (engine === ExecutionEngine.Process) {
      this.wb.warn(localize(9992, null));
      return this.$c(workspaceFolder);
    }
    return { workspaceFolder, set: { tasks: custom }, configurations: customizedTasks, hasErrors: configuration2.hasParseErrors };
  }
  $c(workspaceFolder) {
    return { workspaceFolder, set: void 0, configurations: void 0, hasErrors: false };
  }
  async ad(workspaceFolder, config, runSource, custom, customized, source, isRecentTask = false) {
    if (!config) {
      return false;
    } else if (!workspaceFolder) {
      this.Gb.trace("TaskService.computeTasksForSingleConfig: no workspace folder for worskspace", this.w?.id);
      return false;
    }
    const taskSystemInfo = this.Xb(workspaceFolder.uri.scheme);
    const problemReporter = new ProblemReporter(this.P);
    const parseResult = $shc(workspaceFolder, this.w, taskSystemInfo ? taskSystemInfo.platform : $x, config, problemReporter, source, this.xb, isRecentTask);
    let hasErrors = false;
    if (!parseResult.validationStatus.isOK() && parseResult.validationStatus.state !== 1) {
      this.Vb(runSource);
      hasErrors = true;
    }
    if (problemReporter.status.isFatal()) {
      problemReporter.fatal(localize(9993, null));
      return hasErrors;
    }
    if (parseResult.configured && parseResult.configured.length > 0) {
      for (const task of parseResult.configured) {
        customized[task.configures._key] = task;
      }
    }
    if (!this.Uc && parseResult.custom.length > 0) {
      console.warn("Custom workspace tasks are not supported.");
    } else {
      for (const task of parseResult.custom) {
        custom.push(task);
      }
    }
    return hasErrors;
  }
  bd(workspaceFolder) {
    const { config, hasParseErrors } = this.gd(workspaceFolder);
    return Promise.resolve({ workspaceFolder, config, hasErrors: hasParseErrors });
  }
  dd() {
    const workspaceFolders = [];
    const ignoredWorkspaceFolders = [];
    let executionEngine = ExecutionEngine.Terminal;
    let schemaVersion = 2;
    let workspace2;
    if (this.jb.getWorkbenchState() === 2) {
      const workspaceFolder = this.jb.getWorkspace().folders[0];
      workspaceFolders.push(workspaceFolder);
      executionEngine = this.ed(workspaceFolder);
      const telemetryData = {
        executionEngineVersion: executionEngine
      };
      this.kb.publicLog("taskService.engineVersion", telemetryData);
      schemaVersion = this.fd(workspaceFolder);
    } else if (this.jb.getWorkbenchState() === 3) {
      workspace2 = this.jb.getWorkspace();
      for (const workspaceFolder of this.jb.getWorkspace().folders) {
        if (schemaVersion === this.fd(workspaceFolder)) {
          workspaceFolders.push(workspaceFolder);
        } else {
          ignoredWorkspaceFolders.push(workspaceFolder);
          this.Xc(localize(9994, null, workspaceFolder.uri.fsPath));
        }
      }
    }
    return [workspaceFolders, ignoredWorkspaceFolders, executionEngine, schemaVersion, workspace2];
  }
  ed(workspaceFolder) {
    const { config } = this.gd(workspaceFolder);
    if (!config) {
      return ExecutionEngine._default;
    }
    return ExecutionEngine2.from(config);
  }
  fd(workspaceFolder) {
    const { config } = this.gd(workspaceFolder);
    if (!config) {
      return 2;
    }
    return JsonSchemaVersion2.from(config);
  }
  gd(workspaceFolder, source) {
    let result;
    if (source !== TaskSourceKind.User && this.jb.getWorkbenchState() === 1) {
      result = void 0;
    } else {
      const wholeConfig = this.bb.inspect("tasks", { resource: workspaceFolder.uri });
      switch (source) {
        case TaskSourceKind.User: {
          if (wholeConfig.userValue !== wholeConfig.workspaceFolderValue) {
            result = $Lv(wholeConfig.userValue);
          }
          break;
        }
        case TaskSourceKind.Workspace:
          result = $Lv(wholeConfig.workspaceFolderValue);
          break;
        case TaskSourceKind.WorkspaceFile: {
          if (this.jb.getWorkbenchState() === 3 && wholeConfig.workspaceFolderValue !== wholeConfig.workspaceValue) {
            result = $Lv(wholeConfig.workspaceValue);
          }
          break;
        }
        default:
          result = $Lv(wholeConfig.workspaceFolderValue);
      }
    }
    if (!result) {
      return { config: void 0, hasParseErrors: false };
    }
    const parseErrors = result.$parseErrors;
    if (parseErrors) {
      let isAffected = false;
      for (const parseError of parseErrors) {
        if (/tasks\.json$/.test(parseError)) {
          isAffected = true;
          break;
        }
      }
      if (isAffected) {
        this.Xc(localize(9995, null));
        this.Vb();
        return { config: void 0, hasParseErrors: true };
      }
    }
    return { config: result, hasParseErrors: false };
  }
  inTerminal() {
    if (this.I) {
      return this.I instanceof $Dhc;
    }
    return this.s === ExecutionEngine.Terminal;
  }
  configureAction() {
    const thisCapture = this;
    return new class extends $Um {
      constructor() {
        super(ConfigureTaskAction.ID, ConfigureTaskAction.TEXT.value, void 0, true, () => {
          thisCapture.Jd();
          return Promise.resolve(void 0);
        });
      }
    }();
  }
  hd(err) {
    let showOutput = true;
    if (err instanceof $VSb) {
      const buildError = err;
      const needsConfig = buildError.code === 0 || buildError.code === 2 || buildError.code === 3;
      const needsTerminate = buildError.code === 1;
      if (needsConfig || needsTerminate) {
        this.wb.prompt(buildError.severity, buildError.message, [{
          label: needsConfig ? ConfigureTaskAction.TEXT.value : localize(9996, null),
          run: () => {
            if (needsConfig) {
              this.Jd();
            } else {
              this.Ad();
            }
          }
        }]);
      } else {
        this.wb.notify({ severity: buildError.severity, message: buildError.message });
      }
    } else if (err instanceof Error) {
      const error = err;
      this.wb.error(error.message);
      showOutput = false;
    } else if ($zg(err)) {
      this.wb.error(err);
    } else {
      this.wb.error(localize(9997, null));
    }
    if (showOutput) {
      this.Vb();
    }
  }
  jd() {
    return this.bb.getValue($Ehc);
  }
  async kd(tasks2, group2 = false, sort2 = false, selectedEntry, includeRecents = true) {
    let encounteredTasks = {};
    if (tasks2 === void 0 || tasks2 === null || tasks2.length === 0) {
      return [];
    }
    const TaskQuickPickEntry = (task) => {
      const newEntry = { label: task._label, description: this.getTaskDescription(task), task, detail: this.jd() ? task.configurationProperties.detail : void 0 };
      if (encounteredTasks[task._id]) {
        if (encounteredTasks[task._id].length === 1) {
          encounteredTasks[task._id][0].label += " (1)";
        }
        newEntry.label = newEntry.label + " (" + (encounteredTasks[task._id].length + 1).toString() + ")";
      } else {
        encounteredTasks[task._id] = [];
      }
      encounteredTasks[task._id].push(newEntry);
      return newEntry;
    };
    function fillEntries(entries3, tasks3, groupLabel) {
      if (tasks3.length) {
        entries3.push({ type: "separator", label: groupLabel });
      }
      for (const task of tasks3) {
        const entry = TaskQuickPickEntry(task);
        entry.buttons = [{ iconClass: ThemeIcon.asClassName($Hhc), tooltip: localize(9998, null) }];
        if (selectedEntry && task === selectedEntry.task) {
          entries3.unshift(selectedEntry);
        } else {
          entries3.push(entry);
        }
      }
    }
    let entries2;
    if (group2) {
      entries2 = [];
      if (tasks2.length === 1) {
        entries2.push(TaskQuickPickEntry(tasks2[0]));
      } else {
        const recentlyUsedTasks = await this.getSavedTasks("historical");
        const recent = [];
        const recentSet = /* @__PURE__ */ new Set();
        let configured = [];
        let detected = [];
        const taskMap = /* @__PURE__ */ Object.create(null);
        tasks2.forEach((task) => {
          const key2 = task.getCommonTaskId();
          if (key2) {
            taskMap[key2] = task;
          }
        });
        recentlyUsedTasks.reverse().forEach((recentTask) => {
          const key2 = recentTask.getCommonTaskId();
          if (key2) {
            recentSet.add(key2);
            const task = taskMap[key2];
            if (task) {
              recent.push(task);
            }
          }
        });
        for (const task of tasks2) {
          const key2 = task.getCommonTaskId();
          if (!key2 || !recentSet.has(key2)) {
            if (task._source.kind === TaskSourceKind.Workspace || task._source.kind === TaskSourceKind.User) {
              configured.push(task);
            } else {
              detected.push(task);
            }
          }
        }
        const sorter3 = this.createSorter();
        if (includeRecents) {
          fillEntries(entries2, recent, localize(9999, null));
        }
        configured = configured.sort((a, b) => sorter3.compare(a, b));
        fillEntries(entries2, configured, localize(1e4, null));
        detected = detected.sort((a, b) => sorter3.compare(a, b));
        fillEntries(entries2, detected, localize(10001, null));
      }
    } else {
      if (sort2) {
        const sorter3 = this.createSorter();
        tasks2 = tasks2.sort((a, b) => sorter3.compare(a, b));
      }
      entries2 = tasks2.map((task) => TaskQuickPickEntry(task));
    }
    encounteredTasks = {};
    return entries2;
  }
  async ld(placeHolder, defaultEntry, type, name) {
    return this.Jb.createInstance($Ihc).show(placeHolder, defaultEntry, type, name);
  }
  async md(tasks2, placeHolder, defaultEntry, group2 = false, sort2 = false, selectedEntry, additionalEntries, name) {
    const resolvedTasks = await tasks2;
    const entries2 = await $Lh(this.kd(resolvedTasks, group2, sort2, selectedEntry), 200, () => void 0);
    if (!entries2) {
      return void 0;
    }
    if (entries2.length === 1 && this.bb.getValue($Fhc)) {
      return entries2[0];
    } else if (entries2.length === 0 && defaultEntry) {
      entries2.push(defaultEntry);
    } else if (entries2.length > 1 && additionalEntries && additionalEntries.length > 0) {
      entries2.push({ type: "separator", label: "" });
      entries2.push(additionalEntries[0]);
    }
    return this.ob.pick(entries2, {
      value: name,
      placeHolder,
      matchOnDescription: true,
      onDidTriggerItemButton: (context) => {
        const task = context.item.task;
        this.ob.cancel();
        if ($iQ.is(task)) {
          this.customize(task, void 0, true);
        } else if ($gQ.is(task)) {
          this.openConfig(task);
        }
      }
    });
  }
  nd() {
    return this.getRecentlyUsedTasksV1().size > 0 && this.cc("historical").size === 0;
  }
  async od(tasks2) {
    if (!this.nd()) {
      return;
    }
    const recentlyUsedTasks = this.getRecentlyUsedTasksV1();
    const taskMap = /* @__PURE__ */ Object.create(null);
    tasks2.forEach((task) => {
      const key2 = task.getKey();
      if (key2) {
        taskMap[key2] = task;
      }
    });
    const reversed = [...recentlyUsedTasks.keys()].reverse();
    for (const key2 in reversed) {
      const task = taskMap[key2];
      if (task) {
        await this.hc(task);
      }
    }
    this.sb.remove(
      $Jhc_1.c,
      1
      /* StorageScope.WORKSPACE */
    );
  }
  pd() {
    if (this.Ob.length === 0 || !this.Rb) {
      return Promise.resolve(void 0);
    }
    this.wb.prompt(severity_default.Info, localize(10002, null, this.Ob.map((f) => f.name).join(", ")), [{
      label: localize(10003, null),
      isSecondary: true,
      run: () => {
        this.sb.store(
          $Jhc_1.j,
          true,
          1,
          1
          /* StorageTarget.MACHINE */
        );
        this.z = false;
      }
    }]);
    return Promise.resolve(void 0);
  }
  async qd() {
    if ($1Sb && !$2Sb) {
      return false;
    }
    await this.Fb.workspaceTrustInitialized;
    if (!this.Fb.isWorkspaceTrusted()) {
      return await this.Eb.requestWorkspaceTrust({
        message: localize(10004, null)
      }) === true;
    }
    return true;
  }
  async rd(filter) {
    if (!this.n) {
      return;
    }
    if (!filter) {
      return this.td();
    }
    const type = typeof filter === "string" ? void 0 : filter.type;
    const taskName = typeof filter === "string" ? filter : filter.task;
    const grouped = await this.Oc({ type });
    const identifier2 = this.Cd(filter);
    const tasks2 = grouped.all();
    const resolver = this.Fc(grouped);
    const folderURIs = this.jb.getWorkspace().folders.map((folder) => folder.uri);
    if (this.jb.getWorkbenchState() === 3) {
      folderURIs.push(this.jb.getWorkspace().configuration);
    }
    folderURIs.push($bQ);
    if (identifier2) {
      for (const uri of folderURIs) {
        const task = await resolver.resolve(uri, identifier2);
        if (task) {
          this.run(task);
          return;
        }
      }
    }
    const exactMatchTask = !taskName ? void 0 : tasks2.find((t) => t.configurationProperties.identifier === taskName || t.getDefinition(true)?.configurationProperties?.identifier === taskName);
    if (!exactMatchTask) {
      return this.td(tasks2, type, taskName);
    }
    for (const uri of folderURIs) {
      const task = await resolver.resolve(uri, taskName);
      if (task) {
        await this.run(
          task,
          { attachProblemMatcher: true },
          1
          /* TaskRunSource.User */
        );
        return;
      }
    }
  }
  sd(filter) {
    if (!this.$b(filter)) {
      return { tasks: Promise.resolve([]), grouped: Promise.resolve(new TaskMap()) };
    }
    const grouped = this.Oc(filter);
    const tasks2 = grouped.then((map) => {
      if (!filter || !filter.type) {
        return map.all();
      }
      const result = [];
      map.forEach((tasks3) => {
        for (const task of tasks3) {
          if ($iQ.is(task) && task.defines.type === filter.type) {
            result.push(task);
          } else if ($gQ.is(task)) {
            if (task.type === filter.type) {
              result.push(task);
            } else {
              const customizes = task.customizes();
              if (customizes && customizes.type === filter.type) {
                result.push(task);
              }
            }
          }
        }
      });
      return result;
    });
    return { tasks: tasks2, grouped };
  }
  td(tasks2, type, name) {
    const pickThen = (task) => {
      if (task === void 0) {
        return;
      }
      if (task === null) {
        this.Jd();
      } else {
        this.run(
          task,
          { attachProblemMatcher: true },
          1
          /* TaskRunSource.User */
        ).then(void 0, (reason) => {
        });
      }
    };
    const placeholder = localize(10005, null);
    this.pd().then(() => {
      if (this.bb.getValue(USE_SLOW_PICKER)) {
        let taskResult = void 0;
        if (!tasks2) {
          taskResult = this.sd();
        }
        this.md(tasks2 ? tasks2 : taskResult.tasks, placeholder, {
          label: "$(plus) " + localize(10006, null),
          task: null
        }, true, void 0, void 0, void 0, name).then((entry) => {
          return pickThen(entry ? entry.task : void 0);
        });
      } else {
        this.ld(placeholder, {
          label: "$(plus) " + localize(10007, null),
          task: null
        }, type, name).then(pickThen);
      }
    });
  }
  ud() {
    $_P.onReady().then(() => {
      return this.hb.saveAll({
        reason: 2
        /* SaveReason.AUTO */
      }).then(() => {
        const executeResult = this.Mc().rerun();
        if (executeResult) {
          return this.Ic(executeResult);
        } else {
          if (!this.O.get()) {
            this.td();
          }
          return Promise.resolve(void 0);
        }
      });
    });
  }
  /**
   *
   * @param tasks - The tasks which need to be filtered
   * @param tasksInList - This tells splitPerGroupType to filter out globbed tasks (into defaults)
   * @returns
   */
  vd(tasks2, taskGlobsInList = false) {
    const defaults = [];
    for (const task of tasks2.filter((t) => !!t.configurationProperties.group)) {
      if (taskGlobsInList && typeof task.configurationProperties.group.isDefault === "string") {
        defaults.push(task);
      } else if (!taskGlobsInList && task.configurationProperties.group.isDefault === true) {
        defaults.push(task);
      }
    }
    return defaults;
  }
  wd(taskGroup, strings, configure, legacyCommand) {
    if (this.Qb === 1) {
      legacyCommand();
      return;
    }
    const options3 = {
      location: 10,
      title: strings.fetching
    };
    const promise = (async () => {
      async function runSingleTask(task, problemMatcherOptions, that) {
        that.run(
          task,
          problemMatcherOptions,
          1
          /* TaskRunSource.User */
        ).then(void 0, (reason) => {
        });
      }
      const chooseAndRunTask = (tasks2) => {
        this.pd().then(() => {
          this.md(tasks2, strings.select, {
            label: strings.notFoundConfigure,
            task: null
          }, true).then((entry) => {
            const task = entry ? entry.task : void 0;
            if (task === void 0) {
              return;
            }
            if (task === null) {
              configure.apply(this);
              return;
            }
            runSingleTask(task, { attachProblemMatcher: true }, this);
          });
        });
      };
      let groupTasks = [];
      const { globGroupTasks, globTasksDetected } = await this.xd(taskGroup._id);
      groupTasks = [...globGroupTasks];
      if (!globTasksDetected && groupTasks.length === 0) {
        groupTasks = await this.Zb(taskGroup, true);
      }
      const handleMultipleTasks = (areGlobTasks) => {
        return this.wc(taskGroup).then((tasks2) => {
          if (tasks2.length > 0) {
            const defaults = this.vd(tasks2, areGlobTasks);
            if (defaults.length === 1) {
              runSingleTask(defaults[0], void 0, this);
              return;
            } else if (defaults.length > 0) {
              tasks2 = defaults;
            }
          }
          chooseAndRunTask(tasks2);
        });
      };
      const resolveTaskAndRun = (taskGroupTask) => {
        if ($hQ.is(taskGroupTask)) {
          this.tryResolveTask(taskGroupTask).then((resolvedTask) => {
            runSingleTask(resolvedTask, void 0, this);
          });
        } else {
          runSingleTask(taskGroupTask, void 0, this);
        }
      };
      if (groupTasks.length === 1) {
        return resolveTaskAndRun(groupTasks[0]);
      }
      if (globTasksDetected && groupTasks.length > 1) {
        return handleMultipleTasks(true);
      }
      if (!groupTasks.length) {
        groupTasks = await this.Zb(taskGroup, true);
      }
      if (groupTasks.length === 1) {
        return resolveTaskAndRun(groupTasks[0]);
      }
      return handleMultipleTasks(false);
    })();
    this.tb.withProgress(options3, () => promise);
  }
  async xd(taskGroupId) {
    let globTasksDetected = false;
    const absoluteURI = $mL.getOriginalUri(this.hb.activeEditor);
    if (absoluteURI) {
      const workspaceFolder = this.jb.getWorkspaceFolder(absoluteURI);
      if (workspaceFolder) {
        const configuredTasks = this.gd(workspaceFolder)?.config?.tasks;
        if (configuredTasks) {
          globTasksDetected = configuredTasks.filter((task) => task.group && typeof task.group !== "string" && typeof task.group.isDefault === "string").length > 0;
          if (globTasksDetected) {
            const relativePath = workspaceFolder?.uri ? $xh(workspaceFolder.uri, absoluteURI) ?? absoluteURI.path : absoluteURI.path;
            const globGroupTasks = await this.Yb((task) => {
              const currentTaskGroup = task.configurationProperties.group;
              if (currentTaskGroup && typeof currentTaskGroup !== "string" && typeof currentTaskGroup.isDefault === "string") {
                return currentTaskGroup._id === taskGroupId && $Cl(currentTaskGroup.isDefault, relativePath);
              }
              globTasksDetected = false;
              return false;
            });
            return { globGroupTasks, globTasksDetected };
          }
        }
      }
    }
    return { globGroupTasks: [], globTasksDetected };
  }
  yd() {
    if (!this.n) {
      return;
    }
    return this.wd(TaskGroup.Build, {
      fetching: localize(10008, null),
      select: localize(10009, null),
      notFoundConfigure: localize(10010, null)
    }, this.Kd, this.nc);
  }
  zd() {
    return this.wd(TaskGroup.Test, {
      fetching: localize(10011, null),
      select: localize(10012, null),
      notFoundConfigure: localize(10013, null)
    }, this.Ld, this.oc);
  }
  Ad(arg) {
    if (arg === "terminateAll") {
      this.Kc();
      return;
    }
    const runQuickPick = (promise) => {
      this.md(promise || this.getActiveTasks(), localize(10014, null), {
        label: localize(10015, null),
        task: void 0
      }, false, true, void 0, [{
        label: localize(10016, null),
        id: "terminateAll",
        task: void 0
      }]).then((entry) => {
        if (entry && entry.id === "terminateAll") {
          this.Kc();
        }
        const task = entry ? entry.task : void 0;
        if (task === void 0 || task === null) {
          return;
        }
        this.terminate(task);
      });
    };
    if (this.inTerminal()) {
      const identifier2 = this.Cd(arg);
      let promise;
      if (identifier2 !== void 0) {
        promise = this.getActiveTasks();
        promise.then((tasks2) => {
          for (const task of tasks2) {
            if (task.matches(identifier2)) {
              this.terminate(task);
              return;
            }
          }
          runQuickPick(promise);
        });
      } else {
        runQuickPick();
      }
    } else {
      this.ac().then((active) => {
        if (active) {
          this.Kc().then((responses) => {
            const response = responses[0];
            if (response.success) {
              return;
            }
            if (response.code && response.code === 3) {
              this.wb.error(localize(10017, null));
            } else {
              this.wb.error(localize(10018, null));
            }
          });
        }
      });
    }
  }
  async Bd(arg) {
    const activeTasks = await this.getActiveTasks();
    if (activeTasks.length === 1) {
      this.Jc(activeTasks[0]);
      return;
    }
    if (this.inTerminal()) {
      const identifier2 = this.Cd(arg);
      if (identifier2 !== void 0) {
        for (const task of activeTasks) {
          if (task.matches(identifier2)) {
            this.Jc(task);
            return;
          }
        }
      }
      const entry = await this.md(activeTasks, localize(10019, null), {
        label: localize(10020, null),
        task: null
      }, false, true);
      if (entry && entry.task) {
        this.Jc(entry.task);
      }
    } else {
      if (activeTasks.length > 0) {
        this.Jc(activeTasks[0]);
      }
    }
  }
  Cd(filter) {
    let result = void 0;
    if ($zg(filter)) {
      result = filter;
    } else if (filter && $zg(filter.type)) {
      result = TaskDefinition.createTaskIdentifier(filter, console);
    }
    return result;
  }
  Dd(taskConfig) {
    return !!taskConfig && !!taskConfig.tasks && taskConfig.tasks.length > 0;
  }
  Ed(resource, taskSource) {
    let configFileCreated = false;
    this.ib.stat(resource).then((stat) => stat, () => void 0).then(async (stat) => {
      const fileExists = !!stat;
      const configValue = this.bb.inspect("tasks", { resource });
      let tasksExistInFile;
      let target;
      switch (taskSource) {
        case TaskSourceKind.User:
          tasksExistInFile = this.Dd(configValue.userValue);
          target = 2;
          break;
        case TaskSourceKind.WorkspaceFile:
          tasksExistInFile = this.Dd(configValue.workspaceValue);
          target = 5;
          break;
        default:
          tasksExistInFile = this.Dd(configValue.workspaceFolderValue);
          target = 6;
      }
      let content;
      if (!tasksExistInFile) {
        const pickTemplateResult = await this.ob.pick($qhc(), { placeHolder: localize(10021, null) });
        if (!pickTemplateResult) {
          return Promise.resolve(void 0);
        }
        content = pickTemplateResult.content;
        const editorConfig = this.bb.getValue();
        if (editorConfig.editor.insertSpaces) {
          content = content.replace(/(\n)(\t+)/g, (_, s1, s2) => s1 + " ".repeat(s2.length * editorConfig.editor.tabSize));
        }
        configFileCreated = true;
      }
      if (!fileExists && content) {
        return this.lb.create([{ resource, value: content }]).then((result) => {
          return result[0].resource;
        });
      } else if (fileExists && (tasksExistInFile || content)) {
        const statResource = stat?.resource;
        if (content && statResource) {
          this.bb.updateValue("tasks", $yw(content), { resource: statResource }, target);
        }
        return statResource;
      }
      return void 0;
    }).then((resource2) => {
      if (!resource2) {
        return;
      }
      this.hb.openEditor({
        resource: resource2,
        options: {
          pinned: configFileCreated
          // pin only if config file is created #8727
        }
      });
    });
  }
  Fd(value) {
    const candidate = value;
    return candidate && !!candidate.task;
  }
  Gd(value) {
    const candidate = value;
    return candidate && !!candidate.settingType;
  }
  Hd(task) {
    if ($iQ.is(task)) {
      this.customize(task, void 0, true);
    } else if ($gQ.is(task)) {
      this.openConfig(task);
    } else if ($hQ.is(task)) {
    }
  }
  Id(selection) {
    if (!selection) {
      return;
    }
    if (this.Fd(selection)) {
      this.Hd(selection.task);
    } else if (this.Gd(selection)) {
      const taskQuickPick = this.Jb.createInstance($Ihc);
      taskQuickPick.handleSettingOption(selection.settingType);
    } else if (selection.folder && this.jb.getWorkbenchState() !== 1) {
      this.Ed(selection.folder.toResource(".vscode/tasks.json"), TaskSourceKind.Workspace);
    } else {
      const resource = this.Cc(TaskSourceKind.User);
      if (resource) {
        this.Ed(resource, TaskSourceKind.User);
      }
    }
  }
  getTaskDescription(task) {
    let description;
    if (task._source.kind === TaskSourceKind.User) {
      description = localize(10022, null);
    } else if (task._source.kind === TaskSourceKind.WorkspaceFile) {
      description = task.getWorkspaceFileName();
    } else if (this.needsFolderQualification()) {
      const workspaceFolder = task.getWorkspaceFolder();
      if (workspaceFolder) {
        description = workspaceFolder.name;
      }
    }
    return description;
  }
  async Jd() {
    if (!await this.qd()) {
      return;
    }
    let taskPromise;
    if (this.Qb === 2) {
      taskPromise = this.Oc();
    } else {
      taskPromise = Promise.resolve(new TaskMap());
    }
    const stats = this.jb.getWorkspace().folders.map((folder) => {
      return this.ib.stat(folder.toResource(".vscode/tasks.json")).then((stat) => stat, () => void 0);
    });
    const createLabel = localize(10023, null);
    const openLabel = localize(10024, null);
    const tokenSource = new $ad();
    const cancellationToken = tokenSource.token;
    const entries2 = Promise.all(stats).then((stats2) => {
      return taskPromise.then((taskMap) => {
        const entries3 = [];
        let configuredCount = 0;
        let tasks2 = taskMap.all();
        if (tasks2.length > 0) {
          tasks2 = tasks2.sort((a, b) => a._label.localeCompare(b._label));
          for (const task of tasks2) {
            const entry = { label: $Ihc.getTaskLabelWithIcon(task), task, description: this.getTaskDescription(task), detail: this.jd() ? task.configurationProperties.detail : void 0 };
            $Ihc.applyColorStyles(task, entry, this.Hb);
            entries3.push(entry);
            if (!$iQ.is(task)) {
              configuredCount++;
            }
          }
        }
        const needsCreateOrOpen = configuredCount === 0;
        if (needsCreateOrOpen || taskMap.get($bQ).length === configuredCount) {
          const label3 = stats2[0] !== void 0 ? openLabel : createLabel;
          if (entries3.length) {
            entries3.push({ type: "separator" });
          }
          entries3.push({ label: label3, folder: this.jb.getWorkspace().folders[0] });
        }
        if (entries3.length === 1 && !needsCreateOrOpen) {
          tokenSource.cancel();
        }
        return entries3;
      });
    });
    const timeout = await Promise.race([new Promise((resolve) => {
      entries2.then(() => resolve(false));
    }), new Promise((resolve) => {
      const timer = setTimeout(() => {
        clearTimeout(timer);
        resolve(true);
      }, 200);
    })]);
    if (!timeout && (await entries2).length === 1 && this.bb.getValue($Fhc)) {
      const entry = (await entries2)[0];
      if (entry.task) {
        this.Id(entry);
        return;
      }
    }
    const entriesWithSettings = entries2.then((resolvedEntries) => {
      resolvedEntries.push(...$Ihc.allSettingEntries(this.bb));
      return resolvedEntries;
    });
    this.ob.pick(entriesWithSettings, { placeHolder: localize(10025, null) }, cancellationToken).then(async (selection) => {
      if (cancellationToken.isCancellationRequested) {
        const task = (await entries2)[0];
        if (task.task) {
          selection = task;
        }
      }
      this.Id(selection);
    });
  }
  Kd() {
    if (this.Qb === 2) {
      this.tasks().then((tasks2) => {
        if (tasks2.length === 0) {
          this.Jd();
          return;
        }
        const entries2 = [];
        let selectedTask;
        let selectedEntry;
        this.pd().then(async () => {
          const { globGroupTasks } = await this.xd(TaskGroup.Build._id);
          let defaultTasks = globGroupTasks;
          if (!defaultTasks?.length) {
            defaultTasks = this.vd(tasks2, false);
          }
          let defaultBuildTask;
          if (defaultTasks.length === 1) {
            const group2 = defaultTasks[0].configurationProperties.group;
            if (group2) {
              if (typeof group2 === "string" && group2 === TaskGroup.Build._id) {
                defaultBuildTask = defaultTasks[0];
              } else {
                defaultBuildTask = defaultTasks[0];
              }
            }
          }
          for (const task of tasks2) {
            if (task === defaultBuildTask) {
              const label3 = localize(10026, null, $Ihc.getTaskLabelWithIcon(task, task.getQualifiedLabel()));
              selectedTask = task;
              selectedEntry = { label: label3, task, description: this.getTaskDescription(task), detail: this.jd() ? task.configurationProperties.detail : void 0 };
              $Ihc.applyColorStyles(task, selectedEntry, this.Hb);
            } else {
              const entry = { label: $Ihc.getTaskLabelWithIcon(task), task, description: this.getTaskDescription(task), detail: this.jd() ? task.configurationProperties.detail : void 0 };
              $Ihc.applyColorStyles(task, entry, this.Hb);
              entries2.push(entry);
            }
          }
          if (selectedEntry) {
            entries2.unshift(selectedEntry);
          }
          const tokenSource = new $ad();
          const cancellationToken = tokenSource.token;
          this.ob.pick(entries2, { placeHolder: localize(10027, null) }, cancellationToken).then(async (entry) => {
            if (cancellationToken.isCancellationRequested) {
              const task2 = (await entries2)[0];
              if (task2.task) {
                entry = task2;
              }
            }
            const task = entry && "task" in entry ? entry.task : void 0;
            if (task === void 0 || task === null) {
              return;
            }
            if (task === selectedTask && $gQ.is(task)) {
              this.openConfig(task);
            }
            if (!$jQ.is(task)) {
              this.customize(task, { group: { kind: "build", isDefault: true } }, true).then(() => {
                if (selectedTask && task !== selectedTask && !$jQ.is(selectedTask)) {
                  this.customize(selectedTask, { group: "build" }, false);
                }
              });
            }
          });
          this.ob.pick(entries2, {
            placeHolder: localize(10028, null)
          }).then((entry) => {
            const task = entry && "task" in entry ? entry.task : void 0;
            if (task === void 0 || task === null) {
              return;
            }
            if (task === selectedTask && $gQ.is(task)) {
              this.openConfig(task);
            }
            if (!$jQ.is(task)) {
              this.customize(task, { group: { kind: "build", isDefault: true } }, true).then(() => {
                if (selectedTask && task !== selectedTask && !$jQ.is(selectedTask)) {
                  this.customize(selectedTask, { group: "build" }, false);
                }
              });
            }
          });
        });
      });
    } else {
      this.Jd();
    }
  }
  Ld() {
    if (this.Qb === 2) {
      this.tasks().then((tasks2) => {
        if (tasks2.length === 0) {
          this.Jd();
          return;
        }
        let selectedTask;
        let selectedEntry;
        for (const task of tasks2) {
          const taskGroup = TaskGroup.from(task.configurationProperties.group);
          if (taskGroup && taskGroup.isDefault && taskGroup._id === TaskGroup.Test._id) {
            selectedTask = task;
            break;
          }
        }
        if (selectedTask) {
          selectedEntry = {
            label: localize(10029, null, selectedTask.getQualifiedLabel()),
            task: selectedTask,
            detail: this.jd() ? selectedTask.configurationProperties.detail : void 0
          };
        }
        this.pd().then(() => {
          this.md(tasks2, localize(10030, null), void 0, true, false, selectedEntry).then((entry) => {
            const task = entry ? entry.task : void 0;
            if (!task) {
              return;
            }
            if (task === selectedTask && $gQ.is(task)) {
              this.openConfig(task);
            }
            if (!$jQ.is(task)) {
              this.customize(task, { group: { kind: "test", isDefault: true } }, true).then(() => {
                if (selectedTask && task !== selectedTask && !$jQ.is(selectedTask)) {
                  this.customize(selectedTask, { group: "test" }, false);
                }
              });
            }
          });
        });
      });
    } else {
      this.Jd();
    }
  }
  async runShowTasks() {
    const activeTasksPromise = this.getActiveTasks();
    const activeTasks = await activeTasksPromise;
    let group2;
    if (activeTasks.length === 1) {
      this.I.revealTask(activeTasks[0]);
    } else if (activeTasks.length && activeTasks.every((task) => {
      if ($jQ.is(task)) {
        return false;
      }
      if (!group2) {
        group2 = task.command.presentation?.group;
      }
      return task.command.presentation?.group && task.command.presentation.group === group2;
    })) {
      this.I.revealTask(activeTasks[0]);
    } else {
      this.md(activeTasksPromise, localize(10031, null), {
        label: localize(10032, null),
        task: null
      }, false, true).then((entry) => {
        const task = entry ? entry.task : void 0;
        if (task === void 0 || task === null) {
          return;
        }
        this.I.revealTask(task);
      });
    }
  }
  async Md(folder) {
    const tasksFile = folder.toResource(".vscode/tasks.json");
    if (await this.ib.exists(tasksFile)) {
      const oldFile = tasksFile.with({ path: `${tasksFile.path}.old` });
      await this.ib.copy(tasksFile, oldFile, true);
      return [oldFile, tasksFile];
    }
    return void 0;
  }
  Nd(task, suppressTaskName, globalConfig) {
    if (!$gQ.is(task)) {
      return;
    }
    const configElement = {
      label: task._label
    };
    const oldTaskTypes = /* @__PURE__ */ new Set(["gulp", "jake", "grunt"]);
    if ($zg(task.command.name) && oldTaskTypes.has(task.command.name)) {
      configElement.type = task.command.name;
      configElement.task = task.command.args[0];
    } else {
      if (task.command.runtime === RuntimeType.Shell) {
        configElement.type = RuntimeType.toString(RuntimeType.Shell);
      }
      if (task.command.name && !suppressTaskName && !globalConfig.windows?.command && !globalConfig.osx?.command && !globalConfig.linux?.command) {
        configElement.command = task.command.name;
      } else if (suppressTaskName) {
        configElement.command = task._source.config.element.command;
      }
      if (task.command.args && (!Array.isArray(task.command.args) || task.command.args.length > 0)) {
        if (!globalConfig.windows?.args && !globalConfig.osx?.args && !globalConfig.linux?.args) {
          configElement.args = task.command.args;
        } else {
          configElement.args = task._source.config.element.args;
        }
      }
    }
    if (task.configurationProperties.presentation) {
      configElement.presentation = task.configurationProperties.presentation;
    }
    if (task.configurationProperties.isBackground) {
      configElement.isBackground = task.configurationProperties.isBackground;
    }
    if (task.configurationProperties.problemMatchers) {
      configElement.problemMatcher = task._source.config.element.problemMatcher;
    }
    if (task.configurationProperties.group) {
      configElement.group = task.configurationProperties.group;
    }
    task._source.config.element = configElement;
    const tempTask = new $gQ(task._id, task._source, task._label, task.type, task.command, task.hasDefinedMatchers, task.runOptions, task.configurationProperties);
    const configTask = this.Ac(tempTask);
    if (configTask) {
      return configTask;
    }
    return;
  }
  async Od() {
    if (this.Qb === 2) {
      return;
    }
    if (!this.Fb.isWorkspaceTrusted()) {
      this.B(Event2.once(this.Fb.onDidChangeTrust)((isTrusted) => {
        if (isTrusted) {
          this.Od();
        }
      }));
      return;
    }
    const tasks2 = await this.Oc();
    const fileDiffs = [];
    for (const folder of this.Nb) {
      const diff3 = await this.Md(folder);
      if (diff3) {
        fileDiffs.push(diff3);
      }
      if (!diff3) {
        continue;
      }
      const configTasks = [];
      const suppressTaskName = !!this.bb.getValue("tasks.suppressTaskName", { resource: folder.uri });
      const globalConfig = {
        windows: this.bb.getValue("tasks.windows", { resource: folder.uri }),
        osx: this.bb.getValue("tasks.osx", { resource: folder.uri }),
        linux: this.bb.getValue("tasks.linux", { resource: folder.uri })
      };
      tasks2.get(folder).forEach((task) => {
        const configTask = this.Nd(task, suppressTaskName, globalConfig);
        if (configTask) {
          configTasks.push(configTask);
        }
      });
      this.I = void 0;
      this.G = void 0;
      await this.Bc(folder, "tasks.tasks", configTasks);
      await this.Bc(folder, "tasks.version", "2.0.0");
      if (this.bb.getValue("tasks.showOutput", { resource: folder.uri })) {
        await this.bb.updateValue("tasks.showOutput", void 0, { resource: folder.uri });
      }
      if (this.bb.getValue("tasks.isShellCommand", { resource: folder.uri })) {
        await this.bb.updateValue("tasks.isShellCommand", void 0, { resource: folder.uri });
      }
      if (this.bb.getValue("tasks.suppressTaskName", { resource: folder.uri })) {
        await this.bb.updateValue("tasks.suppressTaskName", void 0, { resource: folder.uri });
      }
    }
    this.Ub();
    this.wb.prompt(severity_default.Warning, fileDiffs.length === 1 ? localize(10033, null) : localize(10034, null), [{
      label: fileDiffs.length === 1 ? localize(10035, null) : localize(10036, null),
      run: async () => {
        for (const upgrade of fileDiffs) {
          await this.hb.openEditor({
            original: { resource: upgrade[0] },
            modified: { resource: upgrade[1] }
          });
        }
      }
    }]);
  }
};
$Jhc = $Jhc_1 = __decorate([
  __param(0, $kl),
  __param(1, $DE),
  __param(2, $RS),
  __param(3, $uqb),
  __param(4, $uob),
  __param(5, $sn),
  __param(6, $mJ),
  __param(7, $km),
  __param(8, $Zk),
  __param(9, $zv),
  __param(10, $cK),
  __param(11, $sG),
  __param(12, $wN),
  __param(13, $1M),
  __param(14, $nY),
  __param(15, $4Pb),
  __param(16, $7Pb),
  __param(17, $jv),
  __param(18, $TJ),
  __param(19, $O4),
  __param(20, $Yv),
  __param(21, $PJ),
  __param(22, $on),
  __param(23, $US),
  __param(24, $fY),
  __param(25, $aT),
  __param(26, $oG),
  __param(27, $TK),
  __param(28, $$M),
  __param(29, $5M),
  __param(30, $4M),
  __param(31, $wn),
  __param(32, $gs),
  __param(33, $KL),
  __param(34, $RL),
  __param(35, $Pk)
], $Jhc);

// out-build/vs/workbench/contrib/tasks/browser/tasksQuickAccess.js
var $Khc_1;
var $Khc = class $Khc2 extends $rhb {
  static {
    $Khc_1 = this;
  }
  static {
    this.PREFIX = "task ";
  }
  constructor(extensionService, a, b, h3, j, m, n, r2) {
    super($Khc_1.PREFIX, {
      noResultsPick: {
        label: localize(10106, null)
      }
    });
    this.a = a;
    this.b = b;
    this.h = h3;
    this.j = j;
    this.m = m;
    this.n = n;
    this.r = r2;
  }
  async g(filter, disposables, token) {
    if (token.isCancellationRequested) {
      return [];
    }
    const taskQuickPick = new $Ihc(this.a, this.b, this.h, this.j, this.n, this.m, this.r);
    const topLevelPicks = await taskQuickPick.getTopLevelEntries();
    const taskPicks = [];
    for (const entry of topLevelPicks.entries) {
      const highlights = $Rl(filter, entry.label);
      if (!highlights) {
        continue;
      }
      if (entry.type === "separator") {
        taskPicks.push(entry);
      }
      const task = entry.task;
      const quickAccessEntry = entry;
      quickAccessEntry.highlights = { label: highlights };
      quickAccessEntry.trigger = (index) => {
        if (index === 1 && quickAccessEntry.buttons?.length === 2) {
          const key2 = task && !$zg(task) ? task.getKey() : void 0;
          if (key2) {
            this.a.removeRecentlyUsedTask(key2);
          }
          return TriggerAction.REFRESH_PICKER;
        } else {
          if ($iQ.is(task)) {
            this.a.customize(task, void 0, true);
          } else if ($gQ.is(task)) {
            this.a.openConfig(task);
          }
          return TriggerAction.CLOSE_PICKER;
        }
      };
      quickAccessEntry.accept = async () => {
        if ($zg(task)) {
          const showResult = await taskQuickPick.show(localize(10107, null), void 0, task);
          if (showResult) {
            this.a.run(showResult, { attachProblemMatcher: true });
          }
        } else {
          this.a.run(await this.t(task), { attachProblemMatcher: true });
        }
      };
      taskPicks.push(quickAccessEntry);
    }
    return taskPicks;
  }
  async t(task) {
    if (!$hQ.is(task)) {
      return task;
    }
    return this.a.tryResolveTask(task);
  }
};
$Khc = $Khc_1 = __decorate([
  __param(0, $wN),
  __param(1, $3Sb),
  __param(2, $kl),
  __param(3, $1M),
  __param(4, $PJ),
  __param(5, $Yv),
  __param(6, $gs),
  __param(7, $jv)
], $Khc);

// out-build/vs/workbench/contrib/tasks/browser/task.contribution.js
var workbenchRegistry4 = $Wn.as(Extensions2.Workbench);
workbenchRegistry4.registerWorkbenchContribution(
  $mhc,
  4
  /* LifecyclePhase.Eventually */
);
$hJ($nhc);
$dJ.appendMenuItem($bJ.CommandPalette, {
  command: {
    id: $nhc.ID,
    title: $nhc.LABEL,
    category: $dQ
  },
  when: $2Sb
});
var $Lhc = class $Lhc2 extends $3c {
  constructor(c, f, g) {
    super();
    this.c = c;
    this.f = f;
    this.g = g;
    this.b = 0;
    this.h();
  }
  h() {
    let promise = void 0;
    let resolve;
    this.B(this.c.onDidStateChange((event) => {
      if (event.kind === "changed") {
        this.j();
      }
      if (!this.m(event)) {
        switch (event.kind) {
          case "active":
            this.b++;
            if (this.b === 1) {
              if (!promise) {
                ({ promise, resolve } = $Oh());
              }
            }
            break;
          case "inactive":
            if (this.b > 0) {
              this.b--;
              if (this.b === 0) {
                if (promise && resolve) {
                  resolve();
                }
              }
            }
            break;
          case "terminated":
            if (this.b !== 0) {
              this.b = 0;
              if (promise && resolve) {
                resolve();
              }
            }
            break;
        }
      }
      if (promise && event.kind === "active" && this.b === 1) {
        this.g.withProgress({ location: 10, command: "workbench.action.tasks.showTasks" }, (progress) => {
          progress.report({ message: localize(10041, null) });
          return promise;
        }).then(() => {
          promise = void 0;
        });
      }
    }));
  }
  async j() {
    const tasks2 = await this.c.getActiveTasks();
    if (tasks2.length === 0) {
      if (this.a) {
        this.a.dispose();
        this.a = void 0;
      }
    } else {
      const itemProps = {
        name: localize(10042, null),
        text: `$(tools) ${tasks2.length}`,
        ariaLabel: localize(10043, null, tasks2.length),
        tooltip: localize(10044, null),
        command: "workbench.action.tasks.showTasks"
      };
      if (!this.a) {
        this.a = this.f.addEntry(
          itemProps,
          "status.runningTasks",
          0,
          49
          /* Medium Priority, next to Markers */
        );
      } else {
        this.a.update(itemProps);
      }
    }
  }
  m(event) {
    if (!this.c.inTerminal() || event.kind === "changed") {
      return false;
    }
    if (($zg(event.group) ? event.group : event.group?._id) !== TaskGroup.Build._id) {
      return true;
    }
    return event.__task.configurationProperties.problemMatchers === void 0 || event.__task.configurationProperties.problemMatchers.length === 0;
  }
};
$Lhc = __decorate([
  __param(0, $3Sb),
  __param(1, $$qb),
  __param(2, $TJ)
], $Lhc);
workbenchRegistry4.registerWorkbenchContribution(
  $Lhc,
  3
  /* LifecyclePhase.Restored */
);
$dJ.appendMenuItem($bJ.MenubarTerminalMenu, {
  group: "3_run",
  command: {
    id: "workbench.action.tasks.runTask",
    title: localize(10045, null)
  },
  order: 1,
  when: $2Sb
});
$dJ.appendMenuItem($bJ.MenubarTerminalMenu, {
  group: "3_run",
  command: {
    id: "workbench.action.tasks.build",
    title: localize(10046, null)
  },
  order: 2,
  when: $2Sb
});
$dJ.appendMenuItem($bJ.MenubarTerminalMenu, {
  group: "5_manage",
  command: {
    precondition: $cQ,
    id: "workbench.action.tasks.showTasks",
    title: localize(10047, null)
  },
  order: 1,
  when: $2Sb
});
$dJ.appendMenuItem($bJ.MenubarTerminalMenu, {
  group: "5_manage",
  command: {
    precondition: $cQ,
    id: "workbench.action.tasks.restartTask",
    title: localize(10048, null)
  },
  order: 2,
  when: $2Sb
});
$dJ.appendMenuItem($bJ.MenubarTerminalMenu, {
  group: "5_manage",
  command: {
    precondition: $cQ,
    id: "workbench.action.tasks.terminate",
    title: localize(10049, null)
  },
  order: 3,
  when: $2Sb
});
$dJ.appendMenuItem($bJ.MenubarTerminalMenu, {
  group: "7_configure",
  command: {
    id: "workbench.action.tasks.configureTaskRunner",
    title: localize(10050, null)
  },
  order: 1,
  when: $2Sb
});
$dJ.appendMenuItem($bJ.MenubarTerminalMenu, {
  group: "7_configure",
  command: {
    id: "workbench.action.tasks.configureDefaultBuildTask",
    title: localize(10051, null)
  },
  order: 2,
  when: $2Sb
});
$dJ.appendMenuItem($bJ.CommandPalette, {
  command: {
    id: "workbench.action.tasks.openWorkspaceFileTasks",
    title: localize2(10076, "Open Workspace Tasks"),
    category: $dQ
  },
  when: $7m.and($epb.isEqualTo("workspace"), $2Sb)
});
$dJ.appendMenuItem($bJ.CommandPalette, {
  command: {
    id: ConfigureTaskAction.ID,
    title: ConfigureTaskAction.TEXT,
    category: $dQ
  },
  when: $2Sb
});
$dJ.appendMenuItem($bJ.CommandPalette, {
  command: {
    id: "workbench.action.tasks.showLog",
    title: localize2(10077, "Show Task Log"),
    category: $dQ
  },
  when: $2Sb
});
$dJ.appendMenuItem($bJ.CommandPalette, {
  command: {
    id: "workbench.action.tasks.runTask",
    title: localize2(10078, "Run Task"),
    category: $dQ
  }
});
$dJ.appendMenuItem($bJ.CommandPalette, {
  command: {
    id: "workbench.action.tasks.reRunTask",
    title: localize2(10079, "Rerun Last Task"),
    category: $dQ
  },
  when: $2Sb
});
$dJ.appendMenuItem($bJ.CommandPalette, {
  command: {
    id: "workbench.action.tasks.restartTask",
    title: localize2(10080, "Restart Running Task"),
    category: $dQ
  },
  when: $2Sb
});
$dJ.appendMenuItem($bJ.CommandPalette, {
  command: {
    id: "workbench.action.tasks.showTasks",
    title: localize2(10081, "Show Running Tasks"),
    category: $dQ
  },
  when: $2Sb
});
$dJ.appendMenuItem($bJ.CommandPalette, {
  command: {
    id: "workbench.action.tasks.terminate",
    title: localize2(10082, "Terminate Task"),
    category: $dQ
  },
  when: $2Sb
});
$dJ.appendMenuItem($bJ.CommandPalette, {
  command: {
    id: "workbench.action.tasks.build",
    title: localize2(10083, "Run Build Task"),
    category: $dQ
  },
  when: $2Sb
});
$dJ.appendMenuItem($bJ.CommandPalette, {
  command: {
    id: "workbench.action.tasks.test",
    title: localize2(10084, "Run Test Task"),
    category: $dQ
  },
  when: $2Sb
});
$dJ.appendMenuItem($bJ.CommandPalette, {
  command: {
    id: "workbench.action.tasks.configureDefaultBuildTask",
    title: localize2(10085, "Configure Default Build Task"),
    category: $dQ
  },
  when: $2Sb
});
$dJ.appendMenuItem($bJ.CommandPalette, {
  command: {
    id: "workbench.action.tasks.configureDefaultTestTask",
    title: localize2(10086, "Configure Default Test Task"),
    category: $dQ
  },
  when: $2Sb
});
$dJ.appendMenuItem($bJ.CommandPalette, {
  command: {
    id: "workbench.action.tasks.openUserTasks",
    title: localize2(10087, "Open User Tasks"),
    category: $dQ
  },
  when: $2Sb
});
var UserTasksGlobalActionContribution = class extends $3c {
  constructor() {
    super();
    this.a();
  }
  a() {
    const id2 = "workbench.action.tasks.openUserTasks";
    const title = localize(10052, null);
    this.B($dJ.appendMenuItem($bJ.GlobalActivity, {
      command: {
        id: id2,
        title
      },
      when: $2Sb,
      group: "2_configuration",
      order: 6
    }));
    this.B($dJ.appendMenuItem($bJ.MenubarPreferencesMenu, {
      command: {
        id: id2,
        title
      },
      when: $2Sb,
      group: "2_configuration",
      order: 6
    }));
  }
};
workbenchRegistry4.registerWorkbenchContribution(
  UserTasksGlobalActionContribution,
  3
  /* LifecyclePhase.Restored */
);
$0I.registerKeybindingRule({
  id: "workbench.action.tasks.build",
  weight: 200,
  when: $YSb,
  primary: 2048 | 1024 | 32
  /* KeyCode.KeyB */
});
var outputChannelRegistry = $Wn.as($SS.OutputChannels);
outputChannelRegistry.registerChannel({ id: $Jhc.OutputChannelId, label: $Jhc.OutputChannelLabel, log: false });
var quickAccessRegistry5 = $Wn.as($CM.Quickaccess);
var tasksPickerContextKey = "inTasksPicker";
quickAccessRegistry5.registerQuickAccessProvider({
  ctor: $Khc,
  prefix: $Khc.PREFIX,
  contextKey: tasksPickerContextKey,
  placeholder: localize(10053, null),
  helpEntries: [{ description: localize(10054, null), commandCenterOrder: 60 }]
});
var schema8 = {
  id: $sK,
  description: "Task definition file",
  type: "object",
  allowTrailingCommas: true,
  allowComments: true,
  default: {
    version: "2.0.0",
    tasks: [
      {
        label: "My Task",
        command: "echo hello",
        type: "shell",
        args: [],
        problemMatcher: ["$tsc"],
        presentation: {
          reveal: "always"
        },
        group: "build"
      }
    ]
  }
};
schema8.definitions = {
  ...jsonSchema_v1_default.definitions,
  ...jsonSchema_v2_default.definitions
};
schema8.oneOf = [...jsonSchema_v2_default.oneOf || [], ...jsonSchema_v1_default.oneOf || []];
var jsonRegistry5 = $Wn.as($Xn.JSONContribution);
jsonRegistry5.registerSchema($sK, schema8);
var $Mhc = class extends $3c {
  static {
    this.ID = "taskRegistryContribution";
  }
  constructor() {
    super();
    this.B($_P.onMatcherChanged(() => {
      $phc();
      jsonRegistry5.notifySchemaChanged($sK);
    }));
    this.B($aQ.onDefinitionsChanged(() => {
      $ohc();
      jsonRegistry5.notifySchemaChanged($sK);
    }));
  }
};
$PL(
  $Mhc.ID,
  $Mhc,
  3
  /* WorkbenchPhase.AfterRestored */
);
var configurationRegistry14 = $Wn.as($Ht.Configuration);
configurationRegistry14.registerConfiguration({
  id: "task",
  order: 100,
  title: localize(10055, null),
  type: "object",
  properties: {
    [
      "task.problemMatchers.neverPrompt"
      /* TaskSettingId.ProblemMatchersNeverPrompt */
    ]: {
      markdownDescription: localize(10056, null),
      "oneOf": [
        {
          type: "boolean",
          markdownDescription: localize(10057, null)
        },
        {
          type: "object",
          patternProperties: {
            ".*": {
              type: "boolean"
            }
          },
          markdownDescription: localize(10058, null),
          default: {
            "shell": true
          }
        }
      ],
      default: false
    },
    [
      "task.autoDetect"
      /* TaskSettingId.AutoDetect */
    ]: {
      markdownDescription: localize(10059, null),
      type: "string",
      enum: ["on", "off"],
      default: "on"
    },
    [
      "task.slowProviderWarning"
      /* TaskSettingId.SlowProviderWarning */
    ]: {
      markdownDescription: localize(10060, null),
      "oneOf": [
        {
          type: "boolean",
          markdownDescription: localize(10061, null)
        },
        {
          type: "array",
          items: {
            type: "string",
            markdownDescription: localize(10062, null)
          }
        }
      ],
      default: true
    },
    [
      "task.quickOpen.history"
      /* TaskSettingId.QuickOpenHistory */
    ]: {
      markdownDescription: localize(10063, null),
      type: "number",
      default: 30,
      minimum: 0,
      maximum: 30
    },
    [
      "task.quickOpen.detail"
      /* TaskSettingId.QuickOpenDetail */
    ]: {
      markdownDescription: localize(10064, null),
      type: "boolean",
      default: true
    },
    [
      "task.quickOpen.skip"
      /* TaskSettingId.QuickOpenSkip */
    ]: {
      type: "boolean",
      description: localize(10065, null),
      default: false
    },
    [
      "task.quickOpen.showAll"
      /* TaskSettingId.QuickOpenShowAll */
    ]: {
      type: "boolean",
      description: localize(10066, null),
      default: false
    },
    [
      "task.allowAutomaticTasks"
      /* TaskSettingId.AllowAutomaticTasks */
    ]: {
      type: "string",
      enum: ["on", "off"],
      enumDescriptions: [
        localize(10067, null),
        localize(10068, null)
      ],
      description: localize(10069, null),
      default: "on",
      restricted: true
    },
    [
      "task.reconnection"
      /* TaskSettingId.Reconnection */
    ]: {
      type: "boolean",
      description: localize(10070, null),
      default: true
    },
    [
      "task.saveBeforeRun"
      /* TaskSettingId.SaveBeforeRun */
    ]: {
      markdownDescription: localize(10071, null),
      type: "string",
      enum: ["always", "never", "prompt"],
      enumDescriptions: [
        localize(10072, null),
        localize(10073, null),
        localize(10074, null)
      ],
      default: "always"
    },
    [
      "task.verboseLogging"
      /* TaskSettingId.VerboseLogging */
    ]: {
      type: "boolean",
      description: localize(10075, null),
      default: false
    }
  }
});

// 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 $ad();
  setTimeout(() => source.cancel(), millis);
  return source.token;
}
function combineTimeoutCancellation(a, b) {
  if (a.isCancellationRequested || b.isCancellationRequested) {
    return CancellationToken.Cancelled;
  }
  const source = new $ad();
  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 $2c();
    ({ promise: this.promise, resolve: this.f, reject: this.g } = $Oh());
    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, path, query, debugConnectionType, debugLabel, timeoutCancellationToken) {
  const result = new PromiseWithTimeout(timeoutCancellationToken);
  const sw = $te.create(false);
  logService.info(`Creating a socket (${debugLabel})...`);
  $S(`code/willCreateSocket/${debugConnectionType}`);
  remoteSocketFactoryService.connect(connectTo, path, query, debugLabel).then((socket) => {
    if (result.didTimeout) {
      $S(`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 {
      $S(`code/didCreateSocketOK/${debugConnectionType}`);
      logService.info(`Creating a socket (${debugLabel}) was successful after ${sw.elapsed()} ms.`);
      result.resolve(socket);
    }
  }, (err) => {
    $S(`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(options3, connectionType, args2, timeoutCancellationToken) {
  const logPrefix = connectLogPrefix(options3, connectionType);
  options3.logService.trace(`${logPrefix} 1/6. invoking socketFactory.connect().`);
  let socket;
  try {
    socket = await createSocket(options3.logService, options3.remoteSocketFactoryService, options3.connectTo, $bh.getServerRootPath(), `reconnectionToken=${options3.reconnectionToken}&reconnection=${options3.reconnectionProtocol ? "true" : "false"}`, connectionTypeToString(connectionType), `renderer-${connectionTypeToString(connectionType)}-${options3.reconnectionToken}`, timeoutCancellationToken);
  } catch (error) {
    options3.logService.error(`${logPrefix} socketFactory.connect() failed or timed out. Error:`);
    options3.logService.error(error);
    throw error;
  }
  options3.logService.trace(`${logPrefix} 2/6. socketFactory.connect() was successful.`);
  let protocol;
  let ownsProtocol;
  if (options3.reconnectionProtocol) {
    options3.reconnectionProtocol.beginAcceptReconnection(socket, null);
    protocol = options3.reconnectionProtocol;
    ownsProtocol = false;
  } else {
    protocol = new $tu({ socket });
    ownsProtocol = true;
  }
  options3.logService.trace(`${logPrefix} 3/6. sending AuthRequest control message.`);
  const message = await raceWithTimeoutCancellation(options3.signService.createNewMessage($ps()), timeoutCancellationToken);
  const authRequest = {
    type: "auth",
    auth: options3.connectionToken || "00000000000000000000",
    data: message.data
  };
  protocol.sendControl($Ci.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;
    }
    options3.logService.trace(`${logPrefix} 4/6. received SignRequest control message.`);
    const isValid2 = await raceWithTimeoutCancellation(options3.signService.validate(message, msg.signedData), timeoutCancellationToken);
    if (!isValid2) {
      const error = new Error("Refused to connect to unsupported server");
      error.code = "VSCODE_CONNECTION_ERROR";
      throw error;
    }
    const signed = await raceWithTimeoutCancellation(options3.signService.sign(msg.data), timeoutCancellationToken);
    const connTypeRequest = {
      type: "connectionType",
      commit: options3.commit,
      signedData: signed,
      desiredConnectionType: connectionType
    };
    if (args2) {
      connTypeRequest.args = args2;
    }
    options3.logService.trace(`${logPrefix} 5/6. sending ConnectionTypeRequest control message.`);
    protocol.sendControl($Ci.fromString(JSON.stringify(connTypeRequest)));
    return { protocol, ownsProtocol };
  } catch (error) {
    if (error && error.code === "ETIMEDOUT") {
      options3.logService.error(`${logPrefix} the handshake timed out. Error:`);
      options3.logService.error(error);
    }
    if (error && error.code === "VSCODE_CONNECTION_ERROR") {
      options3.logService.error(`${logPrefix} received error control message when negotiating connection. Error:`);
      options3.logService.error(error);
    }
    if (ownsProtocol) {
      safeDisposeProtocolAndSocket(protocol);
    }
    throw error;
  }
}
async function connectToRemoteExtensionHostAgentAndReadOneMessage(options3, connectionType, args2, timeoutCancellationToken) {
  const startTime = Date.now();
  const logPrefix = connectLogPrefix(options3, connectionType);
  const { protocol, ownsProtocol } = await connectToRemoteExtensionHostAgent(options3, connectionType, args2, timeoutCancellationToken);
  const result = new PromiseWithTimeout(timeoutCancellationToken);
  result.registerDisposable(protocol.onControlMessage((raw) => {
    const msg = JSON.parse(raw.toString());
    const error = getErrorFromMessage(msg);
    if (error) {
      options3.logService.error(`${logPrefix} received error control message when negotiating connection. Error:`);
      options3.logService.error(error);
      if (ownsProtocol) {
        safeDisposeProtocolAndSocket(protocol);
      }
      result.reject(error);
    } else {
      options3.reconnectionProtocol?.endAcceptReconnection();
      options3.logService.trace(`${logPrefix} 6/6. handshake finished, connection is up and running after ${logElapsed(startTime)}!`);
      result.resolve({ protocol, firstMessage: msg });
    }
  }));
  return result.promise;
}
async function doConnectRemoteAgentManagement(options3, timeoutCancellationToken) {
  const { protocol } = await connectToRemoteExtensionHostAgentAndReadOneMessage(options3, 1, void 0, timeoutCancellationToken);
  return { protocol };
}
async function doConnectRemoteAgentExtensionHost(options3, startArguments, timeoutCancellationToken) {
  const { protocol, firstMessage } = await connectToRemoteExtensionHostAgentAndReadOneMessage(options3, 2, startArguments, timeoutCancellationToken);
  const debugPort = firstMessage && firstMessage.debugPort;
  return { protocol, debugPort };
}
async function resolveConnectionOptions(options3, reconnectionToken, reconnectionProtocol) {
  const { connectTo, connectionToken } = await options3.addressProvider.getAddress();
  return {
    commit: options3.commit,
    quality: options3.quality,
    connectTo,
    connectionToken,
    reconnectionToken,
    reconnectionProtocol,
    remoteSocketFactoryService: options3.remoteSocketFactoryService,
    signService: options3.signService,
    logService: options3.logService
  };
}
async function $iC(options3, remoteAuthority, clientId) {
  return createInitialConnection(options3, async (simpleOptions) => {
    const { protocol } = await doConnectRemoteAgentManagement(simpleOptions, CancellationToken.None);
    return new $rC(options3, remoteAuthority, clientId, simpleOptions.reconnectionToken, protocol);
  });
}
async function $jC(options3, startArguments) {
  return createInitialConnection(options3, async (simpleOptions) => {
    const { protocol, debugPort } = await doConnectRemoteAgentExtensionHost(simpleOptions, startArguments, CancellationToken.None);
    return new $sC(options3, startArguments, simpleOptions.reconnectionToken, protocol, debugPort);
  });
}
async function createInitialConnection(options3, connectionFactory) {
  const MAX_ATTEMPTS = 5;
  for (let attempt = 1; ; attempt++) {
    try {
      const reconnectionToken = $ps();
      const simpleOptions = await resolveConnectionOptions(options3, reconnectionToken, null);
      const result = await connectionFactory(simpleOptions);
      return result;
    } catch (err) {
      if (attempt < MAX_ATTEMPTS) {
        options3.logService.error(`[remote-connection][attempt ${attempt}] An error occurred in initial connection! Will retry... Error:`);
        options3.logService.error(err);
      } else {
        options3.logService.error(`[remote-connection][attempt ${attempt}]  An error occurred in initial connection! It will be treated as a permanent error. Error:`);
        options3.logService.error(err);
        $qC.triggerPermanentFailure(0, 0, $eC.isHandled(err));
        throw err;
      }
    }
  }
}
function sleep(seconds) {
  return $Hh((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 $lC = class {
  constructor(reconnectionToken, millisSinceLastIncomingData) {
    this.reconnectionToken = reconnectionToken;
    this.millisSinceLastIncomingData = millisSinceLastIncomingData;
    this.type = 0;
  }
};
var $mC = 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 $nC = class {
  constructor(reconnectionToken, millisSinceLastIncomingData, attempt) {
    this.reconnectionToken = reconnectionToken;
    this.millisSinceLastIncomingData = millisSinceLastIncomingData;
    this.attempt = attempt;
    this.type = 2;
  }
};
var $oC = class {
  constructor(reconnectionToken, millisSinceLastIncomingData, attempt) {
    this.reconnectionToken = reconnectionToken;
    this.millisSinceLastIncomingData = millisSinceLastIncomingData;
    this.attempt = attempt;
    this.type = 4;
  }
};
var $pC = class {
  constructor(reconnectionToken, millisSinceLastIncomingData, attempt, handled) {
    this.reconnectionToken = reconnectionToken;
    this.millisSinceLastIncomingData = millisSinceLastIncomingData;
    this.attempt = attempt;
    this.handled = handled;
    this.type = 3;
  }
};
var $qC = class _$qC extends $3c {
  static triggerPermanentFailure(millisSinceLastIncomingData, attempt, handled) {
    this._permanentFailure = true;
    this.f = millisSinceLastIncomingData;
    this.g = attempt;
    this.h = handled;
    this.j.forEach((instance2) => instance2.D(this.f, this.g, this.h));
  }
  static debugTriggerReconnection() {
    this.j.forEach((instance2) => instance2.y());
  }
  static debugPauseSocketWriting() {
    this.j.forEach((instance2) => instance2.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 || _$qC._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 $ze());
    this.onDidStateChange = this.m.event;
    this.c = false;
    this.r = false;
    this.s = false;
    this.m.fire(new $oC(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();
    }));
    _$qC.j.push(this);
    this.B($1c(() => {
      const myIndex = _$qC.j.indexOf(this);
      if (myIndex >= 0) {
        _$qC.j.splice(myIndex, 1);
      }
    }));
    if (this.n) {
      this.D(_$qC.f, _$qC.g, _$qC.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 $lC(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 $mC(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 $nC(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 $oC(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 ($eC.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 ($kb(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 $eC) {
          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, $eC.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) {
      _$qC.triggerPermanentFailure(millisSinceLastIncomingData, attempt, handled);
    } else {
      this.D(millisSinceLastIncomingData, attempt, handled);
    }
  }
  D(millisSinceLastIncomingData, attempt, handled) {
    this.m.fire(new $pC(this.reconnectionToken, millisSinceLastIncomingData, attempt, handled));
    safeDisposeProtocolAndSocket(this.protocol);
  }
  F() {
    this.protocol.pauseSocketWriting();
  }
};
var $rC = class extends $qC {
  constructor(options3, remoteAuthority, clientId, reconnectionToken, protocol) {
    super(
      1,
      options3,
      reconnectionToken,
      protocol,
      /*reconnectionFailureIsFatal*/
      true
    );
    this.client = this.B(new $ru(protocol, {
      remoteAuthority,
      clientId
    }, options3.ipcLogger));
  }
  async G(options3, timeoutCancellationToken) {
    await doConnectRemoteAgentManagement(options3, timeoutCancellationToken);
  }
};
var $sC = class extends $qC {
  constructor(options3, startArguments, reconnectionToken, protocol, debugPort) {
    super(
      2,
      options3,
      reconnectionToken,
      protocol,
      /*reconnectionFailureIsFatal*/
      false
    );
    this.H = startArguments;
    this.debugPort = debugPort;
  }
  async G(options3, timeoutCancellationToken) {
    await doConnectRemoteAgentExtensionHost(options3, this.H, timeoutCancellationToken);
  }
};
function safeDisposeProtocolAndSocket(protocol) {
  try {
    protocol.acceptDisconnect();
    const socket = protocol.getSocket();
    protocol.dispose();
    socket.dispose();
  } catch (err) {
    $gb(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(options3, connectionType) {
  return `${commonLogPrefix(connectionType, options3.reconnectionToken, !!options3.reconnectionProtocol)}[${options3.connectTo}]`;
}
function logElapsed(startTime) {
  return `${Date.now() - startTime} ms`;
}

// out-build/vs/platform/download/common/downloadIpc.js
var $7W = class {
  constructor(a) {
    this.a = a;
  }
  listen(_, event, arg) {
    throw new Error("Invalid listen");
  }
  call(context, command4, args2) {
    switch (command4) {
      case "download":
        return this.a.download(URI.revive(args2[0]), URI.revive(args2[1]));
    }
    throw new Error("Invalid call");
  }
};

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

// out-build/vs/workbench/contrib/remote/common/remote.contribution.js
var $Nhc = class $Nhc2 {
  static {
    this.ID = "workbench.contrib.remoteLabel";
  }
  constructor(a, b) {
    this.a = a;
    this.b = b;
    this.c();
  }
  c() {
    this.b.getEnvironment().then((remoteEnvironment) => {
      const os = remoteEnvironment?.os || OS;
      const formatting = {
        label: "${path}",
        separator: os === 1 ? "\\" : "/",
        tildify: os !== 1,
        normalizeDriveLetter: os === 1,
        workspaceSuffix: $r ? void 0 : Schemas.vscodeRemote
      };
      this.a.registerFormatter({
        scheme: Schemas.vscodeRemote,
        formatting
      });
      if (remoteEnvironment) {
        this.a.registerFormatter({
          scheme: Schemas.vscodeUserData,
          formatting
        });
      }
    });
  }
};
$Nhc = __decorate([
  __param(0, $ZI),
  __param(1, $RL)
], $Nhc);
var RemoteChannelsContribution = class RemoteChannelsContribution2 extends $3c {
  constructor(remoteAgentService, downloadService, loggerService) {
    super();
    const connection = remoteAgentService.getConnection();
    if (connection) {
      connection.registerChannel("download", new $7W(downloadService));
      connection.withChannel("logger", async (channel) => this.B(new $rB(loggerService, channel)));
    }
  }
};
RemoteChannelsContribution = __decorate([
  __param(0, $RL),
  __param(1, $6W),
  __param(2, $xn)
], RemoteChannelsContribution);
var RemoteInvalidWorkspaceDetector = class RemoteInvalidWorkspaceDetector2 extends $3c {
  static {
    this.ID = "workbench.contrib.remoteInvalidWorkspaceDetector";
  }
  constructor(a, b, c, f, g, remoteAgentService) {
    super();
    this.a = a;
    this.b = b;
    this.c = c;
    this.f = f;
    this.g = g;
    if (this.c.remoteAuthority) {
      remoteAgentService.getEnvironment().then((remoteEnv) => {
        if (remoteEnv) {
          this.h();
        }
      });
    }
  }
  async h() {
    const workspace2 = this.f.getWorkspace();
    const workspaceUriToStat = workspace2.configuration ?? workspace2.folders.at(0)?.uri;
    if (!workspaceUriToStat) {
      return;
    }
    const exists = await this.a.exists(workspaceUriToStat);
    if (exists) {
      return;
    }
    const res = await this.b.confirm({
      type: "warning",
      message: localize(9256, null),
      detail: localize(9257, null),
      primaryButton: localize(9258, null)
    });
    if (res.confirmed) {
      if (workspace2.configuration) {
        return this.g.pickWorkspaceAndOpen({});
      }
      return this.g.pickFolderAndOpen({});
    }
  }
};
RemoteInvalidWorkspaceDetector = __decorate([
  __param(0, $km),
  __param(1, $Yv),
  __param(2, $US),
  __param(3, $Zk),
  __param(4, $1v),
  __param(5, $RL)
], RemoteInvalidWorkspaceDetector);
var workbenchContributionsRegistry6 = $Wn.as(Extensions2.Workbench);
$PL(
  $Nhc.ID,
  $Nhc,
  1
  /* WorkbenchPhase.BlockStartup */
);
workbenchContributionsRegistry6.registerWorkbenchContribution(
  RemoteChannelsContribution,
  3
  /* LifecyclePhase.Restored */
);
$PL(
  RemoteInvalidWorkspaceDetector.ID,
  RemoteInvalidWorkspaceDetector,
  1
  /* WorkbenchPhase.BlockStartup */
);
var enableDiagnostics = true;
if (enableDiagnostics) {
  class TriggerReconnectAction extends $gJ {
    constructor() {
      super({
        id: "workbench.action.triggerReconnect",
        title: localize2(9300, "Connection: Trigger Reconnect"),
        category: $qn.Developer,
        f1: true
      });
    }
    async run(accessor) {
      $qC.debugTriggerReconnection();
    }
  }
  class PauseSocketWriting extends $gJ {
    constructor() {
      super({
        id: "workbench.action.pauseSocketWriting",
        title: localize2(9301, "Connection: Pause socket writing"),
        category: $qn.Developer,
        f1: true
      });
    }
    async run(accessor) {
      $qC.debugPauseSocketWriting();
    }
  }
  $hJ(TriggerReconnectAction);
  $hJ(PauseSocketWriting);
}
var extensionKindSchema2 = {
  type: "string",
  enum: [
    "ui",
    "workspace"
  ],
  enumDescriptions: [
    localize(9259, null),
    localize(9260, null)
  ]
};
$Wn.as($Ht.Configuration).registerConfiguration({
  id: "remote",
  title: localize(9261, null),
  type: "object",
  properties: {
    "remote.extensionKind": {
      type: "object",
      markdownDescription: localize(9262, null),
      patternProperties: {
        "([a-z0-9A-Z][a-z0-9-A-Z]*)\\.([a-z0-9A-Z][a-z0-9-A-Z]*)$": {
          oneOf: [{ type: "array", items: extensionKindSchema2 }, extensionKindSchema2],
          default: ["ui"]
        }
      },
      default: {
        "pub.name": ["ui"]
      }
    },
    "remote.restoreForwardedPorts": {
      type: "boolean",
      markdownDescription: localize(9263, null),
      default: true
    },
    "remote.autoForwardPorts": {
      type: "boolean",
      markdownDescription: localize(9264, null, "`#remote.autoForwardPortsSource#`"),
      default: true
    },
    "remote.autoForwardPortsSource": {
      type: "string",
      markdownDescription: localize(9265, null, "`#remote.autoForwardPorts#`", "`#remote.autoForwardPortsSource#`"),
      enum: ["process", "output", "hybrid"],
      enumDescriptions: [
        localize(9266, null),
        localize(9267, null),
        localize(9268, null)
      ],
      default: "process"
    },
    "remote.autoForwardPortsFallback": {
      type: "number",
      default: 20,
      markdownDescription: localize(9269, null)
    },
    "remote.forwardOnOpen": {
      type: "boolean",
      description: localize(9270, null),
      default: true
    },
    // Consider making changes to extensions\configuration-editing\schemas\devContainer.schema.src.json
    // and extensions\configuration-editing\schemas\attachContainer.schema.json
    // to keep in sync with devcontainer.json schema.
    "remote.portsAttributes": {
      type: "object",
      patternProperties: {
        "(^\\d+(-\\d+)?$)|(.+)": {
          type: "object",
          description: localize(9271, null),
          properties: {
            "onAutoForward": {
              type: "string",
              enum: ["notify", "openBrowser", "openBrowserOnce", "openPreview", "silent", "ignore"],
              enumDescriptions: [
                localize(9272, null),
                localize(9273, null),
                localize(9274, null),
                localize(9275, null),
                localize(9276, null),
                localize(9277, null)
              ],
              description: localize(9278, null),
              default: "notify"
            },
            "elevateIfNeeded": {
              type: "boolean",
              description: localize(9279, null),
              default: false
            },
            "label": {
              type: "string",
              description: localize(9280, null),
              default: localize(9281, null)
            },
            "requireLocalPort": {
              type: "boolean",
              markdownDescription: localize(9282, null),
              default: false
            },
            "protocol": {
              type: "string",
              enum: ["http", "https"],
              description: localize(9283, null)
            }
          },
          default: {
            "label": localize(9284, null),
            "onAutoForward": "notify"
          }
        }
      },
      markdownDescription: localize(9285, null),
      defaultSnippets: [{ body: { "${1:3000}": { label: "${2:Application}", onAutoForward: "openPreview" } } }],
      errorMessage: localize(9286, null),
      additionalProperties: false,
      default: {
        "443": {
          "protocol": "https"
        },
        "8443": {
          "protocol": "https"
        }
      }
    },
    "remote.otherPortsAttributes": {
      type: "object",
      properties: {
        "onAutoForward": {
          type: "string",
          enum: ["notify", "openBrowser", "openPreview", "silent", "ignore"],
          enumDescriptions: [
            localize(9287, null),
            localize(9288, null),
            localize(9289, null),
            localize(9290, null),
            localize(9291, null)
          ],
          description: localize(9292, null),
          default: "notify"
        },
        "elevateIfNeeded": {
          type: "boolean",
          description: localize(9293, null),
          default: false
        },
        "label": {
          type: "string",
          description: localize(9294, null),
          default: localize(9295, null)
        },
        "requireLocalPort": {
          type: "boolean",
          markdownDescription: localize(9296, null),
          default: false
        },
        "protocol": {
          type: "string",
          enum: ["http", "https"],
          description: localize(9297, null)
        }
      },
      defaultSnippets: [{ body: { onAutoForward: "ignore" } }],
      markdownDescription: localize(9298, null, "`#remote.portsAttributes#`"),
      additionalProperties: false
    },
    "remote.localPortHost": {
      type: "string",
      enum: ["localhost", "allInterfaces"],
      default: "localhost",
      description: localize(9299, null)
    }
  }
});

// out-build/vs/workbench/contrib/remote/browser/showCandidate.js
var $Ohc = class $Ohc2 extends $3c {
  static {
    this.ID = "workbench.contrib.showPortCandidate";
  }
  constructor(remoteExplorerService, environmentService) {
    super();
    const showPortCandidate = environmentService.options?.tunnelProvider?.showPortCandidate;
    if (showPortCandidate) {
      this.B(remoteExplorerService.setCandidateFilter(async (candidates) => {
        const filters2 = await Promise.all(candidates.map((candidate) => showPortCandidate(candidate.host, candidate.port, candidate.detail ?? "")));
        const filteredCandidates = [];
        if (filters2.length !== candidates.length) {
          return candidates;
        }
        for (let i2 = 0; i2 < candidates.length; i2++) {
          if (filters2[i2]) {
            filteredCandidates.push(candidates[i2]);
          }
        }
        return filteredCandidates;
      }));
    }
  }
};
$Ohc = __decorate([
  __param(0, $8Sb),
  __param(1, $M4)
], $Ohc);

// out-build/vs/workbench/contrib/remote/browser/tunnelFactory.js
var $Phc = class $Phc2 extends $3c {
  static {
    this.ID = "workbench.contrib.tunnelFactory";
  }
  constructor(tunnelService, environmentService, a, remoteExplorerService, logService, contextKeyService) {
    super();
    this.a = a;
    const tunnelFactory = environmentService.options?.tunnelProvider?.tunnelFactory;
    if (tunnelFactory) {
      contextKeyService.createKey($WS.key, true);
      let privacyOptions = environmentService.options?.tunnelProvider?.features?.privacyOptions ?? [];
      if (environmentService.options?.tunnelProvider?.features?.public && privacyOptions.length === 0) {
        privacyOptions = [
          {
            id: "private",
            label: localize(9194, null),
            themeIcon: "lock"
          },
          {
            id: "public",
            label: localize(9195, null),
            themeIcon: "eye"
          }
        ];
      }
      this.B(tunnelService.setTunnelProvider({
        forwardPort: async (tunnelOptions, tunnelCreationOptions) => {
          let tunnelPromise;
          try {
            tunnelPromise = tunnelFactory(tunnelOptions, tunnelCreationOptions);
          } catch (e) {
            logService.trace("tunnelFactory: tunnel provider error");
          }
          if (!tunnelPromise) {
            return void 0;
          }
          let tunnel;
          try {
            tunnel = await tunnelPromise;
          } catch (e) {
            logService.trace("tunnelFactory: tunnel provider promise error");
            if (e instanceof Error) {
              return e.message;
            }
            return void 0;
          }
          const localAddress = tunnel.localAddress.startsWith("http") ? tunnel.localAddress : `http://${tunnel.localAddress}`;
          const remoteTunnel = {
            tunnelRemotePort: tunnel.remoteAddress.port,
            tunnelRemoteHost: tunnel.remoteAddress.host,
            // The tunnel factory may give us an inaccessible local address.
            // To make sure this doesn't happen, resolve the uri immediately.
            localAddress: await this.b(localAddress),
            privacy: tunnel.privacy ?? (tunnel.public ? TunnelPrivacyId.Public : TunnelPrivacyId.Private),
            protocol: tunnel.protocol ?? TunnelProtocol.Http,
            dispose: async () => {
              await tunnel.dispose();
            }
          };
          return remoteTunnel;
        }
      }));
      const tunnelInformation = environmentService.options?.tunnelProvider?.features ? {
        features: {
          elevation: !!environmentService.options?.tunnelProvider?.features?.elevation,
          public: !!environmentService.options?.tunnelProvider?.features?.public,
          privacyOptions,
          protocol: environmentService.options?.tunnelProvider?.features?.protocol === void 0 ? true : !!environmentService.options?.tunnelProvider?.features?.protocol
        }
      } : void 0;
      remoteExplorerService.setTunnelInformation(tunnelInformation);
    }
  }
  async b(uri) {
    try {
      return (await this.a.resolveExternalUri(URI.parse(uri))).resolved.toString();
    } catch {
      return uri;
    }
  }
};
$Phc = __decorate([
  __param(0, $tC),
  __param(1, $M4),
  __param(2, $O4),
  __param(3, $8Sb),
  __param(4, $wn),
  __param(5, $on)
], $Phc);

// out-build/vs/workbench/contrib/remote/browser/explorerViewItems.js
var $Qhc = new $nn("selectedRemoteInExplorer", "");
var $Rhc = class $Rhc2 extends $3c {
  constructor(f, g, h3, j, m) {
    super();
    this.f = f;
    this.g = g;
    this.h = h3;
    this.j = j;
    this.m = m;
    this.b = this.B(new $_c());
    this.c = $Qhc.bindTo(f);
    this.a = $bJ.for("workbench.remote.menu.switchRemoteMenu");
    this.B($dJ.appendMenuItem($bJ.ViewContainerTitle, {
      submenu: this.a,
      title: localize(9111, null),
      group: "navigation",
      when: $7m.equals("viewContainer", $HUb),
      order: 1,
      isSelection: true
    }));
    this.B(g.onDidChangeTargetType((e) => {
      this.n(e);
    }));
  }
  setSelectionForConnection() {
    let isSetForConnection = false;
    if (this.b.size > 0) {
      let authority;
      const remoteAuthority = this.h.remoteAuthority;
      let virtualWorkspace;
      if (!remoteAuthority) {
        virtualWorkspace = $9S(this.m.getWorkspace())?.scheme;
      }
      isSetForConnection = true;
      const explorerType = remoteAuthority ? [remoteAuthority.split("+")[0]] : virtualWorkspace ? [virtualWorkspace] : this.j.get(
        $9Sb,
        1
        /* StorageScope.WORKSPACE */
      )?.split(",") ?? this.j.get(
        $9Sb,
        0
        /* StorageScope.PROFILE */
      )?.split(",");
      if (explorerType !== void 0) {
        authority = this.r(explorerType);
      }
      if (authority) {
        this.n(authority);
      }
    }
    return isSetForConnection;
  }
  n(authority) {
    this.c.set(authority[0]);
    this.g.targetType = authority;
  }
  r(explorerType) {
    let authority;
    for (const option of this.b) {
      for (const authorityOption of option[1].authority) {
        for (const explorerOption of explorerType) {
          if (authorityOption === explorerOption) {
            authority = option[1].authority;
            break;
          } else if (option[1].virtualWorkspace === explorerOption) {
            authority = option[1].authority;
            break;
          }
        }
      }
    }
    return authority;
  }
  removeOptionItems(views) {
    for (const view of views) {
      if (view.group && view.group.startsWith("targets") && view.remoteAuthority && (!view.when || this.f.contextMatchesRules(view.when))) {
        const authority = $Ag(view.remoteAuthority) ? view.remoteAuthority : [view.remoteAuthority];
        this.b.deleteAndDispose(authority[0]);
      }
    }
  }
  createOptionItems(views) {
    const startingCount = this.b.size;
    for (const view of views) {
      if (view.group && view.group.startsWith("targets") && view.remoteAuthority && (!view.when || this.f.contextMatchesRules(view.when))) {
        const text2 = view.name;
        const authority = $Ag(view.remoteAuthority) ? view.remoteAuthority : [view.remoteAuthority];
        if (this.b.has(authority[0])) {
          continue;
        }
        const thisCapture = this;
        const action = $hJ(class extends $gJ {
          constructor() {
            super({
              id: `workbench.action.remoteExplorer.show.${authority[0]}`,
              title: text2,
              toggled: $Qhc.isEqualTo(authority[0]),
              menu: {
                id: thisCapture.a
              }
            });
          }
          async run() {
            thisCapture.n(authority);
          }
        });
        this.b.set(authority[0], { text: text2.value, authority, virtualWorkspace: view.virtualWorkspace, dispose: () => action.dispose() });
      }
    }
    if (this.b.size > startingCount) {
      this.setSelectionForConnection();
    }
  }
};
$Rhc = __decorate([
  __param(0, $on),
  __param(1, $8Sb),
  __param(2, $US),
  __param(3, $jv),
  __param(4, $Zk)
], $Rhc);

// out-build/vs/workbench/contrib/welcomeGettingStarted/common/media/theme_picker.js
var theme_picker_default = () => `
<checklist>
	<div class="theme-picker-row">
		<checkbox when-checked="setTheme:${ThemeSettingDefaults.COLOR_THEME_DARK}" checked-on="config.workbench.colorTheme == '${ThemeSettingDefaults.COLOR_THEME_DARK}'">
			<img width="200" src="./dark.png"/>
			${$zf(localize(12092, null))}
		</checkbox>
		<checkbox when-checked="setTheme:${ThemeSettingDefaults.COLOR_THEME_LIGHT}" checked-on="config.workbench.colorTheme == '${ThemeSettingDefaults.COLOR_THEME_LIGHT}'">
			<img width="200" src="./light.png"/>
			${$zf(localize(12093, null))}
		</checkbox>
	</div>
	<div class="theme-picker-row">
		<checkbox when-checked="setTheme:${ThemeSettingDefaults.COLOR_THEME_HC_DARK}" checked-on="config.workbench.colorTheme == '${ThemeSettingDefaults.COLOR_THEME_HC_DARK}'">
			<img width="200" src="./dark-hc.png"/>
			${$zf(localize(12094, null))}
		</checkbox>
		<checkbox when-checked="setTheme:${ThemeSettingDefaults.COLOR_THEME_HC_LIGHT}" checked-on="config.workbench.colorTheme == '${ThemeSettingDefaults.COLOR_THEME_HC_LIGHT}'">
			<img width="200" src="./light-hc.png"/>
			${$zf(localize(12095, null))}
		</checkbox>
	</div>
</checklist>
<checkbox class="theme-picker-link" when-checked="command:workbench.action.selectTheme" checked-on="false">
	${$zf(localize(12096, null))}
</checkbox>
`;

// out-build/vs/workbench/contrib/welcomeGettingStarted/common/media/notebookProfile.js
var profileArg = (profile) => encodeURIComponent(JSON.stringify({ profile }));
var imageSize = 400;
var notebookProfile_default = () => `
<vertically-centered>
<checklist>
	<checkbox on-checked="command:notebook.setProfile?${profileArg("default")}" checked-on="config.notebook.cellFocusIndicator == 'border' && config.notebook.insertToolbarLocation == 'both' && config.notebook.globalToolbar == false && config.notebook.compactView == true && config.notebook.showCellStatusBar == 'visible'">
		<img width="${imageSize}" src="./notebookThemes/default.png"/>
		${$zf(localize(12089, null))}
	</checkbox>
	<checkbox on-checked="command:notebook.setProfile?${profileArg("jupyter")}" checked-on="config.notebook.cellFocusIndicator == 'gutter' && config.notebook.insertToolbarLocation == 'notebookToolbar' && config.notebook.globalToolbar == true && config.notebook.compactView == true  && config.notebook.showCellStatusBar == 'visible'">
		<img width="${imageSize}" src="./notebookThemes/jupyter.png"/>
		${$zf(localize(12090, null))}
	</checkbox>
	<checkbox on-checked="command:notebook.setProfile?${profileArg("colab")}" checked-on="config.notebook.cellFocusIndicator == 'border' && config.notebook.insertToolbarLocation == 'betweenCells' && config.notebook.globalToolbar == false && config.notebook.compactView == false && config.notebook.showCellStatusBar == 'hidden'">
		<img width="${imageSize}" src="./notebookThemes/colab.png"/>
		${$zf(localize(12091, null))}
	</checkbox>
</checklist>
</vertically-centered>
`;

// out-build/vs/workbench/contrib/welcomeGettingStarted/common/gettingStartedContent.js
var GettingStartedContentProviderRegistry = class {
  constructor() {
    this.a = /* @__PURE__ */ new Map();
  }
  registerProvider(moduleId, provider) {
    this.a.set(moduleId, provider);
  }
  getProvider(moduleId) {
    return this.a.get(moduleId);
  }
};
var $Shc = new GettingStartedContentProviderRegistry();
$Shc.registerProvider("vs/workbench/contrib/welcomeGettingStarted/common/media/theme_picker", theme_picker_default);
$Shc.registerProvider("vs/workbench/contrib/welcomeGettingStarted/common/media/notebookProfile", notebookProfile_default);
$Shc.registerProvider("vs/workbench/contrib/welcomeGettingStarted/common/media/empty", () => "");
var setupIcon = $9r("getting-started-setup", $6l.zap, localize(11920, null));
var beginnerIcon = $9r("getting-started-beginner", $6l.lightbulb, localize(11921, null));
var $Uhc = [
  {
    id: "welcome.showNewFileEntries",
    title: localize(11922, null),
    description: localize(11923, null),
    icon: $6l.newFile,
    content: {
      type: "startEntry",
      command: "command:welcome.showNewFileEntries"
    }
  },
  {
    id: "topLevelOpenMac",
    title: localize(11924, null),
    description: localize(11925, null),
    icon: $6l.folderOpened,
    when: "!isWeb && isMac",
    content: {
      type: "startEntry",
      command: "command:workbench.action.files.openFileFolder"
    }
  },
  {
    id: "topLevelOpenFile",
    title: localize(11926, null),
    description: localize(11927, null),
    icon: $6l.goToFile,
    when: "isWeb || !isMac",
    content: {
      type: "startEntry",
      command: "command:workbench.action.files.openFile"
    }
  },
  {
    id: "topLevelOpenFolder",
    title: localize(11928, null),
    description: localize(11929, null),
    icon: $6l.folderOpened,
    when: "!isWeb && !isMac",
    content: {
      type: "startEntry",
      command: "command:workbench.action.files.openFolder"
    }
  },
  {
    id: "topLevelOpenFolderWeb",
    title: localize(11930, null),
    description: localize(11931, null),
    icon: $6l.folderOpened,
    when: "!openFolderWorkspaceSupport && workbenchState == 'workspace'",
    content: {
      type: "startEntry",
      command: "command:workbench.action.files.openFolderViaWorkspace"
    }
  },
  {
    id: "topLevelGitClone",
    title: localize(11932, null),
    description: localize(11933, null),
    when: "config.git.enabled && !git.missing",
    icon: $6l.sourceControl,
    content: {
      type: "startEntry",
      command: "command:git.clone"
    }
  },
  {
    id: "topLevelGitOpen",
    title: localize(11934, null),
    description: localize(11935, null),
    when: "workspacePlatform == 'webworker'",
    icon: $6l.sourceControl,
    content: {
      type: "startEntry",
      command: "command:remoteHub.openRepository"
    }
  },
  {
    id: "topLevelShowWalkthroughs",
    title: localize(11936, null),
    description: localize(11937, null),
    icon: $6l.checklist,
    when: "allWalkthroughsHidden",
    content: {
      type: "startEntry",
      command: "command:welcome.showAllWalkthroughs"
    }
  },
  {
    id: "topLevelRemoteOpen",
    title: localize(11938, null),
    description: localize(11939, null),
    when: "!isWeb",
    icon: $6l.remote,
    content: {
      type: "startEntry",
      command: "command:workbench.action.remote.showMenu"
    }
  },
  {
    id: "topLevelOpenTunnel",
    title: localize(11940, null),
    description: localize(11941, null),
    when: "isWeb && showRemoteStartEntryInWeb",
    icon: $6l.remote,
    content: {
      type: "startEntry",
      command: "command:workbench.action.remote.showWebStartEntryActions"
    }
  }
];
var Button = (title, href) => `[${title}](${href})`;
var CopilotStepTitle = localize(11942, null);
var CopilotDescription = localize(11943, null, product_default.defaultChatAgent?.documentationUrl ?? "");
var CopilotTermsString = localize(11944, null, product_default.defaultChatAgent?.termsStatementUrl ?? "", product_default.defaultChatAgent?.privacyStatementUrl ?? "");
var CopilotSignedOutButton = Button(localize(11945, null), `command:workbench.action.chat.triggerSetup?${encodeURIComponent(JSON.stringify([true]))}`);
var CopilotSignedInButton = Button(localize(11946, null), `command:workbench.action.chat.triggerSetup?${encodeURIComponent(JSON.stringify([true]))}`);
var CopilotCompleteButton = Button(localize(11947, null), "command:workbench.action.chat.open");
function createCopilotSetupStep(id2, button, when, includeTerms) {
  const description = includeTerms ? `${CopilotDescription}

${CopilotTermsString}
${button}` : `${CopilotDescription}
${button}`;
  return {
    id: id2,
    title: CopilotStepTitle,
    description,
    when,
    media: {
      type: "svg",
      altText: "VS Code Copilot multi file edits",
      path: "multi-file-edits.svg"
    }
  };
}
var $Vhc = [
  {
    id: "Setup",
    title: localize(11948, null),
    description: localize(11949, null),
    isFeatured: true,
    icon: setupIcon,
    when: "!isWeb",
    walkthroughPageTitle: localize(11950, null),
    next: "Beginner",
    content: {
      type: "steps",
      steps: [
        createCopilotSetupStep("CopilotSetupSignedOut", CopilotSignedOutButton, "config.chat.experimental.offerSetup && chatSetupSignedOut", true),
        createCopilotSetupStep("CopilotSetupComplete", CopilotCompleteButton, "config.chat.experimental.offerSetup && chatSetupInstalled && (chatSetupEntitled || chatSetupLimited)", false),
        createCopilotSetupStep("CopilotSetupSignedIn", CopilotSignedInButton, "config.chat.experimental.offerSetup && !chatSetupSignedOut && (!chatSetupInstalled || chatSetupCanSignUp)", true),
        {
          id: "pickColorTheme",
          title: localize(11951, null),
          description: localize(11952, null, Button(localize(11953, null), "command:workbench.action.selectTheme")),
          completionEvents: [
            "onSettingChanged:workbench.colorTheme",
            "onCommand:workbench.action.selectTheme"
          ],
          media: { type: "markdown", path: "theme_picker" }
        },
        {
          id: "extensionsWeb",
          title: localize(11954, null),
          description: localize(11955, null, Button(localize(11956, null), "command:workbench.extensions.action.showPopularExtensions")),
          when: "workspacePlatform == 'webworker'",
          media: {
            type: "svg",
            altText: "VS Code extension marketplace with featured language extensions",
            path: "extensions-web.svg"
          }
        },
        {
          id: "findLanguageExtensions",
          title: localize(11957, null),
          description: localize(11958, null, Button(localize(11959, null), "command:workbench.extensions.action.showLanguageExtensions")),
          when: "workspacePlatform != 'webworker'",
          media: {
            type: "svg",
            altText: "Language extensions",
            path: "languages.svg"
          }
        },
        {
          id: "settings",
          title: localize(11960, null),
          description: localize(11961, null, Button(localize(11962, null), "command:toSide:workbench.action.openSettings")),
          when: "!config.chat.experimental.offerSetup",
          media: {
            type: "svg",
            altText: "VS Code Settings",
            path: "settings.svg"
          }
        },
        {
          id: "settingsSync",
          title: localize(11963, null),
          description: localize(11964, null, Button(localize(11965, null), "command:workbench.userDataSync.actions.turnOn")),
          when: "!config.chat.experimental.offerSetup && syncStatus != uninitialized",
          completionEvents: ["onEvent:sync-enabled"],
          media: {
            type: "svg",
            altText: 'The "Turn on Sync" entry in the settings gear menu.',
            path: "settingsSync.svg"
          }
        },
        {
          id: "settingsAndSync",
          title: localize(11966, null),
          description: localize(11967, null, Button(localize(11968, null), "command:toSide:workbench.action.openSettings")),
          when: "config.chat.experimental.offerSetup && syncStatus != uninitialized",
          completionEvents: ["onEvent:sync-enabled"],
          media: {
            type: "svg",
            altText: "VS Code Settings",
            path: "settings.svg"
          }
        },
        {
          id: "commandPaletteTask",
          title: localize(11969, null),
          description: localize(11970, null, Button(localize(11971, null), "command:workbench.action.showCommands")),
          media: { type: "svg", altText: "Command Palette overlay for searching and executing commands.", path: "commandPalette.svg" }
        },
        {
          id: "pickAFolderTask-Mac",
          title: localize(11972, null),
          description: localize(11973, null, Button(localize(11974, null), "command:workbench.action.files.openFileFolder")),
          when: "!config.chat.experimental.offerSetup && isMac && workspaceFolderCount == 0",
          media: {
            type: "svg",
            altText: "Explorer view showing buttons for opening folder and cloning repository.",
            path: "openFolder.svg"
          }
        },
        {
          id: "pickAFolderTask-Other",
          title: localize(11975, null),
          description: localize(11976, null, Button(localize(11977, null), "command:workbench.action.files.openFolder")),
          when: "!config.chat.experimental.offerSetup && !isMac && workspaceFolderCount == 0",
          media: {
            type: "svg",
            altText: "Explorer view showing buttons for opening folder and cloning repository.",
            path: "openFolder.svg"
          }
        },
        {
          id: "quickOpen",
          title: localize(11978, null),
          description: localize(11979, null, Button(localize(11980, null), "command:toSide:workbench.action.quickOpen")),
          when: "workspaceFolderCount != 0",
          media: {
            type: "svg",
            altText: "Go to file in quick search.",
            path: "search.svg"
          }
        },
        {
          id: "videoTutorial",
          title: localize(11981, null),
          description: localize(11982, null, Button(localize(11983, null), "https://aka.ms/vscode-getting-started-video")),
          media: { type: "svg", altText: "VS Code Settings", path: "learn.svg" }
        }
      ]
    }
  },
  {
    id: "SetupWeb",
    title: localize(11984, null),
    description: localize(11985, null),
    isFeatured: true,
    icon: setupIcon,
    when: "isWeb",
    next: "Beginner",
    walkthroughPageTitle: localize(11986, null),
    content: {
      type: "steps",
      steps: [
        {
          id: "pickColorThemeWeb",
          title: localize(11987, null),
          description: localize(11988, null, Button(localize(11989, null), "command:workbench.action.selectTheme")),
          completionEvents: [
            "onSettingChanged:workbench.colorTheme",
            "onCommand:workbench.action.selectTheme"
          ],
          media: { type: "markdown", path: "theme_picker" }
        },
        {
          id: "menuBarWeb",
          title: localize(11990, null),
          description: localize(11991, null, Button(localize(11992, null), "command:workbench.action.toggleMenuBar")),
          when: "isWeb",
          media: {
            type: "svg",
            altText: "Comparing menu dropdown with the visible menu bar.",
            path: "menuBar.svg"
          }
        },
        {
          id: "extensionsWebWeb",
          title: localize(11993, null),
          description: localize(11994, null, Button(localize(11995, null), "command:workbench.extensions.action.showPopularExtensions")),
          when: "workspacePlatform == 'webworker'",
          media: {
            type: "svg",
            altText: "VS Code extension marketplace with featured language extensions",
            path: "extensions-web.svg"
          }
        },
        {
          id: "findLanguageExtensionsWeb",
          title: localize(11996, null),
          description: localize(11997, null, Button(localize(11998, null), "command:workbench.extensions.action.showLanguageExtensions")),
          when: "workspacePlatform != 'webworker'",
          media: {
            type: "svg",
            altText: "Language extensions",
            path: "languages.svg"
          }
        },
        {
          id: "settingsSyncWeb",
          title: localize(11999, null),
          description: localize(12e3, null, Button(localize(12001, null), "command:workbench.userDataSync.actions.turnOn")),
          when: "syncStatus != uninitialized",
          completionEvents: ["onEvent:sync-enabled"],
          media: {
            type: "svg",
            altText: 'The "Turn on Sync" entry in the settings gear menu.',
            path: "settingsSync.svg"
          }
        },
        {
          id: "commandPaletteTaskWeb",
          title: localize(12002, null),
          description: localize(12003, null, Button(localize(12004, null), "command:workbench.action.showCommands")),
          media: { type: "svg", altText: "Command Palette overlay for searching and executing commands.", path: "commandPalette.svg" }
        },
        {
          id: "pickAFolderTask-WebWeb",
          title: localize(12005, null),
          description: localize(12006, null, Button(localize(12007, null), "command:workbench.action.addRootFolder"), Button(localize(12008, null), "command:remoteHub.openRepository")),
          when: "workspaceFolderCount == 0",
          media: {
            type: "svg",
            altText: "Explorer view showing buttons for opening folder and cloning repository.",
            path: "openFolder.svg"
          }
        },
        {
          id: "quickOpenWeb",
          title: localize(12009, null),
          description: localize(12010, null, Button(localize(12011, null), "command:toSide:workbench.action.quickOpen")),
          when: "workspaceFolderCount != 0",
          media: {
            type: "svg",
            altText: "Go to file in quick search.",
            path: "search.svg"
          }
        }
      ]
    }
  },
  {
    id: "SetupAccessibility",
    title: localize(12012, null),
    description: localize(12013, null),
    isFeatured: true,
    icon: setupIcon,
    when: $OD.key,
    next: "Setup",
    walkthroughPageTitle: localize(12014, null),
    content: {
      type: "steps",
      steps: [
        {
          id: "accessibilityHelp",
          title: localize(12015, null),
          description: localize(12016, null, Button(localize(12017, null), "command:editor.action.accessibilityHelp")),
          media: {
            type: "markdown",
            path: "empty"
          }
        },
        {
          id: "accessibleView",
          title: localize(12018, null),
          description: localize(12019, null, Button(localize(12020, null), "command:editor.action.accessibleView")),
          media: {
            type: "markdown",
            path: "empty"
          }
        },
        {
          id: "verbositySettings",
          title: localize(12021, null),
          description: localize(12022, null, Button(localize(12023, null), "command:workbench.action.openAccessibilitySettings")),
          media: {
            type: "markdown",
            path: "empty"
          }
        },
        {
          id: "commandPaletteTaskAccessibility",
          title: localize(12024, null),
          description: localize(12025, null, Button(localize(12026, null), "command:workbench.action.showCommands")),
          media: { type: "markdown", path: "empty" }
        },
        {
          id: "keybindingsAccessibility",
          title: localize(12027, null),
          description: localize(12028, null, Button(localize(12029, null), "command:toSide:workbench.action.openGlobalKeybindings")),
          media: {
            type: "markdown",
            path: "empty"
          }
        },
        {
          id: "accessibilitySignals",
          title: localize(12030, null),
          description: localize(12031, null, Button(localize(12032, null), "command:signals.sounds.help"), Button(localize(12033, null), "command:accessibility.announcement.help")),
          media: {
            type: "markdown",
            path: "empty"
          }
        },
        {
          id: "hover",
          title: localize(12034, null),
          description: localize(12035, null, Button(localize(12036, null), "command:editor.action.showHover")),
          media: {
            type: "markdown",
            path: "empty"
          }
        },
        {
          id: "goToSymbol",
          title: localize(12037, null),
          description: localize(12038, null, Button(localize(12039, null), "command:editor.action.goToSymbol")),
          media: {
            type: "markdown",
            path: "empty"
          }
        },
        {
          id: "codeFolding",
          title: localize(12040, null),
          description: localize(12041, null, Button(localize(12042, null), "command:editor.toggleFold"), Button(localize(12043, null), "command:editor.toggleFoldRecursively")),
          media: {
            type: "markdown",
            path: "empty"
          }
        },
        {
          id: "intellisense",
          title: localize(12044, null),
          description: localize(12045, null, Button(localize(12046, null), "command:editor.action.triggerSuggest"), Button(localize(12047, null), "command:editor.action.inlineSuggest.trigger")),
          media: {
            type: "markdown",
            path: "empty"
          }
        },
        {
          id: "accessibilitySettings",
          title: localize(12048, null),
          description: localize(12049, null, Button(localize(12050, null), "command:workbench.action.openAccessibilitySettings")),
          media: { type: "markdown", path: "empty" }
        }
      ]
    }
  },
  {
    id: "Beginner",
    isFeatured: false,
    title: localize(12051, null),
    icon: beginnerIcon,
    description: localize(12052, null),
    walkthroughPageTitle: localize(12053, null),
    content: {
      type: "steps",
      steps: [
        {
          id: "extensions",
          title: localize(12054, null),
          description: localize(12055, null, Button(localize(12056, null), "command:workbench.extensions.action.showPopularExtensions")),
          when: "workspacePlatform != 'webworker'",
          media: {
            type: "svg",
            altText: "VS Code extension marketplace with featured language extensions",
            path: "extensions.svg"
          }
        },
        {
          id: "terminal",
          title: localize(12057, null),
          description: localize(12058, null, Button(localize(12059, null), "command:workbench.action.terminal.toggleTerminal")),
          when: "workspacePlatform != 'webworker' && remoteName != codespaces && !terminalIsOpen",
          media: {
            type: "svg",
            altText: "Integrated terminal running a few npm commands",
            path: "terminal.svg"
          }
        },
        {
          id: "debugging",
          title: localize(12060, null),
          description: localize(12061, null, Button(localize(12062, null), "command:workbench.action.debug.selectandstart")),
          when: "workspacePlatform != 'webworker' && workspaceFolderCount != 0",
          media: {
            type: "svg",
            altText: "Run and debug view.",
            path: "debug.svg"
          }
        },
        {
          id: "scmClone",
          title: localize(12063, null),
          description: localize(12064, null, Button(localize(12065, null), "command:git.clone")),
          when: "config.git.enabled && !git.missing && workspaceFolderCount == 0",
          media: {
            type: "svg",
            altText: "Source Control view.",
            path: "git.svg"
          }
        },
        {
          id: "scmSetup",
          title: localize(12066, null),
          description: localize(12067, null, Button(localize(12068, null), "command:git.init")),
          when: "config.git.enabled && !git.missing && workspaceFolderCount != 0 && gitOpenRepositoryCount == 0",
          media: {
            type: "svg",
            altText: "Source Control view.",
            path: "git.svg"
          }
        },
        {
          id: "scm",
          title: localize(12069, null),
          description: localize(12070, null, Button(localize(12071, null), "command:workbench.view.scm")),
          when: "config.git.enabled && !git.missing && workspaceFolderCount != 0 && gitOpenRepositoryCount != 0 && activeViewlet != 'workbench.view.scm'",
          media: {
            type: "svg",
            altText: "Source Control view.",
            path: "git.svg"
          }
        },
        {
          id: "installGit",
          title: localize(12072, null),
          description: localize(12073, null, Button(localize(12074, null), "https://aka.ms/vscode-install-git"), "[", "](command:workbench.action.reloadWindow)"),
          when: "git.missing",
          media: {
            type: "svg",
            altText: "Install Git.",
            path: "git.svg"
          },
          completionEvents: [
            "onContext:git.state == initialized"
          ]
        },
        {
          id: "tasks",
          title: localize(12075, null),
          when: "workspaceFolderCount != 0 && workspacePlatform != 'webworker'",
          description: localize(12076, null, Button(localize(12077, null), "command:workbench.action.tasks.runTask")),
          media: {
            type: "svg",
            altText: "Task runner.",
            path: "runTask.svg"
          }
        },
        {
          id: "shortcuts",
          title: localize(12078, null),
          description: localize(12079, null, Button(localize(12080, null), "command:toSide:workbench.action.openGlobalKeybindings")),
          media: {
            type: "svg",
            altText: "Interactive shortcuts.",
            path: "shortcuts.svg"
          }
        },
        {
          id: "workspaceTrust",
          title: localize(12081, null),
          description: localize(12082, null, Button(localize(12083, null), "https://code.visualstudio.com/docs/editor/workspace-trust"), Button(localize(12084, null), "command:toSide:workbench.action.manageTrustedDomain")),
          when: "workspacePlatform != 'webworker' && !isWorkspaceTrusted && workspaceFolderCount == 0",
          media: {
            type: "svg",
            altText: "Workspace Trust editor in Restricted mode and a primary button for switching to Trusted mode.",
            path: "workspaceTrust.svg"
          }
        }
      ]
    }
  },
  {
    id: "notebooks",
    title: localize(12085, null),
    description: "",
    icon: setupIcon,
    isFeatured: false,
    when: `config.${$rM.openGettingStarted} && userHasOpenedNotebook`,
    walkthroughPageTitle: localize(12086, null),
    content: {
      type: "steps",
      steps: [
        {
          completionEvents: ["onCommand:notebook.setProfile"],
          id: "notebookProfile",
          title: localize(12087, null),
          description: localize(12088, null),
          when: "userHasOpenedNotebook",
          media: {
            type: "markdown",
            path: "notebookProfile"
          }
        }
      ]
    }
  }
];

// out-build/vs/workbench/contrib/welcomeGettingStarted/browser/gettingStartedExtensionPoint.js
var titleTranslated = localize(11873, null);
var $Whc = $tN.registerExtensionPoint({
  extensionPoint: "walkthroughs",
  jsonSchema: {
    description: localize(11874, null),
    type: "array",
    items: {
      type: "object",
      required: ["id", "title", "description", "steps"],
      defaultSnippets: [{ body: { "id": "$1", "title": "$2", "description": "$3", "steps": [] } }],
      properties: {
        id: {
          type: "string",
          description: localize(11875, null)
        },
        title: {
          type: "string",
          description: localize(11876, null)
        },
        icon: {
          type: "string",
          description: localize(11877, null)
        },
        description: {
          type: "string",
          description: localize(11878, null)
        },
        featuredFor: {
          type: "array",
          description: localize(11879, null),
          items: {
            type: "string"
          }
        },
        when: {
          type: "string",
          description: localize(11880, null)
        },
        steps: {
          type: "array",
          description: localize(11881, null),
          items: {
            type: "object",
            required: ["id", "title", "media"],
            defaultSnippets: [{
              body: {
                "id": "$1",
                "title": "$2",
                "description": "$3",
                "completionEvents": ["$5"],
                "media": {}
              }
            }],
            properties: {
              id: {
                type: "string",
                description: localize(11882, null)
              },
              title: {
                type: "string",
                description: localize(11883, null)
              },
              description: {
                type: "string",
                description: localize(11884, null, `[${titleTranslated}](command:myext.command)`, `[${titleTranslated}](command:toSide:myext.command)`, `[${titleTranslated}](https://aka.ms)`)
              },
              button: {
                deprecationMessage: localize(11885, null, `[${titleTranslated}](command:myext.command)`, `[${titleTranslated}](command:toSide:myext.command)`, `[${titleTranslated}](https://aka.ms)`)
              },
              media: {
                type: "object",
                description: localize(11886, null),
                oneOf: [
                  {
                    required: ["image", "altText"],
                    additionalProperties: false,
                    properties: {
                      path: {
                        deprecationMessage: localize(11887, null)
                      },
                      image: {
                        description: localize(11888, null),
                        oneOf: [
                          {
                            type: "string"
                          },
                          {
                            type: "object",
                            required: ["dark", "light", "hc", "hcLight"],
                            properties: {
                              dark: {
                                description: localize(11889, null),
                                type: "string"
                              },
                              light: {
                                description: localize(11890, null),
                                type: "string"
                              },
                              hc: {
                                description: localize(11891, null),
                                type: "string"
                              },
                              hcLight: {
                                description: localize(11892, null),
                                type: "string"
                              }
                            }
                          }
                        ]
                      },
                      altText: {
                        type: "string",
                        description: localize(11893, null)
                      }
                    }
                  },
                  {
                    required: ["svg", "altText"],
                    additionalProperties: false,
                    properties: {
                      svg: {
                        description: localize(11894, null),
                        type: "string"
                      },
                      altText: {
                        type: "string",
                        description: localize(11895, null)
                      }
                    }
                  },
                  {
                    required: ["markdown"],
                    additionalProperties: false,
                    properties: {
                      path: {
                        deprecationMessage: localize(11896, null)
                      },
                      markdown: {
                        description: localize(11897, null),
                        type: "string"
                      }
                    }
                  }
                ]
              },
              completionEvents: {
                description: localize(11898, null),
                type: "array",
                items: {
                  type: "string",
                  defaultSnippets: [
                    {
                      label: "onCommand",
                      description: localize(11899, null),
                      body: "onCommand:${1:commandId}"
                    },
                    {
                      label: "onLink",
                      description: localize(11900, null),
                      body: "onLink:${2:linkId}"
                    },
                    {
                      label: "onView",
                      description: localize(11901, null),
                      body: "onView:${2:viewId}"
                    },
                    {
                      label: "onSettingChanged",
                      description: localize(11902, null),
                      body: "onSettingChanged:${2:settingName}"
                    },
                    {
                      label: "onContext",
                      description: localize(11903, null),
                      body: "onContext:${2:key}"
                    },
                    {
                      label: "onExtensionInstalled",
                      description: localize(11904, null),
                      body: "onExtensionInstalled:${3:extensionId}"
                    },
                    {
                      label: "onStepSelected",
                      description: localize(11905, null),
                      body: "onStepSelected"
                    }
                  ]
                }
              },
              doneOn: {
                description: localize(11906, null),
                deprecationMessage: localize(11907, null),
                type: "object",
                required: ["command"],
                defaultSnippets: [{ "body": { command: "$1" } }],
                properties: {
                  "command": {
                    description: localize(11908, null),
                    type: "string"
                  }
                }
              },
              when: {
                type: "string",
                description: localize(11909, null)
              }
            }
          }
        }
      }
    }
  },
  activationEventsGenerator: (walkthroughContributions, result) => {
    for (const walkthroughContribution of walkthroughContributions) {
      if (walkthroughContribution.id) {
        result.push(`onWalkthrough:${walkthroughContribution.id}`);
      }
    }
  }
});

// out-build/vs/workbench/contrib/welcomeGettingStarted/browser/gettingStartedService.js
var $Xhc = new $nn("hasMultipleNewFileEntries", false);
var $Yhc = $Qk("walkthroughsService");
var $Zhc = "workbench.welcomePage.hiddenCategories";
var $1hc = "workbench.welcomePage.walkthroughMetadata";
var BUILT_IN_SOURCE = localize(11914, null);
var DAYS = 24 * 60 * 60 * 1e3;
var NEW_WALKTHROUGH_TIME = 7 * DAYS;
var $2hc = class $2hc2 extends $3c {
  constructor(F, G, H, I, J, L, M, N, O, P, Q, R, S) {
    super();
    this.F = F;
    this.G = G;
    this.H = H;
    this.I = I;
    this.J = J;
    this.L = L;
    this.M = M;
    this.N = N;
    this.O = O;
    this.P = P;
    this.Q = Q;
    this.R = R;
    this.S = S;
    this.b = new $ze();
    this.onDidAddWalkthrough = this.b.event;
    this.c = new $ze();
    this.onDidRemoveWalkthrough = this.c.event;
    this.g = new $ze();
    this.onDidChangeWalkthrough = this.g.event;
    this.h = new $ze();
    this.onDidProgressStep = this.h.event;
    this.n = /* @__PURE__ */ new Set();
    this.r = /* @__PURE__ */ new Map();
    this.t = /* @__PURE__ */ new Map();
    this.u = /* @__PURE__ */ new Map();
    this.w = /* @__PURE__ */ new Set();
    this.y = /* @__PURE__ */ new Set();
    this.z = /* @__PURE__ */ new Set();
    this.C = /* @__PURE__ */ new Set();
    this.D = new Map(JSON.parse(this.F.get($1hc, 0, "[]")));
    this.j = new $Slb("gettingStartedService", this.F);
    this.m = this.j.getMemento(
      0,
      0
      /* StorageTarget.USER */
    );
    this.W();
    $Xhc.bindTo(this.J).set(false);
    this.U();
  }
  U() {
    $Vhc.forEach(async (category8, index) => {
      this._registerWalkthrough({
        ...category8,
        icon: { type: "icon", icon: category8.icon },
        order: $Vhc.length - index,
        source: BUILT_IN_SOURCE,
        when: $7m.deserialize(category8.when) ?? $7m.true(),
        steps: category8.content.steps.map((step, index2) => {
          return {
            ...step,
            completionEvents: step.completionEvents ?? [],
            description: $3hc(step.description),
            category: category8.id,
            order: index2,
            when: $7m.deserialize(step.when) ?? $7m.true(),
            media: step.media.type === "image" ? {
              type: "image",
              altText: step.media.altText,
              path: convertInternalMediaPathsToBrowserURIs(step.media.path)
            } : step.media.type === "svg" ? {
              type: "svg",
              altText: step.media.altText,
              path: $4hc(step.media.path).with({ query: JSON.stringify({ moduleId: "vs/workbench/contrib/welcomeGettingStarted/common/media/" + step.media.path }) })
            } : {
              type: "markdown",
              path: $4hc(step.media.path).with({ query: JSON.stringify({ moduleId: "vs/workbench/contrib/welcomeGettingStarted/common/media/" + step.media.path }) }),
              base: $ih.asFileUri("vs/workbench/contrib/welcomeGettingStarted/common/media/"),
              root: $ih.asFileUri("vs/workbench/contrib/welcomeGettingStarted/common/media/")
            }
          };
        })
      });
    });
    $Whc.setHandler((_, { added, removed }) => {
      added.map((e) => this.X(e.description));
      removed.map((e) => this.Y(e.description));
    });
  }
  W() {
    this.B(this.G.onDidExecuteCommand((command4) => this.progressByEvent(`onCommand:${command4.commandId}`)));
    this.N.getInstalled().then((installed) => {
      installed.forEach((ext) => this.progressByEvent(`extensionInstalled:${ext.identifier.id.toLowerCase()}`));
    });
    this.B(this.N.onDidInstallExtensions((result) => {
      if (result.some((e) => $5z.equals(this.S.defaultChatAgent?.extensionId, e.identifier.id) && !e?.context?.[$fA])) {
        result.forEach((e) => {
          this.w.add(e.identifier.id.toLowerCase());
          this.progressByEvent(`extensionInstalled:${e.identifier.id.toLowerCase()}`);
        });
        return;
      }
      for (const e of result) {
        const skipWalkthrough = e?.context?.[$fA] || e?.context?.[$hA];
        if (!skipWalkthrough) {
          this.w.add(e.identifier.id.toLowerCase());
        }
        this.progressByEvent(`extensionInstalled:${e.identifier.id.toLowerCase()}`);
      }
    }));
    this.B(this.J.onDidChangeContext((event) => {
      if (event.affectsSome(this.C)) {
        this.z.forEach((expression) => {
          if (event.affectsSome(new Set(expression.keys())) && this.J.contextMatchesRules(expression)) {
            this.progressByEvent(`onContext:` + expression.serialize());
          }
        });
      }
    }));
    this.B(this.P.onDidChangeViewVisibility((e) => {
      if (e.visible) {
        this.progressByEvent("onView:" + e.id);
      }
    }));
    this.B(this.M.onDidChangeConfiguration((e) => {
      e.affectedKeys.forEach((key2) => {
        this.progressByEvent("onSettingChanged:" + key2);
      });
    }));
    if (this.L.isEnabled()) {
      this.progressByEvent("onEvent:sync-enabled");
    }
    this.B(this.L.onDidChangeEnablement(() => {
      if (this.L.isEnabled()) {
        this.progressByEvent("onEvent:sync-enabled");
      }
    }));
  }
  markWalkthroughOpened(id2) {
    const walkthrough = this.t.get(id2);
    const prior = this.D.get(id2);
    if (prior && walkthrough) {
      this.D.set(id2, { ...prior, manaullyOpened: true, stepIDs: walkthrough.steps.map((s) => s.id) });
    }
    this.F.store(
      $1hc,
      JSON.stringify([...this.D.entries()]),
      0,
      0
      /* StorageTarget.USER */
    );
  }
  async X(extension) {
    const convertExtensionPathToFileURI = (path) => path.startsWith("https://") ? URI.parse(path, true) : $ih.uriToFileUri($vh(extension.extensionLocation, path));
    const convertExtensionRelativePathsToBrowserURIs = (path) => {
      const convertPath = (path2) => path2.startsWith("https://") ? URI.parse(path2, true) : $ih.uriToBrowserUri($vh(extension.extensionLocation, path2));
      if (typeof path === "string") {
        const converted = convertPath(path);
        return { hcDark: converted, hcLight: converted, dark: converted, light: converted };
      } else {
        return {
          hcDark: convertPath(path.hc),
          hcLight: convertPath(path.hcLight ?? path.light),
          light: convertPath(path.light),
          dark: convertPath(path.dark)
        };
      }
    };
    if (!extension.contributes?.walkthroughs?.length) {
      return;
    }
    let sectionToOpen;
    let sectionToOpenIndex = Math.min();
    await Promise.all(extension.contributes?.walkthroughs?.map(async (walkthrough, index) => {
      const categoryID = extension.identifier.value + "#" + walkthrough.id;
      const isNewlyInstalled = !this.D.get(categoryID);
      if (isNewlyInstalled) {
        this.D.set(categoryID, { firstSeen: +/* @__PURE__ */ new Date(), stepIDs: walkthrough.steps?.map((s) => s.id) ?? [], manaullyOpened: false });
      }
      const override = await Promise.race([
        this.R?.getTreatment(`gettingStarted.overrideCategory.${extension.identifier.value + "." + walkthrough.id}.when`),
        new Promise((resolve) => setTimeout(() => resolve(walkthrough.when), 5e3))
      ]);
      if (this.w.has(extension.identifier.value.toLowerCase()) && this.J.contextMatchesRules($7m.deserialize(override ?? walkthrough.when) ?? $7m.true())) {
        this.w.delete(extension.identifier.value.toLowerCase());
        if (index < sectionToOpenIndex && isNewlyInstalled) {
          sectionToOpen = categoryID;
          sectionToOpenIndex = index;
        }
      }
      const steps = (walkthrough.steps ?? []).map((step, index2) => {
        const description = $3hc(step.description || "");
        const fullyQualifiedID = extension.identifier.value + "#" + walkthrough.id + "#" + step.id;
        let media;
        if (!step.media) {
          throw Error("missing media in walkthrough step: " + walkthrough.id + "@" + step.id);
        }
        if (step.media.image) {
          const altText = step.media.altText;
          if (altText === void 0) {
            console.error("Walkthrough item:", fullyQualifiedID, "is missing altText for its media element.");
          }
          media = { type: "image", altText, path: convertExtensionRelativePathsToBrowserURIs(step.media.image) };
        } else if (step.media.markdown) {
          media = {
            type: "markdown",
            path: convertExtensionPathToFileURI(step.media.markdown),
            base: convertExtensionPathToFileURI($qc(step.media.markdown)),
            root: $ih.uriToFileUri(extension.extensionLocation)
          };
        } else if (step.media.svg) {
          media = {
            type: "svg",
            path: convertExtensionPathToFileURI(step.media.svg),
            altText: step.media.svg
          };
        } else {
          throw new Error("Unknown walkthrough format detected for " + fullyQualifiedID);
        }
        return {
          description,
          media,
          completionEvents: step.completionEvents?.filter((x) => typeof x === "string") ?? [],
          id: fullyQualifiedID,
          title: step.title,
          when: $7m.deserialize(step.when) ?? $7m.true(),
          category: categoryID,
          order: index2
        };
      });
      let isFeatured = false;
      if (walkthrough.featuredFor) {
        const folders = this.I.getWorkspace().folders.map((f) => f.uri);
        const token = new $ad();
        setTimeout(() => token.cancel(), 2e3);
        isFeatured = await this.H.invokeFunction((a) => $8Rb(a, folders, walkthrough.featuredFor, token.token));
      }
      const iconStr = walkthrough.icon ?? extension.icon;
      const walkthoughDescriptor = {
        description: walkthrough.description,
        title: walkthrough.title,
        id: categoryID,
        isFeatured,
        source: extension.displayName ?? extension.name,
        order: 0,
        walkthroughPageTitle: extension.displayName ?? extension.name,
        steps,
        icon: {
          type: "image",
          path: iconStr ? $ih.uriToBrowserUri($vh(extension.extensionLocation, iconStr)).toString(true) : $ozb
        },
        when: $7m.deserialize(override ?? walkthrough.when) ?? $7m.true()
      };
      this._registerWalkthrough(walkthoughDescriptor);
      this.b.fire(this.Z(walkthoughDescriptor));
    }));
    this.F.store(
      $1hc,
      JSON.stringify([...this.D.entries()]),
      0,
      0
      /* StorageTarget.USER */
    );
    const hadLastFoucs = await this.O.hadLastFocus();
    if (hadLastFoucs && sectionToOpen && this.M.getValue("workbench.welcomePage.walkthroughs.openOnInstall")) {
      this.Q.publicLog2("gettingStarted.didAutoOpenWalkthrough", { id: sectionToOpen });
      this.G.executeCommand("workbench.action.openWalkthrough", sectionToOpen);
    }
  }
  Y(extension) {
    if (!extension.contributes?.walkthroughs?.length) {
      return;
    }
    extension.contributes?.walkthroughs?.forEach((section) => {
      const categoryID = extension.identifier.value + "#" + section.id;
      section.steps.forEach((step) => {
        const fullyQualifiedID = extension.identifier.value + "#" + section.id + "#" + step.id;
        this.u.delete(fullyQualifiedID);
      });
      this.t.delete(categoryID);
      this.c.fire(categoryID);
    });
  }
  getWalkthrough(id2) {
    const walkthrough = this.t.get(id2);
    if (!walkthrough) {
      throw Error("Trying to get unknown walkthrough: " + id2);
    }
    return this.Z(walkthrough);
  }
  getWalkthroughs() {
    const registeredCategories = [...this.t.values()];
    const categoriesWithCompletion = registeredCategories.map((category8) => {
      return {
        ...category8,
        content: {
          type: "steps",
          steps: category8.steps
        }
      };
    }).filter((category8) => category8.content.type !== "steps" || category8.content.steps.length).map((category8) => this.Z(category8));
    return categoriesWithCompletion;
  }
  Z(category8) {
    const stepsWithProgress = category8.steps.map((step) => this.$(step));
    const hasOpened = this.D.get(category8.id)?.manaullyOpened;
    const firstSeenDate = this.D.get(category8.id)?.firstSeen;
    const isNew = firstSeenDate && firstSeenDate > +/* @__PURE__ */ new Date() - NEW_WALKTHROUGH_TIME;
    const lastStepIDs = this.D.get(category8.id)?.stepIDs;
    const rawCategory = this.t.get(category8.id);
    if (!rawCategory) {
      throw Error("Could not find walkthrough with id " + category8.id);
    }
    const currentStepIds = rawCategory.steps.map((s) => s.id);
    const hasNewSteps = lastStepIDs && (currentStepIds.length !== lastStepIDs.length || currentStepIds.some((id2, index) => id2 !== lastStepIDs[index]));
    let recencyBonus = 0;
    if (firstSeenDate) {
      const currentDate = +/* @__PURE__ */ new Date();
      const timeSinceFirstSeen = currentDate - firstSeenDate;
      recencyBonus = Math.max(0, (NEW_WALKTHROUGH_TIME - timeSinceFirstSeen) / NEW_WALKTHROUGH_TIME);
    }
    return {
      ...category8,
      recencyBonus,
      steps: stepsWithProgress,
      newItems: !!hasNewSteps,
      newEntry: !!(isNew && !hasOpened)
    };
  }
  $(step) {
    return {
      ...step,
      done: false,
      ...this.m[step.id]
    };
  }
  progressStep(id2) {
    const oldProgress = this.m[id2];
    if (!oldProgress || oldProgress.done !== true) {
      this.m[id2] = { done: true };
      this.j.saveMemento();
      const step = this.cb(id2);
      if (!step) {
        throw Error("Tried to progress unknown step");
      }
      this.h.fire(this.$(step));
    }
  }
  deprogressStep(id2) {
    delete this.m[id2];
    this.j.saveMemento();
    const step = this.cb(id2);
    this.h.fire(this.$(step));
  }
  progressByEvent(event) {
    if (this.n.has(event)) {
      return;
    }
    this.n.add(event);
    this.r.get(event)?.forEach((id2) => this.progressStep(id2));
  }
  registerWalkthrough(walkthoughDescriptor) {
    this._registerWalkthrough({
      ...walkthoughDescriptor,
      steps: walkthoughDescriptor.steps.map((step) => ({ ...step, description: $3hc(step.description) }))
    });
  }
  _registerWalkthrough(walkthroughDescriptor) {
    const oldCategory = this.t.get(walkthroughDescriptor.id);
    if (oldCategory) {
      console.error(`Skipping attempt to overwrite walkthrough. (${walkthroughDescriptor.id})`);
      return;
    }
    this.t.set(walkthroughDescriptor.id, walkthroughDescriptor);
    walkthroughDescriptor.steps.forEach((step) => {
      if (this.u.has(step.id)) {
        throw Error("Attempting to register step with id " + step.id + " twice. Second is dropped.");
      }
      this.u.set(step.id, step);
      step.when.keys().forEach((key2) => this.y.add(key2));
      this.ab(step);
    });
    walkthroughDescriptor.when.keys().forEach((key2) => this.y.add(key2));
  }
  ab(step) {
    if (step.doneOn) {
      console.error(`wakthrough step`, step, `uses deprecated 'doneOn' property. Adopt 'completionEvents' to silence this warning`);
      return;
    }
    if (!step.completionEvents.length) {
      step.completionEvents = $Mb(step.description.filter((linkedText) => linkedText.nodes.length === 1).flatMap((linkedText) => linkedText.nodes.filter((node) => typeof node !== "string").map(({ href }) => {
        if (href.startsWith("command:")) {
          return "onCommand:" + href.slice("command:".length, href.includes("?") ? href.indexOf("?") : void 0);
        }
        if (href.startsWith("https://") || href.startsWith("http://")) {
          return "onLink:" + href;
        }
        return void 0;
      })));
    }
    if (!step.completionEvents.length) {
      step.completionEvents.push("stepSelected");
    }
    for (let event of step.completionEvents) {
      const [_, eventType, argument] = /^([^:]*):?(.*)$/.exec(event) ?? [];
      if (!eventType) {
        console.error(`Unknown completionEvent ${event} when registering step ${step.id}`);
        continue;
      }
      switch (eventType) {
        case "onLink":
        case "onEvent":
        case "onView":
        case "onSettingChanged":
          break;
        case "onContext": {
          const expression = $7m.deserialize(argument);
          if (expression) {
            this.z.add(expression);
            expression.keys().forEach((key2) => this.C.add(key2));
            event = eventType + ":" + expression.serialize();
            if (this.J.contextMatchesRules(expression)) {
              this.n.add(event);
            }
          } else {
            console.error("Unable to parse context key expression:", expression, "in walkthrough step", step.id);
          }
          break;
        }
        case "onStepSelected":
        case "stepSelected":
          event = "stepSelected:" + step.id;
          break;
        case "onCommand":
          event = eventType + ":" + argument.replace(/^toSide:/, "");
          break;
        case "onExtensionInstalled":
        case "extensionInstalled":
          event = "extensionInstalled:" + argument.toLowerCase();
          break;
        default:
          console.error(`Unknown completionEvent ${event} when registering step ${step.id}`);
          continue;
      }
      this.bb(event, step);
    }
  }
  bb(event, step) {
    if (!this.r.has(event)) {
      this.r.set(event, /* @__PURE__ */ new Set());
    }
    this.r.get(event)?.add(step.id);
  }
  cb(id2) {
    const step = this.u.get(id2);
    if (!step) {
      throw Error("Attempting to access step which does not exist in registry " + id2);
    }
    return step;
  }
};
$2hc = __decorate([
  __param(0, $jv),
  __param(1, $sn),
  __param(2, $Pk),
  __param(3, $Zk),
  __param(4, $on),
  __param(5, $6Bb),
  __param(6, $kl),
  __param(7, $sA),
  __param(8, $S4),
  __param(9, $uob),
  __param(10, $zv),
  __param(11, $hFb),
  __param(12, $Vu)
], $2hc);
var $3hc = (desc) => desc.split("\n").filter((x) => x).map((text2) => $U3(text2));
var $4hc = (path) => path.startsWith("https://") ? URI.parse(path, true) : $ih.asFileUri(`vs/workbench/contrib/welcomeGettingStarted/common/media/${path}`);
var convertInternalMediaPathToBrowserURI = (path) => path.startsWith("https://") ? URI.parse(path, true) : $ih.asBrowserUri(`vs/workbench/contrib/welcomeGettingStarted/common/media/${path}`);
var convertInternalMediaPathsToBrowserURIs = (path) => {
  if (typeof path === "string") {
    const converted = convertInternalMediaPathToBrowserURI(path);
    return { hcDark: converted, hcLight: converted, dark: converted, light: converted };
  } else {
    return {
      hcDark: convertInternalMediaPathToBrowserURI(path.hc),
      hcLight: convertInternalMediaPathToBrowserURI(path.hcLight ?? path.light),
      light: convertInternalMediaPathToBrowserURI(path.light),
      dark: convertInternalMediaPathToBrowserURI(path.dark)
    };
  }
};
$hJ(class extends $gJ {
  constructor() {
    super({
      id: "resetGettingStartedProgress",
      category: localize2(11915, "Developer"),
      title: localize2(11916, "Reset Welcome Page Walkthrough Progress"),
      f1: true,
      metadata: {
        description: localize2(11917, "Reset the progress of all Walkthrough steps on the Welcome Page to make them appear as if they are being viewed for the first time, providing a fresh start to the getting started experience.")
      }
    });
  }
  run(accessor) {
    const gettingStartedService = accessor.get($Yhc);
    const storageService = accessor.get($jv);
    storageService.store(
      $Zhc,
      JSON.stringify([]),
      0,
      0
      /* StorageTarget.USER */
    );
    storageService.store(
      $1hc,
      JSON.stringify([]),
      0,
      0
      /* StorageTarget.USER */
    );
    const memento = new $Slb("gettingStartedService", accessor.get($jv));
    const record = memento.getMemento(
      0,
      0
      /* StorageTarget.USER */
    );
    for (const key2 in record) {
      if (Object.prototype.hasOwnProperty.call(record, key2)) {
        try {
          gettingStartedService.deprogressStep(key2);
        } catch (e) {
          console.error(e);
        }
      }
    }
    memento.saveMemento();
  }
});
$SC(
  $Yhc,
  $2hc,
  1
  /* InstantiationType.Delayed */
);

// out-build/vs/workbench/services/storage/browser/storageService.js
var $5hc_1;
var $5hc = class $5hc2 extends $lv {
  static {
    $5hc_1 = this;
  }
  static {
    this.s = 5 * 1e3;
  }
  // every 5s because async operations are not permitted on shutdown
  get hasPendingUpdate() {
    return Boolean(this.W?.hasPendingUpdate || this.Z?.hasPendingUpdate || this.cb?.hasPendingUpdate);
  }
  constructor(eb, fb, gb) {
    super({ flushInterval: $5hc_1.s });
    this.eb = eb;
    this.fb = fb;
    this.gb = gb;
    this.X = new $gi();
    this.$ = this.fb.currentProfile;
    this.ab = this.B(new $2c());
    this.hb();
  }
  hb() {
    this.B(this.fb.onDidChangeCurrentProfile((e) => e.join(this.R(e.profile))));
  }
  async O() {
    await Promises.settled([
      this.jb(),
      this.kb(this.$),
      this.lb()
    ]);
  }
  async jb() {
    const applicationStorageIndexedDB = await $6hc.createApplicationStorage(this.gb);
    this.W = this.B(applicationStorageIndexedDB);
    this.U = this.B(new $fv(this.W));
    this.B(this.U.onDidChangeStorage((e) => this.u(-1, e)));
    await this.U.init();
    this.mb(this.U);
    this.X.complete({ indexedDb: applicationStorageIndexedDB, storage: this.U });
  }
  async kb(profile) {
    this.ab.clear();
    this.$ = profile;
    if ($mv(this.$)) {
      const { indexedDb: applicationStorageIndexedDB, storage: applicationStorage } = await this.X.p;
      this.Z = applicationStorageIndexedDB;
      this.Y = applicationStorage;
      this.ab.add(this.Y.onDidChangeStorage((e) => this.u(0, e)));
    } else {
      const profileStorageIndexedDB = await $6hc.createProfileStorage(this.$, this.gb);
      this.Z = this.ab.add(profileStorageIndexedDB);
      this.Y = this.ab.add(new $fv(this.Z));
      this.ab.add(this.Y.onDidChangeStorage((e) => this.u(0, e)));
      await this.Y.init();
      this.mb(this.Y);
    }
  }
  async lb() {
    const workspaceStorageIndexedDB = await $6hc.createWorkspaceStorage(this.eb.id, this.gb);
    this.cb = this.B(workspaceStorageIndexedDB);
    this.bb = this.B(new $fv(this.cb));
    this.B(this.bb.onDidChangeStorage((e) => this.u(1, e)));
    await this.bb.init();
    this.mb(this.bb);
  }
  mb(storage) {
    const firstOpen = storage.getBoolean($hv);
    if (firstOpen === void 0) {
      storage.set($hv, true);
    } else if (firstOpen) {
      storage.set($hv, false);
    }
  }
  P(scope) {
    switch (scope) {
      case -1:
        return this.U;
      case 0:
        return this.Y;
      default:
        return this.bb;
    }
  }
  Q(scope) {
    switch (scope) {
      case -1:
        return this.W?.name;
      case 0:
        return this.Z?.name;
      default:
        return this.cb?.name;
    }
  }
  async R(toProfile) {
    if (!this.M(this.$, toProfile)) {
      return;
    }
    const oldProfileStorage = $Kg(this.Y);
    const oldItems = oldProfileStorage.items;
    if (oldProfileStorage !== this.U) {
      await oldProfileStorage.close();
    }
    await this.kb(toProfile);
    this.N(
      oldItems,
      $Kg(this.Y),
      0
      /* StorageScope.PROFILE */
    );
  }
  async S(toWorkspace, preserveData) {
    throw new Error("Migrating storage is currently unsupported in Web");
  }
  r() {
    return $Qj().document.hasFocus() && !this.hasPendingUpdate;
  }
  close() {
    this.U?.close();
    this.Z?.close();
    this.cb?.close();
    this.dispose();
  }
  // --- Start PWB: Clear browser history
  openConnections() {
    if (this.W instanceof $6hc) {
      this.W.pwbOpen();
    }
    if (this.Z instanceof $6hc) {
      this.Z.pwbOpen();
    }
    if (this.cb instanceof $6hc) {
      this.cb.pwbOpen();
    }
  }
  closeConnections() {
    if (this.W instanceof $6hc) {
      this.W.pwbClose();
    }
    if (this.Z instanceof $6hc) {
      this.Z.pwbClose();
    }
    if (this.cb instanceof $6hc) {
      this.cb.pwbClose();
    }
  }
  // --- End PWB: Clear browser history
  async clear() {
    for (const scope of [
      -1,
      0,
      1
      /* StorageScope.WORKSPACE */
    ]) {
      for (const target of [
        0,
        1
        /* StorageTarget.MACHINE */
      ]) {
        for (const key2 of this.keys(scope, target)) {
          this.remove(key2, scope);
        }
      }
      await this.P(scope)?.whenFlushed();
    }
    await Promises.settled([
      this.W?.clear() ?? Promise.resolve(),
      this.Z?.clear() ?? Promise.resolve(),
      this.cb?.clear() ?? Promise.resolve()
    ]);
  }
  hasScope(scope) {
    if ($qs(scope)) {
      return this.$.id === scope.id;
    }
    return this.eb.id === scope.id;
  }
};
$5hc = $5hc_1 = __decorate([
  __param(2, $wn)
], $5hc);
var InMemoryIndexedDBStorageDatabase = class extends $gv {
  constructor() {
    super(...arguments);
    this.hasPendingUpdate = false;
    this.name = "in-memory-indexedb-storage";
  }
  async clear() {
    (await this.getItems()).clear();
  }
  dispose() {
  }
};
var $6hc = class _$6hc extends $3c {
  static async createApplicationStorage(logService) {
    return _$6hc.create({ id: "global", broadcastChanges: true }, logService);
  }
  static async createProfileStorage(profile, logService) {
    return _$6hc.create({ id: `global-${profile.id}`, broadcastChanges: true }, logService);
  }
  static async createWorkspaceStorage(workspaceId, logService) {
    return _$6hc.create({ id: workspaceId }, logService);
  }
  static async create(options3, logService) {
    try {
      const database = new _$6hc(options3, logService);
      await database.h;
      return database;
    } catch (error) {
      logService.error(`[IndexedDB Storage ${options3.id}] create(): ${$1m(error, true)}`);
      return new InMemoryIndexedDBStorageDatabase();
    }
  }
  static {
    this.a = "vscode-web-state-db-";
  }
  static {
    this.b = "ItemTable";
  }
  get hasPendingUpdate() {
    return !!this.g;
  }
  constructor(options3, j) {
    super();
    this.j = j;
    this.c = this.B(new $ze());
    this.onDidChangeItemsExternal = this.c.event;
    this.g = void 0;
    this.name = `${_$6hc.a}${options3.id}`;
    this.f = options3.broadcastChanges ? this.B(new $iZ(this.name)) : void 0;
    this.h = this.n();
    this.m();
  }
  m() {
    if (this.f) {
      this.B(this.f.onDidReceiveData((data) => {
        if ($ev(data)) {
          this.c.fire(data);
        }
      }));
    }
  }
  async n() {
    try {
      return await $$1.create(this.name, void 0, [_$6hc.b]);
    } catch (error) {
      this.j.error(`[IndexedDB Storage ${this.name}] connect() error: ${$1m(error)}`);
      throw error;
    }
  }
  async getItems() {
    const db = await this.h;
    function isValid2(value) {
      return typeof value === "string";
    }
    return db.getKeyValues(_$6hc.b, isValid2);
  }
  async updateItems(request) {
    let didUpdate = false;
    this.g = this.r(request);
    try {
      didUpdate = await this.g;
    } finally {
      this.g = void 0;
    }
    if (this.f && didUpdate) {
      const event = {
        changed: request.insert,
        deleted: request.delete
      };
      this.f.postData(event);
    }
  }
  async r(request) {
    const toInsert = request.insert;
    const toDelete = request.delete;
    if (!toInsert && !toDelete || toInsert?.size === 0 && toDelete?.size === 0) {
      return false;
    }
    const db = await this.h;
    await db.runInTransaction(_$6hc.b, "readwrite", (objectStore) => {
      const requests = [];
      if (toInsert) {
        for (const [key2, value] of toInsert) {
          requests.push(objectStore.put(value, key2));
        }
      }
      if (toDelete) {
        for (const key2 of toDelete) {
          requests.push(objectStore.delete(key2));
        }
      }
      return requests;
    });
    db.pwbAddToSessionSet($$1.PWB_CHANGED_CONNECTION_KEY);
    return true;
  }
  async optimize() {
  }
  // --- Start PWB: Clear browser history
  async pwbOpen() {
    const db = await this.h;
    await db.pwbOpen([_$6hc.b]);
  }
  async pwbClose() {
    const db = await this.h;
    await this.g;
    db.pwbClose();
  }
  // --- End PWB
  async close() {
    const db = await this.h;
    await this.g;
    return db.close();
  }
  async clear() {
    const db = await this.h;
    await db.runInTransaction(_$6hc.b, "readwrite", (objectStore) => objectStore.clear());
    db.pwbAddToSessionSet($$1.PWB_CHANGED_CONNECTION_KEY);
  }
};

// out-build/vs/workbench/contrib/remote/browser/remote.js
var HelpTreeVirtualDelegate = class {
  getHeight(element) {
    return 22;
  }
  getTemplateId(element) {
    return "HelpItemTemplate";
  }
};
var HelpTreeRenderer = class {
  constructor() {
    this.templateId = "HelpItemTemplate";
  }
  renderTemplate(container2) {
    container2.classList.add("remote-help-tree-node-item");
    const icon2 = $bk(container2, $(".remote-help-tree-node-item-icon"));
    const parent = container2;
    return { parent, icon: icon2 };
  }
  renderElement(element, index, templateData, height) {
    const container2 = templateData.parent;
    $bk(container2, templateData.icon);
    templateData.icon.classList.add(...element.element.iconClasses);
    const labelContainer = $bk(container2, $(".help-item-label"));
    labelContainer.innerText = element.element.label;
  }
  disposeTemplate(templateData) {
  }
};
var HelpDataSource = class {
  hasChildren(element) {
    return element instanceof HelpModel;
  }
  getChildren(element) {
    if (element instanceof HelpModel && element.items) {
      return element.items;
    }
    return [];
  }
};
var HelpModel = class {
  constructor(a, b, c, d, f, g, h3, j) {
    this.a = a;
    this.b = b;
    this.c = c;
    this.d = d;
    this.f = f;
    this.g = g;
    this.h = h3;
    this.j = j;
    this.l();
    a.onDidChangeHelpInformation(() => this.l());
  }
  k(info, infoKey) {
    return new HelpItemValue(this.d, this.j, info.extensionDescription, typeof info.remoteName === "string" ? [info.remoteName] : info.remoteName, info.virtualWorkspace, info[infoKey]);
  }
  l() {
    const helpItems = [];
    const getStarted = this.a.helpInformation.filter((info) => info.getStarted);
    if (getStarted.length) {
      const helpItemValues = getStarted.map((info) => this.k(info, "getStarted"));
      const getStartedHelpItem = this.items?.find((item) => item.icon === $lUb) ?? new GetStartedHelpItem($lUb, localize(9112, null), helpItemValues, this.c, this.g, this.b, this.f, this.h, this.d);
      getStartedHelpItem.values = helpItemValues;
      helpItems.push(getStartedHelpItem);
    }
    const documentation = this.a.helpInformation.filter((info) => info.documentation);
    if (documentation.length) {
      const helpItemValues = documentation.map((info) => this.k(info, "documentation"));
      const documentationHelpItem = this.items?.find((item) => item.icon === $mUb) ?? new HelpItem($mUb, localize(9113, null), helpItemValues, this.c, this.g, this.b, this.f, this.h);
      documentationHelpItem.values = helpItemValues;
      helpItems.push(documentationHelpItem);
    }
    const issues = this.a.helpInformation.filter((info) => info.issues);
    if (issues.length) {
      const helpItemValues = issues.map((info) => this.k(info, "issues"));
      const reviewIssuesHelpItem = this.items?.find((item) => item.icon === $oUb) ?? new HelpItem($oUb, localize(9114, null), helpItemValues, this.c, this.g, this.b, this.f, this.h);
      reviewIssuesHelpItem.values = helpItemValues;
      helpItems.push(reviewIssuesHelpItem);
    }
    if (helpItems.length) {
      const helpItemValues = this.a.helpInformation.map((info) => this.k(info, "reportIssue"));
      const issueReporterItem = this.items?.find((item) => item.icon === $pUb) ?? new IssueReporterItem($pUb, localize(9115, null), helpItemValues, this.c, this.g, this.d, this.b, this.f, this.h);
      issueReporterItem.values = helpItemValues;
      helpItems.push(issueReporterItem);
    }
    if (helpItems.length) {
      this.items = helpItems;
    }
  }
};
var HelpItemValue = class {
  constructor(c, d, extensionDescription, remoteAuthority, virtualWorkspace, f) {
    this.c = c;
    this.d = d;
    this.extensionDescription = extensionDescription;
    this.remoteAuthority = remoteAuthority;
    this.virtualWorkspace = virtualWorkspace;
    this.f = f;
  }
  get description() {
    return this.g().then(() => this.b);
  }
  get url() {
    return this.g();
  }
  async g() {
    if (this.a === void 0) {
      if (typeof this.f === "string") {
        const url = URI.parse(this.f);
        if (url.authority) {
          this.a = this.f;
        } else {
          const urlCommand = this.c.executeCommand(this.f).then((result) => {
            this.a = result;
            return this.a;
          });
          const emptyString = new Promise((resolve) => setTimeout(() => resolve(""), 500));
          this.a = await Promise.race([urlCommand, emptyString]);
        }
      } else if (this.f?.id) {
        try {
          const walkthroughId = `${this.extensionDescription.id}#${this.f.id}`;
          const walkthrough = await this.d.getWalkthrough(walkthroughId);
          this.b = walkthrough.title;
          this.a = walkthroughId;
        } catch {
        }
      }
    }
    if (this.a === void 0) {
      this.a = "";
    }
    return this.a;
  }
};
var HelpItemBase = class {
  constructor(icon2, label3, values, a, b, c, d) {
    this.icon = icon2;
    this.label = label3;
    this.values = values;
    this.a = a;
    this.b = b;
    this.c = c;
    this.d = d;
    this.iconClasses = [];
    this.iconClasses.push(...ThemeIcon.asClassNameArray(icon2));
    this.iconClasses.push("remote-help-tree-node-item-icon");
  }
  async f() {
    return (await Promise.all(this.values.map(async (value) => {
      return {
        label: value.extensionDescription.displayName || value.extensionDescription.identifier.value,
        description: await value.description ?? await value.url,
        url: await value.url,
        extensionDescription: value.extensionDescription
      };
    }))).filter((item) => item.description);
  }
  async handleClick() {
    const remoteAuthority = this.b.remoteAuthority;
    if (remoteAuthority) {
      for (let i2 = 0; i2 < this.c.targetType.length; i2++) {
        if (remoteAuthority.startsWith(this.c.targetType[i2])) {
          for (const value of this.values) {
            if (value.remoteAuthority) {
              for (const authority of value.remoteAuthority) {
                if (remoteAuthority.startsWith(authority)) {
                  await this.g(value.extensionDescription, await value.url);
                  return;
                }
              }
            }
          }
        }
      }
    } else {
      const virtualWorkspace = $9S(this.d.getWorkspace())?.scheme;
      if (virtualWorkspace) {
        for (let i2 = 0; i2 < this.c.targetType.length; i2++) {
          for (const value of this.values) {
            if (value.virtualWorkspace && value.remoteAuthority) {
              for (const authority of value.remoteAuthority) {
                if (this.c.targetType[i2].startsWith(authority) && virtualWorkspace.startsWith(value.virtualWorkspace)) {
                  await this.g(value.extensionDescription, await value.url);
                  return;
                }
              }
            }
          }
        }
      }
    }
    if (this.values.length > 1) {
      const actions = await this.f();
      if (actions.length) {
        const action = await this.a.pick(actions, { placeHolder: localize(9116, null) });
        if (action) {
          await this.g(action.extensionDescription, action.url);
        }
      }
    } else {
      await this.g(this.values[0].extensionDescription, await this.values[0].url);
    }
  }
};
var GetStartedHelpItem = class extends HelpItemBase {
  constructor(icon2, label3, values, quickInputService, environmentService, h3, remoteExplorerService, workspaceContextService, j) {
    super(icon2, label3, values, quickInputService, environmentService, remoteExplorerService, workspaceContextService);
    this.h = h3;
    this.j = j;
  }
  async g(extensionDescription, urlOrWalkthroughId) {
    if ([Schemas.http, Schemas.https].includes(URI.parse(urlOrWalkthroughId).scheme)) {
      this.h.open(urlOrWalkthroughId, { allowCommands: true });
      return;
    }
    this.j.executeCommand("workbench.action.openWalkthrough", urlOrWalkthroughId);
  }
};
var HelpItem = class extends HelpItemBase {
  constructor(icon2, label3, values, quickInputService, environmentService, h3, remoteExplorerService, workspaceContextService) {
    super(icon2, label3, values, quickInputService, environmentService, remoteExplorerService, workspaceContextService);
    this.h = h3;
  }
  async g(extensionDescription, url) {
    await this.h.open(URI.parse(url), { allowCommands: true });
  }
};
var IssueReporterItem = class extends HelpItemBase {
  constructor(icon2, label3, values, quickInputService, environmentService, h3, j, remoteExplorerService, workspaceContextService) {
    super(icon2, label3, values, quickInputService, environmentService, remoteExplorerService, workspaceContextService);
    this.h = h3;
    this.j = j;
  }
  async f() {
    return Promise.all(this.values.map(async (value) => {
      return {
        label: value.extensionDescription.displayName || value.extensionDescription.identifier.value,
        description: "",
        url: await value.url,
        extensionDescription: value.extensionDescription
      };
    }));
  }
  async g(extensionDescription, url) {
    if (!url) {
      await this.h.executeCommand("workbench.action.openIssueReporter", [extensionDescription.identifier.value]);
    } else {
      await this.j.open(URI.parse(url));
    }
  }
};
var HelpPanel = class HelpPanel2 extends $_ob {
  static {
    this.ID = "~remote.helpPanel";
  }
  static {
    this.TITLE = localize2(9127, "Help and feedback");
  }
  constructor(b, options3, keybindingService, contextMenuService, contextKeyService, configurationService, instantiationService, viewDescriptorService, openerService, c, f, g, h3, themeService, telemetryService, hoverService, j, m) {
    super(options3, keybindingService, contextMenuService, configurationService, contextKeyService, viewDescriptorService, instantiationService, openerService, themeService, telemetryService, hoverService);
    this.b = b;
    this.c = c;
    this.f = f;
    this.g = g;
    this.h = h3;
    this.j = j;
    this.m = m;
  }
  W(container2) {
    super.W(container2);
    container2.classList.add("remote-help");
    const treeContainer = document.createElement("div");
    treeContainer.classList.add("remote-help-content");
    container2.appendChild(treeContainer);
    this.a = this.Db.createInstance($4eb, "RemoteHelp", treeContainer, new HelpTreeVirtualDelegate(), [new HelpTreeRenderer()], new HelpDataSource(), {
      accessibilityProvider: {
        getAriaLabel: (item) => {
          return item.label;
        },
        getWidgetAriaLabel: () => localize(9117, null)
      }
    });
    const model = new HelpModel(this.b, this.Eb, this.c, this.f, this.g, this.h, this.j, this.m);
    this.a.setInput(model);
    this.B(Event2.debounce(this.a.onDidOpen, (last, event) => event, 75, true)((e) => {
      e.element?.handleClick();
    }));
  }
  X(height, width2) {
    super.X(height, width2);
    this.a.layout(height, width2);
  }
};
HelpPanel = __decorate([
  __param(2, $Ty),
  __param(3, $50),
  __param(4, $on),
  __param(5, $kl),
  __param(6, $Pk),
  __param(7, $$M),
  __param(8, $O4),
  __param(9, $1M),
  __param(10, $sn),
  __param(11, $8Sb),
  __param(12, $US),
  __param(13, $gs),
  __param(14, $zv),
  __param(15, $5$),
  __param(16, $Zk),
  __param(17, $Yhc)
], HelpPanel);
var HelpPanelDescriptor = class {
  constructor(viewModel) {
    this.id = HelpPanel.ID;
    this.name = HelpPanel.TITLE;
    this.canToggleVisibility = true;
    this.hideByDefault = false;
    this.group = "help@50";
    this.order = -10;
    this.ctorDescriptor = new $Nk(HelpPanel, [viewModel]);
  }
};
var RemoteViewPaneContainer = class RemoteViewPaneContainer2 extends $dpb {
  constructor(layoutService, telemetryService, contextService, storageService, configurationService, instantiationService, themeService, contextMenuService, extensionService, Mb, viewDescriptorService) {
    super($HUb, Mb.onDidChangeTargetType, configurationService, layoutService, telemetryService, storageService, instantiationService, themeService, contextMenuService, extensionService, contextService, viewDescriptorService);
    this.Mb = Mb;
    this.Ib = new HelpPanelDescriptor(this);
    this.helpInformation = [];
    this.Jb = new $ze();
    this.onDidChangeHelpInformation = this.Jb.event;
    this.Kb = false;
    this.Bb([this.Ib]);
    this.B(this.Lb = this.bb.createInstance($Rhc));
    this.Mb.onDidChangeHelpInformation((extensions) => {
      this.Nb(extensions);
    });
    this.Nb(this.Mb.helpInformation);
    const viewsRegistry8 = $Wn.as(Extensions5.ViewsRegistry);
    this.Lb.createOptionItems(viewsRegistry8.getViews(this.viewContainer));
    this.B(viewsRegistry8.onViewsRegistered((e) => {
      const remoteViews = [];
      for (const view of e) {
        if (view.viewContainer.id === $HUb) {
          remoteViews.push(...view.views);
        }
      }
      if (remoteViews.length > 0) {
        this.Lb.createOptionItems(remoteViews);
      }
    }));
    this.B(viewsRegistry8.onViewsDeregistered((e) => {
      if (e.viewContainer.id === $HUb) {
        this.Lb.removeOptionItems(e.views);
      }
    }));
  }
  Nb(extensions) {
    const helpInformation = [];
    for (const extension of extensions) {
      this.Ob(extension, helpInformation);
    }
    this.helpInformation = helpInformation;
    this.Jb.fire();
    const viewsRegistry8 = $Wn.as(Extensions5.ViewsRegistry);
    if (this.helpInformation.length && !this.Kb) {
      const view = viewsRegistry8.getView(this.Ib.id);
      if (!view) {
        viewsRegistry8.registerViews([this.Ib], this.viewContainer);
      }
      this.Kb = true;
    } else if (this.Kb) {
      viewsRegistry8.deregisterViews([this.Ib], this.viewContainer);
      this.Kb = false;
    }
  }
  Ob(extension, helpInformation) {
    if (!$zN(extension.description, "contribRemoteHelp")) {
      return;
    }
    if (!extension.value.documentation && !extension.value.getStarted && !extension.value.issues) {
      return;
    }
    helpInformation.push({
      extensionDescription: extension.description,
      getStarted: extension.value.getStarted,
      documentation: extension.value.documentation,
      reportIssue: extension.value.reportIssue,
      issues: extension.value.issues,
      remoteName: extension.value.remoteName,
      virtualWorkspace: extension.value.virtualWorkspace
    });
  }
  Cb(viewDescriptor3) {
    return $Ag(viewDescriptor3.remoteAuthority) ? viewDescriptor3.remoteAuthority[0] : viewDescriptor3.remoteAuthority;
  }
  Db(viewDescriptor3) {
    this.Mb.targetType = $Ag(viewDescriptor3.remoteAuthority) ? viewDescriptor3.remoteAuthority : [viewDescriptor3.remoteAuthority];
  }
  getTitle() {
    const title = localize(9118, null);
    return title;
  }
};
RemoteViewPaneContainer = __decorate([
  __param(0, $Vlb),
  __param(1, $zv),
  __param(2, $Zk),
  __param(3, $jv),
  __param(4, $kl),
  __param(5, $Pk),
  __param(6, $gs),
  __param(7, $50),
  __param(8, $wN),
  __param(9, $8Sb),
  __param(10, $$M)
], RemoteViewPaneContainer);
$Wn.as(Extensions5.ViewContainersRegistry).registerViewContainer(
  {
    id: $HUb,
    title: localize2(9128, "Remote Explorer"),
    ctorDescriptor: new $Nk(RemoteViewPaneContainer),
    hideIfEmpty: true,
    viewOrderDelegate: {
      getOrder: (group2) => {
        if (!group2) {
          return;
        }
        let matches = /^targets@(\d+)$/.exec(group2);
        if (matches) {
          return -1e3;
        }
        matches = /^details(@(\d+))?$/.exec(group2);
        if (matches) {
          return -500 + Number(matches[2]);
        }
        matches = /^help(@(\d+))?$/.exec(group2);
        if (matches) {
          return -10;
        }
        return;
      }
    },
    icon: $qUb,
    order: 4
  },
  0
  /* ViewContainerLocation.Sidebar */
);
var $7hc = class $7hc2 {
  constructor(remoteAgentService, timerService) {
    remoteAgentService.getEnvironment().then((remoteEnv) => {
      if (remoteEnv) {
        timerService.setPerformanceMarks("server", remoteEnv.marks);
      }
    });
  }
};
$7hc = __decorate([
  __param(0, $RL),
  __param(1, $iQb)
], $7hc);
var VisibleProgress = class {
  get lastReport() {
    return this.b;
  }
  constructor(progressService, location3, initialReport, buttons, onDidCancel) {
    this.location = location3;
    this.a = false;
    this.b = initialReport;
    this.c = null;
    this.d = null;
    this.f = null;
    const promise = new Promise((resolve) => this.c = resolve);
    progressService.withProgress({ location: location3, buttons }, (progress) => {
      if (!this.a) {
        this.d = progress;
      }
      return promise;
    }, (choice) => onDidCancel(choice, this.b));
    if (this.b) {
      this.report();
    }
  }
  dispose() {
    this.a = true;
    if (this.c) {
      this.c();
      this.c = null;
    }
    this.d = null;
    if (this.f) {
      this.f.dispose();
      this.f = null;
    }
  }
  report(message) {
    if (message) {
      this.b = message;
    }
    if (this.b && this.d) {
      this.d.report({ message: this.b });
    }
  }
  startTimer(completionTime) {
    this.stopTimer();
    this.f = new ReconnectionTimer(this, completionTime);
  }
  stopTimer() {
    if (this.f) {
      this.f.dispose();
      this.f = null;
    }
  }
};
var ReconnectionTimer = class {
  constructor(parent, completionTime) {
    this.a = parent;
    this.b = completionTime;
    this.c = $kj($Y, () => this.d(), 1e3);
    this.d();
  }
  dispose() {
    this.c.dispose();
  }
  d() {
    const remainingTimeMs = this.b - Date.now();
    if (remainingTimeMs < 0) {
      return;
    }
    const remainingTime = Math.ceil(remainingTimeMs / 1e3);
    if (remainingTime === 1) {
      this.a.report(localize(9119, null, remainingTime));
    } else {
      this.a.report(localize(9120, null, remainingTime));
    }
  }
};
var DISCONNECT_PROMPT_TIME = 40 * 1e3;
var $8hc = class $8hc2 extends $3c {
  constructor(remoteAgentService, progressService, dialogService, commandService, quickInputService, logService, environmentService, telemetryService, storageService) {
    super();
    this.a = false;
    const connection = remoteAgentService.getConnection();
    if (connection) {
      let showProgress2 = function(location3, buttons, initialReport = null) {
        if (visibleProgress) {
          visibleProgress.dispose();
          visibleProgress = null;
        }
        if (!location3) {
          location3 = quickInputVisible ? 15 : 20;
        }
        return new VisibleProgress(progressService, location3, initialReport, buttons.map((button) => button.label), (choice, lastReport) => {
          if (typeof choice !== "undefined" && buttons[choice]) {
            buttons[choice].callback();
          } else {
            if (location3 === 20) {
              visibleProgress = showProgress2(15, buttons, lastReport);
            } else {
              hideProgress2();
            }
          }
        });
      }, hideProgress2 = function() {
        if (visibleProgress) {
          visibleProgress.dispose();
          visibleProgress = null;
        }
      };
      var showProgress = showProgress2, hideProgress = hideProgress2;
      let quickInputVisible = false;
      this.B(quickInputService.onShow(() => quickInputVisible = true));
      this.B(quickInputService.onHide(() => quickInputVisible = false));
      let visibleProgress = null;
      let reconnectWaitEvent = null;
      let disposableListener = null;
      let reconnectionToken = "";
      let lastIncomingDataTime = 0;
      let reconnectionAttempts = 0;
      const reconnectButton = {
        label: localize(9121, null),
        callback: () => {
          reconnectWaitEvent?.skipWait();
        }
      };
      const reloadButton = {
        label: localize(9122, null),
        callback: () => {
          telemetryService.publicLog2("remoteReconnectionReload", {
            remoteName: $9v(environmentService.remoteAuthority),
            reconnectionToken,
            millisSinceLastIncomingData: Date.now() - lastIncomingDataTime,
            attempt: reconnectionAttempts
          });
          commandService.executeCommand($azb.ID);
        }
      };
      connection.onDidStateChange((e) => {
        visibleProgress?.stopTimer();
        if (disposableListener) {
          disposableListener.dispose();
          disposableListener = null;
        }
        switch (e.type) {
          case 0:
            reconnectionToken = e.reconnectionToken;
            lastIncomingDataTime = Date.now() - e.millisSinceLastIncomingData;
            reconnectionAttempts = 0;
            telemetryService.publicLog2("remoteConnectionLost", {
              remoteName: $9v(environmentService.remoteAuthority),
              reconnectionToken: e.reconnectionToken
            });
            if (visibleProgress || e.millisSinceLastIncomingData > DISCONNECT_PROMPT_TIME) {
              if (!visibleProgress) {
                visibleProgress = showProgress2(null, [reconnectButton, reloadButton]);
              }
              visibleProgress.report(localize(9123, null));
            }
            if (storageService instanceof $5hc) {
              storageService.closeConnections();
            }
            break;
          case 1:
            if (visibleProgress) {
              reconnectWaitEvent = e;
              visibleProgress = showProgress2(null, [reconnectButton, reloadButton]);
              visibleProgress.startTimer(Date.now() + 1e3 * e.durationSeconds);
            }
            break;
          case 2:
            reconnectionToken = e.reconnectionToken;
            lastIncomingDataTime = Date.now() - e.millisSinceLastIncomingData;
            reconnectionAttempts = e.attempt;
            telemetryService.publicLog2("remoteReconnectionRunning", {
              remoteName: $9v(environmentService.remoteAuthority),
              reconnectionToken: e.reconnectionToken,
              millisSinceLastIncomingData: e.millisSinceLastIncomingData,
              attempt: e.attempt
            });
            if (visibleProgress || e.millisSinceLastIncomingData > DISCONNECT_PROMPT_TIME) {
              visibleProgress = showProgress2(null, [reloadButton]);
              visibleProgress.report(localize(9124, null));
              disposableListener = quickInputService.onShow(() => {
                if (visibleProgress && visibleProgress.location === 20) {
                  visibleProgress = showProgress2(15, [reloadButton], visibleProgress.lastReport);
                }
              });
            }
            break;
          case 3:
            reconnectionToken = e.reconnectionToken;
            lastIncomingDataTime = Date.now() - e.millisSinceLastIncomingData;
            reconnectionAttempts = e.attempt;
            telemetryService.publicLog2("remoteReconnectionPermanentFailure", {
              remoteName: $9v(environmentService.remoteAuthority),
              reconnectionToken: e.reconnectionToken,
              millisSinceLastIncomingData: e.millisSinceLastIncomingData,
              attempt: e.attempt,
              handled: e.handled
            });
            hideProgress2();
            if (e.handled) {
              logService.info(`Error handled: Not showing a notification for the error.`);
              console.log(`Error handled: Not showing a notification for the error.`);
            } else if (!this.a) {
              this.a = true;
              dialogService.confirm({
                type: severity_default.Error,
                message: localize(9125, null),
                primaryButton: localize(9126, null)
              }).then((result) => {
                if (result.confirmed) {
                  commandService.executeCommand($azb.ID);
                }
              });
            }
            break;
          case 4:
            reconnectionToken = e.reconnectionToken;
            lastIncomingDataTime = Date.now() - e.millisSinceLastIncomingData;
            reconnectionAttempts = e.attempt;
            if (storageService instanceof $5hc) {
              storageService.openConnections();
            }
            telemetryService.publicLog2("remoteConnectionGain", {
              remoteName: $9v(environmentService.remoteAuthority),
              reconnectionToken: e.reconnectionToken,
              millisSinceLastIncomingData: e.millisSinceLastIncomingData,
              attempt: e.attempt
            });
            hideProgress2();
            break;
        }
      });
    }
  }
};
$8hc = __decorate([
  __param(0, $RL),
  __param(1, $TJ),
  __param(2, $Yv),
  __param(3, $sn),
  __param(4, $1M),
  __param(5, $wn),
  __param(6, $US),
  __param(7, $zv),
  __param(8, $jv)
], $8hc);

// out-build/vs/workbench/contrib/remote/browser/remoteIndicator.js
var $9hc_1;
var $9hc = class $9hc2 extends $3c {
  static {
    $9hc_1 = this;
  }
  static {
    this.ID = "workbench.contrib.remoteStatusIndicator";
  }
  static {
    this.b = "workbench.action.remote.showMenu";
  }
  static {
    this.c = "workbench.action.remote.close";
  }
  static {
    this.f = !$r;
  }
  static {
    this.g = "workbench.action.remote.extensions";
  }
  static {
    this.h = 40;
  }
  static {
    this.j = 60 * 1e3;
  }
  static {
    this.m = 10 * 1e3;
  }
  get I() {
    if (!this.H) {
      const remoteExtensionTips = { ...this.db.remoteExtensionTips, ...this.db.virtualWorkspaceExtensionTips };
      this.H = Object.values(remoteExtensionTips).filter((value) => value.startEntry !== void 0).map((value) => {
        return {
          id: value.extensionId,
          installed: false,
          friendlyName: value.friendlyName,
          isPlatformCompatible: false,
          dependencies: [],
          helpLink: value.startEntry?.helpLink ?? "",
          startConnectLabel: value.startEntry?.startConnectLabel ?? "",
          startCommand: value.startEntry?.startCommand ?? "",
          priority: value.startEntry?.priority ?? 10,
          supportedPlatforms: value.supportedPlatforms
        };
      });
      this.I.sort((ext1, ext2) => ext1.priority - ext2.priority);
    }
    return this.H;
  }
  constructor(N, O, P, Q, R, S, U, W, X, Y, Z, $149, ab, bb, cb, db, eb, fb, gb) {
    super();
    this.N = N;
    this.O = O;
    this.P = P;
    this.Q = Q;
    this.R = R;
    this.S = S;
    this.U = U;
    this.W = W;
    this.X = X;
    this.Y = Y;
    this.Z = Z;
    this.$ = $149;
    this.ab = ab;
    this.bb = bb;
    this.cb = cb;
    this.db = db;
    this.eb = eb;
    this.fb = fb;
    this.gb = gb;
    this.r = this.B(this.R.createMenu($bJ.StatusBarWindowIndicatorMenu, this.Q));
    this.s = this.B(this.R.createMenu($bJ.StatusBarRemoteIndicatorMenu, this.Q));
    this.u = this.O.remoteAuthority;
    this.w = void 0;
    this.y = void 0;
    this.z = void 0;
    this.C = new $nn("remoteConnectionState", "").bindTo(this.Q);
    this.D = void 0;
    this.F = void 0;
    this.G = /* @__PURE__ */ Object.create(null);
    this.H = void 0;
    this.J = false;
    this.L = this.B(new $ze());
    this.M = this.L.event;
    if (this.u) {
      this.y = "initializing";
      this.C.set(this.y);
    } else {
      this.kb();
    }
    this.hb();
    this.ib();
    this.lb();
    this.tb();
  }
  hb() {
    const category8 = localize2(9188, "Remote");
    const that = this;
    this.B($hJ(class extends $gJ {
      constructor() {
        super({
          id: $9hc_1.b,
          category: category8,
          title: localize2(9189, "Show Remote Menu"),
          f1: true,
          keybinding: {
            weight: 200,
            primary: 2048 | 512 | 45
          }
        });
        this.run = () => that.zb();
      }
    }));
    if ($9hc_1.f) {
      this.B($hJ(class extends $gJ {
        constructor() {
          super({
            id: $9hc_1.c,
            category: category8,
            title: localize2(9190, "Close Remote Connection"),
            f1: true,
            precondition: $7m.or($kpb, $lpb)
          });
          this.run = () => that.Z.openWindow({ forceReuseWindow: true, remoteAuthority: null });
        }
      }));
      if (this.u) {
        $dJ.appendMenuItem($bJ.MenubarFileMenu, {
          group: "6_close",
          command: {
            id: $9hc_1.c,
            title: localize(9168, null)
          },
          order: 3.5
        });
      }
    }
    if (this.bb.isEnabled()) {
      this.B($hJ(class extends $gJ {
        constructor() {
          super({
            id: $9hc_1.g,
            category: category8,
            title: localize2(9191, "Install Remote Development Extensions"),
            f1: true
          });
          this.run = (accessor, input) => {
            const extensionsWorkbenchService = accessor.get($vzb);
            return extensionsWorkbenchService.openSearch(`@recommended:remotes`);
          };
        }
      }));
    }
  }
  ib() {
    const updateRemoteActions = () => {
      this.t = void 0;
      this.tb();
    };
    this.B(this.r.onDidChange(updateRemoteActions));
    this.B(this.s.onDidChange(updateRemoteActions));
    this.B(this.P.onDidChangeFormatters(() => this.tb()));
    const remoteIndicator = this.O.options?.windowIndicator;
    if (remoteIndicator && remoteIndicator.onDidChange) {
      this.B(remoteIndicator.onDidChange(() => this.tb()));
    }
    if (this.u) {
      const connection = this.X.getConnection();
      if (connection) {
        this.B(connection.onDidStateChange((e) => {
          switch (e.type) {
            case 0:
            case 2:
            case 1:
              this.mb("reconnecting");
              break;
            case 3:
              this.mb("disconnected");
              break;
            case 4:
              this.mb("connected");
              break;
          }
        }));
      }
    } else {
      this.B(this.$.onDidChangeWorkbenchState(() => {
        this.kb();
        this.tb();
      }));
    }
    if ($r) {
      this.B(Event2.any(this.B(new $9Z($Y, "online")).event, this.B(new $9Z($Y, "offline")).event)(() => this.pb(navigator.onLine ? "online" : "offline")));
    }
    this.B(this.W.onDidChangeExtensions(async (result) => {
      for (const ext of result.added) {
        const index = this.I.findIndex((value) => $5z.equals(value.id, ext.identifier));
        if (index > -1) {
          this.I[index].installed = true;
        }
      }
    }));
    this.B(this.eb.onDidUninstallExtension(async (result) => {
      const index = this.I.findIndex((value) => $5z.equals(value.id, result.identifier.id));
      if (index > -1) {
        this.I[index].installed = false;
      }
    }));
  }
  async jb() {
    if (this.J) {
      return;
    }
    const currentPlatform = $k($x);
    for (let i2 = 0; i2 < this.I.length; i2++) {
      const extensionId = this.I[i2].id;
      const supportedPlatforms = this.I[i2].supportedPlatforms;
      const isInstalled = (await this.eb.getInstalled()).find((value) => $5z.equals(value.identifier.id, extensionId)) ? true : false;
      this.I[i2].installed = isInstalled;
      if (isInstalled) {
        this.I[i2].isPlatformCompatible = true;
      } else if (supportedPlatforms && !supportedPlatforms.includes(currentPlatform)) {
        this.I[i2].isPlatformCompatible = false;
      } else {
        this.I[i2].isPlatformCompatible = true;
      }
    }
    this.J = true;
    this.L.fire();
    this.tb();
  }
  kb() {
    this.w = $9S(this.$.getWorkspace());
  }
  async lb() {
    await this.W.whenInstalledExtensionsRegistered();
    const remoteAuthority = this.u;
    if (remoteAuthority) {
      (async () => {
        try {
          const { authority } = await this.Y.resolveAuthority(remoteAuthority);
          this.z = authority.connectionToken;
          this.mb("connected");
        } catch (error) {
          this.mb("disconnected");
        }
      })();
    }
    this.tb();
    this.jb();
  }
  mb(newState) {
    if (this.y !== newState) {
      this.y = newState;
      if (this.y === "reconnecting") {
        this.C.set("disconnected");
      } else {
        this.C.set(this.y);
      }
      this.tb();
      if (newState === "connected") {
        this.nb();
      }
    }
  }
  nb() {
    if (!this.u || // only when having a remote connection
    this.F) {
      return;
    }
    this.F = this.B(new $8h(() => this.ob(), $9hc_1.j));
    this.F.schedule($9hc_1.m);
  }
  async ob() {
    if (this.Z.hasFocus && this.D !== "offline") {
      const measurement = await $SL.measure(this.X);
      if (measurement) {
        if (measurement.high) {
          this.pb("high-latency");
        } else if (this.D === "high-latency") {
          this.pb("online");
        }
      }
    }
    this.F?.schedule();
  }
  pb(newState) {
    if (this.D !== newState) {
      const oldState = this.D;
      this.D = newState;
      if (newState === "high-latency") {
        this.ab.warn(`Remote network connection appears to have high latency (${$SL.latency?.current?.toFixed(2)}ms last, ${$SL.latency?.average?.toFixed(2)}ms average)`);
      }
      if (this.z) {
        if (newState === "online" && oldState === "high-latency") {
          this.qb(this.z, "good");
        } else if (newState === "high-latency" && oldState === "online") {
          this.qb(this.z, "poor");
        }
      }
      this.tb();
    }
  }
  qb(connectionToken, connectionHealth) {
    this.cb.publicLog2("remoteConnectionHealth", {
      remoteName: $9v(this.u),
      reconnectionToken: connectionToken,
      connectionHealth
    });
  }
  rb(group2) {
    if (!group2.match(/^(remote|virtualfs)_(\d\d)_(([a-z][a-z0-9+.-]*)_(.*))$/)) {
      if (!this.G[group2]) {
        this.G[group2] = true;
        this.ab.warn(`Invalid group name used in "statusBar/remoteIndicator" menu contribution: ${group2}. Entries ignored. Expected format: 'remote_$ORDER_$REMOTENAME_$GROUPING or 'virtualfs_$ORDER_$FILESCHEME_$GROUPING.`);
      }
      return false;
    }
    return true;
  }
  sb(doNotUseCache) {
    if (!this.t || doNotUseCache) {
      this.t = this.s.getActions().filter((a) => this.rb(a[0])).concat(this.r.getActions());
    }
    return this.t;
  }
  tb() {
    const remoteIndicator = this.O.options?.windowIndicator;
    if (remoteIndicator) {
      let remoteIndicatorLabel = remoteIndicator.label.trim();
      if (!remoteIndicatorLabel.startsWith("$(")) {
        remoteIndicatorLabel = `$(remote) ${remoteIndicatorLabel}`;
      }
      this.ub($Cf(remoteIndicatorLabel, $9hc_1.h), remoteIndicator.tooltip, remoteIndicator.command);
      return;
    }
    if (this.u) {
      const hostLabel = this.P.getHostLabel(Schemas.vscodeRemote, this.u) || this.u;
      switch (this.y) {
        case "initializing":
          this.ub(
            localize(9169, null),
            localize(9170, null),
            void 0,
            true
            /* progress */
          );
          break;
        case "reconnecting":
          this.ub(
            `${localize(9171, null, $Cf(hostLabel, $9hc_1.h))}`,
            void 0,
            void 0,
            true
            /* progress */
          );
          break;
        case "disconnected":
          this.ub(`$(alert) ${localize(9172, null, $Cf(hostLabel, $9hc_1.h))}`);
          break;
        default: {
          const tooltip = new $bm("", { isTrusted: true, supportThemeIcons: true });
          const hostNameTooltip = this.P.getHostTooltip(Schemas.vscodeRemote, this.u);
          if (hostNameTooltip) {
            tooltip.appendMarkdown(hostNameTooltip);
          } else {
            tooltip.appendText(localize(9173, null, hostLabel));
          }
          this.ub(`$(remote) ${$Cf(hostLabel, $9hc_1.h)}`, tooltip);
        }
      }
      return;
    }
    if (this.w) {
      const workspaceLabel = this.P.getHostLabel(this.w.scheme, this.w.authority);
      if (workspaceLabel) {
        const tooltip = new $bm("", { isTrusted: true, supportThemeIcons: true });
        const hostNameTooltip = this.P.getHostTooltip(this.w.scheme, this.w.authority);
        if (hostNameTooltip) {
          tooltip.appendMarkdown(hostNameTooltip);
        } else {
          tooltip.appendText(localize(9174, null, workspaceLabel));
        }
        if (!$r || this.u) {
          tooltip.appendMarkdown("\n\n");
          tooltip.appendMarkdown(localize(9175, null, `command:${$Hzb}`));
        }
        this.ub(`$(remote) ${$Cf(workspaceLabel, $9hc_1.h)}`, tooltip);
        return;
      }
    }
    this.ub(`$(remote)`, localize(9176, null));
    return;
  }
  ub(initialText, initialTooltip, command4, showProgress) {
    const { text: text2, tooltip, ariaLabel } = this.vb(initialText, initialTooltip, showProgress);
    const properties = {
      name: localize(9177, null),
      kind: this.D === "offline" ? "offline" : "remote",
      ariaLabel,
      text: text2,
      showProgress,
      tooltip,
      command: command4 ?? $9hc_1.b
    };
    if (this.n) {
      this.n.update(properties);
    } else {
      this.n = this.N.addEntry(
        properties,
        "status.host",
        0,
        Number.MAX_VALUE
        /* first entry */
      );
    }
  }
  vb(initialText, initialTooltip, showProgress) {
    let text2 = initialText;
    let tooltip = initialTooltip;
    let ariaLabel = $$l(text2);
    function textWithAlert() {
      if (!showProgress && initialText.startsWith("$(remote)")) {
        return initialText.replace("$(remote)", "$(alert)");
      }
      return initialText;
    }
    switch (this.D) {
      case "offline": {
        const offlineMessage = localize(9178, null);
        text2 = textWithAlert();
        tooltip = this.wb(tooltip, offlineMessage);
        ariaLabel = `${ariaLabel}, ${offlineMessage}`;
        break;
      }
      case "high-latency":
        text2 = textWithAlert();
        tooltip = this.wb(tooltip, localize(9179, null, $SL.latency?.current?.toFixed(2), $SL.latency?.average?.toFixed(2)));
        break;
    }
    return { text: text2, tooltip, ariaLabel };
  }
  wb(tooltip, line) {
    let markdownTooltip;
    if (typeof tooltip === "string") {
      markdownTooltip = new $bm(tooltip, { isTrusted: true, supportThemeIcons: true });
    } else {
      markdownTooltip = tooltip ?? new $bm("", { isTrusted: true, supportThemeIcons: true });
    }
    if (markdownTooltip.value.length > 0) {
      markdownTooltip.appendMarkdown("\n\n");
    }
    markdownTooltip.appendMarkdown(line);
    return markdownTooltip;
  }
  async xb(extensionId) {
    const galleryExtension = (await this.bb.getExtensions([{ id: extensionId }], CancellationToken.None))[0];
    await this.eb.installFromGallery(galleryExtension, {
      isMachineScoped: false,
      donotIncludePackAndDependencies: false,
      context: { [$fA]: true }
    });
  }
  async yb(extensionId, startCommand) {
    await $di(async () => {
      const ext = await this.W.getExtension(extensionId);
      if (!ext) {
        throw Error("Failed to find installed remote extension");
      }
      return ext;
    }, 300, 10);
    this.U.executeCommand(startCommand);
    this.cb.publicLog2("workbenchActionExecuted", {
      id: "remoteInstallAndRun",
      detail: extensionId,
      from: "remote indicator"
    });
  }
  zb() {
    const getCategoryLabel = (action) => {
      if (action.item.category) {
        return typeof action.item.category === "string" ? action.item.category : action.item.category.value;
      }
      return void 0;
    };
    const matchCurrentRemote = () => {
      if (this.u) {
        return new RegExp(`^remote_\\d\\d_${$9v(this.u)}_`);
      } else if (this.w) {
        return new RegExp(`^virtualfs_\\d\\d_${this.w.scheme}_`);
      }
      return void 0;
    };
    const computeItems = () => {
      let actionGroups = this.sb(true);
      const items = [];
      const currentRemoteMatcher = matchCurrentRemote();
      if (currentRemoteMatcher) {
        actionGroups = actionGroups.sort((g1, g2) => {
          const isCurrentRemote1 = currentRemoteMatcher.test(g1[0]);
          const isCurrentRemote2 = currentRemoteMatcher.test(g2[0]);
          if (isCurrentRemote1 !== isCurrentRemote2) {
            return isCurrentRemote1 ? -1 : 1;
          }
          if (g1[0] !== "" && g2[0] === "") {
            return -1;
          } else if (g1[0] === "" && g2[0] !== "") {
            return 1;
          }
          return g1[0].localeCompare(g2[0]);
        });
      }
      let lastCategoryName = void 0;
      for (const actionGroup of actionGroups) {
        let hasGroupCategory = false;
        for (const action of actionGroup[1]) {
          if (action instanceof $fJ) {
            if (!hasGroupCategory) {
              const category8 = getCategoryLabel(action);
              if (category8 !== lastCategoryName) {
                items.push({ type: "separator", label: category8 });
                lastCategoryName = category8;
              }
              hasGroupCategory = true;
            }
            const label3 = typeof action.item.title === "string" ? action.item.title : action.item.title.value;
            items.push({
              type: "item",
              id: action.item.id,
              label: label3
            });
          }
        }
      }
      const showExtensionRecommendations = this.gb.getValue("workbench.remoteIndicator.showExtensionRecommendations");
      if (showExtensionRecommendations && this.bb.isEnabled() && this.J) {
        const notInstalledItems = [];
        for (const metadata of this.I) {
          if (!metadata.installed && metadata.isPlatformCompatible) {
            const label3 = metadata.startConnectLabel;
            const buttons = [{
              iconClass: ThemeIcon.asClassName($xCb),
              tooltip: localize(9180, null)
            }];
            notInstalledItems.push({ type: "item", id: metadata.id, label: label3, buttons });
          }
        }
        items.push({
          type: "separator",
          label: localize(9181, null)
        });
        items.push(...notInstalledItems);
      }
      items.push({
        type: "separator"
      });
      const entriesBeforeConfig = items.length;
      if ($9hc_1.f) {
        if (this.u) {
          items.push({
            type: "item",
            id: $9hc_1.c,
            label: localize(9182, null)
          });
          if (this.y === "disconnected") {
            items.push({
              type: "item",
              id: $azb.ID,
              label: localize(9183, null)
            });
          }
        } else if (this.w) {
          items.push({
            type: "item",
            id: $9hc_1.c,
            label: localize(9184, null)
          });
        }
      }
      if (items.length === entriesBeforeConfig) {
        items.pop();
      }
      return items;
    };
    const disposables = new $2c();
    const quickPick = disposables.add(this.S.createQuickPick({ useSeparators: true }));
    quickPick.placeholder = localize(9185, null);
    quickPick.items = computeItems();
    quickPick.sortByLabel = false;
    quickPick.canSelectMany = false;
    disposables.add(Event2.once(quickPick.onDidAccept)(async (_) => {
      const selectedItems = quickPick.selectedItems;
      if (selectedItems.length === 1) {
        const commandId = selectedItems[0].id;
        const remoteExtension = this.I.find((value) => $5z.equals(value.id, commandId));
        if (remoteExtension) {
          quickPick.items = [];
          quickPick.busy = true;
          quickPick.placeholder = localize(9186, null);
          await this.xb(remoteExtension.id);
          quickPick.hide();
          await this.yb(remoteExtension.id, remoteExtension.startCommand);
        } else {
          this.cb.publicLog2("workbenchActionExecuted", {
            id: commandId,
            from: "remote indicator"
          });
          this.U.executeCommand(commandId);
          quickPick.hide();
        }
      }
    }));
    disposables.add(Event2.once(quickPick.onDidTriggerItemButton)(async (e) => {
      const remoteExtension = this.I.find((value) => $5z.equals(value.id, e.item.id));
      if (remoteExtension) {
        await this.fb.open(URI.parse(remoteExtension.helpLink));
      }
    }));
    disposables.add(this.r.onDidChange(() => quickPick.items = computeItems()));
    disposables.add(this.s.onDidChange(() => quickPick.items = computeItems()));
    disposables.add(quickPick.onDidHide(() => disposables.dispose()));
    if (!this.J) {
      quickPick.busy = true;
      this.B(this.M(() => {
        quickPick.busy = false;
        quickPick.items = computeItems();
      }));
    }
    quickPick.show();
  }
};
$9hc = $9hc_1 = __decorate([
  __param(0, $$qb),
  __param(1, $M4),
  __param(2, $ZI),
  __param(3, $on),
  __param(4, $cJ),
  __param(5, $1M),
  __param(6, $sn),
  __param(7, $wN),
  __param(8, $RL),
  __param(9, $bC),
  __param(10, $S4),
  __param(11, $Zk),
  __param(12, $wn),
  __param(13, $pA),
  __param(14, $zv),
  __param(15, $Vu),
  __param(16, $sA),
  __param(17, $O4),
  __param(18, $kl)
], $9hc);
$Wn.as($Ht.Configuration).registerConfiguration({
  ...$UL,
  properties: {
    "workbench.remoteIndicator.showExtensionRecommendations": {
      type: "boolean",
      markdownDescription: localize(9187, null),
      default: true
    }
  }
});

// out-build/vs/workbench/contrib/remote/browser/remoteConnectionHealth.js
var REMOTE_UNSUPPORTED_CONNECTION_CHOICE_KEY = "remote.unsupportedConnectionChoice";
var BANNER_REMOTE_UNSUPPORTED_CONNECTION_DISMISSED_KEY = "workbench.banner.remote.unsupportedConnection.dismissed";
var $0hc = class $0hc2 {
  constructor(a, b, c, d, e, f, g, h3, i2) {
    this.a = a;
    this.b = b;
    this.c = c;
    this.d = d;
    this.e = e;
    this.f = f;
    this.g = g;
    this.h = h3;
    this.i = i2;
    if (this.b.remoteAuthority) {
      this.k();
    }
  }
  async j() {
    let ConnectionChoice;
    (function(ConnectionChoice2) {
      ConnectionChoice2[ConnectionChoice2["Allow"] = 1] = "Allow";
      ConnectionChoice2[ConnectionChoice2["LearnMore"] = 2] = "LearnMore";
      ConnectionChoice2[ConnectionChoice2["Cancel"] = 0] = "Cancel";
    })(ConnectionChoice || (ConnectionChoice = {}));
    const { result, checkboxChecked } = await this.e.prompt({
      type: severity_default.Warning,
      message: localize(9129, null, this.i.nameLong),
      buttons: [
        {
          label: localize(9130, null),
          run: () => 1
          /* ConnectionChoice.Allow */
        },
        {
          label: localize(9131, null),
          run: async () => {
            await this.f.open("https://aka.ms/vscode-remote/faq/old-linux");
            return 2;
          }
        }
      ],
      cancelButton: {
        run: () => 0
        /* ConnectionChoice.Cancel */
      },
      checkbox: {
        label: localize(9132, null)
      }
    });
    if (result === 2) {
      return await this.j();
    }
    const allowed = result === 1;
    if (allowed && checkboxChecked) {
      this.h.store(
        `${REMOTE_UNSUPPORTED_CONNECTION_CHOICE_KEY}.${this.b.remoteAuthority}`,
        allowed,
        0,
        1
        /* StorageTarget.MACHINE */
      );
    }
    return allowed;
  }
  async k() {
    try {
      const environment = await this.a.getRawEnvironment();
      if (environment && environment.isUnsupportedGlibc) {
        let allowed = this.h.getBoolean(
          `${REMOTE_UNSUPPORTED_CONNECTION_CHOICE_KEY}.${this.b.remoteAuthority}`,
          0
          /* StorageScope.PROFILE */
        );
        if (allowed === void 0) {
          allowed = await this.j();
        }
        if (allowed) {
          const bannerDismissedVersion = this.h.get(
            `${BANNER_REMOTE_UNSUPPORTED_CONNECTION_DISMISSED_KEY}`,
            0
            /* StorageScope.PROFILE */
          ) ?? "";
          const shouldShowBanner = bannerDismissedVersion.slice(0, bannerDismissedVersion.lastIndexOf(".")) !== this.i.version.slice(0, this.i.version.lastIndexOf("."));
          if (shouldShowBanner) {
            const actions = [
              {
                label: localize(9133, null),
                href: "https://aka.ms/vscode-remote/faq/old-linux"
              }
            ];
            this.d.show({
              id: "unsupportedGlibcWarning.banner",
              message: localize(9134, null, this.i.nameLong),
              actions,
              icon: $6l.warning,
              closeLabel: `Do not show again in v${this.i.version}`,
              onClose: () => {
                this.h.store(
                  `${BANNER_REMOTE_UNSUPPORTED_CONNECTION_DISMISSED_KEY}`,
                  this.i.version,
                  0,
                  1
                  /* StorageTarget.MACHINE */
                );
              }
            });
          }
        } else {
          this.g.openWindow({ forceReuseWindow: true, remoteAuthority: null });
          return;
        }
      }
      this.c.publicLog2("remoteConnectionSuccess", {
        web: $r,
        connectionTimeMs: await this.a.getConnection()?.getInitialConnectionTimeMs(),
        remoteName: $9v(this.b.remoteAuthority)
      });
      await this.l();
    } catch (err) {
      this.c.publicLog2("remoteConnectionFailure", {
        web: $r,
        connectionTimeMs: await this.a.getConnection()?.getInitialConnectionTimeMs(),
        remoteName: $9v(this.b.remoteAuthority),
        message: err ? err.message : ""
      });
    }
  }
  async l() {
    const measurement = await $SL.measure(this.a);
    if (measurement === void 0) {
      return;
    }
    this.c.publicLog2("remoteConnectionLatency", {
      web: $r,
      remoteName: $9v(this.b.remoteAuthority),
      latencyMs: measurement.current
    });
  }
};
$0hc = __decorate([
  __param(0, $RL),
  __param(1, $US),
  __param(2, $zv),
  __param(3, $jVb),
  __param(4, $Yv),
  __param(5, $O4),
  __param(6, $S4),
  __param(7, $jv),
  __param(8, $Vu)
], $0hc);

// out-build/vs/workbench/contrib/remote/browser/remote.contribution.js
var workbenchContributionsRegistry7 = $Wn.as(Extensions2.Workbench);
$PL(
  $Ohc.ID,
  $Ohc,
  2
  /* WorkbenchPhase.BlockRestore */
);
$PL(
  $Phc.ID,
  $Phc,
  2
  /* WorkbenchPhase.BlockRestore */
);
workbenchContributionsRegistry7.registerWorkbenchContribution(
  $8hc,
  4
  /* LifecyclePhase.Eventually */
);
$PL(
  $9hc.ID,
  $9hc,
  1
  /* WorkbenchPhase.BlockStartup */
);
workbenchContributionsRegistry7.registerWorkbenchContribution(
  $IUb,
  3
  /* LifecyclePhase.Restored */
);
workbenchContributionsRegistry7.registerWorkbenchContribution(
  $JUb,
  4
  /* LifecyclePhase.Eventually */
);
workbenchContributionsRegistry7.registerWorkbenchContribution(
  $KUb,
  4
  /* LifecyclePhase.Eventually */
);
workbenchContributionsRegistry7.registerWorkbenchContribution(
  $7hc,
  4
  /* LifecyclePhase.Eventually */
);
workbenchContributionsRegistry7.registerWorkbenchContribution(
  $0hc,
  3
  /* LifecyclePhase.Restored */
);

// out-build/vs/workbench/contrib/emmet/browser/emmetActions.js
var GrammarContributions = class _GrammarContributions {
  static {
    this.a = {};
  }
  constructor(contributions) {
    if (!Object.keys(_GrammarContributions.a).length) {
      this.b(contributions);
    }
  }
  b(contributions) {
    contributions.forEach((contribution) => {
      contribution.value.forEach((grammar) => {
        if (grammar.language && grammar.scopeName) {
          _GrammarContributions.a[grammar.language] = grammar.scopeName;
        }
      });
    });
  }
  getGrammar(mode) {
    return _GrammarContributions.a[mode];
  }
};
var $$hc = class _$$hc extends $Z5 {
  constructor(opts) {
    super(opts);
    this.h = null;
    this.j = null;
    this.d = opts.actionName;
  }
  static {
    this.e = ["html", "css", "xml", "xsl", "haml", "jade", "jsx", "slim", "scss", "sass", "less", "stylus", "styl", "svg"];
  }
  k(extensionService) {
    if (this.j !== extensionService) {
      this.j = extensionService;
      this.h = extensionService.readExtensionPointContributions($lYb).then((contributions) => {
        return new GrammarContributions(contributions);
      });
    }
    return this.h || Promise.resolve(null);
  }
  run(accessor, editor) {
    const extensionService = accessor.get($wN);
    const commandService = accessor.get($sn);
    return this.k(extensionService).then((grammarContributions) => {
      if (this.id === "editor.emmet.action.expandAbbreviation" && grammarContributions) {
        return commandService.executeCommand("emmet.expandAbbreviation", _$$hc.getLanguage(editor, grammarContributions));
      }
      return void 0;
    });
  }
  static getLanguage(editor, grammars) {
    const model = editor.getModel();
    const selection = editor.getSelection();
    if (!model || !selection) {
      return null;
    }
    const position = selection.getStartPosition();
    model.tokenization.tokenizeIfCheap(position.lineNumber);
    const languageId = model.getLanguageIdAtPosition(position.lineNumber, position.column);
    const syntax = languageId.split(".").pop();
    if (!syntax) {
      return null;
    }
    const checkParentMode = () => {
      const languageGrammar = grammars.getGrammar(syntax);
      if (!languageGrammar) {
        return syntax;
      }
      const languages = languageGrammar.split(".");
      if (languages.length < 2) {
        return syntax;
      }
      for (let i2 = 1; i2 < languages.length; i2++) {
        const language = languages[languages.length - i2];
        if (this.e.indexOf(language) !== -1) {
          return language;
        }
      }
      return syntax;
    };
    return {
      language: syntax,
      parentMode: checkParentMode()
    };
  }
};

// out-build/vs/workbench/contrib/emmet/browser/actions/expandAbbreviation.js
var ExpandAbbreviationAction = class extends $$hc {
  constructor() {
    super({
      id: "editor.emmet.action.expandAbbreviation",
      label: localize2(6336, "Emmet: Expand Abbreviation"),
      precondition: EditorContextKeys.writable,
      actionName: "expand_abbreviation",
      kbOpts: {
        primary: 2,
        kbExpr: $7m.and(EditorContextKeys.editorTextFocus, EditorContextKeys.tabDoesNotMoveFocus, $7m.has("config.emmet.triggerExpansionOnTab")),
        weight: 100
        /* KeybindingWeight.EditorContrib */
      },
      menuOpts: {
        menuId: $bJ.MenubarEditMenu,
        group: "5_insert",
        title: localize(6335, null),
        order: 3
      }
    });
  }
};
$55(ExpandAbbreviationAction);

// out-build/vs/workbench/contrib/codeEditor/browser/accessibility/accessibility.js
var ToggleScreenReaderMode = class extends $gJ {
  constructor() {
    super({
      id: "editor.action.toggleScreenReaderAccessibilityMode",
      title: localize2(5167, "Toggle Screen Reader Accessibility Mode"),
      metadata: {
        description: localize2(5168, "Toggles an optimized mode for usage with screen readers, braille devices, and other assistive technologies.")
      },
      f1: true,
      keybinding: [
        {
          primary: 2048 | 35,
          weight: 200 + 10,
          when: $nsb
        },
        {
          primary: 512 | 59 | 1024,
          linux: {
            primary: 512 | 62 | 1024
            /* KeyMod.Shift */
          },
          weight: 200 + 10
        }
      ]
    });
  }
  async run(accessor) {
    const accessibiiltyService = accessor.get($ND);
    const configurationService = accessor.get($kl);
    const isScreenReaderOptimized = accessibiiltyService.isScreenReaderOptimized();
    configurationService.updateValue(
      "editor.accessibilitySupport",
      isScreenReaderOptimized ? "off" : "on",
      2
      /* ConfigurationTarget.USER */
    );
    $$Z(isScreenReaderOptimized ? AccessibilityHelpNLS.screenReaderModeDisabled : AccessibilityHelpNLS.screenReaderModeEnabled);
  }
};
$hJ(ToggleScreenReaderMode);

// out-build/vs/workbench/contrib/accessibility/browser/editorAccessibilityHelp.js
var $_hc = class extends $3c {
  constructor() {
    super();
    this.B($uSb.addImplementation(90, "editor", async (accessor) => {
      const codeEditorService = accessor.get($U5);
      const accessibleViewService = accessor.get($shb);
      const instantiationService = accessor.get($Pk);
      const commandService = accessor.get($sn);
      let codeEditor = codeEditorService.getActiveCodeEditor() || codeEditorService.getFocusedCodeEditor();
      if (!codeEditor) {
        await commandService.executeCommand($Xtb);
        codeEditor = codeEditorService.getActiveCodeEditor();
      }
      accessibleViewService.show(instantiationService.createInstance(EditorAccessibilityHelpProvider, codeEditor));
    }));
  }
};
var EditorAccessibilityHelpProvider = class EditorAccessibilityHelpProvider2 extends $3c {
  onClose() {
    this.a.focus();
  }
  constructor(a, b, c) {
    super();
    this.a = a;
    this.b = b;
    this.c = c;
    this.id = "editor";
    this.options = { type: "help", readMoreUrl: "https://go.microsoft.com/fwlink/?linkid=851010" };
    this.verbositySettingKey = "accessibility.verbosity.editor";
  }
  provideContent() {
    const options3 = this.a.getOptions();
    const content = [];
    if (options3.get(
      63
      /* EditorOption.inDiffEditor */
    )) {
      if (options3.get(
        96
        /* EditorOption.readOnly */
      )) {
        content.push(AccessibilityHelpNLS.readonlyDiffEditor);
      } else {
        content.push(AccessibilityHelpNLS.editableDiffEditor);
      }
    } else {
      if (options3.get(
        96
        /* EditorOption.readOnly */
      )) {
        content.push(AccessibilityHelpNLS.readonlyEditor);
      } else {
        content.push(AccessibilityHelpNLS.editableEditor);
      }
    }
    content.push(AccessibilityHelpNLS.listSignalSounds);
    content.push(AccessibilityHelpNLS.listAlerts);
    const chatCommandInfo = $bic(this.b, this.c);
    if (chatCommandInfo) {
      content.push(chatCommandInfo);
    }
    const commentCommandInfo = $aic(this.b, this.c, this.a);
    if (commentCommandInfo) {
      content.push(commentCommandInfo);
    }
    if (options3.get(
      120
      /* EditorOption.stickyScroll */
    ).enabled) {
      content.push(AccessibilityHelpNLS.stickScroll);
    }
    if (options3.get(
      150
      /* EditorOption.tabFocusMode */
    )) {
      content.push(AccessibilityHelpNLS.tabFocusModeOnMsg);
    } else {
      content.push(AccessibilityHelpNLS.tabFocusModeOffMsg);
    }
    content.push(AccessibilityHelpNLS.codeFolding);
    content.push(AccessibilityHelpNLS.intellisense);
    content.push(AccessibilityHelpNLS.showOrFocusHover);
    content.push(AccessibilityHelpNLS.goToSymbol);
    content.push(AccessibilityHelpNLS.startDebugging);
    content.push(AccessibilityHelpNLS.setBreakpoint);
    content.push(AccessibilityHelpNLS.debugExecuteSelection);
    content.push(AccessibilityHelpNLS.addToWatch);
    return content.join("\n");
  }
};
EditorAccessibilityHelpProvider = __decorate([
  __param(1, $Ty),
  __param(2, $on)
], EditorAccessibilityHelpProvider);
function $aic(keybindingService, contextKeyService, editor) {
  const editorContext = contextKeyService.getContext(editor.getDomNode());
  if (editorContext.getValue(CommentContextKeys.activeEditorHasCommentingRange.key)) {
    return [CommentAccessibilityHelpNLS.intro, CommentAccessibilityHelpNLS.addComment, CommentAccessibilityHelpNLS.nextCommentThread, CommentAccessibilityHelpNLS.previousCommentThread, CommentAccessibilityHelpNLS.nextRange, CommentAccessibilityHelpNLS.previousRange].join("\n");
  }
  return;
}
function $bic(keybindingService, contextKeyService) {
  if (ChatContextKeys.enabled.getValue(contextKeyService)) {
    return [AccessibilityHelpNLS.quickChat, AccessibilityHelpNLS.startInlineChat].join("\n");
  }
  return;
}

// out-build/vs/workbench/contrib/codeEditor/browser/diffEditorAccessibilityHelp.js
var $cic = class {
  constructor() {
    this.priority = 105;
    this.name = "diff-editor";
    this.when = $an.create("isInDiffEditor", true);
    this.type = "help";
  }
  getProvider(accessor) {
    const editorService = accessor.get($mJ);
    const codeEditorService = accessor.get($U5);
    const keybindingService = accessor.get($Ty);
    const contextKeyService = accessor.get($on);
    if (!(editorService.activeTextEditorControl instanceof $c_)) {
      return;
    }
    const codeEditor = codeEditorService.getActiveCodeEditor() || codeEditorService.getFocusedCodeEditor();
    if (!codeEditor) {
      return;
    }
    const switchSides = localize(5174, null, "<keybinding:diffEditor.switchSide>");
    const diffEditorActiveAnnouncement = localize(5175, null);
    const keys = ["accessibility.signals.diffLineDeleted", "accessibility.signals.diffLineInserted", "accessibility.signals.diffLineModified"];
    const content = [
      localize(5176, null),
      localize(5177, null, "<keybinding:" + $m_.id + ">", "<keybinding:" + $n_.id + ">"),
      switchSides,
      diffEditorActiveAnnouncement,
      localize(5178, null, keys.join(", "))
    ];
    const commentCommandInfo = $aic(keybindingService, contextKeyService, codeEditor);
    if (commentCommandInfo) {
      content.push(commentCommandInfo);
    }
    return new $thb(
      "diffEditor",
      {
        type: "help"
        /* AccessibleViewType.Help */
      },
      () => content.join("\n"),
      () => codeEditor.focus(),
      "accessibility.verbosity.diffEditor"
      /* AccessibilityVerbositySettingId.DiffEditor */
    );
  }
};

// out-build/vs/workbench/contrib/codeEditor/browser/diffEditorHelper.js
var DiffEditorHelperContribution = class DiffEditorHelperContribution2 extends $3c {
  static {
    this.ID = "editor.contrib.diffEditorHelper";
  }
  constructor(a, b, c, f) {
    super();
    this.a = a;
    this.b = b;
    this.c = c;
    this.f = f;
    const isEmbeddedDiffEditor = this.a instanceof $zEb;
    if (!isEmbeddedDiffEditor) {
      const computationResult = $Dd(this, (e) => this.a.onDidUpdateDiff(e), () => (
        /** @description diffEditor.diffComputationResult */
        this.a.getDiffComputationResult()
      ));
      const onlyWhiteSpaceChange = computationResult.map((r2) => r2 && !r2.identical && r2.changes2.length === 0);
      this.B($xd((reader, store) => {
        if (onlyWhiteSpaceChange.read(reader)) {
          const helperWidget = store.add(this.b.createInstance($CLb, this.a.getModifiedEditor(), localize(5179, null), null));
          store.add(helperWidget.onClick(() => {
            this.c.updateValue(this.a.getModel().modified.uri, "diffEditor.ignoreTrimWhitespace", false);
          }));
          helperWidget.render();
        }
      }));
      this.B(this.a.onDidUpdateDiff(() => {
        const diffComputationResult = this.a.getDiffComputationResult();
        if (diffComputationResult && diffComputationResult.quitEarly) {
          this.f.prompt(Severity2.Warning, localize(5180, null, this.a.maxComputationTime), [{
            label: localize(5181, null),
            run: () => {
              this.c.updateValue(this.a.getModel().modified.uri, "diffEditor.maxComputationTime", 0);
            }
          }], {});
        }
      }));
    }
  }
};
DiffEditorHelperContribution = __decorate([
  __param(1, $Pk),
  __param(2, $zG),
  __param(3, $PJ)
], DiffEditorHelperContribution);
$95(DiffEditorHelperContribution.ID, DiffEditorHelperContribution);
$Wn.as($YL.ConfigurationMigration).registerConfigurationMigrations([{
  key: "diffEditor.experimental.collapseUnchangedRegions",
  migrateFn: (value, accessor) => {
    return [
      ["diffEditor.hideUnchangedRegions.enabled", { value }],
      ["diffEditor.experimental.collapseUnchangedRegions", { value: void 0 }]
    ];
  }
}]);
$vhb.register(new $cic());

// out-build/vs/workbench/contrib/codeEditor/browser/editorFeatures.js
var EditorFeaturesInstantiator = class EditorFeaturesInstantiator2 extends $3c {
  static {
    this.ID = "workbench.contrib.editorFeaturesInstantiator";
  }
  constructor(codeEditorService, b) {
    super();
    this.b = b;
    this.a = false;
    this.B(codeEditorService.onWillCreateCodeEditor(() => this.c()));
    this.B(codeEditorService.onWillCreateDiffEditor(() => this.c()));
    if (codeEditorService.listCodeEditors().length > 0 || codeEditorService.listDiffEditors().length > 0) {
      this.c();
    }
  }
  c() {
    if (this.a) {
      return;
    }
    this.a = true;
    const editorFeatures2 = $U_();
    for (const feature of editorFeatures2) {
      try {
        const instance2 = this.b.createInstance(feature);
        if (typeof instance2.dispose === "function") {
          this.B(instance2);
        }
      } catch (err) {
        $gb(err);
      }
    }
  }
};
EditorFeaturesInstantiator = __decorate([
  __param(0, $U5),
  __param(1, $Pk)
], EditorFeaturesInstantiator);
$PL(
  EditorFeaturesInstantiator.ID,
  EditorFeaturesInstantiator,
  2
  /* WorkbenchPhase.BlockRestore */
);

// out-build/vs/workbench/contrib/codeEditor/browser/editorSettingsMigration.js
$Wn.as($YL.ConfigurationMigration).registerConfigurationMigrations($74.items.map((item) => ({
  key: `editor.${item.key}`,
  migrateFn: (value, accessor) => {
    const configurationKeyValuePairs = [];
    const writer = (key2, value2) => configurationKeyValuePairs.push([`editor.${key2}`, { value: value2 }]);
    item.migrate(value, (key2) => accessor(`editor.${key2}`), writer);
    return configurationKeyValuePairs;
  }
})));

// out-build/vs/workbench/contrib/codeEditor/browser/inspectKeybindings.js
var InspectKeyMap = class extends $gJ {
  constructor() {
    super({
      id: "workbench.action.inspectKeyMappings",
      title: localize2(5202, "Inspect Key Mappings"),
      category: $qn.Developer,
      f1: true
    });
  }
  run(accessor, editor) {
    const keybindingService = accessor.get($Ty);
    const editorService = accessor.get($mJ);
    editorService.openEditor({ resource: void 0, contents: keybindingService._dumpDebugInfo(), options: { pinned: true } });
  }
};
$hJ(InspectKeyMap);
var InspectKeyMapJSON = class extends $gJ {
  constructor() {
    super({
      id: "workbench.action.inspectKeyMappingsJSON",
      title: localize2(5203, "Inspect Key Mappings (JSON)"),
      category: $qn.Developer,
      f1: true
    });
  }
  async run(accessor) {
    const editorService = accessor.get($mJ);
    const keybindingService = accessor.get($Ty);
    await editorService.openEditor({ resource: void 0, contents: keybindingService._dumpDebugInfoJSON(), options: { pinned: true } });
  }
};
$hJ(InspectKeyMapJSON);

// out-build/vs/workbench/contrib/codeEditor/browser/largeFileOptimizations.js
var $dic = class $dic2 extends $3c {
  static {
    this.ID = "editor.contrib.largeFileOptimizationsWarner";
  }
  constructor(a, b, c) {
    super();
    this.a = a;
    this.b = b;
    this.c = c;
    this.B(this.a.onDidChangeModel((e) => this.f()));
    this.f();
  }
  f() {
    const model = this.a.getModel();
    if (!model) {
      return;
    }
    if (model.isTooLargeForTokenization()) {
      const message = localize(5204, null, $rc(model.uri.path));
      this.b.prompt(Severity2.Info, message, [
        {
          label: localize(5205, null),
          run: () => {
            this.c.updateValue(`editor.largeFileOptimizations`, false).then(() => {
              this.b.info(localize(5206, null));
            }, (err) => {
              this.b.error(err);
            });
          }
        }
      ], { neverShowAgain: { id: "editor.contrib.largeFileOptimizationsWarner" } });
    }
  }
};
$dic = __decorate([
  __param(1, $PJ),
  __param(2, $kl)
], $dic);
$85(
  $dic.ID,
  $dic,
  1
  /* EditorContributionInstantiation.AfterFirstRender */
);

// out-build/vs/workbench/contrib/codeEditor/browser/quickaccess/gotoLineQuickAccess.js
var $eic = class $eic2 extends $0_b {
  constructor(t, u, v) {
    super();
    this.t = t;
    this.u = u;
    this.v = v;
    this.h = this.t.onDidActiveEditorChange;
  }
  get w() {
    const editorConfig = this.v.getValue().workbench?.editor;
    return {
      openEditorPinned: !editorConfig?.enablePreviewFromQuickOpen || !editorConfig?.enablePreview
    };
  }
  get i() {
    return this.t.activeTextEditorControl;
  }
  f(context, options3) {
    if ((options3.keyMods.alt || this.w.openEditorPinned && options3.keyMods.ctrlCmd || options3.forceSideBySide) && this.t.activeEditor) {
      context.restoreViewState?.();
      const editorOptions2 = {
        selection: options3.range,
        pinned: options3.keyMods.ctrlCmd || this.w.openEditorPinned,
        preserveFocus: options3.preserveFocus
      };
      this.u.sideGroup.openEditor(this.t.activeEditor, editorOptions2);
    } else {
      super.f(context, options3);
    }
  }
};
$eic = __decorate([
  __param(0, $mJ),
  __param(1, $iJ),
  __param(2, $kl)
], $eic);
var GotoLineAction = class _GotoLineAction extends $gJ {
  static {
    this.ID = "workbench.action.gotoLine";
  }
  constructor() {
    super({
      id: _GotoLineAction.ID,
      title: localize2(5214, "Go to Line/Column..."),
      f1: true,
      keybinding: {
        weight: 200,
        when: null,
        primary: 2048 | 37,
        mac: {
          primary: 256 | 37
          /* KeyCode.KeyG */
        }
      }
    });
  }
  async run(accessor) {
    accessor.get($1M).quickAccess.show($eic.PREFIX);
  }
};
$hJ(GotoLineAction);
$Wn.as($CM.Quickaccess).registerQuickAccessProvider({
  ctor: $eic,
  prefix: $0_b.PREFIX,
  placeholder: localize(5212, null),
  helpEntries: [{ description: localize(5213, null), commandId: GotoLineAction.ID }]
});

// out-build/vs/workbench/contrib/format/browser/formatModified.js
$55(class FormatModifiedAction extends $Z5 {
  constructor() {
    super({
      id: "editor.action.formatChanges",
      label: localize2(7459, "Format Modified Lines"),
      precondition: $7m.and(EditorContextKeys.writable, EditorContextKeys.hasDocumentSelectionFormattingProvider)
    });
  }
  async run(accessor, editor) {
    const instaService = accessor.get($Pk);
    if (!editor.hasModel()) {
      return;
    }
    const ranges = await instaService.invokeFunction($fic, editor.getModel());
    if ($Qb(ranges)) {
      return instaService.invokeFunction($chb, editor, ranges, 1, $VJ.None, CancellationToken.None, true);
    }
  }
});
async function $fic(accessor, modified) {
  const quickDiffService = accessor.get($AEb);
  const workerService = accessor.get($I0);
  const modelService = accessor.get($oG);
  const original = await $PEb(quickDiffService, modified.uri, modified.getLanguageId(), $kG(modified));
  if (!original) {
    return null;
  }
  const ranges = [];
  const ref = await modelService.createModelReference(original);
  try {
    if (!workerService.canComputeDirtyDiff(original, modified.uri)) {
      return void 0;
    }
    const changes = await workerService.computeDirtyDiff(original, modified.uri, false);
    if (!$Qb(changes)) {
      return void 0;
    }
    for (const change of changes) {
      ranges.push(modified.validateRange(new $9C(change.modifiedStartLineNumber, 1, change.modifiedEndLineNumber || change.modifiedStartLineNumber, Number.MAX_SAFE_INTEGER)));
    }
  } finally {
    ref.dispose();
  }
  return ranges;
}

// out-build/vs/workbench/contrib/codeEditor/browser/saveParticipants.js
var $gic = class $gic2 {
  constructor(c, d) {
    this.c = c;
    this.d = d;
  }
  async participate(model, context) {
    if (!model.textEditorModel) {
      return;
    }
    const trimTrailingWhitespaceOption = this.c.getValue("files.trimTrailingWhitespace", { overrideIdentifier: model.textEditorModel.getLanguageId(), resource: model.resource });
    const trimInRegexAndStrings = this.c.getValue("files.trimTrailingWhitespaceInRegexAndStrings", { overrideIdentifier: model.textEditorModel.getLanguageId(), resource: model.resource });
    if (trimTrailingWhitespaceOption) {
      this.e(model.textEditorModel, context.reason === 2, trimInRegexAndStrings);
    }
  }
  e(model, isAutoSaved, trimInRegexesAndStrings) {
    let prevSelection = [];
    let cursors = [];
    const editor = findEditor(model, this.d);
    if (editor) {
      prevSelection = editor.getSelections();
      if (isAutoSaved) {
        cursors = prevSelection.map((s) => s.getPosition());
        const snippetsRange = $Dcb.get(editor)?.getSessionEnclosingRange();
        if (snippetsRange) {
          for (let lineNumber = snippetsRange.startLineNumber; lineNumber <= snippetsRange.endLineNumber; lineNumber++) {
            cursors.push(new $8C(lineNumber, model.getLineMaxColumn(lineNumber)));
          }
        }
      }
    }
    const ops = $5ib(model, cursors, trimInRegexesAndStrings);
    if (!ops.length) {
      return;
    }
    model.pushEditOperations(prevSelection, ops, (_edits) => prevSelection);
  }
};
$gic = __decorate([
  __param(0, $kl),
  __param(1, $U5)
], $gic);
function findEditor(model, codeEditorService) {
  let candidate = null;
  if (model.isAttachedToEditor()) {
    for (const editor of codeEditorService.listCodeEditors()) {
      if (editor.hasModel() && editor.getModel() === model) {
        if (editor.hasTextFocus()) {
          return editor;
        }
        candidate = editor;
      }
    }
  }
  return candidate;
}
var $hic = class $hic2 {
  constructor(c, d) {
    this.c = c;
    this.d = d;
  }
  async participate(model, context) {
    if (!model.textEditorModel) {
      return;
    }
    if (this.c.getValue("files.insertFinalNewline", { overrideIdentifier: model.textEditorModel.getLanguageId(), resource: model.resource })) {
      this.e(model.textEditorModel);
    }
  }
  e(model) {
    const lineCount = model.getLineCount();
    const lastLine = model.getLineContent(lineCount);
    const lastLineIsEmptyOrWhitespace = $Qf(lastLine) === -1;
    if (!lineCount || lastLineIsEmptyOrWhitespace) {
      return;
    }
    const edits = [$bD.insert(new $8C(lineCount, model.getLineMaxColumn(lineCount)), model.getEOL())];
    const editor = findEditor(model, this.d);
    if (editor) {
      editor.executeEdits("insertFinalNewLine", edits, editor.getSelections());
    } else {
      model.pushEditOperations([], edits, () => null);
    }
  }
};
$hic = __decorate([
  __param(0, $kl),
  __param(1, $U5)
], $hic);
var $iic = class $iic2 {
  constructor(c, d) {
    this.c = c;
    this.d = d;
  }
  async participate(model, context) {
    if (!model.textEditorModel) {
      return;
    }
    if (this.c.getValue("files.trimFinalNewlines", { overrideIdentifier: model.textEditorModel.getLanguageId(), resource: model.resource })) {
      this.f(
        model.textEditorModel,
        context.reason === 2
        /* SaveReason.AUTO */
      );
    }
  }
  /**
   * returns 0 if the entire file is empty
   */
  e(model) {
    for (let lineNumber = model.getLineCount(); lineNumber >= 1; lineNumber--) {
      const lineLength = model.getLineLength(lineNumber);
      if (lineLength > 0) {
        return lineNumber;
      }
    }
    return 0;
  }
  f(model, isAutoSaved) {
    const lineCount = model.getLineCount();
    if (lineCount === 1) {
      return;
    }
    let prevSelection = [];
    let cannotTouchLineNumber = 0;
    const editor = findEditor(model, this.d);
    if (editor) {
      prevSelection = editor.getSelections();
      if (isAutoSaved) {
        for (let i2 = 0, len = prevSelection.length; i2 < len; i2++) {
          const positionLineNumber = prevSelection[i2].positionLineNumber;
          if (positionLineNumber > cannotTouchLineNumber) {
            cannotTouchLineNumber = positionLineNumber;
          }
        }
      }
    }
    const lastNonEmptyLine = this.e(model);
    const deleteFromLineNumber = Math.max(lastNonEmptyLine + 1, cannotTouchLineNumber + 1);
    const deletionRange = model.validateRange(new $9C(deleteFromLineNumber, 1, lineCount, model.getLineMaxColumn(lineCount)));
    if (deletionRange.isEmpty()) {
      return;
    }
    model.pushEditOperations(prevSelection, [$bD.delete(deletionRange)], (_edits) => prevSelection);
    editor?.setSelections(prevSelection);
  }
};
$iic = __decorate([
  __param(0, $kl),
  __param(1, $U5)
], $iic);
var FormatOnSaveParticipant3 = class FormatOnSaveParticipant4 {
  constructor(c, d, e) {
    this.c = c;
    this.d = d;
    this.e = e;
  }
  async participate(model, context, progress, token) {
    if (!model.textEditorModel) {
      return;
    }
    if (context.reason === 2) {
      return void 0;
    }
    const textEditorModel = model.textEditorModel;
    const overrides = { overrideIdentifier: textEditorModel.getLanguageId(), resource: textEditorModel.uri };
    const nestedProgress = new $VJ((provider) => {
      progress.report({
        message: localize(5221, null, provider.displayName || provider.extensionId && provider.extensionId.value || "???", "command:workbench.action.openSettings?%5B%22editor.formatOnSave%22%5D")
      });
    });
    const enabled = this.c.getValue("editor.formatOnSave", overrides);
    if (!enabled) {
      return void 0;
    }
    const editorOrModel = findEditor(textEditorModel, this.d) || textEditorModel;
    const mode = this.c.getValue("editor.formatOnSaveMode", overrides);
    if (mode === "file") {
      await this.e.invokeFunction($ehb, editorOrModel, 2, nestedProgress, token);
    } else {
      const ranges = await this.e.invokeFunction($fic, $P5(editorOrModel) ? editorOrModel.getModel() : editorOrModel);
      if (ranges === null && mode === "modificationsIfAvailable") {
        await this.e.invokeFunction($ehb, editorOrModel, 2, nestedProgress, token);
      } else if (ranges) {
        await this.e.invokeFunction($chb, editorOrModel, ranges, 2, nestedProgress, token, false);
      }
    }
  }
};
FormatOnSaveParticipant3 = __decorate([
  __param(0, $kl),
  __param(1, $U5),
  __param(2, $Pk)
], FormatOnSaveParticipant3);
var CodeActionOnSaveParticipant3 = class CodeActionOnSaveParticipant4 extends $3c {
  constructor(c, f, g, h3, j, m, n) {
    super();
    this.c = c;
    this.f = f;
    this.g = g;
    this.h = h3;
    this.j = j;
    this.m = m;
    this.n = n;
    this.B(this.h.onDidChangeFocus(() => {
      this.r();
    }));
    this.B(this.j.onDidActiveEditorChange(() => {
      this.r();
    }));
  }
  async r() {
    if (this.c.getValue("editor.codeActions.triggerOnFocusChange") && this.c.getValue("files.autoSave") === "afterDelay") {
      const model = this.m.getActiveCodeEditor()?.getModel();
      if (!model) {
        return void 0;
      }
      const settingsOverrides = { overrideIdentifier: model.getLanguageId(), resource: model.uri };
      const setting = this.c.getValue("editor.codeActionsOnSave", settingsOverrides);
      if (!setting) {
        return void 0;
      }
      if (Array.isArray(setting)) {
        return void 0;
      }
      const settingItems = Object.keys(setting).filter((x) => setting[x] && setting[x] === "always" && $pab.Source.contains(new $oE(x)));
      const cancellationTokenSource = new $ad();
      const codeActionKindList = [];
      for (const item of settingItems) {
        codeActionKindList.push(new $oE(item));
      }
      await this.u(model, codeActionKindList, [], $VJ.None, cancellationTokenSource.token);
    }
  }
  async participate(model, context, progress, token) {
    if (!model.textEditorModel) {
      return;
    }
    const textEditorModel = model.textEditorModel;
    const settingsOverrides = { overrideIdentifier: textEditorModel.getLanguageId(), resource: textEditorModel.uri };
    const setting = this.c.getValue("editor.codeActionsOnSave", settingsOverrides);
    if (!setting) {
      return void 0;
    }
    if (context.reason === 2) {
      return void 0;
    }
    if (context.reason !== 1 && Array.isArray(setting)) {
      return void 0;
    }
    const settingItems = Array.isArray(setting) ? setting : Object.keys(setting).filter((x) => setting[x] && setting[x] !== "never");
    const codeActionsOnSave = this.t(settingItems);
    if (!Array.isArray(setting)) {
      codeActionsOnSave.sort((a, b) => {
        if ($pab.SourceFixAll.contains(a)) {
          if ($pab.SourceFixAll.contains(b)) {
            return 0;
          }
          return -1;
        }
        if ($pab.SourceFixAll.contains(b)) {
          return 1;
        }
        return 0;
      });
    }
    if (!codeActionsOnSave.length) {
      return void 0;
    }
    const excludedActions = Array.isArray(setting) ? [] : Object.keys(setting).filter((x) => setting[x] === "never" || false).map((x) => new $oE(x));
    progress.report({ message: localize(5222, null) });
    const filteredSaveList = Array.isArray(setting) ? codeActionsOnSave : codeActionsOnSave.filter((x) => setting[x.value] === "always" || (setting[x.value] === "explicit" || setting[x.value] === true) && context.reason === 1);
    await this.u(textEditorModel, filteredSaveList, excludedActions, progress, token);
  }
  t(settingItems) {
    const kinds = settingItems.map((x) => new $oE(x));
    return kinds.filter((kind) => {
      return kinds.every((otherKind) => otherKind.equals(kind) || !otherKind.contains(kind));
    });
  }
  async u(model, codeActionsOnSave, excludes, progress, token) {
    const getActionProgress = new class {
      constructor() {
        this.c = /* @__PURE__ */ new Set();
      }
      d() {
        progress.report({
          message: localize(5223, null, [...this.c].map((name) => `'${name}'`).join(", "), "command:workbench.action.openSettings?%5B%22editor.codeActionsOnSave%22%5D")
        });
      }
      report(provider) {
        if (provider.displayName && !this.c.has(provider.displayName)) {
          this.c.add(provider.displayName);
          this.d();
        }
      }
    }();
    for (const codeActionKind of codeActionsOnSave) {
      const sw = new $te();
      const actionsToRun = await this.w(model, codeActionKind, excludes, getActionProgress, token);
      this.n.publicLog2("codeAction.appliedOnSave", {
        codeAction: codeActionKind.value,
        duration: sw.elapsed()
      });
      if (token.isCancellationRequested) {
        actionsToRun.dispose();
        return;
      }
      try {
        for (const action of actionsToRun.validActions) {
          progress.report({ message: localize(5224, null, action.action.title) });
          await this.f.invokeFunction($Dab, action, ApplyCodeActionReason.OnSave, {}, token);
          if (token.isCancellationRequested) {
            return;
          }
        }
      } catch {
      } finally {
        actionsToRun.dispose();
      }
    }
  }
  w(model, codeActionKind, excludes, progress, token) {
    return $Cab(this.g.codeActionProvider, model, model.getFullModelRange(), {
      type: 2,
      triggerAction: CodeActionTriggerSource.OnSave,
      filter: { include: codeActionKind, excludes, includeSourceActions: true }
    }, progress, token);
  }
};
CodeActionOnSaveParticipant3 = __decorate([
  __param(0, $kl),
  __param(1, $Pk),
  __param(2, $mP),
  __param(3, $S4),
  __param(4, $mJ),
  __param(5, $U5),
  __param(6, $zv)
], CodeActionOnSaveParticipant3);
var $jic = class $jic2 extends $3c {
  constructor(c, f) {
    super();
    this.c = c;
    this.f = f;
    this.g();
  }
  g() {
    this.B(this.f.files.addSaveParticipant(this.c.createInstance($gic)));
    this.B(this.f.files.addSaveParticipant(this.c.createInstance(CodeActionOnSaveParticipant3)));
    this.B(this.f.files.addSaveParticipant(this.c.createInstance(FormatOnSaveParticipant3)));
    this.B(this.f.files.addSaveParticipant(this.c.createInstance($hic)));
    this.B(this.f.files.addSaveParticipant(this.c.createInstance($iic)));
  }
};
$jic = __decorate([
  __param(0, $Pk),
  __param(1, $cK)
], $jic);
var workbenchContributionsRegistry8 = $Wn.as(Extensions2.Workbench);
workbenchContributionsRegistry8.registerWorkbenchContribution(
  $jic,
  3
  /* LifecyclePhase.Restored */
);

// out-build/vs/workbench/contrib/codeEditor/browser/toggleColumnSelection.js
var $kic = class _$kic extends $gJ {
  static {
    this.ID = "editor.action.toggleColumnSelection";
  }
  constructor() {
    super({
      id: _$kic.ID,
      title: {
        ...localize2(5226, "Toggle Column Selection Mode"),
        mnemonicTitle: localize(5225, null)
      },
      f1: true,
      toggled: $7m.equals("config.editor.columnSelection", true),
      menu: {
        id: $bJ.MenubarSelectionMenu,
        group: "4_config",
        order: 2
      }
    });
  }
  async run(accessor) {
    const configurationService = accessor.get($kl);
    const codeEditorService = accessor.get($U5);
    const oldValue = configurationService.getValue("editor.columnSelection");
    const codeEditor = this.a(codeEditorService);
    await configurationService.updateValue("editor.columnSelection", !oldValue);
    const newValue = configurationService.getValue("editor.columnSelection");
    if (!codeEditor || codeEditor !== this.a(codeEditorService) || oldValue === newValue || !codeEditor.hasModel() || typeof oldValue !== "boolean" || typeof newValue !== "boolean") {
      return;
    }
    const viewModel = codeEditor._getViewModel();
    if (codeEditor.getOption(
      22
      /* EditorOption.columnSelection */
    )) {
      const selection = codeEditor.getSelection();
      const modelSelectionStart = new $8C(selection.selectionStartLineNumber, selection.selectionStartColumn);
      const viewSelectionStart = viewModel.coordinatesConverter.convertModelPositionToViewPosition(modelSelectionStart);
      const modelPosition = new $8C(selection.positionLineNumber, selection.positionColumn);
      const viewPosition = viewModel.coordinatesConverter.convertModelPositionToViewPosition(modelPosition);
      CoreNavigationCommands.MoveTo.runCoreEditorCommand(viewModel, {
        position: modelSelectionStart,
        viewPosition: viewSelectionStart
      });
      const visibleColumn = viewModel.cursorConfig.visibleColumnFromColumn(viewModel, viewPosition);
      CoreNavigationCommands.ColumnSelect.runCoreEditorCommand(viewModel, {
        position: modelPosition,
        viewPosition,
        doColumnSelect: true,
        mouseColumn: visibleColumn + 1
      });
    } else {
      const columnSelectData = viewModel.getCursorColumnSelectData();
      const fromViewColumn = viewModel.cursorConfig.columnFromVisibleColumn(viewModel, columnSelectData.fromViewLineNumber, columnSelectData.fromViewVisualColumn);
      const fromPosition = viewModel.coordinatesConverter.convertViewPositionToModelPosition(new $8C(columnSelectData.fromViewLineNumber, fromViewColumn));
      const toViewColumn = viewModel.cursorConfig.columnFromVisibleColumn(viewModel, columnSelectData.toViewLineNumber, columnSelectData.toViewVisualColumn);
      const toPosition = viewModel.coordinatesConverter.convertViewPositionToModelPosition(new $8C(columnSelectData.toViewLineNumber, toViewColumn));
      codeEditor.setSelection(new $_D(fromPosition.lineNumber, fromPosition.column, toPosition.lineNumber, toPosition.column));
    }
  }
  a(codeEditorService) {
    const codeEditor = codeEditorService.getFocusedCodeEditor();
    if (codeEditor) {
      return codeEditor;
    }
    return codeEditorService.getActiveCodeEditor();
  }
};
$hJ($kic);

// out-build/vs/workbench/contrib/codeEditor/browser/toggleMinimap.js
var $lic = class _$lic extends $gJ {
  static {
    this.ID = "editor.action.toggleMinimap";
  }
  constructor() {
    super({
      id: _$lic.ID,
      title: {
        ...localize2(5228, "Toggle Minimap"),
        mnemonicTitle: localize(5227, null)
      },
      category: $qn.View,
      f1: true,
      toggled: $7m.equals("config.editor.minimap.enabled", true),
      menu: {
        id: $bJ.MenubarAppearanceMenu,
        group: "4_editor",
        order: 1
      }
    });
  }
  async run(accessor) {
    const configurationService = accessor.get($kl);
    const newValue = !configurationService.getValue("editor.minimap.enabled");
    return configurationService.updateValue("editor.minimap.enabled", newValue);
  }
};
$hJ($lic);

// out-build/vs/workbench/contrib/codeEditor/browser/toggleMultiCursorModifier.js
var $mic = class _$mic extends $gJ {
  static {
    this.ID = "workbench.action.toggleMultiCursorModifier";
  }
  static {
    this.a = "editor.multiCursorModifier";
  }
  constructor() {
    super({
      id: _$mic.ID,
      title: localize2(5232, "Toggle Multi-Cursor Modifier"),
      f1: true
    });
  }
  run(accessor) {
    const configurationService = accessor.get($kl);
    const editorConf = configurationService.getValue("editor");
    const newValue = editorConf.multiCursorModifier === "ctrlCmd" ? "alt" : "ctrlCmd";
    return configurationService.updateValue(_$mic.a, newValue);
  }
};
var multiCursorModifier = new $nn("multiCursorModifier", "altKey");
var MultiCursorModifierContextKeyController = class MultiCursorModifierContextKeyController2 extends $3c {
  constructor(b, contextKeyService) {
    super();
    this.b = b;
    this.a = multiCursorModifier.bindTo(contextKeyService);
    this.c();
    this.B(b.onDidChangeConfiguration((e) => {
      if (e.affectsConfiguration("editor.multiCursorModifier")) {
        this.c();
      }
    }));
  }
  c() {
    const editorConf = this.b.getValue("editor");
    const value = editorConf.multiCursorModifier === "ctrlCmd" ? "ctrlCmd" : "altKey";
    this.a.set(value);
  }
};
MultiCursorModifierContextKeyController = __decorate([
  __param(0, $kl),
  __param(1, $on)
], MultiCursorModifierContextKeyController);
$Wn.as(Extensions2.Workbench).registerWorkbenchContribution(
  MultiCursorModifierContextKeyController,
  3
  /* LifecyclePhase.Restored */
);
$hJ($mic);
$dJ.appendMenuItem($bJ.MenubarSelectionMenu, {
  group: "4_config",
  command: {
    id: $mic.ID,
    title: localize(5229, null)
  },
  when: multiCursorModifier.isEqualTo("ctrlCmd"),
  order: 1
});
$dJ.appendMenuItem($bJ.MenubarSelectionMenu, {
  group: "4_config",
  command: {
    id: $mic.ID,
    title: $m ? localize(5230, null) : localize(5231, null)
  },
  when: multiCursorModifier.isEqualTo("altKey"),
  order: 1
});

// out-build/vs/workbench/contrib/codeEditor/browser/toggleRenderControlCharacter.js
var $nic = class _$nic extends $gJ {
  static {
    this.ID = "editor.action.toggleRenderControlCharacter";
  }
  constructor() {
    super({
      id: _$nic.ID,
      title: {
        ...localize2(5234, "Toggle Control Characters"),
        mnemonicTitle: localize(5233, null)
      },
      category: $qn.View,
      f1: true,
      toggled: $7m.equals("config.editor.renderControlCharacters", true),
      menu: {
        id: $bJ.MenubarAppearanceMenu,
        group: "4_editor",
        order: 5
      }
    });
  }
  run(accessor) {
    const configurationService = accessor.get($kl);
    const newRenderControlCharacters = !configurationService.getValue("editor.renderControlCharacters");
    return configurationService.updateValue("editor.renderControlCharacters", newRenderControlCharacters);
  }
};
$hJ($nic);

// out-build/vs/workbench/contrib/codeEditor/browser/toggleRenderWhitespace.js
var ToggleRenderWhitespaceAction = class _ToggleRenderWhitespaceAction extends $gJ {
  static {
    this.ID = "editor.action.toggleRenderWhitespace";
  }
  constructor() {
    super({
      id: _ToggleRenderWhitespaceAction.ID,
      title: {
        ...localize2(5236, "Toggle Render Whitespace"),
        mnemonicTitle: localize(5235, null)
      },
      category: $qn.View,
      f1: true,
      toggled: $7m.notEquals("config.editor.renderWhitespace", "none"),
      menu: {
        id: $bJ.MenubarAppearanceMenu,
        group: "4_editor",
        order: 4
      }
    });
  }
  run(accessor) {
    const configurationService = accessor.get($kl);
    const renderWhitespace = configurationService.getValue("editor.renderWhitespace");
    let newRenderWhitespace;
    if (renderWhitespace === "none") {
      newRenderWhitespace = "all";
    } else {
      newRenderWhitespace = "none";
    }
    return configurationService.updateValue("editor.renderWhitespace", newRenderWhitespace);
  }
};
$hJ(ToggleRenderWhitespaceAction);

// out-build/vs/workbench/contrib/codeEditor/browser/workbenchReferenceSearch.js
var $oic = class $oic2 extends $hfb {
  constructor(editor, contextKeyService, editorService, notificationService, instantiationService, storageService, configurationService) {
    super(false, editor, contextKeyService, editorService, notificationService, instantiationService, storageService, configurationService);
  }
};
$oic = __decorate([
  __param(1, $on),
  __param(2, $U5),
  __param(3, $PJ),
  __param(4, $Pk),
  __param(5, $jv),
  __param(6, $kl)
], $oic);
$85(
  $hfb.ID,
  $oic,
  4
  /* EditorContributionInstantiation.Lazy */
);

// out-build/vs/workbench/contrib/keybindings/browser/keybindings.contribution.js
var ToggleKeybindingsLogAction = class extends $gJ {
  constructor() {
    super({
      id: "workbench.action.toggleKeybindingsLog",
      title: localize2(7689, "Toggle Keyboard Shortcuts Troubleshooting"),
      category: $qn.Developer,
      f1: true
    });
  }
  run(accessor) {
    const logging = accessor.get($Ty).toggleLogging();
    if (logging) {
      const commandService = accessor.get($sn);
      commandService.executeCommand($QCb);
    }
  }
};
$hJ(ToggleKeybindingsLogAction);

// out-build/vs/workbench/contrib/snippets/browser/commands/configureSnippets.js
var ISnippetPick;
(function(ISnippetPick2) {
  function is(thing) {
    return !!thing && URI.isUri(thing.filepath);
  }
  ISnippetPick2.is = is;
})(ISnippetPick || (ISnippetPick = {}));
async function computePicks(snippetService, userDataProfileService, languageService, labelService) {
  const existing = [];
  const future = [];
  const seen = /* @__PURE__ */ new Set();
  const added = /* @__PURE__ */ new Map();
  for (const file of await snippetService.getSnippetFiles()) {
    if (file.source === 3) {
      continue;
    }
    if (file.isGlobalSnippets) {
      await file.load();
      const names = /* @__PURE__ */ new Set();
      let source;
      outer: for (const snippet2 of file.data) {
        if (!source) {
          source = snippet2.source;
        }
        for (const scope of snippet2.scopes) {
          const name = languageService.getLanguageName(scope);
          if (name) {
            if (names.size >= 4) {
              names.add(`${name}...`);
              break outer;
            } else {
              names.add(name);
            }
          }
        }
      }
      const snippet = {
        label: $sh(file.location),
        filepath: file.location,
        description: names.size === 0 ? localize(9837, null) : localize(9838, null, [...names].join(", "))
      };
      existing.push(snippet);
      if (!source) {
        continue;
      }
      const detail2 = localize(9839, null, source, labelService.getUriLabel(file.location, { relative: true }));
      const lastItem = added.get($sh(file.location));
      if (lastItem) {
        snippet.detail = detail2;
        lastItem.snippet.detail = lastItem.detail;
      }
      added.set($sh(file.location), { snippet, detail: detail2 });
    } else {
      const mode = $sh(file.location).replace(/\.json$/, "");
      existing.push({
        label: $sh(file.location),
        description: `(${languageService.getLanguageName(mode)})`,
        filepath: file.location
      });
      seen.add(mode);
    }
  }
  const dir = userDataProfileService.currentProfile.snippetsHome;
  for (const languageId of languageService.getRegisteredLanguageIds()) {
    const label3 = languageService.getLanguageName(languageId);
    if (label3 && !seen.has(languageId)) {
      future.push({
        label: languageId,
        description: `(${label3})`,
        filepath: $vh(dir, `${languageId}.json`),
        hint: true,
        iconClasses: $hdb(languageId)
      });
    }
  }
  existing.sort((a, b) => {
    const a_ext = $sc(a.filepath.path);
    const b_ext = $sc(b.filepath.path);
    if (a_ext === b_ext) {
      return a.label.localeCompare(b.label);
    } else if (a_ext === ".code-snippets") {
      return -1;
    } else {
      return 1;
    }
  });
  future.sort((a, b) => {
    return a.label.localeCompare(b.label);
  });
  return { existing, future };
}
async function createSnippetFile(scope, defaultPath, quickInputService, fileService, textFileService, opener) {
  function createSnippetUri(input2) {
    const filename = $sc(input2) !== ".code-snippets" ? `${input2}.code-snippets` : input2;
    return $vh(defaultPath, filename);
  }
  await fileService.createFolder(defaultPath);
  const input = await quickInputService.input({
    placeHolder: localize(9840, null),
    async validateInput(input2) {
      if (!input2) {
        return localize(9841, null);
      }
      if (!$Xg(input2)) {
        return localize(9842, null, input2);
      }
      if (await fileService.exists(createSnippetUri(input2))) {
        return localize(9843, null, input2);
      }
      return void 0;
    }
  });
  if (!input) {
    return void 0;
  }
  const resource = createSnippetUri(input);
  await textFileService.write(resource, [
    "{",
    "	// Place your " + scope + " snippets here. Each snippet is defined under a snippet name and has a scope, prefix, body and ",
    "	// description. Add comma separated ids of the languages where the snippet is applicable in the scope field. If scope ",
    "	// is left empty or omitted, the snippet gets applied to all languages. The prefix is what is ",
    "	// used to trigger the snippet and the body will be expanded and inserted. Possible variables are: ",
    "	// $1, $2 for tab stops, $0 for the final cursor position, and ${1:label}, ${2:another} for placeholders. ",
    "	// Placeholders with the same ids are connected.",
    "	// Example:",
    '	// "Print to console": {',
    '	// 	"scope": "javascript,typescript",',
    '	// 	"prefix": "log",',
    '	// 	"body": [',
    `	// 		"console.log('$1');",`,
    '	// 		"$2"',
    "	// 	],",
    '	// 	"description": "Log output to console"',
    "	// }",
    "}"
  ].join("\n"));
  await opener.open(resource);
  return void 0;
}
async function createLanguageSnippetFile(pick, fileService, textFileService) {
  if (await fileService.exists(pick.filepath)) {
    return;
  }
  const contents = [
    "{",
    "	// Place your snippets for " + pick.label + " here. Each snippet is defined under a snippet name and has a prefix, body and ",
    "	// description. The prefix is what is used to trigger the snippet and the body will be expanded and inserted. Possible variables are:",
    "	// $1, $2 for tab stops, $0 for the final cursor position, and ${1:label}, ${2:another} for placeholders. Placeholders with the ",
    "	// same ids are connected.",
    "	// Example:",
    '	// "Print to console": {',
    '	// 	"prefix": "log",',
    '	// 	"body": [',
    `	// 		"console.log('$1');",`,
    '	// 		"$2"',
    "	// 	],",
    '	// 	"description": "Log output to console"',
    "	// }",
    "}"
  ].join("\n");
  await textFileService.write(pick.filepath, contents);
}
var $pic = class extends $c3b {
  constructor() {
    super({
      id: "workbench.action.openSnippets",
      title: localize2(9853, "Configure Snippets"),
      shortTitle: {
        ...localize2(9854, "Snippets"),
        mnemonicTitle: localize(9844, null)
      },
      f1: true,
      menu: [
        { id: $bJ.MenubarPreferencesMenu, group: "2_configuration", order: 5 },
        { id: $bJ.GlobalActivity, group: "2_configuration", order: 5 }
      ]
    });
  }
  async run(accessor) {
    const snippetService = accessor.get($Isb);
    const quickInputService = accessor.get($1M);
    const opener = accessor.get($O4);
    const languageService = accessor.get($1E);
    const userDataProfileService = accessor.get($gT);
    const workspaceService = accessor.get($Zk);
    const fileService = accessor.get($km);
    const textFileService = accessor.get($cK);
    const labelService = accessor.get($ZI);
    const picks = await computePicks(snippetService, userDataProfileService, languageService, labelService);
    const existing = picks.existing;
    const globalSnippetPicks = [{
      scope: localize(9845, null),
      label: localize(9846, null),
      uri: userDataProfileService.currentProfile.snippetsHome
    }];
    const workspaceSnippetPicks = [];
    for (const folder of workspaceService.getWorkspace().folders) {
      workspaceSnippetPicks.push({
        scope: localize(9847, null, folder.name),
        label: localize(9848, null, folder.name),
        uri: folder.toResource(".vscode")
      });
    }
    if (existing.length > 0) {
      existing.unshift({ type: "separator", label: localize(9849, null) });
      existing.push({ type: "separator", label: localize(9850, null) });
    } else {
      existing.push({ type: "separator", label: localize(9851, null) });
    }
    const pick = await quickInputService.pick([].concat(existing, globalSnippetPicks, workspaceSnippetPicks, picks.future), {
      placeHolder: localize(9852, null),
      matchOnDescription: true
    });
    if (globalSnippetPicks.indexOf(pick) >= 0) {
      return createSnippetFile(pick.scope, pick.uri, quickInputService, fileService, textFileService, opener);
    } else if (workspaceSnippetPicks.indexOf(pick) >= 0) {
      return createSnippetFile(pick.scope, pick.uri, quickInputService, fileService, textFileService, opener);
    } else if (ISnippetPick.is(pick)) {
      if (pick.hint) {
        await createLanguageSnippetFile(pick, fileService, textFileService);
      }
      return opener.open(pick.filepath);
    }
  }
};

// out-build/vs/workbench/contrib/snippets/browser/snippetPicker.js
async function $qic(accessor, languageIdOrSnippets) {
  const snippetService = accessor.get($Isb);
  const quickInputService = accessor.get($1M);
  let snippets;
  if (Array.isArray(languageIdOrSnippets)) {
    snippets = languageIdOrSnippets;
  } else {
    snippets = await snippetService.getSnippets(languageIdOrSnippets, { includeDisabledSnippets: true, includeNoPrefixSnippets: true });
  }
  snippets.sort((a, b) => a.snippetSource - b.snippetSource);
  const makeSnippetPicks = () => {
    const result2 = [];
    let prevSnippet;
    for (const snippet of snippets) {
      const pick = {
        label: snippet.prefix || snippet.name,
        detail: snippet.description || snippet.body,
        snippet
      };
      if (!prevSnippet || prevSnippet.snippetSource !== snippet.snippetSource || prevSnippet.source !== snippet.source) {
        let label3 = "";
        switch (snippet.snippetSource) {
          case 1:
            label3 = localize(9866, null);
            break;
          case 3:
            label3 = snippet.source;
            break;
          case 2:
            label3 = localize(9867, null);
            break;
        }
        result2.push({ type: "separator", label: label3 });
      }
      if (snippet.snippetSource === 3) {
        const isEnabled = snippetService.isEnabled(snippet);
        if (isEnabled) {
          pick.buttons = [{
            iconClass: ThemeIcon.asClassName($6l.eyeClosed),
            tooltip: localize(9868, null)
          }];
        } else {
          pick.description = localize(9869, null);
          pick.buttons = [{
            iconClass: ThemeIcon.asClassName($6l.eye),
            tooltip: localize(9870, null)
          }];
        }
      }
      result2.push(pick);
      prevSnippet = snippet;
    }
    return result2;
  };
  const disposables = new $2c();
  const picker = disposables.add(quickInputService.createQuickPick({ useSeparators: true }));
  picker.placeholder = localize(9871, null);
  picker.matchOnDetail = true;
  picker.ignoreFocusOut = false;
  picker.keepScrollPosition = true;
  disposables.add(picker.onDidTriggerItemButton((ctx) => {
    const isEnabled = snippetService.isEnabled(ctx.item.snippet);
    snippetService.updateEnablement(ctx.item.snippet, !isEnabled);
    picker.items = makeSnippetPicks();
  }));
  picker.items = makeSnippetPicks();
  if (!picker.items.length) {
    picker.validationMessage = localize(9872, null);
  }
  picker.show();
  await Promise.race([Event2.toPromise(picker.onDidAccept), Event2.toPromise(picker.onDidHide)]);
  const result = picker.selectedItems[0]?.snippet;
  disposables.dispose();
  return result;
}

// out-build/vs/workbench/contrib/snippets/browser/commands/insertSnippet.js
var Args = class _Args {
  static fromUser(arg) {
    if (!arg || typeof arg !== "object") {
      return _Args.a;
    }
    let { snippet, name, langId } = arg;
    if (typeof snippet !== "string") {
      snippet = void 0;
    }
    if (typeof name !== "string") {
      name = void 0;
    }
    if (typeof langId !== "string") {
      langId = void 0;
    }
    return new _Args(snippet, name, langId);
  }
  static {
    this.a = new _Args(void 0, void 0, void 0);
  }
  constructor(snippet, name, langId) {
    this.snippet = snippet;
    this.name = name;
    this.langId = langId;
  }
};
var $ric = class extends $d3b {
  constructor() {
    super({
      id: "editor.action.insertSnippet",
      title: localize2(9857, "Insert Snippet"),
      f1: true,
      precondition: EditorContextKeys.writable,
      metadata: {
        description: `Insert Snippet`,
        args: [{
          name: "args",
          schema: {
            "type": "object",
            "properties": {
              "snippet": {
                "type": "string"
              },
              "langId": {
                "type": "string"
              },
              "name": {
                "type": "string"
              }
            }
          }
        }]
      }
    });
  }
  async runEditorCommand(accessor, editor, arg) {
    const languageService = accessor.get($1E);
    const snippetService = accessor.get($Isb);
    if (!editor.hasModel()) {
      return;
    }
    const clipboardService = accessor.get($30);
    const instaService = accessor.get($Pk);
    const snippet = await new Promise((resolve, reject) => {
      const { lineNumber, column } = editor.getPosition();
      const { snippet: snippet2, name, langId } = Args.fromUser(arg);
      if (snippet2) {
        return resolve(new $Gsb(false, [], "", "", "", snippet2, "", 1, `random/${Math.random()}`));
      }
      let languageId;
      if (langId) {
        if (!languageService.isRegisteredLanguageId(langId)) {
          return resolve(void 0);
        }
        languageId = langId;
      } else {
        editor.getModel().tokenization.tokenizeIfCheap(lineNumber);
        languageId = editor.getModel().getLanguageIdAtPosition(lineNumber, column);
        if (!languageService.getLanguageName(languageId)) {
          languageId = editor.getModel().getLanguageId();
        }
      }
      if (name) {
        snippetService.getSnippets(languageId, { includeNoPrefixSnippets: true }).then((snippets) => snippets.find((snippet3) => snippet3.name === name)).then(resolve, reject);
      } else {
        resolve(instaService.invokeFunction($qic, languageId));
      }
    });
    if (!snippet) {
      return;
    }
    let clipboardText;
    if (snippet.needsClipboard) {
      clipboardText = await clipboardService.readText();
    }
    editor.focus();
    $Dcb.get(editor)?.insert(snippet.codeSnippet, { clipboardText });
    snippetService.updateUsageTimestamp(snippet);
  }
};

// out-build/vs/workbench/contrib/snippets/browser/commands/surroundWithSnippet.js
async function $sic(snippetsService, model, position, includeDisabledSnippets) {
  const { lineNumber, column } = position;
  model.tokenization.tokenizeIfCheap(lineNumber);
  const languageId = model.getLanguageIdAtPosition(lineNumber, column);
  const allSnippets = await snippetsService.getSnippets(languageId, { includeNoPrefixSnippets: true, includeDisabledSnippets });
  return allSnippets.filter((snippet) => snippet.usesSelection);
}
var $tic = class _$tic extends $d3b {
  static {
    this.options = {
      id: "editor.action.surroundWithSnippet",
      title: localize2(9858, "Surround with Snippet...")
    };
  }
  constructor() {
    super({
      ..._$tic.options,
      precondition: $7m.and(EditorContextKeys.writable, EditorContextKeys.hasNonEmptySelection),
      f1: true
    });
  }
  async runEditorCommand(accessor, editor) {
    if (!editor.hasModel()) {
      return;
    }
    const instaService = accessor.get($Pk);
    const snippetsService = accessor.get($Isb);
    const clipboardService = accessor.get($30);
    const snippets = await $sic(snippetsService, editor.getModel(), editor.getPosition(), true);
    if (!snippets.length) {
      return;
    }
    const snippet = await instaService.invokeFunction($qic, snippets);
    if (!snippet) {
      return;
    }
    let clipboardText;
    if (snippet.needsClipboard) {
      clipboardText = await clipboardService.readText();
    }
    editor.focus();
    $Dcb.get(editor)?.insert(snippet.codeSnippet, { clipboardText });
    snippetsService.updateUsageTimestamp(snippet);
  }
};

// out-build/vs/workbench/contrib/snippets/browser/snippetCodeActionProvider.js
var SurroundWithSnippetCodeActionProvider_1;
var FileTemplateCodeActionProvider_1;
var SurroundWithSnippetCodeActionProvider = class SurroundWithSnippetCodeActionProvider2 {
  static {
    SurroundWithSnippetCodeActionProvider_1 = this;
  }
  static {
    this.a = 4;
  }
  static {
    this.b = {
      kind: $pab.SurroundWith.value,
      title: localize(9859, null),
      command: {
        id: $tic.options.id,
        title: $tic.options.title.value
      }
    };
  }
  constructor(c) {
    this.c = c;
  }
  async provideCodeActions(model, range) {
    if (range.isEmpty()) {
      return void 0;
    }
    const position = $_D.isISelection(range) ? range.getPosition() : range.getStartPosition();
    const snippets = await $sic(this.c, model, position, false);
    if (!snippets.length) {
      return void 0;
    }
    const actions = [];
    for (const snippet of snippets) {
      if (actions.length >= SurroundWithSnippetCodeActionProvider_1.a) {
        actions.push(SurroundWithSnippetCodeActionProvider_1.b);
        break;
      }
      actions.push({
        title: localize(9860, null, snippet.name),
        kind: $pab.SurroundWith.value,
        edit: asWorkspaceEdit(model, range, snippet)
      });
    }
    return {
      actions,
      dispose() {
      }
    };
  }
};
SurroundWithSnippetCodeActionProvider = SurroundWithSnippetCodeActionProvider_1 = __decorate([
  __param(0, $Isb)
], SurroundWithSnippetCodeActionProvider);
var FileTemplateCodeActionProvider = class FileTemplateCodeActionProvider2 {
  static {
    FileTemplateCodeActionProvider_1 = this;
  }
  static {
    this.a = 4;
  }
  static {
    this.b = {
      title: localize(9861, null),
      kind: $pab.SurroundWith.value,
      command: {
        id: $e3b.Id,
        title: ""
      }
    };
  }
  constructor(c) {
    this.c = c;
    this.providedCodeActionKinds = [$pab.SurroundWith.value];
  }
  async provideCodeActions(model) {
    if (model.getValueLength() !== 0) {
      return void 0;
    }
    const snippets = await this.c.getSnippets(model.getLanguageId(), { fileTemplateSnippets: true, includeNoPrefixSnippets: true });
    const actions = [];
    for (const snippet of snippets) {
      if (actions.length >= FileTemplateCodeActionProvider_1.a) {
        actions.push(FileTemplateCodeActionProvider_1.b);
        break;
      }
      actions.push({
        title: localize(9862, null, snippet.name),
        kind: $pab.SurroundWith.value,
        edit: asWorkspaceEdit(model, model.getFullModelRange(), snippet)
      });
    }
    return {
      actions,
      dispose() {
      }
    };
  }
};
FileTemplateCodeActionProvider = FileTemplateCodeActionProvider_1 = __decorate([
  __param(0, $Isb)
], FileTemplateCodeActionProvider);
function asWorkspaceEdit(model, range, snippet) {
  return {
    edits: [{
      versionId: model.getVersionId(),
      resource: model.uri,
      textEdit: {
        range,
        text: snippet.body,
        insertAsSnippet: true
      }
    }]
  };
}
var $uic = class $uic2 {
  constructor(instantiationService, languageFeaturesService, configService) {
    this.a = new $2c();
    const setting = "editor.snippets.codeActions.enabled";
    const sessionStore = new $2c();
    const update = () => {
      sessionStore.clear();
      if (configService.getValue(setting)) {
        sessionStore.add(languageFeaturesService.codeActionProvider.register("*", instantiationService.createInstance(SurroundWithSnippetCodeActionProvider)));
        sessionStore.add(languageFeaturesService.codeActionProvider.register("*", instantiationService.createInstance(FileTemplateCodeActionProvider)));
      }
    };
    update();
    this.a.add(configService.onDidChangeConfiguration((e) => e.affectsConfiguration(setting) && update()));
    this.a.add(sessionStore);
  }
  dispose() {
    this.a.dispose();
  }
};
$uic = __decorate([
  __param(0, $Pk),
  __param(1, $mP),
  __param(2, $kl)
], $uic);

// out-build/vs/workbench/contrib/snippets/browser/snippets.contribution.js
$SC(
  $Isb,
  $Wsb,
  1
  /* InstantiationType.Delayed */
);
$hJ($ric);
$tn.registerCommandAlias("editor.action.showSnippets", "editor.action.insertSnippet");
$hJ($tic);
$hJ($e3b);
$hJ($pic);
var workbenchContribRegistry = $Wn.as(Extensions2.Workbench);
workbenchContribRegistry.registerWorkbenchContribution(
  $uic,
  3
  /* LifecyclePhase.Restored */
);
$Wn.as($Ht.Configuration).registerConfiguration({
  ...$mab,
  "properties": {
    "editor.snippets.codeActions.enabled": {
      "description": localize(9873, null),
      "type": "boolean",
      "default": true
    }
  }
});
var languageScopeSchemaId = "vscode://schemas/snippets";
var snippetSchemaProperties = {
  prefix: {
    description: localize(9874, null),
    type: ["string", "array"]
  },
  isFileTemplate: {
    description: localize(9875, null),
    type: "boolean"
  },
  body: {
    markdownDescription: localize(9876, null),
    type: ["string", "array"],
    items: {
      type: "string"
    }
  },
  description: {
    description: localize(9877, null),
    type: ["string", "array"]
  }
};
var languageScopeSchema = {
  id: languageScopeSchemaId,
  allowComments: true,
  allowTrailingCommas: true,
  defaultSnippets: [{
    label: localize(9878, null),
    body: { "${1:snippetName}": { "prefix": "${2:prefix}", "body": "${3:snippet}", "description": "${4:description}" } }
  }],
  type: "object",
  description: localize(9879, null),
  additionalProperties: {
    type: "object",
    required: ["body"],
    properties: snippetSchemaProperties,
    additionalProperties: false
  }
};
var globalSchemaId = "vscode://schemas/global-snippets";
var globalSchema = {
  id: globalSchemaId,
  allowComments: true,
  allowTrailingCommas: true,
  defaultSnippets: [{
    label: localize(9880, null),
    body: { "${1:snippetName}": { "scope": "${2:scope}", "prefix": "${3:prefix}", "body": "${4:snippet}", "description": "${5:description}" } }
  }],
  type: "object",
  description: localize(9881, null),
  additionalProperties: {
    type: "object",
    required: ["body"],
    properties: {
      ...snippetSchemaProperties,
      scope: {
        description: localize(9882, null),
        type: "string"
      }
    },
    additionalProperties: false
  }
};
var reg = $Wn.as($Xn.JSONContribution);
reg.registerSchema(languageScopeSchemaId, languageScopeSchema);
reg.registerSchema(globalSchemaId, globalSchema);

// out-build/vs/workbench/contrib/format/browser/formatActionsNone.js
$55(class FormatDocumentMultipleAction2 extends $Z5 {
  constructor() {
    super({
      id: "editor.action.formatDocument.none",
      label: localize2(7458, "Format Document"),
      precondition: $7m.and(EditorContextKeys.writable, EditorContextKeys.hasDocumentFormattingProvider.toNegated()),
      kbOpts: {
        kbExpr: EditorContextKeys.editorTextFocus,
        primary: 1024 | 512 | 36,
        linux: {
          primary: 2048 | 1024 | 39
          /* KeyCode.KeyI */
        },
        weight: 100
      }
    });
  }
  async run(accessor, editor) {
    if (!editor.hasModel()) {
      return;
    }
    const commandService = accessor.get($sn);
    const extensionsWorkbenchService = accessor.get($vzb);
    const notificationService = accessor.get($PJ);
    const dialogService = accessor.get($Yv);
    const languageFeaturesService = accessor.get($mP);
    const model = editor.getModel();
    const formatterCount = languageFeaturesService.documentFormattingEditProvider.all(model).length;
    if (formatterCount > 1) {
      return commandService.executeCommand("editor.action.formatDocument.multiple");
    } else if (formatterCount === 1) {
      return commandService.executeCommand("editor.action.formatDocument");
    } else if (model.isTooLargeForSyncing()) {
      notificationService.warn(localize(7455, null));
    } else {
      const langName = model.getLanguageId();
      const message = localize(7456, null, langName);
      const { confirmed } = await dialogService.confirm({
        message,
        primaryButton: localize(7457, null)
      });
      if (confirmed) {
        extensionsWorkbenchService.openSearch(`category:formatters ${langName}`);
      }
    }
  }
});

// out-build/vs/workbench/contrib/folding/browser/folding.contribution.js
var DefaultFoldingRangeProvider_1;
var DefaultFoldingRangeProvider = class DefaultFoldingRangeProvider2 extends $3c {
  static {
    DefaultFoldingRangeProvider_1 = this;
  }
  static {
    this.configName = "editor.defaultFoldingRangeProvider";
  }
  static {
    this.extensionIds = [];
  }
  static {
    this.extensionItemLabels = [];
  }
  static {
    this.extensionDescriptions = [];
  }
  constructor(c, f) {
    super();
    this.c = c;
    this.f = f;
    this.q.add(this.c.onDidChangeExtensions(this.g, this));
    this.q.add($9gb.setFoldingRangeProviderSelector(this.h.bind(this)));
    this.g();
  }
  async g() {
    await this.c.whenInstalledExtensionsRegistered();
    DefaultFoldingRangeProvider_1.extensionIds.length = 0;
    DefaultFoldingRangeProvider_1.extensionItemLabels.length = 0;
    DefaultFoldingRangeProvider_1.extensionDescriptions.length = 0;
    DefaultFoldingRangeProvider_1.extensionIds.push(null);
    DefaultFoldingRangeProvider_1.extensionItemLabels.push(localize(7432, null));
    DefaultFoldingRangeProvider_1.extensionDescriptions.push(localize(7433, null));
    const languageExtensions = [];
    const otherExtensions = [];
    for (const extension of this.c.extensions) {
      if (extension.main || extension.browser) {
        if (extension.categories?.find((cat) => cat === "Programming Languages")) {
          languageExtensions.push(extension);
        } else {
          otherExtensions.push(extension);
        }
      }
    }
    const sorter3 = (a, b) => a.name.localeCompare(b.name);
    for (const extension of languageExtensions.sort(sorter3)) {
      DefaultFoldingRangeProvider_1.extensionIds.push(extension.identifier.value);
      DefaultFoldingRangeProvider_1.extensionItemLabels.push(extension.displayName ?? "");
      DefaultFoldingRangeProvider_1.extensionDescriptions.push(extension.description ?? "");
    }
    for (const extension of otherExtensions.sort(sorter3)) {
      DefaultFoldingRangeProvider_1.extensionIds.push(extension.identifier.value);
      DefaultFoldingRangeProvider_1.extensionItemLabels.push(extension.displayName ?? "");
      DefaultFoldingRangeProvider_1.extensionDescriptions.push(extension.description ?? "");
    }
  }
  h(providers2, document2) {
    const value = this.f.getValue(DefaultFoldingRangeProvider_1.configName, { overrideIdentifier: document2.getLanguageId() });
    if (value) {
      return providers2.filter((p) => p.id === value);
    }
    return void 0;
  }
};
DefaultFoldingRangeProvider = DefaultFoldingRangeProvider_1 = __decorate([
  __param(0, $wN),
  __param(1, $kl)
], DefaultFoldingRangeProvider);
$Wn.as($Ht.Configuration).registerConfiguration({
  ...$mab,
  properties: {
    [DefaultFoldingRangeProvider.configName]: {
      description: localize(7434, null),
      type: ["string", "null"],
      default: null,
      enum: DefaultFoldingRangeProvider.extensionIds,
      enumItemLabels: DefaultFoldingRangeProvider.extensionItemLabels,
      markdownEnumDescriptions: DefaultFoldingRangeProvider.extensionDescriptions
    }
  }
});
$Wn.as(Extensions2.Workbench).registerWorkbenchContribution(
  DefaultFoldingRangeProvider,
  3
  /* LifecyclePhase.Restored */
);

// out-build/vs/workbench/contrib/limitIndicator/browser/limitIndicator.contribution.js
var openSettingsCommand = "workbench.action.openSettings";
var configureSettingsLabel = localize(7703, null);
var $vic = class $vic2 extends $3c {
  constructor(editorService, languageStatusService) {
    super();
    const accessors = [new ColorDecorationAccessor(), new FoldingRangeAccessor()];
    const statusEntries = accessors.map((indicator) => new LanguageStatusEntry(languageStatusService, indicator));
    statusEntries.forEach((entry) => this.B(entry));
    let control;
    const onActiveEditorChanged = () => {
      const activeControl = editorService.activeTextEditorControl;
      if (activeControl === control) {
        return;
      }
      control = activeControl;
      const editor = $S5(activeControl);
      statusEntries.forEach((statusEntry) => statusEntry.onActiveEditorChanged(editor));
    };
    this.B(editorService.onDidActiveEditorChange(onActiveEditorChanged));
    onActiveEditorChanged();
  }
};
$vic = __decorate([
  __param(0, $mJ),
  __param(1, $FS)
], $vic);
var ColorDecorationAccessor = class {
  constructor() {
    this.id = "decoratorsLimitInfo";
    this.name = localize(7704, null);
    this.label = localize(7705, null);
    this.source = localize(7706, null);
    this.settingsId = "editor.colorDecoratorsLimit";
  }
  getLimitReporter(editor) {
    return $Lbb.get(editor)?.limitReporter;
  }
};
var FoldingRangeAccessor = class {
  constructor() {
    this.id = "foldingLimitInfo";
    this.name = localize(7707, null);
    this.label = localize(7708, null);
    this.source = localize(7709, null);
    this.settingsId = "editor.foldingMaximumRegions";
  }
  getLimitReporter(editor) {
    return $9gb.get(editor)?.limitReporter;
  }
};
var LanguageStatusEntry = class {
  constructor(c, d) {
    this.c = c;
    this.d = d;
  }
  onActiveEditorChanged(editor) {
    if (this.b) {
      this.b.dispose();
      this.b = void 0;
    }
    let info;
    if (editor) {
      info = this.d.getLimitReporter(editor);
    }
    this.e(info);
    if (info) {
      this.b = info.onDidChange((_) => {
        this.e(info);
      });
      return true;
    }
    return false;
  }
  e(info) {
    if (this.a) {
      this.a.dispose();
      this.a = void 0;
    }
    if (info && info.limited !== false) {
      const status = {
        id: this.d.id,
        selector: "*",
        name: this.d.name,
        severity: severity_default.Warning,
        label: this.d.label,
        detail: localize(7710, null, info.limited),
        command: { id: openSettingsCommand, arguments: [this.d.settingsId], title: configureSettingsLabel },
        accessibilityInfo: void 0,
        source: this.d.source,
        busy: false
      };
      this.a = this.c.addStatus(status);
    }
  }
  dispose() {
    this.a?.dispose;
    this.a = void 0;
    this.b?.dispose;
    this.b = void 0;
  }
};
$Wn.as(Extensions2.Workbench).registerWorkbenchContribution(
  $vic,
  3
  /* LifecyclePhase.Restored */
);

// out-build/vs/workbench/contrib/inlayHints/browser/inlayHintsAccessibilty.js
var $wic_1;
var $wic = class $wic2 {
  static {
    $wic_1 = this;
  }
  static {
    this.IsReading = new $nn("isReadingLineWithInlayHints", false, { type: "boolean", description: localize(7460, null) });
  }
  static {
    this.ID = "editor.contrib.InlayHintsAccessibility";
  }
  static get(editor) {
    return editor.getContribution($wic_1.ID) ?? void 0;
  }
  constructor(d, contextKeyService, e, f) {
    this.d = d;
    this.e = e;
    this.f = f;
    this.c = new $2c();
    this.a = document.createElement("span");
    this.a.style.position = "fixed";
    this.a.className = "inlayhint-accessibility-element";
    this.a.tabIndex = 0;
    this.a.setAttribute("aria-description", localize(7461, null));
    this.b = $wic_1.IsReading.bindTo(contextKeyService);
  }
  dispose() {
    this.c.dispose();
    this.b.reset();
    this.a.remove();
  }
  g() {
    $$i(this.a);
    this.c.clear();
    this.b.reset();
  }
  async h(line, hints) {
    this.c.clear();
    if (!this.a.isConnected) {
      this.d.getDomNode()?.appendChild(this.a);
    }
    if (!this.d.hasModel() || !this.a.isConnected) {
      this.b.set(false);
      return;
    }
    const cts = new $ad();
    this.c.add(cts);
    for (const hint of hints) {
      await hint.resolve(cts.token);
    }
    if (cts.token.isCancellationRequested) {
      return;
    }
    const model = this.d.getModel();
    const newChildren = [];
    let start = 0;
    let tooLongToRead = false;
    for (const item of hints) {
      const part = model.getValueInRange({ startLineNumber: line, startColumn: start + 1, endLineNumber: line, endColumn: item.hint.position.column });
      if (part.length > 0) {
        newChildren.push(part);
        start = item.hint.position.column - 1;
      }
      if (start > 750) {
        newChildren.push("\u2026");
        tooLongToRead = true;
        break;
      }
      const em = document.createElement("em");
      const { label: label3 } = item.hint;
      if (typeof label3 === "string") {
        em.innerText = label3;
      } else {
        for (const part2 of label3) {
          if (part2.command) {
            const link2 = this.f.createInstance(Link2, em, { href: $0db(part2.command), label: part2.label, title: part2.command.title }, void 0);
            this.c.add(link2);
          } else {
            em.innerText += part2.label;
          }
        }
      }
      newChildren.push(em);
    }
    if (!tooLongToRead) {
      newChildren.push(model.getValueInRange({ startLineNumber: line, startColumn: start + 1, endLineNumber: line, endColumn: Number.MAX_SAFE_INTEGER }));
    }
    $dk(this.a, ...newChildren);
    this.a.focus();
    this.b.set(true);
    this.c.add($_i(this.a, "focusout", () => {
      this.g();
    }));
  }
  startInlayHintsReading() {
    if (!this.d.hasModel()) {
      return;
    }
    const line = this.d.getPosition().lineNumber;
    const hints = $vfb.get(this.d)?.getInlayHintsForLine(line);
    if (!hints || hints.length === 0) {
      this.e.playSignal($N9.noInlayHints);
    } else {
      this.h(line, hints);
    }
  }
  stopInlayHintsReading() {
    this.g();
    this.d.focus();
  }
};
$wic = $wic_1 = __decorate([
  __param(1, $on),
  __param(2, $I9),
  __param(3, $Pk)
], $wic);
$hJ(class StartReadHints extends $25 {
  constructor() {
    super({
      id: "inlayHints.startReadingLineWithHint",
      title: localize2(7462, "Read Line With Inline Hints"),
      precondition: EditorContextKeys.hasInlayHintsProvider,
      f1: true
    });
  }
  runEditorCommand(_accessor, editor) {
    const ctrl = $wic.get(editor);
    ctrl?.startInlayHintsReading();
  }
});
$hJ(class StopReadHints extends $25 {
  constructor() {
    super({
      id: "inlayHints.stopReadingLineWithHint",
      title: localize2(7463, "Stop Inlay Hints Reading"),
      precondition: $wic.IsReading,
      f1: true,
      keybinding: {
        weight: 100,
        primary: 9
        /* KeyCode.Escape */
      }
    });
  }
  runEditorCommand(_accessor, editor) {
    const ctrl = $wic.get(editor);
    ctrl?.stopInlayHintsReading();
  }
});
$85(
  $wic.ID,
  $wic,
  4
  /* EditorContributionInstantiation.Lazy */
);

// out-build/vs/workbench/contrib/themes/browser/themes.contribution.js
var DefaultThemeUpdatedNotificationContribution_1;
var $xic = $9r("theme-selection-manage-extension", $6l.gear, localize(11362, null));
var ConfigureItem;
(function(ConfigureItem2) {
  ConfigureItem2["BROWSE_GALLERY"] = "marketplace";
  ConfigureItem2["EXTENSIONS_VIEW"] = "extensions";
  ConfigureItem2["CUSTOM_TOP_ENTRY"] = "customTopEntry";
})(ConfigureItem || (ConfigureItem = {}));
var MarketplaceThemesPicker = class MarketplaceThemesPicker2 {
  constructor(l, m, n, o, q, r2, u, v, w) {
    this.l = l;
    this.m = m;
    this.n = n;
    this.o = o;
    this.q = q;
    this.r = r2;
    this.u = u;
    this.v = v;
    this.w = w;
    this.b = /* @__PURE__ */ new Set();
    this.d = [];
    this.f = false;
    this.g = void 0;
    this.h = new $ze();
    this.k = new $Th(200);
    this.a = o.getInstalled().then((installed) => {
      const result = /* @__PURE__ */ new Set();
      for (const ext of installed) {
        result.add(ext.identifier.id);
      }
      return result;
    });
  }
  get themes() {
    return this.d;
  }
  get onDidChange() {
    return this.h.event;
  }
  trigger(value) {
    if (this.j) {
      this.j.cancel();
      this.j = void 0;
    }
    this.k.trigger(() => {
      this.j = new $ad();
      return this.x(value, this.j.token);
    });
  }
  async x(value, token) {
    this.f = true;
    this.h.fire();
    try {
      const installedExtensions = await this.a;
      const options3 = { text: `${this.m} ${value}`, pageSize: 20 };
      const pager = await this.n.query(options3, token);
      for (let i2 = 0; i2 < pager.total && i2 < 1; i2++) {
        if (token.isCancellationRequested) {
          break;
        }
        const nThemes = this.d.length;
        const gallery = i2 === 0 ? pager.firstPage : await pager.getPage(i2, token);
        const promises = [];
        const promisesGalleries = [];
        for (let i3 = 0; i3 < gallery.length; i3++) {
          if (token.isCancellationRequested) {
            break;
          }
          const ext = gallery[i3];
          if (!installedExtensions.has(ext.identifier.id) && !this.b.has(ext.identifier.id)) {
            this.b.add(ext.identifier.id);
            promises.push(this.l(ext.publisher, ext.name, ext.version));
            promisesGalleries.push(ext);
          }
        }
        const allThemes = await Promise.all(promises);
        for (let i3 = 0; i3 < allThemes.length; i3++) {
          const ext = promisesGalleries[i3];
          for (const theme of allThemes[i3]) {
            this.d.push({ id: theme.id, theme, label: theme.label, description: `${ext.displayName} \xB7 ${ext.publisherDisplayName}`, galleryExtension: ext, buttons: [configureButton] });
          }
        }
        if (nThemes !== this.d.length) {
          this.d.sort((t1, t2) => t1.label.localeCompare(t2.label));
          this.h.fire();
        }
      }
    } catch (e) {
      if (!$kb(e)) {
        this.r.error(`Error while searching for themes:`, e);
        this.g = "message" in e ? e.message : String(e);
      }
    } finally {
      this.f = false;
      this.h.fire();
    }
  }
  openQuickPick(value, currentTheme, selectTheme) {
    let result = void 0;
    const disposables = new $2c();
    return new Promise((s, _) => {
      const quickpick = disposables.add(this.q.createQuickPick());
      quickpick.items = [];
      quickpick.sortByLabel = false;
      quickpick.matchOnDescription = true;
      quickpick.buttons = [this.q.backButton];
      quickpick.title = "Marketplace Themes";
      quickpick.placeholder = localize(11363, null);
      quickpick.canSelectMany = false;
      disposables.add(quickpick.onDidChangeValue(() => this.trigger(quickpick.value)));
      disposables.add(quickpick.onDidAccept(async (_2) => {
        const themeItem = quickpick.selectedItems[0];
        if (themeItem?.galleryExtension) {
          result = "selected";
          quickpick.hide();
          const success = await this.y(themeItem.galleryExtension);
          if (success) {
            selectTheme(themeItem.theme, true);
          } else {
            selectTheme(currentTheme, true);
          }
        }
      }));
      disposables.add(quickpick.onDidTriggerItemButton((e) => {
        if (isItem(e.item)) {
          const extensionId = e.item.theme?.extensionData?.extensionId;
          if (extensionId) {
            this.v.openSearch(`@id:${extensionId}`);
          } else {
            this.v.openSearch(`${this.m} ${quickpick.value}`);
          }
        }
      }));
      disposables.add(quickpick.onDidChangeActive((themes) => {
        if (result === void 0) {
          selectTheme(themes[0]?.theme, false);
        }
      }));
      disposables.add(quickpick.onDidHide(() => {
        if (result === void 0) {
          selectTheme(currentTheme, true);
          result = "cancelled";
        }
        s(result);
      }));
      disposables.add(quickpick.onDidTriggerButton((e) => {
        if (e === this.q.backButton) {
          result = "back";
          quickpick.hide();
        }
      }));
      disposables.add(this.onDidChange(() => {
        let items = this.themes;
        if (this.f) {
          items = items.concat({ label: "$(loading~spin) Searching for themes...", id: void 0, alwaysShow: true });
        } else if (items.length === 0 && this.g) {
          items = [{ label: `$(error) ${localize(11364, null, this.g)}`, id: void 0, alwaysShow: true }];
        }
        const activeItemId = quickpick.activeItems[0]?.id;
        const newActiveItem = activeItemId ? items.find((i2) => isItem(i2) && i2.id === activeItemId) : void 0;
        quickpick.items = items;
        if (newActiveItem) {
          quickpick.activeItems = [newActiveItem];
        }
      }));
      this.trigger(value);
      quickpick.show();
    }).finally(() => {
      disposables.dispose();
    });
  }
  async y(galleryExtension) {
    this.v.openSearch(`@id:${galleryExtension.identifier.id}`);
    const result = await this.w.confirm({
      message: localize(11365, null, galleryExtension.displayName, galleryExtension.publisherDisplayName),
      primaryButton: localize(11366, null)
    });
    if (!result.confirmed) {
      return false;
    }
    try {
      await this.u.withProgress({
        location: 15,
        title: localize(11367, null, galleryExtension.displayName)
      }, async () => {
        await this.o.installFromGallery(galleryExtension, {
          // Setting this to false is how you get the extension to be synced with Settings Sync (if enabled).
          isMachineScoped: false
        });
      });
      return true;
    } catch (e) {
      this.r.error(`Problem installing extension ${galleryExtension.identifier.id}`, e);
      return false;
    }
  }
  dispose() {
    if (this.j) {
      this.j.cancel();
      this.j = void 0;
    }
    this.k.dispose();
    this.b.clear();
    this.d.length = 0;
  }
};
MarketplaceThemesPicker = __decorate([
  __param(2, $pA),
  __param(3, $sA),
  __param(4, $1M),
  __param(5, $wn),
  __param(6, $TJ),
  __param(7, $vzb),
  __param(8, $Yv)
], MarketplaceThemesPicker);
var InstalledThemesPicker = class InstalledThemesPicker2 {
  constructor(a, b, d, f, g, h3, j, k) {
    this.a = a;
    this.b = b;
    this.d = d;
    this.f = f;
    this.g = g;
    this.h = h3;
    this.j = j;
    this.k = k;
  }
  async openQuickPick(picks, currentTheme) {
    let marketplaceThemePicker;
    if (this.g.isEnabled()) {
      if (this.j.supportsExtensionGalleryResources && this.a.browseMessage) {
        marketplaceThemePicker = this.k.createInstance(MarketplaceThemesPicker, this.d.bind(this), this.a.marketplaceTag);
        picks = [configurationEntry(this.a.browseMessage, ConfigureItem.BROWSE_GALLERY), ...picks];
      } else {
        picks = [...picks, { type: "separator" }, configurationEntry(this.a.installMessage, ConfigureItem.EXTENSIONS_VIEW)];
      }
    }
    let selectThemeTimeout;
    const selectTheme = (theme, applyTheme) => {
      if (selectThemeTimeout) {
        clearTimeout(selectThemeTimeout);
      }
      selectThemeTimeout = $Y.setTimeout(() => {
        selectThemeTimeout = void 0;
        const newTheme = theme ?? currentTheme;
        this.b(newTheme, applyTheme ? "auto" : "preview").then(void 0, (err) => {
          $gb(err);
          this.b(currentTheme, void 0);
        });
      }, applyTheme ? 0 : 200);
    };
    const pickInstalledThemes = (activeItemId) => {
      const disposables = new $2c();
      return new Promise((s, _) => {
        let isCompleted = false;
        const autoFocusIndex = picks.findIndex((p) => isItem(p) && p.id === activeItemId);
        const quickpick = disposables.add(this.f.createQuickPick({ useSeparators: true }));
        quickpick.items = picks;
        quickpick.title = this.a.title;
        quickpick.description = this.a.description;
        quickpick.placeholder = this.a.placeholderMessage;
        quickpick.activeItems = [picks[autoFocusIndex]];
        quickpick.canSelectMany = false;
        quickpick.toggles = this.a.toggles;
        quickpick.toggles?.forEach((toggle) => {
          disposables.add(toggle.onChange(() => this.a.onToggle?.(toggle, quickpick)));
        });
        quickpick.matchOnDescription = true;
        disposables.add(quickpick.onDidAccept(async (_2) => {
          isCompleted = true;
          const theme = quickpick.selectedItems[0];
          if (!theme || theme.configureItem) {
            if (!theme || theme.configureItem === ConfigureItem.EXTENSIONS_VIEW) {
              this.h.openSearch(`${this.a.marketplaceTag} ${quickpick.value}`);
            } else if (theme.configureItem === ConfigureItem.BROWSE_GALLERY) {
              if (marketplaceThemePicker) {
                const res = await marketplaceThemePicker.openQuickPick(quickpick.value, currentTheme, selectTheme);
                if (res === "back") {
                  await pickInstalledThemes(void 0);
                }
              }
            }
          } else {
            selectTheme(theme.theme, true);
          }
          quickpick.hide();
          s();
        }));
        disposables.add(quickpick.onDidChangeActive((themes) => selectTheme(themes[0]?.theme, false)));
        disposables.add(quickpick.onDidHide(() => {
          if (!isCompleted) {
            selectTheme(currentTheme, true);
            s();
          }
          quickpick.dispose();
        }));
        disposables.add(quickpick.onDidTriggerItemButton((e) => {
          if (isItem(e.item)) {
            const extensionId = e.item.theme?.extensionData?.extensionId;
            if (extensionId) {
              this.h.openSearch(`@id:${extensionId}`);
            } else {
              this.h.openSearch(`${this.a.marketplaceTag} ${quickpick.value}`);
            }
          }
        }));
        quickpick.show();
      }).finally(() => {
        disposables.dispose();
      });
    };
    await pickInstalledThemes(currentTheme.id);
    marketplaceThemePicker?.dispose();
  }
};
InstalledThemesPicker = __decorate([
  __param(3, $1M),
  __param(4, $pA),
  __param(5, $vzb),
  __param(6, $Olb),
  __param(7, $Pk)
], InstalledThemesPicker);
var SelectColorThemeCommandId = "workbench.action.selectTheme";
$hJ(class extends $gJ {
  constructor() {
    super({
      id: SelectColorThemeCommandId,
      title: localize2(11405, "Color Theme"),
      category: $qn.Preferences,
      f1: true,
      keybinding: {
        weight: 200,
        primary: $$e(
          2048 | 41,
          2048 | 50
          /* KeyCode.KeyT */
        )
      }
    });
  }
  a(colorScheme) {
    switch (colorScheme) {
      case ColorScheme.DARK:
        return localize(11368, null);
      case ColorScheme.LIGHT:
        return localize(11369, null);
      case ColorScheme.HIGH_CONTRAST_DARK:
        return localize(11370, null);
      case ColorScheme.HIGH_CONTRAST_LIGHT:
        return localize(11371, null);
      default:
        return localize(11372, null);
    }
  }
  async run(accessor) {
    const themeService = accessor.get($rwb);
    const preferencesService = accessor.get($TK);
    const preferredColorScheme = themeService.getPreferredColorScheme();
    let modeConfigureToggle;
    if (preferredColorScheme) {
      modeConfigureToggle = new $Q1({
        title: localize(11373, null),
        icon: $6l.colorMode,
        isChecked: false,
        ...$u$
      });
    } else {
      modeConfigureToggle = new $Q1({
        title: localize(11374, null),
        icon: $6l.colorMode,
        isChecked: false,
        ...$u$
      });
    }
    const options3 = {
      installMessage: localize(11375, null),
      browseMessage: "$(plus) " + localize(11376, null),
      placeholderMessage: this.a(preferredColorScheme),
      marketplaceTag: "category:themes",
      toggles: [modeConfigureToggle],
      onToggle: async (toggle, picker2) => {
        picker2.hide();
        await preferencesService.openSettings({ query: ThemeSettings.DETECT_COLOR_SCHEME });
      }
    };
    const setTheme = (theme, settingsTarget) => themeService.setColorTheme(theme, settingsTarget);
    const getMarketplaceColorThemes = (publisher, name, version2) => themeService.getMarketplaceColorThemes(publisher, name, version2);
    const instantiationService = accessor.get($Pk);
    const picker = instantiationService.createInstance(InstalledThemesPicker, options3, setTheme, getMarketplaceColorThemes);
    const themes = await themeService.getColorThemes();
    const currentTheme = themeService.getColorTheme();
    const lightEntries = toEntries(themes.filter((t) => t.type === ColorScheme.LIGHT), localize(11377, null));
    const darkEntries = toEntries(themes.filter((t) => t.type === ColorScheme.DARK), localize(11378, null));
    const hcEntries = toEntries(themes.filter((t) => $es(t.type)), localize(11379, null));
    let picks;
    switch (preferredColorScheme) {
      case ColorScheme.DARK:
        picks = [...darkEntries, ...lightEntries, ...hcEntries];
        break;
      case ColorScheme.HIGH_CONTRAST_DARK:
      case ColorScheme.HIGH_CONTRAST_LIGHT:
        picks = [...hcEntries, ...lightEntries, ...darkEntries];
        break;
      case ColorScheme.LIGHT:
      default:
        picks = [...lightEntries, ...darkEntries, ...hcEntries];
        break;
    }
    await picker.openQuickPick(picks, currentTheme);
  }
});
var SelectFileIconThemeCommandId = "workbench.action.selectIconTheme";
$hJ(class extends $gJ {
  constructor() {
    super({
      id: SelectFileIconThemeCommandId,
      title: localize2(11406, "File Icon Theme"),
      category: $qn.Preferences,
      f1: true
    });
  }
  async run(accessor) {
    const themeService = accessor.get($rwb);
    const options3 = {
      installMessage: localize(11380, null),
      placeholderMessage: localize(11381, null),
      marketplaceTag: "tag:icon-theme"
    };
    const setTheme = (theme, settingsTarget) => themeService.setFileIconTheme(theme, settingsTarget);
    const getMarketplaceColorThemes = (publisher, name, version2) => themeService.getMarketplaceFileIconThemes(publisher, name, version2);
    const instantiationService = accessor.get($Pk);
    const picker = instantiationService.createInstance(InstalledThemesPicker, options3, setTheme, getMarketplaceColorThemes);
    const picks = [
      { type: "separator", label: localize(11382, null) },
      { id: "", theme: $1Vb.noIconTheme, label: localize(11383, null), description: localize(11384, null) },
      ...toEntries(await themeService.getFileIconThemes())
    ];
    await picker.openQuickPick(picks, themeService.getFileIconTheme());
  }
});
var SelectProductIconThemeCommandId = "workbench.action.selectProductIconTheme";
$hJ(class extends $gJ {
  constructor() {
    super({
      id: SelectProductIconThemeCommandId,
      title: localize2(11407, "Product Icon Theme"),
      category: $qn.Preferences,
      f1: true
    });
  }
  async run(accessor) {
    const themeService = accessor.get($rwb);
    const options3 = {
      installMessage: localize(11385, null),
      browseMessage: "$(plus) " + localize(11386, null),
      placeholderMessage: localize(11387, null),
      marketplaceTag: "tag:product-icon-theme"
    };
    const setTheme = (theme, settingsTarget) => themeService.setProductIconTheme(theme, settingsTarget);
    const getMarketplaceColorThemes = (publisher, name, version2) => themeService.getMarketplaceProductIconThemes(publisher, name, version2);
    const instantiationService = accessor.get($Pk);
    const picker = instantiationService.createInstance(InstalledThemesPicker, options3, setTheme, getMarketplaceColorThemes);
    const picks = [
      { type: "separator", label: localize(11388, null) },
      { id: $7Vb, theme: $8Vb.defaultTheme, label: localize(11389, null) },
      ...toEntries(await themeService.getProductIconThemes())
    ];
    await picker.openQuickPick(picks, themeService.getProductIconTheme());
  }
});
$tn.registerCommand("workbench.action.previewColorTheme", async function(accessor, extension, themeSettingsId) {
  const themeService = accessor.get($rwb);
  let themes = findBuiltInThemes(await themeService.getColorThemes(), extension);
  if (themes.length === 0) {
    themes = await themeService.getMarketplaceColorThemes(extension.publisher, extension.name, extension.version);
  }
  for (const theme of themes) {
    if (!themeSettingsId || theme.settingsId === themeSettingsId) {
      await themeService.setColorTheme(theme, "preview");
      return theme.settingsId;
    }
  }
  return void 0;
});
function findBuiltInThemes(themes, extension) {
  return themes.filter(({ extensionData }) => extensionData && extensionData.extensionIsBuiltin && $1f(extensionData.extensionPublisher, extension.publisher) && $1f(extensionData.extensionName, extension.name));
}
function configurationEntry(label3, configureItem) {
  return {
    id: void 0,
    label: label3,
    alwaysShow: true,
    buttons: [configureButton],
    configureItem
  };
}
function isItem(i2) {
  return i2["type"] !== "separator";
}
function toEntry(theme) {
  const settingId = theme.settingsId ?? void 0;
  const item = {
    id: theme.id,
    theme,
    label: theme.label,
    description: theme.description || (theme.label === settingId ? void 0 : settingId)
  };
  if (theme.extensionData) {
    item.buttons = [configureButton];
  }
  return item;
}
function toEntries(themes, label3) {
  const sorter3 = (t1, t2) => t1.label.localeCompare(t2.label);
  const entries2 = themes.map(toEntry).sort(sorter3);
  if (entries2.length > 0 && label3) {
    entries2.unshift({ type: "separator", label: label3 });
  }
  return entries2;
}
var configureButton = {
  iconClass: ThemeIcon.asClassName($xic),
  tooltip: localize(11390, null)
};
$hJ(class extends $gJ {
  constructor() {
    super({
      id: "workbench.action.generateColorTheme",
      title: localize2(11408, "Generate Color Theme From Current Settings"),
      category: $qn.Developer,
      f1: true
    });
  }
  run(accessor) {
    const themeService = accessor.get($rwb);
    const theme = themeService.getColorTheme();
    const colors = $Wn.as($3n.ColorContribution).getColors();
    const colorIds = colors.map((c) => c.id).sort();
    const resultingColors = {};
    const inherited = [];
    for (const colorId of colorIds) {
      const color2 = theme.getColor(colorId, false);
      if (color2) {
        resultingColors[colorId] = $Vn.Format.CSS.formatHexA(color2, true);
      } else {
        inherited.push(colorId);
      }
    }
    const nullDefaults = [];
    for (const id2 of inherited) {
      const color2 = theme.getColor(id2);
      if (color2) {
        resultingColors["__" + id2] = $Vn.Format.CSS.formatHexA(color2, true);
      } else {
        nullDefaults.push(id2);
      }
    }
    for (const id2 of nullDefaults) {
      resultingColors["__" + id2] = null;
    }
    let contents = JSON.stringify({
      "$schema": $LGb,
      type: theme.type,
      colors: resultingColors,
      tokenColors: theme.tokenColors.filter((t) => !!t.scope)
    }, null, "	");
    contents = contents.replace(/\"__/g, '//"');
    const editorService = accessor.get($mJ);
    return editorService.openEditor({ resource: void 0, contents, languageId: "jsonc", options: { pinned: true } });
  }
});
var toggleLightDarkThemesCommandId = "workbench.action.toggleLightDarkThemes";
$hJ(class extends $gJ {
  constructor() {
    super({
      id: toggleLightDarkThemesCommandId,
      title: localize2(11409, "Toggle between Light/Dark Themes"),
      category: $qn.Preferences,
      f1: true
    });
  }
  async run(accessor) {
    const themeService = accessor.get($rwb);
    const configurationService = accessor.get($kl);
    const notificationService = accessor.get($PJ);
    const preferencesService = accessor.get($TK);
    if (configurationService.getValue(ThemeSettings.DETECT_COLOR_SCHEME)) {
      const message = localize(11391, null, ThemeSettings.DETECT_COLOR_SCHEME);
      notificationService.prompt(Severity2.Info, message, [
        {
          label: localize(11392, null),
          run: () => {
            return preferencesService.openUserSettings({ query: ThemeSettings.DETECT_COLOR_SCHEME });
          }
        }
      ]);
      return;
    }
    const currentTheme = themeService.getColorTheme();
    let newSettingsId = ThemeSettings.PREFERRED_DARK_THEME;
    switch (currentTheme.type) {
      case ColorScheme.LIGHT:
        newSettingsId = ThemeSettings.PREFERRED_DARK_THEME;
        break;
      case ColorScheme.DARK:
        newSettingsId = ThemeSettings.PREFERRED_LIGHT_THEME;
        break;
      case ColorScheme.HIGH_CONTRAST_LIGHT:
        newSettingsId = ThemeSettings.PREFERRED_HC_DARK_THEME;
        break;
      case ColorScheme.HIGH_CONTRAST_DARK:
        newSettingsId = ThemeSettings.PREFERRED_HC_LIGHT_THEME;
        break;
    }
    const themeSettingId = configurationService.getValue(newSettingsId);
    if (themeSettingId && typeof themeSettingId === "string") {
      const theme = (await themeService.getColorThemes()).find((t) => t.settingsId === themeSettingId);
      if (theme) {
        themeService.setColorTheme(theme.id, "auto");
      }
    }
  }
});
var browseColorThemesInMarketplaceCommandId = "workbench.action.browseColorThemesInMarketplace";
$hJ(class extends $gJ {
  constructor() {
    super({
      id: browseColorThemesInMarketplaceCommandId,
      title: localize2(11410, "Browse Color Themes in Marketplace"),
      category: $qn.Preferences,
      f1: true
    });
  }
  async run(accessor) {
    const marketplaceTag = "category:themes";
    const themeService = accessor.get($rwb);
    const extensionGalleryService = accessor.get($pA);
    const extensionResourceLoaderService = accessor.get($Olb);
    const instantiationService = accessor.get($Pk);
    if (!extensionGalleryService.isEnabled() || !extensionResourceLoaderService.supportsExtensionGalleryResources) {
      return;
    }
    const currentTheme = themeService.getColorTheme();
    const getMarketplaceColorThemes = (publisher, name, version2) => themeService.getMarketplaceColorThemes(publisher, name, version2);
    let selectThemeTimeout;
    const selectTheme = (theme, applyTheme) => {
      if (selectThemeTimeout) {
        clearTimeout(selectThemeTimeout);
      }
      selectThemeTimeout = $Y.setTimeout(() => {
        selectThemeTimeout = void 0;
        const newTheme = theme ?? currentTheme;
        themeService.setColorTheme(newTheme, applyTheme ? "auto" : "preview").then(void 0, (err) => {
          $gb(err);
          themeService.setColorTheme(currentTheme, void 0);
        });
      }, applyTheme ? 0 : 200);
    };
    const marketplaceThemePicker = instantiationService.createInstance(MarketplaceThemesPicker, getMarketplaceColorThemes, marketplaceTag);
    await marketplaceThemePicker.openQuickPick("", themeService.getColorTheme(), selectTheme).then(void 0, $gb);
  }
});
var ThemesSubMenu = new $bJ("ThemesSubMenu");
$dJ.appendMenuItem($bJ.GlobalActivity, {
  title: localize(11393, null),
  submenu: ThemesSubMenu,
  group: "2_configuration",
  order: 7
});
$dJ.appendMenuItem($bJ.MenubarPreferencesMenu, {
  title: localize(11394, null),
  submenu: ThemesSubMenu,
  group: "2_configuration",
  order: 7
});
$dJ.appendMenuItem(ThemesSubMenu, {
  command: {
    id: SelectColorThemeCommandId,
    title: localize(11395, null)
  },
  order: 1
});
$dJ.appendMenuItem(ThemesSubMenu, {
  command: {
    id: SelectFileIconThemeCommandId,
    title: localize(11396, null)
  },
  order: 2
});
$dJ.appendMenuItem(ThemesSubMenu, {
  command: {
    id: SelectProductIconThemeCommandId,
    title: localize(11397, null)
  },
  order: 3
});
var DefaultThemeUpdatedNotificationContribution = class DefaultThemeUpdatedNotificationContribution2 {
  static {
    DefaultThemeUpdatedNotificationContribution_1 = this;
  }
  static {
    this.STORAGE_KEY = "themeUpdatedNotificationShown";
  }
  constructor(a, b, d, f, g, h3) {
    this.a = a;
    this.b = b;
    this.d = d;
    this.f = f;
    this.g = g;
    this.h = h3;
    if (d.getBoolean(
      DefaultThemeUpdatedNotificationContribution_1.STORAGE_KEY,
      -1
      /* StorageScope.APPLICATION */
    )) {
      return;
    }
    setTimeout(async () => {
      if (d.getBoolean(
        DefaultThemeUpdatedNotificationContribution_1.STORAGE_KEY,
        -1
        /* StorageScope.APPLICATION */
      )) {
        return;
      }
      if (await this.h.hadLastFocus()) {
        this.d.store(
          DefaultThemeUpdatedNotificationContribution_1.STORAGE_KEY,
          true,
          -1,
          0
          /* StorageTarget.USER */
        );
        if (this.b.hasUpdatedDefaultThemes()) {
          this.j();
        } else {
          const currentTheme = this.b.getColorTheme().settingsId;
          if (currentTheme === ThemeSettingDefaults.COLOR_THEME_LIGHT_OLD || currentTheme === ThemeSettingDefaults.COLOR_THEME_DARK_OLD) {
            this.k();
          }
        }
      }
    }, 3e3);
  }
  async j() {
    const usingLight = this.b.getColorTheme().type === ColorScheme.LIGHT;
    const newThemeSettingsId = usingLight ? ThemeSettingDefaults.COLOR_THEME_LIGHT : ThemeSettingDefaults.COLOR_THEME_DARK;
    const newTheme = (await this.b.getColorThemes()).find((theme) => theme.settingsId === newThemeSettingsId);
    if (newTheme) {
      const choices = [
        {
          label: localize(11398, null),
          run: () => {
            this.l("keepNew");
          }
        },
        {
          label: localize(11399, null),
          run: () => {
            this.l("browse");
            this.f.executeCommand(SelectColorThemeCommandId);
          }
        },
        {
          label: localize(11400, null),
          run: async () => {
            this.l("keepOld");
            const oldSettingsId = usingLight ? ThemeSettingDefaults.COLOR_THEME_LIGHT_OLD : ThemeSettingDefaults.COLOR_THEME_DARK_OLD;
            const oldTheme = (await this.b.getColorThemes()).find((theme) => theme.settingsId === oldSettingsId);
            if (oldTheme) {
              this.b.setColorTheme(oldTheme, "auto");
            }
          }
        }
      ];
      await this.a.prompt(Severity2.Info, localize(11401, null, newTheme.label), choices, {
        onCancel: () => this.l("cancel")
      });
    }
  }
  async k() {
    const newThemeSettingsId = this.b.getColorTheme().type === ColorScheme.LIGHT ? ThemeSettingDefaults.COLOR_THEME_LIGHT : ThemeSettingDefaults.COLOR_THEME_DARK;
    const theme = (await this.b.getColorThemes()).find((theme2) => theme2.settingsId === newThemeSettingsId);
    if (theme) {
      const choices = [
        {
          label: localize(11402, null),
          run: () => {
            this.l("tryNew");
            this.b.setColorTheme(theme, "auto");
          }
        },
        {
          label: localize(11403, null),
          run: () => {
            this.l("cancel");
          }
        }
      ];
      await this.a.prompt(Severity2.Info, localize(11404, null, theme.label), choices, { onCancel: () => this.l("cancel") });
    }
  }
  l(outcome) {
    this.g.publicLog2("themeUpdatedNotication", {
      web: $r,
      reaction: outcome
    });
  }
};
DefaultThemeUpdatedNotificationContribution = DefaultThemeUpdatedNotificationContribution_1 = __decorate([
  __param(0, $PJ),
  __param(1, $rwb),
  __param(2, $jv),
  __param(3, $sn),
  __param(4, $zv),
  __param(5, $S4)
], DefaultThemeUpdatedNotificationContribution);
var workbenchRegistry5 = $Wn.as(Extensions2.Workbench);
workbenchRegistry5.registerWorkbenchContribution(
  DefaultThemeUpdatedNotificationContribution,
  4
  /* LifecyclePhase.Eventually */
);

// out-build/vs/platform/update/common/update.config.contribution.js
var configurationRegistry15 = $Wn.as($Ht.Configuration);
configurationRegistry15.registerConfiguration({
  id: "update",
  order: 15,
  title: localize(2478, null),
  type: "object",
  properties: {
    "update.mode": {
      type: "string",
      enum: ["none", "manual", "start", "default"],
      default: "default",
      scope: 1,
      description: localize(2479, null),
      tags: ["usesOnlineServices"],
      enumDescriptions: [
        localize(2480, null),
        localize(2481, null),
        localize(2482, null),
        localize(2483, null)
      ],
      policy: {
        name: "UpdateMode",
        minimumVersion: "1.67"
      }
    },
    "update.channel": {
      type: "string",
      default: "default",
      scope: 1,
      description: localize(2484, null),
      deprecationMessage: localize(2485, null, "update.mode")
    },
    "update.enableWindowsBackgroundUpdates": {
      type: "boolean",
      default: true,
      scope: 1,
      title: localize(2486, null),
      description: localize(2487, null),
      included: $l && !$r
    },
    "update.showReleaseNotes": {
      type: "boolean",
      default: true,
      scope: 1,
      description: localize(2488, null),
      tags: ["usesOnlineServices"]
    }
  }
});

// out-build/vs/workbench/contrib/markdown/browser/markdownSettingRenderer.js
var $yic = class $yic2 {
  constructor(f, g, h3, i2, j) {
    this.f = f;
    this.g = g;
    this.h = h3;
    this.i = i2;
    this.j = j;
    this.c = /* @__PURE__ */ new Map();
    this.d = /* @__PURE__ */ new Map();
    this.e = /* @__PURE__ */ new Map();
    this.a = new RegExp(`^<a (href)=".*code.*://settings/([^\\s"]+)"(?:\\s*codesetting="([^"]+)")?>`);
    this.b = new RegExp(`^setting\\(([^\\s:)]+)(?::([^)]+))?\\)$`);
  }
  get featuredSettingStates() {
    const result = /* @__PURE__ */ new Map();
    for (const [settingId, value] of this.e) {
      result.set(settingId, this.f.getValue(settingId) === value);
    }
    return result;
  }
  k(raw) {
    const match = this.a.exec(raw);
    if (match && match.length === 4) {
      const settingId = match[2];
      const rendered = this.n(settingId, match[3]);
      if (rendered) {
        return raw.replace(this.a, rendered);
      }
    }
    return void 0;
  }
  l(raw) {
    const match = this.b.exec(raw);
    if (match && match.length === 3) {
      const settingId = match[1];
      const rendered = this.n(settingId, match[2]);
      if (rendered) {
        return raw.replace(this.b, rendered);
      }
    }
    return void 0;
  }
  getHtmlRenderer() {
    return ({ raw }) => {
      const replacedAnchor = this.k(raw);
      if (replacedAnchor) {
        raw = replacedAnchor;
      }
      return raw;
    };
  }
  getCodeSpanRenderer() {
    return ({ text: text2 }) => {
      const replacedSimple = this.l(text2);
      if (replacedSimple) {
        return replacedSimple;
      }
      return `<code>${text2}</code>`;
    };
  }
  settingToUriString(settingId, value) {
    return `${Schemas.codeSetting}://${settingId}${value ? `/${value}` : ""}`;
  }
  m(settingId) {
    if (this.d.has(settingId)) {
      return this.d.get(settingId);
    }
    return this.h.getSetting(settingId);
  }
  parseValue(settingId, value) {
    if (value === "undefined" || value === "") {
      return void 0;
    }
    const setting = this.m(settingId);
    if (!setting) {
      return value;
    }
    switch (setting.type) {
      case "boolean":
        return value === "true";
      case "number":
        return parseInt(value, 10);
      case "string":
      default:
        return value;
    }
  }
  n(settingId, newValue) {
    const setting = this.m(settingId);
    if (!setting) {
      return "";
    }
    return this.u(setting, newValue);
  }
  o(settingId, alreadyDisplayed) {
    if (alreadyDisplayed) {
      return localize(7801, null);
    } else {
      const displayName = $p1b(settingId);
      return localize(7802, null, displayName.category, displayName.label);
    }
  }
  p(settingId) {
    const displayName = $p1b(settingId);
    return localize(7803, null, displayName.category, displayName.label);
  }
  q(setting, value) {
    const currentValue = this.f.getValue(setting.key);
    return currentValue === value || currentValue === void 0 && setting.value === value;
  }
  r(setting, booleanValue) {
    const displayName = $p1b(setting.key);
    if (this.q(setting, booleanValue)) {
      if (booleanValue) {
        return localize(7804, null, displayName.category, displayName.label);
      } else {
        return localize(7805, null, displayName.category, displayName.label);
      }
    }
    if (booleanValue) {
      return localize(7806, null, displayName.category, displayName.label);
    } else {
      return localize(7807, null, displayName.category, displayName.label);
    }
  }
  s(setting, stringValue) {
    const displayName = $p1b(setting.key);
    if (this.q(setting, stringValue)) {
      return localize(7808, null, displayName.category, displayName.label, stringValue);
    }
    return localize(7809, null, displayName.category, displayName.label, stringValue);
  }
  t(setting, numberValue) {
    const displayName = $p1b(setting.key);
    if (this.q(setting, numberValue)) {
      return localize(7810, null, displayName.category, displayName.label, numberValue);
    }
    return localize(7811, null, displayName.category, displayName.label, numberValue);
  }
  u(setting, newValue) {
    const href = this.settingToUriString(setting.key, newValue);
    const title = localize(7812, null);
    return `<code tabindex="0"><a href="${href}" class="codesetting" title="${title}" aria-role="button"><svg width="14" height="14" viewBox="0 0 15 15" xmlns="http://www.w3.org/2000/svg" fill="currentColor"><path d="M9.1 4.4L8.6 2H7.4l-.5 2.4-.7.3-2-1.3-.9.8 1.3 2-.2.7-2.4.5v1.2l2.4.5.3.8-1.3 2 .8.8 2-1.3.8.3.4 2.3h1.2l.5-2.4.8-.3 2 1.3.8-.8-1.3-2 .3-.8 2.3-.4V7.4l-2.4-.5-.3-.8 1.3-2-.8-.8-2 1.3-.7-.2zM9.4 1l.5 2.4L12 2.1l2 2-1.4 2.1 2.4.4v2.8l-2.4.5L14 12l-2 2-2.1-1.4-.5 2.4H6.6l-.5-2.4L4 13.9l-2-2 1.4-2.1L1 9.4V6.6l2.4-.5L2.1 4l2-2 2.1 1.4.4-2.4h2.8zm.6 7c0 1.1-.9 2-2 2s-2-.9-2-2 .9-2 2-2 2 .9 2 2zM8 9c.6 0 1-.4 1-1s-.4-1-1-1-1 .4-1 1 .4 1 1 1z"/></svg>
			<span class="separator"></span>
			<span class="setting-name">${setting.key}</span>
		</a></code>`;
  }
  v(setting, newValue) {
    if (setting.type === "boolean") {
      return this.r(setting, newValue);
    } else if (setting.type === "string") {
      return this.s(setting, newValue);
    } else if (setting.type === "number") {
      return this.t(setting, newValue);
    }
    return void 0;
  }
  async restoreSetting(settingId) {
    const userOriginalSettingValue = this.c.get(settingId);
    this.c.delete(settingId);
    return this.f.updateValue(
      settingId,
      userOriginalSettingValue,
      2
      /* ConfigurationTarget.USER */
    );
  }
  async setSetting(settingId, currentSettingValue, newSettingValue) {
    this.c.set(settingId, currentSettingValue);
    return this.f.updateValue(
      settingId,
      newSettingValue,
      2
      /* ConfigurationTarget.USER */
    );
  }
  getActions(uri) {
    if (uri.scheme !== Schemas.codeSetting) {
      return;
    }
    const actions = [];
    const settingId = uri.authority;
    const newSettingValue = this.parseValue(uri.authority, uri.path.substring(1));
    const currentSettingValue = this.f.inspect(settingId).userValue;
    if (newSettingValue !== void 0 && newSettingValue === currentSettingValue && this.c.has(settingId)) {
      const restoreMessage = this.p(settingId);
      actions.push({
        class: void 0,
        id: "restoreSetting",
        enabled: true,
        tooltip: restoreMessage,
        label: restoreMessage,
        run: () => {
          return this.restoreSetting(settingId);
        }
      });
    } else if (newSettingValue !== void 0) {
      const setting = this.m(settingId);
      const trySettingMessage = setting ? this.v(setting, newSettingValue) : void 0;
      if (setting && trySettingMessage) {
        actions.push({
          class: void 0,
          id: "trySetting",
          enabled: !this.q(setting, newSettingValue),
          tooltip: trySettingMessage,
          label: trySettingMessage,
          run: () => {
            this.setSetting(settingId, currentSettingValue, newSettingValue);
          }
        });
      }
    }
    const viewInSettingsMessage = this.o(settingId, actions.length > 0);
    actions.push({
      class: void 0,
      enabled: true,
      id: "viewInSettings",
      tooltip: viewInSettingsMessage,
      label: viewInSettingsMessage,
      run: () => {
        return this.h.openApplicationSettings({ query: `@id:${settingId}` });
      }
    });
    actions.push({
      class: void 0,
      enabled: true,
      id: "copySettingId",
      tooltip: localize(7813, null),
      label: localize(7814, null),
      run: () => {
        this.j.writeText(settingId);
      }
    });
    return actions;
  }
  w(uri, x, y) {
    const actions = this.getActions(uri);
    if (!actions) {
      return;
    }
    this.g.showContextMenu({
      getAnchor: () => ({ x, y }),
      getActions: () => actions,
      getActionViewItem: (action) => {
        return new $U1(action, action, { label: true });
      }
    });
  }
  async updateSetting(uri, x, y) {
    if (uri.scheme === Schemas.codeSetting) {
      this.i.publicLog2("releaseNotesSettingAction", {
        settingId: uri.authority
      });
      return this.w(uri, x, y);
    }
  }
};
$yic = __decorate([
  __param(0, $kl),
  __param(1, $50),
  __param(2, $TK),
  __param(3, $zv),
  __param(4, $30)
], $yic);

// out-build/vs/workbench/contrib/update/browser/releaseNotesEditor.js
var $zic = class $zic2 {
  constructor(g, h3, i2, j, k, l, m, n, o, p, q, r2, s) {
    this.g = g;
    this.h = h3;
    this.i = i2;
    this.j = j;
    this.k = k;
    this.l = l;
    this.m = m;
    this.n = n;
    this.o = o;
    this.p = p;
    this.q = q;
    this.r = r2;
    this.s = s;
    this.b = /* @__PURE__ */ new Map();
    this.c = void 0;
    this.f = new $2c();
    $YE.onDidChange(() => {
      return this.t();
    });
    l.onDidChangeConfiguration(this.B, this, this.f);
    p.onDidChangeActiveWebviewEditor(this.C, this, this.f);
    this.a = this.s.createInstance($yic);
  }
  async t() {
    if (!this.c || !this.d) {
      return;
    }
    const html3 = await this.A(this.d);
    if (this.c) {
      this.c.webview.setHtml(html3);
    }
  }
  async u(useCurrentFile) {
    if (useCurrentFile) {
      const currentFileUri = this.o.getActiveCodeEditor()?.getModel()?.uri;
      if (currentFileUri) {
        return $uh(currentFileUri);
      }
    }
    return URI.parse("https://code.visualstudio.com/raw");
  }
  async show(version2, useCurrentFile) {
    const releaseNoteText = await this.v(version2, useCurrentFile);
    const base = await this.u(useCurrentFile);
    this.d = { text: releaseNoteText, base };
    const html3 = await this.A(this.d);
    const title = localize(11459, null, version2);
    const activeEditorPane = this.m.activeEditorPane;
    if (this.c) {
      this.c.setName(title);
      this.c.webview.setHtml(html3);
      this.p.revealWebview(this.c, activeEditorPane ? activeEditorPane.group : this.n.activeGroup, false);
    } else {
      this.c = this.p.openWebview({
        title,
        options: {
          tryRestoreScrollPosition: true,
          enableFindWidget: true,
          disableServiceWorker: useCurrentFile ? false : true
        },
        contentOptions: {
          localResourceRoots: useCurrentFile ? [base] : [],
          allowScripts: true
        },
        extension: void 0
      }, "releaseNotes", title, { group: $nJ, preserveFocus: false });
      this.c.webview.onDidClickLink((uri) => this.w(URI.parse(uri)));
      const disposables = new $2c();
      disposables.add(this.c.webview.onMessage((e) => {
        if (e.message.type === "showReleaseNotes") {
          this.l.updateValue("update.showReleaseNotes", e.message.value);
        } else if (e.message.type === "clickSetting") {
          const x = this.c?.webview.container.offsetLeft + e.message.value.x;
          const y = this.c?.webview.container.offsetTop + e.message.value.y;
          this.a.updateSetting(URI.parse(e.message.value.uri), x, y);
        }
      }));
      disposables.add(this.c.onWillDispose(() => {
        disposables.dispose();
        this.c = void 0;
      }));
      this.c.webview.setHtml(html3);
    }
    return true;
  }
  async v(version2, useCurrentFile) {
    const match = /^(\d+\.\d+)\./.exec(version2);
    if (!match) {
      throw new Error("not found");
    }
    const versionLabel = match[1].replace(/\./g, "_");
    const baseUrl = "https://code.visualstudio.com/raw";
    const url = `${baseUrl}/v${versionLabel}.md`;
    const unassigned = localize(11460, null);
    const escapeMdHtml = (text2) => {
      return $zf(text2).replace(/\\/g, "\\\\");
    };
    const patchKeybindings = (text2) => {
      const kb = (match2, kb2) => {
        const keybinding = this.h.lookupKeybinding(kb2);
        if (!keybinding) {
          return unassigned;
        }
        return keybinding.getLabel() || unassigned;
      };
      const kbstyle = (match2, kb2) => {
        const keybinding = $S3.parseKeybinding(kb2);
        if (!keybinding) {
          return unassigned;
        }
        const resolvedKeybindings = this.h.resolveKeybinding(keybinding);
        if (resolvedKeybindings.length === 0) {
          return unassigned;
        }
        return resolvedKeybindings[0].getLabel() || unassigned;
      };
      const kbCode = (match2, binding) => {
        const resolved = kb(match2, binding);
        return resolved ? `<code title="${binding}">${escapeMdHtml(resolved)}</code>` : resolved;
      };
      const kbstyleCode = (match2, binding) => {
        const resolved = kbstyle(match2, binding);
        return resolved ? `<code title="${binding}">${escapeMdHtml(resolved)}</code>` : resolved;
      };
      return text2.replace(/`kb\(([a-z.\d\-]+)\)`/gi, kbCode).replace(/`kbstyle\(([^\)]+)\)`/gi, kbstyleCode).replace(/kb\(([a-z.\d\-]+)\)/gi, (match2, binding) => $fm(kb(match2, binding))).replace(/kbstyle\(([^\)]+)\)/gi, (match2, binding) => $fm(kbstyle(match2, binding)));
    };
    const fetchReleaseNotes = async () => {
      let text2;
      try {
        if (useCurrentFile) {
          const file = this.o.getActiveCodeEditor()?.getModel()?.getValue();
          text2 = file ? file.substring(file.indexOf("#")) : void 0;
        } else {
          text2 = await $bv(await this.k.request({ url }, CancellationToken.None));
        }
      } catch {
        throw new Error("Failed to fetch release notes");
      }
      if (!text2 || !/^#\s/.test(text2) && !useCurrentFile) {
        throw new Error("Invalid release notes");
      }
      return patchKeybindings(text2);
    };
    if (useCurrentFile) {
      return fetchReleaseNotes();
    }
    if (!this.b.has(version2)) {
      this.b.set(version2, (async () => {
        try {
          return await fetchReleaseNotes();
        } catch (err) {
          this.b.delete(version2);
          throw err;
        }
      })());
    }
    return this.b.get(version2);
  }
  async w(uri) {
    if (uri.scheme === Schemas.codeSetting) {
    } else {
      this.z(uri, "ReleaseNotes").then((updated) => this.j.open(updated, { allowCommands: ["workbench.action.openSettings"] })).then(void 0, $gb);
    }
  }
  async z(uri, origin, experiment = "1") {
    if ($iw(this.r, this.g) && $kw(this.l) === 3) {
      if (uri.scheme === "https" && uri.authority === "code.visualstudio.com") {
        return uri.with({ query: `${uri.query ? uri.query + "&" : ""}utm_source=VsCode&utm_medium=${encodeURIComponent(origin)}&utm_content=${encodeURIComponent(experiment)}` });
      }
    }
    return uri;
  }
  async A(fileContent) {
    const nonce = $ps();
    const content = await $Qdc(fileContent.text, this.q, this.i, {
      shouldSanitize: false,
      markedExtensions: [{
        renderer: {
          html: this.a.getHtmlRenderer(),
          codespan: this.a.getCodeSpanRenderer()
        }
      }]
    });
    const colorMap = $YE.getColorMap();
    const css = colorMap ? $4Gb(colorMap) : "";
    const showReleaseNotes2 = Boolean(this.l.getValue("update.showReleaseNotes"));
    return `<!DOCTYPE html>
		<html>
			<head>
				<base href="${$HJb(fileContent.base).toString(true)}/" >
				<meta http-equiv="Content-type" content="text/html;charset=UTF-8">
				<meta http-equiv="Content-Security-Policy" content="default-src 'none'; img-src https: data:; media-src https:; style-src 'nonce-${nonce}' https://code.visualstudio.com; script-src 'nonce-${nonce}';">
				<style nonce="${nonce}">
					${$Pdc}
					${css}

					/* codesetting */

					code:has(.codesetting)+code:not(:has(.codesetting)) {
						display: none;
					}

					code:has(.codesetting) {
						background-color: var(--vscode-textPreformat-background);
						color: var(--vscode-textPreformat-foreground);
						padding-left: 1px;
						margin-right: 3px;
						padding-right: 0px;
					}

					code:has(.codesetting):focus {
						border: 1px solid var(--vscode-button-border, transparent);
					}

					.codesetting {
						color: var(--vscode-textPreformat-foreground);
						padding: 0px 1px 1px 0px;
						font-size: 0px;
						overflow: hidden;
						text-overflow: ellipsis;
						outline-offset: 2px !important;
						box-sizing: border-box;
						text-align: center;
						cursor: pointer;
						display: inline;
						margin-right: 3px;
					}
					.codesetting svg {
						font-size: 12px;
						text-align: center;
						cursor: pointer;
						border: 1px solid var(--vscode-button-secondaryBorder, transparent);
						outline: 1px solid transparent;
						line-height: 9px;
						margin-bottom: -5px;
						padding-left: 0px;
						padding-top: 2px;
						padding-bottom: 2px;
						padding-right: 2px;
						display: inline-block;
						text-decoration: none;
						text-rendering: auto;
						text-transform: none;
						-webkit-font-smoothing: antialiased;
						-moz-osx-font-smoothing: grayscale;
						user-select: none;
						-webkit-user-select: none;
					}
					.codesetting .setting-name {
						font-size: 13px;
						padding-left: 2px;
						padding-right: 3px;
						padding-top: 1px;
						padding-bottom: 1px;
						margin-left: -5px;
						margin-top: -3px;
					}
					.codesetting:hover {
						color: var(--vscode-textPreformat-foreground) !important;
						text-decoration: none !important;
					}
					code:has(.codesetting):hover {
						filter: brightness(140%);
						text-decoration: none !important;
					}
					.codesetting:focus {
						outline: 0 !important;
						text-decoration: none !important;
						color: var(--vscode-button-hoverForeground) !important;
					}
					.codesetting .separator {
						width: 1px;
						height: 14px;
						margin-bottom: -3px;
						display: inline-block;
						background-color: var(--vscode-editor-background);
						font-size: 12px;
						margin-right: 8px;
					}

					header { display: flex; align-items: center; padding-top: 1em; }
				</style>
			</head>
			<body>
				${content}
				<script nonce="${nonce}">
					const vscode = acquireVsCodeApi();
					const container = document.createElement('p');
					container.style.display = 'flex';
					container.style.alignItems = 'center';

					const input = document.createElement('input');
					input.type = 'checkbox';
					input.id = 'showReleaseNotes';
					input.checked = ${showReleaseNotes2};
					container.appendChild(input);

					const label = document.createElement('label');
					label.htmlFor = 'showReleaseNotes';
					label.textContent = '${localize(11461, null)}';
					container.appendChild(label);

					const beforeElement = document.querySelector("body > h1")?.nextElementSibling;
					if (beforeElement) {
						document.body.insertBefore(container, beforeElement);
					} else {
						document.body.appendChild(container);
					}

					window.addEventListener('message', event => {
						if (event.data.type === 'showReleaseNotes') {
							input.checked = event.data.value;
						}
					});

					window.addEventListener('click', event => {
						const href = event.target.href ?? event.target.parentElement?.href ?? event.target.parentElement?.parentElement?.href;
						if (href && (href.startsWith('${Schemas.codeSetting}'))) {
							vscode.postMessage({ type: 'clickSetting', value: { uri: href, x: event.clientX, y: event.clientY }});
						}
					});

					window.addEventListener('keypress', event => {
						if (event.keyCode === 13) {
							if (event.target.children.length > 0 && event.target.children[0].href) {
								const clientRect = event.target.getBoundingClientRect();
								vscode.postMessage({ type: 'clickSetting', value: { uri: event.target.children[0].href, x: clientRect.right , y: clientRect.bottom }});
							}
						}
					});

					input.addEventListener('change', event => {
						vscode.postMessage({ type: 'showReleaseNotes', value: input.checked }, '*');
					});
				</script>
			</body>
		</html>`;
  }
  B(e) {
    if (e.affectsConfiguration("update.showReleaseNotes")) {
      this.D();
    }
  }
  C(input) {
    if (input && input === this.c) {
      this.D();
    }
  }
  D() {
    if (this.c) {
      this.c.webview.postMessage({
        type: "showReleaseNotes",
        value: this.l.getValue("update.showReleaseNotes")
      });
    }
  }
};
$zic = __decorate([
  __param(0, $Xk),
  __param(1, $Ty),
  __param(2, $1E),
  __param(3, $O4),
  __param(4, $9u),
  __param(5, $kl),
  __param(6, $mJ),
  __param(7, $iJ),
  __param(8, $U5),
  __param(9, $SOb),
  __param(10, $wN),
  __param(11, $Vu),
  __param(12, $Pk)
], $zic);

// out-build/vs/workbench/contrib/update/browser/update.js
var $Fic_1;
var $Aic = new $nn(
  "updateState",
  "uninitialized"
  /* StateType.Uninitialized */
);
var $Bic = new $nn("majorMinorUpdateAvailable", false);
var $Cic = new $nn("releaseNotesUrl", "");
var $Dic = new $nn("downloadUrl", "");
var releaseNotesManager = void 0;
function $Eic(instantiationService, version2, useCurrentFile) {
  if (!releaseNotesManager) {
    releaseNotesManager = instantiationService.createInstance($zic);
  }
  return releaseNotesManager.show(version2, useCurrentFile);
}
async function openLatestReleaseNotesInBrowser(accessor) {
  const openerService = accessor.get($O4);
  const productService = accessor.get($Vu);
  if (productService.releaseNotesUrl) {
    const uri = URI.parse(productService.releaseNotesUrl);
    await openerService.open(uri);
  } else {
    throw new Error(localize(11477, null, productService.nameLong));
  }
}
async function showReleaseNotes(accessor, version2) {
  const instantiationService = accessor.get($Pk);
  try {
    await $Eic(instantiationService, version2, false);
  } catch (err) {
    try {
      await instantiationService.invokeFunction(openLatestReleaseNotesInBrowser);
    } catch (err2) {
      throw new Error(`${err.message} and ${err2.message}`);
    }
  }
}
function parseVersion(version2) {
  const match = /([0-9]+)\.([0-9]+)\.([0-9]+)/.exec(version2);
  if (!match) {
    return void 0;
  }
  return {
    major: parseInt(match[1]),
    minor: parseInt(match[2]),
    patch: parseInt(match[3])
  };
}
function isMajorMinorUpdate(before, after) {
  return before.major < after.major || before.minor < after.minor;
}
var $Fic = class $Fic2 {
  static {
    $Fic_1 = this;
  }
  static {
    this.a = "releaseNotes/lastVersion";
  }
  constructor(storageService, instantiationService, notificationService, environmentService, openerService, configurationService, hostService, productService, contextKeyService) {
    if (productService.releaseNotesUrl) {
      const releaseNotesUrlKey = $Cic.bindTo(contextKeyService);
      releaseNotesUrlKey.set(productService.releaseNotesUrl);
    }
    if (productService.downloadUrl) {
      const downloadUrlKey = $Dic.bindTo(contextKeyService);
      downloadUrlKey.set(productService.downloadUrl);
    }
    if ($r) {
      return;
    }
    hostService.hadLastFocus().then(async (hadLastFocus) => {
      if (!hadLastFocus) {
        return;
      }
      const lastVersion = parseVersion(storageService.get($Fic_1.a, -1, ""));
      const currentVersion = parseVersion(productService.version);
      const shouldShowReleaseNotes = configurationService.getValue("update.showReleaseNotes");
      const releaseNotesUrl = productService.releaseNotesUrl;
      if (shouldShowReleaseNotes && !environmentService.skipReleaseNotes && releaseNotesUrl && lastVersion && currentVersion && isMajorMinorUpdate(lastVersion, currentVersion)) {
        $Eic(instantiationService, productService.version, false).then(void 0, () => {
          notificationService.prompt(severity_default.Info, localize(11478, null, productService.nameLong, productService.version), [{
            label: localize(11479, null),
            run: () => {
              const uri = URI.parse(releaseNotesUrl);
              openerService.open(uri);
            }
          }]);
        });
      }
      storageService.store(
        $Fic_1.a,
        productService.version,
        -1,
        1
        /* StorageTarget.MACHINE */
      );
    });
  }
};
$Fic = $Fic_1 = __decorate([
  __param(0, $jv),
  __param(1, $Pk),
  __param(2, $PJ),
  __param(3, $M4),
  __param(4, $O4),
  __param(5, $kl),
  __param(6, $S4),
  __param(7, $Vu),
  __param(8, $on)
], $Fic);
var $Gic = class $Gic2 extends $3c {
  constructor(g, h3, j, m, n, r2, s, t, u, w, y) {
    super();
    this.g = g;
    this.h = h3;
    this.j = j;
    this.m = m;
    this.n = n;
    this.r = r2;
    this.s = s;
    this.t = t;
    this.u = u;
    this.w = w;
    this.y = y;
    this.b = this.B(new $4c());
    this.a = n.state;
    this.c = $Aic.bindTo(this.s);
    this.f = $Bic.bindTo(this.s);
    this.B(n.onStateChange(this.z, this));
    this.z(this.n.state);
    const currentVersion = this.t.commit;
    const lastKnownVersion = this.g.get(
      "update/lastKnownVersion",
      -1
      /* StorageScope.APPLICATION */
    );
    if (currentVersion !== lastKnownVersion) {
      this.g.remove(
        "update/lastKnownVersion",
        -1
        /* StorageScope.APPLICATION */
      );
      this.g.remove(
        "update/updateNotificationTime",
        -1
        /* StorageScope.APPLICATION */
      );
    }
    this.J();
  }
  async z(state) {
    this.c.set(state.type);
    switch (state.type) {
      case "disabled":
        if (state.reason === 5) {
          this.j.notify({
            severity: Severity2.Info,
            message: localize(11480, null, this.t.nameLong),
            actions: {
              primary: [
                new $Um("", localize(11481, null), void 0, void 0, () => {
                  this.u.open("https://aka.ms/vscode-windows-setup");
                })
              ]
            },
            neverShowAgain: { id: "no-updates-running-as-admin" }
          });
        }
        break;
      case "idle":
        if (state.error) {
          this.C(state.error);
        } else if (this.a.type === "checking for updates" && this.a.explicit && await this.y.hadLastFocus()) {
          this.D();
        }
        break;
      case "available for download":
        this.F(state.update);
        break;
      case "downloaded":
        this.G(state.update);
        break;
      case "ready": {
        const productVersion = state.update.productVersion;
        if (productVersion) {
          const currentVersion = parseVersion(this.t.version);
          const nextVersion = parseVersion(productVersion);
          this.f.set(Boolean(currentVersion && nextVersion && isMajorMinorUpdate(currentVersion, nextVersion)));
          this.H(state.update);
        }
        break;
      }
    }
    let badge = void 0;
    let priority = void 0;
    if (state.type === "available for download" || state.type === "downloaded" || state.type === "ready") {
      badge = new $wqb(1, () => localize(11482, null, this.t.nameShort));
    } else if (state.type === "checking for updates") {
      badge = new $yqb(() => localize(11483, null));
      priority = 1;
    } else if (state.type === "downloading") {
      badge = new $yqb(() => localize(11484, null));
      priority = 1;
    } else if (state.type === "updating") {
      badge = new $yqb(() => localize(11485, null));
      priority = 1;
    }
    this.b.clear();
    if (badge) {
      this.b.value = this.r.showGlobalActivity({ badge, priority });
    }
    this.a = state;
  }
  C(error) {
    if (/The request timed out|The network connection was lost/i.test(error)) {
      return;
    }
    error = error.replace(/See https:\/\/github\.com\/Squirrel\/Squirrel\.Mac\/issues\/182 for more information/, "This might mean the application was put on quarantine by macOS. See [this link](https://github.com/microsoft/vscode/issues/7426#issuecomment-425093469) for more information");
    this.j.notify({
      severity: Severity2.Error,
      message: error,
      source: localize(11486, null)
    });
  }
  D() {
    this.m.info(localize(11487, null));
  }
  // linux
  F(update) {
    if (!this.I()) {
      return;
    }
    const productVersion = update.productVersion;
    if (!productVersion) {
      return;
    }
    this.j.prompt(severity_default.Info, localize(11488, null), [{
      label: localize(11489, null),
      run: () => this.n.downloadUpdate()
    }, {
      label: localize(11490, null),
      run: () => {
      }
    }, {
      label: localize(11491, null),
      run: () => {
        this.h.invokeFunction((accessor) => showReleaseNotes(accessor, productVersion));
      }
    }]);
  }
  // windows fast updates
  G(update) {
    if ($m) {
      return;
    }
    if (this.w.getValue("update.enableWindowsBackgroundUpdates") && this.t.target === "user") {
      return;
    }
    if (!this.I()) {
      return;
    }
    const productVersion = update.productVersion;
    if (!productVersion) {
      return;
    }
    this.j.prompt(severity_default.Info, localize(11492, null, this.t.nameLong, productVersion), [{
      label: localize(11493, null),
      run: () => this.n.applyUpdate()
    }, {
      label: localize(11494, null),
      run: () => {
      }
    }, {
      label: localize(11495, null),
      run: () => {
        this.h.invokeFunction((accessor) => showReleaseNotes(accessor, productVersion));
      }
    }]);
  }
  // windows and mac
  H(update) {
    if (!($l && this.t.target !== "user") && !this.I()) {
      return;
    }
    const actions = [{
      label: localize(11496, null),
      run: () => this.n.quitAndInstall()
    }, {
      label: localize(11497, null),
      run: () => {
      }
    }];
    const productVersion = update.productVersion;
    if (productVersion) {
      actions.push({
        label: localize(11498, null),
        run: () => {
          this.h.invokeFunction((accessor) => showReleaseNotes(accessor, productVersion));
        }
      });
    }
    this.j.prompt(severity_default.Info, localize(11499, null, this.t.nameLong), actions, { sticky: true });
  }
  I() {
    const currentVersion = this.t.commit;
    const currentMillis = (/* @__PURE__ */ new Date()).getTime();
    const lastKnownVersion = this.g.get(
      "update/lastKnownVersion",
      -1
      /* StorageScope.APPLICATION */
    );
    if (currentVersion !== lastKnownVersion) {
      this.g.store(
        "update/lastKnownVersion",
        currentVersion,
        -1,
        1
        /* StorageTarget.MACHINE */
      );
      this.g.store(
        "update/updateNotificationTime",
        currentMillis,
        -1,
        1
        /* StorageTarget.MACHINE */
      );
    }
    const updateNotificationMillis = this.g.getNumber("update/updateNotificationTime", -1, currentMillis);
    const diffDays = (currentMillis - updateNotificationMillis) / (1e3 * 60 * 60 * 24);
    return diffDays > 5;
  }
  J() {
    $tn.registerCommand("update.check", () => this.n.checkForUpdates(true));
    $dJ.appendMenuItem($bJ.GlobalActivity, {
      group: "7_update",
      command: {
        id: "update.check",
        title: localize(11500, null)
      },
      when: $Aic.isEqualTo(
        "idle"
        /* StateType.Idle */
      )
    });
    $tn.registerCommand("update.checking", () => {
    });
    $dJ.appendMenuItem($bJ.GlobalActivity, {
      group: "7_update",
      command: {
        id: "update.checking",
        title: localize(11501, null),
        precondition: $7m.false()
      },
      when: $Aic.isEqualTo(
        "checking for updates"
        /* StateType.CheckingForUpdates */
      )
    });
    $tn.registerCommand("update.downloadNow", () => this.n.downloadUpdate());
    $dJ.appendMenuItem($bJ.GlobalActivity, {
      group: "7_update",
      command: {
        id: "update.downloadNow",
        title: localize(11502, null)
      },
      when: $Aic.isEqualTo(
        "available for download"
        /* StateType.AvailableForDownload */
      )
    });
    $tn.registerCommand("update.downloading", () => {
    });
    $dJ.appendMenuItem($bJ.GlobalActivity, {
      group: "7_update",
      command: {
        id: "update.downloading",
        title: localize(11503, null),
        precondition: $7m.false()
      },
      when: $Aic.isEqualTo(
        "downloading"
        /* StateType.Downloading */
      )
    });
    $tn.registerCommand("update.install", () => this.n.applyUpdate());
    $dJ.appendMenuItem($bJ.GlobalActivity, {
      group: "7_update",
      command: {
        id: "update.install",
        title: localize(11504, null)
      },
      when: $Aic.isEqualTo(
        "downloaded"
        /* StateType.Downloaded */
      )
    });
    $tn.registerCommand("update.updating", () => {
    });
    $dJ.appendMenuItem($bJ.GlobalActivity, {
      group: "7_update",
      command: {
        id: "update.updating",
        title: localize(11505, null),
        precondition: $7m.false()
      },
      when: $Aic.isEqualTo(
        "updating"
        /* StateType.Updating */
      )
    });
    if (this.t.quality === "stable") {
      $tn.registerCommand("update.showUpdateReleaseNotes", () => {
        if (this.n.state.type !== "ready") {
          return;
        }
        const productVersion = this.n.state.update.productVersion;
        if (productVersion) {
          this.h.invokeFunction((accessor) => showReleaseNotes(accessor, productVersion));
        }
      });
      $dJ.appendMenuItem($bJ.GlobalActivity, {
        group: "7_update",
        order: 1,
        command: {
          id: "update.showUpdateReleaseNotes",
          title: localize(11506, null)
        },
        when: $7m.and($Aic.isEqualTo(
          "ready"
          /* StateType.Ready */
        ), $Bic)
      });
    }
    $tn.registerCommand("update.restart", () => this.n.quitAndInstall());
    $dJ.appendMenuItem($bJ.GlobalActivity, {
      group: "7_update",
      order: 2,
      command: {
        id: "update.restart",
        title: localize(11507, null)
      },
      when: $Aic.isEqualTo(
        "ready"
        /* StateType.Ready */
      )
    });
    $tn.registerCommand("_update.state", () => {
      return this.a;
    });
  }
};
$Gic = __decorate([
  __param(0, $jv),
  __param(1, $Pk),
  __param(2, $PJ),
  __param(3, $Yv),
  __param(4, $az),
  __param(5, $vqb),
  __param(6, $on),
  __param(7, $Vu),
  __param(8, $O4),
  __param(9, $kl),
  __param(10, $S4)
], $Gic);
var $Hic = class $Hic2 extends $3c {
  constructor(a, b) {
    super();
    this.a = a;
    this.b = b;
    this.c();
  }
  c() {
    const quality = this.a.quality;
    const productQualityChangeHandler = this.b.options?.productQualityChangeHandler;
    if (productQualityChangeHandler && (quality === "stable" || quality === "insider")) {
      const newQuality = quality === "stable" ? "insider" : "stable";
      const commandId = `update.switchQuality.${newQuality}`;
      const isSwitchingToInsiders = newQuality === "insider";
      this.B($hJ(class SwitchQuality extends $gJ {
        constructor() {
          super({
            id: commandId,
            title: isSwitchingToInsiders ? localize(11508, null) : localize(11509, null),
            precondition: $veb,
            menu: {
              id: $bJ.GlobalActivity,
              when: $veb,
              group: "7_update"
            }
          });
        }
        async run(accessor) {
          const dialogService = accessor.get($Yv);
          const userDataSyncEnablementService = accessor.get($6Bb);
          const userDataSyncStoreManagementService = accessor.get($UBb);
          const storageService = accessor.get($jv);
          const userDataSyncWorkbenchService = accessor.get($oXb);
          const userDataSyncService = accessor.get($7Bb);
          const notificationService = accessor.get($PJ);
          try {
            const selectSettingsSyncServiceDialogShownKey = "switchQuality.selectSettingsSyncServiceDialogShown";
            const userDataSyncStore = userDataSyncStoreManagementService.userDataSyncStore;
            let userDataSyncStoreType;
            if (userDataSyncStore && isSwitchingToInsiders && userDataSyncEnablementService.isEnabled() && !storageService.getBoolean(selectSettingsSyncServiceDialogShownKey, -1, false)) {
              userDataSyncStoreType = await this.a(dialogService);
              if (!userDataSyncStoreType) {
                return;
              }
              storageService.store(
                selectSettingsSyncServiceDialogShownKey,
                true,
                -1,
                0
                /* StorageTarget.USER */
              );
              if (userDataSyncStoreType === "stable") {
                await userDataSyncStoreManagementService.switch(userDataSyncStoreType);
              }
            }
            const res = await dialogService.confirm({
              type: "info",
              message: localize(11510, null),
              detail: newQuality === "insider" ? localize(11511, null) : localize(11512, null),
              primaryButton: localize(11513, null)
            });
            if (res.confirmed) {
              const promises = [];
              if (userDataSyncService.status === "syncing") {
                promises.push(Event2.toPromise(Event2.filter(
                  userDataSyncService.onDidChangeStatus,
                  (status) => status !== "syncing"
                  /* SyncStatus.Syncing */
                )));
              }
              if (isSwitchingToInsiders && userDataSyncStoreType) {
                promises.push(userDataSyncWorkbenchService.synchroniseUserDataSyncStoreType());
              }
              await Promises.settled(promises);
              productQualityChangeHandler(newQuality);
            } else {
              if (userDataSyncStoreType) {
                storageService.remove(
                  selectSettingsSyncServiceDialogShownKey,
                  -1
                  /* StorageScope.APPLICATION */
                );
              }
            }
          } catch (error) {
            notificationService.error(error);
          }
        }
        async a(dialogService) {
          const { result } = await dialogService.prompt({
            type: Severity2.Info,
            message: localize(11514, null),
            detail: localize(11515, null),
            buttons: [
              {
                label: localize(11516, null),
                run: () => "insiders"
              },
              {
                label: localize(11517, null),
                run: () => "stable"
              }
            ],
            cancelButton: true
          });
          return result;
        }
      }));
    }
  }
};
$Hic = __decorate([
  __param(0, $Vu),
  __param(1, $M4)
], $Hic);

// out-build/vs/workbench/contrib/update/browser/update.contribution.js
var workbench = $Wn.as(Extensions2.Workbench);
workbench.registerWorkbenchContribution(
  $Fic,
  3
  /* LifecyclePhase.Restored */
);
workbench.registerWorkbenchContribution(
  $Gic,
  3
  /* LifecyclePhase.Restored */
);
workbench.registerWorkbenchContribution(
  $Hic,
  3
  /* LifecyclePhase.Restored */
);
var $Iic = class extends $gJ {
  constructor() {
    super({
      id: $hec,
      title: {
        ...localize2(11468, "Show Release Notes"),
        mnemonicTitle: localize(11462, null)
      },
      category: { value: product_default.nameShort, original: product_default.nameShort },
      f1: true,
      precondition: $Cic,
      menu: [{
        id: $bJ.MenubarHelpMenu,
        group: "1_welcome",
        order: 5,
        when: $Cic
      }]
    });
  }
  async run(accessor) {
    const instantiationService = accessor.get($Pk);
    const productService = accessor.get($Vu);
    const openerService = accessor.get($O4);
    try {
      await $Eic(instantiationService, productService.version, false);
    } catch (err) {
      if (productService.releaseNotesUrl) {
        await openerService.open(URI.parse(productService.releaseNotesUrl));
      } else {
        throw new Error(localize(11463, null, productService.nameLong));
      }
    }
  }
};
var $Jic = class extends $gJ {
  constructor() {
    super({
      id: $iec,
      title: {
        ...localize2(11469, "Open Current File as Release Notes"),
        mnemonicTitle: localize(11464, null)
      },
      category: localize2(11470, "Developer"),
      f1: true
    });
  }
  async run(accessor) {
    const instantiationService = accessor.get($Pk);
    const productService = accessor.get($Vu);
    try {
      await $Eic(instantiationService, productService.version, true);
    } catch (err) {
      throw new Error(localize(11465, null));
    }
  }
};
$hJ($Iic);
$hJ($Jic);
var $Kic = class extends $gJ {
  constructor() {
    super({
      id: "update.checkForUpdate",
      title: localize2(11471, "Check for Updates..."),
      category: { value: product_default.nameShort, original: product_default.nameShort },
      f1: true,
      precondition: $Aic.isEqualTo(
        "idle"
        /* StateType.Idle */
      )
    });
  }
  async run(accessor) {
    const updateService = accessor.get($az);
    return updateService.checkForUpdates(true);
  }
};
var DownloadUpdateAction = class extends $gJ {
  constructor() {
    super({
      id: "update.downloadUpdate",
      title: localize2(11472, "Download Update"),
      category: { value: product_default.nameShort, original: product_default.nameShort },
      f1: true,
      precondition: $Aic.isEqualTo(
        "available for download"
        /* StateType.AvailableForDownload */
      )
    });
  }
  async run(accessor) {
    await accessor.get($az).downloadUpdate();
  }
};
var InstallUpdateAction = class extends $gJ {
  constructor() {
    super({
      id: "update.installUpdate",
      title: localize2(11473, "Install Update"),
      category: { value: product_default.nameShort, original: product_default.nameShort },
      f1: true,
      precondition: $Aic.isEqualTo(
        "downloaded"
        /* StateType.Downloaded */
      )
    });
  }
  async run(accessor) {
    await accessor.get($az).applyUpdate();
  }
};
var RestartToUpdateAction = class extends $gJ {
  constructor() {
    super({
      id: "update.restartToUpdate",
      title: localize2(11474, "Restart to Update"),
      category: { value: product_default.nameShort, original: product_default.nameShort },
      f1: true,
      precondition: $Aic.isEqualTo(
        "ready"
        /* StateType.Ready */
      )
    });
  }
  async run(accessor) {
    await accessor.get($az).quitAndInstall();
  }
};
var DownloadAction = class _DownloadAction extends $gJ {
  static {
    this.ID = "workbench.action.download";
  }
  constructor() {
    super({
      id: _DownloadAction.ID,
      title: localize2(11475, "Download {0}", product_default.nameLong),
      precondition: $7m.and($veb, $Dic),
      // Only show when running in a web browser and a download url is available
      f1: true,
      menu: [{
        id: $bJ.StatusBarWindowIndicatorMenu,
        when: $7m.and($veb, $Dic)
      }]
    });
  }
  run(accessor) {
    const productService = accessor.get($Vu);
    const openerService = accessor.get($O4);
    if (productService.downloadUrl) {
      openerService.open(URI.parse(productService.downloadUrl));
    }
  }
};
$hJ(DownloadAction);
$hJ($Kic);
$hJ(DownloadUpdateAction);
$hJ(InstallUpdateAction);
$hJ(RestartToUpdateAction);
if ($l) {
  class DeveloperApplyUpdateAction extends $gJ {
    constructor() {
      super({
        id: "_update.applyupdate",
        title: localize2(11476, "Apply Update..."),
        category: $qn.Developer,
        f1: true,
        precondition: $Aic.isEqualTo(
          "idle"
          /* StateType.Idle */
        )
      });
    }
    async run(accessor) {
      const updateService = accessor.get($az);
      const fileDialogService = accessor.get($1v);
      const updatePath = await fileDialogService.showOpenDialog({
        title: localize(11466, null),
        filters: [{ name: "Setup", extensions: ["exe"] }],
        canSelectFiles: true,
        openLabel: $7t(localize(11467, null))
      });
      if (!updatePath || !updatePath[0]) {
        return;
      }
      await updateService._applySpecificUpdate(updatePath[0].fsPath);
    }
  }
  $hJ(DeveloperApplyUpdateAction);
}

// out-build/vs/workbench/contrib/surveys/browser/nps.contribution.js
var PROBABILITY = 0.15;
var SESSION_COUNT_KEY = "nps/sessionCount";
var LAST_SESSION_DATE_KEY = "nps/lastSessionDate";
var SKIP_VERSION_KEY = "nps/skipVersion";
var IS_CANDIDATE_KEY = "nps/isCandidate";
var NPSContribution = class NPSContribution2 {
  constructor(storageService, notificationService, telemetryService, openerService, productService) {
    if (!productService.npsSurveyUrl) {
      return;
    }
    const skipVersion = storageService.get(SKIP_VERSION_KEY, -1, "");
    if (skipVersion) {
      return;
    }
    const date = (/* @__PURE__ */ new Date()).toDateString();
    const lastSessionDate = storageService.get(LAST_SESSION_DATE_KEY, -1, (/* @__PURE__ */ new Date(0)).toDateString());
    if (date === lastSessionDate) {
      return;
    }
    const sessionCount = (storageService.getNumber(SESSION_COUNT_KEY, -1, 0) || 0) + 1;
    storageService.store(
      LAST_SESSION_DATE_KEY,
      date,
      -1,
      0
      /* StorageTarget.USER */
    );
    storageService.store(
      SESSION_COUNT_KEY,
      sessionCount,
      -1,
      0
      /* StorageTarget.USER */
    );
    if (sessionCount < 9) {
      return;
    }
    const isCandidate = storageService.getBoolean(IS_CANDIDATE_KEY, -1, false) || Math.random() < PROBABILITY;
    storageService.store(
      IS_CANDIDATE_KEY,
      isCandidate,
      -1,
      0
      /* StorageTarget.USER */
    );
    if (!isCandidate) {
      storageService.store(
        SKIP_VERSION_KEY,
        productService.version,
        -1,
        0
        /* StorageTarget.USER */
      );
      return;
    }
    notificationService.prompt(Severity2.Info, localize(9931, null), [{
      label: localize(9932, null),
      run: () => {
        openerService.open(URI.parse(`${productService.npsSurveyUrl}?o=${encodeURIComponent($hc)}&v=${encodeURIComponent(productService.version)}&m=${encodeURIComponent(telemetryService.machineId)}`));
        storageService.store(
          IS_CANDIDATE_KEY,
          false,
          -1,
          0
          /* StorageTarget.USER */
        );
        storageService.store(
          SKIP_VERSION_KEY,
          productService.version,
          -1,
          0
          /* StorageTarget.USER */
        );
      }
    }, {
      label: localize(9933, null),
      run: () => storageService.store(
        SESSION_COUNT_KEY,
        sessionCount - 3,
        -1,
        0
        /* StorageTarget.USER */
      )
    }, {
      label: localize(9934, null),
      run: () => {
        storageService.store(
          IS_CANDIDATE_KEY,
          false,
          -1,
          0
          /* StorageTarget.USER */
        );
        storageService.store(
          SKIP_VERSION_KEY,
          productService.version,
          -1,
          0
          /* StorageTarget.USER */
        );
      }
    }], { sticky: true, priority: NotificationPriority.URGENT });
  }
};
NPSContribution = __decorate([
  __param(0, $jv),
  __param(1, $PJ),
  __param(2, $zv),
  __param(3, $O4),
  __param(4, $Vu)
], NPSContribution);
if ($z === "en") {
  const workbenchRegistry10 = $Wn.as(Extensions2.Workbench);
  workbenchRegistry10.registerWorkbenchContribution(
    NPSContribution,
    3
    /* LifecyclePhase.Restored */
  );
}

// out-build/vs/workbench/contrib/surveys/browser/languageSurveys.contribution.js
var LanguageSurvey = class extends $3c {
  constructor(data, storageService, notificationService, telemetryService, languageService, textFileService, openerService, productService) {
    super();
    const SESSION_COUNT_KEY2 = `${data.surveyId}.sessionCount`;
    const LAST_SESSION_DATE_KEY2 = `${data.surveyId}.lastSessionDate`;
    const SKIP_VERSION_KEY2 = `${data.surveyId}.skipVersion`;
    const IS_CANDIDATE_KEY2 = `${data.surveyId}.isCandidate`;
    const EDITED_LANGUAGE_COUNT_KEY = `${data.surveyId}.editedCount`;
    const EDITED_LANGUAGE_DATE_KEY = `${data.surveyId}.editedDate`;
    const skipVersion = storageService.get(SKIP_VERSION_KEY2, -1, "");
    if (skipVersion) {
      return;
    }
    const date = (/* @__PURE__ */ new Date()).toDateString();
    if (storageService.getNumber(EDITED_LANGUAGE_COUNT_KEY, -1, 0) < data.editCount) {
      const onModelsSavedWorker = this.B(new $0h((models) => {
        models.forEach((m) => {
          if (m.getLanguageId() === data.languageId && date !== storageService.get(
            EDITED_LANGUAGE_DATE_KEY,
            -1
            /* StorageScope.APPLICATION */
          )) {
            const editedCount = storageService.getNumber(EDITED_LANGUAGE_COUNT_KEY, -1, 0) + 1;
            storageService.store(
              EDITED_LANGUAGE_COUNT_KEY,
              editedCount,
              -1,
              0
              /* StorageTarget.USER */
            );
            storageService.store(
              EDITED_LANGUAGE_DATE_KEY,
              date,
              -1,
              0
              /* StorageTarget.USER */
            );
          }
        });
      }, 250));
      this.B(textFileService.files.onDidSave((e) => onModelsSavedWorker.work(e.model)));
    }
    const lastSessionDate = storageService.get(LAST_SESSION_DATE_KEY2, -1, (/* @__PURE__ */ new Date(0)).toDateString());
    if (date === lastSessionDate) {
      return;
    }
    const sessionCount = storageService.getNumber(SESSION_COUNT_KEY2, -1, 0) + 1;
    storageService.store(
      LAST_SESSION_DATE_KEY2,
      date,
      -1,
      0
      /* StorageTarget.USER */
    );
    storageService.store(
      SESSION_COUNT_KEY2,
      sessionCount,
      -1,
      0
      /* StorageTarget.USER */
    );
    if (sessionCount < 9) {
      return;
    }
    if (storageService.getNumber(EDITED_LANGUAGE_COUNT_KEY, -1, 0) < data.editCount) {
      return;
    }
    const isCandidate = storageService.getBoolean(IS_CANDIDATE_KEY2, -1, false) || Math.random() < data.userProbability;
    storageService.store(
      IS_CANDIDATE_KEY2,
      isCandidate,
      -1,
      0
      /* StorageTarget.USER */
    );
    if (!isCandidate) {
      storageService.store(
        SKIP_VERSION_KEY2,
        productService.version,
        -1,
        0
        /* StorageTarget.USER */
      );
      return;
    }
    notificationService.prompt(Severity2.Info, localize(9927, null, languageService.getLanguageName(data.languageId) ?? data.languageId), [{
      label: localize(9928, null),
      run: () => {
        telemetryService.publicLog(`${data.surveyId}.survey/takeShortSurvey`);
        openerService.open(URI.parse(`${data.surveyUrl}?o=${encodeURIComponent($hc)}&v=${encodeURIComponent(productService.version)}&m=${encodeURIComponent(telemetryService.machineId)}`));
        storageService.store(
          IS_CANDIDATE_KEY2,
          false,
          -1,
          0
          /* StorageTarget.USER */
        );
        storageService.store(
          SKIP_VERSION_KEY2,
          productService.version,
          -1,
          0
          /* StorageTarget.USER */
        );
      }
    }, {
      label: localize(9929, null),
      run: () => {
        telemetryService.publicLog(`${data.surveyId}.survey/remindMeLater`);
        storageService.store(
          SESSION_COUNT_KEY2,
          sessionCount - 3,
          -1,
          0
          /* StorageTarget.USER */
        );
      }
    }, {
      label: localize(9930, null),
      isSecondary: true,
      run: () => {
        telemetryService.publicLog(`${data.surveyId}.survey/dontShowAgain`);
        storageService.store(
          IS_CANDIDATE_KEY2,
          false,
          -1,
          0
          /* StorageTarget.USER */
        );
        storageService.store(
          SKIP_VERSION_KEY2,
          productService.version,
          -1,
          0
          /* StorageTarget.USER */
        );
      }
    }], { sticky: true });
  }
};
var LanguageSurveysContribution = class LanguageSurveysContribution2 {
  constructor(a, b, c, d, f, g, h3, i2) {
    this.a = a;
    this.b = b;
    this.c = c;
    this.d = d;
    this.f = f;
    this.g = g;
    this.h = h3;
    this.i = i2;
    this.j();
  }
  async j() {
    if (!this.g.surveys) {
      return;
    }
    await this.i.whenInstalledExtensionsRegistered();
    this.g.surveys.filter((surveyData) => surveyData.surveyId && surveyData.editCount && surveyData.languageId && surveyData.surveyUrl && surveyData.userProbability).map((surveyData) => new LanguageSurvey(surveyData, this.a, this.b, this.c, this.h, this.d, this.f, this.g));
  }
};
LanguageSurveysContribution = __decorate([
  __param(0, $jv),
  __param(1, $PJ),
  __param(2, $zv),
  __param(3, $cK),
  __param(4, $O4),
  __param(5, $Vu),
  __param(6, $1E),
  __param(7, $wN)
], LanguageSurveysContribution);
if ($z === "en") {
  const workbenchRegistry10 = $Wn.as(Extensions2.Workbench);
  workbenchRegistry10.registerWorkbenchContribution(
    LanguageSurveysContribution,
    3
    /* LifecyclePhase.Restored */
  );
}

// out-build/vs/workbench/contrib/welcomeGettingStarted/browser/gettingStartedColors.js
var $Lic = $5n("welcomePage.background", null, localize(11866, null));
var $Mic = $5n("welcomePage.tileBackground", { dark: $Qo, light: $Qo, hcDark: "#000", hcLight: $Qo }, localize(11867, null));
var $Nic = $5n("welcomePage.tileHoverBackground", { dark: $9n($Qo, 0.2), light: $8n($Qo, 0.1), hcDark: null, hcLight: null }, localize(11868, null));
var $Oic = $5n("welcomePage.tileBorder", { dark: "#ffffff1a", light: "#0000001a", hcDark: $ko, hcLight: $ko }, localize(11869, null));
var $Pic = $5n("welcomePage.progress.background", $xq, localize(11870, null));
var $Qic = $5n("welcomePage.progress.foreground", $no, localize(11871, null));
var $Ric = $5n("walkthrough.stepTitle.foreground", { light: "#000000", dark: "#ffffff", hcDark: null, hcLight: null }, localize(11872, null));

// out-build/vs/workbench/contrib/welcomeGettingStarted/browser/gettingStartedDetailsRenderer.js
var $Sic = class $Sic2 {
  constructor(c, d, f, g) {
    this.c = c;
    this.d = d;
    this.f = f;
    this.g = g;
    this.a = new $Ec();
    this.b = new $Ec();
  }
  async renderMarkdown(path, base) {
    const content = await this.i(path, base);
    const nonce = $ps();
    const colorMap = $YE.getColorMap();
    const css = colorMap ? $4Gb(colorMap) : "";
    const inDev = document.location.protocol === "http:";
    const imgSrcCsp = inDev ? "img-src https: data: http:" : "img-src https: data:";
    return `<!DOCTYPE html>
		<html>
			<head>
				<meta http-equiv="Content-type" content="text/html;charset=UTF-8">
				<meta http-equiv="Content-Security-Policy" content="default-src 'none'; ${imgSrcCsp}; media-src https:; script-src 'nonce-${nonce}'; style-src 'nonce-${nonce}';">
				<style nonce="${nonce}">
					${$Pdc}
					${css}
					body > img {
						align-self: flex-start;
					}
					body > img[centered] {
						align-self: center;
					}
					body {
						display: flex;
						flex-direction: column;
						padding: 0;
						height: inherit;
					}
					.theme-picker-row {
						display: flex;
						justify-content: center;
						gap: 32px;
					}
					checklist {
						display: flex;
						gap: 32px;
						flex-direction: column;
					}
					checkbox {
						display: flex;
						flex-direction: column;
						align-items: center;
						margin: 5px;
						cursor: pointer;
					}
					checkbox > img {
						margin-bottom: 8px !important;
					}
					checkbox.checked > img {
						box-sizing: border-box;
					}
					checkbox.checked > img {
						outline: 2px solid var(--vscode-focusBorder);
						outline-offset: 4px;
						border-radius: 4px;
					}
					.theme-picker-link {
						margin-top: 16px;
						color: var(--vscode-textLink-foreground);
					}
					blockquote > p:first-child {
						margin-top: 0;
					}
					body > * {
						margin-block-end: 0.25em;
						margin-block-start: 0.25em;
					}
					vertically-centered {
						padding-top: 5px;
						padding-bottom: 5px;
						display: flex;
						justify-content: center;
						flex-direction: column;
					}
					html {
						height: 100%;
						padding-right: 32px;
					}
					h1 {
						font-size: 19.5px;
					}
					h2 {
						font-size: 18.5px;
					}
				</style>
			</head>
			<body>
				<vertically-centered>
					${content}
				</vertically-centered>
			</body>
			<script nonce="${nonce}">
				const vscode = acquireVsCodeApi();

				document.querySelectorAll('[when-checked]').forEach(el => {
					el.addEventListener('click', () => {
						vscode.postMessage(el.getAttribute('when-checked'));
					});
				});

				let ongoingLayout = undefined;
				const doLayout = () => {
					document.querySelectorAll('vertically-centered').forEach(element => {
						element.style.marginTop = Math.max((document.body.clientHeight - element.scrollHeight) * 3/10, 0) + 'px';
					});
					ongoingLayout = undefined;
				};

				const layout = () => {
					if (ongoingLayout) {
						clearTimeout(ongoingLayout);
					}
					ongoingLayout = setTimeout(doLayout, 0);
				};

				layout();

				document.querySelectorAll('img').forEach(element => {
					element.onload = layout;
				})

				window.addEventListener('message', event => {
					if (event.data.layoutMeNow) {
						layout();
					}
					if (event.data.enabledContextKeys) {
						document.querySelectorAll('.checked').forEach(element => element.classList.remove('checked'))
						for (const key of event.data.enabledContextKeys) {
							document.querySelectorAll('[checked-on="' + key + '"]').forEach(element => element.classList.add('checked'))
						}
					}
				});
		</script>
		</html>`;
  }
  async renderSVG(path) {
    const content = await this.h(path);
    const nonce = $ps();
    const colorMap = $YE.getColorMap();
    const css = colorMap ? $4Gb(colorMap) : "";
    return `<!DOCTYPE html>
		<html>
			<head>
				<meta http-equiv="Content-type" content="text/html;charset=UTF-8">
				<meta http-equiv="Content-Security-Policy" content="default-src 'none'; img-src data:; style-src 'nonce-${nonce}';">
				<style nonce="${nonce}">
					${$Pdc}
					${css}
					svg {
						position: fixed;
						height: 100%;
						width: 80%;
						left: 50%;
						top: 50%;
						max-width: 530px;
						min-width: 350px;
						transform: translate(-50%,-50%);
					}
				</style>
			</head>
			<body>
				${content}
			</body>
		</html>`;
  }
  async h(path) {
    if (!this.b.has(path)) {
      const contents = await this.j(path, false);
      this.b.set(path, contents);
    }
    return $Kg(this.b.get(path));
  }
  async i(path, base) {
    if (!this.a.has(path)) {
      const contents = await this.j(path);
      const markdownContents = await $Qdc(transformUris(contents, base), this.f, this.g, { allowUnknownProtocols: true });
      this.a.set(path, markdownContents);
    }
    return $Kg(this.a.get(path));
  }
  async j(path, useModuleId = true) {
    try {
      const moduleId = JSON.parse(path.query).moduleId;
      if (useModuleId && moduleId) {
        const contents = await new Promise((resolve, reject) => {
          const provider = $Shc.getProvider(moduleId);
          if (!provider) {
            reject(`Getting started: no provider registered for ${moduleId}`);
          } else {
            resolve(provider());
          }
        });
        return contents;
      }
    } catch {
    }
    try {
      const localizedPath = path.with({ path: path.path.replace(/\.md$/, `.nls.${$z}.md`) });
      const generalizedLocale = $z?.replace(/-.*$/, "");
      const generalizedLocalizedPath = path.with({ path: path.path.replace(/\.md$/, `.nls.${generalizedLocale}.md`) });
      const fileExists = (file) => this.c.stat(file).then((stat) => !!stat.size).catch(() => false);
      const [localizedFileExists, generalizedLocalizedFileExists] = await Promise.all([
        fileExists(localizedPath),
        fileExists(generalizedLocalizedPath)
      ]);
      const bytes = await this.c.readFile(localizedFileExists ? localizedPath : generalizedLocalizedFileExists ? generalizedLocalizedPath : path);
      return bytes.value.toString();
    } catch (e) {
      this.d.error("Error reading markdown document at `" + path + "`: " + e);
      return "";
    }
  }
};
$Sic = __decorate([
  __param(0, $km),
  __param(1, $PJ),
  __param(2, $wN),
  __param(3, $1E)
], $Sic);
var transformUri = (src, base) => {
  const path = $vh(base, src);
  return $HJb(path).toString(true);
};
var transformUris = (content, base) => content.replace(/src="([^"]*)"/g, (_, src) => {
  if (src.startsWith("https://")) {
    return `src="${src}"`;
  }
  return `src="${transformUri(src, base)}"`;
}).replace(/!\[([^\]]*)\]\(([^)]*)\)/g, (_, title, src) => {
  if (src.startsWith("https://")) {
    return `![${title}](${src})`;
  }
  return `![${title}](${transformUri(src, base)})`;
});

// out-build/vs/workbench/contrib/welcomeGettingStarted/browser/gettingStartedIcons.js
var $Tic = $9r("getting-started-step-unchecked", $6l.circleLargeOutline, localize(11910, null));
var $Uic = $9r("getting-started-step-checked", $6l.passFilled, localize(11911, null));

// out-build/vs/workbench/contrib/welcomeGettingStarted/browser/gettingStartedInput.js
var $Vic = "workbench.editors.gettingStartedInput";
var $Wic = class _$Wic extends $nG {
  static {
    this.ID = $Vic;
  }
  static {
    this.RESOURCE = URI.from({ scheme: Schemas.walkThrough, authority: "vscode_getting_started_page" });
  }
  get typeId() {
    return _$Wic.ID;
  }
  get editorId() {
    return this.typeId;
  }
  toUntyped() {
    return {
      resource: _$Wic.RESOURCE,
      options: {
        override: _$Wic.ID,
        pinned: false
      }
    };
  }
  get resource() {
    return _$Wic.RESOURCE;
  }
  matches(other) {
    if (super.matches(other)) {
      return true;
    }
    if (other instanceof _$Wic) {
      return other.selectedCategory === this.selectedCategory;
    }
    return false;
  }
  constructor(options3) {
    super();
    this.a = options3.selectedCategory;
    this.b = options3.selectedStep;
    this.c = !!options3.showTelemetryNotice;
    this.h = options3.showWelcome ?? true;
    this.m = options3.walkthroughPageTitle;
  }
  getName() {
    return this.walkthroughPageTitle ? localize(11912, null, this.walkthroughPageTitle) : localize(11913, null);
  }
  get selectedCategory() {
    return this.a;
  }
  set selectedCategory(selectedCategory) {
    this.a = selectedCategory;
    this.g.fire();
  }
  get selectedStep() {
    return this.b;
  }
  set selectedStep(selectedStep) {
    this.b = selectedStep;
  }
  get showTelemetryNotice() {
    return this.c;
  }
  set showTelemetryNotice(value) {
    this.c = value;
  }
  get showWelcome() {
    return this.h;
  }
  set showWelcome(value) {
    this.h = value;
  }
  get walkthroughPageTitle() {
    return this.m;
  }
  set walkthroughPageTitle(value) {
    this.m = value;
  }
};

// out-build/vs/workbench/contrib/welcomeGettingStarted/browser/startupPage.js
var $Xic = "workbench.welcomePage.restorableWalkthroughs";
var configurationKey = "workbench.startupEditor";
var oldConfigurationKey = "workbench.welcome.enabled";
var telemetryOptOutStorageKey = "workbench.telemetryOptOutShown";
var $Yic = class $Yic2 {
  static {
    this.ID = "workbench.contrib.startupPageEditorResolver";
  }
  constructor(a, editorResolverService) {
    this.a = a;
    editorResolverService.registerEditor(`${$Wic.RESOURCE.scheme}:/**`, {
      id: $Wic.ID,
      label: localize(11918, null),
      priority: RegisteredEditorPriority.builtin
    }, {
      singlePerResource: false,
      canSupportResource: (uri) => uri.scheme === $Wic.RESOURCE.scheme
    }, {
      createEditorInput: ({ resource, options: options3 }) => {
        return {
          editor: this.a.createInstance($Wic, options3),
          options: {
            ...options3,
            pinned: false
          }
        };
      }
    });
  }
};
$Yic = __decorate([
  __param(0, $Pk),
  __param(1, $4L)
], $Yic);
var $Zic = class $Zic2 extends $3c {
  static {
    this.ID = "workbench.contrib.startupPageRunner";
  }
  constructor(a, b, c, f, g, h3, j, m, n, r2, s, t, u) {
    super();
    this.a = a;
    this.b = b;
    this.c = c;
    this.f = f;
    this.g = g;
    this.h = h3;
    this.j = j;
    this.m = m;
    this.n = n;
    this.r = r2;
    this.s = s;
    this.t = t;
    this.u = u;
    this.w().then(void 0, $gb);
    this.B(this.b.onDidCloseEditor((e) => {
      if (e.editor instanceof $Wic) {
        e.editor.selectedCategory = void 0;
        e.editor.selectedStep = void 0;
      }
    }));
  }
  async w() {
    await this.h.when(
      3
      /* LifecyclePhase.Restored */
    );
    if (this.m.enableTelemetry && this.m.showTelemetryOptOut && $kw(this.a) !== 0 && !this.r.skipWelcome && !this.s.get(
      telemetryOptOutStorageKey,
      0
      /* StorageScope.PROFILE */
    )) {
      this.s.store(
        telemetryOptOutStorageKey,
        true,
        0,
        0
        /* StorageTarget.USER */
      );
      await this.C(true);
      return;
    }
    if (this.y()) {
      return;
    }
    const enabled = isStartupPageEnabled(this.a, this.g, this.r);
    if (enabled && this.h.startupKind !== 3) {
      const hasBackups = await this.c.hasBackups();
      if (hasBackups) {
        return;
      }
      if (!this.b.activeEditor || this.j.openedDefaultEditors) {
        const startupEditorSetting = this.a.inspect(configurationKey);
        const isStartupEditorReadme = startupEditorSetting.value === "readme";
        const isStartupEditorUserReadme = startupEditorSetting.userValue === "readme";
        const isStartupEditorDefaultReadme = startupEditorSetting.defaultValue === "readme";
        if (isStartupEditorReadme && (!isStartupEditorUserReadme || !isStartupEditorDefaultReadme)) {
          this.t.warn(`Warning: 'workbench.startupEditor: readme' setting ignored due to being set somewhere other than user or default settings (user=${startupEditorSetting.userValue}, default=${startupEditorSetting.defaultValue})`);
        }
        const openWithReadme = isStartupEditorReadme && (isStartupEditorUserReadme || isStartupEditorDefaultReadme);
        if (openWithReadme) {
          await this.z();
        } else if (startupEditorSetting.value === "welcomePage" || startupEditorSetting.value === "welcomePageInEmptyWorkbench") {
          await this.C();
        } else if (startupEditorSetting.value === "terminal") {
          this.n.executeCommand(
            "workbench.action.createTerminalEditor"
            /* TerminalCommandId.CreateTerminalEditor */
          );
        }
      }
    }
  }
  y() {
    const toRestore = this.s.get(
      $Xic,
      0
      /* StorageScope.PROFILE */
    );
    if (!toRestore) {
      return false;
    } else {
      const restoreData = JSON.parse(toRestore);
      const currentWorkspace = this.g.getWorkspace();
      if (restoreData.folder === $4k.id || restoreData.folder === currentWorkspace.folders[0].uri.toString()) {
        const options3 = { selectedCategory: restoreData.category, selectedStep: restoreData.step, pinned: false };
        this.b.openEditor({
          resource: $Wic.RESOURCE,
          options: options3
        });
        this.s.remove(
          $Xic,
          0
          /* StorageScope.PROFILE */
        );
        return true;
      }
    }
    return false;
  }
  async z() {
    const readmes = $Mb(await Promise.all(this.g.getWorkspace().folders.map(async (folder) => {
      const folderUri = folder.uri;
      const folderStat = await this.f.resolve(folderUri).catch($gb);
      const files = folderStat?.children ? folderStat.children.map((child) => child.name).sort() : [];
      const file = files.find((file2) => file2.toLowerCase() === "readme.md") || files.find((file2) => file2.toLowerCase().startsWith("readme"));
      if (file) {
        return $vh(folderUri, file);
      } else {
        return void 0;
      }
    })));
    if (!this.b.activeEditor) {
      if (readmes.length) {
        const isMarkDown = (readme) => readme.path.toLowerCase().endsWith(".md");
        await Promise.all([
          this.n.executeCommand("markdown.showPreview", null, readmes.filter(isMarkDown), { locked: true }).catch((error) => {
            this.u.error(localize(11919, null, error.message));
          }),
          this.b.openEditors(readmes.filter((readme) => !isMarkDown(readme)).map((readme) => ({ resource: readme })))
        ]);
      } else {
        await this.C();
      }
    }
  }
  async C(showTelemetryNotice) {
    const startupEditorTypeID = $Vic;
    const editor = this.b.activeEditor;
    if (editor?.typeId === startupEditorTypeID || this.b.editors.some((e) => e.typeId === startupEditorTypeID)) {
      return;
    }
    const options3 = editor ? { pinned: false, index: 0, showTelemetryNotice } : { pinned: false, showTelemetryNotice };
    if (startupEditorTypeID === $Vic) {
      this.b.openEditor({
        resource: $Wic.RESOURCE,
        options: options3
      });
    }
  }
};
$Zic = __decorate([
  __param(0, $kl),
  __param(1, $mJ),
  __param(2, $yG),
  __param(3, $km),
  __param(4, $Zk),
  __param(5, $KL),
  __param(6, $Vlb),
  __param(7, $Vu),
  __param(8, $sn),
  __param(9, $US),
  __param(10, $jv),
  __param(11, $wn),
  __param(12, $PJ)
], $Zic);
function isStartupPageEnabled(configurationService, contextService, environmentService) {
  if (environmentService.skipWelcome) {
    return false;
  }
  const startupEditor = configurationService.inspect(configurationKey);
  if (!startupEditor.userValue && !startupEditor.workspaceValue) {
    const welcomeEnabled = configurationService.inspect(oldConfigurationKey);
    if (welcomeEnabled.value !== void 0 && welcomeEnabled.value !== null) {
      return welcomeEnabled.value;
    }
  }
  return startupEditor.value === "welcomePage" || startupEditor.value === "readme" && (startupEditor.userValue === "readme" || startupEditor.defaultValue === "readme") || contextService.getWorkbenchState() === 1 && startupEditor.value === "welcomePageInEmptyWorkbench" || startupEditor.value === "terminal";
}

// out-build/vs/workbench/contrib/welcomeGettingStarted/browser/gettingStartedList.js
var $1ic = class extends $3c {
  constructor(u) {
    super();
    this.u = u;
    this.c = new $ze();
    this.f = this.c.event;
    this.r = false;
    this.t = /* @__PURE__ */ new Set();
    this.s = u.contextService;
    this.m = void 0;
    this.itemCount = 0;
    this.h = $("ul");
    this.j = this.B(new $CZ(this.h, {}));
    this.B(this.f(() => this.j.scanDomNode()));
    this.g = $(".index-list." + u.klass, {}, $("h2", {}, u.title), this.j.getDomNode());
    this.B(this.s.onDidChangeContext((e) => {
      if (e.affectsSome(this.t)) {
        this.rerender();
      }
    }));
  }
  getDomElement() {
    return this.g;
  }
  layout(size) {
    this.j.scanDomNode();
  }
  onDidChange(listener) {
    this.B(this.f(listener));
  }
  register(d) {
    if (this.r) {
      d.dispose();
    } else {
      this.B(d);
    }
  }
  dispose() {
    this.r = true;
    super.dispose();
  }
  setLimit(limit) {
    this.u.limit = limit;
    this.setEntries(this.m);
  }
  rerender() {
    this.setEntries(this.m);
  }
  setEntries(entries2) {
    let entryList = entries2 ?? [];
    this.itemCount = 0;
    const ranker = this.u.rankElement;
    if (ranker) {
      entryList = entryList.filter((e) => ranker(e) !== null);
      entryList.sort((a, b) => ranker(b) - ranker(a));
    }
    const activeEntries = entryList.filter((e) => !e.when || this.s.contextMatchesRules(e.when));
    const limitedEntries = activeEntries.slice(0, this.u.limit);
    const toRender = limitedEntries.map((e) => e.id);
    if (this.m === entries2 && $zb(toRender, this.n)) {
      return;
    }
    this.m = entries2;
    this.t.clear();
    entryList.forEach((e) => {
      const keys = e.when?.keys();
      keys?.forEach((key2) => this.t.add(key2));
    });
    this.n = toRender;
    this.itemCount = limitedEntries.length;
    while (this.h.firstChild) {
      this.h.firstChild.remove();
    }
    this.itemCount = limitedEntries.length;
    for (const entry of limitedEntries) {
      const rendered = this.u.renderElement(entry);
      this.h.appendChild(rendered);
    }
    if (activeEntries.length > limitedEntries.length && this.u.more) {
      this.h.appendChild(this.u.more);
    } else if (entries2 !== void 0 && this.itemCount === 0 && this.u.empty) {
      this.h.appendChild(this.u.empty);
    } else if (this.u.footer) {
      this.h.appendChild(this.u.footer);
    }
    this.c.fire();
  }
};

// out-build/vs/workbench/contrib/welcomeGettingStarted/browser/gettingStarted.js
var $4ic_1;
var SLIDE_TRANSITION_TIME_MS = 250;
var configurationKey2 = "workbench.startupEditor";
var $2ic = new $nn("allWalkthroughsHidden", false);
var $3ic = new $nn("inWelcome", false);
var parsedStartEntries = $Uhc.map((e, i2) => ({
  command: e.content.command,
  description: e.description,
  icon: { type: "icon", icon: e.icon },
  id: e.id,
  order: i2,
  title: e.title,
  when: $7m.deserialize(e.when) ?? $7m.true()
}));
var REDUCED_MOTION_KEY = "workbench.welcomePage.preferReducedMotion";
var $4ic = class $4ic2 extends $5tb {
  static {
    $4ic_1 = this;
  }
  static {
    this.ID = "gettingStartedPage";
  }
  constructor(group2, zb, Ab, Bb, Cb, Db, telemetryService, Eb, Fb, Gb, n, Ib, Jb, Kb, Lb, Mb, contextService, Nb, Ob, Pb, Qb, Rb, Sb, Tb) {
    super($4ic_1.ID, group2, telemetryService, n, Ib);
    this.zb = zb;
    this.Ab = Ab;
    this.Bb = Bb;
    this.Cb = Cb;
    this.Db = Db;
    this.Eb = Eb;
    this.Fb = Fb;
    this.Gb = Gb;
    this.n = n;
    this.Ib = Ib;
    this.Jb = Jb;
    this.Kb = Kb;
    this.Lb = Lb;
    this.Mb = Mb;
    this.Nb = Nb;
    this.Ob = Ob;
    this.Pb = Pb;
    this.Qb = Qb;
    this.Rb = Rb;
    this.Sb = Sb;
    this.Tb = Tb;
    this.g = Promise.resolve();
    this.j = new $2c();
    this.m = new $2c();
    this.r = new $2c();
    this.u = new $2c();
    this.jb = new $Ph();
    this.mb = false;
    this.yb = true;
    this.dc = void 0;
    this.ec = void 0;
    this.kb = $(".gettingStartedContainer", {
      role: "document",
      tabindex: 0,
      "aria-label": localize(11830, null)
    });
    this.tb = $(".getting-started-media");
    this.tb.id = $ps();
    this.xb = this.B(new $2c());
    this.wb = new $Sic(this.Fb, this.Lb, this.Jb, this.Eb);
    this.lb = this.B(contextService.createScoped(this.kb));
    $3ic.bindTo(this.lb).set(true);
    this.db = this.Cb.getWalkthroughs();
    this.B(this.j);
    this.jb = new $Ph();
    const rerender = () => {
      this.db = this.Cb.getWalkthroughs();
      if (this.eb) {
        const existingSteps = this.eb.steps.map((step) => step.id);
        const newCategory = this.db.find((category8) => this.eb?.id === category8.id);
        if (newCategory) {
          const newSteps = newCategory.steps.map((step) => step.id);
          if (!$zb(newSteps, existingSteps)) {
            this.jb.queue(() => this.kc());
          }
        }
      } else {
        this.jb.queue(() => this.kc());
      }
    };
    this.B(this.Cb.onDidAddWalkthrough(rerender));
    this.B(this.Cb.onDidRemoveWalkthrough(rerender));
    this.cb = this.Ob.getRecentlyOpened();
    this.B(Ob.onDidChangeRecentlyOpened(() => {
      this.cb = Ob.getRecentlyOpened();
      rerender();
    }));
    this.B(this.Cb.onDidChangeWalkthrough((category8) => {
      const ourCategory = this.db.find((c) => c.id === category8.id);
      if (!ourCategory) {
        return;
      }
      ourCategory.title = category8.title;
      ourCategory.description = category8.description;
      this.kb.querySelectorAll(`[x-category-title-for="${category8.id}"]`).forEach((step) => step.innerText = ourCategory.title);
      this.kb.querySelectorAll(`[x-category-description-for="${category8.id}"]`).forEach((step) => step.innerText = ourCategory.description);
    }));
    this.B(this.Cb.onDidProgressStep((step) => {
      const category8 = this.db.find((category9) => category9.id === step.category);
      if (!category8) {
        throw Error("Could not find category with ID: " + step.category);
      }
      const ourStep = category8.steps.find((_step) => _step.id === step.id);
      if (!ourStep) {
        throw Error("Could not find step with ID: " + step.id);
      }
      const stats = this.Vb(category8);
      if (!ourStep.done && stats.stepsComplete === stats.stepsTotal - 1) {
        this.Yb(category8.id);
      }
      this.B(this.Db.onDidChangeConfiguration((e) => {
        if (e.affectsConfiguration(REDUCED_MOTION_KEY)) {
          this.kb.classList.toggle("animatable", this.Ub());
        }
      }));
      ourStep.done = step.done;
      if (category8.id === this.eb?.id) {
        const badgeelements = $Kg(this.window.document.querySelectorAll(`[data-done-step-id="${step.id}"]`));
        badgeelements.forEach((badgeelement) => {
          if (step.done) {
            badgeelement.setAttribute("aria-checked", "true");
            badgeelement.parentElement?.setAttribute("aria-checked", "true");
            badgeelement.classList.remove(...ThemeIcon.asClassNameArray($Tic));
            badgeelement.classList.add("complete", ...ThemeIcon.asClassNameArray($Uic));
          } else {
            badgeelement.setAttribute("aria-checked", "false");
            badgeelement.parentElement?.setAttribute("aria-checked", "false");
            badgeelement.classList.remove("complete", ...ThemeIcon.asClassNameArray($Uic));
            badgeelement.classList.add(...ThemeIcon.asClassNameArray($Tic));
          }
        });
      }
      this.oc();
    }));
    this.B(this.Ib.onWillSaveState((e) => {
      if (e.reason !== WillSaveStateReason.SHUTDOWN) {
        return;
      }
      if (this.Sb.getWorkspace().folders.length !== 0) {
        return;
      }
      if (!this.f || !this.eb || !this.f.selectedCategory || !this.f.selectedStep) {
        return;
      }
      const editorPane = this.Mb.activeGroup.activeEditorPane;
      if (!(editorPane instanceof $4ic_1)) {
        return;
      }
      const restoreData = { folder: $4k.id, category: this.f.selectedCategory, step: this.f.selectedStep };
      this.Ib.store(
        $Xic,
        JSON.stringify(restoreData),
        0,
        1
        /* StorageTarget.MACHINE */
      );
    }));
  }
  // remove when 'workbench.welcomePage.preferReducedMotion' deprecated
  Ub() {
    if (this.Db.getValue(REDUCED_MOTION_KEY)) {
      return false;
    }
    if (this.Tb.isMotionReduced()) {
      return false;
    }
    return true;
  }
  Vb(walkthrough) {
    const activeSteps = walkthrough.steps.filter((s) => this.lb.contextMatchesRules(s.when));
    return {
      stepsComplete: activeSteps.filter((s) => s.done).length,
      stepsTotal: activeSteps.length
    };
  }
  async setInput(newInput, options3, context, token) {
    this.kb.classList.remove("animatable");
    this.f = newInput;
    await super.setInput(newInput, options3, context, token);
    await this.kc();
    if (this.Ub()) {
      setTimeout(() => this.kb.classList.add("animatable"), 0);
    }
  }
  async makeCategoryVisibleWhenAvailable(categoryID, stepId) {
    this.pc(categoryID, stepId);
  }
  Wb() {
    this.j.clear();
    this.kb.querySelectorAll("[x-dispatch]").forEach((element) => {
      const dispatch = element.getAttribute("x-dispatch") ?? "";
      let command4, argument;
      if (dispatch.startsWith("openLink:https")) {
        [command4, argument] = ["openLink", dispatch.replace("openLink:", "")];
      } else {
        [command4, argument] = dispatch.split(":");
      }
      if (command4) {
        this.j.add($_i(element, "click", (e) => {
          e.stopPropagation();
          this.Xb(command4, argument);
        }));
        this.j.add($_i(element, "keyup", (e) => {
          const keyboardEvent = new $if(e);
          e.stopPropagation();
          switch (keyboardEvent.keyCode) {
            case 3:
            case 10:
              this.Xb(command4, argument);
              return;
          }
        }));
      }
    });
  }
  async Xb(command4, argument) {
    this.zb.executeCommand("workbench.action.keepEditor");
    this.Q.publicLog2("gettingStarted.ActionExecuted", { command: command4, argument, walkthroughId: this.eb?.id });
    switch (command4) {
      case "scrollPrev": {
        this.yc();
        break;
      }
      case "skip": {
        this.zc();
        break;
      }
      case "showMoreRecents": {
        this.zb.executeCommand($_yb.ID);
        break;
      }
      case "seeAllWalkthroughs": {
        await this.ac();
        break;
      }
      case "openFolder": {
        if (this.lb.contextMatchesRules($7m.and($epb.isEqualTo("workspace")))) {
          this.zb.executeCommand($Zyb.ID);
        } else {
          this.zb.executeCommand($m ? "workbench.action.files.openFileFolder" : "workbench.action.files.openFolder");
        }
        break;
      }
      case "selectCategory": {
        this.pc(argument);
        this.Cb.markWalkthroughOpened(argument);
        break;
      }
      case "selectStartEntry": {
        const selected = $Uhc.find((e) => e.id === argument);
        if (selected) {
          this.sc(selected.content.command);
        } else {
          throw Error("could not find start entry with id: " + argument);
        }
        break;
      }
      case "hideCategory": {
        this.Yb(argument);
        break;
      }
      case "selectTask": {
        this.hc(argument);
        break;
      }
      case "toggleStepCompletion": {
        this.$b(argument);
        break;
      }
      case "allDone": {
        this.Zb();
        break;
      }
      case "nextSection": {
        const next = this.eb?.next;
        if (next) {
          this.fb = this.eb;
          this.pc(next);
        } else {
          console.error("Error scrolling to next section of", this.eb);
        }
        break;
      }
      case "openLink": {
        this.Gb.open(argument);
        break;
      }
      default: {
        console.error("Dispatch to", command4, argument, "not defined");
        break;
      }
    }
  }
  Yb(categoryId) {
    const selectedCategory = this.db.find((category8) => category8.id === categoryId);
    if (!selectedCategory) {
      throw Error("Could not find category with ID " + categoryId);
    }
    this.cc([...this.bc().add(categoryId)]);
    this.pb?.rerender();
  }
  Zb() {
    if (this.eb) {
      this.eb?.steps.forEach((step) => {
        if (!step.done) {
          this.Cb.progressStep(step.id);
        }
      });
      this.Yb(this.eb?.id);
      this.yc();
    } else {
      throw Error("No walkthrough opened");
    }
  }
  $b(argument) {
    const stepToggle = $Kg(this.eb?.steps.find((step) => step.id === argument));
    if (stepToggle.done) {
      this.Cb.deprogressStep(argument);
    } else {
      this.Cb.progressStep(argument);
    }
  }
  async ac() {
    const selection = await this.Nb.pick(this.db.filter((c) => this.lb.contextMatchesRules(c.when)).map((x) => ({
      id: x.id,
      label: x.title,
      detail: x.description,
      description: x.source
    })), { canPickMany: false, matchOnDescription: true, matchOnDetail: true, title: localize(11831, null) });
    if (selection) {
      this.Xb("selectCategory", selection.id);
    }
  }
  bc() {
    return new Set(JSON.parse(this.Ib.get($Zhc, 0, "[]")));
  }
  cc(hidden) {
    this.Ib.store(
      $Zhc,
      JSON.stringify(hidden),
      0,
      0
      /* StorageTarget.USER */
    );
  }
  async fc(stepId, forceRebuild = false) {
    if (!this.eb) {
      throw Error("no walkthrough selected");
    }
    const stepToExpand = $Kg(this.eb.steps.find((step) => step.id === stepId));
    if (!forceRebuild && this.dc === stepId) {
      return;
    }
    this.dc = stepId;
    this.m.clear();
    this.m.add({
      dispose: () => {
        this.dc = void 0;
      }
    });
    if (this.ec !== stepToExpand.media.type) {
      this.ec = stepToExpand.media.type;
      this.u.add($1c(() => {
        this.ec = void 0;
      }));
      $$i(this.tb);
      if (stepToExpand.media.type === "svg") {
        this.ub = this.u.add(this.Rb.createWebviewElement({ title: void 0, options: { disableServiceWorker: true }, contentOptions: {}, extension: void 0 }));
        this.ub.mountTo(this.tb, this.window);
      } else if (stepToExpand.media.type === "markdown") {
        this.ub = this.u.add(this.Rb.createWebviewElement({ options: {}, contentOptions: { localResourceRoots: [stepToExpand.media.root], allowScripts: true }, title: "", extension: void 0 }));
        this.ub.mountTo(this.tb, this.window);
      }
    }
    if (stepToExpand.media.type === "image") {
      this.sb.classList.add("image");
      this.sb.classList.remove("markdown");
      const media = stepToExpand.media;
      const mediaElement = $("img");
      $$i(this.tb);
      this.tb.appendChild(mediaElement);
      mediaElement.setAttribute("alt", media.altText);
      this.ic(mediaElement, media.path);
      this.m.add($_i(this.tb, "click", () => {
        const hrefs = stepToExpand.description.map((lt2) => lt2.nodes.filter((node) => typeof node !== "string").map((node) => node.href)).flat();
        if (hrefs.length === 1) {
          const href = hrefs[0];
          if (href.startsWith("http")) {
            this.Q.publicLog2("gettingStarted.ActionExecuted", { command: "runStepAction", argument: href, walkthroughId: this.eb?.id });
            this.Gb.open(href);
          }
        }
      }));
      this.m.add(this.n.onDidColorThemeChange(() => this.ic(mediaElement, media.path)));
    } else if (stepToExpand.media.type === "svg") {
      this.sb.classList.add("image");
      this.sb.classList.remove("markdown");
      const media = stepToExpand.media;
      this.ub.setHtml(await this.wb.renderSVG(media.path));
      let isDisposed = false;
      this.m.add($1c(() => {
        isDisposed = true;
      }));
      this.m.add(this.n.onDidColorThemeChange(async () => {
        const body = await this.wb.renderSVG(media.path);
        if (!isDisposed) {
          this.ub.setHtml(body);
        }
      }));
      this.m.add($_i(this.tb, "click", () => {
        const hrefs = stepToExpand.description.map((lt2) => lt2.nodes.filter((node) => typeof node !== "string").map((node) => node.href)).flat();
        if (hrefs.length === 1) {
          const href = hrefs[0];
          if (href.startsWith("http")) {
            this.Q.publicLog2("gettingStarted.ActionExecuted", { command: "runStepAction", argument: href, walkthroughId: this.eb?.id });
            this.Gb.open(href);
          }
        }
      }));
      this.m.add(this.ub.onDidClickLink((link2) => {
        if ($0g(link2, Schemas.https) || $0g(link2, Schemas.http) || $0g(link2, Schemas.command)) {
          this.Gb.open(link2, { allowCommands: true });
        }
      }));
    } else if (stepToExpand.media.type === "markdown") {
      this.sb.classList.remove("image");
      this.sb.classList.add("markdown");
      const media = stepToExpand.media;
      const rawHTML = await this.wb.renderMarkdown(media.path, media.base);
      this.ub.setHtml(rawHTML);
      const serializedContextKeyExprs = rawHTML.match(/checked-on=\"([^'][^"]*)\"/g)?.map((attr) => attr.slice('checked-on="'.length, -1).replace(/&#39;/g, "'").replace(/&amp;/g, "&"));
      const postTrueKeysMessage = () => {
        const enabledContextKeys = serializedContextKeyExprs?.filter((expr) => this.lb.contextMatchesRules($7m.deserialize(expr)));
        if (enabledContextKeys) {
          this.ub.postMessage({
            enabledContextKeys
          });
        }
      };
      if (serializedContextKeyExprs) {
        const contextKeyExprs = $Mb(serializedContextKeyExprs.map((expr) => $7m.deserialize(expr)));
        const watchingKeys = new Set(contextKeyExprs.flatMap((expr) => expr.keys()));
        this.m.add(this.lb.onDidChangeContext((e) => {
          if (e.affectsSome(watchingKeys)) {
            postTrueKeysMessage();
          }
        }));
      }
      let isDisposed = false;
      this.m.add($1c(() => {
        isDisposed = true;
      }));
      this.m.add(this.ub.onDidClickLink((link2) => {
        if ($0g(link2, Schemas.https) || $0g(link2, Schemas.http) || $0g(link2, Schemas.command)) {
          const toSide = link2.startsWith("command:toSide:");
          if (toSide) {
            link2 = link2.replace("command:toSide:", "command:");
            this.rc();
          }
          this.Gb.open(link2, { allowCommands: true, openToSide: toSide });
        }
      }));
      if (rawHTML.indexOf("<code>") >= 0) {
        this.m.add(this.n.onDidColorThemeChange(async () => {
          const body = await this.wb.renderMarkdown(media.path, media.base);
          if (!isDisposed) {
            this.ub.setHtml(body);
            postTrueKeysMessage();
          }
        }));
      }
      const layoutDelayer = new $Sh(50);
      this.vb = () => {
        layoutDelayer.trigger(() => {
          this.ub.postMessage({ layoutMeNow: true });
        });
      };
      this.m.add(layoutDelayer);
      this.m.add({ dispose: () => this.vb = void 0 });
      postTrueKeysMessage();
      this.m.add(this.ub.onMessage(async (e) => {
        const message = e.message;
        if (message.startsWith("command:")) {
          this.Gb.open(message, { allowCommands: true });
        } else if (message.startsWith("setTheme:")) {
          const themeId = message.slice("setTheme:".length);
          const theme = (await this.n.getColorThemes()).find((theme2) => theme2.settingsId === themeId);
          if (theme) {
            this.n.setColorTheme(
              theme.id,
              2
              /* ConfigurationTarget.USER */
            );
          }
        } else {
          console.error("Unexpected message", message);
        }
      }));
    }
  }
  async selectStepLoose(id2) {
    if (id2.startsWith(`${this.f.selectedCategory}#`)) {
      this.hc(id2);
    } else {
      const toSelect = this.f.selectedCategory + "#" + id2;
      this.hc(toSelect);
    }
  }
  gc() {
    if (this.Db.getValue(
      "accessibility.verbosity.walkthrough"
      /* AccessibilityVerbositySettingId.Walkthrough */
    )) {
      const kbLabel = this.Bb.lookupKeybinding($vSb.id)?.getAriaLabel();
      return kbLabel ? localize(11832, null, kbLabel) : localize(11833, null);
    }
    return "";
  }
  async hc(id2, delayFocus = true) {
    if (id2) {
      let stepElement = this.kb.querySelector(`[data-step-id="${id2}"]`);
      if (!stepElement) {
        stepElement = this.kb.querySelector(`[data-step-id]`);
        if (!stepElement) {
          return;
        }
        id2 = $Kg(stepElement.getAttribute("data-step-id"));
      }
      stepElement.parentElement?.querySelectorAll(".expanded").forEach((node) => {
        if (node.getAttribute("data-step-id") !== id2) {
          node.classList.remove("expanded");
          node.setAttribute("aria-expanded", "false");
          const codiconElement2 = node.querySelector(".codicon");
          if (codiconElement2) {
            codiconElement2.removeAttribute("tabindex");
          }
        }
      });
      setTimeout(() => stepElement.focus(), delayFocus && this.Ub() ? SLIDE_TRANSITION_TIME_MS : 0);
      this.f.selectedStep = id2;
      stepElement.classList.add("expanded");
      stepElement.setAttribute("aria-expanded", "true");
      this.fc(id2, true);
      const codiconElement = stepElement.querySelector(".codicon");
      if (codiconElement) {
        codiconElement.setAttribute("tabindex", "0");
      }
      this.Cb.progressByEvent("stepSelected:" + id2);
      const step = this.eb?.steps?.find((step2) => step2.id === id2);
      if (step) {
        stepElement.setAttribute("aria-label", `${this.gc()} ${step.title}`);
      }
    } else {
      this.f.selectedStep = void 0;
    }
    this.hb?.scanDomNode();
    this.ib?.scanDomNode();
  }
  ic(element, sources) {
    const themeType = this.n.getColorTheme().type;
    const src = sources[themeType].toString(true).replace(/ /g, "%20");
    element.srcset = src.toLowerCase().endsWith(".svg") ? src : src + " 1.5x";
  }
  Y(parent) {
    if (this.hb) {
      this.hb.dispose();
    }
    if (this.gb) {
      this.gb.dispose();
    }
    this.rb = $(".gettingStartedSlideCategories.gettingStartedSlide");
    const prevButton = $("button.prev-button.button-link", { "x-dispatch": "scrollPrev" }, $("span.scroll-button.codicon.codicon-chevron-left"), $("span.moreText", {}, localize(11834, null)));
    this.qb = $(".gettingStartedSlideDetails.gettingStartedSlide", {}, prevButton);
    this.sb = $(".gettingStartedDetailsContent", {});
    this.hb = this.B(new $CZ(this.sb, { className: "full-height-scrollable" }));
    this.gb = this.B(new $CZ(this.rb, { className: "full-height-scrollable categoriesScrollbar" }));
    this.qb.appendChild(this.hb.getDomNode());
    const gettingStartedPage = $(".gettingStarted", {}, this.gb.getDomNode(), this.qb);
    this.kb.appendChild(gettingStartedPage);
    this.gb.scanDomNode();
    this.hb.scanDomNode();
    parent.appendChild(this.kb);
  }
  async kc() {
    this.xb.clear();
    const showOnStartupCheckbox = new $Q1({
      icon: $6l.check,
      actionClassName: "getting-started-checkbox",
      isChecked: this.Db.getValue(configurationKey2) === "welcomePage",
      title: localize(11835, null),
      ...$u$
    });
    showOnStartupCheckbox.domNode.id = "showOnStartup";
    const showOnStartupLabel = $("label.caption", { for: "showOnStartup" }, localize(11836, null));
    const onShowOnStartupChanged = () => {
      if (showOnStartupCheckbox.checked) {
        this.Q.publicLog2("gettingStarted.ActionExecuted", { command: "showOnStartupChecked", argument: void 0, walkthroughId: this.eb?.id });
        this.Db.updateValue(configurationKey2, "welcomePage");
      } else {
        this.Q.publicLog2("gettingStarted.ActionExecuted", { command: "showOnStartupUnchecked", argument: void 0, walkthroughId: this.eb?.id });
        this.Db.updateValue(configurationKey2, "none");
      }
    };
    this.xb.add(showOnStartupCheckbox);
    this.xb.add(showOnStartupCheckbox.onChange(() => {
      onShowOnStartupChanged();
    }));
    this.xb.add($_i(showOnStartupLabel, "click", () => {
      showOnStartupCheckbox.checked = !showOnStartupCheckbox.checked;
      onShowOnStartupChanged();
    }));
    const header = $(".header", {}, $("h1.product-name.caption", {}, this.Ab.nameLong), $("p.subtitle.description", {}, localize(11837, null)));
    const leftColumn = $(".categories-column.categories-column-left", {});
    const rightColumn = $(".categories-column.categories-column-right", {});
    const startList = this.mc();
    const recentList = this.lc();
    const gettingStartedList = this.nc();
    const footer = $(".footer", {}, $("p.showOnStartup", {}, showOnStartupCheckbox.domNode, showOnStartupLabel));
    const layoutLists = () => {
      if (gettingStartedList.itemCount) {
        this.kb.classList.remove("noWalkthroughs");
        $dk(rightColumn, gettingStartedList.getDomElement());
      } else {
        this.kb.classList.add("noWalkthroughs");
        $dk(rightColumn);
      }
      setTimeout(() => this.gb?.scanDomNode(), 50);
      layoutRecentList();
    };
    const layoutRecentList = () => {
      if (this.kb.classList.contains("noWalkthroughs")) {
        recentList.setLimit(10);
        $dk(leftColumn, startList.getDomElement());
        $dk(rightColumn, recentList.getDomElement());
      } else {
        recentList.setLimit(5);
        $dk(leftColumn, startList.getDomElement(), recentList.getDomElement());
      }
    };
    gettingStartedList.onDidChange(layoutLists);
    layoutLists();
    $dk(this.rb, $(".gettingStartedCategoriesContainer", {}, header, leftColumn, rightColumn, footer));
    this.gb?.scanDomNode();
    this.oc();
    this.Wb();
    if (this.f.selectedCategory) {
      this.eb = this.db.find((category8) => category8.id === this.f.selectedCategory);
      if (!this.eb) {
        this.db = this.Cb.getWalkthroughs();
        this.eb = this.db.find((category8) => category8.id === this.f.selectedCategory);
        if (this.eb) {
          this.uc(this.f.selectedCategory, this.f.selectedStep);
          this.Ac("details");
          return;
        }
      } else {
        this.uc(this.f.selectedCategory, this.f.selectedStep);
        this.Ac("details");
        return;
      }
    }
    const someStepsComplete = this.db.some((category8) => category8.steps.find((s) => s.done));
    if (this.f.showTelemetryNotice && this.Ab.openToWelcomeMainPage) {
      const telemetryNotice = $("p.telemetry-notice");
      this.vc(telemetryNotice);
      footer.appendChild(telemetryNotice);
    } else if (!this.Ab.openToWelcomeMainPage && !someStepsComplete && !this.mb && this.yb) {
      const firstSessionDateString = this.Ib.get(
        $Cv,
        -1
        /* StorageScope.APPLICATION */
      ) || (/* @__PURE__ */ new Date()).toUTCString();
      const daysSinceFirstSession = (+/* @__PURE__ */ new Date() - +new Date(firstSessionDateString)) / 1e3 / 60 / 60 / 24;
      const fistContentBehaviour = daysSinceFirstSession < 1 ? "openToFirstCategory" : "index";
      if (fistContentBehaviour === "openToFirstCategory") {
        const first = this.db.filter((c) => !c.when || this.lb.contextMatchesRules(c.when))[0];
        if (first) {
          this.mb = true;
          this.eb = first;
          this.f.selectedCategory = this.eb?.id;
          this.f.walkthroughPageTitle = this.eb.walkthroughPageTitle;
          this.uc(this.f.selectedCategory, void 0);
          this.Ac(
            "details",
            true
            /* firstLaunch */
          );
          return;
        }
      }
    }
    this.Ac("categories");
  }
  lc() {
    const renderRecent = (recent) => {
      let fullPath;
      let windowOpenable;
      if ($4w(recent)) {
        windowOpenable = { folderUri: recent.folderUri };
        fullPath = recent.label || this.Pb.getWorkspaceLabel(recent.folderUri, {
          verbose: 2
          /* Verbosity.LONG */
        });
      } else {
        fullPath = recent.label || this.Pb.getWorkspaceLabel(recent.workspace, {
          verbose: 2
          /* Verbosity.LONG */
        });
        windowOpenable = { workspaceUri: recent.workspace.configPath };
      }
      const { name, parentPath } = $9t(fullPath);
      const li = $("li");
      const link2 = $("button.button-link");
      link2.innerText = name;
      link2.title = fullPath;
      link2.setAttribute("aria-label", localize(11838, null, name, parentPath));
      link2.addEventListener("click", (e) => {
        this.Q.publicLog2("gettingStarted.ActionExecuted", { command: "openRecent", argument: void 0, walkthroughId: this.eb?.id });
        this.Qb.openWindow([windowOpenable], {
          forceNewWindow: e.ctrlKey || e.metaKey,
          remoteAuthority: recent.remoteAuthority || null
          // local window if remoteAuthority is not set or can not be deducted from the openable
        });
        e.preventDefault();
        e.stopPropagation();
      });
      li.appendChild(link2);
      const span = $("span");
      span.classList.add("path");
      span.classList.add("detail");
      span.innerText = parentPath;
      span.title = fullPath;
      li.appendChild(span);
      return li;
    };
    if (this.nb) {
      this.nb.dispose();
    }
    const recentlyOpenedList = this.nb = new $1ic({
      title: localize(11839, null),
      klass: "recently-opened",
      limit: 5,
      empty: $(".empty-recent", {}, localize(11840, null), $("button.button-link", { "x-dispatch": "openFolder" }, localize(11841, null)), localize(11842, null)),
      more: $(".more", {}, $("button.button-link", {
        "x-dispatch": "showMoreRecents",
        title: localize(11843, null, this.wc($_yb.ID))
      }, localize(11844, null))),
      renderElement: renderRecent,
      contextService: this.lb
    });
    recentlyOpenedList.onDidChange(() => this.Wb());
    this.cb.then(({ workspaces }) => {
      const workspacesWithID = workspaces.filter((recent) => !this.Sb.isCurrentWorkspace($3w(recent) ? recent.workspace : recent.folderUri)).map((recent) => ({ ...recent, id: $3w(recent) ? recent.workspace.id : recent.folderUri.toString() }));
      const updateEntries = () => {
        recentlyOpenedList.setEntries(workspacesWithID);
      };
      updateEntries();
      recentlyOpenedList.register(this.Pb.onDidChangeFormatters(() => updateEntries()));
    }).catch($gb);
    return recentlyOpenedList;
  }
  mc() {
    const renderStartEntry = (entry) => $("li", {}, $("button.button-link", {
      "x-dispatch": "selectStartEntry:" + entry.id,
      title: entry.description + " " + this.wc(entry.command)
    }, this.qc(entry), $("span", {}, entry.title)));
    if (this.ob) {
      this.ob.dispose();
    }
    const startList = this.ob = new $1ic({
      title: localize(11845, null),
      klass: "start-container",
      limit: 10,
      renderElement: renderStartEntry,
      rankElement: (e) => -e.order,
      contextService: this.lb
    });
    startList.setEntries(parsedStartEntries);
    startList.onDidChange(() => this.Wb());
    return startList;
  }
  nc() {
    const renderGetttingStaredWalkthrough = (category8) => {
      const renderNewBadge = (category8.newItems || category8.newEntry) && !category8.isFeatured;
      const newBadge = $(".new-badge", {});
      if (category8.newEntry) {
        $dk(newBadge, $(".new-category", {}, localize(11846, null)));
      } else if (category8.newItems) {
        $dk(newBadge, $(".new-items", {}, localize(11847, null)));
      }
      const featuredBadge = $(".featured-badge", {});
      const descriptionContent = $(".description-content", {});
      if (category8.isFeatured && this.yb) {
        $dk(featuredBadge, $(".featured", {}, $("span.featured-icon.codicon.codicon-star-full")));
        $dk(descriptionContent, ...$B1(category8.description));
      }
      const titleContent = $("h3.category-title.max-lines-3", { "x-category-title-for": category8.id });
      $dk(titleContent, ...$B1(category8.title));
      return $("button.getting-started-category" + (category8.isFeatured && this.yb ? ".featured" : ""), {
        "x-dispatch": "selectCategory:" + category8.id,
        "title": category8.description
      }, featuredBadge, $(".main-content", {}, this.qc(category8), titleContent, renderNewBadge ? newBadge : $(".no-badge"), $("a.codicon.codicon-close.hide-category-button", {
        "tabindex": 0,
        "x-dispatch": "hideCategory:" + category8.id,
        "title": localize(11848, null),
        "role": "button",
        "aria-label": localize(11849, null)
      })), descriptionContent, $(".category-progress", { "x-data-category-id": category8.id }, $(".progress-bar-outer", { "role": "progressbar" }, $(".progress-bar-inner"))));
    };
    if (this.pb) {
      this.pb.dispose();
    }
    const rankWalkthrough = (e) => {
      let rank = e.order;
      if (e.isFeatured) {
        rank += 7;
      }
      if (e.newEntry) {
        rank += 3;
      }
      if (e.newItems) {
        rank += 2;
      }
      if (e.recencyBonus) {
        rank += 4 * e.recencyBonus;
      }
      if (this.bc().has(e.id)) {
        rank = null;
      }
      return rank;
    };
    const gettingStartedList = this.pb = new $1ic({
      title: localize(11850, null),
      klass: "getting-started",
      limit: 5,
      footer: $("span.button-link.see-all-walkthroughs", { "x-dispatch": "seeAllWalkthroughs", "tabindex": 0 }, localize(11851, null)),
      renderElement: renderGetttingStaredWalkthrough,
      rankElement: rankWalkthrough,
      contextService: this.lb
    });
    gettingStartedList.onDidChange(() => {
      const hidden = this.bc();
      const someWalkthroughsHidden = hidden.size || gettingStartedList.itemCount < this.db.filter((c) => this.lb.contextMatchesRules(c.when)).length;
      this.kb.classList.toggle("someWalkthroughsHidden", !!someWalkthroughsHidden);
      this.Wb();
      $2ic.bindTo(this.lb).set(gettingStartedList.itemCount === 0);
      this.oc();
    });
    gettingStartedList.setEntries(this.db);
    $2ic.bindTo(this.lb).set(gettingStartedList.itemCount === 0);
    return gettingStartedList;
  }
  layout(size) {
    this.ib?.scanDomNode();
    this.gb?.scanDomNode();
    this.hb?.scanDomNode();
    this.ob?.layout(size);
    this.pb?.layout(size);
    this.nb?.layout(size);
    if (this.f?.selectedStep && this.ec) {
      this.u.clear();
      this.m.clear();
      this.fc(this.f.selectedStep);
    }
    this.vb?.();
    this.kb.classList.toggle("height-constrained", size.height <= 600);
    this.kb.classList.toggle("width-constrained", size.width <= 400);
    this.kb.classList.toggle("width-semi-constrained", size.width <= 800);
    this.gb?.scanDomNode();
    this.hb?.scanDomNode();
    this.ib?.scanDomNode();
  }
  oc() {
    this.window.document.querySelectorAll(".category-progress").forEach((element) => {
      const categoryID = element.getAttribute("x-data-category-id");
      const category8 = this.db.find((category9) => category9.id === categoryID);
      if (!category8) {
        throw Error("Could not find category with ID " + categoryID);
      }
      const stats = this.Vb(category8);
      const bar = $Kg(element.querySelector(".progress-bar-inner"));
      bar.setAttribute("aria-valuemin", "0");
      bar.setAttribute("aria-valuenow", "" + stats.stepsComplete);
      bar.setAttribute("aria-valuemax", "" + stats.stepsTotal);
      const progress = stats.stepsComplete / stats.stepsTotal * 100;
      bar.style.width = `${progress}%`;
      element.parentElement.classList.toggle("no-progress", stats.stepsComplete === 0);
      if (stats.stepsTotal === stats.stepsComplete) {
        bar.title = localize(11852, null, stats.stepsComplete);
      } else {
        bar.title = localize(11853, null, stats.stepsComplete, stats.stepsTotal);
      }
    });
  }
  async pc(categoryID, stepId) {
    if (!this.db.some((c) => c.id === categoryID)) {
      this.db = this.Cb.getWalkthroughs();
    }
    const ourCategory = this.db.find((c) => c.id === categoryID);
    if (!ourCategory) {
      throw Error("Could not find category with ID: " + categoryID);
    }
    this.g = this.g.then(async () => {
      $dk(this.sb);
      this.f.selectedCategory = categoryID;
      this.f.selectedStep = stepId;
      this.f.walkthroughPageTitle = ourCategory.walkthroughPageTitle;
      this.eb = ourCategory;
      this.uc(categoryID, stepId);
      this.Ac("details");
    });
  }
  qc(category8) {
    const widget = category8.icon.type === "icon" ? $(ThemeIcon.asCSSSelector(category8.icon.icon)) : $("img.category-icon", { src: category8.icon.path });
    widget.classList.add("icon-widget");
    return widget;
  }
  rc() {
    const fullSize = this.Mb.getPart(this.group).contentDimension;
    if (!fullSize || fullSize.width <= 700) {
      return;
    }
    if (this.Mb.count === 1) {
      const sideGroup = this.Mb.addGroup(
        this.Mb.groups[0],
        3
        /* GroupDirection.RIGHT */
      );
      this.Mb.activateGroup(sideGroup);
      const gettingStartedSize = Math.floor(fullSize.width / 2);
      const gettingStartedGroup = this.Mb.getGroups(
        1
        /* GroupsOrder.MOST_RECENTLY_ACTIVE */
      ).find((group2) => group2.activeEditor instanceof $Wic);
      this.Mb.setSize($Kg(gettingStartedGroup), { width: gettingStartedSize, height: fullSize.height });
    }
    const nonGettingStartedGroup = this.Mb.getGroups(
      1
      /* GroupsOrder.MOST_RECENTLY_ACTIVE */
    ).find((group2) => !(group2.activeEditor instanceof $Wic));
    if (nonGettingStartedGroup) {
      this.Mb.activateGroup(nonGettingStartedGroup);
      nonGettingStartedGroup.focus();
    }
  }
  sc(href) {
    const isCommand = href.startsWith("command:");
    const toSide = href.startsWith("command:toSide:");
    const command4 = href.replace(/command:(toSide:)?/, "command:");
    this.Q.publicLog2("gettingStarted.ActionExecuted", { command: "runStepAction", argument: href, walkthroughId: this.eb?.id });
    if (toSide) {
      this.rc();
    }
    if (isCommand) {
      const commandURI = URI.parse(command4);
      let args2 = [];
      try {
        args2 = $bu(decodeURIComponent(commandURI.query));
      } catch {
        try {
          args2 = $bu(commandURI.query);
        } catch {
        }
      }
      if (!Array.isArray(args2)) {
        args2 = [args2];
      }
      if ((commandURI.path === $1yb.ID.toString() || commandURI.path === $Yyb.ID.toString()) && this.Sb.getWorkspace().folders.length === 0) {
        const selectedStepIndex = this.eb?.steps.findIndex((step) => step.id === this.f.selectedStep);
        if (selectedStepIndex !== void 0 && selectedStepIndex > -1 && this.eb?.steps.slice(selectedStepIndex + 1).some((step) => !step.done)) {
          const restoreData = { folder: $4k.id, category: this.f.selectedCategory, step: this.f.selectedStep };
          this.Ib.store(
            $Xic,
            JSON.stringify(restoreData),
            0,
            1
            /* StorageTarget.MACHINE */
          );
        }
      }
      this.zb.executeCommand(commandURI.path, ...args2).then((result) => {
        const toOpen = result?.openFolder;
        if (toOpen) {
          if (!URI.isUri(toOpen)) {
            console.warn("Warn: Running walkthrough command", href, "yielded non-URI `openFolder` result", toOpen, ". It will be disregarded.");
            return;
          }
          const restoreData = { folder: toOpen.toString(), category: this.f.selectedCategory, step: this.f.selectedStep };
          this.Ib.store(
            $Xic,
            JSON.stringify(restoreData),
            0,
            1
            /* StorageTarget.MACHINE */
          );
          this.Qb.openWindow([{ folderUri: toOpen }]);
        }
      });
    } else {
      this.Gb.open(command4, { allowCommands: true });
    }
    if (!isCommand && (href.startsWith("https://") || href.startsWith("http://"))) {
      this.Cb.progressByEvent("onLink:" + href);
    }
  }
  tc(container2, text2) {
    while (container2.firstChild) {
      container2.firstChild.remove();
    }
    for (const linkedText of text2) {
      if (linkedText.nodes.length === 1 && typeof linkedText.nodes[0] !== "string") {
        const node = linkedText.nodes[0];
        const buttonContainer = $bk(container2, $(".button-container"));
        const button = new $k2(buttonContainer, { title: node.title, supportIcons: true, ...$q$ });
        const isCommand = node.href.startsWith("command:");
        const command4 = node.href.replace(/command:(toSide:)?/, "command:");
        button.label = node.label;
        button.onDidClick((e) => {
          e.stopPropagation();
          e.preventDefault();
          this.sc(node.href);
        }, null, this.r);
        if (isCommand) {
          const keybinding = this.xc(command4);
          if (keybinding) {
            const shortcutMessage = $("span.shortcut-message", {}, localize(11854, null));
            container2.appendChild(shortcutMessage);
            const label3 = new $32(shortcutMessage, OS, { ...$o$ });
            label3.set(keybinding);
          }
        }
        this.r.add(button);
      } else {
        const p = $bk(container2, $("p"));
        for (const node of linkedText.nodes) {
          if (typeof node === "string") {
            const labelWithIcon = $B1(node);
            for (const element of labelWithIcon) {
              if (typeof element === "string") {
                p.appendChild($RZ(element, { inline: true, renderCodeSegments: true }));
              } else {
                p.appendChild(element);
              }
            }
          } else {
            const link2 = this.Kb.createInstance(Link2, p, node, { opener: (href) => this.sc(href) });
            this.r.add(link2);
          }
        }
      }
    }
    return container2;
  }
  clearInput() {
    this.m.clear();
    super.clearInput();
  }
  uc(categoryID, selectedStep) {
    if (this.ib) {
      this.ib.dispose();
    }
    this.Jb.whenInstalledExtensionsRegistered().then(() => {
      this.Jb.activateByEvent(`onWalkthrough:${categoryID.replace(/[^#]+#/, "")}`);
    });
    this.r.clear();
    this.u.clear();
    const category8 = this.db.find((category9) => category9.id === categoryID);
    if (!category8) {
      throw Error("could not find category with ID " + categoryID);
    }
    const descriptionContainer = $(".category-description.description.max-lines-3", { "x-category-description-for": category8.id });
    this.tc(descriptionContainer, $3hc(category8.description));
    const categoryDescriptorComponent = $(".getting-started-category", {}, $(".category-description-container", {}, $("h2.category-title.max-lines-3", { "x-category-title-for": category8.id }, ...$B1(category8.title)), descriptionContainer));
    const stepListContainer = $(".step-list-container");
    this.r.add($_i(stepListContainer, "keydown", (e) => {
      const event = new $if(e);
      const currentStepIndex = () => category8.steps.findIndex((e2) => e2.id === this.f.selectedStep);
      if (event.keyCode === 16) {
        const toExpand2 = category8.steps.filter((step, index) => index < currentStepIndex() && this.lb.contextMatchesRules(step.when));
        if (toExpand2.length) {
          this.hc(toExpand2[toExpand2.length - 1].id, false);
        }
      }
      if (event.keyCode === 18) {
        const toExpand2 = category8.steps.find((step, index) => index > currentStepIndex() && this.lb.contextMatchesRules(step.when));
        if (toExpand2) {
          this.hc(toExpand2.id, false);
        }
      }
    }));
    let renderedSteps = void 0;
    const contextKeysToWatch = new Set(category8.steps.flatMap((step) => step.when.keys()));
    const buildStepList = () => {
      category8.steps.sort((a, b) => a.order - b.order);
      const toRender = category8.steps.filter((step) => this.lb.contextMatchesRules(step.when));
      if ($zb(renderedSteps, toRender, (a, b) => a.id === b.id)) {
        return;
      }
      renderedSteps = toRender;
      $dk(stepListContainer, ...renderedSteps.map((step) => {
        const codicon = $(".codicon" + (step.done ? ".complete" + ThemeIcon.asCSSSelector($Uic) : ThemeIcon.asCSSSelector($Tic)), {
          "data-done-step-id": step.id,
          "x-dispatch": "toggleStepCompletion:" + step.id,
          "role": "checkbox",
          "aria-checked": step.done ? "true" : "false"
        });
        const container2 = $(".step-description-container", { "x-step-description-for": step.id });
        this.tc(container2, step.description);
        const stepTitle = $("h3.step-title.max-lines-3", { "x-step-title-for": step.id });
        $dk(stepTitle, ...$B1(step.title));
        const stepDescription = $(".step-container", {}, stepTitle, container2);
        if (step.media.type === "image") {
          stepDescription.appendChild($(".image-description", { "aria-label": localize(11855, null, step.media.altText) }));
        }
        return $("button.getting-started-step", {
          "x-dispatch": "selectTask:" + step.id,
          "data-step-id": step.id,
          "aria-expanded": "false",
          "aria-checked": step.done ? "true" : "false",
          "role": "button"
        }, codicon, stepDescription);
      }));
    };
    buildStepList();
    this.r.add(this.lb.onDidChangeContext((e) => {
      if (e.affectsSome(contextKeysToWatch)) {
        buildStepList();
        this.Wb();
        this.hc(this.f.selectedStep, false);
      }
    }));
    const showNextCategory = this.db.find((_category) => _category.id === category8.next);
    const stepsContainer = $(".getting-started-detail-container", { "role": "list" }, stepListContainer, $(".done-next-container", {}, $("button.button-link.all-done", { "x-dispatch": "allDone" }, $("span.codicon.codicon-check-all"), localize(11856, null)), ...showNextCategory ? [$("button.button-link.next", { "x-dispatch": "nextSection" }, localize(11857, null), $("span.codicon.codicon-arrow-right"))] : []));
    this.ib = this.B(new $CZ(stepsContainer, { className: "steps-container" }));
    const stepListComponent = this.ib.getDomNode();
    const categoryFooter = $(".getting-started-footer");
    if (this.f.showTelemetryNotice && $kw(this.Db) !== 0 && this.Ab.enableTelemetry) {
      this.vc(categoryFooter);
    }
    $dk(this.sb, categoryDescriptorComponent, stepListComponent, this.tb, categoryFooter);
    const toExpand = category8.steps.find((step) => this.lb.contextMatchesRules(step.when) && !step.done) ?? category8.steps[0];
    this.hc(selectedStep ?? toExpand.id, !selectedStep);
    this.ib.scanDomNode();
    this.hb?.scanDomNode();
    this.Wb();
  }
  vc(parent) {
    const mdRenderer = this.Kb.createInstance($Q_, {});
    const privacyStatementCopy = localize(11858, null);
    const privacyStatementButton = `[${privacyStatementCopy}](command:workbench.action.openPrivacyStatementUrl)`;
    const optOutCopy = localize(11859, null);
    const optOutButton = `[${optOutCopy}](command:settings.filterByTelemetry)`;
    const text2 = localize(11860, null, this.Ab.nameShort, privacyStatementButton, optOutButton);
    parent.append(mdRenderer.render({ value: text2, isTrusted: true }).element);
    mdRenderer.dispose();
  }
  wc(command4) {
    command4 = command4.replace(/^command:/, "");
    const label3 = this.Bb.lookupKeybinding(command4)?.getLabel();
    if (!label3) {
      return "";
    } else {
      return `(${label3})`;
    }
  }
  xc(command4) {
    command4 = command4.replace(/^command:/, "");
    return this.Bb.lookupKeybinding(command4);
  }
  async yc() {
    this.g = this.g.then(async () => {
      if (this.fb && this.fb !== this.eb) {
        this.eb = this.fb;
        this.fb = void 0;
        this.makeCategoryVisibleWhenAvailable(this.eb.id);
      } else {
        this.eb = void 0;
        this.f.selectedCategory = void 0;
        this.f.selectedStep = void 0;
        this.f.showTelemetryNotice = false;
        this.f.walkthroughPageTitle = void 0;
        if (this.db.length !== this.pb?.itemCount) {
          this.kc();
        }
        this.hc(void 0);
        this.Ac("categories");
        this.kb.focus();
      }
    });
  }
  zc() {
    this.zb.executeCommand("workbench.action.closeActiveEditor");
  }
  escape() {
    if (this.f.selectedCategory) {
      this.yc();
    } else {
      this.zc();
    }
  }
  Ac(toEnable, firstLaunch = false) {
    const slideManager = $Kg(this.kb.querySelector(".gettingStarted"));
    if (toEnable === "categories") {
      slideManager.classList.remove("showDetails");
      slideManager.classList.add("showCategories");
      this.kb.querySelector(".prev-button.button-link").style.display = "none";
      this.kb.querySelector(".gettingStartedSlideDetails").querySelectorAll("button").forEach((button) => button.disabled = true);
      this.kb.querySelector(".gettingStartedSlideCategories").querySelectorAll("button").forEach((button) => button.disabled = false);
      this.kb.querySelector(".gettingStartedSlideCategories").querySelectorAll("input").forEach((button) => button.disabled = false);
    } else {
      slideManager.classList.add("showDetails");
      slideManager.classList.remove("showCategories");
      const prevButton = this.kb.querySelector(".prev-button.button-link");
      prevButton.style.display = this.f.showWelcome || this.fb ? "block" : "none";
      const moreTextElement = prevButton.querySelector(".moreText");
      moreTextElement.textContent = firstLaunch ? localize(11861, null) : localize(11862, null);
      this.kb.querySelector(".gettingStartedSlideDetails").querySelectorAll("button").forEach((button) => button.disabled = false);
      this.kb.querySelector(".gettingStartedSlideCategories").querySelectorAll("button").forEach((button) => button.disabled = true);
      this.kb.querySelector(".gettingStartedSlideCategories").querySelectorAll("input").forEach((button) => button.disabled = true);
    }
  }
  focus() {
    super.focus();
    const active = this.kb.ownerDocument.activeElement;
    let parent = this.kb.parentElement;
    while (parent && parent !== active) {
      parent = parent.parentElement;
    }
    if (parent) {
      this.kb.focus();
    }
  }
};
$4ic = $4ic_1 = __decorate([
  __param(1, $sn),
  __param(2, $Vu),
  __param(3, $Ty),
  __param(4, $Yhc),
  __param(5, $kl),
  __param(6, $zv),
  __param(7, $1E),
  __param(8, $km),
  __param(9, $O4),
  __param(10, $rwb),
  __param(11, $jv),
  __param(12, $wN),
  __param(13, $Pk),
  __param(14, $PJ),
  __param(15, $iJ),
  __param(16, $on),
  __param(17, $1M),
  __param(18, $2w),
  __param(19, $ZI),
  __param(20, $S4),
  __param(21, $Crb),
  __param(22, $Zk),
  __param(23, $ND)
], $4ic);
var $5ic = class {
  canSerialize(editorInput) {
    return true;
  }
  serialize(editorInput) {
    return JSON.stringify({ selectedCategory: editorInput.selectedCategory, selectedStep: editorInput.selectedStep });
  }
  deserialize(instantiationService, serializedEditorInput) {
    return instantiationService.invokeFunction((accessor) => {
      try {
        const { selectedCategory, selectedStep } = JSON.parse(serializedEditorInput);
        return new $Wic({ selectedCategory, selectedStep });
      } catch {
      }
      return new $Wic({});
    });
  }
};

// out-build/vs/workbench/contrib/welcomeGettingStarted/browser/gettingStartedAccessibleView.js
var $6ic = class {
  constructor() {
    this.type = "view";
    this.priority = 110;
    this.name = "walkthroughs";
    this.when = $3ic;
    this.getProvider = (accessor) => {
      const editorService = accessor.get($mJ);
      const editorPane = editorService.activeEditorPane;
      if (!(editorPane instanceof $4ic)) {
        return;
      }
      const gettingStartedInput = editorPane.input;
      if (!(gettingStartedInput instanceof $Wic) || !gettingStartedInput.selectedCategory) {
        return;
      }
      const gettingStartedService = accessor.get($Yhc);
      const currentWalkthrough = gettingStartedService.getWalkthrough(gettingStartedInput.selectedCategory);
      const currentStepIds = gettingStartedInput.selectedStep;
      if (currentWalkthrough) {
        return new GettingStartedAccessibleProvider(accessor.get($on), accessor.get($sn), accessor.get($O4), editorPane, currentWalkthrough, currentStepIds);
      }
      return;
    };
  }
};
var GettingStartedAccessibleProvider = class extends $3c {
  constructor(c, f, g, h3, j, m) {
    super();
    this.c = c;
    this.f = f;
    this.g = g;
    this.h = h3;
    this.j = j;
    this.m = m;
    this.a = 0;
    this.b = [];
    this.id = "walkthrough";
    this.verbositySettingKey = "accessibility.verbosity.walkthrough";
    this.options = {
      type: "view"
      /* AccessibleViewType.View */
    };
    this.b = j.steps.filter((step) => !step.when || this.c.contextMatchesRules(step.when));
  }
  get actions() {
    const actions = [];
    const step = this.b[this.a];
    const nodes = step.description.map((lt2) => lt2.nodes.filter((node) => typeof node !== "string").map((node) => ({ href: node.href, label: node.label }))).flat();
    if (nodes.length === 1) {
      const node = nodes[0];
      actions.push(new $Um("walthrough.step.action", node.label, ThemeIcon.asClassName($6l.run), true, () => {
        const isCommand = node.href.startsWith("command:");
        const command4 = node.href.replace(/command:(toSide:)?/, "command:");
        if (isCommand) {
          const commandURI = URI.parse(command4);
          let args2 = [];
          try {
            args2 = $bu(decodeURIComponent(commandURI.query));
          } catch {
            try {
              args2 = $bu(commandURI.query);
            } catch {
            }
          }
          if (!Array.isArray(args2)) {
            args2 = [args2];
          }
          this.f.executeCommand(commandURI.path, ...args2);
        } else {
          this.g.open(command4, { allowCommands: true });
        }
      }));
    }
    return actions;
  }
  provideContent() {
    if (this.m) {
      const stepIndex = this.b.findIndex((step) => step.id === this.m);
      if (stepIndex !== -1) {
        this.a = stepIndex;
      }
    }
    return this.n(
      this.j,
      this.b[this.a],
      /* includeTitle */
      true
    );
  }
  n(waltkrough, step, includeTitle) {
    const description = step.description.map((lt2) => lt2.nodes.filter((node) => typeof node === "string")).join("\n");
    const stepsContent = localize(11863, null, step.title, description);
    if (includeTitle) {
      return [
        localize(11864, null, waltkrough.title),
        localize(11865, null, waltkrough.description),
        stepsContent
      ].join("\n");
    } else {
      return stepsContent;
    }
  }
  provideNextContent() {
    if (++this.a >= this.b.length) {
      --this.a;
      return;
    }
    return this.n(this.j, this.b[this.a]);
  }
  providePreviousContent() {
    if (--this.a < 0) {
      ++this.a;
      return;
    }
    return this.n(this.j, this.b[this.a]);
  }
  onClose() {
    if (this.a > -1) {
      const currentStep = this.b[this.a];
      this.h.makeCategoryVisibleWhenAvailable(this.j.id, currentStep.id);
    }
  }
};

// out-build/vs/workbench/contrib/welcomeGettingStarted/browser/gettingStarted.contribution.js
$hJ(class extends $gJ {
  constructor() {
    super({
      id: "workbench.action.openWalkthrough",
      title: localize2(11825, "Welcome"),
      category: $qn.Help,
      f1: true,
      menu: {
        id: $bJ.MenubarHelpMenu,
        group: "1_welcome",
        order: 1
      },
      metadata: {
        description: localize2(11826, "Opens a Walkthrough to help you get started in VS Code.")
      }
    });
  }
  run(accessor, walkthroughID, toSide) {
    const editorGroupsService = accessor.get($iJ);
    const instantiationService = accessor.get($Pk);
    const editorService = accessor.get($mJ);
    const commandService = accessor.get($sn);
    if (walkthroughID) {
      const selectedCategory = typeof walkthroughID === "string" ? walkthroughID : walkthroughID.category;
      let selectedStep;
      if (typeof walkthroughID === "object" && "category" in walkthroughID && "step" in walkthroughID) {
        selectedStep = `${walkthroughID.category}#${walkthroughID.step}`;
      } else {
        selectedStep = void 0;
      }
      if (!selectedCategory && !selectedStep) {
        editorService.openEditor({
          resource: $Wic.RESOURCE,
          options: { preserveFocus: toSide ?? false }
        }, toSide ? $oJ : void 0);
        return;
      }
      for (const group2 of editorGroupsService.groups) {
        if (group2.activeEditor instanceof $Wic) {
          const activeEditor2 = group2.activeEditor;
          activeEditor2.showWelcome = false;
          group2.activeEditorPane.makeCategoryVisibleWhenAvailable(selectedCategory, selectedStep);
          return;
        }
      }
      const result = editorService.findEditors({ typeId: $Wic.ID, editorId: void 0, resource: $Wic.RESOURCE });
      for (const { editor, groupId } of result) {
        if (editor instanceof $Wic) {
          const group2 = editorGroupsService.getGroup(groupId);
          if (!editor.selectedCategory && group2) {
            editor.selectedCategory = selectedCategory;
            editor.selectedStep = selectedStep;
            editor.showWelcome = false;
            group2.openEditor(editor, { revealIfOpened: true });
            return;
          }
        }
      }
      const activeEditor = editorService.activeEditor;
      if (selectedStep && activeEditor instanceof $Wic && activeEditor.selectedCategory === selectedCategory) {
        activeEditor.showWelcome = false;
        commandService.executeCommand("walkthroughs.selectStep", selectedStep);
        return;
      }
      if (activeEditor instanceof $szb) {
        const activeGroup = editorGroupsService.activeGroup;
        activeGroup.replaceEditors([{
          editor: activeEditor,
          replacement: instantiationService.createInstance($Wic, { selectedCategory, selectedStep, showWelcome: false })
        }]);
      } else {
        const options3 = { selectedCategory, selectedStep, showWelcome: false, preserveFocus: toSide ?? false };
        editorService.openEditor({
          resource: $Wic.RESOURCE,
          options: options3
        }, toSide ? $oJ : void 0).then((editor) => {
          editor?.makeCategoryVisibleWhenAvailable(selectedCategory, selectedStep);
        });
      }
    } else {
      editorService.openEditor({
        resource: $Wic.RESOURCE,
        options: { preserveFocus: toSide ?? false }
      }, toSide ? $oJ : void 0);
    }
  }
});
$Wn.as($ZK.EditorFactory).registerEditorSerializer($Wic.ID, $5ic);
$Wn.as($ZK.EditorPane).registerEditorPane($7tb.create($4ic, $4ic.ID, localize(11810, null)), [
  new $Nk($Wic)
]);
var category6 = localize2(11827, "Welcome");
$hJ(class extends $gJ {
  constructor() {
    super({
      id: "welcome.goBack",
      title: localize2(11828, "Go Back"),
      category: category6,
      keybinding: {
        weight: 100,
        primary: 9,
        when: $3ic
      },
      precondition: $7m.equals("activeEditor", "gettingStartedPage"),
      f1: true
    });
  }
  run(accessor) {
    const editorService = accessor.get($mJ);
    const editorPane = editorService.activeEditorPane;
    if (editorPane instanceof $4ic) {
      editorPane.escape();
    }
  }
});
$tn.registerCommand({
  id: "walkthroughs.selectStep",
  handler: (accessor, stepID) => {
    const editorService = accessor.get($mJ);
    const editorPane = editorService.activeEditorPane;
    if (editorPane instanceof $4ic) {
      editorPane.selectStepLoose(stepID);
    } else {
      console.error("Cannot run walkthroughs.selectStep outside of walkthrough context");
    }
  }
});
$hJ(class extends $gJ {
  constructor() {
    super({
      id: "welcome.markStepComplete",
      title: localize(11811, null),
      category: category6
    });
  }
  run(accessor, arg) {
    if (!arg) {
      return;
    }
    const gettingStartedService = accessor.get($Yhc);
    gettingStartedService.progressStep(arg);
  }
});
$hJ(class extends $gJ {
  constructor() {
    super({
      id: "welcome.markStepIncomplete",
      title: localize(11812, null),
      category: category6
    });
  }
  run(accessor, arg) {
    if (!arg) {
      return;
    }
    const gettingStartedService = accessor.get($Yhc);
    gettingStartedService.deprogressStep(arg);
  }
});
$hJ(class extends $gJ {
  constructor() {
    super({
      id: "welcome.showAllWalkthroughs",
      title: localize2(11829, "Open Walkthrough..."),
      category: category6,
      f1: true
    });
  }
  async a(contextService, gettingStartedService) {
    const categories = await gettingStartedService.getWalkthroughs();
    return categories.filter((c) => contextService.contextMatchesRules(c.when)).map((x) => ({
      id: x.id,
      label: x.title,
      detail: x.description,
      description: x.source
    }));
  }
  async run(accessor) {
    const commandService = accessor.get($sn);
    const contextService = accessor.get($on);
    const quickInputService = accessor.get($1M);
    const gettingStartedService = accessor.get($Yhc);
    const extensionService = accessor.get($wN);
    const disposables = new $2c();
    const quickPick = disposables.add(quickInputService.createQuickPick());
    quickPick.canSelectMany = false;
    quickPick.matchOnDescription = true;
    quickPick.matchOnDetail = true;
    quickPick.placeholder = localize(11813, null);
    quickPick.items = await this.a(contextService, gettingStartedService);
    quickPick.busy = true;
    disposables.add(quickPick.onDidAccept(() => {
      const selection = quickPick.selectedItems[0];
      if (selection) {
        commandService.executeCommand("workbench.action.openWalkthrough", selection.id);
      }
      quickPick.hide();
    }));
    disposables.add(quickPick.onDidHide(() => disposables.dispose()));
    await extensionService.whenInstalledExtensionsRegistered();
    gettingStartedService.onDidAddWalkthrough(async () => {
      quickPick.items = await this.a(contextService, gettingStartedService);
    });
    quickPick.show();
    quickPick.busy = false;
  }
});
var $7ic = new $nn("workspacePlatform", void 0, localize(11814, null));
var WorkspacePlatformContribution = class WorkspacePlatformContribution2 {
  static {
    this.ID = "workbench.contrib.workspacePlatform";
  }
  constructor(a, b, d) {
    this.a = a;
    this.b = b;
    this.d = d;
    this.b.getEnvironment().then((env3) => {
      const remoteOS = env3?.os;
      const remotePlatform = remoteOS === 2 ? "mac" : remoteOS === 1 ? "windows" : remoteOS === 3 ? "linux" : void 0;
      if (remotePlatform) {
        $7ic.bindTo(this.d).set(remotePlatform);
      } else if (this.a.localExtensionManagementServer) {
        if ($m) {
          $7ic.bindTo(this.d).set("mac");
        } else if ($n) {
          $7ic.bindTo(this.d).set("linux");
        } else if ($l) {
          $7ic.bindTo(this.d).set("windows");
        }
      } else if (this.a.webExtensionManagementServer) {
        $7ic.bindTo(this.d).set("webworker");
      } else {
        console.error("Error: Unable to detect workspace platform");
      }
    });
  }
};
WorkspacePlatformContribution = __decorate([
  __param(0, $nzb),
  __param(1, $RL),
  __param(2, $on)
], WorkspacePlatformContribution);
var configurationRegistry16 = $Wn.as($Ht.Configuration);
configurationRegistry16.registerConfiguration({
  ...$UL,
  properties: {
    "workbench.welcomePage.walkthroughs.openOnInstall": {
      scope: 2,
      type: "boolean",
      default: true,
      description: localize(11815, null)
    },
    "workbench.startupEditor": {
      "scope": 4,
      "type": "string",
      "enum": ["none", "welcomePage", "readme", "newUntitledFile", "welcomePageInEmptyWorkbench", "terminal"],
      "enumDescriptions": [
        localize(11816, null),
        localize(11817, null),
        localize(11818, null),
        localize(11819, null),
        localize(11820, null),
        localize(11821, null)
      ],
      "default": "welcomePage",
      "description": localize(11822, null)
    },
    "workbench.welcomePage.preferReducedMotion": {
      scope: 1,
      type: "boolean",
      default: false,
      deprecationMessage: localize(11823, null),
      description: localize(11824, null)
    }
  }
});
$PL(
  WorkspacePlatformContribution.ID,
  WorkspacePlatformContribution,
  3
  /* WorkbenchPhase.AfterRestored */
);
$PL(
  $Yic.ID,
  $Yic,
  2
  /* WorkbenchPhase.BlockRestore */
);
$PL(
  $Zic.ID,
  $Zic,
  3
  /* WorkbenchPhase.AfterRestored */
);
$vhb.register(new $6ic());

// out-build/vs/workbench/contrib/welcomeWalkthrough/common/walkThroughContentProvider.js
var WalkThroughContentProviderRegistry = class {
  constructor() {
    this.a = /* @__PURE__ */ new Map();
  }
  registerProvider(moduleId, provider) {
    this.a.set(moduleId, provider);
  }
  getProvider(moduleId) {
    return this.a.get(moduleId);
  }
};
var $8ic = new WalkThroughContentProviderRegistry();
async function $9ic(instantiationService, resource) {
  if (!resource.query) {
    throw new Error("Walkthrough: invalid resource");
  }
  const query = JSON.parse(resource.query);
  if (!query.moduleId) {
    throw new Error("Walkthrough: invalid resource");
  }
  const provider = $8ic.getProvider(query.moduleId);
  if (!provider) {
    throw new Error(`Walkthrough: no provider registered for ${query.moduleId}`);
  }
  return instantiationService.invokeFunction(provider);
}
var $0ic = class $0ic2 {
  static {
    this.ID = "workbench.contrib.walkThroughSnippetContentProvider";
  }
  constructor(b, c, d, e) {
    this.b = b;
    this.c = c;
    this.d = d;
    this.e = e;
    this.a = /* @__PURE__ */ new Map();
    this.b.registerTextModelContentProvider(Schemas.walkThroughSnippet, this);
  }
  async f(resource) {
    let ongoing = this.a.get(resource.toString());
    if (!ongoing) {
      ongoing = $9ic(this.e, resource).then((content) => $MI(content)).finally(() => this.a.delete(resource.toString()));
      this.a.set(resource.toString(), ongoing);
    }
    return ongoing;
  }
  async provideTextContent(resource) {
    const factory = await this.f(resource.with({ fragment: "" }));
    let codeEditorModel = this.d.getModel(resource);
    if (!codeEditorModel) {
      const j = parseInt(resource.fragment);
      let i2 = 0;
      const renderer = new marked.Renderer();
      renderer.code = ({ text: text2, lang }) => {
        i2++;
        const languageId = typeof lang === "string" ? this.c.getLanguageIdByLanguageName(lang) || "" : "";
        const languageSelection = this.c.createById(languageId);
        const model = this.d.createModel(text2, languageSelection, resource.with({ fragment: `${i2}.${lang}` }));
        if (i2 === j) {
          codeEditorModel = model;
        }
        return "";
      };
      const textBuffer = factory.create(
        1
        /* DefaultEndOfLine.LF */
      ).textBuffer;
      const lineCount = textBuffer.getLineCount();
      const range = new $9C(1, 1, lineCount, textBuffer.getLineLength(lineCount) + 1);
      const markdown = textBuffer.getValueInRange(
        range,
        0
        /* EndOfLinePreference.TextDefined */
      );
      marked(markdown, { renderer });
    }
    return $Kg(codeEditorModel);
  }
};
$0ic = __decorate([
  __param(0, $oG),
  __param(1, $1E),
  __param(2, $sG),
  __param(3, $Pk)
], $0ic);

// out-build/vs/workbench/contrib/welcomeWalkthrough/browser/walkThroughInput.js
var $$ic_1;
var WalkThroughModel = class extends $rG {
  constructor(a, b) {
    super();
    this.a = a;
    this.b = b;
  }
  get main() {
    return this.a;
  }
  get snippets() {
    return this.b.map((snippet) => snippet.object);
  }
  dispose() {
    this.b.forEach((ref) => ref.dispose());
    super.dispose();
  }
};
var $$ic = $$ic_1 = class $$ic2 extends $nG {
  get capabilities() {
    return 8 | super.capabilities;
  }
  get resource() {
    return this.h.resource;
  }
  constructor(h3, r2, s) {
    super();
    this.h = h3;
    this.r = r2;
    this.s = s;
    this.a = null;
    this.b = 0;
    this.c = 0;
  }
  get typeId() {
    return this.h.typeId;
  }
  getName() {
    return this.h.name;
  }
  getDescription() {
    return this.h.description || "";
  }
  getTelemetryFrom() {
    return this.h.telemetryFrom;
  }
  getTelemetryDescriptor() {
    const descriptor = super.getTelemetryDescriptor();
    descriptor["target"] = this.getTelemetryFrom();
    return descriptor;
  }
  get onReady() {
    return this.h.onReady;
  }
  get layout() {
    return this.h.layout;
  }
  resolve() {
    if (!this.a) {
      this.a = $9ic(this.r, this.h.resource).then((content) => {
        if (this.resource.path.endsWith(".html")) {
          return new WalkThroughModel(content, []);
        }
        const snippets = [];
        let i2 = 0;
        const renderer = new marked.Renderer();
        renderer.code = ({ lang }) => {
          i2++;
          const resource = this.h.resource.with({ scheme: Schemas.walkThroughSnippet, fragment: `${i2}.${lang}` });
          snippets.push(this.s.createModelReference(resource));
          return `<div id="snippet-${resource.fragment}" class="walkThroughEditorContainer" ></div>`;
        };
        const m = new Marked({ renderer }, $Odc());
        content = m.parse(content, { async: false });
        return Promise.all(snippets).then((refs) => new WalkThroughModel(content, refs));
      });
    }
    return this.a;
  }
  matches(otherInput) {
    if (super.matches(otherInput)) {
      return true;
    }
    if (otherInput instanceof $$ic_1) {
      return $oh(otherInput.h.resource, this.h.resource);
    }
    return false;
  }
  dispose() {
    if (this.a) {
      this.a.then((model) => model.dispose());
      this.a = null;
    }
    super.dispose();
  }
  relativeScrollPosition(topScroll, bottomScroll) {
    this.b = Math.max(this.b, topScroll);
    this.c = Math.max(this.c, bottomScroll);
  }
};
$$ic = $$ic_1 = __decorate([
  __param(1, $Pk),
  __param(2, $oG)
], $$ic);

// out-build/vs/workbench/contrib/welcomeWalkthrough/common/walkThroughUtils.js
var $_ic = $5n("walkThrough.embeddedEditorBackground", { dark: new $Vn(new $Sn(0, 0, 0, 0.4)), light: "#f4f4f4", hcDark: null, hcLight: null }, localize(12123, null));

// out-build/vs/workbench/contrib/welcomeWalkthrough/browser/walkThroughPart.js
var $bjc_1;
var $ajc = new $nn("interactivePlaygroundFocus", false);
var UNBOUND_COMMAND = localize(12121, null);
var WALK_THROUGH_EDITOR_VIEW_STATE_PREFERENCE_KEY = "walkThroughEditorViewState";
var $bjc = class $bjc2 extends $5tb {
  static {
    $bjc_1 = this;
  }
  static {
    this.ID = "workbench.editor.walkThroughPart";
  }
  constructor(group2, telemetryService, themeService, textResourceConfigurationService, s, u, $149, storageService, cb, db, eb, fb, editorGroupService) {
    super($bjc_1.ID, group2, telemetryService, themeService, storageService);
    this.s = s;
    this.u = u;
    this.$ = $149;
    this.cb = cb;
    this.db = db;
    this.eb = eb;
    this.fb = fb;
    this.a = new $2c();
    this.b = [];
    this.g = $ajc.bindTo(this.cb);
    this.r = this.ab(editorGroupService, textResourceConfigurationService, WALK_THROUGH_EDITOR_VIEW_STATE_PREFERENCE_KEY);
  }
  Y(container2) {
    this.c = document.createElement("div");
    this.c.classList.add("welcomePageFocusElement");
    this.c.tabIndex = 0;
    this.c.style.outlineStyle = "none";
    this.f = new $CZ(this.c, {
      horizontal: 1,
      vertical: 1
      /* ScrollbarVisibility.Auto */
    });
    this.a.add(this.f);
    container2.appendChild(this.f.getDomNode());
    this.lb();
    this.mb();
    this.a.add(this.f.onScroll((e) => this.hb()));
  }
  hb() {
    const scrollDimensions = this.f.getScrollDimensions();
    const scrollPosition = this.f.getScrollPosition();
    const scrollHeight = scrollDimensions.scrollHeight;
    if (scrollHeight && this.input instanceof $$ic) {
      const scrollTop = scrollPosition.scrollTop;
      const height = scrollDimensions.height;
      this.input.relativeScrollPosition(scrollTop / scrollHeight, (scrollTop + height) / scrollHeight);
    }
  }
  ib(event) {
    event.preventDefault();
    event.stopPropagation();
    const scrollPosition = this.f.getScrollPosition();
    this.f.setScrollPosition({ scrollTop: scrollPosition.scrollTop - event.translationY });
  }
  jb(element, type, listener, useCapture) {
    element.addEventListener(type, listener, useCapture);
    return $1c(() => {
      element.removeEventListener(type, listener, useCapture);
    });
  }
  lb() {
    this.a.add(this.jb(this.c, "mousedown", (e) => {
      this.focus();
    }));
    this.a.add(this.jb(this.c, "focus", (e) => {
      this.g.set(true);
    }));
    this.a.add(this.jb(this.c, "blur", (e) => {
      this.g.reset();
    }));
    this.a.add(this.jb(this.c, "focusin", (e) => {
      if ($Uj(e.target) && e.target.classList.contains("zone-widget-container")) {
        const scrollPosition = this.f.getScrollPosition();
        this.c.scrollTop = scrollPosition.scrollTop;
        this.c.scrollLeft = scrollPosition.scrollLeft;
      }
      if ($Uj(e.target)) {
        this.j = e.target;
      }
    }));
  }
  mb() {
    this.c.addEventListener("click", (event) => {
      for (let node = event.target; node; node = node.parentNode) {
        if ($Vj(node) && node.href) {
          const baseElement = node.ownerDocument.getElementsByTagName("base")[0] || this.window.location;
          if (baseElement && node.href.indexOf(baseElement.href) >= 0 && node.hash) {
            const scrollTarget = this.c.querySelector(node.hash);
            const innerContent = this.c.firstElementChild;
            if (scrollTarget && innerContent) {
              const targetTop = scrollTarget.getBoundingClientRect().top - 20;
              const containerTop = innerContent.getBoundingClientRect().top;
              this.f.setScrollPosition({ scrollTop: targetTop - containerTop });
            }
          } else {
            this.nb(URI.parse(node.href));
          }
          event.preventDefault();
          break;
        } else if ($Zj(node)) {
          const href = node.getAttribute("data-href");
          if (href) {
            this.nb(URI.parse(href));
          }
          break;
        } else if (node === event.currentTarget) {
          break;
        }
      }
    });
  }
  nb(uri) {
    if (uri.scheme === "command" && uri.path === "git.clone" && !$tn.getCommand("git.clone")) {
      this.eb.info(localize(12122, null));
      return;
    }
    this.u.open(this.ob(uri), { allowCommands: true });
  }
  ob(uri) {
    if (uri.scheme !== "command" || !(this.input instanceof $$ic)) {
      return uri;
    }
    const query = uri.query ? JSON.parse(uri.query) : {};
    query.from = this.input.getTelemetryFrom();
    return uri.with({ query: JSON.stringify(query) });
  }
  layout(dimension) {
    this.m = dimension;
    $tj(this.c, dimension.width, dimension.height);
    this.pb();
    this.b.forEach((disposable) => {
      if (disposable instanceof $D9) {
        disposable.layout();
      }
    });
    const walkthroughInput = this.input instanceof $$ic && this.input;
    if (walkthroughInput && walkthroughInput.layout) {
      walkthroughInput.layout(dimension);
    }
    this.f.scanDomNode();
  }
  pb() {
    const innerContent = this.c.firstElementChild;
    if (this.m && innerContent) {
      innerContent.classList.toggle("max-height-685px", this.m.height <= 685);
    }
  }
  focus() {
    super.focus();
    let active = this.c.ownerDocument.activeElement;
    while (active && active !== this.c) {
      active = active.parentElement;
    }
    if (!active) {
      (this.j || this.c).focus();
    }
    this.g.set(true);
  }
  arrowUp() {
    const scrollPosition = this.f.getScrollPosition();
    this.f.setScrollPosition({ scrollTop: scrollPosition.scrollTop - this.qb() });
  }
  arrowDown() {
    const scrollPosition = this.f.getScrollPosition();
    this.f.setScrollPosition({ scrollTop: scrollPosition.scrollTop + this.qb() });
  }
  qb() {
    let fontSize = this.db.getValue("editor.fontSize");
    if (typeof fontSize !== "number" || fontSize < 1) {
      fontSize = 12;
    }
    return 3 * fontSize;
  }
  pageUp() {
    const scrollDimensions = this.f.getScrollDimensions();
    const scrollPosition = this.f.getScrollPosition();
    this.f.setScrollPosition({ scrollTop: scrollPosition.scrollTop - scrollDimensions.height });
  }
  pageDown() {
    const scrollDimensions = this.f.getScrollDimensions();
    const scrollPosition = this.f.getScrollPosition();
    this.f.setScrollPosition({ scrollTop: scrollPosition.scrollTop + scrollDimensions.height });
  }
  setInput(input, options3, context, token) {
    const store = new $2c();
    this.b.push(store);
    this.c.innerText = "";
    return super.setInput(input, options3, context, token).then(async () => {
      if (input.resource.path.endsWith(".md")) {
        await this.fb.whenInstalledExtensionsRegistered();
      }
      return input.resolve();
    }).then((model) => {
      if (token.isCancellationRequested) {
        return;
      }
      const content = model.main;
      if (!input.resource.path.endsWith(".md")) {
        $wk(this.c, content, { ALLOW_UNKNOWN_PROTOCOLS: true });
        this.pb();
        this.tb();
        this.b.push(this.$.onDidUpdateKeybindings(() => this.tb()));
        input.onReady?.(this.c.firstElementChild, store);
        this.f.scanDomNode();
        this.wb(input);
        this.hb();
        return;
      }
      const innerContent = document.createElement("div");
      innerContent.classList.add("walkThroughContent");
      const markdown = this.sb(content);
      $wk(innerContent, markdown, { ALLOW_UNKNOWN_PROTOCOLS: true });
      this.c.appendChild(innerContent);
      model.snippets.forEach((snippet, i2) => {
        const model2 = snippet.textEditorModel;
        if (!model2) {
          return;
        }
        const id2 = `snippet-${model2.uri.fragment}`;
        const div = innerContent.querySelector(`#${id2.replace(/[\\.]/g, "\\$&")}`);
        const options4 = this.rb(model2.getLanguageId());
        const telemetryData = {
          target: this.input instanceof $$ic ? this.input.getTelemetryFrom() : void 0,
          snippet: i2
        };
        const editor = this.s.createInstance($D9, div, options4, {
          telemetryData
        });
        editor.setModel(model2);
        this.b.push(editor);
        const updateHeight = (initial) => {
          const lineHeight = editor.getOption(
            68
            /* EditorOption.lineHeight */
          );
          const height = `${Math.max(model2.getLineCount() + 1, 4) * lineHeight}px`;
          if (div.style.height !== height) {
            div.style.height = height;
            editor.layout();
            if (!initial) {
              this.f.scanDomNode();
            }
          }
        };
        updateHeight(true);
        this.b.push(editor.onDidChangeModelContent(() => updateHeight(false)));
        this.b.push(editor.onDidChangeCursorPosition((e) => {
          const innerContent2 = this.c.firstElementChild;
          if (innerContent2) {
            const targetTop = div.getBoundingClientRect().top;
            const containerTop = innerContent2.getBoundingClientRect().top;
            const lineHeight = editor.getOption(
              68
              /* EditorOption.lineHeight */
            );
            const lineTop = targetTop + (e.position.lineNumber - 1) * lineHeight - containerTop;
            const lineBottom = lineTop + lineHeight;
            const scrollDimensions = this.f.getScrollDimensions();
            const scrollPosition = this.f.getScrollPosition();
            const scrollTop = scrollPosition.scrollTop;
            const height = scrollDimensions.height;
            if (scrollTop > lineTop) {
              this.f.setScrollPosition({ scrollTop: lineTop });
            } else if (scrollTop < lineBottom - height) {
              this.f.setScrollPosition({ scrollTop: lineBottom - height });
            }
          }
        }));
        this.b.push(this.db.onDidChangeConfiguration((e) => {
          if (e.affectsConfiguration("editor") && snippet.textEditorModel) {
            editor.updateOptions(this.rb(snippet.textEditorModel.getLanguageId()));
          }
        }));
      });
      this.pb();
      this.ub();
      this.b.push(this.db.onDidChangeConfiguration((e) => {
        if (e.affectsConfiguration("editor.multiCursorModifier")) {
          this.ub();
        }
      }));
      input.onReady?.(innerContent, store);
      this.f.scanDomNode();
      this.wb(input);
      this.hb();
      this.b.push($mZ.addTarget(innerContent));
      this.b.push($_i(innerContent, EventType.Change, (e) => this.ib(e)));
    });
  }
  rb(language) {
    const config = $Lv(this.db.getValue("editor", { overrideIdentifier: language }));
    return {
      ...$Bg(config) ? config : /* @__PURE__ */ Object.create(null),
      scrollBeyondLastLine: false,
      scrollbar: {
        verticalScrollbarSize: 14,
        horizontal: "auto",
        useShadows: true,
        verticalHasArrows: false,
        horizontalHasArrows: false,
        alwaysConsumeMouseWheel: false
      },
      overviewRulerLanes: 3,
      fixedOverflowWidgets: false,
      lineNumbersMinChars: 1,
      minimap: { enabled: false }
    };
  }
  sb(input) {
    return input.replace(/kb\(([a-z.\d\-]+)\)/gi, (match, kb) => {
      const keybinding = this.$.lookupKeybinding(kb);
      const shortcut = keybinding ? keybinding.getLabel() || "" : UNBOUND_COMMAND;
      return `<span class="shortcut">${$zf(shortcut)}</span>`;
    });
  }
  tb() {
    const keys = this.c.querySelectorAll(".shortcut[data-command]");
    Array.prototype.forEach.call(keys, (key2) => {
      const command4 = key2.getAttribute("data-command");
      const keybinding = command4 && this.$.lookupKeybinding(command4);
      const label3 = keybinding ? keybinding.getLabel() || "" : UNBOUND_COMMAND;
      while (key2.firstChild) {
        key2.firstChild.remove();
      }
      key2.appendChild(document.createTextNode(label3));
    });
    const ifkeys = this.c.querySelectorAll(".if_shortcut[data-command]");
    Array.prototype.forEach.call(ifkeys, (key2) => {
      const command4 = key2.getAttribute("data-command");
      const keybinding = command4 && this.$.lookupKeybinding(command4);
      key2.style.display = !keybinding ? "none" : "";
    });
  }
  ub() {
    const labels2 = $X2.modifierLabels[OS];
    const value = this.db.getValue("editor.multiCursorModifier");
    const modifier = labels2[value === "ctrlCmd" ? OS === 2 ? "metaKey" : "ctrlKey" : "altKey"];
    const keys = this.c.querySelectorAll(".multi-cursor-modifier");
    Array.prototype.forEach.call(keys, (key2) => {
      while (key2.firstChild) {
        key2.firstChild.remove();
      }
      key2.appendChild(document.createTextNode(modifier));
    });
  }
  vb(input) {
    const scrollPosition = this.f.getScrollPosition();
    this.r.saveEditorState(this.group, input, {
      viewState: {
        scrollTop: scrollPosition.scrollTop,
        scrollLeft: scrollPosition.scrollLeft
      }
    });
  }
  wb(input) {
    const state = this.r.loadEditorState(this.group, input);
    if (state) {
      this.f.setScrollPosition(state.viewState);
    }
  }
  clearInput() {
    if (this.input instanceof $$ic) {
      this.vb(this.input);
    }
    this.b = $Xc(this.b);
    super.clearInput();
  }
  I() {
    if (this.input instanceof $$ic) {
      this.vb(this.input);
    }
    super.I();
  }
  dispose() {
    this.g.reset();
    this.b = $Xc(this.b);
    this.a.dispose();
    super.dispose();
  }
};
$bjc = $bjc_1 = __decorate([
  __param(1, $zv),
  __param(2, $gs),
  __param(3, $zG),
  __param(4, $Pk),
  __param(5, $O4),
  __param(6, $Ty),
  __param(7, $jv),
  __param(8, $on),
  __param(9, $kl),
  __param(10, $PJ),
  __param(11, $wN),
  __param(12, $iJ)
], $bjc);

// out-build/vs/workbench/contrib/welcomeWalkthrough/browser/walkThroughActions.js
var $cjc = {
  id: "workbench.action.interactivePlayground.arrowUp",
  weight: 200,
  when: $7m.and($ajc, EditorContextKeys.editorTextFocus.toNegated()),
  primary: 16,
  handler: (accessor) => {
    const editorService = accessor.get($mJ);
    const activeEditorPane = editorService.activeEditorPane;
    if (activeEditorPane instanceof $bjc) {
      activeEditorPane.arrowUp();
    }
  }
};
var $djc = {
  id: "workbench.action.interactivePlayground.arrowDown",
  weight: 200,
  when: $7m.and($ajc, EditorContextKeys.editorTextFocus.toNegated()),
  primary: 18,
  handler: (accessor) => {
    const editorService = accessor.get($mJ);
    const activeEditorPane = editorService.activeEditorPane;
    if (activeEditorPane instanceof $bjc) {
      activeEditorPane.arrowDown();
    }
  }
};
var $ejc = {
  id: "workbench.action.interactivePlayground.pageUp",
  weight: 200,
  when: $7m.and($ajc, EditorContextKeys.editorTextFocus.toNegated()),
  primary: 11,
  handler: (accessor) => {
    const editorService = accessor.get($mJ);
    const activeEditorPane = editorService.activeEditorPane;
    if (activeEditorPane instanceof $bjc) {
      activeEditorPane.pageUp();
    }
  }
};
var $fjc = {
  id: "workbench.action.interactivePlayground.pageDown",
  weight: 200,
  when: $7m.and($ajc, EditorContextKeys.editorTextFocus.toNegated()),
  primary: 12,
  handler: (accessor) => {
    const editorService = accessor.get($mJ);
    const activeEditorPane = editorService.activeEditorPane;
    if (activeEditorPane instanceof $bjc) {
      activeEditorPane.pageDown();
    }
  }
};

// out-build/vs/workbench/contrib/welcomeWalkthrough/browser/editor/vs_code_editor_walkthrough.js
function $gjc(accessor) {
  const isServerless = $r && !accessor.get($US).remoteAuthority;
  return `
## Interactive Editor Playground
The core editor in VS Code is packed with features.  This page highlights a number of them and lets you interactively try them out through the use of a number of embedded editors.  For full details on the editor features for VS Code and more head over to our [documentation](https://code.visualstudio.com/docs).

* [Multi-cursor Editing](#multi-cursor-editing) - block selection, select all occurrences, add additional cursors and more.
* [IntelliSense](#intellisense) - get code assistance and parameter suggestions for your code and external modules.
* [Line Actions](#line-actions) - quickly move lines around to re-order your code.${!isServerless ? `
* [Rename Refactoring](#rename-refactoring) - quickly rename symbols across your code base.` : ""}
* [Formatting](#formatting) - keep your code looking great with inbuilt document & selection formatting.
* [Code Folding](#code-folding) - focus on the most relevant parts of your code by folding other areas.
* [Errors and Warnings](#errors-and-warnings) - see errors and warnings as you type.
* [Snippets](#snippets) - spend less time typing with snippets.
* [Emmet](#emmet) - integrated Emmet support takes HTML and CSS editing to the next level.
* [JavaScript Type Checking](#javascript-type-checking) - perform type checking on your JavaScript file using TypeScript with zero configuration.



### Multi-Cursor Editing
Using multiple cursors allows you to edit multiple parts of the document at once, greatly improving your productivity.  Try the following actions in the code block below:
1. Box Selection - press <span class="mac-only windows-only">any combination of kb(cursorColumnSelectDown), kb(cursorColumnSelectRight), kb(cursorColumnSelectUp), kb(cursorColumnSelectLeft) to select a block of text. You can also press</span> <span class="shortcut mac-only">|\u21E7\u2325|</span><span class="shortcut windows-only linux-only">|Shift+Alt|</span> while selecting text with the mouse or drag-select using the middle mouse button.
2. Add a cursor - press kb(editor.action.insertCursorAbove) to add a new cursor above, or kb(editor.action.insertCursorBelow) to add a new cursor below. You can also use your mouse with <span class="shortcut"><span class="multi-cursor-modifier"></span>+Click</span> to add a cursor anywhere.
3. Create cursors on all occurrences of a string - select one instance of a string e.g. |background-color| and press kb(editor.action.selectHighlights).  Now you can replace all instances by simply typing.

That is the tip of the iceberg for multi-cursor editing. Have a look at the selection menu and our handy [keyboard reference guide](command:workbench.action.keybindingsReference) for additional actions.

|||css
#p1 {background-color: #ff0000;}                /* red in HEX format */
#p2 {background-color: hsl(120, 100%, 50%);}    /* green in HSL format */
#p3 {background-color: rgba(0, 4, 255, 0.733);} /* blue with alpha channel in RGBA format */
|||

> **CSS Tip:** You may have noticed in the example above we also provide color swatches inline for CSS, additionally if you hover over an element such as |#p1| we will show how this is represented in HTML.  These swatches also act as color pickers that allow you to easily change a color value.  A simple example of some language-specific editor features.

### IntelliSense

Visual Studio Code comes with the powerful IntelliSense for JavaScript and TypeScript pre-installed. In the below example, position the text cursor right after the dot and press kb(editor.action.triggerSuggest) to invoke IntelliSense.  Notice how the suggestions come from the Canvas API.

|||js
const canvas = document.querySelector('canvas');
const context = canvas.getContext('2d');

context.strokeStyle = 'blue';
context.
|||

>**Tip:** While we ship JavaScript and TypeScript support out of the box other languages can be upgraded with better IntelliSense through one of the many [extensions](command:workbench.extensions.action.showPopularExtensions).


### Line Actions
Since it's very common to work with the entire text in a line we provide a set of useful shortcuts to help with this.
1. <span class="mac-only windows-only">Copy a line and insert it above or below the current position with kb(editor.action.copyLinesDownAction) or kb(editor.action.copyLinesUpAction) respectively.</span><span class="linux-only">Copy the entire current line when no text is selected with kb(editor.action.clipboardCopyAction).</span>
2. Move an entire line or selection of lines up or down with kb(editor.action.moveLinesUpAction) and kb(editor.action.moveLinesDownAction) respectively.
3. Delete the entire line with kb(editor.action.deleteLines).

|||json
{
	"name": "John",
	"age": 31,
	"city": "New York"
}
|||

>**Tip:** Another very common task is to comment out a block of code - you can toggle commenting by pressing kb(editor.action.commentLine).


${!isServerless ? `
### Rename Refactoring
It's easy to rename a symbol such as a function name or variable name.  Hit kb(editor.action.rename) while in the symbol |Book| to rename all instances - this will occur across all files in a project. You also have |Rename Symbol| in the right-click context menu.

|||js
// Reference the function
new Book("War of the Worlds", "H G Wells");
new Book("The Martian", "Andy Weir");

/**
 * Represents a book.
 *
 * @param {string} title Title of the book
 * @param {string} author Who wrote the book
 */
function Book(title, author) {
	this.title = title;
	this.author = author;
}
|||

> **JSDoc Tip:** VS Code's IntelliSense uses JSDoc comments to provide richer suggestions. The types and documentation from JSDoc comments show up when you hover over a reference to |Book| or in IntelliSense when you create a new instance of |Book|.

` : ""}
### Formatting
Keeping your code looking great is hard without a good formatter.  Luckily it's easy to format content, either for the entire document with kb(editor.action.formatDocument) or for the current selection with kb(editor.action.formatSelection).  Both of these options are also available through the right-click context menu.

|||js
const cars = ["\u{1F697}", "\u{1F699}", "\u{1F695}"];

for (const car of cars){
	// Drive the car
	console.log(|This is the car \${car}|);
}
|||

>**Tip:** Additional formatters are available in the [extension gallery](command:workbench.extensions.action.showPopularExtensions).  Formatting support can also be configured via [settings](command:workbench.action.openGlobalSettings) e.g. enabling |editor.formatOnSave|.


### Code Folding
In a large file it can often be useful to collapse sections of code to increase readability.  To do this, you can simply press kb(editor.fold) to fold or press kb(editor.unfold) to unfold the ranges at the current cursor position.  Folding can also be done with the down and right angle bracket icons in the left gutter.  To fold all sections use kb(editor.foldAll) or to unfold all use kb(editor.unfoldAll).

|||html
<div>
	<header>
		<ul>
			<li><a href=""></a></li>
			<li><a href=""></a></li>
		</ul>
	</header>
	<footer>
		<p></p>
	</footer>
</div>
|||

>**Tip:** Folding is based on indentation and as a result can apply to all languages.  Simply indent your code to create a foldable section you can fold a certain number of levels with shortcuts like kb(editor.foldLevel1) through to kb(editor.foldLevel5).

### Errors and Warnings
Errors and warnings are highlighted as you edit your code with squiggles.  In the sample below you can see a number of syntax errors.  By pressing kb(editor.action.marker.nextInFiles) you can navigate across them in sequence and see the detailed error message.  As you correct them the squiggles and scrollbar indicators will update.

|||js
// This code has a few syntax errors
Console.log(add(1, 1.5));


function Add(a, b)
	return a + b;
}
|||


###  Snippets
You can greatly accelerate your editing through the use of snippets.  Simply start typing |try| and select |trycatch| from the suggestion list and press kb(insertSnippet) to create a |try|->|catch| block.  Your cursor will be placed on the text |error| for easy editing.  If more than one parameter exists then press kb(jumpToNextSnippetPlaceholder) to jump to it.

|||js

|||

>**Tip:** The [extension gallery](command:workbench.extensions.action.showPopularExtensions) includes snippets for almost every framework and language imaginable.  You can also create your own [user-defined snippets](command:workbench.action.openSnippets).


### Emmet
Emmet takes the snippets idea to a whole new level: you can type CSS-like expressions that can be dynamically parsed, and produce output depending on what you type in the abbreviation. Try it by selecting |Emmet: Expand Abbreviation| from the |Edit| menu with the cursor at the end of a valid Emmet abbreviation or snippet and the expansion will occur.

|||html
ul>li.item$*5
|||

>**Tip:** The [Emmet cheat sheet](https://docs.emmet.io/cheat-sheet/) is a great source of Emmet syntax suggestions. To expand Emmet abbreviations and snippets using the |tab| key use the |emmet.triggerExpansionOnTab| [setting](command:workbench.action.openGlobalSettings). Check out the docs on [Emmet in VS Code](https://code.visualstudio.com/docs/editor/emmet) to learn more.



### JavaScript Type Checking
Sometimes type checking your JavaScript code can help you spot mistakes you might have not caught otherwise. You can run the TypeScript type checker against your existing JavaScript code by simply adding a |// @ts-check| comment to the top of your file.

|||js
// @ts-nocheck

let easy = true;
easy = 42;
|||

>**Tip:** You can also enable the checks workspace or application wide by adding |"js/ts.implicitProjectConfig.checkJs": true| to your workspace or user settings and explicitly ignoring files or lines using |// @ts-nocheck| and |// @ts-expect-error|. Check out the docs on [JavaScript in VS Code](https://code.visualstudio.com/docs/languages/javascript) to learn more.


## Thanks!
Well if you have got this far then you will have touched on some of the editing features in Visual Studio Code.  But don't stop now :)  We have lots of additional [documentation](https://code.visualstudio.com/docs), [introductory videos](https://code.visualstudio.com/docs/getstarted/introvideos) and [tips and tricks](https://go.microsoft.com/fwlink/?linkid=852118) for the product that will help you learn how to use it.  And while you are here, here are a few additional things you can try:
- Open the Integrated Terminal by pressing kb(workbench.action.terminal.toggleTerminal), then see what's possible by [reviewing the terminal documentation](https://code.visualstudio.com/docs/editor/integrated-terminal)
- Work with version control by pressing kb(workbench.view.scm). Understand how to stage, commit, change branches, and view diffs and more by reviewing the [version control documentation](https://code.visualstudio.com/docs/editor/versioncontrol)
- Browse thousands of extensions in our integrated gallery by pressing kb(workbench.view.extensions). The [documentation](https://code.visualstudio.com/docs/editor/extension-gallery) will show you how to see the most popular extensions, disable installed ones and more.

That's all for now,

Happy Coding! \u{1F389}

`.replace(/\|/g, "`");
}

// out-build/vs/workbench/contrib/welcomeWalkthrough/browser/editor/editorWalkThrough.js
$8ic.registerProvider("vs/workbench/contrib/welcomeWalkthrough/browser/editor/vs_code_editor_walkthrough", $gjc);
var typeId = "workbench.editors.walkThroughInput";
var inputOptions = {
  typeId,
  name: localize(12116, null),
  resource: $ih.asBrowserUri("vs/workbench/contrib/welcomeWalkthrough/browser/editor/vs_code_editor_walkthrough.md").with({
    scheme: Schemas.walkThrough,
    query: JSON.stringify({ moduleId: "vs/workbench/contrib/welcomeWalkthrough/browser/editor/vs_code_editor_walkthrough" })
  }),
  telemetryFrom: "walkThrough"
};
var $hjc = class _$hjc extends $gJ {
  static {
    this.ID = "workbench.action.showInteractivePlayground";
  }
  static {
    this.LABEL = localize2(12117, "Interactive Editor Playground");
  }
  constructor() {
    super({
      id: _$hjc.ID,
      title: _$hjc.LABEL,
      category: $qn.Help,
      f1: true,
      metadata: {
        description: localize2(12118, "Opens an interactive playground for learning about the editor.")
      }
    });
  }
  run(serviceAccessor) {
    const editorService = serviceAccessor.get($mJ);
    const instantiationService = serviceAccessor.get($Pk);
    const input = instantiationService.createInstance($$ic, inputOptions);
    return editorService.openEditor(input, { pinned: true }).then(() => void 0);
  }
};
var $ijc = class {
  static {
    this.ID = typeId;
  }
  canSerialize(editorInput) {
    return true;
  }
  serialize(editorInput) {
    return "";
  }
  deserialize(instantiationService) {
    return instantiationService.createInstance($$ic, inputOptions);
  }
};

// out-build/vs/workbench/contrib/welcomeWalkthrough/browser/walkThrough.contribution.js
$Wn.as($ZK.EditorPane).registerEditorPane($7tb.create($bjc, $bjc.ID, localize(12119, null)), [new $Nk($$ic)]);
$hJ($hjc);
$Wn.as($ZK.EditorFactory).registerEditorSerializer($ijc.ID, $ijc);
$PL($0ic.ID, $0ic, { editorTypeId: $bjc.ID });
$0I.registerCommandAndKeybindingRule($cjc);
$0I.registerCommandAndKeybindingRule($djc);
$0I.registerCommandAndKeybindingRule($ejc);
$0I.registerCommandAndKeybindingRule($fjc);
$dJ.appendMenuItem($bJ.MenubarHelpMenu, {
  group: "1_welcome",
  command: {
    id: "workbench.action.showInteractivePlayground",
    title: localize(12120, null)
  },
  order: 3
});

// out-build/vs/workbench/contrib/welcomeViews/common/viewsWelcomeExtensionPoint.js
var ViewsWelcomeExtensionPointFields;
(function(ViewsWelcomeExtensionPointFields2) {
  ViewsWelcomeExtensionPointFields2["view"] = "view";
  ViewsWelcomeExtensionPointFields2["contents"] = "contents";
  ViewsWelcomeExtensionPointFields2["when"] = "when";
  ViewsWelcomeExtensionPointFields2["group"] = "group";
  ViewsWelcomeExtensionPointFields2["enablement"] = "enablement";
})(ViewsWelcomeExtensionPointFields || (ViewsWelcomeExtensionPointFields = {}));
var $jjc = {
  "explorer": "workbench.explorer.emptyView",
  "debug": "workbench.debug.welcome",
  "scm": "workbench.scm",
  "testing": "workbench.view.testing"
};
var viewsWelcomeExtensionPointSchema = Object.freeze({
  type: "array",
  description: localize(12108, null),
  items: {
    type: "object",
    description: localize(12109, null),
    required: [
      ViewsWelcomeExtensionPointFields.view,
      ViewsWelcomeExtensionPointFields.contents
    ],
    properties: {
      [ViewsWelcomeExtensionPointFields.view]: {
        anyOf: [
          {
            type: "string",
            description: localize(12110, null)
          },
          {
            type: "string",
            description: localize(12111, null),
            enum: Object.keys($jjc)
          }
        ]
      },
      [ViewsWelcomeExtensionPointFields.contents]: {
        type: "string",
        description: localize(12112, null)
      },
      [ViewsWelcomeExtensionPointFields.when]: {
        type: "string",
        description: localize(12113, null)
      },
      [ViewsWelcomeExtensionPointFields.group]: {
        type: "string",
        description: localize(12114, null)
      },
      [ViewsWelcomeExtensionPointFields.enablement]: {
        type: "string",
        description: localize(12115, null)
      }
    }
  }
});
var $kjc = {
  extensionPoint: "viewsWelcome",
  jsonSchema: viewsWelcomeExtensionPointSchema
};

// out-build/vs/workbench/contrib/welcomeViews/common/viewsWelcomeContribution.js
var viewsRegistry7 = $Wn.as(Extensions5.ViewsRegistry);
var $ljc = class extends $3c {
  constructor(extensionPoint2) {
    super();
    this.a = /* @__PURE__ */ new Map();
    extensionPoint2.setHandler((_, { added, removed }) => {
      for (const contribution of removed) {
        for (const welcome of contribution.value) {
          const disposable = this.a.get(welcome);
          disposable?.dispose();
        }
      }
      const welcomesByViewId = /* @__PURE__ */ new Map();
      for (const contribution of added) {
        for (const welcome of contribution.value) {
          const { group: group2, order } = parseGroupAndOrder(welcome, contribution);
          const precondition2 = $7m.deserialize(welcome.enablement);
          const id2 = $jjc[welcome.view] ?? welcome.view;
          let viewContentMap = welcomesByViewId.get(id2);
          if (!viewContentMap) {
            viewContentMap = /* @__PURE__ */ new Map();
            welcomesByViewId.set(id2, viewContentMap);
          }
          viewContentMap.set(welcome, {
            content: welcome.contents,
            when: $7m.deserialize(welcome.when),
            precondition: precondition2,
            group: group2,
            order
          });
        }
      }
      for (const [id2, viewContentMap] of welcomesByViewId) {
        const disposables = viewsRegistry7.registerViewWelcomeContent2(id2, viewContentMap);
        for (const [welcome, disposable] of disposables) {
          this.a.set(welcome, disposable);
        }
      }
    });
  }
};
function parseGroupAndOrder(welcome, contribution) {
  let group2;
  let order;
  if (welcome.group) {
    if (!$zN(contribution.description, "contribViewsWelcome")) {
      contribution.collector.warn(localize(12107, null, contribution.description.identifier.value));
      return { group: group2, order };
    }
    const idx = welcome.group.lastIndexOf("@");
    if (idx > 0) {
      group2 = welcome.group.substr(0, idx);
      order = Number(welcome.group.substr(idx + 1)) || void 0;
    } else {
      group2 = welcome.group;
    }
  }
  return { group: group2, order };
}

// out-build/vs/workbench/contrib/welcomeViews/common/viewsWelcome.contribution.js
var extensionPoint = $tN.registerExtensionPoint($kjc);
var WorkbenchConfigurationContribution = class WorkbenchConfigurationContribution2 {
  constructor(instantiationService) {
    instantiationService.createInstance($ljc, extensionPoint);
  }
};
WorkbenchConfigurationContribution = __decorate([
  __param(0, $Pk)
], WorkbenchConfigurationContribution);
$Wn.as(Extensions2.Workbench).registerWorkbenchContribution(
  WorkbenchConfigurationContribution,
  3
  /* LifecyclePhase.Restored */
);

// out-build/vs/workbench/contrib/welcomeViews/common/newFile.contribution.js
var NewFileTemplatesManager_1;
var builtInSource = localize(12097, null);
var category7 = localize2(12105, "Create");
$hJ(class extends $gJ {
  constructor() {
    super({
      id: "welcome.showNewFileEntries",
      title: localize2(12106, "New File..."),
      category: category7,
      f1: true,
      keybinding: {
        primary: 512 + 2048 + 256 + 44,
        weight: 200
      },
      menu: {
        id: $bJ.MenubarFileMenu,
        group: "1_new",
        order: 2
      }
    });
  }
  async run(accessor) {
    return $Kg(NewFileTemplatesManager.Instance).run();
  }
});
var NewFileTemplatesManager = class NewFileTemplatesManager2 extends $3c {
  static {
    NewFileTemplatesManager_1 = this;
  }
  constructor(f, g, h3, j, menuService) {
    super();
    this.f = f;
    this.g = g;
    this.h = h3;
    this.j = j;
    NewFileTemplatesManager_1.Instance = this;
    this.B({ dispose() {
      if (NewFileTemplatesManager_1.Instance === this) {
        NewFileTemplatesManager_1.Instance = void 0;
      }
    } });
    this.c = menuService.createMenu($bJ.NewFile, g);
  }
  m() {
    const items = [];
    for (const [groupName, group2] of this.c.getActions({ renderShortTitle: true })) {
      for (const action of group2) {
        if (action instanceof $fJ) {
          items.push({ commandID: action.item.id, from: action.item.source?.title ?? builtInSource, title: action.label, group: groupName });
        }
      }
    }
    return items;
  }
  async run() {
    const entries2 = this.m();
    if (entries2.length === 0) {
      throw Error("Unexpected empty new items list");
    } else if (entries2.length === 1) {
      this.h.executeCommand(entries2[0].commandID);
      return true;
    } else {
      return this.n(entries2);
    }
  }
  async n(entries2) {
    const { promise: resultPromise, resolve: resolveResult } = $Oh();
    const disposables = new $2c();
    const qp = this.f.createQuickPick({ useSeparators: true });
    qp.title = localize(12098, null);
    qp.placeholder = localize(12099, null);
    qp.sortByLabel = false;
    qp.matchOnDetail = true;
    qp.matchOnDescription = true;
    const sortCategories = (a, b) => {
      const categoryPriority = { "file": 1, "notebook": 2 };
      if (categoryPriority[a.group] && categoryPriority[b.group]) {
        if (categoryPriority[a.group] !== categoryPriority[b.group]) {
          return categoryPriority[b.group] - categoryPriority[a.group];
        }
      } else if (categoryPriority[a.group]) {
        return 1;
      } else if (categoryPriority[b.group]) {
        return -1;
      }
      if (a.from === builtInSource) {
        return 1;
      }
      if (b.from === builtInSource) {
        return -1;
      }
      return a.from.localeCompare(b.from);
    };
    const displayCategory = {
      "file": localize(12100, null),
      "notebook": localize(12101, null)
    };
    const refreshQp = (entries3) => {
      const items = [];
      let lastSeparator;
      entries3.sort((a, b) => -sortCategories(a, b)).forEach((entry) => {
        const command4 = entry.commandID;
        const keybinding = this.j.lookupKeybinding(command4 || "", this.g);
        if (lastSeparator !== entry.group) {
          items.push({
            type: "separator",
            label: displayCategory[entry.group] ?? entry.group
          });
          lastSeparator = entry.group;
        }
        items.push({
          ...entry,
          label: entry.title,
          type: "item",
          keybinding,
          buttons: command4 ? [
            {
              iconClass: "codicon codicon-gear",
              tooltip: localize(12102, null)
            }
          ] : [],
          detail: "",
          description: entry.from
        });
      });
      qp.items = items;
    };
    refreshQp(entries2);
    disposables.add(this.c.onDidChange(() => refreshQp(this.m())));
    disposables.add(qp.onDidChangeValue((val) => {
      if (val === "") {
        refreshQp(entries2);
        return;
      }
      const currentTextEntry = {
        commandID: "workbench.action.files.newFile",
        commandArgs: { languageId: void 0, viewType: void 0, fileName: val },
        title: localize(12103, null, val),
        group: "file",
        from: builtInSource
      };
      refreshQp([currentTextEntry, ...entries2]);
    }));
    disposables.add(qp.onDidAccept(async (e) => {
      const selected = qp.selectedItems[0];
      resolveResult(!!selected);
      qp.hide();
      if (selected) {
        await this.h.executeCommand(selected.commandID, selected.commandArgs);
      }
    }));
    disposables.add(qp.onDidHide(() => {
      qp.dispose();
      disposables.dispose();
      resolveResult(false);
    }));
    disposables.add(qp.onDidTriggerItemButton((e) => {
      qp.hide();
      this.h.executeCommand("workbench.action.openGlobalKeybindings", e.item.commandID);
      resolveResult(false);
    }));
    qp.show();
    return resultPromise;
  }
};
NewFileTemplatesManager = NewFileTemplatesManager_1 = __decorate([
  __param(0, $1M),
  __param(1, $on),
  __param(2, $sn),
  __param(3, $Ty),
  __param(4, $cJ)
], NewFileTemplatesManager);
$Wn.as(Extensions2.Workbench).registerWorkbenchContribution(
  NewFileTemplatesManager,
  3
  /* LifecyclePhase.Restored */
);
$dJ.appendMenuItem($bJ.NewFile, {
  group: "file",
  command: {
    id: "workbench.action.files.newUntitledFile",
    title: localize(12104, null)
  },
  order: 1
});

// out-build/vs/workbench/contrib/callHierarchy/browser/callHierarchyTree.js
var Call = class {
  constructor(item, locations, model, parent) {
    this.item = item;
    this.locations = locations;
    this.model = model;
    this.parent = parent;
  }
  static compare(a, b) {
    let res = $Tf(a.item.uri.toString(), b.item.uri.toString());
    if (res === 0) {
      res = $9C.compareRangesUsingStarts(a.item.range, b.item.range);
    }
    return res;
  }
};
var $njc = class {
  constructor(getDirection) {
    this.getDirection = getDirection;
  }
  hasChildren() {
    return true;
  }
  async getChildren(element) {
    if (element instanceof $dN) {
      return element.roots.map((root) => new Call(root, void 0, element, void 0));
    }
    const { model, item } = element;
    if (this.getDirection() === "outgoingCalls") {
      return (await model.resolveOutgoingCalls(item, CancellationToken.None)).map((call) => {
        return new Call(call.to, call.fromRanges.map((range) => ({ range, uri: item.uri })), model, element);
      });
    } else {
      return (await model.resolveIncomingCalls(item, CancellationToken.None)).map((call) => {
        return new Call(call.from, call.fromRanges.map((range) => ({ range, uri: call.from.uri })), model, element);
      });
    }
  }
};
var $ojc = class {
  compare(element, otherElement) {
    return Call.compare(element, otherElement);
  }
};
var $pjc = class {
  constructor(getDirection) {
    this.getDirection = getDirection;
  }
  getId(element) {
    let res = this.getDirection() + JSON.stringify(element.item.uri) + JSON.stringify(element.item.range);
    if (element.parent) {
      res += this.getId(element.parent);
    }
    return res;
  }
};
var CallRenderingTemplate = class {
  constructor(icon2, label3) {
    this.icon = icon2;
    this.label = label3;
  }
};
var $qjc = class _$qjc {
  constructor() {
    this.templateId = _$qjc.id;
  }
  static {
    this.id = "CallRenderer";
  }
  renderTemplate(container2) {
    container2.classList.add("callhierarchy-element");
    const icon2 = document.createElement("div");
    container2.appendChild(icon2);
    const label3 = new $T2(container2, { supportHighlights: true });
    return new CallRenderingTemplate(icon2, label3);
  }
  renderElement(node, _index, template) {
    const { element, filterData } = node;
    const deprecated = element.item.tags?.includes(
      1
      /* SymbolTag.Deprecated */
    );
    template.icon.className = "";
    template.icon.classList.add("inline", ...ThemeIcon.asClassNameArray(SymbolKinds.toIcon(element.item.kind)));
    template.label.setLabel(element.item.name, element.item.detail, { labelEscapeNewLines: true, matches: $Ul(filterData), strikethrough: deprecated });
  }
  disposeTemplate(template) {
    template.label.dispose();
  }
};
var $rjc = class {
  getHeight(_element) {
    return 22;
  }
  getTemplateId(_element) {
    return $qjc.id;
  }
};
var $sjc = class {
  constructor(getDirection) {
    this.getDirection = getDirection;
  }
  getWidgetAriaLabel() {
    return localize(4601, null);
  }
  getAriaLabel(element) {
    if (this.getDirection() === "outgoingCalls") {
      return localize(4602, null, element.item.name);
    } else {
      return localize(4603, null, element.item.name);
    }
  }
};

// out-build/vs/workbench/contrib/callHierarchy/browser/callHierarchyPeek.js
var $tjc_1;
var State12;
(function(State14) {
  State14["Loading"] = "loading";
  State14["Message"] = "message";
  State14["Data"] = "data";
})(State12 || (State12 = {}));
var LayoutInfo = class {
  static store(info, storageService) {
    storageService.store(
      "callHierarchyPeekLayout",
      JSON.stringify(info),
      0,
      1
      /* StorageTarget.MACHINE */
    );
  }
  static retrieve(storageService) {
    const value = storageService.get("callHierarchyPeekLayout", 0, "{}");
    const defaultInfo = { ratio: 0.7, height: 17 };
    try {
      return { ...defaultInfo, ...JSON.parse(value) };
    } catch {
      return defaultInfo;
    }
  }
  constructor(ratio, height) {
    this.ratio = ratio;
    this.height = height;
  }
};
var CallHierarchyTree = class extends $4eb {
};
var $tjc = class $tjc2 extends $ceb {
  static {
    $tjc_1 = this;
  }
  static {
    this.TitleMenu = new $bJ("callhierarchy/title");
  }
  constructor(editor, db, eb, themeService, fb, gb, hb, ib, jb, kb, lb) {
    super(editor, { showFrame: true, showArrow: true, isResizeable: true, isAccessible: true }, lb);
    this.db = db;
    this.eb = eb;
    this.fb = fb;
    this.gb = gb;
    this.hb = hb;
    this.ib = ib;
    this.jb = jb;
    this.kb = kb;
    this.lb = lb;
    this.i = /* @__PURE__ */ new Map();
    this.cb = new $2c();
    this.create();
    this.fb.addExclusiveWidget(editor, this);
    this.mb(themeService.getColorTheme());
    this.n.add(themeService.onDidColorThemeChange(this.mb, this));
    this.n.add(this.cb);
  }
  dispose() {
    LayoutInfo.store(this.bb, this.ib);
    this.c.dispose();
    this.d.dispose();
    this.m.dispose();
    super.dispose();
  }
  get direction() {
    return this.eb;
  }
  mb(theme) {
    const borderColor = theme.getColor($geb) || $Vn.transparent;
    this.style({
      arrowColor: borderColor,
      frameColor: borderColor,
      headerBackgroundColor: theme.getColor($deb) || $Vn.transparent,
      primaryHeadingColor: theme.getColor($eeb),
      secondaryHeadingColor: theme.getColor($feb)
    });
  }
  T(container2) {
    super.T(container2, true);
    const menu = this.jb.createMenu($tjc_1.TitleMenu, this.kb);
    const updateToolbar = () => {
      const actions = $R$(menu.getActions());
      this.O.clear();
      this.O.push(actions, { label: false, icon: true });
    };
    this.n.add(menu);
    this.n.add(menu.onDidChange(updateToolbar));
    updateToolbar();
  }
  X(parent) {
    this.bb = LayoutInfo.retrieve(this.ib);
    this.r = new $rj(0, 0);
    this.a = parent;
    parent.classList.add("call-hierarchy");
    const message = document.createElement("div");
    message.classList.add("message");
    parent.appendChild(message);
    this.b = message;
    this.b.tabIndex = 0;
    const container2 = document.createElement("div");
    container2.classList.add("results");
    parent.appendChild(container2);
    this.c = new $r2(container2, {
      orientation: 1
      /* Orientation.HORIZONTAL */
    });
    const editorContainer = document.createElement("div");
    editorContainer.classList.add("editor");
    container2.appendChild(editorContainer);
    const editorOptions2 = {
      scrollBeyondLastLine: false,
      scrollbar: {
        verticalScrollbarSize: 14,
        horizontal: "auto",
        useShadows: true,
        verticalHasArrows: false,
        horizontalHasArrows: false,
        alwaysConsumeMouseWheel: false
      },
      overviewRulerLanes: 2,
      fixedOverflowWidgets: true,
      minimap: {
        enabled: false
      }
    };
    this.m = this.lb.createInstance($bdb, editorContainer, editorOptions2, {}, this.editor);
    const treeContainer = document.createElement("div");
    treeContainer.classList.add("tree");
    container2.appendChild(treeContainer);
    const options3 = {
      sorter: new $ojc(),
      accessibilityProvider: new $sjc(() => this.eb),
      identityProvider: new $pjc(() => this.eb),
      expandOnlyOnTwistieClick: true,
      overrideStyles: {
        listBackground: $heb
      }
    };
    this.d = this.lb.createInstance(CallHierarchyTree, "CallHierarchyPeek", treeContainer, new $rjc(), [this.lb.createInstance($qjc)], this.lb.createInstance($njc, () => this.eb), options3);
    this.c.addView({
      onDidChange: Event2.None,
      element: editorContainer,
      minimumSize: 200,
      maximumSize: Number.MAX_VALUE,
      layout: (width2) => {
        if (this.r.height) {
          this.m.layout({ height: this.r.height, width: width2 });
        }
      }
    }, Sizing.Distribute);
    this.c.addView({
      onDidChange: Event2.None,
      element: treeContainer,
      minimumSize: 100,
      maximumSize: Number.MAX_VALUE,
      layout: (width2) => {
        if (this.r.height) {
          this.d.layout(this.r.height, width2);
        }
      }
    }, Sizing.Distribute);
    this.n.add(this.c.onDidSashChange(() => {
      if (this.r.width) {
        this.bb.ratio = this.c.getViewSize(0) / this.r.width;
      }
    }));
    this.n.add(this.d.onDidChangeFocus(this.pb, this));
    this.n.add(this.m.onMouseDown((e) => {
      const { event, target } = e;
      if (event.detail !== 2) {
        return;
      }
      const [focus] = this.d.getFocus();
      if (!focus) {
        return;
      }
      this.dispose();
      this.gb.openEditor({
        resource: focus.item.uri,
        options: { selection: target.range }
      });
    }));
    this.n.add(this.d.onMouseDblClick((e) => {
      if (e.target === TreeMouseEventTarget.Twistie) {
        return;
      }
      if (e.element) {
        this.dispose();
        this.gb.openEditor({
          resource: e.element.item.uri,
          options: { selection: e.element.item.selectionRange, pinned: true }
        });
      }
    }));
    this.n.add(this.d.onDidChangeSelection((e) => {
      const [element] = e.elements;
      if (element && $4j(e.browserEvent)) {
        this.dispose();
        this.gb.openEditor({
          resource: element.item.uri,
          options: { selection: element.item.selectionRange, pinned: true }
        });
      }
    }));
  }
  async pb() {
    const [element] = this.d.getFocus();
    if (!element) {
      return;
    }
    this.cb.clear();
    const options3 = {
      description: "call-hierarchy-decoration",
      stickiness: 1,
      className: "call-decoration",
      overviewRuler: {
        color: $hs($qeb),
        position: OverviewRulerLane.Center
      }
    };
    let previewUri;
    if (this.eb === "outgoingCalls") {
      previewUri = element.parent ? element.parent.item.uri : element.model.root.uri;
    } else {
      previewUri = element.item.uri;
    }
    const value = await this.hb.createModelReference(previewUri);
    this.m.setModel(value.object.textEditorModel);
    const decorations = [];
    let fullRange;
    let locations = element.locations;
    if (!locations) {
      locations = [{ uri: element.item.uri, range: element.item.selectionRange }];
    }
    for (const loc of locations) {
      if (loc.uri.toString() === previewUri.toString()) {
        decorations.push({ range: loc.range, options: options3 });
        fullRange = !fullRange ? loc.range : $9C.plusRange(loc.range, fullRange);
      }
    }
    if (fullRange) {
      this.m.revealRangeInCenter(
        fullRange,
        1
        /* ScrollType.Immediate */
      );
      const decorationsCollection = this.m.createDecorationsCollection(decorations);
      this.cb.add($1c(() => decorationsCollection.clear()));
    }
    this.cb.add(value);
    const title = this.eb === "outgoingCalls" ? localize(4596, null, element.model.root.name) : localize(4597, null, element.model.root.name);
    this.setTitle(title);
  }
  showLoading() {
    this.a.dataset["state"] = "loading";
    this.setTitle(localize(4598, null));
    this.qb();
  }
  showMessage(message) {
    this.a.dataset["state"] = "message";
    this.setTitle("");
    this.setMetaTitle("");
    this.b.innerText = message;
    this.qb();
    this.b.focus();
  }
  async showModel(model) {
    this.qb();
    const viewState = this.i.get(this.eb);
    await this.d.setInput(model, viewState);
    const root = this.d.getNode(model).children[0];
    await this.d.expand(root.element);
    if (root.children.length === 0) {
      this.showMessage(this.eb === "outgoingCalls" ? localize(4599, null, model.root.name) : localize(4600, null, model.root.name));
    } else {
      this.a.dataset["state"] = "data";
      if (!viewState || this.d.getFocus().length === 0) {
        this.d.setFocus([root.children[0].element]);
      }
      this.d.domFocus();
      this.pb();
    }
  }
  getModel() {
    return this.d.getInput();
  }
  getFocused() {
    return this.d.getFocus()[0];
  }
  async updateDirection(newDirection) {
    const model = this.d.getInput();
    if (model && newDirection !== this.eb) {
      this.i.set(this.eb, this.d.getViewState());
      this.eb = newDirection;
      await this.showModel(model);
    }
  }
  qb() {
    if (!this.w) {
      this.editor.revealLineInCenterIfOutsideViewport(
        this.db.lineNumber,
        0
        /* ScrollType.Smooth */
      );
      super.show($9C.fromPositions(this.db), this.bb.height);
    }
  }
  C(width2) {
    if (this.r) {
      this.ab(this.r.height, width2);
    }
  }
  ab(height, width2) {
    if (this.r.height !== height || this.r.width !== width2) {
      super.ab(height, width2);
      this.r = new $rj(width2, height);
      this.bb.height = this.l ? this.l.heightInLines : this.bb.height;
      this.c.layout(width2);
      this.c.resizeView(0, width2 * this.bb.ratio);
    }
  }
};
$tjc = $tjc_1 = __decorate([
  __param(3, $gs),
  __param(4, $aeb),
  __param(5, $mJ),
  __param(6, $oG),
  __param(7, $jv),
  __param(8, $cJ),
  __param(9, $on),
  __param(10, $Pk)
], $tjc);

// out-build/vs/workbench/contrib/callHierarchy/browser/callHierarchy.contribution.js
var CallHierarchyController_1;
var _ctxHasCallHierarchyProvider = new $nn("editorHasCallHierarchyProvider", false, localize(4584, null));
var _ctxCallHierarchyVisible = new $nn("callHierarchyVisible", false, localize(4585, null));
var _ctxCallHierarchyDirection = new $nn("callHierarchyDirection", void 0, { type: "string", description: localize(4586, null) });
function sanitizedDirection(candidate) {
  return candidate === "outgoingCalls" || candidate === "incomingCalls" ? candidate : "incomingCalls";
}
var CallHierarchyController = class CallHierarchyController2 {
  static {
    CallHierarchyController_1 = this;
  }
  static {
    this.Id = "callHierarchy";
  }
  static get(editor) {
    return editor.getContribution(CallHierarchyController_1.Id);
  }
  static {
    this.a = "callHierarchy/defaultDirection";
  }
  constructor(h3, i2, j, k, l) {
    this.h = h3;
    this.i = i2;
    this.j = j;
    this.k = k;
    this.l = l;
    this.e = new $2c();
    this.f = new $2c();
    this.c = _ctxCallHierarchyVisible.bindTo(this.i);
    this.b = _ctxHasCallHierarchyProvider.bindTo(this.i);
    this.d = _ctxCallHierarchyDirection.bindTo(this.i);
    this.e.add(Event2.any(h3.onDidChangeModel, h3.onDidChangeModelLanguage, $cN.onDidChange)(() => {
      this.b.set(h3.hasModel() && $cN.has(h3.getModel()));
    }));
    this.e.add(this.f);
  }
  dispose() {
    this.b.reset();
    this.c.reset();
    this.e.dispose();
  }
  async startCallHierarchyFromEditor() {
    this.f.clear();
    if (!this.h.hasModel()) {
      return;
    }
    const document2 = this.h.getModel();
    const position = this.h.getPosition();
    if (!$cN.has(document2)) {
      return;
    }
    const cts = new $ad();
    const model = $dN.create(document2, position, cts.token);
    const direction = sanitizedDirection(this.j.get(
      CallHierarchyController_1.a,
      0,
      "incomingCalls"
      /* CallHierarchyDirection.CallsTo */
    ));
    this.m(position, direction, model, cts);
  }
  async startCallHierarchyFromCallHierarchy() {
    if (!this.g) {
      return;
    }
    const model = this.g.getModel();
    const call = this.g.getFocused();
    if (!call || !model) {
      return;
    }
    const newEditor = await this.k.openCodeEditor({ resource: call.item.uri }, this.h);
    if (!newEditor) {
      return;
    }
    const newModel = model.fork(call.item);
    this.f.clear();
    CallHierarchyController_1.get(newEditor)?.m($9C.lift(newModel.root.selectionRange).getStartPosition(), this.g.direction, Promise.resolve(newModel), new $ad());
  }
  m(position, direction, model, cts) {
    this.c.set(true);
    this.d.set(direction);
    Event2.any(this.h.onDidChangeModel, this.h.onDidChangeModelLanguage)(this.endCallHierarchy, this, this.f);
    this.g = this.l.createInstance($tjc, this.h, position, direction);
    this.g.showLoading();
    this.f.add(this.g.onDidClose(() => {
      this.endCallHierarchy();
      this.j.store(
        CallHierarchyController_1.a,
        this.g.direction,
        0,
        0
        /* StorageTarget.USER */
      );
    }));
    this.f.add({ dispose() {
      cts.dispose(true);
    } });
    this.f.add(this.g);
    model.then((model2) => {
      if (cts.token.isCancellationRequested) {
        return;
      }
      if (model2) {
        this.f.add(model2);
        this.g.showModel(model2);
      } else {
        this.g.showMessage(localize(4587, null));
      }
    }).catch((err) => {
      if ($kb(err)) {
        this.endCallHierarchy();
        return;
      }
      this.g.showMessage(localize(4588, null));
    });
  }
  showOutgoingCalls() {
    this.g?.updateDirection(
      "outgoingCalls"
      /* CallHierarchyDirection.CallsFrom */
    );
    this.d.set(
      "outgoingCalls"
      /* CallHierarchyDirection.CallsFrom */
    );
  }
  showIncomingCalls() {
    this.g?.updateDirection(
      "incomingCalls"
      /* CallHierarchyDirection.CallsTo */
    );
    this.d.set(
      "incomingCalls"
      /* CallHierarchyDirection.CallsTo */
    );
  }
  endCallHierarchy() {
    this.f.clear();
    this.c.set(false);
    this.h.focus();
  }
};
CallHierarchyController = CallHierarchyController_1 = __decorate([
  __param(1, $on),
  __param(2, $jv),
  __param(3, $U5),
  __param(4, $Pk)
], CallHierarchyController);
$85(
  CallHierarchyController.Id,
  CallHierarchyController,
  0
  /* EditorContributionInstantiation.Eager */
);
$hJ(class PeekCallHierarchyAction extends $25 {
  constructor() {
    super({
      id: "editor.showCallHierarchy",
      title: localize2(4592, "Peek Call Hierarchy"),
      menu: {
        id: $bJ.EditorContextPeek,
        group: "navigation",
        order: 1e3,
        when: $7m.and(_ctxHasCallHierarchyProvider, PeekContext.notInPeekEditor, EditorContextKeys.isInEmbeddedEditor.toNegated())
      },
      keybinding: {
        when: EditorContextKeys.editorTextFocus,
        weight: 200,
        primary: 1024 + 512 + 38
        /* KeyCode.KeyH */
      },
      precondition: $7m.and(_ctxHasCallHierarchyProvider, PeekContext.notInPeekEditor),
      f1: true
    });
  }
  async runEditorCommand(_accessor, editor) {
    return CallHierarchyController.get(editor)?.startCallHierarchyFromEditor();
  }
});
$hJ(class extends $25 {
  constructor() {
    super({
      id: "editor.showIncomingCalls",
      title: localize2(4593, "Show Incoming Calls"),
      icon: $9r("callhierarchy-incoming", $6l.callIncoming, localize(4589, null)),
      precondition: $7m.and(_ctxCallHierarchyVisible, _ctxCallHierarchyDirection.isEqualTo(
        "outgoingCalls"
        /* CallHierarchyDirection.CallsFrom */
      )),
      keybinding: {
        weight: 200,
        primary: 1024 + 512 + 38
      },
      menu: {
        id: $tjc.TitleMenu,
        when: _ctxCallHierarchyDirection.isEqualTo(
          "outgoingCalls"
          /* CallHierarchyDirection.CallsFrom */
        ),
        order: 1
      }
    });
  }
  runEditorCommand(_accessor, editor) {
    return CallHierarchyController.get(editor)?.showIncomingCalls();
  }
});
$hJ(class extends $25 {
  constructor() {
    super({
      id: "editor.showOutgoingCalls",
      title: localize2(4594, "Show Outgoing Calls"),
      icon: $9r("callhierarchy-outgoing", $6l.callOutgoing, localize(4590, null)),
      precondition: $7m.and(_ctxCallHierarchyVisible, _ctxCallHierarchyDirection.isEqualTo(
        "incomingCalls"
        /* CallHierarchyDirection.CallsTo */
      )),
      keybinding: {
        weight: 200,
        primary: 1024 + 512 + 38
      },
      menu: {
        id: $tjc.TitleMenu,
        when: _ctxCallHierarchyDirection.isEqualTo(
          "incomingCalls"
          /* CallHierarchyDirection.CallsTo */
        ),
        order: 1
      }
    });
  }
  runEditorCommand(_accessor, editor) {
    return CallHierarchyController.get(editor)?.showOutgoingCalls();
  }
});
$hJ(class extends $25 {
  constructor() {
    super({
      id: "editor.refocusCallHierarchy",
      title: localize2(4595, "Refocus Call Hierarchy"),
      precondition: _ctxCallHierarchyVisible,
      keybinding: {
        weight: 200,
        primary: 1024 + 3
        /* KeyCode.Enter */
      }
    });
  }
  async runEditorCommand(_accessor, editor) {
    return CallHierarchyController.get(editor)?.startCallHierarchyFromCallHierarchy();
  }
});
$hJ(class extends $25 {
  constructor() {
    super({
      id: "editor.closeCallHierarchy",
      title: localize(4591, null),
      icon: $6l.close,
      precondition: _ctxCallHierarchyVisible,
      keybinding: {
        weight: 200 + 10,
        primary: 9,
        when: $7m.not("config.editor.stablePeek")
      },
      menu: {
        id: $tjc.TitleMenu,
        order: 1e3
      }
    });
  }
  runEditorCommand(_accessor, editor) {
    return CallHierarchyController.get(editor)?.endCallHierarchy();
  }
});

// out-build/vs/workbench/contrib/typeHierarchy/browser/typeHierarchyTree.js
var Type3 = class {
  constructor(item, model, parent) {
    this.item = item;
    this.model = model;
    this.parent = parent;
  }
  static compare(a, b) {
    let res = $Tf(a.item.uri.toString(), b.item.uri.toString());
    if (res === 0) {
      res = $9C.compareRangesUsingStarts(a.item.range, b.item.range);
    }
    return res;
  }
};
var $vjc = class {
  constructor(getDirection) {
    this.getDirection = getDirection;
  }
  hasChildren() {
    return true;
  }
  async getChildren(element) {
    if (element instanceof $uS) {
      return element.roots.map((root) => new Type3(root, element, void 0));
    }
    const { model, item } = element;
    if (this.getDirection() === "supertypes") {
      return (await model.provideSupertypes(item, CancellationToken.None)).map((item2) => {
        return new Type3(item2, model, element);
      });
    } else {
      return (await model.provideSubtypes(item, CancellationToken.None)).map((item2) => {
        return new Type3(item2, model, element);
      });
    }
  }
};
var $wjc = class {
  compare(element, otherElement) {
    return Type3.compare(element, otherElement);
  }
};
var $xjc = class {
  constructor(getDirection) {
    this.getDirection = getDirection;
  }
  getId(element) {
    let res = this.getDirection() + JSON.stringify(element.item.uri) + JSON.stringify(element.item.range);
    if (element.parent) {
      res += this.getId(element.parent);
    }
    return res;
  }
};
var TypeRenderingTemplate = class {
  constructor(icon2, label3) {
    this.icon = icon2;
    this.label = label3;
  }
};
var $yjc = class _$yjc {
  constructor() {
    this.templateId = _$yjc.id;
  }
  static {
    this.id = "TypeRenderer";
  }
  renderTemplate(container2) {
    container2.classList.add("typehierarchy-element");
    const icon2 = document.createElement("div");
    container2.appendChild(icon2);
    const label3 = new $T2(container2, { supportHighlights: true });
    return new TypeRenderingTemplate(icon2, label3);
  }
  renderElement(node, _index, template) {
    const { element, filterData } = node;
    const deprecated = element.item.tags?.includes(
      1
      /* SymbolTag.Deprecated */
    );
    template.icon.classList.add("inline", ...ThemeIcon.asClassNameArray(SymbolKinds.toIcon(element.item.kind)));
    template.label.setLabel(element.item.name, element.item.detail, { labelEscapeNewLines: true, matches: $Ul(filterData), strikethrough: deprecated });
  }
  disposeTemplate(template) {
    template.label.dispose();
  }
};
var $zjc = class {
  getHeight(_element) {
    return 22;
  }
  getTemplateId(_element) {
    return $yjc.id;
  }
};
var $Ajc = class {
  constructor(getDirection) {
    this.getDirection = getDirection;
  }
  getWidgetAriaLabel() {
    return localize(11456, null);
  }
  getAriaLabel(element) {
    if (this.getDirection() === "supertypes") {
      return localize(11457, null, element.item.name);
    } else {
      return localize(11458, null, element.item.name);
    }
  }
};

// out-build/vs/workbench/contrib/typeHierarchy/browser/typeHierarchyPeek.js
var $Bjc_1;
var State13;
(function(State14) {
  State14["Loading"] = "loading";
  State14["Message"] = "message";
  State14["Data"] = "data";
})(State13 || (State13 = {}));
var LayoutInfo2 = class {
  static store(info, storageService) {
    storageService.store(
      "typeHierarchyPeekLayout",
      JSON.stringify(info),
      0,
      1
      /* StorageTarget.MACHINE */
    );
  }
  static retrieve(storageService) {
    const value = storageService.get("typeHierarchyPeekLayout", 0, "{}");
    const defaultInfo = { ratio: 0.7, height: 17 };
    try {
      return { ...defaultInfo, ...JSON.parse(value) };
    } catch {
      return defaultInfo;
    }
  }
  constructor(ratio, height) {
    this.ratio = ratio;
    this.height = height;
  }
};
var TypeHierarchyTree = class extends $4eb {
};
var $Bjc = class $Bjc2 extends $ceb {
  static {
    $Bjc_1 = this;
  }
  static {
    this.TitleMenu = new $bJ("typehierarchy/title");
  }
  constructor(editor, db, eb, themeService, fb, gb, hb, ib, jb, kb, lb) {
    super(editor, { showFrame: true, showArrow: true, isResizeable: true, isAccessible: true }, lb);
    this.db = db;
    this.eb = eb;
    this.fb = fb;
    this.gb = gb;
    this.hb = hb;
    this.ib = ib;
    this.jb = jb;
    this.kb = kb;
    this.lb = lb;
    this.i = /* @__PURE__ */ new Map();
    this.cb = new $2c();
    this.create();
    this.fb.addExclusiveWidget(editor, this);
    this.mb(themeService.getColorTheme());
    this.n.add(themeService.onDidColorThemeChange(this.mb, this));
    this.n.add(this.cb);
  }
  dispose() {
    LayoutInfo2.store(this.bb, this.ib);
    this.c.dispose();
    this.d.dispose();
    this.m.dispose();
    super.dispose();
  }
  get direction() {
    return this.eb;
  }
  mb(theme) {
    const borderColor = theme.getColor($geb) || $Vn.transparent;
    this.style({
      arrowColor: borderColor,
      frameColor: borderColor,
      headerBackgroundColor: theme.getColor($deb) || $Vn.transparent,
      primaryHeadingColor: theme.getColor($eeb),
      secondaryHeadingColor: theme.getColor($feb)
    });
  }
  T(container2) {
    super.T(container2, true);
    const menu = this.jb.createMenu($Bjc_1.TitleMenu, this.kb);
    const updateToolbar = () => {
      const actions = $R$(menu.getActions());
      this.O.clear();
      this.O.push(actions, { label: false, icon: true });
    };
    this.n.add(menu);
    this.n.add(menu.onDidChange(updateToolbar));
    updateToolbar();
  }
  X(parent) {
    this.bb = LayoutInfo2.retrieve(this.ib);
    this.r = new $rj(0, 0);
    this.a = parent;
    parent.classList.add("type-hierarchy");
    const message = document.createElement("div");
    message.classList.add("message");
    parent.appendChild(message);
    this.b = message;
    this.b.tabIndex = 0;
    const container2 = document.createElement("div");
    container2.classList.add("results");
    parent.appendChild(container2);
    this.c = new $r2(container2, {
      orientation: 1
      /* Orientation.HORIZONTAL */
    });
    const editorContainer = document.createElement("div");
    editorContainer.classList.add("editor");
    container2.appendChild(editorContainer);
    const editorOptions2 = {
      scrollBeyondLastLine: false,
      scrollbar: {
        verticalScrollbarSize: 14,
        horizontal: "auto",
        useShadows: true,
        verticalHasArrows: false,
        horizontalHasArrows: false,
        alwaysConsumeMouseWheel: false
      },
      overviewRulerLanes: 2,
      fixedOverflowWidgets: true,
      minimap: {
        enabled: false
      }
    };
    this.m = this.lb.createInstance($bdb, editorContainer, editorOptions2, {}, this.editor);
    const treeContainer = document.createElement("div");
    treeContainer.classList.add("tree");
    container2.appendChild(treeContainer);
    const options3 = {
      sorter: new $wjc(),
      accessibilityProvider: new $Ajc(() => this.eb),
      identityProvider: new $xjc(() => this.eb),
      expandOnlyOnTwistieClick: true,
      overrideStyles: {
        listBackground: $heb
      }
    };
    this.d = this.lb.createInstance(TypeHierarchyTree, "TypeHierarchyPeek", treeContainer, new $zjc(), [this.lb.createInstance($yjc)], this.lb.createInstance($vjc, () => this.eb), options3);
    this.c.addView({
      onDidChange: Event2.None,
      element: editorContainer,
      minimumSize: 200,
      maximumSize: Number.MAX_VALUE,
      layout: (width2) => {
        if (this.r.height) {
          this.m.layout({ height: this.r.height, width: width2 });
        }
      }
    }, Sizing.Distribute);
    this.c.addView({
      onDidChange: Event2.None,
      element: treeContainer,
      minimumSize: 100,
      maximumSize: Number.MAX_VALUE,
      layout: (width2) => {
        if (this.r.height) {
          this.d.layout(this.r.height, width2);
        }
      }
    }, Sizing.Distribute);
    this.n.add(this.c.onDidSashChange(() => {
      if (this.r.width) {
        this.bb.ratio = this.c.getViewSize(0) / this.r.width;
      }
    }));
    this.n.add(this.d.onDidChangeFocus(this.pb, this));
    this.n.add(this.m.onMouseDown((e) => {
      const { event, target } = e;
      if (event.detail !== 2) {
        return;
      }
      const [focus] = this.d.getFocus();
      if (!focus) {
        return;
      }
      this.dispose();
      this.gb.openEditor({
        resource: focus.item.uri,
        options: { selection: target.range }
      });
    }));
    this.n.add(this.d.onMouseDblClick((e) => {
      if (e.target === TreeMouseEventTarget.Twistie) {
        return;
      }
      if (e.element) {
        this.dispose();
        this.gb.openEditor({
          resource: e.element.item.uri,
          options: { selection: e.element.item.selectionRange, pinned: true }
        });
      }
    }));
    this.n.add(this.d.onDidChangeSelection((e) => {
      const [element] = e.elements;
      if (element && $4j(e.browserEvent)) {
        this.dispose();
        this.gb.openEditor({
          resource: element.item.uri,
          options: { selection: element.item.selectionRange, pinned: true }
        });
      }
    }));
  }
  async pb() {
    const [element] = this.d.getFocus();
    if (!element) {
      return;
    }
    this.cb.clear();
    const options3 = {
      description: "type-hierarchy-decoration",
      stickiness: 1,
      className: "type-decoration",
      overviewRuler: {
        color: $hs($qeb),
        position: OverviewRulerLane.Center
      }
    };
    let previewUri;
    if (this.eb === "supertypes") {
      previewUri = element.parent ? element.parent.item.uri : element.model.root.uri;
    } else {
      previewUri = element.item.uri;
    }
    const value = await this.hb.createModelReference(previewUri);
    this.m.setModel(value.object.textEditorModel);
    const decorations = [];
    let fullRange;
    const loc = { uri: element.item.uri, range: element.item.selectionRange };
    if (loc.uri.toString() === previewUri.toString()) {
      decorations.push({ range: loc.range, options: options3 });
      fullRange = !fullRange ? loc.range : $9C.plusRange(loc.range, fullRange);
    }
    if (fullRange) {
      this.m.revealRangeInCenter(
        fullRange,
        1
        /* ScrollType.Immediate */
      );
      const decorationsCollection = this.m.createDecorationsCollection(decorations);
      this.cb.add($1c(() => decorationsCollection.clear()));
    }
    this.cb.add(value);
    const title = this.eb === "supertypes" ? localize(11451, null, element.model.root.name) : localize(11452, null, element.model.root.name);
    this.setTitle(title);
  }
  showLoading() {
    this.a.dataset["state"] = "loading";
    this.setTitle(localize(11453, null));
    this.qb();
  }
  showMessage(message) {
    this.a.dataset["state"] = "message";
    this.setTitle("");
    this.setMetaTitle("");
    this.b.innerText = message;
    this.qb();
    this.b.focus();
  }
  async showModel(model) {
    this.qb();
    const viewState = this.i.get(this.eb);
    await this.d.setInput(model, viewState);
    const root = this.d.getNode(model).children[0];
    await this.d.expand(root.element);
    if (root.children.length === 0) {
      this.showMessage(this.eb === "supertypes" ? localize(11454, null, model.root.name) : localize(11455, null, model.root.name));
    } else {
      this.a.dataset["state"] = "data";
      if (!viewState || this.d.getFocus().length === 0) {
        this.d.setFocus([root.children[0].element]);
      }
      this.d.domFocus();
      this.pb();
    }
  }
  getModel() {
    return this.d.getInput();
  }
  getFocused() {
    return this.d.getFocus()[0];
  }
  async updateDirection(newDirection) {
    const model = this.d.getInput();
    if (model && newDirection !== this.eb) {
      this.i.set(this.eb, this.d.getViewState());
      this.eb = newDirection;
      await this.showModel(model);
    }
  }
  qb() {
    if (!this.w) {
      this.editor.revealLineInCenterIfOutsideViewport(
        this.db.lineNumber,
        0
        /* ScrollType.Smooth */
      );
      super.show($9C.fromPositions(this.db), this.bb.height);
    }
  }
  C(width2) {
    if (this.r) {
      this.ab(this.r.height, width2);
    }
  }
  ab(height, width2) {
    if (this.r.height !== height || this.r.width !== width2) {
      super.ab(height, width2);
      this.r = new $rj(width2, height);
      this.bb.height = this.l ? this.l.heightInLines : this.bb.height;
      this.c.layout(width2);
      this.c.resizeView(0, width2 * this.bb.ratio);
    }
  }
};
$Bjc = $Bjc_1 = __decorate([
  __param(3, $gs),
  __param(4, $aeb),
  __param(5, $mJ),
  __param(6, $oG),
  __param(7, $jv),
  __param(8, $cJ),
  __param(9, $on),
  __param(10, $Pk)
], $Bjc);

// out-build/vs/workbench/contrib/typeHierarchy/browser/typeHierarchy.contribution.js
var TypeHierarchyController_1;
var _ctxHasTypeHierarchyProvider = new $nn("editorHasTypeHierarchyProvider", false, localize(11441, null));
var _ctxTypeHierarchyVisible = new $nn("typeHierarchyVisible", false, localize(11442, null));
var _ctxTypeHierarchyDirection = new $nn("typeHierarchyDirection", void 0, { type: "string", description: localize(11443, null) });
function sanitizedDirection2(candidate) {
  return candidate === "subtypes" || candidate === "supertypes" ? candidate : "subtypes";
}
var TypeHierarchyController = class TypeHierarchyController2 {
  static {
    TypeHierarchyController_1 = this;
  }
  static {
    this.Id = "typeHierarchy";
  }
  static get(editor) {
    return editor.getContribution(TypeHierarchyController_1.Id);
  }
  static {
    this.a = "typeHierarchy/defaultDirection";
  }
  constructor(_editor, h3, i2, j, k) {
    this._editor = _editor;
    this.h = h3;
    this.i = i2;
    this.j = j;
    this.k = k;
    this.e = new $2c();
    this.f = new $2c();
    this.b = _ctxHasTypeHierarchyProvider.bindTo(this.h);
    this.c = _ctxTypeHierarchyVisible.bindTo(this.h);
    this.d = _ctxTypeHierarchyDirection.bindTo(this.h);
    this.e.add(Event2.any(_editor.onDidChangeModel, _editor.onDidChangeModelLanguage, $tS.onDidChange)(() => {
      this.b.set(_editor.hasModel() && $tS.has(_editor.getModel()));
    }));
    this.e.add(this.f);
  }
  dispose() {
    this.e.dispose();
  }
  // Peek
  async startTypeHierarchyFromEditor() {
    this.f.clear();
    if (!this._editor.hasModel()) {
      return;
    }
    const document2 = this._editor.getModel();
    const position = this._editor.getPosition();
    if (!$tS.has(document2)) {
      return;
    }
    const cts = new $ad();
    const model = $uS.create(document2, position, cts.token);
    const direction = sanitizedDirection2(this.i.get(
      TypeHierarchyController_1.a,
      0,
      "subtypes"
      /* TypeHierarchyDirection.Subtypes */
    ));
    this.l(position, direction, model, cts);
  }
  l(position, direction, model, cts) {
    this.c.set(true);
    this.d.set(direction);
    Event2.any(this._editor.onDidChangeModel, this._editor.onDidChangeModelLanguage)(this.endTypeHierarchy, this, this.f);
    this.g = this.k.createInstance($Bjc, this._editor, position, direction);
    this.g.showLoading();
    this.f.add(this.g.onDidClose(() => {
      this.endTypeHierarchy();
      this.i.store(
        TypeHierarchyController_1.a,
        this.g.direction,
        0,
        0
        /* StorageTarget.USER */
      );
    }));
    this.f.add({ dispose() {
      cts.dispose(true);
    } });
    this.f.add(this.g);
    model.then((model2) => {
      if (cts.token.isCancellationRequested) {
        return;
      }
      if (model2) {
        this.f.add(model2);
        this.g.showModel(model2);
      } else {
        this.g.showMessage(localize(11444, null));
      }
    }).catch((err) => {
      if ($kb(err)) {
        this.endTypeHierarchy();
        return;
      }
      this.g.showMessage(localize(11445, null));
    });
  }
  async startTypeHierarchyFromTypeHierarchy() {
    if (!this.g) {
      return;
    }
    const model = this.g.getModel();
    const typeItem = this.g.getFocused();
    if (!typeItem || !model) {
      return;
    }
    const newEditor = await this.j.openCodeEditor({ resource: typeItem.item.uri }, this._editor);
    if (!newEditor) {
      return;
    }
    const newModel = model.fork(typeItem.item);
    this.f.clear();
    TypeHierarchyController_1.get(newEditor)?.l($9C.lift(newModel.root.selectionRange).getStartPosition(), this.g.direction, Promise.resolve(newModel), new $ad());
  }
  showSupertypes() {
    this.g?.updateDirection(
      "supertypes"
      /* TypeHierarchyDirection.Supertypes */
    );
    this.d.set(
      "supertypes"
      /* TypeHierarchyDirection.Supertypes */
    );
  }
  showSubtypes() {
    this.g?.updateDirection(
      "subtypes"
      /* TypeHierarchyDirection.Subtypes */
    );
    this.d.set(
      "subtypes"
      /* TypeHierarchyDirection.Subtypes */
    );
  }
  endTypeHierarchy() {
    this.f.clear();
    this.c.set(false);
    this._editor.focus();
  }
};
TypeHierarchyController = TypeHierarchyController_1 = __decorate([
  __param(1, $on),
  __param(2, $jv),
  __param(3, $U5),
  __param(4, $Pk)
], TypeHierarchyController);
$85(
  TypeHierarchyController.Id,
  TypeHierarchyController,
  0
  /* EditorContributionInstantiation.Eager */
);
$hJ(class PeekTypeHierarchyAction extends $25 {
  constructor() {
    super({
      id: "editor.showTypeHierarchy",
      title: localize2(11447, "Peek Type Hierarchy"),
      menu: {
        id: $bJ.EditorContextPeek,
        group: "navigation",
        order: 1e3,
        when: $7m.and(_ctxHasTypeHierarchyProvider, PeekContext.notInPeekEditor)
      },
      precondition: $7m.and(_ctxHasTypeHierarchyProvider, PeekContext.notInPeekEditor),
      f1: true
    });
  }
  async runEditorCommand(_accessor, editor) {
    return TypeHierarchyController.get(editor)?.startTypeHierarchyFromEditor();
  }
});
$hJ(class extends $25 {
  constructor() {
    super({
      id: "editor.showSupertypes",
      title: localize2(11448, "Show Supertypes"),
      icon: $6l.typeHierarchySuper,
      precondition: $7m.and(_ctxTypeHierarchyVisible, _ctxTypeHierarchyDirection.isEqualTo(
        "subtypes"
        /* TypeHierarchyDirection.Subtypes */
      )),
      keybinding: {
        weight: 200,
        primary: 1024 + 512 + 38
      },
      menu: {
        id: $Bjc.TitleMenu,
        when: _ctxTypeHierarchyDirection.isEqualTo(
          "subtypes"
          /* TypeHierarchyDirection.Subtypes */
        ),
        order: 1
      }
    });
  }
  runEditorCommand(_accessor, editor) {
    return TypeHierarchyController.get(editor)?.showSupertypes();
  }
});
$hJ(class extends $25 {
  constructor() {
    super({
      id: "editor.showSubtypes",
      title: localize2(11449, "Show Subtypes"),
      icon: $6l.typeHierarchySub,
      precondition: $7m.and(_ctxTypeHierarchyVisible, _ctxTypeHierarchyDirection.isEqualTo(
        "supertypes"
        /* TypeHierarchyDirection.Supertypes */
      )),
      keybinding: {
        weight: 200,
        primary: 1024 + 512 + 38
      },
      menu: {
        id: $Bjc.TitleMenu,
        when: _ctxTypeHierarchyDirection.isEqualTo(
          "supertypes"
          /* TypeHierarchyDirection.Supertypes */
        ),
        order: 1
      }
    });
  }
  runEditorCommand(_accessor, editor) {
    return TypeHierarchyController.get(editor)?.showSubtypes();
  }
});
$hJ(class extends $25 {
  constructor() {
    super({
      id: "editor.refocusTypeHierarchy",
      title: localize2(11450, "Refocus Type Hierarchy"),
      precondition: _ctxTypeHierarchyVisible,
      keybinding: {
        weight: 200,
        primary: 1024 + 3
        /* KeyCode.Enter */
      }
    });
  }
  async runEditorCommand(_accessor, editor) {
    return TypeHierarchyController.get(editor)?.startTypeHierarchyFromTypeHierarchy();
  }
});
$hJ(class extends $25 {
  constructor() {
    super({
      id: "editor.closeTypeHierarchy",
      title: localize(11446, null),
      icon: $6l.close,
      precondition: _ctxTypeHierarchyVisible,
      keybinding: {
        weight: 200 + 10,
        primary: 9,
        when: $7m.not("config.editor.stablePeek")
      },
      menu: {
        id: $Bjc.TitleMenu,
        order: 1e3
      }
    });
  }
  runEditorCommand(_accessor, editor) {
    return TypeHierarchyController.get(editor)?.endTypeHierarchy();
  }
});

// out-build/vs/workbench/contrib/codeEditor/browser/outline/documentSymbolsTree.js
var $Jjc_1;
var $Cjc = class {
  getKeyboardNavigationLabel(element) {
    if (element instanceof $nhb) {
      return element.label;
    } else {
      return element.symbol.name;
    }
  }
};
var $Djc = class {
  constructor(c) {
    this.c = c;
  }
  getWidgetAriaLabel() {
    return this.c;
  }
  getAriaLabel(element) {
    if (element instanceof $nhb) {
      return element.label;
    } else {
      return $UE(element.symbol.name, element.symbol.kind);
    }
  }
};
var $Ejc = class {
  getId(element) {
    return element.id;
  }
};
var $Fjc = class $Fjc2 {
  constructor(c) {
    this.c = c;
  }
  getDragURI(element) {
    const resource = $ohb.get(element)?.uri;
    if (!resource) {
      return null;
    }
    if (element instanceof $mhb) {
      const symbolUri = symbolRangeUri(resource, element.symbol);
      return symbolUri.fsPath + (symbolUri.fragment ? "#" + symbolUri.fragment : "");
    } else {
      return resource.fsPath;
    }
  }
  getDragLabel(elements, originalEvent) {
    if (elements.length !== 1) {
      return void 0;
    }
    const element = elements[0];
    return element instanceof $mhb ? element.symbol.name : element.label;
  }
  onDragStart(data, originalEvent) {
    const elements = data.elements;
    const item = elements[0];
    if (!item || !originalEvent.dataTransfer) {
      return;
    }
    const resource = $ohb.get(item)?.uri;
    if (!resource) {
      return;
    }
    const outlineElements = item instanceof $mhb ? [item] : Array.from(item.children.values());
    $D_(outlineElements.map((oe) => ({
      name: oe.symbol.name,
      fsPath: resource.fsPath,
      range: oe.symbol.range,
      kind: oe.symbol.kind
    })), originalEvent);
    this.c.invokeFunction((accessor) => $Eob(accessor, outlineElements.map((oe) => ({
      resource,
      selection: oe.symbol.range
    })), originalEvent));
  }
  onDragOver() {
    return false;
  }
  drop() {
  }
  dispose() {
  }
};
$Fjc = __decorate([
  __param(0, $Pk)
], $Fjc);
function symbolRangeUri(resource, symbol) {
  return $P4(resource, symbol.range);
}
var DocumentSymbolGroupTemplate = class {
  static {
    this.id = "DocumentSymbolGroupTemplate";
  }
  constructor(labelContainer, label3) {
    this.labelContainer = labelContainer;
    this.label = label3;
  }
  dispose() {
    this.label.dispose();
  }
};
var DocumentSymbolTemplate = class {
  static {
    this.id = "DocumentSymbolTemplate";
  }
  constructor(container2, iconLabel, iconClass, decoration3) {
    this.container = container2;
    this.iconLabel = iconLabel;
    this.iconClass = iconClass;
    this.decoration = decoration3;
  }
};
var $Gjc = class {
  getHeight(_element) {
    return 22;
  }
  getTemplateId(element) {
    return element instanceof $nhb ? DocumentSymbolGroupTemplate.id : DocumentSymbolTemplate.id;
  }
};
var $Hjc = class {
  constructor() {
    this.templateId = DocumentSymbolGroupTemplate.id;
  }
  renderTemplate(container2) {
    const labelContainer = $(".outline-element-label");
    container2.classList.add("outline-element");
    $bk(container2, labelContainer);
    return new DocumentSymbolGroupTemplate(labelContainer, new $S2(labelContainer));
  }
  renderElement(node, _index, template) {
    template.label.set(node.element.label, $Ul(node.filterData));
  }
  disposeTemplate(_template) {
    _template.dispose();
  }
};
var $Ijc = class $Ijc2 {
  constructor(c, target, d, e) {
    this.c = c;
    this.d = d;
    this.e = e;
    this.templateId = DocumentSymbolTemplate.id;
  }
  renderTemplate(container2) {
    container2.classList.add("outline-element");
    const iconLabel = new $T2(container2, { supportHighlights: true });
    const iconClass = $(".outline-element-icon");
    const decoration3 = $(".outline-element-decoration");
    container2.prepend(iconClass);
    container2.appendChild(decoration3);
    return new DocumentSymbolTemplate(container2, iconLabel, iconClass, decoration3);
  }
  renderElement(node, _index, template) {
    const { element } = node;
    const extraClasses = ["nowrap"];
    const options3 = {
      matches: $Ul(node.filterData),
      labelEscapeNewLines: true,
      extraClasses,
      title: localize(5208, null, element.symbol.name, $TE[element.symbol.kind])
    };
    if (this.d.getValue(
      "outline.icons"
      /* OutlineConfigKeys.icons */
    )) {
      template.iconClass.className = "";
      template.iconClass.classList.add("outline-element-icon", "inline", ...ThemeIcon.asClassNameArray(SymbolKinds.toIcon(element.symbol.kind)));
    }
    if (element.symbol.tags.indexOf(
      1
      /* SymbolTag.Deprecated */
    ) >= 0) {
      extraClasses.push(`deprecated`);
      options3.matches = [];
    }
    template.iconLabel.setLabel(element.symbol.name, element.symbol.detail, options3);
    if (this.c) {
      this.f(element, template);
    }
  }
  f(element, template) {
    if (!element.marker) {
      $ik(template.decoration);
      template.container.style.removeProperty("--outline-element-color");
      return;
    }
    const { count, topSev } = element.marker;
    const color2 = this.e.getColorTheme().getColor(topSev === MarkerSeverity.Error ? $xr : $yr);
    const cssColor = color2 ? color2.toString() : "inherit";
    const problem = this.d.getValue("problems.visibility");
    const configProblems = this.d.getValue(
      "outline.problems.colors"
      /* OutlineConfigKeys.problemsColors */
    );
    if (!problem || !configProblems) {
      template.container.style.removeProperty("--outline-element-color");
    } else {
      template.container.style.setProperty("--outline-element-color", cssColor);
    }
    if (problem === void 0) {
      return;
    }
    const configBadges = this.d.getValue(
      "outline.problems.badges"
      /* OutlineConfigKeys.problemsBadges */
    );
    if (!configBadges || !problem) {
      $ik(template.decoration);
    } else if (count > 0) {
      $hk(template.decoration);
      template.decoration.classList.remove("bubble");
      template.decoration.innerText = count < 10 ? count.toString() : "+9";
      template.decoration.title = count === 1 ? localize(5209, null) : localize(5210, null, count);
      template.decoration.style.setProperty("--outline-element-color", cssColor);
    } else {
      $hk(template.decoration);
      template.decoration.classList.add("bubble");
      template.decoration.innerText = "\uEA71";
      template.decoration.title = localize(5211, null);
      template.decoration.style.setProperty("--outline-element-color", cssColor);
    }
  }
  disposeTemplate(_template) {
    _template.iconLabel.dispose();
  }
};
$Ijc = __decorate([
  __param(2, $kl),
  __param(3, $gs)
], $Ijc);
var $Jjc = class $Jjc2 {
  static {
    $Jjc_1 = this;
  }
  static {
    this.kindToConfigName = Object.freeze({
      [
        0
        /* SymbolKind.File */
      ]: "showFiles",
      [
        1
        /* SymbolKind.Module */
      ]: "showModules",
      [
        2
        /* SymbolKind.Namespace */
      ]: "showNamespaces",
      [
        3
        /* SymbolKind.Package */
      ]: "showPackages",
      [
        4
        /* SymbolKind.Class */
      ]: "showClasses",
      [
        5
        /* SymbolKind.Method */
      ]: "showMethods",
      [
        6
        /* SymbolKind.Property */
      ]: "showProperties",
      [
        7
        /* SymbolKind.Field */
      ]: "showFields",
      [
        8
        /* SymbolKind.Constructor */
      ]: "showConstructors",
      [
        9
        /* SymbolKind.Enum */
      ]: "showEnums",
      [
        10
        /* SymbolKind.Interface */
      ]: "showInterfaces",
      [
        11
        /* SymbolKind.Function */
      ]: "showFunctions",
      [
        12
        /* SymbolKind.Variable */
      ]: "showVariables",
      [
        13
        /* SymbolKind.Constant */
      ]: "showConstants",
      [
        14
        /* SymbolKind.String */
      ]: "showStrings",
      [
        15
        /* SymbolKind.Number */
      ]: "showNumbers",
      [
        16
        /* SymbolKind.Boolean */
      ]: "showBooleans",
      [
        17
        /* SymbolKind.Array */
      ]: "showArrays",
      [
        18
        /* SymbolKind.Object */
      ]: "showObjects",
      [
        19
        /* SymbolKind.Key */
      ]: "showKeys",
      [
        20
        /* SymbolKind.Null */
      ]: "showNull",
      [
        21
        /* SymbolKind.EnumMember */
      ]: "showEnumMembers",
      [
        22
        /* SymbolKind.Struct */
      ]: "showStructs",
      [
        23
        /* SymbolKind.Event */
      ]: "showEvents",
      [
        24
        /* SymbolKind.Operator */
      ]: "showOperators",
      [
        25
        /* SymbolKind.TypeParameter */
      ]: "showTypeParameters"
    });
  }
  constructor(c, d) {
    this.c = c;
    this.d = d;
  }
  filter(element) {
    const outline = $ohb.get(element);
    if (!(element instanceof $mhb)) {
      return true;
    }
    const configName = $Jjc_1.kindToConfigName[element.symbol.kind];
    const configKey = `${this.c}.${configName}`;
    return this.d.getValue(outline?.uri, configKey);
  }
};
$Jjc = $Jjc_1 = __decorate([
  __param(1, $zG)
], $Jjc);
var $Kjc = class {
  constructor() {
    this.c = new $hj($Y, () => new Intl.Collator(void 0, { numeric: true }));
  }
  compareByPosition(a, b) {
    if (a instanceof $nhb && b instanceof $nhb) {
      return a.order - b.order;
    } else if (a instanceof $mhb && b instanceof $mhb) {
      return $9C.compareRangesUsingStarts(a.symbol.range, b.symbol.range) || this.c.value.compare(a.symbol.name, b.symbol.name);
    }
    return 0;
  }
  compareByType(a, b) {
    if (a instanceof $nhb && b instanceof $nhb) {
      return a.order - b.order;
    } else if (a instanceof $mhb && b instanceof $mhb) {
      return a.symbol.kind - b.symbol.kind || this.c.value.compare(a.symbol.name, b.symbol.name);
    }
    return 0;
  }
  compareByName(a, b) {
    if (a instanceof $nhb && b instanceof $nhb) {
      return a.order - b.order;
    } else if (a instanceof $mhb && b instanceof $mhb) {
      return this.c.value.compare(a.symbol.name, b.symbol.name) || $9C.compareRangesUsingStarts(a.symbol.range, b.symbol.range);
    }
    return 0;
  }
};

// out-build/vs/workbench/contrib/codeEditor/browser/outline/documentSymbolsOutline.js
var DocumentSymbolBreadcrumbsSource = class DocumentSymbolBreadcrumbsSource2 {
  constructor(b, c) {
    this.b = b;
    this.c = c;
    this.a = [];
  }
  getBreadcrumbElements() {
    return this.a;
  }
  clear() {
    this.a = [];
  }
  update(model, position) {
    const newElements = this.d(model, position);
    this.a = newElements;
  }
  d(model, position) {
    let item = model.getItemEnclosingPosition(position);
    if (!item) {
      return [];
    }
    const chain = [];
    while (item) {
      chain.push(item);
      const parent = item.parent;
      if (parent instanceof $ohb) {
        break;
      }
      if (parent instanceof $nhb && parent.parent && parent.parent.children.size === 1) {
        break;
      }
      item = parent;
    }
    const result = [];
    for (let i2 = chain.length - 1; i2 >= 0; i2--) {
      const element = chain[i2];
      if (this.f(element)) {
        break;
      }
      result.push(element);
    }
    if (result.length === 0) {
      return [];
    }
    return result;
  }
  f(element) {
    if (!(element instanceof $mhb)) {
      return false;
    }
    const key2 = `breadcrumbs.${$Jjc.kindToConfigName[element.symbol.kind]}`;
    let uri;
    if (this.b && this.b.getModel()) {
      const model = this.b.getModel();
      uri = model.uri;
    }
    return !this.c.getValue(uri, key2);
  }
};
DocumentSymbolBreadcrumbsSource = __decorate([
  __param(1, $zG)
], DocumentSymbolBreadcrumbsSource);
var DocumentSymbolsOutline = class DocumentSymbolsOutline2 {
  get activeElement() {
    const posistion = this.g.getPosition();
    if (!posistion || !this.c) {
      return void 0;
    } else {
      return this.c.getItemEnclosingPosition(posistion);
    }
  }
  constructor(g, target, firstLoadBarrier, h3, j, k, l, m, textResourceConfigurationService, instantiationService) {
    this.g = g;
    this.h = h3;
    this.j = j;
    this.k = k;
    this.l = l;
    this.m = m;
    this.a = new $2c();
    this.b = new $ze();
    this.onDidChange = this.b.event;
    this.d = new $2c();
    this.outlineKind = "documentSymbols";
    this.f = new DocumentSymbolBreadcrumbsSource(g, textResourceConfigurationService);
    const delegate = new $Gjc();
    const renderers = [new $Hjc(), instantiationService.createInstance($Ijc, true, target)];
    const treeDataSource = {
      getChildren: (parent) => {
        if (parent instanceof $mhb || parent instanceof $nhb) {
          return parent.children.values();
        }
        if (parent === this && this.c) {
          return this.c.children.values();
        }
        return [];
      }
    };
    const comparator = new $Kjc();
    const initialState = textResourceConfigurationService.getValue(
      g.getModel()?.uri,
      "outline.collapseItems"
      /* OutlineConfigKeys.collapseItems */
    );
    const options3 = {
      collapseByDefault: target === 2 || target === 1 && initialState === "alwaysCollapse",
      expandOnlyOnTwistieClick: true,
      multipleSelectionSupport: false,
      identityProvider: new $Ejc(),
      keyboardNavigationLabelProvider: new $Cjc(),
      accessibilityProvider: new $Djc(localize(5207, null)),
      filter: target === 1 ? instantiationService.createInstance($Jjc, "outline") : target === 2 ? instantiationService.createInstance($Jjc, "breadcrumbs") : void 0,
      dnd: instantiationService.createInstance($Fjc)
    };
    this.config = {
      breadcrumbsDataSource: this.f,
      delegate,
      renderers,
      treeDataSource,
      comparator,
      options: options3,
      quickPickDataSource: { getQuickPickElements: () => {
        throw new Error("not implemented");
      } }
    };
    this.a.add(h3.documentSymbolProvider.onDidChange((_) => this.n()));
    this.a.add(this.g.onDidChangeModel((_) => this.n()));
    this.a.add(this.g.onDidChangeModelLanguage((_) => this.n()));
    const updateSoon = new $6h();
    this.a.add(updateSoon);
    this.a.add(this.g.onDidChangeModelContent((event) => {
      const model = this.g.getModel();
      if (model) {
        const timeout = k.getDebounceValue(model);
        updateSoon.cancelAndSet(() => this.n(event), timeout);
      }
    }));
    this.a.add(this.g.onDidDispose(() => this.d.clear()));
    this.n().finally(() => firstLoadBarrier.open());
  }
  dispose() {
    this.a.dispose();
    this.d.dispose();
  }
  get isEmpty() {
    return !this.c || $lhb.empty(this.c);
  }
  get uri() {
    return this.c?.uri;
  }
  async reveal(entry, options3, sideBySide, select) {
    const model = $ohb.get(entry);
    if (!model || !(entry instanceof $mhb)) {
      return;
    }
    await this.j.openCodeEditor({
      resource: model.uri,
      options: {
        ...options3,
        selection: select ? entry.symbol.range : $9C.collapseToStart(entry.symbol.selectionRange),
        selectionRevealType: 3
      }
    }, this.g, sideBySide);
  }
  preview(entry) {
    if (!(entry instanceof $mhb)) {
      return $3c.None;
    }
    const { symbol } = entry;
    this.g.revealRangeInCenterIfOutsideViewport(
      symbol.range,
      0
      /* ScrollType.Smooth */
    );
    const decorationsCollection = this.g.createDecorationsCollection([{
      range: symbol.range,
      options: {
        description: "document-symbols-outline-range-highlight",
        className: "rangeHighlight",
        isWholeLine: true
      }
    }]);
    return $1c(() => decorationsCollection.clear());
  }
  captureViewState() {
    const viewState = this.g.saveViewState();
    return $1c(() => {
      if (viewState) {
        this.g.restoreViewState(viewState);
      }
    });
  }
  async n(contentChangeEvent) {
    this.d.clear();
    if (!contentChangeEvent) {
      this.p(void 0);
    }
    if (!this.g.hasModel()) {
      return;
    }
    const buffer = this.g.getModel();
    if (!this.h.documentSymbolProvider.has(buffer)) {
      return;
    }
    const cts = new $ad();
    const versionIdThen = buffer.getVersionId();
    const timeoutTimer = new $6h();
    this.d.add(timeoutTimer);
    this.d.add($1c(() => cts.dispose(true)));
    try {
      const model = await this.k.getOrCreate(buffer, cts.token);
      if (cts.token.isCancellationRequested) {
        return;
      }
      if ($lhb.empty(model) || !this.g.hasModel()) {
        this.p(model);
        return;
      }
      if (contentChangeEvent && this.c && buffer.getLineCount() >= 25) {
        const newSize = $lhb.size(model);
        const newLength = buffer.getValueLength();
        const newRatio = newSize / newLength;
        const oldSize = $lhb.size(this.c);
        const oldLength = newLength - contentChangeEvent.changes.reduce((prev, value) => prev + value.rangeLength, 0);
        const oldRatio = oldSize / oldLength;
        if (newRatio <= oldRatio * 0.5 || newRatio >= oldRatio * 1.5) {
          const value = await $Ih($Wh(2e3).then(() => true), cts.token, false);
          if (!value) {
            return;
          }
        }
      }
      this.o(model);
      this.d.add(this.m.onDidChangeMarker((textModel) => {
        if ($oh(model.uri, textModel.uri)) {
          this.o(model);
          this.b.fire({});
        }
      }));
      this.d.add(this.l.onDidChangeConfiguration((e) => {
        if (e.affectsConfiguration(
          "outline.problems.enabled"
          /* OutlineConfigKeys.problemsEnabled */
        ) || e.affectsConfiguration("problems.visibility")) {
          const problem = this.l.getValue("problems.visibility");
          const config = this.l.getValue(
            "outline.problems.enabled"
            /* OutlineConfigKeys.problemsEnabled */
          );
          if (!problem || !config) {
            model.updateMarker([]);
          } else {
            this.o(model);
          }
          this.b.fire({});
        }
        if (e.affectsConfiguration("outline")) {
          this.b.fire({});
        }
        if (e.affectsConfiguration("breadcrumbs") && this.g.hasModel()) {
          this.f.update(model, this.g.getPosition());
          this.b.fire({});
        }
      }));
      this.d.add(this.l.onDidChangeConfiguration((e) => {
        if (e.affectsConfiguration(
          "outline.icons"
          /* OutlineConfigKeys.icons */
        )) {
          this.b.fire({});
        }
        if (e.affectsConfiguration("outline")) {
          this.b.fire({});
        }
      }));
      this.d.add(this.g.onDidChangeCursorPosition((_) => {
        timeoutTimer.cancelAndSet(() => {
          if (!buffer.isDisposed() && versionIdThen === buffer.getVersionId() && this.g.hasModel()) {
            this.f.update(model, this.g.getPosition());
            this.b.fire({ affectOnlyActiveElement: true });
          }
        }, 150);
      }));
      this.p(model);
    } catch (err) {
      this.p(void 0);
      $gb(err);
    }
  }
  o(model) {
    const problem = this.l.getValue("problems.visibility");
    const config = this.l.getValue(
      "outline.problems.enabled"
      /* OutlineConfigKeys.problemsEnabled */
    );
    if (!model || !problem || !config) {
      return;
    }
    const markers = [];
    for (const [range, marker] of this.m.getLiveMarkers(model.uri)) {
      if (marker.severity === MarkerSeverity.Error || marker.severity === MarkerSeverity.Warning) {
        markers.push({ ...range, severity: marker.severity });
      }
    }
    model.updateMarker(markers);
  }
  p(model) {
    const position = this.g.getPosition();
    if (!position || !model) {
      this.c = void 0;
      this.f.clear();
    } else {
      if (!this.c?.merge(model)) {
        this.c = model;
      }
      this.f.update(model, position);
    }
    this.b.fire({});
  }
};
DocumentSymbolsOutline = __decorate([
  __param(3, $mP),
  __param(4, $U5),
  __param(5, $phb),
  __param(6, $kl),
  __param(7, $V6),
  __param(8, $zG),
  __param(9, $Pk)
], DocumentSymbolsOutline);
var DocumentSymbolsOutlineCreator = class DocumentSymbolsOutlineCreator2 {
  constructor(outlineService) {
    const reg2 = outlineService.registerOutlineCreator(this);
    this.dispose = () => reg2.dispose();
  }
  matches(candidate) {
    const ctrl = candidate.getControl();
    return $P5(ctrl) || $Q5(ctrl);
  }
  async createOutline(pane, target, _token) {
    const control = pane.getControl();
    let editor;
    if ($P5(control)) {
      editor = control;
    } else if ($Q5(control)) {
      editor = control.getModifiedEditor();
    }
    if (!editor) {
      return void 0;
    }
    const firstLoadBarrier = new $Uh();
    const result = editor.invokeWithinContext((accessor) => accessor.get($Pk).createInstance(DocumentSymbolsOutline, editor, target, firstLoadBarrier));
    await firstLoadBarrier.wait();
    return result;
  }
};
DocumentSymbolsOutlineCreator = __decorate([
  __param(0, $vyb)
], DocumentSymbolsOutlineCreator);
$Wn.as(Extensions2.Workbench).registerWorkbenchContribution(
  DocumentSymbolsOutlineCreator,
  4
  /* LifecyclePhase.Eventually */
);

// out-build/vs/workbench/contrib/outline/browser/outlineViewState.js
var $Ljc = class {
  constructor() {
    this.a = false;
    this.b = true;
    this.c = 0;
    this.d = new $ze();
    this.onDidChange = this.d.event;
  }
  dispose() {
    this.d.dispose();
  }
  set followCursor(value) {
    if (value !== this.a) {
      this.a = value;
      this.d.fire({ followCursor: true });
    }
  }
  get followCursor() {
    return this.a;
  }
  get filterOnType() {
    return this.b;
  }
  set filterOnType(value) {
    if (value !== this.b) {
      this.b = value;
      this.d.fire({ filterOnType: true });
    }
  }
  set sortBy(value) {
    if (value !== this.c) {
      this.c = value;
      this.d.fire({ sortBy: true });
    }
  }
  get sortBy() {
    return this.c;
  }
  persist(storageService) {
    storageService.store(
      "outline/state",
      JSON.stringify({
        followCursor: this.followCursor,
        sortBy: this.sortBy,
        filterOnType: this.filterOnType
      }),
      1,
      1
      /* StorageTarget.MACHINE */
    );
  }
  restore(storageService) {
    const raw = storageService.get(
      "outline/state",
      1
      /* StorageScope.WORKSPACE */
    );
    if (!raw) {
      return;
    }
    let data;
    try {
      data = JSON.parse(raw);
    } catch (e) {
      return;
    }
    this.followCursor = data.followCursor;
    this.sortBy = data.sortBy ?? 0;
    if (typeof data.filterOnType === "boolean") {
      this.filterOnType = data.filterOnType;
    }
  }
};

// out-build/vs/workbench/contrib/outline/browser/outlinePane.js
var OutlineTreeSorter3 = class {
  constructor(c, order) {
    this.c = c;
    this.order = order;
  }
  compare(a, b) {
    if (this.order === 2) {
      return this.c.compareByType(a, b);
    } else if (this.order === 1) {
      return this.c.compareByName(a, b);
    } else {
      return this.c.compareByPosition(a, b);
    }
  }
};
var $Mjc = class $Mjc2 extends $_ob {
  static {
    this.Id = "outline";
  }
  constructor(options3, dc, ec, viewDescriptorService, fc, gc, configurationService, keybindingService, contextKeyService, contextMenuService, openerService, themeService, telemetryService, hoverService) {
    super(options3, keybindingService, contextMenuService, configurationService, contextKeyService, viewDescriptorService, ec, openerService, themeService, telemetryService, hoverService);
    this.dc = dc;
    this.ec = ec;
    this.fc = fc;
    this.gc = gc;
    this.c = new $2c();
    this.f = new $2c();
    this.g = new $2c();
    this.h = new $Ljc();
    this.j = new $4c();
    this.ab = new $Hc(10);
    this.h.restore(this.fc);
    this.c.add(this.h);
    contextKeyService.bufferChangeEvents(() => {
      this.sb = $JLb.bindTo(contextKeyService);
      this.ac = $KLb.bindTo(contextKeyService);
      this.bc = $LLb.bindTo(contextKeyService);
      this.cc = $MLb.bindTo(contextKeyService);
    });
    const updateContext = () => {
      this.sb.set(this.h.followCursor);
      this.ac.set(this.h.filterOnType);
      this.bc.set(this.h.sortBy);
    };
    updateContext();
    this.c.add(this.h.onDidChange(updateContext));
  }
  dispose() {
    this.c.dispose();
    this.g.dispose();
    this.f.dispose();
    this.j.dispose();
    super.dispose();
  }
  focus() {
    super.focus();
    this.t?.domFocus();
  }
  W(container2) {
    super.W(container2);
    this.m = container2;
    container2.classList.add("outline-pane");
    const progressContainer = $(".outline-progress");
    this.n = $(".outline-message");
    this.r = new $02(progressContainer, $s$);
    this.s = $(".outline-tree");
    $bk(container2, progressContainer, this.n, this.s);
    this.c.add(this.onDidChangeBodyVisibility((visible) => {
      if (!visible) {
        this.j.clear();
        this.g.clear();
        this.f.clear();
      } else if (!this.j.value) {
        const event = Event2.any(this.gc.onDidActiveEditorChange, this.dc.onDidChange);
        this.j.value = event(() => this.lc(this.gc.activeEditorPane));
        this.lc(this.gc.activeEditorPane);
      }
    }));
  }
  X(height, width2) {
    super.X(height, width2);
    this.t?.layout(height, width2);
    this.L = new $rj(width2, height);
  }
  collapseAll() {
    this.t?.collapseAll();
  }
  expandAll() {
    this.t?.expandAll();
  }
  get outlineViewState() {
    return this.h;
  }
  jc(message) {
    this.m.classList.add("message");
    this.r.stop().hide();
    this.n.innerText = message;
  }
  kc(uri) {
    if (this.t) {
      const oldOutline = this.t.getInput();
      if (!uri) {
        uri = oldOutline?.uri;
      }
      if (oldOutline && uri) {
        this.ab.set(`${oldOutline.outlineKind}/${uri}`, this.t.getViewState());
        return true;
      }
    }
    return false;
  }
  lc(pane) {
    this.g.clear();
    if (pane) {
      this.g.add(pane.onDidChangeControl(() => {
        this.mc(pane);
      }));
    }
    this.mc(pane);
  }
  async mc(pane) {
    const resource = $mL.getOriginalUri(pane?.input);
    const didCapture = this.kc();
    this.f.clear();
    if (!pane || !this.dc.canCreateOutline(pane) || !resource) {
      return this.jc(localize(8672, null));
    }
    let loadingMessage;
    if (!didCapture) {
      loadingMessage = new $6h(() => {
        this.jc(localize(8673, null, $sh(resource)));
      }, 100);
    }
    this.r.infinite().show(500);
    const cts = new $ad();
    this.f.add($1c(() => cts.dispose(true)));
    const newOutline = await this.dc.createOutline(pane, 1, cts.token);
    loadingMessage?.dispose();
    if (!newOutline) {
      return;
    }
    if (cts.token.isCancellationRequested) {
      newOutline?.dispose();
      return;
    }
    this.f.add(newOutline);
    this.r.stop().hide();
    const sorter3 = new OutlineTreeSorter3(newOutline.config.comparator, this.h.sortBy);
    const tree = this.ec.createInstance($3eb, "OutlinePane", this.s, newOutline.config.delegate, newOutline.config.renderers, newOutline.config.treeDataSource, {
      ...newOutline.config.options,
      sorter: sorter3,
      expandOnDoubleClick: false,
      expandOnlyOnTwistieClick: true,
      multipleSelectionSupport: false,
      hideTwistiesOfChildlessElements: true,
      defaultFindMode: this.h.filterOnType ? TreeFindMode.Filter : TreeFindMode.Highlight,
      overrideStyles: this.Xb().listOverrideStyles
    });
    $NLb.bindTo(tree.contextKeyService);
    const updateTree = () => {
      if (newOutline.isEmpty) {
        this.jc(localize(8674, null, $sh(resource)));
        this.kc(resource);
        tree.setInput(void 0);
      } else if (!tree.getInput()) {
        this.m.classList.remove("message");
        const state = this.ab.get(`${newOutline.outlineKind}/${newOutline.uri}`);
        tree.setInput(newOutline, state && $o3.lift(state));
      } else {
        this.m.classList.remove("message");
        tree.updateChildren();
      }
    };
    updateTree();
    this.f.add(newOutline.onDidChange(updateTree));
    tree.findMode = this.h.filterOnType ? TreeFindMode.Filter : TreeFindMode.Highlight;
    this.f.add(this.Cb.onDidChangeLocation(({ views }) => {
      if (views.some((v) => v.id === this.id)) {
        tree.updateOptions({ overrideStyles: this.Xb().listOverrideStyles });
      }
    }));
    this.f.add(tree.onDidChangeFindMode((mode) => this.h.filterOnType = mode === TreeFindMode.Filter));
    let idPool = 0;
    this.f.add(tree.onDidOpen(async (e) => {
      const myId = ++idPool;
      const isDoubleClick = e.browserEvent?.type === "dblclick";
      if (!isDoubleClick) {
        await $Wh(150);
        if (myId !== idPool) {
          return;
        }
      }
      await newOutline.reveal(e.element, e.editorOptions, e.sideBySide, isDoubleClick);
    }));
    const revealActiveElement = () => {
      if (!this.h.followCursor || !newOutline.activeElement) {
        return;
      }
      let item = newOutline.activeElement;
      while (item) {
        const top2 = tree.getRelativeTop(item);
        if (top2 === null) {
          tree.reveal(item, 0.5);
        }
        if (tree.getRelativeTop(item) !== null) {
          tree.setFocus([item]);
          tree.setSelection([item]);
          break;
        }
        item = tree.getParentElement(item);
      }
    };
    revealActiveElement();
    this.f.add(newOutline.onDidChange(revealActiveElement));
    this.f.add(this.h.onDidChange((e) => {
      this.h.persist(this.fc);
      if (e.filterOnType) {
        tree.findMode = this.h.filterOnType ? TreeFindMode.Filter : TreeFindMode.Highlight;
      }
      if (e.followCursor) {
        revealActiveElement();
      }
      if (e.sortBy) {
        sorter3.order = this.h.sortBy;
        tree.resort();
      }
    }));
    let viewState;
    this.f.add(tree.onDidChangeFindPattern((pattern) => {
      if (tree.findMode === TreeFindMode.Highlight) {
        return;
      }
      if (!viewState && pattern) {
        viewState = tree.getViewState();
        tree.expandAll();
      } else if (!pattern && viewState) {
        tree.setInput(tree.getInput(), viewState);
        viewState = void 0;
      }
    }));
    const updateAllCollapsedCtx = () => {
      this.cc.set(tree.getNode(null).children.every((node) => !node.collapsible || node.collapsed));
    };
    this.f.add(tree.onDidChangeCollapseState(updateAllCollapsedCtx));
    this.f.add(tree.onDidChangeModel(updateAllCollapsedCtx));
    updateAllCollapsedCtx();
    tree.layout(this.L?.height, this.L?.width);
    this.t = tree;
    this.f.add($1c(() => {
      tree.dispose();
      this.t = void 0;
    }));
  }
};
$Mjc = __decorate([
  __param(1, $vyb),
  __param(2, $Pk),
  __param(3, $$M),
  __param(4, $jv),
  __param(5, $mJ),
  __param(6, $kl),
  __param(7, $Ty),
  __param(8, $on),
  __param(9, $50),
  __param(10, $O4),
  __param(11, $gs),
  __param(12, $zv),
  __param(13, $5$)
], $Mjc);

// out-build/vs/workbench/contrib/outline/browser/outlineActions.js
$hJ(class CollapseAll extends $cpb {
  constructor() {
    super({
      viewId: IOutlinePane.Id,
      id: "outline.collapse",
      title: localize(8665, null),
      f1: false,
      icon: $6l.collapseAll,
      menu: {
        id: $bJ.ViewTitle,
        group: "navigation",
        when: $7m.and($7m.equals("view", IOutlinePane.Id), $MLb.isEqualTo(false))
      }
    });
  }
  runInView(_accessor, view) {
    view.collapseAll();
  }
});
$hJ(class ExpandAll extends $cpb {
  constructor() {
    super({
      viewId: IOutlinePane.Id,
      id: "outline.expand",
      title: localize(8666, null),
      f1: false,
      icon: $6l.expandAll,
      menu: {
        id: $bJ.ViewTitle,
        group: "navigation",
        when: $7m.and($7m.equals("view", IOutlinePane.Id), $MLb.isEqualTo(true))
      }
    });
  }
  runInView(_accessor, view) {
    view.expandAll();
  }
});
$hJ(class FollowCursor extends $cpb {
  constructor() {
    super({
      viewId: IOutlinePane.Id,
      id: "outline.followCursor",
      title: localize(8667, null),
      f1: false,
      toggled: $JLb,
      menu: {
        id: $bJ.ViewTitle,
        group: "config",
        order: 1,
        when: $7m.equals("view", IOutlinePane.Id)
      }
    });
  }
  runInView(_accessor, view) {
    view.outlineViewState.followCursor = !view.outlineViewState.followCursor;
  }
});
$hJ(class FilterOnType extends $cpb {
  constructor() {
    super({
      viewId: IOutlinePane.Id,
      id: "outline.filterOnType",
      title: localize(8668, null),
      f1: false,
      toggled: $KLb,
      menu: {
        id: $bJ.ViewTitle,
        group: "config",
        order: 2,
        when: $7m.equals("view", IOutlinePane.Id)
      }
    });
  }
  runInView(_accessor, view) {
    view.outlineViewState.filterOnType = !view.outlineViewState.filterOnType;
  }
});
$hJ(class SortByPosition extends $cpb {
  constructor() {
    super({
      viewId: IOutlinePane.Id,
      id: "outline.sortByPosition",
      title: localize(8669, null),
      f1: false,
      toggled: $LLb.isEqualTo(
        0
        /* OutlineSortOrder.ByPosition */
      ),
      menu: {
        id: $bJ.ViewTitle,
        group: "sort",
        order: 1,
        when: $7m.equals("view", IOutlinePane.Id)
      }
    });
  }
  runInView(_accessor, view) {
    view.outlineViewState.sortBy = 0;
  }
});
$hJ(class SortByName extends $cpb {
  constructor() {
    super({
      viewId: IOutlinePane.Id,
      id: "outline.sortByName",
      title: localize(8670, null),
      f1: false,
      toggled: $LLb.isEqualTo(
        1
        /* OutlineSortOrder.ByName */
      ),
      menu: {
        id: $bJ.ViewTitle,
        group: "sort",
        order: 2,
        when: $7m.equals("view", IOutlinePane.Id)
      }
    });
  }
  runInView(_accessor, view) {
    view.outlineViewState.sortBy = 1;
  }
});
$hJ(class SortByKind extends $cpb {
  constructor() {
    super({
      viewId: IOutlinePane.Id,
      id: "outline.sortByKind",
      title: localize(8671, null),
      f1: false,
      toggled: $LLb.isEqualTo(
        2
        /* OutlineSortOrder.ByKind */
      ),
      menu: {
        id: $bJ.ViewTitle,
        group: "sort",
        order: 3,
        when: $7m.equals("view", IOutlinePane.Id)
      }
    });
  }
  runInView(_accessor, view) {
    view.outlineViewState.sortBy = 2;
  }
});

// out-build/vs/workbench/contrib/outline/browser/outline.contribution.js
var outlineViewIcon = $9r("outline-view-icon", $6l.symbolClass, localize(8629, null));
$Wn.as(Extensions5.ViewsRegistry).registerViews([{
  id: IOutlinePane.Id,
  name: localize2(8664, "Outline"),
  containerIcon: outlineViewIcon,
  ctorDescriptor: new $Nk($Mjc),
  canToggleVisibility: true,
  canMoveView: true,
  hideByDefault: false,
  collapsed: true,
  order: 2,
  weight: 30,
  focusCommand: { id: "outline.focus" }
}], $dzb);
$Wn.as($Ht.Configuration).registerConfiguration({
  "id": "outline",
  "order": 117,
  "title": localize(8630, null),
  "type": "object",
  "properties": {
    [
      "outline.icons"
      /* OutlineConfigKeys.icons */
    ]: {
      "description": localize(8631, null),
      "type": "boolean",
      "default": true
    },
    [
      "outline.collapseItems"
      /* OutlineConfigKeys.collapseItems */
    ]: {
      "description": localize(8632, null),
      "type": "string",
      scope: 5,
      "enum": [
        "alwaysCollapse",
        "alwaysExpand"
      ],
      "enumDescriptions": [
        localize(8633, null),
        localize(8634, null)
      ],
      "default": "alwaysExpand"
    },
    [
      "outline.problems.enabled"
      /* OutlineConfigKeys.problemsEnabled */
    ]: {
      "markdownDescription": localize(8635, null, "`#problems.visibility#`"),
      "type": "boolean",
      "default": true
    },
    [
      "outline.problems.colors"
      /* OutlineConfigKeys.problemsColors */
    ]: {
      "markdownDescription": localize(8636, null, "`#problems.visibility#`"),
      "type": "boolean",
      "default": true
    },
    [
      "outline.problems.badges"
      /* OutlineConfigKeys.problemsBadges */
    ]: {
      "markdownDescription": localize(8637, null, "`#problems.visibility#`"),
      "type": "boolean",
      "default": true
    },
    "outline.showFiles": {
      type: "boolean",
      scope: 5,
      default: true,
      markdownDescription: localize(8638, null)
    },
    "outline.showModules": {
      type: "boolean",
      scope: 5,
      default: true,
      markdownDescription: localize(8639, null)
    },
    "outline.showNamespaces": {
      type: "boolean",
      default: true,
      scope: 5,
      markdownDescription: localize(8640, null)
    },
    "outline.showPackages": {
      type: "boolean",
      default: true,
      scope: 5,
      markdownDescription: localize(8641, null)
    },
    "outline.showClasses": {
      type: "boolean",
      default: true,
      scope: 5,
      markdownDescription: localize(8642, null)
    },
    "outline.showMethods": {
      type: "boolean",
      default: true,
      scope: 5,
      markdownDescription: localize(8643, null)
    },
    "outline.showProperties": {
      type: "boolean",
      default: true,
      scope: 5,
      markdownDescription: localize(8644, null)
    },
    "outline.showFields": {
      type: "boolean",
      default: true,
      scope: 5,
      markdownDescription: localize(8645, null)
    },
    "outline.showConstructors": {
      type: "boolean",
      default: true,
      scope: 5,
      markdownDescription: localize(8646, null)
    },
    "outline.showEnums": {
      type: "boolean",
      default: true,
      scope: 5,
      markdownDescription: localize(8647, null)
    },
    "outline.showInterfaces": {
      type: "boolean",
      default: true,
      scope: 5,
      markdownDescription: localize(8648, null)
    },
    "outline.showFunctions": {
      type: "boolean",
      default: true,
      scope: 5,
      markdownDescription: localize(8649, null)
    },
    "outline.showVariables": {
      type: "boolean",
      default: true,
      scope: 5,
      markdownDescription: localize(8650, null)
    },
    "outline.showConstants": {
      type: "boolean",
      default: true,
      scope: 5,
      markdownDescription: localize(8651, null)
    },
    "outline.showStrings": {
      type: "boolean",
      default: true,
      scope: 5,
      markdownDescription: localize(8652, null)
    },
    "outline.showNumbers": {
      type: "boolean",
      default: true,
      scope: 5,
      markdownDescription: localize(8653, null)
    },
    "outline.showBooleans": {
      type: "boolean",
      scope: 5,
      default: true,
      markdownDescription: localize(8654, null)
    },
    "outline.showArrays": {
      type: "boolean",
      default: true,
      scope: 5,
      markdownDescription: localize(8655, null)
    },
    "outline.showObjects": {
      type: "boolean",
      default: true,
      scope: 5,
      markdownDescription: localize(8656, null)
    },
    "outline.showKeys": {
      type: "boolean",
      default: true,
      scope: 5,
      markdownDescription: localize(8657, null)
    },
    "outline.showNull": {
      type: "boolean",
      default: true,
      scope: 5,
      markdownDescription: localize(8658, null)
    },
    "outline.showEnumMembers": {
      type: "boolean",
      default: true,
      scope: 5,
      markdownDescription: localize(8659, null)
    },
    "outline.showStructs": {
      type: "boolean",
      default: true,
      scope: 5,
      markdownDescription: localize(8660, null)
    },
    "outline.showEvents": {
      type: "boolean",
      default: true,
      scope: 5,
      markdownDescription: localize(8661, null)
    },
    "outline.showOperators": {
      type: "boolean",
      default: true,
      scope: 5,
      markdownDescription: localize(8662, null)
    },
    "outline.showTypeParameters": {
      type: "boolean",
      default: true,
      scope: 5,
      markdownDescription: localize(8663, null)
    }
  }
});

// out-build/vs/workbench/contrib/languageDetection/browser/languageDetection.contribution.js
var LanguageDetectionStatusContribution_1;
var detectLanguageCommandId = "editor.detectLanguage";
var LanguageDetectionStatusContribution = class LanguageDetectionStatusContribution2 {
  static {
    LanguageDetectionStatusContribution_1 = this;
  }
  static {
    this.a = "status.languageDetectionStatus";
  }
  constructor(f, g, h3, i2, j, k) {
    this.f = f;
    this.g = g;
    this.h = h3;
    this.i = i2;
    this.j = j;
    this.k = k;
    this.b = new $2c();
    this.d = new $Th(1e3);
    this.e = new $2c();
    i2.onDidActiveEditorChange(() => this.l(true), this, this.b);
    this.l(false);
  }
  dispose() {
    this.b.dispose();
    this.d.dispose();
    this.c?.dispose();
    this.e.dispose();
  }
  l(clear) {
    if (clear) {
      this.c?.dispose();
      this.c = void 0;
    }
    this.d.trigger(() => this.m());
  }
  async m() {
    const editor = $S5(this.i.activeTextEditorControl);
    this.e.clear();
    editor?.onDidChangeModelLanguage(() => this.l(true), this, this.e);
    editor?.onDidChangeModelContent(() => this.l(false), this, this.e);
    const editorModel = editor?.getModel();
    const editorUri = editorModel?.uri;
    const existingId = editorModel?.getLanguageId();
    const enablementConfig = this.h.getValue("workbench.editor.languageDetectionHints");
    const enabled = typeof enablementConfig === "object" && enablementConfig?.untitledEditors;
    const disableLightbulb = !enabled || editorUri?.scheme !== Schemas.untitled || !existingId;
    if (disableLightbulb || !editorUri) {
      this.c?.dispose();
      this.c = void 0;
    } else {
      const lang = await this.f.detectLanguage(editorUri);
      const skip = { "jsonc": "json" };
      const existing = editorModel.getLanguageId();
      if (lang && lang !== existing && skip[existing] !== lang) {
        const detectedName = this.j.getLanguageName(lang) || lang;
        let tooltip = localize(7690, null, detectedName);
        const keybinding = this.k.lookupKeybinding(detectLanguageCommandId);
        const label3 = keybinding?.getLabel();
        if (label3) {
          tooltip += ` (${label3})`;
        }
        const props = {
          name: localize(7691, null),
          ariaLabel: localize(7692, null, lang),
          tooltip,
          command: detectLanguageCommandId,
          text: "$(lightbulb-autofix)"
        };
        if (!this.c) {
          this.c = this.g.addEntry(props, LanguageDetectionStatusContribution_1.a, 1, { id: "status.editor.mode", alignment: 1, compact: true });
        } else {
          this.c.update(props);
        }
      } else {
        this.c?.dispose();
        this.c = void 0;
      }
    }
  }
};
LanguageDetectionStatusContribution = LanguageDetectionStatusContribution_1 = __decorate([
  __param(0, $tG),
  __param(1, $$qb),
  __param(2, $kl),
  __param(3, $mJ),
  __param(4, $1E),
  __param(5, $Ty)
], LanguageDetectionStatusContribution);
$Wn.as(Extensions2.Workbench).registerWorkbenchContribution(
  LanguageDetectionStatusContribution,
  3
  /* LifecyclePhase.Restored */
);
$hJ(class extends $gJ {
  constructor() {
    super({
      id: detectLanguageCommandId,
      title: localize2(7694, "Detect Language from Content"),
      f1: true,
      precondition: $7m.and($1Ab.toNegated(), EditorContextKeys.editorTextFocus),
      keybinding: {
        primary: 34 | 512 | 1024,
        weight: 200
        /* KeybindingWeight.WorkbenchContrib */
      }
    });
  }
  async run(accessor) {
    const editorService = accessor.get($mJ);
    const languageDetectionService = accessor.get($tG);
    const editor = $S5(editorService.activeTextEditorControl);
    const notificationService = accessor.get($PJ);
    const editorUri = editor?.getModel()?.uri;
    if (editorUri) {
      const lang = await languageDetectionService.detectLanguage(editorUri);
      if (lang) {
        editor.getModel()?.setLanguage(lang, $uG);
      } else {
        notificationService.warn(localize(7693, null));
      }
    }
  }
});

// out-build/vs/workbench/contrib/languageStatus/browser/languageStatus.js
var LanguageStatus_1;
var LanguageStatusViewModel = class {
  constructor(combined, dedicated) {
    this.combined = combined;
    this.dedicated = dedicated;
  }
  isEqual(other) {
    return $zb(this.combined, other.combined) && $zb(this.dedicated, other.dedicated);
  }
};
var StoredCounter = class StoredCounter2 {
  constructor(a, b) {
    this.a = a;
    this.b = b;
  }
  get value() {
    return this.a.getNumber(this.b, 0, 0);
  }
  increment() {
    const n = this.value + 1;
    this.a.store(
      this.b,
      n,
      0,
      1
      /* StorageTarget.MACHINE */
    );
    return n;
  }
};
StoredCounter = __decorate([
  __param(0, $jv)
], StoredCounter);
var $Njc = class $Njc2 extends $3c {
  static {
    this.Id = "status.languageStatus";
  }
  constructor(a) {
    super();
    this.a = a;
    for (const part of a.parts) {
      this.b(part);
    }
    this.B(a.onDidCreateAuxiliaryEditorPart((part) => this.b(part)));
  }
  b(part) {
    const disposables = new $2c();
    Event2.once(part.onWillDispose)(() => disposables.dispose());
    const scopedInstantiationService = this.a.getScopedInstantiationService(part);
    disposables.add(scopedInstantiationService.createInstance(LanguageStatus));
  }
};
$Njc = __decorate([
  __param(0, $iJ)
], $Njc);
var LanguageStatus = class LanguageStatus2 {
  static {
    LanguageStatus_1 = this;
  }
  static {
    this.a = "status.languageStatus";
  }
  static {
    this.b = "languageStatus.dedicated";
  }
  constructor(k, l, m, o, p, q) {
    this.k = k;
    this.l = l;
    this.m = m;
    this.o = o;
    this.p = p;
    this.q = q;
    this.c = new $2c();
    this.f = /* @__PURE__ */ new Set();
    this.i = /* @__PURE__ */ new Map();
    this.j = new $2c();
    q.onDidChangeValue(0, LanguageStatus_1.b, this.c)(this.r, this, this.c);
    this.s();
    this.d = new StoredCounter(q, "languageStatus.interactCount");
    k.onDidChange(this.v, this, this.c);
    m.onDidActiveEditorChange(this.v, this, this.c);
    this.v();
    l.onDidChangeEntryVisibility((e) => {
      if (!e.visible && this.f.has(e.id)) {
        this.f.delete(e.id);
        this.v();
        this.t();
      }
    }, void 0, this.c);
  }
  dispose() {
    this.c.dispose();
    this.h?.dispose();
    $Xc(this.i.values());
    this.j.dispose();
  }
  // --- persisting dedicated items
  r() {
    this.s();
    this.v();
  }
  s() {
    const raw = this.q.get(LanguageStatus_1.b, 0, "[]");
    try {
      const ids = JSON.parse(raw);
      this.f = new Set(ids);
    } catch {
      this.f.clear();
    }
  }
  t() {
    if (this.f.size === 0) {
      this.q.remove(
        LanguageStatus_1.b,
        0
        /* StorageScope.PROFILE */
      );
    } else {
      const raw = JSON.stringify(Array.from(this.f.keys()));
      this.q.store(
        LanguageStatus_1.b,
        raw,
        0,
        0
        /* StorageTarget.USER */
      );
    }
  }
  // --- language status model and UI
  u(editor) {
    if (!editor?.hasModel()) {
      return new LanguageStatusViewModel([], []);
    }
    const all = this.k.getLanguageStatus(editor.getModel());
    const combined = [];
    const dedicated = [];
    for (const item of all) {
      if (this.f.has(item.id)) {
        dedicated.push(item);
      }
      combined.push(item);
    }
    return new LanguageStatusViewModel(combined, dedicated);
  }
  v() {
    const editor = $S5(this.m.activeTextEditorControl);
    const model = this.u(editor);
    if (this.g?.isEqual(model)) {
      return;
    }
    this.j.clear();
    this.g = model;
    editor?.onDidChangeModelLanguage(this.v, this, this.j);
    if (model.combined.length === 0) {
      this.h?.dispose();
      this.h = void 0;
    } else {
      const [first] = model.combined;
      const showSeverity = first.severity >= severity_default.Warning;
      const text2 = LanguageStatus_1.x(first.severity);
      let isOneBusy = false;
      const ariaLabels = [];
      const element = document.createElement("div");
      for (const status of model.combined) {
        const isPinned = model.dedicated.includes(status);
        element.appendChild(this.w(status, showSeverity, isPinned, this.j));
        ariaLabels.push(LanguageStatus_1.A(status).label);
        isOneBusy = isOneBusy || !isPinned && status.busy;
      }
      const props = {
        name: localize(7695, null),
        ariaLabel: localize(7696, null, ariaLabels.join(", next: ")),
        tooltip: element,
        command: $brb,
        text: isOneBusy ? "$(loading~spin)" : text2
      };
      if (!this.h) {
        this.h = this.l.addEntry(props, LanguageStatus_1.a, 1, { id: "status.editor.mode", alignment: 0, compact: true });
      } else {
        this.h.update(props);
      }
      const userHasInteractedWithStatus = this.d.value >= 3;
      const targetWindow = getWindow(editor?.getContainerDomNode());
      const node = targetWindow.document.querySelector(".monaco-workbench .statusbar DIV#status\\.languageStatus A>SPAN.codicon");
      const container2 = targetWindow.document.querySelector(".monaco-workbench .statusbar DIV#status\\.languageStatus");
      if ($Uj(node) && container2) {
        const _wiggle = "wiggle";
        const _flash = "flash";
        if (!isOneBusy) {
          node.classList.toggle(_wiggle, showSeverity || !userHasInteractedWithStatus);
          this.j.add($_i(node, "animationend", (_e) => node.classList.remove(_wiggle)));
          container2.classList.toggle(_flash, showSeverity);
          this.j.add($_i(container2, "animationend", (_e) => container2.classList.remove(_flash)));
        } else {
          node.classList.remove(_wiggle);
          container2.classList.remove(_flash);
        }
      }
      if (!userHasInteractedWithStatus) {
        const hoverTarget = targetWindow.document.querySelector(".monaco-workbench .context-view");
        if ($Uj(hoverTarget)) {
          const observer = new MutationObserver(() => {
            if (targetWindow.document.contains(element)) {
              this.d.increment();
              observer.disconnect();
            }
          });
          observer.observe(hoverTarget, { childList: true, subtree: true });
          this.j.add($1c(() => observer.disconnect()));
        }
      }
    }
    const newDedicatedEntries = /* @__PURE__ */ new Map();
    for (const status of model.dedicated) {
      const props = LanguageStatus_1.B(status);
      let entry = this.i.get(status.id);
      if (!entry) {
        entry = this.l.addEntry(props, status.id, 1, {
          id: "status.editor.mode",
          alignment: 1
          /* StatusbarAlignment.RIGHT */
        });
      } else {
        entry.update(props);
        this.i.delete(status.id);
      }
      newDedicatedEntries.set(status.id, entry);
    }
    $Xc(this.i.values());
    this.i = newDedicatedEntries;
  }
  w(status, showSeverity, isPinned, store) {
    const parent = document.createElement("div");
    parent.classList.add("hover-language-status");
    const severity = document.createElement("div");
    severity.classList.add("severity", `sev${status.severity}`);
    severity.classList.toggle("show", showSeverity);
    const severityText = LanguageStatus_1.y(status.severity);
    $bk(severity, ...$B1(severityText));
    parent.appendChild(severity);
    const element = document.createElement("div");
    element.classList.add("element");
    parent.appendChild(element);
    const left = document.createElement("div");
    left.classList.add("left");
    element.appendChild(left);
    const label3 = document.createElement("span");
    label3.classList.add("label");
    const labelValue = typeof status.label === "string" ? status.label : status.label.value;
    $bk(label3, ...$B1(computeText(labelValue, status.busy)));
    left.appendChild(label3);
    const detail2 = document.createElement("span");
    detail2.classList.add("detail");
    this.z(detail2, status.detail, store);
    left.appendChild(detail2);
    const right = document.createElement("div");
    right.classList.add("right");
    element.appendChild(right);
    const { command: command4 } = status;
    if (command4) {
      store.add(new Link2(right, {
        label: command4.title,
        title: command4.tooltip,
        href: URI.from({
          scheme: "command",
          path: command4.id,
          query: command4.arguments && JSON.stringify(command4.arguments)
        }).toString()
      }, { hoverDelegate: $7$ }, this.o, this.p));
    }
    const actionBar = new $LZ(right, { hoverDelegate: $7$ });
    const actionLabel = isPinned ? localize(7697, null) : localize(7698, null);
    actionBar.setAriaLabel(actionLabel);
    store.add(actionBar);
    let action;
    if (!isPinned) {
      action = new $Um("pin", actionLabel, ThemeIcon.asClassName($6l.pin), true, () => {
        this.f.add(status.id);
        this.l.updateEntryVisibility(status.id, true);
        this.v();
        this.t();
      });
    } else {
      action = new $Um("unpin", actionLabel, ThemeIcon.asClassName($6l.pinned), true, () => {
        this.f.delete(status.id);
        this.l.updateEntryVisibility(status.id, false);
        this.v();
        this.t();
      });
    }
    actionBar.push(action, { icon: true, label: false });
    store.add(action);
    return parent;
  }
  static x(sev) {
    switch (sev) {
      case severity_default.Error:
        return "$(bracket-error)";
      case severity_default.Warning:
        return "$(bracket-dot)";
      default:
        return "$(bracket)";
    }
  }
  static y(sev) {
    switch (sev) {
      case severity_default.Error:
        return "$(error)";
      case severity_default.Warning:
        return "$(info)";
      default:
        return "$(check)";
    }
  }
  z(target, text2, store) {
    for (const node of $U3(text2).nodes) {
      if (typeof node === "string") {
        const parts = $B1(node);
        $bk(target, ...parts);
      } else {
        store.add(new Link2(target, node, void 0, this.o, this.p));
      }
    }
  }
  static A(status) {
    if (status.accessibilityInfo) {
      return status.accessibilityInfo;
    }
    const textValue = typeof status.label === "string" ? status.label : status.label.value;
    if (status.detail) {
      return { label: localize(7699, null, textValue, status.detail) };
    } else {
      return { label: localize(7700, null, textValue) };
    }
  }
  // ---
  static B(item) {
    let kind;
    if (item.severity === severity_default.Warning) {
      kind = "warning";
    } else if (item.severity === severity_default.Error) {
      kind = "error";
    }
    const textValue = typeof item.label === "string" ? item.label : item.label.shortValue;
    return {
      name: localize(7701, null, item.name),
      text: computeText(textValue, item.busy),
      ariaLabel: LanguageStatus_1.A(item).label,
      role: item.accessibilityInfo?.role,
      tooltip: item.command?.tooltip || new $bm(item.detail, { isTrusted: true, supportThemeIcons: true }),
      kind,
      command: item.command
    };
  }
};
LanguageStatus = LanguageStatus_1 = __decorate([
  __param(0, $FS),
  __param(1, $$qb),
  __param(2, $mJ),
  __param(3, $5$),
  __param(4, $O4),
  __param(5, $jv)
], LanguageStatus);
var $Ojc = class extends $gJ {
  constructor() {
    super({
      id: "editor.inlayHints.Reset",
      title: localize2(7702, "Reset Language Status Interaction Counter"),
      category: $qn.View,
      f1: true
    });
  }
  run(accessor) {
    accessor.get($jv).remove(
      "languageStatus.interactCount",
      0
      /* StorageScope.PROFILE */
    );
  }
};
function computeText(text2, loading) {
  return $Lf([text2 !== "" && text2, loading && "$(loading~spin)"], "\xA0\xA0");
}

// out-build/vs/workbench/contrib/languageStatus/browser/languageStatus.contribution.js
$PL(
  $Njc.Id,
  $Njc,
  3
  /* WorkbenchPhase.AfterRestored */
);
$hJ($Ojc);

// out-build/vs/workbench/contrib/authentication/browser/actions/signOutOfAccountAction.js
var $Pjc = class extends $gJ {
  constructor() {
    super({
      id: "_signOutOfAccount",
      title: localize(4517, null),
      f1: false
    });
  }
  async run(accessor, { providerId, accountLabel }) {
    const authenticationService = accessor.get($xS);
    const authenticationUsageService = accessor.get($RCb);
    const authenticationAccessService = accessor.get($V4);
    const dialogService = accessor.get($Yv);
    if (!providerId || !accountLabel) {
      throw new Error("Invalid arguments. Expected: { providerId: string; accountLabel: string }");
    }
    const allSessions = await authenticationService.getSessions(providerId);
    const sessions = allSessions.filter((s) => s.account.label === accountLabel);
    const accountUsages = authenticationUsageService.readAccountUsages(providerId, accountLabel);
    const { confirmed } = await dialogService.confirm({
      type: severity_default.Info,
      message: accountUsages.length ? localize(4518, null, accountLabel, accountUsages.map((usage) => usage.extensionName).join("\n")) : localize(4519, null, accountLabel),
      primaryButton: localize(4520, null)
    });
    if (confirmed) {
      const removeSessionPromises = sessions.map((session) => authenticationService.removeSession(providerId, session.id));
      await Promise.all(removeSessionPromises);
      authenticationUsageService.removeAccountUsage(providerId, accountLabel);
      authenticationAccessService.removeAllowedExtensions(providerId, accountLabel);
    }
  }
};

// out-build/vs/workbench/contrib/authentication/browser/actions/manageTrustedExtensionsForAccountAction.js
var $Qjc = class extends $gJ {
  constructor() {
    super({
      id: "_manageTrustedExtensionsForAccount",
      title: localize2(4515, "Manage Trusted Extensions For Account"),
      category: localize2(4516, "Accounts"),
      f1: true
    });
  }
  run(accessor, options3) {
    const instantiationService = accessor.get($Pk);
    return instantiationService.createInstance(ManageTrustedExtensionsForAccountActionImpl).run(options3);
  }
};
var ManageTrustedExtensionsForAccountActionImpl = class ManageTrustedExtensionsForAccountActionImpl2 {
  constructor(c, d, f, g, h3, j, k, l) {
    this.c = c;
    this.d = d;
    this.f = f;
    this.g = g;
    this.h = h3;
    this.j = j;
    this.k = k;
    this.l = l;
  }
  async run(options3) {
    const { providerId, accountLabel } = await this.m(options3?.providerId, options3?.accountLabel);
    if (!providerId || !accountLabel) {
      return;
    }
    const items = await this.n(providerId, accountLabel);
    if (!items.length) {
      return;
    }
    const disposables = new $2c();
    const picker = this.p(disposables, providerId, accountLabel);
    picker.items = items;
    picker.selectedItems = items.filter((i2) => i2.type !== "separator" && !!i2.picked);
    picker.show();
  }
  async m(providerId, accountLabel) {
    if (!providerId || !accountLabel) {
      const accounts = new Array();
      for (const id2 of this.h.getProviderIds()) {
        const providerLabel = this.h.getProvider(id2).label;
        const sessions = await this.h.getSessions(id2);
        const uniqueAccountLabels = /* @__PURE__ */ new Set();
        for (const session of sessions) {
          if (!uniqueAccountLabels.has(session.account.label)) {
            uniqueAccountLabels.add(session.account.label);
            accounts.push({ providerId: id2, providerLabel, accountLabel: session.account.label });
          }
        }
      }
      const pick = await this.g.pick(accounts.map((account) => ({
        providerId: account.providerId,
        label: account.accountLabel,
        description: account.providerLabel
      })), {
        placeHolder: localize(4505, null),
        matchOnDescription: true
      });
      if (pick) {
        providerId = pick.providerId;
        accountLabel = pick.label;
      } else {
        return { providerId: void 0, accountLabel: void 0 };
      }
    }
    return { providerId, accountLabel };
  }
  async n(providerId, accountLabel) {
    let allowedExtensions = this.k.readAllowedExtensions(providerId, accountLabel);
    const resolvedExtensions = await Promise.all(allowedExtensions.map((ext) => this.d.getExtension(ext.id)));
    allowedExtensions = resolvedExtensions.map((ext, i2) => ext ? allowedExtensions[i2] : void 0).filter((ext) => !!ext);
    const trustedExtensionAuthAccess = this.c.trustedExtensionAuthAccess;
    const trustedExtensionIds = (
      // Case 1: trustedExtensionAuthAccess is an array
      Array.isArray(trustedExtensionAuthAccess) ? trustedExtensionAuthAccess : typeof trustedExtensionAuthAccess === "object" ? trustedExtensionAuthAccess[providerId] ?? [] : []
    );
    for (const extensionId of trustedExtensionIds) {
      const allowedExtension = allowedExtensions.find((ext) => ext.id === extensionId);
      if (!allowedExtension) {
        const extension = await this.d.getExtension(extensionId);
        if (extension) {
          allowedExtensions.push({
            id: extensionId,
            name: extension.displayName || extension.name,
            allowed: true,
            trusted: true
          });
        }
      } else {
        allowedExtension.allowed = true;
        allowedExtension.trusted = true;
      }
    }
    if (!allowedExtensions.length) {
      this.f.info(localize(4506, null));
      return [];
    }
    const usages = this.j.readAccountUsages(providerId, accountLabel);
    const trustedExtensions = [];
    const otherExtensions = [];
    for (const extension of allowedExtensions) {
      const usage = usages.find((usage2) => extension.id === usage2.extensionId);
      extension.lastUsed = usage?.lastUsed;
      if (extension.trusted) {
        trustedExtensions.push(extension);
      } else {
        otherExtensions.push(extension);
      }
    }
    const sortByLastUsed = (a, b) => (b.lastUsed || 0) - (a.lastUsed || 0);
    const items = [
      ...otherExtensions.sort(sortByLastUsed).map(this.o),
      { type: "separator", label: localize(4507, null) },
      ...trustedExtensions.sort(sortByLastUsed).map(this.o)
    ];
    return items;
  }
  o(extension) {
    const lastUsed = extension.lastUsed;
    const description = lastUsed ? localize(4508, null, $Qu(lastUsed, true)) : localize(4509, null);
    let tooltip;
    let disabled;
    if (extension.trusted) {
      tooltip = localize(4510, null);
      disabled = true;
    }
    return {
      label: extension.name,
      extension,
      description,
      tooltip,
      disabled,
      buttons: [{
        tooltip: localize(4511, null),
        iconClass: ThemeIcon.asClassName($6l.settingsGear)
      }],
      picked: extension.allowed === void 0 || extension.allowed
    };
  }
  p(disposableStore, providerId, accountLabel) {
    const quickPick = disposableStore.add(this.g.createQuickPick({ useSeparators: true }));
    quickPick.canSelectMany = true;
    quickPick.customButton = true;
    quickPick.customLabel = localize(4512, null);
    quickPick.title = localize(4513, null);
    quickPick.placeholder = localize(4514, null);
    disposableStore.add(quickPick.onDidAccept(() => {
      const updatedAllowedList = quickPick.items.filter((item) => item.type !== "separator").map((i2) => i2.extension);
      const allowedExtensionsSet = new Set(quickPick.selectedItems.map((i2) => i2.extension));
      updatedAllowedList.forEach((extension) => {
        extension.allowed = allowedExtensionsSet.has(extension);
      });
      this.k.updateAllowedExtensions(providerId, accountLabel, updatedAllowedList);
      quickPick.hide();
    }));
    disposableStore.add(quickPick.onDidHide(() => {
      disposableStore.dispose();
    }));
    disposableStore.add(quickPick.onDidCustom(() => {
      quickPick.hide();
    }));
    disposableStore.add(quickPick.onDidTriggerItemButton((e) => this.l.executeCommand("_manageAccountPreferencesForExtension", e.item.extension.id, providerId)));
    return quickPick;
  }
};
ManageTrustedExtensionsForAccountActionImpl = __decorate([
  __param(0, $Vu),
  __param(1, $wN),
  __param(2, $Yv),
  __param(3, $1M),
  __param(4, $xS),
  __param(5, $RCb),
  __param(6, $V4),
  __param(7, $sn)
], ManageTrustedExtensionsForAccountActionImpl);

// out-build/vs/workbench/contrib/authentication/browser/actions/manageAccountPreferencesForExtensionAction.js
var $Rjc = class extends $gJ {
  constructor() {
    super({
      id: "_manageAccountPreferencesForExtension",
      title: localize2(4503, "Manage Extension Account Preferences"),
      category: localize2(4504, "Accounts"),
      f1: false
    });
  }
  run(accessor, extensionId, providerId) {
    return accessor.get($Pk).createInstance(ManageAccountPreferenceForExtensionActionImpl).run(extensionId, providerId);
  }
};
var ManageAccountPreferenceForExtensionActionImpl = class ManageAccountPreferenceForExtensionActionImpl2 {
  constructor(c, d, f, g, h3, i2, j) {
    this.c = c;
    this.d = d;
    this.f = f;
    this.g = g;
    this.h = h3;
    this.i = i2;
    this.j = j;
  }
  async run(extensionId, providerId) {
    if (!extensionId) {
      return;
    }
    const extension = await this.i.getExtension(extensionId);
    if (!extension) {
      throw new Error(`No extension with id ${extensionId}`);
    }
    const providerIds = new Array();
    const providerIdToAccounts = /* @__PURE__ */ new Map();
    if (providerId) {
      providerIds.push(providerId);
      providerIdToAccounts.set(providerId, await this.c.getAccounts(providerId));
    } else {
      for (const providerId2 of this.c.getProviderIds()) {
        if (providerId2.startsWith($wS)) {
          continue;
        }
        const accounts2 = await this.c.getAccounts(providerId2);
        for (const account of accounts2) {
          const usage = this.g.readAccountUsages(providerId2, account.label).find((u) => $5z.equals(u.extensionId, extensionId));
          if (usage) {
            providerIds.push(providerId2);
            providerIdToAccounts.set(providerId2, accounts2);
            break;
          }
        }
      }
    }
    let chosenProviderId = providerIds[0];
    if (providerIds.length > 1) {
      const result = await this.d.pick(providerIds.map((providerId2) => ({
        label: this.c.getProvider(providerId2).label,
        id: providerId2
      })), {
        placeHolder: localize(4495, null),
        title: localize(4496, null)
      });
      chosenProviderId = result?.id;
    }
    if (!chosenProviderId) {
      await this.f.info(localize(4497, null));
      return;
    }
    const currentAccountNamePreference = this.h.getAccountPreference(extensionId, chosenProviderId);
    const accounts = providerIdToAccounts.get(chosenProviderId);
    const items = this.l(accounts, chosenProviderId, currentAccountNamePreference);
    const provider = this.c.getProvider(chosenProviderId);
    if (provider.supportsMultipleAccounts) {
      const lastUsedScopes = accounts.flatMap((account) => this.g.readAccountUsages(chosenProviderId, account.label).find((u) => $5z.equals(u.extensionId, extensionId))).filter((usage) => !!usage).sort((a, b) => b.lastUsed - a.lastUsed)?.[0]?.scopes;
      if (lastUsedScopes) {
        items.push({ type: "separator" });
        items.push({
          providerId: chosenProviderId,
          scopes: lastUsedScopes,
          label: localize(4498, null)
        });
      }
    }
    const disposables = new $2c();
    const picker = this.k(disposables, extensionId, extension.displayName ?? extension.name, provider.label);
    if (items.length === 0) {
      disposables.add(this.m(picker));
      return;
    }
    picker.items = items;
    picker.show();
  }
  k(disposableStore, extensionId, extensionLabel, providerLabel) {
    const picker = disposableStore.add(this.d.createQuickPick({ useSeparators: true }));
    disposableStore.add(picker.onDidHide(() => {
      disposableStore.dispose();
    }));
    picker.placeholder = localize(4499, null, extensionLabel, providerLabel);
    picker.title = localize(4500, null, extensionLabel);
    picker.sortByLabel = false;
    disposableStore.add(picker.onDidAccept(async () => {
      picker.hide();
      await this.n(extensionId, picker.selectedItems);
    }));
    return picker;
  }
  l(accounts, providerId, currentAccountNamePreference) {
    return accounts.map((a) => currentAccountNamePreference === a.label ? {
      label: a.label,
      account: a,
      providerId,
      description: localize(4501, null),
      picked: true
    } : {
      label: a.label,
      account: a,
      providerId
    });
  }
  m(picker) {
    picker.validationMessage = localize(4502, null);
    picker.buttons = [this.d.backButton];
    picker.show();
    return Event2.filter(picker.onDidTriggerButton, (e) => e === this.d.backButton)(() => this.run());
  }
  async n(extensionId, selectedItems) {
    for (const item of selectedItems) {
      let account;
      if (!item.account) {
        try {
          const session = await this.c.createSession(item.providerId, item.scopes);
          account = session.account;
        } catch (e) {
          this.j.error(e);
          continue;
        }
      } else {
        account = item.account;
      }
      const providerId = item.providerId;
      const currentAccountName = this.h.getAccountPreference(extensionId, providerId);
      if (currentAccountName === account.label) {
        continue;
      }
      this.h.updateAccountPreference(extensionId, providerId, account);
    }
  }
};
ManageAccountPreferenceForExtensionActionImpl = __decorate([
  __param(0, $xS),
  __param(1, $1M),
  __param(2, $Yv),
  __param(3, $RCb),
  __param(4, $yS),
  __param(5, $wN),
  __param(6, $wn)
], ManageAccountPreferenceForExtensionActionImpl);

// out-build/vs/workbench/contrib/authentication/browser/authentication.contribution.js
var codeExchangeProxyCommand = $tn.registerCommand("workbench.getCodeExchangeProxyEndpoints", function(accessor, _) {
  const environmentService = accessor.get($M4);
  return environmentService.options?.codeExchangeProxyEndpoints;
});
var AuthenticationDataRenderer = class extends $3c {
  constructor() {
    super(...arguments);
    this.type = "table";
  }
  shouldRender(manifest) {
    return !!manifest.contributes?.authentication;
  }
  render(manifest) {
    const authentication = manifest.contributes?.authentication || [];
    if (!authentication.length) {
      return { data: { headers: [], rows: [] }, dispose: () => {
      } };
    }
    const headers = [
      localize(4521, null),
      localize(4522, null)
    ];
    const rows = authentication.sort((a, b) => a.label.localeCompare(b.label)).map((auth) => {
      return [
        auth.label,
        auth.id
      ];
    });
    return {
      data: {
        headers,
        rows
      },
      dispose: () => {
      }
    };
  }
};
var extensionFeature = $Wn.as(Extensions3.ExtensionFeaturesRegistry).registerExtensionFeature({
  id: "authentication",
  label: localize(4523, null),
  access: {
    canToggle: false
  },
  renderer: new $Nk(AuthenticationDataRenderer)
});
var AuthenticationContribution = class AuthenticationContribution2 extends $3c {
  static {
    this.ID = "workbench.contrib.authentication";
  }
  constructor(f) {
    super();
    this.f = f;
    this.c = $dJ.appendMenuItem($bJ.AccountsContext, {
      command: {
        id: "noAuthenticationProviders",
        title: localize(4524, null),
        precondition: $7m.false()
      }
    });
    this.B(codeExchangeProxyCommand);
    this.B(extensionFeature);
    if (f.getProviderIds().length) {
      this.j();
    }
    this.g();
    this.h();
  }
  g() {
    this.B(this.f.onDidRegisterAuthenticationProvider((_e) => {
      this.j();
    }));
    this.B(this.f.onDidUnregisterAuthenticationProvider((_e) => {
      if (!this.f.getProviderIds().length) {
        this.c = $dJ.appendMenuItem($bJ.AccountsContext, {
          command: {
            id: "noAuthenticationProviders",
            title: localize(4525, null),
            precondition: $7m.false()
          }
        });
      }
    }));
  }
  h() {
    this.B($hJ($Pjc));
    this.B($hJ($Qjc));
    this.B($hJ($Rjc));
  }
  j() {
    this.c?.dispose();
    this.c = void 0;
  }
};
AuthenticationContribution = __decorate([
  __param(0, $xS)
], AuthenticationContribution);
var AuthenticationUsageContribution = class AuthenticationUsageContribution2 {
  static {
    this.ID = "workbench.contrib.authenticationUsage";
  }
  constructor(c) {
    this.c = c;
    this.d();
  }
  async d() {
    await this.c.initializeExtensionUsageCache();
  }
};
AuthenticationUsageContribution = __decorate([
  __param(0, $RCb)
], AuthenticationUsageContribution);
$PL(
  AuthenticationContribution.ID,
  AuthenticationContribution,
  3
  /* WorkbenchPhase.AfterRestored */
);
$PL(
  AuthenticationUsageContribution.ID,
  AuthenticationUsageContribution,
  4
  /* WorkbenchPhase.Eventually */
);

// out-build/vs/workbench/contrib/userDataSync/browser/userDataSyncConflictsView.js
var $Sjc = class $Sjc2 extends $gUb {
  constructor(options3, ab, keybindingService, contextMenuService, configurationService, contextKeyService, viewDescriptorService, instantiationService, openerService, themeService, telemetryService, notificationService, hoverService, sb, ac, bc, cc, accessibleViewVisibilityService) {
    super(options3, keybindingService, contextMenuService, configurationService, contextKeyService, viewDescriptorService, instantiationService, openerService, themeService, telemetryService, notificationService, hoverService, accessibleViewVisibilityService);
    this.ab = ab;
    this.sb = sb;
    this.ac = ac;
    this.bc = bc;
    this.cc = cc;
    this.B(this.sb.onDidChangeConflicts(() => this.f.refresh()));
    this.gc();
  }
  n(container2) {
    super.n($bk(container2, $("")));
    const that = this;
    this.f.message = localize(11749, null);
    this.f.dataProvider = { getChildren() {
      return that.ec();
    } };
  }
  async ec() {
    const roots = [];
    const conflictResources = this.sb.conflicts.map((conflict) => conflict.conflicts.map((resourcePreview) => ({ ...resourcePreview, syncResource: conflict.syncResource, profile: conflict.profile }))).flat().sort((a, b) => a.profile.id === b.profile.id ? 0 : a.profile.isDefault ? -1 : b.profile.isDefault ? 1 : a.profile.name.localeCompare(b.profile.name));
    const conflictResourcesByProfile = [];
    for (const previewResource of conflictResources) {
      let result = conflictResourcesByProfile[conflictResourcesByProfile.length - 1]?.[0].id === previewResource.profile.id ? conflictResourcesByProfile[conflictResourcesByProfile.length - 1][1] : void 0;
      if (!result) {
        conflictResourcesByProfile.push([previewResource.profile, result = []]);
      }
      result.push(previewResource);
    }
    for (const [profile, resources] of conflictResourcesByProfile) {
      const children = [];
      for (const resource of resources) {
        const handle2 = JSON.stringify(resource);
        const treeItem = {
          handle: handle2,
          resourceUri: resource.remoteResource,
          label: { label: $sh(resource.remoteResource), strikethrough: resource.mergeState === "accepted" && (resource.localChange === 3 || resource.remoteChange === 3) },
          description: $pXb(resource.syncResource),
          collapsibleState: TreeItemCollapsibleState2.None,
          command: { id: `workbench.actions.sync.openConflicts`, title: "", arguments: [{ $treeViewId: "", $treeItemHandle: handle2 }] },
          contextValue: `sync-conflict-resource`
        };
        children.push(treeItem);
      }
      roots.push({
        handle: profile.id,
        label: { label: profile.name },
        collapsibleState: TreeItemCollapsibleState2.Expanded,
        children
      });
    }
    return conflictResourcesByProfile.length === 1 && conflictResourcesByProfile[0][0].isDefault ? roots[0].children ?? [] : roots;
  }
  fc(handle2) {
    const parsed = JSON.parse(handle2);
    return {
      syncResource: parsed.syncResource,
      profile: $ss(parsed.profile, this.cc.profilesHome.scheme),
      localResource: URI.revive(parsed.localResource),
      remoteResource: URI.revive(parsed.remoteResource),
      baseResource: URI.revive(parsed.baseResource),
      previewResource: URI.revive(parsed.previewResource),
      acceptedResource: URI.revive(parsed.acceptedResource),
      localChange: parsed.localChange,
      remoteChange: parsed.remoteChange,
      mergeState: parsed.mergeState
    };
  }
  gc() {
    const that = this;
    this.B($hJ(class OpenConflictsAction extends $gJ {
      constructor() {
        super({
          id: `workbench.actions.sync.openConflicts`,
          title: localize(11750, null)
        });
      }
      async run(accessor, handle2) {
        const conflict = that.fc(handle2.$treeItemHandle);
        return that.open(conflict);
      }
    }));
    this.B($hJ(class AcceptRemoteAction extends $gJ {
      constructor() {
        super({
          id: `workbench.actions.sync.acceptRemote`,
          title: localize(11751, null),
          icon: $6l.cloudDownload,
          menu: {
            id: $bJ.ViewItemContext,
            when: $7m.and($7m.equals("view", $BXb), $7m.equals("viewItem", "sync-conflict-resource")),
            group: "inline",
            order: 1
          }
        });
      }
      async run(accessor, handle2) {
        const conflict = that.fc(handle2.$treeItemHandle);
        await that.ac.accept({ syncResource: conflict.syncResource, profile: conflict.profile }, conflict.remoteResource, void 0, that.bc.isEnabled());
      }
    }));
    this.B($hJ(class AcceptLocalAction extends $gJ {
      constructor() {
        super({
          id: `workbench.actions.sync.acceptLocal`,
          title: localize(11752, null),
          icon: $6l.cloudUpload,
          menu: {
            id: $bJ.ViewItemContext,
            when: $7m.and($7m.equals("view", $BXb), $7m.equals("viewItem", "sync-conflict-resource")),
            group: "inline",
            order: 2
          }
        });
      }
      async run(accessor, handle2) {
        const conflict = that.fc(handle2.$treeItemHandle);
        await that.ac.accept({ syncResource: conflict.syncResource, profile: conflict.profile }, conflict.localResource, void 0, that.bc.isEnabled());
      }
    }));
  }
  async open(conflictToOpen) {
    if (!this.sb.conflicts.some(({ conflicts }) => conflicts.some(({ localResource }) => $oh(localResource, conflictToOpen.localResource)))) {
      return;
    }
    const remoteResourceName = localize(11753, null, $sh(conflictToOpen.remoteResource));
    const localResourceName = localize(11754, null, $sh(conflictToOpen.remoteResource));
    await this.ab.openEditor({
      input1: { resource: conflictToOpen.remoteResource, label: localize(11755, null), description: remoteResourceName },
      input2: { resource: conflictToOpen.localResource, label: localize(11756, null), description: localResourceName },
      base: { resource: conflictToOpen.baseResource },
      result: { resource: conflictToOpen.previewResource },
      options: {
        preserveFocus: true,
        revealIfVisible: true,
        pinned: true,
        override: $1K.id
      }
    });
    return;
  }
};
$Sjc = __decorate([
  __param(1, $mJ),
  __param(2, $Ty),
  __param(3, $50),
  __param(4, $kl),
  __param(5, $on),
  __param(6, $$M),
  __param(7, $Pk),
  __param(8, $O4),
  __param(9, $gs),
  __param(10, $zv),
  __param(11, $PJ),
  __param(12, $5$),
  __param(13, $7Bb),
  __param(14, $oXb),
  __param(15, $6Bb),
  __param(16, $rs),
  __param(17, $9ob)
], $Sjc);

// out-build/vs/workbench/contrib/userDataSync/browser/userDataSyncViews.js
var $Tjc = class $Tjc2 extends $3c {
  constructor(container2, f, g, h3, j) {
    super();
    this.f = f;
    this.g = g;
    this.h = h3;
    this.j = j;
    this.n(container2);
  }
  n(container2) {
    this.r(container2);
    this.t(container2, true);
    this.s(container2);
    this.t(container2, false);
    this.y(container2);
    this.u(container2);
  }
  r(container2) {
    const viewsRegistry8 = $Wn.as(Extensions5.ViewsRegistry);
    const viewName = localize2(11784, "Conflicts");
    const viewDescriptor3 = {
      id: $BXb,
      name: viewName,
      ctorDescriptor: new $Nk($Sjc),
      when: $7m.and($wXb, $xXb),
      canToggleVisibility: false,
      canMoveView: false,
      treeView: this.f.createInstance($jUb, $BXb, viewName.value),
      collapsed: false,
      order: 100
    };
    viewsRegistry8.registerViews([viewDescriptor3], container2);
  }
  s(container2) {
    const id2 = `workbench.views.sync.machines`;
    const name = localize2(11785, "Synced Machines");
    const treeView = this.f.createInstance($jUb, id2, name.value);
    const dataProvider = this.f.createInstance(UserDataSyncMachinesViewDataProvider, treeView);
    treeView.showRefreshAction = true;
    treeView.canSelectMany = true;
    treeView.dataProvider = dataProvider;
    this.B(Event2.any(this.h.onDidChange, this.j.onDidResetRemote)(() => treeView.refresh()));
    const viewsRegistry8 = $Wn.as(Extensions5.ViewsRegistry);
    const viewDescriptor3 = {
      id: id2,
      name,
      ctorDescriptor: new $Nk($gUb),
      when: $7m.and($sXb.notEqualsTo(
        "uninitialized"
        /* SyncStatus.Uninitialized */
      ), $uXb.isEqualTo(
        "available"
        /* AccountStatus.Available */
      ), $vXb),
      canToggleVisibility: true,
      canMoveView: false,
      treeView,
      collapsed: false,
      order: 300
    };
    viewsRegistry8.registerViews([viewDescriptor3], container2);
    this.B($hJ(class extends $gJ {
      constructor() {
        super({
          id: `workbench.actions.sync.editMachineName`,
          title: localize(11757, null),
          icon: $6l.edit,
          menu: {
            id: $bJ.ViewItemContext,
            when: $7m.and($7m.equals("view", id2)),
            group: "inline"
          }
        });
      }
      async run(accessor, handle2) {
        const changed = await dataProvider.rename(handle2.$treeItemHandle);
        if (changed) {
          await treeView.refresh();
        }
      }
    }));
    this.B($hJ(class extends $gJ {
      constructor() {
        super({
          id: `workbench.actions.sync.turnOffSyncOnMachine`,
          title: localize(11758, null),
          menu: {
            id: $bJ.ViewItemContext,
            when: $7m.and($7m.equals("view", id2), $7m.equals("viewItem", "sync-machine"))
          }
        });
      }
      async run(accessor, handle2, selected) {
        if (await dataProvider.disable((selected || [handle2]).map((handle3) => handle3.$treeItemHandle))) {
          await treeView.refresh();
        }
      }
    }));
  }
  t(container2, remote) {
    const id2 = `workbench.views.sync.${remote ? "remote" : "local"}Activity`;
    const name = remote ? localize2(11786, "Sync Activity (Remote)") : localize2(11787, "Sync Activity (Local)");
    const treeView = this.f.createInstance($jUb, id2, name.value);
    treeView.showCollapseAllAction = true;
    treeView.showRefreshAction = true;
    treeView.dataProvider = remote ? this.f.createInstance(RemoteUserDataSyncActivityViewDataProvider) : this.f.createInstance(LocalUserDataSyncActivityViewDataProvider);
    this.B(Event2.any(this.g.onDidChangeResourceEnablement, this.g.onDidChangeEnablement, this.j.onDidResetLocal, this.j.onDidResetRemote)(() => treeView.refresh()));
    const viewsRegistry8 = $Wn.as(Extensions5.ViewsRegistry);
    const viewDescriptor3 = {
      id: id2,
      name,
      ctorDescriptor: new $Nk($gUb),
      when: $7m.and($sXb.notEqualsTo(
        "uninitialized"
        /* SyncStatus.Uninitialized */
      ), $uXb.isEqualTo(
        "available"
        /* AccountStatus.Available */
      ), $vXb),
      canToggleVisibility: true,
      canMoveView: false,
      treeView,
      collapsed: false,
      order: remote ? 200 : 400,
      hideByDefault: !remote
    };
    viewsRegistry8.registerViews([viewDescriptor3], container2);
    this.w(id2);
  }
  u(container2) {
    const id2 = `workbench.views.sync.externalActivity`;
    const name = localize2(11788, "Sync Activity (Developer)");
    const dataProvider = this.f.createInstance(ExtractedUserDataSyncActivityViewDataProvider, void 0);
    const treeView = this.f.createInstance($jUb, id2, name.value);
    treeView.showCollapseAllAction = false;
    treeView.showRefreshAction = false;
    treeView.dataProvider = dataProvider;
    const viewsRegistry8 = $Wn.as(Extensions5.ViewsRegistry);
    const viewDescriptor3 = {
      id: id2,
      name,
      ctorDescriptor: new $Nk($gUb),
      when: $vXb,
      canToggleVisibility: true,
      canMoveView: false,
      treeView,
      collapsed: false,
      hideByDefault: false
    };
    viewsRegistry8.registerViews([viewDescriptor3], container2);
    this.B($hJ(class extends $gJ {
      constructor() {
        super({
          id: `workbench.actions.sync.loadActivity`,
          title: localize(11759, null),
          icon: $6l.cloudUpload,
          menu: {
            id: $bJ.ViewTitle,
            when: $7m.equals("view", id2),
            group: "navigation"
          }
        });
      }
      async run(accessor) {
        const fileDialogService = accessor.get($1v);
        const result = await fileDialogService.showOpenDialog({
          title: localize(11760, null),
          canSelectFiles: true,
          canSelectFolders: true,
          canSelectMany: false
        });
        if (!result?.[0]) {
          return;
        }
        dataProvider.activityDataResource = result[0];
        await treeView.refresh();
      }
    }));
  }
  w(viewId) {
    this.B($hJ(class extends $gJ {
      constructor() {
        super({
          id: `workbench.actions.sync.${viewId}.resolveResource`,
          title: localize(11761, null),
          menu: {
            id: $bJ.ViewItemContext,
            when: $7m.and($7m.equals("view", viewId), $7m.regex("viewItem", /sync-resource-.*/i))
          }
        });
      }
      async run(accessor, handle2) {
        const { resource } = JSON.parse(handle2.$treeItemHandle);
        const editorService = accessor.get($mJ);
        await editorService.openEditor({ resource: URI.parse(resource), options: { pinned: true } });
      }
    }));
    this.B($hJ(class extends $gJ {
      constructor() {
        super({
          id: `workbench.actions.sync.${viewId}.compareWithLocal`,
          title: localize(11762, null),
          menu: {
            id: $bJ.ViewItemContext,
            when: $7m.and($7m.equals("view", viewId), $7m.regex("viewItem", /sync-associatedResource-.*/i))
          }
        });
      }
      async run(accessor, handle2) {
        const commandService = accessor.get($sn);
        const { resource, comparableResource } = JSON.parse(handle2.$treeItemHandle);
        const remoteResource = URI.parse(resource);
        const localResource = URI.parse(comparableResource);
        return commandService.executeCommand($_ub, remoteResource, localResource, localize(11763, null, localize(11764, null, $sh(remoteResource)), localize(11765, null, $sh(localResource))), void 0);
      }
    }));
    this.B($hJ(class extends $gJ {
      constructor() {
        super({
          id: `workbench.actions.sync.${viewId}.replaceCurrent`,
          title: localize(11766, null),
          icon: $6l.discard,
          menu: {
            id: $bJ.ViewItemContext,
            when: $7m.and($7m.equals("view", viewId), $7m.regex("viewItem", /sync-resource-.*/i), $7m.notEquals("viewItem", `sync-resource-${"profiles"}`)),
            group: "inline"
          }
        });
      }
      async run(accessor, handle2) {
        const dialogService = accessor.get($Yv);
        const userDataSyncService = accessor.get($7Bb);
        const { syncResourceHandle, syncResource } = JSON.parse(handle2.$treeItemHandle);
        const result = await dialogService.confirm({
          message: localize(11767, null, $pXb(syncResource)),
          type: "info",
          title: $qXb.value
        });
        if (result.confirmed) {
          return userDataSyncService.replace({ created: syncResourceHandle.created, uri: URI.revive(syncResourceHandle.uri) });
        }
      }
    }));
  }
  y(container2) {
    const id2 = `workbench.views.sync.troubleshoot`;
    const name = localize2(11789, "Troubleshoot");
    const treeView = this.f.createInstance($jUb, id2, name.value);
    const dataProvider = this.f.createInstance(UserDataSyncTroubleshootViewDataProvider);
    treeView.showRefreshAction = true;
    treeView.dataProvider = dataProvider;
    const viewsRegistry8 = $Wn.as(Extensions5.ViewsRegistry);
    const viewDescriptor3 = {
      id: id2,
      name,
      ctorDescriptor: new $Nk($gUb),
      when: $vXb,
      canToggleVisibility: true,
      canMoveView: false,
      treeView,
      collapsed: false,
      order: 500,
      hideByDefault: true
    };
    viewsRegistry8.registerViews([viewDescriptor3], container2);
  }
};
$Tjc = __decorate([
  __param(1, $Pk),
  __param(2, $6Bb),
  __param(3, $HBb),
  __param(4, $7Bb)
], $Tjc);
var UserDataSyncActivityViewDataProvider = class UserDataSyncActivityViewDataProvider2 {
  constructor(f, g, h3, i2, j, k) {
    this.f = f;
    this.g = g;
    this.h = h3;
    this.i = i2;
    this.j = j;
    this.k = k;
    this.d = /* @__PURE__ */ new Map();
  }
  async getChildren(element) {
    try {
      if (!element) {
        return await this.l();
      }
      if (element.profile || element.handle === this.k.defaultProfile.id) {
        let promise = this.d.get(element.handle);
        if (!promise) {
          this.d.set(element.handle, promise = this.o(element.profile));
        }
        return await promise;
      }
      if (element.syncResourceHandle) {
        return await this.n(element);
      }
      return [];
    } catch (error) {
      if (!(error instanceof $1Bb)) {
        error = $1Bb.toUserDataSyncError(error);
      }
      if (error instanceof $1Bb && error.code === "IncompatibleRemoteContent") {
        this.j.notify({
          severity: Severity2.Error,
          message: error.message,
          actions: {
            primary: [
              new $Um("reset", localize(11768, null), void 0, true, () => this.i.resetSyncedData())
            ]
          }
        });
      } else {
        this.j.error(error);
      }
      throw error;
    }
  }
  async l() {
    this.d.clear();
    const roots = [];
    const profiles2 = await this.q();
    if (profiles2.length) {
      const profileTreeItem = {
        handle: this.k.defaultProfile.id,
        label: { label: this.k.defaultProfile.name },
        collapsibleState: TreeItemCollapsibleState2.Expanded
      };
      roots.push(profileTreeItem);
    } else {
      const defaultSyncResourceHandles = await this.o();
      roots.push(...defaultSyncResourceHandles);
    }
    for (const profile of profiles2) {
      const profileTreeItem = {
        handle: profile.id,
        label: { label: profile.name },
        collapsibleState: TreeItemCollapsibleState2.Collapsed,
        profile
      };
      roots.push(profileTreeItem);
    }
    return roots;
  }
  async n(element) {
    const syncResourceHandle = element.syncResourceHandle;
    const associatedResources = await this.g.getAssociatedResources(syncResourceHandle);
    const previousAssociatedResources = syncResourceHandle.previous ? await this.g.getAssociatedResources(syncResourceHandle.previous) : [];
    return associatedResources.map(({ resource, comparableResource }) => {
      const handle2 = JSON.stringify({ resource: resource.toString(), comparableResource: comparableResource.toString() });
      const previousResource = previousAssociatedResources.find((previous) => $sh(previous.resource) === $sh(resource))?.resource;
      return {
        handle: handle2,
        collapsibleState: TreeItemCollapsibleState2.None,
        resourceUri: resource,
        command: previousResource ? {
          id: $_ub,
          title: "",
          arguments: [
            previousResource,
            resource,
            localize(11769, null, `${$sh(resource)} (${$Qu(syncResourceHandle.previous.created, true)})`, `${$sh(resource)} (${$Qu(syncResourceHandle.created, true)})`),
            void 0
          ]
        } : {
          id: $$ub,
          title: "",
          arguments: [resource, void 0, void 0]
        },
        contextValue: `sync-associatedResource-${syncResourceHandle.syncResource}`
      };
    });
  }
  async o(profile) {
    const treeItems = [];
    const result = await Promise.all($RBb.map(async (syncResource) => {
      const resourceHandles = await this.r(syncResource, profile);
      return resourceHandles.map((resourceHandle, index) => ({ ...resourceHandle, syncResource, previous: resourceHandles[index + 1] }));
    }));
    const syncResourceHandles = result.flat().sort((a, b) => b.created - a.created);
    for (const syncResourceHandle of syncResourceHandles) {
      const handle2 = JSON.stringify({ syncResourceHandle, syncResource: syncResourceHandle.syncResource });
      treeItems.push({
        handle: handle2,
        collapsibleState: TreeItemCollapsibleState2.Collapsed,
        label: { label: $pXb(syncResourceHandle.syncResource) },
        description: $Qu(syncResourceHandle.created, true),
        tooltip: new Date(syncResourceHandle.created).toLocaleString(),
        themeIcon: $js,
        syncResourceHandle,
        contextValue: `sync-resource-${syncResourceHandle.syncResource}`
      });
    }
    return treeItems;
  }
};
UserDataSyncActivityViewDataProvider = __decorate([
  __param(0, $7Bb),
  __param(1, $8Bb),
  __param(2, $9Bb),
  __param(3, $oXb),
  __param(4, $PJ),
  __param(5, $rs)
], UserDataSyncActivityViewDataProvider);
var LocalUserDataSyncActivityViewDataProvider = class extends UserDataSyncActivityViewDataProvider {
  r(syncResource, profile) {
    return this.g.getLocalSyncResourceHandles(syncResource, profile);
  }
  async q() {
    return this.k.profiles.filter((p) => !p.isDefault).map((p) => ({
      id: p.id,
      collection: p.id,
      name: p.name
    }));
  }
};
var RemoteUserDataSyncActivityViewDataProvider = class RemoteUserDataSyncActivityViewDataProvider2 extends UserDataSyncActivityViewDataProvider {
  constructor(userDataSyncService, userDataSyncResourceProviderService, userDataAutoSyncService, t, userDataSyncWorkbenchService, notificationService, userDataProfilesService) {
    super(userDataSyncService, userDataSyncResourceProviderService, userDataAutoSyncService, userDataSyncWorkbenchService, notificationService, userDataProfilesService);
    this.t = t;
  }
  async getChildren(element) {
    if (!element) {
      this.s = void 0;
    }
    return super.getChildren(element);
  }
  u() {
    if (this.s === void 0) {
      this.s = this.t.getMachines();
    }
    return this.s;
  }
  r(syncResource, profile) {
    return this.g.getRemoteSyncResourceHandles(syncResource, profile);
  }
  q() {
    return this.g.getRemoteSyncedProfiles();
  }
  async n(element) {
    const children = await super.n(element);
    if (children.length) {
      const machineId = await this.g.getMachineId(element.syncResourceHandle);
      if (machineId) {
        const machines = await this.u();
        const machine = machines.find(({ id: id2 }) => id2 === machineId);
        children[0].description = machine?.isCurrent ? localize(11770, null) : machine?.name;
      }
    }
    return children;
  }
};
RemoteUserDataSyncActivityViewDataProvider = __decorate([
  __param(0, $7Bb),
  __param(1, $8Bb),
  __param(2, $9Bb),
  __param(3, $HBb),
  __param(4, $oXb),
  __param(5, $PJ),
  __param(6, $rs)
], RemoteUserDataSyncActivityViewDataProvider);
var ExtractedUserDataSyncActivityViewDataProvider = class ExtractedUserDataSyncActivityViewDataProvider2 extends UserDataSyncActivityViewDataProvider {
  constructor(activityDataResource, userDataSyncService, userDataSyncResourceProviderService, userDataAutoSyncService, userDataSyncWorkbenchService, notificationService, userDataProfilesService, u, v) {
    super(userDataSyncService, userDataSyncResourceProviderService, userDataAutoSyncService, userDataSyncWorkbenchService, notificationService, userDataProfilesService);
    this.activityDataResource = activityDataResource;
    this.u = u;
    this.v = v;
  }
  async getChildren(element) {
    if (!element) {
      this.s = void 0;
      if (!this.activityDataResource) {
        return [];
      }
      const stat = await this.u.resolve(this.activityDataResource);
      if (stat.isDirectory) {
        this.t = this.activityDataResource;
      } else {
        this.t = this.v.extUri.joinPath(this.v.extUri.dirname(this.activityDataResource), "remoteActivity");
        try {
          await this.u.del(this.t, { recursive: true });
        } catch (e) {
        }
        await this.f.extractActivityData(this.activityDataResource, this.t);
      }
    }
    return super.getChildren(element);
  }
  r(syncResource, profile) {
    return this.g.getLocalSyncResourceHandles(syncResource, profile, this.t);
  }
  async q() {
    return this.g.getLocalSyncedProfiles(this.t);
  }
  async n(element) {
    const children = await super.n(element);
    if (children.length) {
      const machineId = await this.g.getMachineId(element.syncResourceHandle);
      if (machineId) {
        const machines = await this.z();
        const machine = machines.find(({ id: id2 }) => id2 === machineId);
        children[0].description = machine?.isCurrent ? localize(11771, null) : machine?.name;
      }
    }
    return children;
  }
  z() {
    if (this.s === void 0) {
      this.s = this.g.getLocalSyncedMachines(this.t);
    }
    return this.s;
  }
};
ExtractedUserDataSyncActivityViewDataProvider = __decorate([
  __param(1, $7Bb),
  __param(2, $8Bb),
  __param(3, $9Bb),
  __param(4, $oXb),
  __param(5, $PJ),
  __param(6, $rs),
  __param(7, $km),
  __param(8, $vl)
], ExtractedUserDataSyncActivityViewDataProvider);
var UserDataSyncMachinesViewDataProvider = class UserDataSyncMachinesViewDataProvider2 {
  constructor(f, g, h3, i2, j, k) {
    this.f = f;
    this.g = g;
    this.h = h3;
    this.i = i2;
    this.j = j;
    this.k = k;
  }
  async getChildren(element) {
    if (!element) {
      this.d = void 0;
    }
    try {
      let machines = await this.l();
      machines = machines.filter((m) => !m.disabled).sort((m1, m2) => m1.isCurrent ? -1 : 1);
      this.f.message = machines.length ? void 0 : localize(11772, null);
      return machines.map(({ id: id2, name, isCurrent, platform }) => ({
        handle: id2,
        collapsibleState: TreeItemCollapsibleState2.None,
        label: { label: name },
        description: isCurrent ? localize(11773, null) : void 0,
        themeIcon: platform && $IBb(platform) ? $6l.globe : $6l.vm,
        contextValue: "sync-machine"
      }));
    } catch (error) {
      this.i.error(error);
      return [];
    }
  }
  l() {
    if (this.d === void 0) {
      this.d = this.g.getMachines();
    }
    return this.d;
  }
  async disable(machineIds) {
    const machines = await this.l();
    const machinesToDisable = machines.filter(({ id: id2 }) => machineIds.includes(id2));
    if (!machinesToDisable.length) {
      throw new Error(localize(11774, null, machineIds.join(",")));
    }
    const result = await this.j.confirm({
      type: "info",
      message: machinesToDisable.length > 1 ? localize(11775, null) : localize(11776, null, machinesToDisable[0].name),
      primaryButton: localize(11777, null)
    });
    if (!result.confirmed) {
      return false;
    }
    if (machinesToDisable.some((machine) => machine.isCurrent)) {
      await this.k.turnoff(false);
    }
    const otherMachinesToDisable = machinesToDisable.filter((machine) => !machine.isCurrent).map((machine) => [machine.id, false]);
    if (otherMachinesToDisable.length) {
      await this.g.setEnablements(otherMachinesToDisable);
    }
    return true;
  }
  async rename(machineId) {
    const disposableStore = new $2c();
    const inputBox = disposableStore.add(this.h.createInputBox());
    inputBox.placeholder = localize(11778, null);
    inputBox.busy = true;
    inputBox.show();
    const machines = await this.l();
    const machine = machines.find(({ id: id2 }) => id2 === machineId);
    if (!machine) {
      inputBox.hide();
      disposableStore.dispose();
      throw new Error(localize(11779, null, machineId));
    }
    inputBox.busy = false;
    inputBox.value = machine.name;
    const validateMachineName = (machineName) => {
      machineName = machineName.trim();
      return machineName && !machines.some((m) => m.id !== machineId && m.name === machineName) ? machineName : null;
    };
    disposableStore.add(inputBox.onDidChangeValue(() => inputBox.validationMessage = validateMachineName(inputBox.value) ? "" : localize(11780, null)));
    return new Promise((c, e) => {
      disposableStore.add(inputBox.onDidAccept(async () => {
        const machineName = validateMachineName(inputBox.value);
        disposableStore.dispose();
        if (machineName && machineName !== machine.name) {
          try {
            await this.g.renameMachine(machineId, machineName);
            c(true);
          } catch (error) {
            e(error);
          }
        } else {
          c(false);
        }
      }));
    });
  }
};
UserDataSyncMachinesViewDataProvider = __decorate([
  __param(1, $HBb),
  __param(2, $1M),
  __param(3, $PJ),
  __param(4, $Yv),
  __param(5, $oXb)
], UserDataSyncMachinesViewDataProvider);
var UserDataSyncTroubleshootViewDataProvider = class UserDataSyncTroubleshootViewDataProvider2 {
  constructor(d, f, g, h3) {
    this.d = d;
    this.f = f;
    this.g = g;
    this.h = h3;
  }
  async getChildren(element) {
    if (!element) {
      return [{
        handle: "SYNC_LOGS",
        collapsibleState: TreeItemCollapsibleState2.Collapsed,
        label: { label: localize(11781, null) },
        themeIcon: $6l.folder
      }, {
        handle: "LAST_SYNC_STATES",
        collapsibleState: TreeItemCollapsibleState2.Collapsed,
        label: { label: localize(11782, null) },
        themeIcon: $6l.folder
      }];
    }
    if (element.handle === "LAST_SYNC_STATES") {
      return this.i();
    }
    if (element.handle === "SYNC_LOGS") {
      return this.j();
    }
    return [];
  }
  async i() {
    const result = [];
    for (const syncResource of $RBb) {
      const resource = $TBb(void 0, syncResource, this.g, this.h.extUri);
      if (await this.d.exists(resource)) {
        result.push({
          handle: resource.toString(),
          label: { label: $pXb(syncResource) },
          collapsibleState: TreeItemCollapsibleState2.None,
          resourceUri: resource,
          command: { id: $$ub, title: "", arguments: [resource, void 0, void 0] }
        });
      }
    }
    return result;
  }
  async j() {
    const logResources = await this.f.getAllLogResources();
    const result = [];
    for (const syncLogResource of logResources) {
      const logFolder = this.h.extUri.dirname(syncLogResource);
      result.push({
        handle: syncLogResource.toString(),
        collapsibleState: TreeItemCollapsibleState2.None,
        resourceUri: syncLogResource,
        label: { label: this.h.extUri.basename(logFolder) },
        description: this.h.extUri.isEqual(logFolder, this.g.logsHome) ? localize(11783, null) : void 0,
        command: { id: $$ub, title: "", arguments: [syncLogResource, void 0, void 0] }
      });
    }
    return result;
  }
};
UserDataSyncTroubleshootViewDataProvider = __decorate([
  __param(0, $km),
  __param(1, $oXb),
  __param(2, $Xk),
  __param(3, $vl)
], UserDataSyncTroubleshootViewDataProvider);

// out-build/vs/workbench/contrib/userDataSync/browser/userDataSync.js
var turnOffSyncCommand = { id: "workbench.userDataSync.actions.turnOff", title: localize2(11742, "Turn Off") };
var configureSyncCommand = { id: $yXb, title: localize2(11743, "Configure...") };
var showConflictsCommandId = "workbench.userDataSync.actions.showConflicts";
var syncNowCommand = {
  id: "workbench.userDataSync.actions.syncNow",
  title: localize2(11744, "Sync Now"),
  description(userDataSyncService) {
    if (userDataSyncService.status === "syncing") {
      return localize(11672, null);
    }
    if (userDataSyncService.lastSyncTime) {
      return localize(11673, null, $Qu(userDataSyncService.lastSyncTime, true));
    }
    return void 0;
  }
};
var showSyncSettingsCommand = { id: "workbench.userDataSync.actions.settings", title: localize2(11745, "Show Settings") };
var showSyncedDataCommand = { id: "workbench.userDataSync.actions.showSyncedData", title: localize2(11746, "Show Synced Data") };
var CONTEXT_TURNING_ON_STATE = new $nn("userDataSyncTurningOn", false);
var $Ujc = class $Ujc2 extends $3c {
  constructor(g, h3, j, contextKeyService, m, n, r2, s, t, u, w, y, userDataAutoSyncService, textModelResolverService, z, C, D, F, G, H, I, J, L) {
    super();
    this.g = g;
    this.h = h3;
    this.j = j;
    this.m = m;
    this.n = n;
    this.r = r2;
    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 = G;
    this.H = H;
    this.I = I;
    this.J = J;
    this.L = L;
    this.b = this.B(new $4c());
    this.f = this.B(new $4c());
    this.O = /* @__PURE__ */ new Map();
    this.W = /* @__PURE__ */ new Map();
    this.qb = this.B(new $4c());
    this.a = CONTEXT_TURNING_ON_STATE.bindTo(contextKeyService);
    if (j.enabled) {
      $PBb();
      this.ab();
      this.$();
      this.P(this.h.conflicts);
      this.B(Event2.any(Event2.debounce(h3.onDidChangeStatus, () => void 0, 500), this.g.onDidChangeEnablement, this.j.onDidChangeAccountStatus)(() => {
        this.ab();
        this.$();
      }));
      this.B(h3.onDidChangeConflicts(() => this.P(this.h.conflicts)));
      this.B(g.onDidChangeEnablement(() => this.P(this.h.conflicts)));
      this.B(h3.onSyncErrors((errors) => this.X(errors)));
      this.B(userDataAutoSyncService.onError((error) => this.S(error)));
      this.kb();
      this.Cb();
      textModelResolverService.registerTextModelContentProvider($aCb, w.createInstance(UserDataRemoteContentProvider));
      this.B(Event2.any(h3.onDidChangeStatus, g.onDidChangeEnablement)(
        () => this.M = !g.isEnabled() && h3.status !== "idle"
        /* SyncStatus.Idle */
      ));
    }
  }
  get M() {
    return !!this.a.get();
  }
  set M(turningOn) {
    this.a.set(turningOn);
    this.$();
  }
  N({ syncResource: resource, profile }) {
    return `${profile.id}:${resource}`;
  }
  P(conflicts) {
    this.$();
    this.rb();
    if (!this.g.isEnabled()) {
      return;
    }
    if (conflicts.length) {
      for (const [key2, disposable] of this.O.entries()) {
        if (!conflicts.some((conflict) => this.N(conflict) === key2)) {
          disposable.dispose();
          this.O.delete(key2);
        }
      }
      for (const conflict of this.h.conflicts) {
        const key2 = this.N(conflict);
        if (!this.O.has(key2)) {
          const conflictsArea = $pXb(conflict.syncResource);
          const handle2 = this.n.prompt(Severity2.Warning, localize(11674, null, conflictsArea.toLowerCase()), [
            {
              label: localize(11675, null),
              run: () => {
                this.C.publicLog2("sync/handleConflicts", { source: conflict.syncResource, action: "acceptLocal" });
                this.R(conflict, conflict.conflicts[0]);
              }
            },
            {
              label: localize(11676, null),
              run: () => {
                this.C.publicLog2("sync/handleConflicts", { source: conflict.syncResource, action: "acceptRemote" });
                this.Q(conflict, conflict.conflicts[0]);
              }
            },
            {
              label: localize(11677, null),
              run: () => {
                this.C.publicLog2("sync/showConflicts", { source: conflict.syncResource });
                this.j.showConflicts(conflict.conflicts[0]);
              }
            }
          ], {
            sticky: true
          });
          this.O.set(key2, $1c(() => {
            handle2.close();
            this.O.delete(key2);
          }));
        }
      }
    } else {
      this.O.forEach((disposable) => disposable.dispose());
      this.O.clear();
    }
  }
  async Q(syncResource, conflict) {
    try {
      await this.h.accept(syncResource, conflict.remoteResource, void 0, this.g.isEnabled());
    } catch (e) {
      this.n.error(localize(11678, null, `command:${$zXb}`));
    }
  }
  async R(syncResource, conflict) {
    try {
      await this.h.accept(syncResource, conflict.localResource, void 0, this.g.isEnabled());
    } catch (e) {
      this.n.error(localize(11679, null, `command:${$zXb}`));
    }
  }
  S(error) {
    switch (error.code) {
      case "SessionExpired":
        this.n.notify({
          severity: Severity2.Info,
          message: localize(11680, null),
          actions: {
            primary: [new $Um("turn on sync", localize(11681, null), void 0, true, () => this.bb())]
          }
        });
        break;
      case "TurnedOff":
        this.n.notify({
          severity: Severity2.Info,
          message: localize(11682, null),
          actions: {
            primary: [new $Um("turn on sync", localize(11683, null), void 0, true, () => this.bb())]
          }
        });
        break;
      case "TooLarge":
        if (error.resource === "keybindings" || error.resource === "settings" || error.resource === "tasks") {
          this.hb(error.resource);
          const sourceArea = $pXb(error.resource);
          this.U(error.resource, localize(11684, null, sourceArea.toLowerCase(), sourceArea.toLowerCase(), "100kb"), error);
        }
        break;
      case "LocalTooManyProfiles":
        this.hb(
          "profiles"
          /* SyncResource.Profiles */
        );
        this.n.error(localize(11685, null));
        break;
      case "IncompatibleLocalContent":
      case "Gone":
      case "UpgradeRequired": {
        const message = localize(11686, null, this.D.version, this.D.commit);
        const operationId = error.operationId ? localize(11687, null, error.operationId) : void 0;
        this.n.notify({
          severity: Severity2.Error,
          message: operationId ? `${message} ${operationId}` : message
        });
        break;
      }
      case "MethodNotFound": {
        const message = localize(11688, null);
        const operationId = error.operationId ? localize(11689, null, error.operationId) : void 0;
        this.n.notify({
          severity: Severity2.Error,
          message: operationId ? `${message} ${operationId}` : message,
          actions: {
            primary: [
              new $Um("Show Sync Logs", localize(11690, null), void 0, true, () => this.J.executeCommand($zXb)),
              new $Um("Report Issue", localize(11691, null), void 0, true, () => this.L.openReporter())
            ]
          }
        });
        break;
      }
      case "IncompatibleRemoteContent":
        this.n.notify({
          severity: Severity2.Error,
          message: localize(11692, null),
          actions: {
            primary: [
              new $Um("reset", localize(11693, null), void 0, true, () => this.j.resetSyncedData()),
              new $Um("show synced data", localize(11694, null), void 0, true, () => this.j.showSyncActivity())
            ]
          }
        });
        return;
      case "ServiceChanged":
        this.n.notify({
          severity: Severity2.Info,
          message: this.H.userDataSyncStore?.type === "insiders" ? localize(11695, null) : localize(11696, null)
        });
        return;
      case "DefaultServiceChanged":
        if (this.g.isEnabled()) {
          this.n.notify({
            severity: Severity2.Info,
            message: localize(11697, null)
          });
        } else {
          this.n.notify({
            severity: Severity2.Info,
            message: localize(11698, null, this.D.nameLong),
            actions: {
              primary: [new $Um("turn on sync", localize(11699, null), void 0, true, () => this.bb())]
            }
          });
        }
        return;
    }
  }
  U(resource, message, error) {
    const operationId = error.operationId ? localize(11700, null, error.operationId) : void 0;
    this.n.notify({
      severity: Severity2.Error,
      message: operationId ? `${message} ${operationId}` : message,
      actions: {
        primary: [new $Um("open sync file", localize(11701, null, $pXb(resource)), void 0, true, () => resource === "settings" ? this.z.openUserSettings({ jsonEditor: true }) : this.z.openGlobalKeybindingSettings(true))]
      }
    });
  }
  X(errors) {
    if (errors.length) {
      for (const { profile, syncResource: resource, error } of errors) {
        switch (error.code) {
          case "LocalInvalidContent":
            this.Y({ profile, syncResource: resource });
            break;
          default: {
            const key2 = `${profile.id}:${resource}`;
            const disposable = this.W.get(key2);
            if (disposable) {
              disposable.dispose();
              this.W.delete(key2);
            }
          }
        }
      }
    } else {
      this.W.forEach((disposable) => disposable.dispose());
      this.W.clear();
    }
  }
  Y({ profile, syncResource: source }) {
    if (this.s.currentProfile.id !== profile.id) {
      return;
    }
    const key2 = `${profile.id}:${source}`;
    if (this.W.has(key2)) {
      return;
    }
    if (source !== "settings" && source !== "keybindings" && source !== "tasks") {
      return;
    }
    if (!this.I.hasFocus) {
      return;
    }
    const resource = source === "settings" ? this.s.currentProfile.settingsResource : source === "keybindings" ? this.s.currentProfile.keybindingsResource : this.s.currentProfile.tasksResource;
    const editorUri = $mL.getCanonicalUri(this.r.activeEditor, { supportSideBySide: SideBySideEditor.PRIMARY });
    if ($oh(resource, editorUri)) {
      return;
    }
    const errorArea = $pXb(source);
    const handle2 = this.n.notify({
      severity: Severity2.Error,
      message: localize(11702, null, errorArea.toLowerCase()),
      actions: {
        primary: [new $Um("open sync file", localize(11703, null, errorArea), void 0, true, () => source === "settings" ? this.z.openUserSettings({ jsonEditor: true }) : this.z.openGlobalKeybindingSettings(true))]
      }
    });
    this.W.set(key2, $1c(() => {
      handle2.close();
      this.W.delete(key2);
    }));
  }
  Z() {
    return this.h.conflicts.reduce((result, { conflicts }) => {
      return result + conflicts.length;
    }, 0);
  }
  async $() {
    this.b.clear();
    let badge = void 0;
    let priority = void 0;
    if (this.h.conflicts.length && this.g.isEnabled()) {
      badge = new $wqb(this.Z(), () => localize(11704, null, $qXb.value));
    } else if (this.M) {
      badge = new $yqb(() => localize(11705, null));
      priority = 1;
    }
    if (badge) {
      this.b.value = this.m.showGlobalActivity({ badge, priority });
    }
  }
  async ab() {
    this.f.clear();
    let badge = void 0;
    if (this.h.status !== "uninitialized" && this.g.isEnabled() && this.j.accountStatus === "unavailable") {
      badge = new $wqb(1, () => localize(11706, null));
    }
    if (badge) {
      this.f.value = this.m.showAccountsActivity({ badge, priority: void 0 });
    }
  }
  async bb() {
    try {
      if (!this.j.authenticationProviders.length) {
        throw new Error(localize(11707, null));
      }
      const turnOn = await this.cb();
      if (!turnOn) {
        return;
      }
      if (this.H.userDataSyncStore?.canSwitch) {
        await this.jb(this.H.userDataSyncStore);
      }
      await this.j.turnOn();
    } catch (e) {
      if ($kb(e)) {
        return;
      }
      if (e instanceof $1Bb) {
        switch (e.code) {
          case "TooLarge":
            if (e.resource === "keybindings" || e.resource === "settings" || e.resource === "tasks") {
              this.U(e.resource, localize(11708, null, $pXb(e.resource).toLowerCase(), "100kb"), e);
              return;
            }
            break;
          case "IncompatibleLocalContent":
          case "Gone":
          case "UpgradeRequired": {
            const message = localize(11709, null, this.D.version, this.D.commit);
            const operationId = e.operationId ? localize(11710, null, e.operationId) : void 0;
            this.n.notify({
              severity: Severity2.Error,
              message: operationId ? `${message} ${operationId}` : message
            });
            return;
          }
          case "IncompatibleRemoteContent":
            this.n.notify({
              severity: Severity2.Error,
              message: localize(11711, null),
              actions: {
                primary: [
                  new $Um("reset", localize(11712, null), void 0, true, () => this.j.resetSyncedData()),
                  new $Um("show synced data", localize(11713, null), void 0, true, () => this.j.showSyncActivity())
                ]
              }
            });
            return;
          case "Unauthorized":
          case "Forbidden":
            this.n.error(localize(11714, null));
            return;
        }
        this.n.error(localize(11715, null, `command:${$zXb}`));
      } else {
        this.n.error(localize(11716, null, $qb(e)));
      }
    }
  }
  async cb() {
    return new Promise((c, e) => {
      const disposables = new $2c();
      const quickPick = this.u.createQuickPick();
      disposables.add(quickPick);
      quickPick.title = $qXb.value;
      quickPick.ok = false;
      quickPick.customButton = true;
      quickPick.customLabel = localize(11717, null);
      quickPick.description = localize(11718, null);
      quickPick.canSelectMany = true;
      quickPick.ignoreFocusOut = true;
      quickPick.hideInput = true;
      quickPick.hideCheckAll = true;
      const items = this.db();
      quickPick.items = items;
      quickPick.selectedItems = items.filter((item) => this.g.isResourceEnabled(item.id));
      let accepted = false;
      disposables.add(Event2.any(quickPick.onDidAccept, quickPick.onDidCustom)(() => {
        accepted = true;
        quickPick.hide();
      }));
      disposables.add(quickPick.onDidHide(() => {
        try {
          if (accepted) {
            this.eb(items, quickPick.selectedItems);
          }
          c(accepted);
        } catch (error) {
          e(error);
        } finally {
          disposables.dispose();
        }
      }));
      quickPick.show();
    });
  }
  db() {
    return [{
      id: "settings",
      label: $pXb(
        "settings"
        /* SyncResource.Settings */
      )
    }, {
      id: "keybindings",
      label: $pXb(
        "keybindings"
        /* SyncResource.Keybindings */
      )
    }, {
      id: "snippets",
      label: $pXb(
        "snippets"
        /* SyncResource.Snippets */
      )
    }, {
      id: "tasks",
      label: $pXb(
        "tasks"
        /* SyncResource.Tasks */
      )
    }, {
      id: "globalState",
      label: $pXb(
        "globalState"
        /* SyncResource.GlobalState */
      )
    }, {
      id: "extensions",
      label: $pXb(
        "extensions"
        /* SyncResource.Extensions */
      )
    }, {
      id: "profiles",
      label: $pXb(
        "profiles"
        /* SyncResource.Profiles */
      )
    }];
  }
  eb(items, selectedItems) {
    for (const item of items) {
      const wasEnabled = this.g.isResourceEnabled(item.id);
      const isEnabled = !!selectedItems.filter((selected) => selected.id === item.id)[0];
      if (wasEnabled !== isEnabled) {
        this.g.setResourceEnablement(item.id, isEnabled);
      }
    }
  }
  async fb() {
    return new Promise((c, e) => {
      const disposables = new $2c();
      const quickPick = this.u.createQuickPick();
      disposables.add(quickPick);
      quickPick.title = localize(11719, null, $qXb.value);
      quickPick.placeholder = localize(11720, null);
      quickPick.canSelectMany = true;
      quickPick.ignoreFocusOut = true;
      quickPick.ok = true;
      const items = this.db();
      quickPick.items = items;
      quickPick.selectedItems = items.filter((item) => this.g.isResourceEnabled(item.id));
      disposables.add(quickPick.onDidAccept(async () => {
        if (quickPick.selectedItems.length) {
          this.eb(items, quickPick.selectedItems);
          quickPick.hide();
        }
      }));
      disposables.add(quickPick.onDidHide(() => {
        disposables.dispose();
        c();
      }));
      quickPick.show();
    });
  }
  async gb() {
    const result = await this.t.confirm({
      message: localize(11721, null),
      detail: localize(11722, null),
      primaryButton: localize(11723, null),
      checkbox: this.j.accountStatus === "available" ? {
        label: localize(11724, null)
      } : void 0
    });
    if (result.confirmed) {
      return this.j.turnoff(!!result.checkboxChecked);
    }
  }
  hb(source) {
    switch (source) {
      case "settings":
        return this.g.setResourceEnablement("settings", false);
      case "keybindings":
        return this.g.setResourceEnablement("keybindings", false);
      case "snippets":
        return this.g.setResourceEnablement("snippets", false);
      case "tasks":
        return this.g.setResourceEnablement("tasks", false);
      case "extensions":
        return this.g.setResourceEnablement("extensions", false);
      case "globalState":
        return this.g.setResourceEnablement("globalState", false);
      case "profiles":
        return this.g.setResourceEnablement("profiles", false);
    }
  }
  ib() {
    return this.y.showChannel($_Bb);
  }
  async jb(userDataSyncStore) {
    return new Promise((c, e) => {
      const disposables = new $2c();
      const quickPick = disposables.add(this.u.createQuickPick());
      quickPick.title = localize(11725, null, $qXb.value);
      quickPick.description = localize(11726, null);
      quickPick.hideInput = true;
      quickPick.ignoreFocusOut = true;
      const getDescription = (url) => {
        const isDefault = $oh(url, userDataSyncStore.defaultUrl);
        if (isDefault) {
          return localize(11727, null);
        }
        return void 0;
      };
      quickPick.items = [
        {
          id: "insiders",
          label: localize(11728, null),
          description: getDescription(userDataSyncStore.insidersUrl)
        },
        {
          id: "stable",
          label: localize(11729, null),
          description: getDescription(userDataSyncStore.stableUrl)
        }
      ];
      disposables.add(quickPick.onDidAccept(async () => {
        try {
          await this.H.switch(quickPick.selectedItems[0].id);
          c();
        } catch (error) {
          e(error);
        } finally {
          quickPick.hide();
        }
      }));
      disposables.add(quickPick.onDidHide(() => disposables.dispose()));
      quickPick.show();
    });
  }
  kb() {
    if (this.g.canToggleEnablement()) {
      this.lb();
      this.vb();
    }
    this.mb();
    this.nb();
    this.ob();
    this.rb();
    this.tb();
    this.sb();
    this.ub();
    this.wb();
    this.yb();
    this.zb();
    this.xb();
    this.Eb();
    this.Ab();
    if ($r) {
      this.Bb();
    }
  }
  lb() {
    const that = this;
    const when = $7m.and($sXb.notEqualsTo(
      "uninitialized"
      /* SyncStatus.Uninitialized */
    ), $tXb.toNegated(), CONTEXT_TURNING_ON_STATE.negate());
    this.B($hJ(class TurningOnSyncAction extends $gJ {
      constructor() {
        super({
          id: "workbench.userDataSync.actions.turnOn",
          title: localize2(11747, "Backup and Sync Settings..."),
          category: $qXb,
          f1: true,
          precondition: when,
          menu: [{
            group: "3_configuration",
            id: $bJ.GlobalActivity,
            when,
            order: 2
          }, {
            group: "3_configuration",
            id: $bJ.MenubarPreferencesMenu,
            when,
            order: 2
          }, {
            group: "1_settings",
            id: $bJ.AccountsContext,
            when,
            order: 2
          }]
        });
      }
      async run() {
        return that.bb();
      }
    }));
  }
  mb() {
    const when = $7m.and($sXb.notEqualsTo(
      "uninitialized"
      /* SyncStatus.Uninitialized */
    ), $tXb.toNegated(), CONTEXT_TURNING_ON_STATE);
    this.B($hJ(class TurningOnSyncAction extends $gJ {
      constructor() {
        super({
          id: "workbench.userData.actions.turningOn",
          title: localize(11730, null),
          precondition: $7m.false(),
          menu: [{
            group: "3_configuration",
            id: $bJ.GlobalActivity,
            when,
            order: 2
          }, {
            group: "1_settings",
            id: $bJ.AccountsContext,
            when
          }]
        });
      }
      async run() {
      }
    }));
  }
  nb() {
    const that = this;
    this.B($hJ(class TurningOnSyncAction extends $gJ {
      constructor() {
        super({
          id: "workbench.userData.actions.cancelTurnOn",
          title: localize(11731, null),
          icon: $6l.stopCircle,
          menu: {
            id: $bJ.ViewContainerTitle,
            when: $7m.and(CONTEXT_TURNING_ON_STATE, $7m.equals("viewContainer", $AXb)),
            group: "navigation",
            order: 1
          }
        });
      }
      async run() {
        return that.j.turnoff(false);
      }
    }));
  }
  ob() {
    const that = this;
    const id2 = "workbench.userData.actions.signin";
    const when = $7m.and($sXb.notEqualsTo(
      "uninitialized"
      /* SyncStatus.Uninitialized */
    ), $tXb, $uXb.isEqualTo(
      "unavailable"
      /* AccountStatus.Unavailable */
    ));
    this.B($hJ(class StopSyncAction extends $gJ {
      constructor() {
        super({
          id: "workbench.userData.actions.signin",
          title: localize(11732, null),
          menu: {
            group: "3_configuration",
            id: $bJ.GlobalActivity,
            when,
            order: 2
          }
        });
      }
      async run() {
        try {
          await that.j.signIn();
        } catch (e) {
          that.n.error(e);
        }
      }
    }));
    this.B($dJ.appendMenuItem($bJ.AccountsContext, {
      group: "1_settings",
      command: {
        id: id2,
        title: localize(11733, null)
      },
      when
    }));
  }
  pb() {
    return localize2(11748, "Show Conflicts ({0})", this.Z());
  }
  rb() {
    this.qb.value = void 0;
    const that = this;
    this.qb.value = $hJ(class TurningOnSyncAction extends $gJ {
      constructor() {
        super({
          id: showConflictsCommandId,
          get title() {
            return that.pb();
          },
          category: $qXb,
          f1: true,
          precondition: $xXb,
          menu: [{
            group: "3_configuration",
            id: $bJ.GlobalActivity,
            when: $xXb,
            order: 2
          }, {
            group: "3_configuration",
            id: $bJ.MenubarPreferencesMenu,
            when: $xXb,
            order: 2
          }]
        });
      }
      async run() {
        return that.j.showConflicts();
      }
    });
  }
  sb() {
    const that = this;
    const when = $7m.and($tXb, $uXb.notEqualsTo(
      "unavailable"
      /* AccountStatus.Unavailable */
    ), $sXb.notEqualsTo(
      "uninitialized"
      /* SyncStatus.Uninitialized */
    ));
    this.B($hJ(class SyncStatusAction extends $gJ {
      constructor() {
        super({
          id: "workbench.userDataSync.actions.manage",
          title: localize(11734, null),
          toggled: $$m.INSTANCE,
          menu: [
            {
              id: $bJ.GlobalActivity,
              group: "3_configuration",
              when,
              order: 2
            },
            {
              id: $bJ.MenubarPreferencesMenu,
              group: "3_configuration",
              when,
              order: 2
            },
            {
              id: $bJ.AccountsContext,
              group: "1_settings",
              when
            }
          ]
        });
      }
      run(accessor) {
        return new Promise((c, e) => {
          const quickInputService = accessor.get($1M);
          const commandService = accessor.get($sn);
          const disposables = new $2c();
          const quickPick = quickInputService.createQuickPick({ useSeparators: true });
          disposables.add(quickPick);
          const items = [];
          if (that.h.conflicts.length) {
            items.push({ id: showConflictsCommandId, label: `${$qXb.value}: ${that.pb().original}` });
            items.push({ type: "separator" });
          }
          items.push({ id: configureSyncCommand.id, label: `${$qXb.value}: ${configureSyncCommand.title.original}` });
          items.push({ id: showSyncSettingsCommand.id, label: `${$qXb.value}: ${showSyncSettingsCommand.title.original}` });
          items.push({ id: showSyncedDataCommand.id, label: `${$qXb.value}: ${showSyncedDataCommand.title.original}` });
          items.push({ type: "separator" });
          items.push({ id: syncNowCommand.id, label: `${$qXb.value}: ${syncNowCommand.title.original}`, description: syncNowCommand.description(that.h) });
          if (that.g.canToggleEnablement()) {
            const account = that.j.current;
            items.push({ id: turnOffSyncCommand.id, label: `${$qXb.value}: ${turnOffSyncCommand.title.original}`, description: account ? `${account.accountName} (${that.G.getProvider(account.authenticationProviderId).label})` : void 0 });
          }
          quickPick.items = items;
          disposables.add(quickPick.onDidAccept(() => {
            if (quickPick.selectedItems[0] && quickPick.selectedItems[0].id) {
              commandService.executeCommand(quickPick.selectedItems[0].id);
            }
            quickPick.hide();
          }));
          disposables.add(quickPick.onDidHide(() => {
            disposables.dispose();
            c();
          }));
          quickPick.show();
        });
      }
    }));
  }
  tb() {
    const that = this;
    const when = $7m.and($uXb.isEqualTo(
      "available"
      /* AccountStatus.Available */
    ), $sXb.notEqualsTo(
      "uninitialized"
      /* SyncStatus.Uninitialized */
    ));
    this.B($hJ(class SyncStatusAction extends $gJ {
      constructor() {
        super({
          id: showSyncedDataCommand.id,
          title: showSyncedDataCommand.title,
          category: $qXb,
          precondition: when,
          menu: {
            id: $bJ.CommandPalette,
            when
          }
        });
      }
      run(accessor) {
        return that.j.showSyncActivity();
      }
    }));
  }
  ub() {
    const that = this;
    this.B($hJ(class SyncNowAction extends $gJ {
      constructor() {
        super({
          id: syncNowCommand.id,
          title: syncNowCommand.title,
          category: $qXb,
          menu: {
            id: $bJ.CommandPalette,
            when: $7m.and($tXb, $uXb.isEqualTo(
              "available"
              /* AccountStatus.Available */
            ), $sXb.notEqualsTo(
              "uninitialized"
              /* SyncStatus.Uninitialized */
            ))
          }
        });
      }
      run(accessor) {
        return that.j.syncNow();
      }
    }));
  }
  vb() {
    const that = this;
    this.B($hJ(class StopSyncAction extends $gJ {
      constructor() {
        super({
          id: turnOffSyncCommand.id,
          title: turnOffSyncCommand.title,
          category: $qXb,
          menu: {
            id: $bJ.CommandPalette,
            when: $7m.and($sXb.notEqualsTo(
              "uninitialized"
              /* SyncStatus.Uninitialized */
            ), $tXb)
          }
        });
      }
      async run() {
        try {
          await that.gb();
        } catch (e) {
          if (!$kb(e)) {
            that.n.error(localize(11735, null, `command:${$zXb}`));
          }
        }
      }
    }));
  }
  wb() {
    const that = this;
    const when = $7m.and($sXb.notEqualsTo(
      "uninitialized"
      /* SyncStatus.Uninitialized */
    ), $tXb);
    this.B($hJ(class ConfigureSyncAction extends $gJ {
      constructor() {
        super({
          id: configureSyncCommand.id,
          title: configureSyncCommand.title,
          category: $qXb,
          icon: $6l.settingsGear,
          tooltip: localize(11736, null),
          menu: [{
            id: $bJ.CommandPalette,
            when
          }, {
            id: $bJ.ViewContainerTitle,
            when: $7m.and($tXb, $7m.equals("viewContainer", $AXb)),
            group: "navigation",
            order: 2
          }]
        });
      }
      run() {
        return that.fb();
      }
    }));
  }
  xb() {
    const that = this;
    this.B($hJ(class ShowSyncActivityAction extends $gJ {
      constructor() {
        super({
          id: $zXb,
          title: localize(11737, null, $qXb.value),
          tooltip: localize(11738, null),
          icon: $6l.output,
          menu: [{
            id: $bJ.CommandPalette,
            when: $7m.and($sXb.notEqualsTo(
              "uninitialized"
              /* SyncStatus.Uninitialized */
            ))
          }, {
            id: $bJ.ViewContainerTitle,
            when: $7m.equals("viewContainer", $AXb),
            group: "navigation",
            order: 1
          }]
        });
      }
      run() {
        return that.ib();
      }
    }));
  }
  yb() {
    this.B($hJ(class ShowSyncSettingsAction extends $gJ {
      constructor() {
        super({
          id: showSyncSettingsCommand.id,
          title: showSyncSettingsCommand.title,
          category: $qXb,
          menu: {
            id: $bJ.CommandPalette,
            when: $7m.and($sXb.notEqualsTo(
              "uninitialized"
              /* SyncStatus.Uninitialized */
            ))
          }
        });
      }
      run(accessor) {
        accessor.get($TK).openUserSettings({ jsonEditor: false, query: "@tag:sync" });
      }
    }));
  }
  zb() {
    const that = this;
    this.B($hJ(class HelpAction extends $gJ {
      constructor() {
        super({
          id: "workbench.userDataSync.actions.help",
          title: $qXb,
          category: $qn.Help,
          menu: [{
            id: $bJ.CommandPalette,
            when: $7m.and($sXb.notEqualsTo(
              "uninitialized"
              /* SyncStatus.Uninitialized */
            ))
          }]
        });
      }
      run() {
        return that.F.open(URI.parse("https://aka.ms/vscode-settings-sync-help"));
      }
    }));
    $dJ.appendMenuItem($bJ.ViewContainerTitle, {
      command: {
        id: "workbench.userDataSync.actions.help",
        title: $qn.Help.value
      },
      when: $7m.equals("viewContainer", $AXb),
      group: "1_help"
    });
  }
  Ab() {
    const that = this;
    this.B($hJ(class AcceptMergesAction extends $gJ {
      constructor() {
        super({
          id: "workbench.userDataSync.actions.acceptMerges",
          title: localize(11739, null),
          menu: [{
            id: $bJ.EditorContent,
            when: $7m.and($hIb, $7m.regex($mIb.key, new RegExp(`^${$aCb}:`)))
          }]
        });
      }
      async run(accessor, previewResource) {
        const textFileService = accessor.get($cK);
        await textFileService.save(previewResource);
        const content = await textFileService.read(previewResource);
        await that.h.accept(this.a(previewResource), previewResource, content.value, true);
      }
      a(previewResource) {
        const conflict = that.h.conflicts.find(({ conflicts }) => conflicts.some((conflict2) => $oh(conflict2.previewResource, previewResource)));
        if (conflict) {
          return conflict;
        }
        throw new Error(`Unknown resource: ${previewResource.toString()}`);
      }
    }));
  }
  Bb() {
    this.B($hJ(class DownloadSyncActivityAction extends $gJ {
      constructor() {
        super($CXb);
      }
      async run(accessor) {
        const userDataSyncWorkbenchService = accessor.get($oXb);
        const notificationService = accessor.get($PJ);
        const folder = await userDataSyncWorkbenchService.downloadSyncActivity();
        if (folder) {
          notificationService.info(localize(11740, null));
        }
      }
    }));
  }
  Cb() {
    const container2 = this.Db();
    this.Fb(container2);
  }
  Db() {
    return $Wn.as(Extensions5.ViewContainersRegistry).registerViewContainer(
      {
        id: $AXb,
        title: $qXb,
        ctorDescriptor: new $Nk($oqb, [$AXb, { mergeViewWithContainerWhenSingleView: true }]),
        icon: $rXb,
        hideIfEmpty: true
      },
      0
      /* ViewContainerLocation.Sidebar */
    );
  }
  Eb() {
    const that = this;
    this.B($hJ(class extends $gJ {
      constructor() {
        super({
          id: "workbench.actions.syncData.reset",
          title: localize(11741, null),
          menu: [{
            id: $bJ.ViewContainerTitle,
            when: $7m.equals("viewContainer", $AXb),
            group: "0_configure"
          }]
        });
      }
      run() {
        return that.j.resetSyncedData();
      }
    }));
  }
  Fb(container2) {
    this.B(this.w.createInstance($Tjc, container2));
  }
};
$Ujc = __decorate([
  __param(0, $6Bb),
  __param(1, $7Bb),
  __param(2, $oXb),
  __param(3, $on),
  __param(4, $vqb),
  __param(5, $PJ),
  __param(6, $mJ),
  __param(7, $gT),
  __param(8, $Yv),
  __param(9, $1M),
  __param(10, $Pk),
  __param(11, $RS),
  __param(12, $9Bb),
  __param(13, $oG),
  __param(14, $TK),
  __param(15, $zv),
  __param(16, $Vu),
  __param(17, $O4),
  __param(18, $xS),
  __param(19, $UBb),
  __param(20, $S4),
  __param(21, $sn),
  __param(22, $6zb)
], $Ujc);
var UserDataRemoteContentProvider = class UserDataRemoteContentProvider2 {
  constructor(a, b, d) {
    this.a = a;
    this.b = b;
    this.d = d;
  }
  provideTextContent(uri) {
    if (uri.scheme === $aCb) {
      return this.a.resolveContent(uri).then((content) => this.b.createModel(content || "", this.d.createById("jsonc"), uri));
    }
    return null;
  }
};
UserDataRemoteContentProvider = __decorate([
  __param(0, $7Bb),
  __param(1, $sG),
  __param(2, $1E)
], UserDataRemoteContentProvider);

// out-build/vs/workbench/contrib/userDataSync/browser/userDataSyncTrigger.js
var $Vjc = class $Vjc2 extends $3c {
  constructor(editorService, a, viewsService, userDataAutoSyncService, hostService) {
    super();
    this.a = a;
    const event = Event2.filter(Event2.any(Event2.map(editorService.onDidActiveEditorChange, () => this.b(editorService.activeEditor)), Event2.map(Event2.filter(viewsService.onDidChangeViewContainerVisibility, (e) => e.id === $tzb && e.visible), (e) => e.id)), (source) => source !== void 0);
    if ($r) {
      this.B(Event2.debounce(Event2.any(Event2.map(hostService.onDidChangeFocus, () => "windowFocus"), Event2.map(event, (source) => source)), (last, source) => last ? [...last, source] : [source], 1e3)((sources) => userDataAutoSyncService.triggerSync(sources, true, false)));
    } else {
      this.B(event((source) => userDataAutoSyncService.triggerSync([source], true, false)));
    }
  }
  b(editorInput) {
    if (!editorInput) {
      return void 0;
    }
    if (editorInput instanceof $FVb) {
      return "settingsEditor";
    }
    if (editorInput instanceof $EVb) {
      return "keybindingsEditor";
    }
    const resource = editorInput.resource;
    if ($oh(resource, this.a.defaultProfile.settingsResource)) {
      return "settingsEditor";
    }
    if ($oh(resource, this.a.defaultProfile.keybindingsResource)) {
      return "keybindingsEditor";
    }
    return void 0;
  }
};
$Vjc = __decorate([
  __param(0, $mJ),
  __param(1, $rs),
  __param(2, $uob),
  __param(3, $9Bb),
  __param(4, $S4)
], $Vjc);

// out-build/vs/workbench/contrib/userDataSync/browser/userDataSync.contribution.js
var UserDataSyncReportIssueContribution = class UserDataSyncReportIssueContribution2 extends $3c {
  constructor(userDataAutoSyncService, a, b, c, f) {
    super();
    this.a = a;
    this.b = b;
    this.c = c;
    this.f = f;
    this.B(userDataAutoSyncService.onError((error) => this.g(error)));
  }
  g(error) {
    switch (error.code) {
      case "LocalTooManyRequests": {
        const message = $r ? localize(11663, null, this.b.nameLong) : localize(11664, null, this.b.nameLong);
        this.a.notify({
          severity: Severity2.Error,
          message,
          actions: {
            primary: [
              new $Um("Show Sync Logs", localize(11665, null), void 0, true, () => this.c.executeCommand($zXb)),
              new $Um("Restart", $r ? localize(11666, null) : localize(11667, null), void 0, true, () => this.f.restart())
            ]
          }
        });
        return;
      }
      case "RemoteTooManyRequests": {
        const operationId = error.operationId ? localize(11668, null, error.operationId) : void 0;
        const message = localize(11669, null);
        this.a.notify({
          severity: Severity2.Error,
          message: operationId ? `${message} ${operationId}` : message,
          source: error.operationId ? localize(11670, null, error.operationId) : void 0,
          actions: {
            primary: [
              new $Um("Show Sync Logs", localize(11671, null), void 0, true, () => this.c.executeCommand($zXb))
            ]
          }
        });
        return;
      }
    }
  }
};
UserDataSyncReportIssueContribution = __decorate([
  __param(0, $9Bb),
  __param(1, $PJ),
  __param(2, $Vu),
  __param(3, $sn),
  __param(4, $S4)
], UserDataSyncReportIssueContribution);
var workbenchRegistry6 = $Wn.as(Extensions2.Workbench);
workbenchRegistry6.registerWorkbenchContribution(
  $Ujc,
  3
  /* LifecyclePhase.Restored */
);
workbenchRegistry6.registerWorkbenchContribution(
  $Vjc,
  4
  /* LifecyclePhase.Eventually */
);
workbenchRegistry6.registerWorkbenchContribution(
  UserDataSyncReportIssueContribution,
  4
  /* LifecyclePhase.Eventually */
);

// out-build/vs/workbench/contrib/tags/common/workspaceTags.js
var $Zjc = $Qk("workspaceTagsService");

// out-build/vs/workbench/contrib/userDataProfile/browser/userDataProfilesEditorModel.js
var $7jc_1;
function $2jc(element) {
  return element.resourceType !== void 0;
}
function $3jc(element) {
  return element.label !== void 0;
}
var $4jc = class $4jc2 extends $3c {
  constructor(name, icon2, flags, workspaces, isActive2, g, h3, j, m, n, s, t, u, w) {
    super();
    this.g = g;
    this.h = h3;
    this.j = j;
    this.m = m;
    this.n = n;
    this.s = s;
    this.t = t;
    this.u = u;
    this.w = w;
    this.c = this.B(new $ze());
    this.onDidChange = this.c.event;
    this.f = this.B(new $8h(() => this.O(), 500));
    this.y = "";
    this.F = false;
    this.H = false;
    this.y = name;
    this.z = icon2;
    this.D = flags;
    this.C = workspaces;
    this.F = isActive2;
    this.B(this.onDidChange((e) => {
      if (!e.message) {
        this.validate();
      }
      this.save();
    }));
    this.B(this.u.onProfileAwareDidInstallExtensions((results) => {
      const profile = this.P();
      if (profile && results.some((r2) => !r2.error && (r2.applicationScoped || this.s.extUri.isEqual(r2.profileLocation, profile.extensionsResource)))) {
        this.c.fire({ extensions: true });
      }
    }));
    this.B(this.u.onProfileAwareDidUninstallExtension((e) => {
      const profile = this.P();
      if (profile && !e.error && (e.applicationScoped || this.s.extUri.isEqual(e.profileLocation, profile.extensionsResource))) {
        this.c.fire({ extensions: true });
      }
    }));
    this.B(this.u.onProfileAwareDidUpdateExtensionMetadata((e) => {
      const profile = this.P();
      if (profile && e.local.isApplicationScoped || this.s.extUri.isEqual(e.profileLocation, profile?.extensionsResource)) {
        this.c.fire({ extensions: true });
      }
    }));
  }
  get name() {
    return this.y;
  }
  set name(name) {
    name = name.trim();
    if (this.y !== name) {
      this.y = name;
      this.c.fire({ name: true });
    }
  }
  get icon() {
    return this.z;
  }
  set icon(icon2) {
    if (this.z !== icon2) {
      this.z = icon2;
      this.c.fire({ icon: true });
    }
  }
  get workspaces() {
    return this.C;
  }
  set workspaces(workspaces) {
    if (!$zb(this.C, workspaces, (a, b) => a.toString() === b.toString())) {
      this.C = workspaces;
      this.c.fire({ workspaces: true });
    }
  }
  get flags() {
    return this.D;
  }
  set flags(flags) {
    if (!$Pv(this.D, flags)) {
      this.D = flags;
      this.c.fire({ flags: true });
    }
  }
  get active() {
    return this.F;
  }
  set active(active) {
    if (this.F !== active) {
      this.F = active;
      this.c.fire({ active: true });
    }
  }
  get message() {
    return this.G;
  }
  set message(message) {
    if (this.G !== message) {
      this.G = message;
      this.c.fire({ message: true });
    }
  }
  get disabled() {
    return this.H;
  }
  set disabled(saving) {
    if (this.H !== saving) {
      this.H = saving;
      this.c.fire({ disabled: true });
    }
  }
  getFlag(key2) {
    return this.flags?.[key2] ?? false;
  }
  setFlag(key2, value) {
    const flags = this.flags ? { ...this.flags } : {};
    if (value) {
      flags[key2] = true;
    } else {
      delete flags[key2];
    }
    this.flags = flags;
  }
  validate() {
    if (!this.name) {
      this.message = localize(11636, null);
      return;
    }
    if (this.shouldValidateName() && this.name !== this.getInitialName() && this.h.profiles.some((p) => p.name === this.name)) {
      this.message = localize(11637, null, this.name);
      return;
    }
    if (this.flags && this.flags.settings && this.flags.keybindings && this.flags.tasks && this.flags.snippets && this.flags.extensions) {
      this.message = localize(11638, null);
      return;
    }
    this.message = void 0;
  }
  async getChildren(resourceType) {
    if (resourceType === void 0) {
      const resourceTypes = [
        "settings",
        "keybindings",
        "tasks",
        "snippets",
        "extensions"
        /* ProfileResourceType.Extensions */
      ];
      return Promise.all(resourceTypes.map(async (r2) => {
        const children = r2 === "settings" || r2 === "keybindings" || r2 === "tasks" ? await this.I(r2) : [];
        return {
          handle: r2,
          checkbox: void 0,
          resourceType: r2,
          openAction: children.length ? new $Um("_open", localize(11639, null), ThemeIcon.asClassName($6l.goToFile), true, () => children[0]?.openAction?.run()) : void 0
        };
      }));
    }
    return this.I(resourceType);
  }
  async I(resourceType) {
    return [];
  }
  async J(profile, resourceType) {
    profile = this.getFlag(resourceType) ? this.h.defaultProfile : profile;
    let children = [];
    switch (resourceType) {
      case "settings":
        children = await this.w.createInstance($CWb, profile).getChildren();
        break;
      case "keybindings":
        children = await this.w.createInstance($FWb, profile).getChildren();
        break;
      case "snippets":
        children = await this.w.createInstance($IWb, profile).getChildren() ?? [];
        break;
      case "tasks":
        children = await this.w.createInstance($LWb, profile).getChildren();
        break;
      case "extensions":
        children = await this.w.createInstance($PWb, profile).getChildren();
        break;
    }
    return children.map((child) => this.L(child));
  }
  L(child, primaryActions, contextMenuActions) {
    return {
      handle: child.handle,
      checkbox: child.checkbox,
      label: child.label?.label ?? "",
      description: $zg(child.description) ? child.description : void 0,
      resource: URI.revive(child.resourceUri),
      icon: child.themeIcon,
      openAction: new $Um("_openChild", localize(11640, null), ThemeIcon.asClassName($6l.goToFile), true, async () => {
        if (child.parent.type === "extensions") {
          await this.j.executeCommand("extension.open", child.handle, void 0, true, void 0, true);
        } else if (child.resourceUri) {
          await this.j.executeCommand($$ub, child.resourceUri, [$oJ], void 0);
        }
      }),
      actions: {
        primary: primaryActions,
        contextMenu: contextMenuActions
      }
    };
  }
  getInitialName() {
    return "";
  }
  shouldValidateName() {
    return true;
  }
  getCurrentWorkspace() {
    const workspace2 = this.m.getWorkspace();
    return workspace2.configuration ?? workspace2.folders[0]?.uri;
  }
  openWorkspace(workspace2) {
    if (this.s.extUri.extname(workspace2) === $bl) {
      this.n.openWindow([{ workspaceUri: workspace2 }], { forceNewWindow: true });
    } else {
      this.n.openWindow([{ folderUri: workspace2 }], { forceNewWindow: true });
    }
  }
  save() {
    this.f.schedule();
  }
  M(profile) {
    if (this.name !== profile.name) {
      return true;
    }
    if (this.icon !== profile.icon) {
      return true;
    }
    if (!$Pv(this.flags ?? {}, profile.useDefaultFlags ?? {})) {
      return true;
    }
    if (!$zb(this.workspaces ?? [], profile.workspaces ?? [], (a, b) => a.toString() === b.toString())) {
      return true;
    }
    return false;
  }
  async N(profile) {
    if (!this.M(profile)) {
      return;
    }
    this.validate();
    if (this.message) {
      return;
    }
    const useDefaultFlags = this.flags ? this.flags.settings && this.flags.keybindings && this.flags.tasks && this.flags.globalState && this.flags.extensions ? void 0 : this.flags : void 0;
    return await this.g.updateProfile(profile, {
      name: this.name,
      icon: this.icon,
      useDefaultFlags: profile.useDefaultFlags && !useDefaultFlags ? {} : useDefaultFlags,
      workspaces: this.workspaces
    });
  }
};
$4jc = __decorate([
  __param(5, $hT),
  __param(6, $rs),
  __param(7, $sn),
  __param(8, $Zk),
  __param(9, $S4),
  __param(10, $vl),
  __param(11, $km),
  __param(12, $pzb),
  __param(13, $Pk)
], $4jc);
var $5jc = class $5jc2 extends $4jc {
  get profile() {
    return this.Q;
  }
  constructor(Q, titleButtons, actions, R, S, userDataProfileManagementService, userDataProfilesService, commandService, workspaceContextService, hostService, uriIdentityService, fileService, extensionManagementService, instantiationService) {
    super(Q.name, Q.icon, Q.useDefaultFlags, Q.workspaces, R.currentProfile.id === Q.id, userDataProfileManagementService, userDataProfilesService, commandService, workspaceContextService, hostService, uriIdentityService, fileService, extensionManagementService, instantiationService);
    this.Q = Q;
    this.titleButtons = titleButtons;
    this.actions = actions;
    this.R = R;
    this.S = S;
    this.W = false;
    this.W = this.S.getValue($2L) === this.profile.name;
    this.B(S.onDidChangeConfiguration((e) => {
      if (e.affectsConfiguration($2L)) {
        this.isNewWindowProfile = this.S.getValue($2L) === this.profile.name;
      }
    }));
    this.B(this.R.onDidChangeCurrentProfile(() => this.active = this.R.currentProfile.id === this.profile.id));
    this.B(this.h.onDidChangeProfiles(({ updated }) => {
      const profile = updated.find((p) => p.id === this.profile.id);
      if (profile) {
        this.Q = profile;
        this.reset();
        this.c.fire({ profile: true });
      }
    }));
    this.B(fileService.watch(this.profile.snippetsHome));
    this.B(fileService.onDidFilesChange((e) => {
      if (e.affects(this.profile.snippetsHome)) {
        this.c.fire({ snippets: true });
      }
    }));
  }
  P() {
    return this.profile;
  }
  reset() {
    this.name = this.Q.name;
    this.icon = this.Q.icon;
    this.flags = this.Q.useDefaultFlags;
    this.workspaces = this.Q.workspaces;
  }
  updateWorkspaces(toAdd, toRemove) {
    const workspaces = new $Fc(this.workspaces ?? []);
    for (const workspace2 of toAdd) {
      workspaces.add(workspace2);
    }
    for (const workspace2 of toRemove) {
      workspaces.delete(workspace2);
    }
    this.workspaces = [...workspaces.values()];
  }
  async toggleNewWindowProfile() {
    if (this.W) {
      await this.S.updateValue($2L, null);
    } else {
      await this.S.updateValue($2L, this.profile.name);
    }
  }
  get isNewWindowProfile() {
    return this.W;
  }
  set isNewWindowProfile(isNewWindowProfile) {
    if (this.W !== isNewWindowProfile) {
      this.W = isNewWindowProfile;
      this.c.fire({ newWindowProfile: true });
    }
  }
  async toggleCurrentWindowProfile() {
    if (this.R.currentProfile.id === this.profile.id) {
      await this.g.switchProfile(this.h.defaultProfile);
    } else {
      await this.g.switchProfile(this.profile);
    }
  }
  async O() {
    await this.N(this.profile);
  }
  async I(resourceType) {
    if (resourceType === "extensions") {
      const children = await this.w.createInstance($PWb, this.profile).getChildren();
      return children.map((child) => this.L(child, void 0, [{
        id: "applyToAllProfiles",
        label: localize(11641, null),
        checked: child.applicationScoped,
        enabled: true,
        class: "",
        tooltip: "",
        run: async () => {
          const extensions = await this.u.getInstalled(void 0, this.profile.extensionsResource);
          const extension = extensions.find((e) => $DA(e.identifier, child.identifier));
          if (extension) {
            await this.u.toggleAppliationScope(extension, this.profile.extensionsResource);
          }
        }
      }]));
    }
    return this.J(this.profile, resourceType);
  }
  getInitialName() {
    return this.profile.name;
  }
};
$5jc = __decorate([
  __param(3, $gT),
  __param(4, $kl),
  __param(5, $hT),
  __param(6, $rs),
  __param(7, $sn),
  __param(8, $Zk),
  __param(9, $S4),
  __param(10, $vl),
  __param(11, $km),
  __param(12, $pzb),
  __param(13, $Pk)
], $5jc);
var USER_DATA_PROFILE_TEMPLATE_PREVIEW_SCHEME = "userdataprofiletemplatepreview";
var $6jc = class $6jc2 extends $4jc {
  get copyFromTemplates() {
    return this.Q;
  }
  constructor(name, copyFrom, titleButtons, actions, X, userDataProfileManagementService, userDataProfilesService, commandService, workspaceContextService, hostService, uriIdentityService, fileService, extensionManagementService, instantiationService) {
    super(name, void 0, void 0, void 0, false, userDataProfileManagementService, userDataProfilesService, commandService, workspaceContextService, hostService, uriIdentityService, fileService, extensionManagementService, instantiationService);
    this.titleButtons = titleButtons;
    this.actions = actions;
    this.X = X;
    this.Q = new $Ec();
    this.S = null;
    this.$ = this.B(new $2c());
    this.U = name;
    this.Y = copyFrom;
    this.Z = this.cb(copyFrom);
    this.db();
    this.B(this.t.registerProvider(USER_DATA_PROFILE_TEMPLATE_PREVIEW_SCHEME, this.B(new $WWb())));
    this.B($1c(() => {
      if (this.previewProfile) {
        this.h.removeProfile(this.previewProfile);
      }
    }));
  }
  get copyFrom() {
    return this.Y;
  }
  set copyFrom(copyFrom) {
    if (this.Y !== copyFrom) {
      this.Y = copyFrom;
      this.c.fire({ copyFrom: true });
      this.flags = void 0;
      this.copyFlags = this.cb(copyFrom);
      if (copyFrom instanceof URI) {
        this.R?.cancel();
        this.R = void 0;
      }
      this.db();
    }
  }
  get copyFlags() {
    return this.Z;
  }
  set copyFlags(flags) {
    if (!$Pv(this.Z, flags)) {
      this.Z = flags;
      this.c.fire({ copyFlags: true });
    }
  }
  get previewProfile() {
    return this.ab;
  }
  set previewProfile(profile) {
    if (this.ab !== profile) {
      this.ab = profile;
      this.c.fire({ preview: true });
      this.$.clear();
      if (this.ab) {
        this.$.add(this.t.watch(this.ab.snippetsHome));
        this.$.add(this.t.onDidFilesChange((e) => {
          if (!this.ab) {
            return;
          }
          if (e.affects(this.ab.snippetsHome)) {
            this.c.fire({ snippets: true });
          }
        }));
      }
    }
  }
  P() {
    return this.previewProfile;
  }
  cb(copyFrom) {
    return copyFrom ? {
      settings: true,
      keybindings: true,
      snippets: true,
      tasks: true,
      extensions: true
    } : void 0;
  }
  async db() {
    this.disabled = true;
    try {
      if (this.copyFrom instanceof URI) {
        await this.resolveTemplate(this.copyFrom);
        if (this.S) {
          this.copyFromTemplates.set(this.copyFrom, this.S.name);
          if (this.U === this.name) {
            this.name = this.U = this.S.name ?? "";
          }
          if (this.W === this.icon) {
            this.icon = this.W = this.S.icon;
          }
          this.setCopyFlag("settings", !!this.S.settings);
          this.setCopyFlag("keybindings", !!this.S.keybindings);
          this.setCopyFlag("tasks", !!this.S.tasks);
          this.setCopyFlag("snippets", !!this.S.snippets);
          this.setCopyFlag("extensions", !!this.S.extensions);
          this.c.fire({ copyFromInfo: true });
        }
        return;
      }
      if ($qs(this.copyFrom)) {
        if (this.U === this.name) {
          this.name = this.U = localize(11642, null, this.copyFrom.name);
        }
        if (this.W === this.icon) {
          this.icon = this.W = this.copyFrom.icon;
        }
        this.setCopyFlag("settings", true);
        this.setCopyFlag("keybindings", true);
        this.setCopyFlag("tasks", true);
        this.setCopyFlag("snippets", true);
        this.setCopyFlag("extensions", true);
        this.c.fire({ copyFromInfo: true });
        return;
      }
      if (this.U === this.name) {
        this.name = this.U = localize(11643, null);
      }
      if (this.W === this.icon) {
        this.icon = this.W = void 0;
      }
      this.setCopyFlag("settings", false);
      this.setCopyFlag("keybindings", false);
      this.setCopyFlag("tasks", false);
      this.setCopyFlag("snippets", false);
      this.setCopyFlag("extensions", false);
      this.c.fire({ copyFromInfo: true });
    } finally {
      this.disabled = false;
    }
  }
  async resolveTemplate(uri) {
    if (!this.R) {
      this.R = $Hh(async (token) => {
        const template = await this.X.resolveProfileTemplate(uri);
        if (!token.isCancellationRequested) {
          this.S = template;
        }
      });
    }
    await this.R;
    return this.S;
  }
  hasResource(resourceType) {
    if (this.S) {
      switch (resourceType) {
        case "settings":
          return !!this.S.settings;
        case "keybindings":
          return !!this.S.keybindings;
        case "snippets":
          return !!this.S.snippets;
        case "tasks":
          return !!this.S.tasks;
        case "extensions":
          return !!this.S.extensions;
      }
    }
    return true;
  }
  getCopyFlag(key2) {
    return this.copyFlags?.[key2] ?? false;
  }
  setCopyFlag(key2, value) {
    const flags = this.copyFlags ? { ...this.copyFlags } : {};
    flags[key2] = value;
    this.copyFlags = flags;
  }
  getCopyFromName() {
    if ($qs(this.copyFrom)) {
      return this.copyFrom.name;
    }
    if (this.copyFrom instanceof URI) {
      return this.copyFromTemplates.get(this.copyFrom);
    }
    return void 0;
  }
  async I(resourceType) {
    if (this.getFlag(resourceType)) {
      return this.J(this.h.defaultProfile, resourceType);
    }
    if (!this.getCopyFlag(resourceType)) {
      return [];
    }
    if (this.previewProfile) {
      return this.J(this.previewProfile, resourceType);
    }
    if (this.copyFrom instanceof URI) {
      await this.resolveTemplate(this.copyFrom);
      if (!this.S) {
        return [];
      }
      return this.fb(this.S, resourceType);
    }
    if (this.copyFrom) {
      return this.J(this.copyFrom, resourceType);
    }
    return [];
  }
  async fb(profileTemplate, resourceType) {
    const location3 = URI.from({ scheme: USER_DATA_PROFILE_TEMPLATE_PREVIEW_SCHEME, path: `/root/profiles/${profileTemplate.name}` });
    const cacheLocation = URI.from({ scheme: USER_DATA_PROFILE_TEMPLATE_PREVIEW_SCHEME, path: `/root/cache/${profileTemplate.name}` });
    const profile = $ts($ps(), this.name, location3, cacheLocation);
    switch (resourceType) {
      case "settings":
        if (profileTemplate.settings) {
          await this.w.createInstance($BWb).apply(profileTemplate.settings, profile);
          return this.J(profile, resourceType);
        }
        return [];
      case "keybindings":
        if (profileTemplate.keybindings) {
          await this.w.createInstance($EWb).apply(profileTemplate.keybindings, profile);
          return this.J(profile, resourceType);
        }
        return [];
      case "snippets":
        if (profileTemplate.snippets) {
          await this.w.createInstance($HWb).apply(profileTemplate.snippets, profile);
          return this.J(profile, resourceType);
        }
        return [];
      case "tasks":
        if (profileTemplate.tasks) {
          await this.w.createInstance($KWb).apply(profileTemplate.tasks, profile);
          return this.J(profile, resourceType);
        }
        return [];
      case "extensions":
        if (profileTemplate.extensions) {
          const children = await this.w.createInstance($QWb, profileTemplate.extensions).getChildren();
          return children.map((child) => this.L(child));
        }
        return [];
    }
    return [];
  }
  shouldValidateName() {
    return !this.copyFrom;
  }
  getInitialName() {
    return this.previewProfile?.name ?? "";
  }
  async O() {
    if (this.previewProfile) {
      const profile = await this.N(this.previewProfile);
      if (profile) {
        this.previewProfile = profile;
      }
    }
  }
};
$6jc = __decorate([
  __param(4, $nT),
  __param(5, $hT),
  __param(6, $rs),
  __param(7, $sn),
  __param(8, $Zk),
  __param(9, $S4),
  __param(10, $vl),
  __param(11, $km),
  __param(12, $pzb),
  __param(13, $Pk)
], $6jc);
var $7jc = class $7jc2 extends $rG {
  static {
    $7jc_1 = this;
  }
  static getInstance(instantiationService) {
    if (!$7jc_1.c) {
      $7jc_1.c = instantiationService.createInstance($7jc_1);
    }
    return $7jc_1.c;
  }
  get profiles() {
    return this.g.map(([profile]) => profile).sort((a, b) => {
      if (a instanceof $6jc) {
        return 1;
      }
      if (b instanceof $6jc) {
        return -1;
      }
      if (a instanceof $5jc && a.profile.isDefault) {
        return -1;
      }
      if (b instanceof $5jc && b.profile.isDefault) {
        return 1;
      }
      return a.name.localeCompare(b.name);
    });
  }
  constructor(s, t, u, w, y, z, C, D, F, G) {
    super();
    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 = G;
    this.g = [];
    this.m = this.B(new $ze());
    this.onDidChange = this.m.event;
    for (const profile of t.profiles) {
      if (!profile.isTransient) {
        this.g.push(this.I(profile));
      }
    }
    this.B($1c(() => this.g.splice(0, this.g.length).map(([, disposables]) => disposables.dispose())));
    this.B(t.onDidChangeProfiles((e) => this.H(e)));
  }
  H(e) {
    let changed = false;
    for (const profile of e.added) {
      if (!profile.isTransient && profile.name !== this.j?.name) {
        changed = true;
        this.g.push(this.I(profile));
      }
    }
    for (const profile of e.removed) {
      if (profile.id === this.j?.previewProfile?.id) {
        this.j.previewProfile = void 0;
      }
      const index = this.g.findIndex(([p]) => p instanceof $5jc && p.profile.id === profile.id);
      if (index !== -1) {
        changed = true;
        this.g.splice(index, 1).map(([, disposables]) => disposables.dispose());
      }
    }
    if (changed) {
      this.m.fire(void 0);
    }
  }
  getTemplates() {
    if (!this.n) {
      this.n = this.u.getBuiltinProfileTemplates();
    }
    return this.n;
  }
  I(profile) {
    const disposables = new $2c();
    const activateAction = disposables.add(new $Um("userDataProfile.activate", localize(11644, null), ThemeIcon.asClassName($6l.check), true, () => this.u.switchProfile(profileElement.profile)));
    const copyFromProfileAction = disposables.add(new $Um("userDataProfile.copyFromProfile", localize(11645, null), ThemeIcon.asClassName($6l.copy), true, () => this.createNewProfile(profileElement.profile)));
    const exportAction = disposables.add(new $Um("userDataProfile.export", localize(11646, null), ThemeIcon.asClassName($6l.export), true, () => this.w.exportProfile(profile)));
    const deleteAction = disposables.add(new $Um("userDataProfile.delete", localize(11647, null), ThemeIcon.asClassName($6l.trash), true, () => this.O(profileElement.profile)));
    const newWindowAction = disposables.add(new $Um("userDataProfile.newWindow", localize(11648, null), ThemeIcon.asClassName($6l.emptyWindow), true, () => this.P(profileElement.profile)));
    const primaryActions = [];
    primaryActions.push(activateAction);
    primaryActions.push(newWindowAction);
    const secondaryActions = [];
    secondaryActions.push(copyFromProfileAction);
    secondaryActions.push(exportAction);
    if (!profile.isDefault) {
      secondaryActions.push(new $Wm());
      secondaryActions.push(deleteAction);
    }
    const profileElement = disposables.add(this.G.createInstance($5jc, profile, [[], []], [primaryActions, secondaryActions]));
    activateAction.enabled = this.s.currentProfile.id !== profileElement.profile.id;
    disposables.add(this.s.onDidChangeCurrentProfile(() => activateAction.enabled = this.s.currentProfile.id !== profileElement.profile.id));
    return [profileElement, disposables];
  }
  async createNewProfile(copyFrom) {
    if (this.j) {
      const result = await this.y.confirm({
        type: "info",
        message: localize(11649, null),
        primaryButton: localize(11650, null),
        cancelButton: localize(11651, null)
      });
      if (!result.confirmed) {
        return;
      }
      this.revert();
    }
    if (copyFrom instanceof URI) {
      try {
        await this.w.resolveProfileTemplate(copyFrom);
      } catch (error) {
        this.y.error($qb(error));
        return;
      }
    }
    if (!this.j) {
      const disposables = new $2c();
      const cancellationTokenSource = new $ad();
      disposables.add($1c(() => cancellationTokenSource.dispose(true)));
      const primaryActions = [];
      const secondaryActions = [];
      const createAction = disposables.add(new $Um("userDataProfile.create", localize(11652, null), void 0, true, () => this.saveNewProfile(false, cancellationTokenSource.token)));
      primaryActions.push(createAction);
      if ($r && copyFrom instanceof URI && $mT(copyFrom)) {
        primaryActions.push(new $Um("userDataProfile.createInDesktop", localize(11653, null, this.D.nameLong), void 0, true, () => this.F.open(copyFrom, { openExternal: true })));
      }
      const cancelAction = disposables.add(new $Um("userDataProfile.cancel", localize(11654, null), ThemeIcon.asClassName($6l.trash), true, () => this.N()));
      secondaryActions.push(cancelAction);
      const previewProfileAction = disposables.add(new $Um("userDataProfile.preview", localize(11655, null), ThemeIcon.asClassName($6l.openPreview), true, () => this.L(cancellationTokenSource.token)));
      secondaryActions.push(previewProfileAction);
      const exportAction = disposables.add(new $Um("userDataProfile.export", localize(11656, null), ThemeIcon.asClassName($6l.export), $qs(copyFrom), () => this.M(cancellationTokenSource.token)));
      this.j = disposables.add(this.G.createInstance($6jc, copyFrom ? "" : localize(11657, null), copyFrom, [primaryActions, secondaryActions], [[cancelAction], [exportAction]]));
      const updateCreateActionLabel = () => {
        if (createAction.enabled) {
          if (this.j?.copyFrom && this.t.profiles.some((p) => !p.isTransient && p.name === this.j?.name)) {
            createAction.label = localize(11658, null);
          } else {
            createAction.label = localize(11659, null);
          }
        }
      };
      updateCreateActionLabel();
      disposables.add(this.j.onDidChange((e) => {
        if (e.preview || e.disabled || e.message) {
          createAction.enabled = !this.j?.disabled && !this.j?.message;
          previewProfileAction.enabled = !this.j?.previewProfile && !this.j?.disabled && !this.j?.message;
        }
        if (e.name || e.copyFrom) {
          updateCreateActionLabel();
          exportAction.enabled = $qs(this.j?.copyFrom);
        }
      }));
      disposables.add(this.t.onDidChangeProfiles((e) => {
        updateCreateActionLabel();
        this.j?.validate();
      }));
      this.g.push([this.j, disposables]);
      this.m.fire(this.j);
    }
    return this.j;
  }
  revert() {
    this.J();
    this.m.fire(void 0);
  }
  J() {
    if (this.j) {
      const index = this.g.findIndex(([p]) => p === this.j);
      if (index !== -1) {
        this.g.splice(index, 1).map(([, disposables]) => disposables.dispose());
      }
      this.j = void 0;
    }
  }
  async L(token) {
    if (!this.j) {
      return;
    }
    if (this.j.previewProfile) {
      return;
    }
    const profile = await this.saveNewProfile(true, token);
    if (profile) {
      this.j.previewProfile = profile;
      if ($r) {
        await this.u.switchProfile(profile);
      } else {
        await this.P(profile);
      }
    }
  }
  async M(token) {
    if (!this.j) {
      return;
    }
    if (!$qs(this.j.copyFrom)) {
      return;
    }
    const profile = $ts($ps(), this.j.name, this.j.copyFrom.location, this.j.copyFrom.cacheHome, {
      icon: this.j.icon,
      useDefaultFlags: this.j.flags
    }, this.t.defaultProfile);
    await this.w.exportProfile(profile, this.j.copyFlags);
  }
  async saveNewProfile(transient, token) {
    if (!this.j) {
      return void 0;
    }
    this.j.validate();
    if (this.j.message) {
      return void 0;
    }
    this.j.disabled = true;
    let profile;
    try {
      if (this.j.previewProfile) {
        if (!transient) {
          profile = await this.u.updateProfile(this.j.previewProfile, { transient: false });
        }
      } else {
        const { flags, icon: icon2, name, copyFrom } = this.j;
        const useDefaultFlags = flags ? flags.settings && flags.keybindings && flags.tasks && flags.globalState && flags.extensions ? void 0 : flags : void 0;
        const createProfileTelemetryData = { source: copyFrom instanceof URI ? "template" : $qs(copyFrom) ? "profile" : copyFrom ? "external" : void 0 };
        if (copyFrom instanceof URI) {
          const template = await this.j.resolveTemplate(copyFrom);
          if (template) {
            this.z.publicLog2("userDataProfile.createFromTemplate", createProfileTelemetryData);
            profile = await this.w.createProfileFromTemplate(template, {
              name,
              useDefaultFlags,
              icon: icon2,
              resourceTypeFlags: this.j.copyFlags,
              transient
            }, token ?? CancellationToken.None);
          }
        } else if ($qs(copyFrom)) {
          this.z.publicLog2("userDataProfile.createFromProfile", createProfileTelemetryData);
          profile = await this.w.createFromProfile(copyFrom, {
            name,
            useDefaultFlags,
            icon: icon2,
            resourceTypeFlags: this.j.copyFlags,
            transient
          }, token ?? CancellationToken.None);
        } else {
          this.z.publicLog2("userDataProfile.createEmptyProfile", createProfileTelemetryData);
          profile = await this.u.createProfile(name, { useDefaultFlags, icon: icon2, transient });
        }
      }
    } finally {
      if (this.j) {
        this.j.disabled = false;
      }
    }
    if (token?.isCancellationRequested) {
      if (profile) {
        try {
          await this.u.removeProfile(profile);
        } catch (error) {
        }
      }
      return;
    }
    if (profile && !profile.isTransient && this.j) {
      this.J();
      const existing = this.g.find(([p]) => p.name === profile.name);
      if (existing) {
        this.m.fire(existing[0]);
      } else {
        this.H({ added: [profile], removed: [], updated: [], all: this.t.profiles });
      }
    }
    return profile;
  }
  async N() {
    if (!this.j) {
      return;
    }
    if (this.j.previewProfile) {
      await this.u.removeProfile(this.j.previewProfile);
      return;
    }
    this.J();
    this.m.fire(void 0);
  }
  async O(profile) {
    const result = await this.y.confirm({
      type: "info",
      message: localize(11660, null, profile.name),
      primaryButton: localize(11661, null),
      cancelButton: localize(11662, null)
    });
    if (result.confirmed) {
      await this.u.removeProfile(profile);
    }
  }
  async P(profile) {
    await this.C.openWindow({ forceProfile: profile.name });
  }
};
$7jc = $7jc_1 = __decorate([
  __param(0, $gT),
  __param(1, $rs),
  __param(2, $hT),
  __param(3, $nT),
  __param(4, $Yv),
  __param(5, $zv),
  __param(6, $S4),
  __param(7, $Vu),
  __param(8, $O4),
  __param(9, $Pk)
], $7jc);

// out-build/vs/base/browser/ui/radio/radio.js
var $$2 = class extends $qZ {
  constructor(opts) {
    super();
    this.a = this.B(new $ze());
    this.onDidSelect = this.a.event;
    this.g = [];
    this.n = this.B(new $_c());
    this.c = opts.hoverDelegate ?? this.B($KZ());
    this.domNode = $(".monaco-custom-radio");
    this.domNode.setAttribute("role", "radio");
    this.setItems(opts.items);
  }
  setItems(items) {
    this.n.clearAndDisposeAll();
    this.g = items;
    this.h = this.g.find((item) => item.isActive) ?? this.g[0];
    for (let index = 0; index < this.g.length; index++) {
      const item = this.g[index];
      const disposables = new $2c();
      const button = disposables.add(new $k2(this.domNode, {
        hoverDelegate: this.c,
        title: item.tooltip,
        supportIcons: true
      }));
      button.enabled = !item.disabled;
      disposables.add(button.onDidClick(() => {
        if (this.h !== item) {
          this.h = item;
          this.r();
          this.a.fire(index);
        }
      }));
      this.n.set(button, { item, dispose: () => disposables.dispose() });
    }
    this.r();
  }
  setActiveItem(index) {
    if (index < 0 || index >= this.g.length) {
      throw new Error("Invalid Index");
    }
    this.h = this.g[index];
    this.r();
  }
  setEnabled(enabled) {
    for (const [button] of this.n) {
      button.enabled = enabled;
    }
  }
  r() {
    let isActive2 = false;
    for (const [button, { item }] of this.n) {
      const isPreviousActive = isActive2;
      isActive2 = item === this.h;
      button.element.classList.toggle("active", isActive2);
      button.element.classList.toggle("previous-active", isPreviousActive);
      button.label = item.text;
    }
  }
};

// out-build/vs/workbench/contrib/userDataProfile/browser/userDataProfilesEditor.js
var $9jc_1;
var ExistingProfileResourceTreeRenderer_1;
var NewProfileResourceTreeRenderer_1;
var ProfileResourceChildTreeItemRenderer_1;
var WorkspaceUriHostColumnRenderer_1;
var WorkspaceUriPathColumnRenderer_1;
var WorkspaceUriActionsColumnRenderer_1;
var $0jc_1;
var editIcon = $9r("profiles-editor-edit-folder", $6l.edit, localize(11557, null));
var removeIcon = $9r("profiles-editor-remove-folder", $6l.close, localize(11558, null));
var $8jc = $5n("profiles.sashBorder", $Jmb, localize(11559, null));
var listStyles = $J$({
  listActiveSelectionBackground: $Ko,
  listActiveSelectionForeground: $eo,
  listFocusAndSelectionBackground: $Ko,
  listFocusAndSelectionForeground: $eo,
  listFocusBackground: $Ko,
  listFocusForeground: $eo,
  listHoverForeground: $eo,
  listHoverBackground: $Ko,
  listHoverOutline: $Ko,
  listFocusOutline: $Ko,
  listInactiveSelectionBackground: $Ko,
  listInactiveSelectionForeground: $eo,
  listInactiveFocusBackground: $Ko,
  listInactiveFocusOutline: $Ko,
  treeIndentGuidesStroke: void 0,
  treeInactiveIndentGuidesStroke: void 0,
  tableOddRowsBackgroundColor: $Ko
});
var $9jc = class $9jc2 extends $5tb {
  static {
    $9jc_1 = this;
  }
  static {
    this.ID = "workbench.editor.userDataProfiles";
  }
  constructor(group2, telemetryService, themeService, storageService, s, u, cb, db) {
    super($9jc_1.ID, group2, telemetryService, themeService, storageService);
    this.s = s;
    this.u = u;
    this.cb = cb;
    this.db = db;
    this.r = [];
  }
  layout(dimension, position) {
    if (this.c && this.f) {
      const height = dimension.height - 20;
      this.f.layout(this.c?.clientWidth, height);
      this.f.el.style.height = `${height}px`;
    }
  }
  Y(parent) {
    this.c = $bk(parent, $(".profiles-editor"));
    const sidebarView = $bk(this.c, $(".sidebar-view"));
    const sidebarContainer = $bk(sidebarView, $(".sidebar-container"));
    const contentsView = $bk(this.c, $(".contents-view"));
    const contentsContainer = $bk(contentsView, $(".contents-container"));
    this.j = this.B(this.db.createInstance(ProfileWidget, contentsContainer));
    this.f = new $r2(this.c, {
      orientation: 1,
      proportionalLayout: true
    });
    this.fb(sidebarContainer);
    this.f.addView({
      onDidChange: Event2.None,
      element: sidebarView,
      minimumSize: 200,
      maximumSize: 350,
      layout: (width2, _, height) => {
        sidebarView.style.width = `${width2}px`;
        if (height && this.g) {
          const listHeight = height - 40 - 15;
          this.g.getHTMLElement().style.height = `${listHeight}px`;
          this.g.layout(listHeight, width2);
        }
      }
    }, 300, void 0, true);
    this.f.addView({
      onDidChange: Event2.None,
      element: contentsView,
      minimumSize: 550,
      maximumSize: Number.POSITIVE_INFINITY,
      layout: (width2, _, height) => {
        contentsView.style.width = `${width2}px`;
        if (height) {
          this.j?.layout(new $rj(width2, height));
        }
      }
    }, Sizing.Distribute, void 0, true);
    this.ib();
    this.updateStyles();
  }
  updateStyles() {
    const borderColor = this.h.getColor($8jc);
    this.f?.style({ separatorBorder: borderColor });
  }
  fb(parent) {
    this.gb($bk(parent, $(".new-profile-button")));
    const renderer = this.db.createInstance(ProfileElementRenderer);
    const delegate = new ProfileElementDelegate();
    this.g = this.B(this.db.createInstance($Web, "ProfilesList", $bk(parent, $(".profiles-list")), delegate, [renderer], {
      multipleSelectionSupport: false,
      setRowLineHeight: false,
      horizontalScrolling: false,
      accessibilityProvider: {
        getAriaLabel(profileElement) {
          return profileElement?.name ?? "";
        },
        getWidgetAriaLabel() {
          return localize(11560, null);
        }
      },
      openOnSingleClick: true,
      identityProvider: {
        getId(e) {
          if (e instanceof $5jc) {
            return e.profile.id;
          }
          return e.name;
        }
      },
      alwaysConsumeMouseWheel: false
    }));
  }
  gb(parent) {
    const button = this.B(new $l2(parent, {
      actions: {
        getActions: () => {
          const actions = [];
          if (this.r.length) {
            actions.push(new $Xm("from.template", localize(11561, null), this.hb()));
            actions.push(new $Wm());
          }
          actions.push(new $Um("importProfile", localize(11562, null), void 0, true, () => this.kb()));
          return actions;
        }
      },
      addPrimaryActionToDropdown: false,
      contextMenuProvider: this.cb,
      supportIcons: true,
      ...$q$
    }));
    button.label = localize(11563, null);
    this.B(button.onDidClick((e) => this.createNewProfile()));
  }
  hb() {
    return this.r.map((template) => new $Um(`template:${template.url}`, template.name, void 0, true, () => this.createNewProfile(URI.parse(template.url))));
  }
  ib() {
    if (this.g) {
      this.B(this.g.onDidChangeSelection((e) => {
        const [element] = e.elements;
        if (element instanceof $4jc) {
          this.j?.render(element);
        }
      }));
      this.B(this.g.onContextMenu((e) => {
        const actions = [];
        if (!e.element) {
          actions.push(...this.jb());
        }
        if (e.element instanceof $4jc) {
          actions.push(...e.element.actions[1]);
        }
        if (actions.length) {
          this.cb.showContextMenu({
            getAnchor: () => e.anchor,
            getActions: () => actions,
            getActionsContext: () => e.element
          });
        }
      }));
      this.B(this.g.onMouseDblClick((e) => {
        if (!e.element) {
          this.createNewProfile();
        }
      }));
    }
  }
  jb() {
    const actions = [];
    actions.push(new $Um("newProfile", localize(11564, null), void 0, true, () => this.createNewProfile()));
    const templateActions = this.hb();
    if (templateActions.length) {
      actions.push(new $Xm("from.template", localize(11565, null), templateActions));
    }
    actions.push(new $Wm());
    actions.push(new $Um("importProfile", localize(11566, null), void 0, true, () => this.kb()));
    return actions;
  }
  async kb() {
    const disposables = new $2c();
    const quickPick = disposables.add(this.s.createQuickPick());
    const updateQuickPickItems = (value) => {
      const quickPickItems = [];
      if (value) {
        quickPickItems.push({ label: quickPick.value, description: localize(11567, null) });
      }
      quickPickItems.push({ label: localize(11568, null) });
      quickPick.items = quickPickItems;
    };
    quickPick.title = localize(11569, null);
    quickPick.placeholder = localize(11570, null);
    quickPick.ignoreFocusOut = true;
    disposables.add(quickPick.onDidChangeValue(updateQuickPickItems));
    updateQuickPickItems();
    quickPick.matchOnLabel = false;
    quickPick.matchOnDescription = false;
    disposables.add(quickPick.onDidAccept(async () => {
      quickPick.hide();
      const selectedItem = quickPick.selectedItems[0];
      if (!selectedItem) {
        return;
      }
      const url = selectedItem.label === quickPick.value ? URI.parse(quickPick.value) : await this.lb();
      if (url) {
        this.createNewProfile(url);
      }
    }));
    disposables.add(quickPick.onDidHide(() => disposables.dispose()));
    quickPick.show();
  }
  async createNewProfile(copyFrom) {
    await this.m?.createNewProfile(copyFrom);
  }
  selectProfile(profile) {
    const index = this.m?.profiles.findIndex((p) => p instanceof $5jc && p.profile.id === profile.id);
    if (index !== void 0 && index >= 0) {
      this.g?.setSelection([index]);
    }
  }
  async lb() {
    const profileLocation = await this.u.showOpenDialog({
      canSelectFolders: false,
      canSelectFiles: true,
      canSelectMany: false,
      filters: $sT,
      title: localize(11571, null)
    });
    if (!profileLocation) {
      return null;
    }
    return profileLocation[0];
  }
  async setInput(input, options3, context, token) {
    await super.setInput(input, options3, context, token);
    this.m = await input.resolve();
    this.m.getTemplates().then((templates) => {
      this.r = templates;
      if (this.j) {
        this.j.templates = templates;
      }
    });
    this.mb();
    this.B(this.m.onDidChange((element) => this.mb(element)));
  }
  focus() {
    super.focus();
    this.g?.domFocus();
  }
  mb(elementToSelect) {
    if (!this.m) {
      return;
    }
    const currentSelectionIndex = this.g?.getSelection()?.[0];
    const currentSelection = currentSelectionIndex !== void 0 ? this.g?.element(currentSelectionIndex) : void 0;
    this.g?.splice(0, this.g.length, this.m.profiles);
    if (elementToSelect) {
      this.g?.setSelection([this.m.profiles.indexOf(elementToSelect)]);
    } else if (currentSelection) {
      if (!this.m.profiles.includes(currentSelection)) {
        const elementToSelect2 = this.m.profiles.find((profile) => profile.name === currentSelection.name) ?? this.m.profiles[0];
        if (elementToSelect2) {
          this.g?.setSelection([this.m.profiles.indexOf(elementToSelect2)]);
        }
      }
    } else {
      const elementToSelect2 = this.m.profiles.find((profile) => profile.active) ?? this.m.profiles[0];
      if (elementToSelect2) {
        this.g?.setSelection([this.m.profiles.indexOf(elementToSelect2)]);
      }
    }
  }
};
$9jc = $9jc_1 = __decorate([
  __param(1, $zv),
  __param(2, $gs),
  __param(3, $jv),
  __param(4, $1M),
  __param(5, $1v),
  __param(6, $50),
  __param(7, $Pk)
], $9jc);
var ProfileElementDelegate = class {
  getHeight(element) {
    return 22;
  }
  getTemplateId() {
    return "profileListElement";
  }
};
var ProfileElementRenderer = class ProfileElementRenderer2 {
  constructor(c) {
    this.c = c;
    this.templateId = "profileListElement";
  }
  renderTemplate(container2) {
    const disposables = new $2c();
    const elementDisposables = new $2c();
    container2.classList.add("profile-list-item");
    const icon2 = $bk(container2, $(".profile-list-item-icon"));
    const label3 = $bk(container2, $(".profile-list-item-label"));
    const dirty = $bk(container2, $(`span${ThemeIcon.asCSSSelector($6l.circleFilled)}`));
    const description = $bk(container2, $(".profile-list-item-description"));
    $bk(description, $(`span${ThemeIcon.asCSSSelector($6l.check)}`), $("span", void 0, localize(11572, null)));
    const actionsContainer = $bk(container2, $(".profile-tree-item-actions-container"));
    const actionBar = disposables.add(this.c.createInstance($3$, actionsContainer, {
      hoverDelegate: disposables.add($KZ()),
      highlightToggledItems: true
    }));
    return { label: label3, icon: icon2, dirty, description, actionBar, disposables, elementDisposables };
  }
  renderElement(element, index, templateData, height) {
    templateData.elementDisposables.clear();
    templateData.label.textContent = element.name;
    templateData.label.classList.toggle("new-profile", element instanceof $6jc);
    templateData.icon.className = ThemeIcon.asClassName(element.icon ? ThemeIcon.fromId(element.icon) : $VTb);
    templateData.dirty.classList.toggle("hide", !(element instanceof $6jc));
    templateData.description.classList.toggle("hide", !element.active);
    templateData.elementDisposables.add(element.onDidChange((e) => {
      if (e.name) {
        templateData.label.textContent = element.name;
      }
      if (e.icon) {
        if (element.icon) {
          templateData.icon.className = ThemeIcon.asClassName(ThemeIcon.fromId(element.icon));
        } else {
          templateData.icon.className = "hide";
        }
      }
      if (e.active) {
        templateData.description.classList.toggle("hide", !element.active);
      }
    }));
    const setActions = () => templateData.actionBar.setActions(element.actions[0].filter((a) => a.enabled), element.actions[1].filter((a) => a.enabled));
    setActions();
    const events = [];
    for (const action of element.actions.flat()) {
      if (action instanceof $Um) {
        events.push(action.onDidChange);
      }
    }
    templateData.elementDisposables.add(Event2.any(...events)((e) => {
      if (e.enabled !== void 0) {
        setActions();
      }
    }));
  }
  disposeElement(element, index, templateData, height) {
    templateData.elementDisposables.clear();
  }
  disposeTemplate(templateData) {
    templateData.disposables.dispose();
    templateData.elementDisposables.dispose();
  }
};
ProfileElementRenderer = __decorate([
  __param(0, $Pk)
], ProfileElementRenderer);
var ProfileWidget = class ProfileWidget2 extends $3c {
  set templates(templates) {
    this.j.setTemplates(templates);
    this.h.rerender();
  }
  constructor(parent, r2, s) {
    super();
    this.r = r2;
    this.s = s;
    this.m = this.B(new $4c());
    this.n = [];
    const header = $bk(parent, $(".profile-header"));
    const title = $bk(header, $(".profile-title-container"));
    this.c = $bk(title, $(""));
    const body = $bk(parent, $(".profile-body"));
    const delegate = new ProfileTreeDelegate();
    const contentsRenderer = this.B(this.s.createInstance(ContentsProfileRenderer));
    const associationsRenderer = this.B(this.s.createInstance(ProfileWorkspacesRenderer));
    this.n.push(associationsRenderer);
    this.j = this.B(this.s.createInstance(CopyFromProfileRenderer));
    this.f = $bk(body, $(".profile-tree"));
    this.h = this.B(this.s.createInstance($4eb, "ProfileEditor-Tree", this.f, delegate, [
      this.B(this.s.createInstance(ProfileNameRenderer)),
      this.B(this.s.createInstance(ProfileIconRenderer)),
      this.B(this.s.createInstance(UseForCurrentWindowPropertyRenderer)),
      this.B(this.s.createInstance(UseAsDefaultProfileRenderer)),
      this.j,
      contentsRenderer,
      associationsRenderer
    ], this.s.createInstance(ProfileTreeDataSource), {
      multipleSelectionSupport: false,
      horizontalScrolling: false,
      accessibilityProvider: {
        getAriaLabel(element) {
          return element?.element ?? "";
        },
        getWidgetAriaLabel() {
          return "";
        }
      },
      identityProvider: {
        getId(element) {
          return element.element;
        }
      },
      expandOnlyOnTwistieClick: true,
      renderIndentGuides: RenderIndentGuides.None,
      enableStickyScroll: false,
      openOnSingleClick: false,
      setRowLineHeight: false,
      supportDynamicHeights: true,
      alwaysConsumeMouseWheel: false
    }));
    this.h.style(listStyles);
    this.B(contentsRenderer.onDidChangeContentHeight((e) => this.h.updateElementHeight(e, void 0)));
    this.B(associationsRenderer.onDidChangeContentHeight((e) => this.h.updateElementHeight(e, void 0)));
    this.B(contentsRenderer.onDidChangeSelection((e) => {
      if (e.selected) {
        this.h.setFocus([]);
        this.h.setSelection([]);
      }
    }));
    this.B(this.h.onDidChangeContentHeight((e) => {
      if (this.t) {
        this.layout(this.t);
      }
    }));
    this.B(this.h.onDidChangeSelection((e) => {
      if (e.elements.length) {
        contentsRenderer.clearSelection();
      }
    }));
    this.g = $bk(body, $(".profile-row-container.profile-button-container"));
  }
  layout(dimension) {
    this.t = dimension;
    const treeContentHeight = this.h.contentHeight;
    const height = Math.min(treeContentHeight, dimension.height - (this.m.value?.element instanceof $6jc ? 116 : 54));
    this.f.style.height = `${height}px`;
    this.h.layout(height, dimension.width);
    for (const participant of this.n) {
      participant.layout();
    }
  }
  render(profileElement) {
    if (this.m.value?.element === profileElement) {
      return;
    }
    if (this.m.value?.element instanceof $5jc) {
      this.m.value.element.reset();
    }
    this.h.setInput(profileElement);
    const disposables = new $2c();
    this.m.value = { element: profileElement, dispose: () => disposables.dispose() };
    this.c.textContent = profileElement.name;
    disposables.add(profileElement.onDidChange((e) => {
      if (e.name) {
        this.c.textContent = profileElement.name;
      }
    }));
    const [primaryTitleButtons, secondatyTitleButtons] = profileElement.titleButtons;
    if (primaryTitleButtons?.length || secondatyTitleButtons?.length) {
      this.g.classList.remove("hide");
      if (secondatyTitleButtons?.length) {
        for (const action of secondatyTitleButtons) {
          const button = disposables.add(new $k2(this.g, {
            ...$q$,
            secondary: true
          }));
          button.label = action.label;
          button.enabled = action.enabled;
          disposables.add(button.onDidClick(() => this.r.showWhile(action.run())));
          disposables.add(action.onDidChange((e) => {
            if (!$Gg(e.enabled)) {
              button.enabled = action.enabled;
            }
            if (!$Gg(e.label)) {
              button.label = action.label;
            }
          }));
        }
      }
      if (primaryTitleButtons?.length) {
        for (const action of primaryTitleButtons) {
          const button = disposables.add(new $k2(this.g, {
            ...$q$
          }));
          button.label = action.label;
          button.enabled = action.enabled;
          disposables.add(button.onDidClick(() => this.r.showWhile(action.run())));
          disposables.add(action.onDidChange((e) => {
            if (!$Gg(e.enabled)) {
              button.enabled = action.enabled;
            }
            if (!$Gg(e.label)) {
              button.label = action.label;
            }
          }));
          disposables.add(profileElement.onDidChange((e) => {
            if (e.message) {
              button.setTitle(profileElement.message ?? action.label);
              button.element.classList.toggle("error", !!profileElement.message);
            }
          }));
        }
      }
    } else {
      this.g.classList.add("hide");
    }
    if (profileElement instanceof $6jc) {
      this.h.focusFirst();
    }
    if (this.t) {
      this.layout(this.t);
    }
  }
};
ProfileWidget = __decorate([
  __param(1, $ZJ),
  __param(2, $Pk)
], ProfileWidget);
var ProfileTreeDelegate = class extends $m1 {
  getTemplateId({ element }) {
    return element;
  }
  hasDynamicHeight({ element }) {
    return element === "contents" || element === "workspaces";
  }
  d({ element, root }) {
    switch (element) {
      case "name":
        return 72;
      case "icon":
        return 68;
      case "copyFrom":
        return 90;
      case "useForCurrent":
      case "useAsDefault":
        return 68;
      case "contents":
        return 258;
      case "workspaces":
        return (root.workspaces ? root.workspaces.length * 24 + 30 : 0) + 112;
    }
  }
};
var ProfileTreeDataSource = class {
  hasChildren(element) {
    return element instanceof $4jc;
  }
  async getChildren(element) {
    if (element instanceof $4jc) {
      const children = [];
      if (element instanceof $6jc) {
        children.push({ element: "name", root: element });
        children.push({ element: "icon", root: element });
        children.push({ element: "copyFrom", root: element });
        children.push({ element: "contents", root: element });
      } else if (element instanceof $5jc) {
        if (!element.profile.isDefault) {
          children.push({ element: "name", root: element });
          children.push({ element: "icon", root: element });
        }
        children.push({ element: "useAsDefault", root: element });
        children.push({ element: "contents", root: element });
        children.push({ element: "workspaces", root: element });
      }
      return children;
    }
    return [];
  }
};
var ProfileContentTreeElementDelegate = class {
  getTemplateId(element) {
    if (!element.element.resourceType) {
      return ProfileResourceChildTreeItemRenderer.TEMPLATE_ID;
    }
    if (element.root instanceof $6jc) {
      return NewProfileResourceTreeRenderer.TEMPLATE_ID;
    }
    return ExistingProfileResourceTreeRenderer.TEMPLATE_ID;
  }
  getHeight(element) {
    return 24;
  }
};
var ProfileResourceTreeDataSource = class ProfileResourceTreeDataSource2 {
  constructor(c) {
    this.c = c;
  }
  hasChildren(element) {
    if (element instanceof $4jc) {
      return true;
    }
    if (element.element.resourceType) {
      if (element.element.resourceType !== "extensions" && element.element.resourceType !== "snippets") {
        return false;
      }
      if (element.root instanceof $6jc) {
        const resourceType = element.element.resourceType;
        if (element.root.getFlag(resourceType)) {
          return true;
        }
        if (!element.root.hasResource(resourceType)) {
          return false;
        }
        if (element.root.copyFrom === void 0) {
          return false;
        }
        if (!element.root.getCopyFlag(resourceType)) {
          return false;
        }
      }
      return true;
    }
    return false;
  }
  async getChildren(element) {
    if (element instanceof $4jc) {
      const children = await element.getChildren();
      return children.map((e) => ({ element: e, root: element }));
    }
    if (element.element.resourceType) {
      const progressRunner = this.c.show(true, 500);
      try {
        const extensions = await element.root.getChildren(element.element.resourceType);
        return extensions.map((e) => ({ element: e, root: element.root }));
      } finally {
        progressRunner.done();
      }
    }
    return [];
  }
};
ProfileResourceTreeDataSource = __decorate([
  __param(0, $ZJ)
], ProfileResourceTreeDataSource);
var AbstractProfileResourceTreeRenderer = class extends $3c {
  c(resourceType) {
    switch (resourceType) {
      case "settings":
        return localize(11573, null);
      case "keybindings":
        return localize(11574, null);
      case "snippets":
        return localize(11575, null);
      case "tasks":
        return localize(11576, null);
      case "extensions":
        return localize(11577, null);
    }
    return "";
  }
  disposeElement(element, index, templateData, height) {
    templateData.elementDisposables.clear();
  }
  disposeTemplate(templateData) {
    templateData.disposables.dispose();
  }
};
var ProfilePropertyRenderer = class extends AbstractProfileResourceTreeRenderer {
  renderElement({ element }, index, templateData, height) {
    templateData.elementDisposables.clear();
    templateData.element = element;
  }
};
var ProfileNameRenderer = class ProfileNameRenderer2 extends ProfilePropertyRenderer {
  constructor(f, g) {
    super();
    this.f = f;
    this.g = g;
    this.templateId = "name";
  }
  renderTemplate(parent) {
    const disposables = new $2c();
    const elementDisposables = disposables.add(new $2c());
    let profileElement;
    const nameContainer = $bk(parent, $(".profile-row-container"));
    $bk(nameContainer, $(".profile-label-element", void 0, localize(11578, null)));
    const nameInput = disposables.add(new $I2(nameContainer, this.g, {
      inputBoxStyles: $C$({
        inputBorder: $5Zb
      }),
      ariaLabel: localize(11579, null),
      placeholder: localize(11580, null),
      validationOptions: {
        validation: (value) => {
          if (!value) {
            return {
              content: localize(11581, null),
              type: 2
              /* MessageType.WARNING */
            };
          }
          if (profileElement?.root.disabled) {
            return null;
          }
          if (!profileElement?.root.shouldValidateName()) {
            return null;
          }
          const initialName = profileElement?.root.getInitialName();
          value = value.trim();
          if (initialName !== value && this.f.profiles.some((p) => !p.isTransient && p.name === value)) {
            return {
              content: localize(11582, null, value),
              type: 2
              /* MessageType.WARNING */
            };
          }
          return null;
        }
      }
    }));
    nameInput.onDidChange((value) => {
      if (profileElement && value) {
        profileElement.root.name = value;
      }
    });
    const focusTracker = disposables.add($_j(nameInput.inputElement));
    disposables.add(focusTracker.onDidBlur(() => {
      if (profileElement && !nameInput.value) {
        nameInput.value = profileElement.root.name;
      }
    }));
    const renderName = (profileElement2) => {
      nameInput.value = profileElement2.root.name;
      nameInput.validate();
      const isDefaultProfile = profileElement2.root instanceof $5jc && profileElement2.root.profile.isDefault;
      if (profileElement2.root.disabled || isDefaultProfile) {
        nameInput.disable();
      } else {
        nameInput.enable();
      }
      if (isDefaultProfile) {
        nameInput.setTooltip(localize(11583, null));
      } else {
        nameInput.setTooltip(localize(11584, null));
      }
    };
    return {
      set element(element) {
        profileElement = element;
        renderName(profileElement);
        elementDisposables.add(profileElement.root.onDidChange((e) => {
          if (e.name || e.disabled) {
            renderName(element);
          }
          if (e.profile) {
            nameInput.validate();
          }
        }));
      },
      disposables,
      elementDisposables
    };
  }
};
ProfileNameRenderer = __decorate([
  __param(0, $rs),
  __param(1, $40)
], ProfileNameRenderer);
var ProfileIconRenderer = class ProfileIconRenderer2 extends ProfilePropertyRenderer {
  constructor(g, h3) {
    super();
    this.g = g;
    this.h = h3;
    this.templateId = "icon";
    this.f = $JZ("element");
  }
  renderTemplate(parent) {
    const disposables = new $2c();
    const elementDisposables = disposables.add(new $2c());
    let profileElement;
    const iconContainer = $bk(parent, $(".profile-row-container"));
    $bk(iconContainer, $(".profile-label-element", void 0, localize(11585, null)));
    const iconValueContainer = $bk(iconContainer, $(".profile-icon-container"));
    const iconElement = $bk(iconValueContainer, $(`${ThemeIcon.asCSSSelector($VTb)}`, { "tabindex": "0", "role": "button", "aria-label": localize(11586, null) }));
    const iconHover = disposables.add(this.h.setupManagedHover(this.f, iconElement, ""));
    const iconSelectBox = disposables.add(this.g.createInstance($tfc, { icons: $WTb, inputBoxStyles: $B$ }));
    let hoverWidget;
    const showIconSelectBox = () => {
      if (profileElement?.root instanceof $5jc && profileElement.root.profile.isDefault) {
        return;
      }
      if (profileElement?.root.disabled) {
        return;
      }
      if (profileElement?.root instanceof $5jc && profileElement.root.profile.isDefault) {
        return;
      }
      iconSelectBox.clearInput();
      hoverWidget = this.h.showHover({
        content: iconSelectBox.domNode,
        target: iconElement,
        position: {
          hoverPosition: 2
        },
        persistence: {
          sticky: true
        },
        appearance: {
          showPointer: true
        }
      }, true);
      if (hoverWidget) {
        iconSelectBox.layout(new $rj(486, 292));
        iconSelectBox.focus();
      }
    };
    disposables.add($_i(iconElement, $7j.CLICK, (e) => {
      $9j.stop(e, true);
      showIconSelectBox();
    }));
    disposables.add($_i(iconElement, $7j.KEY_DOWN, (e) => {
      const event = new $if(e);
      if (event.equals(
        3
        /* KeyCode.Enter */
      ) || event.equals(
        10
        /* KeyCode.Space */
      )) {
        $9j.stop(event, true);
        showIconSelectBox();
      }
    }));
    disposables.add($_i(iconSelectBox.domNode, $7j.KEY_DOWN, (e) => {
      const event = new $if(e);
      if (event.equals(
        9
        /* KeyCode.Escape */
      )) {
        $9j.stop(event, true);
        hoverWidget?.dispose();
        iconElement.focus();
      }
    }));
    disposables.add(iconSelectBox.onDidSelect((selectedIcon) => {
      hoverWidget?.dispose();
      iconElement.focus();
      if (profileElement) {
        profileElement.root.icon = selectedIcon.id;
      }
    }));
    $bk(iconValueContainer, $(".profile-description-element", void 0, localize(11587, null)));
    const renderIcon = (profileElement2) => {
      if (profileElement2?.root instanceof $5jc && profileElement2.root.profile.isDefault) {
        iconValueContainer.classList.add("disabled");
        iconHover.update(localize(11588, null));
      } else {
        iconHover.update(localize(11589, null));
        iconValueContainer.classList.remove("disabled");
      }
      if (profileElement2.root.icon) {
        iconElement.className = ThemeIcon.asClassName(ThemeIcon.fromId(profileElement2.root.icon));
      } else {
        iconElement.className = ThemeIcon.asClassName(ThemeIcon.fromId($VTb.id));
      }
    };
    return {
      set element(element) {
        profileElement = element;
        renderIcon(profileElement);
        elementDisposables.add(profileElement.root.onDidChange((e) => {
          if (e.icon) {
            renderIcon(element);
          }
        }));
      },
      disposables,
      elementDisposables
    };
  }
};
ProfileIconRenderer = __decorate([
  __param(0, $Pk),
  __param(1, $5$)
], ProfileIconRenderer);
var UseForCurrentWindowPropertyRenderer = class UseForCurrentWindowPropertyRenderer2 extends ProfilePropertyRenderer {
  constructor(f) {
    super();
    this.f = f;
    this.templateId = "useForCurrent";
  }
  renderTemplate(parent) {
    const disposables = new $2c();
    const elementDisposables = disposables.add(new $2c());
    let profileElement;
    const useForCurrentWindowContainer = $bk(parent, $(".profile-row-container"));
    $bk(useForCurrentWindowContainer, $(".profile-label-element", void 0, localize(11590, null)));
    const useForCurrentWindowValueContainer = $bk(useForCurrentWindowContainer, $(".profile-use-for-current-container"));
    const useForCurrentWindowTitle = localize(11591, null);
    const useForCurrentWindowCheckbox = disposables.add(new $R1(useForCurrentWindowTitle, false, $x$));
    $bk(useForCurrentWindowValueContainer, useForCurrentWindowCheckbox.domNode);
    const useForCurrentWindowLabel = $bk(useForCurrentWindowValueContainer, $(".profile-description-element", void 0, useForCurrentWindowTitle));
    disposables.add(useForCurrentWindowCheckbox.onChange(() => {
      if (profileElement?.root instanceof $5jc) {
        profileElement.root.toggleCurrentWindowProfile();
      }
    }));
    disposables.add($_i(useForCurrentWindowLabel, $7j.CLICK, () => {
      if (profileElement?.root instanceof $5jc) {
        profileElement.root.toggleCurrentWindowProfile();
      }
    }));
    const renderUseCurrentProfile = (profileElement2) => {
      useForCurrentWindowCheckbox.checked = profileElement2.root instanceof $5jc && this.f.currentProfile.id === profileElement2.root.profile.id;
      if (useForCurrentWindowCheckbox.checked && this.f.currentProfile.isDefault) {
        useForCurrentWindowCheckbox.disable();
      } else {
        useForCurrentWindowCheckbox.enable();
      }
    };
    const that = this;
    return {
      set element(element) {
        profileElement = element;
        renderUseCurrentProfile(profileElement);
        elementDisposables.add(that.f.onDidChangeCurrentProfile((e) => {
          renderUseCurrentProfile(element);
        }));
      },
      disposables,
      elementDisposables
    };
  }
};
UseForCurrentWindowPropertyRenderer = __decorate([
  __param(0, $gT)
], UseForCurrentWindowPropertyRenderer);
var UseAsDefaultProfileRenderer = class extends ProfilePropertyRenderer {
  constructor() {
    super(...arguments);
    this.templateId = "useAsDefault";
  }
  renderTemplate(parent) {
    const disposables = new $2c();
    const elementDisposables = disposables.add(new $2c());
    let profileElement;
    const useAsDefaultProfileContainer = $bk(parent, $(".profile-row-container"));
    $bk(useAsDefaultProfileContainer, $(".profile-label-element", void 0, localize(11592, null)));
    const useAsDefaultProfileValueContainer = $bk(useAsDefaultProfileContainer, $(".profile-use-as-default-container"));
    const useAsDefaultProfileTitle = localize(11593, null);
    const useAsDefaultProfileCheckbox = disposables.add(new $R1(useAsDefaultProfileTitle, false, $x$));
    $bk(useAsDefaultProfileValueContainer, useAsDefaultProfileCheckbox.domNode);
    const useAsDefaultProfileLabel = $bk(useAsDefaultProfileValueContainer, $(".profile-description-element", void 0, useAsDefaultProfileTitle));
    disposables.add(useAsDefaultProfileCheckbox.onChange(() => {
      if (profileElement?.root instanceof $5jc) {
        profileElement.root.toggleNewWindowProfile();
      }
    }));
    disposables.add($_i(useAsDefaultProfileLabel, $7j.CLICK, () => {
      if (profileElement?.root instanceof $5jc) {
        profileElement.root.toggleNewWindowProfile();
      }
    }));
    const renderUseAsDefault = (profileElement2) => {
      useAsDefaultProfileCheckbox.checked = profileElement2.root instanceof $5jc && profileElement2.root.isNewWindowProfile;
    };
    return {
      set element(element) {
        profileElement = element;
        renderUseAsDefault(profileElement);
        elementDisposables.add(profileElement.root.onDidChange((e) => {
          if (e.newWindowProfile) {
            renderUseAsDefault(element);
          }
        }));
      },
      disposables,
      elementDisposables
    };
  }
};
var CopyFromProfileRenderer = class CopyFromProfileRenderer2 extends ProfilePropertyRenderer {
  constructor(g, h3, j, m) {
    super();
    this.g = g;
    this.h = h3;
    this.j = j;
    this.m = m;
    this.templateId = "copyFrom";
    this.f = [];
  }
  renderTemplate(parent) {
    const disposables = new $2c();
    const elementDisposables = disposables.add(new $2c());
    let profileElement;
    const copyFromContainer = $bk(parent, $(".profile-row-container.profile-copy-from-container"));
    $bk(copyFromContainer, $(".profile-label-element", void 0, localize(11594, null)));
    $bk(copyFromContainer, $(".profile-description-element", void 0, localize(11595, null)));
    const copyFromSelectBox = disposables.add(this.h.createInstance($N1, [], 0, this.m, $K$, {
      useCustomDrawn: true,
      ariaLabel: localize(11596, null)
    }));
    copyFromSelectBox.render($bk(copyFromContainer, $(".profile-select-container")));
    const render = (profileElement2, copyFromOptions) => {
      copyFromSelectBox.setOptions(copyFromOptions);
      const id2 = profileElement2.copyFrom instanceof URI ? profileElement2.copyFrom.toString() : profileElement2.copyFrom?.id;
      const index = id2 ? copyFromOptions.findIndex((option) => option.id === id2) : 0;
      copyFromSelectBox.select(index);
    };
    const that = this;
    return {
      set element(element) {
        profileElement = element;
        if (profileElement.root instanceof $6jc) {
          const newProfileElement = profileElement.root;
          let copyFromOptions = that.n(newProfileElement);
          render(newProfileElement, copyFromOptions);
          copyFromSelectBox.setEnabled(!newProfileElement.previewProfile && !newProfileElement.disabled);
          elementDisposables.add(profileElement.root.onDidChange((e) => {
            if (e.copyFrom || e.copyFromInfo) {
              copyFromOptions = that.n(newProfileElement);
              render(newProfileElement, copyFromOptions);
            }
            if (e.preview || e.disabled) {
              copyFromSelectBox.setEnabled(!newProfileElement.previewProfile && !newProfileElement.disabled);
            }
          }));
          elementDisposables.add(copyFromSelectBox.onDidSelect((option) => {
            newProfileElement.copyFrom = copyFromOptions[option.index].source;
          }));
        }
      },
      disposables,
      elementDisposables
    };
  }
  setTemplates(templates) {
    this.f = templates;
  }
  n(profileElement) {
    const separator = { text: "\u2500\u2500\u2500\u2500\u2500\u2500", isDisabled: true };
    const copyFromOptions = [];
    copyFromOptions.push({ text: localize(11597, null) });
    for (const [copyFromTemplate, name] of profileElement.copyFromTemplates) {
      if (!this.f.some((template) => this.j.extUri.isEqual(URI.parse(template.url), copyFromTemplate))) {
        copyFromOptions.push({ text: `${name} (${$sh(copyFromTemplate)})`, id: copyFromTemplate.toString(), source: copyFromTemplate });
      }
    }
    if (this.f.length) {
      copyFromOptions.push({ ...separator, decoratorRight: localize(11598, null) });
      for (const template of this.f) {
        copyFromOptions.push({ text: template.name, id: template.url, source: URI.parse(template.url) });
      }
    }
    copyFromOptions.push({ ...separator, decoratorRight: localize(11599, null) });
    for (const profile of this.g.profiles) {
      if (!profile.isTransient) {
        copyFromOptions.push({ text: profile.name, id: profile.id, source: profile });
      }
    }
    return copyFromOptions;
  }
};
CopyFromProfileRenderer = __decorate([
  __param(0, $rs),
  __param(1, $Pk),
  __param(2, $vl),
  __param(3, $40)
], CopyFromProfileRenderer);
var ContentsProfileRenderer = class ContentsProfileRenderer2 extends ProfilePropertyRenderer {
  constructor(j, m, n) {
    super();
    this.j = j;
    this.m = m;
    this.n = n;
    this.templateId = "contents";
    this.f = this.B(new $ze());
    this.onDidChangeContentHeight = this.f.event;
    this.g = this.B(new $ze());
    this.onDidChangeSelection = this.g.event;
  }
  renderTemplate(parent) {
    const disposables = new $2c();
    const elementDisposables = disposables.add(new $2c());
    let profileElement;
    const configureRowContainer = $bk(parent, $(".profile-row-container"));
    $bk(configureRowContainer, $(".profile-label-element", void 0, localize(11600, null)));
    const contentsDescriptionElement = $bk(configureRowContainer, $(".profile-description-element"));
    const contentsTreeHeader = $bk(configureRowContainer, $(".profile-content-tree-header"));
    const optionsLabel = $(".options-header", void 0, $("span", void 0, localize(11601, null)));
    $bk(contentsTreeHeader, $(""), $("", void 0, localize(11602, null)), optionsLabel, $(""));
    const delegate = new ProfileContentTreeElementDelegate();
    const profilesContentTree = this.h = disposables.add(this.n.createInstance($4eb, "ProfileEditor-ContentsTree", $bk(configureRowContainer, $(".profile-content-tree.file-icon-themable-tree.show-file-icons")), delegate, [
      this.n.createInstance(ExistingProfileResourceTreeRenderer),
      this.n.createInstance(NewProfileResourceTreeRenderer),
      this.n.createInstance(ProfileResourceChildTreeItemRenderer)
    ], this.n.createInstance(ProfileResourceTreeDataSource), {
      multipleSelectionSupport: false,
      horizontalScrolling: false,
      accessibilityProvider: {
        getAriaLabel(element) {
          if ((element?.element).resourceType) {
            return (element?.element).resourceType;
          }
          if ((element?.element).label) {
            return (element?.element).label;
          }
          return "";
        },
        getWidgetAriaLabel() {
          return "";
        }
      },
      identityProvider: {
        getId(element) {
          if (element?.element.handle) {
            return element.element.handle;
          }
          return "";
        }
      },
      expandOnlyOnTwistieClick: true,
      renderIndentGuides: RenderIndentGuides.None,
      enableStickyScroll: false,
      openOnSingleClick: false,
      alwaysConsumeMouseWheel: false
    }));
    this.h.style(listStyles);
    disposables.add($1c(() => this.h = void 0));
    disposables.add(this.h.onDidChangeContentHeight((height) => {
      this.h?.layout(height);
      if (profileElement) {
        this.f.fire(profileElement);
      }
    }));
    disposables.add(this.h.onDidChangeSelection((e) => {
      if (profileElement) {
        this.g.fire({ element: profileElement, selected: !!e.elements.length });
      }
    }));
    disposables.add(this.h.onDidOpen(async (e) => {
      if (!e.browserEvent) {
        return;
      }
      if (e.element?.element.openAction) {
        await e.element.element.openAction.run();
      }
    }));
    disposables.add(this.h.onContextMenu(async (e) => {
      if (!e.element?.element.actions?.contextMenu?.length) {
        return;
      }
      this.m.showContextMenu({
        getAnchor: () => e.anchor,
        getActions: () => e.element?.element?.actions?.contextMenu ?? [],
        getActionsContext: () => e.element
      });
    }));
    const updateDescription = (element) => {
      $$i(contentsDescriptionElement);
      const markdown = new $bm();
      if (element.root instanceof $5jc && element.root.profile.isDefault) {
        markdown.appendMarkdown(localize(11603, null));
      } else {
        markdown.appendMarkdown(localize(11604, null));
        if (element.root instanceof $6jc) {
          const copyFromName = element.root.getCopyFromName();
          const optionName = copyFromName === this.j.defaultProfile.name ? localize(11605, null, copyFromName) : copyFromName;
          if (optionName) {
            markdown.appendMarkdown(localize(11606, null, optionName, copyFromName));
          }
          markdown.appendMarkdown(localize(11607, null)).appendMarkdown(localize(11608, null));
        }
      }
      $bk(contentsDescriptionElement, elementDisposables.add($D1(markdown)).element);
    };
    const that = this;
    return {
      set element(element) {
        profileElement = element;
        updateDescription(element);
        if (element.root instanceof $6jc) {
          contentsTreeHeader.classList.remove("default-profile");
        } else if (element.root instanceof $5jc) {
          contentsTreeHeader.classList.toggle("default-profile", element.root.profile.isDefault);
        }
        profilesContentTree.setInput(profileElement.root);
        elementDisposables.add(profileElement.root.onDidChange((e) => {
          if (e.copyFrom || e.copyFlags || e.flags || e.extensions || e.snippets || e.preview) {
            profilesContentTree.updateChildren(element.root);
          }
          if (e.copyFromInfo) {
            updateDescription(element);
            that.f.fire(element);
          }
        }));
      },
      disposables,
      elementDisposables: new $2c()
    };
  }
  clearSelection() {
    if (this.h) {
      this.h.setSelection([]);
      this.h.setFocus([]);
    }
  }
};
ContentsProfileRenderer = __decorate([
  __param(0, $rs),
  __param(1, $50),
  __param(2, $Pk)
], ContentsProfileRenderer);
var ProfileWorkspacesRenderer = class ProfileWorkspacesRenderer2 extends ProfilePropertyRenderer {
  constructor(j, m, n, r2) {
    super();
    this.j = j;
    this.m = m;
    this.n = n;
    this.r = r2;
    this.templateId = "workspaces";
    this.f = this.B(new $ze());
    this.onDidChangeContentHeight = this.f.event;
    this.g = this.B(new $ze());
    this.onDidChangeSelection = this.g.event;
  }
  renderTemplate(parent) {
    const disposables = new $2c();
    const elementDisposables = disposables.add(new $2c());
    let profileElement;
    const profileWorkspacesRowContainer = $bk(parent, $(".profile-row-container"));
    $bk(profileWorkspacesRowContainer, $(".profile-label-element", void 0, localize(11609, null)));
    const profileWorkspacesDescriptionElement = $bk(profileWorkspacesRowContainer, $(".profile-description-element"));
    const workspacesTableContainer = $bk(profileWorkspacesRowContainer, $(".profile-associations-table"));
    const table = this.h = disposables.add(this.r.createInstance($Yeb, "ProfileEditor-AssociationsTable", workspacesTableContainer, new class {
      constructor() {
        this.headerRowHeight = 30;
      }
      getHeight() {
        return 24;
      }
    }(), [
      {
        label: "",
        tooltip: "",
        weight: 1,
        minimumWidth: 30,
        maximumWidth: 30,
        templateId: WorkspaceUriEmptyColumnRenderer.TEMPLATE_ID,
        project(row) {
          return row;
        }
      },
      {
        label: localize(11610, null),
        tooltip: "",
        weight: 2,
        templateId: WorkspaceUriHostColumnRenderer.TEMPLATE_ID,
        project(row) {
          return row;
        }
      },
      {
        label: localize(11611, null),
        tooltip: "",
        weight: 7,
        templateId: WorkspaceUriPathColumnRenderer.TEMPLATE_ID,
        project(row) {
          return row;
        }
      },
      {
        label: "",
        tooltip: "",
        weight: 1,
        minimumWidth: 84,
        maximumWidth: 84,
        templateId: WorkspaceUriActionsColumnRenderer.TEMPLATE_ID,
        project(row) {
          return row;
        }
      }
    ], [
      new WorkspaceUriEmptyColumnRenderer(),
      this.r.createInstance(WorkspaceUriHostColumnRenderer),
      this.r.createInstance(WorkspaceUriPathColumnRenderer),
      this.r.createInstance(WorkspaceUriActionsColumnRenderer)
    ], {
      horizontalScrolling: false,
      alwaysConsumeMouseWheel: false,
      openOnSingleClick: false,
      multipleSelectionSupport: false,
      accessibilityProvider: {
        getAriaLabel: (item) => {
          const hostLabel = getHostLabel(this.j, item.workspace);
          if (hostLabel === void 0 || hostLabel.length === 0) {
            return localize(11612, null, this.j.getUriLabel(item.workspace));
          }
          return localize(11613, null, this.j.getUriLabel(item.workspace), hostLabel);
        },
        getWidgetAriaLabel: () => localize(11614, null)
      },
      identityProvider: {
        getId(element) {
          return element.workspace.toString();
        }
      }
    }));
    this.h.style(listStyles);
    disposables.add($1c(() => this.h = void 0));
    disposables.add(this.h.onDidChangeSelection((e) => {
      if (profileElement) {
        this.g.fire({ element: profileElement, selected: !!e.elements.length });
      }
    }));
    const addButtonBarElement = $bk(profileWorkspacesRowContainer, $(".profile-workspaces-button-container"));
    const buttonBar = disposables.add(new $n2(addButtonBarElement));
    const addButton = this.B(buttonBar.addButton({ title: localize(11615, null), ...$q$ }));
    addButton.label = localize(11616, null);
    disposables.add(addButton.onDidClick(async () => {
      const uris = await this.n.showOpenDialog({
        canSelectFiles: false,
        canSelectFolders: true,
        canSelectMany: true,
        openLabel: localize(11617, null),
        title: localize(11618, null)
      });
      if (uris) {
        if (profileElement?.root instanceof $5jc) {
          profileElement.root.updateWorkspaces(uris, []);
        }
      }
    }));
    disposables.add(table.onDidOpen((item) => {
      if (item?.element) {
        item.element.profileElement.openWorkspace(item.element.workspace);
      }
    }));
    const updateTable = () => {
      if (profileElement?.root instanceof $5jc && profileElement.root.workspaces?.length) {
        profileWorkspacesDescriptionElement.textContent = localize(11619, null);
        workspacesTableContainer.classList.remove("hide");
        table.splice(0, table.length, profileElement.root.workspaces.map((workspace2) => ({ workspace: workspace2, profileElement: profileElement.root })).sort((a, b) => this.m.extUri.compare(a.workspace, b.workspace)));
        this.layout();
      } else {
        profileWorkspacesDescriptionElement.textContent = localize(11620, null);
        workspacesTableContainer.classList.add("hide");
      }
    };
    const that = this;
    return {
      set element(element) {
        profileElement = element;
        if (element.root instanceof $5jc) {
          updateTable();
        }
        elementDisposables.add(profileElement.root.onDidChange((e) => {
          if (profileElement && e.workspaces) {
            updateTable();
            that.f.fire(profileElement);
          }
        }));
      },
      disposables,
      elementDisposables: new $2c()
    };
  }
  layout() {
    if (this.h) {
      this.h.layout(this.h.length * 24 + 30, void 0);
    }
  }
  clearSelection() {
    if (this.h) {
      this.h.setSelection([]);
      this.h.setFocus([]);
    }
  }
};
ProfileWorkspacesRenderer = __decorate([
  __param(0, $ZI),
  __param(1, $vl),
  __param(2, $1v),
  __param(3, $Pk)
], ProfileWorkspacesRenderer);
var ExistingProfileResourceTreeRenderer = class ExistingProfileResourceTreeRenderer2 extends AbstractProfileResourceTreeRenderer {
  static {
    ExistingProfileResourceTreeRenderer_1 = this;
  }
  static {
    this.TEMPLATE_ID = "ExistingProfileResourceTemplate";
  }
  constructor(f) {
    super();
    this.f = f;
    this.templateId = ExistingProfileResourceTreeRenderer_1.TEMPLATE_ID;
  }
  renderTemplate(parent) {
    const disposables = new $2c();
    const container2 = $bk(parent, $(".profile-tree-item-container.existing-profile-resource-type-container"));
    const label3 = $bk(container2, $(".profile-resource-type-label"));
    const radio = disposables.add(new $$2({ items: [] }));
    $bk($bk(container2, $(".profile-resource-options-container")), radio.domNode);
    const actionsContainer = $bk(container2, $(".profile-resource-actions-container"));
    const actionBar = disposables.add(this.f.createInstance($3$, actionsContainer, {
      hoverDelegate: disposables.add($KZ()),
      highlightToggledItems: true
    }));
    return { label: label3, radio, actionBar, disposables, elementDisposables: disposables.add(new $2c()) };
  }
  renderElement({ element: profileResourceTreeElement }, index, templateData, height) {
    templateData.elementDisposables.clear();
    const { element, root } = profileResourceTreeElement;
    if (!(root instanceof $5jc)) {
      throw new Error("ExistingProfileResourceTreeRenderer can only render existing profile element");
    }
    if ($zg(element) || !$2jc(element)) {
      throw new Error("Invalid profile resource element");
    }
    const updateRadioItems = () => {
      templateData.radio.setItems([
        {
          text: localize(11621, null),
          tooltip: localize(11622, null, resourceTypeTitle),
          isActive: root.getFlag(element.resourceType)
        },
        {
          text: root.name,
          tooltip: localize(11623, null, resourceTypeTitle, root.name),
          isActive: !root.getFlag(element.resourceType)
        }
      ]);
    };
    const resourceTypeTitle = this.c(element.resourceType);
    templateData.label.textContent = resourceTypeTitle;
    if (root instanceof $5jc && root.profile.isDefault) {
      templateData.radio.domNode.classList.add("hide");
    } else {
      templateData.radio.domNode.classList.remove("hide");
      updateRadioItems();
      templateData.elementDisposables.add(root.onDidChange((e) => {
        if (e.name) {
          updateRadioItems();
        }
      }));
      templateData.elementDisposables.add(templateData.radio.onDidSelect((index2) => root.setFlag(element.resourceType, index2 === 0)));
    }
    const actions = [];
    if (element.openAction) {
      actions.push(element.openAction);
    }
    if (element.actions?.primary) {
      actions.push(...element.actions.primary);
    }
    templateData.actionBar.setActions(actions);
  }
};
ExistingProfileResourceTreeRenderer = ExistingProfileResourceTreeRenderer_1 = __decorate([
  __param(0, $Pk)
], ExistingProfileResourceTreeRenderer);
var NewProfileResourceTreeRenderer = class NewProfileResourceTreeRenderer2 extends AbstractProfileResourceTreeRenderer {
  static {
    NewProfileResourceTreeRenderer_1 = this;
  }
  static {
    this.TEMPLATE_ID = "NewProfileResourceTemplate";
  }
  constructor(f, g) {
    super();
    this.f = f;
    this.g = g;
    this.templateId = NewProfileResourceTreeRenderer_1.TEMPLATE_ID;
  }
  renderTemplate(parent) {
    const disposables = new $2c();
    const container2 = $bk(parent, $(".profile-tree-item-container.new-profile-resource-type-container"));
    const labelContainer = $bk(container2, $(".profile-resource-type-label-container"));
    const label3 = $bk(labelContainer, $("span.profile-resource-type-label"));
    const radio = disposables.add(new $$2({ items: [] }));
    $bk($bk(container2, $(".profile-resource-options-container")), radio.domNode);
    const actionsContainer = $bk(container2, $(".profile-resource-actions-container"));
    const actionBar = disposables.add(this.g.createInstance($3$, actionsContainer, {
      hoverDelegate: disposables.add($KZ()),
      highlightToggledItems: true
    }));
    return { label: label3, radio, actionBar, disposables, elementDisposables: disposables.add(new $2c()) };
  }
  renderElement({ element: profileResourceTreeElement }, index, templateData, height) {
    templateData.elementDisposables.clear();
    const { element, root } = profileResourceTreeElement;
    if (!(root instanceof $6jc)) {
      throw new Error("NewProfileResourceTreeRenderer can only render new profile element");
    }
    if ($zg(element) || !$2jc(element)) {
      throw new Error("Invalid profile resource element");
    }
    const resourceTypeTitle = this.c(element.resourceType);
    templateData.label.textContent = resourceTypeTitle;
    const renderRadioItems = () => {
      const options3 = [
        {
          text: localize(11624, null),
          tooltip: localize(11625, null, resourceTypeTitle)
        },
        {
          text: localize(11626, null),
          tooltip: localize(11627, null, resourceTypeTitle)
        }
      ];
      const copyFromName = root.getCopyFromName();
      const name = copyFromName === this.f.defaultProfile.name ? localize(11628, null, copyFromName) : copyFromName;
      if (root.copyFrom && name) {
        templateData.radio.setItems([
          {
            text: name,
            tooltip: name ? localize(11629, null, resourceTypeTitle, name) : localize(11630, null)
          },
          ...options3
        ]);
        templateData.radio.setActiveItem(root.getCopyFlag(element.resourceType) ? 0 : root.getFlag(element.resourceType) ? 1 : 2);
      } else {
        templateData.radio.setItems(options3);
        templateData.radio.setActiveItem(root.getFlag(element.resourceType) ? 0 : 1);
      }
    };
    if (root.copyFrom) {
      templateData.elementDisposables.add(templateData.radio.onDidSelect((index2) => {
        root.setFlag(element.resourceType, index2 === 1);
        root.setCopyFlag(element.resourceType, index2 === 0);
      }));
    } else {
      templateData.elementDisposables.add(templateData.radio.onDidSelect((index2) => {
        root.setFlag(element.resourceType, index2 === 0);
      }));
    }
    renderRadioItems();
    templateData.radio.setEnabled(!root.disabled && !root.previewProfile);
    templateData.elementDisposables.add(root.onDidChange((e) => {
      if (e.disabled || e.preview) {
        templateData.radio.setEnabled(!root.disabled && !root.previewProfile);
      }
      if (e.copyFrom || e.copyFromInfo) {
        renderRadioItems();
      }
    }));
    const actions = [];
    if (element.openAction) {
      actions.push(element.openAction);
    }
    if (element.actions?.primary) {
      actions.push(...element.actions.primary);
    }
    templateData.actionBar.setActions(actions);
  }
};
NewProfileResourceTreeRenderer = NewProfileResourceTreeRenderer_1 = __decorate([
  __param(0, $rs),
  __param(1, $Pk)
], NewProfileResourceTreeRenderer);
var ProfileResourceChildTreeItemRenderer = class ProfileResourceChildTreeItemRenderer2 extends AbstractProfileResourceTreeRenderer {
  static {
    ProfileResourceChildTreeItemRenderer_1 = this;
  }
  static {
    this.TEMPLATE_ID = "ProfileResourceChildTreeItemTemplate";
  }
  constructor(h3) {
    super();
    this.h = h3;
    this.templateId = ProfileResourceChildTreeItemRenderer_1.TEMPLATE_ID;
    this.f = h3.createInstance($lsb, $ksb);
    this.g = this.B(h3.createInstance($6$, "mouse", false, {}));
  }
  renderTemplate(parent) {
    const disposables = new $2c();
    const container2 = $bk(parent, $(".profile-tree-item-container.profile-resource-child-container"));
    const checkbox = disposables.add(new $R1("", false, $x$));
    $bk(container2, checkbox.domNode);
    const resourceLabel = disposables.add(this.f.create(container2, { hoverDelegate: this.g }));
    const actionsContainer = $bk(container2, $(".profile-resource-actions-container"));
    const actionBar = disposables.add(this.h.createInstance($3$, actionsContainer, {
      hoverDelegate: disposables.add($KZ()),
      highlightToggledItems: true
    }));
    return { checkbox, resourceLabel, actionBar, disposables, elementDisposables: disposables.add(new $2c()) };
  }
  renderElement({ element: profileResourceTreeElement }, index, templateData, height) {
    templateData.elementDisposables.clear();
    const { element } = profileResourceTreeElement;
    if ($zg(element) || !$3jc(element)) {
      throw new Error("Invalid profile resource element");
    }
    if (element.checkbox) {
      templateData.checkbox.domNode.setAttribute("tabindex", "0");
      templateData.checkbox.domNode.classList.remove("hide");
      templateData.checkbox.checked = element.checkbox.isChecked;
      templateData.checkbox.domNode.ariaLabel = element.checkbox.accessibilityInformation?.label ?? "";
      if (element.checkbox.accessibilityInformation?.role) {
        templateData.checkbox.domNode.role = element.checkbox.accessibilityInformation.role;
      }
    } else {
      templateData.checkbox.domNode.removeAttribute("tabindex");
      templateData.checkbox.domNode.classList.add("hide");
    }
    templateData.resourceLabel.setResource({
      name: element.resource ? $sh(element.resource) : element.label,
      description: element.description,
      resource: element.resource
    }, {
      forceLabel: true,
      icon: element.icon,
      hideIcon: !element.resource && !element.icon
    });
    const actions = [];
    if (element.openAction) {
      actions.push(element.openAction);
    }
    if (element.actions?.primary) {
      actions.push(...element.actions.primary);
    }
    templateData.actionBar.setActions(actions);
  }
};
ProfileResourceChildTreeItemRenderer = ProfileResourceChildTreeItemRenderer_1 = __decorate([
  __param(0, $Pk)
], ProfileResourceChildTreeItemRenderer);
var WorkspaceUriEmptyColumnRenderer = class _WorkspaceUriEmptyColumnRenderer {
  constructor() {
    this.templateId = _WorkspaceUriEmptyColumnRenderer.TEMPLATE_ID;
  }
  static {
    this.TEMPLATE_ID = "empty";
  }
  renderTemplate(container2) {
    return {};
  }
  renderElement(item, index, templateData, height) {
  }
  disposeTemplate() {
  }
};
var WorkspaceUriHostColumnRenderer = class WorkspaceUriHostColumnRenderer2 {
  static {
    WorkspaceUriHostColumnRenderer_1 = this;
  }
  static {
    this.TEMPLATE_ID = "host";
  }
  constructor(c, d) {
    this.c = c;
    this.d = d;
    this.templateId = WorkspaceUriHostColumnRenderer_1.TEMPLATE_ID;
  }
  renderTemplate(container2) {
    const disposables = new $2c();
    const renderDisposables = disposables.add(new $2c());
    const element = container2.appendChild($(".host"));
    const hostContainer = element.appendChild($("div.host-label"));
    const buttonBarContainer = element.appendChild($("div.button-bar"));
    return {
      element,
      hostContainer,
      buttonBarContainer,
      disposables,
      renderDisposables
    };
  }
  renderElement(item, index, templateData, height) {
    templateData.renderDisposables.clear();
    templateData.renderDisposables.add({ dispose: () => {
      $$i(templateData.buttonBarContainer);
    } });
    templateData.hostContainer.innerText = getHostLabel(this.d, item.workspace);
    templateData.element.classList.toggle("current-workspace", this.c.extUri.isEqual(item.workspace, item.profileElement.getCurrentWorkspace()));
    templateData.hostContainer.style.display = "";
    templateData.buttonBarContainer.style.display = "none";
  }
  disposeTemplate(templateData) {
    templateData.disposables.dispose();
  }
};
WorkspaceUriHostColumnRenderer = WorkspaceUriHostColumnRenderer_1 = __decorate([
  __param(0, $vl),
  __param(1, $ZI)
], WorkspaceUriHostColumnRenderer);
var WorkspaceUriPathColumnRenderer = class WorkspaceUriPathColumnRenderer2 {
  static {
    WorkspaceUriPathColumnRenderer_1 = this;
  }
  static {
    this.TEMPLATE_ID = "path";
  }
  constructor(d, f) {
    this.d = d;
    this.f = f;
    this.templateId = WorkspaceUriPathColumnRenderer_1.TEMPLATE_ID;
    this.c = $JZ("mouse");
  }
  renderTemplate(container2) {
    const disposables = new $2c();
    const element = container2.appendChild($(".path"));
    const pathLabel = element.appendChild($("div.path-label"));
    const pathHover = disposables.add(this.f.setupManagedHover(this.c, pathLabel, ""));
    const renderDisposables = disposables.add(new $2c());
    return {
      element,
      pathLabel,
      pathHover,
      disposables,
      renderDisposables
    };
  }
  renderElement(item, index, templateData, height) {
    templateData.renderDisposables.clear();
    const stringValue = this.g(item.workspace);
    templateData.pathLabel.innerText = stringValue;
    templateData.element.classList.toggle("current-workspace", this.d.extUri.isEqual(item.workspace, item.profileElement.getCurrentWorkspace()));
    templateData.pathHover.update(stringValue);
  }
  disposeTemplate(templateData) {
    templateData.disposables.dispose();
    templateData.renderDisposables.dispose();
  }
  g(uri) {
    if (uri.scheme === Schemas.file) {
      return $1t(uri.fsPath);
    }
    if (uri.path.startsWith($kc.sep)) {
      const pathWithoutLeadingSeparator = uri.path.substring(1);
      const isWindowsPath = $5g(pathWithoutLeadingSeparator, true);
      if (isWindowsPath) {
        return $1t($jc.normalize(pathWithoutLeadingSeparator), true);
      }
    }
    return uri.path;
  }
};
WorkspaceUriPathColumnRenderer = WorkspaceUriPathColumnRenderer_1 = __decorate([
  __param(0, $vl),
  __param(1, $5$)
], WorkspaceUriPathColumnRenderer);
var ChangeProfileAction = class ChangeProfileAction2 extends $Um {
  constructor(c, f) {
    super("changeProfile", "", ThemeIcon.asClassName(editIcon));
    this.c = c;
    this.f = f;
    this.tooltip = localize(11631, null);
  }
  getSwitchProfileActions() {
    return this.f.profiles.filter((profile) => !profile.isTransient).sort((a, b) => a.isDefault ? -1 : b.isDefault ? 1 : a.name.localeCompare(b.name)).map((profile) => ({
      id: `switchProfileTo${profile.id}`,
      label: profile.name,
      class: void 0,
      enabled: true,
      checked: profile.id === this.c.profileElement.profile.id,
      tooltip: "",
      run: () => {
        if (profile.id === this.c.profileElement.profile.id) {
          return;
        }
        this.f.updateProfile(profile, { workspaces: [...profile.workspaces ?? [], this.c.workspace] });
      }
    }));
  }
};
ChangeProfileAction = __decorate([
  __param(1, $rs)
], ChangeProfileAction);
var WorkspaceUriActionsColumnRenderer = class WorkspaceUriActionsColumnRenderer2 {
  static {
    WorkspaceUriActionsColumnRenderer_1 = this;
  }
  static {
    this.TEMPLATE_ID = "actions";
  }
  constructor(c, d, f, g) {
    this.c = c;
    this.d = d;
    this.f = f;
    this.g = g;
    this.templateId = WorkspaceUriActionsColumnRenderer_1.TEMPLATE_ID;
  }
  renderTemplate(container2) {
    const disposables = new $2c();
    const element = container2.appendChild($(".profile-workspaces-actions-container"));
    const hoverDelegate = disposables.add($KZ());
    const actionBar = disposables.add(new $LZ(element, {
      hoverDelegate,
      actionViewItemProvider: (action) => {
        if (action instanceof ChangeProfileAction) {
          return new $L2(action, { getActions: () => action.getSwitchProfileActions() }, this.f, {
            classNames: action.class,
            hoverDelegate
          });
        }
        return void 0;
      }
    }));
    return { actionBar, disposables };
  }
  renderElement(item, index, templateData, height) {
    templateData.actionBar.clear();
    const actions = [];
    actions.push(this.h(item));
    actions.push(new ChangeProfileAction(item, this.c));
    actions.push(this.i(item));
    templateData.actionBar.push(actions, { icon: true });
  }
  h(item) {
    return {
      label: "",
      class: ThemeIcon.asClassName($6l.window),
      enabled: !this.g.extUri.isEqual(item.workspace, item.profileElement.getCurrentWorkspace()),
      id: "openWorkspace",
      tooltip: localize(11632, null),
      run: () => item.profileElement.openWorkspace(item.workspace)
    };
  }
  i(item) {
    return {
      label: "",
      class: ThemeIcon.asClassName(removeIcon),
      enabled: this.d.getDefaultProfileToUse().id !== item.profileElement.profile.id,
      id: "deleteTrustedUri",
      tooltip: localize(11633, null),
      run: () => item.profileElement.updateWorkspaces([], [item.workspace])
    };
  }
  disposeTemplate(templateData) {
    templateData.disposables.dispose();
  }
};
WorkspaceUriActionsColumnRenderer = WorkspaceUriActionsColumnRenderer_1 = __decorate([
  __param(0, $rs),
  __param(1, $hT),
  __param(2, $50),
  __param(3, $vl)
], WorkspaceUriActionsColumnRenderer);
function getHostLabel(labelService, workspaceUri) {
  return workspaceUri.authority ? labelService.getHostLabel(workspaceUri.scheme, workspaceUri.authority) : localize(11634, null);
}
var $0jc = class $0jc2 extends $nG {
  static {
    $0jc_1 = this;
  }
  static {
    this.ID = "workbench.input.userDataProfiles";
  }
  get dirty() {
    return this.h;
  }
  set dirty(dirty) {
    if (this.h !== dirty) {
      this.h = dirty;
      this.f.fire();
    }
  }
  constructor(m) {
    super();
    this.m = m;
    this.resource = void 0;
    this.h = false;
    this.c = $7jc.getInstance(this.m);
    this.B(this.c.onDidChange((e) => this.dirty = this.c.profiles.some((profile) => profile instanceof $6jc)));
  }
  get typeId() {
    return $0jc_1.ID;
  }
  getName() {
    return localize(11635, null);
  }
  getIcon() {
    return $oT;
  }
  async resolve() {
    await this.c.resolve();
    return this.c;
  }
  isDirty() {
    return this.dirty;
  }
  async save() {
    await this.c.saveNewProfile();
    return this;
  }
  async revert() {
    this.c.revert();
  }
  matches(otherInput) {
    return otherInput instanceof $0jc_1;
  }
  dispose() {
    for (const profile of this.c.profiles) {
      if (profile instanceof $5jc) {
        profile.reset();
      }
    }
    super.dispose();
  }
};
$0jc = $0jc_1 = __decorate([
  __param(0, $Pk)
], $0jc);
var $$jc = class {
  canSerialize(editorInput) {
    return true;
  }
  serialize(editorInput) {
    return "";
  }
  deserialize(instantiationService) {
    return instantiationService.createInstance($0jc);
  }
};

// out-build/vs/workbench/contrib/userDataProfile/browser/userDataProfile.js
var $_jc = new $bJ("OpenProfile");
var ProfilesMenu = new $bJ("Profiles");
var $akc = class $akc2 extends $3c {
  static {
    this.ID = "workbench.contrib.userDataProfiles";
  }
  constructor(h3, j, m, n, r2, s, contextKeyService, t, u, w, y, environmentService) {
    super();
    this.h = h3;
    this.j = j;
    this.m = m;
    this.n = n;
    this.r = r2;
    this.s = s;
    this.t = t;
    this.u = u;
    this.w = w;
    this.y = y;
    this.H = this.B(new $4c());
    this.c = $tT.bindTo(contextKeyService);
    this.f = $uT.bindTo(contextKeyService);
    this.c.set(this.h.currentProfile.id);
    this.f.set(!!this.h.currentProfile.isTransient);
    this.B(this.h.onDidChangeCurrentProfile((e) => {
      this.c.set(this.h.currentProfile.id);
      this.f.set(!!this.h.currentProfile.isTransient);
    }));
    this.g = $vT.bindTo(contextKeyService);
    this.g.set(this.j.profiles.length > 1);
    this.B(this.j.onDidChangeProfiles((e) => this.g.set(this.j.profiles.length > 1)));
    this.C();
    this.D();
    this.B(this.y.registerHandler(this));
    if ($r) {
      w.when(
        4
        /* LifecyclePhase.Eventually */
      ).then(() => j.cleanUp());
    }
    this.W();
    if (environmentService.options?.profileToPreview) {
      w.when(
        3
        /* LifecyclePhase.Restored */
      ).then(() => this.handleURL(URI.revive(environmentService.options.profileToPreview)));
    }
  }
  async handleURL(uri) {
    if ($mT(uri)) {
      const editor = await this.z();
      if (editor) {
        editor.createNewProfile(uri);
        return true;
      }
    }
    return false;
  }
  async z() {
    const editor = await this.t.activeGroup.openEditor(new $0jc(this.u));
    return editor;
  }
  C() {
    $Wn.as($ZK.EditorPane).registerEditorPane($7tb.create($9jc, $9jc.ID, localize(11531, null)), [
      new $Nk($0jc)
    ]);
    $Wn.as($ZK.EditorFactory).registerEditorSerializer($0jc.ID, $$jc);
  }
  D() {
    this.F();
    this.B(this.O());
    this.B(this.N());
    this.G();
    this.L();
    this.I();
    this.B(this.j.onDidChangeProfiles(() => this.I()));
    this.B(this.P());
    this.Q();
    this.R();
    this.S();
    this.U();
  }
  F() {
    const getProfilesTitle = () => {
      return localize(11532, null, this.h.currentProfile.name);
    };
    $dJ.appendMenuItem($bJ.GlobalActivity, {
      get title() {
        return getProfilesTitle();
      },
      submenu: ProfilesMenu,
      group: "2_configuration",
      order: 1,
      when: $vT
    });
    $dJ.appendMenuItem($bJ.MenubarPreferencesMenu, {
      get title() {
        return getProfilesTitle();
      },
      submenu: ProfilesMenu,
      group: "2_configuration",
      order: 1,
      when: $vT
    });
  }
  G() {
    $dJ.appendMenuItem($bJ.MenubarFileMenu, {
      title: localize(11533, null),
      submenu: $_jc,
      group: "1_new",
      order: 4
    });
  }
  I() {
    this.H.value = new $2c();
    for (const profile of this.j.profiles) {
      if (!profile.isTransient) {
        this.H.value.add(this.J(profile));
        this.H.value.add(this.M(profile));
      }
    }
  }
  J(profile) {
    const that = this;
    return $hJ(class ProfileEntryAction extends $gJ {
      constructor() {
        super({
          id: `workbench.profiles.actions.profileEntry.${profile.id}`,
          title: profile.name,
          metadata: {
            description: localize2(11541, "Switch to {0} profile", profile.name)
          },
          toggled: $7m.equals($tT.key, profile.id),
          menu: [
            {
              id: ProfilesMenu,
              group: "0_profiles"
            }
          ]
        });
      }
      async run(accessor) {
        if (that.h.currentProfile.id !== profile.id) {
          return that.m.switchProfile(profile);
        }
      }
    });
  }
  L() {
    return $hJ(class NewWindowWithProfileAction extends $gJ {
      constructor() {
        super({
          id: `workbench.profiles.actions.newWindowWithProfile`,
          title: localize2(11542, "New Window with Profile..."),
          category: $qT,
          precondition: $vT,
          f1: true
        });
      }
      async run(accessor) {
        const quickInputService = accessor.get($1M);
        const userDataProfilesService = accessor.get($rs);
        const hostService = accessor.get($S4);
        const pick = await quickInputService.pick(userDataProfilesService.profiles.map((profile) => ({
          label: profile.name,
          profile
        })), {
          title: localize(11534, null),
          placeHolder: localize(11535, null),
          canPickMany: false
        });
        if (pick) {
          return hostService.openWindow({ remoteAuthority: null, forceProfile: pick.profile.name });
        }
      }
    });
  }
  M(profile) {
    const disposables = new $2c();
    const id2 = `workbench.action.openProfile.${profile.name.replace("/s+/", "_")}`;
    disposables.add($hJ(class NewWindowAction extends $gJ {
      constructor() {
        super({
          id: id2,
          title: localize2(11543, "{0}", profile.name),
          metadata: {
            description: localize2(11544, "Open New Window with {0} Profile", profile.name)
          },
          menu: {
            id: $_jc,
            group: "0_profiles",
            when: $vT
          }
        });
      }
      run(accessor) {
        const hostService = accessor.get($S4);
        return hostService.openWindow({ remoteAuthority: null, forceProfile: profile.name });
      }
    }));
    disposables.add($dJ.appendMenuItem($bJ.CommandPalette, {
      command: {
        id: id2,
        category: $qT,
        title: localize2(11545, "Open {0} Profile", profile.name),
        precondition: $vT
      }
    }));
    return disposables;
  }
  N() {
    const that = this;
    return $hJ(class SwitchProfileAction extends $gJ {
      constructor() {
        super({
          id: `workbench.profiles.actions.switchProfile`,
          title: localize2(11546, "Switch Profile..."),
          category: $qT,
          f1: true
        });
      }
      async run(accessor) {
        const quickInputService = accessor.get($1M);
        const items = [];
        for (const profile of that.j.profiles) {
          items.push({
            id: profile.id,
            label: profile.id === that.h.currentProfile.id ? `$(check) ${profile.name}` : profile.name,
            profile
          });
        }
        const result = await quickInputService.pick(items.sort((a, b) => a.profile.name.localeCompare(b.profile.name)), {
          placeHolder: localize(11536, null)
        });
        if (result) {
          await that.m.switchProfile(result.profile);
        }
      }
    });
  }
  O() {
    const disposables = new $2c();
    disposables.add($hJ(class ManageProfilesAction extends $gJ {
      constructor() {
        super({
          id: `workbench.profiles.actions.manageProfiles`,
          title: {
            ...localize2(11547, "Profiles"),
            mnemonicTitle: localize(11537, null)
          },
          menu: [
            {
              id: $bJ.GlobalActivity,
              group: "2_configuration",
              order: 1,
              when: $vT.negate()
            },
            {
              id: $bJ.MenubarPreferencesMenu,
              group: "2_configuration",
              order: 1,
              when: $vT.negate()
            },
            {
              id: ProfilesMenu,
              group: "1_manage",
              order: 1
            }
          ]
        });
      }
      run(accessor) {
        const editorGroupsService = accessor.get($iJ);
        const instantiationService = accessor.get($Pk);
        return editorGroupsService.activeGroup.openEditor(new $0jc(instantiationService));
      }
    }));
    disposables.add($dJ.appendMenuItem($bJ.CommandPalette, {
      command: {
        id: "workbench.profiles.actions.manageProfiles",
        category: $qn.Preferences,
        title: localize2(11548, "Open Profiles (UI)")
      }
    }));
    return disposables;
  }
  P() {
    const that = this;
    const disposables = new $2c();
    const id2 = "workbench.profiles.actions.exportProfile";
    disposables.add($hJ(class ExportProfileAction extends $gJ {
      constructor() {
        super({
          id: id2,
          title: localize2(11549, "Export Profile..."),
          category: $qT,
          f1: true
        });
      }
      async run() {
        const editor = await that.z();
        editor?.selectProfile(that.h.currentProfile);
      }
    }));
    disposables.add($dJ.appendMenuItem($bJ.MenubarShare, {
      command: {
        id: id2,
        title: localize2(11550, "Export Profile ({0})...", that.h.currentProfile.name)
      }
    }));
    return disposables;
  }
  Q() {
    const that = this;
    this.B($hJ(class CreateFromCurrentProfileAction extends $gJ {
      constructor() {
        super({
          id: "workbench.profiles.actions.createFromCurrentProfile",
          title: localize2(11551, "Save Current Profile As..."),
          category: $qT,
          f1: true
        });
      }
      async run() {
        const editor = await that.z();
        editor?.createNewProfile(that.h.currentProfile);
      }
    }));
  }
  R() {
    const that = this;
    this.B($hJ(class CreateProfileAction extends $gJ {
      constructor() {
        super({
          id: "workbench.profiles.actions.createProfile",
          title: localize2(11552, "New Profile..."),
          category: $qT,
          f1: true,
          menu: [
            {
              id: $_jc,
              group: "1_manage_profiles",
              order: 1
            }
          ]
        });
      }
      async run(accessor) {
        const editor = await that.z();
        return editor?.createNewProfile();
      }
    }));
  }
  S() {
    this.B($hJ(class DeleteProfileAction extends $gJ {
      constructor() {
        super({
          id: "workbench.profiles.actions.deleteProfile",
          title: localize2(11553, "Delete Profile..."),
          category: $qT,
          f1: true,
          precondition: $vT
        });
      }
      async run(accessor) {
        const quickInputService = accessor.get($1M);
        const userDataProfileService = accessor.get($gT);
        const userDataProfilesService = accessor.get($rs);
        const userDataProfileManagementService = accessor.get($hT);
        const notificationService = accessor.get($PJ);
        const profiles2 = userDataProfilesService.profiles.filter((p) => !p.isDefault && !p.isTransient);
        if (profiles2.length) {
          const picks = await quickInputService.pick(profiles2.map((profile) => ({
            label: profile.name,
            description: profile.id === userDataProfileService.currentProfile.id ? localize(11538, null) : void 0,
            profile
          })), {
            title: localize(11539, null),
            placeHolder: localize(11540, null),
            canPickMany: true
          });
          if (picks) {
            try {
              await Promise.all(picks.map((pick) => userDataProfileManagementService.removeProfile(pick.profile)));
            } catch (error) {
              notificationService.error(error);
            }
          }
        }
      }
    }));
  }
  U() {
    this.B($hJ(class HelpAction extends $gJ {
      constructor() {
        super({
          id: "workbench.profiles.actions.help",
          title: $pT,
          category: $qn.Help,
          menu: [{
            id: $bJ.CommandPalette
          }]
        });
      }
      run(accessor) {
        return accessor.get($O4).open(URI.parse("https://aka.ms/vscode-profiles-help"));
      }
    }));
  }
  async W() {
    await this.w.when(
      4
      /* LifecyclePhase.Eventually */
    );
    if (this.j.profiles.length > 1) {
      this.n.publicLog2("profiles:count", { count: this.j.profiles.length - 1 });
    }
    const workspaceId = await this.s.getTelemetryWorkspaceId(this.r.getWorkspace(), this.r.getWorkbenchState());
    this.n.publicLog2("workspaceProfileInfo", {
      workspaceId,
      defaultProfile: this.h.currentProfile.isDefault
    });
  }
};
$akc = __decorate([
  __param(0, $gT),
  __param(1, $rs),
  __param(2, $hT),
  __param(3, $zv),
  __param(4, $Zk),
  __param(5, $Zjc),
  __param(6, $on),
  __param(7, $iJ),
  __param(8, $Pk),
  __param(9, $KL),
  __param(10, $4y),
  __param(11, $M4)
], $akc);

// out-build/vs/workbench/contrib/userDataProfile/browser/userDataProfileActions.js
var CreateTransientProfileAction = class _CreateTransientProfileAction extends $gJ {
  static {
    this.ID = "workbench.profiles.actions.createTemporaryProfile";
  }
  static {
    this.TITLE = localize2(11554, "Create a Temporary Profile");
  }
  constructor() {
    super({
      id: _CreateTransientProfileAction.ID,
      title: _CreateTransientProfileAction.TITLE,
      category: $qT,
      f1: true
    });
  }
  async run(accessor) {
    return accessor.get($hT).createAndEnterTransientProfile();
  }
};
$hJ(CreateTransientProfileAction);
$hJ(class CleanupProfilesAction extends $gJ {
  constructor() {
    super({
      id: "workbench.profiles.actions.cleanupProfiles",
      title: localize2(11555, "Cleanup Profiles"),
      category: $qn.Developer,
      f1: true
    });
  }
  async run(accessor) {
    return accessor.get($rs).cleanUp();
  }
});
$hJ(class ResetWorkspacesAction extends $gJ {
  constructor() {
    super({
      id: "workbench.profiles.actions.resetWorkspaces",
      title: localize2(11556, "Reset Workspace Profiles Associations"),
      category: $qn.Developer,
      f1: true
    });
  }
  async run(accessor) {
    const userDataProfilesService = accessor.get($rs);
    return userDataProfilesService.resetWorkspaces();
  }
});

// out-build/vs/workbench/contrib/userDataProfile/browser/userDataProfile.contribution.js
$PL(
  $akc.ID,
  $akc,
  2
  /* WorkbenchPhase.BlockRestore */
);

// out-build/vs/workbench/contrib/editSessions/common/editSessions.js
var $ckc = localize2(6332, "Cloud Changes");
var $dkc = $Qk("IEditSessionsStorageService");
var $ekc = $Qk("IEditSessionsLogService");
var ChangeType2;
(function(ChangeType3) {
  ChangeType3[ChangeType3["Addition"] = 1] = "Addition";
  ChangeType3[ChangeType3["Deletion"] = 2] = "Deletion";
})(ChangeType2 || (ChangeType2 = {}));
var FileType2;
(function(FileType3) {
  FileType3[FileType3["File"] = 1] = "File";
})(FileType2 || (FileType2 = {}));
var $fkc = 3;
var $gkc = "editSessionsSignedIn";
var $hkc = new $nn($gkc, false);
var $ikc = "editSessionsPending";
var $jkc = new $nn($ikc, false);
var $kkc = "workbench.view.editSessions";
var $lkc = "workbench.views.editSessions.data";
var $mkc = localize2(6333, "Cloud Changes");
var $nkc = $9r("edit-sessions-view-icon", $6l.cloudDownload, localize(6331, null));
var $okc = new $nn("editSessionsShowView", false);
var $pkc = "vscode-edit-sessions";
function $qkc(version2, content) {
  switch (version2) {
    case 1:
      return $Ci.fromString(content);
    case 2:
      return $Vi(content);
    default:
      throw new Error("Upgrade to a newer version to decode this content.");
  }
}
function $rkc(editSessionId) {
  const sha1 = new $3i();
  sha1.update(editSessionId);
  return sha1.digest();
}
var $skc = "editSessions";

// out-build/vs/workbench/contrib/editSessions/browser/editSessionsStorageService.js
var $tkc_1;
var $tkc = class $tkc2 extends $3c {
  static {
    $tkc_1 = this;
  }
  static {
    this.h = "editSessionAccountPreference";
  }
  get isSignedIn() {
    return this.X !== void 0;
  }
  get onDidSignIn() {
    return this.r.event;
  }
  get onDidSignOut() {
    return this.s.event;
  }
  get lastWrittenResources() {
    return this.t;
  }
  get lastReadResources() {
    return this.u;
  }
  constructor(w, y, z, C, D, F, G, H, I, J, L) {
    super();
    this.w = w;
    this.y = y;
    this.z = z;
    this.C = C;
    this.D = D;
    this.F = F;
    this.G = G;
    this.H = H;
    this.I = I;
    this.J = J;
    this.L = L;
    this.SIZE_LIMIT = Math.floor(1024 * 1024 * 1.9);
    this.c = this.H["editSessions.store"];
    this.j = false;
    this.r = new $ze();
    this.s = new $ze();
    this.t = /* @__PURE__ */ new Map();
    this.u = /* @__PURE__ */ new Map();
    this.B(this.C.onDidChangeSessions((e) => this.ab(e.event)));
    this.B(this.y.onDidChangeValue(-1, $tkc_1.h, this.q)(() => this.Z()));
    this.bb();
    this.cb();
    this.n = $hkc.bindTo(this.I);
    this.n.set(this.X !== void 0);
  }
  /**
   * @param resource: The resource to retrieve content for.
   * @param content An object representing resource state to be restored.
   * @returns The ref of the stored state.
   */
  async write(resource, content) {
    await this.initialize("write", false);
    if (!this.j) {
      throw new Error("Please sign in to store your edit session.");
    }
    if (typeof content !== "string" && content.machine === void 0) {
      content.machine = await this.O();
    }
    content = typeof content === "string" ? content : JSON.stringify(content);
    const ref = await this.storeClient.writeResource(resource, content, null, void 0, $ZBb($ps()));
    this.t.set(resource, { ref, content });
    return ref;
  }
  /**
   * @param resource: The resource to retrieve content for.
   * @param ref: A specific content ref to retrieve content for, if it exists.
   * If undefined, this method will return the latest saved edit session, if any.
   *
   * @returns An object representing the requested or latest state, if any.
   */
  async read(resource, ref) {
    await this.initialize("read", false);
    if (!this.j) {
      throw new Error("Please sign in to apply your latest edit session.");
    }
    let content;
    const headers = $ZBb($ps());
    try {
      if (ref !== void 0) {
        content = await this.storeClient?.resolveResourceContent(resource, ref, void 0, headers);
      } else {
        const result = await this.storeClient?.readResource(resource, null, void 0, headers);
        content = result?.content;
        ref = result?.ref;
      }
    } catch (ex) {
      this.G.error(ex);
    }
    if (content !== void 0 && content !== null && ref !== void 0) {
      this.u.set(resource, { ref, content });
      return { ref, content };
    }
    return void 0;
  }
  async delete(resource, ref) {
    await this.initialize("write", false);
    if (!this.j) {
      throw new Error(`Unable to delete edit session with ref ${ref}.`);
    }
    try {
      await this.storeClient?.deleteResource(resource, ref);
    } catch (ex) {
      this.G.error(ex);
    }
  }
  async list(resource) {
    await this.initialize("read", false);
    if (!this.j) {
      throw new Error(`Unable to list edit sessions.`);
    }
    try {
      return this.storeClient?.getAllResourceRefs(resource) ?? [];
    } catch (ex) {
      this.G.error(ex);
    }
    return [];
  }
  async initialize(reason, silent = false) {
    if (this.j) {
      return true;
    }
    this.j = await this.M(reason, silent);
    this.n.set(this.j);
    if (this.j) {
      this.r.fire();
    }
    return this.j;
  }
  /**
   *
   * Ensures that the store client is initialized,
   * meaning that authentication is configured and it
   * can be used to communicate with the remote storage service
   */
  async M(reason, silent) {
    await this.D.whenInstalledExtensionsRegistered();
    if (!this.c?.url) {
      throw new Error("Unable to initialize sessions sync as session sync preference is not configured in product.json.");
    }
    if (this.storeClient === void 0) {
      return false;
    }
    this.B(this.storeClient.onTokenFailed(() => {
      this.G.info("Clearing edit sessions authentication preference because of successive token failures.");
      this.$();
    }));
    if (this.f === void 0) {
      this.f = new $JBb(this.F, this.w, this.y, this.storeClient, this.G, this.H);
    }
    if (this.g !== void 0) {
      return true;
    }
    const authenticationSession = await this.P(reason, silent);
    if (authenticationSession !== void 0) {
      this.g = authenticationSession;
      this.storeClient.setAuthToken(authenticationSession.token, authenticationSession.providerId);
    }
    return authenticationSession !== void 0;
  }
  async getMachineById(machineId) {
    await this.initialize("read", false);
    if (!this.N) {
      const machines = await this.f.getMachines();
      this.N = machines.reduce((map, machine) => map.set(machine.id, machine.name), /* @__PURE__ */ new Map());
    }
    return this.N.get(machineId);
  }
  async O() {
    const currentMachineId = await this.f.getMachines().then((machines) => machines.find((m) => m.isCurrent)?.id);
    if (currentMachineId === void 0) {
      await this.f.addCurrentMachine();
      return await this.f.getMachines().then((machines) => machines.find((m) => m.isCurrent).id);
    }
    return currentMachineId;
  }
  async P(reason, silent) {
    if (this.X) {
      this.G.info(`Searching for existing authentication session with ID ${this.X}`);
      const existingSession = await this.Y();
      if (existingSession) {
        this.G.info(`Found existing authentication session with ID ${existingSession.session.id}`);
        return { sessionId: existingSession.session.id, token: existingSession.session.idToken ?? existingSession.session.accessToken, providerId: existingSession.session.providerId };
      } else {
        this.s.fire();
      }
    }
    if (this.Q()) {
      this.G.info(`Reusing user data sync enablement`);
      const authenticationSessionInfo = await $Y4(this.L, this.H);
      if (authenticationSessionInfo !== void 0) {
        this.G.info(`Using current authentication session with ID ${authenticationSessionInfo.id}`);
        this.X = authenticationSessionInfo.id;
        return { sessionId: authenticationSessionInfo.id, token: authenticationSessionInfo.accessToken, providerId: authenticationSessionInfo.providerId };
      }
    }
    if (silent) {
      return;
    }
    const authenticationSession = await this.R(reason);
    if (authenticationSession !== void 0) {
      this.X = authenticationSession.id;
      return { sessionId: authenticationSession.id, token: authenticationSession.idToken ?? authenticationSession.accessToken, providerId: authenticationSession.providerId };
    }
    return void 0;
  }
  Q() {
    return $r && this.y.isNew(
      -1
      /* StorageScope.APPLICATION */
    ) && this.y.isNew(
      1
      /* StorageScope.WORKSPACE */
    );
  }
  /**
   *
   * Prompts the user to pick an authentication option for storing and getting edit sessions.
   */
  async R(reason) {
    const disposables = new $2c();
    const quickpick = disposables.add(this.z.createQuickPick({ useSeparators: true }));
    quickpick.ok = false;
    quickpick.placeholder = reason === "read" ? localize(6307, null) : localize(6308, null);
    quickpick.ignoreFocusOut = true;
    quickpick.items = await this.S();
    return new Promise((resolve, reject) => {
      disposables.add(quickpick.onDidHide((e) => {
        reject(new $lb());
        disposables.dispose();
      }));
      disposables.add(quickpick.onDidAccept(async (e) => {
        const selection = quickpick.selectedItems[0];
        const session = "provider" in selection ? { ...await this.C.createSession(selection.provider.id, selection.provider.scopes), providerId: selection.provider.id } : "session" in selection ? selection.session : void 0;
        resolve(session);
        quickpick.hide();
      }));
      quickpick.show();
    });
  }
  async S() {
    const options3 = [];
    options3.push({ type: "separator", label: localize(6309, null) });
    const sessions = await this.U();
    options3.push(...sessions);
    options3.push({ type: "separator", label: localize(6310, null) });
    for (const authenticationProvider of await this.W()) {
      const signedInForProvider = sessions.some((account) => account.session.providerId === authenticationProvider.id);
      if (!signedInForProvider || this.C.getProvider(authenticationProvider.id).supportsMultipleAccounts) {
        const providerName = this.C.getProvider(authenticationProvider.id).label;
        options3.push({ label: localize(6311, null, providerName), provider: authenticationProvider });
      }
    }
    return options3;
  }
  /**
   *
   * Returns all authentication sessions available from {@link W}.
   */
  async U() {
    const authenticationProviders = await this.W();
    const accounts = /* @__PURE__ */ new Map();
    let currentSession;
    for (const provider of authenticationProviders) {
      const sessions = await this.C.getSessions(provider.id, provider.scopes);
      for (const session of sessions) {
        const item = {
          label: session.account.label,
          description: this.C.getProvider(provider.id).label,
          session: { ...session, providerId: provider.id }
        };
        accounts.set(item.session.account.id, item);
        if (this.X === session.id) {
          currentSession = item;
        }
      }
    }
    if (currentSession !== void 0) {
      accounts.set(currentSession.session.account.id, currentSession);
    }
    return [...accounts.values()].sort((a, b) => a.label.localeCompare(b.label));
  }
  /**
   *
   * Returns all authentication providers which can be used to authenticate
   * to the remote storage service, based on product.json configuration
   * and registered authentication providers.
   */
  async W() {
    if (!this.c) {
      throw new Error("Unable to get configured authentication providers as session sync preference is not configured in product.json.");
    }
    const authenticationProviders = this.c.authenticationProviders;
    const configuredAuthenticationProviders = Object.keys(authenticationProviders).reduce((result, id2) => {
      result.push({ id: id2, scopes: authenticationProviders[id2].scopes });
      return result;
    }, []);
    const availableAuthenticationProviders = this.C.declaredProviders;
    return configuredAuthenticationProviders.filter(({ id: id2 }) => availableAuthenticationProviders.some((provider) => provider.id === id2));
  }
  get X() {
    return this.y.get(
      $tkc_1.h,
      -1
      /* StorageScope.APPLICATION */
    );
  }
  set X(sessionId) {
    this.G.trace(`Saving authentication session preference for ID ${sessionId}.`);
    if (sessionId === void 0) {
      this.y.remove(
        $tkc_1.h,
        -1
        /* StorageScope.APPLICATION */
      );
    } else {
      this.y.store(
        $tkc_1.h,
        sessionId,
        -1,
        1
        /* StorageTarget.MACHINE */
      );
    }
  }
  async Y() {
    const accounts = await this.U();
    return accounts.find((account) => account.session.id === this.X);
  }
  async Z() {
    const newSessionId = this.X;
    const previousSessionId = this.g?.sessionId;
    if (previousSessionId !== newSessionId) {
      this.G.trace(`Resetting authentication state because authentication session ID preference changed from ${previousSessionId} to ${newSessionId}.`);
      this.g = void 0;
      this.j = false;
    }
  }
  $() {
    this.g = void 0;
    this.j = false;
    this.X = void 0;
    this.n.set(false);
  }
  ab(e) {
    if (this.g?.sessionId && e.removed?.find((session) => session.id === this.g?.sessionId)) {
      this.$();
    }
  }
  bb() {
    const that = this;
    const id2 = "workbench.editSessions.actions.signIn";
    const when = $7m.and($7m.equals($ikc, false), $7m.equals($gkc, false));
    this.B($hJ(class ResetEditSessionAuthenticationAction extends $gJ {
      constructor() {
        super({
          id: id2,
          title: localize(6312, null),
          category: $ckc,
          precondition: when,
          menu: [
            {
              id: $bJ.CommandPalette
            },
            {
              id: $bJ.AccountsContext,
              group: "2_editSessions",
              when
            }
          ]
        });
      }
      async run() {
        return await that.initialize("write", false);
      }
    }));
    this.B($dJ.appendMenuItem($bJ.AccountsContext, {
      group: "2_editSessions",
      command: {
        id: id2,
        title: localize(6313, null)
      },
      when: $7m.and($7m.equals($ikc, true), $7m.equals($gkc, false))
    }));
  }
  cb() {
    const that = this;
    this.B($hJ(class ResetEditSessionAuthenticationAction extends $gJ {
      constructor() {
        super({
          id: "workbench.editSessions.actions.resetAuth",
          title: localize(6314, null),
          category: $ckc,
          precondition: $7m.equals($gkc, true),
          menu: [
            {
              id: $bJ.CommandPalette
            },
            {
              id: $bJ.AccountsContext,
              group: "2_editSessions",
              when: $7m.equals($gkc, true)
            }
          ]
        });
      }
      async run() {
        const result = await that.J.confirm({
          message: localize(6315, null),
          checkbox: { label: localize(6316, null) }
        });
        if (result.confirmed) {
          if (result.checkboxChecked) {
            that.storeClient?.deleteResource("editSessions", null);
          }
          that.$();
        }
      }
    }));
  }
};
$tkc = $tkc_1 = __decorate([
  __param(0, $km),
  __param(1, $jv),
  __param(2, $1M),
  __param(3, $xS),
  __param(4, $wN),
  __param(5, $Xk),
  __param(6, $ekc),
  __param(7, $Vu),
  __param(8, $on),
  __param(9, $Yv),
  __param(10, $J4)
], $tkc);

// out-build/vs/workbench/contrib/editSessions/common/editSessionsLogService.js
var $ukc = class $ukc2 extends $Bn {
  constructor(loggerService, environmentService) {
    super();
    this.h = this.B(loggerService.createLogger($vh(environmentService.logsHome, `${$skc}.log`), { id: $skc, name: localize(6334, null) }));
  }
  trace(message, ...args2) {
    this.h.trace(message, ...args2);
  }
  debug(message, ...args2) {
    this.h.debug(message, ...args2);
  }
  info(message, ...args2) {
    this.h.info(message, ...args2);
  }
  warn(message, ...args2) {
    this.h.warn(message, ...args2);
  }
  error(message, ...args2) {
    this.h.error(message, ...args2);
  }
  flush() {
    this.h.flush();
  }
};
$ukc = __decorate([
  __param(0, $xn),
  __param(1, $Xk)
], $ukc);

// out-build/vs/workbench/contrib/editSessions/browser/editSessionsViews.js
var EDIT_SESSIONS_COUNT_KEY = "editSessionsCount";
var EDIT_SESSIONS_COUNT_CONTEXT_KEY = new $nn(EDIT_SESSIONS_COUNT_KEY, 0);
var $vkc = class $vkc2 extends $3c {
  constructor(container2, a) {
    super();
    this.a = a;
    this.b(container2);
  }
  b(container2) {
    const viewId = $lkc;
    const treeView = this.a.createInstance($jUb, viewId, $mkc.value);
    treeView.showCollapseAllAction = true;
    treeView.showRefreshAction = true;
    treeView.dataProvider = this.a.createInstance(EditSessionDataViewDataProvider);
    const viewsRegistry8 = $Wn.as(Extensions5.ViewsRegistry);
    viewsRegistry8.registerViews([{
      id: viewId,
      name: $mkc,
      ctorDescriptor: new $Nk($gUb),
      canToggleVisibility: true,
      canMoveView: false,
      treeView,
      collapsed: false,
      when: $7m.and($okc),
      order: 100,
      hideByDefault: true
    }], container2);
    viewsRegistry8.registerViewWelcomeContent(viewId, {
      content: localize(6317, null, `[${localize(6318, null)}](command:workbench.editSessions.actions.store)`),
      when: $7m.equals(EDIT_SESSIONS_COUNT_KEY, 0),
      order: 1
    });
    this.B($hJ(class extends $gJ {
      constructor() {
        super({
          id: "workbench.editSessions.actions.resume",
          title: localize(6319, null),
          icon: $6l.desktopDownload,
          menu: {
            id: $bJ.ViewItemContext,
            when: $7m.and($7m.equals("view", viewId), $7m.regex("viewItem", /edit-session/i)),
            group: "inline"
          }
        });
      }
      async run(accessor, handle2) {
        const editSessionId = URI.parse(handle2.$treeItemHandle).path.substring(1);
        const commandService = accessor.get($sn);
        await commandService.executeCommand("workbench.editSessions.actions.resumeLatest", editSessionId, true);
        await treeView.refresh();
      }
    }));
    this.B($hJ(class extends $gJ {
      constructor() {
        super({
          id: "workbench.editSessions.actions.store",
          title: localize(6320, null),
          icon: $6l.cloudUpload
        });
      }
      async run(accessor, handle2) {
        const commandService = accessor.get($sn);
        await commandService.executeCommand("workbench.editSessions.actions.storeCurrent");
        await treeView.refresh();
      }
    }));
    this.B($hJ(class extends $gJ {
      constructor() {
        super({
          id: "workbench.editSessions.actions.delete",
          title: localize(6321, null),
          icon: $6l.trash,
          menu: {
            id: $bJ.ViewItemContext,
            when: $7m.and($7m.equals("view", viewId), $7m.regex("viewItem", /edit-session/i)),
            group: "inline"
          }
        });
      }
      async run(accessor, handle2) {
        const editSessionId = URI.parse(handle2.$treeItemHandle).path.substring(1);
        const dialogService = accessor.get($Yv);
        const editSessionStorageService = accessor.get($dkc);
        const result = await dialogService.confirm({
          message: localize(6322, null, editSessionId),
          detail: localize(6323, null),
          type: "warning",
          title: $mkc.value
        });
        if (result.confirmed) {
          await editSessionStorageService.delete("editSessions", editSessionId);
          await treeView.refresh();
        }
      }
    }));
    this.B($hJ(class extends $gJ {
      constructor() {
        super({
          id: "workbench.editSessions.actions.deleteAll",
          title: localize(6324, null),
          icon: $6l.trash,
          menu: {
            id: $bJ.ViewTitle,
            when: $7m.and($7m.equals("view", viewId), $7m.greater(EDIT_SESSIONS_COUNT_KEY, 0))
          }
        });
      }
      async run(accessor) {
        const dialogService = accessor.get($Yv);
        const editSessionStorageService = accessor.get($dkc);
        const result = await dialogService.confirm({
          message: localize(6325, null),
          detail: localize(6326, null),
          type: "warning",
          title: $mkc.value
        });
        if (result.confirmed) {
          await editSessionStorageService.delete("editSessions", null);
          await treeView.refresh();
        }
      }
    }));
  }
};
$vkc = __decorate([
  __param(1, $Pk)
], $vkc);
var EditSessionDataViewDataProvider = class EditSessionDataViewDataProvider2 {
  constructor(b, c, d, e) {
    this.b = b;
    this.c = c;
    this.d = d;
    this.e = e;
    this.a = EDIT_SESSIONS_COUNT_CONTEXT_KEY.bindTo(this.c);
  }
  async getChildren(element) {
    if (!element) {
      return this.f();
    }
    const [ref, folderName, filePath] = URI.parse(element.handle).path.substring(1).split("/");
    if (ref && !folderName) {
      return this.g(ref);
    } else if (ref && folderName && !filePath) {
      return this.h(ref, folderName);
    }
    return [];
  }
  async f() {
    const allEditSessions = await this.b.list("editSessions");
    this.a.set(allEditSessions.length);
    const editSessions = [];
    for (const session of allEditSessions) {
      const resource = URI.from({ scheme: $pkc, authority: "remote-session-content", path: `/${session.ref}` });
      const sessionData = await this.b.read("editSessions", session.ref);
      if (!sessionData) {
        continue;
      }
      const content = JSON.parse(sessionData.content);
      const label3 = content.folders.map((folder) => folder.name).join(", ") ?? session.ref;
      const machineId = content.machine;
      const machineName = machineId ? await this.b.getMachineById(machineId) : void 0;
      const description = machineName === void 0 ? $Qu(session.created, true) : `${$Qu(session.created, true)}\xA0\xA0\u2022\xA0\xA0${machineName}`;
      editSessions.push({
        handle: resource.toString(),
        collapsibleState: TreeItemCollapsibleState2.Collapsed,
        label: { label: label3 },
        description,
        themeIcon: $6l.repo,
        contextValue: `edit-session`
      });
    }
    return editSessions;
  }
  async g(ref) {
    const data = await this.b.read("editSessions", ref);
    if (!data) {
      return [];
    }
    const content = JSON.parse(data.content);
    if (content.folders.length === 1) {
      const folder = content.folders[0];
      return this.h(ref, folder.name);
    }
    return content.folders.map((folder) => {
      const resource = URI.from({ scheme: $pkc, authority: "remote-session-content", path: `/${data.ref}/${folder.name}` });
      return {
        handle: resource.toString(),
        collapsibleState: TreeItemCollapsibleState2.Collapsed,
        label: { label: folder.name },
        themeIcon: $6l.folder
      };
    });
  }
  async h(ref, folderName) {
    const data = await this.b.read("editSessions", ref);
    if (!data) {
      return [];
    }
    const content = JSON.parse(data.content);
    const currentWorkspaceFolder = this.d.getWorkspace().folders.find((folder) => folder.name === folderName);
    const editSessionFolder = content.folders.find((folder) => folder.name === folderName);
    if (!editSessionFolder) {
      return [];
    }
    return Promise.all(editSessionFolder.workingChanges.map(async (change) => {
      const cloudChangeUri = URI.from({ scheme: $pkc, authority: "remote-session-content", path: `/${data.ref}/${folderName}/${change.relativeFilePath}` });
      if (currentWorkspaceFolder?.uri) {
        const localCopy = $vh(currentWorkspaceFolder.uri, change.relativeFilePath);
        if (change.type === ChangeType2.Addition && await this.e.exists(localCopy)) {
          return {
            handle: cloudChangeUri.toString(),
            resourceUri: cloudChangeUri,
            collapsibleState: TreeItemCollapsibleState2.None,
            label: { label: change.relativeFilePath },
            themeIcon: $6l.file,
            command: {
              id: "vscode.diff",
              title: localize(6327, null),
              arguments: [
                localCopy,
                cloudChangeUri,
                `${$rc(change.relativeFilePath)} (${localize(6328, null)} \u2194 ${localize(6329, null)})`,
                void 0
              ]
            }
          };
        }
      }
      return {
        handle: cloudChangeUri.toString(),
        resourceUri: cloudChangeUri,
        collapsibleState: TreeItemCollapsibleState2.None,
        label: { label: change.relativeFilePath },
        themeIcon: $6l.file,
        command: {
          id: $$ub,
          title: localize(6330, null),
          arguments: [cloudChangeUri, void 0, void 0]
        }
      };
    }));
  }
};
EditSessionDataViewDataProvider = __decorate([
  __param(0, $dkc),
  __param(1, $on),
  __param(2, $Zk),
  __param(3, $km)
], EditSessionDataViewDataProvider);

// out-build/vs/workbench/contrib/editSessions/browser/editSessionsFileSystemProvider.js
var $wkc = class $wkc2 {
  static {
    this.SCHEMA = $pkc;
  }
  constructor(a) {
    this.a = a;
    this.capabilities = 2048 + 2;
    this.onDidChangeCapabilities = Event2.None;
    this.onDidChangeFile = Event2.None;
  }
  async readFile(resource) {
    const match = /(?<ref>[^/]+)\/(?<folderName>[^/]+)\/(?<filePath>.*)/.exec(resource.path.substring(1));
    if (!match?.groups) {
      throw FileSystemProviderErrorCode.FileNotFound;
    }
    const { ref, folderName, filePath } = match.groups;
    const data = await this.a.read("editSessions", ref);
    if (!data) {
      throw FileSystemProviderErrorCode.FileNotFound;
    }
    const content = JSON.parse(data.content);
    const change = content.folders.find((f) => f.name === folderName)?.workingChanges.find((change2) => change2.relativeFilePath === filePath);
    if (!change || change.type === ChangeType2.Deletion) {
      throw FileSystemProviderErrorCode.FileNotFound;
    }
    return $qkc(content.version, change.contents).buffer;
  }
  async stat(resource) {
    const content = await this.readFile(resource);
    const currentTime = Date.now();
    return {
      type: FileType.File,
      permissions: FilePermission.Readonly,
      mtime: currentTime,
      ctime: currentTime,
      size: content.byteLength
    };
  }
  watch(resource, opts) {
    return $3c.None;
  }
  async mkdir(resource) {
  }
  async readdir(resource) {
    return [];
  }
  async rename(from, to, opts) {
  }
  async delete(resource, opts) {
  }
  async writeFile() {
    throw new $sb();
  }
};
$wkc = __decorate([
  __param(0, $dkc)
], $wkc);

// out-build/vs/workbench/services/workspaces/common/workspaceIdentityService.js
var $xkc = $Qk("IWorkspaceIdentityService");
var $ykc = class $ykc2 {
  constructor(a, b) {
    this.a = a;
    this.b = b;
  }
  async getWorkspaceStateFolders(cancellationToken) {
    const workspaceStateFolders = [];
    for (const workspaceFolder of this.a.getWorkspace().folders) {
      const workspaceFolderIdentity = await this.b.getEditSessionIdentifier(workspaceFolder, cancellationToken);
      if (!workspaceFolderIdentity) {
        continue;
      }
      workspaceStateFolders.push({ resourceUri: workspaceFolder.uri.toString(), workspaceFolderIdentity });
    }
    return workspaceStateFolders;
  }
  async matches(incomingWorkspaceFolders, cancellationToken) {
    const incomingToCurrentWorkspaceFolderUris = {};
    const incomingIdentitiesToIncomingWorkspaceFolders = {};
    for (const workspaceFolder of incomingWorkspaceFolders) {
      incomingIdentitiesToIncomingWorkspaceFolders[workspaceFolder.workspaceFolderIdentity] = workspaceFolder.resourceUri;
    }
    const currentWorkspaceFoldersToIdentities = /* @__PURE__ */ new Map();
    for (const workspaceFolder of this.a.getWorkspace().folders) {
      const workspaceFolderIdentity = await this.b.getEditSessionIdentifier(workspaceFolder, cancellationToken);
      if (!workspaceFolderIdentity) {
        continue;
      }
      currentWorkspaceFoldersToIdentities.set(workspaceFolder, workspaceFolderIdentity);
    }
    for (const [currentWorkspaceFolder, currentWorkspaceFolderIdentity] of currentWorkspaceFoldersToIdentities.entries()) {
      const incomingWorkspaceFolder = incomingIdentitiesToIncomingWorkspaceFolders[currentWorkspaceFolderIdentity];
      if (incomingWorkspaceFolder) {
        incomingToCurrentWorkspaceFolderUris[incomingWorkspaceFolder] = currentWorkspaceFolder.uri.toString();
        continue;
      }
      let hasCompleteMatch = false;
      for (const [incomingIdentity, incomingFolder] of Object.entries(incomingIdentitiesToIncomingWorkspaceFolders)) {
        if (await this.b.provideEditSessionIdentityMatch(currentWorkspaceFolder, currentWorkspaceFolderIdentity, incomingIdentity, cancellationToken) === EditSessionIdentityMatch.Complete) {
          incomingToCurrentWorkspaceFolderUris[incomingFolder] = currentWorkspaceFolder.uri.toString();
          hasCompleteMatch = true;
          break;
        }
      }
      if (hasCompleteMatch) {
        continue;
      }
      return false;
    }
    const convertUri = (uriToConvert) => {
      for (const incomingFolderUriKey of Object.keys(incomingToCurrentWorkspaceFolderUris)) {
        const incomingFolderUri = URI.parse(incomingFolderUriKey);
        if ($ph(incomingFolderUri, uriToConvert)) {
          const currentWorkspaceFolderUri = incomingToCurrentWorkspaceFolderUris[incomingFolderUriKey];
          const relativeFilePath = $xh(incomingFolderUri, uriToConvert);
          if (relativeFilePath) {
            return $vh(URI.parse(currentWorkspaceFolderUri), relativeFilePath);
          }
        }
      }
      return uriToConvert;
    };
    const uriReplacer = (obj, depth = 0) => {
      if (!obj || depth > 200) {
        return obj;
      }
      if (obj instanceof $Ci || obj instanceof Uint8Array) {
        return obj;
      }
      if (URI.isUri(obj)) {
        return convertUri(obj);
      }
      if (Array.isArray(obj)) {
        for (let i2 = 0; i2 < obj.length; ++i2) {
          obj[i2] = uriReplacer(obj[i2], depth + 1);
        }
      } else {
        for (const key2 in obj) {
          if (Object.hasOwnProperty.call(obj, key2)) {
            obj[key2] = uriReplacer(obj[key2], depth + 1);
          }
        }
      }
      return obj;
    };
    return uriReplacer;
  }
};
$ykc = __decorate([
  __param(0, $Zk),
  __param(1, $2M)
], $ykc);
$SC(
  $xkc,
  $ykc,
  1
  /* InstantiationType.Delayed */
);

// out-build/vs/workbench/contrib/editSessions/common/workspaceStateSync.js
var NullBackupStoreService = class {
  async writeResource() {
    return;
  }
  async getAllResourceRefs() {
    return [];
  }
  async resolveResourceContent() {
    return null;
  }
};
var NullEnablementService = class {
  constructor() {
    this.a = new $ze();
    this.onDidChangeEnablement = this.a.event;
    this.b = new $ze();
    this.onDidChangeResourceEnablement = this.b.event;
  }
  isEnabled() {
    return true;
  }
  canToggleEnablement() {
    return true;
  }
  setEnablement(_enabled) {
  }
  isResourceEnabled(_resource) {
    return true;
  }
  setResourceEnablement(_resource, _enabled) {
  }
  getResourceSyncStateVersion(_resource) {
    return void 0;
  }
};
var $zkc = class $zkc2 extends $LXb {
  constructor(profile, collection, userDataSyncStoreService, logService, fileService, environmentService, telemetryService, configurationService, storageService, uriIdentityService, vb, wb) {
    const userDataSyncLocalStoreService = new NullBackupStoreService();
    const userDataSyncEnablementService = new NullEnablementService();
    super({ syncResource: "workspaceState", profile }, collection, fileService, environmentService, storageService, userDataSyncStoreService, userDataSyncLocalStoreService, userDataSyncEnablementService, telemetryService, logService, configurationService, uriIdentityService);
    this.vb = vb;
    this.wb = wb;
    this.pb = 1;
  }
  async sync() {
    const cancellationTokenSource = new $ad();
    const folders = await this.vb.getWorkspaceStateFolders(cancellationTokenSource.token);
    if (!folders.length) {
      return;
    }
    await this.I.flush();
    const keys = this.I.keys(
      1,
      0
      /* StorageTarget.USER */
    );
    if (!keys.length) {
      return;
    }
    const contributedData = {};
    keys.forEach((key2) => {
      const data = this.I.get(
        key2,
        1
        /* StorageScope.WORKSPACE */
      );
      if (data) {
        contributedData[key2] = data;
      }
    });
    const content = { folders, storage: contributedData, version: this.pb };
    await this.wb.write("workspaceState", $au(content));
  }
  async apply() {
    const payload = this.wb.lastReadResources.get("editSessions")?.content;
    const workspaceStateId = payload ? JSON.parse(payload).workspaceStateId : void 0;
    const resource = await this.wb.read("workspaceState", workspaceStateId);
    if (!resource) {
      return null;
    }
    const remoteWorkspaceState = $bu(resource.content);
    if (!remoteWorkspaceState) {
      this.O.info("Skipping initializing workspace state because remote workspace state does not exist.");
      return null;
    }
    const cancellationTokenSource = new $ad();
    const replaceUris = await this.vb.matches(remoteWorkspaceState.folders, cancellationTokenSource.token);
    if (!replaceUris) {
      this.O.info("Skipping initializing workspace state because remote workspace state does not match current workspace.");
      return null;
    }
    const storage = {};
    for (const key2 of Object.keys(remoteWorkspaceState.storage)) {
      storage[key2] = remoteWorkspaceState.storage[key2];
    }
    if (Object.keys(storage).length) {
      const storageEntries = [];
      for (const key2 of Object.keys(storage)) {
        try {
          const value = $bu(storage[key2]);
          replaceUris(value);
          storageEntries.push({
            key: key2,
            value,
            scope: 1,
            target: 0
            /* StorageTarget.USER */
          });
        } catch {
          storageEntries.push({
            key: key2,
            value: storage[key2],
            scope: 1,
            target: 0
            /* StorageTarget.USER */
          });
        }
      }
      this.I.storeAll(storageEntries, true);
    }
    this.wb.delete("workspaceState", resource.ref);
    return null;
  }
  // TODO@joyceerhl implement AbstractSynchronizer in full
  tb(remoteUserData, lastSyncUserData, result, force) {
    throw new Error("Method not implemented.");
  }
  async qb(remoteUserData, lastSyncUserData, isRemoteDataFromCurrentMachine, userDataSyncConfiguration, token) {
    return [];
  }
  rb(resourcePreview, token) {
    throw new Error("Method not implemented.");
  }
  sb(resourcePreview, resource, content, token) {
    throw new Error("Method not implemented.");
  }
  async ub(lastSyncUserData) {
    return true;
  }
  async hasLocalData() {
    return false;
  }
  async resolveContent(uri) {
    return null;
  }
};
$zkc = __decorate([
  __param(4, $km),
  __param(5, $Xk),
  __param(6, $zv),
  __param(7, $kl),
  __param(8, $jv),
  __param(9, $vl),
  __param(10, $xkc),
  __param(11, $dkc)
], $zkc);

// out-build/vs/workbench/contrib/editSessions/common/editSessionsStorageClient.js
var $bkc = class extends $FXb {
};

// out-build/vs/workbench/contrib/editSessions/browser/editSessions.contribution.js
var $Akc_1;
$SC(
  $ekc,
  $ukc,
  1
  /* InstantiationType.Delayed */
);
$SC(
  $dkc,
  $tkc,
  1
  /* InstantiationType.Delayed */
);
var continueWorkingOnCommand = {
  id: "_workbench.editSessions.actions.continueEditSession",
  title: localize2(6300, "Continue Working On..."),
  precondition: $fpb.notEqualsTo("0"),
  f1: true
};
var openLocalFolderCommand = {
  id: "_workbench.editSessions.actions.continueEditSession.openLocalFolder",
  title: localize2(6301, "Open In Local Folder"),
  category: $ckc,
  precondition: $7m.and($veb.toNegated(), $lpb)
};
var showOutputChannelCommand = {
  id: "workbench.editSessions.actions.showOutputChannel",
  title: localize2(6302, "Show Log"),
  category: $ckc
};
var installAdditionalContinueOnOptionsCommand = {
  id: "workbench.action.continueOn.extensions",
  title: localize(6254, null)
};
$hJ(class extends $gJ {
  constructor() {
    super({ ...installAdditionalContinueOnOptionsCommand, f1: false });
  }
  async run(accessor) {
    return accessor.get($vzb).openSearch("@tag:continueOn");
  }
});
var resumeProgressOptionsTitle = `[${localize(6255, null)}](command:${showOutputChannelCommand.id})`;
var resumeProgressOptions = {
  location: 10,
  type: "syncing"
};
var queryParamName = "editSessionId";
var useEditSessionsWithContinueOn = "workbench.editSessions.continueOn";
var $Akc = class $Akc2 extends $3c {
  static {
    $Akc_1 = this;
  }
  static {
    this.h = "applicationLaunchedViaContinueOn";
  }
  constructor(s, t, u, w, y, z, C, D, F, G, H, I, J, L, M, N, O, P, Q, R, S, U, W, X, Y, Z, $149, ab, bb) {
    super();
    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 = G;
    this.H = H;
    this.I = I;
    this.J = J;
    this.L = L;
    this.M = M;
    this.N = N;
    this.O = O;
    this.P = P;
    this.Q = Q;
    this.R = R;
    this.S = S;
    this.U = U;
    this.W = W;
    this.X = X;
    this.Y = Y;
    this.Z = Z;
    this.$ = $149;
    this.ab = ab;
    this.bb = bb;
    this.a = [];
    this.j = this.B(new $4c());
    this.m = /* @__PURE__ */ new Set();
    this.b = $okc.bindTo(this.P);
    this.g = $jkc.bindTo(this.P);
    this.g.set(false);
    if (!this.I["editSessions.store"]?.url) {
      return;
    }
    this.r = new $bkc(URI.parse(this.I["editSessions.store"].url), this.I, this.Z, this.F, this.G, this.t, this.S);
    this.s.storeClient = this.r;
    this.n = new $zkc(this.$.defaultProfile, void 0, this.r, this.F, this.t, this.G, this.y, this.J, this.S, this.ab, this.bb, this.s);
    this.cb();
    this.gb();
    this.fb();
    this.rb();
    this.B(this.t.registerProvider($wkc.SCHEMA, new $wkc(this.s)));
    this.R.onWillShutdown((e) => {
      if (e.reason !== 3 && this.s.isSignedIn && this.J.getValue("workbench.experimental.cloudChanges.autoStore") === "onShutdown" && !$r) {
        e.join(this.eb(), { id: "autoStoreWorkingChanges", label: localize(6256, null) });
      }
    });
    this.B(this.s.onDidSignIn(() => this.db()));
    this.B(this.s.onDidSignOut(() => this.db()));
  }
  async cb() {
    const shouldAutoResumeOnReload = this.J.getValue("workbench.cloudChanges.autoResume") === "onReload";
    if (this.G.editSessionId !== void 0) {
      this.F.info(`Resuming cloud changes, reason: found editSessionId ${this.G.editSessionId} in environment service...`);
      await this.u.withProgress(resumeProgressOptions, async (progress) => await this.resumeEditSession(this.G.editSessionId, void 0, void 0, void 0, progress).finally(() => this.G.editSessionId = void 0));
    } else if (shouldAutoResumeOnReload && this.s.isSignedIn) {
      this.F.info("Resuming cloud changes, reason: cloud changes enabled...");
      await this.u.withProgress(resumeProgressOptions, async (progress) => await this.resumeEditSession(void 0, true, void 0, void 0, progress));
    } else if (shouldAutoResumeOnReload) {
      const hasApplicationLaunchedFromContinueOnFlow = this.S.getBoolean($Akc_1.h, -1, false);
      this.F.info(`Prompting to enable cloud changes, has application previously launched from Continue On flow: ${hasApplicationLaunchedFromContinueOnFlow}`);
      const handlePendingEditSessions = () => {
        this.F.info("Showing badge to enable cloud changes in accounts menu...");
        this.db();
        this.g.set(true);
        const disposable = this.s.onDidSignIn(async () => {
          disposable.dispose();
          this.F.info("Showing badge to enable cloud changes in accounts menu succeeded, resuming cloud changes...");
          await this.u.withProgress(resumeProgressOptions, async (progress) => await this.resumeEditSession(void 0, true, void 0, void 0, progress));
          this.S.remove(
            $Akc_1.h,
            -1
            /* StorageScope.APPLICATION */
          );
          this.G.continueOn = void 0;
        });
      };
      if (this.G.continueOn !== void 0 && !this.s.isSignedIn && // and user has not yet been prompted to sign in on this machine
      hasApplicationLaunchedFromContinueOnFlow === false) {
        this.S.store(
          $Akc_1.h,
          true,
          -1,
          1
          /* StorageTarget.MACHINE */
        );
        this.F.info("Prompting to enable cloud changes...");
        await this.s.initialize("read");
        if (this.s.isSignedIn) {
          this.F.info("Prompting to enable cloud changes succeeded, resuming cloud changes...");
          await this.u.withProgress(resumeProgressOptions, async (progress) => await this.resumeEditSession(void 0, true, void 0, void 0, progress));
        } else {
          handlePendingEditSessions();
        }
      } else if (!this.s.isSignedIn && // and user has been prompted to sign in on this machine
      hasApplicationLaunchedFromContinueOnFlow === true) {
        handlePendingEditSessions();
      }
    } else {
      this.F.debug("Auto resuming cloud changes disabled.");
    }
  }
  db() {
    if (this.s.isSignedIn) {
      return this.j.clear();
    }
    const badge = new $wqb(1, () => localize(6257, null));
    this.j.value = this.U.showAccountsActivity({ badge });
  }
  async eb() {
    const cancellationTokenSource = new $ad();
    await this.u.withProgress({
      location: 10,
      type: "syncing",
      title: localize(6258, null)
    }, async () => this.storeEditSession(false, cancellationTokenSource.token), () => {
      cancellationTokenSource.cancel();
      cancellationTokenSource.dispose();
    });
  }
  fb() {
    const container2 = $Wn.as(Extensions5.ViewContainersRegistry).registerViewContainer({
      id: $kkc,
      title: $mkc,
      ctorDescriptor: new $Nk($oqb, [$kkc, { mergeViewWithContainerWhenSingleView: true }]),
      icon: $nkc,
      hideIfEmpty: true
    }, 0, { doNotRegisterOpenCommand: true });
    this.B(this.H.createInstance($vkc, container2));
  }
  gb() {
    this.jb();
    this.kb();
    this.lb();
    this.tb();
    this.ib();
    this.hb();
  }
  hb() {
    this.B($hJ(class ShowEditSessionOutput extends $gJ {
      constructor() {
        super(showOutputChannelCommand);
      }
      run(accessor, ...args2) {
        const outputChannel = accessor.get($RS);
        void outputChannel.showChannel($skc);
      }
    }));
  }
  ib() {
    const that = this;
    this.B($hJ(class ShowEditSessionView extends $gJ {
      constructor() {
        super({
          id: "workbench.editSessions.actions.showEditSessions",
          title: localize2(6303, "Show Cloud Changes"),
          category: $ckc,
          f1: true
        });
      }
      async run(accessor) {
        that.b.set(true);
        const viewsService = accessor.get($uob);
        await viewsService.openView($lkc);
      }
    }));
  }
  jb() {
    const that = this;
    this.B($hJ(class ContinueEditSessionAction extends $gJ {
      constructor() {
        super(continueWorkingOnCommand);
      }
      async run(accessor, workspaceUri, destination) {
        let uri = workspaceUri;
        if (!destination && !uri) {
          destination = await that.ub();
          if (!destination) {
            that.y.publicLog2("continueOn.editSessions.pick.outcome", { outcome: "noSelection" });
            return;
          }
        }
        const shouldStoreEditSession = await that.qb();
        let ref;
        if (shouldStoreEditSession) {
          that.y.publicLog2("continueOn.editSessions.store");
          const cancellationTokenSource = new $ad();
          try {
            ref = await that.u.withProgress({
              location: 15,
              cancellable: true,
              type: "syncing",
              title: localize(6259, null)
            }, async () => {
              const ref2 = await that.storeEditSession(false, cancellationTokenSource.token);
              if (ref2 !== void 0) {
                that.y.publicLog2("continueOn.editSessions.store.outcome", { outcome: "storeSucceeded", hashedId: $rkc(ref2) });
              } else {
                that.y.publicLog2("continueOn.editSessions.store.outcome", { outcome: "storeSkipped" });
              }
              return ref2;
            }, () => {
              cancellationTokenSource.cancel();
              cancellationTokenSource.dispose();
              that.y.publicLog2("continueOn.editSessions.store.outcome", { outcome: "storeCancelledByUser" });
            });
          } catch (ex) {
            that.y.publicLog2("continueOn.editSessions.store.outcome", { outcome: "storeFailed" });
            throw ex;
          }
        }
        uri = destination ? await that.vb(destination) : uri;
        if (uri === void 0) {
          return;
        }
        if (ref !== void 0 && uri !== "noDestinationUri") {
          const encodedRef = encodeURIComponent(ref);
          uri = uri.with({
            query: uri.query.length > 0 ? uri.query + `&${queryParamName}=${encodedRef}&continueOn=1` : `${queryParamName}=${encodedRef}&continueOn=1`
          });
          that.F.info(`Opening ${uri.toString()}`);
          await that.w.open(uri, { openExternal: true });
        } else if (!shouldStoreEditSession && uri !== "noDestinationUri") {
          that.F.info(`Opening ${uri.toString()}`);
          await that.w.open(uri, { openExternal: true });
        } else if (ref === void 0 && shouldStoreEditSession) {
          that.F.warn(`Failed to store working changes when invoking ${continueWorkingOnCommand.id}.`);
        }
      }
    }));
  }
  kb() {
    const that = this;
    this.B($hJ(class ResumeLatestEditSessionAction extends $gJ {
      constructor() {
        super({
          id: "workbench.editSessions.actions.resumeLatest",
          title: localize2(6304, "Resume Latest Changes from Cloud"),
          category: $ckc,
          f1: true
        });
      }
      async run(accessor, editSessionId, forceApplyUnrelatedChange) {
        await that.u.withProgress({ ...resumeProgressOptions, title: resumeProgressOptionsTitle }, async () => await that.resumeEditSession(editSessionId, void 0, forceApplyUnrelatedChange));
      }
    }));
    this.B($hJ(class ResumeLatestEditSessionAction extends $gJ {
      constructor() {
        super({
          id: "workbench.editSessions.actions.resumeFromSerializedPayload",
          title: localize2(6305, "Resume Changes from Serialized Data"),
          category: "Developer",
          f1: true
        });
      }
      async run(accessor, editSessionId) {
        const data = await that.N.input({ prompt: "Enter serialized data" });
        if (data) {
          that.s.lastReadResources.set("editSessions", { content: data, ref: "" });
        }
        await that.u.withProgress({ ...resumeProgressOptions, title: resumeProgressOptionsTitle }, async () => await that.resumeEditSession(editSessionId, void 0, void 0, void 0, void 0, data));
      }
    }));
  }
  lb() {
    const that = this;
    this.B($hJ(class StoreLatestEditSessionAction extends $gJ {
      constructor() {
        super({
          id: "workbench.editSessions.actions.storeCurrent",
          title: localize2(6306, "Store Working Changes in Cloud"),
          category: $ckc,
          f1: true
        });
      }
      async run(accessor) {
        const cancellationTokenSource = new $ad();
        await that.u.withProgress({
          location: 15,
          title: localize(6260, null)
        }, async () => {
          that.y.publicLog2("editSessions.store");
          await that.storeEditSession(true, cancellationTokenSource.token);
        }, () => {
          cancellationTokenSource.cancel();
          cancellationTokenSource.dispose();
        });
      }
    }));
  }
  async resumeEditSession(ref, silent, forceApplyUnrelatedChange, applyPartialMatch, progress, serializedData) {
    await this.X.getEnvironment();
    if (this.L.getWorkbenchState() === 1) {
      return;
    }
    this.F.info(ref !== void 0 ? `Resuming changes from cloud with ref ${ref}...` : "Checking for pending cloud changes...");
    if (silent && !await this.s.initialize("read", true)) {
      return;
    }
    this.y.publicLog2("editSessions.resume");
    performance.mark("code/willResumeEditSessionFromIdentifier");
    progress?.report({ message: localize(6261, null) });
    const data = serializedData ? { content: serializedData, ref: "" } : await this.s.read("editSessions", ref);
    if (!data) {
      if (ref === void 0 && !silent) {
        this.C.info(localize(6262, null));
      } else if (ref !== void 0) {
        this.C.warn(localize(6263, null, ref));
      }
      this.F.info(ref !== void 0 ? `Aborting resuming changes from cloud as no edit session content is available to be applied from ref ${ref}.` : `Aborting resuming edit session as no edit session content is available to be applied`);
      return;
    }
    progress?.report({ message: resumeProgressOptionsTitle });
    const editSession = JSON.parse(data.content);
    ref = data.ref;
    if (editSession.version > $fkc) {
      this.C.error(localize(6264, null, this.I.nameLong));
      this.y.publicLog2("editSessions.resume.outcome", { hashedId: $rkc(ref), outcome: "clientUpdateNeeded" });
      return;
    }
    try {
      const { changes, conflictingChanges } = await this.mb(editSession, ref, forceApplyUnrelatedChange, applyPartialMatch);
      if (changes.length === 0) {
        return;
      }
      if (conflictingChanges.length > 0) {
        const { confirmed } = await this.D.confirm({
          type: Severity2.Warning,
          message: conflictingChanges.length > 1 ? localize(6265, null, conflictingChanges.length) : localize(6266, null, $sh(conflictingChanges[0].uri)),
          detail: conflictingChanges.length > 1 ? $2v(conflictingChanges.map((c) => c.uri)) : void 0
        });
        if (!confirmed) {
          return;
        }
      }
      for (const { uri, type, contents } of changes) {
        if (type === ChangeType2.Addition) {
          await this.t.writeFile(uri, $qkc(editSession.version, contents));
        } else if (type === ChangeType2.Deletion && await this.t.exists(uri)) {
          await this.t.del(uri);
        }
      }
      await this.n?.apply(false, {});
      this.F.info(`Deleting edit session with ref ${ref} after successfully applying it to current workspace...`);
      await this.s.delete("editSessions", ref);
      this.F.info(`Deleted edit session with ref ${ref}.`);
      this.y.publicLog2("editSessions.resume.outcome", { hashedId: $rkc(ref), outcome: "resumeSucceeded" });
    } catch (ex) {
      this.F.error("Failed to resume edit session, reason: ", ex.toString());
      this.C.error(localize(6267, null));
    }
    performance.mark("code/didResumeEditSessionFromIdentifier");
  }
  async mb(editSession, ref, forceApplyUnrelatedChange = false, applyPartialMatch = false) {
    const changes = [];
    const conflictingChanges = [];
    const workspaceFolders = this.L.getWorkspace().folders;
    const cancellationTokenSource = new $ad();
    for (const folder of editSession.folders) {
      let folderRoot;
      if (folder.canonicalIdentity) {
        for (const f of workspaceFolders) {
          const identity = await this.M.getEditSessionIdentifier(f, cancellationTokenSource.token);
          this.F.info(`Matching identity ${identity} against edit session folder identity ${folder.canonicalIdentity}...`);
          if ($Pv(identity, folder.canonicalIdentity) || forceApplyUnrelatedChange) {
            folderRoot = f;
            break;
          }
          if (identity !== void 0) {
            const match = await this.M.provideEditSessionIdentityMatch(f, identity, folder.canonicalIdentity, cancellationTokenSource.token);
            if (match === EditSessionIdentityMatch.Complete) {
              folderRoot = f;
              break;
            } else if (match === EditSessionIdentityMatch.Partial && this.J.getValue("workbench.experimental.cloudChanges.partialMatches.enabled") === true) {
              if (!applyPartialMatch) {
                this.C.prompt(Severity2.Info, localize(6268, null), [{ label: localize(6269, null), run: () => this.resumeEditSession(ref, false, void 0, true) }]);
              } else {
                folderRoot = f;
                break;
              }
            }
          }
        }
      } else {
        folderRoot = workspaceFolders.find((f) => f.name === folder.name);
      }
      if (!folderRoot) {
        this.F.info(`Skipping applying ${folder.workingChanges.length} changes from edit session with ref ${ref} as no matching workspace folder was found.`);
        return { changes: [], conflictingChanges: [], contributedStateHandlers: [] };
      }
      const localChanges = /* @__PURE__ */ new Set();
      for (const repository of this.z.repositories) {
        if (repository.provider.rootUri !== void 0 && this.L.getWorkspaceFolder(repository.provider.rootUri)?.name === folder.name) {
          const repositoryChanges = this.ob(repository);
          repositoryChanges.forEach((change) => localChanges.add(change.toString()));
        }
      }
      for (const change of folder.workingChanges) {
        const uri = $vh(folderRoot.uri, change.relativeFilePath);
        changes.push({ uri, type: change.type, contents: change.contents });
        if (await this.nb(localChanges, uri, change)) {
          conflictingChanges.push({ uri, type: change.type, contents: change.contents });
        }
      }
    }
    return { changes, conflictingChanges };
  }
  async nb(localChanges, uriWithIncomingChanges, incomingChange) {
    if (!localChanges.has(uriWithIncomingChanges.toString())) {
      return false;
    }
    const { contents, type } = incomingChange;
    switch (type) {
      case ChangeType2.Addition: {
        const [originalContents, incomingContents] = await Promise.all([
          $2i(contents),
          $2i($Wi((await this.t.readFile(uriWithIncomingChanges)).value))
        ]);
        return originalContents !== incomingContents;
      }
      case ChangeType2.Deletion: {
        return await this.t.exists(uriWithIncomingChanges);
      }
      default:
        throw new Error("Unhandled change type.");
    }
  }
  async storeEditSession(fromStoreCommand, cancellationToken) {
    const folders = [];
    let editSessionSize = 0;
    let hasEdits = false;
    await this.W.saveAll();
    for (const repository of this.z.repositories) {
      const trackedUris = this.ob(repository);
      const workingChanges = [];
      const { rootUri } = repository.provider;
      const workspaceFolder = rootUri ? this.L.getWorkspaceFolder(rootUri) : void 0;
      let name = workspaceFolder?.name;
      for (const uri of trackedUris) {
        const workspaceFolder2 = this.L.getWorkspaceFolder(uri);
        if (!workspaceFolder2) {
          this.F.info(`Skipping working change ${uri.toString()} as no associated workspace folder was found.`);
          continue;
        }
        await this.M.onWillCreateEditSessionIdentity(workspaceFolder2, cancellationToken);
        name = name ?? workspaceFolder2.name;
        const relativeFilePath = $xh(workspaceFolder2.uri, uri) ?? uri.path;
        try {
          if (!(await this.t.stat(uri)).isFile) {
            continue;
          }
        } catch {
        }
        hasEdits = true;
        if (await this.t.exists(uri)) {
          const contents = $Wi((await this.t.readFile(uri)).value);
          editSessionSize += contents.length;
          if (editSessionSize > this.s.SIZE_LIMIT) {
            this.C.error(localize(6270, null));
            return void 0;
          }
          workingChanges.push({ type: ChangeType2.Addition, fileType: FileType2.File, contents, relativeFilePath });
        } else {
          workingChanges.push({ type: ChangeType2.Deletion, fileType: FileType2.File, contents: void 0, relativeFilePath });
        }
      }
      let canonicalIdentity = void 0;
      if (workspaceFolder !== null && workspaceFolder !== void 0) {
        canonicalIdentity = await this.M.getEditSessionIdentifier(workspaceFolder, cancellationToken);
      }
      folders.push({ workingChanges, name: name ?? "", canonicalIdentity: canonicalIdentity ?? void 0, absoluteUri: workspaceFolder?.uri.toString() });
    }
    await this.n?.sync(null, {});
    if (!hasEdits) {
      this.F.info("Skipped storing working changes in the cloud as there are no edits to store.");
      if (fromStoreCommand) {
        this.C.info(localize(6271, null));
      }
      return void 0;
    }
    const data = { folders, version: 2, workspaceStateId: this.s.lastWrittenResources.get("workspaceState")?.ref };
    try {
      this.F.info(`Storing edit session...`);
      const ref = await this.s.write("editSessions", data);
      this.F.info(`Stored edit session with ref ${ref}.`);
      return ref;
    } catch (ex) {
      this.F.error(`Failed to store edit session, reason: `, ex.toString());
      if (ex instanceof $2Bb) {
        switch (ex.code) {
          case "TooLarge":
            this.y.publicLog2("editSessions.upload.failed", { reason: "TooLarge" });
            this.C.error(localize(6272, null));
            break;
          default:
            this.y.publicLog2("editSessions.upload.failed", { reason: "unknown" });
            this.C.error(localize(6273, null));
            break;
        }
      }
    }
    return void 0;
  }
  ob(repository) {
    return repository.provider.groups.reduce((resources, resourceGroups) => {
      resourceGroups.resources.forEach((resource) => resources.add(resource.sourceUri));
      return resources;
    }, /* @__PURE__ */ new Set());
  }
  pb() {
    for (const repository of this.z.repositories) {
      if (this.ob(repository).size > 0) {
        return true;
      }
    }
    return false;
  }
  async qb() {
    if (this.s.isSignedIn) {
      return this.pb();
    }
    if (this.J.getValue(useEditSessionsWithContinueOn) === "off") {
      this.y.publicLog2("continueOn.editSessions.canStore.outcome", { outcome: "disabledEditSessionsViaSetting" });
      return false;
    }
    if (this.pb()) {
      const disposables = new $2c();
      const quickpick = disposables.add(this.N.createQuickPick());
      quickpick.placeholder = localize(6274, null);
      quickpick.ok = false;
      quickpick.ignoreFocusOut = true;
      const withCloudChanges = { label: localize(6275, null) };
      const withoutCloudChanges = { label: localize(6276, null) };
      quickpick.items = [withCloudChanges, withoutCloudChanges];
      const continueWithCloudChanges = await new Promise((resolve, reject) => {
        disposables.add(quickpick.onDidAccept(() => {
          resolve(quickpick.selectedItems[0] === withCloudChanges);
          disposables.dispose();
        }));
        disposables.add(quickpick.onDidHide(() => {
          reject(new $lb());
          disposables.dispose();
        }));
        quickpick.show();
      });
      if (!continueWithCloudChanges) {
        this.y.publicLog2("continueOn.editSessions.canStore.outcome", { outcome: "didNotEnableEditSessionsWhenPrompted" });
        return continueWithCloudChanges;
      }
      const initialized = await this.s.initialize("write");
      if (!initialized) {
        this.y.publicLog2("continueOn.editSessions.canStore.outcome", { outcome: "didNotEnableEditSessionsWhenPrompted" });
      }
      return initialized;
    }
    return false;
  }
  //#region Continue Edit Session extension contribution point
  rb() {
    continueEditSessionExtPoint.setHandler((extensions) => {
      const continueEditSessionOptions = [];
      for (const extension of extensions) {
        if (!$zN(extension.description, "contribEditSessions")) {
          continue;
        }
        if (!Array.isArray(extension.value)) {
          continue;
        }
        for (const contribution of extension.value) {
          const command4 = $dJ.getCommand(contribution.command);
          if (!command4) {
            return;
          }
          const icon2 = command4.icon;
          const title = typeof command4.title === "string" ? command4.title : command4.title.value;
          const when = $7m.deserialize(contribution.when);
          continueEditSessionOptions.push(new ContinueEditSessionItem(ThemeIcon.isThemeIcon(icon2) ? `$(${icon2.id}) ${title}` : title, command4.id, command4.source?.title, when, contribution.documentation));
          if (contribution.qualifiedName) {
            this.sb(command4.id, contribution.qualifiedName, contribution.category ?? command4.category, when, contribution.remoteGroup);
          }
        }
      }
      this.a = continueEditSessionOptions;
    });
  }
  sb(commandId, qualifiedName, category8, when, remoteGroup) {
    const command4 = {
      id: `${continueWorkingOnCommand.id}.${commandId}`,
      title: { original: qualifiedName, value: qualifiedName },
      category: typeof category8 === "string" ? { original: category8, value: category8 } : category8,
      precondition: when,
      f1: true
    };
    if (!this.m.has(command4.id)) {
      this.m.add(command4.id);
      this.B($hJ(class StandaloneContinueOnOption extends $gJ {
        constructor() {
          super(command4);
        }
        async run(accessor) {
          return accessor.get($sn).executeCommand(continueWorkingOnCommand.id, void 0, commandId);
        }
      }));
      if (remoteGroup !== void 0) {
        $dJ.appendMenuItem($bJ.StatusBarRemoteIndicatorMenu, {
          group: remoteGroup,
          command: command4,
          when: command4.precondition
        });
      }
    }
  }
  tb() {
    const that = this;
    this.B($hJ(class ContinueInLocalFolderAction extends $gJ {
      constructor() {
        super(openLocalFolderCommand);
      }
      async run(accessor) {
        const selection = await that.Q.showOpenDialog({
          title: localize(6277, null),
          canSelectFolders: true,
          canSelectMany: false,
          canSelectFiles: false,
          availableFileSystems: [Schemas.file]
        });
        return selection?.length !== 1 ? void 0 : URI.from({
          scheme: that.I.urlProtocol,
          authority: Schemas.file,
          path: selection[0].path
        });
      }
    }));
    if ($9S(this.L.getWorkspace()) !== void 0 && $p) {
      this.sb(openLocalFolderCommand.id, localize(6278, null), void 0, openLocalFolderCommand.precondition, void 0);
    }
  }
  async ub() {
    const disposables = new $2c();
    const quickPick = disposables.add(this.N.createQuickPick({ useSeparators: true }));
    const workspaceContext = this.L.getWorkbenchState() === 2 ? this.L.getWorkspace().folders[0].name : this.L.getWorkspace().folders.map((folder) => folder.name).join(", ");
    quickPick.placeholder = localize(6279, null, `'${workspaceContext}'`);
    quickPick.items = this.wb();
    this.Y.onDidChangeExtensions(() => {
      quickPick.items = this.wb();
    });
    const command4 = await new Promise((resolve, reject) => {
      disposables.add(quickPick.onDidHide(() => {
        disposables.dispose();
        resolve(void 0);
      }));
      disposables.add(quickPick.onDidAccept((e) => {
        const selection = quickPick.activeItems[0].command;
        if (selection === installAdditionalContinueOnOptionsCommand.id) {
          void this.O.executeCommand(installAdditionalContinueOnOptionsCommand.id);
        } else {
          resolve(selection);
          quickPick.hide();
        }
      }));
      quickPick.show();
      disposables.add(quickPick.onDidTriggerItemButton(async (e) => {
        if (e.item.documentation !== void 0) {
          const uri = URI.isUri(e.item.documentation) ? URI.parse(e.item.documentation) : await this.O.executeCommand(e.item.documentation);
          void this.w.open(uri, { openExternal: true });
        }
      }));
    });
    quickPick.dispose();
    return command4;
  }
  async vb(command4) {
    try {
      const uri = await this.O.executeCommand(command4);
      if (uri === void 0) {
        this.y.publicLog2("continueOn.openDestination.outcome", { selection: command4, outcome: "noDestinationUri" });
        return "noDestinationUri";
      }
      if (URI.isUri(uri)) {
        this.y.publicLog2("continueOn.openDestination.outcome", { selection: command4, outcome: "resolvedUri" });
        return uri;
      }
      this.y.publicLog2("continueOn.openDestination.outcome", { selection: command4, outcome: "invalidDestination" });
      return void 0;
    } catch (ex) {
      if (ex instanceof $lb) {
        this.y.publicLog2("continueOn.openDestination.outcome", { selection: command4, outcome: "cancelled" });
      } else {
        this.y.publicLog2("continueOn.openDestination.outcome", { selection: command4, outcome: "unknownError" });
      }
      return void 0;
    }
  }
  wb() {
    const items = [...this.a].filter((option) => option.when === void 0 || this.P.contextMatchesRules(option.when));
    if ($9S(this.L.getWorkspace()) !== void 0 && $p) {
      items.push(new ContinueEditSessionItem("$(folder) " + localize(6280, null), openLocalFolderCommand.id, localize(6281, null)));
    }
    const sortedItems = items.sort((item1, item2) => item1.label.localeCompare(item2.label));
    return sortedItems.concat({ type: "separator" }, new ContinueEditSessionItem(installAdditionalContinueOnOptionsCommand.title, installAdditionalContinueOnOptionsCommand.id));
  }
};
$Akc = $Akc_1 = __decorate([
  __param(0, $dkc),
  __param(1, $km),
  __param(2, $TJ),
  __param(3, $O4),
  __param(4, $zv),
  __param(5, $dS),
  __param(6, $PJ),
  __param(7, $Yv),
  __param(8, $ekc),
  __param(9, $Xk),
  __param(10, $Pk),
  __param(11, $Vu),
  __param(12, $kl),
  __param(13, $Zk),
  __param(14, $2M),
  __param(15, $1M),
  __param(16, $sn),
  __param(17, $on),
  __param(18, $1v),
  __param(19, $KL),
  __param(20, $jv),
  __param(21, $vqb),
  __param(22, $mJ),
  __param(23, $RL),
  __param(24, $wN),
  __param(25, $9u),
  __param(26, $rs),
  __param(27, $vl),
  __param(28, $xkc)
], $Akc);
var infoButtonClass = ThemeIcon.asClassName($6l.info);
var ContinueEditSessionItem = class {
  constructor(label3, command4, description, when, documentation) {
    this.label = label3;
    this.command = command4;
    this.description = description;
    this.when = when;
    this.documentation = documentation;
    if (documentation !== void 0) {
      this.buttons = [{
        iconClass: infoButtonClass,
        tooltip: localize(6282, null)
      }];
    }
  }
};
var continueEditSessionExtPoint = $tN.registerExtensionPoint({
  extensionPoint: "continueEditSession",
  jsonSchema: {
    description: localize(6283, null),
    type: "array",
    items: {
      type: "object",
      properties: {
        command: {
          description: localize(6284, null),
          type: "string"
        },
        group: {
          description: localize(6285, null),
          type: "string"
        },
        qualifiedName: {
          description: localize(6286, null),
          type: "string"
        },
        description: {
          description: localize(6287, null),
          type: "string"
        },
        remoteGroup: {
          description: localize(6288, null),
          type: "string"
        },
        when: {
          description: localize(6289, null),
          type: "string"
        }
      },
      required: ["command"]
    }
  }
});
var workbenchRegistry7 = $Wn.as(Extensions2.Workbench);
workbenchRegistry7.registerWorkbenchContribution(
  $Akc,
  3
  /* LifecyclePhase.Restored */
);
$Wn.as($Ht.Configuration).registerConfiguration({
  ...$UL,
  "properties": {
    "workbench.experimental.cloudChanges.autoStore": {
      enum: ["onShutdown", "off"],
      enumDescriptions: [
        localize(6290, null),
        localize(6291, null)
      ],
      "type": "string",
      "tags": ["experimental", "usesOnlineServices"],
      "default": "off",
      "markdownDescription": localize(6292, null)
    },
    "workbench.cloudChanges.autoResume": {
      enum: ["onReload", "off"],
      enumDescriptions: [
        localize(6293, null),
        localize(6294, null)
      ],
      "type": "string",
      "tags": ["usesOnlineServices"],
      "default": "onReload",
      "markdownDescription": localize(6295, null)
    },
    "workbench.cloudChanges.continueOn": {
      enum: ["prompt", "off"],
      enumDescriptions: [
        localize(6296, null),
        localize(6297, null)
      ],
      type: "string",
      tags: ["usesOnlineServices"],
      default: "prompt",
      markdownDescription: localize(6298, null)
    },
    "workbench.experimental.cloudChanges.partialMatches.enabled": {
      "type": "boolean",
      "tags": ["experimental", "usesOnlineServices"],
      "default": false,
      "markdownDescription": localize(6299, null)
    }
  }
});

// out-build/vs/workbench/contrib/codeActions/browser/codeActionsContribution.js
var createCodeActionsAutoSave = (description) => {
  return {
    type: "string",
    enum: ["always", "explicit", "never", true, false],
    enumDescriptions: [
      localize(5154, null),
      localize(5155, null),
      localize(5156, null),
      localize(5157, null),
      localize(5158, null)
    ],
    default: "explicit",
    description
  };
};
var createNotebookCodeActionsAutoSave = (description) => {
  return {
    type: ["string", "boolean"],
    enum: ["explicit", "never", true, false],
    enumDescriptions: [
      localize(5159, null),
      localize(5160, null),
      localize(5161, null),
      localize(5162, null)
    ],
    default: "explicit",
    description
  };
};
var codeActionsOnSaveSchema = {
  oneOf: [
    {
      type: "object",
      additionalProperties: {
        type: "string"
      }
    },
    {
      type: "array",
      items: { type: "string" }
    }
  ],
  markdownDescription: localize(5163, null, "`#files.autoSave#`"),
  type: ["object", "array"],
  additionalProperties: {
    type: "string",
    enum: ["always", "explicit", "never", true, false]
  },
  default: {},
  scope: 5
};
var $Bkc = Object.freeze({
  ...$mab,
  properties: {
    "editor.codeActionsOnSave": codeActionsOnSaveSchema
  }
});
var notebookCodeActionsOnSaveSchema = {
  oneOf: [
    {
      type: "object",
      additionalProperties: {
        type: "string"
      }
    },
    {
      type: "array",
      items: { type: "string" }
    }
  ],
  markdownDescription: localize(5164, null, "`#files.autoSave#`"),
  type: "object",
  additionalProperties: {
    type: ["string", "boolean"],
    enum: ["explicit", "never", true, false]
    // enum: ['explicit', 'always', 'never'], -- autosave support needs to be built first
    // nls.localize('always', 'Always triggers Code Actions on save, including autosave, focus, and window change events.'),
  },
  default: {}
};
var $Ckc = Object.freeze({
  ...$mab,
  properties: {
    "notebook.codeActionsOnSave": notebookCodeActionsOnSaveSchema
  }
});
var $Dkc = class $Dkc2 extends $3c {
  constructor(keybindingService, c) {
    super();
    this.c = c;
    this.a = this.B(new $ze());
    this.b = [];
    this.B(Event2.runAndSubscribe(Event2.debounce(c.codeActionProvider.onDidChange, () => {
    }, 1e3), () => {
      this.b = this.f();
      this.g(this.b);
      this.a.fire();
    }));
    keybindingService.registerSchemaContribution({
      getSchemaAdditions: () => this.h(),
      onDidChange: this.a.event
    });
  }
  f() {
    const out = /* @__PURE__ */ new Map();
    for (const provider of this.c.codeActionProvider.allNoModel()) {
      for (const kind of provider.providedCodeActionKinds ?? []) {
        out.set(kind, new $oE(kind));
      }
    }
    return Array.from(out.values());
  }
  g(allProvidedKinds) {
    const properties = { ...codeActionsOnSaveSchema.properties };
    const notebookProperties = { ...notebookCodeActionsOnSaveSchema.properties };
    for (const codeActionKind of allProvidedKinds) {
      if ($pab.Source.contains(codeActionKind) && !properties[codeActionKind.value]) {
        properties[codeActionKind.value] = createCodeActionsAutoSave(localize(5165, null, codeActionKind.value));
        notebookProperties[codeActionKind.value] = createNotebookCodeActionsAutoSave(localize(5166, null, codeActionKind.value));
      }
    }
    codeActionsOnSaveSchema.properties = properties;
    notebookCodeActionsOnSaveSchema.properties = notebookProperties;
    $Wn.as($Ht.Configuration).notifyConfigurationSchemaUpdated($Bkc);
  }
  h() {
    const conditionalSchema = (command4, kinds) => {
      return {
        if: {
          required: ["command"],
          properties: {
            "command": { const: command4 }
          }
        },
        then: {
          properties: {
            "args": {
              required: ["kind"],
              properties: {
                "kind": {
                  anyOf: [
                    { enum: Array.from(kinds) },
                    { type: "string" }
                  ]
                }
              }
            }
          }
        }
      };
    };
    const filterProvidedKinds = (ofKind) => {
      const out = /* @__PURE__ */ new Set();
      for (const providedKind of this.b) {
        if (ofKind.contains(providedKind)) {
          out.add(providedKind.value);
        }
      }
      return Array.from(out);
    };
    return [
      conditionalSchema($uab, filterProvidedKinds($oE.Empty)),
      conditionalSchema($xab, filterProvidedKinds($pab.Refactor)),
      conditionalSchema($zab, filterProvidedKinds($pab.Source))
    ];
  }
};
$Dkc = __decorate([
  __param(0, $Ty),
  __param(1, $mP)
], $Dkc);

// out-build/vs/workbench/contrib/codeActions/browser/codeActions.contribution.js
$Wn.as($Ht.Configuration).registerConfiguration($Bkc);
$Wn.as($Ht.Configuration).registerConfiguration($Ckc);
$Wn.as(Extensions2.Workbench).registerWorkbenchContribution(
  $Dkc,
  4
  /* LifecyclePhase.Eventually */
);

// out-build/vs/workbench/contrib/timeline/common/timelineService.js
var $Ekc = new $nn("timelineHasProvider", false);
var $Fkc = class $Fkc2 {
  constructor(j, k, l, m) {
    this.j = j;
    this.k = k;
    this.l = l;
    this.m = m;
    this.c = new $ze();
    this.onDidChangeProviders = this.c.event;
    this.d = new $ze();
    this.onDidChangeTimeline = this.d.event;
    this.f = new $ze();
    this.onDidChangeUri = this.f.event;
    this.h = /* @__PURE__ */ new Map();
    this.i = /* @__PURE__ */ new Map();
    this.g = $Ekc.bindTo(this.m);
    this.n();
  }
  getSources() {
    return [...this.h.values()].map((p) => ({ id: p.id, label: p.label }));
  }
  getTimeline(id2, uri, options3, tokenSource) {
    this.j.trace(`TimelineService#getTimeline(${id2}): uri=${uri.toString()}`);
    const provider = this.h.get(id2);
    if (provider === void 0) {
      return void 0;
    }
    if (typeof provider.scheme === "string") {
      if (provider.scheme !== "*" && provider.scheme !== uri.scheme) {
        return void 0;
      }
    } else if (!provider.scheme.includes(uri.scheme)) {
      return void 0;
    }
    return {
      result: provider.provideTimeline(uri, options3, tokenSource.token).then((result) => {
        if (result === void 0) {
          return void 0;
        }
        result.items = result.items.map((item) => ({ ...item, source: provider.id }));
        result.items.sort((a, b) => b.timestamp - a.timestamp || b.source.localeCompare(a.source, void 0, { numeric: true, sensitivity: "base" }));
        return result;
      }),
      options: options3,
      source: provider.id,
      tokenSource,
      uri
    };
  }
  registerTimelineProvider(provider) {
    this.j.trace(`TimelineService#registerTimelineProvider: id=${provider.id}`);
    const id2 = provider.id;
    const existing = this.h.get(id2);
    if (existing) {
      try {
        existing?.dispose();
      } catch {
      }
    }
    this.h.set(id2, provider);
    this.n();
    if (provider.onDidChange) {
      this.i.set(id2, provider.onDidChange((e) => this.d.fire(e)));
    }
    this.c.fire({ added: [id2] });
    return {
      dispose: () => {
        this.h.delete(id2);
        this.c.fire({ removed: [id2] });
      }
    };
  }
  unregisterTimelineProvider(id2) {
    this.j.trace(`TimelineService#unregisterTimelineProvider: id=${id2}`);
    if (!this.h.has(id2)) {
      return;
    }
    this.h.delete(id2);
    this.i.delete(id2);
    this.n();
    this.c.fire({ removed: [id2] });
  }
  setUri(uri) {
    this.k.openView($rS, true);
    this.f.fire(uri);
  }
  n() {
    this.g.set(this.h.size !== 0);
  }
};
$Fkc = __decorate([
  __param(0, $wn),
  __param(1, $uob),
  __param(2, $kl),
  __param(3, $on)
], $Fkc);

// out-build/vs/workbench/contrib/timeline/browser/timelinePane.js
var ItemHeight = 22;
function isLoadMoreCommand(item) {
  return item instanceof LoadMoreCommand;
}
function isTimelineItem(item) {
  return !!item && !item.handle.startsWith("vscode-command:");
}
function updateRelativeTime(item, lastRelativeTime) {
  item.relativeTime = isTimelineItem(item) ? $Qu(item.timestamp) : void 0;
  item.relativeTimeFullWord = isTimelineItem(item) ? $Qu(item.timestamp, false, true) : void 0;
  if (lastRelativeTime === void 0 || item.relativeTime !== lastRelativeTime) {
    lastRelativeTime = item.relativeTime;
    item.hideRelativeTime = false;
  } else {
    item.hideRelativeTime = true;
  }
  return lastRelativeTime;
}
var TimelineAggregate = class {
  constructor(timeline) {
    this.d = false;
    this.f = false;
    this.source = timeline.source;
    this.items = timeline.items;
    this.c = timeline.paging?.cursor;
    this.lastRenderedIndex = -1;
  }
  get cursor() {
    return this.c;
  }
  get more() {
    return this.c !== void 0;
  }
  get newest() {
    return this.items[0];
  }
  get oldest() {
    return this.items[this.items.length - 1];
  }
  add(timeline, options3) {
    let updated = false;
    if (timeline.items.length !== 0 && this.items.length !== 0) {
      updated = true;
      const ids = /* @__PURE__ */ new Set();
      const timestamps = /* @__PURE__ */ new Set();
      for (const item2 of timeline.items) {
        if (item2.id === void 0) {
          timestamps.add(item2.timestamp);
        } else {
          ids.add(item2.id);
        }
      }
      let i2 = this.items.length;
      let item;
      while (i2--) {
        item = this.items[i2];
        if (item.id !== void 0 && ids.has(item.id) || timestamps.has(item.timestamp)) {
          this.items.splice(i2, 1);
        }
      }
      if ((timeline.items[timeline.items.length - 1]?.timestamp ?? 0) >= (this.newest?.timestamp ?? 0)) {
        this.items.splice(0, 0, ...timeline.items);
      } else {
        this.items.push(...timeline.items);
      }
    } else if (timeline.items.length !== 0) {
      updated = true;
      this.items.push(...timeline.items);
    }
    if (options3.cursor !== void 0 || typeof options3.limit !== "object") {
      this.c = timeline.paging?.cursor;
    }
    if (updated) {
      this.items.sort((a, b) => b.timestamp - a.timestamp || (a.source === void 0 ? b.source === void 0 ? 0 : 1 : b.source === void 0 ? -1 : b.source.localeCompare(a.source, void 0, { numeric: true, sensitivity: "base" })));
    }
    return updated;
  }
  get stale() {
    return this.d;
  }
  get requiresReset() {
    return this.f;
  }
  invalidate(requiresReset) {
    this.d = true;
    this.f = requiresReset;
  }
};
var LoadMoreCommand = class {
  constructor(loading) {
    this.handle = "vscode-command:loadMore";
    this.timestamp = 0;
    this.description = void 0;
    this.tooltip = void 0;
    this.contextValue = void 0;
    this.id = void 0;
    this.icon = void 0;
    this.iconDark = void 0;
    this.source = void 0;
    this.relativeTime = void 0;
    this.relativeTimeFullWord = void 0;
    this.hideRelativeTime = void 0;
    this.c = false;
    this.c = loading;
  }
  get loading() {
    return this.c;
  }
  set loading(value) {
    this.c = value;
  }
  get ariaLabel() {
    return this.label;
  }
  get label() {
    return this.loading ? localize(11419, null) : localize(11420, null);
  }
  get themeIcon() {
    return void 0;
  }
};
var $Gkc = new $nn("timelineFollowActiveEditor", true, true);
var $Hkc = new $nn("timelineExcludeSources", "[]", true);
var $Ikc = new $nn("timelineFocused", true);
var $Jkc = class $Jkc2 extends $_ob {
  static {
    this.TITLE = localize2(11434, "Timeline");
  }
  constructor(options3, keybindingService, contextMenuService, contextKeyService, configurationService, bc, viewDescriptorService, instantiationService, cc, dc, ec, fc, openerService, themeService, telemetryService, hoverService, gc, hc, ic) {
    super({ ...options3, titleMenuId: $bJ.TimelineTitle }, keybindingService, contextMenuService, configurationService, contextKeyService, viewDescriptorService, instantiationService, openerService, themeService, telemetryService, hoverService);
    this.bc = bc;
    this.cc = cc;
    this.dc = dc;
    this.ec = ec;
    this.fc = fc;
    this.gc = gc;
    this.hc = hc;
    this.ic = ic;
    this.ab = /* @__PURE__ */ new Map();
    this.sb = /* @__PURE__ */ new Map();
    this.jc = true;
    this.xc = true;
    this.yc = 0;
    this.zc = 0;
    this.Fc = false;
    this.m = this.B(this.Db.createInstance(TimelinePaneCommands, this));
    this.r = $Gkc.bindTo(this.Bb);
    this.t = $Hkc.bindTo(this.Bb);
    const excludedSourcesString = bc.get("timeline.excludeSources", 0, "[]");
    this.t.set(excludedSourcesString);
    this.L = new Set(JSON.parse(excludedSourcesString));
    this.B(bc.onDidChangeValue(0, "timeline.excludeSources", this.q)(this.mc, this));
    this.B(configurationService.onDidChangeConfiguration(this.nc, this));
    this.B(fc.onDidChangeProviders(this.pc, this));
    this.B(fc.onDidChangeTimeline(this.qc, this));
    this.B(fc.onDidChangeUri((uri) => this.setUri(uri), this));
  }
  get followActiveEditor() {
    return this.jc;
  }
  set followActiveEditor(value) {
    if (this.jc === value) {
      return;
    }
    this.jc = value;
    this.r.set(value);
    this.updateFilename(this.rc);
    if (value) {
      this.oc();
    }
  }
  get pageOnScroll() {
    if (this.kc === void 0) {
      this.kc = this.Ab.getValue("timeline.pageOnScroll") ?? false;
    }
    return this.kc;
  }
  get pageSize() {
    let pageSize = this.Ab.getValue("timeline.pageSize");
    if (pageSize === void 0 || pageSize === null) {
      pageSize = Math.max(20, Math.floor((this.h?.renderHeight ?? 0 / ItemHeight) + (this.pageOnScroll ? 1 : -1)));
    }
    return pageSize;
  }
  reset() {
    this.Cc(true);
  }
  setUri(uri) {
    this.lc(uri, true);
  }
  lc(uri, disableFollowing) {
    if (disableFollowing) {
      this.followActiveEditor = false;
    }
    this.ac = uri;
    this.updateFilename(uri ? this.gc.getUriBasenameLabel(uri) : void 0);
    this.j?.setUri(uri);
    this.Cc(true);
  }
  mc() {
    const excludedSourcesString = this.bc.get("timeline.excludeSources", 0, "[]");
    this.t.set(excludedSourcesString);
    this.L = new Set(JSON.parse(excludedSourcesString));
    const missing = this.fc.getSources().filter(({ id: id2 }) => !this.L.has(id2) && !this.sb.has(id2));
    if (missing.length !== 0) {
      this.Cc(true, missing.map(({ id: id2 }) => id2));
    } else {
      this.Ic();
    }
  }
  nc(e) {
    if (e.affectsConfiguration("timeline.pageOnScroll")) {
      this.kc = void 0;
    }
  }
  oc() {
    if (!this.followActiveEditor || !this.isExpanded()) {
      return;
    }
    const uri = $mL.getOriginalUri(this.cc.activeEditor, { supportSideBySide: SideBySideEditor.PRIMARY });
    if (this.hc.extUri.isEqual(uri, this.ac) && uri !== void 0 || // Fallback to match on fsPath if we are dealing with files or git schemes
    uri?.fsPath === this.ac?.fsPath && (uri?.scheme === Schemas.file || uri?.scheme === "git") && (this.ac?.scheme === Schemas.file || this.ac?.scheme === "git")) {
      for (const source of this.fc.getSources()) {
        if (this.L.has(source.id)) {
          continue;
        }
        const timeline = this.sb.get(source.id);
        if (timeline !== void 0 && !timeline.stale) {
          continue;
        }
        if (timeline !== void 0) {
          this.Ec(timeline, timeline.requiresReset);
        } else {
          this.Dc(source.id, uri, true);
        }
      }
      return;
    }
    this.lc(uri, false);
  }
  pc(e) {
    if (e.removed) {
      for (const source of e.removed) {
        this.sb.delete(source);
      }
      this.Ic();
    }
    if (e.added) {
      this.Cc(true, e.added);
    }
  }
  qc(e) {
    if (e?.uri === void 0 || this.hc.extUri.isEqual(URI.revive(e.uri), this.ac)) {
      const timeline = this.sb.get(e.id);
      if (timeline === void 0) {
        return;
      }
      if (this.isBodyVisible()) {
        this.Ec(timeline, e.reset);
      } else {
        timeline.invalidate(e.reset);
      }
    }
  }
  updateFilename(filename) {
    this.rc = filename;
    if (this.followActiveEditor || !filename) {
      this.Sb(filename);
    } else {
      this.Sb(`${filename} (pinned)`);
    }
  }
  get message() {
    return this.sc;
  }
  set message(message) {
    this.sc = message;
    this.tc();
  }
  tc() {
    if (this.sc !== void 0) {
      this.uc(this.sc);
    } else {
      this.vc();
    }
  }
  uc(message) {
    if (!this.f) {
      return;
    }
    this.f.classList.remove("hide");
    this.wc();
    this.f.textContent = message;
  }
  vc() {
    this.wc();
    this.f.classList.add("hide");
  }
  wc() {
    $$i(this.f);
  }
  get Ac() {
    return this.zc > 0;
  }
  Bc(cancelPending) {
    this.zc = 0;
    this.yc = this.pageSize;
    this.sb.clear();
    if (cancelPending) {
      for (const { tokenSource } of this.ab.values()) {
        tokenSource.dispose(true);
      }
      this.ab.clear();
      if (!this.isBodyVisible() && this.h) {
        this.h.setChildren(null, void 0);
        this.xc = true;
      }
    }
  }
  async Cc(reset, sources) {
    if (sources === void 0) {
      if (reset) {
        this.Bc(true);
      }
      if (this.ac?.scheme === Schemas.vscodeSettings || this.ac?.scheme === Schemas.webviewPanel || this.ac?.scheme === Schemas.walkThrough) {
        this.ac = void 0;
        this.Bc(false);
        this.Ic();
        return;
      }
      if (this.xc && this.ac !== void 0) {
        this.setLoadingUriMessage();
      }
    }
    if (this.ac === void 0) {
      this.Bc(false);
      this.Ic();
      return;
    }
    if (!this.isBodyVisible()) {
      return;
    }
    let hasPendingRequests = false;
    for (const source of sources ?? this.fc.getSources().map((s) => s.id)) {
      const requested = this.Dc(source, this.ac, reset);
      if (requested) {
        hasPendingRequests = true;
      }
    }
    if (!hasPendingRequests) {
      this.Ic();
    } else if (this.xc) {
      this.setLoadingUriMessage();
    }
  }
  Dc(source, uri, reset, options3) {
    if (this.L.has(source)) {
      return false;
    }
    const timeline = this.sb.get(source);
    if (!reset && options3?.cursor !== void 0 && timeline !== void 0 && (!timeline?.more || timeline.items.length > timeline.lastRenderedIndex + this.pageSize)) {
      return false;
    }
    if (options3 === void 0) {
      if (!reset && timeline !== void 0 && timeline.items.length > 0 && !timeline.more) {
        return false;
      }
      options3 = { cursor: reset ? void 0 : timeline?.cursor, limit: this.pageSize };
    }
    let request = this.ab.get(source);
    if (request !== void 0) {
      options3.cursor = request.options.cursor;
      if (typeof options3.limit === "number") {
        if (typeof request.options.limit === "number") {
          options3.limit += request.options.limit;
        } else {
          options3.limit = request.options.limit;
        }
      }
    }
    request?.tokenSource.dispose(true);
    options3.cacheResults = true;
    options3.resetCache = reset;
    request = this.fc.getTimeline(source, uri, options3, new $ad());
    if (request === void 0) {
      return false;
    }
    this.ab.set(source, request);
    request.tokenSource.token.onCancellationRequested(() => this.ab.delete(source));
    this.Gc(request);
    return true;
  }
  Ec(timeline, reset) {
    if (reset) {
      this.sb.delete(timeline.source);
      const { oldest } = timeline;
      this.Dc(timeline.source, this.ac, true, oldest !== void 0 ? { limit: { timestamp: oldest.timestamp, id: oldest.id } } : void 0);
    } else {
      const { newest } = timeline;
      this.Dc(timeline.source, this.ac, false, newest !== void 0 ? { limit: { timestamp: newest.timestamp, id: newest.id } } : { limit: this.pageSize });
    }
  }
  async Gc(request) {
    let response;
    try {
      response = await this.ec.withProgress({ location: this.id }, () => request.result);
    } finally {
      this.ab.delete(request.source);
    }
    if (response === void 0 || request.tokenSource.token.isCancellationRequested || request.uri !== this.ac) {
      if (this.ab.size === 0 && this.Fc) {
        this.Ic();
      }
      return;
    }
    const source = request.source;
    let updated = false;
    const timeline = this.sb.get(source);
    if (timeline === void 0) {
      this.sb.set(source, new TimelineAggregate(response));
      updated = true;
    } else {
      updated = timeline.add(response, request.options);
    }
    if (updated) {
      this.Fc = true;
      if (this.Ac && this.ab.size !== 0) {
        this.Jc();
      } else {
        this.Ic();
      }
    } else if (this.ab.size === 0) {
      if (this.Fc) {
        this.Ic();
      } else {
        this.h.rerender();
      }
    }
  }
  *Hc() {
    let more = false;
    if (this.ac === void 0 || this.sb.size === 0) {
      this.zc = 0;
      return;
    }
    const maxCount = this.yc;
    let count = 0;
    if (this.sb.size === 1) {
      const [source, timeline] = Iterable.first(this.sb);
      timeline.lastRenderedIndex = -1;
      if (this.L.has(source)) {
        this.zc = 0;
        return;
      }
      if (timeline.items.length !== 0) {
        this.zc = 1;
      }
      more = timeline.more;
      let lastRelativeTime;
      for (const item of timeline.items) {
        item.relativeTime = void 0;
        item.hideRelativeTime = void 0;
        count++;
        if (count > maxCount) {
          more = true;
          break;
        }
        lastRelativeTime = updateRelativeTime(item, lastRelativeTime);
        yield { element: item };
      }
      timeline.lastRenderedIndex = count - 1;
    } else {
      let getNextMostRecentSource2 = function() {
        return sources.filter((source) => !source.nextItem.done).reduce((previous, current) => previous === void 0 || current.nextItem.value.timestamp >= previous.nextItem.value.timestamp ? current : previous, void 0);
      };
      var getNextMostRecentSource = getNextMostRecentSource2;
      const sources = [];
      let hasAnyItems = false;
      let mostRecentEnd = 0;
      for (const [source, timeline] of this.sb) {
        timeline.lastRenderedIndex = -1;
        if (this.L.has(source) || timeline.stale) {
          continue;
        }
        if (timeline.items.length !== 0) {
          hasAnyItems = true;
        }
        if (timeline.more) {
          more = true;
          const last = timeline.items[Math.min(maxCount, timeline.items.length - 1)];
          if (last.timestamp > mostRecentEnd) {
            mostRecentEnd = last.timestamp;
          }
        }
        const iterator = timeline.items[Symbol.iterator]();
        sources.push({ timeline, iterator, nextItem: iterator.next() });
      }
      this.zc = hasAnyItems ? 1 : 0;
      let lastRelativeTime;
      let nextSource;
      while (nextSource = getNextMostRecentSource2()) {
        nextSource.timeline.lastRenderedIndex++;
        const item = nextSource.nextItem.value;
        item.relativeTime = void 0;
        item.hideRelativeTime = void 0;
        if (item.timestamp >= mostRecentEnd) {
          count++;
          if (count > maxCount) {
            more = true;
            break;
          }
          lastRelativeTime = updateRelativeTime(item, lastRelativeTime);
          yield { element: item };
        }
        nextSource.nextItem = nextSource.iterator.next();
      }
    }
    this.zc = count;
    if (count > 0) {
      if (more) {
        yield {
          element: new LoadMoreCommand(this.ab.size !== 0)
        };
      } else if (this.ab.size !== 0) {
        yield {
          element: new LoadMoreCommand(true)
        };
      }
    }
  }
  Ic() {
    if (!this.isBodyVisible()) {
      return;
    }
    this.h.setChildren(null, this.Hc());
    this.xc = !this.Ac;
    if (this.ac === void 0) {
      this.updateFilename(void 0);
      this.message = localize(11421, null);
    } else if (this.xc) {
      if (this.ab.size !== 0) {
        this.setLoadingUriMessage();
      } else {
        this.updateFilename(this.gc.getUriBasenameLabel(this.ac));
        const scmProviderCount = this.Bb.getContextKeyValue("scm.providerCount");
        if (this.fc.getSources().filter(({ id: id2 }) => !this.L.has(id2)).length === 0) {
          this.message = localize(11422, null);
        } else {
          if (this.Ab.getValue("workbench.localHistory.enabled") && !this.L.has("timeline.localHistory")) {
            this.message = localize(11423, null);
          } else if (this.L.size > 0) {
            this.message = localize(11424, null);
          } else {
            this.message = localize(11425, null);
          }
        }
        if (!scmProviderCount || scmProviderCount === 0) {
          this.message += " " + localize(11426, null);
        }
      }
    } else {
      this.updateFilename(this.gc.getUriBasenameLabel(this.ac));
      this.message = void 0;
    }
    this.Fc = false;
  }
  Jc() {
    this.Ic();
  }
  focus() {
    super.focus();
    this.h.domFocus();
  }
  setExpanded(expanded2) {
    const changed = super.setExpanded(expanded2);
    if (changed && this.isBodyVisible()) {
      if (!this.followActiveEditor) {
        this.lc(this.ac, true);
      } else {
        this.oc();
      }
    }
    return changed;
  }
  setVisible(visible) {
    if (visible) {
      this.ic.activateByEvent("onView:timeline");
      this.n = new $2c();
      this.cc.onDidActiveEditorChange(this.oc, this, this.n);
      this.onDidFocus(() => this.Jc(), this, this.n);
      super.setVisible(visible);
      this.oc();
    } else {
      this.n?.dispose();
      super.setVisible(visible);
    }
  }
  X(height, width2) {
    super.X(height, width2);
    this.h.layout(height, width2);
  }
  Ob(container2) {
    super.Ob(container2, this.title);
    container2.classList.add("timeline-view");
  }
  W(container2) {
    super.W(container2);
    this.c = container2;
    container2.classList.add("tree-explorer-viewlet-tree-view", "timeline-tree-view");
    this.f = $bk(this.c, $(".message"));
    this.f.classList.add("timeline-subtle");
    this.message = localize(11427, null);
    this.g = document.createElement("div");
    this.g.classList.add("customview-tree", "file-icon-themable-tree", "hide-arrows");
    container2.appendChild(this.g);
    this.j = this.Db.createInstance(TimelineTreeRenderer, this.m);
    this.j.onDidScrollToEnd((item) => {
      if (this.pageOnScroll) {
        this.Nc(item);
      }
    });
    this.h = this.Db.createInstance($1eb, "TimelinePane", this.g, new $Mkc(), [this.j], {
      identityProvider: new $Kkc(),
      accessibilityProvider: {
        getAriaLabel(element) {
          if (isLoadMoreCommand(element)) {
            return element.ariaLabel;
          }
          return element.accessibilityInformation ? element.accessibilityInformation.label : localize(11428, null, element.relativeTimeFullWord ?? "", element.label);
        },
        getRole(element) {
          if (isLoadMoreCommand(element)) {
            return "treeitem";
          }
          return element.accessibilityInformation && element.accessibilityInformation.role ? element.accessibilityInformation.role : "treeitem";
        },
        getWidgetAriaLabel() {
          return localize(11429, null);
        }
      },
      keyboardNavigationLabelProvider: new $Lkc(),
      multipleSelectionSupport: false,
      overrideStyles: this.Xb().listOverrideStyles
    });
    $Ikc.bindTo(this.h.contextKeyService);
    this.B(this.h.onContextMenu((e) => this.Oc(this.m, e)));
    this.B(this.h.onDidChangeSelection((e) => this.ensureValidItems()));
    this.B(this.h.onDidOpen((e) => {
      if (!e.browserEvent || !this.ensureValidItems()) {
        return;
      }
      const selection = this.h.getSelection();
      let item;
      if (selection.length === 1) {
        item = selection[0];
      }
      if (item === null) {
        return;
      }
      if (isTimelineItem(item)) {
        if (item.command) {
          let args2 = item.command.arguments ?? [];
          if (item.command.id === $$ub || item.command.id === $_ub) {
            args2 = [...args2, e];
          }
          this.dc.executeCommand(item.command.id, ...args2);
        }
      } else if (isLoadMoreCommand(item)) {
        this.Nc(item);
      }
    }));
  }
  Nc(item) {
    if (item.loading) {
      return;
    }
    item.loading = true;
    this.h.rerender(item);
    if (this.ab.size !== 0) {
      return;
    }
    this.yc = this.zc + this.pageSize;
    this.Cc(false);
  }
  ensureValidItems() {
    if (!this.Ac || !this.fc.getSources().some(({ id: id2 }) => !this.L.has(id2) && this.sb.has(id2))) {
      this.h.setChildren(null, void 0);
      this.xc = true;
      this.setLoadingUriMessage();
      return false;
    }
    return true;
  }
  setLoadingUriMessage() {
    const file = this.ac && this.gc.getUriBasenameLabel(this.ac);
    this.updateFilename(file);
    this.message = file ? localize(11430, null, file) : "";
  }
  Oc(commands2, treeEvent) {
    const item = treeEvent.element;
    if (item === null) {
      return;
    }
    const event = treeEvent.browserEvent;
    event.preventDefault();
    event.stopPropagation();
    if (!this.ensureValidItems()) {
      return;
    }
    this.h.setFocus([item]);
    const actions = commands2.getItemContextActions(item);
    if (!actions.length) {
      return;
    }
    this.zb.showContextMenu({
      getAnchor: () => treeEvent.anchor,
      getActions: () => actions,
      getActionViewItem: (action) => {
        const keybinding = this.yb.lookupKeybinding(action.id);
        if (keybinding) {
          return new $U1(action, action, { label: true, keybinding: keybinding.getLabel() });
        }
        return void 0;
      },
      onHide: (wasCancelled) => {
        if (wasCancelled) {
          this.h.domFocus();
        }
      },
      getActionsContext: () => ({ uri: this.ac, item }),
      actionRunner: new TimelineActionRunner()
    });
  }
};
__decorate([
  $$t(500)
], $Jkc.prototype, "Jc", null);
$Jkc = __decorate([
  __param(1, $Ty),
  __param(2, $50),
  __param(3, $on),
  __param(4, $kl),
  __param(5, $jv),
  __param(6, $$M),
  __param(7, $Pk),
  __param(8, $mJ),
  __param(9, $sn),
  __param(10, $TJ),
  __param(11, $sS),
  __param(12, $O4),
  __param(13, $gs),
  __param(14, $zv),
  __param(15, $5$),
  __param(16, $ZI),
  __param(17, $vl),
  __param(18, $wN)
], $Jkc);
var TimelineElementTemplate = class {
  static {
    this.id = "TimelineElementTemplate";
  }
  constructor(container2, actionViewItemProvider, hoverDelegate) {
    container2.classList.add("custom-view-tree-node-item");
    this.icon = $bk(container2, $(".custom-view-tree-node-item-icon"));
    this.iconLabel = new $T2(container2, { supportHighlights: true, supportIcons: true, hoverDelegate });
    const timestampContainer = $bk(this.iconLabel.element, $(".timeline-timestamp-container"));
    this.timestamp = $bk(timestampContainer, $("span.timeline-timestamp"));
    const actionsContainer = $bk(this.iconLabel.element, $(".actions"));
    this.actionBar = new $LZ(actionsContainer, { actionViewItemProvider });
  }
  dispose() {
    this.iconLabel.dispose();
    this.actionBar.dispose();
  }
  reset() {
    this.icon.className = "";
    this.icon.style.backgroundImage = "";
    this.actionBar.clear();
  }
};
var $Kkc = class {
  getId(item) {
    return item.handle;
  }
};
var TimelineActionRunner = class extends $Vm {
  async u(action, { uri, item }) {
    if (!isTimelineItem(item)) {
      await action.run();
      return;
    }
    await action.run({
      $mid: 12,
      handle: item.handle,
      source: item.source,
      uri
    }, uri, item.source);
  }
};
var $Lkc = class {
  getKeyboardNavigationLabel(element) {
    return element.label;
  }
};
var $Mkc = class {
  getHeight(_element) {
    return ItemHeight;
  }
  getTemplateId(element) {
    return TimelineElementTemplate.id;
  }
};
var TimelineTreeRenderer = class TimelineTreeRenderer2 {
  constructor(g, h3, j) {
    this.g = g;
    this.h = h3;
    this.j = j;
    this.c = new $ze();
    this.onDidScrollToEnd = this.c.event;
    this.templateId = TimelineElementTemplate.id;
    this.f = $X$.bind(void 0, this.h);
    this.d = this.h.createInstance($6$, "element", false, {
      position: {
        hoverPosition: 1
        /* HoverPosition.RIGHT */
        // Will flip when there's no space
      }
    });
  }
  setUri(uri) {
    this.k = uri;
  }
  renderTemplate(container2) {
    return new TimelineElementTemplate(container2, this.f, this.d);
  }
  renderElement(node, index, template, height) {
    template.reset();
    const { element: item } = node;
    const theme = this.j.getColorTheme();
    const icon2 = theme.type === ColorScheme.LIGHT ? item.icon : item.iconDark;
    const iconUrl = icon2 ? URI.revive(icon2) : null;
    if (iconUrl) {
      template.icon.className = "custom-view-tree-node-item-icon";
      template.icon.style.backgroundImage = $5Z(iconUrl);
      template.icon.style.color = "";
    } else if (item.themeIcon) {
      template.icon.className = `custom-view-tree-node-item-icon ${ThemeIcon.asClassName(item.themeIcon)}`;
      if (item.themeIcon.color) {
        template.icon.style.color = theme.getColor(item.themeIcon.color.id)?.toString() ?? "";
      } else {
        template.icon.style.color = "";
      }
      template.icon.style.backgroundImage = "";
    } else {
      template.icon.className = "custom-view-tree-node-item-icon";
      template.icon.style.backgroundImage = "";
      template.icon.style.color = "";
    }
    const tooltip = item.tooltip ? $zg(item.tooltip) ? item.tooltip : { markdown: item.tooltip, markdownNotSupportedFallback: $G1(item.tooltip) } : void 0;
    template.iconLabel.setLabel(item.label, item.description, {
      title: tooltip,
      matches: $Ul(node.filterData)
    });
    template.timestamp.textContent = item.relativeTime ?? "";
    template.timestamp.ariaLabel = item.relativeTimeFullWord ?? "";
    template.timestamp.parentElement.classList.toggle("timeline-timestamp--duplicate", isTimelineItem(item) && item.hideRelativeTime);
    template.actionBar.context = { uri: this.k, item };
    template.actionBar.actionRunner = new TimelineActionRunner();
    template.actionBar.push(this.g.getItemActions(item), { icon: true, label: false });
    if (isLoadMoreCommand(item)) {
      setTimeout(() => this.c.fire(item), 0);
    }
  }
  disposeTemplate(template) {
    template.dispose();
  }
};
TimelineTreeRenderer = __decorate([
  __param(1, $Pk),
  __param(2, $gs)
], TimelineTreeRenderer);
var timelineRefresh = $9r("timeline-refresh", $6l.refresh, localize(11431, null));
var timelinePin = $9r("timeline-pin", $6l.pin, localize(11432, null));
var timelineUnpin = $9r("timeline-unpin", $6l.pinned, localize(11433, null));
var TimelinePaneCommands = class TimelinePaneCommands2 extends $3c {
  constructor(f, g, h3, j, m) {
    super();
    this.f = f;
    this.g = g;
    this.h = h3;
    this.j = j;
    this.m = m;
    this.B(this.c = new $2c());
    this.B($hJ(class extends $gJ {
      constructor() {
        super({
          id: "timeline.refresh",
          title: localize2(11435, "Refresh"),
          icon: timelineRefresh,
          category: localize2(11436, "Timeline"),
          menu: {
            id: $bJ.TimelineTitle,
            group: "navigation",
            order: 99
          }
        });
      }
      run(accessor, ...args2) {
        f.reset();
      }
    }));
    this.B($tn.registerCommand("timeline.toggleFollowActiveEditor", (accessor, ...args2) => f.followActiveEditor = !f.followActiveEditor));
    this.B($dJ.appendMenuItem($bJ.TimelineTitle, {
      command: {
        id: "timeline.toggleFollowActiveEditor",
        title: localize2(11437, "Pin the Current Timeline"),
        icon: timelinePin,
        category: localize2(11438, "Timeline")
      },
      group: "navigation",
      order: 98,
      when: $Gkc
    }));
    this.B($dJ.appendMenuItem($bJ.TimelineTitle, {
      command: {
        id: "timeline.toggleFollowActiveEditor",
        title: localize2(11439, "Unpin the Current Timeline"),
        icon: timelineUnpin,
        category: localize2(11440, "Timeline")
      },
      group: "navigation",
      order: 98,
      when: $Gkc.toNegated()
    }));
    this.B(g.onDidChangeProviders(() => this.r()));
    this.r();
  }
  getItemActions(element) {
    return this.n($bJ.TimelineItemContext, { key: "timelineItem", value: element.contextValue }).primary;
  }
  getItemContextActions(element) {
    return this.n($bJ.TimelineItemContext, { key: "timelineItem", value: element.contextValue }).secondary;
  }
  n(menuId, context) {
    const contextKeyService = this.j.createOverlay([
      ["view", this.f.id],
      [context.key, context.value]
    ]);
    const menu = this.m.getMenuActions(menuId, contextKeyService, { shouldForwardArgs: true });
    return $O$(menu, "inline");
  }
  r() {
    this.c.clear();
    const excluded = new Set(JSON.parse(this.h.get("timeline.excludeSources", 0, "[]")));
    for (const source of this.g.getSources()) {
      this.c.add($hJ(class extends $gJ {
        constructor() {
          super({
            id: `timeline.toggleExcludeSource:${source.id}`,
            title: source.label,
            menu: {
              id: $bJ.TimelineFilterSubMenu,
              group: "navigation"
            },
            toggled: $7m.regex(`timelineExcludeSources`, new RegExp(`\\b${$Af(source.id)}\\b`)).negate()
          });
        }
        run(accessor, ...args2) {
          if (excluded.has(source.id)) {
            excluded.delete(source.id);
          } else {
            excluded.add(source.id);
          }
          const storageService = accessor.get($jv);
          storageService.store(
            "timeline.excludeSources",
            JSON.stringify([...excluded.keys()]),
            0,
            0
            /* StorageTarget.USER */
          );
        }
      }));
    }
  }
};
TimelinePaneCommands = __decorate([
  __param(1, $sS),
  __param(2, $jv),
  __param(3, $on),
  __param(4, $cJ)
], TimelinePaneCommands);

// out-build/vs/workbench/contrib/timeline/browser/timeline.contribution.js
var timelineViewIcon = $9r("timeline-view-icon", $6l.history, localize(11411, null));
var timelineOpenIcon = $9r("timeline-open", $6l.history, localize(11412, null));
var $Nkc = class {
  constructor() {
    this.id = $rS;
    this.name = $Jkc.TITLE;
    this.containerIcon = timelineViewIcon;
    this.ctorDescriptor = new $Nk($Jkc);
    this.order = 2;
    this.weight = 30;
    this.collapsed = true;
    this.canToggleVisibility = true;
    this.hideByDefault = false;
    this.canMoveView = true;
    this.when = $Ekc;
    this.focusCommand = { id: "timeline.focus" };
  }
};
var configurationRegistry17 = $Wn.as($Ht.Configuration);
configurationRegistry17.registerConfiguration({
  id: "timeline",
  order: 1001,
  title: localize(11413, null),
  type: "object",
  properties: {
    "timeline.pageSize": {
      type: ["number", "null"],
      default: null,
      markdownDescription: localize(11414, null)
    },
    "timeline.pageOnScroll": {
      type: "boolean",
      default: false,
      description: localize(11415, null)
    }
  }
});
$Wn.as(Extensions5.ViewsRegistry).registerViews([new $Nkc()], $dzb);
var OpenTimelineAction;
(function(OpenTimelineAction2) {
  OpenTimelineAction2.ID = "files.openTimeline";
  OpenTimelineAction2.LABEL = localize(11416, null);
  function handler() {
    return (accessor, arg) => {
      const service = accessor.get($sS);
      return service.setUri(arg);
    };
  }
  OpenTimelineAction2.handler = handler;
})(OpenTimelineAction || (OpenTimelineAction = {}));
$tn.registerCommand(OpenTimelineAction.ID, OpenTimelineAction.handler());
$dJ.appendMenuItem($bJ.ExplorerContext, {
  group: "4_timeline",
  order: 1,
  command: {
    id: OpenTimelineAction.ID,
    title: OpenTimelineAction.LABEL,
    icon: timelineOpenIcon
  },
  when: $7m.and($7sb.toNegated(), $lqb.HasResource, $Ekc)
});
var timelineFilter = $9r("timeline-filter", $6l.filter, localize(11417, null));
$dJ.appendMenuItem($bJ.TimelineTitle, {
  submenu: $bJ.TimelineFilterSubMenu,
  title: localize(11418, null),
  group: "navigation",
  order: 100,
  icon: timelineFilter
});
$SC(
  $sS,
  $Fkc,
  1
  /* InstantiationType.Delayed */
);

// out-build/vs/workbench/services/workingCopy/common/workingCopyHistory.js
var $Okc = $Qk("workingCopyHistoryService");
var $Pkc = 20;

// out-build/vs/workbench/contrib/localHistory/browser/localHistoryFileSystemProvider.js
var $Qkc = class _$Qkc {
  static {
    this.SCHEMA = "vscode-local-history";
  }
  static toLocalHistoryFileSystem(resource) {
    const serializedLocalHistoryResource = {
      location: resource.location.toString(true),
      associatedResource: resource.associatedResource.toString(true)
    };
    return resource.associatedResource.with({
      scheme: _$Qkc.SCHEMA,
      query: JSON.stringify(serializedLocalHistoryResource)
    });
  }
  static fromLocalHistoryFileSystem(resource) {
    const serializedLocalHistoryResource = JSON.parse(resource.query);
    return {
      location: URI.parse(serializedLocalHistoryResource.location),
      associatedResource: URI.parse(serializedLocalHistoryResource.associatedResource)
    };
  }
  static {
    this.a = URI.from({ scheme: _$Qkc.SCHEMA, path: "/empty" });
  }
  static {
    this.EMPTY = {
      location: _$Qkc.a,
      associatedResource: _$Qkc.a
    };
  }
  get capabilities() {
    return 2 | 2048;
  }
  constructor(b) {
    this.b = b;
    this.c = /* @__PURE__ */ new Map();
    this.onDidChangeCapabilities = Event2.None;
    this.onDidChangeFile = Event2.None;
  }
  async d(resource) {
    const scheme = resource.scheme;
    let providerPromise = this.c.get(scheme);
    if (!providerPromise) {
      const provider = this.b.getProvider(scheme);
      if (provider) {
        providerPromise = Promise.resolve(provider);
      } else {
        providerPromise = new Promise((resolve) => {
          const disposable = this.b.onDidChangeFileSystemProviderRegistrations((e) => {
            if (e.added && e.provider && e.scheme === scheme) {
              disposable.dispose();
              resolve(e.provider);
            }
          });
        });
      }
      this.c.set(scheme, providerPromise);
    }
    return providerPromise;
  }
  //#region Supported File Operations
  async stat(resource) {
    const location3 = _$Qkc.fromLocalHistoryFileSystem(resource).location;
    if ($oh(_$Qkc.a, location3)) {
      return { type: FileType.File, ctime: 0, mtime: 0, size: 0 };
    }
    return (await this.d(location3)).stat(location3);
  }
  async readFile(resource) {
    const location3 = _$Qkc.fromLocalHistoryFileSystem(resource).location;
    if ($oh(_$Qkc.a, location3)) {
      return $Ci.fromString("").buffer;
    }
    const provider = await this.d(location3);
    if ($nm(provider)) {
      return provider.readFile(location3);
    }
    throw new Error("Unsupported");
  }
  async writeFile(resource, content, opts) {
  }
  async mkdir(resource) {
  }
  async readdir(resource) {
    return [];
  }
  async rename(from, to, opts) {
  }
  async delete(resource, opts) {
  }
  watch(resource, opts) {
    return $3c.None;
  }
};

// out-build/vs/workbench/contrib/localHistory/browser/localHistory.js
var localHistoryDateFormatter = void 0;
function $Rkc() {
  if (!localHistoryDateFormatter) {
    const options3 = { year: "numeric", month: "long", day: "numeric", hour: "numeric", minute: "numeric" };
    const formatter = $Uu.DateTimeFormat($z, options3);
    localHistoryDateFormatter = {
      format: (date) => formatter.format(date)
    };
  }
  return localHistoryDateFormatter;
}
var $Skc = "localHistory:item";
var $Tkc = $7m.equals("timelineItem", $Skc);
var $Ukc = $9r("localHistory-icon", $6l.circleOutline, localize(7718, null));
var $Vkc = $9r("localHistory-restore", $6l.check, localize(7719, null));

// out-build/vs/workbench/contrib/localHistory/browser/localHistoryCommands.js
var LOCAL_HISTORY_CATEGORY = localize2(7740, "Local History");
var CTX_LOCAL_HISTORY_ENABLED = $7m.has("config.workbench.localHistory.enabled");
var $Wkc = localize2(7741, "Compare with File");
$hJ(class extends $gJ {
  constructor() {
    super({
      id: "workbench.action.localHistory.compareWithFile",
      title: $Wkc,
      menu: {
        id: $bJ.TimelineItemContext,
        group: "1_compare",
        order: 1,
        when: $Tkc
      }
    });
  }
  async run(accessor, item) {
    const commandService = accessor.get($sn);
    const workingCopyHistoryService = accessor.get($Okc);
    const { entry } = await $Ykc(workingCopyHistoryService, item);
    if (entry) {
      return commandService.executeCommand($_ub, ...$Xkc(entry, entry.workingCopy.resource));
    }
  }
});
$hJ(class extends $gJ {
  constructor() {
    super({
      id: "workbench.action.localHistory.compareWithPrevious",
      title: localize2(7742, "Compare with Previous"),
      menu: {
        id: $bJ.TimelineItemContext,
        group: "1_compare",
        order: 2,
        when: $Tkc
      }
    });
  }
  async run(accessor, item) {
    const commandService = accessor.get($sn);
    const workingCopyHistoryService = accessor.get($Okc);
    const editorService = accessor.get($mJ);
    const { entry, previous } = await $Ykc(workingCopyHistoryService, item);
    if (entry) {
      if (!previous) {
        return openEntry(entry, editorService);
      }
      return commandService.executeCommand($_ub, ...$Xkc(previous, entry));
    }
  }
});
var itemSelectedForCompare = void 0;
var LocalHistoryItemSelectedForCompare = new $nn("localHistoryItemSelectedForCompare", false, true);
$hJ(class extends $gJ {
  constructor() {
    super({
      id: "workbench.action.localHistory.selectForCompare",
      title: localize2(7743, "Select for Compare"),
      menu: {
        id: $bJ.TimelineItemContext,
        group: "2_compare_with",
        order: 2,
        when: $Tkc
      }
    });
  }
  async run(accessor, item) {
    const workingCopyHistoryService = accessor.get($Okc);
    const contextKeyService = accessor.get($on);
    const { entry } = await $Ykc(workingCopyHistoryService, item);
    if (entry) {
      itemSelectedForCompare = item;
      LocalHistoryItemSelectedForCompare.bindTo(contextKeyService).set(true);
    }
  }
});
$hJ(class extends $gJ {
  constructor() {
    super({
      id: "workbench.action.localHistory.compareWithSelected",
      title: localize2(7744, "Compare with Selected"),
      menu: {
        id: $bJ.TimelineItemContext,
        group: "2_compare_with",
        order: 1,
        when: $7m.and($Tkc, LocalHistoryItemSelectedForCompare)
      }
    });
  }
  async run(accessor, item) {
    const workingCopyHistoryService = accessor.get($Okc);
    const commandService = accessor.get($sn);
    if (!itemSelectedForCompare) {
      return;
    }
    const selectedEntry = (await $Ykc(workingCopyHistoryService, itemSelectedForCompare)).entry;
    if (!selectedEntry) {
      return;
    }
    const { entry } = await $Ykc(workingCopyHistoryService, item);
    if (entry) {
      return commandService.executeCommand($_ub, ...$Xkc(selectedEntry, entry));
    }
  }
});
$hJ(class extends $gJ {
  constructor() {
    super({
      id: "workbench.action.localHistory.open",
      title: localize2(7745, "Show Contents"),
      menu: {
        id: $bJ.TimelineItemContext,
        group: "3_contents",
        order: 1,
        when: $Tkc
      }
    });
  }
  async run(accessor, item) {
    const workingCopyHistoryService = accessor.get($Okc);
    const editorService = accessor.get($mJ);
    const { entry } = await $Ykc(workingCopyHistoryService, item);
    if (entry) {
      return openEntry(entry, editorService);
    }
  }
});
var RESTORE_CONTENTS_LABEL = localize2(7746, "Restore Contents");
$hJ(class extends $gJ {
  constructor() {
    super({
      id: "workbench.action.localHistory.restoreViaEditor",
      title: RESTORE_CONTENTS_LABEL,
      menu: {
        id: $bJ.EditorTitle,
        group: "navigation",
        order: -10,
        when: $lqb.Scheme.isEqualTo($Qkc.SCHEMA)
      },
      icon: $Vkc
    });
  }
  async run(accessor, uri) {
    const { associatedResource, location: location3 } = $Qkc.fromLocalHistoryFileSystem(uri);
    return restore(accessor, { uri: associatedResource, handle: $rh(location3) });
  }
});
$hJ(class extends $gJ {
  constructor() {
    super({
      id: "workbench.action.localHistory.restore",
      title: RESTORE_CONTENTS_LABEL,
      menu: {
        id: $bJ.TimelineItemContext,
        group: "3_contents",
        order: 2,
        when: $Tkc
      }
    });
  }
  async run(accessor, item) {
    return restore(accessor, item);
  }
});
var restoreSaveSource = $bL.registerSource("localHistoryRestore.source", localize(7720, null));
async function restore(accessor, item) {
  const fileService = accessor.get($km);
  const dialogService = accessor.get($Yv);
  const workingCopyService = accessor.get($XI);
  const workingCopyHistoryService = accessor.get($Okc);
  const editorService = accessor.get($mJ);
  const { entry } = await $Ykc(workingCopyHistoryService, item);
  if (entry) {
    const { confirmed } = await dialogService.confirm({
      type: "warning",
      message: localize(7721, null, $sh(entry.workingCopy.resource)),
      detail: localize(7722, null),
      primaryButton: localize(7723, null)
    });
    if (!confirmed) {
      return;
    }
    const workingCopies = workingCopyService.getAll(entry.workingCopy.resource);
    if (workingCopies) {
      for (const workingCopy of workingCopies) {
        if (workingCopy.isDirty()) {
          await workingCopy.revert({ soft: true });
        }
      }
    }
    try {
      await fileService.cloneFile(entry.location, entry.workingCopy.resource);
    } catch (error) {
      await dialogService.error(localize(7724, null, $sh(entry.workingCopy.resource)), $1m(error));
      return;
    }
    if (workingCopies) {
      for (const workingCopy of workingCopies) {
        await workingCopy.revert({ force: true });
      }
    }
    await editorService.openEditor({ resource: entry.workingCopy.resource });
    await workingCopyHistoryService.addEntry({
      resource: entry.workingCopy.resource,
      source: restoreSaveSource
    }, CancellationToken.None);
    await closeEntry(entry, editorService);
  }
}
$hJ(class extends $gJ {
  constructor() {
    super({
      id: "workbench.action.localHistory.restoreViaPicker",
      title: localize2(7747, "Find Entry to Restore"),
      f1: true,
      category: LOCAL_HISTORY_CATEGORY,
      precondition: CTX_LOCAL_HISTORY_ENABLED
    });
  }
  async run(accessor) {
    const workingCopyHistoryService = accessor.get($Okc);
    const quickInputService = accessor.get($1M);
    const modelService = accessor.get($sG);
    const languageService = accessor.get($1E);
    const labelService = accessor.get($ZI);
    const editorService = accessor.get($mJ);
    const fileService = accessor.get($km);
    const commandService = accessor.get($sn);
    const historyService = accessor.get($tY);
    const resourcePickerDisposables = new $2c();
    const resourcePicker = resourcePickerDisposables.add(quickInputService.createQuickPick());
    let cts = new $ad();
    resourcePickerDisposables.add(resourcePicker.onDidHide(() => cts.dispose(true)));
    resourcePicker.busy = true;
    resourcePicker.show();
    const resources = new $Fc(await workingCopyHistoryService.getAll(cts.token));
    const recentEditorResources = new $Fc($Mb(historyService.getHistory().map(({ resource: resource2 }) => resource2)));
    const resourcesSortedByRecency = [];
    for (const resource2 of recentEditorResources) {
      if (resources.has(resource2)) {
        resourcesSortedByRecency.push(resource2);
        resources.delete(resource2);
      }
    }
    resourcesSortedByRecency.push(...[...resources].sort((r1, r2) => r1.fsPath < r2.fsPath ? -1 : 1));
    resourcePicker.busy = false;
    resourcePicker.placeholder = localize(7725, null);
    resourcePicker.matchOnLabel = true;
    resourcePicker.matchOnDescription = true;
    resourcePicker.items = [...resourcesSortedByRecency].map((resource2) => ({
      resource: resource2,
      label: $rh(resource2),
      description: labelService.getUriLabel($uh(resource2), { relative: true }),
      iconClasses: $gdb(modelService, languageService, resource2)
    }));
    await Event2.toPromise(resourcePicker.onDidAccept);
    resourcePickerDisposables.dispose();
    const resource = resourcePicker.selectedItems.at(0)?.resource;
    if (!resource) {
      return;
    }
    const entryPickerDisposables = new $2c();
    const entryPicker = entryPickerDisposables.add(quickInputService.createQuickPick());
    cts = new $ad();
    entryPickerDisposables.add(entryPicker.onDidHide(() => cts.dispose(true)));
    entryPicker.busy = true;
    entryPicker.show();
    const entries2 = await workingCopyHistoryService.getEntries(resource, cts.token);
    entryPicker.busy = false;
    entryPicker.canAcceptInBackground = true;
    entryPicker.placeholder = localize(7726, null);
    entryPicker.matchOnLabel = true;
    entryPicker.matchOnDescription = true;
    entryPicker.items = Array.from(entries2).reverse().map((entry) => ({
      entry,
      label: `$(circle-outline) ${$bL.getSourceLabel(entry.source)}`,
      description: toLocalHistoryEntryDateLabel(entry.timestamp)
    }));
    entryPickerDisposables.add(entryPicker.onDidAccept(async (e) => {
      if (!e.inBackground) {
        entryPickerDisposables.dispose();
      }
      const selectedItem = entryPicker.selectedItems.at(0);
      if (!selectedItem) {
        return;
      }
      const resourceExists = await fileService.exists(selectedItem.entry.workingCopy.resource);
      if (resourceExists) {
        return commandService.executeCommand($_ub, ...$Xkc(selectedItem.entry, selectedItem.entry.workingCopy.resource, { preserveFocus: e.inBackground }));
      }
      return openEntry(selectedItem.entry, editorService, { preserveFocus: e.inBackground });
    }));
  }
});
$dJ.appendMenuItem($bJ.TimelineTitle, { command: { id: "workbench.action.localHistory.restoreViaPicker", title: localize2(7748, "Local History: Find Entry to Restore...") }, group: "submenu", order: 1, when: CTX_LOCAL_HISTORY_ENABLED });
$hJ(class extends $gJ {
  constructor() {
    super({
      id: "workbench.action.localHistory.rename",
      title: localize2(7749, "Rename"),
      menu: {
        id: $bJ.TimelineItemContext,
        group: "5_edit",
        order: 1,
        when: $Tkc
      }
    });
  }
  async run(accessor, item) {
    const workingCopyHistoryService = accessor.get($Okc);
    const quickInputService = accessor.get($1M);
    const { entry } = await $Ykc(workingCopyHistoryService, item);
    if (entry) {
      const disposables = new $2c();
      const inputBox = disposables.add(quickInputService.createInputBox());
      inputBox.title = localize(7727, null);
      inputBox.ignoreFocusOut = true;
      inputBox.placeholder = localize(7728, null);
      inputBox.value = $bL.getSourceLabel(entry.source);
      inputBox.show();
      disposables.add(inputBox.onDidAccept(() => {
        if (inputBox.value) {
          workingCopyHistoryService.updateEntry(entry, { source: inputBox.value }, CancellationToken.None);
        }
        disposables.dispose();
      }));
    }
  }
});
$hJ(class extends $gJ {
  constructor() {
    super({
      id: "workbench.action.localHistory.delete",
      title: localize2(7750, "Delete"),
      menu: {
        id: $bJ.TimelineItemContext,
        group: "5_edit",
        order: 2,
        when: $Tkc
      }
    });
  }
  async run(accessor, item) {
    const workingCopyHistoryService = accessor.get($Okc);
    const editorService = accessor.get($mJ);
    const dialogService = accessor.get($Yv);
    const { entry } = await $Ykc(workingCopyHistoryService, item);
    if (entry) {
      const { confirmed } = await dialogService.confirm({
        type: "warning",
        message: localize(7729, null, entry.workingCopy.name, toLocalHistoryEntryDateLabel(entry.timestamp)),
        detail: localize(7730, null),
        primaryButton: localize(7731, null)
      });
      if (!confirmed) {
        return;
      }
      await workingCopyHistoryService.removeEntry(entry, CancellationToken.None);
      await closeEntry(entry, editorService);
    }
  }
});
$hJ(class extends $gJ {
  constructor() {
    super({
      id: "workbench.action.localHistory.deleteAll",
      title: localize2(7751, "Delete All"),
      f1: true,
      category: LOCAL_HISTORY_CATEGORY,
      precondition: CTX_LOCAL_HISTORY_ENABLED
    });
  }
  async run(accessor) {
    const dialogService = accessor.get($Yv);
    const workingCopyHistoryService = accessor.get($Okc);
    const { confirmed } = await dialogService.confirm({
      type: "warning",
      message: localize(7732, null),
      detail: localize(7733, null),
      primaryButton: localize(7734, null)
    });
    if (!confirmed) {
      return;
    }
    await workingCopyHistoryService.removeAll(CancellationToken.None);
  }
});
$hJ(class extends $gJ {
  constructor() {
    super({
      id: "workbench.action.localHistory.create",
      title: localize2(7752, "Create Entry"),
      f1: true,
      category: LOCAL_HISTORY_CATEGORY,
      precondition: $7m.and(CTX_LOCAL_HISTORY_ENABLED, $Dpb)
    });
  }
  async run(accessor) {
    const workingCopyHistoryService = accessor.get($Okc);
    const quickInputService = accessor.get($1M);
    const editorService = accessor.get($mJ);
    const labelService = accessor.get($ZI);
    const pathService = accessor.get($aT);
    const resource = $mL.getOriginalUri(editorService.activeEditor, { supportSideBySide: SideBySideEditor.PRIMARY });
    if (resource?.scheme !== pathService.defaultUriScheme && resource?.scheme !== Schemas.vscodeUserData) {
      return;
    }
    const disposables = new $2c();
    const inputBox = disposables.add(quickInputService.createInputBox());
    inputBox.title = localize(7735, null);
    inputBox.ignoreFocusOut = true;
    inputBox.placeholder = localize(7736, null, labelService.getUriBasenameLabel(resource));
    inputBox.show();
    disposables.add(inputBox.onDidAccept(async () => {
      const entrySource = inputBox.value;
      disposables.dispose();
      if (entrySource) {
        await workingCopyHistoryService.addEntry({ resource, source: inputBox.value }, CancellationToken.None);
      }
    }));
  }
});
async function openEntry(entry, editorService, options3) {
  const resource = $Qkc.toLocalHistoryFileSystem({ location: entry.location, associatedResource: entry.workingCopy.resource });
  await editorService.openEditor({
    resource,
    label: localize(7737, null, entry.workingCopy.name, $bL.getSourceLabel(entry.source), toLocalHistoryEntryDateLabel(entry.timestamp)),
    options: options3
  });
}
async function closeEntry(entry, editorService) {
  const resource = $Qkc.toLocalHistoryFileSystem({ location: entry.location, associatedResource: entry.workingCopy.resource });
  const editors = editorService.findEditors(resource, { supportSideBySide: SideBySideEditor.ANY });
  await editorService.closeEditors(editors, { preserveFocus: true });
}
function $Xkc(arg1, arg2, options3) {
  const originalResource = $Qkc.toLocalHistoryFileSystem({ location: arg1.location, associatedResource: arg1.workingCopy.resource });
  let label3;
  let modifiedResource;
  if (URI.isUri(arg2)) {
    const resource = arg2;
    modifiedResource = resource;
    label3 = localize(7738, null, arg1.workingCopy.name, $bL.getSourceLabel(arg1.source), toLocalHistoryEntryDateLabel(arg1.timestamp), arg1.workingCopy.name);
  } else {
    const modified = arg2;
    modifiedResource = $Qkc.toLocalHistoryFileSystem({ location: modified.location, associatedResource: modified.workingCopy.resource });
    label3 = localize(7739, null, arg1.workingCopy.name, $bL.getSourceLabel(arg1.source), toLocalHistoryEntryDateLabel(arg1.timestamp), modified.workingCopy.name, $bL.getSourceLabel(modified.source), toLocalHistoryEntryDateLabel(modified.timestamp));
  }
  return [
    originalResource,
    modifiedResource,
    label3,
    options3 ? [void 0, options3] : void 0
  ];
}
async function $Ykc(workingCopyHistoryService, descriptor) {
  const entries2 = await workingCopyHistoryService.getEntries(descriptor.uri, CancellationToken.None);
  let currentEntry = void 0;
  let previousEntry = void 0;
  for (let i2 = 0; i2 < entries2.length; i2++) {
    const entry = entries2[i2];
    if (entry.id === descriptor.handle) {
      currentEntry = entry;
      previousEntry = entries2[i2 - 1];
      break;
    }
  }
  return {
    entry: currentEntry,
    previous: previousEntry
  };
}
var SEP = /\//g;
function toLocalHistoryEntryDateLabel(timestamp) {
  return `${$Rkc().format(timestamp).replace(SEP, "-")}`;
}

// out-build/vs/workbench/contrib/localHistory/browser/localHistoryTimeline.js
var $Zkc_1;
var $Zkc = class $Zkc2 extends $3c {
  static {
    $Zkc_1 = this;
  }
  static {
    this.ID = "workbench.contrib.localHistoryTimeline";
  }
  static {
    this.a = "workbench.localHistory.enabled";
  }
  constructor(f, g, h3, j, m, n, r2) {
    super();
    this.f = f;
    this.g = g;
    this.h = h3;
    this.j = j;
    this.m = m;
    this.n = n;
    this.r = r2;
    this.id = "timeline.localHistory";
    this.label = localize(7753, null);
    this.scheme = "*";
    this.b = this.B(new $ze());
    this.onDidChange = this.b.event;
    this.c = this.B(new $4c());
    this.s();
    this.u();
  }
  s() {
    this.t();
    this.B(this.j.registerProvider($Qkc.SCHEMA, new $Qkc(this.j)));
  }
  t() {
    if (this.n.getValue($Zkc_1.a)) {
      this.c.value = this.f.registerTimelineProvider(this);
    } else {
      this.c.clear();
    }
  }
  u() {
    this.B(this.g.onDidAddEntry((e) => this.w(e.entry)));
    this.B(this.g.onDidChangeEntry((e) => this.w(e.entry)));
    this.B(this.g.onDidReplaceEntry((e) => this.w(e.entry)));
    this.B(this.g.onDidRemoveEntry((e) => this.w(e.entry)));
    this.B(this.g.onDidRemoveEntries(() => this.w(
      void 0
      /* all entries */
    )));
    this.B(this.g.onDidMoveEntries(() => this.w(
      void 0
      /* all entries */
    )));
    this.B(this.n.onDidChangeConfiguration((e) => {
      if (e.affectsConfiguration($Zkc_1.a)) {
        this.t();
      }
    }));
  }
  w(entry) {
    this.b.fire({
      id: this.id,
      uri: entry?.workingCopy.resource,
      reset: true
      // there is no other way to indicate that items might have been replaced/removed
    });
  }
  async provideTimeline(uri, options3, token) {
    const items = [];
    let resource = void 0;
    if (uri.scheme === $Qkc.SCHEMA) {
      resource = $Qkc.fromLocalHistoryFileSystem(uri).associatedResource;
    } else if (uri.scheme === this.h.defaultUriScheme || uri.scheme === Schemas.vscodeUserData) {
      resource = uri;
    } else if (this.j.hasProvider(uri)) {
      resource = URI.from({
        scheme: this.h.defaultUriScheme,
        authority: this.m.remoteAuthority ?? $$S(this.r.getWorkspace()),
        path: uri.path
      });
    }
    if (resource) {
      const entries2 = await this.g.getEntries(resource, token);
      for (const entry of entries2) {
        items.push(this.y(entry));
      }
    }
    return {
      source: this.id,
      items
    };
  }
  y(entry) {
    return {
      handle: entry.id,
      label: $bL.getSourceLabel(entry.source),
      tooltip: new $bm(`$(history) ${$Rkc().format(entry.timestamp)}

${$bL.getSourceLabel(entry.source)}${entry.sourceDescription ? ` (${entry.sourceDescription})` : ``}`, { supportThemeIcons: true }),
      source: this.id,
      timestamp: entry.timestamp,
      themeIcon: $Ukc,
      contextValue: $Skc,
      command: {
        id: $_ub,
        title: $Wkc.value,
        arguments: $Xkc(entry, entry.workingCopy.resource)
      }
    };
  }
};
$Zkc = $Zkc_1 = __decorate([
  __param(0, $sS),
  __param(1, $Okc),
  __param(2, $aT),
  __param(3, $km),
  __param(4, $US),
  __param(5, $kl),
  __param(6, $Zk)
], $Zkc);

// out-build/vs/workbench/contrib/localHistory/browser/localHistory.contribution.js
$PL(
  $Zkc.ID,
  $Zkc,
  2
  /* WorkbenchPhase.BlockRestore */
);

// out-build/vs/workbench/contrib/workspace/browser/workspaceTrustEditor.js
var TrustedUriActionsColumnRenderer_1;
var TrustedUriPathColumnRenderer_1;
var TrustedUriHostColumnRenderer_1;
var $3kc_1;
var $2kc = $9r("workspace-trust-banner", $6l.shield, localize(12189, null));
var checkListIcon = $9r("workspace-trust-editor-check", $6l.check, localize(12190, null));
var xListIcon = $9r("workspace-trust-editor-cross", $6l.x, localize(12191, null));
var folderPickerIcon = $9r("workspace-trust-editor-folder-picker", $6l.folder, localize(12192, null));
var editIcon2 = $9r("workspace-trust-editor-edit-folder", $6l.edit, localize(12193, null));
var removeIcon2 = $9r("workspace-trust-editor-remove-folder", $6l.close, localize(12194, null));
var WorkspaceTrustedUrisTable = class WorkspaceTrustedUrisTable2 extends $3c {
  constructor(n, r2, t, w, y, z, C) {
    super();
    this.n = n;
    this.r = r2;
    this.t = t;
    this.w = w;
    this.y = y;
    this.z = z;
    this.C = C;
    this.c = this.B(new $ze());
    this.onDidAcceptEdit = this.c.event;
    this.f = this.B(new $ze());
    this.onDidRejectEdit = this.f.event;
    this.g = this.B(new $ze());
    this.onEdit = this.g.event;
    this.h = this.B(new $ze());
    this.onDelete = this.h.event;
    this.m = n.appendChild($(".workspace-trusted-folders-description"));
    const tableElement = n.appendChild($(".trusted-uris-table"));
    const addButtonBarElement = n.appendChild($(".trusted-uris-button-bar"));
    this.j = this.r.createInstance($Yeb, "WorkspaceTrust", tableElement, new TrustedUriTableVirtualDelegate(), [
      {
        label: localize(12195, null),
        tooltip: "",
        weight: 1,
        templateId: TrustedUriHostColumnRenderer.TEMPLATE_ID,
        project(row) {
          return row;
        }
      },
      {
        label: localize(12196, null),
        tooltip: "",
        weight: 8,
        templateId: TrustedUriPathColumnRenderer.TEMPLATE_ID,
        project(row) {
          return row;
        }
      },
      {
        label: "",
        tooltip: "",
        weight: 1,
        minimumWidth: 75,
        maximumWidth: 75,
        templateId: TrustedUriActionsColumnRenderer.TEMPLATE_ID,
        project(row) {
          return row;
        }
      }
    ], [
      this.r.createInstance(TrustedUriHostColumnRenderer),
      this.r.createInstance(TrustedUriPathColumnRenderer, this),
      this.r.createInstance(TrustedUriActionsColumnRenderer, this, this.G)
    ], {
      horizontalScrolling: false,
      alwaysConsumeMouseWheel: false,
      openOnSingleClick: false,
      multipleSelectionSupport: false,
      accessibilityProvider: {
        getAriaLabel: (item) => {
          const hostLabel = getHostLabel2(this.z, item);
          if (hostLabel === void 0 || hostLabel.length === 0) {
            return localize(12197, null, this.z.getUriLabel(item.uri));
          }
          return localize(12198, null, this.z.getUriLabel(item.uri), hostLabel);
        },
        getWidgetAriaLabel: () => localize(12199, null)
      },
      identityProvider: {
        getId(element) {
          return element.uri.toString();
        }
      }
    });
    this.B(this.j.onDidOpen((item) => {
      if (item && item.element && !item.browserEvent?.defaultPrevented) {
        this.edit(item.element, true);
      }
    }));
    const buttonBar = this.B(new $n2(addButtonBarElement));
    const addButton = this.B(buttonBar.addButton({ title: localize(12200, null), ...$q$ }));
    addButton.label = localize(12201, null);
    this.B(addButton.onDidClick(async () => {
      const uri = await this.C.showOpenDialog({
        canSelectFiles: false,
        canSelectFolders: true,
        canSelectMany: false,
        defaultUri: this.G,
        openLabel: localize(12202, null),
        title: localize(12203, null)
      });
      if (uri) {
        this.w.setUrisTrust(uri, true);
      }
    }));
    this.B(this.w.onDidChangeTrustedFolders(() => {
      this.updateTable();
    }));
  }
  D(item) {
    const index = this.H.indexOf(item);
    if (index === -1) {
      for (let i2 = 0; i2 < this.H.length; i2++) {
        if (this.H[i2].uri === item.uri) {
          return i2;
        }
      }
    }
    return index;
  }
  F(item, focus = true) {
    const index = this.D(item);
    if (index !== -1) {
      if (focus) {
        this.j.domFocus();
        this.j.setFocus([index]);
      }
      this.j.setSelection([index]);
    }
  }
  get G() {
    return this.t.getWorkspace().folders[0]?.uri || URI.file("/");
  }
  get H() {
    const currentWorkspace = this.t.getWorkspace();
    const currentWorkspaceUris = currentWorkspace.folders.map((folder) => folder.uri);
    if (currentWorkspace.configuration) {
      currentWorkspaceUris.push(currentWorkspace.configuration);
    }
    const entries2 = this.w.getTrustedUris().map((uri) => {
      let relatedToCurrentWorkspace = false;
      for (const workspaceUri of currentWorkspaceUris) {
        relatedToCurrentWorkspace = relatedToCurrentWorkspace || this.y.extUri.isEqualOrParent(workspaceUri, uri);
      }
      return {
        uri,
        parentOfWorkspaceItem: relatedToCurrentWorkspace
      };
    });
    const sortedEntries = entries2.sort((a, b) => {
      if (a.uri.scheme !== b.uri.scheme) {
        if (a.uri.scheme === Schemas.file) {
          return -1;
        }
        if (b.uri.scheme === Schemas.file) {
          return 1;
        }
      }
      const aIsWorkspace = a.uri.path.endsWith(".code-workspace");
      const bIsWorkspace = b.uri.path.endsWith(".code-workspace");
      if (aIsWorkspace !== bIsWorkspace) {
        if (aIsWorkspace) {
          return 1;
        }
        if (bIsWorkspace) {
          return -1;
        }
      }
      return a.uri.fsPath.localeCompare(b.uri.fsPath);
    });
    return sortedEntries;
  }
  layout() {
    this.j.layout(this.H.length * TrustedUriTableVirtualDelegate.ROW_HEIGHT + TrustedUriTableVirtualDelegate.HEADER_ROW_HEIGHT, void 0);
  }
  updateTable() {
    const entries2 = this.H;
    this.n.classList.toggle("empty", entries2.length === 0);
    this.m.innerText = entries2.length ? localize(12204, null) : localize(12205, null);
    this.j.splice(0, Number.POSITIVE_INFINITY, this.H);
    this.layout();
  }
  validateUri(path, item) {
    if (!item) {
      return null;
    }
    if (item.uri.scheme === "vscode-vfs") {
      const segments = path.split($kc.sep).filter((s) => s.length);
      if (segments.length === 0 && path.startsWith($kc.sep)) {
        return {
          type: 2,
          content: localize(12206, null, getHostLabel2(this.z, item))
        };
      }
      if (segments.length === 1) {
        return {
          type: 2,
          content: localize(12207, null, segments[0], getHostLabel2(this.z, item))
        };
      }
      if (segments.length > 2) {
        return {
          type: 3,
          content: localize(12208, null, path)
        };
      }
    }
    return null;
  }
  acceptEdit(item, uri) {
    const trustedFolders = this.w.getTrustedUris();
    const index = trustedFolders.findIndex((u) => this.y.extUri.isEqual(u, item.uri));
    if (index >= trustedFolders.length || index === -1) {
      trustedFolders.push(uri);
    } else {
      trustedFolders[index] = uri;
    }
    this.w.setTrustedUris(trustedFolders);
    this.c.fire(item);
  }
  rejectEdit(item) {
    this.f.fire(item);
  }
  async delete(item) {
    this.j.focusNext();
    await this.w.setUrisTrust([item.uri], false);
    if (this.j.getFocus().length === 0) {
      this.j.focusLast();
    }
    this.h.fire(item);
    this.j.domFocus();
  }
  async edit(item, usePickerIfPossible) {
    const canUseOpenDialog = item.uri.scheme === Schemas.file || item.uri.scheme === this.G.scheme && this.y.extUri.isEqualAuthority(this.G.authority, item.uri.authority) && !$8S(item.uri);
    if (canUseOpenDialog && usePickerIfPossible) {
      const uri = await this.C.showOpenDialog({
        canSelectFiles: false,
        canSelectFolders: true,
        canSelectMany: false,
        defaultUri: item.uri,
        openLabel: localize(12209, null),
        title: localize(12210, null)
      });
      if (uri) {
        this.acceptEdit(item, uri[0]);
      } else {
        this.rejectEdit(item);
      }
    } else {
      this.F(item);
      this.g.fire(item);
    }
  }
};
WorkspaceTrustedUrisTable = __decorate([
  __param(1, $Pk),
  __param(2, $Zk),
  __param(3, $4M),
  __param(4, $vl),
  __param(5, $ZI),
  __param(6, $1v)
], WorkspaceTrustedUrisTable);
var TrustedUriTableVirtualDelegate = class _TrustedUriTableVirtualDelegate {
  constructor() {
    this.headerRowHeight = _TrustedUriTableVirtualDelegate.HEADER_ROW_HEIGHT;
  }
  static {
    this.HEADER_ROW_HEIGHT = 30;
  }
  static {
    this.ROW_HEIGHT = 24;
  }
  getHeight(item) {
    return _TrustedUriTableVirtualDelegate.ROW_HEIGHT;
  }
};
var TrustedUriActionsColumnRenderer = class TrustedUriActionsColumnRenderer2 {
  static {
    TrustedUriActionsColumnRenderer_1 = this;
  }
  static {
    this.TEMPLATE_ID = "actions";
  }
  constructor(c, d, f) {
    this.c = c;
    this.d = d;
    this.f = f;
    this.templateId = TrustedUriActionsColumnRenderer_1.TEMPLATE_ID;
  }
  renderTemplate(container2) {
    const element = container2.appendChild($(".actions"));
    const actionBar = new $LZ(element);
    return { actionBar };
  }
  renderElement(item, index, templateData, height) {
    templateData.actionBar.clear();
    const canUseOpenDialog = item.uri.scheme === Schemas.file || item.uri.scheme === this.d.scheme && this.f.extUri.isEqualAuthority(this.d.authority, item.uri.authority) && !$8S(item.uri);
    const actions = [];
    if (canUseOpenDialog) {
      actions.push(this.h(item));
    }
    actions.push(this.g(item));
    actions.push(this.j(item));
    templateData.actionBar.push(actions, { icon: true });
  }
  g(item) {
    return {
      label: "",
      class: ThemeIcon.asClassName(editIcon2),
      enabled: true,
      id: "editTrustedUri",
      tooltip: localize(12211, null),
      run: () => {
        this.c.edit(item, false);
      }
    };
  }
  h(item) {
    return {
      label: "",
      class: ThemeIcon.asClassName(folderPickerIcon),
      enabled: true,
      id: "pickerTrustedUri",
      tooltip: localize(12212, null),
      run: () => {
        this.c.edit(item, true);
      }
    };
  }
  j(item) {
    return {
      label: "",
      class: ThemeIcon.asClassName(removeIcon2),
      enabled: true,
      id: "deleteTrustedUri",
      tooltip: localize(12213, null),
      run: async () => {
        await this.c.delete(item);
      }
    };
  }
  disposeTemplate(templateData) {
    templateData.actionBar.dispose();
  }
};
TrustedUriActionsColumnRenderer = TrustedUriActionsColumnRenderer_1 = __decorate([
  __param(2, $vl)
], TrustedUriActionsColumnRenderer);
var TrustedUriPathColumnRenderer = class TrustedUriPathColumnRenderer2 {
  static {
    TrustedUriPathColumnRenderer_1 = this;
  }
  static {
    this.TEMPLATE_ID = "path";
  }
  constructor(d, f) {
    this.d = d;
    this.f = f;
    this.templateId = TrustedUriPathColumnRenderer_1.TEMPLATE_ID;
  }
  renderTemplate(container2) {
    const element = container2.appendChild($(".path"));
    const pathLabel = element.appendChild($("div.path-label"));
    const pathInput = new $I2(element, this.f, {
      validationOptions: {
        validation: (value) => this.d.validateUri(value, this.c)
      },
      inputBoxStyles: $B$
    });
    const disposables = new $2c();
    const renderDisposables = disposables.add(new $2c());
    return {
      element,
      pathLabel,
      pathInput,
      disposables,
      renderDisposables
    };
  }
  renderElement(item, index, templateData, height) {
    templateData.renderDisposables.clear();
    this.c = item;
    templateData.renderDisposables.add(this.d.onEdit(async (e) => {
      if (item === e) {
        templateData.element.classList.add("input-mode");
        templateData.pathInput.focus();
        templateData.pathInput.select();
        templateData.element.parentElement.style.paddingLeft = "0px";
      }
    }));
    templateData.renderDisposables.add($_i(templateData.pathInput.element, $7j.DBLCLICK, (e) => {
      $9j.stop(e);
    }));
    const hideInputBox = () => {
      templateData.element.classList.remove("input-mode");
      templateData.element.parentElement.style.paddingLeft = "5px";
    };
    const accept = () => {
      hideInputBox();
      const pathToUse = templateData.pathInput.value;
      const uri = $5g(pathToUse) ? item.uri.with({ path: $kc.sep + $Tg(pathToUse) }) : item.uri.with({ path: pathToUse });
      templateData.pathLabel.innerText = this.g(uri);
      if (uri) {
        this.d.acceptEdit(item, uri);
      }
    };
    const reject = () => {
      hideInputBox();
      templateData.pathInput.value = stringValue;
      this.d.rejectEdit(item);
    };
    templateData.renderDisposables.add($aj(templateData.pathInput.inputElement, $7j.KEY_DOWN, (e) => {
      let handled = false;
      if (e.equals(
        3
        /* KeyCode.Enter */
      )) {
        accept();
        handled = true;
      } else if (e.equals(
        9
        /* KeyCode.Escape */
      )) {
        reject();
        handled = true;
      }
      if (handled) {
        e.preventDefault();
        e.stopPropagation();
      }
    }));
    templateData.renderDisposables.add($_i(templateData.pathInput.inputElement, $7j.BLUR, () => {
      reject();
    }));
    const stringValue = this.g(item.uri);
    templateData.pathInput.value = stringValue;
    templateData.pathLabel.innerText = stringValue;
    templateData.element.classList.toggle("current-workspace-parent", item.parentOfWorkspaceItem);
  }
  disposeTemplate(templateData) {
    templateData.disposables.dispose();
    templateData.renderDisposables.dispose();
  }
  g(uri) {
    if (uri.scheme === Schemas.file) {
      return $1t(uri.fsPath);
    }
    if (uri.path.startsWith($kc.sep)) {
      const pathWithoutLeadingSeparator = uri.path.substring(1);
      const isWindowsPath = $5g(pathWithoutLeadingSeparator, true);
      if (isWindowsPath) {
        return $1t($jc.normalize(pathWithoutLeadingSeparator), true);
      }
    }
    return uri.path;
  }
};
TrustedUriPathColumnRenderer = TrustedUriPathColumnRenderer_1 = __decorate([
  __param(1, $40)
], TrustedUriPathColumnRenderer);
function getHostLabel2(labelService, item) {
  return item.uri.authority ? labelService.getHostLabel(item.uri.scheme, item.uri.authority) : localize(12214, null);
}
var TrustedUriHostColumnRenderer = class TrustedUriHostColumnRenderer2 {
  static {
    TrustedUriHostColumnRenderer_1 = this;
  }
  static {
    this.TEMPLATE_ID = "host";
  }
  constructor(c) {
    this.c = c;
    this.templateId = TrustedUriHostColumnRenderer_1.TEMPLATE_ID;
  }
  renderTemplate(container2) {
    const disposables = new $2c();
    const renderDisposables = disposables.add(new $2c());
    const element = container2.appendChild($(".host"));
    const hostContainer = element.appendChild($("div.host-label"));
    const buttonBarContainer = element.appendChild($("div.button-bar"));
    return {
      element,
      hostContainer,
      buttonBarContainer,
      disposables,
      renderDisposables
    };
  }
  renderElement(item, index, templateData, height) {
    templateData.renderDisposables.clear();
    templateData.renderDisposables.add({ dispose: () => {
      $$i(templateData.buttonBarContainer);
    } });
    templateData.hostContainer.innerText = getHostLabel2(this.c, item);
    templateData.element.classList.toggle("current-workspace-parent", item.parentOfWorkspaceItem);
    templateData.hostContainer.style.display = "";
    templateData.buttonBarContainer.style.display = "none";
  }
  disposeTemplate(templateData) {
    templateData.disposables.dispose();
  }
};
TrustedUriHostColumnRenderer = TrustedUriHostColumnRenderer_1 = __decorate([
  __param(0, $ZI)
], TrustedUriHostColumnRenderer);
var $3kc = class $3kc2 extends $5tb {
  static {
    $3kc_1 = this;
  }
  static {
    this.ID = "workbench.editor.workspaceTrust";
  }
  constructor(group2, telemetryService, themeService, storageService, ib, jb, kb, lb, mb, nb, ob, pb, qb) {
    super($3kc_1.ID, group2, telemetryService, themeService, storageService);
    this.ib = ib;
    this.jb = jb;
    this.kb = kb;
    this.lb = lb;
    this.mb = mb;
    this.nb = nb;
    this.ob = ob;
    this.pb = pb;
    this.qb = qb;
    this.xb = false;
    this.yb = this.B(new $2c());
    this.Lb = [];
  }
  Y(parent) {
    this.c = $bk(parent, $(".workspace-trust-editor", { tabindex: "0" }));
    this.Bb(this.c);
    const scrollableContent = $(".workspace-trust-editor-body");
    this.cb = this.B(new $CZ(scrollableContent, {
      horizontal: 2,
      vertical: 1
    }));
    $bk(this.c, this.cb.getDomNode());
    this.Db(scrollableContent);
    this.Cb(scrollableContent);
    this.c.style.setProperty("--workspace-trust-selected-color", $Zn($Uq));
    this.c.style.setProperty("--workspace-trust-unselected-color", $Zn($Yq));
    this.c.style.setProperty("--workspace-trust-check-color", $Zn($gGb));
    this.c.style.setProperty("--workspace-trust-x-color", $Zn($Vo));
    this.B($_i(this.c, $7j.KEY_DOWN, (e) => {
      const event = new $if(e);
      if (event.equals(
        16
        /* KeyCode.UpArrow */
      ) || event.equals(
        18
        /* KeyCode.DownArrow */
      )) {
        const navOrder = [this.f, this.eb, this.fb, this.gb];
        const currentIndex = navOrder.findIndex((element) => {
          return $Nj(element);
        });
        let newIndex = currentIndex;
        if (event.equals(
          18
          /* KeyCode.DownArrow */
        )) {
          newIndex++;
        } else if (event.equals(
          16
          /* KeyCode.UpArrow */
        )) {
          newIndex = Math.max(0, newIndex);
          newIndex--;
        }
        newIndex += navOrder.length;
        newIndex %= navOrder.length;
        navOrder[newIndex].focus();
      } else if (event.equals(
        9
        /* KeyCode.Escape */
      )) {
        this.c.focus();
      } else if (event.equals(
        2048 | 3
        /* KeyCode.Enter */
      )) {
        if (this.mb.canSetWorkspaceTrust()) {
          this.mb.setWorkspaceTrust(!this.mb.isWorkspaceTrusted());
        }
      } else if (event.equals(
        2048 | 1024 | 3
        /* KeyCode.Enter */
      )) {
        if (this.mb.canSetParentFolderTrust()) {
          this.mb.setParentFolderTrust(true);
        }
      }
    }));
  }
  focus() {
    super.focus();
    this.c.focus();
  }
  async setInput(input, options3, context, token) {
    await super.setInput(input, options3, context, token);
    if (token.isCancellationRequested) {
      return;
    }
    await this.mb.workspaceTrustInitialized;
    this.sb();
    await this.zb();
  }
  sb() {
    this.B(this.jb.onChange(() => this.zb()));
    this.B(this.nb.onDidChangeRestrictedSettings(() => this.zb()));
    this.B(this.mb.onDidChangeTrust(() => this.zb()));
    this.B(this.mb.onDidChangeTrustedFolders(() => this.zb()));
  }
  tb(trusted) {
    if (trusted) {
      return "workspace-trust-header workspace-trust-trusted";
    }
    return "workspace-trust-header workspace-trust-untrusted";
  }
  ub(trusted) {
    if (trusted) {
      if (this.mb.isWorkspaceTrustForced()) {
        return localize(12215, null);
      }
      switch (this.ib.getWorkbenchState()) {
        case 1:
          return localize(12216, null);
        case 2:
          return localize(12217, null);
        case 3:
          return localize(12218, null);
      }
    }
    return localize(12219, null);
  }
  vb(trusted) {
    return ThemeIcon.asClassNameArray($2kc);
  }
  wb(trusted) {
    let title = "";
    let subTitle = "";
    switch (this.ib.getWorkbenchState()) {
      case 1: {
        title = trusted ? localize(12220, null) : localize(12221, null);
        subTitle = trusted ? localize(12222, null) : localize(12223, null);
        break;
      }
      case 2: {
        title = trusted ? localize(12224, null) : localize(12225, null);
        subTitle = trusted ? localize(12226, null) : localize(12227, null);
        break;
      }
      case 3: {
        title = trusted ? localize(12228, null) : localize(12229, null);
        subTitle = trusted ? localize(12230, null) : localize(12231, null);
        break;
      }
    }
    return [title, subTitle];
  }
  async zb() {
    if (this.xb) {
      return;
    }
    this.xb = true;
    this.yb.clear();
    const isWorkspaceTrusted = this.mb.isWorkspaceTrusted();
    this.c.classList.toggle("trusted", isWorkspaceTrusted);
    this.c.classList.toggle("untrusted", !isWorkspaceTrusted);
    this.m.innerText = this.ub(isWorkspaceTrusted);
    this.j.className = "workspace-trust-title-icon";
    this.j.classList.add(...this.vb(isWorkspaceTrusted));
    this.r.innerText = "";
    const headerDescriptionText = $bk(this.r, $("div"));
    headerDescriptionText.innerText = isWorkspaceTrusted ? localize(12232, null) : localize(12233, null, this.pb.nameShort);
    const headerDescriptionActions = $bk(this.r, $("div"));
    const headerDescriptionActionsText = localize(12234, null, `command:workbench.trust.configure`);
    for (const node of $U3(headerDescriptionActionsText).nodes) {
      if (typeof node === "string") {
        $bk(headerDescriptionActions, document.createTextNode(node));
      } else {
        this.yb.add(this.lb.createInstance(Link2, headerDescriptionActions, { ...node, tabIndex: -1 }, {}));
      }
    }
    this.f.className = this.tb(isWorkspaceTrusted);
    this.c.setAttribute("aria-label", `${localize(12235, null)}:  ${this.f.innerText}`);
    const restrictedSettings = this.nb.restrictedSettings;
    const configurationRegistry22 = $Wn.as($Ht.Configuration);
    const settingsRequiringTrustedWorkspaceCount = restrictedSettings.default.filter((key2) => {
      const property = configurationRegistry22.getConfigurationProperties()[key2];
      if (property.scope === 1 || property.scope === 2) {
        return false;
      }
      if (property.deprecationMessage || property.markdownDeprecationMessage) {
        if (restrictedSettings.workspace?.includes(key2)) {
          return true;
        }
        if (restrictedSettings.workspaceFolder) {
          for (const workspaceFolderSettings of restrictedSettings.workspaceFolder.values()) {
            if (workspaceFolderSettings.includes(key2)) {
              return true;
            }
          }
        }
        return false;
      }
      return true;
    }).length;
    this.Eb(settingsRequiringTrustedWorkspaceCount, this.Ab());
    this.hb.updateTable();
    this.cb.getDomNode().style.height = `calc(100% - ${this.f.clientHeight}px)`;
    this.cb.scanDomNode();
    this.xb = false;
  }
  Ab() {
    const set = /* @__PURE__ */ new Set();
    const inVirtualWorkspace = $_S(this.ib.getWorkspace());
    const localExtensions = this.jb.local.filter((ext) => ext.local).map((ext) => ext.local);
    for (const extension of localExtensions) {
      const enablementState = this.ob.getEnablementState(extension);
      if (enablementState !== 10 && enablementState !== 11 && enablementState !== 0 && enablementState !== 7) {
        continue;
      }
      if (inVirtualWorkspace && this.kb.getExtensionVirtualWorkspaceSupportType(extension.manifest) === false) {
        continue;
      }
      if (this.kb.getExtensionUntrustedWorkspaceSupportType(extension.manifest) !== true) {
        set.add(extension.identifier.id);
        continue;
      }
      const dependencies = $NA(localExtensions, extension);
      if (dependencies.some((ext) => this.kb.getExtensionUntrustedWorkspaceSupportType(ext.manifest) === false)) {
        set.add(extension.identifier.id);
      }
    }
    return set.size;
  }
  Bb(parent) {
    this.f = $bk(parent, $(".workspace-trust-header", { tabIndex: "0" }));
    this.g = $bk(this.f, $(".workspace-trust-title"));
    this.j = $bk(this.g, $(".workspace-trust-title-icon"));
    this.m = $bk(this.g, $(".workspace-trust-title-text"));
    this.r = $bk(this.f, $(".workspace-trust-description"));
  }
  Cb(parent) {
    this.gb = $bk(parent, $(".workspace-trust-settings", { tabIndex: "0" }));
    const configurationTitle = $bk(this.gb, $(".workspace-trusted-folders-title"));
    configurationTitle.innerText = localize(12236, null);
    this.hb = this.B(this.lb.createInstance(WorkspaceTrustedUrisTable, this.gb));
  }
  Db(parent) {
    this.db = $bk(parent, $(".workspace-trust-features"));
    this.eb = $bk(this.db, $(".workspace-trust-limitations.trusted", { tabIndex: "0" }));
    this.fb = $bk(this.db, $(".workspace-trust-limitations.untrusted", { tabIndex: "0" }));
  }
  async Eb(numSettings, numExtensions) {
    $$i(this.eb);
    $$i(this.fb);
    const [trustedTitle, trustedSubTitle] = this.wb(true);
    this.Jb(this.eb, trustedTitle, trustedSubTitle);
    const trustedContainerItems = this.ib.getWorkbenchState() === 1 ? [
      localize(12237, null),
      localize(12238, null),
      localize(12239, null)
    ] : [
      localize(12240, null),
      localize(12241, null),
      localize(12242, null),
      localize(12243, null)
    ];
    this.Kb(this.eb, trustedContainerItems, ThemeIcon.asClassNameArray(checkListIcon));
    const [untrustedTitle, untrustedSubTitle] = this.wb(false);
    this.Jb(this.fb, untrustedTitle, untrustedSubTitle);
    const untrustedContainerItems = this.ib.getWorkbenchState() === 1 ? [
      localize(12244, null),
      localize(12245, null),
      fixBadLocalizedLinks(localize(12246, null, numExtensions, `command:${$Hzb}`))
    ] : [
      localize(12247, null),
      localize(12248, null),
      fixBadLocalizedLinks(numSettings ? localize(12249, null, numSettings, "command:settings.filterUntrusted") : localize(12250, null)),
      fixBadLocalizedLinks(localize(12251, null, numExtensions, `command:${$Hzb}`))
    ];
    this.Kb(this.fb, untrustedContainerItems, ThemeIcon.asClassNameArray(xListIcon));
    if (this.mb.isWorkspaceTrusted()) {
      if (this.mb.canSetWorkspaceTrust()) {
        this.Hb(this.fb);
      } else {
        this.Ib(this.fb);
      }
    } else {
      if (this.mb.canSetWorkspaceTrust()) {
        this.Gb(this.eb);
      }
    }
  }
  Fb(parent, buttonInfo, enabled) {
    const buttonRow = $bk(parent, $(".workspace-trust-buttons-row"));
    const buttonContainer = $bk(buttonRow, $(".workspace-trust-buttons"));
    const buttonBar = this.yb.add(new $n2(buttonContainer));
    for (const { action, keybinding } of buttonInfo) {
      const button = buttonBar.addButtonWithDescription($q$);
      button.label = action.label;
      button.enabled = enabled !== void 0 ? enabled : action.enabled;
      button.description = keybinding.getLabel();
      button.element.ariaLabel = action.label + ", " + localize(12252, null, keybinding.getAriaLabel());
      this.yb.add(button.onDidClick((e) => {
        if (e) {
          $9j.stop(e, true);
        }
        action.run();
      }));
    }
  }
  Gb(parent) {
    const trustAction = new $Um("workspace.trust.button.action.grant", localize(12253, null), void 0, true, async () => {
      await this.mb.setWorkspaceTrust(true);
    });
    const trustActions = [{ action: trustAction, keybinding: this.qb.resolveUserBinding($m ? "Cmd+Enter" : "Ctrl+Enter")[0] }];
    if (this.mb.canSetParentFolderTrust()) {
      const workspaceIdentifier = $5k(this.ib.getWorkspace());
      const name = $sh($uh(workspaceIdentifier.uri));
      const trustMessageElement = $bk(parent, $(".trust-message-box"));
      trustMessageElement.innerText = localize(12254, null, name);
      const trustParentAction = new $Um("workspace.trust.button.action.grantParent", localize(12255, null), void 0, true, async () => {
        await this.mb.setParentFolderTrust(true);
      });
      trustActions.push({ action: trustParentAction, keybinding: this.qb.resolveUserBinding($m ? "Cmd+Shift+Enter" : "Ctrl+Shift+Enter")[0] });
    }
    this.Fb(parent, trustActions);
  }
  Hb(parent) {
    this.Fb(parent, [{
      action: new $Um("workspace.trust.button.action.deny", localize(12256, null), void 0, true, async () => {
        await this.mb.setWorkspaceTrust(false);
      }),
      keybinding: this.qb.resolveUserBinding($m ? "Cmd+Enter" : "Ctrl+Enter")[0]
    }]);
  }
  Ib(parent) {
    if (this.ib.getWorkbenchState() === 1) {
      return;
    }
    const textElement = $bk(parent, $(".workspace-trust-untrusted-description"));
    if (!this.mb.isWorkspaceTrustForced()) {
      textElement.innerText = this.ib.getWorkbenchState() === 3 ? localize(12257, null) : localize(12258, null);
    } else {
      textElement.innerText = localize(12259, null);
    }
  }
  Jb(parent, headerText, subtitleText) {
    const limitationsHeaderContainer = $bk(parent, $(".workspace-trust-limitations-header"));
    const titleElement = $bk(limitationsHeaderContainer, $(".workspace-trust-limitations-title"));
    const textElement = $bk(titleElement, $(".workspace-trust-limitations-title-text"));
    const subtitleElement = $bk(limitationsHeaderContainer, $(".workspace-trust-limitations-subtitle"));
    textElement.innerText = headerText;
    subtitleElement.innerText = subtitleText;
  }
  Kb(parent, limitations, iconClassNames) {
    const listContainer = $bk(parent, $(".workspace-trust-limitations-list-container"));
    const limitationsList = $bk(listContainer, $("ul"));
    for (const limitation of limitations) {
      const limitationListItem = $bk(limitationsList, $("li"));
      const icon2 = $bk(limitationListItem, $(".list-item-icon"));
      const text2 = $bk(limitationListItem, $(".list-item-text"));
      icon2.classList.add(...iconClassNames);
      const linkedText = $U3(limitation);
      for (const node of linkedText.nodes) {
        if (typeof node === "string") {
          $bk(text2, document.createTextNode(node));
        } else {
          this.yb.add(this.lb.createInstance(Link2, text2, { ...node, tabIndex: -1 }, {}));
        }
      }
    }
  }
  layout(dimension) {
    if (!this.isVisible()) {
      return;
    }
    this.hb.layout();
    this.Lb.forEach((participant) => {
      participant.layout();
    });
    this.cb.scanDomNode();
  }
};
__decorate([
  $$t(100)
], $3kc.prototype, "zb", null);
$3kc = $3kc_1 = __decorate([
  __param(1, $zv),
  __param(2, $gs),
  __param(3, $jv),
  __param(4, $Zk),
  __param(5, $vzb),
  __param(6, $LCb),
  __param(7, $Pk),
  __param(8, $4M),
  __param(9, $EK),
  __param(10, $qzb),
  __param(11, $Vu),
  __param(12, $Ty)
], $3kc);
function fixBadLocalizedLinks(badString) {
  const regex = /(.*)\[(.+)\]\s*\((.+)\)(.*)/;
  return badString.replace(regex, "$1[$2]($3)$4");
}

// out-build/vs/workbench/services/workspaces/browser/workspaceTrustEditorInput.js
var WorkspaceTrustEditorIcon = $9r("workspace-trust-editor-label-icon", $6l.shield, localize(13638, null));
var $1kc = class _$1kc extends $nG {
  constructor() {
    super(...arguments);
    this.resource = URI.from({
      scheme: Schemas.vscodeWorkspaceTrust,
      path: `workspaceTrustEditor`
    });
  }
  static {
    this.ID = "workbench.input.workspaceTrust";
  }
  get capabilities() {
    return 2 | 8;
  }
  get typeId() {
    return _$1kc.ID;
  }
  matches(otherInput) {
    return super.matches(otherInput) || otherInput instanceof _$1kc;
  }
  getName() {
    return localize(13639, null);
  }
  getIcon() {
    return WorkspaceTrustEditorIcon;
  }
};

// out-build/vs/workbench/contrib/workspace/browser/workspace.contribution.js
var BANNER_RESTRICTED_MODE = "workbench.banner.restrictedMode";
var STARTUP_PROMPT_SHOWN_KEY = "workspace.trust.startupPrompt.shown";
var BANNER_RESTRICTED_MODE_DISMISSED_KEY = "workbench.banner.restrictedMode.dismissed";
var $4kc = class $4kc2 extends $3c {
  constructor(contextKeyService, workspaceTrustEnablementService, workspaceTrustManagementService) {
    super();
    this.a = $Fac.IsEnabled.bindTo(contextKeyService);
    this.a.set(workspaceTrustEnablementService.isWorkspaceTrustEnabled());
    this.c = $Fac.IsTrusted.bindTo(contextKeyService);
    this.c.set(workspaceTrustManagementService.isWorkspaceTrusted());
    this.B(workspaceTrustManagementService.onDidChangeTrust((trusted) => this.c.set(trusted)));
  }
};
$4kc = __decorate([
  __param(0, $on),
  __param(1, $3M),
  __param(2, $4M)
], $4kc);
$Wn.as(Extensions2.Workbench).registerWorkbenchContribution(
  $4kc,
  3
  /* LifecyclePhase.Restored */
);
var $5kc = class $5kc2 extends $3c {
  static {
    this.ID = "workbench.contrib.workspaceTrustRequestHandler";
  }
  constructor(a, c, f, g, h3) {
    super();
    this.a = a;
    this.c = c;
    this.f = f;
    this.g = g;
    this.h = h3;
    this.m();
  }
  get j() {
    return !$1k($5k(this.f.getWorkspace()));
  }
  m() {
    this.B(this.h.onDidInitiateOpenFilesTrustRequest(async () => {
      await this.g.workspaceResolved;
      const markdownDetails = [
        this.f.getWorkbenchState() !== 1 ? localize(12124, null) : localize(12125, null),
        localize(12126, null)
      ];
      await this.a.prompt({
        type: Severity2.Info,
        message: this.f.getWorkbenchState() !== 1 ? localize(12127, null) : localize(12128, null),
        buttons: [
          {
            label: localize(12129, null),
            run: ({ checkboxChecked }) => this.h.completeOpenFilesTrustRequest(1, !!checkboxChecked)
          },
          {
            label: localize(12130, null),
            run: ({ checkboxChecked }) => this.h.completeOpenFilesTrustRequest(2, !!checkboxChecked)
          }
        ],
        cancelButton: {
          run: () => this.h.completeOpenFilesTrustRequest(
            3
            /* WorkspaceTrustUriResponse.Cancel */
          )
        },
        checkbox: {
          label: localize(12131, null),
          checked: false
        },
        custom: {
          icon: $6l.shield,
          markdownDetails: markdownDetails.map((md) => {
            return { markdown: new $bm(md) };
          })
        }
      });
    }));
    this.B(this.h.onDidInitiateWorkspaceTrustRequest(async (requestOptions) => {
      await this.g.workspaceResolved;
      const message = this.j ? localize(12132, null) : localize(12133, null);
      const defaultDetails = localize(12134, null);
      const details = requestOptions?.message ?? defaultDetails;
      const buttons = requestOptions?.buttons ?? [
        { label: this.j ? localize(12135, null) : localize(12136, null), type: "ContinueWithTrust" },
        { label: localize(12137, null), type: "Manage" }
      ];
      if (!buttons.some((b) => b.type === "Cancel")) {
        buttons.push({ label: localize(12138, null), type: "Cancel" });
      }
      const { result } = await this.a.prompt({
        type: Severity2.Info,
        message,
        custom: {
          icon: $6l.shield,
          markdownDetails: [
            { markdown: new $bm(details) },
            { markdown: new $bm(localize(12139, null)) }
          ]
        },
        buttons: buttons.filter((b) => b.type !== "Cancel").map((button) => {
          return {
            label: button.label,
            run: () => button.type
          };
        }),
        cancelButton: (() => {
          const cancelButton = buttons.find((b) => b.type === "Cancel");
          if (!cancelButton) {
            return void 0;
          }
          return {
            label: cancelButton.label,
            run: () => cancelButton.type
          };
        })()
      });
      switch (result) {
        case "ContinueWithTrust":
          await this.h.completeWorkspaceTrustRequest(true);
          break;
        case "ContinueWithoutTrust":
          await this.h.completeWorkspaceTrustRequest(void 0);
          break;
        case "Manage":
          this.h.cancelWorkspaceTrustRequest();
          await this.c.executeCommand($Gac);
          break;
        case "Cancel":
          this.h.cancelWorkspaceTrustRequest();
          break;
      }
    }));
  }
};
$5kc = __decorate([
  __param(0, $Yv),
  __param(1, $sn),
  __param(2, $Zk),
  __param(3, $4M),
  __param(4, $5M)
], $5kc);
var $6kc = class $6kc2 extends $3c {
  constructor(f, g, h3, j, m, n, r2, s, t, u, w, y, z, C, D) {
    super();
    this.f = f;
    this.g = g;
    this.h = h3;
    this.j = j;
    this.m = m;
    this.n = n;
    this.r = r2;
    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.a = `status.workspaceTrust`;
    this.c = this.B(new $4c());
    (async () => {
      await this.j.workspaceTrustInitialized;
      if (this.h.isWorkspaceTrustEnabled()) {
        this.F();
        this.S(this.j.isWorkspaceTrusted());
        if (this.w.hasFocus) {
          this.I();
        } else {
          const focusDisposable = this.w.onDidChangeFocus((focused) => {
            if (focused) {
              focusDisposable.dispose();
              this.I();
            }
          });
        }
      }
    })();
  }
  F() {
    this.B(this.g.onWillChangeWorkspaceFolders((e) => {
      if (e.fromCache) {
        return;
      }
      if (!this.h.isWorkspaceTrustEnabled()) {
        return;
      }
      const addWorkspaceFolder = async (e2) => {
        const trusted = this.j.isWorkspaceTrusted();
        if (trusted && (e2.changes.added.length || e2.changes.changed.length)) {
          const addedFoldersTrustInfo = await Promise.all(e2.changes.added.map((folder) => this.j.getUriTrustInfo(folder.uri)));
          if (!addedFoldersTrustInfo.map((info) => info.trusted).every((trusted2) => trusted2)) {
            const { confirmed } = await this.f.confirm({
              type: Severity2.Info,
              message: localize(12140, null),
              detail: localize(12141, null),
              cancelButton: localize(12142, null),
              custom: { icon: $6l.shield }
            });
            await this.j.setUrisTrust(addedFoldersTrustInfo.map((i2) => i2.uri), confirmed);
          }
        }
      };
      return e.join(addWorkspaceFolder(e));
    }));
    this.B(this.j.onDidChangeTrust((trusted) => {
      this.G(trusted);
    }));
    this.B(this.s.onDidInitiateWorkspaceTrustRequestOnStartup(async () => {
      let titleString;
      let learnMoreString;
      let trustOption;
      let dontTrustOption;
      const isAiGeneratedWorkspace = await this.M();
      if (isAiGeneratedWorkspace && this.y.aiGeneratedWorkspaceTrust) {
        titleString = this.y.aiGeneratedWorkspaceTrust.title;
        learnMoreString = this.y.aiGeneratedWorkspaceTrust.startupTrustRequestLearnMore;
        trustOption = this.y.aiGeneratedWorkspaceTrust.trustOption;
        dontTrustOption = this.y.aiGeneratedWorkspaceTrust.dontTrustOption;
      } else {
        console.warn("AI generated workspace trust dialog contents not available.");
      }
      const title = titleString ?? (this.L ? localize(12143, null) : localize(12144, null));
      let checkboxText;
      const workspaceIdentifier = $5k(this.g.getWorkspace());
      const isSingleFolderWorkspace = $1k(workspaceIdentifier);
      const isEmptyWindow = $2k(workspaceIdentifier);
      if (!isAiGeneratedWorkspace && this.j.canSetParentFolderTrust()) {
        const name = $sh($uh(workspaceIdentifier.uri));
        checkboxText = localize(12145, null, name);
      }
      this.H(title, { label: trustOption ?? localize(12146, null), sublabel: isSingleFolderWorkspace ? localize(12147, null) : localize(12148, null) }, { label: dontTrustOption ?? localize(12149, null), sublabel: isSingleFolderWorkspace ? localize(12150, null) : localize(12151, null) }, [
        !isSingleFolderWorkspace ? localize(12152, null, this.y.nameShort) : localize(12153, null, this.y.nameShort),
        learnMoreString ?? localize(12154, null),
        !isEmptyWindow ? `\`${this.u.getWorkspaceLabel(workspaceIdentifier, {
          verbose: 2
          /* Verbosity.LONG */
        })}\`` : ""
      ], checkboxText);
    }));
  }
  G(trusted) {
    const bannerItem = this.N(!trusted);
    this.S(trusted);
    if (bannerItem) {
      if (!trusted) {
        this.t.show(bannerItem);
      } else {
        this.t.hide(BANNER_RESTRICTED_MODE);
      }
    }
  }
  //#region Dialog
  async H(question, trustedOption, untrustedOption, markdownStrings, trustParentString) {
    await this.f.prompt({
      type: Severity2.Info,
      message: question,
      checkbox: trustParentString ? {
        label: trustParentString
      } : void 0,
      buttons: [
        {
          label: trustedOption.label,
          run: async ({ checkboxChecked }) => {
            if (checkboxChecked) {
              await this.j.setParentFolderTrust(true);
            } else {
              await this.s.completeWorkspaceTrustRequest(true);
            }
          }
        },
        {
          label: untrustedOption.label,
          run: () => {
            this.G(false);
            this.s.cancelWorkspaceTrustRequest();
          }
        }
      ],
      custom: {
        buttonDetails: [
          trustedOption.sublabel,
          untrustedOption.sublabel
        ],
        disableCloseAction: true,
        icon: $6l.shield,
        markdownDetails: markdownStrings.map((md) => {
          return { markdown: new $bm(md) };
        })
      }
    });
    this.r.store(
      STARTUP_PROMPT_SHOWN_KEY,
      true,
      1,
      1
      /* StorageTarget.MACHINE */
    );
  }
  async I() {
    if (this.j.isWorkspaceTrusted()) {
      this.G(true);
      return;
    }
    if (!this.j.canSetWorkspaceTrust()) {
      return;
    }
    if ($_S(this.g.getWorkspace())) {
      this.G(false);
      return;
    }
    if (this.g.getWorkbenchState() === 1) {
      this.G(false);
      return;
    }
    if (this.J === "never") {
      this.G(false);
      return;
    }
    if (this.J === "once" && this.r.getBoolean(STARTUP_PROMPT_SHOWN_KEY, 1, false)) {
      this.G(false);
      return;
    }
    this.s.requestWorkspaceTrustOnStartup();
  }
  get J() {
    return this.m.getValue($BCb);
  }
  get L() {
    return !$1k($5k(this.g.getWorkspace()));
  }
  async M() {
    const aiGeneratedWorkspaces = URI.joinPath(this.C.workspaceStorageHome, "aiGeneratedWorkspaces.json");
    return await this.D.exists(aiGeneratedWorkspaces).then(async (result) => {
      if (result) {
        try {
          const content = await this.D.readFile(aiGeneratedWorkspaces);
          const workspaces = JSON.parse(content.value.toString());
          if (workspaces.indexOf(this.g.getWorkspace().folders[0].uri.toString()) > -1) {
            return true;
          }
        } catch (e) {
        }
      }
      return false;
    });
  }
  //#endregion
  //#region Banner
  N(restrictedMode) {
    const dismissedRestricted = this.r.getBoolean(BANNER_RESTRICTED_MODE_DISMISSED_KEY, 1, false);
    if (this.Q === "never") {
      return void 0;
    }
    if (this.Q === "untilDismissed" && dismissedRestricted) {
      return void 0;
    }
    const actions = [
      {
        label: localize(12155, null),
        href: "command:" + $Gac
      },
      {
        label: localize(12156, null),
        href: "https://aka.ms/vscode-workspace-trust"
      }
    ];
    return {
      id: BANNER_RESTRICTED_MODE,
      icon: $2kc,
      ariaLabel: this.O(),
      message: this.P(),
      actions,
      onClose: () => {
        if (restrictedMode) {
          this.r.store(
            BANNER_RESTRICTED_MODE_DISMISSED_KEY,
            true,
            1,
            1
            /* StorageTarget.MACHINE */
          );
        }
      }
    };
  }
  O() {
    switch (this.g.getWorkbenchState()) {
      case 1:
        return localize(12157, null);
      case 2:
        return localize(12158, null);
      case 3:
        return localize(12159, null);
    }
  }
  P() {
    switch (this.g.getWorkbenchState()) {
      case 1:
        return localize(12160, null);
      case 2:
        return localize(12161, null);
      case 3:
        return localize(12162, null);
    }
  }
  get Q() {
    const result = this.m.getValue($CCb);
    if (result !== "always" && $r && !this.z.getConnection()?.remoteAuthority) {
      return "never";
    }
    return result;
  }
  //#endregion
  //#region Statusbar
  R() {
    let ariaLabel = "";
    let toolTip;
    switch (this.g.getWorkbenchState()) {
      case 1: {
        ariaLabel = localize(12163, null);
        toolTip = {
          value: localize(12164, null, `command:${$Hzb}`, `command:${$Gac}`),
          isTrusted: true,
          supportThemeIcons: true
        };
        break;
      }
      case 2: {
        ariaLabel = localize(12165, null);
        toolTip = {
          value: localize(12166, null, `command:${$Hzb}`, `command:${$Gac}`),
          isTrusted: true,
          supportThemeIcons: true
        };
        break;
      }
      case 3: {
        ariaLabel = localize(12167, null);
        toolTip = {
          value: localize(12168, null, `command:${$Hzb}`, `command:${$Gac}`),
          isTrusted: true,
          supportThemeIcons: true
        };
        break;
      }
    }
    return {
      name: localize(12169, null),
      text: `$(shield) ${localize(12170, null)}`,
      ariaLabel,
      tooltip: toolTip,
      command: $Gac,
      kind: "prominent"
    };
  }
  S(trusted) {
    if (trusted && this.c.value) {
      this.c.clear();
      return;
    }
    if (!trusted && !this.c.value) {
      const entry = this.R();
      this.c.value = this.n.addEntry(
        entry,
        this.a,
        0,
        0.99 * Number.MAX_VALUE
        /* Right of remote indicator */
      );
    }
  }
};
$6kc = __decorate([
  __param(0, $Yv),
  __param(1, $Zk),
  __param(2, $3M),
  __param(3, $4M),
  __param(4, $kl),
  __param(5, $$qb),
  __param(6, $jv),
  __param(7, $5M),
  __param(8, $jVb),
  __param(9, $ZI),
  __param(10, $S4),
  __param(11, $Vu),
  __param(12, $RL),
  __param(13, $Xk),
  __param(14, $km)
], $6kc);
$PL(
  $5kc.ID,
  $5kc,
  2
  /* WorkbenchPhase.BlockRestore */
);
$Wn.as(Extensions2.Workbench).registerWorkbenchContribution(
  $6kc,
  3
  /* LifecyclePhase.Restored */
);
var WorkspaceTrustEditorInputSerializer = class {
  canSerialize(editorInput) {
    return true;
  }
  serialize(input) {
    return "";
  }
  deserialize(instantiationService) {
    return instantiationService.createInstance($1kc);
  }
};
$Wn.as($ZK.EditorFactory).registerEditorSerializer($1kc.ID, WorkspaceTrustEditorInputSerializer);
$Wn.as($ZK.EditorPane).registerEditorPane($7tb.create($3kc, $3kc.ID, localize(12171, null)), [
  new $Nk($1kc)
]);
var CONFIGURE_TRUST_COMMAND_ID = "workbench.trust.configure";
var WORKSPACES_CATEGORY = localize2(12186, "Workspaces");
$hJ(class extends $gJ {
  constructor() {
    super({
      id: CONFIGURE_TRUST_COMMAND_ID,
      title: localize2(12187, "Configure Workspace Trust Settings"),
      precondition: $7m.and($Fac.IsEnabled, $7m.equals(`config.${$ACb}`, true)),
      category: WORKSPACES_CATEGORY,
      f1: true
    });
  }
  run(accessor) {
    accessor.get($TK).openUserSettings({ jsonEditor: false, query: `@tag:${$DZb}` });
  }
});
$hJ(class extends $gJ {
  constructor() {
    super({
      id: $Gac,
      title: localize2(12188, "Manage Workspace Trust"),
      precondition: $7m.and($Fac.IsEnabled, $7m.equals(`config.${$ACb}`, true)),
      category: WORKSPACES_CATEGORY,
      f1: true
    });
  }
  run(accessor) {
    const editorService = accessor.get($mJ);
    const instantiationService = accessor.get($Pk);
    const input = instantiationService.createInstance($1kc);
    editorService.openEditor(input, { pinned: true });
    return;
  }
});
$Wn.as($Ht.Configuration).registerConfiguration({
  ...$VL,
  properties: {
    [$ACb]: {
      type: "boolean",
      default: true,
      description: localize(12172, null),
      tags: [$DZb],
      scope: 1
    },
    [$BCb]: {
      type: "string",
      default: "once",
      description: localize(12173, null),
      tags: [$DZb],
      scope: 1,
      enum: ["always", "once", "never"],
      enumDescriptions: [
        localize(12174, null),
        localize(12175, null),
        localize(12176, null)
      ]
    },
    [$CCb]: {
      type: "string",
      default: "untilDismissed",
      description: localize(12177, null),
      tags: [$DZb],
      scope: 1,
      enum: ["always", "untilDismissed", "never"],
      enumDescriptions: [
        localize(12178, null),
        localize(12179, null),
        localize(12180, null)
      ]
    },
    [$DCb]: {
      type: "string",
      default: "prompt",
      markdownDescription: localize(12181, null, $ECb),
      tags: [$DZb],
      scope: 1,
      enum: ["prompt", "open", "newWindow"],
      enumDescriptions: [
        localize(12182, null),
        localize(12183, null),
        localize(12184, null)
      ]
    },
    [$ECb]: {
      type: "boolean",
      default: true,
      markdownDescription: localize(12185, null, $DCb),
      tags: [$DZb],
      scope: 1
      /* ConfigurationScope.APPLICATION */
    }
  }
});
var WorkspaceTrustTelemetryContribution = class WorkspaceTrustTelemetryContribution2 extends $3c {
  constructor(a, c, f, g, h3) {
    super();
    this.a = a;
    this.c = c;
    this.f = f;
    this.g = g;
    this.h = h3;
    this.h.workspaceTrustInitialized.then(() => {
      this.j();
      this.m(this.h.isWorkspaceTrusted());
      this.B(this.h.onDidChangeTrust((isTrusted) => this.m(isTrusted)));
    });
  }
  j() {
    if (!this.g.isWorkspaceTrustEnabled()) {
      const disabledByCliFlag = this.a.disableWorkspaceTrust;
      this.c.publicLog2("workspaceTrustDisabled", {
        reason: disabledByCliFlag ? "cli" : "setting"
      });
      return;
    }
    this.c.publicLog2("workspaceTrustFolderCounts", {
      trustedFoldersCount: this.h.getTrustedUris().length
    });
  }
  async m(isTrusted) {
    if (!this.g.isWorkspaceTrustEnabled()) {
      return;
    }
    this.c.publicLog2("workspaceTrustStateChanged", {
      workspaceId: this.f.getWorkspace().id,
      isTrusted
    });
    if (isTrusted) {
      const getDepth = (folder) => {
        let resolvedPath = $oc(folder);
        let depth = 0;
        while ($qc(resolvedPath) !== resolvedPath && depth < 100) {
          resolvedPath = $qc(resolvedPath);
          depth++;
        }
        return depth;
      };
      for (const folder of this.f.getWorkspace().folders) {
        const { trusted, uri } = await this.h.getUriTrustInfo(folder.uri);
        if (!trusted) {
          continue;
        }
        const workspaceFolderDepth = getDepth(folder.uri.fsPath);
        const trustedFolderDepth = getDepth(uri.fsPath);
        const delta = workspaceFolderDepth - trustedFolderDepth;
        this.c.publicLog2("workspaceFolderDepthBelowTrustedFolder", { workspaceFolderDepth, trustedFolderDepth, delta });
      }
    }
  }
};
WorkspaceTrustTelemetryContribution = __decorate([
  __param(0, $US),
  __param(1, $zv),
  __param(2, $Zk),
  __param(3, $3M),
  __param(4, $4M)
], WorkspaceTrustTelemetryContribution);
$Wn.as(Extensions2.Workbench).registerWorkbenchContribution(
  WorkspaceTrustTelemetryContribution,
  3
  /* LifecyclePhase.Restored */
);

// out-build/vs/workbench/contrib/workspaces/browser/workspaces.contribution.js
var $7kc = class $7kc2 extends $3c {
  constructor(a, b, c, f, g, h3) {
    super();
    this.a = a;
    this.b = b;
    this.c = c;
    this.f = f;
    this.g = g;
    this.h = h3;
    this.j();
  }
  async j() {
    const folder = this.a.getWorkspace().folders[0];
    if (!folder || this.a.getWorkbenchState() !== 2 || $_S(this.a.getWorkspace())) {
      return;
    }
    const rootFileNames = (await this.c.resolve(folder.uri)).children?.map((child) => child.name);
    if (Array.isArray(rootFileNames)) {
      const workspaceFiles = rootFileNames.filter($jl);
      if (workspaceFiles.length > 0) {
        this.m(folder.uri, workspaceFiles);
      }
    }
  }
  m(folder, workspaces) {
    const neverShowAgain = { id: "workspaces.dontPromptToOpen", scope: NeverShowAgainScope.WORKSPACE, isSecondary: true };
    if (workspaces.length === 1) {
      const workspaceFile = workspaces[0];
      this.b.prompt(Severity2.Info, localize(12262, null, workspaceFile, "https://go.microsoft.com/fwlink/?linkid=2025315"), [{
        label: localize(12263, null),
        run: () => this.g.openWindow([{ workspaceUri: $vh(folder, workspaceFile) }])
      }], {
        neverShowAgain,
        priority: !this.h.isNew(
          1
          /* StorageScope.WORKSPACE */
        ) ? NotificationPriority.SILENT : void 0
        // https://github.com/microsoft/vscode/issues/125315
      });
    } else if (workspaces.length > 1) {
      this.b.prompt(Severity2.Info, localize(12264, null, "https://go.microsoft.com/fwlink/?linkid=2025315"), [{
        label: localize(12265, null),
        run: () => {
          this.f.pick(workspaces.map((workspace2) => ({ label: workspace2 })), { placeHolder: localize(12266, null) }).then((pick) => {
            if (pick) {
              this.g.openWindow([{ workspaceUri: $vh(folder, pick.label) }]);
            }
          });
        }
      }], {
        neverShowAgain,
        priority: !this.h.isNew(
          1
          /* StorageScope.WORKSPACE */
        ) ? NotificationPriority.SILENT : void 0
        // https://github.com/microsoft/vscode/issues/125315
      });
    }
  }
};
$7kc = __decorate([
  __param(0, $Zk),
  __param(1, $PJ),
  __param(2, $km),
  __param(3, $1M),
  __param(4, $S4),
  __param(5, $jv)
], $7kc);
$Wn.as(Extensions2.Workbench).registerWorkbenchContribution(
  $7kc,
  4
  /* LifecyclePhase.Eventually */
);
$hJ(class extends $gJ {
  constructor() {
    super({
      id: "workbench.action.openWorkspaceFromEditor",
      title: localize2(12268, "Open Workspace"),
      f1: false,
      menu: {
        id: $bJ.EditorContent,
        when: $7m.and($lqb.Extension.isEqualTo($bl), $Dpb.isEqualTo($mtb), $mpb.toNegated())
      }
    });
  }
  async run(accessor, uri) {
    const hostService = accessor.get($S4);
    const contextService = accessor.get($Zk);
    const notificationService = accessor.get($PJ);
    if (contextService.getWorkbenchState() === 3) {
      const workspaceConfiguration = contextService.getWorkspace().configuration;
      if (workspaceConfiguration && $oh(workspaceConfiguration, uri)) {
        notificationService.info(localize(12267, null));
        return;
      }
    }
    return hostService.openWindow([{ workspaceUri: uri }]);
  }
});

// out-build/vs/workbench/contrib/list/browser/tableColumnResizeQuickPick.js
var $8kc = class $8kc2 extends $3c {
  constructor(a, b) {
    super();
    this.a = a;
    this.b = b;
  }
  async show() {
    const items = [];
    this.a.getColumnLabels().forEach((label3, index) => {
      if (label3) {
        items.push({ label: label3, index });
      }
    });
    const column = await this.b.pick(items, { placeHolder: localize(7713, null) });
    if (!column) {
      return;
    }
    const value = await this.b.input({
      placeHolder: localize(7714, null),
      prompt: localize(7715, null, column.label),
      validateInput: (input) => this.c(input)
    });
    const percentageValue = value ? Number.parseInt(value) : void 0;
    if (!percentageValue) {
      return;
    }
    this.a.resizeColumn(column.index, percentageValue);
  }
  async c(input) {
    const percentage = Number.parseInt(input);
    if (input && !Number.isInteger(percentage)) {
      return localize(7716, null);
    } else if (percentage < 0 || percentage > 100) {
      return localize(7717, null);
    }
    return null;
  }
};
$8kc = __decorate([
  __param(1, $1M)
], $8kc);

// out-build/vs/workbench/contrib/list/browser/listResizeColumnAction.js
var $9kc = class extends $gJ {
  constructor() {
    super({
      id: "list.resizeColumn",
      title: { value: localize(7711, null), original: "Resize Column" },
      category: { value: localize(7712, null), original: "List" },
      precondition: $Leb,
      f1: true
    });
  }
  async run(accessor) {
    const listService = accessor.get($Deb);
    const instantiationService = accessor.get($Pk);
    const list2 = listService.lastFocusedList;
    if (list2 instanceof $e3) {
      await instantiationService.createInstance($8kc, list2).show();
    }
  }
};

// out-build/vs/workbench/contrib/list/browser/list.contribution.js
var $0kc = class $0kc2 {
  static {
    this.ID = "workbench.contrib.listContext";
  }
  constructor(contextKeyService) {
    contextKeyService.createKey("listSupportsTypeNavigation", true);
    contextKeyService.createKey("listSupportsKeyboardNavigation", true);
  }
};
$0kc = __decorate([
  __param(0, $on)
], $0kc);
$PL(
  $0kc.ID,
  $0kc,
  1
  /* WorkbenchPhase.BlockStartup */
);
$hJ($9kc);

// out-build/vs/workbench/contrib/accessibilitySignals/browser/accessibilitySignalDebuggerContribution.js
var $$kc = class $$kc2 extends $3c {
  constructor(debugService, a) {
    super();
    this.a = a;
    const isEnabled = $Dd(this, a.onSoundEnabledChanged($N9.onDebugBreak), () => a.isSoundEnabled($N9.onDebugBreak));
    this.B($xd((reader, store) => {
      if (!isEnabled.read(reader)) {
        return;
      }
      const sessionDisposables = /* @__PURE__ */ new Map();
      store.add($1c(() => {
        sessionDisposables.forEach((d) => d.dispose());
        sessionDisposables.clear();
      }));
      store.add(debugService.onDidNewSession((session) => sessionDisposables.set(session, this.b(session))));
      store.add(debugService.onDidEndSession(({ session }) => {
        sessionDisposables.get(session)?.dispose();
        sessionDisposables.delete(session);
      }));
      debugService.getModel().getSessions().forEach((session) => sessionDisposables.set(session, this.b(session)));
    }));
  }
  b(session) {
    return session.onDidChangeState((e) => {
      const stoppedDetails = session.getStoppedDetails();
      const BREAKPOINT_STOP_REASON = "breakpoint";
      if (stoppedDetails && stoppedDetails.reason === BREAKPOINT_STOP_REASON) {
        this.a.playSignal($N9.onDebugBreak);
      }
    });
  }
};
$$kc = __decorate([
  __param(0, $0R),
  __param(1, $I9)
], $$kc);

// out-build/vs/workbench/contrib/accessibilitySignals/browser/commands.js
var $_kc = class _$_kc extends $gJ {
  static {
    this.ID = "signals.sounds.help";
  }
  constructor() {
    super({
      id: _$_kc.ID,
      title: localize2(4492, "Help: List Signal Sounds"),
      f1: true,
      metadata: {
        description: localize(4485, null)
      }
    });
  }
  async run(accessor) {
    const accessibilitySignalService = accessor.get($I9);
    const quickInputService = accessor.get($1M);
    const configurationService = accessor.get($kl);
    const accessibilityService = accessor.get($ND);
    const preferencesService = accessor.get($TK);
    const userGestureSignals = [$N9.save, $N9.format];
    const items = $N9.allAccessibilitySignals.map((signal, idx) => ({
      label: userGestureSignals.includes(signal) ? `${signal.name} (${configurationService.getValue(signal.settingsKey + ".sound")})` : signal.name,
      signal,
      buttons: userGestureSignals.includes(signal) ? [{
        iconClass: ThemeIcon.asClassName($6l.settingsGear),
        tooltip: localize(4486, null),
        alwaysVisible: true
      }] : []
    })).sort((a, b) => a.label.localeCompare(b.label));
    const disposables = new $2c();
    const qp = disposables.add(quickInputService.createQuickPick());
    qp.items = items;
    qp.selectedItems = items.filter((i2) => accessibilitySignalService.isSoundEnabled(i2.signal) || userGestureSignals.includes(i2.signal) && configurationService.getValue(i2.signal.settingsKey + ".sound") !== "never");
    disposables.add(qp.onDidAccept(() => {
      const enabledSounds = qp.selectedItems.map((i2) => i2.signal);
      const disabledSounds = qp.items.map((i2) => i2.signal).filter((i2) => !enabledSounds.includes(i2));
      for (const signal of enabledSounds) {
        let { sound, announcement } = configurationService.getValue(signal.settingsKey);
        sound = userGestureSignals.includes(signal) ? "userGesture" : accessibilityService.isScreenReaderOptimized() ? "auto" : "on";
        if (announcement) {
          configurationService.updateValue(signal.settingsKey, { sound, announcement });
        } else {
          configurationService.updateValue(signal.settingsKey, { sound });
        }
      }
      for (const signal of disabledSounds) {
        const announcement = configurationService.getValue(signal.settingsKey + ".announcement");
        const sound = getDisabledSettingValue(userGestureSignals.includes(signal), accessibilityService.isScreenReaderOptimized());
        const value = announcement ? { sound, announcement } : { sound };
        configurationService.updateValue(signal.settingsKey, value);
      }
      qp.hide();
    }));
    disposables.add(qp.onDidTriggerItemButton((e) => {
      preferencesService.openUserSettings({ jsonEditor: true, revealSetting: { key: e.item.signal.settingsKey, edit: true } });
    }));
    disposables.add(qp.onDidChangeActive(() => {
      accessibilitySignalService.playSound(qp.activeItems[0].signal.sound.getSound(true), true, $J9);
    }));
    disposables.add(qp.onDidHide(() => disposables.dispose()));
    qp.placeholder = localize(4487, null);
    qp.canSelectMany = true;
    await qp.show();
  }
};
function getDisabledSettingValue(isUserGestureSignal, isScreenReaderOptimized) {
  return isScreenReaderOptimized ? isUserGestureSignal ? "never" : "off" : isUserGestureSignal ? "never" : "auto";
}
var $alc = class _$alc extends $gJ {
  static {
    this.ID = "accessibility.announcement.help";
  }
  constructor() {
    super({
      id: _$alc.ID,
      title: localize2(4493, "Help: List Signal Announcements"),
      f1: true,
      metadata: {
        description: localize(4488, null)
      }
    });
  }
  async run(accessor) {
    const accessibilitySignalService = accessor.get($I9);
    const quickInputService = accessor.get($1M);
    const configurationService = accessor.get($kl);
    const accessibilityService = accessor.get($ND);
    const preferencesService = accessor.get($TK);
    const userGestureSignals = [$N9.save, $N9.format];
    const items = $N9.allAccessibilitySignals.filter((c) => !!c.legacyAnnouncementSettingsKey).map((signal, idx) => ({
      label: userGestureSignals.includes(signal) ? `${signal.name} (${configurationService.getValue(signal.settingsKey + ".announcement")})` : signal.name,
      signal,
      buttons: userGestureSignals.includes(signal) ? [{
        iconClass: ThemeIcon.asClassName($6l.settingsGear),
        tooltip: localize(4489, null),
        alwaysVisible: true
      }] : []
    })).sort((a, b) => a.label.localeCompare(b.label));
    const disposables = new $2c();
    const qp = disposables.add(quickInputService.createQuickPick());
    qp.items = items;
    qp.selectedItems = items.filter((i2) => accessibilitySignalService.isAnnouncementEnabled(i2.signal) || userGestureSignals.includes(i2.signal) && configurationService.getValue(i2.signal.settingsKey + ".announcement") !== "never");
    const screenReaderOptimized = accessibilityService.isScreenReaderOptimized();
    disposables.add(qp.onDidAccept(() => {
      if (!screenReaderOptimized) {
        qp.hide();
        return;
      }
      const enabledAnnouncements = qp.selectedItems.map((i2) => i2.signal);
      const disabledAnnouncements = $N9.allAccessibilitySignals.filter((cue) => !!cue.legacyAnnouncementSettingsKey && !enabledAnnouncements.includes(cue));
      for (const signal of enabledAnnouncements) {
        let { sound, announcement } = configurationService.getValue(signal.settingsKey);
        announcement = userGestureSignals.includes(signal) ? "userGesture" : signal.announcementMessage && accessibilityService.isScreenReaderOptimized() ? "auto" : void 0;
        configurationService.updateValue(signal.settingsKey, { sound, announcement });
      }
      for (const signal of disabledAnnouncements) {
        const announcement = getDisabledSettingValue(userGestureSignals.includes(signal), true);
        const sound = configurationService.getValue(signal.settingsKey + ".sound");
        const value = announcement ? { sound, announcement } : { sound };
        configurationService.updateValue(signal.settingsKey, value);
      }
      qp.hide();
    }));
    disposables.add(qp.onDidTriggerItemButton((e) => {
      preferencesService.openUserSettings({ jsonEditor: true, revealSetting: { key: e.item.signal.settingsKey, edit: true } });
    }));
    disposables.add(qp.onDidHide(() => disposables.dispose()));
    qp.placeholder = screenReaderOptimized ? localize(4490, null) : localize(4491, null);
    qp.canSelectMany = true;
    await qp.show();
  }
};

// out-build/vs/workbench/contrib/accessibilitySignals/browser/editorTextPropertySignalsContribution.js
var $blc = class $blc2 extends $3c {
  constructor(f, g, h3) {
    super();
    this.f = f;
    this.g = g;
    this.h = h3;
    this.a = [
      this.g.createInstance(MarkerTextProperty, $N9.errorAtPosition, $N9.errorOnLine, MarkerSeverity.Error),
      this.g.createInstance(MarkerTextProperty, $N9.warningAtPosition, $N9.warningOnLine, MarkerSeverity.Warning),
      this.g.createInstance(FoldedAreaTextProperty),
      this.g.createInstance(BreakpointTextProperty)
    ];
    this.b = $2d(this, (reader) => this.a.flatMap((p) => [p.lineSignal, p.positionSignal]).filter($Hg).some((signal) => $Td(this, this.h.getEnabledState(signal, false)).read(reader)));
    this.c = $Dd(this, this.f.onDidActiveEditorChange, (_) => {
      const activeTextEditorControl = this.f.activeTextEditorControl;
      const editor = $Q5(activeTextEditorControl) ? activeTextEditorControl.getOriginalEditor() : $P5(activeTextEditorControl) ? activeTextEditorControl : void 0;
      return editor && editor.hasModel() ? { editor, model: editor.getModel() } : void 0;
    });
    this.B($xd((reader, store) => {
      if (!this.b.read(reader)) {
        return;
      }
      const activeEditor = this.c.read(reader);
      if (activeEditor) {
        this.j(activeEditor.editor, activeEditor.model, store);
      }
    }));
  }
  j(editor, editorModel, store) {
    let lastLine = -1;
    const ignoredLineSignalsForCurrentLine = /* @__PURE__ */ new Set();
    const timeouts = store.add(new $2c());
    const propertySources = this.a.map((p) => ({ source: p.createSource(editor, editorModel), property: p }));
    const didType = $Ld(editor.onDidChangeModelContent, 100, store);
    store.add(editor.onDidChangeCursorPosition((args2) => {
      timeouts.clear();
      if (args2 && args2.reason !== 3 && args2.reason !== 0) {
        ignoredLineSignalsForCurrentLine.clear();
        return;
      }
      const trigger = (property, source, mode) => {
        const signal = mode === "line" ? property.lineSignal : property.positionSignal;
        if (!signal || !this.h.getEnabledState(signal, false).value || !source.isPresent(position, mode, void 0)) {
          return;
        }
        for (const modality of ["sound", "announcement"]) {
          if (this.h.getEnabledState(signal, false, modality).value) {
            const delay = this.h.getDelayMs(signal, modality, mode) + (didType.get() ? 1e3 : 0);
            timeouts.add($Xh(() => {
              if (source.isPresent(position, mode, void 0)) {
                if (!(mode === "line") || !ignoredLineSignalsForCurrentLine.has(property)) {
                  this.h.playSignal(signal, { modality });
                }
                ignoredLineSignalsForCurrentLine.add(property);
              }
            }, delay));
          }
        }
      };
      const position = args2.position;
      const lineNumber = position.lineNumber;
      if (lineNumber !== lastLine) {
        ignoredLineSignalsForCurrentLine.clear();
        lastLine = lineNumber;
        for (const p of propertySources) {
          trigger(p.property, p.source, "line");
        }
      }
      for (const p of propertySources) {
        trigger(p.property, p.source, "positional");
      }
      for (const s of propertySources) {
        if (![s.property.lineSignal, s.property.positionSignal].some((s2) => s2 && this.h.getEnabledState(s2, false).value)) {
          return;
        }
        let lastValueAtPosition = void 0;
        let lastValueOnLine = void 0;
        timeouts.add($td((reader) => {
          const newValueAtPosition = s.source.isPresentAtPosition(args2.position, reader);
          const newValueOnLine = s.source.isPresentOnLine(args2.position.lineNumber, reader);
          if (lastValueAtPosition !== void 0 && lastValueAtPosition !== void 0) {
            if (!lastValueAtPosition && newValueAtPosition) {
              trigger(s.property, s.source, "positional");
            }
            if (!lastValueOnLine && newValueOnLine) {
              trigger(s.property, s.source, "line");
            }
          }
          lastValueAtPosition = newValueAtPosition;
          lastValueOnLine = newValueOnLine;
        }));
      }
    }));
  }
};
$blc = __decorate([
  __param(0, $mJ),
  __param(1, $Pk),
  __param(2, $I9)
], $blc);
var TextPropertySource = class _TextPropertySource {
  static {
    this.notPresent = new _TextPropertySource({ isPresentAtPosition: () => false, isPresentOnLine: () => false });
  }
  constructor(options3) {
    this.isPresentOnLine = options3.isPresentOnLine;
    this.isPresentAtPosition = options3.isPresentAtPosition ?? (() => false);
  }
  isPresent(position, mode, reader) {
    return mode === "line" ? this.isPresentOnLine(position.lineNumber, reader) : this.isPresentAtPosition(position, reader);
  }
};
var MarkerTextProperty = class MarkerTextProperty2 {
  constructor(positionSignal, lineSignal, a, b) {
    this.positionSignal = positionSignal;
    this.lineSignal = lineSignal;
    this.a = a;
    this.b = b;
    this.debounceWhileTyping = true;
  }
  createSource(editor, model) {
    const obs = $Gd("onMarkerChanged", this.b.onMarkerChanged);
    return new TextPropertySource({
      isPresentAtPosition: (position, reader) => {
        obs.read(reader);
        const hasMarker = this.b.read({ resource: model.uri }).some((m) => m.severity === this.a && m.startLineNumber <= position.lineNumber && position.lineNumber <= m.endLineNumber && m.startColumn <= position.column && position.column <= m.endColumn);
        return hasMarker;
      },
      isPresentOnLine: (lineNumber, reader) => {
        obs.read(reader);
        const hasMarker = this.b.read({ resource: model.uri }).some((m) => m.severity === this.a && m.startLineNumber <= lineNumber && lineNumber <= m.endLineNumber);
        return hasMarker;
      }
    });
  }
};
MarkerTextProperty = __decorate([
  __param(3, $DE)
], MarkerTextProperty);
var FoldedAreaTextProperty = class {
  constructor() {
    this.lineSignal = $N9.foldedArea;
  }
  createSource(editor, _model) {
    const foldingController = $9gb.get(editor);
    if (!foldingController) {
      return TextPropertySource.notPresent;
    }
    const foldingModel = $Cd(foldingController.getFoldingModel() ?? Promise.resolve(void 0));
    return new TextPropertySource({
      isPresentOnLine(lineNumber, reader) {
        const m = foldingModel.read(reader);
        const regionAtLine = m.value?.getRegionAtLine(lineNumber);
        const hasFolding = !regionAtLine ? false : regionAtLine.isCollapsed && regionAtLine.startLineNumber === lineNumber;
        return hasFolding;
      }
    });
  }
};
var BreakpointTextProperty = class BreakpointTextProperty2 {
  constructor(a) {
    this.a = a;
    this.lineSignal = $N9.break;
  }
  createSource(editor, model) {
    const signal = $Gd("onDidChangeBreakpoints", this.a.getModel().onDidChangeBreakpoints);
    const debugService = this.a;
    return new TextPropertySource({
      isPresentOnLine(lineNumber, reader) {
        signal.read(reader);
        const breakpoints = debugService.getModel().getBreakpoints({ uri: model.uri, lineNumber });
        const hasBreakpoints = breakpoints.length > 0;
        return hasBreakpoints;
      }
    });
  }
};
BreakpointTextProperty = __decorate([
  __param(0, $0R)
], BreakpointTextProperty);

// out-build/vs/workbench/contrib/accessibilitySignals/browser/accessibilitySignal.contribution.js
$SC(
  $I9,
  $K9,
  1
  /* InstantiationType.Delayed */
);
$PL(
  "EditorTextPropertySignalsContribution",
  $Zjb(() => $blc),
  3
  /* WorkbenchPhase.AfterRestored */
);
$PL(
  "AccessibilitySignalLineDebuggerContribution",
  $$kc,
  3
  /* WorkbenchPhase.AfterRestored */
);
$hJ($_kc);
$hJ($alc);

// out-build/vs/workbench/contrib/deprecatedExtensionMigrator/browser/deprecatedExtensionMigrator.contribution.js
var DeprecatedExtensionMigratorContribution = class DeprecatedExtensionMigratorContribution2 {
  constructor(a, b, c, f, g) {
    this.a = a;
    this.b = b;
    this.c = c;
    this.f = f;
    this.g = g;
    this.i = "deprecatedExtensionMigrator.state";
    this.h().catch($gb);
  }
  async h() {
    const bracketPairColorizerId = "coenraads.bracket-pair-colorizer";
    await this.b.queryLocal();
    const extension = this.b.installed.find((e) => e.identifier.id === bracketPairColorizerId);
    if (!extension || extension.enablementState !== 10 && extension.enablementState !== 11) {
      return;
    }
    const state = await this.j();
    const disablementLogEntry = state.disablementLog.some((d) => d.extensionId === bracketPairColorizerId);
    if (disablementLogEntry) {
      return;
    }
    state.disablementLog.push({ extensionId: bracketPairColorizerId, disablementDateTime: (/* @__PURE__ */ new Date()).getTime() });
    await this.k(state);
    await this.b.setEnablement(
      extension,
      8
      /* EnablementState.DisabledGlobally */
    );
    const nativeBracketPairColorizationEnabledKey = "editor.bracketPairColorization.enabled";
    const bracketPairColorizationEnabled = !!this.a.inspect(nativeBracketPairColorizationEnabledKey).user;
    this.f.notify({
      message: localize(6244, null),
      severity: Severity2.Info,
      actions: {
        primary: [
          new $Um("", localize(6245, null), void 0, void 0, () => {
            this.b.uninstall(extension);
          })
        ],
        secondary: [
          !bracketPairColorizationEnabled ? new $Um("", localize(6246, null), void 0, void 0, () => {
            this.a.updateValue(
              nativeBracketPairColorizationEnabledKey,
              true,
              2
              /* ConfigurationTarget.USER */
            );
          }) : void 0,
          new $Um("", localize(6247, null), void 0, void 0, () => {
            this.g.open("https://github.com/microsoft/vscode/issues/155179");
          })
        ].filter($Hg)
      }
    });
  }
  async j() {
    const jsonStr = await this.c.get(this.i, -1, "");
    if (jsonStr === "") {
      return { disablementLog: [] };
    }
    return JSON.parse(jsonStr);
  }
  async k(state) {
    const json = JSON.stringify(state);
    await this.c.store(
      this.i,
      json,
      -1,
      0
      /* StorageTarget.USER */
    );
  }
};
DeprecatedExtensionMigratorContribution = __decorate([
  __param(0, $kl),
  __param(1, $vzb),
  __param(2, $jv),
  __param(3, $PJ),
  __param(4, $O4)
], DeprecatedExtensionMigratorContribution);
$Wn.as(Extensions2.Workbench).registerWorkbenchContribution(
  DeprecatedExtensionMigratorContribution,
  3
  /* LifecyclePhase.Restored */
);

// out-build/vs/workbench/contrib/bracketPairColorizer2Telemetry/browser/bracketPairColorizer2Telemetry.contribution.js
var BracketPairColorizer2TelemetryContribution = class BracketPairColorizer2TelemetryContribution2 {
  constructor(a, b, c) {
    this.a = a;
    this.b = b;
    this.c = c;
    this.d().catch($gb);
  }
  async d() {
    const bracketPairColorizerId = "coenraads.bracket-pair-colorizer-2";
    await this.b.queryLocal();
    const extension = this.b.installed.find((e) => e.identifier.id === bracketPairColorizerId);
    if (!extension || extension.enablementState !== 10 && extension.enablementState !== 11) {
      return;
    }
    const nativeBracketPairColorizationEnabledKey = "editor.bracketPairColorization.enabled";
    const nativeColorizationEnabled = !!this.a.getValue(nativeBracketPairColorizationEnabledKey);
    this.c.publicLog2("bracketPairColorizerTwoUsage", {
      nativeColorizationEnabled
    });
  }
};
BracketPairColorizer2TelemetryContribution = __decorate([
  __param(0, $kl),
  __param(1, $vzb),
  __param(2, $zv)
], BracketPairColorizer2TelemetryContribution);
$Wn.as(Extensions2.Workbench).registerWorkbenchContribution(
  BracketPairColorizer2TelemetryContribution,
  3
  /* LifecyclePhase.Restored */
);

// out-build/vs/workbench/contrib/accessibility/browser/unfocusedViewDimmingContribution.js
var $clc = class $clc2 extends $3c {
  constructor(configurationService) {
    super();
    this.b = void 0;
    this.B($1c(() => this.f()));
    this.B(Event2.runAndSubscribe(configurationService.onDidChangeConfiguration, (e) => {
      if (e && !e.affectsConfiguration(
        "accessibility.dimUnfocused.enabled"
        /* AccessibilityWorkbenchSettingId.DimUnfocusedEnabled */
      ) && !e.affectsConfiguration(
        "accessibility.dimUnfocused.opacity"
        /* AccessibilityWorkbenchSettingId.DimUnfocusedOpacity */
      )) {
        return;
      }
      let cssTextContent = "";
      const enabled = ensureBoolean(configurationService.getValue(
        "accessibility.dimUnfocused.enabled"
        /* AccessibilityWorkbenchSettingId.DimUnfocusedEnabled */
      ), false);
      if (enabled) {
        const opacity = $4i(
          ensureNumber(
            configurationService.getValue(
              "accessibility.dimUnfocused.opacity"
              /* AccessibilityWorkbenchSettingId.DimUnfocusedOpacity */
            ),
            0.75
            /* ViewDimUnfocusedOpacityProperties.Default */
          ),
          0.2,
          1
          /* ViewDimUnfocusedOpacityProperties.Maximum */
        );
        if (opacity !== 1) {
          const rules = /* @__PURE__ */ new Set();
          const filterRule = `filter: opacity(${opacity});`;
          rules.add(`.monaco-workbench .pane-body.integrated-terminal:not(:focus-within) .tabs-container { ${filterRule} }`);
          rules.add(`.monaco-workbench .pane-body.integrated-terminal .terminal-wrapper:not(:focus-within) { ${filterRule} }`);
          rules.add(`.monaco-workbench .editor-instance:not(:focus-within) .monaco-editor { ${filterRule} }`);
          rules.add(`.monaco-workbench .editor-instance:not(:focus-within) .breadcrumbs-below-tabs { ${filterRule} }`);
          rules.add(`.monaco-workbench .editor-instance:not(:focus-within) .terminal-wrapper { ${filterRule} }`);
          rules.add(`.monaco-workbench .editor-instance:not(:focus-within) .settings-editor { ${filterRule} }`);
          rules.add(`.monaco-workbench .editor-instance:not(:focus-within) .keybindings-editor { ${filterRule} }`);
          rules.add(`.monaco-workbench .editor-instance:not(:focus-within) .monaco-editor-pane-placeholder { ${filterRule} }`);
          rules.add(`.monaco-workbench .editor-instance:not(:focus-within) .gettingStartedContainer { ${filterRule} }`);
          cssTextContent = [...rules].join("\n");
        }
      }
      if (cssTextContent.length === 0) {
        this.f();
      } else {
        this.c().textContent = cssTextContent;
      }
    }));
  }
  c() {
    if (!this.a) {
      this.b = new $2c();
      this.a = $VZ(void 0, void 0, this.b);
      this.a.className = "accessibilityUnfocusedViewOpacity";
    }
    return this.a;
  }
  f() {
    this.b?.dispose();
    this.b = void 0;
    this.a = void 0;
  }
};
$clc = __decorate([
  __param(0, $kl)
], $clc);
function ensureBoolean(value, defaultValue) {
  return typeof value === "boolean" ? value : defaultValue;
}
function ensureNumber(value, defaultValue) {
  return typeof value === "number" ? value : defaultValue;
}

// out-build/vs/workbench/contrib/accessibility/browser/accessibilityStatus.js
var $dlc = class $dlc2 extends $3c {
  static {
    this.ID = "workbench.contrib.accessibilityStatus";
  }
  constructor(g, h3, j, m) {
    super();
    this.g = g;
    this.h = h3;
    this.j = j;
    this.m = m;
    this.a = null;
    this.b = false;
    this.f = this.B(new $4c());
    this.B($tn.registerCommand({ id: "showEditorScreenReaderNotification", handler: () => this.r() }));
    this.s(this.j.isScreenReaderOptimized());
    this.n();
  }
  n() {
    this.B(this.j.onDidChangeScreenReaderOptimized(() => this.t()));
    this.B(this.g.onDidChangeConfiguration((c) => {
      if (c.affectsConfiguration("editor.accessibilitySupport")) {
        this.t();
      }
    }));
  }
  r() {
    this.a = this.h.prompt(severity_default.Info, localize(4439, null), [{
      label: localize(4440, null),
      run: () => {
        this.g.updateValue(
          "editor.accessibilitySupport",
          "on",
          2
          /* ConfigurationTarget.USER */
        );
      }
    }, {
      label: localize(4441, null),
      run: () => {
        this.g.updateValue(
          "editor.accessibilitySupport",
          "off",
          2
          /* ConfigurationTarget.USER */
        );
      }
    }], {
      sticky: true,
      priority: NotificationPriority.URGENT
    });
    Event2.once(this.a.onDidClose)(() => this.a = null);
  }
  s(visible) {
    if (visible) {
      if (!this.f.value) {
        const text2 = localize(4442, null);
        this.f.value = this.m.addEntry({
          name: localize(4443, null),
          text: text2,
          ariaLabel: text2,
          command: "showEditorScreenReaderNotification",
          kind: "prominent",
          showInAllWindows: true
        }, "status.editor.screenReaderMode", 1, 100.6);
      }
    } else {
      this.f.clear();
    }
  }
  t() {
    const screenReaderDetected = this.j.isScreenReaderOptimized();
    if (screenReaderDetected) {
      const screenReaderConfiguration = this.g.getValue("editor.accessibilitySupport");
      if (screenReaderConfiguration === "auto") {
        if (!this.b) {
          this.b = true;
          setTimeout(() => this.r(), 100);
        }
      }
    }
    if (this.a) {
      this.a.close();
    }
    this.s(this.j.isScreenReaderOptimized());
  }
};
$dlc = __decorate([
  __param(0, $kl),
  __param(1, $PJ),
  __param(2, $ND),
  __param(3, $$qb)
], $dlc);

// out-build/vs/workbench/contrib/accessibilitySignals/browser/saveAccessibilitySignal.js
var $elc = class $elc2 extends $3c {
  static {
    this.ID = "workbench.contrib.saveAccessibilitySignal";
  }
  constructor(a, b) {
    super();
    this.a = a;
    this.b = b;
    this.B(this.b.onDidSave((e) => this.a.playSignal($N9.save, {
      userGesture: e.reason === 1
      /* SaveReason.EXPLICIT */
    })));
  }
};
$elc = __decorate([
  __param(0, $I9),
  __param(1, $XI)
], $elc);

// out-build/vs/workbench/contrib/accessibilitySignals/browser/openDiffEditorAnnouncement.js
var $flc = class $flc2 extends $3c {
  static {
    this.ID = "workbench.contrib.diffEditorActiveAnnouncement";
  }
  constructor(b, c, f) {
    super();
    this.b = b;
    this.c = c;
    this.f = f;
    this.B(Event2.runAndSubscribe(c.onDidChangeScreenReaderOptimized, () => this.g()));
    this.B(f.onDidChangeConfiguration((e) => {
      if (e.affectsConfiguration(
        "accessibility.verbosity.diffEditorActive"
        /* AccessibilityVerbositySettingId.DiffEditorActive */
      )) {
        this.g();
      }
    }));
  }
  g() {
    const announcementEnabled = this.f.getValue(
      "accessibility.verbosity.diffEditorActive"
      /* AccessibilityVerbositySettingId.DiffEditorActive */
    );
    const screenReaderOptimized = this.c.isScreenReaderOptimized();
    if (!announcementEnabled || !screenReaderOptimized) {
      this.a?.dispose();
      this.a = void 0;
      return;
    }
    if (this.a) {
      return;
    }
    this.a = this.B(this.b.onDidActiveEditorChange(() => {
      if ($Q5(this.b.activeTextEditorControl)) {
        this.c.alert(localize(4494, null));
      }
    }));
  }
};
$flc = __decorate([
  __param(0, $mJ),
  __param(1, $ND),
  __param(2, $kl)
], $flc);

// out-build/vs/workbench/contrib/speech/browser/speechAccessibilitySignal.js
var $glc = class $glc2 extends $3c {
  static {
    this.ID = "workbench.contrib.speechAccessibilitySignal";
  }
  constructor(a, b) {
    super();
    this.a = a;
    this.b = b;
    this.B(this.b.onDidStartSpeechToTextSession(() => this.a.playSignal($N9.voiceRecordingStarted)));
    this.B(this.b.onDidEndSpeechToTextSession(() => this.a.playSignal($N9.voiceRecordingStopped)));
  }
};
$glc = __decorate([
  __param(0, $I9),
  __param(1, $jS)
], $glc);

// out-build/vs/workbench/contrib/accessibility/browser/accessibleViewKeybindingResolver.js
function $hlc(keybindingService, value) {
  if (!value) {
    return;
  }
  const configureKeybindingItems = [];
  const configuredKeybindingItems = [];
  const matches = value.matchAll(/(\<keybinding:(?<commandId>[^\<]*)\>)/gm);
  for (const match of [...matches]) {
    const commandId = match?.groups?.commandId;
    let kbLabel;
    if (match?.length && commandId) {
      const keybinding = keybindingService.lookupKeybinding(commandId)?.getAriaLabel();
      if (!keybinding) {
        kbLabel = ` (unassigned keybinding)`;
        configureKeybindingItems.push({
          label: commandId,
          id: commandId
        });
      } else {
        kbLabel = " (" + keybinding + ")";
        configuredKeybindingItems.push({
          label: commandId,
          id: commandId
        });
      }
      value = value.replace(match[0], kbLabel);
    }
  }
  const content = new $bm(value);
  content.isTrusted = true;
  return { content, configureKeybindingItems: configureKeybindingItems.length ? configureKeybindingItems : void 0, configuredKeybindingItems: configuredKeybindingItems.length ? configuredKeybindingItems : void 0 };
}

// out-build/vs/workbench/contrib/accessibility/browser/accessibleView.js
var DIMENSIONS;
(function(DIMENSIONS2) {
  DIMENSIONS2[DIMENSIONS2["MAX_WIDTH"] = 600] = "MAX_WIDTH";
})(DIMENSIONS || (DIMENSIONS = {}));
var $ilc = class $ilc2 extends $3c {
  get editorWidget() {
    return this.a;
  }
  constructor(L, M, N, O, P, Q, R, S, U, W, X, Y, Z, $149, ab) {
    super();
    this.L = L;
    this.M = M;
    this.N = N;
    this.O = O;
    this.P = P;
    this.Q = Q;
    this.R = R;
    this.S = S;
    this.U = U;
    this.W = W;
    this.X = X;
    this.Y = Y;
    this.Z = Z;
    this.$ = $149;
    this.ab = ab;
    this.z = false;
    this.b = $nsb.bindTo(this.Q);
    this.g = $osb.bindTo(this.Q);
    this.h = $psb.bindTo(this.Q);
    this.j = $qsb.bindTo(this.Q);
    this.m = $rsb.bindTo(this.Q);
    this.n = $tsb.bindTo(this.Q);
    this.r = $usb.bindTo(this.Q);
    this.s = $vsb.bindTo(this.Q);
    this.f = $ssb.bindTo(this.Q);
    this.t = $wsb.bindTo(this.Q);
    this.u = $xsb.bindTo(this.Q);
    this.C = document.createElement("div");
    this.C.classList.add("accessible-view");
    if (this.N.getValue(
      "accessibility.hideAccessibleView"
      /* AccessibilityWorkbenchSettingId.HideAccessibleView */
    )) {
      this.C.classList.add("hide");
    }
    const codeEditorWidgetOptions = {
      contributions: EditorExtensionsRegistry.getEditorContributions().filter((c) => c.id !== $fbb.ID)
    };
    const titleBar = document.createElement("div");
    titleBar.classList.add("accessible-view-title-bar");
    this.D = document.createElement("div");
    this.D.classList.add("accessible-view-title");
    titleBar.appendChild(this.D);
    const actionBar = document.createElement("div");
    actionBar.classList.add("accessible-view-action-bar");
    titleBar.appendChild(actionBar);
    this.C.appendChild(titleBar);
    this.F = this.B(M.createInstance($3$, actionBar, {
      orientation: 0
      /* ActionsOrientation.HORIZONTAL */
    }));
    this.F.context = { viewId: "accessibleView" };
    const toolbarElt = this.F.getElement();
    toolbarElt.tabIndex = 0;
    const editorOptions2 = {
      ...$Zsb(this.N),
      lineDecorationsWidth: 6,
      dragAndDrop: false,
      cursorWidth: 1,
      wordWrap: "off",
      wrappingStrategy: "advanced",
      wrappingIndent: "none",
      padding: { top: 2, bottom: 2 },
      quickSuggestions: false,
      renderWhitespace: "none",
      dropIntoEditor: { enabled: false },
      readOnly: true,
      fontFamily: "var(--monaco-monospace-font)"
    };
    this.$.registerTextModelContentProvider(Schemas.accessibleView, this);
    this.a = this.B(this.M.createInstance($D9, this.C, editorOptions2, codeEditorWidgetOptions));
    this.B(this.R.onDidChangeScreenReaderOptimized(() => {
      if (this.G && this.b.get()) {
        this.show(this.G);
      }
    }));
    this.B(this.N.onDidChangeConfiguration((e) => {
      if (this.G instanceof $thb && e.affectsConfiguration(this.G.verbositySettingKey)) {
        if (this.b.get()) {
          this.show(this.G);
        }
        this.j.set(this.N.getValue(this.G.verbositySettingKey));
        this.hb(this.G.actions, this.G.options.type);
      }
      if (e.affectsConfiguration(
        "accessibility.hideAccessibleView"
        /* AccessibilityWorkbenchSettingId.HideAccessibleView */
      )) {
        this.C.classList.toggle("hide", this.N.getValue(
          "accessibility.hideAccessibleView"
          /* AccessibilityWorkbenchSettingId.HideAccessibleView */
        ));
      }
    }));
    this.B(this.a.onDidDispose(() => this.bb()));
    this.B(this.a.onDidChangeCursorPosition(() => {
      this.f.set(this.a.getPosition()?.lineNumber === this.a.getModel()?.getLineCount());
    }));
    this.B(this.a.onDidChangeCursorPosition(() => {
      const cursorPosition = this.a.getPosition()?.lineNumber;
      if (this.w && cursorPosition !== void 0) {
        const inCodeBlock = this.w.find((c) => c.startLine <= cursorPosition && c.endLine >= cursorPosition) !== void 0;
        this.r.set(inCodeBlock);
      }
    }));
  }
  provideTextContent(resource) {
    return this.jb(resource);
  }
  bb() {
    this.b.reset();
    this.g.reset();
    this.h.reset();
    this.j.reset();
    this.m.reset();
    this.n.reset();
    this.u.reset();
    this.t.reset();
  }
  getPosition(id2) {
    if (!id2 || !this.I || this.I.id !== id2) {
      return void 0;
    }
    return this.a.getPosition() || void 0;
  }
  setPosition(position, reveal, select) {
    this.a.setPosition(position);
    if (reveal) {
      this.a.revealPosition(position);
    }
    if (select) {
      const lineLength = this.a.getModel()?.getLineLength(position.lineNumber) ?? 0;
      if (lineLength) {
        this.a.setSelection({ startLineNumber: position.lineNumber, startColumn: 1, endLineNumber: position.lineNumber, endColumn: lineLength + 1 });
      }
    }
  }
  getCodeBlockContext() {
    const position = this.a.getPosition();
    if (!this.w?.length || !position) {
      return;
    }
    const codeBlockIndex = this.w?.findIndex((c) => c.startLine <= position?.lineNumber && c.endLine >= position?.lineNumber);
    const codeBlock = codeBlockIndex !== void 0 && codeBlockIndex > -1 ? this.w[codeBlockIndex] : void 0;
    if (!codeBlock || codeBlockIndex === void 0) {
      return;
    }
    return { code: codeBlock.code, languageId: codeBlock.languageId, codeBlockIndex, element: void 0 };
  }
  navigateToCodeBlock(type) {
    const position = this.a.getPosition();
    if (!this.w?.length || !position) {
      return;
    }
    let codeBlock;
    const codeBlocks = this.w.slice();
    if (type === "previous") {
      codeBlock = codeBlocks.reverse().find((c) => c.endLine < position.lineNumber);
    } else {
      codeBlock = codeBlocks.find((c) => c.startLine > position.lineNumber);
    }
    if (!codeBlock) {
      return;
    }
    this.setPosition(new $8C(codeBlock.startLine, 1), true);
  }
  showLastProvider(id2) {
    if (!this.I || this.I.options.id !== id2) {
      return;
    }
    this.show(this.I);
  }
  show(provider, symbol, showAccessibleViewHelp, position) {
    provider = provider ?? this.G;
    if (!provider) {
      return;
    }
    provider.onOpen?.();
    const delegate = {
      getAnchor: () => {
        return { x: $Qj().innerWidth / 2 - Math.min(
          this.U.activeContainerDimension.width * 0.62,
          600
          /* DIMENSIONS.MAX_WIDTH */
        ) / 2, y: this.U.activeContainerOffset.quickPickTop };
      },
      render: (container2) => {
        this.J = container2;
        this.J.classList.add("accessible-view-container");
        return this.gb(provider, container2, showAccessibleViewHelp);
      },
      onHide: () => {
        if (!showAccessibleViewHelp) {
          this.lb();
          this.G?.dispose();
          this.G = void 0;
          this.bb();
        }
      }
    };
    this.P.showContextView(delegate);
    if (position) {
      queueMicrotask(() => {
        this.a.revealLine(position.lineNumber);
        this.a.setSelection({ startLineNumber: position.lineNumber, startColumn: position.column, endLineNumber: position.lineNumber, endColumn: position.column });
      });
    }
    if (symbol && this.G) {
      this.showSymbol(this.G, symbol);
    }
    if (provider instanceof $thb && provider.onDidRequestClearLastProvider) {
      this.B(provider.onDidRequestClearLastProvider((id2) => {
        if (this.I?.options.id === id2) {
          this.I = void 0;
        }
      }));
    }
    if (provider.options.id) {
      this.I = provider;
    }
    if (provider.id === "panelChat" || provider.id === "quickChat") {
      this.B(this.Y.registerProvider({ getCodeBlockContext: () => this.getCodeBlockContext() }, "accessibleView"));
    }
    if (provider instanceof $uhb) {
      this.Z.store(
        `${$QD}${provider.id}`,
        true,
        -1,
        0
        /* StorageTarget.USER */
      );
    }
    if (provider.onDidChangeContent) {
      this.B(provider.onDidChangeContent(() => {
        if (this.J) {
          this.gb(provider, this.J, showAccessibleViewHelp);
        }
      }));
    }
  }
  previous() {
    const newContent = this.G?.providePreviousContent?.();
    if (!this.G || !this.J || !newContent) {
      return;
    }
    this.gb(this.G, this.J, void 0, newContent);
  }
  next() {
    const newContent = this.G?.provideNextContent?.();
    if (!this.G || !this.J || !newContent) {
      return;
    }
    this.gb(this.G, this.J, void 0, newContent);
  }
  cb() {
    if (!this.G) {
      return false;
    }
    return this.G instanceof $thb ? this.N.getValue(this.G.verbositySettingKey) === true : this.Z.getBoolean(`${$QD}${this.G.id}`, -1, false);
  }
  goToSymbol() {
    if (!this.G) {
      return;
    }
    this.M.createInstance(AccessibleViewSymbolQuickPick, this).show(this.G);
  }
  calculateCodeBlocks(markdown) {
    if (!markdown) {
      return;
    }
    if (this.G?.id !== "panelChat" && this.G?.id !== "quickChat") {
      return;
    }
    if (this.G.options.language && this.G.options.language !== "markdown") {
      return;
    }
    const lines = markdown.split("\n");
    this.w = [];
    let inBlock = false;
    let startLine = 0;
    let languageId;
    lines.forEach((line, i2) => {
      if (!inBlock && line.startsWith("```")) {
        inBlock = true;
        startLine = i2 + 1;
        languageId = line.substring(3).trim();
      } else if (inBlock && line.endsWith("```")) {
        inBlock = false;
        const endLine = i2;
        const code = lines.slice(startLine, endLine).join("\n");
        this.w?.push({ startLine, endLine, code, languageId });
      }
    });
    this.s.set(this.w.length > 0);
  }
  getSymbols() {
    const provider = this.G instanceof $thb ? this.G : void 0;
    if (!this.H || !provider) {
      return;
    }
    const symbols = provider.getSymbols?.() || [];
    if (symbols?.length) {
      return symbols;
    }
    if (provider.options.language && provider.options.language !== "markdown") {
      return;
    }
    const markdownTokens = marked.lexer(this.H);
    if (!markdownTokens) {
      return;
    }
    this.db(markdownTokens, symbols);
    return symbols.length ? symbols : void 0;
  }
  openHelpLink() {
    if (!this.G?.options.readMoreUrl) {
      return;
    }
    this.L.open(URI.parse(this.G.options.readMoreUrl));
  }
  configureKeybindings(unassigned) {
    this.z = true;
    const provider = this.lb();
    const items = unassigned ? provider?.options?.configureKeybindingItems : provider?.options?.configuredKeybindingItems;
    if (!items) {
      return;
    }
    const disposables = this.B(new $2c());
    const quickPick = disposables.add(this.ab.createQuickPick());
    quickPick.items = items;
    quickPick.title = localize(4444, null);
    quickPick.placeholder = localize(4445, null);
    quickPick.show();
    disposables.add(quickPick.onDidAccept(async () => {
      const item = quickPick.selectedItems[0];
      if (item) {
        await this.X.executeCommand("workbench.action.openGlobalKeybindings", item.id);
      }
      quickPick.dispose();
    }));
    disposables.add(quickPick.onDidHide(() => {
      if (!quickPick.selectedItems.length && provider) {
        this.show(provider);
      }
      disposables.dispose();
      this.z = false;
    }));
  }
  db(tokens, symbols) {
    let firstListItem;
    for (const token of tokens) {
      let label3 = void 0;
      if ("type" in token) {
        switch (token.type) {
          case "heading":
          case "paragraph":
          case "code":
            label3 = token.text;
            break;
          case "list": {
            const firstItem = token.items[0];
            if (!firstItem) {
              break;
            }
            firstListItem = `- ${firstItem.text}`;
            label3 = token.items.map((i2) => i2.text).join(", ");
            break;
          }
        }
      }
      if (label3) {
        symbols.push({ markdownToParse: label3, label: localize(4446, null, token.type, label3), ariaLabel: localize(4447, null, token.type, label3), firstListItem });
        firstListItem = void 0;
      }
    }
  }
  showSymbol(provider, symbol) {
    if (!this.H) {
      return;
    }
    let lineNumber = symbol.lineNumber;
    const markdownToParse = symbol.markdownToParse;
    if (lineNumber === void 0 && markdownToParse === void 0) {
      return;
    }
    if (lineNumber === void 0 && markdownToParse) {
      const index = this.H.split("\n").findIndex((line) => line.includes(markdownToParse.split("\n")[0]) || symbol.firstListItem && line.includes(symbol.firstListItem)) ?? -1;
      if (index >= 0) {
        lineNumber = index + 1;
      }
    }
    if (lineNumber === void 0) {
      return;
    }
    this.show(provider, void 0, void 0, { lineNumber, column: 1 });
    this.eb(provider, true);
  }
  disableHint() {
    if (!(this.G instanceof $thb)) {
      return;
    }
    this.N.updateValue(this.G?.verbositySettingKey, false);
    $$Z(localize(4448, null, this.G.verbositySettingKey));
  }
  eb(provider, shown) {
    if (provider.options.type === "help") {
      this.b.set(shown);
      this.g.reset();
    } else {
      this.g.set(shown);
      this.b.reset();
    }
    this.h.set(provider.provideNextContent !== void 0 || provider.providePreviousContent !== void 0);
    this.j.set(this.cb());
    this.m.set(this.kb() ? this.getSymbols()?.length > 0 : false);
  }
  fb(provider, updatedContent) {
    let content = updatedContent ?? provider.provideContent();
    if (provider.options.type === "view") {
      this.H = content;
      this.t.reset();
      this.u.reset();
      return;
    }
    const readMoreLinkHint = this.vb(provider);
    const disableHelpHint = this.pb(provider);
    const screenReaderModeHint = this.tb(provider);
    const exitThisDialogHint = this.ub(provider);
    let configureKbHint = "";
    let configureAssignedKbHint = "";
    const resolvedContent = $hlc(this.S, screenReaderModeHint + content + readMoreLinkHint + disableHelpHint + exitThisDialogHint);
    if (resolvedContent) {
      content = resolvedContent.content.value;
      if (resolvedContent.configureKeybindingItems) {
        provider.options.configureKeybindingItems = resolvedContent.configureKeybindingItems;
        this.t.set(true);
        configureKbHint = this.rb();
      } else {
        this.u.reset();
      }
      if (resolvedContent.configuredKeybindingItems) {
        provider.options.configuredKeybindingItems = resolvedContent.configuredKeybindingItems;
        this.u.set(true);
        configureAssignedKbHint = this.sb();
      } else {
        this.u.reset();
      }
    }
    this.H = content + configureKbHint + configureAssignedKbHint;
  }
  gb(provider, container2, showAccessibleViewHelp, updatedContent) {
    this.G = provider;
    this.n.set(provider.id);
    const verbose = this.cb();
    this.fb(provider, updatedContent);
    this.calculateCodeBlocks(this.H);
    this.eb(provider, true);
    const widgetIsFocused = this.a.hasTextFocus() || this.a.hasWidgetFocus();
    this.jb(URI.from({ path: `accessible-view-${provider.id}`, scheme: Schemas.accessibleView, fragment: this.H })).then((model) => {
      if (!model) {
        return;
      }
      this.a.setModel(model);
      const domNode = this.a.getDomNode();
      if (!domNode) {
        return;
      }
      model.setLanguage(provider.options.language ?? "markdown");
      container2.appendChild(this.C);
      let actionsHint = "";
      const hasActions = this.h.get() || this.j.get() || this.m.get() || provider.actions?.length;
      if (verbose && !showAccessibleViewHelp && hasActions) {
        actionsHint = provider.options.position ? localize(4449, null) : localize(4450, null);
      }
      let ariaLabel = provider.options.type === "help" ? localize(4451, null) : localize(4452, null);
      this.D.textContent = ariaLabel;
      if (actionsHint && provider.options.type === "view") {
        ariaLabel = localize(4453, null, actionsHint);
      } else if (actionsHint) {
        ariaLabel = localize(4454, null, actionsHint);
      }
      if ($l && widgetIsFocused) {
        ariaLabel = "";
      }
      this.a.updateOptions({ ariaLabel });
      this.a.focus();
      if (this.G?.options.position) {
        const position = this.a.getPosition();
        const isDefaultPosition = position?.lineNumber === 1 && position.column === 1;
        if (this.G.options.position === "bottom" || this.G.options.position === "initial-bottom" && isDefaultPosition) {
          const lastLine = this.editorWidget.getModel()?.getLineCount();
          const position2 = lastLine !== void 0 && lastLine > 0 ? new $8C(lastLine, 1) : void 0;
          if (position2) {
            this.a.setPosition(position2);
            this.a.revealLine(position2.lineNumber);
          }
        }
      }
    });
    this.hb(this.G.actions, provider.options.type);
    const hide3 = (e) => {
      if (!this.z) {
        provider.onClose();
      }
      e?.stopPropagation();
      this.P.hideContextView();
      this.eb(provider, false);
      this.I = void 0;
      this.H = void 0;
      this.G?.dispose();
      this.G = void 0;
    };
    const disposableStore = new $2c();
    disposableStore.add(this.a.onKeyDown((e) => {
      if (e.keyCode === 3) {
        this.X.executeCommand("editor.action.openLink");
      } else if (e.keyCode === 9 || shouldHide(e.browserEvent, this.S, this.N)) {
        hide3(e);
      } else if (e.keyCode === 38 && provider.options.readMoreUrl) {
        const url = provider.options.readMoreUrl;
        $$Z(AccessibilityHelpNLS.openingDocs);
        this.L.open(URI.parse(url));
        e.preventDefault();
        e.stopPropagation();
      }
      if (provider instanceof $thb) {
        provider.onKeyDown?.(e);
      }
    }));
    disposableStore.add($_i(this.F.getElement(), $7j.KEY_DOWN, (e) => {
      const keyboardEvent = new $if(e);
      if (keyboardEvent.equals(
        9
        /* KeyCode.Escape */
      )) {
        hide3(e);
      }
    }));
    disposableStore.add(this.a.onDidBlurEditorWidget(() => {
      if (!$Mj(this.F.getElement())) {
        hide3();
      }
    }));
    disposableStore.add(this.a.onDidContentSizeChange(() => this.ib()));
    disposableStore.add(this.U.onDidLayoutActiveContainer(() => this.ib()));
    return disposableStore;
  }
  hb(providedActions, type) {
    this.F.setAriaLabel(type === "help" ? localize(4455, null) : localize(4456, null));
    const toolbarMenu = this.B(this.W.createMenu($bJ.AccessibleView, this.Q));
    const menuActions = $R$(toolbarMenu.getActions({}));
    if (providedActions) {
      for (const providedAction of providedActions) {
        providedAction.class = providedAction.class || ThemeIcon.asClassName($6l.primitiveSquare);
        providedAction.checked = void 0;
      }
      this.F.setActions([...providedActions, ...menuActions]);
    } else {
      this.F.setActions(menuActions);
    }
  }
  ib() {
    const dimension = this.U.activeContainerDimension;
    const maxHeight = dimension.height && dimension.height * 0.4;
    const height = Math.min(maxHeight, this.a.getContentHeight());
    const width2 = Math.min(
      dimension.width * 0.62,
      600
      /* DIMENSIONS.MAX_WIDTH */
    );
    this.a.layout({ width: width2, height });
  }
  async jb(resource) {
    const existing = this.O.getModel(resource);
    if (existing && !existing.isDisposed()) {
      return existing;
    }
    return this.O.createModel(resource.fragment, null, resource, false);
  }
  kb() {
    if (!this.G) {
      return false;
    }
    return this.G.options.type === "help" || this.G.options.language === "markdown" || this.G.options.language === void 0 || this.G instanceof $thb && !!this.G.getSymbols?.();
  }
  lb() {
    const provider = this.G;
    if (!provider) {
      return;
    }
    const lastProvider = provider instanceof $thb ? new $thb(provider.id, provider.options, provider.provideContent.bind(provider), provider.onClose.bind(provider), provider.verbositySettingKey, provider.onOpen?.bind(provider), provider.actions, provider.provideNextContent?.bind(provider), provider.providePreviousContent?.bind(provider), provider.onDidChangeContent?.bind(provider), provider.onKeyDown?.bind(provider), provider.getSymbols?.bind(provider)) : new $uhb(provider.id, provider.options, provider.provideContent.bind(provider), provider.onClose.bind(provider), provider.onOpen?.bind(provider), provider.provideNextContent?.bind(provider), provider.providePreviousContent?.bind(provider), provider.actions, provider.onDidChangeContent?.bind(provider));
    return lastProvider;
  }
  showAccessibleViewHelp() {
    const lastProvider = this.lb();
    if (!lastProvider) {
      return;
    }
    let accessibleViewHelpProvider;
    if (lastProvider instanceof $thb) {
      accessibleViewHelpProvider = new $thb(lastProvider.id, {
        type: "help"
        /* AccessibleViewType.Help */
      }, () => lastProvider.options.customHelp ? lastProvider?.options.customHelp() : this.mb(this.kb()), () => {
        this.P.hideContextView();
        queueMicrotask(() => this.show(lastProvider));
      }, lastProvider.verbositySettingKey);
    } else {
      accessibleViewHelpProvider = new $uhb(lastProvider.id, {
        type: "help"
        /* AccessibleViewType.Help */
      }, () => lastProvider.options.customHelp ? lastProvider?.options.customHelp() : this.mb(this.kb()), () => {
        this.P.hideContextView();
        queueMicrotask(() => this.show(lastProvider));
      });
    }
    this.P.hideContextView();
    if (accessibleViewHelpProvider) {
      queueMicrotask(() => this.show(accessibleViewHelpProvider, void 0, true));
    }
  }
  mb(providerHasSymbols) {
    const navigationHint = this.ob();
    const goToSymbolHint = this.qb(providerHasSymbols);
    const toolbarHint = localize(4457, null);
    const chatHints = this.nb();
    let hint = localize(4458, null);
    if (navigationHint) {
      hint += " - " + navigationHint + "\n";
    }
    if (goToSymbolHint) {
      hint += " - " + goToSymbolHint + "\n";
    }
    if (toolbarHint) {
      hint += " - " + toolbarHint + "\n";
    }
    if (chatHints) {
      hint += chatHints;
    }
    return hint;
  }
  nb() {
    if (this.G?.id !== "panelChat" && this.G?.id !== "quickChat") {
      return;
    }
    return [
      localize(4459, null, "<keybinding:workbench.action.chat.insertCodeBlock>"),
      localize(4460, null, "<keybinding:workbench.action.chat.insertIntoNewFile>"),
      localize(4461, null, "<keybinding:workbench.action.chat.runInTerminal>")
    ].join("\n");
  }
  ob() {
    return localize(4462, null, `<keybinding:${"editor.action.accessibleViewNext"}`, `<keybinding:${"editor.action.accessibleViewPrevious"}>`);
  }
  pb(provider) {
    if (provider.options.type === "help" && this.cb()) {
      return localize(4463, null, `<keybinding:${"editor.action.accessibleViewDisableHint"}>`);
    }
    return "";
  }
  qb(providerHasSymbols) {
    if (!providerHasSymbols) {
      return;
    }
    return localize(4464, null, `<keybinding:${"editor.action.accessibleViewGoToSymbol"}>`);
  }
  rb() {
    const configureKb = this.S.lookupKeybinding(
      "editor.action.accessibilityHelpConfigureKeybindings"
      /* AccessibilityCommandId.AccessibilityHelpConfigureKeybindings */
    )?.getAriaLabel();
    const keybindingToConfigureQuickPick = configureKb ? "(" + configureKb + ")" : "by assigning a keybinding to the command Accessibility Help Configure Unassigned Keybindings.";
    return localize(4465, null, keybindingToConfigureQuickPick);
  }
  sb() {
    const configureKb = this.S.lookupKeybinding(
      "editor.action.accessibilityHelpConfigureAssignedKeybindings"
      /* AccessibilityCommandId.AccessibilityHelpConfigureAssignedKeybindings */
    )?.getAriaLabel();
    const keybindingToConfigureQuickPick = configureKb ? "(" + configureKb + ")" : "by assigning a keybinding to the command Accessibility Help Configure Assigned Keybindings.";
    return localize(4466, null, keybindingToConfigureQuickPick);
  }
  tb(provider) {
    const accessibilitySupport = this.R.isScreenReaderOptimized();
    let screenReaderModeHint = "";
    const turnOnMessage = $m ? AccessibilityHelpNLS.changeConfigToOnMac : AccessibilityHelpNLS.changeConfigToOnWinLinux;
    if (accessibilitySupport && provider.id === "editor") {
      screenReaderModeHint = AccessibilityHelpNLS.auto_on;
      screenReaderModeHint += "\n";
    } else if (!accessibilitySupport) {
      screenReaderModeHint = AccessibilityHelpNLS.auto_off + "\n" + turnOnMessage;
      screenReaderModeHint += "\n";
    }
    return screenReaderModeHint;
  }
  ub(provider) {
    return this.cb() && !provider.options.position ? localize(4467, null) : "";
  }
  vb(provider) {
    return provider.options.readMoreUrl ? localize(4468, null, `<keybinding:${"editor.action.accessibilityHelpOpenHelpLink"}>`) : "";
  }
};
$ilc = __decorate([
  __param(0, $O4),
  __param(1, $Pk),
  __param(2, $kl),
  __param(3, $sG),
  __param(4, $40),
  __param(5, $on),
  __param(6, $ND),
  __param(7, $Ty),
  __param(8, $Ulb),
  __param(9, $cJ),
  __param(10, $sn),
  __param(11, $8Nb),
  __param(12, $jv),
  __param(13, $oG),
  __param(14, $1M)
], $ilc);
var $jlc = class $jlc2 extends $3c {
  constructor(b, f, g) {
    super();
    this.b = b;
    this.f = f;
    this.g = g;
  }
  show(provider, position) {
    if (!this.a) {
      this.a = this.B(this.b.createInstance($ilc));
    }
    this.a.show(provider, void 0, void 0, position);
  }
  configureKeybindings(unassigned) {
    this.a?.configureKeybindings(unassigned);
  }
  openHelpLink() {
    this.a?.openHelpLink();
  }
  showLastProvider(id2) {
    this.a?.showLastProvider(id2);
  }
  next() {
    this.a?.next();
  }
  previous() {
    this.a?.previous();
  }
  goToSymbol() {
    this.a?.goToSymbol();
  }
  getOpenAriaHint(verbositySettingKey) {
    if (!this.f.getValue(verbositySettingKey)) {
      return null;
    }
    const keybinding = this.g.lookupKeybinding(
      "editor.action.accessibleView"
      /* AccessibilityCommandId.OpenAccessibleView */
    )?.getAriaLabel();
    let hint = null;
    if (keybinding) {
      hint = localize(4469, null, keybinding);
    } else {
      hint = localize(4470, null);
    }
    return hint;
  }
  disableHint() {
    this.a?.disableHint();
  }
  showAccessibleViewHelp() {
    this.a?.showAccessibleViewHelp();
  }
  getPosition(id2) {
    return this.a?.getPosition(id2) ?? void 0;
  }
  getLastPosition() {
    const lastLine = this.a?.editorWidget.getModel()?.getLineCount();
    return lastLine !== void 0 && lastLine > 0 ? new $8C(lastLine, 1) : void 0;
  }
  setPosition(position, reveal, select) {
    this.a?.setPosition(position, reveal, select);
  }
  getCodeBlockContext() {
    return this.a?.getCodeBlockContext();
  }
  navigateToCodeBlock(type) {
    this.a?.navigateToCodeBlock(type);
  }
};
$jlc = __decorate([
  __param(0, $Pk),
  __param(1, $kl),
  __param(2, $Ty)
], $jlc);
var AccessibleViewSymbolQuickPick = class AccessibleViewSymbolQuickPick2 {
  constructor(a, b) {
    this.a = a;
    this.b = b;
  }
  show(provider) {
    const disposables = new $2c();
    const quickPick = disposables.add(this.b.createQuickPick());
    quickPick.placeholder = localize(4471, null);
    quickPick.title = localize(4472, null);
    const picks = [];
    const symbols = this.a.getSymbols();
    if (!symbols) {
      return;
    }
    for (const symbol of symbols) {
      picks.push({
        label: symbol.label,
        ariaLabel: symbol.ariaLabel
      });
    }
    quickPick.canSelectMany = false;
    quickPick.items = symbols;
    quickPick.show();
    disposables.add(quickPick.onDidAccept(() => {
      this.a.showSymbol(provider, quickPick.selectedItems[0]);
      quickPick.hide();
    }));
    disposables.add(quickPick.onDidHide(() => {
      if (quickPick.selectedItems.length === 0) {
        this.a.show(provider);
      }
      disposables.dispose();
    }));
  }
};
AccessibleViewSymbolQuickPick = __decorate([
  __param(1, $1M)
], AccessibleViewSymbolQuickPick);
function shouldHide(event, keybindingService, configurationService) {
  if (!configurationService.getValue(
    "accessibility.accessibleView.closeOnKeyPress"
    /* AccessibilityWorkbenchSettingId.AccessibleViewCloseOnKeyPress */
  )) {
    return false;
  }
  const standardKeyboardEvent = new $if(event);
  const resolveResult = keybindingService.softDispatch(standardKeyboardEvent, standardKeyboardEvent.target);
  const isValidChord = resolveResult.kind === 1;
  if (keybindingService.inChordMode || isValidChord) {
    return false;
  }
  return shouldHandleKey(event) && !event.ctrlKey && !event.altKey && !event.metaKey && !event.shiftKey;
}
function shouldHandleKey(event) {
  return !!event.code.match(/^(Key[A-Z]|Digit[0-9]|Equal|Comma|Period|Slash|Quote|Backquote|Backslash|Minus|Semicolon|Space|Enter)$/);
}

// out-build/vs/workbench/contrib/accessibility/browser/accessibleViewContributions.js
var $klc = class extends $3c {
  constructor() {
    super();
    this.B($uSb.addImplementation(115, "accessible-view-help", (accessor) => {
      accessor.get($shb).showAccessibleViewHelp();
      return true;
    }, $osb));
  }
};
var $llc = class extends $3c {
  constructor() {
    super();
    $vhb.getImplementations().forEach((impl) => {
      const implementation = (accessor) => {
        const provider = impl.getProvider(accessor);
        if (!provider) {
          return false;
        }
        try {
          accessor.get($shb).show(provider);
          return true;
        } catch {
          provider.dispose();
          return false;
        }
      };
      if (impl.type === "view") {
        this.B($vSb.addImplementation(impl.priority, impl.name, implementation, impl.when));
      } else {
        this.B($uSb.addImplementation(impl.priority, impl.name, implementation, impl.when));
      }
    });
  }
};

// out-build/vs/workbench/contrib/accessibility/browser/extensionAccesibilityHelp.contribution.js
var $mlc = class $mlc2 extends $3c {
  static {
    this.ID = "extensionAccessibilityHelpDialogContribution";
  }
  constructor(keybindingService) {
    super();
    this.a = this.B(new $_c());
    this.B($Wn.as(Extensions5.ViewsRegistry).onViewsRegistered((e) => {
      for (const view of e) {
        for (const viewDescriptor3 of view.views) {
          if (viewDescriptor3.accessibilityHelpContent) {
            this.a.set(viewDescriptor3.id, registerAccessibilityHelpAction(keybindingService, viewDescriptor3));
          }
        }
      }
    }));
    this.B($Wn.as(Extensions5.ViewsRegistry).onViewsDeregistered((e) => {
      for (const viewDescriptor3 of e.views) {
        if (viewDescriptor3.accessibilityHelpContent) {
          this.a.get(viewDescriptor3.id)?.dispose();
        }
      }
    }));
  }
};
$mlc = __decorate([
  __param(0, $Ty)
], $mlc);
function registerAccessibilityHelpAction(keybindingService, viewDescriptor3) {
  const disposableStore = new $2c();
  const content = viewDescriptor3.accessibilityHelpContent?.value;
  if (!content) {
    throw new Error("No content provided for the accessibility help dialog");
  }
  disposableStore.add($vhb.register({
    priority: 95,
    name: viewDescriptor3.id,
    type: "help",
    when: $jqb.isEqualTo(viewDescriptor3.id),
    getProvider: (accessor) => {
      const viewsService = accessor.get($uob);
      return new $uhb(viewDescriptor3.id, {
        type: "help"
        /* AccessibleViewType.Help */
      }, () => content, () => viewsService.openView(viewDescriptor3.id, true));
    }
  }));
  disposableStore.add(keybindingService.onDidUpdateKeybindings(() => {
    disposableStore.clear();
    disposableStore.add(registerAccessibilityHelpAction(keybindingService, viewDescriptor3));
  }));
  return disposableStore;
}

// out-build/vs/workbench/contrib/accessibility/browser/accessibility.contribution.js
$Bsb();
$SC(
  $shb,
  $jlc,
  1
  /* InstantiationType.Delayed */
);
$SC(
  $9ob,
  $0ob,
  1
  /* InstantiationType.Delayed */
);
var workbenchRegistry8 = $Wn.as(Extensions2.Workbench);
workbenchRegistry8.registerWorkbenchContribution(
  $_hc,
  4
  /* LifecyclePhase.Eventually */
);
workbenchRegistry8.registerWorkbenchContribution(
  $clc,
  3
  /* LifecyclePhase.Restored */
);
workbenchRegistry8.registerWorkbenchContribution(
  $klc,
  4
  /* LifecyclePhase.Eventually */
);
workbenchRegistry8.registerWorkbenchContribution(
  $llc,
  4
  /* LifecyclePhase.Eventually */
);
$PL(
  $dlc.ID,
  $dlc,
  2
  /* WorkbenchPhase.BlockRestore */
);
$PL(
  $mlc.ID,
  $mlc,
  2
  /* WorkbenchPhase.BlockRestore */
);
$PL(
  $elc.ID,
  $elc,
  3
  /* WorkbenchPhase.AfterRestored */
);
$PL(
  $glc.ID,
  $glc,
  3
  /* WorkbenchPhase.AfterRestored */
);
$PL(
  $flc.ID,
  $flc,
  3
  /* WorkbenchPhase.AfterRestored */
);
$PL(
  $Dsb.ID,
  $Dsb,
  3
  /* WorkbenchPhase.AfterRestored */
);

// out-build/vs/workbench/contrib/share/browser/shareService.js
var $nlc = new $nn("shareProviderCount", 0, localize(9834, null));
var $olc = class $olc2 {
  constructor(d, e, f, g, h3) {
    this.d = d;
    this.e = e;
    this.f = f;
    this.g = g;
    this.h = h3;
    this.c = /* @__PURE__ */ new Set();
    this.providerCount = $nlc.bindTo(this.d);
  }
  registerShareProvider(provider) {
    this.c.add(provider);
    this.providerCount.set(this.c.size);
    return {
      dispose: () => {
        this.c.delete(provider);
        this.providerCount.set(this.c.size);
      }
    };
  }
  getShareActions() {
    return [];
  }
  async provideShare(item, token) {
    const language = this.g.getActiveCodeEditor()?.getModel()?.getLanguageId() ?? "";
    const providers2 = [...this.c.values()].filter((p) => $qE(p.selector, item.resourceUri, language, true, void 0, void 0) > 0).sort((a, b) => a.priority - b.priority);
    if (providers2.length === 0) {
      return void 0;
    }
    if (providers2.length === 1) {
      this.h.publicLog2("shareService.share", { providerId: providers2[0].id });
      return providers2[0].provideShare(item, token);
    }
    const items = providers2.map((p) => ({ label: p.label, provider: p }));
    const selected = await this.f.pick(items, { canPickMany: false, placeHolder: localize(9835, null, this.e.getUriLabel(item.resourceUri)) }, token);
    if (selected !== void 0) {
      this.h.publicLog2("shareService.share", { providerId: selected.provider.id });
      return selected.provider.provideShare(item, token);
    }
    return;
  }
};
$olc = __decorate([
  __param(0, $on),
  __param(1, $ZI),
  __param(2, $1M),
  __param(3, $U5),
  __param(4, $zv)
], $olc);

// out-build/vs/workbench/contrib/share/browser/share.contribution.js
var ShareWorkbenchContribution_1;
var targetMenus = [
  $bJ.EditorContextShare,
  $bJ.SCMResourceContextShare,
  $bJ.OpenEditorsContextShare,
  $bJ.EditorTitleContextShare,
  $bJ.MenubarShare,
  // MenuId.EditorLineNumberContext, // todo@joyceerhl add share
  $bJ.ExplorerContextShare
];
var ShareWorkbenchContribution = class ShareWorkbenchContribution2 {
  static {
    ShareWorkbenchContribution_1 = this;
  }
  static {
    this.a = "workbench.experimental.share.enabled";
  }
  constructor(c, d) {
    this.c = c;
    this.d = d;
    if (this.d.getValue(ShareWorkbenchContribution_1.a)) {
      this.f();
    }
    this.d.onDidChangeConfiguration((e) => {
      if (e.affectsConfiguration(ShareWorkbenchContribution_1.a)) {
        const settingValue = this.d.getValue(ShareWorkbenchContribution_1.a);
        if (settingValue === true && this.b === void 0) {
          this.f();
        } else if (settingValue === false && this.b !== void 0) {
          this.b?.clear();
          this.b = void 0;
        }
      }
    });
  }
  f() {
    if (!this.b) {
      this.b = new $2c();
    }
    this.b.add($hJ(class ShareAction extends $gJ {
      static {
        this.ID = "workbench.action.share";
      }
      static {
        this.LABEL = localize2(9833, "Share...");
      }
      constructor() {
        super({
          id: ShareAction.ID,
          title: ShareAction.LABEL,
          f1: true,
          icon: $6l.linkExternal,
          precondition: $7m.and($nlc.notEqualsTo(0), $fpb.notEqualsTo(0)),
          keybinding: {
            weight: 200,
            primary: 512 | 2048 | 49
          },
          menu: [
            { id: $bJ.CommandCenter, order: 1e3 }
          ]
        });
      }
      async run(accessor, ...args2) {
        const shareService = accessor.get($JTb);
        const activeEditor = accessor.get($mJ)?.activeEditor;
        const resourceUri = (activeEditor && $mL.getOriginalUri(activeEditor, { supportSideBySide: SideBySideEditor.PRIMARY })) ?? accessor.get($Zk).getWorkspace().folders[0].uri;
        const clipboardService = accessor.get($30);
        const dialogService = accessor.get($Yv);
        const urlService = accessor.get($O4);
        const progressService = accessor.get($TJ);
        const selection = accessor.get($U5).getActiveCodeEditor()?.getSelection() ?? void 0;
        const result = await progressService.withProgress({
          location: 10,
          detail: localize(9827, null)
        }, async () => shareService.provideShare({ resourceUri, selection }, CancellationToken.None));
        if (result) {
          const uriText = result.toString();
          const isResultText = typeof result === "string";
          await clipboardService.writeText(uriText);
          dialogService.prompt({
            type: Severity2.Info,
            message: isResultText ? localize(9828, null) : localize(9829, null),
            custom: {
              icon: $6l.check,
              markdownDetails: [{
                markdown: new $bm(`<div aria-label='${uriText}'>${uriText}</div>`, { supportHtml: true }),
                classes: [isResultText ? "share-dialog-input-text" : "share-dialog-input-link"]
              }]
            },
            cancelButton: localize(9830, null),
            buttons: isResultText ? [] : [{ label: localize(9831, null), run: () => {
              urlService.open(result, { openExternal: true });
            } }]
          });
        }
      }
    }));
    const actions = this.c.getShareActions();
    for (const menuId of targetMenus) {
      for (const action of actions) {
        this.b.add($dJ.appendMenuItem(menuId, action));
      }
    }
  }
};
ShareWorkbenchContribution = ShareWorkbenchContribution_1 = __decorate([
  __param(0, $JTb),
  __param(1, $kl)
], ShareWorkbenchContribution);
$SC(
  $JTb,
  $olc,
  1
  /* InstantiationType.Delayed */
);
var workbenchContributionsRegistry9 = $Wn.as(Extensions2.Workbench);
workbenchContributionsRegistry9.registerWorkbenchContribution(
  ShareWorkbenchContribution,
  4
  /* LifecyclePhase.Eventually */
);
$Wn.as($Ht.Configuration).registerConfiguration({
  ...$UL,
  properties: {
    "workbench.experimental.share.enabled": {
      type: "boolean",
      default: false,
      tags: ["experimental"],
      markdownDescription: localize(9832, null, "`#window.commandCenter#`", "`true`"),
      restricted: false
    }
  }
});

// out-build/vs/workbench/contrib/scrollLocking/browser/scrollLocking.js
var $plc = class $plc2 extends $3c {
  static {
    this.ID = "workbench.contrib.syncScrolling";
  }
  constructor(h3, j) {
    super();
    this.h = h3;
    this.j = j;
    this.a = /* @__PURE__ */ new Map();
    this.b = this.B(new $2c());
    this.c = new $2c();
    this.f = this.B(new $4c());
    this.g = false;
    this.r = new $J3();
    this.z();
  }
  m() {
    this.b.add(this.h.onDidVisibleEditorsChange(() => this.s()));
  }
  n() {
    this.m();
    this.s();
  }
  toggle() {
    if (this.g) {
      this.w();
    } else {
      this.n();
    }
    this.g = !this.g;
    this.y(this.g);
  }
  s() {
    this.c.clear();
    this.a.clear();
    for (const pane of this.u()) {
      if (!$6K(pane)) {
        continue;
      }
      this.a.set(pane, pane.getScrollPosition());
      this.c.add(pane.onDidChangeScroll(() => this.r.runExclusivelyOrSkip(() => {
        this.t(pane);
      })));
    }
  }
  t(scrolledPane) {
    const scrolledPaneInitialOffset = this.a.get(scrolledPane);
    if (scrolledPaneInitialOffset === void 0) {
      throw new Error("Scrolled pane not tracked");
    }
    if (!$6K(scrolledPane)) {
      throw new Error("Scrolled pane does not support scrolling");
    }
    const scrolledPaneCurrentPosition = scrolledPane.getScrollPosition();
    const scrolledFromInitial = {
      scrollTop: scrolledPaneCurrentPosition.scrollTop - scrolledPaneInitialOffset.scrollTop,
      scrollLeft: scrolledPaneCurrentPosition.scrollLeft !== void 0 && scrolledPaneInitialOffset.scrollLeft !== void 0 ? scrolledPaneCurrentPosition.scrollLeft - scrolledPaneInitialOffset.scrollLeft : void 0
    };
    for (const pane of this.u()) {
      if (pane === scrolledPane) {
        continue;
      }
      if (!$6K(pane)) {
        continue;
      }
      const initialOffset = this.a.get(pane);
      if (initialOffset === void 0) {
        throw new Error("Could not find initial offset for pane");
      }
      const currentPanePosition = pane.getScrollPosition();
      const newPaneScrollPosition = {
        scrollTop: initialOffset.scrollTop + scrolledFromInitial.scrollTop,
        scrollLeft: initialOffset.scrollLeft !== void 0 && scrolledFromInitial.scrollLeft !== void 0 ? initialOffset.scrollLeft + scrolledFromInitial.scrollLeft : void 0
      };
      if (currentPanePosition.scrollTop === newPaneScrollPosition.scrollTop && currentPanePosition.scrollLeft === newPaneScrollPosition.scrollLeft) {
        continue;
      }
      pane.setScrollPosition(newPaneScrollPosition);
    }
  }
  u() {
    const panes = [];
    for (const pane of this.h.visibleEditorPanes) {
      if (pane instanceof $_tb) {
        const primaryPane = pane.getPrimaryEditorPane();
        const secondaryPane = pane.getSecondaryEditorPane();
        if (primaryPane) {
          panes.push(primaryPane);
        }
        if (secondaryPane) {
          panes.push(secondaryPane);
        }
        continue;
      }
      panes.push(pane);
    }
    return panes;
  }
  w() {
    this.c.clear();
    this.b.clear();
    this.a.clear();
  }
  // Actions & Commands
  y(active) {
    if (active) {
      if (!this.f.value) {
        const text2 = localize(9532, null);
        const tooltip = localize(9533, null);
        this.f.value = this.j.addEntry({
          name: text2,
          text: text2,
          tooltip,
          ariaLabel: text2,
          command: {
            id: "workbench.action.toggleLockedScrolling",
            title: ""
          },
          kind: "prominent",
          showInAllWindows: true
        }, "status.scrollLockingEnabled", 1, 102);
      }
    } else {
      this.f.clear();
    }
  }
  z() {
    const $this = this;
    this.B($hJ(class extends $gJ {
      constructor() {
        super({
          id: "workbench.action.toggleLockedScrolling",
          title: {
            ...localize2(9537, "Toggle Locked Scrolling Across Editors"),
            mnemonicTitle: localize(9534, null)
          },
          category: $qn.View,
          f1: true,
          metadata: {
            description: localize(9535, null)
          }
        });
      }
      run() {
        $this.toggle();
      }
    }));
    this.B($hJ(class extends $gJ {
      constructor() {
        super({
          id: "workbench.action.holdLockedScrolling",
          title: {
            ...localize2(9538, "Hold Locked Scrolling Across Editors"),
            mnemonicTitle: localize(9536, null)
          },
          category: $qn.View
        });
      }
      run(accessor) {
        const keybindingService = accessor.get($Ty);
        $this.toggle();
        const holdMode = keybindingService.enableKeybindingHoldMode("workbench.action.holdLockedScrolling");
        if (!holdMode) {
          return;
        }
        holdMode.finally(() => {
          $this.toggle();
        });
      }
    }));
  }
  dispose() {
    this.w();
    super.dispose();
  }
};
$plc = __decorate([
  __param(0, $mJ),
  __param(1, $$qb)
], $plc);

// out-build/vs/workbench/contrib/scrollLocking/browser/scrollLocking.contribution.js
$PL(
  $plc.ID,
  $plc,
  4
  /* WorkbenchPhase.Eventually */
);

// out-build/vs/workbench/contrib/inlineCompletions/browser/inlineCompletionLanguageStatusBarContribution.js
var $qlc_1;
var $qlc = class $qlc2 extends $3c {
  static {
    $qlc_1 = this;
  }
  static {
    this.hot = $P3($qlc_1);
  }
  static {
    this.Id = "vs.editor.contrib.inlineCompletionLanguageStatusBarContribution";
  }
  constructor(b, f, g) {
    super();
    this.b = b;
    this.f = f;
    this.g = g;
    this.a = $G9("editor.inlineSuggest.experimentalInlineEditsEnabled", false, this.g);
    const c = $3hb.get(this.b);
    this.B($xd((reader, store) => {
      if (!this.a.read(reader)) {
        return;
      }
      const model = c?.model.read(reader);
      if (!model) {
        return;
      }
      const status = model.status.read(reader);
      const statusMap = {
        loading: { shortLabel: "", label: "Loading", loading: true },
        ghostText: { shortLabel: "$(lightbulb)", label: "Inline Completion available", loading: false },
        inlineEdit: { shortLabel: "$(lightbulb-sparkle)", label: "Inline Edit available", loading: false },
        noSuggestion: { shortLabel: "$(circle-slash)", label: "No inline suggestion available", loading: false }
      };
      store.add(this.f.addStatus({
        accessibilityInfo: void 0,
        busy: statusMap[status].loading,
        command: void 0,
        detail: "Inline Suggestions",
        id: "inlineSuggestions",
        label: { value: statusMap[status].label, shortValue: statusMap[status].shortLabel },
        name: "Inline Suggestions",
        selector: { pattern: model.textModel.uri.fsPath },
        severity: severity_default.Info,
        source: "inlineSuggestions"
      }));
    }));
  }
};
$qlc = $qlc_1 = __decorate([
  __param(1, $FS),
  __param(2, $kl)
], $qlc);

// out-build/vs/workbench/contrib/inlineCompletions/browser/inlineCompletions.contribution.js
$85(
  $qlc.Id,
  $yhb($qlc.hot),
  3
  /* EditorContributionInstantiation.Eventually */
);

// out-build/vs/workbench/contrib/dropOrPasteInto/browser/commands.js
var $rlc = class $rlc2 {
  static {
    this.ID = "workbench.contrib.dropOrPasteInto";
  }
  constructor(a) {
    this.a = a;
    $iab.setConfigureDefaultAction($Zm({
      id: "workbench.action.configurePreferredPasteAction",
      label: localize(6248, null),
      run: () => this.b()
    }));
    $Yfb.setConfigureDefaultAction($Zm({
      id: "workbench.action.configurePreferredDropAction",
      label: localize(6249, null),
      run: () => this.c()
    }));
  }
  b() {
    return this.a.openUserSettings({
      jsonEditor: true,
      revealSetting: { key: $gab, edit: true }
    });
  }
  c() {
    return this.a.openUserSettings({
      jsonEditor: true,
      revealSetting: { key: $Vfb, edit: true }
    });
  }
};
$rlc = __decorate([
  __param(0, $TK)
], $rlc);

// out-build/vs/workbench/contrib/dropOrPasteInto/browser/configurationSchema.js
var dropEnumValues = [];
var dropAsPreferenceSchema = {
  type: "array",
  scope: 5,
  description: localize(6250, null),
  default: [],
  items: {
    description: localize(6251, null),
    anyOf: [
      { type: "string" },
      { enum: dropEnumValues }
    ]
  }
};
var pasteEnumValues = [];
var pasteAsPreferenceSchema = {
  type: "array",
  scope: 5,
  description: localize(6252, null),
  default: [],
  items: {
    description: localize(6253, null),
    anyOf: [
      { type: "string" },
      { enum: pasteEnumValues }
    ]
  }
};
var $slc = Object.freeze({
  ...$mab,
  properties: {
    [$gab]: pasteAsPreferenceSchema,
    [$Vfb]: dropAsPreferenceSchema
  }
});
var $tlc = class $tlc2 extends $3c {
  static {
    this.ID = "workbench.contrib.dropOrPasteIntoSchema";
  }
  constructor(keybindingService, f) {
    super();
    this.f = f;
    this.a = this.B(new $ze());
    this.b = [];
    this.c = [];
    this.B(Event2.runAndSubscribe(Event2.debounce(Event2.any(f.documentPasteEditProvider.onDidChange, f.documentPasteEditProvider.onDidChange), () => {
    }, 1e3), () => {
      this.g();
      this.h();
      this.a.fire();
    }));
    keybindingService.registerSchemaContribution({
      getSchemaAdditions: () => this.j(),
      onDidChange: this.a.event
    });
  }
  g() {
    const dropKinds = /* @__PURE__ */ new Map();
    for (const provider of this.f.documentDropEditProvider.allNoModel()) {
      for (const kind of provider.providedDropEditKinds ?? []) {
        dropKinds.set(kind.value, kind);
      }
    }
    this.b = Array.from(dropKinds.values());
    const pasteKinds = /* @__PURE__ */ new Map();
    for (const provider of this.f.documentPasteEditProvider.allNoModel()) {
      for (const kind of provider.providedPasteEditKinds ?? []) {
        pasteKinds.set(kind.value, kind);
      }
    }
    this.c = Array.from(pasteKinds.values());
  }
  h() {
    pasteEnumValues.length = 0;
    for (const codeActionKind of this.c) {
      pasteEnumValues.push(codeActionKind.value);
    }
    dropEnumValues.length = 0;
    for (const codeActionKind of this.b) {
      dropEnumValues.push(codeActionKind.value);
    }
    $Wn.as($Ht.Configuration).notifyConfigurationSchemaUpdated($slc);
  }
  j() {
    return [
      {
        if: {
          required: ["command"],
          properties: {
            "command": { const: $Y_ }
          }
        },
        then: {
          properties: {
            "args": {
              oneOf: [
                {
                  required: ["kind"],
                  properties: {
                    "kind": {
                      anyOf: [
                        { enum: Array.from(this.c.map((x) => x.value)) },
                        { type: "string" }
                      ]
                    }
                  }
                },
                {
                  required: ["preferences"],
                  properties: {
                    "preferences": {
                      type: "array",
                      items: {
                        anyOf: [
                          { enum: Array.from(this.c.map((x) => x.value)) },
                          { type: "string" }
                        ]
                      }
                    }
                  }
                }
              ]
            }
          }
        }
      }
    ];
  }
};
$tlc = __decorate([
  __param(0, $Ty),
  __param(1, $mP)
], $tlc);

// out-build/vs/workbench/contrib/dropOrPasteInto/browser/dropOrPasteInto.contribution.js
$PL(
  $rlc.ID,
  $rlc,
  4
  /* WorkbenchPhase.Eventually */
);
$PL(
  $tlc.ID,
  $tlc,
  4
  /* WorkbenchPhase.Eventually */
);
$Wn.as($Ht.Configuration).registerConfiguration($slc);

// out-build/vs/platform/extensionManagement/common/allowedExtensionsService.js
function isGalleryExtension(extension) {
  return extension.type === "gallery";
}
function isIExtension(extension) {
  return extension.type === 1 || extension.type === 0;
}
var VersionRegex = /^(?<version>\d+\.\d+\.\d+(-.*)?)(@(?<platform>.+))?$/;
var $UY = class $UY2 extends $3c {
  constructor(productService, f) {
    super();
    this.f = f;
    this.c = this.B(new $ze());
    this.onDidChangeAllowedExtensions = this.c.event;
    this.b = productService.extensionPublisherOrgs?.map((p) => p.toLowerCase()) ?? [];
    this.a = this.g();
    this.B(this.f.onDidChangeConfiguration((e) => {
      if (e.affectsConfiguration($CA)) {
        this.a = this.g();
        this.c.fire();
      }
    }));
  }
  g() {
    const value = this.f.getValue($CA);
    if (!$Bg(value) || Array.isArray(value)) {
      return void 0;
    }
    const entries2 = Object.entries(value).map(([key2, value2]) => [key2.toLowerCase(), value2]);
    if (entries2.length === 1 && entries2[0][0] === "*" && entries2[0][1] === true) {
      return void 0;
    }
    return Object.fromEntries(entries2);
  }
  isAllowed(extension) {
    if (!this.a) {
      return true;
    }
    let id2, version2, targetPlatform, prerelease2, publisher, publisherDisplayName;
    if (isGalleryExtension(extension)) {
      id2 = extension.identifier.id.toLowerCase();
      version2 = extension.version;
      prerelease2 = extension.properties.isPreReleaseVersion;
      publisher = extension.publisher.toLowerCase();
      publisherDisplayName = extension.publisherDisplayName.toLowerCase();
      targetPlatform = extension.properties.targetPlatform;
    } else if (isIExtension(extension)) {
      id2 = extension.identifier.id.toLowerCase();
      version2 = extension.manifest.version;
      prerelease2 = extension.preRelease;
      publisher = extension.manifest.publisher.toLowerCase();
      publisherDisplayName = extension.publisherDisplayName?.toLowerCase();
      targetPlatform = extension.targetPlatform;
    } else {
      id2 = extension.id.toLowerCase();
      version2 = extension.version ?? "*";
      targetPlatform = extension.targetPlatform ?? "universal";
      prerelease2 = extension.prerelease ?? false;
      publisher = extension.id.substring(0, extension.id.indexOf(".")).toLowerCase();
      publisherDisplayName = extension.publisherDisplayName?.toLowerCase();
    }
    const settingsCommandLink = URI.parse(`command:workbench.action.openSettings?${encodeURIComponent(JSON.stringify({ query: `@id:${$CA}` }))}`).toString();
    const extensionValue = this.a[id2];
    const extensionReason = new $bm(localize(1815, null, settingsCommandLink));
    if (!$Gg(extensionValue)) {
      if ($Fg(extensionValue)) {
        return extensionValue ? true : extensionReason;
      }
      if (extensionValue === "stable" && prerelease2) {
        return new $bm(localize(1816, null, settingsCommandLink));
      }
      if (version2 !== "*" && Array.isArray(extensionValue) && !extensionValue.some((v) => {
        const match = VersionRegex.exec(v);
        if (match && match.groups) {
          const { platform: p, version: v2 } = match.groups;
          if (v2 !== version2) {
            return false;
          }
          if (targetPlatform !== "universal" && p && targetPlatform !== p) {
            return false;
          }
          return true;
        }
        return false;
      })) {
        return new $bm(localize(1817, null, version2, settingsCommandLink));
      }
      return true;
    }
    const publisherKey = publisherDisplayName && this.b.includes(publisherDisplayName) ? publisherDisplayName : publisher;
    const publisherValue = this.a[publisherKey];
    if (!$Gg(publisherValue)) {
      if ($Fg(publisherValue)) {
        return publisherValue ? true : new $bm(localize(1818, null, publisherKey, settingsCommandLink));
      }
      if (publisherValue === "stable" && prerelease2) {
        return new $bm(localize(1819, null, publisherKey, settingsCommandLink));
      }
      return true;
    }
    if (this.a["*"] === true) {
      return true;
    }
    return extensionReason;
  }
};
$UY = __decorate([
  __param(0, $Vu),
  __param(1, $kl)
], $UY);

// out-build/vs/workbench/workbench.common.main.js
$SC(
  $$Bb,
  $FYb,
  1
  /* InstantiationType.Delayed */
);
$SC(
  $xA,
  $UY,
  1
  /* InstantiationType.Delayed */
);
$SC(
  $DYb,
  $EYb,
  1
  /* InstantiationType.Delayed */
);
$SC(
  $vA,
  $cWb,
  1
  /* InstantiationType.Delayed */
);
$SC(
  $AM,
  $BM,
  1
  /* InstantiationType.Delayed */
);
$SC(
  $pA,
  $0W,
  1
  /* InstantiationType.Delayed */
);
$SC(
  $40,
  $1Xb,
  1
  /* InstantiationType.Delayed */
);
$SC(
  $Deb,
  $Eeb,
  1
  /* InstantiationType.Delayed */
);
$SC(
  $I0,
  $xYb,
  0
  /* InstantiationType.Eager */
);
$SC(
  $V6,
  $yYb,
  1
  /* InstantiationType.Delayed */
);
$SC(
  $DE,
  $AYb,
  1
  /* InstantiationType.Delayed */
);
$SC(
  $on,
  $bUb,
  1
  /* InstantiationType.Delayed */
);
$SC(
  $zG,
  $BYb,
  1
  /* InstantiationType.Delayed */
);
$SC(
  $6W,
  $eZ,
  1
  /* InstantiationType.Delayed */
);
$SC(
  $O4,
  $CYb,
  1
  /* InstantiationType.Delayed */
);

// out-build/vs/workbench/browser/parts/dialogs/dialogHandler.js
var $ulc_1;
var $ulc = class $ulc2 extends $Zv {
  static {
    $ulc_1 = this;
  }
  static {
    this.g = [
      "copy",
      "cut",
      "editor.action.selectAll",
      "editor.action.clipboardCopyAction",
      "editor.action.clipboardCutAction",
      "editor.action.clipboardPasteAction"
    ];
  }
  constructor(i2, j, k, l, m, n) {
    super();
    this.i = i2;
    this.j = j;
    this.k = k;
    this.l = l;
    this.m = m;
    this.n = n;
    this.h = this.l.createInstance($Q_, {});
  }
  async prompt(prompt) {
    this.i.trace("DialogService#prompt", prompt.message);
    const buttons = this.b(prompt);
    const { button, checkboxChecked } = await this.o(prompt.type, prompt.message, buttons, prompt.detail, prompt.cancelButton ? buttons.length - 1 : -1, prompt.checkbox, void 0, typeof prompt?.custom === "object" ? prompt.custom : void 0);
    return this.f(prompt, button, checkboxChecked);
  }
  async confirm(confirmation) {
    this.i.trace("DialogService#confirm", confirmation.message);
    const buttons = this.a(confirmation);
    const { button, checkboxChecked } = await this.o(confirmation.type ?? "question", confirmation.message, buttons, confirmation.detail, buttons.length - 1, confirmation.checkbox, void 0, typeof confirmation?.custom === "object" ? confirmation.custom : void 0);
    return { confirmed: button === 0, checkboxChecked };
  }
  async input(input) {
    this.i.trace("DialogService#input", input.message);
    const buttons = this.c(input);
    const { button, checkboxChecked, values } = await this.o(input.type ?? "question", input.message, buttons, input.detail, buttons.length - 1, input?.checkbox, input.inputs, typeof input.custom === "object" ? input.custom : void 0);
    return { confirmed: button === 0, checkboxChecked, values };
  }
  async about() {
    const detailString = (useAgo) => {
      return localize(3103, null, this.m.version || "Unknown", this.m.commit || "Unknown", this.m.date ? `${this.m.date}${useAgo ? " (" + $Qu(new Date(this.m.date), true) + ")" : ""}` : "Unknown", navigator.userAgent);
    };
    const detail2 = detailString(true);
    const detailToCopy = detailString(false);
    const { button } = await this.o(severity_default.Info, this.m.nameLong, [
      localize(3104, null),
      localize(3105, null)
    ], detail2, 1);
    if (button === 0) {
      this.n.writeText(detailToCopy);
    }
  }
  async o(type, message, buttons, detail2, cancelId, checkbox, inputs, customOptions, cancellationToken) {
    const dialogDisposables = new $2c();
    const renderBody = customOptions ? (parent) => {
      parent.classList.add(...customOptions.classes || []);
      customOptions.markdownDetails?.forEach((markdownDetail) => {
        const result2 = this.h.render(markdownDetail.markdown);
        parent.appendChild(result2.element);
        result2.element.classList.add(...markdownDetail.classes || []);
        dialogDisposables.add(result2);
      });
    } : void 0;
    const dialog = new $K2(this.j.activeContainer, message, buttons, {
      detail: detail2,
      cancelId,
      type: this.e(type),
      keyEventProcessor: (event) => {
        const resolved = this.k.softDispatch(event, this.j.activeContainer);
        if (resolved.kind === 2 && resolved.commandId) {
          if ($ulc_1.g.indexOf(resolved.commandId) === -1) {
            $9j.stop(event, true);
          }
        }
      },
      renderBody,
      icon: customOptions?.icon,
      disableCloseAction: customOptions?.disableCloseAction,
      closeOnLinkClick: customOptions?.closeOnLinkClick,
      buttonDetails: customOptions?.buttonDetails,
      checkboxLabel: checkbox?.label,
      checkboxChecked: checkbox?.checked,
      inputs,
      buttonStyles: $q$,
      checkboxStyles: $x$,
      inputBoxStyles: $B$,
      dialogStyles: $z$
    });
    dialogDisposables.add(dialog);
    const result = await dialog.show();
    dialogDisposables.dispose();
    return result;
  }
};
$ulc = $ulc_1 = __decorate([
  __param(0, $wn),
  __param(1, $Ulb),
  __param(2, $Ty),
  __param(3, $Pk),
  __param(4, $Vu),
  __param(5, $30)
], $ulc);

// out-build/vs/workbench/browser/parts/dialogs/dialog.web.contribution.js
var $vlc = class $vlc2 extends $3c {
  static {
    this.ID = "workbench.contrib.dialogHandler";
  }
  constructor(f, logService, layoutService, keybindingService, instantiationService, productService, clipboardService) {
    super();
    this.f = f;
    this.b = new $sf(() => new $ulc(logService, layoutService, keybindingService, instantiationService, productService, clipboardService));
    this.a = this.f.model;
    this.B(this.a.onWillShowDialog(() => {
      if (!this.c) {
        this.g();
      }
    }));
    this.g();
  }
  async g() {
    while (this.a.dialogs.length) {
      this.c = this.a.dialogs[0];
      let result = void 0;
      try {
        if (this.c.args.confirmArgs) {
          const args2 = this.c.args.confirmArgs;
          result = await this.b.value.confirm(args2.confirmation);
        } else if (this.c.args.inputArgs) {
          const args2 = this.c.args.inputArgs;
          result = await this.b.value.input(args2.input);
        } else if (this.c.args.promptArgs) {
          const args2 = this.c.args.promptArgs;
          result = await this.b.value.prompt(args2.prompt);
        } else {
          await this.b.value.about();
        }
      } catch (error) {
        result = error;
      }
      this.c.close(result);
      this.c = void 0;
    }
  }
};
$vlc = __decorate([
  __param(0, $Yv),
  __param(1, $wn),
  __param(2, $Ulb),
  __param(3, $Ty),
  __param(4, $Pk),
  __param(5, $Vu),
  __param(6, $30)
], $vlc);
$PL(
  $vlc.ID,
  $vlc,
  1
  /* WorkbenchPhase.BlockStartup */
);

// out-build/vs/workbench/browser/style.js
$ms((theme, collector) => {
  const workbenchBackground = $4lb(theme);
  collector.addRule(`.monaco-workbench { background-color: ${workbenchBackground}; }`);
  const windowSelectionBackground = theme.getColor($mo);
  if (windowSelectionBackground) {
    collector.addRule(`.monaco-workbench ::selection { background-color: ${windowSelectionBackground}; }`);
  }
  if ($r) {
    const titleBackground = theme.getColor($6nb);
    if (titleBackground) {
      const metaElementId = "monaco-workbench-meta-theme-color";
      let metaElement = $Y.document.getElementById(metaElementId);
      if (!metaElement) {
        metaElement = $Sj();
        metaElement.name = "theme-color";
        metaElement.id = metaElementId;
      }
      metaElement.content = titleBackground.toString();
    }
  }
  if ($Xe) {
    collector.addRule(`
			body.web {
				touch-action: none;
			}
			.monaco-workbench .monaco-editor .view-lines {
				user-select: text;
				-webkit-user-select: text;
			}
		`);
  }
  if ($u && $2e()) {
    collector.addRule(`body { background-color: ${workbenchBackground}; }`);
  }
});

// out-build/vs/workbench/browser/parts/notifications/notificationsTelemetry.js
function $wlc(message, source, silent) {
  return {
    id: $Xi(message.toString()).toString(),
    silent,
    source: source || "core"
  };
}
var $xlc = class $xlc2 extends $3c {
  constructor(a, b) {
    super();
    this.a = a;
    this.b = b;
    this.c();
  }
  c() {
    this.B(this.b.onDidAddNotification((notification) => {
      const source = notification.source && typeof notification.source !== "string" ? notification.source.id : notification.source;
      this.a.publicLog2("notification:show", $wlc(notification.message, source, notification.priority === NotificationPriority.SILENT));
    }));
    this.B(this.b.onDidRemoveNotification((notification) => {
      const source = notification.source && typeof notification.source !== "string" ? notification.source.id : notification.source;
      this.a.publicLog2("notification:close", $wlc(notification.message, source, notification.priority === NotificationPriority.SILENT));
    }));
  }
};
$xlc = __decorate([
  __param(0, $zv),
  __param(1, $PJ)
], $xlc);

// out-build/vs/workbench/browser/parts/notifications/notificationsCommands.js
var $ylc = "notifications.showList";
var $zlc = "notifications.hideList";
var TOGGLE_NOTIFICATIONS_CENTER = "notifications.toggleList";
var $Alc = "notifications.hideToasts";
var FOCUS_NOTIFICATION_TOAST = "notifications.focusToasts";
var FOCUS_NEXT_NOTIFICATION_TOAST = "notifications.focusNextToast";
var FOCUS_PREVIOUS_NOTIFICATION_TOAST = "notifications.focusPreviousToast";
var FOCUS_FIRST_NOTIFICATION_TOAST = "notifications.focusFirstToast";
var FOCUS_LAST_NOTIFICATION_TOAST = "notifications.focusLastToast";
var $Blc = "notification.collapse";
var $Clc = "notification.expand";
var $Dlc = "notification.acceptPrimaryAction";
var TOGGLE_NOTIFICATION = "notification.toggle";
var $Elc = "notification.clear";
var $Flc = "notifications.clearAll";
var $Glc = "notifications.toggleDoNotDisturbMode";
var $Hlc = "notifications.toggleDoNotDisturbModeBySource";
function $Ilc(listService, context) {
  if ($mWb(context)) {
    return context;
  }
  const list2 = listService.lastFocusedList;
  if (list2 instanceof $Web) {
    let element = list2.getFocusedElements()[0];
    if (!$mWb(element)) {
      if (list2.isDOMFocused()) {
        element = list2.element(0);
      }
    }
    if ($mWb(element)) {
      return element;
    }
  }
  return void 0;
}
function $Jlc(center, toasts, model) {
  $0I.registerCommandAndKeybindingRule({
    id: $ylc,
    weight: 200,
    primary: $$e(
      2048 | 41,
      2048 | 1024 | 44
      /* KeyCode.KeyN */
    ),
    handler: () => {
      toasts.hide();
      center.show();
    }
  });
  $0I.registerCommandAndKeybindingRule({
    id: $zlc,
    weight: 200 + 50,
    when: $$pb,
    primary: 9,
    handler: (accessor) => {
      const telemetryService = accessor.get($zv);
      for (const notification of model.notifications) {
        if (notification.visible) {
          telemetryService.publicLog2("notification:hide", $wlc(notification.message.original, notification.sourceId, notification.priority === NotificationPriority.SILENT));
        }
      }
      center.hide();
    }
  });
  $tn.registerCommand(TOGGLE_NOTIFICATIONS_CENTER, () => {
    if (center.isVisible) {
      center.hide();
    } else {
      toasts.hide();
      center.show();
    }
  });
  $0I.registerCommandAndKeybindingRule({
    id: $Elc,
    weight: 200,
    when: $0pb,
    primary: 20,
    mac: {
      primary: 2048 | 1
      /* KeyCode.Backspace */
    },
    handler: (accessor, args2) => {
      const accessibilitySignalService = accessor.get($I9);
      const notification = $Ilc(accessor.get($Deb), args2);
      if (notification && !notification.hasProgress) {
        notification.close();
        accessibilitySignalService.playSignal($N9.clear);
      }
    }
  });
  $0I.registerCommandAndKeybindingRule({
    id: $Clc,
    weight: 200,
    when: $0pb,
    primary: 17,
    handler: (accessor, args2) => {
      const notification = $Ilc(accessor.get($Deb), args2);
      notification?.expand();
    }
  });
  $0I.registerCommandAndKeybindingRule({
    id: $Dlc,
    weight: 200,
    when: $7m.or($0pb, $_pb),
    primary: 2048 | 1024 | 31,
    handler: (accessor) => {
      const actionRunner = accessor.get($Pk).createInstance($Klc);
      const notification = $Ilc(accessor.get($Deb)) || model.notifications.at(0);
      if (!notification) {
        return;
      }
      const primaryAction = notification.actions?.primary ? notification.actions.primary.at(0) : void 0;
      if (!primaryAction) {
        return;
      }
      actionRunner.run(primaryAction, notification);
      notification.close();
    }
  });
  $0I.registerCommandAndKeybindingRule({
    id: $Blc,
    weight: 200,
    when: $0pb,
    primary: 15,
    handler: (accessor, args2) => {
      const notification = $Ilc(accessor.get($Deb), args2);
      notification?.collapse();
    }
  });
  $0I.registerCommandAndKeybindingRule({
    id: TOGGLE_NOTIFICATION,
    weight: 200,
    when: $0pb,
    primary: 10,
    secondary: [
      3
      /* KeyCode.Enter */
    ],
    handler: (accessor) => {
      const notification = $Ilc(accessor.get($Deb));
      notification?.toggle();
    }
  });
  $tn.registerCommand($Alc, (accessor) => {
    const telemetryService = accessor.get($zv);
    for (const notification of model.notifications) {
      if (notification.visible) {
        telemetryService.publicLog2("notification:hide", $wlc(notification.message.original, notification.sourceId, notification.priority === NotificationPriority.SILENT));
      }
    }
    toasts.hide();
  });
  $0I.registerKeybindingRule({
    id: $Alc,
    weight: 200 - 50,
    // lower when not focused (e.g. let editor suggest win over this command)
    when: $_pb,
    primary: 9
    /* KeyCode.Escape */
  });
  $0I.registerKeybindingRule({
    id: $Alc,
    weight: 200 + 100,
    // higher when focused
    when: $7m.and($_pb, $0pb),
    primary: 9
    /* KeyCode.Escape */
  });
  $tn.registerCommand(FOCUS_NOTIFICATION_TOAST, () => toasts.focus());
  $0I.registerCommandAndKeybindingRule({
    id: FOCUS_NEXT_NOTIFICATION_TOAST,
    weight: 200,
    when: $7m.and($0pb, $_pb),
    primary: 18,
    handler: () => {
      toasts.focusNext();
    }
  });
  $0I.registerCommandAndKeybindingRule({
    id: FOCUS_PREVIOUS_NOTIFICATION_TOAST,
    weight: 200,
    when: $7m.and($0pb, $_pb),
    primary: 16,
    handler: () => {
      toasts.focusPrevious();
    }
  });
  $0I.registerCommandAndKeybindingRule({
    id: FOCUS_FIRST_NOTIFICATION_TOAST,
    weight: 200,
    when: $7m.and($0pb, $_pb),
    primary: 11,
    secondary: [
      14
      /* KeyCode.Home */
    ],
    handler: () => {
      toasts.focusFirst();
    }
  });
  $0I.registerCommandAndKeybindingRule({
    id: FOCUS_LAST_NOTIFICATION_TOAST,
    weight: 200,
    when: $7m.and($0pb, $_pb),
    primary: 12,
    secondary: [
      13
      /* KeyCode.End */
    ],
    handler: () => {
      toasts.focusLast();
    }
  });
  $tn.registerCommand($Flc, () => center.clearAll());
  $tn.registerCommand($Glc, (accessor) => {
    const notificationService = accessor.get($PJ);
    notificationService.setFilter(notificationService.getFilter() === NotificationsFilter.ERROR ? NotificationsFilter.OFF : NotificationsFilter.ERROR);
  });
  $tn.registerCommand($Hlc, (accessor) => {
    const notificationService = accessor.get($PJ);
    const quickInputService = accessor.get($1M);
    const sortedFilters = notificationService.getFilters().sort((a, b) => a.label.localeCompare(b.label));
    const disposables = new $2c();
    const picker = disposables.add(quickInputService.createQuickPick());
    picker.items = sortedFilters.map((source) => ({
      id: source.id,
      label: source.label,
      tooltip: `${source.label} (${source.id})`,
      filter: source.filter
    }));
    picker.canSelectMany = true;
    picker.placeholder = localize(3646, null);
    picker.selectedItems = picker.items.filter((item) => item.filter === NotificationsFilter.OFF);
    picker.show();
    disposables.add(picker.onDidAccept(async () => {
      for (const item of picker.items) {
        notificationService.setFilter({
          id: item.id,
          label: item.label,
          filter: picker.selectedItems.includes(item) ? NotificationsFilter.OFF : NotificationsFilter.ERROR
        });
      }
      picker.hide();
    }));
    disposables.add(picker.onDidHide(() => disposables.dispose()));
  });
  const category8 = localize2(3647, "Notifications");
  $dJ.appendMenuItem($bJ.CommandPalette, { command: { id: $ylc, title: localize2(3648, "Show Notifications"), category: category8 } });
  $dJ.appendMenuItem($bJ.CommandPalette, { command: { id: $zlc, title: localize2(3649, "Hide Notifications"), category: category8 }, when: $$pb });
  $dJ.appendMenuItem($bJ.CommandPalette, { command: { id: $Flc, title: localize2(3650, "Clear All Notifications"), category: category8 } });
  $dJ.appendMenuItem($bJ.CommandPalette, { command: { id: $Dlc, title: localize2(3651, "Accept Notification Primary Action"), category: category8 } });
  $dJ.appendMenuItem($bJ.CommandPalette, { command: { id: $Glc, title: localize2(3652, "Toggle Do Not Disturb Mode"), category: category8 } });
  $dJ.appendMenuItem($bJ.CommandPalette, { command: { id: $Hlc, title: localize2(3653, "Toggle Do Not Disturb Mode By Source..."), category: category8 } });
  $dJ.appendMenuItem($bJ.CommandPalette, { command: { id: FOCUS_NOTIFICATION_TOAST, title: localize2(3654, "Focus Notification Toast"), category: category8 }, when: $_pb });
}
var $Klc = class $Klc2 extends $Vm {
  constructor(c, g) {
    super();
    this.c = c;
    this.g = g;
  }
  async u(action, context) {
    this.c.publicLog2("workbenchActionExecuted", { id: action.id, from: "message" });
    if ($mWb(context)) {
      this.c.publicLog2("notification:actionExecuted", {
        id: $Xi(context.message.original.toString()).toString(),
        actionLabel: action.label,
        source: context.sourceId || "core",
        silent: context.priority === NotificationPriority.SILENT
      });
    }
    try {
      await super.u(action, context);
    } catch (error) {
      this.g.error(error);
    }
  }
};
$Klc = __decorate([
  __param(0, $zv),
  __param(1, $PJ)
], $Klc);

// out-build/vs/workbench/browser/parts/notifications/notificationsActions.js
var clearIcon = $9r("notifications-clear", $6l.close, localize(3619, null));
var clearAllIcon = $9r("notifications-clear-all", $6l.clearAll, localize(3620, null));
var hideIcon = $9r("notifications-hide", $6l.chevronDown, localize(3621, null));
var expandIcon = $9r("notifications-expand", $6l.chevronUp, localize(3622, null));
var collapseIcon2 = $9r("notifications-collapse", $6l.chevronDown, localize(3623, null));
var configureIcon = $9r("notifications-configure", $6l.gear, localize(3624, null));
var doNotDisturbIcon = $9r("notifications-do-not-disturb", $6l.bellSlash, localize(3625, null));
var $Llc = class $Llc2 extends $Um {
  static {
    this.ID = $Elc;
  }
  static {
    this.LABEL = localize(3626, null);
  }
  constructor(id2, label3, a) {
    super(id2, label3, ThemeIcon.asClassName(clearIcon));
    this.a = a;
  }
  async run(notification) {
    this.a.executeCommand($Elc, notification);
  }
};
$Llc = __decorate([
  __param(2, $sn)
], $Llc);
var $Mlc = class $Mlc2 extends $Um {
  static {
    this.ID = $Flc;
  }
  static {
    this.LABEL = localize(3627, null);
  }
  constructor(id2, label3, a) {
    super(id2, label3, ThemeIcon.asClassName(clearAllIcon));
    this.a = a;
  }
  async run() {
    this.a.executeCommand($Flc);
  }
};
$Mlc = __decorate([
  __param(2, $sn)
], $Mlc);
var $Nlc = class $Nlc2 extends $Um {
  static {
    this.ID = $Glc;
  }
  static {
    this.LABEL = localize(3628, null);
  }
  constructor(id2, label3, a) {
    super(id2, label3, ThemeIcon.asClassName(doNotDisturbIcon));
    this.a = a;
  }
  async run() {
    this.a.executeCommand($Glc);
  }
};
$Nlc = __decorate([
  __param(2, $sn)
], $Nlc);
var $Olc = class $Olc2 extends $Um {
  static {
    this.ID = $Hlc;
  }
  static {
    this.LABEL = localize(3629, null);
  }
  constructor(id2, label3, a) {
    super(id2, label3);
    this.a = a;
  }
  async run() {
    this.a.executeCommand($Hlc);
  }
};
$Olc = __decorate([
  __param(2, $sn)
], $Olc);
var $Plc = class extends $Um {
  static {
    this.ID = "workbench.action.configureDoNotDisturbMode";
  }
  static {
    this.LABEL = localize(3630, null);
  }
  constructor(id2, label3) {
    super(id2, label3, ThemeIcon.asClassName(doNotDisturbIcon));
  }
};
var $Qlc = class $Qlc2 extends $Um {
  static {
    this.ID = $zlc;
  }
  static {
    this.LABEL = localize(3631, null);
  }
  constructor(id2, label3, a) {
    super(id2, label3, ThemeIcon.asClassName(hideIcon));
    this.a = a;
  }
  async run() {
    this.a.executeCommand($zlc);
  }
};
$Qlc = __decorate([
  __param(2, $sn)
], $Qlc);
var $Rlc = class $Rlc2 extends $Um {
  static {
    this.ID = $Clc;
  }
  static {
    this.LABEL = localize(3632, null);
  }
  constructor(id2, label3, a) {
    super(id2, label3, ThemeIcon.asClassName(expandIcon));
    this.a = a;
  }
  async run(notification) {
    this.a.executeCommand($Clc, notification);
  }
};
$Rlc = __decorate([
  __param(2, $sn)
], $Rlc);
var $Slc = class $Slc2 extends $Um {
  static {
    this.ID = $Blc;
  }
  static {
    this.LABEL = localize(3633, null);
  }
  constructor(id2, label3, a) {
    super(id2, label3, ThemeIcon.asClassName(collapseIcon2));
    this.a = a;
  }
  async run(notification) {
    this.a.executeCommand($Blc, notification);
  }
};
$Slc = __decorate([
  __param(2, $sn)
], $Slc);
var $Tlc = class extends $Um {
  static {
    this.ID = "workbench.action.configureNotification";
  }
  static {
    this.LABEL = localize(3634, null);
  }
  constructor(id2, label3, notification) {
    super(id2, label3, ThemeIcon.asClassName(configureIcon));
    this.notification = notification;
  }
};
var $Ulc = class $Ulc2 extends $Um {
  static {
    this.ID = "workbench.action.copyNotificationMessage";
  }
  static {
    this.LABEL = localize(3635, null);
  }
  constructor(id2, label3, a) {
    super(id2, label3);
    this.a = a;
  }
  run(notification) {
    return this.a.writeText(notification.message.raw);
  }
};
$Ulc = __decorate([
  __param(2, $30)
], $Ulc);

// out-build/vs/workbench/browser/parts/notifications/notificationsViewer.js
var $Wlc_1;
var $Xlc_1;
var $Vlc = class _$Vlc {
  static {
    this.a = 42;
  }
  static {
    this.b = 22;
  }
  constructor(container2) {
    this.c = this.d(container2);
  }
  d(container2) {
    const offsetHelper = document.createElement("div");
    offsetHelper.classList.add("notification-offset-helper");
    container2.appendChild(offsetHelper);
    return offsetHelper;
  }
  getHeight(notification) {
    if (!notification.expanded) {
      return _$Vlc.a;
    }
    let expandedHeight = _$Vlc.a;
    const preferredMessageHeight = this.f(notification);
    const messageOverflows = _$Vlc.b < preferredMessageHeight;
    if (messageOverflows) {
      const overflow = preferredMessageHeight - _$Vlc.b;
      expandedHeight += overflow;
    }
    if (notification.source || $Qb(notification.actions && notification.actions.primary)) {
      expandedHeight += _$Vlc.a;
    }
    if (expandedHeight === _$Vlc.a) {
      notification.collapse(
        true
        /* skip events, no change in height */
      );
    }
    return expandedHeight;
  }
  f(notification) {
    let actions = 0;
    if (!notification.hasProgress) {
      actions++;
    }
    if (notification.canCollapse) {
      actions++;
    }
    if ($Qb(notification.actions && notification.actions.secondary)) {
      actions++;
    }
    this.c.style.width = `${450 - (10 + 30 + actions * 30 - Math.max(actions - 1, 0) * 4)}px`;
    const renderedMessage = NotificationMessageRenderer.render(notification.message);
    this.c.appendChild(renderedMessage);
    const preferredHeight = Math.max(this.c.offsetHeight, this.c.scrollHeight);
    $$i(this.c);
    return preferredHeight;
  }
  getTemplateId(element) {
    if (element instanceof $oWb) {
      return $Wlc.TEMPLATE_ID;
    }
    throw new Error("unknown element type: " + element);
  }
};
var NotificationMessageRenderer = class {
  static render(message, actionHandler) {
    const messageContainer = document.createElement("span");
    for (const node of message.linkedText.nodes) {
      if (typeof node === "string") {
        messageContainer.appendChild(document.createTextNode(node));
      } else {
        let title = node.title;
        if (!title && node.href.startsWith("command:")) {
          title = localize(3677, null, node.href.substr("command:".length));
        } else if (!title) {
          title = node.href;
        }
        const anchor = $("a", { href: node.href, title, tabIndex: 0 }, node.label);
        if (actionHandler) {
          const handleOpen = (e) => {
            if ($8j(e)) {
              $9j.stop(e, true);
            }
            actionHandler.callback(node.href);
          };
          const onClick2 = actionHandler.toDispose.add(new $9Z(anchor, $7j.CLICK)).event;
          const onKeydown = actionHandler.toDispose.add(new $9Z(anchor, $7j.KEY_DOWN)).event;
          const onSpaceOrEnter = Event2.chain(onKeydown, ($149) => $149.filter((e) => {
            const event = new $if(e);
            return event.equals(
              10
              /* KeyCode.Space */
            ) || event.equals(
              3
              /* KeyCode.Enter */
            );
          }));
          actionHandler.toDispose.add($mZ.addTarget(anchor));
          const onTap = actionHandler.toDispose.add(new $9Z(anchor, EventType.Tap)).event;
          Event2.any(onClick2, onTap, onSpaceOrEnter)(handleOpen, null, actionHandler.toDispose);
        }
        messageContainer.appendChild(anchor);
      }
    }
    return messageContainer;
  }
};
var $Wlc = class $Wlc2 {
  static {
    $Wlc_1 = this;
  }
  static {
    this.TEMPLATE_ID = "notification";
  }
  constructor(a, b, c, d) {
    this.a = a;
    this.b = b;
    this.c = c;
    this.d = d;
  }
  get templateId() {
    return $Wlc_1.TEMPLATE_ID;
  }
  renderTemplate(container2) {
    const data = /* @__PURE__ */ Object.create(null);
    data.toDispose = new $2c();
    data.container = document.createElement("div");
    data.container.classList.add("notification-list-item");
    data.mainRow = document.createElement("div");
    data.mainRow.classList.add("notification-list-item-main-row");
    data.icon = document.createElement("div");
    data.icon.classList.add("notification-list-item-icon", "codicon");
    data.message = document.createElement("div");
    data.message.classList.add("notification-list-item-message");
    const that = this;
    const toolbarContainer = document.createElement("div");
    toolbarContainer.classList.add("notification-list-item-toolbar-container");
    data.toolbar = new $LZ(toolbarContainer, {
      ariaLabel: localize(3678, null),
      actionViewItemProvider: (action, options3) => {
        if (action instanceof $Tlc) {
          return data.toDispose.add(new $L2(action, {
            getActions() {
              const actions = [];
              const source = { id: action.notification.sourceId, label: action.notification.source };
              if ($QJ(source)) {
                const isSourceFiltered = that.d.getFilter(source) === NotificationsFilter.ERROR;
                actions.push($Zm({
                  id: source.id,
                  label: isSourceFiltered ? localize(3679, null, source.label) : localize(3680, null, source.label),
                  run: () => that.d.setFilter({ ...source, filter: isSourceFiltered ? NotificationsFilter.OFF : NotificationsFilter.ERROR })
                }));
                if (action.notification.actions?.secondary?.length) {
                  actions.push(new $Wm());
                }
              }
              if (Array.isArray(action.notification.actions?.secondary)) {
                actions.push(...action.notification.actions.secondary);
              }
              return actions;
            }
          }, this.b, {
            ...options3,
            actionRunner: this.a,
            classNames: action.class
          }));
        }
        return void 0;
      },
      actionRunner: this.a
    });
    data.toDispose.add(data.toolbar);
    data.detailsRow = document.createElement("div");
    data.detailsRow.classList.add("notification-list-item-details-row");
    data.source = document.createElement("div");
    data.source.classList.add("notification-list-item-source");
    data.buttonsContainer = document.createElement("div");
    data.buttonsContainer.classList.add("notification-list-item-buttons-container");
    container2.appendChild(data.container);
    data.container.appendChild(data.detailsRow);
    data.detailsRow.appendChild(data.source);
    data.detailsRow.appendChild(data.buttonsContainer);
    data.container.appendChild(data.mainRow);
    data.mainRow.appendChild(data.icon);
    data.mainRow.appendChild(data.message);
    data.mainRow.appendChild(toolbarContainer);
    data.progress = new $02(container2, $s$);
    data.toDispose.add(data.progress);
    data.renderer = this.c.createInstance($Xlc, data, this.a);
    data.toDispose.add(data.renderer);
    return data;
  }
  renderElement(notification, index, data) {
    data.renderer.setInput(notification);
  }
  disposeTemplate(templateData) {
    $Xc(templateData.toDispose);
  }
};
$Wlc = $Wlc_1 = __decorate([
  __param(1, $50),
  __param(2, $Pk),
  __param(3, $PJ)
], $Wlc);
var $Xlc = class $Xlc2 extends $3c {
  static {
    $Xlc_1 = this;
  }
  static {
    this.f = [Severity2.Info, Severity2.Warning, Severity2.Error];
  }
  constructor(h3, j, m, n, r2, s, t) {
    super();
    this.h = h3;
    this.j = j;
    this.m = m;
    this.n = n;
    this.r = r2;
    this.s = s;
    this.t = t;
    this.g = this.B(new $2c());
    if (!$Xlc_1.a) {
      $Xlc_1.a = n.createInstance($Llc, $Llc.ID, $Llc.LABEL);
      $Xlc_1.b = n.createInstance($Rlc, $Rlc.ID, $Rlc.LABEL);
      $Xlc_1.c = n.createInstance($Slc, $Slc.ID, $Slc.LABEL);
    }
  }
  setInput(notification) {
    this.g.clear();
    this.u(notification);
  }
  u(notification) {
    this.h.container.classList.toggle("expanded", notification.expanded);
    this.g.add($_i(this.h.container, $7j.MOUSE_UP, (e) => {
      if (e.button === 1) {
        $9j.stop(e, true);
      }
    }));
    this.g.add($_i(this.h.container, $7j.AUXCLICK, (e) => {
      if (!notification.hasProgress && e.button === 1) {
        $9j.stop(e, true);
        notification.close();
      }
    }));
    this.w(notification);
    const messageCustomHover = this.g.add(this.t.setupManagedHover($JZ("mouse"), this.h.message, ""));
    const messageOverflows = this.y(notification, messageCustomHover);
    this.z(notification, messageOverflows);
    const sourceCustomHover = this.g.add(this.t.setupManagedHover($JZ("mouse"), this.h.source, ""));
    this.C(notification, sourceCustomHover);
    this.D(notification);
    this.F(notification);
    this.g.add(notification.onDidChangeContent((event) => {
      switch (event.kind) {
        case 0:
          this.w(notification);
          break;
        case 3:
          this.F(notification);
          break;
        case 1:
          this.y(notification, messageCustomHover);
          break;
      }
    }));
  }
  w(notification) {
    $Xlc_1.f.forEach((severity) => {
      if (notification.severity !== severity) {
        this.h.icon.classList.remove(...ThemeIcon.asClassNameArray(this.G(severity)));
      }
    });
    this.h.icon.classList.add(...ThemeIcon.asClassNameArray(this.G(notification.severity)));
  }
  y(notification, customHover) {
    $$i(this.h.message);
    this.h.message.appendChild(NotificationMessageRenderer.render(notification.message, {
      callback: (link2) => this.m.open(URI.parse(link2), { allowCommands: true }),
      toDispose: this.g
    }));
    const messageOverflows = notification.canCollapse && !notification.expanded && this.h.message.scrollWidth > this.h.message.clientWidth;
    customHover.update(messageOverflows ? this.h.message.textContent + "" : "");
    return messageOverflows;
  }
  z(notification, messageOverflows) {
    const actions = [];
    if ($Qb(notification.actions?.secondary)) {
      const configureNotificationAction = this.n.createInstance($Tlc, $Tlc.ID, $Tlc.LABEL, notification);
      actions.push(configureNotificationAction);
      this.g.add(configureNotificationAction);
    }
    let showExpandCollapseAction = false;
    if (notification.canCollapse) {
      if (notification.expanded) {
        showExpandCollapseAction = true;
      } else if (notification.source) {
        showExpandCollapseAction = true;
      } else if (messageOverflows) {
        showExpandCollapseAction = true;
      }
    }
    if (showExpandCollapseAction) {
      actions.push(notification.expanded ? $Xlc_1.c : $Xlc_1.b);
    }
    if (!notification.hasProgress) {
      actions.push($Xlc_1.a);
    }
    this.h.toolbar.clear();
    this.h.toolbar.context = notification;
    actions.forEach((action) => this.h.toolbar.push(action, { icon: true, label: false, keybinding: this.H(action) }));
  }
  C(notification, sourceCustomHover) {
    if (notification.expanded && notification.source) {
      this.h.source.textContent = localize(3681, null, notification.source);
      sourceCustomHover.update(notification.source);
    } else {
      this.h.source.textContent = "";
      sourceCustomHover.update("");
    }
  }
  D(notification) {
    $$i(this.h.buttonsContainer);
    const primaryActions = notification.actions ? notification.actions.primary : void 0;
    if (notification.expanded && $Qb(primaryActions)) {
      const that = this;
      const actionRunner = new class extends $Vm {
        async u(action) {
          that.j.run(action, notification);
          if (!(action instanceof $pWb) || !action.keepOpen) {
            notification.close();
          }
        }
      }();
      const buttonToolbar = this.g.add(new $n2(this.h.buttonsContainer));
      for (let i2 = 0; i2 < primaryActions.length; i2++) {
        const action = primaryActions[i2];
        const options3 = {
          title: true,
          // assign titles to buttons in case they overflow
          secondary: i2 > 0,
          ...$q$
        };
        const dropdownActions = action instanceof $pWb ? action.menu : void 0;
        const button = this.g.add(dropdownActions ? buttonToolbar.addButtonWithDropdown({
          ...options3,
          contextMenuProvider: this.s,
          actions: dropdownActions,
          actionRunner
        }) : buttonToolbar.addButton(options3));
        button.label = action.label;
        this.g.add(button.onDidClick((e) => {
          if (e) {
            $9j.stop(e, true);
          }
          actionRunner.run(action);
        }));
      }
    }
  }
  F(notification) {
    if (!notification.hasProgress) {
      this.h.progress.stop().hide();
      return;
    }
    const state = notification.progress.state;
    if (state.infinite) {
      this.h.progress.infinite().show();
    } else if (typeof state.total === "number" || typeof state.worked === "number") {
      if (typeof state.total === "number" && !this.h.progress.hasTotal()) {
        this.h.progress.total(state.total);
      }
      if (typeof state.worked === "number") {
        this.h.progress.setWorked(state.worked).show();
      }
    } else {
      this.h.progress.done().hide();
    }
  }
  G(severity) {
    switch (severity) {
      case Severity2.Warning:
        return $6l.warning;
      case Severity2.Error:
        return $6l.error;
    }
    return $6l.info;
  }
  H(action) {
    const keybinding = this.r.lookupKeybinding(action.id);
    return keybinding ? keybinding.getLabel() : null;
  }
};
$Xlc = $Xlc_1 = __decorate([
  __param(2, $O4),
  __param(3, $Pk),
  __param(4, $Ty),
  __param(5, $50),
  __param(6, $5$)
], $Xlc);

// out-build/vs/workbench/browser/parts/notifications/notificationsList.js
var $Ylc = class $Ylc2 extends $3c {
  constructor(h3, j, m, n) {
    super();
    this.h = h3;
    this.j = j;
    this.m = m;
    this.n = n;
    this.f = [];
  }
  show() {
    if (this.g) {
      return;
    }
    if (!this.b) {
      this.r();
    }
    this.g = true;
  }
  r() {
    this.a = document.createElement("div");
    this.a.classList.add("notifications-list-container");
    const actionRunner = this.B(this.m.createInstance($Klc));
    const renderer = this.m.createInstance($Wlc, actionRunner);
    const listDelegate = this.c = new $Vlc(this.a);
    const options3 = this.j;
    const list2 = this.b = this.B(this.m.createInstance($Web, "NotificationsList", this.a, listDelegate, [renderer], {
      ...options3,
      setRowLineHeight: false,
      horizontalScrolling: false,
      overrideStyles: {
        listBackground: $kob
      },
      accessibilityProvider: this.m.createInstance(NotificationAccessibilityProvider, options3)
    }));
    const copyAction = this.B(this.m.createInstance($Ulc, $Ulc.ID, $Ulc.LABEL));
    this.B(list2.onContextMenu((e) => {
      if (!e.element) {
        return;
      }
      this.n.showContextMenu({
        getAnchor: () => e.anchor,
        getActions: () => [copyAction],
        getActionsContext: () => e.element,
        actionRunner
      });
    }));
    this.B(list2.onMouseDblClick((event) => event.element.toggle()));
    const listFocusTracker = this.B($_j(list2.getHTMLElement()));
    this.B(listFocusTracker.onDidBlur(() => {
      if (getWindow(this.a).document.hasFocus()) {
        list2.setFocus([]);
      }
    }));
    $0pb.bindTo(list2.contextKeyService);
    this.B(list2.onDidChangeSelection((e) => {
      if (e.indexes.length > 0) {
        list2.setSelection([]);
      }
    }));
    this.h.appendChild(this.a);
  }
  updateNotificationsList(start, deleteCount, items = []) {
    const [list2, listContainer] = $Lg(this.b, this.a);
    const listHasDOMFocus = $Nj(listContainer);
    const focusedIndex = list2.getFocus()[0];
    const focusedItem = this.f[focusedIndex];
    let focusRelativeTop = null;
    if (typeof focusedIndex === "number") {
      focusRelativeTop = list2.getRelativeTop(focusedIndex);
    }
    this.f.splice(start, deleteCount, ...items);
    list2.splice(start, deleteCount, items);
    list2.layout();
    if (this.f.length === 0) {
      this.hide();
    } else if (typeof focusedIndex === "number") {
      let indexToFocus = 0;
      if (focusedItem) {
        let indexToFocusCandidate = this.f.indexOf(focusedItem);
        if (indexToFocusCandidate === -1) {
          indexToFocusCandidate = focusedIndex - 1;
        }
        if (indexToFocusCandidate < this.f.length && indexToFocusCandidate >= 0) {
          indexToFocus = indexToFocusCandidate;
        }
      }
      if (typeof focusRelativeTop === "number") {
        list2.reveal(indexToFocus, focusRelativeTop);
      }
      list2.setFocus([indexToFocus]);
    }
    if (this.g && listHasDOMFocus) {
      list2.domFocus();
    }
  }
  updateNotificationHeight(item) {
    const index = this.f.indexOf(item);
    if (index === -1) {
      return;
    }
    const [list2, listDelegate] = $Lg(this.b, this.c);
    list2.updateElementHeight(index, listDelegate.getHeight(item));
    list2.layout();
  }
  hide() {
    if (!this.g || !this.b) {
      return;
    }
    this.g = false;
    this.b.splice(0, this.f.length);
    this.f = [];
  }
  focusFirst() {
    if (!this.b) {
      return;
    }
    this.b.focusFirst();
    this.b.domFocus();
  }
  hasFocus() {
    if (!this.a) {
      return false;
    }
    return $Nj(this.a);
  }
  layout(width2, maxHeight) {
    if (this.a && this.b) {
      this.a.style.width = `${width2}px`;
      if (typeof maxHeight === "number") {
        this.b.getHTMLElement().style.maxHeight = `${maxHeight}px`;
      }
      this.b.layout();
    }
  }
  dispose() {
    this.hide();
    super.dispose();
  }
};
$Ylc = __decorate([
  __param(2, $Pk),
  __param(3, $50)
], $Ylc);
var NotificationAccessibilityProvider = class NotificationAccessibilityProvider2 {
  constructor(a, b, c) {
    this.a = a;
    this.b = b;
    this.c = c;
  }
  getAriaLabel(element) {
    let accessibleViewHint;
    const keybinding = this.b.lookupKeybinding("editor.action.accessibleView")?.getAriaLabel();
    if (this.c.getValue("accessibility.verbosity.notification")) {
      accessibleViewHint = keybinding ? localize(3655, null, keybinding) : localize(3656, null);
    }
    if (!element.source) {
      return accessibleViewHint ? localize(3657, null, element.message.raw, accessibleViewHint) : localize(3658, null, element.message.raw);
    }
    return accessibleViewHint ? localize(3659, null, element.message.raw, element.source, accessibleViewHint) : localize(3660, null, element.message.raw, element.source);
  }
  getWidgetAriaLabel() {
    return this.a.widgetAriaLabel ?? localize(3661, null);
  }
  getRole() {
    return "dialog";
  }
};
NotificationAccessibilityProvider = __decorate([
  __param(1, $Ty),
  __param(2, $kl)
], NotificationAccessibilityProvider);

// out-build/vs/workbench/browser/parts/notifications/notificationsCenter.js
var $Zlc_1;
var $Zlc = class $Zlc2 extends $ns {
  static {
    $Zlc_1 = this;
  }
  static {
    this.c = new $rj(450, 400);
  }
  static {
    this.f = 10;
  }
  // maximum number of notification sources to show in configure dropdown
  constructor(F, G, themeService, H, I, J, L, M, N, O, P) {
    super(themeService);
    this.F = F;
    this.G = G;
    this.H = H;
    this.I = I;
    this.J = J;
    this.L = L;
    this.M = M;
    this.N = N;
    this.O = O;
    this.P = P;
    this.g = this.B(new $ze());
    this.onDidChangeVisibility = this.g.event;
    this.y = $$pb.bindTo(this.J);
    this.y = $$pb.bindTo(J);
    this.Q();
  }
  Q() {
    this.B(this.G.onDidChangeNotification((e) => this.X(e)));
    this.B(this.I.onDidLayoutMainContainer((dimension) => this.layout($rj.lift(dimension))));
    this.B(this.N.onDidChangeFilter(() => this.R()));
  }
  R() {
    if (this.N.getFilter() === NotificationsFilter.ERROR) {
      this.hide();
    }
  }
  get isVisible() {
    return !!this.t;
  }
  show() {
    if (this.t) {
      const notificationsList2 = $Kg(this.s);
      notificationsList2.show();
      notificationsList2.focusFirst();
      return;
    }
    if (!this.j) {
      this.U();
    }
    this.S();
    const [notificationsList, notificationsCenterContainer] = $Lg(this.s, this.j);
    this.t = true;
    notificationsCenterContainer.classList.add("visible");
    notificationsList.show();
    this.layout(this.u);
    notificationsList.updateNotificationsList(0, 0, this.G.notifications);
    notificationsList.focusFirst();
    this.updateStyles();
    this.G.notifications.forEach((notification) => notification.updateVisibility(true));
    this.y.set(true);
    this.g.fire();
  }
  S() {
    const [notificationsCenterTitle, clearAllAction] = $Lg(this.r, this.C);
    if (this.G.notifications.length === 0) {
      notificationsCenterTitle.textContent = localize(3639, null);
      clearAllAction.enabled = false;
    } else {
      notificationsCenterTitle.textContent = localize(3640, null);
      clearAllAction.enabled = this.G.notifications.some((notification) => !notification.hasProgress);
    }
  }
  U() {
    this.j = document.createElement("div");
    this.j.classList.add("notifications-center");
    this.m = document.createElement("div");
    this.m.classList.add("notifications-center-header");
    this.j.appendChild(this.m);
    this.r = document.createElement("span");
    this.r.classList.add("notifications-center-header-title");
    this.m.appendChild(this.r);
    const toolbarContainer = document.createElement("div");
    toolbarContainer.classList.add("notifications-center-header-toolbar");
    this.m.appendChild(toolbarContainer);
    const actionRunner = this.B(this.H.createInstance($Klc));
    const that = this;
    const notificationsToolBar = this.B(new $LZ(toolbarContainer, {
      ariaLabel: localize(3641, null),
      actionRunner,
      actionViewItemProvider: (action, options3) => {
        if (action.id === $Plc.ID) {
          return this.B(this.H.createInstance($L2, action, {
            getActions() {
              const actions = [$Zm({
                id: $Nlc.ID,
                label: that.N.getFilter() === NotificationsFilter.OFF ? localize(3642, null) : localize(3643, null),
                run: () => that.N.setFilter(that.N.getFilter() === NotificationsFilter.OFF ? NotificationsFilter.ERROR : NotificationsFilter.OFF)
              })];
              const sortedFilters = that.N.getFilters().sort((a, b) => a.label.localeCompare(b.label));
              for (const source of sortedFilters.slice(0, $Zlc_1.f)) {
                if (actions.length === 1) {
                  actions.push(new $Wm());
                }
                actions.push($Zm({
                  id: `${$Nlc.ID}.${source.id}`,
                  label: source.label,
                  checked: source.filter !== NotificationsFilter.ERROR,
                  run: () => that.N.setFilter({
                    ...source,
                    filter: source.filter === NotificationsFilter.ERROR ? NotificationsFilter.OFF : NotificationsFilter.ERROR
                  })
                }));
              }
              if (sortedFilters.length > $Zlc_1.f) {
                actions.push(new $Wm());
                actions.push(that.B(that.H.createInstance($Olc, $Olc.ID, localize(3644, null))));
              }
              return actions;
            }
          }, this.P, {
            ...options3,
            actionRunner,
            classNames: action.class,
            keybindingProvider: (action2) => this.M.lookupKeybinding(action2.id)
          }));
        }
        return void 0;
      }
    }));
    this.C = this.B(this.H.createInstance($Mlc, $Mlc.ID, $Mlc.LABEL));
    notificationsToolBar.push(this.C, { icon: true, label: false, keybinding: this.W(this.C) });
    this.D = this.B(this.H.createInstance($Plc, $Plc.ID, $Plc.LABEL));
    notificationsToolBar.push(this.D, { icon: true, label: false });
    const hideAllAction = this.B(this.H.createInstance($Qlc, $Qlc.ID, $Qlc.LABEL));
    notificationsToolBar.push(hideAllAction, { icon: true, label: false, keybinding: this.W(hideAllAction) });
    this.s = this.H.createInstance($Ylc, this.j, {
      widgetAriaLabel: localize(3645, null)
    });
    this.F.appendChild(this.j);
  }
  W(action) {
    const keybinding = this.M.lookupKeybinding(action.id);
    return keybinding ? keybinding.getLabel() : null;
  }
  X(e) {
    if (!this.t) {
      return;
    }
    let focusEditor = false;
    const [notificationsList, notificationsCenterContainer] = $Lg(this.s, this.j);
    switch (e.kind) {
      case 0:
        notificationsList.updateNotificationsList(e.index, 0, [e.item]);
        e.item.updateVisibility(true);
        break;
      case 1:
        switch (e.detail) {
          case 2:
            notificationsList.updateNotificationsList(e.index, 1, [e.item]);
            break;
          case 1:
            if (e.item.expanded) {
              notificationsList.updateNotificationHeight(e.item);
            }
            break;
        }
        break;
      case 2:
        notificationsList.updateNotificationsList(e.index, 1, [e.item]);
        break;
      case 3:
        focusEditor = $Nj(notificationsCenterContainer);
        notificationsList.updateNotificationsList(e.index, 1);
        e.item.updateVisibility(false);
        break;
    }
    this.S();
    if (this.G.notifications.length === 0) {
      this.hide();
      if (focusEditor) {
        this.L.activeGroup.focus();
      }
    }
  }
  hide() {
    if (!this.t || !this.j || !this.s) {
      return;
    }
    const focusEditor = $Nj(this.j);
    this.t = false;
    this.j.classList.remove("visible");
    this.s.hide();
    this.G.notifications.forEach((notification) => notification.updateVisibility(false));
    this.y.set(false);
    this.g.fire();
    if (focusEditor) {
      this.L.activeGroup.focus();
    }
  }
  updateStyles() {
    if (this.j && this.m) {
      const widgetShadowColor = this.z($Rp);
      this.j.style.boxShadow = widgetShadowColor ? `0 0 8px 2px ${widgetShadowColor}` : "";
      const borderColor = this.z($hob);
      this.j.style.border = borderColor ? `1px solid ${borderColor}` : "";
      const headerForeground = this.z($mob);
      this.m.style.color = headerForeground ?? "";
      const headerBackground = this.z($nob);
      this.m.style.background = headerBackground ?? "";
    }
  }
  layout(dimension) {
    this.u = dimension;
    if (this.t && this.j) {
      const maxWidth = $Zlc_1.c.width;
      const maxHeight = $Zlc_1.c.height;
      let availableWidth = maxWidth;
      let availableHeight = maxHeight;
      if (this.u) {
        availableWidth = this.u.width;
        availableWidth -= 2 * 8;
        availableHeight = this.u.height - 35;
        if (this.I.isVisible("workbench.parts.statusbar", $Y)) {
          availableHeight -= 22;
        }
        if (this.I.isVisible("workbench.parts.titlebar", $Y)) {
          availableHeight -= 22;
        }
        availableHeight -= 2 * 12;
      }
      const notificationsList = $Kg(this.s);
      notificationsList.layout(Math.min(maxWidth, availableWidth), Math.min(maxHeight, availableHeight));
    }
  }
  clearAll() {
    this.hide();
    for (const notification of [...this.G.notifications]) {
      if (!notification.hasProgress) {
        notification.close();
      }
      this.O.playSignal($N9.clear);
    }
  }
};
$Zlc = $Zlc_1 = __decorate([
  __param(2, $gs),
  __param(3, $Pk),
  __param(4, $Vlb),
  __param(5, $on),
  __param(6, $iJ),
  __param(7, $Ty),
  __param(8, $PJ),
  __param(9, $I9),
  __param(10, $50)
], $Zlc);

// out-build/vs/workbench/browser/parts/notifications/notificationsAlerts.js
var $1lc = class extends $3c {
  constructor(a) {
    super();
    this.a = a;
    for (const notification of a.notifications) {
      this.f(notification);
    }
    this.b();
  }
  b() {
    this.B(this.a.onDidChangeNotification((e) => this.c(e)));
  }
  c(e) {
    if (e.kind === 0) {
      this.f(e.item);
      if (e.item.severity === Severity2.Error) {
        if (e.item.message.original instanceof Error) {
          console.error(e.item.message.original);
        } else {
          console.error($1m(e.item.message.linkedText.toString(), true));
        }
      }
    }
  }
  f(notification) {
    if (notification.priority === NotificationPriority.SILENT) {
      return;
    }
    const listener = notification.onDidChangeContent((e) => {
      if (e.kind === 1) {
        this.g(notification);
      }
    });
    Event2.once(notification.onDidClose)(() => listener.dispose());
    this.g(notification);
  }
  g(notification) {
    let alertText;
    if (notification.severity === Severity2.Error) {
      alertText = localize(3636, null, notification.message.linkedText.toString());
    } else if (notification.severity === Severity2.Warning) {
      alertText = localize(3637, null, notification.message.linkedText.toString());
    } else {
      alertText = localize(3638, null, notification.message.linkedText.toString());
    }
    $$Z(alertText);
  }
};

// out-build/vs/workbench/browser/parts/notifications/notificationsStatus.js
var $2lc = class $2lc2 extends $3c {
  constructor(h3, j, m) {
    super();
    this.h = h3;
    this.j = j;
    this.m = m;
    this.b = 0;
    this.f = false;
    this.g = false;
    this.s();
    if (h3.statusMessage) {
      this.w(h3.statusMessage);
    }
    this.n();
  }
  n() {
    this.B(this.h.onDidChangeNotification((e) => this.r(e)));
    this.B(this.h.onDidChangeStatusMessage((e) => this.u(e)));
    this.B(this.m.onDidChangeFilter(() => this.s()));
  }
  r(e) {
    if (!this.f) {
      if (e.kind === 0) {
        this.b++;
      } else if (e.kind === 3 && this.b > 0) {
        this.b--;
      }
    }
    this.s();
  }
  s() {
    let notificationsInProgress = 0;
    if (!this.f && !this.g) {
      for (const notification of this.h.notifications) {
        if (notification.hasProgress) {
          notificationsInProgress++;
        }
      }
    }
    let statusProperties = {
      name: localize(3662, null),
      text: `${notificationsInProgress > 0 || this.b > 0 ? "$(bell-dot)" : "$(bell)"}`,
      ariaLabel: localize(3663, null),
      command: this.f ? $zlc : $ylc,
      tooltip: this.t(notificationsInProgress),
      showBeak: this.f
    };
    if (this.m.getFilter() === NotificationsFilter.ERROR) {
      statusProperties = {
        ...statusProperties,
        text: `${notificationsInProgress > 0 || this.b > 0 ? "$(bell-slash-dot)" : "$(bell-slash)"}`,
        ariaLabel: localize(3664, null),
        tooltip: localize(3665, null)
      };
    }
    if (!this.a) {
      this.a = this.j.addEntry(
        statusProperties,
        "status.notifications",
        1,
        -Number.MAX_VALUE
        /* towards the far end of the right hand side */
      );
    } else {
      this.a.update(statusProperties);
    }
  }
  t(notificationsInProgress) {
    if (this.f) {
      return localize(3666, null);
    }
    if (this.h.notifications.length === 0) {
      return localize(3667, null);
    }
    if (notificationsInProgress === 0) {
      if (this.b === 0) {
        return localize(3668, null);
      }
      if (this.b === 1) {
        return localize(3669, null);
      }
      return localize(3670, null, this.b);
    }
    if (this.b === 0) {
      return localize(3671, null, notificationsInProgress);
    }
    if (this.b === 1) {
      return localize(3672, null, notificationsInProgress);
    }
    return localize(3673, null, this.b, notificationsInProgress);
  }
  update(isCenterVisible, isToastsVisible) {
    let updateNotificationsCenterStatusItem = false;
    if (this.f !== isCenterVisible) {
      this.f = isCenterVisible;
      this.b = 0;
      updateNotificationsCenterStatusItem = true;
    }
    if (this.g !== isToastsVisible) {
      this.g = isToastsVisible;
      updateNotificationsCenterStatusItem = true;
    }
    if (updateNotificationsCenterStatusItem) {
      this.s();
    }
  }
  u(e) {
    const statusItem = e.item;
    switch (e.kind) {
      case 0:
        this.w(statusItem);
        break;
      case 1:
        if (this.c && this.c[0] === statusItem) {
          $Xc(this.c[1]);
          this.c = void 0;
        }
        break;
    }
  }
  w(item) {
    const message = item.message;
    const showAfter = item.options && typeof item.options.showAfter === "number" ? item.options.showAfter : 0;
    const hideAfter = item.options && typeof item.options.hideAfter === "number" ? item.options.hideAfter : -1;
    if (this.c) {
      $Xc(this.c[1]);
    }
    let statusMessageEntry;
    let showHandle = setTimeout(() => {
      statusMessageEntry = this.j.addEntry(
        {
          name: localize(3674, null),
          text: message,
          ariaLabel: message
        },
        "status.message",
        0,
        -Number.MAX_VALUE
        /* far right on left hand side */
      );
      showHandle = null;
    }, showAfter);
    let hideHandle;
    const statusMessageDispose = {
      dispose: () => {
        if (showHandle) {
          clearTimeout(showHandle);
        }
        if (hideHandle) {
          clearTimeout(hideHandle);
        }
        statusMessageEntry?.dispose();
      }
    };
    if (hideAfter > 0) {
      hideHandle = setTimeout(() => statusMessageDispose.dispose(), hideAfter);
    }
    this.c = [item, statusMessageDispose];
  }
};
$2lc = __decorate([
  __param(1, $$qb),
  __param(2, $PJ)
], $2lc);

// out-build/vs/workbench/browser/parts/notifications/notificationsToasts.js
var $3lc_1;
var ToastVisibility;
(function(ToastVisibility2) {
  ToastVisibility2[ToastVisibility2["HIDDEN_OR_VISIBLE"] = 0] = "HIDDEN_OR_VISIBLE";
  ToastVisibility2[ToastVisibility2["HIDDEN"] = 1] = "HIDDEN";
  ToastVisibility2[ToastVisibility2["VISIBLE"] = 2] = "VISIBLE";
})(ToastVisibility || (ToastVisibility = {}));
var $3lc = class $3lc2 extends $ns {
  static {
    $3lc_1 = this;
  }
  static {
    this.a = 450;
  }
  static {
    this.b = 3;
  }
  static {
    this.c = {
      [Severity2.Info]: 15e3,
      [Severity2.Warning]: 18e3,
      [Severity2.Error]: 2e4
    };
  }
  static {
    this.f = {
      // Count for the number of notifications over 800ms...
      interval: 800,
      // ...and ensure we are not showing more than MAX_NOTIFICATIONS
      limit: this.b
    };
  }
  get isVisible() {
    return !!this.j;
  }
  constructor(D, F, G, H, themeService, I, J, L, M) {
    super(themeService);
    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.g = this.B(new $ze());
    this.onDidChangeVisibility = this.g.event;
    this.j = false;
    this.t = /* @__PURE__ */ new Map();
    this.u = /* @__PURE__ */ new Map();
    this.y = $_pb.bindTo(this.J);
    this.C = new $fi($3lc_1.f.interval);
    this.N();
  }
  N() {
    this.B(this.H.onDidLayoutMainContainer((dimension) => this.layout($rj.lift(dimension))));
    this.L.when(
      3
      /* LifecyclePhase.Restored */
    ).then(() => {
      this.F.notifications.forEach((notification) => this.P(notification));
      this.B(this.F.onDidChangeNotification((e) => this.O(e)));
    });
    this.B(this.F.onDidChangeFilter(({ global, sources }) => {
      if (global === NotificationsFilter.ERROR) {
        this.hide();
      } else if (sources) {
        for (const [notification] of this.t) {
          if (typeof notification.sourceId === "string" && sources.get(notification.sourceId) === NotificationsFilter.ERROR && notification.severity !== Severity2.Error && notification.priority !== NotificationPriority.URGENT) {
            this.S(notification);
          }
        }
      }
    }));
  }
  O(e) {
    switch (e.kind) {
      case 0:
        return this.P(e.item);
      case 3:
        return this.S(e.item);
    }
  }
  P(item) {
    if (this.s) {
      return;
    }
    if (item.priority === NotificationPriority.SILENT) {
      return;
    }
    if (this.C.increment() > $3lc_1.f.limit) {
      return;
    }
    const itemDisposables = new $2c();
    this.u.set(item, itemDisposables);
    itemDisposables.add($jj(getWindow(this.D), () => this.Q(item, itemDisposables)));
  }
  Q(item, itemDisposables) {
    let notificationsToastsContainer = this.m;
    if (!notificationsToastsContainer) {
      notificationsToastsContainer = this.m = document.createElement("div");
      notificationsToastsContainer.classList.add("notifications-toasts");
      this.D.appendChild(notificationsToastsContainer);
    }
    notificationsToastsContainer.classList.add("visible");
    const notificationToastContainer = document.createElement("div");
    notificationToastContainer.classList.add("notification-toast-container");
    const firstToast = notificationsToastsContainer.firstChild;
    if (firstToast) {
      notificationsToastsContainer.insertBefore(notificationToastContainer, firstToast);
    } else {
      notificationsToastsContainer.appendChild(notificationToastContainer);
    }
    const notificationToast = document.createElement("div");
    notificationToast.classList.add("notification-toast");
    notificationToastContainer.appendChild(notificationToast);
    const notificationList = this.G.createInstance($Ylc, notificationToast, {
      verticalScrollMode: 2,
      widgetAriaLabel: (() => {
        if (!item.source) {
          return localize(3675, null, item.message.raw);
        }
        return localize(3676, null, item.message.raw, item.source);
      })()
    });
    itemDisposables.add(notificationList);
    const toast = { item, list: notificationList, container: notificationToastContainer, toast: notificationToast };
    this.t.set(item, toast);
    itemDisposables.add($1c(() => this.ab(toast, false)));
    notificationList.show();
    const maxDimensions = this.Y();
    this.Z(maxDimensions.width);
    notificationList.updateNotificationsList(0, 0, [item]);
    this.$(maxDimensions.height);
    itemDisposables.add(item.onDidChangeExpansion(() => {
      notificationList.updateNotificationsList(0, 1, [item]);
    }));
    itemDisposables.add(item.onDidChangeContent((e) => {
      switch (e.kind) {
        case 2:
          notificationList.updateNotificationsList(0, 1, [item]);
          break;
        case 1:
          if (item.expanded) {
            notificationList.updateNotificationHeight(item);
          }
          break;
      }
    }));
    Event2.once(item.onDidClose)(() => {
      this.S(item);
    });
    this.R(item, notificationToastContainer, notificationList, itemDisposables);
    this.updateStyles();
    this.y.set(true);
    notificationToast.classList.add("notification-fade-in");
    itemDisposables.add($_i(notificationToast, "transitionend", () => {
      notificationToast.classList.remove("notification-fade-in");
      notificationToast.classList.add("notification-fade-in-done");
    }));
    item.updateVisibility(true);
    if (!this.j) {
      this.j = true;
      this.g.fire();
    }
  }
  R(item, notificationToastContainer, notificationList, disposables) {
    let isMouseOverToast = false;
    disposables.add($_i(notificationToastContainer, $7j.MOUSE_OVER, () => isMouseOverToast = true));
    disposables.add($_i(notificationToastContainer, $7j.MOUSE_OUT, () => isMouseOverToast = false));
    let purgeTimeoutHandle;
    let listener;
    const hideAfterTimeout = () => {
      purgeTimeoutHandle = setTimeout(() => {
        if (!this.M.hasFocus) {
          if (!listener) {
            listener = this.M.onDidChangeFocus((focus) => {
              if (focus) {
                hideAfterTimeout();
              }
            });
            disposables.add(listener);
          }
        } else if (item.sticky || // never hide sticky notifications
        notificationList.hasFocus() || // never hide notifications with focus
        isMouseOverToast) {
          hideAfterTimeout();
        } else {
          this.S(item);
        }
      }, $3lc_1.c[item.severity]);
    };
    hideAfterTimeout();
    disposables.add($1c(() => clearTimeout(purgeTimeoutHandle)));
  }
  S(item) {
    let focusEditor = false;
    const notificationToast = this.t.get(item);
    if (notificationToast) {
      const toastHasDOMFocus = $Nj(notificationToast.container);
      if (toastHasDOMFocus) {
        focusEditor = !(this.focusNext() || this.focusPrevious());
      }
      this.t.delete(item);
    }
    const notificationDisposables = this.u.get(item);
    if (notificationDisposables) {
      $Xc(notificationDisposables);
      this.u.delete(item);
    }
    if (this.t.size > 0) {
      this.layout(this.r);
    } else {
      this.W();
      if (focusEditor) {
        this.I.activeGroup.focus();
      }
    }
  }
  U() {
    this.t.clear();
    this.u.forEach((disposable) => $Xc(disposable));
    this.u.clear();
    this.W();
  }
  W() {
    this.m?.classList.remove("visible");
    this.y.set(false);
    if (this.j) {
      this.j = false;
      this.g.fire();
    }
  }
  hide() {
    const focusEditor = this.m ? $Nj(this.m) : false;
    this.U();
    if (focusEditor) {
      this.I.activeGroup.focus();
    }
  }
  focus() {
    const toasts = this.X(ToastVisibility.VISIBLE);
    if (toasts.length > 0) {
      toasts[0].list.focusFirst();
      return true;
    }
    return false;
  }
  focusNext() {
    const toasts = this.X(ToastVisibility.VISIBLE);
    for (let i2 = 0; i2 < toasts.length; i2++) {
      const toast = toasts[i2];
      if (toast.list.hasFocus()) {
        const nextToast = toasts[i2 + 1];
        if (nextToast) {
          nextToast.list.focusFirst();
          return true;
        }
        break;
      }
    }
    return false;
  }
  focusPrevious() {
    const toasts = this.X(ToastVisibility.VISIBLE);
    for (let i2 = 0; i2 < toasts.length; i2++) {
      const toast = toasts[i2];
      if (toast.list.hasFocus()) {
        const previousToast = toasts[i2 - 1];
        if (previousToast) {
          previousToast.list.focusFirst();
          return true;
        }
        break;
      }
    }
    return false;
  }
  focusFirst() {
    const toast = this.X(ToastVisibility.VISIBLE)[0];
    if (toast) {
      toast.list.focusFirst();
      return true;
    }
    return false;
  }
  focusLast() {
    const toasts = this.X(ToastVisibility.VISIBLE);
    if (toasts.length > 0) {
      toasts[toasts.length - 1].list.focusFirst();
      return true;
    }
    return false;
  }
  update(isCenterVisible) {
    if (this.s !== isCenterVisible) {
      this.s = isCenterVisible;
      if (this.s) {
        this.U();
      }
    }
  }
  updateStyles() {
    this.t.forEach(({ toast }) => {
      const backgroundColor = this.z($kob);
      toast.style.background = backgroundColor ? backgroundColor : "";
      const widgetShadowColor = this.z($Rp);
      toast.style.boxShadow = widgetShadowColor ? `0 0 8px 2px ${widgetShadowColor}` : "";
      const borderColor = this.z($iob);
      toast.style.border = borderColor ? `1px solid ${borderColor}` : "";
    });
  }
  X(state) {
    const notificationToasts = [];
    this.t.forEach((toast) => {
      switch (state) {
        case ToastVisibility.HIDDEN_OR_VISIBLE:
          notificationToasts.push(toast);
          break;
        case ToastVisibility.HIDDEN:
          if (!this.bb(toast)) {
            notificationToasts.push(toast);
          }
          break;
        case ToastVisibility.VISIBLE:
          if (this.bb(toast)) {
            notificationToasts.push(toast);
          }
          break;
      }
    });
    return notificationToasts.reverse();
  }
  layout(dimension) {
    this.r = dimension;
    const maxDimensions = this.Y();
    if (maxDimensions.height) {
      this.$(maxDimensions.height);
    }
    this.Z(maxDimensions.width);
  }
  Y() {
    const maxWidth = $3lc_1.a;
    let availableWidth = maxWidth;
    let availableHeight;
    if (this.r) {
      availableWidth = this.r.width;
      availableWidth -= 2 * 8;
      availableHeight = this.r.height;
      if (this.H.isVisible("workbench.parts.statusbar", $Y)) {
        availableHeight -= 22;
      }
      if (this.H.isVisible("workbench.parts.titlebar", $Y)) {
        availableHeight -= 22;
      }
      availableHeight -= 2 * 12;
    }
    availableHeight = typeof availableHeight === "number" ? Math.round(availableHeight * 0.618) : 0;
    return new $rj(Math.min(maxWidth, availableWidth), availableHeight);
  }
  Z(width2) {
    this.t.forEach(({ list: list2 }) => list2.layout(width2));
  }
  $(heightToGive) {
    let visibleToasts = 0;
    for (const toast of this.X(ToastVisibility.HIDDEN_OR_VISIBLE)) {
      toast.container.style.opacity = "0";
      this.ab(toast, true);
      heightToGive -= toast.container.offsetHeight;
      let makeVisible = false;
      if (visibleToasts === $3lc_1.b) {
        makeVisible = false;
      } else if (heightToGive >= 0) {
        makeVisible = true;
      }
      this.ab(toast, makeVisible);
      toast.container.style.opacity = "";
      if (makeVisible) {
        visibleToasts++;
      }
    }
  }
  ab(toast, visible) {
    if (this.bb(toast) === visible) {
      return;
    }
    const notificationsToastsContainer = $Kg(this.m);
    if (visible) {
      notificationsToastsContainer.appendChild(toast.container);
    } else {
      toast.container.remove();
    }
    toast.item.updateVisibility(visible);
  }
  bb(toast) {
    return !!toast.container.parentElement;
  }
};
$3lc = $3lc_1 = __decorate([
  __param(2, $Pk),
  __param(3, $Vlb),
  __param(4, $gs),
  __param(5, $iJ),
  __param(6, $on),
  __param(7, $KL),
  __param(8, $S4)
], $3lc);

// out-build/vs/workbench/browser/contextkeys.js
var $4lc = class $4lc2 extends $3c {
  constructor(S, U, W, X, Y, Z, $149, ab, bb, cb) {
    super();
    this.S = S;
    this.U = U;
    this.W = W;
    this.X = X;
    this.Y = Y;
    this.Z = Z;
    this.$ = $149;
    this.ab = ab;
    this.bb = bb;
    this.cb = cb;
    $seb.bindTo(this.S);
    $teb.bindTo(this.S);
    $ueb.bindTo(this.S);
    $veb.bindTo(this.S);
    $web.bindTo(this.S);
    $xeb.bindTo(this.S);
    $yeb.bindTo(this.S);
    $kpb.bindTo(this.S).set($9v(this.X.remoteAuthority) || "");
    this.y = $lpb.bindTo(this.S);
    this.z = $mpb.bindTo(this.S);
    this.pb();
    $ppb.bindTo(this.S).set(WebFileSystemAccess.supported($Y));
    const isDevelopment = !this.X.isBuilt || this.X.isExtensionDevelopment;
    $zeb.bindTo(this.S).set(isDevelopment);
    $5m($zeb.key, isDevelopment);
    $Aeb.bindTo(this.S).set(this.Y.quality || "");
    $qpb.bindTo(this.S).set(Y.embedderIdentifier);
    this.c = $Jpb.bindTo(this.S);
    this.f = $Kpb.bindTo(this.S);
    this.g = $Lpb.bindTo(this.S);
    this.h = $Mpb.bindTo(this.S);
    this.j = $Npb.bindTo(this.S);
    this.m = $Wpb.bindTo(this.S);
    this.b = $jpb.bindTo(this.S);
    this.b.set(this.cb.hasDirty);
    this.a = $Ceb.bindTo(this.S);
    this.r = $epb.bindTo(this.S);
    this.jb();
    this.s = $fpb.bindTo(this.S);
    this.kb();
    this.t = $gpb.bindTo(this.S);
    this.t.set($p || typeof this.X.remoteAuthority === "string");
    this.w = $ipb.bindTo(this.S);
    this.w.set($p || typeof this.X.remoteAuthority === "string");
    this.u = $hpb.bindTo(this.S);
    this.u.set($p || typeof this.X.remoteAuthority === "string");
    this.n = $Zpb.bindTo(this.S);
    this.lb();
    this.D = $npb.bindTo(this.S);
    this.F = $opb.bindTo(this.S);
    this.C = $Xpb.bindTo(this.S);
    this.G = $Ypb.bindTo(this.S);
    this.I = $1pb.bindTo(this.S);
    this.P = $2pb.bindTo(this.S);
    this.H = $3pb.bindTo(this.S);
    this.Q = $8pb.bindTo(this.S);
    this.R = $7pb.bindTo(this.S);
    this.ob();
    this.J = $fqb.bindTo(this.S);
    this.J.set($Xlb(this.ab.getPanelPosition()));
    this.L = $hqb.bindTo(this.S);
    this.L.set(this.ab.isVisible(
      "workbench.parts.panel"
      /* Parts.PANEL_PART */
    ));
    this.N = $iqb.bindTo(this.S);
    this.N.set(this.ab.isPanelMaximized());
    this.M = $gqb.bindTo(this.S);
    this.M.set(this.ab.getPanelAlignment());
    this.O = $cqb.bindTo(this.S);
    this.O.set(this.ab.isVisible(
      "workbench.parts.auxiliarybar"
      /* Parts.AUXILIARYBAR_PART */
    ));
    $rpb.bindTo(this.S).set(this.X.isEnabledFileDownloads ?? true);
    $spb.bindTo(this.S).set(this.X.isEnabledFileUploads ?? true);
    this.db();
  }
  db() {
    this.Z.whenReady.then(() => {
      this.hb();
      this.fb();
      this.eb();
    });
    this.B(this.$.onDidActiveEditorChange(() => this.fb()));
    this.B(this.$.onDidVisibleEditorsChange(() => this.eb()));
    this.B(this.Z.onDidAddGroup(() => this.gb()));
    this.B(this.Z.onDidRemoveGroup(() => this.gb()));
    this.B(this.Z.onDidChangeGroupIndex(() => this.fb()));
    this.B(this.Z.onDidChangeGroupLocked(() => this.fb()));
    this.B(this.Z.onDidChangeEditorPartOptions(() => this.hb()));
    this.B(Event2.runAndSubscribe(onDidRegisterWindow, ({ window: window3, disposables }) => disposables.add($_i(window3, $7j.FOCUS_IN, () => this.ib(window3.document), true)), { window: $Y, disposables: this.q }));
    this.B(this.U.onDidChangeWorkbenchState(() => this.jb()));
    this.B(this.U.onDidChangeWorkspaceFolders(() => {
      this.kb();
      this.pb();
    }));
    this.B(this.W.onDidChangeConfiguration((e) => {
      if (e.affectsConfiguration("workbench.editor.openSideBySideDirection")) {
        this.lb();
      }
    }));
    this.B(this.ab.onDidChangeZenMode((enabled) => this.C.set(enabled)));
    this.B(this.ab.onDidChangeActiveContainer(() => this.F.set(this.ab.activeContainer !== this.ab.mainContainer)));
    this.B($Te((windowId) => {
      if (windowId === $Y.vscodeWindowId) {
        this.D.set($Se($Y));
      }
    }));
    this.B(this.ab.onDidChangeMainEditorCenteredLayout((centered) => this.G.set(centered)));
    this.B(this.ab.onDidChangePanelPosition((position) => this.J.set(position)));
    this.B(this.ab.onDidChangePanelAlignment((alignment) => this.M.set(alignment)));
    this.B(this.bb.onDidPaneCompositeClose(() => this.nb()));
    this.B(this.bb.onDidPaneCompositeOpen(() => this.nb()));
    this.B(this.ab.onDidChangePartVisibility(() => {
      this.I.set(this.ab.isVisible("workbench.parts.editor", $Y));
      this.L.set(this.ab.isVisible(
        "workbench.parts.panel"
        /* Parts.PANEL_PART */
      ));
      this.N.set(this.ab.isPanelMaximized());
      this.O.set(this.ab.isVisible(
        "workbench.parts.auxiliarybar"
        /* Parts.AUXILIARYBAR_PART */
      ));
      this.ob();
    }));
    this.B(this.cb.onDidChangeDirty((workingCopy) => this.b.set(workingCopy.isDirty() || this.cb.hasDirty)));
  }
  eb() {
    const visibleEditorPanes = this.$.visibleEditorPanes;
    if (visibleEditorPanes.length > 0) {
      this.m.set(true);
    } else {
      this.m.reset();
    }
  }
  // Context keys depending on the state of the editor group itself
  fb() {
    if (!this.$.activeEditor) {
      this.c.set(true);
    } else {
      this.c.reset();
    }
    const activeGroup = this.Z.activeGroup;
    this.f.set(activeGroup.index + 1);
    this.h.set(activeGroup.isLocked);
    this.gb();
  }
  // Context keys depending on the state of other editor groups
  gb() {
    const groupCount = this.Z.count;
    if (groupCount > 1) {
      this.j.set(true);
    } else {
      this.j.reset();
    }
    const activeGroup = this.Z.activeGroup;
    this.g.set(activeGroup.index === groupCount - 1);
  }
  hb() {
    this.P.set(this.Z.partOptions.showTabs === "multiple");
  }
  ib(ownerDocument) {
    function activeElementIsInput() {
      return !!ownerDocument.activeElement && $Fk(ownerDocument.activeElement);
    }
    const isInputFocused = activeElementIsInput();
    this.a.set(isInputFocused);
    if (isInputFocused) {
      const tracker2 = $_j(ownerDocument.activeElement);
      Event2.once(tracker2.onDidBlur)(() => {
        if ($Qj().document === ownerDocument) {
          this.a.set(activeElementIsInput());
        }
        tracker2.dispose();
      });
    }
  }
  jb() {
    this.r.set(this.mb());
  }
  kb() {
    this.s.set(this.U.getWorkspace().folders.length);
  }
  lb() {
    const direction = $lJ(this.W);
    this.n.set(
      direction === 1
      /* GroupDirection.DOWN */
    );
  }
  mb() {
    switch (this.U.getWorkbenchState()) {
      case 1:
        return "empty";
      case 2:
        return "folder";
      case 3:
        return "workspace";
    }
  }
  nb() {
    this.H.set(this.ab.isVisible(
      "workbench.parts.sidebar"
      /* Parts.SIDEBAR_PART */
    ));
  }
  ob() {
    this.Q.set(this.ab.isVisible("workbench.parts.titlebar", $Y));
    this.R.set($Es(this.W));
  }
  pb() {
    this.y.set($0S(this.U.getWorkspace()) || "");
    this.z.set($fl(this.U.getWorkspace()));
  }
};
$4lc = __decorate([
  __param(0, $on),
  __param(1, $Zk),
  __param(2, $kl),
  __param(3, $M4),
  __param(4, $Vu),
  __param(5, $iJ),
  __param(6, $mJ),
  __param(7, $Vlb),
  __param(8, $uqb),
  __param(9, $XI)
], $4lc);

// out-build/vs/workbench/browser/layout.js
var LayoutClasses;
(function(LayoutClasses2) {
  LayoutClasses2["SIDEBAR_HIDDEN"] = "nosidebar";
  LayoutClasses2["MAIN_EDITOR_AREA_HIDDEN"] = "nomaineditorarea";
  LayoutClasses2["PANEL_HIDDEN"] = "nopanel";
  LayoutClasses2["AUXILIARYBAR_HIDDEN"] = "noauxiliarybar";
  LayoutClasses2["STATUSBAR_HIDDEN"] = "nostatusbar";
  LayoutClasses2["FULLSCREEN"] = "fullscreen";
  LayoutClasses2["MAXIMIZED"] = "maximized";
  LayoutClasses2["WINDOW_BORDER"] = "border";
})(LayoutClasses || (LayoutClasses = {}));
var $5lc = [
  "workbench.activityBar.location",
  "window.commandCenter",
  "workbench.editor.editorActionsLocation",
  "workbench.layoutControl.enabled",
  "workbench.navigationControl.enabled",
  "window.menuBarVisibility",
  "window.titleBarStyle",
  "window.customTitleBarVisibility"
];
var $6lc = class extends $3c {
  get activeContainer() {
    return this.u($Pj());
  }
  get containers() {
    const containers = [];
    for (const { window: window3 } of getWindows()) {
      containers.push(this.u(window3.document));
    }
    return containers;
  }
  u(targetDocument) {
    if (targetDocument === this.mainContainer.ownerDocument) {
      return this.mainContainer;
    } else {
      return targetDocument.body.getElementsByClassName("monaco-workbench")[0];
    }
  }
  whenContainerStylesLoaded(window3) {
    return this.w.get(window3.vscodeWindowId);
  }
  get mainContainerDimension() {
    return this.y;
  }
  get activeContainerDimension() {
    return this.z(this.activeContainer);
  }
  z(container2) {
    if (container2 === this.mainContainer) {
      return this.mainContainerDimension;
    } else {
      return $qj(container2);
    }
  }
  get mainContainerOffset() {
    return this.C($Y);
  }
  get activeContainerOffset() {
    return this.C(getWindow(this.activeContainer));
  }
  C(targetWindow) {
    let top2 = 0;
    let quickPickTop = 0;
    if (this.isVisible(
      "workbench.parts.banner"
      /* Parts.BANNER_PART */
    )) {
      top2 = this.Lb(
        "workbench.parts.banner"
        /* Parts.BANNER_PART */
      ).maximumHeight;
      quickPickTop = top2;
    }
    const titlebarVisible = this.isVisible("workbench.parts.titlebar", targetWindow);
    if (titlebarVisible) {
      top2 += this.Lb(
        "workbench.parts.titlebar"
        /* Parts.TITLEBAR_PART */
      ).maximumHeight;
      quickPickTop = top2;
    }
    const isCommandCenterVisible = titlebarVisible && this.S.getValue(
      "window.commandCenter"
      /* LayoutSettings.COMMAND_CENTER */
    ) !== false;
    if (isCommandCenterVisible) {
      quickPickTop = 6;
    }
    return { top: top2, quickPickTop };
  }
  constructor(nb) {
    super();
    this.nb = nb;
    this.a = this.B(new $ze());
    this.onDidChangeZenMode = this.a.event;
    this.b = this.B(new $ze());
    this.onDidChangeMainEditorCenteredLayout = this.b.event;
    this.c = this.B(new $ze());
    this.onDidChangePanelAlignment = this.c.event;
    this.f = this.B(new $ze());
    this.onDidChangeWindowMaximized = this.f.event;
    this.g = this.B(new $ze());
    this.onDidChangePanelPosition = this.g.event;
    this.h = this.B(new $ze());
    this.onDidChangePartVisibility = this.h.event;
    this.j = this.B(new $ze());
    this.onDidChangeNotificationsVisibility = this.j.event;
    this.m = this.B(new $ze());
    this.onDidLayoutMainContainer = this.m.event;
    this.n = this.B(new $ze());
    this.onDidLayoutActiveContainer = this.n.event;
    this.r = this.B(new $ze());
    this.onDidLayoutContainer = this.r.event;
    this.s = this.B(new $ze());
    this.onDidAddContainer = this.s.event;
    this.t = this.B(new $ze());
    this.onDidChangeActiveContainer = this.t.event;
    this.mainContainer = document.createElement("div");
    this.w = /* @__PURE__ */ new Map();
    this.D = /* @__PURE__ */ new Map();
    this.F = false;
    this.mb = false;
    this.Eb = false;
    this.Gb = new $gi();
    this.Hb = this.Gb.p;
    this.Ib = new $gi();
    this.whenRestored = this.Ib.p;
    this.Jb = false;
  }
  ob(accessor) {
    this.Q = accessor.get($M4);
    this.S = accessor.get($kl);
    this.W = accessor.get($S4);
    this.cb = accessor.get($Zk);
    this.U = accessor.get($jv);
    this.db = accessor.get($yG);
    this.fb = accessor.get($gs);
    this.R = accessor.get($wN);
    this.hb = accessor.get($wn);
    this.ib = accessor.get($zv);
    this.jb = accessor.get($Uob);
    this.X = accessor.get($mJ);
    this.Y = this.X.createScoped("main", this.q);
    this.Z = accessor.get($iJ);
    this.$ = accessor.get($uqb);
    this.bb = accessor.get($$M);
    this.ab = accessor.get($RTb);
    this.eb = accessor.get($PJ);
    this.gb = accessor.get($$qb);
    accessor.get($jVb);
    this.pb();
    this.zb(accessor.get($KL), accessor.get($km));
  }
  pb() {
    const showEditorIfHidden = () => {
      if (!this.isVisible("workbench.parts.editor", $Y)) {
        this.toggleMaximizedPanel();
      }
    };
    this.Z.whenRestored.then(() => {
      this.B(this.Y.onDidVisibleEditorsChange(showEditorIfHidden));
      this.B(this.Z.mainPart.onDidActivateGroup(showEditorIfHidden));
      this.B(this.Y.onDidActiveEditorChange(() => this.centerMainEditorLayout(this.lb.getRuntimeValue(LayoutStateKeys.MAIN_EDITOR_CENTERED))));
    });
    this.B(this.S.onDidChangeConfiguration((e) => {
      if ([
        ...$5lc,
        LegacyWorkbenchLayoutSettings.SIDEBAR_POSITION,
        LegacyWorkbenchLayoutSettings.STATUSBAR_VISIBLE
      ].some((setting) => e.affectsConfiguration(setting))) {
        const editorActionsMovedToTitlebar = e.affectsConfiguration(
          "workbench.editor.editorActionsLocation"
          /* LayoutSettings.EDITOR_ACTIONS_LOCATION */
        ) && this.S.getValue(
          "workbench.editor.editorActionsLocation"
          /* LayoutSettings.EDITOR_ACTIONS_LOCATION */
        ) === "titleBar";
        let activityBarMovedToTopOrBottom = false;
        if (e.affectsConfiguration(
          "workbench.activityBar.location"
          /* LayoutSettings.ACTIVITY_BAR_LOCATION */
        )) {
          const activityBarPosition = this.S.getValue(
            "workbench.activityBar.location"
            /* LayoutSettings.ACTIVITY_BAR_LOCATION */
          );
          activityBarMovedToTopOrBottom = activityBarPosition === "top" || activityBarPosition === "bottom";
        }
        if (activityBarMovedToTopOrBottom || editorActionsMovedToTitlebar) {
          if (this.S.getValue(
            "window.customTitleBarVisibility"
            /* TitleBarSetting.CUSTOM_TITLE_BAR_VISIBILITY */
          ) === "never") {
            this.S.updateValue(
              "window.customTitleBarVisibility",
              "auto"
              /* CustomTitleBarVisibility.AUTO */
            );
          }
        }
        this.wb();
      }
    }));
    this.B($Te((windowId) => this.sb(windowId)));
    this.B(this.Z.mainPart.onDidAddGroup(() => this.centerMainEditorLayout(this.lb.getRuntimeValue(LayoutStateKeys.MAIN_EDITOR_CENTERED))));
    this.B(this.Z.mainPart.onDidRemoveGroup(() => this.centerMainEditorLayout(this.lb.getRuntimeValue(LayoutStateKeys.MAIN_EDITOR_CENTERED))));
    this.B(this.Z.mainPart.onDidChangeGroupMaximized(() => this.centerMainEditorLayout(this.lb.getRuntimeValue(LayoutStateKeys.MAIN_EDITOR_CENTERED))));
    this.B($_i(this.mainContainer, $7j.SCROLL, () => this.mainContainer.scrollTop = 0));
    const showingCustomMenu = ($l || $n || $r) && !$Ds(this.S);
    if (showingCustomMenu) {
      this.B(this.ab.onMenubarVisibilityChange((visible) => this.qb(visible)));
    }
    this.B(this.fb.onDidColorThemeChange(() => this.yb()));
    this.B(this.W.onDidChangeFocus((focused) => this.ub(focused)));
    this.B(this.W.onDidChangeActiveWindow(() => this.tb()));
    if ($r && typeof navigator.windowControlsOverlay === "object") {
      this.B($_i(navigator.windowControlsOverlay, "geometrychange", () => this.ac()));
    }
    this.B(this.jb.onDidOpenAuxiliaryWindow(({ window: window3, disposables }) => {
      const windowId = window3.window.vscodeWindowId;
      this.w.set(windowId, window3.whenStylesHaveLoaded);
      window3.whenStylesHaveLoaded.then(() => this.w.delete(windowId));
      disposables.add($1c(() => this.w.delete(windowId)));
      const eventDisposables = disposables.add(new $2c());
      this.s.fire({ container: window3.container, disposables: eventDisposables });
      disposables.add(window3.onDidLayout((dimension) => this.rb(window3.container, dimension)));
    }));
  }
  qb(visible) {
    if (visible !== this.kb.runtime.menuBar.toggled) {
      this.kb.runtime.menuBar.toggled = visible;
      const menuBarVisibility = $Bs(this.S);
      if ($r && menuBarVisibility === "toggle") {
        this.G.setViewVisible(this.H, $1lb(this.S, $Y, this.kb.runtime.menuBar.toggled));
      } else if (this.kb.runtime.mainWindowFullscreen && (menuBarVisibility === "toggle" || menuBarVisibility === "classic")) {
        this.G.setViewVisible(this.H, $1lb(this.S, $Y, this.kb.runtime.menuBar.toggled));
      }
      this.rb(this.mainContainer, this.y);
    }
  }
  rb(container2, dimension) {
    if (container2 === this.mainContainer) {
      this.m.fire(dimension);
    }
    if ($Oj(container2)) {
      this.n.fire(dimension);
    }
    this.r.fire({ container: container2, dimension });
  }
  sb(windowId) {
    if (windowId !== $Y.vscodeWindowId) {
      return;
    }
    this.kb.runtime.mainWindowFullscreen = $Se($Y);
    if (this.kb.runtime.mainWindowFullscreen) {
      this.mainContainer.classList.add(LayoutClasses.FULLSCREEN);
    } else {
      this.mainContainer.classList.remove(LayoutClasses.FULLSCREEN);
      const zenModeExitInfo = this.lb.getRuntimeValue(LayoutStateKeys.ZEN_MODE_EXIT_INFO);
      if (zenModeExitInfo.transitionedToFullScreen && this.Ob()) {
        this.toggleZenMode();
      }
    }
    this.G.edgeSnapping = this.kb.runtime.mainWindowFullscreen;
    if ($Cs(this.S)) {
      this.G.setViewVisible(this.H, $1lb(this.S, $Y, this.kb.runtime.menuBar.toggled));
      this.yb(true);
    }
  }
  tb() {
    const activeContainerId = this.vb();
    if (this.kb.runtime.activeContainerId !== activeContainerId) {
      this.kb.runtime.activeContainerId = activeContainerId;
      this.yb();
      this.t.fire();
    }
  }
  ub(hasFocus) {
    if (this.kb.runtime.hasFocus !== hasFocus) {
      this.kb.runtime.hasFocus = hasFocus;
      this.yb();
    }
  }
  vb() {
    const activeContainer = this.activeContainer;
    return getWindow(activeContainer).vscodeWindowId;
  }
  wb(skipLayout) {
    this.updateCustomTitleBarVisibility();
    this.updateMenubarVisibility(!!skipLayout);
    this.Z.whenRestored.then(() => {
      this.centerMainEditorLayout(this.lb.getRuntimeValue(LayoutStateKeys.MAIN_EDITOR_CENTERED), skipLayout);
    });
  }
  xb(position) {
    const activityBar = this.Lb(
      "workbench.parts.activitybar"
      /* Parts.ACTIVITYBAR_PART */
    );
    const sideBar = this.Lb(
      "workbench.parts.sidebar"
      /* Parts.SIDEBAR_PART */
    );
    const auxiliaryBar = this.Lb(
      "workbench.parts.auxiliarybar"
      /* Parts.AUXILIARYBAR_PART */
    );
    const newPositionValue = position === 0 ? "left" : "right";
    const oldPositionValue = position === 1 ? "left" : "right";
    const panelAlignment = this.getPanelAlignment();
    const panelPosition = this.getPanelPosition();
    this.lb.setRuntimeValue(LayoutStateKeys.SIDEBAR_POSITON, position);
    const activityBarContainer = $Kg(activityBar.getContainer());
    const sideBarContainer = $Kg(sideBar.getContainer());
    const auxiliaryBarContainer = $Kg(auxiliaryBar.getContainer());
    activityBarContainer.classList.remove(oldPositionValue);
    sideBarContainer.classList.remove(oldPositionValue);
    activityBarContainer.classList.add(newPositionValue);
    sideBarContainer.classList.add(newPositionValue);
    auxiliaryBarContainer.classList.remove(newPositionValue);
    auxiliaryBarContainer.classList.add(oldPositionValue);
    activityBar.updateStyles();
    sideBar.updateStyles();
    auxiliaryBar.updateStyles();
    this.Xb(position, panelAlignment, panelPosition);
  }
  yb(skipLayout = false) {
    if ($r || $l || // not working well with zooming (border often not visible)
    $Gs(this.S) || // not working with WCO (border cannot draw over the overlay)
    $Ds(this.S)) {
      return;
    }
    const theme = this.fb.getColorTheme();
    const activeBorder = theme.getColor($sob);
    const inactiveBorder = theme.getColor($tob);
    const didHaveMainWindowBorder = this.hasMainWindowBorder();
    for (const container2 of this.containers) {
      const isMainContainer = container2 === this.mainContainer;
      const isActiveContainer = this.activeContainer === container2;
      const containerWindowId = getWindowId(getWindow(container2));
      let windowBorder = false;
      if (!this.kb.runtime.mainWindowFullscreen && !this.kb.runtime.maximized.has(containerWindowId) && (activeBorder || inactiveBorder)) {
        windowBorder = true;
        const borderColor = isActiveContainer && this.kb.runtime.hasFocus ? activeBorder : inactiveBorder ?? activeBorder;
        container2.style.setProperty("--window-border-color", borderColor?.toString() ?? "transparent");
      }
      if (isMainContainer) {
        this.kb.runtime.mainWindowBorder = windowBorder;
      }
      container2.classList.toggle(LayoutClasses.WINDOW_BORDER, windowBorder);
    }
    if (!skipLayout && didHaveMainWindowBorder !== this.hasMainWindowBorder()) {
      this.layout();
    }
  }
  zb(lifecycleService, fileService) {
    this.lb = new LayoutStateModel(this.U, this.S, this.cb, this.nb);
    this.lb.load();
    if (this.lb.getRuntimeValue(LayoutStateKeys.PANEL_HIDDEN) && this.lb.getRuntimeValue(LayoutStateKeys.EDITOR_HIDDEN)) {
      this.lb.setRuntimeValue(LayoutStateKeys.EDITOR_HIDDEN, false);
    }
    this.B(this.lb.onDidChangeState((change) => {
      if (change.key === LayoutStateKeys.ACTIVITYBAR_HIDDEN) {
        this.Sb(change.value);
      }
      if (change.key === LayoutStateKeys.STATUSBAR_HIDDEN) {
        this.Qb(change.value);
      }
      if (change.key === LayoutStateKeys.SIDEBAR_POSITON) {
        this.xb(change.value);
      }
      if (change.key === LayoutStateKeys.PANEL_POSITION) {
        this.setPanelPosition(change.value);
      }
      if (change.key === LayoutStateKeys.PANEL_ALIGNMENT) {
        this.setPanelAlignment(change.value);
      }
      this.wb();
    }));
    const initialEditorsState = this.Fb();
    if (initialEditorsState) {
      this.hb.trace("Initial editor state", initialEditorsState);
    }
    const initialLayoutState = {
      layout: {
        editors: initialEditorsState?.layout
      },
      editor: {
        restoreEditors: this.Bb(this.cb, initialEditorsState),
        editorsToOpen: this.Db(fileService, initialEditorsState)
      },
      views: {
        defaults: this.Ab(this.Q, this.U),
        containerToRestore: {}
      }
    };
    const layoutRuntimeState = {
      activeContainerId: this.vb(),
      mainWindowFullscreen: $Se($Y),
      hasFocus: this.W.hasFocus,
      maximized: /* @__PURE__ */ new Set(),
      mainWindowBorder: false,
      menuBar: {
        toggled: false
      },
      zenMode: {
        transitionDisposables: new $_c()
      }
    };
    this.kb = {
      initialization: initialLayoutState,
      runtime: layoutRuntimeState
    };
    if (this.isVisible(
      "workbench.parts.sidebar"
      /* Parts.SIDEBAR_PART */
    )) {
      let viewContainerToRestore;
      if (!this.Q.isBuilt || lifecycleService.startupKind === 3 || this.Q.isExtensionDevelopment && !this.Q.extensionTestsLocationURI) {
        viewContainerToRestore = this.U.get($hVb.activeViewletSettingsKey, 1, this.bb.getDefaultViewContainer(
          0
          /* ViewContainerLocation.Sidebar */
        )?.id);
      } else {
        viewContainerToRestore = this.bb.getDefaultViewContainer(
          0
          /* ViewContainerLocation.Sidebar */
        )?.id;
      }
      if (viewContainerToRestore) {
        this.kb.initialization.views.containerToRestore.sideBar = viewContainerToRestore;
      } else {
        this.lb.setRuntimeValue(LayoutStateKeys.SIDEBAR_HIDDEN, true);
      }
    }
    if (this.isVisible(
      "workbench.parts.panel"
      /* Parts.PANEL_PART */
    )) {
      const viewContainerToRestore = this.U.get($dVb.activePanelSettingsKey, 1, this.bb.getDefaultViewContainer(
        1
        /* ViewContainerLocation.Panel */
      )?.id);
      if (viewContainerToRestore) {
        this.kb.initialization.views.containerToRestore.panel = viewContainerToRestore;
      } else {
        this.lb.setRuntimeValue(LayoutStateKeys.PANEL_HIDDEN, true);
      }
    }
    if (this.isVisible(
      "workbench.parts.auxiliarybar"
      /* Parts.AUXILIARYBAR_PART */
    )) {
      let viewContainerToRestore = this.U.get($cVb.activePanelSettingsKey, 1, this.bb.getDefaultViewContainer(
        2
        /* ViewContainerLocation.AuxiliaryBar */
      )?.id);
      if (viewContainerToRestore) {
        if (viewContainerToRestore === "workbench.panel.chatSidebar") {
          viewContainerToRestore = "workbench.panel.chat";
        }
        this.kb.initialization.views.containerToRestore.auxiliaryBar = viewContainerToRestore;
      } else {
        this.lb.setRuntimeValue(LayoutStateKeys.AUXILIARYBAR_HIDDEN, true);
      }
    }
    this.yb(true);
  }
  Ab(environmentService, storageService) {
    const defaultLayout = environmentService.options?.defaultLayout;
    if (!defaultLayout) {
      return void 0;
    }
    if (!defaultLayout.force && !storageService.isNew(
      1
      /* StorageScope.WORKSPACE */
    )) {
      return void 0;
    }
    const { views } = defaultLayout;
    if (views?.length) {
      return views.map((view) => view.id);
    }
    return void 0;
  }
  Bb(contextService, initialEditorsState) {
    if ($fl(contextService.getWorkspace())) {
      return false;
    }
    const forceRestoreEditors = this.S.getValue("window.restoreWindows") === "preserve";
    return !!forceRestoreEditors || initialEditorsState === void 0;
  }
  Cb() {
    return this.kb.initialization.editor.restoreEditors;
  }
  async Db(fileService, initialEditorsState) {
    if (initialEditorsState) {
      const filesToMerge = $Mb(await $nL(initialEditorsState.filesToMerge, fileService, this.hb));
      if (filesToMerge.length === 4 && $8K(filesToMerge[0]) && $8K(filesToMerge[1]) && $8K(filesToMerge[2]) && $8K(filesToMerge[3])) {
        return [{
          editor: {
            input1: { resource: filesToMerge[0].resource },
            input2: { resource: filesToMerge[1].resource },
            base: { resource: filesToMerge[2].resource },
            result: { resource: filesToMerge[3].resource },
            options: { pinned: true }
          }
        }];
      }
      const filesToDiff = $Mb(await $nL(initialEditorsState.filesToDiff, fileService, this.hb));
      if (filesToDiff.length === 2) {
        return [{
          editor: {
            original: { resource: filesToDiff[0].resource },
            modified: { resource: filesToDiff[1].resource },
            options: { pinned: true }
          }
        }];
      }
      const filesToOpenOrCreate = [];
      const resolvedFilesToOpenOrCreate = await $nL(initialEditorsState.filesToOpenOrCreate, fileService, this.hb);
      for (let i2 = 0; i2 < resolvedFilesToOpenOrCreate.length; i2++) {
        const resolvedFileToOpenOrCreate = resolvedFilesToOpenOrCreate[i2];
        if (resolvedFileToOpenOrCreate) {
          filesToOpenOrCreate.push({
            editor: resolvedFileToOpenOrCreate,
            viewColumn: initialEditorsState.filesToOpenOrCreate?.[i2].viewColumn
            // take over `viewColumn` from initial state
          });
        }
      }
      return filesToOpenOrCreate;
    } else if (this.cb.getWorkbenchState() === 1 && this.S.getValue("workbench.startupEditor") === "newUntitledFile") {
      if (this.Z.hasRestorableState) {
        return [];
      }
      const hasBackups = await this.db.hasBackups();
      if (hasBackups) {
        return [];
      }
      return [{
        editor: { resource: void 0 }
        // open empty untitled file
      }];
    }
    return [];
  }
  get openedDefaultEditors() {
    return this.Eb;
  }
  Fb() {
    const defaultLayout = this.Q.options?.defaultLayout;
    if ((defaultLayout?.editors?.length || defaultLayout?.layout?.editors) && (defaultLayout.force || this.U.isNew(
      1
      /* StorageScope.WORKSPACE */
    ))) {
      this.Eb = true;
      return {
        layout: defaultLayout.layout?.editors,
        filesToOpenOrCreate: defaultLayout?.editors?.map((editor) => {
          return {
            viewColumn: editor.viewColumn,
            fileUri: URI.revive(editor.uri),
            openOnlyIfExists: editor.openOnlyIfExists,
            options: editor.options
          };
        })
      };
    }
    const { filesToOpenOrCreate, filesToDiff, filesToMerge } = this.Q;
    if (filesToOpenOrCreate || filesToDiff || filesToMerge) {
      return { filesToOpenOrCreate, filesToDiff, filesToMerge };
    }
    return void 0;
  }
  isRestored() {
    return this.Jb;
  }
  Kb() {
    const layoutReadyPromises = [];
    const layoutRestoredPromises = [];
    layoutReadyPromises.push((async () => {
      $S("code/willRestoreEditors");
      await this.Z.whenReady;
      $S("code/restoreEditors/editorGroupsReady");
      if (this.kb.initialization.layout?.editors) {
        this.Z.mainPart.applyLayout(this.kb.initialization.layout.editors);
      }
      const editors = await this.kb.initialization.editor.editorsToOpen;
      $S("code/restoreEditors/editorsToOpenResolved");
      let openEditorsPromise = void 0;
      if (editors.length) {
        const editorGroupsInVisualOrder = this.Z.mainPart.getGroups(
          2
          /* GroupsOrder.GRID_APPEARANCE */
        );
        const mapEditorsToGroup = /* @__PURE__ */ new Map();
        for (const editor of editors) {
          const group2 = editorGroupsInVisualOrder[(editor.viewColumn ?? 1) - 1];
          let editorsByGroup = mapEditorsToGroup.get(group2.id);
          if (!editorsByGroup) {
            editorsByGroup = /* @__PURE__ */ new Set();
            mapEditorsToGroup.set(group2.id, editorsByGroup);
          }
          editorsByGroup.add(editor.editor);
        }
        openEditorsPromise = Promise.all(Array.from(mapEditorsToGroup).map(async ([groupId, editors2]) => {
          try {
            await this.X.openEditors(Array.from(editors2), groupId, { validateTrust: true });
          } catch (error) {
            this.hb.error(error);
          }
        }));
      }
      layoutRestoredPromises.push(Promise.all([
        openEditorsPromise?.finally(() => $S("code/restoreEditors/editorsOpened")),
        this.Z.whenRestored.finally(() => $S("code/restoreEditors/editorGroupsRestored"))
      ]).finally(() => {
        $S("code/didRestoreEditors");
      }));
    })());
    const restoreDefaultViewsPromise = (async () => {
      if (this.kb.initialization.views.defaults?.length) {
        $S("code/willOpenDefaultViews");
        const locationsRestored = [];
        const tryOpenView = (view) => {
          const location3 = this.bb.getViewLocationById(view.id);
          if (location3 !== null) {
            const container2 = this.bb.getViewContainerByViewId(view.id);
            if (container2) {
              if (view.order >= (locationsRestored?.[location3]?.order ?? 0)) {
                locationsRestored[location3] = { id: container2.id, order: view.order };
              }
              const containerModel = this.bb.getViewContainerModel(container2);
              containerModel.setCollapsed(view.id, false);
              containerModel.setVisible(view.id, true);
              return true;
            }
          }
          return false;
        };
        const defaultViews = [...this.kb.initialization.views.defaults].reverse().map((v, index) => ({ id: v, order: index }));
        let i2 = defaultViews.length;
        while (i2) {
          i2--;
          if (tryOpenView(defaultViews[i2])) {
            defaultViews.splice(i2, 1);
          }
        }
        if (defaultViews.length) {
          await this.R.whenInstalledExtensionsRegistered();
          let i3 = defaultViews.length;
          while (i3) {
            i3--;
            if (tryOpenView(defaultViews[i3])) {
              defaultViews.splice(i3, 1);
            }
          }
        }
        if (locationsRestored[
          0
          /* ViewContainerLocation.Sidebar */
        ]) {
          this.kb.initialization.views.containerToRestore.sideBar = locationsRestored[
            0
            /* ViewContainerLocation.Sidebar */
          ].id;
        }
        if (locationsRestored[
          1
          /* ViewContainerLocation.Panel */
        ]) {
          this.kb.initialization.views.containerToRestore.panel = locationsRestored[
            1
            /* ViewContainerLocation.Panel */
          ].id;
        }
        if (locationsRestored[
          2
          /* ViewContainerLocation.AuxiliaryBar */
        ]) {
          this.kb.initialization.views.containerToRestore.auxiliaryBar = locationsRestored[
            2
            /* ViewContainerLocation.AuxiliaryBar */
          ].id;
        }
        $S("code/didOpenDefaultViews");
      }
    })();
    layoutReadyPromises.push(restoreDefaultViewsPromise);
    layoutReadyPromises.push((async () => {
      await restoreDefaultViewsPromise;
      if (!this.kb.initialization.views.containerToRestore.sideBar) {
        return;
      }
      $S("code/willRestoreViewlet");
      const viewlet = await this.$.openPaneComposite(
        this.kb.initialization.views.containerToRestore.sideBar,
        0
        /* ViewContainerLocation.Sidebar */
      );
      if (!viewlet) {
        await this.$.openPaneComposite(
          this.bb.getDefaultViewContainer(
            0
            /* ViewContainerLocation.Sidebar */
          )?.id,
          0
          /* ViewContainerLocation.Sidebar */
        );
      }
      $S("code/didRestoreViewlet");
    })());
    layoutReadyPromises.push((async () => {
      await restoreDefaultViewsPromise;
      if (!this.kb.initialization.views.containerToRestore.panel) {
        return;
      }
      $S("code/willRestorePanel");
      const panel = await this.$.openPaneComposite(
        this.kb.initialization.views.containerToRestore.panel,
        1
        /* ViewContainerLocation.Panel */
      );
      if (!panel) {
        await this.$.openPaneComposite(
          this.bb.getDefaultViewContainer(
            1
            /* ViewContainerLocation.Panel */
          )?.id,
          1
          /* ViewContainerLocation.Panel */
        );
      }
      $S("code/didRestorePanel");
    })());
    layoutReadyPromises.push((async () => {
      await restoreDefaultViewsPromise;
      if (!this.kb.initialization.views.containerToRestore.auxiliaryBar) {
        return;
      }
      $S("code/willRestoreAuxiliaryBar");
      const panel = await this.$.openPaneComposite(
        this.kb.initialization.views.containerToRestore.auxiliaryBar,
        2
        /* ViewContainerLocation.AuxiliaryBar */
      );
      if (!panel) {
        await this.$.openPaneComposite(
          this.bb.getDefaultViewContainer(
            2
            /* ViewContainerLocation.AuxiliaryBar */
          )?.id,
          2
          /* ViewContainerLocation.AuxiliaryBar */
        );
      }
      $S("code/didRestoreAuxiliaryBar");
    })());
    const zenModeWasActive = this.Ob();
    const restoreZenMode = getZenModeConfiguration(this.S).restore;
    if (zenModeWasActive) {
      this.Pb(!restoreZenMode);
      this.toggleZenMode(false, true);
    }
    if (this.lb.getRuntimeValue(LayoutStateKeys.MAIN_EDITOR_CENTERED)) {
      this.centerMainEditorLayout(true, true);
    }
    Promises.settled(layoutReadyPromises).finally(() => {
      this.Gb.complete();
      Promises.settled(layoutRestoredPromises).finally(() => {
        this.Jb = true;
        this.Ib.complete();
      });
    });
  }
  registerPart(part) {
    const id2 = part.getId();
    this.D.set(id2, part);
    return $1c(() => this.D.delete(id2));
  }
  Lb(key2) {
    const part = this.D.get(key2);
    if (!part) {
      throw new Error(`Unknown part ${key2}`);
    }
    return part;
  }
  registerNotifications(delegate) {
    this.B(delegate.onDidChangeNotificationsVisibility((visible) => this.j.fire(visible)));
  }
  hasFocus(part) {
    const container2 = this.getContainer($Qj(), part);
    if (!container2) {
      return false;
    }
    const activeElement = $Lj();
    if (!activeElement) {
      return false;
    }
    return $Fj(activeElement, container2);
  }
  focusPart(part, targetWindow = $Y) {
    const container2 = this.getContainer(targetWindow, part) ?? this.mainContainer;
    switch (part) {
      case "workbench.parts.editor":
        this.Z.getPart(container2).activeGroup.focus();
        break;
      case "workbench.parts.panel": {
        this.$.getActivePaneComposite(
          1
          /* ViewContainerLocation.Panel */
        )?.focus();
        break;
      }
      case "workbench.parts.sidebar": {
        this.$.getActivePaneComposite(
          0
          /* ViewContainerLocation.Sidebar */
        )?.focus();
        break;
      }
      case "workbench.parts.auxiliarybar": {
        this.$.getActivePaneComposite(
          2
          /* ViewContainerLocation.AuxiliaryBar */
        )?.focus();
        break;
      }
      case "workbench.parts.activitybar":
        this.Lb(
          "workbench.parts.sidebar"
          /* Parts.SIDEBAR_PART */
        ).focusActivityBar();
        break;
      case "workbench.parts.statusbar":
        this.gb.getPart(container2).focus();
        break;
      default: {
        container2?.focus();
      }
    }
  }
  getContainer(targetWindow, part) {
    if (typeof part === "undefined") {
      return this.u(targetWindow.document);
    }
    if (targetWindow === $Y) {
      return this.Lb(part).getContainer();
    }
    let partCandidate;
    if (part === "workbench.parts.editor") {
      partCandidate = this.Z.getPart(this.u(targetWindow.document));
    } else if (part === "workbench.parts.statusbar") {
      partCandidate = this.gb.getPart(this.u(targetWindow.document));
    } else if (part === "workbench.parts.titlebar") {
      partCandidate = this.ab.getPart(this.u(targetWindow.document));
    }
    if (partCandidate instanceof Part) {
      return partCandidate.getContainer();
    }
    return void 0;
  }
  isVisible(part, targetWindow = $Y) {
    if (targetWindow !== $Y && part === "workbench.parts.editor") {
      return true;
    }
    if (this.F) {
      switch (part) {
        case "workbench.parts.titlebar":
          return this.G.isViewVisible(this.H);
        case "workbench.parts.sidebar":
          return !this.lb.getRuntimeValue(LayoutStateKeys.SIDEBAR_HIDDEN);
        case "workbench.parts.panel":
          return !this.lb.getRuntimeValue(LayoutStateKeys.PANEL_HIDDEN);
        case "workbench.parts.auxiliarybar":
          return !this.lb.getRuntimeValue(LayoutStateKeys.AUXILIARYBAR_HIDDEN);
        case "workbench.parts.statusbar":
          return !this.lb.getRuntimeValue(LayoutStateKeys.STATUSBAR_HIDDEN);
        case "workbench.parts.activitybar":
          return !this.lb.getRuntimeValue(LayoutStateKeys.ACTIVITYBAR_HIDDEN);
        case "workbench.parts.editor":
          return !this.lb.getRuntimeValue(LayoutStateKeys.EDITOR_HIDDEN);
        case "workbench.parts.banner":
          return this.G.isViewVisible(this.I);
        default:
          return false;
      }
    }
    switch (part) {
      case "workbench.parts.titlebar":
        return $1lb(this.S, $Y, this.kb.runtime.menuBar.toggled);
      case "workbench.parts.sidebar":
        return !this.lb.getRuntimeValue(LayoutStateKeys.SIDEBAR_HIDDEN);
      case "workbench.parts.panel":
        return !this.lb.getRuntimeValue(LayoutStateKeys.PANEL_HIDDEN);
      case "workbench.parts.auxiliarybar":
        return !this.lb.getRuntimeValue(LayoutStateKeys.AUXILIARYBAR_HIDDEN);
      case "workbench.parts.statusbar":
        return !this.lb.getRuntimeValue(LayoutStateKeys.STATUSBAR_HIDDEN);
      case "workbench.parts.activitybar":
        return !this.lb.getRuntimeValue(LayoutStateKeys.ACTIVITYBAR_HIDDEN);
      case "workbench.parts.editor":
        return !this.lb.getRuntimeValue(LayoutStateKeys.EDITOR_HIDDEN);
      default:
        return false;
    }
  }
  Mb() {
    return $r && !$3e();
  }
  focus() {
    this.focusPart("workbench.parts.editor", getWindow(this.activeContainer));
  }
  Nb() {
    const activePanel = this.$.getActivePaneComposite(
      1
      /* ViewContainerLocation.Panel */
    );
    if ((this.hasFocus(
      "workbench.parts.panel"
      /* Parts.PANEL_PART */
    ) || !this.isVisible(
      "workbench.parts.editor"
      /* Parts.EDITOR_PART */
    )) && activePanel) {
      activePanel.focus();
    } else {
      this.focus();
    }
  }
  getMaximumEditorDimensions(container2) {
    const targetWindow = getWindow(container2);
    const containerDimension = this.z(container2);
    if (container2 === this.mainContainer) {
      const isPanelHorizontal = $Wlb(this.getPanelPosition());
      const takenWidth = (this.isVisible(
        "workbench.parts.activitybar"
        /* Parts.ACTIVITYBAR_PART */
      ) ? this.J.minimumWidth : 0) + (this.isVisible(
        "workbench.parts.sidebar"
        /* Parts.SIDEBAR_PART */
      ) ? this.L.minimumWidth : 0) + (this.isVisible(
        "workbench.parts.panel"
        /* Parts.PANEL_PART */
      ) && !isPanelHorizontal ? this.M.minimumWidth : 0) + (this.isVisible(
        "workbench.parts.auxiliarybar"
        /* Parts.AUXILIARYBAR_PART */
      ) ? this.N.minimumWidth : 0);
      const takenHeight = (this.isVisible("workbench.parts.titlebar", targetWindow) ? this.H.minimumHeight : 0) + (this.isVisible("workbench.parts.statusbar", targetWindow) ? this.P.minimumHeight : 0) + (this.isVisible(
        "workbench.parts.panel"
        /* Parts.PANEL_PART */
      ) && isPanelHorizontal ? this.M.minimumHeight : 0);
      const availableWidth = containerDimension.width - takenWidth;
      const availableHeight = containerDimension.height - takenHeight;
      return { width: availableWidth, height: availableHeight };
    } else {
      const takenHeight = (this.isVisible("workbench.parts.titlebar", targetWindow) ? this.H.minimumHeight : 0) + (this.isVisible("workbench.parts.statusbar", targetWindow) ? this.P.minimumHeight : 0);
      return { width: containerDimension.width, height: containerDimension.height - takenHeight };
    }
  }
  Ob() {
    return this.lb.getRuntimeValue(LayoutStateKeys.ZEN_MODE_ACTIVE);
  }
  Pb(active) {
    this.lb.setRuntimeValue(LayoutStateKeys.ZEN_MODE_ACTIVE, active);
  }
  toggleZenMode(skipLayout, restoring = false) {
    this.Pb(!this.Ob());
    this.kb.runtime.zenMode.transitionDisposables.clearAndDisposeAll();
    const setLineNumbers = (lineNumbers) => {
      for (const editor of this.Y.visibleTextEditorControls) {
        if (!lineNumbers && $P5(editor) && editor.hasModel()) {
          const model = editor.getModel();
          lineNumbers = this.S.getValue("editor.lineNumbers", { resource: model.uri, overrideIdentifier: model.getLanguageId() });
        }
        if (!lineNumbers) {
          lineNumbers = this.S.getValue("editor.lineNumbers");
        }
        editor.updateOptions({ lineNumbers });
      }
    };
    let toggleMainWindowFullScreen = false;
    const config = getZenModeConfiguration(this.S);
    const zenModeExitInfo = this.lb.getRuntimeValue(LayoutStateKeys.ZEN_MODE_EXIT_INFO);
    if (this.Ob()) {
      toggleMainWindowFullScreen = !this.kb.runtime.mainWindowFullscreen && config.fullScreen && !$u;
      if (!restoring) {
        zenModeExitInfo.transitionedToFullScreen = toggleMainWindowFullScreen;
        zenModeExitInfo.transitionedToCenteredEditorLayout = !this.isMainEditorLayoutCentered() && config.centerLayout;
        zenModeExitInfo.handleNotificationsDoNotDisturbMode = this.eb.getFilter() === NotificationsFilter.OFF;
        zenModeExitInfo.wasVisible.sideBar = this.isVisible(
          "workbench.parts.sidebar"
          /* Parts.SIDEBAR_PART */
        );
        zenModeExitInfo.wasVisible.panel = this.isVisible(
          "workbench.parts.panel"
          /* Parts.PANEL_PART */
        );
        zenModeExitInfo.wasVisible.auxiliaryBar = this.isVisible(
          "workbench.parts.auxiliarybar"
          /* Parts.AUXILIARYBAR_PART */
        );
        this.lb.setRuntimeValue(LayoutStateKeys.ZEN_MODE_EXIT_INFO, zenModeExitInfo);
      }
      this.Yb(true, true);
      this.$b(true, true);
      this.Vb(true, true);
      if (config.hideActivityBar) {
        this.Sb(true, true);
      }
      if (config.hideStatusBar) {
        this.Qb(true, true);
      }
      if (config.hideLineNumbers) {
        setLineNumbers("off");
        this.kb.runtime.zenMode.transitionDisposables.set("zenMode.hideLineNumbers", this.Y.onDidVisibleEditorsChange(() => setLineNumbers("off")));
      }
      if (config.showTabs !== this.Z.partOptions.showTabs) {
        this.kb.runtime.zenMode.transitionDisposables.set("zenMode.showTabs", this.Z.mainPart.enforcePartOptions({ showTabs: config.showTabs }));
      }
      if (config.silentNotifications && zenModeExitInfo.handleNotificationsDoNotDisturbMode) {
        this.eb.setFilter(NotificationsFilter.ERROR);
      }
      if (config.centerLayout) {
        this.centerMainEditorLayout(true, true);
      }
      this.kb.runtime.zenMode.transitionDisposables.set("configurationChange", this.S.onDidChangeConfiguration((e) => {
        if (e.affectsConfiguration(
          "zenMode.hideActivityBar"
          /* ZenModeSettings.HIDE_ACTIVITYBAR */
        )) {
          const zenModeHideActivityBar = this.S.getValue(
            "zenMode.hideActivityBar"
            /* ZenModeSettings.HIDE_ACTIVITYBAR */
          );
          this.Sb(zenModeHideActivityBar, true);
        }
        if (e.affectsConfiguration(
          "zenMode.hideStatusBar"
          /* ZenModeSettings.HIDE_STATUSBAR */
        )) {
          const zenModeHideStatusBar = this.S.getValue(
            "zenMode.hideStatusBar"
            /* ZenModeSettings.HIDE_STATUSBAR */
          );
          this.Qb(zenModeHideStatusBar, true);
        }
        if (e.affectsConfiguration(
          "zenMode.centerLayout"
          /* ZenModeSettings.CENTER_LAYOUT */
        )) {
          const zenModeCenterLayout = this.S.getValue(
            "zenMode.centerLayout"
            /* ZenModeSettings.CENTER_LAYOUT */
          );
          this.centerMainEditorLayout(zenModeCenterLayout, true);
        }
        if (e.affectsConfiguration(
          "zenMode.showTabs"
          /* ZenModeSettings.SHOW_TABS */
        )) {
          const zenModeShowTabs = this.S.getValue(
            "zenMode.showTabs"
            /* ZenModeSettings.SHOW_TABS */
          ) ?? "multiple";
          this.kb.runtime.zenMode.transitionDisposables.set("zenMode.showTabs", this.Z.mainPart.enforcePartOptions({ showTabs: zenModeShowTabs }));
        }
        if (e.affectsConfiguration(
          "zenMode.silentNotifications"
          /* ZenModeSettings.SILENT_NOTIFICATIONS */
        )) {
          const zenModeSilentNotifications = !!this.S.getValue(
            "zenMode.silentNotifications"
            /* ZenModeSettings.SILENT_NOTIFICATIONS */
          );
          if (zenModeExitInfo.handleNotificationsDoNotDisturbMode) {
            this.eb.setFilter(zenModeSilentNotifications ? NotificationsFilter.ERROR : NotificationsFilter.OFF);
          }
        }
        if (e.affectsConfiguration(
          "zenMode.hideLineNumbers"
          /* ZenModeSettings.HIDE_LINENUMBERS */
        )) {
          const lineNumbersType = this.S.getValue(
            "zenMode.hideLineNumbers"
            /* ZenModeSettings.HIDE_LINENUMBERS */
          ) ? "off" : void 0;
          setLineNumbers(lineNumbersType);
          this.kb.runtime.zenMode.transitionDisposables.set("zenMode.hideLineNumbers", this.Y.onDidVisibleEditorsChange(() => setLineNumbers(lineNumbersType)));
        }
      }));
    } else {
      if (zenModeExitInfo.wasVisible.panel) {
        this.Yb(false, true);
      }
      if (zenModeExitInfo.wasVisible.auxiliaryBar) {
        this.$b(false, true);
      }
      if (zenModeExitInfo.wasVisible.sideBar) {
        this.Vb(false, true);
      }
      if (!this.lb.getRuntimeValue(LayoutStateKeys.ACTIVITYBAR_HIDDEN, true)) {
        this.Sb(false, true);
      }
      if (!this.lb.getRuntimeValue(LayoutStateKeys.STATUSBAR_HIDDEN, true)) {
        this.Qb(false, true);
      }
      if (zenModeExitInfo.transitionedToCenteredEditorLayout) {
        this.centerMainEditorLayout(false, true);
      }
      if (zenModeExitInfo.handleNotificationsDoNotDisturbMode) {
        this.eb.setFilter(NotificationsFilter.OFF);
      }
      setLineNumbers();
      this.focus();
      toggleMainWindowFullScreen = zenModeExitInfo.transitionedToFullScreen && this.kb.runtime.mainWindowFullscreen;
    }
    if (!skipLayout) {
      this.layout();
    }
    if (toggleMainWindowFullScreen) {
      this.W.toggleFullScreen($Y);
    }
    this.a.fire(this.Ob());
  }
  Qb(hidden, skipLayout) {
    this.lb.setRuntimeValue(LayoutStateKeys.STATUSBAR_HIDDEN, hidden);
    if (hidden) {
      this.mainContainer.classList.add(LayoutClasses.STATUSBAR_HIDDEN);
    } else {
      this.mainContainer.classList.remove(LayoutClasses.STATUSBAR_HIDDEN);
    }
    this.G.setViewVisible(this.P, !hidden);
  }
  Rb() {
    const titleBar = this.Lb(
      "workbench.parts.titlebar"
      /* Parts.TITLEBAR_PART */
    );
    const bannerPart = this.Lb(
      "workbench.parts.banner"
      /* Parts.BANNER_PART */
    );
    const editorPart = this.Lb(
      "workbench.parts.editor"
      /* Parts.EDITOR_PART */
    );
    const activityBar = this.Lb(
      "workbench.parts.activitybar"
      /* Parts.ACTIVITYBAR_PART */
    );
    const panelPart = this.Lb(
      "workbench.parts.panel"
      /* Parts.PANEL_PART */
    );
    const auxiliaryBarPart = this.Lb(
      "workbench.parts.auxiliarybar"
      /* Parts.AUXILIARYBAR_PART */
    );
    const sideBar = this.Lb(
      "workbench.parts.sidebar"
      /* Parts.SIDEBAR_PART */
    );
    const statusBar = this.Lb(
      "workbench.parts.statusbar"
      /* Parts.STATUSBAR_PART */
    );
    this.H = titleBar;
    this.I = bannerPart;
    this.L = sideBar;
    this.J = activityBar;
    this.O = editorPart;
    this.M = panelPart;
    this.N = auxiliaryBarPart;
    this.P = statusBar;
    const viewMap = {
      [
        "workbench.parts.activitybar"
        /* Parts.ACTIVITYBAR_PART */
      ]: this.J,
      [
        "workbench.parts.banner"
        /* Parts.BANNER_PART */
      ]: this.I,
      [
        "workbench.parts.titlebar"
        /* Parts.TITLEBAR_PART */
      ]: this.H,
      [
        "workbench.parts.editor"
        /* Parts.EDITOR_PART */
      ]: this.O,
      [
        "workbench.parts.panel"
        /* Parts.PANEL_PART */
      ]: this.M,
      [
        "workbench.parts.sidebar"
        /* Parts.SIDEBAR_PART */
      ]: this.L,
      [
        "workbench.parts.statusbar"
        /* Parts.STATUSBAR_PART */
      ]: this.P,
      [
        "workbench.parts.auxiliarybar"
        /* Parts.AUXILIARYBAR_PART */
      ]: this.N
    };
    const fromJSON = ({ type }) => viewMap[type];
    const workbenchGrid = $y2.deserialize(this.dc(), { fromJSON }, { proportionalLayout: false });
    this.mainContainer.prepend(workbenchGrid.element);
    this.mainContainer.setAttribute("role", "application");
    this.G = workbenchGrid;
    this.G.edgeSnapping = this.kb.runtime.mainWindowFullscreen;
    for (const part of [titleBar, editorPart, activityBar, panelPart, sideBar, statusBar, auxiliaryBarPart, bannerPart]) {
      this.B(part.onDidVisibilityChange((visible) => {
        if (part === sideBar) {
          this.Vb(!visible, true);
        } else if (part === panelPart) {
          this.Yb(!visible, true);
        } else if (part === auxiliaryBarPart) {
          this.$b(!visible, true);
        } else if (part === editorPart) {
          this.Ub(!visible, true);
        }
        this.h.fire();
        this.rb(this.mainContainer, this.y);
      }));
    }
    this.B(this.U.onWillSaveState((e) => {
      const sideBarSize = this.lb.getRuntimeValue(LayoutStateKeys.SIDEBAR_HIDDEN) ? this.G.getViewCachedVisibleSize(this.L) : this.G.getViewSize(this.L).width;
      this.lb.setInitializationValue(LayoutStateKeys.SIDEBAR_SIZE, sideBarSize);
      const panelSize = this.lb.getRuntimeValue(LayoutStateKeys.PANEL_HIDDEN) ? this.G.getViewCachedVisibleSize(this.M) : $Wlb(this.lb.getRuntimeValue(LayoutStateKeys.PANEL_POSITION)) ? this.G.getViewSize(this.M).height : this.G.getViewSize(this.M).width;
      this.lb.setInitializationValue(LayoutStateKeys.PANEL_SIZE, panelSize);
      const auxiliaryBarSize = this.lb.getRuntimeValue(LayoutStateKeys.AUXILIARYBAR_HIDDEN) ? this.G.getViewCachedVisibleSize(this.N) : this.G.getViewSize(this.N).width;
      this.lb.setInitializationValue(LayoutStateKeys.AUXILIARYBAR_SIZE, auxiliaryBarSize);
      this.lb.save(true, true);
    }));
  }
  layout() {
    if (!this.mb) {
      this.y = $qj(
        this.kb.runtime.mainWindowFullscreen ? $Y.document.body : (
          // in fullscreen mode, make sure to use <body> element because
          this.nb
        )
        // in that case the workbench will span the entire site
      );
      this.hb.trace(`Layout#layout, height: ${this.y.height}, width: ${this.y.width}`);
      $uj(this.mainContainer, 0, 0, 0, 0, "relative");
      $tj(this.mainContainer, this.y.width, this.y.height);
      this.G.layout(this.y.width, this.y.height);
      this.F = true;
      this.rb(this.mainContainer, this.y);
    }
  }
  isMainEditorLayoutCentered() {
    return this.lb.getRuntimeValue(LayoutStateKeys.MAIN_EDITOR_CENTERED);
  }
  centerMainEditorLayout(active, skipLayout) {
    this.lb.setRuntimeValue(LayoutStateKeys.MAIN_EDITOR_CENTERED, active);
    const activeMainEditor = this.Y.activeEditor;
    let isEditorComplex = false;
    if (activeMainEditor instanceof $fub) {
      isEditorComplex = this.S.getValue("diffEditor.renderSideBySide");
    } else if (activeMainEditor?.hasCapability(
      256
      /* EditorInputCapabilities.MultipleEditors */
    )) {
      isEditorComplex = true;
    }
    const isCenteredLayoutAutoResizing = this.S.getValue("workbench.editor.centeredLayoutAutoResize");
    if (isCenteredLayoutAutoResizing && (this.Z.mainPart.groups.length > 1 && !this.Z.mainPart.hasMaximizedGroup() || isEditorComplex)) {
      active = false;
    }
    if (this.Z.mainPart.isLayoutCentered() !== active) {
      this.Z.mainPart.centerLayout(active);
      if (!skipLayout) {
        this.layout();
      }
    }
    this.b.fire(this.lb.getRuntimeValue(LayoutStateKeys.MAIN_EDITOR_CENTERED));
  }
  getSize(part) {
    return this.G.getViewSize(this.Lb(part));
  }
  setSize(part, size) {
    this.G.resizeView(this.Lb(part), size);
  }
  resizePart(part, sizeChangeWidth, sizeChangeHeight) {
    const sizeChangePxWidth = Math.sign(sizeChangeWidth) * $mk($Qj(), Math.abs(sizeChangeWidth));
    const sizeChangePxHeight = Math.sign(sizeChangeHeight) * $mk($Qj(), Math.abs(sizeChangeHeight));
    let viewSize;
    switch (part) {
      case "workbench.parts.sidebar":
        viewSize = this.G.getViewSize(this.L);
        this.G.resizeView(this.L, {
          width: viewSize.width + sizeChangePxWidth,
          height: viewSize.height
        });
        break;
      case "workbench.parts.panel":
        viewSize = this.G.getViewSize(this.M);
        this.G.resizeView(this.M, {
          width: viewSize.width + ($Wlb(this.getPanelPosition()) ? 0 : sizeChangePxWidth),
          height: viewSize.height + ($Wlb(this.getPanelPosition()) ? sizeChangePxHeight : 0)
        });
        break;
      case "workbench.parts.auxiliarybar":
        viewSize = this.G.getViewSize(this.N);
        this.G.resizeView(this.N, {
          width: viewSize.width + sizeChangePxWidth,
          height: viewSize.height
        });
        break;
      case "workbench.parts.editor":
        viewSize = this.G.getViewSize(this.O);
        if (this.Z.mainPart.count === 1) {
          this.G.resizeView(this.O, {
            width: viewSize.width + sizeChangePxWidth,
            height: viewSize.height + sizeChangePxHeight
          });
        } else {
          const activeGroup = this.Z.mainPart.activeGroup;
          const { width: width2, height } = this.Z.mainPart.getSize(activeGroup);
          this.Z.mainPart.setSize(activeGroup, { width: width2 + sizeChangePxWidth, height: height + sizeChangePxHeight });
          const { width: newWidth, height: newHeight } = this.Z.mainPart.getSize(activeGroup);
          if (sizeChangePxHeight && height === newHeight || sizeChangePxWidth && width2 === newWidth) {
            this.G.resizeView(this.O, {
              width: viewSize.width + (sizeChangePxWidth && width2 === newWidth ? sizeChangePxWidth : 0),
              height: viewSize.height + (sizeChangePxHeight && height === newHeight ? sizeChangePxHeight : 0)
            });
          }
        }
        break;
      default:
        return;
    }
  }
  Sb(hidden, skipLayout) {
    this.lb.setRuntimeValue(LayoutStateKeys.ACTIVITYBAR_HIDDEN, hidden);
    this.G.setViewVisible(this.J, !hidden);
  }
  Tb(hidden) {
    this.G.setViewVisible(this.I, !hidden);
  }
  Ub(hidden, skipLayout) {
    this.lb.setRuntimeValue(LayoutStateKeys.EDITOR_HIDDEN, hidden);
    if (hidden) {
      this.mainContainer.classList.add(LayoutClasses.MAIN_EDITOR_AREA_HIDDEN);
    } else {
      this.mainContainer.classList.remove(LayoutClasses.MAIN_EDITOR_AREA_HIDDEN);
    }
    this.G.setViewVisible(this.O, !hidden);
    if (hidden && !this.isVisible(
      "workbench.parts.panel"
      /* Parts.PANEL_PART */
    )) {
      this.Yb(false, true);
    }
  }
  getLayoutClasses() {
    return $Mb([
      !this.isVisible(
        "workbench.parts.sidebar"
        /* Parts.SIDEBAR_PART */
      ) ? LayoutClasses.SIDEBAR_HIDDEN : void 0,
      !this.isVisible("workbench.parts.editor", $Y) ? LayoutClasses.MAIN_EDITOR_AREA_HIDDEN : void 0,
      !this.isVisible(
        "workbench.parts.panel"
        /* Parts.PANEL_PART */
      ) ? LayoutClasses.PANEL_HIDDEN : void 0,
      !this.isVisible(
        "workbench.parts.auxiliarybar"
        /* Parts.AUXILIARYBAR_PART */
      ) ? LayoutClasses.AUXILIARYBAR_HIDDEN : void 0,
      !this.isVisible(
        "workbench.parts.statusbar"
        /* Parts.STATUSBAR_PART */
      ) ? LayoutClasses.STATUSBAR_HIDDEN : void 0,
      this.kb.runtime.mainWindowFullscreen ? LayoutClasses.FULLSCREEN : void 0
    ]);
  }
  Vb(hidden, skipLayout) {
    this.lb.setRuntimeValue(LayoutStateKeys.SIDEBAR_HIDDEN, hidden);
    if (hidden) {
      this.mainContainer.classList.add(LayoutClasses.SIDEBAR_HIDDEN);
    } else {
      this.mainContainer.classList.remove(LayoutClasses.SIDEBAR_HIDDEN);
    }
    if (hidden && this.$.getActivePaneComposite(
      0
      /* ViewContainerLocation.Sidebar */
    )) {
      this.$.hideActivePaneComposite(
        0
        /* ViewContainerLocation.Sidebar */
      );
      this.Nb();
    } else if (!hidden && !this.$.getActivePaneComposite(
      0
      /* ViewContainerLocation.Sidebar */
    )) {
      const viewletToOpen = this.$.getLastActivePaneCompositeId(
        0
        /* ViewContainerLocation.Sidebar */
      );
      if (viewletToOpen) {
        const viewlet = this.$.openPaneComposite(viewletToOpen, 0, true);
        if (!viewlet) {
          this.$.openPaneComposite(this.bb.getDefaultViewContainer(
            0
            /* ViewContainerLocation.Sidebar */
          )?.id, 0, true);
        }
      }
    }
    this.G.setViewVisible(this.L, !hidden);
  }
  Wb(id2) {
    const viewContainer5 = this.bb.getViewContainerById(id2);
    if (!viewContainer5) {
      return false;
    }
    const viewContainerModel = this.bb.getViewContainerModel(viewContainer5);
    if (!viewContainerModel) {
      return false;
    }
    return viewContainerModel.activeViewDescriptors.length >= 1;
  }
  Xb(sideBarPosition, panelAlignment, panelPosition) {
    const isPanelVertical = !$Wlb(panelPosition);
    const sideBarSiblingToEditor = isPanelVertical || !(panelAlignment === "center" || sideBarPosition === 0 && panelAlignment === "right" || sideBarPosition === 1 && panelAlignment === "left");
    const auxiliaryBarSiblingToEditor = isPanelVertical || !(panelAlignment === "center" || sideBarPosition === 1 && panelAlignment === "right" || sideBarPosition === 0 && panelAlignment === "left");
    const preMovePanelWidth = !this.isVisible(
      "workbench.parts.panel"
      /* Parts.PANEL_PART */
    ) ? Sizing2.Invisible(this.G.getViewCachedVisibleSize(this.M) ?? this.M.minimumWidth) : this.G.getViewSize(this.M).width;
    const preMovePanelHeight = !this.isVisible(
      "workbench.parts.panel"
      /* Parts.PANEL_PART */
    ) ? Sizing2.Invisible(this.G.getViewCachedVisibleSize(this.M) ?? this.M.minimumHeight) : this.G.getViewSize(this.M).height;
    const preMoveSideBarSize = !this.isVisible(
      "workbench.parts.sidebar"
      /* Parts.SIDEBAR_PART */
    ) ? Sizing2.Invisible(this.G.getViewCachedVisibleSize(this.L) ?? this.L.minimumWidth) : this.G.getViewSize(this.L).width;
    const preMoveAuxiliaryBarSize = !this.isVisible(
      "workbench.parts.auxiliarybar"
      /* Parts.AUXILIARYBAR_PART */
    ) ? Sizing2.Invisible(this.G.getViewCachedVisibleSize(this.N) ?? this.N.minimumWidth) : this.G.getViewSize(this.N).width;
    if (sideBarPosition === 0) {
      this.G.moveViewTo(this.J, [2, 0]);
      this.G.moveView(
        this.L,
        preMoveSideBarSize,
        sideBarSiblingToEditor ? this.O : this.J,
        sideBarSiblingToEditor ? 2 : 3
        /* Direction.Right */
      );
      if (auxiliaryBarSiblingToEditor) {
        this.G.moveView(
          this.N,
          preMoveAuxiliaryBarSize,
          this.O,
          3
          /* Direction.Right */
        );
      } else {
        this.G.moveViewTo(this.N, [2, -1]);
      }
    } else {
      this.G.moveViewTo(this.J, [2, -1]);
      this.G.moveView(
        this.L,
        preMoveSideBarSize,
        sideBarSiblingToEditor ? this.O : this.J,
        sideBarSiblingToEditor ? 3 : 2
        /* Direction.Left */
      );
      if (auxiliaryBarSiblingToEditor) {
        this.G.moveView(
          this.N,
          preMoveAuxiliaryBarSize,
          this.O,
          2
          /* Direction.Left */
        );
      } else {
        this.G.moveViewTo(this.N, [2, 0]);
      }
    }
    if (isPanelVertical) {
      this.G.moveView(
        this.M,
        preMovePanelWidth,
        this.O,
        panelPosition === 0 ? 2 : 3
        /* Direction.Right */
      );
      this.G.resizeView(this.M, {
        height: preMovePanelHeight,
        width: preMovePanelWidth
      });
    }
    if (this.isVisible(
      "workbench.parts.sidebar"
      /* Parts.SIDEBAR_PART */
    )) {
      this.G.resizeView(this.L, {
        height: this.G.getViewSize(this.L).height,
        width: preMoveSideBarSize
      });
    }
    if (this.isVisible(
      "workbench.parts.auxiliarybar"
      /* Parts.AUXILIARYBAR_PART */
    )) {
      this.G.resizeView(this.N, {
        height: this.G.getViewSize(this.N).height,
        width: preMoveAuxiliaryBarSize
      });
    }
  }
  setPanelAlignment(alignment, skipLayout) {
    if (!$Wlb(this.getPanelPosition())) {
      this.setPanelPosition(
        2
        /* Position.BOTTOM */
      );
    }
    if (alignment !== "center" && this.isPanelMaximized()) {
      this.toggleMaximizedPanel();
    }
    this.lb.setRuntimeValue(LayoutStateKeys.PANEL_ALIGNMENT, alignment);
    this.Xb(this.getSideBarPosition(), alignment, this.getPanelPosition());
    this.c.fire(alignment);
  }
  Yb(hidden, skipLayout) {
    if (!this.G) {
      return;
    }
    const wasHidden = !this.isVisible(
      "workbench.parts.panel"
      /* Parts.PANEL_PART */
    );
    this.lb.setRuntimeValue(LayoutStateKeys.PANEL_HIDDEN, hidden);
    const isPanelMaximized = this.isPanelMaximized();
    const panelOpensMaximized = this.Zb();
    if (hidden) {
      this.mainContainer.classList.add(LayoutClasses.PANEL_HIDDEN);
    } else {
      this.mainContainer.classList.remove(LayoutClasses.PANEL_HIDDEN);
    }
    let focusEditor = false;
    if (hidden && this.$.getActivePaneComposite(
      1
      /* ViewContainerLocation.Panel */
    )) {
      this.$.hideActivePaneComposite(
        1
        /* ViewContainerLocation.Panel */
      );
      focusEditor = $u ? false : true;
    } else if (!hidden && !this.$.getActivePaneComposite(
      1
      /* ViewContainerLocation.Panel */
    )) {
      let panelToOpen = this.$.getLastActivePaneCompositeId(
        1
        /* ViewContainerLocation.Panel */
      );
      if (!panelToOpen || !this.Wb(panelToOpen)) {
        panelToOpen = this.bb.getViewContainersByLocation(
          1
          /* ViewContainerLocation.Panel */
        ).find((viewContainer5) => this.Wb(viewContainer5.id))?.id;
      }
      if (panelToOpen) {
        const focus = !skipLayout;
        this.$.openPaneComposite(panelToOpen, 1, focus);
      }
    }
    if (hidden && isPanelMaximized) {
      this.toggleMaximizedPanel();
    }
    if (wasHidden === hidden) {
      return;
    }
    this.G.setViewVisible(this.M, !hidden);
    if (!hidden) {
      if (!skipLayout && isPanelMaximized !== panelOpensMaximized) {
        this.toggleMaximizedPanel();
      }
    } else {
      this.lb.setRuntimeValue(LayoutStateKeys.PANEL_WAS_LAST_MAXIMIZED, isPanelMaximized);
    }
    if (focusEditor) {
      this.Z.mainPart.activeGroup.focus();
    }
  }
  toggleMaximizedPanel() {
    const size = this.G.getViewSize(this.M);
    const panelPosition = this.getPanelPosition();
    const isMaximized = this.isPanelMaximized();
    if (!isMaximized) {
      if (this.isVisible(
        "workbench.parts.panel"
        /* Parts.PANEL_PART */
      )) {
        if ($Wlb(panelPosition)) {
          this.lb.setRuntimeValue(LayoutStateKeys.PANEL_LAST_NON_MAXIMIZED_HEIGHT, size.height);
        } else {
          this.lb.setRuntimeValue(LayoutStateKeys.PANEL_LAST_NON_MAXIMIZED_WIDTH, size.width);
        }
      }
      this.Ub(true);
    } else {
      this.Ub(false);
      this.G.resizeView(this.M, {
        width: $Wlb(panelPosition) ? size.width : this.lb.getRuntimeValue(LayoutStateKeys.PANEL_LAST_NON_MAXIMIZED_WIDTH),
        height: $Wlb(panelPosition) ? this.lb.getRuntimeValue(LayoutStateKeys.PANEL_LAST_NON_MAXIMIZED_HEIGHT) : size.height
      });
    }
    this.lb.setRuntimeValue(LayoutStateKeys.PANEL_WAS_LAST_MAXIMIZED, !isMaximized);
  }
  Zb() {
    if (this.getPanelAlignment() !== "center" && $Wlb(this.getPanelPosition())) {
      return false;
    }
    const panelOpensMaximized = $Zlb(this.S.getValue(WorkbenchLayoutSettings.PANEL_OPENS_MAXIMIZED));
    const panelLastIsMaximized = this.lb.getRuntimeValue(LayoutStateKeys.PANEL_WAS_LAST_MAXIMIZED);
    return panelOpensMaximized === 0 || panelOpensMaximized === 2 && panelLastIsMaximized;
  }
  $b(hidden, skipLayout) {
    this.lb.setRuntimeValue(LayoutStateKeys.AUXILIARYBAR_HIDDEN, hidden);
    if (hidden) {
      this.mainContainer.classList.add(LayoutClasses.AUXILIARYBAR_HIDDEN);
    } else {
      this.mainContainer.classList.remove(LayoutClasses.AUXILIARYBAR_HIDDEN);
    }
    if (hidden && this.$.getActivePaneComposite(
      2
      /* ViewContainerLocation.AuxiliaryBar */
    )) {
      this.$.hideActivePaneComposite(
        2
        /* ViewContainerLocation.AuxiliaryBar */
      );
      this.Nb();
    } else if (!hidden && !this.$.getActivePaneComposite(
      2
      /* ViewContainerLocation.AuxiliaryBar */
    )) {
      let panelToOpen = this.$.getLastActivePaneCompositeId(
        2
        /* ViewContainerLocation.AuxiliaryBar */
      );
      if (!panelToOpen || !this.Wb(panelToOpen)) {
        panelToOpen = this.bb.getViewContainersByLocation(
          2
          /* ViewContainerLocation.AuxiliaryBar */
        ).find((viewContainer5) => this.Wb(viewContainer5.id))?.id;
      }
      if (panelToOpen) {
        const focus = !skipLayout;
        this.$.openPaneComposite(panelToOpen, 2, focus);
      }
    }
    this.G.setViewVisible(this.N, !hidden);
  }
  setPartHidden(hidden, part, targetWindow = $Y) {
    switch (part) {
      case "workbench.parts.activitybar":
        return this.Sb(hidden);
      case "workbench.parts.sidebar":
        return this.Vb(hidden);
      case "workbench.parts.editor":
        return this.Ub(hidden);
      case "workbench.parts.banner":
        return this.Tb(hidden);
      case "workbench.parts.auxiliarybar":
        return this.$b(hidden);
      case "workbench.parts.panel":
        return this.Yb(hidden);
    }
  }
  hasMainWindowBorder() {
    return this.kb.runtime.mainWindowBorder;
  }
  getMainWindowBorderRadius() {
    return this.kb.runtime.mainWindowBorder && $m ? "5px" : void 0;
  }
  isPanelMaximized() {
    return (this.getPanelAlignment() === "center" || !$Wlb(this.getPanelPosition())) && !this.isVisible("workbench.parts.editor", $Y);
  }
  getSideBarPosition() {
    return this.lb.getRuntimeValue(LayoutStateKeys.SIDEBAR_POSITON);
  }
  getPanelAlignment() {
    return this.lb.getRuntimeValue(LayoutStateKeys.PANEL_ALIGNMENT);
  }
  updateMenubarVisibility(skipLayout) {
    const shouldShowTitleBar = $1lb(this.S, $Y, this.kb.runtime.menuBar.toggled);
    if (!skipLayout && this.G && shouldShowTitleBar !== this.isVisible("workbench.parts.titlebar", $Y)) {
      this.G.setViewVisible(this.H, shouldShowTitleBar);
    }
  }
  updateCustomTitleBarVisibility() {
    const shouldShowTitleBar = $1lb(this.S, $Y, this.kb.runtime.menuBar.toggled);
    const titlebarVisible = this.isVisible(
      "workbench.parts.titlebar"
      /* Parts.TITLEBAR_PART */
    );
    if (shouldShowTitleBar !== titlebarVisible) {
      this.G.setViewVisible(this.H, shouldShowTitleBar);
    }
  }
  toggleMenuBar() {
    let currentVisibilityValue = $Bs(this.S);
    if (typeof currentVisibilityValue !== "string") {
      currentVisibilityValue = "classic";
    }
    let newVisibilityValue;
    if (currentVisibilityValue === "visible" || currentVisibilityValue === "classic") {
      newVisibilityValue = $Ds(this.S) ? "toggle" : "compact";
    } else {
      newVisibilityValue = "classic";
    }
    this.S.updateValue("window.menuBarVisibility", newVisibilityValue);
  }
  getPanelPosition() {
    return this.lb.getRuntimeValue(LayoutStateKeys.PANEL_POSITION);
  }
  setPanelPosition(position) {
    if (!this.isVisible(
      "workbench.parts.panel"
      /* Parts.PANEL_PART */
    )) {
      this.Yb(false);
    }
    const panelPart = this.Lb(
      "workbench.parts.panel"
      /* Parts.PANEL_PART */
    );
    const oldPositionValue = $Xlb(this.getPanelPosition());
    const newPositionValue = $Xlb(position);
    const panelContainer = $Kg(panelPart.getContainer());
    panelContainer.classList.remove(oldPositionValue);
    panelContainer.classList.add(newPositionValue);
    panelPart.updateStyles();
    const size = this.G.getViewSize(this.M);
    const sideBarSize = this.G.getViewSize(this.L);
    const auxiliaryBarSize = this.G.getViewSize(this.N);
    let editorHidden = !this.isVisible("workbench.parts.editor", $Y);
    if (newPositionValue !== oldPositionValue && !editorHidden) {
      if ($Wlb(position)) {
        this.lb.setRuntimeValue(LayoutStateKeys.PANEL_LAST_NON_MAXIMIZED_WIDTH, size.width);
      } else if ($Wlb($Ylb(oldPositionValue))) {
        this.lb.setRuntimeValue(LayoutStateKeys.PANEL_LAST_NON_MAXIMIZED_HEIGHT, size.height);
      }
    }
    if ($Wlb(position) && this.getPanelAlignment() !== "center" && editorHidden) {
      this.toggleMaximizedPanel();
      editorHidden = false;
    }
    this.lb.setRuntimeValue(LayoutStateKeys.PANEL_POSITION, position);
    const sideBarVisible = this.isVisible(
      "workbench.parts.sidebar"
      /* Parts.SIDEBAR_PART */
    );
    const auxiliaryBarVisible = this.isVisible(
      "workbench.parts.auxiliarybar"
      /* Parts.AUXILIARYBAR_PART */
    );
    if (position === 2) {
      this.G.moveView(
        this.M,
        editorHidden ? size.height : this.lb.getRuntimeValue(LayoutStateKeys.PANEL_LAST_NON_MAXIMIZED_HEIGHT),
        this.O,
        1
        /* Direction.Down */
      );
    } else if (position === 3) {
      this.G.moveView(
        this.M,
        editorHidden ? size.height : this.lb.getRuntimeValue(LayoutStateKeys.PANEL_LAST_NON_MAXIMIZED_HEIGHT),
        this.O,
        0
        /* Direction.Up */
      );
    } else if (position === 1) {
      this.G.moveView(
        this.M,
        editorHidden ? size.width : this.lb.getRuntimeValue(LayoutStateKeys.PANEL_LAST_NON_MAXIMIZED_WIDTH),
        this.O,
        3
        /* Direction.Right */
      );
    } else {
      this.G.moveView(
        this.M,
        editorHidden ? size.width : this.lb.getRuntimeValue(LayoutStateKeys.PANEL_LAST_NON_MAXIMIZED_WIDTH),
        this.O,
        2
        /* Direction.Left */
      );
    }
    this.G.resizeView(this.L, sideBarSize);
    if (!sideBarVisible) {
      this.Vb(true);
    }
    this.G.resizeView(this.N, auxiliaryBarSize);
    if (!auxiliaryBarVisible) {
      this.$b(true);
    }
    if ($Wlb(position)) {
      this.Xb(this.getSideBarPosition(), this.getPanelAlignment(), position);
    }
    this.g.fire(newPositionValue);
  }
  isWindowMaximized(targetWindow) {
    return this.kb.runtime.maximized.has(getWindowId(targetWindow));
  }
  updateWindowMaximizedState(targetWindow, maximized) {
    this.mainContainer.classList.toggle(LayoutClasses.MAXIMIZED, maximized);
    const targetWindowId = getWindowId(targetWindow);
    if (maximized === this.kb.runtime.maximized.has(targetWindowId)) {
      return;
    }
    if (maximized) {
      this.kb.runtime.maximized.add(targetWindowId);
    } else {
      this.kb.runtime.maximized.delete(targetWindowId);
    }
    this.yb();
    this.f.fire({ windowId: targetWindowId, maximized });
  }
  getVisibleNeighborPart(part, direction) {
    if (!this.G) {
      return void 0;
    }
    if (!this.isVisible(part, $Y)) {
      return void 0;
    }
    const neighborViews = this.G.getNeighborViews(this.Lb(part), direction, false);
    if (!neighborViews) {
      return void 0;
    }
    for (const neighborView of neighborViews) {
      const neighborPart = [
        "workbench.parts.activitybar",
        "workbench.parts.editor",
        "workbench.parts.panel",
        "workbench.parts.auxiliarybar",
        "workbench.parts.sidebar",
        "workbench.parts.statusbar",
        "workbench.parts.titlebar"
        /* Parts.TITLEBAR_PART */
      ].find((partId) => this.Lb(partId) === neighborView && this.isVisible(partId, $Y));
      if (neighborPart !== void 0) {
        return neighborPart;
      }
    }
    return void 0;
  }
  ac() {
    const bannerFirst = this.G.getNeighborViews(this.H, 0, false).length > 0;
    const shouldBannerBeFirst = this.Mb();
    if (bannerFirst !== shouldBannerBeFirst) {
      this.G.moveView(
        this.I,
        Sizing2.Distribute,
        this.H,
        shouldBannerBeFirst ? 0 : 1
        /* Direction.Down */
      );
    }
    this.G.setViewVisible(this.H, $1lb(this.S, $Y, this.kb.runtime.menuBar.toggled));
  }
  bc(nodes, availableHeight, availableWidth) {
    if (!nodes.sideBar && !nodes.auxiliaryBar) {
      nodes.editor.size = availableHeight;
      return nodes.editor;
    }
    const result = [nodes.editor];
    nodes.editor.size = availableWidth;
    if (nodes.sideBar) {
      if (this.lb.getRuntimeValue(LayoutStateKeys.SIDEBAR_POSITON) === 0) {
        result.splice(0, 0, nodes.sideBar);
      } else {
        result.push(nodes.sideBar);
      }
      nodes.editor.size -= this.lb.getRuntimeValue(LayoutStateKeys.SIDEBAR_HIDDEN) ? 0 : nodes.sideBar.size;
    }
    if (nodes.auxiliaryBar) {
      if (this.lb.getRuntimeValue(LayoutStateKeys.SIDEBAR_POSITON) === 1) {
        result.splice(0, 0, nodes.auxiliaryBar);
      } else {
        result.push(nodes.auxiliaryBar);
      }
      nodes.editor.size -= this.lb.getRuntimeValue(LayoutStateKeys.AUXILIARYBAR_HIDDEN) ? 0 : nodes.auxiliaryBar.size;
    }
    return {
      type: "branch",
      data: result,
      size: availableHeight
    };
  }
  cc(nodes, availableWidth, availableHeight) {
    const activityBarSize = this.lb.getRuntimeValue(LayoutStateKeys.ACTIVITYBAR_HIDDEN) ? 0 : nodes.activityBar.size;
    const sideBarSize = this.lb.getRuntimeValue(LayoutStateKeys.SIDEBAR_HIDDEN) ? 0 : nodes.sideBar.size;
    const auxiliaryBarSize = this.lb.getRuntimeValue(LayoutStateKeys.AUXILIARYBAR_HIDDEN) ? 0 : nodes.auxiliaryBar.size;
    const panelSize = this.lb.getInitializationValue(LayoutStateKeys.PANEL_SIZE) ? 0 : nodes.panel.size;
    const panelPostion = this.lb.getRuntimeValue(LayoutStateKeys.PANEL_POSITION);
    const sideBarPosition = this.lb.getRuntimeValue(LayoutStateKeys.SIDEBAR_POSITON);
    const result = [];
    if (!$Wlb(panelPostion)) {
      result.push(nodes.editor);
      nodes.editor.size = availableWidth - activityBarSize - sideBarSize - panelSize - auxiliaryBarSize;
      if (panelPostion === 1) {
        result.push(nodes.panel);
      } else {
        result.splice(0, 0, nodes.panel);
      }
      if (sideBarPosition === 0) {
        result.push(nodes.auxiliaryBar);
        result.splice(0, 0, nodes.sideBar);
        result.splice(0, 0, nodes.activityBar);
      } else {
        result.splice(0, 0, nodes.auxiliaryBar);
        result.push(nodes.sideBar);
        result.push(nodes.activityBar);
      }
    } else {
      const panelAlignment = this.lb.getRuntimeValue(LayoutStateKeys.PANEL_ALIGNMENT);
      const sideBarNextToEditor = !(panelAlignment === "center" || sideBarPosition === 0 && panelAlignment === "right" || sideBarPosition === 1 && panelAlignment === "left");
      const auxiliaryBarNextToEditor = !(panelAlignment === "center" || sideBarPosition === 1 && panelAlignment === "right" || sideBarPosition === 0 && panelAlignment === "left");
      const editorSectionWidth = availableWidth - activityBarSize - (sideBarNextToEditor ? 0 : sideBarSize) - (auxiliaryBarNextToEditor ? 0 : auxiliaryBarSize);
      const editorNodes = this.bc({
        editor: nodes.editor,
        sideBar: sideBarNextToEditor ? nodes.sideBar : void 0,
        auxiliaryBar: auxiliaryBarNextToEditor ? nodes.auxiliaryBar : void 0
      }, availableHeight - panelSize, editorSectionWidth);
      result.push({
        type: "branch",
        data: panelPostion === 2 ? [editorNodes, nodes.panel] : [nodes.panel, editorNodes],
        size: editorSectionWidth
      });
      if (!sideBarNextToEditor) {
        if (sideBarPosition === 0) {
          result.splice(0, 0, nodes.sideBar);
        } else {
          result.push(nodes.sideBar);
        }
      }
      if (!auxiliaryBarNextToEditor) {
        if (sideBarPosition === 1) {
          result.splice(0, 0, nodes.auxiliaryBar);
        } else {
          result.push(nodes.auxiliaryBar);
        }
      }
      if (sideBarPosition === 0) {
        result.splice(0, 0, nodes.activityBar);
      } else {
        result.push(nodes.activityBar);
      }
    }
    return result;
  }
  dc() {
    const { width: width2, height } = this.lb.getInitializationValue(LayoutStateKeys.GRID_SIZE);
    const sideBarSize = this.lb.getInitializationValue(LayoutStateKeys.SIDEBAR_SIZE);
    const auxiliaryBarPartSize = this.lb.getInitializationValue(LayoutStateKeys.AUXILIARYBAR_SIZE);
    const panelSize = this.lb.getInitializationValue(LayoutStateKeys.PANEL_SIZE);
    const titleBarHeight = this.H.minimumHeight;
    const bannerHeight = this.I.minimumHeight;
    const statusBarHeight = this.P.minimumHeight;
    const activityBarWidth = this.J.minimumWidth;
    const middleSectionHeight = height - titleBarHeight - statusBarHeight;
    const titleAndBanner = [
      {
        type: "leaf",
        data: {
          type: "workbench.parts.titlebar"
          /* Parts.TITLEBAR_PART */
        },
        size: titleBarHeight,
        visible: this.isVisible("workbench.parts.titlebar", $Y)
      },
      {
        type: "leaf",
        data: {
          type: "workbench.parts.banner"
          /* Parts.BANNER_PART */
        },
        size: bannerHeight,
        visible: false
      }
    ];
    const activityBarNode = {
      type: "leaf",
      data: {
        type: "workbench.parts.activitybar"
        /* Parts.ACTIVITYBAR_PART */
      },
      size: activityBarWidth,
      visible: !this.lb.getRuntimeValue(LayoutStateKeys.ACTIVITYBAR_HIDDEN)
    };
    const sideBarNode = {
      type: "leaf",
      data: {
        type: "workbench.parts.sidebar"
        /* Parts.SIDEBAR_PART */
      },
      size: sideBarSize,
      visible: !this.lb.getRuntimeValue(LayoutStateKeys.SIDEBAR_HIDDEN)
    };
    const auxiliaryBarNode = {
      type: "leaf",
      data: {
        type: "workbench.parts.auxiliarybar"
        /* Parts.AUXILIARYBAR_PART */
      },
      size: auxiliaryBarPartSize,
      visible: this.isVisible(
        "workbench.parts.auxiliarybar"
        /* Parts.AUXILIARYBAR_PART */
      )
    };
    const editorNode = {
      type: "leaf",
      data: {
        type: "workbench.parts.editor"
        /* Parts.EDITOR_PART */
      },
      size: 0,
      // Update based on sibling sizes
      visible: !this.lb.getRuntimeValue(LayoutStateKeys.EDITOR_HIDDEN)
    };
    const panelNode = {
      type: "leaf",
      data: {
        type: "workbench.parts.panel"
        /* Parts.PANEL_PART */
      },
      size: panelSize,
      visible: !this.lb.getRuntimeValue(LayoutStateKeys.PANEL_HIDDEN)
    };
    const middleSection = this.cc({
      activityBar: activityBarNode,
      auxiliaryBar: auxiliaryBarNode,
      editor: editorNode,
      panel: panelNode,
      sideBar: sideBarNode
    }, width2, middleSectionHeight);
    const result = {
      root: {
        type: "branch",
        size: width2,
        data: [
          ...this.Mb() ? titleAndBanner.reverse() : titleAndBanner,
          {
            type: "branch",
            data: middleSection,
            size: middleSectionHeight
          },
          {
            type: "leaf",
            data: {
              type: "workbench.parts.statusbar"
              /* Parts.STATUSBAR_PART */
            },
            size: statusBarHeight,
            visible: !this.lb.getRuntimeValue(LayoutStateKeys.STATUSBAR_HIDDEN)
          }
        ]
      },
      orientation: 0,
      width: width2,
      height
    };
    const layoutDescriptor = {
      activityBarVisible: !this.lb.getRuntimeValue(LayoutStateKeys.ACTIVITYBAR_HIDDEN),
      sideBarVisible: !this.lb.getRuntimeValue(LayoutStateKeys.SIDEBAR_HIDDEN),
      auxiliaryBarVisible: !this.lb.getRuntimeValue(LayoutStateKeys.AUXILIARYBAR_HIDDEN),
      panelVisible: !this.lb.getRuntimeValue(LayoutStateKeys.PANEL_HIDDEN),
      statusbarVisible: !this.lb.getRuntimeValue(LayoutStateKeys.STATUSBAR_HIDDEN),
      sideBarPosition: $Xlb(this.lb.getRuntimeValue(LayoutStateKeys.SIDEBAR_POSITON)),
      panelPosition: $Xlb(this.lb.getRuntimeValue(LayoutStateKeys.PANEL_POSITION))
    };
    this.ib.publicLog2("startupLayout", layoutDescriptor);
    return result;
  }
  dispose() {
    super.dispose();
    this.mb = true;
  }
};
function getZenModeConfiguration(configurationService) {
  return configurationService.getValue(WorkbenchLayoutSettings.ZEN_MODE_CONFIG);
}
var WorkbenchLayoutStateKey = class {
  constructor(name, scope, target, defaultValue) {
    this.name = name;
    this.scope = scope;
    this.target = target;
    this.defaultValue = defaultValue;
  }
};
var RuntimeStateKey = class extends WorkbenchLayoutStateKey {
  constructor(name, scope, target, defaultValue, zenModeIgnore) {
    super(name, scope, target, defaultValue);
    this.zenModeIgnore = zenModeIgnore;
    this.runtime = true;
  }
};
var InitializationStateKey = class extends WorkbenchLayoutStateKey {
  constructor() {
    super(...arguments);
    this.runtime = false;
  }
};
var LayoutStateKeys = {
  // Editor
  MAIN_EDITOR_CENTERED: new RuntimeStateKey("editor.centered", 1, 1, false),
  // Zen Mode
  ZEN_MODE_ACTIVE: new RuntimeStateKey("zenMode.active", 1, 1, false),
  ZEN_MODE_EXIT_INFO: new RuntimeStateKey("zenMode.exitInfo", 1, 1, {
    transitionedToCenteredEditorLayout: false,
    transitionedToFullScreen: false,
    handleNotificationsDoNotDisturbMode: false,
    wasVisible: {
      auxiliaryBar: false,
      panel: false,
      sideBar: false
    }
  }),
  // Part Sizing
  GRID_SIZE: new InitializationStateKey("grid.size", 0, 1, { width: 800, height: 600 }),
  SIDEBAR_SIZE: new InitializationStateKey("sideBar.size", 0, 1, 200),
  AUXILIARYBAR_SIZE: new InitializationStateKey("auxiliaryBar.size", 0, 1, 200),
  PANEL_SIZE: new InitializationStateKey("panel.size", 0, 1, 300),
  PANEL_LAST_NON_MAXIMIZED_HEIGHT: new RuntimeStateKey("panel.lastNonMaximizedHeight", 0, 1, 300),
  PANEL_LAST_NON_MAXIMIZED_WIDTH: new RuntimeStateKey("panel.lastNonMaximizedWidth", 0, 1, 300),
  PANEL_WAS_LAST_MAXIMIZED: new RuntimeStateKey("panel.wasLastMaximized", 1, 1, false),
  // Part Positions
  SIDEBAR_POSITON: new RuntimeStateKey(
    "sideBar.position",
    1,
    1,
    0
    /* Position.LEFT */
  ),
  PANEL_POSITION: new RuntimeStateKey(
    "panel.position",
    1,
    1,
    2
    /* Position.BOTTOM */
  ),
  PANEL_ALIGNMENT: new RuntimeStateKey("panel.alignment", 0, 0, "center"),
  // Part Visibility
  ACTIVITYBAR_HIDDEN: new RuntimeStateKey("activityBar.hidden", 1, 1, false, true),
  SIDEBAR_HIDDEN: new RuntimeStateKey("sideBar.hidden", 1, 1, false),
  EDITOR_HIDDEN: new RuntimeStateKey("editor.hidden", 1, 1, false),
  PANEL_HIDDEN: new RuntimeStateKey("panel.hidden", 1, 1, true),
  AUXILIARYBAR_HIDDEN: new RuntimeStateKey("auxiliaryBar.hidden", 1, 1, true),
  STATUSBAR_HIDDEN: new RuntimeStateKey("statusBar.hidden", 1, 1, false, true)
};
var WorkbenchLayoutSettings;
(function(WorkbenchLayoutSettings2) {
  WorkbenchLayoutSettings2["PANEL_POSITION"] = "workbench.panel.defaultLocation";
  WorkbenchLayoutSettings2["PANEL_OPENS_MAXIMIZED"] = "workbench.panel.opensMaximized";
  WorkbenchLayoutSettings2["ZEN_MODE_CONFIG"] = "zenMode";
  WorkbenchLayoutSettings2["EDITOR_CENTERED_LAYOUT_AUTO_RESIZE"] = "workbench.editor.centeredLayoutAutoResize";
})(WorkbenchLayoutSettings || (WorkbenchLayoutSettings = {}));
var LegacyWorkbenchLayoutSettings;
(function(LegacyWorkbenchLayoutSettings2) {
  LegacyWorkbenchLayoutSettings2["STATUSBAR_VISIBLE"] = "workbench.statusBar.visible";
  LegacyWorkbenchLayoutSettings2["SIDEBAR_POSITION"] = "workbench.sideBar.location";
})(LegacyWorkbenchLayoutSettings || (LegacyWorkbenchLayoutSettings = {}));
var LayoutStateModel = class _LayoutStateModel extends $3c {
  static {
    this.STORAGE_PREFIX = "workbench.";
  }
  constructor(c, f, g, h3) {
    super();
    this.c = c;
    this.f = f;
    this.g = g;
    this.h = h3;
    this.a = this.B(new $ze());
    this.onDidChangeState = this.a.event;
    this.b = /* @__PURE__ */ new Map();
    this.B(this.f.onDidChangeConfiguration((configurationChange) => this.j(configurationChange)));
  }
  j(configurationChangeEvent) {
    if (configurationChangeEvent.affectsConfiguration(
      "workbench.activityBar.location"
      /* LayoutSettings.ACTIVITY_BAR_LOCATION */
    )) {
      this.r(LayoutStateKeys.ACTIVITYBAR_HIDDEN, this.n());
    }
    if (configurationChangeEvent.affectsConfiguration(LegacyWorkbenchLayoutSettings.STATUSBAR_VISIBLE)) {
      this.r(LayoutStateKeys.STATUSBAR_HIDDEN, !this.f.getValue(LegacyWorkbenchLayoutSettings.STATUSBAR_VISIBLE));
    }
    if (configurationChangeEvent.affectsConfiguration(LegacyWorkbenchLayoutSettings.SIDEBAR_POSITION)) {
      this.r(LayoutStateKeys.SIDEBAR_POSITON, $Ylb(this.f.getValue(LegacyWorkbenchLayoutSettings.SIDEBAR_POSITION) ?? "left"));
    }
  }
  m(key2, value) {
    const isZenMode = this.getRuntimeValue(LayoutStateKeys.ZEN_MODE_ACTIVE);
    if (key2.zenModeIgnore && isZenMode) {
      return;
    }
    if (key2 === LayoutStateKeys.ACTIVITYBAR_HIDDEN) {
      this.f.updateValue("workbench.activityBar.location", value ? "hidden" : void 0);
    } else if (key2 === LayoutStateKeys.STATUSBAR_HIDDEN) {
      this.f.updateValue(LegacyWorkbenchLayoutSettings.STATUSBAR_VISIBLE, !value);
    } else if (key2 === LayoutStateKeys.SIDEBAR_POSITON) {
      this.f.updateValue(LegacyWorkbenchLayoutSettings.SIDEBAR_POSITION, $Xlb(value));
    }
  }
  load() {
    let key2;
    for (key2 in LayoutStateKeys) {
      const stateKey = LayoutStateKeys[key2];
      const value = this.t(stateKey);
      if (value !== void 0) {
        this.b.set(stateKey.name, value);
      }
    }
    this.b.set(LayoutStateKeys.ACTIVITYBAR_HIDDEN.name, this.n());
    this.b.set(LayoutStateKeys.STATUSBAR_HIDDEN.name, !this.f.getValue(LegacyWorkbenchLayoutSettings.STATUSBAR_VISIBLE));
    this.b.set(LayoutStateKeys.SIDEBAR_POSITON.name, $Ylb(this.f.getValue(LegacyWorkbenchLayoutSettings.SIDEBAR_POSITION) ?? "left"));
    const workbenchDimensions = $qj(this.h);
    LayoutStateKeys.PANEL_POSITION.defaultValue = $Ylb(this.f.getValue(WorkbenchLayoutSettings.PANEL_POSITION) ?? "bottom");
    LayoutStateKeys.GRID_SIZE.defaultValue = { height: workbenchDimensions.height, width: workbenchDimensions.width };
    LayoutStateKeys.SIDEBAR_SIZE.defaultValue = Math.min(300, workbenchDimensions.width / 4);
    LayoutStateKeys.AUXILIARYBAR_SIZE.defaultValue = Math.min(300, workbenchDimensions.width / 4);
    LayoutStateKeys.PANEL_SIZE.defaultValue = this.b.get(LayoutStateKeys.PANEL_POSITION.name) ?? $Wlb(LayoutStateKeys.PANEL_POSITION.defaultValue) ? workbenchDimensions.height / 3 : workbenchDimensions.width / 4;
    LayoutStateKeys.SIDEBAR_HIDDEN.defaultValue = this.g.getWorkbenchState() === 1;
    for (key2 in LayoutStateKeys) {
      const stateKey = LayoutStateKeys[key2];
      if (this.b.get(stateKey.name) === void 0) {
        this.b.set(stateKey.name, stateKey.defaultValue);
      }
    }
    this.B(this.c.onDidChangeValue(0, void 0, this.q)((storageChangeEvent) => {
      let key3;
      for (key3 in LayoutStateKeys) {
        const stateKey = LayoutStateKeys[key3];
        if (stateKey instanceof RuntimeStateKey && stateKey.scope === 0 && stateKey.target === 0) {
          if (`${_LayoutStateModel.STORAGE_PREFIX}${stateKey.name}` === storageChangeEvent.key) {
            const value = this.t(stateKey) ?? stateKey.defaultValue;
            if (this.b.get(stateKey.name) !== value) {
              this.b.set(stateKey.name, value);
              this.a.fire({ key: stateKey, value });
            }
          }
        }
      }
    }));
  }
  save(workspace2, global) {
    let key2;
    const isZenMode = this.getRuntimeValue(LayoutStateKeys.ZEN_MODE_ACTIVE);
    for (key2 in LayoutStateKeys) {
      const stateKey = LayoutStateKeys[key2];
      if (workspace2 && stateKey.scope === 1 || global && stateKey.scope === 0) {
        if (isZenMode && stateKey instanceof RuntimeStateKey && stateKey.zenModeIgnore) {
          continue;
        }
        this.s(stateKey);
      }
    }
  }
  getInitializationValue(key2) {
    return this.b.get(key2.name);
  }
  setInitializationValue(key2, value) {
    this.b.set(key2.name, value);
  }
  getRuntimeValue(key2, fallbackToSetting) {
    if (fallbackToSetting) {
      switch (key2) {
        case LayoutStateKeys.ACTIVITYBAR_HIDDEN:
          this.b.set(key2.name, this.n());
          break;
        case LayoutStateKeys.STATUSBAR_HIDDEN:
          this.b.set(key2.name, !this.f.getValue(LegacyWorkbenchLayoutSettings.STATUSBAR_VISIBLE));
          break;
        case LayoutStateKeys.SIDEBAR_POSITON:
          this.b.set(key2.name, this.f.getValue(LegacyWorkbenchLayoutSettings.SIDEBAR_POSITION) ?? "left");
          break;
      }
    }
    return this.b.get(key2.name);
  }
  setRuntimeValue(key2, value) {
    this.b.set(key2.name, value);
    const isZenMode = this.getRuntimeValue(LayoutStateKeys.ZEN_MODE_ACTIVE);
    if (key2.scope === 0) {
      if (!isZenMode || !key2.zenModeIgnore) {
        this.s(key2);
        this.m(key2, value);
      }
    }
  }
  n() {
    const oldValue = this.f.getValue("workbench.activityBar.visible");
    if (oldValue !== void 0) {
      return !oldValue;
    }
    return this.f.getValue(
      "workbench.activityBar.location"
      /* LayoutSettings.ACTIVITY_BAR_LOCATION */
    ) !== "default";
  }
  r(key2, value) {
    const previousValue = this.b.get(key2.name);
    if (previousValue === value) {
      return;
    }
    this.setRuntimeValue(key2, value);
    this.a.fire({ key: key2, value });
  }
  s(key2) {
    const value = this.b.get(key2.name);
    this.c.store(`${_LayoutStateModel.STORAGE_PREFIX}${key2.name}`, typeof value === "object" ? JSON.stringify(value) : value, key2.scope, key2.target);
  }
  t(key2) {
    let value = this.c.get(`${_LayoutStateModel.STORAGE_PREFIX}${key2.name}`, key2.scope);
    if (value !== void 0) {
      switch (typeof key2.defaultValue) {
        case "boolean":
          value = value === "true";
          break;
        case "number":
          value = parseInt(value);
          break;
        case "object":
          value = JSON.parse(value);
          break;
      }
    }
    return value;
  }
};

// out-build/vs/workbench/browser/parts/notifications/notificationAccessibleView.js
var $7lc = class {
  constructor() {
    this.priority = 90;
    this.name = "notifications";
    this.when = $0pb;
    this.type = "view";
  }
  getProvider(accessor) {
    const accessibleViewService = accessor.get($shb);
    const listService = accessor.get($Deb);
    const commandService = accessor.get($sn);
    const accessibilitySignalService = accessor.get($I9);
    function getProvider() {
      const notification = $Ilc(listService);
      if (!notification) {
        return;
      }
      commandService.executeCommand("notifications.showList");
      let notificationIndex;
      const list2 = listService.lastFocusedList;
      if (list2 instanceof $Web) {
        notificationIndex = list2.indexOf(notification);
      }
      if (notificationIndex === void 0) {
        return;
      }
      function focusList() {
        commandService.executeCommand("notifications.showList");
        if (list2 && notificationIndex !== void 0) {
          list2.domFocus();
          try {
            list2.setFocus([notificationIndex]);
          } catch {
          }
        }
      }
      function getContentForNotification() {
        const notification2 = $Ilc(listService);
        const message = notification2?.message.original.toString();
        if (!notification2) {
          return;
        }
        return notification2.source ? localize(3615, null, message, notification2.source) : localize(3616, null, message);
      }
      const content = getContentForNotification();
      if (!content) {
        return;
      }
      notification.onDidClose(() => accessibleViewService.next());
      return new $thb("notification", {
        type: "view"
        /* AccessibleViewType.View */
      }, () => content, () => focusList(), "accessibility.verbosity.notification", void 0, getActionsFromNotification(notification, accessibilitySignalService), () => {
        if (!list2) {
          return;
        }
        focusList();
        list2.focusNext();
        return getContentForNotification();
      }, () => {
        if (!list2) {
          return;
        }
        focusList();
        list2.focusPrevious();
        return getContentForNotification();
      });
    }
    return getProvider();
  }
};
function getActionsFromNotification(notification, accessibilitySignalService) {
  let actions = void 0;
  if (notification.actions) {
    actions = [];
    if (notification.actions.primary) {
      actions.push(...notification.actions.primary);
    }
    if (notification.actions.secondary) {
      actions.push(...notification.actions.secondary);
    }
  }
  if (actions) {
    for (const action of actions) {
      action.class = ThemeIcon.asClassName($6l.bell);
      const initialAction = action.run;
      action.run = () => {
        initialAction();
        notification.close();
      };
    }
  }
  const manageExtension = actions?.find((a) => a.label.includes("Manage Extension"));
  if (manageExtension) {
    manageExtension.class = ThemeIcon.asClassName($6l.gear);
  }
  if (actions) {
    actions.push({
      id: "clearNotification",
      label: localize(3617, null),
      tooltip: localize(3618, null),
      run: () => {
        notification.close();
        accessibilitySignalService.playSignal($N9.clear);
      },
      enabled: true,
      class: ThemeIcon.asClassName($6l.clearAll)
    });
  }
  return actions;
}

// out-build/vs/workbench/browser/workbench.js
var $8lc = class extends $6lc {
  constructor(parent, gc, hc, logService) {
    super(parent);
    this.gc = gc;
    this.hc = hc;
    this.ec = this.B(new $ze());
    this.onWillShutdown = this.ec.event;
    this.fc = this.B(new $ze());
    this.onDidShutdown = this.fc.event;
    this.jc = { message: void 0, time: 0 };
    $S("code/willStartWorkbench");
    this.ic(logService);
  }
  ic(logService) {
    $Y.addEventListener("unhandledrejection", (event) => {
      $gb(event.reason);
      event.preventDefault();
    });
    setUnexpectedErrorHandler((error) => this.kc(error, logService));
  }
  kc(error, logService) {
    const message = $1m(error, true);
    if (!message) {
      return;
    }
    const now = Date.now();
    if (message === this.jc.message && now - this.jc.time <= 1e3) {
      return;
    }
    this.jc.time = now;
    this.jc.message = message;
    logService.error(message);
  }
  startup() {
    try {
      this.B($we(175));
      const instantiationService = this.lc(this.hc);
      instantiationService.invokeFunction((accessor) => {
        const lifecycleService = accessor.get($KL);
        const storageService = accessor.get($jv);
        const configurationService = accessor.get($kl);
        const hostService = accessor.get($S4);
        const hoverService = accessor.get($5$);
        const dialogService = accessor.get($Yv);
        const notificationService = accessor.get($PJ);
        $IZ((placement, enableInstantHover) => instantiationService.createInstance($6$, placement, enableInstantHover, {}));
        $I1(hoverService);
        this.ob(accessor);
        $Wn.as(Extensions2.Workbench).start(accessor);
        $Wn.as($ZK.EditorFactory).start(accessor);
        this.B(instantiationService.createInstance($4lc));
        this.mc(lifecycleService, storageService, configurationService, hostService, dialogService);
        this.rc(instantiationService, notificationService, storageService, configurationService);
        this.Rb();
        this.layout();
        this.uc(lifecycleService);
      });
      return instantiationService;
    } catch (error) {
      $gb(error);
      throw error;
    }
  }
  lc(serviceCollection) {
    serviceCollection.set($Vlb, this);
    const contributedServices = $TC();
    for (const [id2, descriptor] of contributedServices) {
      serviceCollection.set(id2, descriptor);
    }
    const instantiationService = new $0B(serviceCollection, true);
    instantiationService.invokeFunction((accessor) => {
      const lifecycleService = accessor.get($KL);
      const configurationService = accessor.get($kl);
      if (typeof configurationService.acquireInstantiationService === "function") {
        configurationService.acquireInstantiationService(instantiationService);
      }
      lifecycleService.phase = 2;
    });
    return instantiationService;
  }
  mc(lifecycleService, storageService, configurationService, hostService, dialogService) {
    this.B(configurationService.onDidChangeConfiguration((e) => this.oc(e, configurationService)));
    if ($p) {
      this.B(storageService.onWillSaveState((e) => {
        if (e.reason === WillSaveStateReason.SHUTDOWN) {
          this.qc(storageService);
        }
      }));
    } else {
      this.B(lifecycleService.onWillShutdown(() => this.qc(storageService)));
    }
    this.B(lifecycleService.onWillShutdown((event) => this.ec.fire(event)));
    this.B(lifecycleService.onDidShutdown(() => {
      this.fc.fire();
      this.dispose();
    }));
    this.B(hostService.onDidChangeFocus((focus) => {
      if (!focus) {
        storageService.flush();
      }
    }));
    this.B(dialogService.onWillShowDialog(() => this.mainContainer.classList.add("modal-dialog-visible")));
    this.B(dialogService.onDidShowDialog(() => this.mainContainer.classList.remove("modal-dialog-visible")));
  }
  oc(e, configurationService) {
    if (!$m) {
      return;
    }
    if (e && !e.affectsConfiguration("workbench.fontAliasing")) {
      return;
    }
    const aliasing = configurationService.getValue("workbench.fontAliasing");
    if (this.nc === aliasing) {
      return;
    }
    this.nc = aliasing;
    const fontAliasingValues = ["antialiased", "none", "auto"];
    this.mainContainer.classList.remove(...fontAliasingValues.map((value) => `monaco-font-aliasing-${value}`));
    if (fontAliasingValues.some((option) => option === aliasing)) {
      this.mainContainer.classList.add(`monaco-font-aliasing-${aliasing}`);
    }
  }
  pc(storageService, configurationService) {
    const storedFontInfoRaw = storageService.get(
      "editorFontInfo",
      -1
      /* StorageScope.APPLICATION */
    );
    if (storedFontInfoRaw) {
      try {
        const storedFontInfo = JSON.parse(storedFontInfoRaw);
        if (Array.isArray(storedFontInfo)) {
          $64.restoreFontInfo($Y, storedFontInfo);
        }
      } catch (err) {
      }
    }
    $64.readFontInfo($Y, $ED.createFromRawSettings(configurationService.getValue("editor"), $_1.getInstance($Y).value));
  }
  qc(storageService) {
    const serializedFontInfo = $64.serializeFontInfo($Y);
    if (serializedFontInfo) {
      storageService.store(
        "editorFontInfo",
        JSON.stringify(serializedFontInfo),
        -1,
        1
        /* StorageTarget.MACHINE */
      );
    }
  }
  rc(instantiationService, notificationService, storageService, configurationService) {
    $0Z(this.mainContainer);
    $72((msDelayTime, msLoopTime) => instantiationService.createInstance($F8b, msDelayTime, msLoopTime));
    const platformClass = $l ? "windows" : $n ? "linux" : "mac";
    const workbenchClasses = $Mb([
      "monaco-workbench",
      platformClass,
      $r ? "web" : void 0,
      $We ? "chromium" : $Ue ? "firefox" : $Xe ? "safari" : void 0,
      ...this.getLayoutClasses(),
      ...this.gc?.extraClasses ? this.gc.extraClasses : []
    ]);
    this.mainContainer.classList.add(...workbenchClasses);
    $Y.document.body.classList.add(platformClass);
    if ($r) {
      $Y.document.body.classList.add("web");
    }
    this.oc(void 0, configurationService);
    this.pc(storageService, configurationService);
    for (const { id: id2, role, classes: classes2, options: options3 } of [
      { id: "workbench.parts.titlebar", role: "none", classes: ["titlebar"] },
      { id: "workbench.parts.banner", role: "banner", classes: ["banner"] },
      { id: "workbench.parts.activitybar", role: "none", classes: ["activitybar", this.getSideBarPosition() === 0 ? "left" : "right"] },
      // Use role 'none' for some parts to make screen readers less chatty #114892
      { id: "workbench.parts.sidebar", role: "none", classes: ["sidebar", this.getSideBarPosition() === 0 ? "left" : "right"] },
      { id: "workbench.parts.editor", role: "main", classes: ["editor"], options: { restorePreviousState: this.Cb() } },
      { id: "workbench.parts.panel", role: "none", classes: ["panel", "basepanel", $Xlb(this.getPanelPosition())] },
      { id: "workbench.parts.auxiliarybar", role: "none", classes: ["auxiliarybar", "basepanel", this.getSideBarPosition() === 0 ? "right" : "left"] },
      { id: "workbench.parts.statusbar", role: "status", classes: ["statusbar"] }
    ]) {
      const partContainer = this.sc(id2, role, classes2);
      $S(`code/willCreatePart/${id2}`);
      this.Lb(id2).create(partContainer, options3);
      $S(`code/didCreatePart/${id2}`);
    }
    this.tc(instantiationService, notificationService);
    this.nb.appendChild(this.mainContainer);
  }
  sc(id2, role, classes2) {
    const part = document.createElement(role === "status" ? "footer" : "div");
    part.classList.add("part", ...classes2);
    part.id = id2;
    part.setAttribute("role", role);
    if (role === "status") {
      part.setAttribute("aria-live", "off");
    }
    return part;
  }
  tc(instantiationService, notificationService) {
    const notificationsCenter = this.B(instantiationService.createInstance($Zlc, this.mainContainer, notificationService.model));
    const notificationsToasts = this.B(instantiationService.createInstance($3lc, this.mainContainer, notificationService.model));
    this.B(instantiationService.createInstance($1lc, notificationService.model));
    const notificationsStatus = instantiationService.createInstance($2lc, notificationService.model);
    this.B(instantiationService.createInstance($xlc));
    this.B(notificationsCenter.onDidChangeVisibility(() => {
      notificationsStatus.update(notificationsCenter.isVisible, notificationsToasts.isVisible);
      notificationsToasts.update(notificationsCenter.isVisible);
    }));
    this.B(notificationsToasts.onDidChangeVisibility(() => {
      notificationsStatus.update(notificationsCenter.isVisible, notificationsToasts.isVisible);
    }));
    $Jlc(notificationsCenter, notificationsToasts, notificationService.model);
    $vhb.register(new $7lc());
    this.registerNotifications({
      onDidChangeNotificationsVisibility: Event2.map(Event2.any(notificationsToasts.onDidChangeVisibility, notificationsCenter.onDidChangeVisibility), () => notificationsToasts.isVisible || notificationsCenter.isVisible)
    });
  }
  uc(lifecycleService) {
    try {
      this.Kb();
    } catch (error) {
      $gb(error);
    }
    this.Hb.finally(() => Promise.race([
      this.whenRestored,
      $Wh(2e3)
    ]).finally(() => {
      function markDidStartWorkbench() {
        $S("code/didStartWorkbench");
        performance.measure("perf: workbench create & restore", "code/didLoadWorkbenchMain", "code/didStartWorkbench");
      }
      if (this.isRestored()) {
        markDidStartWorkbench();
      } else {
        this.whenRestored.finally(() => markDidStartWorkbench());
      }
      lifecycleService.phase = 3;
      const eventuallyPhaseScheduler = this.B(new $8h(() => {
        this.B($gj($Y, () => lifecycleService.phase = 4, 2500));
      }, 2500));
      eventuallyPhaseScheduler.schedule();
    }));
  }
};

// out-build/vs/platform/files/common/watcher.js
var $9s = class _$9s extends $3c {
  static {
    this.a = 5;
  }
  constructor(h3, j, m, n) {
    super();
    this.h = h3;
    this.j = j;
    this.m = m;
    this.n = n;
    this.c = this.B(new $4c());
    this.f = void 0;
    this.g = 0;
  }
  s() {
    const disposables = new $2c();
    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 < _$9s.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();
  }
};
function $_s(changes) {
  return changes.map((change) => ({
    type: change.type,
    resource: URI.revive(change.resource),
    cId: change.cId
  }));
}

// out-build/vs/platform/files/common/diskFileSystemProviderClient.js
var $dy = class extends $3c {
  constructor(a, b) {
    super();
    this.a = a;
    this.b = b;
    this.onDidChangeCapabilities = Event2.None;
    this.f = this.B(new $ze());
    this.onDidChangeFile = this.f.event;
    this.g = this.B(new $ze());
    this.onDidWatchError = this.g.event;
    this.h = $ps();
    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 = $qi((data) => $Ci.concat(data.map((data2) => $Ci.wrap(data2))).buffer);
    const disposables = new $2c();
    disposables.add(this.a.listen("readFileStream", [resource, opts])((dataOrErrorOrEnd) => {
      if (dataOrErrorOrEnd instanceof $Ci) {
        stream.write(dataOrErrorOrEnd.buffer);
      } else {
        if (dataOrErrorOrEnd === "end") {
          stream.end();
        } else {
          let error;
          if (dataOrErrorOrEnd instanceof Error) {
            error = dataOrErrorOrEnd;
          } else {
            const errorCandidate = dataOrErrorOrEnd;
            error = $xm(errorCandidate.message ?? $1m(errorCandidate), errorCandidate.code ?? FileSystemProviderErrorCode.Unknown);
          }
          stream.error(error);
          stream.end();
        }
        disposables.dispose();
      }
    }));
    disposables.add(token.onCancellationRequested(() => {
      stream.error($mb());
      stream.end();
      disposables.dispose();
    }));
    return stream;
  }
  writeFile(resource, content, opts) {
    return this.a.call("writeFile", [resource, $Ci.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, $Ci.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($_s(events));
      } else {
        const error = eventsOrError;
        this.g.fire(error);
      }
    }));
  }
  watch(resource, opts) {
    const req = $ps();
    this.a.call("watch", [this.h, req, resource, opts]);
    return $1c(() => this.a.call("unwatch", [this.h, req]));
  }
};

// out-build/vs/workbench/services/remote/common/remoteFileSystemProviderClient.js
var $HY = "remoteFilesystem";
var $IY = class _$IY extends $dy {
  static register(remoteAgentService, fileService, logService) {
    const connection = remoteAgentService.getConnection();
    if (!connection) {
      return $3c.None;
    }
    const disposables = new $2c();
    const environmentPromise = (async () => {
      try {
        const environment = await remoteAgentService.getRawEnvironment();
        if (environment) {
          fileService.registerProvider(Schemas.vscodeRemote, disposables.add(new _$IY(environment, connection)));
        } else {
          logService.error("Cannot register remote filesystem provider. Remote environment doesnot exist.");
        }
      } catch (error) {
        logService.error("Cannot register remote filesystem provider. Error while fetching remote environment.", $qb(error));
      }
    })();
    disposables.add(fileService.onWillActivateFileSystemProvider((e) => {
      if (e.scheme === Schemas.vscodeRemote) {
        e.join(environmentPromise);
      }
    }));
    return disposables;
  }
  constructor(remoteAgentEnvironment, connection) {
    super(connection.getChannel($HY), {
      pathCaseSensitive: remoteAgentEnvironment.os === 3
      /* OperatingSystem.Linux */
    });
  }
};

// out-build/vs/workbench/services/remote/common/remoteAgentEnvironmentChannel.js
var $GX = class {
  static async getEnvironmentData(channel, remoteAuthority, profile) {
    const args2 = {
      remoteAuthority,
      profile
    };
    const data = await channel.call("getEnvironmentData", args2);
    return {
      pid: data.pid,
      connectionToken: data.connectionToken,
      appRoot: URI.revive(data.appRoot),
      settingsPath: URI.revive(data.settingsPath),
      logsPath: URI.revive(data.logsPath),
      extensionHostLogsPath: URI.revive(data.extensionHostLogsPath),
      globalStorageHome: URI.revive(data.globalStorageHome),
      workspaceStorageHome: URI.revive(data.workspaceStorageHome),
      localHistoryHome: URI.revive(data.localHistoryHome),
      userHome: URI.revive(data.userHome),
      os: data.os,
      arch: data.arch,
      marks: data.marks,
      useHostProxy: data.useHostProxy,
      profiles: $cu(data.profiles),
      isUnsupportedGlibc: data.isUnsupportedGlibc
    };
  }
  static async getExtensionHostExitInfo(channel, remoteAuthority, reconnectionToken) {
    const args2 = {
      remoteAuthority,
      reconnectionToken
    };
    return channel.call("getExtensionHostExitInfo", args2);
  }
  static getDiagnosticInfo(channel, options3) {
    return channel.call("getDiagnosticInfo", options3);
  }
  static updateTelemetryLevel(channel, telemetryLevel) {
    return channel.call("updateTelemetryLevel", { telemetryLevel });
  }
  static logTelemetry(channel, eventName, data) {
    return channel.call("logTelemetry", { eventName, data });
  }
  static flushTelemetry(channel) {
    return channel.call("flushTelemetry");
  }
  static async ping(channel) {
    await channel.call("ping");
  }
};

// out-build/vs/platform/sign/common/sign.js
var $kz = "signService";
var $lz = $Qk($kz);

// out-build/vs/workbench/services/remote/common/abstractRemoteAgentService.js
var $9lc = class $9lc2 extends $3c {
  constructor(f, g, h3, productService, j, signService, logService) {
    super();
    this.f = f;
    this.g = g;
    this.h = h3;
    this.j = j;
    if (this.h.remoteAuthority) {
      this.a = this.B(new RemoteAgentConnection(this.h.remoteAuthority, productService.commit, productService.quality, this.f, this.j, signService, logService));
    } else {
      this.a = null;
    }
    this.b = null;
  }
  getConnection() {
    return this.a;
  }
  getEnvironment() {
    return this.getRawEnvironment().then(void 0, () => null);
  }
  getRawEnvironment() {
    if (!this.b) {
      this.b = this.m(async (channel, connection) => {
        const env3 = await $GX.getEnvironmentData(channel, connection.remoteAuthority, this.g.currentProfile.isDefault ? void 0 : this.g.currentProfile.id);
        this.j._setAuthorityConnectionToken(connection.remoteAuthority, env3.connectionToken);
        return env3;
      }, null);
    }
    return this.b;
  }
  getExtensionHostExitInfo(reconnectionToken) {
    return this.m((channel, connection) => $GX.getExtensionHostExitInfo(channel, connection.remoteAuthority, reconnectionToken), null);
  }
  getDiagnosticInfo(options3) {
    return this.m((channel) => $GX.getDiagnosticInfo(channel, options3), void 0);
  }
  updateTelemetryLevel(telemetryLevel) {
    return this.n((channel) => $GX.updateTelemetryLevel(channel, telemetryLevel), void 0);
  }
  logTelemetry(eventName, data) {
    return this.n((channel) => $GX.logTelemetry(channel, eventName, data), void 0);
  }
  flushTelemetry() {
    return this.n((channel) => $GX.flushTelemetry(channel), void 0);
  }
  getRoundTripTime() {
    return this.n(async (channel) => {
      const start = Date.now();
      await $GX.ping(channel);
      return Date.now() - start;
    }, void 0);
  }
  async endConnection() {
    if (this.a) {
      await this.a.end();
      this.a.dispose();
    }
  }
  m(callback, fallback2) {
    const connection = this.getConnection();
    if (!connection) {
      return Promise.resolve(fallback2);
    }
    return connection.withChannel("remoteextensionsenvironment", (channel) => callback(channel, connection));
  }
  n(callback, fallback2) {
    const connection = this.getConnection();
    if (!connection) {
      return Promise.resolve(fallback2);
    }
    return connection.withChannel("telemetry", (channel) => callback(channel, connection));
  }
};
$9lc = __decorate([
  __param(0, $gC),
  __param(1, $gT),
  __param(2, $US),
  __param(3, $Vu),
  __param(4, $bC),
  __param(5, $lz),
  __param(6, $wn)
], $9lc);
var RemoteAgentConnection = class extends $3c {
  constructor(remoteAuthority, h3, j, m, n, r2, s) {
    super();
    this.h = h3;
    this.j = j;
    this.m = m;
    this.n = n;
    this.r = r2;
    this.s = s;
    this.a = this.B(new $ze());
    this.onReconnecting = this.a.event;
    this.b = this.B(new $ze());
    this.onDidStateChange = this.b.event;
    this.end = () => Promise.resolve();
    this.remoteAuthority = remoteAuthority;
    this.f = null;
  }
  getChannel(channelName) {
    return $lu(this.t().then((c) => c.getChannel(channelName)));
  }
  withChannel(channelName, callback) {
    const channel = this.getChannel(channelName);
    const result = callback(channel);
    return result;
  }
  registerChannel(channelName, channel) {
    this.t().then((client) => client.registerChannel(channelName, channel));
  }
  async getInitialConnectionTimeMs() {
    try {
      await this.t();
    } catch {
    }
    return this.g;
  }
  t() {
    if (!this.f) {
      this.f = this.u();
    }
    return this.f;
  }
  async u() {
    let firstCall = true;
    const options3 = {
      commit: this.h,
      quality: this.j,
      addressProvider: {
        getAddress: async () => {
          if (firstCall) {
            firstCall = false;
          } else {
            this.a.fire(void 0);
          }
          const { authority } = await this.n.resolveAuthority(this.remoteAuthority);
          return { connectTo: authority.connectTo, connectionToken: authority.connectionToken };
        }
      },
      remoteSocketFactoryService: this.m,
      signService: this.r,
      logService: this.s,
      ipcLogger: false ? new $ou(`Local \u2192 Remote`, `Remote \u2192 Local`) : null
    };
    let connection;
    const start = Date.now();
    try {
      connection = this.B(await $iC(options3, this.remoteAuthority, `renderer`));
    } finally {
      this.g = Date.now() - start;
    }
    connection.protocol.onDidDispose(() => {
      connection.dispose();
    });
    this.end = () => {
      connection.protocol.sendDisconnect();
      return connection.protocol.drain();
    };
    this.B(connection.onDidStateChange((e) => this.b.fire(e)));
    return connection.client;
  }
};

// out-build/vs/workbench/services/remote/browser/remoteAgentService.js
var $0lc = class $0lc2 extends $9lc {
  constructor(remoteSocketFactoryService, userDataProfileService, environmentService, productService, remoteAuthorityResolverService, signService, logService) {
    super(remoteSocketFactoryService, userDataProfileService, environmentService, productService, remoteAuthorityResolverService, signService, logService);
  }
};
$0lc = __decorate([
  __param(0, $gC),
  __param(1, $gT),
  __param(2, $US),
  __param(3, $Vu),
  __param(4, $bC),
  __param(5, $lz),
  __param(6, $wn)
], $0lc);
var RemoteConnectionFailureNotificationContribution = class RemoteConnectionFailureNotificationContribution2 {
  static {
    this.ID = "workbench.contrib.browserRemoteConnectionFailureNotification";
  }
  constructor(remoteAgentService, a, b) {
    this.a = a;
    this.b = b;
    remoteAgentService.getRawEnvironment().then(void 0, (err) => {
      if (!$eC.isHandled(err)) {
        this.c(err);
      }
    });
  }
  async c(err) {
    await this.a.prompt({
      type: Severity2.Error,
      message: localize(13082, null),
      detail: localize(13083, null, err ? err.message : ""),
      buttons: [
        {
          label: localize(13084, null),
          run: () => this.b.reload()
        }
      ]
    });
  }
};
RemoteConnectionFailureNotificationContribution = __decorate([
  __param(0, $RL),
  __param(1, $Yv),
  __param(2, $S4)
], RemoteConnectionFailureNotificationContribution);
$PL(
  RemoteConnectionFailureNotificationContribution.ID,
  RemoteConnectionFailureNotificationContribution,
  2
  /* WorkbenchPhase.BlockRestore */
);

// out-build/vs/platform/remote/browser/remoteAuthorityResolverService.js
var $$lc = class $$lc2 extends $3c {
  constructor(isWorkbenchOptionsBasedResolution, connectionToken, resourceUriProvider, serverBasePath, productService, j) {
    super();
    this.j = j;
    this.a = this.B(new $ze());
    this.onDidChangeConnectionData = this.a.event;
    this.b = /* @__PURE__ */ new Map();
    this.c = /* @__PURE__ */ new Map();
    this.f = connectionToken;
    this.g = /* @__PURE__ */ new Map();
    this.h = isWorkbenchOptionsBasedResolution;
    if (resourceUriProvider) {
      $bh.setDelegate(resourceUriProvider);
    }
    $bh.setServerRootPath(productService, serverBasePath);
  }
  async resolveAuthority(authority) {
    let result = this.b.get(authority);
    if (!result) {
      result = new $gi();
      this.b.set(authority, result);
      if (this.h) {
        this.m(authority).then((v) => result.complete(v), (err) => result.error(err));
      }
    }
    return result.p;
  }
  async getCanonicalURI(uri) {
    return uri;
  }
  getConnectionData(authority) {
    if (!this.c.has(authority)) {
      return null;
    }
    const resolverResult = this.c.get(authority);
    const connectionToken = this.g.get(authority) || resolverResult.authority.connectionToken;
    return {
      connectTo: resolverResult.authority.connectTo,
      connectionToken
    };
  }
  async m(authority) {
    const authorityPrefix = $fC(authority);
    const sw = $te.create(false);
    this.j.info(`Resolving connection token (${authorityPrefix})...`);
    $S(`code/willResolveConnectionToken/${authorityPrefix}`);
    const connectionToken = await Promise.resolve(this.g.get(authority) || this.f);
    $S(`code/didResolveConnectionToken/${authorityPrefix}`);
    this.j.info(`Resolved connection token (${authorityPrefix}) after ${sw.elapsed()} ms`);
    const defaultPort = /^https:/.test($Y.location.href) ? 443 : 80;
    const { host, port } = $$v(authority, defaultPort);
    const result = { authority: { authority, connectTo: new $dC(host, port), connectionToken } };
    $bh.set(authority, host, port);
    this.c.set(authority, result);
    this.a.fire();
    return result;
  }
  _clearResolvedAuthority(authority) {
    if (this.b.has(authority)) {
      this.b.get(authority).cancel();
      this.b.delete(authority);
    }
  }
  _setResolvedAuthority(resolvedAuthority, options3) {
    if (this.b.has(resolvedAuthority.authority)) {
      const request = this.b.get(resolvedAuthority.authority);
      if (resolvedAuthority.connectTo.type === 0) {
        $bh.set(resolvedAuthority.authority, resolvedAuthority.connectTo.host, resolvedAuthority.connectTo.port);
      }
      if (resolvedAuthority.connectionToken) {
        $bh.setConnectionToken(resolvedAuthority.authority, resolvedAuthority.connectionToken);
      }
      request.complete({ authority: resolvedAuthority, options: options3 });
      this.a.fire();
    }
  }
  _setResolvedAuthorityError(authority, err) {
    if (this.b.has(authority)) {
      const request = this.b.get(authority);
      request.error($ub.fromError(err));
    }
  }
  _setAuthorityConnectionToken(authority, connectionToken) {
    this.g.set(authority, connectionToken);
    $bh.setConnectionToken(authority, connectionToken);
    this.a.fire();
  }
  _setCanonicalURIProvider(provider) {
  }
};
$$lc = __decorate([
  __param(4, $Vu),
  __param(5, $wn)
], $$lc);

// out-build/vs/platform/files/common/io.js
async function $ey(provider, resource, target, transformer, options3, token) {
  let error = void 0;
  try {
    await doReadFileIntoStream(provider, resource, target, transformer, options3, token);
  } catch (err) {
    error = err;
  } finally {
    if (error && options3.errorTransformer) {
      error = options3.errorTransformer(error);
    }
    if (typeof error !== "undefined") {
      target.error(error);
    }
    target.end();
  }
}
async function doReadFileIntoStream(provider, resource, target, transformer, options3, token) {
  throwIfCancelled(token);
  const handle2 = await provider.open(resource, { create: false });
  try {
    throwIfCancelled(token);
    let totalBytesRead = 0;
    let bytesRead = 0;
    let allowedRemainingBytes = options3 && typeof options3.length === "number" ? options3.length : void 0;
    let buffer = $Ci.alloc(Math.min(options3.bufferSize, typeof allowedRemainingBytes === "number" ? allowedRemainingBytes : options3.bufferSize));
    let posInFile = options3 && typeof options3.position === "number" ? options3.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 = $Ci.alloc(Math.min(options3.bufferSize, typeof allowedRemainingBytes === "number" ? allowedRemainingBytes : options3.bufferSize));
        posInBuffer = 0;
      }
    } while (bytesRead > 0 && (typeof allowedRemainingBytes !== "number" || allowedRemainingBytes > 0) && throwIfCancelled(token) && throwIfTooLarge(totalBytesRead, options3));
    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 $ym(error);
  } finally {
    await provider.close(handle2);
  }
}
function throwIfCancelled(token) {
  if (token.isCancellationRequested) {
    throw $mb();
  }
  return true;
}
function throwIfTooLarge(totalBytesRead, options3) {
  if (typeof options3?.limits?.size === "number" && totalBytesRead > options3.limits.size) {
    throw $xm(localize(1943, null), FileSystemProviderErrorCode.FileTooLarge);
  }
  return true;
}

// out-build/vs/platform/files/common/fileService.js
var $7B_1;
var $7B = class $7B2 extends $3c {
  static {
    $7B_1 = this;
  }
  constructor(b) {
    super();
    this.b = b;
    this.a = 256 * 1024;
    this.c = this.B(new $ze());
    this.onDidChangeFileSystemProviderRegistrations = this.c.event;
    this.f = this.B(new $ze());
    this.onWillActivateFileSystemProvider = this.f.event;
    this.g = this.B(new $ze());
    this.onDidChangeFileSystemProviderCapabilities = this.g.event;
    this.h = /* @__PURE__ */ new Map();
    this.r = this.B(new $ze());
    this.onDidRunOperation = this.r.event;
    this.X = this.B(new $ze());
    this.Y = this.B(new $ze());
    this.onDidFilesChange = this.Y.event;
    this.Z = this.B(new $ze());
    this.onDidWatchError = this.Z.event;
    this.$ = /* @__PURE__ */ new Map();
    this.cb = this.B(new $5h());
  }
  registerProvider(scheme, provider) {
    if (this.h.has(scheme)) {
      throw new Error(`A filesystem provider for the scheme '${scheme}' is already registered.`);
    }
    $S(`code/registerFilesystem/${scheme}`);
    const providerDisposables2 = new $2c();
    this.h.set(scheme, provider);
    this.c.fire({ added: true, scheme, provider });
    providerDisposables2.add(provider.onDidChangeFile((changes) => {
      const event = new $Dm(changes, !this.S(provider));
      this.X.fire(event);
      if (!event.hasCorrelation()) {
        this.Y.fire(event);
      }
    }));
    if (typeof provider.onDidWatchError === "function") {
      providerDisposables2.add(provider.onDidWatchError((error) => this.Z.fire(new Error(error))));
    }
    providerDisposables2.add(provider.onDidChangeCapabilities(() => this.g.fire({ provider, scheme })));
    return $1c(() => {
      this.c.fire({ added: false, scheme, provider });
      this.h.delete(scheme);
      $Xc(providerDisposables2);
    });
  }
  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 (!$zh(resource)) {
      throw new $Fm(
        localize(1916, 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 $ub();
      error.message = localize(1917, null, resource.toString());
      throw error;
    }
    return provider;
  }
  async m(resource) {
    const provider = await this.j(resource);
    if ($qm(provider) || $nm(provider) || $rm(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 ($qm(provider) || $nm(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, options3) {
    try {
      return await this.s(resource, options3);
    } catch (error) {
      if ($Am(error) === FileSystemProviderErrorCode.FileNotFound) {
        throw new $Fm(
          localize(1918, null, this.sb(resource)),
          1
          /* FileOperationResult.FILE_NOT_FOUND */
        );
      }
      throw $ym(error);
    }
  }
  async s(resource, options3) {
    const provider = await this.j(resource);
    const isPathCaseSensitive = this.S(provider);
    const resolveTo = options3?.resolveTo;
    const resolveSingleChildDescendants = options3?.resolveSingleChildDescendants;
    const resolveMetadata = options3?.resolveMetadata;
    const stat = await provider.stat(resource);
    let trie;
    return this.t(provider, resource, stat, void 0, !!resolveMetadata, (stat2, siblings) => {
      if (!trie) {
        trie = $Wk.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: $Qm({ mtime: stat.mtime, size: stat.size }),
      children: void 0
    };
    if (fileStat.isDirectory && recurse(fileStat, siblings)) {
      try {
        const entries2 = await provider.readdir(resource);
        const resolvedEntries = await Promises.settled(entries2.map(async ([name, type]) => {
          try {
            const childResource = providerExtUri.joinPath(resource, name);
            const childStat = resolveMetadata ? await provider.stat(childResource) : { type };
            return await this.t(provider, childResource, childStat, entries2.length, resolveMetadata, recurse);
          } catch (error) {
            this.b.trace(error);
            return null;
          }
        }));
        fileStat.children = $Mb(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, options3) {
    try {
      await this.u(resource, options3);
    } catch (error) {
      return error;
    }
    return true;
  }
  async u(resource, options3) {
    if (!options3?.overwrite && await this.exists(resource)) {
      throw new $Fm(localize(1919, null, this.sb(resource)), 3, options3);
    }
  }
  async createFile(resource, bufferOrReadableOrStream = $Ci.fromString(""), options3) {
    await this.u(resource, options3);
    const fileStat = await this.writeFile(resource, bufferOrReadableOrStream);
    this.r.fire(new $Cm(resource, 0, fileStat));
    return fileStat;
  }
  async writeFile(resource, bufferOrReadableOrStream, options3) {
    const provider = this.qb(await this.n(resource), resource);
    const { providerExtUri } = this.R(provider);
    let writeFileOptions = options3;
    if ($tm(provider) && !writeFileOptions?.atomic) {
      const enforcedAtomicWrite = provider.enforceAtomicWriteFile?.(resource);
      if (enforcedAtomicWrite) {
        writeFileOptions = { ...options3, atomic: enforcedAtomicWrite };
      }
    }
    try {
      const stat = await this.w(provider, resource, writeFileOptions);
      if (!stat) {
        await this.U(provider, providerExtUri.dirname(resource));
      }
      let bufferOrReadableOrStreamOrBufferedStream;
      if ($nm(provider) && !(bufferOrReadableOrStream instanceof $Ci)) {
        if ($oi(bufferOrReadableOrStream)) {
          const bufferedStream = await $vi(bufferOrReadableOrStream, 3);
          if (bufferedStream.ended) {
            bufferOrReadableOrStreamOrBufferedStream = $Ci.concat(bufferedStream.buffer);
          } else {
            bufferOrReadableOrStreamOrBufferedStream = bufferedStream;
          }
        } else {
          bufferOrReadableOrStreamOrBufferedStream = $si(bufferOrReadableOrStream, (data) => $Ci.concat(data), 3);
        }
      } else {
        bufferOrReadableOrStreamOrBufferedStream = bufferOrReadableOrStream;
      }
      if (!$qm(provider) || // buffered writing is unsupported
      $nm(provider) && bufferOrReadableOrStreamOrBufferedStream instanceof $Ci || // data is a full buffer already
      $nm(provider) && $tm(provider) && writeFileOptions?.atomic) {
        await this.hb(provider, resource, writeFileOptions, bufferOrReadableOrStreamOrBufferedStream);
      } else {
        await this.db(provider, resource, writeFileOptions, bufferOrReadableOrStreamOrBufferedStream instanceof $Ci ? $Ni(bufferOrReadableOrStreamOrBufferedStream) : bufferOrReadableOrStreamOrBufferedStream);
      }
      this.r.fire(new $Cm(
        resource,
        4
        /* FileOperation.WRITE */
      ));
    } catch (error) {
      throw new $Fm(localize(1920, null, this.sb(resource), $ym(error).toString()), $Bm(error), writeFileOptions);
    }
    return this.resolve(resource, { resolveMetadata: true });
  }
  async w(provider, resource, options3) {
    const unlock = !!options3?.unlock;
    if (unlock && !(provider.capabilities & 8192)) {
      throw new Error(localize(1921, null, this.sb(resource)));
    }
    const atomic = !!options3?.atomic;
    if (atomic) {
      if (!(provider.capabilities & 32768)) {
        throw new Error(localize(1922, null, this.sb(resource)));
      }
      if (!(provider.capabilities & 2)) {
        throw new Error(localize(1923, null, this.sb(resource)));
      }
      if (unlock) {
        throw new Error(localize(1924, 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 $Fm(localize(1925, null, this.sb(resource)), 0, options3);
    }
    this.rb(resource, stat);
    if (typeof options3?.mtime === "number" && typeof options3.etag === "string" && options3.etag !== $Pm && typeof stat.mtime === "number" && typeof stat.size === "number" && options3.mtime < stat.mtime && options3.etag !== $Qm({ mtime: options3.mtime, size: stat.size })) {
      throw new $Fm(localize(1926, null), 3, options3);
    }
    return stat;
  }
  async readFile(resource, options3, token) {
    const provider = await this.m(resource);
    if (options3?.atomic) {
      return this.z(provider, resource, options3, token);
    }
    return this.C(provider, resource, options3, token);
  }
  async z(provider, resource, options3, token) {
    return new Promise((resolve, reject) => {
      this.cb.queueFor(resource, async () => {
        try {
          const content = await this.C(provider, resource, options3, token);
          resolve(content);
        } catch (error) {
          reject(error);
        }
      }, this.R(provider).providerExtUri);
    });
  }
  async C(provider, resource, options3, token) {
    const stream = await this.D(provider, resource, {
      ...options3,
      // 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 $Oi(stream.value)
    };
  }
  async readFileStream(resource, options3, token) {
    const provider = await this.m(resource);
    return this.D(provider, resource, options3, token);
  }
  async D(provider, resource, options3, token) {
    const cancellableSource = new $ad(token);
    let readFileOptions = options3;
    if ($sm(provider) && provider.enforceAtomicReadFile?.(resource)) {
      readFileOptions = { ...options3, 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 !== $Pm) {
        await statPromise;
      }
      if (readFileOptions?.atomic && $sm(provider) || // atomic reads are always unbuffered
      !($qm(provider) || $rm(provider)) || // provider has no buffered capability
      $nm(provider) && readFileOptions?.preferUnbuffered) {
        fileStream = this.I(provider, resource, readFileOptions);
      } else if ($rm(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 $ti(fileStream);
      }
      throw this.F(error, resource, readFileOptions);
    }
  }
  F(error, resource, options3) {
    const message = localize(1927, null, this.sb(resource), $ym(error).toString());
    if (error instanceof $Hm) {
      return new $Hm(message, error.stat, options3);
    }
    if (error instanceof $Gm) {
      return new $Gm(message, error.fileOperationResult, error.size, error.options);
    }
    return new $Fm(message, $Bm(error), options3);
  }
  G(provider, resource, token, options3 = /* @__PURE__ */ Object.create(null)) {
    const fileStream = provider.readFileStream(resource, options3, token);
    return $zi(fileStream, {
      data: (data) => data instanceof $Ci ? data : $Ci.wrap(data),
      error: (error) => this.F(error, resource, options3)
    }, (data) => $Ci.concat(data));
  }
  H(provider, resource, token, options3 = /* @__PURE__ */ Object.create(null)) {
    const stream = $Si();
    $ey(provider, resource, stream, (data) => data, {
      ...options3,
      bufferSize: this.a,
      errorTransformer: (error) => this.F(error, resource, options3)
    }, token);
    return stream;
  }
  I(provider, resource, options3) {
    const stream = $qi((data) => $Ci.concat(data));
    (async () => {
      try {
        let buffer;
        if (options3?.atomic && $sm(provider)) {
          buffer = await provider.readFile(resource, { atomic: true });
        } else {
          buffer = await provider.readFile(resource);
        }
        if (typeof options3?.position === "number") {
          buffer = buffer.slice(options3.position);
        }
        if (typeof options3?.length === "number") {
          buffer = buffer.slice(0, options3.length);
        }
        this.L(resource, buffer.byteLength, options3);
        stream.end($Ci.wrap(buffer));
      } catch (err) {
        stream.error(err);
        stream.end();
      }
    })();
    return stream;
  }
  async J(resource, options3) {
    const stat = await this.resolve(resource, { resolveMetadata: true });
    if (stat.isDirectory) {
      throw new $Fm(localize(1928, null, this.sb(resource)), 0, options3);
    }
    if (typeof options3?.etag === "string" && options3.etag !== $Pm && options3.etag === stat.etag) {
      throw new $Hm(localize(1929, null), stat, options3);
    }
    this.L(resource, stat.size, options3);
    return stat;
  }
  L(resource, size, options3) {
    if (typeof options3?.limits?.size === "number" && size > options3.limits.size) {
      throw new $Gm(localize(1930, null, this.sb(resource)), 7, size, options3);
    }
  }
  //#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 $Cm(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 $Cm(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 && $om(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 ($qm(sourceProvider) && $qm(targetProvider)) {
      return this.jb(sourceProvider, source, targetProvider, target);
    }
    if ($qm(sourceProvider) && $nm(targetProvider)) {
      return this.pb(sourceProvider, source, targetProvider, target);
    }
    if ($nm(sourceProvider) && $qm(targetProvider)) {
      return this.nb(sourceProvider, source, targetProvider, target);
    }
    if ($nm(sourceProvider) && $nm(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(1931, null, this.sb(source), this.sb(target)));
      }
      if (!isSameResourceWithDifferentPathCase && providerExtUri.isEqualOrParent(target, source)) {
        throw new Error(localize(1932, null, this.sb(source), this.sb(target)));
      }
    }
    const exists = await this.exists(target);
    if (exists && !isSameResourceWithDifferentPathCase) {
      if (!overwrite) {
        throw new $Fm(
          localize(1933, 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(1934, null, this.sb(source), this.sb(target)));
        }
      }
    }
    return { exists, isSameResourceWithDifferentPathCase };
  }
  R(provider) {
    const isPathCaseSensitive = this.S(provider);
    return {
      providerExtUri: isPathCaseSensitive ? $lh : $nh,
      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 $Cm(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(1935, null, this.sb(directory)));
        }
        break;
      } catch (error) {
        if ($Am(error) !== FileSystemProviderErrorCode.FileNotFound) {
          throw error;
        }
        directoriesToCreate.push(providerExtUri.basename(directory));
        directory = providerExtUri.dirname(directory);
      }
    }
    for (let i2 = directoriesToCreate.length - 1; i2 >= 0; i2--) {
      directory = providerExtUri.joinPath(directory, directoriesToCreate[i2]);
      try {
        await provider.mkdir(directory);
      } catch (error) {
        if ($Am(error) !== FileSystemProviderErrorCode.FileExists) {
          throw error;
        }
      }
    }
  }
  async canDelete(resource, options3) {
    try {
      await this.W(resource, options3);
    } catch (error) {
      return error;
    }
    return true;
  }
  async W(resource, options3) {
    const provider = this.qb(await this.j(resource), resource);
    const useTrash = !!options3?.useTrash;
    if (useTrash && !(provider.capabilities & 4096)) {
      throw new Error(localize(1936, null, this.sb(resource)));
    }
    const atomic = options3?.atomic;
    if (atomic && !(provider.capabilities & 65536)) {
      throw new Error(localize(1937, null, this.sb(resource)));
    }
    if (useTrash && atomic) {
      throw new Error(localize(1938, 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 $Fm(
        localize(1939, null, this.sb(resource)),
        1
        /* FileOperationResult.FILE_NOT_FOUND */
      );
    }
    const recursive = !!options3?.recursive;
    if (!recursive) {
      const stat2 = await this.resolve(resource);
      if (stat2.isDirectory && Array.isArray(stat2.children) && stat2.children.length > 0) {
        throw new Error(localize(1940, null, this.sb(resource)));
      }
    }
    return provider;
  }
  async del(resource, options3) {
    const provider = await this.W(resource, options3);
    let deleteFileOptions = options3;
    if ($um(provider) && !deleteFileOptions?.atomic) {
      const enforcedAtomicDelete = provider.enforceAtomicDelete?.(resource);
      if (enforcedAtomicDelete) {
        deleteFileOptions = { ...options3, 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 $Cm(
      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 && $pm(sourceProvider)) {
      return sourceProvider.cloneFile(source, target);
    }
    await this.U(targetProvider, this.R(targetProvider).providerExtUri.dirname(target));
    if (sourceProvider === targetProvider && $om(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, options3) {
    return this.watch(resource, {
      ...options3,
      // 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: $7B_1.ab++
    });
  }
  watch(resource, options3 = { recursive: false, excludes: [] }) {
    const disposables = new $2c();
    let watchDisposed = false;
    let disposeWatch = () => {
      watchDisposed = true;
    };
    disposables.add($1c(() => disposeWatch()));
    (async () => {
      try {
        const disposable = await this.bb(resource, options3);
        if (watchDisposed) {
          $Xc(disposable);
        } else {
          disposeWatch = () => $Xc(disposable);
        }
      } catch (error) {
        this.b.error(error);
      }
    })();
    const correlationId = options3.correlationId;
    if (typeof correlationId === "number") {
      const fileChangeEmitter = disposables.add(new $ze());
      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, options3) {
    const provider = await this.j(resource);
    const watchHash = $Xi([this.R(provider).providerExtUri.getComparisonKey(resource), options3]);
    let watcher = this.$.get(watchHash);
    if (!watcher) {
      watcher = {
        count: 0,
        disposable: provider.watch(resource, options3)
      };
      this.$.set(watchHash, watcher);
    }
    watcher.count += 1;
    return $1c(() => {
      if (watcher) {
        watcher.count--;
        if (watcher.count === 0) {
          $Xc(watcher.disposable);
          this.$.delete(watchHash);
        }
      }
    });
  }
  dispose() {
    super.dispose();
    for (const [, watcher] of this.$) {
      $Xc(watcher.disposable);
    }
    this.$.clear();
  }
  async db(provider, resource, options3, readableOrStreamOrBufferedStream) {
    return this.cb.queueFor(resource, async () => {
      const handle2 = await provider.open(resource, { create: true, unlock: options3?.unlock ?? false });
      try {
        if ($oi(readableOrStreamOrBufferedStream) || $pi(readableOrStreamOrBufferedStream)) {
          await this.eb(provider, handle2, readableOrStreamOrBufferedStream);
        } else {
          await this.fb(provider, handle2, readableOrStreamOrBufferedStream);
        }
      } catch (error) {
        throw $ym(error);
      } finally {
        await provider.close(handle2);
      }
    }, this.R(provider).providerExtUri);
  }
  async eb(provider, handle2, streamOrBufferedStream) {
    let posInFile = 0;
    let stream;
    if ($pi(streamOrBufferedStream)) {
      if (streamOrBufferedStream.buffer.length > 0) {
        const chunk = $Ci.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) => {
      $ui(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, options3, bufferOrReadableOrStreamOrBufferedStream) {
    return this.cb.queueFor(resource, () => this.ib(provider, resource, options3, bufferOrReadableOrStreamOrBufferedStream), this.R(provider).providerExtUri);
  }
  async ib(provider, resource, options3, bufferOrReadableOrStreamOrBufferedStream) {
    let buffer;
    if (bufferOrReadableOrStreamOrBufferedStream instanceof $Ci) {
      buffer = bufferOrReadableOrStreamOrBufferedStream;
    } else if ($oi(bufferOrReadableOrStreamOrBufferedStream)) {
      buffer = await $Oi(bufferOrReadableOrStreamOrBufferedStream);
    } else if ($pi(bufferOrReadableOrStreamOrBufferedStream)) {
      buffer = await $Pi(bufferOrReadableOrStreamOrBufferedStream);
    } else {
      buffer = $Mi(bufferOrReadableOrStreamOrBufferedStream);
    }
    await provider.writeFile(resource, buffer.buffer, { create: true, overwrite: true, unlock: options3?.unlock ?? false, atomic: options3?.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 = $Ci.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 $ym(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, $Ci.wrap(buffer), buffer.byteLength, 0, 0);
    } catch (error) {
      throw $ym(error);
    } finally {
      await targetProvider.close(targetHandle);
    }
  }
  async pb(sourceProvider, source, targetProvider, target) {
    const buffer = await $Oi(this.H(sourceProvider, source, CancellationToken.None));
    await this.hb(targetProvider, target, void 0, buffer);
  }
  qb(provider, resource) {
    if (provider.capabilities & 2048) {
      throw new $Fm(
        localize(1941, null, this.sb(resource)),
        6
        /* FileOperationResult.FILE_PERMISSION_DENIED */
      );
    }
    return provider;
  }
  rb(resource, stat) {
    if ((stat.permissions ?? 0) & FilePermission.Readonly) {
      throw new $Fm(
        localize(1942, null, this.sb(resource)),
        6
        /* FileOperationResult.FILE_PERMISSION_DENIED */
      );
    }
  }
  sb(resource) {
    if (resource.scheme === Schemas.file) {
      return resource.fsPath;
    }
    return resource.toString(true);
  }
};
$7B = $7B_1 = __decorate([
  __param(0, $wn)
], $7B);

// out-build/vs/platform/configuration/common/configurationModels.js
function freeze2(data) {
  return Object.isFrozen(data) ? data : $Mv(data);
}
var $SB = class _$SB {
  static createEmptyModel(logService) {
    return new _$SB({}, [], [], 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 _$SB) {
            return raw;
          }
          const parser2 = new $TB("", this.f);
          parser2.parseRaw(raw);
          return parser2.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 ? $sl(this.contents, section) : this.contents;
  }
  inspect(section, overrideIdentifier) {
    const that = this;
    return {
      get value() {
        return freeze2(that.rawConfiguration.getValue(section));
      },
      get override() {
        return overrideIdentifier ? freeze2(that.rawConfiguration.getOverrideValue(section, overrideIdentifier)) : void 0;
      },
      get merged() {
        return freeze2(overrideIdentifier ? that.rawConfiguration.override(overrideIdentifier).getValue(section) : that.rawConfiguration.getValue(section));
      },
      get overrides() {
        const overrides = [];
        for (const { contents, identifiers: identifiers2, keys } of that.rawConfiguration.overrides) {
          const value = new _$SB(contents, keys, [], void 0, that.f).getValue(section);
          if (value !== void 0) {
            overrides.push({ identifiers: identifiers2, value });
          }
        }
        return overrides.length ? freeze2(overrides) : void 0;
      }
    };
  }
  getOverrideValue(section, overrideIdentifier) {
    const overrideContents = this.j(overrideIdentifier);
    return overrideContents ? section ? $sl(overrideContents, section) : overrideContents : void 0;
  }
  getKeysForOverrideIdentifier(identifier2) {
    const keys = [];
    for (const override of this.overrides) {
      if (override.identifiers.includes(identifier2)) {
        keys.push(...override.keys);
      }
    }
    return $Rb(keys);
  }
  getAllOverrideIdentifiers() {
    const result = [];
    for (const override of this.overrides) {
      result.push(...override.identifiers);
    }
    return $Rb(result);
  }
  override(identifier2) {
    let overrideConfigurationModel = this.a.get(identifier2);
    if (!overrideConfigurationModel) {
      overrideConfigurationModel = this.h(identifier2);
      this.a.set(identifier2, overrideConfigurationModel);
    }
    return overrideConfigurationModel;
  }
  merge(...others) {
    const contents = $Lv(this.contents);
    const overrides = $Lv(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) => $zb(o.identifiers, otherOverride.identifiers));
        if (override) {
          this.i(override.contents, otherOverride.contents);
          override.keys.push(...otherOverride.keys);
          override.keys = $Rb(override.keys);
        } else {
          overrides.push($Lv(otherOverride));
        }
      }
      for (const key2 of other.keys) {
        if (keys.indexOf(key2) === -1) {
          keys.push(key2);
        }
      }
    }
    return new _$SB(contents, keys, overrides, raws.every((raw) => raw instanceof _$SB) ? void 0 : raws, this.f);
  }
  h(identifier2) {
    const overrideContents = this.j(identifier2);
    if (!overrideContents || typeof overrideContents !== "object" || !Object.keys(overrideContents).length) {
      return this;
    }
    const contents = {};
    for (const key2 of $Rb([...Object.keys(this.contents), ...Object.keys(overrideContents)])) {
      let contentsForKey = this.contents[key2];
      const overrideContentsForKey = overrideContents[key2];
      if (overrideContentsForKey) {
        if (typeof contentsForKey === "object" && typeof overrideContentsForKey === "object") {
          contentsForKey = $Lv(contentsForKey);
          this.i(contentsForKey, overrideContentsForKey);
        } else {
          contentsForKey = overrideContentsForKey;
        }
      }
      contents[key2] = contentsForKey;
    }
    return new _$SB(contents, this.keys, this.overrides, void 0, this.f);
  }
  i(source, target) {
    for (const key2 of Object.keys(target)) {
      if (key2 in source) {
        if ($Bg(source[key2]) && $Bg(target[key2])) {
          this.i(source[key2], target[key2]);
          continue;
        }
      }
      source[key2] = $Lv(target[key2]);
    }
  }
  j(identifier2) {
    let contentsForIdentifierOnly = null;
    let contents = null;
    const mergeContents = (contentsToMerge) => {
      if (contentsToMerge) {
        if (contents) {
          this.i(contents, contentsToMerge);
        } else {
          contents = $Lv(contentsToMerge);
        }
      }
    };
    for (const override of this.overrides) {
      if (override.identifiers.length === 1 && override.identifiers[0] === identifier2) {
        contentsForIdentifierOnly = override.contents;
      } else if (override.identifiers.includes(identifier2)) {
        mergeContents(override.contents);
      }
    }
    mergeContents(contentsForIdentifierOnly);
    return contents;
  }
  toJSON() {
    return {
      contents: this.contents,
      overrides: this.overrides,
      keys: this.keys
    };
  }
  // Update methods
  addValue(key2, value) {
    this.k(key2, value, true);
  }
  setValue(key2, value) {
    this.k(key2, value, false);
  }
  removeValue(key2) {
    const index = this.keys.indexOf(key2);
    if (index === -1) {
      return;
    }
    this.keys.splice(index, 1);
    $rl(this.contents, key2);
    if ($Rt.test(key2)) {
      this.overrides.splice(this.overrides.findIndex((o) => $zb(o.identifiers, $St(key2))), 1);
    }
  }
  k(key2, value, add) {
    $ql(this.contents, key2, value, (e) => this.f.error(e));
    add = add || this.keys.indexOf(key2) === -1;
    if (add) {
      this.keys.push(key2);
    }
    if ($Rt.test(key2)) {
      const identifiers2 = $St(key2);
      const override = {
        identifiers: identifiers2,
        keys: Object.keys(this.contents[key2]),
        contents: $pl(this.contents[key2], (message) => this.f.error(message))
      };
      const index = this.overrides.findIndex((o) => $zb(o.identifiers, identifiers2));
      if (index !== -1) {
        this.overrides[index] = override;
      } else {
        this.overrides.push(override);
      }
    }
  }
};
var $TB = 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 || $SB.createEmptyModel(this.g);
  }
  get restrictedConfigurations() {
    return this.c;
  }
  get errors() {
    return this.d;
  }
  parse(content, options3) {
    if (!$Ig(content)) {
      const raw = this.h(content);
      this.parseRaw(raw, options3);
    }
  }
  reparse(options3) {
    if (this.a) {
      this.parseRaw(this.a, options3);
    }
  }
  parseRaw(raw, options3) {
    this.a = raw;
    const { contents, keys, overrides, restricted, hasExcludedProperties } = this.i(raw, options3);
    this.b = new $SB(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 array2 = [];
        onValue(array2);
        previousParents.push(currentParent);
        currentParent = array2;
        currentProperty = null;
      },
      onArrayEnd: () => {
        currentParent = previousParents.pop();
      },
      onLiteralValue: onValue,
      onError: (error, offset, length) => {
        parseErrors.push({ error, offset, length });
      }
    };
    if (content) {
      try {
        $Fw(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, options3) {
    const configurationProperties = $Wn.as($Ht.Configuration).getConfigurationProperties();
    const filtered = this.j(raw, configurationProperties, true, options3);
    raw = filtered.raw;
    const contents = $pl(raw, (message) => this.g.error(`Conflict in settings file ${this.f}: ${message}`));
    const keys = Object.keys(raw);
    const overrides = this.m(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, options3) {
    let hasExcludedProperties = false;
    if (!options3?.scopes && !options3?.skipRestricted && !options3?.exclude?.length) {
      return { raw: properties, restricted: [], hasExcludedProperties };
    }
    const raw = {};
    const restricted = [];
    for (const key2 in properties) {
      if ($Rt.test(key2) && filterOverriddenProperties) {
        const result = this.j(properties[key2], configurationProperties, false, options3);
        raw[key2] = result.raw;
        hasExcludedProperties = hasExcludedProperties || result.hasExcludedProperties;
        restricted.push(...result.restricted);
      } else {
        const propertySchema = configurationProperties[key2];
        if (propertySchema?.restricted) {
          restricted.push(key2);
        }
        if (this.l(key2, propertySchema, options3)) {
          raw[key2] = properties[key2];
        } else {
          hasExcludedProperties = true;
        }
      }
    }
    return { raw, restricted, hasExcludedProperties };
  }
  l(key2, propertySchema, options3) {
    if (options3.exclude?.includes(key2)) {
      return false;
    }
    if (options3.include?.includes(key2)) {
      return true;
    }
    if (options3.skipRestricted && propertySchema?.restricted) {
      return false;
    }
    if (options3.skipUnregistered && !propertySchema) {
      return false;
    }
    const scope = propertySchema ? typeof propertySchema.scope !== "undefined" ? propertySchema.scope : 3 : void 0;
    if (scope === void 0 || options3.scopes === void 0) {
      return true;
    }
    return options3.scopes.includes(scope);
  }
  m(raw, conflictReporter) {
    const overrides = [];
    for (const key2 of Object.keys(raw)) {
      if ($Rt.test(key2)) {
        const overrideRaw = {};
        for (const keyInOverrideRaw in raw[key2]) {
          overrideRaw[keyInOverrideRaw] = raw[key2][keyInOverrideRaw];
        }
        overrides.push({
          identifiers: $St(key2),
          keys: Object.keys(overrideRaw),
          contents: $pl(overrideRaw, conflictReporter)
        });
      }
    }
    return overrides;
  }
};
var $UB = class extends $3c {
  constructor(c, f, extUri, g, h3) {
    super();
    this.c = c;
    this.f = f;
    this.g = g;
    this.h = h3;
    this.b = this.B(new $ze());
    this.onDidChange = this.b.event;
    this.a = new $TB(this.c.toString(), h3);
    this.B(this.g.watch(extUri.dirname(this.c)));
    this.B(this.g.watch(this.c));
    this.B(Event2.any(Event2.filter(this.g.onDidFilesChange, (e) => e.contains(this.c)), Event2.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 $SB.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, h3, i2, 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 = h3;
    this.i = i2;
    this.j = j;
    this.k = k;
    this.l = l;
    this.m = m;
  }
  get value() {
    return freeze2(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 $VB = class _$VB {
  constructor(j, l, m, n, p, q, r2, s, t, u) {
    this.j = j;
    this.l = l;
    this.m = m;
    this.n = n;
    this.p = p;
    this.q = q;
    this.r = r2;
    this.s = s;
    this.t = t;
    this.u = u;
    this.h = null;
    this.i = new $Ec();
    this.v = null;
  }
  getValue(section, overrides, workspace2) {
    const consolidateConfigurationModel = this.w(section, overrides, workspace2);
    return consolidateConfigurationModel.getValue(section);
  }
  updateValue(key2, value, overrides = {}) {
    let memoryConfiguration;
    if (overrides.resource) {
      memoryConfiguration = this.t.get(overrides.resource);
      if (!memoryConfiguration) {
        memoryConfiguration = $SB.createEmptyModel(this.u);
        this.t.set(overrides.resource, memoryConfiguration);
      }
    } else {
      memoryConfiguration = this.s;
    }
    if (value === void 0) {
      memoryConfiguration.removeValue(key2);
    } else {
      memoryConfiguration.setValue(key2, value);
    }
    if (!overrides.resource) {
      this.h = null;
    }
  }
  inspect(key2, overrides, workspace2) {
    const consolidateConfigurationModel = this.w(key2, overrides, workspace2);
    const folderConfigurationModel = this.A(overrides.resource, workspace2);
    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(key2, overrideIdentifier) !== void 0) {
          overrideIdentifiers.add(overrideIdentifier);
        }
      }
    }
    return new ConfigurationInspectValue(key2, overrides, consolidateConfigurationModel.getValue(key2), 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, workspace2 ? this.q : void 0, folderConfigurationModel ? folderConfigurationModel : void 0, memoryConfigurationModel);
  }
  keys(workspace2) {
    const folderConfigurationModel = this.A(void 0, workspace2);
    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, configuration2) {
    this.r.set(resource, configuration2);
    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 } = compare4(this.j, defaults);
      keys = [...added, ...updated, ...removed];
    }
    for (const key2 of keys) {
      for (const overrideIdentifier of $St(key2)) {
        const fromKeys = this.j.getKeysForOverrideIdentifier(overrideIdentifier);
        const toKeys = defaults.getKeysForOverrideIdentifier(overrideIdentifier);
        const keys2 = [
          ...toKeys.filter((key3) => fromKeys.indexOf(key3) === -1),
          ...fromKeys.filter((key3) => toKeys.indexOf(key3) === -1),
          ...fromKeys.filter((key3) => !$Pv(this.j.override(overrideIdentifier).getValue(key3), defaults.override(overrideIdentifier).getValue(key3)))
        ];
        overrides.push([overrideIdentifier, keys2]);
      }
    }
    this.updateDefaultConfiguration(defaults);
    return { keys, overrides };
  }
  compareAndUpdatePolicyConfiguration(policyConfiguration) {
    const { added, updated, removed } = compare4(this.l, policyConfiguration);
    const keys = [...added, ...updated, ...removed];
    if (keys.length) {
      this.updatePolicyConfiguration(policyConfiguration);
    }
    return { keys, overrides: [] };
  }
  compareAndUpdateApplicationConfiguration(application) {
    const { added, updated, removed, overrides } = compare4(this.applicationConfiguration, application);
    const keys = [...added, ...updated, ...removed];
    if (keys.length) {
      this.updateApplicationConfiguration(application);
    }
    return { keys, overrides };
  }
  compareAndUpdateLocalUserConfiguration(user) {
    const { added, updated, removed, overrides } = compare4(this.localUserConfiguration, user);
    const keys = [...added, ...updated, ...removed];
    if (keys.length) {
      this.updateLocalUserConfiguration(user);
    }
    return { keys, overrides };
  }
  compareAndUpdateRemoteUserConfiguration(user) {
    const { added, updated, removed, overrides } = compare4(this.remoteUserConfiguration, user);
    const keys = [...added, ...updated, ...removed];
    if (keys.length) {
      this.updateRemoteUserConfiguration(user);
    }
    return { keys, overrides };
  }
  compareAndUpdateWorkspaceConfiguration(workspaceConfiguration) {
    const { added, updated, removed, overrides } = compare4(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 } = compare4(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 } = compare4(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, workspace2) {
    let configurationModel = this.x(overrides, workspace2);
    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 }, workspace2) {
    let consolidateConfiguration = this.y();
    if (workspace2 && resource) {
      const root = workspace2.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, workspace2) {
    if (workspace2 && resource) {
      const root = workspace2.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((key2) => keys.add(key2));
    this.userConfiguration.keys.forEach((key2) => keys.add(key2));
    this.q.keys.forEach((key2) => keys.add(key2));
    this.r.forEach((folderConfiguration) => folderConfiguration.keys.forEach((key2) => keys.add(key2)));
    return [...keys.values()];
  }
  B() {
    const keys = /* @__PURE__ */ new Set();
    this.j.getAllOverrideIdentifiers().forEach((key2) => keys.add(key2));
    this.userConfiguration.getAllOverrideIdentifiers().forEach((key2) => keys.add(key2));
    this.q.getAllOverrideIdentifiers().forEach((key2) => keys.add(key2));
    this.r.forEach((folderConfiguration) => folderConfiguration.getAllOverrideIdentifiers().forEach((key2) => keys.add(key2)));
    return [...keys.values()];
  }
  D(overrideIdentifier) {
    const keys = /* @__PURE__ */ new Set();
    this.j.getKeysForOverrideIdentifier(overrideIdentifier).forEach((key2) => keys.add(key2));
    this.userConfiguration.getKeysForOverrideIdentifier(overrideIdentifier).forEach((key2) => keys.add(key2));
    this.q.getKeysForOverrideIdentifier(overrideIdentifier).forEach((key2) => keys.add(key2));
    this.r.forEach((folderConfiguration) => folderConfiguration.getKeysForOverrideIdentifier(overrideIdentifier).forEach((key2) => keys.add(key2)));
    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 $Ec());
    return new _$VB(defaultConfiguration, policyConfiguration, applicationConfiguration, userConfiguration, $SB.createEmptyModel(logService), workspaceConfiguration, folders, $SB.createEmptyModel(logService), new $Ec(), logService);
  }
  static E(model, logService) {
    return new $SB(model.contents, model.keys, model.overrides, void 0, logService);
  }
};
function $WB(...changes) {
  if (changes.length === 0) {
    return { keys: [], overrides: [] };
  }
  if (changes.length === 1) {
    return changes[0];
  }
  const keysSet = /* @__PURE__ */ new Set();
  const overridesMap = /* @__PURE__ */ new Map();
  for (const change of changes) {
    change.keys.forEach((key2) => keysSet.add(key2));
    change.overrides.forEach(([identifier2, keys]) => {
      const result = $Bc(overridesMap, identifier2, /* @__PURE__ */ new Set());
      keys.forEach((key2) => result.add(key2));
    });
  }
  const overrides = [];
  overridesMap.forEach((keys, identifier2) => overrides.push([identifier2, [...keys.values()]]));
  return { keys: [...keysSet.values()], overrides };
}
var $XB = class {
  constructor(change, f, g, h3, i2) {
    this.change = change;
    this.f = f;
    this.g = g;
    this.h = h3;
    this.i = i2;
    this.a = "\n";
    this.b = this.a.charCodeAt(0);
    this.c = ".".charCodeAt(0);
    this.affectedKeys = /* @__PURE__ */ new Set();
    this.j = void 0;
    for (const key2 of change.keys) {
      this.affectedKeys.add(key2);
    }
    for (const [, keys] of change.overrides) {
      for (const key2 of keys) {
        this.affectedKeys.add(key2);
      }
    }
    this.d = this.a;
    for (const key2 of this.affectedKeys) {
      this.d += key2 + this.a;
    }
  }
  get previousConfiguration() {
    if (!this.j && this.f) {
      this.j = $VB.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 !$Pv(value1, value2);
    }
    return true;
  }
};
function compare4(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((key2) => !fromOverrideIdentifiers.includes(key2));
    for (const identifier2 of addedOverrideIdentifiers) {
      overrides.push([identifier2, to.getKeysForOverrideIdentifier(identifier2)]);
    }
  }
  if (from) {
    const removedOverrideIdentifiers = fromOverrideIdentifiers.filter((key2) => !toOverrideIdentifiers.includes(key2));
    for (const identifier2 of removedOverrideIdentifiers) {
      overrides.push([identifier2, from.getKeysForOverrideIdentifier(identifier2)]);
    }
  }
  if (to && from) {
    for (const identifier2 of fromOverrideIdentifiers) {
      if (toOverrideIdentifiers.includes(identifier2)) {
        const result = compareConfigurationContents({ contents: from.getOverrideValue(void 0, identifier2) || {}, keys: from.getKeysForOverrideIdentifier(identifier2) }, { contents: to.getOverrideValue(void 0, identifier2) || {}, keys: to.getKeysForOverrideIdentifier(identifier2) });
        overrides.push([identifier2, [...result.added, ...result.removed, ...result.updated]]);
      }
    }
  }
  return { added, removed, updated, overrides };
}
function compareConfigurationContents(to, from) {
  const added = to ? from ? to.keys.filter((key2) => from.keys.indexOf(key2) === -1) : [...to.keys] : [];
  const removed = from ? to ? from.keys.filter((key2) => to.keys.indexOf(key2) === -1) : [...from.keys] : [];
  const updated = [];
  if (to && from) {
    for (const key2 of from.keys) {
      if (to.keys.indexOf(key2) !== -1) {
        const value1 = $sl(from.contents, key2);
        const value2 = $sl(to.contents, key2);
        if (!$Pv(value1, value2)) {
          updated.push(key2);
        }
      }
    }
  }
  return { added, removed, updated };
}

// out-build/vs/platform/policy/common/policy.js
var $Pn = $Qk("policy");
var $Rn = class {
  constructor() {
    this.onDidChange = Event2.None;
  }
  async updatePolicyDefinitions() {
    return {};
  }
  getPolicyValue() {
    return void 0;
  }
  serialize() {
    return void 0;
  }
};

// out-build/vs/platform/configuration/common/configurations.js
var $YB = class extends $3c {
  get configurationModel() {
    return this.b;
  }
  constructor(c) {
    super();
    this.c = c;
    this.a = this.B(new $ze());
    this.onDidChangeConfiguration = this.a.event;
    this.b = $SB.createEmptyModel(this.c);
  }
  async initialize() {
    this.h();
    this.B($Wn.as($Ht.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, $Wn.as($Ht.Configuration).getConfigurationProperties());
    this.a.fire({ defaults: this.configurationModel, properties });
  }
  g() {
    return {};
  }
  h() {
    this.b = $SB.createEmptyModel(this.c);
    const properties = $Wn.as($Ht.Configuration).getConfigurationProperties();
    this.j(Object.keys(properties), properties);
  }
  j(properties, configurationProperties) {
    const configurationDefaultsOverrides = this.g();
    for (const key2 of properties) {
      const defaultOverrideValue = configurationDefaultsOverrides[key2];
      const propertySchema = configurationProperties[key2];
      if (defaultOverrideValue !== void 0) {
        this.b.setValue(key2, defaultOverrideValue);
      } else if (propertySchema) {
        this.b.setValue(key2, propertySchema.default);
      } else {
        this.b.removeValue(key2);
      }
    }
  }
};
var $ZB = class {
  constructor() {
    this.onDidChangeConfiguration = Event2.None;
    this.configurationModel = $SB.createEmptyModel(new $Jn());
  }
  async initialize() {
    return this.configurationModel;
  }
};
var $1B = class $1B2 extends $3c {
  get configurationModel() {
    return this.b;
  }
  constructor(c, f, g) {
    super();
    this.c = c;
    this.f = f;
    this.g = g;
    this.a = this.B(new $ze());
    this.onDidChangeConfiguration = this.a.event;
    this.b = $SB.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 = $Wn.as($Ht.Configuration).getConfigurationProperties();
    for (const key2 of properties) {
      const config = configurationProperties[key2];
      if (!config) {
        keys.push(key2);
        continue;
      }
      if (config.policy) {
        if (config.type !== "string" && config.type !== "number" && config.type !== "array" && config.type !== "object") {
          this.g.warn(`Policy ${config.policy.name} has unsupported type ${config.type}`);
          continue;
        }
        keys.push(key2);
        policyDefinitions[config.policy.name] = { type: config.type === "number" ? "number" : "string" };
      }
    }
    if (!$Mg(policyDefinitions)) {
      await this.f.updatePolicyDefinitions(policyDefinitions);
    }
    return keys;
  }
  j(policyNames) {
    this.g.trace("PolicyConfiguration#onDidChangePolicies", policyNames);
    const policyConfigurations = $Wn.as($Ht.Configuration).getPolicyConfigurations();
    const keys = $Mb(policyNames.map((policyName) => policyConfigurations.get(policyName)));
    this.m(keys, true);
  }
  m(keys, trigger) {
    this.g.trace("PolicyConfiguration#update", keys);
    const configurationProperties = $Wn.as($Ht.Configuration).getConfigurationProperties();
    const changed = [];
    const wasEmpty = this.b.isEmpty();
    for (const key2 of keys) {
      const proprety = configurationProperties[key2];
      const policyName = proprety?.policy?.name;
      if (policyName) {
        let policyValue = this.f.getPolicyValue(policyName);
        if ($zg(policyValue) && proprety.type !== "string") {
          try {
            policyValue = this.n(policyValue);
          } catch (e) {
            this.g.error(`Error parsing policy value ${policyName}:`, $qb(e));
            continue;
          }
        }
        if (wasEmpty ? policyValue !== void 0 : !$Pv(this.b.getValue(key2), policyValue)) {
          changed.push([key2, policyValue]);
        }
      } else {
        if (this.b.getValue(key2) !== void 0) {
          changed.push([key2, void 0]);
        }
      }
    }
    if (changed.length) {
      this.g.trace("PolicyConfiguration#changed", changed);
      const old = this.b;
      this.b = $SB.createEmptyModel(this.g);
      for (const key2 of old.keys) {
        this.b.setValue(key2, old.getValue(key2));
      }
      for (const [key2, policyValue] of changed) {
        if (policyValue === void 0) {
          this.b.removeValue(key2);
        } else {
          this.b.setValue(key2, policyValue);
        }
      }
      if (trigger) {
        this.a.fire(this.b);
      }
    }
  }
  n(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) {
        if (currentParent[currentProperty] !== void 0) {
          throw new Error(`Duplicate property found: ${currentProperty}`);
        }
        currentParent[currentProperty] = value;
      }
    }
    const visitor = {
      onObjectBegin: () => {
        const object = {};
        onValue(object);
        previousParents.push(currentParent);
        currentParent = object;
        currentProperty = null;
      },
      onObjectProperty: (name) => {
        currentProperty = name;
      },
      onObjectEnd: () => {
        currentParent = previousParents.pop();
      },
      onArrayBegin: () => {
        const array2 = [];
        onValue(array2);
        previousParents.push(currentParent);
        currentParent = array2;
        currentProperty = null;
      },
      onArrayEnd: () => {
        currentParent = previousParents.pop();
      },
      onLiteralValue: onValue,
      onError: (error, offset, length) => {
        parseErrors.push({ error, offset, length });
      }
    };
    if (content) {
      $Fw(content, visitor);
      raw = currentParent[0] || {};
    }
    if (parseErrors.length > 0) {
      throw new Error(parseErrors.map((e) => $qb(e.error)).join("\n"));
    }
    return raw;
  }
};
$1B = __decorate([
  __param(1, $Pn),
  __param(2, $wn)
], $1B);

// out-build/vs/workbench/services/configuration/common/configurationModels.js
var $_lc = class extends $TB {
  constructor(name, logService) {
    super(name, logService);
    this.n = [];
    this.p = false;
    this.q = new $TB(name, logService);
    this.r = $SB.createEmptyModel(logService);
    this.s = $SB.createEmptyModel(logService);
  }
  get folders() {
    return this.n;
  }
  get transient() {
    return this.p;
  }
  get settingsModel() {
    return this.q.configurationModel;
  }
  get launchModel() {
    return this.r;
  }
  get tasksModel() {
    return this.s;
  }
  reparseWorkspaceSettings(configurationParseOptions) {
    this.q.reparse(configurationParseOptions);
  }
  getRestrictedWorkspaceSettings() {
    return this.q.restrictedConfigurations;
  }
  i(raw, configurationParseOptions) {
    this.n = raw["folders"] || [];
    this.p = $Fg(raw["transient"]) && raw["transient"];
    this.q.parseRaw(raw["settings"], configurationParseOptions);
    this.r = this.u(raw, "launch");
    this.s = this.u(raw, "tasks");
    return super.i(raw, configurationParseOptions);
  }
  u(raw, key2) {
    const data = raw[key2];
    if (data) {
      const contents = $pl(data, (message) => console.error(`Conflict in settings file ${this.f}: ${message}`));
      const scopedContents = /* @__PURE__ */ Object.create(null);
      scopedContents[key2] = contents;
      const keys = Object.keys(data).map((k) => `${key2}.${k}`);
      return new $SB(scopedContents, keys, [], void 0, this.g);
    }
    return $SB.createEmptyModel(this.g);
  }
};
var $amc = class extends $TB {
  constructor(name, n, logService) {
    super(name, logService);
    this.n = n;
  }
  i(raw, configurationParseOptions) {
    const contents = $pl(raw, (message) => console.error(`Conflict in settings file ${this.f}: ${message}`));
    const scopedContents = /* @__PURE__ */ Object.create(null);
    scopedContents[this.n] = contents;
    const keys = Object.keys(raw).map((key2) => `${this.n}.${key2}`);
    return { contents: scopedContents, keys, overrides: [] };
  }
};
var $bmc = class extends $VB {
  constructor(defaults, policy, application, localUser, remoteUser, workspaceConfiguration, folders, memoryConfiguration, memoryConfigurationByResource, a, logService) {
    super(defaults, policy, application, localUser, remoteUser, workspaceConfiguration, folders, memoryConfiguration, memoryConfigurationByResource, logService);
    this.a = a;
  }
  getValue(key2, overrides = {}) {
    return super.getValue(key2, overrides, this.a);
  }
  inspect(key2, overrides = {}) {
    return super.inspect(key2, overrides, this.a);
  }
  keys() {
    return super.keys(this.a);
  }
  compareAndDeleteFolderConfiguration(folder) {
    if (this.a && this.a.folders.length > 0 && this.a.folders[0].uri.toString() === folder.toString()) {
      return { keys: [], overrides: [] };
    }
    return super.compareAndDeleteFolderConfiguration(folder);
  }
  compare(other) {
    const compare8 = (fromKeys, toKeys, overrideIdentifier) => {
      const keys2 = [];
      keys2.push(...toKeys.filter((key2) => fromKeys.indexOf(key2) === -1));
      keys2.push(...fromKeys.filter((key2) => toKeys.indexOf(key2) === -1));
      keys2.push(...fromKeys.filter((key2) => {
        if (toKeys.indexOf(key2) === -1) {
          return false;
        }
        if (!$Pv(this.getValue(key2, { overrideIdentifier }), other.getValue(key2, { overrideIdentifier }))) {
          return true;
        }
        return this.a && this.a.folders.some((folder) => !$Pv(this.getValue(key2, { resource: folder.uri, overrideIdentifier }), other.getValue(key2, { resource: folder.uri, overrideIdentifier })));
      }));
      return keys2;
    };
    const keys = compare8(this.allKeys(), other.allKeys());
    const overrides = [];
    const allOverrideIdentifiers = $Rb([...this.B(), ...other.B()]);
    for (const overrideIdentifier of allOverrideIdentifiers) {
      const keys2 = compare8(this.D(overrideIdentifier), other.D(overrideIdentifier), overrideIdentifier);
      if (keys2.length) {
        overrides.push([overrideIdentifier, keys2]);
      }
    }
    return { keys, overrides };
  }
};

// out-build/vs/workbench/services/configuration/common/configurationEditing.js
var ConfigurationEditingErrorCode;
(function(ConfigurationEditingErrorCode2) {
  ConfigurationEditingErrorCode2[ConfigurationEditingErrorCode2["ERROR_UNKNOWN_KEY"] = 0] = "ERROR_UNKNOWN_KEY";
  ConfigurationEditingErrorCode2[ConfigurationEditingErrorCode2["ERROR_INVALID_WORKSPACE_CONFIGURATION_APPLICATION"] = 1] = "ERROR_INVALID_WORKSPACE_CONFIGURATION_APPLICATION";
  ConfigurationEditingErrorCode2[ConfigurationEditingErrorCode2["ERROR_INVALID_WORKSPACE_CONFIGURATION_MACHINE"] = 2] = "ERROR_INVALID_WORKSPACE_CONFIGURATION_MACHINE";
  ConfigurationEditingErrorCode2[ConfigurationEditingErrorCode2["ERROR_INVALID_FOLDER_CONFIGURATION"] = 3] = "ERROR_INVALID_FOLDER_CONFIGURATION";
  ConfigurationEditingErrorCode2[ConfigurationEditingErrorCode2["ERROR_INVALID_USER_TARGET"] = 4] = "ERROR_INVALID_USER_TARGET";
  ConfigurationEditingErrorCode2[ConfigurationEditingErrorCode2["ERROR_INVALID_WORKSPACE_TARGET"] = 5] = "ERROR_INVALID_WORKSPACE_TARGET";
  ConfigurationEditingErrorCode2[ConfigurationEditingErrorCode2["ERROR_INVALID_FOLDER_TARGET"] = 6] = "ERROR_INVALID_FOLDER_TARGET";
  ConfigurationEditingErrorCode2[ConfigurationEditingErrorCode2["ERROR_INVALID_RESOURCE_LANGUAGE_CONFIGURATION"] = 7] = "ERROR_INVALID_RESOURCE_LANGUAGE_CONFIGURATION";
  ConfigurationEditingErrorCode2[ConfigurationEditingErrorCode2["ERROR_NO_WORKSPACE_OPENED"] = 8] = "ERROR_NO_WORKSPACE_OPENED";
  ConfigurationEditingErrorCode2[ConfigurationEditingErrorCode2["ERROR_CONFIGURATION_FILE_DIRTY"] = 9] = "ERROR_CONFIGURATION_FILE_DIRTY";
  ConfigurationEditingErrorCode2[ConfigurationEditingErrorCode2["ERROR_CONFIGURATION_FILE_MODIFIED_SINCE"] = 10] = "ERROR_CONFIGURATION_FILE_MODIFIED_SINCE";
  ConfigurationEditingErrorCode2[ConfigurationEditingErrorCode2["ERROR_INVALID_CONFIGURATION"] = 11] = "ERROR_INVALID_CONFIGURATION";
  ConfigurationEditingErrorCode2[ConfigurationEditingErrorCode2["ERROR_POLICY_CONFIGURATION"] = 12] = "ERROR_POLICY_CONFIGURATION";
  ConfigurationEditingErrorCode2[ConfigurationEditingErrorCode2["ERROR_INTERNAL"] = 13] = "ERROR_INTERNAL";
})(ConfigurationEditingErrorCode || (ConfigurationEditingErrorCode = {}));
var $cmc = class extends $ub {
  constructor(message, code) {
    super(message);
    this.code = code;
  }
};
var EditableConfigurationTarget;
(function(EditableConfigurationTarget2) {
  EditableConfigurationTarget2[EditableConfigurationTarget2["USER_LOCAL"] = 1] = "USER_LOCAL";
  EditableConfigurationTarget2[EditableConfigurationTarget2["USER_REMOTE"] = 2] = "USER_REMOTE";
  EditableConfigurationTarget2[EditableConfigurationTarget2["WORKSPACE"] = 3] = "WORKSPACE";
  EditableConfigurationTarget2[EditableConfigurationTarget2["WORKSPACE_FOLDER"] = 4] = "WORKSPACE_FOLDER";
})(EditableConfigurationTarget || (EditableConfigurationTarget = {}));
var $dmc = class $dmc2 {
  constructor(b, c, d, e, f, g, h3, i2, j, k, l, m) {
    this.b = b;
    this.c = c;
    this.d = d;
    this.e = e;
    this.f = f;
    this.g = g;
    this.h = h3;
    this.i = i2;
    this.j = j;
    this.k = k;
    this.l = l;
    this.m = m;
    this.a = new $3h();
  }
  async writeConfiguration(target, value, options3 = {}) {
    const operation = this.F(target, value, options3.scopes || {});
    return this.a.queue(async () => {
      try {
        await this.n(operation, options3);
      } catch (error) {
        if (options3.donotNotifyError) {
          throw error;
        }
        await this.t(error, operation, options3.scopes);
      }
    });
  }
  async n(operation, options3) {
    await this.E(operation.target, operation, !options3.handleDirtyFile, options3.scopes || {});
    const resource = operation.resource;
    const reference = await this.C(resource);
    try {
      const formattingOptions = this.s(reference.object.textEditorModel);
      await this.o(operation, reference.object.textEditorModel, formattingOptions, options3);
    } finally {
      reference.dispose();
    }
  }
  async o(operation, model, formattingOptions, options3) {
    if (this.D(model.getValue(), operation)) {
      throw this.y(11, operation.target, operation);
    }
    if (this.i.isDirty(model.uri) && options3.handleDirtyFile) {
      switch (options3.handleDirtyFile) {
        case "save":
          await this.p(model, operation);
          break;
        case "revert":
          await this.i.revert(model.uri);
          break;
      }
    }
    const edit3 = this.r(operation, model.getValue(), formattingOptions)[0];
    if (edit3 && this.q(edit3, model)) {
      await this.p(model, operation);
    }
  }
  async p(model, operation) {
    try {
      await this.i.save(model.uri, { ignoreErrorHandler: true });
    } catch (error) {
      if (error.fileOperationResult === 3) {
        throw this.y(10, operation.target, operation);
      }
      throw new $cmc(
        localize(12568, null, this.A(operation.target), error.message),
        13
        /* ConfigurationEditingErrorCode.ERROR_INTERNAL */
      );
    }
  }
  q(edit3, model) {
    const startPosition = model.getPositionAt(edit3.offset);
    const endPosition = model.getPositionAt(edit3.offset + edit3.length);
    const range = new $9C(startPosition.lineNumber, startPosition.column, endPosition.lineNumber, endPosition.column);
    const currentText = model.getValueInRange(range);
    if (edit3.content !== currentText) {
      const editOperation = currentText ? $bD.replace(range, edit3.content) : $bD.insert(startPosition, edit3.content);
      model.pushEditOperations([new $_D(startPosition.lineNumber, startPosition.column, startPosition.lineNumber, startPosition.column)], [editOperation], () => []);
      return true;
    }
    return false;
  }
  r({ value, jsonPath }, modelContent, formattingOptions) {
    if (jsonPath.length) {
      return $Xw(modelContent, jsonPath, value, formattingOptions);
    }
    const content = JSON.stringify(value, null, formattingOptions.insertSpaces && formattingOptions.tabSize ? " ".repeat(formattingOptions.tabSize) : "	");
    return [{
      content,
      length: modelContent.length,
      offset: 0
    }];
  }
  s(model) {
    const { insertSpaces, tabSize } = model.getOptions();
    const eol = model.getEOL();
    return { insertSpaces, tabSize, eol };
  }
  async t(error, operation, scopes) {
    switch (error.code) {
      case 11:
        this.u(error, operation);
        break;
      case 9:
        this.v(error, operation, scopes);
        break;
      case 10:
        return this.n(operation, { scopes, handleDirtyFile: "revert" });
      default:
        this.j.error(error.message);
    }
  }
  u(error, operation) {
    const openStandAloneConfigurationActionLabel = operation.workspaceStandAloneConfigurationKey === $AK ? localize(12569, null) : operation.workspaceStandAloneConfigurationKey === $BK ? localize(12570, null) : null;
    if (openStandAloneConfigurationActionLabel) {
      this.j.prompt(Severity2.Error, error.message, [{
        label: openStandAloneConfigurationActionLabel,
        run: () => this.x(operation.resource)
      }]);
    } else {
      this.j.prompt(Severity2.Error, error.message, [{
        label: localize(12571, null),
        run: () => this.w(operation)
      }]);
    }
  }
  v(error, operation, scopes) {
    const openStandAloneConfigurationActionLabel = operation.workspaceStandAloneConfigurationKey === $AK ? localize(12572, null) : operation.workspaceStandAloneConfigurationKey === $BK ? localize(12573, null) : null;
    if (openStandAloneConfigurationActionLabel) {
      this.j.prompt(Severity2.Error, error.message, [
        {
          label: localize(12574, null),
          run: () => {
            const key2 = operation.key ? `${operation.workspaceStandAloneConfigurationKey}.${operation.key}` : operation.workspaceStandAloneConfigurationKey;
            this.writeConfiguration(operation.target, { key: key2, value: operation.value }, { handleDirtyFile: "save", scopes });
          }
        },
        {
          label: openStandAloneConfigurationActionLabel,
          run: () => this.x(operation.resource)
        }
      ]);
    } else {
      this.j.prompt(Severity2.Error, error.message, [
        {
          label: localize(12575, null),
          run: () => this.writeConfiguration(operation.target, { key: operation.key, value: operation.value }, { handleDirtyFile: "save", scopes })
        },
        {
          label: localize(12576, null),
          run: () => this.w(operation)
        }
      ]);
    }
  }
  w(operation) {
    const options3 = { jsonEditor: true };
    switch (operation.target) {
      case 1:
        this.k.openUserSettings(options3);
        break;
      case 2:
        this.k.openRemoteSettings(options3);
        break;
      case 3:
        this.k.openWorkspaceSettings(options3);
        break;
      case 4:
        if (operation.resource) {
          const workspaceFolder = this.d.getWorkspaceFolder(operation.resource);
          if (workspaceFolder) {
            this.k.openFolderSettings({ folderUri: workspaceFolder.uri, jsonEditor: true });
          }
        }
        break;
    }
  }
  x(resource) {
    this.l.openEditor({ resource, options: { pinned: true } });
  }
  y(code, target, operation) {
    const message = this.z(code, target, operation);
    return new $cmc(message, code);
  }
  z(error, target, operation) {
    switch (error) {
      case 12:
        return localize(12577, null, operation.key);
      case 0:
        return localize(12578, null, this.A(target), operation.key);
      case 1:
        return localize(12579, null, operation.key);
      case 2:
        return localize(12580, null, operation.key);
      case 3:
        return localize(12581, null, operation.key);
      case 4:
        return localize(12582, null, operation.key);
      case 5:
        return localize(12583, null, operation.key);
      case 6:
        return localize(12584, null);
      case 7:
        return localize(12585, null, operation.key);
      case 8:
        return localize(12586, null, this.A(target));
      case 11: {
        if (operation.workspaceStandAloneConfigurationKey === $AK) {
          return localize(12587, null);
        }
        if (operation.workspaceStandAloneConfigurationKey === $BK) {
          return localize(12588, null);
        }
        switch (target) {
          case 1:
            return localize(12589, null);
          case 2:
            return localize(12590, null);
          case 3:
            return localize(12591, null);
          case 4: {
            let workspaceFolderName = "<<unknown>>";
            if (operation.resource) {
              const folder = this.d.getWorkspaceFolder(operation.resource);
              if (folder) {
                workspaceFolderName = folder.name;
              }
            }
            return localize(12592, null, workspaceFolderName);
          }
          default:
            return "";
        }
      }
      case 9: {
        if (operation.workspaceStandAloneConfigurationKey === $AK) {
          return localize(12593, null);
        }
        if (operation.workspaceStandAloneConfigurationKey === $BK) {
          return localize(12594, null);
        }
        switch (target) {
          case 1:
            return localize(12595, null);
          case 2:
            return localize(12596, null);
          case 3:
            return localize(12597, null);
          case 4: {
            let workspaceFolderName = "<<unknown>>";
            if (operation.resource) {
              const folder = this.d.getWorkspaceFolder(operation.resource);
              if (folder) {
                workspaceFolderName = folder.name;
              }
            }
            return localize(12598, null, workspaceFolderName);
          }
          default:
            return "";
        }
      }
      case 10:
        if (operation.workspaceStandAloneConfigurationKey === $AK) {
          return localize(12599, null);
        }
        if (operation.workspaceStandAloneConfigurationKey === $BK) {
          return localize(12600, null);
        }
        switch (target) {
          case 1:
            return localize(12601, null);
          case 2:
            return localize(12602, null);
          case 3:
            return localize(12603, null);
          case 4:
            return localize(12604, null);
        }
      case 13:
        return localize(12605, null, this.A(target));
    }
  }
  A(target) {
    switch (target) {
      case 1:
        return localize(12606, null);
      case 2:
        return localize(12607, null);
      case 3:
        return localize(12608, null);
      case 4:
        return localize(12609, null);
      default:
        return "";
    }
  }
  B(resource) {
    const basename = this.m.extUri.basename(resource);
    const configurationValue = basename.substr(0, basename.length - this.m.extUri.extname(resource).length);
    switch (configurationValue) {
      case $AK:
        return $FK;
      default:
        return "{}";
    }
  }
  async C(resource) {
    const exists = await this.g.exists(resource);
    if (!exists) {
      await this.i.write(resource, this.B(resource), { encoding: "utf8" });
    }
    return this.h.createModelReference(resource);
  }
  D(content, operation) {
    if (operation.workspaceStandAloneConfigurationKey && !operation.key) {
      return false;
    }
    const parseErrors = [];
    $yw(content, parseErrors, { allowTrailingComma: true, allowEmptyContent: true });
    return parseErrors.length > 0;
  }
  async E(target, operation, checkDirty, overrides) {
    if (this.c.inspect(operation.key).policyValue !== void 0) {
      throw this.y(12, target, operation);
    }
    const configurationProperties = $Wn.as($Ht.Configuration).getConfigurationProperties();
    const configurationScope = configurationProperties[operation.key]?.scope;
    if (!operation.workspaceStandAloneConfigurationKey) {
      const validKeys = this.c.keys().default;
      if (validKeys.indexOf(operation.key) < 0 && !$Rt.test(operation.key) && operation.value !== void 0) {
        throw this.y(0, target, operation);
      }
    }
    if (operation.workspaceStandAloneConfigurationKey) {
      if (operation.workspaceStandAloneConfigurationKey !== $AK && (target === 1 || target === 2)) {
        throw this.y(4, target, operation);
      }
    }
    if ((target === 3 || target === 4) && this.d.getWorkbenchState() === 1) {
      throw this.y(8, target, operation);
    }
    if (target === 3) {
      if (!operation.workspaceStandAloneConfigurationKey && !$Rt.test(operation.key)) {
        if (configurationScope === 1) {
          throw this.y(1, target, operation);
        }
        if (configurationScope === 2) {
          throw this.y(2, target, operation);
        }
      }
    }
    if (target === 4) {
      if (!operation.resource) {
        throw this.y(6, target, operation);
      }
      if (!operation.workspaceStandAloneConfigurationKey && !$Rt.test(operation.key)) {
        if (configurationScope !== void 0 && !$zK.includes(configurationScope)) {
          throw this.y(3, target, operation);
        }
      }
    }
    if (overrides.overrideIdentifiers?.length) {
      if (configurationScope !== 5) {
        throw this.y(7, target, operation);
      }
    }
    if (!operation.resource) {
      throw this.y(6, target, operation);
    }
    if (checkDirty && this.i.isDirty(operation.resource)) {
      throw this.y(9, target, operation);
    }
  }
  F(target, config, overrides) {
    if (config.key) {
      const standaloneConfigurationMap = target === 1 ? $DK : $CK;
      const standaloneConfigurationKeys = Object.keys(standaloneConfigurationMap);
      for (const key3 of standaloneConfigurationKeys) {
        const resource2 = this.H(target, key3, standaloneConfigurationMap[key3], overrides.resource, void 0);
        if (config.key === key3) {
          const jsonPath2 = this.G(resource2) ? [key3] : [];
          return { key: jsonPath2[jsonPath2.length - 1], jsonPath: jsonPath2, value: config.value, resource: resource2 ?? void 0, workspaceStandAloneConfigurationKey: key3, target };
        }
        const keyPrefix = `${key3}.`;
        if (config.key.indexOf(keyPrefix) === 0) {
          const jsonPath2 = this.G(resource2) ? [key3, config.key.substr(keyPrefix.length)] : [config.key.substr(keyPrefix.length)];
          return { key: jsonPath2[jsonPath2.length - 1], jsonPath: jsonPath2, value: config.value, resource: resource2 ?? void 0, workspaceStandAloneConfigurationKey: key3, target };
        }
      }
    }
    const key2 = config.key;
    const configurationProperties = $Wn.as($Ht.Configuration).getConfigurationProperties();
    const configurationScope = configurationProperties[key2]?.scope;
    let jsonPath = overrides.overrideIdentifiers?.length ? [$Tt(overrides.overrideIdentifiers), key2] : [key2];
    if (target === 1 || target === 2) {
      return { key: key2, jsonPath, value: config.value, resource: this.H(target, key2, "", null, configurationScope) ?? void 0, target };
    }
    const resource = this.H(target, key2, $kK, overrides.resource, configurationScope);
    if (this.G(resource)) {
      jsonPath = ["settings", ...jsonPath];
    }
    return { key: key2, jsonPath, value: config.value, resource: resource ?? void 0, target };
  }
  G(resource) {
    const workspace2 = this.d.getWorkspace();
    return !!(workspace2.configuration && resource && workspace2.configuration.fsPath === resource.fsPath);
  }
  H(target, key2, relativePath, resource, scope) {
    if (target === 1) {
      if (key2 === $AK) {
        return this.e.currentProfile.tasksResource;
      } else {
        if (!this.e.currentProfile.isDefault && this.c.isSettingAppliedForAllProfiles(key2)) {
          return this.f.defaultProfile.settingsResource;
        }
        return this.e.currentProfile.settingsResource;
      }
    }
    if (target === 2) {
      return this.b;
    }
    const workbenchState = this.d.getWorkbenchState();
    if (workbenchState !== 1) {
      const workspace2 = this.d.getWorkspace();
      if (target === 3) {
        if (workbenchState === 3) {
          return workspace2.configuration ?? null;
        }
        if (workbenchState === 2) {
          return workspace2.folders[0].toResource(relativePath);
        }
      }
      if (target === 4) {
        if (resource) {
          const folder = this.d.getWorkspaceFolder(resource);
          if (folder) {
            return folder.toResource(relativePath);
          }
        }
      }
    }
    return null;
  }
};
$dmc = __decorate([
  __param(1, $EK),
  __param(2, $Zk),
  __param(3, $gT),
  __param(4, $rs),
  __param(5, $km),
  __param(6, $oG),
  __param(7, $cK),
  __param(8, $PJ),
  __param(9, $TK),
  __param(10, $mJ),
  __param(11, $vl)
], $dmc);

// out-build/vs/workbench/services/configuration/browser/configuration.js
var $emc = class _$emc extends $YB {
  static {
    this.DEFAULT_OVERRIDES_CACHE_EXISTS_KEY = "DefaultOverridesCacheExists";
  }
  constructor(t, environmentService, logService) {
    super(logService);
    this.t = t;
    this.m = $Wn.as($Ht.Configuration);
    this.n = {};
    this.r = { type: "defaults", key: "configurationDefaultsOverrides" };
    this.s = false;
    if (environmentService.options?.configurationDefaults) {
      this.m.registerDefaultConfigurations([{ overrides: environmentService.options.configurationDefaults }]);
    }
  }
  g() {
    return this.n;
  }
  async initialize() {
    await this.y();
    return super.initialize();
  }
  reload() {
    this.s = true;
    this.n = {};
    this.C();
    return super.reload();
  }
  hasCachedConfigurationDefaultsOverrides() {
    return !$Mg(this.n);
  }
  y() {
    if (!this.w) {
      this.w = (async () => {
        try {
          if (localStorage.getItem(_$emc.DEFAULT_OVERRIDES_CACHE_EXISTS_KEY)) {
            const content = await this.t.read(this.r);
            if (content) {
              this.n = JSON.parse(content);
            }
          }
        } catch (error) {
        }
        this.n = $Bg(this.n) ? this.n : {};
      })();
    }
    return this.w;
  }
  f(properties, defaultsOverrides) {
    super.f(properties, defaultsOverrides);
    if (defaultsOverrides) {
      this.C();
    }
  }
  async C() {
    if (!this.s) {
      return;
    }
    const cachedConfigurationDefaultsOverrides = {};
    const configurationDefaultsOverrides = this.m.getConfigurationDefaultsOverrides();
    for (const [key2, value] of configurationDefaultsOverrides) {
      if (!$Rt.test(key2) && value.value !== void 0) {
        cachedConfigurationDefaultsOverrides[key2] = value.value;
      }
    }
    try {
      if (Object.keys(cachedConfigurationDefaultsOverrides).length) {
        localStorage.setItem(_$emc.DEFAULT_OVERRIDES_CACHE_EXISTS_KEY, "yes");
        await this.t.write(this.r, JSON.stringify(cachedConfigurationDefaultsOverrides));
      } else {
        localStorage.removeItem(_$emc.DEFAULT_OVERRIDES_CACHE_EXISTS_KEY);
        await this.t.remove(this.r);
      }
    } catch (error) {
    }
  }
};
var $fmc = class extends $UB {
  constructor(userDataProfilesService, fileService, uriIdentityService, logService) {
    super(userDataProfilesService.defaultProfile.settingsResource, { scopes: [
      1
      /* ConfigurationScope.APPLICATION */
    ], skipUnregistered: true }, uriIdentityService.extUri, fileService, logService);
    this.j = this.B(new $ze());
    this.onDidChangeConfiguration = this.j.event;
    this.B(this.onDidChange(() => this.m.schedule()));
    this.m = this.B(new $8h(() => this.loadConfiguration().then((configurationModel) => this.j.fire(configurationModel)), 50));
  }
  async initialize() {
    return this.loadConfiguration();
  }
  async loadConfiguration() {
    const model = await super.loadConfiguration();
    const value = model.getValue($GK);
    const allProfilesSettings = Array.isArray(value) ? value : [];
    return this.f.include || allProfilesSettings.length ? this.reparse({ ...this.f, include: allProfilesSettings }) : model;
  }
};
var $gmc = class extends $3c {
  get hasTasksLoaded() {
    return this.b.value instanceof FileServiceBasedConfiguration;
  }
  constructor(g, h3, j, m, n, r2) {
    super();
    this.g = g;
    this.h = h3;
    this.j = j;
    this.m = m;
    this.n = n;
    this.r = r2;
    this.a = this.B(new $ze());
    this.onDidChangeConfiguration = this.a.event;
    this.b = this.B(new $4c());
    this.c = this.B(new $4c());
    this.b.value = new $UB(g, this.j, n.extUri, this.m, r2);
    this.c.value = this.b.value.onDidChange(() => this.f.schedule());
    this.f = this.B(new $8h(() => this.b.value.loadConfiguration().then((configurationModel) => this.a.fire(configurationModel)), 50));
  }
  async reset(settingsResource, tasksResource, configurationParseOptions) {
    this.g = settingsResource;
    this.h = tasksResource;
    this.j = configurationParseOptions;
    return this.s();
  }
  async s(settingsConfiguration) {
    const folder = this.n.extUri.dirname(this.g);
    const standAloneConfigurationResources = this.h ? [[$AK, this.h]] : [];
    const fileServiceBasedConfiguration = new FileServiceBasedConfiguration(folder.toString(), this.g, standAloneConfigurationResources, this.j, this.m, this.n, this.r);
    const configurationModel = await fileServiceBasedConfiguration.loadConfiguration(settingsConfiguration);
    this.b.value = fileServiceBasedConfiguration;
    if (this.c.value) {
      this.c.value = this.b.value.onDidChange(() => this.f.schedule());
    }
    return configurationModel;
  }
  async initialize() {
    return this.b.value.loadConfiguration();
  }
  async reload(settingsConfiguration) {
    if (this.hasTasksLoaded) {
      return this.b.value.loadConfiguration();
    }
    return this.s(settingsConfiguration);
  }
  reparse(parseOptions) {
    this.j = { ...this.j, ...parseOptions };
    return this.b.value.reparse(this.j);
  }
  getRestrictedSettings() {
    return this.b.value.getRestrictedSettings();
  }
};
var FileServiceBasedConfiguration = class extends $3c {
  constructor(name, j, m, configurationParseOptions, n, r2, s) {
    super();
    this.j = j;
    this.m = m;
    this.n = n;
    this.r = r2;
    this.s = s;
    this.h = this.B(new $ze());
    this.onDidChange = this.h.event;
    this.a = [this.j, ...this.m.map(([, resource]) => resource)];
    this.B($Zc(...this.a.map((resource) => $Zc(
      this.n.watch(r2.extUri.dirname(resource)),
      // Also listen to the resource incase the resource is a symlink - https://github.com/microsoft/vscode/issues/118134
      this.n.watch(resource)
    ))));
    this.b = new $TB(name, s);
    this.c = configurationParseOptions;
    this.f = [];
    this.g = $SB.createEmptyModel(this.s);
    this.B(Event2.debounce(Event2.any(Event2.filter(this.n.onDidFilesChange, (e) => this.u(e)), Event2.filter(this.n.onDidRunOperation, (e) => this.w(e))), () => void 0, 100)(() => this.h.fire()));
  }
  async resolveContents(donotResolveSettings) {
    const resolveContents = async (resources) => {
      return Promise.all(resources.map(async (resource) => {
        try {
          const content = await this.n.readFile(resource, { atomic: true });
          return content.value.toString();
        } catch (error) {
          this.s.trace(`Error while resolving configuration file '${resource.toString()}': ${$qb(error)}`);
          if (error.fileOperationResult !== 1 && error.fileOperationResult !== 9) {
            this.s.error(error);
          }
        }
        return "{}";
      }));
    };
    const [[settingsContent], standAloneConfigurationContents] = await Promise.all([
      donotResolveSettings ? Promise.resolve([void 0]) : resolveContents([this.j]),
      resolveContents(this.m.map(([, resource]) => resource))
    ]);
    return [settingsContent, standAloneConfigurationContents.map((content, index) => [this.m[index][0], content])];
  }
  async loadConfiguration(settingsConfiguration) {
    const [settingsContent, standAloneConfigurationContents] = await this.resolveContents(!!settingsConfiguration);
    this.f = [];
    this.b.parse("", this.c);
    if (settingsContent !== void 0) {
      this.b.parse(settingsContent, this.c);
    }
    for (let index = 0; index < standAloneConfigurationContents.length; index++) {
      const contents = standAloneConfigurationContents[index][1];
      if (contents !== void 0) {
        const standAloneConfigurationModelParser = new $amc(this.m[index][1].toString(), this.m[index][0], this.s);
        standAloneConfigurationModelParser.parse(contents);
        this.f.push(standAloneConfigurationModelParser.configurationModel);
      }
    }
    this.t(settingsConfiguration);
    return this.g;
  }
  getRestrictedSettings() {
    return this.b.restrictedConfigurations;
  }
  reparse(configurationParseOptions) {
    const oldContents = this.b.configurationModel.contents;
    this.c = configurationParseOptions;
    this.b.reparse(this.c);
    if (!$Pv(oldContents, this.b.configurationModel.contents)) {
      this.t();
    }
    return this.g;
  }
  t(settingsConfiguration) {
    this.g = (settingsConfiguration ?? this.b.configurationModel).merge(...this.f);
  }
  u(event) {
    if (this.a.some((resource) => event.contains(resource))) {
      return true;
    }
    if (this.a.some((resource) => event.contains(
      this.r.extUri.dirname(resource),
      2
      /* FileChangeType.DELETED */
    ))) {
      return true;
    }
    return false;
  }
  w(event) {
    if ((event.isOperation(
      0
      /* FileOperation.CREATE */
    ) || event.isOperation(
      3
      /* FileOperation.COPY */
    ) || event.isOperation(
      1
      /* FileOperation.DELETE */
    ) || event.isOperation(
      4
      /* FileOperation.WRITE */
    )) && this.a.some((resource) => this.r.extUri.isEqual(event.resource, resource))) {
      return true;
    }
    if (event.isOperation(
      1
      /* FileOperation.DELETE */
    ) && this.a.some((resource) => this.r.extUri.isEqual(event.resource, this.r.extUri.dirname(resource)))) {
      return true;
    }
    return false;
  }
};
var $hmc = class extends $3c {
  constructor(remoteAuthority, configurationCache, fileService, uriIdentityService, remoteAgentService, logService) {
    super();
    this.f = null;
    this.g = this.B(new $ze());
    this.onDidChangeConfiguration = this.g.event;
    this.h = this.B(new $ze());
    this.onDidInitialize = this.h.event;
    this.b = fileService;
    this.c = this.a = new CachedRemoteUserConfiguration(remoteAuthority, configurationCache, { scopes: $xK }, logService);
    remoteAgentService.getEnvironment().then(async (environment) => {
      if (environment) {
        const userConfiguration = this.B(new FileServiceBasedRemoteUserConfiguration(environment.settingsPath, { scopes: $xK }, this.b, uriIdentityService, logService));
        this.B(userConfiguration.onDidChangeConfiguration((configurationModel2) => this.j(configurationModel2)));
        this.f = userConfiguration.initialize();
        const configurationModel = await this.f;
        this.c.dispose();
        this.c = userConfiguration;
        this.j(configurationModel);
        this.h.fire(configurationModel);
      }
    });
  }
  async initialize() {
    if (this.c instanceof FileServiceBasedRemoteUserConfiguration) {
      return this.c.initialize();
    }
    let configurationModel = await this.c.initialize();
    if (this.f) {
      configurationModel = await this.f;
      this.f = null;
    }
    return configurationModel;
  }
  reload() {
    return this.c.reload();
  }
  reparse() {
    return this.c.reparse({ scopes: $xK });
  }
  getRestrictedSettings() {
    return this.c.getRestrictedSettings();
  }
  j(configurationModel) {
    this.m();
    this.g.fire(configurationModel);
  }
  async m() {
    if (this.c instanceof FileServiceBasedRemoteUserConfiguration) {
      let content;
      try {
        content = await this.c.resolveContent();
      } catch (error) {
        if (error.fileOperationResult !== 1) {
          return;
        }
      }
      await this.a.updateConfiguration(content);
    }
  }
};
var FileServiceBasedRemoteUserConfiguration = class extends $3c {
  constructor(j, configurationParseOptions, m, n, r2) {
    super();
    this.j = j;
    this.m = m;
    this.n = n;
    this.r = r2;
    this.f = this.B(new $ze());
    this.onDidChangeConfiguration = this.f.event;
    this.g = this.B(new $4c());
    this.h = this.B(new $4c());
    this.a = new $TB(this.j.toString(), r2);
    this.b = configurationParseOptions;
    this.B(m.onDidFilesChange((e) => this.y(e)));
    this.B(m.onDidRunOperation((e) => this.z(e)));
    this.c = this.B(new $8h(() => this.reload().then((configurationModel) => this.f.fire(configurationModel)), 50));
    this.B($1c(() => {
      this.t();
      this.w();
    }));
  }
  s() {
    this.g.value = this.m.watch(this.j);
  }
  t() {
    this.g.value = void 0;
  }
  u() {
    const directory = this.n.extUri.dirname(this.j);
    this.h.value = this.m.watch(directory);
  }
  w() {
    this.h.value = void 0;
  }
  async initialize() {
    const exists = await this.m.exists(this.j);
    this.C(exists);
    return this.reload();
  }
  async resolveContent() {
    const content = await this.m.readFile(this.j, { atomic: true });
    return content.value.toString();
  }
  async reload() {
    try {
      const content = await this.resolveContent();
      this.a.parse(content, this.b);
      return this.a.configurationModel;
    } catch (e) {
      return $SB.createEmptyModel(this.r);
    }
  }
  reparse(configurationParseOptions) {
    this.b = configurationParseOptions;
    this.a.reparse(this.b);
    return this.a.configurationModel;
  }
  getRestrictedSettings() {
    return this.a.restrictedConfigurations;
  }
  y(event) {
    let affectedByChanges = false;
    if (event.contains(
      this.j,
      1
      /* FileChangeType.ADDED */
    )) {
      affectedByChanges = true;
      this.C(true);
    } else if (event.contains(
      this.j,
      2
      /* FileChangeType.DELETED */
    )) {
      affectedByChanges = true;
      this.C(false);
    } else if (event.contains(
      this.j,
      0
      /* FileChangeType.UPDATED */
    )) {
      affectedByChanges = true;
    }
    if (affectedByChanges) {
      this.c.schedule();
    }
  }
  z(event) {
    if ((event.isOperation(
      0
      /* FileOperation.CREATE */
    ) || event.isOperation(
      3
      /* FileOperation.COPY */
    ) || event.isOperation(
      1
      /* FileOperation.DELETE */
    ) || event.isOperation(
      4
      /* FileOperation.WRITE */
    )) && this.n.extUri.isEqual(event.resource, this.j)) {
      this.c.schedule();
    }
  }
  C(exists) {
    if (exists) {
      this.w();
      this.s();
    } else {
      this.t();
      this.u();
    }
  }
};
var CachedRemoteUserConfiguration = class extends $3c {
  constructor(remoteAuthority, h3, configurationParseOptions, logService) {
    super();
    this.h = h3;
    this.a = this.B(new $ze());
    this.onDidChange = this.a.event;
    this.b = { type: "user", key: remoteAuthority };
    this.c = new $TB("CachedRemoteUserConfiguration", logService);
    this.f = configurationParseOptions;
    this.g = $SB.createEmptyModel(logService);
  }
  getConfigurationModel() {
    return this.g;
  }
  initialize() {
    return this.reload();
  }
  reparse(configurationParseOptions) {
    this.f = configurationParseOptions;
    this.c.reparse(this.f);
    this.g = this.c.configurationModel;
    return this.g;
  }
  getRestrictedSettings() {
    return this.c.restrictedConfigurations;
  }
  async reload() {
    try {
      const content = await this.h.read(this.b);
      const parsed = JSON.parse(content);
      if (parsed.content) {
        this.c.parse(parsed.content, this.f);
        this.g = this.c.configurationModel;
      }
    } catch (e) {
    }
    return this.g;
  }
  async updateConfiguration(content) {
    if (content) {
      return this.h.write(this.b, JSON.stringify({ content }));
    } else {
      return this.h.remove(this.b);
    }
  }
};
var $imc = class extends $3c {
  get initialized() {
    return this.j;
  }
  constructor(m, n, r2, s) {
    super();
    this.m = m;
    this.n = n;
    this.r = r2;
    this.s = s;
    this.c = this.B(new $2c());
    this.f = null;
    this.g = false;
    this.h = this.B(new $ze());
    this.onDidUpdateConfiguration = this.h.event;
    this.j = false;
    this.n = n;
    this.b = this.a = new CachedWorkspaceConfiguration(m, s);
  }
  async initialize(workspaceIdentifier, workspaceTrusted) {
    this.f = workspaceIdentifier;
    this.g = workspaceTrusted;
    if (!this.j) {
      if (this.m.needsCaching(this.f.configPath)) {
        this.b = this.a;
        this.t(this.f);
      } else {
        this.u(new FileServiceBasedWorkspaceConfiguration(this.n, this.r, this.s));
      }
    }
    await this.reload();
  }
  async reload() {
    if (this.f) {
      await this.b.load(this.f, { scopes: $yK, skipRestricted: this.w() });
    }
  }
  getFolders() {
    return this.b.getFolders();
  }
  setFolders(folders, jsonEditingService) {
    if (this.f) {
      return jsonEditingService.write(this.f.configPath, [{ path: ["folders"], value: folders }], true).then(() => this.reload());
    }
    return Promise.resolve();
  }
  isTransient() {
    return this.b.isTransient();
  }
  getConfiguration() {
    return this.b.getWorkspaceSettings();
  }
  updateWorkspaceTrust(trusted) {
    this.g = trusted;
    return this.reparseWorkspaceSettings();
  }
  reparseWorkspaceSettings() {
    this.b.reparseWorkspaceSettings({ scopes: $yK, skipRestricted: this.w() });
    return this.getConfiguration();
  }
  getRestrictedSettings() {
    return this.b.getRestrictedSettings();
  }
  async t(workspaceIdentifier) {
    await $Rm(workspaceIdentifier.configPath, this.n);
    if (!(this.b instanceof FileServiceBasedWorkspaceConfiguration)) {
      const fileServiceBasedWorkspaceConfiguration = this.B(new FileServiceBasedWorkspaceConfiguration(this.n, this.r, this.s));
      await fileServiceBasedWorkspaceConfiguration.load(workspaceIdentifier, { scopes: $yK, skipRestricted: this.w() });
      this.u(fileServiceBasedWorkspaceConfiguration);
      this.y(false, true);
    }
  }
  u(fileServiceBasedWorkspaceConfiguration) {
    this.c.clear();
    this.b = this.c.add(fileServiceBasedWorkspaceConfiguration);
    this.c.add(this.b.onDidChange((e) => this.y(true, false)));
    this.j = true;
  }
  w() {
    return !this.g;
  }
  async y(reload, fromCache) {
    if (reload) {
      await this.reload();
    }
    this.z();
    this.h.fire(fromCache);
  }
  async z() {
    if (this.f && this.m.needsCaching(this.f.configPath) && this.b instanceof FileServiceBasedWorkspaceConfiguration) {
      const content = await this.b.resolveContent(this.f);
      await this.a.updateWorkspace(this.f, content);
    }
  }
};
var FileServiceBasedWorkspaceConfiguration = class extends $3c {
  constructor(g, uriIdentityService, h3) {
    super();
    this.g = g;
    this.h = h3;
    this.a = null;
    this.f = this.B(new $ze());
    this.onDidChange = this.f.event;
    this.workspaceConfigurationModelParser = new $_lc("", h3);
    this.workspaceSettings = $SB.createEmptyModel(h3);
    this.B(Event2.any(Event2.filter(this.g.onDidFilesChange, (e) => !!this.a && e.contains(this.a.configPath)), Event2.filter(this.g.onDidRunOperation, (e) => !!this.a && (e.isOperation(
      0
      /* FileOperation.CREATE */
    ) || e.isOperation(
      3
      /* FileOperation.COPY */
    ) || e.isOperation(
      1
      /* FileOperation.DELETE */
    ) || e.isOperation(
      4
      /* FileOperation.WRITE */
    )) && uriIdentityService.extUri.isEqual(e.resource, this.a.configPath)))(() => this.c.schedule()));
    this.c = this.B(new $8h(() => this.f.fire(), 50));
    this.b = this.B(this.m());
  }
  get workspaceIdentifier() {
    return this.a;
  }
  async resolveContent(workspaceIdentifier) {
    const content = await this.g.readFile(workspaceIdentifier.configPath, { atomic: true });
    return content.value.toString();
  }
  async load(workspaceIdentifier, configurationParseOptions) {
    if (!this.a || this.a.id !== workspaceIdentifier.id) {
      this.a = workspaceIdentifier;
      this.workspaceConfigurationModelParser = new $_lc(this.a.id, this.h);
      $Xc(this.b);
      this.b = this.B(this.m());
    }
    let contents = "";
    try {
      contents = await this.resolveContent(this.a);
    } catch (error) {
      const exists = await this.g.exists(this.a.configPath);
      if (exists) {
        this.h.error(error);
      }
    }
    this.workspaceConfigurationModelParser.parse(contents, configurationParseOptions);
    this.j();
  }
  getConfigurationModel() {
    return this.workspaceConfigurationModelParser.configurationModel;
  }
  getFolders() {
    return this.workspaceConfigurationModelParser.folders;
  }
  isTransient() {
    return this.workspaceConfigurationModelParser.transient;
  }
  getWorkspaceSettings() {
    return this.workspaceSettings;
  }
  reparseWorkspaceSettings(configurationParseOptions) {
    this.workspaceConfigurationModelParser.reparseWorkspaceSettings(configurationParseOptions);
    this.j();
    return this.getWorkspaceSettings();
  }
  getRestrictedSettings() {
    return this.workspaceConfigurationModelParser.getRestrictedWorkspaceSettings();
  }
  j() {
    this.workspaceSettings = this.workspaceConfigurationModelParser.settingsModel.merge(this.workspaceConfigurationModelParser.launchModel, this.workspaceConfigurationModelParser.tasksModel);
  }
  m() {
    return this.a ? this.g.watch(this.a.configPath) : $3c.None;
  }
};
var CachedWorkspaceConfiguration = class {
  constructor(a, b) {
    this.a = a;
    this.b = b;
    this.onDidChange = Event2.None;
    this.workspaceConfigurationModelParser = new $_lc("", b);
    this.workspaceSettings = $SB.createEmptyModel(b);
  }
  async load(workspaceIdentifier, configurationParseOptions) {
    try {
      const key2 = this.d(workspaceIdentifier);
      const contents = await this.a.read(key2);
      const parsed = JSON.parse(contents);
      if (parsed.content) {
        this.workspaceConfigurationModelParser = new $_lc(key2.key, this.b);
        this.workspaceConfigurationModelParser.parse(parsed.content, configurationParseOptions);
        this.c();
      }
    } catch (e) {
    }
  }
  get workspaceIdentifier() {
    return null;
  }
  getConfigurationModel() {
    return this.workspaceConfigurationModelParser.configurationModel;
  }
  getFolders() {
    return this.workspaceConfigurationModelParser.folders;
  }
  isTransient() {
    return this.workspaceConfigurationModelParser.transient;
  }
  getWorkspaceSettings() {
    return this.workspaceSettings;
  }
  reparseWorkspaceSettings(configurationParseOptions) {
    this.workspaceConfigurationModelParser.reparseWorkspaceSettings(configurationParseOptions);
    this.c();
    return this.getWorkspaceSettings();
  }
  getRestrictedSettings() {
    return this.workspaceConfigurationModelParser.getRestrictedWorkspaceSettings();
  }
  c() {
    this.workspaceSettings = this.workspaceConfigurationModelParser.settingsModel.merge(this.workspaceConfigurationModelParser.launchModel, this.workspaceConfigurationModelParser.tasksModel);
  }
  async updateWorkspace(workspaceIdentifier, content) {
    try {
      const key2 = this.d(workspaceIdentifier);
      if (content) {
        await this.a.write(key2, JSON.stringify({ content }));
      } else {
        await this.a.remove(key2);
      }
    } catch (error) {
    }
  }
  d(workspaceIdentifier) {
    return {
      type: "workspaces",
      key: workspaceIdentifier.id
    };
  }
};
var CachedFolderConfiguration = class {
  constructor(folder, configFolderRelativePath, configurationParseOptions, g, h3) {
    this.g = g;
    this.h = h3;
    this.onDidChange = Event2.None;
    this.f = { type: "folder", key: $Xi($vh(folder, configFolderRelativePath).toString()).toString(16) };
    this.a = new $TB("CachedFolderConfiguration", h3);
    this.b = configurationParseOptions;
    this.c = [];
    this.d = $SB.createEmptyModel(h3);
  }
  async loadConfiguration() {
    try {
      const contents = await this.g.read(this.f);
      const { content: configurationContents } = JSON.parse(contents.toString());
      if (configurationContents) {
        for (const key2 of Object.keys(configurationContents)) {
          if (key2 === $jK) {
            this.a.parse(configurationContents[key2], this.b);
          } else {
            const standAloneConfigurationModelParser = new $amc(key2, key2, this.h);
            standAloneConfigurationModelParser.parse(configurationContents[key2]);
            this.c.push(standAloneConfigurationModelParser.configurationModel);
          }
        }
      }
      this.i();
    } catch (e) {
    }
    return this.d;
  }
  async updateConfiguration(settingsContent, standAloneConfigurationContents) {
    const content = {};
    if (settingsContent) {
      content[$jK] = settingsContent;
    }
    standAloneConfigurationContents.forEach(([key2, contents]) => {
      if (contents) {
        content[key2] = contents;
      }
    });
    if (Object.keys(content).length) {
      await this.g.write(this.f, JSON.stringify({ content }));
    } else {
      await this.g.remove(this.f);
    }
  }
  getRestrictedSettings() {
    return this.a.restrictedConfigurations;
  }
  reparse(configurationParseOptions) {
    this.b = configurationParseOptions;
    this.a.reparse(this.b);
    this.i();
    return this.d;
  }
  i() {
    this.d = this.a.configurationModel.merge(...this.c);
  }
  getUnsupportedKeys() {
    return [];
  }
};
var $jmc = class extends $3c {
  constructor(useCache, workspaceFolder, configFolderRelativePath, h3, j, fileService, uriIdentityService, logService, m) {
    super();
    this.workspaceFolder = workspaceFolder;
    this.h = h3;
    this.j = j;
    this.m = m;
    this.a = this.B(new $ze());
    this.onDidChange = this.a.event;
    this.c = 3 === this.h ? $zK : $yK;
    this.f = uriIdentityService.extUri.joinPath(workspaceFolder.uri, configFolderRelativePath);
    this.g = new CachedFolderConfiguration(workspaceFolder.uri, configFolderRelativePath, { scopes: this.c, skipRestricted: this.n() }, m, logService);
    if (useCache && this.m.needsCaching(workspaceFolder.uri)) {
      this.b = this.g;
      $Rm(workspaceFolder.uri, fileService).then(() => {
        this.b = this.B(this.s(fileService, uriIdentityService, logService));
        this.B(this.b.onDidChange((e) => this.r()));
        this.r();
      });
    } else {
      this.b = this.B(this.s(fileService, uriIdentityService, logService));
      this.B(this.b.onDidChange((e) => this.r()));
    }
  }
  loadConfiguration() {
    return this.b.loadConfiguration();
  }
  updateWorkspaceTrust(trusted) {
    this.j = trusted;
    return this.reparse();
  }
  reparse() {
    const configurationModel = this.b.reparse({ scopes: this.c, skipRestricted: this.n() });
    this.t();
    return configurationModel;
  }
  getRestrictedSettings() {
    return this.b.getRestrictedSettings();
  }
  n() {
    return !this.j;
  }
  r() {
    this.t();
    this.a.fire();
  }
  s(fileService, uriIdentityService, logService) {
    const settingsResource = uriIdentityService.extUri.joinPath(this.f, `${$jK}.json`);
    const standAloneConfigurationResources = [$AK, $BK].map((name) => [name, uriIdentityService.extUri.joinPath(this.f, `${name}.json`)]);
    return new FileServiceBasedConfiguration(this.f.toString(), settingsResource, standAloneConfigurationResources, { scopes: this.c, skipRestricted: this.n() }, fileService, uriIdentityService, logService);
  }
  async t() {
    if (this.m.needsCaching(this.f) && this.b instanceof FileServiceBasedConfiguration) {
      const [settingsContent, standAloneConfigurationContents] = await this.b.resolveContents();
      this.g.updateConfiguration(settingsContent, standAloneConfigurationContents);
    }
  }
};

// out-build/vs/workbench/services/configuration/browser/configurationService.js
function getLocalUserConfigurationScopes(userDataProfile, hasRemote) {
  return userDataProfile.isDefault || userDataProfile.useDefaultFlags?.settings ? hasRemote ? $wK : void 0 : hasRemote ? $vK : $uK;
}
var Workspace = class extends $0k {
  constructor() {
    super(...arguments);
    this.initialized = false;
  }
};
var $kmc = class extends $3c {
  get restrictedSettings() {
    return this.M;
  }
  constructor({ remoteAuthority, configurationCache }, environmentService, R, S, U, W, X, Y, policyService) {
    super();
    this.R = R;
    this.S = S;
    this.U = U;
    this.W = W;
    this.X = X;
    this.Y = Y;
    this.n = false;
    this.t = null;
    this.y = null;
    this.F = this.B(new $ze());
    this.onDidChangeConfiguration = this.F.event;
    this.G = this.B(new $ze());
    this.onWillChangeWorkspaceFolders = this.G.event;
    this.H = this.B(new $ze());
    this.onDidChangeWorkspaceFolders = this.H.event;
    this.I = this.B(new $ze());
    this.onDidChangeWorkspaceName = this.I.event;
    this.J = this.B(new $ze());
    this.onDidChangeWorkbenchState = this.J.event;
    this.L = true;
    this.M = { default: [] };
    this.N = this.B(new $ze());
    this.onDidChangeRestrictedSettings = this.N.event;
    this.O = $Wn.as($Ht.Configuration);
    this.g = new $Uh();
    this.h = new $Uh();
    this.r = this.B(new $emc(configurationCache, environmentService, Y));
    this.s = policyService instanceof $Rn ? new $ZB() : this.B(new $1B(this.r, policyService, Y));
    this.j = configurationCache;
    this.m = new $bmc(this.r.configurationModel, this.s.configurationModel, $SB.createEmptyModel(Y), $SB.createEmptyModel(Y), $SB.createEmptyModel(Y), $SB.createEmptyModel(Y), new $Ec(), $SB.createEmptyModel(Y), new $Ec(), this.c, Y);
    this.u = this.B(new $2c());
    this.Z();
    this.w = this.B(new $gmc(R.currentProfile.settingsResource, R.currentProfile.tasksResource, { scopes: getLocalUserConfigurationScopes(R.currentProfile, !!remoteAuthority) }, U, X, Y));
    this.C = new $Ec();
    this.B(this.w.onDidChangeConfiguration((userConfiguration) => this.wb(userConfiguration)));
    if (remoteAuthority) {
      const remoteUserConfiguration = this.y = this.B(new $hmc(remoteAuthority, configurationCache, U, X, W, Y));
      this.B(remoteUserConfiguration.onDidInitialize((remoteUserConfigurationModel) => {
        this.B(remoteUserConfiguration.onDidChangeConfiguration((remoteUserConfigurationModel2) => this.xb(remoteUserConfigurationModel2)));
        this.xb(remoteUserConfigurationModel);
        this.g.open();
      }));
    } else {
      this.g.open();
    }
    this.z = this.B(new $imc(configurationCache, U, X, Y));
    this.B(this.z.onDidUpdateConfiguration((fromCache) => {
      this.yb(fromCache).then(() => {
        if (this.c) {
          this.c.initialized = this.z.initialized;
          this.gb(fromCache);
        }
      });
    }));
    this.B(this.r.onDidChangeConfiguration(({ properties, defaults }) => this.tb(defaults, properties)));
    this.B(this.s.onDidChangeConfiguration((configurationModel) => this.ub(configurationModel)));
    this.B(R.onDidChangeCurrentProfile((e) => this.sb(e)));
    this.D = new $3h();
  }
  Z() {
    this.u.clear();
    if (this.R.currentProfile.isDefault || this.R.currentProfile.useDefaultFlags?.settings) {
      this.t = null;
    } else {
      this.t = this.u.add(this.B(new $fmc(this.S, this.U, this.X, this.Y)));
      this.u.add(this.t.onDidChangeConfiguration((configurationModel) => this.vb(configurationModel)));
    }
  }
  // Workspace Context Service Impl
  async getCompleteWorkspace() {
    await this.h.wait();
    return this.getWorkspace();
  }
  getWorkspace() {
    return this.c;
  }
  getWorkbenchState() {
    if (this.c.configuration) {
      return 3;
    }
    if (this.c.folders.length === 1) {
      return 2;
    }
    return 1;
  }
  getWorkspaceFolder(resource) {
    return this.c.getFolder(resource);
  }
  addFolders(foldersToAdd, index) {
    return this.updateFolders(foldersToAdd, [], index);
  }
  removeFolders(foldersToRemove) {
    return this.updateFolders([], foldersToRemove);
  }
  async updateFolders(foldersToAdd, foldersToRemove, index) {
    return this.D.queue(() => this.$(foldersToAdd, foldersToRemove, index));
  }
  isInsideWorkspace(resource) {
    return !!this.getWorkspaceFolder(resource);
  }
  isCurrentWorkspace(workspaceIdOrFolder) {
    switch (this.getWorkbenchState()) {
      case 2: {
        let folderUri = void 0;
        if (URI.isUri(workspaceIdOrFolder)) {
          folderUri = workspaceIdOrFolder;
        } else if ($1k(workspaceIdOrFolder)) {
          folderUri = workspaceIdOrFolder.uri;
        }
        return URI.isUri(folderUri) && this.X.extUri.isEqual(folderUri, this.c.folders[0].uri);
      }
      case 3:
        return $6k(workspaceIdOrFolder) && this.c.id === workspaceIdOrFolder.id;
    }
    return false;
  }
  async $(foldersToAdd, foldersToRemove, index) {
    if (this.getWorkbenchState() !== 3) {
      return Promise.resolve(void 0);
    }
    if (foldersToAdd.length + foldersToRemove.length === 0) {
      return Promise.resolve(void 0);
    }
    let foldersHaveChanged = false;
    let currentWorkspaceFolders = this.getWorkspace().folders;
    let newStoredFolders = currentWorkspaceFolders.map((f) => f.raw).filter((folder, index2) => {
      if (!$6w(folder)) {
        return true;
      }
      return !this.bb(foldersToRemove, currentWorkspaceFolders[index2].uri);
    });
    foldersHaveChanged = currentWorkspaceFolders.length !== newStoredFolders.length;
    if (foldersToAdd.length) {
      const workspaceConfigPath = this.getWorkspace().configuration;
      const workspaceConfigFolder = this.X.extUri.dirname(workspaceConfigPath);
      currentWorkspaceFolders = $8w(newStoredFolders, workspaceConfigPath, this.X.extUri);
      const currentWorkspaceFolderUris = currentWorkspaceFolders.map((folder) => folder.uri);
      const storedFoldersToAdd = [];
      for (const folderToAdd of foldersToAdd) {
        const folderURI = folderToAdd.uri;
        if (this.bb(currentWorkspaceFolderUris, folderURI)) {
          continue;
        }
        try {
          const result = await this.U.stat(folderURI);
          if (!result.isDirectory) {
            continue;
          }
        } catch (e) {
        }
        storedFoldersToAdd.push($7w(folderURI, false, folderToAdd.name, workspaceConfigFolder, this.X.extUri));
      }
      if (storedFoldersToAdd.length > 0) {
        foldersHaveChanged = true;
        if (typeof index === "number" && index >= 0 && index < newStoredFolders.length) {
          newStoredFolders = newStoredFolders.slice(0);
          newStoredFolders.splice(index, 0, ...storedFoldersToAdd);
        } else {
          newStoredFolders = [...newStoredFolders, ...storedFoldersToAdd];
        }
      }
    }
    if (foldersHaveChanged) {
      return this.ab(newStoredFolders);
    }
    return Promise.resolve(void 0);
  }
  async ab(folders) {
    if (!this.P) {
      throw new Error("Cannot update workspace folders because workspace service is not yet ready to accept writes.");
    }
    await this.P.invokeFunction((accessor) => this.z.setFolders(folders, accessor.get($CBb)));
    return this.yb(false);
  }
  bb(resources, toCheck) {
    return resources.some((resource) => this.X.extUri.isEqual(resource, toCheck));
  }
  // Workspace Configuration Service Impl
  getConfigurationData() {
    return this.m.toData();
  }
  getValue(arg1, arg2) {
    const section = typeof arg1 === "string" ? arg1 : void 0;
    const overrides = $ll(arg1) ? arg1 : $ll(arg2) ? arg2 : void 0;
    return this.m.getValue(section, overrides);
  }
  async updateValue(key2, value, arg3, arg4, options3) {
    const overrides = $ml(arg3) ? arg3 : $ll(arg3) ? { resource: arg3.resource, overrideIdentifiers: arg3.overrideIdentifier ? [arg3.overrideIdentifier] : void 0 } : void 0;
    const target = overrides ? arg4 : arg3;
    const targets = target ? [target] : [];
    if (overrides?.overrideIdentifiers) {
      overrides.overrideIdentifiers = $Rb(overrides.overrideIdentifiers);
      overrides.overrideIdentifiers = overrides.overrideIdentifiers.length ? overrides.overrideIdentifiers : void 0;
    }
    if (!targets.length) {
      if (overrides?.overrideIdentifiers && overrides.overrideIdentifiers.length > 1) {
        throw new Error("Configuration Target is required while updating the value for multiple override identifiers");
      }
      const inspect = this.inspect(key2, { resource: overrides?.resource, overrideIdentifier: overrides?.overrideIdentifiers ? overrides.overrideIdentifiers[0] : void 0 });
      targets.push(...this.Kb(key2, value, inspect));
      if ($Pv(value, inspect.defaultValue) && targets.length === 1 && (targets[0] === 2 || targets[0] === 3)) {
        value = void 0;
      }
    }
    await Promises.settled(targets.map((target2) => this.Hb(key2, value, target2, overrides, options3)));
  }
  async reloadConfiguration(target) {
    if (target === void 0) {
      this.kb();
      const application = await this.lb(true);
      const { local, remote } = await this.mb();
      await this.ob();
      await this.qb(application, local, remote, true);
      return;
    }
    if ($9k(target)) {
      await this.pb(target);
      return;
    }
    switch (target) {
      case 7:
        this.kb();
        return;
      case 2: {
        const { local, remote } = await this.mb();
        await this.qb(this.m.applicationConfiguration, local, remote, true);
        return;
      }
      case 3:
        await this.reloadLocalUserConfiguration();
        return;
      case 4:
        await this.nb();
        return;
      case 5:
      case 6:
        await this.ob();
        return;
    }
  }
  hasCachedConfigurationDefaultsOverrides() {
    return this.r.hasCachedConfigurationDefaultsOverrides();
  }
  inspect(key2, overrides) {
    return this.m.inspect(key2, overrides);
  }
  keys() {
    return this.m.keys();
  }
  async whenRemoteConfigurationLoaded() {
    await this.g.wait();
  }
  /**
   * At present, all workspaces (empty, single-folder, multi-root) in local and remote
   * can be initialized without requiring extension host except following case:
   *
   * A multi root workspace with .code-workspace file that has to be resolved by an extension.
   * Because of readonly `rootPath` property in extension API we have to resolve multi root workspace
   * before extension host starts so that `rootPath` can be set to first folder.
   *
   * This restriction is lifted partially for web in `MainThreadWorkspace`.
   * In web, we start extension host with empty `rootPath` in this case.
   *
   * Related root path issue discussion is being tracked here - https://github.com/microsoft/vscode/issues/69335
   */
  async initialize(arg) {
    $S("code/willInitWorkspaceService");
    const trigger = this.n;
    this.n = false;
    const workspace2 = await this.cb(arg);
    await this.hb(workspace2, trigger);
    this.gb(false);
    $S("code/didInitWorkspaceService");
  }
  updateWorkspaceTrust(trusted) {
    if (this.L !== trusted) {
      this.L = trusted;
      const data = this.m.toData();
      const folderConfigurationModels = [];
      for (const folder of this.c.folders) {
        const folderConfiguration = this.C.get(folder.uri);
        let configurationModel;
        if (folderConfiguration) {
          configurationModel = folderConfiguration.updateWorkspaceTrust(this.L);
          this.m.updateFolderConfiguration(folder.uri, configurationModel);
        }
        folderConfigurationModels.push(configurationModel);
      }
      if (this.getWorkbenchState() === 2) {
        if (folderConfigurationModels[0]) {
          this.m.updateWorkspaceConfiguration(folderConfigurationModels[0]);
        }
      } else {
        this.m.updateWorkspaceConfiguration(this.z.updateWorkspaceTrust(this.L));
      }
      this.zb();
      let keys = [];
      if (this.restrictedSettings.userLocal) {
        keys.push(...this.restrictedSettings.userLocal);
      }
      if (this.restrictedSettings.userRemote) {
        keys.push(...this.restrictedSettings.userRemote);
      }
      if (this.restrictedSettings.workspace) {
        keys.push(...this.restrictedSettings.workspace);
      }
      this.restrictedSettings.workspaceFolder?.forEach((value) => keys.push(...value));
      keys = $Rb(keys);
      if (keys.length) {
        this.Lb(
          { keys, overrides: [] },
          { data, workspace: this.c },
          5
          /* ConfigurationTarget.WORKSPACE */
        );
      }
    }
  }
  acquireInstantiationService(instantiationService) {
    this.P = instantiationService;
  }
  isSettingAppliedForAllProfiles(key2) {
    if (this.O.getConfigurationProperties()[key2]?.scope === 1) {
      return true;
    }
    const allProfilesSettings = this.getValue($GK) ?? [];
    return Array.isArray(allProfilesSettings) && allProfilesSettings.includes(key2);
  }
  async cb(arg) {
    if ($6k(arg)) {
      return this.db(arg);
    }
    if ($1k(arg)) {
      return this.eb(arg);
    }
    return this.fb(arg);
  }
  async db(workspaceIdentifier) {
    await this.z.initialize({ id: workspaceIdentifier.id, configPath: workspaceIdentifier.configPath }, this.L);
    const workspaceConfigPath = workspaceIdentifier.configPath;
    const workspaceFolders = $8w(this.z.getFolders(), workspaceConfigPath, this.X.extUri);
    const workspaceId = workspaceIdentifier.id;
    const workspace2 = new Workspace(workspaceId, workspaceFolders, this.z.isTransient(), workspaceConfigPath, (uri) => this.X.extUri.ignorePathCasing(uri));
    workspace2.initialized = this.z.initialized;
    return workspace2;
  }
  eb(singleFolderWorkspaceIdentifier) {
    const workspace2 = new Workspace(singleFolderWorkspaceIdentifier.id, [$_k(singleFolderWorkspaceIdentifier.uri)], false, null, (uri) => this.X.extUri.ignorePathCasing(uri));
    workspace2.initialized = true;
    return workspace2;
  }
  fb(emptyWorkspaceIdentifier) {
    const workspace2 = new Workspace(emptyWorkspaceIdentifier.id, [], false, null, (uri) => this.X.extUri.ignorePathCasing(uri));
    workspace2.initialized = true;
    return Promise.resolve(workspace2);
  }
  gb(fromCache) {
    if (!this.h.isOpen() && this.c.initialized) {
      this.h.open();
      this.Fb(fromCache);
    }
  }
  async hb(workspace2, trigger) {
    const hasWorkspaceBefore = !!this.c;
    let previousState;
    let previousWorkspacePath;
    let previousFolders = [];
    if (hasWorkspaceBefore) {
      previousState = this.getWorkbenchState();
      previousWorkspacePath = this.c.configuration ? this.c.configuration.fsPath : void 0;
      previousFolders = this.c.folders;
      this.c.update(workspace2);
    } else {
      if (!workspace2.initialized && this.z.initialized) {
        workspace2.initialized = true;
      }
      this.c = workspace2;
    }
    await this.jb(trigger);
    if (hasWorkspaceBefore) {
      const newState = this.getWorkbenchState();
      if (previousState && newState !== previousState) {
        this.J.fire(newState);
      }
      const newWorkspacePath = this.c.configuration ? this.c.configuration.fsPath : void 0;
      if (previousWorkspacePath && newWorkspacePath !== previousWorkspacePath || newState !== previousState) {
        this.I.fire();
      }
      const folderChanges = this.ib(previousFolders, this.c.folders);
      if (folderChanges && (folderChanges.added.length || folderChanges.removed.length || folderChanges.changed.length)) {
        await this.Bb(folderChanges, false);
        this.H.fire(folderChanges);
      }
    }
    if (!this.w.hasTasksLoaded) {
      this.B($gj($Y, () => this.reloadLocalUserConfiguration(false, this.m.localUserConfiguration)));
    }
  }
  ib(currentFolders, newFolders) {
    const result = { added: [], removed: [], changed: [] };
    result.added = newFolders.filter((newFolder) => !currentFolders.some((currentFolder) => newFolder.uri.toString() === currentFolder.uri.toString()));
    for (let currentIndex = 0; currentIndex < currentFolders.length; currentIndex++) {
      const currentFolder = currentFolders[currentIndex];
      let newIndex = 0;
      for (newIndex = 0; newIndex < newFolders.length && currentFolder.uri.toString() !== newFolders[newIndex].uri.toString(); newIndex++) {
      }
      if (newIndex < newFolders.length) {
        if (currentIndex !== newIndex || currentFolder.name !== newFolders[newIndex].name) {
          result.changed.push(currentFolder);
        }
      } else {
        result.removed.push(currentFolder);
      }
    }
    return result;
  }
  async jb(trigger) {
    await this.r.initialize();
    const initPolicyConfigurationPromise = this.s.initialize();
    const initApplicationConfigurationPromise = this.t ? this.t.initialize() : Promise.resolve($SB.createEmptyModel(this.Y));
    const initUserConfiguration = async () => {
      $S("code/willInitUserConfiguration");
      const result = await Promise.all([this.w.initialize(), this.y ? this.y.initialize() : Promise.resolve($SB.createEmptyModel(this.Y))]);
      if (this.t) {
        const applicationConfigurationModel = await initApplicationConfigurationPromise;
        result[0] = this.w.reparse({ exclude: applicationConfigurationModel.getValue($GK) });
      }
      $S("code/didInitUserConfiguration");
      return result;
    };
    const [, application, [local, remote]] = await Promise.all([
      initPolicyConfigurationPromise,
      initApplicationConfigurationPromise,
      initUserConfiguration()
    ]);
    $S("code/willInitWorkspaceConfiguration");
    await this.qb(application, local, remote, trigger);
    $S("code/didInitWorkspaceConfiguration");
  }
  kb() {
    this.tb(this.r.reload());
  }
  async lb(donotTrigger) {
    if (!this.t) {
      return $SB.createEmptyModel(this.Y);
    }
    const model = await this.t.loadConfiguration();
    if (!donotTrigger) {
      this.vb(model);
    }
    return model;
  }
  async mb() {
    const [local, remote] = await Promise.all([this.reloadLocalUserConfiguration(true), this.nb(true)]);
    return { local, remote };
  }
  async reloadLocalUserConfiguration(donotTrigger, settingsConfiguration) {
    const model = await this.w.reload(settingsConfiguration);
    if (!donotTrigger) {
      this.wb(model);
    }
    return model;
  }
  async nb(donotTrigger) {
    if (this.y) {
      const model = await this.y.reload();
      if (!donotTrigger) {
        this.xb(model);
      }
      return model;
    }
    return $SB.createEmptyModel(this.Y);
  }
  async ob() {
    const workbenchState = this.getWorkbenchState();
    if (workbenchState === 2) {
      return this.Cb(this.c.folders[0]);
    }
    if (workbenchState === 3) {
      return this.z.reload().then(() => this.yb(false));
    }
  }
  pb(folder) {
    return this.Cb(folder);
  }
  async qb(applicationConfigurationModel, userConfigurationModel, remoteUserConfigurationModel, trigger) {
    this.C = new $Ec();
    const folders = this.c.folders;
    const folderConfigurations = await this.Eb(folders);
    const workspaceConfiguration = this.rb(folderConfigurations);
    const folderConfigurationModels = new $Ec();
    folderConfigurations.forEach((folderConfiguration, index) => folderConfigurationModels.set(folders[index].uri, folderConfiguration));
    const currentConfiguration = this.m;
    this.m = new $bmc(this.r.configurationModel, this.s.configurationModel, applicationConfigurationModel, userConfigurationModel, remoteUserConfigurationModel, workspaceConfiguration, folderConfigurationModels, $SB.createEmptyModel(this.Y), new $Ec(), this.c, this.Y);
    this.n = true;
    if (trigger) {
      const change = this.m.compare(currentConfiguration);
      this.Lb(
        change,
        { data: currentConfiguration.toData(), workspace: this.c },
        5
        /* ConfigurationTarget.WORKSPACE */
      );
    }
    this.zb();
  }
  rb(folderConfigurations) {
    switch (this.getWorkbenchState()) {
      case 2:
        return folderConfigurations[0];
      case 3:
        return this.z.getConfiguration();
      default:
        return $SB.createEmptyModel(this.Y);
    }
  }
  sb(e) {
    e.join((async () => {
      const promises = [];
      promises.push(this.w.reset(e.profile.settingsResource, e.profile.tasksResource, { scopes: getLocalUserConfigurationScopes(e.profile, !!this.y) }));
      if (e.previous.isDefault !== e.profile.isDefault || !!e.previous.useDefaultFlags?.settings !== !!e.profile.useDefaultFlags?.settings) {
        this.Z();
        if (this.t) {
          promises.push(this.lb(true));
        }
      }
      let [localUser, application] = await Promise.all(promises);
      application = application ?? this.m.applicationConfiguration;
      if (this.t) {
        localUser = this.w.reparse({ exclude: application.getValue($GK) });
      }
      await this.qb(application, localUser, this.m.remoteUserConfiguration, true);
    })());
  }
  tb(configurationModel, properties) {
    if (this.c) {
      const previousData = this.m.toData();
      const change = this.m.compareAndUpdateDefaultConfiguration(configurationModel, properties);
      if (this.t) {
        this.m.updateApplicationConfiguration(this.t.reparse());
      }
      if (this.y) {
        this.m.updateLocalUserConfiguration(this.w.reparse());
        this.m.updateRemoteUserConfiguration(this.y.reparse());
      }
      if (this.getWorkbenchState() === 2) {
        const folderConfiguration = this.C.get(this.c.folders[0].uri);
        if (folderConfiguration) {
          this.m.updateWorkspaceConfiguration(folderConfiguration.reparse());
          this.m.updateFolderConfiguration(this.c.folders[0].uri, folderConfiguration.reparse());
        }
      } else {
        this.m.updateWorkspaceConfiguration(this.z.reparseWorkspaceSettings());
        for (const folder of this.c.folders) {
          const folderConfiguration = this.C.get(folder.uri);
          if (folderConfiguration) {
            this.m.updateFolderConfiguration(folder.uri, folderConfiguration.reparse());
          }
        }
      }
      this.Lb(
        change,
        { data: previousData, workspace: this.c },
        7
        /* ConfigurationTarget.DEFAULT */
      );
      this.zb();
    }
  }
  ub(policyConfiguration) {
    const previous = { data: this.m.toData(), workspace: this.c };
    const change = this.m.compareAndUpdatePolicyConfiguration(policyConfiguration);
    this.Lb(
      change,
      previous,
      7
      /* ConfigurationTarget.DEFAULT */
    );
  }
  vb(applicationConfiguration) {
    const previous = { data: this.m.toData(), workspace: this.c };
    const previousAllProfilesSettings = this.m.applicationConfiguration.getValue($GK) ?? [];
    const change = this.m.compareAndUpdateApplicationConfiguration(applicationConfiguration);
    const currentAllProfilesSettings = this.getValue($GK) ?? [];
    const configurationProperties = this.O.getConfigurationProperties();
    const changedKeys = [];
    for (const changedKey of change.keys) {
      if (configurationProperties[changedKey]?.scope === 1) {
        changedKeys.push(changedKey);
        if (changedKey === $GK) {
          for (const previousAllProfileSetting of previousAllProfilesSettings) {
            if (!currentAllProfilesSettings.includes(previousAllProfileSetting)) {
              changedKeys.push(previousAllProfileSetting);
            }
          }
          for (const currentAllProfileSetting of currentAllProfilesSettings) {
            if (!previousAllProfilesSettings.includes(currentAllProfileSetting)) {
              changedKeys.push(currentAllProfileSetting);
            }
          }
        }
      } else if (currentAllProfilesSettings.includes(changedKey)) {
        changedKeys.push(changedKey);
      }
    }
    change.keys = changedKeys;
    if (change.keys.includes($GK)) {
      this.m.updateLocalUserConfiguration(this.w.reparse({ exclude: currentAllProfilesSettings }));
    }
    this.Lb(
      change,
      previous,
      2
      /* ConfigurationTarget.USER */
    );
  }
  wb(userConfiguration) {
    const previous = { data: this.m.toData(), workspace: this.c };
    const change = this.m.compareAndUpdateLocalUserConfiguration(userConfiguration);
    this.Lb(
      change,
      previous,
      2
      /* ConfigurationTarget.USER */
    );
  }
  xb(userConfiguration) {
    const previous = { data: this.m.toData(), workspace: this.c };
    const change = this.m.compareAndUpdateRemoteUserConfiguration(userConfiguration);
    this.Lb(
      change,
      previous,
      2
      /* ConfigurationTarget.USER */
    );
  }
  async yb(fromCache) {
    if (this.c && this.c.configuration) {
      let newFolders = $8w(this.z.getFolders(), this.c.configuration, this.X.extUri);
      if (this.c.initialized) {
        const { added, removed, changed } = this.ib(this.c.folders, newFolders);
        if (added.length || removed.length || changed.length) {
          newFolders = await this.Gb(newFolders);
        } else {
          newFolders = this.c.folders;
        }
      }
      await this.Ab(newFolders, this.z.getConfiguration(), fromCache);
    }
  }
  zb() {
    const changed = [];
    const allProperties = this.O.getConfigurationProperties();
    const defaultRestrictedSettings = Object.keys(allProperties).filter((key2) => allProperties[key2].restricted).sort((a, b) => a.localeCompare(b));
    const defaultDelta = $Jb(defaultRestrictedSettings, this.M.default, (a, b) => a.localeCompare(b));
    changed.push(...defaultDelta.added, ...defaultDelta.removed);
    const application = (this.t?.getRestrictedSettings() || []).sort((a, b) => a.localeCompare(b));
    const applicationDelta = $Jb(application, this.M.application || [], (a, b) => a.localeCompare(b));
    changed.push(...applicationDelta.added, ...applicationDelta.removed);
    const userLocal = this.w.getRestrictedSettings().sort((a, b) => a.localeCompare(b));
    const userLocalDelta = $Jb(userLocal, this.M.userLocal || [], (a, b) => a.localeCompare(b));
    changed.push(...userLocalDelta.added, ...userLocalDelta.removed);
    const userRemote = (this.y?.getRestrictedSettings() || []).sort((a, b) => a.localeCompare(b));
    const userRemoteDelta = $Jb(userRemote, this.M.userRemote || [], (a, b) => a.localeCompare(b));
    changed.push(...userRemoteDelta.added, ...userRemoteDelta.removed);
    const workspaceFolderMap = new $Ec();
    for (const workspaceFolder of this.c.folders) {
      const cachedFolderConfig = this.C.get(workspaceFolder.uri);
      const folderRestrictedSettings = (cachedFolderConfig?.getRestrictedSettings() || []).sort((a, b) => a.localeCompare(b));
      if (folderRestrictedSettings.length) {
        workspaceFolderMap.set(workspaceFolder.uri, folderRestrictedSettings);
      }
      const previous = this.M.workspaceFolder?.get(workspaceFolder.uri) || [];
      const workspaceFolderDelta = $Jb(folderRestrictedSettings, previous, (a, b) => a.localeCompare(b));
      changed.push(...workspaceFolderDelta.added, ...workspaceFolderDelta.removed);
    }
    const workspace2 = this.getWorkbenchState() === 3 ? this.z.getRestrictedSettings().sort((a, b) => a.localeCompare(b)) : this.c.folders[0] ? workspaceFolderMap.get(this.c.folders[0].uri) || [] : [];
    const workspaceDelta = $Jb(workspace2, this.M.workspace || [], (a, b) => a.localeCompare(b));
    changed.push(...workspaceDelta.added, ...workspaceDelta.removed);
    if (changed.length) {
      this.M = {
        default: defaultRestrictedSettings,
        application: application.length ? application : void 0,
        userLocal: userLocal.length ? userLocal : void 0,
        userRemote: userRemote.length ? userRemote : void 0,
        workspace: workspace2.length ? workspace2 : void 0,
        workspaceFolder: workspaceFolderMap.size ? workspaceFolderMap : void 0
      };
      this.N.fire(this.restrictedSettings);
    }
  }
  async Ab(workspaceFolders, configuration2, fromCache) {
    const previous = { data: this.m.toData(), workspace: this.c };
    const change = this.m.compareAndUpdateWorkspaceConfiguration(configuration2);
    const changes = this.ib(this.c.folders, workspaceFolders);
    if (changes.added.length || changes.removed.length || changes.changed.length) {
      this.c.folders = workspaceFolders;
      const change2 = await this.Db();
      await this.Bb(changes, fromCache);
      this.Lb(
        change2,
        previous,
        6
        /* ConfigurationTarget.WORKSPACE_FOLDER */
      );
      this.H.fire(changes);
    } else {
      this.Lb(
        change,
        previous,
        5
        /* ConfigurationTarget.WORKSPACE */
      );
    }
    this.zb();
  }
  async Bb(changes, fromCache) {
    const joiners = [];
    this.G.fire({
      join(updateWorkspaceTrustStatePromise) {
        joiners.push(updateWorkspaceTrustStatePromise);
      },
      changes,
      fromCache
    });
    try {
      await Promises.settled(joiners);
    } catch (error) {
    }
  }
  async Cb(folder) {
    const [folderConfiguration] = await this.Eb([folder]);
    const previous = { data: this.m.toData(), workspace: this.c };
    const folderConfigurationChange = this.m.compareAndUpdateFolderConfiguration(folder.uri, folderConfiguration);
    if (this.getWorkbenchState() === 2) {
      const workspaceConfigurationChange = this.m.compareAndUpdateWorkspaceConfiguration(folderConfiguration);
      this.Lb(
        $WB(folderConfigurationChange, workspaceConfigurationChange),
        previous,
        5
        /* ConfigurationTarget.WORKSPACE */
      );
    } else {
      this.Lb(
        folderConfigurationChange,
        previous,
        6
        /* ConfigurationTarget.WORKSPACE_FOLDER */
      );
    }
    this.zb();
  }
  async Db() {
    const changes = [];
    for (const key2 of this.C.keys()) {
      if (!this.c.folders.filter((folder) => folder.uri.toString() === key2.toString())[0]) {
        const folderConfiguration = this.C.get(key2);
        folderConfiguration.dispose();
        this.C.delete(key2);
        changes.push(this.m.compareAndDeleteFolderConfiguration(key2));
      }
    }
    const toInitialize = this.c.folders.filter((folder) => !this.C.has(folder.uri));
    if (toInitialize.length) {
      const folderConfigurations = await this.Eb(toInitialize);
      folderConfigurations.forEach((folderConfiguration, index) => {
        changes.push(this.m.compareAndUpdateFolderConfiguration(toInitialize[index].uri, folderConfiguration));
      });
    }
    return $WB(...changes);
  }
  Eb(folders) {
    return Promise.all([...folders.map((folder) => {
      let folderConfiguration = this.C.get(folder.uri);
      if (!folderConfiguration) {
        folderConfiguration = new $jmc(!this.n, folder, $iK, this.getWorkbenchState(), this.L, this.U, this.X, this.Y, this.j);
        this.B(folderConfiguration.onDidChange(() => this.Cb(folder)));
        this.C.set(folder.uri, this.B(folderConfiguration));
      }
      return folderConfiguration.loadConfiguration();
    })]);
  }
  async Fb(fromCache) {
    const validWorkspaceFolders = await this.Gb(this.c.folders);
    const { removed } = this.ib(this.c.folders, validWorkspaceFolders);
    if (removed.length) {
      await this.Ab(validWorkspaceFolders, this.z.getConfiguration(), fromCache);
    }
  }
  // Filter out workspace folders which are files (not directories)
  // Workspace folders those cannot be resolved are not filtered because they are handled by the Explorer.
  async Gb(workspaceFolders) {
    const validWorkspaceFolders = [];
    for (const workspaceFolder of workspaceFolders) {
      try {
        const result = await this.U.stat(workspaceFolder.uri);
        if (!result.isDirectory) {
          continue;
        }
      } catch (e) {
        this.Y.warn(`Ignoring the error while validating workspace folder ${workspaceFolder.uri.toString()} - ${$1m(e)}`);
      }
      validWorkspaceFolders.push(workspaceFolder);
    }
    return validWorkspaceFolders;
  }
  async Hb(key2, value, target, overrides, options3) {
    if (!this.P) {
      throw new Error("Cannot write configuration because the configuration service is not yet ready to accept writes.");
    }
    if (target === 7) {
      throw new Error("Invalid configuration target");
    }
    if (target === 8) {
      const previous = { data: this.m.toData(), workspace: this.c };
      this.m.updateValue(key2, value, overrides);
      this.Lb({ keys: overrides?.overrideIdentifiers?.length ? [$Tt(overrides.overrideIdentifiers), key2] : [key2], overrides: overrides?.overrideIdentifiers?.length ? overrides.overrideIdentifiers.map((overrideIdentifier) => [overrideIdentifier, [key2]]) : [] }, previous, target);
      return;
    }
    const editableConfigurationTarget = this.Mb(target, key2);
    if (!editableConfigurationTarget) {
      throw new Error("Invalid configuration target");
    }
    if (editableConfigurationTarget === 2 && !this.y) {
      throw new Error("Invalid configuration target");
    }
    if (overrides?.overrideIdentifiers?.length && overrides.overrideIdentifiers.length > 1) {
      const configurationModel = this.Jb(editableConfigurationTarget, overrides.resource);
      if (configurationModel) {
        const overrideIdentifiers = overrides.overrideIdentifiers.sort();
        const existingOverrides = configurationModel.overrides.find((override) => $zb([...override.identifiers].sort(), overrideIdentifiers));
        if (existingOverrides) {
          overrides.overrideIdentifiers = existingOverrides.identifiers;
        }
      }
    }
    this.Q = this.Q ?? this.Ib(this.P);
    await (await this.Q).writeConfiguration(editableConfigurationTarget, { key: key2, value }, { scopes: overrides, ...options3 });
    switch (editableConfigurationTarget) {
      case 1:
        if (this.t && this.isSettingAppliedForAllProfiles(key2)) {
          await this.lb();
        } else {
          await this.reloadLocalUserConfiguration();
        }
        return;
      case 2:
        return this.nb().then(() => void 0);
      case 3:
        return this.ob();
      case 4: {
        const workspaceFolder = overrides && overrides.resource ? this.c.getFolder(overrides.resource) : null;
        if (workspaceFolder) {
          return this.pb(workspaceFolder);
        }
      }
    }
  }
  async Ib(instantiationService) {
    const remoteSettingsResource = (await this.W.getEnvironment())?.settingsPath ?? null;
    return instantiationService.createInstance($dmc, remoteSettingsResource);
  }
  Jb(target, resource) {
    switch (target) {
      case 1:
        return this.m.localUserConfiguration;
      case 2:
        return this.m.remoteUserConfiguration;
      case 3:
        return this.m.workspaceConfiguration;
      case 4:
        return resource ? this.m.folderConfigurations.get(resource) : void 0;
    }
  }
  getConfigurationModel(target, resource) {
    switch (target) {
      case 3:
        return this.m.localUserConfiguration;
      case 4:
        return this.m.remoteUserConfiguration;
      case 5:
        return this.m.workspaceConfiguration;
      case 6:
        return resource ? this.m.folderConfigurations.get(resource) : void 0;
      default:
        return void 0;
    }
  }
  Kb(key2, value, inspect) {
    if ($Pv(value, inspect.value)) {
      return [];
    }
    const definedTargets = [];
    if (inspect.workspaceFolderValue !== void 0) {
      definedTargets.push(
        6
        /* ConfigurationTarget.WORKSPACE_FOLDER */
      );
    }
    if (inspect.workspaceValue !== void 0) {
      definedTargets.push(
        5
        /* ConfigurationTarget.WORKSPACE */
      );
    }
    if (inspect.userRemoteValue !== void 0) {
      definedTargets.push(
        4
        /* ConfigurationTarget.USER_REMOTE */
      );
    }
    if (inspect.userLocalValue !== void 0) {
      definedTargets.push(
        3
        /* ConfigurationTarget.USER_LOCAL */
      );
    }
    if (inspect.applicationValue !== void 0) {
      definedTargets.push(
        1
        /* ConfigurationTarget.APPLICATION */
      );
    }
    if (value === void 0) {
      return definedTargets;
    }
    return [
      definedTargets[0] || 2
      /* ConfigurationTarget.USER */
    ];
  }
  Lb(change, previous, target) {
    if (change.keys.length) {
      if (target !== 7) {
        this.Y.debug(`Configuration keys changed in ${$nl(target)} target`, ...change.keys);
      }
      const configurationChangeEvent = new $XB(change, previous, this.m, this.c, this.Y);
      configurationChangeEvent.source = target;
      this.F.fire(configurationChangeEvent);
    }
  }
  Mb(target, key2) {
    if (target === 1) {
      return 1;
    }
    if (target === 2) {
      if (this.y) {
        const scope = this.O.getConfigurationProperties()[key2]?.scope;
        if (scope === 2 || scope === 6) {
          return 2;
        }
        if (this.inspect(key2).userRemoteValue !== void 0) {
          return 2;
        }
      }
      return 1;
    }
    if (target === 3) {
      return 1;
    }
    if (target === 4) {
      return 2;
    }
    if (target === 5) {
      return 3;
    }
    if (target === 6) {
      return 4;
    }
    return null;
  }
};
var RegisterConfigurationSchemasContribution = class RegisterConfigurationSchemasContribution2 extends $3c {
  constructor(c, g, h3, extensionService, lifecycleService) {
    super();
    this.c = c;
    this.g = g;
    this.h = h3;
    extensionService.whenInstalledExtensionsRegistered().then(() => {
      this.j();
      const configurationRegistry22 = $Wn.as($Ht.Configuration);
      const delayer4 = this.B(new $Sh(50));
      this.B(Event2.any(configurationRegistry22.onDidUpdateConfiguration, configurationRegistry22.onDidSchemaChange, h3.onDidChangeTrust)(() => delayer4.trigger(
        () => this.j(),
        lifecycleService.phase === 4 ? void 0 : 2500
        /* delay longer in early phases */
      )));
    });
  }
  j() {
    const allSettingsSchema = {
      properties: $It.properties,
      patternProperties: $It.patternProperties,
      additionalProperties: true,
      allowTrailingCommas: true,
      allowComments: true
    };
    const userSettingsSchema = this.g.remoteAuthority ? {
      properties: Object.assign({}, $Jt.properties, $Mt.properties, $Nt.properties),
      patternProperties: $It.patternProperties,
      additionalProperties: true,
      allowTrailingCommas: true,
      allowComments: true
    } : allSettingsSchema;
    const profileSettingsSchema = {
      properties: Object.assign({}, $Kt.properties, $Lt.properties, $Mt.properties, $Nt.properties),
      patternProperties: $It.patternProperties,
      additionalProperties: true,
      allowTrailingCommas: true,
      allowComments: true
    };
    const machineSettingsSchema = {
      properties: Object.assign({}, $Kt.properties, $Lt.properties, $Mt.properties, $Nt.properties),
      patternProperties: $It.patternProperties,
      additionalProperties: true,
      allowTrailingCommas: true,
      allowComments: true
    };
    const workspaceSettingsSchema = {
      properties: Object.assign({}, this.n($Lt.properties), this.n($Mt.properties), this.n($Nt.properties)),
      patternProperties: $It.patternProperties,
      additionalProperties: true,
      allowTrailingCommas: true,
      allowComments: true
    };
    const defaultSettingsSchema = {
      properties: Object.keys($It.properties).reduce((result, key2) => {
        result[key2] = Object.assign({ deprecationMessage: void 0 }, $It.properties[key2]);
        return result;
      }, {}),
      patternProperties: Object.keys($It.patternProperties).reduce((result, key2) => {
        result[key2] = Object.assign({ deprecationMessage: void 0 }, $It.patternProperties[key2]);
        return result;
      }, {}),
      additionalProperties: true,
      allowTrailingCommas: true,
      allowComments: true
    };
    const folderSettingsSchema = 3 === this.c.getWorkbenchState() ? {
      properties: Object.assign({}, this.n($Lt.properties), this.n($Nt.properties)),
      patternProperties: $It.patternProperties,
      additionalProperties: true,
      allowTrailingCommas: true,
      allowComments: true
    } : workspaceSettingsSchema;
    const configDefaultsSchema = {
      type: "object",
      description: localize(12566, null),
      properties: Object.assign({}, this.r($Lt.properties), this.r($Mt.properties), this.r($Nt.properties)),
      patternProperties: {
        [$Qt]: {
          type: "object",
          default: {},
          $ref: $Ot
        }
      },
      additionalProperties: false
    };
    this.m({
      defaultSettingsSchema,
      userSettingsSchema,
      profileSettingsSchema,
      machineSettingsSchema,
      workspaceSettingsSchema,
      folderSettingsSchema,
      configDefaultsSchema
    });
  }
  m(schemas2) {
    const jsonRegistry6 = $Wn.as($Xn.JSONContribution);
    jsonRegistry6.registerSchema($lK, schemas2.defaultSettingsSchema);
    jsonRegistry6.registerSchema($mK, schemas2.userSettingsSchema);
    jsonRegistry6.registerSchema($nK, schemas2.profileSettingsSchema);
    jsonRegistry6.registerSchema($oK, schemas2.machineSettingsSchema);
    jsonRegistry6.registerSchema($pK, schemas2.workspaceSettingsSchema);
    jsonRegistry6.registerSchema($qK, schemas2.folderSettingsSchema);
    jsonRegistry6.registerSchema($Pt, schemas2.configDefaultsSchema);
  }
  n(properties) {
    if (this.h.isWorkspaceTrusted()) {
      return properties;
    }
    const result = {};
    Object.entries(properties).forEach(([key2, value]) => {
      if (!value.restricted) {
        result[key2] = value;
      }
    });
    return result;
  }
  r(properties) {
    const result = {};
    Object.entries(properties).forEach(([key2, value]) => {
      if (!value.disallowConfigurationDefault) {
        result[key2] = value;
      }
    });
    return result;
  }
};
RegisterConfigurationSchemasContribution = __decorate([
  __param(0, $Zk),
  __param(1, $US),
  __param(2, $4M),
  __param(3, $wN),
  __param(4, $KL)
], RegisterConfigurationSchemasContribution);
var ResetConfigurationDefaultsOverridesCache = class ResetConfigurationDefaultsOverridesCache2 extends $3c {
  constructor(configurationService, extensionService) {
    super();
    if (configurationService.hasCachedConfigurationDefaultsOverrides()) {
      extensionService.whenInstalledExtensionsRegistered().then(() => configurationService.reloadConfiguration(
        7
        /* ConfigurationTarget.DEFAULT */
      ));
    }
  }
};
ResetConfigurationDefaultsOverridesCache = __decorate([
  __param(0, $kl),
  __param(1, $wN)
], ResetConfigurationDefaultsOverridesCache);
var UpdateExperimentalSettingsDefaults = class UpdateExperimentalSettingsDefaults2 extends $3c {
  static {
    this.ID = "workbench.contrib.updateExperimentalSettingsDefaults";
  }
  constructor(h3) {
    super();
    this.h = h3;
    this.c = /* @__PURE__ */ new Set();
    this.g = $Wn.as($Ht.Configuration);
    this.j(Object.keys(this.g.getConfigurationProperties()));
    this.B(this.g.onDidUpdateConfiguration(({ properties }) => this.j(properties)));
  }
  async j(properties) {
    const overrides = {};
    const allProperties = this.g.getConfigurationProperties();
    for (const property of properties) {
      const schema9 = allProperties[property];
      const tags = schema9?.tags;
      if (!tags || !tags.some((tag2) => tag2.toLowerCase() === "onexp")) {
        continue;
      }
      if (this.c.has(property)) {
        continue;
      }
      this.c.add(property);
      try {
        const value = await this.h.getTreatment(`config.${property}`);
        if (!$Gg(value) && !$Pv(value, schema9.default)) {
          overrides[property] = value;
        }
      } catch (error) {
      }
    }
    if (Object.keys(overrides).length) {
      this.g.registerDefaultConfigurations([{ overrides }]);
    }
  }
};
UpdateExperimentalSettingsDefaults = __decorate([
  __param(0, $hFb)
], UpdateExperimentalSettingsDefaults);
var workbenchContributionsRegistry10 = $Wn.as(Extensions2.Workbench);
workbenchContributionsRegistry10.registerWorkbenchContribution(
  RegisterConfigurationSchemasContribution,
  3
  /* LifecyclePhase.Restored */
);
workbenchContributionsRegistry10.registerWorkbenchContribution(
  ResetConfigurationDefaultsOverridesCache,
  4
  /* LifecyclePhase.Eventually */
);
$PL(
  UpdateExperimentalSettingsDefaults.ID,
  UpdateExperimentalSettingsDefaults,
  2
  /* WorkbenchPhase.BlockRestore */
);
var configurationRegistry18 = $Wn.as($Ht.Configuration);
configurationRegistry18.registerConfiguration({
  ...$UL,
  properties: {
    [$GK]: {
      "type": "array",
      description: localize(12567, null),
      "default": [],
      "scope": 1,
      additionalProperties: true,
      uniqueItems: true
    }
  }
});

// out-build/vs/workbench/services/configuration/common/configurationCache.js
var $lmc = class {
  constructor(c, environmentService, d) {
    this.c = c;
    this.d = d;
    this.b = /* @__PURE__ */ new Map();
    this.a = environmentService.cacheHome;
  }
  needsCaching(resource) {
    return !this.c.includes(resource.scheme);
  }
  read(key2) {
    return this.f(key2).read();
  }
  write(key2, content) {
    return this.f(key2).save(content);
  }
  remove(key2) {
    return this.f(key2).remove();
  }
  f({ type, key: key2 }) {
    const k = `${type}:${key2}`;
    let cachedConfiguration = this.b.get(k);
    if (!cachedConfiguration) {
      cachedConfiguration = new CachedConfiguration({ type, key: key2 }, this.a, this.d);
      this.b.set(k, cachedConfiguration);
    }
    return cachedConfiguration;
  }
};
var CachedConfiguration = class {
  constructor({ type, key: key2 }, cacheHome, d) {
    this.d = d;
    this.b = $vh(cacheHome, "CachedConfigurations", type, key2);
    this.c = $vh(this.b, type === "workspaces" ? "workspace.json" : "configuration.json");
    this.a = new $3h();
  }
  async read() {
    try {
      const content = await this.d.readFile(this.c);
      return content.value.toString();
    } catch (e) {
      return "";
    }
  }
  async save(content) {
    const created2 = await this.f();
    if (created2) {
      await this.a.queue(async () => {
        await this.d.writeFile(this.c, $Ci.fromString(content));
      });
    }
  }
  async remove() {
    try {
      await this.a.queue(() => this.d.del(this.b, { recursive: true, useTrash: false }));
    } catch (error) {
      if (error.fileOperationResult !== 1) {
        throw error;
      }
    }
  }
  async f() {
    if (await this.d.exists(this.b)) {
      return true;
    }
    try {
      await this.d.createFolder(this.b);
      return true;
    } catch (error) {
      return false;
    }
  }
};

// out-build/vs/platform/sign/common/abstractSignService.js
var $OC = class _$OC {
  constructor() {
    this.b = /* @__PURE__ */ new Map();
  }
  static {
    this.a = 1;
  }
  async createNewMessage(value) {
    try {
      const validator = await this.c();
      if (validator) {
        const id2 = String(_$OC.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/browser/signService.js
var KEY_SIZE = 32;
var IV_SIZE = 16;
var STEP_SIZE = KEY_SIZE + IV_SIZE;
var $mmc = class $mmc2 extends $OC {
  constructor(f) {
    super();
    this.f = f;
  }
  c() {
    return this.j().then((vsda) => {
      const v = new vsda.validator();
      return {
        createNewMessage: (arg) => v.createNewMessage(arg),
        validate: (arg) => v.validate(arg),
        dispose: () => v.free()
      };
    });
  }
  d(arg) {
    return this.j().then((vsda) => vsda.sign(arg));
  }
  async j() {
    const checkInterval = new $lj();
    let [wasm] = await Promise.all([
      this.k(),
      new Promise((resolve, reject) => {
        $sJ("vsda", "rust/web/vsda.js").then(() => resolve(), reject);
        checkInterval.cancelAndSet(() => {
          if (typeof vsda_web !== "undefined") {
            resolve();
          }
        }, 50, $Y);
      }).finally(() => checkInterval.dispose())
    ]);
    const keyBytes = new TextEncoder().encode(this.f.serverLicense?.join("\n") || "");
    for (let i2 = 0; i2 + STEP_SIZE < keyBytes.length; i2 += STEP_SIZE) {
      const key2 = await crypto.subtle.importKey("raw", keyBytes.slice(i2 + IV_SIZE, i2 + IV_SIZE + KEY_SIZE), { name: "AES-CBC" }, false, ["decrypt"]);
      wasm = await crypto.subtle.decrypt({ name: "AES-CBC", iv: keyBytes.slice(i2, i2 + IV_SIZE) }, key2, wasm);
    }
    await vsda_web.default(wasm);
    return vsda_web;
  }
  async k() {
    const url = $tJ("vsda", "rust/web/vsda_bg.wasm");
    const response = await fetch(url);
    if (!response.ok) {
      throw new Error("error loading vsda");
    }
    return response.arrayBuffer();
  }
};
__decorate([
  $0t
], $mmc.prototype, "j", null);
$mmc = __decorate([
  __param(0, $Vu)
], $mmc);

// out-build/vs/workbench/services/workspaces/browser/workspaces.js
function $nmc(workspaceUri) {
  return {
    id: getWorkspaceId(workspaceUri),
    configPath: workspaceUri
  };
}
function $omc(folderUri) {
  return {
    id: getWorkspaceId(folderUri),
    uri: folderUri
  };
}
function getWorkspaceId(uri) {
  return $Xi(uri.toString()).toString(16);
}

// out-build/vs/platform/files/browser/indexedDBFileSystemProvider.js
var ERR_FILE_NOT_FOUND = $xm(localize(1904, null), FileSystemProviderErrorCode.FileNotFound);
var ERR_FILE_IS_DIR = $xm(localize(1905, null), FileSystemProviderErrorCode.FileIsADirectory);
var ERR_FILE_NOT_DIR = $xm(localize(1906, null), FileSystemProviderErrorCode.FileNotADirectory);
var ERR_DIR_NOT_EMPTY = $xm(localize(1907, null), FileSystemProviderErrorCode.Unknown);
var ERR_FILE_EXCEEDS_STORAGE_QUOTA = $xm(localize(1908, null), FileSystemProviderErrorCode.FileExceedsStorageQuota);
var ERR_UNKNOWN_INTERNAL = (message) => $xm(localize(1909, null, message), FileSystemProviderErrorCode.Unknown);
var IndexedDBFileSystemNode = class _IndexedDBFileSystemNode {
  constructor(a) {
    this.a = a;
    this.type = a.type;
  }
  read(path) {
    return this.b(path.split("/").filter((p) => p.length));
  }
  b(pathParts) {
    if (pathParts.length === 0) {
      return this.a;
    }
    if (this.a.type !== FileType.Directory) {
      throw ERR_UNKNOWN_INTERNAL("Internal error reading from IndexedDBFSNode -- expected directory at " + this.a.path);
    }
    const next = this.a.children.get(pathParts[0]);
    if (!next) {
      return void 0;
    }
    return next.b(pathParts.slice(1));
  }
  delete(path) {
    const toDelete = path.split("/").filter((p) => p.length);
    if (toDelete.length === 0) {
      if (this.a.type !== FileType.Directory) {
        throw ERR_UNKNOWN_INTERNAL(`Internal error deleting from IndexedDBFSNode. Expected root entry to be directory`);
      }
      this.a.children.clear();
    } else {
      return this.d(toDelete, path);
    }
  }
  d(pathParts, originalPath) {
    if (pathParts.length === 0) {
      throw ERR_UNKNOWN_INTERNAL(`Internal error deleting from IndexedDBFSNode -- got no deletion path parts (encountered while deleting ${originalPath})`);
    } else if (this.a.type !== FileType.Directory) {
      throw ERR_UNKNOWN_INTERNAL("Internal error deleting from IndexedDBFSNode -- expected directory at " + this.a.path);
    } else if (pathParts.length === 1) {
      this.a.children.delete(pathParts[0]);
    } else {
      const next = this.a.children.get(pathParts[0]);
      if (!next) {
        throw ERR_UNKNOWN_INTERNAL("Internal error deleting from IndexedDBFSNode -- expected entry at " + this.a.path + "/" + next);
      }
      next.d(pathParts.slice(1), originalPath);
    }
  }
  add(path, entry) {
    this.f(path.split("/").filter((p) => p.length), entry, path);
  }
  f(pathParts, entry, originalPath) {
    if (pathParts.length === 0) {
      throw ERR_UNKNOWN_INTERNAL(`Internal error creating IndexedDBFSNode -- adding empty path (encountered while adding ${originalPath})`);
    } else if (this.a.type !== FileType.Directory) {
      throw ERR_UNKNOWN_INTERNAL(`Internal error creating IndexedDBFSNode -- parent is not a directory (encountered while adding ${originalPath})`);
    } else if (pathParts.length === 1) {
      const next = pathParts[0];
      const existing = this.a.children.get(next);
      if (entry.type === "dir") {
        if (existing?.a.type === FileType.File) {
          throw ERR_UNKNOWN_INTERNAL(`Internal error creating IndexedDBFSNode -- overwriting file with directory: ${this.a.path}/${next} (encountered while adding ${originalPath})`);
        }
        this.a.children.set(next, existing ?? new _IndexedDBFileSystemNode({
          type: FileType.Directory,
          path: this.a.path + "/" + next,
          children: /* @__PURE__ */ new Map()
        }));
      } else {
        if (existing?.a.type === FileType.Directory) {
          throw ERR_UNKNOWN_INTERNAL(`Internal error creating IndexedDBFSNode -- overwriting directory with file: ${this.a.path}/${next} (encountered while adding ${originalPath})`);
        }
        this.a.children.set(next, new _IndexedDBFileSystemNode({
          type: FileType.File,
          path: this.a.path + "/" + next,
          size: entry.size
        }));
      }
    } else if (pathParts.length > 1) {
      const next = pathParts[0];
      let childNode = this.a.children.get(next);
      if (!childNode) {
        childNode = new _IndexedDBFileSystemNode({
          children: /* @__PURE__ */ new Map(),
          path: this.a.path + "/" + next,
          type: FileType.Directory
        });
        this.a.children.set(next, childNode);
      } else if (childNode.type === FileType.File) {
        throw ERR_UNKNOWN_INTERNAL(`Internal error creating IndexedDBFSNode -- overwriting file entry with directory: ${this.a.path}/${next} (encountered while adding ${originalPath})`);
      }
      childNode.f(pathParts.slice(1), entry, originalPath);
    }
  }
  print(indentation = "") {
    console.log(indentation + this.a.path);
    if (this.a.type === FileType.Directory) {
      this.a.children.forEach((child) => child.print(indentation + " "));
    }
  }
};
var $pmc = class extends $3c {
  constructor(scheme, n, r2, watchCrossWindowChanges) {
    super();
    this.scheme = scheme;
    this.n = n;
    this.r = r2;
    this.capabilities = 2 | 1024;
    this.onDidChangeCapabilities = Event2.None;
    this.a = new $kh(() => false);
    this.f = this.B(new $ze());
    this.onDidChangeFile = this.f.event;
    this.g = this.B(new $ze());
    this.onReportError = this.g.event;
    this.h = /* @__PURE__ */ new Map();
    this.y = [];
    this.m = new $Ph();
    if (watchCrossWindowChanges) {
      this.b = this.B(new $iZ(`vscode.indexedDB.${scheme}.changes`));
      this.B(this.b.onDidReceiveData((changes) => {
        this.f.fire(changes.map((c) => ({ type: c.type, resource: URI.revive(c.resource) })));
      }));
    }
  }
  watch(resource, opts) {
    return $3c.None;
  }
  async mkdir(resource) {
    try {
      const resourceStat = await this.stat(resource);
      if (resourceStat.type === FileType.File) {
        throw ERR_FILE_NOT_DIR;
      }
    } catch (error) {
    }
    (await this.u()).add(resource.path, { type: "dir" });
  }
  async stat(resource) {
    const entry = (await this.u()).read(resource.path);
    if (entry?.type === FileType.File) {
      return {
        type: FileType.File,
        ctime: 0,
        mtime: this.h.get(resource.toString()) || 0,
        size: entry.size ?? (await this.readFile(resource)).byteLength
      };
    }
    if (entry?.type === FileType.Directory) {
      return {
        type: FileType.Directory,
        ctime: 0,
        mtime: 0,
        size: 0
      };
    }
    throw ERR_FILE_NOT_FOUND;
  }
  async readdir(resource) {
    try {
      const entry = (await this.u()).read(resource.path);
      if (!entry) {
        return [];
      }
      if (entry.type !== FileType.Directory) {
        throw ERR_FILE_NOT_DIR;
      } else {
        return [...entry.children.entries()].map(([name, node]) => [name, node.type]);
      }
    } catch (error) {
      this.D("readDir", error);
      throw error;
    }
  }
  async readFile(resource) {
    try {
      const result = await this.n.runInTransaction(this.r, "readonly", (objectStore) => objectStore.get(resource.path));
      if (result === void 0) {
        throw ERR_FILE_NOT_FOUND;
      }
      const buffer = result instanceof Uint8Array ? result : $zg(result) ? $Ci.fromString(result).buffer : void 0;
      if (buffer === void 0) {
        throw ERR_UNKNOWN_INTERNAL(`IndexedDB entry at "${resource.path}" in unexpected format`);
      }
      const fileTree = await this.u();
      fileTree.add(resource.path, { type: "file", size: buffer.byteLength });
      return buffer;
    } catch (error) {
      this.D("readFile", error);
      throw error;
    }
  }
  async writeFile(resource, content, opts) {
    try {
      const existing = await this.stat(resource).catch(() => void 0);
      if (existing?.type === FileType.Directory) {
        throw ERR_FILE_IS_DIR;
      }
      await this.w([[resource, content]]);
    } catch (error) {
      this.D("writeFile", error);
      throw error;
    }
  }
  async rename(from, to, opts) {
    const fileTree = await this.u();
    const fromEntry = fileTree.read(from.path);
    if (!fromEntry) {
      throw ERR_FILE_NOT_FOUND;
    }
    const toEntry2 = fileTree.read(to.path);
    if (toEntry2) {
      if (!opts.overwrite) {
        throw $xm("file exists already", FileSystemProviderErrorCode.FileExists);
      }
      if (toEntry2.type !== fromEntry.type) {
        throw $xm("Cannot rename files with different types", FileSystemProviderErrorCode.Unknown);
      }
      await this.delete(to, { recursive: true, useTrash: false, atomic: false });
    }
    const toTargetResource = (path) => this.a.joinPath(to, this.a.relativePath(from, from.with({ path })) || "");
    const sourceEntries = await this.s(from);
    const sourceFiles = [];
    for (const sourceEntry of sourceEntries) {
      if (sourceEntry[1] === FileType.File) {
        sourceFiles.push(sourceEntry);
      } else if (sourceEntry[1] === FileType.Directory) {
        fileTree.add(toTargetResource(sourceEntry[0]).path, { type: "dir" });
      }
    }
    if (sourceFiles.length) {
      const targetFiles = [];
      const sourceFilesContents = await this.n.runInTransaction(this.r, "readonly", (objectStore) => sourceFiles.map(([path]) => objectStore.get(path)));
      for (let index = 0; index < sourceFiles.length; index++) {
        const content = sourceFilesContents[index] instanceof Uint8Array ? sourceFilesContents[index] : $zg(sourceFilesContents[index]) ? $Ci.fromString(sourceFilesContents[index]).buffer : void 0;
        if (content) {
          targetFiles.push([toTargetResource(sourceFiles[index][0]), content]);
        }
      }
      await this.w(targetFiles);
    }
    await this.delete(from, { recursive: true, useTrash: false, atomic: false });
  }
  async delete(resource, opts) {
    let stat;
    try {
      stat = await this.stat(resource);
    } catch (e) {
      if (e.code === FileSystemProviderErrorCode.FileNotFound) {
        return;
      }
      throw e;
    }
    let toDelete;
    if (opts.recursive) {
      const tree = await this.s(resource);
      toDelete = tree.map(([path]) => path);
    } else {
      if (stat.type === FileType.Directory && (await this.readdir(resource)).length) {
        throw ERR_DIR_NOT_EMPTY;
      }
      toDelete = [resource.path];
    }
    await this.C(toDelete);
    (await this.u()).delete(resource.path);
    toDelete.forEach((key2) => this.h.delete(key2));
    this.t(toDelete.map((path) => ({
      resource: resource.with({ path }),
      type: 2
      /* FileChangeType.DELETED */
    })));
  }
  async s(resource) {
    const stat = await this.stat(resource);
    const allEntries = [[resource.path, stat.type]];
    if (stat.type === FileType.Directory) {
      const dirEntries = await this.readdir(resource);
      for (const [key2, type] of dirEntries) {
        const childResource = this.a.joinPath(resource, key2);
        allEntries.push([childResource.path, type]);
        if (type === FileType.Directory) {
          const childEntries = await this.s(childResource);
          allEntries.push(...childEntries);
        }
      }
    }
    return allEntries;
  }
  t(changes) {
    if (changes.length) {
      this.f.fire(changes);
      this.b?.postData(changes);
    }
  }
  u() {
    if (!this.j) {
      this.j = (async () => {
        const rootNode = new IndexedDBFileSystemNode({
          children: /* @__PURE__ */ new Map(),
          path: "",
          type: FileType.Directory
        });
        const result = await this.n.runInTransaction(this.r, "readonly", (objectStore) => objectStore.getAllKeys());
        const keys = result.map((key2) => key2.toString());
        keys.forEach((key2) => rootNode.add(key2, { type: "file" }));
        return rootNode;
      })();
    }
    return this.j;
  }
  async w(files) {
    files.forEach(([resource, content]) => this.y.push({ content, resource }));
    await this.m.queue(() => this.z());
    const fileTree = await this.u();
    for (const [resource, content] of files) {
      fileTree.add(resource.path, { type: "file", size: content.byteLength });
      this.h.set(resource.toString(), Date.now());
    }
    this.t(files.map(([resource]) => ({
      resource,
      type: 0
      /* FileChangeType.UPDATED */
    })));
  }
  async z() {
    if (this.y.length) {
      const fileBatch = this.y.splice(0, this.y.length);
      try {
        await this.n.runInTransaction(this.r, "readwrite", (objectStore) => fileBatch.map((entry) => {
          return objectStore.put(entry.content, entry.resource.path);
        }));
        this.n.pwbAddToSessionSet($$1.PWB_CHANGED_CONNECTION_KEY);
      } catch (ex) {
        if (ex instanceof DOMException && ex.name === "QuotaExceededError") {
          throw ERR_FILE_EXCEEDS_STORAGE_QUOTA;
        }
        throw ex;
      }
    }
  }
  async C(keys) {
    if (keys.length) {
      await this.n.runInTransaction(this.r, "readwrite", (objectStore) => keys.map((key2) => objectStore.delete(key2)));
      this.n.pwbAddToSessionSet($$1.PWB_CHANGED_CONNECTION_KEY);
    }
  }
  async reset() {
    await this.n.runInTransaction(this.r, "readwrite", (objectStore) => objectStore.clear());
    this.n.pwbAddToSessionSet($$1.PWB_CHANGED_CONNECTION_KEY);
  }
  D(operation, error) {
    this.g.fire({ scheme: this.scheme, operation, code: error instanceof $wm || error instanceof $01 ? error.code : "unknown" });
  }
};

// out-build/vs/platform/request/common/requestIpc.js
var $CX = class {
  constructor(a) {
    this.a = a;
  }
  async request(options3, token) {
    const [res, buffer] = await this.a.call("request", [options3], token);
    return { res, stream: $Qi(buffer) };
  }
  async resolveProxy(url) {
    return this.a.call("resolveProxy", [url]);
  }
  async lookupAuthorization(authInfo) {
    return this.a.call("lookupAuthorization", [authInfo]);
  }
  async lookupKerberosAuthorization(url) {
    return this.a.call("lookupKerberosAuthorization", [url]);
  }
  async loadCertificates() {
    return this.a.call("loadCertificates");
  }
};

// out-build/vs/base/parts/request/common/requestImpl.js
async function $s4(options3, token, isOnline) {
  if (token.isCancellationRequested) {
    throw $mb();
  }
  const cancellation = new AbortController();
  const disposable = token.onCancellationRequested(() => cancellation.abort());
  const signal = options3.timeout ? AbortSignal.any([
    cancellation.signal,
    AbortSignal.timeout(options3.timeout)
  ]) : cancellation.signal;
  try {
    const fetchInit = {
      method: options3.type || "GET",
      headers: getRequestHeaders(options3),
      body: options3.data,
      signal
    };
    if (options3.disableCache) {
      fetchInit.cache = "no-store";
    }
    const res = await fetch(options3.url || "", fetchInit);
    return {
      res: {
        statusCode: res.status,
        headers: getResponseHeaders(res)
      },
      stream: $Qi($Ci.wrap(new Uint8Array(await res.arrayBuffer())))
    };
  } catch (err) {
    if (isOnline && !isOnline()) {
      throw new $8u();
    }
    if (err?.name === "AbortError") {
      throw $mb();
    }
    if (err?.name === "TimeoutError") {
      throw new Error(`Fetch timeout: ${options3.timeout}ms`);
    }
    throw err;
  } finally {
    disposable.dispose();
  }
}
function getRequestHeaders(options3) {
  if (options3.headers || options3.user || options3.password || options3.proxyAuthorization) {
    const headers = new Headers();
    outer: for (const k in options3.headers) {
      switch (k.toLowerCase()) {
        case "user-agent":
        case "accept-encoding":
        case "content-length":
          continue outer;
      }
      const header = options3.headers[k];
      if (typeof header === "string") {
        headers.set(k, header);
      } else if (Array.isArray(header)) {
        for (const h3 of header) {
          headers.append(k, h3);
        }
      }
    }
    if (options3.user || options3.password) {
      headers.set("Authorization", "Basic " + btoa(`${options3.user || ""}:${options3.password || ""}`));
    }
    if (options3.proxyAuthorization) {
      headers.set("Proxy-Authorization", options3.proxyAuthorization);
    }
    return headers;
  }
  return void 0;
}
function getResponseHeaders(res) {
  const headers = /* @__PURE__ */ Object.create(null);
  res.headers.forEach((value, key2) => {
    if (headers[key2]) {
      if (Array.isArray(headers[key2])) {
        headers[key2].push(value);
      } else {
        headers[key2] = [headers[key2], value];
      }
    } else {
      headers[key2] = value;
    }
  });
  return headers;
}

// out-build/vs/workbench/services/request/browser/requestService.js
var $qmc = class $qmc2 extends $0u {
  constructor(f, g, logService) {
    super(logService);
    this.f = f;
    this.g = g;
  }
  async request(options3, token) {
    try {
      if (!options3.proxyAuthorization) {
        options3.proxyAuthorization = this.g.getValue("http.proxyAuthorization");
      }
      const context = await this.c(options3, () => $s4(options3, token, () => navigator.onLine));
      const connection = this.f.getConnection();
      if (connection && context.res.statusCode === 405) {
        return this.h(connection, options3, token);
      }
      return context;
    } catch (error) {
      const connection = this.f.getConnection();
      if (connection) {
        return this.h(connection, options3, token);
      }
      throw error;
    }
  }
  async resolveProxy(url) {
    return void 0;
  }
  async lookupAuthorization(authInfo) {
    return void 0;
  }
  async lookupKerberosAuthorization(url) {
    return void 0;
  }
  async loadCertificates() {
    return [];
  }
  h(connection, options3, token) {
    return connection.withChannel("request", (channel) => new $CX(channel).request(options3, token));
  }
};
$qmc = __decorate([
  __param(0, $RL),
  __param(1, $kl),
  __param(2, $wn)
], $qmc);
$tn.registerCommand("_workbench.fetchJSON", async function(accessor, url, method) {
  const result = await fetch(url, { method, headers: { Accept: "application/json" } });
  if (result.ok) {
    return result.json();
  } else {
    throw new Error(result.statusText);
  }
});

// out-build/vs/base/common/skipList.js
var _a3;
var Node5 = class {
  constructor(level, key2, value) {
    this.level = level;
    this.key = key2;
    this.value = value;
    this.forward = [];
  }
};
var NIL = void 0;
var $UC = class _$UC {
  /**
   *
   * @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 Node5(this.c, NIL, NIL);
  }
  get size() {
    return this.f;
  }
  clear() {
    this.e = new Node5(this.c, NIL, NIL);
    this.f = 0;
  }
  has(key2) {
    return Boolean(_$UC.g(this, key2, this.comparator));
  }
  get(key2) {
    return _$UC.g(this, key2, this.comparator)?.value;
  }
  set(key2, value) {
    if (_$UC.h(this, key2, value, this.comparator)) {
      this.f += 1;
    }
    return this;
  }
  delete(key2) {
    const didDelete = _$UC.k(this, key2, 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(list2, searchKey, comparator) {
    let x = list2.e;
    for (let i2 = list2.d - 1; i2 >= 0; i2--) {
      while (x.forward[i2] && comparator(x.forward[i2].key, searchKey) < 0) {
        x = x.forward[i2];
      }
    }
    x = x.forward[0];
    if (x && comparator(x.key, searchKey) === 0) {
      return x;
    }
    return void 0;
  }
  static h(list2, searchKey, value, comparator) {
    const update = [];
    let x = list2.e;
    for (let i2 = list2.d - 1; i2 >= 0; i2--) {
      while (x.forward[i2] && comparator(x.forward[i2].key, searchKey) < 0) {
        x = x.forward[i2];
      }
      update[i2] = x;
    }
    x = x.forward[0];
    if (x && comparator(x.key, searchKey) === 0) {
      x.value = value;
      return false;
    } else {
      const lvl = _$UC.j(list2);
      if (lvl > list2.d) {
        for (let i2 = list2.d; i2 < lvl; i2++) {
          update[i2] = list2.e;
        }
        list2.d = lvl;
      }
      x = new Node5(lvl, searchKey, value);
      for (let i2 = 0; i2 < lvl; i2++) {
        x.forward[i2] = update[i2].forward[i2];
        update[i2].forward[i2] = x;
      }
      return true;
    }
  }
  static j(list2, p = 0.5) {
    let lvl = 1;
    while (Math.random() < p && lvl < list2.c) {
      lvl += 1;
    }
    return lvl;
  }
  static k(list2, searchKey, comparator) {
    const update = [];
    let x = list2.e;
    for (let i2 = list2.d - 1; i2 >= 0; i2--) {
      while (x.forward[i2] && comparator(x.forward[i2].key, searchKey) < 0) {
        x = x.forward[i2];
      }
      update[i2] = x;
    }
    x = x.forward[0];
    if (!x || comparator(x.key, searchKey) !== 0) {
      return false;
    }
    for (let i2 = 0; i2 < list2.d; i2++) {
      if (update[i2].forward[i2] !== x) {
        break;
      }
      update[i2].forward[i2] = x.forward[i2];
    }
    while (list2.d > 0 && list2.e.forward[list2.d - 1] === NIL) {
      list2.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 $VC = class $VC2 {
  constructor(g) {
    this.g = g;
    this.c = new $2c();
    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(Event2.any(g.onDidChangeFileSystemProviderRegistrations, g.onDidChangeFileSystemProviderCapabilities)((e) => {
      schemeIgnoresPathCasingCache.delete(e.scheme);
    }));
    this.extUri = new $kh(ignorePathCasing);
    this.d = new $UC((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 = $wh(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 entries2 = [...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 i2 = 0; i2 < newSize; i2++) {
      this.d.set(entries2[i2][0], entries2[i2][1].touch());
    }
  }
};
$VC = __decorate([
  __param(0, $km)
], $VC);
$SC(
  $vl,
  $VC,
  1
  /* InstantiationType.Delayed */
);

// out-build/vs/workbench/services/output/common/delayedLogChannel.js
var $rmc = class $rmc2 {
  constructor(id2, name, b, c) {
    this.b = b;
    this.c = c;
    this.a = c.createLogger(b, { name, id: id2, hidden: true });
  }
  log(level, message) {
    this.c.setVisibility(this.b, true);
    log(this.a, level, message);
  }
};
$rmc = __decorate([
  __param(3, $xn)
], $rmc);

// out-build/vs/workbench/services/userDataProfile/common/userDataProfileService.js
var $smc = class extends $3c {
  get currentProfile() {
    return this.b;
  }
  constructor(currentProfile) {
    super();
    this.a = this.B(new $ze());
    this.onDidChangeCurrentProfile = this.a.event;
    this.b = currentProfile;
  }
  async updateCurrentProfile(userDataProfile) {
    if ($Pv(this.b, userDataProfile)) {
      return;
    }
    const previous = this.b;
    this.b = userDataProfile;
    const joiners = [];
    this.a.fire({
      previous,
      profile: userDataProfile,
      join(promise) {
        joiners.push(promise);
      }
    });
    await Promises.settled(joiners);
  }
};

// out-build/vs/platform/userDataProfile/browser/userDataProfile.js
var $tmc = class $tmc2 extends $us {
  constructor(environmentService, fileService, uriIdentityService, logService) {
    super(environmentService, fileService, uriIdentityService, logService);
    this.S = this.B(new $iZ(`${$us.b}.changes`));
    this.B(this.S.onDidReceiveData((changes) => {
      try {
        this.z = void 0;
        const added = changes.added.map((p) => $ss(p, this.profilesHome.scheme));
        const removed = changes.removed.map((p) => $ss(p, this.profilesHome.scheme));
        const updated = changes.updated.map((p) => $ss(p, this.profilesHome.scheme));
        this.U(added.filter((a) => a.isTransient), removed.filter((a) => a.isTransient), updated.filter((a) => a.isTransient));
        this.g.fire({
          added,
          removed,
          updated,
          all: this.profiles
        });
      } catch (error) {
      }
    }));
  }
  U(added, removed, updated) {
    if (added.length) {
      this.r.profiles.push(...added);
    }
    if (removed.length || updated.length) {
      const allTransientProfiles = this.r.profiles;
      this.r.profiles = [];
      for (const profile of allTransientProfiles) {
        if (removed.some((p) => profile.id === p.id)) {
          continue;
        }
        this.r.profiles.push(updated.find((p) => profile.id === p.id) ?? profile);
      }
    }
  }
  N() {
    try {
      const value = localStorage.getItem($us.b);
      if (value) {
        return $cu(JSON.parse(value));
      }
    } catch (error) {
      this.y.error(error);
    }
    return [];
  }
  J(added, removed, updated) {
    super.J(added, removed, updated);
    this.S.postData({ added, removed, updated });
  }
  O(storedProfiles) {
    localStorage.setItem($us.b, JSON.stringify(storedProfiles));
  }
  P() {
    try {
      const value = localStorage.getItem($us.c);
      if (value) {
        return JSON.parse(value);
      }
    } catch (error) {
      this.y.error(error);
    }
    return {};
  }
  Q(storedProfileAssociations) {
    localStorage.setItem($us.c, JSON.stringify(storedProfileAssociations));
  }
};
$tmc = __decorate([
  __param(0, $Xk),
  __param(1, $km),
  __param(2, $vl),
  __param(3, $wn)
], $tmc);

// out-build/vs/platform/log/common/logService.js
var $WC = class extends $3c {
  constructor(primaryLogger, otherLoggers = []) {
    super();
    this.a = new $Gn([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, ...args2) {
    this.a.trace(message, ...args2);
  }
  debug(message, ...args2) {
    this.a.debug(message, ...args2);
  }
  info(message, ...args2) {
    this.a.info(message, ...args2);
  }
  warn(message, ...args2) {
    this.a.warn(message, ...args2);
  }
  error(message, ...args2) {
    this.a.error(message, ...args2);
  }
  flush() {
    this.a.flush();
  }
};

// out-build/vs/platform/remote/browser/browserSocketFactory.js
var BrowserWebSocket = class extends $3c {
  traceSocketEvent(type, data) {
    SocketDiagnostics.traceSocketEvent(this.h, this.g, type, data);
  }
  constructor(url, debugLabel) {
    super();
    this.a = new $ze();
    this.onData = this.a.event;
    this.b = this.B(new $ze());
    this.onOpen = this.b.event;
    this.c = this.B(new $ze());
    this.onClose = this.c.event;
    this.f = this.B(new $ze());
    this.onError = this.f.event;
    this.g = debugLabel;
    this.h = new WebSocket(url);
    this.traceSocketEvent("created", { type: "BrowserWebSocket", url });
    this.j = new FileReader();
    this.m = [];
    this.n = false;
    this.r = false;
    this.j.onload = (event) => {
      this.n = false;
      const buff = event.target.result;
      this.traceSocketEvent("read", buff);
      this.a.fire(buff);
      if (this.m.length > 0) {
        enqueue(this.m.shift());
      }
    };
    const enqueue = (blob) => {
      if (this.n) {
        this.m.push(blob);
        return;
      }
      this.n = true;
      this.j.readAsArrayBuffer(blob);
    };
    this.s = (ev) => {
      const blob = ev.data;
      this.traceSocketEvent("browserWebSocketBlobReceived", { type: blob.type, size: blob.size });
      enqueue(blob);
    };
    this.h.addEventListener("message", this.s);
    this.B($_i(this.h, "open", (e) => {
      this.traceSocketEvent(
        "open"
        /* SocketDiagnosticsEventType.Open */
      );
      this.b.fire();
    }));
    let pendingErrorEvent = null;
    const sendPendingErrorNow = () => {
      const err = pendingErrorEvent;
      pendingErrorEvent = null;
      this.f.fire(err);
    };
    const errorRunner = this.B(new $8h(sendPendingErrorNow, 0));
    const sendErrorSoon = (err) => {
      errorRunner.cancel();
      pendingErrorEvent = err;
      errorRunner.schedule();
    };
    const sendErrorNow = (err) => {
      errorRunner.cancel();
      pendingErrorEvent = err;
      sendPendingErrorNow();
    };
    this.B($_i(this.h, "close", (e) => {
      this.traceSocketEvent("close", { code: e.code, reason: e.reason, wasClean: e.wasClean });
      this.r = true;
      if (pendingErrorEvent) {
        if (!navigator.onLine) {
          sendErrorNow(new $eC("Browser is offline", RemoteAuthorityResolverErrorCode.TemporarilyNotAvailable, e));
        } else {
          if (!e.wasClean) {
            sendErrorNow(new $eC(e.reason || `WebSocket close with status code ${e.code}`, RemoteAuthorityResolverErrorCode.TemporarilyNotAvailable, e));
          } else {
            errorRunner.cancel();
            sendPendingErrorNow();
          }
        }
      }
      this.c.fire({ code: e.code, reason: e.reason, wasClean: e.wasClean, event: e });
    }));
    this.B($_i(this.h, "error", (err) => {
      this.traceSocketEvent("error", { message: err?.message });
      sendErrorSoon(err);
    }));
  }
  send(data) {
    if (this.r) {
      return;
    }
    this.traceSocketEvent("write", data);
    this.h.send(data);
  }
  close() {
    this.r = true;
    this.traceSocketEvent(
      "close"
      /* SocketDiagnosticsEventType.Close */
    );
    this.h.close();
    this.h.removeEventListener("message", this.s);
    this.dispose();
  }
};
var defaultWebSocketFactory = new class {
  create(url, debugLabel) {
    return new BrowserWebSocket(url, debugLabel);
  }
}();
var BrowserSocket = class {
  traceSocketEvent(type, data) {
    if (typeof this.socket.traceSocketEvent === "function") {
      this.socket.traceSocketEvent(type, data);
    } else {
      SocketDiagnostics.traceSocketEvent(this.socket, this.debugLabel, type, data);
    }
  }
  constructor(socket, debugLabel) {
    this.socket = socket;
    this.debugLabel = debugLabel;
  }
  dispose() {
    this.socket.close();
  }
  onData(listener) {
    return this.socket.onData((data) => listener($Ci.wrap(new Uint8Array(data))));
  }
  onClose(listener) {
    const adapter = (e) => {
      if (typeof e === "undefined") {
        listener(e);
      } else {
        listener({
          type: 1,
          code: e.code,
          reason: e.reason,
          wasClean: e.wasClean,
          event: e.event
        });
      }
    };
    return this.socket.onClose(adapter);
  }
  onEnd(listener) {
    return $3c.None;
  }
  write(buffer) {
    this.socket.send(buffer.buffer);
  }
  end() {
    this.socket.close();
  }
  drain() {
    return Promise.resolve();
  }
};
var $L4 = class {
  constructor(webSocketFactory) {
    this.a = webSocketFactory || defaultWebSocketFactory;
  }
  supports(connectTo) {
    return true;
  }
  connect({ host, port }, path, query, debugLabel) {
    return new Promise((resolve, reject) => {
      const webSocketSchema = /^https:/.test($Y.location.href) ? "wss" : "ws";
      path = ($Y.location.pathname + "/" + path).replace(/\/\/+/g, "/");
      const socket = this.a.create(`${webSocketSchema}://${/:/.test(host) && !/\[/.test(host) ? `[${host}]` : host}:${port}${path}?${query}&skipWebSocketFrames=false`, debugLabel);
      const errorListener = socket.onError(reject);
      socket.onOpen(() => {
        errorListener.dispose();
        resolve(new BrowserSocket(socket, debugLabel));
      });
    });
  }
};

// out-build/vs/workbench/services/userDataProfile/browser/userDataProfileInit.js
var $umc = class $umc2 {
  constructor(c, d, e, f, g, h3, i2) {
    this.c = c;
    this.d = d;
    this.e = e;
    this.f = f;
    this.g = g;
    this.h = h3;
    this.i = i2;
    this.a = [];
    this.b = new $Uh();
  }
  async whenInitializationFinished() {
    await this.b.wait();
  }
  async requiresInitialization() {
    if (!this.c.options?.profile?.contents) {
      return false;
    }
    if (!this.f.isNew(
      0
      /* StorageScope.PROFILE */
    )) {
      return false;
    }
    return true;
  }
  async initializeRequiredResources() {
    this.g.trace(`UserDataProfileInitializer#initializeRequiredResources`);
    const promises = [];
    const profileTemplate = await this.l();
    if (profileTemplate?.settings) {
      promises.push(this.n(
        new $AWb(this.e, this.d, this.g),
        profileTemplate.settings,
        "settings"
        /* ProfileResourceType.Settings */
      ));
    }
    if (profileTemplate?.globalState) {
      promises.push(this.n(
        new $RWb(this.f),
        profileTemplate.globalState,
        "globalState"
        /* ProfileResourceType.GlobalState */
      ));
    }
    await Promise.all(promises);
  }
  async initializeOtherResources(instantiationService) {
    try {
      this.g.trace(`UserDataProfileInitializer#initializeOtherResources`);
      const promises = [];
      const profileTemplate = await this.l();
      if (profileTemplate?.keybindings) {
        promises.push(this.n(
          new $DWb(this.e, this.d, this.g),
          profileTemplate.keybindings,
          "keybindings"
          /* ProfileResourceType.Keybindings */
        ));
      }
      if (profileTemplate?.tasks) {
        promises.push(this.n(
          new $JWb(this.e, this.d, this.g),
          profileTemplate.tasks,
          "tasks"
          /* ProfileResourceType.Tasks */
        ));
      }
      if (profileTemplate?.snippets) {
        promises.push(this.n(
          new $GWb(this.e, this.d, this.h),
          profileTemplate.snippets,
          "snippets"
          /* ProfileResourceType.Snippets */
        ));
      }
      promises.push(this.initializeInstalledExtensions(instantiationService));
      await Promises.settled(promises);
    } finally {
      this.b.open();
    }
  }
  async initializeInstalledExtensions(instantiationService) {
    if (!this.j) {
      const profileTemplate = await this.l();
      if (profileTemplate?.extensions) {
        this.j = this.n(
          instantiationService.createInstance($MWb),
          profileTemplate.extensions,
          "extensions"
          /* ProfileResourceType.Extensions */
        );
      } else {
        this.j = Promise.resolve();
      }
    }
    return this.j;
  }
  l() {
    if (!this.k) {
      this.k = this.m();
    }
    return this.k;
  }
  async m() {
    if (!this.c.options?.profile?.contents) {
      return null;
    }
    if ($zg(this.c.options.profile.contents)) {
      try {
        return JSON.parse(this.c.options.profile.contents);
      } catch (error) {
        this.g.error(error);
        return null;
      }
    }
    try {
      const url = URI.revive(this.c.options.profile.contents).toString(true);
      const context = await this.i.request({ type: "GET", url }, CancellationToken.None);
      if (context.res.statusCode === 200) {
        return await $cv(context);
      } else {
        this.g.warn(`UserDataProfileInitializer: Failed to get profile from URL: ${url}. Status code: ${context.res.statusCode}.`);
      }
    } catch (error) {
      this.g.error(error);
    }
    return null;
  }
  async n(initializer, content, profileResource) {
    try {
      if (this.a.includes(profileResource)) {
        this.g.info(`UserDataProfileInitializer: ${profileResource} initialized already.`);
        return;
      }
      this.a.push(profileResource);
      this.g.trace(`UserDataProfileInitializer: Initializing ${profileResource}`);
      await initializer.initialize(content);
      this.g.info(`UserDataProfileInitializer: Initialized ${profileResource}`);
    } catch (error) {
      this.g.info(`UserDataProfileInitializer: Error while initializing ${profileResource}`);
      this.g.error(error);
    }
  }
};
$umc = __decorate([
  __param(0, $M4),
  __param(1, $km),
  __param(2, $gT),
  __param(3, $jv),
  __param(4, $wn),
  __param(5, $vl),
  __param(6, $9u)
], $umc);

// out-build/vs/platform/userDataSync/common/extensionsMerge.js
function $vmc(localExtensions, remoteExtensions, lastSyncExtensions, skippedExtensions, ignoredExtensions, lastSyncBuiltinExtensions) {
  const added = [];
  const removed = [];
  const updated = [];
  if (!remoteExtensions) {
    const remote2 = localExtensions.filter(({ identifier: identifier2 }) => ignoredExtensions.every((id2) => id2.toLowerCase() !== identifier2.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 = (identifier2) => {
    if (identifier2.uuid) {
      uuids.set(identifier2.id.toLowerCase(), identifier2.uuid);
    }
  };
  localExtensions.forEach(({ identifier: identifier2 }) => addUUID(identifier2));
  remoteExtensions.forEach(({ identifier: identifier2 }) => addUUID(identifier2));
  lastSyncExtensions?.forEach(({ identifier: identifier2 }) => addUUID(identifier2));
  skippedExtensions?.forEach(({ identifier: identifier2 }) => addUUID(identifier2));
  lastSyncBuiltinExtensions?.forEach((identifier2) => addUUID(identifier2));
  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, $Lv(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 = compare5(localExtensionsMap, remoteExtensionsMap, ignoredExtensionsSet, false);
  if (localToRemote.added.size > 0 || localToRemote.removed.size > 0 || localToRemote.updated.size > 0) {
    const baseToLocal = compare5(lastSyncExtensionsMap, localExtensionsMap, ignoredExtensionsSet, false);
    const baseToRemote = compare5(lastSyncExtensionsMap, remoteExtensionsMap, ignoredExtensionsSet, true);
    const merge2 = (key2, localExtension, remoteExtension, preferred) => {
      let pinned, version2, preRelease;
      if (localExtension.installed) {
        pinned = preferred.pinned;
        preRelease = preferred.preRelease;
        if (pinned) {
          version2 = preferred.version;
        }
      } else {
        pinned = remoteExtension.pinned;
        preRelease = remoteExtension.preRelease;
        if (pinned) {
          version2 = remoteExtension.version;
        }
      }
      if (pinned === void 0) {
        pinned = localExtension.pinned;
        if (pinned) {
          version2 = localExtension.version;
        }
      }
      if (preRelease === void 0) {
        preRelease = localExtension.preRelease;
      }
      return {
        ...preferred,
        installed: localExtension.installed || remoteExtension.installed,
        pinned,
        preRelease,
        version: version2 ?? (remoteExtension.version && (!localExtension.installed || gt(remoteExtension.version, localExtension.version)) ? remoteExtension.version : localExtension.version),
        state: mergeExtensionState(localExtension, remoteExtension, lastSyncExtensionsMap?.get(key2))
      };
    };
    for (const key2 of baseToRemote.removed.values()) {
      const localExtension = localExtensionsMap.get(key2);
      if (!localExtension) {
        continue;
      }
      const baseExtension = $Kg(lastSyncExtensionsMap?.get(key2));
      const wasAnInstalledExtensionDuringLastSync = lastSyncBuiltinExtensionsSet && !lastSyncBuiltinExtensionsSet.has(key2) && baseExtension.installed;
      if (localExtension.installed && wasAnInstalledExtensionDuringLastSync) {
        removed.push(localExtension.identifier);
      } else {
        newRemoteExtensionsMap.set(key2, localExtension);
      }
    }
    for (const key2 of baseToRemote.added.values()) {
      const remoteExtension = $Kg(remoteExtensionsMap.get(key2));
      const localExtension = localExtensionsMap.get(key2);
      if (localExtension) {
        if (localToRemote.updated.has(key2)) {
          const mergedExtension = merge2(key2, localExtension, remoteExtension, remoteExtension);
          if (!areSame2(localExtension, remoteExtension, false, false)) {
            updated.push(massageOutgoingExtension(mergedExtension, key2));
          }
          newRemoteExtensionsMap.set(key2, mergedExtension);
        }
      } else {
        if (remoteExtension.installed) {
          added.push(massageOutgoingExtension(remoteExtension, key2));
        }
      }
    }
    for (const key2 of baseToRemote.updated.values()) {
      const remoteExtension = $Kg(remoteExtensionsMap.get(key2));
      const baseExtension = $Kg(lastSyncExtensionsMap?.get(key2));
      const localExtension = localExtensionsMap.get(key2);
      if (localExtension) {
        const wasAnInstalledExtensionDuringLastSync = lastSyncBuiltinExtensionsSet && !lastSyncBuiltinExtensionsSet.has(key2) && baseExtension.installed;
        if (wasAnInstalledExtensionDuringLastSync && localExtension.installed && !remoteExtension.installed) {
          removed.push(localExtension.identifier);
        } else {
          const mergedExtension = merge2(key2, localExtension, remoteExtension, remoteExtension);
          updated.push(massageOutgoingExtension(mergedExtension, key2));
          newRemoteExtensionsMap.set(key2, mergedExtension);
        }
      } else if (remoteExtension.installed) {
        added.push(massageOutgoingExtension(remoteExtension, key2));
      }
    }
    for (const key2 of baseToLocal.added.values()) {
      if (baseToRemote.added.has(key2)) {
        continue;
      }
      newRemoteExtensionsMap.set(key2, $Kg(localExtensionsMap.get(key2)));
    }
    for (const key2 of baseToLocal.updated.values()) {
      if (baseToRemote.removed.has(key2)) {
        continue;
      }
      if (baseToRemote.updated.has(key2)) {
        continue;
      }
      const localExtension = $Kg(localExtensionsMap.get(key2));
      const remoteExtension = $Kg(remoteExtensionsMap.get(key2));
      newRemoteExtensionsMap.set(key2, merge2(key2, localExtension, remoteExtension, localExtension));
    }
    for (const key2 of baseToLocal.removed.values()) {
      if (baseToRemote.updated.has(key2)) {
        continue;
      }
      if (baseToRemote.removed.has(key2)) {
        continue;
      }
      if (skippedExtensionsMap.has(key2)) {
        continue;
      }
      if (!$Kg(remoteExtensionsMap.get(key2)).installed) {
        continue;
      }
      if (!lastSyncBuiltinExtensionsSet) {
        continue;
      }
      if (lastSyncBuiltinExtensionsSet.has(key2) || !$Kg(lastSyncExtensionsMap?.get(key2)).installed) {
        continue;
      }
      newRemoteExtensionsMap.delete(key2);
    }
  }
  const remote = [];
  const remoteChanges = compare5(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, key2) => remote.push(massageOutgoingExtension(value, key2)));
  }
  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 compare5(from, to, ignoredExtensions, checkVersionProperty) {
  const fromKeys = from ? [...from.keys()].filter((key2) => !ignoredExtensions.has(key2)) : [];
  const toKeys = [...to.keys()].filter((key2) => !ignoredExtensions.has(key2));
  const added = toKeys.filter((key2) => !fromKeys.includes(key2)).reduce((r2, key2) => {
    r2.add(key2);
    return r2;
  }, /* @__PURE__ */ new Set());
  const removed = fromKeys.filter((key2) => !toKeys.includes(key2)).reduce((r2, key2) => {
    r2.add(key2);
    return r2;
  }, /* @__PURE__ */ new Set());
  const updated = /* @__PURE__ */ new Set();
  for (const key2 of fromKeys) {
    if (removed.has(key2)) {
      continue;
    }
    const fromExtension = from.get(key2);
    const toExtension2 = to.get(key2);
    if (!toExtension2 || !areSame2(fromExtension, toExtension2, checkVersionProperty, true)) {
      updated.add(key2);
    }
  }
  return { added, removed, updated };
}
function areSame2(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 = $Lv(localState);
  const baseToRemote = baseState ? compareExtensionState(baseState, remoteState) : { added: Object.keys(remoteState).reduce((r2, k) => {
    r2.add(k);
    return r2;
  }, /* @__PURE__ */ new Set()), removed: /* @__PURE__ */ new Set(), updated: /* @__PURE__ */ new Set() };
  const baseToLocal = baseState ? compareExtensionState(baseState, localState) : { added: Object.keys(localState).reduce((r2, k) => {
    r2.add(k);
    return r2;
  }, /* @__PURE__ */ new Set()), removed: /* @__PURE__ */ new Set(), updated: /* @__PURE__ */ new Set() };
  for (const key2 of [...baseToRemote.added.values(), ...baseToRemote.updated.values()]) {
    mergedState[key2] = remoteState[key2];
  }
  for (const key2 of baseToRemote.removed.values()) {
    if (!baseToLocal.updated.has(key2)) {
      delete mergedState[key2];
    }
  }
  return mergedState;
}
function compareExtensionState(from, to) {
  const fromKeys = Object.keys(from);
  const toKeys = Object.keys(to);
  const added = toKeys.filter((key2) => !fromKeys.includes(key2)).reduce((r2, key2) => {
    r2.add(key2);
    return r2;
  }, /* @__PURE__ */ new Set());
  const removed = fromKeys.filter((key2) => !toKeys.includes(key2)).reduce((r2, key2) => {
    r2.add(key2);
    return r2;
  }, /* @__PURE__ */ new Set());
  const updated = /* @__PURE__ */ new Set();
  for (const key2 of fromKeys) {
    if (removed.has(key2)) {
      continue;
    }
    const value1 = from[key2];
    const value2 = to[key2];
    if (!$Pv(value1, value2)) {
      updated.add(key2);
    }
  }
  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, key2) {
  const massagedExtension = {
    ...extension,
    identifier: {
      id: extension.identifier.id,
      uuid: key2.startsWith("uuid:") ? key2.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/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) => !$DA(installed.identifier, extension.identifier))) {
          extension.installed = true;
        }
      }
    }
  }
  return extensions;
}
function $wmc(syncData) {
  return JSON.parse(syncData.content);
}
function $xmc(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 $Tf(e1.identifier.id, e2.identifier.id);
  });
  return format2 ? $Tw(extensions, {}) : JSON.stringify(extensions);
}
var $ymc = class $ymc2 extends $LXb {
  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: $aCb, authority: "base" });
    this.yb = this.wb.with({ scheme: $aCb, authority: "local" });
    this.zb = this.wb.with({ scheme: $aCb, authority: "remote" });
    this.Ab = this.wb.with({ scheme: $aCb, authority: "accepted" });
    this.Bb = this.Eb.createInstance($zmc);
    this.B(Event2.any(Event2.filter(this.Cb.onDidInstallExtensions, (e) => e.some(({ local }) => !!local)), Event2.filter(this.Cb.onDidUninstallExtension, (e) => !e.error), Event2.filter(userDataProfileStorageService.onDidChange, (e) => e.valueChanges.some(({ profile: profile2, changes }) => this.syncResource.profile.id === profile2.id && changes.some((change) => change.key === $tA))), 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 } = $vmc(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 } = $vmc(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 = (identifier2) => {
      idsOrUUIDs.add(identifier2.id.toLowerCase());
      if (identifier2.uuid) {
        idsOrUUIDs.add(identifier2.uuid);
      }
    };
    preview.forEach(({ identifier: identifier2 }) => addIdentifier(identifier2));
    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 = $vmc(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 = $vmc(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 $xmc(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;
  }
};
$ymc = __decorate([
  __param(2, $Xk),
  __param(3, $km),
  __param(4, $jv),
  __param(5, $VBb),
  __param(6, $WBb),
  __param(7, $sA),
  __param(8, $DYb),
  __param(9, $$Bb),
  __param(10, $kl),
  __param(11, $6Bb),
  __param(12, $zv),
  __param(13, $AM),
  __param(14, $vl),
  __param(15, $$A),
  __param(16, $Pk)
], $ymc);
var $zmc = class $zmc2 {
  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: identifier2, isBuiltin, manifest, preRelease, pinned, isApplicationScoped } = extension;
        const syncExntesion = { identifier: identifier2, preRelease, version: manifest.version, pinned: !!pinned };
        if (isApplicationScoped && !$8z(manifest)) {
          syncExntesion.isApplicationScoped = isApplicationScoped;
        }
        if (disabledExtensions.some((disabledExtension) => $DA(disabledExtension, identifier2))) {
          syncExntesion.disabled = true;
        }
        if (!isBuiltin) {
          syncExntesion.installed = true;
        }
        try {
          const keys = extensionStorageService.getKeysForSync({ id: identifier2.id, version: manifest.version });
          if (keys) {
            const extensionStorageState = extensionStorageService.getExtensionState(extension, true) || {};
            syncExntesion.state = Object.keys(extensionStorageState).reduce((state, key2) => {
              if (keys.includes(key2)) {
                state[key2] = extensionStorageState[key2];
              }
              return state;
            }, {});
          }
        } catch (error) {
          this.g.info(`${$KXb("extensions", profile)}: Error while parsing extension state`, $qb(error));
        }
        return syncExntesion;
      });
    });
    return { localExtensions, ignoredExtensions };
  }
  async updateLocalExtensions(added, removed, updated, skippedExtensions, profile) {
    const syncResourceLogLabel = $KXb("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) => $DA(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) => $DA(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 version2 = e.pinned ? e.version : void 0;
          const extension = (await this.c.getExtensions([{ ...e.identifier, version: version2, preRelease: version2 ? 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) => $DA(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 || version2 && installedExtension.manifest.version !== version2) {
                if (await this.a.canInstall(extension) === true) {
                  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: {
                        [$fA]: true,
                        [$gA]: "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: identifier2, isBuiltin }) => !isBuiltin && removed.some((r2) => $DA(identifier2, r2)));
      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: identifier2, local, error, source } of results) {
      const gallery = source;
      if (local) {
        this.g.info(`${syncResourceLogLabel}: Installed extension.`, identifier2.id, gallery.version);
        removeFromSkipped.push(identifier2);
      } else {
        const e = syncExtensionsToInstall.get(identifier2.id.toLowerCase());
        if (e) {
          addToSkipped.push(e);
          this.g.info(`${syncResourceLogLabel}: Skipped synchronizing extension`, gallery.displayName || gallery.identifier.id);
        }
        if (error instanceof $rA && [
          "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) => $DA(e, skippedExtension.identifier))) {
        newSkippedExtensions.push(skippedExtension);
      }
    }
    for (const skippedExtension of addToSkipped) {
      if (!newSkippedExtensions.some((e) => $DA(e.identifier, skippedExtension.identifier))) {
        newSkippedExtensions.push(skippedExtension);
      }
    }
    return newSkippedExtensions;
  }
  h(state, extension, version2, extensionStorageService) {
    const extensionState = extensionStorageService.getExtensionState(extension, true) || {};
    const keys = version2 ? extensionStorageService.getKeysForSync({ id: extension.identifier.id, version: version2 }) : void 0;
    if (keys) {
      keys.forEach((key2) => {
        extensionState[key2] = state[key2];
      });
    } else {
      Object.keys(state).forEach((key2) => extensionState[key2] = state[key2]);
    }
    extensionStorageService.setExtensionState(extension, extensionState, true);
  }
  async j(profile, fn) {
    return this.b.withProfileScopedStorageService(profile, async (storageService) => {
      const disposables = new $2c();
      const instantiationService = disposables.add(this.f.createChild(new $Ok([$jv, storageService])));
      const extensionEnablementService = disposables.add(instantiationService.createInstance($cWb));
      const extensionStorageService = disposables.add(instantiationService.createInstance($BM));
      try {
        return await fn(extensionEnablementService, extensionStorageService);
      } finally {
        disposables.dispose();
      }
    });
  }
};
$zmc = __decorate([
  __param(0, $sA),
  __param(1, $$A),
  __param(2, $pA),
  __param(3, $DYb),
  __param(4, $Pk),
  __param(5, $$Bb)
], $zmc);
var $Amc = class $Amc2 extends $OXb {
  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((i2) => $DA(i2.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 };
  }
};
$Amc = __decorate([
  __param(0, $sA),
  __param(1, $DYb),
  __param(2, $km),
  __param(3, $rs),
  __param(4, $Xk),
  __param(5, $wn),
  __param(6, $jv),
  __param(7, $vl)
], $Amc);

// out-build/vs/platform/userDataSync/common/keybindingsMerge.js
function parseKeybindings(content) {
  return $yw(content) || [];
}
async function $Bmc(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((r2, k) => {
    r2.add(k);
    return r2;
  }, /* @__PURE__ */ new Set()), removed: /* @__PURE__ */ new Set(), updated: /* @__PURE__ */ new Set() };
  const baseToRemoteByCommand = baseByCommand ? compareByCommand(baseByCommand, remoteByCommand, normalizedKeys) : { added: [...remoteByCommand.keys()].reduce((r2, k) => {
    r2.add(k);
    return r2;
  }, /* @__PURE__ */ new Set()), removed: /* @__PURE__ */ new Set(), updated: /* @__PURE__ */ new Set() };
  const commandsMergeResult = computeMergeResult(localToRemoteByCommand, baseToLocalByCommand, baseToRemoteByCommand);
  let mergeContent = localContent;
  for (const command4 of commandsMergeResult.removed.values()) {
    if (commandsMergeResult.conflicts.has(command4)) {
      continue;
    }
    mergeContent = removeKeybindings(mergeContent, command4, formattingOptions);
  }
  for (const command4 of commandsMergeResult.added.values()) {
    if (commandsMergeResult.conflicts.has(command4)) {
      continue;
    }
    const keybindings = remoteByCommand.get(command4);
    if (keybindings.some((keybinding) => keybinding.command !== `-${command4}` && keybindingsMergeResult.conflicts.has(normalizedKeys[keybinding.key]))) {
      commandsMergeResult.conflicts.add(command4);
      continue;
    }
    mergeContent = addKeybindings(mergeContent, keybindings, formattingOptions);
  }
  for (const command4 of commandsMergeResult.updated.values()) {
    if (commandsMergeResult.conflicts.has(command4)) {
      continue;
    }
    const keybindings = remoteByCommand.get(command4);
    if (keybindings.some((keybinding) => keybinding.command !== `-${command4}` && keybindingsMergeResult.conflicts.has(normalizedKeys[keybinding.key]))) {
      commandsMergeResult.conflicts.add(command4);
      continue;
    }
    mergeContent = updateKeybindings(mergeContent, command4, 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 key2 of baseToLocal.removed.values()) {
    if (baseToRemote.updated.has(key2)) {
      conflicts.add(key2);
    }
  }
  for (const key2 of baseToRemote.removed.values()) {
    if (conflicts.has(key2)) {
      continue;
    }
    if (baseToLocal.updated.has(key2)) {
      conflicts.add(key2);
    } else {
      removed.add(key2);
    }
  }
  for (const key2 of baseToLocal.added.values()) {
    if (conflicts.has(key2)) {
      continue;
    }
    if (baseToRemote.added.has(key2)) {
      if (localToRemote.updated.has(key2)) {
        conflicts.add(key2);
      }
    }
  }
  for (const key2 of baseToRemote.added.values()) {
    if (conflicts.has(key2)) {
      continue;
    }
    if (baseToLocal.added.has(key2)) {
      if (localToRemote.updated.has(key2)) {
        conflicts.add(key2);
      }
    } else {
      added.add(key2);
    }
  }
  for (const key2 of baseToLocal.updated.values()) {
    if (conflicts.has(key2)) {
      continue;
    }
    if (baseToRemote.updated.has(key2)) {
      if (localToRemote.updated.has(key2)) {
        conflicts.add(key2);
      }
    }
  }
  for (const key2 of baseToRemote.updated.values()) {
    if (conflicts.has(key2)) {
      continue;
    }
    if (baseToLocal.updated.has(key2)) {
      if (localToRemote.updated.has(key2)) {
        conflicts.add(key2);
      }
    } else {
      updated.add(key2);
    }
  }
  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((r2, k) => {
    r2.add(k);
    return r2;
  }, /* @__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((r2, k) => {
    r2.add(k);
    return r2;
  }, /* @__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 key2 = keys[keybinding.key];
    let value = map.get(key2);
    if (!value) {
      value = [];
      map.set(key2, value);
    }
    value.push(keybinding);
  }
  return map;
}
function byCommand(keybindings) {
  const map = /* @__PURE__ */ new Map();
  for (const keybinding of keybindings) {
    const command4 = keybinding.command[0] === "-" ? keybinding.command.substring(1) : keybinding.command;
    let value = map.get(command4);
    if (!value) {
      value = [];
      map.set(command4, value);
    }
    value.push(keybinding);
  }
  return map;
}
function compareByKeybinding(from, to) {
  const fromKeys = [...from.keys()];
  const toKeys = [...to.keys()];
  const added = toKeys.filter((key2) => !fromKeys.includes(key2)).reduce((r2, key2) => {
    r2.add(key2);
    return r2;
  }, /* @__PURE__ */ new Set());
  const removed = fromKeys.filter((key2) => !toKeys.includes(key2)).reduce((r2, key2) => {
    r2.add(key2);
    return r2;
  }, /* @__PURE__ */ new Set());
  const updated = /* @__PURE__ */ new Set();
  for (const key2 of fromKeys) {
    if (removed.has(key2)) {
      continue;
    }
    const value1 = from.get(key2).map((keybinding) => ({ ...keybinding, ...{ key: key2 } }));
    const value2 = to.get(key2).map((keybinding) => ({ ...keybinding, ...{ key: key2 } }));
    if (!$zb(value1, value2, (a, b) => isSameKeybinding(a, b))) {
      updated.add(key2);
    }
  }
  return { added, removed, updated };
}
function compareByCommand(from, to, normalizedKeys) {
  const fromKeys = [...from.keys()];
  const toKeys = [...to.keys()];
  const added = toKeys.filter((key2) => !fromKeys.includes(key2)).reduce((r2, key2) => {
    r2.add(key2);
    return r2;
  }, /* @__PURE__ */ new Set());
  const removed = fromKeys.filter((key2) => !toKeys.includes(key2)).reduce((r2, key2) => {
    r2.add(key2);
    return r2;
  }, /* @__PURE__ */ new Set());
  const updated = /* @__PURE__ */ new Set();
  for (const key2 of fromKeys) {
    if (removed.has(key2)) {
      continue;
    }
    const value1 = from.get(key2).map((keybinding) => ({ ...keybinding, ...{ key: normalizedKeys[keybinding.key] } }));
    const value2 = to.get(key2).map((keybinding) => ({ ...keybinding, ...{ key: normalizedKeys[keybinding.key] } }));
    if (!areSameKeybindingsWithSameCommand(value1, value2)) {
      updated.add(key2);
    }
  }
  return { added, removed, updated };
}
function areSameKeybindingsWithSameCommand(value1, value2) {
  if (!$zb(value1.filter(({ command: command4 }) => command4[0] !== "-"), value2.filter(({ command: command4 }) => command4[0] !== "-"), (a, b) => isSameKeybinding(a, b))) {
    return false;
  }
  if (!$zb(value1.filter(({ command: command4 }) => command4[0] === "-"), value2.filter(({ command: command4 }) => command4[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 = $7m.deserialize(a.when);
  const whenB = $7m.deserialize(b.when);
  if (whenA && !whenB || !whenA && whenB) {
    return false;
  }
  if (whenA && whenB && !whenA.equals(whenB)) {
    return false;
  }
  if (!$Pv(a.args, b.args)) {
    return false;
  }
  return true;
}
function addKeybindings(content, keybindings, formattingOptions) {
  for (const keybinding of keybindings) {
    content = edit2(content, [-1], keybinding, formattingOptions);
  }
  return content;
}
function removeKeybindings(content, command4, formattingOptions) {
  const keybindings = parseKeybindings(content);
  for (let index = keybindings.length - 1; index >= 0; index--) {
    if (keybindings[index].command === command4 || keybindings[index].command === `-${command4}`) {
      content = edit2(content, [index], void 0, formattingOptions);
    }
  }
  return content;
}
function updateKeybindings(content, command4, keybindings, formattingOptions) {
  const allKeybindings = parseKeybindings(content);
  const location3 = allKeybindings.findIndex((keybinding) => keybinding.command === command4 || keybinding.command === `-${command4}`);
  for (let index = allKeybindings.length - 1; index >= 0; index--) {
    if (allKeybindings[index].command === command4 || allKeybindings[index].command === `-${command4}`) {
      content = edit2(content, [index], void 0, formattingOptions);
    }
  }
  for (let index = keybindings.length - 1; index >= 0; index--) {
    content = edit2(content, [location3], keybindings[index], formattingOptions);
  }
  return content;
}

// out-build/vs/platform/userDataSync/common/keybindingsSync.js
function $Cmc(syncContent, platformSpecific, logService) {
  try {
    const parsed = JSON.parse(syncContent);
    if (!platformSpecific) {
      return $Gg(parsed.all) ? null : parsed.all;
    }
    switch (OS) {
      case 2:
        return $Gg(parsed.mac) ? null : parsed.mac;
      case 3:
        return $Gg(parsed.linux) ? null : parsed.linux;
      case 1:
        return $Gg(parsed.windows) ? null : parsed.windows;
    }
  } catch (e) {
    logService.error(e);
    return null;
  }
}
var $Dmc = class $Dmc2 extends $NXb {
  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: $aCb, authority: "base" });
    this.Gb = this.Eb.with({ scheme: $aCb, authority: "local" });
    this.Hb = this.Eb.with({ scheme: $aCb, authority: "remote" });
    this.Ib = this.Eb.with({ scheme: $aCb, authority: "accepted" });
    this.B(Event2.filter(configurationService.onDidChangeConfiguration, (e) => e.affectsConfiguration("settingsSync.keybindingsPerPlatform"))(() => this.Q()));
  }
  async qb(remoteUserData, lastSyncUserData, isRemoteDataFromCurrentMachine, userDataSyncConfiguration) {
    const remoteContent = remoteUserData.syncData ? $Cmc(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 $1Bb(localize(2492, null), "LocalInvalidContent", this.resource);
      }
      if (!lastSyncContent || lastSyncContent !== localContent2 || lastSyncContent !== remoteContent) {
        this.O.trace(`${this.D}: Merging remote keybindings with local keybindings...`);
        const result = await $Bmc(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 $Bmc(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 $1Bb(localize(2493, 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 = $yw(localFileContent.value.toString());
        if ($Qb(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 $Cmc(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($OBb);
  }
};
$Dmc = __decorate([
  __param(2, $VBb),
  __param(3, $WBb),
  __param(4, $$Bb),
  __param(5, $kl),
  __param(6, $6Bb),
  __param(7, $km),
  __param(8, $Xk),
  __param(9, $jv),
  __param(10, $0Bb),
  __param(11, $zv),
  __param(12, $vl)
], $Dmc);
var $Emc = class $Emc2 extends $OXb {
  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, $Ci.fromString(keybindingsContent));
    await this.n(remoteUserData);
  }
  async i() {
    try {
      const fileContent = await this.k.readFile(this.g.defaultProfile.settingsResource);
      const keybindings = $yw(fileContent.value.toString());
      return !$Qb(keybindings);
    } catch (error) {
      return error.fileOperationResult === 1;
    }
  }
  p(syncContent) {
    try {
      return $Cmc(syncContent, true, this.j);
    } catch (e) {
      this.j.error(e);
      return null;
    }
  }
};
$Emc = __decorate([
  __param(0, $km),
  __param(1, $rs),
  __param(2, $Xk),
  __param(3, $$Bb),
  __param(4, $jv),
  __param(5, $vl)
], $Emc);

// 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 $Fmc(syncContent) {
  const parsed = JSON.parse(syncContent);
  return isSettingsSyncContent(parsed) ? parsed : (
    /* migrate */
    { settings: syncContent }
  );
}
var $Gmc = class $Gmc2 extends $NXb {
  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: $aCb, authority: "base" });
    this.localResource = this.previewResource.with({ scheme: $aCb, authority: "local" });
    this.remoteResource = this.previewResource.with({ scheme: $aCb, authority: "remote" });
    this.acceptedResource = this.previewResource.with({ scheme: $aCb, 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 parser2 = new $TB($NBb, this.O);
    if (remoteSettingsSyncContent?.settings) {
      parser2.parse(remoteSettingsSyncContent.settings);
    }
    return parser2.configurationModel.getValue($NBb) || {};
  }
  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 = $xWb(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 = $xWb(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 ? $wWb(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 ? $wWb(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 ? $wWb(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 ? $wWb(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 = $wWb(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 !$yWb(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 = $wWb(content, "{}", ignoredSettings, formatUtils);
    }
    return content;
  }
  Mb(remoteUserData) {
    return remoteUserData.syncData ? this.Nb(remoteUserData.syncData.content) : null;
  }
  Nb(syncContent) {
    try {
      return $Fmc(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(Event2.any(Event2.filter(this.Fb.onDidInstallExtensions, (e) => e.some(({ local }) => !!local)), Event2.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 $uWb(defaultIgnoredSettings, this.P, content);
  }
  async Tb() {
    const systemExtensions = await this.Fb.getInstalled(
      0
      /* ExtensionType.System */
    );
    return $Rb(systemExtensions.map((e) => $MBb(e.manifest)).flat());
  }
  async Ub() {
    const userExtensions = await this.Fb.getInstalled(1, this.Eb.extensionsResource);
    return $Rb(userExtensions.map((e) => $MBb(e.manifest)).flat());
  }
  Vb(content) {
    if (this.Ab(content, false)) {
      throw new $1Bb(localize(2494, null), "LocalInvalidContent", this.resource);
    }
  }
};
$Gmc = __decorate([
  __param(2, $km),
  __param(3, $Xk),
  __param(4, $jv),
  __param(5, $VBb),
  __param(6, $WBb),
  __param(7, $$Bb),
  __param(8, $0Bb),
  __param(9, $kl),
  __param(10, $6Bb),
  __param(11, $zv),
  __param(12, $sA),
  __param(13, $vl)
], $Gmc);
var $Hmc = class $Hmc2 extends $OXb {
  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, $Ci.fromString(settingsSyncContent.settings));
    await this.n(remoteUserData);
  }
  async i() {
    try {
      const fileContent = await this.k.readFile(this.g.defaultProfile.settingsResource);
      return $yWb(fileContent.value.toString().trim());
    } catch (error) {
      return error.fileOperationResult === 1;
    }
  }
  p(syncContent) {
    try {
      return $Fmc(syncContent);
    } catch (e) {
      this.j.error(e);
    }
    return null;
  }
};
$Hmc = __decorate([
  __param(0, $km),
  __param(1, $rs),
  __param(2, $Xk),
  __param(3, $$Bb),
  __param(4, $jv),
  __param(5, $vl)
], $Hmc);

// out-build/vs/platform/userDataSync/common/snippetsMerge.js
function $Imc(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 key2 of baseToLocal.removed.values()) {
    if (baseToRemote.updated.has(key2)) {
      localAdded[key2] = remote[key2];
    } else {
      remoteRemoved.add(key2);
    }
  }
  for (const key2 of baseToRemote.removed.values()) {
    if (conflicts.has(key2)) {
      continue;
    }
    if (baseToLocal.updated.has(key2)) {
      conflicts.add(key2);
    } else {
      localRemoved.add(key2);
    }
  }
  for (const key2 of baseToLocal.updated.values()) {
    if (conflicts.has(key2)) {
      continue;
    }
    if (baseToRemote.updated.has(key2)) {
      if (localToRemote.updated.has(key2)) {
        conflicts.add(key2);
      }
    } else {
      remoteUpdated[key2] = local[key2];
    }
  }
  for (const key2 of baseToRemote.updated.values()) {
    if (conflicts.has(key2)) {
      continue;
    }
    if (baseToLocal.updated.has(key2)) {
      if (localToRemote.updated.has(key2)) {
        conflicts.add(key2);
      }
    } else if (local[key2] !== void 0) {
      localUpdated[key2] = remote[key2];
    }
  }
  for (const key2 of baseToLocal.added.values()) {
    if (conflicts.has(key2)) {
      continue;
    }
    if (baseToRemote.added.has(key2)) {
      if (localToRemote.updated.has(key2)) {
        conflicts.add(key2);
      }
    } else {
      remoteAdded[key2] = local[key2];
    }
  }
  for (const key2 of baseToRemote.added.values()) {
    if (conflicts.has(key2)) {
      continue;
    }
    if (baseToLocal.added.has(key2)) {
      if (localToRemote.updated.has(key2)) {
        conflicts.add(key2);
      }
    } else {
      localAdded[key2] = remote[key2];
    }
  }
  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((key2) => !fromKeys.includes(key2)).reduce((r2, key2) => {
    r2.add(key2);
    return r2;
  }, /* @__PURE__ */ new Set());
  const removed = fromKeys.filter((key2) => !toKeys.includes(key2)).reduce((r2, key2) => {
    r2.add(key2);
    return r2;
  }, /* @__PURE__ */ new Set());
  const updated = /* @__PURE__ */ new Set();
  for (const key2 of fromKeys) {
    if (removed.has(key2)) {
      continue;
    }
    const fromSnippet = from[key2];
    const toSnippet = to[key2];
    if (fromSnippet !== toSnippet) {
      updated.add(key2);
    }
  }
  return { added, removed, updated };
}
function $Jmc(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 $Kmc(syncData) {
  return JSON.parse(syncData.content);
}
var $Lmc = class $Lmc2 extends $LXb {
  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(Event2.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 = $Imc(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 = $Imc(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: $aCb, 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: $aCb, 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 key2 of Object.keys(snippetsMergeResult.local.added)) {
      const previewResult = {
        content: snippetsMergeResult.local.added[key2],
        hasConflicts: false,
        localChange: 1,
        remoteChange: 0
      };
      resourcePreviews.set(key2, {
        baseResource: this.h.joinPath(this.g, key2).with({ scheme: $aCb, authority: "base" }),
        baseContent: null,
        fileContent: null,
        localResource: this.h.joinPath(this.g, key2).with({ scheme: $aCb, authority: "local" }),
        localContent: null,
        remoteResource: this.h.joinPath(this.g, key2).with({ scheme: $aCb, authority: "remote" }),
        remoteContent: remoteSnippets[key2],
        previewResource: this.h.joinPath(this.g, key2),
        previewResult,
        localChange: previewResult.localChange,
        remoteChange: previewResult.remoteChange,
        acceptedResource: this.h.joinPath(this.g, key2).with({ scheme: $aCb, authority: "accepted" })
      });
    }
    for (const key2 of Object.keys(snippetsMergeResult.local.updated)) {
      const previewResult = {
        content: snippetsMergeResult.local.updated[key2],
        hasConflicts: false,
        localChange: 2,
        remoteChange: 0
      };
      const localContent = localFileContent[key2] ? localFileContent[key2].value.toString() : null;
      resourcePreviews.set(key2, {
        baseResource: this.h.joinPath(this.g, key2).with({ scheme: $aCb, authority: "base" }),
        baseContent: baseSnippets[key2] ?? null,
        localResource: this.h.joinPath(this.g, key2).with({ scheme: $aCb, authority: "local" }),
        fileContent: localFileContent[key2],
        localContent,
        remoteResource: this.h.joinPath(this.g, key2).with({ scheme: $aCb, authority: "remote" }),
        remoteContent: remoteSnippets[key2],
        previewResource: this.h.joinPath(this.g, key2),
        previewResult,
        localChange: previewResult.localChange,
        remoteChange: previewResult.remoteChange,
        acceptedResource: this.h.joinPath(this.g, key2).with({ scheme: $aCb, authority: "accepted" })
      });
    }
    for (const key2 of snippetsMergeResult.local.removed) {
      const previewResult = {
        content: null,
        hasConflicts: false,
        localChange: 3,
        remoteChange: 0
      };
      const localContent = localFileContent[key2] ? localFileContent[key2].value.toString() : null;
      resourcePreviews.set(key2, {
        baseResource: this.h.joinPath(this.g, key2).with({ scheme: $aCb, authority: "base" }),
        baseContent: baseSnippets[key2] ?? null,
        localResource: this.h.joinPath(this.g, key2).with({ scheme: $aCb, authority: "local" }),
        fileContent: localFileContent[key2],
        localContent,
        remoteResource: this.h.joinPath(this.g, key2).with({ scheme: $aCb, authority: "remote" }),
        remoteContent: null,
        previewResource: this.h.joinPath(this.g, key2),
        previewResult,
        localChange: previewResult.localChange,
        remoteChange: previewResult.remoteChange,
        acceptedResource: this.h.joinPath(this.g, key2).with({ scheme: $aCb, authority: "accepted" })
      });
    }
    for (const key2 of Object.keys(snippetsMergeResult.remote.added)) {
      const previewResult = {
        content: snippetsMergeResult.remote.added[key2],
        hasConflicts: false,
        localChange: 0,
        remoteChange: 1
      };
      const localContent = localFileContent[key2] ? localFileContent[key2].value.toString() : null;
      resourcePreviews.set(key2, {
        baseResource: this.h.joinPath(this.g, key2).with({ scheme: $aCb, authority: "base" }),
        baseContent: baseSnippets[key2] ?? null,
        localResource: this.h.joinPath(this.g, key2).with({ scheme: $aCb, authority: "local" }),
        fileContent: localFileContent[key2],
        localContent,
        remoteResource: this.h.joinPath(this.g, key2).with({ scheme: $aCb, authority: "remote" }),
        remoteContent: null,
        previewResource: this.h.joinPath(this.g, key2),
        previewResult,
        localChange: previewResult.localChange,
        remoteChange: previewResult.remoteChange,
        acceptedResource: this.h.joinPath(this.g, key2).with({ scheme: $aCb, authority: "accepted" })
      });
    }
    for (const key2 of Object.keys(snippetsMergeResult.remote.updated)) {
      const previewResult = {
        content: snippetsMergeResult.remote.updated[key2],
        hasConflicts: false,
        localChange: 0,
        remoteChange: 2
      };
      const localContent = localFileContent[key2] ? localFileContent[key2].value.toString() : null;
      resourcePreviews.set(key2, {
        baseResource: this.h.joinPath(this.g, key2).with({ scheme: $aCb, authority: "base" }),
        baseContent: baseSnippets[key2] ?? null,
        localResource: this.h.joinPath(this.g, key2).with({ scheme: $aCb, authority: "local" }),
        fileContent: localFileContent[key2],
        localContent,
        remoteResource: this.h.joinPath(this.g, key2).with({ scheme: $aCb, authority: "remote" }),
        remoteContent: remoteSnippets[key2],
        previewResource: this.h.joinPath(this.g, key2),
        previewResult,
        localChange: previewResult.localChange,
        remoteChange: previewResult.remoteChange,
        acceptedResource: this.h.joinPath(this.g, key2).with({ scheme: $aCb, authority: "accepted" })
      });
    }
    for (const key2 of snippetsMergeResult.remote.removed) {
      const previewResult = {
        content: null,
        hasConflicts: false,
        localChange: 0,
        remoteChange: 3
      };
      resourcePreviews.set(key2, {
        baseResource: this.h.joinPath(this.g, key2).with({ scheme: $aCb, authority: "base" }),
        baseContent: baseSnippets[key2] ?? null,
        localResource: this.h.joinPath(this.g, key2).with({ scheme: $aCb, authority: "local" }),
        fileContent: null,
        localContent: null,
        remoteResource: this.h.joinPath(this.g, key2).with({ scheme: $aCb, authority: "remote" }),
        remoteContent: remoteSnippets[key2],
        previewResource: this.h.joinPath(this.g, key2),
        previewResult,
        localChange: previewResult.localChange,
        remoteChange: previewResult.remoteChange,
        acceptedResource: this.h.joinPath(this.g, key2).with({ scheme: $aCb, authority: "accepted" })
      });
    }
    for (const key2 of snippetsMergeResult.conflicts) {
      const previewResult = {
        content: baseSnippets[key2] ?? null,
        hasConflicts: true,
        localChange: localFileContent[key2] ? 2 : 1,
        remoteChange: remoteSnippets[key2] ? 2 : 1
        /* Change.Added */
      };
      const localContent = localFileContent[key2] ? localFileContent[key2].value.toString() : null;
      resourcePreviews.set(key2, {
        baseResource: this.h.joinPath(this.g, key2).with({ scheme: $aCb, authority: "base" }),
        baseContent: baseSnippets[key2] ?? null,
        localResource: this.h.joinPath(this.g, key2).with({ scheme: $aCb, authority: "local" }),
        fileContent: localFileContent[key2] || null,
        localContent,
        remoteResource: this.h.joinPath(this.g, key2).with({ scheme: $aCb, authority: "remote" }),
        remoteContent: remoteSnippets[key2] || null,
        previewResource: this.h.joinPath(this.g, key2),
        previewResult,
        localChange: previewResult.localChange,
        remoteChange: previewResult.remoteChange,
        acceptedResource: this.h.joinPath(this.g, key2).with({ scheme: $aCb, authority: "accepted" })
      });
    }
    for (const key2 of Object.keys(localFileContent)) {
      if (!resourcePreviews.has(key2)) {
        const previewResult = {
          content: localFileContent[key2] ? localFileContent[key2].value.toString() : null,
          hasConflicts: false,
          localChange: 0,
          remoteChange: 0
          /* Change.None */
        };
        const localContent = localFileContent[key2] ? localFileContent[key2].value.toString() : null;
        resourcePreviews.set(key2, {
          baseResource: this.h.joinPath(this.g, key2).with({ scheme: $aCb, authority: "base" }),
          baseContent: baseSnippets[key2] ?? null,
          localResource: this.h.joinPath(this.g, key2).with({ scheme: $aCb, authority: "local" }),
          fileContent: localFileContent[key2] || null,
          localContent,
          remoteResource: this.h.joinPath(this.g, key2).with({ scheme: $aCb, authority: "remote" }),
          remoteContent: remoteSnippets[key2] || null,
          previewResource: this.h.joinPath(this.g, key2),
          previewResult,
          localChange: previewResult.localChange,
          remoteChange: previewResult.remoteChange,
          acceptedResource: this.h.joinPath(this.g, key2).with({ scheme: $aCb, authority: "accepted" })
        });
      }
    }
    return [...resourcePreviews.values()];
  }
  async resolveContent(uri) {
    if (this.h.isEqualOrParent(uri, this.g.with({ scheme: $aCb, authority: "remote" })) || this.h.isEqualOrParent(uri, this.g.with({ scheme: $aCb, authority: "local" })) || this.h.isEqualOrParent(uri, this.g.with({ scheme: $aCb, authority: "base" })) || this.h.isEqualOrParent(uri, this.g.with({ scheme: $aCb, 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 key2 = remoteResource ? this.h.basename(remoteResource) : this.h.basename(localResource);
        const resource = this.h.joinPath(this.vb, key2);
        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, $Ci.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, $Ci.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 = $Lv(currentSnippets);
    for (const { acceptResult, localResource, remoteResource, remoteChange } of resourcePreviews) {
      if (remoteChange !== 0) {
        const key2 = localResource ? this.h.basename(localResource) : this.h.basename(remoteResource);
        if (remoteChange === 3) {
          delete newSnippets[key2];
        } else {
          newSnippets[key2] = acceptResult.content;
        }
      }
    }
    if (!$Jmc(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 $Kmc(syncData);
  }
  Gb(snippetsFileContents) {
    const snippets = {};
    for (const key2 of Object.keys(snippetsFileContents)) {
      snippets[key2] = snippetsFileContents[key2].value.toString();
    }
    return snippets;
  }
  async Hb() {
    const snippets = {};
    let stat;
    try {
      stat = await this.G.resolve(this.vb);
    } catch (e) {
      if (e instanceof $Fm && 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 key2 = this.h.relativePath(this.vb, resource);
        const content = await this.G.readFile(resource);
        snippets[key2] = content;
      }
    }
    return snippets;
  }
};
$Lmc = __decorate([
  __param(2, $Xk),
  __param(3, $km),
  __param(4, $jv),
  __param(5, $VBb),
  __param(6, $WBb),
  __param(7, $$Bb),
  __param(8, $kl),
  __param(9, $6Bb),
  __param(10, $zv),
  __param(11, $vl)
], $Lmc);
var $Mmc = class $Mmc2 extends $OXb {
  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 key2 of Object.keys(remoteSnippets)) {
      const content = remoteSnippets[key2];
      if (content) {
        const resource = this.d.joinPath(this.g.defaultProfile.snippetsHome, key2);
        await this.k.createFile(resource, $Ci.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;
    }
  }
};
$Mmc = __decorate([
  __param(0, $km),
  __param(1, $rs),
  __param(2, $Xk),
  __param(3, $$Bb),
  __param(4, $jv),
  __param(5, $vl)
], $Mmc);

// out-build/vs/platform/userDataSync/common/tasksSync.js
function $Nmc(syncContent, logService) {
  try {
    const parsed = JSON.parse(syncContent);
    return parsed.tasks ?? null;
  } catch (e) {
    logService.error(e);
    return null;
  }
}
var $Omc = class $Omc2 extends $MXb {
  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: $aCb, authority: "base" });
    this.Cb = this.Ab.with({ scheme: $aCb, authority: "local" });
    this.Db = this.Ab.with({ scheme: $aCb, authority: "remote" });
    this.Eb = this.Ab.with({ scheme: $aCb, authority: "accepted" });
  }
  async qb(remoteUserData, lastSyncUserData, isRemoteDataFromCurrentMachine, userDataSyncConfiguration) {
    const remoteContent = remoteUserData.syncData ? $Nmc(remoteUserData.syncData.content, this.O) : null;
    lastSyncUserData = lastSyncUserData === null && isRemoteDataFromCurrentMachine ? remoteUserData : lastSyncUserData;
    const lastSyncContent = lastSyncUserData?.syncData ? $Nmc(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 ? $Nmc(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(tasks2) {
    return tasks2 ? { tasks: tasks2 } : {};
  }
};
$Omc = __decorate([
  __param(2, $VBb),
  __param(3, $WBb),
  __param(4, $$Bb),
  __param(5, $kl),
  __param(6, $6Bb),
  __param(7, $km),
  __param(8, $Xk),
  __param(9, $jv),
  __param(10, $zv),
  __param(11, $vl)
], $Omc);
var $Pmc = class $Pmc2 extends $OXb {
  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 ? $Nmc(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, $Ci.fromString(tasksContent));
    await this.n(remoteUserData);
  }
  async p() {
    return this.k.exists(this.c);
  }
};
$Pmc = __decorate([
  __param(0, $km),
  __param(1, $rs),
  __param(2, $Xk),
  __param(3, $$Bb),
  __param(4, $jv),
  __param(5, $vl)
], $Pmc);
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/workbench/services/userDataSync/browser/userDataSyncInit.js
var $Qmc = class $Qmc2 {
  constructor(f, g, h3, i2, j, k, l, m, n, o) {
    this.f = f;
    this.g = g;
    this.h = h3;
    this.i = i2;
    this.j = j;
    this.k = k;
    this.l = l;
    this.m = m;
    this.n = n;
    this.o = o;
    this.a = [];
    this.b = new $Uh();
    this.d = null;
    this.q().then((userDataSyncStoreClient) => {
      if (!userDataSyncStoreClient) {
        this.b.open();
      }
    });
  }
  q() {
    if (!this.p) {
      this.p = (async () => {
        try {
          if (!$r) {
            this.n.trace(`Skipping initializing user data in desktop`);
            return;
          }
          if (!this.k.isNew(
            -1
            /* StorageScope.APPLICATION */
          )) {
            this.n.trace(`Skipping initializing user data as application was opened before`);
            return;
          }
          if (!this.k.isNew(
            1
            /* StorageScope.WORKSPACE */
          )) {
            this.n.trace(`Skipping initializing user data as workspace was opened before`);
            return;
          }
          if (this.f.options?.settingsSyncOptions?.authenticationProvider && !this.f.options.settingsSyncOptions.enabled) {
            this.n.trace(`Skipping initializing user data as settings sync is disabled`);
            return;
          }
          let authenticationSession;
          try {
            authenticationSession = await $Y4(this.g, this.l);
          } catch (error) {
            this.n.error(error);
          }
          if (!authenticationSession) {
            this.n.trace(`Skipping initializing user data as authentication session is not set`);
            return;
          }
          await this.s(authenticationSession);
          const userDataSyncStore = this.h.userDataSyncStore;
          if (!userDataSyncStore) {
            this.n.trace(`Skipping initializing user data as sync service is not provided`);
            return;
          }
          const userDataSyncStoreClient = new $FXb(userDataSyncStore.url, this.l, this.m, this.n, this.f, this.i, this.k);
          userDataSyncStoreClient.setAuthToken(authenticationSession.accessToken, authenticationSession.providerId);
          const manifest = await userDataSyncStoreClient.manifest(null);
          if (manifest === null) {
            userDataSyncStoreClient.dispose();
            this.n.trace(`Skipping initializing user data as there is no data`);
            return;
          }
          this.n.info(`Using settings sync service ${userDataSyncStore.url.toString()} for initialization`);
          return userDataSyncStoreClient;
        } catch (error) {
          this.n.error(error);
          return;
        }
      })();
    }
    return this.p;
  }
  async s(authenticationSession) {
    const userDataSyncStore = this.h.userDataSyncStore;
    if (!userDataSyncStore?.canSwitch) {
      return;
    }
    const disposables = new $2c();
    try {
      const userDataSyncStoreClient = disposables.add(new $FXb(userDataSyncStore.url, this.l, this.m, this.n, this.f, this.i, this.k));
      userDataSyncStoreClient.setAuthToken(authenticationSession.accessToken, authenticationSession.providerId);
      this.d = await userDataSyncStoreClient.readResource("globalState", null);
      if (this.d) {
        const userDataSyncStoreType = new $UXb(userDataSyncStoreClient, this.k, this.f, this.i, this.n).getSyncStoreType(this.d);
        if (userDataSyncStoreType) {
          await this.h.switch(userDataSyncStoreType);
          if (!$oh(userDataSyncStore.url, this.h.userDataSyncStore?.url)) {
            this.n.info("Switched settings sync store");
            this.d = null;
          }
        }
      }
    } finally {
      disposables.dispose();
    }
  }
  async whenInitializationFinished() {
    await this.b.wait();
  }
  async requiresInitialization() {
    this.n.trace(`UserDataInitializationService#requiresInitialization`);
    const userDataSyncStoreClient = await this.q();
    return !!userDataSyncStoreClient;
  }
  async initializeRequiredResources() {
    this.n.trace(`UserDataInitializationService#initializeRequiredResources`);
    return this.z([
      "settings",
      "globalState"
      /* SyncResource.GlobalState */
    ]);
  }
  async initializeOtherResources(instantiationService) {
    try {
      this.n.trace(`UserDataInitializationService#initializeOtherResources`);
      await Promise.allSettled([this.z([
        "keybindings",
        "snippets",
        "tasks"
        /* SyncResource.Tasks */
      ]), this.t(instantiationService)]);
    } finally {
      this.b.open();
    }
  }
  async t(instantiationService) {
    try {
      await Promise.all([this.initializeInstalledExtensions(instantiationService), this.w(instantiationService)]);
    } finally {
      this.a.push(
        "extensions"
        /* SyncResource.Extensions */
      );
    }
  }
  async initializeInstalledExtensions(instantiationService) {
    if (!this.u) {
      this.u = (async () => {
        this.n.trace(`UserDataInitializationService#initializeInstalledExtensions`);
        const extensionsPreviewInitializer = await this.y(instantiationService);
        if (extensionsPreviewInitializer) {
          await instantiationService.createInstance(InstalledExtensionsInitializer, extensionsPreviewInitializer).initialize();
        }
      })();
    }
    return this.u;
  }
  async w(instantiationService) {
    if (!this.v) {
      this.v = (async () => {
        this.n.trace(`UserDataInitializationService#initializeNewExtensions`);
        const extensionsPreviewInitializer = await this.y(instantiationService);
        if (extensionsPreviewInitializer) {
          await instantiationService.createInstance(NewExtensionsInitializer, extensionsPreviewInitializer).initialize();
        }
      })();
    }
    return this.v;
  }
  y(instantiationService) {
    if (!this.x) {
      this.x = (async () => {
        const userDataSyncStoreClient = await this.q();
        if (!userDataSyncStoreClient) {
          return null;
        }
        const userData = await userDataSyncStoreClient.readResource("extensions", null);
        return instantiationService.createInstance(ExtensionsPreviewInitializer, userData);
      })();
    }
    return this.x;
  }
  async z(syncResources) {
    const userDataSyncStoreClient = await this.q();
    if (!userDataSyncStoreClient) {
      return;
    }
    await Promises.settled(syncResources.map(async (syncResource) => {
      try {
        if (this.a.includes(syncResource)) {
          this.n.info(`${$pXb(syncResource)} initialized already.`);
          return;
        }
        this.a.push(syncResource);
        this.n.trace(`Initializing ${$pXb(syncResource)}`);
        const initializer = this.A(syncResource);
        const userData = await userDataSyncStoreClient.readResource(syncResource, syncResource === "globalState" ? this.d : null);
        await initializer.initialize(userData);
        this.n.info(`Initialized ${$pXb(syncResource)}`);
      } catch (error) {
        this.n.info(`Error while initializing ${$pXb(syncResource)}`);
        this.n.error(error);
      }
    }));
  }
  A(syncResource) {
    switch (syncResource) {
      case "settings":
        return new $Hmc(this.i, this.j, this.f, this.n, this.k, this.o);
      case "keybindings":
        return new $Emc(this.i, this.j, this.f, this.n, this.k, this.o);
      case "tasks":
        return new $Pmc(this.i, this.j, this.f, this.n, this.k, this.o);
      case "snippets":
        return new $Mmc(this.i, this.j, this.f, this.n, this.k, this.o);
      case "globalState":
        return new $TXb(this.k, this.i, this.j, this.f, this.n, this.o);
    }
    throw new Error(`Cannot create initializer for ${syncResource}`);
  }
};
$Qmc = __decorate([
  __param(0, $M4),
  __param(1, $J4),
  __param(2, $UBb),
  __param(3, $km),
  __param(4, $rs),
  __param(5, $jv),
  __param(6, $Vu),
  __param(7, $9u),
  __param(8, $wn),
  __param(9, $vl)
], $Qmc);
var ExtensionsPreviewInitializer = class ExtensionsPreviewInitializer2 extends $Amc {
  constructor(w, extensionManagementService, ignoredExtensionsManagementService, fileService, userDataProfilesService, environmentService, logService, storageService, uriIdentityService) {
    super(extensionManagementService, ignoredExtensionsManagementService, fileService, userDataProfilesService, environmentService, logService, storageService, uriIdentityService);
    this.w = w;
    this.v = null;
  }
  getPreview() {
    if (!this.s) {
      this.s = super.initialize(this.w).then(() => this.v);
    }
    return this.s;
  }
  initialize() {
    throw new Error("should not be called directly");
  }
  async o(remoteUserData) {
    const remoteExtensions = await this.t(remoteUserData);
    if (!remoteExtensions) {
      this.j.info("Skipping initializing extensions because remote extensions does not exist.");
      return;
    }
    const installedExtensions = await this.p.getInstalled();
    this.v = this.u(remoteExtensions, installedExtensions);
  }
};
ExtensionsPreviewInitializer = __decorate([
  __param(1, $sA),
  __param(2, $DYb),
  __param(3, $km),
  __param(4, $rs),
  __param(5, $Xk),
  __param(6, $$Bb),
  __param(7, $jv),
  __param(8, $vl)
], ExtensionsPreviewInitializer);
var InstalledExtensionsInitializer = class InstalledExtensionsInitializer2 {
  constructor(a, b, d, f) {
    this.a = a;
    this.b = b;
    this.d = d;
    this.f = f;
  }
  async initialize() {
    const preview = await this.a.getPreview();
    if (!preview) {
      return;
    }
    for (const installedExtension of preview.installedExtensions) {
      const syncExtension = preview.remoteExtensions.find(({ identifier: identifier2 }) => $DA(identifier2, installedExtension.identifier));
      if (syncExtension?.state) {
        const extensionState = this.d.getExtensionState(installedExtension, true) || {};
        Object.keys(syncExtension.state).forEach((key2) => extensionState[key2] = syncExtension.state[key2]);
        this.d.setExtensionState(installedExtension, extensionState, true);
      }
    }
    if (preview.disabledExtensions.length) {
      for (const identifier2 of preview.disabledExtensions) {
        this.f.trace(`Disabling extension...`, identifier2.id);
        await this.b.disableExtension(identifier2);
        this.f.info(`Disabling extension`, identifier2.id);
      }
    }
  }
};
InstalledExtensionsInitializer = __decorate([
  __param(1, $vA),
  __param(2, $AM),
  __param(3, $$Bb)
], InstalledExtensionsInitializer);
var NewExtensionsInitializer = class NewExtensionsInitializer2 {
  constructor(a, b, d, f, g, h3) {
    this.a = a;
    this.b = b;
    this.d = d;
    this.f = f;
    this.g = g;
    this.h = h3;
  }
  async initialize() {
    const preview = await this.a.getPreview();
    if (!preview) {
      return;
    }
    const newlyEnabledExtensions = [];
    const targetPlatform = await this.g.getTargetPlatform();
    const galleryExtensions = await this.f.getExtensions(preview.newExtensions, { targetPlatform, compatible: true }, CancellationToken.None);
    for (const galleryExtension of galleryExtensions) {
      try {
        const extensionToSync = preview.remoteExtensions.find(({ identifier: identifier2 }) => $DA(identifier2, galleryExtension.identifier));
        if (!extensionToSync) {
          continue;
        }
        if (extensionToSync.state) {
          this.d.setExtensionState(galleryExtension, extensionToSync.state, true);
        }
        this.h.trace(`Installing extension...`, galleryExtension.identifier.id);
        const local = await this.g.installFromGallery(galleryExtension, {
          isMachineScoped: false,
          /* set isMachineScoped to prevent install and sync dialog in web */
          donotIncludePackAndDependencies: true,
          installGivenVersion: !!extensionToSync.version,
          installPreReleaseVersion: extensionToSync.preRelease
        });
        if (!preview.disabledExtensions.some((identifier2) => $DA(identifier2, galleryExtension.identifier))) {
          newlyEnabledExtensions.push(local);
        }
        this.h.info(`Installed extension.`, galleryExtension.identifier.id);
      } catch (error) {
        this.h.error(error);
      }
    }
    const canEnabledExtensions = newlyEnabledExtensions.filter((e) => this.b.canAddExtension($EN(e)));
    if (!await this.i(canEnabledExtensions)) {
      await new Promise((c, e) => {
        const disposable = this.b.onDidChangeExtensions(async () => {
          try {
            if (await this.i(canEnabledExtensions)) {
              disposable.dispose();
              c();
            }
          } catch (error) {
            e(error);
          }
        });
      });
    }
  }
  async i(extensions) {
    await this.b.whenInstalledExtensionsRegistered();
    const runningExtensions = this.b.extensions;
    return extensions.every((e) => runningExtensions.some((r2) => $DA({ id: r2.identifier.value }, e.identifier)));
  }
};
NewExtensionsInitializer = __decorate([
  __param(1, $wN),
  __param(2, $AM),
  __param(3, $pA),
  __param(4, $sA),
  __param(5, $$Bb)
], NewExtensionsInitializer);

// out-build/vs/workbench/services/remote/browser/browserRemoteResourceHandler.js
var $Rmc = class $Rmc2 extends $3c {
  constructor(fileService, a) {
    super();
    this.a = a;
    this.B(a.onDidReceiveRequest(async (request) => {
      let uri;
      try {
        uri = JSON.parse(decodeURIComponent(request.uri.query));
      } catch {
        return request.respondWith(404, new Uint8Array(), {});
      }
      let content;
      try {
        content = await fileService.readFile(URI.from(uri, true));
      } catch (e) {
        const str = $Ci.fromString(e.message).buffer;
        if (e instanceof $Fm && e.fileOperationResult === 1) {
          return request.respondWith(404, str, {});
        } else {
          return request.respondWith(500, str, {});
        }
      }
      const mime = uri.path && $ZC(uri.path);
      request.respondWith(200, content.value.buffer, mime ? { "content-type": mime } : {});
    }));
  }
  getResourceUriProvider() {
    const baseUri = URI.parse(document.location.href);
    return (uri) => baseUri.with({
      path: this.a.path,
      query: JSON.stringify(uri)
    });
  }
};
$Rmc = __decorate([
  __param(0, $km)
], $Rmc);

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

// out-build/vs/platform/log/common/fileLog.js
var MAX_FILE_SIZE = 5 * $Sm.MB;
var FileLogger = class FileLogger2 extends $Cn {
  constructor(u, level, w, y) {
    super();
    this.u = u;
    this.w = w;
    this.y = y;
    this.s = 1;
    this.t = "";
    this.setLevel(level);
    this.r = new $Th(
      100
      /* buffer saves over a short time */
    );
    this.n = this.z();
  }
  async flush() {
    if (!this.t) {
      return;
    }
    await this.n;
    let content = await this.G();
    if (content.length > MAX_FILE_SIZE) {
      await this.y.writeFile(this.F(), $Ci.fromString(content));
      content = "";
    }
    if (this.t) {
      content += this.t;
      this.t = "";
      await this.y.writeFile(this.u, $Ci.fromString(content));
    }
  }
  async z() {
    try {
      await this.y.createFile(this.u);
    } catch (error) {
      if (error.fileOperationResult !== 3) {
        throw error;
      }
    }
  }
  m(level, message) {
    if (this.w) {
      this.t += message;
    } else {
      this.t += `${this.D()} [${this.H(level)}] ${message}
`;
    }
    this.r.trigger(() => this.flush());
  }
  D() {
    const toTwoDigits = (v) => v < 10 ? `0${v}` : v;
    const toThreeDigits = (v) => v < 10 ? `00${v}` : v < 100 ? `0${v}` : v;
    const currentTime = /* @__PURE__ */ new Date();
    return `${currentTime.getFullYear()}-${toTwoDigits(currentTime.getMonth() + 1)}-${toTwoDigits(currentTime.getDate())} ${toTwoDigits(currentTime.getHours())}:${toTwoDigits(currentTime.getMinutes())}:${toTwoDigits(currentTime.getSeconds())}.${toThreeDigits(currentTime.getMilliseconds())}`;
  }
  F() {
    this.s = this.s > 5 ? 1 : this.s;
    return $vh($uh(this.u), `${$sh(this.u)}_${this.s++}`);
  }
  async G() {
    try {
      const content = await this.y.readFile(this.u);
      return content.value.toString();
    } catch (e) {
      return "";
    }
  }
  H(level) {
    switch (level) {
      case LogLevel.Debug:
        return "debug";
      case LogLevel.Error:
        return "error";
      case LogLevel.Info:
        return "info";
      case LogLevel.Trace:
        return "trace";
      case LogLevel.Warning:
        return "warning";
    }
    return "";
  }
};
FileLogger = __decorate([
  __param(3, $km)
], FileLogger);
var $Smc = class extends $Hn {
  constructor(logLevel, logsHome, r2) {
    super(logLevel, logsHome);
    this.r = r2;
  }
  s(resource, logLevel, options3) {
    const logger2 = new $_B(logLevel);
    $Rm(resource, this.r).then(() => logger2.logger = new FileLogger(resource, logger2.getLevel(), !!options3?.donotUseFormatters, this.r));
    return logger2;
  }
};

// out-build/vs/workbench/services/secrets/browser/secretStorageService.js
var $Tmc = class $Tmc2 extends $K4 {
  constructor(storageService, encryptionService, environmentService, logService) {
    super(true, storageService, encryptionService, logService);
    if (environmentService.options?.secretStorageProvider) {
      this.z = environmentService.options.secretStorageProvider;
      this.C = new $Rh();
    }
  }
  get(key2) {
    if (this.z) {
      return this.C.queue(key2, () => this.z.get(key2));
    }
    return super.get(key2);
  }
  set(key2, value) {
    if (this.z) {
      return this.C.queue(key2, async () => {
        await this.z.set(key2, value);
        this.b.fire(key2);
      });
    }
    return super.set(key2, value);
  }
  delete(key2) {
    if (this.z) {
      return this.C.queue(key2, async () => {
        await this.z.delete(key2);
        this.b.fire(key2);
      });
    }
    return super.delete(key2);
  }
  get type() {
    if (this.z) {
      return this.z.type;
    }
    return super.type;
  }
};
$Tmc = __decorate([
  __param(0, $jv),
  __param(1, $Mu),
  __param(2, $M4),
  __param(3, $wn)
], $Tmc);
$SC(
  $J4,
  $Tmc,
  1
  /* InstantiationType.Delayed */
);

// out-build/vs/workbench/services/encryption/browser/encryptionService.js
var $Umc = class {
  encrypt(value) {
    return Promise.resolve(value);
  }
  decrypt(value) {
    return Promise.resolve(value);
  }
  isEncryptionAvailable() {
    return Promise.resolve(false);
  }
  getKeyStorageProvider() {
    return Promise.resolve(
      "basic_text"
      /* KnownStorageProvider.basicText */
    );
  }
  setUsePlainTextEncryption() {
    return Promise.resolve(void 0);
  }
};
$SC(
  $Mu,
  $Umc,
  1
  /* InstantiationType.Delayed */
);

// out-build/vs/workbench/browser/web.main.js
var $Vmc = class extends $3c {
  constructor(c, f) {
    super();
    this.c = c;
    this.f = f;
    this.a = this.B(new $2c());
    this.b = [];
    this.g();
  }
  g() {
    $Re(!!$tk($Y), $Y);
  }
  async open() {
    const [services] = await Promise.all([this.j(), $lk(getWindow(this.c))]);
    const workbench2 = new $8lc(this.c, void 0, services.serviceCollection, services.logService);
    this.h(workbench2);
    const instantiationService = workbench2.startup();
    this.B(instantiationService.createInstance($Tob));
    services.logService.trace("workbench#open with configuration", $Qv(this.f));
    instantiationService.invokeFunction((accessor) => {
      const telemetryService = accessor.get($zv);
      for (const indexedDbFileSystemProvider of this.b) {
        this.B(indexedDbFileSystemProvider.onReportError((e) => telemetryService.publicLog2("indexedDBFileSystemProviderError", e)));
      }
    });
    return instantiationService.invokeFunction((accessor) => {
      const commandService = accessor.get($sn);
      const lifecycleService = accessor.get($KL);
      const timerService = accessor.get($iQb);
      const openerService = accessor.get($O4);
      const productService = accessor.get($Vu);
      const progressService = accessor.get($TJ);
      const environmentService = accessor.get($M4);
      const instantiationService2 = accessor.get($Pk);
      const remoteExplorerService = accessor.get($8Sb);
      const labelService = accessor.get($ZI);
      const embedderTerminalService = accessor.get($U4);
      const remoteAuthorityResolverService = accessor.get($bC);
      const notificationService = accessor.get($PJ);
      async function showMessage(severity, message, ...items) {
        const choice = new $gi();
        const handle2 = notificationService.prompt(severity, message, items.map((item) => ({
          label: item,
          run: () => choice.complete(item)
        })));
        const disposable = handle2.onDidClose(() => {
          choice.complete(void 0);
          disposable.dispose();
        });
        const result = await choice.p;
        handle2.close();
        return result;
      }
      let logger2 = void 0;
      return {
        commands: {
          executeCommand: (command4, ...args2) => commandService.executeCommand(command4, ...args2)
        },
        env: {
          async getUriScheme() {
            return productService.urlProtocol;
          },
          async retrievePerformanceMarks() {
            await timerService.whenReady();
            return timerService.getPerformanceMarks();
          },
          async openUri(uri) {
            return openerService.open(uri, {});
          }
        },
        logger: {
          log: (level, message) => {
            if (!logger2) {
              logger2 = instantiationService2.createInstance($rmc, "webEmbedder", productService.embedderIdentifier || productService.nameShort, $vh($uh(environmentService.logFile), "webEmbedder.log"));
            }
            logger2.log(level, message);
          }
        },
        window: {
          withProgress: (options3, task) => progressService.withProgress(options3, task),
          createTerminal: async (options3) => embedderTerminalService.createTerminal(options3),
          showInformationMessage: (message, ...items) => showMessage(Severity2.Info, message, ...items)
        },
        workspace: {
          didResolveRemoteAuthority: async () => {
            if (!this.f.remoteAuthority) {
              return;
            }
            await remoteAuthorityResolverService.resolveAuthority(this.f.remoteAuthority);
          },
          openTunnel: async (tunnelOptions) => {
            const tunnel = $Kg(await remoteExplorerService.forward({
              remote: tunnelOptions.remoteAddress,
              local: tunnelOptions.localAddressPort,
              name: tunnelOptions.label,
              source: {
                source: TunnelSource.Extension,
                description: labelService.getHostLabel(Schemas.vscodeRemote, this.f.remoteAuthority)
              },
              elevateIfNeeded: false,
              privacy: tunnelOptions.privacy
            }, {
              label: tunnelOptions.label,
              elevateIfNeeded: void 0,
              onAutoForward: void 0,
              requireLocalPort: void 0,
              protocol: tunnelOptions.protocol === TunnelProtocol.Https ? tunnelOptions.protocol : TunnelProtocol.Http
            }));
            if (typeof tunnel === "string") {
              throw new Error(tunnel);
            }
            return new class extends $DC {
            }({
              port: tunnel.tunnelRemotePort,
              host: tunnel.tunnelRemoteHost
            }, tunnel.localAddress, () => tunnel.dispose());
          }
        },
        shutdown: () => lifecycleService.shutdown()
      };
    });
  }
  h(workbench2) {
    this.B(workbench2.onWillShutdown(() => this.a.clear()));
    this.B(workbench2.onDidShutdown(() => this.dispose()));
  }
  async j() {
    const serviceCollection = new $Ok();
    const workspace2 = this.w();
    const productService = $Ov({ _serviceBrand: void 0, ...product_default }, this.f.productConfiguration);
    serviceCollection.set($Vu, productService);
    const logsPath = URI.file(this.f.userDataPath + "/" + $Tu(/* @__PURE__ */ new Date()).replace(/-|:|\.\d+Z$/g, "")).with({ scheme: "vscode-log" });
    const environmentService = new $N4(workspace2.id, logsPath, this.f, productService);
    serviceCollection.set($M4, environmentService);
    const fileLogger = new $_B();
    const fileService = this.B(new $7B(fileLogger));
    serviceCollection.set($km, fileService);
    const loggerService = new $Smc($Kn(environmentService), logsPath, fileService);
    serviceCollection.set($xn, loggerService);
    const otherLoggers = [new $En(loggerService.getLogLevel())];
    if (environmentService.isExtensionDevelopment && !!environmentService.extensionTestsLocationURI) {
      otherLoggers.push(new $Pob(loggerService.getLogLevel()));
    }
    const logger2 = loggerService.createLogger(environmentService.logFile, { id: $PCb, name: localize(3811, null) });
    const logService = new $WC(logger2, otherLoggers);
    serviceCollection.set($wn, logService);
    fileLogger.logger = logService;
    await this.n(environmentService, fileService, logService, loggerService, logsPath);
    const connectionToken = environmentService.options.connectionToken || $zk($_g);
    const remoteResourceLoader = this.f.remoteResourceProvider ? new $Rmc(fileService, this.f.remoteResourceProvider) : void 0;
    const resourceUriProvider = this.f.resourceUriProvider ?? remoteResourceLoader?.getResourceUriProvider();
    const remoteAuthorityResolverService = new $$lc(!environmentService.expectsResolverExtension, connectionToken, resourceUriProvider, this.f.serverBasePath, productService, logService);
    serviceCollection.set($bC, remoteAuthorityResolverService);
    const signService = new $mmc(productService);
    serviceCollection.set($lz, signService);
    const uriIdentityService = new $VC(fileService);
    serviceCollection.set($vl, uriIdentityService);
    const userDataProfilesService = new $tmc(environmentService, fileService, uriIdentityService, logService);
    serviceCollection.set($rs, userDataProfilesService);
    const currentProfile = await this.u(workspace2, userDataProfilesService, environmentService);
    await userDataProfilesService.setProfileForWorkspace(workspace2, currentProfile);
    const userDataProfileService = new $smc(currentProfile);
    serviceCollection.set($gT, userDataProfileService);
    const remoteSocketFactoryService = new $hC();
    remoteSocketFactoryService.register(0, new $L4(this.f.webSocketFactory));
    serviceCollection.set($gC, remoteSocketFactoryService);
    const remoteAgentService = this.B(new $0lc(remoteSocketFactoryService, userDataProfileService, environmentService, productService, remoteAuthorityResolverService, signService, logService));
    serviceCollection.set($RL, remoteAgentService);
    this.B($IY.register(remoteAgentService, fileService, logService));
    const [configurationService, storageService] = await Promise.all([
      this.t(workspace2, environmentService, userDataProfileService, userDataProfilesService, fileService, remoteAgentService, uriIdentityService, logService).then((service) => {
        serviceCollection.set($Zk, service);
        serviceCollection.set($EK, service);
        return service;
      }),
      this.s(workspace2, logService, userDataProfileService).then((service) => {
        serviceCollection.set($jv, service);
        return service;
      })
    ]);
    const workspaceTrustEnablementService = new $ICb(configurationService, environmentService);
    serviceCollection.set($3M, workspaceTrustEnablementService);
    const workspaceTrustManagementService = new $JCb(configurationService, remoteAuthorityResolverService, storageService, uriIdentityService, environmentService, configurationService, workspaceTrustEnablementService, fileService);
    serviceCollection.set($4M, workspaceTrustManagementService);
    configurationService.updateWorkspaceTrust(workspaceTrustManagementService.isWorkspaceTrusted());
    this.B(workspaceTrustManagementService.onDidChangeTrust(() => configurationService.updateWorkspaceTrust(workspaceTrustManagementService.isWorkspaceTrusted())));
    const requestService = new $qmc(remoteAgentService, configurationService, logService);
    serviceCollection.set($9u, requestService);
    const userDataSyncStoreManagementService = new $EXb(productService, configurationService, storageService);
    serviceCollection.set($UBb, userDataSyncStoreManagementService);
    const encryptionService = new $Umc();
    serviceCollection.set($Mu, encryptionService);
    const secretStorageService = new $Tmc(storageService, encryptionService, environmentService, logService);
    serviceCollection.set($J4, secretStorageService);
    const userDataInitializers = [];
    userDataInitializers.push(new $Qmc(environmentService, secretStorageService, userDataSyncStoreManagementService, fileService, userDataProfilesService, storageService, productService, requestService, logService, uriIdentityService));
    if (environmentService.options.profile) {
      userDataInitializers.push(new $umc(environmentService, fileService, userDataProfileService, storageService, logService, uriIdentityService, requestService));
    }
    const userDataInitializationService = new $0Vb(userDataInitializers);
    serviceCollection.set($9Vb, userDataInitializationService);
    try {
      await Promise.race([
        // Do not block more than 5s
        $Wh(5e3),
        this.m(userDataInitializationService, configurationService)
      ]);
    } catch (error) {
      logService.error(error);
    }
    return { serviceCollection, configurationService, logService };
  }
  async m(userDataInitializationService, configurationService) {
    if (await userDataInitializationService.requiresInitialization()) {
      $S("code/willInitRequiredUserData");
      await userDataInitializationService.initializeRequiredResources();
      await configurationService.reloadLocalUserConfiguration();
      $S("code/didInitRequiredUserData");
    }
  }
  async n(environmentService, fileService, logService, loggerService, logsPath) {
    let indexedDB2;
    const userDataStore = "vscode-userdata-store";
    const logsStore = "vscode-logs-store";
    const handlesStore = "vscode-filehandles-store";
    try {
      indexedDB2 = await $$1.create("vscode-web-db", 3, [userDataStore, logsStore, handlesStore]);
      this.a.add($1c(() => indexedDB2?.close()));
    } catch (error) {
      logService.error("Error while creating IndexedDB", error);
    }
    fileService.registerProvider(logsPath.scheme, new $WWb());
    let userDataProvider;
    if (indexedDB2) {
      userDataProvider = new $pmc(Schemas.vscodeUserData, indexedDB2, userDataStore, true);
      this.b.push(userDataProvider);
      this.r(userDataProvider);
    } else {
      logService.info("Using in-memory user data provider");
      userDataProvider = new $WWb();
    }
    fileService.registerProvider(Schemas.vscodeUserData, userDataProvider);
    if (WebFileSystemAccess.supported($Y)) {
      fileService.registerProvider(Schemas.file, new $t_(indexedDB2, handlesStore, logService));
    }
    fileService.registerProvider(Schemas.tmp, new $WWb());
  }
  r(provider) {
    this.B($hJ(class ResetUserDataAction extends $gJ {
      constructor() {
        super({
          id: "workbench.action.resetUserData",
          title: localize2(3813, "Reset User Data"),
          category: $qn.Developer,
          menu: {
            id: $bJ.CommandPalette
          }
        });
      }
      async run(accessor) {
        const dialogService = accessor.get($Yv);
        const hostService = accessor.get($S4);
        const storageService = accessor.get($jv);
        const logService = accessor.get($wn);
        const result = await dialogService.confirm({
          message: localize(3812, null)
        });
        if (result.confirmed) {
          try {
            await provider?.reset();
            if (storageService instanceof $5hc) {
              await storageService.clear();
            }
          } catch (error) {
            logService.error(error);
            throw error;
          }
        }
        hostService.reload();
      }
    }));
  }
  async s(workspace2, logService, userDataProfileService) {
    const storageService = new $5hc(workspace2, userDataProfileService, logService);
    try {
      await storageService.initialize();
      this.a.add($1c(() => storageService.close()));
      return storageService;
    } catch (error) {
      $gb(error);
      logService.error(error);
      return storageService;
    }
  }
  async t(workspace2, environmentService, userDataProfileService, userDataProfilesService, fileService, remoteAgentService, uriIdentityService, logService) {
    if ($6k(workspace2) && $fl(workspace2.configPath)) {
      try {
        const emptyWorkspace = { folders: [] };
        await fileService.createFile(workspace2.configPath, $Ci.fromString(JSON.stringify(emptyWorkspace, null, "	")), { overwrite: false });
      } catch (error) {
      }
    }
    const configurationCache = new $lmc([Schemas.file, Schemas.vscodeUserData, Schemas.tmp], environmentService, fileService);
    const workspaceService = new $kmc({ remoteAuthority: this.f.remoteAuthority, configurationCache }, environmentService, userDataProfileService, userDataProfilesService, fileService, remoteAgentService, uriIdentityService, logService, new $Rn());
    try {
      await workspaceService.initialize(workspace2);
      return workspaceService;
    } catch (error) {
      $gb(error);
      logService.error(error);
      return workspaceService;
    }
  }
  async u(workspace2, userDataProfilesService, environmentService) {
    const profileName = environmentService.options?.profile?.name ?? environmentService.profile;
    if (profileName) {
      const profile = userDataProfilesService.profiles.find((p) => p.name === profileName);
      if (profile) {
        return profile;
      }
      return userDataProfilesService.createNamedProfile(profileName, void 0, workspace2);
    }
    return userDataProfilesService.getProfileForWorkspace(workspace2) ?? userDataProfilesService.defaultProfile;
  }
  w() {
    let workspace2 = void 0;
    if (this.f.workspaceProvider) {
      workspace2 = this.f.workspaceProvider.workspace;
    }
    if (workspace2 && $ys(workspace2)) {
      return $nmc(workspace2.workspaceUri);
    }
    if (workspace2 && $zs(workspace2)) {
      return $omc(workspace2.folderUri);
    }
    return $4k;
  }
};

// out-build/vs/workbench/services/integrity/common/integrity.js
var $Wmc = $Qk("integrityService");

// out-build/vs/workbench/services/integrity/browser/integrityService.js
var $Xmc = class {
  async isPure() {
    return { isPure: true, proof: [] };
  }
};
$SC(
  $Wmc,
  $Xmc,
  1
  /* InstantiationType.Delayed */
);

// out-build/vs/workbench/services/search/common/searchService.js
var $Ymc = class $Ymc2 extends $3c {
  constructor(n, r2, s, t, u, w, z) {
    super();
    this.n = n;
    this.r = r2;
    this.s = s;
    this.t = t;
    this.u = u;
    this.w = w;
    this.z = z;
    this.a = /* @__PURE__ */ new Map();
    this.b = /* @__PURE__ */ new Map();
    this.f = /* @__PURE__ */ new Map();
    this.g = /* @__PURE__ */ new Map();
    this.h = /* @__PURE__ */ new Map();
    this.j = /* @__PURE__ */ new Map();
    this.m = /* @__PURE__ */ new Set();
  }
  registerSearchResultProvider(scheme, type, provider) {
    let list2;
    let deferredMap;
    if (type === 0) {
      list2 = this.a;
      deferredMap = this.g;
    } else if (type === 1) {
      list2 = this.b;
      deferredMap = this.h;
    } else if (type === 2) {
      list2 = this.f;
      deferredMap = this.j;
    } else {
      throw new Error("Unknown SearchProviderType");
    }
    list2.set(scheme, provider);
    if (deferredMap.has(scheme)) {
      deferredMap.get(scheme).complete(provider);
      deferredMap.delete(scheme);
    }
    return $1c(() => {
      list2.delete(scheme);
    });
  }
  async textSearch(query, token, onProgress) {
    const results = this.textSearchSplitSyncAsync(query, token, onProgress);
    const openEditorResults = results.syncResults;
    const otherResults = await results.asyncResults;
    return {
      limitHit: otherResults.limitHit || openEditorResults.limitHit,
      results: [...otherResults.results, ...openEditorResults.results],
      messages: [...otherResults.messages, ...openEditorResults.messages]
    };
  }
  async aiTextSearch(query, token, onProgress) {
    const onProviderProgress = (progress) => {
      if (onProgress) {
        if ($VN(progress)) {
          onProgress(progress);
        } else {
          onProgress(progress);
        }
      }
      if ($WN(progress)) {
        this.t.debug("SearchService#search", progress.message);
      }
    };
    return this.C(query, token, onProviderProgress);
  }
  async getAIName() {
    const provider = this.G(
      3
      /* QueryType.aiText */
    ).get(Schemas.file);
    return await provider?.getAIName();
  }
  textSearchSplitSyncAsync(query, token, onProgress, notebookFilesToIgnore, asyncNotebookFilesToIgnore) {
    const openEditorResults = this.M(query);
    if (onProgress) {
      $Mb([...openEditorResults.results.values()]).filter((e) => !(notebookFilesToIgnore && notebookFilesToIgnore.has(e.resource))).forEach(onProgress);
    }
    const syncResults = {
      results: $Mb([...openEditorResults.results.values()]),
      limitHit: openEditorResults.limitHit ?? false,
      messages: []
    };
    const getAsyncResults = async () => {
      const resolvedAsyncNotebookFilesToIgnore = await asyncNotebookFilesToIgnore ?? new $Fc();
      const onProviderProgress = (progress) => {
        if ($VN(progress)) {
          if (!openEditorResults.results.has(progress.resource) && !resolvedAsyncNotebookFilesToIgnore.has(progress.resource) && onProgress) {
            onProgress(progress);
          }
        } else if (onProgress) {
          onProgress(progress);
        }
        if ($WN(progress)) {
          this.t.debug("SearchService#search", progress.message);
        }
      };
      return await this.C(query, token, onProviderProgress);
    };
    return {
      syncResults,
      asyncResults: getAsyncResults()
    };
  }
  fileSearch(query, token) {
    return this.C(query, token);
  }
  schemeHasFileSearchProvider(scheme) {
    return this.a.has(scheme);
  }
  C(query, token, onProgress) {
    this.t.trace("SearchService#search", JSON.stringify(query));
    const schemesInQuery = this.D(query);
    const providerActivations = [Promise.resolve(null)];
    schemesInQuery.forEach((scheme) => providerActivations.push(this.u.activateByEvent(`onSearch:${scheme}`)));
    providerActivations.push(this.u.activateByEvent("onSearch:file"));
    const providerPromise = (async () => {
      await Promise.all(providerActivations);
      await this.u.whenInstalledExtensionsRegistered();
      if (token && token.isCancellationRequested) {
        return Promise.reject(new $lb());
      }
      const progressCallback = (item) => {
        if (token && token.isCancellationRequested) {
          return;
        }
        onProgress?.(item);
      };
      const exists = await Promise.all(query.folderQueries.map((query2) => this.w.exists(query2.folder)));
      query.folderQueries = query.folderQueries.filter((_, i2) => exists[i2]);
      let completes = await this.I(query, progressCallback, token);
      completes = $Mb(completes);
      if (!completes.length) {
        return {
          limitHit: false,
          results: [],
          messages: []
        };
      }
      return {
        limitHit: completes[0] && completes[0].limitHit,
        stats: completes[0].stats,
        messages: $Mb(completes.flatMap((i2) => i2.messages)).filter($Sb((message) => message.type + message.text + message.trusted)),
        results: completes.flatMap((c) => c.results)
      };
    })();
    return token ? $Jh(providerPromise, token) : providerPromise;
  }
  D(query) {
    const schemes = /* @__PURE__ */ new Set();
    query.folderQueries?.forEach((fq) => schemes.add(fq.folder.scheme));
    query.extraFileResources?.forEach((extraFile) => schemes.add(extraFile.scheme));
    return schemes;
  }
  async F(queryType, scheme) {
    const deferredMap = this.H(queryType);
    if (deferredMap.has(scheme)) {
      return deferredMap.get(scheme).p;
    } else {
      const deferred = new $gi();
      deferredMap.set(scheme, deferred);
      return deferred.p;
    }
  }
  G(type) {
    switch (type) {
      case 1:
        return this.a;
      case 2:
        return this.b;
      case 3:
        return this.f;
      default:
        throw new Error(`Unknown query type: ${type}`);
    }
  }
  H(type) {
    switch (type) {
      case 1:
        return this.g;
      case 2:
        return this.h;
      case 3:
        return this.j;
      default:
        throw new Error(`Unknown query type: ${type}`);
    }
  }
  async I(query, onProviderProgress, token) {
    const e2eSW = $te.create(false);
    const searchPs = [];
    const fqs = this.J(query);
    const someSchemeHasProvider = [...fqs.keys()].some((scheme) => {
      return this.G(query.type).has(scheme);
    });
    if (query.type === 3 && !someSchemeHasProvider) {
      return [];
    }
    await Promise.all([...fqs.keys()].map(async (scheme) => {
      if (query.onlyFileScheme && scheme !== Schemas.file) {
        return;
      }
      const schemeFQs = fqs.get(scheme);
      let provider = this.G(query.type).get(scheme);
      if (!provider) {
        if (someSchemeHasProvider) {
          if (!this.m.has(scheme)) {
            this.t.warn(`No search provider registered for scheme: ${scheme}. Another scheme has a provider, not waiting for ${scheme}`);
            this.m.add(scheme);
          }
          return;
        } else {
          if (!this.m.has(scheme)) {
            this.t.warn(`No search provider registered for scheme: ${scheme}, waiting`);
            this.m.add(scheme);
          }
          provider = await this.F(query.type, scheme);
        }
      }
      const oneSchemeQuery = {
        ...query,
        ...{
          folderQueries: schemeFQs
        }
      };
      const doProviderSearch = () => {
        switch (query.type) {
          case 1:
            return provider.fileSearch(oneSchemeQuery, token);
          case 2:
            return provider.textSearch(oneSchemeQuery, onProviderProgress, token);
          default:
            return provider.textSearch(oneSchemeQuery, onProviderProgress, token);
        }
      };
      searchPs.push(doProviderSearch());
    }));
    return Promise.all(searchPs).then((completes) => {
      const endToEndTime = e2eSW.elapsed();
      this.t.trace(`SearchService#search: ${endToEndTime}ms`);
      completes.forEach((complete) => {
        this.L(query, endToEndTime, complete);
      });
      return completes;
    }, (err) => {
      const endToEndTime = e2eSW.elapsed();
      this.t.trace(`SearchService#search: ${endToEndTime}ms`);
      const searchError = $5N(err);
      this.t.trace(`SearchService#searchError: ${searchError.message}`);
      this.L(query, endToEndTime, void 0, searchError);
      throw searchError;
    });
  }
  J(query) {
    const queries = /* @__PURE__ */ new Map();
    query.folderQueries.forEach((fq) => {
      const schemeFQs = queries.get(fq.folder.scheme) || [];
      schemeFQs.push(fq);
      queries.set(fq.folder.scheme, schemeFQs);
    });
    return queries;
  }
  L(query, endToEndTime, complete, err) {
    const fileSchemeOnly = query.folderQueries.every((fq) => fq.folder.scheme === Schemas.file);
    const otherSchemeOnly = query.folderQueries.every((fq) => fq.folder.scheme !== Schemas.file);
    const scheme = fileSchemeOnly ? Schemas.file : otherSchemeOnly ? "other" : "mixed";
    if (query.type === 1 && complete && complete.stats) {
      const fileSearchStats = complete.stats;
      if (fileSearchStats.fromCache) {
        const cacheStats = fileSearchStats.detailStats;
        this.s.publicLog2("cachedSearchComplete", {
          reason: query._reason,
          resultCount: fileSearchStats.resultCount,
          workspaceFolderCount: query.folderQueries.length,
          endToEndTime,
          sortingTime: fileSearchStats.sortingTime,
          cacheWasResolved: cacheStats.cacheWasResolved,
          cacheLookupTime: cacheStats.cacheLookupTime,
          cacheFilterTime: cacheStats.cacheFilterTime,
          cacheEntryCount: cacheStats.cacheEntryCount,
          scheme
        });
      } else {
        const searchEngineStats = fileSearchStats.detailStats;
        this.s.publicLog2("searchComplete", {
          reason: query._reason,
          resultCount: fileSearchStats.resultCount,
          workspaceFolderCount: query.folderQueries.length,
          endToEndTime,
          sortingTime: fileSearchStats.sortingTime,
          fileWalkTime: searchEngineStats.fileWalkTime,
          directoriesWalked: searchEngineStats.directoriesWalked,
          filesWalked: searchEngineStats.filesWalked,
          cmdTime: searchEngineStats.cmdTime,
          cmdResultCount: searchEngineStats.cmdResultCount,
          scheme
        });
      }
    } else if (query.type === 2) {
      let errorType;
      if (err) {
        errorType = err.code === SearchErrorCode.regexParseError ? "regex" : err.code === SearchErrorCode.unknownEncoding ? "encoding" : err.code === SearchErrorCode.globParseError ? "glob" : err.code === SearchErrorCode.invalidLiteral ? "literal" : err.code === SearchErrorCode.other ? "other" : err.code === SearchErrorCode.canceled ? "canceled" : "unknown";
      }
      this.s.publicLog2("textSearchComplete", {
        reason: query._reason,
        workspaceFolderCount: query.folderQueries.length,
        endToEndTime,
        scheme,
        error: errorType
      });
    }
  }
  M(query) {
    const openEditorResults = new $Ec((uri) => this.z.extUri.getComparisonKey(uri));
    let limitHit = false;
    if (query.type === 2) {
      const canonicalToOriginalResources = new $Ec();
      for (const editorInput of this.r.editors) {
        const canonical = $mL.getCanonicalUri(editorInput, { supportSideBySide: SideBySideEditor.PRIMARY });
        const original = $mL.getOriginalUri(editorInput, { supportSideBySide: SideBySideEditor.PRIMARY });
        if (canonical) {
          canonicalToOriginalResources.set(canonical, original ?? canonical);
        }
      }
      const models = this.n.getModels();
      models.forEach((model) => {
        const resource = model.uri;
        if (!resource) {
          return;
        }
        if (limitHit) {
          return;
        }
        const originalResource = canonicalToOriginalResources.get(resource);
        if (!originalResource) {
          return;
        }
        if (model.getLanguageId() === $QN && !(query.includePattern && query.includePattern["**/*.code-search"])) {
          return;
        }
        if (originalResource.scheme !== Schemas.untitled && !this.w.hasProvider(originalResource)) {
          return;
        }
        if (originalResource.scheme === "git") {
          return;
        }
        if (!this.N(originalResource, query)) {
          return;
        }
        const askMax = ($Dg(query.maxResults) ? query.maxResults : $SN) + 1;
        let matches = model.findMatches(query.contentPattern.pattern, false, !!query.contentPattern.isRegExp, !!query.contentPattern.isCaseSensitive, query.contentPattern.isWordMatch ? query.contentPattern.wordSeparators : null, false, askMax);
        if (matches.length) {
          if (askMax && matches.length >= askMax) {
            limitHit = true;
            matches = matches.slice(0, askMax - 1);
          }
          const fileMatch = new $XN(originalResource);
          openEditorResults.set(originalResource, fileMatch);
          const textSearchResults = $v7b(matches, model, query.previewOptions);
          fileMatch.results = $w7b(textSearchResults, model, query);
        } else {
          openEditorResults.set(originalResource, null);
        }
      });
    }
    return {
      results: openEditorResults,
      limitHit
    };
  }
  N(resource, query) {
    return $3N(query, resource.fsPath);
  }
  async clearCache(cacheKey) {
    const clearPs = Array.from(this.a.values()).map((provider) => provider && provider.clearCache(cacheKey));
    await Promise.all(clearPs);
  }
};
$Ymc = __decorate([
  __param(0, $sG),
  __param(1, $mJ),
  __param(2, $zv),
  __param(3, $wn),
  __param(4, $wN),
  __param(5, $km),
  __param(6, $vl)
], $Ymc);

// out-build/vs/workbench/services/search/common/localFileSearchWorkerTypes.js
var $Zmc = class _$Zmc {
  static {
    this.CHANNEL_NAME = "localFileSearchWorkerHost";
  }
  static getChannel(workerServer) {
    return workerServer.getChannel(_$Zmc.CHANNEL_NAME);
  }
  static setChannel(workerClient, obj) {
    workerClient.setChannel(_$Zmc.CHANNEL_NAME, obj);
  }
};

// out-build/vs/workbench/services/search/browser/searchService.js
var $1mc = class $1mc2 extends $Ymc {
  constructor(modelService, editorService, telemetryService, logService, extensionService, fileService, y, uriIdentityService) {
    super(modelService, editorService, telemetryService, logService, extensionService, fileService, uriIdentityService);
    this.y = y;
    const searchProvider = this.y.createInstance($2mc);
    this.registerSearchResultProvider(Schemas.file, 0, searchProvider);
    this.registerSearchResultProvider(Schemas.file, 1, searchProvider);
  }
};
$1mc = __decorate([
  __param(0, $sG),
  __param(1, $mJ),
  __param(2, $zv),
  __param(3, $wn),
  __param(4, $wN),
  __param(5, $km),
  __param(6, $Pk),
  __param(7, $vl)
], $1mc);
var $2mc = class $2mc2 extends $3c {
  constructor(g, h3) {
    super();
    this.g = g;
    this.h = h3;
    this.b = new $ze();
    this.onDidReceiveTextSearchMatch = this.b.event;
    this.f = 0;
    this.a = null;
  }
  async getAIName() {
    return void 0;
  }
  sendTextSearchMatch(match, queryId) {
    this.b.fire({ match, queryId });
  }
  get j() {
    return this.g.getProvider(Schemas.file);
  }
  async m(queryId) {
    const proxy = this.n().proxy;
    proxy.$cancelQuery(queryId);
  }
  async textSearch(query, onProgress, token) {
    try {
      const queryDisposables = new $2c();
      const proxy = this.n().proxy;
      const results = [];
      let limitHit = false;
      await Promise.all(query.folderQueries.map(async (fq) => {
        const queryId = this.f++;
        queryDisposables.add(token?.onCancellationRequested((e) => this.m(queryId)) || $3c.None);
        const handle2 = await this.j.getHandle(fq.folder);
        if (!handle2 || !WebFileSystemAccess.isFileSystemDirectoryHandle(handle2)) {
          console.error("Could not get directory handle for ", fq);
          return;
        }
        const reviveMatch = (result2) => ({
          resource: URI.revive(result2.resource),
          results: $cu(result2.results)
        });
        queryDisposables.add(this.onDidReceiveTextSearchMatch((e) => {
          if (e.queryId === queryId) {
            onProgress?.(reviveMatch(e.match));
          }
        }));
        const ignorePathCasing = this.h.extUri.ignorePathCasing(fq.folder);
        const folderResults = await proxy.$searchDirectory(handle2, query, fq, ignorePathCasing, queryId);
        for (const folderResult of folderResults.results) {
          results.push($cu(folderResult));
        }
        if (folderResults.limitHit) {
          limitHit = true;
        }
      }));
      queryDisposables.dispose();
      const result = { messages: [], results, limitHit };
      return result;
    } catch (e) {
      console.error("Error performing web worker text search", e);
      return {
        results: [],
        messages: [{
          text: localize(13102, null),
          type: TextSearchCompleteMessageType.Warning
        }]
      };
    }
  }
  async fileSearch(query, token) {
    try {
      const queryDisposables = new $2c();
      let limitHit = false;
      const proxy = this.n().proxy;
      const results = [];
      await Promise.all(query.folderQueries.map(async (fq) => {
        const queryId = this.f++;
        queryDisposables.add(token?.onCancellationRequested((e) => this.m(queryId)) || $3c.None);
        const handle2 = await this.j.getHandle(fq.folder);
        if (!handle2 || !WebFileSystemAccess.isFileSystemDirectoryHandle(handle2)) {
          console.error("Could not get directory handle for ", fq);
          return;
        }
        const caseSensitive = this.h.extUri.ignorePathCasing(fq.folder);
        const folderResults = await proxy.$listDirectory(handle2, query, fq, caseSensitive, queryId);
        for (const folderResult of folderResults.results) {
          results.push({ resource: URI.joinPath(fq.folder, folderResult) });
        }
        if (folderResults.limitHit) {
          limitHit = true;
        }
      }));
      queryDisposables.dispose();
      const result = { messages: [], results, limitHit };
      return result;
    } catch (e) {
      console.error("Error performing web worker file search", e);
      return {
        results: [],
        messages: [{
          text: localize(13103, null),
          type: TextSearchCompleteMessageType.Warning
        }]
      };
    }
  }
  async clearCache(cacheKey) {
    if (this.c?.key === cacheKey) {
      this.c = void 0;
    }
  }
  n() {
    if (!this.a) {
      try {
        this.a = this.B($412("vs/workbench/services/search/worker/localFileSearch", "LocalFileSearchWorker"));
        $Zmc.setChannel(this.a, {
          $sendTextSearchMatch: (match, queryId) => {
            return this.sendTextSearchMatch(match, queryId);
          }
        });
      } catch (err) {
        $X1(err);
        throw err;
      }
    }
    return this.a;
  }
};
__decorate([
  $0t
], $2mc.prototype, "j", null);
$2mc = __decorate([
  __param(0, $km),
  __param(1, $vl)
], $2mc);
$SC(
  $TN,
  $1mc,
  1
  /* InstantiationType.Delayed */
);

// out-build/vs/workbench/services/textfile/common/textFileSaveParticipant.js
var $3mc = class $3mc2 extends $3c {
  constructor(b, c) {
    super();
    this.b = b;
    this.c = c;
    this.a = new $cd();
  }
  addSaveParticipant(participant) {
    const remove = this.a.push(participant);
    return $1c(() => remove());
  }
  async participate(model, context, progress, token) {
    const cts = new $ad(token);
    model.textEditorModel?.pushStackElement();
    progress.report({
      message: localize(13133, null)
    });
    let bubbleCancel = false;
    await this.c.withProgress({
      priority: NotificationPriority.URGENT,
      location: 15,
      cancellable: localize(13134, null),
      delay: model.isDirty() ? 5e3 : 3e3
    }, async (progress2) => {
      for (const saveParticipant of this.a) {
        if (cts.token.isCancellationRequested || !model.textEditorModel) {
          break;
        }
        try {
          const promise = saveParticipant.participate(model, context, progress2, cts.token);
          await $Ih(promise, cts.token);
        } catch (err) {
          if (!$kb(err)) {
            this.b.error(err);
          } else if (!cts.token.isCancellationRequested) {
            cts.cancel();
            bubbleCancel = true;
          }
        }
      }
    }, () => {
      cts.cancel();
    });
    model.textEditorModel?.pushStackElement();
    cts.dispose();
    if (bubbleCancel) {
      throw new $lb();
    }
  }
  dispose() {
    this.a.clear();
    super.dispose();
  }
};
$3mc = __decorate([
  __param(0, $wn),
  __param(1, $TJ)
], $3mc);

// out-build/vs/workbench/services/textfile/common/textFileEditorModelManager.js
var $4mc = class $4mc2 extends $3c {
  get models() {
    return [...this.s.values()];
  }
  constructor(z, C, D, F, G) {
    super();
    this.z = z;
    this.C = C;
    this.D = D;
    this.F = F;
    this.G = G;
    this.a = this.B(new $ze({
      leakWarningThreshold: 500
      /* increased for users with hundreds of inputs opened */
    }));
    this.onDidCreate = this.a.event;
    this.b = this.B(new $ze());
    this.onDidResolve = this.b.event;
    this.c = this.B(new $ze());
    this.onDidRemove = this.c.event;
    this.f = this.B(new $ze());
    this.onDidChangeDirty = this.f.event;
    this.g = this.B(new $ze());
    this.onDidChangeReadonly = this.g.event;
    this.h = this.B(new $ze());
    this.onDidChangeOrphaned = this.h.event;
    this.j = this.B(new $ze());
    this.onDidSaveError = this.j.event;
    this.m = this.B(new $ze());
    this.onDidSave = this.m.event;
    this.n = this.B(new $ze());
    this.onDidRevert = this.n.event;
    this.r = this.B(new $ze());
    this.onDidChangeEncoding = this.r.event;
    this.s = new $Ec();
    this.t = new $Ec();
    this.u = new $Ec();
    this.w = new $Ec();
    this.y = this.B(new $5h());
    this.saveErrorHandler = (() => {
      const notificationService = this.D;
      return {
        onSaveError(error, model) {
          notificationService.error(localize(13132, null, model.name, $1m(error, false)));
        }
      };
    })();
    this.O = /* @__PURE__ */ new Map();
    this.$ = this.B(this.z.createInstance($3mc));
    this.H();
  }
  H() {
    this.B(this.C.onDidFilesChange((e) => this.I(e)));
    this.B(this.C.onDidChangeFileSystemProviderCapabilities((e) => this.J(e)));
    this.B(this.C.onDidChangeFileSystemProviderRegistrations((e) => this.L(e)));
    this.B(this.F.onWillRunWorkingCopyFileOperation((e) => this.P(e)));
    this.B(this.F.onDidFailWorkingCopyFileOperation((e) => this.Q(e)));
    this.B(this.F.onDidRunWorkingCopyFileOperation((e) => this.R(e)));
  }
  I(e) {
    for (const model of this.models) {
      if (model.isDirty()) {
        continue;
      }
      if (e.contains(
        model.resource,
        0,
        1
        /* FileChangeType.ADDED */
      )) {
        this.N(model);
      }
    }
  }
  J(e) {
    this.M(e.scheme);
  }
  L(e) {
    if (!e.added) {
      return;
    }
    this.M(e.scheme);
  }
  M(scheme) {
    for (const model of this.models) {
      if (model.isDirty()) {
        continue;
      }
      if (scheme === model.resource.scheme) {
        this.N(model);
      }
    }
  }
  N(model) {
    const queueSize = this.y.queueSize(model.resource);
    if (queueSize <= 1) {
      this.y.queueFor(model.resource, async () => {
        try {
          await this.U(model);
        } catch (error) {
          $gb(error);
        }
      });
    }
  }
  P(e) {
    if (e.operation === 2 || e.operation === 3) {
      const modelsToRestore = [];
      for (const { source, target } of e.files) {
        if (source) {
          if (this.G.extUri.isEqual(source, target)) {
            continue;
          }
          const sourceModels = [];
          for (const model of this.models) {
            if (this.G.extUri.isEqualOrParent(model.resource, source)) {
              sourceModels.push(model);
            }
          }
          for (const sourceModel of sourceModels) {
            const sourceModelResource = sourceModel.resource;
            let targetModelResource;
            if (this.G.extUri.isEqual(sourceModelResource, source)) {
              targetModelResource = target;
            } else {
              targetModelResource = $vh(target, sourceModelResource.path.substr(source.path.length + 1));
            }
            modelsToRestore.push({
              source: sourceModelResource,
              target: targetModelResource,
              languageId: sourceModel.getLanguageId(),
              encoding: sourceModel.getEncoding(),
              snapshot: sourceModel.isDirty() ? sourceModel.createSnapshot() : void 0
            });
          }
        }
      }
      this.O.set(e.correlationId, modelsToRestore);
    }
  }
  Q(e) {
    if (e.operation === 2 || e.operation === 3) {
      const modelsToRestore = this.O.get(e.correlationId);
      if (modelsToRestore) {
        this.O.delete(e.correlationId);
        modelsToRestore.forEach((model) => {
          if (model.snapshot) {
            this.get(model.source)?.setDirty(true);
          }
        });
      }
    }
  }
  R(e) {
    switch (e.operation) {
      case 0:
        e.waitUntil((async () => {
          for (const { target } of e.files) {
            const model = this.get(target);
            if (model && !model.isDisposed()) {
              await model.revert();
            }
          }
        })());
        break;
      case 2:
      case 3:
        e.waitUntil((async () => {
          const modelsToRestore = this.O.get(e.correlationId);
          if (modelsToRestore) {
            this.O.delete(e.correlationId);
            await Promises.settled(modelsToRestore.map(async (modelToRestore) => {
              const target = this.G.asCanonicalUri(modelToRestore.target);
              const restoredModel = await this.resolve(target, {
                reload: { async: false },
                // enforce a reload
                contents: modelToRestore.snapshot ? $OI(modelToRestore.snapshot) : void 0,
                encoding: modelToRestore.encoding
              });
              if (modelToRestore.languageId && modelToRestore.languageId !== $KF && restoredModel.getLanguageId() === $KF && $th(target) !== $LF) {
                restoredModel.updateTextEditorModel(void 0, modelToRestore.languageId);
              }
            }));
          }
        })());
        break;
    }
  }
  get(resource) {
    return this.s.get(resource);
  }
  S(resource) {
    return this.s.has(resource);
  }
  async U(model) {
    await this.X(model.resource);
    if (model.isDirty() || model.isDisposed() || !this.S(model.resource)) {
      return;
    }
    await this.W(model, { reload: { async: false } });
  }
  async resolve(resource, options3) {
    const pendingResolve = this.X(resource);
    if (pendingResolve) {
      await pendingResolve;
    }
    return this.W(resource, options3);
  }
  async W(resourceOrModel, options3) {
    let model;
    let resource;
    if (URI.isUri(resourceOrModel)) {
      resource = resourceOrModel;
      model = this.get(resource);
    } else {
      resource = resourceOrModel.resource;
      model = resourceOrModel;
    }
    let modelResolve;
    let didCreateModel = false;
    if (model) {
      if (options3?.contents) {
        modelResolve = model.resolve(options3);
      } else if (options3?.reload) {
        if (options3.reload.async) {
          modelResolve = Promise.resolve();
          (async () => {
            try {
              await model.resolve(options3);
            } catch (error) {
              $gb(error);
            }
          })();
        } else {
          modelResolve = model.resolve(options3);
        }
      } else {
        modelResolve = Promise.resolve();
      }
    } else {
      didCreateModel = true;
      const newModel = model = this.z.createInstance($IVb, resource, options3 ? options3.encoding : void 0, options3 ? options3.languageId : void 0);
      modelResolve = model.resolve(options3);
      this.Z(newModel);
    }
    this.w.set(resource, modelResolve);
    this.add(resource, model);
    if (didCreateModel) {
      this.a.fire(model);
      if (model.isDirty()) {
        this.f.fire(model);
      }
    }
    try {
      await modelResolve;
    } catch (error) {
      if (didCreateModel) {
        model.dispose();
      }
      throw error;
    } finally {
      this.w.delete(resource);
    }
    if (options3?.languageId) {
      model.setLanguageId(options3.languageId);
    }
    if (didCreateModel && model.isDirty()) {
      this.f.fire(model);
    }
    return model;
  }
  X(resource) {
    const pendingModelResolve = this.w.get(resource);
    if (!pendingModelResolve) {
      return;
    }
    return this.Y(resource);
  }
  async Y(resource) {
    let currentModelCopyResolve;
    while (this.w.has(resource)) {
      const nextPendingModelResolve = this.w.get(resource);
      if (nextPendingModelResolve === currentModelCopyResolve) {
        return;
      }
      currentModelCopyResolve = nextPendingModelResolve;
      try {
        await nextPendingModelResolve;
      } catch (error) {
      }
    }
  }
  Z(model) {
    const modelListeners = new $2c();
    modelListeners.add(model.onDidResolve((reason) => this.b.fire({ model, reason })));
    modelListeners.add(model.onDidChangeDirty(() => this.f.fire(model)));
    modelListeners.add(model.onDidChangeReadonly(() => this.g.fire(model)));
    modelListeners.add(model.onDidChangeOrphaned(() => this.h.fire(model)));
    modelListeners.add(model.onDidSaveError(() => this.j.fire(model)));
    modelListeners.add(model.onDidSave((e) => this.m.fire({ model, ...e })));
    modelListeners.add(model.onDidRevert(() => this.n.fire(model)));
    modelListeners.add(model.onDidChangeEncoding(() => this.r.fire(model)));
    this.t.set(model.resource, modelListeners);
  }
  add(resource, model) {
    const knownModel = this.s.get(resource);
    if (knownModel === model) {
      return;
    }
    const disposeListener = this.u.get(resource);
    disposeListener?.dispose();
    this.s.set(resource, model);
    this.u.set(resource, model.onWillDispose(() => this.remove(resource)));
  }
  remove(resource) {
    const removed = this.s.delete(resource);
    const disposeListener = this.u.get(resource);
    if (disposeListener) {
      $Xc(disposeListener);
      this.u.delete(resource);
    }
    const modelListener = this.t.get(resource);
    if (modelListener) {
      $Xc(modelListener);
      this.t.delete(resource);
    }
    if (removed) {
      this.c.fire(resource);
    }
  }
  addSaveParticipant(participant) {
    return this.$.addSaveParticipant(participant);
  }
  runSaveParticipants(model, context, progress, token) {
    return this.$.participate(model, context, progress, token);
  }
  //#endregion
  canDispose(model) {
    if (model.isDisposed() || !this.w.has(model.resource) && !model.isDirty()) {
      return true;
    }
    return this.ab(model);
  }
  async ab(model) {
    const pendingResolve = this.X(model.resource);
    if (pendingResolve) {
      await pendingResolve;
      return this.canDispose(model);
    }
    if (model.isDirty()) {
      await Event2.toPromise(model.onDidChangeDirty);
      return this.canDispose(model);
    }
    return true;
  }
  dispose() {
    super.dispose();
    this.s.clear();
    this.w.clear();
    $Xc(this.u.values());
    this.u.clear();
    $Xc(this.t.values());
    this.t.clear();
  }
};
$4mc = __decorate([
  __param(0, $Pk),
  __param(1, $km),
  __param(2, $PJ),
  __param(3, $aK),
  __param(4, $vl)
], $4mc);

// out-build/vs/workbench/services/textfile/browser/textFileService.js
var $5mc_1;
var $5mc = class $5mc2 extends $3c {
  static {
    $5mc_1 = this;
  }
  static {
    this.a = $bL.registerSource("textFileCreate.source", localize(13116, null));
  }
  static {
    this.b = $bL.registerSource("textFileOverwrite.source", localize(13117, null));
  }
  constructor(f, g, h3, j, m, n, r2, s, t, u, w, z, C, D, F, G, H, I) {
    super();
    this.f = f;
    this.g = g;
    this.h = h3;
    this.j = j;
    this.m = m;
    this.n = n;
    this.r = r2;
    this.s = s;
    this.t = t;
    this.u = u;
    this.w = w;
    this.z = z;
    this.C = C;
    this.D = D;
    this.F = F;
    this.G = G;
    this.H = H;
    this.I = I;
    this.files = this.B(this.j.createInstance($4mc));
    this.untitled = this.g;
    this.J();
  }
  //#region decorations
  J() {
    const provider = this.B(new class extends $3c {
      constructor(b) {
        super();
        this.b = b;
        this.label = localize(13118, null);
        this.a = this.B(new $ze());
        this.onDidChange = this.a.event;
        this.c();
      }
      c() {
        this.B(this.b.onDidResolve(({ model }) => {
          if (model.isReadonly() || model.hasState(
            4
            /* TextFileEditorModelState.ORPHAN */
          )) {
            this.a.fire([model.resource]);
          }
        }));
        this.B(this.b.onDidRemove((modelUri) => this.a.fire([modelUri])));
        this.B(this.b.onDidChangeReadonly((model) => this.a.fire([model.resource])));
        this.B(this.b.onDidChangeOrphaned((model) => this.a.fire([model.resource])));
      }
      provideDecorations(uri) {
        const model = this.b.get(uri);
        if (!model || model.isDisposed()) {
          return void 0;
        }
        const isReadonly = model.isReadonly();
        const isOrphaned = model.hasState(
          4
          /* TextFileEditorModelState.ORPHAN */
        );
        if (isReadonly && isOrphaned) {
          return {
            color: $xr,
            letter: $6l.lockSmall,
            strikethrough: true,
            tooltip: localize(13119, null)
          };
        } else if (isReadonly) {
          return {
            letter: $6l.lockSmall,
            tooltip: localize(13120, null)
          };
        } else if (isOrphaned) {
          return {
            color: $xr,
            strikethrough: true,
            tooltip: localize(13121, null)
          };
        }
        return void 0;
      }
    }(this.files));
    this.B(this.I.registerDecorationsProvider(provider));
  }
  get encoding() {
    if (!this.L) {
      this.L = this.B(this.j.createInstance($6mc));
    }
    return this.L;
  }
  async read(resource, options3) {
    const [bufferStream, decoder2] = await this.M(resource, {
      ...options3,
      // 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
    });
    return {
      ...bufferStream,
      encoding: decoder2.detected.encoding || $uJ,
      value: await $ti(decoder2.stream, (strings) => strings.join(""))
    };
  }
  async readStream(resource, options3) {
    const [bufferStream, decoder2] = await this.M(resource, options3);
    return {
      ...bufferStream,
      encoding: decoder2.detected.encoding || $uJ,
      value: await $NI(decoder2.stream)
    };
  }
  async M(resource, options3) {
    const cts = new $ad();
    let bufferStream;
    if (options3?.preferUnbuffered) {
      const content = await this.f.readFile(resource, options3, cts.token);
      bufferStream = {
        ...content,
        value: $Qi(content.value)
      };
    } else {
      bufferStream = await this.f.readFileStream(resource, options3, cts.token);
    }
    try {
      const decoder2 = await this.N(resource, bufferStream.value, options3);
      return [bufferStream, decoder2];
    } catch (error) {
      cts.dispose(true);
      if (error.decodeStreamErrorKind === 1) {
        throw new $dK(localize(13122, null), 0, options3);
      } else {
        throw error;
      }
    }
  }
  async create(operations, undoInfo) {
    const operationsWithContents = await Promise.all(operations.map(async (operation) => {
      const contents = await this.getEncodedReadable(operation.resource, operation.value);
      return {
        resource: operation.resource,
        contents,
        overwrite: operation.options?.overwrite
      };
    }));
    return this.C.create(operationsWithContents, CancellationToken.None, undoInfo);
  }
  async write(resource, value, options3) {
    const readable = await this.getEncodedReadable(resource, value, options3);
    if (options3?.writeElevated && this.H.isSupported(resource)) {
      return this.H.writeFileElevated(resource, readable, options3);
    }
    return this.f.writeFile(resource, readable, options3);
  }
  async getEncodedReadable(resource, value, options3) {
    const { encoding, addBOM } = await this.encoding.getWriteEncoding(resource, options3);
    if (encoding === $uJ && !addBOM) {
      return typeof value === "undefined" ? void 0 : $hK(value);
    }
    value = value || "";
    const snapshot = typeof value === "string" ? $gK(value) : value;
    return $EJ(snapshot, encoding, { addBOM });
  }
  async getDecodedStream(resource, value, options3) {
    return (await this.N(resource, value, options3)).stream;
  }
  N(resource, stream, options3) {
    return $DJ(stream, {
      acceptTextOnly: options3?.acceptTextOnly ?? false,
      guessEncoding: options3?.autoGuessEncoding || this.t.getValue(resource, "files.autoGuessEncoding"),
      candidateGuessEncodings: options3?.candidateGuessEncodings || this.t.getValue(resource, "files.candidateGuessEncodings"),
      overwriteEncoding: async (detectedEncoding) => {
        const { encoding } = await this.encoding.getPreferredReadEncoding(resource, options3, detectedEncoding ?? void 0);
        return encoding;
      }
    });
  }
  //#endregion
  //#region save
  async save(resource, options3) {
    if (resource.scheme === Schemas.untitled) {
      const model = this.untitled.get(resource);
      if (model) {
        let targetUri;
        if (model.hasAssociatedFilePath) {
          targetUri = await this.S(resource);
        } else {
          targetUri = await this.s.pickFileToSave(await this.S(resource), options3?.availableFileSystems);
        }
        if (targetUri) {
          return this.saveAs(resource, targetUri, options3);
        }
      }
    } else {
      const model = this.files.get(resource);
      if (model) {
        return await model.save(options3) ? resource : void 0;
      }
    }
    return void 0;
  }
  async saveAs(source, target, options3) {
    if (!target) {
      target = await this.s.pickFileToSave(await this.S(options3?.suggestedTarget ?? source), options3?.availableFileSystems);
    }
    if (!target) {
      return;
    }
    if (this.u.isReadonly(target)) {
      const confirmed = await this.R(target);
      if (!confirmed) {
        return;
      } else {
        this.u.updateReadonly(target, false);
      }
    }
    if ($oh(source, target)) {
      return this.save(source, {
        ...options3,
        force: true
        /* force to save, even if not dirty (https://github.com/microsoft/vscode/issues/99619) */
      });
    }
    if (this.f.hasProvider(source) && this.D.extUri.isEqual(source, target) && await this.f.exists(source)) {
      await this.C.move([{ file: { source, target } }], CancellationToken.None);
      const success = await this.save(source, options3);
      if (!success) {
        await this.save(target, options3);
      }
      return target;
    }
    return this.O(source, target, options3);
  }
  async O(source, target, options3) {
    let success = false;
    const textFileModel = this.files.get(source);
    if (textFileModel?.isResolved()) {
      success = await this.P(textFileModel, source, target, options3);
    } else if (this.f.hasProvider(source)) {
      await this.f.copy(source, target, true);
      success = true;
    } else {
      const textModel = this.m.getModel(source);
      if (textModel) {
        success = await this.P(textModel, source, target, options3);
      }
    }
    if (!success) {
      return void 0;
    }
    try {
      await this.revert(source);
    } catch (error) {
      this.G.error(error);
    }
    return target;
  }
  async P(sourceModel, source, target, options3) {
    let sourceModelEncoding = void 0;
    const sourceModelWithEncodingSupport = sourceModel;
    if (typeof sourceModelWithEncodingSupport.getEncoding === "function") {
      sourceModelEncoding = sourceModelWithEncodingSupport.getEncoding();
    }
    let targetExists = false;
    let targetModel = this.files.get(target);
    if (targetModel?.isResolved()) {
      targetExists = true;
    } else {
      targetExists = await this.f.exists(target);
      if (!targetExists) {
        await this.create([{ resource: target, value: "" }]);
      }
      try {
        targetModel = await this.files.resolve(target, { encoding: sourceModelEncoding });
      } catch (error) {
        if (targetExists) {
          if (error.textFileOperationResult === 0 || error.fileOperationResult === 7) {
            await this.f.del(target);
            return this.P(sourceModel, source, target, options3);
          }
        }
        throw error;
      }
    }
    let write;
    if (sourceModel instanceof $MJ && sourceModel.hasAssociatedFilePath && targetExists && this.D.extUri.isEqual(target, $Fh(sourceModel.resource, this.n.remoteAuthority, this.z.defaultUriScheme))) {
      write = await this.Q(target);
    } else {
      write = true;
    }
    if (!write) {
      return false;
    }
    let sourceTextModel = void 0;
    if (sourceModel instanceof $xG) {
      if (sourceModel.isResolved()) {
        sourceTextModel = sourceModel.textEditorModel ?? void 0;
      }
    } else {
      sourceTextModel = sourceModel;
    }
    let targetTextModel = void 0;
    if (targetModel.isResolved()) {
      targetTextModel = targetModel.textEditorModel;
    }
    if (sourceTextModel && targetTextModel) {
      targetModel.updatePreferredEncoding(sourceModelEncoding);
      this.m.updateModel(targetTextModel, $OI(sourceTextModel.createSnapshot()));
      const sourceLanguageId = sourceTextModel.getLanguageId();
      const targetLanguageId = targetTextModel.getLanguageId();
      if (sourceLanguageId !== $KF && targetLanguageId === $KF) {
        targetTextModel.setLanguage(sourceLanguageId);
      }
      const sourceTransientProperties = this.w.getTransientModelProperties(sourceTextModel);
      if (sourceTransientProperties) {
        for (const [key2, value] of sourceTransientProperties) {
          this.w.setTransientModelProperty(targetTextModel, key2, value);
        }
      }
    }
    if (!options3?.source) {
      options3 = {
        ...options3,
        source: targetExists ? $5mc_1.b : $5mc_1.a
      };
    }
    return targetModel.save({
      ...options3,
      from: source
    });
  }
  async Q(resource) {
    const { confirmed } = await this.r.confirm({
      type: "warning",
      message: localize(13123, null, $sh(resource)),
      detail: localize(13124, null, $sh(resource), $sh($uh(resource))),
      primaryButton: localize(13125, null)
    });
    return confirmed;
  }
  async R(resource) {
    const { confirmed } = await this.r.confirm({
      type: "warning",
      message: localize(13126, null, $sh(resource)),
      detail: localize(13127, null),
      primaryButton: localize(13128, null)
    });
    return confirmed;
  }
  async S(resource) {
    if (this.f.hasProvider(resource)) {
      return resource;
    }
    const remoteAuthority = this.n.remoteAuthority;
    const defaultFilePath = await this.s.defaultFilePath();
    let suggestedFilename = void 0;
    if (resource.scheme === Schemas.untitled) {
      const model = this.untitled.get(resource);
      if (model) {
        if (model.hasAssociatedFilePath) {
          return $Fh(resource, remoteAuthority, this.z.defaultUriScheme);
        }
        let nameCandidate;
        if (await this.z.hasValidBasename($vh(defaultFilePath, model.name), model.name)) {
          nameCandidate = model.name;
        } else {
          nameCandidate = $sh(resource);
        }
        const languageId = model.getLanguageId();
        if (languageId && languageId !== $KF) {
          suggestedFilename = this.suggestFilename(languageId, nameCandidate);
        } else {
          suggestedFilename = nameCandidate;
        }
      }
    }
    if (!suggestedFilename) {
      suggestedFilename = $sh(resource);
    }
    return $vh(defaultFilePath, suggestedFilename);
  }
  suggestFilename(languageId, untitledName) {
    const languageName = this.F.getLanguageName(languageId);
    if (!languageName) {
      return untitledName;
    }
    const untitledExtension = $sc(untitledName);
    const extensions = this.F.getExtensions(languageId);
    if (extensions.includes(untitledExtension)) {
      return untitledName;
    }
    const primaryExtension = extensions.at(0);
    if (primaryExtension) {
      if (untitledExtension) {
        return `${untitledName.substring(0, untitledName.indexOf(untitledExtension))}${primaryExtension}`;
      }
      return `${untitledName}${primaryExtension}`;
    }
    const filenames = this.F.getFilenames(languageId);
    if (filenames.includes(untitledName)) {
      return untitledName;
    }
    return filenames.at(0) ?? untitledName;
  }
  //#endregion
  //#region revert
  async revert(resource, options3) {
    if (resource.scheme === Schemas.untitled) {
      const model = this.untitled.get(resource);
      if (model) {
        return model.revert(options3);
      }
    } else {
      const model = this.files.get(resource);
      if (model && (model.isDirty() || options3?.force)) {
        return model.revert(options3);
      }
    }
  }
  //#endregion
  //#region dirty
  isDirty(resource) {
    const model = resource.scheme === Schemas.untitled ? this.untitled.get(resource) : this.files.get(resource);
    if (model) {
      return model.isDirty();
    }
    return false;
  }
};
$5mc = $5mc_1 = __decorate([
  __param(0, $km),
  __param(1, $NJ),
  __param(2, $KL),
  __param(3, $Pk),
  __param(4, $sG),
  __param(5, $US),
  __param(6, $Yv),
  __param(7, $1v),
  __param(8, $zG),
  __param(9, $4J),
  __param(10, $U5),
  __param(11, $aT),
  __param(12, $aK),
  __param(13, $vl),
  __param(14, $1E),
  __param(15, $wn),
  __param(16, $8J),
  __param(17, $jsb)
], $5mc);
var $6mc = class $6mc2 extends $3c {
  get b() {
    return this.a;
  }
  set b(value) {
    this.a = value;
  }
  constructor(f, g, h3, j) {
    super();
    this.f = f;
    this.g = g;
    this.h = h3;
    this.j = j;
    this.a = this.n();
    this.m();
  }
  m() {
    this.B(this.h.onDidChangeWorkspaceFolders(() => this.b = this.n()));
  }
  n() {
    const defaultEncodingOverrides = [];
    defaultEncodingOverrides.push({ parent: this.g.userRoamingDataHome, encoding: $uJ });
    defaultEncodingOverrides.push({ extension: $al, encoding: $uJ });
    defaultEncodingOverrides.push({ parent: this.g.untitledWorkspacesHome, encoding: $uJ });
    this.h.getWorkspace().folders.forEach((folder) => {
      defaultEncodingOverrides.push({ parent: $vh(folder.uri, ".vscode"), encoding: $uJ });
    });
    return defaultEncodingOverrides;
  }
  async getWriteEncoding(resource, options3) {
    const { encoding, hasBOM } = await this.getPreferredWriteEncoding(resource, options3 ? options3.encoding : void 0);
    return { encoding, addBOM: hasBOM };
  }
  async getPreferredWriteEncoding(resource, preferredEncoding) {
    const resourceEncoding = await this.r(resource, preferredEncoding);
    return {
      encoding: resourceEncoding,
      hasBOM: resourceEncoding === $wJ || resourceEncoding === $xJ || resourceEncoding === $vJ
      // enforce BOM for certain encodings
    };
  }
  async getPreferredReadEncoding(resource, options3, detectedEncoding) {
    let preferredEncoding;
    if (options3?.encoding) {
      if (detectedEncoding === $vJ && options3.encoding === $uJ) {
        preferredEncoding = $vJ;
      } else {
        preferredEncoding = options3.encoding;
      }
    } else if (typeof detectedEncoding === "string") {
      preferredEncoding = detectedEncoding;
    } else if (this.f.getValue(resource, "files.encoding") === $vJ) {
      preferredEncoding = $uJ;
    }
    const encoding = await this.r(resource, preferredEncoding);
    return {
      encoding,
      hasBOM: encoding === $wJ || encoding === $xJ || encoding === $vJ
      // enforce BOM for certain encodings
    };
  }
  async r(resource, preferredEncoding) {
    let fileEncoding;
    const override = this.s(resource);
    if (override) {
      fileEncoding = override;
    } else if (preferredEncoding) {
      fileEncoding = preferredEncoding;
    } else {
      fileEncoding = this.f.getValue(resource, "files.encoding");
    }
    if (fileEncoding !== $uJ) {
      if (!fileEncoding || !await $FJ(fileEncoding)) {
        fileEncoding = $uJ;
      }
    }
    return fileEncoding;
  }
  s(resource) {
    if (this.b?.length) {
      for (const override of this.b) {
        if (override.parent && this.j.extUri.isEqualOrParent(resource, override.parent)) {
          return override.encoding;
        }
        if (override.extension && $th(resource) === `.${override.extension}`) {
          return override.encoding;
        }
      }
    }
    return void 0;
  }
};
$6mc = __decorate([
  __param(0, $zG),
  __param(1, $US),
  __param(2, $Zk),
  __param(3, $vl)
], $6mc);

// out-build/vs/workbench/services/textfile/browser/browserTextFileService.js
var $7mc = class $7mc2 extends $5mc {
  constructor(fileService, untitledTextEditorService, lifecycleService, instantiationService, modelService, environmentService, dialogService, fileDialogService, textResourceConfigurationService, filesConfigurationService, codeEditorService, pathService, workingCopyFileService, uriIdentityService, languageService, elevatedFileService, logService, decorationsService) {
    super(fileService, untitledTextEditorService, lifecycleService, instantiationService, modelService, environmentService, dialogService, fileDialogService, textResourceConfigurationService, filesConfigurationService, codeEditorService, pathService, workingCopyFileService, uriIdentityService, languageService, logService, elevatedFileService, decorationsService);
    this.y();
  }
  y() {
    this.B(this.h.onBeforeShutdown((event) => event.veto(this.U(), "veto.textFiles")));
  }
  U() {
    if (this.files.models.some((model) => model.hasState(
      2
      /* TextFileEditorModelState.PENDING_SAVE */
    ))) {
      return true;
    }
    return false;
  }
};
$7mc = __decorate([
  __param(0, $km),
  __param(1, $NJ),
  __param(2, $KL),
  __param(3, $Pk),
  __param(4, $sG),
  __param(5, $US),
  __param(6, $Yv),
  __param(7, $1v),
  __param(8, $zG),
  __param(9, $4J),
  __param(10, $U5),
  __param(11, $aT),
  __param(12, $aK),
  __param(13, $vl),
  __param(14, $1E),
  __param(15, $8J),
  __param(16, $wn),
  __param(17, $jsb)
], $7mc);
$SC(
  $cK,
  $7mc,
  0
  /* InstantiationType.Eager */
);

// out-build/vs/workbench/services/keybinding/common/keymapInfo.js
function deserializeMapping(serializedMapping) {
  const mapping2 = serializedMapping;
  const ret = {};
  for (const key2 in mapping2) {
    const result = mapping2[key2];
    if (result.length) {
      const value = result[0];
      const withShift = result[1];
      const withAltGr = result[2];
      const withShiftAltGr = result[3];
      const mask = Number(result[4]);
      const vkey = result.length === 6 ? result[5] : void 0;
      ret[key2] = {
        "value": value,
        "vkey": vkey,
        "withShift": withShift,
        "withAltGr": withAltGr,
        "withShiftAltGr": withShiftAltGr,
        "valueIsDeadKey": (mask & 1) > 0,
        "withShiftIsDeadKey": (mask & 2) > 0,
        "withAltGrIsDeadKey": (mask & 4) > 0,
        "withShiftAltGrIsDeadKey": (mask & 8) > 0
      };
    } else {
      ret[key2] = {
        "value": "",
        "valueIsDeadKey": false,
        "withShift": "",
        "withShiftIsDeadKey": false,
        "withAltGr": "",
        "withAltGrIsDeadKey": false,
        "withShiftAltGr": "",
        "withShiftAltGrIsDeadKey": false
      };
    }
  }
  return ret;
}
var $8mc = class _$8mc {
  constructor(layout, secondaryLayouts, keyboardMapping, isUserKeyboardLayout) {
    this.layout = layout;
    this.secondaryLayouts = secondaryLayouts;
    this.mapping = deserializeMapping(keyboardMapping);
    this.isUserKeyboardLayout = !!isUserKeyboardLayout;
    this.layout.isUserKeyboardLayout = !!isUserKeyboardLayout;
  }
  static createKeyboardLayoutFromDebugInfo(layout, value, isUserKeyboardLayout) {
    const keyboardLayoutInfo = new _$8mc(layout, [], {}, true);
    keyboardLayoutInfo.mapping = value;
    return keyboardLayoutInfo;
  }
  update(other) {
    this.layout = other.layout;
    this.secondaryLayouts = other.secondaryLayouts;
    this.mapping = other.mapping;
    this.isUserKeyboardLayout = other.isUserKeyboardLayout;
    this.layout.isUserKeyboardLayout = other.isUserKeyboardLayout;
  }
  getScore(other) {
    let score2 = 0;
    for (const key2 in other) {
      if ($l && (key2 === "Backslash" || key2 === "KeyQ")) {
        continue;
      }
      if ($n && (key2 === "Backspace" || key2 === "Escape")) {
        continue;
      }
      const currentMapping = this.mapping[key2];
      if (currentMapping === void 0) {
        score2 -= 1;
      }
      const otherMapping = other[key2];
      if (currentMapping && otherMapping && currentMapping.value !== otherMapping.value) {
        score2 -= 1;
      }
    }
    return score2;
  }
  equal(other) {
    if (this.isUserKeyboardLayout !== other.isUserKeyboardLayout) {
      return false;
    }
    if ($Yy(this.layout) !== $Yy(other.layout)) {
      return false;
    }
    return this.fuzzyEqual(other.mapping);
  }
  fuzzyEqual(other) {
    for (const key2 in other) {
      if ($l && (key2 === "Backslash" || key2 === "KeyQ")) {
        continue;
      }
      if (this.mapping[key2] === void 0) {
        return false;
      }
      const currentMapping = this.mapping[key2];
      const otherMapping = other[key2];
      if (currentMapping.value !== otherMapping.value) {
        return false;
      }
    }
    return true;
  }
};

// out-build/vs/platform/keyboardLayout/common/keyboardConfig.js
var DispatchConfig;
(function(DispatchConfig2) {
  DispatchConfig2[DispatchConfig2["Code"] = 0] = "Code";
  DispatchConfig2[DispatchConfig2["KeyCode"] = 1] = "KeyCode";
})(DispatchConfig || (DispatchConfig = {}));
function $9mc(configurationService) {
  const keyboard = configurationService.getValue("keyboard");
  const dispatch = keyboard?.dispatch === "keyCode" ? 1 : 0;
  const mapAltGrToCtrlAlt = Boolean(keyboard?.mapAltGrToCtrlAlt);
  return { dispatch, mapAltGrToCtrlAlt };
}
var configurationRegistry19 = $Wn.as($Ht.Configuration);
var keyboardConfiguration = {
  "id": "keyboard",
  "order": 15,
  "type": "object",
  "title": localize(1958, null),
  "properties": {
    "keyboard.dispatch": {
      scope: 1,
      type: "string",
      enum: ["code", "keyCode"],
      default: "code",
      markdownDescription: localize(1959, null),
      included: OS === 2 || OS === 3
      /* OperatingSystem.Linux */
    },
    "keyboard.mapAltGrToCtrlAlt": {
      scope: 1,
      type: "boolean",
      default: false,
      markdownDescription: localize(1960, null),
      included: OS === 1
      /* OperatingSystem.Windows */
    }
  }
};
configurationRegistry19.registerConfiguration(keyboardConfiguration);

// out-build/vs/platform/keyboardLayout/common/keyboardMapper.js
var $Uy = class {
  constructor(actual) {
    this.a = actual;
    this.b = /* @__PURE__ */ new Map();
  }
  dumpDebugInfo() {
    return this.a.dumpDebugInfo();
  }
  resolveKeyboardEvent(keyboardEvent) {
    return this.a.resolveKeyboardEvent(keyboardEvent);
  }
  resolveKeybinding(keybinding) {
    const hashCode = keybinding.getHashCode();
    const resolved = this.b.get(hashCode);
    if (!resolved) {
      const r2 = this.a.resolveKeybinding(keybinding);
      this.b.set(hashCode, r2);
      return r2;
    }
    return resolved;
  }
};

// out-build/vs/platform/keybinding/common/usLayoutResolvedKeybinding.js
var $0mc = class _$0mc extends $X1b {
  constructor(chords, os) {
    super(os, chords);
  }
  a(keyCode) {
    if (this.c === 2) {
      switch (keyCode) {
        case 15:
          return "\u2190";
        case 16:
          return "\u2191";
        case 17:
          return "\u2192";
        case 18:
          return "\u2193";
      }
    }
    return KeyCodeUtils.toString(keyCode);
  }
  f(chord) {
    if (chord.isDuplicateModifierCase()) {
      return "";
    }
    return this.a(chord.keyCode);
  }
  g(chord) {
    if (chord.isDuplicateModifierCase()) {
      return "";
    }
    return KeyCodeUtils.toString(chord.keyCode);
  }
  h(chord) {
    return KeyCodeUtils.toElectronAccelerator(chord.keyCode);
  }
  l(chord) {
    if (chord.isDuplicateModifierCase()) {
      return "";
    }
    const result = KeyCodeUtils.toUserSettingsUS(chord.keyCode);
    return result ? result.toLowerCase() : result;
  }
  m() {
    return true;
  }
  n(chord) {
    return _$0mc.getDispatchStr(chord);
  }
  static getDispatchStr(chord) {
    if (chord.isModifierKey()) {
      return null;
    }
    let result = "";
    if (chord.ctrlKey) {
      result += "ctrl+";
    }
    if (chord.shiftKey) {
      result += "shift+";
    }
    if (chord.altKey) {
      result += "alt+";
    }
    if (chord.metaKey) {
      result += "meta+";
    }
    result += KeyCodeUtils.toString(chord.keyCode);
    return result;
  }
  o(keybinding) {
    if (keybinding.keyCode === 5 && !keybinding.shiftKey && !keybinding.altKey && !keybinding.metaKey) {
      return "ctrl";
    }
    if (keybinding.keyCode === 4 && !keybinding.ctrlKey && !keybinding.altKey && !keybinding.metaKey) {
      return "shift";
    }
    if (keybinding.keyCode === 6 && !keybinding.ctrlKey && !keybinding.shiftKey && !keybinding.metaKey) {
      return "alt";
    }
    if (keybinding.keyCode === 57 && !keybinding.ctrlKey && !keybinding.shiftKey && !keybinding.altKey) {
      return "meta";
    }
    return null;
  }
  /**
   * *NOTE*: Check return value for `KeyCode.Unknown`.
   */
  static t(scanCode) {
    const immutableKeyCode = $9e[scanCode];
    if (immutableKeyCode !== -1) {
      return immutableKeyCode;
    }
    switch (scanCode) {
      case 10:
        return 31;
      case 11:
        return 32;
      case 12:
        return 33;
      case 13:
        return 34;
      case 14:
        return 35;
      case 15:
        return 36;
      case 16:
        return 37;
      case 17:
        return 38;
      case 18:
        return 39;
      case 19:
        return 40;
      case 20:
        return 41;
      case 21:
        return 42;
      case 22:
        return 43;
      case 23:
        return 44;
      case 24:
        return 45;
      case 25:
        return 46;
      case 26:
        return 47;
      case 27:
        return 48;
      case 28:
        return 49;
      case 29:
        return 50;
      case 30:
        return 51;
      case 31:
        return 52;
      case 32:
        return 53;
      case 33:
        return 54;
      case 34:
        return 55;
      case 35:
        return 56;
      case 36:
        return 22;
      case 37:
        return 23;
      case 38:
        return 24;
      case 39:
        return 25;
      case 40:
        return 26;
      case 41:
        return 27;
      case 42:
        return 28;
      case 43:
        return 29;
      case 44:
        return 30;
      case 45:
        return 21;
      case 51:
        return 88;
      case 52:
        return 86;
      case 53:
        return 92;
      case 54:
        return 94;
      case 55:
        return 93;
      case 56:
        return 0;
      case 57:
        return 85;
      case 58:
        return 95;
      case 59:
        return 91;
      case 60:
        return 87;
      case 61:
        return 89;
      case 62:
        return 90;
      case 106:
        return 97;
    }
    return 0;
  }
  static u(chord) {
    if (!chord) {
      return null;
    }
    if (chord instanceof $bf) {
      return chord;
    }
    const keyCode = this.t(chord.scanCode);
    if (keyCode === 0) {
      return null;
    }
    return new $bf(chord.ctrlKey, chord.shiftKey, chord.altKey, chord.metaKey, keyCode);
  }
  static resolveKeybinding(keybinding, os) {
    const chords = $Qy(keybinding.chords.map((chord) => this.u(chord)));
    if (chords.length > 0) {
      return [new _$0mc(chords, os)];
    }
    return [];
  }
};

// out-build/vs/workbench/services/keybinding/common/fallbackKeyboardMapper.js
var $$mc = class {
  constructor(a, b) {
    this.a = a;
    this.b = b;
  }
  dumpDebugInfo() {
    return "FallbackKeyboardMapper dispatching on keyCode";
  }
  resolveKeyboardEvent(keyboardEvent) {
    const ctrlKey = keyboardEvent.ctrlKey || this.a && keyboardEvent.altGraphKey;
    const altKey = keyboardEvent.altKey || this.a && keyboardEvent.altGraphKey;
    const chord = new $bf(ctrlKey, keyboardEvent.shiftKey, altKey, keyboardEvent.metaKey, keyboardEvent.keyCode);
    const result = this.resolveKeybinding(new $df([chord]));
    return result[0];
  }
  resolveKeybinding(keybinding) {
    return $0mc.resolveKeybinding(keybinding, this.b);
  }
};

// out-build/vs/workbench/services/keybinding/common/macLinuxKeyboardMapper.js
var CHAR_CODE_TO_KEY_CODE = [];
var $_mc = class extends $X1b {
  constructor(mapper, os, chords) {
    super(os, chords);
    this.p = mapper;
  }
  f(chord) {
    return this.p.getUILabelForScanCodeChord(chord);
  }
  g(chord) {
    return this.p.getAriaLabelForScanCodeChord(chord);
  }
  h(chord) {
    return this.p.getElectronAcceleratorLabelForScanCodeChord(chord);
  }
  l(chord) {
    return this.p.getUserSettingsLabelForScanCodeChord(chord);
  }
  m(binding) {
    if (!binding) {
      return true;
    }
    if ($9e[binding.scanCode] !== -1) {
      return true;
    }
    const a = this.p.getAriaLabelForScanCodeChord(binding);
    const b = this.p.getUserSettingsLabelForScanCodeChord(binding);
    if (!a && !b) {
      return true;
    }
    if (!a || !b) {
      return false;
    }
    return a.toLowerCase() === b.toLowerCase();
  }
  n(chord) {
    return this.p.getDispatchStrForScanCodeChord(chord);
  }
  o(chord) {
    if ((chord.scanCode === 157 || chord.scanCode === 161) && !chord.shiftKey && !chord.altKey && !chord.metaKey) {
      return "ctrl";
    }
    if ((chord.scanCode === 159 || chord.scanCode === 163) && !chord.ctrlKey && !chord.shiftKey && !chord.metaKey) {
      return "alt";
    }
    if ((chord.scanCode === 158 || chord.scanCode === 162) && !chord.ctrlKey && !chord.altKey && !chord.metaKey) {
      return "shift";
    }
    if ((chord.scanCode === 160 || chord.scanCode === 164) && !chord.ctrlKey && !chord.shiftKey && !chord.altKey) {
      return "meta";
    }
    return null;
  }
};
var ScanCodeCombo = class {
  constructor(ctrlKey, shiftKey, altKey, scanCode) {
    this.ctrlKey = ctrlKey;
    this.shiftKey = shiftKey;
    this.altKey = altKey;
    this.scanCode = scanCode;
  }
  toString() {
    return `${this.ctrlKey ? "Ctrl+" : ""}${this.shiftKey ? "Shift+" : ""}${this.altKey ? "Alt+" : ""}${$8e.toString(this.scanCode)}`;
  }
  equals(other) {
    return this.ctrlKey === other.ctrlKey && this.shiftKey === other.shiftKey && this.altKey === other.altKey && this.scanCode === other.scanCode;
  }
  c(mapping2) {
    if (!mapping2) {
      return "";
    }
    if (this.ctrlKey && this.shiftKey && this.altKey) {
      return mapping2.withShiftAltGr;
    }
    if (this.ctrlKey && this.altKey) {
      return mapping2.withAltGr;
    }
    if (this.shiftKey) {
      return mapping2.withShift;
    }
    return mapping2.value;
  }
  getProducedChar(mapping2) {
    const charCode = $anc.getCharCode(this.c(mapping2));
    if (charCode === 0) {
      return " --- ";
    }
    if (charCode >= 768 && charCode <= 879) {
      return "U+" + charCode.toString(16);
    }
    return "  " + String.fromCharCode(charCode) + "  ";
  }
};
var KeyCodeCombo = class {
  constructor(ctrlKey, shiftKey, altKey, keyCode) {
    this.ctrlKey = ctrlKey;
    this.shiftKey = shiftKey;
    this.altKey = altKey;
    this.keyCode = keyCode;
  }
  toString() {
    return `${this.ctrlKey ? "Ctrl+" : ""}${this.shiftKey ? "Shift+" : ""}${this.altKey ? "Alt+" : ""}${KeyCodeUtils.toString(this.keyCode)}`;
  }
};
var ScanCodeKeyCodeMapper = class {
  constructor() {
    this.c = [];
    this.d = [];
    this.c = [];
    this.d = [];
  }
  registrationComplete() {
    this.e(
      56
      /* ScanCode.IntlHash */
    );
    this.e(
      106
      /* ScanCode.IntlBackslash */
    );
  }
  e(scanCode) {
    for (let mod = 0; mod < 8; mod++) {
      const encodedKeyCodeCombos = this.c[(scanCode << 3) + mod];
      if (!encodedKeyCodeCombos) {
        continue;
      }
      for (let i2 = 0, len = encodedKeyCodeCombos.length; i2 < len; i2++) {
        const encodedScanCodeCombos = this.d[encodedKeyCodeCombos[i2]];
        if (encodedScanCodeCombos.length === 1) {
          continue;
        }
        for (let j = 0, len2 = encodedScanCodeCombos.length; j < len2; j++) {
          const entry = encodedScanCodeCombos[j];
          const entryScanCode = entry >>> 3;
          if (entryScanCode === scanCode) {
            for (let k = j + 1; k < len2; k++) {
              encodedScanCodeCombos[k - 1] = encodedScanCodeCombos[k];
            }
            encodedScanCodeCombos[len2 - 1] = entry;
          }
        }
      }
    }
  }
  registerIfUnknown(scanCodeCombo, keyCodeCombo) {
    if (keyCodeCombo.keyCode === 0) {
      return;
    }
    const scanCodeComboEncoded = this.f(scanCodeCombo);
    const keyCodeComboEncoded = this.g(keyCodeCombo);
    const keyCodeIsDigit = keyCodeCombo.keyCode >= 21 && keyCodeCombo.keyCode <= 30;
    const keyCodeIsLetter = keyCodeCombo.keyCode >= 31 && keyCodeCombo.keyCode <= 56;
    const existingKeyCodeCombos = this.c[scanCodeComboEncoded];
    if (keyCodeIsDigit || keyCodeIsLetter) {
      if (existingKeyCodeCombos) {
        for (let i2 = 0, len = existingKeyCodeCombos.length; i2 < len; i2++) {
          if (existingKeyCodeCombos[i2] === keyCodeComboEncoded) {
            return;
          }
        }
      }
    } else {
      if (existingKeyCodeCombos && existingKeyCodeCombos.length !== 0) {
        return;
      }
    }
    this.c[scanCodeComboEncoded] = this.c[scanCodeComboEncoded] || [];
    this.c[scanCodeComboEncoded].unshift(keyCodeComboEncoded);
    this.d[keyCodeComboEncoded] = this.d[keyCodeComboEncoded] || [];
    this.d[keyCodeComboEncoded].unshift(scanCodeComboEncoded);
  }
  lookupKeyCodeCombo(keyCodeCombo) {
    const keyCodeComboEncoded = this.g(keyCodeCombo);
    const scanCodeCombosEncoded = this.d[keyCodeComboEncoded];
    if (!scanCodeCombosEncoded || scanCodeCombosEncoded.length === 0) {
      return [];
    }
    const result = [];
    for (let i2 = 0, len = scanCodeCombosEncoded.length; i2 < len; i2++) {
      const scanCodeComboEncoded = scanCodeCombosEncoded[i2];
      const ctrlKey = scanCodeComboEncoded & 1 ? true : false;
      const shiftKey = scanCodeComboEncoded & 2 ? true : false;
      const altKey = scanCodeComboEncoded & 4 ? true : false;
      const scanCode = scanCodeComboEncoded >>> 3;
      result[i2] = new ScanCodeCombo(ctrlKey, shiftKey, altKey, scanCode);
    }
    return result;
  }
  lookupScanCodeCombo(scanCodeCombo) {
    const scanCodeComboEncoded = this.f(scanCodeCombo);
    const keyCodeCombosEncoded = this.c[scanCodeComboEncoded];
    if (!keyCodeCombosEncoded || keyCodeCombosEncoded.length === 0) {
      return [];
    }
    const result = [];
    for (let i2 = 0, len = keyCodeCombosEncoded.length; i2 < len; i2++) {
      const keyCodeComboEncoded = keyCodeCombosEncoded[i2];
      const ctrlKey = keyCodeComboEncoded & 1 ? true : false;
      const shiftKey = keyCodeComboEncoded & 2 ? true : false;
      const altKey = keyCodeComboEncoded & 4 ? true : false;
      const keyCode = keyCodeComboEncoded >>> 3;
      result[i2] = new KeyCodeCombo(ctrlKey, shiftKey, altKey, keyCode);
    }
    return result;
  }
  guessStableKeyCode(scanCode) {
    if (scanCode >= 36 && scanCode <= 45) {
      switch (scanCode) {
        case 36:
          return 22;
        case 37:
          return 23;
        case 38:
          return 24;
        case 39:
          return 25;
        case 40:
          return 26;
        case 41:
          return 27;
        case 42:
          return 28;
        case 43:
          return 29;
        case 44:
          return 30;
        case 45:
          return 21;
      }
    }
    const keyCodeCombos1 = this.lookupScanCodeCombo(new ScanCodeCombo(false, false, false, scanCode));
    const keyCodeCombos2 = this.lookupScanCodeCombo(new ScanCodeCombo(false, true, false, scanCode));
    if (keyCodeCombos1.length === 1 && keyCodeCombos2.length === 1) {
      const shiftKey1 = keyCodeCombos1[0].shiftKey;
      const keyCode1 = keyCodeCombos1[0].keyCode;
      const shiftKey2 = keyCodeCombos2[0].shiftKey;
      const keyCode2 = keyCodeCombos2[0].keyCode;
      if (keyCode1 === keyCode2 && shiftKey1 !== shiftKey2) {
        return keyCode1;
      }
    }
    return -1;
  }
  f(scanCodeCombo) {
    return this.h(scanCodeCombo.ctrlKey, scanCodeCombo.shiftKey, scanCodeCombo.altKey, scanCodeCombo.scanCode);
  }
  g(keyCodeCombo) {
    return this.h(keyCodeCombo.ctrlKey, keyCodeCombo.shiftKey, keyCodeCombo.altKey, keyCodeCombo.keyCode);
  }
  h(ctrlKey, shiftKey, altKey, principal) {
    return ((ctrlKey ? 1 : 0) << 0 | (shiftKey ? 1 : 0) << 1 | (altKey ? 1 : 0) << 2 | principal << 3) >>> 0;
  }
};
var $anc = class _$anc {
  constructor(g, rawMappings, h3, l) {
    this.g = g;
    this.h = h3;
    this.l = l;
    this.e = [];
    this.f = [];
    this.c = [];
    this.d = new ScanCodeKeyCodeMapper();
    this.e = [];
    this.f = [];
    const _registerIfUnknown = (hwCtrlKey, hwShiftKey, hwAltKey, scanCode, kbCtrlKey, kbShiftKey, kbAltKey, keyCode) => {
      this.d.registerIfUnknown(new ScanCodeCombo(hwCtrlKey ? true : false, hwShiftKey ? true : false, hwAltKey ? true : false, scanCode), new KeyCodeCombo(kbCtrlKey ? true : false, kbShiftKey ? true : false, kbAltKey ? true : false, keyCode));
    };
    const _registerAllCombos = (_ctrlKey, _shiftKey, _altKey, scanCode, keyCode) => {
      for (let ctrlKey = _ctrlKey; ctrlKey <= 1; ctrlKey++) {
        for (let shiftKey = _shiftKey; shiftKey <= 1; shiftKey++) {
          for (let altKey = _altKey; altKey <= 1; altKey++) {
            _registerIfUnknown(ctrlKey, shiftKey, altKey, scanCode, ctrlKey, shiftKey, altKey, keyCode);
          }
        }
      }
    };
    for (let scanCode = 0; scanCode < 193; scanCode++) {
      this.e[scanCode] = null;
    }
    for (let scanCode = 0; scanCode < 193; scanCode++) {
      this.f[scanCode] = null;
    }
    for (let scanCode = 0; scanCode < 193; scanCode++) {
      const keyCode = $9e[scanCode];
      if (keyCode !== -1) {
        _registerAllCombos(0, 0, 0, scanCode, keyCode);
        this.e[scanCode] = KeyCodeUtils.toString(keyCode);
        if (keyCode === 0 || keyCode === 5 || keyCode === 57 || keyCode === 6 || keyCode === 4) {
          this.f[scanCode] = null;
        } else {
          this.f[scanCode] = `[${$8e.toString(scanCode)}]`;
        }
      }
    }
    const missingLatinLettersOverride = {};
    {
      const producesLatinLetter = [];
      for (const strScanCode in rawMappings) {
        if (rawMappings.hasOwnProperty(strScanCode)) {
          const scanCode = $8e.toEnum(strScanCode);
          if (scanCode === 0) {
            continue;
          }
          if ($9e[scanCode] !== -1) {
            continue;
          }
          const rawMapping = rawMappings[strScanCode];
          const value = _$anc.getCharCode(rawMapping.value);
          if (value >= 97 && value <= 122) {
            const upperCaseValue = 65 + (value - 97);
            producesLatinLetter[upperCaseValue] = true;
          }
        }
      }
      const _registerLetterIfMissing = (charCode, scanCode, value, withShift) => {
        if (!producesLatinLetter[charCode]) {
          missingLatinLettersOverride[$8e.toString(scanCode)] = {
            value,
            withShift,
            withAltGr: "",
            withShiftAltGr: ""
          };
        }
      };
      _registerLetterIfMissing(65, 10, "a", "A");
      _registerLetterIfMissing(66, 11, "b", "B");
      _registerLetterIfMissing(67, 12, "c", "C");
      _registerLetterIfMissing(68, 13, "d", "D");
      _registerLetterIfMissing(69, 14, "e", "E");
      _registerLetterIfMissing(70, 15, "f", "F");
      _registerLetterIfMissing(71, 16, "g", "G");
      _registerLetterIfMissing(72, 17, "h", "H");
      _registerLetterIfMissing(73, 18, "i", "I");
      _registerLetterIfMissing(74, 19, "j", "J");
      _registerLetterIfMissing(75, 20, "k", "K");
      _registerLetterIfMissing(76, 21, "l", "L");
      _registerLetterIfMissing(77, 22, "m", "M");
      _registerLetterIfMissing(78, 23, "n", "N");
      _registerLetterIfMissing(79, 24, "o", "O");
      _registerLetterIfMissing(80, 25, "p", "P");
      _registerLetterIfMissing(81, 26, "q", "Q");
      _registerLetterIfMissing(82, 27, "r", "R");
      _registerLetterIfMissing(83, 28, "s", "S");
      _registerLetterIfMissing(84, 29, "t", "T");
      _registerLetterIfMissing(85, 30, "u", "U");
      _registerLetterIfMissing(86, 31, "v", "V");
      _registerLetterIfMissing(87, 32, "w", "W");
      _registerLetterIfMissing(88, 33, "x", "X");
      _registerLetterIfMissing(89, 34, "y", "Y");
      _registerLetterIfMissing(90, 35, "z", "Z");
    }
    const mappings = [];
    let mappingsLen = 0;
    for (const strScanCode in rawMappings) {
      if (rawMappings.hasOwnProperty(strScanCode)) {
        const scanCode = $8e.toEnum(strScanCode);
        if (scanCode === 0) {
          continue;
        }
        if ($9e[scanCode] !== -1) {
          continue;
        }
        this.c[scanCode] = rawMappings[strScanCode];
        const rawMapping = missingLatinLettersOverride[strScanCode] || rawMappings[strScanCode];
        const value = _$anc.getCharCode(rawMapping.value);
        const withShift = _$anc.getCharCode(rawMapping.withShift);
        const withAltGr = _$anc.getCharCode(rawMapping.withAltGr);
        const withShiftAltGr = _$anc.getCharCode(rawMapping.withShiftAltGr);
        const mapping2 = {
          scanCode,
          value,
          withShift,
          withAltGr,
          withShiftAltGr
        };
        mappings[mappingsLen++] = mapping2;
        this.f[scanCode] = `[${$8e.toString(scanCode)}]`;
        if (value >= 97 && value <= 122) {
          const upperCaseValue = 65 + (value - 97);
          this.e[scanCode] = String.fromCharCode(upperCaseValue);
        } else if (value >= 65 && value <= 90) {
          this.e[scanCode] = String.fromCharCode(value);
        } else if (value) {
          this.e[scanCode] = String.fromCharCode(value);
        } else {
          this.e[scanCode] = null;
        }
      }
    }
    for (let i2 = mappings.length - 1; i2 >= 0; i2--) {
      const mapping2 = mappings[i2];
      const scanCode = mapping2.scanCode;
      const withShiftAltGr = mapping2.withShiftAltGr;
      if (withShiftAltGr === mapping2.withAltGr || withShiftAltGr === mapping2.withShift || withShiftAltGr === mapping2.value) {
        continue;
      }
      const kb = _$anc.r(withShiftAltGr);
      if (!kb) {
        continue;
      }
      const kbShiftKey = kb.shiftKey;
      const keyCode = kb.keyCode;
      if (kbShiftKey) {
        _registerIfUnknown(1, 1, 1, scanCode, 0, 1, 0, keyCode);
      } else {
        _registerIfUnknown(1, 1, 1, scanCode, 0, 0, 0, keyCode);
      }
    }
    for (let i2 = mappings.length - 1; i2 >= 0; i2--) {
      const mapping2 = mappings[i2];
      const scanCode = mapping2.scanCode;
      const withAltGr = mapping2.withAltGr;
      if (withAltGr === mapping2.withShift || withAltGr === mapping2.value) {
        continue;
      }
      const kb = _$anc.r(withAltGr);
      if (!kb) {
        continue;
      }
      const kbShiftKey = kb.shiftKey;
      const keyCode = kb.keyCode;
      if (kbShiftKey) {
        _registerIfUnknown(1, 0, 1, scanCode, 0, 1, 0, keyCode);
      } else {
        _registerIfUnknown(1, 0, 1, scanCode, 0, 0, 0, keyCode);
      }
    }
    for (let i2 = mappings.length - 1; i2 >= 0; i2--) {
      const mapping2 = mappings[i2];
      const scanCode = mapping2.scanCode;
      const withShift = mapping2.withShift;
      if (withShift === mapping2.value) {
        continue;
      }
      const kb = _$anc.r(withShift);
      if (!kb) {
        continue;
      }
      const kbShiftKey = kb.shiftKey;
      const keyCode = kb.keyCode;
      if (kbShiftKey) {
        _registerIfUnknown(0, 1, 0, scanCode, 0, 1, 0, keyCode);
        _registerIfUnknown(0, 1, 1, scanCode, 0, 1, 1, keyCode);
        _registerIfUnknown(1, 1, 0, scanCode, 1, 1, 0, keyCode);
        _registerIfUnknown(1, 1, 1, scanCode, 1, 1, 1, keyCode);
      } else {
        _registerIfUnknown(0, 1, 0, scanCode, 0, 0, 0, keyCode);
        _registerIfUnknown(0, 1, 0, scanCode, 0, 1, 0, keyCode);
        _registerIfUnknown(0, 1, 1, scanCode, 0, 0, 1, keyCode);
        _registerIfUnknown(0, 1, 1, scanCode, 0, 1, 1, keyCode);
        _registerIfUnknown(1, 1, 0, scanCode, 1, 0, 0, keyCode);
        _registerIfUnknown(1, 1, 0, scanCode, 1, 1, 0, keyCode);
        _registerIfUnknown(1, 1, 1, scanCode, 1, 0, 1, keyCode);
        _registerIfUnknown(1, 1, 1, scanCode, 1, 1, 1, keyCode);
      }
    }
    for (let i2 = mappings.length - 1; i2 >= 0; i2--) {
      const mapping2 = mappings[i2];
      const scanCode = mapping2.scanCode;
      const kb = _$anc.r(mapping2.value);
      if (!kb) {
        continue;
      }
      const kbShiftKey = kb.shiftKey;
      const keyCode = kb.keyCode;
      if (kbShiftKey) {
        _registerIfUnknown(0, 0, 0, scanCode, 0, 1, 0, keyCode);
        _registerIfUnknown(0, 0, 1, scanCode, 0, 1, 1, keyCode);
        _registerIfUnknown(1, 0, 0, scanCode, 1, 1, 0, keyCode);
        _registerIfUnknown(1, 0, 1, scanCode, 1, 1, 1, keyCode);
      } else {
        _registerIfUnknown(0, 0, 0, scanCode, 0, 0, 0, keyCode);
        _registerIfUnknown(0, 0, 1, scanCode, 0, 0, 1, keyCode);
        _registerIfUnknown(0, 1, 0, scanCode, 0, 1, 0, keyCode);
        _registerIfUnknown(0, 1, 1, scanCode, 0, 1, 1, keyCode);
        _registerIfUnknown(1, 0, 0, scanCode, 1, 0, 0, keyCode);
        _registerIfUnknown(1, 0, 1, scanCode, 1, 0, 1, keyCode);
        _registerIfUnknown(1, 1, 0, scanCode, 1, 1, 0, keyCode);
        _registerIfUnknown(1, 1, 1, scanCode, 1, 1, 1, keyCode);
      }
    }
    _registerAllCombos(
      0,
      0,
      0,
      36,
      22
      /* KeyCode.Digit1 */
    );
    _registerAllCombos(
      0,
      0,
      0,
      37,
      23
      /* KeyCode.Digit2 */
    );
    _registerAllCombos(
      0,
      0,
      0,
      38,
      24
      /* KeyCode.Digit3 */
    );
    _registerAllCombos(
      0,
      0,
      0,
      39,
      25
      /* KeyCode.Digit4 */
    );
    _registerAllCombos(
      0,
      0,
      0,
      40,
      26
      /* KeyCode.Digit5 */
    );
    _registerAllCombos(
      0,
      0,
      0,
      41,
      27
      /* KeyCode.Digit6 */
    );
    _registerAllCombos(
      0,
      0,
      0,
      42,
      28
      /* KeyCode.Digit7 */
    );
    _registerAllCombos(
      0,
      0,
      0,
      43,
      29
      /* KeyCode.Digit8 */
    );
    _registerAllCombos(
      0,
      0,
      0,
      44,
      30
      /* KeyCode.Digit9 */
    );
    _registerAllCombos(
      0,
      0,
      0,
      45,
      21
      /* KeyCode.Digit0 */
    );
    this.d.registrationComplete();
  }
  dumpDebugInfo() {
    const result = [];
    const immutableSamples = [
      88,
      104
      /* ScanCode.Numpad0 */
    ];
    let cnt = 0;
    result.push(`isUSStandard: ${this.g}`);
    result.push(`----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------`);
    for (let scanCode = 0; scanCode < 193; scanCode++) {
      if ($9e[scanCode] !== -1) {
        if (immutableSamples.indexOf(scanCode) === -1) {
          continue;
        }
      }
      if (cnt % 4 === 0) {
        result.push(`|       HW Code combination      |  Key  |    KeyCode combination    | Pri |          UI label         |         User settings          |    Electron accelerator   |       Dispatching string       | WYSIWYG |`);
        result.push(`----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------`);
      }
      cnt++;
      const mapping2 = this.c[scanCode];
      for (let mod = 0; mod < 8; mod++) {
        const hwCtrlKey = mod & 1 ? true : false;
        const hwShiftKey = mod & 2 ? true : false;
        const hwAltKey = mod & 4 ? true : false;
        const scanCodeCombo = new ScanCodeCombo(hwCtrlKey, hwShiftKey, hwAltKey, scanCode);
        const resolvedKb = this.resolveKeyboardEvent({
          _standardKeyboardEventBrand: true,
          ctrlKey: scanCodeCombo.ctrlKey,
          shiftKey: scanCodeCombo.shiftKey,
          altKey: scanCodeCombo.altKey,
          metaKey: false,
          altGraphKey: false,
          keyCode: -1,
          code: $8e.toString(scanCode)
        });
        const outScanCodeCombo = scanCodeCombo.toString();
        const outKey = scanCodeCombo.getProducedChar(mapping2);
        const ariaLabel = resolvedKb.getAriaLabel();
        const outUILabel = ariaLabel ? ariaLabel.replace(/Control\+/, "Ctrl+") : null;
        const outUserSettings = resolvedKb.getUserSettingsLabel();
        const outElectronAccelerator = resolvedKb.getElectronAccelerator();
        const outDispatchStr = resolvedKb.getDispatchChords()[0];
        const isWYSIWYG = resolvedKb ? resolvedKb.isWYSIWYG() : false;
        const outWYSIWYG = isWYSIWYG ? "       " : "   NO  ";
        const kbCombos = this.d.lookupScanCodeCombo(scanCodeCombo);
        if (kbCombos.length === 0) {
          result.push(`| ${this.m(outScanCodeCombo, 30)} | ${outKey} | ${this.m("", 25)} | ${this.m("", 3)} | ${this.m(outUILabel, 25)} | ${this.m(outUserSettings, 30)} | ${this.m(outElectronAccelerator, 25)} | ${this.m(outDispatchStr, 30)} | ${outWYSIWYG} |`);
        } else {
          for (let i2 = 0, len = kbCombos.length; i2 < len; i2++) {
            const kbCombo = kbCombos[i2];
            let colPriority;
            const scanCodeCombos = this.d.lookupKeyCodeCombo(kbCombo);
            if (scanCodeCombos.length === 1) {
              colPriority = "";
            } else {
              let priority = -1;
              for (let j = 0; j < scanCodeCombos.length; j++) {
                if (scanCodeCombos[j].equals(scanCodeCombo)) {
                  priority = j + 1;
                  break;
                }
              }
              colPriority = String(priority);
            }
            const outKeybinding = kbCombo.toString();
            if (i2 === 0) {
              result.push(`| ${this.m(outScanCodeCombo, 30)} | ${outKey} | ${this.m(outKeybinding, 25)} | ${this.m(colPriority, 3)} | ${this.m(outUILabel, 25)} | ${this.m(outUserSettings, 30)} | ${this.m(outElectronAccelerator, 25)} | ${this.m(outDispatchStr, 30)} | ${outWYSIWYG} |`);
            } else {
              result.push(`| ${this.m("", 30)} |       | ${this.m(outKeybinding, 25)} | ${this.m(colPriority, 3)} | ${this.m("", 25)} | ${this.m("", 30)} | ${this.m("", 25)} | ${this.m("", 30)} |         |`);
            }
          }
        }
      }
      result.push(`----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------`);
    }
    return result.join("\n");
  }
  m(str, cnt) {
    if (str === null) {
      str = "null";
    }
    while (str.length < cnt) {
      str = " " + str;
    }
    return str;
  }
  keyCodeChordToScanCodeChord(chord) {
    if (chord.keyCode === 3) {
      return [new $cf(
        chord.ctrlKey,
        chord.shiftKey,
        chord.altKey,
        chord.metaKey,
        46
        /* ScanCode.Enter */
      )];
    }
    const scanCodeCombos = this.d.lookupKeyCodeCombo(new KeyCodeCombo(chord.ctrlKey, chord.shiftKey, chord.altKey, chord.keyCode));
    const result = [];
    for (let i2 = 0, len = scanCodeCombos.length; i2 < len; i2++) {
      const scanCodeCombo = scanCodeCombos[i2];
      result[i2] = new $cf(scanCodeCombo.ctrlKey, scanCodeCombo.shiftKey, scanCodeCombo.altKey, chord.metaKey, scanCodeCombo.scanCode);
    }
    return result;
  }
  getUILabelForScanCodeChord(chord) {
    if (!chord) {
      return null;
    }
    if (chord.isDuplicateModifierCase()) {
      return "";
    }
    if (this.l === 2) {
      switch (chord.scanCode) {
        case 86:
          return "\u2190";
        case 88:
          return "\u2191";
        case 85:
          return "\u2192";
        case 87:
          return "\u2193";
      }
    }
    return this.e[chord.scanCode];
  }
  getAriaLabelForScanCodeChord(chord) {
    if (!chord) {
      return null;
    }
    if (chord.isDuplicateModifierCase()) {
      return "";
    }
    return this.e[chord.scanCode];
  }
  getDispatchStrForScanCodeChord(chord) {
    const codeDispatch = this.f[chord.scanCode];
    if (!codeDispatch) {
      return null;
    }
    let result = "";
    if (chord.ctrlKey) {
      result += "ctrl+";
    }
    if (chord.shiftKey) {
      result += "shift+";
    }
    if (chord.altKey) {
      result += "alt+";
    }
    if (chord.metaKey) {
      result += "meta+";
    }
    result += codeDispatch;
    return result;
  }
  getUserSettingsLabelForScanCodeChord(chord) {
    if (!chord) {
      return null;
    }
    if (chord.isDuplicateModifierCase()) {
      return "";
    }
    const immutableKeyCode = $9e[chord.scanCode];
    if (immutableKeyCode !== -1) {
      return KeyCodeUtils.toUserSettingsUS(immutableKeyCode).toLowerCase();
    }
    const constantKeyCode = this.d.guessStableKeyCode(chord.scanCode);
    if (constantKeyCode !== -1) {
      const reverseChords = this.keyCodeChordToScanCodeChord(new $bf(chord.ctrlKey, chord.shiftKey, chord.altKey, chord.metaKey, constantKeyCode));
      for (let i2 = 0, len = reverseChords.length; i2 < len; i2++) {
        const reverseChord = reverseChords[i2];
        if (reverseChord.scanCode === chord.scanCode) {
          return KeyCodeUtils.toUserSettingsUS(constantKeyCode).toLowerCase();
        }
      }
    }
    return this.f[chord.scanCode];
  }
  getElectronAcceleratorLabelForScanCodeChord(chord) {
    if (!chord) {
      return null;
    }
    const immutableKeyCode = $9e[chord.scanCode];
    if (immutableKeyCode !== -1) {
      return KeyCodeUtils.toElectronAccelerator(immutableKeyCode);
    }
    const constantKeyCode = this.d.guessStableKeyCode(chord.scanCode);
    if (this.l === 3 && !this.g) {
      const isOEMKey = constantKeyCode === 85 || constantKeyCode === 86 || constantKeyCode === 87 || constantKeyCode === 88 || constantKeyCode === 89 || constantKeyCode === 90 || constantKeyCode === 91 || constantKeyCode === 92 || constantKeyCode === 93 || constantKeyCode === 94;
      if (isOEMKey) {
        return null;
      }
    }
    if (constantKeyCode !== -1) {
      return KeyCodeUtils.toElectronAccelerator(constantKeyCode);
    }
    return null;
  }
  n(chordParts) {
    if (chordParts.length === 0) {
      return [];
    }
    const result = [];
    this.o(chordParts, 0, [], result);
    return result;
  }
  o(chordParts, currentIndex, previousParts, result) {
    const chordPart = chordParts[currentIndex];
    const isFinalIndex = currentIndex === chordParts.length - 1;
    for (let i2 = 0, len = chordPart.length; i2 < len; i2++) {
      const chords = [...previousParts, chordPart[i2]];
      if (isFinalIndex) {
        result.push(new $_mc(this, this.l, chords));
      } else {
        this.o(chordParts, currentIndex + 1, chords, result);
      }
    }
  }
  resolveKeyboardEvent(keyboardEvent) {
    let code = $8e.toEnum(keyboardEvent.code);
    if (code === 94) {
      code = 46;
    }
    const keyCode = keyboardEvent.keyCode;
    if (keyCode === 15 || keyCode === 16 || keyCode === 17 || keyCode === 18 || keyCode === 20 || keyCode === 19 || keyCode === 14 || keyCode === 13 || keyCode === 12 || keyCode === 11 || keyCode === 1) {
      const immutableScanCode = $0e[keyCode];
      if (immutableScanCode !== -1) {
        code = immutableScanCode;
      }
    } else {
      if (code === 95 || code === 96 || code === 97 || code === 98 || code === 99 || code === 100 || code === 101 || code === 102 || code === 103 || code === 104 || code === 105) {
        if (keyCode >= 0) {
          const immutableScanCode = $0e[keyCode];
          if (immutableScanCode !== -1) {
            code = immutableScanCode;
          }
        }
      }
    }
    const ctrlKey = keyboardEvent.ctrlKey || this.h && keyboardEvent.altGraphKey;
    const altKey = keyboardEvent.altKey || this.h && keyboardEvent.altGraphKey;
    const chord = new $cf(ctrlKey, keyboardEvent.shiftKey, altKey, keyboardEvent.metaKey, code);
    return new $_mc(this, this.l, [chord]);
  }
  p(chord) {
    if (!chord) {
      return [];
    }
    if (chord instanceof $cf) {
      return [chord];
    }
    return this.keyCodeChordToScanCodeChord(chord);
  }
  resolveKeybinding(keybinding) {
    const chords = keybinding.chords.map((chord) => this.p(chord));
    return this.n(chords);
  }
  static q(charCode) {
    switch (charCode) {
      case 12290:
        return 46;
      case 12300:
        return 91;
      case 12301:
        return 93;
      case 12304:
        return 91;
      case 12305:
        return 93;
      case 65307:
        return 59;
      case 65292:
        return 44;
    }
    return charCode;
  }
  static r(charCode) {
    charCode = this.q(charCode);
    if (charCode < CHAR_CODE_TO_KEY_CODE.length) {
      return CHAR_CODE_TO_KEY_CODE[charCode];
    }
    return null;
  }
  /**
   * Attempt to map a combining character to a regular one that renders the same way.
   *
   * https://www.compart.com/en/unicode/bidiclass/NSM
   */
  static getCharCode(char) {
    if (char.length === 0) {
      return 0;
    }
    const charCode = char.charCodeAt(0);
    switch (charCode) {
      case 768:
        return 96;
      case 769:
        return 180;
      case 770:
        return 94;
      case 771:
        return 732;
      case 772:
        return 175;
      case 773:
        return 8254;
      case 774:
        return 728;
      case 775:
        return 729;
      case 776:
        return 168;
      case 778:
        return 730;
      case 779:
        return 733;
    }
    return charCode;
  }
};
(function() {
  function define2(charCode, keyCode, shiftKey) {
    for (let i2 = CHAR_CODE_TO_KEY_CODE.length; i2 < charCode; i2++) {
      CHAR_CODE_TO_KEY_CODE[i2] = null;
    }
    CHAR_CODE_TO_KEY_CODE[charCode] = { keyCode, shiftKey };
  }
  for (let chCode = 65; chCode <= 90; chCode++) {
    define2(chCode, 31 + (chCode - 65), true);
  }
  for (let chCode = 97; chCode <= 122; chCode++) {
    define2(chCode, 31 + (chCode - 97), false);
  }
  define2(59, 85, false);
  define2(58, 85, true);
  define2(61, 86, false);
  define2(43, 86, true);
  define2(44, 87, false);
  define2(60, 87, true);
  define2(45, 88, false);
  define2(95, 88, true);
  define2(46, 89, false);
  define2(62, 89, true);
  define2(47, 90, false);
  define2(63, 90, true);
  define2(96, 91, false);
  define2(126, 91, true);
  define2(91, 92, false);
  define2(123, 92, true);
  define2(92, 93, false);
  define2(124, 93, true);
  define2(93, 94, false);
  define2(125, 94, true);
  define2(39, 95, false);
  define2(34, 95, true);
})();

// out-build/vs/workbench/services/keybinding/browser/keyboardLayoutService.js
var $bnc = class extends $3c {
  get activeKeymap() {
    return this.h;
  }
  get keymapInfos() {
    return this.f;
  }
  get activeKeyboardLayout() {
    if (!this.a) {
      return null;
    }
    return this.h?.layout ?? null;
  }
  get activeKeyMapping() {
    if (!this.a) {
      return null;
    }
    return this.h?.mapping ?? null;
  }
  get keyboardLayouts() {
    return this.f.map((keymapInfo) => keymapInfo.layout);
  }
  constructor(n) {
    super();
    this.n = n;
    this.c = new $ze();
    this.onDidChangeKeyboardMapper = this.c.event;
    this.j = navigator.keyboard !== void 0;
    this.b = null;
    this.a = false;
    this.f = [];
    this.g = [];
    this.h = null;
    if (navigator.keyboard && navigator.keyboard.addEventListener) {
      navigator.keyboard.addEventListener("layoutchange", () => {
        this.w().then((mapping2) => {
          if (this.isKeyMappingActive(mapping2)) {
            return;
          }
          this.setLayoutFromBrowserAPI();
        });
      });
    }
    this.B(this.n.onDidChangeConfiguration((e) => {
      if (e.affectsConfiguration("keyboard")) {
        this.b = null;
        this.c.fire();
      }
    }));
  }
  registerKeyboardLayout(layout) {
    this.f.push(layout);
    this.g = this.f;
  }
  removeKeyboardLayout(layout) {
    let index = this.g.indexOf(layout);
    this.g.splice(index, 1);
    index = this.f.indexOf(layout);
    this.f.splice(index, 1);
  }
  getMatchedKeymapInfo(keyMapping) {
    if (!keyMapping) {
      return null;
    }
    const usStandard = this.getUSStandardLayout();
    if (usStandard) {
      let maxScore = usStandard.getScore(keyMapping);
      if (maxScore === 0) {
        return {
          result: usStandard,
          score: 0
        };
      }
      let result = usStandard;
      for (let i2 = 0; i2 < this.g.length; i2++) {
        const score2 = this.g[i2].getScore(keyMapping);
        if (score2 > maxScore) {
          if (score2 === 0) {
            return {
              result: this.g[i2],
              score: 0
            };
          }
          maxScore = score2;
          result = this.g[i2];
        }
      }
      return {
        result,
        score: maxScore
      };
    }
    for (let i2 = 0; i2 < this.g.length; i2++) {
      if (this.g[i2].fuzzyEqual(keyMapping)) {
        return {
          result: this.g[i2],
          score: 0
        };
      }
    }
    return null;
  }
  getUSStandardLayout() {
    const usStandardLayouts = this.g.filter((layout) => layout.layout.isUSStandard);
    if (usStandardLayouts.length) {
      return usStandardLayouts[0];
    }
    return null;
  }
  isKeyMappingActive(keymap) {
    return this.h && keymap && this.h.fuzzyEqual(keymap);
  }
  setUSKeyboardLayout() {
    this.h = this.getUSStandardLayout();
  }
  setActiveKeyMapping(keymap) {
    let keymapUpdated = false;
    const matchedKeyboardLayout = this.getMatchedKeymapInfo(keymap);
    if (matchedKeyboardLayout) {
      if (!this.h) {
        this.h = matchedKeyboardLayout.result;
        keymapUpdated = true;
      } else if (keymap) {
        if (matchedKeyboardLayout.result.getScore(keymap) > this.h.getScore(keymap)) {
          this.h = matchedKeyboardLayout.result;
          keymapUpdated = true;
        }
      }
    }
    if (!this.h) {
      this.h = this.getUSStandardLayout();
      keymapUpdated = true;
    }
    if (!this.h || !keymapUpdated) {
      return;
    }
    const index = this.g.indexOf(this.h);
    this.g.splice(index, 1);
    this.g.unshift(this.h);
    this.s(this.h);
  }
  setActiveKeymapInfo(keymapInfo) {
    this.h = keymapInfo;
    const index = this.g.indexOf(this.h);
    if (index === 0) {
      return;
    }
    this.g.splice(index, 1);
    this.g.unshift(this.h);
    this.s(this.h);
  }
  setLayoutFromBrowserAPI() {
    this.r(this.a);
  }
  r(initialized, keyboardEvent) {
    if (!initialized) {
      return;
    }
    this.w(keyboardEvent).then((keyMap) => {
      if (this.isKeyMappingActive(keyMap)) {
        return;
      }
      this.setActiveKeyMapping(keyMap);
    });
  }
  getKeyboardMapper() {
    const config = $9mc(this.n);
    if (config.dispatch === 1 || !this.a || !this.h) {
      return new $$mc(config.mapAltGrToCtrlAlt, OS);
    }
    if (!this.b) {
      this.b = new $Uy($cnc.t(this.h, config.mapAltGrToCtrlAlt));
    }
    return this.b;
  }
  validateCurrentKeyboardMapping(keyboardEvent) {
    if (!this.a) {
      return;
    }
    const isCurrentKeyboard = this.u(keyboardEvent);
    if (isCurrentKeyboard) {
      return;
    }
    this.r(true, keyboardEvent);
  }
  setKeyboardLayout(layoutName) {
    const matchedLayouts = this.keymapInfos.filter((keymapInfo) => $Yy(keymapInfo.layout) === layoutName);
    if (matchedLayouts.length > 0) {
      this.setActiveKeymapInfo(matchedLayouts[0]);
    }
  }
  s(keymapInfo) {
    this.a = true;
    this.b = null;
    this.c.fire();
  }
  static t(keymapInfo, mapAltGrToCtrlAlt) {
    const rawMapping = keymapInfo.mapping;
    const isUSStandard = !!keymapInfo.layout.isUSStandard;
    if (OS === 1) {
      return new $Z1b(isUSStandard, rawMapping, mapAltGrToCtrlAlt);
    }
    if (Object.keys(rawMapping).length === 0) {
      return new $$mc(mapAltGrToCtrlAlt, OS);
    }
    return new $anc(isUSStandard, rawMapping, mapAltGrToCtrlAlt, OS);
  }
  //#region Browser API
  u(keyboardEvent) {
    if (!this.a) {
      return true;
    }
    const standardKeyboardEvent = keyboardEvent;
    const currentKeymap = this.h;
    if (!currentKeymap) {
      return true;
    }
    if (standardKeyboardEvent.browserEvent.key === "Dead" || standardKeyboardEvent.browserEvent.isComposing) {
      return true;
    }
    const mapping2 = currentKeymap.mapping[standardKeyboardEvent.code];
    if (!mapping2) {
      return false;
    }
    if (mapping2.value === "") {
      if (keyboardEvent.ctrlKey || keyboardEvent.metaKey) {
        setTimeout(() => {
          this.w().then((keymap) => {
            if (this.isKeyMappingActive(keymap)) {
              return;
            }
            this.setLayoutFromBrowserAPI();
          });
        }, 350);
      }
      return true;
    }
    const expectedValue = standardKeyboardEvent.altKey && standardKeyboardEvent.shiftKey ? mapping2.withShiftAltGr : standardKeyboardEvent.altKey ? mapping2.withAltGr : standardKeyboardEvent.shiftKey ? mapping2.withShift : mapping2.value;
    const isDead = standardKeyboardEvent.altKey && standardKeyboardEvent.shiftKey && mapping2.withShiftAltGrIsDeadKey || standardKeyboardEvent.altKey && mapping2.withAltGrIsDeadKey || standardKeyboardEvent.shiftKey && mapping2.withShiftIsDeadKey || mapping2.valueIsDeadKey;
    if (isDead && standardKeyboardEvent.browserEvent.key !== "Dead") {
      return false;
    }
    if (!isDead && standardKeyboardEvent.browserEvent.key !== expectedValue) {
      return false;
    }
    return true;
  }
  async w(keyboardEvent) {
    if (this.j) {
      try {
        return await navigator.keyboard.getLayoutMap().then((e) => {
          const ret = {};
          for (const key2 of e) {
            ret[key2[0]] = {
              "value": key2[1],
              "withShift": "",
              "withAltGr": "",
              "withShiftAltGr": ""
            };
          }
          return ret;
        });
      } catch {
        this.j = false;
      }
    }
    if (keyboardEvent && !keyboardEvent.shiftKey && !keyboardEvent.altKey && !keyboardEvent.metaKey && !keyboardEvent.metaKey) {
      const ret = {};
      const standardKeyboardEvent = keyboardEvent;
      ret[standardKeyboardEvent.browserEvent.code] = {
        "value": standardKeyboardEvent.browserEvent.key,
        "withShift": "",
        "withAltGr": "",
        "withShiftAltGr": ""
      };
      const matchedKeyboardLayout = this.getMatchedKeymapInfo(ret);
      if (matchedKeyboardLayout) {
        return ret;
      }
      return null;
    }
    return null;
  }
};
var $cnc = class extends $bnc {
  constructor(configurationService, notificationService, storageService, commandService) {
    super(configurationService);
    const platform = $l ? "win" : $m ? "darwin" : "linux";
    import($ih.asBrowserUri(`vs/workbench/services/keybinding/browser/keyboardLayouts/layout.contribution.${platform}.js`).path).then((m) => {
      const keymapInfos = m.KeyboardLayoutContribution.INSTANCE.layoutInfos;
      this.f.push(...keymapInfos.map((info) => new $8mc(info.layout, info.secondaryLayouts, info.mapping, info.isUserKeyboardLayout)));
      this.g = this.f;
      this.a = true;
      this.setLayoutFromBrowserAPI();
    });
  }
};
var UserKeyboardLayout = class extends $3c {
  get keyboardLayout() {
    return this.c;
  }
  constructor(f, g) {
    super();
    this.f = f;
    this.g = g;
    this.b = this.B(new $ze());
    this.onDidChange = this.b.event;
    this.c = null;
    this.a = this.B(new $8h(() => this.h().then((changed) => {
      if (changed) {
        this.b.fire();
      }
    }), 50));
    this.B(Event2.filter(this.g.onDidFilesChange, (e) => e.contains(this.f))(() => this.a.schedule()));
  }
  async initialize() {
    await this.h();
  }
  async h() {
    const existing = this.c;
    try {
      const content = await this.g.readFile(this.f);
      const value = $yw(content.value.toString());
      if ($Gw(value) === "object") {
        const layoutInfo = value.layout;
        const mappings = value.rawMapping;
        this.c = $8mc.createKeyboardLayoutFromDebugInfo(layoutInfo, mappings, true);
      } else {
        this.c = null;
      }
    } catch (e) {
      this.c = null;
    }
    return existing ? !$Pv(existing, this.c) : true;
  }
};
var $dnc = class $dnc2 extends $3c {
  constructor(environmentService, fileService, notificationService, storageService, commandService, g) {
    super();
    this.g = g;
    this.a = new $ze();
    this.onDidChangeKeyboardLayout = this.a.event;
    const keyboardConfig = g.getValue("keyboard");
    const layout = keyboardConfig.layout;
    this.f = layout ?? "autodetect";
    this.c = new $cnc(g, notificationService, storageService, commandService);
    this.B(this.c.onDidChangeKeyboardMapper(() => {
      this.a.fire();
    }));
    if (layout && layout !== "autodetect") {
      this.c.setKeyboardLayout(layout);
    }
    this.B(g.onDidChangeConfiguration((e) => {
      if (e.affectsConfiguration("keyboard.layout")) {
        const keyboardConfig2 = g.getValue("keyboard");
        const layout2 = keyboardConfig2.layout;
        this.f = layout2;
        if (layout2 === "autodetect") {
          this.c.setLayoutFromBrowserAPI();
        } else {
          this.c.setKeyboardLayout(layout2);
        }
      }
    }));
    this.b = new UserKeyboardLayout(environmentService.keyboardLayoutResource, fileService);
    this.b.initialize().then(() => {
      if (this.b.keyboardLayout) {
        this.c.registerKeyboardLayout(this.b.keyboardLayout);
        this.setUserKeyboardLayoutIfMatched();
      }
    });
    this.B(this.b.onDidChange(() => {
      const userKeyboardLayouts = this.c.keymapInfos.filter((layout2) => layout2.isUserKeyboardLayout);
      if (userKeyboardLayouts.length) {
        if (this.b.keyboardLayout) {
          userKeyboardLayouts[0].update(this.b.keyboardLayout);
        } else {
          this.c.removeKeyboardLayout(userKeyboardLayouts[0]);
        }
      } else {
        if (this.b.keyboardLayout) {
          this.c.registerKeyboardLayout(this.b.keyboardLayout);
        }
      }
      this.setUserKeyboardLayoutIfMatched();
    }));
  }
  setUserKeyboardLayoutIfMatched() {
    const keyboardConfig = this.g.getValue("keyboard");
    const layout = keyboardConfig.layout;
    if (layout && this.b.keyboardLayout) {
      if ($Yy(this.b.keyboardLayout.layout) === layout && this.c.activeKeymap) {
        if (!this.b.keyboardLayout.equal(this.c.activeKeymap)) {
          this.c.setActiveKeymapInfo(this.b.keyboardLayout);
        }
      }
    }
  }
  getKeyboardMapper() {
    return this.c.getKeyboardMapper();
  }
  getCurrentKeyboardLayout() {
    return this.c.activeKeyboardLayout;
  }
  getAllKeyboardLayouts() {
    return this.c.keyboardLayouts;
  }
  getRawKeyboardMapping() {
    return this.c.activeKeyMapping;
  }
  validateCurrentKeyboardMapping(keyboardEvent) {
    if (this.f !== "autodetect") {
      return;
    }
    this.c.validateCurrentKeyboardMapping(keyboardEvent);
  }
};
$dnc = __decorate([
  __param(0, $Xk),
  __param(1, $km),
  __param(2, $PJ),
  __param(3, $jv),
  __param(4, $sn),
  __param(5, $kl)
], $dnc);
$SC(
  $Vy,
  $dnc,
  1
  /* InstantiationType.Delayed */
);
var configurationRegistry20 = $Wn.as($Ht.Configuration);
var keyboardConfiguration2 = {
  "id": "keyboard",
  "order": 15,
  "type": "object",
  "title": localize(12964, null),
  "properties": {
    "keyboard.layout": {
      "type": "string",
      "default": "autodetect",
      "description": localize(12965, null)
    }
  }
};
configurationRegistry20.registerConfiguration(keyboardConfiguration2);

// out-build/vs/workbench/services/extensions/common/extensionHostProtocol.js
var UIKind;
(function(UIKind2) {
  UIKind2[UIKind2["Desktop"] = 1] = "Desktop";
  UIKind2[UIKind2["Web"] = 2] = "Web";
})(UIKind || (UIKind = {}));
var ExtensionHostExitCode;
(function(ExtensionHostExitCode2) {
  ExtensionHostExitCode2[ExtensionHostExitCode2["VersionMismatch"] = 55] = "VersionMismatch";
  ExtensionHostExitCode2[ExtensionHostExitCode2["UnexpectedError"] = 81] = "UnexpectedError";
})(ExtensionHostExitCode || (ExtensionHostExitCode = {}));
var MessageType3;
(function(MessageType5) {
  MessageType5[MessageType5["Initialized"] = 0] = "Initialized";
  MessageType5[MessageType5["Ready"] = 1] = "Ready";
  MessageType5[MessageType5["Terminate"] = 2] = "Terminate";
})(MessageType3 || (MessageType3 = {}));
function $jN(type) {
  const result = $Ci.alloc(1);
  switch (type) {
    case 0:
      result.writeUInt8(1, 0);
      break;
    case 1:
      result.writeUInt8(2, 0);
      break;
    case 2:
      result.writeUInt8(3, 0);
      break;
  }
  return result;
}
function $kN(message, type) {
  if (message.byteLength !== 1) {
    return false;
  }
  switch (message.readUInt8(0)) {
    case 1:
      return type === 0;
    case 2:
      return type === 1;
    case 3:
      return type === 2;
    default:
      return false;
  }
}
var NativeLogMarkers;
(function(NativeLogMarkers2) {
  NativeLogMarkers2["Start"] = "START_NATIVE_LOG";
  NativeLogMarkers2["End"] = "END_NATIVE_LOG";
})(NativeLogMarkers || (NativeLogMarkers = {}));

// out-build/vs/workbench/services/extensions/browser/webWorkerExtensionHost.js
var $enc = class $enc2 extends $3c {
  constructor(runningLocation, startup, h3, j, m, n, r2, s, t, u, w, y, z) {
    super();
    this.runningLocation = runningLocation;
    this.startup = startup;
    this.h = h3;
    this.j = j;
    this.m = m;
    this.n = n;
    this.r = r2;
    this.s = s;
    this.t = t;
    this.u = u;
    this.w = w;
    this.y = y;
    this.z = z;
    this.pid = null;
    this.remoteAuthority = null;
    this.extensions = null;
    this.a = this.B(new $ze());
    this.onExit = this.a.event;
    this.b = false;
    this.c = null;
    this.f = null;
    this.g = $vh(this.t.extHostLogsPath, "webWorker");
  }
  async C() {
    const suffixSearchParams = new URLSearchParams();
    if (this.t.debugExtensionHost && this.t.debugRenderer) {
      suffixSearchParams.set("debugged", "1");
    }
    COI.addSearchParam(suffixSearchParams, true, true);
    const suffix = `?${suffixSearchParams.toString()}`;
    const iframeModulePath = `vs/workbench/services/extensions/worker/webWorkerExtensionHostIframe.html`;
    if ($r) {
      const webEndpointUrlTemplate = this.w.webEndpointUrlTemplate;
      const commit = this.w.commit;
      const quality = this.w.quality;
      if (webEndpointUrlTemplate && commit && quality) {
        const key2 = "webWorkerExtensionHostIframeStableOriginUUID";
        let stableOriginUUID = this.z.get(
          key2,
          1
          /* StorageScope.WORKSPACE */
        );
        if (typeof stableOriginUUID === "undefined") {
          stableOriginUUID = $ps();
          this.z.store(
            key2,
            stableOriginUUID,
            1,
            1
            /* StorageTarget.MACHINE */
          );
        }
        const hash = await $kf($Y.origin, stableOriginUUID);
        const baseUrl = webEndpointUrlTemplate.replace("{{uuid}}", `v--${hash}`).replace("{{commit}}", commit).replace("{{quality}}", quality);
        const res = new URL(`${baseUrl}/out/${iframeModulePath}${suffix}`);
        res.searchParams.set("parentOrigin", $Y.origin);
        res.searchParams.set("salt", stableOriginUUID);
        return res.toString();
      }
      console.warn(`The web worker extension host is started in a same-origin iframe!`);
    }
    const relativeExtensionHostIframeSrc = $ih.asBrowserUri(iframeModulePath);
    return `${relativeExtensionHostIframeSrc.toString(true)}${suffix}`;
  }
  async start() {
    if (!this.c) {
      this.c = this.D();
      this.c.then((protocol) => this.f = protocol);
    }
    return this.c;
  }
  async D() {
    const webWorkerExtensionHostIframeSrc = await this.C();
    const emitter = this.B(new $ze());
    const iframe = document.createElement("iframe");
    iframe.setAttribute("class", "web-worker-ext-host-iframe");
    iframe.setAttribute("sandbox", "allow-scripts allow-same-origin");
    iframe.setAttribute("allow", "usb; serial; hid; cross-origin-isolated;");
    iframe.setAttribute("aria-hidden", "true");
    iframe.style.display = "none";
    const vscodeWebWorkerExtHostId = $ps();
    iframe.setAttribute("src", `${webWorkerExtensionHostIframeSrc}&vscodeWebWorkerExtHostId=${vscodeWebWorkerExtHostId}`);
    const barrier = new $Uh();
    let port;
    let barrierError = null;
    let barrierHasError = false;
    let startTimeout = null;
    const rejectBarrier = (exitCode, error) => {
      barrierError = error;
      barrierHasError = true;
      $gb(barrierError);
      clearTimeout(startTimeout);
      this.a.fire([81, barrierError.message]);
      barrier.open();
    };
    const resolveBarrier = (messagePort) => {
      port = messagePort;
      clearTimeout(startTimeout);
      barrier.open();
    };
    startTimeout = setTimeout(() => {
      console.warn(`The Web Worker Extension Host did not start in 60s, that might be a problem.`);
    }, 6e4);
    this.B($_i($Y, "message", (event) => {
      if (event.source !== iframe.contentWindow) {
        return;
      }
      if (event.data.vscodeWebWorkerExtHostId !== vscodeWebWorkerExtHostId) {
        return;
      }
      if (event.data.error) {
        const { name, message, stack } = event.data.error;
        const err = new Error();
        err.message = message;
        err.name = name;
        err.stack = stack;
        return rejectBarrier(81, err);
      }
      if (event.data.type === "vscode.bootstrap.nls") {
        iframe.contentWindow.postMessage({
          type: event.data.type,
          data: {
            workerUrl: $ih.asBrowserUri("vs/workbench/api/worker/extensionHostWorkerMain.js").toString(true),
            fileRoot: globalThis._VSCODE_FILE_ROOT,
            nls: {
              messages: $f(),
              language: $g()
            }
          }
        }, "*");
        return;
      }
      const { data } = event.data;
      if (barrier.isOpen() || !(data instanceof MessagePort)) {
        console.warn("UNEXPECTED message", event);
        const err = new Error("UNEXPECTED message");
        return rejectBarrier(81, err);
      }
      resolveBarrier(data);
    }));
    this.y.mainContainer.appendChild(iframe);
    this.B($1c(() => iframe.remove()));
    await barrier.wait();
    if (barrierHasError) {
      throw barrierError;
    }
    const messagePorts = this.t.options?.messagePorts ?? /* @__PURE__ */ new Map();
    iframe.contentWindow.postMessage({ type: "vscode.init", data: messagePorts }, "*", [...messagePorts.values()]);
    port.onmessage = (event) => {
      const { data } = event;
      if (!(data instanceof ArrayBuffer)) {
        console.warn("UNKNOWN data received", data);
        this.a.fire([77, "UNKNOWN data received"]);
        return;
      }
      emitter.fire($Ci.wrap(new Uint8Array(data, 0, data.byteLength)));
    };
    const protocol = {
      onMessage: emitter.event,
      send: (vsbuf) => {
        const data = vsbuf.buffer.buffer.slice(vsbuf.buffer.byteOffset, vsbuf.buffer.byteOffset + vsbuf.buffer.byteLength);
        port.postMessage(data, [data]);
      }
    };
    return this.F(protocol);
  }
  async F(protocol) {
    await Event2.toPromise(Event2.filter(protocol.onMessage, (msg) => $kN(
      msg,
      1
      /* MessageType.Ready */
    )));
    if (this.b) {
      throw $mb();
    }
    protocol.send($Ci.fromString(JSON.stringify(await this.G())));
    if (this.b) {
      throw $mb();
    }
    await Event2.toPromise(Event2.filter(protocol.onMessage, (msg) => $kN(
      msg,
      0
      /* MessageType.Initialized */
    )));
    if (this.b) {
      throw $mb();
    }
    return protocol;
  }
  dispose() {
    if (this.b) {
      return;
    }
    this.b = true;
    this.f?.send($jN(
      2
      /* MessageType.Terminate */
    ));
    super.dispose();
  }
  getInspectPort() {
    return void 0;
  }
  enableInspectPort() {
    return Promise.resolve(false);
  }
  async G() {
    const initData = await this.h.getInitData();
    this.extensions = initData.extensions;
    const workspace2 = this.m.getWorkspace();
    const nlsBaseUrl = this.w.extensionsGallery?.nlsBaseUrl;
    let nlsUrlWithDetails = void 0;
    if (nlsBaseUrl && this.w.commit && !Language.isDefaultVariant()) {
      nlsUrlWithDetails = URI.joinPath(URI.parse(nlsBaseUrl), this.w.commit, this.w.version, Language.value());
    }
    return {
      commit: this.w.commit,
      version: this.w.version,
      quality: this.w.quality,
      parentPid: 0,
      environment: {
        isExtensionDevelopmentDebug: this.t.debugRenderer,
        appName: this.w.nameLong,
        appHost: this.w.embedderIdentifier ?? ($r ? "web" : "desktop"),
        appUriScheme: this.w.urlProtocol,
        appLanguage: $z,
        extensionTelemetryLogResource: this.t.extHostTelemetryLogFile,
        isExtensionTelemetryLoggingOnly: $jw(this.w, this.t),
        extensionDevelopmentLocationURI: this.t.extensionDevelopmentLocationURI,
        extensionTestsLocationURI: this.t.extensionTestsLocationURI,
        globalStorageHome: this.u.defaultProfile.globalStorageHome,
        workspaceStorageHome: this.t.workspaceStorageHome,
        extensionLogLevel: this.t.extensionLogLevel
      },
      workspace: this.m.getWorkbenchState() === 1 ? void 0 : {
        configuration: workspace2.configuration || void 0,
        id: workspace2.id,
        name: this.n.getWorkspaceLabel(workspace2),
        transient: workspace2.transient
      },
      consoleForward: {
        includeStack: false,
        logNative: this.t.debugRenderer
      },
      extensions: this.extensions.toSnapshot(),
      nlsBaseUrl: nlsUrlWithDetails,
      telemetryInfo: {
        sessionId: this.j.sessionId,
        machineId: this.j.machineId,
        sqmId: this.j.sqmId,
        devDeviceId: this.j.devDeviceId,
        firstSessionDate: this.j.firstSessionDate,
        msftInternal: this.j.msftInternal
      },
      logLevel: this.r.getLevel(),
      loggers: [...this.s.getRegisteredLoggers()],
      logsLocation: this.g,
      autoStart: this.startup === 1,
      remote: {
        authority: this.t.remoteAuthority,
        connectionData: null,
        isRemote: false
      },
      uiKind: $r ? UIKind.Web : UIKind.Desktop
    };
  }
};
$enc = __decorate([
  __param(3, $zv),
  __param(4, $Zk),
  __param(5, $ZI),
  __param(6, $wn),
  __param(7, $xn),
  __param(8, $M4),
  __param(9, $rs),
  __param(10, $Vu),
  __param(11, $Ulb),
  __param(12, $jv)
], $enc);

// out-build/vs/workbench/services/extensions/browser/webWorkerFileSystemProvider.js
var $fnc = class {
  constructor() {
    this.capabilities = 2048 + 2 + 1024;
    this.onDidChangeCapabilities = Event2.None;
    this.onDidChangeFile = Event2.None;
  }
  // working implementations
  async readFile(resource) {
    try {
      const res = await fetch(resource.toString(true));
      if (res.status === 200) {
        return new Uint8Array(await res.arrayBuffer());
      }
      throw $xm(res.statusText, FileSystemProviderErrorCode.Unknown);
    } catch (err) {
      throw $xm(err, FileSystemProviderErrorCode.Unknown);
    }
  }
  // fake implementations
  async stat(_resource) {
    return {
      type: FileType.File,
      size: 0,
      mtime: 0,
      ctime: 0
    };
  }
  watch() {
    return $3c.None;
  }
  // error implementations
  writeFile(_resource, _content, _opts) {
    throw new $sb();
  }
  readdir(_resource) {
    throw new $sb();
  }
  mkdir(_resource) {
    throw new $sb();
  }
  delete(_resource, _opts) {
    throw new $sb();
  }
  rename(_from, _to, _opts) {
    throw new $sb();
  }
};

// out-build/vs/platform/lifecycle/common/lifecycle.js
function $gnc(vetos, onError2) {
  if (vetos.length === 0) {
    return Promise.resolve(false);
  }
  const promises = [];
  let lazyValue = false;
  for (const valueOrPromise of vetos) {
    if (valueOrPromise === true) {
      return Promise.resolve(true);
    }
    if ($Gh(valueOrPromise)) {
      promises.push(valueOrPromise.then((value) => {
        if (value) {
          lazyValue = true;
        }
      }, (err) => {
        onError2(err);
        lazyValue = true;
      }));
    }
  }
  return Promises.settled(promises).then(() => lazyValue);
}

// out-build/vs/workbench/services/extensions/common/extensionDescriptionRegistry.js
var $hnc = class {
  constructor(versionId, removedDueToLooping) {
    this.versionId = versionId;
    this.removedDueToLooping = removedDueToLooping;
  }
};
var $inc = class _$inc {
  static isHostExtension(extensionId, myRegistry, globalRegistry) {
    if (myRegistry.getExtensionDescription(extensionId)) {
      return false;
    }
    const extensionDescription = globalRegistry.getExtensionDescription(extensionId);
    if (!extensionDescription) {
      return false;
    }
    if ((extensionDescription.main || extensionDescription.browser) && extensionDescription.api === "none") {
      return true;
    }
    return false;
  }
  constructor(j, extensionDescriptions) {
    this.j = j;
    this.c = new $ze();
    this.onDidChange = this.c.event;
    this.d = 0;
    this.e = extensionDescriptions;
    this.k();
  }
  k() {
    this.e.sort(extensionCmp);
    this.f = new $7z();
    this.g = [];
    this.h = /* @__PURE__ */ new Map();
    for (const extensionDescription of this.e) {
      if (this.f.has(extensionDescription.identifier)) {
        console.error("Extension `" + extensionDescription.identifier.value + "` is already registered");
        continue;
      }
      this.f.set(extensionDescription.identifier, extensionDescription);
      this.g.push(extensionDescription);
      const activationEvents = this.j.readActivationEvents(extensionDescription);
      for (const activationEvent of activationEvents) {
        if (!this.h.has(activationEvent)) {
          this.h.set(activationEvent, []);
        }
        this.h.get(activationEvent).push(extensionDescription);
      }
    }
  }
  set(extensionDescriptions) {
    this.e = extensionDescriptions;
    this.k();
    this.d++;
    this.c.fire(void 0);
    return {
      versionId: this.d
    };
  }
  deltaExtensions(toAdd, toRemove) {
    this.e = removeExtensions(this.e, toRemove);
    this.e = this.e.concat(toAdd);
    const looping = _$inc.l(this.e);
    this.e = removeExtensions(this.e, looping.map((ext) => ext.identifier));
    this.k();
    this.d++;
    this.c.fire(void 0);
    return new $hnc(this.d, looping);
  }
  static l(extensionDescriptions) {
    const G = new class {
      constructor() {
        this.c = /* @__PURE__ */ new Map();
        this.d = /* @__PURE__ */ new Set();
        this.e = [];
      }
      addNode(id2) {
        if (!this.d.has(id2)) {
          this.d.add(id2);
          this.e.push(id2);
        }
      }
      addArc(from, to) {
        this.addNode(from);
        this.addNode(to);
        if (this.c.has(from)) {
          this.c.get(from).push(to);
        } else {
          this.c.set(from, [to]);
        }
      }
      getArcs(id2) {
        if (this.c.has(id2)) {
          return this.c.get(id2);
        }
        return [];
      }
      hasOnlyGoodArcs(id2, good2) {
        const dependencies = G.getArcs(id2);
        for (let i2 = 0; i2 < dependencies.length; i2++) {
          if (!good2.has(dependencies[i2])) {
            return false;
          }
        }
        return true;
      }
      getNodes() {
        return this.e;
      }
    }();
    const descs = new $7z();
    for (const extensionDescription of extensionDescriptions) {
      descs.set(extensionDescription.identifier, extensionDescription);
      if (extensionDescription.extensionDependencies) {
        for (const depId of extensionDescription.extensionDependencies) {
          G.addArc($5z.toKey(extensionDescription.identifier), $5z.toKey(depId));
        }
      }
    }
    const good = /* @__PURE__ */ new Set();
    G.getNodes().filter((id2) => G.getArcs(id2).length === 0).forEach((id2) => good.add(id2));
    const nodes = G.getNodes().filter((id2) => !good.has(id2));
    let madeProgress;
    do {
      madeProgress = false;
      for (let i2 = 0; i2 < nodes.length; i2++) {
        const id2 = nodes[i2];
        if (G.hasOnlyGoodArcs(id2, good)) {
          nodes.splice(i2, 1);
          i2--;
          good.add(id2);
          madeProgress = true;
        }
      }
    } while (madeProgress);
    return nodes.map((id2) => descs.get(id2));
  }
  containsActivationEvent(activationEvent) {
    return this.h.has(activationEvent);
  }
  containsExtension(extensionId) {
    return this.f.has(extensionId);
  }
  getExtensionDescriptionsForActivationEvent(activationEvent) {
    const extensions = this.h.get(activationEvent);
    return extensions ? extensions.slice(0) : [];
  }
  getAllExtensionDescriptions() {
    return this.g.slice(0);
  }
  getSnapshot() {
    return new $jnc(this.d, this.getAllExtensionDescriptions());
  }
  getExtensionDescription(extensionId) {
    const extension = this.f.get(extensionId);
    return extension ? extension : void 0;
  }
  getExtensionDescriptionByUUID(uuid) {
    for (const extensionDescription of this.g) {
      if (extensionDescription.uuid === uuid) {
        return extensionDescription;
      }
    }
    return void 0;
  }
  getExtensionDescriptionByIdOrUUID(extensionId, uuid) {
    return this.getExtensionDescription(extensionId) ?? (uuid ? this.getExtensionDescriptionByUUID(uuid) : void 0);
  }
};
var $jnc = class {
  constructor(versionId, extensions) {
    this.versionId = versionId;
    this.extensions = extensions;
  }
};
var $knc = class {
  constructor(activationEventsReader) {
    this.d = new Lock();
    this.c = new $inc(activationEventsReader, []);
  }
  async acquireLock(customerName) {
    const lock = await this.d.acquire(customerName);
    return new $lnc(this, lock);
  }
  deltaExtensions(acquiredLock, toAdd, toRemove) {
    if (!acquiredLock.isAcquiredFor(this)) {
      throw new Error("Lock is not held");
    }
    return this.c.deltaExtensions(toAdd, toRemove);
  }
  containsActivationEvent(activationEvent) {
    return this.c.containsActivationEvent(activationEvent);
  }
  containsExtension(extensionId) {
    return this.c.containsExtension(extensionId);
  }
  getExtensionDescriptionsForActivationEvent(activationEvent) {
    return this.c.getExtensionDescriptionsForActivationEvent(activationEvent);
  }
  getAllExtensionDescriptions() {
    return this.c.getAllExtensionDescriptions();
  }
  getSnapshot() {
    return this.c.getSnapshot();
  }
  getExtensionDescription(extensionId) {
    return this.c.getExtensionDescription(extensionId);
  }
  getExtensionDescriptionByUUID(uuid) {
    return this.c.getExtensionDescriptionByUUID(uuid);
  }
  getExtensionDescriptionByIdOrUUID(extensionId, uuid) {
    return this.c.getExtensionDescriptionByIdOrUUID(extensionId, uuid);
  }
};
var $lnc = class extends $3c {
  constructor(f, lock) {
    super();
    this.f = f;
    this.c = false;
    this.B(lock);
  }
  isAcquiredFor(registry4) {
    return !this.c && this.f === registry4;
  }
};
var LockCustomer = class {
  constructor(name) {
    this.name = name;
    const withResolvers = $Oh();
    this.promise = withResolvers.promise;
    this.c = withResolvers.resolve;
  }
  resolve(value) {
    this.c(value);
  }
};
var Lock = class {
  constructor() {
    this.c = [];
    this.d = false;
  }
  async acquire(customerName) {
    const customer = new LockCustomer(customerName);
    this.c.push(customer);
    this.e();
    return customer.promise;
  }
  e() {
    if (this.d) {
      return;
    }
    if (this.c.length === 0) {
      return;
    }
    const customer = this.c.shift();
    this.d = true;
    let customerHoldsLock = true;
    const logLongRunningCustomerTimeout = setTimeout(
      () => {
        if (customerHoldsLock) {
          console.warn(`The customer named ${customer.name} has been holding on to the lock for 30s. This might be a problem.`);
        }
      },
      30 * 1e3
      /* 30 seconds */
    );
    const releaseLock = () => {
      if (!customerHoldsLock) {
        return;
      }
      clearTimeout(logLongRunningCustomerTimeout);
      customerHoldsLock = false;
      this.d = false;
      this.e();
    };
    customer.resolve($1c(releaseLock));
  }
};
var SortBucket;
(function(SortBucket2) {
  SortBucket2[SortBucket2["Builtin"] = 0] = "Builtin";
  SortBucket2[SortBucket2["User"] = 1] = "User";
  SortBucket2[SortBucket2["Dev"] = 2] = "Dev";
})(SortBucket || (SortBucket = {}));
function extensionCmp(a, b) {
  const aSortBucket = a.isBuiltin ? 0 : a.isUnderDevelopment ? 2 : 1;
  const bSortBucket = b.isBuiltin ? 0 : b.isUnderDevelopment ? 2 : 1;
  if (aSortBucket !== bSortBucket) {
    return aSortBucket - bSortBucket;
  }
  const aLastSegment = $kc.basename(a.extensionLocation.path);
  const bLastSegment = $kc.basename(b.extensionLocation.path);
  if (aLastSegment < bLastSegment) {
    return -1;
  }
  if (aLastSegment > bLastSegment) {
    return 1;
  }
  return 0;
}
function removeExtensions(arr, toRemove) {
  const toRemoveSet = new $6z(toRemove);
  return arr.filter((extension) => !toRemoveSet.has(extension.identifier));
}

// out-build/vs/workbench/services/extensions/common/extensionHostKind.js
var ExtensionHostKind;
(function(ExtensionHostKind2) {
  ExtensionHostKind2[ExtensionHostKind2["LocalProcess"] = 1] = "LocalProcess";
  ExtensionHostKind2[ExtensionHostKind2["LocalWebWorker"] = 2] = "LocalWebWorker";
  ExtensionHostKind2[ExtensionHostKind2["Remote"] = 3] = "Remote";
})(ExtensionHostKind || (ExtensionHostKind = {}));
function $gN(kind) {
  if (kind === null) {
    return "None";
  }
  switch (kind) {
    case 1:
      return "LocalProcess";
    case 2:
      return "LocalWebWorker";
    case 3:
      return "Remote";
  }
}
var ExtensionRunningPreference;
(function(ExtensionRunningPreference2) {
  ExtensionRunningPreference2[ExtensionRunningPreference2["None"] = 0] = "None";
  ExtensionRunningPreference2[ExtensionRunningPreference2["Local"] = 1] = "Local";
  ExtensionRunningPreference2[ExtensionRunningPreference2["Remote"] = 2] = "Remote";
})(ExtensionRunningPreference || (ExtensionRunningPreference = {}));
function $hN(preference) {
  switch (preference) {
    case 0:
      return "None";
    case 1:
      return "Local";
    case 2:
      return "Remote";
  }
}
function $iN(_localExtensions, _remoteExtensions, getExtensionKind, pickExtensionHostKind) {
  const localExtensions = toExtensionWithKind(_localExtensions, getExtensionKind);
  const remoteExtensions = toExtensionWithKind(_remoteExtensions, getExtensionKind);
  const allExtensions = /* @__PURE__ */ new Map();
  const collectExtension = (ext) => {
    if (allExtensions.has(ext.key)) {
      return;
    }
    const local = localExtensions.get(ext.key) || null;
    const remote = remoteExtensions.get(ext.key) || null;
    const info = new ExtensionInfo(local, remote);
    allExtensions.set(info.key, info);
  };
  localExtensions.forEach((ext) => collectExtension(ext));
  remoteExtensions.forEach((ext) => collectExtension(ext));
  const extensionHostKinds = /* @__PURE__ */ new Map();
  allExtensions.forEach((ext) => {
    const isInstalledLocally = Boolean(ext.local);
    const isInstalledRemotely = Boolean(ext.remote);
    const isLocallyUnderDevelopment = Boolean(ext.local && ext.local.isUnderDevelopment);
    const isRemotelyUnderDevelopment = Boolean(ext.remote && ext.remote.isUnderDevelopment);
    let preference = 0;
    if (isLocallyUnderDevelopment && !isRemotelyUnderDevelopment) {
      preference = 1;
    } else if (isRemotelyUnderDevelopment && !isLocallyUnderDevelopment) {
      preference = 2;
    }
    extensionHostKinds.set(ext.key, pickExtensionHostKind(ext.identifier, ext.kind, isInstalledLocally, isInstalledRemotely, preference));
  });
  return extensionHostKinds;
}
function toExtensionWithKind(extensions, getExtensionKind) {
  const result = /* @__PURE__ */ new Map();
  extensions.forEach((desc) => {
    const ext = new ExtensionWithKind(desc, getExtensionKind(desc));
    result.set(ext.key, ext);
  });
  return result;
}
var ExtensionWithKind = class {
  constructor(desc, kind) {
    this.desc = desc;
    this.kind = kind;
  }
  get key() {
    return $5z.toKey(this.desc.identifier);
  }
  get isUnderDevelopment() {
    return this.desc.isUnderDevelopment;
  }
};
var ExtensionInfo = class {
  constructor(local, remote) {
    this.local = local;
    this.remote = remote;
  }
  get key() {
    if (this.local) {
      return this.local.key;
    }
    return this.remote.key;
  }
  get identifier() {
    if (this.local) {
      return this.local.desc.identifier;
    }
    return this.remote.desc.identifier;
  }
  get kind() {
    if (this.local) {
      return this.local.kind;
    }
    return this.remote.kind;
  }
};

// out-build/vs/workbench/services/extensions/common/lazyPromise.js
var $mnc = class {
  constructor() {
    this.a = null;
    this.b = null;
    this.d = null;
    this.f = false;
    this.g = null;
    this.h = false;
    this.i = null;
  }
  get [Symbol.toStringTag]() {
    return this.toString();
  }
  j() {
    if (!this.a) {
      this.a = new Promise((c, e) => {
        this.b = c;
        this.d = e;
        if (this.f) {
          this.b(this.g);
        }
        if (this.h) {
          this.d(this.i);
        }
      });
    }
    return this.a;
  }
  resolveOk(value) {
    if (this.f || this.h) {
      return;
    }
    this.f = true;
    this.g = value;
    if (this.a) {
      this.b(value);
    }
  }
  resolveErr(err) {
    if (this.f || this.h) {
      return;
    }
    this.h = true;
    this.i = err;
    if (this.a) {
      this.d(err);
    } else {
      $gb(err);
    }
  }
  then(success, error) {
    return this.j().then(success, error);
  }
  catch(error) {
    return this.j().then(void 0, error);
  }
  finally(callback) {
    return this.j().finally(callback);
  }
};
var $nnc = class extends $mnc {
  constructor() {
    super();
    this.h = true;
    this.i = new $lb();
  }
};

// out-build/vs/workbench/services/extensions/common/rpcProtocol.js
var _a4;
function safeStringify(obj, replacer2) {
  try {
    return JSON.stringify(obj, replacer2);
  } catch (err) {
    return "null";
  }
}
var refSymbolName = "$$ref$$";
var undefinedRef = { [refSymbolName]: -1 };
function $onc(obj, replacer2 = null, useSafeStringify = false) {
  const foundBuffers = [];
  const serialized = (useSafeStringify ? safeStringify : JSON.stringify)(obj, (key2, value) => {
    if (typeof value === "undefined") {
      return undefinedRef;
    } else if (typeof value === "object") {
      if (value instanceof $Ci) {
        const bufferIndex = foundBuffers.push(value) - 1;
        return { [refSymbolName]: bufferIndex };
      }
      if (replacer2) {
        return replacer2(key2, value);
      }
    }
    return value;
  });
  return {
    jsonString: serialized,
    referencedBuffers: foundBuffers
  };
}
function $pnc(jsonString, buffers, uriTransformer) {
  return JSON.parse(jsonString, (_key, value) => {
    if (value) {
      const ref = value[refSymbolName];
      if (typeof ref === "number") {
        return buffers[ref];
      }
      if (uriTransformer && value.$mid === 1) {
        return uriTransformer.transformIncoming(value);
      }
    }
    return value;
  });
}
function stringify(obj, replacer2) {
  return JSON.stringify(obj, replacer2);
}
function createURIReplacer(transformer) {
  if (!transformer) {
    return null;
  }
  return (key2, value) => {
    if (value && value.$mid === 1) {
      return transformer.transformOutgoing(value);
    }
    return value;
  };
}
var RequestInitiator2;
(function(RequestInitiator3) {
  RequestInitiator3[RequestInitiator3["LocalSide"] = 0] = "LocalSide";
  RequestInitiator3[RequestInitiator3["OtherSide"] = 1] = "OtherSide";
})(RequestInitiator2 || (RequestInitiator2 = {}));
var ResponsiveState;
(function(ResponsiveState2) {
  ResponsiveState2[ResponsiveState2["Responsive"] = 0] = "Responsive";
  ResponsiveState2[ResponsiveState2["Unresponsive"] = 1] = "Unresponsive";
})(ResponsiveState || (ResponsiveState = {}));
var noop = () => {
};
var _RPCProtocolSymbol = Symbol.for("rpcProtocol");
var _RPCProxySymbol = Symbol.for("rpcProxy");
var $qnc = class _$qnc extends $3c {
  static {
    _a4 = _RPCProtocolSymbol;
  }
  static {
    this.a = 3 * 1e3;
  }
  // 3s
  constructor(protocol, logger2 = null, transformer = null) {
    super();
    this[_a4] = true;
    this.b = this.B(new $ze());
    this.onDidChangeResponsiveState = this.b.event;
    this.c = protocol;
    this.f = logger2;
    this.g = transformer;
    this.h = createURIReplacer(this.g);
    this.j = false;
    this.m = [];
    this.s = [];
    for (let i2 = 0, len = $BS.count; i2 < len; i2++) {
      this.m[i2] = null;
      this.s[i2] = null;
    }
    this.t = 0;
    this.u = /* @__PURE__ */ Object.create(null);
    this.w = {};
    this.y = 0;
    this.z = 0;
    this.C = 0;
    this.D = this.B(new $8h(() => this.H(), 1e3));
    this.B(this.c.onMessage((msg) => this.L(msg)));
  }
  dispose() {
    this.j = true;
    Object.keys(this.w).forEach((msgId) => {
      const pending = this.w[msgId];
      delete this.w[msgId];
      pending.resolveErr($mb());
    });
    super.dispose();
  }
  drain() {
    if (typeof this.c.drain === "function") {
      return this.c.drain();
    }
    return Promise.resolve();
  }
  F(req) {
    if (this.z === 0) {
      this.C = Date.now() + _$qnc.a;
    }
    this.z++;
    if (!this.D.isScheduled()) {
      this.D.schedule();
    }
  }
  G(req) {
    this.C = Date.now() + _$qnc.a;
    this.z--;
    if (this.z === 0) {
      this.D.cancel();
    }
    this.I(
      0
      /* ResponsiveState.Responsive */
    );
  }
  H() {
    if (this.z === 0) {
      return;
    }
    if (Date.now() > this.C) {
      this.I(
        1
        /* ResponsiveState.Unresponsive */
      );
    } else {
      this.D.schedule();
    }
  }
  I(newResponsiveState) {
    if (this.y === newResponsiveState) {
      return;
    }
    this.y = newResponsiveState;
    this.b.fire(this.y);
  }
  get responsiveState() {
    return this.y;
  }
  transformIncomingURIs(obj) {
    if (!this.g) {
      return obj;
    }
    return $uy(obj, this.g);
  }
  getProxy(identifier2) {
    const { nid: rpcId, sid } = identifier2;
    if (!this.s[rpcId]) {
      this.s[rpcId] = this.J(rpcId, sid);
    }
    return this.s[rpcId];
  }
  J(rpcId, debugName) {
    const handler = {
      get: (target, name) => {
        if (typeof name === "string" && !target[name] && name.charCodeAt(0) === 36) {
          target[name] = (...myArgs) => {
            return this.U(rpcId, name, myArgs);
          };
        }
        if (name === _RPCProxySymbol) {
          return debugName;
        }
        return target[name];
      }
    };
    return new Proxy(/* @__PURE__ */ Object.create(null), handler);
  }
  set(identifier2, value) {
    this.m[identifier2.nid] = value;
    return value;
  }
  assertRegistered(identifiers2) {
    for (let i2 = 0, len = identifiers2.length; i2 < len; i2++) {
      const identifier2 = identifiers2[i2];
      if (!this.m[identifier2.nid]) {
        throw new Error(`Missing proxy instance ${identifier2.sid}`);
      }
    }
  }
  L(rawmsg) {
    if (this.j) {
      return;
    }
    const msgLength = rawmsg.byteLength;
    const buff = MessageBuffer.read(rawmsg, 0);
    const messageType = buff.readUInt8();
    const req = buff.readUInt32();
    switch (messageType) {
      case 1:
      case 2: {
        let { rpcId, method, args: args2 } = MessageIO.deserializeRequestJSONArgs(buff);
        if (this.g) {
          args2 = $uy(args2, this.g);
        }
        this.M(msgLength, req, rpcId, method, args2, messageType === 2);
        break;
      }
      case 3:
      case 4: {
        let { rpcId, method, args: args2 } = MessageIO.deserializeRequestMixedArgs(buff);
        if (this.g) {
          args2 = $uy(args2, this.g);
        }
        this.M(msgLength, req, rpcId, method, args2, messageType === 4);
        break;
      }
      case 5: {
        this.f?.logIncoming(msgLength, req, 0, `ack`);
        this.G(req);
        break;
      }
      case 6: {
        this.N(msgLength, req);
        break;
      }
      case 7: {
        this.O(msgLength, req, void 0);
        break;
      }
      case 9: {
        let value = MessageIO.deserializeReplyOKJSON(buff);
        if (this.g) {
          value = $uy(value, this.g);
        }
        this.O(msgLength, req, value);
        break;
      }
      case 10: {
        const value = MessageIO.deserializeReplyOKJSONWithBuffers(buff, this.g);
        this.O(msgLength, req, value);
        break;
      }
      case 8: {
        const value = MessageIO.deserializeReplyOKVSBuffer(buff);
        this.O(msgLength, req, value);
        break;
      }
      case 11: {
        let err = MessageIO.deserializeReplyErrError(buff);
        if (this.g) {
          err = $uy(err, this.g);
        }
        this.P(msgLength, req, err);
        break;
      }
      case 12: {
        this.P(msgLength, req, void 0);
        break;
      }
      default:
        console.error(`received unexpected message`);
        console.error(rawmsg);
    }
  }
  M(msgLength, req, rpcId, method, args2, usesCancellationToken) {
    this.f?.logIncoming(msgLength, req, 1, `receiveRequest ${$DS(rpcId)}.${method}(`, args2);
    const callId = String(req);
    let promise;
    let cancel;
    if (usesCancellationToken) {
      const cancellationTokenSource = new $ad();
      args2.push(cancellationTokenSource.token);
      promise = this.Q(rpcId, method, args2);
      cancel = () => cancellationTokenSource.cancel();
    } else {
      promise = this.Q(rpcId, method, args2);
      cancel = noop;
    }
    this.u[callId] = cancel;
    const msg = MessageIO.serializeAcknowledged(req);
    this.f?.logOutgoing(msg.byteLength, req, 1, `ack`);
    this.c.send(msg);
    promise.then((r2) => {
      delete this.u[callId];
      const msg2 = MessageIO.serializeReplyOK(req, r2, this.h);
      this.f?.logOutgoing(msg2.byteLength, req, 1, `reply:`, r2);
      this.c.send(msg2);
    }, (err) => {
      delete this.u[callId];
      const msg2 = MessageIO.serializeReplyErr(req, err);
      this.f?.logOutgoing(msg2.byteLength, req, 1, `replyErr:`, err);
      this.c.send(msg2);
    });
  }
  N(msgLength, req) {
    this.f?.logIncoming(msgLength, req, 1, `receiveCancel`);
    const callId = String(req);
    this.u[callId]?.();
  }
  O(msgLength, req, value) {
    this.f?.logIncoming(msgLength, req, 0, `receiveReply:`, value);
    const callId = String(req);
    if (!this.w.hasOwnProperty(callId)) {
      return;
    }
    const pendingReply = this.w[callId];
    delete this.w[callId];
    pendingReply.resolveOk(value);
  }
  P(msgLength, req, value) {
    this.f?.logIncoming(msgLength, req, 0, `receiveReplyErr:`, value);
    const callId = String(req);
    if (!this.w.hasOwnProperty(callId)) {
      return;
    }
    const pendingReply = this.w[callId];
    delete this.w[callId];
    let err = void 0;
    if (value) {
      if (value.$isError) {
        err = new Error();
        err.name = value.name;
        err.message = value.message;
        err.stack = value.stack;
      } else {
        err = value;
      }
    }
    pendingReply.resolveErr(err);
  }
  Q(rpcId, methodName, args2) {
    try {
      return Promise.resolve(this.S(rpcId, methodName, args2));
    } catch (err) {
      return Promise.reject(err);
    }
  }
  S(rpcId, methodName, args2) {
    const actor = this.m[rpcId];
    if (!actor) {
      throw new Error("Unknown actor " + $DS(rpcId));
    }
    const method = actor[methodName];
    if (typeof method !== "function") {
      throw new Error("Unknown method " + methodName + " on actor " + $DS(rpcId));
    }
    return method.apply(actor, args2);
  }
  U(rpcId, methodName, args2) {
    if (this.j) {
      return new $nnc();
    }
    let cancellationToken = null;
    if (args2.length > 0 && CancellationToken.isCancellationToken(args2[args2.length - 1])) {
      cancellationToken = args2.pop();
    }
    if (cancellationToken && cancellationToken.isCancellationRequested) {
      return Promise.reject($mb());
    }
    const serializedRequestArguments = MessageIO.serializeRequestArguments(args2, this.h);
    const req = ++this.t;
    const callId = String(req);
    const result = new $mnc();
    const disposable = new $2c();
    if (cancellationToken) {
      disposable.add(cancellationToken.onCancellationRequested(() => {
        const msg2 = MessageIO.serializeCancel(req);
        this.f?.logOutgoing(msg2.byteLength, req, 0, `cancel`);
        this.c.send(msg2);
      }));
    }
    this.w[callId] = new PendingRPCReply(result, disposable);
    this.F(req);
    const msg = MessageIO.serializeRequest(req, rpcId, methodName, serializedRequestArguments, !!cancellationToken);
    this.f?.logOutgoing(msg.byteLength, req, 0, `request: ${$DS(rpcId)}.${methodName}(`, args2);
    this.c.send(msg);
    return result;
  }
};
var PendingRPCReply = class {
  constructor(a, b) {
    this.a = a;
    this.b = b;
  }
  resolveOk(value) {
    this.a.resolveOk(value);
    this.b.dispose();
  }
  resolveErr(err) {
    this.a.resolveErr(err);
    this.b.dispose();
  }
};
var MessageBuffer = class _MessageBuffer {
  static alloc(type, req, messageSize) {
    const result = new _MessageBuffer($Ci.alloc(
      messageSize + 1 + 4
      /* req */
    ), 0);
    result.writeUInt8(type);
    result.writeUInt32(req);
    return result;
  }
  static read(buff, offset) {
    return new _MessageBuffer(buff, offset);
  }
  get buffer() {
    return this.a;
  }
  constructor(buff, offset) {
    this.a = buff;
    this.b = offset;
  }
  static sizeUInt8() {
    return 1;
  }
  static {
    this.sizeUInt32 = 4;
  }
  writeUInt8(n) {
    this.a.writeUInt8(n, this.b);
    this.b += 1;
  }
  readUInt8() {
    const n = this.a.readUInt8(this.b);
    this.b += 1;
    return n;
  }
  writeUInt32(n) {
    this.a.writeUInt32BE(n, this.b);
    this.b += 4;
  }
  readUInt32() {
    const n = this.a.readUInt32BE(this.b);
    this.b += 4;
    return n;
  }
  static sizeShortString(str) {
    return 1 + str.byteLength;
  }
  writeShortString(str) {
    this.a.writeUInt8(str.byteLength, this.b);
    this.b += 1;
    this.a.set(str, this.b);
    this.b += str.byteLength;
  }
  readShortString() {
    const strByteLength = this.a.readUInt8(this.b);
    this.b += 1;
    const strBuff = this.a.slice(this.b, this.b + strByteLength);
    const str = strBuff.toString();
    this.b += strByteLength;
    return str;
  }
  static sizeLongString(str) {
    return 4 + str.byteLength;
  }
  writeLongString(str) {
    this.a.writeUInt32BE(str.byteLength, this.b);
    this.b += 4;
    this.a.set(str, this.b);
    this.b += str.byteLength;
  }
  readLongString() {
    const strByteLength = this.a.readUInt32BE(this.b);
    this.b += 4;
    const strBuff = this.a.slice(this.b, this.b + strByteLength);
    const str = strBuff.toString();
    this.b += strByteLength;
    return str;
  }
  writeBuffer(buff) {
    this.a.writeUInt32BE(buff.byteLength, this.b);
    this.b += 4;
    this.a.set(buff, this.b);
    this.b += buff.byteLength;
  }
  static sizeVSBuffer(buff) {
    return 4 + buff.byteLength;
  }
  writeVSBuffer(buff) {
    this.a.writeUInt32BE(buff.byteLength, this.b);
    this.b += 4;
    this.a.set(buff, this.b);
    this.b += buff.byteLength;
  }
  readVSBuffer() {
    const buffLength = this.a.readUInt32BE(this.b);
    this.b += 4;
    const buff = this.a.slice(this.b, this.b + buffLength);
    this.b += buffLength;
    return buff;
  }
  static sizeMixedArray(arr) {
    let size = 0;
    size += 1;
    for (let i2 = 0, len = arr.length; i2 < len; i2++) {
      const el = arr[i2];
      size += 1;
      switch (el.type) {
        case 1:
          size += this.sizeLongString(el.value);
          break;
        case 2:
          size += this.sizeVSBuffer(el.value);
          break;
        case 3:
          size += this.sizeUInt32;
          size += this.sizeLongString(el.value);
          for (let i3 = 0; i3 < el.buffers.length; ++i3) {
            size += this.sizeVSBuffer(el.buffers[i3]);
          }
          break;
        case 4:
          break;
      }
    }
    return size;
  }
  writeMixedArray(arr) {
    this.a.writeUInt8(arr.length, this.b);
    this.b += 1;
    for (let i2 = 0, len = arr.length; i2 < len; i2++) {
      const el = arr[i2];
      switch (el.type) {
        case 1:
          this.writeUInt8(
            1
            /* ArgType.String */
          );
          this.writeLongString(el.value);
          break;
        case 2:
          this.writeUInt8(
            2
            /* ArgType.VSBuffer */
          );
          this.writeVSBuffer(el.value);
          break;
        case 3:
          this.writeUInt8(
            3
            /* ArgType.SerializedObjectWithBuffers */
          );
          this.writeUInt32(el.buffers.length);
          this.writeLongString(el.value);
          for (let i3 = 0; i3 < el.buffers.length; ++i3) {
            this.writeBuffer(el.buffers[i3]);
          }
          break;
        case 4:
          this.writeUInt8(
            4
            /* ArgType.Undefined */
          );
          break;
      }
    }
  }
  readMixedArray() {
    const arrLen = this.a.readUInt8(this.b);
    this.b += 1;
    const arr = new Array(arrLen);
    for (let i2 = 0; i2 < arrLen; i2++) {
      const argType = this.readUInt8();
      switch (argType) {
        case 1:
          arr[i2] = this.readLongString();
          break;
        case 2:
          arr[i2] = this.readVSBuffer();
          break;
        case 3: {
          const bufferCount = this.readUInt32();
          const jsonString = this.readLongString();
          const buffers = [];
          for (let i3 = 0; i3 < bufferCount; ++i3) {
            buffers.push(this.readVSBuffer());
          }
          arr[i2] = new $ES($pnc(jsonString, buffers, null));
          break;
        }
        case 4:
          arr[i2] = void 0;
          break;
      }
    }
    return arr;
  }
};
var SerializedRequestArgumentType;
(function(SerializedRequestArgumentType2) {
  SerializedRequestArgumentType2[SerializedRequestArgumentType2["Simple"] = 0] = "Simple";
  SerializedRequestArgumentType2[SerializedRequestArgumentType2["Mixed"] = 1] = "Mixed";
})(SerializedRequestArgumentType || (SerializedRequestArgumentType = {}));
var MessageIO = class {
  static a(arr) {
    for (let i2 = 0, len = arr.length; i2 < len; i2++) {
      if (arr[i2] instanceof $Ci) {
        return true;
      }
      if (arr[i2] instanceof $ES) {
        return true;
      }
      if (typeof arr[i2] === "undefined") {
        return true;
      }
    }
    return false;
  }
  static serializeRequestArguments(args2, replacer2) {
    if (this.a(args2)) {
      const massagedArgs = [];
      for (let i2 = 0, len = args2.length; i2 < len; i2++) {
        const arg = args2[i2];
        if (arg instanceof $Ci) {
          massagedArgs[i2] = { type: 2, value: arg };
        } else if (typeof arg === "undefined") {
          massagedArgs[i2] = {
            type: 4
            /* ArgType.Undefined */
          };
        } else if (arg instanceof $ES) {
          const { jsonString, referencedBuffers } = $onc(arg.value, replacer2);
          massagedArgs[i2] = { type: 3, value: $Ci.fromString(jsonString), buffers: referencedBuffers };
        } else {
          massagedArgs[i2] = { type: 1, value: $Ci.fromString(stringify(arg, replacer2)) };
        }
      }
      return {
        type: 1,
        args: massagedArgs
      };
    }
    return {
      type: 0,
      args: stringify(args2, replacer2)
    };
  }
  static serializeRequest(req, rpcId, method, serializedArgs, usesCancellationToken) {
    switch (serializedArgs.type) {
      case 0:
        return this.b(req, rpcId, method, serializedArgs.args, usesCancellationToken);
      case 1:
        return this.c(req, rpcId, method, serializedArgs.args, usesCancellationToken);
    }
  }
  static b(req, rpcId, method, args2, usesCancellationToken) {
    const methodBuff = $Ci.fromString(method);
    const argsBuff = $Ci.fromString(args2);
    let len = 0;
    len += MessageBuffer.sizeUInt8();
    len += MessageBuffer.sizeShortString(methodBuff);
    len += MessageBuffer.sizeLongString(argsBuff);
    const result = MessageBuffer.alloc(usesCancellationToken ? 2 : 1, req, len);
    result.writeUInt8(rpcId);
    result.writeShortString(methodBuff);
    result.writeLongString(argsBuff);
    return result.buffer;
  }
  static deserializeRequestJSONArgs(buff) {
    const rpcId = buff.readUInt8();
    const method = buff.readShortString();
    const args2 = buff.readLongString();
    return {
      rpcId,
      method,
      args: JSON.parse(args2)
    };
  }
  static c(req, rpcId, method, args2, usesCancellationToken) {
    const methodBuff = $Ci.fromString(method);
    let len = 0;
    len += MessageBuffer.sizeUInt8();
    len += MessageBuffer.sizeShortString(methodBuff);
    len += MessageBuffer.sizeMixedArray(args2);
    const result = MessageBuffer.alloc(usesCancellationToken ? 4 : 3, req, len);
    result.writeUInt8(rpcId);
    result.writeShortString(methodBuff);
    result.writeMixedArray(args2);
    return result.buffer;
  }
  static deserializeRequestMixedArgs(buff) {
    const rpcId = buff.readUInt8();
    const method = buff.readShortString();
    const rawargs = buff.readMixedArray();
    const args2 = new Array(rawargs.length);
    for (let i2 = 0, len = rawargs.length; i2 < len; i2++) {
      const rawarg = rawargs[i2];
      if (typeof rawarg === "string") {
        args2[i2] = JSON.parse(rawarg);
      } else {
        args2[i2] = rawarg;
      }
    }
    return {
      rpcId,
      method,
      args: args2
    };
  }
  static serializeAcknowledged(req) {
    return MessageBuffer.alloc(5, req, 0).buffer;
  }
  static serializeCancel(req) {
    return MessageBuffer.alloc(6, req, 0).buffer;
  }
  static serializeReplyOK(req, res, replacer2) {
    if (typeof res === "undefined") {
      return this.d(req);
    } else if (res instanceof $Ci) {
      return this.e(req, res);
    } else if (res instanceof $ES) {
      const { jsonString, referencedBuffers } = $onc(res.value, replacer2, true);
      return this.g(req, jsonString, referencedBuffers);
    } else {
      return this.f(req, safeStringify(res, replacer2));
    }
  }
  static d(req) {
    return MessageBuffer.alloc(7, req, 0).buffer;
  }
  static e(req, res) {
    let len = 0;
    len += MessageBuffer.sizeVSBuffer(res);
    const result = MessageBuffer.alloc(8, req, len);
    result.writeVSBuffer(res);
    return result.buffer;
  }
  static deserializeReplyOKVSBuffer(buff) {
    return buff.readVSBuffer();
  }
  static f(req, res) {
    const resBuff = $Ci.fromString(res);
    let len = 0;
    len += MessageBuffer.sizeLongString(resBuff);
    const result = MessageBuffer.alloc(9, req, len);
    result.writeLongString(resBuff);
    return result.buffer;
  }
  static g(req, res, buffers) {
    const resBuff = $Ci.fromString(res);
    let len = 0;
    len += MessageBuffer.sizeUInt32;
    len += MessageBuffer.sizeLongString(resBuff);
    for (const buffer of buffers) {
      len += MessageBuffer.sizeVSBuffer(buffer);
    }
    const result = MessageBuffer.alloc(10, req, len);
    result.writeUInt32(buffers.length);
    result.writeLongString(resBuff);
    for (const buffer of buffers) {
      result.writeBuffer(buffer);
    }
    return result.buffer;
  }
  static deserializeReplyOKJSON(buff) {
    const res = buff.readLongString();
    return JSON.parse(res);
  }
  static deserializeReplyOKJSONWithBuffers(buff, uriTransformer) {
    const bufferCount = buff.readUInt32();
    const res = buff.readLongString();
    const buffers = [];
    for (let i2 = 0; i2 < bufferCount; ++i2) {
      buffers.push(buff.readVSBuffer());
    }
    return new $ES($pnc(res, buffers, uriTransformer));
  }
  static serializeReplyErr(req, err) {
    const errStr = err ? safeStringify($ib(err), null) : void 0;
    if (typeof errStr !== "string") {
      return this.h(req);
    }
    const errBuff = $Ci.fromString(errStr);
    let len = 0;
    len += MessageBuffer.sizeLongString(errBuff);
    const result = MessageBuffer.alloc(11, req, len);
    result.writeLongString(errBuff);
    return result.buffer;
  }
  static deserializeReplyErrError(buff) {
    const err = buff.readLongString();
    return JSON.parse(err);
  }
  static h(req) {
    return MessageBuffer.alloc(12, req, 0).buffer;
  }
};
var MessageType4;
(function(MessageType5) {
  MessageType5[MessageType5["RequestJSONArgs"] = 1] = "RequestJSONArgs";
  MessageType5[MessageType5["RequestJSONArgsWithCancellation"] = 2] = "RequestJSONArgsWithCancellation";
  MessageType5[MessageType5["RequestMixedArgs"] = 3] = "RequestMixedArgs";
  MessageType5[MessageType5["RequestMixedArgsWithCancellation"] = 4] = "RequestMixedArgsWithCancellation";
  MessageType5[MessageType5["Acknowledged"] = 5] = "Acknowledged";
  MessageType5[MessageType5["Cancel"] = 6] = "Cancel";
  MessageType5[MessageType5["ReplyOKEmpty"] = 7] = "ReplyOKEmpty";
  MessageType5[MessageType5["ReplyOKVSBuffer"] = 8] = "ReplyOKVSBuffer";
  MessageType5[MessageType5["ReplyOKJSON"] = 9] = "ReplyOKJSON";
  MessageType5[MessageType5["ReplyOKJSONWithBuffers"] = 10] = "ReplyOKJSONWithBuffers";
  MessageType5[MessageType5["ReplyErrError"] = 11] = "ReplyErrError";
  MessageType5[MessageType5["ReplyErrEmpty"] = 12] = "ReplyErrEmpty";
})(MessageType4 || (MessageType4 = {}));
var ArgType;
(function(ArgType2) {
  ArgType2[ArgType2["String"] = 1] = "String";
  ArgType2[ArgType2["VSBuffer"] = 2] = "VSBuffer";
  ArgType2[ArgType2["SerializedObjectWithBuffers"] = 3] = "SerializedObjectWithBuffers";
  ArgType2[ArgType2["Undefined"] = 4] = "Undefined";
})(ArgType || (ArgType = {}));

// out-build/vs/workbench/services/extensions/common/extensionHostManager.js
var $rnc_1;
var LOG_EXTENSION_HOST_COMMUNICATION = false;
var LOG_USE_COLORS = true;
var $rnc = $rnc_1 = class $rnc2 extends $3c {
  get pid() {
    return this.h.pid;
  }
  get kind() {
    return this.h.runningLocation.kind;
  }
  get startup() {
    return this.h.startup;
  }
  get friendyName() {
    return $snc(this.kind, this.pid);
  }
  constructor(extensionHost, initialActivationEvents, s, t, u, w, y) {
    super();
    this.s = s;
    this.t = t;
    this.u = u;
    this.w = w;
    this.y = y;
    this.a = this.B(new $ze());
    this.onDidChangeResponsiveState = this.a.event;
    this.r = false;
    this.b = /* @__PURE__ */ new Map();
    this.c = /* @__PURE__ */ new Set();
    this.f = null;
    this.g = [];
    this.h = extensionHost;
    this.onDidExit = this.h.onExit;
    const startingTelemetryEvent = {
      time: Date.now(),
      action: "starting",
      kind: $gN(this.kind)
    };
    this.w.publicLog2("extensionHostStartup", startingTelemetryEvent);
    this.j = this.h.start().then((protocol) => {
      this.r = true;
      const successTelemetryEvent = {
        time: Date.now(),
        action: "success",
        kind: $gN(this.kind)
      };
      this.w.publicLog2("extensionHostStartup", successTelemetryEvent);
      return this.H(this.kind, protocol);
    }, (err) => {
      this.y.error(`Error received from starting extension host (kind: ${$gN(this.kind)})`);
      this.y.error(err);
      const failureTelemetryEvent = {
        time: Date.now(),
        action: "error",
        kind: $gN(this.kind)
      };
      if (err && err.name) {
        failureTelemetryEvent.errorName = err.name;
      }
      if (err && err.message) {
        failureTelemetryEvent.errorMessage = err.message;
      }
      if (err && err.stack) {
        failureTelemetryEvent.errorStack = err.stack;
      }
      this.w.publicLog2("extensionHostStartup", failureTelemetryEvent);
      return null;
    });
    this.j.then(() => {
      initialActivationEvents.forEach((activationEvent) => this.activateByEvent(
        activationEvent,
        0
        /* ActivationKind.Normal */
      ));
      this.B(registerLatencyTestProvider({
        measure: () => this.z()
      }));
    });
  }
  async disconnect() {
    await this.h?.disconnect?.();
  }
  dispose() {
    this.h?.dispose();
    this.f?.dispose();
    for (let i2 = 0, len = this.g.length; i2 < len; i2++) {
      const customer = this.g[i2];
      try {
        customer.dispose();
      } catch (err) {
        $gb(err);
      }
    }
    this.j = null;
    super.dispose();
  }
  async z() {
    const proxy = await this.j;
    if (!proxy) {
      return null;
    }
    const latency = await this.C(proxy);
    const down = await this.G(proxy);
    const up = await this.F(proxy);
    return {
      remoteAuthority: this.h.remoteAuthority,
      latency,
      down,
      up
    };
  }
  async ready() {
    await this.j;
  }
  async C(proxy) {
    const COUNT = 10;
    let sum = 0;
    for (let i2 = 0; i2 < COUNT; i2++) {
      const sw = $te.create();
      await proxy.test_latency(i2);
      sw.stop();
      sum += sw.elapsed();
    }
    return sum / COUNT;
  }
  static D(byteCount, elapsedMillis) {
    return byteCount * 1e3 * 8 / elapsedMillis;
  }
  async F(proxy) {
    const SIZE = 10 * 1024 * 1024;
    const buff = $Ci.alloc(SIZE);
    const value = Math.ceil(Math.random() * 256);
    for (let i2 = 0; i2 < buff.byteLength; i2++) {
      buff.writeUInt8(i2, value);
    }
    const sw = $te.create();
    await proxy.test_up(buff);
    sw.stop();
    return $rnc_1.D(SIZE, sw.elapsed());
  }
  async G(proxy) {
    const SIZE = 10 * 1024 * 1024;
    const sw = $te.create();
    await proxy.test_down(SIZE);
    sw.stop();
    return $rnc_1.D(SIZE, sw.elapsed());
  }
  H(kind, protocol) {
    let logger2 = null;
    if (LOG_EXTENSION_HOST_COMMUNICATION || this.u.logExtensionHostCommunication) {
      logger2 = new RPCLogger(kind);
    } else if (TelemetryRPCLogger.isEnabled()) {
      logger2 = new TelemetryRPCLogger(this.w);
    }
    this.f = new $qnc(protocol, logger2);
    this.B(this.f.onDidChangeResponsiveState((responsiveState) => this.a.fire(responsiveState)));
    let extensionHostProxy = null;
    let mainProxyIdentifiers = [];
    const extHostContext = {
      remoteAuthority: this.h.remoteAuthority,
      extensionHostKind: this.kind,
      getProxy: (identifier2) => this.f.getProxy(identifier2),
      set: (identifier2, instance2) => this.f.set(identifier2, instance2),
      dispose: () => this.f.dispose(),
      assertRegistered: (identifiers2) => this.f.assertRegistered(identifiers2),
      drain: () => this.f.drain(),
      //#region internal
      internalExtensionService: this.s,
      _setExtensionHostProxy: (value) => {
        extensionHostProxy = value;
      },
      _setAllMainProxyIdentifiers: (value) => {
        mainProxyIdentifiers = value;
      }
      //#endregion
    };
    const namedCustomers = ExtHostCustomersRegistry.getNamedCustomers();
    for (let i2 = 0, len = namedCustomers.length; i2 < len; i2++) {
      const [id2, ctor] = namedCustomers[i2];
      try {
        const instance2 = this.t.createInstance(ctor, extHostContext);
        this.g.push(instance2);
        this.f.set(id2, instance2);
      } catch (err) {
        this.y.error(`Cannot instantiate named customer: '${id2.sid}'`);
        this.y.error(err);
        $gb(err);
      }
    }
    const customers = ExtHostCustomersRegistry.getCustomers();
    for (const ctor of customers) {
      try {
        const instance2 = this.t.createInstance(ctor, extHostContext);
        this.g.push(instance2);
      } catch (err) {
        this.y.error(err);
        $gb(err);
      }
    }
    if (!extensionHostProxy) {
      throw new Error(`Missing IExtensionHostProxy!`);
    }
    this.f.assertRegistered(mainProxyIdentifiers);
    return extensionHostProxy;
  }
  async activate(extension, reason) {
    const proxy = await this.j;
    if (!proxy) {
      return false;
    }
    return proxy.activate(extension, reason);
  }
  activateByEvent(activationEvent, activationKind) {
    if (activationKind === 1 && !this.r) {
      return Promise.resolve();
    }
    if (!this.b.has(activationEvent)) {
      this.b.set(activationEvent, this.I(activationEvent, activationKind));
    }
    return this.b.get(activationEvent);
  }
  activationEventIsDone(activationEvent) {
    return this.c.has(activationEvent);
  }
  async I(activationEvent, activationKind) {
    if (!this.j) {
      return;
    }
    const proxy = await this.j;
    if (!proxy) {
      return;
    }
    if (!this.h.extensions.containsActivationEvent(activationEvent)) {
      this.c.add(activationEvent);
      return;
    }
    await proxy.activateByEvent(activationEvent, activationKind);
    this.c.add(activationEvent);
  }
  async getInspectPort(tryEnableInspector) {
    if (this.h) {
      if (tryEnableInspector) {
        await this.h.enableInspectPort();
      }
      const port = this.h.getInspectPort();
      if (port) {
        return port;
      }
    }
    return void 0;
  }
  async resolveAuthority(remoteAuthority, resolveAttempt) {
    const sw = $te.create(false);
    const prefix = () => `[${$gN(this.h.runningLocation.kind)}${this.h.runningLocation.affinity}][resolveAuthority(${$fC(remoteAuthority)},${resolveAttempt})][${sw.elapsed()}ms] `;
    const logInfo = (msg) => this.y.info(`${prefix()}${msg}`);
    const logError = (msg, err = void 0) => this.y.error(`${prefix()}${msg}`, err);
    logInfo(`obtaining proxy...`);
    const proxy = await this.j;
    if (!proxy) {
      logError(`no proxy`);
      return {
        type: "error",
        error: {
          message: `Cannot resolve authority`,
          code: RemoteAuthorityResolverErrorCode.Unknown,
          detail: void 0
        }
      };
    }
    logInfo(`invoking...`);
    const intervalLogger = new $7h();
    try {
      intervalLogger.cancelAndSet(() => logInfo("waiting..."), 1e3);
      const resolverResult = await proxy.resolveAuthority(remoteAuthority, resolveAttempt);
      intervalLogger.dispose();
      if (resolverResult.type === "ok") {
        logInfo(`returned ${resolverResult.value.authority.connectTo}`);
      } else {
        logError(`returned an error`, resolverResult.error);
      }
      return resolverResult;
    } catch (err) {
      intervalLogger.dispose();
      logError(`returned an error`, err);
      return {
        type: "error",
        error: {
          message: err.message,
          code: RemoteAuthorityResolverErrorCode.Unknown,
          detail: err
        }
      };
    }
  }
  async getCanonicalURI(remoteAuthority, uri) {
    const proxy = await this.j;
    if (!proxy) {
      throw new Error(`Cannot resolve canonical URI`);
    }
    return proxy.getCanonicalURI(remoteAuthority, uri);
  }
  async start(extensionRegistryVersionId, allExtensions, myExtensions) {
    const proxy = await this.j;
    if (!proxy) {
      return;
    }
    const deltaExtensions = this.h.extensions.set(extensionRegistryVersionId, allExtensions, myExtensions);
    return proxy.startExtensionHost(deltaExtensions);
  }
  async extensionTestsExecute() {
    const proxy = await this.j;
    if (!proxy) {
      throw new Error("Could not obtain Extension Host Proxy");
    }
    return proxy.extensionTestsExecute();
  }
  representsRunningLocation(runningLocation) {
    return this.h.runningLocation.equals(runningLocation);
  }
  async deltaExtensions(incomingExtensionsDelta) {
    const proxy = await this.j;
    if (!proxy) {
      return;
    }
    const outgoingExtensionsDelta = this.h.extensions.delta(incomingExtensionsDelta);
    if (!outgoingExtensionsDelta) {
      return;
    }
    return proxy.deltaExtensions(outgoingExtensionsDelta);
  }
  containsExtension(extensionId) {
    return this.h.extensions?.containsExtension(extensionId) ?? false;
  }
  async setRemoteEnvironment(env3) {
    const proxy = await this.j;
    if (!proxy) {
      return;
    }
    return proxy.setRemoteEnvironment(env3);
  }
};
$rnc = $rnc_1 = __decorate([
  __param(3, $Pk),
  __param(4, $US),
  __param(5, $zv),
  __param(6, $wn)
], $rnc);
function $snc(kind, pid) {
  if (pid) {
    return `${$gN(kind)} pid: ${pid}`;
  }
  return `${$gN(kind)}`;
}
var colorTables = [
  ["#2977B1", "#FC802D", "#34A13A", "#D3282F", "#9366BA"],
  ["#8B564C", "#E177C0", "#7F7F7F", "#BBBE3D", "#2EBECD"]
];
function prettyWithoutArrays(data) {
  if (Array.isArray(data)) {
    return data;
  }
  if (data && typeof data === "object" && typeof data.toString === "function") {
    const result = data.toString();
    if (result !== "[object Object]") {
      return result;
    }
  }
  return data;
}
function pretty(data) {
  if (Array.isArray(data)) {
    return data.map(prettyWithoutArrays);
  }
  return prettyWithoutArrays(data);
}
var RPCLogger = class {
  constructor(c) {
    this.c = c;
    this.a = 0;
    this.b = 0;
  }
  d(direction, totalLength, msgLength, req, initiator, str, data) {
    data = pretty(data);
    const colorTable = colorTables[initiator];
    const color2 = LOG_USE_COLORS ? colorTable[req % colorTable.length] : "#000000";
    let args2 = [`%c[${$gN(this.c)}][${direction}]%c[${String(totalLength).padStart(7)}]%c[len: ${String(msgLength).padStart(5)}]%c${String(req).padStart(5)} - ${str}`, "color: darkgreen", "color: grey", "color: grey", `color: ${color2}`];
    if (/\($/.test(str)) {
      args2 = args2.concat(data);
      args2.push(")");
    } else {
      args2.push(data);
    }
    console.log.apply(console, args2);
  }
  logIncoming(msgLength, req, initiator, str, data) {
    this.a += msgLength;
    this.d("Ext \u2192 Win", this.a, msgLength, req, initiator, str, data);
  }
  logOutgoing(msgLength, req, initiator, str, data) {
    this.b += msgLength;
    this.d("Win \u2192 Ext", this.b, msgLength, req, initiator, str, data);
  }
};
var TelemetryRPCLogger = class TelemetryRPCLogger2 {
  static isEnabled() {
    return Math.trunc(Math.random() * 1e3) < 0.5;
  }
  constructor(b) {
    this.b = b;
    this.a = /* @__PURE__ */ new Map();
  }
  logIncoming(msgLength, req, initiator, str) {
    if (initiator === 0 && /^receiveReply(Err)?:/.test(str)) {
      const requestStr = this.a.get(req) ?? "unknown_reply";
      this.a.delete(req);
      this.b.publicLog2("extensionhost.incoming", {
        type: `${str} ${requestStr}`,
        length: msgLength
      });
    }
    if (initiator === 1 && /^receiveRequest /.test(str)) {
      this.b.publicLog2("extensionhost.incoming", {
        type: `${str}`,
        length: msgLength
      });
    }
  }
  logOutgoing(msgLength, req, initiator, str) {
    if (initiator === 0 && str.startsWith("request: ")) {
      this.a.set(req, str);
      this.b.publicLog2("extensionhost.outgoing", {
        type: str,
        length: msgLength
      });
    }
  }
};
TelemetryRPCLogger = __decorate([
  __param(0, $zv)
], TelemetryRPCLogger);
var providers = [];
function registerLatencyTestProvider(provider) {
  providers.push(provider);
  return {
    dispose: () => {
      for (let i2 = 0; i2 < providers.length; i2++) {
        if (providers[i2] === provider) {
          providers.splice(i2, 1);
          return;
        }
      }
    }
  };
}
function getLatencyTestProviders() {
  return providers.slice(0);
}
$hJ(class MeasureExtHostLatencyAction extends $gJ {
  constructor() {
    super({
      id: "editor.action.measureExtHostLatency",
      title: localize2(12806, "Measure Extension Host Latency"),
      category: $qn.Developer,
      f1: true
    });
  }
  async run(accessor) {
    const editorService = accessor.get($mJ);
    const measurements = await Promise.all(getLatencyTestProviders().map((provider) => provider.measure()));
    editorService.openEditor({ resource: void 0, contents: measurements.map(MeasureExtHostLatencyAction.a).join("\n\n"), options: { pinned: true } });
  }
  static a(m) {
    if (!m) {
      return "";
    }
    return `${m.remoteAuthority ? `Authority: ${m.remoteAuthority}
` : ``}Roundtrip latency: ${m.latency.toFixed(3)}ms
Up: ${MeasureExtHostLatencyAction.b(m.up)}
Down: ${MeasureExtHostLatencyAction.b(m.down)}
`;
  }
  static b(n) {
    if (n <= 1024) {
      return `${n} bps`;
    }
    if (n < 1024 * 1024) {
      return `${(n / 1024).toFixed(1)} kbps`;
    }
    return `${(n / 1024 / 1024).toFixed(1)} Mbps`;
  }
});

// out-build/vs/workbench/services/extensions/common/extensionRunningLocationTracker.js
var $tnc = class $tnc2 {
  get maxLocalProcessAffinity() {
    return this.b;
  }
  get maxLocalWebWorkerAffinity() {
    return this.c;
  }
  constructor(d, f, g, h3, i2, j) {
    this.d = d;
    this.f = f;
    this.g = g;
    this.h = h3;
    this.i = i2;
    this.j = j;
    this.a = new $7z();
    this.b = 0;
    this.c = 0;
  }
  set(extensionId, runningLocation) {
    this.a.set(extensionId, runningLocation);
  }
  readExtensionKinds(extensionDescription) {
    if (extensionDescription.isUnderDevelopment && this.g.extensionDevelopmentKind) {
      return this.g.extensionDevelopmentKind;
    }
    return this.j.getExtensionKind(extensionDescription);
  }
  getRunningLocation(extensionId) {
    return this.a.get(extensionId) || null;
  }
  filterByRunningLocation(extensions, desiredRunningLocation) {
    return $unc(extensions, this.a, (extRunningLocation) => desiredRunningLocation.equals(extRunningLocation));
  }
  filterByExtensionHostKind(extensions, desiredExtensionHostKind) {
    return $unc(extensions, this.a, (extRunningLocation) => extRunningLocation.kind === desiredExtensionHostKind);
  }
  filterByExtensionHostManager(extensions, extensionHostManager) {
    return $unc(extensions, this.a, (extRunningLocation) => extensionHostManager.representsRunningLocation(extRunningLocation));
  }
  k(inputExtensions, extensionHostKind, isInitialAllocation) {
    const extensions = new $7z();
    for (const extension of inputExtensions) {
      if (extension.main || extension.browser) {
        extensions.set(extension.identifier, extension);
      }
    }
    for (const extension of this.d.getAllExtensionDescriptions()) {
      if (extension.main || extension.browser) {
        const runningLocation = this.a.get(extension.identifier);
        if (runningLocation && runningLocation.kind === extensionHostKind) {
          extensions.set(extension.identifier, extension);
        }
      }
    }
    const groups = new $7z();
    let groupNumber = 0;
    for (const [_, extension] of extensions) {
      groups.set(extension.identifier, ++groupNumber);
    }
    const changeGroup = (from, to) => {
      for (const [key2, group2] of groups) {
        if (group2 === from) {
          groups.set(key2, to);
        }
      }
    };
    for (const [_, extension] of extensions) {
      if (!extension.extensionDependencies) {
        continue;
      }
      const myGroup = groups.get(extension.identifier);
      for (const depId of extension.extensionDependencies) {
        const depGroup = groups.get(depId);
        if (!depGroup) {
          continue;
        }
        if (depGroup === myGroup) {
          continue;
        }
        changeGroup(depGroup, myGroup);
      }
    }
    const resultingAffinities = /* @__PURE__ */ new Map();
    let lastAffinity = 0;
    for (const [_, extension] of extensions) {
      const runningLocation = this.a.get(extension.identifier);
      if (runningLocation) {
        const group2 = groups.get(extension.identifier);
        resultingAffinities.set(group2, runningLocation.affinity);
        lastAffinity = Math.max(lastAffinity, runningLocation.affinity);
      }
    }
    if (!this.g.isExtensionDevelopment) {
      const configuredAffinities = this.h.getValue("extensions.experimental.affinity") || {};
      const configuredExtensionIds = Object.keys(configuredAffinities);
      const configuredAffinityToResultingAffinity = /* @__PURE__ */ new Map();
      for (const extensionId of configuredExtensionIds) {
        const configuredAffinity = configuredAffinities[extensionId];
        if (typeof configuredAffinity !== "number" || configuredAffinity <= 0 || Math.floor(configuredAffinity) !== configuredAffinity) {
          this.i.info(`Ignoring configured affinity for '${extensionId}' because the value is not a positive integer.`);
          continue;
        }
        const group2 = groups.get(extensionId);
        if (!group2) {
          continue;
        }
        const affinity1 = resultingAffinities.get(group2);
        if (affinity1) {
          configuredAffinityToResultingAffinity.set(configuredAffinity, affinity1);
          continue;
        }
        const affinity2 = configuredAffinityToResultingAffinity.get(configuredAffinity);
        if (affinity2) {
          resultingAffinities.set(group2, affinity2);
          continue;
        }
        if (!isInitialAllocation) {
          this.i.info(`Ignoring configured affinity for '${extensionId}' because extension host(s) are already running. Reload window.`);
          continue;
        }
        const affinity3 = ++lastAffinity;
        configuredAffinityToResultingAffinity.set(configuredAffinity, affinity3);
        resultingAffinities.set(group2, affinity3);
      }
    }
    const result = new $7z();
    for (const extension of inputExtensions) {
      const group2 = groups.get(extension.identifier) || 0;
      const affinity = resultingAffinities.get(group2) || 0;
      result.set(extension.identifier, affinity);
    }
    if (lastAffinity > 0 && isInitialAllocation) {
      for (let affinity = 1; affinity <= lastAffinity; affinity++) {
        const extensionIds = [];
        for (const extension of inputExtensions) {
          if (result.get(extension.identifier) === affinity) {
            extensionIds.push(extension.identifier);
          }
        }
        this.i.info(`Placing extension(s) ${extensionIds.map((e) => e.value).join(", ")} on a separate extension host.`);
      }
    }
    return { affinities: result, maxAffinity: lastAffinity };
  }
  computeRunningLocation(localExtensions, remoteExtensions, isInitialAllocation) {
    return this.l(this.a, localExtensions, remoteExtensions, isInitialAllocation).runningLocation;
  }
  l(existingRunningLocation, localExtensions, remoteExtensions, isInitialAllocation) {
    localExtensions = localExtensions.filter((extension) => !existingRunningLocation.has(extension.identifier));
    remoteExtensions = remoteExtensions.filter((extension) => !existingRunningLocation.has(extension.identifier));
    const extensionHostKinds = $iN(localExtensions, remoteExtensions, (extension) => this.readExtensionKinds(extension), (extensionId, extensionKinds, isInstalledLocally, isInstalledRemotely, preference) => this.f.pickExtensionHostKind(extensionId, extensionKinds, isInstalledLocally, isInstalledRemotely, preference));
    const extensions = new $7z();
    for (const extension of localExtensions) {
      extensions.set(extension.identifier, extension);
    }
    for (const extension of remoteExtensions) {
      extensions.set(extension.identifier, extension);
    }
    const result = new $7z();
    const localProcessExtensions = [];
    const localWebWorkerExtensions = [];
    for (const [extensionIdKey, extensionHostKind] of extensionHostKinds) {
      let runningLocation = null;
      if (extensionHostKind === 1) {
        const extensionDescription = extensions.get(extensionIdKey);
        if (extensionDescription) {
          localProcessExtensions.push(extensionDescription);
        }
      } else if (extensionHostKind === 2) {
        const extensionDescription = extensions.get(extensionIdKey);
        if (extensionDescription) {
          localWebWorkerExtensions.push(extensionDescription);
        }
      } else if (extensionHostKind === 3) {
        runningLocation = new $nN();
      }
      result.set(extensionIdKey, runningLocation);
    }
    const { affinities, maxAffinity } = this.k(localProcessExtensions, 1, isInitialAllocation);
    for (const extension of localProcessExtensions) {
      const affinity = affinities.get(extension.identifier) || 0;
      result.set(extension.identifier, new $lN(affinity));
    }
    const { affinities: localWebWorkerAffinities, maxAffinity: maxLocalWebWorkerAffinity } = this.k(localWebWorkerExtensions, 2, isInitialAllocation);
    for (const extension of localWebWorkerExtensions) {
      const affinity = localWebWorkerAffinities.get(extension.identifier) || 0;
      result.set(extension.identifier, new $mN(affinity));
    }
    for (const [extensionIdKey, runningLocation] of existingRunningLocation) {
      if (runningLocation) {
        result.set(extensionIdKey, runningLocation);
      }
    }
    return { runningLocation: result, maxLocalProcessAffinity: maxAffinity, maxLocalWebWorkerAffinity };
  }
  initializeRunningLocation(localExtensions, remoteExtensions) {
    const { runningLocation, maxLocalProcessAffinity, maxLocalWebWorkerAffinity } = this.l(this.a, localExtensions, remoteExtensions, true);
    this.a = runningLocation;
    this.b = maxLocalProcessAffinity;
    this.c = maxLocalWebWorkerAffinity;
  }
  /**
   * Returns the running locations for the removed extensions.
   */
  deltaExtensions(toAdd, toRemove) {
    const removedRunningLocation = new $7z();
    for (const extensionId of toRemove) {
      const extensionKey = extensionId;
      removedRunningLocation.set(extensionKey, this.a.get(extensionKey) || null);
      this.a.delete(extensionKey);
    }
    this.m(toAdd);
    return removedRunningLocation;
  }
  /**
   * Update `this._runningLocation` with running locations for newly enabled/installed extensions.
   */
  m(toAdd) {
    const localProcessExtensions = [];
    const localWebWorkerExtensions = [];
    for (const extension of toAdd) {
      const extensionKind = this.readExtensionKinds(extension);
      const isRemote = extension.extensionLocation.scheme === Schemas.vscodeRemote;
      const extensionHostKind = this.f.pickExtensionHostKind(
        extension.identifier,
        extensionKind,
        !isRemote,
        isRemote,
        0
        /* ExtensionRunningPreference.None */
      );
      let runningLocation = null;
      if (extensionHostKind === 1) {
        localProcessExtensions.push(extension);
      } else if (extensionHostKind === 2) {
        localWebWorkerExtensions.push(extension);
      } else if (extensionHostKind === 3) {
        runningLocation = new $nN();
      }
      this.a.set(extension.identifier, runningLocation);
    }
    const { affinities } = this.k(localProcessExtensions, 1, false);
    for (const extension of localProcessExtensions) {
      const affinity = affinities.get(extension.identifier) || 0;
      this.a.set(extension.identifier, new $lN(affinity));
    }
    const { affinities: webWorkerExtensionsAffinities } = this.k(localWebWorkerExtensions, 2, false);
    for (const extension of localWebWorkerExtensions) {
      const affinity = webWorkerExtensionsAffinities.get(extension.identifier) || 0;
      this.a.set(extension.identifier, new $mN(affinity));
    }
  }
};
$tnc = __decorate([
  __param(2, $US),
  __param(3, $kl),
  __param(4, $wn),
  __param(5, $LCb)
], $tnc);
function $unc(extensions, runningLocation, predicate) {
  return extensions.filter((ext) => {
    const extRunningLocation = runningLocation.get(ext.identifier);
    return extRunningLocation && predicate(extRunningLocation);
  });
}
function $vnc(extensions, runningLocation, predicate) {
  return extensions.filter((ext) => {
    const extRunningLocation = runningLocation.get(ext);
    return extRunningLocation && predicate(extRunningLocation);
  });
}

// out-build/vs/workbench/services/extensions/common/lazyCreateExtensionHostManager.js
var $xnc = class $xnc2 extends $3c {
  get pid() {
    if (this.f) {
      return this.f.pid;
    }
    return null;
  }
  get kind() {
    return this.b.runningLocation.kind;
  }
  get startup() {
    return this.b.startup;
  }
  get friendyName() {
    return $snc(this.kind, this.pid);
  }
  constructor(extensionHost, h3, j, m) {
    super();
    this.h = h3;
    this.j = j;
    this.m = m;
    this.a = this.B(new $ze());
    this.onDidChangeResponsiveState = this.a.event;
    this.b = extensionHost;
    this.onDidExit = extensionHost.onExit;
    this.c = new $Uh();
    this.f = null;
    this.g = null;
  }
  n(reason) {
    this.m.info(`Creating lazy extension host (${this.friendyName}). Reason: ${reason}`);
    this.f = this.B(this.j.createInstance($rnc, this.b, [], this.h));
    this.B(this.f.onDidChangeResponsiveState((e) => this.a.fire(e)));
    return this.f;
  }
  async r(reason) {
    if (this.f) {
      return this.f;
    }
    const actual = this.n(reason);
    await actual.start(this.g.versionId, this.g.allExtensions, this.g.myExtensions);
    return actual;
  }
  async ready() {
    await this.c.wait();
    if (this.f) {
      await this.f.ready();
    }
  }
  async disconnect() {
    await this.f?.disconnect();
  }
  representsRunningLocation(runningLocation) {
    return this.b.runningLocation.equals(runningLocation);
  }
  async deltaExtensions(extensionsDelta) {
    await this.c.wait();
    if (this.f) {
      return this.f.deltaExtensions(extensionsDelta);
    }
    this.g.delta(extensionsDelta);
    if (extensionsDelta.myToAdd.length > 0) {
      const actual = this.n(`contains ${extensionsDelta.myToAdd.length} new extension(s) (installed or enabled): ${extensionsDelta.myToAdd.map((extId) => extId.value)}`);
      await actual.start(this.g.versionId, this.g.allExtensions, this.g.myExtensions);
      return;
    }
  }
  containsExtension(extensionId) {
    return this.b.extensions?.containsExtension(extensionId) ?? false;
  }
  async activate(extension, reason) {
    await this.c.wait();
    if (this.f) {
      return this.f.activate(extension, reason);
    }
    return false;
  }
  async activateByEvent(activationEvent, activationKind) {
    if (activationKind === 1) {
      if (this.f) {
        return this.f.activateByEvent(activationEvent, activationKind);
      }
      return;
    }
    await this.c.wait();
    if (this.f) {
      return this.f.activateByEvent(activationEvent, activationKind);
    }
  }
  activationEventIsDone(activationEvent) {
    if (!this.c.isOpen()) {
      return false;
    }
    if (this.f) {
      return this.f.activationEventIsDone(activationEvent);
    }
    return true;
  }
  async getInspectPort(tryEnableInspector) {
    await this.c.wait();
    return this.f?.getInspectPort(tryEnableInspector);
  }
  async resolveAuthority(remoteAuthority, resolveAttempt) {
    await this.c.wait();
    if (this.f) {
      return this.f.resolveAuthority(remoteAuthority, resolveAttempt);
    }
    return {
      type: "error",
      error: {
        message: `Cannot resolve authority`,
        code: RemoteAuthorityResolverErrorCode.Unknown,
        detail: void 0
      }
    };
  }
  async getCanonicalURI(remoteAuthority, uri) {
    await this.c.wait();
    if (this.f) {
      return this.f.getCanonicalURI(remoteAuthority, uri);
    }
    throw new Error(`Cannot resolve canonical URI`);
  }
  async start(extensionRegistryVersionId, allExtensions, myExtensions) {
    if (myExtensions.length > 0) {
      const actual = this.n(`contains ${myExtensions.length} extension(s): ${myExtensions.map((extId) => extId.value)}.`);
      const result = actual.start(extensionRegistryVersionId, allExtensions, myExtensions);
      this.c.open();
      return result;
    }
    this.g = new $yN(extensionRegistryVersionId, allExtensions, myExtensions);
    this.c.open();
  }
  async extensionTestsExecute() {
    await this.c.wait();
    const actual = await this.r(`execute tests.`);
    return actual.extensionTestsExecute();
  }
  async setRemoteEnvironment(env3) {
    await this.c.wait();
    if (this.f) {
      return this.f.setRemoteEnvironment(env3);
    }
  }
};
$xnc = __decorate([
  __param(2, $Pk),
  __param(3, $wn)
], $xnc);

// out-build/vs/workbench/services/extensions/common/abstractExtensionService.js
var $ync_1;
var hasOwnProperty4 = Object.hasOwnProperty;
var NO_OP_VOID_PROMISE = Promise.resolve(void 0);
var $ync = $ync_1 = class $ync2 extends $3c {
  constructor(options3, H, I, J, L, M, N, O, P, Q, R, S, U, W, X, Y, Z, $149, ab, bb, cb) {
    super();
    this.H = H;
    this.I = I;
    this.J = J;
    this.L = L;
    this.M = M;
    this.N = N;
    this.O = O;
    this.P = P;
    this.Q = Q;
    this.R = R;
    this.S = S;
    this.U = U;
    this.W = W;
    this.X = X;
    this.Y = Y;
    this.Z = Z;
    this.$ = $149;
    this.ab = ab;
    this.bb = bb;
    this.cb = cb;
    this.c = this.B(new $ze());
    this.onDidRegisterExtensions = this.c.event;
    this.f = this.B(new $ze());
    this.onDidChangeExtensionsStatus = this.f.event;
    this.g = this.B(new $ze({ leakWarningThreshold: 400 }));
    this.onDidChangeExtensions = this.g.event;
    this.h = this.B(new $ze());
    this.onWillActivateByEvent = this.h.event;
    this.j = this.B(new $ze());
    this.onDidChangeResponsiveChange = this.j.event;
    this.m = this.B(new $ze());
    this.onWillStop = this.m.event;
    this.n = new $Inc();
    this.s = new $knc(this.n);
    this.t = new $Uh();
    this.u = new $7z();
    this.w = /* @__PURE__ */ new Set();
    this.z = new $Hnc();
    this.C = [];
    this.D = false;
    this.F = this.B(new ExtensionHostCollection());
    this.G = 0;
    this.a = options3.hasLocalProcess;
    this.b = options3.allowRemoteExtensionsInLocalWebWorker;
    this.B(this.Q.onWillActivateFileSystemProvider((e) => {
      if (e.scheme !== Schemas.vscodeRemote) {
        e.join(this.activateByEvent(`onFileSystem:${e.scheme}`));
      }
    }));
    this.y = new $tnc(this.s, this.J, this.N, this.W, this.Y, this.X);
    this.B(this.P.onEnablementChanged((extensions) => {
      const toAdd = [];
      const toRemove = [];
      for (const extension of extensions) {
        if (this.Fb(extension)) {
          toAdd.push(extension);
        } else {
          toRemove.push(extension);
        }
      }
      if ($w) {
        this.Y.info(`AbstractExtensionService.onEnablementChanged fired for ${extensions.map((e) => e.identifier.id).join(", ")}`);
      }
      this.eb(new DeltaExtensionsQueueItem(toAdd, toRemove));
    }));
    this.B(this.S.onDidChangeProfile(({ added, removed }) => {
      if (added.length || removed.length) {
        if ($w) {
          this.Y.info(`AbstractExtensionService.onDidChangeProfile fired`);
        }
        this.eb(new DeltaExtensionsQueueItem(added, removed));
      }
    }));
    this.B(this.S.onDidEnableExtensions((extensions) => {
      if (extensions.length) {
        if ($w) {
          this.Y.info(`AbstractExtensionService.onDidEnableExtensions fired`);
        }
        this.eb(new DeltaExtensionsQueueItem(extensions, []));
      }
    }));
    this.B(this.S.onDidInstallExtensions((result) => {
      const extensions = [];
      for (const { local, operation } of result) {
        if (local && local.isValid && operation !== 4 && this.Fb(local)) {
          extensions.push(local);
        }
      }
      if (extensions.length) {
        if ($w) {
          this.Y.info(`AbstractExtensionService.onDidInstallExtensions fired for ${extensions.map((e) => e.identifier.id).join(", ")}`);
        }
        this.eb(new DeltaExtensionsQueueItem(extensions, []));
      }
    }));
    this.B(this.S.onDidUninstallExtension((event) => {
      if (!event.error) {
        if ($w) {
          this.Y.info(`AbstractExtensionService.onDidUninstallExtension fired for ${event.identifier.id}`);
        }
        this.eb(new DeltaExtensionsQueueItem([], [event.identifier.id]));
      }
    }));
    this.B(this.ab.onWillShutdown((event) => {
      if (this.Z.getConnection()) {
        event.join(async () => {
          try {
            await this.Z.endConnection();
            await this.tb();
            this.Z.getConnection()?.dispose();
          } catch {
            this.Y.warn("Error while disconnecting remote agent");
          }
        }, {
          id: "join.disconnectRemote",
          label: localize(12793, null),
          order: WillShutdownJoinerOrder.Last
          // after others have joined that might depend on a remote connection
        });
      } else {
        event.join(this.tb(), {
          id: "join.stopExtensionHosts",
          label: localize(12794, null)
        });
      }
    }));
  }
  db(kind) {
    return this.F.getByKind(kind);
  }
  //#region deltaExtensions
  async eb(item) {
    this.C.push(item);
    if (this.D) {
      return;
    }
    let lock = null;
    try {
      this.D = true;
      await this.t.wait();
      lock = await this.s.acquireLock("handleDeltaExtensions");
      while (this.C.length > 0) {
        const item2 = this.C.shift();
        await this.fb(lock, item2.toAdd, item2.toRemove);
      }
    } finally {
      this.D = false;
      lock?.dispose();
    }
  }
  async fb(lock, _toAdd, _toRemove) {
    if ($w) {
      this.Y.info(`AbstractExtensionService._deltaExtensions: toAdd: [${_toAdd.map((e) => e.identifier.id).join(",")}] toRemove: [${_toRemove.map((e) => typeof e === "string" ? e : e.identifier.id).join(",")}]`);
    }
    let toRemove = [];
    for (let i2 = 0, len = _toRemove.length; i2 < len; i2++) {
      const extensionOrId = _toRemove[i2];
      const extensionId = typeof extensionOrId === "string" ? extensionOrId : extensionOrId.identifier.id;
      const extension = typeof extensionOrId === "string" ? null : extensionOrId;
      const extensionDescription = this.s.getExtensionDescription(extensionId);
      if (!extensionDescription) {
        continue;
      }
      if (extension && extensionDescription.extensionLocation.scheme !== extension.location.scheme) {
        continue;
      }
      if (!this.canRemoveExtension(extensionDescription)) {
        continue;
      }
      toRemove.push(extensionDescription);
    }
    const toAdd = [];
    for (let i2 = 0, len = _toAdd.length; i2 < len; i2++) {
      const extension = _toAdd[i2];
      const extensionDescription = $EN(extension, false);
      if (!extensionDescription) {
        continue;
      }
      if (!this.ib(extensionDescription, toRemove)) {
        continue;
      }
      toAdd.push(extensionDescription);
    }
    if (toAdd.length === 0 && toRemove.length === 0) {
      return;
    }
    const result = this.s.deltaExtensions(lock, toAdd, toRemove.map((e) => e.identifier));
    this.g.fire({ added: toAdd, removed: toRemove });
    toRemove = toRemove.concat(result.removedDueToLooping);
    if (result.removedDueToLooping.length > 0) {
      this.M.notify({
        severity: Severity2.Error,
        message: localize(12795, null, result.removedDueToLooping.map((e) => `'${e.identifier.value}'`).join(", "))
      });
    }
    this.H.updateEnabledApiProposals(toAdd);
    this.Gb([].concat(toAdd).concat(toRemove), false);
    await this.gb(result.versionId, toAdd, toRemove.map((e) => e.identifier));
    for (let i2 = 0; i2 < toAdd.length; i2++) {
      this.jb(toAdd[i2]);
    }
  }
  async gb(versionId, toAdd, toRemove) {
    const removedRunningLocation = this.y.deltaExtensions(toAdd, toRemove);
    const promises = this.F.map((extHostManager) => this.hb(extHostManager, versionId, toAdd, toRemove, removedRunningLocation));
    await Promise.all(promises);
  }
  async hb(extensionHostManager, versionId, toAdd, toRemove, removedRunningLocation) {
    const myToAdd = this.y.filterByExtensionHostManager(toAdd, extensionHostManager);
    const myToRemove = $vnc(toRemove, removedRunningLocation, (extRunningLocation) => extensionHostManager.representsRunningLocation(extRunningLocation));
    const addActivationEvents = $fN.createActivationEventsMap(toAdd);
    if ($w) {
      const printExtIds = (extensions) => extensions.map((e) => e.identifier.value).join(",");
      const printIds = (extensions) => extensions.map((e) => e.value).join(",");
      this.Y.info(`AbstractExtensionService: Calling deltaExtensions: toRemove: [${printIds(toRemove)}], toAdd: [${printExtIds(toAdd)}], myToRemove: [${printIds(myToRemove)}], myToAdd: [${printExtIds(myToAdd)}],`);
    }
    await extensionHostManager.deltaExtensions({ versionId, toRemove, toAdd, addActivationEvents, myToRemove, myToAdd: myToAdd.map((extension) => extension.identifier) });
  }
  canAddExtension(extension) {
    return this.ib(extension, []);
  }
  ib(extension, extensionsBeingRemoved) {
    const existing = this.s.getExtensionDescriptionByIdOrUUID(extension.identifier, extension.id);
    if (existing) {
      const isBeingRemoved = extensionsBeingRemoved.some((extensionDescription) => $5z.equals(extension.identifier, extensionDescription.identifier));
      if (!isBeingRemoved) {
        return false;
      }
    }
    const extensionKinds = this.y.readExtensionKinds(extension);
    const isRemote = extension.extensionLocation.scheme === Schemas.vscodeRemote;
    const extensionHostKind = this.J.pickExtensionHostKind(
      extension.identifier,
      extensionKinds,
      !isRemote,
      isRemote,
      0
      /* ExtensionRunningPreference.None */
    );
    if (extensionHostKind === null) {
      return false;
    }
    return true;
  }
  canRemoveExtension(extension) {
    const extensionDescription = this.s.getExtensionDescription(extension.identifier);
    if (!extensionDescription) {
      return false;
    }
    if (this.u.get(extensionDescription.identifier)?.activationStarted) {
      return false;
    }
    return true;
  }
  async jb(extensionDescription) {
    let shouldActivate = false;
    let shouldActivateReason = null;
    let hasWorkspaceContains = false;
    const activationEvents = this.n.readActivationEvents(extensionDescription);
    for (const activationEvent of activationEvents) {
      if (this.w.has(activationEvent)) {
        shouldActivate = true;
        shouldActivateReason = activationEvent;
        break;
      }
      if (activationEvent === "*") {
        shouldActivate = true;
        shouldActivateReason = activationEvent;
        break;
      }
      if (/^workspaceContains/.test(activationEvent)) {
        hasWorkspaceContains = true;
      }
      if (activationEvent === "onStartupFinished") {
        shouldActivate = true;
        shouldActivateReason = activationEvent;
        break;
      }
    }
    if (shouldActivate) {
      await Promise.all(this.F.map((extHostManager) => extHostManager.activate(extensionDescription.identifier, { startup: false, extensionId: extensionDescription.identifier, activationEvent: shouldActivateReason }))).then(() => {
      });
    } else if (hasWorkspaceContains) {
      const workspace2 = await this.U.getCompleteWorkspace();
      const forceUsingSearch = !!this.N.remoteAuthority;
      const host = {
        logService: this.Y,
        folders: workspace2.folders.map((folder) => folder.uri),
        forceUsingSearch,
        exists: (uri) => this.Q.exists(uri),
        checkExists: (folders, includes2, token) => this.L.invokeFunction((accessor) => $8Rb(accessor, folders, includes2, token))
      };
      const result = await $7Rb(host, extensionDescription);
      if (!result) {
        return;
      }
      await Promise.all(this.F.map((extHostManager) => extHostManager.activate(extensionDescription.identifier, { startup: false, extensionId: extensionDescription.identifier, activationEvent: result.activationEvent }))).then(() => {
      });
    }
  }
  //#endregion
  async kb() {
    $S("code/willLoadExtensions");
    this.vb(true, []);
    const lock = await this.s.acquireLock("_initialize");
    try {
      await this.lb(lock);
      const snapshot = this.s.getSnapshot();
      for (const extHostManager of this.F) {
        if (extHostManager.startup !== 1) {
          const extensions = this.y.filterByExtensionHostManager(snapshot.extensions, extHostManager);
          extHostManager.start(snapshot.versionId, snapshot.extensions, extensions.map((extension) => extension.identifier));
        }
      }
    } finally {
      lock.dispose();
    }
    this.ob();
    $S("code/didLoadExtensions");
    await this.mb();
  }
  async lb(lock) {
    let resolverExtensions = [];
    let localExtensions = [];
    let remoteExtensions = [];
    for await (const extensions of this.Pb()) {
      if (extensions instanceof $znc) {
        resolverExtensions = $Dnc(this.Y, this.P, this.H, extensions.extensions, false);
        this.s.deltaExtensions(lock, resolverExtensions, []);
        this.Gb(resolverExtensions, true);
      }
      if (extensions instanceof $Anc) {
        localExtensions = $Dnc(this.Y, this.P, this.H, extensions.extensions, false);
      }
      if (extensions instanceof $Bnc) {
        remoteExtensions = $Dnc(this.Y, this.P, this.H, extensions.extensions, false);
      }
    }
    this.y.initializeRunningLocation(localExtensions, remoteExtensions);
    this.vb(true, []);
    const remoteExtensionsThatNeedToRunLocally = this.b ? this.y.filterByExtensionHostKind(
      remoteExtensions,
      2
      /* ExtensionHostKind.LocalWebWorker */
    ) : [];
    const localProcessExtensions = this.a ? this.y.filterByExtensionHostKind(
      localExtensions,
      1
      /* ExtensionHostKind.LocalProcess */
    ) : [];
    const localWebWorkerExtensions = this.y.filterByExtensionHostKind(
      localExtensions,
      2
      /* ExtensionHostKind.LocalWebWorker */
    );
    remoteExtensions = this.y.filterByExtensionHostKind(
      remoteExtensions,
      3
      /* ExtensionHostKind.Remote */
    );
    for (const ext of remoteExtensionsThatNeedToRunLocally) {
      if (!includes(localWebWorkerExtensions, ext.identifier)) {
        localWebWorkerExtensions.push(ext);
      }
    }
    const allExtensions = remoteExtensions.concat(localProcessExtensions).concat(localWebWorkerExtensions);
    let toAdd = allExtensions;
    if (resolverExtensions.length) {
      toAdd = allExtensions.filter((extension) => !resolverExtensions.some((e) => $5z.equals(e.identifier, extension.identifier) && e.extensionLocation.toString() === extension.extensionLocation.toString()));
      if (allExtensions.length < toAdd.length + resolverExtensions.length) {
        const toRemove = resolverExtensions.filter((registered) => !allExtensions.some((e) => $5z.equals(e.identifier, registered.identifier) && e.extensionLocation.toString() === registered.extensionLocation.toString()));
        if (toRemove.length) {
          this.s.deltaExtensions(lock, [], toRemove.map((e) => e.identifier));
          this.Gb(toRemove, true);
        }
      }
    }
    const result = this.s.deltaExtensions(lock, toAdd, []);
    if (result.removedDueToLooping.length > 0) {
      this.M.notify({
        severity: Severity2.Error,
        message: localize(12796, null, result.removedDueToLooping.map((e) => `'${e.identifier.value}'`).join(", "))
      });
    }
    this.Gb(this.s.getAllExtensionDescriptions(), false);
  }
  async mb() {
    if (!this.N.isExtensionDevelopment || !this.N.extensionTestsLocationURI) {
      return;
    }
    const extensionHostManager = this.nb(this.N.extensionTestsLocationURI);
    if (!extensionHostManager) {
      const msg = localize(12797, null, this.N.extensionTestsLocationURI.toString());
      console.error(msg);
      this.M.error(msg);
      return;
    }
    let exitCode;
    try {
      exitCode = await extensionHostManager.extensionTestsExecute();
      if ($w) {
        this.Y.info(`Extension host test runner exit code: ${exitCode}`);
      }
    } catch (err) {
      if ($w) {
        this.Y.error(`Extension host test runner error`, err);
      }
      console.error(err);
      exitCode = 1;
    }
    this.Qb(exitCode);
  }
  nb(testLocation) {
    let runningLocation = null;
    for (const extension of this.s.getAllExtensionDescriptions()) {
      if ($ph(testLocation, extension.extensionLocation)) {
        runningLocation = this.y.getRunningLocation(extension.identifier);
        break;
      }
    }
    if (runningLocation === null) {
      if (testLocation.scheme === Schemas.vscodeRemote) {
        runningLocation = new $nN();
      } else {
        runningLocation = new $lN(0);
      }
    }
    if (runningLocation !== null) {
      return this.F.getByRunningLocation(runningLocation);
    }
    return null;
  }
  ob() {
    this.t.open();
    this.c.fire(void 0);
    this.f.fire(this.s.getAllExtensionDescriptions().map((e) => e.identifier));
  }
  //#region remote authority resolving
  async pb(remoteAuthority) {
    const MAX_ATTEMPTS = 5;
    for (let attempt = 1; ; attempt++) {
      try {
        return this.rb(remoteAuthority);
      } catch (err) {
        if ($eC.isNoResolverFound(err)) {
          throw err;
        }
        if ($eC.isNotAvailable(err)) {
          throw err;
        }
        if (attempt >= MAX_ATTEMPTS) {
          throw err;
        }
      }
    }
  }
  async qb() {
    const remoteAuthority = this.N.remoteAuthority;
    if (!remoteAuthority) {
      return;
    }
    this.bb._clearResolvedAuthority(remoteAuthority);
    try {
      const result = await this.rb(remoteAuthority);
      this.bb._setResolvedAuthority(result.authority, result.options);
    } catch (err) {
      this.bb._setResolvedAuthorityError(remoteAuthority, err);
    }
  }
  async rb(remoteAuthority) {
    const authorityPrefix = $fC(remoteAuthority);
    const sw = $te.create(false);
    this.Y.info(`Invoking resolveAuthority(${authorityPrefix})...`);
    try {
      $S(`code/willResolveAuthority/${authorityPrefix}`);
      const result = await this.Rb(remoteAuthority);
      $S(`code/didResolveAuthorityOK/${authorityPrefix}`);
      this.Y.info(`resolveAuthority(${authorityPrefix}) returned '${result.authority.connectTo}' after ${sw.elapsed()} ms`);
      return result;
    } catch (err) {
      $S(`code/didResolveAuthorityError/${authorityPrefix}`);
      this.Y.error(`resolveAuthority(${authorityPrefix}) returned an error after ${sw.elapsed()} ms`, err);
      throw err;
    }
  }
  async sb(kind, remoteAuthority) {
    const extensionHosts = this.db(kind);
    if (extensionHosts.length === 0) {
      throw new Error(`Cannot resolve authority`);
    }
    this.G++;
    const results = await Promise.all(extensionHosts.map((extHost) => extHost.resolveAuthority(remoteAuthority, this.G)));
    let bestErrorResult = null;
    for (const result of results) {
      if (result.type === "ok") {
        return result.value;
      }
      if (!bestErrorResult) {
        bestErrorResult = result;
        continue;
      }
      const bestErrorIsUnknown = bestErrorResult.error.code === RemoteAuthorityResolverErrorCode.Unknown;
      const errorIsUnknown = result.error.code === RemoteAuthorityResolverErrorCode.Unknown;
      if (bestErrorIsUnknown && !errorIsUnknown) {
        bestErrorResult = result;
      }
    }
    throw new $eC(bestErrorResult.error.message, bestErrorResult.error.code, bestErrorResult.error.detail);
  }
  //#endregion
  //#region Stopping / Starting / Restarting
  stopExtensionHosts(reason, auto) {
    return this.ub(reason, auto);
  }
  async tb() {
    const previouslyActivatedExtensionIds = [];
    for (const extensionStatus of this.u.values()) {
      if (extensionStatus.activationStarted) {
        previouslyActivatedExtensionIds.push(extensionStatus.id);
      }
    }
    await this.F.stopAllInReverse();
    for (const extensionStatus of this.u.values()) {
      extensionStatus.clearRuntimeStatus();
    }
    if (previouslyActivatedExtensionIds.length > 0) {
      this.f.fire(previouslyActivatedExtensionIds);
    }
  }
  async ub(reason, auto = false) {
    if (auto && this.N.isExtensionDevelopment) {
      return false;
    }
    const vetos = [];
    const vetoReasons = /* @__PURE__ */ new Set();
    this.m.fire({
      reason,
      auto,
      veto(value, reason2) {
        vetos.push(value);
        if (typeof value === "boolean") {
          if (value === true) {
            vetoReasons.add(reason2);
          }
        } else {
          value.then((value2) => {
            if (value2) {
              vetoReasons.add(reason2);
            }
          }).catch((error) => {
            vetoReasons.add(localize(12798, null, reason2, $1m(error)));
          });
        }
      }
    });
    const veto = await $gnc(vetos, (error) => this.Y.error(error));
    if (!veto) {
      await this.tb();
    } else {
      if (!auto) {
        const vetoReasonsArray = Array.from(vetoReasons);
        this.Y.warn(`Extension host was not stopped because of veto (stop reason: ${reason}, veto reason: ${vetoReasonsArray.join(", ")})`);
        await this.cb.warn(localize(12799, null, reason), vetoReasonsArray.length === 1 ? localize(12800, null, vetoReasonsArray[0]) : localize(12801, null, vetoReasonsArray.join("\n -")));
      }
    }
    return !veto;
  }
  vb(isInitialStart, initialActivationEvents) {
    const locations = [];
    for (let affinity = 0; affinity <= this.y.maxLocalProcessAffinity; affinity++) {
      locations.push(new $lN(affinity));
    }
    for (let affinity = 0; affinity <= this.y.maxLocalWebWorkerAffinity; affinity++) {
      locations.push(new $mN(affinity));
    }
    locations.push(new $nN());
    for (const location3 of locations) {
      if (this.F.getByRunningLocation(location3)) {
        continue;
      }
      const res = this.wb(location3, isInitialStart, initialActivationEvents);
      if (res) {
        const [extHostManager, disposableStore] = res;
        this.F.add(extHostManager, disposableStore);
      }
    }
  }
  wb(runningLocation, isInitialStart, initialActivationEvents) {
    const extensionHost = this.I.createExtensionHost(this.y, runningLocation, isInitialStart);
    if (!extensionHost) {
      return null;
    }
    const processManager = this.xb(extensionHost, initialActivationEvents);
    const disposableStore = new $2c();
    disposableStore.add(processManager.onDidExit(([code, signal]) => this.yb(processManager, code, signal)));
    disposableStore.add(processManager.onDidChangeResponsiveState((responsiveState) => {
      this.Y.info(`Extension host (${processManager.friendyName}) is ${responsiveState === 0 ? "responsive" : "unresponsive"}.`);
      this.j.fire({
        extensionHostKind: processManager.kind,
        isResponsive: responsiveState === 0,
        getInspectListener: (tryEnableInspector) => {
          return processManager.getInspectPort(tryEnableInspector);
        }
      });
    }));
    return [processManager, disposableStore];
  }
  xb(extensionHost, initialActivationEvents) {
    const internalExtensionService = this.Kb(extensionHost);
    if (extensionHost.startup === 3 && initialActivationEvents.length === 0) {
      return this.L.createInstance($xnc, extensionHost, internalExtensionService);
    }
    return this.L.createInstance($rnc, extensionHost, initialActivationEvents, internalExtensionService);
  }
  yb(extensionHost, code, signal) {
    const isExtensionDevHost = $vOb(this.N).isExtensionDevHost;
    if (!isExtensionDevHost) {
      this.zb(extensionHost, code, signal);
      return;
    }
    this.Qb(code);
  }
  zb(extensionHost, code, signal) {
    console.error(`Extension host (${extensionHost.friendyName}) terminated unexpectedly. Code: ${code}, Signal: ${signal}`);
    if (extensionHost.kind === 1) {
      this.tb();
    } else if (extensionHost.kind === 3) {
      if (signal) {
        this.Bb(extensionHost, signal);
      }
      this.F.stopOne(extensionHost);
    }
  }
  Ab(reconnectionToken) {
    return new Promise((resolve, reject) => {
      const timeoutHandle = setTimeout(() => {
        reject(new Error("getExtensionHostExitInfo timed out"));
      }, 2e3);
      this.Z.getExtensionHostExitInfo(reconnectionToken).then((r2) => {
        clearTimeout(timeoutHandle);
        resolve(r2);
      }, reject);
    });
  }
  async Bb(extensionHost, reconnectionToken) {
    try {
      const info = await this.Ab(reconnectionToken);
      if (info) {
        this.Y.error(`Extension host (${extensionHost.friendyName}) terminated unexpectedly with code ${info.code}.`);
      }
      this.Cb(extensionHost);
      this.z.registerCrash();
      if (this.z.shouldAutomaticallyRestart()) {
        this.Y.info(`Automatically restarting the remote extension host.`);
        this.M.status(localize(12802, null), { hideAfter: 5e3 });
        this.vb(false, Array.from(this.w.keys()));
      } else {
        this.M.prompt(Severity2.Error, localize(12803, null), [{
          label: localize(12804, null),
          run: () => {
            this.vb(false, Array.from(this.w.keys()));
          }
        }]);
      }
    } catch (err) {
    }
  }
  Cb(extensionHost) {
    const activatedExtensions = [];
    for (const extensionStatus of this.u.values()) {
      if (extensionStatus.activationStarted && extensionHost.containsExtension(extensionStatus.id)) {
        activatedExtensions.push(extensionStatus.id);
      }
    }
    if (activatedExtensions.length > 0) {
      this.Y.error(`Extension host (${extensionHost.friendyName}) terminated unexpectedly. The following extensions were running: ${activatedExtensions.map((id2) => id2.value).join(", ")}`);
    } else {
      this.Y.error(`Extension host (${extensionHost.friendyName}) terminated unexpectedly. No extensions were activated.`);
    }
  }
  async startExtensionHosts(updates) {
    await this.tb();
    if (updates) {
      await this.eb(new DeltaExtensionsQueueItem(updates.toAdd, updates.toRemove));
    }
    const lock = await this.s.acquireLock("startExtensionHosts");
    try {
      this.vb(false, Array.from(this.w.keys()));
      const localProcessExtensionHosts = this.db(
        1
        /* ExtensionHostKind.LocalProcess */
      );
      await Promise.all(localProcessExtensionHosts.map((extHost) => extHost.ready()));
    } finally {
      lock.dispose();
    }
  }
  //#endregion
  //#region IExtensionService
  activateByEvent(activationEvent, activationKind = 0) {
    if (this.t.isOpen()) {
      this.w.add(activationEvent);
      if (!this.s.containsActivationEvent(activationEvent)) {
        return NO_OP_VOID_PROMISE;
      }
      return this.Db(activationEvent, activationKind);
    } else {
      this.w.add(activationEvent);
      if (activationKind === 1) {
        return this.Db(activationEvent, activationKind);
      }
      return this.t.wait().then(() => this.Db(activationEvent, activationKind));
    }
  }
  Db(activationEvent, activationKind) {
    const result = Promise.all(this.F.map((extHostManager) => extHostManager.activateByEvent(activationEvent, activationKind))).then(() => {
    });
    this.h.fire({
      event: activationEvent,
      activation: result
    });
    return result;
  }
  activateById(extensionId, reason) {
    return this._activateById(extensionId, reason);
  }
  activationEventIsDone(activationEvent) {
    if (!this.t.isOpen()) {
      return false;
    }
    if (!this.s.containsActivationEvent(activationEvent)) {
      return true;
    }
    return this.F.every((manager) => manager.activationEventIsDone(activationEvent));
  }
  whenInstalledExtensionsRegistered() {
    return this.t.wait();
  }
  get extensions() {
    return this.s.getAllExtensionDescriptions();
  }
  Eb() {
    return this.t.wait().then(() => this.s.getSnapshot());
  }
  getExtension(id2) {
    return this.t.wait().then(() => {
      return this.s.getExtensionDescription(id2);
    });
  }
  readExtensionPointContributions(extPoint) {
    return this.t.wait().then(() => {
      const availableExtensions = this.s.getAllExtensionDescriptions();
      const result = [];
      for (const desc of availableExtensions) {
        if (desc.contributes && hasOwnProperty4.call(desc.contributes, extPoint.name)) {
          result.push(new $CN(desc, desc.contributes[extPoint.name]));
        }
      }
      return result;
    });
  }
  getExtensionsStatus() {
    const result = /* @__PURE__ */ Object.create(null);
    if (this.s) {
      const extensions = this.s.getAllExtensionDescriptions();
      for (const extension of extensions) {
        const extensionStatus = this.u.get(extension.identifier);
        result[extension.identifier.value] = {
          id: extension.identifier,
          messages: extensionStatus?.messages ?? [],
          activationStarted: extensionStatus?.activationStarted ?? false,
          activationTimes: extensionStatus?.activationTimes ?? void 0,
          runtimeErrors: extensionStatus?.runtimeErrors ?? [],
          runningLocation: this.y.getRunningLocation(extension.identifier)
        };
      }
    }
    return result;
  }
  async getInspectPorts(extensionHostKind, tryEnableInspector) {
    const result = await Promise.all(this.db(extensionHostKind).map((extHost) => extHost.getInspectPort(tryEnableInspector)));
    return result.filter($Hg);
  }
  async setRemoteEnvironment(env3) {
    await this.F.map((manager) => manager.setRemoteEnvironment(env3));
  }
  //#endregion
  // --- impl
  Fb(extension) {
    try {
      return this.P.isEnabled(extension);
    } catch (err) {
      return false;
    }
  }
  Gb(affectedExtensions, onlyResolverExtensionPoints) {
    const affectedExtensionPoints = /* @__PURE__ */ Object.create(null);
    for (const extensionDescription of affectedExtensions) {
      if (extensionDescription.contributes) {
        for (const extPointName in extensionDescription.contributes) {
          if (hasOwnProperty4.call(extensionDescription.contributes, extPointName)) {
            affectedExtensionPoints[extPointName] = true;
          }
        }
      }
    }
    const messageHandler = (msg) => this.Ib(msg);
    const availableExtensions = this.s.getAllExtensionDescriptions();
    const extensionPoints = $tN.getExtensionPoints();
    $S(onlyResolverExtensionPoints ? "code/willHandleResolverExtensionPoints" : "code/willHandleExtensionPoints");
    for (const extensionPoint2 of extensionPoints) {
      if (affectedExtensionPoints[extensionPoint2.name] && (!onlyResolverExtensionPoints || extensionPoint2.canHandleResolver)) {
        $S(`code/willHandleExtensionPoint/${extensionPoint2.name}`);
        $ync_1.Jb(extensionPoint2, availableExtensions, messageHandler);
        $S(`code/didHandleExtensionPoint/${extensionPoint2.name}`);
      }
    }
    $S(onlyResolverExtensionPoints ? "code/didHandleResolverExtensionPoints" : "code/didHandleExtensionPoints");
  }
  Hb(extensionId) {
    if (!this.u.has(extensionId)) {
      this.u.set(extensionId, new $Gnc(extensionId));
    }
    return this.u.get(extensionId);
  }
  Ib(msg) {
    const extensionStatus = this.Hb(msg.extensionId);
    extensionStatus.addMessage(msg);
    const extension = this.s.getExtensionDescription(msg.extensionId);
    const strMsg = `[${msg.extensionId.value}]: ${msg.message}`;
    if (msg.type === Severity2.Error) {
      if (extension && extension.isUnderDevelopment) {
        this.M.notify({ severity: Severity2.Error, message: strMsg });
      }
      this.Y.error(strMsg);
    } else if (msg.type === Severity2.Warning) {
      if (extension && extension.isUnderDevelopment) {
        this.M.notify({ severity: Severity2.Warning, message: strMsg });
      }
      this.Y.warn(strMsg);
    } else {
      this.Y.info(strMsg);
    }
    if (msg.extensionId && this.N.isBuilt && !this.N.isExtensionDevelopment) {
      const { type, extensionId, extensionPointId, message } = msg;
      this.O.publicLog2("extensionsMessage", {
        type,
        extensionId: extensionId.value,
        extensionPointId,
        message
      });
    }
  }
  static Jb(extensionPoint2, availableExtensions, messageHandler) {
    const users = [];
    for (const desc of availableExtensions) {
      if (desc.contributes && hasOwnProperty4.call(desc.contributes, extensionPoint2.name)) {
        users.push({
          description: desc,
          value: desc.contributes[extensionPoint2.name],
          collector: new $oN(messageHandler, desc, extensionPoint2.name)
        });
      }
    }
    extensionPoint2.acceptUsers(users);
  }
  //#region Called by extension host
  Kb(extensionHost) {
    return {
      _activateById: (extensionId, reason) => {
        return this._activateById(extensionId, reason);
      },
      _onWillActivateExtension: (extensionId) => {
        return this.Lb(extensionId, extensionHost.runningLocation);
      },
      _onDidActivateExtension: (extensionId, codeLoadingTime, activateCallTime, activateResolvedTime, activationReason) => {
        return this.Mb(extensionId, codeLoadingTime, activateCallTime, activateResolvedTime, activationReason);
      },
      _onDidActivateExtensionError: (extensionId, error) => {
        return this.Nb(extensionId, error);
      },
      _onExtensionRuntimeError: (extensionId, err) => {
        return this.Ob(extensionId, err);
      }
    };
  }
  async _activateById(extensionId, reason) {
    const results = await Promise.all(this.F.map((manager) => manager.activate(extensionId, reason)));
    const activated = results.some((e) => e);
    if (!activated) {
      throw new Error(`Unknown extension ${extensionId.value}`);
    }
  }
  Lb(extensionId, runningLocation) {
    this.y.set(extensionId, runningLocation);
    const extensionStatus = this.Hb(extensionId);
    extensionStatus.onWillActivate();
  }
  Mb(extensionId, codeLoadingTime, activateCallTime, activateResolvedTime, activationReason) {
    const extensionStatus = this.Hb(extensionId);
    extensionStatus.setActivationTimes(new $BN(codeLoadingTime, activateCallTime, activateResolvedTime, activationReason));
    this.f.fire([extensionId]);
  }
  Nb(extensionId, error) {
    this.O.publicLog2("extensionActivationError", {
      extensionId: extensionId.value,
      error: error.message
    });
  }
  Ob(extensionId, err) {
    const extensionStatus = this.Hb(extensionId);
    extensionStatus.addRuntimeError(err);
    this.f.fire([extensionId]);
  }
};
$ync = $ync_1 = __decorate([
  __param(4, $Pk),
  __param(5, $PJ),
  __param(6, $US),
  __param(7, $zv),
  __param(8, $qzb),
  __param(9, $km),
  __param(10, $Vu),
  __param(11, $pzb),
  __param(12, $Zk),
  __param(13, $kl),
  __param(14, $LCb),
  __param(15, $wn),
  __param(16, $RL),
  __param(17, $NY),
  __param(18, $KL),
  __param(19, $bC),
  __param(20, $Yv)
], $ync);
var ExtensionHostCollection = class extends $3c {
  constructor() {
    super(...arguments);
    this.a = [];
  }
  dispose() {
    for (let i2 = this.a.length - 1; i2 >= 0; i2--) {
      const manager = this.a[i2];
      manager.extensionHost.disconnect();
      manager.dispose();
    }
    this.a = [];
    super.dispose();
  }
  add(extensionHostManager, disposableStore) {
    this.a.push(new ExtensionHostManagerData(extensionHostManager, disposableStore));
  }
  async stopAllInReverse() {
    for (let i2 = this.a.length - 1; i2 >= 0; i2--) {
      const manager = this.a[i2];
      await manager.extensionHost.disconnect();
      manager.dispose();
    }
    this.a = [];
  }
  async stopOne(extensionHostManager) {
    const index = this.a.findIndex((el) => el.extensionHost === extensionHostManager);
    if (index >= 0) {
      this.a.splice(index, 1);
      await extensionHostManager.disconnect();
      extensionHostManager.dispose();
    }
  }
  getByKind(kind) {
    return this.filter((el) => el.kind === kind);
  }
  getByRunningLocation(runningLocation) {
    for (const el of this.a) {
      if (el.extensionHost.representsRunningLocation(runningLocation)) {
        return el.extensionHost;
      }
    }
    return null;
  }
  *[Symbol.iterator]() {
    for (const extensionHostManager of this.a) {
      yield extensionHostManager.extensionHost;
    }
  }
  map(callback) {
    return this.a.map((el) => callback(el.extensionHost));
  }
  every(callback) {
    return this.a.every((el) => callback(el.extensionHost));
  }
  filter(callback) {
    return this.a.filter((el) => callback(el.extensionHost)).map((el) => el.extensionHost);
  }
};
var ExtensionHostManagerData = class {
  constructor(extensionHost, disposableStore) {
    this.extensionHost = extensionHost;
    this.disposableStore = disposableStore;
  }
  dispose() {
    this.disposableStore.dispose();
    this.extensionHost.dispose();
  }
};
var $znc = class {
  constructor(extensions) {
    this.extensions = extensions;
  }
};
var $Anc = class {
  constructor(extensions) {
    this.extensions = extensions;
  }
};
var $Bnc = class {
  constructor(extensions) {
    this.extensions = extensions;
  }
};
var DeltaExtensionsQueueItem = class {
  constructor(toAdd, toRemove) {
    this.toAdd = toAdd;
    this.toRemove = toRemove;
  }
};
function $Cnc(extension) {
  return !!extension.activationEvents?.some((activationEvent) => activationEvent.startsWith("onResolveRemoteAuthority:"));
}
function $Dnc(logService, extensionEnablementService, extensionsProposedApi, extensions, ignoreWorkspaceTrust) {
  extensionsProposedApi.updateEnabledApiProposals(extensions);
  return $Enc(logService, extensionEnablementService, extensions, ignoreWorkspaceTrust);
}
function $Enc(logService, extensionEnablementService, extensions, ignoreWorkspaceTrust) {
  const enabledExtensions = [], extensionsToCheck = [], mappedExtensions = [];
  for (const extension of extensions) {
    if (extension.isUnderDevelopment) {
      enabledExtensions.push(extension);
    } else {
      extensionsToCheck.push(extension);
      mappedExtensions.push($DN(extension));
    }
  }
  const enablementStates = extensionEnablementService.getEnablementStates(mappedExtensions, ignoreWorkspaceTrust ? { trusted: true } : void 0);
  for (let index = 0; index < enablementStates.length; index++) {
    if (extensionEnablementService.isEnabledEnablementState(enablementStates[index])) {
      enabledExtensions.push(extensionsToCheck[index]);
    } else {
      if ($w) {
        logService.info(`filterEnabledExtensions: extension '${extensionsToCheck[index].identifier.value}' is disabled`);
      }
    }
  }
  return enabledExtensions;
}
function includes(extensions, identifier2) {
  for (const extension of extensions) {
    if ($5z.equals(extension.identifier, identifier2)) {
      return true;
    }
  }
  return false;
}
var $Gnc = class {
  get messages() {
    return this.a;
  }
  get activationTimes() {
    return this.b;
  }
  get runtimeErrors() {
    return this.c;
  }
  get activationStarted() {
    return this.d;
  }
  constructor(id2) {
    this.id = id2;
    this.a = [];
    this.b = null;
    this.c = [];
    this.d = false;
  }
  clearRuntimeStatus() {
    this.d = false;
    this.b = null;
    this.c = [];
  }
  addMessage(msg) {
    this.a.push(msg);
  }
  setActivationTimes(activationTimes) {
    this.b = activationTimes;
  }
  addRuntimeError(err) {
    this.c.push(err);
  }
  onWillActivate() {
    this.d = true;
  }
};
var $Hnc = class _$Hnc {
  constructor() {
    this.c = [];
  }
  static {
    this.a = 5 * 60 * 1e3;
  }
  static {
    this.b = 3;
  }
  d() {
    const limit = Date.now() - _$Hnc.a;
    while (this.c.length > 0 && this.c[0].timestamp < limit) {
      this.c.shift();
    }
  }
  registerCrash() {
    this.d();
    this.c.push({ timestamp: Date.now() });
  }
  shouldAutomaticallyRestart() {
    this.d();
    return this.c.length < _$Hnc.b;
  }
};
var $Inc = class {
  readActivationEvents(extensionDescription) {
    return $fN.readActivationEvents(extensionDescription);
  }
};
var ActivationFeatureMarkdowneRenderer = class extends $3c {
  constructor() {
    super(...arguments);
    this.type = "markdown";
  }
  shouldRender(manifest) {
    return !!manifest.activationEvents;
  }
  render(manifest) {
    const activationEvents = manifest.activationEvents || [];
    const data = new $bm();
    if (activationEvents.length) {
      for (const activationEvent of activationEvents) {
        data.appendMarkdown(`- \`${activationEvent}\`
`);
      }
    }
    return {
      data,
      dispose: () => {
      }
    };
  }
};
$Wn.as(Extensions3.ExtensionFeaturesRegistry).registerExtensionFeature({
  id: "activationEvents",
  label: localize(12805, null),
  access: {
    canToggle: false
  },
  renderer: new $Nk(ActivationFeatureMarkdowneRenderer)
});

// out-build/vs/workbench/services/extensions/common/extensionsProposedApi.js
var $wnc = class $wnc2 {
  constructor(e, f, productService) {
    this.e = e;
    this.f = f;
    this.c = new Set((f.extensionEnabledProposedApi ?? []).map((id2) => $5z.toKey(id2)));
    this.b = // --- Start PWB: Always allow proposed API
    true;
    this.d = /* @__PURE__ */ new Map();
    if (productService.extensionEnabledApiProposals) {
      for (const [k, value] of Object.entries(productService.extensionEnabledApiProposals)) {
        const key2 = $5z.toKey(k);
        const proposalNames = value.filter((name) => {
          if (!allApiProposals[name]) {
            e.warn(`Via 'product.json#extensionEnabledApiProposals' extension '${key2}' wants API proposal '${name}' but that proposal DOES NOT EXIST. Likely, the proposal has been finalized (check 'vscode.d.ts') or was abandoned.`);
            return false;
          }
          return true;
        });
        this.d.set(key2, proposalNames);
      }
    }
  }
  updateEnabledApiProposals(extensions) {
    for (const extension of extensions) {
      this.g(extension);
    }
  }
  g(extension) {
    const key2 = $5z.toKey(extension.identifier);
    if ($Qb(extension.enabledApiProposals)) {
      extension.enabledApiProposals = extension.enabledApiProposals.filter((name) => {
        const result = Boolean(allApiProposals[name]);
        if (!result) {
          this.e.error(`Extension '${key2}' wants API proposal '${name}' but that proposal DOES NOT EXIST. Likely, the proposal has been finalized (check 'vscode.d.ts') or was abandoned.`);
        }
        return result;
      });
    }
    if (this.d.has(key2)) {
      const productEnabledProposals = this.d.get(key2);
      const productSet = new Set(productEnabledProposals);
      const extensionSet = new Set(extension.enabledApiProposals);
      const diff3 = new Set([...extensionSet].filter((a) => !productSet.has(a)));
      if (diff3.size > 0) {
        this.e.error(`Extension '${key2}' appears in product.json but enables LESS API proposals than the extension wants.
package.json (LOSES): ${[...extensionSet].join(", ")}
product.json (WINS): ${[...productSet].join(", ")}`);
        if (this.f.isExtensionDevelopment) {
          this.e.error(`Proceeding with EXTRA proposals (${[...diff3].join(", ")}) because extension is in development mode. Still, this EXTENSION WILL BE BROKEN unless product.json is updated.`);
          productEnabledProposals.push(...diff3);
        }
      }
      extension.enabledApiProposals = productEnabledProposals;
      return;
    }
    if (this.b || this.c.has(key2)) {
      return;
    }
    if (!extension.isBuiltin && $Qb(extension.enabledApiProposals)) {
      this.e.error(`Extension '${extension.identifier.value} CANNOT USE these API proposals '${extension.enabledApiProposals?.join(", ") || "*"}'. You MUST start in extension development mode or use the --enable-proposed-api command line flag`);
      extension.enabledApiProposals = [];
    }
  }
};
$wnc = __decorate([
  __param(0, $wn),
  __param(1, $US),
  __param(2, $Vu)
], $wnc);
var ApiProposalsMarkdowneRenderer = class extends $3c {
  constructor() {
    super(...arguments);
    this.type = "markdown";
  }
  shouldRender(manifest) {
    return !!manifest.originalEnabledApiProposals?.length || !!manifest.enabledApiProposals?.length;
  }
  render(manifest) {
    const enabledApiProposals = manifest.originalEnabledApiProposals ?? manifest.enabledApiProposals ?? [];
    const data = new $bm();
    if (enabledApiProposals.length) {
      for (const proposal of enabledApiProposals) {
        data.appendMarkdown(`- \`${proposal}\`
`);
      }
    }
    return {
      data,
      dispose: () => {
      }
    };
  }
};
$Wn.as(Extensions3.ExtensionFeaturesRegistry).registerExtensionFeature({
  id: "enabledApiProposals",
  label: localize(12807, null),
  access: {
    canToggle: false
  },
  renderer: new $Nk(ApiProposalsMarkdowneRenderer)
});

// out-build/vs/workbench/services/extensions/common/extensionsUtil.js
function $MY(system, user, workspace2, development, logService) {
  const result = new $7z();
  system.forEach((systemExtension) => {
    const extension = result.get(systemExtension.identifier);
    if (extension) {
      logService.warn(localize(12891, null, extension.extensionLocation.fsPath, systemExtension.extensionLocation.fsPath));
    }
    result.set(systemExtension.identifier, systemExtension);
  });
  user.forEach((userExtension) => {
    const extension = result.get(userExtension.identifier);
    if (extension) {
      if (extension.isBuiltin) {
        if (gte(extension.version, userExtension.version)) {
          logService.warn(`Skipping extension ${userExtension.extensionLocation.path} in favour of the builtin extension ${extension.extensionLocation.path}.`);
          return;
        }
        userExtension.isBuiltin = true;
      } else {
        logService.warn(localize(12892, null, extension.extensionLocation.fsPath, userExtension.extensionLocation.fsPath));
      }
    } else if (userExtension.isBuiltin) {
      logService.warn(`Skipping obsolete builtin extension ${userExtension.extensionLocation.path}`);
      return;
    }
    result.set(userExtension.identifier, userExtension);
  });
  workspace2.forEach((workspaceExtension) => {
    const extension = result.get(workspaceExtension.identifier);
    if (extension) {
      logService.warn(localize(12893, null, extension.extensionLocation.fsPath, workspaceExtension.extensionLocation.fsPath));
    }
    result.set(workspaceExtension.identifier, workspaceExtension);
  });
  development.forEach((developedExtension) => {
    logService.info(localize(12894, null, developedExtension.extensionLocation.fsPath));
    const extension = result.get(developedExtension.identifier);
    if (extension) {
      if (extension.isBuiltin) {
        developedExtension.isBuiltin = true;
      }
    }
    result.set(developedExtension.identifier, developedExtension);
  });
  return Array.from(result.values());
}

// out-build/vs/workbench/services/extensions/common/remoteExtensionHost.js
var $Jnc = class $Jnc2 extends $3c {
  constructor(runningLocation, j, m, n, r2, s, t, u, w, y, z, C, D) {
    super();
    this.runningLocation = runningLocation;
    this.j = j;
    this.m = m;
    this.n = n;
    this.r = r2;
    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.pid = null;
    this.startup = 1;
    this.extensions = null;
    this.a = this.B(new $ze());
    this.onExit = this.a.event;
    this.g = false;
    this.remoteAuthority = this.j.remoteAuthority;
    this.b = null;
    this.c = false;
    this.f = false;
    const devOpts = $vOb(this.r);
    this.h = devOpts.isExtensionDevHost;
  }
  start() {
    const options3 = {
      commit: this.C.commit,
      quality: this.C.quality,
      addressProvider: {
        getAddress: async () => {
          const { authority } = await this.y.resolveAuthority(this.j.remoteAuthority);
          return { connectTo: authority.connectTo, connectionToken: authority.connectionToken };
        }
      },
      remoteSocketFactoryService: this.m,
      signService: this.D,
      logService: this.t,
      ipcLogger: null
    };
    return this.y.resolveAuthority(this.j.remoteAuthority).then((resolverResult) => {
      const startParams = {
        language: $z,
        debugId: this.r.debugExtensionHost.debugId,
        break: this.r.debugExtensionHost.break,
        port: this.r.debugExtensionHost.port,
        env: { ...this.r.debugExtensionHost.env, ...resolverResult.options?.extensionHostEnv }
      };
      const extDevLocs = this.r.extensionDevelopmentLocationURI;
      let debugOk = true;
      if (extDevLocs && extDevLocs.length > 0) {
        if (extDevLocs[0].scheme === Schemas.file) {
          debugOk = false;
        }
      }
      if (!debugOk) {
        startParams.break = false;
      }
      return $jC(options3, startParams).then((result) => {
        this.B(result);
        const { protocol, debugPort, reconnectionToken } = result;
        const isExtensionDevelopmentDebug = typeof debugPort === "number";
        if (debugOk && this.r.isExtensionDevelopment && this.r.debugExtensionHost.debugId && debugPort) {
          this.z.attachSession(this.r.debugExtensionHost.debugId, debugPort, this.j.remoteAuthority);
        }
        protocol.onDidDispose(() => {
          this.F(reconnectionToken);
        });
        protocol.onSocketClose(() => {
          if (this.h) {
            this.F(reconnectionToken);
          }
        });
        return new Promise((resolve, reject) => {
          const handle2 = setTimeout(() => {
            reject("The remote extension host took longer than 60s to send its ready message.");
          }, 60 * 1e3);
          const disposable = protocol.onMessage((msg) => {
            if ($kN(
              msg,
              1
              /* MessageType.Ready */
            )) {
              this.G(isExtensionDevelopmentDebug).then((data) => {
                protocol.send($Ci.fromString(JSON.stringify(data)));
              });
              return;
            }
            if ($kN(
              msg,
              0
              /* MessageType.Initialized */
            )) {
              clearTimeout(handle2);
              disposable.dispose();
              this.b = protocol;
              resolve(protocol);
              return;
            }
            console.error(`received unexpected message during handshake phase from the extension host: `, msg);
          });
        });
      });
    });
  }
  F(reconnectionToken) {
    if (this.c) {
      return;
    }
    this.c = true;
    if (this.h && this.r.debugExtensionHost.debugId) {
      this.z.close(this.r.debugExtensionHost.debugId);
    }
    if (this.f) {
      return;
    }
    this.a.fire([0, reconnectionToken]);
  }
  async G(isExtensionDevelopmentDebug) {
    const remoteInitData = await this.j.getInitData();
    this.extensions = remoteInitData.extensions;
    const workspace2 = this.n.getWorkspace();
    return {
      commit: this.C.commit,
      version: this.C.version,
      quality: this.C.quality,
      parentPid: remoteInitData.pid,
      environment: {
        isExtensionDevelopmentDebug,
        appRoot: remoteInitData.appRoot,
        appName: this.C.nameLong,
        appHost: this.C.embedderIdentifier || "desktop",
        appUriScheme: this.C.urlProtocol,
        extensionTelemetryLogResource: this.r.extHostTelemetryLogFile,
        isExtensionTelemetryLoggingOnly: $jw(this.C, this.r),
        appLanguage: $z,
        extensionDevelopmentLocationURI: this.r.extensionDevelopmentLocationURI,
        extensionTestsLocationURI: this.r.extensionTestsLocationURI,
        globalStorageHome: remoteInitData.globalStorageHome,
        workspaceStorageHome: remoteInitData.workspaceStorageHome,
        extensionLogLevel: this.r.extensionLogLevel
      },
      workspace: this.n.getWorkbenchState() === 1 ? null : {
        configuration: workspace2.configuration,
        id: workspace2.id,
        name: this.w.getWorkspaceLabel(workspace2),
        transient: workspace2.transient
      },
      remote: {
        isRemote: true,
        authority: this.j.remoteAuthority,
        connectionData: remoteInitData.connectionData
      },
      consoleForward: {
        includeStack: false,
        logNative: Boolean(this.r.debugExtensionHost.debugId)
      },
      extensions: this.extensions.toSnapshot(),
      telemetryInfo: {
        sessionId: this.s.sessionId,
        machineId: this.s.machineId,
        sqmId: this.s.sqmId,
        devDeviceId: this.s.devDeviceId,
        firstSessionDate: this.s.firstSessionDate,
        msftInternal: this.s.msftInternal
      },
      logLevel: this.t.getLevel(),
      loggers: [...this.u.getRegisteredLoggers()],
      logsLocation: remoteInitData.extensionHostLogsPath,
      autoStart: this.startup === 1,
      uiKind: $r ? UIKind.Web : UIKind.Desktop
    };
  }
  getInspectPort() {
    return void 0;
  }
  enableInspectPort() {
    return Promise.resolve(false);
  }
  async disconnect() {
    if (this.b && !this.g) {
      this.b.send($jN(
        2
        /* MessageType.Terminate */
      ));
      this.b.sendDisconnect();
      this.g = true;
      await this.b.drain();
    }
  }
  dispose() {
    super.dispose();
    this.f = true;
    this.disconnect();
    if (this.b) {
      this.b.getSocket().end();
      this.b = null;
    }
  }
};
$Jnc = __decorate([
  __param(2, $gC),
  __param(3, $Zk),
  __param(4, $US),
  __param(5, $zv),
  __param(6, $wn),
  __param(7, $xn),
  __param(8, $ZI),
  __param(9, $bC),
  __param(10, $Ax),
  __param(11, $Vu),
  __param(12, $lz)
], $Jnc);

// out-build/vs/workbench/services/extensions/browser/extensionService.js
var $Lnc_1;
var $Knc = class $Knc2 extends $ync {
  constructor(instantiationService, notificationService, Sb, telemetryService, extensionEnablementService, fileService, productService, extensionManagementService, contextService, configurationService, extensionManifestPropertiesService, Tb, logService, remoteAgentService, remoteExtensionsScannerService, lifecycleService, remoteAuthorityResolverService, Ub, Vb, Wb, Xb, dialogService) {
    const extensionsProposedApi = instantiationService.createInstance($wnc);
    const extensionHostFactory = new BrowserExtensionHostFactory(extensionsProposedApi, () => this.$b(), () => this.Eb(), instantiationService, remoteAgentService, remoteAuthorityResolverService, extensionEnablementService, logService);
    super({ hasLocalProcess: false, allowRemoteExtensionsInLocalWebWorker: true }, extensionsProposedApi, extensionHostFactory, new $Lnc(logService), instantiationService, notificationService, Sb, telemetryService, extensionEnablementService, fileService, productService, extensionManagementService, contextService, configurationService, extensionManifestPropertiesService, logService, remoteAgentService, remoteExtensionsScannerService, lifecycleService, remoteAuthorityResolverService, dialogService);
    this.Sb = Sb;
    this.Tb = Tb;
    this.Ub = Ub;
    this.Vb = Vb;
    this.Wb = Wb;
    this.Xb = Xb;
    lifecycleService.when(
      2
      /* LifecyclePhase.Ready */
    ).then(async () => {
      await this.Ub.initializeInstalledExtensions(this.L);
      this.kb();
    });
    this.Yb();
  }
  Yb() {
    const provider = new $fnc();
    this.B(this.Q.registerProvider(Schemas.http, provider));
    this.B(this.Q.registerProvider(Schemas.https, provider));
  }
  async $b() {
    if (!this.Zb) {
      this.Zb = (async () => {
        const system = [], user = [], development = [];
        try {
          await Promise.all([
            this.Tb.scanSystemExtensions().then((extensions) => system.push(...extensions.map((e) => $EN(e)))),
            this.Tb.scanUserExtensions(this.Vb.currentProfile.extensionsResource, { skipInvalidExtensions: true }).then((extensions) => user.push(...extensions.map((e) => $EN(e)))),
            this.Tb.scanExtensionsUnderDevelopment().then((extensions) => development.push(...extensions.map((e) => $EN(e, true))))
          ]);
        } catch (error) {
          this.Y.error(error);
        }
        return $MY(system, user, [], development, this.Y);
      })();
    }
    return this.Zb;
  }
  async ac(emitter) {
    const [localExtensions, remoteExtensions] = await Promise.all([
      this.$b(),
      this.$.scanExtensions()
    ]);
    if (remoteExtensions.length) {
      emitter.emitOne(new $Bnc(remoteExtensions));
    }
    emitter.emitOne(new $Anc(localExtensions));
  }
  Pb() {
    return new $ji((emitter) => this.cc(emitter));
  }
  async cc(emitter) {
    if (!this.Sb.expectsResolverExtension) {
      return this.ac(emitter);
    }
    const remoteAuthority = this.N.remoteAuthority;
    await this.Wb.workspaceResolved;
    const localExtensions = await this.$b();
    const resolverExtensions = localExtensions.filter((extension) => $Cnc(extension));
    if (resolverExtensions.length) {
      emitter.emitOne(new $znc(resolverExtensions));
    }
    let resolverResult;
    try {
      resolverResult = await this.pb(remoteAuthority);
    } catch (err) {
      if ($eC.isHandled(err)) {
        console.log(`Error handled: Not showing a notification for the error`);
      }
      this.bb._setResolvedAuthorityError(remoteAuthority, err);
      return this.ac(emitter);
    }
    this.bb._setResolvedAuthority(resolverResult.authority, resolverResult.options);
    this.Xb.setTunnelInformation(resolverResult.tunnelInformation);
    const connection = this.Z.getConnection();
    if (connection) {
      connection.onDidStateChange(async (e) => {
        if (e.type === 0) {
          this.bb._clearResolvedAuthority(remoteAuthority);
        }
      });
      connection.onReconnecting(() => this.qb());
    }
    return this.ac(emitter);
  }
  async Qb(code) {
    await this.tb();
    const automatedWindow = $Y;
    if (typeof automatedWindow.codeAutomationExit === "function") {
      automatedWindow.codeAutomationExit(code, await $Oob(this.Q, this.N));
    }
  }
  async Rb(remoteAuthority) {
    return this.sb(2, remoteAuthority);
  }
};
$Knc = __decorate([
  __param(0, $Pk),
  __param(1, $PJ),
  __param(2, $M4),
  __param(3, $zv),
  __param(4, $qzb),
  __param(5, $km),
  __param(6, $Vu),
  __param(7, $pzb),
  __param(8, $Zk),
  __param(9, $kl),
  __param(10, $LCb),
  __param(11, $rzb),
  __param(12, $wn),
  __param(13, $RL),
  __param(14, $NY),
  __param(15, $KL),
  __param(16, $bC),
  __param(17, $9Vb),
  __param(18, $gT),
  __param(19, $4M),
  __param(20, $8Sb),
  __param(21, $Yv)
], $Knc);
var BrowserExtensionHostFactory = class BrowserExtensionHostFactory2 {
  constructor(a, b, c, d, f, g, h3, i2) {
    this.a = a;
    this.b = b;
    this.c = c;
    this.d = d;
    this.f = f;
    this.g = g;
    this.h = h3;
    this.i = i2;
  }
  createExtensionHost(runningLocations, runningLocation, isInitialStart) {
    switch (runningLocation.kind) {
      case 1: {
        return null;
      }
      case 2: {
        const startup = isInitialStart ? 2 : 1;
        return this.d.createInstance($enc, runningLocation, startup, this.j(runningLocations, runningLocation, isInitialStart));
      }
      case 3: {
        const remoteAgentConnection = this.f.getConnection();
        if (remoteAgentConnection) {
          return this.d.createInstance($Jnc, runningLocation, this.k(runningLocations, remoteAgentConnection.remoteAuthority));
        }
        return null;
      }
    }
  }
  j(runningLocations, desiredRunningLocation, isInitialStart) {
    return {
      getInitData: async () => {
        if (isInitialStart) {
          const localExtensions = $Dnc(
            this.i,
            this.h,
            this.a,
            await this.b(),
            /* ignore workspace trust */
            true
          );
          const runningLocation = runningLocations.computeRunningLocation(localExtensions, [], false);
          const myExtensions = $unc(localExtensions, runningLocation, (extRunningLocation) => desiredRunningLocation.equals(extRunningLocation));
          const extensions = new $yN(0, localExtensions, myExtensions.map((extension) => extension.identifier));
          return { extensions };
        } else {
          const snapshot = await this.c();
          const myExtensions = runningLocations.filterByRunningLocation(snapshot.extensions, desiredRunningLocation);
          const extensions = new $yN(snapshot.versionId, snapshot.extensions, myExtensions.map((extension) => extension.identifier));
          return { extensions };
        }
      }
    };
  }
  k(runningLocations, remoteAuthority) {
    return {
      remoteAuthority,
      getInitData: async () => {
        const snapshot = await this.c();
        const remoteEnv = await this.f.getEnvironment();
        if (!remoteEnv) {
          throw new Error("Cannot provide init data for remote extension host!");
        }
        const myExtensions = runningLocations.filterByExtensionHostKind(
          snapshot.extensions,
          3
          /* ExtensionHostKind.Remote */
        );
        const extensions = new $yN(snapshot.versionId, snapshot.extensions, myExtensions.map((extension) => extension.identifier));
        return {
          connectionData: this.g.getConnectionData(remoteAuthority),
          pid: remoteEnv.pid,
          appRoot: remoteEnv.appRoot,
          extensionHostLogsPath: remoteEnv.extensionHostLogsPath,
          globalStorageHome: remoteEnv.globalStorageHome,
          workspaceStorageHome: remoteEnv.workspaceStorageHome,
          extensions
        };
      }
    };
  }
};
BrowserExtensionHostFactory = __decorate([
  __param(3, $Pk),
  __param(4, $RL),
  __param(5, $bC),
  __param(6, $qzb),
  __param(7, $wn)
], BrowserExtensionHostFactory);
var $Lnc = $Lnc_1 = class $Lnc2 {
  constructor(a) {
    this.a = a;
  }
  pickExtensionHostKind(extensionId, extensionKinds, isInstalledLocally, isInstalledRemotely, preference) {
    const result = $Lnc_1.pickRunningLocation(extensionKinds, isInstalledLocally, isInstalledRemotely, preference);
    this.a.trace(`pickRunningLocation for ${extensionId.value}, extension kinds: [${extensionKinds.join(", ")}], isInstalledLocally: ${isInstalledLocally}, isInstalledRemotely: ${isInstalledRemotely}, preference: ${$hN(preference)} => ${$gN(result)}`);
    return result;
  }
  static pickRunningLocation(extensionKinds, isInstalledLocally, isInstalledRemotely, preference) {
    const result = [];
    let canRunRemotely = false;
    for (const extensionKind of extensionKinds) {
      if (extensionKind === "ui" && isInstalledRemotely) {
        if (preference === 2) {
          return 3;
        } else {
          canRunRemotely = true;
        }
      }
      if (extensionKind === "workspace" && isInstalledRemotely) {
        if (preference === 0 || preference === 2) {
          return 3;
        } else {
          result.push(
            3
            /* ExtensionHostKind.Remote */
          );
        }
      }
      if (extensionKind === "web" && (isInstalledLocally || isInstalledRemotely)) {
        if (preference === 0 || preference === 1) {
          return 2;
        } else {
          result.push(
            2
            /* ExtensionHostKind.LocalWebWorker */
          );
        }
      }
    }
    if (canRunRemotely) {
      result.push(
        3
        /* ExtensionHostKind.Remote */
      );
    }
    return result.length > 0 ? result[0] : null;
  }
};
$Lnc = $Lnc_1 = __decorate([
  __param(0, $wn)
], $Lnc);
$SC(
  $wN,
  $Knc,
  0
  /* InstantiationType.Eager */
);

// 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 $PA = class extends Error {
  constructor(message, code) {
    super(message);
    this.code = code;
  }
};
var $QA = $Qk("IExtensionsProfileScannerService");
var $RA = class $RA2 extends $3c {
  constructor(j, m, n, r2, s, t) {
    super();
    this.j = j;
    this.m = m;
    this.n = n;
    this.r = r2;
    this.s = s;
    this.t = t;
    this.b = this.B(new $ze());
    this.onAddExtensions = this.b.event;
    this.c = this.B(new $ze());
    this.onDidAddExtensions = this.c.event;
    this.f = this.B(new $ze());
    this.onRemoveExtensions = this.f.event;
    this.g = this.B(new $ze());
    this.onDidRemoveExtensions = this.g.event;
    this.h = new $Ec();
  }
  scanProfileExtensions(profileLocation, options3) {
    return this.u(profileLocation, void 0, options3);
  }
  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]) => $DA(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) => $DA(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]) => $DA(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 ($DA(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, options3) {
    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 ($Bm(error) !== 1) {
          throw error;
        }
        if (this.r.extUri.isEqual(file, this.n.defaultProfile.extensionsResource)) {
          storedProfileExtensions = await this.D();
        }
        if (!storedProfileExtensions && options3?.bailOutWhenFileNotFound) {
          throw new $PA(
            $qb(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 location3;
          if ($zg(e.relativeLocation) && e.relativeLocation) {
            location3 = this.z(e.relativeLocation);
          } else if ($zg(e.location)) {
            this.t.warn(`Extensions profile: Ignoring extension with invalid location: ${e.location}`);
            continue;
          } else {
            location3 = URI.revive(e.location);
            const relativePath = this.y(location3);
            if (relativePath) {
              migrate = true;
              e.relativeLocation = relativePath;
            }
          }
          if ($Gg(e.metadata?.hasPreReleaseVersion) && e.metadata?.preRelease) {
            migrate = true;
            e.metadata.hasPreReleaseVersion = true;
          }
          extensions.push({
            identifier: e.identifier,
            location: location3,
            version: e.version,
            metadata: e.metadata
          });
        }
        if (migrate) {
          await this.m.writeFile(file, $Ci.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, $Ci.fromString(JSON.stringify(storedProfileExtensions2)));
      }
      return extensions;
    });
  }
  w(file) {
    const error = new $PA(
      `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(path) {
    return this.r.extUri.joinPath(this.j, path);
  }
  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 ($Bm(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, $Ci.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 ($Bm(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 ($Bm(error) !== 1) {
            this.t.error(error);
          }
        }
        try {
          await this.m.del(oldDefaultProfileExtensionsInitLocation);
        } catch (error) {
          if ($Bm(error) !== 1) {
            this.t.error(error);
          }
        }
        return storedProfileExtensions;
      })();
    }
    return this.C;
  }
  F(file) {
    let resourceQueue = this.h.get(file);
    if (!resourceQueue) {
      resourceQueue = new $3h();
      this.h.set(file, resourceQueue);
    }
    return resourceQueue;
  }
};
$RA = __decorate([
  __param(1, $km),
  __param(2, $rs),
  __param(3, $vl),
  __param(4, $zv),
  __param(5, $wn)
], $RA);
function isStoredProfileExtension(candidate) {
  return $Bg(candidate) && $oA(candidate.identifier) && (isUriComponents(candidate.location) || $zg(candidate.location) && candidate.location) && ($Gg(candidate.relativeLocation) || $zg(candidate.relativeLocation)) && candidate.version && $zg(candidate.version);
}
function isUriComponents(thing) {
  if (!thing) {
    return false;
  }
  return $zg(thing.path) && $zg(thing.scheme);
}

// out-build/vs/workbench/services/extensionManagement/browser/extensionsProfileScannerService.js
var $Mnc = class $Mnc2 extends $RA {
  constructor(environmentService, fileService, userDataProfilesService, uriIdentityService, telemetryService, logService) {
    super(environmentService.userRoamingDataHome, fileService, userDataProfilesService, uriIdentityService, telemetryService, logService);
  }
};
$Mnc = __decorate([
  __param(0, $US),
  __param(1, $km),
  __param(2, $rs),
  __param(3, $vl),
  __param(4, $zv),
  __param(5, $wn)
], $Mnc);
$SC(
  $QA,
  $Mnc,
  1
  /* InstantiationType.Delayed */
);

// 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 key2 of Object.keys(b)) {
      bKeys.add(key2);
    }
    if (aKeys.length !== bKeys.size) {
      return false;
    }
    for (const key2 of aKeys) {
      if (a[key2] !== b[key2]) {
        return false;
      }
      bKeys.delete(key2);
    }
    return bKeys.size === 0;
  }
  Translations2.equals = equals;
})(Translations || (Translations = {}));
var $4A = $Qk("IExtensionsScannerService");
var $5A = class $5A2 extends $3c {
  constructor(systemExtensionsLocation, userExtensionsLocation, r2, s, t, u, w, y, z, C, D, F) {
    super();
    this.systemExtensionsLocation = systemExtensionsLocation;
    this.userExtensionsLocation = userExtensionsLocation;
    this.r = r2;
    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 $ze());
    this.onDidChangeCache = this.g.event;
    this.h = $vh(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 = $OA(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 promises = [];
    promises.push(this.M(!!scanOptions.useCache, scanOptions.language));
    promises.push(this.N(scanOptions.language, !!scanOptions.checkControlFile));
    const [defaultSystemExtensions, devSystemExtensions] = await Promise.all(promises);
    return this.J([...defaultSystemExtensions, ...devSystemExtensions], 0, scanOptions, false);
  }
  async scanUserExtensions(scanOptions) {
    const location3 = scanOptions.profileLocation ?? this.userExtensionsLocation;
    this.y.trace("Started scanning user extensions", location3);
    const profileScanOptions = this.D.extUri.isEqual(scanOptions.profileLocation, this.t.defaultProfile.extensionsResource) ? { bailOutWhenFileNotFound: true } : void 0;
    const extensionsScannerInput = await this.P(location3, !!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 $PA && 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) => $DA(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 = $vh(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 = $vh(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($vh(extensionLocation, "package.json"), $Ci.fromString(JSON.stringify(manifest, null, "	")));
  }
  async initializeDefaultProfileExtensions() {
    try {
      await this.u.scanProfileExtensions(this.t.defaultProfile.extensionsResource, { bailOutWhenFileNotFound: true });
    } catch (error) {
      if (error instanceof $PA && 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, $Ci.fromString(JSON.stringify([])));
            } catch (error) {
              if ($Bm(error) !== 1) {
                this.y.warn("Failed to create default profile extensions manifest in extensions installation folder.", this.userExtensionsLocation.toString(), $qb(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, type, scanOptions, pickLatest) {
    if (!scanOptions.includeAllVersions) {
      extensions = this.L(type === 0 ? extensions : void 0, type === 1 ? extensions : void 0, type === "development" ? extensions : void 0, await this.getTargetPlatform(), pickLatest);
    }
    if (!scanOptions.includeInvalid) {
      extensions = extensions.filter((extension) => extension.isValid);
    }
    return extensions.sort((a, b) => {
      const aLastSegment = $rc(a.location.fsPath);
      const bLastSegment = $rc(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 $7z();
    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($lc($nc($ih.asFileUri("").fsPath, "..", ".build", "builtInExtensions")));
    for (const extension of devSystemExtensionsList) {
      const controlState = builtinExtensionControl[extension.name] || "marketplace";
      switch (controlState) {
        case "disabled":
          break;
        case "marketplace":
          devSystemExtensionsLocations.push($vh(devSystemExtensionsLocation, extension.name));
          break;
        default:
          devSystemExtensionsLocations.push(URI.file(controlState));
          break;
      }
    }
    const result = await Promise.all(devSystemExtensionsLocations.map(async (location3) => this.n.scanExtension(await this.P(location3, false, 0, true, language, true, void 0, this.R()))));
    this.y.trace("Scanned dev system extensions:", result.length);
    return $Mb(result);
  }
  async O() {
    try {
      const content = await this.w.readFile(this.r);
      return JSON.parse(content.value.toString());
    } catch (error) {
      return {};
    }
  }
  async P(location3, profile, type, excludeObsolete, language, validate, profileScanOptions, productVersion) {
    const translations = await this.f(language ?? $z);
    const mtime = await this.Q(location3);
    const applicationExtensionsLocation = profile && !this.D.extUri.isEqual(location3, this.t.defaultProfile.extensionsResource) ? this.t.defaultProfile.extensionsResource : void 0;
    const applicationExtensionsLocationMtime = applicationExtensionsLocation ? await this.Q(applicationExtensionsLocation) : void 0;
    return new $6A(location3, mtime, applicationExtensionsLocation, applicationExtensionsLocationMtime, profile, profileScanOptions, type, excludeObsolete, validate, productVersion.version, productVersion.date, this.C.commit, !this.z.isBuilt, language, translations);
  }
  async Q(location3) {
    try {
      const stat = await this.w.stat(location3);
      if (typeof stat.mtime === "number") {
        return stat.mtime;
      }
    } catch (err) {
    }
    return void 0;
  }
  R() {
    return {
      version: this.C.version,
      date: this.C.date
    };
  }
};
$5A = __decorate([
  __param(4, $rs),
  __param(5, $QA),
  __param(6, $km),
  __param(7, $wn),
  __param(8, $Xk),
  __param(9, $Vu),
  __param(10, $vl),
  __param(11, $Pk)
], $5A);
var $6A = class {
  constructor(location3, mtime, applicationExtensionslocation, applicationExtensionslocationMtime, profile, profileScanOptions, type, excludeObsolete, validate, productVersion, productDate, productCommit, devMode, language, translations) {
    this.location = location3;
    this.mtime = mtime;
    this.applicationExtensionslocation = applicationExtensionslocation;
    this.applicationExtensionslocationMtime = applicationExtensionslocationMtime;
    this.profile = profile;
    this.profileScanOptions = profileScanOptions;
    this.type = type;
    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 $oh(a.location, b.location) && a.mtime === b.mtime && $oh(a.applicationExtensionslocation, b.applicationExtensionslocation) && a.applicationExtensionslocationMtime === b.applicationExtensionslocationMtime && a.profile === b.profile && $Pv(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 $3c {
  constructor(g, h3, j, m, productService, n, r2) {
    super();
    this.g = g;
    this.h = h3;
    this.j = j;
    this.m = m;
    this.n = n;
    this.r = r2;
    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 $Mg(obsolete) ? extensions : extensions.filter((e) => !obsolete[$EA.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 && $sh(c.resource).indexOf(".") === 0) {
        return null;
      }
      const extensionScannerInput = new $6A(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 $Mb(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 $6A(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 $Mb(extensions);
  }
  async scanOneOrMultipleExtensions(input) {
    try {
      if (await this.m.exists($vh(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}:`, $qb(error));
      return [];
    }
  }
  async scanExtension(input, metadata) {
    try {
      let manifest = await this.w(input.location);
      if (manifest) {
        if (!manifest.publisher) {
          manifest.publisher = $1z;
        }
        metadata = metadata ?? manifest.__metadata;
        if (metadata && !metadata?.size && manifest.__metadata?.size) {
          metadata.size = manifest.__metadata?.size;
        }
        delete manifest.__metadata;
        const id2 = $IA(manifest.publisher, manifest.name);
        const identifier2 = metadata?.id ? { id: id2, uuid: metadata.id } : { id: id2 };
        const type = metadata?.isSystem ? 0 : input.type;
        const isBuiltin = type === 0 || !!metadata?.isBuiltin;
        manifest = await this.y(input.location, manifest, $6A.createNlsConfiguration(input));
        let extension = {
          type,
          identifier: identifier2,
          manifest,
          location: input.location,
          isBuiltin,
          targetPlatform: metadata?.targetPlatform ?? "undefined",
          publisherDisplayName: metadata?.publisherDisplayName,
          metadata,
          isValid: true,
          validations: [],
          preRelease: !!metadata?.preRelease
        };
        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 = $aA([...manifest.enabledApiProposals]);
        }
        return extension;
      }
    } catch (e) {
      if (input.type !== 0) {
        this.r.error(e);
      }
    }
    return null;
  }
  validate(extension, input) {
    let isValid2 = true;
    const validateApiVersion = this.n.isBuilt && this.f.includes(extension.identifier.id.toLowerCase());
    const validations = $YA(input.productVersion, input.productDate, input.location, extension.manifest, extension.isBuiltin, validateApiVersion);
    for (const [severity, message] of validations) {
      if (severity === severity_default.Error) {
        isValid2 = false;
        this.r.error(this.F(input.location, message));
      }
    }
    extension.isValid = isValid2;
    extension.validations = validations;
    return extension;
  }
  async w(extensionLocation) {
    const manifestLocation = $vh(extensionLocation, "package.json");
    let content;
    try {
      content = (await this.m.readFile(manifestLocation)).value.toString();
    } catch (error) {
      if ($Bm(error) !== 1) {
        this.r.error(this.F(extensionLocation, localize(1855, null, manifestLocation.path, error.message)));
      }
      return null;
    }
    let manifest;
    try {
      manifest = JSON.parse(content);
    } catch (err) {
      const errors = [];
      $yw(content, errors);
      for (const e of errors) {
        this.r.error(this.F(extensionLocation, localize(1856, null, manifestLocation.path, e.offset, e.length, $SA(e.error))));
      }
      return null;
    }
    if ($Gw(manifest) !== "object") {
      this.r.error(this.F(extensionLocation, localize(1857, 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(1858, null, localizedMessages.default?.path, $SA(error.error))));
          });
          return extensionManifest;
        } else if ($Gw(localizedMessages) !== "object") {
          this.r.error(this.F(extensionLocation, localize(1859, null, localizedMessages.default?.path)));
          return extensionManifest;
        }
        const localized = localizedMessages.values || /* @__PURE__ */ Object.create(null);
        return $3A(this.r, extensionManifest, localized, defaults);
      } catch (error) {
      }
    }
    return extensionManifest;
  }
  async z(extensionLocation, extensionManifest, nlsConfiguration) {
    const defaultPackageNLS = $vh(extensionLocation, "package.nls.json");
    const reportErrors = (localized, errors) => {
      errors.forEach((error) => {
        this.r.error(this.F(extensionLocation, localize(1860, null, localized?.path, $SA(error.error))));
      });
    };
    const reportInvalidFormat = (localized) => {
      this.r.error(this.F(extensionLocation, localize(1861, 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 = $yw(content, errors);
        if (errors.length > 0) {
          reportErrors(translationResource, errors);
          return { values: void 0, default: defaultPackageNLS };
        } else if ($Gw(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 = $yw(messageBundleContent, errors);
        if (errors.length > 0) {
          reportErrors(messageBundle.localized, errors);
          return { values: void 0, default: messageBundle.original };
        } else if ($Gw(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 $yw(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 = $vh(extensionLocation, `package.nls.${locale}.json`);
        this.m.exists(toCheck).then((exists) => {
          if (exists) {
            c({ localized: toCheck, original: $vh(extensionLocation, "package.nls.json") });
          }
          const index = locale.lastIndexOf("-");
          if (index === -1) {
            c({ localized: $vh(extensionLocation, "package.nls.json"), original: null });
          } else {
            locale = locale.substring(0, index);
            loop(locale);
          }
        });
      };
      if (nlsConfiguration.devMode || nlsConfiguration.pseudo || !nlsConfiguration.language) {
        return c({ localized: $vh(extensionLocation, "package.nls.json"), original: null });
      }
      loop(nlsConfiguration.language);
    });
  }
  F(extensionLocation, message) {
    return `[${extensionLocation.path}]: ${message}`;
  }
};
ExtensionsScanner = __decorate([
  __param(1, $QA),
  __param(2, $vl),
  __param(3, $km),
  __param(4, $Vu),
  __param(5, $Xk),
  __param(6, $wn)
], 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 $Th(3e3));
    this.I = this.B(new $ze());
    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 && $6A.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: $cu(extensionCacheData.input) };
    } catch (error) {
      this.r.debug("Error while reading the extension cache file:", cacheFile.path, $qb(error));
    }
    return null;
  }
  async N(cacheFile, cacheContents) {
    try {
      await this.m.writeFile(cacheFile, $Ci.fromString(JSON.stringify(cacheContents)));
    } catch (error) {
      this.r.debug("Error while writing the extension cache file:", cacheFile.path, $qb(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 ($Pv(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 ? $Zz : $Yz);
  }
  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, $rs),
  __param(3, $QA),
  __param(4, $vl),
  __param(5, $km),
  __param(6, $Vu),
  __param(7, $Xk),
  __param(8, $wn)
], CachedExtensionsScanner);

// out-build/vs/workbench/services/extensions/browser/extensionsScannerService.js
var $Nnc = class $Nnc2 extends $5A {
  constructor(userDataProfileService, userDataProfilesService, extensionsProfileScannerService, fileService, logService, environmentService, productService, uriIdentityService, instantiationService) {
    super(uriIdentityService.extUri.joinPath(environmentService.userRoamingDataHome, "systemExtensions"), uriIdentityService.extUri.joinPath(environmentService.userRoamingDataHome, "userExtensions"), uriIdentityService.extUri.joinPath(environmentService.userRoamingDataHome, "userExtensions", "control.json"), userDataProfileService.currentProfile, userDataProfilesService, extensionsProfileScannerService, fileService, logService, environmentService, productService, uriIdentityService, instantiationService);
  }
  async f() {
    return {};
  }
};
$Nnc = __decorate([
  __param(0, $gT),
  __param(1, $rs),
  __param(2, $QA),
  __param(3, $km),
  __param(4, $wn),
  __param(5, $US),
  __param(6, $Vu),
  __param(7, $vl),
  __param(8, $Pk)
], $Nnc);
$SC(
  $4A,
  $Nnc,
  1
  /* InstantiationType.Delayed */
);

// out-build/vs/workbench/services/extensionManagement/browser/webExtensionsScannerService.js
function isGalleryExtensionInfo(obj) {
  const galleryExtensionInfo = obj;
  return typeof galleryExtensionInfo?.id === "string" && (galleryExtensionInfo.preRelease === void 0 || typeof galleryExtensionInfo.preRelease === "boolean") && (galleryExtensionInfo.migrateStorageFrom === void 0 || typeof galleryExtensionInfo.migrateStorageFrom === "string");
}
function isUriComponents2(thing) {
  if (!thing) {
    return false;
  }
  return $zg(thing.path) && $zg(thing.scheme);
}
var $Onc = class $Onc2 extends $3c {
  constructor(j, m, n, r2, s, t, u, w, y, z, C, D, lifecycleService) {
    super();
    this.j = j;
    this.m = m;
    this.n = n;
    this.r = r2;
    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.c = void 0;
    this.f = void 0;
    this.g = new $Ec();
    if ($r) {
      this.c = $vh(j.userRoamingDataHome, "systemExtensionsCache.json");
      this.f = $vh(j.userRoamingDataHome, "customBuiltinExtensionsCache.json");
      lifecycleService.when(
        4
        /* LifecyclePhase.Eventually */
      ).then(() => this.Q());
    }
    this.h = z.extensionsEnabledWithApiProposalVersion?.map((id2) => id2.toLowerCase()) ?? [];
  }
  G() {
    if (!this.F) {
      this.F = (async () => {
        let extensions = [];
        const extensionLocations = [];
        const extensionGalleryResources = [];
        const extensionsToMigrate = [];
        const customBuiltinExtensionsInfo = this.j.options && Array.isArray(this.j.options.additionalBuiltinExtensions) ? this.j.options.additionalBuiltinExtensions.map((additionalBuiltinExtension) => $zg(additionalBuiltinExtension) ? { id: additionalBuiltinExtension } : additionalBuiltinExtension) : [];
        for (const e of customBuiltinExtensionsInfo) {
          if (isGalleryExtensionInfo(e)) {
            extensions.push({ id: e.id, preRelease: !!e.preRelease });
            if (e.migrateStorageFrom) {
              extensionsToMigrate.push([e.migrateStorageFrom, e.id]);
            }
          } else if (isUriComponents2(e)) {
            const extensionLocation = URI.revive(e);
            if (this.u.isExtensionGalleryResource(extensionLocation)) {
              extensionGalleryResources.push(extensionLocation);
            } else {
              extensionLocations.push(extensionLocation);
            }
          }
        }
        if (extensions.length) {
          extensions = await this.H(extensions);
        }
        if (extensions.length) {
          this.r.info("Found additional builtin gallery extensions in env", extensions);
        }
        if (extensionLocations.length) {
          this.r.info("Found additional builtin location extensions in env", extensionLocations.map((e) => e.toString()));
        }
        if (extensionGalleryResources.length) {
          this.r.info("Found additional builtin extension gallery resources in env", extensionGalleryResources.map((e) => e.toString()));
        }
        return { extensions, extensionsToMigrate, extensionLocations, extensionGalleryResources };
      })();
    }
    return this.F;
  }
  async H(extensions) {
    const extensionsControlManifest = await this.s.getExtensionsControlManifest();
    const result = [];
    for (const extension of extensions) {
      if (extensionsControlManifest.malicious.some((e) => $DA(e, { id: extension.id }))) {
        this.r.info(`Checking additional builtin extensions: Ignoring '${extension.id}' because it is reported to be malicious.`);
        continue;
      }
      const deprecationInfo = extensionsControlManifest.deprecated[extension.id.toLowerCase()];
      if (deprecationInfo?.extension?.autoMigrate) {
        const preReleaseExtensionId = deprecationInfo.extension.id;
        this.r.info(`Checking additional builtin extensions: '${extension.id}' is deprecated, instead using '${preReleaseExtensionId}'`);
        result.push({ id: preReleaseExtensionId, preRelease: !!extension.preRelease });
      } else {
        result.push(extension);
      }
    }
    return result;
  }
  /**
   * All system extensions bundled with the product
   */
  async I() {
    const systemExtensions = await this.m.scanBuiltinExtensions();
    const cachedSystemExtensions = await Promise.all((await this.pb()).map((e) => this.gb(
      e,
      true,
      0
      /* ExtensionType.System */
    )));
    const result = /* @__PURE__ */ new Map();
    for (const extension of [...systemExtensions, ...cachedSystemExtensions]) {
      const existing = result.get(extension.identifier.id.toLowerCase());
      if (existing) {
        if (gt(existing.manifest.version, extension.manifest.version)) {
          continue;
        }
      }
      result.set(extension.identifier.id.toLowerCase(), extension);
    }
    return [...result.values()];
  }
  /**
   * All extensions defined via `additionalBuiltinExtensions` API
   */
  async J(scanOptions) {
    const [customBuiltinExtensionsFromLocations, customBuiltinExtensionsFromGallery] = await Promise.all([
      this.L(scanOptions),
      this.M(scanOptions)
    ]);
    const customBuiltinExtensions = [...customBuiltinExtensionsFromLocations, ...customBuiltinExtensionsFromGallery];
    await this.P(customBuiltinExtensions);
    return customBuiltinExtensions;
  }
  async L(scanOptions) {
    const { extensionLocations } = await this.G();
    if (!extensionLocations.length) {
      return [];
    }
    const result = [];
    await Promise.allSettled(extensionLocations.map(async (extensionLocation) => {
      try {
        const webExtension = await this.fb(extensionLocation);
        const extension = await this.gb(webExtension, true);
        if (extension.isValid || !scanOptions?.skipInvalidExtensions) {
          result.push(extension);
        } else {
          this.r.info(`Skipping invalid additional builtin extension ${webExtension.identifier.id}`);
        }
      } catch (error) {
        this.r.info(`Error while fetching the additional builtin extension ${extensionLocation.toString()}.`, $qb(error));
      }
    }));
    return result;
  }
  async M(scanOptions) {
    if (!this.s.isEnabled()) {
      this.r.info("Ignoring fetching additional builtin extensions from gallery as it is disabled.");
      return [];
    }
    const result = [];
    const { extensions, extensionGalleryResources } = await this.G();
    try {
      const cacheValue = JSON.stringify({
        extensions: extensions.sort((a, b) => a.id.localeCompare(b.id)),
        extensionGalleryResources: extensionGalleryResources.map((e) => e.toString()).sort()
      });
      const useCache = this.y.get("additionalBuiltinExtensions", -1, "{}") === cacheValue;
      const webExtensions = await (useCache ? this.N() : this.U());
      if (webExtensions.length) {
        await Promise.all(webExtensions.map(async (webExtension) => {
          try {
            const extension = await this.gb(webExtension, true);
            if (extension.isValid || !scanOptions?.skipInvalidExtensions) {
              result.push(extension);
            } else {
              this.r.info(`Skipping invalid additional builtin gallery extension ${webExtension.identifier.id}`);
            }
          } catch (error) {
            this.r.info(`Ignoring additional builtin extension ${webExtension.identifier.id} because there is an error while converting it into scanned extension`, $qb(error));
          }
        }));
      }
      this.y.store(
        "additionalBuiltinExtensions",
        cacheValue,
        -1,
        1
        /* StorageTarget.MACHINE */
      );
    } catch (error) {
      this.r.info("Ignoring following additional builtin extensions as there is an error while fetching them from gallery", extensions.map(({ id: id2 }) => id2), $qb(error));
    }
    return result;
  }
  async N() {
    const cachedCustomBuiltinExtensions = await this.nb();
    const webExtensionsMap = /* @__PURE__ */ new Map();
    for (const webExtension of cachedCustomBuiltinExtensions) {
      const existing = webExtensionsMap.get(webExtension.identifier.id.toLowerCase());
      if (existing) {
        if (gt(existing.version, webExtension.version)) {
          continue;
        }
      }
      if (webExtension.metadata?.isPreReleaseVersion && !webExtension.metadata?.preRelease) {
        webExtension.metadata.preRelease = true;
      }
      webExtensionsMap.set(webExtension.identifier.id.toLowerCase(), webExtension);
    }
    return [...webExtensionsMap.values()];
  }
  async P(customBuiltinExtensions) {
    if (!this.O) {
      this.O = (async () => {
        const { extensionsToMigrate } = await this.G();
        if (!extensionsToMigrate.length) {
          return;
        }
        const fromExtensions = await this.s.getExtensions(extensionsToMigrate.map(([id2]) => ({ id: id2 })), CancellationToken.None);
        try {
          await Promise.allSettled(extensionsToMigrate.map(async ([from, to]) => {
            const toExtension2 = customBuiltinExtensions.find((extension) => $DA(extension.identifier, { id: to }));
            if (toExtension2) {
              const fromExtension = fromExtensions.find((extension) => $DA(extension.identifier, { id: from }));
              const fromExtensionManifest = fromExtension ? await this.s.getManifest(fromExtension, CancellationToken.None) : null;
              const fromExtensionId = fromExtensionManifest ? $GA(fromExtensionManifest.publisher, fromExtensionManifest.name) : from;
              const toExtensionId = $GA(toExtension2.manifest.publisher, toExtension2.manifest.name);
              this.w.addToMigrationList(fromExtensionId, toExtensionId);
            } else {
              this.r.info(`Skipped migrating extension storage from '${from}' to '${to}', because the '${to}' extension is not found.`);
            }
          }));
        } catch (error) {
          this.r.error(error);
        }
      })();
    }
    return this.O;
  }
  async Q() {
    await this.R();
    await this.U();
  }
  async R() {
    const systemExtensions = await this.m.scanBuiltinExtensions();
    const cachedSystemExtensions = (await this.pb()).filter((cached) => {
      const systemExtension = systemExtensions.find((e) => $DA(e.identifier, cached.identifier));
      return systemExtension && gt(cached.version, systemExtension.manifest.version);
    });
    await this.qb(() => cachedSystemExtensions);
  }
  async U() {
    if (!this.S) {
      this.S = (async () => {
        this.r.info("Updating additional builtin extensions cache");
        const { extensions, extensionGalleryResources } = await this.G();
        const [galleryWebExtensions, extensionGalleryResourceWebExtensions] = await Promise.all([
          this.X(extensions),
          this.W(extensionGalleryResources)
        ]);
        const webExtensionsMap = /* @__PURE__ */ new Map();
        for (const webExtension of [...galleryWebExtensions, ...extensionGalleryResourceWebExtensions]) {
          webExtensionsMap.set(webExtension.identifier.id.toLowerCase(), webExtension);
        }
        await this.Y(extensionGalleryResourceWebExtensions, webExtensionsMap);
        const webExtensions = [...webExtensionsMap.values()];
        await this.ob(() => webExtensions);
        return webExtensions;
      })();
    }
    return this.S;
  }
  async W(extensionGalleryResources) {
    if (extensionGalleryResources.length === 0) {
      return [];
    }
    const result = /* @__PURE__ */ new Map();
    const extensionInfos = [];
    await Promise.all(extensionGalleryResources.map(async (extensionGalleryResource) => {
      try {
        const webExtension = await this.db(extensionGalleryResource);
        result.set(webExtension.identifier.id.toLowerCase(), webExtension);
        extensionInfos.push({ id: webExtension.identifier.id, version: webExtension.version });
      } catch (error) {
        this.r.info(`Ignoring additional builtin extension from gallery resource ${extensionGalleryResource.toString()} because there is an error while converting it into web extension`, $qb(error));
      }
    }));
    const galleryExtensions = await this.s.getExtensions(extensionInfos, CancellationToken.None);
    for (const galleryExtension of galleryExtensions) {
      const webExtension = result.get(galleryExtension.identifier.id.toLowerCase());
      if (webExtension) {
        result.set(galleryExtension.identifier.id.toLowerCase(), {
          ...webExtension,
          identifier: { id: webExtension.identifier.id, uuid: galleryExtension.identifier.uuid },
          readmeUri: galleryExtension.assets.readme ? URI.parse(galleryExtension.assets.readme.uri) : void 0,
          changelogUri: galleryExtension.assets.changelog ? URI.parse(galleryExtension.assets.changelog.uri) : void 0,
          metadata: { isPreReleaseVersion: galleryExtension.properties.isPreReleaseVersion, preRelease: galleryExtension.properties.isPreReleaseVersion, isBuiltin: true, pinned: true }
        });
      }
    }
    return [...result.values()];
  }
  async X(extensions) {
    if (extensions.length === 0) {
      return [];
    }
    const webExtensions = [];
    const galleryExtensionsMap = await this.Z(extensions);
    const missingExtensions = extensions.filter(({ id: id2 }) => !galleryExtensionsMap.has(id2.toLowerCase()));
    if (missingExtensions.length) {
      this.r.info("Skipping the additional builtin extensions because their compatible versions are not found.", missingExtensions);
    }
    await Promise.all([...galleryExtensionsMap.values()].map(async (gallery) => {
      try {
        const webExtension = await this.cb(gallery, { isPreReleaseVersion: gallery.properties.isPreReleaseVersion, preRelease: gallery.properties.isPreReleaseVersion, isBuiltin: true });
        webExtensions.push(webExtension);
      } catch (error) {
        this.r.info(`Ignoring additional builtin extension ${gallery.identifier.id} because there is an error while converting it into web extension`, $qb(error));
      }
    }));
    return webExtensions;
  }
  async Y(webExtensions, result) {
    const extensionInfos = [];
    for (const webExtension of webExtensions) {
      for (const e of [...webExtension.manifest?.extensionDependencies ?? [], ...webExtension.manifest?.extensionPack ?? []]) {
        if (!result.has(e.toLowerCase())) {
          extensionInfos.push({ id: e, version: webExtension.version });
        }
      }
    }
    if (extensionInfos.length === 0) {
      return;
    }
    const galleryExtensions = await this.Z(extensionInfos, /* @__PURE__ */ new Set([...result.keys()]));
    await Promise.all([...galleryExtensions.values()].map(async (gallery) => {
      try {
        const webExtension = await this.cb(gallery, { isPreReleaseVersion: gallery.properties.isPreReleaseVersion, preRelease: gallery.properties.isPreReleaseVersion, isBuiltin: true });
        result.set(webExtension.identifier.id.toLowerCase(), webExtension);
      } catch (error) {
        this.r.info(`Ignoring additional builtin extension ${gallery.identifier.id} because there is an error while converting it into web extension`, $qb(error));
      }
    }));
  }
  async Z(toGet, seen = /* @__PURE__ */ new Set(), result = /* @__PURE__ */ new Map()) {
    if (toGet.length === 0) {
      return result;
    }
    const extensions = await this.s.getExtensions(toGet, {
      compatible: true,
      targetPlatform: "web"
      /* TargetPlatform.WEB */
    }, CancellationToken.None);
    const packsAndDependencies = /* @__PURE__ */ new Map();
    for (const extension of extensions) {
      result.set(extension.identifier.id.toLowerCase(), extension);
      for (const id2 of [...$Qb(extension.properties.dependencies) ? extension.properties.dependencies : [], ...$Qb(extension.properties.extensionPack) ? extension.properties.extensionPack : []]) {
        if (!result.has(id2.toLowerCase()) && !packsAndDependencies.has(id2.toLowerCase()) && !seen.has(id2.toLowerCase())) {
          const extensionInfo = toGet.find((e) => $DA(e, extension.identifier));
          packsAndDependencies.set(id2.toLowerCase(), { id: id2, preRelease: extensionInfo?.preRelease });
        }
      }
    }
    return this.Z([...packsAndDependencies.values()].filter(({ id: id2 }) => !result.has(id2.toLowerCase())), seen, result);
  }
  async scanSystemExtensions() {
    return this.I();
  }
  async scanUserExtensions(profileLocation, scanOptions) {
    const extensions = /* @__PURE__ */ new Map();
    const customBuiltinExtensions = await this.J(scanOptions);
    for (const extension of customBuiltinExtensions) {
      extensions.set(extension.identifier.id.toLowerCase(), extension);
    }
    const installedExtensions = await this.bb(profileLocation, scanOptions);
    for (const extension of installedExtensions) {
      extensions.set(extension.identifier.id.toLowerCase(), extension);
    }
    return [...extensions.values()];
  }
  async scanExtensionsUnderDevelopment() {
    const devExtensions = this.j.options?.developmentOptions?.extensions;
    const result = [];
    if (Array.isArray(devExtensions)) {
      await Promise.allSettled(devExtensions.map(async (devExtension) => {
        try {
          const location3 = URI.revive(devExtension);
          if (URI.isUri(location3)) {
            const webExtension = await this.fb(location3);
            result.push(await this.gb(webExtension, false));
          } else {
            this.r.info(`Skipping the extension under development ${devExtension} as it is not URI type.`);
          }
        } catch (error) {
          this.r.info(`Error while fetching the extension under development ${devExtension.toString()}.`, $qb(error));
        }
      }));
    }
    return result;
  }
  async scanExistingExtension(extensionLocation, extensionType, profileLocation) {
    if (extensionType === 0) {
      const systemExtensions = await this.scanSystemExtensions();
      return systemExtensions.find((e) => e.location.toString() === extensionLocation.toString()) || null;
    }
    const userExtensions = await this.scanUserExtensions(profileLocation);
    return userExtensions.find((e) => e.location.toString() === extensionLocation.toString()) || null;
  }
  async scanExtensionManifest(extensionLocation) {
    try {
      return await this.jb(extensionLocation);
    } catch (error) {
      this.r.warn(`Error while fetching manifest from ${extensionLocation.toString()}`, $qb(error));
      return null;
    }
  }
  async addExtensionFromGallery(galleryExtension, metadata, profileLocation) {
    const webExtension = await this.cb(galleryExtension, metadata);
    return this.$(webExtension, profileLocation);
  }
  async addExtension(location3, metadata, profileLocation) {
    const webExtension = await this.fb(location3, void 0, void 0, void 0, void 0, void 0, void 0, metadata);
    const extension = await this.gb(webExtension, false);
    await this.ab([webExtension], profileLocation);
    return extension;
  }
  async removeExtension(extension, profileLocation) {
    await this.mb(profileLocation, (installedExtensions) => installedExtensions.filter((installedExtension) => !$DA(installedExtension.identifier, extension.identifier)));
  }
  async updateMetadata(extension, metadata, profileLocation) {
    let updatedExtension = void 0;
    await this.mb(profileLocation, (installedExtensions) => {
      const result = [];
      for (const installedExtension of installedExtensions) {
        if ($DA(extension.identifier, installedExtension.identifier)) {
          installedExtension.metadata = { ...installedExtension.metadata, ...metadata };
          updatedExtension = installedExtension;
          result.push(installedExtension);
        } else {
          result.push(installedExtension);
        }
      }
      return result;
    });
    if (!updatedExtension) {
      throw new Error("Extension not found");
    }
    return this.gb(updatedExtension, extension.isBuiltin);
  }
  async copyExtensions(fromProfileLocation, toProfileLocation, filter) {
    const extensionsToCopy = [];
    const fromWebExtensions = await this.lb(fromProfileLocation);
    await Promise.all(fromWebExtensions.map(async (webExtension) => {
      const scannedExtension = await this.gb(webExtension, false);
      if (filter(scannedExtension)) {
        extensionsToCopy.push(webExtension);
      }
    }));
    if (extensionsToCopy.length) {
      await this.ab(extensionsToCopy, toProfileLocation);
    }
  }
  async $(webExtension, profileLocation) {
    const isSystem = !!(await this.scanSystemExtensions()).find((e) => $DA(e.identifier, webExtension.identifier));
    const isBuiltin = !!webExtension.metadata?.isBuiltin;
    const extension = await this.gb(webExtension, isBuiltin);
    if (isSystem) {
      await this.qb((systemExtensions) => {
        systemExtensions = systemExtensions.filter((extension2) => !$DA(extension2.identifier, webExtension.identifier));
        systemExtensions.push(webExtension);
        return systemExtensions;
      });
      return extension;
    }
    if (isBuiltin) {
      await this.ob((customBuiltinExtensions) => {
        customBuiltinExtensions = customBuiltinExtensions.filter((extension2) => !$DA(extension2.identifier, webExtension.identifier));
        customBuiltinExtensions.push(webExtension);
        return customBuiltinExtensions;
      });
      const installedExtensions = await this.lb(profileLocation);
      if (installedExtensions.some((e) => $DA(e.identifier, webExtension.identifier))) {
        await this.ab([webExtension], profileLocation);
      }
      return extension;
    }
    await this.ab([webExtension], profileLocation);
    return extension;
  }
  async ab(webExtensions, profileLocation) {
    await this.mb(profileLocation, (installedExtensions) => {
      installedExtensions = installedExtensions.filter((installedExtension) => webExtensions.some((extension) => !$DA(installedExtension.identifier, extension.identifier)));
      installedExtensions.push(...webExtensions);
      return installedExtensions;
    });
  }
  async bb(profileLocation, scanOptions) {
    let installedExtensions = await this.lb(profileLocation);
    if (!this.D.extUri.isEqual(profileLocation, this.C.defaultProfile.extensionsResource)) {
      installedExtensions = installedExtensions.filter((i2) => !i2.metadata?.isApplicationScoped);
      const defaultProfileExtensions = await this.lb(this.C.defaultProfile.extensionsResource);
      installedExtensions.push(...defaultProfileExtensions.filter((i2) => i2.metadata?.isApplicationScoped));
    }
    installedExtensions.sort((a, b) => a.identifier.id < b.identifier.id ? -1 : a.identifier.id > b.identifier.id ? 1 : rcompare(a.version, b.version));
    const result = /* @__PURE__ */ new Map();
    for (const webExtension of installedExtensions) {
      const existing = result.get(webExtension.identifier.id.toLowerCase());
      if (existing && gt(existing.manifest.version, webExtension.version)) {
        continue;
      }
      const extension = await this.gb(webExtension, false);
      if (extension.isValid || !scanOptions?.skipInvalidExtensions) {
        result.set(extension.identifier.id.toLowerCase(), extension);
      } else {
        this.r.info(`Skipping invalid installed extension ${webExtension.identifier.id}`);
      }
    }
    return [...result.values()];
  }
  async cb(galleryExtension, metadata) {
    const extensionLocation = this.u.getExtensionGalleryResourceURL({
      publisher: galleryExtension.publisher,
      name: galleryExtension.name,
      version: galleryExtension.version,
      targetPlatform: galleryExtension.properties.targetPlatform === "web" ? "web" : void 0
    }, "extension");
    if (!extensionLocation) {
      throw new Error("No extension gallery service configured.");
    }
    return this.db(extensionLocation, galleryExtension.identifier, galleryExtension.assets.readme ? URI.parse(galleryExtension.assets.readme.uri) : void 0, galleryExtension.assets.changelog ? URI.parse(galleryExtension.assets.changelog.uri) : void 0, metadata);
  }
  async db(extensionLocation, identifier2, readmeUri, changelogUri, metadata) {
    const extensionResources = await this.hb(extensionLocation);
    const packageNLSResources = this.eb(extensionResources);
    const fallbackPackageNLSResource = extensionResources.find((e) => $rc(e) === "package.nls.json");
    return this.fb(extensionLocation, identifier2, void 0, packageNLSResources, fallbackPackageNLSResource ? URI.parse(fallbackPackageNLSResource) : null, readmeUri, changelogUri, metadata);
  }
  eb(extensionResources) {
    const packageNLSResources = /* @__PURE__ */ new Map();
    extensionResources.forEach((e) => {
      const regexResult = /package\.nls\.([\w-]+)\.json/.exec($rc(e));
      if (regexResult?.[1]) {
        packageNLSResources.set(regexResult[1], URI.parse(e));
      }
    });
    return packageNLSResources;
  }
  async fb(extensionLocation, identifier2, manifest, packageNLSUris, fallbackPackageNLSUri, readmeUri, changelogUri, metadata) {
    if (!manifest) {
      try {
        manifest = await this.jb(extensionLocation);
      } catch (error) {
        throw new Error(`Error while fetching manifest from the location '${extensionLocation.toString()}'. ${$qb(error)}`);
      }
    }
    if (!this.t.canExecuteOnWeb(manifest)) {
      throw new Error(localize(12739, null, manifest.displayName || manifest.name));
    }
    if (fallbackPackageNLSUri === void 0) {
      try {
        fallbackPackageNLSUri = $vh(extensionLocation, "package.nls.json");
        await this.u.readExtensionResource(fallbackPackageNLSUri);
      } catch (error) {
        fallbackPackageNLSUri = void 0;
      }
    }
    const defaultManifestTranslations = fallbackPackageNLSUri ? URI.isUri(fallbackPackageNLSUri) ? await this.kb(fallbackPackageNLSUri) : fallbackPackageNLSUri : null;
    return {
      identifier: { id: $IA(manifest.publisher, manifest.name), uuid: identifier2?.uuid },
      version: manifest.version,
      location: extensionLocation,
      manifest,
      readmeUri,
      changelogUri,
      packageNLSUris,
      fallbackPackageNLSUri: URI.isUri(fallbackPackageNLSUri) ? fallbackPackageNLSUri : void 0,
      defaultManifestTranslations,
      metadata
    };
  }
  async gb(webExtension, isBuiltin, type = 1) {
    const validations = [];
    let manifest = webExtension.manifest;
    if (!manifest) {
      try {
        manifest = await this.jb(webExtension.location);
      } catch (error) {
        validations.push([severity_default.Error, `Error while fetching manifest from the location '${webExtension.location}'. ${$qb(error)}`]);
      }
    }
    if (!manifest) {
      const [publisher, name] = webExtension.identifier.id.split(".");
      manifest = {
        name,
        publisher,
        version: webExtension.version,
        engines: { vscode: "*" }
      };
    }
    const packageNLSUri = webExtension.packageNLSUris?.get(Language.value().toLowerCase());
    const fallbackPackageNLS = webExtension.defaultManifestTranslations ?? webExtension.fallbackPackageNLSUri;
    if (packageNLSUri) {
      manifest = await this.ib(manifest, packageNLSUri, fallbackPackageNLS);
    } else if (fallbackPackageNLS) {
      manifest = await this.ib(manifest, fallbackPackageNLS);
    }
    const uuid = webExtension.metadata?.id;
    const validateApiVersion = this.h.includes(webExtension.identifier.id.toLowerCase());
    validations.push(...$YA(this.z.version, this.z.date, webExtension.location, manifest, false, validateApiVersion));
    let isValid2 = true;
    for (const [severity, message] of validations) {
      if (severity === severity_default.Error) {
        isValid2 = false;
        this.r.error(message);
      }
    }
    if (manifest.enabledApiProposals && validateApiVersion) {
      manifest.enabledApiProposals = $aA([...manifest.enabledApiProposals]);
    }
    return {
      identifier: { id: webExtension.identifier.id, uuid: webExtension.identifier.uuid || uuid },
      location: webExtension.location,
      manifest,
      type,
      isBuiltin,
      readmeUrl: webExtension.readmeUri,
      changelogUrl: webExtension.changelogUri,
      metadata: webExtension.metadata,
      targetPlatform: "web",
      validations,
      isValid: isValid2,
      preRelease: !!webExtension.metadata?.preRelease
    };
  }
  async hb(extensionLocation) {
    try {
      const result = await this.u.readExtensionResource(extensionLocation);
      return JSON.parse(result);
    } catch (error) {
      this.r.warn("Error while fetching extension resources list", $qb(error));
    }
    return [];
  }
  async ib(manifest, nlsURL, fallbackNLS) {
    try {
      const translations = URI.isUri(nlsURL) ? await this.kb(nlsURL) : nlsURL;
      const fallbackTranslations = URI.isUri(fallbackNLS) ? await this.kb(fallbackNLS) : fallbackNLS;
      if (translations) {
        manifest = $3A(this.r, manifest, translations, fallbackTranslations);
      }
    } catch (error) {
    }
    return manifest;
  }
  async jb(location3) {
    const url = $vh(location3, "package.json");
    const content = await this.u.readExtensionResource(url);
    return JSON.parse(content);
  }
  async kb(nlsUrl) {
    try {
      const content = await this.u.readExtensionResource(nlsUrl);
      return JSON.parse(content);
    } catch (error) {
      this.r.error(`Error while fetching translations of an extension`, nlsUrl.toString(), $qb(error));
    }
    return void 0;
  }
  async lb(profileLocation) {
    return this.rb(profileLocation);
  }
  mb(profileLocation, updateFn) {
    return this.rb(profileLocation, updateFn);
  }
  nb() {
    return this.rb(this.f);
  }
  ob(updateFn) {
    return this.rb(this.f, updateFn);
  }
  pb() {
    return this.rb(this.c);
  }
  qb(updateFn) {
    return this.rb(this.c, updateFn);
  }
  async rb(file, updateFn) {
    if (!file) {
      return [];
    }
    return this.ub(file).queue(async () => {
      let webExtensions = [];
      try {
        const content = await this.n.readFile(file);
        const storedWebExtensions = JSON.parse(content.value.toString());
        for (const e of storedWebExtensions) {
          if (!e.location || !e.identifier || !e.version) {
            this.r.info("Ignoring invalid extension while scanning", storedWebExtensions);
            continue;
          }
          let packageNLSUris;
          if (e.packageNLSUris) {
            packageNLSUris = /* @__PURE__ */ new Map();
            Object.entries(e.packageNLSUris).forEach(([key2, value]) => packageNLSUris.set(key2, URI.revive(value)));
          }
          webExtensions.push({
            identifier: e.identifier,
            version: e.version,
            location: URI.revive(e.location),
            manifest: e.manifest,
            readmeUri: URI.revive(e.readmeUri),
            changelogUri: URI.revive(e.changelogUri),
            packageNLSUris,
            fallbackPackageNLSUri: URI.revive(e.fallbackPackageNLSUri),
            defaultManifestTranslations: e.defaultManifestTranslations,
            packageNLSUri: URI.revive(e.packageNLSUri),
            metadata: e.metadata
          });
        }
        try {
          webExtensions = await this.sb(webExtensions, file);
        } catch (error) {
          this.r.error(`Error while migrating scanned extensions in ${file.toString()}`, $qb(error));
        }
      } catch (error) {
        if (error.fileOperationResult !== 1) {
          this.r.error(error);
        }
      }
      if (updateFn) {
        await this.tb(webExtensions = updateFn(webExtensions), file);
      }
      return webExtensions;
    });
  }
  async sb(webExtensions, file) {
    let update = false;
    webExtensions = await Promise.all(webExtensions.map(async (webExtension) => {
      if (!webExtension.manifest) {
        try {
          webExtension.manifest = await this.jb(webExtension.location);
          update = true;
        } catch (error) {
          this.r.error(`Error while updating manifest of an extension in ${file.toString()}`, webExtension.identifier.id, $qb(error));
        }
      }
      if ($Gg(webExtension.defaultManifestTranslations)) {
        if (webExtension.fallbackPackageNLSUri) {
          try {
            const content = await this.u.readExtensionResource(webExtension.fallbackPackageNLSUri);
            webExtension.defaultManifestTranslations = JSON.parse(content);
            update = true;
          } catch (error) {
            this.r.error(`Error while fetching default manifest translations of an extension`, webExtension.identifier.id, $qb(error));
          }
        } else {
          update = true;
          webExtension.defaultManifestTranslations = null;
        }
      }
      const migratedLocation = $Plb(
        webExtension.location,
        "web"
        /* TargetPlatform.WEB */
      );
      if (migratedLocation) {
        update = true;
        webExtension.location = migratedLocation;
      }
      if ($Gg(webExtension.metadata?.hasPreReleaseVersion) && webExtension.metadata?.preRelease) {
        update = true;
        webExtension.metadata.hasPreReleaseVersion = true;
      }
      return webExtension;
    }));
    if (update) {
      await this.tb(webExtensions, file);
    }
    return webExtensions;
  }
  async tb(webExtensions, file) {
    function toStringDictionary(dictionary) {
      if (!dictionary) {
        return void 0;
      }
      const result = /* @__PURE__ */ Object.create(null);
      dictionary.forEach((value, key2) => result[key2] = value.toJSON());
      return result;
    }
    const storedWebExtensions = webExtensions.map((e) => ({
      identifier: e.identifier,
      version: e.version,
      manifest: e.manifest,
      location: e.location.toJSON(),
      readmeUri: e.readmeUri?.toJSON(),
      changelogUri: e.changelogUri?.toJSON(),
      packageNLSUris: toStringDictionary(e.packageNLSUris),
      defaultManifestTranslations: e.defaultManifestTranslations,
      fallbackPackageNLSUri: e.fallbackPackageNLSUri?.toJSON(),
      metadata: e.metadata
    }));
    await this.n.writeFile(file, $Ci.fromString(JSON.stringify(storedWebExtensions)));
  }
  ub(file) {
    let resourceQueue = this.g.get(file);
    if (!resourceQueue) {
      this.g.set(file, resourceQueue = new $3h());
    }
    return resourceQueue;
  }
};
$Onc = __decorate([
  __param(0, $M4),
  __param(1, $bA),
  __param(2, $km),
  __param(3, $wn),
  __param(4, $pA),
  __param(5, $LCb),
  __param(6, $Olb),
  __param(7, $AM),
  __param(8, $jv),
  __param(9, $Vu),
  __param(10, $rs),
  __param(11, $vl),
  __param(12, $KL)
], $Onc);
if ($r) {
  $hJ(class extends $gJ {
    constructor() {
      super({
        id: "workbench.extensions.action.openInstalledWebExtensionsResource",
        title: localize2(12740, "Open Installed Web Extensions Resource"),
        category: $qn.Developer,
        f1: true,
        precondition: $veb
      });
    }
    run(serviceAccessor) {
      const editorService = serviceAccessor.get($mJ);
      const userDataProfileService = serviceAccessor.get($gT);
      editorService.openEditor({ resource: userDataProfileService.currentProfile.extensionsResource });
    }
  });
}
$SC(
  $rzb,
  $Onc,
  1
  /* InstantiationType.Delayed */
);

// out-build/vs/platform/extensionManagement/common/abstractExtensionManagementService.js
var $cX = class $cX2 extends $3c {
  constructor(g, h3) {
    super();
    this.g = g;
    this.h = h3;
  }
  async canInstall(extension) {
    const allowedToInstall = this.h.isAllowed({ id: extension.identifier.id, publisherDisplayName: extension.publisherDisplayName });
    if (allowedToInstall !== true) {
      return new $bm(localize(1798, null, allowedToInstall.value));
    }
    if (!await this.j(extension)) {
      const productName = $r ? localize(1799, null, this.g.nameLong) : this.g.nameLong;
      const learnLink = $r ? "https://aka.ms/vscode-web-extensions-guide" : "https://aka.ms/vscode-platform-specific-extensions";
      return new $bm(`${localize(1800, null, extension.displayName ?? extension.identifier.id, productName, $jA(await this.getTargetPlatform()))} [${localize(1801, null)}](${learnLink})`);
    }
    return true;
  }
  async j(extension) {
    const currentTargetPlatform = await this.getTargetPlatform();
    return extension.allTargetPlatforms.some((targetPlatform) => $nA(targetPlatform, extension.allTargetPlatforms, currentTargetPlatform));
  }
};
$cX = __decorate([
  __param(0, $Vu),
  __param(1, $xA)
], $cX);
var $dX = class $dX2 extends $cX {
  get onInstallExtension() {
    return this.u.event;
  }
  get onDidInstallExtensions() {
    return this.w.event;
  }
  get onUninstallExtension() {
    return this.y.event;
  }
  get onDidUninstallExtension() {
    return this.z.event;
  }
  get onDidUpdateExtensionMetadata() {
    return this.C.event;
  }
  constructor(F, G, H, I, productService, allowedExtensionsService, J) {
    super(productService, allowedExtensionsService);
    this.F = F;
    this.G = G;
    this.H = H;
    this.I = I;
    this.J = J;
    this.n = 0;
    this.s = /* @__PURE__ */ new Map();
    this.t = /* @__PURE__ */ new Map();
    this.u = this.B(new $ze());
    this.w = this.B(new $ze());
    this.y = this.B(new $ze());
    this.z = this.B(new $ze());
    this.C = this.B(new $ze());
    this.D = [];
    this.B($1c(() => {
      this.s.forEach(({ task }) => task.cancel());
      this.t.forEach((promise) => promise.cancel());
      this.s.clear();
      this.t.clear();
    }));
  }
  async installFromGallery(extension, options3 = {}) {
    try {
      const results = await this.installGalleryExtensions([{ extension, options: options3 }]);
      const result = results.find(({ identifier: identifier2 }) => $DA(identifier2, extension.identifier));
      if (result?.local) {
        return result?.local;
      }
      if (result?.error) {
        throw result.error;
      }
      throw new $rA(
        `Unknown error while installing extension ${extension.identifier.id}`,
        "Unknown"
        /* ExtensionManagementErrorCode.Unknown */
      );
    } catch (error) {
      throw $eX(error);
    }
  }
  async installGalleryExtensions(extensions) {
    if (!this.F.isEnabled()) {
      throw new $rA(
        localize(1802, null),
        "NotAllowed"
        /* ExtensionManagementErrorCode.NotAllowed */
      );
    }
    const results = [];
    const installableExtensions = [];
    await Promise.allSettled(extensions.map(async ({ extension, options: options3 }) => {
      try {
        const compatible = await this.Q(extension, !!options3?.installGivenVersion, !!options3?.installPreReleaseVersion, options3.productVersion ?? { version: this.g.version, date: this.g.date });
        installableExtensions.push({ ...compatible, options: options3 });
      } catch (error) {
        results.push({ identifier: extension.identifier, operation: 2, source: extension, error, profileLocation: options3.profileLocation ?? this.Z() });
      }
    }));
    if (installableExtensions.length) {
      results.push(...await this.L(installableExtensions));
    }
    return results;
  }
  async uninstall(extension, options3) {
    this.I.trace("ExtensionManagementService#uninstall", extension.identifier.id);
    return this.uninstallExtensions([{ extension, options: options3 }]);
  }
  async toggleAppliationScope(extension, fromProfileLocation) {
    if ($8z(extension.manifest) || extension.isBuiltin) {
      return extension;
    }
    if (extension.isApplicationScoped) {
      let local = await this.updateMetadata(extension, { isApplicationScoped: false }, this.J.defaultProfile.extensionsResource);
      if (!this.H.extUri.isEqual(fromProfileLocation, this.J.defaultProfile.extensionsResource)) {
        local = await this.bb(extension, this.J.defaultProfile.extensionsResource, fromProfileLocation);
      }
      for (const profile of this.J.profiles) {
        const existing = (await this.getInstalled(1, profile.extensionsResource)).find((e) => $DA(e.identifier, extension.identifier));
        if (existing) {
          this.C.fire({ local: existing, profileLocation: profile.extensionsResource });
        } else {
          this.z.fire({ identifier: extension.identifier, profileLocation: profile.extensionsResource });
        }
      }
      return local;
    } else {
      const local = this.H.extUri.isEqual(fromProfileLocation, this.J.defaultProfile.extensionsResource) ? await this.updateMetadata(extension, { isApplicationScoped: true }, this.J.defaultProfile.extensionsResource) : await this.bb(extension, fromProfileLocation, this.J.defaultProfile.extensionsResource, { isApplicationScoped: true });
      this.w.fire([{ identifier: local.identifier, operation: 2, local, profileLocation: this.J.defaultProfile.extensionsResource, applicationScoped: true }]);
      return local;
    }
  }
  getExtensionsControlManifest() {
    const now = (/* @__PURE__ */ new Date()).getTime();
    if (!this.m || now - this.n > 1e3 * 60 * 5) {
      this.m = this.Y();
      this.n = now;
    }
    return this.m;
  }
  registerParticipant(participant) {
    this.D.push(participant);
  }
  async resetPinnedStateForAllUserExtensions(pinned) {
    try {
      await this.O(this.J.profiles.map(async (profile) => {
        const extensions = await this.getInstalled(1, profile.extensionsResource);
        await this.O(extensions.map(async (extension) => {
          if (extension.pinned !== pinned) {
            await this.updateMetadata(extension, { pinned }, profile.extensionsResource);
          }
        }));
      }));
    } catch (error) {
      this.I.error("Error while resetting pinned state for all user extensions", $qb(error));
      throw error;
    }
  }
  async L(extensions) {
    const installExtensionResultsMap = /* @__PURE__ */ new Map();
    const installingExtensionsMap = /* @__PURE__ */ new Map();
    const alreadyRequestedInstallations = [];
    const getInstallExtensionTaskKey = (extension, profileLocation) => `${$EA.create(extension).toString()}-${profileLocation.toString()}`;
    const createInstallExtensionTask = (manifest, extension, options3, root) => {
      if (!URI.isUri(extension)) {
        if (installingExtensionsMap.has(`${extension.identifier.id.toLowerCase()}-${options3.profileLocation.toString()}`)) {
          return;
        }
        const existingInstallingExtension = this.s.get(getInstallExtensionTaskKey(extension, options3.profileLocation));
        if (existingInstallingExtension) {
          if (root && this.N(root, existingInstallingExtension.task)) {
            const identifier2 = existingInstallingExtension.task.identifier;
            this.I.info("Waiting for already requested installing extension", identifier2.id, root.identifier.id, options3.profileLocation.toString());
            existingInstallingExtension.waitingTasks.push(root);
            alreadyRequestedInstallations.push(Event2.toPromise(Event2.filter(this.onDidInstallExtensions, (results2) => results2.some((result) => $DA(result.identifier, identifier2)))).then((results2) => {
              this.I.info("Finished waiting for already requested installing extension", identifier2.id, root.identifier.id, options3.profileLocation.toString());
              const result = results2.find((result2) => $DA(result2.identifier, identifier2));
              if (!result?.local) {
                throw new Error(`Extension ${identifier2.id} is not installed`);
              }
            }));
          }
          return;
        }
      }
      const installExtensionTask = this.$(manifest, extension, options3);
      const key2 = `${$IA(manifest.publisher, manifest.name)}-${options3.profileLocation.toString()}`;
      installingExtensionsMap.set(key2, { task: installExtensionTask, root });
      this.u.fire({ identifier: installExtensionTask.identifier, source: extension, profileLocation: options3.profileLocation });
      this.I.info("Installing extension:", installExtensionTask.identifier.id, options3);
      if (!URI.isUri(extension)) {
        this.s.set(getInstallExtensionTaskKey(extension, options3.profileLocation), { task: installExtensionTask, waitingTasks: [] });
      }
    };
    try {
      for (const { manifest, extension, options: options3 } of extensions) {
        const isApplicationScoped = options3.isApplicationScoped || options3.isBuiltin || $8z(manifest);
        const installExtensionTaskOptions = {
          ...options3,
          installOnlyNewlyAddedFromExtensionPack: options3.installOnlyNewlyAddedFromExtensionPack ?? !URI.isUri(extension),
          isApplicationScoped,
          profileLocation: isApplicationScoped ? this.J.defaultProfile.extensionsResource : options3.profileLocation ?? this.Z(),
          productVersion: options3.productVersion ?? { version: this.g.version, date: this.g.date }
        };
        const existingInstallExtensionTask = !URI.isUri(extension) ? this.s.get(getInstallExtensionTaskKey(extension, installExtensionTaskOptions.profileLocation)) : void 0;
        if (existingInstallExtensionTask) {
          this.I.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.I.info("Installing the extension without checking dependencies and pack", task.identifier.id);
        } else {
          try {
            const allDepsAndPackExtensionsToInstall = await this.P(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 options3 = { ...task.options, context: { ...task.options.context, [$hA]: true } };
            for (const { gallery, manifest } of $Rb(allDepsAndPackExtensionsToInstall, ({ gallery: gallery2 }) => gallery2.identifier.id)) {
              if (installed.some(({ identifier: identifier2 }) => $DA(identifier2, gallery.identifier))) {
                continue;
              }
              createInstallExtensionTask(manifest, gallery, options3, task);
            }
          } catch (error) {
            if (URI.isUri(task.source)) {
              if ($Qb(task.manifest.extensionDependencies)) {
                this.I.warn(`Cannot install dependencies of extension:`, task.identifier.id, error.message);
              }
              if ($Qb(task.manifest.extensionPack)) {
                this.I.warn(`Cannot install packed extensions of extension:`, task.identifier.id, error.message);
              }
            } else {
              this.I.error("Error while preparing to install dependencies and extension packs of the extension:", task.identifier.id);
              throw error;
            }
          }
        }
      }));
      const otherProfilesToUpdate = await this.M([...installingExtensionsMap.values()].map(({ task }) => task));
      for (const [profileLocation, task] of otherProfilesToUpdate) {
        createInstallExtensionTask(task.manifest, task.source, { ...task.options, profileLocation }, void 0);
      }
      await this.O([...installingExtensionsMap.entries()].map(async ([key2, { task }]) => {
        const startTime = (/* @__PURE__ */ new Date()).getTime();
        let local;
        try {
          local = await task.run();
          await this.O(
            this.D.map((participant) => participant.postInstall(local, task.source, task.options, CancellationToken.None)),
            "PostInstall"
            /* ExtensionManagementErrorCode.PostInstall */
          );
        } catch (e) {
          const error = $eX(e);
          if (!URI.isUri(task.source)) {
            reportTelemetry(this.G, task.operation === 3 ? "extensionGallery:update" : "extensionGallery:install", {
              extensionData: $LA(task.source),
              error,
              source: task.options.context?.[$gA]
            });
          }
          installExtensionResultsMap.set(key2, { error, identifier: task.identifier, operation: task.operation, source: task.source, context: task.options.context, profileLocation: task.options.profileLocation, applicationScoped: task.options.isApplicationScoped });
          this.I.error("Error while installing the extension", task.identifier.id, $qb(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.G, isUpdate ? "extensionGallery:update" : "extensionGallery:install", {
            extensionData: $LA(task.source),
            verificationStatus: task.verificationStatus,
            duration: (/* @__PURE__ */ new Date()).getTime() - startTime,
            durationSinceUpdate,
            source: task.options.context?.[$gA]
          });
          if ($r && task.operation !== 3) {
            try {
              await this.F.reportStatistic(
                local.manifest.publisher,
                local.manifest.name,
                local.manifest.version,
                "install"
                /* StatisticType.Install */
              );
            } catch (error) {
            }
          }
        }
        installExtensionResultsMap.set(key2, { 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.O(alreadyRequestedInstallations);
      }
    } 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 [key2, { task, root }] of installingExtensionsMap) {
        const result = installExtensionResultsMap.get(key2);
        if (!result) {
          task.cancel();
          installExtensionResultsMap.set(key2, getErrorResult(task));
        } else if (result.local && root && !installExtensionResultsMap.get(`${root.identifier.id.toLowerCase()}-${task.options.profileLocation.toString()}`)?.local) {
          rollbackTasks.push(this.ab(result.local, { versionOnly: true, profileLocation: task.options.profileLocation }));
          installExtensionResultsMap.set(key2, getErrorResult(task));
        }
      }
      for (const [key2, { task }] of installingExtensionsMap) {
        const result = installExtensionResultsMap.get(key2);
        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.ab(result.local, { versionOnly: true, profileLocation: task.options.profileLocation }));
          installExtensionResultsMap.set(key2, getErrorResult(task));
        }
      }
      if (rollbackTasks.length) {
        await Promise.allSettled(rollbackTasks.map(async (rollbackTask) => {
          try {
            await rollbackTask.run();
            this.I.info("Rollback: Uninstalled extension", rollbackTask.extension.identifier.id);
          } catch (error2) {
            this.I.warn("Rollback: Error while uninstalling extension", rollbackTask.extension.identifier.id, $qb(error2));
          }
        }));
      }
    } finally {
      for (const { task } of installingExtensionsMap.values()) {
        if (task.source && !URI.isUri(task.source)) {
          this.s.delete(getInstallExtensionTaskKey(task.source, task.options.profileLocation));
        }
      }
    }
    const results = [...installExtensionResultsMap.values()];
    for (const result of results) {
      if (result.local) {
        this.I.info(`Extension installed successfully:`, result.identifier.id, result.profileLocation.toString());
      }
    }
    this.w.fire(results);
    return results;
  }
  async M(tasks2) {
    const otherProfilesToUpdate = [];
    const profileExtensionsCache = new $Ec();
    for (const task of tasks2) {
      if (task.operation !== 3 || task.options.isApplicationScoped || task.options.pinned || task.options.installGivenVersion || URI.isUri(task.source)) {
        continue;
      }
      for (const profile of this.J.profiles) {
        if (this.H.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) => $DA(e.identifier, task.identifier));
        if (installedExtension && !installedExtension.pinned) {
          otherProfilesToUpdate.push([profile.extensionsResource, task]);
        }
      }
    }
    return otherProfilesToUpdate;
  }
  N(taskToWait, taskToWaitFor) {
    for (const [, { task, waitingTasks }] of this.s.entries()) {
      if (task === taskToWait) {
        if (waitingTasks.includes(taskToWaitFor)) {
          return false;
        }
        if (waitingTasks.some((waitingTask) => this.N(waitingTask, taskToWaitFor))) {
          return false;
        }
      }
      if (task === taskToWaitFor && waitingTasks[0] && !this.N(taskToWait, waitingTasks[0])) {
        return false;
      }
    }
    return true;
  }
  async O(promises, errorCode) {
    const results = [];
    const errors = [];
    const promiseResults = await Promise.allSettled(promises);
    for (const r2 of promiseResults) {
      if (r2.status === "fulfilled") {
        results.push(r2.value);
      } else {
        errors.push($eX(r2.reason, errorCode));
      }
    }
    if (!errors.length) {
      return results;
    }
    if (errors.length === 1) {
      throw errors[0];
    }
    let error = new $rA(
      "",
      "Unknown"
      /* ExtensionManagementErrorCode.Unknown */
    );
    for (const current of errors) {
      error = new $rA(error.message ? `${error.message}, ${current.message}` : current.message, current.code !== "Unknown" && current.code !== "Internal" ? current.code : error.code);
    }
    throw error;
  }
  async P(extensionIdentifier, manifest, getOnlyNewlyAddedFromExtensionPack, installPreRelease, profile, productVersion) {
    if (!this.F.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) => $DA(e.identifier, extensionIdentifier2)) : void 0;
        for (const extension of manifest2.extensionPack) {
          if (!(existing && existing.manifest.extensionPack && existing.manifest.extensionPack.some((old) => $DA({ id: old }, { id: extension })))) {
            if (dependenciesAndPackExtensions.every((e) => !$DA({ id: e }, { id: extension }))) {
              dependenciesAndPackExtensions.push(extension);
            }
          }
        }
      }
      if (dependenciesAndPackExtensions.length) {
        const ids = dependenciesAndPackExtensions.filter((id2) => knownIdentifiers.every((galleryIdentifier) => !$DA(galleryIdentifier, { id: id2 })));
        if (ids.length) {
          const galleryExtensions = await this.F.getExtensions(ids.map((id2) => ({ id: id2, preRelease: installPreRelease })), CancellationToken.None);
          for (const galleryExtension of galleryExtensions) {
            if (knownIdentifiers.find((identifier2) => $DA(identifier2, galleryExtension.identifier))) {
              continue;
            }
            const isDependency = dependecies.some((id2) => $DA({ id: id2 }, galleryExtension.identifier));
            let compatible;
            try {
              compatible = await this.Q(galleryExtension, false, installPreRelease, productVersion);
            } catch (error) {
              if (!isDependency) {
                this.I.info("Skipping the packed extension as it cannot be installed", galleryExtension.identifier.id, $qb(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 Q(extension, sameVersion, installPreRelease, productVersion) {
    let compatibleExtension;
    const extensionsControlManifest = await this.getExtensionsControlManifest();
    if (extensionsControlManifest.malicious.some((identifier2) => $DA(extension.identifier, identifier2))) {
      throw new $rA(
        localize(1803, null, extension.identifier.id),
        "Malicious"
        /* ExtensionManagementErrorCode.Malicious */
      );
    }
    const deprecationInfo = extensionsControlManifest.deprecated[extension.identifier.id.toLowerCase()];
    if (deprecationInfo?.extension?.autoMigrate) {
      this.I.info(`The '${extension.identifier.id}' extension is deprecated, fetching the compatible '${deprecationInfo.extension.id}' extension instead.`);
      compatibleExtension = (await this.F.getExtensions([{ id: deprecationInfo.extension.id, preRelease: deprecationInfo.extension.preRelease }], { targetPlatform: await this.getTargetPlatform(), compatible: true, productVersion }, CancellationToken.None))[0];
      if (!compatibleExtension) {
        throw new $rA(
          localize(1804, null, extension.identifier.id, deprecationInfo.extension.id),
          "Deprecated"
          /* ExtensionManagementErrorCode.Deprecated */
        );
      }
    } else {
      if (await this.canInstall(extension) !== true) {
        const targetPlatform = await this.getTargetPlatform();
        throw new $rA(
          localize(1805, null, extension.identifier.id, this.g.nameLong, $jA(targetPlatform)),
          "IncompatibleTargetPlatform"
          /* ExtensionManagementErrorCode.IncompatibleTargetPlatform */
        );
      }
      compatibleExtension = await this.R(extension, sameVersion, installPreRelease, productVersion);
      if (!compatibleExtension) {
        const incompatibleApiProposalsMessages = [];
        if (!$2A(extension.properties.enabledApiProposals ?? [], incompatibleApiProposalsMessages)) {
          throw new $rA(
            localize(1806, null, extension.displayName ?? extension.identifier.id, incompatibleApiProposalsMessages[0]),
            "IncompatibleApi"
            /* ExtensionManagementErrorCode.IncompatibleApi */
          );
        }
        if (!installPreRelease && extension.properties.isPreReleaseVersion && (await this.F.getExtensions([extension.identifier], CancellationToken.None))[0]) {
          throw new $rA(
            localize(1807, null, extension.displayName ?? extension.identifier.id),
            "ReleaseVersionNotFound"
            /* ExtensionManagementErrorCode.ReleaseVersionNotFound */
          );
        }
        throw new $rA(
          localize(1808, null, extension.identifier.id, this.g.nameLong, this.g.version),
          "Incompatible"
          /* ExtensionManagementErrorCode.Incompatible */
        );
      }
    }
    this.I.info("Getting Manifest...", compatibleExtension.identifier.id);
    const manifest = await this.F.getManifest(compatibleExtension, CancellationToken.None);
    if (manifest === null) {
      throw new $rA(
        `Missing manifest for extension ${compatibleExtension.identifier.id}`,
        "Invalid"
        /* ExtensionManagementErrorCode.Invalid */
      );
    }
    if (manifest.version !== compatibleExtension.version) {
      throw new $rA(
        `Cannot install '${compatibleExtension.identifier.id}' extension because of version mismatch in Marketplace`,
        "Invalid"
        /* ExtensionManagementErrorCode.Invalid */
      );
    }
    return { extension: compatibleExtension, manifest };
  }
  async R(extension, sameVersion, includePreRelease, productVersion) {
    const targetPlatform = await this.getTargetPlatform();
    let compatibleExtension = null;
    if (!sameVersion && extension.hasPreReleaseVersion && extension.properties.isPreReleaseVersion !== includePreRelease) {
      compatibleExtension = (await this.F.getExtensions([{ ...extension.identifier, preRelease: includePreRelease }], { targetPlatform, compatible: true, productVersion }, CancellationToken.None))[0] || null;
    }
    if (!compatibleExtension && await this.F.isExtensionCompatible(extension, includePreRelease, targetPlatform, productVersion)) {
      compatibleExtension = extension;
    }
    if (!compatibleExtension) {
      if (sameVersion) {
        compatibleExtension = (await this.F.getExtensions([{ ...extension.identifier, version: extension.version }], { targetPlatform, compatible: true, productVersion }, CancellationToken.None))[0] || null;
      } else {
        compatibleExtension = await this.F.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.ab(extension, uninstallOptions);
      this.t.set(getUninstallExtensionTaskKey(uninstallExtensionTask.extension, uninstallOptions), uninstallExtensionTask);
      this.I.info("Uninstalling extension from the profile:", `${extension.identifier.id}@${extension.manifest.version}`, uninstallOptions.profileLocation.toString());
      this.y.fire({ identifier: extension.identifier, profileLocation: uninstallOptions.profileLocation, applicationScoped: extension.isApplicationScoped });
      return uninstallExtensionTask;
    };
    const postUninstallExtension = (extension, uninstallOptions, error) => {
      if (error) {
        this.I.error("Failed to uninstall extension from the profile:", `${extension.identifier.id}@${extension.manifest.version}`, uninstallOptions.profileLocation.toString(), error.message);
      } else {
        this.I.info("Successfully uninstalled extension from the profile", `${extension.identifier.id}@${extension.manifest.version}`, uninstallOptions.profileLocation.toString());
      }
      reportTelemetry(this.G, "extensionGallery:uninstall", { extensionData: $KA(extension), error });
      this.z.fire({ identifier: extension.identifier, error: error?.code, profileLocation: uninstallOptions.profileLocation, applicationScoped: extension.isApplicationScoped });
    };
    const allTasks = [];
    const processedTasks = [];
    const alreadyRequestedUninstalls = [];
    const installedExtensionsMap = new $Ec();
    for (const { extension, options: options3 } of extensions) {
      const uninstallOptions = {
        ...options3,
        profileLocation: extension.isApplicationScoped ? this.J.defaultProfile.extensionsResource : options3?.profileLocation ?? this.Z()
      };
      const uninstallExtensionTask = this.t.get(getUninstallExtensionTaskKey(extension, uninstallOptions));
      if (uninstallExtensionTask) {
        this.I.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.I.info("Uninstalling the extension without including packed extension", `${task.extension.identifier.id}@${task.extension.manifest.version}`);
        } else {
          const packedExtensions = this.W(task.extension, installed);
          for (const packedExtension of packedExtensions) {
            if (this.t.has(getUninstallExtensionTaskKey(packedExtension, task.options))) {
              this.I.info("Extensions is already requested to uninstall", packedExtension.identifier.id);
            } else {
              allTasks.push(createUninstallExtensionTask(packedExtension, task.options));
            }
          }
        }
        if (task.options.donotCheckDependents) {
          this.I.info("Uninstalling the extension without checking dependents", `${task.extension.identifier.id}@${task.extension.manifest.version}`);
        } else {
          this.S(allTasks.map((task2) => task2.extension), installed, task.extension);
        }
      }
      await this.O(allTasks.map(async (task) => {
        try {
          await task.run();
          await this.O(this.D.map((participant) => participant.postUninstall(task.extension, task.options, CancellationToken.None)));
          if (task.extension.identifier.uuid) {
            try {
              await this.F.reportStatistic(
                task.extension.manifest.publisher,
                task.extension.manifest.name,
                task.extension.manifest.version,
                "uninstall"
                /* StatisticType.Uninstall */
              );
            } catch (error) {
            }
          }
        } catch (e) {
          const error = $eX(e);
          postUninstallExtension(task.extension, task.options, error);
          throw error;
        } finally {
          processedTasks.push(task);
        }
      }));
      if (alreadyRequestedUninstalls.length) {
        await this.O(alreadyRequestedUninstalls);
      }
      for (const task of allTasks) {
        postUninstallExtension(task.extension, task.options);
      }
    } catch (e) {
      const error = $eX(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.t.delete(getUninstallExtensionTaskKey(task.extension, task.options))) {
          this.I.warn("Uninstallation task is not found in the cache", task.extension.identifier.id);
        }
      }
    }
  }
  S(extensionsToUninstall, installed, extensionToUninstall) {
    for (const extension of extensionsToUninstall) {
      const dependents = this.X(extension, installed);
      if (dependents.length) {
        const remainingDependents = dependents.filter((dependent) => !extensionsToUninstall.some((e) => $DA(e.identifier, dependent.identifier)));
        if (remainingDependents.length) {
          throw new Error(this.U(extension, remainingDependents, extensionToUninstall));
        }
      }
    }
  }
  U(dependingExtension, dependents, extensionToUninstall) {
    if (extensionToUninstall === dependingExtension) {
      if (dependents.length === 1) {
        return localize(1809, null, extensionToUninstall.manifest.displayName || extensionToUninstall.manifest.name, dependents[0].manifest.displayName || dependents[0].manifest.name);
      }
      if (dependents.length === 2) {
        return localize(1810, 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(1811, 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(1812, 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(1813, 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(1814, 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);
  }
  W(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((i2) => !i2.isBuiltin && extensionsPack.some((id2) => $DA({ id: id2 }, i2.identifier)));
      const packOfPackedExtensions = [];
      for (const packedExtension of packedExtensions) {
        packOfPackedExtensions.push(...this.W(packedExtension, installed, checked));
      }
      return [...packedExtensions, ...packOfPackedExtensions];
    }
    return [];
  }
  X(extension, installed) {
    return installed.filter((e) => e.manifest.extensionDependencies && e.manifest.extensionDependencies.some((id2) => $DA({ id: id2 }, extension.identifier)));
  }
  async Y() {
    try {
      this.I.trace("ExtensionManagementService.updateControlCache");
      return await this.F.getExtensionsControlManifest();
    } catch (err) {
      this.I.trace("ExtensionManagementService.refreshControlCache - failed to get extension control manifest", $qb(err));
      return { malicious: [], deprecated: {}, search: [] };
    }
  }
};
$dX = __decorate([
  __param(0, $pA),
  __param(1, $zv),
  __param(2, $vl),
  __param(3, $wn),
  __param(4, $Vu),
  __param(5, $xA),
  __param(6, $rs)
], $dX);
function $eX(error, code) {
  if (error instanceof $rA) {
    return error;
  }
  let extensionManagementError;
  if (error instanceof $qA) {
    extensionManagementError = new $rA(
      error.message,
      error.code === "DownloadFailedWriting" ? "DownloadFailedWriting" : "Gallery"
      /* ExtensionManagementErrorCode.Gallery */
    );
  } else {
    extensionManagementError = new $rA(error.message, $kb(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 $fX = class {
  constructor() {
    this.d = new $Uh();
  }
  async waitUntilTaskIsFinished() {
    await this.d.wait();
    return this.g;
  }
  run() {
    if (!this.g) {
      this.g = $Hh((token) => this.h(token));
    }
    this.d.open();
    return this.g;
  }
  cancel() {
    if (!this.g) {
      this.g = $Hh((token) => {
        return new Promise((c, e) => {
          const disposable = token.onCancellationRequested(() => {
            disposable.dispose();
            e(new $lb());
          });
        });
      });
      this.d.open();
    }
    this.g.cancel();
  }
};

// out-build/vs/workbench/services/extensionManagement/common/webExtensionManagementService.js
var $Pnc = class $Pnc2 extends $dX {
  get onProfileAwareInstallExtension() {
    return super.onInstallExtension;
  }
  get onInstallExtension() {
    return Event2.filter(this.onProfileAwareInstallExtension, (e) => this.gb(e), this.f);
  }
  get onProfileAwareDidInstallExtensions() {
    return super.onDidInstallExtensions;
  }
  get onDidInstallExtensions() {
    return Event2.filter(Event2.map(this.onProfileAwareDidInstallExtensions, (results) => results.filter((e) => this.gb(e)), this.f), (results) => results.length > 0, this.f);
  }
  get onProfileAwareUninstallExtension() {
    return super.onUninstallExtension;
  }
  get onUninstallExtension() {
    return Event2.filter(this.onProfileAwareUninstallExtension, (e) => this.gb(e), this.f);
  }
  get onProfileAwareDidUninstallExtension() {
    return super.onDidUninstallExtension;
  }
  get onDidUninstallExtension() {
    return Event2.filter(this.onProfileAwareDidUninstallExtension, (e) => this.gb(e), this.f);
  }
  get onProfileAwareDidUpdateExtensionMetadata() {
    return super.onDidUpdateExtensionMetadata;
  }
  constructor(extensionGalleryService, telemetryService, logService, db, eb, fb, productService, allowedExtensionsService, userDataProfilesService, uriIdentityService) {
    super(extensionGalleryService, telemetryService, uriIdentityService, logService, productService, allowedExtensionsService, userDataProfilesService);
    this.db = db;
    this.eb = eb;
    this.fb = fb;
    this.f = this.B(new $2c());
    this.cb = this.B(new $ze());
    this.onDidChangeProfile = this.cb.event;
    this.B(fb.onDidChangeCurrentProfile((e) => {
      if (!this.H.extUri.isEqual(e.previous.extensionsResource, e.profile.extensionsResource)) {
        e.join(this.ob(e));
      }
    }));
  }
  gb({ profileLocation, applicationScoped }) {
    profileLocation = profileLocation ?? this.fb.currentProfile.extensionsResource;
    return applicationScoped || this.H.extUri.isEqual(this.fb.currentProfile.extensionsResource, profileLocation);
  }
  async getTargetPlatform() {
    return "web";
  }
  async j(extension) {
    if (this.kb(extension)) {
      return true;
    }
    return super.j(extension);
  }
  async getInstalled(type, profileLocation) {
    const extensions = [];
    if (type === void 0 || type === 0) {
      const systemExtensions = await this.db.scanSystemExtensions();
      extensions.push(...systemExtensions);
    }
    if (type === void 0 || type === 1) {
      const userExtensions = await this.db.scanUserExtensions(profileLocation ?? this.fb.currentProfile.extensionsResource);
      extensions.push(...userExtensions);
    }
    return extensions.map((e) => toLocalExtension(e));
  }
  async install(location3, options3 = {}) {
    this.I.trace("ExtensionManagementService#install", location3.toString());
    const manifest = await this.db.scanExtensionManifest(location3);
    if (!manifest || !manifest.name || !manifest.version) {
      throw new Error(`Cannot find a valid extension from the location ${location3.toString()}`);
    }
    const result = await this.L([{ manifest, extension: location3, options: options3 }]);
    if (result[0]?.local) {
      return result[0]?.local;
    }
    if (result[0]?.error) {
      throw result[0].error;
    }
    throw $eX(new Error(`Unknown error while installing extension ${$IA(manifest.publisher, manifest.name)}`));
  }
  installFromLocation(location3, profileLocation) {
    return this.install(location3, { profileLocation });
  }
  async bb(extension, fromProfileLocation, toProfileLocation, metadata) {
    const target = await this.db.scanExistingExtension(extension.location, extension.type, toProfileLocation);
    const source = await this.db.scanExistingExtension(extension.location, extension.type, fromProfileLocation);
    metadata = { ...source?.metadata, ...metadata };
    let scanned;
    if (target) {
      scanned = await this.db.updateMetadata(extension, { ...target.metadata, ...metadata }, toProfileLocation);
    } else {
      scanned = await this.db.addExtension(extension.location, metadata, toProfileLocation);
    }
    return toLocalExtension(scanned);
  }
  async installExtensionsFromProfile(extensions, fromProfileLocation, toProfileLocation) {
    const result = [];
    const extensionsToInstall = (await this.db.scanUserExtensions(fromProfileLocation)).filter((e) => extensions.some((id2) => $DA(id2, e.identifier)));
    if (extensionsToInstall.length) {
      await Promise.allSettled(extensionsToInstall.map(async (e) => {
        let local = await this.installFromLocation(e.location, toProfileLocation);
        if (e.metadata) {
          local = await this.updateMetadata(local, e.metadata, fromProfileLocation);
        }
        result.push(local);
      }));
    }
    return result;
  }
  async updateMetadata(local, metadata, profileLocation) {
    if (metadata.isMachineScoped === false) {
      metadata.isMachineScoped = void 0;
    }
    if (metadata.isBuiltin === false) {
      metadata.isBuiltin = void 0;
    }
    if (metadata.pinned === false) {
      metadata.pinned = void 0;
    }
    const updatedExtension = await this.db.updateMetadata(local, metadata, profileLocation);
    const updatedLocalExtension = toLocalExtension(updatedExtension);
    this.C.fire({ local: updatedLocalExtension, profileLocation });
    return updatedLocalExtension;
  }
  async copyExtensions(fromProfileLocation, toProfileLocation) {
    await this.db.copyExtensions(fromProfileLocation, toProfileLocation, (e) => !e.metadata?.isApplicationScoped);
  }
  async R(extension, sameVersion, includePreRelease, productVersion) {
    const compatibleExtension = await super.R(extension, sameVersion, includePreRelease, productVersion);
    if (compatibleExtension) {
      return compatibleExtension;
    }
    if (this.kb(extension)) {
      return extension;
    }
    return null;
  }
  kb(gallery) {
    const configuredExtensionKind = this.eb.getUserConfiguredExtensionKind(gallery.identifier);
    return !!configuredExtensionKind && configuredExtensionKind.includes("web");
  }
  Z() {
    return this.fb.currentProfile.extensionsResource;
  }
  $(manifest, extension, options3) {
    return new InstallExtensionTask(manifest, extension, options3, this.db, this.J);
  }
  ab(extension, options3) {
    return new UninstallExtensionTask(extension, options3, this.db);
  }
  zip(extension) {
    throw new Error("unsupported");
  }
  getManifest(vsix) {
    throw new Error("unsupported");
  }
  download() {
    throw new Error("unsupported");
  }
  reinstallFromGallery() {
    throw new Error("unsupported");
  }
  async cleanUp() {
  }
  async ob(e) {
    const previousProfileLocation = e.previous.extensionsResource;
    const currentProfileLocation = e.profile.extensionsResource;
    if (!previousProfileLocation || !currentProfileLocation) {
      throw new Error("This should not happen");
    }
    const oldExtensions = await this.db.scanUserExtensions(previousProfileLocation);
    const newExtensions = await this.db.scanUserExtensions(currentProfileLocation);
    const { added, removed } = $Jb(oldExtensions, newExtensions, (a, b) => $Tf(`${$5z.toKey(a.identifier.id)}@${a.manifest.version}`, `${$5z.toKey(b.identifier.id)}@${b.manifest.version}`));
    this.cb.fire({ added: added.map((e2) => toLocalExtension(e2)), removed: removed.map((e2) => toLocalExtension(e2)) });
  }
};
$Pnc = __decorate([
  __param(0, $pA),
  __param(1, $zv),
  __param(2, $wn),
  __param(3, $rzb),
  __param(4, $LCb),
  __param(5, $gT),
  __param(6, $Vu),
  __param(7, $xA),
  __param(8, $rs),
  __param(9, $vl)
], $Pnc);
function toLocalExtension(extension) {
  const metadata = getMetadata(void 0, extension);
  return {
    ...extension,
    identifier: { id: extension.identifier.id, uuid: metadata.id ?? extension.identifier.uuid },
    isMachineScoped: !!metadata.isMachineScoped,
    isApplicationScoped: !!metadata.isApplicationScoped,
    publisherId: metadata.publisherId || null,
    publisherDisplayName: metadata.publisherDisplayName,
    installedTimestamp: metadata.installedTimestamp,
    isPreReleaseVersion: !!metadata.isPreReleaseVersion,
    hasPreReleaseVersion: !!metadata.hasPreReleaseVersion,
    preRelease: extension.preRelease,
    targetPlatform: "web",
    updated: !!metadata.updated,
    pinned: !!metadata?.pinned,
    isWorkspaceScoped: false,
    source: metadata?.source ?? (extension.identifier.uuid ? "gallery" : "resource"),
    size: metadata.size ?? 0
  };
}
function getMetadata(options3, existingExtension) {
  const metadata = { ...existingExtension?.metadata || {} };
  metadata.isMachineScoped = options3?.isMachineScoped || metadata.isMachineScoped;
  return metadata;
}
var InstallExtensionTask = class extends $fX {
  get profileLocation() {
    return this.f;
  }
  get operation() {
    return $Gg(this.options.operation) ? this.j : this.options.operation;
  }
  constructor(manifest, k, options3, l, m) {
    super();
    this.manifest = manifest;
    this.k = k;
    this.options = options3;
    this.l = l;
    this.m = m;
    this.f = this.options.profileLocation;
    this.j = 2;
    this.identifier = URI.isUri(k) ? { id: $IA(manifest.publisher, manifest.name) } : k.identifier;
    this.source = k;
  }
  async h(token) {
    const userExtensions = await this.l.scanUserExtensions(this.options.profileLocation);
    const existingExtension = userExtensions.find((e) => $DA(e.identifier, this.identifier));
    if (existingExtension) {
      this.j = 3;
    }
    const metadata = getMetadata(this.options, existingExtension);
    if (!URI.isUri(this.k)) {
      metadata.id = this.k.identifier.uuid;
      metadata.publisherDisplayName = this.k.publisherDisplayName;
      metadata.publisherId = this.k.publisherId;
      metadata.installedTimestamp = Date.now();
      metadata.isPreReleaseVersion = this.k.properties.isPreReleaseVersion;
      metadata.hasPreReleaseVersion = metadata.hasPreReleaseVersion || this.k.properties.isPreReleaseVersion;
      metadata.isBuiltin = this.options.isBuiltin || existingExtension?.isBuiltin;
      metadata.isSystem = existingExtension?.type === 0 ? true : void 0;
      metadata.updated = !!existingExtension;
      metadata.isApplicationScoped = this.options.isApplicationScoped || metadata.isApplicationScoped;
      metadata.preRelease = $Fg(this.options.preRelease) ? this.options.preRelease : this.options.installPreReleaseVersion || this.k.properties.isPreReleaseVersion || metadata.preRelease;
      metadata.source = URI.isUri(this.k) ? "resource" : "gallery";
    }
    metadata.pinned = this.options.installGivenVersion ? true : this.options.pinned ?? metadata.pinned;
    this.f = metadata.isApplicationScoped ? this.m.defaultProfile.extensionsResource : this.options.profileLocation;
    const scannedExtension = URI.isUri(this.k) ? await this.l.addExtension(this.k, metadata, this.profileLocation) : await this.l.addExtensionFromGallery(this.k, metadata, this.profileLocation);
    return toLocalExtension(scannedExtension);
  }
};
var UninstallExtensionTask = class extends $fX {
  constructor(extension, options3, f) {
    super();
    this.extension = extension;
    this.options = options3;
    this.f = f;
  }
  h(token) {
    return this.f.removeExtension(this.extension, this.options.profileLocation);
  }
};

// out-build/vs/platform/extensionManagement/common/extensionManagementIpc.js
function transformIncomingExtension(extension, transformer) {
  transformer = transformer ? transformer : $sy;
  const manifest = extension.manifest;
  const transformed = $vy({ ...extension, ...{ manifest: void 0 } }, transformer);
  return { ...transformed, ...{ manifest } };
}
var $hX = class extends $cX {
  get onInstallExtension() {
    return this.f.event;
  }
  get onDidInstallExtensions() {
    return this.m.event;
  }
  get onUninstallExtension() {
    return this.n.event;
  }
  get onDidUninstallExtension() {
    return this.s.event;
  }
  get onDidUpdateExtensionMetadata() {
    return this.t.event;
  }
  constructor(u, productService, allowedExtensionsService) {
    super(productService, allowedExtensionsService);
    this.u = u;
    this.f = this.B(new $ze());
    this.m = this.B(new $ze());
    this.n = this.B(new $ze());
    this.s = this.B(new $ze());
    this.t = this.B(new $ze());
    this.B(this.u.listen("onInstallExtension")((e) => this.w({ ...e, source: this.F(e.source) ? URI.revive(e.source) : e.source, profileLocation: URI.revive(e.profileLocation) })));
    this.B(this.u.listen("onDidInstallExtensions")((results) => this.y(results.map((e) => ({ ...e, local: e.local ? transformIncomingExtension(e.local, null) : e.local, source: this.F(e.source) ? URI.revive(e.source) : e.source, profileLocation: URI.revive(e.profileLocation) })))));
    this.B(this.u.listen("onUninstallExtension")((e) => this.z({ ...e, profileLocation: URI.revive(e.profileLocation) })));
    this.B(this.u.listen("onDidUninstallExtension")((e) => this.C({ ...e, profileLocation: URI.revive(e.profileLocation) })));
    this.B(this.u.listen("onDidUpdateExtensionMetadata")((e) => this.D({ profileLocation: URI.revive(e.profileLocation), local: transformIncomingExtension(e.local, null) })));
  }
  w(event) {
    this.f.fire(event);
  }
  y(results) {
    this.m.fire(results);
  }
  z(event) {
    this.n.fire(event);
  }
  C(event) {
    this.s.fire(event);
  }
  D(event) {
    this.t.fire(event);
  }
  F(thing) {
    if (!thing) {
      return false;
    }
    return typeof thing.path === "string" && typeof thing.scheme === "string";
  }
  getTargetPlatform() {
    if (!this.G) {
      this.G = this.u.call("getTargetPlatform");
    }
    return this.G;
  }
  zip(extension) {
    return Promise.resolve(this.u.call("zip", [extension]).then((result) => URI.revive(result)));
  }
  install(vsix, options3) {
    return Promise.resolve(this.u.call("install", [vsix, options3])).then((local) => transformIncomingExtension(local, null));
  }
  installFromLocation(location3, profileLocation) {
    return Promise.resolve(this.u.call("installFromLocation", [location3, profileLocation])).then((local) => transformIncomingExtension(local, null));
  }
  async installExtensionsFromProfile(extensions, fromProfileLocation, toProfileLocation) {
    const result = await this.u.call("installExtensionsFromProfile", [extensions, fromProfileLocation, toProfileLocation]);
    return result.map((local) => transformIncomingExtension(local, null));
  }
  getManifest(vsix) {
    return Promise.resolve(this.u.call("getManifest", [vsix]));
  }
  installFromGallery(extension, installOptions) {
    return Promise.resolve(this.u.call("installFromGallery", [extension, installOptions])).then((local) => transformIncomingExtension(local, null));
  }
  async installGalleryExtensions(extensions) {
    const results = await this.u.call("installGalleryExtensions", [extensions]);
    return results.map((e) => ({ ...e, local: e.local ? transformIncomingExtension(e.local, null) : e.local, source: this.F(e.source) ? URI.revive(e.source) : e.source, profileLocation: URI.revive(e.profileLocation) }));
  }
  uninstall(extension, options3) {
    if (extension.isWorkspaceScoped) {
      throw new Error("Cannot uninstall a workspace extension");
    }
    return Promise.resolve(this.u.call("uninstall", [extension, options3]));
  }
  uninstallExtensions(extensions) {
    if (extensions.some((e) => e.extension.isWorkspaceScoped)) {
      throw new Error("Cannot uninstall a workspace extension");
    }
    return Promise.resolve(this.u.call("uninstallExtensions", [extensions]));
  }
  reinstallFromGallery(extension) {
    return Promise.resolve(this.u.call("reinstallFromGallery", [extension])).then((local) => transformIncomingExtension(local, null));
  }
  getInstalled(type = null, extensionsProfileResource, productVersion) {
    return Promise.resolve(this.u.call("getInstalled", [type, extensionsProfileResource, productVersion])).then((extensions) => extensions.map((extension) => transformIncomingExtension(extension, null)));
  }
  updateMetadata(local, metadata, extensionsProfileResource) {
    return Promise.resolve(this.u.call("updateMetadata", [local, metadata, extensionsProfileResource])).then((extension) => transformIncomingExtension(extension, null));
  }
  resetPinnedStateForAllUserExtensions(pinned) {
    return this.u.call("resetPinnedStateForAllUserExtensions", [pinned]);
  }
  toggleAppliationScope(local, fromProfileLocation) {
    return this.u.call("toggleAppliationScope", [local, fromProfileLocation]).then((extension) => transformIncomingExtension(extension, null));
  }
  copyExtensions(fromProfileLocation, toProfileLocation) {
    return this.u.call("copyExtensions", [fromProfileLocation, toProfileLocation]);
  }
  getExtensionsControlManifest() {
    return Promise.resolve(this.u.call("getExtensionsControlManifest"));
  }
  async download(extension, operation, donotVerifySignature) {
    const result = await this.u.call("download", [extension, operation, donotVerifySignature]);
    return URI.revive(result);
  }
  async cleanUp() {
    return this.u.call("cleanUp");
  }
  registerParticipant() {
    throw new Error("Not Supported");
  }
};

// out-build/vs/workbench/services/extensionManagement/common/extensionManagementChannelClient.js
var $Qnc = class extends $hX {
  get onProfileAwareDidInstallExtensions() {
    return this.I.event;
  }
  get onProfileAwareDidUninstallExtension() {
    return this.J.event;
  }
  get onProfileAwareDidUpdateExtensionMetadata() {
    return this.L.event;
  }
  constructor(channel, productService, allowedExtensionsService, M, N) {
    super(channel, productService, allowedExtensionsService);
    this.M = M;
    this.N = N;
    this.H = this.B(new $ze());
    this.onDidChangeProfile = this.H.event;
    this.I = this.B(new $ze());
    this.J = this.B(new $ze());
    this.L = this.B(new $ze());
    this.B(M.onDidChangeCurrentProfile((e) => {
      if (!this.N.extUri.isEqual(e.previous.extensionsResource, e.profile.extensionsResource)) {
        e.join(this.W(e));
      }
    }));
  }
  async w(data) {
    const result = this.Z(data.profileLocation, data.applicationScoped ?? false);
    if (result instanceof Promise ? await result : result) {
      this.f.fire(data);
    }
  }
  async y(results) {
    const filtered = [];
    for (const e of results) {
      const result = this.Z(e.profileLocation, e.applicationScoped ?? e.local?.isApplicationScoped ?? false);
      if (result instanceof Promise ? await result : result) {
        filtered.push(e);
      }
    }
    if (filtered.length) {
      this.m.fire(filtered);
    }
    this.I.fire(results);
  }
  async z(data) {
    const result = this.Z(data.profileLocation, data.applicationScoped ?? false);
    if (result instanceof Promise ? await result : result) {
      this.n.fire(data);
    }
  }
  async C(data) {
    const result = this.Z(data.profileLocation, data.applicationScoped ?? false);
    if (result instanceof Promise ? await result : result) {
      this.s.fire(data);
    }
    this.J.fire(data);
  }
  async D(data) {
    const result = this.Z(data.profileLocation, data.local?.isApplicationScoped ?? false);
    if (result instanceof Promise ? await result : result) {
      this.t.fire(data);
    }
    this.L.fire(data);
  }
  async install(vsix, installOptions) {
    installOptions = { ...installOptions, profileLocation: await this.Y(installOptions?.profileLocation) };
    return super.install(vsix, installOptions);
  }
  async installFromLocation(location3, profileLocation) {
    return super.installFromLocation(location3, await this.Y(profileLocation));
  }
  async installFromGallery(extension, installOptions) {
    installOptions = { ...installOptions, profileLocation: await this.Y(installOptions?.profileLocation) };
    return super.installFromGallery(extension, installOptions);
  }
  async installGalleryExtensions(extensions) {
    const infos = [];
    for (const extension of extensions) {
      infos.push({ ...extension, options: { ...extension.options, profileLocation: await this.Y(extension.options?.profileLocation) } });
    }
    return super.installGalleryExtensions(infos);
  }
  async uninstall(extension, options3) {
    options3 = { ...options3, profileLocation: await this.Y(options3?.profileLocation) };
    return super.uninstall(extension, options3);
  }
  async uninstallExtensions(extensions) {
    const infos = [];
    for (const { extension, options: options3 } of extensions) {
      infos.push({ extension, options: { ...options3, profileLocation: await this.Y(options3?.profileLocation) } });
    }
    return super.uninstallExtensions(infos);
  }
  async getInstalled(type = null, extensionsProfileResource, productVersion) {
    return super.getInstalled(type, await this.Y(extensionsProfileResource), productVersion);
  }
  async updateMetadata(local, metadata, extensionsProfileResource) {
    return super.updateMetadata(local, metadata, await this.Y(extensionsProfileResource));
  }
  async toggleAppliationScope(local, fromProfileLocation) {
    return super.toggleAppliationScope(local, await this.Y(fromProfileLocation));
  }
  async copyExtensions(fromProfileLocation, toProfileLocation) {
    return super.copyExtensions(await this.Y(fromProfileLocation), await this.Y(toProfileLocation));
  }
  async W(e) {
    const previousProfileLocation = await this.Y(e.previous.extensionsResource);
    const currentProfileLocation = await this.Y(e.profile.extensionsResource);
    if (this.N.extUri.isEqual(previousProfileLocation, currentProfileLocation)) {
      return;
    }
    const eventData = await this.X(previousProfileLocation, currentProfileLocation);
    this.H.fire(eventData);
  }
  async X(previousProfileLocation, currentProfileLocation, preserveExtensions) {
    const oldExtensions = await this.getInstalled(1, previousProfileLocation);
    const newExtensions = await this.getInstalled(1, currentProfileLocation);
    if (preserveExtensions?.length) {
      const extensionsToInstall = [];
      for (const extension of oldExtensions) {
        if (preserveExtensions.some((id2) => $5z.equals(extension.identifier.id, id2)) && !newExtensions.some((e) => $5z.equals(e.identifier.id, extension.identifier.id))) {
          extensionsToInstall.push(extension.identifier);
        }
      }
      if (extensionsToInstall.length) {
        await this.installExtensionsFromProfile(extensionsToInstall, previousProfileLocation, currentProfileLocation);
      }
    }
    return $Jb(oldExtensions, newExtensions, (a, b) => $Tf(`${$5z.toKey(a.identifier.id)}@${a.manifest.version}`, `${$5z.toKey(b.identifier.id)}@${b.manifest.version}`));
  }
  async Y(profileLocation) {
    return profileLocation ?? this.M.currentProfile.extensionsResource;
  }
};

// out-build/vs/workbench/services/extensionManagement/common/remoteExtensionManagementService.js
var $Rnc = class $Rnc2 extends $Qnc {
  constructor(channel, productService, allowedExtensionsService, userDataProfileService, $149, ab, uriIdentityService) {
    super(channel, productService, allowedExtensionsService, userDataProfileService, uriIdentityService);
    this.$ = $149;
    this.ab = ab;
  }
  async Z(profileLocation, applicationScoped) {
    if (applicationScoped) {
      return true;
    }
    if (!profileLocation && this.M.currentProfile.isDefault) {
      return true;
    }
    const currentRemoteProfile = await this.ab.getRemoteProfile(this.M.currentProfile);
    if (this.N.extUri.isEqual(currentRemoteProfile.extensionsResource, profileLocation)) {
      return true;
    }
    return false;
  }
  async Y(profileLocation) {
    if (!profileLocation && this.M.currentProfile.isDefault) {
      return void 0;
    }
    profileLocation = await super.Y(profileLocation);
    let profile = this.$.profiles.find((p) => this.N.extUri.isEqual(p.extensionsResource, profileLocation));
    if (profile) {
      profile = await this.ab.getRemoteProfile(profile);
    } else {
      profile = (await this.ab.getRemoteProfiles()).find((p) => this.N.extUri.isEqual(p.extensionsResource, profileLocation));
    }
    return profile?.extensionsResource;
  }
  async X(previousProfileLocation, currentProfileLocation, preserveExtensions) {
    const remoteProfiles = await this.ab.getRemoteProfiles();
    const previousProfile = remoteProfiles.find((p) => this.N.extUri.isEqual(p.extensionsResource, previousProfileLocation));
    const currentProfile = remoteProfiles.find((p) => this.N.extUri.isEqual(p.extensionsResource, currentProfileLocation));
    if (previousProfile?.id === currentProfile?.id) {
      return { added: [], removed: [] };
    }
    return super.X(previousProfileLocation, currentProfileLocation, preserveExtensions);
  }
};
$Rnc = __decorate([
  __param(1, $Vu),
  __param(2, $xA),
  __param(3, $gT),
  __param(4, $rs),
  __param(5, $ZWb),
  __param(6, $vl)
], $Rnc);

// out-build/vs/workbench/services/extensionManagement/common/extensionManagementServerService.js
var $Snc = class $Snc2 {
  constructor(remoteAgentService, labelService, instantiationService) {
    this.localExtensionManagementServer = null;
    this.remoteExtensionManagementServer = null;
    this.webExtensionManagementServer = null;
    const remoteAgentConnection = remoteAgentService.getConnection();
    if (remoteAgentConnection) {
      const extensionManagementService = instantiationService.createInstance($Rnc, remoteAgentConnection.getChannel("extensions"));
      this.remoteExtensionManagementServer = {
        id: "remote",
        extensionManagementService,
        get label() {
          return labelService.getHostLabel(Schemas.vscodeRemote, remoteAgentConnection.remoteAuthority) || localize(12745, null);
        }
      };
    }
    if ($r) {
      const extensionManagementService = instantiationService.createInstance($Pnc);
      this.webExtensionManagementServer = {
        id: "web",
        extensionManagementService,
        label: localize(12746, null)
      };
    }
  }
  getExtensionManagementServer(extension) {
    if (extension.location.scheme === Schemas.vscodeRemote) {
      return this.remoteExtensionManagementServer;
    }
    if (this.webExtensionManagementServer) {
      return this.webExtensionManagementServer;
    }
    throw new Error(`Invalid Extension ${extension.location}`);
  }
  getExtensionInstallLocation(extension) {
    const server = this.getExtensionManagementServer(extension);
    return server === this.remoteExtensionManagementServer ? 2 : 3;
  }
};
$Snc = __decorate([
  __param(0, $RL),
  __param(1, $ZI),
  __param(2, $Pk)
], $Snc);
$SC(
  $nzb,
  $Snc,
  1
  /* InstantiationType.Delayed */
);

// 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 $sJ("@microsoft/1ds-core-js", "bundle/ms.core.min.js") : await import("@microsoft/1ds-core-js");
  const postPlugin = $r ? await $sJ("@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 $KY = class {
  constructor(e, f, g, iKeyOrClientFactory, h3) {
    this.e = e;
    this.f = f;
    this.g = g;
    this.h = h3;
    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) => {
      $gb(err);
      console.error(err);
    });
  }
  log(eventName, data) {
    if (!this.a) {
      return;
    }
    data = $Ov(data, this.g);
    data = $lw(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/browser/1dsAppender.js
var $Tnc = class extends $KY {
  constructor(isInternalTelemetry, eventPrefix, defaultData, iKeyOrClientFactory) {
    super(isInternalTelemetry, eventPrefix, defaultData, iKeyOrClientFactory);
  }
};

// out-build/vs/platform/telemetry/common/telemetryLogAppender.js
var $Unc = class $Unc2 extends $3c {
  constructor(logService, loggerService, environmentService, productService, b = "") {
    super();
    this.b = b;
    const logger2 = loggerService.getLogger($fw);
    if (logger2) {
      this.a = this.B(logger2);
    } else {
      const justLoggingAndNotSending = $jw(productService, environmentService);
      const logSuffix = justLoggingAndNotSending ? " (Not Sent)" : "";
      const isVisible = () => $iw(productService, environmentService) && logService.getLevel() === LogLevel.Trace;
      this.a = this.B(loggerService.createLogger($fw, { name: localize(2106, null, logSuffix), hidden: !isVisible() }));
      this.B(logService.onDidChangeLogLevel(() => loggerService.setVisibility($fw, 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}`, $lw(data));
  }
};
$Unc = __decorate([
  __param(0, $wn),
  __param(1, $xn),
  __param(2, $Xk),
  __param(3, $Vu)
], $Unc);

// out-build/vs/platform/telemetry/common/telemetryService.js
var $tz = class $tz2 {
  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 $2c();
    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($Iv) || e.affectsConfiguration($Kv) || e.affectsConfiguration($Jv);
      if (affectsTelemetryConfig) {
        this.m();
      }
    }));
  }
  setExperimentProperty(name, value) {
    this.d[name] = value;
  }
  m() {
    let level = $kw(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 = $Ov(data, this.d);
    data = $pw(data, this.j);
    data = $Ov(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);
  }
};
$tz = __decorate([
  __param(1, $kl),
  __param(2, $Vu)
], $tz);
function getTelemetryLevelSettingDescription() {
  const telemetryText = localize(2107, null, product_default.nameLong);
  const externalLinksStatement = !product_default.privacyStatementUrl ? localize(2108, null, "https://aka.ms/vscode-telemetry") : localize(2109, null, "https://aka.ms/vscode-telemetry", product_default.privacyStatementUrl);
  const restartString = !$r ? localize(2110, null) : "";
  const crashReportsHeader = localize(2111, null);
  const errorsHeader = localize(2112, null);
  const usageHeader = localize(2113, null);
  const telemetryTableDescription = localize(2114, null);
  const telemetryTable = `
|       | ${crashReportsHeader} | ${errorsHeader} | ${usageHeader} |
|:------|:---------------------:|:---------------:|:--------------:|
| all   |            \u2713          |        \u2713        |        \u2713       |
| error |            \u2713          |        \u2713        |        -       |
| crash |            \u2713          |        -        |        -       |
| off   |            -          |        -        |        -       |
`;
  const deprecatedSettingNote = localize(2115, null);
  const telemetryDescription = `
${telemetryText} ${externalLinksStatement} ${restartString}

&nbsp;

${telemetryTableDescription}
${telemetryTable}

&nbsp;

${deprecatedSettingNote}
`;
  return telemetryDescription;
}
$Wn.as($Ht.Configuration).registerConfiguration({
  "id": $Hv,
  "order": 1,
  "type": "object",
  "title": localize(2116, null),
  "properties": {
    [$Iv]: {
      "type": "string",
      "enum": [
        "all",
        "error",
        "crash",
        "off"
        /* TelemetryConfiguration.OFF */
      ],
      "enumDescriptions": [
        localize(2117, null),
        localize(2118, null),
        localize(2119, null),
        localize(2120, null)
      ],
      "markdownDescription": getTelemetryLevelSettingDescription(),
      "default": "all",
      "restricted": true,
      "scope": 1,
      "tags": ["usesOnlineServices", "telemetry"]
    }
  }
});
$Wn.as($Ht.Configuration).registerConfiguration({
  "id": $Hv,
  "order": 110,
  "type": "object",
  "title": localize(2121, null),
  "properties": {
    [$Kv]: {
      "type": "boolean",
      "markdownDescription": !product_default.privacyStatementUrl ? localize(2122, null, product_default.nameLong) : localize(2123, null, product_default.nameLong, product_default.privacyStatementUrl),
      "default": true,
      "restricted": true,
      "markdownDeprecationMessage": localize(2124, null, `\`#${$Iv}#\``),
      "scope": 1,
      "tags": ["usesOnlineServices", "telemetry"]
    }
  }
});

// out-build/vs/workbench/services/telemetry/browser/workbenchCommonProperties.js
function cleanUserAgent(userAgent2) {
  return userAgent2.replace(/(\d+\.\d+)(\.\d+)+/g, "$1");
}
function $Vnc(storageService, commit, version2, isInternalTelemetry, remoteAuthority, productIdentifier, removeMachineId, resolveAdditionalProperties) {
  const result = /* @__PURE__ */ Object.create(null);
  const firstSessionDate = storageService.get(
    $Cv,
    -1
    /* StorageScope.APPLICATION */
  );
  const lastSessionDate = storageService.get(
    $Dv,
    -1
    /* StorageScope.APPLICATION */
  );
  let machineId;
  if (!removeMachineId) {
    machineId = storageService.get(
      $Ev,
      -1
      /* StorageScope.APPLICATION */
    );
    if (!machineId) {
      machineId = $ps();
      storageService.store(
        $Ev,
        machineId,
        -1,
        1
        /* StorageTarget.MACHINE */
      );
    }
  } else {
    machineId = `Redacted-${productIdentifier ?? "web"}`;
  }
  result["common.firstSessionDate"] = firstSessionDate;
  result["common.lastSessionDate"] = lastSessionDate || "";
  result["common.isNewSession"] = !lastSessionDate ? "1" : "0";
  result["common.remoteAuthority"] = $mw(remoteAuthority);
  result["common.machineId"] = machineId;
  result["sessionID"] = $ps() + Date.now();
  result["commitHash"] = commit;
  result["version"] = version2;
  result["common.platform"] = $k($x);
  result["common.product"] = productIdentifier ?? "web";
  result["common.userAgent"] = $y ? cleanUserAgent($y) : void 0;
  result["common.isTouchDevice"] = String($mZ.isTouchDevice());
  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 (resolveAdditionalProperties) {
    $Ov(result, resolveAdditionalProperties());
  }
  return result;
}

// out-build/vs/workbench/services/telemetry/browser/telemetryService.js
var $Wnc = class $Wnc2 extends $3c {
  get sessionId() {
    return this.a.sessionId;
  }
  get machineId() {
    return this.a.machineId;
  }
  get sqmId() {
    return this.a.sqmId;
  }
  get devDeviceId() {
    return this.a.devDeviceId;
  }
  get firstSessionDate() {
    return this.a.firstSessionDate;
  }
  get msftInternal() {
    return this.a.msftInternal;
  }
  constructor(environmentService, logService, loggerService, configurationService, storageService, productService, remoteAgentService) {
    super();
    this.a = $dw;
    this.sendErrorTelemetry = true;
    this.a = this.b(environmentService, logService, loggerService, configurationService, storageService, productService, remoteAgentService);
    this.B(configurationService.onDidChangeConfiguration((e) => {
      if (e.affectsConfiguration($Iv)) {
        this.a = this.b(environmentService, logService, loggerService, configurationService, storageService, productService, remoteAgentService);
      }
    }));
  }
  /**
   * Initializes the telemetry service to be a full fledged service.
   * This is only done once and only when telemetry is enabled as this will also ping the endpoint to
   * ensure its not adblocked and we can send telemetry
   */
  b(environmentService, logService, loggerService, configurationService, storageService, productService, remoteAgentService) {
    const telemetrySupported = $iw(productService, environmentService) && productService.aiConfig?.ariaKey;
    if (telemetrySupported && $kw(configurationService) !== 0 && this.a === $dw) {
      const appenders = [];
      const isInternal = $nw(productService, configurationService);
      if (!$jw(productService, environmentService)) {
        if (remoteAgentService.getConnection() !== null) {
          const remoteTelemetryProvider = {
            log: remoteAgentService.logTelemetry.bind(remoteAgentService),
            flush: remoteAgentService.flushTelemetry.bind(remoteAgentService)
          };
          appenders.push(remoteTelemetryProvider);
        } else {
          appenders.push(new $Tnc(isInternal, "monacoworkbench", null, productService.aiConfig?.ariaKey));
        }
      }
      appenders.push(new $Unc(logService, loggerService, environmentService, productService));
      const config = {
        appenders,
        commonProperties: $Vnc(storageService, productService.commit, productService.version, isInternal, environmentService.remoteAuthority, productService.embedderIdentifier, productService.removeTelemetryMachineId, environmentService.options && environmentService.options.resolveCommonTelemetryProperties),
        sendErrorTelemetry: this.sendErrorTelemetry
      };
      return this.B(new $tz(config, configurationService, productService));
    }
    return this.a;
  }
  setExperimentProperty(name, value) {
    return this.a.setExperimentProperty(name, value);
  }
  get telemetryLevel() {
    return this.a.telemetryLevel;
  }
  publicLog(eventName, data) {
    this.a.publicLog(eventName, data);
  }
  publicLog2(eventName, data) {
    this.publicLog(eventName, data);
  }
  publicLogError(errorEventName, data) {
    this.a.publicLog(errorEventName, data);
  }
  publicLogError2(eventName, data) {
    this.publicLogError(eventName, data);
  }
};
$Wnc = __decorate([
  __param(0, $M4),
  __param(1, $wn),
  __param(2, $xn),
  __param(3, $kl),
  __param(4, $jv),
  __param(5, $Vu),
  __param(6, $RL)
], $Wnc);
$SC(
  $zv,
  $Wnc,
  1
  /* InstantiationType.Delayed */
);

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

// out-build/vs/workbench/services/url/browser/urlService.js
var BrowserURLOpener = class {
  constructor(a, b) {
    this.a = a;
    this.b = b;
  }
  async open(resource, options3) {
    if (options3?.openExternal) {
      return false;
    }
    if (!$0g(resource, this.b.urlProtocol)) {
      return false;
    }
    if (typeof resource === "string") {
      resource = URI.parse(resource);
    }
    return this.a.open(resource, { trusted: true });
  }
};
var $R4 = class $R42 extends $Gz {
  constructor(environmentService, openerService, productService) {
    super();
    this.b = environmentService.options?.urlCallbackProvider;
    if (this.b) {
      this.B(this.b.onCallback((uri) => this.open(uri, { trusted: true })));
    }
    this.B(openerService.registerOpener(new BrowserURLOpener(this, productService)));
  }
  create(options3) {
    if (this.b) {
      return this.b.create(options3);
    }
    return URI.parse("unsupported://");
  }
};
$R4 = __decorate([
  __param(0, $M4),
  __param(1, $O4),
  __param(2, $Vu)
], $R4);
$SC(
  $4y,
  $R4,
  1
  /* InstantiationType.Delayed */
);

// out-build/vs/workbench/services/update/browser/updateService.js
var $T4 = class $T42 extends $3c {
  get state() {
    return this.b;
  }
  set state(state) {
    this.b = state;
    this.a.fire(state);
  }
  constructor(c, f) {
    super();
    this.c = c;
    this.f = f;
    this.a = this.B(new $ze());
    this.onStateChange = this.a.event;
    this.b = $_y.Uninitialized;
    this.checkForUpdates(false);
  }
  async isLatestVersion() {
    const update = await this.g(false);
    if (update === void 0) {
      return void 0;
    }
    return !!update;
  }
  async checkForUpdates(explicit) {
    await this.g(explicit);
  }
  async g(explicit) {
    if (this.c.options && this.c.options.updateProvider) {
      const updateProvider = this.c.options.updateProvider;
      this.state = $_y.CheckingForUpdates(explicit);
      const update = await updateProvider.checkForUpdate();
      if (update) {
        this.state = $_y.Ready({ version: update.version, productVersion: update.version });
      } else {
        this.state = $_y.Idle(
          1
          /* UpdateType.Archive */
        );
      }
      return update;
    }
    return void 0;
  }
  async downloadUpdate() {
  }
  async applyUpdate() {
    this.f.reload();
  }
  async quitAndInstall() {
    this.f.reload();
  }
  async _applySpecificUpdate(packagePath) {
  }
};
$T4 = __decorate([
  __param(0, $M4),
  __param(1, $S4)
], $T4);
$SC(
  $az,
  $T4,
  0
  /* InstantiationType.Eager */
);

// out-build/vs/workbench/services/workspaces/browser/workspacesService.js
var $Xnc_1;
var $Xnc = class $Xnc2 extends $3c {
  static {
    $Xnc_1 = this;
  }
  static {
    this.RECENTLY_OPENED_KEY = "recently.opened";
  }
  constructor(b, c, f, g, h3, j) {
    super();
    this.b = b;
    this.c = c;
    this.f = f;
    this.g = g;
    this.h = h3;
    this.j = j;
    this.a = this.B(new $ze());
    this.onDidChangeRecentlyOpened = this.a.event;
    this.r();
    this.m();
  }
  m() {
    this.B(this.b.onDidChangeValue(-1, $Xnc_1.RECENTLY_OPENED_KEY, this.q)(() => this.a.fire()));
    this.B(this.c.onDidChangeWorkspaceFolders((e) => this.n(e)));
  }
  n(e) {
    if (!$fl(this.c.getWorkspace())) {
      return;
    }
    for (const folder of e.added) {
      this.addRecentlyOpened([{ folderUri: folder.uri }]);
    }
  }
  r() {
    const workspace2 = this.c.getWorkspace();
    const remoteAuthority = this.h.remoteAuthority;
    switch (this.c.getWorkbenchState()) {
      case 2:
        this.addRecentlyOpened([{ folderUri: workspace2.folders[0].uri, remoteAuthority }]);
        break;
      case 3:
        this.addRecentlyOpened([{ workspace: { id: workspace2.id, configPath: workspace2.configuration }, remoteAuthority }]);
        break;
    }
  }
  //#region Workspaces History
  async getRecentlyOpened() {
    const recentlyOpenedRaw = this.b.get(
      $Xnc_1.RECENTLY_OPENED_KEY,
      -1
      /* StorageScope.APPLICATION */
    );
    if (recentlyOpenedRaw) {
      const recentlyOpened = $0w(JSON.parse(recentlyOpenedRaw), this.f);
      recentlyOpened.workspaces = recentlyOpened.workspaces.filter((recent) => {
        if ($4w(recent) && recent.folderUri.scheme === Schemas.file && !$fl(this.c.getWorkspace())) {
          return false;
        }
        if ($3w(recent) && $fl(recent.workspace.configPath)) {
          return false;
        }
        return true;
      });
      return recentlyOpened;
    }
    return { workspaces: [], files: [] };
  }
  async addRecentlyOpened(recents) {
    const recentlyOpened = await this.getRecentlyOpened();
    for (const recent of recents) {
      if ($5w(recent)) {
        this.s(recentlyOpened, [recent.fileUri]);
        recentlyOpened.files.unshift(recent);
      } else if ($4w(recent)) {
        this.s(recentlyOpened, [recent.folderUri]);
        recentlyOpened.workspaces.unshift(recent);
      } else {
        this.s(recentlyOpened, [recent.workspace.configPath]);
        recentlyOpened.workspaces.unshift(recent);
      }
    }
    return this.t(recentlyOpened);
  }
  async removeRecentlyOpened(paths) {
    const recentlyOpened = await this.getRecentlyOpened();
    this.s(recentlyOpened, paths);
    return this.t(recentlyOpened);
  }
  s(recentlyOpened, paths) {
    recentlyOpened.files = recentlyOpened.files.filter((file) => {
      return !paths.some((path) => path.toString() === file.fileUri.toString());
    });
    recentlyOpened.workspaces = recentlyOpened.workspaces.filter((workspace2) => {
      return !paths.some((path) => path.toString() === ($4w(workspace2) ? workspace2.folderUri.toString() : workspace2.workspace.configPath.toString()));
    });
  }
  async t(data) {
    return this.b.store(
      $Xnc_1.RECENTLY_OPENED_KEY,
      JSON.stringify($$w(data)),
      -1,
      0
      /* StorageTarget.USER */
    );
  }
  async clearRecentlyOpened() {
    this.b.remove(
      $Xnc_1.RECENTLY_OPENED_KEY,
      -1
      /* StorageScope.APPLICATION */
    );
  }
  //#endregion
  //#region Workspace Management
  async enterWorkspace(workspaceUri) {
    return { workspace: await this.getWorkspaceIdentifier(workspaceUri) };
  }
  async createUntitledWorkspace(folders, remoteAuthority) {
    const randomId = (Date.now() + Math.round(Math.random() * 1e3)).toString();
    const newUntitledWorkspacePath = $vh(this.h.untitledWorkspacesHome, `Untitled-${randomId}.${$al}`);
    const storedWorkspaceFolder = [];
    if (folders) {
      for (const folder of folders) {
        storedWorkspaceFolder.push($7w(folder.uri, true, folder.name, this.h.untitledWorkspacesHome, this.j.extUri));
      }
    }
    const storedWorkspace = { folders: storedWorkspaceFolder, remoteAuthority };
    await this.g.writeFile(newUntitledWorkspacePath, $Ci.fromString(JSON.stringify(storedWorkspace, null, "	")));
    return this.getWorkspaceIdentifier(newUntitledWorkspacePath);
  }
  async deleteUntitledWorkspace(workspace2) {
    try {
      await this.g.del(workspace2.configPath);
    } catch (error) {
      if (error.fileOperationResult !== 1) {
        throw error;
      }
    }
  }
  async getWorkspaceIdentifier(workspaceUri) {
    return $nmc(workspaceUri);
  }
  //#endregion
  //#region Dirty Workspaces
  async getDirtyWorkspaces() {
    return [];
  }
};
$Xnc = $Xnc_1 = __decorate([
  __param(0, $jv),
  __param(1, $Zk),
  __param(2, $wn),
  __param(3, $km),
  __param(4, $US),
  __param(5, $vl)
], $Xnc);
$SC(
  $2w,
  $Xnc,
  1
  /* InstantiationType.Delayed */
);

// out-build/vs/workbench/services/workspaces/browser/abstractWorkspaceEditingService.js
var $Ync = class $Ync2 extends $3c {
  constructor(a, b, c, f, g, h3, j, m, n, r2, s, t, u, w, y, z) {
    super();
    this.a = a;
    this.b = b;
    this.c = c;
    this.f = f;
    this.g = g;
    this.h = h3;
    this.j = j;
    this.m = m;
    this.n = n;
    this.r = r2;
    this.s = s;
    this.t = t;
    this.u = u;
    this.w = w;
    this.y = y;
    this.z = z;
  }
  async pickNewWorkspacePath() {
    const availableFileSystems = [Schemas.file];
    if (this.n.remoteAuthority) {
      availableFileSystems.unshift(Schemas.vscodeRemote);
    }
    let workspacePath = await this.r.showSaveDialog({
      saveLabel: $7t(localize(13634, null)),
      title: localize(13635, null),
      filters: $cl,
      defaultUri: $vh(await this.r.defaultWorkspacePath(), this.C()),
      availableFileSystems
    });
    if (!workspacePath) {
      return;
    }
    if (!$jl(workspacePath)) {
      workspacePath = workspacePath.with({ path: `${workspacePath.path}.${$al}` });
    }
    return workspacePath;
  }
  C() {
    const configPathURI = this.R()?.configPath;
    if (configPathURI && $il(configPathURI, this.n)) {
      return $sh(configPathURI);
    }
    const folder = this.b.getWorkspace().folders.at(0);
    if (folder) {
      return `${$sh(folder.uri)}.${$al}`;
    }
    return `workspace.${$al}`;
  }
  async updateFolders(index, deleteCount, foldersToAddCandidates, donotNotifyError) {
    const folders = this.b.getWorkspace().folders;
    let foldersToDelete = [];
    if (typeof deleteCount === "number") {
      foldersToDelete = folders.slice(index, index + deleteCount).map((folder) => folder.uri);
    }
    let foldersToAdd = [];
    if (Array.isArray(foldersToAddCandidates)) {
      foldersToAdd = foldersToAddCandidates.map((folderToAdd) => ({ uri: $Ch(folderToAdd.uri), name: folderToAdd.name }));
    }
    const wantsToDelete = foldersToDelete.length > 0;
    const wantsToAdd = foldersToAdd.length > 0;
    if (!wantsToAdd && !wantsToDelete) {
      return;
    }
    if (wantsToAdd && !wantsToDelete) {
      return this.F(foldersToAdd, index, donotNotifyError);
    }
    if (wantsToDelete && !wantsToAdd) {
      return this.removeFolders(foldersToDelete);
    } else {
      if (this.G(foldersToDelete)) {
        return this.createAndEnterWorkspace(foldersToAdd);
      }
      if (this.b.getWorkbenchState() !== 3) {
        return this.F(foldersToAdd, index, donotNotifyError);
      }
      return this.D(foldersToAdd, foldersToDelete, index, donotNotifyError);
    }
  }
  async D(foldersToAdd, foldersToDelete, index, donotNotifyError = false) {
    try {
      await this.b.updateFolders(foldersToAdd, foldersToDelete, index);
    } catch (error) {
      if (donotNotifyError) {
        throw error;
      }
      this.J(error);
    }
  }
  addFolders(foldersToAddCandidates, donotNotifyError = false) {
    const foldersToAdd = foldersToAddCandidates.map((folderToAdd) => ({ uri: $Ch(folderToAdd.uri), name: folderToAdd.name }));
    return this.F(foldersToAdd, void 0, donotNotifyError);
  }
  async F(foldersToAdd, index, donotNotifyError = false) {
    const state = this.b.getWorkbenchState();
    const remoteAuthority = this.n.remoteAuthority;
    if (remoteAuthority) {
      foldersToAdd = foldersToAdd.filter((folder) => folder.uri.scheme !== Schemas.file && (folder.uri.scheme !== Schemas.vscodeRemote || $Ah(folder.uri.authority, remoteAuthority)));
    }
    if (state !== 3) {
      let newWorkspaceFolders = this.b.getWorkspace().folders.map((folder) => ({ uri: folder.uri }));
      newWorkspaceFolders.splice(typeof index === "number" ? index : newWorkspaceFolders.length, 0, ...foldersToAdd);
      newWorkspaceFolders = $Rb(newWorkspaceFolders, (folder) => this.u.extUri.getComparisonKey(folder.uri));
      if (state === 1 && newWorkspaceFolders.length === 0 || state === 2 && newWorkspaceFolders.length === 1) {
        return;
      }
      return this.createAndEnterWorkspace(newWorkspaceFolders);
    }
    try {
      await this.b.addFolders(foldersToAdd, index);
    } catch (error) {
      if (donotNotifyError) {
        throw error;
      }
      this.J(error);
    }
  }
  async removeFolders(foldersToRemove, donotNotifyError = false) {
    if (this.G(foldersToRemove)) {
      return this.createAndEnterWorkspace([]);
    }
    try {
      await this.b.removeFolders(foldersToRemove);
    } catch (error) {
      if (donotNotifyError) {
        throw error;
      }
      this.J(error);
    }
  }
  G(folders) {
    if (this.b.getWorkbenchState() === 2) {
      const workspaceFolder = this.b.getWorkspace().folders[0];
      return folders.some((folder) => this.u.extUri.isEqual(folder, workspaceFolder.uri));
    }
    return false;
  }
  async createAndEnterWorkspace(folders, path) {
    if (path && !await this.isValidTargetWorkspacePath(path)) {
      return;
    }
    const remoteAuthority = this.n.remoteAuthority;
    const untitledWorkspace = await this.m.createUntitledWorkspace(folders, remoteAuthority);
    if (path) {
      try {
        await this.H(untitledWorkspace, path);
      } finally {
        await this.m.deleteUntitledWorkspace(untitledWorkspace);
      }
    } else {
      path = untitledWorkspace.configPath;
      if (!this.z.currentProfile.isDefault) {
        await this.y.setProfileForWorkspace(untitledWorkspace, this.z.currentProfile);
      }
    }
    return this.enterWorkspace(path);
  }
  async saveAndEnterWorkspace(workspaceUri) {
    const workspaceIdentifier = this.R();
    if (!workspaceIdentifier) {
      return;
    }
    if ($oh(workspaceIdentifier.configPath, workspaceUri)) {
      return this.I(workspaceIdentifier);
    }
    if (!await this.isValidTargetWorkspacePath(workspaceUri)) {
      return;
    }
    await this.H(workspaceIdentifier, workspaceUri);
    return this.enterWorkspace(workspaceUri);
  }
  async isValidTargetWorkspacePath(workspaceUri) {
    return true;
  }
  async H(workspace2, targetConfigPathURI) {
    const configPathURI = workspace2.configPath;
    const isNotUntitledWorkspace = !$el(targetConfigPathURI, this.n);
    if (isNotUntitledWorkspace && !this.z.currentProfile.isDefault) {
      const newWorkspace = await this.m.getWorkspaceIdentifier(targetConfigPathURI);
      await this.y.setProfileForWorkspace(newWorkspace, this.z.currentProfile);
    }
    if (this.u.extUri.isEqual(configPathURI, targetConfigPathURI)) {
      return;
    }
    const isFromUntitledWorkspace = $el(configPathURI, this.n);
    const raw = await this.h.readFile(configPathURI);
    const newRawWorkspaceContents = $9w(raw.value.toString(), configPathURI, isFromUntitledWorkspace, targetConfigPathURI, this.u.extUri);
    await this.j.create([{ resource: targetConfigPathURI, value: newRawWorkspaceContents, options: { overwrite: true } }]);
    await this.Q(targetConfigPathURI);
  }
  async I(workspace2) {
    const configPathURI = workspace2.configPath;
    const existingModel = this.j.files.get(configPathURI);
    if (existingModel) {
      await existingModel.save({
        force: true,
        reason: 1
        /* SaveReason.EXPLICIT */
      });
      return;
    }
    const workspaceFileExists = await this.h.exists(configPathURI);
    if (workspaceFileExists) {
      return;
    }
    const newWorkspace = { folders: [] };
    const newRawWorkspaceContents = $9w(JSON.stringify(newWorkspace, null, "	"), configPathURI, false, configPathURI, this.u.extUri);
    await this.j.create([{ resource: configPathURI, value: newRawWorkspaceContents }]);
  }
  J(error) {
    switch (error.code) {
      case 0:
        this.L();
        break;
      default:
        this.f.error(error.message);
    }
  }
  L() {
    const message = localize(13636, null);
    this.M(message);
  }
  M(message) {
    this.f.prompt(Severity2.Error, message, [{
      label: localize(13637, null),
      run: () => this.g.executeCommand("workbench.action.openWorkspaceConfigFile")
    }]);
  }
  async N(workspaceUri) {
    if (!!this.n.extensionTestsLocationURI) {
      throw new Error("Entering a new workspace is not possible in tests.");
    }
    const workspace2 = await this.m.getWorkspaceIdentifier(workspaceUri);
    if (this.b.getWorkbenchState() === 2) {
      await this.O(workspace2);
    }
    await this.c.initialize(workspace2);
    return this.m.enterWorkspace(workspaceUri);
  }
  O(toWorkspace) {
    return this.P(
      toWorkspace,
      (setting) => setting.scope === 3
      /* ConfigurationScope.WINDOW */
    );
  }
  copyWorkspaceSettings(toWorkspace) {
    return this.P(toWorkspace);
  }
  P(toWorkspace, filter) {
    const configurationProperties = $Wn.as($Ht.Configuration).getConfigurationProperties();
    const targetWorkspaceConfiguration = {};
    for (const key2 of this.c.keys().workspace) {
      if (configurationProperties[key2]) {
        if (filter && !filter(configurationProperties[key2])) {
          continue;
        }
        targetWorkspaceConfiguration[key2] = this.c.inspect(key2).workspaceValue;
      }
    }
    return this.a.write(toWorkspace.configPath, [{ path: ["settings"], value: targetWorkspaceConfiguration }], true);
  }
  async Q(configPathURI) {
    if (this.b.getWorkbenchState() !== 1 && this.w.isWorkspaceTrusted()) {
      await this.w.setUrisTrust([configPathURI], true);
    }
  }
  R() {
    const identifier2 = $5k(this.b.getWorkspace());
    if ($6k(identifier2)) {
      return identifier2;
    }
    return void 0;
  }
};
$Ync = __decorate([
  __param(0, $CBb),
  __param(1, $Zk),
  __param(2, $EK),
  __param(3, $PJ),
  __param(4, $sn),
  __param(5, $km),
  __param(6, $cK),
  __param(7, $2w),
  __param(8, $US),
  __param(9, $1v),
  __param(10, $Yv),
  __param(11, $S4),
  __param(12, $vl),
  __param(13, $4M),
  __param(14, $rs),
  __param(15, $gT)
], $Ync);

// out-build/vs/workbench/services/workspaces/browser/workspaceEditingService.js
var $Znc = class $Znc2 extends $Ync {
  constructor(jsonEditingService, contextService, configurationService, notificationService, commandService, fileService, textFileService, workspacesService, environmentService, fileDialogService, dialogService, hostService, uriIdentityService, workspaceTrustManagementService, userDataProfilesService, userDataProfileService) {
    super(jsonEditingService, contextService, configurationService, notificationService, commandService, fileService, textFileService, workspacesService, environmentService, fileDialogService, dialogService, hostService, uriIdentityService, workspaceTrustManagementService, userDataProfilesService, userDataProfileService);
  }
  async enterWorkspace(workspaceUri) {
    const result = await this.N(workspaceUri);
    if (result) {
      await this.t.openWindow([{ workspaceUri }], { forceReuseWindow: true });
    }
  }
};
$Znc = __decorate([
  __param(0, $CBb),
  __param(1, $Zk),
  __param(2, $EK),
  __param(3, $PJ),
  __param(4, $sn),
  __param(5, $km),
  __param(6, $cK),
  __param(7, $2w),
  __param(8, $US),
  __param(9, $1v),
  __param(10, $Yv),
  __param(11, $S4),
  __param(12, $vl),
  __param(13, $4M),
  __param(14, $rs),
  __param(15, $gT)
], $Znc);
$SC(
  $zob,
  $Znc,
  1
  /* InstantiationType.Delayed */
);

// out-build/vs/workbench/services/dialogs/browser/simpleFileDialog.js
var OpenLocalFileCommand;
(function(OpenLocalFileCommand2) {
  OpenLocalFileCommand2.ID = "workbench.action.files.openLocalFile";
  OpenLocalFileCommand2.LABEL = localize(12674, null);
  function handler() {
    return (accessor) => {
      const dialogService = accessor.get($1v);
      return dialogService.pickFileAndOpen({ forceNewWindow: false, availableFileSystems: [Schemas.file] });
    };
  }
  OpenLocalFileCommand2.handler = handler;
})(OpenLocalFileCommand || (OpenLocalFileCommand = {}));
var SaveLocalFileCommand;
(function(SaveLocalFileCommand2) {
  SaveLocalFileCommand2.ID = "workbench.action.files.saveLocalFile";
  SaveLocalFileCommand2.LABEL = localize(12675, null);
  function handler() {
    return (accessor) => {
      const editorService = accessor.get($mJ);
      const activeEditorPane = editorService.activeEditorPane;
      if (activeEditorPane) {
        return editorService.save({ groupId: activeEditorPane.group.id, editor: activeEditorPane.input }, {
          saveAs: true,
          availableFileSystems: [Schemas.file],
          reason: 1
          /* SaveReason.EXPLICIT */
        });
      }
      return Promise.resolve(void 0);
    };
  }
  SaveLocalFileCommand2.handler = handler;
})(SaveLocalFileCommand || (SaveLocalFileCommand = {}));
var OpenLocalFolderCommand;
(function(OpenLocalFolderCommand2) {
  OpenLocalFolderCommand2.ID = "workbench.action.files.openLocalFolder";
  OpenLocalFolderCommand2.LABEL = localize(12676, null);
  function handler() {
    return (accessor) => {
      const dialogService = accessor.get($1v);
      return dialogService.pickFolderAndOpen({ forceNewWindow: false, availableFileSystems: [Schemas.file] });
    };
  }
  OpenLocalFolderCommand2.handler = handler;
})(OpenLocalFolderCommand || (OpenLocalFolderCommand = {}));
var OpenLocalFileFolderCommand;
(function(OpenLocalFileFolderCommand2) {
  OpenLocalFileFolderCommand2.ID = "workbench.action.files.openLocalFileFolder";
  OpenLocalFileFolderCommand2.LABEL = localize(12677, null);
  function handler() {
    return (accessor) => {
      const dialogService = accessor.get($1v);
      return dialogService.pickFileFolderAndOpen({ forceNewWindow: false, availableFileSystems: [Schemas.file] });
    };
  }
  OpenLocalFileFolderCommand2.handler = handler;
})(OpenLocalFileFolderCommand || (OpenLocalFileFolderCommand = {}));
var UpdateResult;
(function(UpdateResult2) {
  UpdateResult2[UpdateResult2["Updated"] = 0] = "Updated";
  UpdateResult2[UpdateResult2["UpdatedWithTrailing"] = 1] = "UpdatedWithTrailing";
  UpdateResult2[UpdateResult2["Updating"] = 2] = "Updating";
  UpdateResult2[UpdateResult2["NotUpdated"] = 3] = "NotUpdated";
  UpdateResult2[UpdateResult2["InvalidPath"] = 4] = "InvalidPath";
})(UpdateResult || (UpdateResult = {}));
var $1nc = new $nn("remoteFileDialogVisible", false);
var $2nc = class $2nc2 extends $3c {
  constructor(M, N, O, P, Q, R, S, U, W, X, Y, Z, contextKeyService, $149) {
    super();
    this.M = M;
    this.N = N;
    this.O = O;
    this.P = P;
    this.Q = Q;
    this.R = R;
    this.S = S;
    this.U = U;
    this.W = W;
    this.X = X;
    this.Y = Y;
    this.Z = Z;
    this.$ = $149;
    this.f = false;
    this.g = true;
    this.h = false;
    this.n = false;
    this.w = "";
    this.y = "";
    this.F = false;
    this.I = "/";
    this.J = this.B(new $ze());
    this.m = this.W.remoteAuthority;
    this.u = $1nc.bindTo(contextKeyService);
    this.t = this.Y.defaultUriScheme;
  }
  set busy(busy) {
    if (this.c.busy !== busy) {
      this.c.busy = busy;
      this.J.fire(busy);
    }
  }
  get busy() {
    return this.c.busy;
  }
  async showOpenDialog(options3 = {}) {
    this.t = this.cb(options3.availableFileSystems, options3.defaultUri);
    this.C = await this.eb();
    this.D = await this.eb(true);
    const newOptions = this.ab(options3);
    if (!newOptions) {
      return Promise.resolve(void 0);
    }
    this.a = newOptions;
    return this.fb();
  }
  async showSaveDialog(options3) {
    this.t = this.cb(options3.availableFileSystems, options3.defaultUri);
    this.C = await this.eb();
    this.D = await this.eb(true);
    this.n = true;
    const newOptions = this.ab(options3, true);
    if (!newOptions) {
      return Promise.resolve(void 0);
    }
    this.a = newOptions;
    this.a.canSelectFolders = true;
    this.a.canSelectFiles = true;
    return new Promise((resolve) => {
      this.fb(true).then((folderUri) => {
        resolve(folderUri);
      });
    });
  }
  ab(options3, isSave = false) {
    let defaultUri = void 0;
    let filename = void 0;
    if (options3.defaultUri) {
      defaultUri = this.t === options3.defaultUri.scheme ? options3.defaultUri : void 0;
      filename = isSave ? $sh(options3.defaultUri) : void 0;
    }
    if (!defaultUri) {
      defaultUri = this.C;
      if (filename) {
        defaultUri = $vh(defaultUri, filename);
      }
    }
    if (this.t !== Schemas.file && !this.M.hasProvider(defaultUri)) {
      this.Q.info(localize(12678, null, defaultUri.toString()));
      return void 0;
    }
    const newOptions = $Lv(options3);
    newOptions.defaultUri = defaultUri;
    return newOptions;
  }
  bb(path, hintUri) {
    if (!path.startsWith("\\\\")) {
      path = path.replace(/\\/g, "/");
    }
    const uri = this.t === Schemas.file ? URI.file(path) : URI.from({ scheme: this.t, path, query: hintUri?.query, fragment: hintUri?.fragment });
    const authority = uri.scheme === Schemas.file ? void 0 : this.m ?? hintUri?.authority;
    return $Fh(
      uri,
      authority,
      // If there is a remote authority, then we should use the system's default URI as the local scheme.
      // If there is *no* remote authority, then we should use the default scheme for this dialog as that is already local.
      authority ? this.Y.defaultUriScheme : uri.scheme
    );
  }
  cb(available, defaultUri) {
    if (available && available.length > 0) {
      if (defaultUri && available.indexOf(defaultUri.scheme) >= 0) {
        return defaultUri.scheme;
      }
      return available[0];
    } else if (defaultUri) {
      return defaultUri.scheme;
    }
    return Schemas.file;
  }
  async db() {
    if (this.H === void 0) {
      this.H = await this.X.getEnvironment();
    }
    return this.H;
  }
  eb(trueHome = false) {
    return trueHome ? this.Y.userHome({ preferLocal: this.t === Schemas.file }) : this.R.preferredHome(this.t);
  }
  async fb(isSave = false) {
    this.h = !!this.a.canSelectFolders;
    this.g = !!this.a.canSelectFiles;
    this.I = this.O.getSeparator(this.t, this.m);
    this.f = false;
    this.F = await this.Cb();
    let homedir = this.a.defaultUri ? this.a.defaultUri : this.P.getWorkspace().folders[0].uri;
    let stat;
    const ext = $th(homedir);
    if (this.a.defaultUri) {
      try {
        stat = await this.M.stat(this.a.defaultUri);
      } catch (e) {
      }
      if (!stat || !stat.isDirectory) {
        homedir = $uh(this.a.defaultUri);
        this.r = $sh(this.a.defaultUri);
      }
    }
    return new Promise((resolve) => {
      this.c = this.B(this.N.createQuickPick());
      this.busy = true;
      this.c.matchOnLabel = false;
      this.c.sortByLabel = false;
      this.c.ignoreFocusOut = true;
      this.c.ok = true;
      if (isSave && this.W.isEnabledFileDownloads || !isSave && this.W.isEnabledFileUploads) {
        if (this.t !== Schemas.file && this.a && this.a.availableFileSystems && this.a.availableFileSystems.length > 1 && this.a.availableFileSystems.indexOf(Schemas.file) > -1) {
          this.c.customButton = true;
          this.c.customLabel = localize(12679, null);
          let action;
          if (isSave) {
            action = SaveLocalFileCommand;
          } else {
            action = this.g ? this.h ? OpenLocalFileFolderCommand : OpenLocalFileCommand : OpenLocalFolderCommand;
          }
          const keybinding = this.Z.lookupKeybinding(action.ID);
          if (keybinding) {
            const label3 = keybinding.getLabel();
            if (label3) {
              this.c.customHover = $wf("{0} ({1})", action.LABEL, label3);
            }
          }
        }
      }
      let isResolving = 0;
      let isAcceptHandled = false;
      this.b = $uh(homedir);
      this.w = "";
      this.y = "";
      this.c.title = this.a.title;
      this.c.value = this.Ab(this.b, true);
      this.c.valueSelection = [this.c.value.length, this.c.value.length];
      const doResolve = (uri) => {
        if (uri) {
          uri = $Dh(uri, this.I);
          uri = $Ch(uri);
        }
        resolve(uri);
        this.u.set(false);
        this.dispose();
      };
      this.B(this.c.onDidCustom(() => {
        if (isAcceptHandled || this.busy) {
          return;
        }
        isAcceptHandled = true;
        isResolving++;
        if (this.a.availableFileSystems && this.a.availableFileSystems.length > 1) {
          this.a.availableFileSystems = this.a.availableFileSystems.slice(1);
        }
        this.c.hide();
        if (isSave) {
          return this.R.showSaveDialog(this.a).then((result) => {
            doResolve(result);
          });
        } else {
          return this.R.showOpenDialog(this.a).then((result) => {
            doResolve(result ? result[0] : void 0);
          });
        }
      }));
      const handleAccept = () => {
        if (this.busy) {
          this.J.event((busy) => {
            if (!busy) {
              handleAccept();
            }
          });
          return;
        } else if (isAcceptHandled) {
          return;
        }
        isAcceptHandled = true;
        isResolving++;
        this.mb().then((resolveValue) => {
          if (resolveValue) {
            this.c.hide();
            doResolve(resolveValue);
          } else if (this.f) {
            doResolve(void 0);
          } else {
            isResolving--;
            isAcceptHandled = false;
          }
        });
      };
      this.B(this.c.onDidAccept((_) => {
        handleAccept();
      }));
      this.B(this.c.onDidChangeActive((i2) => {
        isAcceptHandled = false;
        if (i2.length === 1 && this.jb()) {
          this.c.validationMessage = void 0;
          const userPath = this.kb();
          if (!$1f(this.c.value.substring(0, userPath.length), userPath)) {
            this.c.valueSelection = [0, this.c.value.length];
            this.ub(userPath, userPath);
          }
          this.tb(userPath, this.w, i2[0], true);
        }
      }));
      this.B(this.c.onDidChangeValue(async (value) => {
        return this.gb(value);
      }));
      this.B(this.c.onDidHide(() => {
        this.f = true;
        if (isResolving === 0) {
          doResolve(void 0);
        }
      }));
      this.c.show();
      this.u.set(true);
      this.zb(homedir, true, this.r).then(() => {
        if (this.r) {
          this.c.valueSelection = [this.c.value.length - this.r.length, this.c.value.length - ext.length];
        } else {
          this.c.valueSelection = [this.c.value.length, this.c.value.length];
        }
        this.busy = false;
      });
    });
  }
  dispose() {
    super.dispose();
  }
  async gb(value) {
    try {
      if (this.ib()) {
        if (!$1f(value, this.kb()) && !this.hb(value)) {
          this.c.validationMessage = void 0;
          const filePickBoxUri = this.lb();
          let updated = UpdateResult.NotUpdated;
          if (!$nh.isEqual(this.b, filePickBoxUri)) {
            updated = await this.qb(value, filePickBoxUri);
          }
          if (updated === UpdateResult.NotUpdated || updated === UpdateResult.UpdatedWithTrailing) {
            this.sb(value);
          }
        } else {
          this.c.activeItems = [];
          this.w = "";
        }
      }
    } catch {
    }
  }
  hb(value) {
    return this.G && value.length > this.G.length && $1f(value.substring(0, this.G.length), this.G);
  }
  ib() {
    if ($1f(this.c.value, this.Bb(this.b, this.w + this.y))) {
      return false;
    }
    return true;
  }
  jb() {
    if (this.z === (this.c.activeItems ? this.c.activeItems[0] : void 0)) {
      return false;
    }
    return true;
  }
  kb() {
    const currentFolderPath = this.Ab(this.b);
    if ($1f(this.c.value.substr(0, this.w.length), this.w)) {
      if ($1f(this.c.value.substr(0, currentFolderPath.length), currentFolderPath)) {
        return currentFolderPath;
      } else {
        return this.w;
      }
    } else {
      return this.Bb(this.b, this.w);
    }
  }
  lb() {
    const directUri = this.bb(this.c.value.trimRight(), this.b);
    const currentPath = this.Ab(this.b);
    if ($1f(this.c.value, currentPath)) {
      return this.b;
    }
    const currentDisplayUri = this.bb(currentPath, this.b);
    const relativePath = $xh(currentDisplayUri, directUri);
    const isSameRoot = this.c.value.length > 1 && currentPath.length > 1 ? $1f(this.c.value.substr(0, 2), currentPath.substr(0, 2)) : false;
    if (relativePath && isSameRoot) {
      let path = $vh(this.b, relativePath);
      const directBasename = $sh(directUri);
      if (directBasename === "." || directBasename === "..") {
        path = this.bb(this.Bb(path, directBasename), this.b);
      }
      return $Bh(directUri) ? $Dh(path) : path;
    } else {
      return directUri;
    }
  }
  async mb() {
    this.busy = true;
    if (this.c.activeItems.length === 1) {
      const item = this.c.selectedItems[0];
      if (item.isFolder) {
        if (this.r) {
          await this.zb(item.uri, true, this.r);
        } else {
          const newPath = this.Ab(item.uri);
          if ($2f(newPath, this.c.value) && $1f(item.label, $sh(item.uri))) {
            this.c.valueSelection = [this.Ab(this.b).length, this.c.value.length];
            this.ub(newPath, this.Eb(item.uri));
          } else if (item.label === ".." && $2f(this.c.value, newPath)) {
            this.c.valueSelection = [newPath.length, this.c.value.length];
            this.ub(newPath, "");
          } else {
            await this.zb(item.uri, true);
          }
        }
        this.c.busy = false;
        return;
      }
    } else {
      if (await this.qb(this.c.value, this.lb()) !== UpdateResult.NotUpdated) {
        this.c.busy = false;
        return;
      }
    }
    let resolveValue;
    if (this.c.activeItems.length === 0) {
      resolveValue = this.lb();
    } else if (this.c.activeItems.length === 1) {
      resolveValue = this.c.selectedItems[0].uri;
    }
    if (resolveValue) {
      resolveValue = this.vb(resolveValue);
    }
    if (await this.yb(resolveValue)) {
      this.busy = false;
      return resolveValue;
    }
    this.busy = false;
    return void 0;
  }
  nb(value) {
    let lastDir = value;
    let dir = $uh(value);
    while (!$oh(lastDir, dir)) {
      lastDir = dir;
      dir = $uh(dir);
    }
    return dir;
  }
  ob(value) {
    const home2 = this.D;
    if (value.length > 0 && value[0] === "~") {
      return $vh(home2, value.substring(1));
    }
    return this.bb(value);
  }
  pb(uri, stat) {
    if (stat.isDirectory) {
      if (!this.Db(uri.path)) {
        return $Dh(uri);
      }
    }
    return uri;
  }
  async qb(value, valueUri) {
    if (value.length > 0 && value[0] === "~") {
      const newDir = this.ob(value);
      return await this.zb(newDir, true) ? UpdateResult.UpdatedWithTrailing : UpdateResult.Updated;
    } else if (value === "\\") {
      valueUri = this.nb(this.b);
      value = this.Ab(valueUri);
      return await this.zb(valueUri, true) ? UpdateResult.UpdatedWithTrailing : UpdateResult.Updated;
    } else {
      const newFolderIsOldFolder = $nh.isEqual(this.b, valueUri);
      const newFolderIsSubFolder = $nh.isEqual(this.b, $uh(valueUri));
      const newFolderIsParent = $nh.isEqualOrParent(this.b, $uh(valueUri));
      const newFolderIsUnrelated = !newFolderIsParent && !newFolderIsSubFolder;
      if (!newFolderIsOldFolder && (this.Db(value) || newFolderIsParent || newFolderIsUnrelated)) {
        let stat;
        try {
          stat = await this.M.stat(valueUri);
        } catch (e) {
        }
        if (stat && stat.isDirectory && $sh(valueUri) !== "." && this.Db(value)) {
          valueUri = this.pb(valueUri, stat);
          return await this.zb(valueUri) ? UpdateResult.UpdatedWithTrailing : UpdateResult.Updated;
        } else if (this.Db(value)) {
          this.c.validationMessage = localize(12680, null);
          this.G = value;
          return UpdateResult.InvalidPath;
        } else {
          let inputUriDirname = $uh(valueUri);
          const currentFolderWithoutSep = $Ch($Dh(this.b));
          const inputUriDirnameWithoutSep = $Ch($Dh(inputUriDirname));
          if (!$nh.isEqual(currentFolderWithoutSep, inputUriDirnameWithoutSep) && (!/^[a-zA-Z]:$/.test(this.c.value) || !$1f(this.Ab(this.b).substring(0, this.c.value.length), this.c.value))) {
            let statWithoutTrailing;
            try {
              statWithoutTrailing = await this.M.stat(inputUriDirname);
            } catch (e) {
            }
            if (statWithoutTrailing && statWithoutTrailing.isDirectory) {
              this.G = void 0;
              inputUriDirname = this.pb(inputUriDirname, statWithoutTrailing);
              return await this.zb(inputUriDirname, false, $sh(valueUri)) ? UpdateResult.UpdatedWithTrailing : UpdateResult.Updated;
            }
          }
        }
      }
    }
    this.G = void 0;
    return UpdateResult.NotUpdated;
  }
  rb(value) {
    const ext = $th(value);
    if (this.r && ext) {
      this.r = $sh(value);
    }
  }
  sb(value) {
    value = this.Ab(this.ob(value));
    const asUri = this.bb(value);
    const inputBasename = $sh(asUri);
    const userPath = this.kb();
    const pathsEqual = $1f(userPath, value.substring(0, userPath.length)) || $1f(value, userPath.substring(0, value.length));
    if (pathsEqual) {
      let hasMatch = false;
      for (let i2 = 0; i2 < this.c.items.length; i2++) {
        const item = this.c.items[i2];
        if (this.tb(value, inputBasename, item)) {
          hasMatch = true;
          break;
        }
      }
      if (!hasMatch) {
        const userBasename = inputBasename.length >= 2 ? userPath.substring(userPath.length - inputBasename.length + 2) : "";
        this.w = userBasename === inputBasename ? inputBasename : "";
        this.y = "";
        this.c.activeItems = [];
        this.rb(asUri);
      }
    } else {
      this.w = inputBasename;
      this.y = "";
      this.c.activeItems = [];
      this.rb(asUri);
    }
  }
  tb(startingValue, startingBasename, quickPickItem, force = false) {
    if (this.busy) {
      this.w = startingBasename;
      this.y = "";
      return false;
    }
    const itemBasename = quickPickItem.label;
    if (itemBasename === "..") {
      this.w = "";
      this.y = "";
      this.z = quickPickItem;
      if (force) {
        $Pj().execCommand("insertText", false, "");
      }
      return false;
    } else if (!force && itemBasename.length >= startingBasename.length && $1f(itemBasename.substr(0, startingBasename.length), startingBasename)) {
      this.w = startingBasename;
      this.z = quickPickItem;
      this.y = "";
      if (quickPickItem.isFolder || !this.r) {
        this.c.activeItems = [quickPickItem];
      } else {
        this.c.activeItems = [];
      }
      return true;
    } else if (force && !$1f(this.Eb(quickPickItem.uri), this.w + this.y)) {
      this.w = "";
      if (!this.$.isScreenReaderOptimized()) {
        this.y = this.wb(itemBasename);
      }
      this.z = quickPickItem;
      if (!this.$.isScreenReaderOptimized()) {
        this.c.valueSelection = [this.Ab(this.b, true).length, this.c.value.length];
        this.ub(this.Bb(this.b, this.y), this.y);
        this.c.valueSelection = [this.c.value.length - this.y.length, this.c.value.length];
      }
      return true;
    } else {
      this.w = startingBasename;
      this.y = "";
      return false;
    }
  }
  ub(wholeValue, insertText) {
    if (this.c.inputHasFocus()) {
      $Pj().execCommand("insertText", false, insertText);
      if (this.c.value !== wholeValue) {
        this.c.value = wholeValue;
        this.gb(wholeValue);
      }
    } else {
      this.c.value = wholeValue;
      this.gb(wholeValue);
    }
  }
  vb(uri) {
    let result = uri;
    if (this.n && this.a.filters && this.a.filters.length > 0 && !$Bh(uri)) {
      let hasExt = false;
      const currentExt = $th(uri).substr(1);
      for (let i2 = 0; i2 < this.a.filters.length; i2++) {
        for (let j = 0; j < this.a.filters[i2].extensions.length; j++) {
          if (this.a.filters[i2].extensions[j] === "*" || this.a.filters[i2].extensions[j] === currentExt) {
            hasExt = true;
            break;
          }
        }
        if (hasExt) {
          break;
        }
      }
      if (!hasExt) {
        result = $vh($uh(uri), $sh(uri) + "." + this.a.filters[0].extensions[0]);
      }
    }
    return result;
  }
  wb(path) {
    return path.length > 1 && this.Db(path) ? path.substr(0, path.length - 1) : path;
  }
  xb(uri, message) {
    const disposableStore = new $2c();
    const prompt = disposableStore.add(this.N.createQuickPick());
    prompt.title = message;
    prompt.ignoreFocusOut = true;
    prompt.ok = true;
    prompt.customButton = true;
    prompt.customLabel = localize(12681, null);
    prompt.value = this.Ab(uri);
    let isResolving = false;
    return new Promise((resolve) => {
      disposableStore.add(prompt.onDidAccept(() => {
        isResolving = true;
        prompt.hide();
        resolve(true);
      }));
      disposableStore.add(prompt.onDidHide(() => {
        if (!isResolving) {
          resolve(false);
        }
        this.c.show();
        this.f = false;
        disposableStore.dispose();
      }));
      disposableStore.add(prompt.onDidChangeValue(() => {
        prompt.hide();
      }));
      disposableStore.add(prompt.onDidCustom(() => {
        prompt.hide();
      }));
      prompt.show();
    });
  }
  async yb(uri) {
    if (uri === void 0) {
      this.c.validationMessage = localize(12682, null);
      return Promise.resolve(false);
    }
    let stat;
    let statDirname;
    try {
      statDirname = await this.M.stat($uh(uri));
      stat = await this.M.stat(uri);
    } catch (e) {
    }
    if (this.n) {
      if (stat && stat.isDirectory) {
        this.c.validationMessage = localize(12683, null);
        return Promise.resolve(false);
      } else if (stat) {
        const message = localize(12684, null, $sh(uri));
        return this.xb(uri, message);
      } else if (!$Xg($sh(uri), this.F)) {
        this.c.validationMessage = localize(12685, null);
        return Promise.resolve(false);
      } else if (!statDirname) {
        const message = localize(12686, null, $sh($uh(uri)));
        return this.xb(uri, message);
      } else if (!statDirname.isDirectory) {
        this.c.validationMessage = localize(12687, null);
        return Promise.resolve(false);
      } else if (statDirname.readonly) {
        this.c.validationMessage = localize(12688, null);
        return Promise.resolve(false);
      }
    } else {
      if (!stat) {
        this.c.validationMessage = localize(12689, null);
        return Promise.resolve(false);
      } else if (uri.path === "/" && this.F) {
        this.c.validationMessage = localize(12690, null);
        return Promise.resolve(false);
      } else if (stat.isDirectory && !this.h) {
        this.c.validationMessage = localize(12691, null);
        return Promise.resolve(false);
      } else if (!stat.isDirectory && !this.g) {
        this.c.validationMessage = localize(12692, null);
        return Promise.resolve(false);
      }
    }
    return Promise.resolve(true);
  }
  // Returns true if there is a file at the end of the URI.
  async zb(newFolder, force = false, trailing) {
    this.busy = true;
    this.y = "";
    const isSave = !!trailing;
    let result = false;
    const updatingPromise = $Hh(async (token) => {
      let folderStat;
      try {
        folderStat = await this.M.resolve(newFolder);
        if (!folderStat.isDirectory) {
          trailing = $sh(newFolder);
          newFolder = $uh(newFolder);
          folderStat = void 0;
          result = true;
        }
      } catch (e) {
      }
      const newValue = trailing ? this.Bb(newFolder, trailing) : this.Ab(newFolder, true);
      this.b = this.Db(newFolder.path) ? newFolder : $Dh(newFolder, this.I);
      this.w = trailing ? trailing : "";
      return this.Gb(folderStat, this.b, token).then((items) => {
        if (token.isCancellationRequested) {
          this.busy = false;
          return false;
        }
        this.c.itemActivation = ItemActivation.NONE;
        this.c.items = items;
        if (!$1f(this.c.value, newValue) && force) {
          this.c.valueSelection = [0, this.c.value.length];
          this.ub(newValue, newValue);
        }
        if (force && trailing && isSave) {
          this.c.valueSelection = [this.c.value.length - trailing.length, this.c.value.length - trailing.length];
        } else if (!trailing) {
          this.c.valueSelection = [this.c.value.length, this.c.value.length];
        }
        this.busy = false;
        this.L = void 0;
        return result;
      });
    });
    if (this.L !== void 0) {
      this.L.cancel();
    }
    this.L = updatingPromise;
    return updatingPromise;
  }
  Ab(uri, endWithSeparator = false) {
    let result = $1t(uri.fsPath, this.F).replace(/\n/g, "");
    if (this.I === "/") {
      result = result.replace(/\\/g, this.I);
    } else {
      result = result.replace(/\//g, this.I);
    }
    if (endWithSeparator && !this.Db(result)) {
      result = result + this.I;
    }
    return result;
  }
  Bb(uri, additional) {
    if (additional === ".." || additional === ".") {
      const basePath = this.Ab(uri, true);
      return basePath + additional;
    } else {
      return this.Ab($vh(uri, additional));
    }
  }
  async Cb() {
    let isWindowsOS = $l;
    const env3 = await this.db();
    if (env3) {
      isWindowsOS = env3.os === 1;
    }
    return isWindowsOS;
  }
  Db(s) {
    return /[\/\\]$/.test(s);
  }
  Eb(fullPath) {
    const child = this.Ab(fullPath, true);
    const parent = this.Ab($uh(fullPath), true);
    return child.substring(parent.length);
  }
  async Fb(currFolder) {
    const fileRepresentationCurr = this.b.with({ scheme: Schemas.file, authority: "" });
    const fileRepresentationParent = $uh(fileRepresentationCurr);
    if (!$oh(fileRepresentationCurr, fileRepresentationParent)) {
      const parentFolder = $uh(currFolder);
      if (await this.M.exists(parentFolder)) {
        return { label: "..", uri: $Dh(parentFolder, this.I), isFolder: true };
      }
    }
    return void 0;
  }
  async Gb(folder, currentFolder, token) {
    const result = [];
    const backDir = await this.Fb(currentFolder);
    try {
      if (!folder) {
        folder = await this.M.resolve(currentFolder);
      }
      const items = folder.children ? await Promise.all(folder.children.map((child) => this.Ib(child, currentFolder, token))) : [];
      for (const item of items) {
        if (item) {
          result.push(item);
        }
      }
    } catch (e) {
      console.log(e);
    }
    if (token.isCancellationRequested) {
      return [];
    }
    const sorted = result.sort((i1, i2) => {
      if (i1.isFolder !== i2.isFolder) {
        return i1.isFolder ? -1 : 1;
      }
      const trimmed1 = this.Db(i1.label) ? i1.label.substr(0, i1.label.length - 1) : i1.label;
      const trimmed2 = this.Db(i2.label) ? i2.label.substr(0, i2.label.length - 1) : i2.label;
      return trimmed1.localeCompare(trimmed2);
    });
    if (backDir) {
      sorted.unshift(backDir);
    }
    return sorted;
  }
  Hb(file) {
    if (this.a.filters) {
      for (let i2 = 0; i2 < this.a.filters.length; i2++) {
        for (let j = 0; j < this.a.filters[i2].extensions.length; j++) {
          const testExt = this.a.filters[i2].extensions[j];
          if (testExt === "*" || file.path.endsWith("." + testExt)) {
            return true;
          }
        }
      }
      return false;
    }
    return true;
  }
  async Ib(stat, parent, token) {
    if (token.isCancellationRequested) {
      return void 0;
    }
    let fullPath = $vh(parent, stat.name);
    if (stat.isDirectory) {
      const filename = $sh(fullPath);
      fullPath = $Dh(fullPath, this.I);
      return { label: filename, uri: fullPath, isFolder: true, iconClasses: $gdb(this.S, this.U, fullPath || void 0, FileKind.FOLDER) };
    } else if (!stat.isDirectory && this.g && this.Hb(fullPath)) {
      return { label: stat.name, uri: fullPath, isFolder: false, iconClasses: $gdb(this.S, this.U, fullPath || void 0) };
    }
    return void 0;
  }
};
$2nc = __decorate([
  __param(0, $km),
  __param(1, $1M),
  __param(2, $ZI),
  __param(3, $Zk),
  __param(4, $PJ),
  __param(5, $1v),
  __param(6, $sG),
  __param(7, $1E),
  __param(8, $M4),
  __param(9, $RL),
  __param(10, $aT),
  __param(11, $Ty),
  __param(12, $on),
  __param(13, $ND)
], $2nc);

// out-build/vs/workbench/services/dialogs/browser/abstractFileDialogService.js
var $3nc = class $3nc2 {
  constructor(a, b, c, d, f, g, h3, i2, j, k, l, m, n, o, p, q, r2) {
    this.a = a;
    this.b = b;
    this.c = c;
    this.d = d;
    this.f = f;
    this.g = g;
    this.h = h3;
    this.i = i2;
    this.j = j;
    this.k = k;
    this.l = l;
    this.m = m;
    this.n = n;
    this.o = o;
    this.p = p;
    this.q = q;
    this.r = r2;
  }
  async defaultFilePath(schemeFilter = this.G(), authorityFilter = this.H()) {
    let candidate = this.c.getLastActiveFile(schemeFilter, authorityFilter);
    if (!candidate) {
      candidate = this.c.getLastActiveWorkspaceRoot(schemeFilter, authorityFilter);
    } else {
      candidate = $uh(candidate);
    }
    if (!candidate) {
      candidate = await this.preferredHome(schemeFilter);
    }
    return candidate;
  }
  async defaultFolderPath(schemeFilter = this.G(), authorityFilter = this.H()) {
    let candidate = this.c.getLastActiveWorkspaceRoot(schemeFilter, authorityFilter);
    if (!candidate) {
      candidate = this.c.getLastActiveFile(schemeFilter, authorityFilter);
    }
    if (!candidate) {
      return this.preferredHome(schemeFilter);
    }
    return $uh(candidate);
  }
  async preferredHome(schemeFilter = this.G()) {
    const preferLocal = schemeFilter === Schemas.file;
    const preferredHomeConfig = this.g.inspect("files.dialog.defaultPath");
    const preferredHomeCandidate = preferLocal ? preferredHomeConfig.userLocalValue : preferredHomeConfig.userRemoteValue;
    if (preferredHomeCandidate) {
      const isPreferredHomeCandidateAbsolute = preferLocal ? $mc(preferredHomeCandidate) : (await this.n.path).isAbsolute(preferredHomeCandidate);
      if (isPreferredHomeCandidateAbsolute) {
        const preferredHomeNormalized = preferLocal ? $lc(preferredHomeCandidate) : (await this.n.path).normalize(preferredHomeCandidate);
        const preferredHome = $Fh(await this.n.fileURI(preferredHomeNormalized), this.d.remoteAuthority, this.n.defaultUriScheme);
        if (await this.h.exists(preferredHome)) {
          return preferredHome;
        }
      }
    }
    return this.n.userHome({ preferLocal });
  }
  async defaultWorkspacePath(schemeFilter = this.G()) {
    let defaultWorkspacePath;
    if (this.b.getWorkbenchState() === 3) {
      const configuration2 = this.b.getWorkspace().configuration;
      if (configuration2?.scheme === schemeFilter && $il(configuration2, this.d) && !$fl(configuration2)) {
        defaultWorkspacePath = $uh(configuration2);
      }
    }
    if (!defaultWorkspacePath) {
      defaultWorkspacePath = await this.defaultFilePath(schemeFilter);
    }
    return defaultWorkspacePath;
  }
  async showSaveConfirm(fileNamesOrResources) {
    if (this.s()) {
      this.r.trace("FileDialogService: refused to show save confirmation dialog in tests.");
      return 1;
    }
    return this.t(fileNamesOrResources);
  }
  s() {
    if (this.d.isExtensionDevelopment && this.d.extensionTestsLocationURI) {
      return true;
    }
    return !!this.d.enableSmokeTestDriver;
  }
  async t(fileNamesOrResources) {
    if (fileNamesOrResources.length === 0) {
      return 1;
    }
    let message;
    let detail2 = localize(12651, null);
    if (fileNamesOrResources.length === 1) {
      message = localize(12652, null, typeof fileNamesOrResources[0] === "string" ? fileNamesOrResources[0] : $sh(fileNamesOrResources[0]));
    } else {
      message = localize(12653, null, fileNamesOrResources.length);
      detail2 = $2v(fileNamesOrResources) + "\n" + detail2;
    }
    const { result } = await this.j.prompt({
      type: severity_default.Warning,
      message,
      detail: detail2,
      buttons: [
        {
          label: fileNamesOrResources.length > 1 ? localize(12654, null) : localize(12655, null),
          run: () => 0
          /* ConfirmResult.SAVE */
        },
        {
          label: localize(12656, null),
          run: () => 1
          /* ConfirmResult.DONT_SAVE */
        }
      ],
      cancelButton: {
        run: () => 2
        /* ConfirmResult.CANCEL */
      }
    });
    return result;
  }
  u(schema9, _isFolder) {
    return schema9 === Schemas.untitled ? [Schemas.file] : schema9 !== Schemas.file ? [schema9, Schemas.file] : [schema9];
  }
  async v(schema9, options3, preferNewWindow) {
    const title = localize(12657, null);
    const availableFileSystems = this.u(schema9);
    const uri = await this.E({ canSelectFiles: true, canSelectFolders: true, canSelectMany: false, defaultUri: options3.defaultUri, title, availableFileSystems });
    if (uri) {
      const stat = await this.h.stat(uri);
      const toOpen = stat.isDirectory ? { folderUri: uri } : { fileUri: uri };
      if (!$ys(toOpen) && $As(toOpen)) {
        this.x(toOpen.fileUri);
      }
      if (stat.isDirectory || options3.forceNewWindow || preferNewWindow) {
        await this.a.openWindow([toOpen], { forceNewWindow: options3.forceNewWindow, remoteAuthority: options3.remoteAuthority });
      } else {
        await this.p.openEditors([{ resource: uri, options: { source: EditorOpenSource.USER, pinned: true } }], void 0, { validateTrust: true });
      }
    }
  }
  async w(schema9, options3, preferNewWindow) {
    const title = localize(12658, null);
    const availableFileSystems = this.u(schema9);
    const uri = await this.E({ canSelectFiles: true, canSelectFolders: false, canSelectMany: false, defaultUri: options3.defaultUri, title, availableFileSystems });
    if (uri) {
      this.x(uri);
      if (options3.forceNewWindow || preferNewWindow) {
        await this.a.openWindow([{ fileUri: uri }], { forceNewWindow: options3.forceNewWindow, remoteAuthority: options3.remoteAuthority });
      } else {
        await this.p.openEditors([{ resource: uri, options: { source: EditorOpenSource.USER, pinned: true } }], void 0, { validateTrust: true });
      }
    }
  }
  x(uri) {
    this.l.addRecentlyOpened([{ fileUri: uri, label: this.m.getUriLabel(uri) }]);
  }
  async y(schema9, options3) {
    const title = localize(12659, null);
    const availableFileSystems = this.u(schema9, true);
    const uri = await this.E({ canSelectFiles: false, canSelectFolders: true, canSelectMany: false, defaultUri: options3.defaultUri, title, availableFileSystems });
    if (uri) {
      return this.a.openWindow([{ folderUri: uri }], { forceNewWindow: options3.forceNewWindow, remoteAuthority: options3.remoteAuthority });
    }
  }
  async z(schema9, options3) {
    const title = localize(12660, null);
    const filters2 = [{ name: localize(12661, null), extensions: [$al] }];
    const availableFileSystems = this.u(schema9, true);
    const uri = await this.E({ canSelectFiles: true, canSelectFolders: false, canSelectMany: false, defaultUri: options3.defaultUri, title, filters: filters2, availableFileSystems });
    if (uri) {
      return this.a.openWindow([{ workspaceUri: uri }], { forceNewWindow: options3.forceNewWindow, remoteAuthority: options3.remoteAuthority });
    }
  }
  async A(schema9, options3) {
    if (!options3.availableFileSystems) {
      options3.availableFileSystems = this.u(schema9);
    }
    options3.title = localize(12662, null);
    const uri = await this.F(options3);
    if (uri) {
      this.x(uri);
    }
    return uri;
  }
  async B(schema9, options3) {
    if (!options3.availableFileSystems) {
      options3.availableFileSystems = this.u(schema9);
    }
    return this.F(options3);
  }
  async C(schema9, options3) {
    if (!options3.availableFileSystems) {
      options3.availableFileSystems = this.u(schema9, options3.canSelectFolders);
    }
    const uri = await this.E(options3);
    return uri ? [uri] : void 0;
  }
  D() {
    return this.f.createInstance($2nc);
  }
  E(options3) {
    return this.D().showOpenDialog(options3);
  }
  F(options3) {
    return this.D().showSaveDialog(options3);
  }
  G(defaultUriScheme) {
    return defaultUriScheme ?? this.n.defaultUriScheme;
  }
  H() {
    return this.d.remoteAuthority;
  }
  I(options3) {
    return options3.availableFileSystems && options3.availableFileSystems[0] || this.G(options3.defaultUri?.scheme);
  }
  J(options3) {
    if (options3.availableFileSystems && options3.availableFileSystems.length > 0) {
      return options3.availableFileSystems;
    }
    const availableFileSystems = [Schemas.file];
    if (this.d.remoteAuthority) {
      availableFileSystems.unshift(Schemas.vscodeRemote);
    }
    return availableFileSystems;
  }
  K(defaultUri, availableFileSystems) {
    const options3 = {
      defaultUri,
      title: localize(12663, null),
      availableFileSystems
    };
    const ext = defaultUri ? $th(defaultUri) : void 0;
    let matchingFilter;
    const registeredLanguageNames = this.k.getSortedRegisteredLanguageNames();
    const registeredLanguageFilters = $Mb(registeredLanguageNames.map(({ languageName, languageId }) => {
      const extensions = this.k.getExtensions(languageId);
      if (!extensions.length) {
        return null;
      }
      const filter = { name: languageName, extensions: $Rb(extensions).slice(0, 10).map((e) => $Ef(e, ".")) };
      const extOrPlaintext = ext || $LF;
      if (!matchingFilter && extensions.includes(extOrPlaintext)) {
        matchingFilter = filter;
        const trimmedExt = $Ef(extOrPlaintext, ".");
        if (!filter.extensions.includes(trimmedExt)) {
          filter.extensions.unshift(trimmedExt);
        }
        return null;
      }
      return filter;
    }));
    if (!matchingFilter && ext) {
      matchingFilter = { name: $Ef(ext, ".").toUpperCase(), extensions: [$Ef(ext, ".")] };
    }
    options3.filters = $Mb([
      { name: localize(12664, null), extensions: ["*"] },
      matchingFilter,
      ...registeredLanguageFilters,
      { name: localize(12665, null), extensions: [""] }
    ]);
    return options3;
  }
};
$3nc = __decorate([
  __param(0, $S4),
  __param(1, $Zk),
  __param(2, $tY),
  __param(3, $US),
  __param(4, $Pk),
  __param(5, $kl),
  __param(6, $km),
  __param(7, $O4),
  __param(8, $Yv),
  __param(9, $1E),
  __param(10, $2w),
  __param(11, $ZI),
  __param(12, $aT),
  __param(13, $sn),
  __param(14, $mJ),
  __param(15, $U5),
  __param(16, $wn)
], $3nc);

// out-build/vs/workbench/services/dialogs/browser/fileDialogService.js
var $4nc = class extends $3nc {
  get L() {
    return this.h.getProvider(Schemas.file);
  }
  async pickFileFolderAndOpen(options3) {
    const schema9 = this.I(options3);
    if (!options3.defaultUri) {
      options3.defaultUri = await this.defaultFilePath(schema9);
    }
    if (this.P(schema9)) {
      return super.v(schema9, options3, false);
    }
    throw new Error(localize(12666, null));
  }
  u(schema9, isFolder) {
    return schema9 === Schemas.untitled ? [Schemas.file] : schema9 !== Schemas.file && (!isFolder || schema9 !== Schemas.vscodeRemote) ? [schema9, Schemas.file] : [schema9];
  }
  async pickFileAndOpen(options3) {
    const schema9 = this.I(options3);
    if (!options3.defaultUri) {
      options3.defaultUri = await this.defaultFilePath(schema9);
    }
    if (this.P(schema9)) {
      return super.w(schema9, options3, false);
    }
    const activeWindow = $Qj();
    if (!WebFileSystemAccess.supported(activeWindow)) {
      return this.O("open");
    }
    let fileHandle = void 0;
    try {
      [fileHandle] = await activeWindow.showOpenFilePicker({ multiple: false });
    } catch (error) {
      return;
    }
    if (!WebFileSystemAccess.isFileSystemFileHandle(fileHandle)) {
      return;
    }
    const uri = await this.L.registerFileHandle(fileHandle);
    this.x(uri);
    await this.i.open(uri, { fromUserGesture: true, editorOptions: { pinned: true } });
  }
  async pickFolderAndOpen(options3) {
    const schema9 = this.I(options3);
    if (!options3.defaultUri) {
      options3.defaultUri = await this.defaultFolderPath(schema9);
    }
    if (this.P(schema9)) {
      return super.y(schema9, options3);
    }
    throw new Error(localize(12667, null));
  }
  async pickWorkspaceAndOpen(options3) {
    options3.availableFileSystems = this.J(options3);
    const schema9 = this.I(options3);
    if (!options3.defaultUri) {
      options3.defaultUri = await this.defaultWorkspacePath(schema9);
    }
    if (this.P(schema9)) {
      return super.z(schema9, options3);
    }
    throw new Error(localize(12668, null));
  }
  async pickFileToSave(defaultUri, availableFileSystems) {
    const schema9 = this.I({ defaultUri, availableFileSystems });
    const options3 = this.K(defaultUri, availableFileSystems);
    if (this.P(schema9)) {
      return super.A(schema9, options3);
    }
    const activeWindow = $Qj();
    if (!WebFileSystemAccess.supported(activeWindow)) {
      return this.O("save");
    }
    let fileHandle = void 0;
    const startIn = Iterable.first(this.L.directories);
    try {
      fileHandle = await activeWindow.showSaveFilePicker({ types: this.N(options3.filters), ...{ suggestedName: $sh(defaultUri), startIn } });
    } catch (error) {
      return;
    }
    if (!WebFileSystemAccess.isFileSystemFileHandle(fileHandle)) {
      return void 0;
    }
    return this.L.registerFileHandle(fileHandle);
  }
  N(filters2) {
    return filters2?.filter((filter) => {
      return !(filter.extensions.length === 1 && (filter.extensions[0] === "*" || filter.extensions[0] === ""));
    }).map((filter) => {
      const accept = {};
      const extensions = filter.extensions.filter((ext) => ext.indexOf("-") < 0 && ext.indexOf("*") < 0 && ext.indexOf("_") < 0);
      accept[$ZC(`fileName.${filter.extensions[0]}`) ?? "text/plain"] = extensions.map((ext) => ext.startsWith(".") ? ext : `.${ext}`);
      return {
        description: filter.name,
        accept
      };
    });
  }
  async showSaveDialog(options3) {
    const schema9 = this.I(options3);
    if (this.P(schema9)) {
      return super.B(schema9, options3);
    }
    const activeWindow = $Qj();
    if (!WebFileSystemAccess.supported(activeWindow)) {
      return this.O("save");
    }
    let fileHandle = void 0;
    const startIn = Iterable.first(this.L.directories);
    try {
      fileHandle = await activeWindow.showSaveFilePicker({ types: this.N(options3.filters), ...options3.defaultUri ? { suggestedName: $sh(options3.defaultUri) } : void 0, ...{ startIn } });
    } catch (error) {
      return void 0;
    }
    if (!WebFileSystemAccess.isFileSystemFileHandle(fileHandle)) {
      return void 0;
    }
    return this.L.registerFileHandle(fileHandle);
  }
  async showOpenDialog(options3) {
    const schema9 = this.I(options3);
    if (this.P(schema9)) {
      return super.C(schema9, options3);
    }
    const activeWindow = $Qj();
    if (!WebFileSystemAccess.supported(activeWindow)) {
      return this.O("open");
    }
    let uri;
    const startIn = Iterable.first(this.L.directories) ?? "documents";
    try {
      if (options3.canSelectFiles) {
        const handle2 = await activeWindow.showOpenFilePicker({ multiple: false, types: this.N(options3.filters), ...{ startIn } });
        if (handle2.length === 1 && WebFileSystemAccess.isFileSystemFileHandle(handle2[0])) {
          uri = await this.L.registerFileHandle(handle2[0]);
        }
      } else {
        const handle2 = await activeWindow.showDirectoryPicker({ ...{ startIn } });
        uri = await this.L.registerDirectoryHandle(handle2);
      }
    } catch (error) {
    }
    return uri ? [uri] : void 0;
  }
  async O(context) {
    if (context === "save") {
      const activeCodeEditor = this.q.getActiveCodeEditor();
      if (!(activeCodeEditor instanceof $bdb)) {
        const activeTextModel = activeCodeEditor?.getModel();
        if (activeTextModel) {
          $rk($Ci.fromString(activeTextModel.getValue()).buffer, $sh(activeTextModel.uri));
          return;
        }
      }
    }
    const buttons = [
      {
        label: localize(12669, null),
        run: async () => {
          await this.o.executeCommand("workbench.action.remote.showMenu");
        }
      },
      {
        label: localize(12670, null),
        run: async () => {
          await this.i.open("https://aka.ms/VSCodeWebLocalFileSystemAccess");
        }
      }
    ];
    if (context === "open") {
      buttons.push({
        label: localize(12671, null),
        run: async () => {
          const files = await $sk();
          if (files) {
            const filesData = (await this.f.invokeFunction((accessor) => $y_(accessor, files))).filter((fileData) => !fileData.isDirectory);
            if (filesData.length > 0) {
              this.p.openEditors(filesData.map((fileData) => {
                return {
                  resource: fileData.resource,
                  contents: fileData.contents?.toString(),
                  options: { pinned: true }
                };
              }));
            }
          }
        }
      });
    }
    await this.j.prompt({
      type: severity_default.Warning,
      message: localize(12672, null),
      detail: localize(12673, null),
      buttons
    });
    return void 0;
  }
  P(scheme) {
    return ![Schemas.file, Schemas.vscodeUserData, Schemas.tmp].includes(scheme);
  }
};
__decorate([
  $0t
], $4nc.prototype, "L", null);
$SC(
  $1v,
  $4nc,
  1
  /* InstantiationType.Delayed */
);

// out-build/vs/workbench/services/host/browser/browserHostService.js
var HostShutdownReason;
(function(HostShutdownReason2) {
  HostShutdownReason2[HostShutdownReason2["Unknown"] = 1] = "Unknown";
  HostShutdownReason2[HostShutdownReason2["Keyboard"] = 2] = "Keyboard";
  HostShutdownReason2[HostShutdownReason2["Api"] = 3] = "Api";
})(HostShutdownReason || (HostShutdownReason = {}));
var $5nc = class $5nc2 extends $3c {
  constructor(c, f, g, h3, j, m, n, s, t, u, w) {
    super();
    this.c = c;
    this.f = f;
    this.g = g;
    this.h = h3;
    this.j = j;
    this.m = m;
    this.n = n;
    this.s = s;
    this.t = t;
    this.u = u;
    this.w = w;
    this.b = HostShutdownReason.Unknown;
    if (j.options?.workspaceProvider) {
      this.a = j.options.workspaceProvider;
    } else {
      this.a = new class {
        constructor() {
          this.workspace = void 0;
          this.trusted = void 0;
        }
        async open() {
          return true;
        }
      }();
    }
    this.y();
  }
  y() {
    this.B(this.n.onBeforeShutdown((e) => this.z(e)));
    this.B($yk.getInstance().event(() => this.C()));
  }
  z(e) {
    switch (this.b) {
      case HostShutdownReason.Unknown:
      case HostShutdownReason.Keyboard: {
        const confirmBeforeClose = this.f.getValue("window.confirmBeforeClose");
        if (confirmBeforeClose === "always" || confirmBeforeClose === "keyboardOnly" && this.b === HostShutdownReason.Keyboard) {
          e.veto(true, "veto.confirmBeforeClose");
        }
        break;
      }
      case HostShutdownReason.Api:
        break;
    }
    this.b = HostShutdownReason.Unknown;
  }
  C() {
    if (this.b === HostShutdownReason.Api) {
      return;
    }
    if ($yk.getInstance().isModifierPressed) {
      this.b = HostShutdownReason.Keyboard;
    } else {
      this.b = HostShutdownReason.Unknown;
    }
  }
  //#region Focus
  get onDidChangeFocus() {
    const emitter = this.B(new $ze());
    this.B(Event2.runAndSubscribe(onDidRegisterWindow, ({ window: window3, disposables }) => {
      const focusTracker = disposables.add($_j(window3));
      const visibilityTracker = disposables.add(new $9Z(window3.document, "visibilitychange"));
      Event2.any(Event2.map(focusTracker.onDidFocus, () => this.hasFocus, disposables), Event2.map(focusTracker.onDidBlur, () => this.hasFocus, disposables), Event2.map(visibilityTracker.event, () => this.hasFocus, disposables), Event2.map(this.onDidChangeActiveWindow, () => this.hasFocus, disposables))((focus) => emitter.fire(focus));
    }, { window: $Y, disposables: this.q }));
    return Event2.latch(emitter.event, void 0, this.q);
  }
  get hasFocus() {
    return $Pj().hasFocus();
  }
  async hadLastFocus() {
    return true;
  }
  async focus(targetWindow) {
    targetWindow.focus();
  }
  //#endregion
  //#region Window
  get onDidChangeActiveWindow() {
    const emitter = this.B(new $ze());
    this.B(Event2.runAndSubscribe(onDidRegisterWindow, ({ window: window3, disposables }) => {
      const windowId = getWindowId(window3);
      const focusTracker = disposables.add($_j(window3));
      disposables.add(focusTracker.onDidFocus(() => emitter.fire(windowId)));
      if ($Z(window3)) {
        disposables.add($kj(window3, () => {
          const hasFocus = window3.document.hasFocus();
          if (hasFocus) {
            emitter.fire(windowId);
          }
          return hasFocus;
        }, 100, 20));
      }
    }, { window: $Y, disposables: this.q }));
    return Event2.latch(emitter.event, void 0, this.q);
  }
  get onDidChangeFullScreen() {
    const emitter = this.B(new $ze());
    this.B(Event2.runAndSubscribe(onDidRegisterWindow, ({ window: window3, disposables }) => {
      const windowId = getWindowId(window3);
      const viewport = $u && window3.visualViewport ? window3.visualViewport : window3;
      for (const event of [$7j.FULLSCREEN_CHANGE, $7j.WK_FULLSCREEN_CHANGE]) {
        disposables.add($_i(window3.document, event, () => emitter.fire({ windowId, fullscreen: !!$tk(window3) })));
      }
      disposables.add($oj(
        viewport,
        $7j.RESIZE,
        () => emitter.fire({ windowId, fullscreen: !!$tk(window3) }),
        void 0,
        $m ? 2e3 : 800
        /* can be throttled */
      ));
    }, { window: $Y, disposables: this.q }));
    return emitter.event;
  }
  openWindow(arg1, arg2) {
    if (Array.isArray(arg1)) {
      return this.D(arg1, arg2);
    }
    return this.J(arg1);
  }
  async D(toOpen, options3) {
    const payload = this.G(false, options3);
    const fileOpenables = [];
    const foldersToAdd = [];
    for (const openable of toOpen) {
      openable.label = openable.label || this.H(openable);
      if ($zs(openable)) {
        if (options3?.addMode) {
          foldersToAdd.push({ uri: openable.folderUri });
        } else {
          this.L({ folderUri: openable.folderUri }, { reuse: this.I(
            options3,
            false
            /* no file */
          ), payload });
        }
      } else if ($ys(openable)) {
        this.L({ workspaceUri: openable.workspaceUri }, { reuse: this.I(
          options3,
          false
          /* no file */
        ), payload });
      } else if ($As(openable)) {
        fileOpenables.push(openable);
      }
    }
    if (foldersToAdd.length > 0) {
      this.F((accessor) => {
        const workspaceEditingService = accessor.get($zob);
        workspaceEditingService.addFolders(foldersToAdd);
      });
    }
    if (fileOpenables.length > 0) {
      this.F(async (accessor) => {
        const editorService = accessor.get($mJ);
        if (options3?.mergeMode && fileOpenables.length === 4) {
          const editors = $Mb(await $nL(fileOpenables, this.g, this.s));
          if (editors.length !== 4 || !$8K(editors[0]) || !$8K(editors[1]) || !$8K(editors[2]) || !$8K(editors[3])) {
            return;
          }
          if (this.I(
            options3,
            true
            /* file */
          )) {
            editorService.openEditor({
              input1: { resource: editors[0].resource },
              input2: { resource: editors[1].resource },
              base: { resource: editors[2].resource },
              result: { resource: editors[3].resource },
              options: { pinned: true }
            });
          } else {
            const environment = /* @__PURE__ */ new Map();
            environment.set("mergeFile1", editors[0].resource.toString());
            environment.set("mergeFile2", editors[1].resource.toString());
            environment.set("mergeFileBase", editors[2].resource.toString());
            environment.set("mergeFileResult", editors[3].resource.toString());
            this.L(void 0, { payload: Array.from(environment.entries()) });
          }
        } else if (options3?.diffMode && fileOpenables.length === 2) {
          const editors = $Mb(await $nL(fileOpenables, this.g, this.s));
          if (editors.length !== 2 || !$8K(editors[0]) || !$8K(editors[1])) {
            return;
          }
          if (this.I(
            options3,
            true
            /* file */
          )) {
            editorService.openEditor({
              original: { resource: editors[0].resource },
              modified: { resource: editors[1].resource },
              options: { pinned: true }
            });
          } else {
            const environment = /* @__PURE__ */ new Map();
            environment.set("diffFileSecondary", editors[0].resource.toString());
            environment.set("diffFilePrimary", editors[1].resource.toString());
            this.L(void 0, { payload: Array.from(environment.entries()) });
          }
        } else {
          for (const openable of fileOpenables) {
            if (this.I(
              options3,
              true
              /* file */
            )) {
              let openables = [];
              if (options3?.gotoLineMode) {
                const pathColumnAware = $8g(openable.fileUri.path);
                openables = [{
                  fileUri: openable.fileUri.with({ path: pathColumnAware.path }),
                  options: {
                    selection: !$Gg(pathColumnAware.line) ? { startLineNumber: pathColumnAware.line, startColumn: pathColumnAware.column || 1 } : void 0
                  }
                }];
              } else {
                openables = [openable];
              }
              editorService.openEditors($Mb(await $nL(openables, this.g, this.s)), void 0, { validateTrust: true });
            } else {
              const environment = /* @__PURE__ */ new Map();
              environment.set("openFile", openable.fileUri.toString());
              if (options3?.gotoLineMode) {
                environment.set("gotoLineMode", "true");
              }
              this.L(void 0, { payload: Array.from(environment.entries()) });
            }
          }
        }
        const waitMarkerFileURI = options3?.waitMarkerFileURI;
        if (waitMarkerFileURI) {
          (async () => {
            await this.m.invokeFunction((accessor2) => $9tb(accessor2, fileOpenables.map((fileOpenable) => fileOpenable.fileUri)));
            await this.g.del(waitMarkerFileURI);
          })();
        }
      });
    }
  }
  F(fn) {
    this.m.invokeFunction((accessor) => fn(accessor));
  }
  G(isEmptyWindow, options3) {
    const newPayload = new Array();
    if (!isEmptyWindow && this.j.extensionDevelopmentLocationURI) {
      newPayload.push(["extensionDevelopmentPath", this.j.extensionDevelopmentLocationURI.toString()]);
      if (this.j.debugExtensionHost.debugId) {
        newPayload.push(["debugId", this.j.debugExtensionHost.debugId]);
      }
      if (this.j.debugExtensionHost.port) {
        newPayload.push(["inspect-brk-extensions", String(this.j.debugExtensionHost.port)]);
      }
    }
    const newWindowProfile = options3?.forceProfile ? this.w.profiles.find((profile) => profile.name === options3?.forceProfile) : void 0;
    if (newWindowProfile && !newWindowProfile.isDefault) {
      newPayload.push(["profile", newWindowProfile.name]);
    }
    return newPayload.length ? newPayload : void 0;
  }
  H(openable) {
    if ($zs(openable)) {
      return this.h.getWorkspaceLabel(openable.folderUri, {
        verbose: 2
        /* Verbosity.LONG */
      });
    }
    if ($ys(openable)) {
      return this.h.getWorkspaceLabel($nmc(openable.workspaceUri), {
        verbose: 2
        /* Verbosity.LONG */
      });
    }
    return this.h.getUriLabel(openable.fileUri);
  }
  I(options3 = /* @__PURE__ */ Object.create(null), isFile) {
    if (options3.waitMarkerFileURI) {
      return true;
    }
    const windowConfig = this.f.getValue("window");
    const openInNewWindowConfig = isFile ? windowConfig?.openFilesInNewWindow || "off" : windowConfig?.openFoldersInNewWindow || "default";
    let openInNewWindow = (options3.preferNewWindow || !!options3.forceNewWindow) && !options3.forceReuseWindow;
    if (!options3.forceNewWindow && !options3.forceReuseWindow && (openInNewWindowConfig === "on" || openInNewWindowConfig === "off")) {
      openInNewWindow = openInNewWindowConfig === "on";
    }
    return !openInNewWindow;
  }
  async J(options3) {
    return this.L(void 0, {
      reuse: options3?.forceReuseWindow,
      payload: this.G(true, options3)
    });
  }
  async L(workspace2, options3) {
    if (workspace2 && $zs(workspace2) && workspace2.folderUri.scheme === Schemas.file && $fl(this.u.getWorkspace())) {
      this.F(async (accessor) => {
        const workspaceEditingService = accessor.get($zob);
        await workspaceEditingService.updateFolders(0, this.u.getWorkspace().folders.length, [{ uri: workspace2.folderUri }]);
      });
      return;
    }
    if (options3?.reuse) {
      await this.M(
        4
        /* ShutdownReason.LOAD */
      );
    }
    const opened = await this.a.open(workspace2, options3);
    if (!opened) {
      const { confirmed } = await this.t.confirm({
        type: severity_default.Warning,
        message: localize(12935, null),
        primaryButton: localize(12936, null)
      });
      if (confirmed) {
        await this.a.open(workspace2, options3);
      }
    }
  }
  async toggleFullScreen(targetWindow) {
    const target = this.c.getContainer(targetWindow);
    if (targetWindow.document.fullscreen !== void 0) {
      if (!targetWindow.document.fullscreen) {
        try {
          return await target.requestFullscreen();
        } catch (error) {
          this.s.warn("toggleFullScreen(): requestFullscreen failed");
        }
      } else {
        try {
          return await targetWindow.document.exitFullscreen();
        } catch (error) {
          this.s.warn("toggleFullScreen(): exitFullscreen failed");
        }
      }
    }
    if (targetWindow.document.webkitIsFullScreen !== void 0) {
      try {
        if (!targetWindow.document.webkitIsFullScreen) {
          target.webkitRequestFullscreen();
        } else {
          targetWindow.document.webkitExitFullscreen();
        }
      } catch {
        this.s.warn("toggleFullScreen(): requestFullscreen/exitFullscreen failed");
      }
    }
  }
  async moveTop(targetWindow) {
  }
  async getCursorScreenPoint() {
    return void 0;
  }
  //#endregion
  //#region Lifecycle
  async restart() {
    this.reload();
  }
  async reload() {
    await this.M(
      3
      /* ShutdownReason.RELOAD */
    );
    $Y.location.reload();
  }
  async close() {
    await this.M(
      1
      /* ShutdownReason.CLOSE */
    );
    $Y.close();
  }
  async withExpectedShutdown(expectedShutdownTask) {
    const previousShutdownReason = this.b;
    try {
      this.b = HostShutdownReason.Api;
      return await expectedShutdownTask();
    } finally {
      this.b = previousShutdownReason;
    }
  }
  async M(reason) {
    this.b = HostShutdownReason.Api;
    return this.n.withExpectedShutdown(reason);
  }
  //#endregion
  //#region Screenshots
  async getScreenshot() {
    const store = new $2c();
    const video = document.createElement("video");
    store.add($1c(() => video.remove()));
    let stream;
    try {
      stream = await navigator.mediaDevices.getDisplayMedia({
        audio: false,
        video: true
      });
      video.srcObject = stream;
      video.play();
      await Promise.all([
        new Promise((r2) => store.add($_i(video, "loadedmetadata", () => r2()))),
        new Promise((r2) => store.add($_i(video, "canplaythrough", () => r2())))
      ]);
      const canvas = document.createElement("canvas");
      canvas.width = video.videoWidth;
      canvas.height = video.videoHeight;
      const ctx = canvas.getContext("2d");
      if (!ctx) {
        return void 0;
      }
      ctx.drawImage(video, 0, 0, canvas.width, canvas.height);
      const blob = await new Promise((resolve) => canvas.toBlob((blob2) => resolve(blob2), "image/jpeg", 0.95));
      if (!blob) {
        throw new Error("Failed to create blob from canvas");
      }
      return blob.arrayBuffer();
    } catch (error) {
      console.error("Error taking screenshot:", error);
      return void 0;
    } finally {
      store.dispose();
      if (stream) {
        for (const track of stream.getTracks()) {
          track.stop();
        }
      }
    }
  }
  //#endregion
  //#region Native Handle
  async getNativeWindowHandle(_windowId) {
    return void 0;
  }
};
__decorate([
  $0t
], $5nc.prototype, "onDidChangeFocus", null);
__decorate([
  $0t
], $5nc.prototype, "onDidChangeActiveWindow", null);
__decorate([
  $0t
], $5nc.prototype, "onDidChangeFullScreen", null);
$5nc = __decorate([
  __param(0, $Ulb),
  __param(1, $kl),
  __param(2, $km),
  __param(3, $ZI),
  __param(4, $M4),
  __param(5, $Pk),
  __param(6, $KL),
  __param(7, $wn),
  __param(8, $Yv),
  __param(9, $Zk),
  __param(10, $rs)
], $5nc);
$SC(
  $S4,
  $5nc,
  1
  /* InstantiationType.Delayed */
);

// out-build/vs/workbench/services/lifecycle/common/lifecycleService.js
var $Mob_1;
var $Mob = class $Mob2 extends $3c {
  static {
    $Mob_1 = this;
  }
  static {
    this.a = "lifecyle.lastShutdownReason";
  }
  get startupKind() {
    return this.j;
  }
  get phase() {
    return this.m;
  }
  constructor(s, t) {
    super();
    this.s = s;
    this.t = t;
    this.b = this.B(new $ze());
    this.onBeforeShutdown = this.b.event;
    this.c = this.B(new $ze());
    this.onWillShutdown = this.c.event;
    this.f = this.B(new $ze());
    this.onDidShutdown = this.f.event;
    this.g = this.B(new $ze());
    this.onBeforeShutdownError = this.g.event;
    this.h = this.B(new $ze());
    this.onShutdownVeto = this.h.event;
    this.m = 1;
    this.n = /* @__PURE__ */ new Map();
    this.j = this.u();
    this.B(this.t.onWillSaveState((e) => {
      if (e.reason === WillSaveStateReason.SHUTDOWN) {
        this.t.store(
          $Mob_1.a,
          this.r,
          1,
          1
          /* StorageTarget.MACHINE */
        );
      }
    }));
  }
  u() {
    const startupKind = this.w() ?? 1;
    this.s.trace(`[lifecycle] starting up (startup kind: ${startupKind})`);
    return startupKind;
  }
  w() {
    const lastShutdownReason = this.t.getNumber(
      $Mob_1.a,
      1
      /* StorageScope.WORKSPACE */
    );
    this.t.remove(
      $Mob_1.a,
      1
      /* StorageScope.WORKSPACE */
    );
    let startupKind = void 0;
    switch (lastShutdownReason) {
      case 3:
        startupKind = 3;
        break;
      case 4:
        startupKind = 4;
        break;
    }
    return startupKind;
  }
  set phase(value) {
    if (value < this.phase) {
      throw new Error("Lifecycle cannot go backwards");
    }
    if (this.m === value) {
      return;
    }
    this.s.trace(`lifecycle: phase changed (value: ${value})`);
    this.m = value;
    $S(`code/LifecyclePhase/${$ML(value)}`);
    const barrier = this.n.get(this.m);
    if (barrier) {
      barrier.open();
      this.n.delete(this.m);
    }
  }
  async when(phase) {
    if (phase <= this.m) {
      return;
    }
    let barrier = this.n.get(phase);
    if (!barrier) {
      barrier = new $Uh();
      this.n.set(phase, barrier);
    }
    await barrier.wait();
  }
};
$Mob = $Mob_1 = __decorate([
  __param(0, $wn),
  __param(1, $jv)
], $Mob);

// out-build/vs/workbench/services/lifecycle/browser/lifecycleService.js
var $Nob = class $Nob2 extends $Mob {
  constructor(logService, storageService) {
    super(logService, storageService);
    this.y = void 0;
    this.z = void 0;
    this.C = false;
    this.D = false;
    this.F();
  }
  F() {
    this.y = $_i($Y, $7j.BEFORE_UNLOAD, (e) => this.G(e));
    this.z = $_i($Y, $7j.PAGE_HIDE, () => this.J());
  }
  G(event) {
    if (this.C) {
      this.s.info("[lifecycle] onBeforeUnload triggered but ignored once");
      this.C = false;
    } else {
      this.s.info("[lifecycle] onBeforeUnload triggered and handled with veto support");
      this.I(() => this.H(event));
    }
  }
  H(event) {
    event.preventDefault();
    event.returnValue = localize(13011, null);
  }
  withExpectedShutdown(reason, callback) {
    if (typeof reason === "number") {
      this.r = reason;
      return this.t.flush(WillSaveStateReason.SHUTDOWN);
    } else {
      this.C = true;
      try {
        callback?.();
      } finally {
        this.C = false;
      }
    }
  }
  async shutdown() {
    this.s.info("[lifecycle] shutdown triggered");
    this.y?.dispose();
    this.z?.dispose();
    await this.t.flush(WillSaveStateReason.SHUTDOWN);
    this.I();
  }
  I(vetoShutdown) {
    const logService = this.s;
    this.t.flush(WillSaveStateReason.SHUTDOWN);
    let veto = false;
    function handleVeto(vetoResult, id2) {
      if (typeof vetoShutdown !== "function") {
        return;
      }
      if (vetoResult instanceof Promise) {
        logService.error(`[lifecycle] Long running operations before shutdown are unsupported in the web (id: ${id2})`);
        veto = true;
      }
      if (vetoResult === true) {
        logService.info(`[lifecycle]: Unload was prevented (id: ${id2})`);
        veto = true;
      }
    }
    this.b.fire({
      reason: 2,
      veto(value, id2) {
        handleVeto(value, id2);
      },
      finalVeto(valueFn, id2) {
        handleVeto(valueFn(), id2);
      }
    });
    if (veto && typeof vetoShutdown === "function") {
      return vetoShutdown();
    }
    return this.J();
  }
  J() {
    if (this.D) {
      return;
    }
    this.D = true;
    this.B($_i($Y, $7j.PAGE_SHOW, (e) => this.L(e)));
    const logService = this.s;
    this.c.fire({
      reason: 2,
      joiners: () => [],
      // Unsupported in web
      token: CancellationToken.None,
      // Unsupported in web
      join(promise, joiner) {
        if (typeof promise === "function") {
          promise();
        }
        logService.error(`[lifecycle] Long running operations during shutdown are unsupported in the web (id: ${joiner.id})`);
      },
      force: () => {
      }
    });
    this.f.fire();
  }
  L(event) {
    const wasRestoredFromCache = event.persisted;
    if (!wasRestoredFromCache) {
      return;
    }
    this.withExpectedShutdown({ disableShutdownHandling: true }, () => $Y.location.reload());
  }
  w() {
    let startupKind = super.w();
    if (typeof startupKind !== "number") {
      const timing = performance.getEntriesByType("navigation").at(0);
      if (timing?.type === "reload") {
        startupKind = 3;
      }
    }
    return startupKind;
  }
};
$Nob = __decorate([
  __param(0, $wn),
  __param(1, $jv)
], $Nob);
$SC(
  $KL,
  $Nob,
  0
  /* InstantiationType.Eager */
);

// out-build/vs/platform/clipboard/browser/clipboardService.js
var $6nc_1;
var vscodeResourcesMime = "application/vnd.code.resources";
var $6nc = class $6nc2 extends $3c {
  static {
    $6nc_1 = this;
  }
  constructor(a, b) {
    super();
    this.a = a;
    this.b = b;
    this.g = /* @__PURE__ */ new Map();
    this.j = "";
    this.m = [];
    this.n = void 0;
    if ($Xe || $Ye) {
      this.f();
    }
    this.B(Event2.runAndSubscribe(onDidRegisterWindow, ({ window: window3, disposables }) => {
      disposables.add($_i(window3.document, "copy", () => this.t()));
    }, { window: $Y, disposables: this.q }));
  }
  async readImage() {
    try {
      const clipboardItems = await navigator.clipboard.read();
      const clipboardItem = clipboardItems[0];
      const supportedImageTypes = ["image/png", "image/jpeg", "image/gif", "image/tiff", "image/bmp"];
      const mimeType = supportedImageTypes.find((type) => clipboardItem.types.includes(type));
      if (mimeType) {
        const blob = await clipboardItem.getType(mimeType);
        const buffer = await blob.arrayBuffer();
        return new Uint8Array(buffer);
      } else {
        console.error("No supported image type found in the clipboard");
      }
    } catch (error) {
      console.error("Error reading image from clipboard:", error);
    }
    return new Uint8Array(0);
  }
  // In Safari, it has the following note:
  //
  // "The request to write to the clipboard must be triggered during a user gesture.
  // A call to clipboard.write or clipboard.writeText outside the scope of a user
  // gesture(such as "click" or "touch" event handlers) will result in the immediate
  // rejection of the promise returned by the API call."
  // From: https://webkit.org/blog/10855/async-clipboard-api/
  //
  // Since extensions run in a web worker, and handle gestures in an asynchronous way,
  // they are not classified by Safari as "in response to a user gesture" and will reject.
  //
  // This function sets up some handlers to work around that behavior.
  f() {
    const handler = () => {
      const currentWritePromise = new $gi();
      if (this.c && !this.c.isSettled) {
        this.c.cancel();
      }
      this.c = currentWritePromise;
      $Qj().navigator.clipboard.write([new ClipboardItem({
        "text/plain": currentWritePromise.p
      })]).catch(async (err) => {
        if (!(err instanceof Error) || err.name !== "NotAllowedError" || !currentWritePromise.isRejected) {
          this.b.error(err);
        }
      });
    };
    this.B(Event2.runAndSubscribe(this.a.onDidAddContainer, ({ container: container2, disposables }) => {
      disposables.add($_i(container2, "click", handler));
      disposables.add($_i(container2, "keydown", handler));
    }, { container: this.a.mainContainer, disposables: this.q }));
  }
  async writeText(text2, type) {
    this.t();
    if (type) {
      this.g.set(type, text2);
      return;
    }
    if (this.c) {
      return this.c.complete(text2);
    }
    try {
      return await $Qj().navigator.clipboard.writeText(text2);
    } catch (error) {
      console.error(error);
    }
    this.h(text2);
  }
  h(text2) {
    const activeDocument = $Pj();
    const activeElement = activeDocument.activeElement;
    const textArea = activeDocument.body.appendChild($("textarea", { "aria-hidden": true }));
    textArea.style.height = "1px";
    textArea.style.width = "1px";
    textArea.style.position = "absolute";
    textArea.value = text2;
    textArea.focus();
    textArea.select();
    activeDocument.execCommand("copy");
    if ($Uj(activeElement)) {
      activeElement.focus();
    }
    textArea.remove();
  }
  async readText(type) {
    if (type) {
      return this.g.get(type) || "";
    }
    try {
      return await $Qj().navigator.clipboard.readText();
    } catch (error) {
      console.error(error);
    }
    return "";
  }
  async readFindText() {
    return this.j;
  }
  async writeFindText(text2) {
    this.j = text2;
  }
  static {
    this.r = 1e3;
  }
  async writeResources(resources) {
    try {
      await $Qj().navigator.clipboard.write([
        new ClipboardItem({
          [`web ${vscodeResourcesMime}`]: new Blob([
            JSON.stringify(resources.map((x) => x.toJSON()))
          ], {
            type: vscodeResourcesMime
          })
        })
      ]);
    } catch (error) {
    }
    if (resources.length === 0) {
      this.t();
    } else {
      this.m = resources;
      this.n = await this.s();
    }
  }
  async readResources() {
    try {
      const items = await $Qj().navigator.clipboard.read();
      for (const item of items) {
        if (item.types.includes(`web ${vscodeResourcesMime}`)) {
          const blob = await item.getType(`web ${vscodeResourcesMime}`);
          const resources = JSON.parse(await blob.text()).map((x) => URI.from(x));
          return resources;
        }
      }
    } catch (error) {
    }
    const resourcesStateHash = await this.s();
    if (this.n !== resourcesStateHash) {
      this.t();
    }
    return this.m;
  }
  async s() {
    if (this.m.length === 0) {
      return void 0;
    }
    const clipboardText = await this.readText();
    return $Xi(clipboardText.substring(0, $6nc_1.r));
  }
  async hasResources() {
    try {
      const items = await $Qj().navigator.clipboard.read();
      for (const item of items) {
        if (item.types.includes(`web ${vscodeResourcesMime}`)) {
          return true;
        }
      }
    } catch (error) {
    }
    return this.m.length > 0;
  }
  clearInternalState() {
    this.t();
  }
  t() {
    this.m = [];
    this.n = void 0;
  }
};
$6nc = $6nc_1 = __decorate([
  __param(0, $Ulb),
  __param(1, $wn)
], $6nc);

// out-build/vs/workbench/services/clipboard/browser/clipboardService.js
var $7nc = class $7nc2 extends $6nc {
  constructor(u, w, y, logService, layoutService) {
    super(layoutService, logService);
    this.u = u;
    this.w = w;
    this.y = y;
  }
  async writeText(text2, type) {
    if (!!this.y.extensionTestsLocationURI && typeof type !== "string") {
      type = "vscode-tests";
    }
    return super.writeText(text2, type);
  }
  async readText(type) {
    if (!!this.y.extensionTestsLocationURI && typeof type !== "string") {
      type = "vscode-tests";
    }
    if (type) {
      return super.readText(type);
    }
    try {
      return await $Qj().navigator.clipboard.readText();
    } catch (error) {
      return new Promise((resolve) => {
        const listener = new $2c();
        const handle2 = this.u.prompt(Severity2.Error, localize(12563, null), [{
          label: localize(12564, null),
          run: async () => {
            listener.dispose();
            resolve(await this.readText(type));
          }
        }, {
          label: localize(12565, null),
          run: () => this.w.open("https://go.microsoft.com/fwlink/?linkid=2151362")
        }], {
          sticky: true
        });
        listener.add(Event2.once(handle2.onDidClose)(() => resolve("")));
      });
    }
  }
};
$7nc = __decorate([
  __param(0, $PJ),
  __param(1, $O4),
  __param(2, $US),
  __param(3, $wn),
  __param(4, $Ulb)
], $7nc);
$SC(
  $30,
  $7nc,
  1
  /* InstantiationType.Delayed */
);

// out-build/vs/workbench/services/localization/browser/localeService.js
var localeStorage = new class LocaleStorage {
  static {
    this.a = "vscode.nls.locale";
  }
  static {
    this.b = "vscode.nls.languagePackExtensionId";
  }
  setLocale(locale) {
    localStorage.setItem(LocaleStorage.a, locale);
    this.c(locale);
  }
  c(locale) {
    document.cookie = `${LocaleStorage.a}=${locale};path=/;max-age=3153600000`;
  }
  clearLocale() {
    localStorage.removeItem(LocaleStorage.a);
    this.d();
  }
  d() {
    document.cookie = `${LocaleStorage.a}=;path=/;max-age=0`;
  }
  setExtensionId(extensionId) {
    localStorage.setItem(LocaleStorage.b, extensionId);
  }
  getExtensionId() {
    return localStorage.getItem(LocaleStorage.b);
  }
  clearExtensionId() {
    localStorage.removeItem(LocaleStorage.b);
  }
}();
var $8nc = class $8nc2 {
  constructor(a, b, c) {
    this.a = a;
    this.b = b;
    this.c = c;
  }
  async setLocale(languagePackItem, _skipDialog = false) {
    const locale = languagePackItem.id;
    if (locale === Language.value() || !locale && Language.value() === navigator.language.toLowerCase()) {
      return;
    }
    if (locale) {
      localeStorage.setLocale(locale);
      if (languagePackItem.extensionId) {
        localeStorage.setExtensionId(languagePackItem.extensionId);
      }
    } else {
      localeStorage.clearLocale();
      localeStorage.clearExtensionId();
    }
    const restartDialog = await this.a.confirm({
      type: "info",
      message: localize(13012, null, this.c.nameLong),
      detail: localize(13013, null, languagePackItem.label),
      primaryButton: localize(13014, null)
    });
    if (restartDialog.confirmed) {
      this.b.restart();
    }
  }
  async clearLocalePreference() {
    localeStorage.clearLocale();
    localeStorage.clearExtensionId();
    if (Language.value() === navigator.language.toLowerCase()) {
      return;
    }
    const restartDialog = await this.a.confirm({
      type: "info",
      message: localize(13015, null, this.c.nameLong),
      detail: localize(13016, null),
      primaryButton: localize(13017, null)
    });
    if (restartDialog.confirmed) {
      this.b.restart();
    }
  }
};
$8nc = __decorate([
  __param(0, $Yv),
  __param(1, $S4),
  __param(2, $Vu)
], $8nc);
var WebActiveLanguagePackService = class WebActiveLanguagePackService2 {
  constructor(a, b) {
    this.a = a;
    this.b = b;
  }
  async getExtensionIdProvidingCurrentLocale() {
    const language = Language.value();
    if (language === $j) {
      return void 0;
    }
    const extensionId = localeStorage.getExtensionId();
    if (extensionId) {
      return extensionId;
    }
    if (!this.a.isEnabled()) {
      return void 0;
    }
    try {
      const tagResult = await this.a.query({ text: `tag:lp-${language}` }, CancellationToken.None);
      const extensionToInstall = tagResult.firstPage.find((e) => e.publisher === "MS-CEINTL" && e.name.startsWith("vscode-language-pack"));
      if (extensionToInstall) {
        localeStorage.setExtensionId(extensionToInstall.identifier.id);
        return extensionToInstall.identifier.id;
      }
    } catch (e) {
      this.b.error(e);
    }
    return void 0;
  }
};
WebActiveLanguagePackService = __decorate([
  __param(0, $pA),
  __param(1, $wn)
], WebActiveLanguagePackService);
$SC(
  $NCb,
  $8nc,
  1
  /* InstantiationType.Delayed */
);
$SC(
  $OCb,
  WebActiveLanguagePackService,
  1
  /* InstantiationType.Delayed */
);

// out-build/vs/workbench/services/path/browser/pathService.js
var $9nc = class $9nc2 extends $bT {
  constructor(remoteAgentService, environmentService, contextService) {
    super(guessLocalUserHome(environmentService, contextService), remoteAgentService, environmentService, contextService);
  }
};
$9nc = __decorate([
  __param(0, $RL),
  __param(1, $US),
  __param(2, $Zk)
], $9nc);
function guessLocalUserHome(environmentService, contextService) {
  const workspace2 = contextService.getWorkspace();
  const firstFolder = workspace2.folders.at(0);
  if (firstFolder) {
    return firstFolder.uri;
  }
  if (workspace2.configuration) {
    return $uh(workspace2.configuration);
  }
  return URI.from({
    scheme: $bT.findDefaultUriScheme(environmentService, contextService),
    authority: environmentService.remoteAuthority,
    path: "/"
  });
}
$SC(
  $aT,
  $9nc,
  1
  /* InstantiationType.Delayed */
);

// out-build/vs/workbench/services/themes/browser/browserHostColorSchemeService.js
var $0nc = class extends $3c {
  constructor() {
    super();
    this.a = this.B(new $ze());
    this.b();
  }
  b() {
    $Le($Y, "(prefers-color-scheme: dark)", () => {
      this.a.fire();
    });
    $Le($Y, "(forced-colors: active)", () => {
      this.a.fire();
    });
  }
  get onDidChangeColorScheme() {
    return this.a.event;
  }
  get dark() {
    if ($Y.matchMedia(`(prefers-color-scheme: light)`).matches) {
      return false;
    } else if ($Y.matchMedia(`(prefers-color-scheme: dark)`).matches) {
      return true;
    }
    return false;
  }
  get highContrast() {
    if ($Y.matchMedia(`(forced-colors: active)`).matches) {
      return true;
    }
    return false;
  }
};
$SC(
  $NGb,
  $0nc,
  1
  /* InstantiationType.Delayed */
);

// out-build/vs/workbench/services/workingCopy/common/workingCopyBackupService.js
var WorkingCopyBackupServiceImpl_1;
var $$nc = class _$$nc {
  static async create(backupRoot, fileService) {
    const model = new _$$nc(backupRoot, fileService);
    await model.d();
    return model;
  }
  constructor(b, c) {
    this.b = b;
    this.c = c;
    this.a = new $Ec();
  }
  async d() {
    try {
      const backupRootStat = await this.c.resolve(this.b);
      if (backupRootStat.children) {
        await Promises.settled(backupRootStat.children.filter((child) => child.isDirectory).map(async (backupSchemaFolder) => {
          const backupSchemaFolderStat = await this.c.resolve(backupSchemaFolder.resource);
          if (backupSchemaFolderStat.children) {
            for (const backupForSchema of backupSchemaFolderStat.children) {
              if (!backupForSchema.isDirectory) {
                this.add(backupForSchema.resource);
              }
            }
          }
        }));
      }
    } catch (error) {
    }
  }
  add(resource, versionId = 0, meta) {
    this.a.set(resource, {
      versionId,
      meta: $Lv(meta)
    });
  }
  update(resource, meta) {
    const entry = this.a.get(resource);
    if (entry) {
      entry.meta = $Lv(meta);
    }
  }
  count() {
    return this.a.size;
  }
  has(resource, versionId, meta) {
    const entry = this.a.get(resource);
    if (!entry) {
      return false;
    }
    if (typeof versionId === "number" && versionId !== entry.versionId) {
      return false;
    }
    if (meta && !$Pv(meta, entry.meta)) {
      return false;
    }
    return true;
  }
  get() {
    return Array.from(this.a.keys());
  }
  remove(resource) {
    this.a.delete(resource);
  }
  clear() {
    this.a.clear();
  }
};
var $_nc = class $_nc2 extends $3c {
  constructor(backupWorkspaceHome, b, g) {
    super();
    this.b = b;
    this.g = g;
    this.a = this.B(this.h(backupWorkspaceHome));
  }
  h(backupWorkspaceHome) {
    if (backupWorkspaceHome) {
      return new WorkingCopyBackupServiceImpl(backupWorkspaceHome, this.b, this.g);
    }
    return new $aoc();
  }
  reinitialize(backupWorkspaceHome) {
    if (this.a instanceof WorkingCopyBackupServiceImpl) {
      if (backupWorkspaceHome) {
        this.a.initialize(backupWorkspaceHome);
      } else {
        this.a = new $aoc();
      }
    }
  }
  hasBackups() {
    return this.a.hasBackups();
  }
  hasBackupSync(identifier2, versionId, meta) {
    return this.a.hasBackupSync(identifier2, versionId, meta);
  }
  backup(identifier2, content, versionId, meta, token) {
    return this.a.backup(identifier2, content, versionId, meta, token);
  }
  discardBackup(identifier2, token) {
    return this.a.discardBackup(identifier2, token);
  }
  discardBackups(filter) {
    return this.a.discardBackups(filter);
  }
  getBackups() {
    return this.a.getBackups();
  }
  resolve(identifier2) {
    return this.a.resolve(identifier2);
  }
  toBackupResource(identifier2) {
    return this.a.toBackupResource(identifier2);
  }
  joinBackups() {
    return this.a.joinBackups();
  }
};
$_nc = __decorate([
  __param(1, $km),
  __param(2, $wn)
], $_nc);
var WorkingCopyBackupServiceImpl = class WorkingCopyBackupServiceImpl2 extends $3c {
  static {
    WorkingCopyBackupServiceImpl_1 = this;
  }
  static {
    this.a = "\n";
  }
  static {
    this.b = "\n".charCodeAt(0);
  }
  static {
    this.c = " ";
  }
  static {
    this.f = 1e4;
  }
  constructor(m, n, r2) {
    super();
    this.m = m;
    this.n = n;
    this.r = r2;
    this.g = this.B(new $5h());
    this.j = void 0;
    this.initialize(m);
  }
  initialize(backupWorkspaceResource) {
    this.m = backupWorkspaceResource;
    this.h = this.s();
  }
  async s() {
    this.j = await $$nc.create(this.m, this.n);
    return this.j;
  }
  async hasBackups() {
    const model = await this.h;
    await this.joinBackups();
    return model.count() > 0;
  }
  hasBackupSync(identifier2, versionId, meta) {
    if (!this.j) {
      return false;
    }
    const backupResource = this.toBackupResource(identifier2);
    return this.j.has(backupResource, versionId, meta);
  }
  async backup(identifier2, content, versionId, meta, token) {
    const model = await this.h;
    if (token?.isCancellationRequested) {
      return;
    }
    const backupResource = this.toBackupResource(identifier2);
    if (model.has(backupResource, versionId, meta)) {
      return;
    }
    return this.g.queueFor(backupResource, async () => {
      if (token?.isCancellationRequested) {
        return;
      }
      if (model.has(backupResource, versionId, meta)) {
        return;
      }
      let preamble = this.t(identifier2, meta);
      if (preamble.length >= WorkingCopyBackupServiceImpl_1.f) {
        preamble = this.t(identifier2);
      }
      const preambleBuffer = $Ci.fromString(preamble);
      let backupBuffer;
      if ($oi(content)) {
        backupBuffer = $Ui(preambleBuffer, content);
      } else if (content) {
        backupBuffer = $Ti(preambleBuffer, content);
      } else {
        backupBuffer = $Ci.concat([preambleBuffer, $Ci.fromString("")]);
      }
      await this.n.writeFile(backupResource, backupBuffer);
      model.add(backupResource, versionId, meta);
    });
  }
  t(identifier2, meta) {
    return `${identifier2.resource.toString()}${WorkingCopyBackupServiceImpl_1.c}${JSON.stringify({ ...meta, typeId: identifier2.typeId })}${WorkingCopyBackupServiceImpl_1.a}`;
  }
  async discardBackups(filter) {
    const model = await this.h;
    const except = filter?.except;
    if (Array.isArray(except) && except.length > 0) {
      const exceptMap = new $Ec();
      for (const exceptWorkingCopy of except) {
        exceptMap.set(this.toBackupResource(exceptWorkingCopy), true);
      }
      await Promises.settled(model.get().map(async (backupResource) => {
        if (!exceptMap.has(backupResource)) {
          await this.u(backupResource);
        }
      }));
    } else {
      await this.w(this.m);
      model.clear();
    }
  }
  discardBackup(identifier2, token) {
    const backupResource = this.toBackupResource(identifier2);
    return this.u(backupResource, token);
  }
  async u(backupResource, token) {
    const model = await this.h;
    if (token?.isCancellationRequested) {
      return;
    }
    return this.g.queueFor(backupResource, async () => {
      if (token?.isCancellationRequested) {
        return;
      }
      await this.w(backupResource);
      model.remove(backupResource);
    });
  }
  async w(backupResource) {
    try {
      await this.n.del(backupResource, { recursive: true });
    } catch (error) {
      if (error.fileOperationResult !== 1) {
        throw error;
      }
    }
  }
  async getBackups() {
    const model = await this.h;
    await this.joinBackups();
    const backups = await Promise.all(model.get().map((backupResource) => this.y(backupResource, model)));
    return $Mb(backups);
  }
  async y(backupResource, model) {
    let res = void 0;
    await this.g.queueFor(backupResource, async () => {
      if (!model.has(backupResource)) {
        return;
      }
      const backupPreamble = await this.z(backupResource, WorkingCopyBackupServiceImpl_1.a, WorkingCopyBackupServiceImpl_1.f);
      if (!backupPreamble) {
        return;
      }
      const metaStartIndex = backupPreamble.indexOf(WorkingCopyBackupServiceImpl_1.c);
      let resourcePreamble;
      let metaPreamble;
      if (metaStartIndex > 0) {
        resourcePreamble = backupPreamble.substring(0, metaStartIndex);
        metaPreamble = backupPreamble.substr(metaStartIndex + 1);
      } else {
        resourcePreamble = backupPreamble;
        metaPreamble = void 0;
      }
      const { typeId: typeId2, meta } = this.C(metaPreamble);
      model.update(backupResource, meta);
      res = {
        typeId: typeId2 ?? $qG,
        resource: URI.parse(resourcePreamble)
      };
    });
    return res;
  }
  async z(backupResource, matchingString, maximumBytesToRead) {
    const contents = (await this.n.readFile(backupResource, { length: maximumBytesToRead })).value.toString();
    const matchingStringIndex = contents.indexOf(matchingString);
    if (matchingStringIndex >= 0) {
      return contents.substr(0, matchingStringIndex);
    }
    return void 0;
  }
  async resolve(identifier2) {
    const backupResource = this.toBackupResource(identifier2);
    const model = await this.h;
    let res = void 0;
    await this.g.queueFor(backupResource, async () => {
      if (!model.has(backupResource)) {
        return;
      }
      const backupStream = await this.n.readFileStream(backupResource);
      const peekedBackupStream = await $vi(backupStream.value, 1);
      const firstBackupChunk = $Ci.concat(peekedBackupStream.buffer);
      const preambleEndIndex = firstBackupChunk.buffer.indexOf(WorkingCopyBackupServiceImpl_1.b);
      if (preambleEndIndex === -1) {
        this.r.trace(`Backup: Could not find meta end marker in ${backupResource}. The file is probably corrupt (filesize: ${backupStream.size}).`);
        return void 0;
      }
      const preambelRaw = firstBackupChunk.slice(0, preambleEndIndex).toString();
      let meta;
      const metaStartIndex = preambelRaw.indexOf(WorkingCopyBackupServiceImpl_1.c);
      if (metaStartIndex !== -1) {
        meta = this.C(preambelRaw.substr(metaStartIndex + 1)).meta;
      }
      model.update(backupResource, meta);
      const firstBackupChunkWithoutPreamble = firstBackupChunk.slice(preambleEndIndex + 1);
      let value;
      if (peekedBackupStream.ended) {
        value = $Qi(firstBackupChunkWithoutPreamble);
      } else {
        value = $Ui(firstBackupChunkWithoutPreamble, peekedBackupStream.stream);
      }
      res = { value, meta };
    });
    return res;
  }
  C(preambleMetaRaw) {
    let typeId2 = void 0;
    let meta = void 0;
    if (preambleMetaRaw) {
      try {
        meta = JSON.parse(preambleMetaRaw);
        typeId2 = meta?.typeId;
        if (typeof meta?.typeId === "string") {
          delete meta.typeId;
          if ($Mg(meta)) {
            meta = void 0;
          }
        }
      } catch (error) {
      }
    }
    return { typeId: typeId2, meta };
  }
  toBackupResource(identifier2) {
    return $vh(this.m, identifier2.resource.scheme, $boc(identifier2));
  }
  joinBackups() {
    return this.g.whenDrained();
  }
};
WorkingCopyBackupServiceImpl = WorkingCopyBackupServiceImpl_1 = __decorate([
  __param(1, $km),
  __param(2, $wn)
], WorkingCopyBackupServiceImpl);
var $aoc = class extends $3c {
  constructor() {
    super();
    this.a = new $Ec();
  }
  async hasBackups() {
    return this.a.size > 0;
  }
  hasBackupSync(identifier2, versionId) {
    const backupResource = this.toBackupResource(identifier2);
    return this.a.has(backupResource);
  }
  async backup(identifier2, content, versionId, meta, token) {
    const backupResource = this.toBackupResource(identifier2);
    this.a.set(backupResource, {
      typeId: identifier2.typeId,
      content: content instanceof $Ci ? content : content ? $oi(content) ? await $Oi(content) : $Mi(content) : $Ci.fromString(""),
      meta
    });
  }
  async resolve(identifier2) {
    const backupResource = this.toBackupResource(identifier2);
    const backup = this.a.get(backupResource);
    if (backup) {
      return { value: $Qi(backup.content), meta: backup.meta };
    }
    return void 0;
  }
  async getBackups() {
    return Array.from(this.a.entries()).map(([resource, backup]) => ({ typeId: backup.typeId, resource }));
  }
  async discardBackup(identifier2) {
    this.a.delete(this.toBackupResource(identifier2));
  }
  async discardBackups(filter) {
    const except = filter?.except;
    if (Array.isArray(except) && except.length > 0) {
      const exceptMap = new $Ec();
      for (const exceptWorkingCopy of except) {
        exceptMap.set(this.toBackupResource(exceptWorkingCopy), true);
      }
      for (const backup of await this.getBackups()) {
        if (!exceptMap.has(this.toBackupResource(backup))) {
          await this.discardBackup(backup);
        }
      }
    } else {
      this.a.clear();
    }
  }
  toBackupResource(identifier2) {
    return URI.from({ scheme: Schemas.inMemory, path: $boc(identifier2) });
  }
  async joinBackups() {
    return;
  }
};
function $boc(identifier2) {
  let resource;
  if (identifier2.typeId.length > 0) {
    const typeIdHash = hashString(identifier2.typeId);
    if (identifier2.resource.path) {
      resource = $vh(identifier2.resource, typeIdHash);
    } else {
      resource = identifier2.resource.with({ path: typeIdHash });
    }
  } else {
    resource = identifier2.resource;
  }
  return hashPath(resource);
}
function hashPath(resource) {
  const str = resource.scheme === Schemas.file || resource.scheme === Schemas.untitled ? resource.fsPath : resource.toString();
  return hashString(str);
}
function hashString(str) {
  return $Xi(str).toString(16);
}

// out-build/vs/workbench/services/workingCopy/common/workingCopyBackupTracker.js
var $coc = class _$coc extends $3c {
  constructor(a, b, c, f, g, h3, j, m) {
    super();
    this.a = a;
    this.b = b;
    this.c = c;
    this.f = f;
    this.g = g;
    this.h = h3;
    this.j = j;
    this.m = m;
    this.u = /* @__PURE__ */ new Map();
    this.w = /* @__PURE__ */ new Map();
    this.y = false;
    this.Q = /* @__PURE__ */ new Set();
    this.R = this.W();
    this.S = false;
    for (const workingCopy of this.b.modifiedWorkingCopies) {
      this.z(workingCopy);
    }
    this.n();
  }
  n() {
    this.B(this.b.onDidRegister((workingCopy) => this.z(workingCopy)));
    this.B(this.b.onDidUnregister((workingCopy) => this.C(workingCopy)));
    this.B(this.b.onDidChangeDirty((workingCopy) => this.D(workingCopy)));
    this.B(this.b.onDidChangeContent((workingCopy) => this.F(workingCopy)));
    this.B(this.f.onBeforeShutdown((event) => event.finalVeto(() => this.r(event.reason), "veto.backups")));
    this.B(this.f.onWillShutdown(() => this.s()));
    this.B(this.h.onDidRegisterHandler((handler) => this.X(handler)));
  }
  s() {
    this.O();
    this.P();
  }
  static {
    this.t = {
      ["default"]: 1e3,
      ["delayed"]: 2e3
    };
  }
  z(workingCopy) {
    if (this.y) {
      this.c.warn(`[backup tracker] suspended, ignoring register event`, workingCopy.resource.toString(), workingCopy.typeId);
      return;
    }
    if (workingCopy.isModified()) {
      this.G(workingCopy);
    }
  }
  C(workingCopy) {
    this.u.delete(workingCopy);
    if (this.y) {
      this.c.warn(`[backup tracker] suspended, ignoring unregister event`, workingCopy.resource.toString(), workingCopy.typeId);
      return;
    }
    this.J(workingCopy);
  }
  D(workingCopy) {
    if (this.y) {
      this.c.warn(`[backup tracker] suspended, ignoring dirty change event`, workingCopy.resource.toString(), workingCopy.typeId);
      return;
    }
    if (workingCopy.isDirty()) {
      this.G(workingCopy);
    } else {
      this.J(workingCopy);
    }
  }
  F(workingCopy) {
    const contentVersionId = this.I(workingCopy);
    this.u.set(workingCopy, contentVersionId + 1);
    if (this.y) {
      this.c.warn(`[backup tracker] suspended, ignoring content change event`, workingCopy.resource.toString(), workingCopy.typeId);
      return;
    }
    if (workingCopy.isModified()) {
      this.G(workingCopy);
    }
  }
  G(workingCopy) {
    this.M(workingCopy);
    this.c.trace(`[backup tracker] scheduling backup`, workingCopy.resource.toString(), workingCopy.typeId);
    const workingCopyIdentifier = { resource: workingCopy.resource, typeId: workingCopy.typeId };
    const cts = new $ad();
    const handle2 = setTimeout(async () => {
      if (cts.token.isCancellationRequested) {
        return;
      }
      if (workingCopy.isModified()) {
        this.c.trace(`[backup tracker] creating backup`, workingCopy.resource.toString(), workingCopy.typeId);
        try {
          const backup = await workingCopy.backup(cts.token);
          if (cts.token.isCancellationRequested) {
            return;
          }
          if (workingCopy.isModified()) {
            this.c.trace(`[backup tracker] storing backup`, workingCopy.resource.toString(), workingCopy.typeId);
            await this.a.backup(workingCopy, backup.content, this.I(workingCopy), backup.meta, cts.token);
          }
        } catch (error) {
          this.c.error(error);
        }
      }
      if (!cts.token.isCancellationRequested) {
        this.N(workingCopyIdentifier);
      }
    }, this.H(workingCopy));
    this.w.set(workingCopyIdentifier, {
      cancel: () => {
        this.c.trace(`[backup tracker] clearing pending backup creation`, workingCopy.resource.toString(), workingCopy.typeId);
        cts.cancel();
      },
      disposable: $1c(() => {
        cts.dispose();
        clearTimeout(handle2);
      })
    });
  }
  H(workingCopy) {
    if (typeof workingCopy.backupDelay === "number") {
      return workingCopy.backupDelay;
    }
    let backupScheduleDelay;
    if (workingCopy.capabilities & 2) {
      backupScheduleDelay = "default";
    } else {
      backupScheduleDelay = this.g.hasShortAutoSaveDelay(workingCopy.resource) ? "delayed" : "default";
    }
    return _$coc.t[backupScheduleDelay];
  }
  I(workingCopy) {
    return this.u.get(workingCopy) || 0;
  }
  J(workingCopy) {
    this.M(workingCopy);
    const workingCopyIdentifier = { resource: workingCopy.resource, typeId: workingCopy.typeId };
    const cts = new $ad();
    this.L(workingCopyIdentifier, cts);
    this.w.set(workingCopyIdentifier, {
      cancel: () => {
        this.c.trace(`[backup tracker] clearing pending backup discard`, workingCopy.resource.toString(), workingCopy.typeId);
        cts.cancel();
      },
      disposable: cts
    });
  }
  async L(workingCopyIdentifier, cts) {
    this.c.trace(`[backup tracker] discarding backup`, workingCopyIdentifier.resource.toString(), workingCopyIdentifier.typeId);
    try {
      await this.a.discardBackup(workingCopyIdentifier, cts.token);
    } catch (error) {
      this.c.error(error);
    }
    if (!cts.token.isCancellationRequested) {
      this.N(workingCopyIdentifier);
    }
  }
  M(workingCopy) {
    let workingCopyIdentifier = void 0;
    for (const [identifier2] of this.w) {
      if (identifier2.resource.toString() === workingCopy.resource.toString() && identifier2.typeId === workingCopy.typeId) {
        workingCopyIdentifier = identifier2;
        break;
      }
    }
    if (workingCopyIdentifier) {
      this.N(workingCopyIdentifier, { cancel: true });
    }
  }
  N(workingCopyIdentifier, options3) {
    const pendingBackupOperation = this.w.get(workingCopyIdentifier);
    if (!pendingBackupOperation) {
      return;
    }
    if (options3?.cancel) {
      pendingBackupOperation.cancel();
    }
    pendingBackupOperation.disposable.dispose();
    this.w.delete(workingCopyIdentifier);
  }
  O() {
    for (const [, operation] of this.w) {
      operation.cancel();
      operation.disposable.dispose();
    }
    this.w.clear();
  }
  P() {
    this.y = true;
    return { resume: () => this.y = false };
  }
  get U() {
    return this.S;
  }
  async W() {
    await this.f.when(
      3
      /* LifecyclePhase.Restored */
    );
    for (const backup of await this.a.getBackups()) {
      this.Q.add(backup);
    }
    this.S = true;
  }
  async X(handler) {
    await this.R;
    const openedEditorsForBackups = /* @__PURE__ */ new Set();
    const nonOpenedEditorsForBackups = /* @__PURE__ */ new Set();
    const restoredBackups = /* @__PURE__ */ new Set();
    for (const unrestoredBackup of this.Q) {
      const canHandleUnrestoredBackup = await handler.handles(unrestoredBackup);
      if (!canHandleUnrestoredBackup) {
        continue;
      }
      let hasOpenedEditorForBackup = false;
      for (const { editor } of this.j.getEditors(
        0
        /* EditorsOrder.MOST_RECENTLY_ACTIVE */
      )) {
        const isUnrestoredBackupOpened = handler.isOpen(unrestoredBackup, editor);
        if (isUnrestoredBackupOpened) {
          openedEditorsForBackups.add(editor);
          hasOpenedEditorForBackup = true;
        }
      }
      if (!hasOpenedEditorForBackup) {
        nonOpenedEditorsForBackups.add(await handler.createEditor(unrestoredBackup));
      }
      restoredBackups.add(unrestoredBackup);
    }
    if (nonOpenedEditorsForBackups.size > 0) {
      await this.m.activeGroup.openEditors([...nonOpenedEditorsForBackups].map((nonOpenedEditorForBackup) => ({
        editor: nonOpenedEditorForBackup,
        options: {
          pinned: true,
          preserveFocus: true,
          inactive: true
        }
      })));
      for (const nonOpenedEditorForBackup of nonOpenedEditorsForBackups) {
        openedEditorsForBackups.add(nonOpenedEditorForBackup);
      }
    }
    await Promises.settled([...openedEditorsForBackups].map(async (openedEditorForBackup) => {
      if (this.j.isVisible(openedEditorForBackup)) {
        return;
      }
      return openedEditorForBackup.resolve();
    }));
    for (const restoredBackup of restoredBackups) {
      this.Q.delete(restoredBackup);
    }
  }
};

// out-build/vs/workbench/services/workingCopy/browser/workingCopyBackupTracker.js
var $doc = class $doc2 extends $coc {
  static {
    this.ID = "workbench.contrib.browserWorkingCopyBackupTracker";
  }
  constructor(workingCopyBackupService, filesConfigurationService, workingCopyService, lifecycleService, logService, workingCopyEditorService, editorService, editorGroupService) {
    super(workingCopyBackupService, workingCopyService, logService, lifecycleService, filesConfigurationService, workingCopyEditorService, editorService, editorGroupService);
  }
  r(reason) {
    const modifiedWorkingCopies = this.b.modifiedWorkingCopies;
    if (!modifiedWorkingCopies.length) {
      return false;
    }
    if (!this.g.isHotExitEnabled) {
      return true;
    }
    for (const modifiedWorkingCopy of modifiedWorkingCopies) {
      if (!this.a.hasBackupSync(modifiedWorkingCopy, this.I(modifiedWorkingCopy))) {
        this.c.warn("Unload veto: pending backups");
        return true;
      }
    }
    return false;
  }
};
$doc = __decorate([
  __param(0, $yG),
  __param(1, $4J),
  __param(2, $XI),
  __param(3, $KL),
  __param(4, $wn),
  __param(5, $6J),
  __param(6, $mJ),
  __param(7, $iJ)
], $doc);

// out-build/vs/workbench/services/workingCopy/browser/workingCopyBackupService.js
var $eoc = class $eoc2 extends $_nc {
  constructor(contextService, environmentService, fileService, logService) {
    super($vh(environmentService.userRoamingDataHome, "Backups", contextService.getWorkspace().id), fileService, logService);
  }
};
$eoc = __decorate([
  __param(0, $Zk),
  __param(1, $US),
  __param(2, $km),
  __param(3, $wn)
], $eoc);
$SC(
  $yG,
  $eoc,
  0
  /* InstantiationType.Eager */
);
$PL(
  $doc.ID,
  $doc,
  1
  /* WorkbenchPhase.BlockStartup */
);

// out-build/vs/workbench/services/tunnel/browser/tunnelService.js
var $foc = class $foc2 extends $EC {
  constructor(logService, H, configurationService) {
    super(logService, configurationService);
    this.H = H;
  }
  isPortPrivileged(_port) {
    return false;
  }
  F(tunnelProvider, remoteHost, remotePort, _localHost, localPort, elevateIfNeeded, privacy, protocol) {
    const existing = this.D(remoteHost, remotePort);
    if (existing) {
      ++existing.refcount;
      return existing.value;
    }
    if ($vC(tunnelProvider)) {
      return this.G(tunnelProvider, remoteHost, remotePort, localPort, elevateIfNeeded, privacy, protocol);
    }
    return void 0;
  }
  canTunnel(uri) {
    return super.canTunnel(uri) && !!this.H.remoteAuthority;
  }
};
$foc = __decorate([
  __param(0, $wn),
  __param(1, $US),
  __param(2, $kl)
], $foc);
$SC(
  $tC,
  $foc,
  1
  /* InstantiationType.Delayed */
);

// out-build/vs/workbench/services/files/browser/elevatedFileService.js
var $goc = class {
  isSupported(resource) {
    return false;
  }
  async writeFileElevated(resource, value, options3) {
    throw new Error("Unsupported");
  }
};
$SC(
  $8J,
  $goc,
  1
  /* InstantiationType.Delayed */
);

// out-build/vs/workbench/services/workingCopy/common/workingCopyHistoryTracker.js
var $hoc_1;
var $hoc = class $hoc2 extends $3c {
  static {
    $hoc_1 = this;
  }
  static {
    this.a = {
      ENABLED: "workbench.localHistory.enabled",
      SIZE_LIMIT: "workbench.localHistory.maxFileSize",
      EXCLUDES: "workbench.localHistory.exclude"
    };
  }
  static {
    this.b = $bL.registerSource("undoRedo.source", localize(13620, null));
  }
  constructor(m, n, r2, s, t, u, w, y) {
    super();
    this.m = m;
    this.n = n;
    this.r = r2;
    this.s = s;
    this.t = t;
    this.u = u;
    this.w = w;
    this.y = y;
    this.c = this.B(new $2h($Pkc));
    this.f = this.B(new $ci(() => {
      const matcher = this.B(new $2J((root) => this.t.getValue($hoc_1.a.EXCLUDES, { resource: root }), (event) => event.affectsConfiguration($hoc_1.a.EXCLUDES), this.w, this.t));
      return matcher;
    }));
    this.g = new $Ec((resource) => this.r.extUri.getComparisonKey(resource));
    this.h = new $Ec((resource) => this.r.extUri.getComparisonKey(resource));
    this.j = new $Ec((resource) => this.r.extUri.getComparisonKey(resource));
    this.z();
  }
  z() {
    this.B(this.y.onDidRunOperation((e) => this.C(e)));
    this.B(this.m.onDidChangeContent((workingCopy) => this.D(workingCopy)));
    this.B(this.m.onDidSave((e) => this.G(e)));
  }
  async C(e) {
    if (!this.J(e)) {
      return;
    }
    const source = e.resource;
    const target = e.target.resource;
    const resources = await this.n.moveEntries(source, target);
    for (const resource of resources) {
      const contentVersion = this.F(resource);
      this.j.set(resource, contentVersion);
    }
  }
  D(workingCopy) {
    const contentVersionId = this.F(workingCopy.resource);
    this.h.set(workingCopy.resource, contentVersionId + 1);
  }
  F(resource) {
    return this.h.get(resource) || 0;
  }
  G(e) {
    if (!this.I(e)) {
      return;
    }
    const contentVersion = this.F(e.workingCopy.resource);
    if (this.j.get(e.workingCopy.resource) === contentVersion) {
      return;
    }
    this.g.get(e.workingCopy.resource)?.dispose(true);
    const cts = new $ad();
    this.g.set(e.workingCopy.resource, cts);
    this.c.queue(async () => {
      if (cts.token.isCancellationRequested) {
        return;
      }
      const contentVersion2 = this.F(e.workingCopy.resource);
      let source = e.source;
      if (!e.source) {
        source = this.H(e);
      }
      await this.n.addEntry({ resource: e.workingCopy.resource, source, timestamp: e.stat.mtime }, cts.token);
      this.j.set(e.workingCopy.resource, contentVersion2);
      if (cts.token.isCancellationRequested) {
        return;
      }
      this.g.delete(e.workingCopy.resource);
    });
  }
  H(e) {
    const lastStackElement = this.u.getLastElement(e.workingCopy.resource);
    if (lastStackElement) {
      if (lastStackElement.code === "undoredo.textBufferEdit") {
        return void 0;
      }
      return lastStackElement.label;
    }
    const allStackElements = this.u.getElements(e.workingCopy.resource);
    if (allStackElements.future.length > 0 || allStackElements.past.length > 0) {
      return $hoc_1.b;
    }
    return void 0;
  }
  I(e) {
    if (!$0J(e)) {
      return false;
    }
    return this.L(e.workingCopy.resource, e.stat);
  }
  J(e) {
    if (!e.isOperation(
      2
      /* FileOperation.MOVE */
    )) {
      return false;
    }
    return this.L(e.target.resource, e.target);
  }
  L(resource, stat) {
    if (resource.scheme !== this.s.defaultUriScheme && // track history for all workspace resources
    resource.scheme !== Schemas.vscodeUserData && // track history for all settings
    resource.scheme !== Schemas.inMemory) {
      return false;
    }
    const configuredMaxFileSizeInBytes = 1024 * this.t.getValue($hoc_1.a.SIZE_LIMIT, { resource });
    if (stat.size > configuredMaxFileSizeInBytes) {
      return false;
    }
    if (this.t.getValue($hoc_1.a.ENABLED, { resource }) === false) {
      return false;
    }
    return !this.f.value.matches(resource);
  }
};
$hoc = $hoc_1 = __decorate([
  __param(0, $XI),
  __param(1, $Okc),
  __param(2, $vl),
  __param(3, $aT),
  __param(4, $kl),
  __param(5, $_F),
  __param(6, $Zk),
  __param(7, $km)
], $hoc);

// out-build/vs/workbench/services/workingCopy/common/workingCopyHistoryService.js
var $joc_1;
var $koc_1;
var $ioc = class _$ioc {
  static {
    this.ENTRIES_FILE = "entries.json";
  }
  static {
    this.a = $bL.registerSource("default.source", localize(13616, null));
  }
  static {
    this.b = {
      MAX_ENTRIES: "workbench.localHistory.maxFileEntries",
      MERGE_PERIOD: "workbench.localHistory.mergeWindow"
    };
  }
  constructor(workingCopyResource, n, o, q, r2, s, t, u, v, w, x) {
    this.n = n;
    this.o = o;
    this.q = q;
    this.r = r2;
    this.s = s;
    this.t = t;
    this.u = u;
    this.v = v;
    this.w = w;
    this.x = x;
    this.c = [];
    this.d = void 0;
    this.f = void 0;
    this.g = void 0;
    this.h = void 0;
    this.i = void 0;
    this.j = void 0;
    this.k = 0;
    this.l = this.k;
    this.m = new $2h(1);
    this.y(workingCopyResource);
  }
  y(workingCopyResource) {
    this.f = workingCopyResource;
    this.g = this.v.getUriBasenameLabel(workingCopyResource);
    this.j = new RegExp(`[A-Za-z0-9]{4}${$Af($th(workingCopyResource))}`);
    this.h = this.z(this.n, workingCopyResource);
    this.i = $vh(this.h, _$ioc.ENTRIES_FILE);
    this.c = [];
    this.d = void 0;
  }
  z(historyHome, workingCopyResource) {
    return $vh(historyHome, $Xi(workingCopyResource.toString()).toString(16));
  }
  async addEntry(source = _$ioc.a, sourceDescription = void 0, timestamp = Date.now(), token) {
    let entryToReplace = void 0;
    const lastEntry = this.c.at(-1);
    if (lastEntry && lastEntry.source === source) {
      const configuredReplaceInterval = this.x.getValue(_$ioc.b.MERGE_PERIOD, { resource: this.f });
      if (timestamp - lastEntry.timestamp <= configuredReplaceInterval * 1e3) {
        entryToReplace = lastEntry;
      }
    }
    let entry;
    if (entryToReplace) {
      entry = await this.B(entryToReplace, source, sourceDescription, timestamp, token);
    } else {
      entry = await this.A(source, sourceDescription, timestamp, token);
    }
    if (this.t.flushOnChange && !token.isCancellationRequested) {
      await this.store(token);
    }
    return entry;
  }
  async A(source, sourceDescription = void 0, timestamp, token) {
    const workingCopyResource = $Kg(this.f);
    const workingCopyName = $Kg(this.g);
    const historyEntriesFolder = $Kg(this.h);
    const id2 = `${$9g(void 0, void 0, 4)}${$th(workingCopyResource)}`;
    const location3 = $vh(historyEntriesFolder, id2);
    await this.u.cloneFile(workingCopyResource, location3);
    const entry = {
      id: id2,
      workingCopy: { resource: workingCopyResource, name: workingCopyName },
      location: location3,
      timestamp,
      source,
      sourceDescription
    };
    this.c.push(entry);
    this.k++;
    this.o.fire({ entry });
    return entry;
  }
  async B(entry, source, sourceDescription = void 0, timestamp, token) {
    const workingCopyResource = $Kg(this.f);
    await this.u.cloneFile(workingCopyResource, entry.location);
    entry.source = source;
    entry.sourceDescription = sourceDescription;
    entry.timestamp = timestamp;
    this.k++;
    this.r.fire({ entry });
    return entry;
  }
  async removeEntry(entry, token) {
    await this.C();
    if (token.isCancellationRequested) {
      return false;
    }
    const index = this.c.indexOf(entry);
    if (index === -1) {
      return false;
    }
    await this.I(entry);
    this.c.splice(index, 1);
    this.k++;
    this.s.fire({ entry });
    if (this.t.flushOnChange && !token.isCancellationRequested) {
      await this.store(token);
    }
    return true;
  }
  async updateEntry(entry, properties, token) {
    await this.C();
    if (token.isCancellationRequested) {
      return;
    }
    const index = this.c.indexOf(entry);
    if (index === -1) {
      return;
    }
    entry.source = properties.source;
    this.k++;
    this.q.fire({ entry });
    if (this.t.flushOnChange && !token.isCancellationRequested) {
      await this.store(token);
    }
  }
  async getEntries() {
    await this.C();
    const configuredMaxEntries = this.x.getValue(_$ioc.b.MAX_ENTRIES, { resource: this.f });
    if (this.c.length > configuredMaxEntries) {
      return this.c.slice(this.c.length - configuredMaxEntries);
    }
    return this.c;
  }
  async hasEntries(skipResolve) {
    if (!skipResolve) {
      await this.C();
    }
    return this.c.length > 0;
  }
  C() {
    if (!this.d) {
      this.d = this.D();
    }
    return this.d;
  }
  async D() {
    const entries2 = await this.E();
    for (const entry of this.c) {
      entries2.set(entry.id, entry);
    }
    this.c = Array.from(entries2.values()).sort((entryA, entryB) => entryA.timestamp - entryB.timestamp);
  }
  async E() {
    const workingCopyResource = $Kg(this.f);
    const workingCopyName = $Kg(this.g);
    const [entryListing, entryStats] = await Promise.all([
      // Resolve entries listing file
      this.K(),
      // Resolve children of history folder
      this.L()
    ]);
    const entries2 = /* @__PURE__ */ new Map();
    if (entryStats) {
      for (const entryStat of entryStats) {
        entries2.set(entryStat.name, {
          id: entryStat.name,
          workingCopy: { resource: workingCopyResource, name: workingCopyName },
          location: entryStat.resource,
          timestamp: entryStat.mtime,
          source: _$ioc.a,
          sourceDescription: void 0
        });
      }
    }
    if (entryListing) {
      for (const entry of entryListing.entries) {
        const existingEntry = entries2.get(entry.id);
        if (existingEntry) {
          entries2.set(entry.id, {
            ...existingEntry,
            timestamp: entry.timestamp,
            source: entry.source ?? existingEntry.source,
            sourceDescription: entry.sourceDescription ?? existingEntry.sourceDescription
          });
        }
      }
    }
    return entries2;
  }
  async moveEntries(target, source, token) {
    const timestamp = Date.now();
    const sourceDescription = this.v.getUriLabel($Kg(this.f));
    const sourceHistoryEntriesFolder = $Kg(this.h);
    const targetHistoryEntriesFolder = $Kg(target.h);
    try {
      for (const entry of this.c) {
        await this.u.move(entry.location, $vh(targetHistoryEntriesFolder, entry.id), true);
      }
      await this.u.del(sourceHistoryEntriesFolder, { recursive: true });
    } catch (error) {
      if (!this.M(error)) {
        try {
          await this.u.move(sourceHistoryEntriesFolder, targetHistoryEntriesFolder, true);
        } catch (error2) {
          if (!this.M(error2)) {
            this.N(error2);
          }
        }
      }
    }
    const allEntries = $Rb([...this.c, ...target.c], (entry) => entry.id).sort((entryA, entryB) => entryA.timestamp - entryB.timestamp);
    const targetWorkingCopyResource = $Kg(target.f);
    this.y(targetWorkingCopyResource);
    const targetWorkingCopyName = $Kg(target.g);
    for (const entry of allEntries) {
      this.c.push({
        id: entry.id,
        location: $vh(targetHistoryEntriesFolder, entry.id),
        source: entry.source,
        sourceDescription: entry.sourceDescription,
        timestamp: entry.timestamp,
        workingCopy: {
          resource: targetWorkingCopyResource,
          name: targetWorkingCopyName
        }
      });
    }
    await this.addEntry(source, sourceDescription, timestamp, token);
    await this.store(token);
  }
  async store(token) {
    if (!this.F()) {
      return;
    }
    await this.m.queue(async () => {
      if (token.isCancellationRequested || !this.F()) {
        return;
      }
      return this.G(token);
    });
  }
  F() {
    return this.l !== this.k;
  }
  async G(token) {
    const historyEntriesFolder = $Kg(this.h);
    await this.C();
    if (token.isCancellationRequested) {
      return void 0;
    }
    await this.H();
    const storedVersion = this.k;
    if (this.c.length === 0) {
      try {
        await this.u.del(historyEntriesFolder, { recursive: true });
      } catch (error) {
        this.N(error);
      }
    } else {
      await this.J();
    }
    this.l = storedVersion;
  }
  async H() {
    const configuredMaxEntries = this.x.getValue(_$ioc.b.MAX_ENTRIES, { resource: this.f });
    if (this.c.length <= configuredMaxEntries) {
      return;
    }
    const entriesToDelete = this.c.slice(0, this.c.length - configuredMaxEntries);
    const entriesToKeep = this.c.slice(this.c.length - configuredMaxEntries);
    for (const entryToDelete of entriesToDelete) {
      await this.I(entryToDelete);
    }
    this.c = entriesToKeep;
    for (const entry of entriesToDelete) {
      this.s.fire({ entry });
    }
  }
  async I(entry) {
    try {
      await this.u.del(entry.location);
    } catch (error) {
      this.N(error);
    }
  }
  async J() {
    const workingCopyResource = $Kg(this.f);
    const historyEntriesListingFile = $Kg(this.i);
    const serializedModel = {
      version: 1,
      resource: workingCopyResource.toString(),
      entries: this.c.map((entry) => {
        return {
          id: entry.id,
          source: entry.source !== _$ioc.a ? entry.source : void 0,
          sourceDescription: entry.sourceDescription,
          timestamp: entry.timestamp
        };
      })
    };
    await this.u.writeFile(historyEntriesListingFile, $Ci.fromString(JSON.stringify(serializedModel)));
  }
  async K() {
    const historyEntriesListingFile = $Kg(this.i);
    let serializedModel = void 0;
    try {
      serializedModel = JSON.parse((await this.u.readFile(historyEntriesListingFile)).value.toString());
    } catch (error) {
      if (!this.M(error)) {
        this.N(error);
      }
    }
    return serializedModel;
  }
  async L() {
    const historyEntriesFolder = $Kg(this.h);
    const historyEntriesNameMatcher = $Kg(this.j);
    let rawEntries = void 0;
    try {
      rawEntries = (await this.u.resolve(historyEntriesFolder, { resolveMetadata: true })).children;
    } catch (error) {
      if (!this.M(error)) {
        this.N(error);
      }
    }
    if (!rawEntries) {
      return void 0;
    }
    return rawEntries.filter(
      (entry) => !$oh(entry.resource, this.i) && // not the listings file
      historyEntriesNameMatcher.test(entry.name)
      // matching our expected file pattern for entries
    );
  }
  M(error) {
    return error instanceof $Fm && error.fileOperationResult === 1;
  }
  N(error) {
    this.w.trace("[Working Copy History Service]", error);
  }
};
var $joc = class $joc2 extends $3c {
  static {
    $joc_1 = this;
  }
  static {
    this.a = $bL.registerSource("moved.source", localize(13617, null));
  }
  static {
    this.b = $bL.registerSource("renamed.source", localize(13618, null));
  }
  constructor(s, t, u, w, y, z, C) {
    super();
    this.s = s;
    this.t = t;
    this.u = u;
    this.w = w;
    this.y = y;
    this.z = z;
    this.C = C;
    this.c = this.B(new $ze());
    this.onDidAddEntry = this.c.event;
    this.f = this.B(new $ze());
    this.onDidChangeEntry = this.f.event;
    this.g = this.B(new $ze());
    this.onDidReplaceEntry = this.g.event;
    this.h = this.B(new $ze());
    this.onDidMoveEntries = this.h.event;
    this.j = this.B(new $ze());
    this.onDidRemoveEntry = this.j.event;
    this.m = this.B(new $ze());
    this.onDidRemoveEntries = this.m.event;
    this.n = new $gi();
    this.r = new $Ec((resource) => this.w.extUri.getComparisonKey(resource));
    this.D();
  }
  async D() {
    let historyHome = void 0;
    try {
      const remoteEnv = await this.t.getEnvironment();
      if (remoteEnv) {
        historyHome = remoteEnv.localHistoryHome;
      }
    } catch (error) {
      this.z.trace(error);
    }
    if (!historyHome) {
      historyHome = this.u.localHistoryHome;
    }
    this.n.complete(historyHome);
  }
  async moveEntries(source, target) {
    const limiter = new $2h($Pkc);
    const promises = [];
    for (const [resource, model] of this.r) {
      if (!this.w.extUri.isEqualOrParent(resource, source)) {
        continue;
      }
      let targetResource;
      if (this.w.extUri.isEqual(source, resource)) {
        targetResource = target;
      } else {
        const index = $7g(resource.path, source.path);
        targetResource = $vh(target, resource.path.substr(index + source.path.length + 1));
      }
      let saveSource;
      if (this.w.extUri.isEqual($uh(resource), $uh(targetResource))) {
        saveSource = $joc_1.b;
      } else {
        saveSource = $joc_1.a;
      }
      promises.push(limiter.queue(() => this.F(model, saveSource, resource, targetResource)));
    }
    if (!promises.length) {
      return [];
    }
    const resources = await Promise.all(promises);
    this.h.fire();
    return resources;
  }
  async F(source, saveSource, sourceWorkingCopyResource, targetWorkingCopyResource) {
    const target = await this.G(targetWorkingCopyResource);
    await source.moveEntries(target, saveSource, CancellationToken.None);
    this.r.delete(sourceWorkingCopyResource);
    this.r.set(targetWorkingCopyResource, source);
    return targetWorkingCopyResource;
  }
  async addEntry({ resource, source, timestamp }, token) {
    if (!this.s.hasProvider(resource)) {
      return void 0;
    }
    const model = await this.G(resource);
    if (token.isCancellationRequested) {
      return void 0;
    }
    return model.addEntry(source, void 0, timestamp, token);
  }
  async updateEntry(entry, properties, token) {
    const model = await this.G(entry.workingCopy.resource);
    if (token.isCancellationRequested) {
      return;
    }
    return model.updateEntry(entry, properties, token);
  }
  async removeEntry(entry, token) {
    const model = await this.G(entry.workingCopy.resource);
    if (token.isCancellationRequested) {
      return false;
    }
    return model.removeEntry(entry, token);
  }
  async removeAll(token) {
    const historyHome = await this.n.p;
    if (token.isCancellationRequested) {
      return;
    }
    this.r.clear();
    await this.s.del(historyHome, { recursive: true });
    this.m.fire();
  }
  async getEntries(resource, token) {
    const model = await this.G(resource);
    if (token.isCancellationRequested) {
      return [];
    }
    const entries2 = await model.getEntries();
    return entries2 ?? [];
  }
  async getAll(token) {
    const historyHome = await this.n.p;
    if (token.isCancellationRequested) {
      return [];
    }
    const all = new $Ec();
    for (const [resource, model] of this.r) {
      const hasInMemoryEntries = await model.hasEntries(
        true
        /* skip resolving because we resolve below from disk */
      );
      if (hasInMemoryEntries) {
        all.set(resource, true);
      }
    }
    try {
      const resolvedHistoryHome = await this.s.resolve(historyHome);
      if (resolvedHistoryHome.children) {
        const limiter = new $2h($Pkc);
        const promises = [];
        for (const child of resolvedHistoryHome.children) {
          promises.push(limiter.queue(async () => {
            if (token.isCancellationRequested) {
              return;
            }
            try {
              const serializedModel = JSON.parse((await this.s.readFile($vh(child.resource, $ioc.ENTRIES_FILE))).value.toString());
              if (serializedModel.entries.length > 0) {
                all.set(URI.parse(serializedModel.resource), true);
              }
            } catch (error) {
            }
          }));
        }
        await Promise.all(promises);
      }
    } catch (error) {
    }
    return Array.from(all.keys());
  }
  async G(resource) {
    const historyHome = await this.n.p;
    let model = this.r.get(resource);
    if (!model) {
      model = new $ioc(resource, historyHome, this.c, this.f, this.g, this.j, this.H(), this.s, this.y, this.z, this.C);
      this.r.set(resource, model);
    }
    return model;
  }
};
$joc = $joc_1 = __decorate([
  __param(0, $km),
  __param(1, $RL),
  __param(2, $US),
  __param(3, $vl),
  __param(4, $ZI),
  __param(5, $wn),
  __param(6, $kl)
], $joc);
var $koc = class $koc2 extends $joc {
  static {
    $koc_1 = this;
  }
  static {
    this.I = 5 * 60 * 1e3;
  }
  // 5min
  constructor(fileService, remoteAgentService, environmentService, uriIdentityService, labelService, N, logService, configurationService) {
    super(fileService, remoteAgentService, environmentService, uriIdentityService, labelService, logService, configurationService);
    this.N = N;
    this.J = typeof this.u.remoteAuthority === "string";
    this.L = this.B(new $ad());
    this.M = this.B(new $8h(() => this.S(this.L.token), $koc_1.I));
    this.O();
  }
  O() {
    if (!this.J) {
      this.B(this.N.onWillShutdown((e) => this.Q(e)));
      this.B(Event2.any(this.onDidAddEntry, this.onDidChangeEntry, this.onDidReplaceEntry, this.onDidRemoveEntry)(() => this.R()));
    }
  }
  H() {
    return {
      flushOnChange: this.J
      /* because the connection might drop anytime */
    };
  }
  Q(e) {
    this.M.dispose();
    this.L.dispose(true);
    e.join(this.S(e.token), { id: "join.workingCopyHistory", label: localize(13619, null) });
  }
  R() {
    if (!this.M.isScheduled()) {
      this.M.schedule();
    }
  }
  async S(token) {
    const limiter = new $2h($Pkc);
    const promises = [];
    const models = Array.from(this.r.values());
    for (const model of models) {
      promises.push(limiter.queue(async () => {
        if (token.isCancellationRequested) {
          return;
        }
        try {
          await model.store(token);
        } catch (error) {
          this.z.trace(error);
        }
      }));
    }
    await Promise.all(promises);
  }
};
$koc = $koc_1 = __decorate([
  __param(0, $km),
  __param(1, $RL),
  __param(2, $US),
  __param(3, $vl),
  __param(4, $ZI),
  __param(5, $KL),
  __param(6, $wn),
  __param(7, $kl)
], $koc);
$Wn.as(Extensions2.Workbench).registerWorkbenchContribution(
  $hoc,
  3
  /* LifecyclePhase.Restored */
);

// out-build/vs/workbench/services/workingCopy/browser/workingCopyHistoryService.js
var $loc = class $loc2 extends $joc {
  constructor(fileService, remoteAgentService, environmentService, uriIdentityService, labelService, logService, configurationService) {
    super(fileService, remoteAgentService, environmentService, uriIdentityService, labelService, logService, configurationService);
  }
  H() {
    return {
      flushOnChange: true
      /* because browsers support no long running shutdown */
    };
  }
};
$loc = __decorate([
  __param(0, $km),
  __param(1, $RL),
  __param(2, $US),
  __param(3, $vl),
  __param(4, $ZI),
  __param(5, $wn),
  __param(6, $kl)
], $loc);
$SC(
  $Okc,
  $loc,
  1
  /* InstantiationType.Delayed */
);

// out-build/vs/platform/userDataSync/common/userDataSyncEnablementService.js
var enablementKey = "sync.enable";
var $moc = class $moc2 extends $3c {
  constructor(c, f, g, h3) {
    super();
    this.c = c;
    this.f = f;
    this.g = g;
    this.h = h3;
    this.a = new $ze();
    this.onDidChangeEnablement = this.a.event;
    this.b = new $ze();
    this.onDidChangeResourceEnablement = this.b.event;
    this.B(c.onDidChangeValue(-1, void 0, this.q)((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($5Bb(resource), -1, true);
  }
  setResourceEnablement(resource, enabled) {
    if (this.isResourceEnabled(resource) !== enabled) {
      const resourceEnablementKey = $5Bb(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 = $RBb.filter((resourceKey2) => $5Bb(resourceKey2) === storageChangeEvent.key)[0];
    if (resourceKey) {
      this.b.fire([resourceKey, this.isResourceEnabled(resourceKey)]);
      return;
    }
  }
};
$moc = __decorate([
  __param(0, $jv),
  __param(1, $zv),
  __param(2, $Xk),
  __param(3, $UBb)
], $moc);

// out-build/vs/workbench/services/userDataSync/browser/userDataSyncEnablementService.js
var $noc = class extends $moc {
  get n() {
    return this.g;
  }
  getResourceSyncStateVersion(resource) {
    return resource === "extensions" ? this.n.options?.settingsSyncOptions?.extensionsSyncStateVersion : void 0;
  }
};
$SC(
  $6Bb,
  $noc,
  1
  /* InstantiationType.Delayed */
);

// out-build/vs/workbench/services/userDataSync/browser/webUserDataSyncEnablementService.js
var $ooc = class extends $noc {
  constructor() {
    super(...arguments);
    this.r = void 0;
  }
  canToggleEnablement() {
    return this.s() && super.canToggleEnablement();
  }
  isEnabled() {
    if (!this.s()) {
      return false;
    }
    if (this.r === void 0) {
      this.r = this.n.options?.settingsSyncOptions?.enabled;
    }
    if (this.r === void 0) {
      this.r = super.isEnabled();
    }
    return this.r;
  }
  setEnablement(enabled) {
    if (enabled && !this.canToggleEnablement()) {
      return;
    }
    if (this.r !== enabled) {
      this.r = enabled;
      super.setEnablement(enabled);
    }
  }
  getResourceSyncStateVersion(resource) {
    return resource === "extensions" ? this.n.options?.settingsSyncOptions?.extensionsSyncStateVersion : void 0;
  }
  s() {
    return !!this.n.options?.workspaceProvider?.trusted;
  }
};
$SC(
  $6Bb,
  $ooc,
  1
  /* InstantiationType.Delayed */
);

// out-build/vs/workbench/services/userDataProfile/browser/userDataProfileStorageService.js
var $poc = class $poc2 extends $_A {
  constructor(storageService, j, m) {
    super(true, storageService);
    this.j = j;
    this.m = m;
    this.h = this.B(new $ze());
    this.onDidChange = this.h.event;
    const disposables = this.B(new $2c());
    this.B(Event2.filter(storageService.onDidChangeTarget, (e) => e.scope === 0, disposables)(() => this.n()));
    this.B(storageService.onDidChangeValue(0, void 0, disposables)((e) => this.r(e)));
  }
  n() {
    this.h.fire({ targetChanges: [this.j.currentProfile], valueChanges: [] });
  }
  r(e) {
    this.h.fire({ targetChanges: [], valueChanges: [{ profile: this.j.currentProfile, changes: [e] }] });
  }
  g(profile) {
    return $mv(profile) ? $6hc.createApplicationStorage(this.m) : $6hc.createProfileStorage(profile, this.m);
  }
};
$poc = __decorate([
  __param(0, $jv),
  __param(1, $gT),
  __param(2, $wn)
], $poc);
$SC(
  $$A,
  $poc,
  1
  /* InstantiationType.Delayed */
);

// out-build/vs/workbench/services/configurationResolver/browser/baseConfigurationResolverService.js
var LAST_INPUT_STORAGE_KEY = "configResolveInputLru";
var LAST_INPUT_CACHE_SIZE = 5;
var $qoc = class _$qoc extends $DY {
  static {
    this.INPUT_OR_COMMAND_VARIABLES_PATTERN = /\${((input|command):(.*?))}/g;
  }
  constructor(context, envVariablesPromise, editorService, e, k, q, r2, t, u, extensionService, w) {
    super({
      getFolderUri: (folderName) => {
        const folder = q.getWorkspace().folders.filter((f) => f.name === folderName).pop();
        return folder ? folder.uri : void 0;
      },
      getWorkspaceFolderCount: () => {
        return q.getWorkspace().folders.length;
      },
      getConfigurationValue: (folderUri, suffix) => {
        return e.getValue(suffix, folderUri ? { resource: folderUri } : {});
      },
      getAppRoot: () => {
        return context.getAppRoot();
      },
      getExecPath: () => {
        return context.getExecPath();
      },
      getFilePath: () => {
        const fileResource = $mL.getOriginalUri(editorService.activeEditor, {
          supportSideBySide: SideBySideEditor.PRIMARY,
          filterByScheme: [Schemas.file, Schemas.vscodeUserData, this.u.defaultUriScheme]
        });
        if (!fileResource) {
          return void 0;
        }
        return this.t.getUriLabel(fileResource, { noPrefix: true });
      },
      getWorkspaceFolderPathForFile: () => {
        const fileResource = $mL.getOriginalUri(editorService.activeEditor, {
          supportSideBySide: SideBySideEditor.PRIMARY,
          filterByScheme: [Schemas.file, Schemas.vscodeUserData, this.u.defaultUriScheme]
        });
        if (!fileResource) {
          return void 0;
        }
        const wsFolder = q.getWorkspaceFolder(fileResource);
        if (!wsFolder) {
          return void 0;
        }
        return this.t.getUriLabel(wsFolder.uri, { noPrefix: true });
      },
      getSelectedText: () => {
        const activeTextEditorControl = editorService.activeTextEditorControl;
        let activeControl = null;
        if ($P5(activeTextEditorControl)) {
          activeControl = activeTextEditorControl;
        } else if ($Q5(activeTextEditorControl)) {
          const original = activeTextEditorControl.getOriginalEditor();
          const modified = activeTextEditorControl.getModifiedEditor();
          activeControl = original.hasWidgetFocus() ? original : modified;
        }
        const activeModel = activeControl?.getModel();
        const activeSelection = activeControl?.getSelection();
        if (activeModel && activeSelection) {
          return activeModel.getValueInRange(activeSelection);
        }
        return void 0;
      },
      getLineNumber: () => {
        const activeTextEditorControl = editorService.activeTextEditorControl;
        if ($P5(activeTextEditorControl)) {
          const selection = activeTextEditorControl.getSelection();
          if (selection) {
            const lineNumber = selection.positionLineNumber;
            return String(lineNumber);
          }
        }
        return void 0;
      },
      getExtension: (id2) => {
        return extensionService.getExtension(id2);
      }
    }, t, u.userHome().then((home2) => home2.path), envVariablesPromise);
    this.e = e;
    this.k = k;
    this.q = q;
    this.r = r2;
    this.t = t;
    this.u = u;
    this.w = w;
    this.d = new $3h();
  }
  async resolveWithInteractionReplace(folder, config, section, variables, target) {
    config = await this.resolveAnyAsync(folder, config);
    return this.resolveWithInteraction(folder, config, section, variables, target).then((mapping2) => {
      if (!mapping2) {
        return null;
      } else if (mapping2.size > 0) {
        return this.resolveAnyAsync(folder, config, Object.fromEntries(mapping2));
      } else {
        return config;
      }
    });
  }
  async resolveWithInteraction(folder, config, section, variables, target) {
    const resolved = await this.resolveAnyMap(folder, config);
    config = resolved.newConfig;
    const allVariableMapping = resolved.resolvedVariables;
    return this.y(folder, config, variables, section, target).then((inputOrCommandMapping) => {
      if (this.x(inputOrCommandMapping, allVariableMapping)) {
        return allVariableMapping;
      }
      return void 0;
    });
  }
  /**
   * Add all items from newMapping to fullMapping. Returns false if newMapping is undefined.
   */
  x(newMapping, fullMapping) {
    if (!newMapping) {
      return false;
    }
    for (const [key2, value] of Object.entries(newMapping)) {
      fullMapping.set(key2, value);
    }
    return true;
  }
  /**
   * Finds and executes all input and command variables in the given configuration and returns their values as a dictionary.
   * Please note: this method does not substitute the input or command variables (so the configuration is not modified).
   * The returned dictionary can be passed to "resolvePlatform" for the actual substitution.
   * See #6569.
   *
   * @param variableToCommandMap Aliases for commands
   */
  async y(folder, configuration2, variableToCommandMap, section, target) {
    if (!configuration2) {
      return Promise.resolve(void 0);
    }
    let inputs = [];
    if (this.q.getWorkbenchState() !== 1 && section) {
      const overrides = folder ? { resource: folder.uri } : {};
      const result = this.e.inspect(section, overrides);
      if (result && (result.userValue || result.workspaceValue || result.workspaceFolderValue)) {
        switch (target) {
          case 2:
            inputs = result.userValue?.inputs;
            break;
          case 5:
            inputs = result.workspaceValue?.inputs;
            break;
          default:
            inputs = result.workspaceFolderValue?.inputs;
        }
      } else {
        const valueResult = this.e.getValue(section, overrides);
        if (valueResult) {
          inputs = valueResult.inputs;
        }
      }
    }
    const variables = [];
    this.z(configuration2, variables);
    const variableValues = /* @__PURE__ */ Object.create(null);
    for (const variable of variables) {
      const [type, name] = variable.split(":", 2);
      let result;
      switch (type) {
        case "input":
          result = await this.A(section, name, inputs);
          break;
        case "command": {
          const commandId = (variableToCommandMap ? variableToCommandMap[name] : void 0) || name;
          result = await this.k.executeCommand(commandId, configuration2);
          if (typeof result !== "string" && !$Ig(result)) {
            throw new Error(localize(12611, null, commandId));
          }
          break;
        }
        default:
          if (this.h.has(variable)) {
            result = await this.h.get(variable)();
          }
      }
      if (typeof result === "string") {
        variableValues[variable] = result;
      } else {
        return void 0;
      }
    }
    return variableValues;
  }
  /**
   * Recursively finds all command or input variables in object and pushes them into variables.
   * @param object object is searched for variables.
   * @param variables All found variables are returned in variables.
   */
  z(object, variables) {
    if (typeof object === "string") {
      let matches;
      while ((matches = _$qoc.INPUT_OR_COMMAND_VARIABLES_PATTERN.exec(object)) !== null) {
        if (matches.length === 4) {
          const command4 = matches[1];
          if (variables.indexOf(command4) < 0) {
            variables.push(command4);
          }
        }
      }
      for (const contributed of this.h.keys()) {
        if (variables.indexOf(contributed) < 0 && object.indexOf("${" + contributed + "}") >= 0) {
          variables.push(contributed);
        }
      }
    } else if (Array.isArray(object)) {
      for (const value of object) {
        this.z(value, variables);
      }
    } else if (object) {
      for (const value of Object.values(object)) {
        this.z(value, variables);
      }
    }
  }
  /**
   * Takes the provided input info and shows the quick pick so the user can provide the value for the input
   * @param variable Name of the input variable.
   * @param inputInfos Information about each possible input variable.
   */
  A(section, variable, inputInfos) {
    if (!inputInfos) {
      return Promise.reject(new Error(localize(12612, null, variable, "inputs")));
    }
    const info = inputInfos.filter((item) => item.id === variable).pop();
    if (info) {
      const missingAttribute = (attrName) => {
        throw new Error(localize(12613, null, variable, info.type, attrName));
      };
      const defaultValueMap = this.C();
      const defaultValueKey = `${section}.${variable}`;
      const previousPickedValue = defaultValueMap.get(defaultValueKey);
      switch (info.type) {
        case "promptString": {
          if (!$zg(info.description)) {
            missingAttribute("description");
          }
          const inputOptions2 = { prompt: info.description, ignoreFocusLost: true, value: previousPickedValue };
          if (info.default) {
            inputOptions2.value = info.default;
          }
          if (info.password) {
            inputOptions2.password = info.password;
          }
          return this.d.queue(() => this.r.input(inputOptions2)).then((resolvedInput) => {
            if (typeof resolvedInput === "string") {
              this.B(defaultValueMap.set(defaultValueKey, resolvedInput));
            }
            return resolvedInput;
          });
        }
        case "pickString": {
          if (!$zg(info.description)) {
            missingAttribute("description");
          }
          if (Array.isArray(info.options)) {
            for (const pickOption of info.options) {
              if (!$zg(pickOption) && !$zg(pickOption.value)) {
                missingAttribute("value");
              }
            }
          } else {
            missingAttribute("options");
          }
          const picks = new Array();
          for (const pickOption of info.options) {
            const value = $zg(pickOption) ? pickOption : pickOption.value;
            const label3 = $zg(pickOption) ? void 0 : pickOption.label;
            const item = {
              label: label3 ? `${label3}: ${value}` : value,
              value
            };
            if (value === info.default) {
              item.description = localize(12614, null);
              picks.unshift(item);
            } else if (!info.default && value === previousPickedValue) {
              picks.unshift(item);
            } else {
              picks.push(item);
            }
          }
          const pickOptions = { placeHolder: info.description, matchOnDetail: true, ignoreFocusLost: true };
          return this.d.queue(() => this.r.pick(picks, pickOptions, void 0)).then((resolvedInput) => {
            if (resolvedInput) {
              const value = resolvedInput.value;
              this.B(defaultValueMap.set(defaultValueKey, value));
              return value;
            }
            return void 0;
          });
        }
        case "command": {
          if (!$zg(info.command)) {
            missingAttribute("command");
          }
          return this.d.queue(() => this.k.executeCommand(info.command, info.args)).then((result) => {
            if (typeof result === "string" || $Ig(result)) {
              return result;
            }
            throw new Error(localize(12615, null, variable, info.command));
          });
        }
        default:
          throw new Error(localize(12616, null, variable));
      }
    }
    return Promise.reject(new Error(localize(12617, null, variable)));
  }
  B(lru) {
    this.w.store(
      LAST_INPUT_STORAGE_KEY,
      JSON.stringify(lru.toJSON()),
      1,
      1
      /* StorageTarget.MACHINE */
    );
  }
  C() {
    const contents = this.w.get(
      LAST_INPUT_STORAGE_KEY,
      1
      /* StorageScope.WORKSPACE */
    );
    const lru = new $Hc(LAST_INPUT_CACHE_SIZE);
    try {
      if (contents) {
        lru.fromJSON(JSON.parse(contents));
      }
    } catch {
    }
    return lru;
  }
};

// out-build/vs/workbench/services/configurationResolver/browser/configurationResolverService.js
var $roc = class $roc2 extends $qoc {
  constructor(editorService, configurationService, commandService, workspaceContextService, quickInputService, labelService, pathService, extensionService, storageService) {
    super({ getAppRoot: () => void 0, getExecPath: () => void 0 }, Promise.resolve(/* @__PURE__ */ Object.create(null)), editorService, configurationService, commandService, workspaceContextService, quickInputService, labelService, pathService, extensionService, storageService);
  }
};
$roc = __decorate([
  __param(0, $mJ),
  __param(1, $kl),
  __param(2, $sn),
  __param(3, $Zk),
  __param(4, $1M),
  __param(5, $ZI),
  __param(6, $aT),
  __param(7, $wN),
  __param(8, $jv)
], $roc);
$SC(
  $nY,
  $roc,
  1
  /* InstantiationType.Delayed */
);

// out-build/vs/platform/extensionResourceLoader/browser/extensionResourceLoaderService.js
var ExtensionResourceLoaderService = class ExtensionResourceLoaderService2 extends $Qlb {
  constructor(fileService, storageService, productService, environmentService, configurationService, m) {
    super(fileService, storageService, productService, environmentService, configurationService);
    this.m = m;
  }
  async readExtensionResource(uri) {
    uri = $ih.uriToBrowserUri(uri);
    if (uri.scheme !== Schemas.http && uri.scheme !== Schemas.https && uri.scheme !== Schemas.data) {
      const result = await this.c.readFile(uri);
      return result.value.toString();
    }
    const requestInit = {};
    if (this.isExtensionGalleryResource(uri)) {
      requestInit.headers = await this.h();
      requestInit.mode = "cors";
    }
    const response = await fetch(uri.toString(true), requestInit);
    if (response.status !== 200) {
      this.m.info(`Request to '${uri.toString(true)}' failed with status code ${response.status}`);
      throw new Error(response.statusText);
    }
    return response.text();
  }
};
ExtensionResourceLoaderService = __decorate([
  __param(0, $km),
  __param(1, $jv),
  __param(2, $Vu),
  __param(3, $Xk),
  __param(4, $kl),
  __param(5, $wn)
], ExtensionResourceLoaderService);
$SC(
  $Olb,
  ExtensionResourceLoaderService,
  1
  /* InstantiationType.Delayed */
);

// out-build/vs/platform/contextview/browser/contextMenuHandler.js
var $soc = class {
  constructor(g, h3, i2, j) {
    this.g = g;
    this.h = h3;
    this.i = i2;
    this.j = j;
    this.a = null;
    this.b = null;
    this.c = null;
    this.d = null;
    this.f = { blockMouse: true };
  }
  configure(options3) {
    this.f = options3;
  }
  showContextMenu(delegate) {
    const actions = delegate.getActions();
    if (!actions.length) {
      return;
    }
    this.a = $Lj();
    let menu;
    const shadowRootElement = $Uj(delegate.domForShadowRoot) ? delegate.domForShadowRoot : void 0;
    this.g.showContextView({
      getAnchor: () => delegate.getAnchor(),
      canRelayout: false,
      anchorAlignment: delegate.anchorAlignment,
      anchorAxisAlignment: delegate.anchorAxisAlignment,
      render: (container2) => {
        this.b = container2;
        const className = delegate.getMenuClassName ? delegate.getMenuClassName() : "";
        if (className) {
          container2.className += " " + className;
        }
        if (this.f.blockMouse) {
          this.c = container2.appendChild($(".context-view-block"));
          this.c.style.position = "fixed";
          this.c.style.cursor = "initial";
          this.c.style.left = "0";
          this.c.style.top = "0";
          this.c.style.width = "100%";
          this.c.style.height = "100%";
          this.c.style.zIndex = "-1";
          this.d?.dispose();
          this.d = $_i(this.c, $7j.MOUSE_DOWN, (e) => e.stopPropagation());
        }
        const menuDisposables = new $2c();
        const actionRunner = delegate.actionRunner || new $Vm();
        actionRunner.onWillRun((evt) => this.k(evt, !delegate.skipTelemetry), this, menuDisposables);
        actionRunner.onDidRun(this.l, this, menuDisposables);
        menu = new $f2(container2, actions, {
          actionViewItemProvider: delegate.getActionViewItem,
          context: delegate.getActionsContext ? delegate.getActionsContext() : null,
          actionRunner,
          getKeyBinding: delegate.getKeyBinding ? delegate.getKeyBinding : (action) => this.j.lookupKeybinding(action.id)
        }, $M$);
        menu.onDidCancel(() => this.g.hideContextView(true), null, menuDisposables);
        menu.onDidBlur(() => this.g.hideContextView(true), null, menuDisposables);
        const targetWindow = getWindow(container2);
        menuDisposables.add($_i(targetWindow, $7j.BLUR, () => this.g.hideContextView(true)));
        menuDisposables.add($_i(targetWindow, $7j.MOUSE_DOWN, (e) => {
          if (e.defaultPrevented) {
            return;
          }
          const event = new $lf(targetWindow, e);
          let element = event.target;
          if (event.rightButton) {
            return;
          }
          while (element) {
            if (element === container2) {
              return;
            }
            element = element.parentElement;
          }
          this.g.hideContextView(true);
        }));
        return $Zc(menuDisposables, menu);
      },
      focus: () => {
        menu?.focus(!!delegate.autoSelectFirstItem);
      },
      onHide: (didCancel) => {
        delegate.onHide?.(!!didCancel);
        if (this.c) {
          this.c.remove();
          this.c = null;
        }
        this.d?.dispose();
        this.d = null;
        if (!!this.b && ($Lj() === this.b || $Dj($Lj(), this.b))) {
          this.a?.focus();
        }
        this.b = null;
      }
    }, shadowRootElement, !!shadowRootElement);
  }
  k(e, logTelemetry) {
    if (logTelemetry) {
      this.h.publicLog2("workbenchActionExecuted", { id: e.action.id, from: "contextMenu" });
    }
    this.g.hideContextView(false);
  }
  l(e) {
    if (e.error && !$kb(e.error)) {
      this.i.error(e.error);
    }
  }
};

// out-build/vs/platform/contextview/browser/contextMenuService.js
var $toc = class $toc2 extends $3c {
  get b() {
    if (!this.a) {
      this.a = new $soc(this.j, this.g, this.h, this.m);
    }
    return this.a;
  }
  constructor(g, h3, j, m, n, s) {
    super();
    this.g = g;
    this.h = h3;
    this.j = j;
    this.m = m;
    this.n = n;
    this.s = s;
    this.a = void 0;
    this.c = this.q.add(new $ze());
    this.onDidShowContextMenu = this.c.event;
    this.f = this.q.add(new $ze());
    this.onDidHideContextMenu = this.f.event;
  }
  configure(options3) {
    this.b.configure(options3);
  }
  // ContextMenu
  showContextMenu(delegate) {
    delegate = ContextMenuMenuDelegate.transform(delegate, this.n, this.s);
    this.b.showContextMenu({
      ...delegate,
      onHide: (didCancel) => {
        delegate.onHide?.(didCancel);
        this.f.fire();
      }
    });
    $yk.getInstance().resetKeyStatus();
    this.c.fire();
  }
};
$toc = __decorate([
  __param(0, $zv),
  __param(1, $PJ),
  __param(2, $40),
  __param(3, $Ty),
  __param(4, $cJ),
  __param(5, $on)
], $toc);
var ContextMenuMenuDelegate;
(function(ContextMenuMenuDelegate2) {
  function is(thing) {
    return thing && thing.menuId instanceof $bJ;
  }
  function transform(delegate, menuService, globalContextKeyService) {
    if (!is(delegate)) {
      return delegate;
    }
    const { menuId, menuActionOptions, contextKeyService } = delegate;
    return {
      ...delegate,
      getActions: () => {
        let target = [];
        if (menuId) {
          const menu = menuService.getMenuActions(menuId, contextKeyService ?? globalContextKeyService, menuActionOptions);
          target = $P$(menu);
        }
        if (!delegate.getActions) {
          return target;
        } else {
          return $Wm.join(delegate.getActions(), target);
        }
      }
    };
  }
  ContextMenuMenuDelegate2.transform = transform;
})(ContextMenuMenuDelegate || (ContextMenuMenuDelegate = {}));

// out-build/vs/platform/extensionManagement/common/extensionTipsService.js
var $uoc = class $uoc2 extends $3c {
  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($vh(folder, configPath))).value.toString();
        for (const [key2, value] of Object.entries(tip.recommendations)) {
          if (!value.contentPattern || new RegExp(value.contentPattern, "mig").test(content)) {
            result.push({
              extensionId: key2,
              extensionName: value.name,
              configName: tip.configName,
              important: !!value.important,
              isExtensionPack: !!value.isExtensionPack,
              whenNotInstalled: value.whenNotInstalled
            });
          }
        }
      } catch (error) {
      }
    }
    return result;
  }
};
$uoc = __decorate([
  __param(0, $km),
  __param(1, $Vu)
], $uoc);

// out-build/vs/workbench/services/extensionManagement/common/extensionManagementService.js
var WorkspaceExtensionsManagementService_1;
function isGalleryExtension2(extension) {
  return extension.type === "gallery";
}
var $woc = class $woc2 extends $3c {
  constructor(n, t, u, w, y, z, C, D, F, G, H, I, J, L, M, N) {
    super();
    this.n = n;
    this.t = t;
    this.u = u;
    this.w = w;
    this.y = y;
    this.z = z;
    this.C = C;
    this.D = D;
    this.F = F;
    this.G = G;
    this.H = H;
    this.I = I;
    this.J = J;
    this.L = L;
    this.M = M;
    this.N = N;
    this.a = this.B(new $ze());
    this.b = this.B(new $ze());
    this.c = this.B(new $ze());
    this.f = this.B(new $ze());
    this.g = this.B(new $ze());
    this.h = this.B(new $ze());
    this.j = [];
    this.m = this.B(this.L.createInstance(WorkspaceExtensionsManagementService));
    this.onDidEnableExtensions = this.m.onDidChangeInvalidExtensions;
    if (this.n.localExtensionManagementServer) {
      this.j.push(this.n.localExtensionManagementServer);
    }
    if (this.n.remoteExtensionManagementServer) {
      this.j.push(this.n.remoteExtensionManagementServer);
    }
    if (this.n.webExtensionManagementServer) {
      this.j.push(this.n.webExtensionManagementServer);
    }
    const onInstallExtensionEventMultiplexer = this.B(new $Fe());
    this.B(onInstallExtensionEventMultiplexer.add(this.a.event));
    this.onInstallExtension = onInstallExtensionEventMultiplexer.event;
    const onDidInstallExtensionsEventMultiplexer = this.B(new $Fe());
    this.B(onDidInstallExtensionsEventMultiplexer.add(this.b.event));
    this.onDidInstallExtensions = onDidInstallExtensionsEventMultiplexer.event;
    const onDidProfileAwareInstallExtensionsEventMultiplexer = this.B(new $Fe());
    this.B(onDidProfileAwareInstallExtensionsEventMultiplexer.add(this.g.event));
    this.onProfileAwareDidInstallExtensions = onDidProfileAwareInstallExtensionsEventMultiplexer.event;
    const onUninstallExtensionEventMultiplexer = this.B(new $Fe());
    this.B(onUninstallExtensionEventMultiplexer.add(this.c.event));
    this.onUninstallExtension = onUninstallExtensionEventMultiplexer.event;
    const onDidUninstallExtensionEventMultiplexer = this.B(new $Fe());
    this.B(onDidUninstallExtensionEventMultiplexer.add(this.f.event));
    this.onDidUninstallExtension = onDidUninstallExtensionEventMultiplexer.event;
    const onDidProfileAwareUninstallExtensionEventMultiplexer = this.B(new $Fe());
    this.B(onDidProfileAwareUninstallExtensionEventMultiplexer.add(this.h.event));
    this.onProfileAwareDidUninstallExtension = onDidProfileAwareUninstallExtensionEventMultiplexer.event;
    const onDidUpdateExtensionMetadaEventMultiplexer = this.B(new $Fe());
    this.onDidUpdateExtensionMetadata = onDidUpdateExtensionMetadaEventMultiplexer.event;
    const onDidProfileAwareUpdateExtensionMetadaEventMultiplexer = this.B(new $Fe());
    this.onProfileAwareDidUpdateExtensionMetadata = onDidProfileAwareUpdateExtensionMetadaEventMultiplexer.event;
    const onDidChangeProfileEventMultiplexer = this.B(new $Fe());
    this.onDidChangeProfile = onDidChangeProfileEventMultiplexer.event;
    for (const server of this.j) {
      this.B(onInstallExtensionEventMultiplexer.add(Event2.map(server.extensionManagementService.onInstallExtension, (e) => ({ ...e, server }))));
      this.B(onDidInstallExtensionsEventMultiplexer.add(server.extensionManagementService.onDidInstallExtensions));
      this.B(onDidProfileAwareInstallExtensionsEventMultiplexer.add(server.extensionManagementService.onProfileAwareDidInstallExtensions));
      this.B(onUninstallExtensionEventMultiplexer.add(Event2.map(server.extensionManagementService.onUninstallExtension, (e) => ({ ...e, server }))));
      this.B(onDidUninstallExtensionEventMultiplexer.add(Event2.map(server.extensionManagementService.onDidUninstallExtension, (e) => ({ ...e, server }))));
      this.B(onDidProfileAwareUninstallExtensionEventMultiplexer.add(Event2.map(server.extensionManagementService.onProfileAwareDidUninstallExtension, (e) => ({ ...e, server }))));
      this.B(onDidUpdateExtensionMetadaEventMultiplexer.add(server.extensionManagementService.onDidUpdateExtensionMetadata));
      this.B(onDidProfileAwareUpdateExtensionMetadaEventMultiplexer.add(server.extensionManagementService.onProfileAwareDidUpdateExtensionMetadata));
      this.B(onDidChangeProfileEventMultiplexer.add(Event2.map(server.extensionManagementService.onDidChangeProfile, (e) => ({ ...e, server }))));
    }
  }
  async getInstalled(type, profileLocation, productVersion) {
    const result = [];
    await Promise.all(this.j.map(async (server) => {
      const installed = await server.extensionManagementService.getInstalled(type, profileLocation, productVersion);
      if (server === this.bb()) {
        const workspaceExtensions = await this.getInstalledWorkspaceExtensions(true);
        installed.push(...workspaceExtensions);
      }
      result.push(...installed);
    }));
    return result;
  }
  uninstall(extension, options3) {
    return this.uninstallExtensions([{ extension, options: options3 }]);
  }
  async uninstallExtensions(extensions) {
    const workspaceExtensions = [];
    const groupedExtensions = /* @__PURE__ */ new Map();
    const addExtensionToServer = (server, extension, options3) => {
      let extensions2 = groupedExtensions.get(server);
      if (!extensions2) {
        groupedExtensions.set(server, extensions2 = []);
      }
      extensions2.push({ extension, options: options3 });
    };
    for (const { extension, options: options3 } of extensions) {
      if (extension.isWorkspaceScoped) {
        workspaceExtensions.push(extension);
        continue;
      }
      const server = this.ab(extension);
      if (!server) {
        throw new Error(`Invalid location ${extension.location.toString()}`);
      }
      addExtensionToServer(server, extension, options3);
      if (this.j.length > 1 && $9z(extension.manifest)) {
        const otherServers = this.j.filter((s) => s !== server);
        for (const otherServer of otherServers) {
          const installed = await otherServer.extensionManagementService.getInstalled();
          const extensionInOtherServer = installed.find((i2) => !i2.isBuiltin && $DA(i2.identifier, extension.identifier));
          if (extensionInOtherServer) {
            addExtensionToServer(otherServer, extensionInOtherServer, options3);
          }
        }
      }
    }
    const promises = [];
    for (const workspaceExtension of workspaceExtensions) {
      promises.push(this.W(workspaceExtension));
    }
    for (const [server, extensions2] of groupedExtensions.entries()) {
      promises.push(this.O(server, extensions2));
    }
    const result = await Promise.allSettled(promises);
    const errors = result.filter((r2) => r2.status === "rejected").map((r2) => r2.reason);
    if (errors.length) {
      throw new Error(errors.map((e) => e.message).join("\n"));
    }
  }
  async O(server, extensions) {
    if (server === this.n.localExtensionManagementServer && this.n.remoteExtensionManagementServer) {
      for (const { extension } of extensions) {
        const installedExtensions = await this.n.remoteExtensionManagementServer.extensionManagementService.getInstalled(
          1
          /* ExtensionType.User */
        );
        const dependentNonUIExtensions = installedExtensions.filter((i2) => !this.H.prefersExecuteOnUI(i2.manifest) && i2.manifest.extensionDependencies && i2.manifest.extensionDependencies.some((id2) => $DA({ id: id2 }, extension.identifier)));
        if (dependentNonUIExtensions.length) {
          throw new Error(this.P(extension, dependentNonUIExtensions));
        }
      }
    }
    return server.extensionManagementService.uninstallExtensions(extensions);
  }
  P(extension, dependents) {
    if (dependents.length === 1) {
      return localize(12747, null, extension.manifest.displayName || extension.manifest.name, dependents[0].manifest.displayName || dependents[0].manifest.name);
    }
    if (dependents.length === 2) {
      return localize(12748, null, extension.manifest.displayName || extension.manifest.name, dependents[0].manifest.displayName || dependents[0].manifest.name, dependents[1].manifest.displayName || dependents[1].manifest.name);
    }
    return localize(12749, null, extension.manifest.displayName || extension.manifest.name, dependents[0].manifest.displayName || dependents[0].manifest.name, dependents[1].manifest.displayName || dependents[1].manifest.name);
  }
  async reinstallFromGallery(extension) {
    const server = this.ab(extension);
    if (server) {
      await this.cb(extension.manifest, false);
      return server.extensionManagementService.reinstallFromGallery(extension);
    }
    return Promise.reject(`Invalid location ${extension.location.toString()}`);
  }
  updateMetadata(extension, metadata) {
    const server = this.ab(extension);
    if (server) {
      const profile = extension.isApplicationScoped ? this.w.defaultProfile : this.u.currentProfile;
      return server.extensionManagementService.updateMetadata(extension, metadata, profile.extensionsResource);
    }
    return Promise.reject(`Invalid location ${extension.location.toString()}`);
  }
  async resetPinnedStateForAllUserExtensions(pinned) {
    await Promise.allSettled(this.j.map((server) => server.extensionManagementService.resetPinnedStateForAllUserExtensions(pinned)));
  }
  zip(extension) {
    const server = this.ab(extension);
    if (server) {
      return server.extensionManagementService.zip(extension);
    }
    return Promise.reject(`Invalid location ${extension.location.toString()}`);
  }
  download(extension, operation, donotVerifySignature) {
    if (this.n.localExtensionManagementServer) {
      return this.n.localExtensionManagementServer.extensionManagementService.download(extension, operation, donotVerifySignature);
    }
    throw new Error("Cannot download extension");
  }
  async install(vsix, options3) {
    const manifest = await this.getManifest(vsix);
    return this.installVSIX(vsix, manifest, options3);
  }
  async installVSIX(vsix, manifest, options3) {
    const serversToInstall = this.Q(manifest);
    if (serversToInstall?.length) {
      await this.cb(manifest, false);
      const [local] = await Promises.settled(serversToInstall.map((server) => this.R(vsix, server, options3)));
      return local;
    }
    return Promise.reject("No Servers to Install");
  }
  Q(manifest) {
    if (this.n.localExtensionManagementServer && this.n.remoteExtensionManagementServer) {
      if ($9z(manifest)) {
        return [this.n.localExtensionManagementServer, this.n.remoteExtensionManagementServer];
      }
      if (this.H.prefersExecuteOnUI(manifest)) {
        return [this.n.localExtensionManagementServer];
      }
      return [this.n.remoteExtensionManagementServer];
    }
    if (this.n.localExtensionManagementServer) {
      return [this.n.localExtensionManagementServer];
    }
    if (this.n.remoteExtensionManagementServer) {
      return [this.n.remoteExtensionManagementServer];
    }
    return void 0;
  }
  async installFromLocation(location3) {
    if (location3.scheme === Schemas.file) {
      if (this.n.localExtensionManagementServer) {
        return this.n.localExtensionManagementServer.extensionManagementService.installFromLocation(location3, this.u.currentProfile.extensionsResource);
      }
      throw new Error("Local extension management server is not found");
    }
    if (location3.scheme === Schemas.vscodeRemote) {
      if (this.n.remoteExtensionManagementServer) {
        return this.n.remoteExtensionManagementServer.extensionManagementService.installFromLocation(location3, this.u.currentProfile.extensionsResource);
      }
      throw new Error("Remote extension management server is not found");
    }
    if (!this.n.webExtensionManagementServer) {
      throw new Error("Web extension management server is not found");
    }
    return this.n.webExtensionManagementServer.extensionManagementService.installFromLocation(location3, this.u.currentProfile.extensionsResource);
  }
  R(vsix, server, options3) {
    return server.extensionManagementService.install(vsix, options3);
  }
  getManifest(vsix) {
    if (vsix.scheme === Schemas.file && this.n.localExtensionManagementServer) {
      return this.n.localExtensionManagementServer.extensionManagementService.getManifest(vsix);
    }
    if (vsix.scheme === Schemas.file && this.n.remoteExtensionManagementServer) {
      return this.n.remoteExtensionManagementServer.extensionManagementService.getManifest(vsix);
    }
    if (vsix.scheme === Schemas.vscodeRemote && this.n.remoteExtensionManagementServer) {
      return this.n.remoteExtensionManagementServer.extensionManagementService.getManifest(vsix);
    }
    return Promise.reject("No Servers");
  }
  async canInstall(extension) {
    if (isGalleryExtension2(extension)) {
      return this.S(extension);
    }
    return this.U(extension);
  }
  async S(gallery) {
    if (this.n.localExtensionManagementServer && await this.n.localExtensionManagementServer.extensionManagementService.canInstall(gallery) === true) {
      return true;
    }
    const manifest = await this.t.getManifest(gallery, CancellationToken.None);
    if (!manifest) {
      return new $bm().appendText(localize(12750, null));
    }
    if (this.n.remoteExtensionManagementServer && await this.n.remoteExtensionManagementServer.extensionManagementService.canInstall(gallery) === true && this.H.canExecuteOnWorkspace(manifest)) {
      return true;
    }
    if (this.n.webExtensionManagementServer && await this.n.webExtensionManagementServer.extensionManagementService.canInstall(gallery) === true && this.H.canExecuteOnWeb(manifest)) {
      return true;
    }
    return new $bm().appendText(localize(12751, null, gallery.displayName || gallery.name));
  }
  async U(extension) {
    if (this.n.localExtensionManagementServer) {
      return true;
    }
    if (this.n.remoteExtensionManagementServer && this.H.canExecuteOnWorkspace(extension.manifest)) {
      return true;
    }
    if (this.n.webExtensionManagementServer && this.H.canExecuteOnWeb(extension.manifest)) {
      return true;
    }
    return new $bm().appendText(localize(12752, null, extension.manifest.displayName ?? extension.identifier.id));
  }
  async updateFromGallery(gallery, extension, installOptions) {
    const server = this.ab(extension);
    if (!server) {
      return Promise.reject(`Invalid location ${extension.location.toString()}`);
    }
    const servers = [];
    if ($9z(extension.manifest)) {
      servers.push(...this.j.filter((server2) => server2 !== this.n.webExtensionManagementServer));
    } else {
      servers.push(server);
    }
    installOptions = { ...installOptions || {}, isApplicationScoped: extension.isApplicationScoped };
    return Promises.settled(servers.map((server2) => server2.extensionManagementService.installFromGallery(gallery, installOptions))).then(([local]) => local);
  }
  async installGalleryExtensions(extensions) {
    const results = /* @__PURE__ */ new Map();
    const extensionsByServer = /* @__PURE__ */ new Map();
    await Promise.all(extensions.map(async ({ extension, options: options3 }) => {
      try {
        const servers = await this.X(extension, options3);
        if (!options3.isMachineScoped && this.Z()) {
          if (this.n.localExtensionManagementServer && !servers.includes(this.n.localExtensionManagementServer) && await this.n.localExtensionManagementServer.extensionManagementService.canInstall(extension) === true) {
            servers.push(this.n.localExtensionManagementServer);
          }
        }
        for (const server of servers) {
          let exensions = extensionsByServer.get(server);
          if (!exensions) {
            extensionsByServer.set(server, exensions = []);
          }
          exensions.push({ extension, options: options3 });
        }
      } catch (error) {
        results.set(extension.identifier.id.toLowerCase(), {
          identifier: extension.identifier,
          source: extension,
          error,
          operation: 2,
          profileLocation: options3.profileLocation ?? this.u.currentProfile.extensionsResource
        });
      }
    }));
    await Promise.all([...extensionsByServer.entries()].map(async ([server, extensions2]) => {
      const serverResults = await server.extensionManagementService.installGalleryExtensions(extensions2);
      for (const result of serverResults) {
        results.set(result.identifier.id.toLowerCase(), result);
      }
    }));
    return [...results.values()];
  }
  async installFromGallery(gallery, installOptions) {
    const servers = await this.X(gallery, installOptions);
    if (!installOptions || $Gg(installOptions.isMachineScoped)) {
      const isMachineScoped = await this.$([gallery]);
      installOptions = { ...installOptions || {}, isMachineScoped };
    }
    if (installOptions.installEverywhere || !installOptions.isMachineScoped && this.Z()) {
      if (this.n.localExtensionManagementServer && !servers.includes(this.n.localExtensionManagementServer) && await this.n.localExtensionManagementServer.extensionManagementService.canInstall(gallery) === true) {
        servers.push(this.n.localExtensionManagementServer);
      }
    }
    return Promises.settled(servers.map((server) => server.extensionManagementService.installFromGallery(gallery, installOptions))).then(([local]) => local);
  }
  async getExtensions(locations) {
    const scannedExtensions = await this.M.scanMultipleExtensions(locations, 1, { includeInvalid: true });
    const result = [];
    await Promise.all(scannedExtensions.map(async (scannedExtension) => {
      const workspaceExtension = await this.m.toLocalWorkspaceExtension(scannedExtension);
      if (workspaceExtension) {
        result.push({
          type: "resource",
          identifier: workspaceExtension.identifier,
          location: workspaceExtension.location,
          manifest: workspaceExtension.manifest,
          changelogUri: workspaceExtension.changelogUrl,
          readmeUri: workspaceExtension.readmeUrl
        });
      }
    }));
    return result;
  }
  getInstalledWorkspaceExtensionLocations() {
    return this.m.getInstalledWorkspaceExtensionsLocations();
  }
  async getInstalledWorkspaceExtensions(includeInvalid) {
    return this.m.getInstalled(includeInvalid);
  }
  async installResourceExtension(extension, installOptions) {
    if (!this.U(extension)) {
      throw new Error("This extension cannot be installed in the current workspace.");
    }
    if (!installOptions.isWorkspaceScoped) {
      return this.installFromLocation(extension.location);
    }
    this.J.info(`Installing the extension ${extension.identifier.id} from ${extension.location.toString()} in workspace`);
    const server = this.bb();
    this.a.fire({
      identifier: extension.identifier,
      source: extension.location,
      server,
      applicationScoped: false,
      profileLocation: this.u.currentProfile.extensionsResource,
      workspaceScoped: true
    });
    try {
      await this.cb(extension.manifest, true);
      const workspaceExtension = await this.m.install(extension);
      this.J.info(`Successfully installed the extension ${workspaceExtension.identifier.id} from ${extension.location.toString()} in the workspace`);
      this.b.fire([{
        identifier: workspaceExtension.identifier,
        source: extension.location,
        operation: 2,
        applicationScoped: false,
        profileLocation: this.u.currentProfile.extensionsResource,
        local: workspaceExtension,
        workspaceScoped: true
      }]);
      return workspaceExtension;
    } catch (error) {
      this.J.error(`Failed to install the extension ${extension.identifier.id} from ${extension.location.toString()} in the workspace`, $qb(error));
      this.b.fire([{
        identifier: extension.identifier,
        source: extension.location,
        operation: 2,
        applicationScoped: false,
        profileLocation: this.u.currentProfile.extensionsResource,
        error,
        workspaceScoped: true
      }]);
      throw error;
    }
  }
  async W(extension) {
    if (!extension.isWorkspaceScoped) {
      throw new Error("The extension is not a workspace extension");
    }
    this.J.info(`Uninstalling the workspace extension ${extension.identifier.id} from ${extension.location.toString()}`);
    const server = this.bb();
    this.c.fire({
      identifier: extension.identifier,
      server,
      applicationScoped: false,
      workspaceScoped: true,
      profileLocation: this.u.currentProfile.extensionsResource
    });
    try {
      await this.m.uninstall(extension);
      this.J.info(`Successfully uninstalled the workspace extension ${extension.identifier.id} from ${extension.location.toString()}`);
      this.N.publicLog2("workspaceextension:uninstall");
      this.f.fire({
        identifier: extension.identifier,
        server,
        applicationScoped: false,
        workspaceScoped: true,
        profileLocation: this.u.currentProfile.extensionsResource
      });
    } catch (error) {
      this.J.error(`Failed to uninstall the workspace extension ${extension.identifier.id} from ${extension.location.toString()}`, $qb(error));
      this.f.fire({
        identifier: extension.identifier,
        server,
        error,
        applicationScoped: false,
        workspaceScoped: true,
        profileLocation: this.u.currentProfile.extensionsResource
      });
      throw error;
    }
  }
  async X(gallery, installOptions) {
    const manifest = await this.t.getManifest(gallery, CancellationToken.None);
    if (!manifest) {
      return Promise.reject(localize(12753, null, gallery.displayName || gallery.name));
    }
    const servers = [];
    if ($9z(manifest)) {
      servers.push(...this.j.filter((server) => server !== this.n.webExtensionManagementServer));
    } else {
      const server = this.Y(manifest);
      if (server) {
        servers.push(server);
      }
    }
    if (!servers.length) {
      const error = new Error(localize(12754, null, gallery.displayName || gallery.name));
      error.name = "Unsupported";
      throw error;
    }
    if (installOptions?.context?.[$gA] !== "settingsSync") {
      await this.cb(manifest, false);
    }
    if (!installOptions?.donotIncludePackAndDependencies) {
      await this.db(gallery, manifest);
    }
    return servers;
  }
  Y(manifest) {
    if (this.j.length === 1 && this.n.localExtensionManagementServer) {
      return this.n.localExtensionManagementServer;
    }
    const extensionKind = this.H.getExtensionKind(manifest);
    for (const kind of extensionKind) {
      if (kind === "ui" && this.n.localExtensionManagementServer) {
        return this.n.localExtensionManagementServer;
      }
      if (kind === "workspace" && this.n.remoteExtensionManagementServer) {
        return this.n.remoteExtensionManagementServer;
      }
      if (kind === "web" && this.n.webExtensionManagementServer) {
        return this.n.webExtensionManagementServer;
      }
    }
    return this.n.localExtensionManagementServer;
  }
  Z() {
    return this.D.isEnabled() && this.D.isResourceEnabled(
      "extensions"
      /* SyncResource.Extensions */
    );
  }
  async $(extensions) {
    if (this.Z()) {
      const { result } = await this.F.prompt({
        type: severity_default.Info,
        message: extensions.length === 1 ? localize(12755, null) : localize(12756, null),
        detail: extensions.length === 1 ? localize(12757, null, extensions[0].displayName) : localize(12758, null),
        buttons: [
          {
            label: localize(12759, null),
            run: () => false
          },
          {
            label: localize(12760, null),
            run: () => true
          }
        ],
        cancelButton: {
          run: () => {
            throw new $lb();
          }
        }
      });
      return result;
    }
    return false;
  }
  getExtensionsControlManifest() {
    if (this.n.localExtensionManagementServer) {
      return this.n.localExtensionManagementServer.extensionManagementService.getExtensionsControlManifest();
    }
    if (this.n.remoteExtensionManagementServer) {
      return this.n.remoteExtensionManagementServer.extensionManagementService.getExtensionsControlManifest();
    }
    if (this.n.webExtensionManagementServer) {
      return this.n.webExtensionManagementServer.extensionManagementService.getExtensionsControlManifest();
    }
    return Promise.resolve({ malicious: [], deprecated: {}, search: [] });
  }
  ab(extension) {
    if (extension.isWorkspaceScoped) {
      return this.bb();
    }
    return this.n.getExtensionManagementServer(extension);
  }
  bb() {
    if (this.n.remoteExtensionManagementServer) {
      return this.n.remoteExtensionManagementServer;
    }
    if (this.n.localExtensionManagementServer) {
      return this.n.localExtensionManagementServer;
    }
    if (this.n.webExtensionManagementServer) {
      return this.n.webExtensionManagementServer;
    }
    throw new Error("No extension server found");
  }
  async cb(manifest, requireTrust) {
    if (requireTrust || this.H.getExtensionUntrustedWorkspaceSupportType(manifest) === false) {
      const buttons = [];
      buttons.push({ label: localize(12761, null), type: "ContinueWithTrust" });
      if (!requireTrust) {
        buttons.push({ label: localize(12762, null), type: "ContinueWithoutTrust" });
      }
      buttons.push({ label: localize(12763, null), type: "Manage" });
      const trustState = await this.G.requestWorkspaceTrust({
        message: localize(12764, null),
        buttons
      });
      if (trustState === void 0) {
        throw new $lb();
      }
    }
  }
  async db(extension, manifest) {
    if (this.j.length !== 1 || this.j[0] !== this.n.webExtensionManagementServer) {
      return;
    }
    const nonWebExtensions = [];
    if (manifest.extensionPack?.length) {
      const extensions = await this.t.getExtensions(manifest.extensionPack.map((id2) => ({ id: id2 })), CancellationToken.None);
      for (const extension2 of extensions) {
        if (await this.j[0].extensionManagementService.canInstall(extension2) !== true) {
          nonWebExtensions.push(extension2);
        }
      }
      if (nonWebExtensions.length && nonWebExtensions.length === extensions.length) {
        throw new $rA(
          "Not supported in Web",
          "Unsupported"
          /* ExtensionManagementErrorCode.Unsupported */
        );
      }
    }
    const productName = localize(12765, null, this.z.nameLong);
    const virtualWorkspaceSupport = this.H.getExtensionVirtualWorkspaceSupportType(manifest);
    const virtualWorkspaceSupportReason = $3z(manifest.capabilities?.virtualWorkspaces);
    const hasLimitedSupport = virtualWorkspaceSupport === "limited" || !!virtualWorkspaceSupportReason;
    if (!nonWebExtensions.length && !hasLimitedSupport) {
      return;
    }
    const limitedSupportMessage = localize(12766, null, extension.displayName || extension.identifier.id, productName);
    let message;
    let buttons = [];
    let detail2;
    const installAnywayButton = {
      label: localize(12767, null),
      run: () => {
      }
    };
    const showExtensionsButton = {
      label: localize(12768, null),
      run: () => this.L.invokeFunction((accessor) => accessor.get($sn).executeCommand("extension.open", extension.identifier.id, "extensionPack"))
    };
    if (nonWebExtensions.length && hasLimitedSupport) {
      message = limitedSupportMessage;
      detail2 = `${virtualWorkspaceSupportReason ? `${virtualWorkspaceSupportReason}
` : ""}${localize(12769, null)}`;
      buttons = [
        installAnywayButton,
        showExtensionsButton
      ];
    } else if (hasLimitedSupport) {
      message = limitedSupportMessage;
      detail2 = virtualWorkspaceSupportReason || void 0;
      buttons = [installAnywayButton];
    } else {
      message = localize(12770, null, extension.displayName || extension.identifier.id, productName);
      buttons = [
        installAnywayButton,
        showExtensionsButton
      ];
    }
    await this.F.prompt({
      type: severity_default.Info,
      message,
      detail: detail2,
      buttons,
      cancelButton: {
        run: () => {
          throw new $lb();
        }
      }
    });
  }
  getTargetPlatform() {
    if (!this.eb) {
      this.eb = $OA(this.I, this.J);
    }
    return this.eb;
  }
  async cleanUp() {
    await Promise.allSettled(this.j.map((server) => server.extensionManagementService.cleanUp()));
  }
  toggleAppliationScope(extension, fromProfileLocation) {
    const server = this.ab(extension);
    if (server) {
      return server.extensionManagementService.toggleAppliationScope(extension, fromProfileLocation);
    }
    throw new Error("Not Supported");
  }
  copyExtensions(from, to) {
    if (this.n.remoteExtensionManagementServer) {
      throw new Error("Not Supported");
    }
    if (this.n.localExtensionManagementServer) {
      return this.n.localExtensionManagementServer.extensionManagementService.copyExtensions(from, to);
    }
    if (this.n.webExtensionManagementServer) {
      return this.n.webExtensionManagementServer.extensionManagementService.copyExtensions(from, to);
    }
    return Promise.resolve();
  }
  registerParticipant() {
    throw new Error("Not Supported");
  }
  installExtensionsFromProfile(extensions, fromProfileLocation, toProfileLocation) {
    throw new Error("Not Supported");
  }
};
$woc = __decorate([
  __param(0, $nzb),
  __param(1, $pA),
  __param(2, $gT),
  __param(3, $rs),
  __param(4, $kl),
  __param(5, $Vu),
  __param(6, $6W),
  __param(7, $6Bb),
  __param(8, $Yv),
  __param(9, $5M),
  __param(10, $LCb),
  __param(11, $km),
  __param(12, $wn),
  __param(13, $Pk),
  __param(14, $4A),
  __param(15, $zv)
], $woc);
var WorkspaceExtensionsManagementService = class WorkspaceExtensionsManagementService2 extends $3c {
  static {
    WorkspaceExtensionsManagementService_1 = this;
  }
  static {
    this.a = "workspaceExtensions.locations";
  }
  constructor(h3, j, m, n, t, u, w) {
    super();
    this.h = h3;
    this.j = j;
    this.m = m;
    this.n = n;
    this.t = t;
    this.u = u;
    this.w = w;
    this.b = this.B(new $ze());
    this.onDidChangeInvalidExtensions = this.b.event;
    this.c = [];
    this.g = this.B(new $2c());
    this.B(Event2.debounce(this.h.onDidFilesChange, (last, e) => {
      (last = last ?? []).push(e);
      return last;
    }, 1e3)((events) => {
      const changedInvalidExtensions = this.c.filter((extension) => !extension.isValid && events.some((e) => e.affects(extension.location)));
      if (changedInvalidExtensions.length) {
        this.C(changedInvalidExtensions);
      }
    }));
    this.f = this.y();
  }
  async y() {
    const existingLocations = this.getInstalledWorkspaceExtensionsLocations();
    if (!existingLocations.length) {
      return;
    }
    await Promise.allSettled(existingLocations.map(async (location3) => {
      if (!this.m.isInsideWorkspace(location3)) {
        this.j.info(`Removing the workspace extension ${location3.toString()} as it is not inside the workspace`);
        return;
      }
      if (!await this.h.exists(location3)) {
        this.j.info(`Removing the workspace extension ${location3.toString()} as it does not exist`);
        return;
      }
      try {
        const extension = await this.scanWorkspaceExtension(location3);
        if (extension) {
          this.c.push(extension);
        } else {
          this.j.info(`Skipping workspace extension ${location3.toString()} as it does not exist`);
        }
      } catch (error) {
        this.j.error("Skipping the workspace extension", location3.toString(), error);
      }
    }));
    this.D();
  }
  z() {
    this.g.clear();
    for (const extension of this.c) {
      if (!extension.isValid) {
        this.g.add(this.h.watch(extension.location));
      }
    }
  }
  async C(extensions) {
    const validExtensions = [];
    await Promise.all(extensions.map(async (extension) => {
      const newExtension = await this.scanWorkspaceExtension(extension.location);
      if (newExtension?.isValid) {
        validExtensions.push(newExtension);
      }
    }));
    let changed = false;
    for (const extension of validExtensions) {
      const index = this.c.findIndex((e) => this.u.extUri.isEqual(e.location, extension.location));
      if (index !== -1) {
        changed = true;
        this.c.splice(index, 1, extension);
      }
    }
    if (changed) {
      this.D();
      this.b.fire(validExtensions);
    }
  }
  async getInstalled(includeInvalid) {
    await this.f;
    return this.c.filter((e) => includeInvalid || e.isValid);
  }
  async install(extension) {
    await this.f;
    const workspaceExtension = await this.scanWorkspaceExtension(extension.location);
    if (!workspaceExtension) {
      throw new Error("Cannot install the extension as it does not exist.");
    }
    const existingExtensionIndex = this.c.findIndex((e) => $DA(e.identifier, extension.identifier));
    if (existingExtensionIndex === -1) {
      this.c.push(workspaceExtension);
    } else {
      this.c.splice(existingExtensionIndex, 1, workspaceExtension);
    }
    this.D();
    this.w.publicLog2("workspaceextension:install");
    return workspaceExtension;
  }
  async uninstall(extension) {
    await this.f;
    const existingExtensionIndex = this.c.findIndex((e) => $DA(e.identifier, extension.identifier));
    if (existingExtensionIndex !== -1) {
      this.c.splice(existingExtensionIndex, 1);
      this.D();
    }
    this.w.publicLog2("workspaceextension:uninstall");
  }
  getInstalledWorkspaceExtensionsLocations() {
    const locations = [];
    try {
      const parsed = JSON.parse(this.t.get(WorkspaceExtensionsManagementService_1.a, 1, "[]"));
      if (Array.isArray(locations)) {
        for (const location3 of parsed) {
          if ($zg(location3)) {
            if (this.m.getWorkbenchState() === 2) {
              locations.push(this.m.getWorkspace().folders[0].toResource(location3));
            } else {
              this.j.warn(`Invalid value for 'extensions' in workspace storage: ${location3}`);
            }
          } else {
            locations.push(URI.revive(location3));
          }
        }
      } else {
        this.j.warn(`Invalid value for 'extensions' in workspace storage: ${locations}`);
      }
    } catch (error) {
      this.j.warn(`Error parsing workspace extensions locations: ${$qb(error)}`);
    }
    return locations;
  }
  D() {
    const locations = this.c.map((extension) => extension.location);
    if (this.m.getWorkbenchState() === 2) {
      this.t.store(
        WorkspaceExtensionsManagementService_1.a,
        JSON.stringify($Mb(locations.map((location3) => this.u.extUri.relativePath(this.m.getWorkspace().folders[0].uri, location3)))),
        1,
        1
        /* StorageTarget.MACHINE */
      );
    } else {
      this.t.store(
        WorkspaceExtensionsManagementService_1.a,
        JSON.stringify(locations),
        1,
        1
        /* StorageTarget.MACHINE */
      );
    }
    this.z();
  }
  async scanWorkspaceExtension(location3) {
    const scannedExtension = await this.n.scanExistingExtension(location3, 1, { includeInvalid: true });
    return scannedExtension ? this.toLocalWorkspaceExtension(scannedExtension) : null;
  }
  async toLocalWorkspaceExtension(extension) {
    const stat = await this.h.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;
    }
    const validations = [...extension.validations];
    let isValid2 = extension.isValid;
    if (extension.manifest.main) {
      if (!await this.h.exists(this.u.extUri.joinPath(extension.location, extension.manifest.main))) {
        isValid2 = false;
        validations.push([severity_default.Error, localize(12771, null, extension.manifest.main)]);
      }
    }
    return {
      identifier: extension.identifier,
      type: extension.type,
      isBuiltin: extension.isBuiltin || !!extension.metadata?.isBuiltin,
      location: extension.location,
      manifest: extension.manifest,
      targetPlatform: extension.targetPlatform,
      validations,
      isValid: isValid2,
      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: true,
      source: "resource",
      size: extension.metadata?.size ?? 0
    };
  }
};
WorkspaceExtensionsManagementService = WorkspaceExtensionsManagementService_1 = __decorate([
  __param(0, $km),
  __param(1, $wn),
  __param(2, $Zk),
  __param(3, $4A),
  __param(4, $jv),
  __param(5, $vl),
  __param(6, $zv)
], WorkspaceExtensionsManagementService);

// out-build/vs/platform/userDataSync/common/userDataSyncLocalStoreService.js
var $xoc = class $xoc2 extends $3c {
  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 $RBb) {
        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 ($Bm(error) !== 1) {
        this.f.error(error);
      }
      return;
    }
    if (stat.children) {
      for (const child of stat.children) {
        if (child.isDirectory && !$RBb.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 ($Bm(error) !== 1) {
        throw error;
      }
    }
    return [];
  }
  async resolveResourceContent(resourceKey, ref, collection, root) {
    const folder = this.j(resourceKey, collection, root);
    const file = $vh(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 = $vh(folder, `${$Tu(cTime).replace(/-|:|\.\d+Z$/g, "")}.json`);
    try {
      await this.b.writeFile(resource, $Ci.fromString(content));
    } catch (e) {
      this.f.error(e);
    }
  }
  j(resource, collection, root = this.a.userDataSyncHome) {
    return $vh(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();
  }
};
$xoc = __decorate([
  __param(0, $Xk),
  __param(1, $km),
  __param(2, $kl),
  __param(3, $$Bb),
  __param(4, $rs)
], $xoc);

// out-build/vs/platform/userDataSync/common/userDataProfilesManifestMerge.js
function $yoc(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((key2) => !fromKeys.includes(key2));
  const removed = fromKeys.filter((key2) => !toKeys.includes(key2));
  const updated = [];
  for (const { id: id2, name, icon: icon2, useDefaultFlags } of from) {
    if (removed.includes(id2)) {
      continue;
    }
    const toProfile = to.find((p) => p.id === id2);
    if (!toProfile || toProfile.name !== name || toProfile.icon !== icon2 || !$Pv(toProfile.useDefaultFlags, useDefaultFlags)) {
      updated.push(id2);
    }
  }
  return { added, removed, updated };
}

// out-build/vs/platform/userDataSync/common/userDataProfilesManifestSync.js
var $zoc = class $zoc2 extends $LXb {
  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: $aCb, authority: "base" });
    this.localResource = this.previewResource.with({ scheme: $aCb, authority: "local" });
    this.remoteResource = this.previewResource.with({ scheme: $aCb, authority: "remote" });
    this.acceptedResource = this.previewResource.with({ scheme: $aCb, authority: "accepted" });
    this.B(vb.onDidChangeProfiles(() => this.Q()));
  }
  async getLastSyncedProfiles() {
    const lastSyncUserData = await this.getLastSyncUserData();
    return lastSyncUserData?.syncData ? $Boc(lastSyncUserData.syncData) : null;
  }
  async getRemoteSyncedProfiles(manifest) {
    const lastSyncUserData = await this.getLastSyncUserData();
    const remoteUserData = await this.X(manifest, lastSyncUserData);
    return remoteUserData?.syncData ? $Boc(remoteUserData.syncData) : null;
  }
  async qb(remoteUserData, lastSyncUserData, isRemoteDataFromCurrentMachine) {
    const remoteProfiles = remoteUserData.syncData ? $Boc(remoteUserData.syncData) : null;
    const lastSyncProfiles = lastSyncUserData?.syncData ? $Boc(lastSyncUserData.syncData) : null;
    const localProfiles = this.Db();
    const { local, remote } = $yoc(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 = $Aoc(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 ? $Boc(lastSyncUserData.syncData) : null;
    const localProfiles = this.Db();
    const { remote } = $yoc(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 = $yoc(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 = $yoc(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 $1Bb(
        "Too many profiles to sync. Please remove some profiles and try again.",
        "LocalTooManyProfiles"
        /* UserDataSyncErrorCode.LocalTooManyProfiles */
      );
    }
    if (localChange !== 0) {
      await this.nb($Aoc(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, { 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, 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, 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, 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(profiles2, ref) {
    return this.mb(this.Eb(profiles2), 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 ? $Tw(JSON.parse(content), {}) : content;
    }
    return null;
  }
  Db() {
    return this.vb.profiles.filter((p) => !p.isDefault && !p.isTransient);
  }
  Eb(profiles2) {
    return JSON.stringify([...profiles2].sort((a, b) => a.name.localeCompare(b.name)));
  }
};
$zoc = __decorate([
  __param(2, $rs),
  __param(3, $km),
  __param(4, $Xk),
  __param(5, $jv),
  __param(6, $VBb),
  __param(7, $WBb),
  __param(8, $$Bb),
  __param(9, $kl),
  __param(10, $6Bb),
  __param(11, $zv),
  __param(12, $vl)
], $zoc);
function $Aoc(profiles2, format2) {
  const result = [...profiles2].sort((a, b) => a.name.localeCompare(b.name)).map((p) => ({ id: p.id, name: p.name }));
  return format2 ? $Tw(result, {}) : JSON.stringify(result);
}
function $Boc(syncData) {
  return JSON.parse(syncData.content);
}

// out-build/vs/platform/userDataSync/common/userDataSyncService.js
var LAST_SYNC_TIME_KEY = "sync.lastSyncTime";
var $Coc = class $Coc2 extends $3c {
  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 $ze());
    this.onDidChangeStatus = this.g.event;
    this.h = this.B(new $ze());
    this.onDidChangeLocal = this.h.event;
    this.j = [];
    this.m = this.B(new $ze());
    this.onDidChangeConflicts = this.m.event;
    this.n = [];
    this.r = this.B(new $ze());
    this.onSyncErrors = this.r.event;
    this.t = void 0;
    this.u = this.B(new $ze());
    this.onDidChangeLastSyncTime = this.u.event;
    this.w = this.B(new $ze());
    this.onDidResetLocal = this.w.event;
    this.y = this.B(new $ze());
    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($1c(() => this.cb()));
    this.B(new $8h(
      () => 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 = $ps();
    try {
      const syncHeaders = $ZBb(executionId);
      if (disableCache) {
        syncHeaders["Cache-Control"] = "no-cache";
      }
      manifest = await this.D.manifest(manifest, syncHeaders);
    } catch (error) {
      const userDataSyncError = $1Bb.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 = $Hh((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 $1Bb(
        "Cannot start manual sync when sync is enabled",
        "LocalError"
        /* UserDataSyncErrorCode.LocalError */
      );
    }
    this.H.info("Sync started.");
    const startTime = (/* @__PURE__ */ new Date()).getTime();
    const executionId = $ps();
    const syncHeaders = $ZBb(executionId);
    let manifest;
    try {
      manifest = await this.D.manifest(null, syncHeaders);
    } catch (error) {
      const userDataSyncError = $1Bb.toUserDataSyncError(error);
      reportUserDataSyncError(userDataSyncError, executionId, this.F, this.I);
      throw userDataSyncError;
    }
    await this.resetLocal();
    const that = this;
    const cancellableToken = new $ad();
    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 ($1Bb.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 [key2, 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(key2);
    }
  }
  async R(manifest, executionId, token) {
    try {
      this.Z(
        "syncing"
        /* SyncStatus.Syncing */
      );
      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);
      }
    } finally {
      this.Z(
        "idle"
        /* SyncStatus.Idle */
      );
    }
  }
  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, apply2) {
    this.db();
    await this.X(syncResource.profile, async (synchronizer) => {
      if (syncResource.syncResource === synchronizer.resource) {
        await synchronizer.accept(resource, content);
        if (apply2) {
          await synchronizer.apply($Fg(apply2) ? false : apply2.force, $ZBb($ps()));
        }
        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 key2 of allKeys) {
      if (!key2.endsWith(".lastSyncUserData")) {
        continue;
      }
      const segments = key2.split(".");
      if (segments.length === 3) {
        lastSyncProfileKeys.push([key2, segments[0]]);
      }
    }
    if (!lastSyncProfileKeys.length) {
      return;
    }
    const disposables = new $2c();
    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 [key2, collection] of lastSyncProfileKeys) {
        if (!lastSyncedCollections.includes(collection)) {
          this.H.info(`Removing last sync state for stale profile: ${collection}`);
          this.J.remove(
            key2,
            -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($zoc, 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(location3) {
    this.db();
    const data = await this.D.getActivityData();
    await this.C.writeFile(location3, data);
  }
  async extractActivityData(activityDataResource, location3) {
    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 version2 of activityData.resources[resource]) {
          await this.O.writeResource(resource, version2.content, new Date(version2.created * 1e3), void 0, location3);
        }
      }
    }
    if (activityData.collections) {
      for (const collection in activityData.collections) {
        for (const resource in activityData.collections[collection].resources) {
          for (const version2 of activityData.collections[collection].resources?.[resource] ?? []) {
            await this.O.writeResource(resource, version2.content, new Date(version2.created * 1e3), collection, location3);
          }
        }
      }
    }
  }
  async X(profile, action) {
    const disposables = new $2c();
    try {
      const activeProfileSyncronizer = this.z.get(profile.id);
      if (activeProfileSyncronizer) {
        const result = await this.Y(activeProfileSyncronizer[0], action, disposables);
        return $Gg(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 $Gg(result) ? null : result;
      }
      const userDataProfileManifestSynchronizer = disposables.add(this.G.createInstance($zoc, 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 $Gg(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 (!$Gg(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 (!$zb(this.j, conflicts, (a, b) => a.profile.id === b.profile.id && a.syncResource === b.syncResource && $zb(a.conflicts, b.conflicts, (a2, b2) => $oh(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 $2c();
      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");
    }
  }
};
$Coc = __decorate([
  __param(0, $km),
  __param(1, $VBb),
  __param(2, $UBb),
  __param(3, $Pk),
  __param(4, $$Bb),
  __param(5, $zv),
  __param(6, $jv),
  __param(7, $6Bb),
  __param(8, $rs),
  __param(9, $8Bb),
  __param(10, $WBb)
], $Coc);
var ProfileSynchronizer = class ProfileSynchronizer2 extends $3c {
  get enabled() {
    return this.f.sort((a, b) => a[1] - b[1]).map(([synchronizer]) => synchronizer);
  }
  get disabled() {
    return $RBb.filter((syncResource) => !this.r.isResourceEnabled(syncResource));
  }
  get status() {
    return this.g;
  }
  get conflicts() {
    return this.m;
  }
  constructor(profile, collection, r2, t, u, w, y, z, C) {
    super();
    this.profile = profile;
    this.collection = collection;
    this.r = r2;
    this.t = t;
    this.u = u;
    this.w = w;
    this.y = y;
    this.z = z;
    this.C = C;
    this.f = [];
    this.g = "idle";
    this.h = this.B(new $ze());
    this.onDidChangeStatus = this.h.event;
    this.j = this.B(new $ze());
    this.onDidChangeLocal = this.j.event;
    this.m = [];
    this.n = this.B(new $ze());
    this.onDidChangeConflicts = this.n.event;
    this.B(r2.onDidChangeResourceEnablement(([syncResource, enablement]) => this.D(syncResource, enablement)));
    this.B($1c(() => this.f.splice(0, this.f.length).forEach(([, , disposable]) => disposable.dispose())));
    for (const syncResource of $RBb) {
      if (r2.isResourceEnabled(syncResource)) {
        this.F(syncResource);
      }
    }
  }
  D(syncResource, enabled) {
    if (enabled) {
      this.F(syncResource);
    } else {
      this.G(syncResource);
    }
  }
  F(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 (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 $2c();
    const synchronizer = disposables.add(this.createSynchronizer(syncResource));
    disposables.add(synchronizer.onDidChangeStatus(() => this.J()));
    disposables.add(synchronizer.onDidChangeConflicts(() => this.L()));
    disposables.add(synchronizer.onDidChangeLocal(() => this.j.fire(syncResource)));
    const order = this.M(syncResource);
    this.f.push([synchronizer, order, disposables]);
  }
  G(syncResource) {
    const index = this.f.findIndex(([synchronizer]) => synchronizer.resource === syncResource);
    if (index !== -1) {
      const [[synchronizer, , disposable]] = this.f.splice(index, 1);
      disposable.dispose();
      this.J();
      synchronizer.stop().then(null, (error) => this.z.error(error));
    }
  }
  createSynchronizer(syncResource) {
    switch (syncResource) {
      case "settings":
        return this.t.createInstance($Gmc, this.profile, this.collection);
      case "keybindings":
        return this.t.createInstance($Dmc, this.profile, this.collection);
      case "snippets":
        return this.t.createInstance($Lmc, this.profile, this.collection);
      case "tasks":
        return this.t.createInstance($Omc, this.profile, this.collection);
      case "globalState":
        return this.t.createInstance($RXb, this.profile, this.collection);
      case "extensions":
        return this.t.createInstance($ymc, this.profile, this.collection);
      case "profiles":
        return this.t.createInstance($zoc, 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 = $ZBb(executionId);
      const resourceManifest = (this.collection ? manifest?.collections?.[this.collection]?.latest : manifest?.latest) ?? null;
      const userDataSyncConfiguration = merge2 ? await this.H(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 = $1Bb.toUserDataSyncError(e);
          reportUserDataSyncError(userDataSyncError, executionId, this.w, this.y);
          if (canBailout(e)) {
            throw userDataSyncError;
          }
          this.z.error(e);
          this.z.error(`${synchroniser.resource}: ${$1m(e)}`);
          syncErrors.push([synchroniser.resource, userDataSyncError]);
        }
      }
      return syncErrors;
    } finally {
      this.J();
    }
  }
  async apply(executionId, token) {
    const syncHeaders = $ZBb(executionId);
    for (const synchroniser of this.enabled) {
      if (token.isCancellationRequested) {
        return;
      }
      try {
        await synchroniser.apply(false, syncHeaders);
      } catch (e) {
        const userDataSyncError = $1Bb.toUserDataSyncError(e);
        reportUserDataSyncError(userDataSyncError, executionId, this.w, this.y);
        if (canBailout(e)) {
          throw userDataSyncError;
        }
        this.z.error(e);
        this.z.error(`${synchroniser.resource}: ${$1m(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}: ${$1m(e)}`);
        this.z.error(e);
      }
    }
  }
  async H(manifest) {
    if (!this.profile.isDefault) {
      return {};
    }
    const local = this.C.getValue($NBb);
    const settingsSynchronizer = this.enabled.find((synchronizer) => synchronizer instanceof $Gmc);
    if (settingsSynchronizer) {
      const remote = await settingsSynchronizer.getRemoteUserDataSyncConfiguration(manifest);
      return { ...local, ...remote };
    }
    return local;
  }
  I(status) {
    if (this.g !== status) {
      this.g = status;
      this.h.fire(status);
    }
  }
  J() {
    this.L();
    if (this.enabled.some(
      (s) => s.status === "hasConflicts"
      /* SyncStatus.HasConflicts */
    )) {
      return this.I(
        "hasConflicts"
        /* SyncStatus.HasConflicts */
      );
    }
    if (this.enabled.some(
      (s) => s.status === "syncing"
      /* SyncStatus.Syncing */
    )) {
      return this.I(
        "syncing"
        /* SyncStatus.Syncing */
      );
    }
    return this.I(
      "idle"
      /* SyncStatus.Idle */
    );
  }
  L() {
    const conflicts = this.enabled.filter(
      (s) => s.status === "hasConflicts"
      /* SyncStatus.HasConflicts */
    ).filter((s) => s.conflicts.conflicts.length > 0).map((s) => s.conflicts);
    if (!$zb(this.m, conflicts, (a, b) => a.syncResource === b.syncResource && $zb(a.conflicts, b.conflicts, (a2, b2) => $oh(a2.previewResource, b2.previewResource)))) {
      this.m = conflicts;
      this.n.fire(conflicts);
    }
  }
  M(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, $6Bb),
  __param(3, $Pk),
  __param(4, $pA),
  __param(5, $UBb),
  __param(6, $zv),
  __param(7, $$Bb),
  __param(8, $kl)
], ProfileSynchronizer);
function canBailout(e) {
  if (e instanceof $1Bb) {
    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 $2Bb ? String(userDataSyncError.serverCode) : void 0,
    url: userDataSyncError instanceof $2Bb ? userDataSyncError.url : void 0,
    resource: userDataSyncError.resource,
    executionId,
    service: userDataSyncStoreManagementService.userDataSyncStore.url.toString()
  });
}

// 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 $Doc = class $Doc2 extends $3c {
  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 $4c());
    this.b = 0;
    this.c = void 0;
    this.g = false;
    this.h = this.B(new $ze());
    this.onError = this.h.event;
    this.S = [];
    this.f = this.B(new $Th(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 (!$oh(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(Event2.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 ${$Tu(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 = $1Bb.toUserDataSyncError(error);
    if (userDataSyncError instanceof $3Bb) {
      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 $Wh(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;
  }
};
$Doc = __decorate([
  __param(0, $Vu),
  __param(1, $UBb),
  __param(2, $VBb),
  __param(3, $6Bb),
  __param(4, $7Bb),
  __param(5, $$Bb),
  __param(6, $eWb),
  __param(7, $zv),
  __param(8, $HBb),
  __param(9, $jv)
], $Doc);
var AutoSync = class _AutoSync extends $3c {
  static {
    this.a = "Interval";
  }
  constructor(m, n, r2, s, u, w, y, z, C) {
    super();
    this.m = m;
    this.n = n;
    this.r = r2;
    this.s = s;
    this.u = u;
    this.w = w;
    this.y = y;
    this.z = z;
    this.C = C;
    this.b = this.B(new $4c());
    this.c = this.B(new $ze());
    this.onDidStartSync = this.c.event;
    this.f = this.B(new $ze());
    this.onDidFinishSync = this.f.event;
    this.g = null;
  }
  start() {
    this.B(this.onDidFinishSync(() => this.D()));
    this.B($1c(() => {
      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 = $Xh(() => {
      this.sync(_AutoSync.a, false);
      this.b.value = void 0;
    }, this.n);
  }
  sync(reason, disableCache) {
    const syncPromise = $Hh(async (token) => {
      if (this.j) {
        try {
          this.y.debug("Auto Sync: Waiting until sync is finished.");
          await this.j;
        } catch (error) {
          if ($kb(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 && !$oh(this.m, this.r.userDataSyncStore?.url);
  }
  async G() {
    const previous = await this.r.getPreviousUserDataSyncStore();
    const current = this.r.userDataSyncStore;
    return !!current && !!previous && (!$oh(current.defaultUrl, previous.defaultUrl) || !$oh(current.insidersUrl, previous.insidersUrl) || !$oh(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 ($1Bb.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 $3Bb(
            localize(2495, null),
            "DefaultServiceChanged"
            /* UserDataSyncErrorCode.DefaultServiceChanged */
          );
        } else {
          throw new $3Bb(
            localize(2496, null),
            "ServiceChanged"
            /* UserDataSyncErrorCode.ServiceChanged */
          );
        }
      } else {
        throw new $3Bb(
          localize(2497, 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 $3Bb(
            localize(2498, null),
            "DefaultServiceChanged"
            /* UserDataSyncErrorCode.DefaultServiceChanged */
          );
        } else {
          throw new $3Bb(
            localize(2499, null),
            "ServiceChanged"
            /* UserDataSyncErrorCode.ServiceChanged */
          );
        }
      } else {
        throw new $3Bb(
          localize(2500, 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 $3Bb(
        localize(2501, 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 $3Bb(
          $1m(error),
          error instanceof $1Bb ? 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/accessibility/browser/accessibilityService.js
var $Eoc = class $Eoc2 extends $3c {
  constructor(n, r2, s) {
    super();
    this.n = n;
    this.r = r2;
    this.s = s;
    this.b = 0;
    this.c = new $ze();
    this.h = new $ze();
    this.m = new $ze();
    this.a = $OD.bindTo(this.n);
    const updateContextKey = () => this.a.set(this.isScreenReaderOptimized());
    this.B(this.s.onDidChangeConfiguration((e) => {
      if (e.affectsConfiguration("editor.accessibilitySupport")) {
        updateContextKey();
        this.c.fire();
      }
      if (e.affectsConfiguration("workbench.reduceMotion")) {
        this.f = this.s.getValue("workbench.reduceMotion");
        this.h.fire();
      }
    }));
    updateContextKey();
    this.B(this.onDidChangeScreenReaderOptimized(() => updateContextKey()));
    const reduceMotionMatcher = $Y.matchMedia(`(prefers-reduced-motion: reduce)`);
    this.g = reduceMotionMatcher.matches;
    this.f = this.s.getValue("workbench.reduceMotion");
    this.j = this.s.getValue("accessibility.underlineLinks");
    this.t(reduceMotionMatcher);
    this.u();
  }
  t(reduceMotionMatcher) {
    this.B($_i(reduceMotionMatcher, "change", () => {
      this.g = reduceMotionMatcher.matches;
      if (this.f === "auto") {
        this.h.fire();
      }
    }));
    const updateRootClasses = () => {
      const reduce = this.isMotionReduced();
      this.r.mainContainer.classList.toggle("reduce-motion", reduce);
      this.r.mainContainer.classList.toggle("enable-motion", !reduce);
    };
    updateRootClasses();
    this.B(this.onDidChangeReducedMotion(() => updateRootClasses()));
  }
  u() {
    this.B(this.s.onDidChangeConfiguration((e) => {
      if (e.affectsConfiguration("accessibility.underlineLinks")) {
        const linkUnderlinesEnabled = this.s.getValue("accessibility.underlineLinks");
        this.j = linkUnderlinesEnabled;
        this.m.fire();
      }
    }));
    const updateLinkUnderlineClasses = () => {
      const underlineLinks = this.j;
      this.r.mainContainer.classList.toggle("underline-links", underlineLinks);
    };
    updateLinkUnderlineClasses();
    this.B(this.onDidChangeLinkUnderlines(() => updateLinkUnderlineClasses()));
  }
  onDidChangeLinkUnderlines(listener) {
    return this.m.event(listener);
  }
  get onDidChangeScreenReaderOptimized() {
    return this.c.event;
  }
  isScreenReaderOptimized() {
    const config = this.s.getValue("editor.accessibilitySupport");
    return config === "on" || config === "auto" && this.b === 2;
  }
  get onDidChangeReducedMotion() {
    return this.h.event;
  }
  isMotionReduced() {
    const config = this.f;
    return config === "on" || config === "auto" && this.g;
  }
  alwaysUnderlineAccessKeys() {
    return Promise.resolve(false);
  }
  getAccessibilitySupport() {
    return this.b;
  }
  setAccessibilitySupport(accessibilitySupport) {
    if (this.b === accessibilitySupport) {
      return;
    }
    this.b = accessibilitySupport;
    this.c.fire();
  }
  alert(message) {
    $$Z(message);
  }
  status(message) {
    $_Z(message);
  }
};
$Eoc = __decorate([
  __param(0, $on),
  __param(1, $Ulb),
  __param(2, $kl)
], $Eoc);

// out-build/vs/workbench/browser/parts/titlebar/commandCenterControl.js
var CommandCenterCenterViewItem_1;
var $UTb = class $UTb2 {
  constructor(windowTitle, hoverDelegate, instantiationService, quickInputService) {
    this.a = new $2c();
    this.b = new $ze();
    this.onDidChangeVisibility = this.b.event;
    this.element = document.createElement("div");
    this.element.classList.add("command-center");
    const titleToolbar = instantiationService.createInstance($4$, this.element, $bJ.CommandCenter, {
      contextMenu: $bJ.TitleBarContext,
      hiddenItemStrategy: -1,
      toolbarOptions: {
        primaryGroup: () => true
      },
      telemetrySource: "commandCenter",
      actionViewItemProvider: (action, options3) => {
        if (action instanceof $eJ && action.item.submenu === $bJ.CommandCenterCenter) {
          return instantiationService.createInstance(CommandCenterCenterViewItem, action, windowTitle, { ...options3, hoverDelegate });
        } else {
          return $X$(instantiationService, action, { ...options3, hoverDelegate });
        }
      }
    });
    this.a.add(Event2.filter(quickInputService.onShow, () => $Oj(this.element), this.a)(this.c.bind(this, false)));
    this.a.add(quickInputService.onHide(this.c.bind(this, true)));
    this.a.add(titleToolbar);
  }
  c(show2) {
    this.element.classList.toggle("hide", !show2);
    this.b.fire();
  }
  dispose() {
    this.a.dispose();
  }
};
$UTb = __decorate([
  __param(2, $Pk),
  __param(3, $1M)
], $UTb);
var CommandCenterCenterViewItem = class CommandCenterCenterViewItem2 extends $T1 {
  static {
    CommandCenterCenterViewItem_1 = this;
  }
  static {
    this.a = "workbench.action.quickOpenWithModes";
  }
  constructor(c, g, options3, h3, m, n, r2) {
    super(void 0, c.actions.find((action) => action.id === "workbench.action.quickOpenWithModes") ?? c.actions[0], options3);
    this.c = c;
    this.g = g;
    this.h = h3;
    this.m = m;
    this.n = n;
    this.r = r2;
    this.b = options3.hoverDelegate ?? $JZ("mouse");
  }
  render(container2) {
    super.render(container2);
    container2.classList.add("command-center-center");
    container2.classList.toggle("multiple", this.c.actions.length > 1);
    const hover = this.q.add(this.h.setupManagedHover(this.b, container2, this.F()));
    this.q.add(this.g.onDidChange(() => {
      hover.update(this.F());
    }));
    const groups = [];
    for (const action of this.c.actions) {
      if (action instanceof $Xm) {
        groups.push(action.actions);
      } else {
        groups.push([action]);
      }
    }
    for (let i2 = 0; i2 < groups.length; i2++) {
      const group2 = groups[i2];
      const toolbar = this.n.createInstance($3$, container2, {
        hiddenItemStrategy: -1,
        telemetrySource: "commandCenterCenter",
        actionViewItemProvider: (action, options3) => {
          options3 = {
            ...options3,
            hoverDelegate: this.b
          };
          if (action.id !== CommandCenterCenterViewItem_1.a) {
            return $X$(this.n, action, options3);
          }
          const that = this;
          return this.n.createInstance(class CommandCenterQuickPickItem extends $T1 {
            constructor() {
              super(void 0, action, options3);
            }
            render(container3) {
              super.render(container3);
              container3.classList.toggle("command-center-quick-pick");
              container3.role = "button";
              const action2 = this.action;
              const searchIcon = document.createElement("span");
              searchIcon.ariaHidden = "true";
              searchIcon.className = action2.class ?? "";
              searchIcon.classList.add("search-icon");
              const label3 = this.b();
              const labelElement = document.createElement("span");
              labelElement.classList.add("search-label");
              labelElement.innerText = label3;
              $dk(container3, searchIcon, labelElement);
              const hover2 = this.q.add(that.h.setupManagedHover(that.b, container3, this.F()));
              this.q.add(that.g.onDidChange(() => {
                hover2.update(this.F());
                labelElement.innerText = this.b();
              }));
              this.q.add(that.r.onDidChangeEditorPartOptions(({ newPartOptions, oldPartOptions }) => {
                if (newPartOptions.showTabs !== oldPartOptions.showTabs) {
                  hover2.update(this.F());
                  labelElement.innerText = this.b();
                }
              }));
            }
            F() {
              return that.F();
            }
            b() {
              const { prefix, suffix } = that.g.getTitleDecorations();
              let label3 = that.g.workspaceName;
              if (that.g.isCustomTitleFormat()) {
                label3 = that.g.getWindowTitle();
              } else if (that.r.partOptions.showTabs === "none") {
                label3 = that.g.fileName ?? label3;
              }
              if (!label3) {
                label3 = localize(3743, null);
              }
              if (prefix) {
                label3 = localize(3744, null, prefix, label3);
              }
              if (suffix) {
                label3 = localize(3745, null, label3, suffix);
              }
              return label3.replaceAll(/\r\n|\r|\n/g, "\u23CE");
            }
          });
        }
      });
      toolbar.setActions(group2);
      this.q.add(toolbar);
      if (i2 < groups.length - 1) {
        const icon2 = $C1($6l.circleSmallFilled);
        icon2.style.padding = "0 12px";
        icon2.style.height = "100%";
        icon2.style.opacity = "0.5";
        container2.appendChild(icon2);
      }
    }
  }
  F() {
    const kb = this.m.lookupKeybinding(this.action.id)?.getLabel();
    const title = kb ? localize(3746, null, this.g.workspaceName, kb, this.g.value) : localize(3747, null, this.g.workspaceName, this.g.value);
    return title;
  }
};
CommandCenterCenterViewItem = CommandCenterCenterViewItem_1 = __decorate([
  __param(3, $5$),
  __param(4, $Ty),
  __param(5, $Pk),
  __param(6, $iJ)
], CommandCenterCenterViewItem);
$dJ.appendMenuItem($bJ.CommandCenter, {
  submenu: $bJ.CommandCenterCenter,
  title: localize(3748, null),
  icon: $6l.shield,
  order: 101
});

// out-build/vs/workbench/browser/parts/titlebar/titlebarPart.js
var $7Tb_1;
var $4Tb = class $4Tb2 extends $3lb {
  constructor(a, storageService, themeService) {
    super("workbench.titleService", themeService, storageService);
    this.a = a;
    this.mainPart = this.B(this.b());
    this.onMenubarVisibilityChange = this.mainPart.onMenubarVisibilityChange;
    this.s = void 0;
    this.t = /* @__PURE__ */ new Map();
    this.B(this.registerPart(this.mainPart));
    this.c();
    this.m();
  }
  b() {
    return this.a.createInstance($6Tb);
  }
  c() {
    const that = this;
    this.B($hJ(class FocusTitleBar extends $gJ {
      constructor() {
        super({
          id: `workbench.action.focusTitleBar`,
          title: localize2(3786, "Focus Title Bar"),
          category: $qn.View,
          f1: true
        });
      }
      run() {
        that.j($Pj()).focus();
      }
    }));
  }
  m() {
    this.B($tn.registerCommand({
      id: "registerWindowTitleVariable",
      handler: (accessor, name, contextKey) => {
        this.registerVariables([{ name, contextKey }]);
      },
      metadata: {
        description: "Registers a new title variable",
        args: [
          { name: "name", schema: { type: "string" }, description: "The name of the variable to register" },
          { name: "contextKey", schema: { type: "string" }, description: "The context key to use for the value of the variable" }
        ]
      }
    }));
  }
  //#region Auxiliary Titlebar Parts
  createAuxiliaryTitlebarPart(container2, editorGroupsContainer) {
    const titlebarPartContainer = document.createElement("div");
    titlebarPartContainer.classList.add("part", "titlebar");
    titlebarPartContainer.setAttribute("role", "none");
    titlebarPartContainer.style.position = "relative";
    container2.insertBefore(titlebarPartContainer, container2.firstChild);
    const disposables = new $2c();
    const titlebarPart = this.r(titlebarPartContainer, editorGroupsContainer);
    disposables.add(this.registerPart(titlebarPart));
    disposables.add(Event2.runAndSubscribe(titlebarPart.onDidChange, () => titlebarPartContainer.style.height = `${titlebarPart.height}px`));
    titlebarPart.create(titlebarPartContainer);
    if (this.s) {
      titlebarPart.updateProperties(this.s);
    }
    if (this.t.size) {
      titlebarPart.registerVariables(Array.from(this.t.values()));
    }
    Event2.once(titlebarPart.onWillDispose)(() => disposables.dispose());
    return titlebarPart;
  }
  r(container2, editorGroupsContainer) {
    return this.a.createInstance($7Tb, container2, editorGroupsContainer, this.mainPart);
  }
  updateProperties(properties) {
    this.s = properties;
    for (const part of this.parts) {
      part.updateProperties(properties);
    }
  }
  registerVariables(variables) {
    const newVariables = [];
    for (const variable of variables) {
      if (!this.t.has(variable.name)) {
        this.t.set(variable.name, variable);
        newVariables.push(variable);
      }
    }
    for (const part of this.parts) {
      part.registerVariables(newVariables);
    }
  }
};
$4Tb = __decorate([
  __param(0, $Pk),
  __param(1, $jv),
  __param(2, $gs)
], $4Tb);
var $5Tb = class $5Tb2 extends Part {
  get minimumHeight() {
    const wcoEnabled = $r && $3e();
    let value = this.cc || wcoEnabled ? $Fs : 30;
    if (wcoEnabled) {
      value = Math.max(value, $4e(getWindow(this.element))?.height ?? 0);
    }
    return value / (this.preventZoom ? $Pe(getWindow(this.element)) : 1);
  }
  get maximumHeight() {
    return this.minimumHeight;
  }
  constructor(id2, targetWindow, editorGroupsContainer, Cb, Db, Eb, Fb, themeService, Gb, layoutService, Hb, Ib, Jb, editorService, Kb, Lb) {
    super(id2, { hasTitle: false }, themeService, Gb, layoutService);
    this.Cb = Cb;
    this.Db = Db;
    this.Eb = Eb;
    this.Fb = Fb;
    this.Gb = Gb;
    this.Hb = Hb;
    this.Ib = Ib;
    this.Jb = Jb;
    this.Kb = Kb;
    this.Lb = Lb;
    this.minimumWidth = 0;
    this.maximumWidth = Number.POSITIVE_INFINITY;
    this.a = this.B(new $ze());
    this.onMenubarVisibilityChange = this.a.event;
    this.b = this.B(new $ze());
    this.onWillDispose = this.b.event;
    this.nb = this.B(new $2c());
    this.ob = this.B(new $2c());
    this.rb = this.B(new $2c());
    this.sb = this.B(new $2c());
    this.tb = this.B(new $2c());
    this.vb = this.B(new $2c());
    this.wb = $Es(this.Db);
    this.xb = false;
    this.yb = editorGroupsContainer !== "main";
    this.Ab = editorService.createScoped(editorGroupsContainer, this.q);
    this.Bb = editorGroupsContainer === "main" ? Jb.mainPart : editorGroupsContainer;
    this.zb = this.B(Fb.createInstance($0Tb, targetWindow, editorGroupsContainer));
    this.ub = this.B($KZ());
    this.Mb(getWindowId(targetWindow));
  }
  Mb(targetWindowId) {
    this.B(this.Ib.onDidChangeFocus((focused) => focused ? this.Ob() : this.Nb()));
    this.B(this.Ib.onDidChangeActiveWindow((windowId) => windowId === targetWindowId ? this.Ob() : this.Nb()));
    this.B(this.Db.onDidChangeConfiguration((e) => this.Qb(e)));
    this.B(this.Jb.onDidChangeEditorPartOptions((e) => this.Pb(e)));
  }
  Nb() {
    this.xb = true;
    this.updateStyles();
  }
  Ob() {
    this.xb = false;
    this.updateStyles();
  }
  Pb({ oldPartOptions, newPartOptions }) {
    if (oldPartOptions.editorActionsLocation !== newPartOptions.editorActionsLocation || oldPartOptions.showTabs !== newPartOptions.showTabs) {
      if ($Cs(this.Db, this.wb) && this.mb) {
        this.Yb();
        this.Zb({ editorActions: true });
        this.ab.fire(void 0);
      }
    }
  }
  Qb(event) {
    if (!this.yb && !$Ds(this.Db, this.wb) && (!$m || $r)) {
      if (event.affectsConfiguration("window.menuBarVisibility")) {
        if (this.ac === "compact") {
          this.Sb();
        } else {
          this.Rb();
        }
      }
    }
    if ($Cs(this.Db, this.wb) && this.mb) {
      const affectsLayoutControl = event.affectsConfiguration(
        "workbench.layoutControl.enabled"
        /* LayoutSettings.LAYOUT_ACTIONS */
      );
      const affectsActivityControl = event.affectsConfiguration(
        "workbench.activityBar.location"
        /* LayoutSettings.ACTIVITY_BAR_LOCATION */
      );
      if (affectsLayoutControl || affectsActivityControl) {
        this.Zb({ layoutActions: affectsLayoutControl, activityActions: affectsActivityControl });
        this.ab.fire(void 0);
      }
    }
    if (event.affectsConfiguration(
      "window.commandCenter"
      /* LayoutSettings.COMMAND_CENTER */
    )) {
      this.Vb();
      this.ab.fire(void 0);
    }
  }
  Rb() {
    if (this.kb) {
      return;
    }
    this.hb = this.B(this.Fb.createInstance($TTb));
    this.kb = $bk(this.eb, $("div.menubar"));
    this.kb.setAttribute("role", "menubar");
    this.B(this.hb.onVisibilityChange((e) => this.Tb(e)));
    this.hb.create(this.kb);
  }
  Sb() {
    this.hb?.dispose();
    this.hb = void 0;
    this.kb?.remove();
    this.kb = void 0;
    this.Tb(false);
  }
  Tb(visible) {
    if ($r || $l || $n) {
      if (this.lb) {
        this.layout(this.lb.width, this.lb.height);
      }
      this.a.fire(visible);
    }
  }
  updateProperties(properties) {
    this.zb.updateProperties(properties);
  }
  registerVariables(variables) {
    this.zb.registerVariables(variables);
  }
  Q(parent) {
    this.element = parent;
    this.c = $bk(parent, $(".titlebar-container"));
    this.eb = $bk(this.c, $(".titlebar-left"));
    this.fb = $bk(this.c, $(".titlebar-center"));
    this.gb = $bk(this.c, $(".titlebar-right"));
    if (!$m && !$r && !$Ds(this.Db, this.wb)) {
      this.ib = $ck(this.eb, $("a.window-appicon"));
      if (!this.yb && $r) {
        const homeIndicator = this.Eb.options?.homeIndicator;
        if (homeIndicator) {
          const icon2 = $0r().getIcon(homeIndicator.icon) ? { id: homeIndicator.icon } : $6l.code;
          this.ib.setAttribute("href", homeIndicator.href);
          this.ib.classList.add(...ThemeIcon.asClassNameArray(icon2));
          this.jb = document.createElement("div");
          this.jb.classList.add("home-bar-icon-badge");
          this.ib.appendChild(this.jb);
        }
      }
    }
    this.cb = $ck(this.c, $("div.titlebar-drag-region"));
    if (!this.yb && !$Ds(this.Db, this.wb) && (!$m || $r) && this.ac !== "compact") {
      this.Rb();
    }
    this.db = $bk(this.fb, $("div.window-title"));
    this.Vb();
    if ($Cs(this.Db, this.wb)) {
      this.pb = $bk(this.gb, $("div.action-toolbar-container"));
      this.Yb();
      this.Zb();
    }
    if (!$Ds(this.Db, this.wb)) {
      let primaryWindowControlsLocation = $m ? "left" : "right";
      if ($m && $p) {
        const localeInfo = $Uu.Locale($B);
        if (localeInfo?.textInfo?.direction === "rtl") {
          primaryWindowControlsLocation = "right";
        }
      }
      if ($m && $p && primaryWindowControlsLocation === "left") {
      } else {
        this.bb = $bk(primaryWindowControlsLocation === "left" ? this.eb : this.gb, $("div.window-controls-container"));
        if ($r) {
          $bk(primaryWindowControlsLocation === "left" ? this.gb : this.eb, $("div.window-controls-container"));
        }
        if ($3e()) {
          this.bb.classList.add("wco-enabled");
        }
      }
    }
    {
      this.B($_i(this.c, $7j.CONTEXT_MENU, (e) => {
        $9j.stop(e);
        let targetMenu;
        if ($m && $Uj(e.target) && $Dj(e.target, this.db)) {
          targetMenu = $bJ.TitleBarTitleContext;
        } else {
          targetMenu = $bJ.TitleBarContext;
        }
        this.$b(e, targetMenu);
      }));
      if ($m) {
        this.B($_i(
          this.db,
          $7j.MOUSE_DOWN,
          (e) => {
            if (e.metaKey) {
              $9j.stop(
                e,
                true
                /* stop bubbling to prevent command center from opening */
              );
              this.$b(e, $bJ.TitleBarTitleContext);
            }
          },
          true
          /* capture phase to prevent command center from opening */
        ));
      }
    }
    this.updateStyles();
    return this.element;
  }
  Vb() {
    this.vb.clear();
    if (!this.cc) {
      this.db.innerText = this.zb.value;
      this.vb.add(this.zb.onDidChange(() => {
        this.db.innerText = this.zb.value;
      }));
    } else {
      const commandCenter = this.Fb.createInstance($UTb, this.zb, this.ub);
      $dk(this.db, commandCenter.element);
      this.vb.add(commandCenter);
    }
  }
  Wb(action, options3) {
    if (!this.yb) {
      if (action.id === $Pzb) {
        return this.Fb.createInstance($2Tb, {
          position: () => 2
          /* HoverPosition.BELOW */
        }, options3);
      }
      if (action.id === $Qzb) {
        return this.Fb.createInstance($1Tb, {
          position: () => 2
          /* HoverPosition.BELOW */
        }, options3);
      }
    }
    const activeEditorPane = this.Bb.activeGroup?.activeEditorPane;
    if (activeEditorPane && activeEditorPane instanceof $5tb) {
      const result = activeEditorPane.getActionViewItem(action, options3);
      if (result) {
        return result;
      }
    }
    return $X$(this.Fb, action, { ...options3, menuAsChild: false });
  }
  Xb(action) {
    const editorPaneAwareContextKeyService = this.Bb.activeGroup?.activeEditorPane?.scopedContextKeyService ?? this.Hb;
    return this.Lb.lookupKeybinding(action.id, editorPaneAwareContextKeyService);
  }
  Yb() {
    this.nb.clear();
    this.mb = this.nb.add(this.Fb.createInstance($3$, this.pb, {
      contextMenu: $bJ.TitleBarContext,
      orientation: 0,
      ariaLabel: localize(3785, null),
      getKeyBinding: (action) => this.Xb(action),
      overflowBehavior: { maxItems: 9, exempted: [$Qzb, $Pzb, ...$bvb] },
      anchorAlignmentProvider: () => 1,
      telemetrySource: "titlePart",
      highlightToggledItems: this.dc,
      // Only show toggled state for editor actions (Layout actions are not shown as toggled)
      actionViewItemProvider: (action, options3) => this.Wb(action, options3),
      hoverDelegate: this.ub
    }));
    if (this.dc) {
      this.nb.add(this.Bb.onDidChangeActiveGroup(() => this.Zb({ editorActions: true })));
    }
  }
  Zb(update = true) {
    if (update === true) {
      update = { editorActions: true, layoutActions: true, activityActions: true };
    }
    const updateToolBarActions = () => {
      const actions = { primary: [], secondary: [] };
      if (this.dc) {
        this.ob.clear();
        const activeGroup = this.Bb.activeGroup;
        if (activeGroup) {
          const editorActions = activeGroup.createEditorActions(this.ob);
          actions.primary.push(...editorActions.actions.primary);
          actions.secondary.push(...editorActions.actions.secondary);
          this.ob.add(editorActions.onDidChange(() => updateToolBarActions()));
        }
      }
      if (this.ec) {
        if ($3Tb(this.Gb)) {
          actions.primary.push($Szb);
        }
        actions.primary.push($Tzb);
      }
      if (this.qb) {
        $S$(
          this.qb.getActions(),
          actions,
          () => !this.dc
          // Layout Actions in overflow menu when editor actions enabled in title bar
        );
      }
      this.mb.setActions($MZ(actions.primary), $MZ(actions.secondary));
    };
    if (update.editorActions) {
      this.rb.clear();
      if (this.dc && this.Ab.activeEditor !== void 0) {
        const context = { groupId: this.Bb.activeGroup.id };
        this.mb.actionRunner = new $Iyb(context);
        this.mb.context = context;
        this.rb.add(this.mb.actionRunner);
      } else {
        this.mb.actionRunner = new $Vm();
        this.mb.context = void 0;
        this.rb.add(this.mb.actionRunner);
      }
    }
    if (update.layoutActions) {
      this.sb.clear();
      if (this.bc) {
        this.qb = this.Kb.createMenu($bJ.LayoutControlMenu, this.Hb);
        this.sb.add(this.qb);
        this.sb.add(this.qb.onDidChange(() => updateToolBarActions()));
      } else {
        this.qb = void 0;
      }
    }
    if (update.activityActions) {
      this.tb.clear();
      if (this.ec) {
        this.tb.add(this.Gb.onDidChangeValue(0, $YTb.ACCOUNTS_VISIBILITY_PREFERENCE_KEY, this.q)(() => updateToolBarActions()));
      }
    }
    updateToolBarActions();
  }
  updateStyles() {
    super.updateStyles();
    if (this.element) {
      if (this.xb) {
        this.element.classList.add("inactive");
      } else {
        this.element.classList.remove("inactive");
      }
      const titleBackground = this.z(this.xb ? $7nb : $6nb, (color2, theme) => {
        return color2.isOpaque() ? color2 : color2.makeOpaque($4lb(theme));
      }) || "";
      this.element.style.backgroundColor = titleBackground;
      if (this.jb) {
        this.jb.style.backgroundColor = titleBackground;
      }
      if (titleBackground && $Vn.fromHex(titleBackground).isLighter()) {
        this.element.classList.add("light");
      } else {
        this.element.classList.remove("light");
      }
      const titleForeground = this.z(this.xb ? $5nb : $4nb);
      this.element.style.color = titleForeground || "";
      const titleBorder = this.z($8nb);
      this.element.style.borderBottom = titleBorder ? `1px solid ${titleBorder}` : "";
    }
  }
  $b(e, menuId) {
    const event = new $lf(getWindow(this.element), e);
    this.Cb.showContextMenu({
      getAnchor: () => event,
      menuId,
      contextKeyService: this.Hb,
      domForShadowRoot: $m && $p ? event.target : void 0
    });
  }
  get ac() {
    if (this.yb) {
      return "hidden";
    }
    return $Bs(this.Db);
  }
  get bc() {
    return !this.yb && this.Db.getValue(
      "workbench.layoutControl.enabled"
      /* LayoutSettings.LAYOUT_ACTIONS */
    ) !== false;
  }
  get cc() {
    return this.Db.getValue(
      "window.commandCenter"
      /* LayoutSettings.COMMAND_CENTER */
    ) !== false;
  }
  get dc() {
    return this.Jb.partOptions.editorActionsLocation === "titleBar" || this.Jb.partOptions.editorActionsLocation === "default" && this.Jb.partOptions.showTabs === "none";
  }
  get ec() {
    const activityBarPosition = this.Db.getValue(
      "workbench.activityBar.location"
      /* LayoutSettings.ACTIVITY_BAR_LOCATION */
    );
    return !this.yb && (activityBarPosition === "top" || activityBarPosition === "bottom");
  }
  get hasZoomableElements() {
    const hasMenubar = !(this.ac === "hidden" || this.ac === "compact" || !$r && $m);
    const hasCommandCenter = this.cc;
    const hasToolBarActions = this.bc || this.dc || this.ec;
    return hasMenubar || hasCommandCenter || hasToolBarActions;
  }
  get preventZoom() {
    return $Pe(getWindow(this.element)) < 1 || !this.hasZoomableElements;
  }
  layout(width2, height) {
    this.fc(new $rj(width2, height));
    super.Z(width2, height);
  }
  fc(dimension) {
    this.lb = dimension;
    if ($Cs(this.Db, this.wb)) {
      const zoomFactor = $Pe(getWindow(this.element));
      this.element.style.setProperty("--zoom-factor", zoomFactor.toString());
      this.c.classList.toggle("counter-zoom", this.preventZoom);
      if (this.hb) {
        const menubarDimension = new $rj(0, dimension.height);
        this.hb.layout(menubarDimension);
      }
    }
  }
  focus() {
    if (this.hb) {
      this.hb.toggleFocus();
    } else {
      this.element.querySelector('[tabindex]:not([tabindex="-1"])').focus();
    }
  }
  toJSON() {
    return {
      type: "workbench.parts.titlebar"
      /* Parts.TITLEBAR_PART */
    };
  }
  dispose() {
    this.b.fire();
    super.dispose();
  }
};
$5Tb = __decorate([
  __param(3, $50),
  __param(4, $kl),
  __param(5, $M4),
  __param(6, $Pk),
  __param(7, $gs),
  __param(8, $jv),
  __param(9, $Vlb),
  __param(10, $on),
  __param(11, $S4),
  __param(12, $iJ),
  __param(13, $mJ),
  __param(14, $cJ),
  __param(15, $Ty)
], $5Tb);
var $6Tb = class $6Tb2 extends $5Tb {
  constructor(contextMenuService, configurationService, environmentService, instantiationService, themeService, storageService, layoutService, contextKeyService, hostService, editorGroupService, editorService, menuService, keybindingService) {
    super("workbench.parts.titlebar", $Y, "main", contextMenuService, configurationService, environmentService, instantiationService, themeService, storageService, layoutService, contextKeyService, hostService, editorGroupService, editorService, menuService, keybindingService);
  }
};
$6Tb = __decorate([
  __param(0, $50),
  __param(1, $kl),
  __param(2, $M4),
  __param(3, $Pk),
  __param(4, $gs),
  __param(5, $jv),
  __param(6, $Vlb),
  __param(7, $on),
  __param(8, $S4),
  __param(9, $iJ),
  __param(10, $mJ),
  __param(11, $cJ),
  __param(12, $Ty)
], $6Tb);
var $7Tb = class $7Tb2 extends $5Tb {
  static {
    $7Tb_1 = this;
  }
  static {
    this.y = 1;
  }
  get height() {
    return this.minimumHeight;
  }
  constructor(container2, editorGroupsContainer, gc, contextMenuService, configurationService, environmentService, instantiationService, themeService, storageService, layoutService, contextKeyService, hostService, editorGroupService, editorService, menuService, keybindingService) {
    const id2 = $7Tb_1.y++;
    super(`workbench.parts.auxiliaryTitle.${id2}`, getWindow(container2), editorGroupsContainer, contextMenuService, configurationService, environmentService, instantiationService, themeService, storageService, layoutService, contextKeyService, hostService, editorGroupService, editorService, menuService, keybindingService);
    this.container = container2;
    this.gc = gc;
  }
  get preventZoom() {
    return $Pe(getWindow(this.element)) < 1 || !this.gc.hasZoomableElements;
  }
};
$7Tb = $7Tb_1 = __decorate([
  __param(3, $50),
  __param(4, $kl),
  __param(5, $M4),
  __param(6, $Pk),
  __param(7, $gs),
  __param(8, $jv),
  __param(9, $Vlb),
  __param(10, $on),
  __param(11, $S4),
  __param(12, $iJ),
  __param(13, $mJ),
  __param(14, $cJ),
  __param(15, $Ty)
], $7Tb);

// out-build/vs/platform/languagePacks/browser/languagePacks.js
var $Foc = class $Foc2 extends $zX {
  constructor(a, extensionGalleryService, b) {
    super(extensionGalleryService);
    this.a = a;
    this.b = b;
  }
  async getBuiltInExtensionTranslationsUri(id2, language) {
    const queryTimeout = new $ad();
    setTimeout(() => queryTimeout.cancel(), 1e3);
    let result;
    try {
      result = await this.c.query({
        text: `tag:"lp-${language}"`,
        pageSize: 5
      }, queryTimeout.token);
    } catch (err) {
      this.b.error(err);
      return void 0;
    }
    const languagePackExtensions = result.firstPage.find((e) => e.properties.localizedLanguages?.length);
    if (!languagePackExtensions) {
      this.b.trace(`No language pack found for language ${language}`);
      return void 0;
    }
    const manifestTimeout = new $ad();
    setTimeout(() => queryTimeout.cancel(), 1e3);
    const manifest = await this.c.getManifest(languagePackExtensions, manifestTimeout.token);
    const localization = manifest?.contributes?.localizations?.find((l) => l.languageId === language);
    const translation = localization?.translations.find((t) => t.id === id2);
    if (!translation) {
      this.b.trace(`No translation found for id '${id2}, in ${manifest?.name}`);
      return void 0;
    }
    const uri = this.a.getExtensionGalleryResourceURL({
      // If translation is defined then manifest should have been defined.
      name: manifest.name,
      publisher: manifest.publisher,
      version: manifest.version
    });
    if (!uri) {
      this.b.trace("Gallery does not provide extension resources.");
      return void 0;
    }
    return URI.joinPath(uri, translation.path);
  }
  // Web doesn't have a concept of language packs, so we just return an empty array
  getInstalledLanguages() {
    return Promise.resolve([]);
  }
};
$Foc = __decorate([
  __param(0, $Olb),
  __param(1, $pA),
  __param(2, $wn)
], $Foc);

// out-build/vs/workbench/contrib/logs/common/logsDataCleaner.js
var $Goc = class $Goc2 extends $3c {
  constructor(a, b, c) {
    super();
    this.a = a;
    this.b = b;
    this.c = c;
    this.f();
  }
  f() {
    let handle2 = setTimeout(async () => {
      handle2 = void 0;
      const stat = await this.b.resolve($uh(this.a.logsHome));
      if (stat.children) {
        const currentLog = $sh(this.a.logsHome);
        const allSessions = stat.children.filter((stat2) => stat2.isDirectory && /^\d{8}T\d{6}$/.test(stat2.name));
        const oldSessions = allSessions.sort().filter((d, i2) => d.name !== currentLog);
        const toDelete = oldSessions.slice(0, Math.max(0, oldSessions.length - 49));
        Promises.settled(toDelete.map((stat2) => this.b.del(stat2.resource, { recursive: true })));
      }
    }, 10 * 1e3);
    this.c.onWillShutdown(() => {
      if (handle2) {
        clearTimeout(handle2);
        handle2 = void 0;
      }
    });
  }
};
$Goc = __decorate([
  __param(0, $US),
  __param(1, $km),
  __param(2, $KL)
], $Goc);

// out-build/vs/workbench/contrib/logs/browser/logs.contribution.js
var WebLogOutputChannels = class WebLogOutputChannels2 extends $3c {
  constructor(a) {
    super();
    this.a = a;
    this.b();
  }
  b() {
    this.a.createInstance($Goc);
    this.B($hJ(class extends $gJ {
      constructor() {
        super({
          id: $p_b.ID,
          title: $p_b.TITLE,
          category: $qn.Developer,
          f1: true
        });
      }
      run(servicesAccessor) {
        return servicesAccessor.get($Pk).createInstance($p_b, $p_b.ID, $p_b.TITLE.value).run();
      }
    }));
  }
};
WebLogOutputChannels = __decorate([
  __param(0, $Pk)
], WebLogOutputChannels);
$Wn.as(Extensions2.Workbench).registerWorkbenchContribution(
  WebLogOutputChannels,
  3
  /* LifecyclePhase.Restored */
);

// out-build/vs/workbench/contrib/localization/common/localizationsActions.js
var $Hoc = class _$Hoc extends $gJ {
  static {
    this.ID = "workbench.action.configureLocale";
  }
  constructor() {
    super({
      id: _$Hoc.ID,
      title: localize2(7773, "Configure Display Language"),
      menu: {
        id: $bJ.CommandPalette
      },
      metadata: {
        description: localize2(7774, "Changes the locale of VS Code based on installed language packs. Common languages include French, Chinese, Spanish, Japanese, German, Korean, and more.")
      }
    });
  }
  async run(accessor) {
    const languagePackService = accessor.get($yX);
    const quickInputService = accessor.get($1M);
    const localeService = accessor.get($NCb);
    const extensionWorkbenchService = accessor.get($vzb);
    const installedLanguages = await languagePackService.getInstalledLanguages();
    const disposables = new $2c();
    const qp = disposables.add(quickInputService.createQuickPick({ useSeparators: true }));
    qp.matchOnDescription = true;
    qp.placeholder = localize(7769, null);
    if (installedLanguages?.length) {
      const items = [{ type: "separator", label: localize(7770, null) }];
      qp.items = items.concat(this.a(installedLanguages));
    }
    const source = new $ad();
    disposables.add(qp.onDispose(() => {
      source.cancel();
      disposables.dispose();
    }));
    const installedSet = new Set(installedLanguages?.map((language) => language.id) ?? []);
    languagePackService.getAvailableLanguages().then((availableLanguages) => {
      const newLanguages = availableLanguages.filter((l) => l.id && !installedSet.has(l.id));
      if (newLanguages.length) {
        qp.items = [
          ...qp.items,
          { type: "separator", label: localize(7771, null) },
          ...this.a(newLanguages)
        ];
      }
      qp.busy = false;
    });
    disposables.add(qp.onDidAccept(async () => {
      const selectedLanguage = qp.activeItems[0];
      if (selectedLanguage) {
        qp.hide();
        await localeService.setLocale(selectedLanguage);
      }
    }));
    disposables.add(qp.onDidTriggerItemButton(async (e) => {
      qp.hide();
      if (e.item.extensionId) {
        await extensionWorkbenchService.open(e.item.extensionId);
      }
    }));
    qp.show();
    qp.busy = true;
  }
  a(items) {
    for (const item of items) {
      if (item.extensionId) {
        item.buttons = [{
          tooltip: localize(7772, null),
          iconClass: "codicon-info"
        }];
      }
    }
    return items;
  }
};
var $Ioc = class _$Ioc extends $gJ {
  static {
    this.ID = "workbench.action.clearLocalePreference";
  }
  static {
    this.LABEL = localize2(7775, "Clear Display Language Preference");
  }
  constructor() {
    super({
      id: _$Ioc.ID,
      title: _$Ioc.LABEL,
      menu: {
        id: $bJ.CommandPalette
      }
    });
  }
  async run(accessor) {
    const localeService = accessor.get($NCb);
    await localeService.clearLocalePreference();
  }
};

// out-build/vs/workbench/contrib/localization/common/localization.contribution.js
var $Joc = class extends $3c {
  constructor() {
    super();
    $hJ($Hoc);
    $hJ($Ioc);
    $tN.registerExtensionPoint({
      extensionPoint: "localizations",
      defaultExtensionKind: ["ui", "workspace"],
      jsonSchema: {
        description: localize(7757, null),
        type: "array",
        default: [],
        items: {
          type: "object",
          required: ["languageId", "translations"],
          defaultSnippets: [{ body: { languageId: "", languageName: "", localizedLanguageName: "", translations: [{ id: "vscode", path: "" }] } }],
          properties: {
            languageId: {
              description: localize(7758, null),
              type: "string"
            },
            languageName: {
              description: localize(7759, null),
              type: "string"
            },
            localizedLanguageName: {
              description: localize(7760, null),
              type: "string"
            },
            translations: {
              description: localize(7761, null),
              type: "array",
              default: [{ id: "vscode", path: "" }],
              items: {
                type: "object",
                required: ["id", "path"],
                properties: {
                  id: {
                    type: "string",
                    description: localize(7762, null),
                    pattern: "^((vscode)|([a-z0-9A-Z][a-z0-9A-Z-]*)\\.([a-z0-9A-Z][a-z0-9A-Z-]*))$",
                    patternErrorMessage: localize(7763, null)
                  },
                  path: {
                    type: "string",
                    description: localize(7764, null)
                  }
                },
                defaultSnippets: [{ body: { id: "", path: "" } }]
              }
            }
          }
        }
      }
    });
  }
};
var LocalizationsDataRenderer = class extends $3c {
  constructor() {
    super(...arguments);
    this.type = "table";
  }
  shouldRender(manifest) {
    return !!manifest.contributes?.localizations;
  }
  render(manifest) {
    const localizations = manifest.contributes?.localizations || [];
    if (!localizations.length) {
      return { data: { headers: [], rows: [] }, dispose: () => {
      } };
    }
    const headers = [
      localize(7765, null),
      localize(7766, null),
      localize(7767, null)
    ];
    const rows = localizations.sort((a, b) => a.languageId.localeCompare(b.languageId)).map((localization) => {
      return [
        localization.languageId,
        localization.languageName ?? "",
        localization.localizedLanguageName ?? ""
      ];
    });
    return {
      data: {
        headers,
        rows
      },
      dispose: () => {
      }
    };
  }
};
$Wn.as(Extensions3.ExtensionFeaturesRegistry).registerExtensionFeature({
  id: "localizations",
  label: localize(7768, null),
  access: {
    canToggle: false
  },
  renderer: new $Nk(LocalizationsDataRenderer)
});

// out-build/vs/workbench/contrib/localization/browser/localization.contribution.js
var $Koc = class extends $Joc {
};
var workbenchRegistry9 = $Wn.as(Extensions2.Workbench);
workbenchRegistry9.registerWorkbenchContribution(
  $Koc,
  4
  /* LifecyclePhase.Eventually */
);

// out-build/vs/workbench/contrib/performance/browser/startupTimings.js
var $Loc = class $Loc2 {
  constructor(a, b, c, d, e) {
    this.a = a;
    this.b = b;
    this.c = c;
    this.d = d;
    this.e = e;
  }
  async f() {
    if (this.c.startupKind !== 1) {
      return $LL(this.c.startupKind);
    }
    if (!this.e.isWorkspaceTrusted()) {
      return "Workspace not trusted";
    }
    const activeViewlet = this.b.getActivePaneComposite(
      0
      /* ViewContainerLocation.Sidebar */
    );
    if (!activeViewlet || activeViewlet.getId() !== $3sb) {
      return "Explorer viewlet not visible";
    }
    const visibleEditorPanes = this.a.visibleEditorPanes;
    if (visibleEditorPanes.length !== 1) {
      return `Expected text editor count : 1, Actual : ${visibleEditorPanes.length}`;
    }
    if (!$P5(visibleEditorPanes[0].getControl())) {
      return "Active editor is not a text editor";
    }
    const activePanel = this.b.getActivePaneComposite(
      1
      /* ViewContainerLocation.Panel */
    );
    if (activePanel) {
      return `Current active panel : ${this.b.getPaneComposite(
        activePanel.getId(),
        1
        /* ViewContainerLocation.Panel */
      )?.name}`;
    }
    const isLatestVersion = await this.d.isLatestVersion();
    if (isLatestVersion === false) {
      return "Not on latest version, updates available";
    }
    return void 0;
  }
};
$Loc = __decorate([
  __param(0, $mJ),
  __param(1, $uqb),
  __param(2, $KL),
  __param(3, $az),
  __param(4, $4M)
], $Loc);
var $Moc = class $Moc2 extends $Loc {
  constructor(editorService, paneCompositeService, lifecycleService, updateService, workspaceTrustService, g, h3, i2, j, k) {
    super(editorService, paneCompositeService, lifecycleService, updateService, workspaceTrustService);
    this.g = g;
    this.h = h3;
    this.i = i2;
    this.j = j;
    this.k = k;
    this.l();
  }
  async l() {
    if (!this.i.profDurationMarkers) {
      return;
    }
    await this.g.whenReady();
    const standardStartupError = await this.f();
    const perfBaseline = await this.g.perfBaseline;
    const [from, to] = this.i.profDurationMarkers;
    const content = `${this.g.getDuration(from, to)}	${this.k.nameShort}	${(this.k.commit || "").slice(0, 10) || "0000000000"}	${this.j.sessionId}	${standardStartupError === void 0 ? "standard_start" : "NO_standard_start : " + standardStartupError}	${String(perfBaseline).padStart(4, "0")}ms
`;
    this.h.info(`[prof-timers] ${content}`);
  }
};
$Moc = __decorate([
  __param(0, $mJ),
  __param(1, $uqb),
  __param(2, $KL),
  __param(3, $az),
  __param(4, $4M),
  __param(5, $iQb),
  __param(6, $wn),
  __param(7, $M4),
  __param(8, $zv),
  __param(9, $Vu)
], $Moc);
var $Noc = class $Noc2 {
  constructor(telemetryService) {
    for (const item of performance.getEntriesByType("resource")) {
      try {
        const url = new URL(item.name);
        const name = $kc.basename(url.pathname);
        telemetryService.publicLog2("startup.resource.perf", {
          hosthash: `H${$Xi(url.host).toString(16)}`,
          name,
          duration: item.duration
        });
      } catch {
      }
    }
  }
};
$Noc = __decorate([
  __param(0, $zv)
], $Noc);

// out-build/vs/workbench/contrib/performance/browser/performance.web.contribution.js
$Wn.as(Extensions2.Workbench).registerWorkbenchContribution(
  $Noc,
  4
  /* LifecyclePhase.Eventually */
);
$Wn.as(Extensions2.Workbench).registerWorkbenchContribution(
  $Moc,
  4
  /* LifecyclePhase.Eventually */
);

// out-build/vs/workbench/contrib/preferences/browser/keyboardLayoutPicker.js
var $Ooc = class $Ooc2 extends $3c {
  static {
    this.ID = "workbench.contrib.keyboardLayoutPicker";
  }
  constructor(f, g) {
    super();
    this.f = f;
    this.g = g;
    this.c = this.B(new $4c());
    const name = localize(8758, null);
    const layout = this.f.getCurrentKeyboardLayout();
    if (layout) {
      const layoutInfo = $Xy(layout);
      const text2 = localize(8759, null, layoutInfo.label);
      this.c.value = this.g.addEntry(
        {
          name,
          text: text2,
          ariaLabel: text2,
          command: $FZb
        },
        "status.workbench.keyboardLayout",
        1
        /* StatusbarAlignment.RIGHT */
      );
    }
    this.B(this.f.onDidChangeKeyboardLayout(() => {
      const layout2 = this.f.getCurrentKeyboardLayout();
      const layoutInfo = $Xy(layout2);
      if (this.c.value) {
        const text2 = localize(8760, null, layoutInfo.label);
        this.c.value.update({
          name,
          text: text2,
          ariaLabel: text2,
          command: $FZb
        });
      } else {
        const text2 = localize(8761, null, layoutInfo.label);
        this.c.value = this.g.addEntry(
          {
            name,
            text: text2,
            ariaLabel: text2,
            command: $FZb
          },
          "status.workbench.keyboardLayout",
          1
          /* StatusbarAlignment.RIGHT */
        );
      }
    }));
  }
};
$Ooc = __decorate([
  __param(0, $Vy),
  __param(1, $$qb)
], $Ooc);
$PL(
  $Ooc.ID,
  $Ooc,
  1
  /* WorkbenchPhase.BlockStartup */
);
var DEFAULT_CONTENT = [
  `// ${localize(8762, null)}`,
  `// ${localize(8763, null)}`,
  ``,
  `// Once you have the keyboard layout info, please paste it below.`,
  "\n"
].join("\n");
$hJ(class extends $gJ {
  constructor() {
    super({
      id: $FZb,
      title: localize2(8769, "Change Keyboard Layout"),
      f1: true
    });
  }
  async run(accessor) {
    const keyboardLayoutService = accessor.get($Vy);
    const quickInputService = accessor.get($1M);
    const configurationService = accessor.get($kl);
    const environmentService = accessor.get($Xk);
    const editorService = accessor.get($mJ);
    const fileService = accessor.get($km);
    const layouts = keyboardLayoutService.getAllKeyboardLayouts();
    const currentLayout = keyboardLayoutService.getCurrentKeyboardLayout();
    const layoutConfig = configurationService.getValue("keyboard.layout");
    const isAutoDetect = layoutConfig === "autodetect";
    const picks = layouts.map((layout) => {
      const picked = !isAutoDetect && $Wy(currentLayout, layout);
      const layoutInfo = $Xy(layout);
      return {
        layout,
        label: [layoutInfo.label, layout && layout.isUserKeyboardLayout ? "(User configured layout)" : ""].join(" "),
        id: layout.text || layout.lang || layout.layout,
        description: layoutInfo.description + (picked ? " (Current layout)" : ""),
        picked: !isAutoDetect && $Wy(currentLayout, layout)
      };
    }).sort((a, b) => {
      return a.label < b.label ? -1 : a.label > b.label ? 1 : 0;
    });
    if (picks.length > 0) {
      const platform = $m ? "Mac" : $l ? "Win" : "Linux";
      picks.unshift({ type: "separator", label: localize(8764, null, platform) });
    }
    const configureKeyboardLayout = { label: localize(8765, null) };
    picks.unshift(configureKeyboardLayout);
    const autoDetectMode = {
      label: localize(8766, null),
      description: isAutoDetect ? `Current: ${$Xy(currentLayout).label}` : void 0,
      picked: isAutoDetect ? true : void 0
    };
    picks.unshift(autoDetectMode);
    const pick = await quickInputService.pick(picks, { placeHolder: localize(8767, null), matchOnDescription: true });
    if (!pick) {
      return;
    }
    if (pick === autoDetectMode) {
      configurationService.updateValue("keyboard.layout", "autodetect");
      return;
    }
    if (pick === configureKeyboardLayout) {
      const file = environmentService.keyboardLayoutResource;
      await fileService.stat(file).then(void 0, () => {
        return fileService.createFile(file, $Ci.fromString(DEFAULT_CONTENT));
      }).then((stat) => {
        if (!stat) {
          return void 0;
        }
        return editorService.openEditor({
          resource: stat.resource,
          languageId: "jsonc",
          options: { pinned: true }
        });
      }, (error) => {
        throw new Error(localize(8768, null, file.toString(), error));
      });
      return Promise.resolve();
    }
    configurationService.updateValue("keyboard.layout", $Yy(pick.layout));
  }
});

// out-build/vs/platform/debug/common/extensionHostDebugIpc.js
var $Bx = class {
  constructor() {
    this.a = new $ze();
    this.b = new $ze();
    this.c = new $ze();
    this.d = new $ze();
  }
  static {
    this.ChannelName = "extensionhostdebugservice";
  }
  call(ctx, command4, arg) {
    switch (command4) {
      case "close":
        return Promise.resolve(this.a.fire({ sessionId: arg[0] }));
      case "reload":
        return Promise.resolve(this.b.fire({ sessionId: arg[0] }));
      case "terminate":
        return Promise.resolve(this.c.fire({ sessionId: arg[0] }));
      case "attach":
        return Promise.resolve(this.d.fire({ sessionId: arg[0], port: arg[1], subId: arg[2] }));
    }
    throw new Error("Method not implemented.");
  }
  listen(ctx, event, arg) {
    switch (event) {
      case "close":
        return this.a.event;
      case "reload":
        return this.b.event;
      case "terminate":
        return this.c.event;
      case "attach":
        return this.d.event;
    }
    throw new Error("Method not implemented.");
  }
};
var $Cx = class extends $3c {
  constructor(b) {
    super();
    this.b = b;
  }
  reload(sessionId) {
    this.b.call("reload", [sessionId]);
  }
  get onReload() {
    return this.b.listen("reload");
  }
  close(sessionId) {
    this.b.call("close", [sessionId]);
  }
  get onClose() {
    return this.b.listen("close");
  }
  attachSession(sessionId, port, subId) {
    this.b.call("attach", [sessionId, port, subId]);
  }
  get onAttachSession() {
    return this.b.listen("attach");
  }
  terminateSession(sessionId, subId) {
    this.b.call("terminate", [sessionId, subId]);
  }
  get onTerminateSession() {
    return this.b.listen("terminate");
  }
  openExtensionDevelopmentHostWindow(args2, debugRenderer) {
    return this.b.call("openExtensionDevelopmentHostWindow", [args2, debugRenderer]);
  }
};

// out-build/vs/workbench/contrib/debug/browser/extensionHostDebugService.js
var BrowserExtensionHostDebugService_1;
var BrowserExtensionHostDebugService = class BrowserExtensionHostDebugService2 extends $Cx {
  static {
    BrowserExtensionHostDebugService_1 = this;
  }
  static {
    this.c = "debug.lastExtensionDevelopmentWorkspace";
  }
  constructor(remoteAgentService, environmentService, logService, hostService, contextService, storageService, fileService) {
    const connection = remoteAgentService.getConnection();
    let channel;
    if (connection) {
      channel = connection.getChannel($Bx.ChannelName);
    } else {
      channel = { call: async () => void 0, listen: () => Event2.None };
    }
    super(channel);
    this.g = storageService;
    this.h = fileService;
    if (environmentService.options && environmentService.options.workspaceProvider) {
      this.f = environmentService.options.workspaceProvider;
    } else {
      this.f = { open: async () => true, workspace: void 0, trusted: void 0 };
      logService.warn("Extension Host Debugging not available due to missing workspace provider.");
    }
    this.B(this.onReload((event) => {
      if (environmentService.isExtensionDevelopment && environmentService.debugExtensionHost.debugId === event.sessionId) {
        hostService.reload();
      }
    }));
    this.B(this.onClose((event) => {
      if (environmentService.isExtensionDevelopment && environmentService.debugExtensionHost.debugId === event.sessionId) {
        hostService.close();
      }
    }));
    if (environmentService.isExtensionDevelopment && !environmentService.extensionTestsLocationURI) {
      const workspaceId = $5k(contextService.getWorkspace());
      if ($1k(workspaceId) || $6k(workspaceId)) {
        const serializedWorkspace = $1k(workspaceId) ? { folderUri: workspaceId.uri.toJSON() } : { workspaceUri: workspaceId.configPath.toJSON() };
        storageService.store(
          BrowserExtensionHostDebugService_1.c,
          JSON.stringify(serializedWorkspace),
          0,
          1
          /* StorageTarget.MACHINE */
        );
      } else {
        storageService.remove(
          BrowserExtensionHostDebugService_1.c,
          0
          /* StorageScope.PROFILE */
        );
      }
    }
  }
  async openExtensionDevelopmentHostWindow(args2, _debugRenderer) {
    const environment = /* @__PURE__ */ new Map();
    const fileUriArg = this.j("file-uri", args2);
    if (fileUriArg && !$jl(fileUriArg)) {
      environment.set("openFile", fileUriArg);
    }
    const copyArgs = [
      "extensionDevelopmentPath",
      "extensionTestsPath",
      "extensionEnvironment",
      "debugId",
      "inspect-brk-extensions",
      "inspect-extensions"
    ];
    for (const argName of copyArgs) {
      const value = this.j(argName, args2);
      if (value) {
        environment.set(argName, value);
      }
    }
    let debugWorkspace = void 0;
    const folderUriArg = this.j("folder-uri", args2);
    if (folderUriArg) {
      debugWorkspace = { folderUri: URI.parse(folderUriArg) };
    } else {
      const fileUriArg2 = this.j("file-uri", args2);
      if (fileUriArg2 && $jl(fileUriArg2)) {
        debugWorkspace = { workspaceUri: URI.parse(fileUriArg2) };
      }
    }
    const extensionTestsPath = this.j("extensionTestsPath", args2);
    if (!debugWorkspace && !extensionTestsPath) {
      const lastExtensionDevelopmentWorkspace = this.g.get(
        BrowserExtensionHostDebugService_1.c,
        0
        /* StorageScope.PROFILE */
      );
      if (lastExtensionDevelopmentWorkspace) {
        try {
          const serializedWorkspace = JSON.parse(lastExtensionDevelopmentWorkspace);
          if (serializedWorkspace.workspaceUri) {
            debugWorkspace = { workspaceUri: URI.revive(serializedWorkspace.workspaceUri) };
          } else if (serializedWorkspace.folderUri) {
            debugWorkspace = { folderUri: URI.revive(serializedWorkspace.folderUri) };
          }
        } catch (error) {
        }
      }
    }
    if (debugWorkspace) {
      const debugWorkspaceResource = $zs(debugWorkspace) ? debugWorkspace.folderUri : $ys(debugWorkspace) ? debugWorkspace.workspaceUri : void 0;
      if (debugWorkspaceResource) {
        const workspaceExists = await this.h.exists(debugWorkspaceResource);
        if (!workspaceExists) {
          debugWorkspace = void 0;
        }
      }
    }
    const success = await this.f.open(debugWorkspace, {
      reuse: false,
      // debugging always requires a new window
      payload: Array.from(environment.entries())
      // mandatory properties to enable debugging
    });
    return { success };
  }
  j(key2, args2) {
    for (const a of args2) {
      const k = `--${key2}=`;
      if (a.indexOf(k) === 0) {
        return a.substring(k.length);
      }
    }
    return void 0;
  }
};
BrowserExtensionHostDebugService = BrowserExtensionHostDebugService_1 = __decorate([
  __param(0, $RL),
  __param(1, $M4),
  __param(2, $wn),
  __param(3, $S4),
  __param(4, $Zk),
  __param(5, $jv),
  __param(6, $km)
], BrowserExtensionHostDebugService);
$SC(
  $Ax,
  BrowserExtensionHostDebugService,
  1
  /* InstantiationType.Delayed */
);

// out-build/vs/workbench/contrib/welcomeBanner/browser/welcomeBanner.contribution.js
var WelcomeBannerContribution_1;
var WelcomeBannerContribution = class WelcomeBannerContribution2 {
  static {
    WelcomeBannerContribution_1 = this;
  }
  static {
    this.a = "workbench.banner.welcome.dismissed";
  }
  constructor(bannerService, storageService, environmentService) {
    const welcomeBanner = environmentService.options?.welcomeBanner;
    if (!welcomeBanner) {
      return;
    }
    if (storageService.getBoolean(WelcomeBannerContribution_1.a, 0, false)) {
      return;
    }
    let icon2 = void 0;
    if (typeof welcomeBanner.icon === "string") {
      icon2 = ThemeIcon.fromId(welcomeBanner.icon);
    } else if (welcomeBanner.icon) {
      icon2 = URI.revive(welcomeBanner.icon);
    }
    bannerService.show({
      id: "welcome.banner",
      message: welcomeBanner.message,
      icon: icon2,
      actions: welcomeBanner.actions,
      onClose: () => {
        storageService.store(
          WelcomeBannerContribution_1.a,
          true,
          0,
          1
          /* StorageTarget.MACHINE */
        );
      }
    });
  }
};
WelcomeBannerContribution = WelcomeBannerContribution_1 = __decorate([
  __param(0, $jVb),
  __param(1, $jv),
  __param(2, $M4)
], WelcomeBannerContribution);
$Wn.as(Extensions2.Workbench).registerWorkbenchContribution(
  WelcomeBannerContribution,
  3
  /* LifecyclePhase.Restored */
);

// out-build/vs/workbench/contrib/welcomeDialog/browser/welcomeWidget.js
var $Poc = class extends $3c {
  constructor(g, h3, j, m, n) {
    super();
    this.g = g;
    this.h = h3;
    this.j = j;
    this.m = m;
    this.n = n;
    this.f = this.h.createInstance($Q_, {});
    this.t = false;
    this.a = document.createElement("div");
    this.a.className = "welcome-widget";
    this.b = this.a.appendChild($(".monaco-dialog-box"));
    this.b.setAttribute("role", "dialog");
    $ik(this.a);
    this.c = this.b.appendChild($(".dialog-message-container"));
  }
  async executeCommand(commandId, ...args2) {
    try {
      await this.j.executeCommand(commandId, ...args2);
      this.m.publicLog2("workbenchActionExecuted", {
        id: commandId,
        from: "welcomeWidget"
      });
    } catch (ex) {
    }
  }
  async render(title, message, buttonText, buttonAction) {
    if (!this.g._getViewModel()) {
      return;
    }
    await this.r(title, message, buttonText, buttonAction);
    this.g.addOverlayWidget(this);
    this.u();
    this.m.publicLog2("workbenchActionExecuted", {
      id: "welcomeWidgetRendered",
      from: "welcomeWidget"
    });
  }
  async r(title, message, buttonText, buttonAction) {
    const actionBar = this.B(new $LZ(this.b, {}));
    const action = this.B(new $Um("dialog.close", localize(11809, null), ThemeIcon.asClassName($6l.dialogClose), true, async () => {
      this.w();
    }));
    actionBar.push(action, { icon: true, label: false });
    const renderBody = (message2, icon2) => {
      const mds = new $bm(void 0, { supportThemeIcons: true, supportHtml: true });
      mds.appendMarkdown(`<a class="copilot">$(${icon2})</a>`);
      mds.appendMarkdown(message2);
      return mds;
    };
    const titleElement = this.c.appendChild($("#monaco-dialog-message-detail.dialog-message-detail-title"));
    const titleElementMdt = this.f.render(renderBody(title, "zap"));
    titleElement.appendChild(titleElementMdt.element);
    this.s(this.c, message.split("\n").filter((x) => x).map((text2) => $U3(text2)));
    const buttonsRowElement = this.c.appendChild($(".dialog-buttons-row"));
    const buttonContainer = buttonsRowElement.appendChild($(".dialog-buttons"));
    const buttonBar = this.B(new $n2(buttonContainer));
    const primaryButton = this.B(buttonBar.addButtonWithDescription({ title: true, secondary: false, ...$q$ }));
    primaryButton.label = $7t(buttonText, true);
    this.B(primaryButton.onDidClick(async () => {
      await this.executeCommand(buttonAction);
    }));
    buttonBar.buttons[0].focus();
  }
  s(container2, text2) {
    for (const linkedText of text2) {
      const p = $bk(container2, $("p"));
      for (const node of linkedText.nodes) {
        if (typeof node === "string") {
          const labelWithIcon = $B1(node);
          for (const element of labelWithIcon) {
            if (typeof element === "string") {
              p.appendChild($RZ(element, { inline: true, renderCodeSegments: true }));
            } else {
              p.appendChild(element);
            }
          }
        } else {
          const link2 = this.h.createInstance(Link2, p, node, {
            opener: (href) => {
              this.m.publicLog2("workbenchActionExecuted", {
                id: "welcomeWidetLinkAction",
                from: "welcomeWidget"
              });
              this.n.open(href, { allowCommands: true });
            }
          });
          this.B(link2);
        }
      }
    }
    return container2;
  }
  getId() {
    return "editor.contrib.welcomeWidget";
  }
  getDomNode() {
    return this.a;
  }
  getPosition() {
    return {
      preference: 0
      /* OverlayWidgetPositionPreference.TOP_RIGHT_CORNER */
    };
  }
  u() {
    if (this.t) {
      return;
    }
    this.t = true;
    this.a.style.display = "block";
  }
  w() {
    if (!this.t) {
      return;
    }
    this.t = true;
    this.a.style.display = "none";
    this.g.removeOverlayWidget(this);
    this.m.publicLog2("workbenchActionExecuted", {
      id: "welcomeWidgetDismissed",
      from: "welcomeWidget"
    });
  }
};
$ms((theme, collector) => {
  const addBackgroundColorRule = (selector, color2) => {
    if (color2) {
      collector.addRule(`.monaco-editor ${selector} { background-color: ${color2}; }`);
    }
  };
  const widgetBackground = theme.getColor($Qo);
  addBackgroundColorRule(".welcome-widget", widgetBackground);
  const widgetShadowColor = theme.getColor($Rp);
  if (widgetShadowColor) {
    collector.addRule(`.welcome-widget { box-shadow: 0 0 8px 2px ${widgetShadowColor}; }`);
  }
  const widgetBorderColor = theme.getColor($Sp);
  if (widgetBorderColor) {
    collector.addRule(`.welcome-widget { border-left: 1px solid ${widgetBorderColor}; border-right: 1px solid ${widgetBorderColor}; border-bottom: 1px solid ${widgetBorderColor}; }`);
  }
  const hcBorder = theme.getColor($ko);
  if (hcBorder) {
    collector.addRule(`.welcome-widget { border: 1px solid ${hcBorder}; }`);
  }
  const foreground = theme.getColor($Ro);
  if (foreground) {
    collector.addRule(`.welcome-widget { color: ${foreground}; }`);
  }
});

// out-build/vs/workbench/contrib/welcomeDialog/browser/welcomeDialog.contribution.js
var configurationKey3 = "workbench.welcome.experimental.dialog";
var WelcomeDialogContribution = class WelcomeDialogContribution2 extends $3c {
  constructor(storageService, environmentService, configurationService, contextService, codeEditorService, instantiationService, commandService, telemetryService, openerService, editorService) {
    super();
    this.a = false;
    if (!storageService.isNew(
      -1
      /* StorageScope.APPLICATION */
    )) {
      return;
    }
    const setting = configurationService.inspect(configurationKey3);
    if (!setting.value) {
      return;
    }
    const welcomeDialog = environmentService.options?.welcomeDialog;
    if (!welcomeDialog) {
      return;
    }
    this.B(editorService.onDidActiveEditorChange(() => {
      if (!this.a) {
        const codeEditor = codeEditorService.getActiveCodeEditor();
        if (codeEditor?.hasModel()) {
          const scheduler = new $8h(() => {
            const notificationsVisible = contextService.contextMatchesRules($7m.deserialize("notificationCenterVisible")) || contextService.contextMatchesRules($7m.deserialize("notificationToastsVisible"));
            if (codeEditor === codeEditorService.getActiveCodeEditor() && !notificationsVisible) {
              this.a = true;
              const welcomeWidget = new $Poc(codeEditor, instantiationService, commandService, telemetryService, openerService);
              welcomeWidget.render(welcomeDialog.title, welcomeDialog.message, welcomeDialog.buttonText, welcomeDialog.buttonCommand);
            }
          }, 3e3);
          this.B(codeEditor.onDidChangeModelContent((e) => {
            if (!this.a) {
              scheduler.schedule();
            }
          }));
        }
      }
    }));
  }
};
WelcomeDialogContribution = __decorate([
  __param(0, $jv),
  __param(1, $M4),
  __param(2, $kl),
  __param(3, $on),
  __param(4, $U5),
  __param(5, $Pk),
  __param(6, $sn),
  __param(7, $zv),
  __param(8, $O4),
  __param(9, $mJ)
], WelcomeDialogContribution);
$Wn.as(Extensions2.Workbench).registerWorkbenchContribution(
  WelcomeDialogContribution,
  4
  /* LifecyclePhase.Eventually */
);
var configurationRegistry21 = $Wn.as($Ht.Configuration);
configurationRegistry21.registerConfiguration({
  ...$TL,
  properties: {
    "workbench.welcome.experimental.dialog": {
      scope: 1,
      type: "boolean",
      default: false,
      tags: ["experimental"],
      description: localize(11808, null)
    }
  }
});

// out-build/vs/workbench/contrib/webview/browser/themeing.js
var $Qoc = class $Qoc2 extends $3c {
  constructor(c, f) {
    super();
    this.c = c;
    this.f = f;
    this.a = void 0;
    this.b = this.B(new $ze());
    this.onThemeDataChanged = this.b.event;
    this.B(this.c.onDidColorThemeChange(() => {
      this.g();
    }));
    const webviewConfigurationKeys = ["editor.fontFamily", "editor.fontWeight", "editor.fontSize", "accessibility.underlineLinks"];
    this.B(this.f.onDidChangeConfiguration((e) => {
      if (webviewConfigurationKeys.some((key2) => e.affectsConfiguration(key2))) {
        this.g();
      }
    }));
  }
  getTheme() {
    return this.c.getColorTheme();
  }
  getWebviewThemeData() {
    if (!this.a) {
      const configuration2 = this.f.getValue("editor");
      const editorFontFamily = configuration2.fontFamily || EDITOR_FONT_DEFAULTS.fontFamily;
      const editorFontWeight = configuration2.fontWeight || EDITOR_FONT_DEFAULTS.fontWeight;
      const editorFontSize = configuration2.fontSize || EDITOR_FONT_DEFAULTS.fontSize;
      const linkUnderlines = this.f.getValue("accessibility.underlineLinks");
      const theme = this.c.getColorTheme();
      const exportedColors = $6n().getColors().reduce((colors, entry) => {
        const color2 = theme.getColor(entry.id);
        if (color2) {
          colors["vscode-" + entry.id.replace(".", "-")] = color2.toString();
        }
        return colors;
      }, {});
      const styles = {
        "vscode-font-family": $91,
        "vscode-font-weight": "normal",
        "vscode-font-size": "13px",
        "vscode-editor-font-family": editorFontFamily,
        "vscode-editor-font-weight": editorFontWeight,
        "vscode-editor-font-size": editorFontSize + "px",
        "text-link-decoration": linkUnderlines ? "underline" : "none",
        ...exportedColors
      };
      const activeTheme = ApiThemeClassName.fromTheme(theme);
      this.a = { styles, activeTheme, themeLabel: theme.label, themeId: theme.settingsId };
    }
    return this.a;
  }
  g() {
    this.a = void 0;
    this.b.fire();
  }
};
$Qoc = __decorate([
  __param(0, $rwb),
  __param(1, $kl)
], $Qoc);
var ApiThemeClassName;
(function(ApiThemeClassName2) {
  ApiThemeClassName2["light"] = "vscode-light";
  ApiThemeClassName2["dark"] = "vscode-dark";
  ApiThemeClassName2["highContrast"] = "vscode-high-contrast";
  ApiThemeClassName2["highContrastLight"] = "vscode-high-contrast-light";
})(ApiThemeClassName || (ApiThemeClassName = {}));
(function(ApiThemeClassName2) {
  function fromTheme(theme) {
    switch (theme.type) {
      case ColorScheme.LIGHT:
        return ApiThemeClassName2.light;
      case ColorScheme.DARK:
        return ApiThemeClassName2.dark;
      case ColorScheme.HIGH_CONTRAST_DARK:
        return ApiThemeClassName2.highContrast;
      case ColorScheme.HIGH_CONTRAST_LIGHT:
        return ApiThemeClassName2.highContrastLight;
    }
  }
  ApiThemeClassName2.fromTheme = fromTheme;
})(ApiThemeClassName || (ApiThemeClassName = {}));

// out-build/vs/platform/webview/common/webviewPortMapping.js
var $yrb = class {
  constructor(b, c, d) {
    this.b = b;
    this.c = c;
    this.d = d;
    this.a = /* @__PURE__ */ new Map();
  }
  async getRedirect(resolveAuthority, url) {
    const uri = URI.parse(url);
    const requestLocalHostInfo = $wC(uri);
    if (!requestLocalHostInfo) {
      return void 0;
    }
    for (const mapping2 of this.c()) {
      if (mapping2.webviewPort === requestLocalHostInfo.port) {
        const extensionLocation = this.b();
        if (extensionLocation && extensionLocation.scheme === Schemas.vscodeRemote) {
          const tunnel = resolveAuthority && await this.e(resolveAuthority, mapping2.extensionHostPort);
          if (tunnel) {
            if (tunnel.tunnelLocalPort === mapping2.webviewPort) {
              return void 0;
            }
            return encodeURI(uri.with({
              authority: `127.0.0.1:${tunnel.tunnelLocalPort}`
            }).toString(true));
          }
        }
        if (mapping2.webviewPort !== mapping2.extensionHostPort) {
          return encodeURI(uri.with({
            authority: `${requestLocalHostInfo.address}:${mapping2.extensionHostPort}`
          }).toString(true));
        }
      }
    }
    return void 0;
  }
  async dispose() {
    for (const tunnel of this.a.values()) {
      await tunnel.dispose();
    }
    this.a.clear();
  }
  async e(remoteAuthority, remotePort) {
    const existing = this.a.get(remotePort);
    if (existing) {
      return existing;
    }
    const tunnelOrError = await this.d.openTunnel({ getAddress: async () => remoteAuthority }, void 0, remotePort);
    let tunnel;
    if (typeof tunnelOrError === "string") {
      tunnel = void 0;
    }
    if (tunnel) {
      this.a.set(remotePort, tunnel);
    }
    return tunnel;
  }
};

// out-build/vs/platform/webview/common/mimeTypes.js
var webviewMimeTypes = /* @__PURE__ */ new Map([
  [".svg", "image/svg+xml"],
  [".txt", $YC.text],
  [".css", "text/css"],
  [".js", "application/javascript"],
  [".cjs", "application/javascript"],
  [".mjs", "application/javascript"],
  [".json", "application/json"],
  [".html", "text/html"],
  [".htm", "text/html"],
  [".xhtml", "application/xhtml+xml"],
  [".oft", "font/otf"],
  [".xml", "application/xml"],
  [".wasm", "application/wasm"]
]);
function $Roc(resource) {
  const ext = $sc(resource.fsPath).toLowerCase();
  return webviewMimeTypes.get(ext) || $1C(resource.fsPath) || $YC.unknown;
}

// out-build/vs/workbench/contrib/webview/browser/resourceLoading.js
var WebviewResourceResponse;
(function(WebviewResourceResponse2) {
  let Type4;
  (function(Type5) {
    Type5[Type5["Success"] = 0] = "Success";
    Type5[Type5["Failed"] = 1] = "Failed";
    Type5[Type5["AccessDenied"] = 2] = "AccessDenied";
    Type5[Type5["NotModified"] = 3] = "NotModified";
  })(Type4 = WebviewResourceResponse2.Type || (WebviewResourceResponse2.Type = {}));
  class StreamSuccess {
    constructor(stream, etag, mtime, mimeType) {
      this.stream = stream;
      this.etag = etag;
      this.mtime = mtime;
      this.mimeType = mimeType;
      this.type = Type4.Success;
    }
  }
  WebviewResourceResponse2.StreamSuccess = StreamSuccess;
  WebviewResourceResponse2.Failed = { type: Type4.Failed };
  WebviewResourceResponse2.AccessDenied = { type: Type4.AccessDenied };
  class NotModified {
    constructor(mimeType, mtime) {
      this.mimeType = mimeType;
      this.mtime = mtime;
      this.type = Type4.NotModified;
    }
  }
  WebviewResourceResponse2.NotModified = NotModified;
})(WebviewResourceResponse || (WebviewResourceResponse = {}));
async function $Soc(requestUri, options3, fileService, logService, token) {
  logService.debug(`loadLocalResource - begin. requestUri=${requestUri}`);
  const resourceToLoad = getResourceToLoad(requestUri, options3.roots);
  logService.debug(`loadLocalResource - found resource to load. requestUri=${requestUri}, resourceToLoad=${resourceToLoad}`);
  if (!resourceToLoad) {
    return WebviewResourceResponse.AccessDenied;
  }
  const mime = $Roc(requestUri);
  try {
    const result = await fileService.readFileStream(resourceToLoad, { etag: options3.ifNoneMatch }, token);
    return new WebviewResourceResponse.StreamSuccess(result.value, result.etag, result.mtime, mime);
  } catch (err) {
    if (err instanceof $Fm) {
      const result = err.fileOperationResult;
      if (result === 2) {
        return new WebviewResourceResponse.NotModified(mime, err.options?.mtime);
      }
    }
    logService.debug(`loadLocalResource - Error using fileReader. requestUri=${requestUri}`);
    console.log(err);
    return WebviewResourceResponse.Failed;
  }
}
function getResourceToLoad(requestUri, roots) {
  for (const root of roots) {
    if (containsResource(root, requestUri)) {
      return normalizeResourcePath(requestUri);
    }
  }
  return void 0;
}
function containsResource(root, resource) {
  if (root.scheme !== resource.scheme) {
    return false;
  }
  let resourceFsPath = $lc(resource.fsPath);
  let rootPath = $lc(root.fsPath + (root.fsPath.endsWith(sep) ? "" : sep));
  if ($Wg(root.fsPath) && $Wg(resource.fsPath)) {
    rootPath = rootPath.toLowerCase();
    resourceFsPath = resourceFsPath.toLowerCase();
  }
  return resourceFsPath.startsWith(rootPath);
}
function normalizeResourcePath(resource) {
  if (resource.scheme === Schemas.vscodeRemote) {
    return URI.from({
      scheme: Schemas.vscodeRemote,
      authority: resource.authority,
      path: "/vscode-resource",
      query: JSON.stringify({
        requestResourcePath: resource.path
      })
    });
  }
  return resource;
}

// out-build/vs/workbench/contrib/webview/browser/webviewFindWidget.js
var $Toc = class $Toc2 extends $Sfc {
  async S(dataChanged) {
    return void 0;
  }
  constructor(gb, contextViewService, contextKeyService, hoverService, keybindingService) {
    super({
      showCommonFindToggles: false,
      checkImeCompletionState: gb.checkImeCompletionState,
      enableSash: true
    }, contextViewService, contextKeyService, hoverService, keybindingService);
    this.gb = gb;
    this.fb = $Arb.bindTo(contextKeyService);
    this.B(gb.hasFindResult((hasResult) => {
      this.bb(hasResult);
      this.cb();
    }));
    this.B(gb.onDidStopFind(() => {
      this.bb(false);
    }));
  }
  find(previous) {
    const val = this.U;
    if (val) {
      this.gb.find(val, previous);
    }
  }
  hide(animated = true) {
    super.hide(animated);
    this.gb.stopFind(true);
    this.gb.focus();
  }
  N() {
    const val = this.U;
    if (val) {
      this.gb.updateFind(val);
    } else {
      this.gb.stopFind(false);
    }
    return false;
  }
  O() {
    this.fb.set(true);
  }
  P() {
    this.fb.reset();
  }
  Q() {
  }
  R() {
  }
  findFirst() {
  }
};
$Toc = __decorate([
  __param(1, $40),
  __param(2, $on),
  __param(3, $5$),
  __param(4, $Ty)
], $Toc);

// out-build/vs/workbench/contrib/webview/browser/webviewElement.js
var WebviewState;
(function(WebviewState2) {
  let Type4;
  (function(Type5) {
    Type5[Type5["Initializing"] = 0] = "Initializing";
    Type5[Type5["Ready"] = 1] = "Ready";
  })(Type4 = WebviewState2.Type || (WebviewState2.Type = {}));
  class Initializing {
    constructor(pendingMessages) {
      this.pendingMessages = pendingMessages;
      this.type = 0;
    }
  }
  WebviewState2.Initializing = Initializing;
  WebviewState2.Ready = {
    type: 1
    /* Type.Ready */
  };
})(WebviewState || (WebviewState = {}));
var webviewIdContext = "webviewId";
var $Uoc = class $Uoc2 extends $3c {
  get c() {
    return typeof this.b === "number" ? getWindowById(this.b)?.window : void 0;
  }
  get h() {
    return "browser";
  }
  get n() {
    return this.m;
  }
  get isFocused() {
    if (!this.r) {
      return false;
    }
    if (!this.c) {
      return false;
    }
    if (this.c.document.activeElement && this.c.document.activeElement !== this.n) {
      return false;
    }
    return true;
  }
  constructor(initInfo, N, configurationService, contextMenuService, notificationService, O, P, Q, R, S, U, instantiationService, W) {
    super();
    this.N = N;
    this.O = O;
    this.P = P;
    this.Q = Q;
    this.R = R;
    this.S = S;
    this.U = U;
    this.W = W;
    this.a = $ps();
    this.b = void 0;
    this.j = 4;
    this.s = new WebviewState.Initializing([]);
    this.w = this.B(new $ad());
    this.D = this.B(new $Th(50));
    this.F = this.B(new $ze());
    this.G = this.F.event;
    this.I = /* @__PURE__ */ new Map();
    this.checkImeCompletionState = true;
    this.L = false;
    this.X = this.B(new $ze());
    this.onMissingCsp = this.X.event;
    this.Y = this.B(new $ze());
    this.onDidClickLink = this.Y.event;
    this.Z = this.B(new $ze());
    this.onDidReload = this.Z.event;
    this.$ = this.B(new $ze());
    this.onMessage = this.$.event;
    this.ab = this.B(new $ze());
    this.onDidScroll = this.ab.event;
    this.bb = this.B(new $ze());
    this.onDidWheel = this.bb.event;
    this.cb = this.B(new $ze());
    this.onDidUpdateState = this.cb.event;
    this.db = this.B(new $ze());
    this.onDidFocus = this.db.event;
    this.eb = this.B(new $ze());
    this.onDidBlur = this.eb.event;
    this.fb = this.B(new $ze());
    this.onFatalError = this.fb.event;
    this.gb = this.B(new $ze());
    this.onDidDispose = this.gb.event;
    this.rb = false;
    this.Db = this.B(new $ze());
    this.hasFindResult = this.Db.event;
    this.Eb = this.B(new $ze());
    this.onDidStopFind = this.Eb.event;
    this.providedViewType = initInfo.providedViewType;
    this.origin = initInfo.origin ?? this.a;
    this.M = initInfo.options;
    this.extension = initInfo.extension;
    this.t = {
      html: "",
      title: initInfo.title,
      options: initInfo.contentOptions,
      state: void 0
    };
    this.u = this.B(new $yrb(() => this.extension?.location, () => this.t.options.portMapping || [], this.U));
    this.m = this.ib(initInfo.options, initInfo.contentOptions);
    this.B(this.qb("no-csp-found", () => {
      this.sb();
    }));
    this.B(this.qb("did-click-link", ({ uri }) => {
      this.Y.fire(uri);
    }));
    this.B(this.qb("onmessage", ({ message, transfer }) => {
      this.$.fire({ message, transfer });
    }));
    this.B(this.qb("did-scroll", ({ scrollYPercentage }) => {
      this.ab.fire({ scrollYPercentage });
    }));
    this.B(this.qb("do-reload", () => {
      this.reload();
    }));
    this.B(this.qb("do-update-state", (state) => {
      this.state = state;
      this.cb.fire(state);
    }));
    this.B(this.qb("did-focus", () => {
      this.vb(true);
    }));
    this.B(this.qb("did-blur", () => {
      this.vb(false);
    }));
    this.B(this.qb("did-scroll-wheel", (event) => {
      this.bb.fire(event);
    }));
    this.B(this.qb("did-find", ({ didFind }) => {
      this.Db.fire(didFind);
    }));
    this.B(this.qb("fatal-error", (e) => {
      notificationService.error(localize(11797, null, e.message));
      this.fb.fire({ message: e.message });
    }));
    this.B(this.qb("did-keydown", (data) => {
      this.wb("keydown", data);
    }));
    this.B(this.qb("did-keyup", (data) => {
      this.wb("keyup", data);
    }));
    this.B(this.qb("did-context-menu", (data) => {
      if (!this.n) {
        return;
      }
      if (!this.z) {
        return;
      }
      const elementBox = this.n.getBoundingClientRect();
      const contextKeyService = this.z.createOverlay([
        ...Object.entries(data.context),
        [webviewIdContext, this.providedViewType]
      ]);
      contextMenuService.showContextMenu({
        menuId: $bJ.WebviewContext,
        menuActionOptions: { shouldForwardArgs: true },
        contextKeyService,
        getActionsContext: () => ({ ...data.context, webview: this.providedViewType }),
        getAnchor: () => ({
          x: elementBox.x + data.clientX,
          y: elementBox.y + data.clientY
        })
      });
      this.hb("set-context-menu-visible", { visible: true });
    }));
    this.B(this.qb("load-resource", async (entry) => {
      try {
        const authority = $IJb(entry.authority);
        const uri = URI.from({
          scheme: entry.scheme,
          authority,
          path: decodeURIComponent(entry.path),
          // This gets re-encoded
          query: entry.query ? decodeURIComponent(entry.query) : entry.query
        });
        this.zb(entry.id, uri, entry.ifNoneMatch);
      } catch (e) {
        this.hb("did-load-resource", {
          id: entry.id,
          status: 404,
          path: entry.path
        });
      }
    }));
    this.B(this.qb("load-localhost", (entry) => {
      this.Bb(entry.id, entry.origin);
    }));
    this.B(Event2.runAndSubscribe(N.onThemeDataChanged, () => this.ub()));
    this.B(W.onDidChangeReducedMotion(() => this.ub()));
    this.B(W.onDidChangeScreenReaderOptimized(() => this.ub()));
    this.B(contextMenuService.onDidHideContextMenu(() => this.hb("set-context-menu-visible", { visible: false })));
    this.C = configurationService.getValue("window.confirmBeforeClose");
    this.B(configurationService.onDidChangeConfiguration((e) => {
      if (e.affectsConfiguration("window.confirmBeforeClose")) {
        this.C = configurationService.getValue("window.confirmBeforeClose");
        this.hb("set-confirm-before-close", this.C);
      }
    }));
    this.B(this.qb("drag-start", () => {
      this.lb();
    }));
    this.B(this.qb("drag", (event) => {
      this.xb("drag", event);
    }));
    if (initInfo.options.enableFindWidget) {
      this.J = this.B(instantiationService.createInstance($Toc, this));
    }
  }
  dispose() {
    this.L = true;
    this.n?.remove();
    this.m = void 0;
    this.H = void 0;
    if (this.s.type === 0) {
      for (const message of this.s.pendingMessages) {
        message.resolve(false);
      }
      this.s.pendingMessages = [];
    }
    this.gb.fire();
    this.w.dispose(true);
    super.dispose();
  }
  setContextKeyService(contextKeyService) {
    this.z = contextKeyService;
  }
  postMessage(message, transfer) {
    return this.hb("message", { message, transfer });
  }
  async hb(channel, data, _createElement = []) {
    if (this.s.type === 0) {
      const { promise, resolve } = $Oh();
      this.s.pendingMessages.push({ channel, data, transferable: _createElement, resolve });
      return promise;
    } else {
      return this.pb(channel, data, _createElement);
    }
  }
  ib(options3, _contentOptions) {
    const element = document.createElement("iframe");
    element.name = this.a;
    element.className = `webview ${options3.customClasses || ""}`;
    element.sandbox.add("allow-scripts", "allow-same-origin", "allow-forms", "allow-pointer-lock", "allow-downloads");
    const allowRules = ["cross-origin-isolated", "autoplay"];
    if (!$Ue) {
      allowRules.push("clipboard-read", "clipboard-write");
    }
    element.setAttribute("allow", allowRules.join("; "));
    element.style.border = "none";
    element.style.width = "100%";
    element.style.height = "100%";
    element.focus = () => {
      this.Cb();
    };
    return element;
  }
  jb(encodedWebviewOrigin, extension, options3, targetWindow) {
    const params = {
      id: this.a,
      origin: this.origin,
      swVersion: String(this.j),
      extensionId: extension?.id.value ?? "",
      platform: this.h,
      "vscode-resource-base-authority": $FJb,
      parentOrigin: targetWindow.origin
    };
    if (this.M.disableServiceWorker) {
      params.disableServiceWorker = "true";
    }
    if (this.O.remoteAuthority) {
      params.remoteAuthority = this.O.remoteAuthority;
    }
    if (options3.purpose) {
      params.purpose = options3.purpose;
    }
    COI.addSearchParam(params, true, true);
    const queryString = new URLSearchParams(params).toString();
    const fileName = $Ue ? "index-no-csp.html" : "index.html";
    this.n.setAttribute("src", `${this.nb(encodedWebviewOrigin)}/${fileName}?${queryString}`);
  }
  mountTo(element, targetWindow) {
    if (!this.n) {
      return;
    }
    this.b = targetWindow.vscodeWindowId;
    this.f = $kf(targetWindow.origin, this.origin).then((id2) => this.g = id2);
    this.f.then((encodedWebviewOrigin) => {
      if (!this.L) {
        this.jb(encodedWebviewOrigin, this.extension, this.M, targetWindow);
      }
    });
    this.kb(targetWindow);
    if (this.J) {
      element.appendChild(this.J.getDomNode());
    }
    for (const eventName of [$7j.MOUSE_DOWN, $7j.MOUSE_MOVE, $7j.DROP]) {
      this.B($_i(element, eventName, () => {
        this.mb();
      }));
    }
    for (const node of [element, targetWindow]) {
      this.B($_i(node, $7j.DRAG_END, () => {
        this.mb();
      }));
    }
    element.id = this.a;
    element.appendChild(this.n);
  }
  kb(targetWindow) {
    const subscription = this.B($_i(targetWindow, "message", (e) => {
      if (!this.g || e?.data?.target !== this.a) {
        return;
      }
      if (e.origin !== this.ob(this.g)) {
        console.log(`Skipped renderer receiving message due to mismatched origins: ${e.origin} ${this.ob}`);
        return;
      }
      if (e.data.channel === "webview-ready") {
        if (this.H) {
          return;
        }
        this.Q.debug(`Webview(${this.a}): webview ready`);
        this.H = e.ports[0];
        this.H.onmessage = (e2) => {
          const handlers = this.I.get(e2.data.channel);
          if (!handlers) {
            console.log(`No handlers found for '${e2.data.channel}'`);
            return;
          }
          handlers?.forEach((handler) => handler(e2.data.data, e2));
        };
        this.n?.classList.add("ready");
        if (this.s.type === 0) {
          this.s.pendingMessages.forEach(({ channel, data, resolve }) => resolve(this.pb(channel, data)));
        }
        this.s = WebviewState.Ready;
        subscription.dispose();
      }
    }));
  }
  lb() {
    if (this.n) {
      this.n.style.pointerEvents = "none";
    }
  }
  mb() {
    if (this.n) {
      this.n.style.pointerEvents = "auto";
    }
  }
  nb(encodedWebviewOrigin) {
    const webviewExternalEndpoint = this.O.webviewExternalEndpoint;
    if (!webviewExternalEndpoint) {
      throw new Error(`'webviewExternalEndpoint' has not been configured. Webviews will not work!`);
    }
    const endpoint = webviewExternalEndpoint.replace("{{uuid}}", encodedWebviewOrigin);
    if (endpoint[endpoint.length - 1] === "/") {
      return endpoint.slice(0, endpoint.length - 1);
    }
    return endpoint;
  }
  ob(encodedWebviewOrigin) {
    const uri = URI.parse(this.nb(encodedWebviewOrigin));
    return uri.scheme + "://" + uri.authority.toLowerCase();
  }
  pb(channel, data, transferable = []) {
    if (this.n && this.H) {
      this.H.postMessage({ channel, args: data }, transferable);
      return true;
    }
    return false;
  }
  qb(channel, handler) {
    let handlers = this.I.get(channel);
    if (!handlers) {
      handlers = /* @__PURE__ */ new Set();
      this.I.set(channel, handlers);
    }
    handlers.add(handler);
    return $1c(() => {
      this.I.get(channel)?.delete(handler);
    });
  }
  sb() {
    if (this.rb) {
      return;
    }
    this.rb = true;
    if (this.extension?.id) {
      if (this.O.isExtensionDevelopment) {
        this.X.fire(this.extension.id);
      }
      const payload = {
        extension: this.extension.id.value
      };
      this.S.publicLog2("webviewMissingCsp", payload);
    }
  }
  reload() {
    this.tb(this.t);
    const subscription = this.B(this.qb("did-load", () => {
      this.Z.fire();
      subscription.dispose();
    }));
  }
  setHtml(html3) {
    this.tb({ ...this.t, html: html3 });
    this.F.fire(html3);
  }
  setTitle(title) {
    this.t = { ...this.t, title };
    this.hb("set-title", title);
  }
  set contentOptions(options3) {
    this.Q.debug(`Webview(${this.a}): will update content options`);
    if ($Drb(options3, this.t.options)) {
      this.Q.debug(`Webview(${this.a}): skipping content options update`);
      return;
    }
    this.tb({ ...this.t, options: options3 });
  }
  set localResourcesRoot(resources) {
    this.t = {
      ...this.t,
      options: { ...this.t.options, localResourceRoots: resources }
    };
  }
  set state(state) {
    this.t = { ...this.t, state };
  }
  set initialScrollProgress(value) {
    this.hb("initial-scroll-position", value);
  }
  tb(newContent) {
    this.Q.debug(`Webview(${this.a}): will update content`);
    this.t = newContent;
    const allowScripts = !!this.t.options.allowScripts;
    this.hb("content", {
      contents: this.t.html,
      title: this.t.title,
      options: {
        allowMultipleAPIAcquire: !!this.t.options.allowMultipleAPIAcquire,
        allowScripts,
        allowForms: this.t.options.allowForms ?? allowScripts
        // For back compat, we allow forms by default when scripts are enabled
      },
      state: this.t.state,
      cspSource: $GJb,
      confirmBeforeClose: this.C
    });
  }
  ub() {
    let { styles, activeTheme, themeLabel, themeId } = this.N.getWebviewThemeData();
    if (this.M.transformCssVariables) {
      styles = this.M.transformCssVariables(styles);
    }
    const reduceMotion = this.W.isMotionReduced();
    const screenReader = this.W.isScreenReaderOptimized();
    this.hb("styles", { styles, activeTheme, themeId, themeLabel, reduceMotion, screenReader });
  }
  vb(isFocused) {
    this.r = isFocused;
    if (isFocused) {
      this.db.fire();
    } else {
      this.eb.fire();
    }
  }
  wb(type, event) {
    const emulatedKeyboardEvent = new KeyboardEvent(type, event);
    Object.defineProperty(emulatedKeyboardEvent, "target", {
      get: () => this.n
    });
    this.c?.dispatchEvent(emulatedKeyboardEvent);
  }
  xb(type, event) {
    const emulatedDragEvent = new DragEvent(type, event);
    Object.defineProperty(emulatedDragEvent, "target", {
      get: () => this.n
    });
    this.c?.dispatchEvent(emulatedDragEvent);
  }
  windowDidDragStart() {
    this.lb();
  }
  windowDidDragEnd() {
    this.mb();
  }
  selectAll() {
    this.yb("selectAll");
  }
  copy() {
    this.yb("copy");
  }
  paste() {
    this.yb("paste");
  }
  cut() {
    this.yb("cut");
  }
  undo() {
    this.yb("undo");
  }
  redo() {
    this.yb("redo");
  }
  yb(command4) {
    if (this.n) {
      this.hb("execCommand", command4);
    }
  }
  async zb(id2, uri, ifNoneMatch) {
    try {
      const result = await $Soc(uri, {
        ifNoneMatch,
        roots: this.t.options.localResourceRoots || []
      }, this.P, this.Q, this.w.token);
      switch (result.type) {
        case WebviewResourceResponse.Type.Success: {
          const buffer = await this.Ab(result.stream);
          return this.hb("did-load-resource", {
            id: id2,
            status: 200,
            path: uri.path,
            mime: result.mimeType,
            data: buffer,
            etag: result.etag,
            mtime: result.mtime
          }, [buffer]);
        }
        case WebviewResourceResponse.Type.NotModified: {
          return this.hb("did-load-resource", {
            id: id2,
            status: 304,
            // not modified
            path: uri.path,
            mime: result.mimeType,
            mtime: result.mtime
          });
        }
        case WebviewResourceResponse.Type.AccessDenied: {
          return this.hb("did-load-resource", {
            id: id2,
            status: 401,
            // unauthorized
            path: uri.path
          });
        }
      }
    } catch {
    }
    return this.hb("did-load-resource", {
      id: id2,
      status: 404,
      path: uri.path
    });
  }
  async Ab(stream) {
    const vsBuffer = await $Oi(stream);
    return vsBuffer.buffer.buffer;
  }
  async Bb(id2, origin) {
    const authority = this.O.remoteAuthority;
    const resolveAuthority = authority ? await this.R.resolveAuthority(authority) : void 0;
    const redirect = resolveAuthority ? await this.u.getRedirect(resolveAuthority.authority, origin) : void 0;
    return this.hb("did-load-localhost", {
      id: id2,
      origin,
      location: redirect
    });
  }
  focus() {
    this.Cb();
    this.vb(true);
  }
  Cb() {
    if (!this.n) {
      return;
    }
    try {
      this.n.contentWindow?.focus();
    } catch {
    }
    this.D.trigger(async () => {
      if (!this.isFocused || !this.n) {
        return;
      }
      if (this.c?.document.activeElement && this.c.document.activeElement !== this.n && this.c.document.activeElement?.tagName !== "BODY") {
        return;
      }
      this.c?.document.body?.focus();
      this.hb("focus", void 0);
    });
  }
  /**
   * Webviews expose a stateful find API.
   * Successive calls to find will move forward or backward through onFindResults
   * depending on the supplied options.
   *
   * @param value The string to search for. Empty strings are ignored.
   */
  find(value, previous) {
    if (!this.n) {
      return;
    }
    this.hb("find", { value, previous });
  }
  updateFind(value) {
    if (!value || !this.n) {
      return;
    }
    this.hb("find", { value });
  }
  stopFind(keepSelection) {
    if (!this.n) {
      return;
    }
    this.hb("find-stop", { clearSelection: !keepSelection });
    this.Eb.fire();
  }
  showFind(animated = true) {
    this.J?.reveal(void 0, animated);
  }
  hideFind(animated = true) {
    this.J?.hide(animated);
  }
  runFindAction(previous) {
    this.J?.find(previous);
  }
};
$Uoc = __decorate([
  __param(2, $kl),
  __param(3, $50),
  __param(4, $PJ),
  __param(5, $US),
  __param(6, $km),
  __param(7, $wn),
  __param(8, $bC),
  __param(9, $zv),
  __param(10, $tC),
  __param(11, $Pk),
  __param(12, $ND)
], $Uoc);

// out-build/vs/workbench/contrib/webview/browser/overlayWebview.js
var $Voc = class $Voc2 extends $3c {
  get z() {
    return getWindowById(this.y, true).window;
  }
  constructor(initInfo, I, J, L) {
    super();
    this.I = I;
    this.J = J;
    this.L = L;
    this.a = true;
    this.b = /* @__PURE__ */ new Set();
    this.c = this.B(new $4c());
    this.g = this.B(new $2c());
    this.h = "";
    this.m = 0;
    this.n = void 0;
    this.w = void 0;
    this.y = void 0;
    this.C = this.B(new $4c());
    this.G = false;
    this.M = false;
    this.N = this.B(new $ze());
    this.onDidDispose = this.N.event;
    this.Q = this.B(new $ze());
    this.onDidFocus = this.Q.event;
    this.R = this.B(new $ze());
    this.onDidBlur = this.R.event;
    this.S = this.B(new $ze());
    this.onDidClickLink = this.S.event;
    this.U = this.B(new $ze());
    this.onDidReload = this.U.event;
    this.W = this.B(new $ze());
    this.onDidScroll = this.W.event;
    this.X = this.B(new $ze());
    this.onDidUpdateState = this.X.event;
    this.Y = this.B(new $ze());
    this.onMessage = this.Y.event;
    this.Z = this.B(new $ze());
    this.onMissingCsp = this.Z.event;
    this.$ = this.B(new $ze());
    this.onDidWheel = this.$.event;
    this.ab = this.B(new $ze());
    this.onFatalError = this.ab.event;
    this.providedViewType = initInfo.providedViewType;
    this.origin = initInfo.origin ?? $ps();
    this.j = initInfo.title;
    this.s = initInfo.extension;
    this.u = initInfo.options;
    this.t = initInfo.contentOptions;
  }
  get isFocused() {
    return !!this.c.value?.isFocused;
  }
  dispose() {
    this.M = true;
    this.H?.domNode.remove();
    this.H = void 0;
    for (const msg of this.b) {
      msg.resolve(false);
    }
    this.b.clear();
    this.N.fire();
    super.dispose();
  }
  get container() {
    if (this.M) {
      throw new Error(`OverlayWebview has been disposed`);
    }
    if (!this.H) {
      const node = document.createElement("div");
      node.style.position = "absolute";
      node.style.overflow = "hidden";
      this.H = new $nZ(node);
      this.H.setVisibility("hidden");
      this.I.getContainer(this.z).appendChild(node);
    }
    return this.H.domNode;
  }
  claim(owner, targetWindow, scopedContextKeyService) {
    if (this.M) {
      return;
    }
    const oldOwner = this.w;
    if (this.y !== targetWindow.vscodeWindowId) {
      this.release(oldOwner);
      this.c.clear();
      this.g.clear();
      this.H?.domNode.remove();
      this.H = void 0;
    }
    this.w = owner;
    this.y = targetWindow.vscodeWindowId;
    this.P(targetWindow);
    if (oldOwner !== owner) {
      const contextKeyService = scopedContextKeyService || this.L;
      this.C.clear();
      this.C.value = contextKeyService.createScoped(this.container);
      const wasFindVisible = this.D?.get();
      this.D?.reset();
      this.D = $zrb.bindTo(contextKeyService);
      this.D.set(!!wasFindVisible);
      this.F?.reset();
      this.F = $Brb.bindTo(contextKeyService);
      this.F.set(!!this.options.enableFindWidget);
      this.c.value?.setContextKeyService(this.C.value);
    }
  }
  release(owner) {
    if (this.w !== owner) {
      return;
    }
    this.C.clear();
    this.w = void 0;
    if (this.H) {
      this.H.setVisibility("hidden");
    }
    if (this.u.retainContextWhenHidden) {
      this.G = !!this.D?.get();
      this.hideFind(false);
    } else {
      this.c.clear();
      this.g.clear();
    }
  }
  layoutWebviewOverElement(element, dimension, clippingContainer) {
    if (!this.H || !this.H.domNode.parentElement) {
      return;
    }
    const whenContainerStylesLoaded = this.I.whenContainerStylesLoaded(this.z);
    if (whenContainerStylesLoaded) {
      whenContainerStylesLoaded.then(() => this.O(element, dimension, clippingContainer));
    } else {
      this.O(element, dimension, clippingContainer);
    }
  }
  O(element, dimension, clippingContainer) {
    if (!this.H || !this.H.domNode.parentElement) {
      return;
    }
    const frameRect = element.getBoundingClientRect();
    const containerRect = this.H.domNode.parentElement.getBoundingClientRect();
    const parentBorderTop = (containerRect.height - this.H.domNode.parentElement.clientHeight) / 2;
    const parentBorderLeft = (containerRect.width - this.H.domNode.parentElement.clientWidth) / 2;
    this.H.setTop(frameRect.top - containerRect.top - parentBorderTop);
    this.H.setLeft(frameRect.left - containerRect.left - parentBorderLeft);
    this.H.setWidth(dimension ? dimension.width : frameRect.width);
    this.H.setHeight(dimension ? dimension.height : frameRect.height);
    if (clippingContainer) {
      const { top: top2, left, right, bottom } = computeClippingRect(frameRect, clippingContainer);
      this.H.domNode.style.clipPath = `polygon(${left}px ${top2}px, ${right}px ${top2}px, ${right}px ${bottom}px, ${left}px ${bottom}px)`;
    }
  }
  P(targetWindow) {
    if (this.M) {
      throw new Error("OverlayWebview is disposed");
    }
    if (!this.c.value) {
      const webview = this.J.createWebviewElement({
        providedViewType: this.providedViewType,
        origin: this.origin,
        title: this.j,
        options: this.u,
        contentOptions: this.t,
        extension: this.extension
      });
      this.c.value = webview;
      webview.state = this.n;
      if (this.C.value) {
        this.c.value.setContextKeyService(this.C.value);
      }
      if (this.h) {
        webview.setHtml(this.h);
      }
      if (this.u.tryRestoreScrollPosition) {
        webview.initialScrollProgress = this.m;
      }
      this.F?.set(!!this.options.enableFindWidget);
      webview.mountTo(this.container, targetWindow);
      this.g.clear();
      this.g.add(webview.onDidFocus(() => {
        this.Q.fire();
      }));
      this.g.add(webview.onDidBlur(() => {
        this.R.fire();
      }));
      this.g.add(webview.onDidClickLink((x) => {
        this.S.fire(x);
      }));
      this.g.add(webview.onMessage((x) => {
        this.Y.fire(x);
      }));
      this.g.add(webview.onMissingCsp((x) => {
        this.Z.fire(x);
      }));
      this.g.add(webview.onDidWheel((x) => {
        this.$.fire(x);
      }));
      this.g.add(webview.onDidReload(() => {
        this.U.fire();
      }));
      this.g.add(webview.onFatalError((x) => {
        this.ab.fire(x);
      }));
      this.g.add(webview.onDidScroll((x) => {
        this.m = x.scrollYPercentage;
        this.W.fire(x);
      }));
      this.g.add(webview.onDidUpdateState((state) => {
        this.n = state;
        this.X.fire(state);
      }));
      if (this.a) {
        this.b.forEach(async (msg) => {
          msg.resolve(await webview.postMessage(msg.message, msg.transfer));
        });
      }
      this.a = false;
      this.b.clear();
    }
    if (this.options.retainContextWhenHidden && this.G) {
      this.showFind(false);
      this.G = false;
    }
    this.H?.setVisibility("visible");
  }
  setHtml(html3) {
    this.h = html3;
    this.bb((webview) => webview.setHtml(html3));
  }
  setTitle(title) {
    this.j = title;
    this.bb((webview) => webview.setTitle(title));
  }
  get initialScrollProgress() {
    return this.m;
  }
  set initialScrollProgress(value) {
    this.m = value;
    this.bb((webview) => webview.initialScrollProgress = value);
  }
  get state() {
    return this.n;
  }
  set state(value) {
    this.n = value;
    this.bb((webview) => webview.state = value);
  }
  get extension() {
    return this.s;
  }
  set extension(value) {
    this.s = value;
    this.bb((webview) => webview.extension = value);
  }
  get options() {
    return this.u;
  }
  set options(value) {
    this.u = { customClasses: this.u.customClasses, ...value };
  }
  get contentOptions() {
    return this.t;
  }
  set contentOptions(value) {
    this.t = value;
    this.bb((webview) => webview.contentOptions = value);
  }
  set localResourcesRoot(resources) {
    this.bb((webview) => webview.localResourcesRoot = resources);
  }
  async postMessage(message, transfer) {
    if (this.c.value) {
      return this.c.value.postMessage(message, transfer);
    }
    if (this.a) {
      let resolve;
      const p = new Promise((r2) => resolve = r2);
      this.b.add({ message, transfer, resolve });
      return p;
    }
    return false;
  }
  focus() {
    this.c.value?.focus();
  }
  reload() {
    this.c.value?.reload();
  }
  selectAll() {
    this.c.value?.selectAll();
  }
  copy() {
    this.c.value?.copy();
  }
  paste() {
    this.c.value?.paste();
  }
  cut() {
    this.c.value?.cut();
  }
  undo() {
    this.c.value?.undo();
  }
  redo() {
    this.c.value?.redo();
  }
  showFind(animated = true) {
    if (this.c.value) {
      this.c.value.showFind(animated);
      this.D?.set(true);
    }
  }
  hideFind(animated = true) {
    this.D?.reset();
    this.c.value?.hideFind(animated);
  }
  runFindAction(previous) {
    this.c.value?.runFindAction(previous);
  }
  bb(f) {
    if (this.c.value) {
      f(this.c.value);
    }
  }
  windowDidDragStart() {
    this.c.value?.windowDidDragStart();
  }
  windowDidDragEnd() {
    this.c.value?.windowDidDragEnd();
  }
  setContextKeyService(contextKeyService) {
    this.c.value?.setContextKeyService(contextKeyService);
  }
};
$Voc = __decorate([
  __param(1, $Vlb),
  __param(2, $Crb),
  __param(3, $on)
], $Voc);
function computeClippingRect(frameRect, clipper) {
  const rootRect = clipper.getBoundingClientRect();
  const top2 = Math.max(rootRect.top - frameRect.top, 0);
  const right = Math.max(frameRect.width - (frameRect.right - rootRect.right), 0);
  const bottom = Math.max(frameRect.height - (frameRect.bottom - rootRect.bottom), 0);
  const left = Math.max(rootRect.left - frameRect.left, 0);
  return { top: top2, right, bottom, left };
}

// out-build/vs/workbench/contrib/webview/browser/webviewService.js
var $Woc = class $Woc2 extends $3c {
  constructor(b) {
    super();
    this.b = b;
    this.g = /* @__PURE__ */ new Set();
    this.h = this.B(new $ze());
    this.onDidChangeActiveWebview = this.h.event;
    this.a = this.b.createInstance($Qoc);
  }
  get activeWebview() {
    return this.c;
  }
  f(value) {
    if (value !== this.c) {
      this.c = value;
      this.h.fire(value);
    }
  }
  get webviews() {
    return this.g.values();
  }
  createWebviewElement(initInfo) {
    const webview = this.b.createInstance($Uoc, initInfo, this.a);
    this.j(webview);
    return webview;
  }
  createWebviewOverlay(initInfo) {
    const webview = this.b.createInstance($Voc, initInfo);
    this.j(webview);
    return webview;
  }
  j(webview) {
    this.g.add(webview);
    const store = new $2c();
    store.add(webview.onDidFocus(() => {
      this.f(webview);
    }));
    const onBlur = () => {
      if (this.c === webview) {
        this.f(void 0);
      }
    };
    store.add(webview.onDidBlur(onBlur));
    store.add(webview.onDidDispose(() => {
      onBlur();
      store.dispose();
      this.g.delete(webview);
    }));
  }
};
$Woc = __decorate([
  __param(0, $Pk)
], $Woc);

// out-build/vs/workbench/contrib/webview/browser/webview.web.contribution.js
$SC(
  $Crb,
  $Woc,
  1
  /* InstantiationType.Delayed */
);

// out-build/vs/workbench/contrib/extensions/common/reportExtensionIssueAction.js
var $Xoc_1;
var $Xoc = class $Xoc2 extends $Um {
  static {
    $Xoc_1 = this;
  }
  static {
    this.m = "workbench.extensions.action.reportExtensionIssue";
  }
  static {
    this.n = localize(6983, null);
  }
  // TODO: Consider passing in IExtensionStatus or IExtensionHostProfile for additional data
  constructor(c, f) {
    super($Xoc_1.m, $Xoc_1.n, "extension-action report-issue");
    this.c = c;
    this.f = f;
    this.enabled = c.isBuiltin || !!c.repository && !!c.repository.url;
  }
  async run() {
    await this.f.openReporter({
      extensionId: this.c.identifier.value
    });
  }
};
$Xoc = $Xoc_1 = __decorate([
  __param(1, $6zb)
], $Xoc);

// out-build/vs/workbench/contrib/extensions/browser/browserRuntimeExtensionsEditor.js
var $Yoc = class extends $nec {
  nb() {
    return null;
  }
  ob(extensionId) {
    return void 0;
  }
  pb(element) {
    return null;
  }
  qb(element) {
    if (element.marketplaceInfo) {
      return this.db.createInstance($Xoc, element.description);
    }
    return null;
  }
};

// out-build/vs/workbench/contrib/extensions/browser/extensions.web.contribution.js
$Wn.as($ZK.EditorPane).registerEditorPane($7tb.create($Yoc, $Yoc.ID, localize(6602, null)), [new $Nk($mec)]);

// out-build/vs/workbench/contrib/terminal/browser/terminalProfileResolverService.js
var generatedProfileName = "Generated";
var $Zoc = class extends $3c {
  get defaultProfileName() {
    return this.c;
  }
  constructor(f, g, h3, j, m, n, r2, s) {
    super();
    this.f = f;
    this.g = g;
    this.h = h3;
    this.j = j;
    this.m = m;
    this.n = n;
    this.r = r2;
    this.s = s;
    this.b = $0r();
    if (this.s.getConnection()) {
      this.s.getEnvironment().then((env3) => this.a = env3?.os || OS);
    } else {
      this.a = OS;
    }
    this.B(this.g.onDidChangeConfiguration((e) => {
      if (e.affectsConfiguration(
        "terminal.integrated.defaultProfile.windows"
        /* TerminalSettingId.DefaultProfileWindows */
      ) || e.affectsConfiguration(
        "terminal.integrated.defaultProfile.osx"
        /* TerminalSettingId.DefaultProfileMacOs */
      ) || e.affectsConfiguration(
        "terminal.integrated.defaultProfile.linux"
        /* TerminalSettingId.DefaultProfileLinux */
      )) {
        this.t();
      }
    }));
    this.B(this.n.onDidChangeAvailableProfiles(() => this.t()));
  }
  async t() {
    if (this.a) {
      this.c = (await this.getDefaultProfile({
        remoteAuthority: this.s.getConnection()?.remoteAuthority,
        os: this.a
      }))?.profileName;
    }
  }
  resolveIcon(shellLaunchConfig, os) {
    if (shellLaunchConfig.icon) {
      shellLaunchConfig.icon = this.u(shellLaunchConfig.icon) || this.getDefaultIcon();
      return;
    }
    if (shellLaunchConfig.customPtyImplementation) {
      shellLaunchConfig.icon = this.getDefaultIcon();
      return;
    }
    if (shellLaunchConfig.executable) {
      return;
    }
    const defaultProfile = this.z(os);
    if (defaultProfile) {
      shellLaunchConfig.icon = defaultProfile.icon;
    }
    if (!shellLaunchConfig.icon) {
      shellLaunchConfig.icon = this.getDefaultIcon();
    }
  }
  getDefaultIcon(resource) {
    return this.b.getIcon(this.g.getValue("terminal.integrated.tabs.defaultIcon", { resource })) || $6l.terminal;
  }
  async resolveShellLaunchConfig(shellLaunchConfig, options3) {
    let resolvedProfile;
    if (shellLaunchConfig.executable) {
      resolvedProfile = await this.F({
        path: shellLaunchConfig.executable,
        args: shellLaunchConfig.args,
        profileName: generatedProfileName,
        isDefault: false
      }, options3);
    } else {
      resolvedProfile = await this.getDefaultProfile(options3);
    }
    shellLaunchConfig.executable = resolvedProfile.path;
    shellLaunchConfig.args = resolvedProfile.args;
    if (resolvedProfile.env) {
      if (shellLaunchConfig.env) {
        shellLaunchConfig.env = { ...shellLaunchConfig.env, ...resolvedProfile.env };
      } else {
        shellLaunchConfig.env = resolvedProfile.env;
      }
    }
    const resource = shellLaunchConfig === void 0 || typeof shellLaunchConfig.cwd === "string" ? void 0 : shellLaunchConfig.cwd;
    shellLaunchConfig.icon = this.u(shellLaunchConfig.icon) || this.u(resolvedProfile.icon) || this.getDefaultIcon(resource);
    if (resolvedProfile.overrideName) {
      shellLaunchConfig.name = resolvedProfile.profileName;
    }
    shellLaunchConfig.color = shellLaunchConfig.color || resolvedProfile.color || this.g.getValue("terminal.integrated.tabs.defaultColor", { resource });
    if (shellLaunchConfig.useShellEnvironment === void 0) {
      shellLaunchConfig.useShellEnvironment = this.g.getValue(
        "terminal.integrated.inheritEnv"
        /* TerminalSettingId.InheritEnv */
      );
    }
  }
  async getDefaultShell(options3) {
    return (await this.getDefaultProfile(options3)).path;
  }
  async getDefaultShellArgs(options3) {
    return (await this.getDefaultProfile(options3)).args || [];
  }
  async getDefaultProfile(options3) {
    return this.F(await this.w(options3), options3);
  }
  getEnvironment(remoteAuthority) {
    return this.f.getEnvironment(remoteAuthority);
  }
  u(icon2) {
    if (!icon2) {
      return void 0;
    }
    if (typeof icon2 === "string") {
      return ThemeIcon.fromId(icon2);
    }
    if (ThemeIcon.isThemeIcon(icon2)) {
      return icon2;
    }
    if (URI.isUri(icon2) || $wB(icon2)) {
      return URI.revive(icon2);
    }
    if (typeof icon2 === "object" && "light" in icon2 && "dark" in icon2) {
      const castedIcon = icon2;
      if ((URI.isUri(castedIcon.light) || $wB(castedIcon.light)) && (URI.isUri(castedIcon.dark) || $wB(castedIcon.dark))) {
        return { light: URI.revive(castedIcon.light), dark: URI.revive(castedIcon.dark) };
      }
    }
    return void 0;
  }
  async w(options3) {
    if (options3.allowAutomationShell) {
      const automationShellProfile = this.D(options3);
      if (automationShellProfile) {
        return automationShellProfile;
      }
    }
    await this.n.profilesReady;
    const defaultProfile = this.z(options3.os);
    if (defaultProfile) {
      return this.y(options3, defaultProfile);
    }
    return this.y(options3, await this.C(options3));
  }
  y(options3, profile) {
    if (options3.allowAutomationShell) {
      const profileClone = $Lv(profile);
      profileClone.icon = $6l.tools;
      return profileClone;
    }
    return profile;
  }
  z(os) {
    return this.n.getDefaultProfile(os);
  }
  async C(options3) {
    const executable = await this.f.getDefaultSystemShell(options3.remoteAuthority, options3.os);
    if (options3.os === OS) {
      let existingProfile = this.n.availableProfiles.find((e) => $uc(e.path).name === $uc(executable).name);
      if (existingProfile) {
        if (options3.allowAutomationShell) {
          existingProfile = $Lv(existingProfile);
          existingProfile.icon = $6l.tools;
        }
        return existingProfile;
      }
    }
    let args2;
    if (options3.os === 2 && $uc(executable).name.match(/(zsh|bash)/)) {
      args2 = ["--login"];
    } else {
      args2 = [];
    }
    const icon2 = this.I(executable);
    return {
      profileName: generatedProfileName,
      path: executable,
      args: args2,
      icon: icon2,
      isDefault: false
    };
  }
  D(options3) {
    const automationProfile = this.g.getValue(`terminal.integrated.automationProfile.${this.H(options3.os)}`);
    if (this.J(automationProfile, options3.os)) {
      automationProfile.icon = this.u(automationProfile.icon) || $6l.tools;
      return automationProfile;
    }
    return void 0;
  }
  async F(profile, options3) {
    const env3 = await this.f.getEnvironment(options3.remoteAuthority);
    if (options3.os === 1) {
      const isWoW64 = !!env3.hasOwnProperty("PROCESSOR_ARCHITEW6432");
      const windir = env3.windir;
      if (!isWoW64 && windir) {
        const sysnativePath = $nc(windir, "Sysnative").replace(/\//g, "\\").toLowerCase();
        if (profile.path && profile.path.toLowerCase().indexOf(sysnativePath) === 0) {
          profile.path = $nc(windir, "System32", profile.path.substr(sysnativePath.length + 1));
        }
      }
      if (profile.path) {
        profile.path = profile.path.replace(/\//g, "\\");
      }
    }
    const activeWorkspaceRootUri = this.j.getLastActiveWorkspaceRoot(options3.remoteAuthority ? Schemas.vscodeRemote : Schemas.file);
    const lastActiveWorkspace = activeWorkspaceRootUri ? this.r.getWorkspaceFolder(activeWorkspaceRootUri) ?? void 0 : void 0;
    profile.path = await this.G(profile.path, env3, lastActiveWorkspace);
    if (profile.args) {
      if (typeof profile.args === "string") {
        profile.args = await this.G(profile.args, env3, lastActiveWorkspace);
      } else {
        profile.args = await Promise.all(profile.args.map((arg) => this.G(arg, env3, lastActiveWorkspace)));
      }
    }
    return profile;
  }
  async G(value, env3, lastActiveWorkspace) {
    try {
      value = await this.h.resolveWithEnvironment(env3, lastActiveWorkspace, value);
    } catch (e) {
      this.m.error(`Could not resolve shell`, e);
    }
    return value;
  }
  H(os) {
    switch (os) {
      case 3:
        return "linux";
      case 2:
        return "osx";
      case 1:
        return "windows";
    }
  }
  I(shell) {
    const file = $uc(shell).name;
    switch (file) {
      case "bash":
        return $6l.terminalBash;
      case "pwsh":
      case "powershell":
        return $6l.terminalPowershell;
      case "tmux":
        return $6l.terminalTmux;
      case "cmd":
        return $6l.terminalCmd;
      default:
        return void 0;
    }
  }
  J(profile, os) {
    if (profile === null || profile === void 0 || typeof profile !== "object") {
      return false;
    }
    if ("path" in profile && typeof profile.path === "string") {
      return true;
    }
    return false;
  }
};
__decorate([
  $$t(200)
], $Zoc.prototype, "t", null);
var $1oc = class $1oc2 extends $Zoc {
  constructor(configurationResolverService, configurationService, historyService, logService, terminalInstanceService, terminalProfileService, workspaceContextService, remoteAgentService) {
    super({
      getDefaultSystemShell: async (remoteAuthority, os) => {
        const backend = await terminalInstanceService.getBackend(remoteAuthority);
        if (!remoteAuthority || !backend) {
          return os === 1 ? "pwsh" : "bash";
        }
        return backend.getDefaultSystemShell(os);
      },
      getEnvironment: async (remoteAuthority) => {
        const backend = await terminalInstanceService.getBackend(remoteAuthority);
        if (!remoteAuthority || !backend) {
          return env;
        }
        return backend.getEnvironment();
      }
    }, configurationService, configurationResolverService, historyService, logService, terminalProfileService, workspaceContextService, remoteAgentService);
  }
};
$1oc = __decorate([
  __param(0, $nY),
  __param(1, $kl),
  __param(2, $tY),
  __param(3, $8x),
  __param(4, $8Pb),
  __param(5, $hY),
  __param(6, $Zk),
  __param(7, $RL)
], $1oc);

// out-build/vs/workbench/contrib/terminal/browser/terminal.web.contribution.js
$SC(
  $fY,
  $1oc,
  1
  /* InstantiationType.Delayed */
);
$0I.registerKeybindingRule({
  id: "workbench.action.terminal.new",
  weight: 200,
  when: TerminalContextKeys.notFocus,
  primary: 2048 | 1024 | 33
  /* KeyCode.KeyC */
});

// out-build/vs/workbench/contrib/tasks/browser/taskService.js
var $2oc = class _$2oc extends $Jhc {
  static {
    this.Pd = localize(10105, null);
  }
  Mc() {
    if (this.I) {
      return this.I;
    }
    if (this.Pb !== ExecutionEngine.Terminal) {
      throw new Error(_$2oc.Pd);
    }
    this.I = this.Lc();
    this.J = [
      this.I.onDidStateChange((event) => {
        this.O.set(this.I.isActiveSync());
        this.Q.fire(event);
      })
    ];
    return this.I;
  }
  cd(workspaceFolder) {
    throw new Error(_$2oc.Pd);
  }
  $b(filter) {
    return this.Pb === ExecutionEngine.Terminal;
  }
};
$SC(
  $3Sb,
  $2oc,
  1
  /* InstantiationType.Delayed */
);

// out-build/vs/workbench/contrib/tags/browser/workspaceTagsService.js
var $3oc = class {
  getTags() {
    return Promise.resolve({});
  }
  async getTelemetryWorkspaceId(workspace2, state) {
    return void 0;
  }
  getHashedRemotesFromUri(workspaceUri, stripEndingDotGit) {
    return Promise.resolve([]);
  }
};
$SC(
  $Zjc,
  $3oc,
  1
  /* InstantiationType.Delayed */
);

// out-build/vs/workbench/contrib/issue/browser/issueReporterPage.js
var sendSystemInfoLabel = $zf(localize(7620, null));
var sendProcessInfoLabel = $zf(localize(7621, null));
var sendWorkspaceInfoLabel = $zf(localize(7622, null));
var sendExtensionsLabel = $zf(localize(7623, null));
var sendExperimentsLabel = $zf(localize(7624, null));
var sendExtensionData = $zf(localize(7625, null));
var reviewGuidanceLabel = localize(
  // intentionally not escaped because of its embedded tags
  7626,
  null
);
var issueReporterPage_default = () => `
<div class="issue-reporter" id="issue-reporter">
	<div id="english" class="input-group hidden">${$zf(localize(7627, null))}</div>

	<div id="review-guidance-help-text" class="input-group">${reviewGuidanceLabel}</div>

	<div class="section">
		<div class="input-group">
			<label class="inline-label" for="issue-type">${$zf(localize(7628, null))}</label>
			<select id="issue-type" class="inline-form-control">
				<!-- To be dynamically filled -->
			</select>
		</div>

		<div class="input-group" id="problem-source">
			<label class="inline-label" for="issue-source">${$zf(localize(7629, null))} <span class="required-input">*</span></label>
			<select id="issue-source" class="inline-form-control" required>
				<!-- To be dynamically filled -->
			</select>
			<div id="issue-source-empty-error" class="validation-error hidden" role="alert">${$zf(localize(7630, null))}</div>
			<div id="problem-source-help-text" class="instructions hidden">${$zf(localize(7631, null)).replace("{0}", () => `<span tabIndex=0 role="button" id="disableExtensions" class="workbenchCommand">${$zf(localize(7632, null))}</span>`)}
			</div>

			<div id="extension-selection">
				<label class="inline-label" for="extension-selector">${$zf(localize(7633, null))} <span class="required-input">*</span></label>
				<select id="extension-selector" class="inline-form-control">
					<!-- To be dynamically filled -->
				</select>
				<div id="extension-selection-validation-error" class="validation-error hidden" role="alert">${$zf(localize(7634, null)).replace("{0}", () => `<span tabIndex=0 role="button" id="extensionBugsLink" class="workbenchCommand"><!-- To be dynamically filled --></span>`)}</div>
				<div id="extension-selection-validation-error-no-url" class="validation-error hidden" role="alert">
					${$zf(localize(7635, null))}
				</div>
			</div>
		</div>

		<div id="issue-title-container" class="input-group">
			<label class="inline-label" for="issue-title">${$zf(localize(7636, null))} <span class="required-input">*</span></label>
			<input id="issue-title" type="text" class="inline-form-control" placeholder="${$zf(localize(7637, null))}" required>
			<div id="issue-title-empty-error" class="validation-error hidden" role="alert">${$zf(localize(7638, null))}</div>
			<div id="issue-title-length-validation-error" class="validation-error hidden" role="alert">${$zf(localize(7639, null))}</div>
			<small id="similar-issues">
				<!-- To be dynamically filled -->
			</small>
		</div>

	</div>

	<div class="input-group description-section">
		<label for="description" id="issue-description-label">
			<!-- To be dynamically filled -->
		</label>
		<div class="instructions" id="issue-description-subtitle">
			<!-- To be dynamically filled -->
		</div>
		<div class="block-info-text">
			<textarea name="description" id="description" placeholder="${$zf(localize(7640, null))}" required></textarea>
		</div>
		<div id="description-empty-error" class="validation-error hidden" role="alert">${$zf(localize(7641, null))}</div>
		<div id="description-short-error" class="validation-error hidden" role="alert">${$zf(localize(7642, null))}</div>
	</div>

	<div class="system-info" id="block-container">
		<div class="block block-extension-data">
			<input class="send-extension-data" aria-label="${sendExtensionData}" type="checkbox" id="includeExtensionData" checked/>
			<label class="extension-caption" id="extension-caption" for="includeExtensionData">
				${sendExtensionData}
				<span id="ext-loading" hidden></span>
				<span class="ext-parens" hidden>(</span><a href="#" class="showInfo" id="extension-id">${$zf(localize(7643, null))}</a><span class="ext-parens" hidden>)</span>
			</label>
			<pre class="block-info" id="extension-data" placeholder="${$zf(localize(7644, null))}" style="white-space: pre-wrap; user-select: text;">
				<!-- To be dynamically filled -->
			</pre>
		</div>

		<div class="block block-system">
			<input class="sendData" aria-label="${sendSystemInfoLabel}" type="checkbox" id="includeSystemInfo" checked/>
			<label class="caption" for="includeSystemInfo">
				${sendSystemInfoLabel}
				(<a href="#" class="showInfo">${$zf(localize(7645, null))}</a>)
			</label>
			<div class="block-info hidden" style="user-select: text;">
				<!-- To be dynamically filled -->
		</div>
		</div>
		<div class="block block-process">
			<input class="sendData" aria-label="${sendProcessInfoLabel}" type="checkbox" id="includeProcessInfo" checked/>
			<label class="caption" for="includeProcessInfo">
				${sendProcessInfoLabel}
				(<a href="#" class="showInfo">${$zf(localize(7646, null))}</a>)
			</label>
			<pre class="block-info hidden" style="user-select: text;">
				<code>
				<!-- To be dynamically filled -->
				</code>
			</pre>
		</div>
		<div class="block block-workspace">
			<input class="sendData" aria-label="${sendWorkspaceInfoLabel}" type="checkbox" id="includeWorkspaceInfo" checked/>
			<label class="caption" for="includeWorkspaceInfo">
				${sendWorkspaceInfoLabel}
				(<a href="#" class="showInfo">${$zf(localize(7647, null))}</a>)
			</label>
			<pre id="systemInfo" class="block-info hidden" style="user-select: text;">
				<code>
				<!-- To be dynamically filled -->
				</code>
			</pre>
		</div>
		<div class="block block-extensions">
			<input class="sendData" aria-label="${sendExtensionsLabel}" type="checkbox" id="includeExtensions" checked/>
			<label class="caption" for="includeExtensions">
				${sendExtensionsLabel}
				(<a href="#" class="showInfo">${$zf(localize(7648, null))}</a>)
			</label>
			<div id="systemInfo" class="block-info hidden" style="user-select: text;">
				<!-- To be dynamically filled -->
			</div>
		</div>
		<div class="block block-experiments">
			<input class="sendData" aria-label="${sendExperimentsLabel}" type="checkbox" id="includeExperiments" checked/>
			<label class="caption" for="includeExperiments">
				${sendExperimentsLabel}
				(<a href="#" class="showInfo">${$zf(localize(7649, null))}</a>)
			</label>
			<pre class="block-info hidden" style="user-select: text;">
				<!-- To be dynamically filled -->
			</pre>
		</div>
	</div>
</div>`;

// out-build/vs/workbench/contrib/issue/browser/issueReporterModel.js
var $4oc = class {
  constructor(initialData) {
    const defaultData = {
      issueType: 0,
      includeSystemInfo: true,
      includeWorkspaceInfo: true,
      includeProcessInfo: true,
      includeExtensions: true,
      includeExperiments: true,
      includeExtensionData: true,
      allExtensions: []
    };
    this.a = initialData ? Object.assign(defaultData, initialData) : defaultData;
    $Y.addEventListener("message", async (event) => {
      if (event.data && event.data.sendChannel === "vscode:triggerIssueData") {
        $Y.postMessage({
          data: { issueBody: this.a.issueDescription, issueTitle: this.a.issueTitle },
          replyChannel: "vscode:triggerIssueDataResponse"
        }, "*");
      }
    });
  }
  getData() {
    return this.a;
  }
  update(newData) {
    Object.assign(this.a, newData);
  }
  serialize() {
    const modes = [];
    if (this.a.restrictedMode) {
      modes.push("Restricted");
    }
    if (this.a.isUnsupported) {
      modes.push("Unsupported");
    }
    return `
Type: <b>${this.d()}</b>

${this.a.issueDescription}
${this.c()}
VS Code version: ${this.a.versionInfo && this.a.versionInfo.vscodeVersion}
OS version: ${this.a.versionInfo && this.a.versionInfo.os}
Modes:${modes.length ? " " + modes.join(", ") : ""}
${this.b()}
${this.f()}
<!-- generated by issue reporter -->`;
  }
  b() {
    if (this.a.systemInfo && this.a.systemInfo.remoteData.length) {
      return this.a.systemInfo.remoteData.map((remote) => $Ix(remote) ? remote.errorMessage : `Remote OS version: ${remote.machineInfo.os}`).join("\n") + "\n";
    }
    return "";
  }
  fileOnExtension() {
    const fileOnExtensionSupported = this.a.issueType === 0 || this.a.issueType === 1 || this.a.issueType === 2;
    return fileOnExtensionSupported && this.a.fileOnExtension;
  }
  c() {
    if (this.fileOnExtension() && this.a.selectedExtension) {
      return `
Extension version: ${this.a.selectedExtension.version}`;
    } else {
      return "";
    }
  }
  d() {
    if (this.a.issueType === 0) {
      return "Bug";
    } else if (this.a.issueType === 1) {
      return "Performance Issue";
    } else {
      return "Feature Request";
    }
  }
  f() {
    let info = "";
    if (this.a.fileOnMarketplace) {
      return info;
    }
    const isBugOrPerformanceIssue = this.a.issueType === 0 || this.a.issueType === 1;
    if (isBugOrPerformanceIssue) {
      if (this.a.includeExtensionData && this.a.extensionData) {
        info += this.g();
      }
      if (this.a.includeSystemInfo && this.a.systemInfo) {
        info += this.h();
      }
      if (this.a.includeSystemInfo && this.a.systemInfoWeb) {
        info += "System Info: " + this.a.systemInfoWeb;
      }
    }
    if (this.a.issueType === 1) {
      if (this.a.includeProcessInfo) {
        info += this.i();
      }
      if (this.a.includeWorkspaceInfo) {
        info += this.j();
      }
    }
    if (isBugOrPerformanceIssue) {
      if (!this.a.fileOnExtension && this.a.includeExtensions) {
        info += this.l();
      }
      if (this.a.includeExperiments && this.a.experimentInfo) {
        info += this.k();
      }
    }
    return info;
  }
  g() {
    return this.a.extensionData ?? "";
  }
  h() {
    let md = `<details>
<summary>System Info</summary>

|Item|Value|
|---|---|
`;
    if (this.a.systemInfo) {
      md += `|CPUs|${this.a.systemInfo.cpus}|
|GPU Status|${Object.keys(this.a.systemInfo.gpuStatus).map((key2) => `${key2}: ${this.a.systemInfo.gpuStatus[key2]}`).join("<br>")}|
|Load (avg)|${this.a.systemInfo.load}|
|Memory (System)|${this.a.systemInfo.memory}|
|Process Argv|${this.a.systemInfo.processArgs.replace(/\\/g, "\\\\")}|
|Screen Reader|${this.a.systemInfo.screenReader}|
|VM|${this.a.systemInfo.vmHint}|`;
      if (this.a.systemInfo.linuxEnv) {
        md += `
|DESKTOP_SESSION|${this.a.systemInfo.linuxEnv.desktopSession}|
|XDG_CURRENT_DESKTOP|${this.a.systemInfo.linuxEnv.xdgCurrentDesktop}|
|XDG_SESSION_DESKTOP|${this.a.systemInfo.linuxEnv.xdgSessionDesktop}|
|XDG_SESSION_TYPE|${this.a.systemInfo.linuxEnv.xdgSessionType}|`;
      }
      this.a.systemInfo.remoteData.forEach((remote) => {
        if ($Ix(remote)) {
          md += `

${remote.errorMessage}`;
        } else {
          md += `

|Item|Value|
|---|---|
|Remote|${remote.latency ? `${remote.hostName} (latency: ${remote.latency.current.toFixed(2)}ms last, ${remote.latency.average.toFixed(2)}ms average)` : remote.hostName}|
|OS|${remote.machineInfo.os}|
|CPUs|${remote.machineInfo.cpus}|
|Memory (System)|${remote.machineInfo.memory}|
|VM|${remote.machineInfo.vmHint}|`;
        }
      });
    }
    md += "\n</details>";
    return md;
  }
  i() {
    return `<details>
<summary>Process Info</summary>

\`\`\`
${this.a.processInfo}
\`\`\`

</details>
`;
  }
  j() {
    return `<details>
<summary>Workspace Info</summary>

\`\`\`
${this.a.workspaceInfo};
\`\`\`

</details>
`;
  }
  k() {
    return `<details>
<summary>A/B Experiments</summary>

\`\`\`
${this.a.experimentInfo}
\`\`\`

</details>
`;
  }
  l() {
    if (this.a.extensionsDisabled) {
      return "Extensions disabled";
    }
    const themeExclusionStr = this.a.numberOfThemeExtesions ? `
(${this.a.numberOfThemeExtesions} theme extensions excluded)` : "";
    if (!this.a.enabledNonThemeExtesions) {
      return "Extensions: none" + themeExclusionStr;
    }
    const tableHeader = `Extension|Author (truncated)|Version
---|---|---`;
    const table = this.a.enabledNonThemeExtesions.map((e) => {
      return `${e.name}|${e.publisher?.substr(0, 3) ?? "N/A"}|${e.version}`;
    }).join("\n");
    return `<details><summary>Extensions (${this.a.enabledNonThemeExtesions.length})</summary>

${tableHeader}
${table}
${themeExclusionStr}

</details>`;
  }
};

// out-build/vs/workbench/contrib/issue/common/issueReporterUtil.js
function $5oc(url) {
  if (url.endsWith(".git")) {
    url = url.substr(0, url.length - 4);
  }
  url = $Gf(url, "/");
  if (url.endsWith("/new")) {
    url = $Gf(url, "/new");
  }
  if (url.endsWith("/issues")) {
    url = $Gf(url, "/issues");
  }
  return url;
}

// out-build/vs/workbench/contrib/issue/browser/baseIssueReporterService.js
var MAX_URL_LENGTH = 7500;
var IssueSource2;
(function(IssueSource3) {
  IssueSource3["VSCode"] = "vscode";
  IssueSource3["Extension"] = "extension";
  IssueSource3["Marketplace"] = "marketplace";
  IssueSource3["Unknown"] = "unknown";
})(IssueSource2 || (IssueSource2 = {}));
var $6oc = class $6oc2 extends $3c {
  constructor(disableExtensions, data, os, product2, window3, isWeb, issueFormService, themeService) {
    super();
    this.disableExtensions = disableExtensions;
    this.data = data;
    this.os = os;
    this.product = product2;
    this.window = window3;
    this.isWeb = isWeb;
    this.issueFormService = issueFormService;
    this.themeService = themeService;
    this.receivedSystemInfo = false;
    this.numberOfSearchResultsDisplayed = 0;
    this.receivedPerformanceInfo = false;
    this.shouldQueueSearch = false;
    this.hasBeenSubmitted = false;
    this.openReporter = false;
    this.loadingExtensionData = false;
    this.selectedExtension = "";
    this.delayedSubmit = new $Sh(300);
    this.nonGitHubIssueUrl = false;
    const targetExtension = data.extensionId ? data.enabledExtensions.find((extension) => extension.id.toLocaleLowerCase() === data.extensionId?.toLocaleLowerCase()) : void 0;
    this.issueReporterModel = new $4oc({
      ...data,
      issueType: data.issueType || 0,
      versionInfo: {
        vscodeVersion: `${product2.nameShort} ${!!product2.darwinUniversalAssetId ? `${product2.version} (Universal)` : product2.version} (${product2.commit || "Commit unknown"}, ${product2.date || "Date unknown"})`,
        os: `${this.os.type} ${this.os.arch} ${this.os.release}${$o ? " snap" : ""}`
      },
      extensionsDisabled: !!this.disableExtensions,
      fileOnExtension: data.extensionId ? !targetExtension?.isBuiltin : void 0,
      selectedExtension: targetExtension
    });
    const fileOnMarketplace = data.issueSource === IssueSource2.Marketplace;
    const fileOnProduct = data.issueSource === IssueSource2.VSCode;
    this.issueReporterModel.update({ fileOnMarketplace, fileOnProduct });
    const issueReporterElement = this.getElementById("issue-reporter");
    if (issueReporterElement) {
      this.previewButton = new $k2(issueReporterElement, $j2);
      const issueRepoName = document.createElement("a");
      issueReporterElement.appendChild(issueRepoName);
      issueRepoName.id = "show-repo-name";
      issueRepoName.classList.add("hidden");
      this.updatePreviewButtonState();
    }
    const issueTitle = data.issueTitle;
    if (issueTitle) {
      const issueTitleElement = this.getElementById("issue-title");
      if (issueTitleElement) {
        issueTitleElement.value = issueTitle;
      }
    }
    const issueBody = data.issueBody;
    if (issueBody) {
      const description = this.getElementById("description");
      if (description) {
        description.value = issueBody;
        this.issueReporterModel.update({ issueDescription: issueBody });
      }
    }
    if (this.window.document.documentElement.lang !== "en") {
      show(this.getElementById("english"));
    }
    const codiconStyleSheet = $VZ();
    codiconStyleSheet.id = "codiconStyles";
    const iconsStyleSheet = this.B($$Vb(this.themeService));
    function updateAll() {
      codiconStyleSheet.textContent = iconsStyleSheet.getCSS();
    }
    const delayer4 = new $8h(updateAll, 0);
    iconsStyleSheet.onDidChange(() => delayer4.schedule());
    delayer4.schedule();
    this.g(data.enabledExtensions);
    this.y();
    this.c(data.styles);
    if ((data.data || data.uri) && targetExtension) {
      this.updateExtensionStatus(targetExtension);
    }
  }
  render() {
    this.renderBlocks();
  }
  setInitialFocus() {
    const { fileOnExtension } = this.issueReporterModel.getData();
    if (fileOnExtension) {
      const issueTitle = this.window.document.getElementById("issue-title");
      issueTitle?.focus();
    } else {
      const issueType = this.window.document.getElementById("issue-type");
      issueType?.focus();
    }
  }
  // TODO @justschen: After migration to Aux Window, switch to dedicated css.
  c(styles) {
    const styleTag = document.createElement("style");
    const content = [];
    if (styles.inputBackground) {
      content.push(`input[type="text"], textarea, select, .issues-container > .issue > .issue-state, .block-info { background-color: ${styles.inputBackground} !important; }`);
    }
    if (styles.backgroundColor) {
      content.push(`.monaco-workbench { background-color: ${styles.backgroundColor} !important; }`);
      content.push(`.issue-reporter-body::-webkit-scrollbar-track { background-color: ${styles.backgroundColor}; }`);
    }
    if (styles.inputBorder) {
      content.push(`input[type="text"], textarea, select { border: 1px solid ${styles.inputBorder}; }`);
    } else {
      content.push(`input[type="text"], textarea, select { border: 1px solid transparent; }`);
    }
    if (styles.inputForeground) {
      content.push(`input[type="text"], textarea, select, .issues-container > .issue > .issue-state, .block-info { color: ${styles.inputForeground} !important; }`);
    }
    if (styles.inputErrorBorder) {
      content.push(`.invalid-input, .invalid-input:focus, .validation-error { border: 1px solid ${styles.inputErrorBorder} !important; }`);
      content.push(`.required-input { color: ${styles.inputErrorBorder}; }`);
    }
    if (styles.inputErrorBackground) {
      content.push(`.validation-error { background: ${styles.inputErrorBackground}; }`);
    }
    if (styles.inputErrorForeground) {
      content.push(`.validation-error { color: ${styles.inputErrorForeground}; }`);
    }
    if (styles.inputActiveBorder) {
      content.push(`input[type='text']:focus, textarea:focus, select:focus, summary:focus, button:focus, a:focus, .workbenchCommand:focus  { border: 1px solid ${styles.inputActiveBorder}; outline-style: none; }`);
    }
    if (styles.textLinkColor) {
      content.push(`a, .workbenchCommand { color: ${styles.textLinkColor}; }`);
    }
    if (styles.textLinkColor) {
      content.push(`a { color: ${styles.textLinkColor}; }`);
    }
    if (styles.textLinkActiveForeground) {
      content.push(`a:hover, .workbenchCommand:hover { color: ${styles.textLinkActiveForeground}; }`);
    }
    if (styles.sliderActiveColor) {
      content.push(`.issue-reporter-body::-webkit-scrollbar-thumb:active { background-color: ${styles.sliderActiveColor}; }`);
    }
    if (styles.sliderHoverColor) {
      content.push(`.issue-reporter-body::-webkit-scrollbar-thumb { background-color: ${styles.sliderHoverColor}; }`);
      content.push(`.issue-reporter-body::--webkit-scrollbar-thumb:hover { background-color: ${styles.sliderHoverColor}; }`);
    }
    if (styles.buttonBackground) {
      content.push(`.monaco-text-button { background-color: ${styles.buttonBackground} !important; }`);
    }
    if (styles.buttonForeground) {
      content.push(`.monaco-text-button { color: ${styles.buttonForeground} !important; }`);
    }
    if (styles.buttonHoverBackground) {
      content.push(`.monaco-text-button:not(.disabled):hover, .monaco-text-button:focus { background-color: ${styles.buttonHoverBackground} !important; }`);
    }
    styleTag.textContent = content.join("\n");
    this.window.document.head.appendChild(styleTag);
    this.window.document.body.style.color = styles.color || "";
  }
  async f(extension) {
    try {
      if (extension.uri) {
        const uri = URI.revive(extension.uri);
        extension.bugsUrl = uri.toString();
      }
    } catch (e) {
      this.renderBlocks();
    }
  }
  g(extensions) {
    const installedExtensions = extensions.filter((x) => !x.isBuiltin);
    const { nonThemes, themes } = $a(installedExtensions, (ext) => {
      return ext.isTheme ? "themes" : "nonThemes";
    });
    const numberOfThemeExtesions = themes && themes.length;
    this.issueReporterModel.update({ numberOfThemeExtesions, enabledNonThemeExtesions: nonThemes, allExtensions: installedExtensions });
    this.updateExtensionTable(nonThemes, numberOfThemeExtesions);
    if (this.disableExtensions || installedExtensions.length === 0) {
      this.getElementById("disableExtensions").disabled = true;
    }
    this.h(installedExtensions);
  }
  h(extensions) {
    const extensionOptions = extensions.map((extension) => {
      return {
        name: extension.displayName || extension.name || "",
        id: extension.id
      };
    });
    extensionOptions.sort((a, b) => {
      const aName = a.name.toLowerCase();
      const bName = b.name.toLowerCase();
      if (aName > bName) {
        return 1;
      }
      if (aName < bName) {
        return -1;
      }
      return 0;
    });
    const makeOption = (extension, selectedExtension) => {
      const selected = selectedExtension && extension.id === selectedExtension.id;
      return $("option", {
        "value": extension.id,
        "selected": selected || ""
      }, extension.name);
    };
    const extensionsSelector = this.getElementById("extension-selector");
    if (extensionsSelector) {
      const { selectedExtension } = this.issueReporterModel.getData();
      $dk(extensionsSelector, this.makeOption("", localize(7574, null), true), ...extensionOptions.map((extension) => makeOption(extension, selectedExtension)));
      if (!selectedExtension) {
        extensionsSelector.selectedIndex = 0;
      }
      this.addEventListener("extension-selector", "change", async (e) => {
        this.clearExtensionData();
        const selectedExtensionId = e.target.value;
        this.selectedExtension = selectedExtensionId;
        const extensions2 = this.issueReporterModel.getData().allExtensions;
        const matches = extensions2.filter((extension) => extension.id === selectedExtensionId);
        if (matches.length) {
          this.issueReporterModel.update({ selectedExtension: matches[0] });
          const selectedExtension2 = this.issueReporterModel.getData().selectedExtension;
          if (selectedExtension2) {
            const iconElement = document.createElement("span");
            iconElement.classList.add(...ThemeIcon.asClassNameArray($6l.loading), "codicon-modifier-spin");
            this.setLoading(iconElement);
            const openReporterData = await this.j(selectedExtension2);
            if (openReporterData) {
              if (this.selectedExtension === selectedExtensionId) {
                this.removeLoading(iconElement, true);
                this.data = openReporterData;
              }
            } else {
              if (!this.loadingExtensionData) {
                iconElement.classList.remove(...ThemeIcon.asClassNameArray($6l.loading), "codicon-modifier-spin");
              }
              this.removeLoading(iconElement);
              this.clearExtensionData();
              selectedExtension2.data = void 0;
              selectedExtension2.uri = void 0;
            }
            if (this.selectedExtension === selectedExtensionId) {
              this.updateExtensionStatus(matches[0]);
              this.openReporter = false;
            }
          } else {
            this.issueReporterModel.update({ selectedExtension: void 0 });
            this.clearSearchResults();
            this.clearExtensionData();
            this.validateSelectedExtension();
            this.updateExtensionStatus(matches[0]);
          }
        }
      });
    }
    this.addEventListener("problem-source", "change", (_) => {
      this.clearExtensionData();
      this.validateSelectedExtension();
    });
  }
  async j(extension) {
    try {
      const data = await this.issueFormService.sendReporterMenu(extension.id);
      return data;
    } catch (e) {
      console.error(e);
      return void 0;
    }
  }
  setEventHandlers() {
    ["includeSystemInfo", "includeProcessInfo", "includeWorkspaceInfo", "includeExtensions", "includeExperiments", "includeExtensionData"].forEach((elementId) => {
      this.addEventListener(elementId, "click", (event) => {
        event.stopPropagation();
        this.issueReporterModel.update({ [elementId]: !this.issueReporterModel.getData()[elementId] });
      });
    });
    const showInfoElements = this.window.document.getElementsByClassName("showInfo");
    for (let i2 = 0; i2 < showInfoElements.length; i2++) {
      const showInfo = showInfoElements.item(i2);
      showInfo.addEventListener("click", (e) => {
        e.preventDefault();
        const label3 = e.target;
        if (label3) {
          const containingElement = label3.parentElement && label3.parentElement.parentElement;
          const info = containingElement && containingElement.lastElementChild;
          if (info && info.classList.contains("hidden")) {
            show(info);
            label3.textContent = localize(7575, null);
          } else {
            hide2(info);
            label3.textContent = localize(7576, null);
          }
        }
      });
    }
    this.addEventListener("issue-source", "change", (e) => {
      const value = e.target.value;
      const problemSourceHelpText = this.getElementById("problem-source-help-text");
      if (value === "") {
        this.issueReporterModel.update({ fileOnExtension: void 0 });
        show(problemSourceHelpText);
        this.clearSearchResults();
        this.render();
        return;
      } else {
        hide2(problemSourceHelpText);
      }
      const descriptionTextArea = this.getElementById("issue-title");
      if (value === IssueSource2.VSCode) {
        descriptionTextArea.placeholder = localize(7577, null);
      } else if (value === IssueSource2.Extension) {
        descriptionTextArea.placeholder = localize(7578, null);
      } else if (value === IssueSource2.Marketplace) {
        descriptionTextArea.placeholder = localize(7579, null);
      } else {
        descriptionTextArea.placeholder = localize(7580, null);
      }
      let fileOnExtension, fileOnMarketplace = false;
      if (value === IssueSource2.Extension) {
        fileOnExtension = true;
      } else if (value === IssueSource2.Marketplace) {
        fileOnMarketplace = true;
      }
      this.issueReporterModel.update({ fileOnExtension, fileOnMarketplace });
      this.render();
      const title = this.getElementById("issue-title").value;
      this.searchIssues(title, fileOnExtension, fileOnMarketplace);
    });
    this.addEventListener("description", "input", (e) => {
      const issueDescription = e.target.value;
      this.issueReporterModel.update({ issueDescription });
      if (this.issueReporterModel.fileOnExtension() === false) {
        const title = this.getElementById("issue-title").value;
        this.searchVSCodeIssues(title, issueDescription);
      }
    });
    this.addEventListener("issue-title", "input", (_) => {
      const titleElement = this.getElementById("issue-title");
      if (titleElement) {
        const title = titleElement.value;
        this.issueReporterModel.update({ issueTitle: title });
      }
    });
    this.addEventListener("issue-title", "input", (e) => {
      const title = e.target.value;
      const lengthValidationMessage = this.getElementById("issue-title-length-validation-error");
      const issueUrl = this.getIssueUrl();
      if (title && this.getIssueUrlWithTitle(title, issueUrl).length > MAX_URL_LENGTH) {
        show(lengthValidationMessage);
      } else {
        hide2(lengthValidationMessage);
      }
      const issueSource = this.getElementById("issue-source");
      if (!issueSource || issueSource.value === "") {
        return;
      }
      const { fileOnExtension, fileOnMarketplace } = this.issueReporterModel.getData();
      this.searchIssues(title, fileOnExtension, fileOnMarketplace);
    });
    this.previewButton.onDidClick(async () => {
      this.delayedSubmit.trigger(async () => {
        this.createIssue();
      });
    });
    this.addEventListener("disableExtensions", "click", () => {
      this.issueFormService.reloadWithExtensionsDisabled();
    });
    this.addEventListener("extensionBugsLink", "click", (e) => {
      const url = e.target.innerText;
      $nk(url);
    });
    this.addEventListener("disableExtensions", "keydown", (e) => {
      e.stopPropagation();
      if (e.key === "Enter" || e.key === " ") {
        this.issueFormService.reloadWithExtensionsDisabled();
      }
    });
    this.window.document.onkeydown = async (e) => {
      const cmdOrCtrlKey = $m ? e.metaKey : e.ctrlKey;
      if (cmdOrCtrlKey && e.key === "Enter") {
        this.delayedSubmit.trigger(async () => {
          if (await this.createIssue()) {
            this.close();
          }
        });
      }
      if (cmdOrCtrlKey && e.key === "w") {
        e.stopPropagation();
        e.preventDefault();
        const issueTitle = this.getElementById("issue-title").value;
        const { issueDescription } = this.issueReporterModel.getData();
        if (!this.hasBeenSubmitted && (issueTitle || issueDescription)) {
          this.issueFormService.showConfirmCloseDialog();
        } else {
          this.close();
        }
      }
      if ($m) {
        if (cmdOrCtrlKey && e.key === "a" && e.target) {
          if ($Yj(e.target) || $Xj(e.target)) {
            e.target.select();
          }
        }
      }
    };
  }
  updatePerformanceInfo(info) {
    this.issueReporterModel.update(info);
    this.receivedPerformanceInfo = true;
    const state = this.issueReporterModel.getData();
    this.D(state);
    this.F(state);
    this.updatePreviewButtonState();
  }
  updatePreviewButtonState() {
    if (this.m()) {
      if (this.data.githubAccessToken) {
        this.previewButton.label = localize(7581, null);
      } else {
        this.previewButton.label = localize(7582, null);
      }
      this.previewButton.enabled = true;
    } else {
      this.previewButton.enabled = false;
      this.previewButton.label = localize(7583, null);
    }
    const issueRepoName = this.getElementById("show-repo-name");
    const selectedExtension = this.issueReporterModel.getData().selectedExtension;
    if (selectedExtension && selectedExtension.uri) {
      const urlString = URI.revive(selectedExtension.uri).toString();
      issueRepoName.href = urlString;
      issueRepoName.addEventListener("click", (e) => this.H(e));
      issueRepoName.addEventListener("auxclick", (e) => this.H(e));
      const gitHubInfo = this.parseGitHubUrl(urlString);
      issueRepoName.textContent = gitHubInfo ? gitHubInfo.owner + "/" + gitHubInfo.repositoryName : urlString;
      Object.assign(issueRepoName.style, {
        alignSelf: "flex-end",
        display: "block",
        fontSize: "13px",
        marginBottom: "10px",
        padding: "4px 0px",
        textDecoration: "none",
        width: "auto"
      });
      show(issueRepoName);
    } else {
      issueRepoName.removeAttribute("style");
      hide2(issueRepoName);
    }
    this.z();
  }
  m() {
    const issueType = this.issueReporterModel.getData().issueType;
    if (this.loadingExtensionData) {
      return false;
    }
    if (this.isWeb) {
      if (issueType === 2 || issueType === 1 || issueType === 0) {
        return true;
      }
    } else {
      if (issueType === 0 && this.receivedSystemInfo) {
        return true;
      }
      if (issueType === 1 && this.receivedSystemInfo && this.receivedPerformanceInfo) {
        return true;
      }
      if (issueType === 2) {
        return true;
      }
    }
    return false;
  }
  n() {
    const selectedExtension = this.issueReporterModel.getData().selectedExtension;
    return selectedExtension && selectedExtension.repositoryUrl;
  }
  getExtensionBugsUrl() {
    const selectedExtension = this.issueReporterModel.getData().selectedExtension;
    return selectedExtension && selectedExtension.bugsUrl;
  }
  searchVSCodeIssues(title, issueDescription) {
    if (title) {
      this.u(title, issueDescription);
    } else {
      this.clearSearchResults();
    }
  }
  searchIssues(title, fileOnExtension, fileOnMarketplace) {
    if (fileOnExtension) {
      return this.r(title);
    }
    if (fileOnMarketplace) {
      return this.s(title);
    }
    const description = this.issueReporterModel.getData().issueDescription;
    this.searchVSCodeIssues(title, description);
  }
  r(title) {
    const url = this.z();
    if (title) {
      const matches = /^https?:\/\/github\.com\/(.*)/.exec(url);
      if (matches && matches.length) {
        const repo = matches[1];
        return this.t(repo, title);
      }
      if (this.issueReporterModel.getData().selectedExtension) {
        this.clearSearchResults();
        return this.w([]);
      }
    }
    this.clearSearchResults();
  }
  s(title) {
    if (title) {
      const gitHubInfo = this.parseGitHubUrl(this.product.reportMarketplaceIssueUrl);
      if (gitHubInfo) {
        return this.t(`${gitHubInfo.owner}/${gitHubInfo.repositoryName}`, title);
      }
    }
  }
  async close() {
    await this.issueFormService.closeReporter();
  }
  clearSearchResults() {
    const similarIssues = this.getElementById("similar-issues");
    similarIssues.innerText = "";
    this.numberOfSearchResultsDisplayed = 0;
  }
  t(repo, title) {
    const query = `is:issue+repo:${repo}+${title}`;
    const similarIssues = this.getElementById("similar-issues");
    fetch(`https://api.github.com/search/issues?q=${query}`).then((response) => {
      response.json().then((result) => {
        similarIssues.innerText = "";
        if (result && result.items) {
          this.w(result.items);
        } else {
          const message = $("div.list-title");
          message.textContent = localize(7584, null);
          similarIssues.appendChild(message);
          const resetTime = response.headers.get("X-RateLimit-Reset");
          const timeToWait = resetTime ? parseInt(resetTime) - Math.floor(Date.now() / 1e3) : 1;
          if (this.shouldQueueSearch) {
            this.shouldQueueSearch = false;
            setTimeout(() => {
              this.t(repo, title);
              this.shouldQueueSearch = true;
            }, timeToWait * 1e3);
          }
        }
      }).catch((_) => {
        console.warn("Timeout or query limit exceeded");
      });
    }).catch((_) => {
      console.warn("Error fetching GitHub issues");
    });
  }
  u(title, body) {
    const url = "https://vscode-probot.westus.cloudapp.azure.com:7890/duplicate_candidates";
    const init = {
      method: "POST",
      body: JSON.stringify({
        title,
        body
      }),
      headers: new Headers({
        "Content-Type": "application/json"
      })
    };
    fetch(url, init).then((response) => {
      response.json().then((result) => {
        this.clearSearchResults();
        if (result && result.candidates) {
          this.w(result.candidates);
        } else {
          throw new Error("Unexpected response, no candidates property");
        }
      }).catch((_) => {
      });
    }).catch((_) => {
    });
  }
  w(results) {
    const similarIssues = this.getElementById("similar-issues");
    if (results.length) {
      const issues = $("div.issues-container");
      const issuesText = $("div.list-title");
      issuesText.textContent = localize(7585, null);
      this.numberOfSearchResultsDisplayed = results.length < 5 ? results.length : 5;
      for (let i2 = 0; i2 < this.numberOfSearchResultsDisplayed; i2++) {
        const issue = results[i2];
        const link2 = $("a.issue-link", { href: issue.html_url });
        link2.textContent = issue.title;
        link2.title = issue.title;
        link2.addEventListener("click", (e) => this.H(e));
        link2.addEventListener("auxclick", (e) => this.H(e));
        let issueState;
        let item;
        if (issue.state) {
          issueState = $("span.issue-state");
          const issueIcon = $("span.issue-icon");
          issueIcon.appendChild($C1(issue.state === "open" ? $6l.issueOpened : $6l.issueClosed));
          const issueStateLabel = $("span.issue-state.label");
          issueStateLabel.textContent = issue.state === "open" ? localize(7586, null) : localize(7587, null);
          issueState.title = issue.state === "open" ? localize(7588, null) : localize(7589, null);
          issueState.appendChild(issueIcon);
          issueState.appendChild(issueStateLabel);
          item = $("div.issue", void 0, issueState, link2);
        } else {
          item = $("div.issue", void 0, link2);
        }
        issues.appendChild(item);
      }
      similarIssues.appendChild(issuesText);
      similarIssues.appendChild(issues);
    } else {
      const message = $("div.list-title");
      message.textContent = localize(7590, null);
      similarIssues.appendChild(message);
    }
  }
  y() {
    const makeOption = (issueType2, description) => $("option", { "value": issueType2.valueOf() }, $zf(description));
    const typeSelect = this.getElementById("issue-type");
    const { issueType } = this.issueReporterModel.getData();
    $dk(typeSelect, makeOption(0, localize(7591, null)), makeOption(2, localize(7592, null)), makeOption(1, localize(7593, null)));
    typeSelect.value = issueType.toString();
    this.setSourceOptions();
  }
  makeOption(value, description, disabled) {
    const option = document.createElement("option");
    option.disabled = disabled;
    option.value = value;
    option.textContent = description;
    return option;
  }
  setSourceOptions() {
    const sourceSelect = this.getElementById("issue-source");
    const { issueType, fileOnExtension, selectedExtension, fileOnMarketplace, fileOnProduct } = this.issueReporterModel.getData();
    let selected = sourceSelect.selectedIndex;
    if (selected === -1) {
      if (fileOnExtension !== void 0) {
        selected = fileOnExtension ? 2 : 1;
      } else if (selectedExtension?.isBuiltin) {
        selected = 1;
      } else if (fileOnMarketplace) {
        selected = 3;
      } else if (fileOnProduct) {
        selected = 1;
      }
    }
    sourceSelect.innerText = "";
    sourceSelect.append(this.makeOption("", localize(7594, null), true));
    sourceSelect.append(this.makeOption(IssueSource2.VSCode, localize(7595, null), false));
    sourceSelect.append(this.makeOption(IssueSource2.Extension, localize(7596, null), false));
    if (this.product.reportMarketplaceIssueUrl) {
      sourceSelect.append(this.makeOption(IssueSource2.Marketplace, localize(7597, null), false));
    }
    if (issueType !== 2) {
      sourceSelect.append(this.makeOption(IssueSource2.Unknown, localize(7598, null), false));
    }
    if (selected !== -1 && selected < sourceSelect.options.length) {
      sourceSelect.selectedIndex = selected;
    } else {
      sourceSelect.selectedIndex = 0;
      hide2(this.getElementById("problem-source-help-text"));
    }
  }
  renderBlocks() {
    const { issueType, fileOnExtension, fileOnMarketplace, selectedExtension } = this.issueReporterModel.getData();
    const blockContainer = this.getElementById("block-container");
    const systemBlock = this.window.document.querySelector(".block-system");
    const processBlock = this.window.document.querySelector(".block-process");
    const workspaceBlock = this.window.document.querySelector(".block-workspace");
    const extensionsBlock = this.window.document.querySelector(".block-extensions");
    const experimentsBlock = this.window.document.querySelector(".block-experiments");
    const extensionDataBlock = this.window.document.querySelector(".block-extension-data");
    const problemSource = this.getElementById("problem-source");
    const descriptionTitle = this.getElementById("issue-description-label");
    const descriptionSubtitle = this.getElementById("issue-description-subtitle");
    const extensionSelector = this.getElementById("extension-selection");
    const titleTextArea = this.getElementById("issue-title-container");
    const descriptionTextArea = this.getElementById("description");
    const extensionDataTextArea = this.getElementById("extension-data");
    hide2(blockContainer);
    hide2(systemBlock);
    hide2(processBlock);
    hide2(workspaceBlock);
    hide2(extensionsBlock);
    hide2(experimentsBlock);
    hide2(extensionSelector);
    hide2(extensionDataTextArea);
    hide2(extensionDataBlock);
    show(problemSource);
    show(titleTextArea);
    show(descriptionTextArea);
    if (fileOnExtension) {
      show(extensionSelector);
    }
    if (selectedExtension && this.nonGitHubIssueUrl) {
      hide2(titleTextArea);
      hide2(descriptionTextArea);
      $dk(descriptionTitle, localize(7599, null));
      $dk(descriptionSubtitle, localize(7600, null, selectedExtension.displayName));
      this.previewButton.label = localize(7601, null);
      return;
    }
    if (fileOnExtension && selectedExtension?.data) {
      const data = selectedExtension?.data;
      extensionDataTextArea.innerText = data.toString();
      extensionDataTextArea.readOnly = true;
      show(extensionDataBlock);
    }
    if (fileOnExtension && this.openReporter) {
      extensionDataTextArea.readOnly = true;
      setTimeout(() => {
        if (this.openReporter) {
          show(extensionDataBlock);
        }
      }, 100);
      show(extensionDataBlock);
    }
    if (issueType === 0) {
      if (!fileOnMarketplace) {
        show(blockContainer);
        show(systemBlock);
        show(experimentsBlock);
        if (!fileOnExtension) {
          show(extensionsBlock);
        }
      }
      $dk(descriptionTitle, localize(7602, null) + " ", $("span.required-input", void 0, "*"));
      $dk(descriptionSubtitle, localize(7603, null));
    } else if (issueType === 1) {
      if (!fileOnMarketplace) {
        show(blockContainer);
        show(systemBlock);
        show(processBlock);
        show(workspaceBlock);
        show(experimentsBlock);
      }
      if (fileOnExtension) {
        show(extensionSelector);
      } else if (!fileOnMarketplace) {
        show(extensionsBlock);
      }
      $dk(descriptionTitle, localize(7604, null) + " ", $("span.required-input", void 0, "*"));
      $dk(descriptionSubtitle, localize(7605, null));
    } else if (issueType === 2) {
      $dk(descriptionTitle, localize(7606, null) + " ", $("span.required-input", void 0, "*"));
      $dk(descriptionSubtitle, localize(7607, null));
    }
  }
  validateInput(inputId) {
    const inputElement = this.getElementById(inputId);
    const inputValidationMessage = this.getElementById(`${inputId}-empty-error`);
    const descriptionShortMessage = this.getElementById(`description-short-error`);
    if (inputId === "description" && this.nonGitHubIssueUrl && this.data.extensionId) {
      return true;
    } else if (!inputElement.value) {
      inputElement.classList.add("invalid-input");
      inputValidationMessage?.classList.remove("hidden");
      descriptionShortMessage?.classList.add("hidden");
      return false;
    } else if (inputId === "description" && inputElement.value.length < 10) {
      inputElement.classList.add("invalid-input");
      descriptionShortMessage?.classList.remove("hidden");
      inputValidationMessage?.classList.add("hidden");
      return false;
    } else {
      inputElement.classList.remove("invalid-input");
      inputValidationMessage?.classList.add("hidden");
      if (inputId === "description") {
        descriptionShortMessage?.classList.add("hidden");
      }
      return true;
    }
  }
  validateInputs() {
    let isValid2 = true;
    ["issue-title", "description", "issue-source"].forEach((elementId) => {
      isValid2 = this.validateInput(elementId) && isValid2;
    });
    if (this.issueReporterModel.fileOnExtension()) {
      isValid2 = this.validateInput("extension-selector") && isValid2;
    }
    return isValid2;
  }
  async submitToGitHub(issueTitle, issueBody, gitHubDetails) {
    const url = `https://api.github.com/repos/${gitHubDetails.owner}/${gitHubDetails.repositoryName}/issues`;
    const init = {
      method: "POST",
      body: JSON.stringify({
        title: issueTitle,
        body: issueBody
      }),
      headers: new Headers({
        "Content-Type": "application/json",
        "Authorization": `Bearer ${this.data.githubAccessToken}`,
        "User-Agent": "request"
      })
    };
    const response = await fetch(url, init);
    if (!response.ok) {
      console.error("Invalid GitHub URL provided.");
      return false;
    }
    const result = await response.json();
    $Y.open(result.html_url, "_blank");
    this.close();
    return true;
  }
  async createIssue() {
    const selectedExtension = this.issueReporterModel.getData().selectedExtension;
    const hasUri = this.nonGitHubIssueUrl;
    if (hasUri) {
      const url2 = this.getExtensionBugsUrl();
      if (url2) {
        this.hasBeenSubmitted = true;
        return true;
      }
    }
    if (!this.validateInputs()) {
      const invalidInput = this.window.document.getElementsByClassName("invalid-input");
      if (invalidInput.length) {
        invalidInput[0].focus();
      }
      this.addEventListener("issue-title", "input", (_) => {
        this.validateInput("issue-title");
      });
      this.addEventListener("description", "input", (_) => {
        this.validateInput("description");
      });
      this.addEventListener("issue-source", "change", (_) => {
        this.validateInput("issue-source");
      });
      if (this.issueReporterModel.fileOnExtension()) {
        this.addEventListener("extension-selector", "change", (_) => {
          this.validateInput("extension-selector");
        });
      }
      return false;
    }
    this.hasBeenSubmitted = true;
    const issueTitle = this.getElementById("issue-title").value;
    const issueBody = this.issueReporterModel.serialize();
    let issueUrl = this.getIssueUrl();
    if (!issueUrl) {
      console.error("No issue url found");
      return false;
    }
    if (selectedExtension?.uri) {
      const uri = URI.revive(selectedExtension.uri);
      issueUrl = uri.toString();
    }
    const gitHubDetails = this.parseGitHubUrl(issueUrl);
    if (this.data.githubAccessToken && gitHubDetails) {
      return this.submitToGitHub(issueTitle, issueBody, gitHubDetails);
    }
    const baseUrl = this.getIssueUrlWithTitle(this.getElementById("issue-title").value, issueUrl);
    let url = baseUrl + `&body=${encodeURIComponent(issueBody)}`;
    if (url.length > MAX_URL_LENGTH) {
      try {
        url = await this.writeToClipboard(baseUrl, issueBody);
      } catch (_) {
        console.error("Writing to clipboard failed");
        return false;
      }
    }
    this.window.open(url, "_blank");
    return true;
  }
  async writeToClipboard(baseUrl, issueBody) {
    const shouldWrite = await this.issueFormService.showClipboardDialog();
    if (!shouldWrite) {
      throw new $lb();
    }
    return baseUrl + `&body=${encodeURIComponent(localize(7608, null))}`;
  }
  getIssueUrl() {
    return this.issueReporterModel.fileOnExtension() ? this.z() : this.issueReporterModel.getData().fileOnMarketplace ? this.product.reportMarketplaceIssueUrl : this.product.reportIssueUrl;
  }
  parseGitHubUrl(url) {
    const match = /^https?:\/\/github\.com\/([^\/]*)\/([^\/]*).*/.exec(url);
    if (match && match.length) {
      return {
        owner: match[1],
        repositoryName: match[2]
      };
    } else {
      console.error("No GitHub issues match");
    }
    return void 0;
  }
  z() {
    let repositoryUrl = "";
    const bugsUrl = this.getExtensionBugsUrl();
    const extensionUrl = this.n();
    if (bugsUrl && bugsUrl.match(/^https?:\/\/github\.com\/([^\/]*)\/([^\/]*)\/?(\/issues)?$/)) {
      repositoryUrl = $5oc(bugsUrl);
    } else if (extensionUrl && extensionUrl.match(/^https?:\/\/github\.com\/([^\/]*)\/([^\/]*)$/)) {
      repositoryUrl = $5oc(extensionUrl);
    } else {
      this.nonGitHubIssueUrl = true;
      repositoryUrl = bugsUrl || extensionUrl || "";
    }
    return repositoryUrl;
  }
  getIssueUrlWithTitle(issueTitle, repositoryUrl) {
    if (this.issueReporterModel.fileOnExtension()) {
      repositoryUrl = repositoryUrl + "/issues/new";
    }
    const queryStringPrefix = repositoryUrl.indexOf("?") === -1 ? "?" : "&";
    return `${repositoryUrl}${queryStringPrefix}title=${encodeURIComponent(issueTitle)}`;
  }
  clearExtensionData() {
    this.nonGitHubIssueUrl = false;
    this.issueReporterModel.update({ extensionData: void 0 });
    this.data.issueBody = this.data.issueBody || "";
    this.data.data = void 0;
    this.data.uri = void 0;
  }
  async updateExtensionStatus(extension) {
    this.issueReporterModel.update({ selectedExtension: extension });
    const template = this.data.issueBody;
    if (template) {
      const descriptionTextArea = this.getElementById("description");
      const descriptionText = descriptionTextArea.value;
      if (descriptionText === "" || !descriptionText.includes(template.toString())) {
        const fullTextArea = descriptionText + (descriptionText === "" ? "" : "\n") + template.toString();
        descriptionTextArea.value = fullTextArea;
        this.issueReporterModel.update({ issueDescription: fullTextArea });
      }
    }
    const data = this.data.data;
    if (data) {
      this.issueReporterModel.update({ extensionData: data });
      extension.data = data;
      const extensionDataBlock = this.window.document.querySelector(".block-extension-data");
      show(extensionDataBlock);
      this.renderBlocks();
    }
    const uri = this.data.uri;
    if (uri) {
      extension.uri = uri;
      this.f(extension);
    }
    this.validateSelectedExtension();
    const title = this.getElementById("issue-title").value;
    this.r(title);
    this.updatePreviewButtonState();
    this.renderBlocks();
  }
  validateSelectedExtension() {
    const extensionValidationMessage = this.getElementById("extension-selection-validation-error");
    const extensionValidationNoUrlsMessage = this.getElementById("extension-selection-validation-error-no-url");
    hide2(extensionValidationMessage);
    hide2(extensionValidationNoUrlsMessage);
    const extension = this.issueReporterModel.getData().selectedExtension;
    if (!extension) {
      this.previewButton.enabled = true;
      return;
    }
    if (this.loadingExtensionData) {
      return;
    }
    const hasValidGitHubUrl = this.z();
    if (hasValidGitHubUrl) {
      this.previewButton.enabled = true;
    } else {
      this.C();
      this.previewButton.enabled = false;
    }
  }
  setLoading(element) {
    this.openReporter = true;
    this.loadingExtensionData = true;
    this.updatePreviewButtonState();
    const extensionDataCaption = this.getElementById("extension-id");
    hide2(extensionDataCaption);
    const extensionDataCaption2 = Array.from(this.window.document.querySelectorAll(".ext-parens"));
    extensionDataCaption2.forEach((extensionDataCaption22) => hide2(extensionDataCaption22));
    const showLoading = this.getElementById("ext-loading");
    show(showLoading);
    while (showLoading.firstChild) {
      showLoading.firstChild.remove();
    }
    showLoading.append(element);
    this.renderBlocks();
  }
  removeLoading(element, fromReporter = false) {
    this.openReporter = fromReporter;
    this.loadingExtensionData = false;
    this.updatePreviewButtonState();
    const extensionDataCaption = this.getElementById("extension-id");
    show(extensionDataCaption);
    const extensionDataCaption2 = Array.from(this.window.document.querySelectorAll(".ext-parens"));
    extensionDataCaption2.forEach((extensionDataCaption22) => show(extensionDataCaption22));
    const hideLoading = this.getElementById("ext-loading");
    hide2(hideLoading);
    if (hideLoading.firstChild) {
      element.remove();
    }
    this.renderBlocks();
  }
  C() {
    const extensionValidationMessage = this.getElementById("extension-selection-validation-error");
    const extensionValidationNoUrlsMessage = this.getElementById("extension-selection-validation-error-no-url");
    const bugsUrl = this.getExtensionBugsUrl();
    if (bugsUrl) {
      show(extensionValidationMessage);
      const link2 = this.getElementById("extensionBugsLink");
      link2.textContent = bugsUrl;
      return;
    }
    const extensionUrl = this.n();
    if (extensionUrl) {
      show(extensionValidationMessage);
      const link2 = this.getElementById("extensionBugsLink");
      link2.textContent = extensionUrl;
      return;
    }
    show(extensionValidationNoUrlsMessage);
  }
  D(state) {
    const target = this.window.document.querySelector(".block-process .block-info");
    if (target) {
      $dk(target, $("code", void 0, state.processInfo ?? ""));
    }
  }
  F(state) {
    this.window.document.querySelector(".block-workspace .block-info code").textContent = "\n" + state.workspaceInfo;
  }
  updateExtensionTable(extensions, numThemeExtensions) {
    const target = this.window.document.querySelector(".block-extensions .block-info");
    if (target) {
      if (this.disableExtensions) {
        $dk(target, localize(7609, null));
        return;
      }
      const themeExclusionStr = numThemeExtensions ? `
(${numThemeExtensions} theme extensions excluded)` : "";
      extensions = extensions || [];
      if (!extensions.length) {
        target.innerText = "Extensions: none" + themeExclusionStr;
        return;
      }
      $dk(target, this.G(extensions), document.createTextNode(themeExclusionStr));
    }
  }
  G(extensions) {
    return $("table", void 0, $("tr", void 0, $("th", void 0, "Extension"), $("th", void 0, "Author (truncated)"), $("th", void 0, "Version")), ...extensions.map((extension) => $("tr", void 0, $("td", void 0, extension.name), $("td", void 0, extension.publisher?.substr(0, 3) ?? "N/A"), $("td", void 0, extension.version))));
  }
  H(event) {
    event.preventDefault();
    event.stopPropagation();
    if (event.which < 3) {
      $nk(event.target.href);
    }
  }
  getElementById(elementId) {
    const element = this.window.document.getElementById(elementId);
    if (element) {
      return element;
    } else {
      return void 0;
    }
  }
  addEventListener(elementId, eventType, handler) {
    const element = this.getElementById(elementId);
    element?.addEventListener(eventType, handler);
  }
};
__decorate([
  $$t(300)
], $6oc.prototype, "t", null);
__decorate([
  $$t(300)
], $6oc.prototype, "u", null);
$6oc = __decorate([
  __param(6, $5zb),
  __param(7, $gs)
], $6oc);
function hide2(el) {
  el?.classList.add("hidden");
}
function show(el) {
  el?.classList.remove("hidden");
}

// out-build/vs/workbench/contrib/issue/browser/issueReporterService.js
var $9oc = class $9oc2 extends $6oc {
  constructor(disableExtensions, data, os, product2, window3, issueFormService, themeService) {
    super(disableExtensions, data, os, product2, window3, true, issueFormService, themeService);
    const target = this.window.document.querySelector(".block-system .block-info");
    const webInfo = this.window.navigator.userAgent;
    if (webInfo) {
      target?.appendChild(this.window.document.createTextNode(webInfo));
      this.receivedSystemInfo = true;
      this.issueReporterModel.update({ systemInfoWeb: webInfo });
    }
    this.setEventHandlers();
  }
  setEventHandlers() {
    super.setEventHandlers();
    this.addEventListener("issue-type", "change", (event) => {
      const issueType = parseInt(event.target.value);
      this.issueReporterModel.update({ issueType });
      const descriptionTextArea = this.getElementById("issue-title");
      if (descriptionTextArea) {
        descriptionTextArea.placeholder = localize(7650, null);
      }
      this.updatePreviewButtonState();
      this.setSourceOptions();
      this.render();
    });
  }
};
$9oc = __decorate([
  __param(5, $5zb),
  __param(6, $gs)
], $9oc);

// out-build/vs/workbench/contrib/issue/browser/issueFormService.js
var $0oc = class $0oc2 {
  constructor(g, h3, i2, j, k, l, m) {
    this.g = g;
    this.h = h3;
    this.i = i2;
    this.j = j;
    this.k = k;
    this.l = l;
    this.m = m;
    this.b = null;
    this.c = new $6z();
    this.d = "";
    this.e = "";
    this.f = "";
  }
  async openReporter(data) {
    if (this.hasToReload(data)) {
      return;
    }
    await this.openAuxIssueReporter(data);
    if (this.b) {
      const issueReporter = this.g.createInstance($9oc, false, data, { type: this.f, arch: this.d, release: this.e }, product_default, this.b);
      issueReporter.render();
    }
  }
  async openAuxIssueReporter(data, bounds) {
    let issueReporterBounds = { width: 700, height: 800 };
    if (bounds && bounds.x && bounds.y) {
      const centerX = bounds.x + bounds.width / 2;
      const centerY = bounds.y + bounds.height / 2;
      issueReporterBounds = { ...issueReporterBounds, x: centerX - 350, y: centerY - 400 };
    }
    const disposables = new $2c();
    const auxiliaryWindow = disposables.add(await this.h.open({ mode: AuxiliaryWindowMode.Normal, bounds: issueReporterBounds, nativeTitlebar: true, disableFullscreen: true }));
    if (auxiliaryWindow) {
      await auxiliaryWindow.whenStylesHaveLoaded;
      auxiliaryWindow.window.document.title = "Issue Reporter";
      auxiliaryWindow.window.document.body.classList.add("issue-reporter-body");
      const div = document.createElement("div");
      div.classList.add("monaco-workbench");
      auxiliaryWindow.container.remove();
      auxiliaryWindow.window.document.body.appendChild(div);
      $wk(div, issueReporterPage_default());
      this.b = auxiliaryWindow.window;
    } else {
      console.error("Failed to open auxiliary window");
    }
    this.b?.addEventListener("beforeunload", () => {
      auxiliaryWindow.window.close();
      this.b = null;
    });
  }
  async sendReporterMenu(extensionId) {
    const menu = this.i.createMenu($bJ.IssueReporter, this.j);
    const actions = menu.getActions({ renderShortTitle: true }).flatMap((entry) => entry[1]);
    for (const action of actions) {
      try {
        if (action.item && "source" in action.item && action.item.source?.id.toLowerCase() === extensionId.toLowerCase()) {
          this.c.add(extensionId.toLowerCase());
          await action.run();
        }
      } catch (error) {
        console.error(error);
      }
    }
    if (!this.c.has(extensionId)) {
      return void 0;
    }
    this.c.delete(new $5z(extensionId));
    menu.dispose();
    const result = this.a;
    this.a = void 0;
    return result ?? void 0;
  }
  //#region used by issue reporter
  async closeReporter() {
    this.b?.close();
  }
  async reloadWithExtensionsDisabled() {
    if (this.b) {
      try {
        await this.m.reload({ disableExtensions: true });
      } catch (error) {
        this.k.error(error);
      }
    }
  }
  async showConfirmCloseDialog() {
    await this.l.prompt({
      type: severity_default.Warning,
      message: localize(7611, null),
      buttons: [
        {
          label: localize(7612, null),
          run: () => {
            this.closeReporter();
            this.b = null;
          }
        },
        {
          label: localize(7613, null),
          run: () => {
          }
        }
      ]
    });
  }
  async showClipboardDialog() {
    let result = false;
    await this.l.prompt({
      type: severity_default.Warning,
      message: localize(7614, null),
      buttons: [
        {
          label: localize(7615, null),
          run: () => {
            result = true;
          }
        },
        {
          label: localize(7616, null),
          run: () => {
            result = false;
          }
        }
      ]
    });
    return result;
  }
  hasToReload(data) {
    if (data.extensionId && this.c.has(data.extensionId)) {
      this.a = data;
      this.b?.focus();
      return true;
    }
    if (this.b) {
      this.b.focus();
      return true;
    }
    return false;
  }
};
$0oc = __decorate([
  __param(0, $Pk),
  __param(1, $Uob),
  __param(2, $cJ),
  __param(3, $on),
  __param(4, $wn),
  __param(5, $Yv),
  __param(6, $S4)
], $0oc);

// out-build/vs/workbench/contrib/issue/browser/issueService.js
var $$oc = class $$oc2 {
  constructor(a, b, c, d, f, g, h3, i2, j, k, l) {
    this.a = a;
    this.b = b;
    this.c = c;
    this.d = d;
    this.f = f;
    this.g = g;
    this.h = h3;
    this.i = i2;
    this.j = j;
    this.k = k;
    this.l = l;
  }
  async openReporter(options3) {
    if (!this.l.getValue("issueReporter.experimental.webReporter")) {
      const extensionId = options3.extensionId;
      if (!extensionId) {
        if (this.b.reportIssueUrl) {
          const uri2 = this.n(this.b.reportIssueUrl);
          $nk(uri2);
          return;
        }
        throw new Error(`No issue reporting URL configured for ${this.b.nameLong}.`);
      }
      const selectedExtension = this.a.extensions.filter((ext) => ext.identifier.value === options3.extensionId)[0];
      const extensionGitHubUrl = this.m(selectedExtension);
      if (!extensionGitHubUrl) {
        throw new Error(`Unable to find issue reporting url for ${extensionId}`);
      }
      const uri = this.n(`${extensionGitHubUrl}/issues/new`, selectedExtension);
      $nk(uri);
    }
    if (this.b.reportIssueUrl) {
      const theme = this.d.getColorTheme();
      const experiments = await this.f.getCurrentExperiments();
      let githubAccessToken = "";
      try {
        const githubSessions = await this.k.getSessions("github");
        const potentialSessions = githubSessions.filter((session) => session.scopes.includes("repo"));
        githubAccessToken = potentialSessions[0]?.accessToken;
      } catch (e) {
      }
      let isUnsupported = false;
      try {
        isUnsupported = !(await this.h.isPure()).isPure;
      } catch (e) {
      }
      const extensionData = [];
      try {
        const extensions = await this.i.getInstalled();
        const enabledExtensions = extensions.filter((extension) => this.j.isEnabled(extension) || options3.extensionId && extension.identifier.id === options3.extensionId);
        extensionData.push(...enabledExtensions.map((extension) => {
          const { manifest } = extension;
          const manifestKeys = manifest.contributes ? Object.keys(manifest.contributes) : [];
          const isTheme = !manifest.main && !manifest.browser && manifestKeys.length === 1 && manifestKeys[0] === "themes";
          const isBuiltin = extension.type === 0;
          return {
            name: manifest.name,
            publisher: manifest.publisher,
            version: manifest.version,
            repositoryUrl: manifest.repository && manifest.repository.url,
            bugsUrl: manifest.bugs && manifest.bugs.url,
            displayName: manifest.displayName,
            id: extension.identifier.id,
            data: options3.data,
            uri: options3.uri,
            isTheme,
            isBuiltin,
            extensionData: "Extensions data loading"
          };
        }));
      } catch (e) {
        extensionData.push({
          name: "Workbench Issue Service",
          publisher: "Unknown",
          version: "Unknown",
          repositoryUrl: void 0,
          bugsUrl: void 0,
          extensionData: `Extensions not loaded: ${e}`,
          displayName: `Extensions not loaded: ${e}`,
          id: "workbench.issue",
          isTheme: false,
          isBuiltin: true
        });
      }
      const issueReporterData = Object.assign({
        styles: $_oc(theme),
        zoomLevel: $Ne($Y),
        enabledExtensions: extensionData,
        experiments: experiments?.join("\n"),
        restrictedMode: !this.g.isWorkspaceTrusted(),
        isUnsupported,
        githubAccessToken
      }, options3);
      return this.c.openReporter(issueReporterData);
    }
    throw new Error(`No issue reporting URL configured for ${this.b.nameLong}.`);
  }
  m(extension) {
    if (extension.isBuiltin && this.b.reportIssueUrl) {
      return $5oc(this.b.reportIssueUrl);
    }
    let repositoryUrl = "";
    const bugsUrl = extension?.bugs?.url;
    const extensionUrl = extension?.repository?.url;
    if (bugsUrl && bugsUrl.match(/^https?:\/\/github\.com\/(.*)/)) {
      repositoryUrl = $5oc(bugsUrl);
    } else if (extensionUrl && extensionUrl.match(/^https?:\/\/github\.com\/(.*)/)) {
      repositoryUrl = $5oc(extensionUrl);
    }
    return repositoryUrl;
  }
  n(baseUri, extension) {
    const issueDescription = `ADD ISSUE DESCRIPTION HERE

Version: ${this.b.version}
Commit: ${this.b.commit ?? "unknown"}
User Agent: ${$y ?? "unknown"}
Embedder: ${this.b.embedderIdentifier ?? "unknown"}
${extension?.version ? `
Extension version: ${extension.version}` : ""}
<!-- generated by web issue reporter -->`;
    return `${baseUri}?body=${encodeURIComponent(issueDescription)}&labels=web`;
  }
};
$$oc = __decorate([
  __param(0, $wN),
  __param(1, $Vu),
  __param(2, $5zb),
  __param(3, $gs),
  __param(4, $hFb),
  __param(5, $4M),
  __param(6, $Wmc),
  __param(7, $sA),
  __param(8, $qzb),
  __param(9, $xS),
  __param(10, $kl)
], $$oc);
function $_oc(theme) {
  return {
    backgroundColor: getColor2(theme, $Pnb),
    color: getColor2(theme, $eo),
    textLinkColor: getColor2(theme, $no),
    textLinkActiveForeground: getColor2(theme, $oo),
    inputBackground: getColor2(theme, $xq),
    inputForeground: getColor2(theme, $yq),
    inputBorder: getColor2(theme, $zq),
    inputActiveBorder: getColor2(theme, $Aq),
    inputErrorBorder: getColor2(theme, $Nq),
    inputErrorBackground: getColor2(theme, $Lq),
    inputErrorForeground: getColor2(theme, $Mq),
    buttonBackground: getColor2(theme, $Uq),
    buttonForeground: getColor2(theme, $Sq),
    buttonHoverBackground: getColor2(theme, $Vq),
    sliderActiveColor: getColor2(theme, $Fo),
    sliderBackgroundColor: getColor2(theme, $Do),
    sliderHoverColor: getColor2(theme, $Eo)
  };
}
function getColor2(theme, key2) {
  const color2 = theme.getColor(key2);
  return color2 ? color2.toString() : void 0;
}
$SC(
  $6zb,
  $$oc,
  1
  /* InstantiationType.Delayed */
);

// out-build/vs/workbench/contrib/issue/browser/issueTroubleshoot.js
var TroubleshootIssueService_1;
var IssueTroubleshootUi_1;
var ITroubleshootIssueService = $Qk("ITroubleshootIssueService");
var TroubleshootStage;
(function(TroubleshootStage2) {
  TroubleshootStage2[TroubleshootStage2["EXTENSIONS"] = 1] = "EXTENSIONS";
  TroubleshootStage2[TroubleshootStage2["WORKBENCH"] = 2] = "WORKBENCH";
})(TroubleshootStage || (TroubleshootStage = {}));
var TroubleShootState = class _TroubleShootState {
  static fromJSON(raw) {
    if (!raw) {
      return void 0;
    }
    try {
      const data = JSON.parse(raw);
      if ((data.stage === TroubleshootStage.EXTENSIONS || data.stage === TroubleshootStage.WORKBENCH) && typeof data.profile === "string") {
        return new _TroubleShootState(data.stage, data.profile);
      }
    } catch {
    }
    return void 0;
  }
  constructor(stage, profile) {
    this.stage = stage;
    this.profile = profile;
  }
};
var TroubleshootIssueService = class TroubleshootIssueService2 extends $3c {
  static {
    TroubleshootIssueService_1 = this;
  }
  static {
    this.storageKey = "issueTroubleshootState";
  }
  constructor(b, f, g, h3, j, m, n, r2, s, t, u, w, y, z) {
    super();
    this.b = b;
    this.f = f;
    this.g = g;
    this.h = h3;
    this.j = j;
    this.m = m;
    this.n = n;
    this.r = r2;
    this.s = s;
    this.t = t;
    this.u = u;
    this.w = w;
    this.y = y;
    this.z = z;
  }
  isActive() {
    return this.state !== void 0;
  }
  async start() {
    if (this.isActive()) {
      throw new Error("invalid state");
    }
    const res = await this.j.confirm({
      message: localize(7651, null),
      detail: localize(7652, null, this.u.nameLong),
      primaryButton: localize(7653, null),
      custom: true
    });
    if (!res.confirmed) {
      return;
    }
    const originalProfile = this.b.currentProfile;
    await this.h.createTroubleshootProfile();
    this.state = new TroubleShootState(TroubleshootStage.EXTENSIONS, originalProfile.id);
    await this.resume();
  }
  async resume() {
    if (!this.isActive()) {
      return;
    }
    if (this.state?.stage === TroubleshootStage.EXTENSIONS && !this.m.isActive) {
      await this.C();
    }
    if (this.state?.stage === TroubleshootStage.WORKBENCH) {
      await this.D();
    }
    await this.stop();
  }
  async stop() {
    if (!this.isActive()) {
      return;
    }
    if (this.a) {
      this.a.close();
      this.a = void 0;
    }
    if (this.m.isActive) {
      await this.m.reset();
    }
    const profile = this.f.profiles.find((p) => p.id === this.state?.profile) ?? this.f.defaultProfile;
    this.state = void 0;
    await this.g.switchProfile(profile);
  }
  async C() {
    if (!(await this.r.getInstalled(
      1
      /* ExtensionType.User */
    )).length) {
      this.state = new TroubleShootState(TroubleshootStage.WORKBENCH, this.state.profile);
      return;
    }
    const result = await this.G(localize(7654, null));
    if (result === "good") {
      const profile = this.f.profiles.find((p) => p.id === this.state.profile) ?? this.f.defaultProfile;
      await this.F(profile);
    }
    if (result === "bad") {
      this.state = new TroubleShootState(TroubleshootStage.WORKBENCH, this.state.profile);
    }
    if (result === "stop") {
      await this.stop();
    }
  }
  async D() {
    await this.g.createAndEnterTransientProfile();
    this.L(this.state);
    const result = await this.G(localize(7655, null));
    if (result === "stop") {
      await this.stop();
    }
    if (result === "good") {
      await this.H(localize(7656, null));
    }
    if (result === "bad") {
      await this.H(localize(7657, null, this.u.nameLong));
    }
  }
  async F(profile) {
    await this.g.switchProfile(profile);
    const extensions = (await this.r.getInstalled(
      1
      /* ExtensionType.User */
    )).filter((ext) => this.s.isEnabled(ext));
    await this.m.start(extensions);
    await this.w.reload();
  }
  G(message) {
    return new Promise((c, e) => {
      const goodPrompt = {
        label: localize(7658, null),
        run: () => c("good")
      };
      const badPrompt = {
        label: localize(7659, null),
        run: () => c("bad")
      };
      const stop = {
        label: localize(7660, null),
        run: () => c("stop")
      };
      this.a = this.n.prompt(Severity2.Info, message, [goodPrompt, badPrompt, stop], { sticky: true, priority: NotificationPriority.URGENT });
    });
  }
  async H(message) {
    let isCheckedInInsiders = false;
    if (this.u.quality === "stable") {
      const res = await this.I();
      if (res === "good") {
        await this.j.prompt({
          type: Severity2.Info,
          message: localize(7661, null),
          detail: localize(7662, null, this.u.nameLong),
          custom: true
        });
        return;
      }
      if (res === "stop") {
        await this.stop();
        return;
      }
      if (res === "bad") {
        isCheckedInInsiders = true;
      }
    }
    await this.t.openReporter({
      issueBody: `> ${message} ${isCheckedInInsiders ? `It is confirmed that the issue exists in ${this.u.nameLong} Insiders` : ""}`
    });
  }
  async I() {
    const confirmRes = await this.j.confirm({
      type: "info",
      message: localize(7663, null),
      primaryButton: localize(7664, null, this.u.nameLong),
      cancelButton: localize(7665, null),
      detail: localize(7666, null, this.u.nameLong),
      custom: {
        disableCloseAction: true
      }
    });
    if (!confirmRes.confirmed) {
      return void 0;
    }
    const opened = await this.z.open(URI.parse("https://aka.ms/vscode-insiders"));
    if (!opened) {
      return void 0;
    }
    const res = await this.j.prompt({
      type: "info",
      message: localize(7667, null),
      buttons: [{
        label: localize(7668, null),
        run: () => "good"
      }, {
        label: localize(7669, null),
        run: () => "bad"
      }],
      cancelButton: {
        label: localize(7670, null),
        run: () => "stop"
      },
      detail: localize(7671, null, this.u.nameLong),
      custom: {
        disableCloseAction: true
      }
    });
    return res.result;
  }
  get state() {
    if (this.J === void 0) {
      const raw = this.y.get(
        TroubleshootIssueService_1.storageKey,
        0
        /* StorageScope.PROFILE */
      );
      this.J = TroubleShootState.fromJSON(raw);
    }
    return this.J || void 0;
  }
  set state(state) {
    this.J = state ?? null;
    this.L(state);
  }
  L(state) {
    if (state) {
      this.y.store(
        TroubleshootIssueService_1.storageKey,
        JSON.stringify(state),
        0,
        1
        /* StorageTarget.MACHINE */
      );
    } else {
      this.y.remove(
        TroubleshootIssueService_1.storageKey,
        0
        /* StorageScope.PROFILE */
      );
    }
  }
};
TroubleshootIssueService = TroubleshootIssueService_1 = __decorate([
  __param(0, $gT),
  __param(1, $rs),
  __param(2, $hT),
  __param(3, $nT),
  __param(4, $Yv),
  __param(5, $gWb),
  __param(6, $PJ),
  __param(7, $sA),
  __param(8, $qzb),
  __param(9, $6zb),
  __param(10, $Vu),
  __param(11, $S4),
  __param(12, $jv),
  __param(13, $O4)
], TroubleshootIssueService);
var IssueTroubleshootUi = class IssueTroubleshootUi2 extends $3c {
  static {
    IssueTroubleshootUi_1 = this;
  }
  static {
    this.ctxIsTroubleshootActive = new $nn("isIssueTroubleshootActive", false);
  }
  constructor(a, b, storageService) {
    super();
    this.a = a;
    this.b = b;
    this.f();
    if (b.isActive()) {
      b.resume();
    }
    this.B(storageService.onDidChangeValue(0, TroubleshootIssueService.storageKey, this.q)(() => {
      this.f();
    }));
  }
  f() {
    IssueTroubleshootUi_1.ctxIsTroubleshootActive.bindTo(this.a).set(this.b.isActive());
  }
};
IssueTroubleshootUi = IssueTroubleshootUi_1 = __decorate([
  __param(0, $on),
  __param(1, ITroubleshootIssueService),
  __param(2, $jv)
], IssueTroubleshootUi);
$Wn.as(Extensions2.Workbench).registerWorkbenchContribution(
  IssueTroubleshootUi,
  3
  /* LifecyclePhase.Restored */
);
$hJ(class TroubleshootIssueAction extends $gJ {
  constructor() {
    super({
      id: "workbench.action.troubleshootIssue.start",
      title: localize2(7672, "Troubleshoot Issue..."),
      category: $qn.Help,
      f1: true,
      precondition: $7m.and(IssueTroubleshootUi.ctxIsTroubleshootActive.negate(), $kpb.isEqualTo(""), $veb.negate())
    });
  }
  run(accessor) {
    return accessor.get(ITroubleshootIssueService).start();
  }
});
$hJ(class extends $gJ {
  constructor() {
    super({
      id: "workbench.action.troubleshootIssue.stop",
      title: localize2(7673, "Stop Troubleshoot Issue"),
      category: $qn.Help,
      f1: true,
      precondition: IssueTroubleshootUi.ctxIsTroubleshootActive
    });
  }
  async run(accessor) {
    return accessor.get(ITroubleshootIssueService).stop();
  }
});
$SC(
  ITroubleshootIssueService,
  TroubleshootIssueService,
  1
  /* InstantiationType.Delayed */
);

// out-build/vs/workbench/contrib/issue/common/issue.contribution.js
var OpenIssueReporterActionId = "workbench.action.openIssueReporter";
var OpenIssueReporterApiId = "vscode.openIssueReporter";
var OpenIssueReporterCommandMetadata = {
  description: "Open the issue reporter and optionally prefill part of the form.",
  args: [
    {
      name: "options",
      description: "Data to use to prefill the issue reporter with.",
      isOptional: true,
      schema: {
        oneOf: [
          {
            type: "string",
            description: "The extension id to preselect."
          },
          {
            type: "object",
            properties: {
              extensionId: {
                type: "string"
              },
              issueTitle: {
                type: "string"
              },
              issueBody: {
                type: "string"
              }
            }
          }
        ]
      }
    }
  ]
};
var $apc = class $apc2 extends $3c {
  constructor(productService, configurationService) {
    super();
    if (!productService.reportIssueUrl) {
      return;
    }
    this.B($tn.registerCommand({
      id: OpenIssueReporterActionId,
      handler: function(accessor, args2) {
        const data = typeof args2 === "string" ? { extensionId: args2 } : Array.isArray(args2) ? { extensionId: args2[0] } : args2 ?? {};
        return accessor.get($6zb).openReporter(data);
      },
      metadata: OpenIssueReporterCommandMetadata
    }));
    this.B($tn.registerCommand({
      id: OpenIssueReporterApiId,
      handler: function(accessor, args2) {
        const data = typeof args2 === "string" ? { extensionId: args2 } : Array.isArray(args2) ? { extensionId: args2[0] } : args2 ?? {};
        return accessor.get($6zb).openReporter(data);
      },
      metadata: OpenIssueReporterCommandMetadata
    }));
    const reportIssue = {
      id: OpenIssueReporterActionId,
      title: localize2(7675, "Report Issue..."),
      category: $qn.Help
    };
    this.B($dJ.appendMenuItem($bJ.CommandPalette, { command: reportIssue }));
    this.B($dJ.appendMenuItem($bJ.MenubarHelpMenu, {
      group: "3_feedback",
      command: {
        id: OpenIssueReporterActionId,
        title: localize(7674, null)
      },
      order: 3
    }));
  }
};
$apc = __decorate([
  __param(0, $Vu),
  __param(1, $kl)
], $apc);

// out-build/vs/workbench/contrib/issue/browser/issue.contribution.js
var WebIssueContribution = class WebIssueContribution2 extends $apc {
  constructor(productService, configurationService) {
    super(productService, configurationService);
    $Wn.as($Ht.Configuration).registerConfiguration({
      properties: {
        "issueReporter.experimental.webReporter": {
          type: "boolean",
          default: productService.quality !== "stable",
          description: "Enable experimental issue reporter for web."
        }
      }
    });
  }
};
WebIssueContribution = __decorate([
  __param(0, $Vu),
  __param(1, $kl)
], WebIssueContribution);
$Wn.as(Extensions2.Workbench).registerWorkbenchContribution(
  WebIssueContribution,
  3
  /* LifecyclePhase.Restored */
);
$SC(
  $6zb,
  $$oc,
  1
  /* InstantiationType.Delayed */
);
$SC(
  $5zb,
  $0oc,
  1
  /* InstantiationType.Delayed */
);
$tn.registerCommand("_issues.getSystemStatus", (accessor) => {
  return localize(7610, null);
});

// out-build/vs/workbench/contrib/splash/browser/splash.js
var $bpc = $Qk("ISplashStorageService");

// out-build/vs/workbench/contrib/splash/browser/partsSplash.js
var $cpc_1;
var $cpc = class $cpc2 {
  static {
    $cpc_1 = this;
  }
  static {
    this.ID = "workbench.contrib.partsSplash";
  }
  static {
    this.a = "monaco-parts-splash";
  }
  constructor(d, f, g, h3, i2, editorGroupsService, lifecycleService) {
    this.d = d;
    this.f = f;
    this.g = g;
    this.h = h3;
    this.i = i2;
    this.b = new $2c();
    Event2.once(f.onDidLayoutMainContainer)(() => {
      this.l();
      $S("code/didRemovePartsSplash");
    }, void 0, this.b);
    const lastIdleSchedule = this.b.add(new $4c());
    const savePartsSplashSoon = () => {
      lastIdleSchedule.value = $gj($Y, () => this.j(), 2500);
    };
    lifecycleService.when(
      3
      /* LifecyclePhase.Restored */
    ).then(() => {
      Event2.any(Event2.filter($Te, (windowId) => windowId === $Y.vscodeWindowId), editorGroupsService.mainPart.onDidLayout, d.onDidColorThemeChange)(savePartsSplashSoon, void 0, this.b);
      savePartsSplashSoon();
    });
    h3.onDidChangeConfiguration((e) => {
      if (e.affectsConfiguration(
        "window.titleBarStyle"
        /* TitleBarSetting.TITLE_BAR_STYLE */
      )) {
        this.c = true;
        this.j();
      }
    }, this, this.b);
  }
  dispose() {
    this.b.dispose();
  }
  j() {
    const theme = this.d.getColorTheme();
    this.i.saveWindowSplash({
      zoomLevel: this.h.getValue("window.zoomLevel"),
      baseTheme: $ks(theme.type),
      colorInfo: {
        foreground: theme.getColor($eo)?.toString(),
        background: $Vn.Format.CSS.formatHex(theme.getColor($Ko) || $4lb(theme)),
        editorBackground: theme.getColor($Ko)?.toString(),
        titleBarBackground: theme.getColor($6nb)?.toString(),
        titleBarBorder: theme.getColor($8nb)?.toString(),
        activityBarBackground: theme.getColor($nnb)?.toString(),
        activityBarBorder: theme.getColor($qnb)?.toString(),
        sideBarBackground: theme.getColor($Pnb)?.toString(),
        sideBarBorder: theme.getColor($Rnb)?.toString(),
        statusBarBackground: theme.getColor($4mb)?.toString(),
        statusBarBorder: theme.getColor($6mb)?.toString(),
        statusBarNoFolderBackground: theme.getColor($5mb)?.toString(),
        windowBorder: theme.getColor($sob)?.toString() ?? theme.getColor($tob)?.toString()
      },
      layoutInfo: !this.k() ? void 0 : {
        sideBarSide: this.f.getSideBarPosition() === 1 ? "right" : "left",
        editorPartMinWidth: $Xob.width,
        titleBarHeight: this.f.isVisible("workbench.parts.titlebar", $Y) ? $Bj($Kg(this.f.getContainer(
          $Y,
          "workbench.parts.titlebar"
          /* Parts.TITLEBAR_PART */
        ))) : 0,
        activityBarWidth: this.f.isVisible(
          "workbench.parts.activitybar"
          /* Parts.ACTIVITYBAR_PART */
        ) ? $xj($Kg(this.f.getContainer(
          $Y,
          "workbench.parts.activitybar"
          /* Parts.ACTIVITYBAR_PART */
        ))) : 0,
        sideBarWidth: this.f.isVisible(
          "workbench.parts.sidebar"
          /* Parts.SIDEBAR_PART */
        ) ? $xj($Kg(this.f.getContainer(
          $Y,
          "workbench.parts.sidebar"
          /* Parts.SIDEBAR_PART */
        ))) : 0,
        statusBarHeight: this.f.isVisible("workbench.parts.statusbar", $Y) ? $Bj($Kg(this.f.getContainer(
          $Y,
          "workbench.parts.statusbar"
          /* Parts.STATUSBAR_PART */
        ))) : 0,
        windowBorder: this.f.hasMainWindowBorder(),
        windowBorderRadius: this.f.getMainWindowBorderRadius()
      }
    });
  }
  k() {
    return !$Se($Y) && !this.g.isExtensionDevelopment && !this.c;
  }
  l() {
    const element = $Y.document.getElementById($cpc_1.a);
    if (element) {
      element.style.display = "none";
    }
    const defaultStyles3 = $Y.document.head.getElementsByClassName("initialShellColors");
    defaultStyles3[0]?.remove();
  }
};
$cpc = $cpc_1 = __decorate([
  __param(0, $gs),
  __param(1, $Vlb),
  __param(2, $US),
  __param(3, $kl),
  __param(4, $bpc),
  __param(5, $iJ),
  __param(6, $KL)
], $cpc);

// out-build/vs/workbench/contrib/splash/browser/splash.contribution.js
$SC(
  $bpc,
  class SplashStorageService {
    async saveWindowSplash(splash) {
      const raw = JSON.stringify(splash);
      localStorage.setItem("monaco-parts-splash", raw);
    }
  },
  1
  /* InstantiationType.Delayed */
);
$PL(
  $cpc.ID,
  $cpc,
  1
  /* WorkbenchPhase.BlockStartup */
);

// out-build/vs/workbench/contrib/remote/browser/remoteStartEntry.js
var $epc_1;
var $dpc = new $nn("showRemoteStartEntryInWeb", false);
var $epc = class $epc2 extends $3c {
  static {
    $epc_1 = this;
  }
  static {
    this.a = "workbench.action.remote.showWebStartEntryActions";
  }
  constructor(f, g, h3, j, m, n) {
    super();
    this.f = f;
    this.g = g;
    this.h = h3;
    this.j = j;
    this.m = m;
    this.n = n;
    const remoteExtensionTips = this.g.remoteExtensionTips?.["tunnel"];
    this.c = remoteExtensionTips?.startEntry?.startCommand ?? "";
    this.b = remoteExtensionTips?.extensionId ?? "";
    this.t();
    this.r();
    this.s();
  }
  r() {
    const category8 = localize2(9192, "Remote");
    const startEntry = this;
    this.B($hJ(class extends $gJ {
      constructor() {
        super({
          id: $epc_1.a,
          category: category8,
          title: localize2(9193, "Show Remote Start Entry for web"),
          f1: false
        });
      }
      async run() {
        await startEntry.u();
      }
    }));
  }
  s() {
    this.B(this.j.onEnablementChanged(async (result) => {
      for (const ext of result) {
        if ($5z.equals(this.b, ext.identifier.id)) {
          if (this.j.isEnabled(ext)) {
            $dpc.bindTo(this.n).set(true);
          } else {
            $dpc.bindTo(this.n).set(false);
          }
        }
      }
    }));
  }
  async t() {
    const installed = (await this.h.getInstalled()).find((value) => $5z.equals(value.identifier.id, this.b));
    if (installed) {
      if (this.j.isEnabled(installed)) {
        $dpc.bindTo(this.n).set(true);
      }
    }
  }
  async u() {
    this.f.executeCommand(this.c);
    this.m.publicLog2("workbenchActionExecuted", {
      id: this.c,
      from: "remote start entry"
    });
  }
};
$epc = $epc_1 = __decorate([
  __param(0, $sn),
  __param(1, $Vu),
  __param(2, $sA),
  __param(3, $qzb),
  __param(4, $zv),
  __param(5, $on)
], $epc);

// out-build/vs/workbench/contrib/remote/browser/remoteStartEntry.contribution.js
$Wn.as(Extensions2.Workbench).registerWorkbenchContribution(
  $epc,
  3
  /* LifecyclePhase.Restored */
);

// out-build/vs/workbench/browser/web.factory.js
var created = false;
var workbenchPromise = new $gi();
function $fpc(domElement, options3) {
  $S("code/didLoadWorkbenchMain");
  if (created) {
    throw new Error("Unable to create the VSCode workbench more than once.");
  } else {
    created = true;
  }
  if (Array.isArray(options3.commands)) {
    for (const command4 of options3.commands) {
      $tn.registerCommand(command4.id, (accessor, ...args2) => {
        return command4.handler(...args2);
      });
      if (command4.label) {
        for (const menu of $5b(command4.menu ?? Menu.CommandPalette)) {
          $dJ.appendMenuItem(asMenuId(menu), { command: { id: command4.id, title: command4.label } });
        }
      }
    }
  }
  let instantiatedWorkbench = void 0;
  new $Vmc(domElement, options3).open().then((workbench2) => {
    instantiatedWorkbench = workbench2;
    workbenchPromise.complete(workbench2);
  });
  return $1c(() => {
    if (instantiatedWorkbench) {
      instantiatedWorkbench.shutdown();
    } else {
      workbenchPromise.p.then((instantiatedWorkbench2) => instantiatedWorkbench2.shutdown());
    }
  });
}
function asMenuId(menu) {
  switch (menu) {
    case Menu.CommandPalette:
      return $bJ.CommandPalette;
    case Menu.StatusBarWindowIndicatorMenu:
      return $bJ.StatusBarWindowIndicatorMenu;
  }
}
var commands;
(function(commands2) {
  async function executeCommand(command4, ...args2) {
    const workbench2 = await workbenchPromise.p;
    return workbench2.commands.executeCommand(command4, ...args2);
  }
  commands2.executeCommand = executeCommand;
})(commands || (commands = {}));
var logger;
(function(logger2) {
  function log4(level, message) {
    workbenchPromise.p.then((workbench2) => workbench2.logger.log(level, message));
  }
  logger2.log = log4;
})(logger || (logger = {}));
var env2;
(function(env3) {
  async function retrievePerformanceMarks() {
    const workbench2 = await workbenchPromise.p;
    return workbench2.env.retrievePerformanceMarks();
  }
  env3.retrievePerformanceMarks = retrievePerformanceMarks;
  async function getUriScheme() {
    const workbench2 = await workbenchPromise.p;
    return workbench2.env.getUriScheme();
  }
  env3.getUriScheme = getUriScheme;
  async function openUri(target) {
    const workbench2 = await workbenchPromise.p;
    return workbench2.env.openUri(target);
  }
  env3.openUri = openUri;
})(env2 || (env2 = {}));
var window2;
(function(window3) {
  async function withProgress(options3, task) {
    const workbench2 = await workbenchPromise.p;
    return workbench2.window.withProgress(options3, task);
  }
  window3.withProgress = withProgress;
  async function createTerminal(options3) {
    const workbench2 = await workbenchPromise.p;
    workbench2.window.createTerminal(options3);
  }
  window3.createTerminal = createTerminal;
  async function showInformationMessage(message, ...items) {
    const workbench2 = await workbenchPromise.p;
    return await workbench2.window.showInformationMessage(message, ...items);
  }
  window3.showInformationMessage = showInformationMessage;
})(window2 || (window2 = {}));
var workspace;
(function(workspace2) {
  async function didResolveRemoteAuthority() {
    const workbench2 = await workbenchPromise.p;
    await workbench2.workspace.didResolveRemoteAuthority();
  }
  workspace2.didResolveRemoteAuthority = didResolveRemoteAuthority;
  async function openTunnel(tunnelOptions) {
    const workbench2 = await workbenchPromise.p;
    return workbench2.workspace.openTunnel(tunnelOptions);
  }
  workspace2.openTunnel = openTunnel;
})(workspace || (workspace = {}));

// out-build/vs/platform/userDataSync/common/userDataSyncResourceProvider.js
var $gpc_1;
var $gpc = class $gpc2 {
  static {
    $gpc_1 = this;
  }
  static {
    this.a = "not-existing-resource";
  }
  static {
    this.b = "remote-backup";
  }
  static {
    this.c = "local-backup";
  }
  constructor(e, f, g, uriIdentityService, h3, i2, j, k, l, n) {
    this.e = e;
    this.f = f;
    this.g = g;
    this.h = h3;
    this.i = i2;
    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 $Boc(syncData);
    }
    return [];
  }
  async getLocalSyncedProfiles(location3) {
    const refs = await this.f.getAllResourceRefs("profiles", void 0, location3);
    if (refs.length) {
      const content = await this.f.resolveResourceContent("profiles", refs[0].ref, void 0, location3);
      if (content) {
        const syncData = this.L(
          content,
          "profiles"
          /* SyncResource.Profiles */
        );
        return $Boc(syncData);
      }
    }
    return [];
  }
  async getLocalSyncedMachines(location3) {
    const refs = await this.f.getAllResourceRefs("machines", void 0, location3);
    if (refs.length) {
      const content = await this.f.resolveResourceContent("machines", refs[0].ref, void 0, location3);
      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: created2, ref }) => ({
      created: created2,
      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, location3) {
    const handles = await this.f.getAllResourceRefs(syncResource, profile?.collection, location3);
    return handles.map(({ created: created2, ref }) => ({
      created: created2,
      uri: this.J({
        remote: false,
        syncResource,
        profile: profile?.id ?? this.k.defaultProfile.id,
        collection: profile?.collection,
        ref,
        node: void 0,
        location: location3
      })
    }));
  }
  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 $7v(this.h, this.j, this.i);
  }
  async resolveContent(uri) {
    const resolved = this.K(uri);
    if (!resolved) {
      return null;
    }
    if (resolved.node === $gpc_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, location3) {
    if (remote) {
      const { content } = await this.M(syncResource, ref, collection);
      return content;
    }
    return this.f.resolveResourceContent(syncResource, ref, collection, location3);
  }
  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, $gpc_1.a);
    return [{ resource, comparableResource }];
  }
  t(syncData, node) {
    switch (node) {
      case "settings.json":
        return $Fmc(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, $gpc_1.a);
    return [{ resource, comparableResource }];
  }
  v(syncData, node) {
    switch (node) {
      case "keybindings.json":
        return $Cmc(syncData.content, !!this.l.getValue($OBb), this.g);
    }
    return null;
  }
  w(uri, profile) {
    const resource = this.d.joinPath(uri, "tasks.json");
    const comparableResource = profile ? profile.tasksResource : this.d.joinPath(uri, $gpc_1.a);
    return [{ resource, comparableResource }];
  }
  x(syncData, node) {
    switch (node) {
      case "tasks.json":
        return $Nmc(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 = $Kmc(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, $gpc_1.a);
          result.push({ resource, comparableResource });
        }
        return result;
      }
    }
    return [];
  }
  z(syncData, node) {
    return $Kmc(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, $gpc_1.a);
    return [{ resource, comparableResource }];
  }
  B(syncData, node) {
    switch (node) {
      case "extensions.json":
        return $xmc($wmc(syncData), true);
    }
    return null;
  }
  async C(profile) {
    const { localExtensions } = await this.n.createInstance($zmc).getLocalExtensions(profile);
    return $xmc(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, $gpc_1.a);
    return [{ resource, comparableResource }];
  }
  E(syncData, node) {
    switch (node) {
      case "globalState.json":
        return $QXb(JSON.parse(syncData.content), true);
    }
    return null;
  }
  async F(profile) {
    const localGlobalState = await this.n.createInstance($SXb).getLocalGlobalState(profile);
    return $QXb(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 $Tw(JSON.parse(syncData.content), {});
    }
    return null;
  }
  async I(profile) {
    return $Aoc(this.k.profiles.filter((p) => !p.isDefault && !p.isTransient), true);
  }
  J(syncResourceUriInfo) {
    const authority = syncResourceUriInfo.remote ? $gpc_1.b : $gpc_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: $aCb, authority, path: `/`, query: syncResourceUriInfo.location?.query, fragment: syncResourceUriInfo.location?.fragment }), ...paths);
  }
  K(uri) {
    if (uri.scheme !== $aCb) {
      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 === $gpc_1.b;
    let scheme;
    let authority;
    const locationPaths = [];
    let syncResource;
    let profile;
    let collection;
    let ref;
    let node;
    while (paths.length) {
      const path = paths.shift();
      if (path.startsWith("scheme:")) {
        scheme = path.substring("scheme:".length);
      } else if (path.startsWith("authority:")) {
        authority = path.substring("authority:".length);
      } else if (path.startsWith("syncResource:")) {
        syncResource = path.substring("syncResource:".length);
      } else if (path.startsWith("profile:")) {
        profile = path.substring("profile:".length);
      } else if (path.startsWith("collection:")) {
        collection = path.substring("collection:".length);
      } else if (path.startsWith("ref:")) {
        ref = path.substring("ref:".length);
      } else if (!syncResource) {
        locationPaths.push(path);
      } else {
        node = path;
      }
    }
    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 ($JXb(syncData)) {
        return syncData;
      }
    } catch (error) {
      this.g.error(error);
    }
    throw new $1Bb(localize(2509, null), "IncompatibleRemoteContent", syncResource);
  }
  async M(syncResource, ref, collection) {
    const content = await this.e.resolveResourceContent(syncResource, ref, collection);
    return { ref, content };
  }
};
$gpc = $gpc_1 = __decorate([
  __param(0, $VBb),
  __param(1, $WBb),
  __param(2, $$Bb),
  __param(3, $vl),
  __param(4, $Xk),
  __param(5, $jv),
  __param(6, $km),
  __param(7, $rs),
  __param(8, $kl),
  __param(9, $Pk)
], $gpc);

// out-build/vs/workbench/workbench.web.main.internal.js
$SC(
  $pzb,
  $woc,
  1
  /* InstantiationType.Delayed */
);
$SC(
  $ND,
  $Eoc,
  1
  /* InstantiationType.Delayed */
);
$SC(
  $50,
  $toc,
  1
  /* InstantiationType.Delayed */
);
$SC(
  $VBb,
  $GXb,
  1
  /* InstantiationType.Delayed */
);
$SC(
  $HBb,
  $JBb,
  1
  /* InstantiationType.Delayed */
);
$SC(
  $WBb,
  $xoc,
  1
  /* InstantiationType.Delayed */
);
$SC(
  $eWb,
  $fWb,
  1
  /* InstantiationType.Delayed */
);
$SC(
  $7Bb,
  $Coc,
  1
  /* InstantiationType.Delayed */
);
$SC(
  $8Bb,
  $gpc,
  1
  /* InstantiationType.Delayed */
);
$SC(
  $9Bb,
  $Doc,
  0
  /* InstantiationType.Eager */
);
$SC(
  $RTb,
  $4Tb,
  0
  /* InstantiationType.Eager */
);
$SC(
  $wA,
  $uoc,
  1
  /* InstantiationType.Delayed */
);
$SC(
  $iQb,
  $kQb,
  1
  /* InstantiationType.Delayed */
);
$SC(
  $Av,
  $ew,
  1
  /* InstantiationType.Delayed */
);
$SC(
  $Hx,
  $Jx,
  1
  /* InstantiationType.Delayed */
);
$SC(
  $yX,
  $Foc,
  1
  /* InstantiationType.Delayed */
);
if (globalThis.__VSCODE_WEB_ESM_PROMISE) {
  const exports2 = {
    // Factory
    create: $fpc,
    // Basic Types
    URI,
    Event: Event2,
    Emitter: $ze,
    Disposable: $3c,
    // GroupOrientation,
    LogLevel,
    RemoteAuthorityResolverError: $eC,
    RemoteAuthorityResolverErrorCode,
    // Facade API
    env: env2,
    window: window2,
    workspace,
    commands,
    logger,
    Menu
  };
  globalThis.__VSCODE_WEB_ESM_PROMISE(exports2);
  delete globalThis.__VSCODE_WEB_ESM_PROMISE;
}

// out-build/vs/code/browser/workbench/urlPorts.js
function obscurePort(x) {
  return x * BigInt(8854) % BigInt(65535);
}
function splitToken(token) {
  try {
    const multiplier = parseInt(token.slice(0, 4), 16);
    const key2 = parseInt(token.slice(4), 16);
    return {
      multiplier: BigInt(multiplier),
      key: BigInt(key2)
    };
  } catch {
  }
  return void 0;
}
function $I4(token, port) {
  const tokenData = splitToken(token);
  if (tokenData) {
    const result = obscurePort(BigInt(port)) * tokenData.multiplier ^ tokenData.key;
    return result.toString(16).padStart(8, "0");
  }
  return void 0;
}

// out-build/vs/code/browser/workbench/workbench.js
var TransparentCrypto = class {
  async seal(data) {
    return data;
  }
  async unseal(data) {
    return data;
  }
};
var AESConstants;
(function(AESConstants2) {
  AESConstants2["ALGORITHM"] = "AES-GCM";
  AESConstants2[AESConstants2["KEY_LENGTH"] = 256] = "KEY_LENGTH";
  AESConstants2[AESConstants2["IV_LENGTH"] = 12] = "IV_LENGTH";
})(AESConstants || (AESConstants = {}));
var NetworkError = class extends Error {
  constructor(inner) {
    super(inner.message);
    this.name = inner.name;
    this.stack = inner.stack;
  }
};
var ServerKeyedAESCrypto = class {
  /** Gets whether the algorithm is supported; requires a secure context */
  static supported() {
    return !!crypto.subtle;
  }
  constructor(b) {
    this.b = b;
  }
  async seal(data) {
    const iv = $Y.crypto.getRandomValues(new Uint8Array(
      12
      /* AESConstants.IV_LENGTH */
    ));
    const clientKeyObj = await $Y.crypto.subtle.generateKey({
      name: "AES-GCM",
      length: 256
      /* AESConstants.KEY_LENGTH */
    }, true, ["encrypt", "decrypt"]);
    const clientKey = new Uint8Array(await $Y.crypto.subtle.exportKey("raw", clientKeyObj));
    const key2 = await this.c(clientKey);
    const dataUint8Array = new TextEncoder().encode(data);
    const cipherText = await $Y.crypto.subtle.encrypt({ name: "AES-GCM", iv }, key2, dataUint8Array);
    const result = new Uint8Array([...clientKey, ...iv, ...new Uint8Array(cipherText)]);
    return $Wi($Ci.wrap(result));
  }
  async unseal(data) {
    const dataUint8Array = $Vi(data);
    if (dataUint8Array.byteLength < 60) {
      throw Error("Invalid length for the value for credentials.crypto");
    }
    const keyLength = 256 / 8;
    const clientKey = dataUint8Array.slice(0, keyLength);
    const iv = dataUint8Array.slice(
      keyLength,
      keyLength + 12
      /* AESConstants.IV_LENGTH */
    );
    const cipherText = dataUint8Array.slice(
      keyLength + 12
      /* AESConstants.IV_LENGTH */
    );
    const key2 = await this.c(clientKey.buffer);
    const decrypted = await $Y.crypto.subtle.decrypt({ name: "AES-GCM", iv: iv.buffer }, key2, cipherText.buffer);
    return new TextDecoder().decode(new Uint8Array(decrypted));
  }
  /**
   * Given a clientKey, returns the CryptoKey object that is used to encrypt/decrypt the data.
   * The actual key is (clientKey XOR serverKey)
   */
  async c(clientKey) {
    if (!clientKey || clientKey.byteLength !== 256 / 8) {
      throw Error("Invalid length for clientKey");
    }
    const serverKey = await this.d();
    const keyData = new Uint8Array(256 / 8);
    for (let i2 = 0; i2 < keyData.byteLength; i2++) {
      keyData[i2] = clientKey[i2] ^ serverKey[i2];
    }
    return $Y.crypto.subtle.importKey("raw", keyData, {
      name: "AES-GCM",
      length: 256
    }, true, ["encrypt", "decrypt"]);
  }
  async d() {
    if (this.a) {
      return this.a;
    }
    let attempt = 0;
    let lastError;
    while (attempt <= 3) {
      try {
        const res = await fetch(this.b, { credentials: "include", method: "POST" });
        if (!res.ok) {
          throw new Error(res.statusText);
        }
        const serverKey = new Uint8Array(await res.arrayBuffer());
        if (serverKey.byteLength !== 256 / 8) {
          throw Error(`The key retrieved by the server is not ${256} bit long.`);
        }
        this.a = serverKey;
        return this.a;
      } catch (e) {
        lastError = e instanceof Error ? e : new Error(String(e));
        attempt++;
        await new Promise((resolve) => setTimeout(resolve, attempt * attempt * 100));
      }
    }
    if (lastError) {
      throw new NetworkError(lastError);
    }
    throw new Error("Unknown error");
  }
};
var LocalStorageSecretStorageProvider = class {
  constructor(c) {
    this.c = c;
    this.a = "secrets.provider";
    this.b = this.d();
    this.type = "persisted";
  }
  async d() {
    const record = this.f();
    const encrypted = localStorage.getItem(this.a);
    if (encrypted) {
      try {
        const decrypted = JSON.parse(await this.c.unseal(encrypted));
        return { ...record, ...decrypted };
      } catch (err) {
        console.error("Failed to decrypt secrets from localStorage", err);
        if (!(err instanceof NetworkError)) {
          localStorage.removeItem(this.a);
        }
      }
    }
    return record;
  }
  f() {
    let authSessionInfo;
    const authSessionElement = $Y.document.getElementById("vscode-workbench-auth-session");
    const authSessionElementAttribute = authSessionElement ? authSessionElement.getAttribute("data-settings") : void 0;
    if (authSessionElementAttribute) {
      try {
        authSessionInfo = JSON.parse(authSessionElementAttribute);
      } catch (error) {
      }
    }
    if (!authSessionInfo) {
      return {};
    }
    const record = {};
    record[`${product_default.urlProtocol}.loginAccount`] = JSON.stringify(authSessionInfo);
    if (authSessionInfo.providerId !== "github") {
      console.error(`Unexpected auth provider: ${authSessionInfo.providerId}. Expected 'github'.`);
      return record;
    }
    const authAccount = JSON.stringify({ extensionId: "vscode.github-authentication", key: "github.auth" });
    record[authAccount] = JSON.stringify(authSessionInfo.scopes.map((scopes) => ({
      id: authSessionInfo.id,
      scopes,
      accessToken: authSessionInfo.accessToken
    })));
    return record;
  }
  async get(key2) {
    const secrets = await this.b;
    return secrets[key2];
  }
  async set(key2, value) {
    const secrets = await this.b;
    secrets[key2] = value;
    this.b = Promise.resolve(secrets);
    this.g();
  }
  async delete(key2) {
    const secrets = await this.b;
    delete secrets[key2];
    this.b = Promise.resolve(secrets);
    this.g();
  }
  async g() {
    try {
      const encrypted = await this.c.seal(JSON.stringify(await this.b));
      localStorage.setItem(this.a, encrypted);
    } catch (err) {
      console.error(err);
    }
  }
};
var LocalStorageURLCallbackProvider = class _LocalStorageURLCallbackProvider extends $3c {
  static {
    this.a = 0;
  }
  static {
    this.b = [
      "scheme",
      "authority",
      "path",
      "query",
      "fragment"
    ];
  }
  constructor(m) {
    super();
    this.m = m;
    this.c = this.B(new $ze());
    this.onCallback = this.c.event;
    this.f = /* @__PURE__ */ new Set();
    this.g = Date.now();
    this.h = void 0;
  }
  create(options3 = {}) {
    const id2 = ++_LocalStorageURLCallbackProvider.a;
    const queryParams = [`vscode-reqid=${id2}`];
    for (const key2 of _LocalStorageURLCallbackProvider.b) {
      const value = options3[key2];
      if (value) {
        queryParams.push(`vscode-${key2}=${encodeURIComponent(value)}`);
      }
    }
    if (!(options3.authority === "vscode.github-authentication" && options3.path === "/dummy")) {
      const key2 = `vscode-web.url-callbacks[${id2}]`;
      localStorage.removeItem(key2);
      this.f.add(id2);
      this.n();
    }
    return URI.parse($Y.location.href).with({ path: this.m, query: queryParams.join("&") });
  }
  n() {
    if (this.j) {
      return;
    }
    const fn = () => this.s();
    $Y.addEventListener("storage", fn);
    this.j = { dispose: () => $Y.removeEventListener("storage", fn) };
  }
  r() {
    this.j?.dispose();
    this.j = void 0;
  }
  // this fires every time local storage changes, but we
  // don't want to check more often than once a second
  async s() {
    const ellapsed = Date.now() - this.g;
    if (ellapsed > 1e3) {
      this.t();
    } else if (this.h === void 0) {
      this.h = setTimeout(() => {
        this.h = void 0;
        this.t();
      }, 1e3 - ellapsed);
    }
  }
  t() {
    let pendingCallbacks;
    for (const id2 of this.f) {
      const key2 = `vscode-web.url-callbacks[${id2}]`;
      const result = localStorage.getItem(key2);
      if (result !== null) {
        try {
          this.c.fire(URI.revive(JSON.parse(result)));
        } catch (error) {
          console.error(error);
        }
        pendingCallbacks = pendingCallbacks ?? new Set(this.f);
        pendingCallbacks.delete(id2);
        localStorage.removeItem(key2);
      }
    }
    if (pendingCallbacks) {
      this.f = pendingCallbacks;
      if (this.f.size === 0) {
        this.r();
      }
    }
    this.g = Date.now();
  }
};
var WorkspaceProvider = class _WorkspaceProvider {
  static {
    this.a = "ew";
  }
  static {
    this.b = "folder";
  }
  static {
    this.c = "workspace";
  }
  static {
    this.d = "payload";
  }
  static create(config) {
    let foundWorkspace = false;
    let workspace2;
    let payload = /* @__PURE__ */ Object.create(null);
    const query = new URL(document.location.href).searchParams;
    query.forEach((value, key2) => {
      switch (key2) {
        case _WorkspaceProvider.b:
          if (config.remoteAuthority && value.startsWith($kc.sep)) {
            workspace2 = { folderUri: URI.from({ scheme: Schemas.vscodeRemote, path: value, authority: config.remoteAuthority }) };
          } else {
            workspace2 = { folderUri: URI.parse(value) };
          }
          foundWorkspace = true;
          break;
        case _WorkspaceProvider.c:
          if (config.remoteAuthority && value.startsWith($kc.sep)) {
            workspace2 = { workspaceUri: URI.from({ scheme: Schemas.vscodeRemote, path: value, authority: config.remoteAuthority }) };
          } else {
            workspace2 = { workspaceUri: URI.parse(value) };
          }
          foundWorkspace = true;
          break;
        case _WorkspaceProvider.a:
          workspace2 = void 0;
          foundWorkspace = true;
          break;
        case _WorkspaceProvider.d:
          try {
            payload = $bu(value);
          } catch (error) {
            console.error(error);
          }
          break;
      }
    });
    if (!foundWorkspace) {
      if (config.folderUri) {
        workspace2 = { folderUri: URI.revive(config.folderUri) };
      } else if (config.workspaceUri) {
        workspace2 = { workspaceUri: URI.revive(config.workspaceUri) };
      }
    }
    return new _WorkspaceProvider(workspace2, payload, config);
  }
  constructor(workspace2, payload, f) {
    this.workspace = workspace2;
    this.payload = payload;
    this.f = f;
    this.trusted = true;
  }
  async open(workspace2, options3) {
    if (options3?.reuse && !options3.payload && this.j(this.workspace, workspace2)) {
      return true;
    }
    const targetHref = this.g(workspace2, options3);
    if (targetHref) {
      if (options3?.reuse) {
        $Y.location.href = targetHref;
        return true;
      } else {
        let result;
        if ($2e()) {
          result = $Y.open(targetHref, "_blank", "toolbar=no");
        } else {
          result = $Y.open(targetHref);
        }
        return !!result;
      }
    }
    return false;
  }
  g(workspace2, options3) {
    let targetHref = void 0;
    if (!workspace2) {
      targetHref = `${document.location.origin}${document.location.pathname}?${_WorkspaceProvider.a}=true`;
    } else if ($zs(workspace2)) {
      const queryParamFolder = this.h(workspace2.folderUri);
      targetHref = `${document.location.origin}${document.location.pathname}?${_WorkspaceProvider.b}=${queryParamFolder}`;
    } else if ($ys(workspace2)) {
      const queryParamWorkspace = this.h(workspace2.workspaceUri);
      targetHref = `${document.location.origin}${document.location.pathname}?${_WorkspaceProvider.c}=${queryParamWorkspace}`;
    }
    if (options3?.payload) {
      targetHref += `&${_WorkspaceProvider.d}=${encodeURIComponent(JSON.stringify(options3.payload))}`;
    }
    return targetHref;
  }
  h(uri) {
    if (this.f.remoteAuthority && uri.scheme === Schemas.vscodeRemote) {
      return encodeURIComponent(`${$kc.sep}${$Ff(uri.path, $kc.sep)}`).replaceAll("%2F", "/");
    }
    return encodeURIComponent(uri.toString(true));
  }
  j(workspaceA, workspaceB) {
    if (!workspaceA || !workspaceB) {
      return workspaceA === workspaceB;
    }
    if ($zs(workspaceA) && $zs(workspaceB)) {
      return $oh(workspaceA.folderUri, workspaceB.folderUri);
    }
    if ($ys(workspaceA) && $ys(workspaceB)) {
      return $oh(workspaceA.workspaceUri, workspaceB.workspaceUri);
    }
    return false;
  }
  hasRemote() {
    if (this.workspace) {
      if ($zs(this.workspace)) {
        return this.workspace.folderUri.scheme === Schemas.vscodeRemote;
      }
      if ($ys(this.workspace)) {
        return this.workspace.workspaceUri.scheme === Schemas.vscodeRemote;
      }
    }
    return true;
  }
};
function readCookie(name) {
  const cookies = document.cookie.split("; ");
  for (const cookie of cookies) {
    if (cookie.startsWith(name + "=")) {
      return cookie.substring(name.length + 1);
    }
  }
  return void 0;
}
(function() {
  const configElement = $Y.document.getElementById("vscode-workbench-web-configuration");
  const configElementAttribute = configElement ? configElement.getAttribute("data-settings") : void 0;
  if (!configElement || !configElementAttribute) {
    throw new Error("Missing web configuration element");
  }
  const config = { ...JSON.parse(configElementAttribute), remoteAuthority: location.host };
  const secretStorageKeyPath = readCookie("vscode-secret-key-path");
  const secretStorageCrypto = secretStorageKeyPath && ServerKeyedAESCrypto.supported() ? new ServerKeyedAESCrypto(secretStorageKeyPath) : new TransparentCrypto();
  $fpc($Y.document.body, {
    ...config,
    windowIndicator: config.windowIndicator ?? { label: "$(remote)", tooltip: `${product_default.nameShort} Web` },
    settingsSyncOptions: config.settingsSyncOptions ? { enabled: config.settingsSyncOptions.enabled } : void 0,
    workspaceProvider: WorkspaceProvider.create(config),
    urlCallbackProvider: new LocalStorageURLCallbackProvider(config.callbackRoute),
    // --- PWB Start: proxy port url ---
    resolveExternalUri: (uri) => {
      let resolvedUri = uri;
      const localhostMatch = $wC(resolvedUri);
      if (localhostMatch && resolvedUri.authority !== location.host) {
        if (config.productConfiguration && config.productConfiguration.proxyEndpointTemplate) {
          let template = config.productConfiguration.proxyEndpointTemplate;
          const portToken = template.split("/").pop();
          template = template.slice(0, template.lastIndexOf("/") + 1);
          let securePort, renderedTemplate;
          if (portToken !== void 0) {
            securePort = $I4(portToken, localhostMatch.port);
            if (securePort) {
              renderedTemplate = template.replace("{{port}}", securePort);
            }
          }
          if (!renderedTemplate) {
            renderedTemplate = template.replace("/p/", "/proxy/").replace("{{port}}", localhostMatch.port.toString());
          }
          const resolvedScheme = $Y.location.protocol.slice(0, -1);
          resolvedUri = resolvedUri.with({
            scheme: resolvedScheme,
            authority: $Y.location.host,
            path: $nc($Y.location.pathname, renderedTemplate, resolvedUri.path)
          });
        } else {
          throw new Error(`Failed to resolve external URI: ${uri.toString()}. Could not determine base url because productConfiguration missing.`);
        }
      }
      return Promise.resolve(resolvedUri);
    },
    tunnelProvider: {
      tunnelFactory: (tunnelOptions, tunnelCreationOptions) => {
        const onDidDispose = new $ze();
        let isDisposed = false;
        return Promise.resolve({
          remoteAddress: tunnelOptions.remoteAddress,
          localAddress: `localhost:${tunnelOptions.remoteAddress.port}`,
          onDidDispose: onDidDispose.event,
          dispose: () => {
            if (!isDisposed) {
              isDisposed = true;
              onDidDispose.fire();
            }
          }
        });
      }
    },
    // --- End PWB ---
    secretStorageProvider: config.remoteAuthority && !secretStorageKeyPath ? void 0 : new LocalStorageSecretStorageProvider(secretStorageCrypto)
  });
})();
export {
  LocalStorageSecretStorageProvider
};
/*! @license DOMPurify 3.1.7 | (c) Cure53 and other contributors | Released under the Apache license 2.0 and Mozilla Public License 2.0 | github.com/cure53/DOMPurify/blob/3.1.7/LICENSE */
//!this.editor.getOption(EditorOption.suggest).showStatusBar || this._state === State.Empty || this._state === State.Loading ? 0 : itemHeight;

//# sourceMappingURL=workbench.js.map
